diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..db2a596ae1 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +* text eol=crlf \ No newline at end of file diff --git a/3rdParty/ONNX/OnnxToolsPA.h b/3rdParty/ONNX/OnnxToolsPA.h index 7e038f75ae..ed20b4a6c4 100644 --- a/3rdParty/ONNX/OnnxToolsPA.h +++ b/3rdParty/ONNX/OnnxToolsPA.h @@ -1,38 +1,38 @@ -/* Simple Integer Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#ifndef PokemonAutomation_3rdParty_OnnxToolsPA_H -#define PokemonAutomation_3rdParty_OnnxToolsPA_H - -#include -#include -#include "Common/Cpp/Unicode.h" - -namespace PokemonAutomation{ - -#ifdef _WIN32 - -inline std::wstring str_to_onnx_str(const std::string& str){ - return utf8_to_wstr(str); -} - - -#else - - -inline std::string str_to_onnx_str(std::string str){ - return str; -} - - -#endif - - - -} -#endif +/* Simple Integer Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#ifndef PokemonAutomation_3rdParty_OnnxToolsPA_H +#define PokemonAutomation_3rdParty_OnnxToolsPA_H + +#include +#include +#include "Common/Cpp/Unicode.h" + +namespace PokemonAutomation{ + +#ifdef _WIN32 + +inline std::wstring str_to_onnx_str(const std::string& str){ + return utf8_to_wstr(str); +} + + +#else + + +inline std::string str_to_onnx_str(std::string str){ + return str; +} + + +#endif + + + +} +#endif diff --git a/3rdParty/ONNX/cpu_provider_factory.h b/3rdParty/ONNX/cpu_provider_factory.h index 3aa39ca860..292678692b 100644 --- a/3rdParty/ONNX/cpu_provider_factory.h +++ b/3rdParty/ONNX/cpu_provider_factory.h @@ -1,19 +1,19 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#include "onnxruntime_c_api.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * \param use_arena zero: false. non-zero: true. - */ -ORT_EXPORT -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CPU, _In_ OrtSessionOptions* options, int use_arena) -ORT_ALL_ARGS_NONNULL; - -#ifdef __cplusplus -} -#endif +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#include "onnxruntime_c_api.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \param use_arena zero: false. non-zero: true. + */ +ORT_EXPORT +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CPU, _In_ OrtSessionOptions* options, int use_arena) +ORT_ALL_ARGS_NONNULL; + +#ifdef __cplusplus +} +#endif diff --git a/3rdParty/ONNX/onnxruntime_c_api.h b/3rdParty/ONNX/onnxruntime_c_api.h index 6cda7f00f4..b01b7e48dc 100644 --- a/3rdParty/ONNX/onnxruntime_c_api.h +++ b/3rdParty/ONNX/onnxruntime_c_api.h @@ -1,6195 +1,6195 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// See docs\c_cxx\README.md on generating the Doxygen documentation from this file - -/** \mainpage ONNX Runtime - * - * ONNX Runtime is a high-performance inference and training graph execution engine for deep learning models. - * - * ONNX Runtime's C, C++ APIs offer an easy to use interface to onboard and execute onnx models. - * - \subpage c_cpp_api "Core C, C++ APIs" - * - \subpage training_c_cpp_api "Training C, C++ APIs for on-device training" - * - * \page c_cpp_api Core C, C++ APIs - *

C

- * - * ::OrtApi - Click here to go to the structure with all C API functions. - * - *

C++

- * - * ::Ort - Click here to go to the namespace holding all of the C++ wrapper classes - * - * It is a set of header only wrapper classes around the C API. The goal is to turn the C style return value error codes into C++ exceptions, and to - * automate memory management through standard C++ RAII principles. - * - * \addtogroup Global - * ONNX Runtime C API - * @{ - */ - -#pragma once -#include -#include -#include -#include - -/** \brief The API version defined in this header - * - * This value is used by some API functions to behave as this version of the header expects. - */ -#define ORT_API_VERSION 22 - -#ifdef __cplusplus -extern "C" { -#endif - -//! @} -// SAL2 Definitions -#ifndef _MSC_VER -#define _In_ -#define _In_z_ -#define _In_opt_ -#define _In_opt_z_ -#define _Out_ -#define _Outptr_ -#define _Out_opt_ -#define _Inout_ -#define _Inout_opt_ -#define _Frees_ptr_opt_ -#define _Ret_maybenull_ -#define _Ret_notnull_ -#define _Check_return_ -#define _Outptr_result_maybenull_ -#define _In_reads_(X) -#define _Inout_updates_(X) -#define _Out_writes_(X) -#define _Inout_updates_all_(X) -#define _Out_writes_bytes_all_(X) -#define _Out_writes_all_(X) -#define _Success_(X) -#define _Outptr_result_buffer_maybenull_(X) -#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull)) -#else -#include -#define ORT_ALL_ARGS_NONNULL -#endif - -#ifdef _WIN32 -// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort. -// dllexport is not used, we use a .def file. -#ifdef ORT_DLL_IMPORT -#define ORT_EXPORT __declspec(dllimport) -#else -#define ORT_EXPORT -#endif -#define ORT_API_CALL _stdcall -#define ORT_MUST_USE_RESULT -#define ORTCHAR_T wchar_t -#else -// To make symbols visible on macOS/iOS -#ifdef __APPLE__ -#define ORT_EXPORT __attribute__((visibility("default"))) -#else -#define ORT_EXPORT -#endif -#define ORT_API_CALL -#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result)) -#define ORTCHAR_T char -#endif - -/// ORTCHAR_T, ORT_TSTR are reserved specifically for path handling. -/// All other strings are UTF-8 encoded, use char and std::string -#ifndef ORT_TSTR -#ifdef _WIN32 -#define ORT_TSTR(X) L##X -// When X is a macro, L##X is not defined. In this case, we need to use ORT_TSTR_ON_MACRO. -#define ORT_TSTR_ON_MACRO(X) L"" X -#else -#define ORT_TSTR(X) X -#define ORT_TSTR_ON_MACRO(X) X -#endif -#endif - -// On Windows, ORT_FILE is a wchar_t version of the __FILE__ macro. -// Otherwise, ORT_FILE is equivalent to __FILE__. -#ifndef ORT_FILE -#define ORT_FILE_INTERNAL(x) ORT_TSTR(x) -#define ORT_FILE ORT_FILE_INTERNAL(__FILE__) -#endif - -// Any pointer marked with _In_ or _Out_, cannot be NULL. - -// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation -// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that. -// for ReleaseXXX(...) functions, they can accept NULL pointer. - -#ifdef __cplusplus -// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept. -// Such complex condition is needed because compilers set __cplusplus value differently. -#ifndef __has_feature -#define __has_feature(x) 0 -#endif -#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept))) -#define NO_EXCEPTION noexcept -#else -#define NO_EXCEPTION throw() -#endif -#else -#define NO_EXCEPTION -#endif - -// __VA_ARGS__ on Windows and Linux are different -#define ORT_API(RETURN_TYPE, NAME, ...) RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION - -#define ORT_API_STATUS(NAME, ...) \ - _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) \ - NO_EXCEPTION ORT_MUST_USE_RESULT - -// XXX: Unfortunately, SAL annotations are known to not work with function pointers -#define ORT_API2_STATUS(NAME, ...) \ - _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT - -// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT -#define ORT_API_STATUS_IMPL(NAME, ...) \ - _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION - -#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input) - -#ifdef __DOXYGEN__ -#undef ORT_API_STATUS -#define ORT_API_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) -#undef ORT_API2_STATUS -#define ORT_API2_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) -#undef ORT_CLASS_RELEASE -#define ORT_CLASS_RELEASE(X) void Release##X(Ort##X* input) -#undef NO_EXCEPTION -#define NO_EXCEPTION -#endif -/** \addtogroup Global - * ONNX Runtime C API - * @{ - */ - -/** Copied from TensorProto::DataType - * Currently, Ort doesn't support complex64, complex128 - */ -typedef enum ONNXTensorElementDataType { - ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED, - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string - ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL, - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16, - ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t - ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components - ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components - ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16, // Non-IEEE floating-point format based on IEEE754 single-precision - // float 8 types were introduced in onnx 1.14, see https://onnx.ai/onnx/technical/float8.html - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN, // Non-IEEE floating-point format based on IEEE754 single-precision - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2, // Non-IEEE floating-point format based on IEEE754 single-precision - ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision - // Int4 types were introduced in ONNX 1.16. See https://onnx.ai/onnx/technical/int4.html - ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT4, // maps to a pair of packed uint4 values (size == 1 byte) - ONNX_TENSOR_ELEMENT_DATA_TYPE_INT4 // maps to a pair of packed int4 values (size == 1 byte) -} ONNXTensorElementDataType; - -// Synced with onnx TypeProto oneof -typedef enum ONNXType { - ONNX_TYPE_UNKNOWN, - ONNX_TYPE_TENSOR, - ONNX_TYPE_SEQUENCE, - ONNX_TYPE_MAP, - ONNX_TYPE_OPAQUE, - ONNX_TYPE_SPARSETENSOR, - ONNX_TYPE_OPTIONAL -} ONNXType; - -// These types are synced with internal -// SparseFormatFlags -typedef enum OrtSparseFormat { - ORT_SPARSE_UNDEFINED = 0, - ORT_SPARSE_COO = 0x1, - ORT_SPARSE_CSRC = 0x2, - ORT_SPARSE_BLOCK_SPARSE = 0x4 -} OrtSparseFormat; - -// Enum allows to query sparse tensor indices -enum OrtSparseIndicesFormat { - ORT_SPARSE_COO_INDICES, - ORT_SPARSE_CSR_INNER_INDICES, - ORT_SPARSE_CSR_OUTER_INDICES, - ORT_SPARSE_BLOCK_SPARSE_INDICES -}; - -/** \brief Logging severity levels - * - * In typical API usage, specifying a logging severity level specifies the minimum severity of log messages to show. - */ -typedef enum OrtLoggingLevel { - ORT_LOGGING_LEVEL_VERBOSE, ///< Verbose informational messages (least severe). - ORT_LOGGING_LEVEL_INFO, ///< Informational messages. - ORT_LOGGING_LEVEL_WARNING, ///< Warning messages. - ORT_LOGGING_LEVEL_ERROR, ///< Error messages. - ORT_LOGGING_LEVEL_FATAL, ///< Fatal error messages (most severe). -} OrtLoggingLevel; - -typedef enum OrtErrorCode { - ORT_OK, - ORT_FAIL, - ORT_INVALID_ARGUMENT, - ORT_NO_SUCHFILE, - ORT_NO_MODEL, - ORT_ENGINE_ERROR, - ORT_RUNTIME_EXCEPTION, - ORT_INVALID_PROTOBUF, - ORT_MODEL_LOADED, - ORT_NOT_IMPLEMENTED, - ORT_INVALID_GRAPH, - ORT_EP_FAIL, - ORT_MODEL_LOAD_CANCELED, - ORT_MODEL_REQUIRES_COMPILATION, -} OrtErrorCode; - -typedef enum OrtOpAttrType { - ORT_OP_ATTR_UNDEFINED = 0, - ORT_OP_ATTR_INT, - ORT_OP_ATTR_INTS, - ORT_OP_ATTR_FLOAT, - ORT_OP_ATTR_FLOATS, - ORT_OP_ATTR_STRING, - ORT_OP_ATTR_STRINGS, -} OrtOpAttrType; - -//! @} -#define ORT_RUNTIME_CLASS(X) \ - struct Ort##X; \ - typedef struct Ort##X Ort##X - -/** \addtogroup Global - * ONNX Runtime C API - * @{ - */ -// The actual types defined have an Ort prefix -ORT_RUNTIME_CLASS(Env); -ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success -ORT_RUNTIME_CLASS(MemoryInfo); -ORT_RUNTIME_CLASS(IoBinding); -ORT_RUNTIME_CLASS(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) -ORT_RUNTIME_CLASS(Value); -ORT_RUNTIME_CLASS(RunOptions); -ORT_RUNTIME_CLASS(TypeInfo); -ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo); -ORT_RUNTIME_CLASS(MapTypeInfo); -ORT_RUNTIME_CLASS(SequenceTypeInfo); -ORT_RUNTIME_CLASS(OptionalTypeInfo); -ORT_RUNTIME_CLASS(SessionOptions); -ORT_RUNTIME_CLASS(CustomOpDomain); -ORT_RUNTIME_CLASS(ModelMetadata); -ORT_RUNTIME_CLASS(ThreadPoolParams); -ORT_RUNTIME_CLASS(ThreadingOptions); -ORT_RUNTIME_CLASS(ArenaCfg); -ORT_RUNTIME_CLASS(PrepackedWeightsContainer); -ORT_RUNTIME_CLASS(TensorRTProviderOptionsV2); -ORT_RUNTIME_CLASS(NvTensorRtRtxProviderOptions); -ORT_RUNTIME_CLASS(CUDAProviderOptionsV2); -ORT_RUNTIME_CLASS(CANNProviderOptions); -ORT_RUNTIME_CLASS(DnnlProviderOptions); -ORT_RUNTIME_CLASS(Op); -ORT_RUNTIME_CLASS(OpAttr); -ORT_RUNTIME_CLASS(Logger); -ORT_RUNTIME_CLASS(ShapeInferContext); -ORT_RUNTIME_CLASS(LoraAdapter); -ORT_RUNTIME_CLASS(ValueInfo); -ORT_RUNTIME_CLASS(Node); -ORT_RUNTIME_CLASS(Graph); -ORT_RUNTIME_CLASS(Model); -ORT_RUNTIME_CLASS(ModelCompilationOptions); -ORT_RUNTIME_CLASS(HardwareDevice); -ORT_RUNTIME_CLASS(EpDevice); -ORT_RUNTIME_CLASS(KeyValuePairs); - -#ifdef _MSC_VER -typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr; -#else -typedef OrtStatus* OrtStatusPtr; -#endif - -/** \brief Memory allocation interface - * - * Structure of function pointers that defines a memory allocator. This can be created and filled in by the user for custom allocators. - * - * When an allocator is passed to any function, be sure that the allocator object is not destroyed until the last allocated object using it is freed. - */ -typedef struct OrtAllocator { - uint32_t version; ///< Must be initialized to ORT_API_VERSION - void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes - void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p); ///< Free a block of memory previously allocated with OrtAllocator::Alloc - const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_); ///< Return a pointer to an ::OrtMemoryInfo that describes this allocator - /** - * @brief Optional allocation function to use for memory allocations made during session initialization. - * Use this function if you want to separate allocations made by ORT during Run() calls from - * those made during session initialization. This allows for separate memory management strategies for these allocations. - */ - void*(ORT_API_CALL* Reserve)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes -} OrtAllocator; - -typedef void(ORT_API_CALL* OrtLoggingFunction)( - void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location, - const char* message); - -/** \brief Graph optimization level - * - * Refer to https://www.onnxruntime.ai/docs/performance/graph-optimizations.html#graph-optimization-levels - * for an in-depth understanding of the Graph Optimization Levels. - */ -typedef enum GraphOptimizationLevel { - ORT_DISABLE_ALL = 0, - ORT_ENABLE_BASIC = 1, - ORT_ENABLE_EXTENDED = 2, - ORT_ENABLE_ALL = 99 -} GraphOptimizationLevel; - -typedef enum ExecutionMode { - ORT_SEQUENTIAL = 0, - ORT_PARALLEL = 1, -} ExecutionMode; - -/** \brief Language projection identifiers - * /see OrtApi::SetLanguageProjection - */ -typedef enum OrtLanguageProjection { - ORT_PROJECTION_C = 0, - ORT_PROJECTION_CPLUSPLUS = 1, - ORT_PROJECTION_CSHARP = 2, - ORT_PROJECTION_PYTHON = 3, - ORT_PROJECTION_JAVA = 4, - ORT_PROJECTION_WINML = 5, - ORT_PROJECTION_NODEJS = 6, -} OrtLanguageProjection; - -struct OrtKernelInfo; -typedef struct OrtKernelInfo OrtKernelInfo; -struct OrtKernelContext; -typedef struct OrtKernelContext OrtKernelContext; -struct OrtCustomOp; -typedef struct OrtCustomOp OrtCustomOp; - -typedef enum OrtAllocatorType { - OrtInvalidAllocator = -1, - OrtDeviceAllocator = 0, - OrtArenaAllocator = 1 -} OrtAllocatorType; - -/** \brief Memory types for allocated memory, execution provider specific types should be extended in each provider. - */ -// Whenever this struct is updated, please also update the MakeKey function in onnxruntime / core / framework / execution_provider.cc -typedef enum OrtMemType { - OrtMemTypeCPUInput = -2, ///< Any CPU memory used by non-CPU execution provider - OrtMemTypeCPUOutput = -1, ///< CPU accessible memory outputted by non-CPU execution provider, i.e. CUDA_PINNED - OrtMemTypeCPU = OrtMemTypeCPUOutput, ///< Temporary CPU accessible memory allocated by non-CPU execution provider, i.e. CUDA_PINNED - OrtMemTypeDefault = 0, ///< The default allocator for execution provider -} OrtMemType; - -/** \brief This mimics OrtDevice type constants so they can be returned in the API - */ -typedef enum OrtMemoryInfoDeviceType { - OrtMemoryInfoDeviceType_CPU = 0, - OrtMemoryInfoDeviceType_GPU = 1, - OrtMemoryInfoDeviceType_FPGA = 2 -} OrtMemoryInfoDeviceType; - -typedef enum OrtHardwareDeviceType { - OrtHardwareDeviceType_CPU, - OrtHardwareDeviceType_GPU, - OrtHardwareDeviceType_NPU -} OrtHardwareDeviceType; - -/** \brief These are the default EP selection policies used by ORT when doing automatic EP selection. - */ -typedef enum OrtExecutionProviderDevicePolicy { - OrtExecutionProviderDevicePolicy_DEFAULT, - OrtExecutionProviderDevicePolicy_PREFER_CPU, - OrtExecutionProviderDevicePolicy_PREFER_NPU, - OrtExecutionProviderDevicePolicy_PREFER_GPU, - OrtExecutionProviderDevicePolicy_MAX_PERFORMANCE, - OrtExecutionProviderDevicePolicy_MAX_EFFICIENCY, - OrtExecutionProviderDevicePolicy_MIN_OVERALL_POWER, -} OrtExecutionProviderDevicePolicy; - -/** \brief Delegate to allow providing custom OrtEpDevice selection logic - * - * This delegate is called by the EP selection code to allow the user to provide custom device selection logic. - * The user can use this to select OrtEpDevice instances from the list of available devices. - * - * \param ep_devices The list of available devices. - * \param num_devices The number of available devices. - * \param model_metadata The model metadata. - * \param runtime_metadata The runtime metadata. May be nullptr. - * \param selected Pre-allocated array to populate with selected OrtEpDevice pointers from ep_devices. - * \param max_ep_devices The maximum number of devices that can be selected in the pre-allocated array. - Currently the maximum is 8. - * \param num_ep_devices The number of selected devices. - * \param state Opaque pointer. Required to use the delegate from other languages like C# and python. - * - * \return OrtStatus* Selection status. Return nullptr on success. - * Use CreateStatus to provide error info. Use ORT_FAIL as the error code. - * ORT will release the OrtStatus* if not null. - */ -typedef OrtStatus* (*EpSelectionDelegate)(_In_ const OrtEpDevice** ep_devices, - _In_ size_t num_devices, - _In_ const OrtKeyValuePairs* model_metadata, - _In_opt_ const OrtKeyValuePairs* runtime_metadata, - _Inout_ const OrtEpDevice** selected, - _In_ size_t max_selected, - _Out_ size_t* num_selected, - _In_ void* state); - -/** \brief Algorithm to use for cuDNN Convolution Op - */ -typedef enum OrtCudnnConvAlgoSearch { - OrtCudnnConvAlgoSearchExhaustive, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx - OrtCudnnConvAlgoSearchHeuristic, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7 - OrtCudnnConvAlgoSearchDefault, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM -} OrtCudnnConvAlgoSearch; - -/** \brief CUDA Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_CUDA - */ -typedef struct OrtCUDAProviderOptions { -#ifdef __cplusplus - OrtCUDAProviderOptions() - : device_id{}, - cudnn_conv_algo_search{OrtCudnnConvAlgoSearchExhaustive}, - gpu_mem_limit{SIZE_MAX}, - arena_extend_strategy{}, - do_copy_in_default_stream{1}, - has_user_compute_stream{}, - user_compute_stream{}, - default_memory_arena_cfg{}, - tunable_op_enable{false}, - tunable_op_tuning_enable{false}, - tunable_op_max_tuning_duration_ms{} {} -#endif - - /** \brief CUDA device Id - * Defaults to 0. - */ - int device_id; - - /** \brief CUDA Convolution algorithm search configuration. - * See enum OrtCudnnConvAlgoSearch for more details. - * Defaults to OrtCudnnConvAlgoSearchExhaustive. - */ - OrtCudnnConvAlgoSearch cudnn_conv_algo_search; - - /** \brief CUDA memory limit (To use all possible memory pass in maximum size_t) - * Defaults to SIZE_MAX. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - size_t gpu_mem_limit; - - /** \brief Strategy used to grow the memory arena - * 0 = kNextPowerOfTwo
- * 1 = kSameAsRequested
- * Defaults to 0. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - int arena_extend_strategy; - - /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the CUDA EP - * 0 = Use separate streams for copying and compute. - * 1 = Use the same stream for copying and compute. - * Defaults to 1. - * WARNING: Setting this to 0 may result in data races for some models. - * Please see issue #4829 for more details. - */ - int do_copy_in_default_stream; - - /** \brief Flag indicating if there is a user provided compute stream - * Defaults to 0. - */ - int has_user_compute_stream; - - /** \brief User provided compute stream. - * If provided, please set `has_user_compute_stream` to 1. - */ - void* user_compute_stream; - - /** \brief CUDA memory arena configuration parameters - */ - OrtArenaCfg* default_memory_arena_cfg; - - /** \brief Enable TunableOp for using. - * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_ENABLE. - */ - int tunable_op_enable; - - /** \brief Enable TunableOp for tuning. - * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_TUNING_ENABLE. - */ - int tunable_op_tuning_enable; - - /** \brief Max tuning duration time limit for each instance of TunableOp. - * Defaults to 0 to disable the limit. - */ - int tunable_op_max_tuning_duration_ms; - -} OrtCUDAProviderOptions; - -/** \brief ROCM Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_ROCM - */ -typedef struct OrtROCMProviderOptions { -#ifdef __cplusplus - OrtROCMProviderOptions() - : device_id{}, - miopen_conv_exhaustive_search{0}, - gpu_mem_limit{SIZE_MAX}, - arena_extend_strategy{}, - do_copy_in_default_stream{1}, - has_user_compute_stream{}, - user_compute_stream{}, - default_memory_arena_cfg{}, - enable_hip_graph{false}, - tunable_op_enable{false}, - tunable_op_tuning_enable{false}, - tunable_op_max_tuning_duration_ms{} {} -#endif - - /** \brief ROCM device Id - * Defaults to 0. - */ - int device_id; - - /** \brief ROCM MIOpen Convolution algorithm exaustive search option. - * Defaults to 0 (false). - */ - int miopen_conv_exhaustive_search; - - /** \brief ROCM memory limit (To use all possible memory pass in maximum size_t) - * Defaults to SIZE_MAX. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - size_t gpu_mem_limit; - - /** \brief Strategy used to grow the memory arena - * 0 = kNextPowerOfTwo
- * 1 = kSameAsRequested
- * Defaults to 0. - * \note If a ::OrtArenaCfg has been applied, it will override this field - */ - int arena_extend_strategy; - - /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the ROCM EP - * 0 = Use separate streams for copying and compute. - * 1 = Use the same stream for copying and compute. - * Defaults to 1. - * WARNING: Setting this to 0 may result in data races for some models. - * Please see issue #4829 for more details. - */ - int do_copy_in_default_stream; - - /** \brief Flag indicating if there is a user provided compute stream - * Defaults to 0. - */ - int has_user_compute_stream; - - /** \brief User provided compute stream. - * If provided, please set `has_user_compute_stream` to 1. - */ - void* user_compute_stream; - - /** \brief ROCM memory arena configuration parameters - */ - OrtArenaCfg* default_memory_arena_cfg; - - int enable_hip_graph; - - /** \brief Enable TunableOp for using. - * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_ENABLE. - */ - int tunable_op_enable; - - /** \brief Enable TunableOp for tuning. - * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. - * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_TUNING_ENABLE. - */ - int tunable_op_tuning_enable; - - /** \brief Max tuning duration time limit for each instance of TunableOp. - * Defaults to 0 to disable the limit. - */ - int tunable_op_max_tuning_duration_ms; - -} OrtROCMProviderOptions; - -/** \brief TensorRT Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_TensorRT - */ -typedef struct OrtTensorRTProviderOptions { - int device_id; ///< CUDA device id (0 = default device) - int has_user_compute_stream; // indicator of user specified CUDA compute stream. - void* user_compute_stream; // user specified CUDA compute stream. - int trt_max_partition_iterations; // maximum iterations for TensorRT parser to get capability - int trt_min_subgraph_size; // minimum size of TensorRT subgraphs - size_t trt_max_workspace_size; // maximum workspace size for TensorRT. - int trt_fp16_enable; // enable TensorRT FP16 precision. Default 0 = false, nonzero = true - int trt_int8_enable; // enable TensorRT INT8 precision. Default 0 = false, nonzero = true - const char* trt_int8_calibration_table_name; // TensorRT INT8 calibration table name. - int trt_int8_use_native_calibration_table; // use native TensorRT generated calibration table. Default 0 = false, nonzero = true - int trt_dla_enable; // enable DLA. Default 0 = false, nonzero = true - int trt_dla_core; // DLA core number. Default 0 - int trt_dump_subgraphs; // dump TRT subgraph. Default 0 = false, nonzero = true - int trt_engine_cache_enable; // enable engine caching. Default 0 = false, nonzero = true - const char* trt_engine_cache_path; // specify engine cache path - int trt_engine_decryption_enable; // enable engine decryption. Default 0 = false, nonzero = true - const char* trt_engine_decryption_lib_path; // specify engine decryption library path - int trt_force_sequential_engine_build; // force building TensorRT engine sequentially. Default 0 = false, nonzero = true - // This is the legacy struct and don't add new fields here. - // For new field that can be represented by string, please add it in include/onnxruntime/core/providers/tensorrt/tensorrt_provider_options.h - // For non-string field, need to create a new separate api to handle it. -} OrtTensorRTProviderOptions; - -/** \brief MIGraphX Provider Options - * - * \see OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX - */ -typedef struct OrtMIGraphXProviderOptions { - int device_id; // hip device id. - int migraphx_fp16_enable; // MIGraphX FP16 precision. Default 0 = false, nonzero = true - int migraphx_int8_enable; // MIGraphX INT8 precision. Default 0 = false, nonzero = true - int migraphx_use_native_calibration_table; // MIGraphx INT8 cal table. Default 0 = false, noznero = true - const char* migraphx_int8_calibration_table_name; // MIGraphx INT8 calibration table name - int migraphx_save_compiled_model; // migraphx save compiled model. Default 0 = false, noznero = true - const char* migraphx_save_model_path; // migraphx model path name - int migraphx_load_compiled_model; // migraphx int8 cal table. Default 0 = false, noznero = true - const char* migraphx_load_model_path; // migraphx model path name - bool migraphx_exhaustive_tune; // migraphx tuned compile Default = false -} OrtMIGraphXProviderOptions; - -/** \brief OpenVINO Provider Options - * \brief This Struct is frozen since ORT 1.13.0. Its maintained part of Legacy API for compatibility. - * \brief For latest OpenVINO Provider Options update to the ProviderOptions map. - * \brief Latest OpenVINO Provider Options are listed in the - * \htmlonly - * onnxruntime document. - * \endhtmlonly - * \see OrtApi::SessionOptionsAppendExecutionProvider() - */ -typedef struct OrtOpenVINOProviderOptions { -#ifdef __cplusplus - OrtOpenVINOProviderOptions() : device_type{}, - enable_npu_fast_compile{}, - device_id{}, - num_of_threads{}, - cache_dir{}, - context{}, - enable_opencl_throttling{}, - enable_dynamic_shapes{} {} -#endif - /** \brief Device type string - * - * Valid settings are one of: "CPU_FP32", "CPU_FP16", "GPU_FP32", "GPU_FP16" - */ - const char* device_type; - unsigned char enable_npu_fast_compile; ///< 0 = disabled, nonzero = enabled - const char* device_id; - size_t num_of_threads; ///< 0 = Use default number of threads - const char* cache_dir; // path is set to empty by default - void* context; - unsigned char enable_opencl_throttling; ///< 0 = disabled, nonzero = enabled - unsigned char enable_dynamic_shapes; ///< 0 = disabled, nonzero = enabled -} OrtOpenVINOProviderOptions; - -struct OrtApi; -typedef struct OrtApi OrtApi; - -struct OrtTrainingApi; -typedef struct OrtTrainingApi OrtTrainingApi; - -struct OrtModelEditorApi; -typedef struct OrtModelEditorApi OrtModelEditorApi; - -struct OrtCompileApi; -typedef struct OrtCompileApi OrtCompileApi; - -struct OrtEpApi; -typedef struct OrtEpApi OrtEpApi; - -/** \brief The helper interface to get the right version of OrtApi - * - * Get a pointer to this structure through ::OrtGetApiBase - */ -struct OrtApiBase { - /** \brief Get a pointer to the requested version of the ::OrtApi - * - * \param[in] version Must be ::ORT_API_VERSION - * \return The ::OrtApi for the version requested, nullptr will be returned if this version is unsupported, for example when using a runtime - * older than the version created with this header file. - * - * One can call GetVersionString() to get the version of the Onnxruntime library for logging - * and error reporting purposes. - */ - const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION; - - /** \brief Returns a null terminated string of the version of the Onnxruntime library (eg: "1.8.1") - * - * \return UTF-8 encoded version string. Do not deallocate the returned buffer. - */ - const char*(ORT_API_CALL* GetVersionString)(void)NO_EXCEPTION; -}; - -typedef struct OrtApiBase OrtApiBase; - -/** \brief The Onnxruntime library's entry point to access the C API - * - * Call this to get the a pointer to an ::OrtApiBase - */ -ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION; - -/** \brief Thread work loop function - * - * Onnxruntime will provide the working loop on custom thread creation - * Argument is an onnxruntime built-in type which will be provided when thread pool calls OrtCustomCreateThreadFn - */ -typedef void (*OrtThreadWorkerFn)(void* ort_worker_fn_param); - -typedef const struct OrtCustomHandleType { - char __place_holder; -}* OrtCustomThreadHandle; - -/** \brief Ort custom thread creation function - * - * The function should return a thread handle to be used in onnxruntime thread pools - * Onnxruntime will throw exception on return value of nullptr or 0, indicating that the function failed to create a thread - */ -typedef OrtCustomThreadHandle (*OrtCustomCreateThreadFn)(void* ort_custom_thread_creation_options, OrtThreadWorkerFn ort_thread_worker_fn, void* ort_worker_fn_param); - -/** \brief Custom thread join function - * - * Onnxruntime thread pool destructor will call the function to join a custom thread. - * Argument ort_custom_thread_handle is the value returned by OrtCustomCreateThreadFn - */ -typedef void (*OrtCustomJoinThreadFn)(OrtCustomThreadHandle ort_custom_thread_handle); - -typedef OrtStatus*(ORT_API_CALL* RegisterCustomOpsFn)(OrtSessionOptions* options, const OrtApiBase* api); - -/** \brief Callback function for RunAsync - * - * \param[in] user_data User specific data that passed back to the callback - * \param[out] outputs On succeed, outputs host inference results, on error, the value will be nullptr - * \param[out] num_outputs Number of outputs, on error, the value will be zero - * \param[out] status On error, status will provide details - */ -typedef void (*RunAsyncCallbackFn)(void* user_data, OrtValue** outputs, size_t num_outputs, OrtStatusPtr status); - -/** \brief The C API - * - * All C API functions are defined inside this structure as pointers to functions. - * Call OrtApiBase::GetApi to get a pointer to it - * - * \nosubgrouping - */ -struct OrtApi { - /// \name OrtStatus - /// @{ - - /** - * \brief Create an OrtStatus from a null terminated string - * - * \param[in] code - * \param[in] msg A null-terminated string. Its contents will be copied. - * \return A new OrtStatus object, must be destroyed with OrtApi::ReleaseStatus - */ - OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /** \brief Get OrtErrorCode from OrtStatus - * - * \param[in] status - * \return OrtErrorCode that \p status was created with - */ - OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /** \brief Get error string from OrtStatus - * - * \param[in] status - * \return The error message inside the `status`. Do not free the returned value. - */ - const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /// @} - /// \name OrtEnv - /// @{ - - /** \brief Create an OrtEnv - * - * \note Invoking this function will return the same instance of the environment as that returned by a previous call - * to another env creation function; all arguments to this function will be ignored. - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnv, OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); - - /** \brief Create an OrtEnv - * - * \note Invoking this function will return the same instance of the environment as that returned by a previous call - * to another env creation function; all arguments to this function will be ignored. If you want to provide your - * own logging function, consider setting it using the SetUserLoggingFunction API instead. - * \param[in] logging_function A pointer to a logging function. - * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to - * `logging_function`. This parameter is optional. - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnvWithCustomLogger, _In_ OrtLoggingFunction logging_function, _In_opt_ void* logger_param, - _In_ OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); - - /** \brief Enable Telemetry - * - * \note Telemetry events are on by default since they are lightweight - * \param[in] env - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env); - /** \brief Disable Telemetry - * - * \see OrtApi::EnableTelemetryEvents - * \param[in] env - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Create an OrtSession from a model file - * - * \param[in] env - * \param[in] model_path - * \param[in] options - * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - // TODO: document the path separator convention? '/' vs '\' - // TODO: should specify the access characteristics of model_path. Is this read only during the - // execution of CreateSession, or does the OrtSession retain a handle to the file/directory - // and continue to access throughout the OrtSession lifetime? - // What sort of access is needed to model_path : read or read/write? - ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, - _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); - - /** \brief Create an OrtSession from memory - * - * \param[in] env - * \param[in] model_data - * \param[in] model_data_length - * \param[in] options - * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env, - _In_ const void* model_data, size_t model_data_length, - _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); - - /** \brief Run the model in an ::OrtSession - * - * Will not return until the model run has completed. Multiple threads might be used to run the model based on - * the options in the ::OrtSession and settings used when creating the ::OrtEnv - * - * \param[in] session - * \param[in] run_options If nullptr, will use a default ::OrtRunOptions - * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names - * \param[in] inputs Array of ::OrtValue%s of the input values - * \param[in] input_len Number of elements in the input_names and inputs arrays - * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names - * \param[in] output_names_len Number of elements in the output_names and outputs array - * \param[out] outputs Array of ::OrtValue%s that the outputs are stored in. This can also be - * an array of nullptr values, in this case ::OrtValue objects will be allocated and pointers - * to them will be set into the `outputs` array. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(Run, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, - _In_reads_(input_len) const char* const* input_names, - _In_reads_(input_len) const OrtValue* const* inputs, size_t input_len, - _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, - _Inout_updates_all_(output_names_len) OrtValue** outputs); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Create an ::OrtSessionOptions object - * - * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these - * functions to enable them in the session:
- * OrtSessionOptionsAppendExecutionProvider_CPU
- * OrtSessionOptionsAppendExecutionProvider_CUDA
- * OrtSessionOptionsAppendExecutionProvider_(remaining providers...)
- * The order they are called indicates the preference order as well. In other words call this method - * on your most preferred execution provider first followed by the less preferred ones. - * If none are called Ort will use its internal CPU execution provider. - * - * \param[out] options The newly created OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options); - - /** \brief Set filepath to save optimized model after graph level transformations - * - * \param[in] options - * \param[in] optimized_model_filepath - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options, - _In_ const ORTCHAR_T* optimized_model_filepath); - - /** \brief Create a copy of an existing ::OrtSessionOptions - * - * \param[in] in_options OrtSessionOptions to copy - * \param[out] out_options Returned newly created ::OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options, - _Outptr_ OrtSessionOptions** out_options); - - /** \brief Set execution mode - * - * Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model - * has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance. - * See [docs/ONNX_Runtime_Perf_Tuning.md] for more details. - * - * \param[in] options - * \param[in] execution_mode - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode); - - /** \brief Enable profiling for a session - * - * \param[in] options - * \param[in] profile_file_prefix - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix); - - /** \brief Disable profiling for a session - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options); - - /** \brief Enable the memory pattern optimization - * - * The idea is if the input shapes are the same, we could trace the internal memory allocation - * and generate a memory pattern for future request. So next time we could just do one allocation - * with a big chunk for all the internal memory allocation. - * \note Memory pattern optimization is only available when Sequential Execution mode is enabled (see OrtApi::SetSessionExecutionMode) - * - * \see OrtApi::DisableMemPattern - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options); - - /** \brief Disable the memory pattern optimization - * - * \see OrtApi::EnableMemPattern - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options); - - /** \brief Enable the memory arena on CPU - * - * Arena may pre-allocate memory for future usage. - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options); - - /** \brief Disable the memory arena on CPU - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options); - - /** \brief Set session log id - * - * \param[in] options - * \param[in] logid The log identifier. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid); - - /** \brief Set session log verbosity level - * - * Applies to session load, initialization, etc - * - * \param[in] options - * \param[in] session_log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level); - - /** \brief Set session log severity level - * - * \param[in] options - * \param[in] session_log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level); - - /** \brief Set the optimization level to apply when loading a graph - * - * Please see https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html for an in-depth explanation - * \param[in,out] options The session options object - * \param[in] graph_optimization_level The optimization level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options, - GraphOptimizationLevel graph_optimization_level); - - /** \brief Sets the number of threads used to parallelize the execution within nodes - * - * When running a single node operation, ex. add, this sets the maximum number of threads to use. - * - * \note If built with OpenMP, this has no effect on the number of threads used. In this case - * use the OpenMP env variables to configure the number of intra op num threads. - * - * \param[in] options - * \param[in] intra_op_num_threads Number of threads to use
- * A value of 0 will use the default number of threads
- * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads); - - /** \brief Sets the number of threads used to parallelize the execution of the graph - * - * If nodes can be run in parallel, this sets the maximum number of threads to use to run them in parallel. - * - * \note If sequential execution is enabled this value is ignored, it acts as if it was set to 1. - * - * \param[in] options - * \param[in] inter_op_num_threads Number of threads to use
- * A value of 0 will use the default number of threads
- * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads); - - /// @} - /// \name OrtCustomOpDomain - /// @{ - - /** \brief Create a custom op domain - * - * \param[in] domain - * \param[out] out Newly created domain. Must be freed with OrtApi::ReleaseCustomOpDomain - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out); - - /** \brief Add a custom op to a custom op domain - * - * \note The OrtCustomOp* pointer must remain valid until the ::OrtCustomOpDomain using it is released - * - * \param[in] custom_op_domain - * \param[in] op - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Add custom op domain to a session options - * - * \note The OrtCustomOpDomain* must not be deleted until all sessions using it are released - * - * \param[in] options - * \param[in] custom_op_domain - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain); - - /** \deprecated Use OrtApi::RegisterCustomOpsLibrary_V2. - * - * Registers custom ops from a shared library. - * - * Loads a shared library (dll on windows, so on linux, etc) named 'library_path' and looks for this entry point: - * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); - * It then passes in the provided session options to this function along with the api base. - * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in - * session options are destroyed, or if an error occurs and it is non null. - * - * \param[in] options - * \param[in] library_path - * \param[out] library_handle OS specific handle to the loaded library (Use FreeLibrary on Windows, dlclose on Linux, etc.. to unload) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path, _Outptr_ void** library_handle); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Get input count for a session - * - * This number must also match the number of inputs passed to OrtApi::Run - * - * \see OrtApi::SessionGetInputTypeInfo, OrtApi::SessionGetInputName, OrtApi::Session - * - * \param[in] session - * \param[out] out Number of inputs - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* session, _Out_ size_t* out); - - /** \brief Get output count for a session - * - * This number must also match the number of outputs returned by OrtApi::Run - * - * \see OrtApi::SessionGetOutputTypeInfo, OrtApi::SessionGetOutputName, OrtApi::Session - * - * \param[in] session - * \param[out] out Number of outputs - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* session, _Out_ size_t* out); - - /** \brief Get overridable initializer count - * - * \see OrtApi::SessionGetOverridableInitializerTypeInfo, OrtApi::SessionGetOverridableInitializerName - * - * \param[in] session - * \param[in] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* session, _Out_ size_t* out); - - /** \brief Get input type information - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) - * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get output type information - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) - * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get overridable initializer type information - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) - * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get input name - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) - * \param[in] allocator - * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get output name - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) - * \param[in] allocator - * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get overridable initializer name - * - * \param[in] session - * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) - * \param[in] allocator - * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* session, size_t index, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /// @} - /// \name OrtRunOptions - /// @{ - - /** \brief Create an OrtRunOptions - * - * \param[out] out Returned newly created ::OrtRunOptions. Must be freed with OrtApi::ReleaseRunOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out); - - /** \brief Set per-run log verbosity level - * - * \see OrtApi::RunOptionsGetRunLogVerbosityLevel - * - * \param[in] options - * \param[in] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int log_verbosity_level); - - /** \brief Set per-run log severity level - * - * \see OrtApi::RunOptionsGetRunLogSeverityLevel - * - * \param[in] options - * \param[in] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). - */ - ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int log_severity_level); - - /** \brief Set per-run tag - * - * This is used in a per-run log identifier. - * - * \see OrtApi::RunOptionsGetRunTag - * - * \param[in] options - * \param[in] run_tag The run tag. - */ - ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions* options, _In_ const char* run_tag); - - /** \brief Get per-run log verbosity level - * - * \see OrtApi::RunOptionsSetRunLogVerbosityLevel - * - * \param[in] options - * \param[out] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options, - _Out_ int* log_verbosity_level); - - /** \brief Get per-run log severity level - * - * \see OrtApi::RunOptionsSetRunLogSeverityLevel - * - * \param[in] options - * \param[out] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). - */ - ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* log_severity_level); - - /** \brief Get per-run tag - * - * This is used in a per-run log identifier. - * - * \see OrtApi::RunOptionsSetRunTag - * - * \param[in] options - * \param[out] run_tag The run tag. - * Do not free this value, it is owned by `options`. It will be invalidated if the run tag - * changes (i.e., with OrtApi::RunOptionsSetRunTag) or `options` is freed. - */ - ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions* options, _Out_ const char** run_tag); - - /** \brief Set terminate flag - * - * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error. - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options); - - /** \brief Clears the terminate flag - * - * Used so the OrtRunOptions instance can be used in a new OrtApi::Run call without it instantly terminating - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Create a tensor - * - * Create a tensor using a supplied ::OrtAllocator - * - * \param[in] allocator - * \param[in] shape Pointer to the tensor shape dimensions. - * \param[in] shape_len The number of tensor shape dimensions. - * \param[in] type - * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type, _Outptr_ OrtValue** out); - - /** \brief Create a tensor backed by a user supplied buffer - * - * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after. - * p_data is owned by caller. ReleaseValue won't release p_data. - * - * If you wish to transfer ownership of p_data to ORT use CreateTensorWithDataAndDeleterAsOrtValue. - * - * \param[in] info Memory description of where the p_data buffer resides (CPU vs GPU etc). - * \param[in] p_data Pointer to the data buffer. - * \param[in] p_data_len The number of bytes in the data buffer. - * \param[in] shape Pointer to the tensor shape dimensions. - * \param[in] shape_len The number of tensor shape dimensions. - * \param[in] type The data type. - * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, - size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type, - _Outptr_ OrtValue** out); - - /** \brief Return if an ::OrtValue is a tensor type - * - * \param[in] value A tensor type (string tensors are not supported) - * \param[out] out Set to 1 iff ::OrtValue is a tensor, 0 otherwise - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out); - - /** \brief Get a pointer to the raw data inside a tensor - * - * Used to read/write/modify the internal tensor data directly. - * \note The returned pointer is valid until the \p value is destroyed. - * - * \param[in] value A tensor type (string tensors are not supported) - * \param[out] out Filled in with a pointer to the internal storage - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorMutableData, _In_ OrtValue* value, _Outptr_ void** out); - - /** \brief Set all strings at once in a string tensor - * - * \param[in,out] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING - * \param[in] s An array of strings. Each string in this array must be null terminated. - * \param[in] s_len Count of strings in s (Must match the size of \p value's tensor shape) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len); - - /** \brief Get total byte length for all strings in a string tensor - * - * Typically used with OrtApi::GetStringTensorContent - * - * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING - * \param[out] len Total byte length of all strings (does not include trailing nulls) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len); - - /** \brief Get all strings from a string tensor - * - * An example of the results:
- * Given \p value is a string tensor with the strings { "This" "is" "a" "test" }
- * \p s must have a size of 11 bytes
- * \p offsets must have 4 elements
- * After the call, these values will be filled in:
- * \p s will contain "Thisisatest"
- * \p offsets will contain { 0, 4, 6, 7 }
- * The length of the last string is just s_len - offsets[last] - * - * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING - * \param[in] s Buffer to sequentially write all tensor strings to. Each string is NOT null-terminated. - * \param[in] s_len Number of bytes of buffer pointed to by \p s (Get it from OrtApi::GetStringTensorDataLength) - * \param[out] offsets Array of start offsets into the strings written to \p s - * \param[in] offsets_len Number of elements in offsets - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s, - size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len); - - /// @} - /// \name OrtTypeInfo - /// @{ - - /** \brief Get ::OrtTensorTypeAndShapeInfo from an ::OrtTypeInfo - * - * \param[in] type_info - * \param[out] out Do not free this value, it will be valid until type_info is freed. - * If type_info does not represent tensor, this value will be set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out); - - /** \brief Get ::ONNXType from ::OrtTypeInfo - * - * \param[in] type_info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ enum ONNXType* out); - - /// @} - /// \name OrtTensorTypeAndShapeInfo - /// @{ - - /** \brief Create an ::OrtTensorTypeAndShapeInfo object - * - * \param[out] out Returns newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Set element type in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[in] type - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo* info, enum ONNXTensorElementDataType type); - - /** \brief Set shape information in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[in] dim_values Array with `dim_count` elements. Can contain negative values. - * \param[in] dim_count Number of elements in `dim_values` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count); - - /** \brief Get element type in ::OrtTensorTypeAndShapeInfo - * - * \see OrtApi::SetTensorElementType - * - * \param[in] info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo* info, - _Out_ enum ONNXTensorElementDataType* out); - - /** \brief Get dimension count in ::OrtTensorTypeAndShapeInfo - * - * \see OrtApi::GetDimensions - * - * \param[in] info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); - - /** \brief Get dimensions in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[out] dim_values Array with `dim_values_length` elements. On return, filled with the dimensions stored in the ::OrtTensorTypeAndShapeInfo - * \param[in] dim_values_length Number of elements in `dim_values`. Use OrtApi::GetDimensionsCount to get this value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, - size_t dim_values_length); - - /** \brief Get symbolic dimension names in ::OrtTensorTypeAndShapeInfo - * - * \param[in] info - * \param[in] dim_params Array with `dim_params_length` elements. On return filled with pointers to null terminated strings of the dimension names - * \param[in] dim_params_length Number of elements in `dim_params`. Use OrtApi::GetDimensionsCount to get this value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, - _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length); - - /** \brief Get total number of elements in a tensor shape from an ::OrtTensorTypeAndShapeInfo - * - * Return the number of elements specified by the tensor shape (all dimensions multiplied by each other). - * For 0 dimensions, 1 is returned. If any dimension is less than 0, the result is always -1. - * - * Examples:
- * [] = 1
- * [1,3,4] = 12
- * [2,0,4] = 0
- * [-1,3,4] = -1
- * - * \param[in] info - * \param[out] out Number of elements - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Get type and shape information from a tensor ::OrtValue - * - * \param[in] value Must be a tensor (not a map/sequence/etc) or will return failure - * \param[out] out Newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Get type information of an OrtValue - * - * \param[in] value - * \param[out] out Newly created ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out); - - /** \brief Get ONNXType of an ::OrtValue - * - * \param[in] value - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out); - - /// @} - /// \name OrtMemoryInfo - /// @{ - - /** \brief Create an ::OrtMemoryInfo - * - * \param[in] name - * \param[in] type - * \param[in] id - * \param[in] mem_type - * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtAPi::ReleaseMemoryInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name, enum OrtAllocatorType type, int id, - enum OrtMemType mem_type, _Outptr_ OrtMemoryInfo** out); - - /** \brief Create an ::OrtMemoryInfo for CPU memory - * - * Special case version of OrtApi::CreateMemoryInfo for CPU based memory. Same as using OrtApi::CreateMemoryInfo with name = "Cpu" and id = 0. - * - * \param[in] type - * \param[in] mem_type - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type, - _Outptr_ OrtMemoryInfo** out); - - /** \brief Compare ::OrtMemoryInfo objects for equality - * - * Compares all settings of each ::OrtMemoryInfo for equality - * - * \param[in] info1 - * \param[in] info2 - * \param[out] out Set to 0 if equal, -1 if not equal - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out); - - /** \brief Get name from ::OrtMemoryInfo - * - * \param[in] ptr - * \param[out] out Writes null terminated string to this pointer. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtMemoryInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out); - - /** \brief Get the id from ::OrtMemoryInfo - */ - ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out); - - /** \brief Get the ::OrtMemType from ::OrtMemoryInfo - */ - ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out); - - /** \brief Get the ::OrtAllocatorType from ::OrtMemoryInfo - */ - ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out); - - /// @} - /// \name OrtAllocator - /// @{ - - /// \brief Calls OrtAllocator::Alloc function - ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ort_allocator, size_t size, _Outptr_ void** out); - /// \brief Calls OrtAllocator::Free function - ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ort_allocator, void* p); - /// \brief Calls OrtAllocator::Info function - ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ort_allocator, _Outptr_ const struct OrtMemoryInfo** out); - - /** \brief Get the default allocator - * - * The default allocator is a CPU based, non-arena. Always returns the same pointer to the same default allocator. - * - * \param[out] out Returned value should NOT be freed - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Override session symbolic dimensions - * - * Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable - * optimizations that can take advantage of fixed values (such as memory planning, etc) - * - * \param[in] options - * \param[in] dim_denotation - * \param[in] dim_value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation, - _In_ int64_t dim_value); - - /// @} - /// \name OrtValue - /// @{ - - /* Internal information (not seen in Doxygen) - * - * APIs to support non-tensor types - map and sequence. - * Currently only the following types are supported - * Note: the following types should be kept in sync with data_types.h - * Map types - * ========= - * std::map - * std::map - * std::map - * std::map - * std::map - * std::map - * std::map - * std::map - * - * Sequence types - * ============== - * std::vector - * std::vector - * std::vector - * std::vector - * std::vector> - * std::vector - */ - - /** \brief Get non tensor data from an ::OrtValue - * - * If `value` is of type ONNX_TYPE_MAP, you need to retrieve the keys and values - * separately. Use index=0 to retrieve keys and index=1 to retrieve values. - * If `value` is of type ONNX_TYPE_SEQUENCE, use index to retrieve the index'th element - * of the sequence. - * - * \param[in] value - * \param[in] index See above for usage based on `value` type - * \param[in] allocator Allocator used to allocate ::OrtValue - * \param[out] out Created ::OrtValue that holds the element requested. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator, - _Outptr_ OrtValue** out); - - /** \brief Get non tensor value count from an ::OrtValue - * - * If `value` is of type ONNX_TYPE_MAP 2 will always be returned. For ONNX_TYPE_SEQUENCE - * the number of elements in the sequence will be returned - * - * \param[in] value - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out); - - /** \brief Create a map or sequence ::OrtValue - * - * To construct a map (ONNX_TYPE_MAP), use num_values = 2 and `in` should be an array of 2 ::OrtValue%s - * representing keys and values.
- * - * To construct a sequence (ONNX_TYPE_SEQUENCE), use num_values = N where N is the number of the elements in the - * sequence. 'in' should be an array of N ::OrtValue%s. - * - * \param[in] in See above for details - * \param[in] num_values - * \param[in] value_type Must be either ONNX_TYPE_MAP or ONNX_TYPE_SEQUENCE - * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values, - enum ONNXType value_type, _Outptr_ OrtValue** out); - - /** \brief Create an opaque (custom user defined type) ::OrtValue - * - * Constructs an ::OrtValue that contains a value of non-standard type created for - * experiments or while awaiting standardization. ::OrtValue in this case would contain - * an internal representation of the Opaque type. Opaque types are distinguished from - * each other by two strings 1) domain and 2) type name. The combination of the two - * must be unique, so the type representation is properly identified internally. The combination - * must be properly registered from within ORT at both compile/run time or by another API. - * - * To construct the ::OrtValue pass domain and type names, also a pointer to a data container - * the type of which must be known to both ORT and the client program. That data container may or may - * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for - * verification purposes. - * - * \param[in] domain_name Null terminated string of the domain name - * \param[in] type_name Null terminated string of the type name - * \param[in] data_container User pointer Data to populate ::OrtValue - * \param[in] data_container_size Size in bytes of what `data_container` points to - * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name, - _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out); - - /** \brief Get internal data from an opaque (custom user defined type) ::OrtValue - * - * Copies internal data from an opaque value into a user provided buffer - * - * \see OrtApi::CreateOpaqueValue - * - * \param[in] domain_name Null terminated string of the domain name - * \param[in] type_name Null terminated string of the type name - * \param[in] in The opaque ::OrtValue - * \param[out] data_container Buffer to copy data into - * \param[out] data_container_size Size in bytes of the buffer pointed to by data_container. Must match the size of the internal buffer. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in, - _Out_ void* data_container, size_t data_container_size); - - /// @} - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Get a float stored as an attribute in the graph node - * - * \param[in] info ::OrtKernelInfo instance - * \param[in] name Null terminated string of the name of the attribute - * \param[out] out Pointer to memory where the attribute will be stored - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ float* out); - - /** \brief Fetch a 64-bit int stored as an attribute in the graph node - * - * \param[in] info ::OrtKernelInfo instance - * \param[in] name Null terminated string of the name of the attribute - * \param[out] out Pointer to memory where the attribute will be stored - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ int64_t* out); - - /** \brief Fetch a string stored as an attribute in the graph node - * - * If `out` is nullptr, the value of `size` is set to the true size of the string - * attribute, and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual string attribute's size, - * the value of `size` is set to the true size of the string attribute, the provided memory - * is filled with the attribute's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string attribute's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string attribute - * and a failure status is returned.) - * - * \param[in] info ::OrtKernelInfo instance - * \param[in] name Null terminated string of the name of the attribute - * \param[out] out Pointer to memory where the attribute will be stored - * \param[in,out] size See above comments for details - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out, - _Inout_ size_t* size); - - /// @} - /// \name OrtKernelContext - /// Custom operator APIs. - /// @{ - - /** \brief Used for custom operators, get the input count of a kernel - * - * \see ::OrtCustomOp - */ - ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); - - /** \brief Used for custom operators, get the output count of a kernel - * - * \see ::OrtCustomOp - */ - ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); - - /** \brief Used for custom operators, get an input of a kernel - * - * The function attempts fetches the input of the kernel. If the input is optional - * and not present, the function returns success and out is set to nullptr. - * - * \param[in] context ::OrtKernelContext instance - * \param[in] index See KernelContext_GetInputCount for boundaries check. - * \param[out] out OrtValue if the input is present otherwise is set nullptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index, - _Out_ const OrtValue** out); - - /** \brief Used for custom operators, get an output of a kernel - * - * The function attempts fetches the output of the kernel. If the output is optional - * and not present, the function returns success and out is set to nullptr. - * - * \param[in] context ::OrtKernelContext instance - * \param[in] index See KernelContext_GetOutputCount for boundaries check. - * \param[in] dim_values output dimensions - * \param[in] dim_count number of dimensions - * \param[out] out a ptr to OrtValue to output otherwise set to nullptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index, - _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out); - - /// @} - /// \name OrtEnv - /// @{ - ORT_CLASS_RELEASE(Env); - /// @} - /// \name OrtStatus - /// @{ - ORT_CLASS_RELEASE(Status); - /// @} - /// \name OrtMemoryInfo - /// @{ - ORT_CLASS_RELEASE(MemoryInfo); - /// @} - /// \name OrtSession - /// @{ - ORT_CLASS_RELEASE(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) - /// @} - /// \name OrtValue - /// @{ - ORT_CLASS_RELEASE(Value); - /// @} - /// \name OrtRunOptions - /// @{ - ORT_CLASS_RELEASE(RunOptions); - /// @} - /// \name OrtTypeInfo - /// @{ - ORT_CLASS_RELEASE(TypeInfo); - /// @} - /// \name OrtTensorTypeAndShapeInfo - /// @{ - ORT_CLASS_RELEASE(TensorTypeAndShapeInfo); - /// @} - /// \name OrtSessionOptions - /// @{ - ORT_CLASS_RELEASE(SessionOptions); - /// @} - /// \name OrtCustomOpDomain - /// @{ - ORT_CLASS_RELEASE(CustomOpDomain); - - /// @} - /// \name OrtTypeInfo - /// @{ - - /** \brief Get denotation from type information - * - * Augments ::OrtTypeInfo to return denotations on the type. - * - * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor. - * - * \param[in] type_info - * \param[out] denotation Pointer to the null terminated denotation string is written to this pointer. This pointer is valid until the object is destroyed or the name is changed, do not free. - * \param[out] len Length in bytes of the string returned in `denotation` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ const char** const denotation, - _Out_ size_t* len); - - /** \brief Get detailed map information from an ::OrtTypeInfo - * - * This augments ::OrtTypeInfo to return an ::OrtMapTypeInfo when the type is a map. - * The OrtMapTypeInfo has additional information about the map's key type and value type. - * - * This is used by WinML to support model reflection APIs. - * - * \param[out] type_info - * \param[out] out A pointer to the ::OrtMapTypeInfo. Do not free this value. If type_info - * does not contain a map, this value will be set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtMapTypeInfo** out); - - /** \brief Cast ::OrtTypeInfo to an ::OrtSequenceTypeInfo - * - * This api augments ::OrtTypeInfo to return an ::OrtSequenceTypeInfo when the type is a sequence. - * The ::OrtSequenceTypeInfo has additional information about the sequence's element type. - * - * This is used by WinML to support model reflection APIs. - * - * \param[in] type_info - * \param[out] out A pointer to the OrtSequenceTypeInfo. Do not free this value. If type_info - * doesn not contain a sequence, this value will be set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out); - - /// @} - /// \name OrtMapTypeInfo - /// @{ - - /** \brief Get key type from an ::OrtMapTypeInfo - * - * Key types are restricted to being scalar types. - * - * This is used by WinML to support model reflection APIs. - * - * \param[in] map_type_info - * \param[out] out - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out); - - /** \brief Get the value type from an ::OrtMapTypeInfo - * - * \param[in] map_type_info - * \param[out] type_info A copy of the OrtTypeInfo for the map value type. - * The user must free this value with ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info); - - /// @} - /// \name OrtSequenceTypeInfo - /// @{ - - /** \brief Get element type from an ::OrtSequenceTypeInfo - * - * This is used by WinML to support model reflection APIs. - * - * \param[in] sequence_type_info - * \param[out] type_info A copy of the OrtTypeInfo for the sequence element type. - * The user must free this value with ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info, - _Outptr_ OrtTypeInfo** type_info); - - /// @} - /// \name OrtMapTypeInfo - /// @{ - ORT_CLASS_RELEASE(MapTypeInfo); - /// @} - /// \name OrtSequenceTypeInfo - /// @{ - ORT_CLASS_RELEASE(SequenceTypeInfo); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief End profiling and return filename of the profile data - * - * Profiling is turned on through OrtApi::EnableProfiling - * - * \param[in] session - * \param[in] allocator - * \param[out] out Null terminated string of the filename, allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* session, _Inout_ OrtAllocator* allocator, _Outptr_ char** out); - - /** \brief Get ::OrtModelMetadata from an ::OrtSession - * - * \param[in] session - * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* session, _Outptr_ OrtModelMetadata** out); - - /// @} - /// \name OrtModelMetadata - /// @{ - - /** \brief Get `producer name` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get `graph name` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Get `domain` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator, - _Outptr_ char** value); - - /** \brief Get `description` from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /** \brief Return data for a key in the custom metadata map in an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[in] allocator - * \param[in] key Null terminated string - * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` - * `value` will be set to nullptr if the given key is not found in the custom metadata map. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value); - - /** \brief Get version number from an ::OrtModelMetadata - * - * \param[in] model_metadata - * \param[out] value Set to the version number - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value); - - ORT_CLASS_RELEASE(ModelMetadata); - - /// @} - /// \name OrtEnv - /// @{ - - /** \brief Create an OrtEnv - * - * Create an environment with global threadpools that will be shared across sessions. - * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use - * its own thread pools. - * - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[in] tp_options - * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel log_severity_level, _In_ const char* logid, - _In_ const OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Use global thread pool on a session - * - * Disable using per session thread pool and use the shared global threadpool. - * This should be used in conjunction with OrtApi::CreateEnvWithGlobalThreadPools. - * - * \param[in] options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options); - - /// @} - /// \name OrtThreadingOptions - /// @{ - - /** \brief Create an ::OrtThreadingOptions - * - * \param[out] out Newly created ::OrtThreadingOptions. Must be freed with OrtApi::ReleaseThreadingOptions - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out); - - ORT_CLASS_RELEASE(ThreadingOptions); - - /// @} - /// \name OrtModelMetadata - /// @{ - - /** - * - * \param[in] model_metadata - * \param[in] allocator - * \param[out] keys Array of null terminated strings (array count = num_keys) allocated using `allocator`. - * The strings and the pointer array must be freed using `allocator` - * `keys` will be set to nullptr if the custom metadata map is empty. - * \param[out] num_keys Set to the number of elements in the `keys` array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** - * - * Override symbolic dimensions (by specific name strings) with actual values - * if known at session initialization time to enable optimizations that can - * take advantage of fixed values (such as memory planning, etc) - * - */ - ORT_API2_STATUS(AddFreeDimensionOverrideByName, - _Inout_ OrtSessionOptions* options, _In_ const char* dim_name, - _In_ int64_t dim_value); - - /// @} - /// \name Misc - /// @{ - - /** \brief Get the names of all available providers - * - * \note The providers in the list are not guaranteed to be usable. They may fail to load due to missing system dependencies. - * For example, if the CUDA/cuDNN libraries are not installed, the CUDA provider will report an error when it is added to the session options. - * - * \param[out] out_ptr Set to a pointer to an array of null terminated strings of the available providers. The entries and the - * array itself must be freed using OrtApi::ReleaseAvailableProviders - * \param[out] provider_length Set to the number of entries in the `out_ptr` array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr, _Out_ int* provider_length); - - /** \brief Release data from OrtApi::GetAvailableProviders. This API will never fail - * so you can rely on it in a noexcept code. - * - * \param[in] ptr The `out_ptr` result from OrtApi::GetAvailableProviders. - * \param[in] providers_length The `provider_length` result from OrtApi::GetAvailableProviders - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr, - _In_ int providers_length); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Get the length of a single string in a string tensor - * - * \param[in] value A string tensor - * \param[in] index Index of the string in the tensor - * \param[out] out Set to number of bytes of the string element - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out); - - /** \brief Get a single string from a string tensor - * - * \param[in] value A string tensor - * \param[in] s_len Number of bytes in the `s` buffer. Must match the value returned by OrtApi::GetStringTensorElementLength. - * \param[in] index Index of the string in the tensor - * \param[out] s The string element contents in UTF-8 encoding. The string is NOT null-terminated. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s); - - /** \brief Set a single string in a string tensor - * - * \param[in] value A string tensor - * \param[in] s A null terminated UTF-8 encoded string - * \param[in] index Index of the string in the tensor to set - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Set a session configuration entry as a pair of strings - * - * If a configuration with same key exists, this will overwrite the configuration with the given config_value. - * - * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h - * - * \param[in] options - * \param[in] config_key A null terminated string representation of the config key - * \param[in] config_value A null terminated string representation of the config value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options, - _In_z_ const char* config_key, _In_z_ const char* config_value); - - /// @} - /// \name OrtAllocator - /// @{ - - /** \brief Create an allocator for an ::OrtSession following an ::OrtMemoryInfo - * - * \param[in] session - * \param[in] mem_info valid ::OrtMemoryInfo instance - * \param[out] out Newly created ::OrtAllocator. Must be freed with OrtApi::ReleaseAllocator - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* session, _In_ const OrtMemoryInfo* mem_info, - _Outptr_ OrtAllocator** out); - - /** \brief Release an ::OrtAllocator obtained from OrtApi::CreateAllocator - */ - ORT_CLASS_RELEASE(Allocator); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Run a model using Io Bindings for the inputs & outputs - * - * \see OrtApi::Run - * - * \param[in] session - * \param[in] run_options - * \param[in] binding_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* session, _In_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr); - - /** \brief Create an ::OrtIoBinding instance - * - * An IoBinding object allows one to bind pre-allocated ::OrtValue%s to input names. - * Thus if you want to use a raw on device buffer as input or output you can avoid - * extra copy during runtime. - * - * \param[in] session - * \param[out] out Newly created ::OrtIoBinding. Must be freed with OrtApi::ReleaseIoBinding - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* session, _Outptr_ OrtIoBinding** out); - - /// @} - /// \name OrtIoBinding - /// @{ - - /** \brief Release an ::OrtIoBinding obtained from OrtApi::CreateIoBinding - */ - ORT_CLASS_RELEASE(IoBinding); - - /** \brief Bind an ::OrtValue to an ::OrtIoBinding input - * - * When using OrtApi::RunWithBinding this value is used for the named input - * - * \param[in] binding_ptr - * \param[in] name Name for the model input - * \param[in] val_ptr ::OrtValue of Tensor type. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); - - /** \brief Bind an ::OrtValue to an ::OrtIoBinding output - * - * When using OrtApi::RunWithBinding this value is used for the named output - * - * \param[in] binding_ptr - * \param[in] name Null terminated string of the model output name - * \param[in] val_ptr ::OrtValue of Tensor type. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); - - /** \brief Bind an ::OrtIoBinding output to a device - * - * Binds the ::OrtValue to a device which is specified by ::OrtMemoryInfo. - * You can either create an instance of ::OrtMemoryInfo with a device id or obtain one from the allocator that you have created/are using - * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocate and bind a chunk of - * memory within ::OrtValue ahead of time. - * - * \see OrtApi::RunWithBinding - * - * \param[in] binding_ptr - * \param[in] name Null terminated string of the device name - * \param[in] mem_info_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* mem_info_ptr); - - /** \brief Get the names of an ::OrtIoBinding's outputs - * - * Returns the names of the outputs in the order they were bound. This is useful after running the model - * with bound outputs because the returned names are in order in which output ::OrtValue are returned. This is useful if - * the order of outputs and their names is not known. - * - * \param[in] binding_ptr - * \param[in] allocator Allocator used to allocate continuous buffers for output strings and lengths. - * \param[out] buffer Returns an array of non-null terminated UTF-8 strings. The number of strings stored is returned in the count parameter. - * This buffer is allocated using `allocator` and must be freed using it. - * \param[out] lengths Returns an array of `count` lengths of the strings returned in `buffer` - * This buffer is allocated using `allocator` and must be freed using it. - * \param[out] count Number of strings returned. If `binding_ptr` has no bound outputs, zero is returned, - * no memory allocation is performed and buffer and lengths are set to nullptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, - _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count); - - /** \brief Get the output ::OrtValue objects from an ::OrtIoBinding - * - * Returns an array of pointers to individually allocated ::OrtValue%s that contain results of a model execution with OrtApi::RunWithBinding - * The array contains the same number of ::OrtValue%s and they are in the same order as they were bound with OrtApi::BindOutput - * or OrtApi::BindOutputToDevice. - * - * The returned ::OrtValue%s must be released using OrtApi::ReleaseValue after they are no longer needed. - * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after - * all the ::OrtValue%s contained therein are individually released. - * - * \param[in] binding_ptr - * \param[in] allocator Allocator used to allocate output array - * \param[out] output Set to the allocated array of allocated ::OrtValue outputs. Set to nullptr if there are 0 outputs. - * \param[out] output_count Set to number of ::OrtValue%s returned - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, - _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count); - - /** \brief Clears any previously set Inputs for an ::OrtIoBinding - */ - void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /** \brief Clears any previously set Outputs for an ::OrtIoBinding - */ - void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Direct memory access to a specified tensor element - * - * For example, given a tensor with shape of [3,224,224], a pointer to the element at location [2,150,128] can be retrieved - * - * This function only works for numeric type tensors (No strings, etc). - * This is a no-copy method whose returned pointer is valid until the passed in ::OrtValue is free'd. - * - * \param[in] value - * \param[in] location_values Pointer to an array of index values that specify an element's location relative to its shape - * \param[in] location_values_count Number of elements in location_values. Must match the number of elements in the tensor's shape. - * \param[out] out Set to a pointer to the element specified - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out); - - /// @} - /// \name OrtEnv - /// @{ - - /** \brief Create an allocator and register it with the ::OrtEnv - * - * Enables sharing the allocator between multiple sessions that use the same env instance. - * Lifetime of the created allocator will be valid for the duration of the environment. - * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. - * - * See https://onnxruntime.ai/docs/get-started/with-c.html for details. - * - * \param[in] env ::OrtEnv instance - * \param[in] mem_info - * \param[in] arena_cfg Pass nullptr for defaults - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info, - _In_ const OrtArenaCfg* arena_cfg); - - /** \brief Set language projection - * - * Set the language projection for collecting telemetry data when Env is created. - * - * The default is ORT_PROJECTION_C, which means it will classify the language not in the list to C also. - * - * \param[in] ort_env - * \param[in] projection - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Return the time that profiling was started - * - * \note The timer precision varies per platform. On Windows and MacOS, the precision will be ~100ns - * - * \param[in] session - * \param[out] out nanoseconds of profiling's start time - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* session, _Outptr_ uint64_t* out); - - /// @} - /// \name OrtThreadingOptions - /// @{ - - /** \brief Set global intra-op thread count - * - * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools - * - * \param[in] tp_options - * \param[in] intra_op_num_threads Number of threads, special values:
- * 0 = Use default thread count
- * 1 = The invoking thread will be used; no threads will be created in the thread pool. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads); - - /** \brief Set global inter-op thread count - * - * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools - * - * \param[in] tp_options - * \param[in] inter_op_num_threads Number of threads, special values:
- * 0 = Use default thread count
- * 1 = The invoking thread will be used; no threads will be created in the thread pool. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads); - - /** \brief Set global spin control options - * - * This will configure the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. - * Allow spinning of thread pools when their queues are empty. This will set the value for both - * inter_op and intra_op threadpools. - * - * \param[in] tp_options - * \param[in] allow_spinning Valid values are 0 or 1.
- * 0 = It won't spin (recommended if CPU usage is high)
- * 1 = Threadpool will spin to wait for queue to become non-empty - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Add a pre-allocated initializer to a session - * - * If a model contains an initializer with a name that is same as the name passed to this call, - * ORT will use this initializer instance instead of deserializing one from the model file. This - * is useful when you want to share the same initializer across sessions. - * - * \param[in] options - * \param[in] name Null terminated string of the initializer name - * \param[in] val ::OrtValue containing the initializer. Its lifetime and the underlying initializer buffer must be - * managed by the user (created using the OrtApi::CreateTensorWithDataAsOrtValue) and it must outlive the session object - * to which it is added. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name, - _In_ const OrtValue* val); - - /// @} - /// \name OrtEnv - /// @{ - - /** - * Create a custom environment with global threadpools and logger that will be shared across sessions. - * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use - * its own thread pools. - * - * \param[in] logging_function A pointer to a logging function. - * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to - * `logging_function`. - * \param[in] log_severity_level The log severity level. - * \param[in] logid The log identifier. - * \param[in] tp_options - * \param[out] out Newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel log_severity_level, - _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Append CUDA provider to session options - * - * If CUDA is not available (due to a non CUDA enabled build, or if CUDA is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] cuda_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA, - _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options); - - /** \brief Append ROCM execution provider to the session options - * - * If ROCM is not available (due to a non ROCM enabled build, or if ROCM is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] rocm_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_ROCM, - _In_ OrtSessionOptions* options, _In_ const OrtROCMProviderOptions* rocm_options); - - /** \brief Append OpenVINO execution provider to the session options - * - * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. - * - * \param[in] options - * \param[in] provider_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO, - _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options); - - /// @} - /// \name OrtThreadingOptions - /// @{ - - /** \brief Set threading flush-to-zero and denormal-as-zero - * - * Sets global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. - * Flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool. - * \note This option is not needed if the models used have no denormals. Having no denormals is recommended as this option may hurt model accuracy. - * - * \param[in] tp_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options); - - /// @} - /// \name OrtArenaCfg - /// @{ - - /** \deprecated Use OrtApi::CreateArenaCfgV2 - * - * This will create the configuration of an arena that can eventually be used to define an arena based allocator's behavior - * - * \param[in] max_mem Use 0 to allow ORT to choose the default - * \param[in] arena_extend_strategy Use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested - * \param[in] initial_chunk_size_bytes Use -1 to allow ORT to choose the default - * \param[in] max_dead_bytes_per_chunk Use -1 to allow ORT to choose the default - * \param[in] out A pointer to an OrtArenaCfg instance - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, - int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out); - - ORT_CLASS_RELEASE(ArenaCfg); - - /// @} - /// \name OrtModelMetadata - /// @{ - - /** - * Use this to obtain the description of the graph present in the model - * (doc_string field of the GraphProto message within the ModelProto message). - * If it doesn't exist, an empty string will be returned. - * - * \param[in] model_metadata An instance of ::OrtModelMetadata - * \param[in] allocator Allocator used to allocate the string that will be returned back - * \param[out] value Set to a null terminated string allocated using `allocator`. The caller is responsible for freeing it using `allocator` - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata, - _Inout_ OrtAllocator* allocator, _Outptr_ char** value); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Append TensorRT provider to session options - * - * If TensorRT is not available (due to a non TensorRT enabled build, or if TensorRT is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] tensorrt_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT, - _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptions* tensorrt_options); - - /// @} - /// \name Misc - /// @{ - - /** \brief Set current GPU device ID - * - * Set the current device id of the GPU execution provider (CUDA/tensorrt/rocm). The device id should be less - * than the total number of devices available. This is only useful when multiple-GPUs are installed and it is - * required to restrict execution to a single GPU. - * - * \param[in] device_id - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetCurrentGpuDeviceId, _In_ int device_id); - - /** \brief Get current GPU device ID - * - * Get the current device id of the GPU execution provider (CUDA/tensorrt/rocm). - * - * \see OrtApi::SetCurrentGpuDeviceId - * - * \param[out] device_id - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetCurrentGpuDeviceId, _In_ int* device_id); - - /// @} - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Fetch an array of int64_t values stored as an attribute in the graph node - * - * - * If `out` is nullptr, the value of `size` is set to the true size of the attribute - * array's size, and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual attribute array's size, - * the value of `size` is set to the true size of the attribute array's size, - * the provided memory is filled with the attribute's contents, - * and a success status is returned. - * - * If the `size` parameter is less than the actual attribute array's size and `out` - * is not nullptr, the value of `size` is set to the true size of the attribute array's size - * and a failure status is returned.) - * - * \param[in] info instance - * \param[in] name name of the attribute to be parsed - * \param[out] out pointer to memory where the attribute's contents are to be stored - * \param[in, out] size actual size of attribute array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ float* out, _Inout_ size_t* size); - - /** \brief Fetch an array of int64_t values stored as an attribute in the graph node - * - * If `out` is nullptr, the value of `size` is set to the true size of the attribute - * array's size, and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual attribute array's size, - * the value of `size` is set to the true size of the attribute array's size, - * the provided memory is filled with the attribute's contents, - * and a success status is returned. - * - * If the `size` parameter is less than the actual attribute array's size and `out` - * is not nullptr, the value of `size` is set to the true size of the attribute array's size - * and a failure status is returned.) - * - * \param[in] info instance - * \param[in] name name of the attribute to be parsed - * \param[out] out pointer to memory where the attribute's contents are to be stored - * \param[in, out] size actual size of attribute array - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, - _Out_ int64_t* out, _Inout_ size_t* size); - - /// @} - /// \name OrtArenaCfg - /// @{ - - /** \brief Create an ::OrtArenaCfg - * - * Create the configuration of an arena that can eventually be used to define an arena based allocator's behavior. - * - * Supported keys are (See https://onnxruntime.ai/docs/get-started/with-c.html for details on what the - * following parameters mean and how to choose these values.): - * "max_mem": Maximum memory that can be allocated by the arena based allocator. - * Use 0 for ORT to pick the best value. Default is 0. - * "arena_extend_strategy": 0 = kNextPowerOfTwo, 1 = kSameAsRequested. - * Use -1 to allow ORT to choose the default. - * "initial_chunk_size_bytes": (Possible) Size of the first allocation in the arena. - * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. - * Ultimately, the first allocation size is determined by the allocation memory request. - * "max_dead_bytes_per_chunk": Threshold of unused memory in an allocated chunk of arena memory after - * crossing which the current chunk is chunked into 2. - * "initial_growth_chunk_size_bytes": (Possible) Size of the second allocation in the arena. - * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. - * "max_power_of_two_extend_bytes": The maximum enxtend size if arena strategy is `kNextPowerOfTwo`. - * It is not an allocation limit, it is only a limit for extension when requested byte is less than the limit. - * When requested bytes is more than the limit, allocator will still return as requested. - * Use -1 to allow ORT to choose the default 1GB for max_power_of_two_extend_bytes. - * Ultimately, the allocation size is determined by the allocation memory request. - * Further allocation sizes are governed by the arena extend strategy. - * - * \param[in] arena_config_keys Keys to configure the arena - * \param[in] arena_config_values Values to configure the arena - * \param[in] num_keys Number of keys in `arena_config_keys` and `arena_config_values` - * \param[out] out Newly created ::OrtArenaCfg. Must be freed with OrtApi::ReleaseArenaCfg - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateArenaCfgV2, _In_reads_(num_keys) const char* const* arena_config_keys, - _In_reads_(num_keys) const size_t* arena_config_values, _In_ size_t num_keys, - _Outptr_ OrtArenaCfg** out); - - /// @} - /// \name OrtRunOptions - /// @{ - - /** \brief Set a single run configuration entry as a pair of strings - * - * If a configuration with same key exists, this will overwrite the configuration with the given config_value - * - * The config_key and the format of config_value are defined in onnxruntime_run_options_config_keys.h - * - * \param[in] options - * \param[in] config_key A null terminated string representation of the config key - * \param[in] config_value A null terminated string representation of the config value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(AddRunConfigEntry, _Inout_ OrtRunOptions* options, - _In_z_ const char* config_key, _In_z_ const char* config_value); - - /// @} - /// \name OrtPrepackedWeightsContainer - /// @{ - - /** \brief Create an ::OrtPrepackedWeightsContainer - * - * This container will hold pre-packed buffers of shared initializers for sharing between sessions - * (i.e.) if there are shared initializers that can be shared between sessions, the pre-packed buffers - * of these (if any) may possibly be shared to provide memory footprint savings. Pass this container - * to sessions that you would like to share pre-packed buffers of shared initializers at session - * creation time. - * - * \param[out] out Newly created ::OrtPrepackedWeightsContainer. Must be freed with OrtApi::ReleasePrepackedWeightsContainer - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreatePrepackedWeightsContainer, _Outptr_ OrtPrepackedWeightsContainer** out); - - /** \brief Release OrtPrepackedWeightsContainer instance - * - * \note instance must not be released until the sessions using it are released - */ - ORT_CLASS_RELEASE(PrepackedWeightsContainer); - - /// @} - /// \name OrtSession - /// @{ - - /** \brief Create session with prepacked weights container - * - * Same functionality offered by OrtApi::CreateSession except that a container that contains - * pre-packed weights' buffers is written into/read from by the created session. - * This is useful when used in conjunction with OrtApi::AddInitializer which injects - * shared initializer info into sessions. Wherever possible, the pre-packed versions of these - * shared initializers are cached in this container so that multiple sessions can just re-use - * these instead of duplicating these in memory. - * - * \param[in] env OrtEnv instance instance - * \param[in] model_path Null terminated string of the path (wchar on Windows, char otherwise) - * \param[in] options - * \param[in] prepacked_weights_container - * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionWithPrepackedWeightsContainer, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, - _In_ const OrtSessionOptions* options, - _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, - _Outptr_ OrtSession** out); - - /** \brief Create session from memory with prepacked weights container - * - * Same functionality offered by OrtApi::CreateSessionFromArray except that a container that contains - * pre-packed weights' buffers is written into/read from by the created session. - * This is useful when used in conjunction with OrtApi::AddInitializer which injects - * shared initializer info into sessions. Wherever possible, the pre-packed versions of these - * shared initializers are cached in this container so that multiple sessions can just re-use - * these instead of duplicating these in memory. - * - * \param[in] env - * \param[in] model_data Array of bytes holding the model - * \param[in] model_data_length Number of bytes in `model_data_model` - * \param[in] options - * \param[in] prepacked_weights_container - * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSessionFromArrayWithPrepackedWeightsContainer, _In_ const OrtEnv* env, - _In_ const void* model_data, size_t model_data_length, - _In_ const OrtSessionOptions* options, - _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, - _Outptr_ OrtSession** out); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Append TensorRT execution provider to the session options - * - * If TensorRT is not available (due to a non TensorRT enabled build), this function will return failure. - * - * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, it takes an - * ::OrtTensorRTProviderOptions which is publicly defined. This takes an opaque ::OrtTensorRTProviderOptionsV2 - * which must be created with OrtApi::CreateTensorRTProviderOptions. - * - * For OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, the user needs to instantiate ::OrtTensorRTProviderOptions - * as well as allocate/release buffers for some members of ::OrtTensorRTProviderOptions. - * Here, OrtApi::CreateTensorRTProviderOptions and Ortapi::ReleaseTensorRTProviderOptions will do the memory management for you. - * - * \param[in] options - * \param[in] tensorrt_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT_V2, - _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options); - - /// @} - /// \name OrtTensorRTProviderOptionsV2 - /// @{ - - /** \brief Create an OrtTensorRTProviderOptionsV2 - * - * \param[out] out Newly created ::OrtTensorRTProviderOptionsV2. Must be released with OrtApi::ReleaseTensorRTProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateTensorRTProviderOptions, _Outptr_ OrtTensorRTProviderOptionsV2** out); - - /** \brief Set options in a TensorRT Execution Provider. - * - * Please refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#cc - * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtTensorRTProviderOptionsV2 - * and value should be its related range. Recreates the options and only sets the supplied values. - * - * For example, key="trt_max_workspace_size" and value="2147483648" - * - * \param[in] tensorrt_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UpdateTensorRTProviderOptions, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Get serialized TensorRT provider options string. - * - * For example, "trt_max_workspace_size=2147483648;trt_max_partition_iterations=10;trt_int8_enable=1;......" - * - * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with OrtApi::CreateAllocator or OrtApi::GetAllocatorWithDefaultOptions - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorRTProviderOptionsAsString, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtTensorRTProviderOptionsV2 - * - * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does - */ - void(ORT_API_CALL* ReleaseTensorRTProviderOptions)(_Frees_ptr_opt_ OrtTensorRTProviderOptionsV2* input); - - /// @} - /// \name OrtSessionOptions - /// @{ - - /** \brief Enable custom operators - * - * See onnxruntime-extensions: https://github.com/microsoft/onnxruntime-extensions.git - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(EnableOrtCustomOps, _Inout_ OrtSessionOptions* options); - - /// @} - /// \name OrtAllocator - /// @{ - - /** \brief Register a custom allocator - * - * Enables sharing between multiple sessions that use the same env instance. - * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. - * - * The behavior of this is exactly the same as OrtApi::CreateAndRegisterAllocator except - * instead of ORT creating an allocator based on provided info, in this case - * ORT uses the user-provided custom allocator. - * See https://onnxruntime.ai/docs/get-started/with-c.html for details. - * - * \param[in] env - * \param[in] allocator User provided allocator - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(RegisterAllocator, _Inout_ OrtEnv* env, _In_ OrtAllocator* allocator); - - /** \brief Unregister a custom allocator - * - * It is an error if you provide an ::OrtMemoryInfo not corresponding to any - * registered allocators for sharing. - * - * \param[in] env - * \param[in] mem_info - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UnregisterAllocator, _Inout_ OrtEnv* env, - _In_ const OrtMemoryInfo* mem_info); - - /// @} - /// \name OrtValue - /// @{ - - /** \brief Sets *out to 1 iff an ::OrtValue is a SparseTensor, and 0 otherwise - * - * \param[in] value existing ::OrtValue - * \param[out] out unless an error occurs, contains 1 iff the value contains an instance - * of sparse tensor or 0 otherwise. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(IsSparseTensor, _In_ const OrtValue* value, _Out_ int* out); - - /** \brief Create an ::OrtValue with a sparse tensor that is empty. - * - * Use FillSparseTensor() functions to populate sparse tensor with non-zero values and - * format specific indices data. - * Use ReleaseValue to destroy the sparse tensor, this will also release the buffer inside the output value - * if any was allocated. - * \param[in,out] allocator allocator to use when performing an allocation. Allocation will be performed - * by FillSparseTensor() APIs. The lifespan of the allocator instance must eclipse the lifespan - * this sparse tensor instance as the same allocator will be used to free memory. - * \param[in] dense_shape shape of the original dense tensor - * \param[in] dense_shape_len number of shape dimensions being passed - * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx - * \param[out] out Should be freed by calling ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSparseTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* dense_shape, - size_t dense_shape_len, ONNXTensorElementDataType type, _Outptr_ OrtValue** out); - - /** - * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. - * This will allocate required memory and copy the supplied NNZ values and COO indices into that memory allocation. - * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. - * - * \param[in,out] ort_value ::OrtValue to populate with data - * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified - * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. - * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. - * \param[in] values_shape pointer to values shape array - * \param[in] values_shape_len length of the values_shape - * \param[in] values pointer to an array of values. For strings, pass const char**. - * \param[in] indices_data pointer to a location of COO indices - * \param[in] indices_num number of COO indices - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillSparseTensorCoo, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, - _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, - _In_ const int64_t* indices_data, size_t indices_num); - - /** - * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. - * This will allocate required memory and copy the supplied NNZ values and CSR indices into that memory allocation. - * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. - * - * \param[in,out] ort_value ::OrtValue to populate with data - * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified - * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. - * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. - * \param[in] values_shape pointer to values shape array - * \param[in] values_shape_len length of the values_shape - * \param[in] values - pointer to an array of values. For strings, pass const char**. - * \param[in] inner_indices_data pointer to a location of CSR inner indices - * \param[in] inner_indices_num number of CSR inner indices - * \param[in] outer_indices_data pointer to a location of CSR outer indices - * \param[in] outer_indices_num number of CSR outer indices - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillSparseTensorCsr, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, - _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, - _In_ const int64_t* inner_indices_data, size_t inner_indices_num, - _In_ const int64_t* outer_indices_data, size_t outer_indices_num); - - /** - * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. - * This will allocate required memory and copy the supplied NNZ values and BlockSparse indices into that memory allocation. - * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. - * - * \param[in,out] ort_value ::OrtValue to populate with data - * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified - * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. - * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. - * \param[in] values_shape - * \param[in] values_shape_len - * \param[in] values structure with values information - * \param[in] indices_shape_data pointer to a location of indices shape - * \param[in] indices_shape_len length of the block sparse indices shape - * \param[in] indices_data pointer to a location of indices data. Shape will determine the length of the indices data. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(FillSparseTensorBlockSparse, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, - _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, - _In_ const int64_t* indices_shape_data, size_t indices_shape_len, - _In_ const int32_t* indices_data); - - /** - * Create an ::OrtValue with a sparse tensor. This is the first step. - * Next, use UseIndices() functions to supply sparse tensor with - * format specific indices data and set its sparse format to a specific enum value. - * This will not perform memory allocations. It will - * use supplied user buffer which should outlive the created sparse tensor. - * Use OrtApi::ReleaseValue to destroy the sparse tensor. It would not release the supplied values buffer. - * This function can not be used to map strings from the user allocated memory. Strings must always be copied - * and have UTF-8 encoding. Therefore, use OrtApi::CreateSparseTensorAsOrtValue above and then fill it with data - * using appropriate Make*() function. - * - * \param[in] info memory info where sparse values reside. - * \param[in,out] p_data pointer to a user allocated buffer with values. To create a full sparse tensor with no non-zero - * values, pass nullptr - * \param[in] dense_shape shape of the original dense tensor - * \param[in] dense_shape_len number of shape dimensions being passed - * \param[in] values_shape shape of the values data. To create a fully sparse tensor with no non-zero values, - * pass {0} shape. - * \param[in] values_shape_len number of values shape dimensions - * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx - * \param[out] out Should be freed by calling ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(CreateSparseTensorWithValuesAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, - _In_ const int64_t* dense_shape, size_t dense_shape_len, - _In_ const int64_t* values_shape, size_t values_shape_len, - ONNXTensorElementDataType type, _Outptr_ OrtValue** out); - - /** - * This assigns Coo format indices to the SparseTensor that was created by - * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to - * ORT_SPARSE_COO. This will not allocate any additional memory for data. The life span of - * indices_data buffer should eclipse the life span of this ::OrtValue. - * - * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue - * \param[in,out] indices_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. - * \param[in] indices_num number of COO indices. Should either be 0 for fully sparse tensors, be equal - * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue for 1-D {nnz} indices or - * be twice as number of nnz values for a 2-D indices {nnz, 2} - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UseCooIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* indices_data, size_t indices_num); - - /** - * The assigns CSR format indices to the SparseTensor that was created by - * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to - * ORT_SPARSE_CSRC. This will not allocate any additional memory for data. The life spans of - * inner_data and outer_data buffers should eclipse the life span of this ::OrtValue. - * - * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue - * \param[in,out] inner_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. - * \param[in] inner_num number of inner CSR indices. Should either be 0 for fully sparse tensors or be equal - * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue. - * \param[in,out] outer_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. - * \param[in] outer_num number of CSR outer indices. Should either be 0 for fully sparse tensors or - * equal to rows + 1 of the dense shape. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UseCsrIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* inner_data, size_t inner_num, - _Inout_ int64_t* outer_data, size_t outer_num); - - /** - * The assigns BlockSparse format indices to the SparseTensor that was created by - * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to - * ORT_SPARSE_BLOCK_SPARSE. This will not allocate any additional memory for data. The life span of - * indices_data buffer must eclipse the lifespan of this ::OrtValue. - * - * \param[in,out] ort_value OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue - * \param[in] indices_shape pointer to indices shape. Use {0} for fully sparse tensors - * \param[in] indices_shape_len length of the indices shape - * \param[in,out] indices_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(UseBlockSparseIndices, _Inout_ OrtValue* ort_value, const int64_t* indices_shape, size_t indices_shape_len, _Inout_ int32_t* indices_data); - - /** \brief Returns sparse tensor format enum iff a given ort value contains an instance of sparse tensor. - * - * \param[in] ort_value ::OrtValue that contains an instance of sparse tensor - * \param[out] out pointer to out parameter - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorFormat, _In_ const OrtValue* ort_value, _Out_ enum OrtSparseFormat* out); - - /** \brief Returns data type and shape of sparse tensor values (nnz) iff ::OrtValue contains a SparseTensor. - * - * \param[in] ort_value An ::OrtValue that contains a fully constructed sparse tensor - * \param[out] out Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorValuesTypeAndShape, _In_ const OrtValue* ort_value, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Returns numeric data for sparse tensor values (nnz). For string values use GetStringTensor*(). - * - * \param[in] ort_value an instance of ::OrtValue containing sparse tensor - * \param[out] out returns a pointer to values data. Do not attempt to free this ptr. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorValues, _In_ const OrtValue* ort_value, _Outptr_ const void** out); - - /** \brief Returns data type, shape for the type of indices specified by indices_format. - * - * \param[in] ort_value ::OrtValue containing sparse tensor. - * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse - * tensor does not contain. - * \param[out] out an instance of ::OrtTensorTypeAndShapeInfo. Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorIndicesTypeShape, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Outptr_ OrtTensorTypeAndShapeInfo** out); - - /** \brief Returns indices data for the type of the indices specified by indices_format - * - * \param[in] ort_value ::OrtValue containing sparse tensor. - * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse tensor does not contain. - * \param[out] num_indices Pointer to where the number of indices entries is returned - * \param[out] indices Returned pointer to the indices data. Do not free the returned pointer as it refers to internal data owned by the ::OrtValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetSparseTensorIndices, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Out_ size_t* num_indices, _Outptr_ const void** indices); - /// @} - /// \name OrtSessionOptions - /// @{ - - /** - * \brief Sets out to 1 iff an optional type OrtValue has an element, 0 otherwise (OrtValue is None) - * Use this API to find if the optional type OrtValue is None or not. - * If the optional type OrtValue is not None, use the OrtValue just like any other OrtValue. - * For example, if you get an OrtValue that corresponds to Optional(tensor) and - * if HasValue() returns true, use it as tensor and so on. - - * \param[in] value Input OrtValue. - * \param[out] out indicating if the input OrtValue contains data (1) or if it is a None (0) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(HasValue, _In_ const OrtValue* value, _Out_ int* out); - - /// @} - /// \name OrtKernelContext - /// Custom operator APIs. - /// @{ - - /** \brief Used for custom operators, gets the GPU compute stream to use to launch the custom a GPU kernel - * \see ::OrtCustomOp - * \param[in] context OrtKernelContext instance - * \param[out] out Returns pointer to a GPU compute stream that can be used to launch the custom GPU kernel. - * If retrieving the GPU compute stream is not relevant (GPU not enabled in the build, kernel partitioned to - * some other EP), then a nullptr is returned as the output param. - * Do not free or mutate the returned pointer as it refers to internal data owned by the underlying session. - * Only use it for custom kernel launching. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context, _Outptr_ void** out); - - /// @} - /// \name GetTensorMemoryInfo - /// @{ - /** \brief Returns a pointer to the ::OrtMemoryInfo of a Tensor - * \param[in] value ::OrtValue containing tensor. - * \param[out] mem_info ::OrtMemoryInfo of the tensor. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetTensorMemoryInfo, _In_ const OrtValue* value, _Out_ const OrtMemoryInfo** mem_info); - - /// @} - /// \name GetExecutionProviderApi - /// @{ - /** \brief Get a pointer to the requested version of the Execution Provider specific - * API extensions to the OrtApi - * \param[in] provider_name The name of the execution provider name. Currently only the following - * values are supported: "DML". - * \param[in] version Must be ::ORT_API_VERSION. - * \param[out] provider_api A void pointer containing a reference to the execution provider versioned api structure. - * For example, the provider_api pointer can be cast to the OrtDmlApi* when the provider_name is "DML". - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetExecutionProviderApi, _In_ const char* provider_name, _In_ uint32_t version, _Outptr_ const void** provider_api); - - /// @} - - /// \name SessionOptions - /// @{ - /** \brief Set custom thread creation function - * - * \param[in] options Session options - * \param[in] ort_custom_create_thread_fn Custom thread creation function - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsSetCustomCreateThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); - - /** \brief Set creation options for custom thread - * - * \param[in] options Session options - * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsSetCustomThreadCreationOptions, _Inout_ OrtSessionOptions* options, _In_ void* ort_custom_thread_creation_options); - - /** \brief Set custom thread join function - * - * \param[in] options Session options - * \param[in] ort_custom_join_thread_fn Custom join thread function, must not be nullptr when ort_custom_create_thread_fn is set - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SessionOptionsSetCustomJoinThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); - /// @} - - /// \name OrtThreadingOptions - /// @{ - /** \brief Set custom thread creation function for global thread pools - * - * \param[inout] tp_options - * \param[in] ort_custom_create_thread_fn Custom thread creation function - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalCustomCreateThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); - - /** \brief Set custom thread creation options for global thread pools - * - * \param[inout] tp_options - * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalCustomThreadCreationOptions, _Inout_ OrtThreadingOptions* tp_options, _In_ void* ort_custom_thread_creation_options); - - /** \brief Set custom thread join function for global thread pools - * - * \param[inout] tp_options - * \param[in] ort_custom_join_thread_fn Custom thread join function, must not be nullptr when global ort_custom_create_thread_fn is set - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SetGlobalCustomJoinThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); - /// @} - - /** \brief Synchronize bound inputs. The call may be necessary for some providers, such as cuda, - * in case the system that allocated bound memory operated on a different stream. However, the - * operation is provider specific and could be a no-op. - * - * \param[inout] binding_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SynchronizeBoundInputs, _Inout_ OrtIoBinding* binding_ptr); - - /** \brief Synchronize bound outputs. The call may be necessary for some providers, such as cuda, - * in case the system that allocated bound memory operated on a different stream. However, the - * operation is provider specific and could be a no-op. - * - * \param[inout] binding_ptr - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(SynchronizeBoundOutputs, _Inout_ OrtIoBinding* binding_ptr); - - /// \name OrtSessionOptions - /// @{ - - /** \brief Append CUDA execution provider to the session options - * - * If CUDA is not available (due to a non CUDA enabled build), this function will return failure. - * - * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_CUDA, it takes an - * ::OrtCUDAProviderOptions which is publicly defined. This takes an opaque ::OrtCUDAProviderOptionsV2 - * which must be created with OrtApi::CreateCUDAProviderOptions. - * - * For OrtApi::SessionOptionsAppendExecutionProvider_CUDA, the user needs to instantiate ::OrtCUDAProviderOptions - * as well as allocate/release buffers for some members of ::OrtCUDAProviderOptions. - * Here, OrtApi::CreateCUDAProviderOptions and Ortapi::ReleaseCUDAProviderOptions will do the memory management for you. - * - * \param[in] options - * \param[in] cuda_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA_V2, - _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptionsV2* cuda_options); - - /// @} - /// \name OrtCUDAProviderOptionsV2 - /// @{ - - /** \brief Create an OrtCUDAProviderOptionsV2 - * - * \param[out] out Newly created ::OrtCUDAProviderOptionsV2. Must be released with OrtApi::ReleaseCudaProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(CreateCUDAProviderOptions, _Outptr_ OrtCUDAProviderOptionsV2** out); - - /** \brief Set options in a CUDA Execution Provider. - * - * Please refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#configuration-options - * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtCUDAProviderOptionsV2 - * and value should be its related range. Recreates the options and only sets the supplied values. - * - * For example, key="device_id" and value="0" - * - * \param[in] cuda_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(UpdateCUDAProviderOptions, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** - * Get serialized CUDA provider options string. - * - * For example, "device_id=0;arena_extend_strategy=0;......" - * - * \param cuda_options - OrtCUDAProviderOptionsV2 instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(GetCUDAProviderOptionsAsString, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtCUDAProviderOptionsV2 - * - * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does - * - * \since Version 1.11. - */ - void(ORT_API_CALL* ReleaseCUDAProviderOptions)(_Frees_ptr_opt_ OrtCUDAProviderOptionsV2* input); - - /// @} - - /** \brief Append MIGraphX provider to session options - * - * If MIGraphX is not available (due to a non MIGraphX enabled build, or if MIGraphX is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] migraphx_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.11. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_MIGraphX, - _In_ OrtSessionOptions* options, _In_ const OrtMIGraphXProviderOptions* migraphx_options); - - /** \brief Replace initialized Tensors with external data with the data provided in initializers. - * - * The function will find the initialized TensorProtos with external data in the graph with the provided names and - * replace them with the provided tensors. The API verifies that the TensorProto being replaced - * has an external data reference and has the same name, dimensions and data type as its replacement. The replacement - * will occur before any of the optimizations take place. The data will be copied into the graph - * since TensorProto can't refer to the user provided buffers. - * - * Once the model has been loaded, the OrtValue(s) added to SessionOptions instance will be removed - * from the internal SessionOptions copy to save memory, the user provided buffers can then be deallocated - * and the SessionOptions instance that refers to them can be destroyed. - * - * \param[in] options - * \param[in] initializer_names Array of null terminated UTF-8 encoded strings of the initializers names. - * \param[in] initializers Array of ::OrtValue type - * \param[in] num_initializers Number of elements in the initializer_names and initializers - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.12. - */ - ORT_API2_STATUS(AddExternalInitializers, _In_ OrtSessionOptions* options, - _In_reads_(num_initializers) const char* const* initializer_names, - _In_reads_(num_initializers) const OrtValue* const* initializers, size_t num_initializers); - - /** \brief: Create attribute of onnxruntime operator - * - * \param[in] name Name of the attribute - * \param[in] data Data content of the attribute - * \param[in] len Number of bytes stored in data - * \param[in] type Data type - * \param[out] op_attr Attribute that has been created, which must be released by OrtApi::ReleaseOpAttr - * - * \since Version 1.12. - */ - ORT_API2_STATUS(CreateOpAttr, - _In_ const char* name, - _In_ const void* data, - _In_ int len, - _In_ OrtOpAttrType type, - _Outptr_ OrtOpAttr** op_attr); - - /* \brief: Release op attribute - * - * \param[in] opAttr Attribute created by OrtApi::CreateOpAttr - * - * \since Version 1.12. - */ - ORT_CLASS_RELEASE(OpAttr); - - /** \brief: Create onnxruntime native operator - * - * \param[in] info Kernel info - * \param[in] op_name Operator name - * \param[in] domain Operator domain - * \param[in] version Operator opset version - * \param[in] type_constraint_names Name of the type contraints, such as "T" or "T1" - * \param[in] type_constraint_values Type of each contraints - * \param[in] type_constraint_count Number of contraints - * \param[in] attr_values Attributes used to initialize the operator - * \param[in] attr_count Number of the attributes - * \param[in] input_count Number of inputs - * \param[in] output_count Number of outputs - * \param[out] ort_op Operator that has been created - * - * \since Version 1.12. - */ - ORT_API2_STATUS(CreateOp, - _In_ const OrtKernelInfo* info, - _In_z_ const char* op_name, - _In_z_ const char* domain, - int version, - _In_reads_(type_constraint_count) const char** type_constraint_names, - _In_reads_(type_constraint_count) const ONNXTensorElementDataType* type_constraint_values, - int type_constraint_count, - _In_reads_(attr_count) const OrtOpAttr* const* attr_values, - int attr_count, - int input_count, - int output_count, - _Outptr_ OrtOp** ort_op); - - /** \brief: Invoke the operator created by OrtApi::CreateOp - * The inputs must follow the order as specified in onnx specification - * - * \param[in] context Kernel context - * \param[in] ort_op Operator that has been created - * \param[in] input_values Array of inputs - * \param[in] input_count Number of inputs - * \param[in] output_values Array of outputs - * \param[in] output_count Number of outputs - * - * \since Version 1.12. - */ - ORT_API2_STATUS(InvokeOp, - _In_ const OrtKernelContext* context, - _In_ const OrtOp* ort_op, - _In_ const OrtValue* const* input_values, - _In_ int input_count, - _Inout_ OrtValue* const* output_values, - _In_ int output_count); - - /* \brief: Release an onnxruntime operator - * - * \param[in] Op Operator created by OrtApi::CreateOp - * - * \since Version 1.12. - */ - ORT_CLASS_RELEASE(Op); - - /** \brief: Append execution provider to the session options. - * \param[in] options - * \param[in] provider_name - provider to add. - * \param[in] provider_options_keys - keys to configure the provider options - * \param[in] provider_options_values - values to configure the provider options - * \param[in] num_keys - number of keys passed in - * - * Currently supported provider names: - * QNNExecutionProvider (or QNN) - * OpenVINOExecutionProvider (or OpenVINO) - * XnnpackExecutionProvider (or XNNPACK) - * WebNNExecutionProvider (or WEBNN) - * WebGpuExecutionProvider (or WebGPU) - * AzureExecutionProvider (or AZURE) - * JsExecutionProvider (or JS) - * VitisAIExecutionProvider (or VitisAI) - * CoreMLExecutionProvider (or CoreML) - * - * Note: If an execution provider has a dedicated SessionOptionsAppendExecutionProvider_ function - * that should be used to add it. - * - * QNN supported keys: - * "backend_type": Type of QNN backend. Specifies a backend path that is the associated QNN backend library file - * name. E.g., given backend type "htp", on Windows, the backend path would be "QnnHtp.dll", and on other - * platforms, it would be "libQnnHtp.so". Mutually exclusive with "backend_path". - * Available options: - * -# "cpu" - * -# "gpu" - * -# "htp": Default. - * -# "saver" - * "backend_path": File path to QNN backend library. Mutually exclusive with "backend_type". - * "profiling_level": QNN profiling level. - * Available options: - * -# "off": Default. - * -# "basic" - * -# "detailed" - * "profiling_file_path": QNN profiling file path if ETW not enabled. - * "rpc_control_latency": QNN RPC control latency. - * "vtcm_mb": QNN VTCM size in MB. default to 0(not set). - * "htp_performance_mode": QNN performance mode. - * Available options: - * -# "burst" - * -# "balanced" - * -# "default": Default. - * -# "high_performance" - * -# "high_power_saver" - * -# "low_balanced" - * -# "extreme_power_saver" - * -# "low_power_saver" - * -# "power_saver" - * -# "sustained_high_performance" - * "qnn_saver_path": File path to the QNN Saver backend library. If specified, QNN Saver will be enabled and will - * dump QNN API calls to disk for replay/debugging. QNN Saver produces incorrect model inference results and - * may alter model/EP partitioning. Use only for debugging. - * "qnn_context_priority": QNN context priority. - * Available options: - * -# "low" - * -# "normal": Default. - * -# "normal_high" - * -# "high" - * "htp_graph_finalization_optimization_mode": Set the optimization mode for graph finalization on the HTP backend. - * Available options: - * -# "0": Default. - * -# "1": Faster preparation time, less optimal graph. - * -# "2": Longer preparation time, more optimal graph. - * -# "3": Longest preparation time, most likely even more optimal graph. See QNN SDK documentation for specific - * details. - * "soc_model": The SoC model number. Refer to the QNN SDK documentation for valid values. - * Defaults to "0" (unknown). - * "htp_arch": The minimum HTP architecture the driver will use to select compatible QNN operators. - * Available options: - * -# "0": Default (none). - * -# "68" - * -# "69" - * -# "73" - * -# "75" - * "device_id": The ID of the device to use when setting 'htp_arch'. Defaults to "0" (for single device). - * "enable_htp_fp16_precision": Used for float32 model for HTP backend. - * Enable the float32 model to be inferenced with fp16 precision. Otherwise, it will be fp32 precision. - * -# "0": With fp32 precision. - * -# "1": Default. With fp16 precision. - * "offload_graph_io_quantization": Offload graph input quantization and graph output dequantization to another - * execution provider (typically CPU EP). - * -# "0": Disabled. QNN EP will handle quantization and dequantization of graph I/O. - * -# "1": Enabled. This is the default value. - * "enable_htp_spill_fill_buffer": Enable HTP spill fill buffer setting. The flag is used while generating context - * binary. - * -# "0": Default. Disabled. - * -# "1": Enabled. - * "enable_htp_shared_memory_allocator": Enable the QNN HTP shared memory allocator. Requires libcdsprpc.so/dll to - * be available. - * -# "0": Default. Disabled. - * -# "1": Enabled. - * "dump_json_qnn_graph": Set to "1" to dump QNN graphs generated by QNN EP as JSON files. Each graph partition - * assigned to QNN EP is dumped to a separate file. - * "json_qnn_graph_dir": Directory in which to dump QNN JSON graphs. If not specified, QNN graphs are dumped in the - * program's current working directory. Ignored if "dump_json_qnn_graph" is not set. - * - * XNNPACK supported keys: - * "intra_op_num_threads": number of thread-pool size to use for XNNPACK execution provider. - * default value is 0, which means to use the session thread-pool size. - * - * \since Version 1.12. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider, _In_ OrtSessionOptions* options, - _In_ const char* provider_name, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /* \brief: Get a copy of kernel info - * - * \param[in] info Kernel info - * \param[out] info_copy Copy of kernel info - * - * \since Version 1.12. - */ - ORT_API2_STATUS(CopyKernelInfo, - _In_ const OrtKernelInfo* info, - _Outptr_ OrtKernelInfo** info_copy); - - /* \brief: Release kernel info - * - * \param[in] KernelInfo A copy of kernel info returned by CopyKernelInfo - * - * \since Version 1.12. - */ - ORT_CLASS_RELEASE(KernelInfo); - - /// \name Ort Training - /// @{ - /** \brief Gets the Training C Api struct - * - * Call this function to access the ::OrtTrainingApi structure that holds pointers to functions that enable - * training with onnxruntime. - * \note A NULL pointer will be returned and no error message will be printed if the training api - * is not supported with this build. A NULL pointer will be returned and an error message will be - * printed if the provided version is unsupported, for example when using a runtime older than the - * version created with this header file. - * - * \param[in] version Must be ::ORT_API_VERSION - * \return The ::OrtTrainingApi struct for the version requested. - * - * \since Version 1.13 - */ - const OrtTrainingApi*(ORT_API_CALL* GetTrainingApi)(uint32_t version)NO_EXCEPTION; - - /// @} - - /** \brief Append CANN provider to session options - * - * If CANN is not available (due to a non CANN enabled build, or if CANN is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] cann_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CANN, - _In_ OrtSessionOptions* options, _In_ const OrtCANNProviderOptions* cann_options); - - /** \brief Create an OrtCANNProviderOptions - * - * \param[out] out created ::OrtCANNProviderOptions. Must be released with OrtApi::ReleaseCANNProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(CreateCANNProviderOptions, _Outptr_ OrtCANNProviderOptions** out); - - /** \brief Set options in a CANN Execution Provider. - * - * \param[in] cann_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(UpdateCANNProviderOptions, _Inout_ OrtCANNProviderOptions* cann_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Get serialized CANN provider options string. - * - * \param[in] cann_options OrtCANNProviderOptions instance - * \param[in] allocator a ptr to an instance of OrtAllocator obtained with CreateAllocator() - * or GetAllocatorWithDefaultOptions(), the specified allocator will be used to allocate - * continuous buffers for output strings and lengths. - * \param[out] ptr is a UTF-8 null terminated string allocated using 'allocator'. - * The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.13. - */ - ORT_API2_STATUS(GetCANNProviderOptionsAsString, _In_ const OrtCANNProviderOptions* cann_options, - _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an OrtCANNProviderOptions - * - * \param[in] input The pointer of OrtCANNProviderOptions which will been deleted - * - * \since Version 1.13. - */ - void(ORT_API_CALL* ReleaseCANNProviderOptions)(_Frees_ptr_opt_ OrtCANNProviderOptions* input); - - /* \brief Get OrtDevice type from MemoryInfo - * - * \since Version 1.14 - */ - void(ORT_API_CALL* MemoryInfoGetDeviceType)(_In_ const OrtMemoryInfo* ptr, _Out_ OrtMemoryInfoDeviceType* out); - - /* \brief Update the OrtEnv instance with custom log severity level - * - * \param[in] ort_env The OrtEnv instance being used - * \param[in] log_severity_level The log severity level. - * - * \since Version 1.14. - */ - ORT_API2_STATUS(UpdateEnvWithCustomLogLevel, _In_ OrtEnv* ort_env, OrtLoggingLevel log_severity_level); - - /* \brief Set affinities for intra op threads - * - * Affinity string follows format: - * logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id - * Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. - * e.g. 1,2,3;4,5 - * specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. - * To ease the configuration, an "interval" is also allowed: - * e.g. 1-8;8-16;17-24 - * orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. - * Note: - * 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, - * ort does not set affinity on the main thread which is started and managed by the calling app; - * 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, - * an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. - * Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. - * - * \since Version 1.14 - */ - ORT_API2_STATUS(SetGlobalIntraOpThreadAffinity, _Inout_ OrtThreadingOptions* tp_options, const char* affinity_string); - - /** \brief Register custom ops from a shared library. - * - * Loads a shared library (.dll on windows, .so on linux, etc) named 'library_name' and looks for this entry point: - * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); - * It then passes in the provided session options to this function along with the api base. - * - * The handle to the loaded library is automatically released by ORT when the last OrtSession that references the - * library handle is released. If no OrtSession is created, then the library handle is released when the provided - * OrtSessionOptions is released. - * - * \param[in] options The session options. - * \param[in] library_name The name of the shared library to load and register. Refer to OS-specific dynamic library - * loading utilities (e.g., LoadLibraryEx on Windows or dlopen on Linux/MacOS) for information - * on the format of library names and search paths. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(RegisterCustomOpsLibrary_V2, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* library_name); - - /** \brief Register custom ops by calling a RegisterCustomOpsFn function. - * - * Searches for registration_func_name and if found calls it. - * - * The library containing the function must either be linked against or previously loaded by the executable. - * - * If you want ONNX Runtime to load the library and manage its lifetime, use RegisterCustomOpsLibrary_V2. - * - * RegisterCustomOpsUsingFunction can be used in scenarios where it may not be possible for ONNX Runtime to load - * the library from a path. e.g. mobile platforms where the library must be linked into the app. - * - * The registration function must have the signature of RegisterCustomOpsFn: - * OrtStatus* (*fn)(OrtSessionOptions* options, const OrtApiBase* api); - * - * See https://onnxruntime.ai/docs/reference/operators/add-custom-op.html for details on how the registration - * function should be implemented. - * - * \param[in] options OrtSessionOptions that is passed through as the first argument in the call to the - * registration function. - * \param[in] registration_func_name Name of registration function to use. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(RegisterCustomOpsUsingFunction, _Inout_ OrtSessionOptions* options, - _In_ const char* registration_func_name); - - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Get the number of inputs from ::OrtKernelInfo. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the number of inputs - * during kernel/session creation. - * - * \param[in] info Instance of ::OrtKernelInfo. - * \param[out] out Pointer to variable assigned with the result on success. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); - - /** \brief Get the number of outputs from ::OrtKernelInfo. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the number of outputs - * during kernel/session creation. - * - * \param[in] info Instance of ::OrtKernelInfo. - * \param[out] out Pointer to variable assigned with the result on success. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); - - /** \brief Get the name of a ::OrtKernelInfo's input. - * - * Used in the CreateKernel callback of an OrtCustomOp to query an input's name - * during kernel/session creation. - * - * If `out` is nullptr, the value of `size` is set to the size of the name - * string (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the name string's size, - * the value of `size` is set to the true size of the string (including null-terminator), - * the provided memory is filled with the string's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string - * and a failure status is returned. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index The index of the input name to get. Returns a failure status if out-of-bounds. - * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the input's name. - * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, - _Inout_ size_t* size); - - /** \brief Get the name of a ::OrtKernelInfo's output. - * - * Used in the CreateKernel callback of an OrtCustomOp to query an output's name - * during kernel/session creation. - * - * If `out` is nullptr, the value of `size` is set to the size of the name - * string (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the name string's size, - * the value of `size` is set to the true size of the string (including null-terminator), - * the provided memory is filled with the string's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string - * and a failure status is returned. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index The index of the output name to get. Returns a failure status if out-of-bounds. - * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the output's - * name. - * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, - _Inout_ size_t* size); - - /** \brief Get the type information for a ::OrtKernelInfo's input. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information - * of an input during kernel/session creation. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index Which input to get the type information for - * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get the type information for a ::OrtKernelInfo's output. - * - * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information - * of an output during kernel/session creation. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[in] index Which input to get the type information for - * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Get a ::OrtValue tensor stored as an attribute in the graph node. - * - * Used in the CreateKernel callback of an OrtCustomOp to get a tensor attribute. - * - * \param[in] info ::OrtKernelInfo instance. - * \param[in] name UTF-8 null-terminated string representing the attribute's name. - * \param[in] allocator Allocator used to allocate the internal tensor state. - * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue, - * which will also free internal tensor state allocated with the provided allocator. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name, - _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out); - - /// @} - /// \name OrtSessionOptions - /// Custom operator APIs - /// @{ - - /** \brief Checks if the given session configuration entry exists. - * - * The config_key formats are defined in onnxruntime_session_options_config_keys.h - * - * Can be used in a custom operator library to check for session configuration entries - * that target one or more custom operators in the library. Example: The config entry - * custom_op.myop.some_key targets a custom op named "myop". - * - * \param[in] options The ::OrtSessionOptions instance. - * \param[in] config_key A null-terminated UTF-8 string representation of the configuration key. - * \param[out] out Pointer set to 1 if the entry exists and 0 otherwise. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(HasSessionConfigEntry, _In_ const OrtSessionOptions* options, - _In_z_ const char* config_key, _Out_ int* out); - - /** \brief Get a session configuration value. - * - * Returns a failure status if the configuration key does not exist. - * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h - * - * If `config_value` is nullptr, the value of `size` is set to the true size of the string - * value (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the actual string value's size, - * the value of `size` is set to the true size of the string value, the provided memory - * is filled with the value's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string value's size and `config_value` - * is not nullptr, the value of `size` is set to the true size of the string value - * and a failure status is returned. - * - * Can be used in a custom operator library to get session configuration entries - * that target one or more custom operators in the library. Example: The config entry - * custom_op.myop.some_key targets a custom op named "myop". - * - * \param[in] options The session options. - * \param[in] config_key A null-terminated UTF-8 string representation of the config key. - * \param[in] config_value Pointer to memory where the null-terminated UTF-8 string value will be stored. - * \param[in,out] size Pointer to the size of the `config_value` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.14 - */ - ORT_API2_STATUS(GetSessionConfigEntry, _In_ const OrtSessionOptions* options, - _In_z_ const char* config_key, _Out_ char* config_value, _Inout_ size_t* size); - - /// @} - - /** \brief Append dnnl provider to session options - * - * If oneDNN is not available, this function will return failure. - * - * \param[in] options - * \param[in] dnnl_options - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_Dnnl, - _In_ OrtSessionOptions* options, _In_ const OrtDnnlProviderOptions* dnnl_options); - - /** \brief Create an OrtDnnlProviderOptions - * - * \param[out] out Newly created ::OrtDnnlProviderOptions. Must be released with OrtApi::ReleaseDnnlProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(CreateDnnlProviderOptions, _Outptr_ OrtDnnlProviderOptions** out); - - /** \brief Set options in a oneDNN Execution Provider. - * - * Key should be in null terminated string format of the member of ::OrtDnnlProviderOptions - * and value should be its related range. - * - * For example, key="use_arena" and value="1" - * - * \param[in] dnnl_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(UpdateDnnlProviderOptions, _Inout_ OrtDnnlProviderOptions* dnnl_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** - * Get serialized oneDNN provider options string. - * - * For example, "use_arena=1;......" - * - * \param dnnl_options - OrtDnnlProviderOptions instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(GetDnnlProviderOptionsAsString, _In_ const OrtDnnlProviderOptions* dnnl_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtDnnlProviderOptions - * - * \since Version 1.15. - */ - void(ORT_API_CALL* ReleaseDnnlProviderOptions)(_Frees_ptr_opt_ OrtDnnlProviderOptions* input); - - /// \name OrtKernelInfo - /// Custom operator APIs. - /// @{ - - /** \brief Get the graph node name from ::OrtKernelInfo. - * - * If `out` is nullptr, the value of `size` is set to the size of the name - * string (including null-terminator), and a success status is returned. - * - * If the `size` parameter is greater than or equal to the name string's size, - * the value of `size` is set to the true size of the string (including null-terminator), - * the provided memory is filled with the string's contents, and a success status is returned. - * - * If the `size` parameter is less than the actual string's size and `out` - * is not nullptr, the value of `size` is set to the true size of the string - * and a failure status is returned. - * - * Can be used in a custom operator's CreateKernel callback to get the name of the operator's node name in the graph. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the name. - * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_ char* out, _Inout_ size_t* size); - - /** \brief Get the session logger from ::OrtKernelInfo. - * - * Used in the CreateKernel callback of an OrtCustomOp to get a logger that can be used to log - * messages. - * - * \param[in] info An instance of ::OrtKernelInfo. - * \param[out] logger Pointer set to the session's ::OrtLogger. Owned by ONNX Runtime, so do not free. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger); - - /// @} - /// \name OrtKernelContext - /// Custom operator APIs. - /// @{ - - /** \brief Get the runtime logger from ::OrtKernelContext. - * - * Used in the KernelCompute callback of an OrtCustomOp to get a logger that can be used to log - * messages during inference. - * - * \param[in] context An instance of ::OrtKernelContext. - * \param[out] logger Pointer set to the kernel context's ::OrtLogger. Owned by ONNX Runtime, so do not free. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(KernelContext_GetLogger, _In_ const OrtKernelContext* context, _Outptr_ const OrtLogger** logger); - - /// @} - /// \name OrtLogger - /// Custom operator APIs. - /// @{ - - /** \brief Logs a message at the given severity level using the provided ::OrtLogger. - * - * Only messages with a severity level equal or greater than the ::OrtLogger's logging severity level - * are logged. Use OrtApi::Logger_GetLoggingSeverityLevel to get the ::OrtLogger's logging severity - * level. - * - * Can be used in custom operators to log messages with the logger retrieved via OrtApi::KernelInfo_GetLogger. - * - * \param[in] logger The ::OrtLogger instance. - * \param[in] log_severity_level The message's severity level. - * \param[in] message The message to log. - * \param[in] file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. - * \param[in] line_number The file line number in which the message is logged. Usually the value of __LINE__. - * \param[in] func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level, - _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number, - _In_z_ const char* func_name); - - /** \brief Get the logging severity level of the ::OrtLogger. - * - * Can be used in a custom operator to get the logging serverity level of the ::OrtLogger associated with - * the ::OrtKernelInfo. - * - * \param[in] logger The ::OrtLogger instance. - * \param[out] out Pointer to variable assigned with the logging severity level on success. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.15 - */ - ORT_API2_STATUS(Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger, _Out_ OrtLoggingLevel* out); - - /// @} - - /** \brief Get a ::OrtValue tensor stored as a constant initializer in the graph node. - * - * Used in the CreateKernel callback of an OrtCustomOp to get a tensor value. - * - * \param[in] info ::OrtKernelInfo instance. - * \param[in] index The node index. - * \param[out] is_constant Is it a constant node input or not. - * \param[out] out The OrtValue tensor value. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, size_t index, _Out_ int* is_constant, _Outptr_ const OrtValue** out); - - /** \brief Get Optional Type information from an ::OrtTypeInfo - * - * This augments ::OrtTypeInfo to return an ::OrtOptionalTypeInfo when the type is optional. - * The OrtOptionalTypeInfo also has a nested ::OrtTypeInfo that describes the type of the optional value. - * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. - * The actual OrtValues that are supplied in place of optional type inputs should contain - * specific type that is described by ::OrtOptionalTypeInfo. - * - * So the picture: ::OrtTypeInfo -> ::OrtOptionalTypeInfo -> ::OrtTypeInfo (describes the type that can be supplied - * in place of the optional type when creating the actual ::OrtValue). - * - * \param[in] type_info - * \param[out] out A pointer to the ::OrtOptionalTypeInfo. Do not free this value, - * it is owned by OrtTypeInfo instance. When the type_info does not represent - * optional type, nullptr is returned in out. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(CastTypeInfoToOptionalTypeInfo, _In_ const OrtTypeInfo* type_info, - _Outptr_result_maybenull_ const OrtOptionalTypeInfo** out); - - /** \brief Get OrtTypeInfo for the allowed contained type from an ::OrtOptionalTypeInfo. - * - * This augments ::OrtOptionalTypeInfo to return an ::OrtTypeInfo for the contained type. - * The OrtOptionalTypeInfo has a nested ::OrtTypeInfo that describes the type of the optional value. - * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. - * The actual OrtValues that are supplied in place of optional type inputs should contain - * specific type that is described by the returned ::OrtTypeInfo. - * - * \param[in] optional_type_info - * \param[out] out A copy of ::OrtTypeInfo for what the optional value could be. - * The user must free this value with ReleaseTypeInfo. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(GetOptionalContainedTypeInfo, _In_ const OrtOptionalTypeInfo* optional_type_info, - _Outptr_ OrtTypeInfo** out); - - /** \brief Set a single string in a string tensor - * Do not zero terminate the string data. - * - * \param[in] value A string tensor - * \param[in] index - flat index of the element - * \param[in] length_in_bytes length of the buffer in utf-8 bytes (without the null terminator) - * \param[inout] buffer - address of return value - * - * \snippet{doc} snippets.dox OrtStatus Return Value - */ - ORT_API2_STATUS(GetResizedStringTensorElementBuffer, _Inout_ OrtValue* value, _In_ size_t index, _In_ size_t length_in_bytes, _Inout_ char** buffer); - - /** \brief Get Allocator from KernelContext for a specific memoryInfo. Please use C API ReleaseAllocator to release out object - * - * \param[in] context OrtKernelContext instance - * \param[in] mem_info OrtMemoryInfo instance - * \param[out] out A pointer to OrtAllocator. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.15. - */ - ORT_API2_STATUS(KernelContext_GetAllocator, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out); - - /** \brief Returns a null terminated string of the build info including git info and cxx flags - * - * \return UTF-8 encoded version string. Do not deallocate the returned buffer. - * - * \since Version 1.15. - */ - const char*(ORT_API_CALL* GetBuildInfoString)(void); - - /// \name OrtROCMProviderOptions - /// @{ - - /** \brief Create an OrtROCMProviderOptions - * - * \param[out] out Newly created ::OrtROCMProviderOptions. Must be released with OrtApi::ReleaseROCMProviderOptions - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.16. - */ - ORT_API2_STATUS(CreateROCMProviderOptions, _Outptr_ OrtROCMProviderOptions** out); - - /** \brief Set options in a ROCm Execution Provider. - * - * Please refer to https://onnxruntime.ai/docs/execution-providers/ROCm-ExecutionProvider.html - * to know the available keys and values. Key should be in null terminated string format of the member of - * ::OrtROCMProviderOptions and value should be its related range. - * - * For example, key="device_id" and value="0" - * - * \param[in] rocm_options - * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys - * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values - * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.16. - */ - ORT_API2_STATUS(UpdateROCMProviderOptions, _Inout_ OrtROCMProviderOptions* rocm_options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** - * Get serialized ROCm provider options string. - * - * For example, "device_id=0;arena_extend_strategy=0;......" - * - * \param rocm_options - OrtROCMProviderOptions instance - * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() - * the specified allocator will be used to allocate continuous buffers for output strings and lengths. - * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.16. - */ - ORT_API2_STATUS(GetROCMProviderOptionsAsString, _In_ const OrtROCMProviderOptions* rocm_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); - - /** \brief Release an ::OrtROCMProviderOptions - * - * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does - * - * \since Version 1.16. - */ - void(ORT_API_CALL* ReleaseROCMProviderOptions)(_Frees_ptr_opt_ OrtROCMProviderOptions* input); - - /** \brief Create an allocator with specific type and register it with the ::OrtEnv - * This API enhance CreateAndRegisterAllocator that it can create an allocator with specific type, not just CPU allocator - * Enables sharing the allocator between multiple sessions that use the same env instance. - * Lifetime of the created allocator will be valid for the duration of the environment. - * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. - * \param[in] env OrtEnv instance - * \param[in] provider_type ExecutionProvider type - * \param[in] mem_info OrtMemoryInfo instance - * \param[in] arena_cfg Arena configuration - * \param[in] provider_options_keys key of the provider options map - * \param[in] provider_options_values value of the provider options map - * \param[in] num_keys Length of the provider options map - */ - ORT_API2_STATUS(CreateAndRegisterAllocatorV2, _Inout_ OrtEnv* env, _In_ const char* provider_type, _In_ const OrtMemoryInfo* mem_info, _In_ const OrtArenaCfg* arena_cfg, - _In_reads_(num_keys) const char* const* provider_options_keys, _In_reads_(num_keys) const char* const* provider_options_values, _In_ size_t num_keys); - - /** \brief Run the model asynchronously in a thread owned by intra op thread pool - * - * \param[in] session - * \param[in] run_options If nullptr, will use a default ::OrtRunOptions - * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names - * \param[in] input Array of ::OrtValue%s of the input values - * \param[in] input_len Number of elements in the input_names and inputs arrays - * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names - * \param[in] output_names_len Number of elements in the output_names and outputs array - * \param[out] output OrtValue* array of size output_names_len. - * On calling RunAsync, output[i] could either be a null or a pointer to a preallocated OrtValue. - * Later, the output array will be passed to run_async_callback with all null(s) filled with valid - * OrtValue pointer(s) allocated by onnxruntime. - * NOTE: it is customer's duty to finally release the output array and each of its member, - * regardless of whether the member (OrtValue*) is allocated by onnxruntime or preallocated by the customer. - * \param[in] run_async_callback Callback function on model run completion - * \param[in] user_data User data that pass back to run_async_callback - */ - ORT_API2_STATUS(RunAsync, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, - _In_reads_(input_len) const char* const* input_names, - _In_reads_(input_len) const OrtValue* const* input, size_t input_len, - _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, - _Inout_updates_all_(output_names_len) OrtValue** output, - _In_ RunAsyncCallbackFn run_async_callback, _In_opt_ void* user_data); - - /** - * Update TensorRT EP provider option where its data type is pointer, for example 'user_compute_stream'. - * If the data type of the provider option can be represented by string please use UpdateTensorRTProviderOptions. - * - * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. - * - * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance - * \param key - Name of the provider option - * \param value - A pointer to the instance that will be assigned to this provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(UpdateTensorRTProviderOptionsWithValue, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _In_ void* value); - - /** - * Get TensorRT EP provider option where its data type is pointer. - * If the data type of the provider option can be represented by string please use GetTensorRTProviderOptionsAsString. - * - * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance - * \param key - Name of the provider option - * \param ptr - A pointer to the instance that is kept by the provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(GetTensorRTProviderOptionsByName, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _Outptr_ void** ptr); - - /** - * Update CUDA EP provider option where its data type is pointer, for example 'user_compute_stream'. - * If the data type of the provider option can be represented by string please use UpdateCUDAProviderOptions. - * - * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. - * - * \param cuda_options - OrtCUDAProviderOptionsV2 instance - * \param key - Name of the provider option - * \param value - A pointer to the instance that will be assigned to this provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(UpdateCUDAProviderOptionsWithValue, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _In_ void* value); - - /** - * Get CUDA EP provider option where its data type is pointer. - * If the data type of the provider option can be represented by string please use GetCUDAProviderOptionsAsString. - * - * \param cuda_options - OrtCUDAProviderOptionsV2 instance - * \param key - Name of the provider option - * \param ptr - A pointer to the instance that is kept by the provider option - * - * \since Version 1.16. - */ - ORT_API2_STATUS(GetCUDAProviderOptionsByName, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _Outptr_ void** ptr); - - /** - * Get a EP resource. - * E.g. a cuda stream or a cublas handle - * - * \param context - Kernel context - * \param resource_version - Version of the resource - * \param resource_id - Type of resource - * \param resource - A pointer to returned resource - * - * \since Version 1.16. - */ - ORT_API2_STATUS(KernelContext_GetResource, _In_ const OrtKernelContext* context, _In_ int resource_version, - _In_ int resource_id, _Outptr_ void** resource); - - /** \brief Set user logging function - * - * By default the logger created by the CreateEnv* functions is used to create the session logger as well. - * This function allows a user to override this default session logger with a logger of their own choosing. This way - * the user doesn't have to create a separate environment with a custom logger. This addresses the problem when - * the user already created an env but now wants to use a different logger for a specific session (for debugging or - * other reasons). - * - * \param[in] options - * \param[in] user_logging_function A pointer to a logging function. - * \param[in] user_logging_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to - * `user_logging_function`. This parameter is optional. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SetUserLoggingFunction, _Inout_ OrtSessionOptions* options, - _In_ OrtLoggingFunction user_logging_function, _In_opt_ void* user_logging_param); - - /** - * Get number of input from OrtShapeInferContext - * - * \param[in] context - * \param[out] out The number of inputs - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_GetInputCount, _In_ const OrtShapeInferContext* context, _Out_ size_t* out); - - /** - * Get type and shape info of an input - * - * \param[in] context - * \param[in] index The index of the input - * \param[out] info Type shape info of the input - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_GetInputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _Outptr_ OrtTensorTypeAndShapeInfo** info); - - /** - * Get attribute from OrtShapeInferContext. Note that OrtShapeInferContext is a per-node context, one could only read attribute from current node. - * - * \param[in] context - * \param[in] attr_name Name of the attribute - * \param[out] attr Handle of the attribute fetched - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_GetAttribute, _In_ const OrtShapeInferContext* context, _In_ const char* attr_name, _Outptr_ const OrtOpAttr** attr); - - /** - * Set type and shape info of an output - * - * \param[in] context - * \param[in] index The index of the output - * \param[out] info Type shape info of the output - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ShapeInferContext_SetOutputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _In_ const OrtTensorTypeAndShapeInfo* info); - - /** - * Set symbolic shape to type shape info - * - * \param[in] info Type shape info - * \param[in] dim_params Symbolic strings - * \param[in] dim_params_length Number of strings - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SetSymbolicDimensions, _In_ OrtTensorTypeAndShapeInfo* info, _In_ const char* dim_params[], _In_ size_t dim_params_length); - - /** - * Read contents of an attribute to data - * - * \param[in] op_attr - * \param[in] type Attribute type - * \param[out] data Memory address to save raw content of the attribute - * \param[in] len Number of bytes allowed to store in data - * \param[out] out Number of bytes required to save the data when the call failed, or the real number of bytes saved to data on success - * - * \since Version 1.17. - */ - ORT_API2_STATUS(ReadOpAttr, _In_ const OrtOpAttr* op_attr, _In_ OrtOpAttrType type, _Inout_ void* data, _In_ size_t len, _Out_ size_t* out); - - /** \brief Set whether to use deterministic compute. - * - * Default is false. If set to true, this will enable deterministic compute for GPU kernels where possible. - * Note that this most likely will have a performance cost. - * - * \param[in] options - * \param[in] value - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SetDeterministicCompute, _Inout_ OrtSessionOptions* options, bool value); - - /** - * Run fn in parallel - * - * \param[in] context - * \param[in] fn Function accepting usr_data and an integer as iterator - * \param[in] total The number of times fn is to be invoked - * \param[in] num_batch Number of batches by which the "total" is to be divided in maximum. When zero, there is no limit - * \param[in] usr_data User data to be passed back to fn - * - * \since Version 1.17. - */ - ORT_API2_STATUS(KernelContext_ParallelFor, _In_ const OrtKernelContext* context, _In_ void (*fn)(void*, size_t), _In_ size_t total, _In_ size_t num_batch, _In_ void* usr_data); - - /** \brief Append OpenVINO execution provider to the session options - * - * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. - * - * \param[in] options - * \param[in] provider_options_keys - * \param[in] provider_options_values - * \param[in] num_keys - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.17. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO_V2, - _In_ OrtSessionOptions* options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Append VitisAI provider to session options - * - * If VitisAI is not available (due to a non VitisAI enabled build, or if VitisAI is not installed on the system), this function will return failure. - * - * \param[in] options - * \param[in] provider_options_keys - * \param[in] provider_options_values - * \param[in] num_keys - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_VitisAI, - _In_ OrtSessionOptions* options, - _In_reads_(num_keys) const char* const* provider_options_keys, - _In_reads_(num_keys) const char* const* provider_options_values, - _In_ size_t num_keys); - - /** \brief Get scratch buffer from the corresponding allocator under the sepcific OrtMemoryInfo object. - * NOTE: callers are responsible to release this scratch buffer from the corresponding allocator - * \param[in] context OrtKernelContext instance - * \param[in] mem_info OrtMemoryInfo instance - * \param[in] count_or_bytes How many bytes is this scratch buffer - * \param[out] out A pointer to the scrach buffer - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(KernelContext_GetScratchBuffer, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _In_ size_t count_or_bytes, _Outptr_ void** out); - - /** \brief Get allocator from KernelInfo for a specific memory type. Please use C API ReleaseAllocator to release out object - * - * \param[in] info OrtKernelInfo instance - * \param[in] mem_type OrtMemType object - * \param[out] out A pointer to OrtAllocator - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(KernelInfoGetAllocator, _In_ const OrtKernelInfo* info, _In_ OrtMemType mem_type, _Outptr_ OrtAllocator** out); - - /** \brief Replace initialized Tensors with external data with the provided files in memory - * - * The function will find the initialized TensorProtos with external data in the graph with the provided - * external file names and the file content in memory. The API gets the external file name, offset, data length - * from TensorProto, and locate the tensor data from the file in memory buffer. - * It creates a Tensor to replace the existing Tensor in graph. The replacement - * will occur before any of the optimizations take place. The data will be copied into the graph - * since TensorProto can't refer to the user provided buffers. - * - * \param[in] options - * \param[in] external_initializer_file_names Array of null terminated UTF-8 encoded strings of the file names - * which holds the external initializers. - * \param[in] external_initializer_file_buffer_array Array of pointers to the buffer of the file content. - * The buffer can be freed after session creation. - * \param[in] external_initializer_file_lengths Array of size_t to indicate the length of file content - * \param[in] num_external_initializer_files Number of external files - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.18. - */ - ORT_API2_STATUS(AddExternalInitializersFromFilesInMemory, _In_ OrtSessionOptions* options, - _In_reads_(num_external_initializer_files) const ORTCHAR_T* const* external_initializer_file_names, - _In_reads_(num_external_initializer_files) char* const* external_initializer_file_buffer_array, - _In_reads_(num_external_initializer_files) const size_t* external_initializer_file_lengths, - size_t num_external_initializer_files); - - /** \brief Create an OrtLoraAdapter - * - * The function attempts to locate file specified by adapter_file_path, read it and create an OrtLoraAdapter - * instance. The adapter_file_path should be a valid path to a file that contains a valid Lora Adapter - * format. The function attempts to validate the format at load time. The file will always be memory mapped, unless - * the platform does not support memory mapping, in which case the file will be read into memory. - * - * \param[in] adapter_file_path adapter file path. - * \param[in] allocator optional pointer to a device allocator. If specified - * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. - * The data would still be copied to device if required by the model at inference time. - * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with - * OrtApi::ReleaseLoraAdapter. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(CreateLoraAdapter, const ORTCHAR_T* adapter_file_path, _In_ OrtAllocator* allocator, - _Outptr_ OrtLoraAdapter** out); - - /** \brief Create an OrtLoraAdapter - * - * The function copies the bytes from the array and creates an OrtLoraAdapter instance. - * - * - * \param[in] bytes pointer to a valid Lora Adapter format buffer. - * \param[in] num_bytes length of bytes buffer. - * \param[in] allocator optional pointer to a device allocator. If specified - * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. - * The data would still be copied to device if required by the model at inference time. - * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with - * OrtApi::ReleaseLoraAdapter. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(CreateLoraAdapterFromArray, _In_ const void* bytes, size_t num_bytes, _In_ OrtAllocator* allocator, - _Outptr_ OrtLoraAdapter** out); - - /** \brief Release an ::OrtLoraAdapter obtained from OrtApi::CreateLoraAdapter - */ - ORT_CLASS_RELEASE(LoraAdapter); - - /** \brief Add the Lora Adapter to the list of active adapters. - * - * The function adds the Lora Adapter to the list of active adapters. The Lora Adapter must be created with - * OrtApi::CreateLoraAdapter or FromArray. The Lora Adapter will be used by the session to run the model. - * The instance of the OrtRunOptions can then be used to customize the Run() calls. - * More than one OrtLoraAdapter can be active at the same time. Lora Parameters that belong to different - * Lora adapters that will be active at the same time must not overlap. - * This setting does not affect RunWithBinding. - * - * \param[in] options OrtRunOptions instance - * \param[in] adapter OrtLoraAdapter instance - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(RunOptionsAddActiveLoraAdapter, _Inout_ OrtRunOptions* options, _In_ const OrtLoraAdapter* adapter); - - /// @} - /// \name OrtEpDynamicOptions - /// @{ - - /** \brief Set DynamicOptions for EPs (Execution Providers) - * - * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` - * Look for `kOrtEpDynamicOptions` - * - * \param[in] sess OrtSession - * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys - * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values - * \param[in] kv_len Number of elements in the keys and values arrays - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.20. - */ - ORT_API2_STATUS(SetEpDynamicOptions, _Inout_ OrtSession* sess, _In_reads_(kv_len) const char* const* keys, - _In_reads_(kv_len) const char* const* values, _In_ size_t kv_len); - - /** \brief Release an OrtValueInfo instance if it was not added to an OrtGraph. - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(ValueInfo); - - /** \brief Release an OrtNode if it was not added to an OrtGraph. - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(Node); - - /** \brief Release an OrtGraph. - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(Graph); - - /** \brief Release an OrtModel. - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(Model); - - /** \brief Get the value name from an OrtValueInfo instance. - * \param[in] value_info The OrtValueInfo instance. - * \param[out] name The name of the OrtValueInfo - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_API2_STATUS(GetValueInfoName, _In_ const OrtValueInfo* value_info, _Out_ const char** name); - - /** \brief Get the type information from an OrtValueInfo instance. - * \param[in] value_info The OrtValueInfo instance. - * \param[out] type_info The type info of the OrtValueInfo - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_API2_STATUS(GetValueInfoTypeInfo, _In_ const OrtValueInfo* value_info, _Outptr_ const OrtTypeInfo** type_info); - - /** \brief Get the Model Editor API instance - * - * Get the Model Editor API instance to create a new model or augment an existing model. - * - * \return Model Editor API struct - * - * \since Version 1.22. - */ - const OrtModelEditorApi*(ORT_API_CALL* GetModelEditorApi)(); - - /** \brief Create an OrtValue for a Tensor that uses pre-existing memory. - * - * ORT will take ownership of the memory and free it using the provided deleter when no longer in use. - * - * \param[in] deleter OrtAllocator instance that will be used to free the memory. - * Only the OrtAllocator:Info and OrtAllocator::Release functions are required. - * The OrtMemoryInfo returned by OrtAllocator::Info must match the location of p_data. - * \param[in] p_data Pointer to the memory that will be used by the Tensor. ORT will take ownership of the memory. - * \param[in] p_data_len Length of the memory in bytes. - * \param[in] shape Dimensions of the Tensor. All values should be > 0. - * \param[in] shape_len Number of dimensions in the shape array. - * \param[in] type Data type of the Tensor. - * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateTensorWithDataAndDeleterAsOrtValue, _In_ OrtAllocator* deleter, - _In_ void* p_data, size_t p_data_len, - _In_ const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type, - _Outptr_ OrtValue** out); - - /** \brief sets load cancellation flag to abort session loading process. - * - * \param[in] options instance that was passed to the session at creation time. - * \param[in] cancel setting this to true after model loading process was initiated will - * attempt to cancel the loading process. If cancellation is successful, CreateSession() - * CreateSessionFromArray() or any other session creation API that take session options as an - * argument will return an OrtStatus indicating that session loading was canceled at user request, - * error code ORT_MODEL_LOAD_CANCELED. - * The APIs above would not return any valid Session instance. This is the best case effort and the result - * is not guaranteed. The session may have already been created and initialized - * before the cancellation request was issued. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SessionOptionsSetLoadCancellationFlag, _Inout_ OrtSessionOptions* options, - _In_ bool cancel); - - /** \brief Get the Compile API instance. - * - * Get the Compile API instance to compile ONNX models. Execution providers that support compilation fuse a subgraph - * into an EPContext node that wraps a provider-specific binary representation of the subgraph. - * For more details about the EPContext design, refer to: - * \htmlonly - * EPContext design document. - * \endhtmlonly - * - * \return Compile API struct instance. - * - * \since Version 1.22. - */ - const OrtCompileApi*(ORT_API_CALL* GetCompileApi)(); - - // - // OrtKeyValuePairs - // - - /** \brief Create an OrtKeyValuePairs instance. - * - * \param[out] out A pointer to a newly created OrtKeyValuePairs instance. - * - * \note Must be released by calling ReleaseKeyValuePairs. - * - * \since Version 1.22. - */ - void(ORT_API_CALL* CreateKeyValuePairs)(_Outptr_ OrtKeyValuePairs** out); - - /** \brief Add a key-value pair to the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[in] key Key to be added. - * \param[in] value Value to be added. - * - * \note The `key` and `value` are copied internally. - * - * \since Version 1.22. - */ - - void(ORT_API_CALL* AddKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key, _In_ const char* value); - - /** \brief Get the value associated with a key in the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[in] key Key to be searched. - * - * \return The value associated with the key, or nullptr if the key does not exist. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetKeyValue)(_In_ const OrtKeyValuePairs* kvps, _In_ const char* key); - - /** \brief Get all the key-value pairs from the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[out] keys Array of keys from `kvps`. - * \param[out] values Array of values from `kvps`. - * \param[out] num_entries Number of entries in `keys` and `values`. - * - * \since Version 1.22. - */ - void(ORT_API_CALL* GetKeyValuePairs)(_In_ const OrtKeyValuePairs* kvps, - _Outptr_ const char* const** keys, _Outptr_ const char* const** values, - _Out_ size_t* num_entries); - - /** \brief Remove a key-value pair from the OrtKeyValuePairs instance. - * - * \param[in] kvps OrtKeyValuePairs instance. - * \param[in] key Key to be removed. No error if not found. - * - * \since Version 1.22. - */ - void(ORT_API_CALL* RemoveKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key); - - /** \brief Release an OrtKeyValuePairs instance. - * - * \param[in] input OrtKeyValuePairs instance to be released. - * - * \since Version 1.22. - */ - ORT_CLASS_RELEASE(KeyValuePairs); - - /** \brief Register an execution provider library with ORT. - * - * The library must export 'CreateEpFactories' and 'ReleaseEpFactory' functions. - * See OrtEpApi for more details. - * - * \param[in] env The OrtEnv instance to register the library in. - * \param[in] registration_name The name to register the execution provider library under. - * \param[in] path The path to the execution provider library. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(RegisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name, - _In_ const ORTCHAR_T* path); - - /** \brief Unregister an execution provider library with ORT. - * - * ORT will call ReleaseEpFactory for all factories created by the library, and unload the library. - * - * You MUST ensure there are no Session instances using execution providers created by the library - * before calling this function. - * - * \param[in] env The OrtEnv instance to unregister the library from. - * \param[in] registration_name The name the execution provider library was registered under. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(UnregisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name); - - /** \brief Get the list of available OrtEpDevice instances. - * - * Each OrtEpDevice instance contains details of the execution provider and the device it will use. - * - * \param[in] env The OrtEnv instance to query. - * \param[out] ep_devices The OrtEpDevice instances that the execution provider will use. - * \param[out] num_ep_devices The number of OrtEpDevice instances returned. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(GetEpDevices, _In_ const OrtEnv* env, - _Outptr_ const OrtEpDevice* const** ep_devices, _Out_ size_t* num_ep_devices); - - /** \brief Append the execution provider that is responsible for the selected OrtEpDevice instances - * to the session options. - * - * \param[in] session_options Session options to add execution provider to. - * \param[in] env Environment that execution providers were registered with. - * \param[in] ep_devices One or more OrtEpDevice instances to create an execution provider for. - * Obtain from GetEpDevices. All OrtEpDevice instances must be from the same execution - * provider. It is only necessary to provide multiple OrtEpDevices if you want to use the - * same execution provider for multiple devices. - * e.g. the EP is capable of running on GPU and NPU. - * \param[in] num_ep_devices Number of OrtEpDevice instances. - * \param[in] ep_option_keys Optional keys to configure the execution provider. - * \param[in] ep_option_vals Optional values to configure the execution provider. - * \param[in] num_ep_options Number of execution provide options to add. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_V2, _In_ OrtSessionOptions* session_options, - _In_ OrtEnv* env, - _In_reads_(num_ep_devices) const OrtEpDevice* const* ep_devices, _In_ size_t num_ep_devices, - _In_reads_(num_op_options) const char* const* ep_option_keys, - _In_reads_(num_op_options) const char* const* ep_option_vals, - size_t num_ep_options); - - /** \brief Set the execution provider selection policy for the session. - * - * Allows users to specify a device selection policy for automatic execution provider (EP) selection. - * If custom selection is required please use SessionOptionsSetEpSelectionPolicyDelegate instead. - * - * \param[in] session_options The OrtSessionOptions instance. - * \param[in] policy The device selection policy to use (see OrtExecutionProviderDevicePolicy). - * - * \since Version 1.22 - */ - ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicy, _In_ OrtSessionOptions* session_options, - _In_ OrtExecutionProviderDevicePolicy policy); - - /** \brief Set the execution provider selection policy delegate for the session. - * - * Allows users to provide a custom device selection policy for automatic execution provider (EP) selection. - * - * \param[in] session_options The OrtSessionOptions instance. - * \param[in] delegate Delegate callback for custom selection. - * \param[in] delegate_state Optional state that will be passed to the delegate callback. nullptr if not required. - * - * \since Version 1.22 - */ - ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicyDelegate, _In_ OrtSessionOptions* session_options, - _In_ EpSelectionDelegate delegate, - _In_opt_ void* delegate_state); - - /** \brief Get the hardware device type. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The hardware device type. - * - * \since Version 1.22. - */ - OrtHardwareDeviceType(ORT_API_CALL* HardwareDevice_Type)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the hardware device's vendor identifier. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The hardware device vendor identifier. - * - * \since Version 1.22. - */ - uint32_t(ORT_API_CALL* HardwareDevice_VendorId)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the hardware device's vendor name. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The hardware device's vendor name. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* HardwareDevice_Vendor)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the hardware device's unique identifier. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return The device id. - * - * \note This is not a unique identifier. It identifies the hardware type when combined with vendor id. - * \since Version 1.22. - */ - uint32_t(ORT_API_CALL* HardwareDevice_DeviceId)(_In_ const OrtHardwareDevice* device); - - /** \brief Get hardware device metadata. - * - * \param[in] device The OrtHardwareDevice instance to query. - * \return An OrtKeyValuePairs instance containing the metadata for the device. - * Note: ORT owns the instance so the user must not call ReleaseKeyValuePairs with it. - * - * \since Version 1.22. - */ - const OrtKeyValuePairs*(ORT_API_CALL* HardwareDevice_Metadata)(_In_ const OrtHardwareDevice* device); - - /** \brief Get the execution provider name. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return The execution provider name. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* EpDevice_EpName)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the execution provider's vendor name. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return The execution provider's vendor name. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* EpDevice_EpVendor)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the metadata for the OrtEpDevice. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return An OrtKeyValuePairs instance containing the metadata for the device. - * - * \since Version 1.22. - */ - const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpMetadata)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the execution provider options for the OrtEpDevice. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return An OrtKeyValuePairs instance containing the execution provider options for the device. - * - * \since Version 1.22. - */ - const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpOptions)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the OrtHardwareDevice instance for the OrtEpDevice. - * - * \param[in] ep_device The OrtEpDevice instance to query. - * \return The OrtHardwareDevice instance for the device. - * - * \since Version 1.22. - */ - const OrtHardwareDevice*(ORT_API_CALL* EpDevice_Device)(_In_ const OrtEpDevice* ep_device); - - /** \brief Get the OrtEpApi instance for implementing an execution provider. - * - * \since Version 1.22. - */ - const OrtEpApi*(ORT_API_CALL* GetEpApi)(); -}; - -/* - * Steps to use a custom op: - * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops - * 2 Create an OrtCustomOp structure for each op and add them to the domain - * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options - */ - -// Specifies some characteristics of inputs/outputs of custom ops: -// Specify if the inputs/outputs are one of: -// 1) Non-optional (input/output must be present in the node) -// 2) Optional (input/output may be absent in the node) -// 3) Variadic: A variadic input or output specifies N (i.e., the minimum arity) or more operands. -// Only the last input or output of a custom op may be marked as variadic. -// The homogeneity of the variadic input or output determines whether all operands must be of the same -// tensor element type. -typedef enum OrtCustomOpInputOutputCharacteristic { - INPUT_OUTPUT_REQUIRED = 0, - INPUT_OUTPUT_OPTIONAL, - INPUT_OUTPUT_VARIADIC, -} OrtCustomOpInputOutputCharacteristic; - -/* - * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by - * the implementor of the custom op. - */ -struct OrtCustomOp { - uint32_t version; // Must be initialized to ORT_API_VERSION - - // This callback creates the kernel, which is a user defined - // parameter that is passed to the Kernel* callbacks below. It is - // recommended to use CreateKernelV2 which allows for a safe error - // propagation by returning an OrtStatusPtr. - void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, - _In_ const OrtKernelInfo* info); - - // Returns the name of the op - const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op); - - // Returns the type of the execution provider, return nullptr to use CPU execution provider - const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op); - - // Returns the count and types of the input & output tensors - ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op); - ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op); - - // Perform a computation step. It is recommended to use - // KernelComputeV2 which allows for a safe error propagation by - // returning an OrtStatusPtr. - void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context); - void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel); - - // Returns the characteristics of the input & output tensors - OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetInputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetOutputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - - // Returns the memory type of the input tensors. This API allows the custom op - // to place the inputs on specific devices. By default, it returns - // OrtMemTypeDefault, which means the input is placed on the default device for - // the execution provider. If the inputs need to be with different memory tyeps, - // this function can be overridden to return the specific memory types. - OrtMemType(ORT_API_CALL* GetInputMemoryType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); - - // Returns the minimum number of input arguments expected for the variadic input. - // Applicable only for custom ops that have a variadic input. - int(ORT_API_CALL* GetVariadicInputMinArity)(_In_ const struct OrtCustomOp* op); - - // Returns true (non-zero) if all arguments of a variadic input have to be of the same type (homogeneous), - // and false (zero) otherwise. - // Applicable only for custom ops that have a variadic input. - int(ORT_API_CALL* GetVariadicInputHomogeneity)(_In_ const struct OrtCustomOp* op); - - // Returns the minimum number of output values expected for the variadic output. - // Applicable only for custom ops that have a variadic output. - int(ORT_API_CALL* GetVariadicOutputMinArity)(_In_ const struct OrtCustomOp* op); - - // Returns true (non-zero) if all outputs values of a variadic output have to be of the same type (homogeneous), - // and false (zero) otherwise. - // Applicable only for custom ops that have a variadic output. - int(ORT_API_CALL* GetVariadicOutputHomogeneity)(_In_ const struct OrtCustomOp* op); - - // Create the kernel state which is passed to each compute call. - OrtStatusPtr(ORT_API_CALL* CreateKernelV2)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, - _In_ const OrtKernelInfo* info, - _Out_ void** kernel); - - // Perform the computation step. - OrtStatusPtr(ORT_API_CALL* KernelComputeV2)(_In_ void* op_kernel, _In_ OrtKernelContext* context); - - OrtStatusPtr(ORT_API_CALL* InferOutputShapeFn)(_In_ const struct OrtCustomOp* op, _In_ OrtShapeInferContext*); - - // Get start range - int(ORT_API_CALL* GetStartVersion)(_In_ const struct OrtCustomOp* op); - int(ORT_API_CALL* GetEndVersion)(_In_ const struct OrtCustomOp* op); - - // Get the inplace_map that defines which output can reuse which input - // Callers will provide 2 raw int* and pass in their address, this function will fill these 2 arrays - // when return, output (*output_index)[i] may reuse the input (*input_index[i]). - // The return value is the size of these 2 arrays. - // Callers are responsible to delete these 2 arrays after use by calling OrtCustomOp::ReleaseMayInplace(). - size_t(ORT_API_CALL* GetMayInplace)(_Out_ int** input_index, _Out_ int** output_index); - - // Release the pointer input_index and output_index allocated from GetMayInplace() function. - // If GetMayInplace() is defined, this function MUST be defined as well. - void(ORT_API_CALL* ReleaseMayInplace)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); - - // Same as GetMayInplace() and ReleaseMayInplace() - size_t(ORT_API_CALL* GetAliasMap)(_Out_ int** input_index, _Out_ int** output_index); - void(ORT_API_CALL* ReleaseAliasMap)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); -}; - -/** - * ORT Model Editor API - */ - -/** - * \brief The OrtModelEditorApi struct provides functions to create or edit an ONNX model. - * - * See onnxruntime/test/shared_lib/test_model_editor_api.cc for example usage. - * - * \since Version 1.22. - */ -struct OrtModelEditorApi { - // Model building/editing requires a full build. We return nullptr from GetModelEditorApi if this is a minimal - // build, so it doesn't matter if there are no function pointers in this struct as a user will never get an - // OrtModelEditorApi instance. We do however need a dummy field to avoid empty struct warning. -#if defined(ORT_MINIMAL_BUILD) - const bool not_defined_in_this_build; -#else - /** \brief Create an OrtTypeInfo instance for a Tensor. - * - * Create an OrtTypeInfo instance for a Tensor to use as graph inputs/outputs with the Model Editor API. - * - * User can release `tensor_info` after creating the OrtTypeInfo. - * - * \param[in] tensor_info Tensor type and shape information. - * \param[out] type_info TypeInfo instance for the tensor. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for a SparseTensor. - * - * Create an OrtTypeInfo instance for a SparseTensor to use as graph inputs/outputs with the Model Editor API. - * - * User can release `tensor_info` after creating the OrtTypeInfo. - * - * \param[in] tensor_info SparseTensor type and shape information. - * \param[out] type_info TypeInfo instance for the tensor. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateSparseTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for a Map. - * - * Create an OrtTypeInfo instance for a Map to use as graph inputs/outputs with the Model Editor API. - * - * User can release `map_value_type` after creating the OrtTypeInfo. - * - * \param[in] map_key_type Key type for the map. - * \param[in] map_value_type Value type for the map. - * \param[out] type_info TypeInfo instance for the map. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateMapTypeInfo, ONNXTensorElementDataType map_key_type, _In_ const OrtTypeInfo* map_value_type, - _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for a Sequence. - * - * Create an OrtTypeInfo instance for a Sequence to use as graph inputs/outputs with the Model Editor API. - * - * User can release `sequence_type` after creating the OrtTypeInfo. - * - * \param[in] sequence_type Sequence type and shape information. - * \param[out] type_info TypeInfo instance for the sequence. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateSequenceTypeInfo, _In_ const OrtTypeInfo* sequence_type, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtTypeInfo instance for an Optional. - * - * Create an OrtTypeInfo instance for an Optional to use as graph inputs/outputs with the Model Editor API. - * - * User can release `contained_type` after creating the OrtTypeInfo. - * - * \param[in] contained_type Tensor type and shape information. - * \param[out] type_info TypeInfo instance for the tensor. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateOptionalTypeInfo, _In_ const OrtTypeInfo* contained_type, _Outptr_ OrtTypeInfo** type_info); - - /** \brief Create an OrtValueInfo for use as an OrtGraph input or output. - * - * \param[in] name The name of the input or output. - * \param[in] type_info The type information for the input or output. The provided value is copied. - * \param[out] value_info The OrtValueInfo instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateValueInfo, _In_ const char* name, _In_ const OrtTypeInfo* type_info, - _Outptr_ OrtValueInfo** value_info); - - /** \brief Create an OrtNode to add to an OrtGraph. - * - * Create an OrtNode. - * - * Create attributes with CreateOpAttr. OrtOpAttr instances are copied. - * - * \param[in] operator_name The name of the operator. - * \param[in] domain_name The domain of the operator. Use an empty string for ONNX operators. - * \param[in] node_name The name of the node. - * \param[in] input_names The names of the inputs. - * \param[in] input_names_len The number of input names. - * \param[in] output_names The names of the outputs. - * \param[in] output_names_len The number of output names. - * \param[in] attributes The optional attributes of the node. - * \param[in] attribs_len The number of attributes. May be zero. - * \param[out] node The OrtNode instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateNode, _In_ const char* operator_name, _In_ const char* domain_name, _In_ const char* node_name, - _In_reads_(input_names_len) const char* const* input_names, size_t input_names_len, - _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, - _In_reads_(attribs_len) _In_opt_ OrtOpAttr** attributes, _In_ size_t attribs_len, - _Outptr_ OrtNode** node); - - /** \brief Create an OrtGraph - * \snippet{doc} snippets.dox OrtStatus Return Value - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateGraph, _Outptr_ OrtGraph** graph); - - /** \brief Set the inputs for the OrtGraph. - * - * Set the graph inputs. This will replace any existing inputs with the new values. - * The OrtGraph takes ownership of the OrtValueInfo instances and you should NOT call ReleaseOrtValueInfo. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] inputs The input OrtValueInfo instances. - * \param[in] inputs_len The number of input OrtValueInfo instances. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SetGraphInputs, _Inout_ OrtGraph* graph, - _In_reads_(inputs_len) _In_ OrtValueInfo** inputs, _In_ size_t inputs_len); - - /** \brief Set the outputs for the OrtGraph. - * - * Set the graph outputs. This will replace any existing outputs with the new values. - * The OrtGraph takes ownership of the OrtValueInfo instances provided and you should NOT call ReleaseOrtValueInfo. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] outputs The output OrtValueInfo instances. - * \param[in] outputs_len The number of output OrtValueInfo instances. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SetGraphOutputs, _Inout_ OrtGraph* graph, - _In_reads_(outputs_len) _In_ OrtValueInfo** outputs, _In_ size_t outputs_len); - - /** \brief Add an initializer to the OrtGraph - * - * ORT will take ownership of the OrtValue and you should NOT call ReleaseOrtValue. - * - * Two options: - * - * Allocated memory: - * Use CreateTensorAsOrtValue (allocates memory) and populate the tensor with the data. - * Set `data_is_external` to false. - * - * Pre-existing memory: - * Use CreateTensorWithDataAsOrtValue or CreateTensorWithDataAndDeleterAsOrtValue to create an OrtValue - * with a tensor that contains a pointer to the existing data. - * Set `data_is_external` to true. - * - * The pointer must remain valid for the duration of the inference session. - * If using CreateTensorWithDataAsOrtValue you are responsible for freeing the memory after the inference session - * is released. - * If using CreateTensorWithDataAndDeleterAsOrtValue, ORT will free the memory using the provided deleter as - * soon as the OrtValue is no longer in use. - * - * NOTE: A tensor containing pre-existing memory MUST have 128 bytes of data or more. - * For smaller tensors use CreateTensorAsOrtValue. - * - * ONNX shape inferencing does not support external data. An initializer involved in shape inferencing is - * typically small (a single value or limited by the rank of a tensor) and uses less than 128 bytes of - * memory, so this limit acts as a simple catch-all rule to avoid issues. - * e.g. Reshape's `shape`, Clip's `min` and `max`, various ops `axes`. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] name The value name for the initializer. - * \param[in] tensor The OrtValue instance containing the tensor data. - * \param[in] data_is_external Set to true if the data is external and should not be copied. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(AddInitializerToGraph, _Inout_ OrtGraph* graph, _In_ const char* name, _In_ OrtValue* tensor, - bool data_is_external); - - /** \brief Add an OrtNode to an OrtGraph - * - * Add the node to the graph. The OrtGraph will take ownership of OrtNode and you should NOT call ReleaseOrtNode. - * - * \param[in] graph The OrtGraph instance to update. - * \param[in] node The OrtNode instance to add to the graph. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(AddNodeToGraph, _Inout_ OrtGraph* graph, _In_ OrtNode* node); - - /** \brief Create an OrtModel. - * - * Create an OrtModel. - * - * This can be used to build a new model, or to augment an existing model. - * - * \param[in] domain_names The domain names for the model. - * If augmenting an existing model add additional domains if needed. - * \param[in] opset_versions The opset versions for the model. - * If augmenting an existing model add additional opset versions if needed. - * \param[in] opset_entries_len The number of domain_names and opset_versions entries. - * Domain and opset entries should be 1:1 - * \param[out] model The OrtModel instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModel, - _In_reads_(opset_entries_len) const char* const* domain_names, - _In_reads_(opset_entries_len) const int* opset_versions, - size_t opset_entries_len, - _Outptr_ OrtModel** model); - - /** \brief Add an OrtGraph to an OrtModel. - * - * Add the graph to a model. This should be called once when creating a new model. - * - * The OrtModel takes ownership of the OrtGraph and you should NOT call ReleaseOrtGraph. - * - * \param[in] model The OrtModel instance to update. - * \param[in] graph The OrtGraph instance to add to the model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(AddGraphToModel, _Inout_ OrtModel* model, _In_ OrtGraph* graph); - - /** \brief Create an OrtSession using the OrtModel. - * - * Create an inference session using the OrtModel instance. - * The OrtModel should have been populated with an OrtGraph containing nodes and initializers, and SetGraphInputs - * and SetGraphOutputs must have been called. - * This will validate the model, run optimizers, and prepare the session for inferencing. - * - * ReleaseOrtModel must be called to free the OrtModel after session creation. - * - * \param[in] env The OrtEnv instance. - * \param[in] model The OrtModel instance. - * \param[in] options The OrtSessionOptions instance. - * \param[out] out The OrtSession instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateSessionFromModel, _In_ const OrtEnv* env, _In_ const OrtModel* model, - _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); - - /** \brief Create an OrtSession to augment an existing model. - * - * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. - * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the - * model is finalized. - * - * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. - * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. - * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made - * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. - * - * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the - * session for inferencing by calling FinalizeModelEditorSession. - * - * \param{in} env The OrtEnv instance. - * \param{in} model_path The path to the existing ONNX model to augment. - * \param{in} options The OrtSessionOptions instance. - * \param{out} out The created OrtSession instance. - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModelEditorSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, - _In_ const OrtSessionOptions* options, - _Outptr_ OrtSession** out); - - /** \brief Create an OrtSession to augment an existing model. - * - * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. - * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the - * model is finalized. - * - * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. - * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. - * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made - * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. - * - * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the - * session for inferencing by calling FinalizeModelEditorSession. - * - * \param{in} env The OrtEnv instance. - * \param{in} model_data The model data for the existing model to augment. - * \param{in} model_data_length The length of the model data. - * \param{in} options The OrtSessionOptions instance. - * \param{out} out The created OrtSession instance. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModelEditorSessionFromArray, _In_ const OrtEnv* env, - _In_ const void* model_data, size_t model_data_length, - _In_ const OrtSessionOptions* options, - _Outptr_ OrtSession** out); - - /** \brief Query the session for the opset version of a domain. - * - * When using the Model Editor API to augment a model, any new nodes must conform to the opset version of the - * original model. To do that the user must be able to discover that opset version. - * Returns an error if the domain is not used in the model. - * - * \param[in] session OrtSession to query - * \param[in] domain Domain to query. The ONNX domain is an empty string. - * \param[out] opset The opset version of the domain. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(SessionGetOpsetForDomain, _In_ const OrtSession* session, _In_ const char* domain, _Out_ int* opset); - - /** \brief Apply changes to augment the ONNX model in a session created using CreateModelEditorSession[FromArray] - * - * Adds new nodes and updates graph inputs/outputs using `model` to augment the original ONNX model in the session. - * All changes will be validated. - * Call FinalizeModelEditorSession to prepare the session for inferencing. - * - * Existing input/outputs will only be updated if the OrtGraph inputs/outputs are set in the OrtModel. - * i.e. you don't need to call SetGraphInputs/SetGraphOutputs if they are unchanged. - * - * ReleaseOrtModel must be called to free the OrtModel after it is applied to the session. - * - * \param[in] session OrtSession to update. Session must have been created using CreateModelEditorSession[FromArray]. - * \param[in] model OrtModel containing new nodes, new initializers, and updated graph input and/or output info. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ApplyModelToModelEditorSession, _Inout_ OrtSession* session, _In_ OrtModel* model); - - /** \brief Finalize the Model Editor session that was created using CreateModelEditorSession[FromArray]. - * - * Finalize the Model Editor session that augmented an ONNX model by adding new nodes. - * This will run optimizers and prepare the session for inferencing. - * - * \param[in] session OrtSession to finalize. Session must have been created using CreateModelEditorSession[FromArray]. - * \param[in] options OrtSessionOptions to use for the session. - * \param[in] prepacked_weights_container Optional OrtPrepackedWeightsContainer to use for the session. - Set to nullptr if not used. - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(FinalizeModelEditorSession, _Inout_ OrtSession* session, _In_ const OrtSessionOptions* options, - _In_opt_ OrtPrepackedWeightsContainer* prepacked_weights_container); -#endif // !defined(ORT_MINIMAL_BUILD) -}; - -/** - * ORT Compile API - */ - -/** - * \brief The OrtCompileApi struct provides functions to compile ONNX models. - * - * Execution providers that support compilation fuse a subgraph into an EPContext node that wraps a provider-specific - * binary representation of the subgraph. - * For more details about the EPContext design, refer to: - * \htmlonly - * EPContext design document. - * \endhtmlonly - * - * Example (error handling not shown): - * OrtStatus* status = NULL; - * OrtCompileApi* compile_api = ort_api->GetCompileApi(); - * OrtModelCompilationOptions* compile_options = NULL; - * - * status = compile_api->CreateModelCompilationOptionsFromSessionOptions(env, session_options, &compile_options); - * status = compile_api->ModelCompilationOptions_SetInputModelPath(compile_options, ORT_TSTR("model.onnx")); - * status = compile_api->ModelCompilationOptions_SetOutputModelPath(compile_options, ORT_TSTR("model.compiled.onnx")); - * status = compile_api->CompileModel(env, compile_options); - * compile_api->ReleaseModelCompilationOptions(compile_options); - * - * \since Version 1.22. - */ -struct OrtCompileApi { - /// @} - /// \name OrtModelCompilationOptions - /// @{ - ORT_CLASS_RELEASE(ModelCompilationOptions); - - /** \brief Creates an OrtModelCompilationOptions object from an existing OrtSessionOptions object. - * - * An OrtModelCompilationOptions object contains the settings used to generate a compiled ONNX model. - * The OrtSessionOptions object has the execution providers with which the model will be compiled. - * - * ReleaseOrtModelCompilationsOptions must be called to free the OrtModelCompilationOptions after calling - * CompileModel. - * - * \param[in] env OrtEnv object. - * \param[in] session_options The OrtSessionOptions instance from which to create the OrtModelCompilationOptions. - * \param[out] out The created OrtModelCompilationOptions instance. - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateModelCompilationOptionsFromSessionOptions, _In_ const OrtEnv* env, - _In_ const OrtSessionOptions* session_options, _Outptr_ OrtModelCompilationOptions** out); - - /** \brief Sets the file path to the input ONNX model to compile. - * - * The input model's location (e.g., file path or memory buffer) must be set with either - * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] input_model_path Null terminated string of the path (wchar on Windows, char otherwise). - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetInputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const ORTCHAR_T* input_model_path); - - /** \brief Sets the buffer that stores the bytes of the loaded ONNX model to compile. - * - * The input model's location (e.g., file path or memory buffer) must be set with either - * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] input_model_data Buffer containing the loaded ONNX model bytes. - * \param[in] input_model_data_size The number of bytes in the `input_model_data` buffer. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetInputModelFromBuffer, - _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const void* input_model_data, - size_t input_model_data_size); - - /** \brief Sets the file path for the output ONNX model generated by CompileModel. - * - * The output model's location (e.g., file path or memory buffer) can be set with either - * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. - * - * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on - * the input model's file path. Examples: - * /Path/my_model.onnx -> /Path/my_model_ctx.onnx - * /Path/my_model -> /Path/my_model_ctx.onnx - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] output_model_path Null terminated string of the path (wchar on Windows, char otherwise). - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const ORTCHAR_T* output_model_path); - - /** \brief Optionally sets the file that should store external initializers for the compiled ONNX model. - * If not set, initializers are stored within the model. - * - * Only initializers for nodes that were not compiled are stored in the external initializers file. - * Compiled nodes contain their initializer data within the `ep_cache_context` attribute of EPContext nodes. - * Refer to ModelCompilationOptions_SetEpContextEmbedMode. - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] external_initializers_file_path Null terminated string of the path to the file. - * \param[in] external_initializers_size_threshold Initializers larger than this threshold are stored in the file. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelExternalInitializersFile, - _In_ OrtModelCompilationOptions* model_compile_options, - _In_ const ORTCHAR_T* external_initializers_file_path, - size_t external_initializers_size_threshold); - - /** \brief Configures model compilation to store the output compiled ONNX model in a buffer. - * - * The caller passes an OrtAllocator that ONNX Runtime uses to allocate memory for the buffer. - * - * The output model's location (e.g., file path or memory buffer) can be set with either - * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. - * - * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on - * the input model's file path. Examples: - * /Path/my_model.onnx -> /Path/my_model_ctx.onnx - * /Path/my_model -> /Path/my_model_ctx.onnx - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] allocator The allocator used to allocate the buffer for the compiled model. - * \param[out] output_model_buffer_ptr Pointer to the buffer that stores the compiled model. - * \param[out] output_model_buffer_size_ptr Pointer set to the size of output model in bytes. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelBuffer, - _In_ OrtModelCompilationOptions* model_compile_options, - _Inout_ OrtAllocator* allocator, - _Outptr_ void** output_model_buffer_ptr, - _Out_ size_t* output_model_buffer_size_ptr); - - /** \brief Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute - * of EPContext nodes. Defaults to false. - * - * If enabled, the `ep_cache_context` attribute of EPContext nodes will store the context binary data, which may - * include weights for compiled subgraphs. - * - * If disabled, the `ep_cache_context` attribute of EPContext nodes will contain the path to the file containing the - * context binary data. The path is set by the execution provider creating the EPContext node. - * - * More details relate to EPContext design refers to: - * \htmlonly - * EPContext design document. - * \endhtmlonly - * - * \param[in] model_compile_options The OrtModelCompilationOptions instance. - * \param[in] embed_ep_context_in_model True to embed EPContext binary data into the EPContext node - * `ep_cache_context` attributes. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(ModelCompilationOptions_SetEpContextEmbedMode, _In_ OrtModelCompilationOptions* model_compile_options, - bool embed_ep_context_in_model); - - /** \brief Compiles an input ONNX model with the given compilation options. - * - * \param[in] env OrtEnv object. - * \param[in] model_options The compilation options that defines compilation options for a model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CompileModel, _In_ const OrtEnv* env, _In_ const OrtModelCompilationOptions* model_options); -}; - -ORT_RUNTIME_CLASS(Ep); -ORT_RUNTIME_CLASS(EpFactory); - -struct OrtEpApi { - /** \brief Create an OrtEpDevice for the EP and an OrtHardwareDevice. - * \param[in] ep_factory Execution provider factory that is creating the instance. - * \param[in] hardware_device Hardware device that the EP can utilize. - * \param[in] ep_metadata Optional OrtKeyValuePairs instance for execution provider metadata that may be used - * during execution provider selection and passed to CreateEp. - * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. - * \param[in] ep_options Optional OrtKeyValuePairs instance for execution provider options that will be added - * to the Session configuration options if the execution provider is selected. - * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. - * \param ep_device OrtExecutionDevice that is created. - * - * \since Version 1.22. - */ - ORT_API2_STATUS(CreateEpDevice, _In_ OrtEpFactory* ep_factory, - _In_ const OrtHardwareDevice* hardware_device, - _In_opt_ const OrtKeyValuePairs* ep_metadata, - _In_opt_ const OrtKeyValuePairs* ep_options, - _Out_ OrtEpDevice** ep_device); - - ORT_CLASS_RELEASE(EpDevice); -}; - -/** - * \brief The OrtEp struct provides functions to implement for an execution provider. - * \since Version 1.22. - */ -struct OrtEp { - /** \brief The ONNX Runtime version the execution provider was compiled with. - * - * Implementation should set to ORT_API_VERSION. - * ORT will use this to ensure it does not call functions that were not available when the library was compiled. - * - * \since Version 1.22. - */ - uint32_t ort_version_supported; - - /** \brief Get the execution provider name. - * - * \param[in] this_ptr The OrtEp instance. - * \return The execution provider name. - * - * \note Returned string is owned by ORT and valid until UnregisterExecutionProviderLibrary is called. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetName)(const OrtEp* this_ptr); - - // OrtStatus* GetCapability(OrtEp* ep, const OrtGraph* graph, - // size_t* num_supported_subgraphs, - // OrtIndexedSubgraph** supported_subgraphs, OrtAllocator* allocator); - - // OrtStatus* Compile(OrtEp* ep, const OrtGraph** graphs, OrtNode** fused_graph_nodes, - // size_t count, OrtNodeComputeInfo* node_compute_infos); - - // TODO: Implement OrtEpApi and the complete OrtEp interface as the next step. -}; - -/** \brief The function signature that ORT will call to create OrtEpFactory instances. - * - * This must be available in a function called 'CreateEpFactories' in the execution provider library. - * - * \param[in] registered_name The name the execution library is registered with by RegisterExecutionProviderLibrary - * \param[in] ort_api_base The OrtApiBase instance that is used by the factory to get the OrtApi instance for the - * version of ORT that the library was compiled against. - * \param[in,out] factories The implementation should create and add OrtEpFactory instances to this - * pre-allocated array. - * i.e. usage is `factories[0] = new MyEpFactory();` - * \param[in] max_factories The maximum number of OrtEpFactory instances that can be added to `factories`. - * Current default is to allow 4 factories. This can be increased in the future if needed. - * \param[out] num_factories The number of OrtEpFactory instances created by the factory and added to `factories`. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ -typedef OrtStatus* (*CreateEpApiFactoriesFn)(_In_ const char* registered_name, _In_ const OrtApiBase* ort_api_base, - _Inout_ OrtEpFactory** factories, _In_ size_t max_factories, - _Out_ size_t* num_factories); - -/** \brief The function signature that ORT will call to release an OrtEpFactory instance. - * - * This must be available in a function called 'ReleaseEpFactory' in the execution provider library. - * - * \param[in] factory The OrtEpFactory instance to release. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version 1.22. - */ -typedef OrtStatus* (*ReleaseEpApiFactoryFn)(_In_ OrtEpFactory* factory); - -/** - * \brief The OrtEpFactory provides functions to create and manage execution providers. - * \since Version 1.22. - */ -struct OrtEpFactory { - /** \brief The ONNX Runtime version the execution provider was compiled with. - * - * Implementation should set to ORT_API_VERSION. - * ORT will use this to ensure it does not call functions that were not available when the library was compiled. - * - * \since Version 1.22. - */ - uint32_t ort_version_supported; - - /** \brief Get the name the of the execution provider that the factory creates. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \return The name of the execution provider the factory creates. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetName)(const OrtEpFactory* this_ptr); - - /** \brief Get the name of vendor who owns the execution provider that the factory creates. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \return vendor The vendor name of the execution provider the factory creates. - * - * \since Version 1.22. - */ - const char*(ORT_API_CALL* GetVendor)(const OrtEpFactory* this_ptr); // return EP vendor - - /** \brief Get information from the execution provider if it supports the OrtHardwareDevice. - * - * \param[in] this_ptr The OrtEpFactory instance. - * Non-const as the factory is passed through to the CreateEp call via the OrtEpDevice. - * \param[in] devices The OrtHardwareDevice instances that are available. - * \param[in] num_devices The number of OrtHardwareDevice instances. - * \param[out] ep_devices OrtEpDevice instances for each OrtHardwareDevice that the EP can use. - * The implementation should call OrtEpApi::CreateEpDevice to create, and add the OrtEpDevice - * instances to this pre-allocated array. ORT will take ownership of the values returned. - * i.e. usage is `ep_devices[0] = ;` - * \param[in] max_ep_devices The maximum number of OrtEpDevices that can be added to ep_devices. - * Current default is 8. This can be increased if needed. - * \param[out] num_ep_devices The number of EP devices added to ep_devices. - * \return true if the factory can create an execution provider that uses `device`. - * - * \note ORT will take ownership or ep_metadata and/or ep_options if they are not null. - * - * \since Version 1.22. - */ - OrtStatus*(ORT_API_CALL* GetSupportedDevices)(_In_ OrtEpFactory* this_ptr, - _In_reads_(num_devices) const OrtHardwareDevice* const* devices, - _In_ size_t num_devices, - _Inout_ OrtEpDevice** ep_devices, - _In_ size_t max_ep_devices, - _Out_ size_t* num_ep_devices); - - /** \brief Function to create an OrtEp instance for use in a Session. - * - * ORT will call ReleaseEp to release the instance when it is no longer needed. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \param[in] devices The OrtHardwareDevice instances that the execution provider was selected to use. - * \param[in] ep_metadata_pairs Execution provider metadata that was provided to OrtEpApi::CreateEpDevice, for each - * device. - * \param[in] num_devices The number of devices the execution provider was selected for. - * \param[in] session_options The OrtSessionOptions instance that contains the configuration options for the - * session. This will include ep_options from GetSupportedDevices as well as any - * user provided overrides. - * Execution provider options will have been added with a prefix of 'ep..'. - * The OrtSessionOptions instance will NOT be valid after this call and should not be - * stored for later use. - * \param[in] logger The OrtLogger instance for the session that the execution provider should use for logging. - * \param[out] ep The OrtEp instance created by the factory. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - * \since Version . This is a placeholder. - */ - OrtStatus*(ORT_API_CALL* CreateEp)(_In_ OrtEpFactory* this_ptr, - _In_reads_(num_devices) const OrtHardwareDevice* const* devices, - _In_reads_(num_devices) const OrtKeyValuePairs* const* ep_metadata_pairs, - _In_ size_t num_devices, - _In_ const OrtSessionOptions* session_options, - _In_ const OrtLogger* logger, _Outptr_ OrtEp** ep); - - /** \brief Release the OrtEp instance. - * - * \param[in] this_ptr The OrtEpFactory instance. - * \param[in] ep The OrtEp instance to release. - * - * \since Version . This is a placeholder. - */ - void(ORT_API_CALL* ReleaseEp)(OrtEpFactory* this_ptr, struct OrtEp* ep); -}; - -/* - * This is the old way to add the CUDA provider to the session, please use SessionOptionsAppendExecutionProvider_CUDA above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with CUDA support and the CUDA provider shared library exists - * - * \param device_id CUDA device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id); - -/* - * This is the old way to add the ROCm provider to the session, please use - * SessionOptionsAppendExecutionProvider_ROCM above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with - * HIP support and the ROCm provider shared library exists - * - * \param device_id HIP device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id); - -/* - * This is the old way to add the MIGraphX provider to the session, please use - * SessionOptionsAppendExecutionProvider_MIGraphX above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with - * HIP support and the MIGraphX provider shared library exists - * - * \param device_id HIP device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id); - -/* - * This is the old way to add the oneDNN provider to the session, please use - * SessionOptionsAppendExecutionProvider_oneDNN above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with - * oneDNN support and the oneDNN provider shared library exists - * - * \param use_arena zero: false. non-zero: true. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena); - -/* - * This is the old way to add the TensorRT provider to the session, please use SessionOptionsAppendExecutionProvider_TensorRT_V2 above to access the latest functionality - * This function always exists, but will only succeed if Onnxruntime was built with TensorRT support and the TensorRT provider shared library exists - * - * \param device_id CUDA device id, starts from zero. - */ -ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Tensorrt, _In_ OrtSessionOptions* options, int device_id); - -#ifdef __cplusplus -} -#endif -/// @} +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// See docs\c_cxx\README.md on generating the Doxygen documentation from this file + +/** \mainpage ONNX Runtime + * + * ONNX Runtime is a high-performance inference and training graph execution engine for deep learning models. + * + * ONNX Runtime's C, C++ APIs offer an easy to use interface to onboard and execute onnx models. + * - \subpage c_cpp_api "Core C, C++ APIs" + * - \subpage training_c_cpp_api "Training C, C++ APIs for on-device training" + * + * \page c_cpp_api Core C, C++ APIs + *

C

+ * + * ::OrtApi - Click here to go to the structure with all C API functions. + * + *

C++

+ * + * ::Ort - Click here to go to the namespace holding all of the C++ wrapper classes + * + * It is a set of header only wrapper classes around the C API. The goal is to turn the C style return value error codes into C++ exceptions, and to + * automate memory management through standard C++ RAII principles. + * + * \addtogroup Global + * ONNX Runtime C API + * @{ + */ + +#pragma once +#include +#include +#include +#include + +/** \brief The API version defined in this header + * + * This value is used by some API functions to behave as this version of the header expects. + */ +#define ORT_API_VERSION 22 + +#ifdef __cplusplus +extern "C" { +#endif + +//! @} +// SAL2 Definitions +#ifndef _MSC_VER +#define _In_ +#define _In_z_ +#define _In_opt_ +#define _In_opt_z_ +#define _Out_ +#define _Outptr_ +#define _Out_opt_ +#define _Inout_ +#define _Inout_opt_ +#define _Frees_ptr_opt_ +#define _Ret_maybenull_ +#define _Ret_notnull_ +#define _Check_return_ +#define _Outptr_result_maybenull_ +#define _In_reads_(X) +#define _Inout_updates_(X) +#define _Out_writes_(X) +#define _Inout_updates_all_(X) +#define _Out_writes_bytes_all_(X) +#define _Out_writes_all_(X) +#define _Success_(X) +#define _Outptr_result_buffer_maybenull_(X) +#define ORT_ALL_ARGS_NONNULL __attribute__((nonnull)) +#else +#include +#define ORT_ALL_ARGS_NONNULL +#endif + +#ifdef _WIN32 +// Define ORT_DLL_IMPORT if your program is dynamically linked to Ort. +// dllexport is not used, we use a .def file. +#ifdef ORT_DLL_IMPORT +#define ORT_EXPORT __declspec(dllimport) +#else +#define ORT_EXPORT +#endif +#define ORT_API_CALL _stdcall +#define ORT_MUST_USE_RESULT +#define ORTCHAR_T wchar_t +#else +// To make symbols visible on macOS/iOS +#ifdef __APPLE__ +#define ORT_EXPORT __attribute__((visibility("default"))) +#else +#define ORT_EXPORT +#endif +#define ORT_API_CALL +#define ORT_MUST_USE_RESULT __attribute__((warn_unused_result)) +#define ORTCHAR_T char +#endif + +/// ORTCHAR_T, ORT_TSTR are reserved specifically for path handling. +/// All other strings are UTF-8 encoded, use char and std::string +#ifndef ORT_TSTR +#ifdef _WIN32 +#define ORT_TSTR(X) L##X +// When X is a macro, L##X is not defined. In this case, we need to use ORT_TSTR_ON_MACRO. +#define ORT_TSTR_ON_MACRO(X) L"" X +#else +#define ORT_TSTR(X) X +#define ORT_TSTR_ON_MACRO(X) X +#endif +#endif + +// On Windows, ORT_FILE is a wchar_t version of the __FILE__ macro. +// Otherwise, ORT_FILE is equivalent to __FILE__. +#ifndef ORT_FILE +#define ORT_FILE_INTERNAL(x) ORT_TSTR(x) +#define ORT_FILE ORT_FILE_INTERNAL(__FILE__) +#endif + +// Any pointer marked with _In_ or _Out_, cannot be NULL. + +// Windows users should use unicode paths when possible to bypass the MAX_PATH limitation +// Every pointer marked with _In_ or _Out_, cannot be NULL. Caller should ensure that. +// for ReleaseXXX(...) functions, they can accept NULL pointer. + +#ifdef __cplusplus +// For any compiler with C++11 support, MSVC 2015 and greater, or Clang version supporting noexcept. +// Such complex condition is needed because compilers set __cplusplus value differently. +#ifndef __has_feature +#define __has_feature(x) 0 +#endif +#if ((__cplusplus >= 201103L) || (_MSC_VER >= 1900) || (defined(__has_feature) && __has_feature(cxx_noexcept))) +#define NO_EXCEPTION noexcept +#else +#define NO_EXCEPTION throw() +#endif +#else +#define NO_EXCEPTION +#endif + +// __VA_ARGS__ on Windows and Linux are different +#define ORT_API(RETURN_TYPE, NAME, ...) RETURN_TYPE ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION + +#define ORT_API_STATUS(NAME, ...) \ + _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) \ + NO_EXCEPTION ORT_MUST_USE_RESULT + +// XXX: Unfortunately, SAL annotations are known to not work with function pointers +#define ORT_API2_STATUS(NAME, ...) \ + _Check_return_ _Ret_maybenull_ OrtStatusPtr(ORT_API_CALL* NAME)(__VA_ARGS__) NO_EXCEPTION ORT_MUST_USE_RESULT + +// Used in *.cc files. Almost as same as ORT_API_STATUS, except without ORT_MUST_USE_RESULT and ORT_EXPORT +#define ORT_API_STATUS_IMPL(NAME, ...) \ + _Success_(return == 0) _Check_return_ _Ret_maybenull_ OrtStatusPtr ORT_API_CALL NAME(__VA_ARGS__) NO_EXCEPTION + +#define ORT_CLASS_RELEASE(X) void(ORT_API_CALL * Release##X)(_Frees_ptr_opt_ Ort##X * input) + +#ifdef __DOXYGEN__ +#undef ORT_API_STATUS +#define ORT_API_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) +#undef ORT_API2_STATUS +#define ORT_API2_STATUS(NAME, ...) OrtStatus* NAME(__VA_ARGS__) +#undef ORT_CLASS_RELEASE +#define ORT_CLASS_RELEASE(X) void Release##X(Ort##X* input) +#undef NO_EXCEPTION +#define NO_EXCEPTION +#endif +/** \addtogroup Global + * ONNX Runtime C API + * @{ + */ + +/** Copied from TensorProto::DataType + * Currently, Ort doesn't support complex64, complex128 + */ +typedef enum ONNXTensorElementDataType { + ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT, // maps to c type float + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8, // maps to c type uint8_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8, // maps to c type int8_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16, // maps to c type uint16_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16, // maps to c type int16_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32, // maps to c type int32_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64, // maps to c type int64_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING, // maps to c++ type std::string + ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL, + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16, + ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE, // maps to c type double + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32, // maps to c type uint32_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64, // maps to c type uint64_t + ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX64, // complex with float32 real and imaginary components + ONNX_TENSOR_ELEMENT_DATA_TYPE_COMPLEX128, // complex with float64 real and imaginary components + ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16, // Non-IEEE floating-point format based on IEEE754 single-precision + // float 8 types were introduced in onnx 1.14, see https://onnx.ai/onnx/technical/float8.html + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2, // Non-IEEE floating-point format based on IEEE754 single-precision + ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ, // Non-IEEE floating-point format based on IEEE754 single-precision + // Int4 types were introduced in ONNX 1.16. See https://onnx.ai/onnx/technical/int4.html + ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT4, // maps to a pair of packed uint4 values (size == 1 byte) + ONNX_TENSOR_ELEMENT_DATA_TYPE_INT4 // maps to a pair of packed int4 values (size == 1 byte) +} ONNXTensorElementDataType; + +// Synced with onnx TypeProto oneof +typedef enum ONNXType { + ONNX_TYPE_UNKNOWN, + ONNX_TYPE_TENSOR, + ONNX_TYPE_SEQUENCE, + ONNX_TYPE_MAP, + ONNX_TYPE_OPAQUE, + ONNX_TYPE_SPARSETENSOR, + ONNX_TYPE_OPTIONAL +} ONNXType; + +// These types are synced with internal +// SparseFormatFlags +typedef enum OrtSparseFormat { + ORT_SPARSE_UNDEFINED = 0, + ORT_SPARSE_COO = 0x1, + ORT_SPARSE_CSRC = 0x2, + ORT_SPARSE_BLOCK_SPARSE = 0x4 +} OrtSparseFormat; + +// Enum allows to query sparse tensor indices +enum OrtSparseIndicesFormat { + ORT_SPARSE_COO_INDICES, + ORT_SPARSE_CSR_INNER_INDICES, + ORT_SPARSE_CSR_OUTER_INDICES, + ORT_SPARSE_BLOCK_SPARSE_INDICES +}; + +/** \brief Logging severity levels + * + * In typical API usage, specifying a logging severity level specifies the minimum severity of log messages to show. + */ +typedef enum OrtLoggingLevel { + ORT_LOGGING_LEVEL_VERBOSE, ///< Verbose informational messages (least severe). + ORT_LOGGING_LEVEL_INFO, ///< Informational messages. + ORT_LOGGING_LEVEL_WARNING, ///< Warning messages. + ORT_LOGGING_LEVEL_ERROR, ///< Error messages. + ORT_LOGGING_LEVEL_FATAL, ///< Fatal error messages (most severe). +} OrtLoggingLevel; + +typedef enum OrtErrorCode { + ORT_OK, + ORT_FAIL, + ORT_INVALID_ARGUMENT, + ORT_NO_SUCHFILE, + ORT_NO_MODEL, + ORT_ENGINE_ERROR, + ORT_RUNTIME_EXCEPTION, + ORT_INVALID_PROTOBUF, + ORT_MODEL_LOADED, + ORT_NOT_IMPLEMENTED, + ORT_INVALID_GRAPH, + ORT_EP_FAIL, + ORT_MODEL_LOAD_CANCELED, + ORT_MODEL_REQUIRES_COMPILATION, +} OrtErrorCode; + +typedef enum OrtOpAttrType { + ORT_OP_ATTR_UNDEFINED = 0, + ORT_OP_ATTR_INT, + ORT_OP_ATTR_INTS, + ORT_OP_ATTR_FLOAT, + ORT_OP_ATTR_FLOATS, + ORT_OP_ATTR_STRING, + ORT_OP_ATTR_STRINGS, +} OrtOpAttrType; + +//! @} +#define ORT_RUNTIME_CLASS(X) \ + struct Ort##X; \ + typedef struct Ort##X Ort##X + +/** \addtogroup Global + * ONNX Runtime C API + * @{ + */ +// The actual types defined have an Ort prefix +ORT_RUNTIME_CLASS(Env); +ORT_RUNTIME_CLASS(Status); // nullptr for Status* indicates success +ORT_RUNTIME_CLASS(MemoryInfo); +ORT_RUNTIME_CLASS(IoBinding); +ORT_RUNTIME_CLASS(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) +ORT_RUNTIME_CLASS(Value); +ORT_RUNTIME_CLASS(RunOptions); +ORT_RUNTIME_CLASS(TypeInfo); +ORT_RUNTIME_CLASS(TensorTypeAndShapeInfo); +ORT_RUNTIME_CLASS(MapTypeInfo); +ORT_RUNTIME_CLASS(SequenceTypeInfo); +ORT_RUNTIME_CLASS(OptionalTypeInfo); +ORT_RUNTIME_CLASS(SessionOptions); +ORT_RUNTIME_CLASS(CustomOpDomain); +ORT_RUNTIME_CLASS(ModelMetadata); +ORT_RUNTIME_CLASS(ThreadPoolParams); +ORT_RUNTIME_CLASS(ThreadingOptions); +ORT_RUNTIME_CLASS(ArenaCfg); +ORT_RUNTIME_CLASS(PrepackedWeightsContainer); +ORT_RUNTIME_CLASS(TensorRTProviderOptionsV2); +ORT_RUNTIME_CLASS(NvTensorRtRtxProviderOptions); +ORT_RUNTIME_CLASS(CUDAProviderOptionsV2); +ORT_RUNTIME_CLASS(CANNProviderOptions); +ORT_RUNTIME_CLASS(DnnlProviderOptions); +ORT_RUNTIME_CLASS(Op); +ORT_RUNTIME_CLASS(OpAttr); +ORT_RUNTIME_CLASS(Logger); +ORT_RUNTIME_CLASS(ShapeInferContext); +ORT_RUNTIME_CLASS(LoraAdapter); +ORT_RUNTIME_CLASS(ValueInfo); +ORT_RUNTIME_CLASS(Node); +ORT_RUNTIME_CLASS(Graph); +ORT_RUNTIME_CLASS(Model); +ORT_RUNTIME_CLASS(ModelCompilationOptions); +ORT_RUNTIME_CLASS(HardwareDevice); +ORT_RUNTIME_CLASS(EpDevice); +ORT_RUNTIME_CLASS(KeyValuePairs); + +#ifdef _MSC_VER +typedef _Return_type_success_(return == 0) OrtStatus* OrtStatusPtr; +#else +typedef OrtStatus* OrtStatusPtr; +#endif + +/** \brief Memory allocation interface + * + * Structure of function pointers that defines a memory allocator. This can be created and filled in by the user for custom allocators. + * + * When an allocator is passed to any function, be sure that the allocator object is not destroyed until the last allocated object using it is freed. + */ +typedef struct OrtAllocator { + uint32_t version; ///< Must be initialized to ORT_API_VERSION + void*(ORT_API_CALL* Alloc)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes + void(ORT_API_CALL* Free)(struct OrtAllocator* this_, void* p); ///< Free a block of memory previously allocated with OrtAllocator::Alloc + const struct OrtMemoryInfo*(ORT_API_CALL* Info)(const struct OrtAllocator* this_); ///< Return a pointer to an ::OrtMemoryInfo that describes this allocator + /** + * @brief Optional allocation function to use for memory allocations made during session initialization. + * Use this function if you want to separate allocations made by ORT during Run() calls from + * those made during session initialization. This allows for separate memory management strategies for these allocations. + */ + void*(ORT_API_CALL* Reserve)(struct OrtAllocator* this_, size_t size); ///< Returns a pointer to an allocated block of `size` bytes +} OrtAllocator; + +typedef void(ORT_API_CALL* OrtLoggingFunction)( + void* param, OrtLoggingLevel severity, const char* category, const char* logid, const char* code_location, + const char* message); + +/** \brief Graph optimization level + * + * Refer to https://www.onnxruntime.ai/docs/performance/graph-optimizations.html#graph-optimization-levels + * for an in-depth understanding of the Graph Optimization Levels. + */ +typedef enum GraphOptimizationLevel { + ORT_DISABLE_ALL = 0, + ORT_ENABLE_BASIC = 1, + ORT_ENABLE_EXTENDED = 2, + ORT_ENABLE_ALL = 99 +} GraphOptimizationLevel; + +typedef enum ExecutionMode { + ORT_SEQUENTIAL = 0, + ORT_PARALLEL = 1, +} ExecutionMode; + +/** \brief Language projection identifiers + * /see OrtApi::SetLanguageProjection + */ +typedef enum OrtLanguageProjection { + ORT_PROJECTION_C = 0, + ORT_PROJECTION_CPLUSPLUS = 1, + ORT_PROJECTION_CSHARP = 2, + ORT_PROJECTION_PYTHON = 3, + ORT_PROJECTION_JAVA = 4, + ORT_PROJECTION_WINML = 5, + ORT_PROJECTION_NODEJS = 6, +} OrtLanguageProjection; + +struct OrtKernelInfo; +typedef struct OrtKernelInfo OrtKernelInfo; +struct OrtKernelContext; +typedef struct OrtKernelContext OrtKernelContext; +struct OrtCustomOp; +typedef struct OrtCustomOp OrtCustomOp; + +typedef enum OrtAllocatorType { + OrtInvalidAllocator = -1, + OrtDeviceAllocator = 0, + OrtArenaAllocator = 1 +} OrtAllocatorType; + +/** \brief Memory types for allocated memory, execution provider specific types should be extended in each provider. + */ +// Whenever this struct is updated, please also update the MakeKey function in onnxruntime / core / framework / execution_provider.cc +typedef enum OrtMemType { + OrtMemTypeCPUInput = -2, ///< Any CPU memory used by non-CPU execution provider + OrtMemTypeCPUOutput = -1, ///< CPU accessible memory outputted by non-CPU execution provider, i.e. CUDA_PINNED + OrtMemTypeCPU = OrtMemTypeCPUOutput, ///< Temporary CPU accessible memory allocated by non-CPU execution provider, i.e. CUDA_PINNED + OrtMemTypeDefault = 0, ///< The default allocator for execution provider +} OrtMemType; + +/** \brief This mimics OrtDevice type constants so they can be returned in the API + */ +typedef enum OrtMemoryInfoDeviceType { + OrtMemoryInfoDeviceType_CPU = 0, + OrtMemoryInfoDeviceType_GPU = 1, + OrtMemoryInfoDeviceType_FPGA = 2 +} OrtMemoryInfoDeviceType; + +typedef enum OrtHardwareDeviceType { + OrtHardwareDeviceType_CPU, + OrtHardwareDeviceType_GPU, + OrtHardwareDeviceType_NPU +} OrtHardwareDeviceType; + +/** \brief These are the default EP selection policies used by ORT when doing automatic EP selection. + */ +typedef enum OrtExecutionProviderDevicePolicy { + OrtExecutionProviderDevicePolicy_DEFAULT, + OrtExecutionProviderDevicePolicy_PREFER_CPU, + OrtExecutionProviderDevicePolicy_PREFER_NPU, + OrtExecutionProviderDevicePolicy_PREFER_GPU, + OrtExecutionProviderDevicePolicy_MAX_PERFORMANCE, + OrtExecutionProviderDevicePolicy_MAX_EFFICIENCY, + OrtExecutionProviderDevicePolicy_MIN_OVERALL_POWER, +} OrtExecutionProviderDevicePolicy; + +/** \brief Delegate to allow providing custom OrtEpDevice selection logic + * + * This delegate is called by the EP selection code to allow the user to provide custom device selection logic. + * The user can use this to select OrtEpDevice instances from the list of available devices. + * + * \param ep_devices The list of available devices. + * \param num_devices The number of available devices. + * \param model_metadata The model metadata. + * \param runtime_metadata The runtime metadata. May be nullptr. + * \param selected Pre-allocated array to populate with selected OrtEpDevice pointers from ep_devices. + * \param max_ep_devices The maximum number of devices that can be selected in the pre-allocated array. + Currently the maximum is 8. + * \param num_ep_devices The number of selected devices. + * \param state Opaque pointer. Required to use the delegate from other languages like C# and python. + * + * \return OrtStatus* Selection status. Return nullptr on success. + * Use CreateStatus to provide error info. Use ORT_FAIL as the error code. + * ORT will release the OrtStatus* if not null. + */ +typedef OrtStatus* (*EpSelectionDelegate)(_In_ const OrtEpDevice** ep_devices, + _In_ size_t num_devices, + _In_ const OrtKeyValuePairs* model_metadata, + _In_opt_ const OrtKeyValuePairs* runtime_metadata, + _Inout_ const OrtEpDevice** selected, + _In_ size_t max_selected, + _Out_ size_t* num_selected, + _In_ void* state); + +/** \brief Algorithm to use for cuDNN Convolution Op + */ +typedef enum OrtCudnnConvAlgoSearch { + OrtCudnnConvAlgoSearchExhaustive, // expensive exhaustive benchmarking using cudnnFindConvolutionForwardAlgorithmEx + OrtCudnnConvAlgoSearchHeuristic, // lightweight heuristic based search using cudnnGetConvolutionForwardAlgorithm_v7 + OrtCudnnConvAlgoSearchDefault, // default algorithm using CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM +} OrtCudnnConvAlgoSearch; + +/** \brief CUDA Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_CUDA + */ +typedef struct OrtCUDAProviderOptions { +#ifdef __cplusplus + OrtCUDAProviderOptions() + : device_id{}, + cudnn_conv_algo_search{OrtCudnnConvAlgoSearchExhaustive}, + gpu_mem_limit{SIZE_MAX}, + arena_extend_strategy{}, + do_copy_in_default_stream{1}, + has_user_compute_stream{}, + user_compute_stream{}, + default_memory_arena_cfg{}, + tunable_op_enable{false}, + tunable_op_tuning_enable{false}, + tunable_op_max_tuning_duration_ms{} {} +#endif + + /** \brief CUDA device Id + * Defaults to 0. + */ + int device_id; + + /** \brief CUDA Convolution algorithm search configuration. + * See enum OrtCudnnConvAlgoSearch for more details. + * Defaults to OrtCudnnConvAlgoSearchExhaustive. + */ + OrtCudnnConvAlgoSearch cudnn_conv_algo_search; + + /** \brief CUDA memory limit (To use all possible memory pass in maximum size_t) + * Defaults to SIZE_MAX. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + size_t gpu_mem_limit; + + /** \brief Strategy used to grow the memory arena + * 0 = kNextPowerOfTwo
+ * 1 = kSameAsRequested
+ * Defaults to 0. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + int arena_extend_strategy; + + /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the CUDA EP + * 0 = Use separate streams for copying and compute. + * 1 = Use the same stream for copying and compute. + * Defaults to 1. + * WARNING: Setting this to 0 may result in data races for some models. + * Please see issue #4829 for more details. + */ + int do_copy_in_default_stream; + + /** \brief Flag indicating if there is a user provided compute stream + * Defaults to 0. + */ + int has_user_compute_stream; + + /** \brief User provided compute stream. + * If provided, please set `has_user_compute_stream` to 1. + */ + void* user_compute_stream; + + /** \brief CUDA memory arena configuration parameters + */ + OrtArenaCfg* default_memory_arena_cfg; + + /** \brief Enable TunableOp for using. + * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_ENABLE. + */ + int tunable_op_enable; + + /** \brief Enable TunableOp for tuning. + * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_CUDA_TUNABLE_OP_TUNING_ENABLE. + */ + int tunable_op_tuning_enable; + + /** \brief Max tuning duration time limit for each instance of TunableOp. + * Defaults to 0 to disable the limit. + */ + int tunable_op_max_tuning_duration_ms; + +} OrtCUDAProviderOptions; + +/** \brief ROCM Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_ROCM + */ +typedef struct OrtROCMProviderOptions { +#ifdef __cplusplus + OrtROCMProviderOptions() + : device_id{}, + miopen_conv_exhaustive_search{0}, + gpu_mem_limit{SIZE_MAX}, + arena_extend_strategy{}, + do_copy_in_default_stream{1}, + has_user_compute_stream{}, + user_compute_stream{}, + default_memory_arena_cfg{}, + enable_hip_graph{false}, + tunable_op_enable{false}, + tunable_op_tuning_enable{false}, + tunable_op_max_tuning_duration_ms{} {} +#endif + + /** \brief ROCM device Id + * Defaults to 0. + */ + int device_id; + + /** \brief ROCM MIOpen Convolution algorithm exaustive search option. + * Defaults to 0 (false). + */ + int miopen_conv_exhaustive_search; + + /** \brief ROCM memory limit (To use all possible memory pass in maximum size_t) + * Defaults to SIZE_MAX. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + size_t gpu_mem_limit; + + /** \brief Strategy used to grow the memory arena + * 0 = kNextPowerOfTwo
+ * 1 = kSameAsRequested
+ * Defaults to 0. + * \note If a ::OrtArenaCfg has been applied, it will override this field + */ + int arena_extend_strategy; + + /** \brief Flag indicating if copying needs to take place on the same stream as the compute stream in the ROCM EP + * 0 = Use separate streams for copying and compute. + * 1 = Use the same stream for copying and compute. + * Defaults to 1. + * WARNING: Setting this to 0 may result in data races for some models. + * Please see issue #4829 for more details. + */ + int do_copy_in_default_stream; + + /** \brief Flag indicating if there is a user provided compute stream + * Defaults to 0. + */ + int has_user_compute_stream; + + /** \brief User provided compute stream. + * If provided, please set `has_user_compute_stream` to 1. + */ + void* user_compute_stream; + + /** \brief ROCM memory arena configuration parameters + */ + OrtArenaCfg* default_memory_arena_cfg; + + int enable_hip_graph; + + /** \brief Enable TunableOp for using. + * Set it to 1/0 to enable/disable TunableOp. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_ENABLE. + */ + int tunable_op_enable; + + /** \brief Enable TunableOp for tuning. + * Set it to 1/0 to enable/disable TunableOp tuning. Otherwise, it is disabled by default. + * This option can be overridden by environment variable ORT_ROCM_TUNABLE_OP_TUNING_ENABLE. + */ + int tunable_op_tuning_enable; + + /** \brief Max tuning duration time limit for each instance of TunableOp. + * Defaults to 0 to disable the limit. + */ + int tunable_op_max_tuning_duration_ms; + +} OrtROCMProviderOptions; + +/** \brief TensorRT Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + */ +typedef struct OrtTensorRTProviderOptions { + int device_id; ///< CUDA device id (0 = default device) + int has_user_compute_stream; // indicator of user specified CUDA compute stream. + void* user_compute_stream; // user specified CUDA compute stream. + int trt_max_partition_iterations; // maximum iterations for TensorRT parser to get capability + int trt_min_subgraph_size; // minimum size of TensorRT subgraphs + size_t trt_max_workspace_size; // maximum workspace size for TensorRT. + int trt_fp16_enable; // enable TensorRT FP16 precision. Default 0 = false, nonzero = true + int trt_int8_enable; // enable TensorRT INT8 precision. Default 0 = false, nonzero = true + const char* trt_int8_calibration_table_name; // TensorRT INT8 calibration table name. + int trt_int8_use_native_calibration_table; // use native TensorRT generated calibration table. Default 0 = false, nonzero = true + int trt_dla_enable; // enable DLA. Default 0 = false, nonzero = true + int trt_dla_core; // DLA core number. Default 0 + int trt_dump_subgraphs; // dump TRT subgraph. Default 0 = false, nonzero = true + int trt_engine_cache_enable; // enable engine caching. Default 0 = false, nonzero = true + const char* trt_engine_cache_path; // specify engine cache path + int trt_engine_decryption_enable; // enable engine decryption. Default 0 = false, nonzero = true + const char* trt_engine_decryption_lib_path; // specify engine decryption library path + int trt_force_sequential_engine_build; // force building TensorRT engine sequentially. Default 0 = false, nonzero = true + // This is the legacy struct and don't add new fields here. + // For new field that can be represented by string, please add it in include/onnxruntime/core/providers/tensorrt/tensorrt_provider_options.h + // For non-string field, need to create a new separate api to handle it. +} OrtTensorRTProviderOptions; + +/** \brief MIGraphX Provider Options + * + * \see OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX + */ +typedef struct OrtMIGraphXProviderOptions { + int device_id; // hip device id. + int migraphx_fp16_enable; // MIGraphX FP16 precision. Default 0 = false, nonzero = true + int migraphx_int8_enable; // MIGraphX INT8 precision. Default 0 = false, nonzero = true + int migraphx_use_native_calibration_table; // MIGraphx INT8 cal table. Default 0 = false, noznero = true + const char* migraphx_int8_calibration_table_name; // MIGraphx INT8 calibration table name + int migraphx_save_compiled_model; // migraphx save compiled model. Default 0 = false, noznero = true + const char* migraphx_save_model_path; // migraphx model path name + int migraphx_load_compiled_model; // migraphx int8 cal table. Default 0 = false, noznero = true + const char* migraphx_load_model_path; // migraphx model path name + bool migraphx_exhaustive_tune; // migraphx tuned compile Default = false +} OrtMIGraphXProviderOptions; + +/** \brief OpenVINO Provider Options + * \brief This Struct is frozen since ORT 1.13.0. Its maintained part of Legacy API for compatibility. + * \brief For latest OpenVINO Provider Options update to the ProviderOptions map. + * \brief Latest OpenVINO Provider Options are listed in the + * \htmlonly + * onnxruntime document. + * \endhtmlonly + * \see OrtApi::SessionOptionsAppendExecutionProvider() + */ +typedef struct OrtOpenVINOProviderOptions { +#ifdef __cplusplus + OrtOpenVINOProviderOptions() : device_type{}, + enable_npu_fast_compile{}, + device_id{}, + num_of_threads{}, + cache_dir{}, + context{}, + enable_opencl_throttling{}, + enable_dynamic_shapes{} {} +#endif + /** \brief Device type string + * + * Valid settings are one of: "CPU_FP32", "CPU_FP16", "GPU_FP32", "GPU_FP16" + */ + const char* device_type; + unsigned char enable_npu_fast_compile; ///< 0 = disabled, nonzero = enabled + const char* device_id; + size_t num_of_threads; ///< 0 = Use default number of threads + const char* cache_dir; // path is set to empty by default + void* context; + unsigned char enable_opencl_throttling; ///< 0 = disabled, nonzero = enabled + unsigned char enable_dynamic_shapes; ///< 0 = disabled, nonzero = enabled +} OrtOpenVINOProviderOptions; + +struct OrtApi; +typedef struct OrtApi OrtApi; + +struct OrtTrainingApi; +typedef struct OrtTrainingApi OrtTrainingApi; + +struct OrtModelEditorApi; +typedef struct OrtModelEditorApi OrtModelEditorApi; + +struct OrtCompileApi; +typedef struct OrtCompileApi OrtCompileApi; + +struct OrtEpApi; +typedef struct OrtEpApi OrtEpApi; + +/** \brief The helper interface to get the right version of OrtApi + * + * Get a pointer to this structure through ::OrtGetApiBase + */ +struct OrtApiBase { + /** \brief Get a pointer to the requested version of the ::OrtApi + * + * \param[in] version Must be ::ORT_API_VERSION + * \return The ::OrtApi for the version requested, nullptr will be returned if this version is unsupported, for example when using a runtime + * older than the version created with this header file. + * + * One can call GetVersionString() to get the version of the Onnxruntime library for logging + * and error reporting purposes. + */ + const OrtApi*(ORT_API_CALL* GetApi)(uint32_t version)NO_EXCEPTION; + + /** \brief Returns a null terminated string of the version of the Onnxruntime library (eg: "1.8.1") + * + * \return UTF-8 encoded version string. Do not deallocate the returned buffer. + */ + const char*(ORT_API_CALL* GetVersionString)(void)NO_EXCEPTION; +}; + +typedef struct OrtApiBase OrtApiBase; + +/** \brief The Onnxruntime library's entry point to access the C API + * + * Call this to get the a pointer to an ::OrtApiBase + */ +ORT_EXPORT const OrtApiBase* ORT_API_CALL OrtGetApiBase(void) NO_EXCEPTION; + +/** \brief Thread work loop function + * + * Onnxruntime will provide the working loop on custom thread creation + * Argument is an onnxruntime built-in type which will be provided when thread pool calls OrtCustomCreateThreadFn + */ +typedef void (*OrtThreadWorkerFn)(void* ort_worker_fn_param); + +typedef const struct OrtCustomHandleType { + char __place_holder; +}* OrtCustomThreadHandle; + +/** \brief Ort custom thread creation function + * + * The function should return a thread handle to be used in onnxruntime thread pools + * Onnxruntime will throw exception on return value of nullptr or 0, indicating that the function failed to create a thread + */ +typedef OrtCustomThreadHandle (*OrtCustomCreateThreadFn)(void* ort_custom_thread_creation_options, OrtThreadWorkerFn ort_thread_worker_fn, void* ort_worker_fn_param); + +/** \brief Custom thread join function + * + * Onnxruntime thread pool destructor will call the function to join a custom thread. + * Argument ort_custom_thread_handle is the value returned by OrtCustomCreateThreadFn + */ +typedef void (*OrtCustomJoinThreadFn)(OrtCustomThreadHandle ort_custom_thread_handle); + +typedef OrtStatus*(ORT_API_CALL* RegisterCustomOpsFn)(OrtSessionOptions* options, const OrtApiBase* api); + +/** \brief Callback function for RunAsync + * + * \param[in] user_data User specific data that passed back to the callback + * \param[out] outputs On succeed, outputs host inference results, on error, the value will be nullptr + * \param[out] num_outputs Number of outputs, on error, the value will be zero + * \param[out] status On error, status will provide details + */ +typedef void (*RunAsyncCallbackFn)(void* user_data, OrtValue** outputs, size_t num_outputs, OrtStatusPtr status); + +/** \brief The C API + * + * All C API functions are defined inside this structure as pointers to functions. + * Call OrtApiBase::GetApi to get a pointer to it + * + * \nosubgrouping + */ +struct OrtApi { + /// \name OrtStatus + /// @{ + + /** + * \brief Create an OrtStatus from a null terminated string + * + * \param[in] code + * \param[in] msg A null-terminated string. Its contents will be copied. + * \return A new OrtStatus object, must be destroyed with OrtApi::ReleaseStatus + */ + OrtStatus*(ORT_API_CALL* CreateStatus)(OrtErrorCode code, _In_ const char* msg)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Get OrtErrorCode from OrtStatus + * + * \param[in] status + * \return OrtErrorCode that \p status was created with + */ + OrtErrorCode(ORT_API_CALL* GetErrorCode)(_In_ const OrtStatus* status) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Get error string from OrtStatus + * + * \param[in] status + * \return The error message inside the `status`. Do not free the returned value. + */ + const char*(ORT_API_CALL* GetErrorMessage)(_In_ const OrtStatus* status)NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an OrtEnv + * + * \note Invoking this function will return the same instance of the environment as that returned by a previous call + * to another env creation function; all arguments to this function will be ignored. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnv, OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); + + /** \brief Create an OrtEnv + * + * \note Invoking this function will return the same instance of the environment as that returned by a previous call + * to another env creation function; all arguments to this function will be ignored. If you want to provide your + * own logging function, consider setting it using the SetUserLoggingFunction API instead. + * \param[in] logging_function A pointer to a logging function. + * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `logging_function`. This parameter is optional. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithCustomLogger, _In_ OrtLoggingFunction logging_function, _In_opt_ void* logger_param, + _In_ OrtLoggingLevel log_severity_level, _In_ const char* logid, _Outptr_ OrtEnv** out); + + /** \brief Enable Telemetry + * + * \note Telemetry events are on by default since they are lightweight + * \param[in] env + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableTelemetryEvents, _In_ const OrtEnv* env); + /** \brief Disable Telemetry + * + * \see OrtApi::EnableTelemetryEvents + * \param[in] env + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableTelemetryEvents, _In_ const OrtEnv* env); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Create an OrtSession from a model file + * + * \param[in] env + * \param[in] model_path + * \param[in] options + * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + // TODO: document the path separator convention? '/' vs '\' + // TODO: should specify the access characteristics of model_path. Is this read only during the + // execution of CreateSession, or does the OrtSession retain a handle to the file/directory + // and continue to access throughout the OrtSession lifetime? + // What sort of access is needed to model_path : read or read/write? + ORT_API2_STATUS(CreateSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession from memory + * + * \param[in] env + * \param[in] model_data + * \param[in] model_data_length + * \param[in] options + * \param[out] out Returned newly created OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionFromArray, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Run the model in an ::OrtSession + * + * Will not return until the model run has completed. Multiple threads might be used to run the model based on + * the options in the ::OrtSession and settings used when creating the ::OrtEnv + * + * \param[in] session + * \param[in] run_options If nullptr, will use a default ::OrtRunOptions + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] inputs Array of ::OrtValue%s of the input values + * \param[in] input_len Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[in] output_names_len Number of elements in the output_names and outputs array + * \param[out] outputs Array of ::OrtValue%s that the outputs are stored in. This can also be + * an array of nullptr values, in this case ::OrtValue objects will be allocated and pointers + * to them will be set into the `outputs` array. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(Run, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, + _In_reads_(input_len) const char* const* input_names, + _In_reads_(input_len) const OrtValue* const* inputs, size_t input_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _Inout_updates_all_(output_names_len) OrtValue** outputs); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Create an ::OrtSessionOptions object + * + * To use additional providers, you must build ORT with the extra providers enabled. Then call one of these + * functions to enable them in the session:
+ * OrtSessionOptionsAppendExecutionProvider_CPU
+ * OrtSessionOptionsAppendExecutionProvider_CUDA
+ * OrtSessionOptionsAppendExecutionProvider_(remaining providers...)
+ * The order they are called indicates the preference order as well. In other words call this method + * on your most preferred execution provider first followed by the less preferred ones. + * If none are called Ort will use its internal CPU execution provider. + * + * \param[out] options The newly created OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionOptions, _Outptr_ OrtSessionOptions** options); + + /** \brief Set filepath to save optimized model after graph level transformations + * + * \param[in] options + * \param[in] optimized_model_filepath + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetOptimizedModelFilePath, _Inout_ OrtSessionOptions* options, + _In_ const ORTCHAR_T* optimized_model_filepath); + + /** \brief Create a copy of an existing ::OrtSessionOptions + * + * \param[in] in_options OrtSessionOptions to copy + * \param[out] out_options Returned newly created ::OrtSessionOptions. Must be freed with OrtApi::ReleaseSessionOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CloneSessionOptions, _In_ const OrtSessionOptions* in_options, + _Outptr_ OrtSessionOptions** out_options); + + /** \brief Set execution mode + * + * Controls whether you want to execute operators in your graph sequentially or in parallel. Usually when the model + * has many branches, setting this option to ExecutionMode.ORT_PARALLEL will give you better performance. + * See [docs/ONNX_Runtime_Perf_Tuning.md] for more details. + * + * \param[in] options + * \param[in] execution_mode + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionExecutionMode, _Inout_ OrtSessionOptions* options, ExecutionMode execution_mode); + + /** \brief Enable profiling for a session + * + * \param[in] options + * \param[in] profile_file_prefix + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableProfiling, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* profile_file_prefix); + + /** \brief Disable profiling for a session + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableProfiling, _Inout_ OrtSessionOptions* options); + + /** \brief Enable the memory pattern optimization + * + * The idea is if the input shapes are the same, we could trace the internal memory allocation + * and generate a memory pattern for future request. So next time we could just do one allocation + * with a big chunk for all the internal memory allocation. + * \note Memory pattern optimization is only available when Sequential Execution mode is enabled (see OrtApi::SetSessionExecutionMode) + * + * \see OrtApi::DisableMemPattern + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableMemPattern, _Inout_ OrtSessionOptions* options); + + /** \brief Disable the memory pattern optimization + * + * \see OrtApi::EnableMemPattern + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableMemPattern, _Inout_ OrtSessionOptions* options); + + /** \brief Enable the memory arena on CPU + * + * Arena may pre-allocate memory for future usage. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableCpuMemArena, _Inout_ OrtSessionOptions* options); + + /** \brief Disable the memory arena on CPU + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisableCpuMemArena, _Inout_ OrtSessionOptions* options); + + /** \brief Set session log id + * + * \param[in] options + * \param[in] logid The log identifier. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogId, _Inout_ OrtSessionOptions* options, const char* logid); + + /** \brief Set session log verbosity level + * + * Applies to session load, initialization, etc + * + * \param[in] options + * \param[in] session_log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogVerbosityLevel, _Inout_ OrtSessionOptions* options, int session_log_verbosity_level); + + /** \brief Set session log severity level + * + * \param[in] options + * \param[in] session_log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionLogSeverityLevel, _Inout_ OrtSessionOptions* options, int session_log_severity_level); + + /** \brief Set the optimization level to apply when loading a graph + * + * Please see https://onnxruntime.ai/docs/performance/model-optimizations/graph-optimizations.html for an in-depth explanation + * \param[in,out] options The session options object + * \param[in] graph_optimization_level The optimization level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetSessionGraphOptimizationLevel, _Inout_ OrtSessionOptions* options, + GraphOptimizationLevel graph_optimization_level); + + /** \brief Sets the number of threads used to parallelize the execution within nodes + * + * When running a single node operation, ex. add, this sets the maximum number of threads to use. + * + * \note If built with OpenMP, this has no effect on the number of threads used. In this case + * use the OpenMP env variables to configure the number of intra op num threads. + * + * \param[in] options + * \param[in] intra_op_num_threads Number of threads to use
+ * A value of 0 will use the default number of threads
+ * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetIntraOpNumThreads, _Inout_ OrtSessionOptions* options, int intra_op_num_threads); + + /** \brief Sets the number of threads used to parallelize the execution of the graph + * + * If nodes can be run in parallel, this sets the maximum number of threads to use to run them in parallel. + * + * \note If sequential execution is enabled this value is ignored, it acts as if it was set to 1. + * + * \param[in] options + * \param[in] inter_op_num_threads Number of threads to use
+ * A value of 0 will use the default number of threads
+ * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetInterOpNumThreads, _Inout_ OrtSessionOptions* options, int inter_op_num_threads); + + /// @} + /// \name OrtCustomOpDomain + /// @{ + + /** \brief Create a custom op domain + * + * \param[in] domain + * \param[out] out Newly created domain. Must be freed with OrtApi::ReleaseCustomOpDomain + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateCustomOpDomain, _In_ const char* domain, _Outptr_ OrtCustomOpDomain** out); + + /** \brief Add a custom op to a custom op domain + * + * \note The OrtCustomOp* pointer must remain valid until the ::OrtCustomOpDomain using it is released + * + * \param[in] custom_op_domain + * \param[in] op + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CustomOpDomain_Add, _Inout_ OrtCustomOpDomain* custom_op_domain, _In_ const OrtCustomOp* op); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Add custom op domain to a session options + * + * \note The OrtCustomOpDomain* must not be deleted until all sessions using it are released + * + * \param[in] options + * \param[in] custom_op_domain + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddCustomOpDomain, _Inout_ OrtSessionOptions* options, _In_ OrtCustomOpDomain* custom_op_domain); + + /** \deprecated Use OrtApi::RegisterCustomOpsLibrary_V2. + * + * Registers custom ops from a shared library. + * + * Loads a shared library (dll on windows, so on linux, etc) named 'library_path' and looks for this entry point: + * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); + * It then passes in the provided session options to this function along with the api base. + * The handle to the loaded library is returned in library_handle. It can be freed by the caller after all sessions using the passed in + * session options are destroyed, or if an error occurs and it is non null. + * + * \param[in] options + * \param[in] library_path + * \param[out] library_handle OS specific handle to the loaded library (Use FreeLibrary on Windows, dlclose on Linux, etc.. to unload) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RegisterCustomOpsLibrary, _Inout_ OrtSessionOptions* options, _In_ const char* library_path, _Outptr_ void** library_handle); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Get input count for a session + * + * This number must also match the number of inputs passed to OrtApi::Run + * + * \see OrtApi::SessionGetInputTypeInfo, OrtApi::SessionGetInputName, OrtApi::Session + * + * \param[in] session + * \param[out] out Number of inputs + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get output count for a session + * + * This number must also match the number of outputs returned by OrtApi::Run + * + * \see OrtApi::SessionGetOutputTypeInfo, OrtApi::SessionGetOutputName, OrtApi::Session + * + * \param[in] session + * \param[out] out Number of outputs + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get overridable initializer count + * + * \see OrtApi::SessionGetOverridableInitializerTypeInfo, OrtApi::SessionGetOverridableInitializerName + * + * \param[in] session + * \param[in] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerCount, _In_ const OrtSession* session, _Out_ size_t* out); + + /** \brief Get input type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get output type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get overridable initializer type information + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) + * \param[out] type_info Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerTypeInfo, _In_ const OrtSession* session, size_t index, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get input name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetInputCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetInputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get output name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOutputCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOutputName, _In_ const OrtSession* session, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get overridable initializer name + * + * \param[in] session + * \param[in] index Must be between 0 (inclusive) and what OrtApi::SessionGetOverridableInitializerCount returns (exclusive) + * \param[in] allocator + * \param[out] value Set to a null terminated UTF-8 encoded string allocated using `allocator`. Must be freed using `allocator`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetOverridableInitializerName, _In_ const OrtSession* session, size_t index, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /// @} + /// \name OrtRunOptions + /// @{ + + /** \brief Create an OrtRunOptions + * + * \param[out] out Returned newly created ::OrtRunOptions. Must be freed with OrtApi::ReleaseRunOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateRunOptions, _Outptr_ OrtRunOptions** out); + + /** \brief Set per-run log verbosity level + * + * \see OrtApi::RunOptionsGetRunLogVerbosityLevel + * + * \param[in] options + * \param[in] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsSetRunLogVerbosityLevel, _Inout_ OrtRunOptions* options, int log_verbosity_level); + + /** \brief Set per-run log severity level + * + * \see OrtApi::RunOptionsGetRunLogSeverityLevel + * + * \param[in] options + * \param[in] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + */ + ORT_API2_STATUS(RunOptionsSetRunLogSeverityLevel, _Inout_ OrtRunOptions* options, int log_severity_level); + + /** \brief Set per-run tag + * + * This is used in a per-run log identifier. + * + * \see OrtApi::RunOptionsGetRunTag + * + * \param[in] options + * \param[in] run_tag The run tag. + */ + ORT_API2_STATUS(RunOptionsSetRunTag, _Inout_ OrtRunOptions* options, _In_ const char* run_tag); + + /** \brief Get per-run log verbosity level + * + * \see OrtApi::RunOptionsSetRunLogVerbosityLevel + * + * \param[in] options + * \param[out] log_verbosity_level \snippet{doc} snippets.dox Log Verbosity Level + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsGetRunLogVerbosityLevel, _In_ const OrtRunOptions* options, + _Out_ int* log_verbosity_level); + + /** \brief Get per-run log severity level + * + * \see OrtApi::RunOptionsSetRunLogSeverityLevel + * + * \param[in] options + * \param[out] log_severity_level The log severity level (refer to ::OrtLoggingLevel for possible values). + */ + ORT_API2_STATUS(RunOptionsGetRunLogSeverityLevel, _In_ const OrtRunOptions* options, _Out_ int* log_severity_level); + + /** \brief Get per-run tag + * + * This is used in a per-run log identifier. + * + * \see OrtApi::RunOptionsSetRunTag + * + * \param[in] options + * \param[out] run_tag The run tag. + * Do not free this value, it is owned by `options`. It will be invalidated if the run tag + * changes (i.e., with OrtApi::RunOptionsSetRunTag) or `options` is freed. + */ + ORT_API2_STATUS(RunOptionsGetRunTag, _In_ const OrtRunOptions* options, _Out_ const char** run_tag); + + /** \brief Set terminate flag + * + * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsSetTerminate, _Inout_ OrtRunOptions* options); + + /** \brief Clears the terminate flag + * + * Used so the OrtRunOptions instance can be used in a new OrtApi::Run call without it instantly terminating + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunOptionsUnsetTerminate, _Inout_ OrtRunOptions* options); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Create a tensor + * + * Create a tensor using a supplied ::OrtAllocator + * + * \param[in] allocator + * \param[in] shape Pointer to the tensor shape dimensions. + * \param[in] shape_len The number of tensor shape dimensions. + * \param[in] type + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** \brief Create a tensor backed by a user supplied buffer + * + * Create a tensor with user's buffer. You can fill the buffer either before calling this function or after. + * p_data is owned by caller. ReleaseValue won't release p_data. + * + * If you wish to transfer ownership of p_data to ORT use CreateTensorWithDataAndDeleterAsOrtValue. + * + * \param[in] info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param[in] p_data Pointer to the data buffer. + * \param[in] p_data_len The number of bytes in the data buffer. + * \param[in] shape Pointer to the tensor shape dimensions. + * \param[in] shape_len The number of tensor shape dimensions. + * \param[in] type The data type. + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorWithDataAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, + size_t p_data_len, _In_ const int64_t* shape, size_t shape_len, ONNXTensorElementDataType type, + _Outptr_ OrtValue** out); + + /** \brief Return if an ::OrtValue is a tensor type + * + * \param[in] value A tensor type (string tensors are not supported) + * \param[out] out Set to 1 iff ::OrtValue is a tensor, 0 otherwise + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(IsTensor, _In_ const OrtValue* value, _Out_ int* out); + + /** \brief Get a pointer to the raw data inside a tensor + * + * Used to read/write/modify the internal tensor data directly. + * \note The returned pointer is valid until the \p value is destroyed. + * + * \param[in] value A tensor type (string tensors are not supported) + * \param[out] out Filled in with a pointer to the internal storage + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorMutableData, _In_ OrtValue* value, _Outptr_ void** out); + + /** \brief Set all strings at once in a string tensor + * + * \param[in,out] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[in] s An array of strings. Each string in this array must be null terminated. + * \param[in] s_len Count of strings in s (Must match the size of \p value's tensor shape) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillStringTensor, _Inout_ OrtValue* value, _In_ const char* const* s, size_t s_len); + + /** \brief Get total byte length for all strings in a string tensor + * + * Typically used with OrtApi::GetStringTensorContent + * + * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[out] len Total byte length of all strings (does not include trailing nulls) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorDataLength, _In_ const OrtValue* value, _Out_ size_t* len); + + /** \brief Get all strings from a string tensor + * + * An example of the results:
+ * Given \p value is a string tensor with the strings { "This" "is" "a" "test" }
+ * \p s must have a size of 11 bytes
+ * \p offsets must have 4 elements
+ * After the call, these values will be filled in:
+ * \p s will contain "Thisisatest"
+ * \p offsets will contain { 0, 4, 6, 7 }
+ * The length of the last string is just s_len - offsets[last] + * + * \param[in] value A tensor of type ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING + * \param[in] s Buffer to sequentially write all tensor strings to. Each string is NOT null-terminated. + * \param[in] s_len Number of bytes of buffer pointed to by \p s (Get it from OrtApi::GetStringTensorDataLength) + * \param[out] offsets Array of start offsets into the strings written to \p s + * \param[in] offsets_len Number of elements in offsets + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorContent, _In_ const OrtValue* value, _Out_writes_bytes_all_(s_len) void* s, + size_t s_len, _Out_writes_all_(offsets_len) size_t* offsets, size_t offsets_len); + + /// @} + /// \name OrtTypeInfo + /// @{ + + /** \brief Get ::OrtTensorTypeAndShapeInfo from an ::OrtTypeInfo + * + * \param[in] type_info + * \param[out] out Do not free this value, it will be valid until type_info is freed. + * If type_info does not represent tensor, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToTensorInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtTensorTypeAndShapeInfo** out); + + /** \brief Get ::ONNXType from ::OrtTypeInfo + * + * \param[in] type_info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetOnnxTypeFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ enum ONNXType* out); + + /// @} + /// \name OrtTensorTypeAndShapeInfo + /// @{ + + /** \brief Create an ::OrtTensorTypeAndShapeInfo object + * + * \param[out] out Returns newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorTypeAndShapeInfo, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Set element type in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] type + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetTensorElementType, _Inout_ OrtTensorTypeAndShapeInfo* info, enum ONNXTensorElementDataType type); + + /** \brief Set shape information in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] dim_values Array with `dim_count` elements. Can contain negative values. + * \param[in] dim_count Number of elements in `dim_values` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetDimensions, OrtTensorTypeAndShapeInfo* info, _In_ const int64_t* dim_values, size_t dim_count); + + /** \brief Get element type in ::OrtTensorTypeAndShapeInfo + * + * \see OrtApi::SetTensorElementType + * + * \param[in] info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorElementType, _In_ const OrtTensorTypeAndShapeInfo* info, + _Out_ enum ONNXTensorElementDataType* out); + + /** \brief Get dimension count in ::OrtTensorTypeAndShapeInfo + * + * \see OrtApi::GetDimensions + * + * \param[in] info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDimensionsCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); + + /** \brief Get dimensions in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[out] dim_values Array with `dim_values_length` elements. On return, filled with the dimensions stored in the ::OrtTensorTypeAndShapeInfo + * \param[in] dim_values_length Number of elements in `dim_values`. Use OrtApi::GetDimensionsCount to get this value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ int64_t* dim_values, + size_t dim_values_length); + + /** \brief Get symbolic dimension names in ::OrtTensorTypeAndShapeInfo + * + * \param[in] info + * \param[in] dim_params Array with `dim_params_length` elements. On return filled with pointers to null terminated strings of the dimension names + * \param[in] dim_params_length Number of elements in `dim_params`. Use OrtApi::GetDimensionsCount to get this value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSymbolicDimensions, _In_ const OrtTensorTypeAndShapeInfo* info, + _Out_writes_all_(dim_params_length) const char* dim_params[], size_t dim_params_length); + + /** \brief Get total number of elements in a tensor shape from an ::OrtTensorTypeAndShapeInfo + * + * Return the number of elements specified by the tensor shape (all dimensions multiplied by each other). + * For 0 dimensions, 1 is returned. If any dimension is less than 0, the result is always -1. + * + * Examples:
+ * [] = 1
+ * [1,3,4] = 12
+ * [2,0,4] = 0
+ * [-1,3,4] = -1
+ * + * \param[in] info + * \param[out] out Number of elements + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorShapeElementCount, _In_ const OrtTensorTypeAndShapeInfo* info, _Out_ size_t* out); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Get type and shape information from a tensor ::OrtValue + * + * \param[in] value Must be a tensor (not a map/sequence/etc) or will return failure + * \param[out] out Newly created ::OrtTensorTypeAndShapeInfo. Must be freed with OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorTypeAndShape, _In_ const OrtValue* value, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Get type information of an OrtValue + * + * \param[in] value + * \param[out] out Newly created ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTypeInfo, _In_ const OrtValue* value, _Outptr_result_maybenull_ OrtTypeInfo** out); + + /** \brief Get ONNXType of an ::OrtValue + * + * \param[in] value + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValueType, _In_ const OrtValue* value, _Out_ enum ONNXType* out); + + /// @} + /// \name OrtMemoryInfo + /// @{ + + /** \brief Create an ::OrtMemoryInfo + * + * \param[in] name + * \param[in] type + * \param[in] id + * \param[in] mem_type + * \param[out] out Newly created ::OrtMemoryInfo. Must be freed with OrtAPi::ReleaseMemoryInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateMemoryInfo, _In_ const char* name, enum OrtAllocatorType type, int id, + enum OrtMemType mem_type, _Outptr_ OrtMemoryInfo** out); + + /** \brief Create an ::OrtMemoryInfo for CPU memory + * + * Special case version of OrtApi::CreateMemoryInfo for CPU based memory. Same as using OrtApi::CreateMemoryInfo with name = "Cpu" and id = 0. + * + * \param[in] type + * \param[in] mem_type + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateCpuMemoryInfo, enum OrtAllocatorType type, enum OrtMemType mem_type, + _Outptr_ OrtMemoryInfo** out); + + /** \brief Compare ::OrtMemoryInfo objects for equality + * + * Compares all settings of each ::OrtMemoryInfo for equality + * + * \param[in] info1 + * \param[in] info2 + * \param[out] out Set to 0 if equal, -1 if not equal + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CompareMemoryInfo, _In_ const OrtMemoryInfo* info1, _In_ const OrtMemoryInfo* info2, _Out_ int* out); + + /** \brief Get name from ::OrtMemoryInfo + * + * \param[in] ptr + * \param[out] out Writes null terminated string to this pointer. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtMemoryInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(MemoryInfoGetName, _In_ const OrtMemoryInfo* ptr, _Out_ const char** out); + + /** \brief Get the id from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetId, _In_ const OrtMemoryInfo* ptr, _Out_ int* out); + + /** \brief Get the ::OrtMemType from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetMemType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtMemType* out); + + /** \brief Get the ::OrtAllocatorType from ::OrtMemoryInfo + */ + ORT_API2_STATUS(MemoryInfoGetType, _In_ const OrtMemoryInfo* ptr, _Out_ OrtAllocatorType* out); + + /// @} + /// \name OrtAllocator + /// @{ + + /// \brief Calls OrtAllocator::Alloc function + ORT_API2_STATUS(AllocatorAlloc, _Inout_ OrtAllocator* ort_allocator, size_t size, _Outptr_ void** out); + /// \brief Calls OrtAllocator::Free function + ORT_API2_STATUS(AllocatorFree, _Inout_ OrtAllocator* ort_allocator, void* p); + /// \brief Calls OrtAllocator::Info function + ORT_API2_STATUS(AllocatorGetInfo, _In_ const OrtAllocator* ort_allocator, _Outptr_ const struct OrtMemoryInfo** out); + + /** \brief Get the default allocator + * + * The default allocator is a CPU based, non-arena. Always returns the same pointer to the same default allocator. + * + * \param[out] out Returned value should NOT be freed + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetAllocatorWithDefaultOptions, _Outptr_ OrtAllocator** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Override session symbolic dimensions + * + * Override symbolic dimensions (by specific denotation strings) with actual values if known at session initialization time to enable + * optimizations that can take advantage of fixed values (such as memory planning, etc) + * + * \param[in] options + * \param[in] dim_denotation + * \param[in] dim_value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddFreeDimensionOverride, _Inout_ OrtSessionOptions* options, _In_ const char* dim_denotation, + _In_ int64_t dim_value); + + /// @} + /// \name OrtValue + /// @{ + + /* Internal information (not seen in Doxygen) + * + * APIs to support non-tensor types - map and sequence. + * Currently only the following types are supported + * Note: the following types should be kept in sync with data_types.h + * Map types + * ========= + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * std::map + * + * Sequence types + * ============== + * std::vector + * std::vector + * std::vector + * std::vector + * std::vector> + * std::vector + */ + + /** \brief Get non tensor data from an ::OrtValue + * + * If `value` is of type ONNX_TYPE_MAP, you need to retrieve the keys and values + * separately. Use index=0 to retrieve keys and index=1 to retrieve values. + * If `value` is of type ONNX_TYPE_SEQUENCE, use index to retrieve the index'th element + * of the sequence. + * + * \param[in] value + * \param[in] index See above for usage based on `value` type + * \param[in] allocator Allocator used to allocate ::OrtValue + * \param[out] out Created ::OrtValue that holds the element requested. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValue, _In_ const OrtValue* value, int index, _Inout_ OrtAllocator* allocator, + _Outptr_ OrtValue** out); + + /** \brief Get non tensor value count from an ::OrtValue + * + * If `value` is of type ONNX_TYPE_MAP 2 will always be returned. For ONNX_TYPE_SEQUENCE + * the number of elements in the sequence will be returned + * + * \param[in] value + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetValueCount, _In_ const OrtValue* value, _Out_ size_t* out); + + /** \brief Create a map or sequence ::OrtValue + * + * To construct a map (ONNX_TYPE_MAP), use num_values = 2 and `in` should be an array of 2 ::OrtValue%s + * representing keys and values.
+ * + * To construct a sequence (ONNX_TYPE_SEQUENCE), use num_values = N where N is the number of the elements in the + * sequence. 'in' should be an array of N ::OrtValue%s. + * + * \param[in] in See above for details + * \param[in] num_values + * \param[in] value_type Must be either ONNX_TYPE_MAP or ONNX_TYPE_SEQUENCE + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateValue, _In_reads_(num_values) const OrtValue* const* in, size_t num_values, + enum ONNXType value_type, _Outptr_ OrtValue** out); + + /** \brief Create an opaque (custom user defined type) ::OrtValue + * + * Constructs an ::OrtValue that contains a value of non-standard type created for + * experiments or while awaiting standardization. ::OrtValue in this case would contain + * an internal representation of the Opaque type. Opaque types are distinguished from + * each other by two strings 1) domain and 2) type name. The combination of the two + * must be unique, so the type representation is properly identified internally. The combination + * must be properly registered from within ORT at both compile/run time or by another API. + * + * To construct the ::OrtValue pass domain and type names, also a pointer to a data container + * the type of which must be known to both ORT and the client program. That data container may or may + * not match the internal representation of the Opaque type. The sizeof(data_container) is passed for + * verification purposes. + * + * \param[in] domain_name Null terminated string of the domain name + * \param[in] type_name Null terminated string of the type name + * \param[in] data_container User pointer Data to populate ::OrtValue + * \param[in] data_container_size Size in bytes of what `data_container` points to + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateOpaqueValue, _In_z_ const char* domain_name, _In_z_ const char* type_name, + _In_ const void* data_container, size_t data_container_size, _Outptr_ OrtValue** out); + + /** \brief Get internal data from an opaque (custom user defined type) ::OrtValue + * + * Copies internal data from an opaque value into a user provided buffer + * + * \see OrtApi::CreateOpaqueValue + * + * \param[in] domain_name Null terminated string of the domain name + * \param[in] type_name Null terminated string of the type name + * \param[in] in The opaque ::OrtValue + * \param[out] data_container Buffer to copy data into + * \param[out] data_container_size Size in bytes of the buffer pointed to by data_container. Must match the size of the internal buffer. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetOpaqueValue, _In_ const char* domain_name, _In_ const char* type_name, _In_ const OrtValue* in, + _Out_ void* data_container, size_t data_container_size); + + /// @} + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get a float stored as an attribute in the graph node + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_float, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ float* out); + + /** \brief Fetch a 64-bit int stored as an attribute in the graph node + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ int64_t* out); + + /** \brief Fetch a string stored as an attribute in the graph node + * + * If `out` is nullptr, the value of `size` is set to the true size of the string + * attribute, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual string attribute's size, + * the value of `size` is set to the true size of the string attribute, the provided memory + * is filled with the attribute's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string attribute's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string attribute + * and a failure status is returned.) + * + * \param[in] info ::OrtKernelInfo instance + * \param[in] name Null terminated string of the name of the attribute + * \param[out] out Pointer to memory where the attribute will be stored + * \param[in,out] size See above comments for details + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_string, _In_ const OrtKernelInfo* info, _In_ const char* name, _Out_ char* out, + _Inout_ size_t* size); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Used for custom operators, get the input count of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetInputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); + + /** \brief Used for custom operators, get the output count of a kernel + * + * \see ::OrtCustomOp + */ + ORT_API2_STATUS(KernelContext_GetOutputCount, _In_ const OrtKernelContext* context, _Out_ size_t* out); + + /** \brief Used for custom operators, get an input of a kernel + * + * The function attempts fetches the input of the kernel. If the input is optional + * and not present, the function returns success and out is set to nullptr. + * + * \param[in] context ::OrtKernelContext instance + * \param[in] index See KernelContext_GetInputCount for boundaries check. + * \param[out] out OrtValue if the input is present otherwise is set nullptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetInput, _In_ const OrtKernelContext* context, _In_ size_t index, + _Out_ const OrtValue** out); + + /** \brief Used for custom operators, get an output of a kernel + * + * The function attempts fetches the output of the kernel. If the output is optional + * and not present, the function returns success and out is set to nullptr. + * + * \param[in] context ::OrtKernelContext instance + * \param[in] index See KernelContext_GetOutputCount for boundaries check. + * \param[in] dim_values output dimensions + * \param[in] dim_count number of dimensions + * \param[out] out a ptr to OrtValue to output otherwise set to nullptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetOutput, _Inout_ OrtKernelContext* context, _In_ size_t index, + _In_ const int64_t* dim_values, size_t dim_count, _Outptr_ OrtValue** out); + + /// @} + /// \name OrtEnv + /// @{ + ORT_CLASS_RELEASE(Env); + /// @} + /// \name OrtStatus + /// @{ + ORT_CLASS_RELEASE(Status); + /// @} + /// \name OrtMemoryInfo + /// @{ + ORT_CLASS_RELEASE(MemoryInfo); + /// @} + /// \name OrtSession + /// @{ + ORT_CLASS_RELEASE(Session); // Don't call ReleaseSession from Dllmain (because session owns a thread pool) + /// @} + /// \name OrtValue + /// @{ + ORT_CLASS_RELEASE(Value); + /// @} + /// \name OrtRunOptions + /// @{ + ORT_CLASS_RELEASE(RunOptions); + /// @} + /// \name OrtTypeInfo + /// @{ + ORT_CLASS_RELEASE(TypeInfo); + /// @} + /// \name OrtTensorTypeAndShapeInfo + /// @{ + ORT_CLASS_RELEASE(TensorTypeAndShapeInfo); + /// @} + /// \name OrtSessionOptions + /// @{ + ORT_CLASS_RELEASE(SessionOptions); + /// @} + /// \name OrtCustomOpDomain + /// @{ + ORT_CLASS_RELEASE(CustomOpDomain); + + /// @} + /// \name OrtTypeInfo + /// @{ + + /** \brief Get denotation from type information + * + * Augments ::OrtTypeInfo to return denotations on the type. + * + * This is used by WinML to determine if an input/output is intended to be an Image or a Tensor. + * + * \param[in] type_info + * \param[out] denotation Pointer to the null terminated denotation string is written to this pointer. This pointer is valid until the object is destroyed or the name is changed, do not free. + * \param[out] len Length in bytes of the string returned in `denotation` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetDenotationFromTypeInfo, _In_ const OrtTypeInfo* type_info, _Out_ const char** const denotation, + _Out_ size_t* len); + + /** \brief Get detailed map information from an ::OrtTypeInfo + * + * This augments ::OrtTypeInfo to return an ::OrtMapTypeInfo when the type is a map. + * The OrtMapTypeInfo has additional information about the map's key type and value type. + * + * This is used by WinML to support model reflection APIs. + * + * \param[out] type_info + * \param[out] out A pointer to the ::OrtMapTypeInfo. Do not free this value. If type_info + * does not contain a map, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToMapTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtMapTypeInfo** out); + + /** \brief Cast ::OrtTypeInfo to an ::OrtSequenceTypeInfo + * + * This api augments ::OrtTypeInfo to return an ::OrtSequenceTypeInfo when the type is a sequence. + * The ::OrtSequenceTypeInfo has additional information about the sequence's element type. + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] type_info + * \param[out] out A pointer to the OrtSequenceTypeInfo. Do not free this value. If type_info + * doesn not contain a sequence, this value will be set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CastTypeInfoToSequenceTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtSequenceTypeInfo** out); + + /// @} + /// \name OrtMapTypeInfo + /// @{ + + /** \brief Get key type from an ::OrtMapTypeInfo + * + * Key types are restricted to being scalar types. + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] map_type_info + * \param[out] out + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetMapKeyType, _In_ const OrtMapTypeInfo* map_type_info, _Out_ enum ONNXTensorElementDataType* out); + + /** \brief Get the value type from an ::OrtMapTypeInfo + * + * \param[in] map_type_info + * \param[out] type_info A copy of the OrtTypeInfo for the map value type. + * The user must free this value with ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetMapValueType, _In_ const OrtMapTypeInfo* map_type_info, _Outptr_ OrtTypeInfo** type_info); + + /// @} + /// \name OrtSequenceTypeInfo + /// @{ + + /** \brief Get element type from an ::OrtSequenceTypeInfo + * + * This is used by WinML to support model reflection APIs. + * + * \param[in] sequence_type_info + * \param[out] type_info A copy of the OrtTypeInfo for the sequence element type. + * The user must free this value with ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSequenceElementType, _In_ const OrtSequenceTypeInfo* sequence_type_info, + _Outptr_ OrtTypeInfo** type_info); + + /// @} + /// \name OrtMapTypeInfo + /// @{ + ORT_CLASS_RELEASE(MapTypeInfo); + /// @} + /// \name OrtSequenceTypeInfo + /// @{ + ORT_CLASS_RELEASE(SequenceTypeInfo); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief End profiling and return filename of the profile data + * + * Profiling is turned on through OrtApi::EnableProfiling + * + * \param[in] session + * \param[in] allocator + * \param[out] out Null terminated string of the filename, allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionEndProfiling, _In_ OrtSession* session, _Inout_ OrtAllocator* allocator, _Outptr_ char** out); + + /** \brief Get ::OrtModelMetadata from an ::OrtSession + * + * \param[in] session + * \param[out] out Newly created ::OrtModelMetadata. Must be freed using OrtApi::ReleaseModelMetadata + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetModelMetadata, _In_ const OrtSession* session, _Outptr_ OrtModelMetadata** out); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** \brief Get `producer name` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetProducerName, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get `graph name` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetGraphName, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Get `domain` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetDomain, _In_ const OrtModelMetadata* model_metadata, _Inout_ OrtAllocator* allocator, + _Outptr_ char** value); + + /** \brief Get `description` from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetDescription, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /** \brief Return data for a key in the custom metadata map in an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[in] allocator + * \param[in] key Null terminated string + * \param[out] value Set to a null terminated string allocated using `allocator`. Must be freed using `allocator` + * `value` will be set to nullptr if the given key is not found in the custom metadata map. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataLookupCustomMetadataMap, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _In_ const char* key, _Outptr_result_maybenull_ char** value); + + /** \brief Get version number from an ::OrtModelMetadata + * + * \param[in] model_metadata + * \param[out] value Set to the version number + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetVersion, _In_ const OrtModelMetadata* model_metadata, _Out_ int64_t* value); + + ORT_CLASS_RELEASE(ModelMetadata); + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an OrtEnv + * + * Create an environment with global threadpools that will be shared across sessions. + * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use + * its own thread pools. + * + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[in] tp_options + * \param[out] out Returned newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithGlobalThreadPools, OrtLoggingLevel log_severity_level, _In_ const char* logid, + _In_ const OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Use global thread pool on a session + * + * Disable using per session thread pool and use the shared global threadpool. + * This should be used in conjunction with OrtApi::CreateEnvWithGlobalThreadPools. + * + * \param[in] options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(DisablePerSessionThreads, _Inout_ OrtSessionOptions* options); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Create an ::OrtThreadingOptions + * + * \param[out] out Newly created ::OrtThreadingOptions. Must be freed with OrtApi::ReleaseThreadingOptions + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateThreadingOptions, _Outptr_ OrtThreadingOptions** out); + + ORT_CLASS_RELEASE(ThreadingOptions); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** + * + * \param[in] model_metadata + * \param[in] allocator + * \param[out] keys Array of null terminated strings (array count = num_keys) allocated using `allocator`. + * The strings and the pointer array must be freed using `allocator` + * `keys` will be set to nullptr if the custom metadata map is empty. + * \param[out] num_keys Set to the number of elements in the `keys` array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetCustomMetadataMapKeys, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_result_buffer_maybenull_(*num_keys) char*** keys, _Out_ int64_t* num_keys); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** + * + * Override symbolic dimensions (by specific name strings) with actual values + * if known at session initialization time to enable optimizations that can + * take advantage of fixed values (such as memory planning, etc) + * + */ + ORT_API2_STATUS(AddFreeDimensionOverrideByName, + _Inout_ OrtSessionOptions* options, _In_ const char* dim_name, + _In_ int64_t dim_value); + + /// @} + /// \name Misc + /// @{ + + /** \brief Get the names of all available providers + * + * \note The providers in the list are not guaranteed to be usable. They may fail to load due to missing system dependencies. + * For example, if the CUDA/cuDNN libraries are not installed, the CUDA provider will report an error when it is added to the session options. + * + * \param[out] out_ptr Set to a pointer to an array of null terminated strings of the available providers. The entries and the + * array itself must be freed using OrtApi::ReleaseAvailableProviders + * \param[out] provider_length Set to the number of entries in the `out_ptr` array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetAvailableProviders, _Outptr_ char*** out_ptr, _Out_ int* provider_length); + + /** \brief Release data from OrtApi::GetAvailableProviders. This API will never fail + * so you can rely on it in a noexcept code. + * + * \param[in] ptr The `out_ptr` result from OrtApi::GetAvailableProviders. + * \param[in] providers_length The `provider_length` result from OrtApi::GetAvailableProviders + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ReleaseAvailableProviders, _In_ char** ptr, + _In_ int providers_length); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Get the length of a single string in a string tensor + * + * \param[in] value A string tensor + * \param[in] index Index of the string in the tensor + * \param[out] out Set to number of bytes of the string element + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorElementLength, _In_ const OrtValue* value, size_t index, _Out_ size_t* out); + + /** \brief Get a single string from a string tensor + * + * \param[in] value A string tensor + * \param[in] s_len Number of bytes in the `s` buffer. Must match the value returned by OrtApi::GetStringTensorElementLength. + * \param[in] index Index of the string in the tensor + * \param[out] s The string element contents in UTF-8 encoding. The string is NOT null-terminated. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetStringTensorElement, _In_ const OrtValue* value, size_t s_len, size_t index, _Out_writes_bytes_all_(s_len) void* s); + + /** \brief Set a single string in a string tensor + * + * \param[in] value A string tensor + * \param[in] s A null terminated UTF-8 encoded string + * \param[in] index Index of the string in the tensor to set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillStringTensorElement, _Inout_ OrtValue* value, _In_ const char* s, size_t index); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Set a session configuration entry as a pair of strings + * + * If a configuration with same key exists, this will overwrite the configuration with the given config_value. + * + * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h + * + * \param[in] options + * \param[in] config_key A null terminated string representation of the config key + * \param[in] config_value A null terminated string representation of the config value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddSessionConfigEntry, _Inout_ OrtSessionOptions* options, + _In_z_ const char* config_key, _In_z_ const char* config_value); + + /// @} + /// \name OrtAllocator + /// @{ + + /** \brief Create an allocator for an ::OrtSession following an ::OrtMemoryInfo + * + * \param[in] session + * \param[in] mem_info valid ::OrtMemoryInfo instance + * \param[out] out Newly created ::OrtAllocator. Must be freed with OrtApi::ReleaseAllocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateAllocator, _In_ const OrtSession* session, _In_ const OrtMemoryInfo* mem_info, + _Outptr_ OrtAllocator** out); + + /** \brief Release an ::OrtAllocator obtained from OrtApi::CreateAllocator + */ + ORT_CLASS_RELEASE(Allocator); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Run a model using Io Bindings for the inputs & outputs + * + * \see OrtApi::Run + * + * \param[in] session + * \param[in] run_options + * \param[in] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RunWithBinding, _Inout_ OrtSession* session, _In_ const OrtRunOptions* run_options, _In_ const OrtIoBinding* binding_ptr); + + /** \brief Create an ::OrtIoBinding instance + * + * An IoBinding object allows one to bind pre-allocated ::OrtValue%s to input names. + * Thus if you want to use a raw on device buffer as input or output you can avoid + * extra copy during runtime. + * + * \param[in] session + * \param[out] out Newly created ::OrtIoBinding. Must be freed with OrtApi::ReleaseIoBinding + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateIoBinding, _Inout_ OrtSession* session, _Outptr_ OrtIoBinding** out); + + /// @} + /// \name OrtIoBinding + /// @{ + + /** \brief Release an ::OrtIoBinding obtained from OrtApi::CreateIoBinding + */ + ORT_CLASS_RELEASE(IoBinding); + + /** \brief Bind an ::OrtValue to an ::OrtIoBinding input + * + * When using OrtApi::RunWithBinding this value is used for the named input + * + * \param[in] binding_ptr + * \param[in] name Name for the model input + * \param[in] val_ptr ::OrtValue of Tensor type. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindInput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); + + /** \brief Bind an ::OrtValue to an ::OrtIoBinding output + * + * When using OrtApi::RunWithBinding this value is used for the named output + * + * \param[in] binding_ptr + * \param[in] name Null terminated string of the model output name + * \param[in] val_ptr ::OrtValue of Tensor type. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindOutput, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtValue* val_ptr); + + /** \brief Bind an ::OrtIoBinding output to a device + * + * Binds the ::OrtValue to a device which is specified by ::OrtMemoryInfo. + * You can either create an instance of ::OrtMemoryInfo with a device id or obtain one from the allocator that you have created/are using + * This is useful when one or more outputs have dynamic shapes and, it is hard to pre-allocate and bind a chunk of + * memory within ::OrtValue ahead of time. + * + * \see OrtApi::RunWithBinding + * + * \param[in] binding_ptr + * \param[in] name Null terminated string of the device name + * \param[in] mem_info_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(BindOutputToDevice, _Inout_ OrtIoBinding* binding_ptr, _In_ const char* name, _In_ const OrtMemoryInfo* mem_info_ptr); + + /** \brief Get the names of an ::OrtIoBinding's outputs + * + * Returns the names of the outputs in the order they were bound. This is useful after running the model + * with bound outputs because the returned names are in order in which output ::OrtValue are returned. This is useful if + * the order of outputs and their names is not known. + * + * \param[in] binding_ptr + * \param[in] allocator Allocator used to allocate continuous buffers for output strings and lengths. + * \param[out] buffer Returns an array of non-null terminated UTF-8 strings. The number of strings stored is returned in the count parameter. + * This buffer is allocated using `allocator` and must be freed using it. + * \param[out] lengths Returns an array of `count` lengths of the strings returned in `buffer` + * This buffer is allocated using `allocator` and must be freed using it. + * \param[out] count Number of strings returned. If `binding_ptr` has no bound outputs, zero is returned, + * no memory allocation is performed and buffer and lengths are set to nullptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetBoundOutputNames, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, + _Out_ char** buffer, _Out_writes_all_(count) size_t** lengths, _Out_ size_t* count); + + /** \brief Get the output ::OrtValue objects from an ::OrtIoBinding + * + * Returns an array of pointers to individually allocated ::OrtValue%s that contain results of a model execution with OrtApi::RunWithBinding + * The array contains the same number of ::OrtValue%s and they are in the same order as they were bound with OrtApi::BindOutput + * or OrtApi::BindOutputToDevice. + * + * The returned ::OrtValue%s must be released using OrtApi::ReleaseValue after they are no longer needed. + * The array is allocated using the specified instance of the allocator and must be freed using the same allocator after + * all the ::OrtValue%s contained therein are individually released. + * + * \param[in] binding_ptr + * \param[in] allocator Allocator used to allocate output array + * \param[out] output Set to the allocated array of allocated ::OrtValue outputs. Set to nullptr if there are 0 outputs. + * \param[out] output_count Set to number of ::OrtValue%s returned + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetBoundOutputValues, _In_ const OrtIoBinding* binding_ptr, _In_ OrtAllocator* allocator, + _Out_writes_all_(output_count) OrtValue*** output, _Out_ size_t* output_count); + + /** \brief Clears any previously set Inputs for an ::OrtIoBinding + */ + void(ORT_API_CALL* ClearBoundInputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /** \brief Clears any previously set Outputs for an ::OrtIoBinding + */ + void(ORT_API_CALL* ClearBoundOutputs)(_Inout_ OrtIoBinding* binding_ptr) NO_EXCEPTION ORT_ALL_ARGS_NONNULL; + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Direct memory access to a specified tensor element + * + * For example, given a tensor with shape of [3,224,224], a pointer to the element at location [2,150,128] can be retrieved + * + * This function only works for numeric type tensors (No strings, etc). + * This is a no-copy method whose returned pointer is valid until the passed in ::OrtValue is free'd. + * + * \param[in] value + * \param[in] location_values Pointer to an array of index values that specify an element's location relative to its shape + * \param[in] location_values_count Number of elements in location_values. Must match the number of elements in the tensor's shape. + * \param[out] out Set to a pointer to the element specified + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(TensorAt, _Inout_ OrtValue* value, const int64_t* location_values, size_t location_values_count, _Outptr_ void** out); + + /// @} + /// \name OrtEnv + /// @{ + + /** \brief Create an allocator and register it with the ::OrtEnv + * + * Enables sharing the allocator between multiple sessions that use the same env instance. + * Lifetime of the created allocator will be valid for the duration of the environment. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * + * See https://onnxruntime.ai/docs/get-started/with-c.html for details. + * + * \param[in] env ::OrtEnv instance + * \param[in] mem_info + * \param[in] arena_cfg Pass nullptr for defaults + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateAndRegisterAllocator, _Inout_ OrtEnv* env, _In_ const OrtMemoryInfo* mem_info, + _In_ const OrtArenaCfg* arena_cfg); + + /** \brief Set language projection + * + * Set the language projection for collecting telemetry data when Env is created. + * + * The default is ORT_PROJECTION_C, which means it will classify the language not in the list to C also. + * + * \param[in] ort_env + * \param[in] projection + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetLanguageProjection, _In_ const OrtEnv* ort_env, _In_ OrtLanguageProjection projection); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Return the time that profiling was started + * + * \note The timer precision varies per platform. On Windows and MacOS, the precision will be ~100ns + * + * \param[in] session + * \param[out] out nanoseconds of profiling's start time + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionGetProfilingStartTimeNs, _In_ const OrtSession* session, _Outptr_ uint64_t* out); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Set global intra-op thread count + * + * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools + * + * \param[in] tp_options + * \param[in] intra_op_num_threads Number of threads, special values:
+ * 0 = Use default thread count
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalIntraOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int intra_op_num_threads); + + /** \brief Set global inter-op thread count + * + * This configures the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools + * + * \param[in] tp_options + * \param[in] inter_op_num_threads Number of threads, special values:
+ * 0 = Use default thread count
+ * 1 = The invoking thread will be used; no threads will be created in the thread pool. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalInterOpNumThreads, _Inout_ OrtThreadingOptions* tp_options, int inter_op_num_threads); + + /** \brief Set global spin control options + * + * This will configure the global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. + * Allow spinning of thread pools when their queues are empty. This will set the value for both + * inter_op and intra_op threadpools. + * + * \param[in] tp_options + * \param[in] allow_spinning Valid values are 0 or 1.
+ * 0 = It won't spin (recommended if CPU usage is high)
+ * 1 = Threadpool will spin to wait for queue to become non-empty + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalSpinControl, _Inout_ OrtThreadingOptions* tp_options, int allow_spinning); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Add a pre-allocated initializer to a session + * + * If a model contains an initializer with a name that is same as the name passed to this call, + * ORT will use this initializer instance instead of deserializing one from the model file. This + * is useful when you want to share the same initializer across sessions. + * + * \param[in] options + * \param[in] name Null terminated string of the initializer name + * \param[in] val ::OrtValue containing the initializer. Its lifetime and the underlying initializer buffer must be + * managed by the user (created using the OrtApi::CreateTensorWithDataAsOrtValue) and it must outlive the session object + * to which it is added. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddInitializer, _Inout_ OrtSessionOptions* options, _In_z_ const char* name, + _In_ const OrtValue* val); + + /// @} + /// \name OrtEnv + /// @{ + + /** + * Create a custom environment with global threadpools and logger that will be shared across sessions. + * Use this in conjunction with OrtApi::DisablePerSessionThreads or else the session will use + * its own thread pools. + * + * \param[in] logging_function A pointer to a logging function. + * \param[in] logger_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `logging_function`. + * \param[in] log_severity_level The log severity level. + * \param[in] logid The log identifier. + * \param[in] tp_options + * \param[out] out Newly created OrtEnv. Must be freed with OrtApi::ReleaseEnv + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateEnvWithCustomLoggerAndGlobalThreadPools, OrtLoggingFunction logging_function, _In_opt_ void* logger_param, OrtLoggingLevel log_severity_level, + _In_ const char* logid, _In_ const struct OrtThreadingOptions* tp_options, _Outptr_ OrtEnv** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append CUDA provider to session options + * + * If CUDA is not available (due to a non CUDA enabled build, or if CUDA is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] cuda_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA, + _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptions* cuda_options); + + /** \brief Append ROCM execution provider to the session options + * + * If ROCM is not available (due to a non ROCM enabled build, or if ROCM is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] rocm_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_ROCM, + _In_ OrtSessionOptions* options, _In_ const OrtROCMProviderOptions* rocm_options); + + /** \brief Append OpenVINO execution provider to the session options + * + * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. + * + * \param[in] options + * \param[in] provider_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO, + _In_ OrtSessionOptions* options, _In_ const OrtOpenVINOProviderOptions* provider_options); + + /// @} + /// \name OrtThreadingOptions + /// @{ + + /** \brief Set threading flush-to-zero and denormal-as-zero + * + * Sets global thread pool options to be used in the call to OrtApi::CreateEnvWithGlobalThreadPools. + * Flush-to-zero and denormal-as-zero are applied to threads in both intra and inter global thread pool. + * \note This option is not needed if the models used have no denormals. Having no denormals is recommended as this option may hurt model accuracy. + * + * \param[in] tp_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalDenormalAsZero, _Inout_ OrtThreadingOptions* tp_options); + + /// @} + /// \name OrtArenaCfg + /// @{ + + /** \deprecated Use OrtApi::CreateArenaCfgV2 + * + * This will create the configuration of an arena that can eventually be used to define an arena based allocator's behavior + * + * \param[in] max_mem Use 0 to allow ORT to choose the default + * \param[in] arena_extend_strategy Use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested + * \param[in] initial_chunk_size_bytes Use -1 to allow ORT to choose the default + * \param[in] max_dead_bytes_per_chunk Use -1 to allow ORT to choose the default + * \param[in] out A pointer to an OrtArenaCfg instance + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateArenaCfg, _In_ size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, + int max_dead_bytes_per_chunk, _Outptr_ OrtArenaCfg** out); + + ORT_CLASS_RELEASE(ArenaCfg); + + /// @} + /// \name OrtModelMetadata + /// @{ + + /** + * Use this to obtain the description of the graph present in the model + * (doc_string field of the GraphProto message within the ModelProto message). + * If it doesn't exist, an empty string will be returned. + * + * \param[in] model_metadata An instance of ::OrtModelMetadata + * \param[in] allocator Allocator used to allocate the string that will be returned back + * \param[out] value Set to a null terminated string allocated using `allocator`. The caller is responsible for freeing it using `allocator` + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(ModelMetadataGetGraphDescription, _In_ const OrtModelMetadata* model_metadata, + _Inout_ OrtAllocator* allocator, _Outptr_ char** value); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append TensorRT provider to session options + * + * If TensorRT is not available (due to a non TensorRT enabled build, or if TensorRT is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] tensorrt_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT, + _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptions* tensorrt_options); + + /// @} + /// \name Misc + /// @{ + + /** \brief Set current GPU device ID + * + * Set the current device id of the GPU execution provider (CUDA/tensorrt/rocm). The device id should be less + * than the total number of devices available. This is only useful when multiple-GPUs are installed and it is + * required to restrict execution to a single GPU. + * + * \param[in] device_id + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetCurrentGpuDeviceId, _In_ int device_id); + + /** \brief Get current GPU device ID + * + * Get the current device id of the GPU execution provider (CUDA/tensorrt/rocm). + * + * \see OrtApi::SetCurrentGpuDeviceId + * + * \param[out] device_id + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetCurrentGpuDeviceId, _In_ int* device_id); + + /// @} + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Fetch an array of int64_t values stored as an attribute in the graph node + * + * + * If `out` is nullptr, the value of `size` is set to the true size of the attribute + * array's size, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual attribute array's size, + * the value of `size` is set to the true size of the attribute array's size, + * the provided memory is filled with the attribute's contents, + * and a success status is returned. + * + * If the `size` parameter is less than the actual attribute array's size and `out` + * is not nullptr, the value of `size` is set to the true size of the attribute array's size + * and a failure status is returned.) + * + * \param[in] info instance + * \param[in] name name of the attribute to be parsed + * \param[out] out pointer to memory where the attribute's contents are to be stored + * \param[in, out] size actual size of attribute array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttributeArray_float, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ float* out, _Inout_ size_t* size); + + /** \brief Fetch an array of int64_t values stored as an attribute in the graph node + * + * If `out` is nullptr, the value of `size` is set to the true size of the attribute + * array's size, and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual attribute array's size, + * the value of `size` is set to the true size of the attribute array's size, + * the provided memory is filled with the attribute's contents, + * and a success status is returned. + * + * If the `size` parameter is less than the actual attribute array's size and `out` + * is not nullptr, the value of `size` is set to the true size of the attribute array's size + * and a failure status is returned.) + * + * \param[in] info instance + * \param[in] name name of the attribute to be parsed + * \param[out] out pointer to memory where the attribute's contents are to be stored + * \param[in, out] size actual size of attribute array + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttributeArray_int64, _In_ const OrtKernelInfo* info, _In_ const char* name, + _Out_ int64_t* out, _Inout_ size_t* size); + + /// @} + /// \name OrtArenaCfg + /// @{ + + /** \brief Create an ::OrtArenaCfg + * + * Create the configuration of an arena that can eventually be used to define an arena based allocator's behavior. + * + * Supported keys are (See https://onnxruntime.ai/docs/get-started/with-c.html for details on what the + * following parameters mean and how to choose these values.): + * "max_mem": Maximum memory that can be allocated by the arena based allocator. + * Use 0 for ORT to pick the best value. Default is 0. + * "arena_extend_strategy": 0 = kNextPowerOfTwo, 1 = kSameAsRequested. + * Use -1 to allow ORT to choose the default. + * "initial_chunk_size_bytes": (Possible) Size of the first allocation in the arena. + * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. + * Ultimately, the first allocation size is determined by the allocation memory request. + * "max_dead_bytes_per_chunk": Threshold of unused memory in an allocated chunk of arena memory after + * crossing which the current chunk is chunked into 2. + * "initial_growth_chunk_size_bytes": (Possible) Size of the second allocation in the arena. + * Only relevant if arena strategy is `kNextPowerOfTwo`. Use -1 to allow ORT to choose the default. + * "max_power_of_two_extend_bytes": The maximum enxtend size if arena strategy is `kNextPowerOfTwo`. + * It is not an allocation limit, it is only a limit for extension when requested byte is less than the limit. + * When requested bytes is more than the limit, allocator will still return as requested. + * Use -1 to allow ORT to choose the default 1GB for max_power_of_two_extend_bytes. + * Ultimately, the allocation size is determined by the allocation memory request. + * Further allocation sizes are governed by the arena extend strategy. + * + * \param[in] arena_config_keys Keys to configure the arena + * \param[in] arena_config_values Values to configure the arena + * \param[in] num_keys Number of keys in `arena_config_keys` and `arena_config_values` + * \param[out] out Newly created ::OrtArenaCfg. Must be freed with OrtApi::ReleaseArenaCfg + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateArenaCfgV2, _In_reads_(num_keys) const char* const* arena_config_keys, + _In_reads_(num_keys) const size_t* arena_config_values, _In_ size_t num_keys, + _Outptr_ OrtArenaCfg** out); + + /// @} + /// \name OrtRunOptions + /// @{ + + /** \brief Set a single run configuration entry as a pair of strings + * + * If a configuration with same key exists, this will overwrite the configuration with the given config_value + * + * The config_key and the format of config_value are defined in onnxruntime_run_options_config_keys.h + * + * \param[in] options + * \param[in] config_key A null terminated string representation of the config key + * \param[in] config_value A null terminated string representation of the config value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(AddRunConfigEntry, _Inout_ OrtRunOptions* options, + _In_z_ const char* config_key, _In_z_ const char* config_value); + + /// @} + /// \name OrtPrepackedWeightsContainer + /// @{ + + /** \brief Create an ::OrtPrepackedWeightsContainer + * + * This container will hold pre-packed buffers of shared initializers for sharing between sessions + * (i.e.) if there are shared initializers that can be shared between sessions, the pre-packed buffers + * of these (if any) may possibly be shared to provide memory footprint savings. Pass this container + * to sessions that you would like to share pre-packed buffers of shared initializers at session + * creation time. + * + * \param[out] out Newly created ::OrtPrepackedWeightsContainer. Must be freed with OrtApi::ReleasePrepackedWeightsContainer + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreatePrepackedWeightsContainer, _Outptr_ OrtPrepackedWeightsContainer** out); + + /** \brief Release OrtPrepackedWeightsContainer instance + * + * \note instance must not be released until the sessions using it are released + */ + ORT_CLASS_RELEASE(PrepackedWeightsContainer); + + /// @} + /// \name OrtSession + /// @{ + + /** \brief Create session with prepacked weights container + * + * Same functionality offered by OrtApi::CreateSession except that a container that contains + * pre-packed weights' buffers is written into/read from by the created session. + * This is useful when used in conjunction with OrtApi::AddInitializer which injects + * shared initializer info into sessions. Wherever possible, the pre-packed versions of these + * shared initializers are cached in this container so that multiple sessions can just re-use + * these instead of duplicating these in memory. + * + * \param[in] env OrtEnv instance instance + * \param[in] model_path Null terminated string of the path (wchar on Windows, char otherwise) + * \param[in] options + * \param[in] prepacked_weights_container + * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionWithPrepackedWeightsContainer, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, + _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, + _Outptr_ OrtSession** out); + + /** \brief Create session from memory with prepacked weights container + * + * Same functionality offered by OrtApi::CreateSessionFromArray except that a container that contains + * pre-packed weights' buffers is written into/read from by the created session. + * This is useful when used in conjunction with OrtApi::AddInitializer which injects + * shared initializer info into sessions. Wherever possible, the pre-packed versions of these + * shared initializers are cached in this container so that multiple sessions can just re-use + * these instead of duplicating these in memory. + * + * \param[in] env + * \param[in] model_data Array of bytes holding the model + * \param[in] model_data_length Number of bytes in `model_data_model` + * \param[in] options + * \param[in] prepacked_weights_container + * \param[out] out Newly created ::OrtSession. Must be freed with OrtApi::ReleaseSession + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSessionFromArrayWithPrepackedWeightsContainer, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, + _Inout_ OrtPrepackedWeightsContainer* prepacked_weights_container, + _Outptr_ OrtSession** out); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Append TensorRT execution provider to the session options + * + * If TensorRT is not available (due to a non TensorRT enabled build), this function will return failure. + * + * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, it takes an + * ::OrtTensorRTProviderOptions which is publicly defined. This takes an opaque ::OrtTensorRTProviderOptionsV2 + * which must be created with OrtApi::CreateTensorRTProviderOptions. + * + * For OrtApi::SessionOptionsAppendExecutionProvider_TensorRT, the user needs to instantiate ::OrtTensorRTProviderOptions + * as well as allocate/release buffers for some members of ::OrtTensorRTProviderOptions. + * Here, OrtApi::CreateTensorRTProviderOptions and Ortapi::ReleaseTensorRTProviderOptions will do the memory management for you. + * + * \param[in] options + * \param[in] tensorrt_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_TensorRT_V2, + _In_ OrtSessionOptions* options, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options); + + /// @} + /// \name OrtTensorRTProviderOptionsV2 + /// @{ + + /** \brief Create an OrtTensorRTProviderOptionsV2 + * + * \param[out] out Newly created ::OrtTensorRTProviderOptionsV2. Must be released with OrtApi::ReleaseTensorRTProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateTensorRTProviderOptions, _Outptr_ OrtTensorRTProviderOptionsV2** out); + + /** \brief Set options in a TensorRT Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#cc + * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtTensorRTProviderOptionsV2 + * and value should be its related range. Recreates the options and only sets the supplied values. + * + * For example, key="trt_max_workspace_size" and value="2147483648" + * + * \param[in] tensorrt_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UpdateTensorRTProviderOptions, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get serialized TensorRT provider options string. + * + * For example, "trt_max_workspace_size=2147483648;trt_max_partition_iterations=10;trt_int8_enable=1;......" + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with OrtApi::CreateAllocator or OrtApi::GetAllocatorWithDefaultOptions + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorRTProviderOptionsAsString, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtTensorRTProviderOptionsV2 + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + */ + void(ORT_API_CALL* ReleaseTensorRTProviderOptions)(_Frees_ptr_opt_ OrtTensorRTProviderOptionsV2* input); + + /// @} + /// \name OrtSessionOptions + /// @{ + + /** \brief Enable custom operators + * + * See onnxruntime-extensions: https://github.com/microsoft/onnxruntime-extensions.git + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(EnableOrtCustomOps, _Inout_ OrtSessionOptions* options); + + /// @} + /// \name OrtAllocator + /// @{ + + /** \brief Register a custom allocator + * + * Enables sharing between multiple sessions that use the same env instance. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * + * The behavior of this is exactly the same as OrtApi::CreateAndRegisterAllocator except + * instead of ORT creating an allocator based on provided info, in this case + * ORT uses the user-provided custom allocator. + * See https://onnxruntime.ai/docs/get-started/with-c.html for details. + * + * \param[in] env + * \param[in] allocator User provided allocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(RegisterAllocator, _Inout_ OrtEnv* env, _In_ OrtAllocator* allocator); + + /** \brief Unregister a custom allocator + * + * It is an error if you provide an ::OrtMemoryInfo not corresponding to any + * registered allocators for sharing. + * + * \param[in] env + * \param[in] mem_info + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UnregisterAllocator, _Inout_ OrtEnv* env, + _In_ const OrtMemoryInfo* mem_info); + + /// @} + /// \name OrtValue + /// @{ + + /** \brief Sets *out to 1 iff an ::OrtValue is a SparseTensor, and 0 otherwise + * + * \param[in] value existing ::OrtValue + * \param[out] out unless an error occurs, contains 1 iff the value contains an instance + * of sparse tensor or 0 otherwise. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(IsSparseTensor, _In_ const OrtValue* value, _Out_ int* out); + + /** \brief Create an ::OrtValue with a sparse tensor that is empty. + * + * Use FillSparseTensor() functions to populate sparse tensor with non-zero values and + * format specific indices data. + * Use ReleaseValue to destroy the sparse tensor, this will also release the buffer inside the output value + * if any was allocated. + * \param[in,out] allocator allocator to use when performing an allocation. Allocation will be performed + * by FillSparseTensor() APIs. The lifespan of the allocator instance must eclipse the lifespan + * this sparse tensor instance as the same allocator will be used to free memory. + * \param[in] dense_shape shape of the original dense tensor + * \param[in] dense_shape_len number of shape dimensions being passed + * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx + * \param[out] out Should be freed by calling ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSparseTensorAsOrtValue, _Inout_ OrtAllocator* allocator, _In_ const int64_t* dense_shape, + size_t dense_shape_len, ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and COO indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape pointer to values shape array + * \param[in] values_shape_len length of the values_shape + * \param[in] values pointer to an array of values. For strings, pass const char**. + * \param[in] indices_data pointer to a location of COO indices + * \param[in] indices_num number of COO indices + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorCoo, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* indices_data, size_t indices_num); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and CSR indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape pointer to values shape array + * \param[in] values_shape_len length of the values_shape + * \param[in] values - pointer to an array of values. For strings, pass const char**. + * \param[in] inner_indices_data pointer to a location of CSR inner indices + * \param[in] inner_indices_num number of CSR inner indices + * \param[in] outer_indices_data pointer to a location of CSR outer indices + * \param[in] outer_indices_num number of CSR outer indices + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorCsr, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* inner_indices_data, size_t inner_indices_num, + _In_ const int64_t* outer_indices_data, size_t outer_indices_num); + + /** + * This fills populates an empty tensor that was created using OrtApi::CreateSparseTensorAsOrtValue. + * This will allocate required memory and copy the supplied NNZ values and BlockSparse indices into that memory allocation. + * Memory allocation is performed using the allocator that was specified with OrtApi::CreateSparseTensorAsOrtValue. + * + * \param[in,out] ort_value ::OrtValue to populate with data + * \param[in] data_mem_info serves to identify the location of the data to be copied. If the allocator specified + * at the creation time has memory info that is not the same as mem_info argument to this function a X-device copy will be performed. + * String data is assumed to be on CPU and will only be copied into a CPU allocated buffer. + * \param[in] values_shape + * \param[in] values_shape_len + * \param[in] values structure with values information + * \param[in] indices_shape_data pointer to a location of indices shape + * \param[in] indices_shape_len length of the block sparse indices shape + * \param[in] indices_data pointer to a location of indices data. Shape will determine the length of the indices data. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(FillSparseTensorBlockSparse, _Inout_ OrtValue* ort_value, _In_ const OrtMemoryInfo* data_mem_info, + _In_ const int64_t* values_shape, size_t values_shape_len, _In_ const void* values, + _In_ const int64_t* indices_shape_data, size_t indices_shape_len, + _In_ const int32_t* indices_data); + + /** + * Create an ::OrtValue with a sparse tensor. This is the first step. + * Next, use UseIndices() functions to supply sparse tensor with + * format specific indices data and set its sparse format to a specific enum value. + * This will not perform memory allocations. It will + * use supplied user buffer which should outlive the created sparse tensor. + * Use OrtApi::ReleaseValue to destroy the sparse tensor. It would not release the supplied values buffer. + * This function can not be used to map strings from the user allocated memory. Strings must always be copied + * and have UTF-8 encoding. Therefore, use OrtApi::CreateSparseTensorAsOrtValue above and then fill it with data + * using appropriate Make*() function. + * + * \param[in] info memory info where sparse values reside. + * \param[in,out] p_data pointer to a user allocated buffer with values. To create a full sparse tensor with no non-zero + * values, pass nullptr + * \param[in] dense_shape shape of the original dense tensor + * \param[in] dense_shape_len number of shape dimensions being passed + * \param[in] values_shape shape of the values data. To create a fully sparse tensor with no non-zero values, + * pass {0} shape. + * \param[in] values_shape_len number of values shape dimensions + * \param[in] type must be one of TENSOR_ELEMENT_DATA_TYPE_xxxx + * \param[out] out Should be freed by calling ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(CreateSparseTensorWithValuesAsOrtValue, _In_ const OrtMemoryInfo* info, _Inout_ void* p_data, + _In_ const int64_t* dense_shape, size_t dense_shape_len, + _In_ const int64_t* values_shape, size_t values_shape_len, + ONNXTensorElementDataType type, _Outptr_ OrtValue** out); + + /** + * This assigns Coo format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_COO. This will not allocate any additional memory for data. The life span of + * indices_data buffer should eclipse the life span of this ::OrtValue. + * + * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in,out] indices_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] indices_num number of COO indices. Should either be 0 for fully sparse tensors, be equal + * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue for 1-D {nnz} indices or + * be twice as number of nnz values for a 2-D indices {nnz, 2} + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseCooIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* indices_data, size_t indices_num); + + /** + * The assigns CSR format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_CSRC. This will not allocate any additional memory for data. The life spans of + * inner_data and outer_data buffers should eclipse the life span of this ::OrtValue. + * + * \param[in,out] ort_value ::OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in,out] inner_data pointer to a user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] inner_num number of inner CSR indices. Should either be 0 for fully sparse tensors or be equal + * to the number of nnz values specified to OrtApi::CreateSparseTensorWithValuesAsOrtValue. + * \param[in,out] outer_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. + * \param[in] outer_num number of CSR outer indices. Should either be 0 for fully sparse tensors or + * equal to rows + 1 of the dense shape. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseCsrIndices, _Inout_ OrtValue* ort_value, _Inout_ int64_t* inner_data, size_t inner_num, + _Inout_ int64_t* outer_data, size_t outer_num); + + /** + * The assigns BlockSparse format indices to the SparseTensor that was created by + * OrtApi::CreateSparseTensorWithValuesAsOrtValue above. It also sets OrtSparseFormat to + * ORT_SPARSE_BLOCK_SPARSE. This will not allocate any additional memory for data. The life span of + * indices_data buffer must eclipse the lifespan of this ::OrtValue. + * + * \param[in,out] ort_value OrtValue instance constructed with OrtApi::CreateSparseTensorWithValuesAsOrtValue + * \param[in] indices_shape pointer to indices shape. Use {0} for fully sparse tensors + * \param[in] indices_shape_len length of the indices shape + * \param[in,out] indices_data pointer to user pre-allocated buffer or nullptr for fully sparse tensors. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(UseBlockSparseIndices, _Inout_ OrtValue* ort_value, const int64_t* indices_shape, size_t indices_shape_len, _Inout_ int32_t* indices_data); + + /** \brief Returns sparse tensor format enum iff a given ort value contains an instance of sparse tensor. + * + * \param[in] ort_value ::OrtValue that contains an instance of sparse tensor + * \param[out] out pointer to out parameter + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorFormat, _In_ const OrtValue* ort_value, _Out_ enum OrtSparseFormat* out); + + /** \brief Returns data type and shape of sparse tensor values (nnz) iff ::OrtValue contains a SparseTensor. + * + * \param[in] ort_value An ::OrtValue that contains a fully constructed sparse tensor + * \param[out] out Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorValuesTypeAndShape, _In_ const OrtValue* ort_value, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Returns numeric data for sparse tensor values (nnz). For string values use GetStringTensor*(). + * + * \param[in] ort_value an instance of ::OrtValue containing sparse tensor + * \param[out] out returns a pointer to values data. Do not attempt to free this ptr. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorValues, _In_ const OrtValue* ort_value, _Outptr_ const void** out); + + /** \brief Returns data type, shape for the type of indices specified by indices_format. + * + * \param[in] ort_value ::OrtValue containing sparse tensor. + * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse + * tensor does not contain. + * \param[out] out an instance of ::OrtTensorTypeAndShapeInfo. Must be freed by OrtApi::ReleaseTensorTypeAndShapeInfo + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorIndicesTypeShape, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Outptr_ OrtTensorTypeAndShapeInfo** out); + + /** \brief Returns indices data for the type of the indices specified by indices_format + * + * \param[in] ort_value ::OrtValue containing sparse tensor. + * \param[in] indices_format One of the indices formats. It is an error to request a format that the sparse tensor does not contain. + * \param[out] num_indices Pointer to where the number of indices entries is returned + * \param[out] indices Returned pointer to the indices data. Do not free the returned pointer as it refers to internal data owned by the ::OrtValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetSparseTensorIndices, _In_ const OrtValue* ort_value, enum OrtSparseIndicesFormat indices_format, _Out_ size_t* num_indices, _Outptr_ const void** indices); + /// @} + /// \name OrtSessionOptions + /// @{ + + /** + * \brief Sets out to 1 iff an optional type OrtValue has an element, 0 otherwise (OrtValue is None) + * Use this API to find if the optional type OrtValue is None or not. + * If the optional type OrtValue is not None, use the OrtValue just like any other OrtValue. + * For example, if you get an OrtValue that corresponds to Optional(tensor) and + * if HasValue() returns true, use it as tensor and so on. + + * \param[in] value Input OrtValue. + * \param[out] out indicating if the input OrtValue contains data (1) or if it is a None (0) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(HasValue, _In_ const OrtValue* value, _Out_ int* out); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Used for custom operators, gets the GPU compute stream to use to launch the custom a GPU kernel + * \see ::OrtCustomOp + * \param[in] context OrtKernelContext instance + * \param[out] out Returns pointer to a GPU compute stream that can be used to launch the custom GPU kernel. + * If retrieving the GPU compute stream is not relevant (GPU not enabled in the build, kernel partitioned to + * some other EP), then a nullptr is returned as the output param. + * Do not free or mutate the returned pointer as it refers to internal data owned by the underlying session. + * Only use it for custom kernel launching. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelContext_GetGPUComputeStream, _In_ const OrtKernelContext* context, _Outptr_ void** out); + + /// @} + /// \name GetTensorMemoryInfo + /// @{ + /** \brief Returns a pointer to the ::OrtMemoryInfo of a Tensor + * \param[in] value ::OrtValue containing tensor. + * \param[out] mem_info ::OrtMemoryInfo of the tensor. Do NOT free the returned pointer. It is valid for the lifetime of the ::OrtValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetTensorMemoryInfo, _In_ const OrtValue* value, _Out_ const OrtMemoryInfo** mem_info); + + /// @} + /// \name GetExecutionProviderApi + /// @{ + /** \brief Get a pointer to the requested version of the Execution Provider specific + * API extensions to the OrtApi + * \param[in] provider_name The name of the execution provider name. Currently only the following + * values are supported: "DML". + * \param[in] version Must be ::ORT_API_VERSION. + * \param[out] provider_api A void pointer containing a reference to the execution provider versioned api structure. + * For example, the provider_api pointer can be cast to the OrtDmlApi* when the provider_name is "DML". + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetExecutionProviderApi, _In_ const char* provider_name, _In_ uint32_t version, _Outptr_ const void** provider_api); + + /// @} + + /// \name SessionOptions + /// @{ + /** \brief Set custom thread creation function + * + * \param[in] options Session options + * \param[in] ort_custom_create_thread_fn Custom thread creation function + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomCreateThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /** \brief Set creation options for custom thread + * + * \param[in] options Session options + * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomThreadCreationOptions, _Inout_ OrtSessionOptions* options, _In_ void* ort_custom_thread_creation_options); + + /** \brief Set custom thread join function + * + * \param[in] options Session options + * \param[in] ort_custom_join_thread_fn Custom join thread function, must not be nullptr when ort_custom_create_thread_fn is set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SessionOptionsSetCustomJoinThreadFn, _Inout_ OrtSessionOptions* options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); + /// @} + + /// \name OrtThreadingOptions + /// @{ + /** \brief Set custom thread creation function for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_create_thread_fn Custom thread creation function + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomCreateThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /** \brief Set custom thread creation options for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_thread_creation_options Custom thread creation options (can be nullptr) + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomThreadCreationOptions, _Inout_ OrtThreadingOptions* tp_options, _In_ void* ort_custom_thread_creation_options); + + /** \brief Set custom thread join function for global thread pools + * + * \param[inout] tp_options + * \param[in] ort_custom_join_thread_fn Custom thread join function, must not be nullptr when global ort_custom_create_thread_fn is set + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SetGlobalCustomJoinThreadFn, _Inout_ OrtThreadingOptions* tp_options, _In_ OrtCustomJoinThreadFn ort_custom_join_thread_fn); + /// @} + + /** \brief Synchronize bound inputs. The call may be necessary for some providers, such as cuda, + * in case the system that allocated bound memory operated on a different stream. However, the + * operation is provider specific and could be a no-op. + * + * \param[inout] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SynchronizeBoundInputs, _Inout_ OrtIoBinding* binding_ptr); + + /** \brief Synchronize bound outputs. The call may be necessary for some providers, such as cuda, + * in case the system that allocated bound memory operated on a different stream. However, the + * operation is provider specific and could be a no-op. + * + * \param[inout] binding_ptr + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(SynchronizeBoundOutputs, _Inout_ OrtIoBinding* binding_ptr); + + /// \name OrtSessionOptions + /// @{ + + /** \brief Append CUDA execution provider to the session options + * + * If CUDA is not available (due to a non CUDA enabled build), this function will return failure. + * + * This is slightly different from OrtApi::SessionOptionsAppendExecutionProvider_CUDA, it takes an + * ::OrtCUDAProviderOptions which is publicly defined. This takes an opaque ::OrtCUDAProviderOptionsV2 + * which must be created with OrtApi::CreateCUDAProviderOptions. + * + * For OrtApi::SessionOptionsAppendExecutionProvider_CUDA, the user needs to instantiate ::OrtCUDAProviderOptions + * as well as allocate/release buffers for some members of ::OrtCUDAProviderOptions. + * Here, OrtApi::CreateCUDAProviderOptions and Ortapi::ReleaseCUDAProviderOptions will do the memory management for you. + * + * \param[in] options + * \param[in] cuda_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CUDA_V2, + _In_ OrtSessionOptions* options, _In_ const OrtCUDAProviderOptionsV2* cuda_options); + + /// @} + /// \name OrtCUDAProviderOptionsV2 + /// @{ + + /** \brief Create an OrtCUDAProviderOptionsV2 + * + * \param[out] out Newly created ::OrtCUDAProviderOptionsV2. Must be released with OrtApi::ReleaseCudaProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(CreateCUDAProviderOptions, _Outptr_ OrtCUDAProviderOptionsV2** out); + + /** \brief Set options in a CUDA Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#configuration-options + * to know the available keys and values. Key should be in null terminated string format of the member of ::OrtCUDAProviderOptionsV2 + * and value should be its related range. Recreates the options and only sets the supplied values. + * + * For example, key="device_id" and value="0" + * + * \param[in] cuda_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(UpdateCUDAProviderOptions, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized CUDA provider options string. + * + * For example, "device_id=0;arena_extend_strategy=0;......" + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(GetCUDAProviderOptionsAsString, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtCUDAProviderOptionsV2 + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + * + * \since Version 1.11. + */ + void(ORT_API_CALL* ReleaseCUDAProviderOptions)(_Frees_ptr_opt_ OrtCUDAProviderOptionsV2* input); + + /// @} + + /** \brief Append MIGraphX provider to session options + * + * If MIGraphX is not available (due to a non MIGraphX enabled build, or if MIGraphX is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] migraphx_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.11. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_MIGraphX, + _In_ OrtSessionOptions* options, _In_ const OrtMIGraphXProviderOptions* migraphx_options); + + /** \brief Replace initialized Tensors with external data with the data provided in initializers. + * + * The function will find the initialized TensorProtos with external data in the graph with the provided names and + * replace them with the provided tensors. The API verifies that the TensorProto being replaced + * has an external data reference and has the same name, dimensions and data type as its replacement. The replacement + * will occur before any of the optimizations take place. The data will be copied into the graph + * since TensorProto can't refer to the user provided buffers. + * + * Once the model has been loaded, the OrtValue(s) added to SessionOptions instance will be removed + * from the internal SessionOptions copy to save memory, the user provided buffers can then be deallocated + * and the SessionOptions instance that refers to them can be destroyed. + * + * \param[in] options + * \param[in] initializer_names Array of null terminated UTF-8 encoded strings of the initializers names. + * \param[in] initializers Array of ::OrtValue type + * \param[in] num_initializers Number of elements in the initializer_names and initializers + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.12. + */ + ORT_API2_STATUS(AddExternalInitializers, _In_ OrtSessionOptions* options, + _In_reads_(num_initializers) const char* const* initializer_names, + _In_reads_(num_initializers) const OrtValue* const* initializers, size_t num_initializers); + + /** \brief: Create attribute of onnxruntime operator + * + * \param[in] name Name of the attribute + * \param[in] data Data content of the attribute + * \param[in] len Number of bytes stored in data + * \param[in] type Data type + * \param[out] op_attr Attribute that has been created, which must be released by OrtApi::ReleaseOpAttr + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CreateOpAttr, + _In_ const char* name, + _In_ const void* data, + _In_ int len, + _In_ OrtOpAttrType type, + _Outptr_ OrtOpAttr** op_attr); + + /* \brief: Release op attribute + * + * \param[in] opAttr Attribute created by OrtApi::CreateOpAttr + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(OpAttr); + + /** \brief: Create onnxruntime native operator + * + * \param[in] info Kernel info + * \param[in] op_name Operator name + * \param[in] domain Operator domain + * \param[in] version Operator opset version + * \param[in] type_constraint_names Name of the type contraints, such as "T" or "T1" + * \param[in] type_constraint_values Type of each contraints + * \param[in] type_constraint_count Number of contraints + * \param[in] attr_values Attributes used to initialize the operator + * \param[in] attr_count Number of the attributes + * \param[in] input_count Number of inputs + * \param[in] output_count Number of outputs + * \param[out] ort_op Operator that has been created + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CreateOp, + _In_ const OrtKernelInfo* info, + _In_z_ const char* op_name, + _In_z_ const char* domain, + int version, + _In_reads_(type_constraint_count) const char** type_constraint_names, + _In_reads_(type_constraint_count) const ONNXTensorElementDataType* type_constraint_values, + int type_constraint_count, + _In_reads_(attr_count) const OrtOpAttr* const* attr_values, + int attr_count, + int input_count, + int output_count, + _Outptr_ OrtOp** ort_op); + + /** \brief: Invoke the operator created by OrtApi::CreateOp + * The inputs must follow the order as specified in onnx specification + * + * \param[in] context Kernel context + * \param[in] ort_op Operator that has been created + * \param[in] input_values Array of inputs + * \param[in] input_count Number of inputs + * \param[in] output_values Array of outputs + * \param[in] output_count Number of outputs + * + * \since Version 1.12. + */ + ORT_API2_STATUS(InvokeOp, + _In_ const OrtKernelContext* context, + _In_ const OrtOp* ort_op, + _In_ const OrtValue* const* input_values, + _In_ int input_count, + _Inout_ OrtValue* const* output_values, + _In_ int output_count); + + /* \brief: Release an onnxruntime operator + * + * \param[in] Op Operator created by OrtApi::CreateOp + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(Op); + + /** \brief: Append execution provider to the session options. + * \param[in] options + * \param[in] provider_name - provider to add. + * \param[in] provider_options_keys - keys to configure the provider options + * \param[in] provider_options_values - values to configure the provider options + * \param[in] num_keys - number of keys passed in + * + * Currently supported provider names: + * QNNExecutionProvider (or QNN) + * OpenVINOExecutionProvider (or OpenVINO) + * XnnpackExecutionProvider (or XNNPACK) + * WebNNExecutionProvider (or WEBNN) + * WebGpuExecutionProvider (or WebGPU) + * AzureExecutionProvider (or AZURE) + * JsExecutionProvider (or JS) + * VitisAIExecutionProvider (or VitisAI) + * CoreMLExecutionProvider (or CoreML) + * + * Note: If an execution provider has a dedicated SessionOptionsAppendExecutionProvider_ function + * that should be used to add it. + * + * QNN supported keys: + * "backend_type": Type of QNN backend. Specifies a backend path that is the associated QNN backend library file + * name. E.g., given backend type "htp", on Windows, the backend path would be "QnnHtp.dll", and on other + * platforms, it would be "libQnnHtp.so". Mutually exclusive with "backend_path". + * Available options: + * -# "cpu" + * -# "gpu" + * -# "htp": Default. + * -# "saver" + * "backend_path": File path to QNN backend library. Mutually exclusive with "backend_type". + * "profiling_level": QNN profiling level. + * Available options: + * -# "off": Default. + * -# "basic" + * -# "detailed" + * "profiling_file_path": QNN profiling file path if ETW not enabled. + * "rpc_control_latency": QNN RPC control latency. + * "vtcm_mb": QNN VTCM size in MB. default to 0(not set). + * "htp_performance_mode": QNN performance mode. + * Available options: + * -# "burst" + * -# "balanced" + * -# "default": Default. + * -# "high_performance" + * -# "high_power_saver" + * -# "low_balanced" + * -# "extreme_power_saver" + * -# "low_power_saver" + * -# "power_saver" + * -# "sustained_high_performance" + * "qnn_saver_path": File path to the QNN Saver backend library. If specified, QNN Saver will be enabled and will + * dump QNN API calls to disk for replay/debugging. QNN Saver produces incorrect model inference results and + * may alter model/EP partitioning. Use only for debugging. + * "qnn_context_priority": QNN context priority. + * Available options: + * -# "low" + * -# "normal": Default. + * -# "normal_high" + * -# "high" + * "htp_graph_finalization_optimization_mode": Set the optimization mode for graph finalization on the HTP backend. + * Available options: + * -# "0": Default. + * -# "1": Faster preparation time, less optimal graph. + * -# "2": Longer preparation time, more optimal graph. + * -# "3": Longest preparation time, most likely even more optimal graph. See QNN SDK documentation for specific + * details. + * "soc_model": The SoC model number. Refer to the QNN SDK documentation for valid values. + * Defaults to "0" (unknown). + * "htp_arch": The minimum HTP architecture the driver will use to select compatible QNN operators. + * Available options: + * -# "0": Default (none). + * -# "68" + * -# "69" + * -# "73" + * -# "75" + * "device_id": The ID of the device to use when setting 'htp_arch'. Defaults to "0" (for single device). + * "enable_htp_fp16_precision": Used for float32 model for HTP backend. + * Enable the float32 model to be inferenced with fp16 precision. Otherwise, it will be fp32 precision. + * -# "0": With fp32 precision. + * -# "1": Default. With fp16 precision. + * "offload_graph_io_quantization": Offload graph input quantization and graph output dequantization to another + * execution provider (typically CPU EP). + * -# "0": Disabled. QNN EP will handle quantization and dequantization of graph I/O. + * -# "1": Enabled. This is the default value. + * "enable_htp_spill_fill_buffer": Enable HTP spill fill buffer setting. The flag is used while generating context + * binary. + * -# "0": Default. Disabled. + * -# "1": Enabled. + * "enable_htp_shared_memory_allocator": Enable the QNN HTP shared memory allocator. Requires libcdsprpc.so/dll to + * be available. + * -# "0": Default. Disabled. + * -# "1": Enabled. + * "dump_json_qnn_graph": Set to "1" to dump QNN graphs generated by QNN EP as JSON files. Each graph partition + * assigned to QNN EP is dumped to a separate file. + * "json_qnn_graph_dir": Directory in which to dump QNN JSON graphs. If not specified, QNN graphs are dumped in the + * program's current working directory. Ignored if "dump_json_qnn_graph" is not set. + * + * XNNPACK supported keys: + * "intra_op_num_threads": number of thread-pool size to use for XNNPACK execution provider. + * default value is 0, which means to use the session thread-pool size. + * + * \since Version 1.12. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider, _In_ OrtSessionOptions* options, + _In_ const char* provider_name, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /* \brief: Get a copy of kernel info + * + * \param[in] info Kernel info + * \param[out] info_copy Copy of kernel info + * + * \since Version 1.12. + */ + ORT_API2_STATUS(CopyKernelInfo, + _In_ const OrtKernelInfo* info, + _Outptr_ OrtKernelInfo** info_copy); + + /* \brief: Release kernel info + * + * \param[in] KernelInfo A copy of kernel info returned by CopyKernelInfo + * + * \since Version 1.12. + */ + ORT_CLASS_RELEASE(KernelInfo); + + /// \name Ort Training + /// @{ + /** \brief Gets the Training C Api struct + * + * Call this function to access the ::OrtTrainingApi structure that holds pointers to functions that enable + * training with onnxruntime. + * \note A NULL pointer will be returned and no error message will be printed if the training api + * is not supported with this build. A NULL pointer will be returned and an error message will be + * printed if the provided version is unsupported, for example when using a runtime older than the + * version created with this header file. + * + * \param[in] version Must be ::ORT_API_VERSION + * \return The ::OrtTrainingApi struct for the version requested. + * + * \since Version 1.13 + */ + const OrtTrainingApi*(ORT_API_CALL* GetTrainingApi)(uint32_t version)NO_EXCEPTION; + + /// @} + + /** \brief Append CANN provider to session options + * + * If CANN is not available (due to a non CANN enabled build, or if CANN is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] cann_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_CANN, + _In_ OrtSessionOptions* options, _In_ const OrtCANNProviderOptions* cann_options); + + /** \brief Create an OrtCANNProviderOptions + * + * \param[out] out created ::OrtCANNProviderOptions. Must be released with OrtApi::ReleaseCANNProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(CreateCANNProviderOptions, _Outptr_ OrtCANNProviderOptions** out); + + /** \brief Set options in a CANN Execution Provider. + * + * \param[in] cann_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(UpdateCANNProviderOptions, _Inout_ OrtCANNProviderOptions* cann_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get serialized CANN provider options string. + * + * \param[in] cann_options OrtCANNProviderOptions instance + * \param[in] allocator a ptr to an instance of OrtAllocator obtained with CreateAllocator() + * or GetAllocatorWithDefaultOptions(), the specified allocator will be used to allocate + * continuous buffers for output strings and lengths. + * \param[out] ptr is a UTF-8 null terminated string allocated using 'allocator'. + * The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.13. + */ + ORT_API2_STATUS(GetCANNProviderOptionsAsString, _In_ const OrtCANNProviderOptions* cann_options, + _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an OrtCANNProviderOptions + * + * \param[in] input The pointer of OrtCANNProviderOptions which will been deleted + * + * \since Version 1.13. + */ + void(ORT_API_CALL* ReleaseCANNProviderOptions)(_Frees_ptr_opt_ OrtCANNProviderOptions* input); + + /* \brief Get OrtDevice type from MemoryInfo + * + * \since Version 1.14 + */ + void(ORT_API_CALL* MemoryInfoGetDeviceType)(_In_ const OrtMemoryInfo* ptr, _Out_ OrtMemoryInfoDeviceType* out); + + /* \brief Update the OrtEnv instance with custom log severity level + * + * \param[in] ort_env The OrtEnv instance being used + * \param[in] log_severity_level The log severity level. + * + * \since Version 1.14. + */ + ORT_API2_STATUS(UpdateEnvWithCustomLogLevel, _In_ OrtEnv* ort_env, OrtLoggingLevel log_severity_level); + + /* \brief Set affinities for intra op threads + * + * Affinity string follows format: + * logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id + * Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. + * e.g. 1,2,3;4,5 + * specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. + * To ease the configuration, an "interval" is also allowed: + * e.g. 1-8;8-16;17-24 + * orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. + * Note: + * 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, + * ort does not set affinity on the main thread which is started and managed by the calling app; + * 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, + * an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. + * Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. + * + * \since Version 1.14 + */ + ORT_API2_STATUS(SetGlobalIntraOpThreadAffinity, _Inout_ OrtThreadingOptions* tp_options, const char* affinity_string); + + /** \brief Register custom ops from a shared library. + * + * Loads a shared library (.dll on windows, .so on linux, etc) named 'library_name' and looks for this entry point: + * OrtStatus* RegisterCustomOps(OrtSessionOptions * options, const OrtApiBase* api); + * It then passes in the provided session options to this function along with the api base. + * + * The handle to the loaded library is automatically released by ORT when the last OrtSession that references the + * library handle is released. If no OrtSession is created, then the library handle is released when the provided + * OrtSessionOptions is released. + * + * \param[in] options The session options. + * \param[in] library_name The name of the shared library to load and register. Refer to OS-specific dynamic library + * loading utilities (e.g., LoadLibraryEx on Windows or dlopen on Linux/MacOS) for information + * on the format of library names and search paths. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(RegisterCustomOpsLibrary_V2, _Inout_ OrtSessionOptions* options, _In_ const ORTCHAR_T* library_name); + + /** \brief Register custom ops by calling a RegisterCustomOpsFn function. + * + * Searches for registration_func_name and if found calls it. + * + * The library containing the function must either be linked against or previously loaded by the executable. + * + * If you want ONNX Runtime to load the library and manage its lifetime, use RegisterCustomOpsLibrary_V2. + * + * RegisterCustomOpsUsingFunction can be used in scenarios where it may not be possible for ONNX Runtime to load + * the library from a path. e.g. mobile platforms where the library must be linked into the app. + * + * The registration function must have the signature of RegisterCustomOpsFn: + * OrtStatus* (*fn)(OrtSessionOptions* options, const OrtApiBase* api); + * + * See https://onnxruntime.ai/docs/reference/operators/add-custom-op.html for details on how the registration + * function should be implemented. + * + * \param[in] options OrtSessionOptions that is passed through as the first argument in the call to the + * registration function. + * \param[in] registration_func_name Name of registration function to use. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(RegisterCustomOpsUsingFunction, _Inout_ OrtSessionOptions* options, + _In_ const char* registration_func_name); + + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get the number of inputs from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the number of inputs + * during kernel/session creation. + * + * \param[in] info Instance of ::OrtKernelInfo. + * \param[out] out Pointer to variable assigned with the result on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); + + /** \brief Get the number of outputs from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the number of outputs + * during kernel/session creation. + * + * \param[in] info Instance of ::OrtKernelInfo. + * \param[out] out Pointer to variable assigned with the result on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputCount, _In_ const OrtKernelInfo* info, _Out_ size_t* out); + + /** \brief Get the name of a ::OrtKernelInfo's input. + * + * Used in the CreateKernel callback of an OrtCustomOp to query an input's name + * during kernel/session creation. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index The index of the input name to get. Returns a failure status if out-of-bounds. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the input's name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, + _Inout_ size_t* size); + + /** \brief Get the name of a ::OrtKernelInfo's output. + * + * Used in the CreateKernel callback of an OrtCustomOp to query an output's name + * during kernel/session creation. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index The index of the output name to get. Returns a failure status if out-of-bounds. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the output's + * name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputName, _In_ const OrtKernelInfo* info, size_t index, _Out_ char* out, + _Inout_ size_t* size); + + /** \brief Get the type information for a ::OrtKernelInfo's input. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information + * of an input during kernel/session creation. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index Which input to get the type information for + * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetInputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get the type information for a ::OrtKernelInfo's output. + * + * Used in the CreateKernel callback of an OrtCustomOp to query the shape and type information + * of an output during kernel/session creation. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[in] index Which input to get the type information for + * \param[out] type_info Pointer set to the resulting ::OrtTypeInfo. Must be freed with OrtApi::ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(KernelInfo_GetOutputTypeInfo, _In_ const OrtKernelInfo* info, size_t index, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Get a ::OrtValue tensor stored as an attribute in the graph node. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a tensor attribute. + * + * \param[in] info ::OrtKernelInfo instance. + * \param[in] name UTF-8 null-terminated string representing the attribute's name. + * \param[in] allocator Allocator used to allocate the internal tensor state. + * \param[out] out Returns newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue, + * which will also free internal tensor state allocated with the provided allocator. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(KernelInfoGetAttribute_tensor, _In_ const OrtKernelInfo* info, _In_z_ const char* name, + _Inout_ OrtAllocator* allocator, _Outptr_ OrtValue** out); + + /// @} + /// \name OrtSessionOptions + /// Custom operator APIs + /// @{ + + /** \brief Checks if the given session configuration entry exists. + * + * The config_key formats are defined in onnxruntime_session_options_config_keys.h + * + * Can be used in a custom operator library to check for session configuration entries + * that target one or more custom operators in the library. Example: The config entry + * custom_op.myop.some_key targets a custom op named "myop". + * + * \param[in] options The ::OrtSessionOptions instance. + * \param[in] config_key A null-terminated UTF-8 string representation of the configuration key. + * \param[out] out Pointer set to 1 if the entry exists and 0 otherwise. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(HasSessionConfigEntry, _In_ const OrtSessionOptions* options, + _In_z_ const char* config_key, _Out_ int* out); + + /** \brief Get a session configuration value. + * + * Returns a failure status if the configuration key does not exist. + * The config_key and the format of config_value are defined in onnxruntime_session_options_config_keys.h + * + * If `config_value` is nullptr, the value of `size` is set to the true size of the string + * value (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the actual string value's size, + * the value of `size` is set to the true size of the string value, the provided memory + * is filled with the value's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string value's size and `config_value` + * is not nullptr, the value of `size` is set to the true size of the string value + * and a failure status is returned. + * + * Can be used in a custom operator library to get session configuration entries + * that target one or more custom operators in the library. Example: The config entry + * custom_op.myop.some_key targets a custom op named "myop". + * + * \param[in] options The session options. + * \param[in] config_key A null-terminated UTF-8 string representation of the config key. + * \param[in] config_value Pointer to memory where the null-terminated UTF-8 string value will be stored. + * \param[in,out] size Pointer to the size of the `config_value` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.14 + */ + ORT_API2_STATUS(GetSessionConfigEntry, _In_ const OrtSessionOptions* options, + _In_z_ const char* config_key, _Out_ char* config_value, _Inout_ size_t* size); + + /// @} + + /** \brief Append dnnl provider to session options + * + * If oneDNN is not available, this function will return failure. + * + * \param[in] options + * \param[in] dnnl_options + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_Dnnl, + _In_ OrtSessionOptions* options, _In_ const OrtDnnlProviderOptions* dnnl_options); + + /** \brief Create an OrtDnnlProviderOptions + * + * \param[out] out Newly created ::OrtDnnlProviderOptions. Must be released with OrtApi::ReleaseDnnlProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(CreateDnnlProviderOptions, _Outptr_ OrtDnnlProviderOptions** out); + + /** \brief Set options in a oneDNN Execution Provider. + * + * Key should be in null terminated string format of the member of ::OrtDnnlProviderOptions + * and value should be its related range. + * + * For example, key="use_arena" and value="1" + * + * \param[in] dnnl_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(UpdateDnnlProviderOptions, _Inout_ OrtDnnlProviderOptions* dnnl_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized oneDNN provider options string. + * + * For example, "use_arena=1;......" + * + * \param dnnl_options - OrtDnnlProviderOptions instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(GetDnnlProviderOptionsAsString, _In_ const OrtDnnlProviderOptions* dnnl_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtDnnlProviderOptions + * + * \since Version 1.15. + */ + void(ORT_API_CALL* ReleaseDnnlProviderOptions)(_Frees_ptr_opt_ OrtDnnlProviderOptions* input); + + /// \name OrtKernelInfo + /// Custom operator APIs. + /// @{ + + /** \brief Get the graph node name from ::OrtKernelInfo. + * + * If `out` is nullptr, the value of `size` is set to the size of the name + * string (including null-terminator), and a success status is returned. + * + * If the `size` parameter is greater than or equal to the name string's size, + * the value of `size` is set to the true size of the string (including null-terminator), + * the provided memory is filled with the string's contents, and a success status is returned. + * + * If the `size` parameter is less than the actual string's size and `out` + * is not nullptr, the value of `size` is set to the true size of the string + * and a failure status is returned. + * + * Can be used in a custom operator's CreateKernel callback to get the name of the operator's node name in the graph. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[out] out Memory location into which to write the UTF-8 null-terminated string representing the name. + * \param[in,out] size Pointer to the size of the `out` buffer. See above comments for details. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelInfo_GetNodeName, _In_ const OrtKernelInfo* info, _Out_ char* out, _Inout_ size_t* size); + + /** \brief Get the session logger from ::OrtKernelInfo. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a logger that can be used to log + * messages. + * + * \param[in] info An instance of ::OrtKernelInfo. + * \param[out] logger Pointer set to the session's ::OrtLogger. Owned by ONNX Runtime, so do not free. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelInfo_GetLogger, _In_ const OrtKernelInfo* info, _Outptr_ const OrtLogger** logger); + + /// @} + /// \name OrtKernelContext + /// Custom operator APIs. + /// @{ + + /** \brief Get the runtime logger from ::OrtKernelContext. + * + * Used in the KernelCompute callback of an OrtCustomOp to get a logger that can be used to log + * messages during inference. + * + * \param[in] context An instance of ::OrtKernelContext. + * \param[out] logger Pointer set to the kernel context's ::OrtLogger. Owned by ONNX Runtime, so do not free. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(KernelContext_GetLogger, _In_ const OrtKernelContext* context, _Outptr_ const OrtLogger** logger); + + /// @} + /// \name OrtLogger + /// Custom operator APIs. + /// @{ + + /** \brief Logs a message at the given severity level using the provided ::OrtLogger. + * + * Only messages with a severity level equal or greater than the ::OrtLogger's logging severity level + * are logged. Use OrtApi::Logger_GetLoggingSeverityLevel to get the ::OrtLogger's logging severity + * level. + * + * Can be used in custom operators to log messages with the logger retrieved via OrtApi::KernelInfo_GetLogger. + * + * \param[in] logger The ::OrtLogger instance. + * \param[in] log_severity_level The message's severity level. + * \param[in] message The message to log. + * \param[in] file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param[in] line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param[in] func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(Logger_LogMessage, _In_ const OrtLogger* logger, OrtLoggingLevel log_severity_level, + _In_z_ const char* message, _In_z_ const ORTCHAR_T* file_path, int line_number, + _In_z_ const char* func_name); + + /** \brief Get the logging severity level of the ::OrtLogger. + * + * Can be used in a custom operator to get the logging serverity level of the ::OrtLogger associated with + * the ::OrtKernelInfo. + * + * \param[in] logger The ::OrtLogger instance. + * \param[out] out Pointer to variable assigned with the logging severity level on success. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.15 + */ + ORT_API2_STATUS(Logger_GetLoggingSeverityLevel, _In_ const OrtLogger* logger, _Out_ OrtLoggingLevel* out); + + /// @} + + /** \brief Get a ::OrtValue tensor stored as a constant initializer in the graph node. + * + * Used in the CreateKernel callback of an OrtCustomOp to get a tensor value. + * + * \param[in] info ::OrtKernelInfo instance. + * \param[in] index The node index. + * \param[out] is_constant Is it a constant node input or not. + * \param[out] out The OrtValue tensor value. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(KernelInfoGetConstantInput_tensor, _In_ const OrtKernelInfo* info, size_t index, _Out_ int* is_constant, _Outptr_ const OrtValue** out); + + /** \brief Get Optional Type information from an ::OrtTypeInfo + * + * This augments ::OrtTypeInfo to return an ::OrtOptionalTypeInfo when the type is optional. + * The OrtOptionalTypeInfo also has a nested ::OrtTypeInfo that describes the type of the optional value. + * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. + * The actual OrtValues that are supplied in place of optional type inputs should contain + * specific type that is described by ::OrtOptionalTypeInfo. + * + * So the picture: ::OrtTypeInfo -> ::OrtOptionalTypeInfo -> ::OrtTypeInfo (describes the type that can be supplied + * in place of the optional type when creating the actual ::OrtValue). + * + * \param[in] type_info + * \param[out] out A pointer to the ::OrtOptionalTypeInfo. Do not free this value, + * it is owned by OrtTypeInfo instance. When the type_info does not represent + * optional type, nullptr is returned in out. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(CastTypeInfoToOptionalTypeInfo, _In_ const OrtTypeInfo* type_info, + _Outptr_result_maybenull_ const OrtOptionalTypeInfo** out); + + /** \brief Get OrtTypeInfo for the allowed contained type from an ::OrtOptionalTypeInfo. + * + * This augments ::OrtOptionalTypeInfo to return an ::OrtTypeInfo for the contained type. + * The OrtOptionalTypeInfo has a nested ::OrtTypeInfo that describes the type of the optional value. + * ::OrtOptionalTypeInfo type can only appear within model metadata to describe inputs/outputs. + * The actual OrtValues that are supplied in place of optional type inputs should contain + * specific type that is described by the returned ::OrtTypeInfo. + * + * \param[in] optional_type_info + * \param[out] out A copy of ::OrtTypeInfo for what the optional value could be. + * The user must free this value with ReleaseTypeInfo. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(GetOptionalContainedTypeInfo, _In_ const OrtOptionalTypeInfo* optional_type_info, + _Outptr_ OrtTypeInfo** out); + + /** \brief Set a single string in a string tensor + * Do not zero terminate the string data. + * + * \param[in] value A string tensor + * \param[in] index - flat index of the element + * \param[in] length_in_bytes length of the buffer in utf-8 bytes (without the null terminator) + * \param[inout] buffer - address of return value + * + * \snippet{doc} snippets.dox OrtStatus Return Value + */ + ORT_API2_STATUS(GetResizedStringTensorElementBuffer, _Inout_ OrtValue* value, _In_ size_t index, _In_ size_t length_in_bytes, _Inout_ char** buffer); + + /** \brief Get Allocator from KernelContext for a specific memoryInfo. Please use C API ReleaseAllocator to release out object + * + * \param[in] context OrtKernelContext instance + * \param[in] mem_info OrtMemoryInfo instance + * \param[out] out A pointer to OrtAllocator. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.15. + */ + ORT_API2_STATUS(KernelContext_GetAllocator, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _Outptr_ OrtAllocator** out); + + /** \brief Returns a null terminated string of the build info including git info and cxx flags + * + * \return UTF-8 encoded version string. Do not deallocate the returned buffer. + * + * \since Version 1.15. + */ + const char*(ORT_API_CALL* GetBuildInfoString)(void); + + /// \name OrtROCMProviderOptions + /// @{ + + /** \brief Create an OrtROCMProviderOptions + * + * \param[out] out Newly created ::OrtROCMProviderOptions. Must be released with OrtApi::ReleaseROCMProviderOptions + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(CreateROCMProviderOptions, _Outptr_ OrtROCMProviderOptions** out); + + /** \brief Set options in a ROCm Execution Provider. + * + * Please refer to https://onnxruntime.ai/docs/execution-providers/ROCm-ExecutionProvider.html + * to know the available keys and values. Key should be in null terminated string format of the member of + * ::OrtROCMProviderOptions and value should be its related range. + * + * For example, key="device_id" and value="0" + * + * \param[in] rocm_options + * \param[in] provider_options_keys Array of UTF-8 null-terminated string for provider options keys + * \param[in] provider_options_values Array of UTF-8 null-terminated string for provider options values + * \param[in] num_keys Number of elements in the `provider_option_keys` and `provider_options_values` arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateROCMProviderOptions, _Inout_ OrtROCMProviderOptions* rocm_options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** + * Get serialized ROCm provider options string. + * + * For example, "device_id=0;arena_extend_strategy=0;......" + * + * \param rocm_options - OrtROCMProviderOptions instance + * \param allocator - a ptr to an instance of OrtAllocator obtained with CreateAllocator() or GetAllocatorWithDefaultOptions() + * the specified allocator will be used to allocate continuous buffers for output strings and lengths. + * \param ptr - is a UTF-8 null terminated string allocated using 'allocator'. The caller is responsible for using the same allocator to free it. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetROCMProviderOptionsAsString, _In_ const OrtROCMProviderOptions* rocm_options, _Inout_ OrtAllocator* allocator, _Outptr_ char** ptr); + + /** \brief Release an ::OrtROCMProviderOptions + * + * \note This is an exception in the naming convention of other Release* functions, as the name of the method does not have the V2 suffix, but the type does + * + * \since Version 1.16. + */ + void(ORT_API_CALL* ReleaseROCMProviderOptions)(_Frees_ptr_opt_ OrtROCMProviderOptions* input); + + /** \brief Create an allocator with specific type and register it with the ::OrtEnv + * This API enhance CreateAndRegisterAllocator that it can create an allocator with specific type, not just CPU allocator + * Enables sharing the allocator between multiple sessions that use the same env instance. + * Lifetime of the created allocator will be valid for the duration of the environment. + * Returns an error if an allocator with the same ::OrtMemoryInfo is already registered. + * \param[in] env OrtEnv instance + * \param[in] provider_type ExecutionProvider type + * \param[in] mem_info OrtMemoryInfo instance + * \param[in] arena_cfg Arena configuration + * \param[in] provider_options_keys key of the provider options map + * \param[in] provider_options_values value of the provider options map + * \param[in] num_keys Length of the provider options map + */ + ORT_API2_STATUS(CreateAndRegisterAllocatorV2, _Inout_ OrtEnv* env, _In_ const char* provider_type, _In_ const OrtMemoryInfo* mem_info, _In_ const OrtArenaCfg* arena_cfg, + _In_reads_(num_keys) const char* const* provider_options_keys, _In_reads_(num_keys) const char* const* provider_options_values, _In_ size_t num_keys); + + /** \brief Run the model asynchronously in a thread owned by intra op thread pool + * + * \param[in] session + * \param[in] run_options If nullptr, will use a default ::OrtRunOptions + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] input Array of ::OrtValue%s of the input values + * \param[in] input_len Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[in] output_names_len Number of elements in the output_names and outputs array + * \param[out] output OrtValue* array of size output_names_len. + * On calling RunAsync, output[i] could either be a null or a pointer to a preallocated OrtValue. + * Later, the output array will be passed to run_async_callback with all null(s) filled with valid + * OrtValue pointer(s) allocated by onnxruntime. + * NOTE: it is customer's duty to finally release the output array and each of its member, + * regardless of whether the member (OrtValue*) is allocated by onnxruntime or preallocated by the customer. + * \param[in] run_async_callback Callback function on model run completion + * \param[in] user_data User data that pass back to run_async_callback + */ + ORT_API2_STATUS(RunAsync, _Inout_ OrtSession* session, _In_opt_ const OrtRunOptions* run_options, + _In_reads_(input_len) const char* const* input_names, + _In_reads_(input_len) const OrtValue* const* input, size_t input_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _Inout_updates_all_(output_names_len) OrtValue** output, + _In_ RunAsyncCallbackFn run_async_callback, _In_opt_ void* user_data); + + /** + * Update TensorRT EP provider option where its data type is pointer, for example 'user_compute_stream'. + * If the data type of the provider option can be represented by string please use UpdateTensorRTProviderOptions. + * + * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param key - Name of the provider option + * \param value - A pointer to the instance that will be assigned to this provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateTensorRTProviderOptionsWithValue, _Inout_ OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _In_ void* value); + + /** + * Get TensorRT EP provider option where its data type is pointer. + * If the data type of the provider option can be represented by string please use GetTensorRTProviderOptionsAsString. + * + * \param tensorrt_options - OrtTensorRTProviderOptionsV2 instance + * \param key - Name of the provider option + * \param ptr - A pointer to the instance that is kept by the provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetTensorRTProviderOptionsByName, _In_ const OrtTensorRTProviderOptionsV2* tensorrt_options, _In_ const char* key, _Outptr_ void** ptr); + + /** + * Update CUDA EP provider option where its data type is pointer, for example 'user_compute_stream'. + * If the data type of the provider option can be represented by string please use UpdateCUDAProviderOptions. + * + * Note: It's caller's responsibility to properly manage the lifetime of the instance pointed by this pointer. + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param key - Name of the provider option + * \param value - A pointer to the instance that will be assigned to this provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(UpdateCUDAProviderOptionsWithValue, _Inout_ OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _In_ void* value); + + /** + * Get CUDA EP provider option where its data type is pointer. + * If the data type of the provider option can be represented by string please use GetCUDAProviderOptionsAsString. + * + * \param cuda_options - OrtCUDAProviderOptionsV2 instance + * \param key - Name of the provider option + * \param ptr - A pointer to the instance that is kept by the provider option + * + * \since Version 1.16. + */ + ORT_API2_STATUS(GetCUDAProviderOptionsByName, _In_ const OrtCUDAProviderOptionsV2* cuda_options, _In_ const char* key, _Outptr_ void** ptr); + + /** + * Get a EP resource. + * E.g. a cuda stream or a cublas handle + * + * \param context - Kernel context + * \param resource_version - Version of the resource + * \param resource_id - Type of resource + * \param resource - A pointer to returned resource + * + * \since Version 1.16. + */ + ORT_API2_STATUS(KernelContext_GetResource, _In_ const OrtKernelContext* context, _In_ int resource_version, + _In_ int resource_id, _Outptr_ void** resource); + + /** \brief Set user logging function + * + * By default the logger created by the CreateEnv* functions is used to create the session logger as well. + * This function allows a user to override this default session logger with a logger of their own choosing. This way + * the user doesn't have to create a separate environment with a custom logger. This addresses the problem when + * the user already created an env but now wants to use a different logger for a specific session (for debugging or + * other reasons). + * + * \param[in] options + * \param[in] user_logging_function A pointer to a logging function. + * \param[in] user_logging_param A pointer to arbitrary data passed as the ::OrtLoggingFunction `param` parameter to + * `user_logging_function`. This parameter is optional. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SetUserLoggingFunction, _Inout_ OrtSessionOptions* options, + _In_ OrtLoggingFunction user_logging_function, _In_opt_ void* user_logging_param); + + /** + * Get number of input from OrtShapeInferContext + * + * \param[in] context + * \param[out] out The number of inputs + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_GetInputCount, _In_ const OrtShapeInferContext* context, _Out_ size_t* out); + + /** + * Get type and shape info of an input + * + * \param[in] context + * \param[in] index The index of the input + * \param[out] info Type shape info of the input + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_GetInputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _Outptr_ OrtTensorTypeAndShapeInfo** info); + + /** + * Get attribute from OrtShapeInferContext. Note that OrtShapeInferContext is a per-node context, one could only read attribute from current node. + * + * \param[in] context + * \param[in] attr_name Name of the attribute + * \param[out] attr Handle of the attribute fetched + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_GetAttribute, _In_ const OrtShapeInferContext* context, _In_ const char* attr_name, _Outptr_ const OrtOpAttr** attr); + + /** + * Set type and shape info of an output + * + * \param[in] context + * \param[in] index The index of the output + * \param[out] info Type shape info of the output + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ShapeInferContext_SetOutputTypeShape, _In_ const OrtShapeInferContext* context, _In_ size_t index, _In_ const OrtTensorTypeAndShapeInfo* info); + + /** + * Set symbolic shape to type shape info + * + * \param[in] info Type shape info + * \param[in] dim_params Symbolic strings + * \param[in] dim_params_length Number of strings + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SetSymbolicDimensions, _In_ OrtTensorTypeAndShapeInfo* info, _In_ const char* dim_params[], _In_ size_t dim_params_length); + + /** + * Read contents of an attribute to data + * + * \param[in] op_attr + * \param[in] type Attribute type + * \param[out] data Memory address to save raw content of the attribute + * \param[in] len Number of bytes allowed to store in data + * \param[out] out Number of bytes required to save the data when the call failed, or the real number of bytes saved to data on success + * + * \since Version 1.17. + */ + ORT_API2_STATUS(ReadOpAttr, _In_ const OrtOpAttr* op_attr, _In_ OrtOpAttrType type, _Inout_ void* data, _In_ size_t len, _Out_ size_t* out); + + /** \brief Set whether to use deterministic compute. + * + * Default is false. If set to true, this will enable deterministic compute for GPU kernels where possible. + * Note that this most likely will have a performance cost. + * + * \param[in] options + * \param[in] value + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SetDeterministicCompute, _Inout_ OrtSessionOptions* options, bool value); + + /** + * Run fn in parallel + * + * \param[in] context + * \param[in] fn Function accepting usr_data and an integer as iterator + * \param[in] total The number of times fn is to be invoked + * \param[in] num_batch Number of batches by which the "total" is to be divided in maximum. When zero, there is no limit + * \param[in] usr_data User data to be passed back to fn + * + * \since Version 1.17. + */ + ORT_API2_STATUS(KernelContext_ParallelFor, _In_ const OrtKernelContext* context, _In_ void (*fn)(void*, size_t), _In_ size_t total, _In_ size_t num_batch, _In_ void* usr_data); + + /** \brief Append OpenVINO execution provider to the session options + * + * If OpenVINO is not available (due to a non OpenVINO enabled build, or if OpenVINO is not installed on the system), this function will fail. + * + * \param[in] options + * \param[in] provider_options_keys + * \param[in] provider_options_values + * \param[in] num_keys + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.17. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_OpenVINO_V2, + _In_ OrtSessionOptions* options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Append VitisAI provider to session options + * + * If VitisAI is not available (due to a non VitisAI enabled build, or if VitisAI is not installed on the system), this function will return failure. + * + * \param[in] options + * \param[in] provider_options_keys + * \param[in] provider_options_values + * \param[in] num_keys + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_VitisAI, + _In_ OrtSessionOptions* options, + _In_reads_(num_keys) const char* const* provider_options_keys, + _In_reads_(num_keys) const char* const* provider_options_values, + _In_ size_t num_keys); + + /** \brief Get scratch buffer from the corresponding allocator under the sepcific OrtMemoryInfo object. + * NOTE: callers are responsible to release this scratch buffer from the corresponding allocator + * \param[in] context OrtKernelContext instance + * \param[in] mem_info OrtMemoryInfo instance + * \param[in] count_or_bytes How many bytes is this scratch buffer + * \param[out] out A pointer to the scrach buffer + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(KernelContext_GetScratchBuffer, _In_ const OrtKernelContext* context, _In_ const OrtMemoryInfo* mem_info, _In_ size_t count_or_bytes, _Outptr_ void** out); + + /** \brief Get allocator from KernelInfo for a specific memory type. Please use C API ReleaseAllocator to release out object + * + * \param[in] info OrtKernelInfo instance + * \param[in] mem_type OrtMemType object + * \param[out] out A pointer to OrtAllocator + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(KernelInfoGetAllocator, _In_ const OrtKernelInfo* info, _In_ OrtMemType mem_type, _Outptr_ OrtAllocator** out); + + /** \brief Replace initialized Tensors with external data with the provided files in memory + * + * The function will find the initialized TensorProtos with external data in the graph with the provided + * external file names and the file content in memory. The API gets the external file name, offset, data length + * from TensorProto, and locate the tensor data from the file in memory buffer. + * It creates a Tensor to replace the existing Tensor in graph. The replacement + * will occur before any of the optimizations take place. The data will be copied into the graph + * since TensorProto can't refer to the user provided buffers. + * + * \param[in] options + * \param[in] external_initializer_file_names Array of null terminated UTF-8 encoded strings of the file names + * which holds the external initializers. + * \param[in] external_initializer_file_buffer_array Array of pointers to the buffer of the file content. + * The buffer can be freed after session creation. + * \param[in] external_initializer_file_lengths Array of size_t to indicate the length of file content + * \param[in] num_external_initializer_files Number of external files + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.18. + */ + ORT_API2_STATUS(AddExternalInitializersFromFilesInMemory, _In_ OrtSessionOptions* options, + _In_reads_(num_external_initializer_files) const ORTCHAR_T* const* external_initializer_file_names, + _In_reads_(num_external_initializer_files) char* const* external_initializer_file_buffer_array, + _In_reads_(num_external_initializer_files) const size_t* external_initializer_file_lengths, + size_t num_external_initializer_files); + + /** \brief Create an OrtLoraAdapter + * + * The function attempts to locate file specified by adapter_file_path, read it and create an OrtLoraAdapter + * instance. The adapter_file_path should be a valid path to a file that contains a valid Lora Adapter + * format. The function attempts to validate the format at load time. The file will always be memory mapped, unless + * the platform does not support memory mapping, in which case the file will be read into memory. + * + * \param[in] adapter_file_path adapter file path. + * \param[in] allocator optional pointer to a device allocator. If specified + * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. + * The data would still be copied to device if required by the model at inference time. + * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with + * OrtApi::ReleaseLoraAdapter. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(CreateLoraAdapter, const ORTCHAR_T* adapter_file_path, _In_ OrtAllocator* allocator, + _Outptr_ OrtLoraAdapter** out); + + /** \brief Create an OrtLoraAdapter + * + * The function copies the bytes from the array and creates an OrtLoraAdapter instance. + * + * + * \param[in] bytes pointer to a valid Lora Adapter format buffer. + * \param[in] num_bytes length of bytes buffer. + * \param[in] allocator optional pointer to a device allocator. If specified + * data is copied to the device at some point before Run() is invoked. If nullptr, data stays on CPU. + * The data would still be copied to device if required by the model at inference time. + * \param[out] out A pointer to a newly created OrtLoraAdapter instance. Must be released with + * OrtApi::ReleaseLoraAdapter. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(CreateLoraAdapterFromArray, _In_ const void* bytes, size_t num_bytes, _In_ OrtAllocator* allocator, + _Outptr_ OrtLoraAdapter** out); + + /** \brief Release an ::OrtLoraAdapter obtained from OrtApi::CreateLoraAdapter + */ + ORT_CLASS_RELEASE(LoraAdapter); + + /** \brief Add the Lora Adapter to the list of active adapters. + * + * The function adds the Lora Adapter to the list of active adapters. The Lora Adapter must be created with + * OrtApi::CreateLoraAdapter or FromArray. The Lora Adapter will be used by the session to run the model. + * The instance of the OrtRunOptions can then be used to customize the Run() calls. + * More than one OrtLoraAdapter can be active at the same time. Lora Parameters that belong to different + * Lora adapters that will be active at the same time must not overlap. + * This setting does not affect RunWithBinding. + * + * \param[in] options OrtRunOptions instance + * \param[in] adapter OrtLoraAdapter instance + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(RunOptionsAddActiveLoraAdapter, _Inout_ OrtRunOptions* options, _In_ const OrtLoraAdapter* adapter); + + /// @} + /// \name OrtEpDynamicOptions + /// @{ + + /** \brief Set DynamicOptions for EPs (Execution Providers) + * + * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` + * Look for `kOrtEpDynamicOptions` + * + * \param[in] sess OrtSession + * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys + * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values + * \param[in] kv_len Number of elements in the keys and values arrays + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.20. + */ + ORT_API2_STATUS(SetEpDynamicOptions, _Inout_ OrtSession* sess, _In_reads_(kv_len) const char* const* keys, + _In_reads_(kv_len) const char* const* values, _In_ size_t kv_len); + + /** \brief Release an OrtValueInfo instance if it was not added to an OrtGraph. + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(ValueInfo); + + /** \brief Release an OrtNode if it was not added to an OrtGraph. + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(Node); + + /** \brief Release an OrtGraph. + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(Graph); + + /** \brief Release an OrtModel. + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(Model); + + /** \brief Get the value name from an OrtValueInfo instance. + * \param[in] value_info The OrtValueInfo instance. + * \param[out] name The name of the OrtValueInfo + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_API2_STATUS(GetValueInfoName, _In_ const OrtValueInfo* value_info, _Out_ const char** name); + + /** \brief Get the type information from an OrtValueInfo instance. + * \param[in] value_info The OrtValueInfo instance. + * \param[out] type_info The type info of the OrtValueInfo + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_API2_STATUS(GetValueInfoTypeInfo, _In_ const OrtValueInfo* value_info, _Outptr_ const OrtTypeInfo** type_info); + + /** \brief Get the Model Editor API instance + * + * Get the Model Editor API instance to create a new model or augment an existing model. + * + * \return Model Editor API struct + * + * \since Version 1.22. + */ + const OrtModelEditorApi*(ORT_API_CALL* GetModelEditorApi)(); + + /** \brief Create an OrtValue for a Tensor that uses pre-existing memory. + * + * ORT will take ownership of the memory and free it using the provided deleter when no longer in use. + * + * \param[in] deleter OrtAllocator instance that will be used to free the memory. + * Only the OrtAllocator:Info and OrtAllocator::Release functions are required. + * The OrtMemoryInfo returned by OrtAllocator::Info must match the location of p_data. + * \param[in] p_data Pointer to the memory that will be used by the Tensor. ORT will take ownership of the memory. + * \param[in] p_data_len Length of the memory in bytes. + * \param[in] shape Dimensions of the Tensor. All values should be > 0. + * \param[in] shape_len Number of dimensions in the shape array. + * \param[in] type Data type of the Tensor. + * \param[out] out Newly created ::OrtValue. Must be freed with OrtApi::ReleaseValue + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateTensorWithDataAndDeleterAsOrtValue, _In_ OrtAllocator* deleter, + _In_ void* p_data, size_t p_data_len, + _In_ const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type, + _Outptr_ OrtValue** out); + + /** \brief sets load cancellation flag to abort session loading process. + * + * \param[in] options instance that was passed to the session at creation time. + * \param[in] cancel setting this to true after model loading process was initiated will + * attempt to cancel the loading process. If cancellation is successful, CreateSession() + * CreateSessionFromArray() or any other session creation API that take session options as an + * argument will return an OrtStatus indicating that session loading was canceled at user request, + * error code ORT_MODEL_LOAD_CANCELED. + * The APIs above would not return any valid Session instance. This is the best case effort and the result + * is not guaranteed. The session may have already been created and initialized + * before the cancellation request was issued. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SessionOptionsSetLoadCancellationFlag, _Inout_ OrtSessionOptions* options, + _In_ bool cancel); + + /** \brief Get the Compile API instance. + * + * Get the Compile API instance to compile ONNX models. Execution providers that support compilation fuse a subgraph + * into an EPContext node that wraps a provider-specific binary representation of the subgraph. + * For more details about the EPContext design, refer to: + * \htmlonly + * EPContext design document. + * \endhtmlonly + * + * \return Compile API struct instance. + * + * \since Version 1.22. + */ + const OrtCompileApi*(ORT_API_CALL* GetCompileApi)(); + + // + // OrtKeyValuePairs + // + + /** \brief Create an OrtKeyValuePairs instance. + * + * \param[out] out A pointer to a newly created OrtKeyValuePairs instance. + * + * \note Must be released by calling ReleaseKeyValuePairs. + * + * \since Version 1.22. + */ + void(ORT_API_CALL* CreateKeyValuePairs)(_Outptr_ OrtKeyValuePairs** out); + + /** \brief Add a key-value pair to the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[in] key Key to be added. + * \param[in] value Value to be added. + * + * \note The `key` and `value` are copied internally. + * + * \since Version 1.22. + */ + + void(ORT_API_CALL* AddKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key, _In_ const char* value); + + /** \brief Get the value associated with a key in the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[in] key Key to be searched. + * + * \return The value associated with the key, or nullptr if the key does not exist. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetKeyValue)(_In_ const OrtKeyValuePairs* kvps, _In_ const char* key); + + /** \brief Get all the key-value pairs from the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[out] keys Array of keys from `kvps`. + * \param[out] values Array of values from `kvps`. + * \param[out] num_entries Number of entries in `keys` and `values`. + * + * \since Version 1.22. + */ + void(ORT_API_CALL* GetKeyValuePairs)(_In_ const OrtKeyValuePairs* kvps, + _Outptr_ const char* const** keys, _Outptr_ const char* const** values, + _Out_ size_t* num_entries); + + /** \brief Remove a key-value pair from the OrtKeyValuePairs instance. + * + * \param[in] kvps OrtKeyValuePairs instance. + * \param[in] key Key to be removed. No error if not found. + * + * \since Version 1.22. + */ + void(ORT_API_CALL* RemoveKeyValuePair)(_In_ OrtKeyValuePairs* kvps, _In_ const char* key); + + /** \brief Release an OrtKeyValuePairs instance. + * + * \param[in] input OrtKeyValuePairs instance to be released. + * + * \since Version 1.22. + */ + ORT_CLASS_RELEASE(KeyValuePairs); + + /** \brief Register an execution provider library with ORT. + * + * The library must export 'CreateEpFactories' and 'ReleaseEpFactory' functions. + * See OrtEpApi for more details. + * + * \param[in] env The OrtEnv instance to register the library in. + * \param[in] registration_name The name to register the execution provider library under. + * \param[in] path The path to the execution provider library. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(RegisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name, + _In_ const ORTCHAR_T* path); + + /** \brief Unregister an execution provider library with ORT. + * + * ORT will call ReleaseEpFactory for all factories created by the library, and unload the library. + * + * You MUST ensure there are no Session instances using execution providers created by the library + * before calling this function. + * + * \param[in] env The OrtEnv instance to unregister the library from. + * \param[in] registration_name The name the execution provider library was registered under. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(UnregisterExecutionProviderLibrary, _In_ OrtEnv* env, _In_ const char* registration_name); + + /** \brief Get the list of available OrtEpDevice instances. + * + * Each OrtEpDevice instance contains details of the execution provider and the device it will use. + * + * \param[in] env The OrtEnv instance to query. + * \param[out] ep_devices The OrtEpDevice instances that the execution provider will use. + * \param[out] num_ep_devices The number of OrtEpDevice instances returned. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(GetEpDevices, _In_ const OrtEnv* env, + _Outptr_ const OrtEpDevice* const** ep_devices, _Out_ size_t* num_ep_devices); + + /** \brief Append the execution provider that is responsible for the selected OrtEpDevice instances + * to the session options. + * + * \param[in] session_options Session options to add execution provider to. + * \param[in] env Environment that execution providers were registered with. + * \param[in] ep_devices One or more OrtEpDevice instances to create an execution provider for. + * Obtain from GetEpDevices. All OrtEpDevice instances must be from the same execution + * provider. It is only necessary to provide multiple OrtEpDevices if you want to use the + * same execution provider for multiple devices. + * e.g. the EP is capable of running on GPU and NPU. + * \param[in] num_ep_devices Number of OrtEpDevice instances. + * \param[in] ep_option_keys Optional keys to configure the execution provider. + * \param[in] ep_option_vals Optional values to configure the execution provider. + * \param[in] num_ep_options Number of execution provide options to add. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SessionOptionsAppendExecutionProvider_V2, _In_ OrtSessionOptions* session_options, + _In_ OrtEnv* env, + _In_reads_(num_ep_devices) const OrtEpDevice* const* ep_devices, _In_ size_t num_ep_devices, + _In_reads_(num_op_options) const char* const* ep_option_keys, + _In_reads_(num_op_options) const char* const* ep_option_vals, + size_t num_ep_options); + + /** \brief Set the execution provider selection policy for the session. + * + * Allows users to specify a device selection policy for automatic execution provider (EP) selection. + * If custom selection is required please use SessionOptionsSetEpSelectionPolicyDelegate instead. + * + * \param[in] session_options The OrtSessionOptions instance. + * \param[in] policy The device selection policy to use (see OrtExecutionProviderDevicePolicy). + * + * \since Version 1.22 + */ + ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicy, _In_ OrtSessionOptions* session_options, + _In_ OrtExecutionProviderDevicePolicy policy); + + /** \brief Set the execution provider selection policy delegate for the session. + * + * Allows users to provide a custom device selection policy for automatic execution provider (EP) selection. + * + * \param[in] session_options The OrtSessionOptions instance. + * \param[in] delegate Delegate callback for custom selection. + * \param[in] delegate_state Optional state that will be passed to the delegate callback. nullptr if not required. + * + * \since Version 1.22 + */ + ORT_API2_STATUS(SessionOptionsSetEpSelectionPolicyDelegate, _In_ OrtSessionOptions* session_options, + _In_ EpSelectionDelegate delegate, + _In_opt_ void* delegate_state); + + /** \brief Get the hardware device type. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The hardware device type. + * + * \since Version 1.22. + */ + OrtHardwareDeviceType(ORT_API_CALL* HardwareDevice_Type)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the hardware device's vendor identifier. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The hardware device vendor identifier. + * + * \since Version 1.22. + */ + uint32_t(ORT_API_CALL* HardwareDevice_VendorId)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the hardware device's vendor name. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The hardware device's vendor name. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* HardwareDevice_Vendor)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the hardware device's unique identifier. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return The device id. + * + * \note This is not a unique identifier. It identifies the hardware type when combined with vendor id. + * \since Version 1.22. + */ + uint32_t(ORT_API_CALL* HardwareDevice_DeviceId)(_In_ const OrtHardwareDevice* device); + + /** \brief Get hardware device metadata. + * + * \param[in] device The OrtHardwareDevice instance to query. + * \return An OrtKeyValuePairs instance containing the metadata for the device. + * Note: ORT owns the instance so the user must not call ReleaseKeyValuePairs with it. + * + * \since Version 1.22. + */ + const OrtKeyValuePairs*(ORT_API_CALL* HardwareDevice_Metadata)(_In_ const OrtHardwareDevice* device); + + /** \brief Get the execution provider name. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return The execution provider name. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* EpDevice_EpName)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the execution provider's vendor name. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return The execution provider's vendor name. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* EpDevice_EpVendor)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the metadata for the OrtEpDevice. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return An OrtKeyValuePairs instance containing the metadata for the device. + * + * \since Version 1.22. + */ + const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpMetadata)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the execution provider options for the OrtEpDevice. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return An OrtKeyValuePairs instance containing the execution provider options for the device. + * + * \since Version 1.22. + */ + const OrtKeyValuePairs*(ORT_API_CALL* EpDevice_EpOptions)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the OrtHardwareDevice instance for the OrtEpDevice. + * + * \param[in] ep_device The OrtEpDevice instance to query. + * \return The OrtHardwareDevice instance for the device. + * + * \since Version 1.22. + */ + const OrtHardwareDevice*(ORT_API_CALL* EpDevice_Device)(_In_ const OrtEpDevice* ep_device); + + /** \brief Get the OrtEpApi instance for implementing an execution provider. + * + * \since Version 1.22. + */ + const OrtEpApi*(ORT_API_CALL* GetEpApi)(); +}; + +/* + * Steps to use a custom op: + * 1 Create an OrtCustomOpDomain with the domain name used by the custom ops + * 2 Create an OrtCustomOp structure for each op and add them to the domain + * 3 Call OrtAddCustomOpDomain to add the custom domain of ops to the session options + */ + +// Specifies some characteristics of inputs/outputs of custom ops: +// Specify if the inputs/outputs are one of: +// 1) Non-optional (input/output must be present in the node) +// 2) Optional (input/output may be absent in the node) +// 3) Variadic: A variadic input or output specifies N (i.e., the minimum arity) or more operands. +// Only the last input or output of a custom op may be marked as variadic. +// The homogeneity of the variadic input or output determines whether all operands must be of the same +// tensor element type. +typedef enum OrtCustomOpInputOutputCharacteristic { + INPUT_OUTPUT_REQUIRED = 0, + INPUT_OUTPUT_OPTIONAL, + INPUT_OUTPUT_VARIADIC, +} OrtCustomOpInputOutputCharacteristic; + +/* + * The OrtCustomOp structure defines a custom op's schema and its kernel callbacks. The callbacks are filled in by + * the implementor of the custom op. + */ +struct OrtCustomOp { + uint32_t version; // Must be initialized to ORT_API_VERSION + + // This callback creates the kernel, which is a user defined + // parameter that is passed to the Kernel* callbacks below. It is + // recommended to use CreateKernelV2 which allows for a safe error + // propagation by returning an OrtStatusPtr. + void*(ORT_API_CALL* CreateKernel)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, + _In_ const OrtKernelInfo* info); + + // Returns the name of the op + const char*(ORT_API_CALL* GetName)(_In_ const struct OrtCustomOp* op); + + // Returns the type of the execution provider, return nullptr to use CPU execution provider + const char*(ORT_API_CALL* GetExecutionProviderType)(_In_ const struct OrtCustomOp* op); + + // Returns the count and types of the input & output tensors + ONNXTensorElementDataType(ORT_API_CALL* GetInputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + size_t(ORT_API_CALL* GetInputTypeCount)(_In_ const struct OrtCustomOp* op); + ONNXTensorElementDataType(ORT_API_CALL* GetOutputType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + size_t(ORT_API_CALL* GetOutputTypeCount)(_In_ const struct OrtCustomOp* op); + + // Perform a computation step. It is recommended to use + // KernelComputeV2 which allows for a safe error propagation by + // returning an OrtStatusPtr. + void(ORT_API_CALL* KernelCompute)(_In_ void* op_kernel, _In_ OrtKernelContext* context); + void(ORT_API_CALL* KernelDestroy)(_In_ void* op_kernel); + + // Returns the characteristics of the input & output tensors + OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetInputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + OrtCustomOpInputOutputCharacteristic(ORT_API_CALL* GetOutputCharacteristic)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + + // Returns the memory type of the input tensors. This API allows the custom op + // to place the inputs on specific devices. By default, it returns + // OrtMemTypeDefault, which means the input is placed on the default device for + // the execution provider. If the inputs need to be with different memory tyeps, + // this function can be overridden to return the specific memory types. + OrtMemType(ORT_API_CALL* GetInputMemoryType)(_In_ const struct OrtCustomOp* op, _In_ size_t index); + + // Returns the minimum number of input arguments expected for the variadic input. + // Applicable only for custom ops that have a variadic input. + int(ORT_API_CALL* GetVariadicInputMinArity)(_In_ const struct OrtCustomOp* op); + + // Returns true (non-zero) if all arguments of a variadic input have to be of the same type (homogeneous), + // and false (zero) otherwise. + // Applicable only for custom ops that have a variadic input. + int(ORT_API_CALL* GetVariadicInputHomogeneity)(_In_ const struct OrtCustomOp* op); + + // Returns the minimum number of output values expected for the variadic output. + // Applicable only for custom ops that have a variadic output. + int(ORT_API_CALL* GetVariadicOutputMinArity)(_In_ const struct OrtCustomOp* op); + + // Returns true (non-zero) if all outputs values of a variadic output have to be of the same type (homogeneous), + // and false (zero) otherwise. + // Applicable only for custom ops that have a variadic output. + int(ORT_API_CALL* GetVariadicOutputHomogeneity)(_In_ const struct OrtCustomOp* op); + + // Create the kernel state which is passed to each compute call. + OrtStatusPtr(ORT_API_CALL* CreateKernelV2)(_In_ const struct OrtCustomOp* op, _In_ const OrtApi* api, + _In_ const OrtKernelInfo* info, + _Out_ void** kernel); + + // Perform the computation step. + OrtStatusPtr(ORT_API_CALL* KernelComputeV2)(_In_ void* op_kernel, _In_ OrtKernelContext* context); + + OrtStatusPtr(ORT_API_CALL* InferOutputShapeFn)(_In_ const struct OrtCustomOp* op, _In_ OrtShapeInferContext*); + + // Get start range + int(ORT_API_CALL* GetStartVersion)(_In_ const struct OrtCustomOp* op); + int(ORT_API_CALL* GetEndVersion)(_In_ const struct OrtCustomOp* op); + + // Get the inplace_map that defines which output can reuse which input + // Callers will provide 2 raw int* and pass in their address, this function will fill these 2 arrays + // when return, output (*output_index)[i] may reuse the input (*input_index[i]). + // The return value is the size of these 2 arrays. + // Callers are responsible to delete these 2 arrays after use by calling OrtCustomOp::ReleaseMayInplace(). + size_t(ORT_API_CALL* GetMayInplace)(_Out_ int** input_index, _Out_ int** output_index); + + // Release the pointer input_index and output_index allocated from GetMayInplace() function. + // If GetMayInplace() is defined, this function MUST be defined as well. + void(ORT_API_CALL* ReleaseMayInplace)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); + + // Same as GetMayInplace() and ReleaseMayInplace() + size_t(ORT_API_CALL* GetAliasMap)(_Out_ int** input_index, _Out_ int** output_index); + void(ORT_API_CALL* ReleaseAliasMap)(_Frees_ptr_opt_ int* input_index, _Frees_ptr_opt_ int* output_index); +}; + +/** + * ORT Model Editor API + */ + +/** + * \brief The OrtModelEditorApi struct provides functions to create or edit an ONNX model. + * + * See onnxruntime/test/shared_lib/test_model_editor_api.cc for example usage. + * + * \since Version 1.22. + */ +struct OrtModelEditorApi { + // Model building/editing requires a full build. We return nullptr from GetModelEditorApi if this is a minimal + // build, so it doesn't matter if there are no function pointers in this struct as a user will never get an + // OrtModelEditorApi instance. We do however need a dummy field to avoid empty struct warning. +#if defined(ORT_MINIMAL_BUILD) + const bool not_defined_in_this_build; +#else + /** \brief Create an OrtTypeInfo instance for a Tensor. + * + * Create an OrtTypeInfo instance for a Tensor to use as graph inputs/outputs with the Model Editor API. + * + * User can release `tensor_info` after creating the OrtTypeInfo. + * + * \param[in] tensor_info Tensor type and shape information. + * \param[out] type_info TypeInfo instance for the tensor. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for a SparseTensor. + * + * Create an OrtTypeInfo instance for a SparseTensor to use as graph inputs/outputs with the Model Editor API. + * + * User can release `tensor_info` after creating the OrtTypeInfo. + * + * \param[in] tensor_info SparseTensor type and shape information. + * \param[out] type_info TypeInfo instance for the tensor. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateSparseTensorTypeInfo, _In_ const OrtTensorTypeAndShapeInfo* tensor_info, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for a Map. + * + * Create an OrtTypeInfo instance for a Map to use as graph inputs/outputs with the Model Editor API. + * + * User can release `map_value_type` after creating the OrtTypeInfo. + * + * \param[in] map_key_type Key type for the map. + * \param[in] map_value_type Value type for the map. + * \param[out] type_info TypeInfo instance for the map. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateMapTypeInfo, ONNXTensorElementDataType map_key_type, _In_ const OrtTypeInfo* map_value_type, + _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for a Sequence. + * + * Create an OrtTypeInfo instance for a Sequence to use as graph inputs/outputs with the Model Editor API. + * + * User can release `sequence_type` after creating the OrtTypeInfo. + * + * \param[in] sequence_type Sequence type and shape information. + * \param[out] type_info TypeInfo instance for the sequence. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateSequenceTypeInfo, _In_ const OrtTypeInfo* sequence_type, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtTypeInfo instance for an Optional. + * + * Create an OrtTypeInfo instance for an Optional to use as graph inputs/outputs with the Model Editor API. + * + * User can release `contained_type` after creating the OrtTypeInfo. + * + * \param[in] contained_type Tensor type and shape information. + * \param[out] type_info TypeInfo instance for the tensor. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateOptionalTypeInfo, _In_ const OrtTypeInfo* contained_type, _Outptr_ OrtTypeInfo** type_info); + + /** \brief Create an OrtValueInfo for use as an OrtGraph input or output. + * + * \param[in] name The name of the input or output. + * \param[in] type_info The type information for the input or output. The provided value is copied. + * \param[out] value_info The OrtValueInfo instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateValueInfo, _In_ const char* name, _In_ const OrtTypeInfo* type_info, + _Outptr_ OrtValueInfo** value_info); + + /** \brief Create an OrtNode to add to an OrtGraph. + * + * Create an OrtNode. + * + * Create attributes with CreateOpAttr. OrtOpAttr instances are copied. + * + * \param[in] operator_name The name of the operator. + * \param[in] domain_name The domain of the operator. Use an empty string for ONNX operators. + * \param[in] node_name The name of the node. + * \param[in] input_names The names of the inputs. + * \param[in] input_names_len The number of input names. + * \param[in] output_names The names of the outputs. + * \param[in] output_names_len The number of output names. + * \param[in] attributes The optional attributes of the node. + * \param[in] attribs_len The number of attributes. May be zero. + * \param[out] node The OrtNode instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateNode, _In_ const char* operator_name, _In_ const char* domain_name, _In_ const char* node_name, + _In_reads_(input_names_len) const char* const* input_names, size_t input_names_len, + _In_reads_(output_names_len) const char* const* output_names, size_t output_names_len, + _In_reads_(attribs_len) _In_opt_ OrtOpAttr** attributes, _In_ size_t attribs_len, + _Outptr_ OrtNode** node); + + /** \brief Create an OrtGraph + * \snippet{doc} snippets.dox OrtStatus Return Value + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateGraph, _Outptr_ OrtGraph** graph); + + /** \brief Set the inputs for the OrtGraph. + * + * Set the graph inputs. This will replace any existing inputs with the new values. + * The OrtGraph takes ownership of the OrtValueInfo instances and you should NOT call ReleaseOrtValueInfo. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] inputs The input OrtValueInfo instances. + * \param[in] inputs_len The number of input OrtValueInfo instances. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SetGraphInputs, _Inout_ OrtGraph* graph, + _In_reads_(inputs_len) _In_ OrtValueInfo** inputs, _In_ size_t inputs_len); + + /** \brief Set the outputs for the OrtGraph. + * + * Set the graph outputs. This will replace any existing outputs with the new values. + * The OrtGraph takes ownership of the OrtValueInfo instances provided and you should NOT call ReleaseOrtValueInfo. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] outputs The output OrtValueInfo instances. + * \param[in] outputs_len The number of output OrtValueInfo instances. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SetGraphOutputs, _Inout_ OrtGraph* graph, + _In_reads_(outputs_len) _In_ OrtValueInfo** outputs, _In_ size_t outputs_len); + + /** \brief Add an initializer to the OrtGraph + * + * ORT will take ownership of the OrtValue and you should NOT call ReleaseOrtValue. + * + * Two options: + * + * Allocated memory: + * Use CreateTensorAsOrtValue (allocates memory) and populate the tensor with the data. + * Set `data_is_external` to false. + * + * Pre-existing memory: + * Use CreateTensorWithDataAsOrtValue or CreateTensorWithDataAndDeleterAsOrtValue to create an OrtValue + * with a tensor that contains a pointer to the existing data. + * Set `data_is_external` to true. + * + * The pointer must remain valid for the duration of the inference session. + * If using CreateTensorWithDataAsOrtValue you are responsible for freeing the memory after the inference session + * is released. + * If using CreateTensorWithDataAndDeleterAsOrtValue, ORT will free the memory using the provided deleter as + * soon as the OrtValue is no longer in use. + * + * NOTE: A tensor containing pre-existing memory MUST have 128 bytes of data or more. + * For smaller tensors use CreateTensorAsOrtValue. + * + * ONNX shape inferencing does not support external data. An initializer involved in shape inferencing is + * typically small (a single value or limited by the rank of a tensor) and uses less than 128 bytes of + * memory, so this limit acts as a simple catch-all rule to avoid issues. + * e.g. Reshape's `shape`, Clip's `min` and `max`, various ops `axes`. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] name The value name for the initializer. + * \param[in] tensor The OrtValue instance containing the tensor data. + * \param[in] data_is_external Set to true if the data is external and should not be copied. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(AddInitializerToGraph, _Inout_ OrtGraph* graph, _In_ const char* name, _In_ OrtValue* tensor, + bool data_is_external); + + /** \brief Add an OrtNode to an OrtGraph + * + * Add the node to the graph. The OrtGraph will take ownership of OrtNode and you should NOT call ReleaseOrtNode. + * + * \param[in] graph The OrtGraph instance to update. + * \param[in] node The OrtNode instance to add to the graph. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(AddNodeToGraph, _Inout_ OrtGraph* graph, _In_ OrtNode* node); + + /** \brief Create an OrtModel. + * + * Create an OrtModel. + * + * This can be used to build a new model, or to augment an existing model. + * + * \param[in] domain_names The domain names for the model. + * If augmenting an existing model add additional domains if needed. + * \param[in] opset_versions The opset versions for the model. + * If augmenting an existing model add additional opset versions if needed. + * \param[in] opset_entries_len The number of domain_names and opset_versions entries. + * Domain and opset entries should be 1:1 + * \param[out] model The OrtModel instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModel, + _In_reads_(opset_entries_len) const char* const* domain_names, + _In_reads_(opset_entries_len) const int* opset_versions, + size_t opset_entries_len, + _Outptr_ OrtModel** model); + + /** \brief Add an OrtGraph to an OrtModel. + * + * Add the graph to a model. This should be called once when creating a new model. + * + * The OrtModel takes ownership of the OrtGraph and you should NOT call ReleaseOrtGraph. + * + * \param[in] model The OrtModel instance to update. + * \param[in] graph The OrtGraph instance to add to the model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(AddGraphToModel, _Inout_ OrtModel* model, _In_ OrtGraph* graph); + + /** \brief Create an OrtSession using the OrtModel. + * + * Create an inference session using the OrtModel instance. + * The OrtModel should have been populated with an OrtGraph containing nodes and initializers, and SetGraphInputs + * and SetGraphOutputs must have been called. + * This will validate the model, run optimizers, and prepare the session for inferencing. + * + * ReleaseOrtModel must be called to free the OrtModel after session creation. + * + * \param[in] env The OrtEnv instance. + * \param[in] model The OrtModel instance. + * \param[in] options The OrtSessionOptions instance. + * \param[out] out The OrtSession instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateSessionFromModel, _In_ const OrtEnv* env, _In_ const OrtModel* model, + _In_ const OrtSessionOptions* options, _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession to augment an existing model. + * + * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. + * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the + * model is finalized. + * + * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. + * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. + * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made + * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. + * + * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the + * session for inferencing by calling FinalizeModelEditorSession. + * + * \param{in} env The OrtEnv instance. + * \param{in} model_path The path to the existing ONNX model to augment. + * \param{in} options The OrtSessionOptions instance. + * \param{out} out The created OrtSession instance. + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModelEditorSession, _In_ const OrtEnv* env, _In_ const ORTCHAR_T* model_path, + _In_ const OrtSessionOptions* options, + _Outptr_ OrtSession** out); + + /** \brief Create an OrtSession to augment an existing model. + * + * Create an OrtSession with an existing model that will be augmented with additional nodes and initializers. + * Nodes can be added before or after the existing nodes in the model. ONNX Runtime will connect the nodes when the + * model is finalized. + * + * To add nodes and initializers to the existing model, first create an OrtModel using CreateModel. + * Add nodes and initializers to the OrtModel using AddNodeToGraph and AddInitializerToGraph. + * Graph inputs/outputs should be updated with SetGraphInputs and SetGraphOutputs as needed to reflect changes made + * by the new nodes. The list of graph inputs/outputs should be for the overall model and not just the new nodes. + * + * Add the new information from the OrtModel to the original model using ApplyModelToSession, and prepare the + * session for inferencing by calling FinalizeModelEditorSession. + * + * \param{in} env The OrtEnv instance. + * \param{in} model_data The model data for the existing model to augment. + * \param{in} model_data_length The length of the model data. + * \param{in} options The OrtSessionOptions instance. + * \param{out} out The created OrtSession instance. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModelEditorSessionFromArray, _In_ const OrtEnv* env, + _In_ const void* model_data, size_t model_data_length, + _In_ const OrtSessionOptions* options, + _Outptr_ OrtSession** out); + + /** \brief Query the session for the opset version of a domain. + * + * When using the Model Editor API to augment a model, any new nodes must conform to the opset version of the + * original model. To do that the user must be able to discover that opset version. + * Returns an error if the domain is not used in the model. + * + * \param[in] session OrtSession to query + * \param[in] domain Domain to query. The ONNX domain is an empty string. + * \param[out] opset The opset version of the domain. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(SessionGetOpsetForDomain, _In_ const OrtSession* session, _In_ const char* domain, _Out_ int* opset); + + /** \brief Apply changes to augment the ONNX model in a session created using CreateModelEditorSession[FromArray] + * + * Adds new nodes and updates graph inputs/outputs using `model` to augment the original ONNX model in the session. + * All changes will be validated. + * Call FinalizeModelEditorSession to prepare the session for inferencing. + * + * Existing input/outputs will only be updated if the OrtGraph inputs/outputs are set in the OrtModel. + * i.e. you don't need to call SetGraphInputs/SetGraphOutputs if they are unchanged. + * + * ReleaseOrtModel must be called to free the OrtModel after it is applied to the session. + * + * \param[in] session OrtSession to update. Session must have been created using CreateModelEditorSession[FromArray]. + * \param[in] model OrtModel containing new nodes, new initializers, and updated graph input and/or output info. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ApplyModelToModelEditorSession, _Inout_ OrtSession* session, _In_ OrtModel* model); + + /** \brief Finalize the Model Editor session that was created using CreateModelEditorSession[FromArray]. + * + * Finalize the Model Editor session that augmented an ONNX model by adding new nodes. + * This will run optimizers and prepare the session for inferencing. + * + * \param[in] session OrtSession to finalize. Session must have been created using CreateModelEditorSession[FromArray]. + * \param[in] options OrtSessionOptions to use for the session. + * \param[in] prepacked_weights_container Optional OrtPrepackedWeightsContainer to use for the session. + Set to nullptr if not used. + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(FinalizeModelEditorSession, _Inout_ OrtSession* session, _In_ const OrtSessionOptions* options, + _In_opt_ OrtPrepackedWeightsContainer* prepacked_weights_container); +#endif // !defined(ORT_MINIMAL_BUILD) +}; + +/** + * ORT Compile API + */ + +/** + * \brief The OrtCompileApi struct provides functions to compile ONNX models. + * + * Execution providers that support compilation fuse a subgraph into an EPContext node that wraps a provider-specific + * binary representation of the subgraph. + * For more details about the EPContext design, refer to: + * \htmlonly + * EPContext design document. + * \endhtmlonly + * + * Example (error handling not shown): + * OrtStatus* status = NULL; + * OrtCompileApi* compile_api = ort_api->GetCompileApi(); + * OrtModelCompilationOptions* compile_options = NULL; + * + * status = compile_api->CreateModelCompilationOptionsFromSessionOptions(env, session_options, &compile_options); + * status = compile_api->ModelCompilationOptions_SetInputModelPath(compile_options, ORT_TSTR("model.onnx")); + * status = compile_api->ModelCompilationOptions_SetOutputModelPath(compile_options, ORT_TSTR("model.compiled.onnx")); + * status = compile_api->CompileModel(env, compile_options); + * compile_api->ReleaseModelCompilationOptions(compile_options); + * + * \since Version 1.22. + */ +struct OrtCompileApi { + /// @} + /// \name OrtModelCompilationOptions + /// @{ + ORT_CLASS_RELEASE(ModelCompilationOptions); + + /** \brief Creates an OrtModelCompilationOptions object from an existing OrtSessionOptions object. + * + * An OrtModelCompilationOptions object contains the settings used to generate a compiled ONNX model. + * The OrtSessionOptions object has the execution providers with which the model will be compiled. + * + * ReleaseOrtModelCompilationsOptions must be called to free the OrtModelCompilationOptions after calling + * CompileModel. + * + * \param[in] env OrtEnv object. + * \param[in] session_options The OrtSessionOptions instance from which to create the OrtModelCompilationOptions. + * \param[out] out The created OrtModelCompilationOptions instance. + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateModelCompilationOptionsFromSessionOptions, _In_ const OrtEnv* env, + _In_ const OrtSessionOptions* session_options, _Outptr_ OrtModelCompilationOptions** out); + + /** \brief Sets the file path to the input ONNX model to compile. + * + * The input model's location (e.g., file path or memory buffer) must be set with either + * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] input_model_path Null terminated string of the path (wchar on Windows, char otherwise). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetInputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const ORTCHAR_T* input_model_path); + + /** \brief Sets the buffer that stores the bytes of the loaded ONNX model to compile. + * + * The input model's location (e.g., file path or memory buffer) must be set with either + * ModelCompilationOptions_SetInputModelPath or ModelCompilationOptions_SetInputModelFromBuffer. + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] input_model_data Buffer containing the loaded ONNX model bytes. + * \param[in] input_model_data_size The number of bytes in the `input_model_data` buffer. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetInputModelFromBuffer, + _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const void* input_model_data, + size_t input_model_data_size); + + /** \brief Sets the file path for the output ONNX model generated by CompileModel. + * + * The output model's location (e.g., file path or memory buffer) can be set with either + * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. + * + * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on + * the input model's file path. Examples: + * /Path/my_model.onnx -> /Path/my_model_ctx.onnx + * /Path/my_model -> /Path/my_model_ctx.onnx + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] output_model_path Null terminated string of the path (wchar on Windows, char otherwise). + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelPath, _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const ORTCHAR_T* output_model_path); + + /** \brief Optionally sets the file that should store external initializers for the compiled ONNX model. + * If not set, initializers are stored within the model. + * + * Only initializers for nodes that were not compiled are stored in the external initializers file. + * Compiled nodes contain their initializer data within the `ep_cache_context` attribute of EPContext nodes. + * Refer to ModelCompilationOptions_SetEpContextEmbedMode. + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] external_initializers_file_path Null terminated string of the path to the file. + * \param[in] external_initializers_size_threshold Initializers larger than this threshold are stored in the file. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelExternalInitializersFile, + _In_ OrtModelCompilationOptions* model_compile_options, + _In_ const ORTCHAR_T* external_initializers_file_path, + size_t external_initializers_size_threshold); + + /** \brief Configures model compilation to store the output compiled ONNX model in a buffer. + * + * The caller passes an OrtAllocator that ONNX Runtime uses to allocate memory for the buffer. + * + * The output model's location (e.g., file path or memory buffer) can be set with either + * ModelCompilationOptions_SetOutputModelPath or ModelCompilationOptions_SetOutputModelBuffer. + * + * If the output model's location is not set, ONNX Runtime will generate an output file with a path based on + * the input model's file path. Examples: + * /Path/my_model.onnx -> /Path/my_model_ctx.onnx + * /Path/my_model -> /Path/my_model_ctx.onnx + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] allocator The allocator used to allocate the buffer for the compiled model. + * \param[out] output_model_buffer_ptr Pointer to the buffer that stores the compiled model. + * \param[out] output_model_buffer_size_ptr Pointer set to the size of output model in bytes. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetOutputModelBuffer, + _In_ OrtModelCompilationOptions* model_compile_options, + _Inout_ OrtAllocator* allocator, + _Outptr_ void** output_model_buffer_ptr, + _Out_ size_t* output_model_buffer_size_ptr); + + /** \brief Enables or disables the embedding of EPContext binary data into the `ep_cache_context` attribute + * of EPContext nodes. Defaults to false. + * + * If enabled, the `ep_cache_context` attribute of EPContext nodes will store the context binary data, which may + * include weights for compiled subgraphs. + * + * If disabled, the `ep_cache_context` attribute of EPContext nodes will contain the path to the file containing the + * context binary data. The path is set by the execution provider creating the EPContext node. + * + * More details relate to EPContext design refers to: + * \htmlonly + * EPContext design document. + * \endhtmlonly + * + * \param[in] model_compile_options The OrtModelCompilationOptions instance. + * \param[in] embed_ep_context_in_model True to embed EPContext binary data into the EPContext node + * `ep_cache_context` attributes. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(ModelCompilationOptions_SetEpContextEmbedMode, _In_ OrtModelCompilationOptions* model_compile_options, + bool embed_ep_context_in_model); + + /** \brief Compiles an input ONNX model with the given compilation options. + * + * \param[in] env OrtEnv object. + * \param[in] model_options The compilation options that defines compilation options for a model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CompileModel, _In_ const OrtEnv* env, _In_ const OrtModelCompilationOptions* model_options); +}; + +ORT_RUNTIME_CLASS(Ep); +ORT_RUNTIME_CLASS(EpFactory); + +struct OrtEpApi { + /** \brief Create an OrtEpDevice for the EP and an OrtHardwareDevice. + * \param[in] ep_factory Execution provider factory that is creating the instance. + * \param[in] hardware_device Hardware device that the EP can utilize. + * \param[in] ep_metadata Optional OrtKeyValuePairs instance for execution provider metadata that may be used + * during execution provider selection and passed to CreateEp. + * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. + * \param[in] ep_options Optional OrtKeyValuePairs instance for execution provider options that will be added + * to the Session configuration options if the execution provider is selected. + * ep_device will copy this instance and the user should call ReleaseKeyValuePairs. + * \param ep_device OrtExecutionDevice that is created. + * + * \since Version 1.22. + */ + ORT_API2_STATUS(CreateEpDevice, _In_ OrtEpFactory* ep_factory, + _In_ const OrtHardwareDevice* hardware_device, + _In_opt_ const OrtKeyValuePairs* ep_metadata, + _In_opt_ const OrtKeyValuePairs* ep_options, + _Out_ OrtEpDevice** ep_device); + + ORT_CLASS_RELEASE(EpDevice); +}; + +/** + * \brief The OrtEp struct provides functions to implement for an execution provider. + * \since Version 1.22. + */ +struct OrtEp { + /** \brief The ONNX Runtime version the execution provider was compiled with. + * + * Implementation should set to ORT_API_VERSION. + * ORT will use this to ensure it does not call functions that were not available when the library was compiled. + * + * \since Version 1.22. + */ + uint32_t ort_version_supported; + + /** \brief Get the execution provider name. + * + * \param[in] this_ptr The OrtEp instance. + * \return The execution provider name. + * + * \note Returned string is owned by ORT and valid until UnregisterExecutionProviderLibrary is called. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetName)(const OrtEp* this_ptr); + + // OrtStatus* GetCapability(OrtEp* ep, const OrtGraph* graph, + // size_t* num_supported_subgraphs, + // OrtIndexedSubgraph** supported_subgraphs, OrtAllocator* allocator); + + // OrtStatus* Compile(OrtEp* ep, const OrtGraph** graphs, OrtNode** fused_graph_nodes, + // size_t count, OrtNodeComputeInfo* node_compute_infos); + + // TODO: Implement OrtEpApi and the complete OrtEp interface as the next step. +}; + +/** \brief The function signature that ORT will call to create OrtEpFactory instances. + * + * This must be available in a function called 'CreateEpFactories' in the execution provider library. + * + * \param[in] registered_name The name the execution library is registered with by RegisterExecutionProviderLibrary + * \param[in] ort_api_base The OrtApiBase instance that is used by the factory to get the OrtApi instance for the + * version of ORT that the library was compiled against. + * \param[in,out] factories The implementation should create and add OrtEpFactory instances to this + * pre-allocated array. + * i.e. usage is `factories[0] = new MyEpFactory();` + * \param[in] max_factories The maximum number of OrtEpFactory instances that can be added to `factories`. + * Current default is to allow 4 factories. This can be increased in the future if needed. + * \param[out] num_factories The number of OrtEpFactory instances created by the factory and added to `factories`. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ +typedef OrtStatus* (*CreateEpApiFactoriesFn)(_In_ const char* registered_name, _In_ const OrtApiBase* ort_api_base, + _Inout_ OrtEpFactory** factories, _In_ size_t max_factories, + _Out_ size_t* num_factories); + +/** \brief The function signature that ORT will call to release an OrtEpFactory instance. + * + * This must be available in a function called 'ReleaseEpFactory' in the execution provider library. + * + * \param[in] factory The OrtEpFactory instance to release. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version 1.22. + */ +typedef OrtStatus* (*ReleaseEpApiFactoryFn)(_In_ OrtEpFactory* factory); + +/** + * \brief The OrtEpFactory provides functions to create and manage execution providers. + * \since Version 1.22. + */ +struct OrtEpFactory { + /** \brief The ONNX Runtime version the execution provider was compiled with. + * + * Implementation should set to ORT_API_VERSION. + * ORT will use this to ensure it does not call functions that were not available when the library was compiled. + * + * \since Version 1.22. + */ + uint32_t ort_version_supported; + + /** \brief Get the name the of the execution provider that the factory creates. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \return The name of the execution provider the factory creates. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetName)(const OrtEpFactory* this_ptr); + + /** \brief Get the name of vendor who owns the execution provider that the factory creates. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \return vendor The vendor name of the execution provider the factory creates. + * + * \since Version 1.22. + */ + const char*(ORT_API_CALL* GetVendor)(const OrtEpFactory* this_ptr); // return EP vendor + + /** \brief Get information from the execution provider if it supports the OrtHardwareDevice. + * + * \param[in] this_ptr The OrtEpFactory instance. + * Non-const as the factory is passed through to the CreateEp call via the OrtEpDevice. + * \param[in] devices The OrtHardwareDevice instances that are available. + * \param[in] num_devices The number of OrtHardwareDevice instances. + * \param[out] ep_devices OrtEpDevice instances for each OrtHardwareDevice that the EP can use. + * The implementation should call OrtEpApi::CreateEpDevice to create, and add the OrtEpDevice + * instances to this pre-allocated array. ORT will take ownership of the values returned. + * i.e. usage is `ep_devices[0] = ;` + * \param[in] max_ep_devices The maximum number of OrtEpDevices that can be added to ep_devices. + * Current default is 8. This can be increased if needed. + * \param[out] num_ep_devices The number of EP devices added to ep_devices. + * \return true if the factory can create an execution provider that uses `device`. + * + * \note ORT will take ownership or ep_metadata and/or ep_options if they are not null. + * + * \since Version 1.22. + */ + OrtStatus*(ORT_API_CALL* GetSupportedDevices)(_In_ OrtEpFactory* this_ptr, + _In_reads_(num_devices) const OrtHardwareDevice* const* devices, + _In_ size_t num_devices, + _Inout_ OrtEpDevice** ep_devices, + _In_ size_t max_ep_devices, + _Out_ size_t* num_ep_devices); + + /** \brief Function to create an OrtEp instance for use in a Session. + * + * ORT will call ReleaseEp to release the instance when it is no longer needed. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \param[in] devices The OrtHardwareDevice instances that the execution provider was selected to use. + * \param[in] ep_metadata_pairs Execution provider metadata that was provided to OrtEpApi::CreateEpDevice, for each + * device. + * \param[in] num_devices The number of devices the execution provider was selected for. + * \param[in] session_options The OrtSessionOptions instance that contains the configuration options for the + * session. This will include ep_options from GetSupportedDevices as well as any + * user provided overrides. + * Execution provider options will have been added with a prefix of 'ep..'. + * The OrtSessionOptions instance will NOT be valid after this call and should not be + * stored for later use. + * \param[in] logger The OrtLogger instance for the session that the execution provider should use for logging. + * \param[out] ep The OrtEp instance created by the factory. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + * \since Version . This is a placeholder. + */ + OrtStatus*(ORT_API_CALL* CreateEp)(_In_ OrtEpFactory* this_ptr, + _In_reads_(num_devices) const OrtHardwareDevice* const* devices, + _In_reads_(num_devices) const OrtKeyValuePairs* const* ep_metadata_pairs, + _In_ size_t num_devices, + _In_ const OrtSessionOptions* session_options, + _In_ const OrtLogger* logger, _Outptr_ OrtEp** ep); + + /** \brief Release the OrtEp instance. + * + * \param[in] this_ptr The OrtEpFactory instance. + * \param[in] ep The OrtEp instance to release. + * + * \since Version . This is a placeholder. + */ + void(ORT_API_CALL* ReleaseEp)(OrtEpFactory* this_ptr, struct OrtEp* ep); +}; + +/* + * This is the old way to add the CUDA provider to the session, please use SessionOptionsAppendExecutionProvider_CUDA above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with CUDA support and the CUDA provider shared library exists + * + * \param device_id CUDA device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_CUDA, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the ROCm provider to the session, please use + * SessionOptionsAppendExecutionProvider_ROCM above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * HIP support and the ROCm provider shared library exists + * + * \param device_id HIP device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_ROCM, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the MIGraphX provider to the session, please use + * SessionOptionsAppendExecutionProvider_MIGraphX above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * HIP support and the MIGraphX provider shared library exists + * + * \param device_id HIP device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_MIGraphX, _In_ OrtSessionOptions* options, int device_id); + +/* + * This is the old way to add the oneDNN provider to the session, please use + * SessionOptionsAppendExecutionProvider_oneDNN above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with + * oneDNN support and the oneDNN provider shared library exists + * + * \param use_arena zero: false. non-zero: true. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Dnnl, _In_ OrtSessionOptions* options, int use_arena); + +/* + * This is the old way to add the TensorRT provider to the session, please use SessionOptionsAppendExecutionProvider_TensorRT_V2 above to access the latest functionality + * This function always exists, but will only succeed if Onnxruntime was built with TensorRT support and the TensorRT provider shared library exists + * + * \param device_id CUDA device id, starts from zero. + */ +ORT_API_STATUS(OrtSessionOptionsAppendExecutionProvider_Tensorrt, _In_ OrtSessionOptions* options, int device_id); + +#ifdef __cplusplus +} +#endif +/// @} diff --git a/3rdParty/ONNX/onnxruntime_cxx_api.h b/3rdParty/ONNX/onnxruntime_cxx_api.h index 1bf2e2f104..bc6f381bb8 100644 --- a/3rdParty/ONNX/onnxruntime_cxx_api.h +++ b/3rdParty/ONNX/onnxruntime_cxx_api.h @@ -1,2865 +1,2865 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// Summary: The Ort C++ API is a header only wrapper around the Ort C API. -// -// The C++ API simplifies usage by returning values directly instead of error codes, throwing exceptions on errors -// and automatically releasing resources in the destructors. The primary purpose of C++ API is exception safety so -// all the resources follow RAII and do not leak memory. -// -// Each of the C++ wrapper classes holds only a pointer to the C internal object. Treat them like smart pointers. -// To create an empty object, pass 'nullptr' to the constructor (for example, Env e{nullptr};). However, you can't use them -// until you assign an instance that actually holds an underlying object. -// -// For Ort objects only move assignment between objects is allowed, there are no copy constructors. -// Some objects have explicit 'Clone' methods for this purpose. -// -// ConstXXXX types are copyable since they do not own the underlying C object, so you can pass them to functions as arguments -// by value or by reference. ConstXXXX types are restricted to const only interfaces. -// -// UnownedXXXX are similar to ConstXXXX but also allow non-const interfaces. -// -// The lifetime of the corresponding owning object must eclipse the lifetimes of the ConstXXXX/UnownedXXXX types. They exists so you do not -// have to fallback to C types and the API with the usual pitfalls. In general, do not use C API from your C++ code. - -#pragma once -#include "onnxruntime_c_api.h" -#include "onnxruntime_float16.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef ORT_NO_EXCEPTIONS -#include -#endif - -/** \brief All C++ Onnxruntime APIs are defined inside this namespace - * - */ -namespace Ort { - -/** \brief All C++ methods that can fail will throw an exception of this type - * - * If ORT_NO_EXCEPTIONS is defined, then any error will result in a call to abort() - */ -struct Exception : std::exception { - Exception(std::string&& string, OrtErrorCode code) : message_{std::move(string)}, code_{code} {} - - OrtErrorCode GetOrtErrorCode() const { return code_; } - const char* what() const noexcept override { return message_.c_str(); } - - private: - std::string message_; - OrtErrorCode code_; -}; - -#ifdef ORT_NO_EXCEPTIONS -// The #ifndef is for the very special case where the user of this library wants to define their own way of handling errors. -// NOTE: This header expects control flow to not continue after calling ORT_CXX_API_THROW -#ifndef ORT_CXX_API_THROW -#define ORT_CXX_API_THROW(string, code) \ - do { \ - std::cerr << Ort::Exception(string, code) \ - .what() \ - << std::endl; \ - abort(); \ - } while (false) -#endif -#else -#define ORT_CXX_API_THROW(string, code) \ - throw Ort::Exception(string, code) -#endif - -// This is used internally by the C++ API. This class holds the global variable that points to the OrtApi, -// it's in a template so that we can define a global variable in a header and make -// it transparent to the users of the API. -template -struct Global { - static const OrtApi* api_; -}; - -// If macro ORT_API_MANUAL_INIT is defined, no static initialization will be performed. Instead, user must call InitApi() before using it. -template -#ifdef ORT_API_MANUAL_INIT -const OrtApi* Global::api_{}; -inline void InitApi() noexcept { Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); } - -// Used by custom operator libraries that are not linked to onnxruntime. Sets the global API object, which is -// required by C++ APIs. -// -// Example mycustomop.cc: -// -// #define ORT_API_MANUAL_INIT -// #include -// #undef ORT_API_MANUAL_INIT -// -// OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api_base) { -// Ort::InitApi(api_base->GetApi(ORT_API_VERSION)); -// // ... -// } -// -inline void InitApi(const OrtApi* api) noexcept { Global::api_ = api; } -#else -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(push) -// "Global initializer calls a non-constexpr function." Therefore you can't use ORT APIs in the other global initializers. -// Please define ORT_API_MANUAL_INIT if it conerns you. -#pragma warning(disable : 26426) -#endif -const OrtApi* Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(pop) -#endif -#endif - -/// This returns a reference to the ORT C API. -inline const OrtApi& GetApi() noexcept { return *Global::api_; } - -/// -/// This function returns the onnxruntime version string -/// -/// version string major.minor.rev -std::string GetVersionString(); - -/// -/// This function returns the onnxruntime build information: including git branch, -/// git commit id, build type(Debug/Release/RelWithDebInfo) and cmake cpp flags. -/// -/// string -std::string GetBuildInfoString(); - -/// -/// This is a C++ wrapper for OrtApi::GetAvailableProviders() and -/// returns a vector of strings representing the available execution providers. -/// -/// vector of strings -std::vector GetAvailableProviders(); - -/// -/// This returns a reference to the ORT C Model Editor API. Used if building or augmenting a model at runtime. -/// -/// ORT C Model Editor API reference -inline const OrtModelEditorApi& GetModelEditorApi() { - auto* api = GetApi().GetModelEditorApi(); - if (api == nullptr) { - // minimal build - ORT_CXX_API_THROW("Model Editor API is not available in this build", ORT_FAIL); - } - - return *api; -} - -/// -/// This returns a reference to the ORT C Compile API. Used if compiling a model at runtime. -/// -/// ORT C Compile API reference -inline const OrtCompileApi& GetCompileApi() { - auto* api = GetApi().GetCompileApi(); - if (api == nullptr) { - // minimal build - ORT_CXX_API_THROW("Compile API is not available in this build", ORT_FAIL); - } - - return *api; -} - -/// -/// This returns a reference to the ORT C EP API. Used if authoring a plugin execution provider. -/// -/// ORT C EP API reference -inline const OrtEpApi& GetEpApi() { - auto* api = GetApi().GetEpApi(); - if (api == nullptr) { - // minimal build - ORT_CXX_API_THROW("EP API is not available in this build", ORT_FAIL); - } - - return *api; -} - -/** \brief IEEE 754 half-precision floating point data type - * - * \details This struct is used for converting float to float16 and back - * so the user could feed inputs and fetch outputs using these type. - * - * The size of the structure should align with uint16_t and one can freely cast - * uint16_t buffers to/from Ort::Float16_t to feed and retrieve data. - * - * \code{.unparsed} - * // This example demonstrates converion from float to float16 - * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; - * std::vector fp16_values; - * fp16_values.reserve(std::size(values)); - * std::transform(std::begin(values), std::end(values), std::back_inserter(fp16_values), - * [](float value) { return Ort::Float16_t(value); }); - * - * \endcode - */ -struct Float16_t : onnxruntime_float16::Float16Impl { - private: - /// - /// Constructor from a 16-bit representation of a float16 value - /// No conversion is done here. - /// - /// 16-bit representation - constexpr explicit Float16_t(uint16_t v) noexcept { val = v; } - - public: - using Base = onnxruntime_float16::Float16Impl; - - /// - /// Default constructor - /// - Float16_t() = default; - - /// - /// Explicit conversion to uint16_t representation of float16. - /// - /// uint16_t bit representation of float16 - /// new instance of Float16_t - constexpr static Float16_t FromBits(uint16_t v) noexcept { return Float16_t(v); } - - /// - /// __ctor from float. Float is converted into float16 16-bit representation. - /// - /// float value - explicit Float16_t(float v) noexcept { val = Base::ToUint16Impl(v); } - - /// - /// Converts float16 to float - /// - /// float representation of float16 value - float ToFloat() const noexcept { return Base::ToFloatImpl(); } - - /// - /// Checks if the value is negative - /// - /// true if negative - using Base::IsNegative; - - /// - /// Tests if the value is NaN - /// - /// true if NaN - using Base::IsNaN; - - /// - /// Tests if the value is finite - /// - /// true if finite - using Base::IsFinite; - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - using Base::IsPositiveInfinity; - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - using Base::IsNegativeInfinity; - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - using Base::IsInfinity; - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - using Base::IsNaNOrZero; - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - using Base::IsNormal; - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - using Base::IsSubnormal; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - using Base::Abs; - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - using Base::Negate; - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - using Base::AreZero; - - /// - /// User defined conversion operator. Converts Float16_t to float. - /// - explicit operator float() const noexcept { return ToFloat(); } - - using Base::operator==; - using Base::operator!=; - using Base::operator<; -}; - -static_assert(sizeof(Float16_t) == sizeof(uint16_t), "Sizes must match"); - -/** \brief bfloat16 (Brain Floating Point) data type - * - * \details This struct is used for converting float to bfloat16 and back - * so the user could feed inputs and fetch outputs using these type. - * - * The size of the structure should align with uint16_t and one can freely cast - * uint16_t buffers to/from Ort::BFloat16_t to feed and retrieve data. - * - * \code{.unparsed} - * // This example demonstrates converion from float to float16 - * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; - * std::vector bfp16_values; - * bfp16_values.reserve(std::size(values)); - * std::transform(std::begin(values), std::end(values), std::back_inserter(bfp16_values), - * [](float value) { return Ort::BFloat16_t(value); }); - * - * \endcode - */ -struct BFloat16_t : onnxruntime_float16::BFloat16Impl { - private: - /// - /// Constructor from a uint16_t representation of bfloat16 - /// used in FromBits() to escape overload resolution issue with - /// constructor from float. - /// No conversion is done. - /// - /// 16-bit bfloat16 value - constexpr explicit BFloat16_t(uint16_t v) noexcept { val = v; } - - public: - using Base = onnxruntime_float16::BFloat16Impl; - - BFloat16_t() = default; - - /// - /// Explicit conversion to uint16_t representation of bfloat16. - /// - /// uint16_t bit representation of bfloat16 - /// new instance of BFloat16_t - static constexpr BFloat16_t FromBits(uint16_t v) noexcept { return BFloat16_t(v); } - - /// - /// __ctor from float. Float is converted into bfloat16 16-bit representation. - /// - /// float value - explicit BFloat16_t(float v) noexcept { val = Base::ToUint16Impl(v); } - - /// - /// Converts bfloat16 to float - /// - /// float representation of bfloat16 value - float ToFloat() const noexcept { return Base::ToFloatImpl(); } - - /// - /// Checks if the value is negative - /// - /// true if negative - using Base::IsNegative; - - /// - /// Tests if the value is NaN - /// - /// true if NaN - using Base::IsNaN; - - /// - /// Tests if the value is finite - /// - /// true if finite - using Base::IsFinite; - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - using Base::IsPositiveInfinity; - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - using Base::IsNegativeInfinity; - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - using Base::IsInfinity; - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - using Base::IsNaNOrZero; - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - using Base::IsNormal; - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - using Base::IsSubnormal; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - using Base::Abs; - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - using Base::Negate; - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - using Base::AreZero; - - /// - /// User defined conversion operator. Converts BFloat16_t to float. - /// - explicit operator float() const noexcept { return ToFloat(); } - - // We do not have an inherited impl for the below operators - // as the internal class implements them a little differently - bool operator==(const BFloat16_t& rhs) const noexcept; - bool operator!=(const BFloat16_t& rhs) const noexcept { return !(*this == rhs); } - bool operator<(const BFloat16_t& rhs) const noexcept; -}; - -static_assert(sizeof(BFloat16_t) == sizeof(uint16_t), "Sizes must match"); - -/** \brief float8e4m3fn (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E4M3FN_t { - uint8_t value; - constexpr Float8E4M3FN_t() noexcept : value(0) {} - constexpr Float8E4M3FN_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E4M3FN_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E4M3FN_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E4M3FN_t) == sizeof(uint8_t), "Sizes must match"); - -/** \brief float8e4m3fnuz (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E4M3FNUZ_t { - uint8_t value; - constexpr Float8E4M3FNUZ_t() noexcept : value(0) {} - constexpr Float8E4M3FNUZ_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E4M3FNUZ_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E4M3FNUZ_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E4M3FNUZ_t) == sizeof(uint8_t), "Sizes must match"); - -/** \brief float8e5m2 (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E5M2_t { - uint8_t value; - constexpr Float8E5M2_t() noexcept : value(0) {} - constexpr Float8E5M2_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E5M2_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E5M2_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E5M2_t) == sizeof(uint8_t), "Sizes must match"); - -/** \brief float8e5m2fnuz (Float8 Floating Point) data type - * \details It is necessary for type dispatching to make use of C++ API - * The type is implicitly convertible to/from uint8_t. - * See https://onnx.ai/onnx/technical/float8.html for further details. - */ -struct Float8E5M2FNUZ_t { - uint8_t value; - constexpr Float8E5M2FNUZ_t() noexcept : value(0) {} - constexpr Float8E5M2FNUZ_t(uint8_t v) noexcept : value(v) {} - constexpr operator uint8_t() const noexcept { return value; } - // nan values are treated like any other value for operator ==, != - constexpr bool operator==(const Float8E5M2FNUZ_t& rhs) const noexcept { return value == rhs.value; }; - constexpr bool operator!=(const Float8E5M2FNUZ_t& rhs) const noexcept { return value != rhs.value; }; -}; - -static_assert(sizeof(Float8E5M2FNUZ_t) == sizeof(uint8_t), "Sizes must match"); - -namespace detail { -// This is used internally by the C++ API. This macro is to make it easy to generate overloaded methods for all of the various OrtRelease* functions for every Ort* type -// This can't be done in the C API since C doesn't have function overloading. -#define ORT_DEFINE_RELEASE(NAME) \ - inline void OrtRelease(Ort##NAME* ptr) { GetApi().Release##NAME(ptr); } - -#define ORT_DEFINE_RELEASE_FROM_API_STRUCT(NAME, API_GETTER) \ - inline void OrtRelease(Ort##NAME* ptr) { API_GETTER().Release##NAME(ptr); } - -ORT_DEFINE_RELEASE(Allocator); -ORT_DEFINE_RELEASE(MemoryInfo); -ORT_DEFINE_RELEASE(CustomOpDomain); -ORT_DEFINE_RELEASE(ThreadingOptions); -ORT_DEFINE_RELEASE(Env); -ORT_DEFINE_RELEASE(RunOptions); -ORT_DEFINE_RELEASE(LoraAdapter); -ORT_DEFINE_RELEASE(Session); -ORT_DEFINE_RELEASE(SessionOptions); -ORT_DEFINE_RELEASE(TensorTypeAndShapeInfo); -ORT_DEFINE_RELEASE(SequenceTypeInfo); -ORT_DEFINE_RELEASE(MapTypeInfo); -ORT_DEFINE_RELEASE(TypeInfo); -ORT_DEFINE_RELEASE(Value); -ORT_DEFINE_RELEASE(ModelMetadata); -ORT_DEFINE_RELEASE(IoBinding); -ORT_DEFINE_RELEASE(ArenaCfg); -ORT_DEFINE_RELEASE(Status); -ORT_DEFINE_RELEASE(OpAttr); -ORT_DEFINE_RELEASE(Op); -ORT_DEFINE_RELEASE(KernelInfo); -ORT_DEFINE_RELEASE(ValueInfo); -ORT_DEFINE_RELEASE(Node); -ORT_DEFINE_RELEASE(Graph); -ORT_DEFINE_RELEASE(Model); -ORT_DEFINE_RELEASE(KeyValuePairs) -ORT_DEFINE_RELEASE_FROM_API_STRUCT(ModelCompilationOptions, GetCompileApi); -ORT_DEFINE_RELEASE_FROM_API_STRUCT(EpDevice, GetEpApi); - -#undef ORT_DEFINE_RELEASE -#undef ORT_DEFINE_RELEASE_FROM_API_STRUCT - -/** \brief This is a tagging template type. Use it with Base to indicate that the C++ interface object - * has no ownership of the underlying C object. - */ -template -struct Unowned { - using Type = T; -}; - -/** \brief Used internally by the C++ API. C++ wrapper types inherit from this. - * This is a zero cost abstraction to wrap the C API objects and delete them on destruction. - * - * All of the C++ classes - * a) serve as containers for pointers to objects that are created by the underlying C API. - * Their size is just a pointer size, no need to dynamically allocate them. Use them by value. - * b) Each of struct XXXX, XXX instances function as smart pointers to the underlying C API objects. - * they would release objects owned automatically when going out of scope, they are move-only. - * c) ConstXXXX and UnownedXXX structs function as non-owning, copyable containers for the above pointers. - * ConstXXXX allow calling const interfaces only. They give access to objects that are owned by somebody else - * such as Onnxruntime or instances of XXXX classes. - * d) serve convenient interfaces that return C++ objects and further enhance exception and type safety so they can be used - * in C++ code. - * - */ - -/// -/// This is a non-const pointer holder that is move-only. Disposes of the pointer on destruction. -/// -template -struct Base { - using contained_type = T; - - constexpr Base() = default; - constexpr explicit Base(contained_type* p) noexcept : p_{p} {} - ~Base() { - OrtRelease(p_); - } - - Base(const Base&) = delete; - Base& operator=(const Base&) = delete; - - Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } - Base& operator=(Base&& v) noexcept { - OrtRelease(p_); - p_ = v.release(); - return *this; - } - - constexpr operator contained_type*() const noexcept { return p_; } - - /// \brief Relinquishes ownership of the contained C object pointer - /// The underlying object is not destroyed - contained_type* release() { - T* p = p_; - p_ = nullptr; - return p; - } - - protected: - contained_type* p_{}; -}; - -// Undefined. For const types use Base> -template -struct Base; - -/// -/// Covers unowned pointers owned by either the ORT -/// or some other instance of CPP wrappers. -/// Used for ConstXXX and UnownedXXXX types that are copyable. -/// Also convenient to wrap raw OrtXX pointers . -/// -/// -template -struct Base> { - using contained_type = typename Unowned::Type; - - constexpr Base() = default; - constexpr explicit Base(contained_type* p) noexcept : p_{p} {} - - ~Base() = default; - - Base(const Base&) = default; - Base& operator=(const Base&) = default; - - Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } - Base& operator=(Base&& v) noexcept { - p_ = nullptr; - std::swap(p_, v.p_); - return *this; - } - - constexpr operator contained_type*() const noexcept { return p_; } - - protected: - contained_type* p_{}; -}; - -// Light functor to release memory with OrtAllocator -struct AllocatedFree { - OrtAllocator* allocator_; - explicit AllocatedFree(OrtAllocator* allocator) - : allocator_(allocator) {} - void operator()(void* ptr) const { - if (ptr) allocator_->Free(allocator_, ptr); - } -}; - -} // namespace detail - -struct AllocatorWithDefaultOptions; -struct Env; -struct EpDevice; -struct Graph; -struct Model; -struct Node; -struct ModelMetadata; -struct TypeInfo; -struct Value; -struct ValueInfo; - -/** \brief unique_ptr typedef used to own strings allocated by OrtAllocators - * and release them at the end of the scope. The lifespan of the given allocator - * must eclipse the lifespan of AllocatedStringPtr instance - */ -using AllocatedStringPtr = std::unique_ptr; - -/** \brief The Status that holds ownership of OrtStatus received from C API - * Use it to safely destroy OrtStatus* returned from the C API. Use appropriate - * constructors to construct an instance of a Status object from exceptions. - */ -struct Status : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit Status(std::nullptr_t) noexcept {} ///< Create an empty object, must be assigned a valid one to be used - explicit Status(OrtStatus* status) noexcept; ///< Takes ownership of OrtStatus instance returned from the C API. - explicit Status(const Exception&) noexcept; ///< Creates status instance out of exception - explicit Status(const std::exception&) noexcept; ///< Creates status instance out of exception - Status(const char* message, OrtErrorCode code) noexcept; ///< Creates status instance out of null-terminated string message. - std::string GetErrorMessage() const; - OrtErrorCode GetErrorCode() const; - bool IsOK() const noexcept; ///< Returns true if instance represents an OK (non-error) status. -}; - -/** \brief The ThreadingOptions - * - * The ThreadingOptions used for set global threadpools' options of The Env. - */ -struct ThreadingOptions : detail::Base { - /// \brief Wraps OrtApi::CreateThreadingOptions - ThreadingOptions(); - - /// \brief Wraps OrtApi::SetGlobalIntraOpNumThreads - ThreadingOptions& SetGlobalIntraOpNumThreads(int intra_op_num_threads); - - /// \brief Wraps OrtApi::SetGlobalInterOpNumThreads - ThreadingOptions& SetGlobalInterOpNumThreads(int inter_op_num_threads); - - /// \brief Wraps OrtApi::SetGlobalSpinControl - ThreadingOptions& SetGlobalSpinControl(int allow_spinning); - - /// \brief Wraps OrtApi::SetGlobalDenormalAsZero - ThreadingOptions& SetGlobalDenormalAsZero(); - - /// \brief Wraps OrtApi::SetGlobalCustomCreateThreadFn - ThreadingOptions& SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); - - /// \brief Wraps OrtApi::SetGlobalCustomThreadCreationOptions - ThreadingOptions& SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options); - - /// \brief Wraps OrtApi::SetGlobalCustomJoinThreadFn - ThreadingOptions& SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); -}; - -namespace detail { -template -struct KeyValuePairsImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - const char* GetValue(const char* key) const; - - // get the pairs in unordered_map. needs to copy to std::string so the hash works as expected - std::unordered_map GetKeyValuePairs() const; - // get the pairs in two vectors. entries will be 1:1 between keys and values. avoids copying to std::string - void GetKeyValuePairs(std::vector& keys, std::vector& values) const; -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstKeyValuePairs = detail::KeyValuePairsImpl>; - -/** \brief Wrapper around ::OrtKeyValuePair */ -struct KeyValuePairs : detail::KeyValuePairsImpl { - explicit KeyValuePairs(std::nullptr_t) {} ///< No instance is created - /// Take ownership of a pointer created by C API - explicit KeyValuePairs(OrtKeyValuePairs* p) : KeyValuePairsImpl{p} {} - - /// \brief Wraps OrtApi::CreateKeyValuePairs - explicit KeyValuePairs(); - - /// \brief Wraps OrtApi::CreateKeyValuePairs and OrtApi::AddKeyValuePair - explicit KeyValuePairs(const std::unordered_map& kv_pairs); - - /// \brief Wraps OrtApi::AddKeyValuePair - void Add(const char* key, const char* value); - - /// \brief Wraps OrtApi::RemoveKeyValuePair - void Remove(const char* key); - - ConstKeyValuePairs GetConst() const { return ConstKeyValuePairs{this->p_}; } -}; - -namespace detail { -template -struct HardwareDeviceImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - OrtHardwareDeviceType Type() const; - uint32_t VendorId() const; - uint32_t DeviceId() const; - const char* Vendor() const; - ConstKeyValuePairs Metadata() const; -}; -} // namespace detail - -/** \brief Wrapper around ::OrtHardwareDevice - * \remarks HardwareDevice is always read-only for API users. - */ -using ConstHardwareDevice = detail::HardwareDeviceImpl>; - -namespace detail { -template -struct EpDeviceImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - const char* EpName() const; - const char* EpVendor() const; - ConstKeyValuePairs EpMetadata() const; - ConstKeyValuePairs EpOptions() const; - ConstHardwareDevice Device() const; -}; -} // namespace detail - -/** \brief Wrapper around ::OrtEpDevice - * \remarks EpDevice is always read-only for ORT API users. - */ -using ConstEpDevice = detail::EpDeviceImpl>; - -/** \brief Mutable EpDevice that is created by EpApi users. - */ -struct EpDevice : detail::EpDeviceImpl { - explicit EpDevice(std::nullptr_t) {} ///< No instance is created - explicit EpDevice(OrtEpDevice* p) : EpDeviceImpl{p} {} ///< Take ownership of a pointer created by C API - - /// \brief Wraps OrtEpApi::CreateEpDevice - EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, - ConstKeyValuePairs ep_metadata = {}, ConstKeyValuePairs ep_options = {}); -}; - -/** \brief The Env (Environment) - * - * The Env holds the logging state used by all other objects. - * Note: One Env must be created before using any other Onnxruntime functionality - */ -struct Env : detail::Base { - explicit Env(std::nullptr_t) {} ///< Create an empty Env object, must be assigned a valid one to be used - - /// \brief Wraps OrtApi::CreateEnv - Env(OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); - - /// \brief Wraps OrtApi::CreateEnvWithCustomLogger - Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param); - - /// \brief Wraps OrtApi::CreateEnvWithGlobalThreadPools - Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); - - /// \brief Wraps OrtApi::CreateEnvWithCustomLoggerAndGlobalThreadPools - Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, - OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); - - /// \brief C Interop Helper - explicit Env(OrtEnv* p) : Base{p} {} - - Env& EnableTelemetryEvents(); ///< Wraps OrtApi::EnableTelemetryEvents - Env& DisableTelemetryEvents(); ///< Wraps OrtApi::DisableTelemetryEvents - - Env& UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level); ///< Wraps OrtApi::UpdateEnvWithCustomLogLevel - - Env& CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocator - - Env& CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, - const std::unordered_map& options, - const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocatorV2 - - Env& RegisterExecutionProviderLibrary(const char* registration_name, const std::basic_string& path); ///< Wraps OrtApi::RegisterExecutionProviderLibrary - Env& UnregisterExecutionProviderLibrary(const char* registration_name); ///< Wraps OrtApi::UnregisterExecutionProviderLibrary - - std::vector GetEpDevices() const; -}; - -/** \brief Custom Op Domain - * - */ -struct CustomOpDomain : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit CustomOpDomain(std::nullptr_t) {} ///< Create an empty CustomOpDomain object, must be assigned a valid one to be used - - /// \brief Wraps OrtApi::CreateCustomOpDomain - explicit CustomOpDomain(const char* domain); - - // This does not take ownership of the op, simply registers it. - void Add(const OrtCustomOp* op); ///< Wraps CustomOpDomain_Add -}; - -/// \brief LoraAdapter holds a set of Lora Parameters loaded from a single file -struct LoraAdapter : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit LoraAdapter(std::nullptr_t) {} ///< Create an empty LoraAdapter object, must be assigned a valid one to be used - /// \brief Wraps OrtApi::CreateLoraAdapter - /// - /// The function attempts to load the adapter from the specified file - /// \param adapter_path The path to the Lora adapter - /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still - /// be copied to device if required by the model at inference time. - static LoraAdapter CreateLoraAdapter(const std::basic_string& adapter_path, - OrtAllocator* allocator); - - /// \brief Wraps OrtApi::CreateLoraAdapterFromArray - /// - /// The function attempts to load the adapter from the specified byte array. - /// \param bytes The byte array containing file LoraAdapter format - /// \param num_bytes The number of bytes in the byte array - /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still - /// be copied to device if required by the model at inference time. - static LoraAdapter CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, - OrtAllocator* allocator); -}; - -/** \brief RunOptions - * - */ -struct RunOptions : detail::Base { - explicit RunOptions(std::nullptr_t) {} ///< Create an empty RunOptions object, must be assigned a valid one to be used - RunOptions(); ///< Wraps OrtApi::CreateRunOptions - - RunOptions& SetRunLogVerbosityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogVerbosityLevel - int GetRunLogVerbosityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogVerbosityLevel - - RunOptions& SetRunLogSeverityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogSeverityLevel - int GetRunLogSeverityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogSeverityLevel - - RunOptions& SetRunTag(const char* run_tag); ///< wraps OrtApi::RunOptionsSetRunTag - const char* GetRunTag() const; ///< Wraps OrtApi::RunOptionsGetRunTag - - RunOptions& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddRunConfigEntry - - /** \brief Terminates all currently executing Session::Run calls that were made using this RunOptions instance - * - * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error - * Wraps OrtApi::RunOptionsSetTerminate - */ - RunOptions& SetTerminate(); - - /** \brief Clears the terminate flag so this RunOptions instance can be used in a new Session::Run call without it instantly terminating - * - * Wraps OrtApi::RunOptionsUnsetTerminate - */ - RunOptions& UnsetTerminate(); - - /** \brief Add the LoraAdapter to the list of active adapters. - * The setting does not affect RunWithBinding() calls. - * - * Wraps OrtApi::RunOptionsAddActiveLoraAdapter - * \param adapter The LoraAdapter to be used as the active adapter - */ - RunOptions& AddActiveLoraAdapter(const LoraAdapter& adapter); -}; - -namespace detail { -// Utility function that returns a SessionOption config entry key for a specific custom operator. -// Ex: custom_op.[custom_op_name].[config] -std::string MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config); -} // namespace detail - -/// -/// Class that represents session configuration entries for one or more custom operators. -/// -/// Example: -/// Ort::CustomOpConfigs op_configs; -/// op_configs.AddConfig("my_custom_op", "device_type", "CPU"); -/// -/// Passed to Ort::SessionOptions::RegisterCustomOpsLibrary. -/// -struct CustomOpConfigs { - CustomOpConfigs() = default; - ~CustomOpConfigs() = default; - CustomOpConfigs(const CustomOpConfigs&) = default; - CustomOpConfigs& operator=(const CustomOpConfigs&) = default; - CustomOpConfigs(CustomOpConfigs&& o) = default; - CustomOpConfigs& operator=(CustomOpConfigs&& o) = default; - - /** \brief Adds a session configuration entry/value for a specific custom operator. - * - * \param custom_op_name The name of the custom operator for which to add a configuration entry. - * Must match the name returned by the CustomOp's GetName() method. - * \param config_key The name of the configuration entry. - * \param config_value The value of the configuration entry. - * \return A reference to this object to enable call chaining. - */ - CustomOpConfigs& AddConfig(const char* custom_op_name, const char* config_key, const char* config_value); - - /** \brief Returns a flattened map of custom operator configuration entries and their values. - * - * The keys has been flattened to include both the custom operator name and the configuration entry key name. - * For example, a prior call to AddConfig("my_op", "key", "value") corresponds to the flattened key/value pair - * {"my_op.key", "value"}. - * - * \return An unordered map of flattened configurations. - */ - const std::unordered_map& GetFlattenedConfigs() const; - - private: - std::unordered_map flat_configs_; -}; - -/** \brief Options object used when creating a new Session object - * - * Wraps ::OrtSessionOptions object and methods - */ - -struct SessionOptions; - -namespace detail { -// we separate const-only methods because passing const ptr to non-const methods -// is only discovered when inline methods are compiled which is counter-intuitive -template -struct ConstSessionOptionsImpl : Base { - using B = Base; - using B::B; - - SessionOptions Clone() const; ///< Creates and returns a copy of this SessionOptions object. Wraps OrtApi::CloneSessionOptions - - std::string GetConfigEntry(const char* config_key) const; ///< Wraps OrtApi::GetSessionConfigEntry - bool HasConfigEntry(const char* config_key) const; ///< Wraps OrtApi::HasSessionConfigEntry - std::string GetConfigEntryOrDefault(const char* config_key, const std::string& def) const; -}; - -template -struct SessionOptionsImpl : ConstSessionOptionsImpl { - using B = ConstSessionOptionsImpl; - using B::B; - - SessionOptionsImpl& SetIntraOpNumThreads(int intra_op_num_threads); ///< Wraps OrtApi::SetIntraOpNumThreads - SessionOptionsImpl& SetInterOpNumThreads(int inter_op_num_threads); ///< Wraps OrtApi::SetInterOpNumThreads - SessionOptionsImpl& SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level); ///< Wraps OrtApi::SetSessionGraphOptimizationLevel - SessionOptionsImpl& SetDeterministicCompute(bool value); ///< Wraps OrtApi::SetDeterministicCompute - - SessionOptionsImpl& EnableCpuMemArena(); ///< Wraps OrtApi::EnableCpuMemArena - SessionOptionsImpl& DisableCpuMemArena(); ///< Wraps OrtApi::DisableCpuMemArena - - SessionOptionsImpl& SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_file); ///< Wraps OrtApi::SetOptimizedModelFilePath - - SessionOptionsImpl& EnableProfiling(const ORTCHAR_T* profile_file_prefix); ///< Wraps OrtApi::EnableProfiling - SessionOptionsImpl& DisableProfiling(); ///< Wraps OrtApi::DisableProfiling - - SessionOptionsImpl& EnableOrtCustomOps(); ///< Wraps OrtApi::EnableOrtCustomOps - - SessionOptionsImpl& EnableMemPattern(); ///< Wraps OrtApi::EnableMemPattern - SessionOptionsImpl& DisableMemPattern(); ///< Wraps OrtApi::DisableMemPattern - - SessionOptionsImpl& SetExecutionMode(ExecutionMode execution_mode); ///< Wraps OrtApi::SetSessionExecutionMode - - SessionOptionsImpl& SetLoadCancellationFlag(bool value); ///< Wraps OrtApi::SessionOptionsSetLoadCancellationFlag - - SessionOptionsImpl& SetLogId(const char* logid); ///< Wraps OrtApi::SetSessionLogId - SessionOptionsImpl& SetLogSeverityLevel(int level); ///< Wraps OrtApi::SetSessionLogSeverityLevel - - SessionOptionsImpl& Add(OrtCustomOpDomain* custom_op_domain); ///< Wraps OrtApi::AddCustomOpDomain - - SessionOptionsImpl& DisablePerSessionThreads(); ///< Wraps OrtApi::DisablePerSessionThreads - - SessionOptionsImpl& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddSessionConfigEntry - - SessionOptionsImpl& AddInitializer(const char* name, const OrtValue* ort_val); ///< Wraps OrtApi::AddInitializer - SessionOptionsImpl& AddExternalInitializers(const std::vector& names, const std::vector& ort_values); ///< Wraps OrtApi::AddExternalInitializers - SessionOptionsImpl& AddExternalInitializersFromFilesInMemory(const std::vector>& external_initializer_file_names, - const std::vector& external_initializer_file_buffer_array, - const std::vector& external_initializer_file_lengths); ///< Wraps OrtApi::AddExternalInitializersFromFilesInMemory - - SessionOptionsImpl& AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA - SessionOptionsImpl& AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA_V2 - SessionOptionsImpl& AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_ROCM - SessionOptionsImpl& AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO - ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO_V2 - SessionOptionsImpl& AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options = {}); - SessionOptionsImpl& AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT - SessionOptionsImpl& AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT - SessionOptionsImpl& AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_CANN - SessionOptionsImpl& AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options); - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_Dnnl - SessionOptionsImpl& AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options); - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider. Currently supports QNN, SNPE and XNNPACK. - SessionOptionsImpl& AppendExecutionProvider(const std::string& provider_name, - const std::unordered_map& provider_options = {}); - - /// Append EPs that have been registered previously with the OrtEnv. - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 - SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, - const KeyValuePairs& ep_options); - /// Append EPs that have been registered previously with the OrtEnv. - /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 - SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, - const std::unordered_map& ep_options); - - /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicy - SessionOptionsImpl& SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy); - - /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicyDelegate - SessionOptionsImpl& SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state = nullptr); - - SessionOptionsImpl& SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomCreateThreadFn - SessionOptionsImpl& SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options); ///< Wraps OrtApi::SessionOptionsSetCustomThreadCreationOptions - SessionOptionsImpl& SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomJoinThreadFn - - ///< Registers the custom operator from the specified shared library via OrtApi::RegisterCustomOpsLibrary_V2. - ///< The custom operator configurations are optional. If provided, custom operator configs are set via - ///< OrtApi::AddSessionConfigEntry. - SessionOptionsImpl& RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, const CustomOpConfigs& custom_op_configs = {}); - - SessionOptionsImpl& RegisterCustomOpsUsingFunction(const char* function_name); ///< Wraps OrtApi::RegisterCustomOpsUsingFunction - - ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_VitisAI - SessionOptionsImpl& AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options = {}); -}; -} // namespace detail - -using UnownedSessionOptions = detail::SessionOptionsImpl>; -using ConstSessionOptions = detail::ConstSessionOptionsImpl>; - -/** \brief Wrapper around ::OrtSessionOptions - * - */ -struct SessionOptions : detail::SessionOptionsImpl { - explicit SessionOptions(std::nullptr_t) {} ///< Create an empty SessionOptions object, must be assigned a valid one to be used - SessionOptions(); ///< Wraps OrtApi::CreateSessionOptions - explicit SessionOptions(OrtSessionOptions* p) : SessionOptionsImpl{p} {} ///< Used for interop with the C API - UnownedSessionOptions GetUnowned() const { return UnownedSessionOptions{this->p_}; } - ConstSessionOptions GetConst() const { return ConstSessionOptions{this->p_}; } -}; - -/** \brief Options object used when compiling a model. - * - * Wraps ::OrtModelCompilationOptions object and methods - */ -struct ModelCompilationOptions : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit ModelCompilationOptions(std::nullptr_t) {} ///< Create an empty ModelCompilationOptions object, must be assigned a valid one to be used. - - ModelCompilationOptions(const Env& env, const SessionOptions& session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions - ModelCompilationOptions(const Env& env, ConstSessionOptions session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions - - ModelCompilationOptions& SetInputModelPath(const ORTCHAR_T* input_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelPath - ModelCompilationOptions& SetInputModelFromBuffer(const void* input_model_data, - size_t input_model_data_size); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelFromBuffer - ModelCompilationOptions& SetEpContextEmbedMode(bool embed_ep_context_in_model); ///< Wraps OrtApi::ModelCompilationOptions_SetEpContextEmbedMode - ModelCompilationOptions& SetOutputModelPath(const ORTCHAR_T* output_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelPath - ModelCompilationOptions& SetOutputModelExternalInitializersFile(const ORTCHAR_T* file_path, - size_t initializer_size_threshold); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelExternalInitializersFile - ModelCompilationOptions& SetOutputModelBuffer(OrtAllocator* allocator, void** output_model_buffer_ptr, - size_t* output_model_buffer_size_ptr); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelBuffer -}; - -/** \brief Compiles an input model to generate a model with EPContext nodes that execute EP-specific kernels. Wraps OrtApi::CompileModels. - * - * \param env: ORT environment object. - * \param model_compilation_options: Compilation options for a model. - * \return A Status indicating success or failure. - */ -Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options); - -/** \brief Wrapper around ::OrtModelMetadata - * - */ -struct ModelMetadata : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit ModelMetadata(std::nullptr_t) {} ///< Create an empty ModelMetadata object, must be assigned a valid one to be used - - /** \brief Returns a copy of the producer name. - * - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetProducerNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetProducerName - - /** \brief Returns a copy of the graph name. - * - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetGraphNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphName - - /** \brief Returns a copy of the domain name. - * - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetDomainAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDomain - - /** \brief Returns a copy of the description. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDescription - - /** \brief Returns a copy of the graph description. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetGraphDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphDescription - - /** \brief Returns a vector of copies of the custom metadata keys. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance std::vector of smart pointers that would deallocate the buffers when out of scope. - * The OrtAllocator instance must be valid at the point of memory release. - */ - std::vector GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetCustomMetadataMapKeys - - /** \brief Looks up a value by a key in the Custom Metadata map - * - * \param key zero terminated string key to lookup - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * maybe nullptr if key is not found. - * - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataLookupCustomMetadataMap - - int64_t GetVersion() const; ///< Wraps OrtApi::ModelMetadataGetVersion -}; - -struct IoBinding; - -namespace detail { - -// we separate const-only methods because passing const ptr to non-const methods -// is only discovered when inline methods are compiled which is counter-intuitive -template -struct ConstSessionImpl : Base { - using B = Base; - using B::B; - - size_t GetInputCount() const; ///< Returns the number of model inputs - size_t GetOutputCount() const; ///< Returns the number of model outputs - size_t GetOverridableInitializerCount() const; ///< Returns the number of inputs that have defaults that can be overridden - - std::vector GetInputNames() const; - std::vector GetOutputNames() const; - std::vector GetOverridableInitializerNames() const; - - /** \brief Returns a copy of input name at the specified index. - * - * \param index must less than the value returned by GetInputCount() - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetInputNameAllocated(size_t index, OrtAllocator* allocator) const; - - /** \brief Returns a copy of output name at then specified index. - * - * \param index must less than the value returned by GetOutputCount() - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const; - - /** \brief Returns a copy of the overridable initializer name at then specified index. - * - * \param index must less than the value returned by GetOverridableInitializerCount() - * \param allocator to allocate memory for the copy of the name returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const; ///< Wraps OrtApi::SessionGetOverridableInitializerName - - uint64_t GetProfilingStartTimeNs() const; ///< Wraps OrtApi::SessionGetProfilingStartTimeNs - ModelMetadata GetModelMetadata() const; ///< Wraps OrtApi::SessionGetModelMetadata - - TypeInfo GetInputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetInputTypeInfo - TypeInfo GetOutputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOutputTypeInfo - TypeInfo GetOverridableInitializerTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOverridableInitializerTypeInfo - - int GetOpset(const std::string& domain) const; ///< Wraps OrtApi::SessionGetOpsetForDomain - - // Will move before checkin if that's the case. - std::vector GetInputs() const; - std::vector GetOutputs() const; -}; - -template -struct SessionImpl : ConstSessionImpl { - using B = ConstSessionImpl; - using B::B; - - /** \brief Run the model returning results in an Ort allocated vector. - * - * Wraps OrtApi::Run - * - * The caller provides a list of inputs and a list of the desired outputs to return. - * - * See the output logs for more information on warnings/errors that occur while processing the model. - * Common errors are.. (TODO) - * - * \param[in] run_options - * \param[in] input_names Array of null terminated strings of length input_count that is the list of input names - * \param[in] input_values Array of Value objects of length input_count that is the list of input values - * \param[in] input_count Number of inputs (the size of the input_names & input_values arrays) - * \param[in] output_names Array of C style strings of length output_count that is the list of output names - * \param[in] output_count Number of outputs (the size of the output_names array) - * \return A std::vector of Value objects that directly maps to the output_names array (eg. output_name[0] is the first entry of the returned vector) - */ - std::vector Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, size_t output_count); - - /** \brief Run the model returning results in user provided outputs - * Same as Run(const RunOptions&, const char* const*, const Value*, size_t,const char* const*, size_t) - */ - void Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count); - - void Run(const RunOptions& run_options, const IoBinding&); ///< Wraps OrtApi::RunWithBinding - - /** \brief Run the model asynchronously in a thread owned by intra op thread pool - * - * Wraps OrtApi::RunAsync - * - * \param[in] run_options - * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names - * \param[in] input_values Array of Value objects of length input_count - * \param[in] input_count Number of elements in the input_names and inputs arrays - * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names - * \param[out] output_values Array of provided Values to be filled with outputs. - * On calling RunAsync, output_values[i] could either be initialized by a null pointer or a preallocated OrtValue*. - * Later, on invoking the callback, each output_values[i] of null will be filled with an OrtValue* allocated by onnxruntime. - * Then, an OrtValue** pointer will be casted from output_values, and pass to the callback. - * NOTE: it is customer's duty to finally release output_values and each of its member, - * regardless of whether the member (Ort::Value) is allocated by onnxruntime or preallocated by the customer. - * \param[in] output_count Number of elements in the output_names and outputs array - * \param[in] callback Callback function on model run completion - * \param[in] user_data User data that pass back to the callback - */ - void RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data); - - /** \brief End profiling and return a copy of the profiling file name. - * - * \param allocator to allocate memory for the copy of the string returned - * \return a instance of smart pointer that would deallocate the buffer when out of scope. - * The OrtAllocator instances must be valid at the point of memory release. - */ - AllocatedStringPtr EndProfilingAllocated(OrtAllocator* allocator); ///< Wraps OrtApi::SessionEndProfiling - - /** \brief Set DynamicOptions for EPs (Execution Providers) - * - * Wraps OrtApi::SetEpDynamicOptions - * - * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` - * Look for `kOrtEpDynamicOptions` - * - * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys - * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values - * \param[in] kv_len Number of elements in the keys and values arrays - */ - void SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len); - - void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container = nullptr); -}; - -} // namespace detail - -using ConstSession = detail::ConstSessionImpl>; -using UnownedSession = detail::SessionImpl>; - -/** \brief Wrapper around ::OrtSession - * - */ -struct Session : detail::SessionImpl { - /// Create an empty Session object, must be assigned a valid one to be used. Wraps OrtApi::CreateSession - explicit Session(std::nullptr_t) {} - explicit Session(OrtSession* p) : SessionImpl{p} {} ///< C API Interop - - Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); - - /// Wraps OrtApi::CreateSessionWithPrepackedWeightsContainer - Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container); - - /// Wraps OrtApi::CreateSessionFromArray - Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options); - - /// Wraps OrtApi::CreateSessionFromArrayWithPrepackedWeightsContainer - Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container); - -#if !defined(ORT_MINIMAL_BUILD) - /// Wraps OrtModelEditorApi::CreateSessionFromModel - Session(const Env& env, const Model& model, const SessionOptions& options); - - /// Wraps OrtModelEditorApi::CreateModelEditorSession - static Session CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); - - /// Wraps OrtModelEditorApi::CreateModelEditorSession - static Session CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, - const SessionOptions& options); -#endif // !defined(ORT_MINIMAL_BUILD) - - ConstSession GetConst() const { return ConstSession{this->p_}; } - UnownedSession GetUnowned() const { return UnownedSession{this->p_}; } -}; - -namespace detail { -template -struct MemoryInfoImpl : Base { - using B = Base; - using B::B; - - std::string GetAllocatorName() const; - OrtAllocatorType GetAllocatorType() const; - int GetDeviceId() const; - OrtMemoryInfoDeviceType GetDeviceType() const; - OrtMemType GetMemoryType() const; - - template - bool operator==(const MemoryInfoImpl& o) const; -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstMemoryInfo = detail::MemoryInfoImpl>; - -/** \brief Wrapper around ::OrtMemoryInfo - * - */ -struct MemoryInfo : detail::MemoryInfoImpl { - static MemoryInfo CreateCpu(OrtAllocatorType type, OrtMemType mem_type1); - explicit MemoryInfo(std::nullptr_t) {} ///< No instance is created - explicit MemoryInfo(OrtMemoryInfo* p) : MemoryInfoImpl{p} {} ///< Take ownership of a pointer created by C API - MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type); - ConstMemoryInfo GetConst() const { return ConstMemoryInfo{this->p_}; } -}; - -namespace detail { -template -struct TensorTypeAndShapeInfoImpl : Base { - using B = Base; - using B::B; - - ONNXTensorElementDataType GetElementType() const; ///< Wraps OrtApi::GetTensorElementType - size_t GetElementCount() const; ///< Wraps OrtApi::GetTensorShapeElementCount - - size_t GetDimensionsCount() const; ///< Wraps OrtApi::GetDimensionsCount - - /** \deprecated use GetShape() returning std::vector - * [[deprecated]] - * This interface is unsafe to use - */ - [[deprecated("use GetShape()")]] void GetDimensions(int64_t* values, size_t values_count) const; ///< Wraps OrtApi::GetDimensions - - void GetSymbolicDimensions(const char** values, size_t values_count) const; ///< Wraps OrtApi::GetSymbolicDimensions - std::vector GetSymbolicDimensions() const; - - std::vector GetShape() const; ///< Uses GetDimensionsCount & GetDimensions to return a std::vector of the shape -}; - -} // namespace detail - -using ConstTensorTypeAndShapeInfo = detail::TensorTypeAndShapeInfoImpl>; - -/** \brief Wrapper around ::OrtTensorTypeAndShapeInfo - * - */ -struct TensorTypeAndShapeInfo : detail::TensorTypeAndShapeInfoImpl { - using Base = detail::TensorTypeAndShapeInfoImpl; - using Base::Base; - - /// Create an empty TensorTypeAndShapeInfo object, must be assigned a valid one to be used - explicit TensorTypeAndShapeInfo(std::nullptr_t) {} - /// Used for interop with the C API - explicit TensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* p) : TensorTypeAndShapeInfoImpl{p} {} - - // Create a TensorTypeAndShapeInfo object with the specified element type and dimensions - // symbolic_dims are optional, but should be 1:1 with dims. - // The value in symbolic_dims will be used for all entries in dims that are -1. - explicit TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, - const std::vector& dims, - const std::vector* symbolic_dims = nullptr); - - ConstTensorTypeAndShapeInfo GetConst() const { return ConstTensorTypeAndShapeInfo{this->p_}; } -}; - -namespace detail { -template -struct SequenceTypeInfoImpl : Base { - using B = Base; - using B::B; - TypeInfo GetSequenceElementType() const; ///< Wraps OrtApi::GetSequenceElementType -}; - -} // namespace detail - -using ConstSequenceTypeInfo = detail::SequenceTypeInfoImpl>; - -/** \brief Wrapper around ::OrtSequenceTypeInfo - * - */ -struct SequenceTypeInfo : detail::SequenceTypeInfoImpl { - using Base = detail::SequenceTypeInfoImpl; - using Base::Base; - - explicit SequenceTypeInfo(std::nullptr_t) {} ///< Create an empty SequenceTypeInfo object, must be assigned a valid one to be used - explicit SequenceTypeInfo(OrtSequenceTypeInfo* p) : SequenceTypeInfoImpl{p} {} ///< Used for interop with the C API - ConstSequenceTypeInfo GetConst() const { return ConstSequenceTypeInfo{this->p_}; } -}; - -namespace detail { -template -struct OptionalTypeInfoImpl : Base { - using B = Base; - using B::B; - TypeInfo GetOptionalElementType() const; ///< Wraps OrtApi::CastOptionalTypeToContainedTypeInfo -}; - -} // namespace detail - -// This is always owned by the TypeInfo and can only be obtained from it. -using ConstOptionalTypeInfo = detail::OptionalTypeInfoImpl>; - -namespace detail { -template -struct MapTypeInfoImpl : detail::Base { - using B = Base; - using B::B; - ONNXTensorElementDataType GetMapKeyType() const; ///< Wraps OrtApi::GetMapKeyType - TypeInfo GetMapValueType() const; ///< Wraps OrtApi::GetMapValueType -}; - -} // namespace detail - -using ConstMapTypeInfo = detail::MapTypeInfoImpl>; - -/** \brief Wrapper around ::OrtMapTypeInfo - * - */ -struct MapTypeInfo : detail::MapTypeInfoImpl { - using Base = detail::MapTypeInfoImpl; - using Base::Base; - - explicit MapTypeInfo(std::nullptr_t) {} ///< Create an empty MapTypeInfo object, must be assigned a valid one to be used - explicit MapTypeInfo(OrtMapTypeInfo* p) : MapTypeInfoImpl{p} {} ///< Used for interop with the C API - ConstMapTypeInfo GetConst() const { return ConstMapTypeInfo{this->p_}; } -}; - -namespace detail { -template -struct TypeInfoImpl : detail::Base { - using B = Base; - using B::B; - - ConstTensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; ///< Wraps OrtApi::CastTypeInfoToTensorInfo - ConstSequenceTypeInfo GetSequenceTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToSequenceTypeInfo - ConstMapTypeInfo GetMapTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToMapTypeInfo - ConstOptionalTypeInfo GetOptionalTypeInfo() const; ///< wraps OrtApi::CastTypeInfoToOptionalTypeInfo - - ONNXType GetONNXType() const; -}; -} // namespace detail - -/// -/// Contains a constant, unowned OrtTypeInfo that can be copied and passed around by value. -/// Provides access to const OrtTypeInfo APIs. -/// -using ConstTypeInfo = detail::TypeInfoImpl>; - -/// -/// Type information that may contain either TensorTypeAndShapeInfo or -/// the information about contained sequence or map depending on the ONNXType. -/// -struct TypeInfo : detail::TypeInfoImpl { - using Base = detail::TypeInfoImpl; - using Base::Base; - - /// Create an empty TypeInfo object, must be assigned a valid one to be used - explicit TypeInfo(std::nullptr_t) {} - explicit TypeInfo(OrtTypeInfo* p) : TypeInfoImpl{p} {} ///< C API Interop - -#if !defined(ORT_MINIMAL_BUILD) - static TypeInfo CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_info); - static TypeInfo CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_info); - static TypeInfo CreateSequenceTypeInfo(ConstTypeInfo sequence_type); - static TypeInfo CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type); - static TypeInfo CreateOptionalTypeInfo(ConstTypeInfo contained_type); -#endif // !defined(ORT_MINIMAL_BUILD) - - ConstTypeInfo GetConst() const { return ConstTypeInfo{this->p_}; } -}; - -namespace detail { -// This structure is used to feed sparse tensor values -// information for use with FillSparseTensor() API -// if the data type for the sparse tensor values is numeric -// use data.p_data, otherwise, use data.str pointer to feed -// values. data.str is an array of const char* that are zero terminated. -// number of strings in the array must match shape size. -// For fully sparse tensors use shape {0} and set p_data/str -// to nullptr. -struct OrtSparseValuesParam { - const int64_t* values_shape; - size_t values_shape_len; - union { - const void* p_data; - const char** str; - } data; -}; - -// Provides a way to pass shape in a single -// argument -struct Shape { - const int64_t* shape; - size_t shape_len; -}; - -template -struct ConstValueImpl : Base { - using B = Base; - using B::B; - - /// - /// Obtains a pointer to a user defined data for experimental purposes - /// - template - void GetOpaqueData(const char* domain, const char* type_name, R&) const; ///< Wraps OrtApi::GetOpaqueValue - - bool IsTensor() const; ///< Returns true if Value is a tensor, false for other types like map/sequence/etc - bool HasValue() const; /// < Return true if OrtValue contains data and returns false if the OrtValue is a None - - size_t GetCount() const; // If a non tensor, returns 2 for map and N for sequence, where N is the number of elements - Value GetValue(int index, OrtAllocator* allocator) const; - - /// - /// This API returns a full length of string data contained within either a tensor or a sparse Tensor. - /// For sparse tensor it returns a full length of stored non-empty strings (values). The API is useful - /// for allocating necessary memory and calling GetStringTensorContent(). - /// - /// total length of UTF-8 encoded bytes contained. No zero terminators counted. - size_t GetStringTensorDataLength() const; - - /// - /// The API copies all of the UTF-8 encoded string data contained within a tensor or a sparse tensor - /// into a supplied buffer. Use GetStringTensorDataLength() to find out the length of the buffer to allocate. - /// The user must also allocate offsets buffer with the number of entries equal to that of the contained - /// strings. - /// - /// Strings are always assumed to be on CPU, no X-device copy. - /// - /// user allocated buffer - /// length in bytes of the allocated buffer - /// a pointer to the offsets user allocated buffer - /// count of offsets, must be equal to the number of strings contained. - /// that can be obtained from the shape of the tensor or from GetSparseTensorValuesTypeAndShapeInfo() - /// for sparse tensors - void GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const; - - /// - /// Returns a const typed pointer to the tensor contained data. - /// No type checking is performed, the caller must ensure the type matches the tensor type. - /// - /// - /// const pointer to data, no copies made - template - const R* GetTensorData() const; ///< Wraps OrtApi::GetTensorMutableData /// - - /// - /// Returns a non-typed pointer to a tensor contained data. - /// - /// const pointer to data, no copies made - const void* GetTensorRawData() const; - - /// - /// The API returns type information for data contained in a tensor. For sparse - /// tensors it returns type information for contained non-zero values. - /// It returns dense shape for sparse tensors. - /// - /// TypeInfo - TypeInfo GetTypeInfo() const; - - /// - /// The API returns type information for data contained in a tensor. For sparse - /// tensors it returns type information for contained non-zero values. - /// It returns dense shape for sparse tensors. - /// - /// TensorTypeAndShapeInfo - TensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; - - /// - /// This API returns information about the memory allocation used to hold data. - /// - /// Non owning instance of MemoryInfo - ConstMemoryInfo GetTensorMemoryInfo() const; - - /// - /// The API copies UTF-8 encoded bytes for the requested string element - /// contained within a tensor or a sparse tensor into a provided buffer. - /// Use GetStringTensorElementLength() to obtain the length of the buffer to allocate. - /// - /// - /// - /// - void GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const; - - /// - /// Returns string tensor UTF-8 encoded string element. - /// Use of this API is recommended over GetStringTensorElement() that takes void* buffer pointer. - /// - /// - /// std::string - std::string GetStringTensorElement(size_t element_index) const; - - /// - /// The API returns a byte length of UTF-8 encoded string element - /// contained in either a tensor or a spare tensor values. - /// - /// - /// byte length for the specified string element - size_t GetStringTensorElementLength(size_t element_index) const; - -#if !defined(DISABLE_SPARSE_TENSORS) - /// - /// The API returns the sparse data format this OrtValue holds in a sparse tensor. - /// If the sparse tensor was not fully constructed, i.e. Use*() or Fill*() API were not used - /// the value returned is ORT_SPARSE_UNDEFINED. - /// - /// Format enum - OrtSparseFormat GetSparseFormat() const; - - /// - /// The API returns type and shape information for stored non-zero values of the - /// sparse tensor. Use GetSparseTensorValues() to obtain values buffer pointer. - /// - /// TensorTypeAndShapeInfo values information - TensorTypeAndShapeInfo GetSparseTensorValuesTypeAndShapeInfo() const; - - /// - /// The API returns type and shape information for the specified indices. Each supported - /// indices have their own enum values even if a give format has more than one kind of indices. - /// Use GetSparseTensorIndicesData() to obtain pointer to indices buffer. - /// - /// enum requested - /// type and shape information - TensorTypeAndShapeInfo GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat format) const; - - /// - /// The API retrieves a pointer to the internal indices buffer. The API merely performs - /// a convenience data type casting on the return type pointer. Make sure you are requesting - /// the right type, use GetSparseTensorIndicesTypeShapeInfo(); - /// - /// type to cast to - /// requested indices kind - /// number of indices entries - /// Pinter to the internal sparse tensor buffer containing indices. Do not free this pointer. - template - const R* GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const; - - /// - /// Returns true if the OrtValue contains a sparse tensor - /// - /// - bool IsSparseTensor() const; - - /// - /// The API returns a pointer to an internal buffer of the sparse tensor - /// containing non-zero values. The API merely does casting. Make sure you - /// are requesting the right data type by calling GetSparseTensorValuesTypeAndShapeInfo() - /// first. - /// - /// numeric data types only. Use GetStringTensor*() to retrieve strings. - /// a pointer to the internal values buffer. Do not free this pointer. - template - const R* GetSparseTensorValues() const; - -#endif -}; - -template -struct ValueImpl : ConstValueImpl { - using B = ConstValueImpl; - using B::B; - - /// - /// Returns a non-const typed pointer to an OrtValue/Tensor contained buffer - /// No type checking is performed, the caller must ensure the type matches the tensor type. - /// - /// non-const pointer to data, no copies made - template - R* GetTensorMutableData(); - - /// - /// Returns a non-typed non-const pointer to a tensor contained data. - /// - /// pointer to data, no copies made - void* GetTensorMutableRawData(); - - /// - // Obtain a reference to an element of data at the location specified - /// by the vector of dims. - /// - /// - /// [in] expressed by a vecotr of dimensions offsets - /// - template - R& At(const std::vector& location); - - /// - /// Set all strings at once in a string tensor - /// - /// [in] An array of strings. Each string in this array must be null terminated. - /// [in] Count of strings in s (Must match the size of \p value's tensor shape) - void FillStringTensor(const char* const* s, size_t s_len); - - /// - /// Set a single string in a string tensor - /// - /// [in] A null terminated UTF-8 encoded string - /// [in] Index of the string in the tensor to set - void FillStringTensorElement(const char* s, size_t index); - - /// - /// Allocate if necessary and obtain a pointer to a UTF-8 - /// encoded string element buffer indexed by the flat element index, - /// of the specified length. - /// - /// This API is for advanced usage. It avoids a need to construct - /// an auxiliary array of string pointers, and allows to write data directly - /// (do not zero terminate). - /// - /// - /// - /// a pointer to a writable buffer - char* GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length); - -#if !defined(DISABLE_SPARSE_TENSORS) - /// - /// Supplies COO format specific indices and marks the contained sparse tensor as being a COO format tensor. - /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user - /// allocated buffers lifespan must eclipse that of the OrtValue. - /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. - /// - /// pointer to the user allocated buffer with indices. Use nullptr for fully sparse tensors. - /// number of indices entries. Use 0 for fully sparse tensors - void UseCooIndices(int64_t* indices_data, size_t indices_num); - - /// - /// Supplies CSR format specific indices and marks the contained sparse tensor as being a CSR format tensor. - /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user - /// allocated buffers lifespan must eclipse that of the OrtValue. - /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. - /// - /// pointer to the user allocated buffer with inner indices or nullptr for fully sparse tensors - /// number of csr inner indices or 0 for fully sparse tensors - /// pointer to the user allocated buffer with outer indices or nullptr for fully sparse tensors - /// number of csr outer indices or 0 for fully sparse tensors - void UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num); - - /// - /// Supplies BlockSparse format specific indices and marks the contained sparse tensor as being a BlockSparse format tensor. - /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user - /// allocated buffers lifespan must eclipse that of the OrtValue. - /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. - /// - /// indices shape or a {0} for fully sparse - /// user allocated buffer with indices or nullptr for fully spare tensors - void UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data); - - /// - /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API - /// and copy the values and COO indices into it. If data_mem_info specifies that the data is located - /// at difference device than the allocator, a X-device copy will be performed if possible. - /// - /// specified buffer memory description - /// values buffer information. - /// coo indices buffer or nullptr for fully sparse data - /// number of COO indices or 0 for fully sparse data - void FillSparseTensorCoo(const OrtMemoryInfo* data_mem_info, const OrtSparseValuesParam& values_param, - const int64_t* indices_data, size_t indices_num); - - /// - /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API - /// and copy the values and CSR indices into it. If data_mem_info specifies that the data is located - /// at difference device than the allocator, a X-device copy will be performed if possible. - /// - /// specified buffer memory description - /// values buffer information - /// csr inner indices pointer or nullptr for fully sparse tensors - /// number of csr inner indices or 0 for fully sparse tensors - /// pointer to csr indices data or nullptr for fully sparse tensors - /// number of csr outer indices or 0 - void FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const int64_t* inner_indices_data, size_t inner_indices_num, - const int64_t* outer_indices_data, size_t outer_indices_num); - - /// - /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API - /// and copy the values and BlockSparse indices into it. If data_mem_info specifies that the data is located - /// at difference device than the allocator, a X-device copy will be performed if possible. - /// - /// specified buffer memory description - /// values buffer information - /// indices shape. use {0} for fully sparse tensors - /// pointer to indices data or nullptr for fully sparse tensors - void FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const Shape& indices_shape, - const int32_t* indices_data); - -#endif -}; - -} // namespace detail - -using ConstValue = detail::ConstValueImpl>; -using UnownedValue = detail::ValueImpl>; - -/** \brief Wrapper around ::OrtValue - * - */ -struct Value : detail::ValueImpl { - using Base = detail::ValueImpl; - using Base::Base; - using OrtSparseValuesParam = detail::OrtSparseValuesParam; - using Shape = detail::Shape; - - explicit Value(std::nullptr_t) {} ///< Create an empty Value object, must be assigned a valid one to be used - Value(Value&&) = default; - Value& operator=(Value&&) = default; - - ConstValue GetConst() const { return ConstValue{this->p_}; } - UnownedValue GetUnowned() const { return UnownedValue{this->p_}; } - - /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. - * \tparam T The numeric datatype. This API is not suitable for strings. - * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). - * \param p_data Pointer to the data buffer. - * \param p_data_element_count The number of elements in the data buffer. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - */ - template - static Value CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, - const int64_t* shape, size_t shape_len); - - /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. - * - * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). - * \param p_data Pointer to the data buffer. - * \param p_data_byte_count The number of bytes in the data buffer. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - * \param type The data type. - */ - static Value CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type); - - /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAndDeleterAsOrtValue. - * - * \param deleter OrtAllocator that will be used to free the buffer when no longer required. - * \param p_data Pointer to the data buffer. - * \param p_data_byte_count The number of bytes in the data buffer. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - * \param type The data type. - */ - static Value CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type); - - /** \brief Creates an OrtValue with a tensor using a supplied OrtAllocator. Wraps OrtApi::CreateTensorAsOrtValue. - * This overload will allocate the buffer for the tensor according to the supplied shape and data type. - * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. - * The input data would need to be copied into the allocated buffer. - * This API is not suitable for strings. - * - * \tparam T The numeric datatype. This API is not suitable for strings. - * \param allocator The allocator to use. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - */ - template - static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len); - - /** \brief Creates an OrtValue with a tensor using the supplied OrtAllocator. - * Wraps OrtApi::CreateTensorAsOrtValue. - * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. - * The input data would need to be copied into the allocated buffer. - * This API is not suitable for strings. - * - * \param allocator The allocator to use. - * \param shape Pointer to the tensor shape dimensions. - * \param shape_len The number of tensor shape dimensions. - * \param type The data type. - */ - static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type); - - /** \brief Creates an OrtValue with a Map Onnx type representation. - * The API would ref-count the supplied OrtValues and they will be released - * when the returned OrtValue is released. The caller may release keys and values after the call - * returns. - * - * \param keys an OrtValue containing a tensor with primitive data type keys. - * \param values an OrtValue that may contain a tensor. Ort currently supports only primitive data type values. - */ - static Value CreateMap(const Value& keys, const Value& values); ///< Wraps OrtApi::CreateValue - - /** \brief Creates an OrtValue with a Sequence Onnx type representation. - * The API would ref-count the supplied OrtValues and they will be released - * when the returned OrtValue is released. The caller may release the values after the call - * returns. - * - * \param values a vector of OrtValues that must have the same Onnx value type. - */ - static Value CreateSequence(const std::vector& values); ///< Wraps OrtApi::CreateValue - - /** \brief Creates an OrtValue wrapping an Opaque type. - * This is used for experimental support of non-tensor types. - * - * \tparam T - the type of the value. - * \param domain - zero terminated utf-8 string. Domain of the type. - * \param type_name - zero terminated utf-8 string. Name of the type. - * \param value - the value to be wrapped. - */ - template - static Value CreateOpaque(const char* domain, const char* type_name, const T& value); ///< Wraps OrtApi::CreateOpaqueValue - -#if !defined(DISABLE_SPARSE_TENSORS) - /// - /// This is a simple forwarding method to the other overload that helps deducing - /// data type enum value from the type of the buffer. - /// - /// numeric datatype. This API is not suitable for strings. - /// Memory description where the user buffers reside (CPU vs GPU etc) - /// pointer to the user supplied buffer, use nullptr for fully sparse tensors - /// a would be dense shape of the tensor - /// non zero values shape. Use a single 0 shape for fully sparse tensors. - /// - template - static Value CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, - const Shape& values_shape); - - /// - /// Creates an OrtValue instance containing SparseTensor. This constructs - /// a sparse tensor that makes use of user allocated buffers. It does not make copies - /// of the user provided data and does not modify it. The lifespan of user provided buffers should - /// eclipse the life span of the resulting OrtValue. This call constructs an instance that only contain - /// a pointer to non-zero values. To fully populate the sparse tensor call UseIndices() API below - /// to supply a sparse format specific indices. - /// This API is not suitable for string data. Use CreateSparseTensor() with allocator specified so strings - /// can be properly copied into the allocated buffer. - /// - /// Memory description where the user buffers reside (CPU vs GPU etc) - /// pointer to the user supplied buffer, use nullptr for fully sparse tensors - /// a would be dense shape of the tensor - /// non zero values shape. Use a single 0 shape for fully sparse tensors. - /// data type - /// Ort::Value instance containing SparseTensor - static Value CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, - const Shape& values_shape, ONNXTensorElementDataType type); - - /// - /// This is a simple forwarding method to the below CreateSparseTensor. - /// This helps to specify data type enum in terms of C++ data type. - /// Use CreateSparseTensor - /// - /// numeric data type only. String data enum must be specified explicitly. - /// allocator to use - /// a would be dense shape of the tensor - /// Ort::Value - template - static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape); - - /// - /// Creates an instance of OrtValue containing sparse tensor. The created instance has no data. - /// The data must be supplied by on of the FillSparseTensor() methods that take both non-zero values - /// and indices. The data will be copied into a buffer that would be allocated using the supplied allocator. - /// Use this API to create OrtValues that contain sparse tensors with all supported data types including - /// strings. - /// - /// allocator to use. The allocator lifespan must eclipse that of the resulting OrtValue - /// a would be dense shape of the tensor - /// data type - /// an instance of Ort::Value - static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, ONNXTensorElementDataType type); - -#endif // !defined(DISABLE_SPARSE_TENSORS) -}; - -/// -/// Represents native memory allocation coming from one of the -/// OrtAllocators registered with OnnxRuntime. -/// Use it to wrap an allocation made by an allocator -/// so it can be automatically released when no longer needed. -/// -struct MemoryAllocation { - MemoryAllocation(OrtAllocator* allocator, void* p, size_t size); - ~MemoryAllocation(); - MemoryAllocation(const MemoryAllocation&) = delete; - MemoryAllocation& operator=(const MemoryAllocation&) = delete; - MemoryAllocation(MemoryAllocation&&) noexcept; - MemoryAllocation& operator=(MemoryAllocation&&) noexcept; - - void* get() { return p_; } - size_t size() const { return size_; } - - private: - OrtAllocator* allocator_; - void* p_; - size_t size_; -}; - -namespace detail { -template -struct AllocatorImpl : Base { - using B = Base; - using B::B; - - void* Alloc(size_t size); - MemoryAllocation GetAllocation(size_t size); - void Free(void* p); - ConstMemoryInfo GetInfo() const; -}; - -} // namespace detail - -/** \brief Wrapper around ::OrtAllocator default instance that is owned by Onnxruntime - * - */ -struct AllocatorWithDefaultOptions : detail::AllocatorImpl> { - explicit AllocatorWithDefaultOptions(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance - AllocatorWithDefaultOptions(); -}; - -/** \brief Wrapper around ::OrtAllocator - * - */ -struct Allocator : detail::AllocatorImpl { - explicit Allocator(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance - Allocator(const Session& session, const OrtMemoryInfo*); -}; - -using UnownedAllocator = detail::AllocatorImpl>; - -namespace detail { -namespace binding_utils { -// Bring these out of template -std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator*); -std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator*); -} // namespace binding_utils - -template -struct ConstIoBindingImpl : Base { - using B = Base; - using B::B; - - std::vector GetOutputNames() const; - std::vector GetOutputNames(OrtAllocator*) const; - std::vector GetOutputValues() const; - std::vector GetOutputValues(OrtAllocator*) const; -}; - -template -struct IoBindingImpl : ConstIoBindingImpl { - using B = ConstIoBindingImpl; - using B::B; - - void BindInput(const char* name, const Value&); - void BindOutput(const char* name, const Value&); - void BindOutput(const char* name, const OrtMemoryInfo*); - void ClearBoundInputs(); - void ClearBoundOutputs(); - void SynchronizeInputs(); - void SynchronizeOutputs(); -}; - -} // namespace detail - -using ConstIoBinding = detail::ConstIoBindingImpl>; -using UnownedIoBinding = detail::IoBindingImpl>; - -/** \brief Wrapper around ::OrtIoBinding - * - */ -struct IoBinding : detail::IoBindingImpl { - explicit IoBinding(std::nullptr_t) {} ///< Create an empty object for convenience. Sometimes, we want to initialize members later. - explicit IoBinding(Session& session); - ConstIoBinding GetConst() const { return ConstIoBinding{this->p_}; } - UnownedIoBinding GetUnowned() const { return UnownedIoBinding{this->p_}; } -}; - -/*! \struct Ort::ArenaCfg - * \brief it is a structure that represents the configuration of an arena based allocator - * \details Please see docs/C_API.md for details - */ -struct ArenaCfg : detail::Base { - explicit ArenaCfg(std::nullptr_t) {} ///< Create an empty ArenaCfg object, must be assigned a valid one to be used - /** - * Wraps OrtApi::CreateArenaCfg - * \param max_mem - use 0 to allow ORT to choose the default - * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested - * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default - * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default - * See docs/C_API.md for details on what the following parameters mean and how to choose these values - */ - ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk); -}; - -// -// Custom OPs (only needed to implement custom OPs) -// - -/// -/// This struct provides life time management for custom op attribute -/// -struct OpAttr : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit OpAttr(std::nullptr_t) {} - OpAttr(const char* name, const void* data, int len, OrtOpAttrType type); -}; - -/** - * Macro that logs a message using the provided logger. Throws an exception if OrtApi::Logger_LogMessage fails. - * Example: ORT_CXX_LOG(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param message A null-terminated UTF-8 message to log. - */ -#define ORT_CXX_LOG(logger, message_severity, message) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - Ort::ThrowOnError(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), message)); \ - } \ - } while (false) - -/** - * Macro that logs a message using the provided logger. Can be used in noexcept code since errors are silently ignored. - * Example: ORT_CXX_LOG_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param message A null-terminated UTF-8 message to log. - */ -#define ORT_CXX_LOG_NOEXCEPT(logger, message_severity, message) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - static_cast(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), message)); \ - } \ - } while (false) - -/** - * Macro that logs a printf-like formatted message using the provided logger. Throws an exception if - * OrtApi::Logger_LogMessage fails or if a formatting error occurs. - * Example: ORT_CXX_LOGF(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. - * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. - * \param ... Zero or more variadic arguments referenced by the format string. - */ -#define ORT_CXX_LOGF(logger, message_severity, /*format,*/...) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - Ort::ThrowOnError(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), __VA_ARGS__)); \ - } \ - } while (false) - -/** - * Macro that logs a printf-like formatted message using the provided logger. Can be used in noexcept code since errors - * are silently ignored. - * Example: ORT_CXX_LOGF_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); - * - * \param logger The Ort::Logger instance to use. Must be a value or reference. - * \param message_severity The logging severity level of the message. - * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. - * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. - * \param ... Zero or more variadic arguments referenced by the format string. - */ -#define ORT_CXX_LOGF_NOEXCEPT(logger, message_severity, /*format,*/...) \ - do { \ - if (message_severity >= logger.GetLoggingSeverityLevel()) { \ - static_cast(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ - static_cast(__FUNCTION__), __VA_ARGS__)); \ - } \ - } while (false) - -/// -/// This class represents an ONNX Runtime logger that can be used to log information with an -/// associated severity level and source code location (file path, line number, function name). -/// -/// A Logger can be obtained from within custom operators by calling Ort::KernelInfo::GetLogger(). -/// Instances of Ort::Logger are the size of two pointers and can be passed by value. -/// -/// Use the ORT_CXX_LOG macros to ensure the source code location is set properly from the callsite -/// and to take advantage of a cached logging severity level that can bypass calls to the underlying C API. -/// -struct Logger { - /** - * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. - */ - Logger() = default; - - /** - * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. - */ - explicit Logger(std::nullptr_t) {} - - /** - * Creates a logger from an ::OrtLogger instance. Caches the logger's current severity level by calling - * OrtApi::Logger_GetLoggingSeverityLevel. Throws an exception if OrtApi::Logger_GetLoggingSeverityLevel fails. - * - * \param logger The ::OrtLogger to wrap. - */ - explicit Logger(const OrtLogger* logger); - - ~Logger() = default; - - Logger(const Logger&) = default; - Logger& operator=(const Logger&) = default; - - Logger(Logger&& v) noexcept = default; - Logger& operator=(Logger&& v) noexcept = default; - - /** - * Returns the logger's current severity level from the cached member. - * - * \return The current ::OrtLoggingLevel. - */ - OrtLoggingLevel GetLoggingSeverityLevel() const noexcept; - - /** - * Logs the provided message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOG or ORT_CXX_LOG_NOEXCEPT - * macros to properly set the source code location and to use the cached severity level to potentially bypass - * calls to the underlying C API. - * - * \param log_severity_level The message's logging severity level. - * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. - * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. - * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. - * \param message The message to log. - * \return A Ort::Status value to indicate error or success. - */ - Status LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, - const char* func_name, const char* message) const noexcept; - - /** - * Logs a printf-like formatted message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOGF or ORT_CXX_LOGF_NOEXCEPT - * macros to properly set the source code location and to use the cached severity level to potentially bypass - * calls to the underlying C API. Returns an error status if a formatting error occurs. - * - * \param log_severity_level The message's logging severity level. - * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. - * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. - * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. - * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. - * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. - * \param args Zero or more variadic arguments referenced by the format string. - * \return A Ort::Status value to indicate error or success. - */ - template - Status LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, - const char* func_name, const char* format, Args&&... args) const noexcept; - - private: - const OrtLogger* logger_{}; - OrtLoggingLevel cached_severity_level_{}; -}; - -/// -/// This class wraps a raw pointer OrtKernelContext* that is being passed -/// to the custom kernel Compute() method. Use it to safely access context -/// attributes, input and output parameters with exception safety guarantees. -/// See usage example in onnxruntime/test/testdata/custom_op_library/custom_op_library.cc -/// -struct KernelContext { - explicit KernelContext(OrtKernelContext* context); - size_t GetInputCount() const; - size_t GetOutputCount() const; - // If input is optional and is not present, the method returns an empty ConstValue - // which can be compared to nullptr. - ConstValue GetInput(size_t index) const; - // If output is optional and is not present, the method returns an empty UnownedValue - // which can be compared to nullptr. - UnownedValue GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const; - UnownedValue GetOutput(size_t index, const std::vector& dims) const; - void* GetGPUComputeStream() const; - Logger GetLogger() const; - OrtAllocator* GetAllocator(const OrtMemoryInfo& memory_info) const; - OrtKernelContext* GetOrtKernelContext() const { return ctx_; } - void ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const; - - private: - OrtKernelContext* ctx_; -}; - -struct KernelInfo; - -namespace detail { -namespace attr_utils { -void GetAttr(const OrtKernelInfo* p, const char* name, float&); -void GetAttr(const OrtKernelInfo* p, const char* name, int64_t&); -void GetAttr(const OrtKernelInfo* p, const char* name, std::string&); -void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); -void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); -} // namespace attr_utils - -template -struct KernelInfoImpl : Base { - using B = Base; - using B::B; - - KernelInfo Copy() const; - - template // R is only implemented for float, int64_t, and string - R GetAttribute(const char* name) const { - R val; - attr_utils::GetAttr(this->p_, name, val); - return val; - } - - template // R is only implemented for std::vector, std::vector - std::vector GetAttributes(const char* name) const { - std::vector result; - attr_utils::GetAttrs(this->p_, name, result); - return result; - } - - Value GetTensorAttribute(const char* name, OrtAllocator* allocator) const; - - size_t GetInputCount() const; - size_t GetOutputCount() const; - - std::string GetInputName(size_t index) const; - std::string GetOutputName(size_t index) const; - - TypeInfo GetInputTypeInfo(size_t index) const; - TypeInfo GetOutputTypeInfo(size_t index) const; - - ConstValue GetTensorConstantInput(size_t index, int* is_constant) const; - - std::string GetNodeName() const; - Logger GetLogger() const; -}; - -} // namespace detail - -using ConstKernelInfo = detail::KernelInfoImpl>; - -/// -/// This struct owns the OrtKernInfo* pointer when a copy is made. -/// For convenient wrapping of OrtKernelInfo* passed to kernel constructor -/// and query attributes, warp the pointer with Ort::Unowned instance -/// so it does not destroy the pointer the kernel does not own. -/// -struct KernelInfo : detail::KernelInfoImpl { - using Base = detail::KernelInfoImpl; - using Base::Base; - explicit KernelInfo(std::nullptr_t) {} ///< Create an empty instance to initialize later - explicit KernelInfo(OrtKernelInfo* info); ///< Take ownership of the instance - ConstKernelInfo GetConst() const { return ConstKernelInfo{this->p_}; } -}; - -/// -/// Create and own custom defined operation. -/// -struct Op : detail::Base { - using Base = detail::Base; - using Base::Base; - - explicit Op(std::nullptr_t) {} ///< Create an empty Operator object, must be assigned a valid one to be used - - explicit Op(OrtOp*); ///< Take ownership of the OrtOp - - static Op Create(const OrtKernelInfo* info, const char* op_name, const char* domain, - int version, const char** type_constraint_names, - const ONNXTensorElementDataType* type_constraint_values, - size_t type_constraint_count, - const OpAttr* attr_values, - size_t attr_count, - size_t input_count, size_t output_count); - - void Invoke(const OrtKernelContext* context, - const Value* input_values, - size_t input_count, - Value* output_values, - size_t output_count); - - // For easier refactoring - void Invoke(const OrtKernelContext* context, - const OrtValue* const* input_values, - size_t input_count, - OrtValue* const* output_values, - size_t output_count); -}; - -/// -/// Provide access to per-node attributes and input shapes, so one could compute and set output shapes. -/// -struct ShapeInferContext { - struct SymbolicInteger { - SymbolicInteger(int64_t i) : i_(i), is_int_(true) {}; - SymbolicInteger(const char* s) : s_(s), is_int_(false) {}; - SymbolicInteger(const SymbolicInteger&) = default; - SymbolicInteger(SymbolicInteger&&) = default; - - SymbolicInteger& operator=(const SymbolicInteger&) = default; - SymbolicInteger& operator=(SymbolicInteger&&) = default; - - bool operator==(const SymbolicInteger& dim) const { - if (is_int_ == dim.is_int_) { - if (is_int_) { - return i_ == dim.i_; - } else { - return std::string{s_} == std::string{dim.s_}; - } - } - return false; - } - - bool IsInt() const { return is_int_; } - int64_t AsInt() const { return i_; } - const char* AsSym() const { return s_; } - - static constexpr int INVALID_INT_DIM = -2; - - private: - union { - int64_t i_; - const char* s_; - }; - bool is_int_; - }; - - using Shape = std::vector; - - ShapeInferContext(const OrtApi* ort_api, OrtShapeInferContext* ctx); - - const Shape& GetInputShape(size_t indice) const { return input_shapes_.at(indice); } - - size_t GetInputCount() const { return input_shapes_.size(); } - - Status SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); - - int64_t GetAttrInt(const char* attr_name); - - using Ints = std::vector; - Ints GetAttrInts(const char* attr_name); - - float GetAttrFloat(const char* attr_name); - - using Floats = std::vector; - Floats GetAttrFloats(const char* attr_name); - - std::string GetAttrString(const char* attr_name); - - using Strings = std::vector; - Strings GetAttrStrings(const char* attr_name); - - private: - const OrtOpAttr* GetAttrHdl(const char* attr_name) const; - const OrtApi* ort_api_; - OrtShapeInferContext* ctx_; - std::vector input_shapes_; -}; - -using ShapeInferFn = Ort::Status (*)(Ort::ShapeInferContext&); - -#define MAX_CUSTOM_OP_END_VER (1UL << 31) - 1 - -template -struct CustomOpBase : OrtCustomOp { - CustomOpBase() { - OrtCustomOp::version = ORT_API_VERSION; - OrtCustomOp::GetName = [](const OrtCustomOp* this_) { return static_cast(this_)->GetName(); }; - - OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* this_) { return static_cast(this_)->GetExecutionProviderType(); }; - - OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetInputTypeCount(); }; - OrtCustomOp::GetInputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputType(index); }; - OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputMemoryType(index); }; - - OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetOutputTypeCount(); }; - OrtCustomOp::GetOutputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputType(index); }; - -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(push) -#pragma warning(disable : 26409) -#endif - OrtCustomOp::KernelDestroy = [](void* op_kernel) { delete static_cast(op_kernel); }; -#if defined(_MSC_VER) && !defined(__clang__) -#pragma warning(pop) -#endif - OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputCharacteristic(index); }; - OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputCharacteristic(index); }; - - OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicInputMinArity(); }; - OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicInputHomogeneity()); }; - OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicOutputMinArity(); }; - OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicOutputHomogeneity()); }; -#ifdef __cpp_if_constexpr - if constexpr (WithStatus) { -#else - if (WithStatus) { -#endif - OrtCustomOp::CreateKernelV2 = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info, void** op_kernel) -> OrtStatusPtr { - return static_cast(this_)->CreateKernelV2(*api, info, op_kernel); - }; - OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { - return static_cast(op_kernel)->ComputeV2(context); - }; - } else { - OrtCustomOp::CreateKernelV2 = nullptr; - OrtCustomOp::KernelComputeV2 = nullptr; - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info) { return static_cast(this_)->CreateKernel(*api, info); }; - OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { - static_cast(op_kernel)->Compute(context); - }; - } - - SetShapeInferFn(0); - - OrtCustomOp::GetStartVersion = [](const OrtCustomOp* this_) { - return static_cast(this_)->start_ver_; - }; - - OrtCustomOp::GetEndVersion = [](const OrtCustomOp* this_) { - return static_cast(this_)->end_ver_; - }; - - OrtCustomOp::GetMayInplace = nullptr; - OrtCustomOp::ReleaseMayInplace = nullptr; - OrtCustomOp::GetAliasMap = nullptr; - OrtCustomOp::ReleaseAliasMap = nullptr; - } - - // Default implementation of GetExecutionProviderType that returns nullptr to default to the CPU provider - const char* GetExecutionProviderType() const { return nullptr; } - - // Default implementations of GetInputCharacteristic() and GetOutputCharacteristic() below - // (inputs and outputs are required by default) - OrtCustomOpInputOutputCharacteristic GetInputCharacteristic(size_t /*index*/) const { - return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; - } - - OrtCustomOpInputOutputCharacteristic GetOutputCharacteristic(size_t /*index*/) const { - return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; - } - - // Default implemention of GetInputMemoryType() that returns OrtMemTypeDefault - OrtMemType GetInputMemoryType(size_t /*index*/) const { - return OrtMemTypeDefault; - } - - // Default implementation of GetVariadicInputMinArity() returns 1 to specify that a variadic input - // should expect at least 1 argument. - int GetVariadicInputMinArity() const { - return 1; - } - - // Default implementation of GetVariadicInputHomegeneity() returns true to specify that all arguments - // to a variadic input should be of the same type. - bool GetVariadicInputHomogeneity() const { - return true; - } - - // Default implementation of GetVariadicOutputMinArity() returns 1 to specify that a variadic output - // should produce at least 1 output value. - int GetVariadicOutputMinArity() const { - return 1; - } - - // Default implementation of GetVariadicOutputHomegeneity() returns true to specify that all output values - // produced by a variadic output should be of the same type. - bool GetVariadicOutputHomogeneity() const { - return true; - } - - // Declare list of session config entries used by this Custom Op. - // Implement this function in order to get configs from CustomOpBase::GetSessionConfigs(). - // This default implementation returns an empty vector of config entries. - std::vector GetSessionConfigKeys() const { - return std::vector{}; - } - - // Ort::CustomOpBase derived class should provide the following static method with the type/shape inferencing - // implementation if needed: - // static OrtStatusPtr InferOutputShape(Ort::ShapeInferContext& context) - template - decltype(&C::InferOutputShape) SetShapeInferFn(decltype(&C::InferOutputShape)) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - ShapeInferContext ctx(&GetApi(), ort_ctx); - return C::InferOutputShape(ctx); - }; - return {}; - } - - template - void SetShapeInferFn(...) { - OrtCustomOp::InferOutputShapeFn = {}; - } - - protected: - // Helper function that returns a map of session config entries specified by CustomOpBase::GetSessionConfigKeys. - void GetSessionConfigs(std::unordered_map& out, ConstSessionOptions options) const; - - int start_ver_ = 1; - int end_ver_ = MAX_CUSTOM_OP_END_VER; -}; - -namespace detail { -template -struct ValueInfoImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - - std::string Name() const; - ConstTypeInfo TypeInfo() const; -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstValueInfo = detail::ValueInfoImpl>; - -/** \brief Wrapper around ::OrtValueInfo - * - */ -struct ValueInfo : detail::ValueInfoImpl { - explicit ValueInfo(std::nullptr_t) {} ///< No instance is created - /// Take ownership of a pointer created by C API - explicit ValueInfo(OrtValueInfo* p) : ValueInfoImpl{p} {} - - // Create ValueInfo for a tensor - explicit ValueInfo(const std::string& name, const ConstTypeInfo& type_info); - - ConstValueInfo GetConst() const { return ConstValueInfo{this->p_}; } -}; - -namespace detail { -template -struct NodeImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; -}; -} // namespace detail - -/** \brief Wrapper around ::OrtNode - * - */ -struct Node : detail::NodeImpl { - explicit Node(std::nullptr_t) {} ///< No instance is created - explicit Node(OrtNode* p) : NodeImpl{p} {} ///< Take ownership of a pointer created by C API - -#if !defined(ORT_MINIMAL_BUILD) - Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names); - - /// - /// Wraps CreateNode. Node takes ownership of attributes on success and updates the OpAttr in `attributes` to do so. - /// - Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes); - - private: - static void Init(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes, - OrtNode*& node); -#endif // !defined(ORT_MINIMAL_BUILD) -}; - -namespace detail { -template -struct GraphImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - -#if !defined(ORT_MINIMAL_BUILD) - void SetInputs(std::vector& inputs); - void SetOutputs(std::vector& outputs); - void AddInitializer(const std::string& name, Value& initializer, bool data_is_external); // Graph takes ownership of Value - void AddNode(Node& node); // Graph takes ownership of Node -#endif // !defined(ORT_MINIMAL_BUILD) -}; -} // namespace detail - -/** \brief Wrapper around ::OrtGraph - * - */ -struct Graph : detail::GraphImpl { - explicit Graph(std::nullptr_t) {} ///< No instance is created - explicit Graph(OrtGraph* p) : GraphImpl{p} {} ///< Take ownership of a pointer created by C API -#if !defined(ORT_MINIMAL_BUILD) - Graph(); -#endif -}; - -namespace detail { -template -struct ModelImpl : Ort::detail::Base { - using B = Ort::detail::Base; - using B::B; - -#if !defined(ORT_MINIMAL_BUILD) - void AddGraph(Graph& graph); -#endif -}; -} // namespace detail - -// Const object holder that does not own the underlying object -using ConstModel = detail::ModelImpl>; - -/** \brief Wrapper around ::OrtModel - * - */ -struct Model : detail::ModelImpl { - using DomainOpsetPair = std::pair; - - explicit Model(std::nullptr_t) {} ///< No instance is created - explicit Model(OrtModel* p) : ModelImpl{p} {} ///< Take ownership of a pointer created by C API - -#if !defined(ORT_MINIMAL_BUILD) - explicit Model(const std::vector& opsets); -#endif - - ConstModel GetConst() const { return ConstModel{this->p_}; } -}; -} // namespace Ort -#include "onnxruntime_cxx_inline.h" +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Summary: The Ort C++ API is a header only wrapper around the Ort C API. +// +// The C++ API simplifies usage by returning values directly instead of error codes, throwing exceptions on errors +// and automatically releasing resources in the destructors. The primary purpose of C++ API is exception safety so +// all the resources follow RAII and do not leak memory. +// +// Each of the C++ wrapper classes holds only a pointer to the C internal object. Treat them like smart pointers. +// To create an empty object, pass 'nullptr' to the constructor (for example, Env e{nullptr};). However, you can't use them +// until you assign an instance that actually holds an underlying object. +// +// For Ort objects only move assignment between objects is allowed, there are no copy constructors. +// Some objects have explicit 'Clone' methods for this purpose. +// +// ConstXXXX types are copyable since they do not own the underlying C object, so you can pass them to functions as arguments +// by value or by reference. ConstXXXX types are restricted to const only interfaces. +// +// UnownedXXXX are similar to ConstXXXX but also allow non-const interfaces. +// +// The lifetime of the corresponding owning object must eclipse the lifetimes of the ConstXXXX/UnownedXXXX types. They exists so you do not +// have to fallback to C types and the API with the usual pitfalls. In general, do not use C API from your C++ code. + +#pragma once +#include "onnxruntime_c_api.h" +#include "onnxruntime_float16.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef ORT_NO_EXCEPTIONS +#include +#endif + +/** \brief All C++ Onnxruntime APIs are defined inside this namespace + * + */ +namespace Ort { + +/** \brief All C++ methods that can fail will throw an exception of this type + * + * If ORT_NO_EXCEPTIONS is defined, then any error will result in a call to abort() + */ +struct Exception : std::exception { + Exception(std::string&& string, OrtErrorCode code) : message_{std::move(string)}, code_{code} {} + + OrtErrorCode GetOrtErrorCode() const { return code_; } + const char* what() const noexcept override { return message_.c_str(); } + + private: + std::string message_; + OrtErrorCode code_; +}; + +#ifdef ORT_NO_EXCEPTIONS +// The #ifndef is for the very special case where the user of this library wants to define their own way of handling errors. +// NOTE: This header expects control flow to not continue after calling ORT_CXX_API_THROW +#ifndef ORT_CXX_API_THROW +#define ORT_CXX_API_THROW(string, code) \ + do { \ + std::cerr << Ort::Exception(string, code) \ + .what() \ + << std::endl; \ + abort(); \ + } while (false) +#endif +#else +#define ORT_CXX_API_THROW(string, code) \ + throw Ort::Exception(string, code) +#endif + +// This is used internally by the C++ API. This class holds the global variable that points to the OrtApi, +// it's in a template so that we can define a global variable in a header and make +// it transparent to the users of the API. +template +struct Global { + static const OrtApi* api_; +}; + +// If macro ORT_API_MANUAL_INIT is defined, no static initialization will be performed. Instead, user must call InitApi() before using it. +template +#ifdef ORT_API_MANUAL_INIT +const OrtApi* Global::api_{}; +inline void InitApi() noexcept { Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); } + +// Used by custom operator libraries that are not linked to onnxruntime. Sets the global API object, which is +// required by C++ APIs. +// +// Example mycustomop.cc: +// +// #define ORT_API_MANUAL_INIT +// #include +// #undef ORT_API_MANUAL_INIT +// +// OrtStatus* ORT_API_CALL RegisterCustomOps(OrtSessionOptions* options, const OrtApiBase* api_base) { +// Ort::InitApi(api_base->GetApi(ORT_API_VERSION)); +// // ... +// } +// +inline void InitApi(const OrtApi* api) noexcept { Global::api_ = api; } +#else +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +// "Global initializer calls a non-constexpr function." Therefore you can't use ORT APIs in the other global initializers. +// Please define ORT_API_MANUAL_INIT if it conerns you. +#pragma warning(disable : 26426) +#endif +const OrtApi* Global::api_ = OrtGetApiBase()->GetApi(ORT_API_VERSION); +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif +#endif + +/// This returns a reference to the ORT C API. +inline const OrtApi& GetApi() noexcept { return *Global::api_; } + +/// +/// This function returns the onnxruntime version string +/// +/// version string major.minor.rev +std::string GetVersionString(); + +/// +/// This function returns the onnxruntime build information: including git branch, +/// git commit id, build type(Debug/Release/RelWithDebInfo) and cmake cpp flags. +/// +/// string +std::string GetBuildInfoString(); + +/// +/// This is a C++ wrapper for OrtApi::GetAvailableProviders() and +/// returns a vector of strings representing the available execution providers. +/// +/// vector of strings +std::vector GetAvailableProviders(); + +/// +/// This returns a reference to the ORT C Model Editor API. Used if building or augmenting a model at runtime. +/// +/// ORT C Model Editor API reference +inline const OrtModelEditorApi& GetModelEditorApi() { + auto* api = GetApi().GetModelEditorApi(); + if (api == nullptr) { + // minimal build + ORT_CXX_API_THROW("Model Editor API is not available in this build", ORT_FAIL); + } + + return *api; +} + +/// +/// This returns a reference to the ORT C Compile API. Used if compiling a model at runtime. +/// +/// ORT C Compile API reference +inline const OrtCompileApi& GetCompileApi() { + auto* api = GetApi().GetCompileApi(); + if (api == nullptr) { + // minimal build + ORT_CXX_API_THROW("Compile API is not available in this build", ORT_FAIL); + } + + return *api; +} + +/// +/// This returns a reference to the ORT C EP API. Used if authoring a plugin execution provider. +/// +/// ORT C EP API reference +inline const OrtEpApi& GetEpApi() { + auto* api = GetApi().GetEpApi(); + if (api == nullptr) { + // minimal build + ORT_CXX_API_THROW("EP API is not available in this build", ORT_FAIL); + } + + return *api; +} + +/** \brief IEEE 754 half-precision floating point data type + * + * \details This struct is used for converting float to float16 and back + * so the user could feed inputs and fetch outputs using these type. + * + * The size of the structure should align with uint16_t and one can freely cast + * uint16_t buffers to/from Ort::Float16_t to feed and retrieve data. + * + * \code{.unparsed} + * // This example demonstrates converion from float to float16 + * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; + * std::vector fp16_values; + * fp16_values.reserve(std::size(values)); + * std::transform(std::begin(values), std::end(values), std::back_inserter(fp16_values), + * [](float value) { return Ort::Float16_t(value); }); + * + * \endcode + */ +struct Float16_t : onnxruntime_float16::Float16Impl { + private: + /// + /// Constructor from a 16-bit representation of a float16 value + /// No conversion is done here. + /// + /// 16-bit representation + constexpr explicit Float16_t(uint16_t v) noexcept { val = v; } + + public: + using Base = onnxruntime_float16::Float16Impl; + + /// + /// Default constructor + /// + Float16_t() = default; + + /// + /// Explicit conversion to uint16_t representation of float16. + /// + /// uint16_t bit representation of float16 + /// new instance of Float16_t + constexpr static Float16_t FromBits(uint16_t v) noexcept { return Float16_t(v); } + + /// + /// __ctor from float. Float is converted into float16 16-bit representation. + /// + /// float value + explicit Float16_t(float v) noexcept { val = Base::ToUint16Impl(v); } + + /// + /// Converts float16 to float + /// + /// float representation of float16 value + float ToFloat() const noexcept { return Base::ToFloatImpl(); } + + /// + /// Checks if the value is negative + /// + /// true if negative + using Base::IsNegative; + + /// + /// Tests if the value is NaN + /// + /// true if NaN + using Base::IsNaN; + + /// + /// Tests if the value is finite + /// + /// true if finite + using Base::IsFinite; + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + using Base::IsPositiveInfinity; + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + using Base::IsNegativeInfinity; + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + using Base::IsInfinity; + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + using Base::IsNaNOrZero; + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + using Base::IsNormal; + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + using Base::IsSubnormal; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + using Base::Abs; + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + using Base::Negate; + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + using Base::AreZero; + + /// + /// User defined conversion operator. Converts Float16_t to float. + /// + explicit operator float() const noexcept { return ToFloat(); } + + using Base::operator==; + using Base::operator!=; + using Base::operator<; +}; + +static_assert(sizeof(Float16_t) == sizeof(uint16_t), "Sizes must match"); + +/** \brief bfloat16 (Brain Floating Point) data type + * + * \details This struct is used for converting float to bfloat16 and back + * so the user could feed inputs and fetch outputs using these type. + * + * The size of the structure should align with uint16_t and one can freely cast + * uint16_t buffers to/from Ort::BFloat16_t to feed and retrieve data. + * + * \code{.unparsed} + * // This example demonstrates converion from float to float16 + * constexpr float values[] = {1.f, 2.f, 3.f, 4.f, 5.f}; + * std::vector bfp16_values; + * bfp16_values.reserve(std::size(values)); + * std::transform(std::begin(values), std::end(values), std::back_inserter(bfp16_values), + * [](float value) { return Ort::BFloat16_t(value); }); + * + * \endcode + */ +struct BFloat16_t : onnxruntime_float16::BFloat16Impl { + private: + /// + /// Constructor from a uint16_t representation of bfloat16 + /// used in FromBits() to escape overload resolution issue with + /// constructor from float. + /// No conversion is done. + /// + /// 16-bit bfloat16 value + constexpr explicit BFloat16_t(uint16_t v) noexcept { val = v; } + + public: + using Base = onnxruntime_float16::BFloat16Impl; + + BFloat16_t() = default; + + /// + /// Explicit conversion to uint16_t representation of bfloat16. + /// + /// uint16_t bit representation of bfloat16 + /// new instance of BFloat16_t + static constexpr BFloat16_t FromBits(uint16_t v) noexcept { return BFloat16_t(v); } + + /// + /// __ctor from float. Float is converted into bfloat16 16-bit representation. + /// + /// float value + explicit BFloat16_t(float v) noexcept { val = Base::ToUint16Impl(v); } + + /// + /// Converts bfloat16 to float + /// + /// float representation of bfloat16 value + float ToFloat() const noexcept { return Base::ToFloatImpl(); } + + /// + /// Checks if the value is negative + /// + /// true if negative + using Base::IsNegative; + + /// + /// Tests if the value is NaN + /// + /// true if NaN + using Base::IsNaN; + + /// + /// Tests if the value is finite + /// + /// true if finite + using Base::IsFinite; + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + using Base::IsPositiveInfinity; + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + using Base::IsNegativeInfinity; + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + using Base::IsInfinity; + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + using Base::IsNaNOrZero; + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + using Base::IsNormal; + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + using Base::IsSubnormal; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + using Base::Abs; + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + using Base::Negate; + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + using Base::AreZero; + + /// + /// User defined conversion operator. Converts BFloat16_t to float. + /// + explicit operator float() const noexcept { return ToFloat(); } + + // We do not have an inherited impl for the below operators + // as the internal class implements them a little differently + bool operator==(const BFloat16_t& rhs) const noexcept; + bool operator!=(const BFloat16_t& rhs) const noexcept { return !(*this == rhs); } + bool operator<(const BFloat16_t& rhs) const noexcept; +}; + +static_assert(sizeof(BFloat16_t) == sizeof(uint16_t), "Sizes must match"); + +/** \brief float8e4m3fn (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E4M3FN_t { + uint8_t value; + constexpr Float8E4M3FN_t() noexcept : value(0) {} + constexpr Float8E4M3FN_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E4M3FN_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E4M3FN_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E4M3FN_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e4m3fnuz (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E4M3FNUZ_t { + uint8_t value; + constexpr Float8E4M3FNUZ_t() noexcept : value(0) {} + constexpr Float8E4M3FNUZ_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E4M3FNUZ_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E4M3FNUZ_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E4M3FNUZ_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e5m2 (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E5M2_t { + uint8_t value; + constexpr Float8E5M2_t() noexcept : value(0) {} + constexpr Float8E5M2_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E5M2_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E5M2_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E5M2_t) == sizeof(uint8_t), "Sizes must match"); + +/** \brief float8e5m2fnuz (Float8 Floating Point) data type + * \details It is necessary for type dispatching to make use of C++ API + * The type is implicitly convertible to/from uint8_t. + * See https://onnx.ai/onnx/technical/float8.html for further details. + */ +struct Float8E5M2FNUZ_t { + uint8_t value; + constexpr Float8E5M2FNUZ_t() noexcept : value(0) {} + constexpr Float8E5M2FNUZ_t(uint8_t v) noexcept : value(v) {} + constexpr operator uint8_t() const noexcept { return value; } + // nan values are treated like any other value for operator ==, != + constexpr bool operator==(const Float8E5M2FNUZ_t& rhs) const noexcept { return value == rhs.value; }; + constexpr bool operator!=(const Float8E5M2FNUZ_t& rhs) const noexcept { return value != rhs.value; }; +}; + +static_assert(sizeof(Float8E5M2FNUZ_t) == sizeof(uint8_t), "Sizes must match"); + +namespace detail { +// This is used internally by the C++ API. This macro is to make it easy to generate overloaded methods for all of the various OrtRelease* functions for every Ort* type +// This can't be done in the C API since C doesn't have function overloading. +#define ORT_DEFINE_RELEASE(NAME) \ + inline void OrtRelease(Ort##NAME* ptr) { GetApi().Release##NAME(ptr); } + +#define ORT_DEFINE_RELEASE_FROM_API_STRUCT(NAME, API_GETTER) \ + inline void OrtRelease(Ort##NAME* ptr) { API_GETTER().Release##NAME(ptr); } + +ORT_DEFINE_RELEASE(Allocator); +ORT_DEFINE_RELEASE(MemoryInfo); +ORT_DEFINE_RELEASE(CustomOpDomain); +ORT_DEFINE_RELEASE(ThreadingOptions); +ORT_DEFINE_RELEASE(Env); +ORT_DEFINE_RELEASE(RunOptions); +ORT_DEFINE_RELEASE(LoraAdapter); +ORT_DEFINE_RELEASE(Session); +ORT_DEFINE_RELEASE(SessionOptions); +ORT_DEFINE_RELEASE(TensorTypeAndShapeInfo); +ORT_DEFINE_RELEASE(SequenceTypeInfo); +ORT_DEFINE_RELEASE(MapTypeInfo); +ORT_DEFINE_RELEASE(TypeInfo); +ORT_DEFINE_RELEASE(Value); +ORT_DEFINE_RELEASE(ModelMetadata); +ORT_DEFINE_RELEASE(IoBinding); +ORT_DEFINE_RELEASE(ArenaCfg); +ORT_DEFINE_RELEASE(Status); +ORT_DEFINE_RELEASE(OpAttr); +ORT_DEFINE_RELEASE(Op); +ORT_DEFINE_RELEASE(KernelInfo); +ORT_DEFINE_RELEASE(ValueInfo); +ORT_DEFINE_RELEASE(Node); +ORT_DEFINE_RELEASE(Graph); +ORT_DEFINE_RELEASE(Model); +ORT_DEFINE_RELEASE(KeyValuePairs) +ORT_DEFINE_RELEASE_FROM_API_STRUCT(ModelCompilationOptions, GetCompileApi); +ORT_DEFINE_RELEASE_FROM_API_STRUCT(EpDevice, GetEpApi); + +#undef ORT_DEFINE_RELEASE +#undef ORT_DEFINE_RELEASE_FROM_API_STRUCT + +/** \brief This is a tagging template type. Use it with Base to indicate that the C++ interface object + * has no ownership of the underlying C object. + */ +template +struct Unowned { + using Type = T; +}; + +/** \brief Used internally by the C++ API. C++ wrapper types inherit from this. + * This is a zero cost abstraction to wrap the C API objects and delete them on destruction. + * + * All of the C++ classes + * a) serve as containers for pointers to objects that are created by the underlying C API. + * Their size is just a pointer size, no need to dynamically allocate them. Use them by value. + * b) Each of struct XXXX, XXX instances function as smart pointers to the underlying C API objects. + * they would release objects owned automatically when going out of scope, they are move-only. + * c) ConstXXXX and UnownedXXX structs function as non-owning, copyable containers for the above pointers. + * ConstXXXX allow calling const interfaces only. They give access to objects that are owned by somebody else + * such as Onnxruntime or instances of XXXX classes. + * d) serve convenient interfaces that return C++ objects and further enhance exception and type safety so they can be used + * in C++ code. + * + */ + +/// +/// This is a non-const pointer holder that is move-only. Disposes of the pointer on destruction. +/// +template +struct Base { + using contained_type = T; + + constexpr Base() = default; + constexpr explicit Base(contained_type* p) noexcept : p_{p} {} + ~Base() { + OrtRelease(p_); + } + + Base(const Base&) = delete; + Base& operator=(const Base&) = delete; + + Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } + Base& operator=(Base&& v) noexcept { + OrtRelease(p_); + p_ = v.release(); + return *this; + } + + constexpr operator contained_type*() const noexcept { return p_; } + + /// \brief Relinquishes ownership of the contained C object pointer + /// The underlying object is not destroyed + contained_type* release() { + T* p = p_; + p_ = nullptr; + return p; + } + + protected: + contained_type* p_{}; +}; + +// Undefined. For const types use Base> +template +struct Base; + +/// +/// Covers unowned pointers owned by either the ORT +/// or some other instance of CPP wrappers. +/// Used for ConstXXX and UnownedXXXX types that are copyable. +/// Also convenient to wrap raw OrtXX pointers . +/// +/// +template +struct Base> { + using contained_type = typename Unowned::Type; + + constexpr Base() = default; + constexpr explicit Base(contained_type* p) noexcept : p_{p} {} + + ~Base() = default; + + Base(const Base&) = default; + Base& operator=(const Base&) = default; + + Base(Base&& v) noexcept : p_{v.p_} { v.p_ = nullptr; } + Base& operator=(Base&& v) noexcept { + p_ = nullptr; + std::swap(p_, v.p_); + return *this; + } + + constexpr operator contained_type*() const noexcept { return p_; } + + protected: + contained_type* p_{}; +}; + +// Light functor to release memory with OrtAllocator +struct AllocatedFree { + OrtAllocator* allocator_; + explicit AllocatedFree(OrtAllocator* allocator) + : allocator_(allocator) {} + void operator()(void* ptr) const { + if (ptr) allocator_->Free(allocator_, ptr); + } +}; + +} // namespace detail + +struct AllocatorWithDefaultOptions; +struct Env; +struct EpDevice; +struct Graph; +struct Model; +struct Node; +struct ModelMetadata; +struct TypeInfo; +struct Value; +struct ValueInfo; + +/** \brief unique_ptr typedef used to own strings allocated by OrtAllocators + * and release them at the end of the scope. The lifespan of the given allocator + * must eclipse the lifespan of AllocatedStringPtr instance + */ +using AllocatedStringPtr = std::unique_ptr; + +/** \brief The Status that holds ownership of OrtStatus received from C API + * Use it to safely destroy OrtStatus* returned from the C API. Use appropriate + * constructors to construct an instance of a Status object from exceptions. + */ +struct Status : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit Status(std::nullptr_t) noexcept {} ///< Create an empty object, must be assigned a valid one to be used + explicit Status(OrtStatus* status) noexcept; ///< Takes ownership of OrtStatus instance returned from the C API. + explicit Status(const Exception&) noexcept; ///< Creates status instance out of exception + explicit Status(const std::exception&) noexcept; ///< Creates status instance out of exception + Status(const char* message, OrtErrorCode code) noexcept; ///< Creates status instance out of null-terminated string message. + std::string GetErrorMessage() const; + OrtErrorCode GetErrorCode() const; + bool IsOK() const noexcept; ///< Returns true if instance represents an OK (non-error) status. +}; + +/** \brief The ThreadingOptions + * + * The ThreadingOptions used for set global threadpools' options of The Env. + */ +struct ThreadingOptions : detail::Base { + /// \brief Wraps OrtApi::CreateThreadingOptions + ThreadingOptions(); + + /// \brief Wraps OrtApi::SetGlobalIntraOpNumThreads + ThreadingOptions& SetGlobalIntraOpNumThreads(int intra_op_num_threads); + + /// \brief Wraps OrtApi::SetGlobalInterOpNumThreads + ThreadingOptions& SetGlobalInterOpNumThreads(int inter_op_num_threads); + + /// \brief Wraps OrtApi::SetGlobalSpinControl + ThreadingOptions& SetGlobalSpinControl(int allow_spinning); + + /// \brief Wraps OrtApi::SetGlobalDenormalAsZero + ThreadingOptions& SetGlobalDenormalAsZero(); + + /// \brief Wraps OrtApi::SetGlobalCustomCreateThreadFn + ThreadingOptions& SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); + + /// \brief Wraps OrtApi::SetGlobalCustomThreadCreationOptions + ThreadingOptions& SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options); + + /// \brief Wraps OrtApi::SetGlobalCustomJoinThreadFn + ThreadingOptions& SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); +}; + +namespace detail { +template +struct KeyValuePairsImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + const char* GetValue(const char* key) const; + + // get the pairs in unordered_map. needs to copy to std::string so the hash works as expected + std::unordered_map GetKeyValuePairs() const; + // get the pairs in two vectors. entries will be 1:1 between keys and values. avoids copying to std::string + void GetKeyValuePairs(std::vector& keys, std::vector& values) const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstKeyValuePairs = detail::KeyValuePairsImpl>; + +/** \brief Wrapper around ::OrtKeyValuePair */ +struct KeyValuePairs : detail::KeyValuePairsImpl { + explicit KeyValuePairs(std::nullptr_t) {} ///< No instance is created + /// Take ownership of a pointer created by C API + explicit KeyValuePairs(OrtKeyValuePairs* p) : KeyValuePairsImpl{p} {} + + /// \brief Wraps OrtApi::CreateKeyValuePairs + explicit KeyValuePairs(); + + /// \brief Wraps OrtApi::CreateKeyValuePairs and OrtApi::AddKeyValuePair + explicit KeyValuePairs(const std::unordered_map& kv_pairs); + + /// \brief Wraps OrtApi::AddKeyValuePair + void Add(const char* key, const char* value); + + /// \brief Wraps OrtApi::RemoveKeyValuePair + void Remove(const char* key); + + ConstKeyValuePairs GetConst() const { return ConstKeyValuePairs{this->p_}; } +}; + +namespace detail { +template +struct HardwareDeviceImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + OrtHardwareDeviceType Type() const; + uint32_t VendorId() const; + uint32_t DeviceId() const; + const char* Vendor() const; + ConstKeyValuePairs Metadata() const; +}; +} // namespace detail + +/** \brief Wrapper around ::OrtHardwareDevice + * \remarks HardwareDevice is always read-only for API users. + */ +using ConstHardwareDevice = detail::HardwareDeviceImpl>; + +namespace detail { +template +struct EpDeviceImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + const char* EpName() const; + const char* EpVendor() const; + ConstKeyValuePairs EpMetadata() const; + ConstKeyValuePairs EpOptions() const; + ConstHardwareDevice Device() const; +}; +} // namespace detail + +/** \brief Wrapper around ::OrtEpDevice + * \remarks EpDevice is always read-only for ORT API users. + */ +using ConstEpDevice = detail::EpDeviceImpl>; + +/** \brief Mutable EpDevice that is created by EpApi users. + */ +struct EpDevice : detail::EpDeviceImpl { + explicit EpDevice(std::nullptr_t) {} ///< No instance is created + explicit EpDevice(OrtEpDevice* p) : EpDeviceImpl{p} {} ///< Take ownership of a pointer created by C API + + /// \brief Wraps OrtEpApi::CreateEpDevice + EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, + ConstKeyValuePairs ep_metadata = {}, ConstKeyValuePairs ep_options = {}); +}; + +/** \brief The Env (Environment) + * + * The Env holds the logging state used by all other objects. + * Note: One Env must be created before using any other Onnxruntime functionality + */ +struct Env : detail::Base { + explicit Env(std::nullptr_t) {} ///< Create an empty Env object, must be assigned a valid one to be used + + /// \brief Wraps OrtApi::CreateEnv + Env(OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief Wraps OrtApi::CreateEnvWithCustomLogger + Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param); + + /// \brief Wraps OrtApi::CreateEnvWithGlobalThreadPools + Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief Wraps OrtApi::CreateEnvWithCustomLoggerAndGlobalThreadPools + Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, + OrtLoggingLevel logging_level = ORT_LOGGING_LEVEL_WARNING, _In_ const char* logid = ""); + + /// \brief C Interop Helper + explicit Env(OrtEnv* p) : Base{p} {} + + Env& EnableTelemetryEvents(); ///< Wraps OrtApi::EnableTelemetryEvents + Env& DisableTelemetryEvents(); ///< Wraps OrtApi::DisableTelemetryEvents + + Env& UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level); ///< Wraps OrtApi::UpdateEnvWithCustomLogLevel + + Env& CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocator + + Env& CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, + const std::unordered_map& options, + const OrtArenaCfg* arena_cfg); ///< Wraps OrtApi::CreateAndRegisterAllocatorV2 + + Env& RegisterExecutionProviderLibrary(const char* registration_name, const std::basic_string& path); ///< Wraps OrtApi::RegisterExecutionProviderLibrary + Env& UnregisterExecutionProviderLibrary(const char* registration_name); ///< Wraps OrtApi::UnregisterExecutionProviderLibrary + + std::vector GetEpDevices() const; +}; + +/** \brief Custom Op Domain + * + */ +struct CustomOpDomain : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit CustomOpDomain(std::nullptr_t) {} ///< Create an empty CustomOpDomain object, must be assigned a valid one to be used + + /// \brief Wraps OrtApi::CreateCustomOpDomain + explicit CustomOpDomain(const char* domain); + + // This does not take ownership of the op, simply registers it. + void Add(const OrtCustomOp* op); ///< Wraps CustomOpDomain_Add +}; + +/// \brief LoraAdapter holds a set of Lora Parameters loaded from a single file +struct LoraAdapter : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit LoraAdapter(std::nullptr_t) {} ///< Create an empty LoraAdapter object, must be assigned a valid one to be used + /// \brief Wraps OrtApi::CreateLoraAdapter + /// + /// The function attempts to load the adapter from the specified file + /// \param adapter_path The path to the Lora adapter + /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still + /// be copied to device if required by the model at inference time. + static LoraAdapter CreateLoraAdapter(const std::basic_string& adapter_path, + OrtAllocator* allocator); + + /// \brief Wraps OrtApi::CreateLoraAdapterFromArray + /// + /// The function attempts to load the adapter from the specified byte array. + /// \param bytes The byte array containing file LoraAdapter format + /// \param num_bytes The number of bytes in the byte array + /// \param allocator optional pointer to a device allocator. If nullptr, the data stays on CPU. It would still + /// be copied to device if required by the model at inference time. + static LoraAdapter CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, + OrtAllocator* allocator); +}; + +/** \brief RunOptions + * + */ +struct RunOptions : detail::Base { + explicit RunOptions(std::nullptr_t) {} ///< Create an empty RunOptions object, must be assigned a valid one to be used + RunOptions(); ///< Wraps OrtApi::CreateRunOptions + + RunOptions& SetRunLogVerbosityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogVerbosityLevel + int GetRunLogVerbosityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogVerbosityLevel + + RunOptions& SetRunLogSeverityLevel(int); ///< Wraps OrtApi::RunOptionsSetRunLogSeverityLevel + int GetRunLogSeverityLevel() const; ///< Wraps OrtApi::RunOptionsGetRunLogSeverityLevel + + RunOptions& SetRunTag(const char* run_tag); ///< wraps OrtApi::RunOptionsSetRunTag + const char* GetRunTag() const; ///< Wraps OrtApi::RunOptionsGetRunTag + + RunOptions& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddRunConfigEntry + + /** \brief Terminates all currently executing Session::Run calls that were made using this RunOptions instance + * + * If a currently executing session needs to be force terminated, this can be called from another thread to force it to fail with an error + * Wraps OrtApi::RunOptionsSetTerminate + */ + RunOptions& SetTerminate(); + + /** \brief Clears the terminate flag so this RunOptions instance can be used in a new Session::Run call without it instantly terminating + * + * Wraps OrtApi::RunOptionsUnsetTerminate + */ + RunOptions& UnsetTerminate(); + + /** \brief Add the LoraAdapter to the list of active adapters. + * The setting does not affect RunWithBinding() calls. + * + * Wraps OrtApi::RunOptionsAddActiveLoraAdapter + * \param adapter The LoraAdapter to be used as the active adapter + */ + RunOptions& AddActiveLoraAdapter(const LoraAdapter& adapter); +}; + +namespace detail { +// Utility function that returns a SessionOption config entry key for a specific custom operator. +// Ex: custom_op.[custom_op_name].[config] +std::string MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config); +} // namespace detail + +/// +/// Class that represents session configuration entries for one or more custom operators. +/// +/// Example: +/// Ort::CustomOpConfigs op_configs; +/// op_configs.AddConfig("my_custom_op", "device_type", "CPU"); +/// +/// Passed to Ort::SessionOptions::RegisterCustomOpsLibrary. +/// +struct CustomOpConfigs { + CustomOpConfigs() = default; + ~CustomOpConfigs() = default; + CustomOpConfigs(const CustomOpConfigs&) = default; + CustomOpConfigs& operator=(const CustomOpConfigs&) = default; + CustomOpConfigs(CustomOpConfigs&& o) = default; + CustomOpConfigs& operator=(CustomOpConfigs&& o) = default; + + /** \brief Adds a session configuration entry/value for a specific custom operator. + * + * \param custom_op_name The name of the custom operator for which to add a configuration entry. + * Must match the name returned by the CustomOp's GetName() method. + * \param config_key The name of the configuration entry. + * \param config_value The value of the configuration entry. + * \return A reference to this object to enable call chaining. + */ + CustomOpConfigs& AddConfig(const char* custom_op_name, const char* config_key, const char* config_value); + + /** \brief Returns a flattened map of custom operator configuration entries and their values. + * + * The keys has been flattened to include both the custom operator name and the configuration entry key name. + * For example, a prior call to AddConfig("my_op", "key", "value") corresponds to the flattened key/value pair + * {"my_op.key", "value"}. + * + * \return An unordered map of flattened configurations. + */ + const std::unordered_map& GetFlattenedConfigs() const; + + private: + std::unordered_map flat_configs_; +}; + +/** \brief Options object used when creating a new Session object + * + * Wraps ::OrtSessionOptions object and methods + */ + +struct SessionOptions; + +namespace detail { +// we separate const-only methods because passing const ptr to non-const methods +// is only discovered when inline methods are compiled which is counter-intuitive +template +struct ConstSessionOptionsImpl : Base { + using B = Base; + using B::B; + + SessionOptions Clone() const; ///< Creates and returns a copy of this SessionOptions object. Wraps OrtApi::CloneSessionOptions + + std::string GetConfigEntry(const char* config_key) const; ///< Wraps OrtApi::GetSessionConfigEntry + bool HasConfigEntry(const char* config_key) const; ///< Wraps OrtApi::HasSessionConfigEntry + std::string GetConfigEntryOrDefault(const char* config_key, const std::string& def) const; +}; + +template +struct SessionOptionsImpl : ConstSessionOptionsImpl { + using B = ConstSessionOptionsImpl; + using B::B; + + SessionOptionsImpl& SetIntraOpNumThreads(int intra_op_num_threads); ///< Wraps OrtApi::SetIntraOpNumThreads + SessionOptionsImpl& SetInterOpNumThreads(int inter_op_num_threads); ///< Wraps OrtApi::SetInterOpNumThreads + SessionOptionsImpl& SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level); ///< Wraps OrtApi::SetSessionGraphOptimizationLevel + SessionOptionsImpl& SetDeterministicCompute(bool value); ///< Wraps OrtApi::SetDeterministicCompute + + SessionOptionsImpl& EnableCpuMemArena(); ///< Wraps OrtApi::EnableCpuMemArena + SessionOptionsImpl& DisableCpuMemArena(); ///< Wraps OrtApi::DisableCpuMemArena + + SessionOptionsImpl& SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_file); ///< Wraps OrtApi::SetOptimizedModelFilePath + + SessionOptionsImpl& EnableProfiling(const ORTCHAR_T* profile_file_prefix); ///< Wraps OrtApi::EnableProfiling + SessionOptionsImpl& DisableProfiling(); ///< Wraps OrtApi::DisableProfiling + + SessionOptionsImpl& EnableOrtCustomOps(); ///< Wraps OrtApi::EnableOrtCustomOps + + SessionOptionsImpl& EnableMemPattern(); ///< Wraps OrtApi::EnableMemPattern + SessionOptionsImpl& DisableMemPattern(); ///< Wraps OrtApi::DisableMemPattern + + SessionOptionsImpl& SetExecutionMode(ExecutionMode execution_mode); ///< Wraps OrtApi::SetSessionExecutionMode + + SessionOptionsImpl& SetLoadCancellationFlag(bool value); ///< Wraps OrtApi::SessionOptionsSetLoadCancellationFlag + + SessionOptionsImpl& SetLogId(const char* logid); ///< Wraps OrtApi::SetSessionLogId + SessionOptionsImpl& SetLogSeverityLevel(int level); ///< Wraps OrtApi::SetSessionLogSeverityLevel + + SessionOptionsImpl& Add(OrtCustomOpDomain* custom_op_domain); ///< Wraps OrtApi::AddCustomOpDomain + + SessionOptionsImpl& DisablePerSessionThreads(); ///< Wraps OrtApi::DisablePerSessionThreads + + SessionOptionsImpl& AddConfigEntry(const char* config_key, const char* config_value); ///< Wraps OrtApi::AddSessionConfigEntry + + SessionOptionsImpl& AddInitializer(const char* name, const OrtValue* ort_val); ///< Wraps OrtApi::AddInitializer + SessionOptionsImpl& AddExternalInitializers(const std::vector& names, const std::vector& ort_values); ///< Wraps OrtApi::AddExternalInitializers + SessionOptionsImpl& AddExternalInitializersFromFilesInMemory(const std::vector>& external_initializer_file_names, + const std::vector& external_initializer_file_buffer_array, + const std::vector& external_initializer_file_lengths); ///< Wraps OrtApi::AddExternalInitializersFromFilesInMemory + + SessionOptionsImpl& AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA + SessionOptionsImpl& AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_CUDA_V2 + SessionOptionsImpl& AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_ROCM + SessionOptionsImpl& AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO + ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_OpenVINO_V2 + SessionOptionsImpl& AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options = {}); + SessionOptionsImpl& AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + SessionOptionsImpl& AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_TensorRT + SessionOptionsImpl& AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options); ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_MIGraphX + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_CANN + SessionOptionsImpl& AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options); + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_Dnnl + SessionOptionsImpl& AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options); + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider. Currently supports QNN, SNPE and XNNPACK. + SessionOptionsImpl& AppendExecutionProvider(const std::string& provider_name, + const std::unordered_map& provider_options = {}); + + /// Append EPs that have been registered previously with the OrtEnv. + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 + SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, + const KeyValuePairs& ep_options); + /// Append EPs that have been registered previously with the OrtEnv. + /// Wraps OrtApi::SessionOptionsAppendExecutionProvider_V2 + SessionOptionsImpl& AppendExecutionProvider_V2(Env& env, const std::vector& ep_devices, + const std::unordered_map& ep_options); + + /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicy + SessionOptionsImpl& SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy); + + /// Wraps OrtApi::SessionOptionsSetEpSelectionPolicyDelegate + SessionOptionsImpl& SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state = nullptr); + + SessionOptionsImpl& SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomCreateThreadFn + SessionOptionsImpl& SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options); ///< Wraps OrtApi::SessionOptionsSetCustomThreadCreationOptions + SessionOptionsImpl& SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn); ///< Wraps OrtApi::SessionOptionsSetCustomJoinThreadFn + + ///< Registers the custom operator from the specified shared library via OrtApi::RegisterCustomOpsLibrary_V2. + ///< The custom operator configurations are optional. If provided, custom operator configs are set via + ///< OrtApi::AddSessionConfigEntry. + SessionOptionsImpl& RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, const CustomOpConfigs& custom_op_configs = {}); + + SessionOptionsImpl& RegisterCustomOpsUsingFunction(const char* function_name); ///< Wraps OrtApi::RegisterCustomOpsUsingFunction + + ///< Wraps OrtApi::SessionOptionsAppendExecutionProvider_VitisAI + SessionOptionsImpl& AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options = {}); +}; +} // namespace detail + +using UnownedSessionOptions = detail::SessionOptionsImpl>; +using ConstSessionOptions = detail::ConstSessionOptionsImpl>; + +/** \brief Wrapper around ::OrtSessionOptions + * + */ +struct SessionOptions : detail::SessionOptionsImpl { + explicit SessionOptions(std::nullptr_t) {} ///< Create an empty SessionOptions object, must be assigned a valid one to be used + SessionOptions(); ///< Wraps OrtApi::CreateSessionOptions + explicit SessionOptions(OrtSessionOptions* p) : SessionOptionsImpl{p} {} ///< Used for interop with the C API + UnownedSessionOptions GetUnowned() const { return UnownedSessionOptions{this->p_}; } + ConstSessionOptions GetConst() const { return ConstSessionOptions{this->p_}; } +}; + +/** \brief Options object used when compiling a model. + * + * Wraps ::OrtModelCompilationOptions object and methods + */ +struct ModelCompilationOptions : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit ModelCompilationOptions(std::nullptr_t) {} ///< Create an empty ModelCompilationOptions object, must be assigned a valid one to be used. + + ModelCompilationOptions(const Env& env, const SessionOptions& session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions + ModelCompilationOptions(const Env& env, ConstSessionOptions session_options); ///< Wraps OrtApi::CreateModelCompilationOptionsFromSessionOptions + + ModelCompilationOptions& SetInputModelPath(const ORTCHAR_T* input_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelPath + ModelCompilationOptions& SetInputModelFromBuffer(const void* input_model_data, + size_t input_model_data_size); ///< Wraps OrtApi::ModelCompilationOptions_SetInputModelFromBuffer + ModelCompilationOptions& SetEpContextEmbedMode(bool embed_ep_context_in_model); ///< Wraps OrtApi::ModelCompilationOptions_SetEpContextEmbedMode + ModelCompilationOptions& SetOutputModelPath(const ORTCHAR_T* output_model_path); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelPath + ModelCompilationOptions& SetOutputModelExternalInitializersFile(const ORTCHAR_T* file_path, + size_t initializer_size_threshold); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelExternalInitializersFile + ModelCompilationOptions& SetOutputModelBuffer(OrtAllocator* allocator, void** output_model_buffer_ptr, + size_t* output_model_buffer_size_ptr); ///< Wraps OrtApi::ModelCompilationOptions_SetOutputModelBuffer +}; + +/** \brief Compiles an input model to generate a model with EPContext nodes that execute EP-specific kernels. Wraps OrtApi::CompileModels. + * + * \param env: ORT environment object. + * \param model_compilation_options: Compilation options for a model. + * \return A Status indicating success or failure. + */ +Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options); + +/** \brief Wrapper around ::OrtModelMetadata + * + */ +struct ModelMetadata : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit ModelMetadata(std::nullptr_t) {} ///< Create an empty ModelMetadata object, must be assigned a valid one to be used + + /** \brief Returns a copy of the producer name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetProducerNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetProducerName + + /** \brief Returns a copy of the graph name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetGraphNameAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphName + + /** \brief Returns a copy of the domain name. + * + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetDomainAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDomain + + /** \brief Returns a copy of the description. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetDescription + + /** \brief Returns a copy of the graph description. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetGraphDescriptionAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetGraphDescription + + /** \brief Returns a vector of copies of the custom metadata keys. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance std::vector of smart pointers that would deallocate the buffers when out of scope. + * The OrtAllocator instance must be valid at the point of memory release. + */ + std::vector GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataGetCustomMetadataMapKeys + + /** \brief Looks up a value by a key in the Custom Metadata map + * + * \param key zero terminated string key to lookup + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * maybe nullptr if key is not found. + * + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const; ///< Wraps OrtApi::ModelMetadataLookupCustomMetadataMap + + int64_t GetVersion() const; ///< Wraps OrtApi::ModelMetadataGetVersion +}; + +struct IoBinding; + +namespace detail { + +// we separate const-only methods because passing const ptr to non-const methods +// is only discovered when inline methods are compiled which is counter-intuitive +template +struct ConstSessionImpl : Base { + using B = Base; + using B::B; + + size_t GetInputCount() const; ///< Returns the number of model inputs + size_t GetOutputCount() const; ///< Returns the number of model outputs + size_t GetOverridableInitializerCount() const; ///< Returns the number of inputs that have defaults that can be overridden + + std::vector GetInputNames() const; + std::vector GetOutputNames() const; + std::vector GetOverridableInitializerNames() const; + + /** \brief Returns a copy of input name at the specified index. + * + * \param index must less than the value returned by GetInputCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetInputNameAllocated(size_t index, OrtAllocator* allocator) const; + + /** \brief Returns a copy of output name at then specified index. + * + * \param index must less than the value returned by GetOutputCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const; + + /** \brief Returns a copy of the overridable initializer name at then specified index. + * + * \param index must less than the value returned by GetOverridableInitializerCount() + * \param allocator to allocate memory for the copy of the name returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const; ///< Wraps OrtApi::SessionGetOverridableInitializerName + + uint64_t GetProfilingStartTimeNs() const; ///< Wraps OrtApi::SessionGetProfilingStartTimeNs + ModelMetadata GetModelMetadata() const; ///< Wraps OrtApi::SessionGetModelMetadata + + TypeInfo GetInputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetInputTypeInfo + TypeInfo GetOutputTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOutputTypeInfo + TypeInfo GetOverridableInitializerTypeInfo(size_t index) const; ///< Wraps OrtApi::SessionGetOverridableInitializerTypeInfo + + int GetOpset(const std::string& domain) const; ///< Wraps OrtApi::SessionGetOpsetForDomain + + // Will move before checkin if that's the case. + std::vector GetInputs() const; + std::vector GetOutputs() const; +}; + +template +struct SessionImpl : ConstSessionImpl { + using B = ConstSessionImpl; + using B::B; + + /** \brief Run the model returning results in an Ort allocated vector. + * + * Wraps OrtApi::Run + * + * The caller provides a list of inputs and a list of the desired outputs to return. + * + * See the output logs for more information on warnings/errors that occur while processing the model. + * Common errors are.. (TODO) + * + * \param[in] run_options + * \param[in] input_names Array of null terminated strings of length input_count that is the list of input names + * \param[in] input_values Array of Value objects of length input_count that is the list of input values + * \param[in] input_count Number of inputs (the size of the input_names & input_values arrays) + * \param[in] output_names Array of C style strings of length output_count that is the list of output names + * \param[in] output_count Number of outputs (the size of the output_names array) + * \return A std::vector of Value objects that directly maps to the output_names array (eg. output_name[0] is the first entry of the returned vector) + */ + std::vector Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, size_t output_count); + + /** \brief Run the model returning results in user provided outputs + * Same as Run(const RunOptions&, const char* const*, const Value*, size_t,const char* const*, size_t) + */ + void Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count); + + void Run(const RunOptions& run_options, const IoBinding&); ///< Wraps OrtApi::RunWithBinding + + /** \brief Run the model asynchronously in a thread owned by intra op thread pool + * + * Wraps OrtApi::RunAsync + * + * \param[in] run_options + * \param[in] input_names Array of null terminated UTF8 encoded strings of the input names + * \param[in] input_values Array of Value objects of length input_count + * \param[in] input_count Number of elements in the input_names and inputs arrays + * \param[in] output_names Array of null terminated UTF8 encoded strings of the output names + * \param[out] output_values Array of provided Values to be filled with outputs. + * On calling RunAsync, output_values[i] could either be initialized by a null pointer or a preallocated OrtValue*. + * Later, on invoking the callback, each output_values[i] of null will be filled with an OrtValue* allocated by onnxruntime. + * Then, an OrtValue** pointer will be casted from output_values, and pass to the callback. + * NOTE: it is customer's duty to finally release output_values and each of its member, + * regardless of whether the member (Ort::Value) is allocated by onnxruntime or preallocated by the customer. + * \param[in] output_count Number of elements in the output_names and outputs array + * \param[in] callback Callback function on model run completion + * \param[in] user_data User data that pass back to the callback + */ + void RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data); + + /** \brief End profiling and return a copy of the profiling file name. + * + * \param allocator to allocate memory for the copy of the string returned + * \return a instance of smart pointer that would deallocate the buffer when out of scope. + * The OrtAllocator instances must be valid at the point of memory release. + */ + AllocatedStringPtr EndProfilingAllocated(OrtAllocator* allocator); ///< Wraps OrtApi::SessionEndProfiling + + /** \brief Set DynamicOptions for EPs (Execution Providers) + * + * Wraps OrtApi::SetEpDynamicOptions + * + * Valid options can be found in `include\onnxruntime\core\session\onnxruntime_session_options_config_keys.h` + * Look for `kOrtEpDynamicOptions` + * + * \param[in] keys Array of null terminated UTF8 encoded strings of EP dynamic option keys + * \param[in] values Array of null terminated UTF8 encoded string of EP dynamic option values + * \param[in] kv_len Number of elements in the keys and values arrays + */ + void SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len); + + void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container = nullptr); +}; + +} // namespace detail + +using ConstSession = detail::ConstSessionImpl>; +using UnownedSession = detail::SessionImpl>; + +/** \brief Wrapper around ::OrtSession + * + */ +struct Session : detail::SessionImpl { + /// Create an empty Session object, must be assigned a valid one to be used. Wraps OrtApi::CreateSession + explicit Session(std::nullptr_t) {} + explicit Session(OrtSession* p) : SessionImpl{p} {} ///< C API Interop + + Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); + + /// Wraps OrtApi::CreateSessionWithPrepackedWeightsContainer + Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); + + /// Wraps OrtApi::CreateSessionFromArray + Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options); + + /// Wraps OrtApi::CreateSessionFromArrayWithPrepackedWeightsContainer + Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); + +#if !defined(ORT_MINIMAL_BUILD) + /// Wraps OrtModelEditorApi::CreateSessionFromModel + Session(const Env& env, const Model& model, const SessionOptions& options); + + /// Wraps OrtModelEditorApi::CreateModelEditorSession + static Session CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options); + + /// Wraps OrtModelEditorApi::CreateModelEditorSession + static Session CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options); +#endif // !defined(ORT_MINIMAL_BUILD) + + ConstSession GetConst() const { return ConstSession{this->p_}; } + UnownedSession GetUnowned() const { return UnownedSession{this->p_}; } +}; + +namespace detail { +template +struct MemoryInfoImpl : Base { + using B = Base; + using B::B; + + std::string GetAllocatorName() const; + OrtAllocatorType GetAllocatorType() const; + int GetDeviceId() const; + OrtMemoryInfoDeviceType GetDeviceType() const; + OrtMemType GetMemoryType() const; + + template + bool operator==(const MemoryInfoImpl& o) const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstMemoryInfo = detail::MemoryInfoImpl>; + +/** \brief Wrapper around ::OrtMemoryInfo + * + */ +struct MemoryInfo : detail::MemoryInfoImpl { + static MemoryInfo CreateCpu(OrtAllocatorType type, OrtMemType mem_type1); + explicit MemoryInfo(std::nullptr_t) {} ///< No instance is created + explicit MemoryInfo(OrtMemoryInfo* p) : MemoryInfoImpl{p} {} ///< Take ownership of a pointer created by C API + MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type); + ConstMemoryInfo GetConst() const { return ConstMemoryInfo{this->p_}; } +}; + +namespace detail { +template +struct TensorTypeAndShapeInfoImpl : Base { + using B = Base; + using B::B; + + ONNXTensorElementDataType GetElementType() const; ///< Wraps OrtApi::GetTensorElementType + size_t GetElementCount() const; ///< Wraps OrtApi::GetTensorShapeElementCount + + size_t GetDimensionsCount() const; ///< Wraps OrtApi::GetDimensionsCount + + /** \deprecated use GetShape() returning std::vector + * [[deprecated]] + * This interface is unsafe to use + */ + [[deprecated("use GetShape()")]] void GetDimensions(int64_t* values, size_t values_count) const; ///< Wraps OrtApi::GetDimensions + + void GetSymbolicDimensions(const char** values, size_t values_count) const; ///< Wraps OrtApi::GetSymbolicDimensions + std::vector GetSymbolicDimensions() const; + + std::vector GetShape() const; ///< Uses GetDimensionsCount & GetDimensions to return a std::vector of the shape +}; + +} // namespace detail + +using ConstTensorTypeAndShapeInfo = detail::TensorTypeAndShapeInfoImpl>; + +/** \brief Wrapper around ::OrtTensorTypeAndShapeInfo + * + */ +struct TensorTypeAndShapeInfo : detail::TensorTypeAndShapeInfoImpl { + using Base = detail::TensorTypeAndShapeInfoImpl; + using Base::Base; + + /// Create an empty TensorTypeAndShapeInfo object, must be assigned a valid one to be used + explicit TensorTypeAndShapeInfo(std::nullptr_t) {} + /// Used for interop with the C API + explicit TensorTypeAndShapeInfo(OrtTensorTypeAndShapeInfo* p) : TensorTypeAndShapeInfoImpl{p} {} + + // Create a TensorTypeAndShapeInfo object with the specified element type and dimensions + // symbolic_dims are optional, but should be 1:1 with dims. + // The value in symbolic_dims will be used for all entries in dims that are -1. + explicit TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, + const std::vector& dims, + const std::vector* symbolic_dims = nullptr); + + ConstTensorTypeAndShapeInfo GetConst() const { return ConstTensorTypeAndShapeInfo{this->p_}; } +}; + +namespace detail { +template +struct SequenceTypeInfoImpl : Base { + using B = Base; + using B::B; + TypeInfo GetSequenceElementType() const; ///< Wraps OrtApi::GetSequenceElementType +}; + +} // namespace detail + +using ConstSequenceTypeInfo = detail::SequenceTypeInfoImpl>; + +/** \brief Wrapper around ::OrtSequenceTypeInfo + * + */ +struct SequenceTypeInfo : detail::SequenceTypeInfoImpl { + using Base = detail::SequenceTypeInfoImpl; + using Base::Base; + + explicit SequenceTypeInfo(std::nullptr_t) {} ///< Create an empty SequenceTypeInfo object, must be assigned a valid one to be used + explicit SequenceTypeInfo(OrtSequenceTypeInfo* p) : SequenceTypeInfoImpl{p} {} ///< Used for interop with the C API + ConstSequenceTypeInfo GetConst() const { return ConstSequenceTypeInfo{this->p_}; } +}; + +namespace detail { +template +struct OptionalTypeInfoImpl : Base { + using B = Base; + using B::B; + TypeInfo GetOptionalElementType() const; ///< Wraps OrtApi::CastOptionalTypeToContainedTypeInfo +}; + +} // namespace detail + +// This is always owned by the TypeInfo and can only be obtained from it. +using ConstOptionalTypeInfo = detail::OptionalTypeInfoImpl>; + +namespace detail { +template +struct MapTypeInfoImpl : detail::Base { + using B = Base; + using B::B; + ONNXTensorElementDataType GetMapKeyType() const; ///< Wraps OrtApi::GetMapKeyType + TypeInfo GetMapValueType() const; ///< Wraps OrtApi::GetMapValueType +}; + +} // namespace detail + +using ConstMapTypeInfo = detail::MapTypeInfoImpl>; + +/** \brief Wrapper around ::OrtMapTypeInfo + * + */ +struct MapTypeInfo : detail::MapTypeInfoImpl { + using Base = detail::MapTypeInfoImpl; + using Base::Base; + + explicit MapTypeInfo(std::nullptr_t) {} ///< Create an empty MapTypeInfo object, must be assigned a valid one to be used + explicit MapTypeInfo(OrtMapTypeInfo* p) : MapTypeInfoImpl{p} {} ///< Used for interop with the C API + ConstMapTypeInfo GetConst() const { return ConstMapTypeInfo{this->p_}; } +}; + +namespace detail { +template +struct TypeInfoImpl : detail::Base { + using B = Base; + using B::B; + + ConstTensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; ///< Wraps OrtApi::CastTypeInfoToTensorInfo + ConstSequenceTypeInfo GetSequenceTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToSequenceTypeInfo + ConstMapTypeInfo GetMapTypeInfo() const; ///< Wraps OrtApi::CastTypeInfoToMapTypeInfo + ConstOptionalTypeInfo GetOptionalTypeInfo() const; ///< wraps OrtApi::CastTypeInfoToOptionalTypeInfo + + ONNXType GetONNXType() const; +}; +} // namespace detail + +/// +/// Contains a constant, unowned OrtTypeInfo that can be copied and passed around by value. +/// Provides access to const OrtTypeInfo APIs. +/// +using ConstTypeInfo = detail::TypeInfoImpl>; + +/// +/// Type information that may contain either TensorTypeAndShapeInfo or +/// the information about contained sequence or map depending on the ONNXType. +/// +struct TypeInfo : detail::TypeInfoImpl { + using Base = detail::TypeInfoImpl; + using Base::Base; + + /// Create an empty TypeInfo object, must be assigned a valid one to be used + explicit TypeInfo(std::nullptr_t) {} + explicit TypeInfo(OrtTypeInfo* p) : TypeInfoImpl{p} {} ///< C API Interop + +#if !defined(ORT_MINIMAL_BUILD) + static TypeInfo CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_info); + static TypeInfo CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_info); + static TypeInfo CreateSequenceTypeInfo(ConstTypeInfo sequence_type); + static TypeInfo CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type); + static TypeInfo CreateOptionalTypeInfo(ConstTypeInfo contained_type); +#endif // !defined(ORT_MINIMAL_BUILD) + + ConstTypeInfo GetConst() const { return ConstTypeInfo{this->p_}; } +}; + +namespace detail { +// This structure is used to feed sparse tensor values +// information for use with FillSparseTensor() API +// if the data type for the sparse tensor values is numeric +// use data.p_data, otherwise, use data.str pointer to feed +// values. data.str is an array of const char* that are zero terminated. +// number of strings in the array must match shape size. +// For fully sparse tensors use shape {0} and set p_data/str +// to nullptr. +struct OrtSparseValuesParam { + const int64_t* values_shape; + size_t values_shape_len; + union { + const void* p_data; + const char** str; + } data; +}; + +// Provides a way to pass shape in a single +// argument +struct Shape { + const int64_t* shape; + size_t shape_len; +}; + +template +struct ConstValueImpl : Base { + using B = Base; + using B::B; + + /// + /// Obtains a pointer to a user defined data for experimental purposes + /// + template + void GetOpaqueData(const char* domain, const char* type_name, R&) const; ///< Wraps OrtApi::GetOpaqueValue + + bool IsTensor() const; ///< Returns true if Value is a tensor, false for other types like map/sequence/etc + bool HasValue() const; /// < Return true if OrtValue contains data and returns false if the OrtValue is a None + + size_t GetCount() const; // If a non tensor, returns 2 for map and N for sequence, where N is the number of elements + Value GetValue(int index, OrtAllocator* allocator) const; + + /// + /// This API returns a full length of string data contained within either a tensor or a sparse Tensor. + /// For sparse tensor it returns a full length of stored non-empty strings (values). The API is useful + /// for allocating necessary memory and calling GetStringTensorContent(). + /// + /// total length of UTF-8 encoded bytes contained. No zero terminators counted. + size_t GetStringTensorDataLength() const; + + /// + /// The API copies all of the UTF-8 encoded string data contained within a tensor or a sparse tensor + /// into a supplied buffer. Use GetStringTensorDataLength() to find out the length of the buffer to allocate. + /// The user must also allocate offsets buffer with the number of entries equal to that of the contained + /// strings. + /// + /// Strings are always assumed to be on CPU, no X-device copy. + /// + /// user allocated buffer + /// length in bytes of the allocated buffer + /// a pointer to the offsets user allocated buffer + /// count of offsets, must be equal to the number of strings contained. + /// that can be obtained from the shape of the tensor or from GetSparseTensorValuesTypeAndShapeInfo() + /// for sparse tensors + void GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const; + + /// + /// Returns a const typed pointer to the tensor contained data. + /// No type checking is performed, the caller must ensure the type matches the tensor type. + /// + /// + /// const pointer to data, no copies made + template + const R* GetTensorData() const; ///< Wraps OrtApi::GetTensorMutableData /// + + /// + /// Returns a non-typed pointer to a tensor contained data. + /// + /// const pointer to data, no copies made + const void* GetTensorRawData() const; + + /// + /// The API returns type information for data contained in a tensor. For sparse + /// tensors it returns type information for contained non-zero values. + /// It returns dense shape for sparse tensors. + /// + /// TypeInfo + TypeInfo GetTypeInfo() const; + + /// + /// The API returns type information for data contained in a tensor. For sparse + /// tensors it returns type information for contained non-zero values. + /// It returns dense shape for sparse tensors. + /// + /// TensorTypeAndShapeInfo + TensorTypeAndShapeInfo GetTensorTypeAndShapeInfo() const; + + /// + /// This API returns information about the memory allocation used to hold data. + /// + /// Non owning instance of MemoryInfo + ConstMemoryInfo GetTensorMemoryInfo() const; + + /// + /// The API copies UTF-8 encoded bytes for the requested string element + /// contained within a tensor or a sparse tensor into a provided buffer. + /// Use GetStringTensorElementLength() to obtain the length of the buffer to allocate. + /// + /// + /// + /// + void GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const; + + /// + /// Returns string tensor UTF-8 encoded string element. + /// Use of this API is recommended over GetStringTensorElement() that takes void* buffer pointer. + /// + /// + /// std::string + std::string GetStringTensorElement(size_t element_index) const; + + /// + /// The API returns a byte length of UTF-8 encoded string element + /// contained in either a tensor or a spare tensor values. + /// + /// + /// byte length for the specified string element + size_t GetStringTensorElementLength(size_t element_index) const; + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// The API returns the sparse data format this OrtValue holds in a sparse tensor. + /// If the sparse tensor was not fully constructed, i.e. Use*() or Fill*() API were not used + /// the value returned is ORT_SPARSE_UNDEFINED. + /// + /// Format enum + OrtSparseFormat GetSparseFormat() const; + + /// + /// The API returns type and shape information for stored non-zero values of the + /// sparse tensor. Use GetSparseTensorValues() to obtain values buffer pointer. + /// + /// TensorTypeAndShapeInfo values information + TensorTypeAndShapeInfo GetSparseTensorValuesTypeAndShapeInfo() const; + + /// + /// The API returns type and shape information for the specified indices. Each supported + /// indices have their own enum values even if a give format has more than one kind of indices. + /// Use GetSparseTensorIndicesData() to obtain pointer to indices buffer. + /// + /// enum requested + /// type and shape information + TensorTypeAndShapeInfo GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat format) const; + + /// + /// The API retrieves a pointer to the internal indices buffer. The API merely performs + /// a convenience data type casting on the return type pointer. Make sure you are requesting + /// the right type, use GetSparseTensorIndicesTypeShapeInfo(); + /// + /// type to cast to + /// requested indices kind + /// number of indices entries + /// Pinter to the internal sparse tensor buffer containing indices. Do not free this pointer. + template + const R* GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const; + + /// + /// Returns true if the OrtValue contains a sparse tensor + /// + /// + bool IsSparseTensor() const; + + /// + /// The API returns a pointer to an internal buffer of the sparse tensor + /// containing non-zero values. The API merely does casting. Make sure you + /// are requesting the right data type by calling GetSparseTensorValuesTypeAndShapeInfo() + /// first. + /// + /// numeric data types only. Use GetStringTensor*() to retrieve strings. + /// a pointer to the internal values buffer. Do not free this pointer. + template + const R* GetSparseTensorValues() const; + +#endif +}; + +template +struct ValueImpl : ConstValueImpl { + using B = ConstValueImpl; + using B::B; + + /// + /// Returns a non-const typed pointer to an OrtValue/Tensor contained buffer + /// No type checking is performed, the caller must ensure the type matches the tensor type. + /// + /// non-const pointer to data, no copies made + template + R* GetTensorMutableData(); + + /// + /// Returns a non-typed non-const pointer to a tensor contained data. + /// + /// pointer to data, no copies made + void* GetTensorMutableRawData(); + + /// + // Obtain a reference to an element of data at the location specified + /// by the vector of dims. + /// + /// + /// [in] expressed by a vecotr of dimensions offsets + /// + template + R& At(const std::vector& location); + + /// + /// Set all strings at once in a string tensor + /// + /// [in] An array of strings. Each string in this array must be null terminated. + /// [in] Count of strings in s (Must match the size of \p value's tensor shape) + void FillStringTensor(const char* const* s, size_t s_len); + + /// + /// Set a single string in a string tensor + /// + /// [in] A null terminated UTF-8 encoded string + /// [in] Index of the string in the tensor to set + void FillStringTensorElement(const char* s, size_t index); + + /// + /// Allocate if necessary and obtain a pointer to a UTF-8 + /// encoded string element buffer indexed by the flat element index, + /// of the specified length. + /// + /// This API is for advanced usage. It avoids a need to construct + /// an auxiliary array of string pointers, and allows to write data directly + /// (do not zero terminate). + /// + /// + /// + /// a pointer to a writable buffer + char* GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length); + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// Supplies COO format specific indices and marks the contained sparse tensor as being a COO format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// pointer to the user allocated buffer with indices. Use nullptr for fully sparse tensors. + /// number of indices entries. Use 0 for fully sparse tensors + void UseCooIndices(int64_t* indices_data, size_t indices_num); + + /// + /// Supplies CSR format specific indices and marks the contained sparse tensor as being a CSR format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// pointer to the user allocated buffer with inner indices or nullptr for fully sparse tensors + /// number of csr inner indices or 0 for fully sparse tensors + /// pointer to the user allocated buffer with outer indices or nullptr for fully sparse tensors + /// number of csr outer indices or 0 for fully sparse tensors + void UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num); + + /// + /// Supplies BlockSparse format specific indices and marks the contained sparse tensor as being a BlockSparse format tensor. + /// Values are supplied with a CreateSparseTensor() API. The supplied indices are not copied and the user + /// allocated buffers lifespan must eclipse that of the OrtValue. + /// The location of the indices is assumed to be the same as specified by OrtMemoryInfo argument at the creation time. + /// + /// indices shape or a {0} for fully sparse + /// user allocated buffer with indices or nullptr for fully spare tensors + void UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and COO indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information. + /// coo indices buffer or nullptr for fully sparse data + /// number of COO indices or 0 for fully sparse data + void FillSparseTensorCoo(const OrtMemoryInfo* data_mem_info, const OrtSparseValuesParam& values_param, + const int64_t* indices_data, size_t indices_num); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and CSR indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information + /// csr inner indices pointer or nullptr for fully sparse tensors + /// number of csr inner indices or 0 for fully sparse tensors + /// pointer to csr indices data or nullptr for fully sparse tensors + /// number of csr outer indices or 0 + void FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const int64_t* inner_indices_data, size_t inner_indices_num, + const int64_t* outer_indices_data, size_t outer_indices_num); + + /// + /// The API will allocate memory using the allocator instance supplied to the CreateSparseTensor() API + /// and copy the values and BlockSparse indices into it. If data_mem_info specifies that the data is located + /// at difference device than the allocator, a X-device copy will be performed if possible. + /// + /// specified buffer memory description + /// values buffer information + /// indices shape. use {0} for fully sparse tensors + /// pointer to indices data or nullptr for fully sparse tensors + void FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const Shape& indices_shape, + const int32_t* indices_data); + +#endif +}; + +} // namespace detail + +using ConstValue = detail::ConstValueImpl>; +using UnownedValue = detail::ValueImpl>; + +/** \brief Wrapper around ::OrtValue + * + */ +struct Value : detail::ValueImpl { + using Base = detail::ValueImpl; + using Base::Base; + using OrtSparseValuesParam = detail::OrtSparseValuesParam; + using Shape = detail::Shape; + + explicit Value(std::nullptr_t) {} ///< Create an empty Value object, must be assigned a valid one to be used + Value(Value&&) = default; + Value& operator=(Value&&) = default; + + ConstValue GetConst() const { return ConstValue{this->p_}; } + UnownedValue GetUnowned() const { return UnownedValue{this->p_}; } + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. + * \tparam T The numeric datatype. This API is not suitable for strings. + * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param p_data Pointer to the data buffer. + * \param p_data_element_count The number of elements in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + */ + template + static Value CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, + const int64_t* shape, size_t shape_len); + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAsOrtValue. + * + * \param info Memory description of where the p_data buffer resides (CPU vs GPU etc). + * \param p_data Pointer to the data buffer. + * \param p_data_byte_count The number of bytes in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates a tensor with a user supplied buffer. Wraps OrtApi::CreateTensorWithDataAndDeleterAsOrtValue. + * + * \param deleter OrtAllocator that will be used to free the buffer when no longer required. + * \param p_data Pointer to the data buffer. + * \param p_data_byte_count The number of bytes in the data buffer. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates an OrtValue with a tensor using a supplied OrtAllocator. Wraps OrtApi::CreateTensorAsOrtValue. + * This overload will allocate the buffer for the tensor according to the supplied shape and data type. + * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. + * The input data would need to be copied into the allocated buffer. + * This API is not suitable for strings. + * + * \tparam T The numeric datatype. This API is not suitable for strings. + * \param allocator The allocator to use. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + */ + template + static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len); + + /** \brief Creates an OrtValue with a tensor using the supplied OrtAllocator. + * Wraps OrtApi::CreateTensorAsOrtValue. + * The allocated buffer will be owned by the returned OrtValue and will be freed when the OrtValue is released. + * The input data would need to be copied into the allocated buffer. + * This API is not suitable for strings. + * + * \param allocator The allocator to use. + * \param shape Pointer to the tensor shape dimensions. + * \param shape_len The number of tensor shape dimensions. + * \param type The data type. + */ + static Value CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type); + + /** \brief Creates an OrtValue with a Map Onnx type representation. + * The API would ref-count the supplied OrtValues and they will be released + * when the returned OrtValue is released. The caller may release keys and values after the call + * returns. + * + * \param keys an OrtValue containing a tensor with primitive data type keys. + * \param values an OrtValue that may contain a tensor. Ort currently supports only primitive data type values. + */ + static Value CreateMap(const Value& keys, const Value& values); ///< Wraps OrtApi::CreateValue + + /** \brief Creates an OrtValue with a Sequence Onnx type representation. + * The API would ref-count the supplied OrtValues and they will be released + * when the returned OrtValue is released. The caller may release the values after the call + * returns. + * + * \param values a vector of OrtValues that must have the same Onnx value type. + */ + static Value CreateSequence(const std::vector& values); ///< Wraps OrtApi::CreateValue + + /** \brief Creates an OrtValue wrapping an Opaque type. + * This is used for experimental support of non-tensor types. + * + * \tparam T - the type of the value. + * \param domain - zero terminated utf-8 string. Domain of the type. + * \param type_name - zero terminated utf-8 string. Name of the type. + * \param value - the value to be wrapped. + */ + template + static Value CreateOpaque(const char* domain, const char* type_name, const T& value); ///< Wraps OrtApi::CreateOpaqueValue + +#if !defined(DISABLE_SPARSE_TENSORS) + /// + /// This is a simple forwarding method to the other overload that helps deducing + /// data type enum value from the type of the buffer. + /// + /// numeric datatype. This API is not suitable for strings. + /// Memory description where the user buffers reside (CPU vs GPU etc) + /// pointer to the user supplied buffer, use nullptr for fully sparse tensors + /// a would be dense shape of the tensor + /// non zero values shape. Use a single 0 shape for fully sparse tensors. + /// + template + static Value CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, + const Shape& values_shape); + + /// + /// Creates an OrtValue instance containing SparseTensor. This constructs + /// a sparse tensor that makes use of user allocated buffers. It does not make copies + /// of the user provided data and does not modify it. The lifespan of user provided buffers should + /// eclipse the life span of the resulting OrtValue. This call constructs an instance that only contain + /// a pointer to non-zero values. To fully populate the sparse tensor call UseIndices() API below + /// to supply a sparse format specific indices. + /// This API is not suitable for string data. Use CreateSparseTensor() with allocator specified so strings + /// can be properly copied into the allocated buffer. + /// + /// Memory description where the user buffers reside (CPU vs GPU etc) + /// pointer to the user supplied buffer, use nullptr for fully sparse tensors + /// a would be dense shape of the tensor + /// non zero values shape. Use a single 0 shape for fully sparse tensors. + /// data type + /// Ort::Value instance containing SparseTensor + static Value CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, + const Shape& values_shape, ONNXTensorElementDataType type); + + /// + /// This is a simple forwarding method to the below CreateSparseTensor. + /// This helps to specify data type enum in terms of C++ data type. + /// Use CreateSparseTensor + /// + /// numeric data type only. String data enum must be specified explicitly. + /// allocator to use + /// a would be dense shape of the tensor + /// Ort::Value + template + static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape); + + /// + /// Creates an instance of OrtValue containing sparse tensor. The created instance has no data. + /// The data must be supplied by on of the FillSparseTensor() methods that take both non-zero values + /// and indices. The data will be copied into a buffer that would be allocated using the supplied allocator. + /// Use this API to create OrtValues that contain sparse tensors with all supported data types including + /// strings. + /// + /// allocator to use. The allocator lifespan must eclipse that of the resulting OrtValue + /// a would be dense shape of the tensor + /// data type + /// an instance of Ort::Value + static Value CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, ONNXTensorElementDataType type); + +#endif // !defined(DISABLE_SPARSE_TENSORS) +}; + +/// +/// Represents native memory allocation coming from one of the +/// OrtAllocators registered with OnnxRuntime. +/// Use it to wrap an allocation made by an allocator +/// so it can be automatically released when no longer needed. +/// +struct MemoryAllocation { + MemoryAllocation(OrtAllocator* allocator, void* p, size_t size); + ~MemoryAllocation(); + MemoryAllocation(const MemoryAllocation&) = delete; + MemoryAllocation& operator=(const MemoryAllocation&) = delete; + MemoryAllocation(MemoryAllocation&&) noexcept; + MemoryAllocation& operator=(MemoryAllocation&&) noexcept; + + void* get() { return p_; } + size_t size() const { return size_; } + + private: + OrtAllocator* allocator_; + void* p_; + size_t size_; +}; + +namespace detail { +template +struct AllocatorImpl : Base { + using B = Base; + using B::B; + + void* Alloc(size_t size); + MemoryAllocation GetAllocation(size_t size); + void Free(void* p); + ConstMemoryInfo GetInfo() const; +}; + +} // namespace detail + +/** \brief Wrapper around ::OrtAllocator default instance that is owned by Onnxruntime + * + */ +struct AllocatorWithDefaultOptions : detail::AllocatorImpl> { + explicit AllocatorWithDefaultOptions(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance + AllocatorWithDefaultOptions(); +}; + +/** \brief Wrapper around ::OrtAllocator + * + */ +struct Allocator : detail::AllocatorImpl { + explicit Allocator(std::nullptr_t) {} ///< Convenience to create a class member and then replace with an instance + Allocator(const Session& session, const OrtMemoryInfo*); +}; + +using UnownedAllocator = detail::AllocatorImpl>; + +namespace detail { +namespace binding_utils { +// Bring these out of template +std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator*); +std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator*); +} // namespace binding_utils + +template +struct ConstIoBindingImpl : Base { + using B = Base; + using B::B; + + std::vector GetOutputNames() const; + std::vector GetOutputNames(OrtAllocator*) const; + std::vector GetOutputValues() const; + std::vector GetOutputValues(OrtAllocator*) const; +}; + +template +struct IoBindingImpl : ConstIoBindingImpl { + using B = ConstIoBindingImpl; + using B::B; + + void BindInput(const char* name, const Value&); + void BindOutput(const char* name, const Value&); + void BindOutput(const char* name, const OrtMemoryInfo*); + void ClearBoundInputs(); + void ClearBoundOutputs(); + void SynchronizeInputs(); + void SynchronizeOutputs(); +}; + +} // namespace detail + +using ConstIoBinding = detail::ConstIoBindingImpl>; +using UnownedIoBinding = detail::IoBindingImpl>; + +/** \brief Wrapper around ::OrtIoBinding + * + */ +struct IoBinding : detail::IoBindingImpl { + explicit IoBinding(std::nullptr_t) {} ///< Create an empty object for convenience. Sometimes, we want to initialize members later. + explicit IoBinding(Session& session); + ConstIoBinding GetConst() const { return ConstIoBinding{this->p_}; } + UnownedIoBinding GetUnowned() const { return UnownedIoBinding{this->p_}; } +}; + +/*! \struct Ort::ArenaCfg + * \brief it is a structure that represents the configuration of an arena based allocator + * \details Please see docs/C_API.md for details + */ +struct ArenaCfg : detail::Base { + explicit ArenaCfg(std::nullptr_t) {} ///< Create an empty ArenaCfg object, must be assigned a valid one to be used + /** + * Wraps OrtApi::CreateArenaCfg + * \param max_mem - use 0 to allow ORT to choose the default + * \param arena_extend_strategy - use -1 to allow ORT to choose the default, 0 = kNextPowerOfTwo, 1 = kSameAsRequested + * \param initial_chunk_size_bytes - use -1 to allow ORT to choose the default + * \param max_dead_bytes_per_chunk - use -1 to allow ORT to choose the default + * See docs/C_API.md for details on what the following parameters mean and how to choose these values + */ + ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk); +}; + +// +// Custom OPs (only needed to implement custom OPs) +// + +/// +/// This struct provides life time management for custom op attribute +/// +struct OpAttr : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit OpAttr(std::nullptr_t) {} + OpAttr(const char* name, const void* data, int len, OrtOpAttrType type); +}; + +/** + * Macro that logs a message using the provided logger. Throws an exception if OrtApi::Logger_LogMessage fails. + * Example: ORT_CXX_LOG(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param message A null-terminated UTF-8 message to log. + */ +#define ORT_CXX_LOG(logger, message_severity, message) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + Ort::ThrowOnError(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), message)); \ + } \ + } while (false) + +/** + * Macro that logs a message using the provided logger. Can be used in noexcept code since errors are silently ignored. + * Example: ORT_CXX_LOG_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log a message"); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param message A null-terminated UTF-8 message to log. + */ +#define ORT_CXX_LOG_NOEXCEPT(logger, message_severity, message) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + static_cast(logger.LogMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), message)); \ + } \ + } while (false) + +/** + * Macro that logs a printf-like formatted message using the provided logger. Throws an exception if + * OrtApi::Logger_LogMessage fails or if a formatting error occurs. + * Example: ORT_CXX_LOGF(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param ... Zero or more variadic arguments referenced by the format string. + */ +#define ORT_CXX_LOGF(logger, message_severity, /*format,*/...) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + Ort::ThrowOnError(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), __VA_ARGS__)); \ + } \ + } while (false) + +/** + * Macro that logs a printf-like formatted message using the provided logger. Can be used in noexcept code since errors + * are silently ignored. + * Example: ORT_CXX_LOGF_NOEXCEPT(logger, ORT_LOGGING_LEVEL_INFO, "Log an int: %d", 12); + * + * \param logger The Ort::Logger instance to use. Must be a value or reference. + * \param message_severity The logging severity level of the message. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param ... Zero or more variadic arguments referenced by the format string. + */ +#define ORT_CXX_LOGF_NOEXCEPT(logger, message_severity, /*format,*/...) \ + do { \ + if (message_severity >= logger.GetLoggingSeverityLevel()) { \ + static_cast(logger.LogFormattedMessage(message_severity, ORT_FILE, __LINE__, \ + static_cast(__FUNCTION__), __VA_ARGS__)); \ + } \ + } while (false) + +/// +/// This class represents an ONNX Runtime logger that can be used to log information with an +/// associated severity level and source code location (file path, line number, function name). +/// +/// A Logger can be obtained from within custom operators by calling Ort::KernelInfo::GetLogger(). +/// Instances of Ort::Logger are the size of two pointers and can be passed by value. +/// +/// Use the ORT_CXX_LOG macros to ensure the source code location is set properly from the callsite +/// and to take advantage of a cached logging severity level that can bypass calls to the underlying C API. +/// +struct Logger { + /** + * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. + */ + Logger() = default; + + /** + * Creates an empty Ort::Logger. Must be initialized from a valid Ort::Logger before use. + */ + explicit Logger(std::nullptr_t) {} + + /** + * Creates a logger from an ::OrtLogger instance. Caches the logger's current severity level by calling + * OrtApi::Logger_GetLoggingSeverityLevel. Throws an exception if OrtApi::Logger_GetLoggingSeverityLevel fails. + * + * \param logger The ::OrtLogger to wrap. + */ + explicit Logger(const OrtLogger* logger); + + ~Logger() = default; + + Logger(const Logger&) = default; + Logger& operator=(const Logger&) = default; + + Logger(Logger&& v) noexcept = default; + Logger& operator=(Logger&& v) noexcept = default; + + /** + * Returns the logger's current severity level from the cached member. + * + * \return The current ::OrtLoggingLevel. + */ + OrtLoggingLevel GetLoggingSeverityLevel() const noexcept; + + /** + * Logs the provided message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOG or ORT_CXX_LOG_NOEXCEPT + * macros to properly set the source code location and to use the cached severity level to potentially bypass + * calls to the underlying C API. + * + * \param log_severity_level The message's logging severity level. + * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * \param message The message to log. + * \return A Ort::Status value to indicate error or success. + */ + Status LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* message) const noexcept; + + /** + * Logs a printf-like formatted message via OrtApi::Logger_LogMessage. Use the ORT_CXX_LOGF or ORT_CXX_LOGF_NOEXCEPT + * macros to properly set the source code location and to use the cached severity level to potentially bypass + * calls to the underlying C API. Returns an error status if a formatting error occurs. + * + * \param log_severity_level The message's logging severity level. + * \param file_path The filepath of the file in which the message is logged. Usually the value of ORT_FILE. + * \param line_number The file line number in which the message is logged. Usually the value of __LINE__. + * \param func_name The name of the function in which the message is logged. Usually the value of __FUNCTION__. + * \param format A null-terminated UTF-8 format string forwarded to a printf-like function. + * Refer to https://en.cppreference.com/w/cpp/io/c/fprintf for information on valid formats. + * \param args Zero or more variadic arguments referenced by the format string. + * \return A Ort::Status value to indicate error or success. + */ + template + Status LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* format, Args&&... args) const noexcept; + + private: + const OrtLogger* logger_{}; + OrtLoggingLevel cached_severity_level_{}; +}; + +/// +/// This class wraps a raw pointer OrtKernelContext* that is being passed +/// to the custom kernel Compute() method. Use it to safely access context +/// attributes, input and output parameters with exception safety guarantees. +/// See usage example in onnxruntime/test/testdata/custom_op_library/custom_op_library.cc +/// +struct KernelContext { + explicit KernelContext(OrtKernelContext* context); + size_t GetInputCount() const; + size_t GetOutputCount() const; + // If input is optional and is not present, the method returns an empty ConstValue + // which can be compared to nullptr. + ConstValue GetInput(size_t index) const; + // If output is optional and is not present, the method returns an empty UnownedValue + // which can be compared to nullptr. + UnownedValue GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const; + UnownedValue GetOutput(size_t index, const std::vector& dims) const; + void* GetGPUComputeStream() const; + Logger GetLogger() const; + OrtAllocator* GetAllocator(const OrtMemoryInfo& memory_info) const; + OrtKernelContext* GetOrtKernelContext() const { return ctx_; } + void ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const; + + private: + OrtKernelContext* ctx_; +}; + +struct KernelInfo; + +namespace detail { +namespace attr_utils { +void GetAttr(const OrtKernelInfo* p, const char* name, float&); +void GetAttr(const OrtKernelInfo* p, const char* name, int64_t&); +void GetAttr(const OrtKernelInfo* p, const char* name, std::string&); +void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); +void GetAttrs(const OrtKernelInfo* p, const char* name, std::vector&); +} // namespace attr_utils + +template +struct KernelInfoImpl : Base { + using B = Base; + using B::B; + + KernelInfo Copy() const; + + template // R is only implemented for float, int64_t, and string + R GetAttribute(const char* name) const { + R val; + attr_utils::GetAttr(this->p_, name, val); + return val; + } + + template // R is only implemented for std::vector, std::vector + std::vector GetAttributes(const char* name) const { + std::vector result; + attr_utils::GetAttrs(this->p_, name, result); + return result; + } + + Value GetTensorAttribute(const char* name, OrtAllocator* allocator) const; + + size_t GetInputCount() const; + size_t GetOutputCount() const; + + std::string GetInputName(size_t index) const; + std::string GetOutputName(size_t index) const; + + TypeInfo GetInputTypeInfo(size_t index) const; + TypeInfo GetOutputTypeInfo(size_t index) const; + + ConstValue GetTensorConstantInput(size_t index, int* is_constant) const; + + std::string GetNodeName() const; + Logger GetLogger() const; +}; + +} // namespace detail + +using ConstKernelInfo = detail::KernelInfoImpl>; + +/// +/// This struct owns the OrtKernInfo* pointer when a copy is made. +/// For convenient wrapping of OrtKernelInfo* passed to kernel constructor +/// and query attributes, warp the pointer with Ort::Unowned instance +/// so it does not destroy the pointer the kernel does not own. +/// +struct KernelInfo : detail::KernelInfoImpl { + using Base = detail::KernelInfoImpl; + using Base::Base; + explicit KernelInfo(std::nullptr_t) {} ///< Create an empty instance to initialize later + explicit KernelInfo(OrtKernelInfo* info); ///< Take ownership of the instance + ConstKernelInfo GetConst() const { return ConstKernelInfo{this->p_}; } +}; + +/// +/// Create and own custom defined operation. +/// +struct Op : detail::Base { + using Base = detail::Base; + using Base::Base; + + explicit Op(std::nullptr_t) {} ///< Create an empty Operator object, must be assigned a valid one to be used + + explicit Op(OrtOp*); ///< Take ownership of the OrtOp + + static Op Create(const OrtKernelInfo* info, const char* op_name, const char* domain, + int version, const char** type_constraint_names, + const ONNXTensorElementDataType* type_constraint_values, + size_t type_constraint_count, + const OpAttr* attr_values, + size_t attr_count, + size_t input_count, size_t output_count); + + void Invoke(const OrtKernelContext* context, + const Value* input_values, + size_t input_count, + Value* output_values, + size_t output_count); + + // For easier refactoring + void Invoke(const OrtKernelContext* context, + const OrtValue* const* input_values, + size_t input_count, + OrtValue* const* output_values, + size_t output_count); +}; + +/// +/// Provide access to per-node attributes and input shapes, so one could compute and set output shapes. +/// +struct ShapeInferContext { + struct SymbolicInteger { + SymbolicInteger(int64_t i) : i_(i), is_int_(true) {}; + SymbolicInteger(const char* s) : s_(s), is_int_(false) {}; + SymbolicInteger(const SymbolicInteger&) = default; + SymbolicInteger(SymbolicInteger&&) = default; + + SymbolicInteger& operator=(const SymbolicInteger&) = default; + SymbolicInteger& operator=(SymbolicInteger&&) = default; + + bool operator==(const SymbolicInteger& dim) const { + if (is_int_ == dim.is_int_) { + if (is_int_) { + return i_ == dim.i_; + } else { + return std::string{s_} == std::string{dim.s_}; + } + } + return false; + } + + bool IsInt() const { return is_int_; } + int64_t AsInt() const { return i_; } + const char* AsSym() const { return s_; } + + static constexpr int INVALID_INT_DIM = -2; + + private: + union { + int64_t i_; + const char* s_; + }; + bool is_int_; + }; + + using Shape = std::vector; + + ShapeInferContext(const OrtApi* ort_api, OrtShapeInferContext* ctx); + + const Shape& GetInputShape(size_t indice) const { return input_shapes_.at(indice); } + + size_t GetInputCount() const { return input_shapes_.size(); } + + Status SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); + + int64_t GetAttrInt(const char* attr_name); + + using Ints = std::vector; + Ints GetAttrInts(const char* attr_name); + + float GetAttrFloat(const char* attr_name); + + using Floats = std::vector; + Floats GetAttrFloats(const char* attr_name); + + std::string GetAttrString(const char* attr_name); + + using Strings = std::vector; + Strings GetAttrStrings(const char* attr_name); + + private: + const OrtOpAttr* GetAttrHdl(const char* attr_name) const; + const OrtApi* ort_api_; + OrtShapeInferContext* ctx_; + std::vector input_shapes_; +}; + +using ShapeInferFn = Ort::Status (*)(Ort::ShapeInferContext&); + +#define MAX_CUSTOM_OP_END_VER (1UL << 31) - 1 + +template +struct CustomOpBase : OrtCustomOp { + CustomOpBase() { + OrtCustomOp::version = ORT_API_VERSION; + OrtCustomOp::GetName = [](const OrtCustomOp* this_) { return static_cast(this_)->GetName(); }; + + OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* this_) { return static_cast(this_)->GetExecutionProviderType(); }; + + OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetInputTypeCount(); }; + OrtCustomOp::GetInputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputType(index); }; + OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputMemoryType(index); }; + + OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* this_) { return static_cast(this_)->GetOutputTypeCount(); }; + OrtCustomOp::GetOutputType = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputType(index); }; + +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(push) +#pragma warning(disable : 26409) +#endif + OrtCustomOp::KernelDestroy = [](void* op_kernel) { delete static_cast(op_kernel); }; +#if defined(_MSC_VER) && !defined(__clang__) +#pragma warning(pop) +#endif + OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetInputCharacteristic(index); }; + OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* this_, size_t index) { return static_cast(this_)->GetOutputCharacteristic(index); }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicInputMinArity(); }; + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicInputHomogeneity()); }; + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp* this_) { return static_cast(this_)->GetVariadicOutputMinArity(); }; + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp* this_) { return static_cast(static_cast(this_)->GetVariadicOutputHomogeneity()); }; +#ifdef __cpp_if_constexpr + if constexpr (WithStatus) { +#else + if (WithStatus) { +#endif + OrtCustomOp::CreateKernelV2 = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info, void** op_kernel) -> OrtStatusPtr { + return static_cast(this_)->CreateKernelV2(*api, info, op_kernel); + }; + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + return static_cast(op_kernel)->ComputeV2(context); + }; + } else { + OrtCustomOp::CreateKernelV2 = nullptr; + OrtCustomOp::KernelComputeV2 = nullptr; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* api, const OrtKernelInfo* info) { return static_cast(this_)->CreateKernel(*api, info); }; + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + static_cast(op_kernel)->Compute(context); + }; + } + + SetShapeInferFn(0); + + OrtCustomOp::GetStartVersion = [](const OrtCustomOp* this_) { + return static_cast(this_)->start_ver_; + }; + + OrtCustomOp::GetEndVersion = [](const OrtCustomOp* this_) { + return static_cast(this_)->end_ver_; + }; + + OrtCustomOp::GetMayInplace = nullptr; + OrtCustomOp::ReleaseMayInplace = nullptr; + OrtCustomOp::GetAliasMap = nullptr; + OrtCustomOp::ReleaseAliasMap = nullptr; + } + + // Default implementation of GetExecutionProviderType that returns nullptr to default to the CPU provider + const char* GetExecutionProviderType() const { return nullptr; } + + // Default implementations of GetInputCharacteristic() and GetOutputCharacteristic() below + // (inputs and outputs are required by default) + OrtCustomOpInputOutputCharacteristic GetInputCharacteristic(size_t /*index*/) const { + return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; + } + + OrtCustomOpInputOutputCharacteristic GetOutputCharacteristic(size_t /*index*/) const { + return OrtCustomOpInputOutputCharacteristic::INPUT_OUTPUT_REQUIRED; + } + + // Default implemention of GetInputMemoryType() that returns OrtMemTypeDefault + OrtMemType GetInputMemoryType(size_t /*index*/) const { + return OrtMemTypeDefault; + } + + // Default implementation of GetVariadicInputMinArity() returns 1 to specify that a variadic input + // should expect at least 1 argument. + int GetVariadicInputMinArity() const { + return 1; + } + + // Default implementation of GetVariadicInputHomegeneity() returns true to specify that all arguments + // to a variadic input should be of the same type. + bool GetVariadicInputHomogeneity() const { + return true; + } + + // Default implementation of GetVariadicOutputMinArity() returns 1 to specify that a variadic output + // should produce at least 1 output value. + int GetVariadicOutputMinArity() const { + return 1; + } + + // Default implementation of GetVariadicOutputHomegeneity() returns true to specify that all output values + // produced by a variadic output should be of the same type. + bool GetVariadicOutputHomogeneity() const { + return true; + } + + // Declare list of session config entries used by this Custom Op. + // Implement this function in order to get configs from CustomOpBase::GetSessionConfigs(). + // This default implementation returns an empty vector of config entries. + std::vector GetSessionConfigKeys() const { + return std::vector{}; + } + + // Ort::CustomOpBase derived class should provide the following static method with the type/shape inferencing + // implementation if needed: + // static OrtStatusPtr InferOutputShape(Ort::ShapeInferContext& context) + template + decltype(&C::InferOutputShape) SetShapeInferFn(decltype(&C::InferOutputShape)) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + ShapeInferContext ctx(&GetApi(), ort_ctx); + return C::InferOutputShape(ctx); + }; + return {}; + } + + template + void SetShapeInferFn(...) { + OrtCustomOp::InferOutputShapeFn = {}; + } + + protected: + // Helper function that returns a map of session config entries specified by CustomOpBase::GetSessionConfigKeys. + void GetSessionConfigs(std::unordered_map& out, ConstSessionOptions options) const; + + int start_ver_ = 1; + int end_ver_ = MAX_CUSTOM_OP_END_VER; +}; + +namespace detail { +template +struct ValueInfoImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + + std::string Name() const; + ConstTypeInfo TypeInfo() const; +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstValueInfo = detail::ValueInfoImpl>; + +/** \brief Wrapper around ::OrtValueInfo + * + */ +struct ValueInfo : detail::ValueInfoImpl { + explicit ValueInfo(std::nullptr_t) {} ///< No instance is created + /// Take ownership of a pointer created by C API + explicit ValueInfo(OrtValueInfo* p) : ValueInfoImpl{p} {} + + // Create ValueInfo for a tensor + explicit ValueInfo(const std::string& name, const ConstTypeInfo& type_info); + + ConstValueInfo GetConst() const { return ConstValueInfo{this->p_}; } +}; + +namespace detail { +template +struct NodeImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; +}; +} // namespace detail + +/** \brief Wrapper around ::OrtNode + * + */ +struct Node : detail::NodeImpl { + explicit Node(std::nullptr_t) {} ///< No instance is created + explicit Node(OrtNode* p) : NodeImpl{p} {} ///< Take ownership of a pointer created by C API + +#if !defined(ORT_MINIMAL_BUILD) + Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names); + + /// + /// Wraps CreateNode. Node takes ownership of attributes on success and updates the OpAttr in `attributes` to do so. + /// + Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes); + + private: + static void Init(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes, + OrtNode*& node); +#endif // !defined(ORT_MINIMAL_BUILD) +}; + +namespace detail { +template +struct GraphImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + +#if !defined(ORT_MINIMAL_BUILD) + void SetInputs(std::vector& inputs); + void SetOutputs(std::vector& outputs); + void AddInitializer(const std::string& name, Value& initializer, bool data_is_external); // Graph takes ownership of Value + void AddNode(Node& node); // Graph takes ownership of Node +#endif // !defined(ORT_MINIMAL_BUILD) +}; +} // namespace detail + +/** \brief Wrapper around ::OrtGraph + * + */ +struct Graph : detail::GraphImpl { + explicit Graph(std::nullptr_t) {} ///< No instance is created + explicit Graph(OrtGraph* p) : GraphImpl{p} {} ///< Take ownership of a pointer created by C API +#if !defined(ORT_MINIMAL_BUILD) + Graph(); +#endif +}; + +namespace detail { +template +struct ModelImpl : Ort::detail::Base { + using B = Ort::detail::Base; + using B::B; + +#if !defined(ORT_MINIMAL_BUILD) + void AddGraph(Graph& graph); +#endif +}; +} // namespace detail + +// Const object holder that does not own the underlying object +using ConstModel = detail::ModelImpl>; + +/** \brief Wrapper around ::OrtModel + * + */ +struct Model : detail::ModelImpl { + using DomainOpsetPair = std::pair; + + explicit Model(std::nullptr_t) {} ///< No instance is created + explicit Model(OrtModel* p) : ModelImpl{p} {} ///< Take ownership of a pointer created by C API + +#if !defined(ORT_MINIMAL_BUILD) + explicit Model(const std::vector& opsets); +#endif + + ConstModel GetConst() const { return ConstModel{this->p_}; } +}; +} // namespace Ort +#include "onnxruntime_cxx_inline.h" diff --git a/3rdParty/ONNX/onnxruntime_cxx_inline.h b/3rdParty/ONNX/onnxruntime_cxx_inline.h index 64cd09f93d..94ad2118fa 100644 --- a/3rdParty/ONNX/onnxruntime_cxx_inline.h +++ b/3rdParty/ONNX/onnxruntime_cxx_inline.h @@ -1,2778 +1,2778 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead. -// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead. -// -// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter -// the main C++ file with implementation details. - -#include -#include -#include -#include -#include -#include - -// Convert OrtStatus to Ort::Status and return -// instead of throwing -#define ORT_CXX_RETURN_ON_API_FAIL(expression) \ - { \ - auto ort_status = (expression); \ - if (ort_status) { \ - return Ort::Status(ort_status); \ - } \ - } - -#ifdef __cpp_if_constexpr -#define ORT_CXX_IF_CONSTEXPR if constexpr -#else -#define ORT_CXX_IF_CONSTEXPR if -#endif - -namespace Ort { - -namespace detail { -inline void ThrowStatus(const Status& st) { - std::string error_message = st.GetErrorMessage(); - OrtErrorCode error_code = st.GetErrorCode(); - ORT_CXX_API_THROW(std::move(error_message), error_code); -} -} // namespace detail - -inline void ThrowOnError(OrtStatus* ort_status) { - if (ort_status) { - Ort::Status st(ort_status); - detail::ThrowStatus(st); - } -} - -inline void ThrowOnError(const Status& st) { - if (st) { - detail::ThrowStatus(st); - } -} - -inline Status::Status(OrtStatus* status) noexcept : detail::Base{status} { -} - -inline Status::Status(const std::exception& e) noexcept { - p_ = GetApi().CreateStatus(ORT_FAIL, e.what()); -} - -inline Status::Status(const Exception& e) noexcept { - p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what()); -} - -inline Status::Status(const char* message, OrtErrorCode code) noexcept { - p_ = GetApi().CreateStatus(code, message); -} - -inline std::string Status::GetErrorMessage() const { - std::string message(GetApi().GetErrorMessage(p_)); - return message; -} - -inline OrtErrorCode Status::GetErrorCode() const { - return GetApi().GetErrorCode(p_); -} - -inline bool Status::IsOK() const noexcept { - return (p_ == nullptr); -} - -// This template converts a C++ type into it's ONNXTensorElementDataType -template -struct TypeToTensorType; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL; -}; - -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2; -}; -template <> -struct TypeToTensorType { - static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ; -}; - -inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is not equal to anything, including itself. - return false; - } - return val == rhs.val; -} - -inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is unordered with respect to everything, including itself. - return false; - } - - const bool left_is_negative = IsNegative(); - if (left_is_negative != rhs.IsNegative()) { - // When the signs of left and right differ, we know that left is less than right if it is - // the negative value. The exception to this is if both values are zero, in which case IEEE - // says they should be equal, even if the signs differ. - return left_is_negative && !AreZero(*this, rhs); - } - return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); -} - -inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size) - : allocator_(allocator), p_(p), size_(size) { -} - -inline MemoryAllocation::~MemoryAllocation() { - if (p_ != nullptr) { - // We do not throw out of destructor - auto ret = GetApi().AllocatorFree(allocator_, p_); - static_cast(ret); - } -} - -inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) { - *this = std::move(o); -} - -inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept { - OrtAllocator* alloc = nullptr; - void* p = nullptr; - size_t sz = 0; - - // Swap out this - std::swap(alloc, allocator_); - std::swap(p, p_); - std::swap(sz, size_); - - // Swap with incoming - std::swap(allocator_, o.allocator_); - std::swap(p_, o.p_); - std::swap(size_, o.size_); - - // Destroy this instance if needed - MemoryAllocation this_alloc(alloc, p, sz); - return *this; -} - -namespace detail { - -template -inline void* AllocatorImpl::Alloc(size_t size) { - void* out; - ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); - return out; -} - -template -inline MemoryAllocation AllocatorImpl::GetAllocation(size_t size) { - void* out; - ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); - MemoryAllocation result(this->p_, out, size); - return result; -} - -template -inline void AllocatorImpl::Free(void* p) { - ThrowOnError(GetApi().AllocatorFree(this->p_, p)); -} - -template -inline ConstMemoryInfo AllocatorImpl::GetInfo() const { - const OrtMemoryInfo* out; - ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out)); - return ConstMemoryInfo{out}; -} - -} // namespace detail - -inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() { - ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_)); -} - -inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) { - ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_)); -} - -namespace detail { - -template -inline std::string MemoryInfoImpl::GetAllocatorName() const { - const char* name = nullptr; - ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name)); - return std::string(name); -} - -template -inline OrtAllocatorType MemoryInfoImpl::GetAllocatorType() const { - OrtAllocatorType type; - ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type)); - return type; -} - -template -inline int MemoryInfoImpl::GetDeviceId() const { - int id = 0; - ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id)); - return id; -} - -template -inline OrtMemoryInfoDeviceType MemoryInfoImpl::GetDeviceType() const { - OrtMemoryInfoDeviceType type; - GetApi().MemoryInfoGetDeviceType(this->p_, &type); - return type; -} - -template -inline OrtMemType MemoryInfoImpl::GetMemoryType() const { - OrtMemType type; - ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type)); - return type; -} - -template -template -inline bool MemoryInfoImpl::operator==(const MemoryInfoImpl& o) const { - int comp_result = 0; - ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result)); - return comp_result == 0; -} - -} // namespace detail - -inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) { - OrtMemoryInfo* p; - ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p)); - return MemoryInfo(p); -} - -inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) { - ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_)); -} - -namespace detail { -template -inline std::vector ConstIoBindingImpl::GetOutputNames() const { - AllocatorWithDefaultOptions allocator; - return binding_utils::GetOutputNamesHelper(this->p_, allocator); -} - -template -inline std::vector ConstIoBindingImpl::GetOutputNames(OrtAllocator* allocator) const { - return binding_utils::GetOutputNamesHelper(this->p_, allocator); -} - -template -inline std::vector ConstIoBindingImpl::GetOutputValues() const { - AllocatorWithDefaultOptions allocator; - return binding_utils::GetOutputValuesHelper(this->p_, allocator); -} - -template -inline std::vector ConstIoBindingImpl::GetOutputValues(OrtAllocator* allocator) const { - return binding_utils::GetOutputValuesHelper(this->p_, allocator); -} - -template -inline void IoBindingImpl::BindInput(const char* name, const Value& value) { - ThrowOnError(GetApi().BindInput(this->p_, name, value)); -} - -template -inline void IoBindingImpl::BindOutput(const char* name, const Value& value) { - ThrowOnError(GetApi().BindOutput(this->p_, name, value)); -} - -template -inline void IoBindingImpl::BindOutput(const char* name, const OrtMemoryInfo* mem_info) { - ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info)); -} - -template -inline void IoBindingImpl::ClearBoundInputs() { - GetApi().ClearBoundInputs(this->p_); -} - -template -inline void IoBindingImpl::ClearBoundOutputs() { - GetApi().ClearBoundOutputs(this->p_); -} - -template -inline void IoBindingImpl::SynchronizeInputs() { - ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_)); -} - -template -inline void IoBindingImpl::SynchronizeOutputs() { - ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_)); -} - -namespace binding_utils { -inline std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { - std::vector result; - auto free_fn = detail::AllocatedFree(allocator); - using Ptr = std::unique_ptr; - - char* buffer = nullptr; - size_t* lengths = nullptr; - size_t count = 0; - ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count)); - - if (count == 0) { - return result; - } - - Ptr buffer_g(buffer, free_fn); - Ptr lengths_g(lengths, free_fn); - - result.reserve(count); - for (size_t i = 0; i < count; ++i) { - auto sz = *lengths; - result.emplace_back(buffer, sz); - buffer += sz; - ++lengths; - } - return result; -} - -inline std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { - std::vector result; - size_t owned = 0; - size_t output_count = 0; - // Lambda to release the buffer when no longer needed and - // make sure that we destroy all instances on exception - auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) { - if (buffer) { - while (owned < output_count) { - auto* p = buffer + owned++; - GetApi().ReleaseValue(*p); - } - allocator->Free(allocator, buffer); - } - }; - using Ptr = std::unique_ptr; - - OrtValue** output_buffer = nullptr; - ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count)); - if (output_count == 0) { - return result; - } - - Ptr buffer_g(output_buffer, free_fn); - - result.reserve(output_count); - for (size_t i = 0; i < output_count; ++i) { - result.emplace_back(output_buffer[i]); - ++owned; - } - return result; -} - -} // namespace binding_utils -} // namespace detail - -inline IoBinding::IoBinding(Session& session) { - ThrowOnError(GetApi().CreateIoBinding(session, &this->p_)); -} - -inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) { - ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_)); -} - -inline ThreadingOptions::ThreadingOptions() { - ThrowOnError(GetApi().CreateThreadingOptions(&p_)); -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) { - ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) { - ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) { - ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() { - ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { - ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { - ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options)); - return *this; -} - -inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { - ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn)); - return *this; -} - -namespace detail { -template -inline const char* KeyValuePairsImpl::GetValue(const char* key) const { - return GetApi().GetKeyValue(this->p_, key); -} - -template -inline std::unordered_map KeyValuePairsImpl::GetKeyValuePairs() const { - std::unordered_map out; - - size_t num_pairs = 0; - const char* const* keys = nullptr; - const char* const* values = nullptr; - GetApi().GetKeyValuePairs(this->p_, &keys, &values, &num_pairs); - if (num_pairs > 0) { - out.reserve(num_pairs); - for (size_t i = 0; i < num_pairs; ++i) { - out.emplace(keys[i], values[i]); - } - } - - return out; -} - -template -inline void KeyValuePairsImpl::GetKeyValuePairs(std::vector& keys, - std::vector& values) const { - keys.clear(); - values.clear(); - - size_t num_pairs = 0; - const char* const* keys_ptr = nullptr; - const char* const* values_ptr = nullptr; - GetApi().GetKeyValuePairs(this->p_, &keys_ptr, &values_ptr, &num_pairs); - if (num_pairs > 0) { - keys.resize(num_pairs); - values.resize(num_pairs); - std::copy(keys_ptr, keys_ptr + num_pairs, keys.begin()); - std::copy(values_ptr, values_ptr + num_pairs, values.begin()); - } -} -} // namespace detail - -inline KeyValuePairs::KeyValuePairs() { - GetApi().CreateKeyValuePairs(&p_); -} - -inline KeyValuePairs::KeyValuePairs(const std::unordered_map& kv_pairs) { - GetApi().CreateKeyValuePairs(&p_); - for (const auto& kv : kv_pairs) { - GetApi().AddKeyValuePair(this->p_, kv.first.c_str(), kv.second.c_str()); - } -} - -inline void KeyValuePairs::Add(const char* key, const char* value) { - GetApi().AddKeyValuePair(this->p_, key, value); -} - -inline void KeyValuePairs::Remove(const char* key) { - GetApi().RemoveKeyValuePair(this->p_, key); -} - -namespace detail { -template -inline OrtHardwareDeviceType HardwareDeviceImpl::Type() const { - return GetApi().HardwareDevice_Type(this->p_); -} - -template -inline uint32_t HardwareDeviceImpl::VendorId() const { - return GetApi().HardwareDevice_VendorId(this->p_); -} - -template -inline uint32_t HardwareDeviceImpl::DeviceId() const { - return GetApi().HardwareDevice_DeviceId(this->p_); -} - -template -inline const char* HardwareDeviceImpl::Vendor() const { - return GetApi().HardwareDevice_Vendor(this->p_); -} - -template -inline ConstKeyValuePairs HardwareDeviceImpl::Metadata() const { - return ConstKeyValuePairs{GetApi().HardwareDevice_Metadata(this->p_)}; -} - -template -inline const char* EpDeviceImpl::EpName() const { - return GetApi().EpDevice_EpName(this->p_); -} - -template -inline const char* EpDeviceImpl::EpVendor() const { - return GetApi().EpDevice_EpVendor(this->p_); -} - -template -inline ConstKeyValuePairs EpDeviceImpl::EpMetadata() const { - return ConstKeyValuePairs(GetApi().EpDevice_EpMetadata(this->p_)); -} - -template -inline ConstKeyValuePairs EpDeviceImpl::EpOptions() const { - return ConstKeyValuePairs(GetApi().EpDevice_EpOptions(this->p_)); -} - -template -inline ConstHardwareDevice EpDeviceImpl::Device() const { - return ConstHardwareDevice(GetApi().EpDevice_Device(this->p_)); -} -} // namespace detail - -inline EpDevice::EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, - ConstKeyValuePairs ep_metadata, ConstKeyValuePairs ep_options) { - ThrowOnError(GetEpApi().CreateEpDevice(&ep_factory, hardware_device, ep_metadata, ep_options, &p_)); -} - -inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) { - ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) { - ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) { - ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, - OrtLoggingLevel logging_level, _In_ const char* logid) { - ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_)); - if (strcmp(logid, "onnxruntime-node") == 0) { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); - } else { - ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); - } -} - -inline Env& Env::EnableTelemetryEvents() { - ThrowOnError(GetApi().EnableTelemetryEvents(p_)); - return *this; -} - -inline Env& Env::DisableTelemetryEvents() { - ThrowOnError(GetApi().DisableTelemetryEvents(p_)); - return *this; -} - -inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) { - ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level)); - return *this; -} - -inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) { - ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg)); - return *this; -} - -inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg) { - std::vector keys, values; - auto num_entries = options.size(); - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - for (const auto& entry : options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries)); - return *this; -} - -inline Env& Env::RegisterExecutionProviderLibrary(const char* registration_name, - const std::basic_string& path) { - ThrowOnError(GetApi().RegisterExecutionProviderLibrary(p_, registration_name, path.c_str())); - return *this; -} - -inline Env& Env::UnregisterExecutionProviderLibrary(const char* registration_name) { - ThrowOnError(GetApi().UnregisterExecutionProviderLibrary(p_, registration_name)); - return *this; -} - -inline std::vector Env::GetEpDevices() const { - size_t num_devices = 0; - const OrtEpDevice* const* device_ptrs = nullptr; - ThrowOnError(GetApi().GetEpDevices(p_, &device_ptrs, &num_devices)); - - std::vector devices; - if (num_devices > 0) { - devices.reserve(num_devices); - for (size_t i = 0; i < num_devices; ++i) { - devices.emplace_back(device_ptrs[i]); - } - } - - return devices; -} - -inline CustomOpDomain::CustomOpDomain(const char* domain) { - ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_)); -} - -inline void CustomOpDomain::Add(const OrtCustomOp* op) { - ThrowOnError(GetApi().CustomOpDomain_Add(p_, op)); -} - -inline LoraAdapter LoraAdapter::CreateLoraAdapter(const std::basic_string& adapter_path, - OrtAllocator* allocator) { - OrtLoraAdapter* p; - ThrowOnError(GetApi().CreateLoraAdapter(adapter_path.c_str(), allocator, &p)); - return LoraAdapter{p}; -} - -inline LoraAdapter LoraAdapter::CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, - OrtAllocator* allocator) { - OrtLoraAdapter* p; - ThrowOnError(GetApi().CreateLoraAdapterFromArray(bytes, num_bytes, allocator, &p)); - return LoraAdapter{p}; -} - -inline RunOptions::RunOptions() { - ThrowOnError(GetApi().CreateRunOptions(&p_)); -} - -inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) { - ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level)); - return *this; -} - -inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) { - ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level)); - return *this; -} - -inline int RunOptions::GetRunLogVerbosityLevel() const { - int out; - ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out)); - return out; -} - -inline int RunOptions::GetRunLogSeverityLevel() const { - int out; - ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out)); - return out; -} - -inline RunOptions& RunOptions::SetRunTag(const char* run_tag) { - ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag)); - return *this; -} - -inline const char* RunOptions::GetRunTag() const { - const char* out; - ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out)); - return out; -} - -inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) { - ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value)); - return *this; -} - -inline RunOptions& RunOptions::SetTerminate() { - ThrowOnError(GetApi().RunOptionsSetTerminate(p_)); - return *this; -} - -inline RunOptions& RunOptions::UnsetTerminate() { - ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_)); - return *this; -} - -inline RunOptions& RunOptions::AddActiveLoraAdapter(const LoraAdapter& adapter) { - ThrowOnError(GetApi().RunOptionsAddActiveLoraAdapter(p_, adapter)); - return *this; -} - -inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, const SessionOptions& session_options) { - ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); -} - -inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, ConstSessionOptions session_options) { - ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); -} - -inline Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options) { - return Ort::Status(GetCompileApi().CompileModel(env, model_compilation_options)); -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelPath( - const ORTCHAR_T* input_model_path) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelPath(this->p_, input_model_path)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelFromBuffer( - const void* input_model_data, size_t input_model_data_size) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelFromBuffer(this->p_, input_model_data, - input_model_data_size)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelPath( - const ORTCHAR_T* output_model_path) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelPath(this->p_, output_model_path)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersFile( - const ORTCHAR_T* file_path, size_t initializer_size_threshold) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersFile( - this->p_, - file_path, - initializer_size_threshold)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelBuffer( - OrtAllocator* allocator, void** output_model_buffer_ptr, size_t* output_model_buffer_size_ptr) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelBuffer(this->p_, allocator, - output_model_buffer_ptr, - output_model_buffer_size_ptr)); - return *this; -} - -inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextEmbedMode( - bool embed_ep_context_in_model) { - Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextEmbedMode( - this->p_, - embed_ep_context_in_model)); - return *this; -} - -namespace detail { - -template -inline Ort::SessionOptions ConstSessionOptionsImpl::Clone() const { - OrtSessionOptions* out; - ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out)); - return SessionOptions{out}; -} - -template -inline std::string ConstSessionOptionsImpl::GetConfigEntry(const char* config_key) const { - size_t size = 0; - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline bool ConstSessionOptionsImpl::HasConfigEntry(const char* config_key) const { - int out = 0; - Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out)); - return static_cast(out); -} - -template -inline std::string ConstSessionOptionsImpl::GetConfigEntryOrDefault(const char* config_key, - const std::string& def) const { - if (!this->HasConfigEntry(config_key)) { - return def; - } - - return this->GetConfigEntry(config_key); -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetIntraOpNumThreads(int intra_op_num_threads) { - ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetInterOpNumThreads(int inter_op_num_threads) { - ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) { - ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetDeterministicCompute(bool value) { - ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) { - ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableProfiling(const ORTCHAR_T* profile_file_prefix) { - ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisableProfiling() { - ThrowOnError(GetApi().DisableProfiling(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableOrtCustomOps() { - ThrowOnError(GetApi().EnableOrtCustomOps(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableMemPattern() { - ThrowOnError(GetApi().EnableMemPattern(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisableMemPattern() { - ThrowOnError(GetApi().DisableMemPattern(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::EnableCpuMemArena() { - ThrowOnError(GetApi().EnableCpuMemArena(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisableCpuMemArena() { - ThrowOnError(GetApi().DisableCpuMemArena(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetExecutionMode(ExecutionMode execution_mode) { - ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetLoadCancellationFlag(bool value) { - ThrowOnError(GetApi().SessionOptionsSetLoadCancellationFlag(this->p_, value)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetLogId(const char* logid) { - ThrowOnError(GetApi().SetSessionLogId(this->p_, logid)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetLogSeverityLevel(int level) { - ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::Add(OrtCustomOpDomain* custom_op_domain) { - ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddConfigEntry(const char* config_key, const char* config_value) { - ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddInitializer(const char* name, const OrtValue* ort_val) { - ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::DisablePerSessionThreads() { - ThrowOnError(GetApi().DisablePerSessionThreads(this->p_)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializers(const std::vector& names, - const std::vector& ort_values) { - const size_t inputs_num = names.size(); - if (inputs_num != ort_values.size()) { - ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT); - } - std::vector names_ptr; - std::vector ort_values_ptrs; - names_ptr.reserve(inputs_num); - ort_values_ptrs.reserve(inputs_num); - for (size_t i = 0; i < inputs_num; ++i) { - names_ptr.push_back(names[i].c_str()); - ort_values_ptrs.push_back(ort_values[i]); - } - ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializersFromFilesInMemory(const std::vector>& file_names, - const std::vector& buffer_array, - const std::vector& file_lengths) { - const size_t inputs_num = file_names.size(); - if (inputs_num != buffer_array.size()) { - ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT); - } - if (inputs_num != file_lengths.size()) { - ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT); - } - std::vector names_ptr; - names_ptr.reserve(inputs_num); - for (size_t i = 0; i < inputs_num; ++i) { - names_ptr.push_back(file_names[i].c_str()); - } - ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(), - file_lengths.data(), inputs_num)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider( - const std::string& provider_name, - const std::unordered_map& provider_options) { - auto num_entries = provider_options.size(); - std::vector keys, values; - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - - for (const auto& entry : provider_options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(), - keys.data(), values.data(), num_entries)); - - return *this; -} - -namespace { -template -void SessionOptionsAppendEP(detail::SessionOptionsImpl& session_options, - Env& env, const std::vector& ep_devices, - const std::vector& ep_options_keys, - const std::vector& ep_options_values) { - std::vector ep_devices_ptrs; - ep_devices_ptrs.reserve(ep_devices.size()); - for (const auto& ep_device : ep_devices) { - ep_devices_ptrs.push_back(ep_device); - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_V2( - session_options, env, ep_devices_ptrs.data(), ep_devices_ptrs.size(), - ep_options_keys.data(), ep_options_values.data(), ep_options_keys.size())); -} -} // namespace - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( - Env& env, const std::vector& ep_devices, const KeyValuePairs& ep_options) { - std::vector ep_options_keys, ep_options_values; - ep_options.GetKeyValuePairs(ep_options_keys, ep_options_values); - - SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( - Env& env, const std::vector& ep_devices, - const std::unordered_map& ep_options) { - std::vector ep_options_keys, ep_options_values; - ep_options_keys.reserve(ep_options.size()); - ep_options_values.reserve(ep_options.size()); - - for (const auto& [key, value] : ep_options) { - ep_options_keys.push_back(key.c_str()); - ep_options_values.push_back(value.c_str()); - } - - SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy) { - ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicy(this->p_, policy)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state) { - ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicyDelegate(this->p_, delegate, state)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { - ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { - ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { - ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) { - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options) { - auto num_entries = provider_options.size(); - std::vector keys, values; - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - - for (const auto& entry : provider_options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_, - keys.data(), values.data(), num_entries)); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options) { - auto num_entries = provider_options.size(); - std::vector keys, values; - if (num_entries > 0) { - keys.reserve(num_entries); - values.reserve(num_entries); - - for (const auto& entry : provider_options) { - keys.push_back(entry.first.c_str()); - values.push_back(entry.second.c_str()); - } - } - - ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries)); - - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, - const CustomOpConfigs& custom_op_configs) { - // Add custom op config entries before registering the custom op library. Otherwise, the config entries _may_ be ignored by - // the custom op library. - for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) { - AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str()); - } - - ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name)); - return *this; -} - -template -inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsUsingFunction(const char* registration_function_name) { - ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name)); - return *this; -} - -/// Session -template -inline size_t ConstSessionImpl::GetInputCount() const { - size_t out; - ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out)); - return out; -} - -template -inline size_t ConstSessionImpl::GetOutputCount() const { - size_t out; - ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out)); - return out; -} - -template -inline size_t ConstSessionImpl::GetOverridableInitializerCount() const { - size_t out; - ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out)); - return out; -} - -template -inline std::vector ConstSessionImpl::GetInputNames() const { - AllocatorWithDefaultOptions allocator; - - auto num_inputs = GetInputCount(); - std::vector input_names; - input_names.reserve(num_inputs); - - for (size_t i = 0; i < num_inputs; ++i) { - char* name = nullptr; - ThrowOnError(GetApi().SessionGetInputName(this->p_, i, allocator, &name)); - input_names.push_back(name); - allocator.Free(name); - } - - return input_names; -} - -template -inline std::vector ConstSessionImpl::GetOutputNames() const { - AllocatorWithDefaultOptions allocator; - - auto num_inputs = GetOutputCount(); - std::vector output_names; - output_names.reserve(num_inputs); - - for (size_t i = 0; i < num_inputs; ++i) { - char* name = nullptr; - ThrowOnError(GetApi().SessionGetOutputName(this->p_, i, allocator, &name)); - output_names.push_back(name); - allocator.Free(name); - } - - return output_names; -} - -template -inline std::vector ConstSessionImpl::GetOverridableInitializerNames() const { - AllocatorWithDefaultOptions allocator; - - auto num_initializers = GetOverridableInitializerCount(); - std::vector initializer_names; - initializer_names.reserve(num_initializers); - - for (size_t i = 0; i < num_initializers; ++i) { - char* name = nullptr; - ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, i, allocator, &name)); - initializer_names.push_back(name); - } - - return initializer_names; -} - -template -inline AllocatedStringPtr ConstSessionImpl::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline AllocatedStringPtr ConstSessionImpl::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline AllocatedStringPtr ConstSessionImpl::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline uint64_t ConstSessionImpl::GetProfilingStartTimeNs() const { - uint64_t out; - ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out)); - return out; -} - -template -inline ModelMetadata ConstSessionImpl::GetModelMetadata() const { - OrtModelMetadata* out; - ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out)); - return ModelMetadata{out}; -} - -template -inline TypeInfo ConstSessionImpl::GetInputTypeInfo(size_t index) const { - OrtTypeInfo* out; - ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline TypeInfo ConstSessionImpl::GetOutputTypeInfo(size_t index) const { - OrtTypeInfo* out; - ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline TypeInfo ConstSessionImpl::GetOverridableInitializerTypeInfo(size_t index) const { - OrtTypeInfo* out; - ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -#if !defined(ORT_MINIMAL_BUILD) -template -inline int ConstSessionImpl::GetOpset(const std::string& domain) const { - int opset; - ThrowOnError(GetModelEditorApi().SessionGetOpsetForDomain(this->p_, domain.c_str(), &opset)); - return opset; -} -#endif // !defined(ORT_MINIMAL_BUILD) - -template -std::vector ConstSessionImpl::GetInputs() const { - const std::vector input_names = GetInputNames(); - - std::vector inputs; - inputs.reserve(input_names.size()); - - for (size_t i = 0; i < input_names.size(); ++i) { - auto type_info = GetInputTypeInfo(i); - inputs.emplace_back(ValueInfo{input_names[i], type_info.GetConst()}); - } - - return inputs; -} - -template -std::vector ConstSessionImpl::GetOutputs() const { - const std::vector output_names = GetOutputNames(); - - std::vector outputs; - outputs.reserve(output_names.size()); - - for (size_t i = 0; i < output_names.size(); ++i) { - auto type_info = GetOutputTypeInfo(i); - outputs.emplace_back(ValueInfo{output_names[i], type_info.GetConst()}); - } - - return outputs; -} - -template -inline std::vector SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, size_t output_count) { - std::vector output_values; - output_values.reserve(output_count); - for (size_t i = 0; i < output_count; i++) - output_values.emplace_back(nullptr); - Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count); - return output_values; -} - -template -inline void SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count) { - static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); - auto ort_input_values = reinterpret_cast(input_values); - auto ort_output_values = reinterpret_cast(output_values); - ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values)); -} - -template -inline void SessionImpl::Run(const RunOptions& run_options, const IoBinding& io_binding) { - ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding)); -} - -template -inline void SessionImpl::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, - const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) { - auto ort_input_values = reinterpret_cast(input_values); - auto ort_output_values = reinterpret_cast(output_values); - ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names, - ort_input_values, input_count, output_names, output_count, - ort_output_values, callback, user_data)); -} - -template -inline AllocatedStringPtr SessionImpl::EndProfilingAllocated(OrtAllocator* allocator) { - char* out = nullptr; - ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -template -inline void SessionImpl::SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len) { - ThrowOnError(GetApi().SetEpDynamicOptions(this->p_, keys, values, kv_len)); -} - -#if !defined(ORT_MINIMAL_BUILD) -template -inline void SessionImpl::FinalizeModelEditorSession(const Model& model, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container) { - ThrowOnError(GetModelEditorApi().ApplyModelToModelEditorSession(this->p_, model)); - ThrowOnError(GetModelEditorApi().FinalizeModelEditorSession(this->p_, options, prepacked_weights_container)); -} -#endif // #if !defined(ORT_MINIMAL_BUILD) - -} // namespace detail - -inline SessionOptions::SessionOptions() { - ThrowOnError(GetApi().CreateSessionOptions(&this->p_)); -} - -/// CustomOpConfigs -inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) { - std::string config_key = "custom_op."; - - config_key += custom_op_name; - config_key += "."; - config_key += config; - - return config_key; -} - -inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) { - const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key); - flat_configs_[full_flat_key] = config_value; - return *this; -} - -inline const std::unordered_map& CustomOpConfigs::GetFlattenedConfigs() const { - return flat_configs_; -} - -inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) { - ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_)); -} - -inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container) { - ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_)); -} - -inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) { - ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_)); -} - -inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, - const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) { - ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options, - prepacked_weights_container, &this->p_)); -} - -#if !defined(ORT_MINIMAL_BUILD) -inline Session::Session(const Env& env, const Model& model, const SessionOptions& options) { - ThrowOnError(GetModelEditorApi().CreateSessionFromModel(env, model.GetConst(), options, &this->p_)); -} - -// static -inline Session Session::CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, - const SessionOptions& options) { - OrtSession* session = nullptr; - ThrowOnError(GetModelEditorApi().CreateModelEditorSession(env, model_path, options, &session)); - return Session(session); -} - -// static -inline Session Session::CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, - const SessionOptions& options) { - OrtSession* session = nullptr; - ThrowOnError(GetModelEditorApi().CreateModelEditorSessionFromArray(env, model_data, model_data_length, options, - &session)); - return Session(session); -} - -void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, - OrtPrepackedWeightsContainer* prepacked_weights_container); -#endif // #if !defined(ORT_MINIMAL_BUILD) - -inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const { - char* out; - ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out)); - return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); -} - -inline std::vector ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const { - auto deletor = detail::AllocatedFree(allocator); - std::vector result; - - char** out = nullptr; - int64_t num_keys = 0; - ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys)); - if (num_keys <= 0) { - return result; - } - - // array of pointers will be freed - std::unique_ptr array_guard(out, deletor); - // reserve may throw - auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); }; - std::unique_ptr strings_guard(out, strings_deletor); - result.reserve(static_cast(num_keys)); - strings_guard.release(); - for (int64_t i = 0; i < num_keys; ++i) { - result.push_back(AllocatedStringPtr(out[i], deletor)); - } - - return result; -} - -inline int64_t ModelMetadata::GetVersion() const { - int64_t out; - ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out)); - return out; -} - -inline TensorTypeAndShapeInfo::TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, - const std::vector& dims, - const std::vector* symbolic_dims) { - ThrowOnError(GetApi().CreateTensorTypeAndShapeInfo(&p_)); - ThrowOnError(GetApi().SetTensorElementType(p_, element_type)); - ThrowOnError(GetApi().SetDimensions(p_, dims.data(), dims.size())); - - if (symbolic_dims) { - std::vector symbolic_dims_cstr; - symbolic_dims_cstr.reserve(symbolic_dims->size()); - std::transform(symbolic_dims->begin(), symbolic_dims->end(), std::back_inserter(symbolic_dims_cstr), - [](const std::string& s) { return s.c_str(); }); - ThrowOnError(GetApi().SetSymbolicDimensions(p_, symbolic_dims_cstr.data(), symbolic_dims_cstr.size())); - } -} - -#if !defined(ORT_MINIMAL_BUILD) -// static -inline TypeInfo TypeInfo::CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_type_and_shape_info) { - OrtTypeInfo* output = nullptr; - ThrowOnError(GetModelEditorApi().CreateTensorTypeInfo(tensor_type_and_shape_info, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_type_and_shape_info) { - OrtTypeInfo* output = nullptr; - ThrowOnError(GetModelEditorApi().CreateSparseTensorTypeInfo(sparse_tensor_type_and_shape_info, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateSequenceTypeInfo(ConstTypeInfo sequence_type) { - OrtTypeInfo* output; - ThrowOnError(GetModelEditorApi().CreateSequenceTypeInfo(sequence_type, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type) { - OrtTypeInfo* output; - ThrowOnError(GetModelEditorApi().CreateMapTypeInfo(key_type, value_type, &output)); - return TypeInfo{output}; -} - -// static -inline TypeInfo TypeInfo::CreateOptionalTypeInfo(ConstTypeInfo contained_type) { - OrtTypeInfo* output; - ThrowOnError(GetModelEditorApi().CreateOptionalTypeInfo(contained_type, &output)); - return TypeInfo{output}; -} -#endif // #if !defined(ORT_MINIMAL_BUILD) - -namespace detail { - -template -inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl::GetElementType() const { - ONNXTensorElementDataType out; - ThrowOnError(GetApi().GetTensorElementType(this->p_, &out)); - return out; -} - -template -inline size_t TensorTypeAndShapeInfoImpl::GetElementCount() const { - size_t out; - ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out)); - return static_cast(out); -} - -template -inline size_t TensorTypeAndShapeInfoImpl::GetDimensionsCount() const { - size_t out; - ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out)); - return out; -} - -template -inline void TensorTypeAndShapeInfoImpl::GetDimensions(int64_t* values, size_t values_count) const { - ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count)); -} - -template -inline void TensorTypeAndShapeInfoImpl::GetSymbolicDimensions(const char** values, size_t values_count) const { - ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count)); -} - -template -inline std::vector TensorTypeAndShapeInfoImpl::GetSymbolicDimensions() const { - std::vector out(GetDimensionsCount(), nullptr); - ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, out.data(), out.size())); - return out; -} - -template -inline std::vector TensorTypeAndShapeInfoImpl::GetShape() const { - std::vector out(GetDimensionsCount(), -1); - ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size())); - return out; -} - -template -inline ConstTensorTypeAndShapeInfo TypeInfoImpl::GetTensorTypeAndShapeInfo() const { - const OrtTensorTypeAndShapeInfo* out; - ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out)); - return ConstTensorTypeAndShapeInfo{out}; -} - -template -inline ConstSequenceTypeInfo TypeInfoImpl::GetSequenceTypeInfo() const { - const OrtSequenceTypeInfo* out; - ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out)); - return ConstSequenceTypeInfo{out}; -} - -template -inline ConstMapTypeInfo TypeInfoImpl::GetMapTypeInfo() const { - const OrtMapTypeInfo* out; - ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out)); - return ConstMapTypeInfo{out}; -} - -template -inline ONNXType TypeInfoImpl::GetONNXType() const { - ONNXType out; - ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out)); - return out; -} - -template -inline TypeInfo SequenceTypeInfoImpl::GetSequenceElementType() const { - OrtTypeInfo* output; - ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output)); - return TypeInfo{output}; -} - -template -inline TypeInfo OptionalTypeInfoImpl::GetOptionalElementType() const { - OrtTypeInfo* info; - ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info)); - return TypeInfo{info}; -} - -template -inline ONNXTensorElementDataType MapTypeInfoImpl::GetMapKeyType() const { - ONNXTensorElementDataType out; - ThrowOnError(GetApi().GetMapKeyType(this->p_, &out)); - return out; -} - -template -inline TypeInfo MapTypeInfoImpl::GetMapValueType() const { - OrtTypeInfo* output; - ThrowOnError(GetApi().GetMapValueType(this->p_, &output)); - return TypeInfo{output}; -} - -template -inline ConstOptionalTypeInfo TypeInfoImpl::GetOptionalTypeInfo() const { - const OrtOptionalTypeInfo* info; - ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info)); - return ConstOptionalTypeInfo{info}; -} - -} // namespace detail - -namespace detail { - -template -template -inline void ConstValueImpl::GetOpaqueData(const char* domain, const char* type_name, R& out) const { - ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R))); -} - -template -inline bool ConstValueImpl::IsTensor() const { - int out; - ThrowOnError(GetApi().IsTensor(this->p_, &out)); - return out != 0; -} - -template -inline bool ConstValueImpl::HasValue() const { - int out; - ThrowOnError(GetApi().HasValue(this->p_, &out)); - return out != 0; -} - -template -inline size_t ConstValueImpl::GetCount() const { - size_t out; - ThrowOnError(GetApi().GetValueCount(this->p_, &out)); - return out; -} - -template -inline Value ConstValueImpl::GetValue(int index, OrtAllocator* allocator) const { - OrtValue* out; - ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out)); - return Value{out}; -} - -template -inline size_t ConstValueImpl::GetStringTensorDataLength() const { - size_t out; - ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out)); - return out; -} - -template -inline size_t ConstValueImpl::GetStringTensorElementLength(size_t element_index) const { - size_t out; - ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out)); - return out; -} - -template -template -inline const R* ConstValueImpl::GetTensorData() const { - R* out; - ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), (void**)&out)); - return out; -} - -template -inline const void* ConstValueImpl::GetTensorRawData() const { - void* out; - ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), &out)); - return out; -} - -template -inline TypeInfo ConstValueImpl::GetTypeInfo() const { - OrtTypeInfo* output; - ThrowOnError(GetApi().GetTypeInfo(this->p_, &output)); - return TypeInfo{output}; -} - -template -inline TensorTypeAndShapeInfo ConstValueImpl::GetTensorTypeAndShapeInfo() const { - OrtTensorTypeAndShapeInfo* output; - ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output)); - return TensorTypeAndShapeInfo{output}; -} - -template -inline ConstMemoryInfo ConstValueImpl::GetTensorMemoryInfo() const { - const OrtMemoryInfo* mem_info; - ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info)); - return ConstMemoryInfo(mem_info); -} - -template -inline void ConstValueImpl::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const { - ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer)); -} - -template -inline std::string ConstValueImpl::GetStringTensorElement(size_t element_index) const { - size_t buffer_length; - ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length)); - - std::string s; - s.resize(buffer_length); - ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0])); - return s; -} - -template -inline void ConstValueImpl::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const { - ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count)); -} - -#if !defined(DISABLE_SPARSE_TENSORS) -template -inline OrtSparseFormat ConstValueImpl::GetSparseFormat() const { - OrtSparseFormat format; - ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format)); - return format; -} - -template -inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorValuesTypeAndShapeInfo() const { - OrtTensorTypeAndShapeInfo* output; - ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output)); - return TensorTypeAndShapeInfo{output}; -} - -template -inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const { - OrtTensorTypeAndShapeInfo* output; - ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output)); - return TensorTypeAndShapeInfo{output}; -} - -template -template -inline const R* ConstValueImpl::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const { - const void* out; - ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out)); - return reinterpret_cast(out); -} - -template -inline bool ConstValueImpl::IsSparseTensor() const { - int out; - ThrowOnError(GetApi().IsSparseTensor(this->p_, &out)); - return out != 0; -} - -template -template -inline const R* ConstValueImpl::GetSparseTensorValues() const { - const void* out; - ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out)); - return reinterpret_cast(out); -} - -#endif - -template -void ValueImpl::FillStringTensor(const char* const* s, size_t s_len) { - ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len)); -} - -template -void ValueImpl::FillStringTensorElement(const char* s, size_t index) { - ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index)); -} - -template -inline char* ValueImpl::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) { - char* result; - ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result)); - return result; -} - -template -void* ValueImpl::GetTensorMutableRawData() { - void* out; - ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out)); - return out; -} - -template -template -R* ValueImpl::GetTensorMutableData() { - R* out; - ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out)); - return out; -} - -template -template -R& ValueImpl::At(const std::vector& location) { - static_assert(!std::is_same::value, "this api does not support std::string"); - R* out; - ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out)); - return *out; -} - -#if !defined(DISABLE_SPARSE_TENSORS) -template -void ValueImpl::UseCooIndices(int64_t* indices_data, size_t indices_num) { - ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num)); -} - -template -void ValueImpl::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) { - ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num)); -} - -template -void ValueImpl::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) { - ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data)); -} - -template -void ValueImpl::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param, - const int64_t* indices_data, size_t indices_num) { - ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape, - values_param.values_shape_len, values_param.data.p_data, - indices_data, indices_num)); -} - -template -void ValueImpl::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const int64_t* inner_indices_data, size_t inner_indices_num, - const int64_t* outer_indices_data, size_t outer_indices_num) { - ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, - inner_indices_data, inner_indices_num, - outer_indices_data, outer_indices_num)); -} - -template -void ValueImpl::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, - const OrtSparseValuesParam& values, - const Shape& indices_shape, - const int32_t* indices_data) { - ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, - indices_shape.shape, indices_shape.shape_len, - indices_data)); -} - -#endif // !defined(DISABLE_SPARSE_TENSORS) - -} // namespace detail - -template -inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, - const int64_t* shape, size_t shape_len) { - return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType::type); -} - -inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out)); - return Value{out}; -} - -inline Value Value::CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, - const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateTensorWithDataAndDeleterAsOrtValue(deleter, p_data, p_data_byte_count, - shape, shape_len, type, &out)); - return Value{out}; -} - -template -inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) { - return CreateTensor(allocator, shape, shape_len, TypeToTensorType::type); -} - -inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out)); - return Value{out}; -} - -#if !defined(DISABLE_SPARSE_TENSORS) - -template -inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, - const Shape& values_shape) { - return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType::type); -} - -inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, - const Shape& values_shape, ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len, - values_shape.shape, values_shape.shape_len, type, - &out)); - return Value{out}; -} - -template -inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) { - return CreateSparseTensor(allocator, dense_shape, TypeToTensorType::type); -} - -inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, - ONNXTensorElementDataType type) { - OrtValue* out; - ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out)); - return Value{out}; -} -#endif // !defined(DISABLE_SPARSE_TENSORS) - -inline Value Value::CreateMap(const Value& keys, const Value& values) { - OrtValue* out; - const OrtValue* inputs[2] = {keys, values}; - ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out)); - return Value{out}; -} - -inline Value Value::CreateSequence(const std::vector& values) { - OrtValue* out; - std::vector values_ort{values.data(), values.data() + values.size()}; - ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out)); - return Value{out}; -} - -template -inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) { - OrtValue* out; - ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out)); - return Value{out}; -} - -// -// Custom OP Inlines -// -inline Logger::Logger(const OrtLogger* logger) : logger_(logger) { - Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_)); -} - -inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept { - return cached_severity_level_; -} - -inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, - const char* func_name, const char* message) const noexcept { - OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number, - func_name); - return Status{status}; -} - -// Disable warnings about the format string not being a literal (-Wformat-nonliteral and -Wformat-security) -// for gcc and clang. The alternative is to use actual C-style variadic parameters and apply -// __attribute__(format(printf...)), which does not work with variadic templates. -#if defined(__GNUC__) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wformat-nonliteral" -#pragma GCC diagnostic ignored "-Wformat-security" -#elif defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wformat-nonliteral" -#pragma clang diagnostic ignored "-Wformat-security" -#endif -template -inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, - int line_number, const char* func_name, const char* format, - Args&&... args) const noexcept { - int msg_len = std::snprintf(nullptr, 0U, format, std::forward(args)...); - - if (msg_len < 0) { // Formatting error - return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL); - } - - OrtStatus* status = nullptr; - const size_t buffer_size = static_cast(msg_len) + 1U; - - constexpr size_t kStackBufferSize = 1024; - - if (buffer_size < kStackBufferSize) { - char buffer[kStackBufferSize]; - snprintf(buffer, kStackBufferSize, format, std::forward(args)...); - status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name); - } else { - // std::make_unique is only supported starting at C++14. -#if (__cplusplus >= 201402L) || (_MSC_VER >= 1900) - auto buffer = std::make_unique(buffer_size); -#else - std::unique_ptr buffer(new char[buffer_size]); -#endif - std::snprintf(buffer.get(), buffer_size, format, std::forward(args)...); - status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name); - } - - return Status{status}; -} -// Re-enable -Wformat-nonliteral and -Wformat-security -#if defined(__GNUC__) -#pragma GCC diagnostic pop -#elif defined(__clang__) -#pragma clang diagnostic pop -#endif - -inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) { -} - -inline size_t KernelContext::GetInputCount() const { - size_t out = 0; - Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out)); - return out; -} - -inline size_t KernelContext::GetOutputCount() const { - size_t out = 0; - Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out)); - return out; -} - -inline ConstValue KernelContext::GetInput(size_t index) const { - const OrtValue* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out)); - return ConstValue{out}; -} - -inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const { - OrtValue* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out)); - return UnownedValue(out); -} - -inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector& dims) const { - OrtValue* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out)); - return UnownedValue(out); -} - -inline void* KernelContext::GetGPUComputeStream() const { - void* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out)); - return out; -} - -inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const { - OrtAllocator* out = nullptr; - Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out)); - return out; -} - -inline Logger KernelContext::GetLogger() const { - const OrtLogger* out = nullptr; - ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out)); - return Logger{out}; -} - -inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const { - ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data)); -} - -inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) { - Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_)); -} - -namespace detail { -template -inline KernelInfo KernelInfoImpl::Copy() const { - OrtKernelInfo* info_copy = nullptr; - Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy)); - return KernelInfo{info_copy}; -} - -template -inline size_t KernelInfoImpl::GetInputCount() const { - size_t out = 0; - ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out)); - return out; -} - -template -inline size_t KernelInfoImpl::GetOutputCount() const { - size_t out = 0; - ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out)); - return out; -} - -template -inline std::string KernelInfoImpl::GetInputName(size_t index) const { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline std::string KernelInfoImpl::GetOutputName(size_t index) const { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline TypeInfo KernelInfoImpl::GetInputTypeInfo(size_t index) const { - OrtTypeInfo* out = nullptr; - ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline TypeInfo KernelInfoImpl::GetOutputTypeInfo(size_t index) const { - OrtTypeInfo* out = nullptr; - ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out)); - return TypeInfo{out}; -} - -template -inline Value KernelInfoImpl::GetTensorAttribute(const char* name, OrtAllocator* allocator) const { - OrtValue* out = nullptr; - ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out)); - return Value{out}; -} - -template -inline ConstValue KernelInfoImpl::GetTensorConstantInput(size_t index, int* is_constant) const { - const OrtValue* out = nullptr; - ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out)); - return ConstValue{out}; -} - -template -inline std::string KernelInfoImpl::GetNodeName() const { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the string value - Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - - return out; -} - -template -inline Logger KernelInfoImpl::GetLogger() const { - const OrtLogger* out = nullptr; - ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out)); - return Logger{out}; -} - -inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) { - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out)); -} - -inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) { - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out)); -} - -inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) { - size_t size = 0; - // Feed nullptr for the data buffer to query the true size of the string attribute - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size)); - - std::string out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size)); - out.resize(size - 1); // remove the terminating character '\0' - out.swap(result); -} - -inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { - size_t size = 0; - // Feed nullptr for the data buffer to query the true size of the attribute - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size)); - - std::vector out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size)); - out.swap(result); -} - -inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { - size_t size = 0; - - // Feed nullptr for the data buffer to query the true size of the attribute - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size)); - - std::vector out; - out.resize(size); - Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size)); - out.swap(result); -} -} // namespace detail - -inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl{info} {} - -inline Op::Op(OrtOp* p) : detail::Base(p) {} - -inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version, - const char** type_constraint_names, - const ONNXTensorElementDataType* type_constraint_values, - size_t type_constraint_count, - const OpAttr* attr_values, size_t attr_count, - size_t input_count, size_t output_count) { - static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*), - "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely"); - auto attr_input_values = reinterpret_cast(attr_values); - OrtOp* op; - Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values, - static_cast(type_constraint_count), - attr_input_values, - static_cast(attr_count), - static_cast(input_count), - static_cast(output_count), &op)); - return Op{op}; -} - -inline void Op::Invoke(const OrtKernelContext* context, - const Value* input_values, - size_t input_count, - Value* output_values, - size_t output_count) { - static_assert(sizeof(Value) == sizeof(OrtValue*), - "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); - auto ort_input_values = reinterpret_cast(input_values); - auto ort_output_values = reinterpret_cast(output_values); - Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast(input_count), - ort_output_values, static_cast(output_count))); -} - -inline void Op::Invoke(const OrtKernelContext* context, - const OrtValue* const* input_values, - size_t input_count, - OrtValue* const* output_values, - size_t output_count) { - Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast(input_count), - output_values, static_cast(output_count))); -} - -inline std::string GetVersionString() { - return OrtGetApiBase()->GetVersionString(); -} - -inline std::string GetBuildInfoString() { - return GetApi().GetBuildInfoString(); -} - -inline std::vector GetAvailableProviders() { - char** providers; - int len; - - auto release_fn = [&len](char** providers) { - // This should always return nullptr. - ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len)); - }; - - ThrowOnError(GetApi().GetAvailableProviders(&providers, &len)); - std::unique_ptr guard(providers, release_fn); - std::vector available_providers; - available_providers.reserve(static_cast(len)); - for (int i = 0; i < len; ++i) { - available_providers.emplace_back(providers[i]); - } - return available_providers; -} - -template -void CustomOpBase::GetSessionConfigs(std::unordered_map& out, - ConstSessionOptions options) const { - const TOp* derived = static_cast(this); - std::vector keys = derived->GetSessionConfigKeys(); - - out.reserve(keys.size()); - - std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), ""); - const size_t prefix_size = config_entry_key.length(); - - for (const auto& key : keys) { - config_entry_key.resize(prefix_size); - config_entry_key.append(key); - out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), ""); - } -} - -inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api, - OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) { - size_t input_count = 0; - Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count)); - for (size_t ith_input = 0; ith_input < input_count; ++ith_input) { - OrtTensorTypeAndShapeInfo* info{}; - Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info)); - TensorTypeAndShapeInfo type_shape_info(info); - auto integer_shape = type_shape_info.GetShape(); - std::vector symbolic_shape(integer_shape.size(), {}); - if (!integer_shape.empty()) { - type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size()); - } - Shape shape; - for (size_t ith = 0; ith < integer_shape.size(); ++ith) { - if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) { - shape.emplace_back(symbolic_shape[ith]); - } else { - shape.emplace_back(integer_shape[ith]); - } - } - input_shapes_.push_back(std::move(shape)); - type_shape_info.release(); - } -} - -inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type) { - OrtTensorTypeAndShapeInfo* info = {}; - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info)); - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetTensorElementType(info, type)); - - using InfoPtr = std::unique_ptr>; - - InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) { - ort_api_->ReleaseTensorTypeAndShapeInfo(obj); - }); - - std::vector integer_dims; - std::vector symbolic_dims; - - for (const auto dim : shape) { - if (dim.IsInt()) { - integer_dims.push_back(dim.AsInt()); - symbolic_dims.push_back(""); - } else { - if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) { - ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT); - } - integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM); - symbolic_dims.push_back(dim.AsSym()); - } - } - - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size())); - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size())); - ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info)); - return Status{nullptr}; -} - -inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - int64_t i = {}; - size_t out = {}; - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INT, &i, sizeof(i), &out)); - return i; -} - -inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - int64_t i = {}; - size_t out = {}; - // first call to get the bytes needed - // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. - // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). - // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, &i, sizeof(i), &out); - if (status) { - size_t num_i = out / sizeof(int64_t); - ShapeInferContext::Ints ints(num_i, 0); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, ints.data(), out, &out)); - return ints; - } else { - if (out == 0u) { - return {}; - } - return {i}; - } -} - -inline float ShapeInferContext::GetAttrFloat(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - float f = {}; - size_t out = {}; - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOAT, &f, sizeof(f), &out)); - return f; -} - -inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - float f = {}; - size_t out = {}; - // first call to get the bytes needed - // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. - // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). - // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, &f, sizeof(f), &out); - if (status) { - size_t num_f = out / sizeof(float); - ShapeInferContext::Floats floats(num_f, 0); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, floats.data(), out, &out)); - return floats; - } else { - if (out == 0u) { - return {}; - } - return {f}; - } -} - -inline std::string ShapeInferContext::GetAttrString(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - char c = {}; - size_t out = {}; - // first call to get the bytes needed - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, &c, sizeof(char), &out); - if (status) { - std::vector chars(out, '\0'); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, chars.data(), out, &out)); - return {chars.data()}; - } else { - return {c}; - } -} - -inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) { - const auto* attr = GetAttrHdl(attr_name); - char c = {}; - size_t out = {}; - // first call to get the bytes needed - // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. - // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). - // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. - auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, &c, sizeof(char), &out); - if (status) { - std::vector chars(out, '\0'); - Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, chars.data(), out, &out)); - ShapeInferContext::Strings strings; - char* char_st = chars.data(); - char* char_ed = char_st + out; - while (char_st < char_ed) { - strings.emplace_back(char_st); - while (*char_st != '\0') { - char_st++; - } - char_st++; - } - return strings; - } else { - if (out == 0u) { - return {}; - } - return {std::string{c}}; - } -} - -inline const OrtOpAttr* ShapeInferContext::GetAttrHdl(const char* attr_name) const { - const OrtOpAttr* attr_hdl = {}; - Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl)); - return attr_hdl; -} - -namespace detail { -inline std::vector StringsToCharPtrs(const std::vector& strings) { - std::vector ptrs; - ptrs.reserve(strings.size()); - std::transform(strings.begin(), strings.end(), std::back_inserter(ptrs), - [](const std::string& s) { return s.c_str(); }); - - return ptrs; -} -} // namespace detail - -#if !defined(ORT_MINIMAL_BUILD) -// static -inline void Node::Init(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes, - OrtNode*& node) { - auto inputs = detail::StringsToCharPtrs(input_names); - auto outputs = detail::StringsToCharPtrs(output_names); - - std::vector attributes_ptrs; - attributes_ptrs.reserve(attributes.size()); - std::transform(attributes.begin(), attributes.end(), std::back_inserter(attributes_ptrs), - [](OpAttr& attr) -> OrtOpAttr* { return attr; }); - - ThrowOnError(GetModelEditorApi().CreateNode(operator_name.c_str(), operator_domain.c_str(), node_name.c_str(), - inputs.data(), inputs.size(), - outputs.data(), outputs.size(), - attributes_ptrs.data(), attributes_ptrs.size(), - &node)); - - // Node now owns the attributes - std::for_each(attributes.begin(), attributes.end(), [](OpAttr& attr) { attr.release(); }); -} - -inline Node::Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names, - std::vector& attributes) { - Init(operator_name, operator_domain, node_name, input_names, output_names, attributes, p_); -} - -inline Node::Node(const std::string& operator_name, const std::string& operator_domain, - const std::string& node_name, - const std::vector& input_names, - const std::vector& output_names) { - std::vector empty_attributes; - Init(operator_name, operator_domain, node_name, input_names, output_names, empty_attributes, p_); -} - -inline Graph::Graph() { - ThrowOnError(GetModelEditorApi().CreateGraph(&p_)); -} - -inline Model::Model(const std::vector& opsets) { - std::vector domains; - std::vector versions; - domains.reserve(opsets.size()); - versions.reserve(opsets.size()); - - for (const auto& pair : opsets) { - domains.push_back(pair.first.c_str()); - versions.push_back(pair.second); - } - - ThrowOnError(GetModelEditorApi().CreateModel(domains.data(), versions.data(), opsets.size(), &p_)); -} - -inline ValueInfo::ValueInfo(const std::string& name, const ConstTypeInfo& type_info) { - ThrowOnError(GetModelEditorApi().CreateValueInfo(name.c_str(), type_info, &p_)); -} -#endif // !defined(ORT_MINIMAL_BUILD) - -namespace detail { -template <> -inline std::string ValueInfoImpl::Name() const { - const char* name = nullptr; - ThrowOnError(GetApi().GetValueInfoName(this->p_, &name)); - return name; -} - -template <> -inline ConstTypeInfo ValueInfoImpl::TypeInfo() const { - const OrtTypeInfo* type_info = nullptr; - ThrowOnError(GetApi().GetValueInfoTypeInfo(this->p_, &type_info)); - return ConstTypeInfo{type_info}; -} - -#if !defined(ORT_MINIMAL_BUILD) -template <> -inline void GraphImpl::SetInputs(std::vector& inputs) { - std::vector inputs_ptrs; - inputs_ptrs.reserve(inputs.size()); - std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_ptrs), - [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); - - ThrowOnError(GetModelEditorApi().SetGraphInputs(p_, inputs_ptrs.data(), inputs_ptrs.size())); - - // Graph now owns the inputs - std::for_each(inputs.begin(), inputs.end(), [](ValueInfo& vi) { vi.release(); }); -} - -template <> -inline void GraphImpl::SetOutputs(std::vector& outputs) { - std::vector outputs_ptrs; - outputs_ptrs.reserve(outputs.size()); - std::transform(outputs.begin(), outputs.end(), std::back_inserter(outputs_ptrs), - [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); - - ThrowOnError(GetModelEditorApi().SetGraphOutputs(p_, outputs_ptrs.data(), outputs_ptrs.size())); - - // Graph now owns the outputs - std::for_each(outputs.begin(), outputs.end(), [](ValueInfo& vi) { vi.release(); }); -} - -template <> -inline void GraphImpl::AddInitializer(const std::string& name, Value& initializer, bool data_is_external) { - // Graph takes ownership of `initializer` - ThrowOnError(GetModelEditorApi().AddInitializerToGraph(p_, name.c_str(), initializer.release(), data_is_external)); -} - -template <> -inline void GraphImpl::AddNode(Node& node) { - // Graph takes ownership of `node` - ThrowOnError(GetModelEditorApi().AddNodeToGraph(p_, node.release())); -} - -template <> -inline void ModelImpl::AddGraph(Graph& graph) { - // Model takes ownership of `graph` - ThrowOnError(GetModelEditorApi().AddGraphToModel(p_, graph.release())); -} -#endif // !defined(ORT_MINIMAL_BUILD) - -} // namespace detail -} // namespace Ort +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Do not include this file directly. Please include "onnxruntime_cxx_api.h" instead. +// If interested in trying out features of the new experimental C++ API, include "experimental_onnxruntime_cxx_api.h" instead. +// +// These are the inline implementations of the C++ header APIs. They're in this separate file as to not clutter +// the main C++ file with implementation details. + +#include +#include +#include +#include +#include +#include + +// Convert OrtStatus to Ort::Status and return +// instead of throwing +#define ORT_CXX_RETURN_ON_API_FAIL(expression) \ + { \ + auto ort_status = (expression); \ + if (ort_status) { \ + return Ort::Status(ort_status); \ + } \ + } + +#ifdef __cpp_if_constexpr +#define ORT_CXX_IF_CONSTEXPR if constexpr +#else +#define ORT_CXX_IF_CONSTEXPR if +#endif + +namespace Ort { + +namespace detail { +inline void ThrowStatus(const Status& st) { + std::string error_message = st.GetErrorMessage(); + OrtErrorCode error_code = st.GetErrorCode(); + ORT_CXX_API_THROW(std::move(error_message), error_code); +} +} // namespace detail + +inline void ThrowOnError(OrtStatus* ort_status) { + if (ort_status) { + Ort::Status st(ort_status); + detail::ThrowStatus(st); + } +} + +inline void ThrowOnError(const Status& st) { + if (st) { + detail::ThrowStatus(st); + } +} + +inline Status::Status(OrtStatus* status) noexcept : detail::Base{status} { +} + +inline Status::Status(const std::exception& e) noexcept { + p_ = GetApi().CreateStatus(ORT_FAIL, e.what()); +} + +inline Status::Status(const Exception& e) noexcept { + p_ = GetApi().CreateStatus(e.GetOrtErrorCode(), e.what()); +} + +inline Status::Status(const char* message, OrtErrorCode code) noexcept { + p_ = GetApi().CreateStatus(code, message); +} + +inline std::string Status::GetErrorMessage() const { + std::string message(GetApi().GetErrorMessage(p_)); + return message; +} + +inline OrtErrorCode Status::GetErrorCode() const { + return GetApi().GetErrorCode(p_); +} + +inline bool Status::IsOK() const noexcept { + return (p_ == nullptr); +} + +// This template converts a C++ type into it's ONNXTensorElementDataType +template +struct TypeToTensorType; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL; +}; + +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2; +}; +template <> +struct TypeToTensorType { + static constexpr ONNXTensorElementDataType type = ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ; +}; + +inline bool BFloat16_t::operator==(const BFloat16_t& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is not equal to anything, including itself. + return false; + } + return val == rhs.val; +} + +inline bool BFloat16_t::operator<(const BFloat16_t& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is unordered with respect to everything, including itself. + return false; + } + + const bool left_is_negative = IsNegative(); + if (left_is_negative != rhs.IsNegative()) { + // When the signs of left and right differ, we know that left is less than right if it is + // the negative value. The exception to this is if both values are zero, in which case IEEE + // says they should be equal, even if the signs differ. + return left_is_negative && !AreZero(*this, rhs); + } + return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); +} + +inline MemoryAllocation::MemoryAllocation(OrtAllocator* allocator, void* p, size_t size) + : allocator_(allocator), p_(p), size_(size) { +} + +inline MemoryAllocation::~MemoryAllocation() { + if (p_ != nullptr) { + // We do not throw out of destructor + auto ret = GetApi().AllocatorFree(allocator_, p_); + static_cast(ret); + } +} + +inline MemoryAllocation::MemoryAllocation(MemoryAllocation&& o) noexcept : allocator_(nullptr), p_(nullptr), size_(0) { + *this = std::move(o); +} + +inline MemoryAllocation& MemoryAllocation::operator=(MemoryAllocation&& o) noexcept { + OrtAllocator* alloc = nullptr; + void* p = nullptr; + size_t sz = 0; + + // Swap out this + std::swap(alloc, allocator_); + std::swap(p, p_); + std::swap(sz, size_); + + // Swap with incoming + std::swap(allocator_, o.allocator_); + std::swap(p_, o.p_); + std::swap(size_, o.size_); + + // Destroy this instance if needed + MemoryAllocation this_alloc(alloc, p, sz); + return *this; +} + +namespace detail { + +template +inline void* AllocatorImpl::Alloc(size_t size) { + void* out; + ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); + return out; +} + +template +inline MemoryAllocation AllocatorImpl::GetAllocation(size_t size) { + void* out; + ThrowOnError(GetApi().AllocatorAlloc(this->p_, size, &out)); + MemoryAllocation result(this->p_, out, size); + return result; +} + +template +inline void AllocatorImpl::Free(void* p) { + ThrowOnError(GetApi().AllocatorFree(this->p_, p)); +} + +template +inline ConstMemoryInfo AllocatorImpl::GetInfo() const { + const OrtMemoryInfo* out; + ThrowOnError(GetApi().AllocatorGetInfo(this->p_, &out)); + return ConstMemoryInfo{out}; +} + +} // namespace detail + +inline AllocatorWithDefaultOptions::AllocatorWithDefaultOptions() { + ThrowOnError(GetApi().GetAllocatorWithDefaultOptions(&this->p_)); +} + +inline Allocator::Allocator(const Session& sess, const OrtMemoryInfo* mem_info) { + ThrowOnError(GetApi().CreateAllocator(sess, mem_info, &this->p_)); +} + +namespace detail { + +template +inline std::string MemoryInfoImpl::GetAllocatorName() const { + const char* name = nullptr; + ThrowOnError(GetApi().MemoryInfoGetName(this->p_, &name)); + return std::string(name); +} + +template +inline OrtAllocatorType MemoryInfoImpl::GetAllocatorType() const { + OrtAllocatorType type; + ThrowOnError(GetApi().MemoryInfoGetType(this->p_, &type)); + return type; +} + +template +inline int MemoryInfoImpl::GetDeviceId() const { + int id = 0; + ThrowOnError(GetApi().MemoryInfoGetId(this->p_, &id)); + return id; +} + +template +inline OrtMemoryInfoDeviceType MemoryInfoImpl::GetDeviceType() const { + OrtMemoryInfoDeviceType type; + GetApi().MemoryInfoGetDeviceType(this->p_, &type); + return type; +} + +template +inline OrtMemType MemoryInfoImpl::GetMemoryType() const { + OrtMemType type; + ThrowOnError(GetApi().MemoryInfoGetMemType(this->p_, &type)); + return type; +} + +template +template +inline bool MemoryInfoImpl::operator==(const MemoryInfoImpl& o) const { + int comp_result = 0; + ThrowOnError(Ort::GetApi().CompareMemoryInfo(this->p_, o, &comp_result)); + return comp_result == 0; +} + +} // namespace detail + +inline MemoryInfo MemoryInfo::CreateCpu(OrtAllocatorType type, OrtMemType mem_type) { + OrtMemoryInfo* p; + ThrowOnError(GetApi().CreateCpuMemoryInfo(type, mem_type, &p)); + return MemoryInfo(p); +} + +inline MemoryInfo::MemoryInfo(const char* name, OrtAllocatorType type, int id, OrtMemType mem_type) { + ThrowOnError(GetApi().CreateMemoryInfo(name, type, id, mem_type, &this->p_)); +} + +namespace detail { +template +inline std::vector ConstIoBindingImpl::GetOutputNames() const { + AllocatorWithDefaultOptions allocator; + return binding_utils::GetOutputNamesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputNames(OrtAllocator* allocator) const { + return binding_utils::GetOutputNamesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputValues() const { + AllocatorWithDefaultOptions allocator; + return binding_utils::GetOutputValuesHelper(this->p_, allocator); +} + +template +inline std::vector ConstIoBindingImpl::GetOutputValues(OrtAllocator* allocator) const { + return binding_utils::GetOutputValuesHelper(this->p_, allocator); +} + +template +inline void IoBindingImpl::BindInput(const char* name, const Value& value) { + ThrowOnError(GetApi().BindInput(this->p_, name, value)); +} + +template +inline void IoBindingImpl::BindOutput(const char* name, const Value& value) { + ThrowOnError(GetApi().BindOutput(this->p_, name, value)); +} + +template +inline void IoBindingImpl::BindOutput(const char* name, const OrtMemoryInfo* mem_info) { + ThrowOnError(GetApi().BindOutputToDevice(this->p_, name, mem_info)); +} + +template +inline void IoBindingImpl::ClearBoundInputs() { + GetApi().ClearBoundInputs(this->p_); +} + +template +inline void IoBindingImpl::ClearBoundOutputs() { + GetApi().ClearBoundOutputs(this->p_); +} + +template +inline void IoBindingImpl::SynchronizeInputs() { + ThrowOnError(GetApi().SynchronizeBoundInputs(this->p_)); +} + +template +inline void IoBindingImpl::SynchronizeOutputs() { + ThrowOnError(GetApi().SynchronizeBoundOutputs(this->p_)); +} + +namespace binding_utils { +inline std::vector GetOutputNamesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { + std::vector result; + auto free_fn = detail::AllocatedFree(allocator); + using Ptr = std::unique_ptr; + + char* buffer = nullptr; + size_t* lengths = nullptr; + size_t count = 0; + ThrowOnError(GetApi().GetBoundOutputNames(binding, allocator, &buffer, &lengths, &count)); + + if (count == 0) { + return result; + } + + Ptr buffer_g(buffer, free_fn); + Ptr lengths_g(lengths, free_fn); + + result.reserve(count); + for (size_t i = 0; i < count; ++i) { + auto sz = *lengths; + result.emplace_back(buffer, sz); + buffer += sz; + ++lengths; + } + return result; +} + +inline std::vector GetOutputValuesHelper(const OrtIoBinding* binding, OrtAllocator* allocator) { + std::vector result; + size_t owned = 0; + size_t output_count = 0; + // Lambda to release the buffer when no longer needed and + // make sure that we destroy all instances on exception + auto free_fn = [&owned, &output_count, allocator](OrtValue** buffer) { + if (buffer) { + while (owned < output_count) { + auto* p = buffer + owned++; + GetApi().ReleaseValue(*p); + } + allocator->Free(allocator, buffer); + } + }; + using Ptr = std::unique_ptr; + + OrtValue** output_buffer = nullptr; + ThrowOnError(GetApi().GetBoundOutputValues(binding, allocator, &output_buffer, &output_count)); + if (output_count == 0) { + return result; + } + + Ptr buffer_g(output_buffer, free_fn); + + result.reserve(output_count); + for (size_t i = 0; i < output_count; ++i) { + result.emplace_back(output_buffer[i]); + ++owned; + } + return result; +} + +} // namespace binding_utils +} // namespace detail + +inline IoBinding::IoBinding(Session& session) { + ThrowOnError(GetApi().CreateIoBinding(session, &this->p_)); +} + +inline ArenaCfg::ArenaCfg(size_t max_mem, int arena_extend_strategy, int initial_chunk_size_bytes, int max_dead_bytes_per_chunk) { + ThrowOnError(GetApi().CreateArenaCfg(max_mem, arena_extend_strategy, initial_chunk_size_bytes, max_dead_bytes_per_chunk, &p_)); +} + +inline ThreadingOptions::ThreadingOptions() { + ThrowOnError(GetApi().CreateThreadingOptions(&p_)); +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalIntraOpNumThreads(int intra_op_num_threads) { + ThrowOnError(GetApi().SetGlobalIntraOpNumThreads(p_, intra_op_num_threads)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalInterOpNumThreads(int inter_op_num_threads) { + ThrowOnError(GetApi().SetGlobalInterOpNumThreads(p_, inter_op_num_threads)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalSpinControl(int allow_spinning) { + ThrowOnError(GetApi().SetGlobalSpinControl(p_, allow_spinning)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalDenormalAsZero() { + ThrowOnError(GetApi().SetGlobalDenormalAsZero(p_)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { + ThrowOnError(GetApi().SetGlobalCustomCreateThreadFn(p_, ort_custom_create_thread_fn)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { + ThrowOnError(GetApi().SetGlobalCustomThreadCreationOptions(p_, ort_custom_thread_creation_options)); + return *this; +} + +inline ThreadingOptions& ThreadingOptions::SetGlobalCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { + ThrowOnError(GetApi().SetGlobalCustomJoinThreadFn(p_, ort_custom_join_thread_fn)); + return *this; +} + +namespace detail { +template +inline const char* KeyValuePairsImpl::GetValue(const char* key) const { + return GetApi().GetKeyValue(this->p_, key); +} + +template +inline std::unordered_map KeyValuePairsImpl::GetKeyValuePairs() const { + std::unordered_map out; + + size_t num_pairs = 0; + const char* const* keys = nullptr; + const char* const* values = nullptr; + GetApi().GetKeyValuePairs(this->p_, &keys, &values, &num_pairs); + if (num_pairs > 0) { + out.reserve(num_pairs); + for (size_t i = 0; i < num_pairs; ++i) { + out.emplace(keys[i], values[i]); + } + } + + return out; +} + +template +inline void KeyValuePairsImpl::GetKeyValuePairs(std::vector& keys, + std::vector& values) const { + keys.clear(); + values.clear(); + + size_t num_pairs = 0; + const char* const* keys_ptr = nullptr; + const char* const* values_ptr = nullptr; + GetApi().GetKeyValuePairs(this->p_, &keys_ptr, &values_ptr, &num_pairs); + if (num_pairs > 0) { + keys.resize(num_pairs); + values.resize(num_pairs); + std::copy(keys_ptr, keys_ptr + num_pairs, keys.begin()); + std::copy(values_ptr, values_ptr + num_pairs, values.begin()); + } +} +} // namespace detail + +inline KeyValuePairs::KeyValuePairs() { + GetApi().CreateKeyValuePairs(&p_); +} + +inline KeyValuePairs::KeyValuePairs(const std::unordered_map& kv_pairs) { + GetApi().CreateKeyValuePairs(&p_); + for (const auto& kv : kv_pairs) { + GetApi().AddKeyValuePair(this->p_, kv.first.c_str(), kv.second.c_str()); + } +} + +inline void KeyValuePairs::Add(const char* key, const char* value) { + GetApi().AddKeyValuePair(this->p_, key, value); +} + +inline void KeyValuePairs::Remove(const char* key) { + GetApi().RemoveKeyValuePair(this->p_, key); +} + +namespace detail { +template +inline OrtHardwareDeviceType HardwareDeviceImpl::Type() const { + return GetApi().HardwareDevice_Type(this->p_); +} + +template +inline uint32_t HardwareDeviceImpl::VendorId() const { + return GetApi().HardwareDevice_VendorId(this->p_); +} + +template +inline uint32_t HardwareDeviceImpl::DeviceId() const { + return GetApi().HardwareDevice_DeviceId(this->p_); +} + +template +inline const char* HardwareDeviceImpl::Vendor() const { + return GetApi().HardwareDevice_Vendor(this->p_); +} + +template +inline ConstKeyValuePairs HardwareDeviceImpl::Metadata() const { + return ConstKeyValuePairs{GetApi().HardwareDevice_Metadata(this->p_)}; +} + +template +inline const char* EpDeviceImpl::EpName() const { + return GetApi().EpDevice_EpName(this->p_); +} + +template +inline const char* EpDeviceImpl::EpVendor() const { + return GetApi().EpDevice_EpVendor(this->p_); +} + +template +inline ConstKeyValuePairs EpDeviceImpl::EpMetadata() const { + return ConstKeyValuePairs(GetApi().EpDevice_EpMetadata(this->p_)); +} + +template +inline ConstKeyValuePairs EpDeviceImpl::EpOptions() const { + return ConstKeyValuePairs(GetApi().EpDevice_EpOptions(this->p_)); +} + +template +inline ConstHardwareDevice EpDeviceImpl::Device() const { + return ConstHardwareDevice(GetApi().EpDevice_Device(this->p_)); +} +} // namespace detail + +inline EpDevice::EpDevice(OrtEpFactory& ep_factory, ConstHardwareDevice& hardware_device, + ConstKeyValuePairs ep_metadata, ConstKeyValuePairs ep_options) { + ThrowOnError(GetEpApi().CreateEpDevice(&ep_factory, hardware_device, ep_metadata, ep_options, &p_)); +} + +inline Env::Env(OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnv(logging_level, logid, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(OrtLoggingLevel logging_level, const char* logid, OrtLoggingFunction logging_function, void* logger_param) { + ThrowOnError(GetApi().CreateEnvWithCustomLogger(logging_function, logger_param, logging_level, logid, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnvWithGlobalThreadPools(logging_level, logid, tp_options, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env::Env(const OrtThreadingOptions* tp_options, OrtLoggingFunction logging_function, void* logger_param, + OrtLoggingLevel logging_level, _In_ const char* logid) { + ThrowOnError(GetApi().CreateEnvWithCustomLoggerAndGlobalThreadPools(logging_function, logger_param, logging_level, logid, tp_options, &p_)); + if (strcmp(logid, "onnxruntime-node") == 0) { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_NODEJS)); + } else { + ThrowOnError(GetApi().SetLanguageProjection(p_, OrtLanguageProjection::ORT_PROJECTION_CPLUSPLUS)); + } +} + +inline Env& Env::EnableTelemetryEvents() { + ThrowOnError(GetApi().EnableTelemetryEvents(p_)); + return *this; +} + +inline Env& Env::DisableTelemetryEvents() { + ThrowOnError(GetApi().DisableTelemetryEvents(p_)); + return *this; +} + +inline Env& Env::UpdateEnvWithCustomLogLevel(OrtLoggingLevel log_severity_level) { + ThrowOnError(GetApi().UpdateEnvWithCustomLogLevel(p_, log_severity_level)); + return *this; +} + +inline Env& Env::CreateAndRegisterAllocator(const OrtMemoryInfo* mem_info, const OrtArenaCfg* arena_cfg) { + ThrowOnError(GetApi().CreateAndRegisterAllocator(p_, mem_info, arena_cfg)); + return *this; +} + +inline Env& Env::CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo* mem_info, const std::unordered_map& options, const OrtArenaCfg* arena_cfg) { + std::vector keys, values; + auto num_entries = options.size(); + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + for (const auto& entry : options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + ThrowOnError(GetApi().CreateAndRegisterAllocatorV2(p_, provider_type.c_str(), mem_info, arena_cfg, keys.data(), values.data(), num_entries)); + return *this; +} + +inline Env& Env::RegisterExecutionProviderLibrary(const char* registration_name, + const std::basic_string& path) { + ThrowOnError(GetApi().RegisterExecutionProviderLibrary(p_, registration_name, path.c_str())); + return *this; +} + +inline Env& Env::UnregisterExecutionProviderLibrary(const char* registration_name) { + ThrowOnError(GetApi().UnregisterExecutionProviderLibrary(p_, registration_name)); + return *this; +} + +inline std::vector Env::GetEpDevices() const { + size_t num_devices = 0; + const OrtEpDevice* const* device_ptrs = nullptr; + ThrowOnError(GetApi().GetEpDevices(p_, &device_ptrs, &num_devices)); + + std::vector devices; + if (num_devices > 0) { + devices.reserve(num_devices); + for (size_t i = 0; i < num_devices; ++i) { + devices.emplace_back(device_ptrs[i]); + } + } + + return devices; +} + +inline CustomOpDomain::CustomOpDomain(const char* domain) { + ThrowOnError(GetApi().CreateCustomOpDomain(domain, &p_)); +} + +inline void CustomOpDomain::Add(const OrtCustomOp* op) { + ThrowOnError(GetApi().CustomOpDomain_Add(p_, op)); +} + +inline LoraAdapter LoraAdapter::CreateLoraAdapter(const std::basic_string& adapter_path, + OrtAllocator* allocator) { + OrtLoraAdapter* p; + ThrowOnError(GetApi().CreateLoraAdapter(adapter_path.c_str(), allocator, &p)); + return LoraAdapter{p}; +} + +inline LoraAdapter LoraAdapter::CreateLoraAdapterFromArray(const void* bytes, size_t num_bytes, + OrtAllocator* allocator) { + OrtLoraAdapter* p; + ThrowOnError(GetApi().CreateLoraAdapterFromArray(bytes, num_bytes, allocator, &p)); + return LoraAdapter{p}; +} + +inline RunOptions::RunOptions() { + ThrowOnError(GetApi().CreateRunOptions(&p_)); +} + +inline RunOptions& RunOptions::SetRunLogVerbosityLevel(int level) { + ThrowOnError(GetApi().RunOptionsSetRunLogVerbosityLevel(p_, level)); + return *this; +} + +inline RunOptions& RunOptions::SetRunLogSeverityLevel(int level) { + ThrowOnError(GetApi().RunOptionsSetRunLogSeverityLevel(p_, level)); + return *this; +} + +inline int RunOptions::GetRunLogVerbosityLevel() const { + int out; + ThrowOnError(GetApi().RunOptionsGetRunLogVerbosityLevel(p_, &out)); + return out; +} + +inline int RunOptions::GetRunLogSeverityLevel() const { + int out; + ThrowOnError(GetApi().RunOptionsGetRunLogSeverityLevel(p_, &out)); + return out; +} + +inline RunOptions& RunOptions::SetRunTag(const char* run_tag) { + ThrowOnError(GetApi().RunOptionsSetRunTag(p_, run_tag)); + return *this; +} + +inline const char* RunOptions::GetRunTag() const { + const char* out; + ThrowOnError(GetApi().RunOptionsGetRunTag(p_, &out)); + return out; +} + +inline RunOptions& RunOptions::AddConfigEntry(const char* config_key, const char* config_value) { + ThrowOnError(GetApi().AddRunConfigEntry(p_, config_key, config_value)); + return *this; +} + +inline RunOptions& RunOptions::SetTerminate() { + ThrowOnError(GetApi().RunOptionsSetTerminate(p_)); + return *this; +} + +inline RunOptions& RunOptions::UnsetTerminate() { + ThrowOnError(GetApi().RunOptionsUnsetTerminate(p_)); + return *this; +} + +inline RunOptions& RunOptions::AddActiveLoraAdapter(const LoraAdapter& adapter) { + ThrowOnError(GetApi().RunOptionsAddActiveLoraAdapter(p_, adapter)); + return *this; +} + +inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, const SessionOptions& session_options) { + ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); +} + +inline ModelCompilationOptions::ModelCompilationOptions(const Env& env, ConstSessionOptions session_options) { + ThrowOnError(GetCompileApi().CreateModelCompilationOptionsFromSessionOptions(env, session_options, &this->p_)); +} + +inline Status CompileModel(const Env& env, const ModelCompilationOptions& model_compilation_options) { + return Ort::Status(GetCompileApi().CompileModel(env, model_compilation_options)); +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelPath( + const ORTCHAR_T* input_model_path) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelPath(this->p_, input_model_path)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetInputModelFromBuffer( + const void* input_model_data, size_t input_model_data_size) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetInputModelFromBuffer(this->p_, input_model_data, + input_model_data_size)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelPath( + const ORTCHAR_T* output_model_path) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelPath(this->p_, output_model_path)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelExternalInitializersFile( + const ORTCHAR_T* file_path, size_t initializer_size_threshold) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelExternalInitializersFile( + this->p_, + file_path, + initializer_size_threshold)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetOutputModelBuffer( + OrtAllocator* allocator, void** output_model_buffer_ptr, size_t* output_model_buffer_size_ptr) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetOutputModelBuffer(this->p_, allocator, + output_model_buffer_ptr, + output_model_buffer_size_ptr)); + return *this; +} + +inline ModelCompilationOptions& ModelCompilationOptions::SetEpContextEmbedMode( + bool embed_ep_context_in_model) { + Ort::ThrowOnError(GetCompileApi().ModelCompilationOptions_SetEpContextEmbedMode( + this->p_, + embed_ep_context_in_model)); + return *this; +} + +namespace detail { + +template +inline Ort::SessionOptions ConstSessionOptionsImpl::Clone() const { + OrtSessionOptions* out; + ThrowOnError(GetApi().CloneSessionOptions(this->p_, &out)); + return SessionOptions{out}; +} + +template +inline std::string ConstSessionOptionsImpl::GetConfigEntry(const char* config_key) const { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().GetSessionConfigEntry(this->p_, config_key, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline bool ConstSessionOptionsImpl::HasConfigEntry(const char* config_key) const { + int out = 0; + Ort::ThrowOnError(GetApi().HasSessionConfigEntry(this->p_, config_key, &out)); + return static_cast(out); +} + +template +inline std::string ConstSessionOptionsImpl::GetConfigEntryOrDefault(const char* config_key, + const std::string& def) const { + if (!this->HasConfigEntry(config_key)) { + return def; + } + + return this->GetConfigEntry(config_key); +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetIntraOpNumThreads(int intra_op_num_threads) { + ThrowOnError(GetApi().SetIntraOpNumThreads(this->p_, intra_op_num_threads)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetInterOpNumThreads(int inter_op_num_threads) { + ThrowOnError(GetApi().SetInterOpNumThreads(this->p_, inter_op_num_threads)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetGraphOptimizationLevel(GraphOptimizationLevel graph_optimization_level) { + ThrowOnError(GetApi().SetSessionGraphOptimizationLevel(this->p_, graph_optimization_level)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetDeterministicCompute(bool value) { + ThrowOnError(GetApi().SetDeterministicCompute(this->p_, value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetOptimizedModelFilePath(const ORTCHAR_T* optimized_model_filepath) { + ThrowOnError(GetApi().SetOptimizedModelFilePath(this->p_, optimized_model_filepath)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableProfiling(const ORTCHAR_T* profile_file_prefix) { + ThrowOnError(GetApi().EnableProfiling(this->p_, profile_file_prefix)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableProfiling() { + ThrowOnError(GetApi().DisableProfiling(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableOrtCustomOps() { + ThrowOnError(GetApi().EnableOrtCustomOps(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableMemPattern() { + ThrowOnError(GetApi().EnableMemPattern(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableMemPattern() { + ThrowOnError(GetApi().DisableMemPattern(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::EnableCpuMemArena() { + ThrowOnError(GetApi().EnableCpuMemArena(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisableCpuMemArena() { + ThrowOnError(GetApi().DisableCpuMemArena(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetExecutionMode(ExecutionMode execution_mode) { + ThrowOnError(GetApi().SetSessionExecutionMode(this->p_, execution_mode)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLoadCancellationFlag(bool value) { + ThrowOnError(GetApi().SessionOptionsSetLoadCancellationFlag(this->p_, value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLogId(const char* logid) { + ThrowOnError(GetApi().SetSessionLogId(this->p_, logid)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetLogSeverityLevel(int level) { + ThrowOnError(GetApi().SetSessionLogSeverityLevel(this->p_, level)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::Add(OrtCustomOpDomain* custom_op_domain) { + ThrowOnError(GetApi().AddCustomOpDomain(this->p_, custom_op_domain)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddConfigEntry(const char* config_key, const char* config_value) { + ThrowOnError(GetApi().AddSessionConfigEntry(this->p_, config_key, config_value)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddInitializer(const char* name, const OrtValue* ort_val) { + ThrowOnError(GetApi().AddInitializer(this->p_, name, ort_val)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::DisablePerSessionThreads() { + ThrowOnError(GetApi().DisablePerSessionThreads(this->p_)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializers(const std::vector& names, + const std::vector& ort_values) { + const size_t inputs_num = names.size(); + if (inputs_num != ort_values.size()) { + ORT_CXX_API_THROW("Expecting names and ort_values to have the same length", ORT_INVALID_ARGUMENT); + } + std::vector names_ptr; + std::vector ort_values_ptrs; + names_ptr.reserve(inputs_num); + ort_values_ptrs.reserve(inputs_num); + for (size_t i = 0; i < inputs_num; ++i) { + names_ptr.push_back(names[i].c_str()); + ort_values_ptrs.push_back(ort_values[i]); + } + ThrowOnError(GetApi().AddExternalInitializers(this->p_, names_ptr.data(), ort_values_ptrs.data(), inputs_num)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AddExternalInitializersFromFilesInMemory(const std::vector>& file_names, + const std::vector& buffer_array, + const std::vector& file_lengths) { + const size_t inputs_num = file_names.size(); + if (inputs_num != buffer_array.size()) { + ORT_CXX_API_THROW("Expecting names and buffer_array to have the same length", ORT_INVALID_ARGUMENT); + } + if (inputs_num != file_lengths.size()) { + ORT_CXX_API_THROW("Expecting names and file_lengths to have the same length", ORT_INVALID_ARGUMENT); + } + std::vector names_ptr; + names_ptr.reserve(inputs_num); + for (size_t i = 0; i < inputs_num; ++i) { + names_ptr.push_back(file_names[i].c_str()); + } + ThrowOnError(GetApi().AddExternalInitializersFromFilesInMemory(this->p_, names_ptr.data(), buffer_array.data(), + file_lengths.data(), inputs_num)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA(const OrtCUDAProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CUDA_V2(const OrtCUDAProviderOptionsV2& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CUDA_V2(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_ROCM(const OrtROCMProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_ROCM(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT(const OrtTensorRTProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_TensorRT_V2(const OrtTensorRTProviderOptionsV2& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_TensorRT_V2(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_MIGraphX(const OrtMIGraphXProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_MIGraphX(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_CANN(const OrtCANNProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_CANN(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_Dnnl(const OrtDnnlProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_Dnnl(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider( + const std::string& provider_name, + const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider(this->p_, provider_name.c_str(), + keys.data(), values.data(), num_entries)); + + return *this; +} + +namespace { +template +void SessionOptionsAppendEP(detail::SessionOptionsImpl& session_options, + Env& env, const std::vector& ep_devices, + const std::vector& ep_options_keys, + const std::vector& ep_options_values) { + std::vector ep_devices_ptrs; + ep_devices_ptrs.reserve(ep_devices.size()); + for (const auto& ep_device : ep_devices) { + ep_devices_ptrs.push_back(ep_device); + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_V2( + session_options, env, ep_devices_ptrs.data(), ep_devices_ptrs.size(), + ep_options_keys.data(), ep_options_values.data(), ep_options_keys.size())); +} +} // namespace + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( + Env& env, const std::vector& ep_devices, const KeyValuePairs& ep_options) { + std::vector ep_options_keys, ep_options_values; + ep_options.GetKeyValuePairs(ep_options_keys, ep_options_values); + + SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_V2( + Env& env, const std::vector& ep_devices, + const std::unordered_map& ep_options) { + std::vector ep_options_keys, ep_options_values; + ep_options_keys.reserve(ep_options.size()); + ep_options_values.reserve(ep_options.size()); + + for (const auto& [key, value] : ep_options) { + ep_options_keys.push_back(key.c_str()); + ep_options_values.push_back(value.c_str()); + } + + SessionOptionsAppendEP(*this, env, ep_devices, ep_options_keys, ep_options_values); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(OrtExecutionProviderDevicePolicy policy) { + ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicy(this->p_, policy)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetEpSelectionPolicy(EpSelectionDelegate delegate, void* state) { + ThrowOnError(GetApi().SessionOptionsSetEpSelectionPolicyDelegate(this->p_, delegate, state)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomCreateThreadFn(OrtCustomCreateThreadFn ort_custom_create_thread_fn) { + ThrowOnError(GetApi().SessionOptionsSetCustomCreateThreadFn(this->p_, ort_custom_create_thread_fn)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomThreadCreationOptions(void* ort_custom_thread_creation_options) { + ThrowOnError(GetApi().SessionOptionsSetCustomThreadCreationOptions(this->p_, ort_custom_thread_creation_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::SetCustomJoinThreadFn(OrtCustomJoinThreadFn ort_custom_join_thread_fn) { + ThrowOnError(GetApi().SessionOptionsSetCustomJoinThreadFn(this->p_, ort_custom_join_thread_fn)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO(const OrtOpenVINOProviderOptions& provider_options) { + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO(this->p_, &provider_options)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_OpenVINO_V2(const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_OpenVINO_V2(this->p_, + keys.data(), values.data(), num_entries)); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::AppendExecutionProvider_VitisAI(const std::unordered_map& provider_options) { + auto num_entries = provider_options.size(); + std::vector keys, values; + if (num_entries > 0) { + keys.reserve(num_entries); + values.reserve(num_entries); + + for (const auto& entry : provider_options) { + keys.push_back(entry.first.c_str()); + values.push_back(entry.second.c_str()); + } + } + + ThrowOnError(GetApi().SessionOptionsAppendExecutionProvider_VitisAI(this->p_, keys.data(), values.data(), num_entries)); + + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsLibrary(const ORTCHAR_T* library_name, + const CustomOpConfigs& custom_op_configs) { + // Add custom op config entries before registering the custom op library. Otherwise, the config entries _may_ be ignored by + // the custom op library. + for (const auto& config_iter : custom_op_configs.GetFlattenedConfigs()) { + AddConfigEntry(config_iter.first.c_str(), config_iter.second.c_str()); + } + + ThrowOnError(GetApi().RegisterCustomOpsLibrary_V2(this->p_, library_name)); + return *this; +} + +template +inline SessionOptionsImpl& SessionOptionsImpl::RegisterCustomOpsUsingFunction(const char* registration_function_name) { + ThrowOnError(GetApi().RegisterCustomOpsUsingFunction(this->p_, registration_function_name)); + return *this; +} + +/// Session +template +inline size_t ConstSessionImpl::GetInputCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetInputCount(this->p_, &out)); + return out; +} + +template +inline size_t ConstSessionImpl::GetOutputCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetOutputCount(this->p_, &out)); + return out; +} + +template +inline size_t ConstSessionImpl::GetOverridableInitializerCount() const { + size_t out; + ThrowOnError(GetApi().SessionGetOverridableInitializerCount(this->p_, &out)); + return out; +} + +template +inline std::vector ConstSessionImpl::GetInputNames() const { + AllocatorWithDefaultOptions allocator; + + auto num_inputs = GetInputCount(); + std::vector input_names; + input_names.reserve(num_inputs); + + for (size_t i = 0; i < num_inputs; ++i) { + char* name = nullptr; + ThrowOnError(GetApi().SessionGetInputName(this->p_, i, allocator, &name)); + input_names.push_back(name); + allocator.Free(name); + } + + return input_names; +} + +template +inline std::vector ConstSessionImpl::GetOutputNames() const { + AllocatorWithDefaultOptions allocator; + + auto num_inputs = GetOutputCount(); + std::vector output_names; + output_names.reserve(num_inputs); + + for (size_t i = 0; i < num_inputs; ++i) { + char* name = nullptr; + ThrowOnError(GetApi().SessionGetOutputName(this->p_, i, allocator, &name)); + output_names.push_back(name); + allocator.Free(name); + } + + return output_names; +} + +template +inline std::vector ConstSessionImpl::GetOverridableInitializerNames() const { + AllocatorWithDefaultOptions allocator; + + auto num_initializers = GetOverridableInitializerCount(); + std::vector initializer_names; + initializer_names.reserve(num_initializers); + + for (size_t i = 0; i < num_initializers; ++i) { + char* name = nullptr; + ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, i, allocator, &name)); + initializer_names.push_back(name); + } + + return initializer_names; +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetInputNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetInputName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetOutputNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetOutputName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline AllocatedStringPtr ConstSessionImpl::GetOverridableInitializerNameAllocated(size_t index, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().SessionGetOverridableInitializerName(this->p_, index, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline uint64_t ConstSessionImpl::GetProfilingStartTimeNs() const { + uint64_t out; + ThrowOnError(GetApi().SessionGetProfilingStartTimeNs(this->p_, &out)); + return out; +} + +template +inline ModelMetadata ConstSessionImpl::GetModelMetadata() const { + OrtModelMetadata* out; + ThrowOnError(GetApi().SessionGetModelMetadata(this->p_, &out)); + return ModelMetadata{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetInputTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetInputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetOutputTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetOutputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo ConstSessionImpl::GetOverridableInitializerTypeInfo(size_t index) const { + OrtTypeInfo* out; + ThrowOnError(GetApi().SessionGetOverridableInitializerTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +#if !defined(ORT_MINIMAL_BUILD) +template +inline int ConstSessionImpl::GetOpset(const std::string& domain) const { + int opset; + ThrowOnError(GetModelEditorApi().SessionGetOpsetForDomain(this->p_, domain.c_str(), &opset)); + return opset; +} +#endif // !defined(ORT_MINIMAL_BUILD) + +template +std::vector ConstSessionImpl::GetInputs() const { + const std::vector input_names = GetInputNames(); + + std::vector inputs; + inputs.reserve(input_names.size()); + + for (size_t i = 0; i < input_names.size(); ++i) { + auto type_info = GetInputTypeInfo(i); + inputs.emplace_back(ValueInfo{input_names[i], type_info.GetConst()}); + } + + return inputs; +} + +template +std::vector ConstSessionImpl::GetOutputs() const { + const std::vector output_names = GetOutputNames(); + + std::vector outputs; + outputs.reserve(output_names.size()); + + for (size_t i = 0; i < output_names.size(); ++i) { + auto type_info = GetOutputTypeInfo(i); + outputs.emplace_back(ValueInfo{output_names[i], type_info.GetConst()}); + } + + return outputs; +} + +template +inline std::vector SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, size_t output_count) { + std::vector output_values; + output_values.reserve(output_count); + for (size_t i = 0; i < output_count; i++) + output_values.emplace_back(nullptr); + Run(run_options, input_names, input_values, input_count, output_names, output_values.data(), output_count); + return output_values; +} + +template +inline void SessionImpl::Run(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count) { + static_assert(sizeof(Value) == sizeof(OrtValue*), "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + ThrowOnError(GetApi().Run(this->p_, run_options, input_names, ort_input_values, input_count, output_names, output_count, ort_output_values)); +} + +template +inline void SessionImpl::Run(const RunOptions& run_options, const IoBinding& io_binding) { + ThrowOnError(GetApi().RunWithBinding(this->p_, run_options, io_binding)); +} + +template +inline void SessionImpl::RunAsync(const RunOptions& run_options, const char* const* input_names, const Value* input_values, size_t input_count, + const char* const* output_names, Value* output_values, size_t output_count, RunAsyncCallbackFn callback, void* user_data) { + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + ThrowOnError(GetApi().RunAsync(this->p_, run_options, input_names, + ort_input_values, input_count, output_names, output_count, + ort_output_values, callback, user_data)); +} + +template +inline AllocatedStringPtr SessionImpl::EndProfilingAllocated(OrtAllocator* allocator) { + char* out = nullptr; + ThrowOnError(GetApi().SessionEndProfiling(this->p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +template +inline void SessionImpl::SetEpDynamicOptions(const char* const* keys, const char* const* values, size_t kv_len) { + ThrowOnError(GetApi().SetEpDynamicOptions(this->p_, keys, values, kv_len)); +} + +#if !defined(ORT_MINIMAL_BUILD) +template +inline void SessionImpl::FinalizeModelEditorSession(const Model& model, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetModelEditorApi().ApplyModelToModelEditorSession(this->p_, model)); + ThrowOnError(GetModelEditorApi().FinalizeModelEditorSession(this->p_, options, prepacked_weights_container)); +} +#endif // #if !defined(ORT_MINIMAL_BUILD) + +} // namespace detail + +inline SessionOptions::SessionOptions() { + ThrowOnError(GetApi().CreateSessionOptions(&this->p_)); +} + +/// CustomOpConfigs +inline std::string detail::MakeCustomOpConfigEntryKey(const char* custom_op_name, const char* config) { + std::string config_key = "custom_op."; + + config_key += custom_op_name; + config_key += "."; + config_key += config; + + return config_key; +} + +inline CustomOpConfigs& CustomOpConfigs::AddConfig(const char* custom_op_name, const char* config_key, const char* config_value) { + const std::string full_flat_key = detail::MakeCustomOpConfigEntryKey(custom_op_name, config_key); + flat_configs_[full_flat_key] = config_value; + return *this; +} + +inline const std::unordered_map& CustomOpConfigs::GetFlattenedConfigs() const { + return flat_configs_; +} + +inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options) { + ThrowOnError(GetApi().CreateSession(env, model_path, options, &this->p_)); +} + +inline Session::Session(const Env& env, const ORTCHAR_T* model_path, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetApi().CreateSessionWithPrepackedWeightsContainer(env, model_path, options, prepacked_weights_container, &this->p_)); +} + +inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, const SessionOptions& options) { + ThrowOnError(GetApi().CreateSessionFromArray(env, model_data, model_data_length, options, &this->p_)); +} + +inline Session::Session(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options, OrtPrepackedWeightsContainer* prepacked_weights_container) { + ThrowOnError(GetApi().CreateSessionFromArrayWithPrepackedWeightsContainer(env, model_data, model_data_length, options, + prepacked_weights_container, &this->p_)); +} + +#if !defined(ORT_MINIMAL_BUILD) +inline Session::Session(const Env& env, const Model& model, const SessionOptions& options) { + ThrowOnError(GetModelEditorApi().CreateSessionFromModel(env, model.GetConst(), options, &this->p_)); +} + +// static +inline Session Session::CreateModelEditorSession(const Env& env, const ORTCHAR_T* model_path, + const SessionOptions& options) { + OrtSession* session = nullptr; + ThrowOnError(GetModelEditorApi().CreateModelEditorSession(env, model_path, options, &session)); + return Session(session); +} + +// static +inline Session Session::CreateModelEditorSession(const Env& env, const void* model_data, size_t model_data_length, + const SessionOptions& options) { + OrtSession* session = nullptr; + ThrowOnError(GetModelEditorApi().CreateModelEditorSessionFromArray(env, model_data, model_data_length, options, + &session)); + return Session(session); +} + +void FinalizeModelEditorSession(const Model& model, const SessionOptions& options, + OrtPrepackedWeightsContainer* prepacked_weights_container); +#endif // #if !defined(ORT_MINIMAL_BUILD) + +inline AllocatedStringPtr ModelMetadata::GetProducerNameAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetProducerName(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetGraphNameAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetGraphName(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetDomainAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetDomain(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr Ort::ModelMetadata::GetDescriptionAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetDescription(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::GetGraphDescriptionAllocated(OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataGetGraphDescription(p_, allocator, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline AllocatedStringPtr ModelMetadata::LookupCustomMetadataMapAllocated(const char* key, OrtAllocator* allocator) const { + char* out; + ThrowOnError(GetApi().ModelMetadataLookupCustomMetadataMap(p_, allocator, key, &out)); + return AllocatedStringPtr(out, detail::AllocatedFree(allocator)); +} + +inline std::vector ModelMetadata::GetCustomMetadataMapKeysAllocated(OrtAllocator* allocator) const { + auto deletor = detail::AllocatedFree(allocator); + std::vector result; + + char** out = nullptr; + int64_t num_keys = 0; + ThrowOnError(GetApi().ModelMetadataGetCustomMetadataMapKeys(p_, allocator, &out, &num_keys)); + if (num_keys <= 0) { + return result; + } + + // array of pointers will be freed + std::unique_ptr array_guard(out, deletor); + // reserve may throw + auto strings_deletor = [&deletor, num_keys](char** out) { for(int64_t i = 0; i < num_keys; ++i) deletor(out[i]); }; + std::unique_ptr strings_guard(out, strings_deletor); + result.reserve(static_cast(num_keys)); + strings_guard.release(); + for (int64_t i = 0; i < num_keys; ++i) { + result.push_back(AllocatedStringPtr(out[i], deletor)); + } + + return result; +} + +inline int64_t ModelMetadata::GetVersion() const { + int64_t out; + ThrowOnError(GetApi().ModelMetadataGetVersion(p_, &out)); + return out; +} + +inline TensorTypeAndShapeInfo::TensorTypeAndShapeInfo(ONNXTensorElementDataType element_type, + const std::vector& dims, + const std::vector* symbolic_dims) { + ThrowOnError(GetApi().CreateTensorTypeAndShapeInfo(&p_)); + ThrowOnError(GetApi().SetTensorElementType(p_, element_type)); + ThrowOnError(GetApi().SetDimensions(p_, dims.data(), dims.size())); + + if (symbolic_dims) { + std::vector symbolic_dims_cstr; + symbolic_dims_cstr.reserve(symbolic_dims->size()); + std::transform(symbolic_dims->begin(), symbolic_dims->end(), std::back_inserter(symbolic_dims_cstr), + [](const std::string& s) { return s.c_str(); }); + ThrowOnError(GetApi().SetSymbolicDimensions(p_, symbolic_dims_cstr.data(), symbolic_dims_cstr.size())); + } +} + +#if !defined(ORT_MINIMAL_BUILD) +// static +inline TypeInfo TypeInfo::CreateTensorInfo(ConstTensorTypeAndShapeInfo tensor_type_and_shape_info) { + OrtTypeInfo* output = nullptr; + ThrowOnError(GetModelEditorApi().CreateTensorTypeInfo(tensor_type_and_shape_info, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateSparseTensorInfo(ConstTensorTypeAndShapeInfo sparse_tensor_type_and_shape_info) { + OrtTypeInfo* output = nullptr; + ThrowOnError(GetModelEditorApi().CreateSparseTensorTypeInfo(sparse_tensor_type_and_shape_info, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateSequenceTypeInfo(ConstTypeInfo sequence_type) { + OrtTypeInfo* output; + ThrowOnError(GetModelEditorApi().CreateSequenceTypeInfo(sequence_type, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateMapTypeInfo(ONNXTensorElementDataType key_type, ConstTypeInfo value_type) { + OrtTypeInfo* output; + ThrowOnError(GetModelEditorApi().CreateMapTypeInfo(key_type, value_type, &output)); + return TypeInfo{output}; +} + +// static +inline TypeInfo TypeInfo::CreateOptionalTypeInfo(ConstTypeInfo contained_type) { + OrtTypeInfo* output; + ThrowOnError(GetModelEditorApi().CreateOptionalTypeInfo(contained_type, &output)); + return TypeInfo{output}; +} +#endif // #if !defined(ORT_MINIMAL_BUILD) + +namespace detail { + +template +inline ONNXTensorElementDataType TensorTypeAndShapeInfoImpl::GetElementType() const { + ONNXTensorElementDataType out; + ThrowOnError(GetApi().GetTensorElementType(this->p_, &out)); + return out; +} + +template +inline size_t TensorTypeAndShapeInfoImpl::GetElementCount() const { + size_t out; + ThrowOnError(GetApi().GetTensorShapeElementCount(this->p_, &out)); + return static_cast(out); +} + +template +inline size_t TensorTypeAndShapeInfoImpl::GetDimensionsCount() const { + size_t out; + ThrowOnError(GetApi().GetDimensionsCount(this->p_, &out)); + return out; +} + +template +inline void TensorTypeAndShapeInfoImpl::GetDimensions(int64_t* values, size_t values_count) const { + ThrowOnError(GetApi().GetDimensions(this->p_, values, values_count)); +} + +template +inline void TensorTypeAndShapeInfoImpl::GetSymbolicDimensions(const char** values, size_t values_count) const { + ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, values, values_count)); +} + +template +inline std::vector TensorTypeAndShapeInfoImpl::GetSymbolicDimensions() const { + std::vector out(GetDimensionsCount(), nullptr); + ThrowOnError(GetApi().GetSymbolicDimensions(this->p_, out.data(), out.size())); + return out; +} + +template +inline std::vector TensorTypeAndShapeInfoImpl::GetShape() const { + std::vector out(GetDimensionsCount(), -1); + ThrowOnError(GetApi().GetDimensions(this->p_, out.data(), out.size())); + return out; +} + +template +inline ConstTensorTypeAndShapeInfo TypeInfoImpl::GetTensorTypeAndShapeInfo() const { + const OrtTensorTypeAndShapeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToTensorInfo(this->p_, &out)); + return ConstTensorTypeAndShapeInfo{out}; +} + +template +inline ConstSequenceTypeInfo TypeInfoImpl::GetSequenceTypeInfo() const { + const OrtSequenceTypeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToSequenceTypeInfo(this->p_, &out)); + return ConstSequenceTypeInfo{out}; +} + +template +inline ConstMapTypeInfo TypeInfoImpl::GetMapTypeInfo() const { + const OrtMapTypeInfo* out; + ThrowOnError(GetApi().CastTypeInfoToMapTypeInfo(this->p_, &out)); + return ConstMapTypeInfo{out}; +} + +template +inline ONNXType TypeInfoImpl::GetONNXType() const { + ONNXType out; + ThrowOnError(GetApi().GetOnnxTypeFromTypeInfo(this->p_, &out)); + return out; +} + +template +inline TypeInfo SequenceTypeInfoImpl::GetSequenceElementType() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetSequenceElementType(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline TypeInfo OptionalTypeInfoImpl::GetOptionalElementType() const { + OrtTypeInfo* info; + ThrowOnError(GetApi().GetOptionalContainedTypeInfo(this->p_, &info)); + return TypeInfo{info}; +} + +template +inline ONNXTensorElementDataType MapTypeInfoImpl::GetMapKeyType() const { + ONNXTensorElementDataType out; + ThrowOnError(GetApi().GetMapKeyType(this->p_, &out)); + return out; +} + +template +inline TypeInfo MapTypeInfoImpl::GetMapValueType() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetMapValueType(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline ConstOptionalTypeInfo TypeInfoImpl::GetOptionalTypeInfo() const { + const OrtOptionalTypeInfo* info; + ThrowOnError(GetApi().CastTypeInfoToOptionalTypeInfo(this->p_, &info)); + return ConstOptionalTypeInfo{info}; +} + +} // namespace detail + +namespace detail { + +template +template +inline void ConstValueImpl::GetOpaqueData(const char* domain, const char* type_name, R& out) const { + ThrowOnError(GetApi().GetOpaqueValue(domain, type_name, this->p_, &out, sizeof(R))); +} + +template +inline bool ConstValueImpl::IsTensor() const { + int out; + ThrowOnError(GetApi().IsTensor(this->p_, &out)); + return out != 0; +} + +template +inline bool ConstValueImpl::HasValue() const { + int out; + ThrowOnError(GetApi().HasValue(this->p_, &out)); + return out != 0; +} + +template +inline size_t ConstValueImpl::GetCount() const { + size_t out; + ThrowOnError(GetApi().GetValueCount(this->p_, &out)); + return out; +} + +template +inline Value ConstValueImpl::GetValue(int index, OrtAllocator* allocator) const { + OrtValue* out; + ThrowOnError(GetApi().GetValue(this->p_, index, allocator, &out)); + return Value{out}; +} + +template +inline size_t ConstValueImpl::GetStringTensorDataLength() const { + size_t out; + ThrowOnError(GetApi().GetStringTensorDataLength(this->p_, &out)); + return out; +} + +template +inline size_t ConstValueImpl::GetStringTensorElementLength(size_t element_index) const { + size_t out; + ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &out)); + return out; +} + +template +template +inline const R* ConstValueImpl::GetTensorData() const { + R* out; + ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), (void**)&out)); + return out; +} + +template +inline const void* ConstValueImpl::GetTensorRawData() const { + void* out; + ThrowOnError(GetApi().GetTensorMutableData(const_cast(this->p_), &out)); + return out; +} + +template +inline TypeInfo ConstValueImpl::GetTypeInfo() const { + OrtTypeInfo* output; + ThrowOnError(GetApi().GetTypeInfo(this->p_, &output)); + return TypeInfo{output}; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetTensorTypeAndShapeInfo() const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetTensorTypeAndShape(this->p_, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +inline ConstMemoryInfo ConstValueImpl::GetTensorMemoryInfo() const { + const OrtMemoryInfo* mem_info; + ThrowOnError(GetApi().GetTensorMemoryInfo(this->p_, &mem_info)); + return ConstMemoryInfo(mem_info); +} + +template +inline void ConstValueImpl::GetStringTensorElement(size_t buffer_length, size_t element_index, void* buffer) const { + ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, buffer)); +} + +template +inline std::string ConstValueImpl::GetStringTensorElement(size_t element_index) const { + size_t buffer_length; + ThrowOnError(GetApi().GetStringTensorElementLength(this->p_, element_index, &buffer_length)); + + std::string s; + s.resize(buffer_length); + ThrowOnError(GetApi().GetStringTensorElement(this->p_, buffer_length, element_index, &s[0])); + return s; +} + +template +inline void ConstValueImpl::GetStringTensorContent(void* buffer, size_t buffer_length, size_t* offsets, size_t offsets_count) const { + ThrowOnError(GetApi().GetStringTensorContent(this->p_, buffer, buffer_length, offsets, offsets_count)); +} + +#if !defined(DISABLE_SPARSE_TENSORS) +template +inline OrtSparseFormat ConstValueImpl::GetSparseFormat() const { + OrtSparseFormat format; + ThrowOnError(GetApi().GetSparseTensorFormat(this->p_, &format)); + return format; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorValuesTypeAndShapeInfo() const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetSparseTensorValuesTypeAndShape(this->p_, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +inline TensorTypeAndShapeInfo ConstValueImpl::GetSparseTensorIndicesTypeShapeInfo(OrtSparseIndicesFormat indices_format) const { + OrtTensorTypeAndShapeInfo* output; + ThrowOnError(GetApi().GetSparseTensorIndicesTypeShape(this->p_, indices_format, &output)); + return TensorTypeAndShapeInfo{output}; +} + +template +template +inline const R* ConstValueImpl::GetSparseTensorIndicesData(OrtSparseIndicesFormat indices_format, size_t& num_indices) const { + const void* out; + ThrowOnError(GetApi().GetSparseTensorIndices(this->p_, indices_format, &num_indices, &out)); + return reinterpret_cast(out); +} + +template +inline bool ConstValueImpl::IsSparseTensor() const { + int out; + ThrowOnError(GetApi().IsSparseTensor(this->p_, &out)); + return out != 0; +} + +template +template +inline const R* ConstValueImpl::GetSparseTensorValues() const { + const void* out; + ThrowOnError(GetApi().GetSparseTensorValues(this->p_, &out)); + return reinterpret_cast(out); +} + +#endif + +template +void ValueImpl::FillStringTensor(const char* const* s, size_t s_len) { + ThrowOnError(GetApi().FillStringTensor(this->p_, s, s_len)); +} + +template +void ValueImpl::FillStringTensorElement(const char* s, size_t index) { + ThrowOnError(GetApi().FillStringTensorElement(this->p_, s, index)); +} + +template +inline char* ValueImpl::GetResizedStringTensorElementBuffer(size_t index, size_t buffer_length) { + char* result; + ThrowOnError(GetApi().GetResizedStringTensorElementBuffer(this->p_, index, buffer_length, &result)); + return result; +} + +template +void* ValueImpl::GetTensorMutableRawData() { + void* out; + ThrowOnError(GetApi().GetTensorMutableData(this->p_, &out)); + return out; +} + +template +template +R* ValueImpl::GetTensorMutableData() { + R* out; + ThrowOnError(GetApi().GetTensorMutableData(this->p_, (void**)&out)); + return out; +} + +template +template +R& ValueImpl::At(const std::vector& location) { + static_assert(!std::is_same::value, "this api does not support std::string"); + R* out; + ThrowOnError(GetApi().TensorAt(this->p_, location.data(), location.size(), (void**)&out)); + return *out; +} + +#if !defined(DISABLE_SPARSE_TENSORS) +template +void ValueImpl::UseCooIndices(int64_t* indices_data, size_t indices_num) { + ThrowOnError(GetApi().UseCooIndices(this->p_, indices_data, indices_num)); +} + +template +void ValueImpl::UseCsrIndices(int64_t* inner_data, size_t inner_num, int64_t* outer_data, size_t outer_num) { + ThrowOnError(GetApi().UseCsrIndices(this->p_, inner_data, inner_num, outer_data, outer_num)); +} + +template +void ValueImpl::UseBlockSparseIndices(const Shape& indices_shape, int32_t* indices_data) { + ThrowOnError(GetApi().UseBlockSparseIndices(this->p_, indices_shape.shape, indices_shape.shape_len, indices_data)); +} + +template +void ValueImpl::FillSparseTensorCoo(const OrtMemoryInfo* mem_info, const OrtSparseValuesParam& values_param, + const int64_t* indices_data, size_t indices_num) { + ThrowOnError(GetApi().FillSparseTensorCoo(this->p_, mem_info, values_param.values_shape, + values_param.values_shape_len, values_param.data.p_data, + indices_data, indices_num)); +} + +template +void ValueImpl::FillSparseTensorCsr(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const int64_t* inner_indices_data, size_t inner_indices_num, + const int64_t* outer_indices_data, size_t outer_indices_num) { + ThrowOnError(GetApi().FillSparseTensorCsr(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, + inner_indices_data, inner_indices_num, + outer_indices_data, outer_indices_num)); +} + +template +void ValueImpl::FillSparseTensorBlockSparse(const OrtMemoryInfo* data_mem_info, + const OrtSparseValuesParam& values, + const Shape& indices_shape, + const int32_t* indices_data) { + ThrowOnError(GetApi().FillSparseTensorBlockSparse(this->p_, data_mem_info, values.values_shape, values.values_shape_len, values.data.p_data, + indices_shape.shape, indices_shape.shape_len, + indices_data)); +} + +#endif // !defined(DISABLE_SPARSE_TENSORS) + +} // namespace detail + +template +inline Value Value::CreateTensor(const OrtMemoryInfo* info, T* p_data, size_t p_data_element_count, + const int64_t* shape, size_t shape_len) { + return CreateTensor(info, p_data, p_data_element_count * sizeof(T), shape, shape_len, TypeToTensorType::type); +} + +inline Value Value::CreateTensor(const OrtMemoryInfo* info, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorWithDataAsOrtValue(info, p_data, p_data_byte_count, shape, shape_len, type, &out)); + return Value{out}; +} + +inline Value Value::CreateTensor(OrtAllocator* deleter, void* p_data, size_t p_data_byte_count, + const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorWithDataAndDeleterAsOrtValue(deleter, p_data, p_data_byte_count, + shape, shape_len, type, &out)); + return Value{out}; +} + +template +inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len) { + return CreateTensor(allocator, shape, shape_len, TypeToTensorType::type); +} + +inline Value Value::CreateTensor(OrtAllocator* allocator, const int64_t* shape, size_t shape_len, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateTensorAsOrtValue(allocator, shape, shape_len, type, &out)); + return Value{out}; +} + +#if !defined(DISABLE_SPARSE_TENSORS) + +template +inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, T* p_data, const Shape& dense_shape, + const Shape& values_shape) { + return CreateSparseTensor(info, p_data, dense_shape, values_shape, TypeToTensorType::type); +} + +inline Value Value::CreateSparseTensor(const OrtMemoryInfo* info, void* p_data, const Shape& dense_shape, + const Shape& values_shape, ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateSparseTensorWithValuesAsOrtValue(info, p_data, dense_shape.shape, dense_shape.shape_len, + values_shape.shape, values_shape.shape_len, type, + &out)); + return Value{out}; +} + +template +inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape) { + return CreateSparseTensor(allocator, dense_shape, TypeToTensorType::type); +} + +inline Value Value::CreateSparseTensor(OrtAllocator* allocator, const Shape& dense_shape, + ONNXTensorElementDataType type) { + OrtValue* out; + ThrowOnError(GetApi().CreateSparseTensorAsOrtValue(allocator, dense_shape.shape, dense_shape.shape_len, type, &out)); + return Value{out}; +} +#endif // !defined(DISABLE_SPARSE_TENSORS) + +inline Value Value::CreateMap(const Value& keys, const Value& values) { + OrtValue* out; + const OrtValue* inputs[2] = {keys, values}; + ThrowOnError(GetApi().CreateValue(inputs, 2, ONNX_TYPE_MAP, &out)); + return Value{out}; +} + +inline Value Value::CreateSequence(const std::vector& values) { + OrtValue* out; + std::vector values_ort{values.data(), values.data() + values.size()}; + ThrowOnError(GetApi().CreateValue(values_ort.data(), values_ort.size(), ONNX_TYPE_SEQUENCE, &out)); + return Value{out}; +} + +template +inline Value Value::CreateOpaque(const char* domain, const char* type_name, const T& data_container) { + OrtValue* out; + ThrowOnError(GetApi().CreateOpaqueValue(domain, type_name, &data_container, sizeof(T), &out)); + return Value{out}; +} + +// +// Custom OP Inlines +// +inline Logger::Logger(const OrtLogger* logger) : logger_(logger) { + Ort::ThrowOnError(GetApi().Logger_GetLoggingSeverityLevel(this->logger_, &this->cached_severity_level_)); +} + +inline OrtLoggingLevel Logger::GetLoggingSeverityLevel() const noexcept { + return cached_severity_level_; +} + +inline Status Logger::LogMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, int line_number, + const char* func_name, const char* message) const noexcept { + OrtStatus* status = GetApi().Logger_LogMessage(logger_, log_severity_level, message, file_path, line_number, + func_name); + return Status{status}; +} + +// Disable warnings about the format string not being a literal (-Wformat-nonliteral and -Wformat-security) +// for gcc and clang. The alternative is to use actual C-style variadic parameters and apply +// __attribute__(format(printf...)), which does not work with variadic templates. +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wformat-nonliteral" +#pragma GCC diagnostic ignored "-Wformat-security" +#elif defined(__clang__) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wformat-nonliteral" +#pragma clang diagnostic ignored "-Wformat-security" +#endif +template +inline Status Logger::LogFormattedMessage(OrtLoggingLevel log_severity_level, const ORTCHAR_T* file_path, + int line_number, const char* func_name, const char* format, + Args&&... args) const noexcept { + int msg_len = std::snprintf(nullptr, 0U, format, std::forward(args)...); + + if (msg_len < 0) { // Formatting error + return Status("Failed to log message due to formatting error", OrtErrorCode::ORT_FAIL); + } + + OrtStatus* status = nullptr; + const size_t buffer_size = static_cast(msg_len) + 1U; + + constexpr size_t kStackBufferSize = 1024; + + if (buffer_size < kStackBufferSize) { + char buffer[kStackBufferSize]; + snprintf(buffer, kStackBufferSize, format, std::forward(args)...); + status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer, file_path, line_number, func_name); + } else { + // std::make_unique is only supported starting at C++14. +#if (__cplusplus >= 201402L) || (_MSC_VER >= 1900) + auto buffer = std::make_unique(buffer_size); +#else + std::unique_ptr buffer(new char[buffer_size]); +#endif + std::snprintf(buffer.get(), buffer_size, format, std::forward(args)...); + status = GetApi().Logger_LogMessage(logger_, log_severity_level, buffer.get(), file_path, line_number, func_name); + } + + return Status{status}; +} +// Re-enable -Wformat-nonliteral and -Wformat-security +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#elif defined(__clang__) +#pragma clang diagnostic pop +#endif + +inline KernelContext::KernelContext(OrtKernelContext* context) : ctx_(context) { +} + +inline size_t KernelContext::GetInputCount() const { + size_t out = 0; + Ort::ThrowOnError(GetApi().KernelContext_GetInputCount(ctx_, &out)); + return out; +} + +inline size_t KernelContext::GetOutputCount() const { + size_t out = 0; + Ort::ThrowOnError(GetApi().KernelContext_GetOutputCount(ctx_, &out)); + return out; +} + +inline ConstValue KernelContext::GetInput(size_t index) const { + const OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetInput(ctx_, index, &out)); + return ConstValue{out}; +} + +inline UnownedValue KernelContext::GetOutput(size_t index, const int64_t* dim_values, size_t dim_count) const { + OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dim_values, dim_count, &out)); + return UnownedValue(out); +} + +inline UnownedValue KernelContext::GetOutput(size_t index, const std::vector& dims) const { + OrtValue* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetOutput(ctx_, index, dims.data(), dims.size(), &out)); + return UnownedValue(out); +} + +inline void* KernelContext::GetGPUComputeStream() const { + void* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetGPUComputeStream(ctx_, &out)); + return out; +} + +inline OrtAllocator* KernelContext::GetAllocator(const OrtMemoryInfo& memory_info) const { + OrtAllocator* out = nullptr; + Ort::ThrowOnError(GetApi().KernelContext_GetAllocator(ctx_, &memory_info, &out)); + return out; +} + +inline Logger KernelContext::GetLogger() const { + const OrtLogger* out = nullptr; + ThrowOnError(GetApi().KernelContext_GetLogger(this->ctx_, &out)); + return Logger{out}; +} + +inline void KernelContext::ParallelFor(void (*fn)(void*, size_t), size_t total, size_t num_batch, void* usr_data) const { + ThrowOnError(GetApi().KernelContext_ParallelFor(ctx_, fn, total, num_batch, usr_data)); +} + +inline OpAttr::OpAttr(const char* name, const void* data, int len, OrtOpAttrType type) { + Ort::ThrowOnError(GetApi().CreateOpAttr(name, data, len, type, &p_)); +} + +namespace detail { +template +inline KernelInfo KernelInfoImpl::Copy() const { + OrtKernelInfo* info_copy = nullptr; + Ort::ThrowOnError(GetApi().CopyKernelInfo(this->p_, &info_copy)); + return KernelInfo{info_copy}; +} + +template +inline size_t KernelInfoImpl::GetInputCount() const { + size_t out = 0; + ThrowOnError(GetApi().KernelInfo_GetInputCount(this->p_, &out)); + return out; +} + +template +inline size_t KernelInfoImpl::GetOutputCount() const { + size_t out = 0; + ThrowOnError(GetApi().KernelInfo_GetOutputCount(this->p_, &out)); + return out; +} + +template +inline std::string KernelInfoImpl::GetInputName(size_t index) const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetInputName(this->p_, index, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline std::string KernelInfoImpl::GetOutputName(size_t index) const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetOutputName(this->p_, index, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline TypeInfo KernelInfoImpl::GetInputTypeInfo(size_t index) const { + OrtTypeInfo* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetInputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline TypeInfo KernelInfoImpl::GetOutputTypeInfo(size_t index) const { + OrtTypeInfo* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetOutputTypeInfo(this->p_, index, &out)); + return TypeInfo{out}; +} + +template +inline Value KernelInfoImpl::GetTensorAttribute(const char* name, OrtAllocator* allocator) const { + OrtValue* out = nullptr; + ThrowOnError(GetApi().KernelInfoGetAttribute_tensor(this->p_, name, allocator, &out)); + return Value{out}; +} + +template +inline ConstValue KernelInfoImpl::GetTensorConstantInput(size_t index, int* is_constant) const { + const OrtValue* out = nullptr; + ThrowOnError(GetApi().KernelInfoGetConstantInput_tensor(this->p_, index, is_constant, &out)); + return ConstValue{out}; +} + +template +inline std::string KernelInfoImpl::GetNodeName() const { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the string value + Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfo_GetNodeName(this->p_, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + + return out; +} + +template +inline Logger KernelInfoImpl::GetLogger() const { + const OrtLogger* out = nullptr; + ThrowOnError(GetApi().KernelInfo_GetLogger(this->p_, &out)); + return Logger{out}; +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, float& out) { + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_float(p, name, &out)); +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, int64_t& out) { + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_int64(p, name, &out)); +} + +inline void attr_utils::GetAttr(const OrtKernelInfo* p, const char* name, std::string& result) { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the string attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, nullptr, &size)); + + std::string out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttribute_string(p, name, &out[0], &size)); + out.resize(size - 1); // remove the terminating character '\0' + out.swap(result); +} + +inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { + size_t size = 0; + // Feed nullptr for the data buffer to query the true size of the attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, nullptr, &size)); + + std::vector out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_float(p, name, out.data(), &size)); + out.swap(result); +} + +inline void attr_utils::GetAttrs(const OrtKernelInfo* p, const char* name, std::vector& result) { + size_t size = 0; + + // Feed nullptr for the data buffer to query the true size of the attribute + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, nullptr, &size)); + + std::vector out; + out.resize(size); + Ort::ThrowOnError(GetApi().KernelInfoGetAttributeArray_int64(p, name, out.data(), &size)); + out.swap(result); +} +} // namespace detail + +inline KernelInfo::KernelInfo(OrtKernelInfo* info) : detail::KernelInfoImpl{info} {} + +inline Op::Op(OrtOp* p) : detail::Base(p) {} + +inline Op Op::Create(const OrtKernelInfo* info, const char* op_name, const char* domain, int version, + const char** type_constraint_names, + const ONNXTensorElementDataType* type_constraint_values, + size_t type_constraint_count, + const OpAttr* attr_values, size_t attr_count, + size_t input_count, size_t output_count) { + static_assert(sizeof(OpAttr) == sizeof(OrtOpAttr*), + "OpAttr's is expected to be just an array of OrtOpAttr in memory so we can reinterpret safely"); + auto attr_input_values = reinterpret_cast(attr_values); + OrtOp* op; + Ort::ThrowOnError(GetApi().CreateOp(info, op_name, domain, version, type_constraint_names, type_constraint_values, + static_cast(type_constraint_count), + attr_input_values, + static_cast(attr_count), + static_cast(input_count), + static_cast(output_count), &op)); + return Op{op}; +} + +inline void Op::Invoke(const OrtKernelContext* context, + const Value* input_values, + size_t input_count, + Value* output_values, + size_t output_count) { + static_assert(sizeof(Value) == sizeof(OrtValue*), + "Value is really just an array of OrtValue* in memory, so we can reinterpret_cast safely"); + auto ort_input_values = reinterpret_cast(input_values); + auto ort_output_values = reinterpret_cast(output_values); + Ort::ThrowOnError(GetApi().InvokeOp(context, p_, ort_input_values, static_cast(input_count), + ort_output_values, static_cast(output_count))); +} + +inline void Op::Invoke(const OrtKernelContext* context, + const OrtValue* const* input_values, + size_t input_count, + OrtValue* const* output_values, + size_t output_count) { + Ort::ThrowOnError(GetApi().InvokeOp(context, p_, input_values, static_cast(input_count), + output_values, static_cast(output_count))); +} + +inline std::string GetVersionString() { + return OrtGetApiBase()->GetVersionString(); +} + +inline std::string GetBuildInfoString() { + return GetApi().GetBuildInfoString(); +} + +inline std::vector GetAvailableProviders() { + char** providers; + int len; + + auto release_fn = [&len](char** providers) { + // This should always return nullptr. + ThrowOnError(GetApi().ReleaseAvailableProviders(providers, len)); + }; + + ThrowOnError(GetApi().GetAvailableProviders(&providers, &len)); + std::unique_ptr guard(providers, release_fn); + std::vector available_providers; + available_providers.reserve(static_cast(len)); + for (int i = 0; i < len; ++i) { + available_providers.emplace_back(providers[i]); + } + return available_providers; +} + +template +void CustomOpBase::GetSessionConfigs(std::unordered_map& out, + ConstSessionOptions options) const { + const TOp* derived = static_cast(this); + std::vector keys = derived->GetSessionConfigKeys(); + + out.reserve(keys.size()); + + std::string config_entry_key = detail::MakeCustomOpConfigEntryKey(derived->GetName(), ""); + const size_t prefix_size = config_entry_key.length(); + + for (const auto& key : keys) { + config_entry_key.resize(prefix_size); + config_entry_key.append(key); + out[key] = options.GetConfigEntryOrDefault(config_entry_key.c_str(), ""); + } +} + +inline ShapeInferContext::ShapeInferContext(const OrtApi* ort_api, + OrtShapeInferContext* ctx) : ort_api_(ort_api), ctx_(ctx) { + size_t input_count = 0; + Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputCount(ctx_, &input_count)); + for (size_t ith_input = 0; ith_input < input_count; ++ith_input) { + OrtTensorTypeAndShapeInfo* info{}; + Ort::ThrowOnError(ort_api_->ShapeInferContext_GetInputTypeShape(ctx, ith_input, &info)); + TensorTypeAndShapeInfo type_shape_info(info); + auto integer_shape = type_shape_info.GetShape(); + std::vector symbolic_shape(integer_shape.size(), {}); + if (!integer_shape.empty()) { + type_shape_info.GetSymbolicDimensions(&symbolic_shape[0], integer_shape.size()); + } + Shape shape; + for (size_t ith = 0; ith < integer_shape.size(); ++ith) { + if (symbolic_shape[ith] && std::string{symbolic_shape[ith]}.size() > 0) { + shape.emplace_back(symbolic_shape[ith]); + } else { + shape.emplace_back(integer_shape[ith]); + } + } + input_shapes_.push_back(std::move(shape)); + type_shape_info.release(); + } +} + +inline Status ShapeInferContext::SetOutputShape(size_t indice, const Shape& shape, ONNXTensorElementDataType type) { + OrtTensorTypeAndShapeInfo* info = {}; + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->CreateTensorTypeAndShapeInfo(&info)); + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetTensorElementType(info, type)); + + using InfoPtr = std::unique_ptr>; + + InfoPtr info_ptr(info, [this](OrtTensorTypeAndShapeInfo* obj) { + ort_api_->ReleaseTensorTypeAndShapeInfo(obj); + }); + + std::vector integer_dims; + std::vector symbolic_dims; + + for (const auto dim : shape) { + if (dim.IsInt()) { + integer_dims.push_back(dim.AsInt()); + symbolic_dims.push_back(""); + } else { + if (!dim.AsSym() || std::string{dim.AsSym()}.empty()) { + ORT_CXX_API_THROW("Symbolic dim must not be an empty string", ORT_INVALID_ARGUMENT); + } + integer_dims.push_back(SymbolicInteger::INVALID_INT_DIM); + symbolic_dims.push_back(dim.AsSym()); + } + } + + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetDimensions(info, integer_dims.data(), integer_dims.size())); + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->SetSymbolicDimensions(info, symbolic_dims.data(), symbolic_dims.size())); + ORT_CXX_RETURN_ON_API_FAIL(ort_api_->ShapeInferContext_SetOutputTypeShape(ctx_, indice, info)); + return Status{nullptr}; +} + +inline int64_t ShapeInferContext::GetAttrInt(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + int64_t i = {}; + size_t out = {}; + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INT, &i, sizeof(i), &out)); + return i; +} + +inline ShapeInferContext::Ints ShapeInferContext::GetAttrInts(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + int64_t i = {}; + size_t out = {}; + // first call to get the bytes needed + // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. + // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). + // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, &i, sizeof(i), &out); + if (status) { + size_t num_i = out / sizeof(int64_t); + ShapeInferContext::Ints ints(num_i, 0); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_INTS, ints.data(), out, &out)); + return ints; + } else { + if (out == 0u) { + return {}; + } + return {i}; + } +} + +inline float ShapeInferContext::GetAttrFloat(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + float f = {}; + size_t out = {}; + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOAT, &f, sizeof(f), &out)); + return f; +} + +inline ShapeInferContext::Floats ShapeInferContext::GetAttrFloats(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + float f = {}; + size_t out = {}; + // first call to get the bytes needed + // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. + // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). + // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, &f, sizeof(f), &out); + if (status) { + size_t num_f = out / sizeof(float); + ShapeInferContext::Floats floats(num_f, 0); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_FLOATS, floats.data(), out, &out)); + return floats; + } else { + if (out == 0u) { + return {}; + } + return {f}; + } +} + +inline std::string ShapeInferContext::GetAttrString(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + char c = {}; + size_t out = {}; + // first call to get the bytes needed + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, &c, sizeof(char), &out); + if (status) { + std::vector chars(out, '\0'); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRING, chars.data(), out, &out)); + return {chars.data()}; + } else { + return {c}; + } +} + +inline ShapeInferContext::Strings ShapeInferContext::GetAttrStrings(const char* attr_name) { + const auto* attr = GetAttrHdl(attr_name); + char c = {}; + size_t out = {}; + // first call to get the bytes needed + // 1. A status == nullptr means that ReadOpAttr was successful. A status != nullptr means failure. + // 2. The ReadOpAttr function should normally be called twice: once to get the needed buffer size (returns a status != nullptr), and a second time to actually read the ints (returns status == null on success). + // 3. This code tries a subtle optimization in the first call to ReadOpAttr. It passes in a buffer (&i) of size 1 just in case there is only 1 int. In this case, status == nullptr and we need to return {i}. + auto status = ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, &c, sizeof(char), &out); + if (status) { + std::vector chars(out, '\0'); + Ort::ThrowOnError(ort_api_->ReadOpAttr(attr, ORT_OP_ATTR_STRINGS, chars.data(), out, &out)); + ShapeInferContext::Strings strings; + char* char_st = chars.data(); + char* char_ed = char_st + out; + while (char_st < char_ed) { + strings.emplace_back(char_st); + while (*char_st != '\0') { + char_st++; + } + char_st++; + } + return strings; + } else { + if (out == 0u) { + return {}; + } + return {std::string{c}}; + } +} + +inline const OrtOpAttr* ShapeInferContext::GetAttrHdl(const char* attr_name) const { + const OrtOpAttr* attr_hdl = {}; + Ort::ThrowOnError(ort_api_->ShapeInferContext_GetAttribute(ctx_, attr_name, &attr_hdl)); + return attr_hdl; +} + +namespace detail { +inline std::vector StringsToCharPtrs(const std::vector& strings) { + std::vector ptrs; + ptrs.reserve(strings.size()); + std::transform(strings.begin(), strings.end(), std::back_inserter(ptrs), + [](const std::string& s) { return s.c_str(); }); + + return ptrs; +} +} // namespace detail + +#if !defined(ORT_MINIMAL_BUILD) +// static +inline void Node::Init(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes, + OrtNode*& node) { + auto inputs = detail::StringsToCharPtrs(input_names); + auto outputs = detail::StringsToCharPtrs(output_names); + + std::vector attributes_ptrs; + attributes_ptrs.reserve(attributes.size()); + std::transform(attributes.begin(), attributes.end(), std::back_inserter(attributes_ptrs), + [](OpAttr& attr) -> OrtOpAttr* { return attr; }); + + ThrowOnError(GetModelEditorApi().CreateNode(operator_name.c_str(), operator_domain.c_str(), node_name.c_str(), + inputs.data(), inputs.size(), + outputs.data(), outputs.size(), + attributes_ptrs.data(), attributes_ptrs.size(), + &node)); + + // Node now owns the attributes + std::for_each(attributes.begin(), attributes.end(), [](OpAttr& attr) { attr.release(); }); +} + +inline Node::Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names, + std::vector& attributes) { + Init(operator_name, operator_domain, node_name, input_names, output_names, attributes, p_); +} + +inline Node::Node(const std::string& operator_name, const std::string& operator_domain, + const std::string& node_name, + const std::vector& input_names, + const std::vector& output_names) { + std::vector empty_attributes; + Init(operator_name, operator_domain, node_name, input_names, output_names, empty_attributes, p_); +} + +inline Graph::Graph() { + ThrowOnError(GetModelEditorApi().CreateGraph(&p_)); +} + +inline Model::Model(const std::vector& opsets) { + std::vector domains; + std::vector versions; + domains.reserve(opsets.size()); + versions.reserve(opsets.size()); + + for (const auto& pair : opsets) { + domains.push_back(pair.first.c_str()); + versions.push_back(pair.second); + } + + ThrowOnError(GetModelEditorApi().CreateModel(domains.data(), versions.data(), opsets.size(), &p_)); +} + +inline ValueInfo::ValueInfo(const std::string& name, const ConstTypeInfo& type_info) { + ThrowOnError(GetModelEditorApi().CreateValueInfo(name.c_str(), type_info, &p_)); +} +#endif // !defined(ORT_MINIMAL_BUILD) + +namespace detail { +template <> +inline std::string ValueInfoImpl::Name() const { + const char* name = nullptr; + ThrowOnError(GetApi().GetValueInfoName(this->p_, &name)); + return name; +} + +template <> +inline ConstTypeInfo ValueInfoImpl::TypeInfo() const { + const OrtTypeInfo* type_info = nullptr; + ThrowOnError(GetApi().GetValueInfoTypeInfo(this->p_, &type_info)); + return ConstTypeInfo{type_info}; +} + +#if !defined(ORT_MINIMAL_BUILD) +template <> +inline void GraphImpl::SetInputs(std::vector& inputs) { + std::vector inputs_ptrs; + inputs_ptrs.reserve(inputs.size()); + std::transform(inputs.begin(), inputs.end(), std::back_inserter(inputs_ptrs), + [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); + + ThrowOnError(GetModelEditorApi().SetGraphInputs(p_, inputs_ptrs.data(), inputs_ptrs.size())); + + // Graph now owns the inputs + std::for_each(inputs.begin(), inputs.end(), [](ValueInfo& vi) { vi.release(); }); +} + +template <> +inline void GraphImpl::SetOutputs(std::vector& outputs) { + std::vector outputs_ptrs; + outputs_ptrs.reserve(outputs.size()); + std::transform(outputs.begin(), outputs.end(), std::back_inserter(outputs_ptrs), + [](ValueInfo& vi) -> OrtValueInfo* { return vi; }); + + ThrowOnError(GetModelEditorApi().SetGraphOutputs(p_, outputs_ptrs.data(), outputs_ptrs.size())); + + // Graph now owns the outputs + std::for_each(outputs.begin(), outputs.end(), [](ValueInfo& vi) { vi.release(); }); +} + +template <> +inline void GraphImpl::AddInitializer(const std::string& name, Value& initializer, bool data_is_external) { + // Graph takes ownership of `initializer` + ThrowOnError(GetModelEditorApi().AddInitializerToGraph(p_, name.c_str(), initializer.release(), data_is_external)); +} + +template <> +inline void GraphImpl::AddNode(Node& node) { + // Graph takes ownership of `node` + ThrowOnError(GetModelEditorApi().AddNodeToGraph(p_, node.release())); +} + +template <> +inline void ModelImpl::AddGraph(Graph& graph) { + // Model takes ownership of `graph` + ThrowOnError(GetModelEditorApi().AddGraphToModel(p_, graph.release())); +} +#endif // !defined(ORT_MINIMAL_BUILD) + +} // namespace detail +} // namespace Ort diff --git a/3rdParty/ONNX/onnxruntime_float16.h b/3rdParty/ONNX/onnxruntime_float16.h index a6923ddd43..408d3ccfb2 100644 --- a/3rdParty/ONNX/onnxruntime_float16.h +++ b/3rdParty/ONNX/onnxruntime_float16.h @@ -1,535 +1,535 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include -#include -#include -#include - -namespace onnxruntime_float16 { - -namespace detail { - -enum class endian { -#if defined(_WIN32) - little = 0, - big = 1, - native = little, -#elif defined(__GNUC__) || defined(__clang__) - little = __ORDER_LITTLE_ENDIAN__, - big = __ORDER_BIG_ENDIAN__, - native = __BYTE_ORDER__, -#else -#error onnxruntime_float16::detail::endian is not implemented in this environment. -#endif -}; - -static_assert( - endian::native == endian::little || endian::native == endian::big, - "Only little-endian or big-endian native byte orders are supported."); - -} // namespace detail - -/// -/// Shared implementation between public and internal classes. CRTP pattern. -/// -template -struct Float16Impl { - protected: - /// - /// Converts from float to uint16_t float16 representation - /// - /// - /// - constexpr static uint16_t ToUint16Impl(float v) noexcept; - - /// - /// Converts float16 to float - /// - /// float representation of float16 value - float ToFloatImpl() const noexcept; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - uint16_t AbsImpl() const noexcept { - return static_cast(val & ~kSignMask); - } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - uint16_t NegateImpl() const noexcept { - return IsNaN() ? val : static_cast(val ^ kSignMask); - } - - public: - // uint16_t special values - static constexpr uint16_t kSignMask = 0x8000U; - static constexpr uint16_t kBiasedExponentMask = 0x7C00U; - static constexpr uint16_t kPositiveInfinityBits = 0x7C00U; - static constexpr uint16_t kNegativeInfinityBits = 0xFC00U; - static constexpr uint16_t kPositiveQNaNBits = 0x7E00U; - static constexpr uint16_t kNegativeQNaNBits = 0xFE00U; - static constexpr uint16_t kMaxValueBits = 0x7BFFU; // Largest normal number - static constexpr uint16_t kOneBits = 0x3C00U; - static constexpr uint16_t kMinusOneBits = 0xBC00U; - - uint16_t val{0}; - - Float16Impl() = default; - - /// - /// Checks if the value is negative - /// - /// true if negative - bool IsNegative() const noexcept { - return static_cast(val) < 0; - } - - /// - /// Tests if the value is NaN - /// - /// true if NaN - bool IsNaN() const noexcept { - return AbsImpl() > kPositiveInfinityBits; - } - - /// - /// Tests if the value is finite - /// - /// true if finite - bool IsFinite() const noexcept { - return AbsImpl() < kPositiveInfinityBits; - } - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - bool IsPositiveInfinity() const noexcept { - return val == kPositiveInfinityBits; - } - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - bool IsNegativeInfinity() const noexcept { - return val == kNegativeInfinityBits; - } - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - bool IsInfinity() const noexcept { - return AbsImpl() == kPositiveInfinityBits; - } - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - bool IsNaNOrZero() const noexcept { - auto abs = AbsImpl(); - return (abs == 0 || abs > kPositiveInfinityBits); - } - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - bool IsNormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) - } - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - bool IsSubnormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) - } - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - static bool AreZero(const Float16Impl& lhs, const Float16Impl& rhs) noexcept { - return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; - } - - bool operator==(const Float16Impl& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is not equal to anything, including itself. - return false; - } - return val == rhs.val; - } - - bool operator!=(const Float16Impl& rhs) const noexcept { return !(*this == rhs); } - - bool operator<(const Float16Impl& rhs) const noexcept { - if (IsNaN() || rhs.IsNaN()) { - // IEEE defines that NaN is unordered with respect to everything, including itself. - return false; - } - - const bool left_is_negative = IsNegative(); - if (left_is_negative != rhs.IsNegative()) { - // When the signs of left and right differ, we know that left is less than right if it is - // the negative value. The exception to this is if both values are zero, in which case IEEE - // says they should be equal, even if the signs differ. - return left_is_negative && !AreZero(*this, rhs); - } - return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); - } -}; - -// The following Float16_t conversions are based on the code from -// Eigen library. - -// The conversion routines are Copyright (c) Fabian Giesen, 2016. -// The original license follows: -// -// Copyright (c) Fabian Giesen, 2016 -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted. -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -namespace detail { -union float32_bits { - unsigned int u; - float f; -}; -} // namespace detail - -template -inline constexpr uint16_t Float16Impl::ToUint16Impl(float v) noexcept { - detail::float32_bits f{}; - f.f = v; - - constexpr detail::float32_bits f32infty = {255 << 23}; - constexpr detail::float32_bits f16max = {(127 + 16) << 23}; - constexpr detail::float32_bits denorm_magic = {((127 - 15) + (23 - 10) + 1) << 23}; - constexpr unsigned int sign_mask = 0x80000000u; - uint16_t val = static_cast(0x0u); - - unsigned int sign = f.u & sign_mask; - f.u ^= sign; - - // NOTE all the integer compares in this function can be safely - // compiled into signed compares since all operands are below - // 0x80000000. Important if you want fast straight SSE2 code - // (since there's no unsigned PCMPGTD). - - if (f.u >= f16max.u) { // result is Inf or NaN (all exponent bits set) - val = (f.u > f32infty.u) ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf - } else { // (De)normalized number or zero - if (f.u < (113 << 23)) { // resulting FP16 is subnormal or zero - // use a magic value to align our 10 mantissa bits at the bottom of - // the float. as long as FP addition is round-to-nearest-even this - // just works. - f.f += denorm_magic.f; - - // and one integer subtract of the bias later, we have our final float! - val = static_cast(f.u - denorm_magic.u); - } else { - unsigned int mant_odd = (f.u >> 13) & 1; // resulting mantissa is odd - - // update exponent, rounding bias part 1 - // Equivalent to `f.u += ((unsigned int)(15 - 127) << 23) + 0xfff`, but - // without arithmetic overflow. - f.u += 0xc8000fffU; - // rounding bias part 2 - f.u += mant_odd; - // take the bits! - val = static_cast(f.u >> 13); - } - } - - val |= static_cast(sign >> 16); - return val; -} - -template -inline float Float16Impl::ToFloatImpl() const noexcept { - constexpr detail::float32_bits magic = {113 << 23}; - constexpr unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift - detail::float32_bits o{}; - - o.u = (val & 0x7fff) << 13; // exponent/mantissa bits - unsigned int exp = shifted_exp & o.u; // just the exponent - o.u += (127 - 15) << 23; // exponent adjust - - // handle exponent special cases - if (exp == shifted_exp) { // Inf/NaN? - o.u += (128 - 16) << 23; // extra exp adjust - } else if (exp == 0) { // Zero/Denormal? - o.u += 1 << 23; // extra exp adjust - o.f -= magic.f; // re-normalize - } - - // Attempt to workaround the Internal Compiler Error on ARM64 - // for bitwise | operator, including std::bitset -#if (defined _MSC_VER) && (defined _M_ARM || defined _M_ARM64 || defined _M_ARM64EC) - if (IsNegative()) { - return -o.f; - } -#else - // original code: - o.u |= (val & 0x8000U) << 16U; // sign bit -#endif - return o.f; -} - -/// Shared implementation between public and internal classes. CRTP pattern. -template -struct BFloat16Impl { - protected: - /// - /// Converts from float to uint16_t float16 representation - /// - /// - /// - static uint16_t ToUint16Impl(float v) noexcept; - - /// - /// Converts bfloat16 to float - /// - /// float representation of bfloat16 value - float ToFloatImpl() const noexcept; - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - uint16_t AbsImpl() const noexcept { - return static_cast(val & ~kSignMask); - } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - uint16_t NegateImpl() const noexcept { - return IsNaN() ? val : static_cast(val ^ kSignMask); - } - - public: - // uint16_t special values - static constexpr uint16_t kSignMask = 0x8000U; - static constexpr uint16_t kBiasedExponentMask = 0x7F80U; - static constexpr uint16_t kPositiveInfinityBits = 0x7F80U; - static constexpr uint16_t kNegativeInfinityBits = 0xFF80U; - static constexpr uint16_t kPositiveQNaNBits = 0x7FC1U; - static constexpr uint16_t kNegativeQNaNBits = 0xFFC1U; - static constexpr uint16_t kMaxValueBits = 0x7F7FU; - static constexpr uint16_t kRoundToNearest = 0x7FFFU; - static constexpr uint16_t kOneBits = 0x3F80U; - static constexpr uint16_t kMinusOneBits = 0xBF80U; - - uint16_t val{0}; - - BFloat16Impl() = default; - - /// - /// Checks if the value is negative - /// - /// true if negative - bool IsNegative() const noexcept { - return static_cast(val) < 0; - } - - /// - /// Tests if the value is NaN - /// - /// true if NaN - bool IsNaN() const noexcept { - return AbsImpl() > kPositiveInfinityBits; - } - - /// - /// Tests if the value is finite - /// - /// true if finite - bool IsFinite() const noexcept { - return AbsImpl() < kPositiveInfinityBits; - } - - /// - /// Tests if the value represents positive infinity. - /// - /// true if positive infinity - bool IsPositiveInfinity() const noexcept { - return val == kPositiveInfinityBits; - } - - /// - /// Tests if the value represents negative infinity - /// - /// true if negative infinity - bool IsNegativeInfinity() const noexcept { - return val == kNegativeInfinityBits; - } - - /// - /// Tests if the value is either positive or negative infinity. - /// - /// True if absolute value is infinity - bool IsInfinity() const noexcept { - return AbsImpl() == kPositiveInfinityBits; - } - - /// - /// Tests if the value is NaN or zero. Useful for comparisons. - /// - /// True if NaN or zero. - bool IsNaNOrZero() const noexcept { - auto abs = AbsImpl(); - return (abs == 0 || abs > kPositiveInfinityBits); - } - - /// - /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). - /// - /// True if so - bool IsNormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) - } - - /// - /// Tests if the value is subnormal (denormal). - /// - /// True if so - bool IsSubnormal() const noexcept { - auto abs = AbsImpl(); - return (abs < kPositiveInfinityBits) // is finite - && (abs != 0) // is not zero - && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) - } - - /// - /// Creates an instance that represents absolute value. - /// - /// Absolute value - Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } - - /// - /// Creates a new instance with the sign flipped. - /// - /// Flipped sign instance - Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } - - /// - /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check - /// for two values by or'ing the private bits together and stripping the sign. They are both zero, - /// and therefore equivalent, if the resulting value is still zero. - /// - /// first value - /// second value - /// True if both arguments represent zero - static bool AreZero(const BFloat16Impl& lhs, const BFloat16Impl& rhs) noexcept { - // IEEE defines that positive and negative zero are equal, this gives us a quick equality check - // for two values by or'ing the private bits together and stripping the sign. They are both zero, - // and therefore equivalent, if the resulting value is still zero. - return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; - } -}; - -template -inline uint16_t BFloat16Impl::ToUint16Impl(float v) noexcept { - uint16_t result; - if (std::isnan(v)) { - result = kPositiveQNaNBits; - } else { - auto get_msb_half = [](float fl) { - uint16_t result; -#ifdef __cpp_if_constexpr - if constexpr (detail::endian::native == detail::endian::little) { -#else - if (detail::endian::native == detail::endian::little) { -#endif - std::memcpy(&result, reinterpret_cast(&fl) + sizeof(uint16_t), sizeof(uint16_t)); - } else { - std::memcpy(&result, &fl, sizeof(uint16_t)); - } - return result; - }; - - uint16_t upper_bits = get_msb_half(v); - union { - uint32_t U32; - float F32; - }; - F32 = v; - U32 += (upper_bits & 1) + kRoundToNearest; - result = get_msb_half(F32); - } - return result; -} - -template -inline float BFloat16Impl::ToFloatImpl() const noexcept { - if (IsNaN()) { - return std::numeric_limits::quiet_NaN(); - } - float result; - char* const first = reinterpret_cast(&result); - char* const second = first + sizeof(uint16_t); -#ifdef __cpp_if_constexpr - if constexpr (detail::endian::native == detail::endian::little) { -#else - if (detail::endian::native == detail::endian::little) { -#endif - std::memset(first, 0, sizeof(uint16_t)); - std::memcpy(second, &val, sizeof(uint16_t)); - } else { - std::memcpy(first, &val, sizeof(uint16_t)); - std::memset(second, 0, sizeof(uint16_t)); - } - return result; -} - -} // namespace onnxruntime_float16 +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include +#include + +namespace onnxruntime_float16 { + +namespace detail { + +enum class endian { +#if defined(_WIN32) + little = 0, + big = 1, + native = little, +#elif defined(__GNUC__) || defined(__clang__) + little = __ORDER_LITTLE_ENDIAN__, + big = __ORDER_BIG_ENDIAN__, + native = __BYTE_ORDER__, +#else +#error onnxruntime_float16::detail::endian is not implemented in this environment. +#endif +}; + +static_assert( + endian::native == endian::little || endian::native == endian::big, + "Only little-endian or big-endian native byte orders are supported."); + +} // namespace detail + +/// +/// Shared implementation between public and internal classes. CRTP pattern. +/// +template +struct Float16Impl { + protected: + /// + /// Converts from float to uint16_t float16 representation + /// + /// + /// + constexpr static uint16_t ToUint16Impl(float v) noexcept; + + /// + /// Converts float16 to float + /// + /// float representation of float16 value + float ToFloatImpl() const noexcept; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + uint16_t AbsImpl() const noexcept { + return static_cast(val & ~kSignMask); + } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + uint16_t NegateImpl() const noexcept { + return IsNaN() ? val : static_cast(val ^ kSignMask); + } + + public: + // uint16_t special values + static constexpr uint16_t kSignMask = 0x8000U; + static constexpr uint16_t kBiasedExponentMask = 0x7C00U; + static constexpr uint16_t kPositiveInfinityBits = 0x7C00U; + static constexpr uint16_t kNegativeInfinityBits = 0xFC00U; + static constexpr uint16_t kPositiveQNaNBits = 0x7E00U; + static constexpr uint16_t kNegativeQNaNBits = 0xFE00U; + static constexpr uint16_t kMaxValueBits = 0x7BFFU; // Largest normal number + static constexpr uint16_t kOneBits = 0x3C00U; + static constexpr uint16_t kMinusOneBits = 0xBC00U; + + uint16_t val{0}; + + Float16Impl() = default; + + /// + /// Checks if the value is negative + /// + /// true if negative + bool IsNegative() const noexcept { + return static_cast(val) < 0; + } + + /// + /// Tests if the value is NaN + /// + /// true if NaN + bool IsNaN() const noexcept { + return AbsImpl() > kPositiveInfinityBits; + } + + /// + /// Tests if the value is finite + /// + /// true if finite + bool IsFinite() const noexcept { + return AbsImpl() < kPositiveInfinityBits; + } + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + bool IsPositiveInfinity() const noexcept { + return val == kPositiveInfinityBits; + } + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + bool IsNegativeInfinity() const noexcept { + return val == kNegativeInfinityBits; + } + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + bool IsInfinity() const noexcept { + return AbsImpl() == kPositiveInfinityBits; + } + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + bool IsNaNOrZero() const noexcept { + auto abs = AbsImpl(); + return (abs == 0 || abs > kPositiveInfinityBits); + } + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + bool IsNormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) + } + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + bool IsSubnormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) + } + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + static bool AreZero(const Float16Impl& lhs, const Float16Impl& rhs) noexcept { + return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; + } + + bool operator==(const Float16Impl& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is not equal to anything, including itself. + return false; + } + return val == rhs.val; + } + + bool operator!=(const Float16Impl& rhs) const noexcept { return !(*this == rhs); } + + bool operator<(const Float16Impl& rhs) const noexcept { + if (IsNaN() || rhs.IsNaN()) { + // IEEE defines that NaN is unordered with respect to everything, including itself. + return false; + } + + const bool left_is_negative = IsNegative(); + if (left_is_negative != rhs.IsNegative()) { + // When the signs of left and right differ, we know that left is less than right if it is + // the negative value. The exception to this is if both values are zero, in which case IEEE + // says they should be equal, even if the signs differ. + return left_is_negative && !AreZero(*this, rhs); + } + return (val != rhs.val) && ((val < rhs.val) ^ left_is_negative); + } +}; + +// The following Float16_t conversions are based on the code from +// Eigen library. + +// The conversion routines are Copyright (c) Fabian Giesen, 2016. +// The original license follows: +// +// Copyright (c) Fabian Giesen, 2016 +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted. +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +namespace detail { +union float32_bits { + unsigned int u; + float f; +}; +} // namespace detail + +template +inline constexpr uint16_t Float16Impl::ToUint16Impl(float v) noexcept { + detail::float32_bits f{}; + f.f = v; + + constexpr detail::float32_bits f32infty = {255 << 23}; + constexpr detail::float32_bits f16max = {(127 + 16) << 23}; + constexpr detail::float32_bits denorm_magic = {((127 - 15) + (23 - 10) + 1) << 23}; + constexpr unsigned int sign_mask = 0x80000000u; + uint16_t val = static_cast(0x0u); + + unsigned int sign = f.u & sign_mask; + f.u ^= sign; + + // NOTE all the integer compares in this function can be safely + // compiled into signed compares since all operands are below + // 0x80000000. Important if you want fast straight SSE2 code + // (since there's no unsigned PCMPGTD). + + if (f.u >= f16max.u) { // result is Inf or NaN (all exponent bits set) + val = (f.u > f32infty.u) ? 0x7e00 : 0x7c00; // NaN->qNaN and Inf->Inf + } else { // (De)normalized number or zero + if (f.u < (113 << 23)) { // resulting FP16 is subnormal or zero + // use a magic value to align our 10 mantissa bits at the bottom of + // the float. as long as FP addition is round-to-nearest-even this + // just works. + f.f += denorm_magic.f; + + // and one integer subtract of the bias later, we have our final float! + val = static_cast(f.u - denorm_magic.u); + } else { + unsigned int mant_odd = (f.u >> 13) & 1; // resulting mantissa is odd + + // update exponent, rounding bias part 1 + // Equivalent to `f.u += ((unsigned int)(15 - 127) << 23) + 0xfff`, but + // without arithmetic overflow. + f.u += 0xc8000fffU; + // rounding bias part 2 + f.u += mant_odd; + // take the bits! + val = static_cast(f.u >> 13); + } + } + + val |= static_cast(sign >> 16); + return val; +} + +template +inline float Float16Impl::ToFloatImpl() const noexcept { + constexpr detail::float32_bits magic = {113 << 23}; + constexpr unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift + detail::float32_bits o{}; + + o.u = (val & 0x7fff) << 13; // exponent/mantissa bits + unsigned int exp = shifted_exp & o.u; // just the exponent + o.u += (127 - 15) << 23; // exponent adjust + + // handle exponent special cases + if (exp == shifted_exp) { // Inf/NaN? + o.u += (128 - 16) << 23; // extra exp adjust + } else if (exp == 0) { // Zero/Denormal? + o.u += 1 << 23; // extra exp adjust + o.f -= magic.f; // re-normalize + } + + // Attempt to workaround the Internal Compiler Error on ARM64 + // for bitwise | operator, including std::bitset +#if (defined _MSC_VER) && (defined _M_ARM || defined _M_ARM64 || defined _M_ARM64EC) + if (IsNegative()) { + return -o.f; + } +#else + // original code: + o.u |= (val & 0x8000U) << 16U; // sign bit +#endif + return o.f; +} + +/// Shared implementation between public and internal classes. CRTP pattern. +template +struct BFloat16Impl { + protected: + /// + /// Converts from float to uint16_t float16 representation + /// + /// + /// + static uint16_t ToUint16Impl(float v) noexcept; + + /// + /// Converts bfloat16 to float + /// + /// float representation of bfloat16 value + float ToFloatImpl() const noexcept; + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + uint16_t AbsImpl() const noexcept { + return static_cast(val & ~kSignMask); + } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + uint16_t NegateImpl() const noexcept { + return IsNaN() ? val : static_cast(val ^ kSignMask); + } + + public: + // uint16_t special values + static constexpr uint16_t kSignMask = 0x8000U; + static constexpr uint16_t kBiasedExponentMask = 0x7F80U; + static constexpr uint16_t kPositiveInfinityBits = 0x7F80U; + static constexpr uint16_t kNegativeInfinityBits = 0xFF80U; + static constexpr uint16_t kPositiveQNaNBits = 0x7FC1U; + static constexpr uint16_t kNegativeQNaNBits = 0xFFC1U; + static constexpr uint16_t kMaxValueBits = 0x7F7FU; + static constexpr uint16_t kRoundToNearest = 0x7FFFU; + static constexpr uint16_t kOneBits = 0x3F80U; + static constexpr uint16_t kMinusOneBits = 0xBF80U; + + uint16_t val{0}; + + BFloat16Impl() = default; + + /// + /// Checks if the value is negative + /// + /// true if negative + bool IsNegative() const noexcept { + return static_cast(val) < 0; + } + + /// + /// Tests if the value is NaN + /// + /// true if NaN + bool IsNaN() const noexcept { + return AbsImpl() > kPositiveInfinityBits; + } + + /// + /// Tests if the value is finite + /// + /// true if finite + bool IsFinite() const noexcept { + return AbsImpl() < kPositiveInfinityBits; + } + + /// + /// Tests if the value represents positive infinity. + /// + /// true if positive infinity + bool IsPositiveInfinity() const noexcept { + return val == kPositiveInfinityBits; + } + + /// + /// Tests if the value represents negative infinity + /// + /// true if negative infinity + bool IsNegativeInfinity() const noexcept { + return val == kNegativeInfinityBits; + } + + /// + /// Tests if the value is either positive or negative infinity. + /// + /// True if absolute value is infinity + bool IsInfinity() const noexcept { + return AbsImpl() == kPositiveInfinityBits; + } + + /// + /// Tests if the value is NaN or zero. Useful for comparisons. + /// + /// True if NaN or zero. + bool IsNaNOrZero() const noexcept { + auto abs = AbsImpl(); + return (abs == 0 || abs > kPositiveInfinityBits); + } + + /// + /// Tests if the value is normal (not zero, subnormal, infinite, or NaN). + /// + /// True if so + bool IsNormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) != 0); // is not subnormal (has a non-zero exponent) + } + + /// + /// Tests if the value is subnormal (denormal). + /// + /// True if so + bool IsSubnormal() const noexcept { + auto abs = AbsImpl(); + return (abs < kPositiveInfinityBits) // is finite + && (abs != 0) // is not zero + && ((abs & kBiasedExponentMask) == 0); // is subnormal (has a zero exponent) + } + + /// + /// Creates an instance that represents absolute value. + /// + /// Absolute value + Derived Abs() const noexcept { return Derived::FromBits(AbsImpl()); } + + /// + /// Creates a new instance with the sign flipped. + /// + /// Flipped sign instance + Derived Negate() const noexcept { return Derived::FromBits(NegateImpl()); } + + /// + /// IEEE defines that positive and negative zero are equal, this gives us a quick equality check + /// for two values by or'ing the private bits together and stripping the sign. They are both zero, + /// and therefore equivalent, if the resulting value is still zero. + /// + /// first value + /// second value + /// True if both arguments represent zero + static bool AreZero(const BFloat16Impl& lhs, const BFloat16Impl& rhs) noexcept { + // IEEE defines that positive and negative zero are equal, this gives us a quick equality check + // for two values by or'ing the private bits together and stripping the sign. They are both zero, + // and therefore equivalent, if the resulting value is still zero. + return static_cast((lhs.val | rhs.val) & ~kSignMask) == 0; + } +}; + +template +inline uint16_t BFloat16Impl::ToUint16Impl(float v) noexcept { + uint16_t result; + if (std::isnan(v)) { + result = kPositiveQNaNBits; + } else { + auto get_msb_half = [](float fl) { + uint16_t result; +#ifdef __cpp_if_constexpr + if constexpr (detail::endian::native == detail::endian::little) { +#else + if (detail::endian::native == detail::endian::little) { +#endif + std::memcpy(&result, reinterpret_cast(&fl) + sizeof(uint16_t), sizeof(uint16_t)); + } else { + std::memcpy(&result, &fl, sizeof(uint16_t)); + } + return result; + }; + + uint16_t upper_bits = get_msb_half(v); + union { + uint32_t U32; + float F32; + }; + F32 = v; + U32 += (upper_bits & 1) + kRoundToNearest; + result = get_msb_half(F32); + } + return result; +} + +template +inline float BFloat16Impl::ToFloatImpl() const noexcept { + if (IsNaN()) { + return std::numeric_limits::quiet_NaN(); + } + float result; + char* const first = reinterpret_cast(&result); + char* const second = first + sizeof(uint16_t); +#ifdef __cpp_if_constexpr + if constexpr (detail::endian::native == detail::endian::little) { +#else + if (detail::endian::native == detail::endian::little) { +#endif + std::memset(first, 0, sizeof(uint16_t)); + std::memcpy(second, &val, sizeof(uint16_t)); + } else { + std::memcpy(first, &val, sizeof(uint16_t)); + std::memset(second, 0, sizeof(uint16_t)); + } + return result; +} + +} // namespace onnxruntime_float16 diff --git a/3rdParty/ONNX/onnxruntime_lite_custom_op.h b/3rdParty/ONNX/onnxruntime_lite_custom_op.h index e8aa0342d6..ce87d8c56d 100644 --- a/3rdParty/ONNX/onnxruntime_lite_custom_op.h +++ b/3rdParty/ONNX/onnxruntime_lite_custom_op.h @@ -1,1119 +1,1119 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// Summary -// The header has APIs to save custom op authors the trouble of defining schemas, -// which will be inferred by functions' signature, as long as their argument list has types supported here. -// Input could be: -// 1. Tensor of onnx data types. -// 2. Span of onnx data types. -// 3. Scalar of onnx data types. -// A input could be optional if indicated as std::optional<...>. -// For an output, it must be a tensor of onnx data types. -// Further, the header also has utility for a simple custom struct, where resources could be kept, to be registered as a custom op. -// For concrete examples, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". -// Note - all APIs in this header are ABI. - -#pragma once -#include "onnxruntime_cxx_api.h" -#include -#include -#include -#include - -namespace Ort { -namespace Custom { - -class ArgBase { - public: - ArgBase(OrtKernelContext* ctx, - size_t indice, - bool is_input) : ctx_(ctx), indice_(indice), is_input_(is_input) {} - virtual ~ArgBase() {}; - - protected: - struct KernelContext ctx_; - size_t indice_; - bool is_input_; -}; - -using ArgPtr = std::unique_ptr; -using ArgPtrs = std::vector; - -class TensorBase : public ArgBase { - public: - TensorBase(OrtKernelContext* ctx, - size_t indice, - bool is_input) : ArgBase(ctx, indice, is_input) {} - - operator bool() const { - return shape_.has_value(); - } - - const std::vector& Shape() const { - if (!shape_.has_value()) { - ORT_CXX_API_THROW("tensor shape is not yet initialized", OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return shape_.value(); - } - - ONNXTensorElementDataType Type() const { - return type_; - } - - int64_t NumberOfElement() const { - if (shape_.has_value()) { - return std::accumulate(shape_->begin(), shape_->end(), 1LL, std::multiplies()); - } else { - return 0; - } - } - - std::string Shape2Str() const { - if (shape_.has_value()) { - std::string shape_str; - for (const auto& dim : *shape_) { - shape_str.append(std::to_string(dim)); - shape_str.append(", "); - } - return shape_str; - } else { - return "empty"; - } - } - - bool IsCpuTensor() const { - return strcmp("Cpu", mem_type_) == 0; - } - - virtual const void* DataRaw() const = 0; - virtual size_t SizeInBytes() const = 0; - - protected: - std::optional> shape_; - ONNXTensorElementDataType type_ = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED; - const char* mem_type_ = "Cpu"; -}; - -template -struct Span { - const T* data_ = {}; - size_t size_ = {}; - void Assign(const T* data, size_t size) { - data_ = data; - size_ = size; - } - size_t size() const { return size_; } - T operator[](size_t indice) const { - return data_[indice]; - } - const T* data() const { return data_; } -}; - -template -class Tensor : public TensorBase { - public: - using TT = typename std::remove_reference::type; - Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { - if (is_input_) { - if (indice >= ctx_.GetInputCount()) { - ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); - } - const_value_ = ctx_.GetInput(indice); - auto type_shape_info = const_value_.GetTensorTypeAndShapeInfo(); - shape_ = type_shape_info.GetShape(); - } - } - const TT* Data() const { - return reinterpret_cast(const_value_.GetTensorRawData()); - } - TT* Allocate(const std::vector& shape) { - shape_ = shape; - if (!data_) { - shape_ = shape; - data_ = ctx_.GetOutput(indice_, shape).template GetTensorMutableData(); - } - return data_; - } - static TT GetT() { return (TT)0; } - const Span& AsSpan() { - if (!shape_.has_value() || shape_->size() != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a span out of Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - span_.Assign(Data(), static_cast((*shape_)[0])); - return span_; - } - const T& AsScalar() { - if (!shape_.has_value() || shape_->size() != 1 || (*shape_)[0] != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a scalar from Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return *Data(); - } - const void* DataRaw() const override { - return reinterpret_cast(Data()); - } - - size_t SizeInBytes() const override { - return sizeof(TT) * static_cast(NumberOfElement()); - } - - private: - ConstValue const_value_; // for input - TT* data_{}; // for output - Span span_; -}; - -template <> -class Tensor : public TensorBase { - public: - using strings = std::vector; - - Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { - if (is_input_) { - if (indice >= ctx_.GetInputCount()) { - ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); - } - auto const_value = ctx_.GetInput(indice); - auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); - shape_ = type_shape_info.GetShape(); - auto num_chars = const_value.GetStringTensorDataLength(); - // note - there will be copy ... - auto num_strings = static_cast(NumberOfElement()); - if (num_strings) { - std::vector chars(num_chars + 1, '\0'); - std::vector offsets(num_strings); - const_value.GetStringTensorContent(static_cast(chars.data()), num_chars, offsets.data(), offsets.size()); - auto upper_bound = num_strings - 1; - input_strings_.resize(num_strings); - for (size_t i = upper_bound;; --i) { - if (i < upper_bound) { - chars[offsets[i + 1]] = '\0'; - } - input_strings_[i] = chars.data() + offsets[i]; - if (0 == i) { - break; - } - } - } - } - } - const strings& Data() const { - return input_strings_; - } - const void* DataRaw() const override { - if (input_strings_.size() != 1) { - ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return reinterpret_cast(input_strings_[0].c_str()); - } - size_t SizeInBytes() const override { - if (input_strings_.size() != 1) { - ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return input_strings_[0].size(); - } - void SetStringOutput(const strings& ss, const std::vector& dims) { - shape_ = dims; - std::vector raw; - for (const auto& s : ss) { - raw.push_back(s.data()); - } - auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); - // note - there will be copy ... - output.FillStringTensor(raw.data(), raw.size()); - } - const Span& AsSpan() { - ORT_CXX_API_THROW("span for TensorT of string not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - const std::string& AsScalar() { - if (input_strings_.size() != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a scalar string from Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return input_strings_[0]; - } - - private: - std::vector input_strings_; // for input -}; - -template <> -class Tensor : public TensorBase { - public: - using strings = std::vector; - using string_views = std::vector; - - Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { - if (is_input_) { - if (indice >= ctx_.GetInputCount()) { - ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); - } - auto const_value = ctx_.GetInput(indice); - auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); - shape_ = type_shape_info.GetShape(); - auto num_chars = const_value.GetStringTensorDataLength(); - chars_.resize(num_chars + 1, '\0'); - auto num_strings = static_cast(NumberOfElement()); - if (num_strings) { - std::vector offsets(num_strings); - const_value.GetStringTensorContent(static_cast(chars_.data()), num_chars, offsets.data(), offsets.size()); - offsets.push_back(num_chars); - for (size_t i = 0; i < num_strings; ++i) { - input_string_views_.emplace_back(chars_.data() + offsets[i], offsets[i + 1] - offsets[i]); - } - } - } - } - const string_views& Data() const { - return input_string_views_; - } - const void* DataRaw() const override { - if (input_string_views_.size() != 1) { - ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return reinterpret_cast(input_string_views_[0].data()); - } - size_t SizeInBytes() const override { - if (input_string_views_.size() != 1) { - ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); - } - return input_string_views_[0].size(); - } - void SetStringOutput(const strings& ss, const std::vector& dims) { - shape_ = dims; - std::vector raw; - for (const auto& s : ss) { - raw.push_back(s.data()); - } - auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); - // note - there will be copy ... - output.FillStringTensor(raw.data(), raw.size()); - } - const Span& AsSpan() { - ORT_CXX_API_THROW("span for TensorT of string view not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - std::string_view AsScalar() { - if (input_string_views_.size() != 1) { - ORT_CXX_API_THROW("invalid shape while trying to get a scalar string view from Ort::Custom::Tensor", - OrtErrorCode::ORT_RUNTIME_EXCEPTION); - } - return input_string_views_[0]; - } - - private: - std::vector chars_; // for input - std::vector input_string_views_; // for input -}; - -using TensorPtr = std::unique_ptr; -using TensorPtrs = std::vector; - -struct TensorArray : public ArgBase { - TensorArray(OrtKernelContext* ctx, - size_t start_indice, - bool is_input) : ArgBase(ctx, - start_indice, - is_input) { - if (is_input) { - auto input_count = ctx_.GetInputCount(); - for (size_t ith_input = start_indice; ith_input < input_count; ++ith_input) { - auto const_value = ctx_.GetInput(start_indice); - auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); - auto type = type_shape_info.GetElementType(); - TensorPtr tensor; - switch (type) { - case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: - tensor = std::make_unique>(ctx, ith_input, true); - break; - case ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING: - tensor = std::make_unique>(ctx, ith_input, true); - break; - default: - ORT_CXX_API_THROW("unknow input type", ORT_RUNTIME_EXCEPTION); - break; - } - tensors_.emplace_back(tensor.release()); - } // for - } - } - template - T* AllocateOutput(size_t ith_output, const std::vector& shape) { - // ith_output is the indice of output relative to the tensor array - // indice_ + ith_output is the indice relative to context - auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); - auto raw_output = tensor.get()->Allocate(shape); - tensors_.emplace_back(tensor.release()); - return raw_output; - } - Tensor& AllocateStringTensor(size_t ith_output) { - // ith_output is the indice of output relative to the tensor array - // indice_ + ith_output is the indice relative to context - auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); - Tensor& output = *tensor; - tensors_.emplace_back(tensor.release()); - return output; - } - size_t Size() const { - return tensors_.size(); - } - const TensorPtr& operator[](size_t ith_input) const { - // ith_input is the indice of output relative to the tensor array - return tensors_.at(ith_input); - } - - private: - TensorPtrs tensors_; -}; - -using Variadic = TensorArray; - -/* -Note: -OrtLiteCustomOp inherits from OrtCustomOp to bridge tween a custom func/struct and ort core. -The lifetime of an OrtLiteCustomOp instance is managed by customer code, not ort, so: -1. DO NOT cast OrtLiteCustomOp to OrtCustomOp and release since there is no virtual destructor in the hierarchy. -2. OrtLiteCustomFunc and OrtLiteCustomStruct, as two sub-structs, can be released in form of OrtLiteCustomOp since all members are kept in the OrtLiteCustomOp, - hence memory could still be recycled properly. -Further, OrtCustomOp is a c struct bearing no v-table, so offspring structs are by design to be of zero virtual functions to maintain cast safety. -*/ -struct OrtLiteCustomOp : public OrtCustomOp { - using ConstOptionalFloatTensor = std::optional&>; - using OptionalFloatTensor = std::optional>; - - // CreateTuple - template - static typename std::enable_if>::type - CreateTuple(OrtKernelContext*, ArgPtrs&, size_t, size_t, const std::string&) { - return std::make_tuple(); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - std::tuple current = std::tuple{context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - std::tuple current = std::tuple{*context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - -#ifdef ORT_CUDA_CTX - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - thread_local CudaContext cuda_context; - cuda_context.Init(*context); - std::tuple current = std::tuple{cuda_context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } -#endif - -#ifdef ORT_ROCM_CTX - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - thread_local RocmContext rocm_context; - rocm_context.Init(*context); - std::tuple current = std::tuple{rocm_context}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } -#endif - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_input, true)); - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_input, true)); - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_output, false)); - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - - template - static typename std::enable_if::value, std::tuple>::type - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { - args.push_back(std::make_unique(context, ith_output, false)); - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; - auto next = CreateTuple(context, args, num_input, num_output, ep); - return std::tuple_cat(current, next); - } - -#define CREATE_TUPLE_INPUT(data_type) \ - template \ - static typename std::enable_if*>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if&>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if*>>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_input < num_input) { \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } \ - template \ - static typename std::enable_if*>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if&>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsSpan()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if*>>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_input < num_input) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } \ - template \ - static typename std::enable_if::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_input < num_input) { \ - if ("CPUExecutionProvider" != ep) { \ - ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ - } \ - args.push_back(std::make_unique>(context, ith_input, true)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } -#define CREATE_TUPLE_OUTPUT(data_type) \ - template \ - static typename std::enable_if*>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_output, false)); \ - std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if&>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - args.push_back(std::make_unique>(context, ith_output, false)); \ - std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - template \ - static typename std::enable_if*>>::value, std::tuple>::type \ - CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ - if (ith_output < num_output) { \ - args.push_back(std::make_unique>(context, ith_output, false)); \ - std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } else { \ - std::tuple current = std::tuple{}; \ - auto next = CreateTuple(context, args, num_input, num_output, ep); \ - return std::tuple_cat(current, next); \ - } \ - } -#define CREATE_TUPLE(data_type) \ - CREATE_TUPLE_INPUT(data_type) \ - CREATE_TUPLE_OUTPUT(data_type) - - CREATE_TUPLE(bool) - CREATE_TUPLE(float) - CREATE_TUPLE(Ort::Float16_t) - CREATE_TUPLE(Ort::BFloat16_t) - CREATE_TUPLE(double) - CREATE_TUPLE(int8_t) - CREATE_TUPLE(int16_t) - CREATE_TUPLE(int32_t) - CREATE_TUPLE(int64_t) - CREATE_TUPLE(uint8_t) - CREATE_TUPLE(uint16_t) - CREATE_TUPLE(uint32_t) - CREATE_TUPLE(uint64_t) - CREATE_TUPLE(std::string) - CREATE_TUPLE_INPUT(std::string_view) - CREATE_TUPLE(Ort::Float8E4M3FN_t) - CREATE_TUPLE(Ort::Float8E4M3FNUZ_t) - CREATE_TUPLE(Ort::Float8E5M2_t) - CREATE_TUPLE(Ort::Float8E5M2FNUZ_t) - - // ParseArgs ... - template - static typename std::enable_if<0 == sizeof...(Ts)>::type - ParseArgs(std::vector&, std::vector&) { - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } - -#ifdef ORT_CUDA_CTX - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } -#endif - -#ifdef ORT_ROCM_CTX - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - ParseArgs(input_types, output_types); - } -#endif - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - - template - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type - ParseArgs(std::vector& input_types, std::vector& output_types) { - output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); - ParseArgs(input_types, output_types); - } - -#define PARSE_INPUT_BASE(pack_type, onnx_type) \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - input_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - input_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - input_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } - -#define PARSE_INPUT(data_type, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Tensor*, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Tensor&, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Span*, onnx_type) \ - PARSE_INPUT_BASE(const Custom::Span&, onnx_type) \ - PARSE_INPUT_BASE(data_type, onnx_type) - -#define PARSE_OUTPUT(data_type, onnx_type) \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - output_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same&>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - output_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } \ - template \ - static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>>::value>::type \ - ParseArgs(std::vector& input_types, std::vector& output_types) { \ - output_types.push_back(onnx_type); \ - ParseArgs(input_types, output_types); \ - } - -#define PARSE_ARGS(data_type, onnx_type) \ - PARSE_INPUT(data_type, onnx_type) \ - PARSE_OUTPUT(data_type, onnx_type) - - PARSE_ARGS(bool, ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) - PARSE_ARGS(float, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) - PARSE_ARGS(Ort::Float16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) - PARSE_ARGS(Ort::BFloat16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16) - PARSE_ARGS(double, ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE) - PARSE_ARGS(int8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8) - PARSE_ARGS(int16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16) - PARSE_ARGS(int32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32) - PARSE_ARGS(int64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) - PARSE_ARGS(uint8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8) - PARSE_ARGS(uint16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16) - PARSE_ARGS(uint32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32) - PARSE_ARGS(uint64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64) - PARSE_ARGS(std::string, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) - PARSE_ARGS(std::string_view, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) // todo - remove string_view output - PARSE_ARGS(Ort::Float8E4M3FN_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN) - PARSE_ARGS(Ort::Float8E4M3FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ) - PARSE_ARGS(Ort::Float8E5M2_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2) - PARSE_ARGS(Ort::Float8E5M2FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ) - - OrtLiteCustomOp(const char* op_name, - const char* execution_provider, - ShapeInferFn shape_infer_fn, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : op_name_(op_name), - execution_provider_(execution_provider), - shape_infer_fn_(shape_infer_fn), - start_ver_(start_ver), - end_ver_(end_ver) { - OrtCustomOp::version = ORT_API_VERSION; - - OrtCustomOp::GetName = [](const OrtCustomOp* op) { return static_cast(op)->op_name_.c_str(); }; - OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* op) { return ((OrtLiteCustomOp*)op)->execution_provider_.c_str(); }; - OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp*, size_t) { return OrtMemTypeDefault; }; - - OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->input_types_.size(); - }; - - OrtCustomOp::GetInputType = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->input_types_[indice]; - }; - - OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->output_types_.size(); - }; - - OrtCustomOp::GetOutputType = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->output_types_[indice]; - }; - - OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->input_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; - }; - - OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* op, size_t indice) { - auto self = reinterpret_cast(op); - return self->output_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; - }; - - OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { - return 1; - }; - - OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { - return 0; - }; - - OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { - return 1; - }; - - OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { - return 0; - }; - - OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { return 0; }; - OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { return 0; }; - OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { return 0; }; - OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { return 0; }; - - OrtCustomOp::CreateKernelV2 = {}; - OrtCustomOp::KernelComputeV2 = {}; - OrtCustomOp::KernelCompute = {}; - - OrtCustomOp::InferOutputShapeFn = {}; - - OrtCustomOp::GetStartVersion = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->start_ver_; - }; - - OrtCustomOp::GetEndVersion = [](const OrtCustomOp* op) { - auto self = reinterpret_cast(op); - return self->end_ver_; - }; - - OrtCustomOp::GetMayInplace = {}; - OrtCustomOp::ReleaseMayInplace = {}; - OrtCustomOp::GetAliasMap = {}; - OrtCustomOp::ReleaseAliasMap = {}; - } - - const std::string op_name_; - const std::string execution_provider_; - - std::vector input_types_; - std::vector output_types_; - - ShapeInferFn shape_infer_fn_ = {}; - - int start_ver_ = 1; - int end_ver_ = MAX_CUSTOM_OP_END_VER; - - void* compute_fn_ = {}; - void* compute_fn_return_status_ = {}; -}; - -//////////////////////////// OrtLiteCustomFunc //////////////////////////////// -// The struct is to implement function-as-op. -// E.g. a function might be defined as: -// void Filter(const Ort::Custom::Tensor& floats_in, Ort::Custom::Tensor& floats_out) { ... } -// It could be registered this way: -// Ort::CustomOpDomain v2_domain{"v2"}; -// std::unique_ptr fil_op_ptr{Ort::Custom::CreateLiteCustomOp("Filter", "CPUExecutionProvider", Filter)}; -// v2_domain.Add(fil_op_ptr.get()); -// session_options.Add(v2_domain); -// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". -template -struct OrtLiteCustomFunc : public OrtLiteCustomOp { - using ComputeFn = void (*)(Args...); - using ComputeFnReturnStatus = Status (*)(Args...); - using MyType = OrtLiteCustomFunc; - - struct Kernel { - size_t num_input_{}; - size_t num_output_{}; - ComputeFn compute_fn_{}; - ComputeFnReturnStatus compute_fn_return_status_{}; - std::string ep_{}; - }; - - OrtLiteCustomFunc(const char* op_name, - const char* execution_provider, - ComputeFn compute_fn, - ShapeInferFn shape_infer_fn = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { - compute_fn_ = reinterpret_cast(compute_fn); - ParseArgs(input_types_, output_types_); - - OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { - auto kernel = reinterpret_cast(op_kernel); - std::vector args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - std::apply([kernel](Args const&... t_args) { kernel->compute_fn_(t_args...); }, t); - }; - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { - auto kernel = std::make_unique(); - auto me = static_cast(this_); - kernel->compute_fn_ = reinterpret_cast(me->compute_fn_); - Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); - Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); - auto self = static_cast(this_); - kernel->ep_ = self->execution_provider_; - return reinterpret_cast(kernel.release()); - }; - - OrtCustomOp::KernelDestroy = [](void* op_kernel) { - delete reinterpret_cast(op_kernel); - }; - - if (shape_infer_fn_) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - auto shape_info_fn = static_cast(op)->shape_infer_fn_; - ShapeInferContext ctx(&GetApi(), ort_ctx); - return shape_info_fn(ctx); - }; - } - } - - OrtLiteCustomFunc(const char* op_name, - const char* execution_provider, - ComputeFnReturnStatus compute_fn_return_status, - ShapeInferFn shape_infer_fn = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { - compute_fn_return_status_ = reinterpret_cast(compute_fn_return_status); - ParseArgs(input_types_, output_types_); - - OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { - auto kernel = reinterpret_cast(op_kernel); - std::vector args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - return std::apply([kernel](Args const&... t_args) { Status status = kernel->compute_fn_return_status_(t_args...); return status.release(); }, t); - }; - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { - auto kernel = std::make_unique(); - auto me = static_cast(this_); - kernel->compute_fn_return_status_ = reinterpret_cast(me->compute_fn_return_status_); - Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); - Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); - auto self = static_cast(this_); - kernel->ep_ = self->execution_provider_; - return reinterpret_cast(kernel.release()); - }; - - OrtCustomOp::KernelDestroy = [](void* op_kernel) { - delete reinterpret_cast(op_kernel); - }; - - if (shape_infer_fn_) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - auto shape_info_fn = static_cast(op)->shape_infer_fn_; - ShapeInferContext ctx(&GetApi(), ort_ctx); - return shape_info_fn(ctx); - }; - } - } -}; // struct OrtLiteCustomFunc - -/////////////////////////// OrtLiteCustomStruct /////////////////////////// -// The struct is to implement struct-as-op. -// E.g. a struct might be defined as: -// struct Merge { -// Merge(const OrtApi* ort_api, const OrtKernelInfo* info) {...} -// void Compute(const Ort::Custom::Tensor& strings_in, -// std::string_view string_in, -// Ort::Custom::Tensor* strings_out) {...} -// bool reverse_ = false; -// }; -// It could be registered this way: -// Ort::CustomOpDomain v2_domain{"v2"}; -// std::unique_ptr mrg_op_ptr{Ort::Custom::CreateLiteCustomOp("Merge", "CPUExecutionProvider")}; -// v2_domain.Add(mrg_op_ptr.get()); -// session_options.Add(v2_domain); -// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". -template -struct OrtLiteCustomStruct : public OrtLiteCustomOp { - template - using CustomComputeFn = void (CustomOp::*)(Args...); - - template - using CustomComputeFnReturnStatus = Status (CustomOp::*)(Args...); - - using MyType = OrtLiteCustomStruct; - - struct Kernel { - size_t num_input_{}; - size_t num_output_{}; - std::unique_ptr custom_op_; - std::string ep_{}; - }; - - OrtLiteCustomStruct(const char* op_name, - const char* execution_provider, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, {}, start_ver, end_ver) { - SetCompute(&CustomOp::Compute); - - OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { - auto kernel = std::make_unique(); - Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); - Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); - kernel->custom_op_ = std::make_unique(ort_api, info); - auto self = static_cast(this_); - kernel->ep_ = self->execution_provider_; - return reinterpret_cast(kernel.release()); - }; - - OrtCustomOp::KernelDestroy = [](void* op_kernel) { - delete reinterpret_cast(op_kernel); - }; - - SetShapeInfer(0); - } - - template - void SetCompute(CustomComputeFn) { - ParseArgs(input_types_, output_types_); - OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { - auto kernel = reinterpret_cast(op_kernel); - ArgPtrs args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - std::apply([kernel](Args const&... t_args) { kernel->custom_op_->Compute(t_args...); }, t); - }; - } - - template - void SetCompute(CustomComputeFnReturnStatus) { - ParseArgs(input_types_, output_types_); - OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { - auto kernel = reinterpret_cast(op_kernel); - ArgPtrs args; - auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); - return std::apply([kernel](Args const&... t_args) { Status status = kernel->custom_op_->Compute(t_args...); return status.release(); }, t); - }; - } - - template - decltype(&C::InferOutputShape) SetShapeInfer(decltype(&C::InferOutputShape)) { - OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { - ShapeInferContext ctx(&GetApi(), ort_ctx); - return C::InferOutputShape(ctx); - }; - return {}; - } - - template - void SetShapeInfer(...) { - OrtCustomOp::InferOutputShapeFn = {}; - } -}; // struct OrtLiteCustomStruct - -/////////////////////////// CreateLiteCustomOp //////////////////////////// - -template -OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, - const char* execution_provider, - void (*custom_compute_fn)(Args...), - Status (*shape_infer_fn)(ShapeInferContext&) = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) { - using LiteOp = OrtLiteCustomFunc; - return std::make_unique(op_name, execution_provider, custom_compute_fn, shape_infer_fn, start_ver, end_ver).release(); -} - -template -OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, - const char* execution_provider, - Status (*custom_compute_fn_v2)(Args...), - Status (*shape_infer_fn)(ShapeInferContext&) = {}, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) { - using LiteOp = OrtLiteCustomFunc; - return std::make_unique(op_name, execution_provider, custom_compute_fn_v2, shape_infer_fn, start_ver, end_ver).release(); -} - -template -OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, - const char* execution_provider, - int start_ver = 1, - int end_ver = MAX_CUSTOM_OP_END_VER) { - using LiteOp = OrtLiteCustomStruct; - return std::make_unique(op_name, execution_provider, start_ver, end_ver).release(); -} - -} // namespace Custom -} // namespace Ort +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// Summary +// The header has APIs to save custom op authors the trouble of defining schemas, +// which will be inferred by functions' signature, as long as their argument list has types supported here. +// Input could be: +// 1. Tensor of onnx data types. +// 2. Span of onnx data types. +// 3. Scalar of onnx data types. +// A input could be optional if indicated as std::optional<...>. +// For an output, it must be a tensor of onnx data types. +// Further, the header also has utility for a simple custom struct, where resources could be kept, to be registered as a custom op. +// For concrete examples, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". +// Note - all APIs in this header are ABI. + +#pragma once +#include "onnxruntime_cxx_api.h" +#include +#include +#include +#include + +namespace Ort { +namespace Custom { + +class ArgBase { + public: + ArgBase(OrtKernelContext* ctx, + size_t indice, + bool is_input) : ctx_(ctx), indice_(indice), is_input_(is_input) {} + virtual ~ArgBase() {}; + + protected: + struct KernelContext ctx_; + size_t indice_; + bool is_input_; +}; + +using ArgPtr = std::unique_ptr; +using ArgPtrs = std::vector; + +class TensorBase : public ArgBase { + public: + TensorBase(OrtKernelContext* ctx, + size_t indice, + bool is_input) : ArgBase(ctx, indice, is_input) {} + + operator bool() const { + return shape_.has_value(); + } + + const std::vector& Shape() const { + if (!shape_.has_value()) { + ORT_CXX_API_THROW("tensor shape is not yet initialized", OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return shape_.value(); + } + + ONNXTensorElementDataType Type() const { + return type_; + } + + int64_t NumberOfElement() const { + if (shape_.has_value()) { + return std::accumulate(shape_->begin(), shape_->end(), 1LL, std::multiplies()); + } else { + return 0; + } + } + + std::string Shape2Str() const { + if (shape_.has_value()) { + std::string shape_str; + for (const auto& dim : *shape_) { + shape_str.append(std::to_string(dim)); + shape_str.append(", "); + } + return shape_str; + } else { + return "empty"; + } + } + + bool IsCpuTensor() const { + return strcmp("Cpu", mem_type_) == 0; + } + + virtual const void* DataRaw() const = 0; + virtual size_t SizeInBytes() const = 0; + + protected: + std::optional> shape_; + ONNXTensorElementDataType type_ = ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED; + const char* mem_type_ = "Cpu"; +}; + +template +struct Span { + const T* data_ = {}; + size_t size_ = {}; + void Assign(const T* data, size_t size) { + data_ = data; + size_ = size; + } + size_t size() const { return size_; } + T operator[](size_t indice) const { + return data_[indice]; + } + const T* data() const { return data_; } +}; + +template +class Tensor : public TensorBase { + public: + using TT = typename std::remove_reference::type; + Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { + if (is_input_) { + if (indice >= ctx_.GetInputCount()) { + ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); + } + const_value_ = ctx_.GetInput(indice); + auto type_shape_info = const_value_.GetTensorTypeAndShapeInfo(); + shape_ = type_shape_info.GetShape(); + } + } + const TT* Data() const { + return reinterpret_cast(const_value_.GetTensorRawData()); + } + TT* Allocate(const std::vector& shape) { + shape_ = shape; + if (!data_) { + shape_ = shape; + data_ = ctx_.GetOutput(indice_, shape).template GetTensorMutableData(); + } + return data_; + } + static TT GetT() { return (TT)0; } + const Span& AsSpan() { + if (!shape_.has_value() || shape_->size() != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a span out of Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + span_.Assign(Data(), static_cast((*shape_)[0])); + return span_; + } + const T& AsScalar() { + if (!shape_.has_value() || shape_->size() != 1 || (*shape_)[0] != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a scalar from Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return *Data(); + } + const void* DataRaw() const override { + return reinterpret_cast(Data()); + } + + size_t SizeInBytes() const override { + return sizeof(TT) * static_cast(NumberOfElement()); + } + + private: + ConstValue const_value_; // for input + TT* data_{}; // for output + Span span_; +}; + +template <> +class Tensor : public TensorBase { + public: + using strings = std::vector; + + Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { + if (is_input_) { + if (indice >= ctx_.GetInputCount()) { + ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); + } + auto const_value = ctx_.GetInput(indice); + auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); + shape_ = type_shape_info.GetShape(); + auto num_chars = const_value.GetStringTensorDataLength(); + // note - there will be copy ... + auto num_strings = static_cast(NumberOfElement()); + if (num_strings) { + std::vector chars(num_chars + 1, '\0'); + std::vector offsets(num_strings); + const_value.GetStringTensorContent(static_cast(chars.data()), num_chars, offsets.data(), offsets.size()); + auto upper_bound = num_strings - 1; + input_strings_.resize(num_strings); + for (size_t i = upper_bound;; --i) { + if (i < upper_bound) { + chars[offsets[i + 1]] = '\0'; + } + input_strings_[i] = chars.data() + offsets[i]; + if (0 == i) { + break; + } + } + } + } + } + const strings& Data() const { + return input_strings_; + } + const void* DataRaw() const override { + if (input_strings_.size() != 1) { + ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return reinterpret_cast(input_strings_[0].c_str()); + } + size_t SizeInBytes() const override { + if (input_strings_.size() != 1) { + ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return input_strings_[0].size(); + } + void SetStringOutput(const strings& ss, const std::vector& dims) { + shape_ = dims; + std::vector raw; + for (const auto& s : ss) { + raw.push_back(s.data()); + } + auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); + // note - there will be copy ... + output.FillStringTensor(raw.data(), raw.size()); + } + const Span& AsSpan() { + ORT_CXX_API_THROW("span for TensorT of string not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + const std::string& AsScalar() { + if (input_strings_.size() != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a scalar string from Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return input_strings_[0]; + } + + private: + std::vector input_strings_; // for input +}; + +template <> +class Tensor : public TensorBase { + public: + using strings = std::vector; + using string_views = std::vector; + + Tensor(OrtKernelContext* ctx, size_t indice, bool is_input) : TensorBase(ctx, indice, is_input) { + if (is_input_) { + if (indice >= ctx_.GetInputCount()) { + ORT_CXX_API_THROW("invalid indice for Ort::Custom::Tensor", OrtErrorCode::ORT_INVALID_ARGUMENT); + } + auto const_value = ctx_.GetInput(indice); + auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); + shape_ = type_shape_info.GetShape(); + auto num_chars = const_value.GetStringTensorDataLength(); + chars_.resize(num_chars + 1, '\0'); + auto num_strings = static_cast(NumberOfElement()); + if (num_strings) { + std::vector offsets(num_strings); + const_value.GetStringTensorContent(static_cast(chars_.data()), num_chars, offsets.data(), offsets.size()); + offsets.push_back(num_chars); + for (size_t i = 0; i < num_strings; ++i) { + input_string_views_.emplace_back(chars_.data() + offsets[i], offsets[i + 1] - offsets[i]); + } + } + } + } + const string_views& Data() const { + return input_string_views_; + } + const void* DataRaw() const override { + if (input_string_views_.size() != 1) { + ORT_CXX_API_THROW("DataRaw() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return reinterpret_cast(input_string_views_[0].data()); + } + size_t SizeInBytes() const override { + if (input_string_views_.size() != 1) { + ORT_CXX_API_THROW("SizeInBytes() only applies to string scalar", ORT_RUNTIME_EXCEPTION); + } + return input_string_views_[0].size(); + } + void SetStringOutput(const strings& ss, const std::vector& dims) { + shape_ = dims; + std::vector raw; + for (const auto& s : ss) { + raw.push_back(s.data()); + } + auto output = ctx_.GetOutput(indice_, dims.data(), dims.size()); + // note - there will be copy ... + output.FillStringTensor(raw.data(), raw.size()); + } + const Span& AsSpan() { + ORT_CXX_API_THROW("span for TensorT of string view not implemented", OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + std::string_view AsScalar() { + if (input_string_views_.size() != 1) { + ORT_CXX_API_THROW("invalid shape while trying to get a scalar string view from Ort::Custom::Tensor", + OrtErrorCode::ORT_RUNTIME_EXCEPTION); + } + return input_string_views_[0]; + } + + private: + std::vector chars_; // for input + std::vector input_string_views_; // for input +}; + +using TensorPtr = std::unique_ptr; +using TensorPtrs = std::vector; + +struct TensorArray : public ArgBase { + TensorArray(OrtKernelContext* ctx, + size_t start_indice, + bool is_input) : ArgBase(ctx, + start_indice, + is_input) { + if (is_input) { + auto input_count = ctx_.GetInputCount(); + for (size_t ith_input = start_indice; ith_input < input_count; ++ith_input) { + auto const_value = ctx_.GetInput(start_indice); + auto type_shape_info = const_value.GetTensorTypeAndShapeInfo(); + auto type = type_shape_info.GetElementType(); + TensorPtr tensor; + switch (type) { + case ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64: + tensor = std::make_unique>(ctx, ith_input, true); + break; + case ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING: + tensor = std::make_unique>(ctx, ith_input, true); + break; + default: + ORT_CXX_API_THROW("unknow input type", ORT_RUNTIME_EXCEPTION); + break; + } + tensors_.emplace_back(tensor.release()); + } // for + } + } + template + T* AllocateOutput(size_t ith_output, const std::vector& shape) { + // ith_output is the indice of output relative to the tensor array + // indice_ + ith_output is the indice relative to context + auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); + auto raw_output = tensor.get()->Allocate(shape); + tensors_.emplace_back(tensor.release()); + return raw_output; + } + Tensor& AllocateStringTensor(size_t ith_output) { + // ith_output is the indice of output relative to the tensor array + // indice_ + ith_output is the indice relative to context + auto tensor = std::make_unique>(ctx_.GetOrtKernelContext(), indice_ + ith_output, false); + Tensor& output = *tensor; + tensors_.emplace_back(tensor.release()); + return output; + } + size_t Size() const { + return tensors_.size(); + } + const TensorPtr& operator[](size_t ith_input) const { + // ith_input is the indice of output relative to the tensor array + return tensors_.at(ith_input); + } + + private: + TensorPtrs tensors_; +}; + +using Variadic = TensorArray; + +/* +Note: +OrtLiteCustomOp inherits from OrtCustomOp to bridge tween a custom func/struct and ort core. +The lifetime of an OrtLiteCustomOp instance is managed by customer code, not ort, so: +1. DO NOT cast OrtLiteCustomOp to OrtCustomOp and release since there is no virtual destructor in the hierarchy. +2. OrtLiteCustomFunc and OrtLiteCustomStruct, as two sub-structs, can be released in form of OrtLiteCustomOp since all members are kept in the OrtLiteCustomOp, + hence memory could still be recycled properly. +Further, OrtCustomOp is a c struct bearing no v-table, so offspring structs are by design to be of zero virtual functions to maintain cast safety. +*/ +struct OrtLiteCustomOp : public OrtCustomOp { + using ConstOptionalFloatTensor = std::optional&>; + using OptionalFloatTensor = std::optional>; + + // CreateTuple + template + static typename std::enable_if>::type + CreateTuple(OrtKernelContext*, ArgPtrs&, size_t, size_t, const std::string&) { + return std::make_tuple(); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + std::tuple current = std::tuple{context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + std::tuple current = std::tuple{*context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + +#ifdef ORT_CUDA_CTX + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + thread_local CudaContext cuda_context; + cuda_context.Init(*context); + std::tuple current = std::tuple{cuda_context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } +#endif + +#ifdef ORT_ROCM_CTX + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + thread_local RocmContext rocm_context; + rocm_context.Init(*context); + std::tuple current = std::tuple{rocm_context}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } +#endif + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_input, true)); + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_input, true)); + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_output, false)); + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + + template + static typename std::enable_if::value, std::tuple>::type + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { + args.push_back(std::make_unique(context, ith_output, false)); + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; + auto next = CreateTuple(context, args, num_input, num_output, ep); + return std::tuple_cat(current, next); + } + +#define CREATE_TUPLE_INPUT(data_type) \ + template \ + static typename std::enable_if*>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if&>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if*>>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_input < num_input) { \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } \ + template \ + static typename std::enable_if*>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if&>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsSpan()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if*>>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_input < num_input) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("span input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{&reinterpret_cast*>(args.back().get())->AsSpan()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } \ + template \ + static typename std::enable_if::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_input < num_input) { \ + if ("CPUExecutionProvider" != ep) { \ + ORT_CXX_API_THROW("scalar input could only be applied to CPU EP", OrtErrorCode::ORT_RUNTIME_EXCEPTION); \ + } \ + args.push_back(std::make_unique>(context, ith_input, true)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())->AsScalar()}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } +#define CREATE_TUPLE_OUTPUT(data_type) \ + template \ + static typename std::enable_if*>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_output, false)); \ + std::tuple current = std::tuple{reinterpret_cast(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if&>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + args.push_back(std::make_unique>(context, ith_output, false)); \ + std::tuple current = std::tuple{reinterpret_cast(*args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + template \ + static typename std::enable_if*>>::value, std::tuple>::type \ + CreateTuple(OrtKernelContext* context, ArgPtrs& args, size_t num_input, size_t num_output, const std::string& ep) { \ + if (ith_output < num_output) { \ + args.push_back(std::make_unique>(context, ith_output, false)); \ + std::tuple current = std::tuple{reinterpret_cast*>(args.back().get())}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } else { \ + std::tuple current = std::tuple{}; \ + auto next = CreateTuple(context, args, num_input, num_output, ep); \ + return std::tuple_cat(current, next); \ + } \ + } +#define CREATE_TUPLE(data_type) \ + CREATE_TUPLE_INPUT(data_type) \ + CREATE_TUPLE_OUTPUT(data_type) + + CREATE_TUPLE(bool) + CREATE_TUPLE(float) + CREATE_TUPLE(Ort::Float16_t) + CREATE_TUPLE(Ort::BFloat16_t) + CREATE_TUPLE(double) + CREATE_TUPLE(int8_t) + CREATE_TUPLE(int16_t) + CREATE_TUPLE(int32_t) + CREATE_TUPLE(int64_t) + CREATE_TUPLE(uint8_t) + CREATE_TUPLE(uint16_t) + CREATE_TUPLE(uint32_t) + CREATE_TUPLE(uint64_t) + CREATE_TUPLE(std::string) + CREATE_TUPLE_INPUT(std::string_view) + CREATE_TUPLE(Ort::Float8E4M3FN_t) + CREATE_TUPLE(Ort::Float8E4M3FNUZ_t) + CREATE_TUPLE(Ort::Float8E5M2_t) + CREATE_TUPLE(Ort::Float8E5M2FNUZ_t) + + // ParseArgs ... + template + static typename std::enable_if<0 == sizeof...(Ts)>::type + ParseArgs(std::vector&, std::vector&) { + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } + +#ifdef ORT_CUDA_CTX + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } +#endif + +#ifdef ORT_ROCM_CTX + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + ParseArgs(input_types, output_types); + } +#endif + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + input_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + + template + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type + ParseArgs(std::vector& input_types, std::vector& output_types) { + output_types.push_back(ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED); + ParseArgs(input_types, output_types); + } + +#define PARSE_INPUT_BASE(pack_type, onnx_type) \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + input_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + input_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + input_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } + +#define PARSE_INPUT(data_type, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Tensor*, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Tensor&, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Span*, onnx_type) \ + PARSE_INPUT_BASE(const Custom::Span&, onnx_type) \ + PARSE_INPUT_BASE(data_type, onnx_type) + +#define PARSE_OUTPUT(data_type, onnx_type) \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + output_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same&>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + output_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } \ + template \ + static typename std::enable_if<0 <= sizeof...(Ts) && std::is_same*>>::value>::type \ + ParseArgs(std::vector& input_types, std::vector& output_types) { \ + output_types.push_back(onnx_type); \ + ParseArgs(input_types, output_types); \ + } + +#define PARSE_ARGS(data_type, onnx_type) \ + PARSE_INPUT(data_type, onnx_type) \ + PARSE_OUTPUT(data_type, onnx_type) + + PARSE_ARGS(bool, ONNX_TENSOR_ELEMENT_DATA_TYPE_BOOL) + PARSE_ARGS(float, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT) + PARSE_ARGS(Ort::Float16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT16) + PARSE_ARGS(Ort::BFloat16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_BFLOAT16) + PARSE_ARGS(double, ONNX_TENSOR_ELEMENT_DATA_TYPE_DOUBLE) + PARSE_ARGS(int8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT8) + PARSE_ARGS(int16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT16) + PARSE_ARGS(int32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT32) + PARSE_ARGS(int64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_INT64) + PARSE_ARGS(uint8_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT8) + PARSE_ARGS(uint16_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT16) + PARSE_ARGS(uint32_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT32) + PARSE_ARGS(uint64_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_UINT64) + PARSE_ARGS(std::string, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) + PARSE_ARGS(std::string_view, ONNX_TENSOR_ELEMENT_DATA_TYPE_STRING) // todo - remove string_view output + PARSE_ARGS(Ort::Float8E4M3FN_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FN) + PARSE_ARGS(Ort::Float8E4M3FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E4M3FNUZ) + PARSE_ARGS(Ort::Float8E5M2_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2) + PARSE_ARGS(Ort::Float8E5M2FNUZ_t, ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT8E5M2FNUZ) + + OrtLiteCustomOp(const char* op_name, + const char* execution_provider, + ShapeInferFn shape_infer_fn, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : op_name_(op_name), + execution_provider_(execution_provider), + shape_infer_fn_(shape_infer_fn), + start_ver_(start_ver), + end_ver_(end_ver) { + OrtCustomOp::version = ORT_API_VERSION; + + OrtCustomOp::GetName = [](const OrtCustomOp* op) { return static_cast(op)->op_name_.c_str(); }; + OrtCustomOp::GetExecutionProviderType = [](const OrtCustomOp* op) { return ((OrtLiteCustomOp*)op)->execution_provider_.c_str(); }; + OrtCustomOp::GetInputMemoryType = [](const OrtCustomOp*, size_t) { return OrtMemTypeDefault; }; + + OrtCustomOp::GetInputTypeCount = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->input_types_.size(); + }; + + OrtCustomOp::GetInputType = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->input_types_[indice]; + }; + + OrtCustomOp::GetOutputTypeCount = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->output_types_.size(); + }; + + OrtCustomOp::GetOutputType = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->output_types_[indice]; + }; + + OrtCustomOp::GetInputCharacteristic = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->input_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; + }; + + OrtCustomOp::GetOutputCharacteristic = [](const OrtCustomOp* op, size_t indice) { + auto self = reinterpret_cast(op); + return self->output_types_[indice] == ONNX_TENSOR_ELEMENT_DATA_TYPE_UNDEFINED ? INPUT_OUTPUT_VARIADIC : INPUT_OUTPUT_OPTIONAL; + }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { + return 1; + }; + + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { + return 0; + }; + + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { + return 1; + }; + + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { + return 0; + }; + + OrtCustomOp::GetVariadicInputMinArity = [](const OrtCustomOp*) { return 0; }; + OrtCustomOp::GetVariadicInputHomogeneity = [](const OrtCustomOp*) { return 0; }; + OrtCustomOp::GetVariadicOutputMinArity = [](const OrtCustomOp*) { return 0; }; + OrtCustomOp::GetVariadicOutputHomogeneity = [](const OrtCustomOp*) { return 0; }; + + OrtCustomOp::CreateKernelV2 = {}; + OrtCustomOp::KernelComputeV2 = {}; + OrtCustomOp::KernelCompute = {}; + + OrtCustomOp::InferOutputShapeFn = {}; + + OrtCustomOp::GetStartVersion = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->start_ver_; + }; + + OrtCustomOp::GetEndVersion = [](const OrtCustomOp* op) { + auto self = reinterpret_cast(op); + return self->end_ver_; + }; + + OrtCustomOp::GetMayInplace = {}; + OrtCustomOp::ReleaseMayInplace = {}; + OrtCustomOp::GetAliasMap = {}; + OrtCustomOp::ReleaseAliasMap = {}; + } + + const std::string op_name_; + const std::string execution_provider_; + + std::vector input_types_; + std::vector output_types_; + + ShapeInferFn shape_infer_fn_ = {}; + + int start_ver_ = 1; + int end_ver_ = MAX_CUSTOM_OP_END_VER; + + void* compute_fn_ = {}; + void* compute_fn_return_status_ = {}; +}; + +//////////////////////////// OrtLiteCustomFunc //////////////////////////////// +// The struct is to implement function-as-op. +// E.g. a function might be defined as: +// void Filter(const Ort::Custom::Tensor& floats_in, Ort::Custom::Tensor& floats_out) { ... } +// It could be registered this way: +// Ort::CustomOpDomain v2_domain{"v2"}; +// std::unique_ptr fil_op_ptr{Ort::Custom::CreateLiteCustomOp("Filter", "CPUExecutionProvider", Filter)}; +// v2_domain.Add(fil_op_ptr.get()); +// session_options.Add(v2_domain); +// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". +template +struct OrtLiteCustomFunc : public OrtLiteCustomOp { + using ComputeFn = void (*)(Args...); + using ComputeFnReturnStatus = Status (*)(Args...); + using MyType = OrtLiteCustomFunc; + + struct Kernel { + size_t num_input_{}; + size_t num_output_{}; + ComputeFn compute_fn_{}; + ComputeFnReturnStatus compute_fn_return_status_{}; + std::string ep_{}; + }; + + OrtLiteCustomFunc(const char* op_name, + const char* execution_provider, + ComputeFn compute_fn, + ShapeInferFn shape_infer_fn = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { + compute_fn_ = reinterpret_cast(compute_fn); + ParseArgs(input_types_, output_types_); + + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + auto kernel = reinterpret_cast(op_kernel); + std::vector args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + std::apply([kernel](Args const&... t_args) { kernel->compute_fn_(t_args...); }, t); + }; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { + auto kernel = std::make_unique(); + auto me = static_cast(this_); + kernel->compute_fn_ = reinterpret_cast(me->compute_fn_); + Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); + Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); + auto self = static_cast(this_); + kernel->ep_ = self->execution_provider_; + return reinterpret_cast(kernel.release()); + }; + + OrtCustomOp::KernelDestroy = [](void* op_kernel) { + delete reinterpret_cast(op_kernel); + }; + + if (shape_infer_fn_) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + auto shape_info_fn = static_cast(op)->shape_infer_fn_; + ShapeInferContext ctx(&GetApi(), ort_ctx); + return shape_info_fn(ctx); + }; + } + } + + OrtLiteCustomFunc(const char* op_name, + const char* execution_provider, + ComputeFnReturnStatus compute_fn_return_status, + ShapeInferFn shape_infer_fn = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, shape_infer_fn, start_ver, end_ver) { + compute_fn_return_status_ = reinterpret_cast(compute_fn_return_status); + ParseArgs(input_types_, output_types_); + + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + auto kernel = reinterpret_cast(op_kernel); + std::vector args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + return std::apply([kernel](Args const&... t_args) { Status status = kernel->compute_fn_return_status_(t_args...); return status.release(); }, t); + }; + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { + auto kernel = std::make_unique(); + auto me = static_cast(this_); + kernel->compute_fn_return_status_ = reinterpret_cast(me->compute_fn_return_status_); + Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); + Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); + auto self = static_cast(this_); + kernel->ep_ = self->execution_provider_; + return reinterpret_cast(kernel.release()); + }; + + OrtCustomOp::KernelDestroy = [](void* op_kernel) { + delete reinterpret_cast(op_kernel); + }; + + if (shape_infer_fn_) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp* op, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + auto shape_info_fn = static_cast(op)->shape_infer_fn_; + ShapeInferContext ctx(&GetApi(), ort_ctx); + return shape_info_fn(ctx); + }; + } + } +}; // struct OrtLiteCustomFunc + +/////////////////////////// OrtLiteCustomStruct /////////////////////////// +// The struct is to implement struct-as-op. +// E.g. a struct might be defined as: +// struct Merge { +// Merge(const OrtApi* ort_api, const OrtKernelInfo* info) {...} +// void Compute(const Ort::Custom::Tensor& strings_in, +// std::string_view string_in, +// Ort::Custom::Tensor* strings_out) {...} +// bool reverse_ = false; +// }; +// It could be registered this way: +// Ort::CustomOpDomain v2_domain{"v2"}; +// std::unique_ptr mrg_op_ptr{Ort::Custom::CreateLiteCustomOp("Merge", "CPUExecutionProvider")}; +// v2_domain.Add(mrg_op_ptr.get()); +// session_options.Add(v2_domain); +// For the complete example, please search keyword "LiteCustomOpTest" under "/onnxruntime/test/". +template +struct OrtLiteCustomStruct : public OrtLiteCustomOp { + template + using CustomComputeFn = void (CustomOp::*)(Args...); + + template + using CustomComputeFnReturnStatus = Status (CustomOp::*)(Args...); + + using MyType = OrtLiteCustomStruct; + + struct Kernel { + size_t num_input_{}; + size_t num_output_{}; + std::unique_ptr custom_op_; + std::string ep_{}; + }; + + OrtLiteCustomStruct(const char* op_name, + const char* execution_provider, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) : OrtLiteCustomOp(op_name, execution_provider, {}, start_ver, end_ver) { + SetCompute(&CustomOp::Compute); + + OrtCustomOp::CreateKernel = [](const OrtCustomOp* this_, const OrtApi* ort_api, const OrtKernelInfo* info) { + auto kernel = std::make_unique(); + Ort::ThrowOnError(ort_api->KernelInfo_GetInputCount(info, &kernel->num_input_)); + Ort::ThrowOnError(ort_api->KernelInfo_GetOutputCount(info, &kernel->num_output_)); + kernel->custom_op_ = std::make_unique(ort_api, info); + auto self = static_cast(this_); + kernel->ep_ = self->execution_provider_; + return reinterpret_cast(kernel.release()); + }; + + OrtCustomOp::KernelDestroy = [](void* op_kernel) { + delete reinterpret_cast(op_kernel); + }; + + SetShapeInfer(0); + } + + template + void SetCompute(CustomComputeFn) { + ParseArgs(input_types_, output_types_); + OrtCustomOp::KernelCompute = [](void* op_kernel, OrtKernelContext* context) { + auto kernel = reinterpret_cast(op_kernel); + ArgPtrs args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + std::apply([kernel](Args const&... t_args) { kernel->custom_op_->Compute(t_args...); }, t); + }; + } + + template + void SetCompute(CustomComputeFnReturnStatus) { + ParseArgs(input_types_, output_types_); + OrtCustomOp::KernelComputeV2 = [](void* op_kernel, OrtKernelContext* context) -> OrtStatusPtr { + auto kernel = reinterpret_cast(op_kernel); + ArgPtrs args; + auto t = CreateTuple<0, 0, Args...>(context, args, kernel->num_input_, kernel->num_output_, kernel->ep_); + return std::apply([kernel](Args const&... t_args) { Status status = kernel->custom_op_->Compute(t_args...); return status.release(); }, t); + }; + } + + template + decltype(&C::InferOutputShape) SetShapeInfer(decltype(&C::InferOutputShape)) { + OrtCustomOp::InferOutputShapeFn = [](const OrtCustomOp*, OrtShapeInferContext* ort_ctx) -> OrtStatusPtr { + ShapeInferContext ctx(&GetApi(), ort_ctx); + return C::InferOutputShape(ctx); + }; + return {}; + } + + template + void SetShapeInfer(...) { + OrtCustomOp::InferOutputShapeFn = {}; + } +}; // struct OrtLiteCustomStruct + +/////////////////////////// CreateLiteCustomOp //////////////////////////// + +template +OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, + const char* execution_provider, + void (*custom_compute_fn)(Args...), + Status (*shape_infer_fn)(ShapeInferContext&) = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) { + using LiteOp = OrtLiteCustomFunc; + return std::make_unique(op_name, execution_provider, custom_compute_fn, shape_infer_fn, start_ver, end_ver).release(); +} + +template +OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, + const char* execution_provider, + Status (*custom_compute_fn_v2)(Args...), + Status (*shape_infer_fn)(ShapeInferContext&) = {}, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) { + using LiteOp = OrtLiteCustomFunc; + return std::make_unique(op_name, execution_provider, custom_compute_fn_v2, shape_infer_fn, start_ver, end_ver).release(); +} + +template +OrtLiteCustomOp* CreateLiteCustomOp(const char* op_name, + const char* execution_provider, + int start_ver = 1, + int end_ver = MAX_CUSTOM_OP_END_VER) { + using LiteOp = OrtLiteCustomStruct; + return std::make_unique(op_name, execution_provider, start_ver, end_ver).release(); +} + +} // namespace Custom +} // namespace Ort diff --git a/3rdParty/ONNX/onnxruntime_run_options_config_keys.h b/3rdParty/ONNX/onnxruntime_run_options_config_keys.h index bb4ce8d3fa..f40ea65910 100644 --- a/3rdParty/ONNX/onnxruntime_run_options_config_keys.h +++ b/3rdParty/ONNX/onnxruntime_run_options_config_keys.h @@ -1,54 +1,54 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -/* - * This file defines RunOptions Config Keys and format of the Config Values. - * - * The Naming Convention for a RunOptions Config Key, - * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" - * Such as "ep.cuda.use_arena" - * The Config Key cannot be empty - * The maximum length of the Config Key is 128 - * - * The string format of a RunOptions Config Value is defined individually for each Config. - * The maximum length of the Config Value is 1024 - */ - -// Key for enabling shrinkages of user listed device memory arenas. -// Expects a list of semi-colon separated key value pairs separated by colon in the following format: -// "device_0:device_id_0;device_1:device_id_1" -// No white-spaces allowed in the provided list string. -// Currently, the only supported devices are : "cpu", "gpu" (case sensitive). -// If "cpu" is included in the list, DisableCpuMemArena() API must not be called (i.e.) arena for cpu should be enabled. -// Example usage: "cpu:0;gpu:0" (or) "gpu:0" -// By default, the value for this key is empty (i.e.) no memory arenas are shrunk -static const char* const kOrtRunOptionsConfigEnableMemoryArenaShrinkage = "memory.enable_memory_arena_shrinkage"; - -// Set to '1' to not synchronize execution providers with CPU at the end of session run. -// Per default it will be set to '0' -// Taking CUDA EP as an example, it omit triggering cudaStreamSynchronize on the compute stream. -static const char* const kOrtRunOptionsConfigDisableSynchronizeExecutionProviders = "disable_synchronize_execution_providers"; - -// Set HTP performance mode for QNN HTP backend before session run. -// options for HTP performance mode: "burst", "balanced", "default", "high_performance", -// "high_power_saver", "low_balanced", "extreme_power_saver", "low_power_saver", "power_saver", -// "sustained_high_performance". Default to "default". -static const char* const kOrtRunOptionsConfigQnnPerfMode = "qnn.htp_perf_mode"; - -// Set HTP performance mode for QNN HTP backend post session run. -static const char* const kOrtRunOptionsConfigQnnPerfModePostRun = "qnn.htp_perf_mode_post_run"; - -// Set RPC control latency for QNN HTP backend -static const char* const kOrtRunOptionsConfigQnnRpcControlLatency = "qnn.rpc_control_latency"; - -// Set QNN Lora Config File for apply Lora in QNN context binary -static const char* const kOrtRunOptionsConfigQnnLoraConfig = "qnn.lora_config"; - -// Set graph annotation id for CUDA EP. Use with enable_cuda_graph=true. -// The value should be an integer. If the value is not set, the default value is 0 and -// ORT session only captures one cuda graph before another capture is requested. -// If the value is set to -1, cuda graph capture/replay is disabled in that run. -// User are not expected to set the value to 0 as it is reserved for internal use. -static const char* const kOrtRunOptionsConfigCudaGraphAnnotation = "gpu_graph_id"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +/* + * This file defines RunOptions Config Keys and format of the Config Values. + * + * The Naming Convention for a RunOptions Config Key, + * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" + * Such as "ep.cuda.use_arena" + * The Config Key cannot be empty + * The maximum length of the Config Key is 128 + * + * The string format of a RunOptions Config Value is defined individually for each Config. + * The maximum length of the Config Value is 1024 + */ + +// Key for enabling shrinkages of user listed device memory arenas. +// Expects a list of semi-colon separated key value pairs separated by colon in the following format: +// "device_0:device_id_0;device_1:device_id_1" +// No white-spaces allowed in the provided list string. +// Currently, the only supported devices are : "cpu", "gpu" (case sensitive). +// If "cpu" is included in the list, DisableCpuMemArena() API must not be called (i.e.) arena for cpu should be enabled. +// Example usage: "cpu:0;gpu:0" (or) "gpu:0" +// By default, the value for this key is empty (i.e.) no memory arenas are shrunk +static const char* const kOrtRunOptionsConfigEnableMemoryArenaShrinkage = "memory.enable_memory_arena_shrinkage"; + +// Set to '1' to not synchronize execution providers with CPU at the end of session run. +// Per default it will be set to '0' +// Taking CUDA EP as an example, it omit triggering cudaStreamSynchronize on the compute stream. +static const char* const kOrtRunOptionsConfigDisableSynchronizeExecutionProviders = "disable_synchronize_execution_providers"; + +// Set HTP performance mode for QNN HTP backend before session run. +// options for HTP performance mode: "burst", "balanced", "default", "high_performance", +// "high_power_saver", "low_balanced", "extreme_power_saver", "low_power_saver", "power_saver", +// "sustained_high_performance". Default to "default". +static const char* const kOrtRunOptionsConfigQnnPerfMode = "qnn.htp_perf_mode"; + +// Set HTP performance mode for QNN HTP backend post session run. +static const char* const kOrtRunOptionsConfigQnnPerfModePostRun = "qnn.htp_perf_mode_post_run"; + +// Set RPC control latency for QNN HTP backend +static const char* const kOrtRunOptionsConfigQnnRpcControlLatency = "qnn.rpc_control_latency"; + +// Set QNN Lora Config File for apply Lora in QNN context binary +static const char* const kOrtRunOptionsConfigQnnLoraConfig = "qnn.lora_config"; + +// Set graph annotation id for CUDA EP. Use with enable_cuda_graph=true. +// The value should be an integer. If the value is not set, the default value is 0 and +// ORT session only captures one cuda graph before another capture is requested. +// If the value is set to -1, cuda graph capture/replay is disabled in that run. +// User are not expected to set the value to 0 as it is reserved for internal use. +static const char* const kOrtRunOptionsConfigCudaGraphAnnotation = "gpu_graph_id"; diff --git a/3rdParty/ONNX/onnxruntime_session_options_config_keys.h b/3rdParty/ONNX/onnxruntime_session_options_config_keys.h index dec8e2b84d..5497d7c71a 100644 --- a/3rdParty/ONNX/onnxruntime_session_options_config_keys.h +++ b/3rdParty/ONNX/onnxruntime_session_options_config_keys.h @@ -1,366 +1,366 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -/* - * This file defines SessionOptions Config Keys and format of the Config Values. - * - * The Naming Convention for a SessionOptions Config Key, - * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" - * Such as "ep.cuda.use_arena" - * The Config Key cannot be empty - * The maximum length of the Config Key is 1024 - * - * The string format of a SessionOptions Config Value is defined individually for each Config. - * The maximum length of the Config Value is 2048 - */ - -// Key for disable PrePacking, -// If the config value is set to "1" then the prepacking is disabled, otherwise prepacking is enabled (default value) -static const char* const kOrtSessionOptionsConfigDisablePrepacking = "session.disable_prepacking"; - -// A value of "1" means allocators registered in the env will be used. "0" means the allocators created in the session -// will be used. Use this to override the usage of env allocators on a per session level. -static const char* const kOrtSessionOptionsConfigUseEnvAllocators = "session.use_env_allocators"; - -// Set to 'ORT' (case sensitive) to load an ORT format model. -// If unset, model type will default to ONNX unless inferred from filename ('.ort' == ORT format) or bytes to be ORT -static const char* const kOrtSessionOptionsConfigLoadModelFormat = "session.load_model_format"; - -// Set to 'ORT' (case sensitive) to save optimized model in ORT format when SessionOptions.optimized_model_path is set. -// If unset, format will default to ONNX unless optimized_model_filepath ends in '.ort'. -static const char* const kOrtSessionOptionsConfigSaveModelFormat = "session.save_model_format"; - -// If a value is "1", flush-to-zero and denormal-as-zero are applied. The default is "0". -// When multiple sessions are created, a main thread doesn't override changes from succeeding session options, -// but threads in session thread pools follow option changes. -// When ORT runs with OpenMP, the same rule is applied, i.e. the first session option to flush-to-zero and -// denormal-as-zero is only applied to global OpenMP thread pool, which doesn't support per-session thread pool. -// Note that an alternative way not using this option at runtime is to train and export a model without denormals -// and that's recommended because turning this option on may hurt model accuracy. -static const char* const kOrtSessionOptionsConfigSetDenormalAsZero = "session.set_denormal_as_zero"; - -// It controls to run quantization model in QDQ (QuantizelinearDeQuantizelinear) format or not. -// "0": enable. ORT does fusion logic for QDQ format. -// "1": disable. ORT doesn't do fusion logic for QDQ format. -// Its default value is "0" unless the DirectML execution provider is registered, in which case it defaults to "1". -static const char* const kOrtSessionOptionsDisableQuantQDQ = "session.disable_quant_qdq"; - -// It controls whether to enable Double QDQ remover and Identical Children Consolidation -// "0": not to disable. ORT does remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs -// "1": disable. ORT doesn't remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs -// Its default value is "0" -static const char* const kOrtSessionOptionsDisableDoubleQDQRemover = "session.disable_double_qdq_remover"; - -// If set to "1", enables the removal of QuantizeLinear/DequantizeLinear node pairs once all QDQ handling has been -// completed. e.g. If after all QDQ handling has completed and we have -> FloatOp -> Q -> DQ -> FloatOp -> the -// Q -> DQ could potentially be removed. This will provide a performance benefit by avoiding going from float to -// 8-bit and back to float, but could impact accuracy. The impact on accuracy will be model specific and depend on -// other factors like whether the model was created using Quantization Aware Training or Post Training Quantization. -// As such, it's best to test to determine if enabling this works well for your scenario. -// The default value is "0" -// Available since version 1.11. -static const char* const kOrtSessionOptionsEnableQuantQDQCleanup = "session.enable_quant_qdq_cleanup"; - -// Enable or disable gelu approximation in graph optimization. "0": disable; "1": enable. The default is "0". -// GeluApproximation has side effects which may change the inference results. It is disabled by default due to this. -static const char* const kOrtSessionOptionsEnableGeluApproximation = "optimization.enable_gelu_approximation"; - -// This setting controls whether to enable AheadOfTime function inlining. -// AOT function inlining examines the graph and attempts to inline as many locally defined functions in the model -// as possible with the help of enabled execution providers. -// This can reduce the number of function calls and improve performance because it is done before -// Level1 optimizers and constant folding. However, under some circumstances, when the EPs are not available, -// one can disable the AOT inlining, produce an optimized model and postpone AOT until run time. -// "0": enable; "1": disable. -// Its default value is "0". -static const char* const kOrtSessionOptionsDisableAheadOfTimeFunctionInlining = "session.disable_aot_function_inlining"; - -#ifdef ENABLE_TRAINING -// Specifies a path of the file containing a list of memory optimization configurations. -// The value should be a string indicating the file path of the config file. -// The content of the config file is a JSON struct like this: -// [ -// "Gelu+Cast+:1:0", -// "Dropout+:1:1" -// ] -// Taking the example of "Gelu+Cast+:1:0", -// > "Gelu+Cast+" is the subgraph string, a valid "subgraph string" should be one subgraph representation -// output by ORT graph transformations. -// > "1" is "optimization strategy", valid values: 0 - disabled, 1 - recompute. -// > "0" is "number of subgraph to apply" which is used to control how many subgraphs to apply optimization, -// to avoid "oversaving" the memory. -static const char* const kOrtSessionOptionsMemoryOptimizerApplyConfig = "optimization.memory_optimizer_config"; - -// Specifies the config for detecting subgraphs for memory footprint reduction. -// The value should be a string contains int separated using commas. The default value is "0:0". -static const char* const kOrtSessionOptionsMemoryOptimizerProbeConfig = "optimization.enable_memory_probe_recompute_config"; -#endif - -// This setting if set should contain a comma separated list of optimizers names that should be disabled. -// Optimizers may take time to execute and affect model loading time. If you feel that a specific optimizer -// does not provider runtime benefits, but affects your model loading time you may disable it using this config -// entry. This option is not enabled in ORT_MINIMAL_BUILD build. -// A list of optimizes is available in onnxruntime/core/optimizer/graph_transformer_utils.cc -// -// Default is an empty string which means no optimizers are disabled. -static const char* const kOrtSessionOptionsDisableSpecifiedOptimizers = "optimization.disable_specified_optimizers"; - -// Enable or disable using device allocator for allocating initialized tensor memory. "1": enable; "0": disable. The default is "0". -// Using device allocators means the memory allocation is made using malloc/new. -static const char* const kOrtSessionOptionsUseDeviceAllocatorForInitializers = "session.use_device_allocator_for_initializers"; - -// Configure whether to allow the inter_op/intra_op threads spinning a number of times before blocking -// "0": thread will block if found no job to run -// "1": default, thread will spin a number of times before blocking -static const char* const kOrtSessionOptionsConfigAllowInterOpSpinning = "session.inter_op.allow_spinning"; -static const char* const kOrtSessionOptionsConfigAllowIntraOpSpinning = "session.intra_op.allow_spinning"; - -// Key for using model bytes directly for ORT format -// If a session is created using an input byte array contains the ORT format model data, -// By default we will copy the model bytes at the time of session creation to ensure the model bytes -// buffer is valid. -// Setting this option to "1" will disable copy the model bytes, and use the model bytes directly. The caller -// has to guarantee that the model bytes are valid until the ORT session using the model bytes is destroyed. -static const char* const kOrtSessionOptionsConfigUseORTModelBytesDirectly = "session.use_ort_model_bytes_directly"; - -/// -/// Key for using the ORT format model flatbuffer bytes directly for initializers. -/// This avoids copying the bytes and reduces peak memory usage during model loading and initialization. -/// Requires `session.use_ort_model_bytes_directly` to be true. -/// If set, the flatbuffer bytes provided when creating the InferenceSession MUST remain valid for the entire -/// duration of the InferenceSession. -/// -static const char* const kOrtSessionOptionsConfigUseORTModelBytesForInitializers = - "session.use_ort_model_bytes_for_initializers"; - -// This should only be specified when exporting an ORT format model for use on a different platform. -// If the ORT format model will be used on ARM platforms set to "1". For other platforms set to "0" -// Available since version 1.11. -static const char* const kOrtSessionOptionsQDQIsInt8Allowed = "session.qdqisint8allowed"; - -// x64 SSE4.1/AVX2/AVX512(with no VNNI) has overflow problem with quantizied matrix multiplication with U8S8. -// To avoid this we need to use slower U8U8 matrix multiplication instead. This option, if -// turned on, use slower U8U8 matrix multiplications. Only effective with AVX2 or AVX512 -// platforms. -static const char* const kOrtSessionOptionsAvx2PrecisionMode = "session.x64quantprecision"; - -// Specifies how minimal build graph optimizations are handled in a full build. -// These optimizations are at the extended level or higher. -// Possible values and their effects are: -// "save": Save runtime optimizations when saving an ORT format model. -// "apply": Only apply optimizations available in a minimal build. -// ""/: Apply optimizations available in a full build. -// Available since version 1.11. -static const char* const kOrtSessionOptionsConfigMinimalBuildOptimizations = - "optimization.minimal_build_optimizations"; - -// Note: The options specific to an EP should be specified prior to appending that EP to the session options object in -// order for them to take effect. - -// Specifies a list of stop op types. Nodes of a type in the stop op types and nodes downstream from them will not be -// run by the NNAPI EP. -// The value should be a ","-delimited list of op types. For example, "Add,Sub". -// If not specified, the default set of stop ops is used. To specify an empty stop ops types list and disable stop op -// exclusion, set the value to "". -static const char* const kOrtSessionOptionsConfigNnapiEpPartitioningStopOps = "ep.nnapi.partitioning_stop_ops"; - -// Enabling dynamic block-sizing for multithreading. -// With a positive value, thread pool will split a task of N iterations to blocks of size starting from: -// N / (num_of_threads * dynamic_block_base) -// As execution progresses, the size will decrease according to the diminishing residual of N, -// meaning the task will be distributed in smaller granularity for better parallelism. -// For some models, it helps to reduce the variance of E2E inference latency and boost performance. -// The feature will not function by default, specify any positive integer, e.g. "4", to enable it. -// Available since version 1.11. -static const char* const kOrtSessionOptionsConfigDynamicBlockBase = "session.dynamic_block_base"; - -// This option allows to decrease CPU usage between infrequent -// requests and forces any TP threads spinning stop immediately when the last of -// concurrent Run() call returns. -// Spinning is restarted on the next Run() call. -// Applies only to internal thread-pools -static const char* const kOrtSessionOptionsConfigForceSpinningStop = "session.force_spinning_stop"; - -// "1": all inconsistencies encountered during shape and type inference -// will result in failures. -// "0": in some cases warnings will be logged but processing will continue. The default. -// May be useful to expose bugs in models. -static const char* const kOrtSessionOptionsConfigStrictShapeTypeInference = "session.strict_shape_type_inference"; - -// "1": every model using a more recent opset than the latest released one will fail -// "0": the model may or may not work if onnxruntime cannot find an implementation, this option -// is used for development purpose. -static const char* const kOrtSessionOptionsConfigStrictAllowReleasedOpsetsOnly = "session.allow_released_opsets_only"; - -// The file saves configuration for partitioning node among logic streams -static const char* const kNodePartitionConfigFile = "session.node_partition_config_file"; - -// This Option allows setting affinities for intra op threads. -// Affinity string follows format: -// logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id -// Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. -// e.g.1,2,3;4,5 -// specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. -// To ease the configuration, an "interval" is also allowed: -// e.g. 1-8;8-16;17-24 -// orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. -// Note: -// 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, since ort does not set affinity on the main thread which -// is started and managed by the calling app; -// 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, -// an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. -// Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. -static const char* const kOrtSessionOptionsConfigIntraOpThreadAffinities = "session.intra_op_thread_affinities"; - -// This option will dump out the model to assist debugging any issues with layout transformation, -// and is primarily intended for developer usage. It is only relevant if an execution provider that requests -// NHWC layout is enabled such as NNAPI, XNNPACK or QNN. -// -// Default is off. Set to "1" to enable. -// -// If modified by layout transformation the model will be dumped after these steps: -// 1) insertion of the layout transformation Transpose nodes -// 2) after those are optimized using the transpose optimizer, -// 3) after the L1 transformers are applied to the updated graph. -// The model will be saved to filename post_layout_transform_step_.onnx. -static const char* const kDebugLayoutTransformation = "session.debug_layout_transformation"; - -// Graph nodes that are not supported by the execution providers (EPs) explicitly added to the session are -// assigned (i.e., "fallback") to the CPU EP by default. -// -// This option allows the user to disable the fallback of unsupported graph nodes to the CPU EP. -// If this option is set to "1", session creation will fail if the execution providers other than the CPU EP cannot -// fully support all of the nodes in the graph. -// -// It is invalid to set this option and explicitly add the CPU EP to the session. In this case, session creation -// will also fail with an error. -// -// Option values: -// - "0": CPU EP fallback is not disabled. [DEFAULT] -// - "1": CPU EP fallback is disabled. -static const char* const kOrtSessionOptionsDisableCPUEPFallback = "session.disable_cpu_ep_fallback"; - -// Use this config when serializing a large model after optimization to specify an external initializers file -static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersFileName = - "session.optimized_model_external_initializers_file_name"; - -// Use this config to control the minimum size of the initializer when externalizing it during serialization -static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersMinSizeInBytes = - "session.optimized_model_external_initializers_min_size_in_bytes"; - -// When loading model from memory buffer and the model has external initializers -// Use this config to set the external data file folder path -// All external data files should be in the same folder -static const char* const kOrtSessionOptionsModelExternalInitializersFileFolderPath = - "session.model_external_initializers_file_folder_path"; - -// Use this config when saving pre-packed constant initializers to an external data file. -// This allows you to memory map pre-packed initializers on model load and leave it to -// to the OS the amount of memory consumed by the pre-packed initializers. Otherwise, -// pre-packed data resides on the heap. -// -// - "0": Default is not save pre-packed initializers to a data file. -// - "1": Save pre-packed constant initializers to an external data file. -// Sample usage: sess_options.add_session_config_entry(kOrtSessionOptionsSavePrePackedConstantInitializers, "1") -static const char* const kOrtSessionOptionsSavePrePackedConstantInitializers = - "session.save_external_prepacked_constant_initializers"; - -// Use this config when you want to collect memory stats for each node in the graph. -// The file format is a CSV file with the following columns: -// The file will be created if it does not exist, and will be overwritten if it does. -// -// The content of the file can be used to estimate memory requirements at run time including -// the temporary allocations. This operation is preferably done on a CPU device, as the model may exceed -// device memory limits in constrained environments. When enabling this option, it is important to disable -// memory patterns, as they tend to allocate large blocks to avoid fragmentation and accommodate needs of multiple -// kernels. Memory patterns may make it difficult to allocate on a device with limited memory. -// -// The collected stats then can be used to partition the graph among the devices in a way that only the -// required memory is allocated on each device. -// -// node_name, initializers_memory, dynamic_outputs_sizes, temp_allocations_size -// -// - "full path to file": there is not a default for this option. If the file can not be opened for writing, an error will be returned. -static const char* const kOrtSessionOptionsCollectNodeMemoryStatsToFile = "session.collect_node_memory_stats_to_file"; - -/// This is a composite CSV setting formatted as "memory limit in kb,file name for collected stats" -/// "limit > 0": enables Capacity Aware Partitioning for Cuda EP. `limit` is optional and when absent -/// the provider may attempt to figure out the memory available automatically. -/// The setting with no limit is expected to look like: ",file name for collected stats" -/// The EP will place nodes on device "file name" : -/// this file is expected to be found at the same folder with the model. The file contains -/// pre-recorded stats collected when running with kOrtSessionOptionsCollectNodeMemoryStatsToFile enforce (see above) -static const char* const kOrtSessionOptionsResourceCudaPartitioningSettings = - "session.resource_cuda_partitioning_settings"; - -// Enable EP context feature to dump the partitioned graph which includes the EP context into Onnx file. -// The dumped Onnx model with EP context can be used for future inference to avoid the EP graph partitioning/compile overhead. -// "0": disable. (default) -// "1": enable. -static const char* const kOrtSessionOptionEpContextEnable = "ep.context_enable"; - -// Specify the file path for the Onnx model which has EP context. -// Default to original_file_name_ctx.onnx if not specified -// Folder is not a valid option -static const char* const kOrtSessionOptionEpContextFilePath = "ep.context_file_path"; - -// Flag to specify whether to dump the EP context into the Onnx model. -// "0": dump the EP context into separate file, keep the file name in the Onnx model. (default). -// "1": dump the EP context into the Onnx model. -static const char* const kOrtSessionOptionEpContextEmbedMode = "ep.context_embed_mode"; - -// Specify the EPContext node name prefix to make it unique -// in case user need to merge/connect multiple EPContext nodes in one model -static const char* const kOrtSessionOptionEpContextNodeNamePrefix = "ep.context_node_name_prefix"; - -// Share EP related resources across sessions -static const char* const kOrtSessionOptionShareEpContexts = "ep.share_ep_contexts"; - -// Stop to share EP related resources across sessions from then on -static const char* const kOrtSessionOptionStopShareEpContexts = "ep.stop_share_ep_contexts"; - -// Used only for context model generation. -// This configuration is used when some nodes are partitioned on the CPU EP and those nodes have external initializers. -// When generating the EP context model, the new model should not rely on the old external data file used by the source ONNX model. -// Use this setting when dumping the EP context model with an external initializers file. -// If specified, all initializers will be placed inside the external data file. -// Otherwise, all initializers will be embedded inside the generated ONNX file. -// By default, this option is not set, meaning all initializers will be included within the ONNX file. -static const char* const kOrtSessionOptionsEpContextModelExternalInitializersFileName = - "ep.context_model_external_initializers_file_name"; - -// Gemm fastmath mode provides fp32 gemm acceleration with bfloat16 based matmul. -// Option values: -// - "0": Gemm FastMath mode is not enabled. [DEFAULT] -// - "1": Gemm FastMath mode is enabled. -static const char* const kOrtSessionOptionsMlasGemmFastMathArm64Bfloat16 = "mlas.enable_gemm_fastmath_arm64_bfloat16"; - -// When converting DQ + MatMul -> MatMulNBits, the accuracy level of the MatMulNBits is controlled by this option. -// Refer to MatMulNBits op schema for more details. -// If not provided, default is 4. -static const char* const kOrtSessionOptionsQDQMatMulNBitsAccuracyLevel = "session.qdq_matmulnbits_accuracy_level"; - -// THIS OPTION IS NOT A REGULAR SESSION OPTION SINCE IT CAN BE MODIFIED AT ANY TIME -// Meant to be used with SetEpDynamicOptions -// Specify the type of workload for this session. -// “Default”: OS determines the scheduling priority and processor performance to service this workload. [Default] -// “Efficient”: OS treats this workload is efficiency oriented with low scheduling priority and efficient processor performance. -static const char* const kOrtEpDynamicOptionsWorkloadType = "ep.dynamic.workload_type"; - -// Disables model compilation during session initialization. -// -// If this option is set to "1", inference session creation will fail with error code ORT_MODEL_REQUIRES_COMPILATION -// if compilation is required to run the model on any Execution Provider added to the session. -// Only the following kinds of models are valid when this option is set to "1": -// - Pre-compiled models that have EPContext nodes for the compiling Execution Providers in the session. -// - Non-compiled models that run only on non-compiling Execution Providers, like CPU EP. -// -// See \href https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html for details about -// compiled models with EPContext nodes. -// -// Option values: -// - "0": EP compile is not disabled. [DEFAULT] -// - "1": EP compile is disabled. -static const char* const kOrtSessionOptionsDisableModelCompile = "session.disable_model_compile"; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +/* + * This file defines SessionOptions Config Keys and format of the Config Values. + * + * The Naming Convention for a SessionOptions Config Key, + * "[Area][.[SubArea1].[SubArea2]...].[Keyname]" + * Such as "ep.cuda.use_arena" + * The Config Key cannot be empty + * The maximum length of the Config Key is 1024 + * + * The string format of a SessionOptions Config Value is defined individually for each Config. + * The maximum length of the Config Value is 2048 + */ + +// Key for disable PrePacking, +// If the config value is set to "1" then the prepacking is disabled, otherwise prepacking is enabled (default value) +static const char* const kOrtSessionOptionsConfigDisablePrepacking = "session.disable_prepacking"; + +// A value of "1" means allocators registered in the env will be used. "0" means the allocators created in the session +// will be used. Use this to override the usage of env allocators on a per session level. +static const char* const kOrtSessionOptionsConfigUseEnvAllocators = "session.use_env_allocators"; + +// Set to 'ORT' (case sensitive) to load an ORT format model. +// If unset, model type will default to ONNX unless inferred from filename ('.ort' == ORT format) or bytes to be ORT +static const char* const kOrtSessionOptionsConfigLoadModelFormat = "session.load_model_format"; + +// Set to 'ORT' (case sensitive) to save optimized model in ORT format when SessionOptions.optimized_model_path is set. +// If unset, format will default to ONNX unless optimized_model_filepath ends in '.ort'. +static const char* const kOrtSessionOptionsConfigSaveModelFormat = "session.save_model_format"; + +// If a value is "1", flush-to-zero and denormal-as-zero are applied. The default is "0". +// When multiple sessions are created, a main thread doesn't override changes from succeeding session options, +// but threads in session thread pools follow option changes. +// When ORT runs with OpenMP, the same rule is applied, i.e. the first session option to flush-to-zero and +// denormal-as-zero is only applied to global OpenMP thread pool, which doesn't support per-session thread pool. +// Note that an alternative way not using this option at runtime is to train and export a model without denormals +// and that's recommended because turning this option on may hurt model accuracy. +static const char* const kOrtSessionOptionsConfigSetDenormalAsZero = "session.set_denormal_as_zero"; + +// It controls to run quantization model in QDQ (QuantizelinearDeQuantizelinear) format or not. +// "0": enable. ORT does fusion logic for QDQ format. +// "1": disable. ORT doesn't do fusion logic for QDQ format. +// Its default value is "0" unless the DirectML execution provider is registered, in which case it defaults to "1". +static const char* const kOrtSessionOptionsDisableQuantQDQ = "session.disable_quant_qdq"; + +// It controls whether to enable Double QDQ remover and Identical Children Consolidation +// "0": not to disable. ORT does remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs +// "1": disable. ORT doesn't remove the middle 2 Nodes from a Q->(QD->Q)->QD pairs +// Its default value is "0" +static const char* const kOrtSessionOptionsDisableDoubleQDQRemover = "session.disable_double_qdq_remover"; + +// If set to "1", enables the removal of QuantizeLinear/DequantizeLinear node pairs once all QDQ handling has been +// completed. e.g. If after all QDQ handling has completed and we have -> FloatOp -> Q -> DQ -> FloatOp -> the +// Q -> DQ could potentially be removed. This will provide a performance benefit by avoiding going from float to +// 8-bit and back to float, but could impact accuracy. The impact on accuracy will be model specific and depend on +// other factors like whether the model was created using Quantization Aware Training or Post Training Quantization. +// As such, it's best to test to determine if enabling this works well for your scenario. +// The default value is "0" +// Available since version 1.11. +static const char* const kOrtSessionOptionsEnableQuantQDQCleanup = "session.enable_quant_qdq_cleanup"; + +// Enable or disable gelu approximation in graph optimization. "0": disable; "1": enable. The default is "0". +// GeluApproximation has side effects which may change the inference results. It is disabled by default due to this. +static const char* const kOrtSessionOptionsEnableGeluApproximation = "optimization.enable_gelu_approximation"; + +// This setting controls whether to enable AheadOfTime function inlining. +// AOT function inlining examines the graph and attempts to inline as many locally defined functions in the model +// as possible with the help of enabled execution providers. +// This can reduce the number of function calls and improve performance because it is done before +// Level1 optimizers and constant folding. However, under some circumstances, when the EPs are not available, +// one can disable the AOT inlining, produce an optimized model and postpone AOT until run time. +// "0": enable; "1": disable. +// Its default value is "0". +static const char* const kOrtSessionOptionsDisableAheadOfTimeFunctionInlining = "session.disable_aot_function_inlining"; + +#ifdef ENABLE_TRAINING +// Specifies a path of the file containing a list of memory optimization configurations. +// The value should be a string indicating the file path of the config file. +// The content of the config file is a JSON struct like this: +// [ +// "Gelu+Cast+:1:0", +// "Dropout+:1:1" +// ] +// Taking the example of "Gelu+Cast+:1:0", +// > "Gelu+Cast+" is the subgraph string, a valid "subgraph string" should be one subgraph representation +// output by ORT graph transformations. +// > "1" is "optimization strategy", valid values: 0 - disabled, 1 - recompute. +// > "0" is "number of subgraph to apply" which is used to control how many subgraphs to apply optimization, +// to avoid "oversaving" the memory. +static const char* const kOrtSessionOptionsMemoryOptimizerApplyConfig = "optimization.memory_optimizer_config"; + +// Specifies the config for detecting subgraphs for memory footprint reduction. +// The value should be a string contains int separated using commas. The default value is "0:0". +static const char* const kOrtSessionOptionsMemoryOptimizerProbeConfig = "optimization.enable_memory_probe_recompute_config"; +#endif + +// This setting if set should contain a comma separated list of optimizers names that should be disabled. +// Optimizers may take time to execute and affect model loading time. If you feel that a specific optimizer +// does not provider runtime benefits, but affects your model loading time you may disable it using this config +// entry. This option is not enabled in ORT_MINIMAL_BUILD build. +// A list of optimizes is available in onnxruntime/core/optimizer/graph_transformer_utils.cc +// +// Default is an empty string which means no optimizers are disabled. +static const char* const kOrtSessionOptionsDisableSpecifiedOptimizers = "optimization.disable_specified_optimizers"; + +// Enable or disable using device allocator for allocating initialized tensor memory. "1": enable; "0": disable. The default is "0". +// Using device allocators means the memory allocation is made using malloc/new. +static const char* const kOrtSessionOptionsUseDeviceAllocatorForInitializers = "session.use_device_allocator_for_initializers"; + +// Configure whether to allow the inter_op/intra_op threads spinning a number of times before blocking +// "0": thread will block if found no job to run +// "1": default, thread will spin a number of times before blocking +static const char* const kOrtSessionOptionsConfigAllowInterOpSpinning = "session.inter_op.allow_spinning"; +static const char* const kOrtSessionOptionsConfigAllowIntraOpSpinning = "session.intra_op.allow_spinning"; + +// Key for using model bytes directly for ORT format +// If a session is created using an input byte array contains the ORT format model data, +// By default we will copy the model bytes at the time of session creation to ensure the model bytes +// buffer is valid. +// Setting this option to "1" will disable copy the model bytes, and use the model bytes directly. The caller +// has to guarantee that the model bytes are valid until the ORT session using the model bytes is destroyed. +static const char* const kOrtSessionOptionsConfigUseORTModelBytesDirectly = "session.use_ort_model_bytes_directly"; + +/// +/// Key for using the ORT format model flatbuffer bytes directly for initializers. +/// This avoids copying the bytes and reduces peak memory usage during model loading and initialization. +/// Requires `session.use_ort_model_bytes_directly` to be true. +/// If set, the flatbuffer bytes provided when creating the InferenceSession MUST remain valid for the entire +/// duration of the InferenceSession. +/// +static const char* const kOrtSessionOptionsConfigUseORTModelBytesForInitializers = + "session.use_ort_model_bytes_for_initializers"; + +// This should only be specified when exporting an ORT format model for use on a different platform. +// If the ORT format model will be used on ARM platforms set to "1". For other platforms set to "0" +// Available since version 1.11. +static const char* const kOrtSessionOptionsQDQIsInt8Allowed = "session.qdqisint8allowed"; + +// x64 SSE4.1/AVX2/AVX512(with no VNNI) has overflow problem with quantizied matrix multiplication with U8S8. +// To avoid this we need to use slower U8U8 matrix multiplication instead. This option, if +// turned on, use slower U8U8 matrix multiplications. Only effective with AVX2 or AVX512 +// platforms. +static const char* const kOrtSessionOptionsAvx2PrecisionMode = "session.x64quantprecision"; + +// Specifies how minimal build graph optimizations are handled in a full build. +// These optimizations are at the extended level or higher. +// Possible values and their effects are: +// "save": Save runtime optimizations when saving an ORT format model. +// "apply": Only apply optimizations available in a minimal build. +// ""/: Apply optimizations available in a full build. +// Available since version 1.11. +static const char* const kOrtSessionOptionsConfigMinimalBuildOptimizations = + "optimization.minimal_build_optimizations"; + +// Note: The options specific to an EP should be specified prior to appending that EP to the session options object in +// order for them to take effect. + +// Specifies a list of stop op types. Nodes of a type in the stop op types and nodes downstream from them will not be +// run by the NNAPI EP. +// The value should be a ","-delimited list of op types. For example, "Add,Sub". +// If not specified, the default set of stop ops is used. To specify an empty stop ops types list and disable stop op +// exclusion, set the value to "". +static const char* const kOrtSessionOptionsConfigNnapiEpPartitioningStopOps = "ep.nnapi.partitioning_stop_ops"; + +// Enabling dynamic block-sizing for multithreading. +// With a positive value, thread pool will split a task of N iterations to blocks of size starting from: +// N / (num_of_threads * dynamic_block_base) +// As execution progresses, the size will decrease according to the diminishing residual of N, +// meaning the task will be distributed in smaller granularity for better parallelism. +// For some models, it helps to reduce the variance of E2E inference latency and boost performance. +// The feature will not function by default, specify any positive integer, e.g. "4", to enable it. +// Available since version 1.11. +static const char* const kOrtSessionOptionsConfigDynamicBlockBase = "session.dynamic_block_base"; + +// This option allows to decrease CPU usage between infrequent +// requests and forces any TP threads spinning stop immediately when the last of +// concurrent Run() call returns. +// Spinning is restarted on the next Run() call. +// Applies only to internal thread-pools +static const char* const kOrtSessionOptionsConfigForceSpinningStop = "session.force_spinning_stop"; + +// "1": all inconsistencies encountered during shape and type inference +// will result in failures. +// "0": in some cases warnings will be logged but processing will continue. The default. +// May be useful to expose bugs in models. +static const char* const kOrtSessionOptionsConfigStrictShapeTypeInference = "session.strict_shape_type_inference"; + +// "1": every model using a more recent opset than the latest released one will fail +// "0": the model may or may not work if onnxruntime cannot find an implementation, this option +// is used for development purpose. +static const char* const kOrtSessionOptionsConfigStrictAllowReleasedOpsetsOnly = "session.allow_released_opsets_only"; + +// The file saves configuration for partitioning node among logic streams +static const char* const kNodePartitionConfigFile = "session.node_partition_config_file"; + +// This Option allows setting affinities for intra op threads. +// Affinity string follows format: +// logical_processor_id,logical_processor_id;logical_processor_id,logical_processor_id +// Semicolon isolates configurations among threads, while comma split processors where ith thread expected to attach to. +// e.g.1,2,3;4,5 +// specifies affinities for two threads, with the 1st thread attach to the 1st, 2nd, and 3rd processor, and 2nd thread to the 4th and 5th. +// To ease the configuration, an "interval" is also allowed: +// e.g. 1-8;8-16;17-24 +// orders that the 1st thread runs on first eight processors, 2nd thread runs on next eight processors, and so forth. +// Note: +// 1. Once set, the number of thread affinities must equal to intra_op_num_threads - 1, since ort does not set affinity on the main thread which +// is started and managed by the calling app; +// 2. For windows, ort will infer the group id from a logical processor id, for example, assuming there are two groups with each has 64 logical processors, +// an id of 64 will be inferred as the last processor of the 1st group, while 65 will be interpreted as the 1st processor of the second group. +// Hence 64-65 is an invalid configuration, because a windows thread cannot be attached to processors across group boundary. +static const char* const kOrtSessionOptionsConfigIntraOpThreadAffinities = "session.intra_op_thread_affinities"; + +// This option will dump out the model to assist debugging any issues with layout transformation, +// and is primarily intended for developer usage. It is only relevant if an execution provider that requests +// NHWC layout is enabled such as NNAPI, XNNPACK or QNN. +// +// Default is off. Set to "1" to enable. +// +// If modified by layout transformation the model will be dumped after these steps: +// 1) insertion of the layout transformation Transpose nodes +// 2) after those are optimized using the transpose optimizer, +// 3) after the L1 transformers are applied to the updated graph. +// The model will be saved to filename post_layout_transform_step_.onnx. +static const char* const kDebugLayoutTransformation = "session.debug_layout_transformation"; + +// Graph nodes that are not supported by the execution providers (EPs) explicitly added to the session are +// assigned (i.e., "fallback") to the CPU EP by default. +// +// This option allows the user to disable the fallback of unsupported graph nodes to the CPU EP. +// If this option is set to "1", session creation will fail if the execution providers other than the CPU EP cannot +// fully support all of the nodes in the graph. +// +// It is invalid to set this option and explicitly add the CPU EP to the session. In this case, session creation +// will also fail with an error. +// +// Option values: +// - "0": CPU EP fallback is not disabled. [DEFAULT] +// - "1": CPU EP fallback is disabled. +static const char* const kOrtSessionOptionsDisableCPUEPFallback = "session.disable_cpu_ep_fallback"; + +// Use this config when serializing a large model after optimization to specify an external initializers file +static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersFileName = + "session.optimized_model_external_initializers_file_name"; + +// Use this config to control the minimum size of the initializer when externalizing it during serialization +static const char* const kOrtSessionOptionsOptimizedModelExternalInitializersMinSizeInBytes = + "session.optimized_model_external_initializers_min_size_in_bytes"; + +// When loading model from memory buffer and the model has external initializers +// Use this config to set the external data file folder path +// All external data files should be in the same folder +static const char* const kOrtSessionOptionsModelExternalInitializersFileFolderPath = + "session.model_external_initializers_file_folder_path"; + +// Use this config when saving pre-packed constant initializers to an external data file. +// This allows you to memory map pre-packed initializers on model load and leave it to +// to the OS the amount of memory consumed by the pre-packed initializers. Otherwise, +// pre-packed data resides on the heap. +// +// - "0": Default is not save pre-packed initializers to a data file. +// - "1": Save pre-packed constant initializers to an external data file. +// Sample usage: sess_options.add_session_config_entry(kOrtSessionOptionsSavePrePackedConstantInitializers, "1") +static const char* const kOrtSessionOptionsSavePrePackedConstantInitializers = + "session.save_external_prepacked_constant_initializers"; + +// Use this config when you want to collect memory stats for each node in the graph. +// The file format is a CSV file with the following columns: +// The file will be created if it does not exist, and will be overwritten if it does. +// +// The content of the file can be used to estimate memory requirements at run time including +// the temporary allocations. This operation is preferably done on a CPU device, as the model may exceed +// device memory limits in constrained environments. When enabling this option, it is important to disable +// memory patterns, as they tend to allocate large blocks to avoid fragmentation and accommodate needs of multiple +// kernels. Memory patterns may make it difficult to allocate on a device with limited memory. +// +// The collected stats then can be used to partition the graph among the devices in a way that only the +// required memory is allocated on each device. +// +// node_name, initializers_memory, dynamic_outputs_sizes, temp_allocations_size +// +// - "full path to file": there is not a default for this option. If the file can not be opened for writing, an error will be returned. +static const char* const kOrtSessionOptionsCollectNodeMemoryStatsToFile = "session.collect_node_memory_stats_to_file"; + +/// This is a composite CSV setting formatted as "memory limit in kb,file name for collected stats" +/// "limit > 0": enables Capacity Aware Partitioning for Cuda EP. `limit` is optional and when absent +/// the provider may attempt to figure out the memory available automatically. +/// The setting with no limit is expected to look like: ",file name for collected stats" +/// The EP will place nodes on device "file name" : +/// this file is expected to be found at the same folder with the model. The file contains +/// pre-recorded stats collected when running with kOrtSessionOptionsCollectNodeMemoryStatsToFile enforce (see above) +static const char* const kOrtSessionOptionsResourceCudaPartitioningSettings = + "session.resource_cuda_partitioning_settings"; + +// Enable EP context feature to dump the partitioned graph which includes the EP context into Onnx file. +// The dumped Onnx model with EP context can be used for future inference to avoid the EP graph partitioning/compile overhead. +// "0": disable. (default) +// "1": enable. +static const char* const kOrtSessionOptionEpContextEnable = "ep.context_enable"; + +// Specify the file path for the Onnx model which has EP context. +// Default to original_file_name_ctx.onnx if not specified +// Folder is not a valid option +static const char* const kOrtSessionOptionEpContextFilePath = "ep.context_file_path"; + +// Flag to specify whether to dump the EP context into the Onnx model. +// "0": dump the EP context into separate file, keep the file name in the Onnx model. (default). +// "1": dump the EP context into the Onnx model. +static const char* const kOrtSessionOptionEpContextEmbedMode = "ep.context_embed_mode"; + +// Specify the EPContext node name prefix to make it unique +// in case user need to merge/connect multiple EPContext nodes in one model +static const char* const kOrtSessionOptionEpContextNodeNamePrefix = "ep.context_node_name_prefix"; + +// Share EP related resources across sessions +static const char* const kOrtSessionOptionShareEpContexts = "ep.share_ep_contexts"; + +// Stop to share EP related resources across sessions from then on +static const char* const kOrtSessionOptionStopShareEpContexts = "ep.stop_share_ep_contexts"; + +// Used only for context model generation. +// This configuration is used when some nodes are partitioned on the CPU EP and those nodes have external initializers. +// When generating the EP context model, the new model should not rely on the old external data file used by the source ONNX model. +// Use this setting when dumping the EP context model with an external initializers file. +// If specified, all initializers will be placed inside the external data file. +// Otherwise, all initializers will be embedded inside the generated ONNX file. +// By default, this option is not set, meaning all initializers will be included within the ONNX file. +static const char* const kOrtSessionOptionsEpContextModelExternalInitializersFileName = + "ep.context_model_external_initializers_file_name"; + +// Gemm fastmath mode provides fp32 gemm acceleration with bfloat16 based matmul. +// Option values: +// - "0": Gemm FastMath mode is not enabled. [DEFAULT] +// - "1": Gemm FastMath mode is enabled. +static const char* const kOrtSessionOptionsMlasGemmFastMathArm64Bfloat16 = "mlas.enable_gemm_fastmath_arm64_bfloat16"; + +// When converting DQ + MatMul -> MatMulNBits, the accuracy level of the MatMulNBits is controlled by this option. +// Refer to MatMulNBits op schema for more details. +// If not provided, default is 4. +static const char* const kOrtSessionOptionsQDQMatMulNBitsAccuracyLevel = "session.qdq_matmulnbits_accuracy_level"; + +// THIS OPTION IS NOT A REGULAR SESSION OPTION SINCE IT CAN BE MODIFIED AT ANY TIME +// Meant to be used with SetEpDynamicOptions +// Specify the type of workload for this session. +// “Default”: OS determines the scheduling priority and processor performance to service this workload. [Default] +// “Efficient”: OS treats this workload is efficiency oriented with low scheduling priority and efficient processor performance. +static const char* const kOrtEpDynamicOptionsWorkloadType = "ep.dynamic.workload_type"; + +// Disables model compilation during session initialization. +// +// If this option is set to "1", inference session creation will fail with error code ORT_MODEL_REQUIRES_COMPILATION +// if compilation is required to run the model on any Execution Provider added to the session. +// Only the following kinds of models are valid when this option is set to "1": +// - Pre-compiled models that have EPContext nodes for the compiling Execution Providers in the session. +// - Non-compiled models that run only on non-compiling Execution Providers, like CPU EP. +// +// See \href https://onnxruntime.ai/docs/execution-providers/EP-Context-Design.html for details about +// compiled models with EPContext nodes. +// +// Option values: +// - "0": EP compile is not disabled. [DEFAULT] +// - "1": EP compile is disabled. +static const char* const kOrtSessionOptionsDisableModelCompile = "session.disable_model_compile"; diff --git a/3rdParty/ONNX/onnxruntime_training_c_api.h b/3rdParty/ONNX/onnxruntime_training_c_api.h index f5897d535c..ed6d151a59 100644 --- a/3rdParty/ONNX/onnxruntime_training_c_api.h +++ b/3rdParty/ONNX/onnxruntime_training_c_api.h @@ -1,731 +1,731 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -// This file contains the training c apis. - -#pragma once -#include -#include "onnxruntime_c_api.h" - -/** \page training_c_cpp_api Training C & C++ APIs - * - * Training C and C++ APIs are an extension of the \ref c_cpp_api "onnxruntime core C and C++ APIs" and should be used in conjunction with them. - * - * In order to train a model with onnxruntime, the following training artifacts must be generated: - * - The training onnx model - * - The checkpoint file - * - The optimizer onnx model - * - The eval onnx model model (optional) - * - * These training artifacts can be generated as part of an offline step using the python [utilities](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md) made available in the `onnxruntime-training` python package. - * - * After these artifacts have been generated, the C and C++ utilities listed in this documentation can be leveraged to perform training. - * - * If any problem is encountered, please create an [issue](https://github.com/microsoft/onnxruntime/issues/new) with your scenario and requirements, and we will be sure to respond and follow up on the request. - * - *

Training C API

- * - * ::OrtTrainingApi - Training C API functions. - * - * This C structure contains functions that enable users to perform training with onnxruntime. - * - * _Sample Code_: - * - * ```c - * #include - * - * OrtApi* g_ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION); - * OrtTrainingApi* g_ort_training_api = g_ort_api->GetTrainingApi(ORT_API_VERSION); - * - * OrtEnv* env = NULL; - * g_ort_api->CreateEnv(logging_level, logid, &env); - * OrtSessionOptions* session_options = NULL; - * g_ort_api->CreateSessionOptions(&session_options); - * - * OrtCheckpointState* state = NULL; - * g_ort_training_api->LoadCheckpoint(path_to_checkpoint, &state); - * - * OrtTrainingSession* training_session = NULL; - * g_ort_training_api->CreateTrainingSession(env, session_options, training_model_path, - * state, eval_model_path, optimizer_model_path, - * &training_session); - * // Training loop - * { - * g_ort_training_api->TrainStep(...); - * g_ort_training_api->OptimizerStep(...); - * g_ort_training_api->LazyResetGrad(...); - * } - * - * g_ort_training_api->ExportModelForInferencing(training_session, inference_model_path, ...); - * g_ort_training_api->SaveCheckpoint(state, path_to_checkpoint, false); - * - * g_ort_training_api->ReleaseTrainingSession(training_session); - * g_ort_training_api->ReleaseCheckpointState(state); - * ``` - * - * > **Note** - * > The ::OrtCheckpointState contains the entire training state that the ::OrtTrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::OrtCheckpointState instance must outlive the lifetime of the ::OrtTrainingSession instance. - * - *

Training C++ API

- * - * @ref TrainingCpp - Training C++ API classes and functions. - * - * These C++ classes and functions enable users to perform training with onnxruntime. - * - * _Sample Code_: - * - * ```cc - * #include - * - * Ort::Env env; - * Ort::SessionOptions session_options; - * - * auto state = Ort::CheckpointState::LoadCheckpoint(path_to_checkpoint); - * auto training_session = Ort::TrainingSession(env, session_options, state, training_model_path, - * eval_model_path, optimizer_model_path); - * - * // Training Loop - * { - * training_session.TrainStep(...); - * training_session.OptimizerStep(...); - * training_session.LazyResetGrad(...); - * } - * - * training_session->ExportModelForInferencing(inference_model_path, ...); - * Ort::CheckpointState::SaveCheckpoint(state, path_to_checkpoint, false); - * ``` - * > **Note** - * > The ::Ort::CheckpointState contains the entire training state that the ::Ort::TrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::Ort::CheckpointState instance must outlive the lifetime of the ::Ort::TrainingSession instance. - */ - -/** @defgroup TrainingC Ort Training C API - * @{ - */ -ORT_RUNTIME_CLASS(TrainingSession); // Type that enables performing training for the given user models. -ORT_RUNTIME_CLASS(CheckpointState); // Type that holds the training states for the training session. - -/** \brief Type of property to be added to or returned from the ::OrtCheckpointState. - */ -typedef enum OrtPropertyType { - OrtIntProperty = 0, - OrtFloatProperty = 1, - OrtStringProperty = 2, -} OrtPropertyType; - -/** \brief The Training C API that holds onnxruntime training function pointers - * - * All the Training C API functions are defined inside this structure as pointers to functions. - * Call OrtApi::GetTrainingApi to get a pointer to this struct. - * - * \nosubgrouping - */ -struct OrtTrainingApi { - /// \name Accessing The Training Session State - /// @{ - - /** \brief Load a checkpoint state from a file on disk into checkpoint_state. - * - * This function will parse a checkpoint file, pull relevant data and load the training - * state into the checkpoint_state. This checkpoint state can then be used to create the - * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training - * session will resume training from the given checkpoint state. - * \note Note that the training session created with a checkpoint state uses this state to store the entire - * training state (including model parameters, its gradients, the optimizer states and the properties). - * As a result, it is required that the checkpoint state outlive the lifetime of the training session. - * \note Note that the checkpoint file can be either the complete checkpoint or the nominal checkpoint. - * - * \param[in] checkpoint_path Path to the checkpoint file - * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(LoadCheckpoint, _In_ const ORTCHAR_T* checkpoint_path, - _Outptr_ OrtCheckpointState** checkpoint_state); - - /** \brief Save the given state to a checkpoint file on disk. - * - * This function serializes the provided checkpoint state to a file on disk. - * This checkpoint can later be loaded by invoking OrtTrainingApi::LoadCheckpoint to resume - * training from this snapshot of the state. - * - * \param[in] checkpoint_state The checkpoint state to save. - * \param[in] checkpoint_path Path to the checkpoint file. - * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SaveCheckpoint, _In_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* checkpoint_path, - const bool include_optimizer_state); - - /// @} - - /// \name Implementing The Training Loop - /// @{ - /** \brief Create a training session that can be used to begin or resume training. - * - * This function creates a training session based on the env and session options provided that can - * begin or resume training from a given checkpoint state for the given onnx models. - * The checkpoint state represents the parameters of the training session which will be moved - * to the device specified by the user through the session options (if necessary). - * The training session requires four training artifacts - * - The training onnx model - * - The evaluation onnx model (optional) - * - The optimizer onnx model - * - The checkpoint file - * - * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). - * - * \param[in] env Environment to be used for the training session. - * \param[in] options Session options that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_path Model to be used to perform training. - * \param[in] eval_model_path Model to be used to perform evaluation. - * \param[in] optimizer_model_path Model to be used to perform gradient descent. - * \param[out] out Created training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(CreateTrainingSession, _In_ const OrtEnv* env, _In_ const OrtSessionOptions* options, - _Inout_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* train_model_path, - _In_ const ORTCHAR_T* eval_model_path, _In_ const ORTCHAR_T* optimizer_model_path, - _Outptr_result_maybenull_ OrtTrainingSession** out); - - /** \brief Create a training session that can be used to begin or resume training. - * This api provides a way to load all the training artifacts from buffers instead of files. - * - * \param[in] env Environment to be used for the training session. - * \param[in] options Session options that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_data Buffer containing the model data to be used to perform training - * \param[in] train_data_length Length of the buffer containing train_model_data - * \param[in] eval_model_data Buffer containing the model data to be used to perform evaluation - * \param[in] eval_data_length Length of the buffer containing eval_model_data - * \param[in] optim_model_data Buffer containing the model data to be used to perform weight update - * \param[in] optim_data_length Length of the buffer containing optim_model_data - * \param[out] out Created training session. - * - */ - ORT_API2_STATUS(CreateTrainingSessionFromBuffer, _In_ const OrtEnv* env, - _In_ const OrtSessionOptions* options, _Inout_ OrtCheckpointState* checkpoint_state, - _In_ const void* train_model_data, size_t train_data_length, - _In_ const void* eval_model_data, size_t eval_data_length, - _In_ const void* optim_model_data, size_t optim_data_length, - _Outptr_result_maybenull_ OrtTrainingSession** out); - - /// @} - - /// \name Model IO Information - /// @{ - - /** \brief Retrieves the number of user outputs in the training model. - * - * This function returns the number of outputs of the training model so that the user can - * allocate space for the number of outputs when OrtTrainingApi::TrainStep is invoked. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user outputs in the training model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the number of user outputs in the eval model. - * - * This function returns the number of outputs of the eval model so that the user can - * allocate space for the number of outputs when OrtTrainingApi::EvalStep is invoked. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user outputs in the eval model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the names of user outputs in the training model. - * - * This function returns the names of outputs of the training model that can be associated with the OrtValue(s) - * returned by the OrtTrainingApi::TrainStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index Index of the output name requested. - * \param[in] allocator Allocator to use to allocate the memory for the name. - * \param[out] output Name of the training model output at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); - - /** \brief Retrieves the names of user outputs in the eval model. - * - * This function returns the names of outputs of the eval model that can be associated with the OrtValue(s) returned - * by the OrtTrainingApi::EvalStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index Index of the output name requested. - * \param[in] allocator Allocator to use to allocate the memory for the name. - * \param[out] output Name of the eval model output at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); - - /// @} - - /// \name Implementing The Training Loop - /// @{ - - /** \brief Reset the gradients of all trainable parameters to zero lazily. - * - * This function sets the internal state of the training session such that the gradients of the trainable - * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are - * computed on the next invocation of the next OrtTrainingApi::TrainStep. - * - * \param[in] session The `this` pointer to the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(LazyResetGrad, _Inout_ OrtTrainingSession* session); - - /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs - * - * This function performs a training step that computes the outputs of the training model and the gradients - * of the trainable parameters for the given inputs. The train step is performed based on the training model - * that was provided to the training session. - * The OrtTrainingApi::TrainStep is equivalent of running forward propagation and backward propagation in a single - * step. - * The gradients computed are stored inside the training session state so they can be later consumed - * by the OrtTrainingApi::OptimizerStep function. - * The gradients can be lazily reset by invoking the OrtTrainingApi::LazyResetGrad function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] run_options Run options for this training step. - * \param[in] inputs_len Number of user inputs to the training model. - * \param[in] inputs The user inputs to the training model. - * \param[in] outputs_len Number of user outputs expected from this training step. - * \param[out] outputs User outputs computed by train step. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainStep, _Inout_ OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, - _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, - _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); - - /** \brief Computes the outputs for the eval model for the given inputs - * - * This function performs an eval step that computes the outputs of the eval model for the given inputs. - * The eval step is performed based on the eval model that was provided to the training session. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] run_options Run options for this eval step. - * \param[in] inputs_len Number of user inputs to the eval model. - * \param[in] inputs The user inputs to the eval model. - * \param[in] outputs_len Number of user outputs expected from this eval step. - * \param[out] outputs User outputs computed by eval step. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(EvalStep, _In_ const OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, - _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, - _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); - - /** \brief Sets the learning rate for this training session. - * - * This function allows users to set the learning rate for the training session. The current - * learning rate is maintained by the training session and can be overwritten by invoking - * this function with the desired learning rate. This function should not be used when a valid - * learning rate scheduler is registered. It should be used either to set the learning rate - * derived from a custom learning rate scheduler or to set a constant learning rate to be used - * throughout the training session. - * \note Please note that this function does not set the initial learning rate that may be needed - * by the predefined learning rate schedulers. To set the initial learning rate for learning - * rate schedulers, please look at the function OrtTrainingApi::RegisterLinearLRScheduler. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] learning_rate Desired learning rate to be set. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SetLearningRate, _Inout_ OrtTrainingSession* sess, _In_ float learning_rate); - - /** \brief Gets the current learning rate for this training session. - * - * This function allows users to get the learning rate for the training session. The current - * learning rate is maintained by the training session, and users can query it for the purpose - * of implementing their own learning rate schedulers. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] learning_rate Learning rate currently in use by the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetLearningRate, _Inout_ OrtTrainingSession* sess, _Out_ float* learning_rate); - - /** \brief Performs the weight updates for the trainable parameters using the optimizer model. - * - * This function performs the weight update step that updates the trainable parameters such that they - * take a step in the direction of their gradients (gradient descent). The optimizer step is performed - * based on the optimizer model that was provided to the training session. - * The updated parameters are stored inside the training state so that they can be used by the next - * OrtTrainingApi::TrainStep function call. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] run_options Run options for this optimizer step. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(OptimizerStep, _Inout_ OrtTrainingSession* sess, - _In_opt_ const OrtRunOptions* run_options); - - /** \brief Registers a linear learning rate scheduler for the training session. - * - * Register a linear learning rate scheduler that decays the learning rate by linearly updated - * multiplicative factor from the initial learning rate set on the training session to 0. The decay - * is performed after the initial warm up phase where the learning rate is linearly incremented - * from 0 to the initial learning rate provided. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] warmup_step_count Warmup steps for LR warmup. - * \param[in] total_step_count Total step count. - * \param[in] initial_lr The initial learning rate to be used by the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(RegisterLinearLRScheduler, _Inout_ OrtTrainingSession* sess, _In_ const int64_t warmup_step_count, - _In_ const int64_t total_step_count, _In_ const float initial_lr); - - /** \brief Update the learning rate based on the registered learing rate scheduler. - * - * Takes a scheduler step that updates the learning rate that is being used by the training session. - * This function should typically be called before invoking the optimizer step for each round, - * or as determined necessary to update the learning rate being used by the training session. - * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this - * function. - * - * \param[in] sess The `this` pointer to the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SchedulerStep, _Inout_ OrtTrainingSession* sess); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - /** \brief Retrieves the size of all the parameters. - * - * Calculates the total number of primitive (datatype of the parameters) elements of all the parameters in the - * training state. - * When trainable_only argument is true, the size is calculated for trainable params only. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Size of all parameter elements. - * \param[in] trainable_only Whether to skip non-trainable parameters - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetParametersSize, _Inout_ OrtTrainingSession* sess, _Out_ size_t* out, bool trainable_only); - - /** \brief Copy all parameters to a contiguous buffer held by the argument parameters_buffer - * - * The parameters_buffer has to be of the size given by GetParametersSize api call, - * with matching setting for the argument trainable_only. All the target parameters must be of the same - * datatype. The OrtValue must be pre-allocated onto - * the desired device. This is a complementary function to OrtTrainingApi::CopyBufferToParameters. - * Parameter ordering is preserved. - * User is responsible for allocating and freeing the resources used by the parameters_buffer. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] trainable_only Whether to skip non-trainable parameters - * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy onto. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(CopyParametersToBuffer, _Inout_ OrtTrainingSession* sess, - _Inout_ OrtValue* parameters_buffer, bool trainable_only); - - /** \brief Copy parameter values from the given contiguous buffer held by parameters_buffer to the training state - * - * The parameters_buffer argument has to be of the size given by OrtTrainingApi::GetParametersSize api call, - * with matching setting for trainable_only argument. All the target parameters must be of the same - * datatype. This is a complementary function to OrtTrainingApi::CopyParametersToBuffer - * and can be used to load updated buffer values onto the training state. - * Parameter ordering is preserved. - * User is responsible for allocating and freeing the resources used by the parameters_buffer. - * In case the training session was created with a nominal checkpoint, invoking this function is required - * to load the updated parameters onto the checkpoint to complete it. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] trainable_only Whether to skip non-trainable parameters - * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy from. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(CopyBufferToParameters, _Inout_ OrtTrainingSession* sess, - _Inout_ OrtValue* parameters_buffer, bool trainable_only); - - /// @} - - /// \name Release Training Resources - /// @{ - - /** \brief Frees up the memory used up by the training session. - * - * This function frees up any memory that was allocated in the training session. The training - * session can no longer be used after this call. - * - */ - ORT_CLASS_RELEASE(TrainingSession); - - /** \brief Frees up the memory used up by the checkpoint state. - * - * This function frees up any memory that was allocated in the checkpoint state. The checkpoint - * state can no longer be used after this call. - * \note Note that the checkpoint state must be released only after the training session has been released. - * - */ - ORT_CLASS_RELEASE(CheckpointState); - - /// @} - - /// \name Prepare For Inferencing - /// @{ - /** \brief Export a model that can be used for inferencing. - * - * If the training session was provided with an eval model, the training session can generate - * an inference model if it knows the inference graph outputs. The input inference graph outputs - * are used to prune the eval model so that the inference model's outputs align with the provided outputs. - * The exported model is saved at the path provided and can be used for inferencing with InferenceSession. - * \note Note that the function re-loads the eval model from the path provided to OrtTrainingApi::CreateTrainingSession - * and expects that this path still be valid. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] inference_model_path Path where the inference model should be serialized to. - * \param[in] graph_outputs_len Size of the graph output names array. - * \param[in] graph_output_names Names of the outputs that are needed in the inference model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(ExportModelForInferencing, _Inout_ OrtTrainingSession* sess, - _In_ const ORTCHAR_T* inference_model_path, size_t graph_outputs_len, - _In_reads_(graph_outputs_len) const char* const* graph_output_names); - - /// @} - - /// \name Training Utilities - /// @{ - /** \brief Sets the seed used for random number generation in Onnxruntime. - * - * Use this function to generate reproducible results. It should be noted that completely reproducible - * results are not guaranteed. - * - * \param[in] seed The seed to be set. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(SetSeed, _In_ const int64_t seed); - - /// @} - - /// \name Model IO Information - /// @{ - /** \brief Retrieves the number of user inputs in the training model. - * - * This function returns the number of inputs of the training model so that the user can accordingly - * allocate the OrtValue(s) provided to the OrtTrainingApi::TrainStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user inputs in the training model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the number of user inputs in the eval model. - * - * This function returns the number of inputs of the eval model so that the user can accordingly - * allocate the OrtValue(s) provided to the OrtTrainingApi::EvalStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[out] out Number of user inputs in the eval model. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); - - /** \brief Retrieves the name of the user input at given index in the training model. - * - * This function returns the names of inputs of the training model that can be associated with the - * OrtValue(s) provided to the OrtTrainingApi::TrainStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index The index of the training model input name requested. - * \param[in] allocator The allocator to use to allocate the memory for the requested name. - * \param[out] output Name of the user input for the training model at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetTrainingModelInputName, _In_ const OrtTrainingSession* sess, size_t index, - _In_ OrtAllocator* allocator, _Outptr_ char** output); - - /** \brief Retrieves the name of the user input at given index in the eval model. - * - * This function returns the names of inputs of the eval model that can be associated with the OrtValue(s) provided - * to the OrtTrainingApi::EvalStep function. - * - * \param[in] sess The `this` pointer to the training session. - * \param[in] index The index of the eval model input name requested. - * \param[in] allocator The allocator to use to allocate the memory for the requested name. - * \param[out] output Name of the user input for the eval model at the given index. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(TrainingSessionGetEvalModelInputName, _In_ const OrtTrainingSession* sess, size_t index, - _In_ OrtAllocator* allocator, _Outptr_ char** output); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Adds or updates the given property to/in the checkpoint state. - * - * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint - * state by the user by calling this function with the corresponding property name and value. - * The given property name must be unique to be able to successfully add the property. - * - * \param[in] checkpoint_state The checkpoint state which should hold the property. - * \param[in] property_name Name of the property being added or updated. - * \param[in] property_type Type of the property associated with the given name. - * \param[in] property_value Property value associated with the given name. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(AddProperty, _Inout_ OrtCheckpointState* checkpoint_state, - _In_ const char* property_name, _In_ enum OrtPropertyType property_type, - _In_ void* property_value); - - /** \brief Gets the property value associated with the given name from the checkpoint state. - * - * Gets the property value from an existing entry in the checkpoint state. The property must - * exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] checkpoint_state The checkpoint state that is currently holding the property. - * \param[in] property_name Name of the property being retrieved. - * \param[in] allocator Allocator used to allocate the memory for the property_value. - * \param[out] property_type Type of the property associated with the given name. - * \param[out] property_value Property value associated with the given name. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetProperty, _In_ const OrtCheckpointState* checkpoint_state, - _In_ const char* property_name, _Inout_ OrtAllocator* allocator, - _Out_ enum OrtPropertyType* property_type, _Outptr_ void** property_value); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Load a checkpoint state from a buffer into checkpoint_state. - * - * This function will parse a checkpoint bytes buffer, pull relevant data and load the training - * state into the checkpoint_state. This checkpoint state can then be used to create the - * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training - * session will resume training from the given checkpoint state. - * \note Note that the training session created with a checkpoint state uses this state to store the entire - * training state (including model parameters, its gradients, the optimizer states and the properties). - * As a result, it is required that the checkpoint state outlive the lifetime of the training session. - * - * \param[in] checkpoint_buffer Path to the checkpoint bytes buffer. - * \param[in] num_bytes Number of bytes in the checkpoint buffer. - * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(LoadCheckpointFromBuffer, _In_ const void* checkpoint_buffer, - _In_ const size_t num_bytes, _Outptr_ OrtCheckpointState** checkpoint_state); - - /** \brief Retrieves the type and shape information of the parameter associated with the given parameter name. - * - * This function retrieves the type and shape of the parameter associated with the given parameter name. - * The parameter must exist in the checkpoint state to be able to retrieve its type and shape information successfully. - * - * \param[in] checkpoint_state The checkpoint state. - * \param[in] parameter_name Name of the parameter being retrieved. - * \param[out] parameter_type_and_shape The type and shape of the parameter being retrieved. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetParameterTypeAndShape, _In_ const OrtCheckpointState* checkpoint_state, - _In_ const char* parameter_name, _Outptr_ OrtTensorTypeAndShapeInfo** parameter_type_and_shape); - - /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. - * - * This function updates a model parameter in the checkpoint state with the given parameter data. - * The training session must be already created with the checkpoint state that contains the parameter - * being updated. The given parameter is copied over to the registered device for the training session. - * The parameter must exist in the checkpoint state to be able to update it successfully. - * - * \param[in] checkpoint_state The checkpoint state. - * \param[in] parameter_name Name of the parameter being updated. - * \param[in] parameter The parameter data that should replace the existing parameter data. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(UpdateParameter, _Inout_ OrtCheckpointState* checkpoint_state, - _In_ const char* parameter_name, _In_ OrtValue* parameter); - - /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. - * - * This function retrieves the model parameter data from the checkpoint state for the given parameter name. - * The parameter is copied over and returned as an OrtValue. The training session must be already created - * with the checkpoint state that contains the parameter being retrieved. - * The parameter must exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] checkpoint_state The checkpoint state. - * \param[in] parameter_name Name of the parameter being retrieved. - * \param[in] allocator Allocator used to allocate the memory for the parameter. - * \param[out] parameter The parameter data that is retrieved from the checkpoint state. - * - * \snippet{doc} snippets.dox OrtStatus Return Value - * - */ - ORT_API2_STATUS(GetParameter, _In_ const OrtCheckpointState* checkpoint_state, - _In_ const char* parameter_name, _Inout_ OrtAllocator* allocator, - _Outptr_ OrtValue** parameter); - - /// @} -}; - -typedef struct OrtTrainingApi OrtTrainingApi; - -/// @} +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +// This file contains the training c apis. + +#pragma once +#include +#include "onnxruntime_c_api.h" + +/** \page training_c_cpp_api Training C & C++ APIs + * + * Training C and C++ APIs are an extension of the \ref c_cpp_api "onnxruntime core C and C++ APIs" and should be used in conjunction with them. + * + * In order to train a model with onnxruntime, the following training artifacts must be generated: + * - The training onnx model + * - The checkpoint file + * - The optimizer onnx model + * - The eval onnx model model (optional) + * + * These training artifacts can be generated as part of an offline step using the python [utilities](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md) made available in the `onnxruntime-training` python package. + * + * After these artifacts have been generated, the C and C++ utilities listed in this documentation can be leveraged to perform training. + * + * If any problem is encountered, please create an [issue](https://github.com/microsoft/onnxruntime/issues/new) with your scenario and requirements, and we will be sure to respond and follow up on the request. + * + *

Training C API

+ * + * ::OrtTrainingApi - Training C API functions. + * + * This C structure contains functions that enable users to perform training with onnxruntime. + * + * _Sample Code_: + * + * ```c + * #include + * + * OrtApi* g_ort_api = OrtGetApiBase()->GetApi(ORT_API_VERSION); + * OrtTrainingApi* g_ort_training_api = g_ort_api->GetTrainingApi(ORT_API_VERSION); + * + * OrtEnv* env = NULL; + * g_ort_api->CreateEnv(logging_level, logid, &env); + * OrtSessionOptions* session_options = NULL; + * g_ort_api->CreateSessionOptions(&session_options); + * + * OrtCheckpointState* state = NULL; + * g_ort_training_api->LoadCheckpoint(path_to_checkpoint, &state); + * + * OrtTrainingSession* training_session = NULL; + * g_ort_training_api->CreateTrainingSession(env, session_options, training_model_path, + * state, eval_model_path, optimizer_model_path, + * &training_session); + * // Training loop + * { + * g_ort_training_api->TrainStep(...); + * g_ort_training_api->OptimizerStep(...); + * g_ort_training_api->LazyResetGrad(...); + * } + * + * g_ort_training_api->ExportModelForInferencing(training_session, inference_model_path, ...); + * g_ort_training_api->SaveCheckpoint(state, path_to_checkpoint, false); + * + * g_ort_training_api->ReleaseTrainingSession(training_session); + * g_ort_training_api->ReleaseCheckpointState(state); + * ``` + * + * > **Note** + * > The ::OrtCheckpointState contains the entire training state that the ::OrtTrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::OrtCheckpointState instance must outlive the lifetime of the ::OrtTrainingSession instance. + * + *

Training C++ API

+ * + * @ref TrainingCpp - Training C++ API classes and functions. + * + * These C++ classes and functions enable users to perform training with onnxruntime. + * + * _Sample Code_: + * + * ```cc + * #include + * + * Ort::Env env; + * Ort::SessionOptions session_options; + * + * auto state = Ort::CheckpointState::LoadCheckpoint(path_to_checkpoint); + * auto training_session = Ort::TrainingSession(env, session_options, state, training_model_path, + * eval_model_path, optimizer_model_path); + * + * // Training Loop + * { + * training_session.TrainStep(...); + * training_session.OptimizerStep(...); + * training_session.LazyResetGrad(...); + * } + * + * training_session->ExportModelForInferencing(inference_model_path, ...); + * Ort::CheckpointState::SaveCheckpoint(state, path_to_checkpoint, false); + * ``` + * > **Note** + * > The ::Ort::CheckpointState contains the entire training state that the ::Ort::TrainingSession uses. As a result, the training session must always have access to the state. That is to say, the ::Ort::CheckpointState instance must outlive the lifetime of the ::Ort::TrainingSession instance. + */ + +/** @defgroup TrainingC Ort Training C API + * @{ + */ +ORT_RUNTIME_CLASS(TrainingSession); // Type that enables performing training for the given user models. +ORT_RUNTIME_CLASS(CheckpointState); // Type that holds the training states for the training session. + +/** \brief Type of property to be added to or returned from the ::OrtCheckpointState. + */ +typedef enum OrtPropertyType { + OrtIntProperty = 0, + OrtFloatProperty = 1, + OrtStringProperty = 2, +} OrtPropertyType; + +/** \brief The Training C API that holds onnxruntime training function pointers + * + * All the Training C API functions are defined inside this structure as pointers to functions. + * Call OrtApi::GetTrainingApi to get a pointer to this struct. + * + * \nosubgrouping + */ +struct OrtTrainingApi { + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a file on disk into checkpoint_state. + * + * This function will parse a checkpoint file, pull relevant data and load the training + * state into the checkpoint_state. This checkpoint state can then be used to create the + * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training + * session will resume training from the given checkpoint state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * As a result, it is required that the checkpoint state outlive the lifetime of the training session. + * \note Note that the checkpoint file can be either the complete checkpoint or the nominal checkpoint. + * + * \param[in] checkpoint_path Path to the checkpoint file + * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LoadCheckpoint, _In_ const ORTCHAR_T* checkpoint_path, + _Outptr_ OrtCheckpointState** checkpoint_state); + + /** \brief Save the given state to a checkpoint file on disk. + * + * This function serializes the provided checkpoint state to a file on disk. + * This checkpoint can later be loaded by invoking OrtTrainingApi::LoadCheckpoint to resume + * training from this snapshot of the state. + * + * \param[in] checkpoint_state The checkpoint state to save. + * \param[in] checkpoint_path Path to the checkpoint file. + * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SaveCheckpoint, _In_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* checkpoint_path, + const bool include_optimizer_state); + + /// @} + + /// \name Implementing The Training Loop + /// @{ + /** \brief Create a training session that can be used to begin or resume training. + * + * This function creates a training session based on the env and session options provided that can + * begin or resume training from a given checkpoint state for the given onnx models. + * The checkpoint state represents the parameters of the training session which will be moved + * to the device specified by the user through the session options (if necessary). + * The training session requires four training artifacts + * - The training onnx model + * - The evaluation onnx model (optional) + * - The optimizer onnx model + * - The checkpoint file + * + * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). + * + * \param[in] env Environment to be used for the training session. + * \param[in] options Session options that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_path Model to be used to perform training. + * \param[in] eval_model_path Model to be used to perform evaluation. + * \param[in] optimizer_model_path Model to be used to perform gradient descent. + * \param[out] out Created training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CreateTrainingSession, _In_ const OrtEnv* env, _In_ const OrtSessionOptions* options, + _Inout_ OrtCheckpointState* checkpoint_state, _In_ const ORTCHAR_T* train_model_path, + _In_ const ORTCHAR_T* eval_model_path, _In_ const ORTCHAR_T* optimizer_model_path, + _Outptr_result_maybenull_ OrtTrainingSession** out); + + /** \brief Create a training session that can be used to begin or resume training. + * This api provides a way to load all the training artifacts from buffers instead of files. + * + * \param[in] env Environment to be used for the training session. + * \param[in] options Session options that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_data Buffer containing the model data to be used to perform training + * \param[in] train_data_length Length of the buffer containing train_model_data + * \param[in] eval_model_data Buffer containing the model data to be used to perform evaluation + * \param[in] eval_data_length Length of the buffer containing eval_model_data + * \param[in] optim_model_data Buffer containing the model data to be used to perform weight update + * \param[in] optim_data_length Length of the buffer containing optim_model_data + * \param[out] out Created training session. + * + */ + ORT_API2_STATUS(CreateTrainingSessionFromBuffer, _In_ const OrtEnv* env, + _In_ const OrtSessionOptions* options, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const void* train_model_data, size_t train_data_length, + _In_ const void* eval_model_data, size_t eval_data_length, + _In_ const void* optim_model_data, size_t optim_data_length, + _Outptr_result_maybenull_ OrtTrainingSession** out); + + /// @} + + /// \name Model IO Information + /// @{ + + /** \brief Retrieves the number of user outputs in the training model. + * + * This function returns the number of outputs of the training model so that the user can + * allocate space for the number of outputs when OrtTrainingApi::TrainStep is invoked. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user outputs in the training model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the number of user outputs in the eval model. + * + * This function returns the number of outputs of the eval model so that the user can + * allocate space for the number of outputs when OrtTrainingApi::EvalStep is invoked. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user outputs in the eval model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelOutputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the names of user outputs in the training model. + * + * This function returns the names of outputs of the training model that can be associated with the OrtValue(s) + * returned by the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index Index of the output name requested. + * \param[in] allocator Allocator to use to allocate the memory for the name. + * \param[out] output Name of the training model output at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); + + /** \brief Retrieves the names of user outputs in the eval model. + * + * This function returns the names of outputs of the eval model that can be associated with the OrtValue(s) returned + * by the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index Index of the output name requested. + * \param[in] allocator Allocator to use to allocate the memory for the name. + * \param[out] output Name of the eval model output at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelOutputName, _In_ const OrtTrainingSession* sess, size_t index, _Inout_ OrtAllocator* allocator, _Outptr_ char** output); + + /// @} + + /// \name Implementing The Training Loop + /// @{ + + /** \brief Reset the gradients of all trainable parameters to zero lazily. + * + * This function sets the internal state of the training session such that the gradients of the trainable + * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are + * computed on the next invocation of the next OrtTrainingApi::TrainStep. + * + * \param[in] session The `this` pointer to the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LazyResetGrad, _Inout_ OrtTrainingSession* session); + + /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs + * + * This function performs a training step that computes the outputs of the training model and the gradients + * of the trainable parameters for the given inputs. The train step is performed based on the training model + * that was provided to the training session. + * The OrtTrainingApi::TrainStep is equivalent of running forward propagation and backward propagation in a single + * step. + * The gradients computed are stored inside the training session state so they can be later consumed + * by the OrtTrainingApi::OptimizerStep function. + * The gradients can be lazily reset by invoking the OrtTrainingApi::LazyResetGrad function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this training step. + * \param[in] inputs_len Number of user inputs to the training model. + * \param[in] inputs The user inputs to the training model. + * \param[in] outputs_len Number of user outputs expected from this training step. + * \param[out] outputs User outputs computed by train step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainStep, _Inout_ OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, + _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, + _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); + + /** \brief Computes the outputs for the eval model for the given inputs + * + * This function performs an eval step that computes the outputs of the eval model for the given inputs. + * The eval step is performed based on the eval model that was provided to the training session. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this eval step. + * \param[in] inputs_len Number of user inputs to the eval model. + * \param[in] inputs The user inputs to the eval model. + * \param[in] outputs_len Number of user outputs expected from this eval step. + * \param[out] outputs User outputs computed by eval step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(EvalStep, _In_ const OrtTrainingSession* sess, _In_opt_ const OrtRunOptions* run_options, + _In_ size_t inputs_len, _In_reads_(inputs_len) const OrtValue* const* inputs, + _In_ size_t outputs_len, _Inout_updates_all_(outputs_len) OrtValue** outputs); + + /** \brief Sets the learning rate for this training session. + * + * This function allows users to set the learning rate for the training session. The current + * learning rate is maintained by the training session and can be overwritten by invoking + * this function with the desired learning rate. This function should not be used when a valid + * learning rate scheduler is registered. It should be used either to set the learning rate + * derived from a custom learning rate scheduler or to set a constant learning rate to be used + * throughout the training session. + * \note Please note that this function does not set the initial learning rate that may be needed + * by the predefined learning rate schedulers. To set the initial learning rate for learning + * rate schedulers, please look at the function OrtTrainingApi::RegisterLinearLRScheduler. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] learning_rate Desired learning rate to be set. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SetLearningRate, _Inout_ OrtTrainingSession* sess, _In_ float learning_rate); + + /** \brief Gets the current learning rate for this training session. + * + * This function allows users to get the learning rate for the training session. The current + * learning rate is maintained by the training session, and users can query it for the purpose + * of implementing their own learning rate schedulers. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] learning_rate Learning rate currently in use by the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetLearningRate, _Inout_ OrtTrainingSession* sess, _Out_ float* learning_rate); + + /** \brief Performs the weight updates for the trainable parameters using the optimizer model. + * + * This function performs the weight update step that updates the trainable parameters such that they + * take a step in the direction of their gradients (gradient descent). The optimizer step is performed + * based on the optimizer model that was provided to the training session. + * The updated parameters are stored inside the training state so that they can be used by the next + * OrtTrainingApi::TrainStep function call. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] run_options Run options for this optimizer step. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(OptimizerStep, _Inout_ OrtTrainingSession* sess, + _In_opt_ const OrtRunOptions* run_options); + + /** \brief Registers a linear learning rate scheduler for the training session. + * + * Register a linear learning rate scheduler that decays the learning rate by linearly updated + * multiplicative factor from the initial learning rate set on the training session to 0. The decay + * is performed after the initial warm up phase where the learning rate is linearly incremented + * from 0 to the initial learning rate provided. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] warmup_step_count Warmup steps for LR warmup. + * \param[in] total_step_count Total step count. + * \param[in] initial_lr The initial learning rate to be used by the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(RegisterLinearLRScheduler, _Inout_ OrtTrainingSession* sess, _In_ const int64_t warmup_step_count, + _In_ const int64_t total_step_count, _In_ const float initial_lr); + + /** \brief Update the learning rate based on the registered learing rate scheduler. + * + * Takes a scheduler step that updates the learning rate that is being used by the training session. + * This function should typically be called before invoking the optimizer step for each round, + * or as determined necessary to update the learning rate being used by the training session. + * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this + * function. + * + * \param[in] sess The `this` pointer to the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SchedulerStep, _Inout_ OrtTrainingSession* sess); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + /** \brief Retrieves the size of all the parameters. + * + * Calculates the total number of primitive (datatype of the parameters) elements of all the parameters in the + * training state. + * When trainable_only argument is true, the size is calculated for trainable params only. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Size of all parameter elements. + * \param[in] trainable_only Whether to skip non-trainable parameters + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParametersSize, _Inout_ OrtTrainingSession* sess, _Out_ size_t* out, bool trainable_only); + + /** \brief Copy all parameters to a contiguous buffer held by the argument parameters_buffer + * + * The parameters_buffer has to be of the size given by GetParametersSize api call, + * with matching setting for the argument trainable_only. All the target parameters must be of the same + * datatype. The OrtValue must be pre-allocated onto + * the desired device. This is a complementary function to OrtTrainingApi::CopyBufferToParameters. + * Parameter ordering is preserved. + * User is responsible for allocating and freeing the resources used by the parameters_buffer. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] trainable_only Whether to skip non-trainable parameters + * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy onto. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CopyParametersToBuffer, _Inout_ OrtTrainingSession* sess, + _Inout_ OrtValue* parameters_buffer, bool trainable_only); + + /** \brief Copy parameter values from the given contiguous buffer held by parameters_buffer to the training state + * + * The parameters_buffer argument has to be of the size given by OrtTrainingApi::GetParametersSize api call, + * with matching setting for trainable_only argument. All the target parameters must be of the same + * datatype. This is a complementary function to OrtTrainingApi::CopyParametersToBuffer + * and can be used to load updated buffer values onto the training state. + * Parameter ordering is preserved. + * User is responsible for allocating and freeing the resources used by the parameters_buffer. + * In case the training session was created with a nominal checkpoint, invoking this function is required + * to load the updated parameters onto the checkpoint to complete it. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] trainable_only Whether to skip non-trainable parameters + * \param[out] parameters_buffer The pre-allocated OrtValue buffer to copy from. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(CopyBufferToParameters, _Inout_ OrtTrainingSession* sess, + _Inout_ OrtValue* parameters_buffer, bool trainable_only); + + /// @} + + /// \name Release Training Resources + /// @{ + + /** \brief Frees up the memory used up by the training session. + * + * This function frees up any memory that was allocated in the training session. The training + * session can no longer be used after this call. + * + */ + ORT_CLASS_RELEASE(TrainingSession); + + /** \brief Frees up the memory used up by the checkpoint state. + * + * This function frees up any memory that was allocated in the checkpoint state. The checkpoint + * state can no longer be used after this call. + * \note Note that the checkpoint state must be released only after the training session has been released. + * + */ + ORT_CLASS_RELEASE(CheckpointState); + + /// @} + + /// \name Prepare For Inferencing + /// @{ + /** \brief Export a model that can be used for inferencing. + * + * If the training session was provided with an eval model, the training session can generate + * an inference model if it knows the inference graph outputs. The input inference graph outputs + * are used to prune the eval model so that the inference model's outputs align with the provided outputs. + * The exported model is saved at the path provided and can be used for inferencing with InferenceSession. + * \note Note that the function re-loads the eval model from the path provided to OrtTrainingApi::CreateTrainingSession + * and expects that this path still be valid. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] inference_model_path Path where the inference model should be serialized to. + * \param[in] graph_outputs_len Size of the graph output names array. + * \param[in] graph_output_names Names of the outputs that are needed in the inference model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(ExportModelForInferencing, _Inout_ OrtTrainingSession* sess, + _In_ const ORTCHAR_T* inference_model_path, size_t graph_outputs_len, + _In_reads_(graph_outputs_len) const char* const* graph_output_names); + + /// @} + + /// \name Training Utilities + /// @{ + /** \brief Sets the seed used for random number generation in Onnxruntime. + * + * Use this function to generate reproducible results. It should be noted that completely reproducible + * results are not guaranteed. + * + * \param[in] seed The seed to be set. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(SetSeed, _In_ const int64_t seed); + + /// @} + + /// \name Model IO Information + /// @{ + /** \brief Retrieves the number of user inputs in the training model. + * + * This function returns the number of inputs of the training model so that the user can accordingly + * allocate the OrtValue(s) provided to the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user inputs in the training model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the number of user inputs in the eval model. + * + * This function returns the number of inputs of the eval model so that the user can accordingly + * allocate the OrtValue(s) provided to the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[out] out Number of user inputs in the eval model. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelInputCount, _In_ const OrtTrainingSession* sess, _Out_ size_t* out); + + /** \brief Retrieves the name of the user input at given index in the training model. + * + * This function returns the names of inputs of the training model that can be associated with the + * OrtValue(s) provided to the OrtTrainingApi::TrainStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index The index of the training model input name requested. + * \param[in] allocator The allocator to use to allocate the memory for the requested name. + * \param[out] output Name of the user input for the training model at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetTrainingModelInputName, _In_ const OrtTrainingSession* sess, size_t index, + _In_ OrtAllocator* allocator, _Outptr_ char** output); + + /** \brief Retrieves the name of the user input at given index in the eval model. + * + * This function returns the names of inputs of the eval model that can be associated with the OrtValue(s) provided + * to the OrtTrainingApi::EvalStep function. + * + * \param[in] sess The `this` pointer to the training session. + * \param[in] index The index of the eval model input name requested. + * \param[in] allocator The allocator to use to allocate the memory for the requested name. + * \param[out] output Name of the user input for the eval model at the given index. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(TrainingSessionGetEvalModelInputName, _In_ const OrtTrainingSession* sess, size_t index, + _In_ OrtAllocator* allocator, _Outptr_ char** output); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Adds or updates the given property to/in the checkpoint state. + * + * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint + * state by the user by calling this function with the corresponding property name and value. + * The given property name must be unique to be able to successfully add the property. + * + * \param[in] checkpoint_state The checkpoint state which should hold the property. + * \param[in] property_name Name of the property being added or updated. + * \param[in] property_type Type of the property associated with the given name. + * \param[in] property_value Property value associated with the given name. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(AddProperty, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const char* property_name, _In_ enum OrtPropertyType property_type, + _In_ void* property_value); + + /** \brief Gets the property value associated with the given name from the checkpoint state. + * + * Gets the property value from an existing entry in the checkpoint state. The property must + * exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] checkpoint_state The checkpoint state that is currently holding the property. + * \param[in] property_name Name of the property being retrieved. + * \param[in] allocator Allocator used to allocate the memory for the property_value. + * \param[out] property_type Type of the property associated with the given name. + * \param[out] property_value Property value associated with the given name. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetProperty, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* property_name, _Inout_ OrtAllocator* allocator, + _Out_ enum OrtPropertyType* property_type, _Outptr_ void** property_value); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a buffer into checkpoint_state. + * + * This function will parse a checkpoint bytes buffer, pull relevant data and load the training + * state into the checkpoint_state. This checkpoint state can then be used to create the + * training session by invoking OrtTrainingApi::CreateTrainingSession. By doing so, the training + * session will resume training from the given checkpoint state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * As a result, it is required that the checkpoint state outlive the lifetime of the training session. + * + * \param[in] checkpoint_buffer Path to the checkpoint bytes buffer. + * \param[in] num_bytes Number of bytes in the checkpoint buffer. + * \param[out] checkpoint_state Checkpoint state that contains the states of the training session. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(LoadCheckpointFromBuffer, _In_ const void* checkpoint_buffer, + _In_ const size_t num_bytes, _Outptr_ OrtCheckpointState** checkpoint_state); + + /** \brief Retrieves the type and shape information of the parameter associated with the given parameter name. + * + * This function retrieves the type and shape of the parameter associated with the given parameter name. + * The parameter must exist in the checkpoint state to be able to retrieve its type and shape information successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being retrieved. + * \param[out] parameter_type_and_shape The type and shape of the parameter being retrieved. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParameterTypeAndShape, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _Outptr_ OrtTensorTypeAndShapeInfo** parameter_type_and_shape); + + /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. + * + * This function updates a model parameter in the checkpoint state with the given parameter data. + * The training session must be already created with the checkpoint state that contains the parameter + * being updated. The given parameter is copied over to the registered device for the training session. + * The parameter must exist in the checkpoint state to be able to update it successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being updated. + * \param[in] parameter The parameter data that should replace the existing parameter data. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(UpdateParameter, _Inout_ OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _In_ OrtValue* parameter); + + /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. + * + * This function retrieves the model parameter data from the checkpoint state for the given parameter name. + * The parameter is copied over and returned as an OrtValue. The training session must be already created + * with the checkpoint state that contains the parameter being retrieved. + * The parameter must exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] checkpoint_state The checkpoint state. + * \param[in] parameter_name Name of the parameter being retrieved. + * \param[in] allocator Allocator used to allocate the memory for the parameter. + * \param[out] parameter The parameter data that is retrieved from the checkpoint state. + * + * \snippet{doc} snippets.dox OrtStatus Return Value + * + */ + ORT_API2_STATUS(GetParameter, _In_ const OrtCheckpointState* checkpoint_state, + _In_ const char* parameter_name, _Inout_ OrtAllocator* allocator, + _Outptr_ OrtValue** parameter); + + /// @} +}; + +typedef struct OrtTrainingApi OrtTrainingApi; + +/// @} diff --git a/3rdParty/ONNX/onnxruntime_training_cxx_api.h b/3rdParty/ONNX/onnxruntime_training_cxx_api.h index 2697db5c21..e78c16136a 100644 --- a/3rdParty/ONNX/onnxruntime_training_cxx_api.h +++ b/3rdParty/ONNX/onnxruntime_training_cxx_api.h @@ -1,418 +1,418 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once -#include "onnxruntime_training_c_api.h" -#include -#include - -namespace Ort::detail { - -#define ORT_DECLARE_TRAINING_RELEASE(NAME) \ - void OrtRelease(Ort##NAME* ptr); - -// These release methods must be forward declared before including onnxruntime_cxx_api.h -// otherwise class Base won't be aware of them -ORT_DECLARE_TRAINING_RELEASE(CheckpointState); -ORT_DECLARE_TRAINING_RELEASE(TrainingSession); - -} // namespace Ort::detail - -#include "onnxruntime_cxx_api.h" - -namespace Ort { - -/// -/// This function returns the C training api struct with the pointers to the ort training C functions. -/// If using C++, please use the class instances instead of invoking the C functions directly. -/// -/// OrtTrainingApi struct with ort training C function pointers. -inline const OrtTrainingApi& GetTrainingApi() { return *GetApi().GetTrainingApi(ORT_API_VERSION); } - -namespace detail { - -#define ORT_DEFINE_TRAINING_RELEASE(NAME) \ - inline void OrtRelease(Ort##NAME* ptr) { GetTrainingApi().Release##NAME(ptr); } - -ORT_DEFINE_TRAINING_RELEASE(CheckpointState); -ORT_DEFINE_TRAINING_RELEASE(TrainingSession); - -#undef ORT_DECLARE_TRAINING_RELEASE -#undef ORT_DEFINE_TRAINING_RELEASE - -} // namespace detail - -using Property = std::variant; - -/** - * \defgroup TrainingCpp Ort Training C++ API - * @{ - */ - -/** \brief Holds the state of the training session. - * - * This class holds the entire training session state that includes model parameters, their gradients, - * optimizer parameters, and user properties. The Ort::TrainingSession leverages the Ort::CheckpointState - * by accessing and updating the contained training state. - * \note Note that the training session created with a checkpoint state uses this state to store the entire - * training state (including model parameters, its gradients, the optimizer states and the properties). - * The Ort::TrainingSession does not hold a copy of the Ort::CheckpointState and as a result, it is required - * that the checkpoint state outlive the lifetime of the training session. - * \note Note that the checkpoint state can be either the complete checkpoint state or the nominal checkpoint - * state depending on the version provided while loading the checkpoint. - * - */ -class CheckpointState : public detail::Base { - private: - CheckpointState(OrtCheckpointState* checkpoint_state) { p_ = checkpoint_state; } - - public: - // Construct the checkpoint state by loading the checkpoint by calling LoadCheckpoint - CheckpointState() = delete; - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Load a checkpoint state from a file on disk into checkpoint_state. - * - * This function will parse a checkpoint file, pull relevant data and load the training - * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the - * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume - * training from the given checkpoint state. - * - * \param[in] path_to_checkpoint Path to the checkpoint file - * \return Ort::CheckpointState object which holds the state of the training session parameters. - * - */ - static CheckpointState LoadCheckpoint(const std::basic_string& path_to_checkpoint); - - /** \brief Load a checkpoint state from a buffer. - * - * This function will parse a checkpoint buffer, pull relevant data and load the training - * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the - * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume - * training from the given checkpoint state. - * - * \param[in] buffer Buffer containing the checkpoint data. - * \return Ort::CheckpointState object which holds the state of the training session parameters. - * - */ - static CheckpointState LoadCheckpointFromBuffer(const std::vector& buffer); - - /** \brief Save the given state to a checkpoint file on disk. - * - * This function serializes the provided checkpoint state to a file on disk. - * This checkpoint can later be loaded by invoking Ort::CheckpointState::LoadCheckpoint to resume - * training from this snapshot of the state. - * - * \param[in] checkpoint_state The checkpoint state to save. - * \param[in] path_to_checkpoint Path to the checkpoint file. - * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. - * - */ - static void SaveCheckpoint(const CheckpointState& checkpoint_state, - const std::basic_string& path_to_checkpoint, - const bool include_optimizer_state = false); - - /** \brief Adds or updates the given property to/in the checkpoint state. - * - * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint - * state by the user by calling this function with the corresponding property name and value. - * The given property name must be unique to be able to successfully add the property. - * - * \param[in] property_name Name of the property being added or updated. - * \param[in] property_value Property value associated with the given name. - * - */ - void AddProperty(const std::string& property_name, const Property& property_value); - - /** \brief Gets the property value associated with the given name from the checkpoint state. - * - * Gets the property value from an existing entry in the checkpoint state. The property must - * exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] property_name Name of the property being retrieved. - * \return Property value associated with the given property name. - * - */ - Property GetProperty(const std::string& property_name); - - /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. - * - * This function updates a model parameter in the checkpoint state with the given parameter data. - * The training session must be already created with the checkpoint state that contains the parameter - * being updated. The given parameter is copied over to the registered device for the training session. - * The parameter must exist in the checkpoint state to be able to update it successfully. - * - * \param[in] parameter_name Name of the parameter being updated. - * \param[in] parameter The parameter data that should replace the existing parameter data. - * - */ - void UpdateParameter(const std::string& parameter_name, const Value& parameter); - - /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. - * - * This function retrieves the model parameter data from the checkpoint state for the given parameter name. - * The parameter is copied over to the provided OrtValue. The training session must be already created - * with the checkpoint state that contains the parameter being retrieved. - * The parameter must exist in the checkpoint state to be able to retrieve it successfully. - * - * \param[in] parameter_name Name of the parameter being retrieved. - * \return The parameter data that is retrieved from the checkpoint state. - * - */ - Value GetParameter(const std::string& parameter_name); - - /// @} -}; - -/** \brief Trainer class that provides training, evaluation and optimizer methods for training an ONNX models. - * - * The training session requires four training artifacts - * - The training onnx model - * - The evaluation onnx model (optional) - * - The optimizer onnx model - * - The checkpoint file - * - * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). - * - */ -class TrainingSession : public detail::Base { - private: - size_t training_model_output_count_, eval_model_output_count_; - - public: - /// \name Constructing the Training Session - /// @{ - /** \brief Create a training session that can be used to begin or resume training. - * - * This constructor instantiates the training session based on the env and session options provided that can - * begin or resume training from a given checkpoint state for the given onnx models. - * The checkpoint state represents the parameters of the training session which will be moved - * to the device specified by the user through the session options (if necessary). - * - * \param[in] env Env to be used for the training session. - * \param[in] session_options SessionOptions that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_path Model to be used to perform training. - * \param[in] eval_model_path Model to be used to perform evaluation. - * \param[in] optimizer_model_path Model to be used to perform gradient descent. - * - */ - TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, - const std::basic_string& train_model_path, - const std::optional>& eval_model_path = std::nullopt, - const std::optional>& optimizer_model_path = std::nullopt); - - /** \brief Create a training session that can be used to begin or resume training. - * This constructor allows the users to load the models from buffers instead of files. - * - * \param[in] env Env to be used for the training session. - * \param[in] session_options SessionOptions that the user can customize for this training session. - * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. - * \param[in] train_model_data Buffer containing training model data. - * \param[in] eval_model_data Buffer containing evaluation model data. - * \param[in] optim_model_data Buffer containing optimizer model (used for performing weight/parameter update). - * - */ - TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, - const std::vector& train_model_data, const std::vector& eval_model_data = {}, - const std::vector& optim_model_data = {}); - /// @} - - /// \name Implementing The Training Loop - /// @{ - /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs - * - * This function performs a training step that computes the outputs of the training model and the gradients - * of the trainable parameters for the given inputs. The train step is performed based on the training model - * that was provided to the training session. - * The Ort::TrainingSession::TrainStep is equivalent of running forward propagation and backward propagation in a single - * step. - * The gradients computed are stored inside the training session state so they can be later consumed - * by the Ort::TrainingSession::OptimizerStep function. - * The gradients can be lazily reset by invoking the Ort::TrainingSession::LazyResetGrad function. - * - * \param[in] input_values The user inputs to the training model. - * \return A std::vector of Ort::Value objects that represents the output of the forward pass of the training model. - * - * - */ - std::vector TrainStep(const std::vector& input_values); - - /** \brief Reset the gradients of all trainable parameters to zero lazily. - * - * This function sets the internal state of the training session such that the gradients of the trainable - * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are - * computed on the next invocation of the next Ort::TrainingSession::TrainStep. - * - */ - void LazyResetGrad(); - - /** \brief Computes the outputs for the eval model for the given inputs - * - * This function performs an eval step that computes the outputs of the eval model for the given inputs. - * The eval step is performed based on the eval model that was provided to the training session. - * - * \param[in] input_values The user inputs to the eval model. - * \return A std::vector of Ort::Value objects that represents the output of the eval pass. - * - */ - std::vector EvalStep(const std::vector& input_values); - - /** \brief Sets the learning rate for this training session. - * - * This function allows users to set the learning rate for the training session. The current - * learning rate is maintained by the training session and can be overwritten by invoking - * this function with the desired learning rate. This function should not be used when a valid - * learning rate scheduler is registered. It should be used either to set the learning rate - * derived from a custom learning rate scheduler or to set a constant learning rate to be used - * throughout the training session. - * \note Please note that this function does not set the initial learning rate that may be needed - * by the predefined learning rate schedulers. To set the initial learning rate for learning - * rate schedulers, please look at the function Ort::TrainingSession::RegisterLinearLRScheduler. - * - * \param[in] learning_rate Desired learning rate to be set. - * - */ - void SetLearningRate(float learning_rate); - - /** \brief Gets the current learning rate for this training session. - * - * This function allows users to get the learning rate for the training session. The current - * learning rate is maintained by the training session, and users can query it for the purpose - * of implementing their own learning rate schedulers. - * - * \return float representing the current learning rate. - * - */ - float GetLearningRate() const; - - /** \brief Registers a linear learning rate scheduler for the training session. - * - * Register a linear learning rate scheduler that decays the learning rate by linearly updated - * multiplicative factor from the initial learning rate set on the training session to 0. The decay - * is performed after the initial warm up phase where the learning rate is linearly incremented - * from 0 to the initial learning rate provided. - * - * \param[in] warmup_step_count Warmup steps for LR warmup. - * \param[in] total_step_count Total step count. - * \param[in] initial_lr The initial learning rate to be used by the training session. - * - */ - void RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, - float initial_lr); - - /** \brief Update the learning rate based on the registered learing rate scheduler. - * - * Takes a scheduler step that updates the learning rate that is being used by the training session. - * This function should typically be called before invoking the optimizer step for each round, - * or as determined necessary to update the learning rate being used by the training session. - * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this - * function. - * - */ - void SchedulerStep(); - - /** \brief Performs the weight updates for the trainable parameters using the optimizer model. - * - * This function performs the weight update step that updates the trainable parameters such that they - * take a step in the direction of their gradients (gradient descent). The optimizer step is performed - * based on the optimizer model that was provided to the training session. - * The updated parameters are stored inside the training state so that they can be used by the next - * Ort::TrainingSession::TrainStep function call. - * - */ - void OptimizerStep(); - - /// @} - - /// \name Prepare For Inferencing - /// @{ - - /** \brief Export a model that can be used for inferencing. - * - * If the training session was provided with an eval model, the training session can generate - * an inference model if it knows the inference graph outputs. The input inference graph outputs - * are used to prune the eval model so that the inference model's outputs align with the provided outputs. - * The exported model is saved at the path provided and can be used for inferencing with Ort::Session. - * \note Note that the function re-loads the eval model from the path provided to Ort::TrainingSession - * and expects that this path still be valid. - * - * \param[in] inference_model_path Path where the inference model should be serialized to. - * \param[in] graph_output_names Names of the outputs that are needed in the inference model. - * - */ - void ExportModelForInferencing(const std::basic_string& inference_model_path, - const std::vector& graph_output_names); - - /// @} - - /// \name Model IO Information - /// @{ - /** \brief Retrieves the names of the user inputs for the training and eval models. - * - * This function returns the names of inputs of the training or eval model that can be associated - * with the Ort::Value(s) provided to the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep - * function. - * - * \param[in] training Whether the training model input names are requested or eval model input names. - * \return Graph input names for either the training model or the eval model. - * - */ - std::vector InputNames(const bool training); - - /** \brief Retrieves the names of the user outputs for the training and eval models. - * - * This function returns the names of outputs of the training or eval model that can be associated - * with the Ort::Value(s) returned by the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep - * function. - * - * \param[in] training Whether the training model output names are requested or eval model output names. - * \return Graph output names for either the training model or the eval model. - * - */ - std::vector OutputNames(const bool training); - - /// @} - - /// \name Accessing The Training Session State - /// @{ - - /** \brief Returns a contiguous buffer that holds a copy of all training state parameters - * - * \param[in] only_trainable Whether to only copy trainable parameters or to copy all parameters. - * \return Contiguous buffer to the model parameters. - * - */ - Value ToBuffer(const bool only_trainable); - - /** \brief Loads the training session model parameters from a contiguous buffer - * - * In case the training session was created with a nominal checkpoint, invoking this function is required - * to load the updated parameters onto the checkpoint to complete it. - * - * \param[in] buffer Contiguous buffer to load the parameters from. - */ - void FromBuffer(Value& buffer); - - /// @} -}; - -/// \name Training Utilities -/// @{ -/** \brief This function sets the seed for generating random numbers. - * - * Use this function to generate reproducible results. It should be noted that completely - * reproducible results are not guaranteed. - * - * \param[in] seed Manual seed to use for random number generation. - */ -void SetSeed(const int64_t seed); -/// @} - -/// @} - -} // namespace Ort - -#include "onnxruntime_training_cxx_inline.h" +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once +#include "onnxruntime_training_c_api.h" +#include +#include + +namespace Ort::detail { + +#define ORT_DECLARE_TRAINING_RELEASE(NAME) \ + void OrtRelease(Ort##NAME* ptr); + +// These release methods must be forward declared before including onnxruntime_cxx_api.h +// otherwise class Base won't be aware of them +ORT_DECLARE_TRAINING_RELEASE(CheckpointState); +ORT_DECLARE_TRAINING_RELEASE(TrainingSession); + +} // namespace Ort::detail + +#include "onnxruntime_cxx_api.h" + +namespace Ort { + +/// +/// This function returns the C training api struct with the pointers to the ort training C functions. +/// If using C++, please use the class instances instead of invoking the C functions directly. +/// +/// OrtTrainingApi struct with ort training C function pointers. +inline const OrtTrainingApi& GetTrainingApi() { return *GetApi().GetTrainingApi(ORT_API_VERSION); } + +namespace detail { + +#define ORT_DEFINE_TRAINING_RELEASE(NAME) \ + inline void OrtRelease(Ort##NAME* ptr) { GetTrainingApi().Release##NAME(ptr); } + +ORT_DEFINE_TRAINING_RELEASE(CheckpointState); +ORT_DEFINE_TRAINING_RELEASE(TrainingSession); + +#undef ORT_DECLARE_TRAINING_RELEASE +#undef ORT_DEFINE_TRAINING_RELEASE + +} // namespace detail + +using Property = std::variant; + +/** + * \defgroup TrainingCpp Ort Training C++ API + * @{ + */ + +/** \brief Holds the state of the training session. + * + * This class holds the entire training session state that includes model parameters, their gradients, + * optimizer parameters, and user properties. The Ort::TrainingSession leverages the Ort::CheckpointState + * by accessing and updating the contained training state. + * \note Note that the training session created with a checkpoint state uses this state to store the entire + * training state (including model parameters, its gradients, the optimizer states and the properties). + * The Ort::TrainingSession does not hold a copy of the Ort::CheckpointState and as a result, it is required + * that the checkpoint state outlive the lifetime of the training session. + * \note Note that the checkpoint state can be either the complete checkpoint state or the nominal checkpoint + * state depending on the version provided while loading the checkpoint. + * + */ +class CheckpointState : public detail::Base { + private: + CheckpointState(OrtCheckpointState* checkpoint_state) { p_ = checkpoint_state; } + + public: + // Construct the checkpoint state by loading the checkpoint by calling LoadCheckpoint + CheckpointState() = delete; + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Load a checkpoint state from a file on disk into checkpoint_state. + * + * This function will parse a checkpoint file, pull relevant data and load the training + * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the + * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume + * training from the given checkpoint state. + * + * \param[in] path_to_checkpoint Path to the checkpoint file + * \return Ort::CheckpointState object which holds the state of the training session parameters. + * + */ + static CheckpointState LoadCheckpoint(const std::basic_string& path_to_checkpoint); + + /** \brief Load a checkpoint state from a buffer. + * + * This function will parse a checkpoint buffer, pull relevant data and load the training + * state and return an instance of Ort::CheckpointState. This checkpoint state can then be used to create the + * training session by instantiating Ort::TrainingSession. By doing so, the training session will resume + * training from the given checkpoint state. + * + * \param[in] buffer Buffer containing the checkpoint data. + * \return Ort::CheckpointState object which holds the state of the training session parameters. + * + */ + static CheckpointState LoadCheckpointFromBuffer(const std::vector& buffer); + + /** \brief Save the given state to a checkpoint file on disk. + * + * This function serializes the provided checkpoint state to a file on disk. + * This checkpoint can later be loaded by invoking Ort::CheckpointState::LoadCheckpoint to resume + * training from this snapshot of the state. + * + * \param[in] checkpoint_state The checkpoint state to save. + * \param[in] path_to_checkpoint Path to the checkpoint file. + * \param[in] include_optimizer_state Flag to indicate whether to save the optimizer state or not. + * + */ + static void SaveCheckpoint(const CheckpointState& checkpoint_state, + const std::basic_string& path_to_checkpoint, + const bool include_optimizer_state = false); + + /** \brief Adds or updates the given property to/in the checkpoint state. + * + * Runtime properties such as epoch, training step, best score, and others can be added to the checkpoint + * state by the user by calling this function with the corresponding property name and value. + * The given property name must be unique to be able to successfully add the property. + * + * \param[in] property_name Name of the property being added or updated. + * \param[in] property_value Property value associated with the given name. + * + */ + void AddProperty(const std::string& property_name, const Property& property_value); + + /** \brief Gets the property value associated with the given name from the checkpoint state. + * + * Gets the property value from an existing entry in the checkpoint state. The property must + * exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] property_name Name of the property being retrieved. + * \return Property value associated with the given property name. + * + */ + Property GetProperty(const std::string& property_name); + + /** \brief Updates the data associated with the model parameter in the checkpoint state for the given parameter name. + * + * This function updates a model parameter in the checkpoint state with the given parameter data. + * The training session must be already created with the checkpoint state that contains the parameter + * being updated. The given parameter is copied over to the registered device for the training session. + * The parameter must exist in the checkpoint state to be able to update it successfully. + * + * \param[in] parameter_name Name of the parameter being updated. + * \param[in] parameter The parameter data that should replace the existing parameter data. + * + */ + void UpdateParameter(const std::string& parameter_name, const Value& parameter); + + /** \brief Gets the data associated with the model parameter from the checkpoint state for the given parameter name. + * + * This function retrieves the model parameter data from the checkpoint state for the given parameter name. + * The parameter is copied over to the provided OrtValue. The training session must be already created + * with the checkpoint state that contains the parameter being retrieved. + * The parameter must exist in the checkpoint state to be able to retrieve it successfully. + * + * \param[in] parameter_name Name of the parameter being retrieved. + * \return The parameter data that is retrieved from the checkpoint state. + * + */ + Value GetParameter(const std::string& parameter_name); + + /// @} +}; + +/** \brief Trainer class that provides training, evaluation and optimizer methods for training an ONNX models. + * + * The training session requires four training artifacts + * - The training onnx model + * - The evaluation onnx model (optional) + * - The optimizer onnx model + * - The checkpoint file + * + * These artifacts can be generated using the `onnxruntime-training` python [utility](https://github.com/microsoft/onnxruntime/blob/main/orttraining/orttraining/python/training/onnxblock/README.md). + * + */ +class TrainingSession : public detail::Base { + private: + size_t training_model_output_count_, eval_model_output_count_; + + public: + /// \name Constructing the Training Session + /// @{ + /** \brief Create a training session that can be used to begin or resume training. + * + * This constructor instantiates the training session based on the env and session options provided that can + * begin or resume training from a given checkpoint state for the given onnx models. + * The checkpoint state represents the parameters of the training session which will be moved + * to the device specified by the user through the session options (if necessary). + * + * \param[in] env Env to be used for the training session. + * \param[in] session_options SessionOptions that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_path Model to be used to perform training. + * \param[in] eval_model_path Model to be used to perform evaluation. + * \param[in] optimizer_model_path Model to be used to perform gradient descent. + * + */ + TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, + const std::basic_string& train_model_path, + const std::optional>& eval_model_path = std::nullopt, + const std::optional>& optimizer_model_path = std::nullopt); + + /** \brief Create a training session that can be used to begin or resume training. + * This constructor allows the users to load the models from buffers instead of files. + * + * \param[in] env Env to be used for the training session. + * \param[in] session_options SessionOptions that the user can customize for this training session. + * \param[in] checkpoint_state Training states that the training session uses as a starting point for training. + * \param[in] train_model_data Buffer containing training model data. + * \param[in] eval_model_data Buffer containing evaluation model data. + * \param[in] optim_model_data Buffer containing optimizer model (used for performing weight/parameter update). + * + */ + TrainingSession(const Env& env, const SessionOptions& session_options, CheckpointState& checkpoint_state, + const std::vector& train_model_data, const std::vector& eval_model_data = {}, + const std::vector& optim_model_data = {}); + /// @} + + /// \name Implementing The Training Loop + /// @{ + /** \brief Computes the outputs of the training model and the gradients of the trainable parameters for the given inputs + * + * This function performs a training step that computes the outputs of the training model and the gradients + * of the trainable parameters for the given inputs. The train step is performed based on the training model + * that was provided to the training session. + * The Ort::TrainingSession::TrainStep is equivalent of running forward propagation and backward propagation in a single + * step. + * The gradients computed are stored inside the training session state so they can be later consumed + * by the Ort::TrainingSession::OptimizerStep function. + * The gradients can be lazily reset by invoking the Ort::TrainingSession::LazyResetGrad function. + * + * \param[in] input_values The user inputs to the training model. + * \return A std::vector of Ort::Value objects that represents the output of the forward pass of the training model. + * + * + */ + std::vector TrainStep(const std::vector& input_values); + + /** \brief Reset the gradients of all trainable parameters to zero lazily. + * + * This function sets the internal state of the training session such that the gradients of the trainable + * parameters in the OrtCheckpointState will be scheduled to be reset just before the new gradients are + * computed on the next invocation of the next Ort::TrainingSession::TrainStep. + * + */ + void LazyResetGrad(); + + /** \brief Computes the outputs for the eval model for the given inputs + * + * This function performs an eval step that computes the outputs of the eval model for the given inputs. + * The eval step is performed based on the eval model that was provided to the training session. + * + * \param[in] input_values The user inputs to the eval model. + * \return A std::vector of Ort::Value objects that represents the output of the eval pass. + * + */ + std::vector EvalStep(const std::vector& input_values); + + /** \brief Sets the learning rate for this training session. + * + * This function allows users to set the learning rate for the training session. The current + * learning rate is maintained by the training session and can be overwritten by invoking + * this function with the desired learning rate. This function should not be used when a valid + * learning rate scheduler is registered. It should be used either to set the learning rate + * derived from a custom learning rate scheduler or to set a constant learning rate to be used + * throughout the training session. + * \note Please note that this function does not set the initial learning rate that may be needed + * by the predefined learning rate schedulers. To set the initial learning rate for learning + * rate schedulers, please look at the function Ort::TrainingSession::RegisterLinearLRScheduler. + * + * \param[in] learning_rate Desired learning rate to be set. + * + */ + void SetLearningRate(float learning_rate); + + /** \brief Gets the current learning rate for this training session. + * + * This function allows users to get the learning rate for the training session. The current + * learning rate is maintained by the training session, and users can query it for the purpose + * of implementing their own learning rate schedulers. + * + * \return float representing the current learning rate. + * + */ + float GetLearningRate() const; + + /** \brief Registers a linear learning rate scheduler for the training session. + * + * Register a linear learning rate scheduler that decays the learning rate by linearly updated + * multiplicative factor from the initial learning rate set on the training session to 0. The decay + * is performed after the initial warm up phase where the learning rate is linearly incremented + * from 0 to the initial learning rate provided. + * + * \param[in] warmup_step_count Warmup steps for LR warmup. + * \param[in] total_step_count Total step count. + * \param[in] initial_lr The initial learning rate to be used by the training session. + * + */ + void RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, + float initial_lr); + + /** \brief Update the learning rate based on the registered learing rate scheduler. + * + * Takes a scheduler step that updates the learning rate that is being used by the training session. + * This function should typically be called before invoking the optimizer step for each round, + * or as determined necessary to update the learning rate being used by the training session. + * \note Please note that a valid predefined learning rate scheduler must be first registered to invoke this + * function. + * + */ + void SchedulerStep(); + + /** \brief Performs the weight updates for the trainable parameters using the optimizer model. + * + * This function performs the weight update step that updates the trainable parameters such that they + * take a step in the direction of their gradients (gradient descent). The optimizer step is performed + * based on the optimizer model that was provided to the training session. + * The updated parameters are stored inside the training state so that they can be used by the next + * Ort::TrainingSession::TrainStep function call. + * + */ + void OptimizerStep(); + + /// @} + + /// \name Prepare For Inferencing + /// @{ + + /** \brief Export a model that can be used for inferencing. + * + * If the training session was provided with an eval model, the training session can generate + * an inference model if it knows the inference graph outputs. The input inference graph outputs + * are used to prune the eval model so that the inference model's outputs align with the provided outputs. + * The exported model is saved at the path provided and can be used for inferencing with Ort::Session. + * \note Note that the function re-loads the eval model from the path provided to Ort::TrainingSession + * and expects that this path still be valid. + * + * \param[in] inference_model_path Path where the inference model should be serialized to. + * \param[in] graph_output_names Names of the outputs that are needed in the inference model. + * + */ + void ExportModelForInferencing(const std::basic_string& inference_model_path, + const std::vector& graph_output_names); + + /// @} + + /// \name Model IO Information + /// @{ + /** \brief Retrieves the names of the user inputs for the training and eval models. + * + * This function returns the names of inputs of the training or eval model that can be associated + * with the Ort::Value(s) provided to the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep + * function. + * + * \param[in] training Whether the training model input names are requested or eval model input names. + * \return Graph input names for either the training model or the eval model. + * + */ + std::vector InputNames(const bool training); + + /** \brief Retrieves the names of the user outputs for the training and eval models. + * + * This function returns the names of outputs of the training or eval model that can be associated + * with the Ort::Value(s) returned by the Ort::TrainingSession::TrainStep or Ort::TrainingSession::EvalStep + * function. + * + * \param[in] training Whether the training model output names are requested or eval model output names. + * \return Graph output names for either the training model or the eval model. + * + */ + std::vector OutputNames(const bool training); + + /// @} + + /// \name Accessing The Training Session State + /// @{ + + /** \brief Returns a contiguous buffer that holds a copy of all training state parameters + * + * \param[in] only_trainable Whether to only copy trainable parameters or to copy all parameters. + * \return Contiguous buffer to the model parameters. + * + */ + Value ToBuffer(const bool only_trainable); + + /** \brief Loads the training session model parameters from a contiguous buffer + * + * In case the training session was created with a nominal checkpoint, invoking this function is required + * to load the updated parameters onto the checkpoint to complete it. + * + * \param[in] buffer Contiguous buffer to load the parameters from. + */ + void FromBuffer(Value& buffer); + + /// @} +}; + +/// \name Training Utilities +/// @{ +/** \brief This function sets the seed for generating random numbers. + * + * Use this function to generate reproducible results. It should be noted that completely + * reproducible results are not guaranteed. + * + * \param[in] seed Manual seed to use for random number generation. + */ +void SetSeed(const int64_t seed); +/// @} + +/// @} + +} // namespace Ort + +#include "onnxruntime_training_cxx_inline.h" diff --git a/3rdParty/ONNX/onnxruntime_training_cxx_inline.h b/3rdParty/ONNX/onnxruntime_training_cxx_inline.h index f9961317da..397cba0b0f 100644 --- a/3rdParty/ONNX/onnxruntime_training_cxx_inline.h +++ b/3rdParty/ONNX/onnxruntime_training_cxx_inline.h @@ -1,295 +1,295 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once -#include "onnxruntime_training_c_api.h" -#include "onnxruntime_cxx_api.h" - -namespace Ort { - -inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, - CheckpointState& checkpoint_state, - const std::basic_string& train_model_path, - const std::optional>& eval_model_path, - const std::optional>& optimizer_model_path) { - ThrowOnError(GetTrainingApi().CreateTrainingSession( - env, session_options, checkpoint_state, - train_model_path.c_str(), - eval_model_path.has_value() ? eval_model_path.value().c_str() : nullptr, - optimizer_model_path.has_value() ? optimizer_model_path.value().c_str() : nullptr, - &p_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); -} - -inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, - CheckpointState& checkpoint_state, - const std::vector& train_model_data, - const std::vector& eval_model_data, - const std::vector& optim_model_data) { - ThrowOnError(GetTrainingApi().CreateTrainingSessionFromBuffer( - env, session_options, checkpoint_state, - train_model_data.data(), train_model_data.size(), - eval_model_data.data(), eval_model_data.size(), - optim_model_data.data(), optim_model_data.size(), - &p_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); - - ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); -} - -inline std::vector TrainingSession::TrainStep(const std::vector& input_values) { - std::vector output_values; - output_values.reserve(training_model_output_count_); - for (size_t i = 0; i < training_model_output_count_; i++) output_values.emplace_back(nullptr); - auto ort_input_values = reinterpret_cast(input_values.data()); - auto ort_output_values = reinterpret_cast(output_values.data()); - RunOptions run_options; - ThrowOnError(GetTrainingApi().TrainStep( - p_, run_options, input_values.size(), ort_input_values, - training_model_output_count_, ort_output_values)); - - return output_values; -} - -inline void TrainingSession::LazyResetGrad() { - ThrowOnError(GetTrainingApi().LazyResetGrad(p_)); -} - -inline std::vector TrainingSession::EvalStep(const std::vector& input_values) { - std::vector output_values; - output_values.reserve(eval_model_output_count_); - for (size_t i = 0; i < eval_model_output_count_; i++) output_values.emplace_back(nullptr); - auto ort_input_values = reinterpret_cast(input_values.data()); - auto ort_output_values = reinterpret_cast(output_values.data()); - RunOptions run_options; - ThrowOnError(GetTrainingApi().EvalStep( - p_, run_options, input_values.size(), ort_input_values, - eval_model_output_count_, ort_output_values)); - - return output_values; -} - -inline void TrainingSession::SetLearningRate(float learning_rate) { - ThrowOnError(GetTrainingApi().SetLearningRate(p_, learning_rate)); -} - -inline float TrainingSession::GetLearningRate() const { - float learning_rate = 0; - ThrowOnError(GetTrainingApi().GetLearningRate(p_, &learning_rate)); - return learning_rate; -} - -inline void TrainingSession::RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, - float initial_lr) { - ThrowOnError(GetTrainingApi().RegisterLinearLRScheduler(p_, warmup_step_count, total_step_count, - initial_lr)); -} - -inline void TrainingSession::SchedulerStep() { - ThrowOnError(GetTrainingApi().SchedulerStep(p_)); -} - -inline void TrainingSession::OptimizerStep() { - RunOptions run_options; - ThrowOnError(GetTrainingApi().OptimizerStep(p_, run_options)); -} - -inline std::vector TrainingSession::InputNames(const bool training) { - auto& input_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputCount - : GetTrainingApi().TrainingSessionGetEvalModelInputCount; - auto& input_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputName - : GetTrainingApi().TrainingSessionGetEvalModelInputName; - - size_t input_count = 0; - ThrowOnError(input_count_function(p_, &input_count)); - std::vector input_names(input_count); - AllocatorWithDefaultOptions allocator; - for (size_t index = 0; index < input_count; ++index) { - char* input_name; - ThrowOnError(input_name_function(p_, index, allocator, &input_name)); - input_names[index] = std::string(input_name); - allocator.Free(input_name); - } - - return input_names; -} - -inline std::vector TrainingSession::OutputNames(const bool training) { - auto& output_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputCount - : GetTrainingApi().TrainingSessionGetEvalModelOutputCount; - auto& output_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputName - : GetTrainingApi().TrainingSessionGetEvalModelOutputName; - - size_t output_count = 0; - ThrowOnError(output_count_function(p_, &output_count)); - std::vector output_names(output_count); - AllocatorWithDefaultOptions allocator; - for (size_t index = 0; index < output_count; ++index) { - char* output_name; - ThrowOnError(output_name_function(p_, index, allocator, &output_name)); - output_names[index] = std::string(output_name); - allocator.Free(output_name); - } - - return output_names; -} - -inline Value TrainingSession::ToBuffer(const bool only_trainable) { - size_t buffer_size = 0U; - ThrowOnError(GetTrainingApi().GetParametersSize(p_, &buffer_size, only_trainable)); - - std::array buffer_shape{static_cast(buffer_size)}; - - AllocatorWithDefaultOptions allocator; - Value buffer = Value::CreateTensor(allocator, buffer_shape.data(), 1U, - ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); - - ThrowOnError(GetTrainingApi().CopyParametersToBuffer(p_, buffer, only_trainable)); - - return buffer; -} - -inline void TrainingSession::FromBuffer(Value& buffer) { - if (!buffer.IsTensor()) { - ThrowStatus(Status("Incorrect buffer received. Expected a tensor buffer.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - } - - auto tensor_info = buffer.GetTensorTypeAndShapeInfo(); - auto buffer_shape = tensor_info.GetShape(); - - if (buffer_shape.size() != 1U) { - ThrowStatus(Status("Incorrect buffer received. Expected a contiguous tensor buffer.", - OrtErrorCode::ORT_INVALID_ARGUMENT)); - } - - auto buffer_size = buffer_shape.front(); - - size_t session_buffer_size = 0U; - ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size, false)); - - if (buffer_size == static_cast(session_buffer_size)) { - ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, false)); - return; - } - - size_t session_buffer_size_trainable_only = 0U; - ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size_trainable_only, true)); - - if (buffer_size == static_cast(session_buffer_size_trainable_only)) { - ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, true)); - return; - } else { - ThrowStatus(Status("Incorrect buffer size received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - } -} - -inline CheckpointState CheckpointState::LoadCheckpoint(const std::basic_string& path_to_checkpoint) { - OrtCheckpointState* checkpoint_state; - ThrowOnError(GetTrainingApi().LoadCheckpoint(path_to_checkpoint.c_str(), &checkpoint_state)); - return CheckpointState(checkpoint_state); -} - -inline CheckpointState CheckpointState::LoadCheckpointFromBuffer(const std::vector& buffer) { - OrtCheckpointState* checkpoint_state; - ThrowOnError(GetTrainingApi().LoadCheckpointFromBuffer(buffer.data(), buffer.size(), &checkpoint_state)); - return CheckpointState(checkpoint_state); -} - -inline void CheckpointState::SaveCheckpoint(const CheckpointState& checkpoint_states, - const std::basic_string& path_to_checkpoint, - const bool include_optimizer_state) { - ThrowOnError(GetTrainingApi().SaveCheckpoint(checkpoint_states, path_to_checkpoint.c_str(), - include_optimizer_state)); -} - -inline void TrainingSession::ExportModelForInferencing(const std::basic_string& inference_model_path, - const std::vector& graph_output_names) { - std::vector output_names; - output_names.reserve(graph_output_names.size()); - for (const auto& output_name : graph_output_names) { - output_names.push_back(output_name.c_str()); - } - ThrowOnError(GetTrainingApi().ExportModelForInferencing( - p_, inference_model_path.c_str(), graph_output_names.size(), output_names.data())); -} - -inline void SetSeed(const int64_t seed) { - ThrowOnError(GetTrainingApi().SetSeed(seed)); -} - -inline void CheckpointState::AddProperty(const std::string& property_name, const Property& property_value) { - if (std::holds_alternative(property_value)) { - int64_t value = std::get(property_value); - void* value_p = &value; - ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtIntProperty, value_p)); - } else if (std::holds_alternative(property_value)) { - float value = std::get(property_value); - void* value_p = &value; - ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtFloatProperty, value_p)); - } else if (std::holds_alternative(property_value)) { - std::string value = std::get(property_value); - auto buffer = std::make_unique(value.length() + 1); - memcpy(buffer.get(), value.c_str(), value.length()); - // AddProperty takes a char* and calls PropertyBag::AddProperty which takes a std::string. The data will be - // copied at that point so buffer can free the local allocation once the call is made. - ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtStringProperty, - buffer.get())); - } else { - ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - } -} - -inline Property CheckpointState::GetProperty(const std::string& property_name) { - void* property_value = nullptr; - OrtPropertyType property_type; - - AllocatorWithDefaultOptions allocator; - ThrowOnError(GetTrainingApi().GetProperty(p_, property_name.c_str(), allocator, &property_type, &property_value)); - - Property property; - - switch (property_type) { - case OrtPropertyType::OrtIntProperty: { - auto value_p = reinterpret_cast(property_value); - property = *value_p; - allocator.Free(property_value); - break; - } - case OrtPropertyType::OrtFloatProperty: { - auto value_p = reinterpret_cast(property_value); - property = *value_p; - allocator.Free(property_value); - break; - } - case OrtPropertyType::OrtStringProperty: { - auto value_p = reinterpret_cast(property_value); - property = std::string(value_p); - allocator.Free(property_value); - break; - } - default: { - ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); - break; - } - } - - return property; -} - -inline void CheckpointState::UpdateParameter(const std::string& parameter_name, const Value& parameter) { - ThrowOnError(GetTrainingApi().UpdateParameter(p_, parameter_name.c_str(), parameter)); -} - -inline Value CheckpointState::GetParameter(const std::string& parameter_name) { - AllocatorWithDefaultOptions allocator; - OrtValue* parameter; - ThrowOnError(GetTrainingApi().GetParameter(p_, parameter_name.c_str(), allocator, ¶meter)); - - return Value{parameter}; -} - -} // namespace Ort +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once +#include "onnxruntime_training_c_api.h" +#include "onnxruntime_cxx_api.h" + +namespace Ort { + +inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, + CheckpointState& checkpoint_state, + const std::basic_string& train_model_path, + const std::optional>& eval_model_path, + const std::optional>& optimizer_model_path) { + ThrowOnError(GetTrainingApi().CreateTrainingSession( + env, session_options, checkpoint_state, + train_model_path.c_str(), + eval_model_path.has_value() ? eval_model_path.value().c_str() : nullptr, + optimizer_model_path.has_value() ? optimizer_model_path.value().c_str() : nullptr, + &p_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); +} + +inline TrainingSession::TrainingSession(const Env& env, const SessionOptions& session_options, + CheckpointState& checkpoint_state, + const std::vector& train_model_data, + const std::vector& eval_model_data, + const std::vector& optim_model_data) { + ThrowOnError(GetTrainingApi().CreateTrainingSessionFromBuffer( + env, session_options, checkpoint_state, + train_model_data.data(), train_model_data.size(), + eval_model_data.data(), eval_model_data.size(), + optim_model_data.data(), optim_model_data.size(), + &p_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetTrainingModelOutputCount(p_, &training_model_output_count_)); + + ThrowOnError(GetTrainingApi().TrainingSessionGetEvalModelOutputCount(p_, &eval_model_output_count_)); +} + +inline std::vector TrainingSession::TrainStep(const std::vector& input_values) { + std::vector output_values; + output_values.reserve(training_model_output_count_); + for (size_t i = 0; i < training_model_output_count_; i++) output_values.emplace_back(nullptr); + auto ort_input_values = reinterpret_cast(input_values.data()); + auto ort_output_values = reinterpret_cast(output_values.data()); + RunOptions run_options; + ThrowOnError(GetTrainingApi().TrainStep( + p_, run_options, input_values.size(), ort_input_values, + training_model_output_count_, ort_output_values)); + + return output_values; +} + +inline void TrainingSession::LazyResetGrad() { + ThrowOnError(GetTrainingApi().LazyResetGrad(p_)); +} + +inline std::vector TrainingSession::EvalStep(const std::vector& input_values) { + std::vector output_values; + output_values.reserve(eval_model_output_count_); + for (size_t i = 0; i < eval_model_output_count_; i++) output_values.emplace_back(nullptr); + auto ort_input_values = reinterpret_cast(input_values.data()); + auto ort_output_values = reinterpret_cast(output_values.data()); + RunOptions run_options; + ThrowOnError(GetTrainingApi().EvalStep( + p_, run_options, input_values.size(), ort_input_values, + eval_model_output_count_, ort_output_values)); + + return output_values; +} + +inline void TrainingSession::SetLearningRate(float learning_rate) { + ThrowOnError(GetTrainingApi().SetLearningRate(p_, learning_rate)); +} + +inline float TrainingSession::GetLearningRate() const { + float learning_rate = 0; + ThrowOnError(GetTrainingApi().GetLearningRate(p_, &learning_rate)); + return learning_rate; +} + +inline void TrainingSession::RegisterLinearLRScheduler(int64_t warmup_step_count, int64_t total_step_count, + float initial_lr) { + ThrowOnError(GetTrainingApi().RegisterLinearLRScheduler(p_, warmup_step_count, total_step_count, + initial_lr)); +} + +inline void TrainingSession::SchedulerStep() { + ThrowOnError(GetTrainingApi().SchedulerStep(p_)); +} + +inline void TrainingSession::OptimizerStep() { + RunOptions run_options; + ThrowOnError(GetTrainingApi().OptimizerStep(p_, run_options)); +} + +inline std::vector TrainingSession::InputNames(const bool training) { + auto& input_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputCount + : GetTrainingApi().TrainingSessionGetEvalModelInputCount; + auto& input_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelInputName + : GetTrainingApi().TrainingSessionGetEvalModelInputName; + + size_t input_count = 0; + ThrowOnError(input_count_function(p_, &input_count)); + std::vector input_names(input_count); + AllocatorWithDefaultOptions allocator; + for (size_t index = 0; index < input_count; ++index) { + char* input_name; + ThrowOnError(input_name_function(p_, index, allocator, &input_name)); + input_names[index] = std::string(input_name); + allocator.Free(input_name); + } + + return input_names; +} + +inline std::vector TrainingSession::OutputNames(const bool training) { + auto& output_count_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputCount + : GetTrainingApi().TrainingSessionGetEvalModelOutputCount; + auto& output_name_function = training ? GetTrainingApi().TrainingSessionGetTrainingModelOutputName + : GetTrainingApi().TrainingSessionGetEvalModelOutputName; + + size_t output_count = 0; + ThrowOnError(output_count_function(p_, &output_count)); + std::vector output_names(output_count); + AllocatorWithDefaultOptions allocator; + for (size_t index = 0; index < output_count; ++index) { + char* output_name; + ThrowOnError(output_name_function(p_, index, allocator, &output_name)); + output_names[index] = std::string(output_name); + allocator.Free(output_name); + } + + return output_names; +} + +inline Value TrainingSession::ToBuffer(const bool only_trainable) { + size_t buffer_size = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &buffer_size, only_trainable)); + + std::array buffer_shape{static_cast(buffer_size)}; + + AllocatorWithDefaultOptions allocator; + Value buffer = Value::CreateTensor(allocator, buffer_shape.data(), 1U, + ONNXTensorElementDataType::ONNX_TENSOR_ELEMENT_DATA_TYPE_FLOAT); + + ThrowOnError(GetTrainingApi().CopyParametersToBuffer(p_, buffer, only_trainable)); + + return buffer; +} + +inline void TrainingSession::FromBuffer(Value& buffer) { + if (!buffer.IsTensor()) { + ThrowStatus(Status("Incorrect buffer received. Expected a tensor buffer.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + auto tensor_info = buffer.GetTensorTypeAndShapeInfo(); + auto buffer_shape = tensor_info.GetShape(); + + if (buffer_shape.size() != 1U) { + ThrowStatus(Status("Incorrect buffer received. Expected a contiguous tensor buffer.", + OrtErrorCode::ORT_INVALID_ARGUMENT)); + } + + auto buffer_size = buffer_shape.front(); + + size_t session_buffer_size = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size, false)); + + if (buffer_size == static_cast(session_buffer_size)) { + ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, false)); + return; + } + + size_t session_buffer_size_trainable_only = 0U; + ThrowOnError(GetTrainingApi().GetParametersSize(p_, &session_buffer_size_trainable_only, true)); + + if (buffer_size == static_cast(session_buffer_size_trainable_only)) { + ThrowOnError(GetTrainingApi().CopyBufferToParameters(p_, buffer, true)); + return; + } else { + ThrowStatus(Status("Incorrect buffer size received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } +} + +inline CheckpointState CheckpointState::LoadCheckpoint(const std::basic_string& path_to_checkpoint) { + OrtCheckpointState* checkpoint_state; + ThrowOnError(GetTrainingApi().LoadCheckpoint(path_to_checkpoint.c_str(), &checkpoint_state)); + return CheckpointState(checkpoint_state); +} + +inline CheckpointState CheckpointState::LoadCheckpointFromBuffer(const std::vector& buffer) { + OrtCheckpointState* checkpoint_state; + ThrowOnError(GetTrainingApi().LoadCheckpointFromBuffer(buffer.data(), buffer.size(), &checkpoint_state)); + return CheckpointState(checkpoint_state); +} + +inline void CheckpointState::SaveCheckpoint(const CheckpointState& checkpoint_states, + const std::basic_string& path_to_checkpoint, + const bool include_optimizer_state) { + ThrowOnError(GetTrainingApi().SaveCheckpoint(checkpoint_states, path_to_checkpoint.c_str(), + include_optimizer_state)); +} + +inline void TrainingSession::ExportModelForInferencing(const std::basic_string& inference_model_path, + const std::vector& graph_output_names) { + std::vector output_names; + output_names.reserve(graph_output_names.size()); + for (const auto& output_name : graph_output_names) { + output_names.push_back(output_name.c_str()); + } + ThrowOnError(GetTrainingApi().ExportModelForInferencing( + p_, inference_model_path.c_str(), graph_output_names.size(), output_names.data())); +} + +inline void SetSeed(const int64_t seed) { + ThrowOnError(GetTrainingApi().SetSeed(seed)); +} + +inline void CheckpointState::AddProperty(const std::string& property_name, const Property& property_value) { + if (std::holds_alternative(property_value)) { + int64_t value = std::get(property_value); + void* value_p = &value; + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtIntProperty, value_p)); + } else if (std::holds_alternative(property_value)) { + float value = std::get(property_value); + void* value_p = &value; + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtFloatProperty, value_p)); + } else if (std::holds_alternative(property_value)) { + std::string value = std::get(property_value); + auto buffer = std::make_unique(value.length() + 1); + memcpy(buffer.get(), value.c_str(), value.length()); + // AddProperty takes a char* and calls PropertyBag::AddProperty which takes a std::string. The data will be + // copied at that point so buffer can free the local allocation once the call is made. + ThrowOnError(GetTrainingApi().AddProperty(p_, property_name.c_str(), OrtPropertyType::OrtStringProperty, + buffer.get())); + } else { + ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + } +} + +inline Property CheckpointState::GetProperty(const std::string& property_name) { + void* property_value = nullptr; + OrtPropertyType property_type; + + AllocatorWithDefaultOptions allocator; + ThrowOnError(GetTrainingApi().GetProperty(p_, property_name.c_str(), allocator, &property_type, &property_value)); + + Property property; + + switch (property_type) { + case OrtPropertyType::OrtIntProperty: { + auto value_p = reinterpret_cast(property_value); + property = *value_p; + allocator.Free(property_value); + break; + } + case OrtPropertyType::OrtFloatProperty: { + auto value_p = reinterpret_cast(property_value); + property = *value_p; + allocator.Free(property_value); + break; + } + case OrtPropertyType::OrtStringProperty: { + auto value_p = reinterpret_cast(property_value); + property = std::string(value_p); + allocator.Free(property_value); + break; + } + default: { + ThrowStatus(Status("Unknown property type received.", OrtErrorCode::ORT_INVALID_ARGUMENT)); + break; + } + } + + return property; +} + +inline void CheckpointState::UpdateParameter(const std::string& parameter_name, const Value& parameter) { + ThrowOnError(GetTrainingApi().UpdateParameter(p_, parameter_name.c_str(), parameter)); +} + +inline Value CheckpointState::GetParameter(const std::string& parameter_name) { + AllocatorWithDefaultOptions allocator; + OrtValue* parameter; + ThrowOnError(GetTrainingApi().GetParameter(p_, parameter_name.c_str(), allocator, ¶meter)); + + return Value{parameter}; +} + +} // namespace Ort diff --git a/3rdParty/ONNX/provider_options.h b/3rdParty/ONNX/provider_options.h index 0e084c009a..aab13e808e 100644 --- a/3rdParty/ONNX/provider_options.h +++ b/3rdParty/ONNX/provider_options.h @@ -1,18 +1,18 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -#pragma once - -#include -#include -#include - -namespace onnxruntime { - -// data types for execution provider options - -using ProviderOptions = std::unordered_map; -using ProviderOptionsVector = std::vector; -using ProviderOptionsMap = std::unordered_map; - -} // namespace onnxruntime +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +#pragma once + +#include +#include +#include + +namespace onnxruntime { + +// data types for execution provider options + +using ProviderOptions = std::unordered_map; +using ProviderOptionsVector = std::vector; +using ProviderOptionsMap = std::unordered_map; + +} // namespace onnxruntime diff --git a/3rdParty/QtWavFile/WavFile.cpp b/3rdParty/QtWavFile/WavFile.cpp index dc400af665..e042b82b7b 100644 --- a/3rdParty/QtWavFile/WavFile.cpp +++ b/3rdParty/QtWavFile/WavFile.cpp @@ -1,199 +1,199 @@ -/* WAV FILE - * - * From: https://github.com/PokemonAutomation/ - * - * Class to read a .wav file. Edited from Qt multimedia example Spectrum: - * https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15 - * The git repo for Qt multimedia code and exmamples is https://code.qt.io/qt/qtmultimedia.git - * The version of the code is Qt5. - * Since the code is licensed by Qt under BSD, we can safely use it with our code base, provided - * that we have the original BSD license below and release the source code. - */ - -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include "WavFile.h" - -#include - -struct chunk -{ - char id[4]; - quint32 size; -}; - -struct RIFFHeader -{ - chunk descriptor; // "RIFF" - char type[4]; // "WAVE" -}; - -struct WAVEHeader -{ - chunk descriptor; - quint16 audioFormat; - quint16 numChannels; - quint32 sample_rate; - quint32 byteRate; - quint16 blockAlign; - quint16 bitsPerSample; -}; - -struct DATAHeader -{ - chunk descriptor; -}; - -struct CombinedHeader -{ - RIFFHeader riff; - WAVEHeader wave; -}; - -WavFile::WavFile(QObject *parent) - : QFile(parent) - , m_headerLength(0) -{ - -} - -bool WavFile::open(const QString &fileName) -{ - close(); - setFileName(fileName); - return QFile::open(QIODevice::ReadOnly) && readHeader(); -} - -const QAudioFormat &WavFile::audioFormat() const -{ - return m_fileFormat; -} - -qint64 WavFile::headerLength() const -{ -return m_headerLength; -} - -bool WavFile::readHeader() -{ - seek(0); - CombinedHeader header; - bool result = read(reinterpret_cast(&header), sizeof(CombinedHeader)) == sizeof(CombinedHeader); - if (result) { - if ((memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0 - || memcmp(&header.riff.descriptor.id, "RIFX", 4) == 0) - && memcmp(&header.riff.type, "WAVE", 4) == 0 - && memcmp(&header.wave.descriptor.id, "fmt ", 4) == 0 - && (header.wave.audioFormat == 1 || header.wave.audioFormat == 0)) { - - // Read off remaining header information - DATAHeader dataHeader; - - if (qFromLittleEndian(header.wave.descriptor.size) > sizeof(WAVEHeader)) { - // Extended data available - quint16 extraFormatBytes; - if (peek((char*)&extraFormatBytes, sizeof(quint16)) != sizeof(quint16)) - return false; - const qint64 throwAwayBytes = sizeof(quint16) + qFromLittleEndian(extraFormatBytes); - if (read(throwAwayBytes).size() != throwAwayBytes) - return false; - } - - if (read((char*)&dataHeader, sizeof(DATAHeader)) != sizeof(DATAHeader)) - return false; - - // Establish format - -#if QT_VERSION_MAJOR == 5 - if (memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0) - m_fileFormat.setByteOrder(QAudioFormat::LittleEndian); - else - m_fileFormat.setByteOrder(QAudioFormat::BigEndian); -#elif QT_VERSION_MAJOR == 6 - // Qt6 audio format does not handle little or big endian. - // So it always assumes little endian. - if (memcmp(&header.riff.descriptor.id, "RIFF", 4) != 0){ - std::cout << "Error: wav file uses big endian format but Qt6 audio format does not support it." << std::endl; - result = false; - } -#endif - int bps = qFromLittleEndian(header.wave.bitsPerSample); - m_fileFormat.setChannelCount(qFromLittleEndian(header.wave.numChannels)); - m_fileFormat.setSampleRate(qFromLittleEndian(header.wave.sample_rate)); -#if QT_VERSION_MAJOR == 5 - m_fileFormat.setCodec("audio/pcm"); - m_fileFormat.setSampleSize(qFromLittleEndian(header.wave.bitsPerSample)); - m_fileFormat.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt); -#elif QT_VERSION_MAJOR == 6 - const int bitsPerSample = qFromLittleEndian(header.wave.bitsPerSample); - if (bitsPerSample == 8 && bps == 8){ - m_fileFormat.setSampleFormat(QAudioFormat::SampleFormat::UInt8); - } else if (bitsPerSample == 16 && bps != 8){ - m_fileFormat.setSampleFormat(QAudioFormat::SampleFormat::Int16); - } else if (bitsPerSample == 32 && bps != 8){ - m_fileFormat.setSampleFormat(QAudioFormat::SampleFormat::Int32); - } else { - std::cout << "Error: wav file uses sample type that Qt6 audio format does not support: bits per sample: " << - bitsPerSample << ", " << (bps == 8 ? "unsigned" : "signed") << std::endl; - result = false; - } -#endif - } else { - result = false; - } - } - m_headerLength = pos(); - return result; -} +/* WAV FILE + * + * From: https://github.com/PokemonAutomation/ + * + * Class to read a .wav file. Edited from Qt multimedia example Spectrum: + * https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15 + * The git repo for Qt multimedia code and exmamples is https://code.qt.io/qt/qtmultimedia.git + * The version of the code is Qt5. + * Since the code is licensed by Qt under BSD, we can safely use it with our code base, provided + * that we have the original BSD license below and release the source code. + */ + +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include "WavFile.h" + +#include + +struct chunk +{ + char id[4]; + quint32 size; +}; + +struct RIFFHeader +{ + chunk descriptor; // "RIFF" + char type[4]; // "WAVE" +}; + +struct WAVEHeader +{ + chunk descriptor; + quint16 audioFormat; + quint16 numChannels; + quint32 sample_rate; + quint32 byteRate; + quint16 blockAlign; + quint16 bitsPerSample; +}; + +struct DATAHeader +{ + chunk descriptor; +}; + +struct CombinedHeader +{ + RIFFHeader riff; + WAVEHeader wave; +}; + +WavFile::WavFile(QObject *parent) + : QFile(parent) + , m_headerLength(0) +{ + +} + +bool WavFile::open(const QString &fileName) +{ + close(); + setFileName(fileName); + return QFile::open(QIODevice::ReadOnly) && readHeader(); +} + +const QAudioFormat &WavFile::audioFormat() const +{ + return m_fileFormat; +} + +qint64 WavFile::headerLength() const +{ +return m_headerLength; +} + +bool WavFile::readHeader() +{ + seek(0); + CombinedHeader header; + bool result = read(reinterpret_cast(&header), sizeof(CombinedHeader)) == sizeof(CombinedHeader); + if (result) { + if ((memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0 + || memcmp(&header.riff.descriptor.id, "RIFX", 4) == 0) + && memcmp(&header.riff.type, "WAVE", 4) == 0 + && memcmp(&header.wave.descriptor.id, "fmt ", 4) == 0 + && (header.wave.audioFormat == 1 || header.wave.audioFormat == 0)) { + + // Read off remaining header information + DATAHeader dataHeader; + + if (qFromLittleEndian(header.wave.descriptor.size) > sizeof(WAVEHeader)) { + // Extended data available + quint16 extraFormatBytes; + if (peek((char*)&extraFormatBytes, sizeof(quint16)) != sizeof(quint16)) + return false; + const qint64 throwAwayBytes = sizeof(quint16) + qFromLittleEndian(extraFormatBytes); + if (read(throwAwayBytes).size() != throwAwayBytes) + return false; + } + + if (read((char*)&dataHeader, sizeof(DATAHeader)) != sizeof(DATAHeader)) + return false; + + // Establish format + +#if QT_VERSION_MAJOR == 5 + if (memcmp(&header.riff.descriptor.id, "RIFF", 4) == 0) + m_fileFormat.setByteOrder(QAudioFormat::LittleEndian); + else + m_fileFormat.setByteOrder(QAudioFormat::BigEndian); +#elif QT_VERSION_MAJOR == 6 + // Qt6 audio format does not handle little or big endian. + // So it always assumes little endian. + if (memcmp(&header.riff.descriptor.id, "RIFF", 4) != 0){ + std::cout << "Error: wav file uses big endian format but Qt6 audio format does not support it." << std::endl; + result = false; + } +#endif + int bps = qFromLittleEndian(header.wave.bitsPerSample); + m_fileFormat.setChannelCount(qFromLittleEndian(header.wave.numChannels)); + m_fileFormat.setSampleRate(qFromLittleEndian(header.wave.sample_rate)); +#if QT_VERSION_MAJOR == 5 + m_fileFormat.setCodec("audio/pcm"); + m_fileFormat.setSampleSize(qFromLittleEndian(header.wave.bitsPerSample)); + m_fileFormat.setSampleType(bps == 8 ? QAudioFormat::UnSignedInt : QAudioFormat::SignedInt); +#elif QT_VERSION_MAJOR == 6 + const int bitsPerSample = qFromLittleEndian(header.wave.bitsPerSample); + if (bitsPerSample == 8 && bps == 8){ + m_fileFormat.setSampleFormat(QAudioFormat::SampleFormat::UInt8); + } else if (bitsPerSample == 16 && bps != 8){ + m_fileFormat.setSampleFormat(QAudioFormat::SampleFormat::Int16); + } else if (bitsPerSample == 32 && bps != 8){ + m_fileFormat.setSampleFormat(QAudioFormat::SampleFormat::Int32); + } else { + std::cout << "Error: wav file uses sample type that Qt6 audio format does not support: bits per sample: " << + bitsPerSample << ", " << (bps == 8 ? "unsigned" : "signed") << std::endl; + result = false; + } +#endif + } else { + result = false; + } + } + m_headerLength = pos(); + return result; +} diff --git a/3rdParty/QtWavFile/WavFile.h b/3rdParty/QtWavFile/WavFile.h index 83c284eea8..ef31ed0cde 100644 --- a/3rdParty/QtWavFile/WavFile.h +++ b/3rdParty/QtWavFile/WavFile.h @@ -1,88 +1,88 @@ -/* WAV FILE - * - * From: https://github.com/PokemonAutomation/ - * - * Class to read a .wav file. Edited from Qt multimedia example Spectrum: - * https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15 - * The git repo for Qt multimedia code and exmamples is https://code.qt.io/qt/qtmultimedia.git - * The version of the code is Qt5. - * Since the code is licensed by Qt under BSD, we can safely use it with our code base, provided - * that we have the orignal BSD license below and release the source code. - */ - -/**************************************************************************** -** -** Copyright (C) 2017 The Qt Company Ltd. -** Contact: https://www.qt.io/licensing/ -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:BSD$ -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms -** and conditions see https://www.qt.io/terms-conditions. For further -** information use the contact form at https://www.qt.io/contact-us. -** -** BSD License Usage -** Alternatively, you may use this file under the terms of the BSD license -** as follows: -** -** "Redistribution and use in source and binary forms, with or without -** modification, are permitted provided that the following conditions are -** met: -** * Redistributions of source code must retain the above copyright -** notice, this list of conditions and the following disclaimer. -** * Redistributions in binary form must reproduce the above copyright -** notice, this list of conditions and the following disclaimer in -** the documentation and/or other materials provided with the -** distribution. -** * Neither the name of The Qt Company Ltd nor the names of its -** contributors may be used to endorse or promote products derived -** from this software without specific prior written permission. -** -** -** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." -** -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PokemonAutomation_AudioPipeline_WAVFILE_H -#define PokemonAutomation_AudioPipeline_WAVFILE_H - -#include -#include -#include - -class WavFile : public QFile -{ -public: - WavFile(QObject *parent = 0); - - using QFile::open; - bool open(const QString &fileName); - const QAudioFormat &audioFormat() const; - qint64 headerLength() const; - -private: - bool readHeader(); - -private: - QAudioFormat m_fileFormat; - qint64 m_headerLength; -}; - -#endif // WAVFILE_H +/* WAV FILE + * + * From: https://github.com/PokemonAutomation/ + * + * Class to read a .wav file. Edited from Qt multimedia example Spectrum: + * https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15 + * The git repo for Qt multimedia code and exmamples is https://code.qt.io/qt/qtmultimedia.git + * The version of the code is Qt5. + * Since the code is licensed by Qt under BSD, we can safely use it with our code base, provided + * that we have the orignal BSD license below and release the source code. + */ + +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** BSD License Usage +** Alternatively, you may use this file under the terms of the BSD license +** as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of The Qt Company Ltd nor the names of its +** contributors may be used to endorse or promote products derived +** from this software without specific prior written permission. +** +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PokemonAutomation_AudioPipeline_WAVFILE_H +#define PokemonAutomation_AudioPipeline_WAVFILE_H + +#include +#include +#include + +class WavFile : public QFile +{ +public: + WavFile(QObject *parent = 0); + + using QFile::open; + bool open(const QString &fileName); + const QAudioFormat &audioFormat() const; + qint64 headerLength() const; + +private: + bool readHeader(); + +private: + QAudioFormat m_fileFormat; + qint64 m_headerLength; +}; + +#endif // WAVFILE_H diff --git a/3rdParty/TesseractPA/TesseractPA.cpp b/3rdParty/TesseractPA/TesseractPA.cpp index a6b812092a..575ceb7494 100644 --- a/3rdParty/TesseractPA/TesseractPA.cpp +++ b/3rdParty/TesseractPA/TesseractPA.cpp @@ -1,70 +1,70 @@ -/* Tesseract Wrapper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef UNIX_LINK_TESSERACT - -#include "TesseractPA.h" - -#include -#include -#include -using std::cout; -using std::endl; - - -// We hope to use our own Tesseract build in future for Unix systems too. -// But right now to run on Linux and Mac we need to use external Tesseract library API directly. -// So the Tesseract API wrapper is defined here to match Windows. - - -struct TesseractAPI_internal{ - tesseract::TessBaseAPI m_api; - - TesseractAPI_internal(const char* path, const char* language){ - if (m_api.Init(path, language)){ - throw "Could not initialize TesseractAPI."; - } - } - -}; - - - -TesseractAPI_internal* TesseractAPI_construct(const char* path, const char* language){ - try{ - return new TesseractAPI_internal(path, language); - }catch (const char* err){ - cout << err << endl; - } - return nullptr; -} -void TesseractAPI_destroy(TesseractAPI_internal* api){ - delete api; -} - - - -char* TesseractAPI_read_bitmap( - TesseractAPI_internal* api, - const unsigned char* data, - size_t width, size_t height, - size_t bytes_per_pixel, size_t bytes_per_line, - size_t ppi -){ - api->m_api.SetImage(data, (int)width, (int)height, (int)bytes_per_pixel, (int)bytes_per_line); - api->m_api.SetSourceResolution((int)ppi); - return api->m_api.GetUTF8Text(); -} -void Tesseract_delete(char* text){ - delete[] text; -} - - -#endif // UNIX_LINK_TESSERACT - - - - +/* Tesseract Wrapper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef UNIX_LINK_TESSERACT + +#include "TesseractPA.h" + +#include +#include +#include +using std::cout; +using std::endl; + + +// We hope to use our own Tesseract build in future for Unix systems too. +// But right now to run on Linux and Mac we need to use external Tesseract library API directly. +// So the Tesseract API wrapper is defined here to match Windows. + + +struct TesseractAPI_internal{ + tesseract::TessBaseAPI m_api; + + TesseractAPI_internal(const char* path, const char* language){ + if (m_api.Init(path, language)){ + throw "Could not initialize TesseractAPI."; + } + } + +}; + + + +TesseractAPI_internal* TesseractAPI_construct(const char* path, const char* language){ + try{ + return new TesseractAPI_internal(path, language); + }catch (const char* err){ + cout << err << endl; + } + return nullptr; +} +void TesseractAPI_destroy(TesseractAPI_internal* api){ + delete api; +} + + + +char* TesseractAPI_read_bitmap( + TesseractAPI_internal* api, + const unsigned char* data, + size_t width, size_t height, + size_t bytes_per_pixel, size_t bytes_per_line, + size_t ppi +){ + api->m_api.SetImage(data, (int)width, (int)height, (int)bytes_per_pixel, (int)bytes_per_line); + api->m_api.SetSourceResolution((int)ppi); + return api->m_api.GetUTF8Text(); +} +void Tesseract_delete(char* text){ + delete[] text; +} + + +#endif // UNIX_LINK_TESSERACT + + + + diff --git a/3rdParty/TesseractPA/TesseractPA.h b/3rdParty/TesseractPA/TesseractPA.h index c50507a226..e5661e9c26 100644 --- a/3rdParty/TesseractPA/TesseractPA.h +++ b/3rdParty/TesseractPA/TesseractPA.h @@ -1,176 +1,176 @@ -/* Tesseract Wrapper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_TesseractPA_H -#define PokemonAutomation_TesseractPA_H - -#include -#include - -//#define TESSERACT_STATIC - -#ifdef TESSERACT_STATIC -#define TESSERACT_EXPORT -#else - -#ifdef _WIN32 - -#ifdef _WINDLL -#define TESSERACT_EXPORT __declspec(dllexport) -#else -#define TESSERACT_EXPORT __declspec(dllimport) -#endif - -#else // not on _WIN32 - -#define TESSERACT_EXPORT __attribute__((visibility("default"))) - -#endif // _WIN32 -#endif // TESSERACT_STATIC - - -#ifdef PA_TESSERACT -#elif _MSC_VER -#pragma warning(disable:4100) // Unreferenced Formal Parameter -#elif __GNUC__ -#pragma GCC diagnostic ignored "-Wunused-parameter" -#endif - - - -#ifdef __cplusplus -extern "C" { -#endif - -// We build a custom Tesseract library, -// https://github.com/PokemonAutomation/Tesseract-OCR_for_Windows -// to ship with SerialProgram on Windows, in the form of tesseractPA.dll. -// The following C API is a wrapper for the raw Tesseract API. The wrapper -// along with Tesseract itself is implemented in tesseractPA.dll. -struct TesseractAPI_internal; -TESSERACT_EXPORT TesseractAPI_internal* TesseractAPI_construct( - const char* path, const char* language -); -TESSERACT_EXPORT void TesseractAPI_destroy(TesseractAPI_internal* api); - -//TESSERACT_EXPORT char* TesseractAPI_read_file(TesseractAPI_internal* api, const char* filepath); -TESSERACT_EXPORT char* TesseractAPI_read_bitmap( - TesseractAPI_internal* api, - const unsigned char* data, - size_t width, size_t height, - size_t bytes_per_pixel, size_t bytes_per_line, - size_t ppi -); -TESSERACT_EXPORT void Tesseract_delete(char* text); - - -#ifdef __cplusplus -} -#endif - - -class TesseractString{ -public: - ~TesseractString(){ -#ifdef PA_TESSERACT - if (m_str != nullptr){ - Tesseract_delete(m_str); - } -#endif - } - TesseractString(const TesseractString&) = delete; - void operator=(const TesseractString&) = delete; - TesseractString(TesseractString&& x) - : m_str(x.m_str) - { - x.m_str = nullptr; - } - void operator=(TesseractString&& x){ - m_str = x.m_str; - x.m_str = nullptr; - } - -public: - const char* c_str() const{ - return m_str; - } - -private: - TesseractString(char* str) - : m_str(str) - {} - -private: - friend class TesseractAPI; - char* m_str; -}; - - -class TesseractAPI{ -public: - ~TesseractAPI(){ -#ifdef PA_TESSERACT - if (m_api != nullptr){ - TesseractAPI_destroy(m_api); - } -#endif - } - TesseractAPI(const TesseractAPI&) = delete; - void operator=(const TesseractAPI&) = delete; - TesseractAPI(TesseractAPI&& x) - : m_api(x.m_api) - { - x.m_api = nullptr; - } - void operator=(TesseractAPI&& x){ - m_api = x.m_api; - x.m_api = nullptr; - } - -public: - TesseractAPI(const char* path, const char* language) -#ifdef PA_TESSERACT - : m_api(TesseractAPI_construct(path, language)) -#endif - {} - - bool valid() const{ return m_api != nullptr; } - -// TesseractString read(const char* filepath){ -//#ifdef PA_TESSERACT -// return TesseractAPI_read_file(m_api, filepath); -//#else -// return nullptr; -//#endif -// } - TesseractString read32( - const unsigned char* data, - size_t width, size_t height, - size_t bytes_per_line, size_t ppi = 100 - ){ -#ifdef PA_TESSERACT - return TesseractAPI_read_bitmap( - m_api, - data, - width, height, - sizeof(uint32_t), - bytes_per_line, - ppi - ); -#else - return nullptr; -#endif - } - -private: - TesseractAPI_internal* m_api = nullptr; -}; - - - - -#endif - +/* Tesseract Wrapper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_TesseractPA_H +#define PokemonAutomation_TesseractPA_H + +#include +#include + +//#define TESSERACT_STATIC + +#ifdef TESSERACT_STATIC +#define TESSERACT_EXPORT +#else + +#ifdef _WIN32 + +#ifdef _WINDLL +#define TESSERACT_EXPORT __declspec(dllexport) +#else +#define TESSERACT_EXPORT __declspec(dllimport) +#endif + +#else // not on _WIN32 + +#define TESSERACT_EXPORT __attribute__((visibility("default"))) + +#endif // _WIN32 +#endif // TESSERACT_STATIC + + +#ifdef PA_TESSERACT +#elif _MSC_VER +#pragma warning(disable:4100) // Unreferenced Formal Parameter +#elif __GNUC__ +#pragma GCC diagnostic ignored "-Wunused-parameter" +#endif + + + +#ifdef __cplusplus +extern "C" { +#endif + +// We build a custom Tesseract library, +// https://github.com/PokemonAutomation/Tesseract-OCR_for_Windows +// to ship with SerialProgram on Windows, in the form of tesseractPA.dll. +// The following C API is a wrapper for the raw Tesseract API. The wrapper +// along with Tesseract itself is implemented in tesseractPA.dll. +struct TesseractAPI_internal; +TESSERACT_EXPORT TesseractAPI_internal* TesseractAPI_construct( + const char* path, const char* language +); +TESSERACT_EXPORT void TesseractAPI_destroy(TesseractAPI_internal* api); + +//TESSERACT_EXPORT char* TesseractAPI_read_file(TesseractAPI_internal* api, const char* filepath); +TESSERACT_EXPORT char* TesseractAPI_read_bitmap( + TesseractAPI_internal* api, + const unsigned char* data, + size_t width, size_t height, + size_t bytes_per_pixel, size_t bytes_per_line, + size_t ppi +); +TESSERACT_EXPORT void Tesseract_delete(char* text); + + +#ifdef __cplusplus +} +#endif + + +class TesseractString{ +public: + ~TesseractString(){ +#ifdef PA_TESSERACT + if (m_str != nullptr){ + Tesseract_delete(m_str); + } +#endif + } + TesseractString(const TesseractString&) = delete; + void operator=(const TesseractString&) = delete; + TesseractString(TesseractString&& x) + : m_str(x.m_str) + { + x.m_str = nullptr; + } + void operator=(TesseractString&& x){ + m_str = x.m_str; + x.m_str = nullptr; + } + +public: + const char* c_str() const{ + return m_str; + } + +private: + TesseractString(char* str) + : m_str(str) + {} + +private: + friend class TesseractAPI; + char* m_str; +}; + + +class TesseractAPI{ +public: + ~TesseractAPI(){ +#ifdef PA_TESSERACT + if (m_api != nullptr){ + TesseractAPI_destroy(m_api); + } +#endif + } + TesseractAPI(const TesseractAPI&) = delete; + void operator=(const TesseractAPI&) = delete; + TesseractAPI(TesseractAPI&& x) + : m_api(x.m_api) + { + x.m_api = nullptr; + } + void operator=(TesseractAPI&& x){ + m_api = x.m_api; + x.m_api = nullptr; + } + +public: + TesseractAPI(const char* path, const char* language) +#ifdef PA_TESSERACT + : m_api(TesseractAPI_construct(path, language)) +#endif + {} + + bool valid() const{ return m_api != nullptr; } + +// TesseractString read(const char* filepath){ +//#ifdef PA_TESSERACT +// return TesseractAPI_read_file(m_api, filepath); +//#else +// return nullptr; +//#endif +// } + TesseractString read32( + const unsigned char* data, + size_t width, size_t height, + size_t bytes_per_line, size_t ppi = 100 + ){ +#ifdef PA_TESSERACT + return TesseractAPI_read_bitmap( + m_api, + data, + width, height, + sizeof(uint32_t), + bytes_per_line, + ppi + ); +#else + return nullptr; +#endif + } + +private: + TesseractAPI_internal* m_api = nullptr; +}; + + + + +#endif + diff --git a/3rdParty/dpp/appcommand.h b/3rdParty/dpp/appcommand.h index 0409980e3d..efe11c196c 100644 --- a/3rdParty/dpp/appcommand.h +++ b/3rdParty/dpp/appcommand.h @@ -1,1222 +1,1222 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Discord limits the maximum number of replies to an autocomplete interaction to 25. - * This value represents that maximum. interaction_response::add_autocomplete_choice does not allow - * adding more than this number of elements to the vector. - */ -#ifndef AUTOCOMPLETE_MAX_CHOICES - #define AUTOCOMPLETE_MAX_CHOICES 25 -#endif - -/** - * @brief Represents command option types. - * These are the possible parameter value types. - */ -enum command_option_type : uint8_t { - /** A sub-command */ - co_sub_command = 1, - /** A sub-command group */ - co_sub_command_group = 2, - /** A string value */ - co_string = 3, - /** An integer value */ - co_integer = 4, - /** A boolean value */ - co_boolean = 5, - /** A user snowflake id */ - co_user = 6, - /** A channel snowflake id. Includes all channel types and categories */ - co_channel = 7, - /** A role snowflake id */ - co_role = 8, - /** A mentionable. Includes users and roles */ - co_mentionable = 9, - /** Any double between -2^53 and 2^53 */ - co_number = 10, - /** File attachment type */ - co_attachment = 11, -}; - -/** - * @brief This type is a variant that can hold any of the potential - * native data types represented by the enum dpp::command_option_type. - * It is used in interactions. - * - * std::monostate indicates an invalid parameter value, e.g. an unfilled optional parameter. - * std::int64_t will be for all integer options, double for decimal numbers and dpp::snowflake for anything ID related. - * - * You can retrieve them with std::get(). - */ -typedef std::variant command_value; - -/** - * @brief This struct represents choices in a multiple choice option - * for a command parameter. - * It has both a string name, and a value parameter which is a variant, - * meaning it can hold different potential types (see dpp::command_value) - * that you can retrieve with std::get(). - */ -struct DPP_EXPORT command_option_choice : public json_interface { - std::string name; //!< Option name (1-32 chars) - command_value value; //!< Option value - std::map name_localizations; //!< Localisations of command option name - - /** - * @brief Construct a new command option choice object - */ - command_option_choice() = default; - - virtual ~command_option_choice() = default; - - /** - * @brief Add a localisation for this command option choice - * @see https://discord.com/developers/docs/reference#locales - * @param language Name of language, see the list of locales linked to above. - * @param _name name of command option choice in the specified language - * @return command_option_choice& reference to self for fluent chaining - */ - command_option_choice& add_localization(const std::string& language, const std::string& _name); - - /** - * @brief Construct a new command option choice object - * - * @param n name to initialise with - * @param v value to initialise with - */ - command_option_choice(const std::string &n, command_value v); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return command_option_choice& Reference to self - */ - command_option_choice& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief helper function to serialize a command_option_choice to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param choice command_option_choice to be serialized - */ -void to_json(nlohmann::json& j, const command_option_choice& choice); - -/** - * @brief A minimum or maximum value for co_number and co_integer dpp::command_option types - */ -typedef std::variant command_option_range; - -/** - * @brief Each command option is a command line parameter. - * It can have a type (see dpp::command_option_type), a name, - * a description, can be required or optional, and can have - * zero or more choices (for multiple choice), plus options. - * Adding options acts like sub-commands and can contain more - * options. - */ -struct DPP_EXPORT command_option : public json_interface { - command_option_type type; //!< Option type (what type of value is accepted) - std::string name; //!< Option name (1-32 chars) - std::string description; //!< Option description (1-100 chars) - bool required; //!< True if this is a mandatory parameter - bool focused; //!< True if the user is typing in this field, when sent via autocomplete - command_value value; //!< Set only by autocomplete went sent as part of an interaction - std::vector choices; //!< List of choices for multiple choice command - bool autocomplete; //!< True if this option supports auto completion - std::vector options; //!< Sub-commands - std::vector channel_types; //!< Allowed channel types for channel snowflake id options - command_option_range min_value; //!< Minimum value allowed, for co_number and co_integer types only - command_option_range max_value; //!< Maximum value allowed, for co_number and co_integer types only - std::map name_localizations; //!< Localisations of command name - std::map description_localizations; //!< Localisations of command description - - - /** - * @brief Construct a new command option object - */ - command_option() = default; - - /** - * @brief Destroy the command option object - */ - virtual ~command_option() = default; - - /** - * @brief Add a localisation for this slash command option - * @see https://discord.com/developers/docs/reference#locales - * @param language Name of language, see the list of locales linked to above. - * @param _name name of slash command option in the specified language - * @param _description description of slash command option in the specified language - * @return command_option& reference to self for fluent chaining - */ - command_option& add_localization(const std::string& language, const std::string& _name, const std::string& _description); - - /** - * @brief Construct a new command option object - * - * @param t Option type - * @param name Option name - * @param description Option description - * @param required True if this is a mandatory parameter - */ - command_option(command_option_type t, const std::string &name, const std::string &description, bool required = false); - - /** - * @brief Add a multiple choice option - * - * @param o choice to add - * @return command_option& returns a reference to self for chaining of calls - * @throw dpp::exception command_option is an autocomplete, so choices cannot be added - */ - command_option& add_choice(const command_option_choice &o); - - /** - * @brief Set the minimum numeric value of the option. - * Only valid if the type is co_number or co_integer. - * @param min_v Minimum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_min_value(command_option_range min_v); - - /** - * @brief Set the maximum numeric value of the option. - * Only valid if the type is co_number or co_integer. - * @param max_v Maximum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_max_value(command_option_range max_v); - - /** - * @brief Set the minimum string length of the option. - * Only valid if the type is co_string - * @param min_v Minimum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_min_length(command_option_range min_v); - - /** - * @brief Set the maximum string length of the option. - * Only valid if the type is co_string - * @param max_v Maximum value - * @return command_option& return a reference to sef for chaining of calls - */ - command_option& set_max_length(command_option_range max_v); - - /** - * @brief Add a sub-command option - * - * @param o Sub-command option to add - * @return command_option& return a reference to self for chaining of calls - */ - command_option& add_option(const command_option &o); - - /** - * @brief Add channel type for option (only for co_channel type options) - * - * @param ch type to set - * @return command_option& return a reference to self for chaining of calls - */ - command_option& add_channel_type(const channel_type ch); - - /** - * @brief Set the auto complete state - * - * @param autocomp True to enable auto completion for this option - * @return command_option& return a reference to self for chaining of calls - * @throw dpp::exception You attempted to enable auto complete on a command_option that has choices added to it - */ - command_option& set_auto_complete(bool autocomp); - - /** - * @brief Fill object properties from JSON. Fills options recursively. - * - * @param j JSON to fill from - * @return command_option& Reference to self - */ - command_option& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief helper function to serialize a command_option to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param opt command_option to be serialized - */ -void to_json(nlohmann::json& j, const command_option& opt); - -/** - * @brief Response types when responding to an interaction within on_interaction_create. - */ -enum interaction_response_type { - ir_pong = 1, //!< Acknowledge a Ping - ir_channel_message_with_source = 4, //!< respond to an interaction with a message - ir_deferred_channel_message_with_source = 5, //!< Acknowledge an interaction and edit a response later, the user sees a loading state - ir_deferred_update_message = 6, //!< for components, acknowledge an interaction and edit the original message later; the user does not see a loading state - ir_update_message = 7, //!< for components, edit the message the component was attached to - ir_autocomplete_reply = 8, //!< Reply to autocomplete interaction. Be sure to do this within 500ms of the interaction! - ir_modal_dialog = 9, //!< A modal dialog box -}; - -/** - * @brief A response to an interaction, used to reply to a command and initiate - * a message, which can be hidden from others (ephemeral) or visible to all. - * - * The dpp::interaction_response object wraps a dpp::message object. To set the - * message as 'ephemeral' (e.g. only the command issuer can see it) you should - * add the dpp::m_ephemeral flag to the dpp::message::flags field. e.g.: - * - * `mymessage.flags |= dpp::m_ephemeral;` - */ -struct DPP_EXPORT interaction_response : public json_interface { - - /** - * @brief Response type from dpp::interaction_response_type. - * Should be one of ir_pong, ir_channel_message_with_source, - * or ir_deferred_channel_message_with_source. - */ - interaction_response_type type; - - /** - * @brief A message object. This pointer is always valid - * while the containing interaction_response exists. - */ - struct message* msg; - - /** - * @brief Array of up to 25 autocomplete choices - */ - std::vector autocomplete_choices; - - /** - * @brief Construct a new interaction response object - */ - interaction_response(); - - /** - * @brief Construct a new interaction response object - * - * @param t Type of reply - * @param m Message to reply with - */ - interaction_response(interaction_response_type t, const struct message& m); - - /** - * @brief Construct a new interaction response object - * - * @param t Type of reply - */ - interaction_response(interaction_response_type t); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return interaction_response& Reference to self - */ - interaction_response& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Add a command option choice - * - * @param achoice command option choice to add - * @return interaction_response& Reference to self - */ - interaction_response& add_autocomplete_choice(const command_option_choice& achoice); - - /** - * @brief Destroy the interaction response object - */ - virtual ~interaction_response(); - -}; - -/** - * @brief Represents a modal dialog box response to an interaction. - * - * A dialog box is a modal popup which appears to the user instead of a message. One or more - * components are displayed on a form (the same component structure as within a dpp::message). - * When the user submits the form an on_form_submit event is dispatched to any listeners. - */ -struct DPP_EXPORT interaction_modal_response : public interaction_response, public json_interface { -private: - size_t current_row; -public: - /** - * @brief Custom ID for the modal form - */ - std::string custom_id; - - /** - * @brief Title of the modal form box - */ - std::string title; - - /** - * @brief List of components. All components must be placed within - * an action row, each outer vector is the action row. - */ - std::vector> components; - - /** - * @brief Construct a new interaction modal response object - */ - interaction_modal_response(); - - /** - * @brief Construct a new interaction modal response object - * - * @param _custom_id Custom ID of the modal form - * @param _title Title of the modal form. It will be truncated to the maximum length of 45 UTF-8 characters. - * @param _components Components to add to the modal form - */ - interaction_modal_response(const std::string& _custom_id, const std::string& _title, const std::vector _components = {}); - - /** - * @brief Set the custom id - * - * @param _custom_id custom id to set - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& set_custom_id(const std::string& _custom_id); - - /** - * @brief Set the title - * - * @param _title title to set - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& set_title(const std::string& _title); - - /** - * @brief Add a component to an interaction modal response - * - * @param c component to add - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& add_component(const component& c); - - /** - * @brief Add a new row to the interaction modal response. - * @note A modal response can have a maximum of five rows. - * @throw dpp::logic_exception if more than five rows are attempted to be added - * @return interaction_modal_response& Reference to self - */ - interaction_modal_response& add_row(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return interaction_response& Reference to self - */ - interaction_modal_response& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * @param with_id include id in json output - * - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Destroy the interaction modal response object - */ - virtual ~interaction_modal_response() = default; -}; - -/** - * @brief Resolved snowflake ids to users, guild members, roles and channels. - */ -struct DPP_EXPORT command_resolved { - /** - * @brief Resolved users - */ - std::map users; - /** - * @brief Resolved guild members - */ - std::map members; - /** - * @brief Resolved total guild member permissions in the channel, including overwrites - */ - std::map member_permissions; - /** - * @brief Resolved roles - */ - std::map roles; - /** - * @brief Resolved channels - */ - std::map channels; - /** - * @brief Resolved messages - */ - std::map messages; - /** - * @brief Resolved attachments - */ - std::map attachments; -}; - -/** - * @brief Values in the command interaction. - * These are the values specified by the user when actually issuing - * the command on a channel or in DM. - */ -struct DPP_EXPORT command_data_option { - std::string name; //!< the name of the parameter - command_option_type type; //!< value of ApplicationCommandOptionType - command_value value; //!< Optional: the value of the pair - std::vector options; //!< Optional: present if this option is a group or subcommand - bool focused; //!< Optional: true if this option is the currently focused option for autocomplete - - /** - * @brief Check if the value variant holds std::monostate and options vector is empty (i.e. the option wasn't supplied) - * @return bool true, if value variant holds std::monostate and options vector is empty - */ - bool empty() { - return std::holds_alternative(value) && options.empty(); - } - - /** - * @brief Get an option value by index - * - * @tparam Type to get from the parameter - * @param index index number of parameter - * @return T returned type - */ - template T& get_value(size_t index) { - return std::get(options.at(index).value); - } -}; - -/** - * @brief helper function to deserialize a command_data_option from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param cdo command_data_option to be deserialized - */ -void from_json(const nlohmann::json& j, command_data_option& cdo); - -/** Types of interaction in the dpp::interaction class - */ -enum interaction_type { - it_ping = 1, //!< ping - it_application_command = 2, //!< application command (slash command) - it_component_button = 3, //!< button click or select menu chosen (component interaction) - it_autocomplete = 4, //!< Autocomplete interaction - it_modal_submit = 5, //!< Modal form submission -}; - -/** - * @brief Right-click context menu types - */ -enum slashcommand_contextmenu_type { - ctxm_none = 0, //!< Undefined context menu type - ctxm_chat_input = 1, //!< DEFAULT, these are the slash commands you're used to - ctxm_user = 2, //!< Add command to user context menu - ctxm_message = 3 //!< Add command to message context menu -}; - -/** - * @brief Details of a command within an interaction. - * This subobject represents the application command associated - * with the interaction. - */ -struct DPP_EXPORT command_interaction { - snowflake id; //!< the ID of the invoked command - std::string name; //!< the name of the invoked command - std::vector options; //!< Optional: the params + values from the user - slashcommand_contextmenu_type type; //!< type of the command interaction - dpp::snowflake target_id; //!< Non-zero target ID for context menu actions. e.g. user id or message id whom clicked or tapped with the context menu https://discord.com/developers/docs/interactions/application-commands#user-commands - - /** - * @brief Get an option value by index - * - * @tparam Type to get from the parameter - * @param index index number of parameter - * @return T returned type - */ - template T& get_value(size_t index) { - return std::get(options.at(index).value); - } - - /** - * @brief Return a ping/mention for the slash command - * - * @return std::string mention. e.g. `` - * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention - */ - std::string get_mention() const; -}; - -/** - * @brief helper function to deserialize a command_interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param ci command_interaction to be deserialized - */ -void from_json(const nlohmann::json& j, command_interaction& ci); - -/** - * @brief A button click for a button component - */ -struct DPP_EXPORT component_interaction { - /** - * @brief Component type (dpp::component_type) - */ - uint8_t component_type; - /** - * @brief Custom ID set when created - */ - std::string custom_id; - /** - * @brief Possible values for a drop down list - */ - std::vector values; -}; - -/** - * @brief An auto complete interaction - */ -struct DPP_EXPORT autocomplete_interaction : public command_interaction { -}; - -/** - * @brief helper function to deserialize a component_interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param bi button_interaction to be deserialized - */ -void from_json(const nlohmann::json& j, component_interaction& bi); - -/** - * @brief helper function to deserialize an autocomplete_interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param ai autocomplete_interaction to be deserialized - */ -void from_json(const nlohmann::json& j, autocomplete_interaction& ai); - -/** - * @brief An interaction represents a user running a command and arrives - * via the dpp::cluster::on_interaction_create event. This is further split - * into the events on_form_submit, on_slashcommand, on_user_context_menu, - * on_button_click, on_select_menu, etc. - */ -class DPP_EXPORT interaction : public managed, public json_interface { - - /** - * @brief Get a resolved object from the resolved set - * - * @tparam T type of object to retrieve - * @tparam C container defintion for resolved container - * @param id Snowflake ID - * @param resolved_set container for the type - * @return const T& retrieved type - * @throws dpp::logic_exception on object not found in resolved set - */ - template const T& get_resolved(snowflake id, const C& resolved_set) const { - auto i = resolved_set.find(id); - if (i == resolved_set.end()) { - throw dpp::logic_exception("ID not found in resolved properties of application command"); - } - return i->second; - } - -public: - snowflake application_id; //!< id of the application this interaction is for - uint8_t type; //!< the type of interaction (dpp::interaction_type) - std::variant data; //!< Optional: the command data payload - snowflake guild_id; //!< Optional: the guild it was sent from - snowflake channel_id; //!< Optional: the channel it was sent from - snowflake message_id; //!< Originating message id for context menu actions - permission app_permissions; //!< Permissions of the bot in the channel/guild where this command was issued - message msg; //!< Originating message for context menu actions - guild_member member; //!< Optional: guild member data for the invoking user, including permissions - user usr; //!< User object for the invoking user - std::string token; //!< a continuation token for responding to the interaction - uint8_t version; //!< read-only property, always 1 - command_resolved resolved; //!< Resolved user/role etc - std::string locale; //!< User's locale (language) - std::string guild_locale; //!< Guild's locale (language) - for guild interactions only - cache_policy_t cache_policy; //!< Cache policy from cluster - - /** - * @brief Construct a new interaction object - */ - interaction(); - - /** - * @brief Destroy the interaction object - */ - virtual ~interaction() = default; - - /** - * @brief Get a user associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id User snowflake ID to find - * @return const dpp::user& user - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::user& get_resolved_user(snowflake id) const; - - /** - * @brief Get the channel this command originated on - * - * @return const dpp::channel& channel - * @throws dpp::logic_exception Command originated from a DM or channel not in cache - */ - const dpp::channel& get_channel() const; - - /** - * @brief Get the guild this command originated on - * - * @return const dpp::guild& guild - * @throws dpp::logic_exception Command originated from a DM or guild not in cache - */ - const dpp::guild& get_guild() const; - - /** - * @brief Get the user who issued this command - * - * @return const dpp::user& user - */ - const dpp::user& get_issuing_user() const; - - /** - * @brief Get the message this action refers to if it is a context menu command - * - * @return const dpp::message& context menu message - */ - const dpp::message& get_context_message() const; - - /** - * @brief Get a role associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Role snowflake ID to find - * @return const dpp::role& role - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::role& get_resolved_role(snowflake id) const; - - /** - * @brief Get a channel associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Channel snowflake ID to find - * @return const dpp::channel& channel - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::channel& get_resolved_channel(snowflake id) const; - - /** - * @brief Get a guild member associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id User snowflake ID to find - * @return const dpp::guild_member& guild member - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::guild_member& get_resolved_member(snowflake id) const; - - /** - * @brief Get a permission associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id User snowflake ID to find - * @return const dpp::permission& permissions for the user including overrides on - * the channel where the command was issued. - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::permission& get_resolved_permission(snowflake id) const; - - /** - * @brief Get a message associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Message snowflake ID to find - * @return const dpp::message& message - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::message& get_resolved_message(snowflake id) const; - - /** - * @brief Get an uploaded attachment associated with the slash command from the resolved list. - * The resolved list contains associated structures for this command and does not - * use the cache or require any extra API calls. - * - * @param id Attachment snowflake ID to find - * @return const dpp::attachment& file attachment - * @throws dpp::logic_exception on object not found in resolved set - */ - const dpp::attachment& get_resolved_attachment(snowflake id) const; - - /** - * @brief Get the command interaction object - * - * @throw dpp::logic_exception if the interaction is not for a command - * - * @return command_interaction object - */ - command_interaction get_command_interaction() const; - - /** - * @brief Get the component interaction object - * - * @throw dpp::logic_exception if the interaction is not for a component - * - * @return component_interaction object - */ - component_interaction get_component_interaction() const; - - /** - * @brief Get the autocomplete interaction object - * - * @throw dpp::logic_exception if the interaction is not for an autocomplete - * - * @return autocomplete_interaction object - */ - autocomplete_interaction get_autocomplete_interaction() const; - - /** - * @brief Get the command name for a command interaction - * - * @return std::string command interaction, or empty string if the interaction - * is not for a command. - */ - std::string get_command_name() const; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return interaction& Reference to self - */ - interaction& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @param with_id True if to include the ID in the JSON - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; -}; - -/** - * @brief helper function to deserialize an interaction from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param i interaction to be deserialized - */ -void from_json(const nlohmann::json& j, interaction& i); - -/** - * @brief type of permission in the dpp::command_permission class - */ -enum command_permission_type { - /** - * @brief Role permission - * - */ - cpt_role = 1, - /** - * @brief User permission - * - */ - cpt_user = 2, -}; - -/** - * @brief Application command permissions allow you to enable or - * disable commands for specific users or roles within a guild - */ -class DPP_EXPORT command_permission : public json_interface { -public: - snowflake id; //!< the ID of the role or user - command_permission_type type; //!< the type of permission - bool permission; //!< true to allow, false, to disallow - - /** - * @brief Construct a new command permission object - */ - command_permission() = default; - - virtual ~command_permission() = default; - - /** - * @brief Construct a new command permission object - * - * @param id The ID of the role or user - * @param t The permission type - * @param permission True to allow, false, to disallow - */ - command_permission(snowflake id, const command_permission_type t, bool permission); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return command_permission& Reference to self - */ - command_permission &fill_from_json(nlohmann::json *j); -}; - -/** - * @brief helper function to serialize a command_permission to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param cp command_permission to be serialized - */ -void to_json(nlohmann::json& j, const command_permission& cp); - -/** - * @brief Returned when fetching the permissions for a command in a guild. - */ -class DPP_EXPORT guild_command_permissions : public json_interface { -public: - snowflake id; //!< the id of the command - snowflake application_id; //!< the id of the application the command belongs to - snowflake guild_id; //!< the id of the guild - std::vector permissions; //!< the permissions for the command in the guild - - /** - * @brief Construct a new guild command permissions object - */ - guild_command_permissions(); - - virtual ~guild_command_permissions() = default; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return guild_command_permissions& Reference to self - */ - guild_command_permissions &fill_from_json(nlohmann::json *j); - -}; - -/** - * @brief helper function to serialize a guild_command_permissions to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param gcp guild_command_permissions to be serialized - */ -void to_json(nlohmann::json& j, const guild_command_permissions& gcp); - -/** - * @brief Represents an application command, created by your bot - * either globally, or on a guild. - */ -class DPP_EXPORT slashcommand : public managed, public json_interface { -public: - /** - * @brief Application id (usually matches your bots id) - */ - snowflake application_id; - - /** - * @brief Context menu type, defaults to dpp::ctxm_chat_input - */ - slashcommand_contextmenu_type type; - - /** - * @brief Command name (1-32 chars) - */ - std::string name; - - /** - * @brief Command description (1-100 chars) - */ - std::string description; - - /** - * @brief Command options (parameters) - */ - std::vector options; - - /** - * @brief Whether the command is enabled by default when the app is added to a guild. - * This has no effect as the default_member_permissions value is used instead. - * @deprecated Discord discourage use of this value and instead you should use slashcommand::default_member_permissions. - */ - bool default_permission; - - /** - * @brief command permissions - * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. - */ - std::vector permissions; - - /** - * @brief autoincrementing version identifier updated during substantial record changes - */ - snowflake version; - - /** - * @brief Localisations of command name - */ - std::map name_localizations; - - /** - * @brief Localisations of command description - */ - std::map description_localizations; - - /** - * @brief The default permissions of this command on a guild. - * D++ defaults this to dpp::p_use_application_commands. - * @note You can set it to 0 to disable the command for everyone except admins by default - */ - permission default_member_permissions; - - /** - * @brief True if this command should be allowed in a DM - * D++ defaults this to false. Cannot be set to true in a guild - * command, only a global command. - */ - bool dm_permission; - - /** - * @brief Indicates whether the command is [age-restricted](https://discord.com/developers/docs/interactions/application-commands#agerestricted-commands). - * Defaults to false - */ - bool nsfw; - - /** - * @brief Construct a new slashcommand object - */ - slashcommand(); - - /** - * @brief Construct a new slashcommand object - * - * @param _name Command name - * @param _description Command description - * @param _application_id Application id (usually the bot's user id) - */ - slashcommand(const std::string &_name, const std::string &_description, const dpp::snowflake _application_id); - - /** - * @brief Destroy the slashcommand object - */ - virtual ~slashcommand(); - - /** - * @brief Add a localisation for this slash command - * @see https://discord.com/developers/docs/reference#locales - * @param language Name of language, see the list of locales linked to above. - * @param _name name of slash command in the specified language - * @param _description description of slash command in the specified language - * @return slashcommand& reference to self for fluent chaining - */ - slashcommand& add_localization(const std::string& language, const std::string& _name, const std::string& _description); - - /** - * @brief Set the dm permission for the command - * - * @param dm true to allow this command in dms - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_dm_permission(bool dm); - - /** - * @brief Set whether the command should be age-restricted or not - * - * @param is_nsfw true if the command should be age-restricted - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_nsfw(bool is_nsfw); - - /** - * @brief Set the default permissions of the slash command - * - * @param defaults default permissions to set. This is a permission bitmask of bits from dpp::permissions - * @note You can set it to 0 to disable the command for everyone except admins by default - * - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_default_permissions(uint64_t defaults); - - /** - * @brief Add an option (parameter) - * - * @param o option (parameter) to add - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& add_option(const command_option &o); - - /** - * @brief Set the type of the slash command (only for context menu entries) - * - * @param _type Type of context menu entry this command represents - * @note If the type is dpp::ctxm_chat_input, the command name will be set to lowercase. - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_type(slashcommand_contextmenu_type _type); - - /** - * @brief Set the name of the command - * - * @param n name of command - * @note The maximum length of a command name is 32 UTF-8 codepoints. - * If your command name is longer than this, it will be truncated. - * The command name will be set to lowercase when the type is the default dpp::ctxm_chat_input. - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_name(const std::string &n); - - /** - * @brief Set the description of the command - * - * @param d description - * @note The maximum length of a command description is 100 UTF-8 codepoints. - * If your command description is longer than this, it will be truncated. - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_description(const std::string &d); - - /** - * @brief Set the application id of the command - * - * @param i application id - * @return slashcommand& reference to self for chaining of calls - */ - slashcommand& set_application_id(snowflake i); - - /** - * @brief Adds a permission to the command - * - * @param p permission to add - * @return slashcommand& reference to self for chaining of calls - * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. - */ - slashcommand& add_permission(const command_permission& p); - - /** - * @brief Disable default permissions, command will be unusable unless - * permissions are overridden with add_permission and - * dpp::guild_command_edit_permissions - * - * @return slashcommand& reference to self for chaining of calls - * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. - */ - slashcommand& disable_default_permissions(); - - /** - * @brief Return a ping/mention for the slash command - * - * @return std::string mention. e.g. `` - * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention - */ - std::string get_mention() const; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return slashcommand& Reference to self - */ - slashcommand& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @param with_id True if to include the ID in the JSON - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; -}; - -/** - * @brief helper function to serialize a slashcommand to json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param cmd slashcommand to be serialized - */ -void to_json(nlohmann::json& j, const slashcommand& cmd); - -/** - * @brief A group of application slash commands - */ -typedef std::unordered_map slashcommand_map; - -/** - * @brief A group of guild command permissions - */ -typedef std::unordered_map guild_command_permissions_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Discord limits the maximum number of replies to an autocomplete interaction to 25. + * This value represents that maximum. interaction_response::add_autocomplete_choice does not allow + * adding more than this number of elements to the vector. + */ +#ifndef AUTOCOMPLETE_MAX_CHOICES + #define AUTOCOMPLETE_MAX_CHOICES 25 +#endif + +/** + * @brief Represents command option types. + * These are the possible parameter value types. + */ +enum command_option_type : uint8_t { + /** A sub-command */ + co_sub_command = 1, + /** A sub-command group */ + co_sub_command_group = 2, + /** A string value */ + co_string = 3, + /** An integer value */ + co_integer = 4, + /** A boolean value */ + co_boolean = 5, + /** A user snowflake id */ + co_user = 6, + /** A channel snowflake id. Includes all channel types and categories */ + co_channel = 7, + /** A role snowflake id */ + co_role = 8, + /** A mentionable. Includes users and roles */ + co_mentionable = 9, + /** Any double between -2^53 and 2^53 */ + co_number = 10, + /** File attachment type */ + co_attachment = 11, +}; + +/** + * @brief This type is a variant that can hold any of the potential + * native data types represented by the enum dpp::command_option_type. + * It is used in interactions. + * + * std::monostate indicates an invalid parameter value, e.g. an unfilled optional parameter. + * std::int64_t will be for all integer options, double for decimal numbers and dpp::snowflake for anything ID related. + * + * You can retrieve them with std::get(). + */ +typedef std::variant command_value; + +/** + * @brief This struct represents choices in a multiple choice option + * for a command parameter. + * It has both a string name, and a value parameter which is a variant, + * meaning it can hold different potential types (see dpp::command_value) + * that you can retrieve with std::get(). + */ +struct DPP_EXPORT command_option_choice : public json_interface { + std::string name; //!< Option name (1-32 chars) + command_value value; //!< Option value + std::map name_localizations; //!< Localisations of command option name + + /** + * @brief Construct a new command option choice object + */ + command_option_choice() = default; + + virtual ~command_option_choice() = default; + + /** + * @brief Add a localisation for this command option choice + * @see https://discord.com/developers/docs/reference#locales + * @param language Name of language, see the list of locales linked to above. + * @param _name name of command option choice in the specified language + * @return command_option_choice& reference to self for fluent chaining + */ + command_option_choice& add_localization(const std::string& language, const std::string& _name); + + /** + * @brief Construct a new command option choice object + * + * @param n name to initialise with + * @param v value to initialise with + */ + command_option_choice(const std::string &n, command_value v); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return command_option_choice& Reference to self + */ + command_option_choice& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief helper function to serialize a command_option_choice to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param choice command_option_choice to be serialized + */ +void to_json(nlohmann::json& j, const command_option_choice& choice); + +/** + * @brief A minimum or maximum value for co_number and co_integer dpp::command_option types + */ +typedef std::variant command_option_range; + +/** + * @brief Each command option is a command line parameter. + * It can have a type (see dpp::command_option_type), a name, + * a description, can be required or optional, and can have + * zero or more choices (for multiple choice), plus options. + * Adding options acts like sub-commands and can contain more + * options. + */ +struct DPP_EXPORT command_option : public json_interface { + command_option_type type; //!< Option type (what type of value is accepted) + std::string name; //!< Option name (1-32 chars) + std::string description; //!< Option description (1-100 chars) + bool required; //!< True if this is a mandatory parameter + bool focused; //!< True if the user is typing in this field, when sent via autocomplete + command_value value; //!< Set only by autocomplete went sent as part of an interaction + std::vector choices; //!< List of choices for multiple choice command + bool autocomplete; //!< True if this option supports auto completion + std::vector options; //!< Sub-commands + std::vector channel_types; //!< Allowed channel types for channel snowflake id options + command_option_range min_value; //!< Minimum value allowed, for co_number and co_integer types only + command_option_range max_value; //!< Maximum value allowed, for co_number and co_integer types only + std::map name_localizations; //!< Localisations of command name + std::map description_localizations; //!< Localisations of command description + + + /** + * @brief Construct a new command option object + */ + command_option() = default; + + /** + * @brief Destroy the command option object + */ + virtual ~command_option() = default; + + /** + * @brief Add a localisation for this slash command option + * @see https://discord.com/developers/docs/reference#locales + * @param language Name of language, see the list of locales linked to above. + * @param _name name of slash command option in the specified language + * @param _description description of slash command option in the specified language + * @return command_option& reference to self for fluent chaining + */ + command_option& add_localization(const std::string& language, const std::string& _name, const std::string& _description); + + /** + * @brief Construct a new command option object + * + * @param t Option type + * @param name Option name + * @param description Option description + * @param required True if this is a mandatory parameter + */ + command_option(command_option_type t, const std::string &name, const std::string &description, bool required = false); + + /** + * @brief Add a multiple choice option + * + * @param o choice to add + * @return command_option& returns a reference to self for chaining of calls + * @throw dpp::exception command_option is an autocomplete, so choices cannot be added + */ + command_option& add_choice(const command_option_choice &o); + + /** + * @brief Set the minimum numeric value of the option. + * Only valid if the type is co_number or co_integer. + * @param min_v Minimum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_min_value(command_option_range min_v); + + /** + * @brief Set the maximum numeric value of the option. + * Only valid if the type is co_number or co_integer. + * @param max_v Maximum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_max_value(command_option_range max_v); + + /** + * @brief Set the minimum string length of the option. + * Only valid if the type is co_string + * @param min_v Minimum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_min_length(command_option_range min_v); + + /** + * @brief Set the maximum string length of the option. + * Only valid if the type is co_string + * @param max_v Maximum value + * @return command_option& return a reference to sef for chaining of calls + */ + command_option& set_max_length(command_option_range max_v); + + /** + * @brief Add a sub-command option + * + * @param o Sub-command option to add + * @return command_option& return a reference to self for chaining of calls + */ + command_option& add_option(const command_option &o); + + /** + * @brief Add channel type for option (only for co_channel type options) + * + * @param ch type to set + * @return command_option& return a reference to self for chaining of calls + */ + command_option& add_channel_type(const channel_type ch); + + /** + * @brief Set the auto complete state + * + * @param autocomp True to enable auto completion for this option + * @return command_option& return a reference to self for chaining of calls + * @throw dpp::exception You attempted to enable auto complete on a command_option that has choices added to it + */ + command_option& set_auto_complete(bool autocomp); + + /** + * @brief Fill object properties from JSON. Fills options recursively. + * + * @param j JSON to fill from + * @return command_option& Reference to self + */ + command_option& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief helper function to serialize a command_option to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param opt command_option to be serialized + */ +void to_json(nlohmann::json& j, const command_option& opt); + +/** + * @brief Response types when responding to an interaction within on_interaction_create. + */ +enum interaction_response_type { + ir_pong = 1, //!< Acknowledge a Ping + ir_channel_message_with_source = 4, //!< respond to an interaction with a message + ir_deferred_channel_message_with_source = 5, //!< Acknowledge an interaction and edit a response later, the user sees a loading state + ir_deferred_update_message = 6, //!< for components, acknowledge an interaction and edit the original message later; the user does not see a loading state + ir_update_message = 7, //!< for components, edit the message the component was attached to + ir_autocomplete_reply = 8, //!< Reply to autocomplete interaction. Be sure to do this within 500ms of the interaction! + ir_modal_dialog = 9, //!< A modal dialog box +}; + +/** + * @brief A response to an interaction, used to reply to a command and initiate + * a message, which can be hidden from others (ephemeral) or visible to all. + * + * The dpp::interaction_response object wraps a dpp::message object. To set the + * message as 'ephemeral' (e.g. only the command issuer can see it) you should + * add the dpp::m_ephemeral flag to the dpp::message::flags field. e.g.: + * + * `mymessage.flags |= dpp::m_ephemeral;` + */ +struct DPP_EXPORT interaction_response : public json_interface { + + /** + * @brief Response type from dpp::interaction_response_type. + * Should be one of ir_pong, ir_channel_message_with_source, + * or ir_deferred_channel_message_with_source. + */ + interaction_response_type type; + + /** + * @brief A message object. This pointer is always valid + * while the containing interaction_response exists. + */ + struct message* msg; + + /** + * @brief Array of up to 25 autocomplete choices + */ + std::vector autocomplete_choices; + + /** + * @brief Construct a new interaction response object + */ + interaction_response(); + + /** + * @brief Construct a new interaction response object + * + * @param t Type of reply + * @param m Message to reply with + */ + interaction_response(interaction_response_type t, const struct message& m); + + /** + * @brief Construct a new interaction response object + * + * @param t Type of reply + */ + interaction_response(interaction_response_type t); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction_response& Reference to self + */ + interaction_response& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Add a command option choice + * + * @param achoice command option choice to add + * @return interaction_response& Reference to self + */ + interaction_response& add_autocomplete_choice(const command_option_choice& achoice); + + /** + * @brief Destroy the interaction response object + */ + virtual ~interaction_response(); + +}; + +/** + * @brief Represents a modal dialog box response to an interaction. + * + * A dialog box is a modal popup which appears to the user instead of a message. One or more + * components are displayed on a form (the same component structure as within a dpp::message). + * When the user submits the form an on_form_submit event is dispatched to any listeners. + */ +struct DPP_EXPORT interaction_modal_response : public interaction_response, public json_interface { +private: + size_t current_row; +public: + /** + * @brief Custom ID for the modal form + */ + std::string custom_id; + + /** + * @brief Title of the modal form box + */ + std::string title; + + /** + * @brief List of components. All components must be placed within + * an action row, each outer vector is the action row. + */ + std::vector> components; + + /** + * @brief Construct a new interaction modal response object + */ + interaction_modal_response(); + + /** + * @brief Construct a new interaction modal response object + * + * @param _custom_id Custom ID of the modal form + * @param _title Title of the modal form. It will be truncated to the maximum length of 45 UTF-8 characters. + * @param _components Components to add to the modal form + */ + interaction_modal_response(const std::string& _custom_id, const std::string& _title, const std::vector _components = {}); + + /** + * @brief Set the custom id + * + * @param _custom_id custom id to set + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& set_custom_id(const std::string& _custom_id); + + /** + * @brief Set the title + * + * @param _title title to set + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& set_title(const std::string& _title); + + /** + * @brief Add a component to an interaction modal response + * + * @param c component to add + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& add_component(const component& c); + + /** + * @brief Add a new row to the interaction modal response. + * @note A modal response can have a maximum of five rows. + * @throw dpp::logic_exception if more than five rows are attempted to be added + * @return interaction_modal_response& Reference to self + */ + interaction_modal_response& add_row(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction_response& Reference to self + */ + interaction_modal_response& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * @param with_id include id in json output + * + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Destroy the interaction modal response object + */ + virtual ~interaction_modal_response() = default; +}; + +/** + * @brief Resolved snowflake ids to users, guild members, roles and channels. + */ +struct DPP_EXPORT command_resolved { + /** + * @brief Resolved users + */ + std::map users; + /** + * @brief Resolved guild members + */ + std::map members; + /** + * @brief Resolved total guild member permissions in the channel, including overwrites + */ + std::map member_permissions; + /** + * @brief Resolved roles + */ + std::map roles; + /** + * @brief Resolved channels + */ + std::map channels; + /** + * @brief Resolved messages + */ + std::map messages; + /** + * @brief Resolved attachments + */ + std::map attachments; +}; + +/** + * @brief Values in the command interaction. + * These are the values specified by the user when actually issuing + * the command on a channel or in DM. + */ +struct DPP_EXPORT command_data_option { + std::string name; //!< the name of the parameter + command_option_type type; //!< value of ApplicationCommandOptionType + command_value value; //!< Optional: the value of the pair + std::vector options; //!< Optional: present if this option is a group or subcommand + bool focused; //!< Optional: true if this option is the currently focused option for autocomplete + + /** + * @brief Check if the value variant holds std::monostate and options vector is empty (i.e. the option wasn't supplied) + * @return bool true, if value variant holds std::monostate and options vector is empty + */ + bool empty() { + return std::holds_alternative(value) && options.empty(); + } + + /** + * @brief Get an option value by index + * + * @tparam Type to get from the parameter + * @param index index number of parameter + * @return T returned type + */ + template T& get_value(size_t index) { + return std::get(options.at(index).value); + } +}; + +/** + * @brief helper function to deserialize a command_data_option from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cdo command_data_option to be deserialized + */ +void from_json(const nlohmann::json& j, command_data_option& cdo); + +/** Types of interaction in the dpp::interaction class + */ +enum interaction_type { + it_ping = 1, //!< ping + it_application_command = 2, //!< application command (slash command) + it_component_button = 3, //!< button click or select menu chosen (component interaction) + it_autocomplete = 4, //!< Autocomplete interaction + it_modal_submit = 5, //!< Modal form submission +}; + +/** + * @brief Right-click context menu types + */ +enum slashcommand_contextmenu_type { + ctxm_none = 0, //!< Undefined context menu type + ctxm_chat_input = 1, //!< DEFAULT, these are the slash commands you're used to + ctxm_user = 2, //!< Add command to user context menu + ctxm_message = 3 //!< Add command to message context menu +}; + +/** + * @brief Details of a command within an interaction. + * This subobject represents the application command associated + * with the interaction. + */ +struct DPP_EXPORT command_interaction { + snowflake id; //!< the ID of the invoked command + std::string name; //!< the name of the invoked command + std::vector options; //!< Optional: the params + values from the user + slashcommand_contextmenu_type type; //!< type of the command interaction + dpp::snowflake target_id; //!< Non-zero target ID for context menu actions. e.g. user id or message id whom clicked or tapped with the context menu https://discord.com/developers/docs/interactions/application-commands#user-commands + + /** + * @brief Get an option value by index + * + * @tparam Type to get from the parameter + * @param index index number of parameter + * @return T returned type + */ + template T& get_value(size_t index) { + return std::get(options.at(index).value); + } + + /** + * @brief Return a ping/mention for the slash command + * + * @return std::string mention. e.g. `` + * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention + */ + std::string get_mention() const; +}; + +/** + * @brief helper function to deserialize a command_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param ci command_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, command_interaction& ci); + +/** + * @brief A button click for a button component + */ +struct DPP_EXPORT component_interaction { + /** + * @brief Component type (dpp::component_type) + */ + uint8_t component_type; + /** + * @brief Custom ID set when created + */ + std::string custom_id; + /** + * @brief Possible values for a drop down list + */ + std::vector values; +}; + +/** + * @brief An auto complete interaction + */ +struct DPP_EXPORT autocomplete_interaction : public command_interaction { +}; + +/** + * @brief helper function to deserialize a component_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param bi button_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, component_interaction& bi); + +/** + * @brief helper function to deserialize an autocomplete_interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param ai autocomplete_interaction to be deserialized + */ +void from_json(const nlohmann::json& j, autocomplete_interaction& ai); + +/** + * @brief An interaction represents a user running a command and arrives + * via the dpp::cluster::on_interaction_create event. This is further split + * into the events on_form_submit, on_slashcommand, on_user_context_menu, + * on_button_click, on_select_menu, etc. + */ +class DPP_EXPORT interaction : public managed, public json_interface { + + /** + * @brief Get a resolved object from the resolved set + * + * @tparam T type of object to retrieve + * @tparam C container defintion for resolved container + * @param id Snowflake ID + * @param resolved_set container for the type + * @return const T& retrieved type + * @throws dpp::logic_exception on object not found in resolved set + */ + template const T& get_resolved(snowflake id, const C& resolved_set) const { + auto i = resolved_set.find(id); + if (i == resolved_set.end()) { + throw dpp::logic_exception("ID not found in resolved properties of application command"); + } + return i->second; + } + +public: + snowflake application_id; //!< id of the application this interaction is for + uint8_t type; //!< the type of interaction (dpp::interaction_type) + std::variant data; //!< Optional: the command data payload + snowflake guild_id; //!< Optional: the guild it was sent from + snowflake channel_id; //!< Optional: the channel it was sent from + snowflake message_id; //!< Originating message id for context menu actions + permission app_permissions; //!< Permissions of the bot in the channel/guild where this command was issued + message msg; //!< Originating message for context menu actions + guild_member member; //!< Optional: guild member data for the invoking user, including permissions + user usr; //!< User object for the invoking user + std::string token; //!< a continuation token for responding to the interaction + uint8_t version; //!< read-only property, always 1 + command_resolved resolved; //!< Resolved user/role etc + std::string locale; //!< User's locale (language) + std::string guild_locale; //!< Guild's locale (language) - for guild interactions only + cache_policy_t cache_policy; //!< Cache policy from cluster + + /** + * @brief Construct a new interaction object + */ + interaction(); + + /** + * @brief Destroy the interaction object + */ + virtual ~interaction() = default; + + /** + * @brief Get a user associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id User snowflake ID to find + * @return const dpp::user& user + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::user& get_resolved_user(snowflake id) const; + + /** + * @brief Get the channel this command originated on + * + * @return const dpp::channel& channel + * @throws dpp::logic_exception Command originated from a DM or channel not in cache + */ + const dpp::channel& get_channel() const; + + /** + * @brief Get the guild this command originated on + * + * @return const dpp::guild& guild + * @throws dpp::logic_exception Command originated from a DM or guild not in cache + */ + const dpp::guild& get_guild() const; + + /** + * @brief Get the user who issued this command + * + * @return const dpp::user& user + */ + const dpp::user& get_issuing_user() const; + + /** + * @brief Get the message this action refers to if it is a context menu command + * + * @return const dpp::message& context menu message + */ + const dpp::message& get_context_message() const; + + /** + * @brief Get a role associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Role snowflake ID to find + * @return const dpp::role& role + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::role& get_resolved_role(snowflake id) const; + + /** + * @brief Get a channel associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Channel snowflake ID to find + * @return const dpp::channel& channel + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::channel& get_resolved_channel(snowflake id) const; + + /** + * @brief Get a guild member associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id User snowflake ID to find + * @return const dpp::guild_member& guild member + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::guild_member& get_resolved_member(snowflake id) const; + + /** + * @brief Get a permission associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id User snowflake ID to find + * @return const dpp::permission& permissions for the user including overrides on + * the channel where the command was issued. + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::permission& get_resolved_permission(snowflake id) const; + + /** + * @brief Get a message associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Message snowflake ID to find + * @return const dpp::message& message + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::message& get_resolved_message(snowflake id) const; + + /** + * @brief Get an uploaded attachment associated with the slash command from the resolved list. + * The resolved list contains associated structures for this command and does not + * use the cache or require any extra API calls. + * + * @param id Attachment snowflake ID to find + * @return const dpp::attachment& file attachment + * @throws dpp::logic_exception on object not found in resolved set + */ + const dpp::attachment& get_resolved_attachment(snowflake id) const; + + /** + * @brief Get the command interaction object + * + * @throw dpp::logic_exception if the interaction is not for a command + * + * @return command_interaction object + */ + command_interaction get_command_interaction() const; + + /** + * @brief Get the component interaction object + * + * @throw dpp::logic_exception if the interaction is not for a component + * + * @return component_interaction object + */ + component_interaction get_component_interaction() const; + + /** + * @brief Get the autocomplete interaction object + * + * @throw dpp::logic_exception if the interaction is not for an autocomplete + * + * @return autocomplete_interaction object + */ + autocomplete_interaction get_autocomplete_interaction() const; + + /** + * @brief Get the command name for a command interaction + * + * @return std::string command interaction, or empty string if the interaction + * is not for a command. + */ + std::string get_command_name() const; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return interaction& Reference to self + */ + interaction& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id True if to include the ID in the JSON + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to deserialize an interaction from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param i interaction to be deserialized + */ +void from_json(const nlohmann::json& j, interaction& i); + +/** + * @brief type of permission in the dpp::command_permission class + */ +enum command_permission_type { + /** + * @brief Role permission + * + */ + cpt_role = 1, + /** + * @brief User permission + * + */ + cpt_user = 2, +}; + +/** + * @brief Application command permissions allow you to enable or + * disable commands for specific users or roles within a guild + */ +class DPP_EXPORT command_permission : public json_interface { +public: + snowflake id; //!< the ID of the role or user + command_permission_type type; //!< the type of permission + bool permission; //!< true to allow, false, to disallow + + /** + * @brief Construct a new command permission object + */ + command_permission() = default; + + virtual ~command_permission() = default; + + /** + * @brief Construct a new command permission object + * + * @param id The ID of the role or user + * @param t The permission type + * @param permission True to allow, false, to disallow + */ + command_permission(snowflake id, const command_permission_type t, bool permission); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return command_permission& Reference to self + */ + command_permission &fill_from_json(nlohmann::json *j); +}; + +/** + * @brief helper function to serialize a command_permission to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cp command_permission to be serialized + */ +void to_json(nlohmann::json& j, const command_permission& cp); + +/** + * @brief Returned when fetching the permissions for a command in a guild. + */ +class DPP_EXPORT guild_command_permissions : public json_interface { +public: + snowflake id; //!< the id of the command + snowflake application_id; //!< the id of the application the command belongs to + snowflake guild_id; //!< the id of the guild + std::vector permissions; //!< the permissions for the command in the guild + + /** + * @brief Construct a new guild command permissions object + */ + guild_command_permissions(); + + virtual ~guild_command_permissions() = default; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return guild_command_permissions& Reference to self + */ + guild_command_permissions &fill_from_json(nlohmann::json *j); + +}; + +/** + * @brief helper function to serialize a guild_command_permissions to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param gcp guild_command_permissions to be serialized + */ +void to_json(nlohmann::json& j, const guild_command_permissions& gcp); + +/** + * @brief Represents an application command, created by your bot + * either globally, or on a guild. + */ +class DPP_EXPORT slashcommand : public managed, public json_interface { +public: + /** + * @brief Application id (usually matches your bots id) + */ + snowflake application_id; + + /** + * @brief Context menu type, defaults to dpp::ctxm_chat_input + */ + slashcommand_contextmenu_type type; + + /** + * @brief Command name (1-32 chars) + */ + std::string name; + + /** + * @brief Command description (1-100 chars) + */ + std::string description; + + /** + * @brief Command options (parameters) + */ + std::vector options; + + /** + * @brief Whether the command is enabled by default when the app is added to a guild. + * This has no effect as the default_member_permissions value is used instead. + * @deprecated Discord discourage use of this value and instead you should use slashcommand::default_member_permissions. + */ + bool default_permission; + + /** + * @brief command permissions + * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. + */ + std::vector permissions; + + /** + * @brief autoincrementing version identifier updated during substantial record changes + */ + snowflake version; + + /** + * @brief Localisations of command name + */ + std::map name_localizations; + + /** + * @brief Localisations of command description + */ + std::map description_localizations; + + /** + * @brief The default permissions of this command on a guild. + * D++ defaults this to dpp::p_use_application_commands. + * @note You can set it to 0 to disable the command for everyone except admins by default + */ + permission default_member_permissions; + + /** + * @brief True if this command should be allowed in a DM + * D++ defaults this to false. Cannot be set to true in a guild + * command, only a global command. + */ + bool dm_permission; + + /** + * @brief Indicates whether the command is [age-restricted](https://discord.com/developers/docs/interactions/application-commands#agerestricted-commands). + * Defaults to false + */ + bool nsfw; + + /** + * @brief Construct a new slashcommand object + */ + slashcommand(); + + /** + * @brief Construct a new slashcommand object + * + * @param _name Command name + * @param _description Command description + * @param _application_id Application id (usually the bot's user id) + */ + slashcommand(const std::string &_name, const std::string &_description, const dpp::snowflake _application_id); + + /** + * @brief Destroy the slashcommand object + */ + virtual ~slashcommand(); + + /** + * @brief Add a localisation for this slash command + * @see https://discord.com/developers/docs/reference#locales + * @param language Name of language, see the list of locales linked to above. + * @param _name name of slash command in the specified language + * @param _description description of slash command in the specified language + * @return slashcommand& reference to self for fluent chaining + */ + slashcommand& add_localization(const std::string& language, const std::string& _name, const std::string& _description); + + /** + * @brief Set the dm permission for the command + * + * @param dm true to allow this command in dms + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_dm_permission(bool dm); + + /** + * @brief Set whether the command should be age-restricted or not + * + * @param is_nsfw true if the command should be age-restricted + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_nsfw(bool is_nsfw); + + /** + * @brief Set the default permissions of the slash command + * + * @param defaults default permissions to set. This is a permission bitmask of bits from dpp::permissions + * @note You can set it to 0 to disable the command for everyone except admins by default + * + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_default_permissions(uint64_t defaults); + + /** + * @brief Add an option (parameter) + * + * @param o option (parameter) to add + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& add_option(const command_option &o); + + /** + * @brief Set the type of the slash command (only for context menu entries) + * + * @param _type Type of context menu entry this command represents + * @note If the type is dpp::ctxm_chat_input, the command name will be set to lowercase. + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_type(slashcommand_contextmenu_type _type); + + /** + * @brief Set the name of the command + * + * @param n name of command + * @note The maximum length of a command name is 32 UTF-8 codepoints. + * If your command name is longer than this, it will be truncated. + * The command name will be set to lowercase when the type is the default dpp::ctxm_chat_input. + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_name(const std::string &n); + + /** + * @brief Set the description of the command + * + * @param d description + * @note The maximum length of a command description is 100 UTF-8 codepoints. + * If your command description is longer than this, it will be truncated. + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_description(const std::string &d); + + /** + * @brief Set the application id of the command + * + * @param i application id + * @return slashcommand& reference to self for chaining of calls + */ + slashcommand& set_application_id(snowflake i); + + /** + * @brief Adds a permission to the command + * + * @param p permission to add + * @return slashcommand& reference to self for chaining of calls + * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. + */ + slashcommand& add_permission(const command_permission& p); + + /** + * @brief Disable default permissions, command will be unusable unless + * permissions are overridden with add_permission and + * dpp::guild_command_edit_permissions + * + * @return slashcommand& reference to self for chaining of calls + * @deprecated Discord discourage use of this value and instead you should use default_member_permissions. + */ + slashcommand& disable_default_permissions(); + + /** + * @brief Return a ping/mention for the slash command + * + * @return std::string mention. e.g. `` + * @note If you want a mention for a subcommand or subcommand group, you can use dpp::utility::slashcommand_mention + */ + std::string get_mention() const; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return slashcommand& Reference to self + */ + slashcommand& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id True if to include the ID in the JSON + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to serialize a slashcommand to json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param cmd slashcommand to be serialized + */ +void to_json(nlohmann::json& j, const slashcommand& cmd); + +/** + * @brief A group of application slash commands + */ +typedef std::unordered_map slashcommand_map; + +/** + * @brief A group of guild command permissions + */ +typedef std::unordered_map guild_command_permissions_map; + +}; diff --git a/3rdParty/dpp/application.h b/3rdParty/dpp/application.h index f84ff4be0d..3d23c8a8d2 100644 --- a/3rdParty/dpp/application.h +++ b/3rdParty/dpp/application.h @@ -1,162 +1,162 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief status of a member of a team who maintain a bot/application - */ -enum team_member_status : uint8_t { - /// User was invited to the team - tms_invited = 1, - /// User has accepted membership onto the team - tms_accepted = 2 -}; - -/** - * @brief Flags for a bot or application - */ -enum application_flags : uint32_t { - /// Has gateway presence intent - apf_gateway_presence = (1 << 12), - /// Has gateway presence intent for <100 guilds - apf_gateway_presence_limited = (1 << 13), - /// Has guild members intent - apf_gateway_guild_members = (1 << 14), - /// Has guild members intent for <100 guilds - apf_gateway_guild_members_limited = (1 << 15), - /// Verification is pending - apf_verification_pending_guild_limit = (1 << 16), - /// Embedded - apf_embedded = (1 << 17), - /// Has approval for message content - apf_gateway_message_content = (1 << 18), - /// Has message content, but <100 guilds - apf_gateway_message_content_limited = (1 << 19), - /// Indicates if the app has registered global application commands - apf_application_command_badge = (1 << 23) -}; - -/** - * @brief Represents the settings for the bot/application's in-app authorization link - */ -struct DPP_EXPORT application_install_params { - permission permissions; //!< A bitmask of dpp::permissions to request for the bot role - std::vector scopes; //!< The [scopes](https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes) as strings to add the application to the server with -}; - -/** - * @brief Represents a team member on a team who maintain a bot/application - */ -class DPP_EXPORT team_member { -public: - team_member_status membership_state; //!< the user's membership state on the team - std::string permissions; //!< will always be [""] - snowflake team_id; //!< the id of the parent team of which they are a member - user member_user; //!< the avatar, discriminator, id, and username of the user -}; - -/** - * @brief Represents a team of users who maintain a bot/application - */ -class DPP_EXPORT app_team { -public: - utility::iconhash icon; //!< a hash of the image of the team's icon (may be empty) - snowflake id; //!< the unique id of the team - std::vector members; //!< the members of the team - std::string name; //!< the name of the team - snowflake owner_user_id; //!< the user id of the current team owner -}; - -/** - * @brief The application class represents details of a bot application - */ -class DPP_EXPORT application : public managed, public json_interface { -public: - std::string name; //!< the name of the app - utility::iconhash icon; //!< the icon hash of the app (may be empty) - std::string description; //!< the description of the app - std::string rpc_origins; //!< Optional: an array of rpc origin urls, if rpc is enabled - bool bot_public; //!< when false only app owner can join the app's bot to guilds - bool bot_require_code_grant; //!< when true the app's bot will only join upon completion of the full oauth2 code grant flow - std::string terms_of_service_url; //!< Optional: the url of the app's terms of service - std::string privacy_policy_url; //!< Optional: the url of the app's privacy policy - user owner; //!< Optional: partial user object containing info on the owner of the application - std::string summary; //!< if this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku @deprecated Will be removed in v11 - std::string verify_key; //!< the hex encoded key for verification in interactions and the GameSDK's GetTicket - app_team team; //!< if the application belongs to a team, this will be a list of the members of that team (may be empty) - snowflake guild_id; //!< Optional: if this application is a game sold on Discord, this field will be the guild to which it has been linked - snowflake primary_sku_id; //!< Optional: if this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists - std::string slug; //!< Optional: if this application is a game sold on Discord, this field will be the URL slug that links to the store page - utility::iconhash cover_image; //!< Optional: the application's default rich presence invite cover image hash - uint32_t flags; //!< Optional: the application's public flags - std::vector tags; //!< Up to 5 tags describing the content and functionality of the application - application_install_params install_params; //!< Settings for the application's default in-app authorization link, if enabled - std::string custom_install_url; //!< The application's default custom authorization link, if enabled - std::string role_connections_verification_url; //!< The application's role connection verification entry point, which when configured will render the app as a verification method in the guild role verification configuration - - /** Constructor */ - application(); - - /** Destructor */ - ~application(); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - application& fill_from_json(nlohmann::json* j); - - /** - * @brief Get the applications cover image url if they have one, otherwise returns an empty string - * - * @param size The size of the cover image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized cover image is returned. - * @return std::string cover image url or empty string - */ - std::string get_cover_image_url(uint16_t size = 0) const; - - /** - * @brief Get the applications icon url if they have one, otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; -}; - -/** A group of applications. - * This is not currently ever sent by Discord API but the DPP standard setup for - * objects that can be received by REST has the possibility for this, so this exists. - * Don't ever expect to see one at present. - */ -typedef std::unordered_map application_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief status of a member of a team who maintain a bot/application + */ +enum team_member_status : uint8_t { + /// User was invited to the team + tms_invited = 1, + /// User has accepted membership onto the team + tms_accepted = 2 +}; + +/** + * @brief Flags for a bot or application + */ +enum application_flags : uint32_t { + /// Has gateway presence intent + apf_gateway_presence = (1 << 12), + /// Has gateway presence intent for <100 guilds + apf_gateway_presence_limited = (1 << 13), + /// Has guild members intent + apf_gateway_guild_members = (1 << 14), + /// Has guild members intent for <100 guilds + apf_gateway_guild_members_limited = (1 << 15), + /// Verification is pending + apf_verification_pending_guild_limit = (1 << 16), + /// Embedded + apf_embedded = (1 << 17), + /// Has approval for message content + apf_gateway_message_content = (1 << 18), + /// Has message content, but <100 guilds + apf_gateway_message_content_limited = (1 << 19), + /// Indicates if the app has registered global application commands + apf_application_command_badge = (1 << 23) +}; + +/** + * @brief Represents the settings for the bot/application's in-app authorization link + */ +struct DPP_EXPORT application_install_params { + permission permissions; //!< A bitmask of dpp::permissions to request for the bot role + std::vector scopes; //!< The [scopes](https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes) as strings to add the application to the server with +}; + +/** + * @brief Represents a team member on a team who maintain a bot/application + */ +class DPP_EXPORT team_member { +public: + team_member_status membership_state; //!< the user's membership state on the team + std::string permissions; //!< will always be [""] + snowflake team_id; //!< the id of the parent team of which they are a member + user member_user; //!< the avatar, discriminator, id, and username of the user +}; + +/** + * @brief Represents a team of users who maintain a bot/application + */ +class DPP_EXPORT app_team { +public: + utility::iconhash icon; //!< a hash of the image of the team's icon (may be empty) + snowflake id; //!< the unique id of the team + std::vector members; //!< the members of the team + std::string name; //!< the name of the team + snowflake owner_user_id; //!< the user id of the current team owner +}; + +/** + * @brief The application class represents details of a bot application + */ +class DPP_EXPORT application : public managed, public json_interface { +public: + std::string name; //!< the name of the app + utility::iconhash icon; //!< the icon hash of the app (may be empty) + std::string description; //!< the description of the app + std::string rpc_origins; //!< Optional: an array of rpc origin urls, if rpc is enabled + bool bot_public; //!< when false only app owner can join the app's bot to guilds + bool bot_require_code_grant; //!< when true the app's bot will only join upon completion of the full oauth2 code grant flow + std::string terms_of_service_url; //!< Optional: the url of the app's terms of service + std::string privacy_policy_url; //!< Optional: the url of the app's privacy policy + user owner; //!< Optional: partial user object containing info on the owner of the application + std::string summary; //!< if this application is a game sold on Discord, this field will be the summary field for the store page of its primary sku @deprecated Will be removed in v11 + std::string verify_key; //!< the hex encoded key for verification in interactions and the GameSDK's GetTicket + app_team team; //!< if the application belongs to a team, this will be a list of the members of that team (may be empty) + snowflake guild_id; //!< Optional: if this application is a game sold on Discord, this field will be the guild to which it has been linked + snowflake primary_sku_id; //!< Optional: if this application is a game sold on Discord, this field will be the id of the "Game SKU" that is created, if exists + std::string slug; //!< Optional: if this application is a game sold on Discord, this field will be the URL slug that links to the store page + utility::iconhash cover_image; //!< Optional: the application's default rich presence invite cover image hash + uint32_t flags; //!< Optional: the application's public flags + std::vector tags; //!< Up to 5 tags describing the content and functionality of the application + application_install_params install_params; //!< Settings for the application's default in-app authorization link, if enabled + std::string custom_install_url; //!< The application's default custom authorization link, if enabled + std::string role_connections_verification_url; //!< The application's role connection verification entry point, which when configured will render the app as a verification method in the guild role verification configuration + + /** Constructor */ + application(); + + /** Destructor */ + ~application(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + application& fill_from_json(nlohmann::json* j); + + /** + * @brief Get the applications cover image url if they have one, otherwise returns an empty string + * + * @param size The size of the cover image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized cover image is returned. + * @return std::string cover image url or empty string + */ + std::string get_cover_image_url(uint16_t size = 0) const; + + /** + * @brief Get the applications icon url if they have one, otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; +}; + +/** A group of applications. + * This is not currently ever sent by Discord API but the DPP standard setup for + * objects that can be received by REST has the possibility for this, so this exists. + * Don't ever expect to see one at present. + */ +typedef std::unordered_map application_map; + +}; diff --git a/3rdParty/dpp/auditlog.h b/3rdParty/dpp/auditlog.h index 49ecbedfba..abcde0a54f 100644 --- a/3rdParty/dpp/auditlog.h +++ b/3rdParty/dpp/auditlog.h @@ -1,214 +1,214 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Defines types of audit log entry - */ -enum audit_type { - /// Guild update - aut_guild_update = 1, - /// Channel create - aut_channel_create = 10, - /// Channel update - aut_channel_update = 11, - /// Channel delete - aut_channel_delete = 12, - /// Channel overwrite create - aut_channel_overwrite_create = 13, - /// Channel overwrite update - aut_channel_overwrite_update = 14, - /// Channel overwrite delete - aut_channel_overwrite_delete = 15, - /// Channel member kick - aut_member_kick = 20, - /// Channel member prune - aut_member_prune = 21, - /// Channel member ban add - aut_member_ban_add = 22, - /// Channel member ban remove - aut_member_ban_remove = 23, - /// Guild member update - aut_member_update = 24, - /// Guild member role update - aut_member_role_update = 25, - /// Guild member move - aut_member_move = 26, - /// Guild member voice disconnect - aut_member_disconnect = 27, - /// Guild bot add - aut_bot_add = 28, - /// Guild role create - aut_role_create = 30, - /// Guild role update - aut_role_update = 31, - /// Guild role delete - aut_role_delete = 32, - /// Guild invite create - aut_invite_create = 40, - /// Guild invite update - aut_invite_update = 41, - /// Guild invite delete - aut_invite_delete = 42, - /// Guild webhook create - aut_webhook_create = 50, - /// Guild webhook update - aut_webhook_update = 51, - /// Guild webhook delete - aut_webhook_delete = 52, - /// Guild emoji create - aut_emoji_create = 60, - /// Guild emoji update - aut_emoji_update = 61, - /// Guild emoji delete - aut_emoji_delete = 62, - /// Guild message delete - aut_message_delete = 72, - /// Guild message bulk delete - aut_message_bulk_delete = 73, - /// Guild message pin - aut_message_pin = 74, - /// Guild message unpin - aut_message_unpin = 75, - /// Guild integration create - aut_integration_create = 80, - /// Guild integration update - aut_integration_update = 81, - /// Guild integration delete - aut_integration_delete = 82, - /// Stage instance create - aut_stage_instance_create = 83, - /// Stage instance update - aut_stage_instance_update = 84, - /// stage instance delete - aut_stage_instance_delete = 85, - /// Sticker create - aut_sticker_create = 90, - /// Sticker update - aut_sticker_update = 91, - /// Sticker delete - aut_sticker_delete = 92, - /// Scheduled event creation - aut_guild_scheduled_event_create = 100, - /// Scheduled event update - aut_guild_scheduled_event_update = 101, - /// Scheduled event deletion - aut_guild_scheduled_event_delete = 102, - /// Thread create - aut_thread_create = 110, - /// Thread update - aut_thread_update = 111, - /// Thread delete - aut_thread_delete = 112, - /// Application command permissions update - aut_appcommand_permission_update = 121, - /// Auto moderation rule creation - aut_automod_rule_create = 140, - /// Auto moderation rule update - aut_automod_rule_update = 141, - /// Auto moderation rule deletion - aut_automod_rule_delete = 142, - /// Message was blocked by Auto Moderation - aut_automod_block_message = 143, - /// Message was flagged by Auto Moderation - aut_automod_flag_to_channel = 144, - /// Member was timed out by Auto Moderation - aut_automod_user_communication_disabled = 145, -}; - -/** - * @brief Defines audit log changes - */ -struct DPP_EXPORT audit_change { - /// Optional: Serialised new value of the change, e.g. for nicknames, the new nickname - std::string new_value; - /// Optional: Serialised old value of the change, e.g. for nicknames, the old nickname - std::string old_value; - /** - * The property name that was changed, e.g. `nick` for nickname changes - * @note For dpp::aut_appcommand_permission_update updates the key is the id of the user, channel, role, or a permission constant that was updated instead of an actual property name - */ - std::string key; -}; - -/** - * @brief Extra information for an audit log entry - */ -struct DPP_EXPORT audit_extra { - std::string automod_rule_name; //!< Name of the Auto Moderation rule that was triggered - std::string automod_rule_trigger_type; //!< Trigger type of the Auto Moderation rule that was triggered - std::string delete_member_days; //!< number of days after which inactive members were kicked - std::string members_removed; //!< number of members removed by the prune - snowflake channel_id; //!< channel in which the entities were targeted - snowflake message_id; //!< id of the message that was targeted - std::string count; //!< number of entities that were targeted - snowflake id; //!< id of the overwritten entity - std::string type; //!< type of overwritten entity - "0" for "role" or "1" for "member" - std::string role_name; //!< name of the role if type is "0" (not present if type is "1") - snowflake application_id; //!< ID of the app whose permissions were targeted -}; - -/** - * @brief An individual audit log entry - */ -struct DPP_EXPORT audit_entry { - snowflake id; //!< id of the entry - /** - * ID of the affected entity (webhook, user, role, etc.) (may be empty) - * @note For dpp::audit_type::aut_appcommand_permission_update updates, it's the command ID or the app ID - */ - snowflake target_id; - std::vector changes; //!< Optional: changes made to the target_id - snowflake user_id; //!< the user or app that made the changes (may be empty) - audit_type type; //!< type of action that occurred - std::optional extra; //!< Optional: additional info for certain action types - std::string reason; //!< Optional: the reason for the change (1-512 characters) -}; - -/** - * @brief The auditlog class represents the audit log entries of a guild. - */ -class DPP_EXPORT auditlog : public json_interface { -public: - std::vector entries; //!< Audit log entries - - /** Constructor */ - auditlog() = default; - - /** Destructor */ - virtual ~auditlog() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - auditlog& fill_from_json(nlohmann::json* j); -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines types of audit log entry + */ +enum audit_type { + /// Guild update + aut_guild_update = 1, + /// Channel create + aut_channel_create = 10, + /// Channel update + aut_channel_update = 11, + /// Channel delete + aut_channel_delete = 12, + /// Channel overwrite create + aut_channel_overwrite_create = 13, + /// Channel overwrite update + aut_channel_overwrite_update = 14, + /// Channel overwrite delete + aut_channel_overwrite_delete = 15, + /// Channel member kick + aut_member_kick = 20, + /// Channel member prune + aut_member_prune = 21, + /// Channel member ban add + aut_member_ban_add = 22, + /// Channel member ban remove + aut_member_ban_remove = 23, + /// Guild member update + aut_member_update = 24, + /// Guild member role update + aut_member_role_update = 25, + /// Guild member move + aut_member_move = 26, + /// Guild member voice disconnect + aut_member_disconnect = 27, + /// Guild bot add + aut_bot_add = 28, + /// Guild role create + aut_role_create = 30, + /// Guild role update + aut_role_update = 31, + /// Guild role delete + aut_role_delete = 32, + /// Guild invite create + aut_invite_create = 40, + /// Guild invite update + aut_invite_update = 41, + /// Guild invite delete + aut_invite_delete = 42, + /// Guild webhook create + aut_webhook_create = 50, + /// Guild webhook update + aut_webhook_update = 51, + /// Guild webhook delete + aut_webhook_delete = 52, + /// Guild emoji create + aut_emoji_create = 60, + /// Guild emoji update + aut_emoji_update = 61, + /// Guild emoji delete + aut_emoji_delete = 62, + /// Guild message delete + aut_message_delete = 72, + /// Guild message bulk delete + aut_message_bulk_delete = 73, + /// Guild message pin + aut_message_pin = 74, + /// Guild message unpin + aut_message_unpin = 75, + /// Guild integration create + aut_integration_create = 80, + /// Guild integration update + aut_integration_update = 81, + /// Guild integration delete + aut_integration_delete = 82, + /// Stage instance create + aut_stage_instance_create = 83, + /// Stage instance update + aut_stage_instance_update = 84, + /// stage instance delete + aut_stage_instance_delete = 85, + /// Sticker create + aut_sticker_create = 90, + /// Sticker update + aut_sticker_update = 91, + /// Sticker delete + aut_sticker_delete = 92, + /// Scheduled event creation + aut_guild_scheduled_event_create = 100, + /// Scheduled event update + aut_guild_scheduled_event_update = 101, + /// Scheduled event deletion + aut_guild_scheduled_event_delete = 102, + /// Thread create + aut_thread_create = 110, + /// Thread update + aut_thread_update = 111, + /// Thread delete + aut_thread_delete = 112, + /// Application command permissions update + aut_appcommand_permission_update = 121, + /// Auto moderation rule creation + aut_automod_rule_create = 140, + /// Auto moderation rule update + aut_automod_rule_update = 141, + /// Auto moderation rule deletion + aut_automod_rule_delete = 142, + /// Message was blocked by Auto Moderation + aut_automod_block_message = 143, + /// Message was flagged by Auto Moderation + aut_automod_flag_to_channel = 144, + /// Member was timed out by Auto Moderation + aut_automod_user_communication_disabled = 145, +}; + +/** + * @brief Defines audit log changes + */ +struct DPP_EXPORT audit_change { + /// Optional: Serialised new value of the change, e.g. for nicknames, the new nickname + std::string new_value; + /// Optional: Serialised old value of the change, e.g. for nicknames, the old nickname + std::string old_value; + /** + * The property name that was changed, e.g. `nick` for nickname changes + * @note For dpp::aut_appcommand_permission_update updates the key is the id of the user, channel, role, or a permission constant that was updated instead of an actual property name + */ + std::string key; +}; + +/** + * @brief Extra information for an audit log entry + */ +struct DPP_EXPORT audit_extra { + std::string automod_rule_name; //!< Name of the Auto Moderation rule that was triggered + std::string automod_rule_trigger_type; //!< Trigger type of the Auto Moderation rule that was triggered + std::string delete_member_days; //!< number of days after which inactive members were kicked + std::string members_removed; //!< number of members removed by the prune + snowflake channel_id; //!< channel in which the entities were targeted + snowflake message_id; //!< id of the message that was targeted + std::string count; //!< number of entities that were targeted + snowflake id; //!< id of the overwritten entity + std::string type; //!< type of overwritten entity - "0" for "role" or "1" for "member" + std::string role_name; //!< name of the role if type is "0" (not present if type is "1") + snowflake application_id; //!< ID of the app whose permissions were targeted +}; + +/** + * @brief An individual audit log entry + */ +struct DPP_EXPORT audit_entry { + snowflake id; //!< id of the entry + /** + * ID of the affected entity (webhook, user, role, etc.) (may be empty) + * @note For dpp::audit_type::aut_appcommand_permission_update updates, it's the command ID or the app ID + */ + snowflake target_id; + std::vector changes; //!< Optional: changes made to the target_id + snowflake user_id; //!< the user or app that made the changes (may be empty) + audit_type type; //!< type of action that occurred + std::optional extra; //!< Optional: additional info for certain action types + std::string reason; //!< Optional: the reason for the change (1-512 characters) +}; + +/** + * @brief The auditlog class represents the audit log entries of a guild. + */ +class DPP_EXPORT auditlog : public json_interface { +public: + std::vector entries; //!< Audit log entries + + /** Constructor */ + auditlog() = default; + + /** Destructor */ + virtual ~auditlog() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + auditlog& fill_from_json(nlohmann::json* j); +}; + +}; diff --git a/3rdParty/dpp/automod.h b/3rdParty/dpp/automod.h index f04dba4230..12a4afcdc3 100644 --- a/3rdParty/dpp/automod.h +++ b/3rdParty/dpp/automod.h @@ -1,363 +1,363 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Possible types of preset filter lists - */ -enum automod_preset_type : uint8_t { - /** - * @brief Strong swearing - */ - amod_preset_profanity = 1, - /** - * @brief Sexual phrases and words - */ - amod_preset_sexual_content = 2, - /** - * @brief Racial and other slurs, hate speech - */ - amod_preset_slurs = 3, -}; - -/** - * @brief Action types to perform on filtering - */ -enum automod_action_type : uint8_t { - /** - * @brief Block the message - */ - amod_action_block_message = 1, - /** - * @brief Send an alert to a given channel - */ - amod_action_send_alert = 2, - /** - * @brief time out the user - */ - amod_action_timeout = 3, -}; - -/** - * @brief Event types, only message send is currently supported - */ -enum automod_event_type : uint8_t { - /** - * @brief Trigger on message send or edit - */ - amod_message_send = 1, -}; - -/** - * @brief Types of moderation to trigger - */ -enum automod_trigger_type : uint8_t { - /** - * @brief Check if content contains words from a user defined list of keywords - */ - amod_type_keyword = 1, - /** - * @brief Harmful/malware links - * @deprecated Removed by Discord - */ - amod_type_harmful_link = 2, - /** - * @brief Check if content represents generic spam - */ - amod_type_spam = 3, - /** - * @brief Check if content contains words from discord pre-defined wordsets - */ - amod_type_keyword_preset = 4, - /** - * @brief Check if content contains more mentions than allowed - */ - amod_type_mention_spam = 5, -}; - -/** - * @brief Metadata associated with an automod action - */ -struct DPP_EXPORT automod_metadata : public json_interface { - /** - * @brief @brief Substrings which will be searched for in content (Maximum of 1000). - * - * Each keyword can be a phrase which contains multiple words. - * All keywords are case insensitive and can be up to 30 characters. - * - * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. - * - * **Examples for the `*` wildcard symbol:** - * - * Prefix - word must start with the keyword - * - * | keyword | matches | - * |----------|-------------------------------------| - * | cat* | catch, Catapult, CAttLE | - * | the mat* | the matrix | - * - * Suffix - word must end with the keyword - * - * | keyword | matches | - * |----------|--------------------------| - * | *cat | wildcat, copyCat | - * | *the mat | breathe mat | - * - * Anywhere - keyword can appear anywhere in the content - * - * | keyword | matches | - * |-----------|-----------------------------| - * | \*cat* | location, eduCation | - * | \*the mat* | breathe matter | - * - * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end - * - * | keyword | matches | - * |---------|-------------| - * | cat | Cat | - * | the mat | the mat | - * - */ - std::vector keywords; - - /** - * @brief Regular expression patterns which will be matched against content (Maximum of 10). - * - * Only Rust flavored regex is currently supported, which can be tested in online editors such as [Rustexp](https://rustexp.lpil.uk/). - * Each regex pattern can be up to 260 characters. - */ - std::vector regex_patterns; - - /** - * @brief Preset keyword list types to moderate - * @see automod_preset_type - */ - std::vector presets; - - /** - * @brief Substrings which should not trigger the rule. - * - * Each keyword can be a phrase which contains multiple words. - * All keywords are case insensitive and can be up to 30 characters. - * - * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. - * - * **Examples for the `*` wildcard symbol:** - * - * Prefix - word must start with the keyword - * - * | keyword | matches | - * |----------|-------------------------------------| - * | cat* | catch, Catapult, CAttLE | - * | the mat* | the matrix | - * - * Suffix - word must end with the keyword - * - * | keyword | matches | - * |----------|--------------------------| - * | *cat | wildcat, copyCat | - * | *the mat | breathe mat | - * - * Anywhere - keyword can appear anywhere in the content - * - * | keyword | matches | - * |-----------|-----------------------------| - * | \*cat* | location, eduCation | - * | \*the mat* | breathe matter | - * - * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end - * - * | keyword | matches | - * |---------|-------------| - * | cat | Cat | - * | the mat | the mat | - * - */ - std::vector allow_list; - - /** - * @brief Total number of unique role and user mentions allowed per message (Maximum of 50) - */ - uint8_t mention_total_limit; - - /** - * @brief Construct a new automod metadata object - */ - automod_metadata(); - - /** - * @brief Destroy the automod metadata object - */ - virtual ~automod_metadata(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return automod_metadata& Reference to self - */ - automod_metadata& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - -}; - -/** - * @brief Represents an automod action - */ -struct DPP_EXPORT automod_action : public json_interface { - /** - * @brief Type of action to take - */ - automod_action_type type; - - /** - * @brief Channel ID, for type dpp::amod_action_send_alert - */ - snowflake channel_id; - - /** - * @brief Timeout duration in seconds (Maximum of 2419200), for dpp::amod_action_timeout - * - */ - int32_t duration_seconds; - - /** - * @brief Construct a new automod action object - */ - automod_action(); - - /** - * @brief Destroy the automod action object - */ - virtual ~automod_action(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return automod_action& Reference to self - */ - automod_action& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** - * @brief Represents an automod rule - */ -class DPP_EXPORT automod_rule : public managed, public json_interface { -public: - /** - * @brief the id of this rule - */ - snowflake id; - /** - * @brief the guild which this rule belongs to - */ - snowflake guild_id; - /** - * @brief the rule name - */ - std::string name; - /** - * @brief The user which first created this rule - */ - snowflake creator_id; - /** - * @brief The rule event type - */ - automod_event_type event_type; - /** - * @brief The rule trigger type - */ - automod_trigger_type trigger_type; - /** - * @brief The rule trigger metadata - */ - automod_metadata trigger_metadata; - /** - * @brief the actions which will execute when the rule is triggered - */ - std::vector actions; - /** - * @brief Whether the rule is enabled - */ - bool enabled; - /** - * @brief the role ids that should not be affected by the rule (Maximum of 20) - */ - std::vector exempt_roles; - /** - * @brief the channel ids that should not be affected by the rule (Maximum of 50) - */ - std::vector exempt_channels; - - /** - * @brief Construct a new automod rule object - */ - automod_rule(); - - /** - * @brief Destroy the automod rule object - */ - virtual ~automod_rule(); - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return automod_rule& Reference to self - */ - automod_rule& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** A group of automod rules. - */ -typedef std::unordered_map automod_rule_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Possible types of preset filter lists + */ +enum automod_preset_type : uint8_t { + /** + * @brief Strong swearing + */ + amod_preset_profanity = 1, + /** + * @brief Sexual phrases and words + */ + amod_preset_sexual_content = 2, + /** + * @brief Racial and other slurs, hate speech + */ + amod_preset_slurs = 3, +}; + +/** + * @brief Action types to perform on filtering + */ +enum automod_action_type : uint8_t { + /** + * @brief Block the message + */ + amod_action_block_message = 1, + /** + * @brief Send an alert to a given channel + */ + amod_action_send_alert = 2, + /** + * @brief time out the user + */ + amod_action_timeout = 3, +}; + +/** + * @brief Event types, only message send is currently supported + */ +enum automod_event_type : uint8_t { + /** + * @brief Trigger on message send or edit + */ + amod_message_send = 1, +}; + +/** + * @brief Types of moderation to trigger + */ +enum automod_trigger_type : uint8_t { + /** + * @brief Check if content contains words from a user defined list of keywords + */ + amod_type_keyword = 1, + /** + * @brief Harmful/malware links + * @deprecated Removed by Discord + */ + amod_type_harmful_link = 2, + /** + * @brief Check if content represents generic spam + */ + amod_type_spam = 3, + /** + * @brief Check if content contains words from discord pre-defined wordsets + */ + amod_type_keyword_preset = 4, + /** + * @brief Check if content contains more mentions than allowed + */ + amod_type_mention_spam = 5, +}; + +/** + * @brief Metadata associated with an automod action + */ +struct DPP_EXPORT automod_metadata : public json_interface { + /** + * @brief @brief Substrings which will be searched for in content (Maximum of 1000). + * + * Each keyword can be a phrase which contains multiple words. + * All keywords are case insensitive and can be up to 30 characters. + * + * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. + * + * **Examples for the `*` wildcard symbol:** + * + * Prefix - word must start with the keyword + * + * | keyword | matches | + * |----------|-------------------------------------| + * | cat* | catch, Catapult, CAttLE | + * | the mat* | the matrix | + * + * Suffix - word must end with the keyword + * + * | keyword | matches | + * |----------|--------------------------| + * | *cat | wildcat, copyCat | + * | *the mat | breathe mat | + * + * Anywhere - keyword can appear anywhere in the content + * + * | keyword | matches | + * |-----------|-----------------------------| + * | \*cat* | location, eduCation | + * | \*the mat* | breathe matter | + * + * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end + * + * | keyword | matches | + * |---------|-------------| + * | cat | Cat | + * | the mat | the mat | + * + */ + std::vector keywords; + + /** + * @brief Regular expression patterns which will be matched against content (Maximum of 10). + * + * Only Rust flavored regex is currently supported, which can be tested in online editors such as [Rustexp](https://rustexp.lpil.uk/). + * Each regex pattern can be up to 260 characters. + */ + std::vector regex_patterns; + + /** + * @brief Preset keyword list types to moderate + * @see automod_preset_type + */ + std::vector presets; + + /** + * @brief Substrings which should not trigger the rule. + * + * Each keyword can be a phrase which contains multiple words. + * All keywords are case insensitive and can be up to 30 characters. + * + * Wildcard symbols (`*`) can be used to customize how each keyword will be matched. + * + * **Examples for the `*` wildcard symbol:** + * + * Prefix - word must start with the keyword + * + * | keyword | matches | + * |----------|-------------------------------------| + * | cat* | catch, Catapult, CAttLE | + * | the mat* | the matrix | + * + * Suffix - word must end with the keyword + * + * | keyword | matches | + * |----------|--------------------------| + * | *cat | wildcat, copyCat | + * | *the mat | breathe mat | + * + * Anywhere - keyword can appear anywhere in the content + * + * | keyword | matches | + * |-----------|-----------------------------| + * | \*cat* | location, eduCation | + * | \*the mat* | breathe matter | + * + * Whole Word - keyword is a full word or phrase and must be surrounded by whitespace at the beginning and end + * + * | keyword | matches | + * |---------|-------------| + * | cat | Cat | + * | the mat | the mat | + * + */ + std::vector allow_list; + + /** + * @brief Total number of unique role and user mentions allowed per message (Maximum of 50) + */ + uint8_t mention_total_limit; + + /** + * @brief Construct a new automod metadata object + */ + automod_metadata(); + + /** + * @brief Destroy the automod metadata object + */ + virtual ~automod_metadata(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return automod_metadata& Reference to self + */ + automod_metadata& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + +}; + +/** + * @brief Represents an automod action + */ +struct DPP_EXPORT automod_action : public json_interface { + /** + * @brief Type of action to take + */ + automod_action_type type; + + /** + * @brief Channel ID, for type dpp::amod_action_send_alert + */ + snowflake channel_id; + + /** + * @brief Timeout duration in seconds (Maximum of 2419200), for dpp::amod_action_timeout + * + */ + int32_t duration_seconds; + + /** + * @brief Construct a new automod action object + */ + automod_action(); + + /** + * @brief Destroy the automod action object + */ + virtual ~automod_action(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return automod_action& Reference to self + */ + automod_action& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** + * @brief Represents an automod rule + */ +class DPP_EXPORT automod_rule : public managed, public json_interface { +public: + /** + * @brief the id of this rule + */ + snowflake id; + /** + * @brief the guild which this rule belongs to + */ + snowflake guild_id; + /** + * @brief the rule name + */ + std::string name; + /** + * @brief The user which first created this rule + */ + snowflake creator_id; + /** + * @brief The rule event type + */ + automod_event_type event_type; + /** + * @brief The rule trigger type + */ + automod_trigger_type trigger_type; + /** + * @brief The rule trigger metadata + */ + automod_metadata trigger_metadata; + /** + * @brief the actions which will execute when the rule is triggered + */ + std::vector actions; + /** + * @brief Whether the rule is enabled + */ + bool enabled; + /** + * @brief the role ids that should not be affected by the rule (Maximum of 20) + */ + std::vector exempt_roles; + /** + * @brief the channel ids that should not be affected by the rule (Maximum of 50) + */ + std::vector exempt_channels; + + /** + * @brief Construct a new automod rule object + */ + automod_rule(); + + /** + * @brief Destroy the automod rule object + */ + virtual ~automod_rule(); + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return automod_rule& Reference to self + */ + automod_rule& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** A group of automod rules. + */ +typedef std::unordered_map automod_rule_map; + +}; diff --git a/3rdParty/dpp/ban.h b/3rdParty/dpp/ban.h index 5695bc74a6..ea35ca4782 100644 --- a/3rdParty/dpp/ban.h +++ b/3rdParty/dpp/ban.h @@ -1,67 +1,67 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief The ban class represents a ban on a guild. - * - */ -class DPP_EXPORT ban : public json_interface { -public: - /** The ban reason */ - std::string reason; - /** User ID the ban applies to */ - snowflake user_id; - - /** Constructor */ - ban(); - - /** Destructor */ - virtual ~ban() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - ban& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json representation of a ban - * @param with_id Include ID in json - * - * @return std::string stringified json - */ - std::string build_json(bool with_id = false) const; -}; - -/** A group of bans - */ -typedef std::unordered_map ban_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief The ban class represents a ban on a guild. + * + */ +class DPP_EXPORT ban : public json_interface { +public: + /** The ban reason */ + std::string reason; + /** User ID the ban applies to */ + snowflake user_id; + + /** Constructor */ + ban(); + + /** Destructor */ + virtual ~ban() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + ban& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json representation of a ban + * @param with_id Include ID in json + * + * @return std::string stringified json + */ + std::string build_json(bool with_id = false) const; +}; + +/** A group of bans + */ +typedef std::unordered_map ban_map; + +}; diff --git a/3rdParty/dpp/cache.h b/3rdParty/dpp/cache.h index 59b3b4e77d..7997e8d75a 100644 --- a/3rdParty/dpp/cache.h +++ b/3rdParty/dpp/cache.h @@ -1,272 +1,272 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -extern DPP_EXPORT std::unordered_map deletion_queue; -extern DPP_EXPORT std::mutex deletion_mutex; - -/** forward declaration */ -class guild_member; - -/** - * @brief A cache object maintains a cache of dpp::managed objects. - * - * This is for example users, channels or guilds. You may instantiate - * your own caches, to contain any type derived from dpp::managed including - * your own types. - * - * @note This class is critical to the operation of the library and therefore - * designed with thread safety in mind. - * @tparam T class type to store, which should be derived from dpp::managed. - */ -template class cache { -private: - /** - * @brief Mutex to protect the cache - * - * This is a shared mutex so reading is cheap. - */ - std::shared_mutex cache_mutex; - - /** - * @brief Container of pointers to cached items - */ - std::unordered_map* cache_map; -public: - - /** - * @brief Construct a new cache object. - * - * Caches must contain classes derived from dpp::managed. - */ - cache() { - cache_map = new std::unordered_map; - } - - /** - * @brief Destroy the cache object - * - * @note This does not delete objects stored in the cache. - */ - ~cache() { - std::unique_lock l(cache_mutex); - delete cache_map; - } - - /** - * @brief Store an object in the cache. Passing a nullptr will have no effect. - * - * The object must be derived from dpp::managed and should be allocated on the heap. - * Generally this is done via `new`. Once stored in the cache the lifetime of the stored - * object is managed by the cache class unless the cache is deleted (at which point responsibility - * for deleting the object returns to its allocator). Objects stored are removed when the - * cache::remove() method is called by placing them into a garbage collection queue for deletion - * within the next 60 seconds, which are then deleted in bulk for efficiency and to aid thread - * safety. - * - * @note Adding an object to the cache with an ID which already exists replaces that entry. - * The previously entered cache item is inserted into the garbage collection queue for deletion - * similarly to if cache::remove() was called first. - * - * @param object object to store. Storing a pointer to the cache relinquishes ownership to the cache object. - */ - void store(T* object) { - if (!object) { - return; - } - std::unique_lock l(cache_mutex); - auto existing = cache_map->find(object->id); - if (existing == cache_map->end()) { - (*cache_map)[object->id] = object; - } else if (object != existing->second) { - /* Flag old pointer for deletion and replace */ - std::lock_guard delete_lock(deletion_mutex); - deletion_queue[existing->second] = time(NULL); - (*cache_map)[object->id] = object; - } - } - - /** - * @brief Remove an object from the cache. - * - * @note The cache class takes ownership of the pointer, and calling this method will - * cause deletion of the object within the next 60 seconds by means of a garbage - * collection queue. This queue aids in efficiency by freeing memory in bulk, and - * assists in thread safety by ensuring that all deletions can be locked and freed - * at the same time. - * - * @param object object to remove. Passing a nullptr will have no effect. - */ - void remove(T* object) { - if (!object) { - return; - } - std::unique_lock l(cache_mutex); - std::lock_guard delete_lock(deletion_mutex); - auto existing = cache_map->find(object->id); - if (existing != cache_map->end()) { - cache_map->erase(existing); - deletion_queue[object] = time(NULL); - } - } - - /** - * @brief Find an object in the cache by id. - * - * The cache is searched for the object. All dpp::managed objects have a snowflake id - * (this is the only field dpp::managed actually has). - * - * @warning Do not hang onto objects returned by cache::find() indefinitely. They may be - * deleted at a later date if cache::remove() is called. If persistence is required, - * take a copy of the object after checking its pointer is non-null. - * - * @param id Object snowflake id to find - * @return Found object or nullptr if the object with this id does not exist. - */ - T* find(snowflake id) { - std::shared_lock l(cache_mutex); - auto r = cache_map->find(id); - if (r != cache_map->end()) { - return r->second; - } - return nullptr; - } - - /** - * @brief Return a count of the number of items in the cache. - * - * This is used by the library e.g. to count guilds, users, and roles - * stored within caches. - * get - * @return uint64_t count of items in the cache - */ - uint64_t count() { - std::shared_lock l(cache_mutex); - return cache_map->size(); - } - - /** - * @brief Return the cache's locking mutex. - * - * Use this whenever you manipulate or iterate raw elements in the cache! - * - * @note If you are only reading from the cache's container, wrap this - * mutex in `std::shared_lock`, else wrap it in a `std::unique_lock`. - * Shared locks will allow for multiple readers whilst blocking writers, - * and unique locks will allow only one writer whilst blocking readers - * and writers. - * - * **Example:** - * - * ```cpp - * dpp::cache* c = dpp::get_guild_cache(); - * std::unordered_map& gc = c->get_container(); - * std::shared_lock l(c->get_mutex()); // MUST LOCK HERE - * for (auto g = gc.begin(); g != gc.end(); ++g) { - * dpp::guild* gp = (dpp::guild*)g->second; - * // Do something here with the guild* in 'gp' - * } - * ``` - * - * @return The mutex used to protect the container - */ - std::shared_mutex& get_mutex() { - return this->cache_mutex; - } - - /** - * @brief Get the container unordered map - * - * @warning Be sure to use cache::get_mutex() correctly if you - * manipulate or iterate the map returned by this method! If you do - * not, this is not thread safe and will cause crashes! - * - * @see cache::get_mutex - * - * @return A reference to the cache's container map - */ - auto & get_container() { - return *(this->cache_map); - } - - /** - * @brief "Rehash" a cache by reallocating the map and copying - * all elements into the new one. - * - * Over a long running timeframe, unordered maps can grow in size - * due to bucket allocation, this function frees that unused memory - * to keep the maps in control over time. If this is an issue which - * is apparent with your use of dpp::cache objects, you should periodically - * call this method. - * - * @warning May be time consuming! This function is O(n) in relation to the - * number of cached entries. - */ - void rehash() { - std::unique_lock l(cache_mutex); - std::unordered_map* n = new std::unordered_map; - n->reserve(cache_map->size()); - for (auto t = cache_map->begin(); t != cache_map->end(); ++t) { - n->insert(*t); - } - delete cache_map; - cache_map = n; - } - - /** - * @brief Get "real" size in RAM of the cached objects - * - * This does not include metadata used to maintain the unordered map itself. - * - * @return size_t size of cache in bytes - */ - size_t bytes() { - std::shared_lock l(cache_mutex); - return sizeof(this) + (cache_map->bucket_count() * sizeof(size_t)); - } - -}; - -/** Run garbage collection across all caches removing deleted items - * that have been deleted over 60 seconds ago. - */ -void DPP_EXPORT garbage_collection(); - -#define cache_decl(type, setter, getter, counter) DPP_EXPORT class type * setter (snowflake id); DPP_EXPORT cache * getter (); DPP_EXPORT uint64_t counter (); - -/* Declare major caches */ -cache_decl(user, find_user, get_user_cache, get_user_count); -cache_decl(guild, find_guild, get_guild_cache, get_guild_count); -cache_decl(role, find_role, get_role_cache, get_role_count); -cache_decl(channel, find_channel, get_channel_cache, get_channel_count); -cache_decl(emoji, find_emoji, get_emoji_cache, get_emoji_count); - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +extern DPP_EXPORT std::unordered_map deletion_queue; +extern DPP_EXPORT std::mutex deletion_mutex; + +/** forward declaration */ +class guild_member; + +/** + * @brief A cache object maintains a cache of dpp::managed objects. + * + * This is for example users, channels or guilds. You may instantiate + * your own caches, to contain any type derived from dpp::managed including + * your own types. + * + * @note This class is critical to the operation of the library and therefore + * designed with thread safety in mind. + * @tparam T class type to store, which should be derived from dpp::managed. + */ +template class cache { +private: + /** + * @brief Mutex to protect the cache + * + * This is a shared mutex so reading is cheap. + */ + std::shared_mutex cache_mutex; + + /** + * @brief Container of pointers to cached items + */ + std::unordered_map* cache_map; +public: + + /** + * @brief Construct a new cache object. + * + * Caches must contain classes derived from dpp::managed. + */ + cache() { + cache_map = new std::unordered_map; + } + + /** + * @brief Destroy the cache object + * + * @note This does not delete objects stored in the cache. + */ + ~cache() { + std::unique_lock l(cache_mutex); + delete cache_map; + } + + /** + * @brief Store an object in the cache. Passing a nullptr will have no effect. + * + * The object must be derived from dpp::managed and should be allocated on the heap. + * Generally this is done via `new`. Once stored in the cache the lifetime of the stored + * object is managed by the cache class unless the cache is deleted (at which point responsibility + * for deleting the object returns to its allocator). Objects stored are removed when the + * cache::remove() method is called by placing them into a garbage collection queue for deletion + * within the next 60 seconds, which are then deleted in bulk for efficiency and to aid thread + * safety. + * + * @note Adding an object to the cache with an ID which already exists replaces that entry. + * The previously entered cache item is inserted into the garbage collection queue for deletion + * similarly to if cache::remove() was called first. + * + * @param object object to store. Storing a pointer to the cache relinquishes ownership to the cache object. + */ + void store(T* object) { + if (!object) { + return; + } + std::unique_lock l(cache_mutex); + auto existing = cache_map->find(object->id); + if (existing == cache_map->end()) { + (*cache_map)[object->id] = object; + } else if (object != existing->second) { + /* Flag old pointer for deletion and replace */ + std::lock_guard delete_lock(deletion_mutex); + deletion_queue[existing->second] = time(NULL); + (*cache_map)[object->id] = object; + } + } + + /** + * @brief Remove an object from the cache. + * + * @note The cache class takes ownership of the pointer, and calling this method will + * cause deletion of the object within the next 60 seconds by means of a garbage + * collection queue. This queue aids in efficiency by freeing memory in bulk, and + * assists in thread safety by ensuring that all deletions can be locked and freed + * at the same time. + * + * @param object object to remove. Passing a nullptr will have no effect. + */ + void remove(T* object) { + if (!object) { + return; + } + std::unique_lock l(cache_mutex); + std::lock_guard delete_lock(deletion_mutex); + auto existing = cache_map->find(object->id); + if (existing != cache_map->end()) { + cache_map->erase(existing); + deletion_queue[object] = time(NULL); + } + } + + /** + * @brief Find an object in the cache by id. + * + * The cache is searched for the object. All dpp::managed objects have a snowflake id + * (this is the only field dpp::managed actually has). + * + * @warning Do not hang onto objects returned by cache::find() indefinitely. They may be + * deleted at a later date if cache::remove() is called. If persistence is required, + * take a copy of the object after checking its pointer is non-null. + * + * @param id Object snowflake id to find + * @return Found object or nullptr if the object with this id does not exist. + */ + T* find(snowflake id) { + std::shared_lock l(cache_mutex); + auto r = cache_map->find(id); + if (r != cache_map->end()) { + return r->second; + } + return nullptr; + } + + /** + * @brief Return a count of the number of items in the cache. + * + * This is used by the library e.g. to count guilds, users, and roles + * stored within caches. + * get + * @return uint64_t count of items in the cache + */ + uint64_t count() { + std::shared_lock l(cache_mutex); + return cache_map->size(); + } + + /** + * @brief Return the cache's locking mutex. + * + * Use this whenever you manipulate or iterate raw elements in the cache! + * + * @note If you are only reading from the cache's container, wrap this + * mutex in `std::shared_lock`, else wrap it in a `std::unique_lock`. + * Shared locks will allow for multiple readers whilst blocking writers, + * and unique locks will allow only one writer whilst blocking readers + * and writers. + * + * **Example:** + * + * ```cpp + * dpp::cache* c = dpp::get_guild_cache(); + * std::unordered_map& gc = c->get_container(); + * std::shared_lock l(c->get_mutex()); // MUST LOCK HERE + * for (auto g = gc.begin(); g != gc.end(); ++g) { + * dpp::guild* gp = (dpp::guild*)g->second; + * // Do something here with the guild* in 'gp' + * } + * ``` + * + * @return The mutex used to protect the container + */ + std::shared_mutex& get_mutex() { + return this->cache_mutex; + } + + /** + * @brief Get the container unordered map + * + * @warning Be sure to use cache::get_mutex() correctly if you + * manipulate or iterate the map returned by this method! If you do + * not, this is not thread safe and will cause crashes! + * + * @see cache::get_mutex + * + * @return A reference to the cache's container map + */ + auto & get_container() { + return *(this->cache_map); + } + + /** + * @brief "Rehash" a cache by reallocating the map and copying + * all elements into the new one. + * + * Over a long running timeframe, unordered maps can grow in size + * due to bucket allocation, this function frees that unused memory + * to keep the maps in control over time. If this is an issue which + * is apparent with your use of dpp::cache objects, you should periodically + * call this method. + * + * @warning May be time consuming! This function is O(n) in relation to the + * number of cached entries. + */ + void rehash() { + std::unique_lock l(cache_mutex); + std::unordered_map* n = new std::unordered_map; + n->reserve(cache_map->size()); + for (auto t = cache_map->begin(); t != cache_map->end(); ++t) { + n->insert(*t); + } + delete cache_map; + cache_map = n; + } + + /** + * @brief Get "real" size in RAM of the cached objects + * + * This does not include metadata used to maintain the unordered map itself. + * + * @return size_t size of cache in bytes + */ + size_t bytes() { + std::shared_lock l(cache_mutex); + return sizeof(this) + (cache_map->bucket_count() * sizeof(size_t)); + } + +}; + +/** Run garbage collection across all caches removing deleted items + * that have been deleted over 60 seconds ago. + */ +void DPP_EXPORT garbage_collection(); + +#define cache_decl(type, setter, getter, counter) DPP_EXPORT class type * setter (snowflake id); DPP_EXPORT cache * getter (); DPP_EXPORT uint64_t counter (); + +/* Declare major caches */ +cache_decl(user, find_user, get_user_cache, get_user_count); +cache_decl(guild, find_guild, get_guild_cache, get_guild_count); +cache_decl(role, find_role, get_role_cache, get_role_count); +cache_decl(channel, find_channel, get_channel_cache, get_channel_count); +cache_decl(emoji, find_emoji, get_emoji_cache, get_emoji_count); + +}; + diff --git a/3rdParty/dpp/channel.h b/3rdParty/dpp/channel.h index 8c72dcaed9..4ce396261e 100644 --- a/3rdParty/dpp/channel.h +++ b/3rdParty/dpp/channel.h @@ -1,803 +1,803 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** @brief Flag integers as received from and sent to discord */ -enum channel_type : uint8_t { - CHANNEL_TEXT = 0, //!< a text channel within a server - DM = 1, //!< a direct message between users - CHANNEL_VOICE = 2, //!< a voice channel within a server - /** - * @brief a direct message between multiple users - * @deprecated this channel type was intended to be used with the now deprecated GameBridge SDK. Existing group dms with bots will continue to function, but newly created channels will be unusable - */ - GROUP_DM = 3, - CHANNEL_CATEGORY = 4, //!< an organizational category that contains up to 50 channels - CHANNEL_ANNOUNCEMENT = 5, //!< a channel that users can follow and crosspost into their own server - /** - * @brief a channel in which game developers can sell their game on Discord - * @deprecated store channels are deprecated by Discord - */ - CHANNEL_STORE = 6, - CHANNEL_ANNOUNCEMENT_THREAD = 10, //!< a temporary sub-channel within a GUILD_ANNOUNCEMENT channel - CHANNEL_PUBLIC_THREAD = 11, //!< a temporary sub-channel within a GUILD_TEXT or GUILD_FORUM channel - CHANNEL_PRIVATE_THREAD = 12, //!< a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission - CHANNEL_STAGE = 13, //!< a "stage" channel, like a voice channel with one authorised speaker - CHANNEL_DIRECTORY = 14, //!< the channel in a [hub](https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ) containing the listed servers - CHANNEL_FORUM = 15 //!< forum channel that can only contain threads -}; - -/** @brief Our flags as stored in the object - * @note The bottom four bits of this flag are reserved to contain the channel_type values - * listed above as provided by Discord. If discord add another value > 15, we will have to - * shuffle these values upwards by one bit. - */ -enum channel_flags : uint16_t { - /// NSFW Gated Channel - c_nsfw = 0b0000000000010000, - /// Video quality forced to 720p - c_video_quality_720p = 0b0000000000100000, - /// Lock permissions (only used when updating channel positions) - c_lock_permissions = 0b0000000001000000, - /// Thread is pinned to the top of its parent forum channel - c_pinned_thread = 0b0000000010000000, - /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. - c_require_tag = 0b0000000100000000, - /* Note that the 9th and 10th bit are used for the forum layout type */ -}; - -/** - * @brief The flags in discord channel's raw "flags" field. We use these for serialisation only, right now. Might be better to create a new field than to make the existing channel::flags from uint8_t to uint16_t, if discord adds more flags in future. - */ -enum discord_channel_flags : uint8_t { - /// Thread is pinned to the top of its parent forum channel - dc_pinned_thread = 1 << 1, - /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. - dc_require_tag = 1 << 4, -}; - -/** - * @brief Types for sort posts in a forum channel - */ -enum default_forum_sort_order_t : uint8_t { - /// Sort forum posts by activity (default) - so_latest_activity = 0, - /// Sort forum posts by creation time (from most recent to oldest) - so_creation_date = 1, -}; - -/** - * @brief Types of forum layout views that indicates how the threads in a forum channel will be displayed for users by default - */ -enum forum_layout_type : uint8_t { - fl_not_set = 0, //!< No default has been set for the forum channel - fl_list_view = 1, //!< Display posts as a list - fl_gallery_view = 2, //!< Display posts as a collection of tiles -}; - -/** - * @brief channel permission overwrite types - */ -enum overwrite_type : uint8_t { - /// Role - ot_role = 0, - /// Member - ot_member = 1 -}; - -/** - * @brief Channel permission overwrites - */ -struct DPP_EXPORT permission_overwrite { - /// ID of the role or the member - snowflake id; - /// Bitmask of allowed permissions - permission allow; - /// Bitmask of denied permissions - permission deny; - /// Type of overwrite. See dpp::overwrite_type - uint8_t type; - - /** - * @brief Construct a new permission_overwrite object - */ - permission_overwrite(); - - /** - * @brief Construct a new permission_overwrite object - * @param id ID of the role or the member to create the overwrite for - * @param allow Bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel - * @param deny Bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel - * @param type Type of overwrite - */ - permission_overwrite(snowflake id, uint64_t allow, uint64_t deny, overwrite_type type); -}; - - -/** - * @brief metadata for threads - */ -struct DPP_EXPORT thread_metadata { - /// Timestamp when the thread's archive status was last changed, used for calculating recent activity - time_t archive_timestamp; - /// The duration in minutes to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 - uint16_t auto_archive_duration; - /// Whether a thread is archived - bool archived; - /// Whether a thread is locked. When a thread is locked, only users with `MANAGE_THREADS` can unarchive it - bool locked; - /// Whether non-moderators can add other non-moderators. Only for private threads - bool invitable; -}; - -/** - * @brief Auto archive duration of threads which will stop showing in the channel list after the specified period of inactivity. - * Defined as an enum to fit into 1 byte. Internally it'll be translated to minutes to match the API - */ -enum auto_archive_duration_t : uint8_t { - /// Auto archive duration of 1 hour. (60 minutes) - arc_1_hour = 1, - /// Auto archive duration of 1 day. (1440 minutes) - arc_1_day = 2, - /// Auto archive duration of 3 days. (4320 minutes) - arc_3_days = 3, - /// Auto archive duration of 1 week. (10080 minutes) - arc_1_week = 4, -}; - -/** - * @brief represents membership of a user with a thread - */ -struct DPP_EXPORT thread_member -{ - /// ID of the thread member is part of - snowflake thread_id; - /// ID of the member - snowflake user_id; - /// The time when user last joined the thread - time_t joined; - /// Any user-thread settings, currently only used for notifications - uint32_t flags; - - /** - * @brief Read struct values from a json object - * @param j json to read values from - * @return A reference to self - */ - thread_member& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief Represents a tag that is able to be applied to a thread in a forum channel - */ -struct DPP_EXPORT forum_tag : public managed { - /** The name of the tag (0-20 characters) */ - std::string name; - /** The emoji of the tag. Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji */ - std::variant emoji; - /** Whether this tag can only be added to or removed from threads by a member with the `MANAGE_THREADS` permission */ - bool moderated; - - /** Constructor */ - forum_tag(); - - /** - * @brief Constructor - * - * @param name The name of the tag. It will be truncated to the maximum length of 20 UTF-8 characters. - */ - forum_tag(const std::string& name); - - /** Destructor */ - virtual ~forum_tag(); - - /** - * @brief Read struct values from a json object - * @param j json to read values from - * @return A reference to self - */ - forum_tag& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json for this forum_tag object - * - * @param with_id include the ID in the json - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Set name of this forum_tag object - * - * @param name Name to set - * @return Reference to self, so these method calls may be chained - * - * @note name will be truncated to 20 chars, if longer - */ - forum_tag& set_name(const std::string& name); -}; - -/** @brief A group of thread member objects*/ -typedef std::unordered_map thread_member_map; - -/** - * @brief A definition of a discord channel. - * There are one of these for every channel type except threads. Threads are - * special snowflakes. Get it? A Discord pun. Hahaha. .... I'll get my coat. - */ -class DPP_EXPORT channel : public managed, public json_interface { -public: - /** Channel name (1-100 characters) */ - std::string name; - - /** Channel topic (0-4096 characters for forum channels, 0-1024 characters for all others) */ - std::string topic; - - /** - * @brief Voice region if set for voice channel, otherwise empty string - */ - std::string rtc_region; - - /** DM recipients */ - std::vector recipients; - - /** Permission overwrites to apply to base permissions */ - std::vector permission_overwrites; - - /** A set of tags that can be used in a forum channel */ - std::vector available_tags; - - /** - * @brief The emoji to show as the default reaction button on a forum post. - * Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji - */ - std::variant default_reaction; - - /** - * @brief Channel icon (for group DMs) - */ - utility::iconhash icon; - - /** User ID of the creator for group DMs or threads */ - snowflake owner_id; - - /** Parent ID (for guild channels: id of the parent category, for threads: id of the text channel this thread was created) */ - snowflake parent_id; - - /** Guild id of the guild that owns the channel */ - snowflake guild_id; - - /** ID of last message to be sent to the channel (may not point to an existing or valid message or thread) */ - snowflake last_message_id; - - /** Timestamp of last pinned message */ - time_t last_pin_timestamp; - - /** - * @brief This is only filled when the channel is part of the `resolved` set - * sent within an interaction. Any other time it contains zero. When filled, - * it contains the calculated permission bitmask of the user issuing the command - * within this channel. - */ - permission permissions; - - /** Sorting position, lower number means higher up the list */ - uint16_t position; - - /** the bitrate (in kilobits) of the voice channel */ - uint16_t bitrate; - - /** amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages or manage_channel, are unaffected*/ - uint16_t rate_limit_per_user; - - /** The initial `rate_limit_per_user` to set on newly created threads in a channel. This field is copied to the thread at creation time and does not live update */ - uint16_t default_thread_rate_limit_per_user; - - /** - * @brief Default duration, copied onto newly created threads. Used by the clients, not the API. - * Threads will stop showing in the channel list after the specified period of inactivity. Defaults to dpp::arc_1_day - */ - auto_archive_duration_t default_auto_archive_duration; - - /** the default sort order type used to order posts in forum channels */ - default_forum_sort_order_t default_sort_order; - - /** Flags bitmap (dpp::channel_flags) */ - uint16_t flags; - - /** Maximum user limit for voice channels (0-99) */ - uint8_t user_limit; - - /** Constructor */ - channel(); - - /** Destructor */ - virtual ~channel(); - - /** - * @brief Create a mentionable channel. - * @param id The ID of the channel. - * @return std::string The formatted mention of the channel. - */ - static std::string get_mention(const snowflake& id); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - channel& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json for this channel object - * - * @param with_id include the ID in the json - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Set name of this channel object - * - * @param name Name to set - * @return Reference to self, so these method calls may be chained - * - * @note name will be truncated to 100 chars, if longer - * @throw dpp::length_exception if length < 1 - */ - channel& set_name(const std::string& name); - - /** - * @brief Set topic of this channel object - * - * @param topic Topic to set - * @return Reference to self, so these method calls may be chained - * - * @note topic will be truncated to 1024 chars, if longer - */ - channel& set_topic(const std::string& topic); - - /** - * @brief Set type of this channel object - * - * @param type Channel type to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_type(channel_type type); - - /** - * @brief Set the default forum layout type for the forum channel - * - * @param layout_type The layout type - * @return Reference to self, so these method calls may be chained - */ - channel& set_default_forum_layout(forum_layout_type layout_type); - - /** - * @brief Set flags for this channel object - * - * @param flags Flag bitmask to set from dpp::channel_flags - * @return Reference to self, so these method calls may be chained - */ - channel& set_flags(const uint16_t flags); - - /** - * @brief Add (bitwise OR) a flag to this channel object - * - * @param flag Flag bit to add from dpp::channel_flags - * @return Reference to self, so these method calls may be chained - */ - channel& add_flag(const channel_flags flag); - - /** - * @brief Remove (bitwise NOT AND) a flag from this channel object - * - * @param flag Flag bit to remove from dpp::channel_flags - * @return Reference to self, so these method calls may be chained - */ - channel& remove_flag(const channel_flags flag); - - /** - * @brief Set position of this channel object - * - * @param position Position to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_position(const uint16_t position); - - /** - * @brief Set guild_id of this channel object - * - * @param guild_id Guild ID to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_guild_id(const snowflake guild_id); - - /** - * @brief Set parent_id of this channel object - * - * @param parent_id Parent ID to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_parent_id(const snowflake parent_id); - - /** - * @brief Set user_limit of this channel object - * - * @param user_limit Limit to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_user_limit(const uint8_t user_limit); - - /** - * @brief Set bitrate of this channel object - * - * @param bitrate Bitrate to set (in kilobits) - * @return Reference to self, so these method calls may be chained - */ - channel& set_bitrate(const uint16_t bitrate); - - /** - * @brief Set nsfw property of this channel object - * - * @param is_nsfw true, if channel is nsfw - * @return Reference to self, so these method calls may be chained - */ - channel& set_nsfw(const bool is_nsfw); - - /** - * @brief Set lock permissions property of this channel object - * Used only with the reorder channels method - * - * @param is_lock_permissions true, if we are to inherit permissions from the category - * @return Reference to self, so these method calls may be chained - */ - channel& set_lock_permissions(const bool is_lock_permissions); - - /** - * @brief Set rate_limit_per_user of this channel object - * - * @param rate_limit_per_user rate_limit_per_user (slowmode in sec) to set - * @return Reference to self, so these method calls may be chained - */ - channel& set_rate_limit_per_user(const uint16_t rate_limit_per_user); - - /** - * @brief Add a permission_overwrite to this channel object - * - * @param id ID of the role or the member you want to add overwrite for - * @param type type of overwrite - * @param allowed_permissions bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel - * @param denied_permissions bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel - * - * @return Reference to self, so these method calls may be chained - */ - channel& add_permission_overwrite(const snowflake id, const overwrite_type type, const uint64_t allowed_permissions, const uint64_t denied_permissions); - - /** - * @brief Get the channel type - * - * @return channel_type Channel type - */ - channel_type get_type() const; - - /** - * @brief Get the default forum layout type used to display posts in forum channels - * - * @return forum_layout_types Forum layout type - */ - forum_layout_type get_default_forum_layout() const; - - /** - * @brief Get the mention ping for the channel - * - * @return std::string mention - */ - std::string get_mention() const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param user The user to resolve the permissions for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - * - * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, - * so consider using guild::permission_overwrites if you already have the guild object. - * - * @warning The method will search for the guild member in the cache by the users id. - * If the guild member is not in cache, the method will always return 0. - */ - permission get_user_permissions(const class user* user) const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param member The member to resolve the permissions for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - * - * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, - * so consider using guild::permission_overwrites if you already have the guild object. - */ - permission get_user_permissions(const class guild_member &member) const; - - /** - * @brief Return a map of members on the channel, built from the guild's - * member list based on which members have the VIEW_CHANNEL permission. - * Does not return reliable information for voice channels, use - * dpp::channel::get_voice_members() instead for this. - * @return A map of guild members keyed by user id. - * @note If the guild this channel belongs to is not in the cache, the function will always return 0. - */ - std::map get_members(); - - /** - * @brief Get a map of members in this channel, if it is a voice channel. - * The map is keyed by snowflake id of the user. - * - * @return std::map The voice members of the channel - */ - std::map get_voice_members(); - - /** - * @brief Get the channel's icon url (if its a group DM), otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; - - /** - * @brief Returns true if the channel is NSFW gated - * - * @return true if NSFW - */ - bool is_nsfw() const; - - /** - * @brief Returns true if the permissions are to be synced with the category it is in. - * Used only and set manually when using the reorder channels method. - * - * @return true if keeping permissions - */ - bool is_locked_permissions() const; - - /** - * @brief Returns true if the channel is a text channel - * - * @return true if text channel - */ - bool is_text_channel() const; - - /** - * @brief Returns true if the channel is a DM - * - * @return true if is a DM - */ - bool is_dm() const; - - /** - * @brief Returns true if the channel is a voice channel - * - * @return true if voice channel - */ - bool is_voice_channel() const; - - /** - * @brief Returns true if the channel is a group DM channel - * - * @return true if group DM - */ - bool is_group_dm() const; - - /** - * @brief Returns true if the channel is a category - * - * @return true if a category - */ - bool is_category() const; - - /** - * @brief Returns true if the channel is a forum - * - * @return true if a forum - */ - bool is_forum() const; - - /** - * @brief Returns true if the channel is an announcement channel - * - * @return true if announcement channel - */ - bool is_news_channel() const; - - /** - * @brief Returns true if the channel is a store channel - * @deprecated store channels are deprecated by Discord - * - * @return true if store channel - */ - bool is_store_channel() const; - - /** - * @brief Returns true if the channel is a stage channel - * - * @return true if stage channel - */ - bool is_stage_channel() const; - - /** - * @brief Returns true if video quality is auto - * - * @return true if video quality is auto - */ - bool is_video_auto() const; - - /** - * @brief Returns true if video quality is 720p - * - * @return true if video quality is 720p - */ - bool is_video_720p() const; - - /** - * @brief Returns true if channel is a pinned thread in forum - * - * @return true, if channel is a pinned thread in forum - */ - bool is_pinned_thread() const; - - /** - * @brief Returns true if a tag is required to be specified when creating a thread in a forum channel - * - * @return true, if a tag is required to be specified when creating a thread in a forum channel - */ - bool is_tag_required() const; - -}; - -/** @brief A definition of a discord thread. - * A thread is a superset of a channel. Not to be confused with `std::thread`! - */ -class DPP_EXPORT thread : public channel { -public: - /** - * @brief Thread member of current user if joined to the thread. - * Note this is only set by certain api calls otherwise contains default data - */ - thread_member member; - - /** Thread metadata (threads) */ - thread_metadata metadata; - - /** Created message. Only filled within the cluster::thread_create_in_forum() method */ - message msg; - - /** - * A list of dpp::forum_tag IDs that have been applied to a thread in a forum channel - */ - std::vector applied_tags; - - /** - * @brief Number of messages ever sent in the thread. - * It's similar to thread::message_count on message creation, but will not decrement the number when a message is deleted - */ - uint32_t total_messages_sent; - - /** - * @brief Number of messages (not including the initial message or deleted messages) of the thread. - * For threads created before July 1, 2022, the message count is inaccurate when it's greater than 50. - */ - uint8_t message_count; - - /** Approximate count of members in a thread (threads) */ - uint8_t member_count; - - /** - * @brief Construct a new thread object - */ - thread(); - - /** - * @brief Returns true if the thread is within an announcement channel - * - * @return true if announcement thread - */ - bool is_news_thread() const; - - /** - * @brief Returns true if the channel is a public thread - * - * @return true if public thread - */ - bool is_public_thread() const; - - /** - * @brief Returns true if the channel is a private thread - * - * @return true if private thread - */ - bool is_private_thread() const; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - thread& fill_from_json(nlohmann::json* j); - - /** - * @brief Destroy the thread object - */ - virtual ~thread(); - - /** - * @brief Build json for this thread object - * - * @param with_id include the ID in the json - * @return std::string JSON string - */ - std::string build_json(bool with_id = false) const; - -}; - - -/** - * @brief Serialize a thread_metadata object to json - * - * @param j JSON object to serialize to - * @param tmdata object to serialize - */ -void to_json(nlohmann::json& j, const thread_metadata& tmdata); - -/** - * @brief Serialize a permission_overwrite object to json - * - * @param j JSON object to serialize to - * @param po object to serialize - */ -void to_json(nlohmann::json& j, const permission_overwrite& po); - -/** - * @brief A group of channels - */ -typedef std::unordered_map channel_map; - -/** - * @brief A group of threads - */ -typedef std::unordered_map thread_map; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** @brief Flag integers as received from and sent to discord */ +enum channel_type : uint8_t { + CHANNEL_TEXT = 0, //!< a text channel within a server + DM = 1, //!< a direct message between users + CHANNEL_VOICE = 2, //!< a voice channel within a server + /** + * @brief a direct message between multiple users + * @deprecated this channel type was intended to be used with the now deprecated GameBridge SDK. Existing group dms with bots will continue to function, but newly created channels will be unusable + */ + GROUP_DM = 3, + CHANNEL_CATEGORY = 4, //!< an organizational category that contains up to 50 channels + CHANNEL_ANNOUNCEMENT = 5, //!< a channel that users can follow and crosspost into their own server + /** + * @brief a channel in which game developers can sell their game on Discord + * @deprecated store channels are deprecated by Discord + */ + CHANNEL_STORE = 6, + CHANNEL_ANNOUNCEMENT_THREAD = 10, //!< a temporary sub-channel within a GUILD_ANNOUNCEMENT channel + CHANNEL_PUBLIC_THREAD = 11, //!< a temporary sub-channel within a GUILD_TEXT or GUILD_FORUM channel + CHANNEL_PRIVATE_THREAD = 12, //!< a temporary sub-channel within a GUILD_TEXT channel that is only viewable by those invited and those with the MANAGE_THREADS permission + CHANNEL_STAGE = 13, //!< a "stage" channel, like a voice channel with one authorised speaker + CHANNEL_DIRECTORY = 14, //!< the channel in a [hub](https://support.discord.com/hc/en-us/articles/4406046651927-Discord-Student-Hubs-FAQ) containing the listed servers + CHANNEL_FORUM = 15 //!< forum channel that can only contain threads +}; + +/** @brief Our flags as stored in the object + * @note The bottom four bits of this flag are reserved to contain the channel_type values + * listed above as provided by Discord. If discord add another value > 15, we will have to + * shuffle these values upwards by one bit. + */ +enum channel_flags : uint16_t { + /// NSFW Gated Channel + c_nsfw = 0b0000000000010000, + /// Video quality forced to 720p + c_video_quality_720p = 0b0000000000100000, + /// Lock permissions (only used when updating channel positions) + c_lock_permissions = 0b0000000001000000, + /// Thread is pinned to the top of its parent forum channel + c_pinned_thread = 0b0000000010000000, + /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. + c_require_tag = 0b0000000100000000, + /* Note that the 9th and 10th bit are used for the forum layout type */ +}; + +/** + * @brief The flags in discord channel's raw "flags" field. We use these for serialisation only, right now. Might be better to create a new field than to make the existing channel::flags from uint8_t to uint16_t, if discord adds more flags in future. + */ +enum discord_channel_flags : uint8_t { + /// Thread is pinned to the top of its parent forum channel + dc_pinned_thread = 1 << 1, + /// Whether a tag is required to be specified when creating a thread in a forum channel. Tags are specified in the thread::applied_tags field. + dc_require_tag = 1 << 4, +}; + +/** + * @brief Types for sort posts in a forum channel + */ +enum default_forum_sort_order_t : uint8_t { + /// Sort forum posts by activity (default) + so_latest_activity = 0, + /// Sort forum posts by creation time (from most recent to oldest) + so_creation_date = 1, +}; + +/** + * @brief Types of forum layout views that indicates how the threads in a forum channel will be displayed for users by default + */ +enum forum_layout_type : uint8_t { + fl_not_set = 0, //!< No default has been set for the forum channel + fl_list_view = 1, //!< Display posts as a list + fl_gallery_view = 2, //!< Display posts as a collection of tiles +}; + +/** + * @brief channel permission overwrite types + */ +enum overwrite_type : uint8_t { + /// Role + ot_role = 0, + /// Member + ot_member = 1 +}; + +/** + * @brief Channel permission overwrites + */ +struct DPP_EXPORT permission_overwrite { + /// ID of the role or the member + snowflake id; + /// Bitmask of allowed permissions + permission allow; + /// Bitmask of denied permissions + permission deny; + /// Type of overwrite. See dpp::overwrite_type + uint8_t type; + + /** + * @brief Construct a new permission_overwrite object + */ + permission_overwrite(); + + /** + * @brief Construct a new permission_overwrite object + * @param id ID of the role or the member to create the overwrite for + * @param allow Bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel + * @param deny Bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel + * @param type Type of overwrite + */ + permission_overwrite(snowflake id, uint64_t allow, uint64_t deny, overwrite_type type); +}; + + +/** + * @brief metadata for threads + */ +struct DPP_EXPORT thread_metadata { + /// Timestamp when the thread's archive status was last changed, used for calculating recent activity + time_t archive_timestamp; + /// The duration in minutes to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080 + uint16_t auto_archive_duration; + /// Whether a thread is archived + bool archived; + /// Whether a thread is locked. When a thread is locked, only users with `MANAGE_THREADS` can unarchive it + bool locked; + /// Whether non-moderators can add other non-moderators. Only for private threads + bool invitable; +}; + +/** + * @brief Auto archive duration of threads which will stop showing in the channel list after the specified period of inactivity. + * Defined as an enum to fit into 1 byte. Internally it'll be translated to minutes to match the API + */ +enum auto_archive_duration_t : uint8_t { + /// Auto archive duration of 1 hour. (60 minutes) + arc_1_hour = 1, + /// Auto archive duration of 1 day. (1440 minutes) + arc_1_day = 2, + /// Auto archive duration of 3 days. (4320 minutes) + arc_3_days = 3, + /// Auto archive duration of 1 week. (10080 minutes) + arc_1_week = 4, +}; + +/** + * @brief represents membership of a user with a thread + */ +struct DPP_EXPORT thread_member +{ + /// ID of the thread member is part of + snowflake thread_id; + /// ID of the member + snowflake user_id; + /// The time when user last joined the thread + time_t joined; + /// Any user-thread settings, currently only used for notifications + uint32_t flags; + + /** + * @brief Read struct values from a json object + * @param j json to read values from + * @return A reference to self + */ + thread_member& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief Represents a tag that is able to be applied to a thread in a forum channel + */ +struct DPP_EXPORT forum_tag : public managed { + /** The name of the tag (0-20 characters) */ + std::string name; + /** The emoji of the tag. Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji */ + std::variant emoji; + /** Whether this tag can only be added to or removed from threads by a member with the `MANAGE_THREADS` permission */ + bool moderated; + + /** Constructor */ + forum_tag(); + + /** + * @brief Constructor + * + * @param name The name of the tag. It will be truncated to the maximum length of 20 UTF-8 characters. + */ + forum_tag(const std::string& name); + + /** Destructor */ + virtual ~forum_tag(); + + /** + * @brief Read struct values from a json object + * @param j json to read values from + * @return A reference to self + */ + forum_tag& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for this forum_tag object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Set name of this forum_tag object + * + * @param name Name to set + * @return Reference to self, so these method calls may be chained + * + * @note name will be truncated to 20 chars, if longer + */ + forum_tag& set_name(const std::string& name); +}; + +/** @brief A group of thread member objects*/ +typedef std::unordered_map thread_member_map; + +/** + * @brief A definition of a discord channel. + * There are one of these for every channel type except threads. Threads are + * special snowflakes. Get it? A Discord pun. Hahaha. .... I'll get my coat. + */ +class DPP_EXPORT channel : public managed, public json_interface { +public: + /** Channel name (1-100 characters) */ + std::string name; + + /** Channel topic (0-4096 characters for forum channels, 0-1024 characters for all others) */ + std::string topic; + + /** + * @brief Voice region if set for voice channel, otherwise empty string + */ + std::string rtc_region; + + /** DM recipients */ + std::vector recipients; + + /** Permission overwrites to apply to base permissions */ + std::vector permission_overwrites; + + /** A set of tags that can be used in a forum channel */ + std::vector available_tags; + + /** + * @brief The emoji to show as the default reaction button on a forum post. + * Contains either nothing, the id of a guild's custom emoji or the unicode character of the emoji + */ + std::variant default_reaction; + + /** + * @brief Channel icon (for group DMs) + */ + utility::iconhash icon; + + /** User ID of the creator for group DMs or threads */ + snowflake owner_id; + + /** Parent ID (for guild channels: id of the parent category, for threads: id of the text channel this thread was created) */ + snowflake parent_id; + + /** Guild id of the guild that owns the channel */ + snowflake guild_id; + + /** ID of last message to be sent to the channel (may not point to an existing or valid message or thread) */ + snowflake last_message_id; + + /** Timestamp of last pinned message */ + time_t last_pin_timestamp; + + /** + * @brief This is only filled when the channel is part of the `resolved` set + * sent within an interaction. Any other time it contains zero. When filled, + * it contains the calculated permission bitmask of the user issuing the command + * within this channel. + */ + permission permissions; + + /** Sorting position, lower number means higher up the list */ + uint16_t position; + + /** the bitrate (in kilobits) of the voice channel */ + uint16_t bitrate; + + /** amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages or manage_channel, are unaffected*/ + uint16_t rate_limit_per_user; + + /** The initial `rate_limit_per_user` to set on newly created threads in a channel. This field is copied to the thread at creation time and does not live update */ + uint16_t default_thread_rate_limit_per_user; + + /** + * @brief Default duration, copied onto newly created threads. Used by the clients, not the API. + * Threads will stop showing in the channel list after the specified period of inactivity. Defaults to dpp::arc_1_day + */ + auto_archive_duration_t default_auto_archive_duration; + + /** the default sort order type used to order posts in forum channels */ + default_forum_sort_order_t default_sort_order; + + /** Flags bitmap (dpp::channel_flags) */ + uint16_t flags; + + /** Maximum user limit for voice channels (0-99) */ + uint8_t user_limit; + + /** Constructor */ + channel(); + + /** Destructor */ + virtual ~channel(); + + /** + * @brief Create a mentionable channel. + * @param id The ID of the channel. + * @return std::string The formatted mention of the channel. + */ + static std::string get_mention(const snowflake& id); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + channel& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for this channel object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Set name of this channel object + * + * @param name Name to set + * @return Reference to self, so these method calls may be chained + * + * @note name will be truncated to 100 chars, if longer + * @throw dpp::length_exception if length < 1 + */ + channel& set_name(const std::string& name); + + /** + * @brief Set topic of this channel object + * + * @param topic Topic to set + * @return Reference to self, so these method calls may be chained + * + * @note topic will be truncated to 1024 chars, if longer + */ + channel& set_topic(const std::string& topic); + + /** + * @brief Set type of this channel object + * + * @param type Channel type to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_type(channel_type type); + + /** + * @brief Set the default forum layout type for the forum channel + * + * @param layout_type The layout type + * @return Reference to self, so these method calls may be chained + */ + channel& set_default_forum_layout(forum_layout_type layout_type); + + /** + * @brief Set flags for this channel object + * + * @param flags Flag bitmask to set from dpp::channel_flags + * @return Reference to self, so these method calls may be chained + */ + channel& set_flags(const uint16_t flags); + + /** + * @brief Add (bitwise OR) a flag to this channel object + * + * @param flag Flag bit to add from dpp::channel_flags + * @return Reference to self, so these method calls may be chained + */ + channel& add_flag(const channel_flags flag); + + /** + * @brief Remove (bitwise NOT AND) a flag from this channel object + * + * @param flag Flag bit to remove from dpp::channel_flags + * @return Reference to self, so these method calls may be chained + */ + channel& remove_flag(const channel_flags flag); + + /** + * @brief Set position of this channel object + * + * @param position Position to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_position(const uint16_t position); + + /** + * @brief Set guild_id of this channel object + * + * @param guild_id Guild ID to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_guild_id(const snowflake guild_id); + + /** + * @brief Set parent_id of this channel object + * + * @param parent_id Parent ID to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_parent_id(const snowflake parent_id); + + /** + * @brief Set user_limit of this channel object + * + * @param user_limit Limit to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_user_limit(const uint8_t user_limit); + + /** + * @brief Set bitrate of this channel object + * + * @param bitrate Bitrate to set (in kilobits) + * @return Reference to self, so these method calls may be chained + */ + channel& set_bitrate(const uint16_t bitrate); + + /** + * @brief Set nsfw property of this channel object + * + * @param is_nsfw true, if channel is nsfw + * @return Reference to self, so these method calls may be chained + */ + channel& set_nsfw(const bool is_nsfw); + + /** + * @brief Set lock permissions property of this channel object + * Used only with the reorder channels method + * + * @param is_lock_permissions true, if we are to inherit permissions from the category + * @return Reference to self, so these method calls may be chained + */ + channel& set_lock_permissions(const bool is_lock_permissions); + + /** + * @brief Set rate_limit_per_user of this channel object + * + * @param rate_limit_per_user rate_limit_per_user (slowmode in sec) to set + * @return Reference to self, so these method calls may be chained + */ + channel& set_rate_limit_per_user(const uint16_t rate_limit_per_user); + + /** + * @brief Add a permission_overwrite to this channel object + * + * @param id ID of the role or the member you want to add overwrite for + * @param type type of overwrite + * @param allowed_permissions bitmask of allowed permissions (refer to enum dpp::permissions) for this user/role in this channel + * @param denied_permissions bitmask of denied permissions (refer to enum dpp::permissions) for this user/role in this channel + * + * @return Reference to self, so these method calls may be chained + */ + channel& add_permission_overwrite(const snowflake id, const overwrite_type type, const uint64_t allowed_permissions, const uint64_t denied_permissions); + + /** + * @brief Get the channel type + * + * @return channel_type Channel type + */ + channel_type get_type() const; + + /** + * @brief Get the default forum layout type used to display posts in forum channels + * + * @return forum_layout_types Forum layout type + */ + forum_layout_type get_default_forum_layout() const; + + /** + * @brief Get the mention ping for the channel + * + * @return std::string mention + */ + std::string get_mention() const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param user The user to resolve the permissions for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + * + * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, + * so consider using guild::permission_overwrites if you already have the guild object. + * + * @warning The method will search for the guild member in the cache by the users id. + * If the guild member is not in cache, the method will always return 0. + */ + permission get_user_permissions(const class user* user) const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param member The member to resolve the permissions for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + * + * @note This is an alias for guild::permission_overwrites and searches for the guild in the cache, + * so consider using guild::permission_overwrites if you already have the guild object. + */ + permission get_user_permissions(const class guild_member &member) const; + + /** + * @brief Return a map of members on the channel, built from the guild's + * member list based on which members have the VIEW_CHANNEL permission. + * Does not return reliable information for voice channels, use + * dpp::channel::get_voice_members() instead for this. + * @return A map of guild members keyed by user id. + * @note If the guild this channel belongs to is not in the cache, the function will always return 0. + */ + std::map get_members(); + + /** + * @brief Get a map of members in this channel, if it is a voice channel. + * The map is keyed by snowflake id of the user. + * + * @return std::map The voice members of the channel + */ + std::map get_voice_members(); + + /** + * @brief Get the channel's icon url (if its a group DM), otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; + + /** + * @brief Returns true if the channel is NSFW gated + * + * @return true if NSFW + */ + bool is_nsfw() const; + + /** + * @brief Returns true if the permissions are to be synced with the category it is in. + * Used only and set manually when using the reorder channels method. + * + * @return true if keeping permissions + */ + bool is_locked_permissions() const; + + /** + * @brief Returns true if the channel is a text channel + * + * @return true if text channel + */ + bool is_text_channel() const; + + /** + * @brief Returns true if the channel is a DM + * + * @return true if is a DM + */ + bool is_dm() const; + + /** + * @brief Returns true if the channel is a voice channel + * + * @return true if voice channel + */ + bool is_voice_channel() const; + + /** + * @brief Returns true if the channel is a group DM channel + * + * @return true if group DM + */ + bool is_group_dm() const; + + /** + * @brief Returns true if the channel is a category + * + * @return true if a category + */ + bool is_category() const; + + /** + * @brief Returns true if the channel is a forum + * + * @return true if a forum + */ + bool is_forum() const; + + /** + * @brief Returns true if the channel is an announcement channel + * + * @return true if announcement channel + */ + bool is_news_channel() const; + + /** + * @brief Returns true if the channel is a store channel + * @deprecated store channels are deprecated by Discord + * + * @return true if store channel + */ + bool is_store_channel() const; + + /** + * @brief Returns true if the channel is a stage channel + * + * @return true if stage channel + */ + bool is_stage_channel() const; + + /** + * @brief Returns true if video quality is auto + * + * @return true if video quality is auto + */ + bool is_video_auto() const; + + /** + * @brief Returns true if video quality is 720p + * + * @return true if video quality is 720p + */ + bool is_video_720p() const; + + /** + * @brief Returns true if channel is a pinned thread in forum + * + * @return true, if channel is a pinned thread in forum + */ + bool is_pinned_thread() const; + + /** + * @brief Returns true if a tag is required to be specified when creating a thread in a forum channel + * + * @return true, if a tag is required to be specified when creating a thread in a forum channel + */ + bool is_tag_required() const; + +}; + +/** @brief A definition of a discord thread. + * A thread is a superset of a channel. Not to be confused with `std::thread`! + */ +class DPP_EXPORT thread : public channel { +public: + /** + * @brief Thread member of current user if joined to the thread. + * Note this is only set by certain api calls otherwise contains default data + */ + thread_member member; + + /** Thread metadata (threads) */ + thread_metadata metadata; + + /** Created message. Only filled within the cluster::thread_create_in_forum() method */ + message msg; + + /** + * A list of dpp::forum_tag IDs that have been applied to a thread in a forum channel + */ + std::vector applied_tags; + + /** + * @brief Number of messages ever sent in the thread. + * It's similar to thread::message_count on message creation, but will not decrement the number when a message is deleted + */ + uint32_t total_messages_sent; + + /** + * @brief Number of messages (not including the initial message or deleted messages) of the thread. + * For threads created before July 1, 2022, the message count is inaccurate when it's greater than 50. + */ + uint8_t message_count; + + /** Approximate count of members in a thread (threads) */ + uint8_t member_count; + + /** + * @brief Construct a new thread object + */ + thread(); + + /** + * @brief Returns true if the thread is within an announcement channel + * + * @return true if announcement thread + */ + bool is_news_thread() const; + + /** + * @brief Returns true if the channel is a public thread + * + * @return true if public thread + */ + bool is_public_thread() const; + + /** + * @brief Returns true if the channel is a private thread + * + * @return true if private thread + */ + bool is_private_thread() const; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + thread& fill_from_json(nlohmann::json* j); + + /** + * @brief Destroy the thread object + */ + virtual ~thread(); + + /** + * @brief Build json for this thread object + * + * @param with_id include the ID in the json + * @return std::string JSON string + */ + std::string build_json(bool with_id = false) const; + +}; + + +/** + * @brief Serialize a thread_metadata object to json + * + * @param j JSON object to serialize to + * @param tmdata object to serialize + */ +void to_json(nlohmann::json& j, const thread_metadata& tmdata); + +/** + * @brief Serialize a permission_overwrite object to json + * + * @param j JSON object to serialize to + * @param po object to serialize + */ +void to_json(nlohmann::json& j, const permission_overwrite& po); + +/** + * @brief A group of channels + */ +typedef std::unordered_map channel_map; + +/** + * @brief A group of threads + */ +typedef std::unordered_map thread_map; + +}; + diff --git a/3rdParty/dpp/cluster.h b/3rdParty/dpp/cluster.h index c52898962e..bb1a8cbab0 100644 --- a/3rdParty/dpp/cluster.h +++ b/3rdParty/dpp/cluster.h @@ -1,3341 +1,3341 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace dpp { - -/** - * @brief Types of startup for cluster::start() - */ -enum start_type : bool { - /** - * @brief Wait forever on a condition variable. - * The cluster will spawn threads for each shard - * and start() will not return in normal operation. - */ - st_wait = false, - - /** - * @brief Return immediately after starting shard threads. - * If you set the parameter of cluster::start() to - * this value, you will have to manage the lifetime - * and scope of your cluster object yourself. Taking it - * out of scope or deleting its pointer will terminate - * the bot. - */ - st_return = true, -}; - -/** @brief The cluster class represents a group of shards and a command queue for sending and - * receiving commands from discord via HTTP. You should usually instantiate a cluster object - * at the very least to make use of the library. - */ -class DPP_EXPORT cluster { - - friend class discord_client; - friend class discord_voice_client; - - /** - * @brief default gateway for connecting the websocket. - */ - std::string default_gateway; - - /** - * @brief queue system for commands sent to Discord, and any replies - */ - request_queue* rest; - - /** - * @brief queue system for arbitrary HTTP requests sent by the user to sites other than Discord - */ - request_queue* raw_rest; - - /** - * @brief True if to use compression on shards - */ - bool compressed; - - /** - * @brief Lock to prevent concurrent access to dm_channels - */ - std::mutex dm_list_lock; - - /** - * @brief Start time of cluster - */ - time_t start_time; - - /** - * @brief Active DM channels for the bot - */ - std::unordered_map dm_channels; - - /** - * @brief Active shards on this cluster. Shard IDs may have gaps between if there - * are multiple clusters. - */ - shard_list shards; - - /** - * @brief List of all active registered timers - */ - timer_reg_t timer_list; - - /** - * @brief List of timers by time - */ - timer_next_t next_timer; - - /** - * @brief Tick active timers - */ - void tick_timers(); - - /** - * @brief Reschedule a timer for its next tick - * - * @param t Timer to reschedule - */ - void timer_reschedule(timer_t* t); -public: - /** - * @brief Current bot token for all shards on this cluster and all commands sent via HTTP - */ - std::string token; - - /** - * @brief Last time the bot sent an IDENTIFY - */ - time_t last_identify; - - /** - * @brief Current bitmask of gateway intents - */ - uint32_t intents; - - /** - * @brief Total number of shards across all clusters - */ - uint32_t numshards; - - /** - * @brief ID of this cluster, between 0 and MAXCLUSTERS-1 inclusive - */ - uint32_t cluster_id; - - /** - * @brief Total number of clusters that are active - */ - uint32_t maxclusters; - - /** - * @brief REST latency (HTTPS ping) in seconds - */ - double rest_ping; - - /** - * @brief The details of the bot user. This is assumed to be identical across all shards - * in the cluster. Each connecting shard updates this information. - */ - dpp::user me; - - /** - * @brief Current cache policy for the cluster - */ - cache_policy_t cache_policy; - - /** - * @brief Websocket mode for all shards in the cluster, either ws_json or ws_etf. - * Production bots should use ETF, while development bots should use JSON. - */ - websocket_protocol_t ws_mode; - - /** - * @brief Condition variable notified when the cluster is terminating. - */ - std::condition_variable terminating; - - /** - * @brief Constructor for creating a cluster. All but the token are optional. - * @param token The bot token to use for all HTTP commands and websocket connections - * @param intents A bitmask of dpd::intents values for all shards on this cluster. This is required to be sent for all bots with over 100 servers. - * @param shards The total number of shards on this bot. If there are multiple clusters, then (shards / clusters) actual shards will run on this cluster. - * If you omit this value, the library will attempt to query the Discord API for the correct number of shards to start. - * @param cluster_id The ID of this cluster, should be between 0 and MAXCLUSTERS-1 - * @param maxclusters The total number of clusters that are active, which may be on separate processes or even separate machines. - * @param compressed Whether or not to use compression for shards on this cluster. Saves a ton of bandwidth at the cost of some CPU - * @param policy Set the user caching policy for the cluster, either lazy (only cache users/members when they message the bot) or aggressive (request whole member lists on seeing new guilds too) - * @param request_threads The number of threads to allocate for making HTTP requests to Discord. This defaults to 12. You can increase this at runtime via the object returned from get_rest(). - * @param request_threads_raw The number of threads to allocate for making HTTP requests to sites outside of Discord. This defaults to 1. You can increase this at runtime via the object returned from get_raw_rest(). - * @throw dpp::exception Thrown on windows, if WinSock fails to initialise, or on any other system if a dpp::request_queue fails to construct - */ - cluster(const std::string& token, uint32_t intents = i_default_intents, uint32_t shards = 0, uint32_t cluster_id = 0, uint32_t maxclusters = 1, bool compressed = true, cache_policy_t policy = { cp_aggressive, cp_aggressive, cp_aggressive }, uint32_t request_threads = 12, uint32_t request_threads_raw = 1); - - /** - * @brief dpp::cluster is non-copyable - */ - cluster(const cluster&) = delete; - - /** - * @brief dpp::cluster is non-moveable - */ - cluster(const cluster&&) = delete; - - /** - * @brief Destroy the cluster object - */ - virtual ~cluster(); - - /** - * @brief End cluster execution without destructing it. - * To restart the cluster, call cluster::start() again. - */ - void shutdown(); - - /** - * @brief Get the rest_queue object which handles HTTPS requests to Discord - * @return request_queue* pointer to request_queue object - */ - request_queue* get_rest(); - - /** - * @brief Get the raw rest_queue object which handles all HTTP(S) requests that are not directed at Discord - * @return request_queue* pointer to request_queue object - */ - request_queue* get_raw_rest(); - - /** - * @brief Set the websocket protocol for all shards on this cluster. - * You should call this method before cluster::start. - * Generally ws_etf is faster, but provides less facilities for debugging should something - * go wrong. It is recommended to use ETF in production and JSON in development. - * - * @param mode websocket protocol to use, either ws_json or ws_etf. - * @return cluster& Reference to self for chaining. - */ - cluster& set_websocket_protocol(websocket_protocol_t mode); - - /** - * @brief Set the audit log reason for the next REST call to be made. - * This is set per-thread, so you must ensure that if you call this method, your request that - * is associated with the reason happens on the same thread where you set the reason. - * Once the next call is made, the audit log reason is cleared for this thread automatically. - * - * Example: - * ``` - * bot.set_audit_reason("Too much abusive content") - * .channel_delete(my_channel_id); - * ``` - * - * @param reason The reason to set for the next REST call on this thread - * @return cluster& Reference to self for chaining. - */ - cluster& set_audit_reason(const std::string &reason); - - /** - * @brief Clear the audit log reason for the next REST call to be made. - * This is set per-thread, so you must ensure that if you call this method, your request that - * is associated with the reason happens on the same thread where you set the reason. - * Once the next call is made, the audit log reason is cleared for this thread automatically. - * - * Example: - * ``` - * bot.set_audit_reason("Won't be sent") - * .clear_audit_reason() - * .channel_delete(my_channel_id); - * ``` - * - * @return cluster& Reference to self for chaining. - */ - cluster& clear_audit_reason(); - - /** - * @brief Get the audit reason set for the next REST call to be made on this thread. - * This is set per-thread, so you must ensure that if you call this method, your request that - * is associated with the reason happens on the same thread where you set the reason. - * Once the next call is made, the audit log reason is cleared for this thread automatically. - * - * @note This method call clears the audit reason when it returns it. - * - * @return std::string The audit reason to be used. - * - */ - std::string get_audit_reason(); - - /** - * @brief Sets the address of the default gateway, for connecting the websockets. - * - * @return cluster& Reference to self for chaining. - */ - cluster& set_default_gateway(std::string& default_gateway); - - /** - * @brief Log a message to whatever log the user is using. - * The logged message is passed up the chain to the on_log event in user code which can then do whatever - * it wants to do with it. - * @param severity The log level from dpp::loglevel - * @param msg The log message to output - */ - void log(dpp::loglevel severity, const std::string &msg) const; - - /** - * @brief Start a timer. Every `frequency` seconds, the callback is called. - * - * @param on_tick The callback lambda to call for this timer when ticked - * @param on_stop The callback lambda to call for this timer when it is stopped - * @param frequency How often to tick the timer in seconds - * @return timer A handle to the timer, used to remove that timer later - */ - timer start_timer(timer_callback_t on_tick, uint64_t frequency, timer_callback_t on_stop = {}); - - /** - * @brief Stop a ticking timer - * - * @param t Timer handle received from cluster::start_timer - * @return bool True if the timer was stopped, false if it did not exist - * @note If the timer has an on_stop lambda, the on_stop lambda will be called. - */ - bool stop_timer(timer t); - - /** - * @brief Get the dm channel for a user id - * - * @param user_id the user id to get the dm channel for - * @return Returns 0 on failure - */ - snowflake get_dm_channel(snowflake user_id); - - /** - * @brief Set the dm channel id for a user id - * - * @param user_id user id to set the dm channel for - * @param channel_id dm channel to set - */ - void set_dm_channel(snowflake user_id, snowflake channel_id); - - /** - * @brief Returns the uptime of the cluster - * - * @return dpp::utility::uptime The uptime of the cluster - */ - dpp::utility::uptime uptime(); - - /** - * @brief Start the cluster, connecting all its shards. - * - * Returns once all shards are connected if return_after is true, - * otherwise enters an infinite loop while the shards run. - * - * @param return_after If true the bot will return to your program after starting shards, if false this function will never return. - */ - void start(bool return_after = true); - - /** - * @brief Set the presence for all shards on the cluster - * - * @param p The presence to set. Only the online status and the first activity are sent. - */ - void set_presence(const class dpp::presence &p); - - /** - * @brief Get a shard by id, returning the discord_client - * - * @param id Shard ID - * @return discord_client* shard, or null - */ - discord_client* get_shard(uint32_t id); - - /** - * @brief Get the list of shards - * - * @return shard_list& Reference to map of shards for this cluster - */ - const shard_list& get_shards(); - - /* Functions for attaching to event handlers */ - - /** - * @brief on voice state update event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_state_update_t&, and returns void. - */ - event_router_t on_voice_state_update; - - - /** - * @brief on voice client disconnect event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_client_disconnect_t&, and returns void. - */ - event_router_t on_voice_client_disconnect; - - - /** - * @brief on voice client speaking event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_client_speaking_t&, and returns void. - */ - event_router_t on_voice_client_speaking; - - - /** - * @brief Called when a log message is to be written to the log. - * You can attach any logging system here you wish, e.g. spdlog, or even just a simple - * use of std::cout or printf. If nothing attaches this log event, then the - * library will be silent. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type log_t&, and returns void. - */ - event_router_t on_log; - - /** - * @brief on guild join request delete. - * Triggered when a user declines the membership screening questionnaire for a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_join_request_delete_t&, and returns void. - */ - event_router_t on_guild_join_request_delete; - - - /** - * @brief Called when a new interaction is created. - * Interactions are created by discord when commands you have registered are issued - * by a user. For an example of this in action please see \ref slashcommands - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type interaction_create_t&, and returns void. - * - * @note There are dedicated events to handle slashcommands (See dpp::cluster::on_slashcommand), - * user context menus (See dpp::cluster::on_user_context_menu) and message context menus (See dpp::cluster::on_message_context_menu) - */ - event_router_t on_interaction_create; - - /** - * @brief Called when a slash command is issued. - * Only dpp::ctxm_chat_input types of interaction are routed to this event. - * For an example of this in action please see \ref slashcommands - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type slashcommand_t&, and returns void. - */ - event_router_t on_slashcommand; - - /** - * @brief Called when a button is clicked attached to a message. - * Button clicks are triggered by discord when buttons are clicked which you have - * associated with a message using dpp::component. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type button_click_t&, and returns void. - */ - event_router_t on_button_click; - - /** - * @brief Called when an auto completed field needs suggestions to present to the user - * This is triggered by discord when option choices have auto completion enabled which you have - * associated with a dpp::slashcommand. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type autocomplete_t&, and returns void. - */ - event_router_t on_autocomplete; - - - /** - * @brief Called when a select menu is clicked attached to a message. - * Select menu clicks are triggered by discord when select menus are clicked which you have - * associated with a message using dpp::component. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type select_click_t&, and returns void. - */ - event_router_t on_select_click; - - /** - * @brief Called when a user right-clicks or long-presses on a message, - * where a slash command is bound to the dpp::ctxm_message command type. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_context_menu_t&, and returns void. - */ - event_router_t on_message_context_menu; - - /** - * @brief Called when a user right-clicks or long-presses on a user, - * where a slash command is bound to the dpp::ctxm_user command type. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type user_context_menu_t&, and returns void. - */ - event_router_t on_user_context_menu; - - /** - * @brief Called when a modal dialog is submitted. - * Form submits are triggered by discord when modal dialogs are submitted which you have - * associated with a slash command using dpp::interaction_modal_response. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type form_submit_t&, and returns void. - */ - event_router_t on_form_submit; - - - /** - * @brief Called when a guild is deleted. - * A guild can be deleted via the bot being kicked, the bot leaving the guild - * explicitly with dpp::cluster::guild_delete, or via the guild being unavailable due to - * an outage. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_delete_t&, and returns void. - */ - event_router_t on_guild_delete; - - - /** - * @brief Called when a channel is deleted from a guild. - * The channel will still be temporarily available in the cache. Pointers to the - * channel should not be retained long-term as they will be deleted by the garbage - * collector. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_delete_t&, and returns void. - */ - event_router_t on_channel_delete; - - - /** - * @brief Called when a channel is edited on a guild. - * The new channel details have already been applied to the guild when you - * receive this event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_update_t&, and returns void. - */ - event_router_t on_channel_update; - - - /** - * @brief Called when a shard is connected and ready. - * A set of cluster::on_guild_create events will follow this event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type ready_t&, and returns void. - */ - event_router_t on_ready; - - - /** - * @brief Called when a message is deleted. - * The message has already been deleted from Discord when you - * receive this event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_delete_t&, and returns void. - */ - event_router_t on_message_delete; - - - /** - * @brief Called when a user leaves a guild (either through being kicked, or choosing to leave) - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_member_remove_t&, and returns void. - */ - event_router_t on_guild_member_remove; - - - /** - * @brief Called when a connection to a shard successfully resumes. - * A resumed session does not need to re-synchronise guilds, members, etc. - * This is generally non-fatal and informational only. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type resumed_t&, and returns void. - */ - event_router_t on_resumed; - - - /** - * @brief Called when a new role is created on a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_role_create_t&, and returns void. - */ - event_router_t on_guild_role_create; - - - /** - * @brief Called when a user is typing on a channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type typing_start_t&, and returns void. - */ - event_router_t on_typing_start; - - - /** - * @brief Called when a new reaction is added to a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_add_t&, and returns void. - */ - event_router_t on_message_reaction_add; - - - /** - * @brief Called when a set of members is received for a guild. - * D++ will request these for all new guilds if needed, after the cluster::on_guild_create - * events. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_members_chunk_t&, and returns void. - */ - event_router_t on_guild_members_chunk; - - - /** - * @brief Called when a single reaction is removed from a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_remove_t&, and returns void. - */ - event_router_t on_message_reaction_remove; - - - /** - * @brief Called when a new guild is created. - * D++ will request members for the guild for its cache using guild_members_chunk. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_create_t&, and returns void. - */ - event_router_t on_guild_create; - - - /** - * @brief Called when a new channel is created on a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_create_t&, and returns void. - */ - event_router_t on_channel_create; - - - /** - * @brief Called when all reactions for a particular emoji are removed from a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_remove_emoji_t&, and returns void. - */ - event_router_t on_message_reaction_remove_emoji; - - - /** - * @brief Called when multiple messages are deleted from a channel or DM. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_delete_bulk_t&, and returns void. - */ - event_router_t on_message_delete_bulk; - - - /** - * @brief Called when an existing role is updated on a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_role_update_t&, and returns void. - */ - event_router_t on_guild_role_update; - - - /** - * @brief Called when a role is deleted in a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_role_delete_t&, and returns void. - */ - event_router_t on_guild_role_delete; - - - /** - * @brief Called when a message is pinned. - * Note that the pinned message is not returned to this event, just the timestamp - * of the last pinned message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type channel_pins_update_t&, and returns void. - */ - event_router_t on_channel_pins_update; - - - /** - * @brief Called when all reactions are removed from a message. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_reaction_remove_all_t&, and returns void. - */ - event_router_t on_message_reaction_remove_all; - - - /** - * @brief Called when we are told which voice server we can use. - * This will be sent either when we establish a new voice channel connection, - * or as discord rearrange their infrastructure. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_server_update_t&, and returns void. - */ - event_router_t on_voice_server_update; - - - /** - * @brief Called when new emojis are added to a guild. - * The complete set of emojis is sent every time. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_emojis_update_t&, and returns void. - */ - event_router_t on_guild_emojis_update; - - - /** - * @brief Called when new stickers are added to a guild. - * The complete set of stickers is sent every time. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_stickers_update_t&, and returns void. - */ - event_router_t on_guild_stickers_update; - - - /** - * @brief Called when a user's presence is updated. - * To receive these you will need the GUILD_PRESENCES privileged intent. - * You will receive many of these, very often, and receiving them will significantly - * increase your bot's CPU usage. If you don't need them it is recommended to not ask - * for them. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type presence_update_t&, and returns void. - */ - event_router_t on_presence_update; - - - /** - * @brief Called when the webhooks for a guild are updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type webhooks_update_t&, and returns void. - */ - event_router_t on_webhooks_update; - - /** - * @brief Called when a new automod rule is created. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_create_t&, and returns void. - */ - event_router_t on_automod_rule_create; - - - /** - * @brief Called when an automod rule is updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_update_t&, and returns void. - */ - event_router_t on_automod_rule_update; - - /** - * @brief Called when an automod rule is deleted. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_delete_t&, and returns void. - */ - event_router_t on_automod_rule_delete; - - /** - * @brief Called when an automod rule is triggered/executed. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type automod_rule_execute_t&, and returns void. - */ - event_router_t on_automod_rule_execute; - - /** - * @brief Called when a new member joins a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_member_add_t&, and returns void. - */ - event_router_t on_guild_member_add; - - - /** - * @brief Called when an invite is deleted from a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type invite_delete_t&, and returns void. - */ - event_router_t on_invite_delete; - - - /** - * @brief Called when details of a guild are updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_update_t&, and returns void. - */ - event_router_t on_guild_update; - - - /** - * @brief Called when an integration is updated for a guild. - * This returns the complete list. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_integrations_update_t&, and returns void. - */ - event_router_t on_guild_integrations_update; - - - /** - * @brief Called when details of a guild member (e.g. their roles or nickname) are updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_member_update_t&, and returns void. - */ - event_router_t on_guild_member_update; - - - /** - * @brief Called when a new invite is created for a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type invite_create_t&, and returns void. - */ - event_router_t on_invite_create; - - - /** - * @brief Called when a message is updated (edited). - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_update_t&, and returns void. - */ - event_router_t on_message_update; - - - /** - * @brief Called when a user is updated. - * This is separate to cluster::on_guild_member_update and includes things such as an avatar change, - * username change, discriminator change or change in subscription status for nitro. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type user_update_t&, and returns void. - */ - event_router_t on_user_update; - - - /** - * @brief Called when a new message arrives from discord. - * Note that D++ does not cache messages. If you want to cache these objects you - * should create something yourself within your bot. Caching of messages is not on - * the roadmap to be supported as it consumes excessive amounts of RAM. - * For an example for caching of messages, please see \ref caching-messages - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type message_create_t&, and returns void. - */ - event_router_t on_message_create; - - - /** - * @brief Called when a ban is added to a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_ban_add_t&, and returns void. - */ - event_router_t on_guild_ban_add; - - - /** - * @brief Called when a ban is removed from a guild. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_ban_remove_t&, and returns void. - */ - event_router_t on_guild_ban_remove; - - - /** - * @brief Called when a new integration is attached to a guild by a user. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type integration_create_t&, and returns void. - */ - event_router_t on_integration_create; - - - /** - * @brief Called when an integration is updated by a user. - * This returns details of just the single integration that has changed. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type integration_update_t&, and returns void. - */ - event_router_t on_integration_update; - - - /** - * @brief Called when an integration is removed by a user. - * An integration is a connection to a guild of a user's associated accounts, - * e.g. youtube or twitch, for automatic assignment of roles etc. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type integration_delete_t&, and returns void. - */ - event_router_t on_integration_delete; - - - /** - * @brief Called when a thread is created. - * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_create_t&, and returns void. - */ - event_router_t on_thread_create; - - - /** - * @brief Called when a thread is updated - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_update_t&, and returns void. - */ - event_router_t on_thread_update; - - - /** - * @brief Called when a thread is deleted - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_delete_t&, and returns void. - */ - event_router_t on_thread_delete; - - - /** - * @brief Called when thread list is synced (upon gaining access to a channel). - * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_list_sync_t&, and returns void. - */ - event_router_t on_thread_list_sync; - - - /** - * @brief Called when current user's thread member object is updated - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_member_update_t&, and returns void. - */ - event_router_t on_thread_member_update; - - - /** - * @brief Called when a thread's member list is updated (without GUILD_MEMBERS intent, is only called for current user) - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type thread_members_update_t&, and returns void. - */ - event_router_t on_thread_members_update; - - - /** - * @brief Called when a new scheduled event is created - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_create_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_create; - - - /** - * @brief Called when a new scheduled event is updated - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_update_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_update; - - - /** - * @brief Called when a new scheduled event is deleted - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_delete_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_delete; - - - /** - * @brief Called when a user is added to a scheduled event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_add_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_user_add; - - - /** - * @brief Called when a user is removed to a scheduled event - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_remove_t&, and returns void. - */ - event_router_t on_guild_scheduled_event_user_remove; - - - /** - * @brief Called when packets are sent from the voice buffer. - * The voice buffer contains packets that are already encoded with Opus and encrypted - * with Sodium, and merged into packets by the repacketizer, which is done in the - * dpp::discord_voice_client::send_audio method. You should use the buffer size properties - * of dpp::voice_buffer_send_t to determine if you should fill the buffer with more - * content. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_buffer_send_t&, and returns void. - */ - event_router_t on_voice_buffer_send; - - - /** - * @brief Called when a user is talking on a voice channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_user_talking_t&, and returns void. - */ - event_router_t on_voice_user_talking; - - - /** - * @brief Called when a voice channel is connected and ready to send audio. - * Note that this is not directly attached to the READY event of the websocket, - * as there is further connection that needs to be done before audio is ready to send. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_ready_t&, and returns void. - */ - event_router_t on_voice_ready; - - - /** - * @brief Called when new audio data is received. - * Each separate user's audio from the voice channel will arrive tagged with - * their user id in the event, if a user can be attributed to the received audio. - * - * @note Receiving audio for bots is not officially supported by discord. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. - */ - event_router_t on_voice_receive; - - /** - * @brief Called when new audio data is received, combined and mixed for all speaking users. - * - * @note Receiving audio for bots is not officially supported by discord. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. - */ - event_router_t on_voice_receive_combined; - - /** - * @brief Called when sending of audio passes over a track marker. - * Track markers are arbitrarily placed "bookmarks" in the audio buffer, placed - * by the bot developer. Each track marker can have a string value associated with it - * which is specified in dpp::discord_voice_client::insert_marker and returned to this - * event. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type voice_track_marker_t&, and returns void. - */ - event_router_t on_voice_track_marker; - - - /** - * @brief Called when a new stage instance is created on a stage channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * - */ - event_router_t on_stage_instance_create; - - - /** - * @brief Called when a stage instance is updated. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type stage_instance_update_t&, and returns void. - */ - event_router_t on_stage_instance_update; - - - /** - * @brief Called when an existing stage instance is deleted from a stage channel. - * - * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. - * The function signature for this event takes a single `const` reference of type stage_instance_delete_t&, and returns void. - */ - event_router_t on_stage_instance_delete; - - - /** - * @brief Post a REST request. Where possible use a helper method instead like message_create - * - * @param endpoint Endpoint to post to, e.g. /api/guilds - * @param major_parameters Major parameters for the endpoint e.g. a guild id - * @param parameters Minor parameters for the API request - * @param method Method, e.g. GET, POST - * @param postdata Post data (usually JSON encoded) - * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. - * @param filename Filename to post for POST requests (for uploading files) - * @param filecontent File content to post for POST requests (for uploading files) - */ - void post_rest(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::string &filename = "", const std::string &filecontent = ""); - - /** - * @brief Post a multipart REST request. Where possible use a helper method instead like message_create - * - * @param endpoint Endpoint to post to, e.g. /api/guilds - * @param major_parameters Major parameters for the endpoint e.g. a guild id - * @param parameters Minor parameters for the API request - * @param method Method, e.g. GET, POST - * @param postdata Post data (usually JSON encoded) - * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. - * @param filename List of filenames to post for POST requests (for uploading files) - * @param filecontent List of file content to post for POST requests (for uploading files) - */ - void post_rest_multipart(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::vector &filename = {}, const std::vector &filecontent = {}); - - /** - * @brief Make a HTTP(S) request. For use when wanting asynchronous access to HTTP APIs outside of Discord. - * - * @param url Full URL to post to, e.g. https://api.somewhere.com/v1/foo/ - * @param method Method, e.g. GET, POST - * @param callback Function to call when the HTTP call completes. No processing is done on the returned data. - * @param postdata POST data - * @param mimetype MIME type of POST data - * @param headers Headers to send with the request - */ - void request(const std::string &url, http_method method, http_completion_event callback, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}); - - /** - * @brief Respond to a slash command - * - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response - * @param interaction_id Interaction id to respond to - * @param token Token for the interaction webhook - * @param r Response to send - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit response to a slash command - * - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response - * @param token Token for the interaction webhook - * @param m Message to send - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_response_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a followup message to a slash command - * - * @param token Token for the interaction webhook - * @param m followup message to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_create(const std::string &token, const message &m, command_completion_event_t callback); - - /** - * @brief Edit original followup message to a slash command - * This is an alias for cluster::interaction_response_edit - * @see cluster::interaction_response_edit - * - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_edit_original(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief - * - * @param token Token for the interaction webhook - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_delete(const std::string &token, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit followup message to a slash command - * The message ID in the message you pass should be correctly set to that of a followup message you previously sent - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the followup message to a slash command - * @param token Token for the interaction webhook - * @param message_id message to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void interaction_followup_get(const std::string &token, snowflake message_id, command_completion_event_t callback); - - /** - * @brief Create a global slash command (a bot can have a maximum of 100 of these). - * - * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command - * @param s Slash command to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_create(const slashcommand &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a global slash command - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command - * @param id The ID of the slash command - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_get(snowflake id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the audit log for a guild - * - * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log - * @param guild_id Guild to get the audit log of - * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user - * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type - * @param before Entries that preceded a specific audit log entry ID. Used for paginating - * @param limit Maximum number of entries (between 1-100) to return - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::auditlog object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit, command_completion_event_t callback); - - /** - * @brief Create a slash command local to a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command - * @note Creating a command with the same name as an existing command for your application will overwrite the old command. - * @param s Slash command to create - * @param guild_id Guild ID to create the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_create(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - - /** - * @brief Create/overwrite guild slash commands. - * Any existing guild slash commands on this guild will be deleted and replaced with these. - * - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands - * @param commands Vector of slash commands to create/update. - * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. - * @param guild_id Guild ID to create/update the slash commands in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_bulk_command_create(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create/overwrite global slash commands. - * Any existing global slash commands will be deleted and replaced with these. - * - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands - * @param commands Vector of slash commands to create/update. - * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. - * Commands that do not already exist will count toward daily application command create limits. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_bulk_command_create(const std::vector &commands, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a global slash command (a bot can have a maximum of 100 of these) - * - * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command - * @param s Slash command to change - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_edit(const slashcommand &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a slash command of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param id The ID of the slash command - * @param guild_id Guild ID to get the slash command from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_get(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a slash command local to a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command - * @param s Slash command to edit - * @param guild_id Guild ID to edit the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_edit(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit slash command permissions of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions - * @note You can only add up to 10 permission overwrites for a command - * @param s Slash command to edit the permissions for - * @param guild_id Guild ID to edit the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_edit_permissions(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the permissions for a slash command of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param id The ID of the slash command to get the permissions for - * @param guild_id Guild ID to get the permissions of - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_command_permissions object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_get_permissions(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit/Overwrite the permissions of all existing slash commands in a guild - * - * @note You can only add up to 10 permission overwrites for a command - * - * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions - * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. - * @param commands A vector of slash commands to edit/overwrite the permissions for - * @param guild_id Guild ID to edit permissions of the slash commands in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead - */ - void guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a global slash command (a bot can have a maximum of 100 of these) - * - * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command - * @param id Slash command to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_command_delete(snowflake id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a slash command local to a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command - * @param id Slash command to delete - * @param guild_id Guild ID to delete the slash command in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_command_delete(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the application's slash commands for a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param guild_id Guild ID to get the slash commands for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_commands_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get all slash command permissions of a guild - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param guild_id Guild ID to get the slash commands permissions for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_commands_get_permissions(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get the application's global slash commands - * - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void global_commands_get(command_completion_event_t callback); - - /** - * @brief Create a direct message, also create the channel for the direct message if needed - * - * @see https://discord.com/developers/docs/resources/user#create-dm - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param user_id User ID of user to send message to - * @param m Message object - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void direct_message_create(snowflake user_id, const message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a message - * - * @see https://discord.com/developers/docs/resources/channel#get-channel-message - * @param message_id Message ID - * @param channel_id Channel ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_get(snowflake message_id, snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Get multiple messages. - * - * This function will attempt to fetch as many messages as possible using multiple API calls if needed. - * - * @see https://discord.com/developers/docs/resources/channel#get-channel-messages - * @param channel_id Channel ID to retrieve messages for - * @param around Messages should be retrieved around this ID if this is set to non-zero - * @param before Messages before this ID should be retrieved if this is set to non-zero - * @param after Messages after this ID should be retrieved if this is set to non-zero - * @param limit This number of messages maximum should be returned, up to a maximum of 100. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit, command_completion_event_t callback); - - /** - * @brief Send a message to a channel. The callback function is called when the message has been sent - * - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param m Message to send - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_create(const struct message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Crosspost a message. The callback function is called when the message has been sent - * - * @see https://discord.com/developers/docs/resources/channel#crosspost-message - * @param message_id Message to crosspost - * @param channel_id Channel ID to crosspost from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_crosspost(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a message on a channel. The callback function is called when the message has been edited - * - * @see https://discord.com/developers/docs/resources/channel#edit-message - * @param m Message to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_edit(const struct message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add a reaction to a message. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/resources/channel#create-reaction - * @param m Message to add a reaction to - * @param reaction Reaction to add. Emojis should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_add_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete own reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction - * @param m Message to delete own reaction from - * @param reaction Reaction to delete. The reaction should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_own_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a user's reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction - * @param m Message to delete a user's reaction from - * @param user_id User ID who's reaction you want to remove - * @param reaction Reaction to remove. Reactions should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction(const struct message &m, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get reactions on a message for a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#get-reactions - * @param m Message to get reactions for - * @param reaction Reaction should be in the form emojiname:id or a unicode character - * @param before Reactions before this ID should be retrieved if this is set to non-zero - * @param after Reactions before this ID should be retrieved if this is set to non-zero - * @param limit This number of reactions maximum should be returned - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_get_reactions(const struct message &m, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); - - /** - * @brief Delete all reactions on a message - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions - * @param m Message to delete reactions from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_all_reactions(const struct message &m, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete all reactions on a message using a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji - * @param m Message to delete reactions from - * @param reaction Reaction to delete, in the form emojiname:id or a unicode character - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction_emoji(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add a reaction to a message by id. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/topics/gateway#message-reaction-add - * @param message_id Message to add reactions to - * @param channel_id Channel to add reactions to - * @param reaction Reaction to add. Emojis should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_add_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete own reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character. - * - * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param reaction Reaction to delete. The reaction should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_own_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a user's reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param user_id User ID who's reaction you want to remove - * @param reaction Reaction to remove. Reactions should be in the form emojiname:id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction(snowflake message_id, snowflake channel_id, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get reactions on a message for a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#get-reactions - * @param message_id Message to get reactions for - * @param channel_id Channel to get reactions for - * @param reaction Reaction should be in the form emojiname:id or a unicode character - * @param before Reactions before this ID should be retrieved if this is set to non-zero - * @param after Reactions before this ID should be retrieved if this is set to non-zero - * @param limit This number of reactions maximum should be returned - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_get_reactions(snowflake message_id, snowflake channel_id, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); - - /** - * @brief Delete all reactions on a message by id - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_all_reactions(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete all reactions on a message using a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character - * - * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji - * @param message_id Message to delete reactions from - * @param channel_id Channel to delete reactions from - * @param reaction Reaction to delete, in the form emojiname:id or a unicode character - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_reaction_emoji(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a message from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/channel#delete-message - * @param message_id Message ID to delete - * @param channel_id Channel to delete from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. - * - * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages - * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) - * @param channel_id Channel to delete from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_delete_bulk(const std::vector &message_ids, snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a channel - * - * @see https://discord.com/developers/docs/resources/channel#get-channel - * @param c Channel ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_get(snowflake c, command_completion_event_t callback); - - /** - * @brief Get all channels for a guild - * - * @see https://discord.com/developers/docs/resources/channel#get-channels - * @param guild_id Guild ID to retrieve channels for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channels_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Create a channel - * - * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, - * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible - * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. - * - * All parameters to this endpoint are optional excluding `name` - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#create-channel - * @param c Channel to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_create(const class channel &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#modify-channel - * @param c Channel to edit/update - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit(const class channel &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit multiple channels positions - * - * Modify the positions of a set of channel objects for the guild. - * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. - * Only channels to be modified are required. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions - * @param c Channel to change the position for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit_positions(const std::vector &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a channel's permissions - * - * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param c Channel to set permissions for - * @param overwrite_id Overwrite to change (a user or role ID) - * @param allow allow permissions bitmask - * @param deny deny permissions bitmask - * @param member true if the overwrite_id is a user id, false if it is a channel id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit_permissions(const class channel &c, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a channel's permissions - * - * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id ID of the channel to set permissions for - * @param overwrite_id Overwrite to change (a user or role ID) - * @param allow allow permissions bitmask - * @param deny deny permissions bitmask - * @param member true if the overwrite_id is a user id, false if it is a channel id - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_edit_permissions(const snowflake channel_id, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel - * @param channel_id Channel id to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_delete(snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get details about an invite - * - * @see https://discord.com/developers/docs/resources/invite#get-invite - * @param invite Invite code to get information on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void invite_get(const std::string &invite, command_completion_event_t callback); - - /** - * @brief Delete an invite - * - * @see https://discord.com/developers/docs/resources/invite#delete-invite - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param invite Invite code to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void invite_delete(const std::string &invite, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get invites for a channel - * - * @see https://discord.com/developers/docs/resources/invite#get-invites - * @param c Channel to get invites for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_invites_get(const class channel &c, command_completion_event_t callback); - - /** - * @brief Create invite for a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#create-channel-invite - * @param c Channel to create an invite on - * @param i Invite to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_invite_create(const class channel &c, const class invite &i, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a channel's pins - * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages - * @param channel_id Channel ID to get pins for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_pins_get(snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Adds a recipient to a Group DM using their access token - * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient - * @param channel_id Channel id to add group DM recipients to - * @param user_id User ID to add - * @param access_token Access token from OAuth2 - * @param nick Nickname of user to apply to the chat - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Removes a recipient from a Group DM - * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient - * @param channel_id Channel ID of group DM - * @param user_id User ID to remove from group DM - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void gdm_remove(snowflake channel_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove a permission from a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission - * @param c Channel to remove permission from - * @param overwrite_id Overwrite to remove, user or channel ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_delete_permission(const class channel &c, snowflake overwrite_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Follow an announcement (news) channel - * @see https://discord.com/developers/docs/resources/channel#follow-news-channel - * @param c Channel id to follow - * @param target_channel_id Channel to subscribe the channel to - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_follow_news(const class channel &c, snowflake target_channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Trigger channel typing indicator - * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator - * @param c Channel to set as typing on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_typing(const class channel &c, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Trigger channel typing indicator - * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator - * @param cid Channel ID to set as typing on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void channel_typing(snowflake cid, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Pin a message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/channel#pin-message - * @param channel_id Channel id to pin message on - * @param message_id Message id to pin message on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_pin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Unpin a message - * @see https://discord.com/developers/docs/resources/channel#unpin-message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id Channel id to unpin message on - * @param message_id Message id to unpin message on - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void message_unpin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a guild - * - * Returns the guild object for the given id. This endpoint will also return approximate_member_count and approximate_presence_count - * for the guild. - * @see https://discord.com/developers/docs/resources/guild#get-guild - * @param g Guild ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get(snowflake g, command_completion_event_t callback); - - /** - * @brief Get a guild preview. Returns a guild object but only a subset of the fields will be populated. - * - * Returns the guild preview object for the given id `g`. If the user is not in the guild, then the guild - * must be lurkable (it must be Discoverable or have a live public stage). - * @see https://discord.com/developers/docs/resources/guild#get-guild-preview - * @param g Guild ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_preview(snowflake g, command_completion_event_t callback); - - /** - * @brief Get a guild member - * @see https://discord.com/developers/docs/resources/guild#get-guild-member - * @param guild_id Guild ID to get member for - * @param user_id User ID of member to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_member(snowflake guild_id, snowflake user_id, command_completion_event_t callback); - - /** - * @brief Search for guild members based on whether their username or nickname starts with the given string. - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see https://discord.com/developers/docs/resources/guild#search-guild-members - * @param guild_id Guild ID to search in - * @param query Query string to match username(s) and nickname(s) against - * @param limit max number of members to return (1-1000) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Get all guild members - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see https://discord.com/developers/docs/resources/guild#get-guild-members - * @param guild_id Guild ID to get all members for - * @param limit max number of members to return (1-1000) - * @param after the highest user id in the previous page - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_members(snowflake guild_id, uint16_t limit, snowflake after, command_completion_event_t callback); - - /** - * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. - * - * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. - * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. - * - * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. - * Members that are pending will have to complete membership screening before they become full members that can talk. - * - * @note All parameters to this endpoint except for access_token are optional. - * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. - * @see https://discord.com/developers/docs/resources/guild#add-guild-member - * @param gm Guild member to add - * @param access_token Access token from Oauth2 scope - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_add_member(const guild_member& gm, const std::string &access_token, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit the properties of an existing guild member - * - * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. - * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. - * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param gm Guild member to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_edit_member(const guild_member& gm, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Moves the guild member to a other voice channel, if member is connected to one. - * Set the `channel_id` to `0` to disconnect the user. - * - * Fires a `Guild Member Update` Gateway event. - * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user - * @param guild_id Guild id to which the user is connected - * @param user_id User id, who should be moved - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Change current user nickname - * - * Modifies the nickname of the current user in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick - * @param guild_id Guild ID to change nickname on - * @param nickname New nickname, or empty string to clear nickname - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_set_nickname(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add role to guild member - * - * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add a role to - * @param user_id User ID to add role to - * @param role_id Role ID to add to the user - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @deprecated Use dpp::cluster::guild_member_remove_role instead - */ - void guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @deprecated Replaced by dpp::cluster::guild_member_kick - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_kick(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Set the timeout of a guild member - * - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to timeout the member in - * @param user_id User ID to set the timeout for - * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add guild ban - * - * Create a guild ban, and optionally delete previous messages sent by the banned user. - * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. - * @see https://discord.com/developers/docs/resources/guild#create-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add ban to - * @param user_id User ID to ban - * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete guild ban - * - * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. - * Fires a Guild Ban Remove Gateway event. - * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild to delete ban from - * @param user_id User ID to delete ban for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_ban_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild ban list - * - * Requires the `BAN_MEMBERS` permission. - * @see https://discord.com/developers/docs/resources/guild#get-guild-bans - * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. - * @param guild_id Guild ID to get bans for - * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit - * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit - * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::ban_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); - - /** - * @brief Get single guild ban - * - * Requires the `BAN_MEMBERS` permission. - * @see https://discord.com/developers/docs/resources/guild#get-guild-ban - * @param guild_id Guild ID to get ban for - * @param user_id User ID of ban to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::ban object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_ban(snowflake guild_id, snowflake user_id, command_completion_event_t callback); - - /** - * @brief Get a template - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template - * @param code Template code - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void template_get(const std::string &code, command_completion_event_t callback); - - /** - * @brief Create a new guild based on a template. - * @note This endpoint can be used only by bots in less than 10 guilds. - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template - * @param code Template code to create guild from - * @param name Guild name to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_create_from_template(const std::string &code, const std::string &name, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild templates - * - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates - * @param guild_id Guild ID to get templates for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_templates_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Creates a template for the guild - * - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template - * @param guild_id Guild to create template from - * @param name Template name to create - * @param description Description of template to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_create(snowflake guild_id, const std::string &name, const std::string &description, command_completion_event_t callback); - - /** - * @brief Syncs the template to the guild's current state. - * - * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template - * @param guild_id Guild to synchronise template for - * @param code Code of template to synchronise - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_sync(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Modifies the template's metadata. - * - * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template - * @param guild_id Guild ID of template to modify - * @param code Template code to modify - * @param name New name of template - * @param description New description of template - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Deletes the template - * - * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template - * @param guild_id Guild ID of template to delete - * @param code Template code to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_template_delete(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a guild - * - * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. - * - * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. - * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an - * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions - * in a channel when also passing in channels with the channels array. - * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within - * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to - * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. - * Category channels must be listed before any children. - * - * @see https://discord.com/developers/docs/resources/guild#create-guild - * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. - * @param g Guild to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_create(const class guild &g, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a guild - * - * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. - * Fires a `Guild Update Gateway` event. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param g Guild to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_edit(const class guild &g, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a guild - * - * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. - * - * @see https://discord.com/developers/docs/resources/guild#delete-guild - * @param guild_id Guild ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_delete(snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get all emojis for a guild - * - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis - * @param guild_id Guild ID to get emojis for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emojis_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get a single emoji - * - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @param guild_id Guild ID to get emoji for - * @param emoji_id Emoji ID to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_get(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback); - - /** - * @brief Create single emoji. - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji - * @param guild_id Guild ID to create emoji om - * @param newemoji Emoji to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_create(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a single emoji. - * - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit emoji on - * @param newemoji Emoji to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_edit(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a guild emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji - * @param guild_id Guild ID to delete emoji on - * @param emoji_id Emoji ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_emoji_delete(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get prune counts - * - * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` - * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the - * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional - * roles will not. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count - * @param guild_id Guild ID to count for pruning - * @param pruneinfo Pruning info - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback); - - /** - * @brief Begin guild prune - * - * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members - * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing - * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. - * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` - * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. - * - * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to prune - * @param pruneinfo Pruning info - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild voice regions. - * - * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. - * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when - * the guild is VIP-enabled. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions - * @param guild_id Guild ID to get voice regions for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_voice_regions(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get guild invites - * - * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-invites - * @param guild_id Guild ID to get invites for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_invites(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get guild integrations - * - * Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations - * @param guild_id Guild ID to get integrations for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::integration_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_integrations(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Modify guild integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration - * @param guild_id Guild ID to modify integration for - * @param i Integration to modify - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::integration object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_modify_integration(snowflake guild_id, const class integration &i, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete guild integration - * - * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. - * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete integration for - * @param integration_id Integration ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_delete_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Sync guild integration - * - * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration - * @param guild_id Guild ID to sync integration on - * @param integration_id Integration ID to synchronise - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sync_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-widget - * @param guild_id Guild ID to get widget for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_widget(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Edit guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit widget for - * @param gw New guild widget information - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_edit_widget(snowflake guild_id, const class guild_widget &gw, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild vanity url, if enabled - * - * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. - * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url - * @param guild_id Guild to get vanity URL for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::invite object in confirmation_callback_t::value filled to match the vanity url. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_get_vanity(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Create a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/webhook#create-webhook - * @param w Webhook to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void create_webhook(const class webhook &w, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get guild webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param guild_id Guild ID to get webhooks for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_guild_webhooks(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get channel webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param channel_id Channel ID to get webhooks for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_channel_webhooks(snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Get webhook - * @see https://discord.com/developers/docs/resources/webhook#get-webhook - * @param webhook_id Webhook ID to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_webhook(snowflake webhook_id, command_completion_event_t callback); - - /** - * @brief Get webhook using token - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token - * @param webhook_id Webhook ID to retrieve - * @param token Token of webhook - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback); - - /** - * @brief Edit webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook - * @param wh Webhook to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_webhook(const class webhook& wh, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit webhook with token (token is encapsulated in the webhook object) - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token - * @param wh Webhook to edit (should include token) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_webhook_with_token(const class webhook& wh, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook - * @param webhook_id Webhook ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_webhook(snowflake webhook_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete webhook with token - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token - * @param webhook_id Webhook ID to delete - * @param token Token of webhook to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Execute webhook - * - * @see https://discord.com/developers/docs/resources/webhook#execute-webhook - * @param wh Webhook to execute - * @param m Message to send - * @param wait waits for server confirmation of message send before response, and returns the created message body - * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived - * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) - * @param callback Function to call when the API call completes. - * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void execute_webhook(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = "", command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get webhook message - * - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message - * @param wh Webhook to get the original message for - * @param message_id The message ID - * @param thread_id ID of the thread the message is in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit webhook message - * - * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on - * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit - * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to - * whether or not an allowed_mentions was present in the request that originally created the message. - * - * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message - * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. - * @param wh Webhook to edit message for - * @param m New message - * @param thread_id ID of the thread the message is in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_webhook_message(const class webhook &wh, const struct message &m, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete webhook message - * - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message - * @param wh Webhook to delete message for - * @param message_id Message ID to delete - * @param thread_id ID of the thread the message is in - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); - - - /** - * @brief Get a role for a guild - * - * @see https://discord.com/developers/docs/resources/guild#get-guild-roles - * @param guild_id Guild ID to get role for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void roles_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Create a role on a guild - * - * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. - * Fires a `Guild Role Create` Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#create-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to create (guild ID is encapsulated in the role object) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void role_create(const class role &r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit a role on a guild - * - * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to edit - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void role_edit(const class role &r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. - * - * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. - * Fires multiple `Guild Role Update` Gateway events. - * - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to change the roles position on - * @param roles Vector of roles to change the positions of - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void roles_edit_position(snowflake guild_id, const std::vector &roles, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a role - * - * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. - * - * @see https://discord.com/developers/docs/resources/guild#delete-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete the role on - * @param role_id Role ID to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void role_delete(snowflake guild_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the application's role connection metadata records - * - * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#get-application-role-connection-metadata-records - * @param application_id The application ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void application_role_connection_get(snowflake application_id, command_completion_event_t callback); - - /** - * @brief Update the application's role connection metadata records - * - * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#update-application-role-connection-metadata-records - * @param application_id The application ID - * @param connection_metadata The application role connection metadata to update - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note An application can have a maximum of 5 metadata records. - */ - void application_role_connection_update(snowflake application_id, const std::vector &connection_metadata, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get user application role connection - * - * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection - * @param application_id The application ID - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void user_application_role_connection_get(snowflake application_id, command_completion_event_t callback); - - /** - * @brief Update user application role connection - * - * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection - * @param application_id The application ID - * @param connection The application role connection to update - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void user_application_role_connection_update(snowflake application_id, const application_role_connection &connection, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a user by id - * - * @see https://discord.com/developers/docs/resources/user#get-user - * @param user_id User ID to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. - * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. - */ - void user_get(snowflake user_id, command_completion_event_t callback); - - /** - * @brief Get current (bot) user - * - * @see https://discord.com/developers/docs/resources/user#get-current-user - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - */ - void current_user_get(command_completion_event_t callback); - - /** - * @brief Get current (bot) application - * - * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::application object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_application_get(command_completion_event_t callback); - - /** - * @brief Modify current member - * - * Modifies the current member in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/guild#modify-current-member - * @param guild_id Guild ID to change on - * @param nickname New nickname, or empty string to clear nickname - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_current_member_edit(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get current user's connections (linked accounts, e.g. steam, xbox). - * This call requires the oauth2 `connections` scope and cannot be executed - * against a bot token. - * @see https://discord.com/developers/docs/resources/user#get-user-connections - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::connection_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_connections_get(command_completion_event_t callback); - - /** - * @brief Get current (bot) user guilds - * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::guild_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_get_guilds(command_completion_event_t callback); - - /** - * @brief Edit current (bot) user - * - * Modifies the current member in a guild. Returns the updated guild_member object on success. - * Fires a `Guild Member Update` Gateway event. - * @see https://discord.com/developers/docs/resources/user#modify-current-user - * @param nickname Nickname to set - * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) - * @param type Type of image for avatar - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::user object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - */ - void current_user_edit(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get current user DM channels - * - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_get_dms(command_completion_event_t callback); - - /** - * @brief Create a dm channel - * @see https://discord.com/developers/docs/resources/user#create-dm - * @param user_id User ID to create DM channel with - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void create_dm_channel(snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Leave a guild - * @see https://discord.com/developers/docs/resources/user#leave-guild - * @param guild_id Guild ID to leave - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_leave_guild(snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a thread in forum channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel - * @param thread_name Name of the forum thread - * @param channel_id Forum channel in which thread to create - * @param msg The message to start the thread with - * @param auto_archive_duration Duration to automatically archive the thread after recent activity - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_create_in_forum(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a thread - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see https://discord.com/developers/docs/resources/guild#create-guild-channel - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD - * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/topics/threads - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param message_id message to start thread with - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Join a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to join - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_join_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Leave a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to leave - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void current_user_leave_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Add a member to a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to add to - * @param user_id Member ID to add - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_member_add(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Remove a member from a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to remove from - * @param user_id Member ID to remove - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_member_remove(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a thread member - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get member for - * @param user_id ID of the user to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_member_get(const snowflake thread_id, const snowflake user_id, command_completion_event_t callback); - - /** - * @brief Get members of a thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get members for - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thread_members_get(snowflake thread_id, command_completion_event_t callback); - - /** - * @brief Get active threads in a guild (Sorted by ID in descending order) - * @see https://discord.com/developers/docs/topics/threads - * @param guild_id Guild to get active threads for - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_active(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) - - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_id Get threads before this id - * @param limit Number of threads to get - * @param callback Function to call when the API call completes - * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit, command_completion_event_t callback); - - /** - * @brief Create a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker - * @param s Sticker to create. Must have its guild ID set. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_create(sticker &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Modify a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker - * @param s Sticker to modify. Must have its guild ID and sticker ID set. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_modify(sticker &s, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a sticker from a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker - * @param sticker_id sticker ID to delete - * @param guild_id guild ID to delete from - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_delete(snowflake sticker_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a nitro sticker - * @see https://discord.com/developers/docs/resources/sticker#get-sticker - * @param id Id of sticker to get. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void nitro_sticker_get(snowflake id, command_completion_event_t callback); - - /** - * @brief Get a guild sticker - * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker - * @param id Id of sticker to get. - * @param guild_id Guild ID of the guild where the sticker is - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_sticker_get(snowflake id, snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get all guild stickers - * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers - * @param guild_id Guild ID of the guild where the sticker is - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_stickers_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get sticker packs - * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::sticker_pack_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void sticker_packs_get(command_completion_event_t callback); - - /** - * @brief Create a stage instance on a stage channel. - * @see https://discord.com/developers/docs/resources/stage-instance#create-stage-instance - * @param instance Stage instance to create - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - */ - void stage_instance_create(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get the stage instance associated with the channel id, if it exists. - * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance - * @param channel_id ID of the associated channel - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void stage_instance_get(const snowflake channel_id, command_completion_event_t callback); - - /** - * @brief Edit a stage instance. - * @see https://discord.com/developers/docs/resources/stage-instance#modify-stage-instance - * @param instance Stage instance to edit - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - */ - void stage_instance_edit(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a stage instance. - * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance - * @param channel_id ID of the associated channel - * @param callback User function to execute when the api call completes - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - */ - void stage_instance_delete(const snowflake channel_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get all voice regions - * @see https://discord.com/developers/docs/resources/voice#list-voice-regions - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_voice_regions(command_completion_event_t callback); - - /** - * @brief Get the gateway information for the bot using the token - * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::gateway object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_gateway_bot(command_completion_event_t callback); - - /** - * @brief Get all scheduled events for a guild - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild - * @param guild_id Guild to get events for - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_events_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get users RSVP'd to an event - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users - * @param guild_id Guild to get user list for - * @param event_id Guild to get user list for - * @param limit Maximum number of results to return - * @param before Return user IDs that fall before this ID, if provided - * @param after Return user IDs that fall after this ID, if provided - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::event_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_users_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback, uint8_t limit = 100, snowflake before = 0, snowflake after = 0); - - /** - * @brief Create a scheduled event on a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event - * @param event Event to create (guild ID must be populated) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_create(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete a scheduled event from a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event - * @param event_id Event ID to delete - * @param guild_id Guild ID of event to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_delete(snowflake event_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit/modify a scheduled event on a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event - * @param event Event to create (event ID and guild ID must be populated) - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_edit(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get a scheduled event for a guild - * - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event - * @param guild_id Guild to get event for - * @param event_id Event ID to get - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void guild_event_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback); - - /** - * @brief Set the bot's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - current user must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. - * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. - * - You are able to set `request_to_speak_timestamp` to any present or future time. - * - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @param callback Function to call when the API call completes. - * @param suppress True if the user's audio should be suppressed, false if it should not - * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. - * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. - */ - void current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Set a user's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - User must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) - * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. - * - When suppressed, the user will have their `request_to_speak_timestamp` removed. - * - * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state - * @param user_id The user to set the voice state of - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @param callback Function to call when the API call completes. - * @param suppress True if the user's audio should be suppressed, false if it should not - * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Get all auto moderation rules for a guild - * - * @param guild_id Guild id of the auto moderation rule - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rules_get(snowflake guild_id, command_completion_event_t callback); - - /** - * @brief Get a single auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Rule id to retrieve - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_get(snowflake guild_id, snowflake rule_id, command_completion_event_t callback); - - /** - * @brief Create an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to create - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_create(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Edit an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to edit. The rule's id must be set. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_edit(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Delete an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Auto moderation rule id to delete - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void automod_rule_delete(snowflake guild_id, snowflake rule_id, command_completion_event_t callback = utility::log_error()); - -#include -#ifdef DPP_CORO -#include -#endif - -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +/** + * @brief Types of startup for cluster::start() + */ +enum start_type : bool { + /** + * @brief Wait forever on a condition variable. + * The cluster will spawn threads for each shard + * and start() will not return in normal operation. + */ + st_wait = false, + + /** + * @brief Return immediately after starting shard threads. + * If you set the parameter of cluster::start() to + * this value, you will have to manage the lifetime + * and scope of your cluster object yourself. Taking it + * out of scope or deleting its pointer will terminate + * the bot. + */ + st_return = true, +}; + +/** @brief The cluster class represents a group of shards and a command queue for sending and + * receiving commands from discord via HTTP. You should usually instantiate a cluster object + * at the very least to make use of the library. + */ +class DPP_EXPORT cluster { + + friend class discord_client; + friend class discord_voice_client; + + /** + * @brief default gateway for connecting the websocket. + */ + std::string default_gateway; + + /** + * @brief queue system for commands sent to Discord, and any replies + */ + request_queue* rest; + + /** + * @brief queue system for arbitrary HTTP requests sent by the user to sites other than Discord + */ + request_queue* raw_rest; + + /** + * @brief True if to use compression on shards + */ + bool compressed; + + /** + * @brief Lock to prevent concurrent access to dm_channels + */ + std::mutex dm_list_lock; + + /** + * @brief Start time of cluster + */ + time_t start_time; + + /** + * @brief Active DM channels for the bot + */ + std::unordered_map dm_channels; + + /** + * @brief Active shards on this cluster. Shard IDs may have gaps between if there + * are multiple clusters. + */ + shard_list shards; + + /** + * @brief List of all active registered timers + */ + timer_reg_t timer_list; + + /** + * @brief List of timers by time + */ + timer_next_t next_timer; + + /** + * @brief Tick active timers + */ + void tick_timers(); + + /** + * @brief Reschedule a timer for its next tick + * + * @param t Timer to reschedule + */ + void timer_reschedule(timer_t* t); +public: + /** + * @brief Current bot token for all shards on this cluster and all commands sent via HTTP + */ + std::string token; + + /** + * @brief Last time the bot sent an IDENTIFY + */ + time_t last_identify; + + /** + * @brief Current bitmask of gateway intents + */ + uint32_t intents; + + /** + * @brief Total number of shards across all clusters + */ + uint32_t numshards; + + /** + * @brief ID of this cluster, between 0 and MAXCLUSTERS-1 inclusive + */ + uint32_t cluster_id; + + /** + * @brief Total number of clusters that are active + */ + uint32_t maxclusters; + + /** + * @brief REST latency (HTTPS ping) in seconds + */ + double rest_ping; + + /** + * @brief The details of the bot user. This is assumed to be identical across all shards + * in the cluster. Each connecting shard updates this information. + */ + dpp::user me; + + /** + * @brief Current cache policy for the cluster + */ + cache_policy_t cache_policy; + + /** + * @brief Websocket mode for all shards in the cluster, either ws_json or ws_etf. + * Production bots should use ETF, while development bots should use JSON. + */ + websocket_protocol_t ws_mode; + + /** + * @brief Condition variable notified when the cluster is terminating. + */ + std::condition_variable terminating; + + /** + * @brief Constructor for creating a cluster. All but the token are optional. + * @param token The bot token to use for all HTTP commands and websocket connections + * @param intents A bitmask of dpd::intents values for all shards on this cluster. This is required to be sent for all bots with over 100 servers. + * @param shards The total number of shards on this bot. If there are multiple clusters, then (shards / clusters) actual shards will run on this cluster. + * If you omit this value, the library will attempt to query the Discord API for the correct number of shards to start. + * @param cluster_id The ID of this cluster, should be between 0 and MAXCLUSTERS-1 + * @param maxclusters The total number of clusters that are active, which may be on separate processes or even separate machines. + * @param compressed Whether or not to use compression for shards on this cluster. Saves a ton of bandwidth at the cost of some CPU + * @param policy Set the user caching policy for the cluster, either lazy (only cache users/members when they message the bot) or aggressive (request whole member lists on seeing new guilds too) + * @param request_threads The number of threads to allocate for making HTTP requests to Discord. This defaults to 12. You can increase this at runtime via the object returned from get_rest(). + * @param request_threads_raw The number of threads to allocate for making HTTP requests to sites outside of Discord. This defaults to 1. You can increase this at runtime via the object returned from get_raw_rest(). + * @throw dpp::exception Thrown on windows, if WinSock fails to initialise, or on any other system if a dpp::request_queue fails to construct + */ + cluster(const std::string& token, uint32_t intents = i_default_intents, uint32_t shards = 0, uint32_t cluster_id = 0, uint32_t maxclusters = 1, bool compressed = true, cache_policy_t policy = { cp_aggressive, cp_aggressive, cp_aggressive }, uint32_t request_threads = 12, uint32_t request_threads_raw = 1); + + /** + * @brief dpp::cluster is non-copyable + */ + cluster(const cluster&) = delete; + + /** + * @brief dpp::cluster is non-moveable + */ + cluster(const cluster&&) = delete; + + /** + * @brief Destroy the cluster object + */ + virtual ~cluster(); + + /** + * @brief End cluster execution without destructing it. + * To restart the cluster, call cluster::start() again. + */ + void shutdown(); + + /** + * @brief Get the rest_queue object which handles HTTPS requests to Discord + * @return request_queue* pointer to request_queue object + */ + request_queue* get_rest(); + + /** + * @brief Get the raw rest_queue object which handles all HTTP(S) requests that are not directed at Discord + * @return request_queue* pointer to request_queue object + */ + request_queue* get_raw_rest(); + + /** + * @brief Set the websocket protocol for all shards on this cluster. + * You should call this method before cluster::start. + * Generally ws_etf is faster, but provides less facilities for debugging should something + * go wrong. It is recommended to use ETF in production and JSON in development. + * + * @param mode websocket protocol to use, either ws_json or ws_etf. + * @return cluster& Reference to self for chaining. + */ + cluster& set_websocket_protocol(websocket_protocol_t mode); + + /** + * @brief Set the audit log reason for the next REST call to be made. + * This is set per-thread, so you must ensure that if you call this method, your request that + * is associated with the reason happens on the same thread where you set the reason. + * Once the next call is made, the audit log reason is cleared for this thread automatically. + * + * Example: + * ``` + * bot.set_audit_reason("Too much abusive content") + * .channel_delete(my_channel_id); + * ``` + * + * @param reason The reason to set for the next REST call on this thread + * @return cluster& Reference to self for chaining. + */ + cluster& set_audit_reason(const std::string &reason); + + /** + * @brief Clear the audit log reason for the next REST call to be made. + * This is set per-thread, so you must ensure that if you call this method, your request that + * is associated with the reason happens on the same thread where you set the reason. + * Once the next call is made, the audit log reason is cleared for this thread automatically. + * + * Example: + * ``` + * bot.set_audit_reason("Won't be sent") + * .clear_audit_reason() + * .channel_delete(my_channel_id); + * ``` + * + * @return cluster& Reference to self for chaining. + */ + cluster& clear_audit_reason(); + + /** + * @brief Get the audit reason set for the next REST call to be made on this thread. + * This is set per-thread, so you must ensure that if you call this method, your request that + * is associated with the reason happens on the same thread where you set the reason. + * Once the next call is made, the audit log reason is cleared for this thread automatically. + * + * @note This method call clears the audit reason when it returns it. + * + * @return std::string The audit reason to be used. + * + */ + std::string get_audit_reason(); + + /** + * @brief Sets the address of the default gateway, for connecting the websockets. + * + * @return cluster& Reference to self for chaining. + */ + cluster& set_default_gateway(std::string& default_gateway); + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Start a timer. Every `frequency` seconds, the callback is called. + * + * @param on_tick The callback lambda to call for this timer when ticked + * @param on_stop The callback lambda to call for this timer when it is stopped + * @param frequency How often to tick the timer in seconds + * @return timer A handle to the timer, used to remove that timer later + */ + timer start_timer(timer_callback_t on_tick, uint64_t frequency, timer_callback_t on_stop = {}); + + /** + * @brief Stop a ticking timer + * + * @param t Timer handle received from cluster::start_timer + * @return bool True if the timer was stopped, false if it did not exist + * @note If the timer has an on_stop lambda, the on_stop lambda will be called. + */ + bool stop_timer(timer t); + + /** + * @brief Get the dm channel for a user id + * + * @param user_id the user id to get the dm channel for + * @return Returns 0 on failure + */ + snowflake get_dm_channel(snowflake user_id); + + /** + * @brief Set the dm channel id for a user id + * + * @param user_id user id to set the dm channel for + * @param channel_id dm channel to set + */ + void set_dm_channel(snowflake user_id, snowflake channel_id); + + /** + * @brief Returns the uptime of the cluster + * + * @return dpp::utility::uptime The uptime of the cluster + */ + dpp::utility::uptime uptime(); + + /** + * @brief Start the cluster, connecting all its shards. + * + * Returns once all shards are connected if return_after is true, + * otherwise enters an infinite loop while the shards run. + * + * @param return_after If true the bot will return to your program after starting shards, if false this function will never return. + */ + void start(bool return_after = true); + + /** + * @brief Set the presence for all shards on the cluster + * + * @param p The presence to set. Only the online status and the first activity are sent. + */ + void set_presence(const class dpp::presence &p); + + /** + * @brief Get a shard by id, returning the discord_client + * + * @param id Shard ID + * @return discord_client* shard, or null + */ + discord_client* get_shard(uint32_t id); + + /** + * @brief Get the list of shards + * + * @return shard_list& Reference to map of shards for this cluster + */ + const shard_list& get_shards(); + + /* Functions for attaching to event handlers */ + + /** + * @brief on voice state update event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_state_update_t&, and returns void. + */ + event_router_t on_voice_state_update; + + + /** + * @brief on voice client disconnect event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_client_disconnect_t&, and returns void. + */ + event_router_t on_voice_client_disconnect; + + + /** + * @brief on voice client speaking event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_client_speaking_t&, and returns void. + */ + event_router_t on_voice_client_speaking; + + + /** + * @brief Called when a log message is to be written to the log. + * You can attach any logging system here you wish, e.g. spdlog, or even just a simple + * use of std::cout or printf. If nothing attaches this log event, then the + * library will be silent. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type log_t&, and returns void. + */ + event_router_t on_log; + + /** + * @brief on guild join request delete. + * Triggered when a user declines the membership screening questionnaire for a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_join_request_delete_t&, and returns void. + */ + event_router_t on_guild_join_request_delete; + + + /** + * @brief Called when a new interaction is created. + * Interactions are created by discord when commands you have registered are issued + * by a user. For an example of this in action please see \ref slashcommands + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type interaction_create_t&, and returns void. + * + * @note There are dedicated events to handle slashcommands (See dpp::cluster::on_slashcommand), + * user context menus (See dpp::cluster::on_user_context_menu) and message context menus (See dpp::cluster::on_message_context_menu) + */ + event_router_t on_interaction_create; + + /** + * @brief Called when a slash command is issued. + * Only dpp::ctxm_chat_input types of interaction are routed to this event. + * For an example of this in action please see \ref slashcommands + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type slashcommand_t&, and returns void. + */ + event_router_t on_slashcommand; + + /** + * @brief Called when a button is clicked attached to a message. + * Button clicks are triggered by discord when buttons are clicked which you have + * associated with a message using dpp::component. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type button_click_t&, and returns void. + */ + event_router_t on_button_click; + + /** + * @brief Called when an auto completed field needs suggestions to present to the user + * This is triggered by discord when option choices have auto completion enabled which you have + * associated with a dpp::slashcommand. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type autocomplete_t&, and returns void. + */ + event_router_t on_autocomplete; + + + /** + * @brief Called when a select menu is clicked attached to a message. + * Select menu clicks are triggered by discord when select menus are clicked which you have + * associated with a message using dpp::component. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type select_click_t&, and returns void. + */ + event_router_t on_select_click; + + /** + * @brief Called when a user right-clicks or long-presses on a message, + * where a slash command is bound to the dpp::ctxm_message command type. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_context_menu_t&, and returns void. + */ + event_router_t on_message_context_menu; + + /** + * @brief Called when a user right-clicks or long-presses on a user, + * where a slash command is bound to the dpp::ctxm_user command type. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type user_context_menu_t&, and returns void. + */ + event_router_t on_user_context_menu; + + /** + * @brief Called when a modal dialog is submitted. + * Form submits are triggered by discord when modal dialogs are submitted which you have + * associated with a slash command using dpp::interaction_modal_response. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type form_submit_t&, and returns void. + */ + event_router_t on_form_submit; + + + /** + * @brief Called when a guild is deleted. + * A guild can be deleted via the bot being kicked, the bot leaving the guild + * explicitly with dpp::cluster::guild_delete, or via the guild being unavailable due to + * an outage. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_delete_t&, and returns void. + */ + event_router_t on_guild_delete; + + + /** + * @brief Called when a channel is deleted from a guild. + * The channel will still be temporarily available in the cache. Pointers to the + * channel should not be retained long-term as they will be deleted by the garbage + * collector. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_delete_t&, and returns void. + */ + event_router_t on_channel_delete; + + + /** + * @brief Called when a channel is edited on a guild. + * The new channel details have already been applied to the guild when you + * receive this event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_update_t&, and returns void. + */ + event_router_t on_channel_update; + + + /** + * @brief Called when a shard is connected and ready. + * A set of cluster::on_guild_create events will follow this event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type ready_t&, and returns void. + */ + event_router_t on_ready; + + + /** + * @brief Called when a message is deleted. + * The message has already been deleted from Discord when you + * receive this event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_delete_t&, and returns void. + */ + event_router_t on_message_delete; + + + /** + * @brief Called when a user leaves a guild (either through being kicked, or choosing to leave) + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_member_remove_t&, and returns void. + */ + event_router_t on_guild_member_remove; + + + /** + * @brief Called when a connection to a shard successfully resumes. + * A resumed session does not need to re-synchronise guilds, members, etc. + * This is generally non-fatal and informational only. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type resumed_t&, and returns void. + */ + event_router_t on_resumed; + + + /** + * @brief Called when a new role is created on a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_role_create_t&, and returns void. + */ + event_router_t on_guild_role_create; + + + /** + * @brief Called when a user is typing on a channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type typing_start_t&, and returns void. + */ + event_router_t on_typing_start; + + + /** + * @brief Called when a new reaction is added to a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_add_t&, and returns void. + */ + event_router_t on_message_reaction_add; + + + /** + * @brief Called when a set of members is received for a guild. + * D++ will request these for all new guilds if needed, after the cluster::on_guild_create + * events. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_members_chunk_t&, and returns void. + */ + event_router_t on_guild_members_chunk; + + + /** + * @brief Called when a single reaction is removed from a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_remove_t&, and returns void. + */ + event_router_t on_message_reaction_remove; + + + /** + * @brief Called when a new guild is created. + * D++ will request members for the guild for its cache using guild_members_chunk. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_create_t&, and returns void. + */ + event_router_t on_guild_create; + + + /** + * @brief Called when a new channel is created on a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_create_t&, and returns void. + */ + event_router_t on_channel_create; + + + /** + * @brief Called when all reactions for a particular emoji are removed from a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_remove_emoji_t&, and returns void. + */ + event_router_t on_message_reaction_remove_emoji; + + + /** + * @brief Called when multiple messages are deleted from a channel or DM. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_delete_bulk_t&, and returns void. + */ + event_router_t on_message_delete_bulk; + + + /** + * @brief Called when an existing role is updated on a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_role_update_t&, and returns void. + */ + event_router_t on_guild_role_update; + + + /** + * @brief Called when a role is deleted in a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_role_delete_t&, and returns void. + */ + event_router_t on_guild_role_delete; + + + /** + * @brief Called when a message is pinned. + * Note that the pinned message is not returned to this event, just the timestamp + * of the last pinned message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type channel_pins_update_t&, and returns void. + */ + event_router_t on_channel_pins_update; + + + /** + * @brief Called when all reactions are removed from a message. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_reaction_remove_all_t&, and returns void. + */ + event_router_t on_message_reaction_remove_all; + + + /** + * @brief Called when we are told which voice server we can use. + * This will be sent either when we establish a new voice channel connection, + * or as discord rearrange their infrastructure. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_server_update_t&, and returns void. + */ + event_router_t on_voice_server_update; + + + /** + * @brief Called when new emojis are added to a guild. + * The complete set of emojis is sent every time. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_emojis_update_t&, and returns void. + */ + event_router_t on_guild_emojis_update; + + + /** + * @brief Called when new stickers are added to a guild. + * The complete set of stickers is sent every time. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_stickers_update_t&, and returns void. + */ + event_router_t on_guild_stickers_update; + + + /** + * @brief Called when a user's presence is updated. + * To receive these you will need the GUILD_PRESENCES privileged intent. + * You will receive many of these, very often, and receiving them will significantly + * increase your bot's CPU usage. If you don't need them it is recommended to not ask + * for them. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type presence_update_t&, and returns void. + */ + event_router_t on_presence_update; + + + /** + * @brief Called when the webhooks for a guild are updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type webhooks_update_t&, and returns void. + */ + event_router_t on_webhooks_update; + + /** + * @brief Called when a new automod rule is created. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_create_t&, and returns void. + */ + event_router_t on_automod_rule_create; + + + /** + * @brief Called when an automod rule is updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_update_t&, and returns void. + */ + event_router_t on_automod_rule_update; + + /** + * @brief Called when an automod rule is deleted. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_delete_t&, and returns void. + */ + event_router_t on_automod_rule_delete; + + /** + * @brief Called when an automod rule is triggered/executed. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type automod_rule_execute_t&, and returns void. + */ + event_router_t on_automod_rule_execute; + + /** + * @brief Called when a new member joins a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_member_add_t&, and returns void. + */ + event_router_t on_guild_member_add; + + + /** + * @brief Called when an invite is deleted from a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type invite_delete_t&, and returns void. + */ + event_router_t on_invite_delete; + + + /** + * @brief Called when details of a guild are updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_update_t&, and returns void. + */ + event_router_t on_guild_update; + + + /** + * @brief Called when an integration is updated for a guild. + * This returns the complete list. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_integrations_update_t&, and returns void. + */ + event_router_t on_guild_integrations_update; + + + /** + * @brief Called when details of a guild member (e.g. their roles or nickname) are updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_member_update_t&, and returns void. + */ + event_router_t on_guild_member_update; + + + /** + * @brief Called when a new invite is created for a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type invite_create_t&, and returns void. + */ + event_router_t on_invite_create; + + + /** + * @brief Called when a message is updated (edited). + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_update_t&, and returns void. + */ + event_router_t on_message_update; + + + /** + * @brief Called when a user is updated. + * This is separate to cluster::on_guild_member_update and includes things such as an avatar change, + * username change, discriminator change or change in subscription status for nitro. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type user_update_t&, and returns void. + */ + event_router_t on_user_update; + + + /** + * @brief Called when a new message arrives from discord. + * Note that D++ does not cache messages. If you want to cache these objects you + * should create something yourself within your bot. Caching of messages is not on + * the roadmap to be supported as it consumes excessive amounts of RAM. + * For an example for caching of messages, please see \ref caching-messages + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type message_create_t&, and returns void. + */ + event_router_t on_message_create; + + + /** + * @brief Called when a ban is added to a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_ban_add_t&, and returns void. + */ + event_router_t on_guild_ban_add; + + + /** + * @brief Called when a ban is removed from a guild. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_ban_remove_t&, and returns void. + */ + event_router_t on_guild_ban_remove; + + + /** + * @brief Called when a new integration is attached to a guild by a user. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type integration_create_t&, and returns void. + */ + event_router_t on_integration_create; + + + /** + * @brief Called when an integration is updated by a user. + * This returns details of just the single integration that has changed. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type integration_update_t&, and returns void. + */ + event_router_t on_integration_update; + + + /** + * @brief Called when an integration is removed by a user. + * An integration is a connection to a guild of a user's associated accounts, + * e.g. youtube or twitch, for automatic assignment of roles etc. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type integration_delete_t&, and returns void. + */ + event_router_t on_integration_delete; + + + /** + * @brief Called when a thread is created. + * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_create_t&, and returns void. + */ + event_router_t on_thread_create; + + + /** + * @brief Called when a thread is updated + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_update_t&, and returns void. + */ + event_router_t on_thread_update; + + + /** + * @brief Called when a thread is deleted + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_delete_t&, and returns void. + */ + event_router_t on_thread_delete; + + + /** + * @brief Called when thread list is synced (upon gaining access to a channel). + * Note that threads are not cached by D++, but a list of thread IDs is accessible in a guild object + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_list_sync_t&, and returns void. + */ + event_router_t on_thread_list_sync; + + + /** + * @brief Called when current user's thread member object is updated + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_member_update_t&, and returns void. + */ + event_router_t on_thread_member_update; + + + /** + * @brief Called when a thread's member list is updated (without GUILD_MEMBERS intent, is only called for current user) + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type thread_members_update_t&, and returns void. + */ + event_router_t on_thread_members_update; + + + /** + * @brief Called when a new scheduled event is created + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_create_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_create; + + + /** + * @brief Called when a new scheduled event is updated + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_update_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_update; + + + /** + * @brief Called when a new scheduled event is deleted + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_delete_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_delete; + + + /** + * @brief Called when a user is added to a scheduled event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_add_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_user_add; + + + /** + * @brief Called when a user is removed to a scheduled event + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type guild_scheduled_event_user_remove_t&, and returns void. + */ + event_router_t on_guild_scheduled_event_user_remove; + + + /** + * @brief Called when packets are sent from the voice buffer. + * The voice buffer contains packets that are already encoded with Opus and encrypted + * with Sodium, and merged into packets by the repacketizer, which is done in the + * dpp::discord_voice_client::send_audio method. You should use the buffer size properties + * of dpp::voice_buffer_send_t to determine if you should fill the buffer with more + * content. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_buffer_send_t&, and returns void. + */ + event_router_t on_voice_buffer_send; + + + /** + * @brief Called when a user is talking on a voice channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_user_talking_t&, and returns void. + */ + event_router_t on_voice_user_talking; + + + /** + * @brief Called when a voice channel is connected and ready to send audio. + * Note that this is not directly attached to the READY event of the websocket, + * as there is further connection that needs to be done before audio is ready to send. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_ready_t&, and returns void. + */ + event_router_t on_voice_ready; + + + /** + * @brief Called when new audio data is received. + * Each separate user's audio from the voice channel will arrive tagged with + * their user id in the event, if a user can be attributed to the received audio. + * + * @note Receiving audio for bots is not officially supported by discord. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. + */ + event_router_t on_voice_receive; + + /** + * @brief Called when new audio data is received, combined and mixed for all speaking users. + * + * @note Receiving audio for bots is not officially supported by discord. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_receive_t&, and returns void. + */ + event_router_t on_voice_receive_combined; + + /** + * @brief Called when sending of audio passes over a track marker. + * Track markers are arbitrarily placed "bookmarks" in the audio buffer, placed + * by the bot developer. Each track marker can have a string value associated with it + * which is specified in dpp::discord_voice_client::insert_marker and returned to this + * event. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type voice_track_marker_t&, and returns void. + */ + event_router_t on_voice_track_marker; + + + /** + * @brief Called when a new stage instance is created on a stage channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * + */ + event_router_t on_stage_instance_create; + + + /** + * @brief Called when a stage instance is updated. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type stage_instance_update_t&, and returns void. + */ + event_router_t on_stage_instance_update; + + + /** + * @brief Called when an existing stage instance is deleted from a stage channel. + * + * @note Use operator() to attach a lambda to this event, and the detach method to detach the listener using the returned ID. + * The function signature for this event takes a single `const` reference of type stage_instance_delete_t&, and returns void. + */ + event_router_t on_stage_instance_delete; + + + /** + * @brief Post a REST request. Where possible use a helper method instead like message_create + * + * @param endpoint Endpoint to post to, e.g. /api/guilds + * @param major_parameters Major parameters for the endpoint e.g. a guild id + * @param parameters Minor parameters for the API request + * @param method Method, e.g. GET, POST + * @param postdata Post data (usually JSON encoded) + * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. + * @param filename Filename to post for POST requests (for uploading files) + * @param filecontent File content to post for POST requests (for uploading files) + */ + void post_rest(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::string &filename = "", const std::string &filecontent = ""); + + /** + * @brief Post a multipart REST request. Where possible use a helper method instead like message_create + * + * @param endpoint Endpoint to post to, e.g. /api/guilds + * @param major_parameters Major parameters for the endpoint e.g. a guild id + * @param parameters Minor parameters for the API request + * @param method Method, e.g. GET, POST + * @param postdata Post data (usually JSON encoded) + * @param callback Function to call when the HTTP call completes. The callback parameter will contain amongst other things, the decoded json. + * @param filename List of filenames to post for POST requests (for uploading files) + * @param filecontent List of file content to post for POST requests (for uploading files) + */ + void post_rest_multipart(const std::string &endpoint, const std::string &major_parameters, const std::string ¶meters, http_method method, const std::string &postdata, json_encode_t callback, const std::vector &filename = {}, const std::vector &filecontent = {}); + + /** + * @brief Make a HTTP(S) request. For use when wanting asynchronous access to HTTP APIs outside of Discord. + * + * @param url Full URL to post to, e.g. https://api.somewhere.com/v1/foo/ + * @param method Method, e.g. GET, POST + * @param callback Function to call when the HTTP call completes. No processing is done on the returned data. + * @param postdata POST data + * @param mimetype MIME type of POST data + * @param headers Headers to send with the request + */ + void request(const std::string &url, http_method method, http_completion_event callback, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}); + + /** + * @brief Respond to a slash command + * + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response + * @param interaction_id Interaction id to respond to + * @param token Token for the interaction webhook + * @param r Response to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit response to a slash command + * + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response + * @param token Token for the interaction webhook + * @param m Message to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_response_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a followup message to a slash command + * + * @param token Token for the interaction webhook + * @param m followup message to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_create(const std::string &token, const message &m, command_completion_event_t callback); + + /** + * @brief Edit original followup message to a slash command + * This is an alias for cluster::interaction_response_edit + * @see cluster::interaction_response_edit + * + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_edit_original(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief + * + * @param token Token for the interaction webhook + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_delete(const std::string &token, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit followup message to a slash command + * The message ID in the message you pass should be correctly set to that of a followup message you previously sent + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_edit(const std::string &token, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the followup message to a slash command + * @param token Token for the interaction webhook + * @param message_id message to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void interaction_followup_get(const std::string &token, snowflake message_id, command_completion_event_t callback); + + /** + * @brief Create a global slash command (a bot can have a maximum of 100 of these). + * + * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command + * @param s Slash command to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_create(const slashcommand &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a global slash command + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command + * @param id The ID of the slash command + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_get(snowflake id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the audit log for a guild + * + * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log + * @param guild_id Guild to get the audit log of + * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user + * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type + * @param before Entries that preceded a specific audit log entry ID. Used for paginating + * @param limit Maximum number of entries (between 1-100) to return + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::auditlog object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit, command_completion_event_t callback); + + /** + * @brief Create a slash command local to a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command + * @note Creating a command with the same name as an existing command for your application will overwrite the old command. + * @param s Slash command to create + * @param guild_id Guild ID to create the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_create(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + + /** + * @brief Create/overwrite guild slash commands. + * Any existing guild slash commands on this guild will be deleted and replaced with these. + * + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands + * @param commands Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_bulk_command_create(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create/overwrite global slash commands. + * Any existing global slash commands will be deleted and replaced with these. + * + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands + * @param commands Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_bulk_command_create(const std::vector &commands, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command + * @param s Slash command to change + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_edit(const slashcommand &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a slash command of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param id The ID of the slash command + * @param guild_id Guild ID to get the slash command from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_get(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a slash command local to a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_edit(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit slash command permissions of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions + * @note You can only add up to 10 permission overwrites for a command + * @param s Slash command to edit the permissions for + * @param guild_id Guild ID to edit the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_edit_permissions(const slashcommand &s, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the permissions for a slash command of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param id The ID of the slash command to get the permissions for + * @param guild_id Guild ID to get the permissions of + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_command_permissions object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_get_permissions(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit/Overwrite the permissions of all existing slash commands in a guild + * + * @note You can only add up to 10 permission overwrites for a command + * + * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions + * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. + * @param commands A vector of slash commands to edit/overwrite the permissions for + * @param guild_id Guild ID to edit permissions of the slash commands in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead + */ + void guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command + * @param id Slash command to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_command_delete(snowflake id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a slash command local to a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_command_delete(snowflake id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the application's slash commands for a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param guild_id Guild ID to get the slash commands for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_commands_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get all slash command permissions of a guild + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param guild_id Guild ID to get the slash commands permissions for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_command_permissions_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_commands_get_permissions(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get the application's global slash commands + * + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::slashcommand_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void global_commands_get(command_completion_event_t callback); + + /** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @see https://discord.com/developers/docs/resources/user#create-dm + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param user_id User ID of user to send message to + * @param m Message object + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void direct_message_create(snowflake user_id, const message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a message + * + * @see https://discord.com/developers/docs/resources/channel#get-channel-message + * @param message_id Message ID + * @param channel_id Channel ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get(snowflake message_id, snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Get multiple messages. + * + * This function will attempt to fetch as many messages as possible using multiple API calls if needed. + * + * @see https://discord.com/developers/docs/resources/channel#get-channel-messages + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages after this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned, up to a maximum of 100. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit, command_completion_event_t callback); + + /** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param m Message to send + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_create(const struct message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @see https://discord.com/developers/docs/resources/channel#crosspost-message + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_crosspost(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @see https://discord.com/developers/docs/resources/channel#edit-message + * @param m Message to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_edit(const struct message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add a reaction to a message. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/resources/channel#create-reaction + * @param m Message to add a reaction to + * @param reaction Reaction to add. Emojis should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_add_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete own reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction + * @param m Message to delete own reaction from + * @param reaction Reaction to delete. The reaction should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_own_reaction(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a user's reaction from a message. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction + * @param m Message to delete a user's reaction from + * @param user_id User ID who's reaction you want to remove + * @param reaction Reaction to remove. Reactions should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction(const struct message &m, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get reactions on a message for a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#get-reactions + * @param m Message to get reactions for + * @param reaction Reaction should be in the form emojiname:id or a unicode character + * @param before Reactions before this ID should be retrieved if this is set to non-zero + * @param after Reactions before this ID should be retrieved if this is set to non-zero + * @param limit This number of reactions maximum should be returned + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get_reactions(const struct message &m, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Delete all reactions on a message + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions + * @param m Message to delete reactions from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_all_reactions(const struct message &m, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete all reactions on a message using a particular emoji. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji + * @param m Message to delete reactions from + * @param reaction Reaction to delete, in the form emojiname:id or a unicode character + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction_emoji(const struct message &m, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add a reaction to a message by id. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/topics/gateway#message-reaction-add + * @param message_id Message to add reactions to + * @param channel_id Channel to add reactions to + * @param reaction Reaction to add. Emojis should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_add_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete own reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character. + * + * @see https://discord.com/developers/docs/resources/channel#delete-own-reaction + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param reaction Reaction to delete. The reaction should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_own_reaction(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a user's reaction from a message by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-user-reaction + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param user_id User ID who's reaction you want to remove + * @param reaction Reaction to remove. Reactions should be in the form emojiname:id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction(snowflake message_id, snowflake channel_id, snowflake user_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get reactions on a message for a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#get-reactions + * @param message_id Message to get reactions for + * @param channel_id Channel to get reactions for + * @param reaction Reaction should be in the form emojiname:id or a unicode character + * @param before Reactions before this ID should be retrieved if this is set to non-zero + * @param after Reactions before this ID should be retrieved if this is set to non-zero + * @param limit This number of reactions maximum should be returned + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_get_reactions(snowflake message_id, snowflake channel_id, const std::string &reaction, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Delete all reactions on a message by id + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_all_reactions(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete all reactions on a message using a particular emoji by id. The reaction string must be either an `emojiname:id` or a unicode character + * + * @see https://discord.com/developers/docs/resources/channel#delete-all-reactions-for-emoji + * @param message_id Message to delete reactions from + * @param channel_id Channel to delete reactions from + * @param reaction Reaction to delete, in the form emojiname:id or a unicode character + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_reaction_emoji(snowflake message_id, snowflake channel_id, const std::string &reaction, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/channel#delete-message + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete(snowflake message_id, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. + * + * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages + * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) + * @param channel_id Channel to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_delete_bulk(const std::vector &message_ids, snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a channel + * + * @see https://discord.com/developers/docs/resources/channel#get-channel + * @param c Channel ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_get(snowflake c, command_completion_event_t callback); + + /** + * @brief Get all channels for a guild + * + * @see https://discord.com/developers/docs/resources/channel#get-channels + * @param guild_id Guild ID to retrieve channels for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channels_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a channel + * + * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, + * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible + * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. + * + * All parameters to this endpoint are optional excluding `name` + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#create-channel + * @param c Channel to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_create(const class channel &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#modify-channel + * @param c Channel to edit/update + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit(const class channel &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit multiple channels positions + * + * Modify the positions of a set of channel objects for the guild. + * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. + * Only channels to be modified are required. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions + * @param c Channel to change the position for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit_positions(const std::vector &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a channel's permissions + * + * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param c Channel to set permissions for + * @param overwrite_id Overwrite to change (a user or role ID) + * @param allow allow permissions bitmask + * @param deny deny permissions bitmask + * @param member true if the overwrite_id is a user id, false if it is a channel id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit_permissions(const class channel &c, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a channel's permissions + * + * @see https://discord.com/developers/docs/resources/channel#edit-channel-permissions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id ID of the channel to set permissions for + * @param overwrite_id Overwrite to change (a user or role ID) + * @param allow allow permissions bitmask + * @param deny deny permissions bitmask + * @param member true if the overwrite_id is a user id, false if it is a channel id + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_edit_permissions(const snowflake channel_id, const snowflake overwrite_id, const uint64_t allow, const uint64_t deny, const bool member, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel + * @param channel_id Channel id to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_delete(snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get details about an invite + * + * @see https://discord.com/developers/docs/resources/invite#get-invite + * @param invite Invite code to get information on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void invite_get(const std::string &invite, command_completion_event_t callback); + + /** + * @brief Delete an invite + * + * @see https://discord.com/developers/docs/resources/invite#delete-invite + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param invite Invite code to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void invite_delete(const std::string &invite, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get invites for a channel + * + * @see https://discord.com/developers/docs/resources/invite#get-invites + * @param c Channel to get invites for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_invites_get(const class channel &c, command_completion_event_t callback); + + /** + * @brief Create invite for a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#create-channel-invite + * @param c Channel to create an invite on + * @param i Invite to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_invite_create(const class channel &c, const class invite &i, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a channel's pins + * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages + * @param channel_id Channel ID to get pins for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_pins_get(snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Adds a recipient to a Group DM using their access token + * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Removes a recipient from a Group DM + * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void gdm_remove(snowflake channel_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove a permission from a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_delete_permission(const class channel &c, snowflake overwrite_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Follow an announcement (news) channel + * @see https://discord.com/developers/docs/resources/channel#follow-news-channel + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_follow_news(const class channel &c, snowflake target_channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Trigger channel typing indicator + * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator + * @param c Channel to set as typing on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_typing(const class channel &c, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Trigger channel typing indicator + * @see https://discord.com/developers/docs/resources/channel#trigger-typing-indicator + * @param cid Channel ID to set as typing on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void channel_typing(snowflake cid, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Pin a message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/channel#pin-message + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_pin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Unpin a message + * @see https://discord.com/developers/docs/resources/channel#unpin-message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void message_unpin(snowflake channel_id, snowflake message_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a guild + * + * Returns the guild object for the given id. This endpoint will also return approximate_member_count and approximate_presence_count + * for the guild. + * @see https://discord.com/developers/docs/resources/guild#get-guild + * @param g Guild ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get(snowflake g, command_completion_event_t callback); + + /** + * @brief Get a guild preview. Returns a guild object but only a subset of the fields will be populated. + * + * Returns the guild preview object for the given id `g`. If the user is not in the guild, then the guild + * must be lurkable (it must be Discoverable or have a live public stage). + * @see https://discord.com/developers/docs/resources/guild#get-guild-preview + * @param g Guild ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_preview(snowflake g, command_completion_event_t callback); + + /** + * @brief Get a guild member + * @see https://discord.com/developers/docs/resources/guild#get-guild-member + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_member(snowflake guild_id, snowflake user_id, command_completion_event_t callback); + + /** + * @brief Search for guild members based on whether their username or nickname starts with the given string. + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see https://discord.com/developers/docs/resources/guild#search-guild-members + * @param guild_id Guild ID to search in + * @param query Query string to match username(s) and nickname(s) against + * @param limit max number of members to return (1-1000) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Get all guild members + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see https://discord.com/developers/docs/resources/guild#get-guild-members + * @param guild_id Guild ID to get all members for + * @param limit max number of members to return (1-1000) + * @param after the highest user id in the previous page + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_members(snowflake guild_id, uint16_t limit, snowflake after, command_completion_event_t callback); + + /** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. + * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. + * + * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. + * Members that are pending will have to complete membership screening before they become full members that can talk. + * + * @note All parameters to this endpoint except for access_token are optional. + * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. + * @see https://discord.com/developers/docs/resources/guild#add-guild-member + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_add_member(const guild_member& gm, const std::string &access_token, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit the properties of an existing guild member + * + * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. + * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. + * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param gm Guild member to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_edit_member(const guild_member& gm, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Moves the guild member to a other voice channel, if member is connected to one. + * Set the `channel_id` to `0` to disconnect the user. + * + * Fires a `Guild Member Update` Gateway event. + * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Change current user nickname + * + * Modifies the nickname of the current user in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick + * @param guild_id Guild ID to change nickname on + * @param nickname New nickname, or empty string to clear nickname + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_set_nickname(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add role to guild member + * + * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @deprecated Use dpp::cluster::guild_member_remove_role instead + */ + void guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @deprecated Replaced by dpp::cluster::guild_member_kick + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_kick(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Set the timeout of a guild member + * + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to timeout the member in + * @param user_id User ID to set the timeout for + * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add guild ban + * + * Create a guild ban, and optionally delete previous messages sent by the banned user. + * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. + * @see https://discord.com/developers/docs/resources/guild#create-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete guild ban + * + * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. + * Fires a Guild Ban Remove Gateway event. + * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_ban_delete(snowflake guild_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild ban list + * + * Requires the `BAN_MEMBERS` permission. + * @see https://discord.com/developers/docs/resources/guild#get-guild-bans + * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. + * @param guild_id Guild ID to get bans for + * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit + * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit + * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::ban_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit, command_completion_event_t callback); + + /** + * @brief Get single guild ban + * + * Requires the `BAN_MEMBERS` permission. + * @see https://discord.com/developers/docs/resources/guild#get-guild-ban + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::ban object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_ban(snowflake guild_id, snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get a template + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template + * @param code Template code + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void template_get(const std::string &code, command_completion_event_t callback); + + /** + * @brief Create a new guild based on a template. + * @note This endpoint can be used only by bots in less than 10 guilds. + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template + * @param code Template code to create guild from + * @param name Guild name to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_create_from_template(const std::string &code, const std::string &name, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild templates + * + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates + * @param guild_id Guild ID to get templates for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_templates_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Creates a template for the guild + * + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_create(snowflake guild_id, const std::string &name, const std::string &description, command_completion_event_t callback); + + /** + * @brief Syncs the template to the guild's current state. + * + * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_sync(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Modifies the template's metadata. + * + * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::dtemplate object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Deletes the template + * + * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_template_delete(snowflake guild_id, const std::string &code, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a guild + * + * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. + * + * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. + * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an + * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions + * in a channel when also passing in channels with the channels array. + * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within + * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to + * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. + * Category channels must be listed before any children. + * + * @see https://discord.com/developers/docs/resources/guild#create-guild + * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. + * @param g Guild to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_create(const class guild &g, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a guild + * + * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. + * Fires a `Guild Update Gateway` event. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param g Guild to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_edit(const class guild &g, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a guild + * + * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. + * + * @see https://discord.com/developers/docs/resources/guild#delete-guild + * @param guild_id Guild ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_delete(snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get all emojis for a guild + * + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis + * @param guild_id Guild ID to get emojis for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emojis_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get a single emoji + * + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_get(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback); + + /** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_create(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a single emoji. + * + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::emoji object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_edit(snowflake guild_id, const class emoji& newemoji, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a guild emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_emoji_delete(snowflake guild_id, snowflake emoji_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get prune counts + * + * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` + * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the + * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional + * roles will not. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback); + + /** + * @brief Begin guild prune + * + * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members + * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing + * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. + * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` + * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. + * + * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::prune object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild voice regions. + * + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when + * the guild is VIP-enabled. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions + * @param guild_id Guild ID to get voice regions for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_voice_regions(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get guild invites + * + * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-invites + * @param guild_id Guild ID to get invites for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_invites(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get guild integrations + * + * Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations + * @param guild_id Guild ID to get integrations for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::integration_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_integrations(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Modify guild integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::integration object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_modify_integration(snowflake guild_id, const class integration &i, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete guild integration + * + * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. + * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_delete_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Sync guild integration + * + * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sync_integration(snowflake guild_id, snowflake integration_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-widget + * @param guild_id Guild ID to get widget for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_widget(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Edit guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_widget object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_edit_widget(snowflake guild_id, const class guild_widget &gw, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild vanity url, if enabled + * + * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. + * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url + * @param guild_id Guild to get vanity URL for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::invite object in confirmation_callback_t::value filled to match the vanity url. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_get_vanity(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/webhook#create-webhook + * @param w Webhook to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void create_webhook(const class webhook &w, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get guild webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param guild_id Guild ID to get webhooks for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_guild_webhooks(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get channel webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param channel_id Channel ID to get webhooks for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_channel_webhooks(snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Get webhook + * @see https://discord.com/developers/docs/resources/webhook#get-webhook + * @param webhook_id Webhook ID to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_webhook(snowflake webhook_id, command_completion_event_t callback); + + /** + * @brief Get webhook using token + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback); + + /** + * @brief Edit webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook + * @param wh Webhook to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_webhook(const class webhook& wh, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token + * @param wh Webhook to edit (should include token) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::webhook object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_webhook_with_token(const class webhook& wh, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook + * @param webhook_id Webhook ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_webhook(snowflake webhook_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete webhook with token + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_webhook_with_token(snowflake webhook_id, const std::string &token, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Execute webhook + * + * @see https://discord.com/developers/docs/resources/webhook#execute-webhook + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) + * @param callback Function to call when the API call completes. + * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void execute_webhook(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = "", command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get webhook message + * + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message + * @param wh Webhook to get the original message for + * @param message_id The message ID + * @param thread_id ID of the thread the message is in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit webhook message + * + * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on + * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit + * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to + * whether or not an allowed_mentions was present in the request that originally created the message. + * + * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message + * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. + * @param wh Webhook to edit message for + * @param m New message + * @param thread_id ID of the thread the message is in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_webhook_message(const class webhook &wh, const struct message &m, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete webhook message + * + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param thread_id ID of the thread the message is in + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id = 0, command_completion_event_t callback = utility::log_error()); + + + /** + * @brief Get a role for a guild + * + * @see https://discord.com/developers/docs/resources/guild#get-guild-roles + * @param guild_id Guild ID to get role for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void roles_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Create a role on a guild + * + * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. + * Fires a `Guild Role Create` Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#create-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to create (guild ID is encapsulated in the role object) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void role_create(const class role &r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit a role on a guild + * + * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to edit + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void role_edit(const class role &r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. + * + * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. + * Fires multiple `Guild Role Update` Gateway events. + * + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to change the roles position on + * @param roles Vector of roles to change the positions of + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::role_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void roles_edit_position(snowflake guild_id, const std::vector &roles, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a role + * + * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. + * + * @see https://discord.com/developers/docs/resources/guild#delete-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void role_delete(snowflake guild_id, snowflake role_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the application's role connection metadata records + * + * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#get-application-role-connection-metadata-records + * @param application_id The application ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void application_role_connection_get(snowflake application_id, command_completion_event_t callback); + + /** + * @brief Update the application's role connection metadata records + * + * @see https://discord.com/developers/docs/resources/application-role-connection-metadata#update-application-role-connection-metadata-records + * @param application_id The application ID + * @param connection_metadata The application role connection metadata to update + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection_metadata_list object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note An application can have a maximum of 5 metadata records. + */ + void application_role_connection_update(snowflake application_id, const std::vector &connection_metadata, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get user application role connection + * + * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection + * @param application_id The application ID + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void user_application_role_connection_get(snowflake application_id, command_completion_event_t callback); + + /** + * @brief Update user application role connection + * + * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection + * @param application_id The application ID + * @param connection The application role connection to update + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application_role_connection object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void user_application_role_connection_update(snowflake application_id, const application_role_connection &connection, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a user by id + * + * @see https://discord.com/developers/docs/resources/user#get-user + * @param user_id User ID to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. + * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. + */ + void user_get(snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get current (bot) user + * + * @see https://discord.com/developers/docs/resources/user#get-current-user + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user_identified object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + */ + void current_user_get(command_completion_event_t callback); + + /** + * @brief Get current (bot) application + * + * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::application object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_application_get(command_completion_event_t callback); + + /** + * @brief Modify current member + * + * Modifies the current member in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/guild#modify-current-member + * @param guild_id Guild ID to change on + * @param nickname New nickname, or empty string to clear nickname + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_current_member_edit(snowflake guild_id, const std::string &nickname, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get current user's connections (linked accounts, e.g. steam, xbox). + * This call requires the oauth2 `connections` scope and cannot be executed + * against a bot token. + * @see https://discord.com/developers/docs/resources/user#get-user-connections + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::connection_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_connections_get(command_completion_event_t callback); + + /** + * @brief Get current (bot) user guilds + * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::guild_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_get_guilds(command_completion_event_t callback); + + /** + * @brief Edit current (bot) user + * + * Modifies the current member in a guild. Returns the updated guild_member object on success. + * Fires a `Guild Member Update` Gateway event. + * @see https://discord.com/developers/docs/resources/user#modify-current-user + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::user object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + */ + void current_user_edit(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get current user DM channels + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_get_dms(command_completion_event_t callback); + + /** + * @brief Create a dm channel + * @see https://discord.com/developers/docs/resources/user#create-dm + * @param user_id User ID to create DM channel with + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::channel object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void create_dm_channel(snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Leave a guild + * @see https://discord.com/developers/docs/resources/user#leave-guild + * @param guild_id Guild ID to leave + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_leave_guild(snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a thread in forum channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel + * @param thread_name Name of the forum thread + * @param channel_id Forum channel in which thread to create + * @param msg The message to start the thread with + * @param auto_archive_duration Duration to automatically archive the thread after recent activity + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_create_in_forum(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a thread + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see https://discord.com/developers/docs/resources/guild#create-guild-channel + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD + * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/topics/threads + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::thread object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Join a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to join + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_join_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Leave a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to leave + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void current_user_leave_thread(snowflake thread_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Add a member to a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_member_add(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Remove a member from a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_member_remove(snowflake thread_id, snowflake user_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a thread member + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get member for + * @param user_id ID of the user to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_member object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_member_get(const snowflake thread_id, const snowflake user_id, command_completion_event_t callback); + + /** + * @brief Get members of a thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get members for + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thread_members_get(snowflake thread_id, command_completion_event_t callback); + + /** + * @brief Get active threads in a guild (Sorted by ID in descending order) + * @see https://discord.com/developers/docs/topics/threads + * @param guild_id Guild to get active threads for + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_active(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + * @param callback Function to call when the API call completes + * On success the callback will contain a dpp::thread_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit, command_completion_event_t callback); + + /** + * @brief Create a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker + * @param s Sticker to create. Must have its guild ID set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_create(sticker &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Modify a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_modify(sticker &s, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a sticker from a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_delete(snowflake sticker_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a nitro sticker + * @see https://discord.com/developers/docs/resources/sticker#get-sticker + * @param id Id of sticker to get. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void nitro_sticker_get(snowflake id, command_completion_event_t callback); + + /** + * @brief Get a guild sticker + * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_sticker_get(snowflake id, snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get all guild stickers + * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers + * @param guild_id Guild ID of the guild where the sticker is + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_stickers_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get sticker packs + * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::sticker_pack_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void sticker_packs_get(command_completion_event_t callback); + + /** + * @brief Create a stage instance on a stage channel. + * @see https://discord.com/developers/docs/resources/stage-instance#create-stage-instance + * @param instance Stage instance to create + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + */ + void stage_instance_create(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get the stage instance associated with the channel id, if it exists. + * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance + * @param channel_id ID of the associated channel + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void stage_instance_get(const snowflake channel_id, command_completion_event_t callback); + + /** + * @brief Edit a stage instance. + * @see https://discord.com/developers/docs/resources/stage-instance#modify-stage-instance + * @param instance Stage instance to edit + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::stage_instance object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + */ + void stage_instance_edit(const stage_instance& instance, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a stage instance. + * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance + * @param channel_id ID of the associated channel + * @param callback User function to execute when the api call completes + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + */ + void stage_instance_delete(const snowflake channel_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get all voice regions + * @see https://discord.com/developers/docs/resources/voice#list-voice-regions + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::voiceregion_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_voice_regions(command_completion_event_t callback); + + /** + * @brief Get the gateway information for the bot using the token + * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::gateway object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_gateway_bot(command_completion_event_t callback); + + /** + * @brief Get all scheduled events for a guild + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild + * @param guild_id Guild to get events for + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_events_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get users RSVP'd to an event + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event-users + * @param guild_id Guild to get user list for + * @param event_id Guild to get user list for + * @param limit Maximum number of results to return + * @param before Return user IDs that fall before this ID, if provided + * @param after Return user IDs that fall after this ID, if provided + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::event_member_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_users_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback, uint8_t limit = 100, snowflake before = 0, snowflake after = 0); + + /** + * @brief Create a scheduled event on a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event + * @param event Event to create (guild ID must be populated) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_create(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete a scheduled event from a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event + * @param event_id Event ID to delete + * @param guild_id Guild ID of event to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_delete(snowflake event_id, snowflake guild_id, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit/modify a scheduled event on a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event + * @param event Event to create (event ID and guild ID must be populated) + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_edit(const scheduled_event& event, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get a scheduled event for a guild + * + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event + * @param guild_id Guild to get event for + * @param event_id Event ID to get + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void guild_event_get(snowflake guild_id, snowflake event_id, command_completion_event_t callback); + + /** + * @brief Set the bot's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - current user must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. + * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. + * - You are able to set `request_to_speak_timestamp` to any present or future time. + * + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @param callback Function to call when the API call completes. + * @param suppress True if the user's audio should be suppressed, false if it should not + * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. + * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. + */ + void current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Set a user's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - User must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) + * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. + * - When suppressed, the user will have their `request_to_speak_timestamp` removed. + * + * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state + * @param user_id The user to set the voice state of + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @param callback Function to call when the API call completes. + * @param suppress True if the user's audio should be suppressed, false if it should not + * On success the callback will contain a dpp::scheduled_event object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Get all auto moderation rules for a guild + * + * @param guild_id Guild id of the auto moderation rule + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule_map object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rules_get(snowflake guild_id, command_completion_event_t callback); + + /** + * @brief Get a single auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Rule id to retrieve + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_get(snowflake guild_id, snowflake rule_id, command_completion_event_t callback); + + /** + * @brief Create an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to create + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_create(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Edit an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to edit. The rule's id must be set. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::automod_rule object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_edit(snowflake guild_id, const automod_rule& r, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Delete an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Auto moderation rule id to delete + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void automod_rule_delete(snowflake guild_id, snowflake rule_id, command_completion_event_t callback = utility::log_error()); + +#include +#ifdef DPP_CORO +#include +#endif + +}; + +}; diff --git a/3rdParty/dpp/cluster_coro_calls.h b/3rdParty/dpp/cluster_coro_calls.h index 46b305a519..aaf4afa6f7 100644 --- a/3rdParty/dpp/cluster_coro_calls.h +++ b/3rdParty/dpp/cluster_coro_calls.h @@ -1,2316 +1,2316 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - - -/* Auto @generated by buildtools/make_coro_struct.php. - * - * DO NOT EDIT BY HAND! - * - * To re-generate this header file re-run the script! - */ -/** - * @brief Create/overwrite global slash commands. - * Any existing global slash commands will be deleted and replaced with these. - * - * @see dpp::cluster::global_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands - * @param commands Vector of slash commands to create/update. - * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. - * Commands that do not already exist will count toward daily application command create limits. - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_bulk_command_create(const std::vector &commands) { - return dpp::awaitable(this, [&] (auto cc) { this->global_bulk_command_create(commands, cc); }); -} - -/** - * @brief Create a global slash command (a bot can have a maximum of 100 of these). - * - * @see dpp::cluster::global_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command - * @param s Slash command to create - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_create(const slashcommand &s) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_create(s, cc); }); -} - -/** - * @brief Get a global slash command - * - * @see dpp::cluster::global_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command - * @param id The ID of the slash command - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_get(snowflake id) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_get(id, cc); }); -} - -/** - * @brief Delete a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command - * @param id Slash command to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_delete(snowflake id) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_delete(id, cc); }); -} - -/** - * @brief Edit a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command - * @param s Slash command to change - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_command_edit(const slashcommand &s) { - return dpp::awaitable(this, [&] (auto cc) { this->global_command_edit(s, cc); }); -} - -/** - * @brief Get the application's global slash commands - * - * @see dpp::cluster::global_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_global_commands_get() { - return dpp::awaitable(this, [&] (auto cc) { this->global_commands_get(cc); }); -} - -/** - * @brief Create/overwrite guild slash commands. - * Any existing guild slash commands on this guild will be deleted and replaced with these. - * - * @see dpp::cluster::guild_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands - * @param commands Vector of slash commands to create/update. - * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. - * @param guild_id Guild ID to create/update the slash commands in - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_bulk_command_create(const std::vector &commands, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_create(commands, guild_id, cc); }); -} - -/** - * @brief Get all slash command permissions of a guild - * - * @see dpp::cluster::guild_commands_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param guild_id Guild ID to get the slash commands permissions for - * @return guild_command_permissions_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_commands_get_permissions(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get_permissions(guild_id, cc); }); -} - -/** - * @brief Edit/Overwrite the permissions of all existing slash commands in a guild - * - * @note You can only add up to 10 permission overwrites for a command - * - * @see dpp::cluster::guild_bulk_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions - * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. - * @param commands A vector of slash commands to edit/overwrite the permissions for - * @param guild_id Guild ID to edit permissions of the slash commands in - * @return guild_command_permissions_map returned object on completion - * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead - * \memberof dpp::cluster - */ -auto inline co_guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_edit_permissions(commands, guild_id, cc); }); -} - -/** - * @brief Create a slash command local to a guild - * - * @see dpp::cluster::guild_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command - * @note Creating a command with the same name as an existing command for your application will overwrite the old command. - * @param s Slash command to create - * @param guild_id Guild ID to create the slash command in - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_create(const slashcommand &s, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_create(s, guild_id, cc); }); -} - -/** - * @brief Delete a slash command local to a guild - * - * @see dpp::cluster::guild_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command - * @param id Slash command to delete - * @param guild_id Guild ID to delete the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_delete(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_delete(id, guild_id, cc); }); -} - -/** - * @brief Edit slash command permissions of a guild - * - * @see dpp::cluster::guild_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions - * @note You can only add up to 10 permission overwrites for a command - * @param s Slash command to edit the permissions for - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_edit_permissions(const slashcommand &s, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit_permissions(s, guild_id, cc); }); -} - -/** - * @brief Get a slash command of a guild - * - * @see dpp::cluster::guild_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param id The ID of the slash command - * @param guild_id Guild ID to get the slash command from - * @return slashcommand returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_get(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get(id, guild_id, cc); }); -} - -/** - * @brief Get the permissions for a slash command of a guild - * - * @see dpp::cluster::guild_command_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param id The ID of the slash command to get the permissions for - * @param guild_id Guild ID to get the permissions of - * @return guild_command_permissions returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_get_permissions(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get_permissions(id, guild_id, cc); }); -} - -/** - * @brief Edit a slash command local to a guild - * - * @see dpp::cluster::guild_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command - * @param s Slash command to edit - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_command_edit(const slashcommand &s, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit(s, guild_id, cc); }); -} - -/** - * @brief Get the application's slash commands for a guild - * - * @see dpp::cluster::guild_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param guild_id Guild ID to get the slash commands for - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_commands_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get(guild_id, cc); }); -} - -/** - * @brief Respond to a slash command - * - * @see dpp::cluster::interaction_response_create - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response - * @param interaction_id Interaction id to respond to - * @param token Token for the interaction webhook - * @param r Response to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_create(interaction_id, token, r, cc); }); -} - -/** - * @brief Edit response to a slash command - * - * @see dpp::cluster::interaction_response_edit - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response - * @param token Token for the interaction webhook - * @param m Message to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_response_edit(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_edit(token, m, cc); }); -} - -/** - * @brief Create a followup message to a slash command - * - * @param token Token for the interaction webhook - * @param m followup message to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_create(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_create(token, m, cc); }); -} - -/** - * @brief Edit original followup message to a slash command - * This is an alias for cluster::interaction_response_edit - * @see dpp::cluster::interaction_followup_edit_original - * @see cluster::interaction_response_edit - * - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_edit_original(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit_original(token, m, cc); }); -} - -/** - * @brief - * - * @param token Token for the interaction webhook - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_delete(const std::string &token) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_delete(token, cc); }); -} - -/** - * @brief Edit followup message to a slash command - * The message ID in the message you pass should be correctly set to that of a followup message you previously sent - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_edit(const std::string &token, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit(token, m, cc); }); -} - -/** - * @brief Get the followup message to a slash command - * @param token Token for the interaction webhook - * @param message_id message to retrieve - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_interaction_followup_get(const std::string &token, snowflake message_id) { - return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_get(token, message_id, cc); }); -} - -/** - * @brief Get all auto moderation rules for a guild - * - * @param guild_id Guild id of the auto moderation rule - * @return automod_rule_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rules_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rules_get(guild_id, cc); }); -} - -/** - * @brief Get a single auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Rule id to retrieve - * @return automod_rule returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_get(snowflake guild_id, snowflake rule_id) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_get(guild_id, rule_id, cc); }); -} - -/** - * @brief Create an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to create - * @return automod_rule returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_create(snowflake guild_id, const automod_rule& r) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_create(guild_id, r, cc); }); -} - -/** - * @brief Edit an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to edit. The rule's id must be set. - * @return automod_rule returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_edit(snowflake guild_id, const automod_rule& r) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_edit(guild_id, r, cc); }); -} - -/** - * @brief Delete an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Auto moderation rule id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_automod_rule_delete(snowflake guild_id, snowflake rule_id) { - return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_delete(guild_id, rule_id, cc); }); -} - -/** - * @brief Create a channel - * - * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, - * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible - * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. - * - * All parameters to this endpoint are optional excluding `name` - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_create - * @see https://discord.com/developers/docs/resources/channel#create-channel - * @param c Channel to create - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_create(const class channel &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_create(c, cc); }); -} - -/** - * @brief Remove a permission from a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete_permission - * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission - * @param c Channel to remove permission from - * @param overwrite_id Overwrite to remove, user or channel ID - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_delete_permission(const class channel &c, snowflake overwrite_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_delete_permission(c, overwrite_id, cc); }); -} - -/** - * @brief Delete a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete - * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel - * @param channel_id Channel id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_delete(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_delete(channel_id, cc); }); -} - -/** - * @brief Edit multiple channels positions - * - * Modify the positions of a set of channel objects for the guild. - * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. - * Only channels to be modified are required. - * - * @see dpp::cluster::channel_edit_positions - * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions - * @param c Channel to change the position for - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_edit_positions(const std::vector &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_edit_positions(c, cc); }); -} - -/** - * @brief Edit a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_edit - * @see https://discord.com/developers/docs/resources/channel#modify-channel - * @param c Channel to edit/update - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_edit(const class channel &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_edit(c, cc); }); -} - -/** - * @brief Follow an announcement (news) channel - * @see dpp::cluster::channel_follow_news - * @see https://discord.com/developers/docs/resources/channel#follow-news-channel - * @param c Channel id to follow - * @param target_channel_id Channel to subscribe the channel to - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_follow_news(const class channel &c, snowflake target_channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_follow_news(c, target_channel_id, cc); }); -} - -/** - * @brief Get a channel - * - * @see dpp::cluster::channel_get - * @see https://discord.com/developers/docs/resources/channel#get-channel - * @param c Channel ID to retrieve - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_get(snowflake c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_get(c, cc); }); -} - -/** - * @brief Create invite for a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_invite_create - * @see https://discord.com/developers/docs/resources/channel#create-channel-invite - * @param c Channel to create an invite on - * @param i Invite to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_invite_create(const class channel &c, const class invite &i) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_invite_create(c, i, cc); }); -} - -/** - * @brief Get invites for a channel - * - * @see dpp::cluster::channel_invites_get - * @see https://discord.com/developers/docs/resources/invite#get-invites - * @param c Channel to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_invites_get(const class channel &c) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_invites_get(c, cc); }); -} - -/** - * @brief Get all channels for a guild - * - * @see dpp::cluster::channels_get - * @see https://discord.com/developers/docs/resources/channel#get-channels - * @param guild_id Guild ID to retrieve channels for - * @return channel_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channels_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channels_get(guild_id, cc); }); -} - -/** - * @brief Create a dm channel - * @see dpp::cluster::create_dm_channel - * @see https://discord.com/developers/docs/resources/user#create-dm - * @param user_id User ID to create DM channel with - * @return channel returned object on completion - * \memberof dpp::cluster - */ -auto inline co_create_dm_channel(snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->create_dm_channel(user_id, cc); }); -} - -/** - * @brief Get current user DM channels - * - * @return channel_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_get_dms() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_dms(cc); }); -} - -/** - * @brief Create a direct message, also create the channel for the direct message if needed - * - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/user#create-dm - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param user_id User ID of user to send message to - * @param m Message object - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_direct_message_create(snowflake user_id, const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->direct_message_create(user_id, m, cc); }); -} - -/** - * @brief Adds a recipient to a Group DM using their access token - * @see dpp::cluster::gdm_add - * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient - * @param channel_id Channel id to add group DM recipients to - * @param user_id User ID to add - * @param access_token Access token from OAuth2 - * @param nick Nickname of user to apply to the chat - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick) { - return dpp::awaitable(this, [&] (auto cc) { this->gdm_add(channel_id, user_id, access_token, nick, cc); }); -} - -/** - * @brief Removes a recipient from a Group DM - * @see dpp::cluster::gdm_remove - * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient - * @param channel_id Channel ID of group DM - * @param user_id User ID to remove from group DM - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_gdm_remove(snowflake channel_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->gdm_remove(channel_id, user_id, cc); }); -} - -/** - * @brief Create single emoji. - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_create - * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji - * @param guild_id Guild ID to create emoji om - * @param newemoji Emoji to create - * @return emoji returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_create(snowflake guild_id, const class emoji& newemoji) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_create(guild_id, newemoji, cc); }); -} - -/** - * @brief Delete a guild emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_delete - * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji - * @param guild_id Guild ID to delete emoji on - * @param emoji_id Emoji ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_delete(snowflake guild_id, snowflake emoji_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_delete(guild_id, emoji_id, cc); }); -} - -/** - * @brief Edit a single emoji. - * - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @see dpp::cluster::guild_emoji_edit - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit emoji on - * @param newemoji Emoji to edit - * @return emoji returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_edit(snowflake guild_id, const class emoji& newemoji) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_edit(guild_id, newemoji, cc); }); -} - -/** - * @brief Get a single emoji - * - * @see dpp::cluster::guild_emoji_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @param guild_id Guild ID to get emoji for - * @param emoji_id Emoji ID to get - * @return emoji returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emoji_get(snowflake guild_id, snowflake emoji_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_get(guild_id, emoji_id, cc); }); -} - -/** - * @brief Get all emojis for a guild - * - * @see dpp::cluster::guild_emojis_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis - * @param guild_id Guild ID to get emojis for - * @return emoji_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_emojis_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_emojis_get(guild_id, cc); }); -} - -/** - * @brief Get the gateway information for the bot using the token - * @see dpp::cluster::get_gateway_bot - * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot - * @return gateway returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_gateway_bot() { - return dpp::awaitable(this, [&] (auto cc) { this->get_gateway_bot(cc); }); -} - -/** - * @brief Modify current member - * - * Modifies the current member in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_current_member_edit - * @see https://discord.com/developers/docs/resources/guild#modify-current-member - * @param guild_id Guild ID to change on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_current_member_edit(snowflake guild_id, const std::string &nickname) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_current_member_edit(guild_id, nickname, cc); }); -} - -/** - * @brief Get the audit log for a guild - * - * @see dpp::cluster::guild_auditlog_get - * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log - * @param guild_id Guild to get the audit log of - * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user - * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type - * @param before Entries that preceded a specific audit log entry ID. Used for paginating - * @param limit Maximum number of entries (between 1-100) to return - * @return auditlog returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_auditlog_get(guild_id, user_id, action_type, before, limit, cc); }); -} - -/** - * @brief Add guild ban - * - * Create a guild ban, and optionally delete previous messages sent by the banned user. - * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. - * @see dpp::cluster::guild_ban_add - * @see https://discord.com/developers/docs/resources/guild#create-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add ban to - * @param user_id User ID to ban - * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_add(guild_id, user_id, delete_message_seconds, cc); }); -} - -/** - * @brief Delete guild ban - * - * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. - * Fires a Guild Ban Remove Gateway event. - * @see dpp::cluster::guild_ban_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild to delete ban from - * @param user_id User ID to delete ban for - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_ban_delete(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_delete(guild_id, user_id, cc); }); -} - -/** - * @brief Create a guild - * - * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. - * - * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. - * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an - * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions - * in a channel when also passing in channels with the channels array. - * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within - * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to - * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. - * Category channels must be listed before any children. - * - * @see dpp::cluster::guild_create - * @see https://discord.com/developers/docs/resources/guild#create-guild - * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. - * @param g Guild to create - * @return guild returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_create(const class guild &g) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_create(g, cc); }); -} - -/** - * @brief Delete a guild - * - * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. - * - * @see dpp::cluster::guild_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild - * @param guild_id Guild ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_delete(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_delete(guild_id, cc); }); -} - -/** - * @brief Delete guild integration - * - * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. - * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. - * - * @see dpp::cluster::guild_delete_integration - * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete integration for - * @param integration_id Integration ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_delete_integration(snowflake guild_id, snowflake integration_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_delete_integration(guild_id, integration_id, cc); }); -} - -/** - * @brief Edit a guild - * - * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. - * Fires a `Guild Update Gateway` event. - * - * @see dpp::cluster::guild_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param g Guild to edit - * @return guild returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_edit(const class guild &g) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_edit(g, cc); }); -} - -/** - * @brief Edit guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_edit_widget - * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit widget for - * @param gw New guild widget information - * @return guild_widget returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_edit_widget(snowflake guild_id, const class guild_widget &gw) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_widget(guild_id, gw, cc); }); -} - -/** - * @brief Get single guild ban - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_ban - * @see https://discord.com/developers/docs/resources/guild#get-guild-ban - * @param guild_id Guild ID to get ban for - * @param user_id User ID of ban to retrieve - * @return ban returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_ban(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_ban(guild_id, user_id, cc); }); -} - -/** - * @brief Get guild ban list - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_bans - * @see https://discord.com/developers/docs/resources/guild#get-guild-bans - * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. - * @param guild_id Guild ID to get bans for - * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit - * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit - * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 - * @return ban_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_bans(guild_id, before, after, limit, cc); }); -} - - -auto inline co_guild_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get(guild_id, cc); }); -} - -/** - * @brief Get guild integrations - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_integrations - * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations - * @param guild_id Guild ID to get integrations for - * @return integration_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_integrations(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_integrations(guild_id, cc); }); -} - - -auto inline co_guild_get_preview(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_preview(guild_id, cc); }); -} - -/** - * @brief Get guild vanity url, if enabled - * - * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. - * @see dpp::cluster::guild_get_vanity - * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url - * @param guild_id Guild to get vanity URL for - * @return invite returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_vanity(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_vanity(guild_id, cc); }); -} - -/** - * @brief Get guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_widget - * @see https://discord.com/developers/docs/resources/guild#get-guild-widget - * @param guild_id Guild ID to get widget for - * @return guild_widget returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_widget(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_widget(guild_id, cc); }); -} - -/** - * @brief Modify guild integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_modify_integration - * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration - * @param guild_id Guild ID to modify integration for - * @param i Integration to modify - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_modify_integration(snowflake guild_id, const class integration &i) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_modify_integration(guild_id, i, cc); }); -} - -/** - * @brief Get prune counts - * - * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` - * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the - * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional - * roles will not. - * - * @see dpp::cluster::guild_get_prune_counts - * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count - * @param guild_id Guild ID to count for pruning - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_prune_counts(guild_id, pruneinfo, cc); }); -} - -/** - * @brief Begin guild prune - * - * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members - * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing - * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. - * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` - * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. - * - * @see dpp::cluster::guild_begin_prune - * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to prune - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_begin_prune(guild_id, pruneinfo, cc); }); -} - -/** - * @brief Change current user nickname - * - * Modifies the nickname of the current user in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_set_nickname - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick - * @param guild_id Guild ID to change nickname on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_set_nickname(snowflake guild_id, const std::string &nickname) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_set_nickname(guild_id, nickname, cc); }); -} - -/** - * @brief Sync guild integration - * - * @see dpp::cluster::guild_sync_integration - * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration - * @param guild_id Guild ID to sync integration on - * @param integration_id Integration ID to synchronise - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sync_integration(snowflake guild_id, snowflake integration_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sync_integration(guild_id, integration_id, cc); }); -} - -/** - * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. - * - * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. - * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. - * - * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. - * Members that are pending will have to complete membership screening before they become full members that can talk. - * - * @note All parameters to this endpoint except for access_token are optional. - * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. - * @see dpp::cluster::guild_add_member - * @see https://discord.com/developers/docs/resources/guild#add-guild-member - * @param gm Guild member to add - * @param access_token Access token from Oauth2 scope - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_add_member(const guild_member& gm, const std::string &access_token) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_add_member(gm, access_token, cc); }); -} - -/** - * @brief Edit the properties of an existing guild member - * - * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. - * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. - * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. - * @see dpp::cluster::guild_edit_member - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param gm Guild member to edit - * @return guild_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_edit_member(const guild_member& gm) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_member(gm, cc); }); -} - -/** - * @brief Get a guild member - * @see dpp::cluster::guild_get_member - * @see https://discord.com/developers/docs/resources/guild#get-guild-member - * @param guild_id Guild ID to get member for - * @param user_id User ID of member to get - * @return guild_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_member(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_member(guild_id, user_id, cc); }); -} - -/** - * @brief Get all guild members - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_get_members - * @see https://discord.com/developers/docs/resources/guild#get-guild-members - * @param guild_id Guild ID to get all members for - * @param limit max number of members to return (1-1000) - * @param after the highest user id in the previous page - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_members(snowflake guild_id, uint16_t limit, snowflake after) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_members(guild_id, limit, after, cc); }); -} - -/** - * @brief Add role to guild member - * - * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_add_role - * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add a role to - * @param user_id User ID to add role to - * @param role_id Role ID to add to the user - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_add_role(guild_id, user_id, role_id, cc); }); -} - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @deprecated Replaced by dpp::cluster::guild_member_kick - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_delete(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete(guild_id, user_id, cc); }); -} - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_kick - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_kick(snowflake guild_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_kick(guild_id, user_id, cc); }); -} - -/** - * @brief Set the timeout of a guild member - * - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_timeout - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to timeout the member in - * @param user_id User ID to set the timeout for - * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_timeout(guild_id, user_id, communication_disabled_until, cc); }); -} - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_delete_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * @deprecated Use dpp::cluster::guild_member_remove_role instead - * \memberof dpp::cluster - */ -auto inline co_guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete_role(guild_id, user_id, role_id, cc); }); -} - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_remove_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_remove_role(guild_id, user_id, role_id, cc); }); -} - -/** - * @brief Moves the guild member to a other voice channel, if member is connected to one. - * Set the `channel_id` to `0` to disconnect the user. - * - * Fires a `Guild Member Update` Gateway event. - * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_member_move - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user - * @param guild_id Guild id to which the user is connected - * @param user_id User id, who should be moved - * @return guild_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_member_move(channel_id, guild_id, user_id, cc); }); -} - -/** - * @brief Search for guild members based on whether their username or nickname starts with the given string. - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_search_members - * @see https://discord.com/developers/docs/resources/guild#search-guild-members - * @param guild_id Guild ID to search in - * @param query Query string to match username(s) and nickname(s) against - * @param limit max number of members to return (1-1000) - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_search_members(guild_id, query, limit, cc); }); -} - -/** - * @brief Get guild invites - * - * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_invites - * @see https://discord.com/developers/docs/resources/guild#get-guild-invites - * @param guild_id Guild ID to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_invites(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_invites(guild_id, cc); }); -} - - -auto inline co_invite_delete(const std::string &invitecode) { - return dpp::awaitable(this, [&] (auto cc) { this->invite_delete(invitecode, cc); }); -} - - -auto inline co_invite_get(const std::string &invitecode) { - return dpp::awaitable(this, [&] (auto cc) { this->invite_get(invitecode, cc); }); -} - -/** - * @brief Send a message to a channel. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param m Message to send - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_create(const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->message_create(m, cc); }); -} - -/** - * @brief Crosspost a message. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_crosspost - * @see https://discord.com/developers/docs/resources/channel#crosspost-message - * @param message_id Message to crosspost - * @param channel_id Channel ID to crosspost from - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_crosspost(snowflake message_id, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_crosspost(message_id, channel_id, cc); }); -} - -/** - * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. - * - * @see dpp::cluster::message_delete_bulk - * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages - * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_delete_bulk(const std::vector& message_ids, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_delete_bulk(message_ids, channel_id, cc); }); -} - -/** - * @brief Delete a message from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::message_delete - * @see https://discord.com/developers/docs/resources/channel#delete-message - * @param message_id Message ID to delete - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_delete(snowflake message_id, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_delete(message_id, channel_id, cc); }); -} - -/** - * @brief Edit a message on a channel. The callback function is called when the message has been edited - * - * @see dpp::cluster::message_edit - * @see https://discord.com/developers/docs/resources/channel#edit-message - * @param m Message to edit - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_edit(const message &m) { - return dpp::awaitable(this, [&] (auto cc) { this->message_edit(m, cc); }); -} - -/** - * @brief Get a message - * - * @see dpp::cluster::message_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-message - * @param message_id Message ID - * @param channel_id Channel ID - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_get(snowflake message_id, snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_get(message_id, channel_id, cc); }); -} - -/** - * @brief Pin a message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::message_pin - * @see https://discord.com/developers/docs/resources/channel#pin-message - * @param channel_id Channel id to pin message on - * @param message_id Message id to pin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_pin(snowflake channel_id, snowflake message_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_pin(channel_id, message_id, cc); }); -} - -/** - * @brief Get multiple messages. - * - * This function will attempt to fetch as many messages as possible using multiple API calls if needed. - * - * @see dpp::cluster::messages_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-messages - * @param channel_id Channel ID to retrieve messages for - * @param around Messages should be retrieved around this ID if this is set to non-zero - * @param before Messages before this ID should be retrieved if this is set to non-zero - * @param after Messages after this ID should be retrieved if this is set to non-zero - * @param limit This number of messages maximum should be returned, up to a maximum of 100. - * @return message_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->messages_get(channel_id, around, before, after, limit, cc); }); -} - -/** - * @brief Unpin a message - * @see dpp::cluster::message_unpin - * @see https://discord.com/developers/docs/resources/channel#unpin-message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id Channel id to unpin message on - * @param message_id Message id to unpin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_message_unpin(snowflake channel_id, snowflake message_id) { - return dpp::awaitable(this, [&] (auto cc) { this->message_unpin(channel_id, message_id, cc); }); -} - -/** - * @brief Get a channel's pins - * @see dpp::cluster::channel_pins_get - * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages - * @param channel_id Channel ID to get pins for - * @return message_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_channel_pins_get(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->channel_pins_get(channel_id, cc); }); -} - -/** - * @brief Create a role on a guild - * - * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. - * Fires a `Guild Role Create` Gateway event. - * - * @see dpp::cluster::role_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to create (guild ID is encapsulated in the role object) - * @return role returned object on completion - * \memberof dpp::cluster - */ -auto inline co_role_create(const class role &r) { - return dpp::awaitable(this, [&] (auto cc) { this->role_create(r, cc); }); -} - -/** - * @brief Delete a role - * - * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. - * - * @see dpp::cluster::role_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete the role on - * @param role_id Role ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_role_delete(snowflake guild_id, snowflake role_id) { - return dpp::awaitable(this, [&] (auto cc) { this->role_delete(guild_id, role_id, cc); }); -} - -/** - * @brief Edit a role on a guild - * - * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. - * - * @see dpp::cluster::role_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to edit - * @return role returned object on completion - * \memberof dpp::cluster - */ -auto inline co_role_edit(const class role &r) { - return dpp::awaitable(this, [&] (auto cc) { this->role_edit(r, cc); }); -} - -/** - * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. - * - * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. - * Fires multiple `Guild Role Update` Gateway events. - * - * @see dpp::cluster::roles_edit_position - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to change the roles position on - * @param roles Vector of roles to change the positions of - * @return role_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_roles_edit_position(snowflake guild_id, const std::vector &roles) { - return dpp::awaitable(this, [&] (auto cc) { this->roles_edit_position(guild_id, roles, cc); }); -} - -/** - * @brief Get a role for a guild - * - * @see dpp::cluster::roles_get - * @see https://discord.com/developers/docs/resources/guild#get-guild-roles - * @param guild_id Guild ID to get role for - * @return role_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_roles_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->roles_get(guild_id, cc); }); -} - -/** - * @brief Get all scheduled events for a guild - * @see dpp::cluster::guild_events_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild - * @param guild_id Guild to get events for - * @return scheduled_event_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_events_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_events_get(guild_id, cc); }); -} - -/** - * @brief Create a scheduled event on a guild - * - * @see dpp::cluster::guild_event_create - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event - * @param event Event to create (guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_create(const scheduled_event& event) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_create(event, cc); }); -} - -/** - * @brief Delete a scheduled event from a guild - * - * @see dpp::cluster::guild_event_delete - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event - * @param event_id Event ID to delete - * @param guild_id Guild ID of event to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_delete(snowflake event_id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_delete(event_id, guild_id, cc); }); -} - -/** - * @brief Edit/modify a scheduled event on a guild - * - * @see dpp::cluster::guild_event_edit - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event - * @param event Event to create (event ID and guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_edit(const scheduled_event& event) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_edit(event, cc); }); -} - -/** - * @brief Get a scheduled event for a guild - * - * @see dpp::cluster::guild_event_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event - * @param guild_id Guild to get event for - * @param event_id Event ID to get - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_event_get(snowflake guild_id, snowflake event_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_event_get(guild_id, event_id, cc); }); -} - - -auto inline co_stage_instance_create(const stage_instance& si) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_create(si, cc); }); -} - -/** - * @brief Get the stage instance associated with the channel id, if it exists. - * @see dpp::cluster::stage_instance_get - * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance - * @param channel_id ID of the associated channel - * @return stage_instance returned object on completion - * \memberof dpp::cluster - */ -auto inline co_stage_instance_get(const snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_get(channel_id, cc); }); -} - - -auto inline co_stage_instance_edit(const stage_instance& si) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_edit(si, cc); }); -} - -/** - * @brief Delete a stage instance. - * @see dpp::cluster::stage_instance_delete - * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance - * @param channel_id ID of the associated channel - * @return confirmation returned object on completion - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * \memberof dpp::cluster - */ -auto inline co_stage_instance_delete(const snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_delete(channel_id, cc); }); -} - -/** - * @brief Create a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_create - * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker - * @param s Sticker to create. Must have its guild ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_create(sticker &s) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_create(s, cc); }); -} - -/** - * @brief Delete a sticker from a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_delete - * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker - * @param sticker_id sticker ID to delete - * @param guild_id guild ID to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_delete(snowflake sticker_id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_delete(sticker_id, guild_id, cc); }); -} - -/** - * @brief Get a guild sticker - * @see dpp::cluster::guild_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker - * @param id Id of sticker to get. - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_get(snowflake id, snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_get(id, guild_id, cc); }); -} - -/** - * @brief Modify a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_modify - * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker - * @param s Sticker to modify. Must have its guild ID and sticker ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_sticker_modify(sticker &s) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_modify(s, cc); }); -} - -/** - * @brief Get all guild stickers - * @see dpp::cluster::guild_stickers_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_stickers_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_stickers_get(guild_id, cc); }); -} - -/** - * @brief Get a nitro sticker - * @see dpp::cluster::nitro_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-sticker - * @param id Id of sticker to get. - * @return sticker returned object on completion - * \memberof dpp::cluster - */ -auto inline co_nitro_sticker_get(snowflake id) { - return dpp::awaitable(this, [&] (auto cc) { this->nitro_sticker_get(id, cc); }); -} - -/** - * @brief Get sticker packs - * @see dpp::cluster::sticker_packs_get - * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs - * @return sticker_pack_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_sticker_packs_get() { - return dpp::awaitable(this, [&] (auto cc) { this->sticker_packs_get(cc); }); -} - -/** - * @brief Create a new guild based on a template. - * @note This endpoint can be used only by bots in less than 10 guilds. - * @see dpp::cluster::guild_create_from_template - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template - * @param code Template code to create guild from - * @param name Guild name to create - * @return guild returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_create_from_template(const std::string &code, const std::string &name) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_create_from_template(code, name, cc); }); -} - -/** - * @brief Creates a template for the guild - * - * @see dpp::cluster::guild_template_create - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template - * @param guild_id Guild to create template from - * @param name Template name to create - * @param description Description of template to create - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_create(snowflake guild_id, const std::string &name, const std::string &description) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_create(guild_id, name, description, cc); }); -} - -/** - * @brief Deletes the template - * - * @see dpp::cluster::guild_template_delete - * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template - * @param guild_id Guild ID of template to delete - * @param code Template code to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_delete(snowflake guild_id, const std::string &code) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_delete(guild_id, code, cc); }); -} - -/** - * @brief Modifies the template's metadata. - * - * @see dpp::cluster::guild_template_modify - * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template - * @param guild_id Guild ID of template to modify - * @param code Template code to modify - * @param name New name of template - * @param description New description of template - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_modify(guild_id, code, name, description, cc); }); -} - -/** - * @brief Get guild templates - * - * @see dpp::cluster::guild_templates_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates - * @param guild_id Guild ID to get templates for - * @return dtemplate_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_templates_get(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_templates_get(guild_id, cc); }); -} - -/** - * @brief Syncs the template to the guild's current state. - * - * @see dpp::cluster::guild_template_sync - * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template - * @param guild_id Guild to synchronise template for - * @param code Code of template to synchronise - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_template_sync(snowflake guild_id, const std::string &code) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_template_sync(guild_id, code, cc); }); -} - -/** - * @brief Get a template - * @see dpp::cluster::template_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template - * @param code Template code - * @return dtemplate returned object on completion - * \memberof dpp::cluster - */ -auto inline co_template_get(const std::string &code) { - return dpp::awaitable(this, [&] (auto cc) { this->template_get(code, cc); }); -} - -/** - * @brief Join a thread - * @see dpp::cluster::current_user_join_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to join - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_join_thread(snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_join_thread(thread_id, cc); }); -} - -/** - * @brief Leave a thread - * @see dpp::cluster::current_user_leave_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_leave_thread(snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_thread(thread_id, cc); }); -} - -/** - * @brief Get active threads in a channel (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_active - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get active threads for - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_active(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_active(channel_id, cc); }); -} - -/** - * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_joined_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_id Get threads before this id - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_joined_private_archived(channel_id, before_id, limit, cc); }); -} - -/** - * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_private_archived(channel_id, before_timestamp, limit, cc); }); -} - -/** - * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_public_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { - return dpp::awaitable(this, [&] (auto cc) { this->threads_get_public_archived(channel_id, before_timestamp, limit, cc); }); -} - -/** - * @brief Get a thread member - * @see dpp::cluster::thread_member_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get member for - * @param user_id ID of the user to get - * @return thread_member returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_member_get(const snowflake thread_id, const snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_member_get(thread_id, user_id, cc); }); -} - -/** - * @brief Get members of a thread - * @see dpp::cluster::thread_members_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get members for - * @return thread_member_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_members_get(snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_members_get(thread_id, cc); }); -} - -/** - * @brief Create a thread - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::thread_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-channel - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD - * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_create(thread_name, channel_id, auto_archive_duration, thread_type, invitable, rate_limit_per_user, cc); }); -} - -/** - * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::thread_create_with_message - * @see https://discord.com/developers/docs/topics/threads - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param message_id message to start thread with - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_create_with_message(thread_name, channel_id, message_id, auto_archive_duration, rate_limit_per_user, cc); }); -} - -/** - * @brief Add a member to a thread - * @see dpp::cluster::thread_member_add - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to add to - * @param user_id Member ID to add - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_member_add(snowflake thread_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_member_add(thread_id, user_id, cc); }); -} - -/** - * @brief Remove a member from a thread - * @see dpp::cluster::thread_member_remove - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to remove from - * @param user_id Member ID to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_thread_member_remove(snowflake thread_id, snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->thread_member_remove(thread_id, user_id, cc); }); -} - -/** - * @brief Edit current (bot) user - * - * Modifies the current member in a guild. Returns the updated guild_member object on success. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::current_user_edit - * @see https://discord.com/developers/docs/resources/user#modify-current-user - * @param nickname Nickname to set - * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) - * @param type Type of image for avatar - * @return user returned object on completion - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - * \memberof dpp::cluster - */ -auto inline co_current_user_edit(const std::string &nickname, const std::string& image_blob, const image_type type) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_edit(nickname, image_blob, type, cc); }); -} - -/** - * @brief Get current (bot) application - * - * @see dpp::cluster::current_application_get - * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information - * @return application returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_application_get() { - return dpp::awaitable(this, [&] (auto cc) { this->current_application_get(cc); }); -} - -/** - * @brief Get current (bot) user - * - * @see dpp::cluster::current_user_get - * @see https://discord.com/developers/docs/resources/user#get-current-user - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * \memberof dpp::cluster - */ -auto inline co_current_user_get() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_get(cc); }); -} - -/** - * @brief Set the bot's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - current user must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. - * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. - * - You are able to set `request_to_speak_timestamp` to any present or future time. - * - * @see dpp::cluster::current_user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. - * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. - * \memberof dpp::cluster - */ -auto inline co_current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress, time_t request_to_speak_timestamp) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_set_voice_state(guild_id, channel_id, suppress, request_to_speak_timestamp, cc); }); -} - -/** - * @brief Set a user's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - User must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) - * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. - * - When suppressed, the user will have their `request_to_speak_timestamp` removed. - * - * @see dpp::cluster::user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state - * @param user_id The user to set the voice state of - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * \memberof dpp::cluster - */ -auto inline co_user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress) { - return dpp::awaitable(this, [&] (auto cc) { this->user_set_voice_state(user_id, guild_id, channel_id, suppress, cc); }); -} - -/** - * @brief Get current user's connections (linked accounts, e.g. steam, xbox). - * This call requires the oauth2 `connections` scope and cannot be executed - * against a bot token. - * @see dpp::cluster::current_user_connections_get - * @see https://discord.com/developers/docs/resources/user#get-user-connections - * @return connection_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_connections_get() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_connections_get(cc); }); -} - -/** - * @brief Get current (bot) user guilds - * @see dpp::cluster::current_user_get_guilds - * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds - * @return guild_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_get_guilds() { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_guilds(cc); }); -} - -/** - * @brief Leave a guild - * @see dpp::cluster::current_user_leave_guild - * @see https://discord.com/developers/docs/resources/user#leave-guild - * @param guild_id Guild ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_current_user_leave_guild(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_guild(guild_id, cc); }); -} - -/** - * @brief Get a user by id - * - * @see dpp::cluster::user_get - * @see https://discord.com/developers/docs/resources/user#get-user - * @param user_id User ID to retrieve - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. - * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. - * \memberof dpp::cluster - */ -auto inline co_user_get(snowflake user_id) { - return dpp::awaitable(this, [&] (auto cc) { this->user_get(user_id, cc); }); -} - -/** - * @brief Get all voice regions - * @see dpp::cluster::get_voice_regions - * @see https://discord.com/developers/docs/resources/voice#list-voice-regions - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_voice_regions() { - return dpp::awaitable(this, [&] (auto cc) { this->get_voice_regions(cc); }); -} - -/** - * @brief Get guild voice regions. - * - * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. - * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when - * the guild is VIP-enabled. - * - * @see dpp::cluster::guild_get_voice_regions - * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions - * @param guild_id Guild ID to get voice regions for - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_guild_get_voice_regions(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->guild_get_voice_regions(guild_id, cc); }); -} - -/** - * @brief Create a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::create_webhook - * @see https://discord.com/developers/docs/resources/webhook#create-webhook - * @param w Webhook to create - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_create_webhook(const class webhook &w) { - return dpp::awaitable(this, [&] (auto cc) { this->create_webhook(w, cc); }); -} - -/** - * @brief Delete a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::delete_webhook - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook - * @param webhook_id Webhook ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_delete_webhook(snowflake webhook_id) { - return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook(webhook_id, cc); }); -} - -/** - * @brief Delete webhook message - * - * @see dpp::cluster::delete_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message - * @param wh Webhook to delete message for - * @param message_id Message ID to delete - * @param thread_id ID of the thread the message is in - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_message(wh, message_id, thread_id, cc); }); -} - -/** - * @brief Delete webhook with token - * @see dpp::cluster::delete_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token - * @param webhook_id Webhook ID to delete - * @param token Token of webhook to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - */ -auto inline co_delete_webhook_with_token(snowflake webhook_id, const std::string &token) { - return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_with_token(webhook_id, token, cc); }); -} - -/** - * @brief Edit webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::edit_webhook - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook - * @param wh Webhook to edit - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_edit_webhook(const class webhook& wh) { - return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook(wh, cc); }); -} - -/** - * @brief Edit webhook message - * - * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on - * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit - * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to - * whether or not an allowed_mentions was present in the request that originally created the message. - * - * @see dpp::cluster::edit_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message - * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. - * @param wh Webhook to edit message for - * @param m New message - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_edit_webhook_message(const class webhook &wh, const struct message& m, snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_message(wh, m, thread_id, cc); }); -} - -/** - * @brief Edit webhook with token (token is encapsulated in the webhook object) - * @see dpp::cluster::edit_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token - * @param wh Webhook to edit (should include token) - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_edit_webhook_with_token(const class webhook& wh) { - return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_with_token(wh, cc); }); -} - -/** - * @brief Execute webhook - * - * @see dpp::cluster::execute_webhook - * @see https://discord.com/developers/docs/resources/webhook#execute-webhook - * @param wh Webhook to execute - * @param m Message to send - * @param wait waits for server confirmation of message send before response, and returns the created message body - * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived - * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) - * @return message returned object on completion - * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. - * \memberof dpp::cluster - */ -auto inline co_execute_webhook(const class webhook &wh, const struct message& m, bool wait, snowflake thread_id, const std::string& thread_name) { - return dpp::awaitable(this, [&] (auto cc) { this->execute_webhook(wh, m, wait, thread_id, thread_name, cc); }); -} - -/** - * @brief Get channel webhooks - * @see dpp::cluster::get_channel_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param channel_id Channel ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_channel_webhooks(snowflake channel_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_channel_webhooks(channel_id, cc); }); -} - -/** - * @brief Get guild webhooks - * @see dpp::cluster::get_guild_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param guild_id Guild ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_guild_webhooks(snowflake guild_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_guild_webhooks(guild_id, cc); }); -} - -/** - * @brief Get webhook - * @see dpp::cluster::get_webhook - * @see https://discord.com/developers/docs/resources/webhook#get-webhook - * @param webhook_id Webhook ID to get - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_webhook(snowflake webhook_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_webhook(webhook_id, cc); }); -} - -/** - * @brief Get webhook message - * - * @see dpp::cluster::get_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message - * @param wh Webhook to get the original message for - * @param message_id The message ID - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { - return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_message(wh, message_id, thread_id, cc); }); -} - -/** - * @brief Get webhook using token - * @see dpp::cluster::get_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token - * @param webhook_id Webhook ID to retrieve - * @param token Token of webhook - * @return webhook returned object on completion - * \memberof dpp::cluster - */ -auto inline co_get_webhook_with_token(snowflake webhook_id, const std::string &token) { - return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_with_token(webhook_id, token, cc); }); -} - - -/* End of auto-generated definitions */ -auto inline co_request(const std::string &url, http_method method, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}) { - return dpp::awaitable(this, [&] (auto cc) { this->request(url, method, cc, mimetype, headers); }); -} - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + + +/* Auto @generated by buildtools/make_coro_struct.php. + * + * DO NOT EDIT BY HAND! + * + * To re-generate this header file re-run the script! + */ +/** + * @brief Create/overwrite global slash commands. + * Any existing global slash commands will be deleted and replaced with these. + * + * @see dpp::cluster::global_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands + * @param commands Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_bulk_command_create(const std::vector &commands) { + return dpp::awaitable(this, [&] (auto cc) { this->global_bulk_command_create(commands, cc); }); +} + +/** + * @brief Create a global slash command (a bot can have a maximum of 100 of these). + * + * @see dpp::cluster::global_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command + * @param s Slash command to create + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_create(const slashcommand &s) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_create(s, cc); }); +} + +/** + * @brief Get a global slash command + * + * @see dpp::cluster::global_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command + * @param id The ID of the slash command + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_get(snowflake id) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_get(id, cc); }); +} + +/** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command + * @param id Slash command to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_delete(snowflake id) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_delete(id, cc); }); +} + +/** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command + * @param s Slash command to change + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_command_edit(const slashcommand &s) { + return dpp::awaitable(this, [&] (auto cc) { this->global_command_edit(s, cc); }); +} + +/** + * @brief Get the application's global slash commands + * + * @see dpp::cluster::global_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_global_commands_get() { + return dpp::awaitable(this, [&] (auto cc) { this->global_commands_get(cc); }); +} + +/** + * @brief Create/overwrite guild slash commands. + * Any existing guild slash commands on this guild will be deleted and replaced with these. + * + * @see dpp::cluster::guild_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands + * @param commands Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_bulk_command_create(const std::vector &commands, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_create(commands, guild_id, cc); }); +} + +/** + * @brief Get all slash command permissions of a guild + * + * @see dpp::cluster::guild_commands_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param guild_id Guild ID to get the slash commands permissions for + * @return guild_command_permissions_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_commands_get_permissions(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get_permissions(guild_id, cc); }); +} + +/** + * @brief Edit/Overwrite the permissions of all existing slash commands in a guild + * + * @note You can only add up to 10 permission overwrites for a command + * + * @see dpp::cluster::guild_bulk_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions + * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. + * @param commands A vector of slash commands to edit/overwrite the permissions for + * @param guild_id Guild ID to edit permissions of the slash commands in + * @return guild_command_permissions_map returned object on completion + * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead + * \memberof dpp::cluster + */ +auto inline co_guild_bulk_command_edit_permissions(const std::vector &commands, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_bulk_command_edit_permissions(commands, guild_id, cc); }); +} + +/** + * @brief Create a slash command local to a guild + * + * @see dpp::cluster::guild_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command + * @note Creating a command with the same name as an existing command for your application will overwrite the old command. + * @param s Slash command to create + * @param guild_id Guild ID to create the slash command in + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_create(const slashcommand &s, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_create(s, guild_id, cc); }); +} + +/** + * @brief Delete a slash command local to a guild + * + * @see dpp::cluster::guild_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_delete(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_delete(id, guild_id, cc); }); +} + +/** + * @brief Edit slash command permissions of a guild + * + * @see dpp::cluster::guild_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions + * @note You can only add up to 10 permission overwrites for a command + * @param s Slash command to edit the permissions for + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_edit_permissions(const slashcommand &s, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit_permissions(s, guild_id, cc); }); +} + +/** + * @brief Get a slash command of a guild + * + * @see dpp::cluster::guild_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param id The ID of the slash command + * @param guild_id Guild ID to get the slash command from + * @return slashcommand returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_get(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get(id, guild_id, cc); }); +} + +/** + * @brief Get the permissions for a slash command of a guild + * + * @see dpp::cluster::guild_command_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param id The ID of the slash command to get the permissions for + * @param guild_id Guild ID to get the permissions of + * @return guild_command_permissions returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_get_permissions(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_get_permissions(id, guild_id, cc); }); +} + +/** + * @brief Edit a slash command local to a guild + * + * @see dpp::cluster::guild_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_command_edit(const slashcommand &s, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_command_edit(s, guild_id, cc); }); +} + +/** + * @brief Get the application's slash commands for a guild + * + * @see dpp::cluster::guild_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param guild_id Guild ID to get the slash commands for + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_commands_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_commands_get(guild_id, cc); }); +} + +/** + * @brief Respond to a slash command + * + * @see dpp::cluster::interaction_response_create + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response + * @param interaction_id Interaction id to respond to + * @param token Token for the interaction webhook + * @param r Response to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_response_create(snowflake interaction_id, const std::string &token, const interaction_response &r) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_create(interaction_id, token, r, cc); }); +} + +/** + * @brief Edit response to a slash command + * + * @see dpp::cluster::interaction_response_edit + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response + * @param token Token for the interaction webhook + * @param m Message to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_response_edit(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_response_edit(token, m, cc); }); +} + +/** + * @brief Create a followup message to a slash command + * + * @param token Token for the interaction webhook + * @param m followup message to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_create(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_create(token, m, cc); }); +} + +/** + * @brief Edit original followup message to a slash command + * This is an alias for cluster::interaction_response_edit + * @see dpp::cluster::interaction_followup_edit_original + * @see cluster::interaction_response_edit + * + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_edit_original(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit_original(token, m, cc); }); +} + +/** + * @brief + * + * @param token Token for the interaction webhook + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_delete(const std::string &token) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_delete(token, cc); }); +} + +/** + * @brief Edit followup message to a slash command + * The message ID in the message you pass should be correctly set to that of a followup message you previously sent + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_edit(const std::string &token, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_edit(token, m, cc); }); +} + +/** + * @brief Get the followup message to a slash command + * @param token Token for the interaction webhook + * @param message_id message to retrieve + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_interaction_followup_get(const std::string &token, snowflake message_id) { + return dpp::awaitable(this, [&] (auto cc) { this->interaction_followup_get(token, message_id, cc); }); +} + +/** + * @brief Get all auto moderation rules for a guild + * + * @param guild_id Guild id of the auto moderation rule + * @return automod_rule_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rules_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rules_get(guild_id, cc); }); +} + +/** + * @brief Get a single auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Rule id to retrieve + * @return automod_rule returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_get(snowflake guild_id, snowflake rule_id) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_get(guild_id, rule_id, cc); }); +} + +/** + * @brief Create an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to create + * @return automod_rule returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_create(snowflake guild_id, const automod_rule& r) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_create(guild_id, r, cc); }); +} + +/** + * @brief Edit an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to edit. The rule's id must be set. + * @return automod_rule returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_edit(snowflake guild_id, const automod_rule& r) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_edit(guild_id, r, cc); }); +} + +/** + * @brief Delete an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Auto moderation rule id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_automod_rule_delete(snowflake guild_id, snowflake rule_id) { + return dpp::awaitable(this, [&] (auto cc) { this->automod_rule_delete(guild_id, rule_id, cc); }); +} + +/** + * @brief Create a channel + * + * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, + * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible + * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. + * + * All parameters to this endpoint are optional excluding `name` + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_create + * @see https://discord.com/developers/docs/resources/channel#create-channel + * @param c Channel to create + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_create(const class channel &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_create(c, cc); }); +} + +/** + * @brief Remove a permission from a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete_permission + * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_delete_permission(const class channel &c, snowflake overwrite_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_delete_permission(c, overwrite_id, cc); }); +} + +/** + * @brief Delete a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete + * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel + * @param channel_id Channel id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_delete(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_delete(channel_id, cc); }); +} + +/** + * @brief Edit multiple channels positions + * + * Modify the positions of a set of channel objects for the guild. + * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. + * Only channels to be modified are required. + * + * @see dpp::cluster::channel_edit_positions + * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions + * @param c Channel to change the position for + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_edit_positions(const std::vector &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_edit_positions(c, cc); }); +} + +/** + * @brief Edit a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_edit + * @see https://discord.com/developers/docs/resources/channel#modify-channel + * @param c Channel to edit/update + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_edit(const class channel &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_edit(c, cc); }); +} + +/** + * @brief Follow an announcement (news) channel + * @see dpp::cluster::channel_follow_news + * @see https://discord.com/developers/docs/resources/channel#follow-news-channel + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_follow_news(const class channel &c, snowflake target_channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_follow_news(c, target_channel_id, cc); }); +} + +/** + * @brief Get a channel + * + * @see dpp::cluster::channel_get + * @see https://discord.com/developers/docs/resources/channel#get-channel + * @param c Channel ID to retrieve + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_get(snowflake c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_get(c, cc); }); +} + +/** + * @brief Create invite for a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_invite_create + * @see https://discord.com/developers/docs/resources/channel#create-channel-invite + * @param c Channel to create an invite on + * @param i Invite to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_invite_create(const class channel &c, const class invite &i) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_invite_create(c, i, cc); }); +} + +/** + * @brief Get invites for a channel + * + * @see dpp::cluster::channel_invites_get + * @see https://discord.com/developers/docs/resources/invite#get-invites + * @param c Channel to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_invites_get(const class channel &c) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_invites_get(c, cc); }); +} + +/** + * @brief Get all channels for a guild + * + * @see dpp::cluster::channels_get + * @see https://discord.com/developers/docs/resources/channel#get-channels + * @param guild_id Guild ID to retrieve channels for + * @return channel_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channels_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channels_get(guild_id, cc); }); +} + +/** + * @brief Create a dm channel + * @see dpp::cluster::create_dm_channel + * @see https://discord.com/developers/docs/resources/user#create-dm + * @param user_id User ID to create DM channel with + * @return channel returned object on completion + * \memberof dpp::cluster + */ +auto inline co_create_dm_channel(snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->create_dm_channel(user_id, cc); }); +} + +/** + * @brief Get current user DM channels + * + * @return channel_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_get_dms() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_dms(cc); }); +} + +/** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/user#create-dm + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param user_id User ID of user to send message to + * @param m Message object + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_direct_message_create(snowflake user_id, const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->direct_message_create(user_id, m, cc); }); +} + +/** + * @brief Adds a recipient to a Group DM using their access token + * @see dpp::cluster::gdm_add + * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_gdm_add(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick) { + return dpp::awaitable(this, [&] (auto cc) { this->gdm_add(channel_id, user_id, access_token, nick, cc); }); +} + +/** + * @brief Removes a recipient from a Group DM + * @see dpp::cluster::gdm_remove + * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_gdm_remove(snowflake channel_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->gdm_remove(channel_id, user_id, cc); }); +} + +/** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_create + * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @return emoji returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_create(snowflake guild_id, const class emoji& newemoji) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_create(guild_id, newemoji, cc); }); +} + +/** + * @brief Delete a guild emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_delete + * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_delete(snowflake guild_id, snowflake emoji_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_delete(guild_id, emoji_id, cc); }); +} + +/** + * @brief Edit a single emoji. + * + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @see dpp::cluster::guild_emoji_edit + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @return emoji returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_edit(snowflake guild_id, const class emoji& newemoji) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_edit(guild_id, newemoji, cc); }); +} + +/** + * @brief Get a single emoji + * + * @see dpp::cluster::guild_emoji_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @return emoji returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emoji_get(snowflake guild_id, snowflake emoji_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emoji_get(guild_id, emoji_id, cc); }); +} + +/** + * @brief Get all emojis for a guild + * + * @see dpp::cluster::guild_emojis_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis + * @param guild_id Guild ID to get emojis for + * @return emoji_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_emojis_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_emojis_get(guild_id, cc); }); +} + +/** + * @brief Get the gateway information for the bot using the token + * @see dpp::cluster::get_gateway_bot + * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot + * @return gateway returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_gateway_bot() { + return dpp::awaitable(this, [&] (auto cc) { this->get_gateway_bot(cc); }); +} + +/** + * @brief Modify current member + * + * Modifies the current member in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_current_member_edit + * @see https://discord.com/developers/docs/resources/guild#modify-current-member + * @param guild_id Guild ID to change on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_current_member_edit(snowflake guild_id, const std::string &nickname) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_current_member_edit(guild_id, nickname, cc); }); +} + +/** + * @brief Get the audit log for a guild + * + * @see dpp::cluster::guild_auditlog_get + * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log + * @param guild_id Guild to get the audit log of + * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user + * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type + * @param before Entries that preceded a specific audit log entry ID. Used for paginating + * @param limit Maximum number of entries (between 1-100) to return + * @return auditlog returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_auditlog_get(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_auditlog_get(guild_id, user_id, action_type, before, limit, cc); }); +} + +/** + * @brief Add guild ban + * + * Create a guild ban, and optionally delete previous messages sent by the banned user. + * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. + * @see dpp::cluster::guild_ban_add + * @see https://discord.com/developers/docs/resources/guild#create-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_ban_add(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_add(guild_id, user_id, delete_message_seconds, cc); }); +} + +/** + * @brief Delete guild ban + * + * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. + * Fires a Guild Ban Remove Gateway event. + * @see dpp::cluster::guild_ban_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_ban_delete(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_ban_delete(guild_id, user_id, cc); }); +} + +/** + * @brief Create a guild + * + * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. + * + * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. + * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an + * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions + * in a channel when also passing in channels with the channels array. + * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within + * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to + * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. + * Category channels must be listed before any children. + * + * @see dpp::cluster::guild_create + * @see https://discord.com/developers/docs/resources/guild#create-guild + * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. + * @param g Guild to create + * @return guild returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_create(const class guild &g) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_create(g, cc); }); +} + +/** + * @brief Delete a guild + * + * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. + * + * @see dpp::cluster::guild_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild + * @param guild_id Guild ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_delete(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_delete(guild_id, cc); }); +} + +/** + * @brief Delete guild integration + * + * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. + * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. + * + * @see dpp::cluster::guild_delete_integration + * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_delete_integration(snowflake guild_id, snowflake integration_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_delete_integration(guild_id, integration_id, cc); }); +} + +/** + * @brief Edit a guild + * + * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. + * Fires a `Guild Update Gateway` event. + * + * @see dpp::cluster::guild_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param g Guild to edit + * @return guild returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_edit(const class guild &g) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_edit(g, cc); }); +} + +/** + * @brief Edit guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_edit_widget + * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @return guild_widget returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_edit_widget(snowflake guild_id, const class guild_widget &gw) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_widget(guild_id, gw, cc); }); +} + +/** + * @brief Get single guild ban + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_ban + * @see https://discord.com/developers/docs/resources/guild#get-guild-ban + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @return ban returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_ban(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_ban(guild_id, user_id, cc); }); +} + +/** + * @brief Get guild ban list + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_bans + * @see https://discord.com/developers/docs/resources/guild#get-guild-bans + * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. + * @param guild_id Guild ID to get bans for + * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit + * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit + * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 + * @return ban_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_bans(snowflake guild_id, snowflake before, snowflake after, snowflake limit) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_bans(guild_id, before, after, limit, cc); }); +} + + +auto inline co_guild_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get(guild_id, cc); }); +} + +/** + * @brief Get guild integrations + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_integrations + * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations + * @param guild_id Guild ID to get integrations for + * @return integration_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_integrations(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_integrations(guild_id, cc); }); +} + + +auto inline co_guild_get_preview(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_preview(guild_id, cc); }); +} + +/** + * @brief Get guild vanity url, if enabled + * + * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. + * @see dpp::cluster::guild_get_vanity + * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url + * @param guild_id Guild to get vanity URL for + * @return invite returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_vanity(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_vanity(guild_id, cc); }); +} + +/** + * @brief Get guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_widget + * @see https://discord.com/developers/docs/resources/guild#get-guild-widget + * @param guild_id Guild ID to get widget for + * @return guild_widget returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_widget(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_widget(guild_id, cc); }); +} + +/** + * @brief Modify guild integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_modify_integration + * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_modify_integration(snowflake guild_id, const class integration &i) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_modify_integration(guild_id, i, cc); }); +} + +/** + * @brief Get prune counts + * + * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` + * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the + * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional + * roles will not. + * + * @see dpp::cluster::guild_get_prune_counts + * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_prune_counts(snowflake guild_id, const struct prune& pruneinfo) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_prune_counts(guild_id, pruneinfo, cc); }); +} + +/** + * @brief Begin guild prune + * + * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members + * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing + * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. + * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` + * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. + * + * @see dpp::cluster::guild_begin_prune + * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_begin_prune(snowflake guild_id, const struct prune& pruneinfo) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_begin_prune(guild_id, pruneinfo, cc); }); +} + +/** + * @brief Change current user nickname + * + * Modifies the nickname of the current user in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_set_nickname + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick + * @param guild_id Guild ID to change nickname on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_set_nickname(snowflake guild_id, const std::string &nickname) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_set_nickname(guild_id, nickname, cc); }); +} + +/** + * @brief Sync guild integration + * + * @see dpp::cluster::guild_sync_integration + * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sync_integration(snowflake guild_id, snowflake integration_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sync_integration(guild_id, integration_id, cc); }); +} + +/** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. + * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. + * + * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. + * Members that are pending will have to complete membership screening before they become full members that can talk. + * + * @note All parameters to this endpoint except for access_token are optional. + * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. + * @see dpp::cluster::guild_add_member + * @see https://discord.com/developers/docs/resources/guild#add-guild-member + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_add_member(const guild_member& gm, const std::string &access_token) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_add_member(gm, access_token, cc); }); +} + +/** + * @brief Edit the properties of an existing guild member + * + * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. + * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. + * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. + * @see dpp::cluster::guild_edit_member + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param gm Guild member to edit + * @return guild_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_edit_member(const guild_member& gm) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_edit_member(gm, cc); }); +} + +/** + * @brief Get a guild member + * @see dpp::cluster::guild_get_member + * @see https://discord.com/developers/docs/resources/guild#get-guild-member + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @return guild_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_member(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_member(guild_id, user_id, cc); }); +} + +/** + * @brief Get all guild members + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_get_members + * @see https://discord.com/developers/docs/resources/guild#get-guild-members + * @param guild_id Guild ID to get all members for + * @param limit max number of members to return (1-1000) + * @param after the highest user id in the previous page + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_members(snowflake guild_id, uint16_t limit, snowflake after) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_members(guild_id, limit, after, cc); }); +} + +/** + * @brief Add role to guild member + * + * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_add_role + * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_add_role(snowflake guild_id, snowflake user_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_add_role(guild_id, user_id, role_id, cc); }); +} + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @deprecated Replaced by dpp::cluster::guild_member_kick + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_delete(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete(guild_id, user_id, cc); }); +} + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_kick + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_kick(snowflake guild_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_kick(guild_id, user_id, cc); }); +} + +/** + * @brief Set the timeout of a guild member + * + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_timeout + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to timeout the member in + * @param user_id User ID to set the timeout for + * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_timeout(snowflake guild_id, snowflake user_id, time_t communication_disabled_until) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_timeout(guild_id, user_id, communication_disabled_until, cc); }); +} + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_delete_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * @deprecated Use dpp::cluster::guild_member_remove_role instead + * \memberof dpp::cluster + */ +auto inline co_guild_member_delete_role(snowflake guild_id, snowflake user_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_delete_role(guild_id, user_id, role_id, cc); }); +} + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_remove_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_remove_role(snowflake guild_id, snowflake user_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_remove_role(guild_id, user_id, role_id, cc); }); +} + +/** + * @brief Moves the guild member to a other voice channel, if member is connected to one. + * Set the `channel_id` to `0` to disconnect the user. + * + * Fires a `Guild Member Update` Gateway event. + * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_member_move + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @return guild_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_member_move(const snowflake channel_id, const snowflake guild_id, const snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_member_move(channel_id, guild_id, user_id, cc); }); +} + +/** + * @brief Search for guild members based on whether their username or nickname starts with the given string. + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_search_members + * @see https://discord.com/developers/docs/resources/guild#search-guild-members + * @param guild_id Guild ID to search in + * @param query Query string to match username(s) and nickname(s) against + * @param limit max number of members to return (1-1000) + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_search_members(snowflake guild_id, const std::string& query, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_search_members(guild_id, query, limit, cc); }); +} + +/** + * @brief Get guild invites + * + * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_invites + * @see https://discord.com/developers/docs/resources/guild#get-guild-invites + * @param guild_id Guild ID to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_invites(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_invites(guild_id, cc); }); +} + + +auto inline co_invite_delete(const std::string &invitecode) { + return dpp::awaitable(this, [&] (auto cc) { this->invite_delete(invitecode, cc); }); +} + + +auto inline co_invite_get(const std::string &invitecode) { + return dpp::awaitable(this, [&] (auto cc) { this->invite_get(invitecode, cc); }); +} + +/** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param m Message to send + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_create(const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->message_create(m, cc); }); +} + +/** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_crosspost + * @see https://discord.com/developers/docs/resources/channel#crosspost-message + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_crosspost(snowflake message_id, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_crosspost(message_id, channel_id, cc); }); +} + +/** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. + * + * @see dpp::cluster::message_delete_bulk + * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages + * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_delete_bulk(const std::vector& message_ids, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_delete_bulk(message_ids, channel_id, cc); }); +} + +/** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::message_delete + * @see https://discord.com/developers/docs/resources/channel#delete-message + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_delete(snowflake message_id, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_delete(message_id, channel_id, cc); }); +} + +/** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @see dpp::cluster::message_edit + * @see https://discord.com/developers/docs/resources/channel#edit-message + * @param m Message to edit + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_edit(const message &m) { + return dpp::awaitable(this, [&] (auto cc) { this->message_edit(m, cc); }); +} + +/** + * @brief Get a message + * + * @see dpp::cluster::message_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-message + * @param message_id Message ID + * @param channel_id Channel ID + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_get(snowflake message_id, snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_get(message_id, channel_id, cc); }); +} + +/** + * @brief Pin a message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::message_pin + * @see https://discord.com/developers/docs/resources/channel#pin-message + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_pin(snowflake channel_id, snowflake message_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_pin(channel_id, message_id, cc); }); +} + +/** + * @brief Get multiple messages. + * + * This function will attempt to fetch as many messages as possible using multiple API calls if needed. + * + * @see dpp::cluster::messages_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-messages + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages after this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned, up to a maximum of 100. + * @return message_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_messages_get(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->messages_get(channel_id, around, before, after, limit, cc); }); +} + +/** + * @brief Unpin a message + * @see dpp::cluster::message_unpin + * @see https://discord.com/developers/docs/resources/channel#unpin-message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_message_unpin(snowflake channel_id, snowflake message_id) { + return dpp::awaitable(this, [&] (auto cc) { this->message_unpin(channel_id, message_id, cc); }); +} + +/** + * @brief Get a channel's pins + * @see dpp::cluster::channel_pins_get + * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages + * @param channel_id Channel ID to get pins for + * @return message_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_channel_pins_get(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->channel_pins_get(channel_id, cc); }); +} + +/** + * @brief Create a role on a guild + * + * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. + * Fires a `Guild Role Create` Gateway event. + * + * @see dpp::cluster::role_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to create (guild ID is encapsulated in the role object) + * @return role returned object on completion + * \memberof dpp::cluster + */ +auto inline co_role_create(const class role &r) { + return dpp::awaitable(this, [&] (auto cc) { this->role_create(r, cc); }); +} + +/** + * @brief Delete a role + * + * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. + * + * @see dpp::cluster::role_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_role_delete(snowflake guild_id, snowflake role_id) { + return dpp::awaitable(this, [&] (auto cc) { this->role_delete(guild_id, role_id, cc); }); +} + +/** + * @brief Edit a role on a guild + * + * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. + * + * @see dpp::cluster::role_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to edit + * @return role returned object on completion + * \memberof dpp::cluster + */ +auto inline co_role_edit(const class role &r) { + return dpp::awaitable(this, [&] (auto cc) { this->role_edit(r, cc); }); +} + +/** + * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. + * + * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. + * Fires multiple `Guild Role Update` Gateway events. + * + * @see dpp::cluster::roles_edit_position + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to change the roles position on + * @param roles Vector of roles to change the positions of + * @return role_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_roles_edit_position(snowflake guild_id, const std::vector &roles) { + return dpp::awaitable(this, [&] (auto cc) { this->roles_edit_position(guild_id, roles, cc); }); +} + +/** + * @brief Get a role for a guild + * + * @see dpp::cluster::roles_get + * @see https://discord.com/developers/docs/resources/guild#get-guild-roles + * @param guild_id Guild ID to get role for + * @return role_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_roles_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->roles_get(guild_id, cc); }); +} + +/** + * @brief Get all scheduled events for a guild + * @see dpp::cluster::guild_events_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild + * @param guild_id Guild to get events for + * @return scheduled_event_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_events_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_events_get(guild_id, cc); }); +} + +/** + * @brief Create a scheduled event on a guild + * + * @see dpp::cluster::guild_event_create + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event + * @param event Event to create (guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_create(const scheduled_event& event) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_create(event, cc); }); +} + +/** + * @brief Delete a scheduled event from a guild + * + * @see dpp::cluster::guild_event_delete + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event + * @param event_id Event ID to delete + * @param guild_id Guild ID of event to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_delete(snowflake event_id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_delete(event_id, guild_id, cc); }); +} + +/** + * @brief Edit/modify a scheduled event on a guild + * + * @see dpp::cluster::guild_event_edit + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event + * @param event Event to create (event ID and guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_edit(const scheduled_event& event) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_edit(event, cc); }); +} + +/** + * @brief Get a scheduled event for a guild + * + * @see dpp::cluster::guild_event_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event + * @param guild_id Guild to get event for + * @param event_id Event ID to get + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_event_get(snowflake guild_id, snowflake event_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_event_get(guild_id, event_id, cc); }); +} + + +auto inline co_stage_instance_create(const stage_instance& si) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_create(si, cc); }); +} + +/** + * @brief Get the stage instance associated with the channel id, if it exists. + * @see dpp::cluster::stage_instance_get + * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance + * @param channel_id ID of the associated channel + * @return stage_instance returned object on completion + * \memberof dpp::cluster + */ +auto inline co_stage_instance_get(const snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_get(channel_id, cc); }); +} + + +auto inline co_stage_instance_edit(const stage_instance& si) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_edit(si, cc); }); +} + +/** + * @brief Delete a stage instance. + * @see dpp::cluster::stage_instance_delete + * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance + * @param channel_id ID of the associated channel + * @return confirmation returned object on completion + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * \memberof dpp::cluster + */ +auto inline co_stage_instance_delete(const snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->stage_instance_delete(channel_id, cc); }); +} + +/** + * @brief Create a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_create + * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker + * @param s Sticker to create. Must have its guild ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_create(sticker &s) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_create(s, cc); }); +} + +/** + * @brief Delete a sticker from a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_delete + * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_delete(snowflake sticker_id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_delete(sticker_id, guild_id, cc); }); +} + +/** + * @brief Get a guild sticker + * @see dpp::cluster::guild_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_get(snowflake id, snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_get(id, guild_id, cc); }); +} + +/** + * @brief Modify a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_modify + * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_sticker_modify(sticker &s) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_sticker_modify(s, cc); }); +} + +/** + * @brief Get all guild stickers + * @see dpp::cluster::guild_stickers_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_stickers_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_stickers_get(guild_id, cc); }); +} + +/** + * @brief Get a nitro sticker + * @see dpp::cluster::nitro_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-sticker + * @param id Id of sticker to get. + * @return sticker returned object on completion + * \memberof dpp::cluster + */ +auto inline co_nitro_sticker_get(snowflake id) { + return dpp::awaitable(this, [&] (auto cc) { this->nitro_sticker_get(id, cc); }); +} + +/** + * @brief Get sticker packs + * @see dpp::cluster::sticker_packs_get + * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs + * @return sticker_pack_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_sticker_packs_get() { + return dpp::awaitable(this, [&] (auto cc) { this->sticker_packs_get(cc); }); +} + +/** + * @brief Create a new guild based on a template. + * @note This endpoint can be used only by bots in less than 10 guilds. + * @see dpp::cluster::guild_create_from_template + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template + * @param code Template code to create guild from + * @param name Guild name to create + * @return guild returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_create_from_template(const std::string &code, const std::string &name) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_create_from_template(code, name, cc); }); +} + +/** + * @brief Creates a template for the guild + * + * @see dpp::cluster::guild_template_create + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_create(snowflake guild_id, const std::string &name, const std::string &description) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_create(guild_id, name, description, cc); }); +} + +/** + * @brief Deletes the template + * + * @see dpp::cluster::guild_template_delete + * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_delete(snowflake guild_id, const std::string &code) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_delete(guild_id, code, cc); }); +} + +/** + * @brief Modifies the template's metadata. + * + * @see dpp::cluster::guild_template_modify + * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_modify(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_modify(guild_id, code, name, description, cc); }); +} + +/** + * @brief Get guild templates + * + * @see dpp::cluster::guild_templates_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates + * @param guild_id Guild ID to get templates for + * @return dtemplate_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_templates_get(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_templates_get(guild_id, cc); }); +} + +/** + * @brief Syncs the template to the guild's current state. + * + * @see dpp::cluster::guild_template_sync + * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_template_sync(snowflake guild_id, const std::string &code) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_template_sync(guild_id, code, cc); }); +} + +/** + * @brief Get a template + * @see dpp::cluster::template_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template + * @param code Template code + * @return dtemplate returned object on completion + * \memberof dpp::cluster + */ +auto inline co_template_get(const std::string &code) { + return dpp::awaitable(this, [&] (auto cc) { this->template_get(code, cc); }); +} + +/** + * @brief Join a thread + * @see dpp::cluster::current_user_join_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to join + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_join_thread(snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_join_thread(thread_id, cc); }); +} + +/** + * @brief Leave a thread + * @see dpp::cluster::current_user_leave_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_leave_thread(snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_thread(thread_id, cc); }); +} + +/** + * @brief Get active threads in a channel (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_active + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get active threads for + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_active(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_active(channel_id, cc); }); +} + +/** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_joined_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_joined_private_archived(snowflake channel_id, snowflake before_id, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_joined_private_archived(channel_id, before_id, limit, cc); }); +} + +/** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_private_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_private_archived(channel_id, before_timestamp, limit, cc); }); +} + +/** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_public_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_threads_get_public_archived(snowflake channel_id, time_t before_timestamp, uint16_t limit) { + return dpp::awaitable(this, [&] (auto cc) { this->threads_get_public_archived(channel_id, before_timestamp, limit, cc); }); +} + +/** + * @brief Get a thread member + * @see dpp::cluster::thread_member_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get member for + * @param user_id ID of the user to get + * @return thread_member returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_member_get(const snowflake thread_id, const snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_member_get(thread_id, user_id, cc); }); +} + +/** + * @brief Get members of a thread + * @see dpp::cluster::thread_members_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get members for + * @return thread_member_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_members_get(snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_members_get(thread_id, cc); }); +} + +/** + * @brief Create a thread + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::thread_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-channel + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD + * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_create(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_create(thread_name, channel_id, auto_archive_duration, thread_type, invitable, rate_limit_per_user, cc); }); +} + +/** + * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::thread_create_with_message + * @see https://discord.com/developers/docs/topics/threads + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_create_with_message(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_create_with_message(thread_name, channel_id, message_id, auto_archive_duration, rate_limit_per_user, cc); }); +} + +/** + * @brief Add a member to a thread + * @see dpp::cluster::thread_member_add + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_member_add(snowflake thread_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_member_add(thread_id, user_id, cc); }); +} + +/** + * @brief Remove a member from a thread + * @see dpp::cluster::thread_member_remove + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_thread_member_remove(snowflake thread_id, snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->thread_member_remove(thread_id, user_id, cc); }); +} + +/** + * @brief Edit current (bot) user + * + * Modifies the current member in a guild. Returns the updated guild_member object on success. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::current_user_edit + * @see https://discord.com/developers/docs/resources/user#modify-current-user + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @return user returned object on completion + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + * \memberof dpp::cluster + */ +auto inline co_current_user_edit(const std::string &nickname, const std::string& image_blob, const image_type type) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_edit(nickname, image_blob, type, cc); }); +} + +/** + * @brief Get current (bot) application + * + * @see dpp::cluster::current_application_get + * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information + * @return application returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_application_get() { + return dpp::awaitable(this, [&] (auto cc) { this->current_application_get(cc); }); +} + +/** + * @brief Get current (bot) user + * + * @see dpp::cluster::current_user_get + * @see https://discord.com/developers/docs/resources/user#get-current-user + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * \memberof dpp::cluster + */ +auto inline co_current_user_get() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_get(cc); }); +} + +/** + * @brief Set the bot's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - current user must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. + * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. + * - You are able to set `request_to_speak_timestamp` to any present or future time. + * + * @see dpp::cluster::current_user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. + * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. + * \memberof dpp::cluster + */ +auto inline co_current_user_set_voice_state(snowflake guild_id, snowflake channel_id, bool suppress, time_t request_to_speak_timestamp) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_set_voice_state(guild_id, channel_id, suppress, request_to_speak_timestamp, cc); }); +} + +/** + * @brief Set a user's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - User must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) + * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. + * - When suppressed, the user will have their `request_to_speak_timestamp` removed. + * + * @see dpp::cluster::user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state + * @param user_id The user to set the voice state of + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * \memberof dpp::cluster + */ +auto inline co_user_set_voice_state(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress) { + return dpp::awaitable(this, [&] (auto cc) { this->user_set_voice_state(user_id, guild_id, channel_id, suppress, cc); }); +} + +/** + * @brief Get current user's connections (linked accounts, e.g. steam, xbox). + * This call requires the oauth2 `connections` scope and cannot be executed + * against a bot token. + * @see dpp::cluster::current_user_connections_get + * @see https://discord.com/developers/docs/resources/user#get-user-connections + * @return connection_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_connections_get() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_connections_get(cc); }); +} + +/** + * @brief Get current (bot) user guilds + * @see dpp::cluster::current_user_get_guilds + * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds + * @return guild_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_get_guilds() { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_get_guilds(cc); }); +} + +/** + * @brief Leave a guild + * @see dpp::cluster::current_user_leave_guild + * @see https://discord.com/developers/docs/resources/user#leave-guild + * @param guild_id Guild ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_current_user_leave_guild(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->current_user_leave_guild(guild_id, cc); }); +} + +/** + * @brief Get a user by id + * + * @see dpp::cluster::user_get + * @see https://discord.com/developers/docs/resources/user#get-user + * @param user_id User ID to retrieve + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. + * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. + * \memberof dpp::cluster + */ +auto inline co_user_get(snowflake user_id) { + return dpp::awaitable(this, [&] (auto cc) { this->user_get(user_id, cc); }); +} + +/** + * @brief Get all voice regions + * @see dpp::cluster::get_voice_regions + * @see https://discord.com/developers/docs/resources/voice#list-voice-regions + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_voice_regions() { + return dpp::awaitable(this, [&] (auto cc) { this->get_voice_regions(cc); }); +} + +/** + * @brief Get guild voice regions. + * + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when + * the guild is VIP-enabled. + * + * @see dpp::cluster::guild_get_voice_regions + * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions + * @param guild_id Guild ID to get voice regions for + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_guild_get_voice_regions(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->guild_get_voice_regions(guild_id, cc); }); +} + +/** + * @brief Create a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::create_webhook + * @see https://discord.com/developers/docs/resources/webhook#create-webhook + * @param w Webhook to create + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_create_webhook(const class webhook &w) { + return dpp::awaitable(this, [&] (auto cc) { this->create_webhook(w, cc); }); +} + +/** + * @brief Delete a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::delete_webhook + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook + * @param webhook_id Webhook ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_delete_webhook(snowflake webhook_id) { + return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook(webhook_id, cc); }); +} + +/** + * @brief Delete webhook message + * + * @see dpp::cluster::delete_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param thread_id ID of the thread the message is in + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_delete_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_message(wh, message_id, thread_id, cc); }); +} + +/** + * @brief Delete webhook with token + * @see dpp::cluster::delete_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + */ +auto inline co_delete_webhook_with_token(snowflake webhook_id, const std::string &token) { + return dpp::awaitable(this, [&] (auto cc) { this->delete_webhook_with_token(webhook_id, token, cc); }); +} + +/** + * @brief Edit webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::edit_webhook + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook + * @param wh Webhook to edit + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_edit_webhook(const class webhook& wh) { + return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook(wh, cc); }); +} + +/** + * @brief Edit webhook message + * + * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on + * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit + * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to + * whether or not an allowed_mentions was present in the request that originally created the message. + * + * @see dpp::cluster::edit_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message + * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. + * @param wh Webhook to edit message for + * @param m New message + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_edit_webhook_message(const class webhook &wh, const struct message& m, snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_message(wh, m, thread_id, cc); }); +} + +/** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * @see dpp::cluster::edit_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token + * @param wh Webhook to edit (should include token) + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_edit_webhook_with_token(const class webhook& wh) { + return dpp::awaitable(this, [&] (auto cc) { this->edit_webhook_with_token(wh, cc); }); +} + +/** + * @brief Execute webhook + * + * @see dpp::cluster::execute_webhook + * @see https://discord.com/developers/docs/resources/webhook#execute-webhook + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) + * @return message returned object on completion + * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. + * \memberof dpp::cluster + */ +auto inline co_execute_webhook(const class webhook &wh, const struct message& m, bool wait, snowflake thread_id, const std::string& thread_name) { + return dpp::awaitable(this, [&] (auto cc) { this->execute_webhook(wh, m, wait, thread_id, thread_name, cc); }); +} + +/** + * @brief Get channel webhooks + * @see dpp::cluster::get_channel_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param channel_id Channel ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_channel_webhooks(snowflake channel_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_channel_webhooks(channel_id, cc); }); +} + +/** + * @brief Get guild webhooks + * @see dpp::cluster::get_guild_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param guild_id Guild ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_guild_webhooks(snowflake guild_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_guild_webhooks(guild_id, cc); }); +} + +/** + * @brief Get webhook + * @see dpp::cluster::get_webhook + * @see https://discord.com/developers/docs/resources/webhook#get-webhook + * @param webhook_id Webhook ID to get + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_webhook(snowflake webhook_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_webhook(webhook_id, cc); }); +} + +/** + * @brief Get webhook message + * + * @see dpp::cluster::get_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message + * @param wh Webhook to get the original message for + * @param message_id The message ID + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_webhook_message(const class webhook &wh, snowflake message_id, snowflake thread_id) { + return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_message(wh, message_id, thread_id, cc); }); +} + +/** + * @brief Get webhook using token + * @see dpp::cluster::get_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @return webhook returned object on completion + * \memberof dpp::cluster + */ +auto inline co_get_webhook_with_token(snowflake webhook_id, const std::string &token) { + return dpp::awaitable(this, [&] (auto cc) { this->get_webhook_with_token(webhook_id, token, cc); }); +} + + +/* End of auto-generated definitions */ +auto inline co_request(const std::string &url, http_method method, const std::string &postdata = "", const std::string &mimetype = "text/plain", const std::multimap &headers = {}) { + return dpp::awaitable(this, [&] (auto cc) { this->request(url, method, cc, mimetype, headers); }); +} + diff --git a/3rdParty/dpp/cluster_sync_calls.h b/3rdParty/dpp/cluster_sync_calls.h index 51adeed1e5..44dd073ecb 100644 --- a/3rdParty/dpp/cluster_sync_calls.h +++ b/3rdParty/dpp/cluster_sync_calls.h @@ -1,2502 +1,2502 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - - -/* Auto @generated by buildtools/make_sync_struct.php. - * - * DO NOT EDIT BY HAND! - * - * To re-generate this header file re-run the script! - */ -/** - * @brief Create/overwrite global slash commands. - * Any existing global slash commands will be deleted and replaced with these. - * - * @see dpp::cluster::global_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands - * @param commands Vector of slash commands to create/update. - * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. - * Commands that do not already exist will count toward daily application command create limits. - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map global_bulk_command_create_sync(const std::vector &commands); - -/** - * @brief Create a global slash command (a bot can have a maximum of 100 of these). - * - * @see dpp::cluster::global_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command - * @param s Slash command to create - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand global_command_create_sync(const slashcommand &s); - -/** - * @brief Get a global slash command - * - * @see dpp::cluster::global_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command - * @param id The ID of the slash command - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand global_command_get_sync(snowflake id); - -/** - * @brief Delete a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command - * @param id Slash command to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation global_command_delete_sync(snowflake id); - -/** - * @brief Edit a global slash command (a bot can have a maximum of 100 of these) - * - * @see dpp::cluster::global_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command - * @param s Slash command to change - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation global_command_edit_sync(const slashcommand &s); - -/** - * @brief Get the application's global slash commands - * - * @see dpp::cluster::global_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map global_commands_get_sync(); - -/** - * @brief Create/overwrite guild slash commands. - * Any existing guild slash commands on this guild will be deleted and replaced with these. - * - * @see dpp::cluster::guild_bulk_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands - * @param commands Vector of slash commands to create/update. - * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. - * @param guild_id Guild ID to create/update the slash commands in - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map guild_bulk_command_create_sync(const std::vector &commands, snowflake guild_id); - -/** - * @brief Get all slash command permissions of a guild - * - * @see dpp::cluster::guild_commands_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param guild_id Guild ID to get the slash commands permissions for - * @return guild_command_permissions_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_command_permissions_map guild_commands_get_permissions_sync(snowflake guild_id); - -/** - * @brief Edit/Overwrite the permissions of all existing slash commands in a guild - * - * @note You can only add up to 10 permission overwrites for a command - * - * @see dpp::cluster::guild_bulk_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions - * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. - * @param commands A vector of slash commands to edit/overwrite the permissions for - * @param guild_id Guild ID to edit permissions of the slash commands in - * @return guild_command_permissions_map returned object on completion - * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_command_permissions_map guild_bulk_command_edit_permissions_sync(const std::vector &commands, snowflake guild_id); - -/** - * @brief Create a slash command local to a guild - * - * @see dpp::cluster::guild_command_create - * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command - * @note Creating a command with the same name as an existing command for your application will overwrite the old command. - * @param s Slash command to create - * @param guild_id Guild ID to create the slash command in - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand guild_command_create_sync(const slashcommand &s, snowflake guild_id); - -/** - * @brief Delete a slash command local to a guild - * - * @see dpp::cluster::guild_command_delete - * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command - * @param id Slash command to delete - * @param guild_id Guild ID to delete the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_command_delete_sync(snowflake id, snowflake guild_id); - -/** - * @brief Edit slash command permissions of a guild - * - * @see dpp::cluster::guild_command_edit_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions - * @note You can only add up to 10 permission overwrites for a command - * @param s Slash command to edit the permissions for - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_command_edit_permissions_sync(const slashcommand &s, snowflake guild_id); - -/** - * @brief Get a slash command of a guild - * - * @see dpp::cluster::guild_command_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param id The ID of the slash command - * @param guild_id Guild ID to get the slash command from - * @return slashcommand returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand guild_command_get_sync(snowflake id, snowflake guild_id); - -/** - * @brief Get the permissions for a slash command of a guild - * - * @see dpp::cluster::guild_command_get_permissions - * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions - * @param id The ID of the slash command to get the permissions for - * @param guild_id Guild ID to get the permissions of - * @return guild_command_permissions returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_command_permissions guild_command_get_permissions_sync(snowflake id, snowflake guild_id); - -/** - * @brief Edit a slash command local to a guild - * - * @see dpp::cluster::guild_command_edit - * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command - * @param s Slash command to edit - * @param guild_id Guild ID to edit the slash command in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_command_edit_sync(const slashcommand &s, snowflake guild_id); - -/** - * @brief Get the application's slash commands for a guild - * - * @see dpp::cluster::guild_commands_get - * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands - * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions - * @param guild_id Guild ID to get the slash commands for - * @return slashcommand_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -slashcommand_map guild_commands_get_sync(snowflake guild_id); - -/** - * @brief Respond to a slash command - * - * @see dpp::cluster::interaction_response_create - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response - * @param interaction_id Interaction id to respond to - * @param token Token for the interaction webhook - * @param r Response to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_response_create_sync(snowflake interaction_id, const std::string &token, const interaction_response &r); - -/** - * @brief Edit response to a slash command - * - * @see dpp::cluster::interaction_response_edit - * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response - * @param token Token for the interaction webhook - * @param m Message to send - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_response_edit_sync(const std::string &token, const message &m); - -/** - * @brief Create a followup message to a slash command - * - * @param token Token for the interaction webhook - * @param m followup message to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_create_sync(const std::string &token, const message &m); - -/** - * @brief Edit original followup message to a slash command - * This is an alias for cluster::interaction_response_edit - * @see dpp::cluster::interaction_followup_edit_original - * @see cluster::interaction_response_edit - * - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_edit_original_sync(const std::string &token, const message &m); - -/** - * @brief - * - * @param token Token for the interaction webhook - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_delete_sync(const std::string &token); - -/** - * @brief Edit followup message to a slash command - * The message ID in the message you pass should be correctly set to that of a followup message you previously sent - * @param token Token for the interaction webhook - * @param m message to edit, the ID should be set - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation interaction_followup_edit_sync(const std::string &token, const message &m); - -/** - * @brief Get the followup message to a slash command - * @param token Token for the interaction webhook - * @param message_id message to retrieve - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message interaction_followup_get_sync(const std::string &token, snowflake message_id); - -/** - * @brief Get all auto moderation rules for a guild - * - * @param guild_id Guild id of the auto moderation rule - * @return automod_rule_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule_map automod_rules_get_sync(snowflake guild_id); - -/** - * @brief Get a single auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Rule id to retrieve - * @return automod_rule returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule automod_rule_get_sync(snowflake guild_id, snowflake rule_id); - -/** - * @brief Create an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to create - * @return automod_rule returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule automod_rule_create_sync(snowflake guild_id, const automod_rule& r); - -/** - * @brief Edit an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param r Auto moderation rule to edit. The rule's id must be set. - * @return automod_rule returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -automod_rule automod_rule_edit_sync(snowflake guild_id, const automod_rule& r); - -/** - * @brief Delete an auto moderation rule - * - * @param guild_id Guild id of the auto moderation rule - * @param rule_id Auto moderation rule id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation automod_rule_delete_sync(snowflake guild_id, snowflake rule_id); - -/** - * @brief Create a channel - * - * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, - * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible - * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. - * - * All parameters to this endpoint are optional excluding `name` - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_create - * @see https://discord.com/developers/docs/resources/channel#create-channel - * @param c Channel to create - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel channel_create_sync(const class channel &c); - -/** - * @brief Remove a permission from a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete_permission - * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission - * @param c Channel to remove permission from - * @param overwrite_id Overwrite to remove, user or channel ID - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_delete_permission_sync(const class channel &c, snowflake overwrite_id); - -/** - * @brief Delete a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_delete - * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel - * @param channel_id Channel id to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_delete_sync(snowflake channel_id); - -/** - * @brief Edit multiple channels positions - * - * Modify the positions of a set of channel objects for the guild. - * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. - * Only channels to be modified are required. - * - * @see dpp::cluster::channel_edit_positions - * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions - * @param c Channel to change the position for - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_edit_positions_sync(const std::vector &c); - -/** - * @brief Edit a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_edit - * @see https://discord.com/developers/docs/resources/channel#modify-channel - * @param c Channel to edit/update - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel channel_edit_sync(const class channel &c); - -/** - * @brief Follow an announcement (news) channel - * @see dpp::cluster::channel_follow_news - * @see https://discord.com/developers/docs/resources/channel#follow-news-channel - * @param c Channel id to follow - * @param target_channel_id Channel to subscribe the channel to - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_follow_news_sync(const class channel &c, snowflake target_channel_id); - -/** - * @brief Get a channel - * - * @see dpp::cluster::channel_get - * @see https://discord.com/developers/docs/resources/channel#get-channel - * @param c Channel ID to retrieve - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel channel_get_sync(snowflake c); - -/** - * @brief Create invite for a channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::channel_invite_create - * @see https://discord.com/developers/docs/resources/channel#create-channel-invite - * @param c Channel to create an invite on - * @param i Invite to create - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation channel_invite_create_sync(const class channel &c, const class invite &i); - -/** - * @brief Get invites for a channel - * - * @see dpp::cluster::channel_invites_get - * @see https://discord.com/developers/docs/resources/invite#get-invites - * @param c Channel to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -invite_map channel_invites_get_sync(const class channel &c); - -/** - * @brief Get all channels for a guild - * - * @see dpp::cluster::channels_get - * @see https://discord.com/developers/docs/resources/channel#get-channels - * @param guild_id Guild ID to retrieve channels for - * @return channel_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel_map channels_get_sync(snowflake guild_id); - -/** - * @brief Create a dm channel - * @see dpp::cluster::create_dm_channel - * @see https://discord.com/developers/docs/resources/user#create-dm - * @param user_id User ID to create DM channel with - * @return channel returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel create_dm_channel_sync(snowflake user_id); - -/** - * @brief Get current user DM channels - * - * @return channel_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -channel_map current_user_get_dms_sync(); - -/** - * @brief Create a direct message, also create the channel for the direct message if needed - * - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/user#create-dm - * @see dpp::cluster::direct_message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param user_id User ID of user to send message to - * @param m Message object - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message direct_message_create_sync(snowflake user_id, const message &m); - -/** - * @brief Adds a recipient to a Group DM using their access token - * @see dpp::cluster::gdm_add - * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient - * @param channel_id Channel id to add group DM recipients to - * @param user_id User ID to add - * @param access_token Access token from OAuth2 - * @param nick Nickname of user to apply to the chat - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation gdm_add_sync(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick); - -/** - * @brief Removes a recipient from a Group DM - * @see dpp::cluster::gdm_remove - * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient - * @param channel_id Channel ID of group DM - * @param user_id User ID to remove from group DM - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation gdm_remove_sync(snowflake channel_id, snowflake user_id); - -/** - * @brief Create single emoji. - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_create - * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji - * @param guild_id Guild ID to create emoji om - * @param newemoji Emoji to create - * @return emoji returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji guild_emoji_create_sync(snowflake guild_id, const class emoji& newemoji); - -/** - * @brief Delete a guild emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_emoji_delete - * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji - * @param guild_id Guild ID to delete emoji on - * @param emoji_id Emoji ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_emoji_delete_sync(snowflake guild_id, snowflake emoji_id); - -/** - * @brief Edit a single emoji. - * - * You must ensure that the emoji passed contained image data using the emoji::load_image() method. - * @see dpp::cluster::guild_emoji_edit - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit emoji on - * @param newemoji Emoji to edit - * @return emoji returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji guild_emoji_edit_sync(snowflake guild_id, const class emoji& newemoji); - -/** - * @brief Get a single emoji - * - * @see dpp::cluster::guild_emoji_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji - * @param guild_id Guild ID to get emoji for - * @param emoji_id Emoji ID to get - * @return emoji returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji guild_emoji_get_sync(snowflake guild_id, snowflake emoji_id); - -/** - * @brief Get all emojis for a guild - * - * @see dpp::cluster::guild_emojis_get - * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis - * @param guild_id Guild ID to get emojis for - * @return emoji_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -emoji_map guild_emojis_get_sync(snowflake guild_id); - -/** - * @brief Get the gateway information for the bot using the token - * @see dpp::cluster::get_gateway_bot - * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot - * @return gateway returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -gateway get_gateway_bot_sync(); - -/** - * @brief Modify current member - * - * Modifies the current member in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_current_member_edit - * @see https://discord.com/developers/docs/resources/guild#modify-current-member - * @param guild_id Guild ID to change on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_current_member_edit_sync(snowflake guild_id, const std::string &nickname); - -/** - * @brief Get the audit log for a guild - * - * @see dpp::cluster::guild_auditlog_get - * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log - * @param guild_id Guild to get the audit log of - * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user - * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type - * @param before Entries that preceded a specific audit log entry ID. Used for paginating - * @param limit Maximum number of entries (between 1-100) to return - * @return auditlog returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -auditlog guild_auditlog_get_sync(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit); - -/** - * @brief Add guild ban - * - * Create a guild ban, and optionally delete previous messages sent by the banned user. - * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. - * @see dpp::cluster::guild_ban_add - * @see https://discord.com/developers/docs/resources/guild#create-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add ban to - * @param user_id User ID to ban - * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_ban_add_sync(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0); - -/** - * @brief Delete guild ban - * - * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. - * Fires a Guild Ban Remove Gateway event. - * @see dpp::cluster::guild_ban_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild to delete ban from - * @param user_id User ID to delete ban for - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_ban_delete_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Create a guild - * - * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. - * - * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. - * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an - * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions - * in a channel when also passing in channels with the channels array. - * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within - * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to - * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. - * Category channels must be listed before any children. - * - * @see dpp::cluster::guild_create - * @see https://discord.com/developers/docs/resources/guild#create-guild - * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. - * @param g Guild to create - * @return guild returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild guild_create_sync(const class guild &g); - -/** - * @brief Delete a guild - * - * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. - * - * @see dpp::cluster::guild_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild - * @param guild_id Guild ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_delete_sync(snowflake guild_id); - -/** - * @brief Delete guild integration - * - * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. - * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. - * - * @see dpp::cluster::guild_delete_integration - * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete integration for - * @param integration_id Integration ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_delete_integration_sync(snowflake guild_id, snowflake integration_id); - -/** - * @brief Edit a guild - * - * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. - * Fires a `Guild Update Gateway` event. - * - * @see dpp::cluster::guild_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param g Guild to edit - * @return guild returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild guild_edit_sync(const class guild &g); - -/** - * @brief Edit guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_edit_widget - * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to edit widget for - * @param gw New guild widget information - * @return guild_widget returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_widget guild_edit_widget_sync(snowflake guild_id, const class guild_widget &gw); - -/** - * @brief Get single guild ban - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_ban - * @see https://discord.com/developers/docs/resources/guild#get-guild-ban - * @param guild_id Guild ID to get ban for - * @param user_id User ID of ban to retrieve - * @return ban returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -ban guild_get_ban_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Get guild ban list - * - * Requires the `BAN_MEMBERS` permission. - * @see dpp::cluster::guild_get_bans - * @see https://discord.com/developers/docs/resources/guild#get-guild-bans - * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. - * @param guild_id Guild ID to get bans for - * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit - * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit - * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 - * @return ban_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -ban_map guild_get_bans_sync(snowflake guild_id, snowflake before, snowflake after, snowflake limit); - - -guild guild_get_sync(snowflake guild_id); - -/** - * @brief Get guild integrations - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_integrations - * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations - * @param guild_id Guild ID to get integrations for - * @return integration_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -integration_map guild_get_integrations_sync(snowflake guild_id); - - -guild guild_get_preview_sync(snowflake guild_id); - -/** - * @brief Get guild vanity url, if enabled - * - * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. - * @see dpp::cluster::guild_get_vanity - * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url - * @param guild_id Guild to get vanity URL for - * @return invite returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -invite guild_get_vanity_sync(snowflake guild_id); - -/** - * @brief Get guild widget - * - * Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_widget - * @see https://discord.com/developers/docs/resources/guild#get-guild-widget - * @param guild_id Guild ID to get widget for - * @return guild_widget returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_widget guild_get_widget_sync(snowflake guild_id); - -/** - * @brief Modify guild integration - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::guild_modify_integration - * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration - * @param guild_id Guild ID to modify integration for - * @param i Integration to modify - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_modify_integration_sync(snowflake guild_id, const class integration &i); - -/** - * @brief Get prune counts - * - * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` - * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the - * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional - * roles will not. - * - * @see dpp::cluster::guild_get_prune_counts - * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count - * @param guild_id Guild ID to count for pruning - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -prune guild_get_prune_counts_sync(snowflake guild_id, const struct prune& pruneinfo); - -/** - * @brief Begin guild prune - * - * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members - * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing - * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. - * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` - * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. - * - * @see dpp::cluster::guild_begin_prune - * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to prune - * @param pruneinfo Pruning info - * @return prune returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -prune guild_begin_prune_sync(snowflake guild_id, const struct prune& pruneinfo); - -/** - * @brief Change current user nickname - * - * Modifies the nickname of the current user in a guild. - * Fires a `Guild Member Update` Gateway event. - * - * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_set_nickname - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick - * @param guild_id Guild ID to change nickname on - * @param nickname New nickname, or empty string to clear nickname - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_set_nickname_sync(snowflake guild_id, const std::string &nickname); - -/** - * @brief Sync guild integration - * - * @see dpp::cluster::guild_sync_integration - * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration - * @param guild_id Guild ID to sync integration on - * @param integration_id Integration ID to synchronise - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_sync_integration_sync(snowflake guild_id, snowflake integration_id); - -/** - * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. - * - * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. - * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. - * - * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. - * Members that are pending will have to complete membership screening before they become full members that can talk. - * - * @note All parameters to this endpoint except for access_token are optional. - * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. - * @see dpp::cluster::guild_add_member - * @see https://discord.com/developers/docs/resources/guild#add-guild-member - * @param gm Guild member to add - * @param access_token Access token from Oauth2 scope - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_add_member_sync(const guild_member& gm, const std::string &access_token); - -/** - * @brief Edit the properties of an existing guild member - * - * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. - * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. - * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. - * @see dpp::cluster::guild_edit_member - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param gm Guild member to edit - * @return guild_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member guild_edit_member_sync(const guild_member& gm); - -/** - * @brief Get a guild member - * @see dpp::cluster::guild_get_member - * @see https://discord.com/developers/docs/resources/guild#get-guild-member - * @param guild_id Guild ID to get member for - * @param user_id User ID of member to get - * @return guild_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member guild_get_member_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Get all guild members - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_get_members - * @see https://discord.com/developers/docs/resources/guild#get-guild-members - * @param guild_id Guild ID to get all members for - * @param limit max number of members to return (1-1000) - * @param after the highest user id in the previous page - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member_map guild_get_members_sync(snowflake guild_id, uint16_t limit, snowflake after); - -/** - * @brief Add role to guild member - * - * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_add_role - * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to add a role to - * @param user_id User ID to add role to - * @param role_id Role ID to add to the user - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_add_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_delete - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @deprecated Replaced by dpp::cluster::guild_member_kick - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_delete_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Remove (kick) a guild member - * - * Remove a member from a guild. Requires `KICK_MEMBERS` permission. - * Fires a `Guild Member Remove` Gateway event. - * @see dpp::cluster::guild_member_kick - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to kick member from - * @param user_id User ID to kick - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_kick_sync(snowflake guild_id, snowflake user_id); - -/** - * @brief Set the timeout of a guild member - * - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_timeout - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to timeout the member in - * @param user_id User ID to set the timeout for - * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_timeout_sync(snowflake guild_id, snowflake user_id, time_t communication_disabled_until); - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_delete_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * @deprecated Use dpp::cluster::guild_member_remove_role instead - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_delete_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); - -/** - * @brief Remove role from guild member - * - * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::guild_member_remove_role - * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to remove role from user on - * @param user_id User ID to remove role from - * @param role_id Role to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_member_remove_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); - -/** - * @brief Moves the guild member to a other voice channel, if member is connected to one. - * Set the `channel_id` to `0` to disconnect the user. - * - * Fires a `Guild Member Update` Gateway event. - * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_member_move - * @see https://discord.com/developers/docs/resources/guild#modify-guild-member - * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user - * @param guild_id Guild id to which the user is connected - * @param user_id User id, who should be moved - * @return guild_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member guild_member_move_sync(const snowflake channel_id, const snowflake guild_id, const snowflake user_id); - -/** - * @brief Search for guild members based on whether their username or nickname starts with the given string. - * - * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. - * @see dpp::cluster::guild_search_members - * @see https://discord.com/developers/docs/resources/guild#search-guild-members - * @param guild_id Guild ID to search in - * @param query Query string to match username(s) and nickname(s) against - * @param limit max number of members to return (1-1000) - * @return guild_member_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_member_map guild_search_members_sync(snowflake guild_id, const std::string& query, uint16_t limit); - -/** - * @brief Get guild invites - * - * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. - * - * @see dpp::cluster::guild_get_invites - * @see https://discord.com/developers/docs/resources/guild#get-guild-invites - * @param guild_id Guild ID to get invites for - * @return invite_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -invite_map guild_get_invites_sync(snowflake guild_id); - - -invite invite_delete_sync(const std::string &invitecode); - - -invite invite_get_sync(const std::string &invitecode); - -/** - * @brief Send a message to a channel. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_create - * @see https://discord.com/developers/docs/resources/channel#create-message - * @param m Message to send - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_create_sync(const struct message &m); - -/** - * @brief Crosspost a message. The callback function is called when the message has been sent - * - * @see dpp::cluster::message_crosspost - * @see https://discord.com/developers/docs/resources/channel#crosspost-message - * @param message_id Message to crosspost - * @param channel_id Channel ID to crosspost from - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_crosspost_sync(snowflake message_id, snowflake channel_id); - -/** - * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. - * - * @see dpp::cluster::message_delete_bulk - * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages - * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_delete_bulk_sync(const std::vector &message_ids, snowflake channel_id); - -/** - * @brief Delete a message from a channel. The callback function is called when the message has been edited - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::message_delete - * @see https://discord.com/developers/docs/resources/channel#delete-message - * @param message_id Message ID to delete - * @param channel_id Channel to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_delete_sync(snowflake message_id, snowflake channel_id); - -/** - * @brief Edit a message on a channel. The callback function is called when the message has been edited - * - * @see dpp::cluster::message_edit - * @see https://discord.com/developers/docs/resources/channel#edit-message - * @param m Message to edit - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_edit_sync(const struct message &m); - -/** - * @brief Get a message - * - * @see dpp::cluster::message_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-message - * @param message_id Message ID - * @param channel_id Channel ID - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message message_get_sync(snowflake message_id, snowflake channel_id); - -/** - * @brief Pin a message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::message_pin - * @see https://discord.com/developers/docs/resources/channel#pin-message - * @param channel_id Channel id to pin message on - * @param message_id Message id to pin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_pin_sync(snowflake channel_id, snowflake message_id); - -/** - * @brief Get multiple messages. - * - * This function will attempt to fetch as many messages as possible using multiple API calls if needed. - * - * @see dpp::cluster::messages_get - * @see https://discord.com/developers/docs/resources/channel#get-channel-messages - * @param channel_id Channel ID to retrieve messages for - * @param around Messages should be retrieved around this ID if this is set to non-zero - * @param before Messages before this ID should be retrieved if this is set to non-zero - * @param after Messages after this ID should be retrieved if this is set to non-zero - * @param limit This number of messages maximum should be returned, up to a maximum of 100. - * @return message_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message_map messages_get_sync(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit); - -/** - * @brief Unpin a message - * @see dpp::cluster::message_unpin - * @see https://discord.com/developers/docs/resources/channel#unpin-message - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param channel_id Channel id to unpin message on - * @param message_id Message id to unpin message on - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation message_unpin_sync(snowflake channel_id, snowflake message_id); - -/** - * @brief Get a channel's pins - * @see dpp::cluster::channel_pins_get - * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages - * @param channel_id Channel ID to get pins for - * @return message_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message_map channel_pins_get_sync(snowflake channel_id); - -/** - * @brief Create a role on a guild - * - * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. - * Fires a `Guild Role Create` Gateway event. - * - * @see dpp::cluster::role_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to create (guild ID is encapsulated in the role object) - * @return role returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role role_create_sync(const class role &r); - -/** - * @brief Delete a role - * - * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. - * - * @see dpp::cluster::role_delete - * @see https://discord.com/developers/docs/resources/guild#delete-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to delete the role on - * @param role_id Role ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation role_delete_sync(snowflake guild_id, snowflake role_id); - -/** - * @brief Edit a role on a guild - * - * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. - * - * @see dpp::cluster::role_edit - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param r Role to edit - * @return role returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role role_edit_sync(const class role &r); - -/** - * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. - * - * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. - * Fires multiple `Guild Role Update` Gateway events. - * - * @see dpp::cluster::roles_edit_position - * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @param guild_id Guild ID to change the roles position on - * @param roles Vector of roles to change the positions of - * @return role_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role_map roles_edit_position_sync(snowflake guild_id, const std::vector &roles); - -/** - * @brief Get a role for a guild - * - * @see dpp::cluster::roles_get - * @see https://discord.com/developers/docs/resources/guild#get-guild-roles - * @param guild_id Guild ID to get role for - * @return role_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -role_map roles_get_sync(snowflake guild_id); - -/** - * @brief Get user application role connection - * - * @see dpp::cluster::user_application_role_connection_get - * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection - * @param application_id The application ID - * @return application_role_connection returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -application_role_connection user_application_role_connection_get_sync(snowflake application_id); - -/** - * @brief Update user application role connection - * - * @see dpp::cluster::user_application_role_connection_update - * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection - * @param application_id The application ID - * @param connection The application role connection to update - * @return application_role_connection returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -application_role_connection user_application_role_connection_update_sync(snowflake application_id, const application_role_connection &connection); - -/** - * @brief Get all scheduled events for a guild - * @see dpp::cluster::guild_events_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild - * @param guild_id Guild to get events for - * @return scheduled_event_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event_map guild_events_get_sync(snowflake guild_id); - -/** - * @brief Create a scheduled event on a guild - * - * @see dpp::cluster::guild_event_create - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event - * @param event Event to create (guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event guild_event_create_sync(const scheduled_event& event); - -/** - * @brief Delete a scheduled event from a guild - * - * @see dpp::cluster::guild_event_delete - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event - * @param event_id Event ID to delete - * @param guild_id Guild ID of event to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_event_delete_sync(snowflake event_id, snowflake guild_id); - -/** - * @brief Edit/modify a scheduled event on a guild - * - * @see dpp::cluster::guild_event_edit - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event - * @param event Event to create (event ID and guild ID must be populated) - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event guild_event_edit_sync(const scheduled_event& event); - -/** - * @brief Get a scheduled event for a guild - * - * @see dpp::cluster::guild_event_get - * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event - * @param guild_id Guild to get event for - * @param event_id Event ID to get - * @return scheduled_event returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -scheduled_event guild_event_get_sync(snowflake guild_id, snowflake event_id); - - -stage_instance stage_instance_create_sync(const stage_instance& si); - -/** - * @brief Get the stage instance associated with the channel id, if it exists. - * @see dpp::cluster::stage_instance_get - * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance - * @param channel_id ID of the associated channel - * @return stage_instance returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -stage_instance stage_instance_get_sync(const snowflake channel_id); - - -stage_instance stage_instance_edit_sync(const stage_instance& si); - -/** - * @brief Delete a stage instance. - * @see dpp::cluster::stage_instance_delete - * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance - * @param channel_id ID of the associated channel - * @return confirmation returned object on completion - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation stage_instance_delete_sync(const snowflake channel_id); - -/** - * @brief Create a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_create - * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker - * @param s Sticker to create. Must have its guild ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker guild_sticker_create_sync(sticker &s); - -/** - * @brief Delete a sticker from a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_delete - * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker - * @param sticker_id sticker ID to delete - * @param guild_id guild ID to delete from - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_sticker_delete_sync(snowflake sticker_id, snowflake guild_id); - -/** - * @brief Get a guild sticker - * @see dpp::cluster::guild_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker - * @param id Id of sticker to get. - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker guild_sticker_get_sync(snowflake id, snowflake guild_id); - -/** - * @brief Modify a sticker in a guild - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::guild_sticker_modify - * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker - * @param s Sticker to modify. Must have its guild ID and sticker ID set. - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker guild_sticker_modify_sync(sticker &s); - -/** - * @brief Get all guild stickers - * @see dpp::cluster::guild_stickers_get - * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers - * @param guild_id Guild ID of the guild where the sticker is - * @return sticker_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker_map guild_stickers_get_sync(snowflake guild_id); - -/** - * @brief Get a nitro sticker - * @see dpp::cluster::nitro_sticker_get - * @see https://discord.com/developers/docs/resources/sticker#get-sticker - * @param id Id of sticker to get. - * @return sticker returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker nitro_sticker_get_sync(snowflake id); - -/** - * @brief Get sticker packs - * @see dpp::cluster::sticker_packs_get - * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs - * @return sticker_pack_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -sticker_pack_map sticker_packs_get_sync(); - -/** - * @brief Create a new guild based on a template. - * @note This endpoint can be used only by bots in less than 10 guilds. - * @see dpp::cluster::guild_create_from_template - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template - * @param code Template code to create guild from - * @param name Guild name to create - * @return guild returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild guild_create_from_template_sync(const std::string &code, const std::string &name); - -/** - * @brief Creates a template for the guild - * - * @see dpp::cluster::guild_template_create - * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template - * @param guild_id Guild to create template from - * @param name Template name to create - * @param description Description of template to create - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate guild_template_create_sync(snowflake guild_id, const std::string &name, const std::string &description); - -/** - * @brief Deletes the template - * - * @see dpp::cluster::guild_template_delete - * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template - * @param guild_id Guild ID of template to delete - * @param code Template code to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation guild_template_delete_sync(snowflake guild_id, const std::string &code); - -/** - * @brief Modifies the template's metadata. - * - * @see dpp::cluster::guild_template_modify - * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template - * @param guild_id Guild ID of template to modify - * @param code Template code to modify - * @param name New name of template - * @param description New description of template - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate guild_template_modify_sync(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description); - -/** - * @brief Get guild templates - * - * @see dpp::cluster::guild_templates_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates - * @param guild_id Guild ID to get templates for - * @return dtemplate_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate_map guild_templates_get_sync(snowflake guild_id); - -/** - * @brief Syncs the template to the guild's current state. - * - * @see dpp::cluster::guild_template_sync - * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template - * @param guild_id Guild to synchronise template for - * @param code Code of template to synchronise - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate guild_template_sync_sync(snowflake guild_id, const std::string &code); - -/** - * @brief Get a template - * @see dpp::cluster::template_get - * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template - * @param code Template code - * @return dtemplate returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -dtemplate template_get_sync(const std::string &code); - -/** - * @brief Join a thread - * @see dpp::cluster::current_user_join_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to join - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_join_thread_sync(snowflake thread_id); - -/** - * @brief Leave a thread - * @see dpp::cluster::current_user_leave_thread - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_leave_thread_sync(snowflake thread_id); - -/** - * @brief Get active threads in a guild (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_active - * @see https://discord.com/developers/docs/topics/threads - * @param guild_id Guild to get active threads for - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_active_sync(snowflake guild_id); - -/** - * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) - * @see dpp::cluster::threads_get_joined_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_id Get threads before this id - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_joined_private_archived_sync(snowflake channel_id, snowflake before_id, uint16_t limit); - -/** - * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_private_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_private_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); - -/** - * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) - * @see dpp::cluster::threads_get_public_archived - * @see https://discord.com/developers/docs/topics/threads - * @param channel_id Channel to get public archived threads for - * @param before_timestamp Get threads before this timestamp - * @param limit Number of threads to get - * @return thread_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_map threads_get_public_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); - -/** - * @brief Get a thread member - * @see dpp::cluster::thread_member_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get member for - * @param user_id ID of the user to get - * @return thread_member returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_member thread_member_get_sync(const snowflake thread_id, const snowflake user_id); - -/** - * @brief Get members of a thread - * @see dpp::cluster::thread_members_get - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread to get members for - * @return thread_member_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread_member_map thread_members_get_sync(snowflake thread_id); - -/** - * @brief Create a thread in forum channel - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::thread_create_in_forum - * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel - * @param thread_name Name of the forum thread - * @param channel_id Forum channel in which thread to create - * @param msg The message to start the thread with - * @param auto_archive_duration Duration to automatically archive the thread after recent activity - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread - * @return thread returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread thread_create_in_forum_sync(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}); - -/** - * @brief Create a thread - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * - * @see dpp::cluster::thread_create - * @see https://discord.com/developers/docs/resources/guild#create-guild-channel - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD - * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread thread_create_sync(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user); - -/** - * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::thread_create_with_message - * @see https://discord.com/developers/docs/topics/threads - * @param thread_name Name of the thread - * @param channel_id Channel in which thread to create - * @param message_id message to start thread with - * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) - * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected - * @return thread returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -thread thread_create_with_message_sync(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user); - -/** - * @brief Add a member to a thread - * @see dpp::cluster::thread_member_add - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to add to - * @param user_id Member ID to add - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation thread_member_add_sync(snowflake thread_id, snowflake user_id); - -/** - * @brief Remove a member from a thread - * @see dpp::cluster::thread_member_remove - * @see https://discord.com/developers/docs/topics/threads - * @param thread_id Thread ID to remove from - * @param user_id Member ID to remove - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation thread_member_remove_sync(snowflake thread_id, snowflake user_id); - -/** - * @brief Edit current (bot) user - * - * Modifies the current member in a guild. Returns the updated guild_member object on success. - * Fires a `Guild Member Update` Gateway event. - * @see dpp::cluster::current_user_edit - * @see https://discord.com/developers/docs/resources/user#modify-current-user - * @param nickname Nickname to set - * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) - * @param type Type of image for avatar - * @return user returned object on completion - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -user current_user_edit_sync(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png); - -/** - * @brief Get current (bot) application - * - * @see dpp::cluster::current_application_get - * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information - * @return application returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -application current_application_get_sync(); - -/** - * @brief Get current (bot) user - * - * @see dpp::cluster::current_user_get - * @see https://discord.com/developers/docs/resources/user#get-current-user - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -user_identified current_user_get_sync(); - -/** - * @brief Set the bot's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - current user must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. - * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. - * - You are able to set `request_to_speak_timestamp` to any present or future time. - * - * @see dpp::cluster::current_user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. - * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_set_voice_state_sync(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0); - -/** - * @brief Set a user's voice state on a stage channel - * - * **Caveats** - * - * There are currently several caveats for this endpoint: - * - * - `channel_id` must currently point to a stage channel. - * - User must already have joined `channel_id`. - * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) - * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. - * - When suppressed, the user will have their `request_to_speak_timestamp` removed. - * - * @see dpp::cluster::user_set_voice_state - * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state - * @param user_id The user to set the voice state of - * @param guild_id Guild to set voice state on - * @param channel_id Stage channel to set voice state on - * @return confirmation returned object on completion - * @param suppress True if the user's audio should be suppressed, false if it should not - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation user_set_voice_state_sync(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false); - -/** - * @brief Get current user's connections (linked accounts, e.g. steam, xbox). - * This call requires the oauth2 `connections` scope and cannot be executed - * against a bot token. - * @see dpp::cluster::current_user_connections_get - * @see https://discord.com/developers/docs/resources/user#get-user-connections - * @return connection_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -connection_map current_user_connections_get_sync(); - -/** - * @brief Get current (bot) user guilds - * @see dpp::cluster::current_user_get_guilds - * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds - * @return guild_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -guild_map current_user_get_guilds_sync(); - -/** - * @brief Leave a guild - * @see dpp::cluster::current_user_leave_guild - * @see https://discord.com/developers/docs/resources/user#leave-guild - * @param guild_id Guild ID to leave - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation current_user_leave_guild_sync(snowflake guild_id); - -/** - * @brief Get a user by id - * - * @see dpp::cluster::user_get - * @see https://discord.com/developers/docs/resources/user#get-user - * @param user_id User ID to retrieve - * @return user_identified returned object on completion - * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. - * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. - * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. - * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -user_identified user_get_sync(snowflake user_id); - -/** - * @brief Get all voice regions - * @see dpp::cluster::get_voice_regions - * @see https://discord.com/developers/docs/resources/voice#list-voice-regions - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -voiceregion_map get_voice_regions_sync(); - -/** - * @brief Get guild voice regions. - * - * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. - * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when - * the guild is VIP-enabled. - * - * @see dpp::cluster::guild_get_voice_regions - * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions - * @param guild_id Guild ID to get voice regions for - * @return voiceregion_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -voiceregion_map guild_get_voice_regions_sync(snowflake guild_id); - -/** - * @brief Create a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::create_webhook - * @see https://discord.com/developers/docs/resources/webhook#create-webhook - * @param w Webhook to create - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook create_webhook_sync(const class webhook &w); - -/** - * @brief Delete a webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::delete_webhook - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook - * @param webhook_id Webhook ID to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation delete_webhook_sync(snowflake webhook_id); - -/** - * @brief Delete webhook message - * - * @see dpp::cluster::delete_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message - * @param wh Webhook to delete message for - * @param message_id Message ID to delete - * @param thread_id ID of the thread the message is in - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation delete_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); - -/** - * @brief Delete webhook with token - * @see dpp::cluster::delete_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token - * @param webhook_id Webhook ID to delete - * @param token Token of webhook to delete - * @return confirmation returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -confirmation delete_webhook_with_token_sync(snowflake webhook_id, const std::string &token); - -/** - * @brief Edit webhook - * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. - * @see dpp::cluster::edit_webhook - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook - * @param wh Webhook to edit - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook edit_webhook_sync(const class webhook& wh); - -/** - * @brief Edit webhook message - * - * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on - * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit - * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to - * whether or not an allowed_mentions was present in the request that originally created the message. - * - * @see dpp::cluster::edit_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message - * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. - * @param wh Webhook to edit message for - * @param m New message - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message edit_webhook_message_sync(const class webhook &wh, const struct message &m, snowflake thread_id = 0); - -/** - * @brief Edit webhook with token (token is encapsulated in the webhook object) - * @see dpp::cluster::edit_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token - * @param wh Webhook to edit (should include token) - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook edit_webhook_with_token_sync(const class webhook& wh); - -/** - * @brief Execute webhook - * - * @see dpp::cluster::execute_webhook - * @see https://discord.com/developers/docs/resources/webhook#execute-webhook - * @param wh Webhook to execute - * @param m Message to send - * @param wait waits for server confirmation of message send before response, and returns the created message body - * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived - * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) - * @return message returned object on completion - * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message execute_webhook_sync(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = ""); - -/** - * @brief Get channel webhooks - * @see dpp::cluster::get_channel_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param channel_id Channel ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook_map get_channel_webhooks_sync(snowflake channel_id); - -/** - * @brief Get guild webhooks - * @see dpp::cluster::get_guild_webhooks - * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks - * @param guild_id Guild ID to get webhooks for - * @return webhook_map returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook_map get_guild_webhooks_sync(snowflake guild_id); - -/** - * @brief Get webhook - * @see dpp::cluster::get_webhook - * @see https://discord.com/developers/docs/resources/webhook#get-webhook - * @param webhook_id Webhook ID to get - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook get_webhook_sync(snowflake webhook_id); - -/** - * @brief Get webhook message - * - * @see dpp::cluster::get_webhook_message - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message - * @param wh Webhook to get the original message for - * @param message_id The message ID - * @param thread_id ID of the thread the message is in - * @return message returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -message get_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); - -/** - * @brief Get webhook using token - * @see dpp::cluster::get_webhook_with_token - * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token - * @param webhook_id Webhook ID to retrieve - * @param token Token of webhook - * @return webhook returned object on completion - * \memberof dpp::cluster - * @throw dpp::rest_exception upon failure to execute REST function - * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. - * Avoid direct use of this function inside an event handler. - */ -webhook get_webhook_with_token_sync(snowflake webhook_id, const std::string &token); - - -/* End of auto-generated definitions */ +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + + +/* Auto @generated by buildtools/make_sync_struct.php. + * + * DO NOT EDIT BY HAND! + * + * To re-generate this header file re-run the script! + */ +/** + * @brief Create/overwrite global slash commands. + * Any existing global slash commands will be deleted and replaced with these. + * + * @see dpp::cluster::global_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-global-application-commands + * @param commands Vector of slash commands to create/update. + * overwriting existing commands that are registered globally for this application. Updates will be available in all guilds after 1 hour. + * Commands that do not already exist will count toward daily application command create limits. + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map global_bulk_command_create_sync(const std::vector &commands); + +/** + * @brief Create a global slash command (a bot can have a maximum of 100 of these). + * + * @see dpp::cluster::global_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-global-application-command + * @param s Slash command to create + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand global_command_create_sync(const slashcommand &s); + +/** + * @brief Get a global slash command + * + * @see dpp::cluster::global_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-command + * @param id The ID of the slash command + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand global_command_get_sync(snowflake id); + +/** + * @brief Delete a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-global-application-command + * @param id Slash command to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation global_command_delete_sync(snowflake id); + +/** + * @brief Edit a global slash command (a bot can have a maximum of 100 of these) + * + * @see dpp::cluster::global_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-global-application-command + * @param s Slash command to change + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation global_command_edit_sync(const slashcommand &s); + +/** + * @brief Get the application's global slash commands + * + * @see dpp::cluster::global_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-global-application-commands + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map global_commands_get_sync(); + +/** + * @brief Create/overwrite guild slash commands. + * Any existing guild slash commands on this guild will be deleted and replaced with these. + * + * @see dpp::cluster::guild_bulk_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#bulk-overwrite-guild-application-commands + * @param commands Vector of slash commands to create/update. + * New guild commands will be available in the guild immediately. If the command did not already exist, it will count toward daily application command create limits. + * @param guild_id Guild ID to create/update the slash commands in + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map guild_bulk_command_create_sync(const std::vector &commands, snowflake guild_id); + +/** + * @brief Get all slash command permissions of a guild + * + * @see dpp::cluster::guild_commands_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param guild_id Guild ID to get the slash commands permissions for + * @return guild_command_permissions_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_command_permissions_map guild_commands_get_permissions_sync(snowflake guild_id); + +/** + * @brief Edit/Overwrite the permissions of all existing slash commands in a guild + * + * @note You can only add up to 10 permission overwrites for a command + * + * @see dpp::cluster::guild_bulk_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#batch-edit-application-command-permissions + * @warning The endpoint will overwrite all existing permissions for all commands of the application in a guild, including slash commands, user commands, and message commands. Meaning that if you forgot to pass a slash command, the permissions of it might be removed. + * @param commands A vector of slash commands to edit/overwrite the permissions for + * @param guild_id Guild ID to edit permissions of the slash commands in + * @return guild_command_permissions_map returned object on completion + * @deprecated This has been disabled with updates to Permissions v2. You can use guild_command_edit_permissions instead + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_command_permissions_map guild_bulk_command_edit_permissions_sync(const std::vector &commands, snowflake guild_id); + +/** + * @brief Create a slash command local to a guild + * + * @see dpp::cluster::guild_command_create + * @see https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command + * @note Creating a command with the same name as an existing command for your application will overwrite the old command. + * @param s Slash command to create + * @param guild_id Guild ID to create the slash command in + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand guild_command_create_sync(const slashcommand &s, snowflake guild_id); + +/** + * @brief Delete a slash command local to a guild + * + * @see dpp::cluster::guild_command_delete + * @see https://discord.com/developers/docs/interactions/application-commands#delete-guild-application-command + * @param id Slash command to delete + * @param guild_id Guild ID to delete the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_command_delete_sync(snowflake id, snowflake guild_id); + +/** + * @brief Edit slash command permissions of a guild + * + * @see dpp::cluster::guild_command_edit_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#edit-application-command-permissions + * @note You can only add up to 10 permission overwrites for a command + * @param s Slash command to edit the permissions for + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_command_edit_permissions_sync(const slashcommand &s, snowflake guild_id); + +/** + * @brief Get a slash command of a guild + * + * @see dpp::cluster::guild_command_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-command + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param id The ID of the slash command + * @param guild_id Guild ID to get the slash command from + * @return slashcommand returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand guild_command_get_sync(snowflake id, snowflake guild_id); + +/** + * @brief Get the permissions for a slash command of a guild + * + * @see dpp::cluster::guild_command_get_permissions + * @see https://discord.com/developers/docs/interactions/application-commands#get-application-command-permissions + * @param id The ID of the slash command to get the permissions for + * @param guild_id Guild ID to get the permissions of + * @return guild_command_permissions returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_command_permissions guild_command_get_permissions_sync(snowflake id, snowflake guild_id); + +/** + * @brief Edit a slash command local to a guild + * + * @see dpp::cluster::guild_command_edit + * @see https://discord.com/developers/docs/interactions/application-commands#edit-guild-application-command + * @param s Slash command to edit + * @param guild_id Guild ID to edit the slash command in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_command_edit_sync(const slashcommand &s, snowflake guild_id); + +/** + * @brief Get the application's slash commands for a guild + * + * @see dpp::cluster::guild_commands_get + * @see https://discord.com/developers/docs/interactions/application-commands#get-guild-application-commands + * @note The returned slash commands will not have permissions set, you need to use a permissions getter e.g. dpp::guild_commands_get_permissions to get the guild command permissions + * @param guild_id Guild ID to get the slash commands for + * @return slashcommand_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +slashcommand_map guild_commands_get_sync(snowflake guild_id); + +/** + * @brief Respond to a slash command + * + * @see dpp::cluster::interaction_response_create + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#create-interaction-response + * @param interaction_id Interaction id to respond to + * @param token Token for the interaction webhook + * @param r Response to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_response_create_sync(snowflake interaction_id, const std::string &token, const interaction_response &r); + +/** + * @brief Edit response to a slash command + * + * @see dpp::cluster::interaction_response_edit + * @see https://discord.com/developers/docs/interactions/receiving-and-responding#edit-original-interaction-response + * @param token Token for the interaction webhook + * @param m Message to send + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_response_edit_sync(const std::string &token, const message &m); + +/** + * @brief Create a followup message to a slash command + * + * @param token Token for the interaction webhook + * @param m followup message to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_create_sync(const std::string &token, const message &m); + +/** + * @brief Edit original followup message to a slash command + * This is an alias for cluster::interaction_response_edit + * @see dpp::cluster::interaction_followup_edit_original + * @see cluster::interaction_response_edit + * + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_edit_original_sync(const std::string &token, const message &m); + +/** + * @brief + * + * @param token Token for the interaction webhook + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_delete_sync(const std::string &token); + +/** + * @brief Edit followup message to a slash command + * The message ID in the message you pass should be correctly set to that of a followup message you previously sent + * @param token Token for the interaction webhook + * @param m message to edit, the ID should be set + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation interaction_followup_edit_sync(const std::string &token, const message &m); + +/** + * @brief Get the followup message to a slash command + * @param token Token for the interaction webhook + * @param message_id message to retrieve + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message interaction_followup_get_sync(const std::string &token, snowflake message_id); + +/** + * @brief Get all auto moderation rules for a guild + * + * @param guild_id Guild id of the auto moderation rule + * @return automod_rule_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule_map automod_rules_get_sync(snowflake guild_id); + +/** + * @brief Get a single auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Rule id to retrieve + * @return automod_rule returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule automod_rule_get_sync(snowflake guild_id, snowflake rule_id); + +/** + * @brief Create an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to create + * @return automod_rule returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule automod_rule_create_sync(snowflake guild_id, const automod_rule& r); + +/** + * @brief Edit an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param r Auto moderation rule to edit. The rule's id must be set. + * @return automod_rule returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +automod_rule automod_rule_edit_sync(snowflake guild_id, const automod_rule& r); + +/** + * @brief Delete an auto moderation rule + * + * @param guild_id Guild id of the auto moderation rule + * @param rule_id Auto moderation rule id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation automod_rule_delete_sync(snowflake guild_id, snowflake rule_id); + +/** + * @brief Create a channel + * + * Create a new channel object for the guild. Requires the `MANAGE_CHANNELS` permission. If setting permission overwrites, + * only permissions your bot has in the guild can be allowed/denied. Setting `MANAGE_ROLES` permission in channels is only possible + * for guild administrators. Returns the new channel object on success. Fires a `Channel Create Gateway` event. + * + * All parameters to this endpoint are optional excluding `name` + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_create + * @see https://discord.com/developers/docs/resources/channel#create-channel + * @param c Channel to create + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel channel_create_sync(const class channel &c); + +/** + * @brief Remove a permission from a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete_permission + * @see https://discord.com/developers/docs/resources/channel#delete-channel-permission + * @param c Channel to remove permission from + * @param overwrite_id Overwrite to remove, user or channel ID + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_delete_permission_sync(const class channel &c, snowflake overwrite_id); + +/** + * @brief Delete a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_delete + * @see https://discord.com/developers/docs/resources/channel#deleteclose-channel + * @param channel_id Channel id to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_delete_sync(snowflake channel_id); + +/** + * @brief Edit multiple channels positions + * + * Modify the positions of a set of channel objects for the guild. + * Requires `MANAGE_CHANNELS` permission. Fires multiple `Channel Update Gateway` events. + * Only channels to be modified are required. + * + * @see dpp::cluster::channel_edit_positions + * @see https://discord.com/developers/docs/resources/guild#modify-guild-channel-positions + * @param c Channel to change the position for + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_edit_positions_sync(const std::vector &c); + +/** + * @brief Edit a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_edit + * @see https://discord.com/developers/docs/resources/channel#modify-channel + * @param c Channel to edit/update + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel channel_edit_sync(const class channel &c); + +/** + * @brief Follow an announcement (news) channel + * @see dpp::cluster::channel_follow_news + * @see https://discord.com/developers/docs/resources/channel#follow-news-channel + * @param c Channel id to follow + * @param target_channel_id Channel to subscribe the channel to + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_follow_news_sync(const class channel &c, snowflake target_channel_id); + +/** + * @brief Get a channel + * + * @see dpp::cluster::channel_get + * @see https://discord.com/developers/docs/resources/channel#get-channel + * @param c Channel ID to retrieve + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel channel_get_sync(snowflake c); + +/** + * @brief Create invite for a channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::channel_invite_create + * @see https://discord.com/developers/docs/resources/channel#create-channel-invite + * @param c Channel to create an invite on + * @param i Invite to create + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation channel_invite_create_sync(const class channel &c, const class invite &i); + +/** + * @brief Get invites for a channel + * + * @see dpp::cluster::channel_invites_get + * @see https://discord.com/developers/docs/resources/invite#get-invites + * @param c Channel to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +invite_map channel_invites_get_sync(const class channel &c); + +/** + * @brief Get all channels for a guild + * + * @see dpp::cluster::channels_get + * @see https://discord.com/developers/docs/resources/channel#get-channels + * @param guild_id Guild ID to retrieve channels for + * @return channel_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel_map channels_get_sync(snowflake guild_id); + +/** + * @brief Create a dm channel + * @see dpp::cluster::create_dm_channel + * @see https://discord.com/developers/docs/resources/user#create-dm + * @param user_id User ID to create DM channel with + * @return channel returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel create_dm_channel_sync(snowflake user_id); + +/** + * @brief Get current user DM channels + * + * @return channel_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +channel_map current_user_get_dms_sync(); + +/** + * @brief Create a direct message, also create the channel for the direct message if needed + * + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/user#create-dm + * @see dpp::cluster::direct_message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param user_id User ID of user to send message to + * @param m Message object + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message direct_message_create_sync(snowflake user_id, const message &m); + +/** + * @brief Adds a recipient to a Group DM using their access token + * @see dpp::cluster::gdm_add + * @see https://discord.com/developers/docs/resources/channel#group-dm-add-recipient + * @param channel_id Channel id to add group DM recipients to + * @param user_id User ID to add + * @param access_token Access token from OAuth2 + * @param nick Nickname of user to apply to the chat + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation gdm_add_sync(snowflake channel_id, snowflake user_id, const std::string &access_token, const std::string &nick); + +/** + * @brief Removes a recipient from a Group DM + * @see dpp::cluster::gdm_remove + * @see https://discord.com/developers/docs/resources/channel#group-dm-remove-recipient + * @param channel_id Channel ID of group DM + * @param user_id User ID to remove from group DM + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation gdm_remove_sync(snowflake channel_id, snowflake user_id); + +/** + * @brief Create single emoji. + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_create + * @see https://discord.com/developers/docs/resources/emoji#create-guild-emoji + * @param guild_id Guild ID to create emoji om + * @param newemoji Emoji to create + * @return emoji returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji guild_emoji_create_sync(snowflake guild_id, const class emoji& newemoji); + +/** + * @brief Delete a guild emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_emoji_delete + * @see https://discord.com/developers/docs/resources/emoji#delete-guild-emoji + * @param guild_id Guild ID to delete emoji on + * @param emoji_id Emoji ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_emoji_delete_sync(snowflake guild_id, snowflake emoji_id); + +/** + * @brief Edit a single emoji. + * + * You must ensure that the emoji passed contained image data using the emoji::load_image() method. + * @see dpp::cluster::guild_emoji_edit + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit emoji on + * @param newemoji Emoji to edit + * @return emoji returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji guild_emoji_edit_sync(snowflake guild_id, const class emoji& newemoji); + +/** + * @brief Get a single emoji + * + * @see dpp::cluster::guild_emoji_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emoji + * @param guild_id Guild ID to get emoji for + * @param emoji_id Emoji ID to get + * @return emoji returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji guild_emoji_get_sync(snowflake guild_id, snowflake emoji_id); + +/** + * @brief Get all emojis for a guild + * + * @see dpp::cluster::guild_emojis_get + * @see https://discord.com/developers/docs/resources/emoji#get-guild-emojis + * @param guild_id Guild ID to get emojis for + * @return emoji_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +emoji_map guild_emojis_get_sync(snowflake guild_id); + +/** + * @brief Get the gateway information for the bot using the token + * @see dpp::cluster::get_gateway_bot + * @see https://discord.com/developers/docs/topics/gateway#get-gateway-bot + * @return gateway returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +gateway get_gateway_bot_sync(); + +/** + * @brief Modify current member + * + * Modifies the current member in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_current_member_edit + * @see https://discord.com/developers/docs/resources/guild#modify-current-member + * @param guild_id Guild ID to change on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_current_member_edit_sync(snowflake guild_id, const std::string &nickname); + +/** + * @brief Get the audit log for a guild + * + * @see dpp::cluster::guild_auditlog_get + * @see https://discord.com/developers/docs/resources/audit-log#get-guild-audit-log + * @param guild_id Guild to get the audit log of + * @param user_id Entries from a specific user ID. Set this to `0` will fetch any user + * @param action_type Entries for a specific dpp::audit_type. Set this to `0` will fetch any type + * @param before Entries that preceded a specific audit log entry ID. Used for paginating + * @param limit Maximum number of entries (between 1-100) to return + * @return auditlog returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +auditlog guild_auditlog_get_sync(snowflake guild_id, snowflake user_id, uint32_t action_type, snowflake before, uint32_t limit); + +/** + * @brief Add guild ban + * + * Create a guild ban, and optionally delete previous messages sent by the banned user. + * Requires the `BAN_MEMBERS` permission. Fires a `Guild Ban Add` Gateway event. + * @see dpp::cluster::guild_ban_add + * @see https://discord.com/developers/docs/resources/guild#create-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add ban to + * @param user_id User ID to ban + * @param delete_message_seconds How many seconds to delete messages for, between 0 and 604800 (7 days). Defaults to 0 + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_ban_add_sync(snowflake guild_id, snowflake user_id, uint32_t delete_message_seconds = 0); + +/** + * @brief Delete guild ban + * + * Remove the ban for a user. Requires the `BAN_MEMBERS` permissions. + * Fires a Guild Ban Remove Gateway event. + * @see dpp::cluster::guild_ban_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-ban + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild to delete ban from + * @param user_id User ID to delete ban for + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_ban_delete_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Create a guild + * + * Create a new guild. Returns a guild object on success. `Fires a Guild Create Gateway` event. + * + * When using the roles parameter, the first member of the array is used to change properties of the guild's everyone role. + * If you are trying to bootstrap a guild with additional roles, keep this in mind. The required id field within each role object is an + * integer placeholder, and will be replaced by the API upon consumption. Its purpose is to allow you to overwrite a role's permissions + * in a channel when also passing in channels with the channels array. + * When using the channels parameter, the position field is ignored, and none of the default channels are created. The id field within + * each channel object may be set to an integer placeholder, and will be replaced by the API upon consumption. Its purpose is to + * allow you to create `GUILD_CATEGORY` channels by setting the `parent_id` field on any children to the category's id field. + * Category channels must be listed before any children. + * + * @see dpp::cluster::guild_create + * @see https://discord.com/developers/docs/resources/guild#create-guild + * @note The region field is deprecated and is replaced by channel.rtc_region. This endpoint can be used only by bots in less than 10 guilds. + * @param g Guild to create + * @return guild returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild guild_create_sync(const class guild &g); + +/** + * @brief Delete a guild + * + * Delete a guild permanently. User must be owner. Fires a `Guild Delete Gateway` event. + * + * @see dpp::cluster::guild_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild + * @param guild_id Guild ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_delete_sync(snowflake guild_id); + +/** + * @brief Delete guild integration + * + * Delete the attached integration object for the guild. Deletes any associated webhooks and kicks the associated bot if there is one. + * Requires the `MANAGE_GUILD` permission. Fires a Guild Integrations Update Gateway event. + * + * @see dpp::cluster::guild_delete_integration + * @see https://discord.com/developers/docs/resources/guild#delete-guild-integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete integration for + * @param integration_id Integration ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_delete_integration_sync(snowflake guild_id, snowflake integration_id); + +/** + * @brief Edit a guild + * + * Modify a guild's settings. Requires the `MANAGE_GUILD` permission. Returns the updated guild object on success. + * Fires a `Guild Update Gateway` event. + * + * @see dpp::cluster::guild_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param g Guild to edit + * @return guild returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild guild_edit_sync(const class guild &g); + +/** + * @brief Edit guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_edit_widget + * @see https://discord.com/developers/docs/resources/guild#modify-guild-widget + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to edit widget for + * @param gw New guild widget information + * @return guild_widget returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_widget guild_edit_widget_sync(snowflake guild_id, const class guild_widget &gw); + +/** + * @brief Get single guild ban + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_ban + * @see https://discord.com/developers/docs/resources/guild#get-guild-ban + * @param guild_id Guild ID to get ban for + * @param user_id User ID of ban to retrieve + * @return ban returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +ban guild_get_ban_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Get guild ban list + * + * Requires the `BAN_MEMBERS` permission. + * @see dpp::cluster::guild_get_bans + * @see https://discord.com/developers/docs/resources/guild#get-guild-bans + * @note Provide a user ID to `before` and `after` for pagination. Users will always be returned in ascending order by the user ID. If both before and after are provided, only before is respected. + * @param guild_id Guild ID to get bans for + * @param before If non-zero, all bans for user ids before this user id will be returned up to the limit + * @param after if non-zero, all bans for user ids after this user id will be returned up to the limit + * @param limit the maximum number of bans to retrieve in this call up to a maximum of 1000 + * @return ban_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +ban_map guild_get_bans_sync(snowflake guild_id, snowflake before, snowflake after, snowflake limit); + + +guild guild_get_sync(snowflake guild_id); + +/** + * @brief Get guild integrations + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_integrations + * @see https://discord.com/developers/docs/resources/guild#get-guild-integrations + * @param guild_id Guild ID to get integrations for + * @return integration_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +integration_map guild_get_integrations_sync(snowflake guild_id); + + +guild guild_get_preview_sync(snowflake guild_id); + +/** + * @brief Get guild vanity url, if enabled + * + * Returns a partial dpp::invite object for guilds with that feature enabled. Requires the `MANAGE_GUILD` permission. code will be null if a vanity url for the guild is not set. + * @see dpp::cluster::guild_get_vanity + * @see https://discord.com/developers/docs/resources/guild#get-guild-vanity-url + * @param guild_id Guild to get vanity URL for + * @return invite returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +invite guild_get_vanity_sync(snowflake guild_id); + +/** + * @brief Get guild widget + * + * Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_widget + * @see https://discord.com/developers/docs/resources/guild#get-guild-widget + * @param guild_id Guild ID to get widget for + * @return guild_widget returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_widget guild_get_widget_sync(snowflake guild_id); + +/** + * @brief Modify guild integration + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::guild_modify_integration + * @see https://discord.com/developers/docs/resources/guild#modify-guild-integration + * @param guild_id Guild ID to modify integration for + * @param i Integration to modify + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_modify_integration_sync(snowflake guild_id, const class integration &i); + +/** + * @brief Get prune counts + * + * Returns a prune object indicating the number of members that would be removed in a prune operation. Requires the `KICK_MEMBERS` + * permission. By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the + * include_roles parameter. Any inactive user that has a subset of the provided role(s) will be counted in the prune and users with additional + * roles will not. + * + * @see dpp::cluster::guild_get_prune_counts + * @see https://discord.com/developers/docs/resources/guild#get-guild-prune-count + * @param guild_id Guild ID to count for pruning + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +prune guild_get_prune_counts_sync(snowflake guild_id, const struct prune& pruneinfo); + +/** + * @brief Begin guild prune + * + * Begin a prune operation. Requires the `KICK_MEMBERS` permission. Returns a prune object indicating the number of members + * that were removed in the prune operation. For large guilds it's recommended to set the `compute_prune_count` option to false, forcing + * 'pruned' to 0. Fires multiple `Guild Member Remove` Gateway events. + * By default, prune will not remove users with roles. You can optionally include specific roles in your prune by providing the `include_roles` + * parameter. Any inactive user that has a subset of the provided role(s) will be included in the prune and users with additional roles will not. + * + * @see dpp::cluster::guild_begin_prune + * @see https://discord.com/developers/docs/resources/guild#begin-guild-prune + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to prune + * @param pruneinfo Pruning info + * @return prune returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +prune guild_begin_prune_sync(snowflake guild_id, const struct prune& pruneinfo); + +/** + * @brief Change current user nickname + * + * Modifies the nickname of the current user in a guild. + * Fires a `Guild Member Update` Gateway event. + * + * @deprecated Deprecated in favor of Modify Current Member. Will be replaced by dpp::cluster::guild_current_member_edit + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_set_nickname + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-nick + * @param guild_id Guild ID to change nickname on + * @param nickname New nickname, or empty string to clear nickname + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_set_nickname_sync(snowflake guild_id, const std::string &nickname); + +/** + * @brief Sync guild integration + * + * @see dpp::cluster::guild_sync_integration + * @see https://discord.com/developers/docs/resources/guild#sync-guild-integration + * @param guild_id Guild ID to sync integration on + * @param integration_id Integration ID to synchronise + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_sync_integration_sync(snowflake guild_id, snowflake integration_id); + +/** + * @brief Add guild member. Needs a specific oauth2 scope, from which you get the access_token. + * + * Adds a user to the guild, provided you have a valid oauth2 access token for the user with the guilds.join scope. + * Returns the guild_member, which is defaulted if the user is already a member of the guild. Fires a `Guild Member Add` Gateway event. + * + * For guilds with Membership Screening enabled, this endpoint will default to adding new members as pending in the guild member object. + * Members that are pending will have to complete membership screening before they become full members that can talk. + * + * @note All parameters to this endpoint except for access_token are optional. + * The bot must be a member of the guild with `CREATE_INSTANT_INVITE` permission. + * @see dpp::cluster::guild_add_member + * @see https://discord.com/developers/docs/resources/guild#add-guild-member + * @param gm Guild member to add + * @param access_token Access token from Oauth2 scope + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_add_member_sync(const guild_member& gm, const std::string &access_token); + +/** + * @brief Edit the properties of an existing guild member + * + * Modify attributes of a guild member. Returns the guild_member. Fires a `Guild Member Update` Gateway event. + * To remove a timeout, set the `communication_disabled_until` to a non-zero time in the past, e.g. 1. + * When moving members to channels, the API user must have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * For moving and disconnecting users from voice, use dpp::cluster::guild_member_move. + * @see dpp::cluster::guild_edit_member + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param gm Guild member to edit + * @return guild_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member guild_edit_member_sync(const guild_member& gm); + +/** + * @brief Get a guild member + * @see dpp::cluster::guild_get_member + * @see https://discord.com/developers/docs/resources/guild#get-guild-member + * @param guild_id Guild ID to get member for + * @param user_id User ID of member to get + * @return guild_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member guild_get_member_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Get all guild members + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_get_members + * @see https://discord.com/developers/docs/resources/guild#get-guild-members + * @param guild_id Guild ID to get all members for + * @param limit max number of members to return (1-1000) + * @param after the highest user id in the previous page + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member_map guild_get_members_sync(snowflake guild_id, uint16_t limit, snowflake after); + +/** + * @brief Add role to guild member + * + * Adds a role to a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_add_role + * @see https://discord.com/developers/docs/resources/guild#add-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to add a role to + * @param user_id User ID to add role to + * @param role_id Role ID to add to the user + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_add_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_delete + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @deprecated Replaced by dpp::cluster::guild_member_kick + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_delete_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Remove (kick) a guild member + * + * Remove a member from a guild. Requires `KICK_MEMBERS` permission. + * Fires a `Guild Member Remove` Gateway event. + * @see dpp::cluster::guild_member_kick + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to kick member from + * @param user_id User ID to kick + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_kick_sync(snowflake guild_id, snowflake user_id); + +/** + * @brief Set the timeout of a guild member + * + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_timeout + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to timeout the member in + * @param user_id User ID to set the timeout for + * @param communication_disabled_until The timestamp when the user's timeout will expire (up to 28 days in the future). Set to 0 to remove the timeout + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_timeout_sync(snowflake guild_id, snowflake user_id, time_t communication_disabled_until); + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_delete_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * @deprecated Use dpp::cluster::guild_member_remove_role instead + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_delete_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); + +/** + * @brief Remove role from guild member + * + * Removes a role from a guild member. Requires the `MANAGE_ROLES` permission. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::guild_member_remove_role + * @see https://discord.com/developers/docs/resources/guild#remove-guild-member-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to remove role from user on + * @param user_id User ID to remove role from + * @param role_id Role to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_member_remove_role_sync(snowflake guild_id, snowflake user_id, snowflake role_id); + +/** + * @brief Moves the guild member to a other voice channel, if member is connected to one. + * Set the `channel_id` to `0` to disconnect the user. + * + * Fires a `Guild Member Update` Gateway event. + * @note When moving members to channels, the API user __must__ have permissions to both connect to the channel and have the `MOVE_MEMBERS` permission. + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_member_move + * @see https://discord.com/developers/docs/resources/guild#modify-guild-member + * @param channel_id Id of the channel to which the user is used. Set to `0` to disconnect the user + * @param guild_id Guild id to which the user is connected + * @param user_id User id, who should be moved + * @return guild_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member guild_member_move_sync(const snowflake channel_id, const snowflake guild_id, const snowflake user_id); + +/** + * @brief Search for guild members based on whether their username or nickname starts with the given string. + * + * @note This endpoint is restricted according to whether the `GUILD_MEMBERS` Privileged Intent is enabled for your application. + * @see dpp::cluster::guild_search_members + * @see https://discord.com/developers/docs/resources/guild#search-guild-members + * @param guild_id Guild ID to search in + * @param query Query string to match username(s) and nickname(s) against + * @param limit max number of members to return (1-1000) + * @return guild_member_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_member_map guild_search_members_sync(snowflake guild_id, const std::string& query, uint16_t limit); + +/** + * @brief Get guild invites + * + * Returns a list of invite objects (with invite metadata) for the guild. Requires the `MANAGE_GUILD` permission. + * + * @see dpp::cluster::guild_get_invites + * @see https://discord.com/developers/docs/resources/guild#get-guild-invites + * @param guild_id Guild ID to get invites for + * @return invite_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +invite_map guild_get_invites_sync(snowflake guild_id); + + +invite invite_delete_sync(const std::string &invitecode); + + +invite invite_get_sync(const std::string &invitecode); + +/** + * @brief Send a message to a channel. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_create + * @see https://discord.com/developers/docs/resources/channel#create-message + * @param m Message to send + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_create_sync(const struct message &m); + +/** + * @brief Crosspost a message. The callback function is called when the message has been sent + * + * @see dpp::cluster::message_crosspost + * @see https://discord.com/developers/docs/resources/channel#crosspost-message + * @param message_id Message to crosspost + * @param channel_id Channel ID to crosspost from + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_crosspost_sync(snowflake message_id, snowflake channel_id); + +/** + * @brief Bulk delete messages from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @note If any message provided older than 2 weeks or any duplicate message ID, it will fail. + * + * @see dpp::cluster::message_delete_bulk + * @see https://discord.com/developers/docs/resources/channel#bulk-delete-messages + * @param message_ids List of message IDs to delete (at least 2 and at most 100 message IDs) + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_delete_bulk_sync(const std::vector &message_ids, snowflake channel_id); + +/** + * @brief Delete a message from a channel. The callback function is called when the message has been edited + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::message_delete + * @see https://discord.com/developers/docs/resources/channel#delete-message + * @param message_id Message ID to delete + * @param channel_id Channel to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_delete_sync(snowflake message_id, snowflake channel_id); + +/** + * @brief Edit a message on a channel. The callback function is called when the message has been edited + * + * @see dpp::cluster::message_edit + * @see https://discord.com/developers/docs/resources/channel#edit-message + * @param m Message to edit + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_edit_sync(const struct message &m); + +/** + * @brief Get a message + * + * @see dpp::cluster::message_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-message + * @param message_id Message ID + * @param channel_id Channel ID + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message message_get_sync(snowflake message_id, snowflake channel_id); + +/** + * @brief Pin a message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::message_pin + * @see https://discord.com/developers/docs/resources/channel#pin-message + * @param channel_id Channel id to pin message on + * @param message_id Message id to pin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_pin_sync(snowflake channel_id, snowflake message_id); + +/** + * @brief Get multiple messages. + * + * This function will attempt to fetch as many messages as possible using multiple API calls if needed. + * + * @see dpp::cluster::messages_get + * @see https://discord.com/developers/docs/resources/channel#get-channel-messages + * @param channel_id Channel ID to retrieve messages for + * @param around Messages should be retrieved around this ID if this is set to non-zero + * @param before Messages before this ID should be retrieved if this is set to non-zero + * @param after Messages after this ID should be retrieved if this is set to non-zero + * @param limit This number of messages maximum should be returned, up to a maximum of 100. + * @return message_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message_map messages_get_sync(snowflake channel_id, snowflake around, snowflake before, snowflake after, uint64_t limit); + +/** + * @brief Unpin a message + * @see dpp::cluster::message_unpin + * @see https://discord.com/developers/docs/resources/channel#unpin-message + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param channel_id Channel id to unpin message on + * @param message_id Message id to unpin message on + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation message_unpin_sync(snowflake channel_id, snowflake message_id); + +/** + * @brief Get a channel's pins + * @see dpp::cluster::channel_pins_get + * @see https://discord.com/developers/docs/resources/channel#get-pinned-messages + * @param channel_id Channel ID to get pins for + * @return message_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message_map channel_pins_get_sync(snowflake channel_id); + +/** + * @brief Create a role on a guild + * + * Create a new role for the guild. Requires the `MANAGE_ROLES` permission. Returns the new role object on success. + * Fires a `Guild Role Create` Gateway event. + * + * @see dpp::cluster::role_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to create (guild ID is encapsulated in the role object) + * @return role returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role role_create_sync(const class role &r); + +/** + * @brief Delete a role + * + * Requires the `MANAGE_ROLES` permission. Fires a `Guild Role Delete` Gateway event. + * + * @see dpp::cluster::role_delete + * @see https://discord.com/developers/docs/resources/guild#delete-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to delete the role on + * @param role_id Role ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation role_delete_sync(snowflake guild_id, snowflake role_id); + +/** + * @brief Edit a role on a guild + * + * Requires the `MANAGE_ROLES` permission. Returns the updated role on success. Fires a `Guild Role Update` Gateway event. + * + * @see dpp::cluster::role_edit + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param r Role to edit + * @return role returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role role_edit_sync(const class role &r); + +/** + * @brief Edit multiple role's position in a guild. Returns a list of all roles of the guild on success. + * + * Modify the positions of a set of role objects for the guild. Requires the `MANAGE_ROLES` permission. + * Fires multiple `Guild Role Update` Gateway events. + * + * @see dpp::cluster::roles_edit_position + * @see https://discord.com/developers/docs/resources/guild#modify-guild-role-positions + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @param guild_id Guild ID to change the roles position on + * @param roles Vector of roles to change the positions of + * @return role_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role_map roles_edit_position_sync(snowflake guild_id, const std::vector &roles); + +/** + * @brief Get a role for a guild + * + * @see dpp::cluster::roles_get + * @see https://discord.com/developers/docs/resources/guild#get-guild-roles + * @param guild_id Guild ID to get role for + * @return role_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +role_map roles_get_sync(snowflake guild_id); + +/** + * @brief Get user application role connection + * + * @see dpp::cluster::user_application_role_connection_get + * @see https://discord.com/developers/docs/resources/user#get-user-application-role-connection + * @param application_id The application ID + * @return application_role_connection returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +application_role_connection user_application_role_connection_get_sync(snowflake application_id); + +/** + * @brief Update user application role connection + * + * @see dpp::cluster::user_application_role_connection_update + * @see https://discord.com/developers/docs/resources/user#update-user-application-role-connection + * @param application_id The application ID + * @param connection The application role connection to update + * @return application_role_connection returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +application_role_connection user_application_role_connection_update_sync(snowflake application_id, const application_role_connection &connection); + +/** + * @brief Get all scheduled events for a guild + * @see dpp::cluster::guild_events_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#list-scheduled-events-for-guild + * @param guild_id Guild to get events for + * @return scheduled_event_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event_map guild_events_get_sync(snowflake guild_id); + +/** + * @brief Create a scheduled event on a guild + * + * @see dpp::cluster::guild_event_create + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#create-guild-scheduled-event + * @param event Event to create (guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event guild_event_create_sync(const scheduled_event& event); + +/** + * @brief Delete a scheduled event from a guild + * + * @see dpp::cluster::guild_event_delete + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#delete-guild-scheduled-event + * @param event_id Event ID to delete + * @param guild_id Guild ID of event to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_event_delete_sync(snowflake event_id, snowflake guild_id); + +/** + * @brief Edit/modify a scheduled event on a guild + * + * @see dpp::cluster::guild_event_edit + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#modify-guild-scheduled-event + * @param event Event to create (event ID and guild ID must be populated) + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event guild_event_edit_sync(const scheduled_event& event); + +/** + * @brief Get a scheduled event for a guild + * + * @see dpp::cluster::guild_event_get + * @see https://discord.com/developers/docs/resources/guild-scheduled-event#get-guild-scheduled-event + * @param guild_id Guild to get event for + * @param event_id Event ID to get + * @return scheduled_event returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +scheduled_event guild_event_get_sync(snowflake guild_id, snowflake event_id); + + +stage_instance stage_instance_create_sync(const stage_instance& si); + +/** + * @brief Get the stage instance associated with the channel id, if it exists. + * @see dpp::cluster::stage_instance_get + * @see https://discord.com/developers/docs/resources/stage-instance#get-stage-instance + * @param channel_id ID of the associated channel + * @return stage_instance returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +stage_instance stage_instance_get_sync(const snowflake channel_id); + + +stage_instance stage_instance_edit_sync(const stage_instance& si); + +/** + * @brief Delete a stage instance. + * @see dpp::cluster::stage_instance_delete + * @see https://discord.com/developers/docs/resources/stage-instance#delete-stage-instance + * @param channel_id ID of the associated channel + * @return confirmation returned object on completion + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation stage_instance_delete_sync(const snowflake channel_id); + +/** + * @brief Create a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_create + * @see https://discord.com/developers/docs/resources/sticker#create-guild-sticker + * @param s Sticker to create. Must have its guild ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker guild_sticker_create_sync(sticker &s); + +/** + * @brief Delete a sticker from a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_delete + * @see https://discord.com/developers/docs/resources/sticker#delete-guild-sticker + * @param sticker_id sticker ID to delete + * @param guild_id guild ID to delete from + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_sticker_delete_sync(snowflake sticker_id, snowflake guild_id); + +/** + * @brief Get a guild sticker + * @see dpp::cluster::guild_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-sticker + * @param id Id of sticker to get. + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker guild_sticker_get_sync(snowflake id, snowflake guild_id); + +/** + * @brief Modify a sticker in a guild + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::guild_sticker_modify + * @see https://discord.com/developers/docs/resources/sticker#modify-guild-sticker + * @param s Sticker to modify. Must have its guild ID and sticker ID set. + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker guild_sticker_modify_sync(sticker &s); + +/** + * @brief Get all guild stickers + * @see dpp::cluster::guild_stickers_get + * @see https://discord.com/developers/docs/resources/sticker#get-guild-stickers + * @param guild_id Guild ID of the guild where the sticker is + * @return sticker_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker_map guild_stickers_get_sync(snowflake guild_id); + +/** + * @brief Get a nitro sticker + * @see dpp::cluster::nitro_sticker_get + * @see https://discord.com/developers/docs/resources/sticker#get-sticker + * @param id Id of sticker to get. + * @return sticker returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker nitro_sticker_get_sync(snowflake id); + +/** + * @brief Get sticker packs + * @see dpp::cluster::sticker_packs_get + * @see https://discord.com/developers/docs/resources/sticker#list-nitro-sticker-packs + * @return sticker_pack_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +sticker_pack_map sticker_packs_get_sync(); + +/** + * @brief Create a new guild based on a template. + * @note This endpoint can be used only by bots in less than 10 guilds. + * @see dpp::cluster::guild_create_from_template + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-from-guild-template + * @param code Template code to create guild from + * @param name Guild name to create + * @return guild returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild guild_create_from_template_sync(const std::string &code, const std::string &name); + +/** + * @brief Creates a template for the guild + * + * @see dpp::cluster::guild_template_create + * @see https://discord.com/developers/docs/resources/guild-template#create-guild-template + * @param guild_id Guild to create template from + * @param name Template name to create + * @param description Description of template to create + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate guild_template_create_sync(snowflake guild_id, const std::string &name, const std::string &description); + +/** + * @brief Deletes the template + * + * @see dpp::cluster::guild_template_delete + * @see https://discord.com/developers/docs/resources/guild-template#delete-guild-template + * @param guild_id Guild ID of template to delete + * @param code Template code to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation guild_template_delete_sync(snowflake guild_id, const std::string &code); + +/** + * @brief Modifies the template's metadata. + * + * @see dpp::cluster::guild_template_modify + * @see https://discord.com/developers/docs/resources/guild-template#modify-guild-template + * @param guild_id Guild ID of template to modify + * @param code Template code to modify + * @param name New name of template + * @param description New description of template + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate guild_template_modify_sync(snowflake guild_id, const std::string &code, const std::string &name, const std::string &description); + +/** + * @brief Get guild templates + * + * @see dpp::cluster::guild_templates_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-templates + * @param guild_id Guild ID to get templates for + * @return dtemplate_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate_map guild_templates_get_sync(snowflake guild_id); + +/** + * @brief Syncs the template to the guild's current state. + * + * @see dpp::cluster::guild_template_sync + * @see https://discord.com/developers/docs/resources/guild-template#sync-guild-template + * @param guild_id Guild to synchronise template for + * @param code Code of template to synchronise + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate guild_template_sync_sync(snowflake guild_id, const std::string &code); + +/** + * @brief Get a template + * @see dpp::cluster::template_get + * @see https://discord.com/developers/docs/resources/guild-template#get-guild-template + * @param code Template code + * @return dtemplate returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +dtemplate template_get_sync(const std::string &code); + +/** + * @brief Join a thread + * @see dpp::cluster::current_user_join_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to join + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_join_thread_sync(snowflake thread_id); + +/** + * @brief Leave a thread + * @see dpp::cluster::current_user_leave_thread + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_leave_thread_sync(snowflake thread_id); + +/** + * @brief Get active threads in a guild (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_active + * @see https://discord.com/developers/docs/topics/threads + * @param guild_id Guild to get active threads for + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_active_sync(snowflake guild_id); + +/** + * @brief Get private archived threads in a channel which current user has joined (Sorted by ID in descending order) + * @see dpp::cluster::threads_get_joined_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_id Get threads before this id + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_joined_private_archived_sync(snowflake channel_id, snowflake before_id, uint16_t limit); + +/** + * @brief Get private archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_private_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_private_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); + +/** + * @brief Get public archived threads in a channel (Sorted by archive_timestamp in descending order) + * @see dpp::cluster::threads_get_public_archived + * @see https://discord.com/developers/docs/topics/threads + * @param channel_id Channel to get public archived threads for + * @param before_timestamp Get threads before this timestamp + * @param limit Number of threads to get + * @return thread_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_map threads_get_public_archived_sync(snowflake channel_id, time_t before_timestamp, uint16_t limit); + +/** + * @brief Get a thread member + * @see dpp::cluster::thread_member_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get member for + * @param user_id ID of the user to get + * @return thread_member returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_member thread_member_get_sync(const snowflake thread_id, const snowflake user_id); + +/** + * @brief Get members of a thread + * @see dpp::cluster::thread_members_get + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread to get members for + * @return thread_member_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread_member_map thread_members_get_sync(snowflake thread_id); + +/** + * @brief Create a thread in forum channel + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::thread_create_in_forum + * @see https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel + * @param thread_name Name of the forum thread + * @param channel_id Forum channel in which thread to create + * @param msg The message to start the thread with + * @param auto_archive_duration Duration to automatically archive the thread after recent activity + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @param applied_tags List of IDs of forum tags (dpp::forum_tag) to apply to this thread + * @return thread returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread thread_create_in_forum_sync(const std::string& thread_name, snowflake channel_id, const message& msg, auto_archive_duration_t auto_archive_duration, uint16_t rate_limit_per_user, std::vector applied_tags = {}); + +/** + * @brief Create a thread + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * + * @see dpp::cluster::thread_create + * @see https://discord.com/developers/docs/resources/guild#create-guild-channel + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param thread_type Type of thread - CHANNEL_PUBLIC_THREAD, CHANNEL_ANNOUNCEMENT_THREAD, CHANNEL_PRIVATE_THREAD + * @param invitable whether non-moderators can add other non-moderators to a thread; only available when creating a private thread + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread thread_create_sync(const std::string& thread_name, snowflake channel_id, uint16_t auto_archive_duration, channel_type thread_type, bool invitable, uint16_t rate_limit_per_user); + +/** + * @brief Create a thread with a message (Discord: ID of a thread is same as message ID) + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::thread_create_with_message + * @see https://discord.com/developers/docs/topics/threads + * @param thread_name Name of the thread + * @param channel_id Channel in which thread to create + * @param message_id message to start thread with + * @param auto_archive_duration Duration after which thread auto-archives. Can be set to - 60, 1440 (for boosted guilds can also be: 4320, 10080) + * @param rate_limit_per_user amount of seconds a user has to wait before sending another message (0-21600); bots, as well as users with the permission manage_messages, manage_thread, or manage_channel, are unaffected + * @return thread returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +thread thread_create_with_message_sync(const std::string& thread_name, snowflake channel_id, snowflake message_id, uint16_t auto_archive_duration, uint16_t rate_limit_per_user); + +/** + * @brief Add a member to a thread + * @see dpp::cluster::thread_member_add + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to add to + * @param user_id Member ID to add + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation thread_member_add_sync(snowflake thread_id, snowflake user_id); + +/** + * @brief Remove a member from a thread + * @see dpp::cluster::thread_member_remove + * @see https://discord.com/developers/docs/topics/threads + * @param thread_id Thread ID to remove from + * @param user_id Member ID to remove + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation thread_member_remove_sync(snowflake thread_id, snowflake user_id); + +/** + * @brief Edit current (bot) user + * + * Modifies the current member in a guild. Returns the updated guild_member object on success. + * Fires a `Guild Member Update` Gateway event. + * @see dpp::cluster::current_user_edit + * @see https://discord.com/developers/docs/resources/user#modify-current-user + * @param nickname Nickname to set + * @param image_blob Avatar data to upload (NOTE: Very heavily rate limited!) + * @param type Type of image for avatar + * @return user returned object on completion + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +user current_user_edit_sync(const std::string &nickname, const std::string& image_blob = "", const image_type type = i_png); + +/** + * @brief Get current (bot) application + * + * @see dpp::cluster::current_application_get + * @see https://discord.com/developers/docs/topics/oauth2#get-current-bot-application-information + * @return application returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +application current_application_get_sync(); + +/** + * @brief Get current (bot) user + * + * @see dpp::cluster::current_user_get + * @see https://discord.com/developers/docs/resources/user#get-current-user + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +user_identified current_user_get_sync(); + +/** + * @brief Set the bot's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - current user must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission to unsuppress yourself. You can always suppress yourself. + * - You must have the `REQUEST_TO_SPEAK` permission to request to speak. You can always clear your own request to speak. + * - You are able to set `request_to_speak_timestamp` to any present or future time. + * + * @see dpp::cluster::current_user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-current-user-voice-state + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * @param request_to_speak_timestamp The time at which we requested to speak, or 0 to clear the request. The time set here must be the current time or in the future. + * @throw std::logic_exception You attempted to set a request_to_speak_timestamp in the past which is not the value of 0. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_set_voice_state_sync(snowflake guild_id, snowflake channel_id, bool suppress = false, time_t request_to_speak_timestamp = 0); + +/** + * @brief Set a user's voice state on a stage channel + * + * **Caveats** + * + * There are currently several caveats for this endpoint: + * + * - `channel_id` must currently point to a stage channel. + * - User must already have joined `channel_id`. + * - You must have the `MUTE_MEMBERS` permission. (Since suppression is the only thing that is available currently) + * - When unsuppressed, non-bot users will have their `request_to_speak_timestamp` set to the current time. Bot users will not. + * - When suppressed, the user will have their `request_to_speak_timestamp` removed. + * + * @see dpp::cluster::user_set_voice_state + * @see https://discord.com/developers/docs/resources/guild#modify-user-voice-state + * @param user_id The user to set the voice state of + * @param guild_id Guild to set voice state on + * @param channel_id Stage channel to set voice state on + * @return confirmation returned object on completion + * @param suppress True if the user's audio should be suppressed, false if it should not + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation user_set_voice_state_sync(snowflake user_id, snowflake guild_id, snowflake channel_id, bool suppress = false); + +/** + * @brief Get current user's connections (linked accounts, e.g. steam, xbox). + * This call requires the oauth2 `connections` scope and cannot be executed + * against a bot token. + * @see dpp::cluster::current_user_connections_get + * @see https://discord.com/developers/docs/resources/user#get-user-connections + * @return connection_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +connection_map current_user_connections_get_sync(); + +/** + * @brief Get current (bot) user guilds + * @see dpp::cluster::current_user_get_guilds + * @see https://discord.com/developers/docs/resources/user#get-current-user-guilds + * @return guild_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +guild_map current_user_get_guilds_sync(); + +/** + * @brief Leave a guild + * @see dpp::cluster::current_user_leave_guild + * @see https://discord.com/developers/docs/resources/user#leave-guild + * @param guild_id Guild ID to leave + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation current_user_leave_guild_sync(snowflake guild_id); + +/** + * @brief Get a user by id + * + * @see dpp::cluster::user_get + * @see https://discord.com/developers/docs/resources/user#get-user + * @param user_id User ID to retrieve + * @return user_identified returned object on completion + * @note The user_identified object is a subclass of dpp::user which contains further details if you have the oauth2 identify or email scopes. + * If you do not have these scopes, these fields are empty. You can safely convert a user_identified to user with `dynamic_cast`. + * @note unless you want something special from `dpp::user_identified` or you've turned off caching, you have no need to call this. + * Call `dpp::find_user` instead that looks up the user in the cache rather than a REST call. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +user_identified user_get_sync(snowflake user_id); + +/** + * @brief Get all voice regions + * @see dpp::cluster::get_voice_regions + * @see https://discord.com/developers/docs/resources/voice#list-voice-regions + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +voiceregion_map get_voice_regions_sync(); + +/** + * @brief Get guild voice regions. + * + * Voice regions per guild are somewhat deprecated in preference of per-channel voice regions. + * Returns a list of voice region objects for the guild. Unlike the similar /voice route, this returns VIP servers when + * the guild is VIP-enabled. + * + * @see dpp::cluster::guild_get_voice_regions + * @see https://discord.com/developers/docs/resources/guild#get-guild-voice-regions + * @param guild_id Guild ID to get voice regions for + * @return voiceregion_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +voiceregion_map guild_get_voice_regions_sync(snowflake guild_id); + +/** + * @brief Create a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::create_webhook + * @see https://discord.com/developers/docs/resources/webhook#create-webhook + * @param w Webhook to create + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook create_webhook_sync(const class webhook &w); + +/** + * @brief Delete a webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::delete_webhook + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook + * @param webhook_id Webhook ID to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation delete_webhook_sync(snowflake webhook_id); + +/** + * @brief Delete webhook message + * + * @see dpp::cluster::delete_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-message + * @param wh Webhook to delete message for + * @param message_id Message ID to delete + * @param thread_id ID of the thread the message is in + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation delete_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); + +/** + * @brief Delete webhook with token + * @see dpp::cluster::delete_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#delete-webhook-with-token + * @param webhook_id Webhook ID to delete + * @param token Token of webhook to delete + * @return confirmation returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +confirmation delete_webhook_with_token_sync(snowflake webhook_id, const std::string &token); + +/** + * @brief Edit webhook + * @note This method supports audit log reasons set by the cluster::set_audit_reason() method. + * @see dpp::cluster::edit_webhook + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook + * @param wh Webhook to edit + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook edit_webhook_sync(const class webhook& wh); + +/** + * @brief Edit webhook message + * + * When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on + * the new content. The allowed_mentions field of the edit request controls how this happens. If there is no explicit + * allowed_mentions in the edit request, the content will be parsed with default allowances, that is, without regard to + * whether or not an allowed_mentions was present in the request that originally created the message. + * + * @see dpp::cluster::edit_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#edit-webhook-message + * @note the attachments array must contain all attachments that should be present after edit, including retained and new attachments provided in the request body. + * @param wh Webhook to edit message for + * @param m New message + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message edit_webhook_message_sync(const class webhook &wh, const struct message &m, snowflake thread_id = 0); + +/** + * @brief Edit webhook with token (token is encapsulated in the webhook object) + * @see dpp::cluster::edit_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#modify-webhook-with-token + * @param wh Webhook to edit (should include token) + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook edit_webhook_with_token_sync(const class webhook& wh); + +/** + * @brief Execute webhook + * + * @see dpp::cluster::execute_webhook + * @see https://discord.com/developers/docs/resources/webhook#execute-webhook + * @param wh Webhook to execute + * @param m Message to send + * @param wait waits for server confirmation of message send before response, and returns the created message body + * @param thread_id Send a message to the specified thread within a webhook's channel. The thread will automatically be unarchived + * @param thread_name Name of thread to create (requires the webhook channel to be a forum channel) + * @return message returned object on completion + * @note If the webhook channel is a forum channel, you must provide either `thread_id` or `thread_name`. If `thread_id` is provided, the message will send in that thread. If `thread_name` is provided, a thread with that name will be created in the forum channel. + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message execute_webhook_sync(const class webhook &wh, const struct message &m, bool wait = false, snowflake thread_id = 0, const std::string& thread_name = ""); + +/** + * @brief Get channel webhooks + * @see dpp::cluster::get_channel_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param channel_id Channel ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook_map get_channel_webhooks_sync(snowflake channel_id); + +/** + * @brief Get guild webhooks + * @see dpp::cluster::get_guild_webhooks + * @see https://discord.com/developers/docs/resources/webhook#get-guild-webhooks + * @param guild_id Guild ID to get webhooks for + * @return webhook_map returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook_map get_guild_webhooks_sync(snowflake guild_id); + +/** + * @brief Get webhook + * @see dpp::cluster::get_webhook + * @see https://discord.com/developers/docs/resources/webhook#get-webhook + * @param webhook_id Webhook ID to get + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook get_webhook_sync(snowflake webhook_id); + +/** + * @brief Get webhook message + * + * @see dpp::cluster::get_webhook_message + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-message + * @param wh Webhook to get the original message for + * @param message_id The message ID + * @param thread_id ID of the thread the message is in + * @return message returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +message get_webhook_message_sync(const class webhook &wh, snowflake message_id, snowflake thread_id = 0); + +/** + * @brief Get webhook using token + * @see dpp::cluster::get_webhook_with_token + * @see https://discord.com/developers/docs/resources/webhook#get-webhook-with-token + * @param webhook_id Webhook ID to retrieve + * @param token Token of webhook + * @return webhook returned object on completion + * \memberof dpp::cluster + * @throw dpp::rest_exception upon failure to execute REST function + * @warning This function is a blocking (synchronous) call and should only be used from within a separate thread. + * Avoid direct use of this function inside an event handler. + */ +webhook get_webhook_with_token_sync(snowflake webhook_id, const std::string &token); + + +/* End of auto-generated definitions */ diff --git a/3rdParty/dpp/collector.h b/3rdParty/dpp/collector.h index 72ddd89a4e..a27d0a2d7a 100644 --- a/3rdParty/dpp/collector.h +++ b/3rdParty/dpp/collector.h @@ -1,435 +1,435 @@ -/* - * Discord erlpack - tidied up for D++, Craig Edwards 2021. - * - * MessagePack system dependencies modified for erlpack. - * - * Copyright (C) 2008-2010 FURUHASHI Sadayuki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Collects objects from events during a specified time period. - * - * This template must be specialised. There are premade specialisations which you can use - * such as dpp::reaction_collector and dpp::message_collector. For these specialised instances - * all you need to do is derive a simple class from them which implements collector::completed(). - * - * A collector will run for the specified number of seconds, attaching itself to the - * given event. During this time any events pass through the collector and collector::filter(). - * This function can return a pointer to an object to allow a copy of that object to be stored - * to a vector, or it can return nullptr to do nothing with that object. For example a collector - * attached to on_message_create would receive an event with the type message_create_t, and from - * this may decide to extract the message_create_t::msg structure, returning a pointer to it, or - * instead may choose to return a nullptr. - * - * When either the predetermined timeout is reached, or the collector::cancel() method is called, - * or the collector is destroyed, the collector::completed() method is called, which will be - * passed a list of collected objects in the order they were collected. - * - * @tparam T parameter type of the event this collector will monitor - * @tparam C object type this collector will store - */ -template class collector -{ -protected: - /// Owning cluster - class cluster* owner; -private: - /// Timed listener - timed_listener, std::function>* tl; - /// stored list - std::vector stored; - /// Trigger flag - bool triggered; -public: - /** - * @brief Construct a new collector object. - * - * The timer for the collector begins immediately on construction of the object. - * - * @param cl Pointer to cluster which manages this collector - * @param duration Duration in seconds to run the collector for - * @param event Event to attach to, e.g. cluster::on_message_create - */ - collector(class cluster* cl, uint64_t duration, event_router_t & event) : owner(cl), triggered(false) { - std::function f = [this](const T& event) { - const C* v = filter(event); - if (v) { - stored.push_back(*v); - } - }; - tl = new dpp::timed_listener, std::function>(cl, duration, event, f, [this](dpp::timer timer_handle) { - if (!triggered) { - triggered = true; - completed(stored); - } - }); - } - - /** - * @brief You must implement this function to receive the completed list of - * captured objects. - * @param list The list of captured objects in captured order - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Filter the list of elements. - * - * Every time an event is fired on the collector, this method wil be called - * to determine if we should add an object to the list or not. This function - * can then process the `element` value, extract the parts which are to be - * saved to a list (e.g. a dpp::message out of a dpp::message_create_t) and - * return it as the return value. Returning a value of nullptr causes no - * object to be stored. - * - * Here is an example of how to filter messages which have specific text in them. - * This should be used with the specialised type dpp::message_collector - * - * ```cpp - * virtual const dpp::message* filter(const dpp::message_create_t& m) { - * if (m.msg.content.find("something i want") != std::string::npos) { - * return &m.msg; - * } else { - * return nullptr; - * } - * } - * ``` - * - * @param element The event data to filter - * @return const C* Returned object or nullptr - */ - virtual const C* filter(const T& element) = 0; - - /** - * @brief Immediately cancels the collector. - * - * Use this if you have met the conditions for which you are collecting objects - * early, e.g. you were watching for a message containing 'yes' or 'no' and have - * received it before the time is up. - * - * @note Causes calling of the completed() method if it has not yet been called. - */ - virtual void cancel() { - delete tl; - tl = nullptr; - } - - /** - * @brief Destroy the collector object. - * @note Causes calling of the completed() method if it has not yet been called. - */ - virtual ~collector() { - delete tl; - } -}; - -/** - * @brief Represents a reaction. - * Can be filled for use in a collector - */ -class collected_reaction : public managed { -public: - /// Reacting user - user react_user; - /// Reacting guild - guild* react_guild{}; - /// Reacting guild member - guild_member react_member; - /// Reacting channel - channel* react_channel{}; - /// Reacted emoji - emoji react_emoji; -}; - -/** - * @brief Template type for base class of channel collector - */ -typedef dpp::collector channel_collector_t; - -/** - * @brief Template type for base class of thread collector - */ -typedef dpp::collector thread_collector_t; - -/** - * @brief Template type for base class of role collector - */ -typedef dpp::collector role_collector_t; - -/** - * @brief Template type for base class of scheduled event collector - */ -typedef dpp::collector scheduled_event_collector_t; - -/** - * @brief Template type for base class of message collector - */ -typedef dpp::collector message_collector_t; - -/** - * @brief Template type for base class of message reaction collector - */ -typedef dpp::collector reaction_collector_t; - -/** - * @brief Message collector. - * Collects messages during a set timeframe and returns them in a list via the completed() method. - */ -class message_collector : public message_collector_t { -public: - /** - * @brief Construct a new message collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - message_collector(cluster* cl, uint64_t duration) : message_collector_t::collector(cl, duration, cl->on_message_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::message* filter(const dpp::message_create_t& element) { return &element.msg; } - - /** - * @brief Destroy the message collector object - */ - virtual ~message_collector() = default; -}; - -/** - * @brief Reaction collector. - * Collects message reactions during a set timeframe and returns them in a list via the completed() method. - */ -class reaction_collector : public reaction_collector_t { - snowflake message_id; - collected_reaction react; -public: - /** - * @brief Construct a new reaction collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - * @param msg_id Optional message ID. If specified, only collects reactions for the given message - */ - reaction_collector(cluster* cl, uint64_t duration, snowflake msg_id = 0) : reaction_collector_t::collector(cl, duration, cl->on_message_reaction_add), message_id(msg_id) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::collected_reaction* filter(const dpp::message_reaction_add_t& element) { - /* Capture reactions for given message ID only */ - if (message_id.empty() || element.message_id == message_id) { - react.id = element.message_id; - react.react_user = element.reacting_user; - react.react_guild = element.reacting_guild; - react.react_member = element.reacting_member; - react.react_channel = element.reacting_channel; - react.react_emoji = element.reacting_emoji; - return &react; - } else { - return nullptr; - } - } - - /** - * @brief Destroy the reaction collector object - */ - virtual ~reaction_collector() = default; -}; - -/** - * @brief Channel collector. - * Collects channels during a set timeframe and returns them in a list via the completed() method. - */ -class channel_collector : public channel_collector_t { -public: - /** - * @brief Construct a new channel collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - channel_collector(cluster* cl, uint64_t duration) : channel_collector_t::collector(cl, duration, cl->on_channel_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::channel* filter(const dpp::channel_create_t& element) { return element.created; } - - /** - * @brief Destroy the channel collector object - */ - virtual ~channel_collector() = default; -}; - -/** - * @brief Thread collector. - * Collects threads during a set timeframe and returns them in a list via the completed() method. - */ -class thread_collector : public thread_collector_t { -public: - /** - * @brief Construct a new thread collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - thread_collector(cluster* cl, uint64_t duration) : thread_collector_t::collector(cl, duration, cl->on_thread_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::thread* filter(const dpp::thread_create_t& element) { return &element.created; } - - /** - * @brief Destroy the thread collector object - */ - virtual ~thread_collector() = default; -}; - -/** - * @brief Role collector. - * Collects guild roles during a set timeframe and returns them in a list via the completed() method. - */ -class role_collector : public role_collector_t { -public: - /** - * @brief Construct a new role collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - role_collector(cluster* cl, uint64_t duration) : role_collector_t::collector(cl, duration, cl->on_guild_role_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::role* filter(const dpp::guild_role_create_t& element) { return element.created; } - - /** - * @brief Destroy the role collector object - */ - virtual ~role_collector() = default; -}; - -/** - * @brief Scheduled event collector. - * Collects messages during a set timeframe and returns them in a list via the completed() method. - */ -class scheduled_event_collector : public scheduled_event_collector_t { -public: - /** - * @brief Construct a new scheduled event collector object - * - * @param cl cluster to associate the collector with - * @param duration Duration of time to run the collector for in seconds - */ - scheduled_event_collector(cluster* cl, uint64_t duration) : scheduled_event_collector_t::collector(cl, duration, cl->on_guild_scheduled_event_create) { } - - /** - * @brief Return the completed collection - * - * @param list items collected during the timeframe specified - */ - virtual void completed(const std::vector& list) = 0; - - /** - * @brief Select and filter the items which are to appear in the list - * This is called every time a new event is fired, to filter the event and determine which - * of the items is sent to the list. Returning nullptr excludes the item from the list. - * - * @param element element to filter - * @return Returned item to add to the list, or nullptr to skip adding this element - */ - virtual const dpp::scheduled_event* filter(const dpp::guild_scheduled_event_create_t& element) { return &element.created; } - - /** - * @brief Destroy the scheduled event collector object - */ - virtual ~scheduled_event_collector() = default; -}; - +/* + * Discord erlpack - tidied up for D++, Craig Edwards 2021. + * + * MessagePack system dependencies modified for erlpack. + * + * Copyright (C) 2008-2010 FURUHASHI Sadayuki + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Collects objects from events during a specified time period. + * + * This template must be specialised. There are premade specialisations which you can use + * such as dpp::reaction_collector and dpp::message_collector. For these specialised instances + * all you need to do is derive a simple class from them which implements collector::completed(). + * + * A collector will run for the specified number of seconds, attaching itself to the + * given event. During this time any events pass through the collector and collector::filter(). + * This function can return a pointer to an object to allow a copy of that object to be stored + * to a vector, or it can return nullptr to do nothing with that object. For example a collector + * attached to on_message_create would receive an event with the type message_create_t, and from + * this may decide to extract the message_create_t::msg structure, returning a pointer to it, or + * instead may choose to return a nullptr. + * + * When either the predetermined timeout is reached, or the collector::cancel() method is called, + * or the collector is destroyed, the collector::completed() method is called, which will be + * passed a list of collected objects in the order they were collected. + * + * @tparam T parameter type of the event this collector will monitor + * @tparam C object type this collector will store + */ +template class collector +{ +protected: + /// Owning cluster + class cluster* owner; +private: + /// Timed listener + timed_listener, std::function>* tl; + /// stored list + std::vector stored; + /// Trigger flag + bool triggered; +public: + /** + * @brief Construct a new collector object. + * + * The timer for the collector begins immediately on construction of the object. + * + * @param cl Pointer to cluster which manages this collector + * @param duration Duration in seconds to run the collector for + * @param event Event to attach to, e.g. cluster::on_message_create + */ + collector(class cluster* cl, uint64_t duration, event_router_t & event) : owner(cl), triggered(false) { + std::function f = [this](const T& event) { + const C* v = filter(event); + if (v) { + stored.push_back(*v); + } + }; + tl = new dpp::timed_listener, std::function>(cl, duration, event, f, [this](dpp::timer timer_handle) { + if (!triggered) { + triggered = true; + completed(stored); + } + }); + } + + /** + * @brief You must implement this function to receive the completed list of + * captured objects. + * @param list The list of captured objects in captured order + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Filter the list of elements. + * + * Every time an event is fired on the collector, this method wil be called + * to determine if we should add an object to the list or not. This function + * can then process the `element` value, extract the parts which are to be + * saved to a list (e.g. a dpp::message out of a dpp::message_create_t) and + * return it as the return value. Returning a value of nullptr causes no + * object to be stored. + * + * Here is an example of how to filter messages which have specific text in them. + * This should be used with the specialised type dpp::message_collector + * + * ```cpp + * virtual const dpp::message* filter(const dpp::message_create_t& m) { + * if (m.msg.content.find("something i want") != std::string::npos) { + * return &m.msg; + * } else { + * return nullptr; + * } + * } + * ``` + * + * @param element The event data to filter + * @return const C* Returned object or nullptr + */ + virtual const C* filter(const T& element) = 0; + + /** + * @brief Immediately cancels the collector. + * + * Use this if you have met the conditions for which you are collecting objects + * early, e.g. you were watching for a message containing 'yes' or 'no' and have + * received it before the time is up. + * + * @note Causes calling of the completed() method if it has not yet been called. + */ + virtual void cancel() { + delete tl; + tl = nullptr; + } + + /** + * @brief Destroy the collector object. + * @note Causes calling of the completed() method if it has not yet been called. + */ + virtual ~collector() { + delete tl; + } +}; + +/** + * @brief Represents a reaction. + * Can be filled for use in a collector + */ +class collected_reaction : public managed { +public: + /// Reacting user + user react_user; + /// Reacting guild + guild* react_guild{}; + /// Reacting guild member + guild_member react_member; + /// Reacting channel + channel* react_channel{}; + /// Reacted emoji + emoji react_emoji; +}; + +/** + * @brief Template type for base class of channel collector + */ +typedef dpp::collector channel_collector_t; + +/** + * @brief Template type for base class of thread collector + */ +typedef dpp::collector thread_collector_t; + +/** + * @brief Template type for base class of role collector + */ +typedef dpp::collector role_collector_t; + +/** + * @brief Template type for base class of scheduled event collector + */ +typedef dpp::collector scheduled_event_collector_t; + +/** + * @brief Template type for base class of message collector + */ +typedef dpp::collector message_collector_t; + +/** + * @brief Template type for base class of message reaction collector + */ +typedef dpp::collector reaction_collector_t; + +/** + * @brief Message collector. + * Collects messages during a set timeframe and returns them in a list via the completed() method. + */ +class message_collector : public message_collector_t { +public: + /** + * @brief Construct a new message collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + message_collector(cluster* cl, uint64_t duration) : message_collector_t::collector(cl, duration, cl->on_message_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::message* filter(const dpp::message_create_t& element) { return &element.msg; } + + /** + * @brief Destroy the message collector object + */ + virtual ~message_collector() = default; +}; + +/** + * @brief Reaction collector. + * Collects message reactions during a set timeframe and returns them in a list via the completed() method. + */ +class reaction_collector : public reaction_collector_t { + snowflake message_id; + collected_reaction react; +public: + /** + * @brief Construct a new reaction collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + * @param msg_id Optional message ID. If specified, only collects reactions for the given message + */ + reaction_collector(cluster* cl, uint64_t duration, snowflake msg_id = 0) : reaction_collector_t::collector(cl, duration, cl->on_message_reaction_add), message_id(msg_id) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::collected_reaction* filter(const dpp::message_reaction_add_t& element) { + /* Capture reactions for given message ID only */ + if (message_id.empty() || element.message_id == message_id) { + react.id = element.message_id; + react.react_user = element.reacting_user; + react.react_guild = element.reacting_guild; + react.react_member = element.reacting_member; + react.react_channel = element.reacting_channel; + react.react_emoji = element.reacting_emoji; + return &react; + } else { + return nullptr; + } + } + + /** + * @brief Destroy the reaction collector object + */ + virtual ~reaction_collector() = default; +}; + +/** + * @brief Channel collector. + * Collects channels during a set timeframe and returns them in a list via the completed() method. + */ +class channel_collector : public channel_collector_t { +public: + /** + * @brief Construct a new channel collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + channel_collector(cluster* cl, uint64_t duration) : channel_collector_t::collector(cl, duration, cl->on_channel_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::channel* filter(const dpp::channel_create_t& element) { return element.created; } + + /** + * @brief Destroy the channel collector object + */ + virtual ~channel_collector() = default; +}; + +/** + * @brief Thread collector. + * Collects threads during a set timeframe and returns them in a list via the completed() method. + */ +class thread_collector : public thread_collector_t { +public: + /** + * @brief Construct a new thread collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + thread_collector(cluster* cl, uint64_t duration) : thread_collector_t::collector(cl, duration, cl->on_thread_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::thread* filter(const dpp::thread_create_t& element) { return &element.created; } + + /** + * @brief Destroy the thread collector object + */ + virtual ~thread_collector() = default; +}; + +/** + * @brief Role collector. + * Collects guild roles during a set timeframe and returns them in a list via the completed() method. + */ +class role_collector : public role_collector_t { +public: + /** + * @brief Construct a new role collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + role_collector(cluster* cl, uint64_t duration) : role_collector_t::collector(cl, duration, cl->on_guild_role_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::role* filter(const dpp::guild_role_create_t& element) { return element.created; } + + /** + * @brief Destroy the role collector object + */ + virtual ~role_collector() = default; +}; + +/** + * @brief Scheduled event collector. + * Collects messages during a set timeframe and returns them in a list via the completed() method. + */ +class scheduled_event_collector : public scheduled_event_collector_t { +public: + /** + * @brief Construct a new scheduled event collector object + * + * @param cl cluster to associate the collector with + * @param duration Duration of time to run the collector for in seconds + */ + scheduled_event_collector(cluster* cl, uint64_t duration) : scheduled_event_collector_t::collector(cl, duration, cl->on_guild_scheduled_event_create) { } + + /** + * @brief Return the completed collection + * + * @param list items collected during the timeframe specified + */ + virtual void completed(const std::vector& list) = 0; + + /** + * @brief Select and filter the items which are to appear in the list + * This is called every time a new event is fired, to filter the event and determine which + * of the items is sent to the list. Returning nullptr excludes the item from the list. + * + * @param element element to filter + * @return Returned item to add to the list, or nullptr to skip adding this element + */ + virtual const dpp::scheduled_event* filter(const dpp::guild_scheduled_event_create_t& element) { return &element.created; } + + /** + * @brief Destroy the scheduled event collector object + */ + virtual ~scheduled_event_collector() = default; +}; + }; \ No newline at end of file diff --git a/3rdParty/dpp/colors.h b/3rdParty/dpp/colors.h index a57e08a273..664a11cd33 100644 --- a/3rdParty/dpp/colors.h +++ b/3rdParty/dpp/colors.h @@ -1,80 +1,80 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include - - /** - * @brief The main namespace for D++ functions. classes and types - */ -namespace dpp { - /** - * @brief predefined color constants - */ - namespace colors { - const uint32_t - white = 0xFFFFFF, - discord_white = 0xFFFFFE, - light_gray = 0xC0C0C0, - gray = 0x808080, - dark_gray = 0x404040, - black = 0x000000, - discord_black = 0x000001, - red = 0xFF0000, - pink = 0xFFAFAF, - orange = 0xFFC800, - yellow = 0xFFFF00, - green = 0x00FF00, - magenta = 0xFF00FF, - cyan = 0x00FFFF, - blue = 0x0000FF, - light_sea_green = 0x1ABC9C, - medium_sea_green = 0x2ECC71, - summer_sky = 0x3498DB, - deep_lilac = 0x9B59B6, - ruby = 0xE91E63, - moon_yellow = 0xF1C40F, - tahiti_gold = 0xE67E22, - cinnabar = 0xE74C3C, - submarine = 0x95A5A6, - blue_aquamarine = 0x607D8B, - deep_sea = 0x11806A, - sea_green = 0x1F8B4C, - endeavour = 0x206694, - vivid_violet = 0x71368A, - jazzberry_jam = 0xAD1457, - dark_goldenrod = 0xC27C0E, - rust = 0xA84300, - brown = 0x992D22, - gray_chateau = 0x979C9F, - bismark = 0x546E7A, - sti_blue = 0x0E4BEF, - wrx_blue = 0x00247D, - rallyart_crimson = 0xE60012, - lime = 0x00FF00, - forest_green = 0x228B22, - cadmium_green = 0x097969, - aquamarine = 0x7FFFD4, - blue_green = 0x088F8F, - raspberry = 0xE30B5C, - scarlet_red = 0xFF2400; - }; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include + + /** + * @brief The main namespace for D++ functions. classes and types + */ +namespace dpp { + /** + * @brief predefined color constants + */ + namespace colors { + const uint32_t + white = 0xFFFFFF, + discord_white = 0xFFFFFE, + light_gray = 0xC0C0C0, + gray = 0x808080, + dark_gray = 0x404040, + black = 0x000000, + discord_black = 0x000001, + red = 0xFF0000, + pink = 0xFFAFAF, + orange = 0xFFC800, + yellow = 0xFFFF00, + green = 0x00FF00, + magenta = 0xFF00FF, + cyan = 0x00FFFF, + blue = 0x0000FF, + light_sea_green = 0x1ABC9C, + medium_sea_green = 0x2ECC71, + summer_sky = 0x3498DB, + deep_lilac = 0x9B59B6, + ruby = 0xE91E63, + moon_yellow = 0xF1C40F, + tahiti_gold = 0xE67E22, + cinnabar = 0xE74C3C, + submarine = 0x95A5A6, + blue_aquamarine = 0x607D8B, + deep_sea = 0x11806A, + sea_green = 0x1F8B4C, + endeavour = 0x206694, + vivid_violet = 0x71368A, + jazzberry_jam = 0xAD1457, + dark_goldenrod = 0xC27C0E, + rust = 0xA84300, + brown = 0x992D22, + gray_chateau = 0x979C9F, + bismark = 0x546E7A, + sti_blue = 0x0E4BEF, + wrx_blue = 0x00247D, + rallyart_crimson = 0xE60012, + lime = 0x00FF00, + forest_green = 0x228B22, + cadmium_green = 0x097969, + aquamarine = 0x7FFFD4, + blue_green = 0x088F8F, + raspberry = 0xE30B5C, + scarlet_red = 0xFF2400; + }; +}; diff --git a/3rdParty/dpp/commandhandler.h b/3rdParty/dpp/commandhandler.h index 1bebc899f5..1e4b12fa96 100644 --- a/3rdParty/dpp/commandhandler.h +++ b/3rdParty/dpp/commandhandler.h @@ -1,392 +1,392 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief dpp::resolved_user contains both a dpp::guild_member and a dpp::user. - * The user can be used to obtain in-depth user details such as if they are nitro, - * and the guild member information to check their roles on a guild etc. - * The Discord API provides both if a parameter is a user ping, - * so we offer both in a combined structure. - */ -struct DPP_EXPORT resolved_user { - /** - * @brief Holds user information - */ - dpp::user user; - /** - * @brief Holds member information - */ - dpp::guild_member member; -}; - -/** - * @brief Represents a received parameter. - * We use variant so that multiple non-related types can be contained within. - */ -typedef std::variant command_parameter; - -/** - * @brief Parameter types when registering a command. - * We don't pass these in when triggering the command in the handler, because it is - * expected the developer added the command so they know what types to expect for each named - * parameter. - */ -enum parameter_type { - pt_string, //!< String value - pt_role, //!< Role object - pt_channel, //!< Channel object - pt_user, //!< User object - pt_integer, //!< 64 bit signed integer - pt_double, //!< double floating point - pt_boolean //!< boolean -}; - -/** - * @brief Details of a command parameter used in registration. - * Note that for non-slash commands optional parameters can only be at the end of - * the list of parameters. - */ -struct DPP_EXPORT param_info { - - /** - * @brief Type of parameter - */ - parameter_type type; - - /** - * @brief True if the parameter is optional. - * For non-slash commands optional parameters may only be on the end of the list. - */ - bool optional; - - /** - * @brief Description of command. Displayed only for slash commands - */ - std::string description; - - /** - * @brief Allowed multiple choice options. - * The key name is the string passed to the command handler - * and the key value is its description displayed to the user. - */ - std::map choices; - - /** - * @brief Construct a new param_info object - * - * @param t Type of parameter - * @param o True if parameter is optional - * @param description The parameter description - * @param opts The options for a multiple choice parameter - */ - param_info(parameter_type t, bool o, const std::string &description, const std::map &opts = {}); -}; - -/** - * @brief Parameter list used during registration. - * Note that use of vector/pair is important here to preserve parameter order, - * as opposed to unordered_map (which doesn't guarantee any order at all) and - * std::map, which reorders keys alphabetically. - */ -typedef std::vector> parameter_registration_t; - -/** - * @brief Parameter list for a called command. - * See dpp::parameter_registration_t for an explanation as to why vector is used. - */ -typedef std::vector> parameter_list_t; - -/** - * @brief Represents the sending source of a command. - * This is passed to any command handler and should be passed back to - * commandhandler::reply(), allowing the reply method to route any replies back - * to the origin, which may be a slash command or a message. Both require different - * response facilities but we want this to be transparent if you use the command - * handler class. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -struct DPP_EXPORT command_source { - /** - * @brief Sending guild id - */ - snowflake guild_id; - /** - * @brief Source channel id - */ - snowflake channel_id; - /** - * @brief Command ID of a slash command - */ - snowflake command_id; - /** - * @brief Token for sending a slash command reply - */ - std::string command_token; - /** - * @brief The user who issued the command - */ - user issuer; - - /** - * @brief Copy of the underlying message_create_t event, if it was a message create event - */ - std::optional message_event; - - /** - * @brief Copy of the underlying interaction_create_t event, if it was an interaction create event - */ - std::optional interaction_event; - - /** - * @brief Construct a command_source object from a message_create_t event - */ - command_source(const struct message_create_t& event); - - /** - * @brief Construct a command_source object from an interaction_create_t event - */ - command_source(const struct interaction_create_t& event); -}; - -/** - * @brief The function definition for a command handler. Expects a command name string, - * and a list of command parameters. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -typedef std::function command_handler; - -/** - * @brief Represents the details of a command added to the command handler class. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -struct DPP_EXPORT command_info_t { - /** - * @brief Function reference for the handler. This is std::function so it can represent - * a class member, a lambda or a raw C function pointer. - */ - command_handler func; - /** - * @brief Parameters requested for the command, with their types - */ - parameter_registration_t parameters; - /** - * @brief Guild ID the command exists on, or 0 to be present on all guilds - */ - snowflake guild_id; -}; - - -/** - * @brief The commandhandler class represents a group of commands, prefixed or slash commands with handling functions. - * - * It can automatically register slash commands, and handle routing of messages and interactions to separated command handler - * functions. - * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. - */ -class DPP_EXPORT commandhandler { -private: - /** - * @brief List of guild commands to bulk register - */ - std::map> bulk_registration_list_guild; - /** - * @brief List of global commands to bulk register - */ - std::vector bulk_registration_list_global; -public: - /** - * @brief Commands in the handler - */ - std::unordered_map commands; - - /** - * @brief Valid prefixes - */ - std::vector prefixes; - - /** - * @brief Set to true automatically if one of the prefixes added is "/" - */ - bool slash_commands_enabled; - - /** - * @brief Cluster we are attached to for issuing REST calls - */ - class cluster* owner; - - /** - * @brief Application ID - */ - snowflake app_id; - - /** - * @brief Interaction event handle - */ - event_handle interactions; - - /** - * @brief Message event handle - */ - event_handle messages; - - /** - * @brief Returns true if the string has a known prefix on the start. - * Modifies string to remove prefix if it returns true. - * - * @param str String to check and modify - * @return true string contained a prefix, prefix removed from string - * @return false string did not contain a prefix - */ - bool string_has_prefix(std::string &str); - -public: - - /** - * @brief Construct a new commandhandler object - * - * @param o Owning cluster to attach to - * @param auto_hook_events Set to true to automatically hook the on_slashcommand - * and on_message events. You should not need to set this to false unless you have a specific - * use case, as D++ supports multiple listeners to an event, so will allow the commandhandler - * to hook to your command events without disrupting other uses for the events you may have. - * @param application_id The application id of the bot. If not specified, the class will - * look within the cluster object and use cluster::me::id instead. - */ - commandhandler(class cluster* o, bool auto_hook_events = true, snowflake application_id = 0); - - /** - * @brief Destroy the commandhandler object - */ - ~commandhandler(); - - /** - * @brief Set the application id after construction - * - * @param o Owning cluster to attach to - */ - commandhandler& set_owner(class cluster* o); - - /** - * @brief Add a prefix to the command handler - * - * @param prefix Prefix to be handled by the command handler - * @return commandhandler& reference to self - */ - commandhandler& add_prefix(const std::string &prefix); - - /** - * @brief Add a command to the command handler - * - * @param command Command to be handled. - * Note that if any one of your prefixes is "/" this will attempt to register - * a global command using the API and you will receive notification of this command - * via an interaction event. - * @param handler Handler function - * @param parameters Parameters to use for the command - * @param description The description of the command, shown for slash commands - * @param guild_id The guild ID to restrict the command to. For slash commands causes registration of a guild command as opposed to a global command. - * @return commandhandler& reference to self - * @throw dpp::logic_exception if application ID cannot be determined - */ - commandhandler& add_command(const std::string &command, const parameter_registration_t ¶meters, command_handler handler, const std::string &description = "", snowflake guild_id = 0); - - /** - * @brief Register all slash commands with Discord - * This method must be called at least once if you are using the "/" prefix to mark the - * end of commands being added to the handler. Note that this uses bulk registration and will replace any - * existing slash commands. - * - * Note that if you have previously registered your commands and they have not changed, you do - * not need to call this again. Discord retains a cache of previously added commands. - * - * @return commandhandler& Reference to self for chaining method calls - */ - commandhandler& register_commands(); - - /** - * @brief Route a command from the on_message_create function. - * Call this method from within your on_message_create with the received - * dpp::message object if you have disabled automatic registration of events. - * - * @param event message create event to parse - */ - void route(const struct dpp::message_create_t& event); - - /** - * @brief Route a command from the on_slashcommand function. - * Call this method from your on_slashcommand with the received - * dpp::interaction_create_t object if you have disabled automatic registration of events. - * - * @param event command interaction event to parse - */ - void route(const struct slashcommand_t & event); - - /** - * @brief Reply to a command. - * You should use this method rather than cluster::message_create as - * the way you reply varies between slash commands and message commands. - * Note you should ALWAYS reply. Slash commands will emit an ugly error - * to the user if you do not emit some form of reply within 3 seconds. - * - * @param m message to reply with. - * @param source source of the command - * @param callback User function to execute when the api call completes. - */ - void reply(const dpp::message &m, command_source source, command_completion_event_t callback = utility::log_error()); - - /** - * @brief Reply to a command without a message, causing the discord client - * to display "Bot name is thinking...". - * The "thinking" message will persist for a maximum of 15 minutes. - * This counts as a reply for a slash command. Slash commands will emit an - * ugly error to the user if you do not emit some form of reply within 3 - * seconds. - * - * @param source source of the command - * @param callback User function to execute when the api call completes. - */ - void thinking(command_source source, command_completion_event_t callback = utility::log_error()); - - /* Easter egg */ - void thonk(command_source source, command_completion_event_t callback = utility::log_error()); - -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief dpp::resolved_user contains both a dpp::guild_member and a dpp::user. + * The user can be used to obtain in-depth user details such as if they are nitro, + * and the guild member information to check their roles on a guild etc. + * The Discord API provides both if a parameter is a user ping, + * so we offer both in a combined structure. + */ +struct DPP_EXPORT resolved_user { + /** + * @brief Holds user information + */ + dpp::user user; + /** + * @brief Holds member information + */ + dpp::guild_member member; +}; + +/** + * @brief Represents a received parameter. + * We use variant so that multiple non-related types can be contained within. + */ +typedef std::variant command_parameter; + +/** + * @brief Parameter types when registering a command. + * We don't pass these in when triggering the command in the handler, because it is + * expected the developer added the command so they know what types to expect for each named + * parameter. + */ +enum parameter_type { + pt_string, //!< String value + pt_role, //!< Role object + pt_channel, //!< Channel object + pt_user, //!< User object + pt_integer, //!< 64 bit signed integer + pt_double, //!< double floating point + pt_boolean //!< boolean +}; + +/** + * @brief Details of a command parameter used in registration. + * Note that for non-slash commands optional parameters can only be at the end of + * the list of parameters. + */ +struct DPP_EXPORT param_info { + + /** + * @brief Type of parameter + */ + parameter_type type; + + /** + * @brief True if the parameter is optional. + * For non-slash commands optional parameters may only be on the end of the list. + */ + bool optional; + + /** + * @brief Description of command. Displayed only for slash commands + */ + std::string description; + + /** + * @brief Allowed multiple choice options. + * The key name is the string passed to the command handler + * and the key value is its description displayed to the user. + */ + std::map choices; + + /** + * @brief Construct a new param_info object + * + * @param t Type of parameter + * @param o True if parameter is optional + * @param description The parameter description + * @param opts The options for a multiple choice parameter + */ + param_info(parameter_type t, bool o, const std::string &description, const std::map &opts = {}); +}; + +/** + * @brief Parameter list used during registration. + * Note that use of vector/pair is important here to preserve parameter order, + * as opposed to unordered_map (which doesn't guarantee any order at all) and + * std::map, which reorders keys alphabetically. + */ +typedef std::vector> parameter_registration_t; + +/** + * @brief Parameter list for a called command. + * See dpp::parameter_registration_t for an explanation as to why vector is used. + */ +typedef std::vector> parameter_list_t; + +/** + * @brief Represents the sending source of a command. + * This is passed to any command handler and should be passed back to + * commandhandler::reply(), allowing the reply method to route any replies back + * to the origin, which may be a slash command or a message. Both require different + * response facilities but we want this to be transparent if you use the command + * handler class. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +struct DPP_EXPORT command_source { + /** + * @brief Sending guild id + */ + snowflake guild_id; + /** + * @brief Source channel id + */ + snowflake channel_id; + /** + * @brief Command ID of a slash command + */ + snowflake command_id; + /** + * @brief Token for sending a slash command reply + */ + std::string command_token; + /** + * @brief The user who issued the command + */ + user issuer; + + /** + * @brief Copy of the underlying message_create_t event, if it was a message create event + */ + std::optional message_event; + + /** + * @brief Copy of the underlying interaction_create_t event, if it was an interaction create event + */ + std::optional interaction_event; + + /** + * @brief Construct a command_source object from a message_create_t event + */ + command_source(const struct message_create_t& event); + + /** + * @brief Construct a command_source object from an interaction_create_t event + */ + command_source(const struct interaction_create_t& event); +}; + +/** + * @brief The function definition for a command handler. Expects a command name string, + * and a list of command parameters. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +typedef std::function command_handler; + +/** + * @brief Represents the details of a command added to the command handler class. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +struct DPP_EXPORT command_info_t { + /** + * @brief Function reference for the handler. This is std::function so it can represent + * a class member, a lambda or a raw C function pointer. + */ + command_handler func; + /** + * @brief Parameters requested for the command, with their types + */ + parameter_registration_t parameters; + /** + * @brief Guild ID the command exists on, or 0 to be present on all guilds + */ + snowflake guild_id; +}; + + +/** + * @brief The commandhandler class represents a group of commands, prefixed or slash commands with handling functions. + * + * It can automatically register slash commands, and handle routing of messages and interactions to separated command handler + * functions. + * @deprecated commandhandler and message commands are deprecated and dpp::slashcommand is encouraged as a replacement. + */ +class DPP_EXPORT commandhandler { +private: + /** + * @brief List of guild commands to bulk register + */ + std::map> bulk_registration_list_guild; + /** + * @brief List of global commands to bulk register + */ + std::vector bulk_registration_list_global; +public: + /** + * @brief Commands in the handler + */ + std::unordered_map commands; + + /** + * @brief Valid prefixes + */ + std::vector prefixes; + + /** + * @brief Set to true automatically if one of the prefixes added is "/" + */ + bool slash_commands_enabled; + + /** + * @brief Cluster we are attached to for issuing REST calls + */ + class cluster* owner; + + /** + * @brief Application ID + */ + snowflake app_id; + + /** + * @brief Interaction event handle + */ + event_handle interactions; + + /** + * @brief Message event handle + */ + event_handle messages; + + /** + * @brief Returns true if the string has a known prefix on the start. + * Modifies string to remove prefix if it returns true. + * + * @param str String to check and modify + * @return true string contained a prefix, prefix removed from string + * @return false string did not contain a prefix + */ + bool string_has_prefix(std::string &str); + +public: + + /** + * @brief Construct a new commandhandler object + * + * @param o Owning cluster to attach to + * @param auto_hook_events Set to true to automatically hook the on_slashcommand + * and on_message events. You should not need to set this to false unless you have a specific + * use case, as D++ supports multiple listeners to an event, so will allow the commandhandler + * to hook to your command events without disrupting other uses for the events you may have. + * @param application_id The application id of the bot. If not specified, the class will + * look within the cluster object and use cluster::me::id instead. + */ + commandhandler(class cluster* o, bool auto_hook_events = true, snowflake application_id = 0); + + /** + * @brief Destroy the commandhandler object + */ + ~commandhandler(); + + /** + * @brief Set the application id after construction + * + * @param o Owning cluster to attach to + */ + commandhandler& set_owner(class cluster* o); + + /** + * @brief Add a prefix to the command handler + * + * @param prefix Prefix to be handled by the command handler + * @return commandhandler& reference to self + */ + commandhandler& add_prefix(const std::string &prefix); + + /** + * @brief Add a command to the command handler + * + * @param command Command to be handled. + * Note that if any one of your prefixes is "/" this will attempt to register + * a global command using the API and you will receive notification of this command + * via an interaction event. + * @param handler Handler function + * @param parameters Parameters to use for the command + * @param description The description of the command, shown for slash commands + * @param guild_id The guild ID to restrict the command to. For slash commands causes registration of a guild command as opposed to a global command. + * @return commandhandler& reference to self + * @throw dpp::logic_exception if application ID cannot be determined + */ + commandhandler& add_command(const std::string &command, const parameter_registration_t ¶meters, command_handler handler, const std::string &description = "", snowflake guild_id = 0); + + /** + * @brief Register all slash commands with Discord + * This method must be called at least once if you are using the "/" prefix to mark the + * end of commands being added to the handler. Note that this uses bulk registration and will replace any + * existing slash commands. + * + * Note that if you have previously registered your commands and they have not changed, you do + * not need to call this again. Discord retains a cache of previously added commands. + * + * @return commandhandler& Reference to self for chaining method calls + */ + commandhandler& register_commands(); + + /** + * @brief Route a command from the on_message_create function. + * Call this method from within your on_message_create with the received + * dpp::message object if you have disabled automatic registration of events. + * + * @param event message create event to parse + */ + void route(const struct dpp::message_create_t& event); + + /** + * @brief Route a command from the on_slashcommand function. + * Call this method from your on_slashcommand with the received + * dpp::interaction_create_t object if you have disabled automatic registration of events. + * + * @param event command interaction event to parse + */ + void route(const struct slashcommand_t & event); + + /** + * @brief Reply to a command. + * You should use this method rather than cluster::message_create as + * the way you reply varies between slash commands and message commands. + * Note you should ALWAYS reply. Slash commands will emit an ugly error + * to the user if you do not emit some form of reply within 3 seconds. + * + * @param m message to reply with. + * @param source source of the command + * @param callback User function to execute when the api call completes. + */ + void reply(const dpp::message &m, command_source source, command_completion_event_t callback = utility::log_error()); + + /** + * @brief Reply to a command without a message, causing the discord client + * to display "Bot name is thinking...". + * The "thinking" message will persist for a maximum of 15 minutes. + * This counts as a reply for a slash command. Slash commands will emit an + * ugly error to the user if you do not emit some form of reply within 3 + * seconds. + * + * @param source source of the command + * @param callback User function to execute when the api call completes. + */ + void thinking(command_source source, command_completion_event_t callback = utility::log_error()); + + /* Easter egg */ + void thonk(command_source source, command_completion_event_t callback = utility::log_error()); + +}; + +}; diff --git a/3rdParty/dpp/coro.h b/3rdParty/dpp/coro.h index 43f4d4fe96..900a67e43b 100644 --- a/3rdParty/dpp/coro.h +++ b/3rdParty/dpp/coro.h @@ -1,158 +1,158 @@ -#ifdef DPP_CORO -#pragma once -#include -#include - -namespace dpp { - - /** - * @brief Shorthand for the coroutine handle's type - */ - using handle_type = std::coroutine_handle; - - class cluster; - - /** - * @brief Return type for coroutines - */ - struct task { - /** - * @brief Required nested promise_type for coroutines - */ - using promise_type = dpp::promise; - }; - - /** - * @brief Implementation of promise_type for dpp's coroutines - */ - struct promise { - /** - * @brief A pointer to the cluster making the requests in the coroutine - */ - cluster* bot = nullptr; - - /** - * @brief The result of the last co_await-ed function - */ - confirmation_callback_t callback; - - /** - * @brief Construct a new promise object - */ - promise() = default; - - /** - * @brief Construct a new promise object - * - * @param ev Base type of all events, only used to get the dpp::cluster pointer - */ - promise(const dpp::event_dispatch_t& ev) : bot(ev.from->creator) { } - - /** - * @brief Get the return object - * - * @return task dpp::task type - */ - task get_return_object() { - return {}; - } - - /** - * @brief Function called when the coroutine is first suspended, never suspends - * - * @return std::suspend_never Never suspend this coroutine at the first suspend point - */ - std::suspend_never initial_suspend() noexcept { - return {}; - } - - /** - * @brief Function called when the coroutine reaches its last suspension point - * - * @return std::suspend_never Never suspend this coroutine at the final suspend point - */ - std::suspend_never final_suspend() noexcept { - return {}; - } - - /** - * @brief Function called when the coroutine returns nothing - */ - void return_void() noexcept {} - - /** - * @brief Function called when coroutine throws a un-catch-ed exception. Does nothing - */ - void unhandled_exception() { - /* try { std::rethrow_exception(std::current_exception()); } */ - /* catch (const std::exception& e) { std::cout << e.what() << '\n'; } */ - } - }; - - /** - * @brief A co_await-able struct which returns the result of stored api call when co_await-ed. Meant to be opaque to the user - * - * @tparam T The type of the function (lambda if auto-generated by the php script) handling the making of api call - */ - template - struct awaitable { - /** - * @brief Pointer to the nested promise object of the coroutine, used for storing and retrieving the result of an api call - */ - promise* p; - - /** - * @brief Pointer to the cluster making the api request - */ - cluster* bot; - - /** - * @brief The function handling the making of request, using the cluster pointer - */ - T api_req; - - /** - * @brief Construct a new awaitable object - * - * @param cl pointer to the cluster making the api request - * @param api_call a function to invoke with the cluster pointer, handles the making of request - */ - awaitable(cluster* cl, T api_call) : bot{cl}, api_req{api_call} {} - - /** - * @brief First function called when this object is co_await-ed, its return type tells if the coroutine should be immediately suspended - * - * @return bool false, signifying immediate suspension - */ - bool await_ready() noexcept { - return false; - } - - /** - * @brief Function called when the coroutine is suspended, makes the api request and queues the resumption of the suspended coroutine, storing the result in promise object - * - * @param handle the handle to the suspended coroutine - */ - void await_suspend(handle_type handle) { - /* p = &handle.promise(); */ - /* if (!p->bot) p->bot = bot; */ - api_req([handle](const confirmation_callback_t& cback) { handle.promise().callback = cback; handle.resume(); }); - } - - /** - * @brief Function called when the coroutine is resumed by its handle, handles the retrieval and return of result from promise object - * - * @return confirmation_callback_t the result of the api call - */ - confirmation_callback_t await_resume() { - return p->callback; - } - }; - -}; - -/* template<> */ -/* struct std::coroutine_traits { */ -/* using promise_type = dpp::promise; */ -/* }; */ -#endif +#ifdef DPP_CORO +#pragma once +#include +#include + +namespace dpp { + + /** + * @brief Shorthand for the coroutine handle's type + */ + using handle_type = std::coroutine_handle; + + class cluster; + + /** + * @brief Return type for coroutines + */ + struct task { + /** + * @brief Required nested promise_type for coroutines + */ + using promise_type = dpp::promise; + }; + + /** + * @brief Implementation of promise_type for dpp's coroutines + */ + struct promise { + /** + * @brief A pointer to the cluster making the requests in the coroutine + */ + cluster* bot = nullptr; + + /** + * @brief The result of the last co_await-ed function + */ + confirmation_callback_t callback; + + /** + * @brief Construct a new promise object + */ + promise() = default; + + /** + * @brief Construct a new promise object + * + * @param ev Base type of all events, only used to get the dpp::cluster pointer + */ + promise(const dpp::event_dispatch_t& ev) : bot(ev.from->creator) { } + + /** + * @brief Get the return object + * + * @return task dpp::task type + */ + task get_return_object() { + return {}; + } + + /** + * @brief Function called when the coroutine is first suspended, never suspends + * + * @return std::suspend_never Never suspend this coroutine at the first suspend point + */ + std::suspend_never initial_suspend() noexcept { + return {}; + } + + /** + * @brief Function called when the coroutine reaches its last suspension point + * + * @return std::suspend_never Never suspend this coroutine at the final suspend point + */ + std::suspend_never final_suspend() noexcept { + return {}; + } + + /** + * @brief Function called when the coroutine returns nothing + */ + void return_void() noexcept {} + + /** + * @brief Function called when coroutine throws a un-catch-ed exception. Does nothing + */ + void unhandled_exception() { + /* try { std::rethrow_exception(std::current_exception()); } */ + /* catch (const std::exception& e) { std::cout << e.what() << '\n'; } */ + } + }; + + /** + * @brief A co_await-able struct which returns the result of stored api call when co_await-ed. Meant to be opaque to the user + * + * @tparam T The type of the function (lambda if auto-generated by the php script) handling the making of api call + */ + template + struct awaitable { + /** + * @brief Pointer to the nested promise object of the coroutine, used for storing and retrieving the result of an api call + */ + promise* p; + + /** + * @brief Pointer to the cluster making the api request + */ + cluster* bot; + + /** + * @brief The function handling the making of request, using the cluster pointer + */ + T api_req; + + /** + * @brief Construct a new awaitable object + * + * @param cl pointer to the cluster making the api request + * @param api_call a function to invoke with the cluster pointer, handles the making of request + */ + awaitable(cluster* cl, T api_call) : bot{cl}, api_req{api_call} {} + + /** + * @brief First function called when this object is co_await-ed, its return type tells if the coroutine should be immediately suspended + * + * @return bool false, signifying immediate suspension + */ + bool await_ready() noexcept { + return false; + } + + /** + * @brief Function called when the coroutine is suspended, makes the api request and queues the resumption of the suspended coroutine, storing the result in promise object + * + * @param handle the handle to the suspended coroutine + */ + void await_suspend(handle_type handle) { + /* p = &handle.promise(); */ + /* if (!p->bot) p->bot = bot; */ + api_req([handle](const confirmation_callback_t& cback) { handle.promise().callback = cback; handle.resume(); }); + } + + /** + * @brief Function called when the coroutine is resumed by its handle, handles the retrieval and return of result from promise object + * + * @return confirmation_callback_t the result of the api call + */ + confirmation_callback_t await_resume() { + return p->callback; + } + }; + +}; + +/* template<> */ +/* struct std::coroutine_traits { */ +/* using promise_type = dpp::promise; */ +/* }; */ +#endif diff --git a/3rdParty/dpp/discordclient.h b/3rdParty/dpp/discordclient.h index 745b705848..50c080c52e 100644 --- a/3rdParty/dpp/discordclient.h +++ b/3rdParty/dpp/discordclient.h @@ -1,519 +1,519 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -#define DISCORD_API_VERSION "10" -#define API_PATH "/api/v" DISCORD_API_VERSION -namespace dpp { - -// Forward declarations -class cluster; - -/** - * @brief This is an opaque class containing zlib library specific structures. - * We define it this way so that the public facing D++ library doesn't require - * the zlib headers be available to build against it. - */ -class zlibcontext; - -/** - * @brief Represents a connection to a voice channel. - * A client can only connect to one voice channel per guild at a time, so these are stored in a map - * in the dpp::discord_client keyed by guild_id. - */ -class DPP_EXPORT voiceconn { - /** - * @brief Owning dpp::discord_client instance - */ - class discord_client* creator; -public: - /** - * @brief Voice Channel ID - */ - snowflake channel_id; - - /** - * @brief Websocket hostname for status - */ - std::string websocket_hostname; - - /** - * @brief Voice Voice session ID - */ - std::string session_id; - - /** - * @brief Voice websocket token - */ - std::string token; - - /** - * @brief voice websocket client - */ - class discord_voice_client* voiceclient; - - /** - * @brief Construct a new voiceconn object - */ - voiceconn() = default; - - /** - * @brief Construct a new voiceconn object - * - * @param o owner - * @param _channel_id voice channel id - */ - voiceconn(class discord_client* o, snowflake _channel_id); - - /** - * @brief Destroy the voiceconn object - */ - ~voiceconn(); - - /** - * @brief return true if the connection is ready to connect - * (has hostname, token and session id) - * - * @return true if ready to connect - */ - bool is_ready(); - - /** - * @brief return true if the connection is active (websocket exists) - * - * @return true if has an active websocket - */ - bool is_active(); - - /** - * @brief Create websocket object and connect it. - * Needs hostname, token and session_id to be set or does nothing. - * - * @param guild_id Guild to connect to the voice channel on - * @return reference to self - * @note It can spawn a thread to establish the connection, so this is NOT a synchronous blocking call! - * You shouldn't call this directly. Use a wrapper function instead. e.g. dpp::guild::connect_member_voice - */ - voiceconn& connect(snowflake guild_id); - - /** - * @brief Disconnect from the currently connected voice channel - * @return reference to self - */ - voiceconn& disconnect(); -}; - -/** @brief Implements a discord client. Each discord_client connects to one shard and derives from a websocket client. */ -class DPP_EXPORT discord_client : public websocket_client -{ -protected: - /** - * @brief Needed so that voice_state_update can call dpp::discord_client::disconnect_voice_internal - */ - friend class dpp::events::voice_state_update; - - /** - * @brief Needed so that guild_create can request member chunks if you have the correct intents - */ - friend class dpp::events::guild_create; - - /** - * @brief Needed to allow cluster::set_presence to use the ETF functions - */ - friend class dpp::cluster; - - /** - * @brief True if the shard is terminating - */ - bool terminating; - - /** - * @brief Disconnect from the connected voice channel on a guild - * - * @param guild_id The guild who's voice channel you wish to disconnect from - * @param send_json True if we should send a json message confirming we are leaving the VC - * Should be set to false if we already receive this message in an event. - */ - void disconnect_voice_internal(snowflake guild_id, bool send_json = true); - -private: - - /** - * @brief Mutex for message queue - */ - std::shared_mutex queue_mutex; - - /** - * @brief Queue of outbound messages - */ - std::deque message_queue; - - /** - * @brief Thread this shard is executing on - */ - std::thread* runner; - - /** - * @brief Run shard loop under a thread. - * Calls discord_client::run() from within a std::thread. - */ - void thread_run(); - - /** - * @brief If true, stream compression is enabled - */ - bool compressed; - - /** - * @brief ZLib decompression buffer - */ - unsigned char* decomp_buffer; - - /** - * @brief Decompressed string - */ - std::string decompressed; - - /** - * @brief This object contains the various zlib structs which - * are not usable by the user of the library directly. They - * are wrapped within this opaque object so that this header - * file does not bring in a dependency on zlib.h. - */ - zlibcontext* zlib; - - /** - * @brief Total decompressed received bytes - */ - uint64_t decompressed_total; - - /** - * @brief Last connect time of cluster - */ - time_t connect_time; - - /** - * @brief Time last ping sent to websocket, in fractional seconds - */ - double ping_start; - - /** - * @brief ETF parser for when in ws_etf mode - */ - class etf_parser* etf; - - /** - * @brief Convert a JSON object to string. - * In JSON protocol mode, call json.dump(), and in ETF mode, - * call etf::build(). - * - * @param json nlohmann::json object to convert - * @return std::string string output in the correct format - */ - std::string jsonobj_to_string(const nlohmann::json& json); - - /** - * @brief Initialise ZLib (websocket compression) - * @throw dpp::exception if ZLib cannot be initialised - */ - void setup_zlib(); - - /** - * @brief Shut down ZLib (websocket compression) - */ - void end_zlib(); - - /** - * @brief Update the websocket hostname with the resume url - * from the last READY event - */ - void set_resume_hostname(); - -public: - /** - * @brief Owning cluster - */ - class dpp::cluster* creator; - - /** - * @brief Heartbeat interval for sending heartbeat keepalive - * @note value in milliseconds - */ - uint32_t heartbeat_interval; - - /** - * @brief Last heartbeat - */ - time_t last_heartbeat; - - /** - * @brief Shard ID of this client - */ - uint32_t shard_id; - - /** - * @brief Total number of shards - */ - uint32_t max_shards; - - /** - * @brief Thread ID - */ - std::thread::native_handle_type thread_id; - - /** - * @brief Last sequence number received, for resumes and pings - */ - uint64_t last_seq; - - /** - * @brief Discord bot token - */ - std::string token; - - /** - * @brief Privileged gateway intents - * @see dpp::intents - */ - uint32_t intents; - - /** - * @brief Discord session id - */ - std::string sessionid; - - /** - * @brief Mutex for voice connections map - */ - std::shared_mutex voice_mutex; - - /** - * @brief Resume count - */ - uint32_t resumes; - - /** - * @brief Reconnection count - */ - uint32_t reconnects; - - /** - * @brief Websocket latency in fractional seconds - */ - double websocket_ping; - - /** - * @brief True if READY or RESUMED has been received - */ - bool ready; - - /** - * @brief Last heartbeat ACK (opcode 11) - */ - time_t last_heartbeat_ack; - - /** - * @brief Current websocket protocol, currently either ETF or JSON - */ - websocket_protocol_t protocol; - - /** - * @brief List of voice channels we are connecting to keyed by guild id - */ - std::unordered_map connecting_voice_channels; - - /** - * @brief The gateway address we reconnect to when we resume a session - */ - std::string resume_gateway_url; - - /** - * @brief Log a message to whatever log the user is using. - * The logged message is passed up the chain to the on_log event in user code which can then do whatever - * it wants to do with it. - * @param severity The log level from dpp::loglevel - * @param msg The log message to output - */ - virtual void log(dpp::loglevel severity, const std::string &msg) const; - - /** - * @brief Handle an event (opcode 0) - * @param event Event name, e.g. MESSAGE_CREATE - * @param j JSON object for the event content - * @param raw Raw JSON event string - */ - virtual void handle_event(const std::string &event, json &j, const std::string &raw); - - /** - * @brief Get the Guild Count for this shard - * - * @return uint64_t guild count - */ - uint64_t get_guild_count(); - - /** - * @brief Get the Member Count for this shard - * - * @return uint64_t member count - */ - uint64_t get_member_count(); - - /** - * @brief Get the Channel Count for this shard - * - * @return uint64_t channel count - */ - uint64_t get_channel_count(); - - /** Fires every second from the underlying socket I/O loop, used for sending heartbeats */ - virtual void one_second_timer(); - - /** - * @brief Queue a message to be sent via the websocket - * - * @param j The JSON data of the message to be sent - * @param to_front If set to true, will place the message at the front of the queue not the back - * (this is for urgent messages such as heartbeat, presence, so they can take precedence over - * chunk requests etc) - */ - void queue_message(const std::string &j, bool to_front = false); - - /** - * @brief Clear the outbound message queue - * @return reference to self - */ - discord_client& clear_queue(); - - /** - * @brief Get the size of the outbound message queue - * - * @return The size of the queue - */ - size_t get_queue_size(); - - /** - * @brief Returns true if the shard is connected - * - * @return True if connected - */ - bool is_connected(); - - /** - * @brief Returns the connection time of the shard - * - * @return dpp::utility::uptime Detail of how long the shard has been connected for - */ - dpp::utility::uptime get_uptime(); - - /** - * @brief Construct a new discord_client object - * - * @param _cluster The owning cluster for this shard - * @param _shard_id The ID of the shard to start - * @param _max_shards The total number of shards across all clusters - * @param _token The bot token to use for identifying to the websocket - * @param intents Privileged intents to use, a bitmask of values from dpp::intents - * @param compressed True if the received data will be gzip compressed - * @param ws_protocol Websocket protocol to use for the connection, JSON or ETF - */ - discord_client(dpp::cluster* _cluster, uint32_t _shard_id, uint32_t _max_shards, const std::string &_token, uint32_t intents = 0, bool compressed = true, websocket_protocol_t ws_protocol = ws_json); - - /** - * @brief Destroy the discord client object - */ - virtual ~discord_client(); - - /** - * @brief Get the decompressed bytes in objectGet decompressed total bytes received - * @return uint64_t bytes received - */ - uint64_t get_decompressed_bytes_in(); - - /** - * @brief Handle JSON from the websocket. - * @param buffer The entire buffer content from the websocket client - * @returns True if a frame has been handled - */ - virtual bool handle_frame(const std::string &buffer); - - /** - * @brief Handle a websocket error. - * @param errorcode The error returned from the websocket - */ - virtual void error(uint32_t errorcode); - - /** - * @brief Start and monitor I/O loop. - * @note this is a blocking call and is usually executed within a - * thread by whatever creates the object. - */ - void run(); - - /** - * @brief Connect to a voice channel - * - * @param guild_id Guild where the voice channel is - * @param channel_id Channel ID of the voice channel - * @param self_mute True if the bot should mute itself - * @param self_deaf True if the bot should deafen itself - * @return reference to self - * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, - * as we have to wait for the connection to the voice server to be established! - * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. - */ - discord_client& connect_voice(snowflake guild_id, snowflake channel_id, bool self_mute = false, bool self_deaf = false); - - /** - * @brief Disconnect from the connected voice channel on a guild - * - * @param guild_id The guild who's voice channel you wish to disconnect from - * @return reference to self - * @note This is NOT a synchronous blocking call! The bot isn't instantly disconnected. - */ - discord_client& disconnect_voice(snowflake guild_id); - - /** - * @brief Get the dpp::voiceconn object for a specific guild on this shard. - * - * @param guild_id The guild ID to retrieve the voice connection for - * @return voiceconn* The voice connection for the guild, or nullptr if there is no - * voice connection to this guild. - */ - voiceconn* get_voice(snowflake guild_id); -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +#define DISCORD_API_VERSION "10" +#define API_PATH "/api/v" DISCORD_API_VERSION +namespace dpp { + +// Forward declarations +class cluster; + +/** + * @brief This is an opaque class containing zlib library specific structures. + * We define it this way so that the public facing D++ library doesn't require + * the zlib headers be available to build against it. + */ +class zlibcontext; + +/** + * @brief Represents a connection to a voice channel. + * A client can only connect to one voice channel per guild at a time, so these are stored in a map + * in the dpp::discord_client keyed by guild_id. + */ +class DPP_EXPORT voiceconn { + /** + * @brief Owning dpp::discord_client instance + */ + class discord_client* creator; +public: + /** + * @brief Voice Channel ID + */ + snowflake channel_id; + + /** + * @brief Websocket hostname for status + */ + std::string websocket_hostname; + + /** + * @brief Voice Voice session ID + */ + std::string session_id; + + /** + * @brief Voice websocket token + */ + std::string token; + + /** + * @brief voice websocket client + */ + class discord_voice_client* voiceclient; + + /** + * @brief Construct a new voiceconn object + */ + voiceconn() = default; + + /** + * @brief Construct a new voiceconn object + * + * @param o owner + * @param _channel_id voice channel id + */ + voiceconn(class discord_client* o, snowflake _channel_id); + + /** + * @brief Destroy the voiceconn object + */ + ~voiceconn(); + + /** + * @brief return true if the connection is ready to connect + * (has hostname, token and session id) + * + * @return true if ready to connect + */ + bool is_ready(); + + /** + * @brief return true if the connection is active (websocket exists) + * + * @return true if has an active websocket + */ + bool is_active(); + + /** + * @brief Create websocket object and connect it. + * Needs hostname, token and session_id to be set or does nothing. + * + * @param guild_id Guild to connect to the voice channel on + * @return reference to self + * @note It can spawn a thread to establish the connection, so this is NOT a synchronous blocking call! + * You shouldn't call this directly. Use a wrapper function instead. e.g. dpp::guild::connect_member_voice + */ + voiceconn& connect(snowflake guild_id); + + /** + * @brief Disconnect from the currently connected voice channel + * @return reference to self + */ + voiceconn& disconnect(); +}; + +/** @brief Implements a discord client. Each discord_client connects to one shard and derives from a websocket client. */ +class DPP_EXPORT discord_client : public websocket_client +{ +protected: + /** + * @brief Needed so that voice_state_update can call dpp::discord_client::disconnect_voice_internal + */ + friend class dpp::events::voice_state_update; + + /** + * @brief Needed so that guild_create can request member chunks if you have the correct intents + */ + friend class dpp::events::guild_create; + + /** + * @brief Needed to allow cluster::set_presence to use the ETF functions + */ + friend class dpp::cluster; + + /** + * @brief True if the shard is terminating + */ + bool terminating; + + /** + * @brief Disconnect from the connected voice channel on a guild + * + * @param guild_id The guild who's voice channel you wish to disconnect from + * @param send_json True if we should send a json message confirming we are leaving the VC + * Should be set to false if we already receive this message in an event. + */ + void disconnect_voice_internal(snowflake guild_id, bool send_json = true); + +private: + + /** + * @brief Mutex for message queue + */ + std::shared_mutex queue_mutex; + + /** + * @brief Queue of outbound messages + */ + std::deque message_queue; + + /** + * @brief Thread this shard is executing on + */ + std::thread* runner; + + /** + * @brief Run shard loop under a thread. + * Calls discord_client::run() from within a std::thread. + */ + void thread_run(); + + /** + * @brief If true, stream compression is enabled + */ + bool compressed; + + /** + * @brief ZLib decompression buffer + */ + unsigned char* decomp_buffer; + + /** + * @brief Decompressed string + */ + std::string decompressed; + + /** + * @brief This object contains the various zlib structs which + * are not usable by the user of the library directly. They + * are wrapped within this opaque object so that this header + * file does not bring in a dependency on zlib.h. + */ + zlibcontext* zlib; + + /** + * @brief Total decompressed received bytes + */ + uint64_t decompressed_total; + + /** + * @brief Last connect time of cluster + */ + time_t connect_time; + + /** + * @brief Time last ping sent to websocket, in fractional seconds + */ + double ping_start; + + /** + * @brief ETF parser for when in ws_etf mode + */ + class etf_parser* etf; + + /** + * @brief Convert a JSON object to string. + * In JSON protocol mode, call json.dump(), and in ETF mode, + * call etf::build(). + * + * @param json nlohmann::json object to convert + * @return std::string string output in the correct format + */ + std::string jsonobj_to_string(const nlohmann::json& json); + + /** + * @brief Initialise ZLib (websocket compression) + * @throw dpp::exception if ZLib cannot be initialised + */ + void setup_zlib(); + + /** + * @brief Shut down ZLib (websocket compression) + */ + void end_zlib(); + + /** + * @brief Update the websocket hostname with the resume url + * from the last READY event + */ + void set_resume_hostname(); + +public: + /** + * @brief Owning cluster + */ + class dpp::cluster* creator; + + /** + * @brief Heartbeat interval for sending heartbeat keepalive + * @note value in milliseconds + */ + uint32_t heartbeat_interval; + + /** + * @brief Last heartbeat + */ + time_t last_heartbeat; + + /** + * @brief Shard ID of this client + */ + uint32_t shard_id; + + /** + * @brief Total number of shards + */ + uint32_t max_shards; + + /** + * @brief Thread ID + */ + std::thread::native_handle_type thread_id; + + /** + * @brief Last sequence number received, for resumes and pings + */ + uint64_t last_seq; + + /** + * @brief Discord bot token + */ + std::string token; + + /** + * @brief Privileged gateway intents + * @see dpp::intents + */ + uint32_t intents; + + /** + * @brief Discord session id + */ + std::string sessionid; + + /** + * @brief Mutex for voice connections map + */ + std::shared_mutex voice_mutex; + + /** + * @brief Resume count + */ + uint32_t resumes; + + /** + * @brief Reconnection count + */ + uint32_t reconnects; + + /** + * @brief Websocket latency in fractional seconds + */ + double websocket_ping; + + /** + * @brief True if READY or RESUMED has been received + */ + bool ready; + + /** + * @brief Last heartbeat ACK (opcode 11) + */ + time_t last_heartbeat_ack; + + /** + * @brief Current websocket protocol, currently either ETF or JSON + */ + websocket_protocol_t protocol; + + /** + * @brief List of voice channels we are connecting to keyed by guild id + */ + std::unordered_map connecting_voice_channels; + + /** + * @brief The gateway address we reconnect to when we resume a session + */ + std::string resume_gateway_url; + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Handle an event (opcode 0) + * @param event Event name, e.g. MESSAGE_CREATE + * @param j JSON object for the event content + * @param raw Raw JSON event string + */ + virtual void handle_event(const std::string &event, json &j, const std::string &raw); + + /** + * @brief Get the Guild Count for this shard + * + * @return uint64_t guild count + */ + uint64_t get_guild_count(); + + /** + * @brief Get the Member Count for this shard + * + * @return uint64_t member count + */ + uint64_t get_member_count(); + + /** + * @brief Get the Channel Count for this shard + * + * @return uint64_t channel count + */ + uint64_t get_channel_count(); + + /** Fires every second from the underlying socket I/O loop, used for sending heartbeats */ + virtual void one_second_timer(); + + /** + * @brief Queue a message to be sent via the websocket + * + * @param j The JSON data of the message to be sent + * @param to_front If set to true, will place the message at the front of the queue not the back + * (this is for urgent messages such as heartbeat, presence, so they can take precedence over + * chunk requests etc) + */ + void queue_message(const std::string &j, bool to_front = false); + + /** + * @brief Clear the outbound message queue + * @return reference to self + */ + discord_client& clear_queue(); + + /** + * @brief Get the size of the outbound message queue + * + * @return The size of the queue + */ + size_t get_queue_size(); + + /** + * @brief Returns true if the shard is connected + * + * @return True if connected + */ + bool is_connected(); + + /** + * @brief Returns the connection time of the shard + * + * @return dpp::utility::uptime Detail of how long the shard has been connected for + */ + dpp::utility::uptime get_uptime(); + + /** + * @brief Construct a new discord_client object + * + * @param _cluster The owning cluster for this shard + * @param _shard_id The ID of the shard to start + * @param _max_shards The total number of shards across all clusters + * @param _token The bot token to use for identifying to the websocket + * @param intents Privileged intents to use, a bitmask of values from dpp::intents + * @param compressed True if the received data will be gzip compressed + * @param ws_protocol Websocket protocol to use for the connection, JSON or ETF + */ + discord_client(dpp::cluster* _cluster, uint32_t _shard_id, uint32_t _max_shards, const std::string &_token, uint32_t intents = 0, bool compressed = true, websocket_protocol_t ws_protocol = ws_json); + + /** + * @brief Destroy the discord client object + */ + virtual ~discord_client(); + + /** + * @brief Get the decompressed bytes in objectGet decompressed total bytes received + * @return uint64_t bytes received + */ + uint64_t get_decompressed_bytes_in(); + + /** + * @brief Handle JSON from the websocket. + * @param buffer The entire buffer content from the websocket client + * @returns True if a frame has been handled + */ + virtual bool handle_frame(const std::string &buffer); + + /** + * @brief Handle a websocket error. + * @param errorcode The error returned from the websocket + */ + virtual void error(uint32_t errorcode); + + /** + * @brief Start and monitor I/O loop. + * @note this is a blocking call and is usually executed within a + * thread by whatever creates the object. + */ + void run(); + + /** + * @brief Connect to a voice channel + * + * @param guild_id Guild where the voice channel is + * @param channel_id Channel ID of the voice channel + * @param self_mute True if the bot should mute itself + * @param self_deaf True if the bot should deafen itself + * @return reference to self + * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, + * as we have to wait for the connection to the voice server to be established! + * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. + */ + discord_client& connect_voice(snowflake guild_id, snowflake channel_id, bool self_mute = false, bool self_deaf = false); + + /** + * @brief Disconnect from the connected voice channel on a guild + * + * @param guild_id The guild who's voice channel you wish to disconnect from + * @return reference to self + * @note This is NOT a synchronous blocking call! The bot isn't instantly disconnected. + */ + discord_client& disconnect_voice(snowflake guild_id); + + /** + * @brief Get the dpp::voiceconn object for a specific guild on this shard. + * + * @param guild_id The guild ID to retrieve the voice connection for + * @return voiceconn* The voice connection for the guild, or nullptr if there is no + * voice connection to this guild. + */ + voiceconn* get_voice(snowflake guild_id); +}; + +}; diff --git a/3rdParty/dpp/discordevents.h b/3rdParty/dpp/discordevents.h index 62f88c33ee..c6474a45c0 100644 --- a/3rdParty/dpp/discordevents.h +++ b/3rdParty/dpp/discordevents.h @@ -1,171 +1,171 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include -#include - -namespace dpp { - -/** @brief Returns a snowflake id from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint64_t DPP_EXPORT snowflake_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a snowflake id from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_snowflake_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); - -/** @brief Returns a string from a json field value, if defined, else returns an empty string. - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -std::string DPP_EXPORT string_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a string from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_string_not_null(const nlohmann::json* j, const char *keyname, std::string &v); - -/** @brief Returns a double from a json field value, if defined, else returns 0. - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -double DPP_EXPORT double_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a double from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_double_not_null(const nlohmann::json* j, const char *keyname, double &v); - -/** @brief Returns a 64 bit unsigned integer from a json field value, if defined, else returns 0. - * DO NOT use this for snowflakes, as usually snowflakes are wrapped in a string! - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint64_t DPP_EXPORT int64_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 64 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int64_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); - -/** @brief Returns a 32 bit unsigned integer from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint32_t DPP_EXPORT int32_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 32 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int32_not_null(const nlohmann::json* j, const char *keyname, uint32_t &v); - -/** @brief Returns a 16 bit unsigned integer from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint16_t DPP_EXPORT int16_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 16 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int16_not_null(const nlohmann::json* j, const char *keyname, uint16_t &v); - -/** @brief Returns an 8 bit unsigned integer from a json field value, if defined, else returns 0 - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -uint8_t DPP_EXPORT int8_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an unsigned 8 bit integer from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_int8_not_null(const nlohmann::json* j, const char *keyname, uint8_t &v); - -/** @brief Returns a boolean value from a json field value, if defined, else returns false - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -bool DPP_EXPORT bool_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets a boolean from a json field value, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_bool_not_null(const nlohmann::json* j, const char *keyname, bool &v); - -/** @brief Returns a time_t from an ISO8601 timestamp field in a json value, if defined, else returns - * epoch value of 0. - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @return found value - */ -time_t DPP_EXPORT ts_not_null(const nlohmann::json* j, const char *keyname); - -/** @brief Sets an timestamp from a json field value containing an ISO8601 string, if defined, else does nothing - * @param j nlohmann::json instance to retrieve value from - * @param keyname key name to check for a value - * @param v Value to change - */ -void DPP_EXPORT set_ts_not_null(const nlohmann::json* j, const char *keyname, time_t &v); - -/** @brief Base64 encode data into a string. - * @param buf Raw binary buffer - * @param buffer_length Buffer length to encode - * @return The base64 encoded string - */ -std::string DPP_EXPORT base64_encode(unsigned char const* buf, unsigned int buffer_length); - -/** - * @brief Convert time_t unix epoch to std::string ISO date/time - * - * @param ts Timestamp to convert - * @return std::string Converted time/date string - */ -std::string DPP_EXPORT ts_to_string(time_t ts); - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include +#include + +namespace dpp { + +/** @brief Returns a snowflake id from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint64_t DPP_EXPORT snowflake_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a snowflake id from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_snowflake_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); + +/** @brief Returns a string from a json field value, if defined, else returns an empty string. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +std::string DPP_EXPORT string_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a string from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_string_not_null(const nlohmann::json* j, const char *keyname, std::string &v); + +/** @brief Returns a double from a json field value, if defined, else returns 0. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +double DPP_EXPORT double_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a double from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_double_not_null(const nlohmann::json* j, const char *keyname, double &v); + +/** @brief Returns a 64 bit unsigned integer from a json field value, if defined, else returns 0. + * DO NOT use this for snowflakes, as usually snowflakes are wrapped in a string! + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint64_t DPP_EXPORT int64_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 64 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int64_not_null(const nlohmann::json* j, const char *keyname, uint64_t &v); + +/** @brief Returns a 32 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint32_t DPP_EXPORT int32_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 32 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int32_not_null(const nlohmann::json* j, const char *keyname, uint32_t &v); + +/** @brief Returns a 16 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint16_t DPP_EXPORT int16_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 16 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int16_not_null(const nlohmann::json* j, const char *keyname, uint16_t &v); + +/** @brief Returns an 8 bit unsigned integer from a json field value, if defined, else returns 0 + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +uint8_t DPP_EXPORT int8_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an unsigned 8 bit integer from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_int8_not_null(const nlohmann::json* j, const char *keyname, uint8_t &v); + +/** @brief Returns a boolean value from a json field value, if defined, else returns false + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +bool DPP_EXPORT bool_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets a boolean from a json field value, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_bool_not_null(const nlohmann::json* j, const char *keyname, bool &v); + +/** @brief Returns a time_t from an ISO8601 timestamp field in a json value, if defined, else returns + * epoch value of 0. + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @return found value + */ +time_t DPP_EXPORT ts_not_null(const nlohmann::json* j, const char *keyname); + +/** @brief Sets an timestamp from a json field value containing an ISO8601 string, if defined, else does nothing + * @param j nlohmann::json instance to retrieve value from + * @param keyname key name to check for a value + * @param v Value to change + */ +void DPP_EXPORT set_ts_not_null(const nlohmann::json* j, const char *keyname, time_t &v); + +/** @brief Base64 encode data into a string. + * @param buf Raw binary buffer + * @param buffer_length Buffer length to encode + * @return The base64 encoded string + */ +std::string DPP_EXPORT base64_encode(unsigned char const* buf, unsigned int buffer_length); + +/** + * @brief Convert time_t unix epoch to std::string ISO date/time + * + * @param ts Timestamp to convert + * @return std::string Converted time/date string + */ +std::string DPP_EXPORT ts_to_string(time_t ts); + +}; diff --git a/3rdParty/dpp/discordvoiceclient.h b/3rdParty/dpp/discordvoiceclient.h index 9ecd3840d5..a98fd84f8d 100644 --- a/3rdParty/dpp/discordvoiceclient.h +++ b/3rdParty/dpp/discordvoiceclient.h @@ -1,868 +1,868 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -struct OpusDecoder; -struct OpusEncoder; -struct OpusRepacketizer; - -namespace dpp { - -// Forward declaration -class cluster; - -/** - * @brief An opus-encoded RTP packet to be sent out to a voice channel - */ -struct DPP_EXPORT voice_out_packet { - /** - * @brief Each string is a UDP packet. - * Generally these will be RTP. - */ - std::string packet; - /** - * @brief Duration of packet - */ - uint64_t duration; -}; - -#define AUDIO_TRACK_MARKER (uint16_t)0xFFFF - -#define AUDIO_OVERLAP_SLEEP_SAMPLES 30 - -/** @brief Implements a discord voice connection. - * Each discord_voice_client connects to one voice channel and derives from a websocket client. - */ -class DPP_EXPORT discord_voice_client : public websocket_client -{ - /** - * @brief Mutex for outbound packet stream - */ - std::mutex stream_mutex; - - /** - * @brief Mutex for message queue - */ - std::shared_mutex queue_mutex; - - /** - * @brief Queue of outbound messages - */ - std::deque message_queue; - - /** - * @brief Thread this connection is executing on - */ - std::thread* runner; - - /** - * @brief Run shard loop under a thread - */ - void thread_run(); - - /** - * @brief Last connect time of voice session - */ - time_t connect_time; - - /** - * @brief IP of UDP/RTP endpoint - */ - std::string ip; - - /** - * @brief Port number of UDP/RTP endpoint - */ - uint16_t port; - - /** - * @brief SSRC value - */ - uint64_t ssrc; - - /** - * @brief List of supported audio encoding modes - */ - std::vector modes; - - /** - * @brief Timescale in nanoseconds - */ - uint64_t timescale; - - /** - * @brief Output buffer - */ - std::vector outbuf; - - /** - * @brief Data type of RTP packet sequence number field. - */ - using rtp_seq_t = uint16_t; - using rtp_timestamp_t = uint32_t; - - /** - * @brief Keeps track of the voice payload to deliver to voice handlers. - */ - struct voice_payload { - /** - * @brief The sequence number of the RTP packet that generated this - * voice payload. - */ - rtp_seq_t seq; - /** - * @brief The timestamp of the RTP packet that generated this voice - * payload. - * - * The timestamp is used to detect the order around where sequence - * number wraps around. - */ - rtp_timestamp_t timestamp; - /** - * @brief The event payload that voice handlers receive. - */ - std::unique_ptr vr; - - /** - * @brief For priority_queue sorting. - * @return true if "this" has lower priority that "other", - * i.e. appears later in the queue; false otherwise. - */ - bool operator<(const voice_payload& other) const; - }; - - struct voice_payload_parking_lot { - /** - * @brief The range of RTP packet sequence number and timestamp in the lot. - * - * The minimum is used to drop packets that arrive too late. Packets - * less than the minimum have been delivered to voice handlers and - * there is no going back. Unfortunately we just have to drop them. - * - * The maximum is used, at flush time, to calculate the minimum for - * the next batch. The maximum is also updated every time we receive an - * RTP packet with a larger value. - */ - struct seq_range_t { - rtp_seq_t min_seq, max_seq; - rtp_timestamp_t min_timestamp, max_timestamp; - } range; - /** - * @brief The queue of parked voice payloads. - * - * We group payloads and deliver them to handlers periodically as the - * handling of out-of-order RTP packets. Payloads in between flushes - * are parked and sorted in this queue. - */ - std::priority_queue parked_payloads; - /** - * @brief The decoder ctls to be set on the decoder. - */ - std::vector> pending_decoder_ctls; - /** - * @brief libopus decoder - * - * Shared with the voice courier thread that does the decoding. - * This is not protected by a mutex because only the courier thread - * uses the decoder. - */ - std::shared_ptr decoder; - }; - /** - * @brief Thread used to deliver incoming voice data to handlers. - */ - std::thread voice_courier; - /** - * @brief Shared state between this voice client and the courier thread. - */ - struct courier_shared_state_t { - /** - * @brief Protects all following members. - */ - std::mutex mtx; - /** - * @brief Signaled when there is a new payload to deliver or terminating state has changed. - */ - std::condition_variable signal_iteration; - /** - * @brief Voice buffers to be reported to handler, grouped by speaker. - * - * Buffers are parked here and flushed every 500ms. - */ - std::map parked_voice_payloads; - /** - * @brief Used to signal termination. - * - * @note Pending payloads are delivered first before termination. - */ - bool terminating = false; - } voice_courier_shared_state; - /** - * @brief The run loop of the voice courier thread. - */ - static void voice_courier_loop(discord_voice_client&, courier_shared_state_t&); - - /** - * @brief If true, audio packet sending is paused - */ - bool paused; - -#ifdef HAVE_VOICE - /** - * @brief libopus encoder - */ - OpusEncoder* encoder; - - /** - * @brief libopus repacketizer - * (merges frames into one packet) - */ - OpusRepacketizer* repacketizer; -#else - /** - * @brief libopus encoder - */ - void* encoder; - - /** - * @brief libopus repacketizer - * (merges frames into one packet) - */ - void* repacketizer; -#endif - - /** - * @brief File descriptor for UDP connection - */ - dpp::socket fd; - - /** - * @brief Secret key for encrypting voice. - * If it has been sent, this is non-null and points to a - * sequence of exactly 32 bytes. - */ - uint8_t* secret_key; - - /** - * @brief Sequence number of outbound audio. This is incremented - * once per frame sent. - */ - uint16_t sequence; - - /** - * @brief Timestamp value used in outbound audio. Each packet - * has the timestamp value which is incremented to match - * how many frames are sent. - */ - uint32_t timestamp; - - /** - * @brief Last sent packet high-resolution timestamp - */ - std::chrono::high_resolution_clock::time_point last_timestamp; - - /** - * @brief Fraction of the sleep that was not executed after the last audio packet was sent - */ - std::chrono::nanoseconds last_sleep_remainder; - - /** - * @brief Maps receiving ssrc to user id - */ - std::unordered_map ssrc_map; - - /** - * @brief This is set to true if we have started sending audio. - * When this moves from false to true, this causes the - * client to send the 'talking' notification to the websocket. - */ - bool sending; - - /** - * @brief Number of track markers in the buffer. For example if there - * are two track markers in the buffer there are 3 tracks. - * - * **Special case:** - * - * If the buffer is empty, there are zero tracks in the - * buffer. - */ - uint32_t tracks; - - /** - * @brief Meta data associated with each track. - * Arbitrary string that the user can set via - * dpp::discord_voice_client::add_marker - */ - std::vector track_meta; - - /** - * @brief Encoding buffer for opus repacketizer and encode - */ - uint8_t encode_buffer[65536]; - - /** - * @brief Send data to UDP socket immediately. - * - * @param data data to send - * @param length length of data to send - * @return int bytes sent. Will return -1 if we cannot send - */ - int udp_send(const char* data, size_t length); - - /** - * @brief Receive data from UDP socket immediately. - * - * @param data data to receive - * @param max_length size of data receiving buffer - * @return int bytes received. -1 if there is an error - * (e.g. EAGAIN) - */ - int udp_recv(char* data, size_t max_length); - - /** - * @brief This hooks the ssl_client, returning the file - * descriptor if we want to send buffered data, or - * -1 if there is nothing to send - * - * @return int file descriptor or -1 - */ - dpp::socket want_write(); - - /** - * @brief This hooks the ssl_client, returning the file - * descriptor if we want to receive buffered data, or - * -1 if we are not wanting to receive - * - * @return int file descriptor or -1 - */ - dpp::socket want_read(); - - /** - * @brief Called by ssl_client when the socket is ready - * for writing, at this point we pick the head item off - * the buffer and send it. So long as it doesn't error - * completely, we pop it off the head of the queue. - */ - void write_ready(); - - /** - * @brief Called by ssl_client when there is data to be - * read. At this point we insert that data into the - * input queue. - */ - void read_ready(); - - /** - * @brief Send data to the UDP socket, using the buffer. - * - * @param packet packet data - * @param len length of packet - * @param duration duration of opus packet - */ - void send(const char* packet, size_t len, uint64_t duration); - - /** - * @brief Queue a message to be sent via the websocket - * - * @param j The JSON data of the message to be sent - * @param to_front If set to true, will place the message at the front of the queue not the back - * (this is for urgent messages such as heartbeat, presence, so they can take precedence over - * chunk requests etc) - */ - void queue_message(const std::string &j, bool to_front = false); - - /** - * @brief Clear the outbound message queue - * - */ - void clear_queue(); - - /** - * @brief Get the size of the outbound message queue - * - * @return The size of the queue - */ - size_t get_queue_size(); - - /** - * @brief Encode a byte buffer using opus codec. - * Multiple opus frames (2880 bytes each) will be encoded into one packet for sending. - * - * @param input Input data as raw bytes of PCM data - * @param inDataSize Input data length - * @param output Output data as an opus encoded packet - * @param outDataSize Output data length, should be at least equal to the input size. - * Will be adjusted on return to the actual compressed data size. - * @return size_t The compressed data size that was encoded. - * @throw dpp::voice_exception If data length to encode is invalid or voice support not compiled into D++ - */ - size_t encode(uint8_t *input, size_t inDataSize, uint8_t *output, size_t &outDataSize); - -public: - - /** - * @brief Owning cluster - */ - class dpp::cluster* creator; - - /** - * @brief This needs to be static, we only initialise libsodium once per program start, - * so initialising it on first use in a voice connection is best. - */ - static bool sodium_initialised; - - /** - * @brief True when the thread is shutting down - */ - bool terminating; - - /** - * @brief Heartbeat interval for sending heartbeat keepalive - */ - uint32_t heartbeat_interval; - - /** - * @brief Last voice channel websocket heartbeat - */ - time_t last_heartbeat; - - /** - * @brief Thread ID - */ - std::thread::native_handle_type thread_id; - - /** - * @brief Discord voice session token - */ - std::string token; - - /** - * @brief Discord voice session id - */ - std::string sessionid; - - /** - * @brief Server ID - */ - snowflake server_id; - - /** - * @brief Channel ID - */ - snowflake channel_id; - - /** - * @brief The audio type to be sent. The default type is recorded audio. - * - * If the audio is recorded, the sending of audio packets is throttled. - * Otherwise, if the audio is live, the sending is not throttled. - * - * Discord voice engine is expecting audio data as if they were from - * some audio device, e.g. microphone, where the data become available - * as they get captured from the audio device. - * - * In case of recorded audio, unlike from a device, the audio data are - * usually instantly available in large chunks. Throttling is needed to - * simulate audio data coming from an audio device. In case of live audio, - * the throttling is by nature, so no extra throttling is needed. - * - * Using live audio mode for recorded audio can cause Discord to skip - * audio data because Discord does not expect to receive, say, 3 minutes' - * worth of audio data in 1 second. - * - * There are some inaccuracies in the throttling method used by the recorded - * audio mode on some systems (mainly Windows) which causes gaps and stutters - * in the resulting audio stream. The overlap audio mode provides a different - * implementation that fixes the issue. This method is slightly more CPU - * intensive, and should only be used if you encounter issues with recorded audio - * on your system. - * - * Use discord_voice_client::set_send_audio_type to change this value as - * it ensures thread safety. - */ - enum send_audio_type_t - { - satype_recorded_audio, - satype_live_audio, - satype_overlap_audio - } send_audio_type = satype_recorded_audio; - - /** - * @brief Sets the gain for the specified user. - * - * Similar to the User Volume slider, controls the listening volume per user. - * Uses native Opus gain control, so clients don't have to perform extra - * audio processing. - * - * The gain setting will affect the both individual and combined voice audio. - * - * The gain value can also be set even before the user connects to the voice - * channel. - * - * @param user_id The ID of the user where the gain is to be controlled. - * @param factor Nonnegative factor to scale the amplitude by, where 1.f reverts - * to the default volume. - */ - void set_user_gain(snowflake user_id, float factor); - - /** - * @brief Log a message to whatever log the user is using. - * The logged message is passed up the chain to the on_log event in user code which can then do whatever - * it wants to do with it. - * @param severity The log level from dpp::loglevel - * @param msg The log message to output - */ - virtual void log(dpp::loglevel severity, const std::string &msg) const; - - /** - * @brief Fires every second from the underlying socket I/O loop, used for sending heartbeats - * @throw dpp::exception if the socket needs to disconnect - */ - virtual void one_second_timer(); - - /** - * @brief voice client is ready to stream audio. - * The voice client is considered ready if it has a secret key. - * - * @return true if ready to stream audio - */ - bool is_ready(); - - /** - * @brief Returns true if the voice client is connected to the websocket - * - * @return True if connected - */ - bool is_connected(); - - /** - * @brief Returns the connection time of the voice client - * - * @return dpp::utility::uptime Detail of how long the voice client has been connected for - */ - dpp::utility::uptime get_uptime(); - - /** Constructor takes shard id, max shards and token. - * @param _cluster The cluster which owns this voice connection, for related logging, REST requests etc - * @param _channel_id The channel id to identify the voice connection as - * @param _server_id The server id (guild id) to identify the voice connection as - * @param _token The voice session token to use for identifying to the websocket - * @param _session_id The voice session id to identify with - * @param _host The voice server hostname to connect to (hostname:port format) - * @throw dpp::voice_exception Sodium or Opus failed to initialise, or D++ is not compiled with voice support - */ - discord_voice_client(dpp::cluster* _cluster, snowflake _channel_id, snowflake _server_id, const std::string &_token, const std::string &_session_id, const std::string &_host); - - /** - * @brief Destroy the discord voice client object - */ - virtual ~discord_voice_client(); - - /** - * @brief Handle JSON from the websocket. - * @param buffer The entire buffer content from the websocket client - * @return bool True if a frame has been handled - * @throw dpp::exception If there was an error processing the frame, or connection to UDP socket failed - */ - virtual bool handle_frame(const std::string &buffer); - - /** - * @brief Handle a websocket error. - * @param errorcode The error returned from the websocket - */ - virtual void error(uint32_t errorcode); - - /** - * @brief Start and monitor I/O loop - */ - void run(); - - /** - * @brief Send raw audio to the voice channel. - * - * You should send an audio packet of 11520 bytes. - * Note that this function can be costly as it has to opus encode - * the PCM audio on the fly, and also encrypt it with libsodium. - * - * @note Because this function encrypts and encodes packets before - * pushing them onto the output queue, if you have a complete stream - * ready to send and know its length it is advisable to call this - * method multiple times to enqueue the entire stream audio so that - * it is all encoded at once (unless you have set use_opus to false). - * Constantly calling this from the dpp::on_voice_buffer_send callback - * can and will eat a TON of cpu! - * - * @param audio_data Raw PCM audio data. Channels are interleaved, - * with each channel's amplitude being a 16 bit value. - * - * The audio data should be 48000Hz signed 16 bit audio. - * - * @param length The length of the audio data. The length should - * be a multiple of 4 (2x 16 bit stereo channels) with a maximum - * length of 11520, which is a complete opus frame at highest - * quality. - * - * @return discord_voice_client& Reference to self - * - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& send_audio_raw(uint16_t* audio_data, const size_t length); - - /** - * @brief Send opus packets to the voice channel - * - * Some containers such as .ogg may contain OPUS - * encoded data already. In this case, we don't need to encode the - * frames using opus here. We can bypass the codec, only applying - * libsodium to the stream. - * - * @param opus_packet Opus packets. Discord expects opus frames - * to be encoded at 48000Hz - * - * @param length The length of the audio data. - * - * @param duration Generally duration is 2.5, 5, 10, 20, 40 or 60 - * if the timescale is 1000000 (1ms) - * - * @return discord_voice_client& Reference to self - * - * @note It is your responsibility to ensure that packets of data - * sent to send_audio are correctly repacketized for streaming, - * e.g. that audio frames are not too large or contain - * an incorrect format. Discord will still expect the same frequency - * and bit width of audio and the same signedness. - * - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length, uint64_t duration); - - /** - * @brief Send opus packets to the voice channel - * - * Some containers such as .ogg may contain OPUS - * encoded data already. In this case, we don't need to encode the - * frames using opus here. We can bypass the codec, only applying - * libsodium to the stream. - * - * Duration is calculated internally - * - * @param opus_packet Opus packets. Discord expects opus frames - * to be encoded at 48000Hz - * - * @param length The length of the audio data. - * - * @return discord_voice_client& Reference to self - * - * @note It is your responsibility to ensure that packets of data - * sent to send_audio are correctly repacketized for streaming, - * e.g. that audio frames are not too large or contain - * an incorrect format. Discord will still expect the same frequency - * and bit width of audio and the same signedness. - * - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length); - - /** - * @brief Send silence to the voice channel - * - * @param duration How long to send silence for. With the standard - * timescale this is in milliseconds. Allowed values are 2.5, - * 5, 10, 20, 40 or 60 milliseconds. - * @return discord_voice_client& Reference to self - * @throw dpp::voice_exception if voice support is not compiled into D++ - */ - discord_voice_client& send_silence(const uint64_t duration); - - /** - * @brief Sets the audio type that will be sent with send_audio_* methods. - * - * @see send_audio_type_t - */ - discord_voice_client& set_send_audio_type(send_audio_type_t type); - - /** - * @brief Set the timescale in nanoseconds. - * - * @param new_timescale Timescale to set. This defaults to 1000000, - * which means 1 millisecond. - * @return discord_voice_client& Reference to self - * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ - */ - discord_voice_client& set_timescale(uint64_t new_timescale); - - /** - * @brief Get the current timescale, this will default to 1000000 - * which means 1 millisecond. - * - * @return uint64_t timescale in nanoseconds - */ - uint64_t get_timescale(); - - /** - * @brief Mark the voice connection as 'speaking'. - * This sends a JSON message to the voice websocket which tells discord - * that the user is speaking. The library automatically calls this for you - * whenever you send audio. - * - * @return discord_voice_client& Reference to self - */ - discord_voice_client& speak(); - - /** - * @brief Pause sending of audio - * - * @param pause True to pause, false to resume - * @return reference to self - */ - discord_voice_client& pause_audio(bool pause); - - /** - * @brief Immediately stop all audio. - * Clears the packet queue. - * @return reference to self - */ - discord_voice_client& stop_audio(); - - /** - * @brief Returns true if we are playing audio - * - * @return true if audio is playing - */ - bool is_playing(); - - /** - * @brief Get the number of seconds remaining - * of the audio output buffer - * - * @return float number of seconds remaining - */ - float get_secs_remaining(); - - /** - * @brief Get the number of tracks remaining - * in the output buffer. - * This is calculated by the number of track - * markers plus one. - * @return uint32_t Number of tracks in the - * buffer - */ - uint32_t get_tracks_remaining(); - - /** - * @brief Get the time remaining to send the - * audio output buffer in hours:minutes:seconds - * - * @return dpp::utility::uptime length of buffer - */ - dpp::utility::uptime get_remaining(); - - /** - * @brief Insert a track marker into the audio - * output buffer. - * A track marker is an arbitrary flag in the - * buffer contents that indicates the end of some - * block of audio of significance to the sender. - * This may be a song from a streaming site, or - * some voice audio/speech, a sound effect, or - * whatever you choose. You can later skip - * to the next marker using the - * dpp::discord_voice_client::skip_to_next_marker - * function. - * @param metadata Arbitrary information related to this - * track - * @return reference to self - */ - discord_voice_client& insert_marker(const std::string& metadata = ""); - - /** - * @brief Skip tp the next track marker, - * previously inserted by using the - * dpp::discord_voice_client::insert_marker - * function. If there are no markers in the - * output buffer, then this skips to the end - * of the buffer and is equivalent to the - * dpp::discord_voice_client::stop_audio - * function. - * @note It is possible to use this function - * while the output stream is paused. - * @return reference to self - */ - discord_voice_client& skip_to_next_marker(); - - /** - * @brief Get the metadata string associated with each inserted marker. - * - * @return const std::vector& list of metadata strings - */ - const std::vector get_marker_metadata(); - - /** - * @brief Returns true if the audio is paused. - * You can unpause with - * dpp::discord_voice_client::pause_audio. - * - * @return true if paused - */ - bool is_paused(); - - /** - * @brief Discord external IP detection. - * @return std::string Your external IP address - * @note This is a blocking operation that waits - * for a single packet from Discord's voice servers. - */ - std::string discover_ip(); -}; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +struct OpusDecoder; +struct OpusEncoder; +struct OpusRepacketizer; + +namespace dpp { + +// Forward declaration +class cluster; + +/** + * @brief An opus-encoded RTP packet to be sent out to a voice channel + */ +struct DPP_EXPORT voice_out_packet { + /** + * @brief Each string is a UDP packet. + * Generally these will be RTP. + */ + std::string packet; + /** + * @brief Duration of packet + */ + uint64_t duration; +}; + +#define AUDIO_TRACK_MARKER (uint16_t)0xFFFF + +#define AUDIO_OVERLAP_SLEEP_SAMPLES 30 + +/** @brief Implements a discord voice connection. + * Each discord_voice_client connects to one voice channel and derives from a websocket client. + */ +class DPP_EXPORT discord_voice_client : public websocket_client +{ + /** + * @brief Mutex for outbound packet stream + */ + std::mutex stream_mutex; + + /** + * @brief Mutex for message queue + */ + std::shared_mutex queue_mutex; + + /** + * @brief Queue of outbound messages + */ + std::deque message_queue; + + /** + * @brief Thread this connection is executing on + */ + std::thread* runner; + + /** + * @brief Run shard loop under a thread + */ + void thread_run(); + + /** + * @brief Last connect time of voice session + */ + time_t connect_time; + + /** + * @brief IP of UDP/RTP endpoint + */ + std::string ip; + + /** + * @brief Port number of UDP/RTP endpoint + */ + uint16_t port; + + /** + * @brief SSRC value + */ + uint64_t ssrc; + + /** + * @brief List of supported audio encoding modes + */ + std::vector modes; + + /** + * @brief Timescale in nanoseconds + */ + uint64_t timescale; + + /** + * @brief Output buffer + */ + std::vector outbuf; + + /** + * @brief Data type of RTP packet sequence number field. + */ + using rtp_seq_t = uint16_t; + using rtp_timestamp_t = uint32_t; + + /** + * @brief Keeps track of the voice payload to deliver to voice handlers. + */ + struct voice_payload { + /** + * @brief The sequence number of the RTP packet that generated this + * voice payload. + */ + rtp_seq_t seq; + /** + * @brief The timestamp of the RTP packet that generated this voice + * payload. + * + * The timestamp is used to detect the order around where sequence + * number wraps around. + */ + rtp_timestamp_t timestamp; + /** + * @brief The event payload that voice handlers receive. + */ + std::unique_ptr vr; + + /** + * @brief For priority_queue sorting. + * @return true if "this" has lower priority that "other", + * i.e. appears later in the queue; false otherwise. + */ + bool operator<(const voice_payload& other) const; + }; + + struct voice_payload_parking_lot { + /** + * @brief The range of RTP packet sequence number and timestamp in the lot. + * + * The minimum is used to drop packets that arrive too late. Packets + * less than the minimum have been delivered to voice handlers and + * there is no going back. Unfortunately we just have to drop them. + * + * The maximum is used, at flush time, to calculate the minimum for + * the next batch. The maximum is also updated every time we receive an + * RTP packet with a larger value. + */ + struct seq_range_t { + rtp_seq_t min_seq, max_seq; + rtp_timestamp_t min_timestamp, max_timestamp; + } range; + /** + * @brief The queue of parked voice payloads. + * + * We group payloads and deliver them to handlers periodically as the + * handling of out-of-order RTP packets. Payloads in between flushes + * are parked and sorted in this queue. + */ + std::priority_queue parked_payloads; + /** + * @brief The decoder ctls to be set on the decoder. + */ + std::vector> pending_decoder_ctls; + /** + * @brief libopus decoder + * + * Shared with the voice courier thread that does the decoding. + * This is not protected by a mutex because only the courier thread + * uses the decoder. + */ + std::shared_ptr decoder; + }; + /** + * @brief Thread used to deliver incoming voice data to handlers. + */ + std::thread voice_courier; + /** + * @brief Shared state between this voice client and the courier thread. + */ + struct courier_shared_state_t { + /** + * @brief Protects all following members. + */ + std::mutex mtx; + /** + * @brief Signaled when there is a new payload to deliver or terminating state has changed. + */ + std::condition_variable signal_iteration; + /** + * @brief Voice buffers to be reported to handler, grouped by speaker. + * + * Buffers are parked here and flushed every 500ms. + */ + std::map parked_voice_payloads; + /** + * @brief Used to signal termination. + * + * @note Pending payloads are delivered first before termination. + */ + bool terminating = false; + } voice_courier_shared_state; + /** + * @brief The run loop of the voice courier thread. + */ + static void voice_courier_loop(discord_voice_client&, courier_shared_state_t&); + + /** + * @brief If true, audio packet sending is paused + */ + bool paused; + +#ifdef HAVE_VOICE + /** + * @brief libopus encoder + */ + OpusEncoder* encoder; + + /** + * @brief libopus repacketizer + * (merges frames into one packet) + */ + OpusRepacketizer* repacketizer; +#else + /** + * @brief libopus encoder + */ + void* encoder; + + /** + * @brief libopus repacketizer + * (merges frames into one packet) + */ + void* repacketizer; +#endif + + /** + * @brief File descriptor for UDP connection + */ + dpp::socket fd; + + /** + * @brief Secret key for encrypting voice. + * If it has been sent, this is non-null and points to a + * sequence of exactly 32 bytes. + */ + uint8_t* secret_key; + + /** + * @brief Sequence number of outbound audio. This is incremented + * once per frame sent. + */ + uint16_t sequence; + + /** + * @brief Timestamp value used in outbound audio. Each packet + * has the timestamp value which is incremented to match + * how many frames are sent. + */ + uint32_t timestamp; + + /** + * @brief Last sent packet high-resolution timestamp + */ + std::chrono::high_resolution_clock::time_point last_timestamp; + + /** + * @brief Fraction of the sleep that was not executed after the last audio packet was sent + */ + std::chrono::nanoseconds last_sleep_remainder; + + /** + * @brief Maps receiving ssrc to user id + */ + std::unordered_map ssrc_map; + + /** + * @brief This is set to true if we have started sending audio. + * When this moves from false to true, this causes the + * client to send the 'talking' notification to the websocket. + */ + bool sending; + + /** + * @brief Number of track markers in the buffer. For example if there + * are two track markers in the buffer there are 3 tracks. + * + * **Special case:** + * + * If the buffer is empty, there are zero tracks in the + * buffer. + */ + uint32_t tracks; + + /** + * @brief Meta data associated with each track. + * Arbitrary string that the user can set via + * dpp::discord_voice_client::add_marker + */ + std::vector track_meta; + + /** + * @brief Encoding buffer for opus repacketizer and encode + */ + uint8_t encode_buffer[65536]; + + /** + * @brief Send data to UDP socket immediately. + * + * @param data data to send + * @param length length of data to send + * @return int bytes sent. Will return -1 if we cannot send + */ + int udp_send(const char* data, size_t length); + + /** + * @brief Receive data from UDP socket immediately. + * + * @param data data to receive + * @param max_length size of data receiving buffer + * @return int bytes received. -1 if there is an error + * (e.g. EAGAIN) + */ + int udp_recv(char* data, size_t max_length); + + /** + * @brief This hooks the ssl_client, returning the file + * descriptor if we want to send buffered data, or + * -1 if there is nothing to send + * + * @return int file descriptor or -1 + */ + dpp::socket want_write(); + + /** + * @brief This hooks the ssl_client, returning the file + * descriptor if we want to receive buffered data, or + * -1 if we are not wanting to receive + * + * @return int file descriptor or -1 + */ + dpp::socket want_read(); + + /** + * @brief Called by ssl_client when the socket is ready + * for writing, at this point we pick the head item off + * the buffer and send it. So long as it doesn't error + * completely, we pop it off the head of the queue. + */ + void write_ready(); + + /** + * @brief Called by ssl_client when there is data to be + * read. At this point we insert that data into the + * input queue. + */ + void read_ready(); + + /** + * @brief Send data to the UDP socket, using the buffer. + * + * @param packet packet data + * @param len length of packet + * @param duration duration of opus packet + */ + void send(const char* packet, size_t len, uint64_t duration); + + /** + * @brief Queue a message to be sent via the websocket + * + * @param j The JSON data of the message to be sent + * @param to_front If set to true, will place the message at the front of the queue not the back + * (this is for urgent messages such as heartbeat, presence, so they can take precedence over + * chunk requests etc) + */ + void queue_message(const std::string &j, bool to_front = false); + + /** + * @brief Clear the outbound message queue + * + */ + void clear_queue(); + + /** + * @brief Get the size of the outbound message queue + * + * @return The size of the queue + */ + size_t get_queue_size(); + + /** + * @brief Encode a byte buffer using opus codec. + * Multiple opus frames (2880 bytes each) will be encoded into one packet for sending. + * + * @param input Input data as raw bytes of PCM data + * @param inDataSize Input data length + * @param output Output data as an opus encoded packet + * @param outDataSize Output data length, should be at least equal to the input size. + * Will be adjusted on return to the actual compressed data size. + * @return size_t The compressed data size that was encoded. + * @throw dpp::voice_exception If data length to encode is invalid or voice support not compiled into D++ + */ + size_t encode(uint8_t *input, size_t inDataSize, uint8_t *output, size_t &outDataSize); + +public: + + /** + * @brief Owning cluster + */ + class dpp::cluster* creator; + + /** + * @brief This needs to be static, we only initialise libsodium once per program start, + * so initialising it on first use in a voice connection is best. + */ + static bool sodium_initialised; + + /** + * @brief True when the thread is shutting down + */ + bool terminating; + + /** + * @brief Heartbeat interval for sending heartbeat keepalive + */ + uint32_t heartbeat_interval; + + /** + * @brief Last voice channel websocket heartbeat + */ + time_t last_heartbeat; + + /** + * @brief Thread ID + */ + std::thread::native_handle_type thread_id; + + /** + * @brief Discord voice session token + */ + std::string token; + + /** + * @brief Discord voice session id + */ + std::string sessionid; + + /** + * @brief Server ID + */ + snowflake server_id; + + /** + * @brief Channel ID + */ + snowflake channel_id; + + /** + * @brief The audio type to be sent. The default type is recorded audio. + * + * If the audio is recorded, the sending of audio packets is throttled. + * Otherwise, if the audio is live, the sending is not throttled. + * + * Discord voice engine is expecting audio data as if they were from + * some audio device, e.g. microphone, where the data become available + * as they get captured from the audio device. + * + * In case of recorded audio, unlike from a device, the audio data are + * usually instantly available in large chunks. Throttling is needed to + * simulate audio data coming from an audio device. In case of live audio, + * the throttling is by nature, so no extra throttling is needed. + * + * Using live audio mode for recorded audio can cause Discord to skip + * audio data because Discord does not expect to receive, say, 3 minutes' + * worth of audio data in 1 second. + * + * There are some inaccuracies in the throttling method used by the recorded + * audio mode on some systems (mainly Windows) which causes gaps and stutters + * in the resulting audio stream. The overlap audio mode provides a different + * implementation that fixes the issue. This method is slightly more CPU + * intensive, and should only be used if you encounter issues with recorded audio + * on your system. + * + * Use discord_voice_client::set_send_audio_type to change this value as + * it ensures thread safety. + */ + enum send_audio_type_t + { + satype_recorded_audio, + satype_live_audio, + satype_overlap_audio + } send_audio_type = satype_recorded_audio; + + /** + * @brief Sets the gain for the specified user. + * + * Similar to the User Volume slider, controls the listening volume per user. + * Uses native Opus gain control, so clients don't have to perform extra + * audio processing. + * + * The gain setting will affect the both individual and combined voice audio. + * + * The gain value can also be set even before the user connects to the voice + * channel. + * + * @param user_id The ID of the user where the gain is to be controlled. + * @param factor Nonnegative factor to scale the amplitude by, where 1.f reverts + * to the default volume. + */ + void set_user_gain(snowflake user_id, float factor); + + /** + * @brief Log a message to whatever log the user is using. + * The logged message is passed up the chain to the on_log event in user code which can then do whatever + * it wants to do with it. + * @param severity The log level from dpp::loglevel + * @param msg The log message to output + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; + + /** + * @brief Fires every second from the underlying socket I/O loop, used for sending heartbeats + * @throw dpp::exception if the socket needs to disconnect + */ + virtual void one_second_timer(); + + /** + * @brief voice client is ready to stream audio. + * The voice client is considered ready if it has a secret key. + * + * @return true if ready to stream audio + */ + bool is_ready(); + + /** + * @brief Returns true if the voice client is connected to the websocket + * + * @return True if connected + */ + bool is_connected(); + + /** + * @brief Returns the connection time of the voice client + * + * @return dpp::utility::uptime Detail of how long the voice client has been connected for + */ + dpp::utility::uptime get_uptime(); + + /** Constructor takes shard id, max shards and token. + * @param _cluster The cluster which owns this voice connection, for related logging, REST requests etc + * @param _channel_id The channel id to identify the voice connection as + * @param _server_id The server id (guild id) to identify the voice connection as + * @param _token The voice session token to use for identifying to the websocket + * @param _session_id The voice session id to identify with + * @param _host The voice server hostname to connect to (hostname:port format) + * @throw dpp::voice_exception Sodium or Opus failed to initialise, or D++ is not compiled with voice support + */ + discord_voice_client(dpp::cluster* _cluster, snowflake _channel_id, snowflake _server_id, const std::string &_token, const std::string &_session_id, const std::string &_host); + + /** + * @brief Destroy the discord voice client object + */ + virtual ~discord_voice_client(); + + /** + * @brief Handle JSON from the websocket. + * @param buffer The entire buffer content from the websocket client + * @return bool True if a frame has been handled + * @throw dpp::exception If there was an error processing the frame, or connection to UDP socket failed + */ + virtual bool handle_frame(const std::string &buffer); + + /** + * @brief Handle a websocket error. + * @param errorcode The error returned from the websocket + */ + virtual void error(uint32_t errorcode); + + /** + * @brief Start and monitor I/O loop + */ + void run(); + + /** + * @brief Send raw audio to the voice channel. + * + * You should send an audio packet of 11520 bytes. + * Note that this function can be costly as it has to opus encode + * the PCM audio on the fly, and also encrypt it with libsodium. + * + * @note Because this function encrypts and encodes packets before + * pushing them onto the output queue, if you have a complete stream + * ready to send and know its length it is advisable to call this + * method multiple times to enqueue the entire stream audio so that + * it is all encoded at once (unless you have set use_opus to false). + * Constantly calling this from the dpp::on_voice_buffer_send callback + * can and will eat a TON of cpu! + * + * @param audio_data Raw PCM audio data. Channels are interleaved, + * with each channel's amplitude being a 16 bit value. + * + * The audio data should be 48000Hz signed 16 bit audio. + * + * @param length The length of the audio data. The length should + * be a multiple of 4 (2x 16 bit stereo channels) with a maximum + * length of 11520, which is a complete opus frame at highest + * quality. + * + * @return discord_voice_client& Reference to self + * + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& send_audio_raw(uint16_t* audio_data, const size_t length); + + /** + * @brief Send opus packets to the voice channel + * + * Some containers such as .ogg may contain OPUS + * encoded data already. In this case, we don't need to encode the + * frames using opus here. We can bypass the codec, only applying + * libsodium to the stream. + * + * @param opus_packet Opus packets. Discord expects opus frames + * to be encoded at 48000Hz + * + * @param length The length of the audio data. + * + * @param duration Generally duration is 2.5, 5, 10, 20, 40 or 60 + * if the timescale is 1000000 (1ms) + * + * @return discord_voice_client& Reference to self + * + * @note It is your responsibility to ensure that packets of data + * sent to send_audio are correctly repacketized for streaming, + * e.g. that audio frames are not too large or contain + * an incorrect format. Discord will still expect the same frequency + * and bit width of audio and the same signedness. + * + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length, uint64_t duration); + + /** + * @brief Send opus packets to the voice channel + * + * Some containers such as .ogg may contain OPUS + * encoded data already. In this case, we don't need to encode the + * frames using opus here. We can bypass the codec, only applying + * libsodium to the stream. + * + * Duration is calculated internally + * + * @param opus_packet Opus packets. Discord expects opus frames + * to be encoded at 48000Hz + * + * @param length The length of the audio data. + * + * @return discord_voice_client& Reference to self + * + * @note It is your responsibility to ensure that packets of data + * sent to send_audio are correctly repacketized for streaming, + * e.g. that audio frames are not too large or contain + * an incorrect format. Discord will still expect the same frequency + * and bit width of audio and the same signedness. + * + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& send_audio_opus(uint8_t* opus_packet, const size_t length); + + /** + * @brief Send silence to the voice channel + * + * @param duration How long to send silence for. With the standard + * timescale this is in milliseconds. Allowed values are 2.5, + * 5, 10, 20, 40 or 60 milliseconds. + * @return discord_voice_client& Reference to self + * @throw dpp::voice_exception if voice support is not compiled into D++ + */ + discord_voice_client& send_silence(const uint64_t duration); + + /** + * @brief Sets the audio type that will be sent with send_audio_* methods. + * + * @see send_audio_type_t + */ + discord_voice_client& set_send_audio_type(send_audio_type_t type); + + /** + * @brief Set the timescale in nanoseconds. + * + * @param new_timescale Timescale to set. This defaults to 1000000, + * which means 1 millisecond. + * @return discord_voice_client& Reference to self + * @throw dpp::voice_exception If data length is invalid or voice support not compiled into D++ + */ + discord_voice_client& set_timescale(uint64_t new_timescale); + + /** + * @brief Get the current timescale, this will default to 1000000 + * which means 1 millisecond. + * + * @return uint64_t timescale in nanoseconds + */ + uint64_t get_timescale(); + + /** + * @brief Mark the voice connection as 'speaking'. + * This sends a JSON message to the voice websocket which tells discord + * that the user is speaking. The library automatically calls this for you + * whenever you send audio. + * + * @return discord_voice_client& Reference to self + */ + discord_voice_client& speak(); + + /** + * @brief Pause sending of audio + * + * @param pause True to pause, false to resume + * @return reference to self + */ + discord_voice_client& pause_audio(bool pause); + + /** + * @brief Immediately stop all audio. + * Clears the packet queue. + * @return reference to self + */ + discord_voice_client& stop_audio(); + + /** + * @brief Returns true if we are playing audio + * + * @return true if audio is playing + */ + bool is_playing(); + + /** + * @brief Get the number of seconds remaining + * of the audio output buffer + * + * @return float number of seconds remaining + */ + float get_secs_remaining(); + + /** + * @brief Get the number of tracks remaining + * in the output buffer. + * This is calculated by the number of track + * markers plus one. + * @return uint32_t Number of tracks in the + * buffer + */ + uint32_t get_tracks_remaining(); + + /** + * @brief Get the time remaining to send the + * audio output buffer in hours:minutes:seconds + * + * @return dpp::utility::uptime length of buffer + */ + dpp::utility::uptime get_remaining(); + + /** + * @brief Insert a track marker into the audio + * output buffer. + * A track marker is an arbitrary flag in the + * buffer contents that indicates the end of some + * block of audio of significance to the sender. + * This may be a song from a streaming site, or + * some voice audio/speech, a sound effect, or + * whatever you choose. You can later skip + * to the next marker using the + * dpp::discord_voice_client::skip_to_next_marker + * function. + * @param metadata Arbitrary information related to this + * track + * @return reference to self + */ + discord_voice_client& insert_marker(const std::string& metadata = ""); + + /** + * @brief Skip tp the next track marker, + * previously inserted by using the + * dpp::discord_voice_client::insert_marker + * function. If there are no markers in the + * output buffer, then this skips to the end + * of the buffer and is equivalent to the + * dpp::discord_voice_client::stop_audio + * function. + * @note It is possible to use this function + * while the output stream is paused. + * @return reference to self + */ + discord_voice_client& skip_to_next_marker(); + + /** + * @brief Get the metadata string associated with each inserted marker. + * + * @return const std::vector& list of metadata strings + */ + const std::vector get_marker_metadata(); + + /** + * @brief Returns true if the audio is paused. + * You can unpause with + * dpp::discord_voice_client::pause_audio. + * + * @return true if paused + */ + bool is_paused(); + + /** + * @brief Discord external IP detection. + * @return std::string Your external IP address + * @note This is a blocking operation that waits + * for a single packet from Discord's voice servers. + */ + std::string discover_ip(); +}; + +}; + diff --git a/3rdParty/dpp/dispatcher.h b/3rdParty/dpp/dispatcher.h index 7f595dcd38..ed3a135ee7 100644 --- a/3rdParty/dpp/dispatcher.h +++ b/3rdParty/dpp/dispatcher.h @@ -1,1779 +1,1779 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/* Forward declaration */ -struct confirmation_callback_t; - -/** - * @brief A function used as a callback for any REST based command - */ -typedef std::function command_completion_event_t; - -/** @brief Base event parameter struct. - * Each event you receive from the library will have its parameter derived from this class. - * The class contains the raw event data, and a pointer to the current shard's dpp::discord_client object. - * You can also use this object to cancel the current event, meaning that any listeners after yours do - * not get notified of the current event if you call it. - */ -struct DPP_EXPORT event_dispatch_t { - /** - * @brief Raw event data. - * If you are using json on your websocket, this will contain json, and if you are using - * ETF as your websocket protocol, it will contain raw ETF data. - */ - const std::string raw_event; - - /** - * @brief Shard the event came from. - * Note that for some events, notably voice events, this may be nullptr. - */ - class discord_client* from; - - /** - * @brief Construct a new event_dispatch_t object - * - * @param client The shard the event originated on. May be a nullptr, e.g. for voice events - * @param raw Raw event data as JSON or ETF - */ - event_dispatch_t(class discord_client* client, const std::string& raw); - - /** - * @brief Cancels the event in progress. Any other attached lambdas for this event after this one are not called. - * Note that event cancellation is a thread local state, and not stored in the object (because object which can - * be cancelled is `const` during the event, and cannot itself contain the changeable state). - * @return const event_dispatch_t& reference to self for chaining - */ - const event_dispatch_t& cancel_event() const; - - /** - * @brief Returns true if the event is cancelled. - * Note that event cancellation is a thread local state, and not stored in the object (because object which can - * be cancelled is `const` during the event, and cannot itself contain the changeable state). - * @return true if the event is cancelled - */ - bool is_cancelled() const; -}; - -/** @brief Log messages */ -struct DPP_EXPORT log_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - log_t(class discord_client* client, const std::string& raw); - /** Severity */ - loglevel severity; - /** Log Message */ - std::string message; - - log_t(const log_t&) = default; -}; - -namespace utility { - /** - * @brief Get a default logger that outputs to std::cout. - * e.g. - * ``` - * bot.on_log(dpp::utility::cout_logger()); - * ``` - * - * @return A logger for attaching to on_log - */ - std::function DPP_EXPORT cout_logger(); - - /** - * @brief The default callback handler for API calls. - * on error, sends the error to the logger. - * - * @return A lambda for attaching to an API callback - */ - std::function DPP_EXPORT log_error(); -}; - -/** @brief Add user to scheduled event */ -struct DPP_EXPORT guild_scheduled_event_user_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_user_add_t(class discord_client* client, const std::string& raw); - /** - * @brief event user added to - */ - snowflake event_id; - - /** - * @brief User being added - * - */ - snowflake user_id; - - /** - * @brief Guild being added to - * - */ - snowflake guild_id; -}; - -/** @brief Delete user from scheduled event */ -struct DPP_EXPORT guild_scheduled_event_user_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_user_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief event user removed from - */ - snowflake event_id; - - /** - * @brief User being removed - * - */ - snowflake user_id; - - /** - * @brief Guild being removed from - * - */ - snowflake guild_id; -}; - -/** @brief Create scheduled event */ -struct DPP_EXPORT guild_scheduled_event_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created event - */ - scheduled_event created; -}; - -/** @brief Create scheduled event */ -struct DPP_EXPORT guild_scheduled_event_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - scheduled_event updated; -}; - -/** @brief Delete scheduled event */ -struct DPP_EXPORT guild_scheduled_event_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - guild_scheduled_event_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief deleted event - */ - scheduled_event deleted; -}; - -/** @brief Create automod rule */ -struct DPP_EXPORT automod_rule_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_create_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - automod_rule created; -}; - -/** @brief Update automod rule */ -struct DPP_EXPORT automod_rule_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - automod_rule updated; -}; - -/** @brief Delete automod rule */ -struct DPP_EXPORT automod_rule_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief updated event - */ - automod_rule deleted; -}; - -/** @brief Execute/trigger automod rule */ -struct DPP_EXPORT automod_rule_execute_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - automod_rule_execute_t(class discord_client* client, const std::string& raw); - - snowflake guild_id; //!< the id of the guild in which action was executed - automod_action action; //!< the action which was executed - snowflake rule_id; //!< the id of the rule which action belongs to - automod_trigger_type rule_trigger_type; //!< the trigger type of rule which was triggered - snowflake user_id; //!< the id of the user which generated the content which triggered the rule - snowflake channel_id; //!< Optional: the id of the channel in which user content was posted - snowflake message_id; //!< Optional: the id of any user message which content belongs to - snowflake alert_system_message_id; //!< Optional: the id of any system auto moderation messages posted as a result of this action - std::string content; //!< the user generated text content - std::string matched_keyword; //!< the word or phrase configured in the rule that triggered the rule (may be empty) - std::string matched_content; //!< the substring in content that triggered the rule (may be empty) -}; - - - -/** @brief Create stage instance */ -struct DPP_EXPORT stage_instance_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - stage_instance_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created stage instance - */ - stage_instance created; -}; - -/** @brief Update stage instance */ -struct DPP_EXPORT stage_instance_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - stage_instance_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated stage instance - */ - stage_instance updated; -}; - -/** @brief Delete stage instance */ -struct DPP_EXPORT stage_instance_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. CAN BE NULL - * for log events originating from the cluster object - * @param raw Raw event text as JSON - */ - stage_instance_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief deleted stage instance - */ - stage_instance deleted; -}; - -/** @brief Voice state update */ -struct DPP_EXPORT voice_state_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - voice_state_update_t(class discord_client* client, const std::string& raw); - /** Voice state */ - voicestate state; -}; - -/** - * @brief Create interaction - */ -struct DPP_EXPORT interaction_create_t : public event_dispatch_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - interaction_create_t(class discord_client* client, const std::string& raw); - - - /** - * @brief Acknowledge interaction without displaying a message to the user, - * for use with button and select menu components. - * - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction - * - * @param t Type of reply to send - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(interaction_response_type t, const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction - * - * @param t Type of reply to send - * @param mt The string value to send, for simple text only messages - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(interaction_response_type t, const std::string & mt, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction. - * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. - * - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Send a reply for this interaction. - * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. - * - * @param mt The string value to send, for simple text only messages - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void reply(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Reply to interaction with a dialog box - * - * @param mr Dialog box response to send - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void dialog(const interaction_modal_response& mr, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Edit the response for this interaction - * - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_response(const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Edit the response for this interaction - * - * @param mt The string value to send, for simple text only messages - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_response(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Set the bot to 'thinking' state - * - * @param ephemeral True if the thinking state should be ephemeral - * @param callback User function to execute when the api call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void thinking(bool ephemeral = false, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Get original response message for this interaction - * - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void get_original_response(command_completion_event_t callback) const; - - /** - * @brief Edit original response message for this interaction - * - * @param m Message object to send. Not all fields are supported by Discord. - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void edit_original_response(const message & m, command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Delete original response message for this interaction. This cannot be used on an ephemeral interaction response. - * - * @param callback Function to call when the API call completes. - * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). - */ - void delete_original_response(command_completion_event_t callback = utility::log_error()) const; - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return const command_value& If the command line parameter does not - * exist, an empty variant is returned. - */ - const virtual command_value& get_parameter(const std::string& name) const; - - /** - * @brief command interaction - */ - interaction command; - - /** - * @brief Destroy this object - */ - virtual ~interaction_create_t() = default; -}; - -/** - * @brief User has issued a slash command - */ -struct DPP_EXPORT slashcommand_t : public interaction_create_t { -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - slashcommand_t(class discord_client* client, const std::string& raw); -}; - -/** - * @brief Click on button - */ -struct DPP_EXPORT button_click_t : public interaction_create_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - button_click_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as buttons dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - /** - * @brief button custom id - */ - std::string custom_id; - /** - * @brief component type - */ - uint8_t component_type; -}; - -struct DPP_EXPORT form_submit_t : public interaction_create_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - form_submit_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as buttons dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - /** - * @brief button custom id - */ - std::string custom_id; - /** - * @brief Message components for form reply - */ - std::vector components; -}; - -/** - * @brief Discord requests that we fill a list of auto completion choices for a command option - */ -struct DPP_EXPORT autocomplete_t : public interaction_create_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - autocomplete_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as auto complete requests dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - - /** - * @brief Command ID - */ - dpp::snowflake id; - - /** - * @brief Command name - */ - std::string name; - - /** - * @brief auto completion options - */ - std::vector options; -}; - -/** - * @brief Base class for context menu interactions, e.g. right click on - * user or message. - */ -struct DPP_EXPORT context_menu_t : public interaction_create_t { -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - context_menu_t(class discord_client* client, const std::string& raw); -}; - -/** - * @brief Event parameter for context menu interactions for messages - */ -struct DPP_EXPORT message_context_menu_t : public context_menu_t { - - /** - * @brief Related message - */ - message ctx_message; -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_context_menu_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get the message which was right-clicked on - * - * @return message right-clicked on - */ - message get_message() const; - - /** - * @brief Set the message object for this event - * - * @param m message to set - * @return message_context_menu_t& reference to self for fluent chaining - */ - message_context_menu_t& set_message(const message& m); -}; - -/** - * @brief Event parameter for context menu interactions for users - */ -struct DPP_EXPORT user_context_menu_t : public context_menu_t { - - /** - * @brief Related user - */ - user ctx_user; -public: - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - user_context_menu_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get the user which was right-clicked on - * - * @return user right clicked on - */ - user get_user() const; - - /** - * @brief Set the user object for this event - * - * @param u user to set - * @return user_context_menu_t& reference to self for fluent chaining - */ - user_context_menu_t& set_user(const user& u); - -}; - -/** - * @brief Click on select - */ -struct DPP_EXPORT select_click_t : public interaction_create_t { - - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - select_click_t(class discord_client* client, const std::string& raw); - - /** - * @brief Get a command line parameter - * - * @param name The command line parameter to retrieve - * @return Always returns an empty parameter as buttons dont have parameters! - */ - const virtual command_value& get_parameter(const std::string& name) const; - - /** - * @brief select menu custom id - */ - std::string custom_id; - /** - * @brief select menu values - */ - std::vector values; - /** - * @brief select menu component type (dpp::component_type) - */ - uint8_t component_type; -}; - - -/** @brief Delete guild */ -struct DPP_EXPORT guild_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_delete_t(class discord_client* client, const std::string& raw); - /** Deleted guild */ - guild* deleted; -}; - -/** @brief Update guild stickers */ -struct DPP_EXPORT guild_stickers_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_stickers_update_t(class discord_client* client, const std::string& raw); - /** Updating guild */ - guild* updating_guild; - /** - * @brief stickers being updated - */ - std::vector stickers; -}; - -/** @brief Guild join request delete (user declined membership screening) */ -struct DPP_EXPORT guild_join_request_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_join_request_delete_t(class discord_client* client, const std::string& raw); - /** Deleted guild */ - snowflake guild_id; - /** - * @brief user id - */ - snowflake user_id; -}; - -/** @brief Delete channel */ -struct DPP_EXPORT channel_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief guild channel is being deleted from - */ - guild* deleting_guild; - /** - * @brief channel being deleted - */ - channel* deleted; -}; - -/** @brief Update channel */ -struct DPP_EXPORT channel_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild channel is being updated on - */ - guild* updating_guild; - /** - * @brief channel being updated - */ - channel* updated; -}; - -/** @brief Session ready */ -struct DPP_EXPORT ready_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - ready_t(class discord_client* client, const std::string& raw); - /** - * @brief websocket session id - */ - std::string session_id; - /** - * @brief shard id - */ - uint32_t shard_id; -}; - -/** @brief Message Deleted */ -struct DPP_EXPORT message_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief message being deleted - */ - message* deleted; -}; - -/** @brief Guild member remove */ -struct DPP_EXPORT guild_member_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_member_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief guild user is being removed from - */ - guild* removing_guild; - /** - * @brief user being removed - */ - user* removed; -}; - -/** @brief Session resumed */ -struct DPP_EXPORT resumed_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - resumed_t(class discord_client* client, const std::string& raw); - /** - * @brief websocket session id - */ - std::string session_id; - /** - * @brief shard id - */ - uint32_t shard_id; -}; - -/** @brief Guild role create */ -struct DPP_EXPORT guild_role_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_role_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild role is being created on - */ - guild* creating_guild; - /** - * @brief role being created - */ - role* created; -}; - -/** @brief Typing start */ -struct DPP_EXPORT typing_start_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - typing_start_t(class discord_client* client, const std::string& raw); - /** - * @brief guild user is typing on - */ - guild* typing_guild; - /** - * @brief channel user is typing on - */ - channel* typing_channel; - /** - * @brief user who is typing. - * Can be nullptr if user is not cached - */ - user* typing_user; - /** - * @brief User id of user typing. - * Always set regardless of caching - */ - snowflake user_id; - /** - * @brief Time of typing event - */ - time_t timestamp; -}; - -/** @brief Voice state update */ -struct DPP_EXPORT voice_track_marker_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on. - * Will always be null. - * @param raw Raw event text as JSON. - * Will always be empty. - */ - voice_track_marker_t(class discord_client* client, const std::string& raw); - /** Voice client */ - class discord_voice_client* voice_client; - /** Track metadata */ - std::string track_meta; -}; - - -/** @brief Message reaction add */ -struct DPP_EXPORT message_reaction_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_add_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief User who reacted - */ - user reacting_user; - /** - * @brief member data of user who reacted - */ - guild_member reacting_member; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief emoji of reaction - */ - emoji reacting_emoji; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; -}; - -/** @brief Guild members chunk */ -struct DPP_EXPORT guild_members_chunk_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_members_chunk_t(class discord_client* client, const std::string& raw); - /** - * @brief guild the members chunk is for - */ - guild* adding; - /** - * @brief list of members in the chunk - */ - guild_member_map* members; -}; - -/** @brief Message reaction remove */ -struct DPP_EXPORT message_reaction_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief User who reacted - */ - dpp::snowflake reacting_user_id; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief emoji of reaction - */ - emoji reacting_emoji; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; -}; - -/** @brief Create guild */ -struct DPP_EXPORT guild_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild that was created - */ - guild* created; - /** - * @brief List of presences of all users on the guild. - * - * This is only filled if you have the GUILD_PRESENCES - * privileged intent. - */ - presence_map presences; - /** - * @brief List of scheduled events in the guild - */ - scheduled_event_map scheduled_events; - /** - * @brief List of stage instances in the guild - */ - stage_instance_map stage_instances; - /** - * @brief List of threads in the guild - */ - thread_map threads; - /** - * @brief List of stickers in the guild - */ - sticker_map stickers; -}; - -/** @brief Create channel */ -struct DPP_EXPORT channel_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild channel was created on - */ - guild* creating_guild; - /** - * @brief channel that was created - */ - channel* created; -}; - -/** @brief Message remove emoji */ -struct DPP_EXPORT message_reaction_remove_emoji_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_remove_emoji_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief emoji of reaction - */ - emoji reacting_emoji; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; -}; - -/** @brief Message delete bulk */ -struct DPP_EXPORT message_delete_bulk_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_delete_bulk_t(class discord_client* client, const std::string& raw); - /** - * @brief guild messages are being deleted upon - */ - guild* deleting_guild; - /** - * @brief user who is deleting the messages - */ - user* deleting_user; - /** - * @brief channel messages are being deleted from - */ - channel* deleting_channel; - /** - * @brief list of message ids of deleted messages - */ - std::vector deleted; -}; - -/** @brief Guild role update */ -struct DPP_EXPORT guild_role_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_role_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where roles are being updated - */ - guild* updating_guild; - /** - * @brief the role being updated - */ - role* updated; -}; - -/** @brief Guild role delete */ -struct DPP_EXPORT guild_role_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_role_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where role is being deleted - */ - guild* deleting_guild; - /** - * @brief role being deleted - */ - role* deleted; - /** - * @brief ID of the deleted role - */ - snowflake role_id; -}; - -/** @brief Channel pins update */ -struct DPP_EXPORT channel_pins_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - channel_pins_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where message is being pinned - */ - guild* pin_guild; - /** - * @brief channel where message is being pinned - */ - channel* pin_channel; - /** - * @brief timestamp of pin - */ - time_t timestamp; -}; - -/** @brief Message remove all reactions */ -struct DPP_EXPORT message_reaction_remove_all_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_reaction_remove_all_t(class discord_client* client, const std::string& raw); - /** - * @brief Guild reaction occurred on - */ - guild* reacting_guild; - /** - * @brief channel the reaction happened on - */ - channel* reacting_channel; - /** - * @brief message id of the message reacted upon - */ - snowflake message_id; - -}; - -/** @brief Voice server update */ -struct DPP_EXPORT voice_server_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - voice_server_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild id where voice server updated - */ - snowflake guild_id; - /** - * @brief voice server token, used to connect to vc - */ - std::string token; - /** - * @brief voice server endpoint wss:// address - * - */ - std::string endpoint; -}; - -/** @brief Guild emojis update */ -struct DPP_EXPORT guild_emojis_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_emojis_update_t(class discord_client* client, const std::string& raw); - /** - * @brief snowflake ids of list of emojis - */ - std::vector emojis; - /** - * @brief guild where emojis are being updated - */ - guild* updating_guild; -}; - -/** - * @brief Presence update - * - */ -struct DPP_EXPORT presence_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - presence_update_t(class discord_client* client, const std::string& raw); - /** - * @brief rich presence being updated - */ - presence rich_presence; -}; - -/** @brief Webhooks update */ -struct DPP_EXPORT webhooks_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - webhooks_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where webhooks are being updated - */ - guild* webhook_guild; - /** - * @brief channel where webhooks are being updated - */ - channel* webhook_channel; -}; - -/** @brief Guild member add */ -struct DPP_EXPORT guild_member_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_member_add_t(class discord_client* client, const std::string& raw); - /** - * @brief guild which gained new member - */ - guild* adding_guild; - /** - * @brief member which was added - */ - guild_member added; -}; - -/** @brief Invite delete */ -struct DPP_EXPORT invite_delete_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - invite_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief the deleted invite - */ - invite deleted_invite; -}; - -/** @brief Guild update */ -struct DPP_EXPORT guild_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild being updated - */ - guild* updated; -}; - -/** @brief Guild integrations update */ -struct DPP_EXPORT guild_integrations_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_integrations_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where integrations are being updated - */ - guild* updating_guild; -}; - -/** @brief Guild member update */ -struct DPP_EXPORT guild_member_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_member_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where member is being updated - */ - guild* updating_guild; - /** - * @brief member being updated - */ - guild_member updated; -}; - -/** @brief Invite create */ -struct DPP_EXPORT invite_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - invite_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created invite - */ - invite created_invite; -}; - -/** @brief Message update */ -struct DPP_EXPORT message_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_update_t(class discord_client* client, const std::string& raw); - /** - * @brief message being updated - */ - message msg; -}; - -/** @brief User update */ -struct DPP_EXPORT user_update_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - user_update_t(class discord_client* client, const std::string& raw); - /** - * @brief user being updated - */ - user updated; -}; - -/** @brief Create message */ -struct DPP_EXPORT message_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - message_create_t(class discord_client* client, const std::string& raw); - /** - * @brief message that was created (sent). - */ - message msg; - /** - * @brief Send a text to the same channel as the channel_id in received event. - * @param m Text to send - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void send(const std::string& m, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Send a message to the same channel as the channel_id in received event. - * @param msg Message to send - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void send(message& msg, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Send a message to the same channel as the channel_id in received event. - * @param msg Message to send - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void send(message&& msg, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Reply to the message received in the event. - * @param m Text to send - * @param mention_replied_user mentions (pings) the author of message replied to, if true - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void reply(const std::string& m, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Reply to the message received in the event. - * @param msg Message to send as a reply. - * @param mention_replied_user mentions (pings) the author of message replied to, if true - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void reply(message& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; - /** - * @brief Reply to the message received in the event. - * @param msg Message to send as a reply. - * @param mention_replied_user mentions (pings) the author of message replied to, if true - * @param callback User function to execute once the API call completes. - * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. - */ - void reply(message&& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; -}; - -/** @brief Guild ban add */ -struct DPP_EXPORT guild_ban_add_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_ban_add_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where ban was added - */ - guild* banning_guild; - /** - * @brief user being banned - */ - user banned; -}; - -/** @brief Guild ban remove */ -struct DPP_EXPORT guild_ban_remove_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - guild_ban_remove_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where ban is being removed - */ - guild* unbanning_guild; - /** - * @brief user being unbanned - */ - user unbanned; -}; - -/** @brief Integration create */ -struct DPP_EXPORT integration_create_t : public event_dispatch_t { - /** Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - integration_create_t(class discord_client* client, const std::string& raw); - /** - * @brief created integration - */ - integration created_integration; -}; - -/** @brief Integration update */ -struct DPP_EXPORT integration_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - integration_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated integration - */ - integration updated_integration; -}; - -/** @brief Integration delete */ -struct DPP_EXPORT integration_delete_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - integration_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief deleted integration - */ - integration deleted_integration; -}; - -/** @brief Thread Create*/ -struct DPP_EXPORT thread_create_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_create_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread was created - */ - guild* creating_guild; - /** - * @brief thread created - */ - thread created; -}; - -/** @brief Thread Update -*/ -struct DPP_EXPORT thread_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_update_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread was updated - */ - guild* updating_guild; - /** - * @brief thread updated - */ - thread updated; -}; - -/** @brief Thread Delete - */ -struct DPP_EXPORT thread_delete_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_delete_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread was deleted - */ - guild* deleting_guild; - /** - * @brief thread deleted - */ - thread deleted; -}; - -/** @brief Thread List Sync - */ -struct DPP_EXPORT thread_list_sync_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_list_sync_t(class discord_client* client, const std::string& raw); - /** - * @brief guild where thread list was synchronised - */ - guild* updating_guild; - /** - * @brief list of threads (channels) synchronised - */ - std::vector threads; - /** - * @brief list of thread members for the channels (threads) - */ - std::vector members; -}; - -/** @brief Thread Member Update - */ -struct DPP_EXPORT thread_member_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_member_update_t(class discord_client* client, const std::string& raw); - /** - * @brief updated thread member - */ - thread_member updated; -}; - -/** @brief Thread Members Update - */ -struct DPP_EXPORT thread_members_update_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * @param raw Raw event text as JSON - */ - thread_members_update_t(class discord_client* client, const std::string& raw); - /** - * @brief thread (channel) id - */ - snowflake thread_id; - /** - * @brief guild thread members updated on - */ - guild* updating_guild; - /** - * @brief new approximate member count - */ - uint8_t member_count; - /** - * @brief added members - */ - std::vector added; - /** - * @brief ids only of removed members - */ - std::vector removed_ids; -}; - -/** @brief voice buffer send - */ -struct DPP_EXPORT voice_buffer_send_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_buffer_send_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where buffer was sent - */ - class discord_voice_client* voice_client; - /** - * @brief encoded size of sent buffer - */ - int buffer_size; -}; - -/** @brief voice user talking */ -struct DPP_EXPORT voice_user_talking_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_user_talking_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where user is talking - */ - class discord_voice_client* voice_client; - /** - * @brief talking user id - */ - snowflake user_id; - /** - * @brief flags for talking user - */ - uint8_t talking_flags; -}; - -/** @brief voice user talking */ -struct DPP_EXPORT voice_ready_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_ready_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client which is ready - */ - class discord_voice_client* voice_client; - /** - * @brief id of voice channel - */ - snowflake voice_channel_id; -}; - -/** @brief voice receive packet */ -struct DPP_EXPORT voice_receive_t : public event_dispatch_t { - -friend class discord_voice_client; - - /** - * @brief Constructor - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as UDP packet. - */ - voice_receive_t(class discord_client* client, const std::string &raw); - /** - * @brief Construct a new voice receive t object - * - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as UDP packet. - * @param vc owning voice client pointer - * @param _user_id user id who is speaking, 0 for a mix of all user audio - * @param pcm user audio to set - * @param length length of user audio in bytes - */ - voice_receive_t(class discord_client* client, const std::string &raw, class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); - /** - * @brief Voice client - */ - class discord_voice_client* voice_client; - /** - * @brief Audio data, encoded as 48kHz stereo PCM or Opus, - * @deprecated Please switch to using audio_data. - */ - uint8_t* audio = nullptr; - /** - * @brief Size of audio buffer - * @deprecated Please switch to using audio_data. - */ - size_t audio_size = 0; - /** - * @brief Audio data, encoded as 48kHz stereo PCM or Opus, - */ - std::basic_string audio_data; - /** - * @brief User ID of speaker (zero if unknown) - */ - snowflake user_id; -protected: - /** - * @brief Reassign values outside of the constructor for use within discord_voice_client - * - * @param vc owning voice client pointer - * @param _user_id user id who is speaking, 0 for a mix of all user audio - * @param pcm user audio to set - * @param length length of user audio in bytes - */ - void reassign(class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); -}; - -/** @brief voice client speaking event */ -struct DPP_EXPORT voice_client_speaking_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_client_speaking_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where user is speaking - */ - class discord_voice_client* voice_client; - /** - * @brief speaking user id - * - */ - snowflake user_id; - /** - * @brief ssrc value of speaking user - */ - uint32_t ssrc; -}; - -/** @brief voice client disconnect event */ -struct DPP_EXPORT voice_client_disconnect_t : public event_dispatch_t { - /** - * @brief Constructor - * @param client The shard the event originated on. - * WILL ALWAYS be NULL. - * @param raw Raw event text as JSON - */ - voice_client_disconnect_t(class discord_client* client, const std::string &raw); - /** - * @brief voice client where user disconnected - */ - class discord_voice_client* voice_client; - /** - * @brief user id of user who left vc - */ - snowflake user_id; -}; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/* Forward declaration */ +struct confirmation_callback_t; + +/** + * @brief A function used as a callback for any REST based command + */ +typedef std::function command_completion_event_t; + +/** @brief Base event parameter struct. + * Each event you receive from the library will have its parameter derived from this class. + * The class contains the raw event data, and a pointer to the current shard's dpp::discord_client object. + * You can also use this object to cancel the current event, meaning that any listeners after yours do + * not get notified of the current event if you call it. + */ +struct DPP_EXPORT event_dispatch_t { + /** + * @brief Raw event data. + * If you are using json on your websocket, this will contain json, and if you are using + * ETF as your websocket protocol, it will contain raw ETF data. + */ + const std::string raw_event; + + /** + * @brief Shard the event came from. + * Note that for some events, notably voice events, this may be nullptr. + */ + class discord_client* from; + + /** + * @brief Construct a new event_dispatch_t object + * + * @param client The shard the event originated on. May be a nullptr, e.g. for voice events + * @param raw Raw event data as JSON or ETF + */ + event_dispatch_t(class discord_client* client, const std::string& raw); + + /** + * @brief Cancels the event in progress. Any other attached lambdas for this event after this one are not called. + * Note that event cancellation is a thread local state, and not stored in the object (because object which can + * be cancelled is `const` during the event, and cannot itself contain the changeable state). + * @return const event_dispatch_t& reference to self for chaining + */ + const event_dispatch_t& cancel_event() const; + + /** + * @brief Returns true if the event is cancelled. + * Note that event cancellation is a thread local state, and not stored in the object (because object which can + * be cancelled is `const` during the event, and cannot itself contain the changeable state). + * @return true if the event is cancelled + */ + bool is_cancelled() const; +}; + +/** @brief Log messages */ +struct DPP_EXPORT log_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + log_t(class discord_client* client, const std::string& raw); + /** Severity */ + loglevel severity; + /** Log Message */ + std::string message; + + log_t(const log_t&) = default; +}; + +namespace utility { + /** + * @brief Get a default logger that outputs to std::cout. + * e.g. + * ``` + * bot.on_log(dpp::utility::cout_logger()); + * ``` + * + * @return A logger for attaching to on_log + */ + std::function DPP_EXPORT cout_logger(); + + /** + * @brief The default callback handler for API calls. + * on error, sends the error to the logger. + * + * @return A lambda for attaching to an API callback + */ + std::function DPP_EXPORT log_error(); +}; + +/** @brief Add user to scheduled event */ +struct DPP_EXPORT guild_scheduled_event_user_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_user_add_t(class discord_client* client, const std::string& raw); + /** + * @brief event user added to + */ + snowflake event_id; + + /** + * @brief User being added + * + */ + snowflake user_id; + + /** + * @brief Guild being added to + * + */ + snowflake guild_id; +}; + +/** @brief Delete user from scheduled event */ +struct DPP_EXPORT guild_scheduled_event_user_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_user_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief event user removed from + */ + snowflake event_id; + + /** + * @brief User being removed + * + */ + snowflake user_id; + + /** + * @brief Guild being removed from + * + */ + snowflake guild_id; +}; + +/** @brief Create scheduled event */ +struct DPP_EXPORT guild_scheduled_event_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created event + */ + scheduled_event created; +}; + +/** @brief Create scheduled event */ +struct DPP_EXPORT guild_scheduled_event_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + scheduled_event updated; +}; + +/** @brief Delete scheduled event */ +struct DPP_EXPORT guild_scheduled_event_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + guild_scheduled_event_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief deleted event + */ + scheduled_event deleted; +}; + +/** @brief Create automod rule */ +struct DPP_EXPORT automod_rule_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_create_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + automod_rule created; +}; + +/** @brief Update automod rule */ +struct DPP_EXPORT automod_rule_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + automod_rule updated; +}; + +/** @brief Delete automod rule */ +struct DPP_EXPORT automod_rule_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief updated event + */ + automod_rule deleted; +}; + +/** @brief Execute/trigger automod rule */ +struct DPP_EXPORT automod_rule_execute_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + automod_rule_execute_t(class discord_client* client, const std::string& raw); + + snowflake guild_id; //!< the id of the guild in which action was executed + automod_action action; //!< the action which was executed + snowflake rule_id; //!< the id of the rule which action belongs to + automod_trigger_type rule_trigger_type; //!< the trigger type of rule which was triggered + snowflake user_id; //!< the id of the user which generated the content which triggered the rule + snowflake channel_id; //!< Optional: the id of the channel in which user content was posted + snowflake message_id; //!< Optional: the id of any user message which content belongs to + snowflake alert_system_message_id; //!< Optional: the id of any system auto moderation messages posted as a result of this action + std::string content; //!< the user generated text content + std::string matched_keyword; //!< the word or phrase configured in the rule that triggered the rule (may be empty) + std::string matched_content; //!< the substring in content that triggered the rule (may be empty) +}; + + + +/** @brief Create stage instance */ +struct DPP_EXPORT stage_instance_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created stage instance + */ + stage_instance created; +}; + +/** @brief Update stage instance */ +struct DPP_EXPORT stage_instance_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated stage instance + */ + stage_instance updated; +}; + +/** @brief Delete stage instance */ +struct DPP_EXPORT stage_instance_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. CAN BE NULL + * for log events originating from the cluster object + * @param raw Raw event text as JSON + */ + stage_instance_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief deleted stage instance + */ + stage_instance deleted; +}; + +/** @brief Voice state update */ +struct DPP_EXPORT voice_state_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + voice_state_update_t(class discord_client* client, const std::string& raw); + /** Voice state */ + voicestate state; +}; + +/** + * @brief Create interaction + */ +struct DPP_EXPORT interaction_create_t : public event_dispatch_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + interaction_create_t(class discord_client* client, const std::string& raw); + + + /** + * @brief Acknowledge interaction without displaying a message to the user, + * for use with button and select menu components. + * + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction + * + * @param t Type of reply to send + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(interaction_response_type t, const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction + * + * @param t Type of reply to send + * @param mt The string value to send, for simple text only messages + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(interaction_response_type t, const std::string & mt, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction. + * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. + * + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Send a reply for this interaction. + * Uses the default type of dpp::ir_channel_message_with_source, a simple message reply. + * + * @param mt The string value to send, for simple text only messages + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void reply(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Reply to interaction with a dialog box + * + * @param mr Dialog box response to send + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void dialog(const interaction_modal_response& mr, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Edit the response for this interaction + * + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_response(const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Edit the response for this interaction + * + * @param mt The string value to send, for simple text only messages + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_response(const std::string & mt, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Set the bot to 'thinking' state + * + * @param ephemeral True if the thinking state should be ephemeral + * @param callback User function to execute when the api call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void thinking(bool ephemeral = false, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Get original response message for this interaction + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void get_original_response(command_completion_event_t callback) const; + + /** + * @brief Edit original response message for this interaction + * + * @param m Message object to send. Not all fields are supported by Discord. + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::message object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void edit_original_response(const message & m, command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Delete original response message for this interaction. This cannot be used on an ephemeral interaction response. + * + * @param callback Function to call when the API call completes. + * On success the callback will contain a dpp::confirmation object in confirmation_callback_t::value. On failure, the value is undefined and confirmation_callback_t::is_error() method will return true. You can obtain full error details with confirmation_callback_t::get_error(). + */ + void delete_original_response(command_completion_event_t callback = utility::log_error()) const; + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return const command_value& If the command line parameter does not + * exist, an empty variant is returned. + */ + const virtual command_value& get_parameter(const std::string& name) const; + + /** + * @brief command interaction + */ + interaction command; + + /** + * @brief Destroy this object + */ + virtual ~interaction_create_t() = default; +}; + +/** + * @brief User has issued a slash command + */ +struct DPP_EXPORT slashcommand_t : public interaction_create_t { +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + slashcommand_t(class discord_client* client, const std::string& raw); +}; + +/** + * @brief Click on button + */ +struct DPP_EXPORT button_click_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + button_click_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + /** + * @brief button custom id + */ + std::string custom_id; + /** + * @brief component type + */ + uint8_t component_type; +}; + +struct DPP_EXPORT form_submit_t : public interaction_create_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + form_submit_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + /** + * @brief button custom id + */ + std::string custom_id; + /** + * @brief Message components for form reply + */ + std::vector components; +}; + +/** + * @brief Discord requests that we fill a list of auto completion choices for a command option + */ +struct DPP_EXPORT autocomplete_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + autocomplete_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as auto complete requests dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + + /** + * @brief Command ID + */ + dpp::snowflake id; + + /** + * @brief Command name + */ + std::string name; + + /** + * @brief auto completion options + */ + std::vector options; +}; + +/** + * @brief Base class for context menu interactions, e.g. right click on + * user or message. + */ +struct DPP_EXPORT context_menu_t : public interaction_create_t { +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + context_menu_t(class discord_client* client, const std::string& raw); +}; + +/** + * @brief Event parameter for context menu interactions for messages + */ +struct DPP_EXPORT message_context_menu_t : public context_menu_t { + + /** + * @brief Related message + */ + message ctx_message; +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_context_menu_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get the message which was right-clicked on + * + * @return message right-clicked on + */ + message get_message() const; + + /** + * @brief Set the message object for this event + * + * @param m message to set + * @return message_context_menu_t& reference to self for fluent chaining + */ + message_context_menu_t& set_message(const message& m); +}; + +/** + * @brief Event parameter for context menu interactions for users + */ +struct DPP_EXPORT user_context_menu_t : public context_menu_t { + + /** + * @brief Related user + */ + user ctx_user; +public: + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + user_context_menu_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get the user which was right-clicked on + * + * @return user right clicked on + */ + user get_user() const; + + /** + * @brief Set the user object for this event + * + * @param u user to set + * @return user_context_menu_t& reference to self for fluent chaining + */ + user_context_menu_t& set_user(const user& u); + +}; + +/** + * @brief Click on select + */ +struct DPP_EXPORT select_click_t : public interaction_create_t { + + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + select_click_t(class discord_client* client, const std::string& raw); + + /** + * @brief Get a command line parameter + * + * @param name The command line parameter to retrieve + * @return Always returns an empty parameter as buttons dont have parameters! + */ + const virtual command_value& get_parameter(const std::string& name) const; + + /** + * @brief select menu custom id + */ + std::string custom_id; + /** + * @brief select menu values + */ + std::vector values; + /** + * @brief select menu component type (dpp::component_type) + */ + uint8_t component_type; +}; + + +/** @brief Delete guild */ +struct DPP_EXPORT guild_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_delete_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + guild* deleted; +}; + +/** @brief Update guild stickers */ +struct DPP_EXPORT guild_stickers_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_stickers_update_t(class discord_client* client, const std::string& raw); + /** Updating guild */ + guild* updating_guild; + /** + * @brief stickers being updated + */ + std::vector stickers; +}; + +/** @brief Guild join request delete (user declined membership screening) */ +struct DPP_EXPORT guild_join_request_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_join_request_delete_t(class discord_client* client, const std::string& raw); + /** Deleted guild */ + snowflake guild_id; + /** + * @brief user id + */ + snowflake user_id; +}; + +/** @brief Delete channel */ +struct DPP_EXPORT channel_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief guild channel is being deleted from + */ + guild* deleting_guild; + /** + * @brief channel being deleted + */ + channel* deleted; +}; + +/** @brief Update channel */ +struct DPP_EXPORT channel_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild channel is being updated on + */ + guild* updating_guild; + /** + * @brief channel being updated + */ + channel* updated; +}; + +/** @brief Session ready */ +struct DPP_EXPORT ready_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + ready_t(class discord_client* client, const std::string& raw); + /** + * @brief websocket session id + */ + std::string session_id; + /** + * @brief shard id + */ + uint32_t shard_id; +}; + +/** @brief Message Deleted */ +struct DPP_EXPORT message_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief message being deleted + */ + message* deleted; +}; + +/** @brief Guild member remove */ +struct DPP_EXPORT guild_member_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief guild user is being removed from + */ + guild* removing_guild; + /** + * @brief user being removed + */ + user* removed; +}; + +/** @brief Session resumed */ +struct DPP_EXPORT resumed_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + resumed_t(class discord_client* client, const std::string& raw); + /** + * @brief websocket session id + */ + std::string session_id; + /** + * @brief shard id + */ + uint32_t shard_id; +}; + +/** @brief Guild role create */ +struct DPP_EXPORT guild_role_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild role is being created on + */ + guild* creating_guild; + /** + * @brief role being created + */ + role* created; +}; + +/** @brief Typing start */ +struct DPP_EXPORT typing_start_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + typing_start_t(class discord_client* client, const std::string& raw); + /** + * @brief guild user is typing on + */ + guild* typing_guild; + /** + * @brief channel user is typing on + */ + channel* typing_channel; + /** + * @brief user who is typing. + * Can be nullptr if user is not cached + */ + user* typing_user; + /** + * @brief User id of user typing. + * Always set regardless of caching + */ + snowflake user_id; + /** + * @brief Time of typing event + */ + time_t timestamp; +}; + +/** @brief Voice state update */ +struct DPP_EXPORT voice_track_marker_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on. + * Will always be null. + * @param raw Raw event text as JSON. + * Will always be empty. + */ + voice_track_marker_t(class discord_client* client, const std::string& raw); + /** Voice client */ + class discord_voice_client* voice_client; + /** Track metadata */ + std::string track_meta; +}; + + +/** @brief Message reaction add */ +struct DPP_EXPORT message_reaction_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_add_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief User who reacted + */ + user reacting_user; + /** + * @brief member data of user who reacted + */ + guild_member reacting_member; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief emoji of reaction + */ + emoji reacting_emoji; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; +}; + +/** @brief Guild members chunk */ +struct DPP_EXPORT guild_members_chunk_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_members_chunk_t(class discord_client* client, const std::string& raw); + /** + * @brief guild the members chunk is for + */ + guild* adding; + /** + * @brief list of members in the chunk + */ + guild_member_map* members; +}; + +/** @brief Message reaction remove */ +struct DPP_EXPORT message_reaction_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief User who reacted + */ + dpp::snowflake reacting_user_id; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief emoji of reaction + */ + emoji reacting_emoji; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; +}; + +/** @brief Create guild */ +struct DPP_EXPORT guild_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild that was created + */ + guild* created; + /** + * @brief List of presences of all users on the guild. + * + * This is only filled if you have the GUILD_PRESENCES + * privileged intent. + */ + presence_map presences; + /** + * @brief List of scheduled events in the guild + */ + scheduled_event_map scheduled_events; + /** + * @brief List of stage instances in the guild + */ + stage_instance_map stage_instances; + /** + * @brief List of threads in the guild + */ + thread_map threads; + /** + * @brief List of stickers in the guild + */ + sticker_map stickers; +}; + +/** @brief Create channel */ +struct DPP_EXPORT channel_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild channel was created on + */ + guild* creating_guild; + /** + * @brief channel that was created + */ + channel* created; +}; + +/** @brief Message remove emoji */ +struct DPP_EXPORT message_reaction_remove_emoji_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_emoji_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief emoji of reaction + */ + emoji reacting_emoji; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; +}; + +/** @brief Message delete bulk */ +struct DPP_EXPORT message_delete_bulk_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_delete_bulk_t(class discord_client* client, const std::string& raw); + /** + * @brief guild messages are being deleted upon + */ + guild* deleting_guild; + /** + * @brief user who is deleting the messages + */ + user* deleting_user; + /** + * @brief channel messages are being deleted from + */ + channel* deleting_channel; + /** + * @brief list of message ids of deleted messages + */ + std::vector deleted; +}; + +/** @brief Guild role update */ +struct DPP_EXPORT guild_role_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where roles are being updated + */ + guild* updating_guild; + /** + * @brief the role being updated + */ + role* updated; +}; + +/** @brief Guild role delete */ +struct DPP_EXPORT guild_role_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_role_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where role is being deleted + */ + guild* deleting_guild; + /** + * @brief role being deleted + */ + role* deleted; + /** + * @brief ID of the deleted role + */ + snowflake role_id; +}; + +/** @brief Channel pins update */ +struct DPP_EXPORT channel_pins_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + channel_pins_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where message is being pinned + */ + guild* pin_guild; + /** + * @brief channel where message is being pinned + */ + channel* pin_channel; + /** + * @brief timestamp of pin + */ + time_t timestamp; +}; + +/** @brief Message remove all reactions */ +struct DPP_EXPORT message_reaction_remove_all_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_reaction_remove_all_t(class discord_client* client, const std::string& raw); + /** + * @brief Guild reaction occurred on + */ + guild* reacting_guild; + /** + * @brief channel the reaction happened on + */ + channel* reacting_channel; + /** + * @brief message id of the message reacted upon + */ + snowflake message_id; + +}; + +/** @brief Voice server update */ +struct DPP_EXPORT voice_server_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + voice_server_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild id where voice server updated + */ + snowflake guild_id; + /** + * @brief voice server token, used to connect to vc + */ + std::string token; + /** + * @brief voice server endpoint wss:// address + * + */ + std::string endpoint; +}; + +/** @brief Guild emojis update */ +struct DPP_EXPORT guild_emojis_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_emojis_update_t(class discord_client* client, const std::string& raw); + /** + * @brief snowflake ids of list of emojis + */ + std::vector emojis; + /** + * @brief guild where emojis are being updated + */ + guild* updating_guild; +}; + +/** + * @brief Presence update + * + */ +struct DPP_EXPORT presence_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + presence_update_t(class discord_client* client, const std::string& raw); + /** + * @brief rich presence being updated + */ + presence rich_presence; +}; + +/** @brief Webhooks update */ +struct DPP_EXPORT webhooks_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + webhooks_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where webhooks are being updated + */ + guild* webhook_guild; + /** + * @brief channel where webhooks are being updated + */ + channel* webhook_channel; +}; + +/** @brief Guild member add */ +struct DPP_EXPORT guild_member_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_add_t(class discord_client* client, const std::string& raw); + /** + * @brief guild which gained new member + */ + guild* adding_guild; + /** + * @brief member which was added + */ + guild_member added; +}; + +/** @brief Invite delete */ +struct DPP_EXPORT invite_delete_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + invite_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief the deleted invite + */ + invite deleted_invite; +}; + +/** @brief Guild update */ +struct DPP_EXPORT guild_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild being updated + */ + guild* updated; +}; + +/** @brief Guild integrations update */ +struct DPP_EXPORT guild_integrations_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_integrations_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where integrations are being updated + */ + guild* updating_guild; +}; + +/** @brief Guild member update */ +struct DPP_EXPORT guild_member_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_member_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where member is being updated + */ + guild* updating_guild; + /** + * @brief member being updated + */ + guild_member updated; +}; + +/** @brief Invite create */ +struct DPP_EXPORT invite_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + invite_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created invite + */ + invite created_invite; +}; + +/** @brief Message update */ +struct DPP_EXPORT message_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_update_t(class discord_client* client, const std::string& raw); + /** + * @brief message being updated + */ + message msg; +}; + +/** @brief User update */ +struct DPP_EXPORT user_update_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + user_update_t(class discord_client* client, const std::string& raw); + /** + * @brief user being updated + */ + user updated; +}; + +/** @brief Create message */ +struct DPP_EXPORT message_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + message_create_t(class discord_client* client, const std::string& raw); + /** + * @brief message that was created (sent). + */ + message msg; + /** + * @brief Send a text to the same channel as the channel_id in received event. + * @param m Text to send + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void send(const std::string& m, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Send a message to the same channel as the channel_id in received event. + * @param msg Message to send + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void send(message& msg, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Send a message to the same channel as the channel_id in received event. + * @param msg Message to send + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void send(message&& msg, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Reply to the message received in the event. + * @param m Text to send + * @param mention_replied_user mentions (pings) the author of message replied to, if true + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void reply(const std::string& m, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Reply to the message received in the event. + * @param msg Message to send as a reply. + * @param mention_replied_user mentions (pings) the author of message replied to, if true + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void reply(message& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; + /** + * @brief Reply to the message received in the event. + * @param msg Message to send as a reply. + * @param mention_replied_user mentions (pings) the author of message replied to, if true + * @param callback User function to execute once the API call completes. + * @note confirmation_callback_t::value contains a message object on success. On failure, value is undefined and confirmation_callback_t::is_error() is true. + */ + void reply(message&& msg, bool mention_replied_user = false, command_completion_event_t callback = utility::log_error()) const; +}; + +/** @brief Guild ban add */ +struct DPP_EXPORT guild_ban_add_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_ban_add_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where ban was added + */ + guild* banning_guild; + /** + * @brief user being banned + */ + user banned; +}; + +/** @brief Guild ban remove */ +struct DPP_EXPORT guild_ban_remove_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + guild_ban_remove_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where ban is being removed + */ + guild* unbanning_guild; + /** + * @brief user being unbanned + */ + user unbanned; +}; + +/** @brief Integration create */ +struct DPP_EXPORT integration_create_t : public event_dispatch_t { + /** Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_create_t(class discord_client* client, const std::string& raw); + /** + * @brief created integration + */ + integration created_integration; +}; + +/** @brief Integration update */ +struct DPP_EXPORT integration_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated integration + */ + integration updated_integration; +}; + +/** @brief Integration delete */ +struct DPP_EXPORT integration_delete_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + integration_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief deleted integration + */ + integration deleted_integration; +}; + +/** @brief Thread Create*/ +struct DPP_EXPORT thread_create_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_create_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread was created + */ + guild* creating_guild; + /** + * @brief thread created + */ + thread created; +}; + +/** @brief Thread Update +*/ +struct DPP_EXPORT thread_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_update_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread was updated + */ + guild* updating_guild; + /** + * @brief thread updated + */ + thread updated; +}; + +/** @brief Thread Delete + */ +struct DPP_EXPORT thread_delete_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_delete_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread was deleted + */ + guild* deleting_guild; + /** + * @brief thread deleted + */ + thread deleted; +}; + +/** @brief Thread List Sync + */ +struct DPP_EXPORT thread_list_sync_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_list_sync_t(class discord_client* client, const std::string& raw); + /** + * @brief guild where thread list was synchronised + */ + guild* updating_guild; + /** + * @brief list of threads (channels) synchronised + */ + std::vector threads; + /** + * @brief list of thread members for the channels (threads) + */ + std::vector members; +}; + +/** @brief Thread Member Update + */ +struct DPP_EXPORT thread_member_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_member_update_t(class discord_client* client, const std::string& raw); + /** + * @brief updated thread member + */ + thread_member updated; +}; + +/** @brief Thread Members Update + */ +struct DPP_EXPORT thread_members_update_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * @param raw Raw event text as JSON + */ + thread_members_update_t(class discord_client* client, const std::string& raw); + /** + * @brief thread (channel) id + */ + snowflake thread_id; + /** + * @brief guild thread members updated on + */ + guild* updating_guild; + /** + * @brief new approximate member count + */ + uint8_t member_count; + /** + * @brief added members + */ + std::vector added; + /** + * @brief ids only of removed members + */ + std::vector removed_ids; +}; + +/** @brief voice buffer send + */ +struct DPP_EXPORT voice_buffer_send_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_buffer_send_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where buffer was sent + */ + class discord_voice_client* voice_client; + /** + * @brief encoded size of sent buffer + */ + int buffer_size; +}; + +/** @brief voice user talking */ +struct DPP_EXPORT voice_user_talking_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_user_talking_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where user is talking + */ + class discord_voice_client* voice_client; + /** + * @brief talking user id + */ + snowflake user_id; + /** + * @brief flags for talking user + */ + uint8_t talking_flags; +}; + +/** @brief voice user talking */ +struct DPP_EXPORT voice_ready_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_ready_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client which is ready + */ + class discord_voice_client* voice_client; + /** + * @brief id of voice channel + */ + snowflake voice_channel_id; +}; + +/** @brief voice receive packet */ +struct DPP_EXPORT voice_receive_t : public event_dispatch_t { + +friend class discord_voice_client; + + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as UDP packet. + */ + voice_receive_t(class discord_client* client, const std::string &raw); + /** + * @brief Construct a new voice receive t object + * + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as UDP packet. + * @param vc owning voice client pointer + * @param _user_id user id who is speaking, 0 for a mix of all user audio + * @param pcm user audio to set + * @param length length of user audio in bytes + */ + voice_receive_t(class discord_client* client, const std::string &raw, class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); + /** + * @brief Voice client + */ + class discord_voice_client* voice_client; + /** + * @brief Audio data, encoded as 48kHz stereo PCM or Opus, + * @deprecated Please switch to using audio_data. + */ + uint8_t* audio = nullptr; + /** + * @brief Size of audio buffer + * @deprecated Please switch to using audio_data. + */ + size_t audio_size = 0; + /** + * @brief Audio data, encoded as 48kHz stereo PCM or Opus, + */ + std::basic_string audio_data; + /** + * @brief User ID of speaker (zero if unknown) + */ + snowflake user_id; +protected: + /** + * @brief Reassign values outside of the constructor for use within discord_voice_client + * + * @param vc owning voice client pointer + * @param _user_id user id who is speaking, 0 for a mix of all user audio + * @param pcm user audio to set + * @param length length of user audio in bytes + */ + void reassign(class discord_voice_client* vc, snowflake _user_id, uint8_t* pcm, size_t length); +}; + +/** @brief voice client speaking event */ +struct DPP_EXPORT voice_client_speaking_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_client_speaking_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where user is speaking + */ + class discord_voice_client* voice_client; + /** + * @brief speaking user id + * + */ + snowflake user_id; + /** + * @brief ssrc value of speaking user + */ + uint32_t ssrc; +}; + +/** @brief voice client disconnect event */ +struct DPP_EXPORT voice_client_disconnect_t : public event_dispatch_t { + /** + * @brief Constructor + * @param client The shard the event originated on. + * WILL ALWAYS be NULL. + * @param raw Raw event text as JSON + */ + voice_client_disconnect_t(class discord_client* client, const std::string &raw); + /** + * @brief voice client where user disconnected + */ + class discord_voice_client* voice_client; + /** + * @brief user id of user who left vc + */ + snowflake user_id; +}; + +}; + diff --git a/3rdParty/dpp/dns.h b/3rdParty/dpp/dns.h index 33265e979c..23d5b1ba99 100644 --- a/3rdParty/dpp/dns.h +++ b/3rdParty/dpp/dns.h @@ -1,76 +1,76 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#endif -#include -#include -#include - -namespace dpp { - - /** - * @brief Represents a cached DNS result. - * Used by the ssl_client class to store cached copies of dns lookups. - */ - struct dns_cache_entry { - /** - * @brief Resolved address information - */ - addrinfo addr; - - /** - * @brief Socket address. - * Discord only supports ipv4, but sockaddr_in6 is larger - * than sockaddr_in, sockaddr_storage will hold either. This - * means that if discord ever do support ipv6 we just flip - * one value in dns.cpp and that should be all that is needed. - */ - sockaddr_storage ai_addr; - - /** - * @brief Time at which this cache entry is invalidated - */ - time_t expire_timestamp; - }; - - /** - * @brief Cache container type - */ - using dns_cache_t = std::unordered_map; - - /** - * @brief Resolve a hostname to an addrinfo - * - * @param hostname Hostname to resolve - * @param port A port number or named service, e.g. "80" - * @return dns_cache_entry* First IP address associated with the hostname DNS record - * @throw dpp::connection_exception On failure to resolve hostname - */ - const dns_cache_entry* resolve_hostname(const std::string& hostname, const std::string& port); -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#endif +#include +#include +#include + +namespace dpp { + + /** + * @brief Represents a cached DNS result. + * Used by the ssl_client class to store cached copies of dns lookups. + */ + struct dns_cache_entry { + /** + * @brief Resolved address information + */ + addrinfo addr; + + /** + * @brief Socket address. + * Discord only supports ipv4, but sockaddr_in6 is larger + * than sockaddr_in, sockaddr_storage will hold either. This + * means that if discord ever do support ipv6 we just flip + * one value in dns.cpp and that should be all that is needed. + */ + sockaddr_storage ai_addr; + + /** + * @brief Time at which this cache entry is invalidated + */ + time_t expire_timestamp; + }; + + /** + * @brief Cache container type + */ + using dns_cache_t = std::unordered_map; + + /** + * @brief Resolve a hostname to an addrinfo + * + * @param hostname Hostname to resolve + * @param port A port number or named service, e.g. "80" + * @return dns_cache_entry* First IP address associated with the hostname DNS record + * @throw dpp::connection_exception On failure to resolve hostname + */ + const dns_cache_entry* resolve_hostname(const std::string& hostname, const std::string& port); +}; diff --git a/3rdParty/dpp/dpp.h b/3rdParty/dpp/dpp.h index 297c94c272..3e3d0b52fb 100644 --- a/3rdParty/dpp/dpp.h +++ b/3rdParty/dpp/dpp.h @@ -1,74 +1,74 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/3rdParty/dpp/dtemplate.h b/3rdParty/dpp/dtemplate.h index 7569c5f786..f9ecb3a406 100644 --- a/3rdParty/dpp/dtemplate.h +++ b/3rdParty/dpp/dtemplate.h @@ -1,103 +1,103 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents a guild template - */ -class DPP_EXPORT dtemplate : public json_interface { -public: - /** - * @brief Template code - */ - std::string code; - /** - * @brief Template name - */ - std::string name; - /** - * @brief Template description - */ - std::string description; - /** - * @brief Usage counter - */ - uint32_t usage_count; - /** - * @brief User ID of creator - */ - snowflake creator_id; - /** - * @brief Creation date/time - * - */ - time_t created_at; - /** - * @brief Last update date/time - */ - time_t updated_at; - /** - * @brief Guild id the template is created from - */ - snowflake source_guild_id; - /** - * @brief True if needs synchronising - */ - bool is_dirty; - - /** - * @brief Construct a new dtemplate object - */ - dtemplate(); - - /** - * @brief Destroy the dtemplate object - */ - virtual ~dtemplate() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - dtemplate& fill_from_json(nlohmann::json* j); - - /** - * @brief Build the JSON for this object - * - * @param with_id Add ID to output - * @return std::string JSON content - */ - std::string build_json(bool with_id = false) const; - -}; - -/** A container of invites */ -typedef std::unordered_map dtemplate_map; - - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents a guild template + */ +class DPP_EXPORT dtemplate : public json_interface { +public: + /** + * @brief Template code + */ + std::string code; + /** + * @brief Template name + */ + std::string name; + /** + * @brief Template description + */ + std::string description; + /** + * @brief Usage counter + */ + uint32_t usage_count; + /** + * @brief User ID of creator + */ + snowflake creator_id; + /** + * @brief Creation date/time + * + */ + time_t created_at; + /** + * @brief Last update date/time + */ + time_t updated_at; + /** + * @brief Guild id the template is created from + */ + snowflake source_guild_id; + /** + * @brief True if needs synchronising + */ + bool is_dirty; + + /** + * @brief Construct a new dtemplate object + */ + dtemplate(); + + /** + * @brief Destroy the dtemplate object + */ + virtual ~dtemplate() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + dtemplate& fill_from_json(nlohmann::json* j); + + /** + * @brief Build the JSON for this object + * + * @param with_id Add ID to output + * @return std::string JSON content + */ + std::string build_json(bool with_id = false) const; + +}; + +/** A container of invites */ +typedef std::unordered_map dtemplate_map; + + +}; diff --git a/3rdParty/dpp/emoji.h b/3rdParty/dpp/emoji.h index 7c47fe5eba..05e841317f 100644 --- a/3rdParty/dpp/emoji.h +++ b/3rdParty/dpp/emoji.h @@ -1,177 +1,177 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -#define MAX_EMOJI_SIZE 256 * 1024 - -/** - * @brief Flags for dpp::emoji - */ -enum emoji_flags : uint8_t { - /// Emoji requires colons - e_require_colons = 0b00000001, - /// Managed (introduced by application) - e_managed = 0b00000010, - /// Animated - e_animated = 0b00000100, - /// Available (false if the guild doesn't meet boosting criteria, etc) - e_available = 0b00001000, -}; - -/** - * @brief Represents an emoji for a dpp::guild - */ -class DPP_EXPORT emoji : public managed, public json_interface { -public: - /** - * @brief Emoji name - */ - std::string name; - /** - * @brief User id who uploaded the emoji - */ - snowflake user_id; - /** - * @brief Flags for the emoji from dpp::emoji_flags - */ - uint8_t flags; - /** - * @brief Image data for the emoji if uploading - */ - std::string* image_data; - - /** - * @brief Construct a new emoji object - */ - emoji(); - - /** - * @brief Construct a new emoji object with name, ID and flags - * - * @param n The emoji's name - * @param i ID, if it has one (unicode does not) - * @param f Emoji flags (emoji_flags) - */ - emoji(const std::string n, const snowflake i = 0, const uint8_t f = 0); - - /** - * @brief Destroy the emoji object - */ - virtual ~emoji(); - - /** - * @brief Create a mentionable emoji - * @param name The name of the emoji. - * @param id The ID of the emoji. - * @param is_animated is emoji animated. - * @return std::string The formatted mention of the emoji. - */ - static std::string get_mention(const std::string& name, const snowflake& id, bool is_animated = false); - - /** - * @brief Read class values from json object - * - * @param j A json object to read from - * @return A reference to self - */ - emoji& fill_from_json(nlohmann::json* j); - - /** - * @brief Build the json for this object - * - * @param with_id include the id in the JSON - * @return std::string json data - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Emoji requires colons - * - * @return true Requires colons - * @return false Does not require colons - */ - bool requires_colons() const; - - /** - * @brief Emoji is managed - * - * @return true Is managed - * @return false Is not managed - */ - bool is_managed() const; - - /** - * @brief Emoji is animated - * - * @return true Is animated - * @return false Is noy animated - */ - bool is_animated() const; - - /** - * @brief Is available - * - * @return true Is available - * @return false Is unavailable - */ - bool is_available() const; - - /** - * @brief Load an image into the object as base64 - * - * @param image_blob Image binary data - * @param type Type of image - * @return emoji& Reference to self - * @throw dpp::exception Image content exceeds discord maximum of 256 kilobytes - */ - emoji& load_image(const std::string &image_blob, const image_type type); - - /** - * @brief Format to name if unicode, name:id if has id or a:name:id if animated - * - * @return Formatted name for reactions - */ - std::string format() const; - - /** - * @brief Get the mention/ping for the emoji - * - * @return std::string mention - */ - std::string get_mention() const; -}; - -/** - * @brief Group of emojis - */ -typedef std::unordered_map emoji_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +#define MAX_EMOJI_SIZE 256 * 1024 + +/** + * @brief Flags for dpp::emoji + */ +enum emoji_flags : uint8_t { + /// Emoji requires colons + e_require_colons = 0b00000001, + /// Managed (introduced by application) + e_managed = 0b00000010, + /// Animated + e_animated = 0b00000100, + /// Available (false if the guild doesn't meet boosting criteria, etc) + e_available = 0b00001000, +}; + +/** + * @brief Represents an emoji for a dpp::guild + */ +class DPP_EXPORT emoji : public managed, public json_interface { +public: + /** + * @brief Emoji name + */ + std::string name; + /** + * @brief User id who uploaded the emoji + */ + snowflake user_id; + /** + * @brief Flags for the emoji from dpp::emoji_flags + */ + uint8_t flags; + /** + * @brief Image data for the emoji if uploading + */ + std::string* image_data; + + /** + * @brief Construct a new emoji object + */ + emoji(); + + /** + * @brief Construct a new emoji object with name, ID and flags + * + * @param n The emoji's name + * @param i ID, if it has one (unicode does not) + * @param f Emoji flags (emoji_flags) + */ + emoji(const std::string n, const snowflake i = 0, const uint8_t f = 0); + + /** + * @brief Destroy the emoji object + */ + virtual ~emoji(); + + /** + * @brief Create a mentionable emoji + * @param name The name of the emoji. + * @param id The ID of the emoji. + * @param is_animated is emoji animated. + * @return std::string The formatted mention of the emoji. + */ + static std::string get_mention(const std::string& name, const snowflake& id, bool is_animated = false); + + /** + * @brief Read class values from json object + * + * @param j A json object to read from + * @return A reference to self + */ + emoji& fill_from_json(nlohmann::json* j); + + /** + * @brief Build the json for this object + * + * @param with_id include the id in the JSON + * @return std::string json data + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Emoji requires colons + * + * @return true Requires colons + * @return false Does not require colons + */ + bool requires_colons() const; + + /** + * @brief Emoji is managed + * + * @return true Is managed + * @return false Is not managed + */ + bool is_managed() const; + + /** + * @brief Emoji is animated + * + * @return true Is animated + * @return false Is noy animated + */ + bool is_animated() const; + + /** + * @brief Is available + * + * @return true Is available + * @return false Is unavailable + */ + bool is_available() const; + + /** + * @brief Load an image into the object as base64 + * + * @param image_blob Image binary data + * @param type Type of image + * @return emoji& Reference to self + * @throw dpp::exception Image content exceeds discord maximum of 256 kilobytes + */ + emoji& load_image(const std::string &image_blob, const image_type type); + + /** + * @brief Format to name if unicode, name:id if has id or a:name:id if animated + * + * @return Formatted name for reactions + */ + std::string format() const; + + /** + * @brief Get the mention/ping for the emoji + * + * @return std::string mention + */ + std::string get_mention() const; +}; + +/** + * @brief Group of emojis + */ +typedef std::unordered_map emoji_map; + +}; diff --git a/3rdParty/dpp/etf.h b/3rdParty/dpp/etf.h index 5b07b6c961..79b18d9338 100644 --- a/3rdParty/dpp/etf.h +++ b/3rdParty/dpp/etf.h @@ -1,642 +1,642 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Parts of this file inspired by, or outright copied from erlpack: - * https://github.com/discord/erlpack/ - * - * Acknowledgements: - * - * sysdep.h: - * Based on work by FURUHASHI Sadayuki in msgpack-python - * (https://github.com/msgpack/msgpack-python) - * - * Copyright (C) 2008-2010 FURUHASHI Sadayuki - * Licensed under the Apache License, Version 2.0 (the "License"). - * - ************************************************************************************/ - -#pragma once -#include -#include -#include - -namespace dpp { - -/** Current ETF format version in use */ -const uint8_t FORMAT_VERSION = 131; - -/** - * @brief Represents a token which identifies the type of value which follows it - * in the ETF binary structure. - */ -enum etf_token_type : uint8_t { - /// 68 [Distribution header] - ett_distribution = 'D', - /// 70 [Float64:IEEE float] - ett_new_float = 'F', - /// 77 [UInt32:Len, UInt8:Bits, Len:Data] - ett_bit_binary = 'M', - /// 80 [UInt4:UncompressedSize, N:ZlibCompressedData] - ett_compressed = 'P', - /// 97 [UInt8:Int] - ett_smallint = 'a', - /// 98 [Int32:Int] - ett_integer = 'b', - /// 99 [31:Float String] Float in string format (formatted "%.20e", sscanf "%lf"). Superseded by ett_new_float - ett_float = 'c', - /// 100 [UInt16:Len, Len:AtomName] max Len is 255 - ett_atom = 'd', - /// 101 [atom:Node, UInt32:ID, UInt8:Creation] - ett_reference = 'e', - /// 102 [atom:Node, UInt32:ID, UInt8:Creation] - ett_port = 'f', - /// 103 [atom:Node, UInt32:ID, UInt32:Serial, UInt8:Creation] - ett_pid = 'g', - /// 104 [UInt8:Arity, N:Elements] - ett_small_tuple = 'h', - /// 105 [UInt32:Arity, N:Elements] - ett_large_tuple = 'i', - /// 106 empty list - ett_nil = 'j', - /// 107 [UInt16:Len, Len:Characters] - ett_string = 'k', - /// 108 [UInt32:Len, Elements, Tail] - ett_list = 'l', - /// 109 [UInt32:Len, Len:Data] - ett_binary = 'm', - /// 110 [UInt8:n, UInt8:Sign, n:nums] - ett_bigint_small = 'n', - /// 111 [UInt32:n, UInt8:Sign, n:nums] - ett_bigint_large = 'o', - /// 112 [UInt32:Size, UInt8:Arity, 16*Uint6-MD5:Uniq, UInt32:Index, UInt32:NumFree, atom:Module, int:OldIndex, int:OldUniq, pid:Pid, NunFree*ext:FreeVars] - ett_new_function = 'p', - /// 113 [atom:Module, atom:Function, smallint:Arity] - ett_export = 'q', - /// 114 [UInt16:Len, atom:Node, UInt8:Creation, Len*UInt32:ID] - ett_new_reference = 'r', - /// 115 [UInt8:Len, Len:AtomName] - ett_atom_small = 's', - /// 116 [UInt32:Airty, N:Pairs] - ett_map = 't', - /// 117 [UInt4:NumFree, pid:Pid, atom:Module, int:Index, int:Uniq, NumFree*ext:FreeVars] - ett_function = 'u', - /// 118 [UInt16:Len, Len:AtomName] max Len is 255 characters (up to 4 bytes per) - ett_atom_utf8 = 'v', - /// 119 [UInt8:Len, Len:AtomName] - ett_atom_utf8_small = 'w' -}; - -/** - * @brief A horrible structure used within the ETF parser to convert uint64_t to double and back. - * This is horrible, but it is the official way erlang term format does this, so we can't really - * mess with it much. - */ -union type_punner { - /** - * @brief binary integer value - */ - uint64_t ui64; - /** - * @brief double floating point value - */ - double df; -}; - -/** - * @brief Represents a buffer of bytes being encoded into ETF - */ -struct DPP_EXPORT etf_buffer { - /** - * @brief Raw buffer - */ - std::vector buf; - /** - * @brief Current used length of buffer - * (this is different from buf.size() as it is pre-allocated - * using resize and may not all be in use) - */ - size_t length; - - /** - * @brief Construct a new etf buffer object - * - * @param initial initial buffer size to allocate - */ - etf_buffer(size_t initial); - - /** - * @brief Destroy the etf buffer object - */ - ~etf_buffer(); -}; - -/** - * @brief The etf_parser class can serialise and deserialise ETF (Erlang Term Format) - * into and out of an nlohmann::json object, so that layers above the websocket don't - * have to be any different for handling ETF. - */ -class DPP_EXPORT etf_parser { - - /** - * @brief Current size of binary data - */ - size_t size; - - /** - * @brief Current offset into binary data - */ - size_t offset; - - /** - * @brief Pointer to binary ETF data to be decoded - */ - uint8_t* data; - - /** - * @brief Parse a single value, and if that value contains other - * values (e.g. an array or map) then call itself recursively. - * - * @return nlohmann::json JSON value from the ETF - */ - nlohmann::json inner_parse(); - - /** - * @brief Read 8 bits of data from the buffer - * - * @return uint8_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint8_t read_8_bits(); - - /** - * @brief Read 16 bits of data from the buffer - * - * @return uint16_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint16_t read_16_bits(); - - /** - * @brief Read 32 bits of data from the buffer - * - * @return uint32_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint32_t read_32_bits(); - - /** - * @brief Read 64 bits of data from the buffer - * - * @return uint64_t data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - uint64_t read_64_bits(); - - /** - * @brief Read string data from the buffer - * - * @param length Length of string to retrieve - * @return const char* data retrieved - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - const char* read_string(uint32_t length); - - /** - * @brief Process an 'atom' value. - * An atom is a "label" or constant value within the data, - * such as a key name, nullptr, or false. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json process_atom(const char* atom, uint16_t length); - - /** - * @brief Decode an 'atom' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_atom(); - - /** - * @brief Decode a small 'atom' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_small_atom(); - - /** - * @brief Decode a small integer value (0-255). - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_small_integer(); - - /** - * @brief Decode an integer value (-MAXINT -> MAXINT-1). - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_integer(); - - /** - * @brief Decode an array of values. - * - * @return nlohmann::json values converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_array(uint32_t length); - - /** - * @brief Decode a list of values. - * - * @return nlohmann::json values converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_list(); - - /** - * @brief Decode a 'tuple' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_tuple(uint32_t length); - - /** - * @brief Decode a nil 'atom' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_nil(); - - /** - * @brief Decode a map (object) value. - * Will recurse to evaluate each member variable. - * - * @return nlohmann::json values converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_map(); - - /** - * @brief Decode a floating point numeric value. - * (depreciated in erlang but still expected to be supported) - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_float(); - - /** - * @brief Decode a floating type numeric value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_new_float(); - - /** - * @brief Decode a 'bigint' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_bigint(uint32_t digits); - - /** - * @brief Decode a small 'bigint' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_bigint_small(); - - /** - * @brief Decode a large 'bigint' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_bigint_large(); - - /** - * @brief Decode a binary value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_binary(); - - /** - * @brief Decode a string value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_string(); - - /** - * @brief Decode a string list value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_string_as_list(); - - /** - * @brief Decode a 'small tuple' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_tuple_small(); - - /** - * @brief Decode a 'large tuple' value. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_tuple_large(); - - /** - * @brief Decode a compressed value. - * This is a zlib-compressed binary blob which contains another - * ETF object. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_compressed(); - - /** - * @brief Decode a 'reference' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_reference(); - - /** - * @brief Decode a 'new reference' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_new_reference(); - - /** - * @brief Decode a 'port' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_port(); - - /** - * @brief Decode a 'PID' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_pid(); - - /** - * @brief Decode an 'export' value. - * Erlang expects this to be supported, in practice Discord doesn't send these right now. - * - * @return nlohmann::json value converted to JSON - * @throw dpp::exception Data stream isn't long enough to fetch requested bits - */ - nlohmann::json decode_export(); - - /** - * @brief Write to output buffer for creation of ETF from JSON - * - * @param pk buffer struct - * @param bytes byte buffer to write - * @param l number of bytes to write - * @throw std::exception Buffer cannot be extended - */ - void buffer_write(etf_buffer *pk, const char *bytes, size_t l); - - /** - * @brief Append version number to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_version(etf_buffer *b); - - /** - * @brief Append nil value to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_nil(etf_buffer *b); - - /** - * @brief Append false value to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_false(etf_buffer *b); - - /** - * @brief Append true value to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_true(etf_buffer *b); - - /** - * @brief Append small integer value to ETF buffer - * - * @param b buffer to append to - * @param d double to append - * @throw std::exception Buffer cannot be extended - */ - void append_small_integer(etf_buffer *b, unsigned char d); - - /** - * @brief Append integer value to ETF buffer - * - * @param b buffer to append to - * @param d integer to append - * @throw std::exception Buffer cannot be extended - */ - void append_integer(etf_buffer *b, int32_t d); - - /** - * @brief Append 64 bit integer value to ETF buffer - * - * @param b buffer to append to - * @param d integer to append - * @throw std::exception Buffer cannot be extended - */ - void append_unsigned_long_long(etf_buffer *b, unsigned long long d); - - /** - * @brief Append 64 bit integer value to ETF buffer - * - * @param b buffer to append to - * @param d integer to append - * @throw std::exception Buffer cannot be extended - */ - void append_long_long(etf_buffer *b, long long d); - - /** - * @brief Append double value to ETF buffer - * - * @param b buffer to append to - * @param f double to append - * @throw std::exception Buffer cannot be extended - */ - void append_double(etf_buffer *b, double f); - - /** - * @brief Append atom value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_atom(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append utf8 atom value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_atom_utf8(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append binary value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_binary(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append string value to ETF buffer - * - * @param b buffer to append to - * @param bytes pointer to string to append - * @param size size of string to append - * @throw std::exception Buffer cannot be extended - */ - void append_string(etf_buffer *b, const char *bytes, size_t size); - - /** - * @brief Append tuple value to ETF buffer - * - * @param b buffer to append to - * @param size size of value to append - * @throw std::exception Buffer cannot be extended - */ - void append_tuple_header(etf_buffer *b, size_t size); - - /** - * @brief Append list terminator to ETF buffer - * - * @param b buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void append_nil_ext(etf_buffer *b); - - /** - * @brief Append a list header value to ETF buffer - * - * @param b buffer to append to - * @param size size of values to append - * @throw std::exception Buffer cannot be extended - */ - void append_list_header(etf_buffer *b, size_t size); - - /** - * @brief Append a map header value to ETF buffer - * - * @param b buffer to append to - * @param size size of values to append - * @throw std::exception Buffer cannot be extended - */ - void append_map_header(etf_buffer *b, size_t size); - - /** - * @brief Build ETF buffer - * - * @param j JSON object to build from - * @param b Buffer to append to - * @throw std::exception Buffer cannot be extended - */ - void inner_build(const nlohmann::json* j, etf_buffer* b); - -public: - /** - * @brief Construct a new etf parser object - */ - etf_parser(); - - /** - * @brief Destroy the etf parser object - */ - ~etf_parser(); - - /** - * @brief Convert ETF binary content to nlohmann::json - * - * @param in Raw binary ETF data (generally from a websocket) - * @return nlohmann::json JSON data for use in the library - * @throw dpp::exception Malformed or otherwise invalid ETF content - */ - nlohmann::json parse(const std::string& in); - - /** - * @brief Create ETF binary data from nlohmann::json - * - * @param j JSON value to encode to ETF - * @return std::string raw ETF data. Note that this can - * and probably will contain null values, use std::string::data() - * and std::string::size() to manipulate or send it. - * @throw std::exception Not enough memory, or invalid data types/values - */ - std::string build(const nlohmann::json& j); -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Parts of this file inspired by, or outright copied from erlpack: + * https://github.com/discord/erlpack/ + * + * Acknowledgements: + * + * sysdep.h: + * Based on work by FURUHASHI Sadayuki in msgpack-python + * (https://github.com/msgpack/msgpack-python) + * + * Copyright (C) 2008-2010 FURUHASHI Sadayuki + * Licensed under the Apache License, Version 2.0 (the "License"). + * + ************************************************************************************/ + +#pragma once +#include +#include +#include + +namespace dpp { + +/** Current ETF format version in use */ +const uint8_t FORMAT_VERSION = 131; + +/** + * @brief Represents a token which identifies the type of value which follows it + * in the ETF binary structure. + */ +enum etf_token_type : uint8_t { + /// 68 [Distribution header] + ett_distribution = 'D', + /// 70 [Float64:IEEE float] + ett_new_float = 'F', + /// 77 [UInt32:Len, UInt8:Bits, Len:Data] + ett_bit_binary = 'M', + /// 80 [UInt4:UncompressedSize, N:ZlibCompressedData] + ett_compressed = 'P', + /// 97 [UInt8:Int] + ett_smallint = 'a', + /// 98 [Int32:Int] + ett_integer = 'b', + /// 99 [31:Float String] Float in string format (formatted "%.20e", sscanf "%lf"). Superseded by ett_new_float + ett_float = 'c', + /// 100 [UInt16:Len, Len:AtomName] max Len is 255 + ett_atom = 'd', + /// 101 [atom:Node, UInt32:ID, UInt8:Creation] + ett_reference = 'e', + /// 102 [atom:Node, UInt32:ID, UInt8:Creation] + ett_port = 'f', + /// 103 [atom:Node, UInt32:ID, UInt32:Serial, UInt8:Creation] + ett_pid = 'g', + /// 104 [UInt8:Arity, N:Elements] + ett_small_tuple = 'h', + /// 105 [UInt32:Arity, N:Elements] + ett_large_tuple = 'i', + /// 106 empty list + ett_nil = 'j', + /// 107 [UInt16:Len, Len:Characters] + ett_string = 'k', + /// 108 [UInt32:Len, Elements, Tail] + ett_list = 'l', + /// 109 [UInt32:Len, Len:Data] + ett_binary = 'm', + /// 110 [UInt8:n, UInt8:Sign, n:nums] + ett_bigint_small = 'n', + /// 111 [UInt32:n, UInt8:Sign, n:nums] + ett_bigint_large = 'o', + /// 112 [UInt32:Size, UInt8:Arity, 16*Uint6-MD5:Uniq, UInt32:Index, UInt32:NumFree, atom:Module, int:OldIndex, int:OldUniq, pid:Pid, NunFree*ext:FreeVars] + ett_new_function = 'p', + /// 113 [atom:Module, atom:Function, smallint:Arity] + ett_export = 'q', + /// 114 [UInt16:Len, atom:Node, UInt8:Creation, Len*UInt32:ID] + ett_new_reference = 'r', + /// 115 [UInt8:Len, Len:AtomName] + ett_atom_small = 's', + /// 116 [UInt32:Airty, N:Pairs] + ett_map = 't', + /// 117 [UInt4:NumFree, pid:Pid, atom:Module, int:Index, int:Uniq, NumFree*ext:FreeVars] + ett_function = 'u', + /// 118 [UInt16:Len, Len:AtomName] max Len is 255 characters (up to 4 bytes per) + ett_atom_utf8 = 'v', + /// 119 [UInt8:Len, Len:AtomName] + ett_atom_utf8_small = 'w' +}; + +/** + * @brief A horrible structure used within the ETF parser to convert uint64_t to double and back. + * This is horrible, but it is the official way erlang term format does this, so we can't really + * mess with it much. + */ +union type_punner { + /** + * @brief binary integer value + */ + uint64_t ui64; + /** + * @brief double floating point value + */ + double df; +}; + +/** + * @brief Represents a buffer of bytes being encoded into ETF + */ +struct DPP_EXPORT etf_buffer { + /** + * @brief Raw buffer + */ + std::vector buf; + /** + * @brief Current used length of buffer + * (this is different from buf.size() as it is pre-allocated + * using resize and may not all be in use) + */ + size_t length; + + /** + * @brief Construct a new etf buffer object + * + * @param initial initial buffer size to allocate + */ + etf_buffer(size_t initial); + + /** + * @brief Destroy the etf buffer object + */ + ~etf_buffer(); +}; + +/** + * @brief The etf_parser class can serialise and deserialise ETF (Erlang Term Format) + * into and out of an nlohmann::json object, so that layers above the websocket don't + * have to be any different for handling ETF. + */ +class DPP_EXPORT etf_parser { + + /** + * @brief Current size of binary data + */ + size_t size; + + /** + * @brief Current offset into binary data + */ + size_t offset; + + /** + * @brief Pointer to binary ETF data to be decoded + */ + uint8_t* data; + + /** + * @brief Parse a single value, and if that value contains other + * values (e.g. an array or map) then call itself recursively. + * + * @return nlohmann::json JSON value from the ETF + */ + nlohmann::json inner_parse(); + + /** + * @brief Read 8 bits of data from the buffer + * + * @return uint8_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint8_t read_8_bits(); + + /** + * @brief Read 16 bits of data from the buffer + * + * @return uint16_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint16_t read_16_bits(); + + /** + * @brief Read 32 bits of data from the buffer + * + * @return uint32_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint32_t read_32_bits(); + + /** + * @brief Read 64 bits of data from the buffer + * + * @return uint64_t data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + uint64_t read_64_bits(); + + /** + * @brief Read string data from the buffer + * + * @param length Length of string to retrieve + * @return const char* data retrieved + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + const char* read_string(uint32_t length); + + /** + * @brief Process an 'atom' value. + * An atom is a "label" or constant value within the data, + * such as a key name, nullptr, or false. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json process_atom(const char* atom, uint16_t length); + + /** + * @brief Decode an 'atom' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_atom(); + + /** + * @brief Decode a small 'atom' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_small_atom(); + + /** + * @brief Decode a small integer value (0-255). + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_small_integer(); + + /** + * @brief Decode an integer value (-MAXINT -> MAXINT-1). + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_integer(); + + /** + * @brief Decode an array of values. + * + * @return nlohmann::json values converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_array(uint32_t length); + + /** + * @brief Decode a list of values. + * + * @return nlohmann::json values converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_list(); + + /** + * @brief Decode a 'tuple' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_tuple(uint32_t length); + + /** + * @brief Decode a nil 'atom' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_nil(); + + /** + * @brief Decode a map (object) value. + * Will recurse to evaluate each member variable. + * + * @return nlohmann::json values converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_map(); + + /** + * @brief Decode a floating point numeric value. + * (depreciated in erlang but still expected to be supported) + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_float(); + + /** + * @brief Decode a floating type numeric value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_new_float(); + + /** + * @brief Decode a 'bigint' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_bigint(uint32_t digits); + + /** + * @brief Decode a small 'bigint' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_bigint_small(); + + /** + * @brief Decode a large 'bigint' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_bigint_large(); + + /** + * @brief Decode a binary value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_binary(); + + /** + * @brief Decode a string value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_string(); + + /** + * @brief Decode a string list value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_string_as_list(); + + /** + * @brief Decode a 'small tuple' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_tuple_small(); + + /** + * @brief Decode a 'large tuple' value. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_tuple_large(); + + /** + * @brief Decode a compressed value. + * This is a zlib-compressed binary blob which contains another + * ETF object. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_compressed(); + + /** + * @brief Decode a 'reference' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_reference(); + + /** + * @brief Decode a 'new reference' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_new_reference(); + + /** + * @brief Decode a 'port' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_port(); + + /** + * @brief Decode a 'PID' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_pid(); + + /** + * @brief Decode an 'export' value. + * Erlang expects this to be supported, in practice Discord doesn't send these right now. + * + * @return nlohmann::json value converted to JSON + * @throw dpp::exception Data stream isn't long enough to fetch requested bits + */ + nlohmann::json decode_export(); + + /** + * @brief Write to output buffer for creation of ETF from JSON + * + * @param pk buffer struct + * @param bytes byte buffer to write + * @param l number of bytes to write + * @throw std::exception Buffer cannot be extended + */ + void buffer_write(etf_buffer *pk, const char *bytes, size_t l); + + /** + * @brief Append version number to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_version(etf_buffer *b); + + /** + * @brief Append nil value to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_nil(etf_buffer *b); + + /** + * @brief Append false value to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_false(etf_buffer *b); + + /** + * @brief Append true value to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_true(etf_buffer *b); + + /** + * @brief Append small integer value to ETF buffer + * + * @param b buffer to append to + * @param d double to append + * @throw std::exception Buffer cannot be extended + */ + void append_small_integer(etf_buffer *b, unsigned char d); + + /** + * @brief Append integer value to ETF buffer + * + * @param b buffer to append to + * @param d integer to append + * @throw std::exception Buffer cannot be extended + */ + void append_integer(etf_buffer *b, int32_t d); + + /** + * @brief Append 64 bit integer value to ETF buffer + * + * @param b buffer to append to + * @param d integer to append + * @throw std::exception Buffer cannot be extended + */ + void append_unsigned_long_long(etf_buffer *b, unsigned long long d); + + /** + * @brief Append 64 bit integer value to ETF buffer + * + * @param b buffer to append to + * @param d integer to append + * @throw std::exception Buffer cannot be extended + */ + void append_long_long(etf_buffer *b, long long d); + + /** + * @brief Append double value to ETF buffer + * + * @param b buffer to append to + * @param f double to append + * @throw std::exception Buffer cannot be extended + */ + void append_double(etf_buffer *b, double f); + + /** + * @brief Append atom value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_atom(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append utf8 atom value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_atom_utf8(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append binary value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_binary(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append string value to ETF buffer + * + * @param b buffer to append to + * @param bytes pointer to string to append + * @param size size of string to append + * @throw std::exception Buffer cannot be extended + */ + void append_string(etf_buffer *b, const char *bytes, size_t size); + + /** + * @brief Append tuple value to ETF buffer + * + * @param b buffer to append to + * @param size size of value to append + * @throw std::exception Buffer cannot be extended + */ + void append_tuple_header(etf_buffer *b, size_t size); + + /** + * @brief Append list terminator to ETF buffer + * + * @param b buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void append_nil_ext(etf_buffer *b); + + /** + * @brief Append a list header value to ETF buffer + * + * @param b buffer to append to + * @param size size of values to append + * @throw std::exception Buffer cannot be extended + */ + void append_list_header(etf_buffer *b, size_t size); + + /** + * @brief Append a map header value to ETF buffer + * + * @param b buffer to append to + * @param size size of values to append + * @throw std::exception Buffer cannot be extended + */ + void append_map_header(etf_buffer *b, size_t size); + + /** + * @brief Build ETF buffer + * + * @param j JSON object to build from + * @param b Buffer to append to + * @throw std::exception Buffer cannot be extended + */ + void inner_build(const nlohmann::json* j, etf_buffer* b); + +public: + /** + * @brief Construct a new etf parser object + */ + etf_parser(); + + /** + * @brief Destroy the etf parser object + */ + ~etf_parser(); + + /** + * @brief Convert ETF binary content to nlohmann::json + * + * @param in Raw binary ETF data (generally from a websocket) + * @return nlohmann::json JSON data for use in the library + * @throw dpp::exception Malformed or otherwise invalid ETF content + */ + nlohmann::json parse(const std::string& in); + + /** + * @brief Create ETF binary data from nlohmann::json + * + * @param j JSON value to encode to ETF + * @return std::string raw ETF data. Note that this can + * and probably will contain null values, use std::string::data() + * and std::string::size() to manipulate or send it. + * @throw std::exception Not enough memory, or invalid data types/values + */ + std::string build(const nlohmann::json& j); +}; + +}; diff --git a/3rdParty/dpp/event.h b/3rdParty/dpp/event.h index 8f50f1d0b1..b82f982eae 100644 --- a/3rdParty/dpp/event.h +++ b/3rdParty/dpp/event.h @@ -1,151 +1,151 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include - -#define event_decl(x,wstype) /** @brief Internal event handler for wstype websocket events. Called for each websocket message of this type. @internal */ \ - class x : public event { public: virtual void handle(dpp::discord_client* client, nlohmann::json &j, const std::string &raw); }; - -namespace dpp { - -class discord_client; - -/** - * @brief The events namespace holds the internal event handlers for each websocket event. - * These are handled internally and also dispatched to the user code if the event is hooked. - */ -namespace events { - -/** - * @brief An event object represents an event handled internally, passed from the websocket e.g. MESSAGE_CREATE. - */ -class DPP_EXPORT event { -public: - /** Pure virtual method for event handler code - * @param client The creating shard - * @param j The json data of the event - * @param raw The raw event json - */ - virtual void handle(class discord_client* client, nlohmann::json &j, const std::string &raw) = 0; -}; - -/* Internal logger */ -event_decl(logger,LOG); - -/* Guilds */ -event_decl(guild_create,GUILD_CREATE); -event_decl(guild_update,GUILD_UPDATE); -event_decl(guild_delete,GUILD_DELETE); -event_decl(guild_ban_add,GUILD_BAN_ADD); -event_decl(guild_ban_remove,GUILD_BAN_REMOVE); -event_decl(guild_emojis_update,GUILD_EMOJIS_UPDATE); -event_decl(guild_integrations_update,GUILD_INTEGRATIONS_UPDATE); -event_decl(guild_join_request_delete,GUILD_JOIN_REQUEST_DELETE); -event_decl(guild_stickers_update,GUILD_STICKERS_UPDATE); - -/* Stage channels */ -event_decl(stage_instance_create,STAGE_INSTANCE_CREATE); -event_decl(stage_instance_update,STAGE_INSTANCE_UPDATE); -event_decl(stage_instance_delete,STAGE_INSTANCE_DELETE); - -/* Guild members */ -event_decl(guild_member_add,GUILD_MEMBER_ADD); -event_decl(guild_member_remove,GUILD_MEMBER_REMOVE); -event_decl(guild_members_chunk,GUILD_MEMBERS_CHUNK); -event_decl(guild_member_update,GUILD_MEMBERS_UPDATE); - -/* Guild roles */ -event_decl(guild_role_create,GUILD_ROLE_CREATE); -event_decl(guild_role_update,GUILD_ROLE_UPDATE); -event_decl(guild_role_delete,GUILD_ROLE_DELETE); - -/* Session state */ -event_decl(resumed,RESUMED); -event_decl(ready,READY); - -/* Channels */ -event_decl(channel_create,CHANNEL_CREATE); -event_decl(channel_update,CHANNEL_UPDATE); -event_decl(channel_delete,CHANNEL_DELETE); -event_decl(channel_pins_update,CHANNEL_PINS_UPDATE); - -/* Threads */ -event_decl(thread_create,THREAD_CREATE); -event_decl(thread_update,THREAD_UPDATE); -event_decl(thread_delete,THREAD_DELETE); -event_decl(thread_list_sync,THREAD_LIST_SYNC); -event_decl(thread_member_update,THREAD_MEMBER_UPDATE); -event_decl(thread_members_update,THREAD_MEMBERS_UPDATE); - -/* Messages */ -event_decl(message_create,MESSAGE_CREATE); -event_decl(message_update,MESSAGE_UPDATE); -event_decl(message_delete,MESSAGE_DELETE); -event_decl(message_delete_bulk,MESSAGE_DELETE_BULK); - -/* Presence/typing */ -event_decl(presence_update,PRESENCE_UPDATE); -event_decl(typing_start,TYPING_START); - -/* Users (outside of guild) */ -event_decl(user_update,USER_UPDATE); - -/* Message reactions */ -event_decl(message_reaction_add,MESSAGE_REACTION_ADD); -event_decl(message_reaction_remove,MESSAGE_REACTION_REMOVE); -event_decl(message_reaction_remove_all,MESSAGE_REACTION_REMOVE_ALL); -event_decl(message_reaction_remove_emoji,MESSAGE_REACTION_REMOVE_EMOJI); - -/* Invites */ -event_decl(invite_create,INVITE_CREATE); -event_decl(invite_delete,INVITE_DELETE); - -/* Voice */ -event_decl(voice_state_update,VOICE_STATE_UPDATE); -event_decl(voice_server_update,VOICE_SERVER_UPDATE); - -/* Webhooks */ -event_decl(webhooks_update,WEBHOOKS_UPDATE); - -/* Application commands */ -event_decl(interaction_create,INTERACTION_CREATE); - -/* Integrations */ -event_decl(integration_create,INTEGRATION_CREATE); -event_decl(integration_update,INTEGRATION_UPDATE); -event_decl(integration_delete,INTEGRATION_DELETE); - -/* Scheduled events */ -event_decl(guild_scheduled_event_create,GUILD_SCHEDULED_EVENT_CREATE); -event_decl(guild_scheduled_event_update,GUILD_SCHEDULED_EVENT_UPDATE); -event_decl(guild_scheduled_event_delete,GUILD_SCHEDULED_EVENT_DELETE); -event_decl(guild_scheduled_event_user_add,GUILD_SCHEDULED_EVENT_USER_ADD); -event_decl(guild_scheduled_event_user_remove,GUILD_SCHEDULED_EVENT_USER_REMOVE); - -/* Auto moderation */ -event_decl(automod_rule_create, AUTO_MODERATION_RULE_CREATE); -event_decl(automod_rule_update, AUTO_MODERATION_RULE_UPDATE); -event_decl(automod_rule_delete, AUTO_MODERATION_RULE_DELETE); -event_decl(automod_rule_execute, AUTO_MODERATION_ACTION_EXECUTION); - -}}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +#define event_decl(x,wstype) /** @brief Internal event handler for wstype websocket events. Called for each websocket message of this type. @internal */ \ + class x : public event { public: virtual void handle(dpp::discord_client* client, nlohmann::json &j, const std::string &raw); }; + +namespace dpp { + +class discord_client; + +/** + * @brief The events namespace holds the internal event handlers for each websocket event. + * These are handled internally and also dispatched to the user code if the event is hooked. + */ +namespace events { + +/** + * @brief An event object represents an event handled internally, passed from the websocket e.g. MESSAGE_CREATE. + */ +class DPP_EXPORT event { +public: + /** Pure virtual method for event handler code + * @param client The creating shard + * @param j The json data of the event + * @param raw The raw event json + */ + virtual void handle(class discord_client* client, nlohmann::json &j, const std::string &raw) = 0; +}; + +/* Internal logger */ +event_decl(logger,LOG); + +/* Guilds */ +event_decl(guild_create,GUILD_CREATE); +event_decl(guild_update,GUILD_UPDATE); +event_decl(guild_delete,GUILD_DELETE); +event_decl(guild_ban_add,GUILD_BAN_ADD); +event_decl(guild_ban_remove,GUILD_BAN_REMOVE); +event_decl(guild_emojis_update,GUILD_EMOJIS_UPDATE); +event_decl(guild_integrations_update,GUILD_INTEGRATIONS_UPDATE); +event_decl(guild_join_request_delete,GUILD_JOIN_REQUEST_DELETE); +event_decl(guild_stickers_update,GUILD_STICKERS_UPDATE); + +/* Stage channels */ +event_decl(stage_instance_create,STAGE_INSTANCE_CREATE); +event_decl(stage_instance_update,STAGE_INSTANCE_UPDATE); +event_decl(stage_instance_delete,STAGE_INSTANCE_DELETE); + +/* Guild members */ +event_decl(guild_member_add,GUILD_MEMBER_ADD); +event_decl(guild_member_remove,GUILD_MEMBER_REMOVE); +event_decl(guild_members_chunk,GUILD_MEMBERS_CHUNK); +event_decl(guild_member_update,GUILD_MEMBERS_UPDATE); + +/* Guild roles */ +event_decl(guild_role_create,GUILD_ROLE_CREATE); +event_decl(guild_role_update,GUILD_ROLE_UPDATE); +event_decl(guild_role_delete,GUILD_ROLE_DELETE); + +/* Session state */ +event_decl(resumed,RESUMED); +event_decl(ready,READY); + +/* Channels */ +event_decl(channel_create,CHANNEL_CREATE); +event_decl(channel_update,CHANNEL_UPDATE); +event_decl(channel_delete,CHANNEL_DELETE); +event_decl(channel_pins_update,CHANNEL_PINS_UPDATE); + +/* Threads */ +event_decl(thread_create,THREAD_CREATE); +event_decl(thread_update,THREAD_UPDATE); +event_decl(thread_delete,THREAD_DELETE); +event_decl(thread_list_sync,THREAD_LIST_SYNC); +event_decl(thread_member_update,THREAD_MEMBER_UPDATE); +event_decl(thread_members_update,THREAD_MEMBERS_UPDATE); + +/* Messages */ +event_decl(message_create,MESSAGE_CREATE); +event_decl(message_update,MESSAGE_UPDATE); +event_decl(message_delete,MESSAGE_DELETE); +event_decl(message_delete_bulk,MESSAGE_DELETE_BULK); + +/* Presence/typing */ +event_decl(presence_update,PRESENCE_UPDATE); +event_decl(typing_start,TYPING_START); + +/* Users (outside of guild) */ +event_decl(user_update,USER_UPDATE); + +/* Message reactions */ +event_decl(message_reaction_add,MESSAGE_REACTION_ADD); +event_decl(message_reaction_remove,MESSAGE_REACTION_REMOVE); +event_decl(message_reaction_remove_all,MESSAGE_REACTION_REMOVE_ALL); +event_decl(message_reaction_remove_emoji,MESSAGE_REACTION_REMOVE_EMOJI); + +/* Invites */ +event_decl(invite_create,INVITE_CREATE); +event_decl(invite_delete,INVITE_DELETE); + +/* Voice */ +event_decl(voice_state_update,VOICE_STATE_UPDATE); +event_decl(voice_server_update,VOICE_SERVER_UPDATE); + +/* Webhooks */ +event_decl(webhooks_update,WEBHOOKS_UPDATE); + +/* Application commands */ +event_decl(interaction_create,INTERACTION_CREATE); + +/* Integrations */ +event_decl(integration_create,INTEGRATION_CREATE); +event_decl(integration_update,INTEGRATION_UPDATE); +event_decl(integration_delete,INTEGRATION_DELETE); + +/* Scheduled events */ +event_decl(guild_scheduled_event_create,GUILD_SCHEDULED_EVENT_CREATE); +event_decl(guild_scheduled_event_update,GUILD_SCHEDULED_EVENT_UPDATE); +event_decl(guild_scheduled_event_delete,GUILD_SCHEDULED_EVENT_DELETE); +event_decl(guild_scheduled_event_user_add,GUILD_SCHEDULED_EVENT_USER_ADD); +event_decl(guild_scheduled_event_user_remove,GUILD_SCHEDULED_EVENT_USER_REMOVE); + +/* Auto moderation */ +event_decl(automod_rule_create, AUTO_MODERATION_RULE_CREATE); +event_decl(automod_rule_update, AUTO_MODERATION_RULE_UPDATE); +event_decl(automod_rule_delete, AUTO_MODERATION_RULE_DELETE); +event_decl(automod_rule_execute, AUTO_MODERATION_ACTION_EXECUTION); + +}}; diff --git a/3rdParty/dpp/event_router.h b/3rdParty/dpp/event_router.h index 6532ed8823..fa8bef7816 100644 --- a/3rdParty/dpp/event_router.h +++ b/3rdParty/dpp/event_router.h @@ -1,246 +1,246 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace dpp { - -/** - * @brief A returned event handle for an event which was attached - */ -typedef size_t event_handle; - -/** - * @brief Handles routing of an event to multiple listeners. - * - * Multiple listeners may attach to the event_router_t by means of operator(). Passing a - * lambda into operator() attaches to the event. - * - * Dispatchers of the event may call the event_router_t::call() method to cause all listeners - * to receive the event. - * - * The event_router_t::empty() method will return true if there are no listeners attached - * to the event_router_t (this can be used to save time by not constructing objects that - * nobody will ever see). - * - * The event_router_t::detach() method removes an existing listener from the event, - * using the event_handle ID returned by operator(). - * - * This class is used by the library to route all websocket events to listening code. - * - * Example: - * - * ```cpp - * // Declare an event that takes log_t as its parameter - * event_router_t my_event; - * - * // Attach a listener to the event - * event_handle id = my_event([&](const log_t& cc) { - * std::cout << cc.message << "\n"; - * }); - * - * // Construct a log_t and call the event (listeners will receive the log_t object) - * log_t lt; - * lt.message = "foo"; - * my_event.call(lt); - * - * // Detach from an event using the handle returned by operator() - * my_event.detach(id); - * ``` - * - * @tparam T type of single parameter passed to event lambda derived from event_dispatch_t - */ -template class event_router_t { -private: - friend class cluster; - - event_handle next_handle = 1; - - /** - * @brief Thread safety mutex - */ - mutable std::shared_mutex lock; - /** - * @brief Container of event listeners keyed by handle, - * as handles are handed out sequentially they will always - * be called in they order they are bound to the event - * as std::map is an ordered container. - */ - std::map> dispatch_container; - - -#ifdef DPP_CORO - /** - * @brief Container for event listeners (coroutines only) - */ - std::map> coroutine_container; -#else - /** - * @brief Dummy container to keep the struct size same - */ - std::map> dummy_container; -#endif - - - /** - * @brief A function to be called whenever the method is called, to check - * some condition that is required for this event to trigger correctly. - */ - std::function warning; - - /** - * @brief Next handle to be given out by the event router - */ - -protected: - - /** - * @brief Set the warning callback object used to check that this - * event is capable of running properly - * - * @param warning_function A checking function to call - */ - void set_warning_callback(std::function warning_function) { - warning = warning_function; - } - -public: - /** - * @brief Construct a new event_router_t object. - */ - event_router_t() = default; - - /** - * @brief Call all attached listeners. - * Listeners may cancel, by calling the event.cancel method. - * - * @param event Class to pass as parameter to all listeners. - */ - void call(const T& event) const { - if (warning) { - warning(event); - } - std::shared_lock l(lock); - std::for_each(dispatch_container.begin(), dispatch_container.end(), [&](auto &ev) { - if (!event.is_cancelled()) { - ev.second(event); - } - }); -#ifdef DPP_CORO - std::for_each(coroutine_container.begin(), coroutine_container.end(), [&](auto &ev) { - if (!event.is_cancelled()) { - ev.second(event); - } - }); -#endif - }; - - /** - * @brief Returns true if the container of listeners is empty, - * i.e. there is nothing listening for this event right now. - * - * @return true if there are no listeners - * @return false if there are some listeners - */ - bool empty() const { - std::shared_lock l(lock); - return dispatch_container.empty(); - } - - /** - * @brief Returns true if any listeners are attached. - * - * This is the boolean opposite of event_router_t::empty(). - * @return true if listeners are attached - * @return false if no listeners are attached - */ - operator bool() const { - return !empty(); - } - - /** - * @brief Attach a lambda to the event, adding a listener. - * The lambda should follow the signature specified when declaring - * the event object and should take exactly one parameter derived - * from event_dispatch_t. - * - * @param func Function lambda to attach to event - * @return event_handle An event handle unique to this event, used to - * detach the listener from the event later if necessary. - */ - event_handle operator()(std::function func) { - return this->attach(func); - } - - /** - * @brief Attach a lambda to the event, adding a listener. - * The lambda should follow the signature specified when declaring - * the event object and should take exactly one parameter derived - * from event_dispatch_t. - * - * @param func Function lambda to attach to event - * @return event_handle An event handle unique to this event, used to - * detach the listener from the event later if necessary. - */ - event_handle attach(std::function func) { - std::unique_lock l(lock); - event_handle h = next_handle++; - dispatch_container.emplace(h, func); - return h; - } - -#ifdef DPP_CORO - event_handle co_attach(std::function func) { - std::unique_lock l(lock); - event_handle h = next_handle++; - coroutine_container.emplace(h, func); - return h; - } -#endif - /** - * @brief Detach a listener from the event using a previously obtained ID. - * - * @param handle An ID obtained from event_router_t::operator() - * @return true The event was successfully detached - * @return false The ID is invalid (possibly already detached, or does not exist) - */ - bool detach(const event_handle& handle) { - std::unique_lock l(lock); - return this->dispatch_container.erase(handle); - } -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +/** + * @brief A returned event handle for an event which was attached + */ +typedef size_t event_handle; + +/** + * @brief Handles routing of an event to multiple listeners. + * + * Multiple listeners may attach to the event_router_t by means of operator(). Passing a + * lambda into operator() attaches to the event. + * + * Dispatchers of the event may call the event_router_t::call() method to cause all listeners + * to receive the event. + * + * The event_router_t::empty() method will return true if there are no listeners attached + * to the event_router_t (this can be used to save time by not constructing objects that + * nobody will ever see). + * + * The event_router_t::detach() method removes an existing listener from the event, + * using the event_handle ID returned by operator(). + * + * This class is used by the library to route all websocket events to listening code. + * + * Example: + * + * ```cpp + * // Declare an event that takes log_t as its parameter + * event_router_t my_event; + * + * // Attach a listener to the event + * event_handle id = my_event([&](const log_t& cc) { + * std::cout << cc.message << "\n"; + * }); + * + * // Construct a log_t and call the event (listeners will receive the log_t object) + * log_t lt; + * lt.message = "foo"; + * my_event.call(lt); + * + * // Detach from an event using the handle returned by operator() + * my_event.detach(id); + * ``` + * + * @tparam T type of single parameter passed to event lambda derived from event_dispatch_t + */ +template class event_router_t { +private: + friend class cluster; + + event_handle next_handle = 1; + + /** + * @brief Thread safety mutex + */ + mutable std::shared_mutex lock; + /** + * @brief Container of event listeners keyed by handle, + * as handles are handed out sequentially they will always + * be called in they order they are bound to the event + * as std::map is an ordered container. + */ + std::map> dispatch_container; + + +#ifdef DPP_CORO + /** + * @brief Container for event listeners (coroutines only) + */ + std::map> coroutine_container; +#else + /** + * @brief Dummy container to keep the struct size same + */ + std::map> dummy_container; +#endif + + + /** + * @brief A function to be called whenever the method is called, to check + * some condition that is required for this event to trigger correctly. + */ + std::function warning; + + /** + * @brief Next handle to be given out by the event router + */ + +protected: + + /** + * @brief Set the warning callback object used to check that this + * event is capable of running properly + * + * @param warning_function A checking function to call + */ + void set_warning_callback(std::function warning_function) { + warning = warning_function; + } + +public: + /** + * @brief Construct a new event_router_t object. + */ + event_router_t() = default; + + /** + * @brief Call all attached listeners. + * Listeners may cancel, by calling the event.cancel method. + * + * @param event Class to pass as parameter to all listeners. + */ + void call(const T& event) const { + if (warning) { + warning(event); + } + std::shared_lock l(lock); + std::for_each(dispatch_container.begin(), dispatch_container.end(), [&](auto &ev) { + if (!event.is_cancelled()) { + ev.second(event); + } + }); +#ifdef DPP_CORO + std::for_each(coroutine_container.begin(), coroutine_container.end(), [&](auto &ev) { + if (!event.is_cancelled()) { + ev.second(event); + } + }); +#endif + }; + + /** + * @brief Returns true if the container of listeners is empty, + * i.e. there is nothing listening for this event right now. + * + * @return true if there are no listeners + * @return false if there are some listeners + */ + bool empty() const { + std::shared_lock l(lock); + return dispatch_container.empty(); + } + + /** + * @brief Returns true if any listeners are attached. + * + * This is the boolean opposite of event_router_t::empty(). + * @return true if listeners are attached + * @return false if no listeners are attached + */ + operator bool() const { + return !empty(); + } + + /** + * @brief Attach a lambda to the event, adding a listener. + * The lambda should follow the signature specified when declaring + * the event object and should take exactly one parameter derived + * from event_dispatch_t. + * + * @param func Function lambda to attach to event + * @return event_handle An event handle unique to this event, used to + * detach the listener from the event later if necessary. + */ + event_handle operator()(std::function func) { + return this->attach(func); + } + + /** + * @brief Attach a lambda to the event, adding a listener. + * The lambda should follow the signature specified when declaring + * the event object and should take exactly one parameter derived + * from event_dispatch_t. + * + * @param func Function lambda to attach to event + * @return event_handle An event handle unique to this event, used to + * detach the listener from the event later if necessary. + */ + event_handle attach(std::function func) { + std::unique_lock l(lock); + event_handle h = next_handle++; + dispatch_container.emplace(h, func); + return h; + } + +#ifdef DPP_CORO + event_handle co_attach(std::function func) { + std::unique_lock l(lock); + event_handle h = next_handle++; + coroutine_container.emplace(h, func); + return h; + } +#endif + /** + * @brief Detach a listener from the event using a previously obtained ID. + * + * @param handle An ID obtained from event_router_t::operator() + * @return true The event was successfully detached + * @return false The ID is invalid (possibly already detached, or does not exist) + */ + bool detach(const event_handle& handle) { + std::unique_lock l(lock); + return this->dispatch_container.erase(handle); + } +}; + +}; diff --git a/3rdParty/dpp/exception.h b/3rdParty/dpp/exception.h index ffdc1bdb83..576e67a812 100644 --- a/3rdParty/dpp/exception.h +++ b/3rdParty/dpp/exception.h @@ -1,201 +1,201 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief The dpp::exception class derives from std::exception and supports some other - * ways of passing in error details such as via std::string. - */ -class exception : public std::exception -{ -protected: - /** - * @brief Exception message - */ - std::string msg; - -public: - - using std::exception::exception; - - /** - * @brief Construct a new exception object - */ - exception() = default; - - /** - * @brief Construct a new exception object - * - * @param what reason message - */ - explicit exception(const char* what) : msg(what) { } - - /** - * @brief Construct a new exception object - * - * @param what reason message - * @param len length of reason message - */ - exception(const char* what, size_t len) : msg(what, len) { } - - /** - * @brief Construct a new exception object - * - * @param what reason message - */ - explicit exception(const std::string& what) : msg(what) { } - - /** - * @brief Construct a new exception object - * - * @param what reason message - */ - explicit exception(std::string&& what) : msg(std::move(what)) { } - - /** - * @brief Construct a new exception object (copy constructor) - */ - exception(const exception&) = default; - - /** - * @brief Construct a new exception object (move constructor) - */ - exception(exception&&) = default; - - /** - * @brief Destroy the exception object - */ - ~exception() override = default; - - /** - * @brief Copy assignment operator - * - * @return exception& reference to self - */ - exception & operator = (const exception &) = default; - - /** - * @brief Move assignment operator - * - * @return exception& reference to self - */ - exception & operator = (exception&&) = default; - - /** - * @brief Get exception message - * - * @return const char* error message - */ - [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; - -}; - -#ifndef _DOXYGEN_ - #define derived_exception(name, ancestor) class name : public dpp::ancestor { \ - public: \ - using dpp::ancestor::ancestor; \ - name() = default; \ - explicit name(const char* what) : ancestor(what) { } \ - name(const char* what, size_t len) : ancestor(what, len) { } \ - explicit name(const std::string& what) : ancestor(what) { } \ - explicit name(std::string&& what) : ancestor(what) { } \ - name(const name&) = default; \ - name(name&&) = default; \ - ~name() override = default; \ - name & operator = (const name &) = default; \ - name & operator = (name&&) = default; \ - [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; \ - }; -#endif - -#ifdef _DOXYGEN_ - /* - * THESE DEFINITIONS ARE NOT THE REAL DEFINITIONS USED BY PROGRAM CODE. - * - * They exist only to cause Doxygen to emit proper documentation for the derived exception types. - * Proper definitions are emitted by the `derived_exception` macro in the "else" section. - */ - - /** - * @brief Represents an error in logic, e.g. you asked the library to do something the Discord API does not support - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class logic_exception : public dpp::exception { }; - /** - * @brief Represents an error reading or writing to a file - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class file_exception : public dpp::exception { }; - /** - * @brief Represents an error establishing or maintaining a connection - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class connection_exception : public dpp::exception { }; - /** - * @brief Represents an error with voice processing - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class voice_exception : public dpp::exception { }; - /** - * @brief Represents an error on a REST API call, e.g. a HTTPS request - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class rest_exception : public dpp::exception { }; - /** - * @brief Represents invalid length of argument being passed to a function - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class length_exception : public dpp::exception { }; - /** - * @brief Represents inability to parse data, usually caused by malformed JSON or ETF - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class parse_exception : public dpp::exception { }; - /** - * @brief Represents invalid access to dpp's cache or its members, which may or may not exist. - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class cache_exception : public dpp::exception { }; - /** - * @brief Represents an attempt to construct a cluster with an invalid bot token. - * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. - */ - class invalid_token_exception : public dpp::rest_exception { }; -#else - derived_exception(logic_exception, exception); - derived_exception(file_exception, exception); - derived_exception(connection_exception, exception); - derived_exception(voice_exception, exception); - derived_exception(rest_exception, exception); - derived_exception(invalid_token_exception, rest_exception); - derived_exception(length_exception, exception); - derived_exception(parse_exception, exception); - derived_exception(cache_exception, exception); -#endif - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief The dpp::exception class derives from std::exception and supports some other + * ways of passing in error details such as via std::string. + */ +class exception : public std::exception +{ +protected: + /** + * @brief Exception message + */ + std::string msg; + +public: + + using std::exception::exception; + + /** + * @brief Construct a new exception object + */ + exception() = default; + + /** + * @brief Construct a new exception object + * + * @param what reason message + */ + explicit exception(const char* what) : msg(what) { } + + /** + * @brief Construct a new exception object + * + * @param what reason message + * @param len length of reason message + */ + exception(const char* what, size_t len) : msg(what, len) { } + + /** + * @brief Construct a new exception object + * + * @param what reason message + */ + explicit exception(const std::string& what) : msg(what) { } + + /** + * @brief Construct a new exception object + * + * @param what reason message + */ + explicit exception(std::string&& what) : msg(std::move(what)) { } + + /** + * @brief Construct a new exception object (copy constructor) + */ + exception(const exception&) = default; + + /** + * @brief Construct a new exception object (move constructor) + */ + exception(exception&&) = default; + + /** + * @brief Destroy the exception object + */ + ~exception() override = default; + + /** + * @brief Copy assignment operator + * + * @return exception& reference to self + */ + exception & operator = (const exception &) = default; + + /** + * @brief Move assignment operator + * + * @return exception& reference to self + */ + exception & operator = (exception&&) = default; + + /** + * @brief Get exception message + * + * @return const char* error message + */ + [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; + +}; + +#ifndef _DOXYGEN_ + #define derived_exception(name, ancestor) class name : public dpp::ancestor { \ + public: \ + using dpp::ancestor::ancestor; \ + name() = default; \ + explicit name(const char* what) : ancestor(what) { } \ + name(const char* what, size_t len) : ancestor(what, len) { } \ + explicit name(const std::string& what) : ancestor(what) { } \ + explicit name(std::string&& what) : ancestor(what) { } \ + name(const name&) = default; \ + name(name&&) = default; \ + ~name() override = default; \ + name & operator = (const name &) = default; \ + name & operator = (name&&) = default; \ + [[nodiscard]] const char* what() const noexcept override { return msg.c_str(); }; \ + }; +#endif + +#ifdef _DOXYGEN_ + /* + * THESE DEFINITIONS ARE NOT THE REAL DEFINITIONS USED BY PROGRAM CODE. + * + * They exist only to cause Doxygen to emit proper documentation for the derived exception types. + * Proper definitions are emitted by the `derived_exception` macro in the "else" section. + */ + + /** + * @brief Represents an error in logic, e.g. you asked the library to do something the Discord API does not support + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class logic_exception : public dpp::exception { }; + /** + * @brief Represents an error reading or writing to a file + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class file_exception : public dpp::exception { }; + /** + * @brief Represents an error establishing or maintaining a connection + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class connection_exception : public dpp::exception { }; + /** + * @brief Represents an error with voice processing + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class voice_exception : public dpp::exception { }; + /** + * @brief Represents an error on a REST API call, e.g. a HTTPS request + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class rest_exception : public dpp::exception { }; + /** + * @brief Represents invalid length of argument being passed to a function + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class length_exception : public dpp::exception { }; + /** + * @brief Represents inability to parse data, usually caused by malformed JSON or ETF + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class parse_exception : public dpp::exception { }; + /** + * @brief Represents invalid access to dpp's cache or its members, which may or may not exist. + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class cache_exception : public dpp::exception { }; + /** + * @brief Represents an attempt to construct a cluster with an invalid bot token. + * @note This is a stub for documentation purposes. For full information on supported methods please see dpp::exception. + */ + class invalid_token_exception : public dpp::rest_exception { }; +#else + derived_exception(logic_exception, exception); + derived_exception(file_exception, exception); + derived_exception(connection_exception, exception); + derived_exception(voice_exception, exception); + derived_exception(rest_exception, exception); + derived_exception(invalid_token_exception, rest_exception); + derived_exception(length_exception, exception); + derived_exception(parse_exception, exception); + derived_exception(cache_exception, exception); +#endif + +}; + diff --git a/3rdParty/dpp/export.h b/3rdParty/dpp/export.h index 5fc9ac465b..423729c98d 100644 --- a/3rdParty/dpp/export.h +++ b/3rdParty/dpp/export.h @@ -1,66 +1,66 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -/* Compile-time check for C++17. - * Either one of the following causes a compile time error: - * __cplusplus not defined at all (this means we are being compiled on a C compiler) - * MSVC defined and _MSVC_LANG < 201703L (Visual Studio, but not C++17 or newer) - * MSVC not defined and __cplusplus < 201703L (Non-visual studio, but not C++17 or newer) - * The additional checks are required because MSVC doesn't correctly set __cplusplus to 201703L, - * which is hugely non-standard, but apparently "it broke stuff" so they dont ever change it - * from C++98. Ugh. - */ -#if (!defined(__cplusplus) || (defined(_MSC_VER) && (!defined(_MSVC_LANG) || _MSVC_LANG < 201703L)) || (!defined(_MSC_VER) && __cplusplus < 201703L)) - #error "D++ Requires a C++17 compatible C++ compiler. Please ensure that you have enabled C++17 in your compiler flags." -#endif - -#ifndef DPP_STATIC - /* Dynamic linked build as shared object or dll */ - #ifdef DPP_BUILD - /* Building the library */ - #ifdef _WIN32 - #include - #define DPP_EXPORT __declspec(dllexport) - #else - #define DPP_EXPORT - #endif - #else - /* Including the library */ - #ifdef _WIN32 - #define DPP_EXPORT __declspec(dllimport) - #else - #define DPP_EXPORT - #endif - #endif -#else - /* Static linked build */ - #if defined(_WIN32) && defined(DPP_BUILD) - #include - #endif - #define DPP_EXPORT -#endif - -#ifndef _WIN32 - #define SOCKET int -#else - #include +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +/* Compile-time check for C++17. + * Either one of the following causes a compile time error: + * __cplusplus not defined at all (this means we are being compiled on a C compiler) + * MSVC defined and _MSVC_LANG < 201703L (Visual Studio, but not C++17 or newer) + * MSVC not defined and __cplusplus < 201703L (Non-visual studio, but not C++17 or newer) + * The additional checks are required because MSVC doesn't correctly set __cplusplus to 201703L, + * which is hugely non-standard, but apparently "it broke stuff" so they dont ever change it + * from C++98. Ugh. + */ +#if (!defined(__cplusplus) || (defined(_MSC_VER) && (!defined(_MSVC_LANG) || _MSVC_LANG < 201703L)) || (!defined(_MSC_VER) && __cplusplus < 201703L)) + #error "D++ Requires a C++17 compatible C++ compiler. Please ensure that you have enabled C++17 in your compiler flags." +#endif + +#ifndef DPP_STATIC + /* Dynamic linked build as shared object or dll */ + #ifdef DPP_BUILD + /* Building the library */ + #ifdef _WIN32 + #include + #define DPP_EXPORT __declspec(dllexport) + #else + #define DPP_EXPORT + #endif + #else + /* Including the library */ + #ifdef _WIN32 + #define DPP_EXPORT __declspec(dllimport) + #else + #define DPP_EXPORT + #endif + #endif +#else + /* Static linked build */ + #if defined(_WIN32) && defined(DPP_BUILD) + #include + #endif + #define DPP_EXPORT +#endif + +#ifndef _WIN32 + #define SOCKET int +#else + #include #endif \ No newline at end of file diff --git a/3rdParty/dpp/guild.h b/3rdParty/dpp/guild.h index 48f7e3fbd6..0684705c65 100644 --- a/3rdParty/dpp/guild.h +++ b/3rdParty/dpp/guild.h @@ -1,980 +1,980 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -class channel; - -/** - * @brief Represents voice regions for guilds and channels. - * @deprecated Deprecated in favour of per-channel regions. - * Please use channel::rtc_region instead. - */ -enum region : uint8_t { - r_brazil, //!< Brazil - r_central_europe, //!< Central Europe - r_hong_kong, //!< Hong Kong - r_india, //!< India - r_japan, //!< Japan - r_russia, //!< Russia - r_singapore, //!< Singapore - r_south_africa, //!< South Africa - r_sydney, //!< Sydney - r_us_central, //!< US Central - r_us_east, //!< US East Coast - r_us_south, //!< US South - r_us_west, //!< US West Coast - r_western_europe //!< Western Europe -}; - -/** - * @brief The various flags that represent the status of a dpp::guild object - */ -enum guild_flags : uint32_t { - /** Large guild */ - g_large = 0b00000000000000000000000000000001, - /** Unavailable guild (inaccessible due to an outage) */ - g_unavailable = 0b00000000000000000000000000000010, - /** Guild has widget enabled */ - g_widget_enabled = 0b00000000000000000000000000000100, - /** Guild can have an invite splash image */ - g_invite_splash = 0b00000000000000000000000000001000, - /** Guild can have VIP regions */ - g_vip_regions = 0b00000000000000000000000000010000, - /** Guild can have a vanity url */ - g_vanity_url = 0b00000000000000000000000000100000, - /** Guild is verified */ - g_verified = 0b00000000000000000000000001000000, - /** Guild is partnered */ - g_partnered = 0b00000000000000000000000010000000, - /** Community features enabled */ - g_community = 0b00000000000000000000000100000000, - /** Guild has commerce features enabled - * @deprecated Removed by Discord - */ - g_commerce = 0b00000000000000000000001000000000, - /** Guild has access to create announcement channels */ - g_news = 0b00000000000000000000010000000000, - /** Guild is discoverable in discovery */ - g_discoverable = 0b00000000000000000000100000000000, - /** Guild is featureable */ - g_featureable = 0b00000000000000000001000000000000, - /** Guild can have an animated icon (doesn't mean it actually has one though) */ - g_animated_icon = 0b00000000000000000010000000000000, - /** Guild can have a banner image */ - g_banner = 0b00000000000000000100000000000000, - /** Guild has a welcome screen */ - g_welcome_screen_enabled = 0b00000000000000001000000000000000, - /** Guild has a member verification gate */ - g_member_verification_gate = 0b00000000000000010000000000000000, - /** Guild has a preview */ - g_preview_enabled = 0b00000000000000100000000000000000, - /** Guild join notifications are off */ - g_no_join_notifications = 0b00000000000001000000000000000000, - /** Guild boost notifications are off */ - g_no_boost_notifications = 0b00000000000010000000000000000000, - /** Guild has an actual animated icon (set by the icon hash starting with 'a_') */ - g_has_animated_icon = 0b00000000000100000000000000000000, - /** Guild has an actual animated banner (set by the icon hash starting with 'a_') */ - g_has_animated_banner = 0b00000000001000000000000000000000, - /** Guild setup tips are off */ - g_no_setup_tips = 0b00000000010000000000000000000000, - /** "Wave to say hi" sticker prompt buttons are off */ - g_no_sticker_greeting = 0b00000000100000000000000000000000, - /** guild has enabled monetization */ - g_monetization_enabled = 0b00000001000000000000000000000000, - /** guild has increased custom sticker slots */ - g_more_stickers = 0b00000010000000000000000000000000, - /** guild has access to create private threads - * @deprecated Removed by Discord - * */ - g_private_threads = 0b00000100000000000000000000000000, - /** guild is able to set role icons */ - g_role_icons = 0b00001000000000000000000000000000, - /** guild has access to the seven day archive time for threads */ - g_seven_day_thread_archive = 0b00010000000000000000000000000000, - /** guild has access to the three day archive time for threads */ - g_three_day_thread_archive = 0b00100000000000000000000000000000, - /** guild has enabled ticketed events */ - g_ticketed_events = 0b01000000000000000000000000000000, - /** guild can have channel banners */ - g_channel_banners = 0b10000000000000000000000000000000, -}; - -/** - * @brief Additional boolean flag values for guild, as guild_flags is full - */ -enum guild_flags_extra : uint8_t { - /** Guild has premium progress bar enabled */ - g_premium_progress_bar_enabled = 0b00000001, - /** Guild can have an animated banner (doesn't mean it actually has one though) */ - g_animated_banner = 0b00000010, - /** Guild has auto moderation */ - g_auto_moderation = 0b00000100, - /** Guild has paused invites, preventing new users from joining */ - g_invites_disabled = 0b00001000, - /** Guild has been set as support server of an app in the App Directory */ - g_developer_support_server = 0b00010000, -}; - -/** - * @brief Various flags that can be used to indicate the status of a guild member. - * @note Use set_mute and set_deaf member functions and do not toggle the bits yourself. - */ -enum guild_member_flags : uint8_t { - /** Member deafened in voice channels */ - gm_deaf = 0b00000001, - /** Member muted in voice channels */ - gm_mute = 0b00000010, - /** Member pending verification by membership screening */ - gm_pending = 0b00000100, - /** Member has animated guild-specific avatar */ - gm_animated_avatar = 0b00001000, - /** gm_deaf or gm_mute has been toggled */ - gm_voice_action = 0b00010000, -}; - -/** - * @brief Represents dpp::user membership upon a dpp::guild. - * This contains the user's nickname, guild roles, and any other guild-specific flags. - */ -class DPP_EXPORT guild_member { -public: - /** Nickname, or empty string if they don't have a nickname on this guild */ - std::string nickname; - /** List of roles this user has on this guild */ - std::vector roles; - /** Guild id */ - snowflake guild_id; - /** User id */ - snowflake user_id; - /** User avatar (per-server avatar is a nitro only feature) */ - utility::iconhash avatar; - /** timestamp of when the time out will be removed; until then, they cannot interact with the guild */ - time_t communication_disabled_until; - /** Date and time the user joined the guild */ - time_t joined_at; - /** Boosting since */ - time_t premium_since; - /** A set of flags built from the bitmask defined by dpp::guild_member_flags */ - uint8_t flags; - - /** Default constructor */ - guild_member(); - - /** Fill this object from a json object. - * @param j The json object to get data from - * @param g_id The guild id to associate the member with - * @param u_id The user id to associate the member with - * @return Reference to self for call chaining - */ - guild_member& fill_from_json(nlohmann::json* j, snowflake g_id, snowflake u_id); - - /** - * @brief Build json string for the member object - * - * @param with_id Add ID to output - * @return std::string json string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Returns true if the user is in time-out (communication disabled) - * - * @return true user is in time-out - * @return false user is not in time-out - */ - bool is_communication_disabled() const; - - /** - * @brief Returns true if the user is deafened - * - * @return true user is deafened - * @return false user is not deafened - */ - bool is_deaf() const; - - /** - * @brief Returns true if the user is muted - * - * @return true user muted - * @return false user not muted - */ - bool is_muted() const; - - /** - * @brief Returns true if pending verification by membership screening - * - * @return true user has completed membership screening - * @return false user has not completed membership screening - */ - bool is_pending() const; - - /** - * @brief Returns true if the user's per-guild custom avatar is animated - * - * @return true user's custom avatar is animated - * @return false user's custom avatar is not animated - */ - bool has_animated_guild_avatar() const; - - /** - * @brief Returns the members per guild avatar if they have one, otherwise returns an empty string - * - * @note per-server avatar is a nitro only feature so it might be not set. If you need the real user avatar, use user::get_avatar_url. - * - * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized avatar is returned. - * @return std::string avatar url or empty string - */ - std::string get_avatar_url(uint16_t size = 0) const; - - /** - * @brief Set the nickname - * - * @param nick Nickname to set - * - * @return guild_member& reference to self - */ - guild_member& set_nickname(const std::string& nick); - - /** - * @brief Get the dpp::user object for this member - * @return dpp::user user object. If not in cache, it returns nullptr - * - * - */ - dpp::user* get_user() const; - - /** - * @brief Set whether the user is muted in voice channels - * - * @param is_muted value to set, true if mute in voice channels - * - * @return guild_member& reference to self - */ - guild_member& set_mute(const bool is_muted); - - /** - * @brief Set whether the user is deafened in voice channels - * - * @param is_deafened value to set, true if deaf in voice channels - * - * @return guild_member& reference to self - */ - guild_member& set_deaf(const bool is_deafened); - - /** - * @brief Set communication_disabled_until - * - * @param timestamp timestamp until communication is disabled - * - * @return guild_member& reference to self - */ - guild_member& set_communication_disabled_until(const time_t timestamp); - - /** - * @brief Return a ping/mention for the user by nickname - * - * @return std::string mention - */ - std::string get_mention() const; -}; - -/** - * @brief Defines a channel on a server's welcome screen - */ -struct welcome_channel_t { - /// the description shown for the channel - std::string description; - /// the emoji name if custom, the unicode character if standard, or null if no emoji is set - std::string emoji_name; - /// the channel's id - snowflake channel_id = 0; - /// the emoji id, if the emoji is custom - snowflake emoji_id = 0; -}; - - -/** - * @brief Defines a server's welcome screen - */ -struct welcome_screen_t { - /// the server description shown in the welcome screen - std::string description; - /// the channels shown in the welcome screen, up to 5 - std::vector welcome_channels; -}; - -/** - * @brief Guild NSFW level. - * Used to represent just how naughty this guild is. Naughty guild, go sit in the corner. - * @note This is set by Discord, and cannot be set by any bot or user on the guild. - */ -enum guild_nsfw_level_t : uint8_t { - /// Default setting, not configured - nsfw_default = 0, - /// Explicit content may be in this guild - nsfw_explicit = 1, - /// Safe for work content only - nsfw_safe = 2, - /// Age restricted, 18+ - nsfw_age_restricted = 3 -}; - -/** - * @brief explicit content filter level. - * This is set by a guild admin, but can be forced to a setting if the server is verified, - * partnered, official etc. - */ -enum guild_explicit_content_t : uint8_t { - /// media content will not be scanned - expl_disabled = 0, - /// media content sent by members without roles will be scanned - expl_members_without_roles = 1, - /// media content sent by all members will be scanned - expl_all_members = 2 -}; - -/** - * @brief MFA level for server. If set to elevated all moderators need MFA to perform specific - * actions such as kick or ban. - */ -enum mfa_level_t : uint8_t { - /// MFA not elevated - mfa_none = 0, - /// MFA elevated - mfa_elevated = 1 -}; - -/** - * @brief Guild verification level - */ -enum verification_level_t : uint8_t { - /// unrestricted - ver_none = 0, - /// must have verified email on account - ver_low = 1, - /// must be registered on Discord for longer than 5 minutes - ver_medium = 2, - /// must be a member of the server for longer than 10 minutes - ver_high = 3, - /// must have a verified phone number - ver_very_high = 4, -}; - -/** - * @brief Default message notification level - */ -enum default_message_notification_t: uint8_t { - /// members will receive notifications for all messages by default - dmn_all = 0, - /// members will receive notifications only for messages that \@mention them by default - dmn_only_mentions = 1, -}; - -/** - * @brief Premium tier - */ -enum guild_premium_tier_t: uint8_t { - /// guild has not unlocked any Server Boost perks - tier_none = 0, - /// guild has unlocked Server Boost level 1 perks - tier_1 = 1, - /// guild has unlocked Server Boost level 2 perks - tier_2 = 2, - /// guild has unlocked Server Boost level 3 perks - tier_3 = 3, -}; - -/** - * @brief Voice AFK timeout values for guild::afk_timeout - */ -enum guild_afk_timeout_t: uint8_t { - /// AFK timeout disabled - afk_off, - /// AFK timeout of 1 Minute - afk_60, - /// AFK timeout of 5 Minutes - afk_300, - /// AFK timeout of 15 Minutes - afk_900, - /// AFK timeout of 30 Minutes - afk_1800, - /// AFK timeout of 1 Hour - afk_3600, -}; - -/** @brief Guild members container - */ -typedef std::unordered_map members_container; - -/** - * @brief Represents a guild on Discord (AKA a server) - */ -class DPP_EXPORT guild : public managed, public json_interface { -public: - /** Guild name */ - std::string name; - - /** Server description */ - std::string description; - - /** - * @brief Vanity url code for verified or partnered servers and boost level 3 - * @note This field cannot be set from the API. Attempts to change this value will be - * silently ignored even if the correct number of boosts or verified/partnered status exist. - * See: https://github.com/discord/discord-api-docs/issues/519 - */ - std::string vanity_url_code; - - /** Roles defined on this server */ - std::vector roles; - - /** List of channels on this server */ - std::vector channels; - - /** List of threads on this server */ - std::vector threads; - - /** List of emojis - */ - std::vector emojis; - - /** List of members in voice channels in the guild. - */ - std::map voice_members; - - /** List of guild members. Note that when you first receive the - * guild create event, this may be empty or near empty. - * This depends upon your dpp::intents and the size of your bot. - * It will be filled by guild member chunk requests. - */ - members_container members; - - /** Welcome screen - */ - welcome_screen_t welcome_screen; - - /** Guild icon hash */ - utility::iconhash icon; - - /** Guild splash hash */ - utility::iconhash splash; - - /** Guild discovery splash hash */ - utility::iconhash discovery_splash; - - /** Server banner hash */ - utility::iconhash banner; - - /** Snowflake id of guild owner */ - snowflake owner_id; - - /** Snowflake ID of AFK voice channel or 0 */ - snowflake afk_channel_id; - - /** ID of creating application, if any, or 0 */ - snowflake application_id; - - /** ID of system channel where discord update messages are sent */ - snowflake system_channel_id; - - /** ID of rules channel for communities */ - snowflake rules_channel_id; - - /** Public updates channel id or 0 */ - snowflake public_updates_channel_id; - - /** Snowflake ID of widget channel, or 0 */ - snowflake widget_channel_id; - - /** Approximate member count. May be sent as zero */ - uint32_t member_count; - - /** Flags bitmask as defined by values within dpp::guild_flags */ - uint32_t flags; - - /** - * @brief the maximum number of presences for the guild. - * @note Generally Discord always fills this with 0, apart from for the largest of guilds - */ - uint32_t max_presences; - - /** - * @brief the maximum number of members for the guild - */ - uint32_t max_members; - - /** Shard ID of the guild */ - uint16_t shard_id; - - /** Number of boosters */ - uint16_t premium_subscription_count; - - /** Voice AFK timeout before moving users to AFK channel */ - guild_afk_timeout_t afk_timeout; - - /** Maximum users in a video channel, or 0 */ - uint8_t max_video_channel_users; - - /** Setting for how notifications are to be delivered to users */ - default_message_notification_t default_message_notifications; - - /** Boost level */ - guild_premium_tier_t premium_tier; - - /** Verification level of server */ - verification_level_t verification_level; - - /** Whether or not explicit content filtering is enable and what setting it is */ - guild_explicit_content_t explicit_content_filter; - - /** If multi factor authentication is required for moderators or not */ - mfa_level_t mfa_level; - - /** - * @brief Guild NSFW level - */ - guild_nsfw_level_t nsfw_level; - - /** - * @brief Additional flags - */ - uint8_t flags_extra; - - /** Default constructor, zeroes all values */ - guild(); - - /** - * @brief Destroy the guild object - */ - virtual ~guild() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - guild& fill_from_json(nlohmann::json* j); - - /** Read class values from json object - * @param shard originating shard - * @param j A json object to read from - * @return A reference to self - */ - guild& fill_from_json(class discord_client* shard, nlohmann::json* j); - - /** Build a JSON string from this object. - * @param with_id True if an ID is to be included in the JSON - * @return JSON string - */ - std::string build_json(bool with_id = false) const; - - /** - * @brief Compute the base permissions for a member on this guild, - * before channel overwrites are applied. - * This method takes into consideration the following cases: - * - Guild owner - * - Guild roles including \@everyone - * - * @param user User to get permissions for - * @return permission permissions bitmask - * @note Requires role cache to be enabled (it's enabled by default). - * - * @warning The method will search for the guild member in the cache by the users id. - * If the guild member is not in cache, the method will always return 0. - */ - permission base_permissions(const class user* user) const; - - /** - * @brief Compute the base permissions for a member on this guild, - * before channel overwrites are applied. - * This method takes into consideration the following cases: - * - Guild owner - * - Guild roles including \@everyone - * - * @param member member to get permissions for - * @return permission permissions bitmask - * @note Requires role cache to be enabled (it's enabled by default). - */ - permission base_permissions(const guild_member &member) const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param base_permissions base permissions before overwrites, - * from guild::base_permissions - * @param user The user to resolve the permissions for - * @param channel Channel to compute permission overwrites for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - * - * @warning The method will search for the guild member in the cache by the users id. - * If the guild member is not in cache, the method will always return 0. - */ - permission permission_overwrites(const uint64_t base_permissions, const user* user, const channel* channel) const; - - /** - * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. - * - * @param member The member to resolve the permissions for - * @param channel Channel to compute permission overwrites for - * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. - * @note Requires role cache to be enabled (it's enabled by default). - */ - permission permission_overwrites(const guild_member &member, const channel &channel) const; - - /** - * @brief Rehash members map - */ - void rehash_members(); - - /** - * @brief Connect to a voice channel another guild member is in - * - * @param user_id User id to join - * @param self_mute True if the bot should mute itself - * @param self_deaf True if the bot should deafen itself - * @return True if the user specified is in a vc, false if they aren't - * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, - * as we have to wait for the connection to the voice server to be established! - * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. - */ - bool connect_member_voice(snowflake user_id, bool self_mute = false, bool self_deaf = false); - - /** - * @brief Get the banner url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. - * @return std::string banner url or empty string - */ - std::string get_banner_url(uint16_t size = 0) const; - - /** - * @brief Get the discovery splash url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the discovery splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized discovery splash is returned. - * @return std::string discovery splash url or empty string - */ - std::string get_discovery_splash_url(uint16_t size = 0) const; - - /** - * @brief Get the icon url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; - - /** - * @brief Get the splash url of the guild if it have one, otherwise returns an empty string - * - * @param size The size of the splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized splash is returned. - * @return std::string splash url or empty string - */ - std::string get_splash_url(uint16_t size = 0) const; - - /** - * @brief Set the name of the guild in the object - * Min length: 2, Max length: 100 (not including leading/trailing spaces) - * @param n Guild name - * @return guild& reference to self - * @throw dpp::length_exception if guild name is too short - */ - guild& set_name(const std::string& n); - - /** - * @brief Is a large server (>250 users) - * @return bool is a large guild - */ - bool is_large() const; - - /** - * @brief Is unavailable due to outage (most other fields will be blank or outdated - * @return bool is unavailable - */ - bool is_unavailable() const; - - /** - * @brief Widget is enabled for this server - * @return bool widget enabled - */ - bool widget_enabled() const; - - /** - * @brief Guild has access to set an invite splash background - * @return bool can have an invite splash - */ - bool has_invite_splash() const; - - /** - * @brief Guild has access to set 384kbps bitrate in voice - * @return bool can have VIP voice regions - */ - bool has_vip_regions() const; - - /** - * @brief Guild has access to set a vanity URL - * @return bool can have vanity url - */ - bool has_vanity_url() const; - - /** - * @brief Guild is a verified server - * @return bool is verified - */ - bool is_verified() const; - - /** - * @brief Guild is a discord partnered server - * @return bool is discord partnered - */ - bool is_partnered() const; - - /** - * @brief Has enabled community - * @return bool has enabled community - */ - bool is_community() const; - - /** - * @brief Guild has access to use commerce features - * @return bool has commerce features enabled - * @deprecated Removed by Discord - */ - bool has_commerce() const; - - /** - * @brief Guild has access to create announcement channels - * @return bool has announcement channels features enabled - */ - bool has_news() const; - - /** - * @brief Guild is discoverable - * @return bool is discoverable - */ - bool is_discoverable() const; - - /** - * @brief Guild is featurable - * @return bool is featurable - */ - bool is_featureable() const; - - /** - * @brief Guild has access to set an animated guild banner image - * @return bool can have animated banner image - */ - bool has_animated_banner() const; - - /** - * @brief Guild has auto moderation features - * @return bool has auto moderation features - */ - bool has_auto_moderation() const; - - /** - * @brief Guild has been set as a support server on the App Directory - * @return bool has been set as a support server of an app in the app directory - */ - bool has_support_server() const; - - /** - * @brief Guild has access to set an animated guild icon - * @return bool can have animated icon - */ - bool has_animated_icon() const; - - /** - * @brief Guild has access to set a guild banner image - * @return bool can have banner image - */ - bool has_banner() const; - - /** - * @brief Guild has enabled the welcome screen - * @return bool enabled welcome screen - */ - bool is_welcome_screen_enabled() const; - - /** - * @brief Guild has enabled membership screening - * @return bool has membership screening - */ - bool has_member_verification_gate() const; - - /** - * @brief Guild has preview enabled - * @return bool has preview - */ - bool is_preview_enabled() const; - - /** - * @brief Guild icon is actually an animated gif - * @return bool is animated gif - */ - bool has_animated_icon_hash() const; - - /** - * @brief Guild banner is actually an animated gif - * @return bool is animated gif - */ - bool has_animated_banner_hash() const; - - - /** - * @brief guild has access to monetization features - * @return bool - */ - bool has_monetization_enabled() const; - - /** - * @brief guild has increased custom sticker slots - * @return bool has more stickers - */ - bool has_more_stickers() const; - - /** - * @brief guild has access to create private threads - * @return bool has private threads - * @deprecated Removed by Discord - */ - bool has_private_threads() const; - - /** - * @brief guild is able to set role icons - * @return bool has role icons - */ - bool has_role_icons() const; - - /** - * @brief guild has access to the seven day archive time for threads - * @return bool has seven day thread archive - */ - bool has_seven_day_thread_archive() const; - - /** - * @brief guild has access to the three day archive time for threads - * @return bool has three day thread archive - */ - bool has_three_day_thread_archive() const; - - /** - * @brief guild has enabled ticketed events - * @return bool has ticketed events - */ - bool has_ticketed_events() const; - - /** - * @brief guild has access to channel banners feature - * @return bool has channel banners - */ - bool has_channel_banners() const; - - /** - * @brief True if the premium progress bar is enabled - * @return bool has progress bar enabled - */ - bool has_premium_progress_bar_enabled() const; - - /** - * @brief True if has paused invites, preventing new users from joining - * @return bool has paused invites - */ - bool has_invites_disabled() const; -}; - -/** A container of guilds */ -typedef std::unordered_map guild_map; - -/** - * @brief Represents a guild widget, simple web widget of member list - */ -class DPP_EXPORT guild_widget { -public: - /** - * @brief Channel widget points to - */ - snowflake channel_id; - - /** - * @brief True if enabled - */ - bool enabled; - - /** - * @brief Construct a new guild widget object - */ - guild_widget(); - - /** - * @brief Build a guild widget from json - * - * @param j json to build from - * @return guild_widget& reference to self - */ - guild_widget& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json for a guild widget - * - * @param with_id Add ID to output - * @return std::string guild widget stringified json - */ - std::string build_json(bool with_id = false) const; -}; - -/** - * @brief helper function to deserialize a guild_member from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param gm guild_member to be deserialized - */ -void from_json(const nlohmann::json& j, guild_member& gm); - -/** A container of guild members */ -typedef std::unordered_map guild_member_map; - -/** - * @brief Get the guild_member from cache of given IDs - * - * @param guild_id ID of the guild to find guild_member for - * @param user_id ID of the user to find guild_member for - * - * @throw dpp::cache_exception if the guild or guild_member is not found in the cache - * @return guild_member the cached object, if found - */ -guild_member DPP_EXPORT find_guild_member(const snowflake guild_id, const snowflake user_id); - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +class channel; + +/** + * @brief Represents voice regions for guilds and channels. + * @deprecated Deprecated in favour of per-channel regions. + * Please use channel::rtc_region instead. + */ +enum region : uint8_t { + r_brazil, //!< Brazil + r_central_europe, //!< Central Europe + r_hong_kong, //!< Hong Kong + r_india, //!< India + r_japan, //!< Japan + r_russia, //!< Russia + r_singapore, //!< Singapore + r_south_africa, //!< South Africa + r_sydney, //!< Sydney + r_us_central, //!< US Central + r_us_east, //!< US East Coast + r_us_south, //!< US South + r_us_west, //!< US West Coast + r_western_europe //!< Western Europe +}; + +/** + * @brief The various flags that represent the status of a dpp::guild object + */ +enum guild_flags : uint32_t { + /** Large guild */ + g_large = 0b00000000000000000000000000000001, + /** Unavailable guild (inaccessible due to an outage) */ + g_unavailable = 0b00000000000000000000000000000010, + /** Guild has widget enabled */ + g_widget_enabled = 0b00000000000000000000000000000100, + /** Guild can have an invite splash image */ + g_invite_splash = 0b00000000000000000000000000001000, + /** Guild can have VIP regions */ + g_vip_regions = 0b00000000000000000000000000010000, + /** Guild can have a vanity url */ + g_vanity_url = 0b00000000000000000000000000100000, + /** Guild is verified */ + g_verified = 0b00000000000000000000000001000000, + /** Guild is partnered */ + g_partnered = 0b00000000000000000000000010000000, + /** Community features enabled */ + g_community = 0b00000000000000000000000100000000, + /** Guild has commerce features enabled + * @deprecated Removed by Discord + */ + g_commerce = 0b00000000000000000000001000000000, + /** Guild has access to create announcement channels */ + g_news = 0b00000000000000000000010000000000, + /** Guild is discoverable in discovery */ + g_discoverable = 0b00000000000000000000100000000000, + /** Guild is featureable */ + g_featureable = 0b00000000000000000001000000000000, + /** Guild can have an animated icon (doesn't mean it actually has one though) */ + g_animated_icon = 0b00000000000000000010000000000000, + /** Guild can have a banner image */ + g_banner = 0b00000000000000000100000000000000, + /** Guild has a welcome screen */ + g_welcome_screen_enabled = 0b00000000000000001000000000000000, + /** Guild has a member verification gate */ + g_member_verification_gate = 0b00000000000000010000000000000000, + /** Guild has a preview */ + g_preview_enabled = 0b00000000000000100000000000000000, + /** Guild join notifications are off */ + g_no_join_notifications = 0b00000000000001000000000000000000, + /** Guild boost notifications are off */ + g_no_boost_notifications = 0b00000000000010000000000000000000, + /** Guild has an actual animated icon (set by the icon hash starting with 'a_') */ + g_has_animated_icon = 0b00000000000100000000000000000000, + /** Guild has an actual animated banner (set by the icon hash starting with 'a_') */ + g_has_animated_banner = 0b00000000001000000000000000000000, + /** Guild setup tips are off */ + g_no_setup_tips = 0b00000000010000000000000000000000, + /** "Wave to say hi" sticker prompt buttons are off */ + g_no_sticker_greeting = 0b00000000100000000000000000000000, + /** guild has enabled monetization */ + g_monetization_enabled = 0b00000001000000000000000000000000, + /** guild has increased custom sticker slots */ + g_more_stickers = 0b00000010000000000000000000000000, + /** guild has access to create private threads + * @deprecated Removed by Discord + * */ + g_private_threads = 0b00000100000000000000000000000000, + /** guild is able to set role icons */ + g_role_icons = 0b00001000000000000000000000000000, + /** guild has access to the seven day archive time for threads */ + g_seven_day_thread_archive = 0b00010000000000000000000000000000, + /** guild has access to the three day archive time for threads */ + g_three_day_thread_archive = 0b00100000000000000000000000000000, + /** guild has enabled ticketed events */ + g_ticketed_events = 0b01000000000000000000000000000000, + /** guild can have channel banners */ + g_channel_banners = 0b10000000000000000000000000000000, +}; + +/** + * @brief Additional boolean flag values for guild, as guild_flags is full + */ +enum guild_flags_extra : uint8_t { + /** Guild has premium progress bar enabled */ + g_premium_progress_bar_enabled = 0b00000001, + /** Guild can have an animated banner (doesn't mean it actually has one though) */ + g_animated_banner = 0b00000010, + /** Guild has auto moderation */ + g_auto_moderation = 0b00000100, + /** Guild has paused invites, preventing new users from joining */ + g_invites_disabled = 0b00001000, + /** Guild has been set as support server of an app in the App Directory */ + g_developer_support_server = 0b00010000, +}; + +/** + * @brief Various flags that can be used to indicate the status of a guild member. + * @note Use set_mute and set_deaf member functions and do not toggle the bits yourself. + */ +enum guild_member_flags : uint8_t { + /** Member deafened in voice channels */ + gm_deaf = 0b00000001, + /** Member muted in voice channels */ + gm_mute = 0b00000010, + /** Member pending verification by membership screening */ + gm_pending = 0b00000100, + /** Member has animated guild-specific avatar */ + gm_animated_avatar = 0b00001000, + /** gm_deaf or gm_mute has been toggled */ + gm_voice_action = 0b00010000, +}; + +/** + * @brief Represents dpp::user membership upon a dpp::guild. + * This contains the user's nickname, guild roles, and any other guild-specific flags. + */ +class DPP_EXPORT guild_member { +public: + /** Nickname, or empty string if they don't have a nickname on this guild */ + std::string nickname; + /** List of roles this user has on this guild */ + std::vector roles; + /** Guild id */ + snowflake guild_id; + /** User id */ + snowflake user_id; + /** User avatar (per-server avatar is a nitro only feature) */ + utility::iconhash avatar; + /** timestamp of when the time out will be removed; until then, they cannot interact with the guild */ + time_t communication_disabled_until; + /** Date and time the user joined the guild */ + time_t joined_at; + /** Boosting since */ + time_t premium_since; + /** A set of flags built from the bitmask defined by dpp::guild_member_flags */ + uint8_t flags; + + /** Default constructor */ + guild_member(); + + /** Fill this object from a json object. + * @param j The json object to get data from + * @param g_id The guild id to associate the member with + * @param u_id The user id to associate the member with + * @return Reference to self for call chaining + */ + guild_member& fill_from_json(nlohmann::json* j, snowflake g_id, snowflake u_id); + + /** + * @brief Build json string for the member object + * + * @param with_id Add ID to output + * @return std::string json string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Returns true if the user is in time-out (communication disabled) + * + * @return true user is in time-out + * @return false user is not in time-out + */ + bool is_communication_disabled() const; + + /** + * @brief Returns true if the user is deafened + * + * @return true user is deafened + * @return false user is not deafened + */ + bool is_deaf() const; + + /** + * @brief Returns true if the user is muted + * + * @return true user muted + * @return false user not muted + */ + bool is_muted() const; + + /** + * @brief Returns true if pending verification by membership screening + * + * @return true user has completed membership screening + * @return false user has not completed membership screening + */ + bool is_pending() const; + + /** + * @brief Returns true if the user's per-guild custom avatar is animated + * + * @return true user's custom avatar is animated + * @return false user's custom avatar is not animated + */ + bool has_animated_guild_avatar() const; + + /** + * @brief Returns the members per guild avatar if they have one, otherwise returns an empty string + * + * @note per-server avatar is a nitro only feature so it might be not set. If you need the real user avatar, use user::get_avatar_url. + * + * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized avatar is returned. + * @return std::string avatar url or empty string + */ + std::string get_avatar_url(uint16_t size = 0) const; + + /** + * @brief Set the nickname + * + * @param nick Nickname to set + * + * @return guild_member& reference to self + */ + guild_member& set_nickname(const std::string& nick); + + /** + * @brief Get the dpp::user object for this member + * @return dpp::user user object. If not in cache, it returns nullptr + * + * + */ + dpp::user* get_user() const; + + /** + * @brief Set whether the user is muted in voice channels + * + * @param is_muted value to set, true if mute in voice channels + * + * @return guild_member& reference to self + */ + guild_member& set_mute(const bool is_muted); + + /** + * @brief Set whether the user is deafened in voice channels + * + * @param is_deafened value to set, true if deaf in voice channels + * + * @return guild_member& reference to self + */ + guild_member& set_deaf(const bool is_deafened); + + /** + * @brief Set communication_disabled_until + * + * @param timestamp timestamp until communication is disabled + * + * @return guild_member& reference to self + */ + guild_member& set_communication_disabled_until(const time_t timestamp); + + /** + * @brief Return a ping/mention for the user by nickname + * + * @return std::string mention + */ + std::string get_mention() const; +}; + +/** + * @brief Defines a channel on a server's welcome screen + */ +struct welcome_channel_t { + /// the description shown for the channel + std::string description; + /// the emoji name if custom, the unicode character if standard, or null if no emoji is set + std::string emoji_name; + /// the channel's id + snowflake channel_id = 0; + /// the emoji id, if the emoji is custom + snowflake emoji_id = 0; +}; + + +/** + * @brief Defines a server's welcome screen + */ +struct welcome_screen_t { + /// the server description shown in the welcome screen + std::string description; + /// the channels shown in the welcome screen, up to 5 + std::vector welcome_channels; +}; + +/** + * @brief Guild NSFW level. + * Used to represent just how naughty this guild is. Naughty guild, go sit in the corner. + * @note This is set by Discord, and cannot be set by any bot or user on the guild. + */ +enum guild_nsfw_level_t : uint8_t { + /// Default setting, not configured + nsfw_default = 0, + /// Explicit content may be in this guild + nsfw_explicit = 1, + /// Safe for work content only + nsfw_safe = 2, + /// Age restricted, 18+ + nsfw_age_restricted = 3 +}; + +/** + * @brief explicit content filter level. + * This is set by a guild admin, but can be forced to a setting if the server is verified, + * partnered, official etc. + */ +enum guild_explicit_content_t : uint8_t { + /// media content will not be scanned + expl_disabled = 0, + /// media content sent by members without roles will be scanned + expl_members_without_roles = 1, + /// media content sent by all members will be scanned + expl_all_members = 2 +}; + +/** + * @brief MFA level for server. If set to elevated all moderators need MFA to perform specific + * actions such as kick or ban. + */ +enum mfa_level_t : uint8_t { + /// MFA not elevated + mfa_none = 0, + /// MFA elevated + mfa_elevated = 1 +}; + +/** + * @brief Guild verification level + */ +enum verification_level_t : uint8_t { + /// unrestricted + ver_none = 0, + /// must have verified email on account + ver_low = 1, + /// must be registered on Discord for longer than 5 minutes + ver_medium = 2, + /// must be a member of the server for longer than 10 minutes + ver_high = 3, + /// must have a verified phone number + ver_very_high = 4, +}; + +/** + * @brief Default message notification level + */ +enum default_message_notification_t: uint8_t { + /// members will receive notifications for all messages by default + dmn_all = 0, + /// members will receive notifications only for messages that \@mention them by default + dmn_only_mentions = 1, +}; + +/** + * @brief Premium tier + */ +enum guild_premium_tier_t: uint8_t { + /// guild has not unlocked any Server Boost perks + tier_none = 0, + /// guild has unlocked Server Boost level 1 perks + tier_1 = 1, + /// guild has unlocked Server Boost level 2 perks + tier_2 = 2, + /// guild has unlocked Server Boost level 3 perks + tier_3 = 3, +}; + +/** + * @brief Voice AFK timeout values for guild::afk_timeout + */ +enum guild_afk_timeout_t: uint8_t { + /// AFK timeout disabled + afk_off, + /// AFK timeout of 1 Minute + afk_60, + /// AFK timeout of 5 Minutes + afk_300, + /// AFK timeout of 15 Minutes + afk_900, + /// AFK timeout of 30 Minutes + afk_1800, + /// AFK timeout of 1 Hour + afk_3600, +}; + +/** @brief Guild members container + */ +typedef std::unordered_map members_container; + +/** + * @brief Represents a guild on Discord (AKA a server) + */ +class DPP_EXPORT guild : public managed, public json_interface { +public: + /** Guild name */ + std::string name; + + /** Server description */ + std::string description; + + /** + * @brief Vanity url code for verified or partnered servers and boost level 3 + * @note This field cannot be set from the API. Attempts to change this value will be + * silently ignored even if the correct number of boosts or verified/partnered status exist. + * See: https://github.com/discord/discord-api-docs/issues/519 + */ + std::string vanity_url_code; + + /** Roles defined on this server */ + std::vector roles; + + /** List of channels on this server */ + std::vector channels; + + /** List of threads on this server */ + std::vector threads; + + /** List of emojis + */ + std::vector emojis; + + /** List of members in voice channels in the guild. + */ + std::map voice_members; + + /** List of guild members. Note that when you first receive the + * guild create event, this may be empty or near empty. + * This depends upon your dpp::intents and the size of your bot. + * It will be filled by guild member chunk requests. + */ + members_container members; + + /** Welcome screen + */ + welcome_screen_t welcome_screen; + + /** Guild icon hash */ + utility::iconhash icon; + + /** Guild splash hash */ + utility::iconhash splash; + + /** Guild discovery splash hash */ + utility::iconhash discovery_splash; + + /** Server banner hash */ + utility::iconhash banner; + + /** Snowflake id of guild owner */ + snowflake owner_id; + + /** Snowflake ID of AFK voice channel or 0 */ + snowflake afk_channel_id; + + /** ID of creating application, if any, or 0 */ + snowflake application_id; + + /** ID of system channel where discord update messages are sent */ + snowflake system_channel_id; + + /** ID of rules channel for communities */ + snowflake rules_channel_id; + + /** Public updates channel id or 0 */ + snowflake public_updates_channel_id; + + /** Snowflake ID of widget channel, or 0 */ + snowflake widget_channel_id; + + /** Approximate member count. May be sent as zero */ + uint32_t member_count; + + /** Flags bitmask as defined by values within dpp::guild_flags */ + uint32_t flags; + + /** + * @brief the maximum number of presences for the guild. + * @note Generally Discord always fills this with 0, apart from for the largest of guilds + */ + uint32_t max_presences; + + /** + * @brief the maximum number of members for the guild + */ + uint32_t max_members; + + /** Shard ID of the guild */ + uint16_t shard_id; + + /** Number of boosters */ + uint16_t premium_subscription_count; + + /** Voice AFK timeout before moving users to AFK channel */ + guild_afk_timeout_t afk_timeout; + + /** Maximum users in a video channel, or 0 */ + uint8_t max_video_channel_users; + + /** Setting for how notifications are to be delivered to users */ + default_message_notification_t default_message_notifications; + + /** Boost level */ + guild_premium_tier_t premium_tier; + + /** Verification level of server */ + verification_level_t verification_level; + + /** Whether or not explicit content filtering is enable and what setting it is */ + guild_explicit_content_t explicit_content_filter; + + /** If multi factor authentication is required for moderators or not */ + mfa_level_t mfa_level; + + /** + * @brief Guild NSFW level + */ + guild_nsfw_level_t nsfw_level; + + /** + * @brief Additional flags + */ + uint8_t flags_extra; + + /** Default constructor, zeroes all values */ + guild(); + + /** + * @brief Destroy the guild object + */ + virtual ~guild() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + guild& fill_from_json(nlohmann::json* j); + + /** Read class values from json object + * @param shard originating shard + * @param j A json object to read from + * @return A reference to self + */ + guild& fill_from_json(class discord_client* shard, nlohmann::json* j); + + /** Build a JSON string from this object. + * @param with_id True if an ID is to be included in the JSON + * @return JSON string + */ + std::string build_json(bool with_id = false) const; + + /** + * @brief Compute the base permissions for a member on this guild, + * before channel overwrites are applied. + * This method takes into consideration the following cases: + * - Guild owner + * - Guild roles including \@everyone + * + * @param user User to get permissions for + * @return permission permissions bitmask + * @note Requires role cache to be enabled (it's enabled by default). + * + * @warning The method will search for the guild member in the cache by the users id. + * If the guild member is not in cache, the method will always return 0. + */ + permission base_permissions(const class user* user) const; + + /** + * @brief Compute the base permissions for a member on this guild, + * before channel overwrites are applied. + * This method takes into consideration the following cases: + * - Guild owner + * - Guild roles including \@everyone + * + * @param member member to get permissions for + * @return permission permissions bitmask + * @note Requires role cache to be enabled (it's enabled by default). + */ + permission base_permissions(const guild_member &member) const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param base_permissions base permissions before overwrites, + * from guild::base_permissions + * @param user The user to resolve the permissions for + * @param channel Channel to compute permission overwrites for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + * + * @warning The method will search for the guild member in the cache by the users id. + * If the guild member is not in cache, the method will always return 0. + */ + permission permission_overwrites(const uint64_t base_permissions, const user* user, const channel* channel) const; + + /** + * @brief Get the overall permissions for a member in this channel, including channel overwrites, role permissions and admin privileges. + * + * @param member The member to resolve the permissions for + * @param channel Channel to compute permission overwrites for + * @return permission Permission overwrites for the member. Made of bits in dpp::permissions. + * @note Requires role cache to be enabled (it's enabled by default). + */ + permission permission_overwrites(const guild_member &member, const channel &channel) const; + + /** + * @brief Rehash members map + */ + void rehash_members(); + + /** + * @brief Connect to a voice channel another guild member is in + * + * @param user_id User id to join + * @param self_mute True if the bot should mute itself + * @param self_deaf True if the bot should deafen itself + * @return True if the user specified is in a vc, false if they aren't + * @note This is NOT a synchronous blocking call! The bot isn't instantly ready to send or listen for audio, + * as we have to wait for the connection to the voice server to be established! + * e.g. wait for dpp::cluster::on_voice_ready event, and then send the audio within that event. + */ + bool connect_member_voice(snowflake user_id, bool self_mute = false, bool self_deaf = false); + + /** + * @brief Get the banner url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. + * @return std::string banner url or empty string + */ + std::string get_banner_url(uint16_t size = 0) const; + + /** + * @brief Get the discovery splash url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the discovery splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized discovery splash is returned. + * @return std::string discovery splash url or empty string + */ + std::string get_discovery_splash_url(uint16_t size = 0) const; + + /** + * @brief Get the icon url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; + + /** + * @brief Get the splash url of the guild if it have one, otherwise returns an empty string + * + * @param size The size of the splash in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized splash is returned. + * @return std::string splash url or empty string + */ + std::string get_splash_url(uint16_t size = 0) const; + + /** + * @brief Set the name of the guild in the object + * Min length: 2, Max length: 100 (not including leading/trailing spaces) + * @param n Guild name + * @return guild& reference to self + * @throw dpp::length_exception if guild name is too short + */ + guild& set_name(const std::string& n); + + /** + * @brief Is a large server (>250 users) + * @return bool is a large guild + */ + bool is_large() const; + + /** + * @brief Is unavailable due to outage (most other fields will be blank or outdated + * @return bool is unavailable + */ + bool is_unavailable() const; + + /** + * @brief Widget is enabled for this server + * @return bool widget enabled + */ + bool widget_enabled() const; + + /** + * @brief Guild has access to set an invite splash background + * @return bool can have an invite splash + */ + bool has_invite_splash() const; + + /** + * @brief Guild has access to set 384kbps bitrate in voice + * @return bool can have VIP voice regions + */ + bool has_vip_regions() const; + + /** + * @brief Guild has access to set a vanity URL + * @return bool can have vanity url + */ + bool has_vanity_url() const; + + /** + * @brief Guild is a verified server + * @return bool is verified + */ + bool is_verified() const; + + /** + * @brief Guild is a discord partnered server + * @return bool is discord partnered + */ + bool is_partnered() const; + + /** + * @brief Has enabled community + * @return bool has enabled community + */ + bool is_community() const; + + /** + * @brief Guild has access to use commerce features + * @return bool has commerce features enabled + * @deprecated Removed by Discord + */ + bool has_commerce() const; + + /** + * @brief Guild has access to create announcement channels + * @return bool has announcement channels features enabled + */ + bool has_news() const; + + /** + * @brief Guild is discoverable + * @return bool is discoverable + */ + bool is_discoverable() const; + + /** + * @brief Guild is featurable + * @return bool is featurable + */ + bool is_featureable() const; + + /** + * @brief Guild has access to set an animated guild banner image + * @return bool can have animated banner image + */ + bool has_animated_banner() const; + + /** + * @brief Guild has auto moderation features + * @return bool has auto moderation features + */ + bool has_auto_moderation() const; + + /** + * @brief Guild has been set as a support server on the App Directory + * @return bool has been set as a support server of an app in the app directory + */ + bool has_support_server() const; + + /** + * @brief Guild has access to set an animated guild icon + * @return bool can have animated icon + */ + bool has_animated_icon() const; + + /** + * @brief Guild has access to set a guild banner image + * @return bool can have banner image + */ + bool has_banner() const; + + /** + * @brief Guild has enabled the welcome screen + * @return bool enabled welcome screen + */ + bool is_welcome_screen_enabled() const; + + /** + * @brief Guild has enabled membership screening + * @return bool has membership screening + */ + bool has_member_verification_gate() const; + + /** + * @brief Guild has preview enabled + * @return bool has preview + */ + bool is_preview_enabled() const; + + /** + * @brief Guild icon is actually an animated gif + * @return bool is animated gif + */ + bool has_animated_icon_hash() const; + + /** + * @brief Guild banner is actually an animated gif + * @return bool is animated gif + */ + bool has_animated_banner_hash() const; + + + /** + * @brief guild has access to monetization features + * @return bool + */ + bool has_monetization_enabled() const; + + /** + * @brief guild has increased custom sticker slots + * @return bool has more stickers + */ + bool has_more_stickers() const; + + /** + * @brief guild has access to create private threads + * @return bool has private threads + * @deprecated Removed by Discord + */ + bool has_private_threads() const; + + /** + * @brief guild is able to set role icons + * @return bool has role icons + */ + bool has_role_icons() const; + + /** + * @brief guild has access to the seven day archive time for threads + * @return bool has seven day thread archive + */ + bool has_seven_day_thread_archive() const; + + /** + * @brief guild has access to the three day archive time for threads + * @return bool has three day thread archive + */ + bool has_three_day_thread_archive() const; + + /** + * @brief guild has enabled ticketed events + * @return bool has ticketed events + */ + bool has_ticketed_events() const; + + /** + * @brief guild has access to channel banners feature + * @return bool has channel banners + */ + bool has_channel_banners() const; + + /** + * @brief True if the premium progress bar is enabled + * @return bool has progress bar enabled + */ + bool has_premium_progress_bar_enabled() const; + + /** + * @brief True if has paused invites, preventing new users from joining + * @return bool has paused invites + */ + bool has_invites_disabled() const; +}; + +/** A container of guilds */ +typedef std::unordered_map guild_map; + +/** + * @brief Represents a guild widget, simple web widget of member list + */ +class DPP_EXPORT guild_widget { +public: + /** + * @brief Channel widget points to + */ + snowflake channel_id; + + /** + * @brief True if enabled + */ + bool enabled; + + /** + * @brief Construct a new guild widget object + */ + guild_widget(); + + /** + * @brief Build a guild widget from json + * + * @param j json to build from + * @return guild_widget& reference to self + */ + guild_widget& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json for a guild widget + * + * @param with_id Add ID to output + * @return std::string guild widget stringified json + */ + std::string build_json(bool with_id = false) const; +}; + +/** + * @brief helper function to deserialize a guild_member from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param gm guild_member to be deserialized + */ +void from_json(const nlohmann::json& j, guild_member& gm); + +/** A container of guild members */ +typedef std::unordered_map guild_member_map; + +/** + * @brief Get the guild_member from cache of given IDs + * + * @param guild_id ID of the guild to find guild_member for + * @param user_id ID of the user to find guild_member for + * + * @throw dpp::cache_exception if the guild or guild_member is not found in the cache + * @return guild_member the cached object, if found + */ +guild_member DPP_EXPORT find_guild_member(const snowflake guild_id, const snowflake user_id); + +}; diff --git a/3rdParty/dpp/httpsclient.h b/3rdParty/dpp/httpsclient.h index d0a51edf2c..20e766afd4 100644 --- a/3rdParty/dpp/httpsclient.h +++ b/3rdParty/dpp/httpsclient.h @@ -1,316 +1,316 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - - -/** - * @brief HTTP connection status - */ -enum http_state : uint8_t { - /** - * @brief Sending/receiving HTTP headers and request body - */ - HTTPS_HEADERS, - - /** - * @brief Receiving body content. - */ - HTTPS_CONTENT, - - /** - * @brief Completed connection, as it was closed or the body is >= Content-Length - * - */ - HTTPS_DONE, - - /** - * @brief Received chunk length - * - */ - HTTPS_CHUNK_LEN, - - /** - * @brief Received chunk trailing CRLF - */ - HTTPS_CHUNK_TRAILER, - - /** - * @brief The last received chunk is the final chunk - */ - HTTPS_CHUNK_LAST, - - /** - * @brief Receiving contents of a chunk - */ - HTTPS_CHUNK_CONTENT -}; - -/** - * @brief Request headers - */ -typedef std::multimap http_headers; - -/** - * @brief Represents a multipart mime body and the correct top-level mime type - * If a non-multipart request is passed in, this is represented as a plain body - * and the application/json mime type. - */ -struct multipart_content { - /** - * @brief Multipart body - */ - std::string body; - /** - * @brief MIME type - */ - std::string mimetype; -}; - -/** - * @brief Represents a HTTP scheme, hostname and port - * split into parts for easy use in https_client. - */ -struct http_connect_info { - /** - * @brief True if the connection should be SSL - */ - bool is_ssl; - /** - * @brief The request scheme, e.g. 'https' or 'http' - */ - std::string scheme; - /** - * @brief The request hostname part, e.g. 'discord.com' - */ - std::string hostname; - /** - * @brief The port number, either determined from the scheme, - * or from the part of the hostname after a colon ":" character - */ - uint16_t port; -}; - -/** - * @brief Implements a HTTPS socket client based on the SSL client. - * @note plaintext HTTP without SSL is also supported via a "downgrade" setting - */ -class DPP_EXPORT https_client : public ssl_client -{ - /** - * @brief Current connection state - */ - http_state state; - - /** - * @brief The type of the request, e.g. GET, POST - */ - std::string request_type; - - /** - * @brief Path part of URL for HTTPS connection - */ - std::string path; - - /** - * @brief The request body, e.g. form data - */ - std::string request_body; - - /** - * @brief The response body, e.g. file content or JSON - */ - std::string body; - - /** - * @brief The reported length of the content. If this is - * UULONG_MAX, then no length was reported by the server. - */ - uint64_t content_length; - - /** - * @brief Headers for the request, e.g. Authorization, etc. - */ - http_headers request_headers; - - /** - * @brief The status of the HTTP request from the server, - * e.g. 200 for OK, 404 for not found. A value of 0 means - * no request has been completed. - */ - uint16_t status; - - /** - * @brief Time at which the request should be abandoned - */ - time_t timeout; - - /** - * @brief If true the content is chunked encoding - */ - bool chunked; - - /** - * @brief Size of current chunk - */ - size_t chunk_size; - - /** - * @brief Number of bytes received in current chunk - */ - size_t chunk_receive; - - /** - * @brief Headers from the server's response, e.g. RateLimit - * headers, cookies, etc. - */ - std::map response_headers; - - /** - * @brief Handle input buffer - * - * @param buffer Buffer to read - * @return returns true if the connection should remain open - */ - bool do_buffer(std::string& buffer); - -protected: - - /** - * @brief Start the connection - */ - virtual void connect(); - - /** - * @brief Get request state - * @return request state - */ - http_state get_state(); - -public: - - /** - * @brief Connect to a specific HTTP(S) server and complete a request. - * - * The constructor will attempt the connection, and return the content. - * By the time the constructor completes, the HTTP request will be stored - * in the object. - * - * @note This is a blocking call. It starts a loop which runs non-blocking - * functions within it, but does not return until the request completes. - * See queues.cpp for how to make this asynchronous. - * - * @param hostname Hostname to connect to - * @param port Port number to connect to, usually 443 for SSL and 80 for plaintext - * @param urlpath path part of URL, e.g. "/api" - * @param verb Request verb, e.g. GET or POST - * @param req_body Request body, use dpp::https_client::build_multipart() to build a multipart MIME body (e.g. for multiple file upload) - * @param extra_headers Additional request headers, e.g. user-agent, authorization, etc - * @param plaintext_connection Set to true to make the connection plaintext (turns off SSL) - * @param request_timeout How many seconds before the connection is considered failed if not finished - */ - https_client(const std::string &hostname, uint16_t port = 443, const std::string &urlpath = "/", const std::string &verb = "GET", const std::string &req_body = "", const http_headers& extra_headers = {}, bool plaintext_connection = false, uint16_t request_timeout = 5); - - /** - * @brief Destroy the https client object - */ - virtual ~https_client(); - - /** - * @brief Build a multipart content from a set of files and some json - * - * @param json The json content - * @param filenames File names of files to send - * @param contents Contents of each of the files to send - * @return multipart mime content and headers - */ - static multipart_content build_multipart(const std::string &json, const std::vector& filenames = {}, const std::vector& contents = {}); - - /** - * @brief Processes incoming data from the SSL socket input buffer. - * - * @param buffer The buffer contents. Can modify this value removing the head elements when processed. - */ - virtual bool handle_buffer(std::string &buffer); - - /** - * @brief Close HTTPS socket - */ - virtual void close(); - - /** - * @brief Fires every second from the underlying socket I/O loop, used for timeouts - */ - virtual void one_second_timer(); - - /** - * @brief Get a HTTP response header - * - * @param header_name Header name to find, case insensitive - * @return Header content or empty string if not found - */ - const std::string get_header(std::string header_name) const; - - /** - * @brief Get all HTTP response headers - * - * @return headers as a map - */ - const std::map get_headers() const; - - /** - * @brief Get the response content - * - * @return response content - */ - const std::string get_content() const; - - /** - * @brief Get the response HTTP status, e.g. - * 200 for OK, 404 for not found, 429 for rate limited. - * A value of 0 indicates the request was not completed. - * - * @return uint16_t HTTP status - */ - uint16_t get_status() const; - - /** - * @brief Break down a scheme, hostname and port into - * a http_connect_info. - * - * All but the hostname portion are optional. The path component - * should not be passed to this function. - * - * @param url URL to break down - * @return Split URL - */ - static http_connect_info get_host_info(std::string url); - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + + +/** + * @brief HTTP connection status + */ +enum http_state : uint8_t { + /** + * @brief Sending/receiving HTTP headers and request body + */ + HTTPS_HEADERS, + + /** + * @brief Receiving body content. + */ + HTTPS_CONTENT, + + /** + * @brief Completed connection, as it was closed or the body is >= Content-Length + * + */ + HTTPS_DONE, + + /** + * @brief Received chunk length + * + */ + HTTPS_CHUNK_LEN, + + /** + * @brief Received chunk trailing CRLF + */ + HTTPS_CHUNK_TRAILER, + + /** + * @brief The last received chunk is the final chunk + */ + HTTPS_CHUNK_LAST, + + /** + * @brief Receiving contents of a chunk + */ + HTTPS_CHUNK_CONTENT +}; + +/** + * @brief Request headers + */ +typedef std::multimap http_headers; + +/** + * @brief Represents a multipart mime body and the correct top-level mime type + * If a non-multipart request is passed in, this is represented as a plain body + * and the application/json mime type. + */ +struct multipart_content { + /** + * @brief Multipart body + */ + std::string body; + /** + * @brief MIME type + */ + std::string mimetype; +}; + +/** + * @brief Represents a HTTP scheme, hostname and port + * split into parts for easy use in https_client. + */ +struct http_connect_info { + /** + * @brief True if the connection should be SSL + */ + bool is_ssl; + /** + * @brief The request scheme, e.g. 'https' or 'http' + */ + std::string scheme; + /** + * @brief The request hostname part, e.g. 'discord.com' + */ + std::string hostname; + /** + * @brief The port number, either determined from the scheme, + * or from the part of the hostname after a colon ":" character + */ + uint16_t port; +}; + +/** + * @brief Implements a HTTPS socket client based on the SSL client. + * @note plaintext HTTP without SSL is also supported via a "downgrade" setting + */ +class DPP_EXPORT https_client : public ssl_client +{ + /** + * @brief Current connection state + */ + http_state state; + + /** + * @brief The type of the request, e.g. GET, POST + */ + std::string request_type; + + /** + * @brief Path part of URL for HTTPS connection + */ + std::string path; + + /** + * @brief The request body, e.g. form data + */ + std::string request_body; + + /** + * @brief The response body, e.g. file content or JSON + */ + std::string body; + + /** + * @brief The reported length of the content. If this is + * UULONG_MAX, then no length was reported by the server. + */ + uint64_t content_length; + + /** + * @brief Headers for the request, e.g. Authorization, etc. + */ + http_headers request_headers; + + /** + * @brief The status of the HTTP request from the server, + * e.g. 200 for OK, 404 for not found. A value of 0 means + * no request has been completed. + */ + uint16_t status; + + /** + * @brief Time at which the request should be abandoned + */ + time_t timeout; + + /** + * @brief If true the content is chunked encoding + */ + bool chunked; + + /** + * @brief Size of current chunk + */ + size_t chunk_size; + + /** + * @brief Number of bytes received in current chunk + */ + size_t chunk_receive; + + /** + * @brief Headers from the server's response, e.g. RateLimit + * headers, cookies, etc. + */ + std::map response_headers; + + /** + * @brief Handle input buffer + * + * @param buffer Buffer to read + * @return returns true if the connection should remain open + */ + bool do_buffer(std::string& buffer); + +protected: + + /** + * @brief Start the connection + */ + virtual void connect(); + + /** + * @brief Get request state + * @return request state + */ + http_state get_state(); + +public: + + /** + * @brief Connect to a specific HTTP(S) server and complete a request. + * + * The constructor will attempt the connection, and return the content. + * By the time the constructor completes, the HTTP request will be stored + * in the object. + * + * @note This is a blocking call. It starts a loop which runs non-blocking + * functions within it, but does not return until the request completes. + * See queues.cpp for how to make this asynchronous. + * + * @param hostname Hostname to connect to + * @param port Port number to connect to, usually 443 for SSL and 80 for plaintext + * @param urlpath path part of URL, e.g. "/api" + * @param verb Request verb, e.g. GET or POST + * @param req_body Request body, use dpp::https_client::build_multipart() to build a multipart MIME body (e.g. for multiple file upload) + * @param extra_headers Additional request headers, e.g. user-agent, authorization, etc + * @param plaintext_connection Set to true to make the connection plaintext (turns off SSL) + * @param request_timeout How many seconds before the connection is considered failed if not finished + */ + https_client(const std::string &hostname, uint16_t port = 443, const std::string &urlpath = "/", const std::string &verb = "GET", const std::string &req_body = "", const http_headers& extra_headers = {}, bool plaintext_connection = false, uint16_t request_timeout = 5); + + /** + * @brief Destroy the https client object + */ + virtual ~https_client(); + + /** + * @brief Build a multipart content from a set of files and some json + * + * @param json The json content + * @param filenames File names of files to send + * @param contents Contents of each of the files to send + * @return multipart mime content and headers + */ + static multipart_content build_multipart(const std::string &json, const std::vector& filenames = {}, const std::vector& contents = {}); + + /** + * @brief Processes incoming data from the SSL socket input buffer. + * + * @param buffer The buffer contents. Can modify this value removing the head elements when processed. + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Close HTTPS socket + */ + virtual void close(); + + /** + * @brief Fires every second from the underlying socket I/O loop, used for timeouts + */ + virtual void one_second_timer(); + + /** + * @brief Get a HTTP response header + * + * @param header_name Header name to find, case insensitive + * @return Header content or empty string if not found + */ + const std::string get_header(std::string header_name) const; + + /** + * @brief Get all HTTP response headers + * + * @return headers as a map + */ + const std::map get_headers() const; + + /** + * @brief Get the response content + * + * @return response content + */ + const std::string get_content() const; + + /** + * @brief Get the response HTTP status, e.g. + * 200 for OK, 404 for not found, 429 for rate limited. + * A value of 0 indicates the request was not completed. + * + * @return uint16_t HTTP status + */ + uint16_t get_status() const; + + /** + * @brief Break down a scheme, hostname and port into + * a http_connect_info. + * + * All but the hostname portion are optional. The path component + * should not be passed to this function. + * + * @param url URL to break down + * @return Split URL + */ + static http_connect_info get_host_info(std::string url); + +}; + }; \ No newline at end of file diff --git a/3rdParty/dpp/integration.h b/3rdParty/dpp/integration.h index 6205b36635..a1de296193 100644 --- a/3rdParty/dpp/integration.h +++ b/3rdParty/dpp/integration.h @@ -1,171 +1,171 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Integration types - */ -enum integration_type { - /// Twitch integration - i_twitch, - /// YouTube integration - i_youtube, - /// Discord integration - i_discord -}; - -/** - * @brief Integration flags - */ -enum integration_flags { - /// Integration enabled - if_enabled = 0b00000001, - /// Integration syncing - if_syncing = 0b00000010, - /// Emoji integration - if_emoticons = 0b00000100, - /// Integration revoked - if_revoked = 0b00001000, - /// Kick users when their subscription expires - if_expire_kick = 0b00010000, -}; - -/** - * @brief An application that has been integrated - */ -struct DPP_EXPORT integration_app { - /// Integration id - snowflake id; - /// Name - std::string name; - /// Icon - std::string icon; - /// Description - std::string description; - /// Integration summary @deprecated Removed by Discord - std::string summary; - /// Pointer to bot user - class user* bot; -}; - -/** - * @brief Represents an integration on a guild, e.g. a connection to twitch. - */ -class DPP_EXPORT integration : public managed, public json_interface { -public: - /** Integration name */ - std::string name; - /** Integration type */ - integration_type type; - /** Integration flags from dpp::integration_flags */ - uint8_t flags; - /** Role id */ - snowflake role_id; - /** User id */ - snowflake user_id; - /** The grace period (in days) before expiring subscribers */ - uint32_t expire_grace_period; - /** Sync time */ - time_t synced_at; - /** Subscriber count */ - uint32_t subscriber_count; - /** Account id */ - std::string account_id; - /** Account name */ - std::string account_name; - /** The bot/OAuth2 application for discord integrations */ - integration_app app; - - /** Default constructor */ - integration(); - - /** Default destructor */ - ~integration(); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - integration& fill_from_json(nlohmann::json* j); - - /** Build a json string from this object. - * @param with_id Add ID to output - * @return JSON string of the object - */ - virtual std::string build_json(bool with_id = false) const; - - /** True if emoticons are enabled */ - bool emoticons_enabled() const; - /** True if integration is enabled */ - bool is_enabled() const; - /** True if is syncing */ - bool is_syncing() const; - /** True if has been revoked */ - bool is_revoked() const; - /** True if expiring kicks the user */ - bool expiry_kicks_user() const; -}; - -/** - * @brief The connection object that the user has attached. - */ -class DPP_EXPORT connection { -public: - std::string id; //!< id of the connection account - std::string name; //!< the username of the connection account - std::string type; //!< the service of the connection (twitch, youtube) - bool revoked; //!< Optional: whether the connection is revoked - std::vector integrations; //!< Optional: an array of partial server integrations - bool verified; //!< whether the connection is verified - bool friend_sync; //!< whether friend sync is enabled for this connection - bool show_activity; //!< whether activities related to this connection will be shown in presence updates - bool two_way_link; //!< Whether this connection has a corresponding third party OAuth2 token - bool visible; //!< visibility of this connection - - /** - * @brief Construct a new connection object - */ - connection(); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - connection& fill_from_json(nlohmann::json* j); - -}; - -/** A group of integrations */ -typedef std::unordered_map integration_map; - -/** A group of connections */ -typedef std::unordered_map connection_map; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Integration types + */ +enum integration_type { + /// Twitch integration + i_twitch, + /// YouTube integration + i_youtube, + /// Discord integration + i_discord +}; + +/** + * @brief Integration flags + */ +enum integration_flags { + /// Integration enabled + if_enabled = 0b00000001, + /// Integration syncing + if_syncing = 0b00000010, + /// Emoji integration + if_emoticons = 0b00000100, + /// Integration revoked + if_revoked = 0b00001000, + /// Kick users when their subscription expires + if_expire_kick = 0b00010000, +}; + +/** + * @brief An application that has been integrated + */ +struct DPP_EXPORT integration_app { + /// Integration id + snowflake id; + /// Name + std::string name; + /// Icon + std::string icon; + /// Description + std::string description; + /// Integration summary @deprecated Removed by Discord + std::string summary; + /// Pointer to bot user + class user* bot; +}; + +/** + * @brief Represents an integration on a guild, e.g. a connection to twitch. + */ +class DPP_EXPORT integration : public managed, public json_interface { +public: + /** Integration name */ + std::string name; + /** Integration type */ + integration_type type; + /** Integration flags from dpp::integration_flags */ + uint8_t flags; + /** Role id */ + snowflake role_id; + /** User id */ + snowflake user_id; + /** The grace period (in days) before expiring subscribers */ + uint32_t expire_grace_period; + /** Sync time */ + time_t synced_at; + /** Subscriber count */ + uint32_t subscriber_count; + /** Account id */ + std::string account_id; + /** Account name */ + std::string account_name; + /** The bot/OAuth2 application for discord integrations */ + integration_app app; + + /** Default constructor */ + integration(); + + /** Default destructor */ + ~integration(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + integration& fill_from_json(nlohmann::json* j); + + /** Build a json string from this object. + * @param with_id Add ID to output + * @return JSON string of the object + */ + virtual std::string build_json(bool with_id = false) const; + + /** True if emoticons are enabled */ + bool emoticons_enabled() const; + /** True if integration is enabled */ + bool is_enabled() const; + /** True if is syncing */ + bool is_syncing() const; + /** True if has been revoked */ + bool is_revoked() const; + /** True if expiring kicks the user */ + bool expiry_kicks_user() const; +}; + +/** + * @brief The connection object that the user has attached. + */ +class DPP_EXPORT connection { +public: + std::string id; //!< id of the connection account + std::string name; //!< the username of the connection account + std::string type; //!< the service of the connection (twitch, youtube) + bool revoked; //!< Optional: whether the connection is revoked + std::vector integrations; //!< Optional: an array of partial server integrations + bool verified; //!< whether the connection is verified + bool friend_sync; //!< whether friend sync is enabled for this connection + bool show_activity; //!< whether activities related to this connection will be shown in presence updates + bool two_way_link; //!< Whether this connection has a corresponding third party OAuth2 token + bool visible; //!< visibility of this connection + + /** + * @brief Construct a new connection object + */ + connection(); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + connection& fill_from_json(nlohmann::json* j); + +}; + +/** A group of integrations */ +typedef std::unordered_map integration_map; + +/** A group of connections */ +typedef std::unordered_map connection_map; + +}; + diff --git a/3rdParty/dpp/intents.h b/3rdParty/dpp/intents.h index 3cb84fb693..1e5932198d 100644 --- a/3rdParty/dpp/intents.h +++ b/3rdParty/dpp/intents.h @@ -1,86 +1,86 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -namespace dpp { - -/** - * @brief intents are a bitmask of allowed events on your websocket. - * - * Some of these are known as Privileged intents (GUILD_MEMBERS and GUILD_PRESENCES) - * and require verification of a bot over 100 servers by discord via submission of - * your real life ID. - */ -enum intents { - /// Intent for receipt of guild information - i_guilds = (1 << 0), - /// Intent for receipt of guild members - i_guild_members = (1 << 1), - /// Intent for receipt of guild bans - i_guild_bans = (1 << 2), - /// Intent for receipt of guild emojis - i_guild_emojis = (1 << 3), - /// Intent for receipt of guild integrations - i_guild_integrations = (1 << 4), - /// Intent for receipt of guild webhooks - i_guild_webhooks = (1 << 5), - /// Intent for receipt of guild invites - i_guild_invites = (1 << 6), - /// Intent for receipt of guild voice states - i_guild_voice_states = (1 << 7), - /// Intent for receipt of guild presences - i_guild_presences = (1 << 8), - /// Intent for receipt of guild messages - i_guild_messages = (1 << 9), - /// Intent for receipt of guild message reactions - i_guild_message_reactions = (1 << 10), - /// Intent for receipt of guild message typing notifications - i_guild_message_typing = (1 << 11), - /// Intent for receipt of direct messages (DMs) - i_direct_messages = (1 << 12), - /// Intent for receipt of direct message reactions - i_direct_message_reactions = (1 << 13), - /// Intent for receipt of direct message typing notifications - i_direct_message_typing = (1 << 14), - /// Intent for receipt of message content - i_message_content = (1 << 15), - /// Scheduled events - i_guild_scheduled_events = (1 << 16), - /// Auto moderation configuration - i_auto_moderation_configuration = (1 << 20), - /// Auto moderation configuration - i_auto_moderation_execution = (1 << 21), - /// Default D++ intents (all non-privileged intents) - i_default_intents = dpp::i_guilds | dpp::i_guild_bans | dpp::i_guild_emojis | dpp::i_guild_integrations | - dpp::i_guild_webhooks | dpp::i_guild_invites | dpp::i_guild_voice_states | - dpp::i_guild_messages | dpp::i_guild_message_reactions | dpp::i_guild_message_typing | - dpp::i_direct_messages | dpp::i_direct_message_typing | dpp::i_direct_message_reactions | - dpp::i_guild_scheduled_events | dpp::i_auto_moderation_configuration | - dpp::i_auto_moderation_execution, - /// Privileged intents requiring ID - i_privileged_intents = dpp::i_guild_members | dpp::i_guild_presences | dpp::i_message_content, - /// Every single intent - i_all_intents = dpp::i_default_intents | dpp::i_privileged_intents, - /// Unverified bots default intents - i_unverified_default_intents = dpp::i_default_intents | dpp::i_message_content -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +namespace dpp { + +/** + * @brief intents are a bitmask of allowed events on your websocket. + * + * Some of these are known as Privileged intents (GUILD_MEMBERS and GUILD_PRESENCES) + * and require verification of a bot over 100 servers by discord via submission of + * your real life ID. + */ +enum intents { + /// Intent for receipt of guild information + i_guilds = (1 << 0), + /// Intent for receipt of guild members + i_guild_members = (1 << 1), + /// Intent for receipt of guild bans + i_guild_bans = (1 << 2), + /// Intent for receipt of guild emojis + i_guild_emojis = (1 << 3), + /// Intent for receipt of guild integrations + i_guild_integrations = (1 << 4), + /// Intent for receipt of guild webhooks + i_guild_webhooks = (1 << 5), + /// Intent for receipt of guild invites + i_guild_invites = (1 << 6), + /// Intent for receipt of guild voice states + i_guild_voice_states = (1 << 7), + /// Intent for receipt of guild presences + i_guild_presences = (1 << 8), + /// Intent for receipt of guild messages + i_guild_messages = (1 << 9), + /// Intent for receipt of guild message reactions + i_guild_message_reactions = (1 << 10), + /// Intent for receipt of guild message typing notifications + i_guild_message_typing = (1 << 11), + /// Intent for receipt of direct messages (DMs) + i_direct_messages = (1 << 12), + /// Intent for receipt of direct message reactions + i_direct_message_reactions = (1 << 13), + /// Intent for receipt of direct message typing notifications + i_direct_message_typing = (1 << 14), + /// Intent for receipt of message content + i_message_content = (1 << 15), + /// Scheduled events + i_guild_scheduled_events = (1 << 16), + /// Auto moderation configuration + i_auto_moderation_configuration = (1 << 20), + /// Auto moderation configuration + i_auto_moderation_execution = (1 << 21), + /// Default D++ intents (all non-privileged intents) + i_default_intents = dpp::i_guilds | dpp::i_guild_bans | dpp::i_guild_emojis | dpp::i_guild_integrations | + dpp::i_guild_webhooks | dpp::i_guild_invites | dpp::i_guild_voice_states | + dpp::i_guild_messages | dpp::i_guild_message_reactions | dpp::i_guild_message_typing | + dpp::i_direct_messages | dpp::i_direct_message_typing | dpp::i_direct_message_reactions | + dpp::i_guild_scheduled_events | dpp::i_auto_moderation_configuration | + dpp::i_auto_moderation_execution, + /// Privileged intents requiring ID + i_privileged_intents = dpp::i_guild_members | dpp::i_guild_presences | dpp::i_message_content, + /// Every single intent + i_all_intents = dpp::i_default_intents | dpp::i_privileged_intents, + /// Unverified bots default intents + i_unverified_default_intents = dpp::i_default_intents | dpp::i_message_content +}; + +}; diff --git a/3rdParty/dpp/invite.h b/3rdParty/dpp/invite.h index 26ac50ddc1..fe61b67e14 100644 --- a/3rdParty/dpp/invite.h +++ b/3rdParty/dpp/invite.h @@ -1,110 +1,110 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents an invite to a discord guild or channel - */ -class DPP_EXPORT invite : public json_interface { -public: - /** Invite code - */ - std::string code; - /** Readonly expiration timestamp of this invite or 0 if the invite doesn't expire - */ - time_t expires_at; - /** Guild for the invite - */ - snowflake guild_id; - /** Channel id for invite - */ - snowflake channel_id; - /** User ID of invite creator - */ - snowflake inviter_id; - /** Target user ID of invite, for invites sent via DM - */ - snowflake target_user_id; - /** Target user type (generally this is always 1, "stream") - */ - uint8_t target_user_type; - /** Approximate number of online users - */ - uint32_t approximate_presence_count; - /** Approximate total users online and offline - */ - uint32_t approximate_member_count; - /** Maximum age (in seconds) of invite - */ - uint32_t max_age; - /** Maximum number of uses - */ - uint32_t max_uses; - /** True if a temporary invite which grants access for a limited time - */ - bool temporary; - /** True if this invite should not replace or "attach to" similar invites - */ - bool unique; - /** How many times this invite has been used - * - * @note Only set when using cluster::channel_invites_get - */ - uint32_t uses; - /** The stage instance data if there is a public stage instance in the stage channel this invite is for - * @deprecated Deprecated - */ - stage_instance stage; - - /** Constructor - */ - invite(); - - /** Destructor - */ - virtual ~invite() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - invite& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_id Include ID in JSON - * @return The JSON text of the invite - */ - virtual std::string build_json(bool with_id = false) const; - -}; - -/** A container of invites */ -typedef std::unordered_map invite_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents an invite to a discord guild or channel + */ +class DPP_EXPORT invite : public json_interface { +public: + /** Invite code + */ + std::string code; + /** Readonly expiration timestamp of this invite or 0 if the invite doesn't expire + */ + time_t expires_at; + /** Guild for the invite + */ + snowflake guild_id; + /** Channel id for invite + */ + snowflake channel_id; + /** User ID of invite creator + */ + snowflake inviter_id; + /** Target user ID of invite, for invites sent via DM + */ + snowflake target_user_id; + /** Target user type (generally this is always 1, "stream") + */ + uint8_t target_user_type; + /** Approximate number of online users + */ + uint32_t approximate_presence_count; + /** Approximate total users online and offline + */ + uint32_t approximate_member_count; + /** Maximum age (in seconds) of invite + */ + uint32_t max_age; + /** Maximum number of uses + */ + uint32_t max_uses; + /** True if a temporary invite which grants access for a limited time + */ + bool temporary; + /** True if this invite should not replace or "attach to" similar invites + */ + bool unique; + /** How many times this invite has been used + * + * @note Only set when using cluster::channel_invites_get + */ + uint32_t uses; + /** The stage instance data if there is a public stage instance in the stage channel this invite is for + * @deprecated Deprecated + */ + stage_instance stage; + + /** Constructor + */ + invite(); + + /** Destructor + */ + virtual ~invite() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + invite& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id Include ID in JSON + * @return The JSON text of the invite + */ + virtual std::string build_json(bool with_id = false) const; + +}; + +/** A container of invites */ +typedef std::unordered_map invite_map; + +}; diff --git a/3rdParty/dpp/json_interface.h b/3rdParty/dpp/json_interface.h index 5097b9b333..302642db12 100644 --- a/3rdParty/dpp/json_interface.h +++ b/3rdParty/dpp/json_interface.h @@ -1,61 +1,61 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include - -namespace dpp { - /** - * @brief Represents an interface for an object that can optionally implement functions - * for converting to and from nlohmann::json. In the event either parse_from_json() or - * build_json() are not implemented and are called, they will throw at runtime. - * - * @tparam T Type of class that implements the interface - */ - template struct DPP_EXPORT json_interface { - protected: - /* Must not destruct through pointer to json_interface. */ - ~json_interface() = default; - - public: - /** - * @brief Convert object from nlohmann::json - * - * @param j nlohmann::json object - * @return T& Reference to self for fluent calling - */ - T& fill_from_json(nlohmann::json* j) { - throw dpp::logic_exception("JSON interface doesn't implement parse_from_json"); - } - - /** - * @brief Build JSON string from the object - * - * @param with_id Include the ID in the JSON - * @return std::string JSON string version of object - */ - virtual std::string build_json(bool with_id = false) const { - throw dpp::logic_exception("JSON interface doesn't implement build_json"); - } - }; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include + +namespace dpp { + /** + * @brief Represents an interface for an object that can optionally implement functions + * for converting to and from nlohmann::json. In the event either parse_from_json() or + * build_json() are not implemented and are called, they will throw at runtime. + * + * @tparam T Type of class that implements the interface + */ + template struct DPP_EXPORT json_interface { + protected: + /* Must not destruct through pointer to json_interface. */ + ~json_interface() = default; + + public: + /** + * @brief Convert object from nlohmann::json + * + * @param j nlohmann::json object + * @return T& Reference to self for fluent calling + */ + T& fill_from_json(nlohmann::json* j) { + throw dpp::logic_exception("JSON interface doesn't implement parse_from_json"); + } + + /** + * @brief Build JSON string from the object + * + * @param with_id Include the ID in the JSON + * @return std::string JSON string version of object + */ + virtual std::string build_json(bool with_id = false) const { + throw dpp::logic_exception("JSON interface doesn't implement build_json"); + } + }; +}; diff --git a/3rdParty/dpp/managed.h b/3rdParty/dpp/managed.h index 4d4cb0fc3b..3939b8994d 100644 --- a/3rdParty/dpp/managed.h +++ b/3rdParty/dpp/managed.h @@ -1,76 +1,76 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include - -namespace dpp { - - /** @brief The managed class is the base class for various types that can - * be stored in a cache that are identified by a dpp::snowflake id. - */ - class DPP_EXPORT managed { - public: - /** - * @brief Unique ID of object set by Discord. - * This value contains a timestamp, worker ID, internal server ID, and an incrementing value. - * Only the timestamp is relevant to us as useful metadata. - */ - snowflake id; - /** - * @brief Constructor, initialises ID - * @param nid ID to set - */ - managed(const snowflake nid = 0); - /** - * @brief Destroy the managed object - */ - virtual ~managed() = default; - - /** - * @brief Get the creation time of this object according to Discord. - * - * @return double creation time inferred from the snowflake ID. - * The minimum possible value is the first second of 2015. - */ - double get_creation_time() const; - - /** - * @brief Comparison operator for comparing two managed objects by id - * - * @param other Other object to compare against - * @return true objects are the same id - * @return false objects are not the same id - */ - bool operator==(const managed& other) const noexcept; - - /** - * @brief Comparison operator for comparing two managed objects by id - * - * @param other Other object to compare against - * @return true objects are not the same id - * @return false objects are the same id - */ - bool operator!=(const managed& other) const noexcept; - }; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include + +namespace dpp { + + /** @brief The managed class is the base class for various types that can + * be stored in a cache that are identified by a dpp::snowflake id. + */ + class DPP_EXPORT managed { + public: + /** + * @brief Unique ID of object set by Discord. + * This value contains a timestamp, worker ID, internal server ID, and an incrementing value. + * Only the timestamp is relevant to us as useful metadata. + */ + snowflake id; + /** + * @brief Constructor, initialises ID + * @param nid ID to set + */ + managed(const snowflake nid = 0); + /** + * @brief Destroy the managed object + */ + virtual ~managed() = default; + + /** + * @brief Get the creation time of this object according to Discord. + * + * @return double creation time inferred from the snowflake ID. + * The minimum possible value is the first second of 2015. + */ + double get_creation_time() const; + + /** + * @brief Comparison operator for comparing two managed objects by id + * + * @param other Other object to compare against + * @return true objects are the same id + * @return false objects are not the same id + */ + bool operator==(const managed& other) const noexcept; + + /** + * @brief Comparison operator for comparing two managed objects by id + * + * @param other Other object to compare against + * @return true objects are not the same id + * @return false objects are the same id + */ + bool operator!=(const managed& other) const noexcept; + }; + +}; diff --git a/3rdParty/dpp/message.h b/3rdParty/dpp/message.h index 61dd046a3b..fb65d8824e 100644 --- a/3rdParty/dpp/message.h +++ b/3rdParty/dpp/message.h @@ -1,1491 +1,1491 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the type of a component - */ -enum component_type : uint8_t { - /// Action row, a container for other components - cot_action_row = 1, - /// Clickable button - cot_button = 2, - /// Select menu for picking from defined text options - cot_selectmenu = 3, - /// Text input - cot_text = 4, - /// Select menu for users - cot_user_selectmenu = 5, - /// Select menu for roles - cot_role_selectmenu = 6, - /// Select menu for mentionables (users and roles) - cot_mentionable_selectmenu = 7, - /// Select menu for channels - cot_channel_selectmenu = 8, -}; - -/** - * @brief Types of text input - */ -enum text_style_type : uint8_t { - /// Intended for short single-line text. - text_short = 1, - /// Intended for much longer inputs. - text_paragraph = 2, -}; - -/** - * @brief Represents the style of a button - */ -enum component_style : uint8_t { - /// Blurple - cos_primary = 1, - /// Grey - cos_secondary, - /// Green - cos_success, - /// Red - cos_danger, - /// An external hyperlink to a website - cos_link -}; - -/** - * @brief An option for a select component - */ -struct DPP_EXPORT select_option : public json_interface { - /** - * @brief Label for option - */ - std::string label; - /** - * @brief Value for option - */ - std::string value; - /** - * @brief Description of option - */ - std::string description; - /** - * @brief True if option is the default option - */ - bool is_default; - /** - * @brief Emoji definition. To set an emoji on your button - * you must set one of either the name or id fields. - * The easiest way is to use the component::set_emoji - * method. - */ - struct inner_select_emoji { - /** - * @brief Set the name field to the name of the emoji. - * For built in unicode emojis, set this to the - * actual unicode value of the emoji e.g. "😄" - * and not for example ":smile:" - */ - std::string name; - /** - * @brief The emoji ID value for emojis that are custom - * ones belonging to a guild. The same rules apply - * as with other emojis, that the bot must be on - * the guild where the emoji resides and it must - * be available for use (e.g. not disabled due to - * lack of boosts etc) - */ - dpp::snowflake id = 0; - /** - * @brief True if the emoji is animated. Only applies to - * custom emojis. - */ - bool animated = false; - } emoji; - - /** - * @brief Construct a new select option object - */ - select_option(); - - /** - * @brief Destructs the select option object. - */ - virtual ~select_option() = default; - - /** - * @brief Construct a new select option object - * - * @param label Label of option - * @param value Value of option - * @param description Description of option - */ - select_option(const std::string &label, const std::string &value, const std::string &description = ""); - - /** - * @brief Set the label - * - * @param l the user-facing name of the option. It will be truncated to the maximum length of 100 UTF-8 characters. - * @return select_option& reference to self for chaining - */ - select_option& set_label(const std::string &l); - - /** - * @brief Set the value - * - * @param v value to set. It will be truncated to the maximum length of 100 UTF-8 characters. - * @return select_option& reference to self for chaining - */ - select_option& set_value(const std::string &v); - - /** - * @brief Set the description - * - * @param d description to set. It will be truncated to the maximum length of 100 UTF-8 characters. - * @return select_option& reference to self for chaining - */ - select_option& set_description(const std::string &d); - - /** - * @brief Set the emoji - * - * @param n emoji name - * @param id emoji id for custom emojis - * @param animated true if animated emoji - * @return select_option& reference to self for chaining - */ - select_option& set_emoji(const std::string &n, dpp::snowflake id = 0, bool animated = false); - - /** - * @brief Set the option as default - * - * @param def true to set the option as default - * @return select_option& reference to self for chaining - */ - select_option& set_default(bool def); - - /** - * @brief Set the emoji as animated - * - * @param anim true if animated - * @return select_option& reference to self for chaining - */ - select_option& set_animated(bool anim); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - select_option& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief Represents the component object. - * A component is a clickable button or drop down list - * within a discord message, where the buttons emit - * on_button_click events when the user interacts with - * them. - * - * You should generally define one component object and - * then insert one or more additional components into it - * using component::add_component(), so that the parent - * object is an action row and the child objects are buttons. - */ -class DPP_EXPORT component : public json_interface { -public: - /** Component type, either a button or action row - */ - component_type type; - - /** Sub components, buttons on an action row - */ - std::vector components; - - /** Component label (for buttons, text inputs). - * Maximum of 80 characters. - */ - std::string label; - - /** Component style (for buttons) - */ - component_style style; - - /** - * @brief Text style (for text inputs) - */ - text_style_type text_style; - - /** Component id (for buttons, menus, text inputs). - * Maximum of 100 characters. - */ - std::string custom_id; - - /** URL for link types (dpp::cos_link). - * Maximum of 512 characters. - */ - std::string url; - - /** Placeholder text for select menus and text inputs (max 150 characters) - */ - std::string placeholder; - - /** Minimum number of items that must be chosen for a select menu. - * Default is -1 to not set this - */ - int32_t min_values; - - /** Maximum number of items that can be chosen for a select menu. - * Default is -1 to not set this - */ - int32_t max_values; - - /** Minimum length for text input (0-4000) - */ - int32_t min_length; - - /** Maximum length for text input (1-4000) - */ - int32_t max_length; - - /** Select options for select menus. Only required and available for select menus of type dpp::cot_selectmenu - */ - std::vector options; - - /** List of channel types (dpp::channel_type) to include in the channel select component (dpp::cot_channel_selectmenu) - */ - std::vector channel_types; - - /** Disabled flag (for buttons) - */ - bool disabled; - - /** Whether the text input is required to be filled - */ - bool required; - - /** Value of the modal (filled or valid when populated from an - * on_form_submit event, or from the set_value function) - */ - std::variant value; - - /** Emoji definition. To set an emoji on your button - * you must set one of either the name or id fields. - * The easiest way is to use the component::set_emoji - * method. - */ - struct inner_emoji { - /** Set the name field to the name of the emoji. - * For built in unicode emojis, set this to the - * actual unicode value of the emoji e.g. "😄" - * and not for example ":smile:" - */ - std::string name; - /** The emoji ID value for emojis that are custom - * ones belonging to a guild. The same rules apply - * as with other emojis, that the bot must be on - * the guild where the emoji resides and it must - * be available for use (e.g. not disabled due to - * lack of boosts etc) - */ - dpp::snowflake id; - /** True if the emoji is animated. Only applies to - * custom emojis. - */ - bool animated; - } emoji; - - /** Constructor - */ - component(); - - /** Destructor - */ - virtual ~component() = default; - - /** - * @brief Add a channel type to include in the channel select component (dpp::cot_channel_selectmenu) - * - * @param ct The dpp::channel_type - * @return component& reference to self - */ - component& add_channel_type(uint8_t ct); - - /** - * @brief Set the type of the component. Button components - * (type dpp::cot_button) should always be contained within - * an action row (type dpp::cot_action_row). As described - * below, many of the other methods automatically set this - * to the correct type so usually you should not need to - * manually call component::set_type(). - * - * @param ct The component type - * @return component& reference to self - */ - component& set_type(component_type ct); - - /** - * @brief Set the text style of a text component - * @note Sets type to `cot_text` - * - * @param ts Text style type to set - * @return component& reference to self - */ - component& set_text_style(text_style_type ts); - - /** - * @brief Set the label of the component, e.g. button text. - * For action rows, this field is ignored. Setting the - * label will auto-set the type to dpp::cot_button. - * - * @param label Label text to set. It will be truncated to the maximum length of 80 UTF-8 characters. - * @return component& Reference to self - */ - component& set_label(const std::string &label); - - /** - * @brief Set the default value of the text input component. - * For action rows, this field is ignored. Setting the - * value will auto-set the type to dpp::cot_text. - * - * @param val Value text to set. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @return component& Reference to self - */ - component& set_default_value(const std::string &val); - - /** - * @brief Set the url for dpp::cos_link types. - * Calling this function sets the style to dpp::cos_link - * and the type to dpp::cot_button. - * - * @param url URL to set. It will be truncated to the maximum length of 512 UTF-8 characters. - * @return component& reference to self. - */ - component& set_url(const std::string &url); - - /** - * @brief Set the style of the component, e.g. button colour. - * For action rows, this field is ignored. Setting the - * style will auto-set the type to dpp::cot_button. - * - * @param cs Component style to set - * @return component& reference to self - */ - component& set_style(component_style cs); - - /** - * @brief Set the id of the component. - * For action rows, this field is ignored. Setting the - * id will auto-set the type to dpp::cot_button. - * - * @param id Custom ID string to set. This ID will be sent - * for any on_button_click events related to the button. - * @note The maximum length of the Custom ID is 100 UTF-8 codepoints. - * If your Custom ID is longer than this, it will be truncated. - * @return component& Reference to self - */ - component& set_id(const std::string &id); - - /** - * @brief Set the component to disabled. - * Defaults to false on all created components. - * - * @param disable True to disable, false to disable. - * @return component& Reference to self - */ - component& set_disabled(bool disable); - - /** - * @brief Set if this component is required. - * Defaults to false on all created components. - * - * @param require True to require this, false to make it optional. - * @return component& Reference to self - */ - component& set_required(bool require); - - /** - * @brief Set the placeholder - * - * @param placeholder placeholder string. It will be truncated to the - * maximum length of 150 UTF-8 characters for select menus, and 100 UTF-8 - * characters for modals. - * @return component& Reference to self - */ - component& set_placeholder(const std::string &placeholder); - - /** - * @brief Set the min value - * - * @param min_values min value to set - * @return component& Reference to self - */ - component& set_min_values(uint32_t min_values); - - /** - * @brief Set the max value - * - * @param max_values max value to set (0 - 25) - * @return component& Reference to self - */ - component& set_max_values(uint32_t max_values); - - /** - * @brief Set the min length of text input - * - * @param min_l min value to set (0 - 25) - * @return component& Reference to self - */ - component& set_min_length(uint32_t min_l); - - /** - * @brief Set the max length of text input - * - * @param max_l max value to set - * @return component& Reference to self - */ - component& set_max_length(uint32_t max_l); - - /** - * @brief Add a select option - * - * @param option option to add - * @return component& Reference to self - */ - component& add_select_option(const select_option &option); - - /** - * @brief Add a sub-component, only valid for action rows. - * Adding subcomponents to a component will automatically - * set this component's type to dpp::cot_action_row. - * - * @param c The sub-component to add - * @return component& reference to self - */ - component& add_component(const component& c); - - /** - * @brief Set the emoji of the current sub-component. - * Only valid for buttons. Adding an emoji to a component - * will automatically set this components type to - * dpp::cot_button. One or both of name and id must be set. - * For a built in unicode emoji, you only need set name, - * and should set it to a unicode character e.g. "😄". - * For custom emojis, set the name to the name of the emoji - * on the guild, and the id to the emoji's ID. - * Setting the animated boolean is only valid for custom - * emojis. - * - * @param name Emoji name, or unicode character to use - * @param id Emoji id, for custom emojis only. - * @param animated True if the custom emoji is animated. - * @return component& Reference to self - */ - component& set_emoji(const std::string& name, dpp::snowflake id = 0, bool animated = false); - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - component& fill_from_json(nlohmann::json* j); - -}; - -/** - * @brief A footer in a dpp::embed - */ -struct DPP_EXPORT embed_footer { - /** Footer text */ - std::string text; - /** Footer icon url */ - std::string icon_url; - /** Proxied icon url */ - std::string proxy_url; - - /** Set footer's text. Returns footer itself so these methods may be "chained" - * @param t string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. - * @return A reference to self - */ - embed_footer& set_text(const std::string& t); - - /** Set footer's icon url. Returns footer itself so these methods may be "chained" - * @param i url to set as footer icon url - * @return A reference to self - */ - embed_footer& set_icon(const std::string& i); - - /** Set footer's proxied icon url. Returns footer itself so these methods may be "chained" - * @param p url to set as footer proxied icon url - * @return A reference to self - */ - embed_footer& set_proxy(const std::string& p); -}; - -/** - * @brief An video, image or thumbnail in a dpp::embed - */ -struct DPP_EXPORT embed_image { - /** URL to image or video */ - std::string url; - /** Proxied image url */ - std::string proxy_url; - /** Height (calculated by discord) */ - std::string height; - /** Width (calculated by discord) */ - std::string width; -}; - -/** - * @brief Embed provider in a dpp::embed. Received from discord but cannot be sent - */ -struct DPP_EXPORT embed_provider { - /** Provider name */ - std::string name; - /** Provider URL */ - std::string url; -}; - -/** - * @brief Author within a dpp::embed object - */ -struct DPP_EXPORT embed_author { - /** Author name */ - std::string name; - /** Author url */ - std::string url; - /** Author icon url */ - std::string icon_url; - /** Proxied icon url */ - std::string proxy_icon_url; -}; - -/** - * @brief A dpp::embed may contain zero or more fields - */ -struct DPP_EXPORT embed_field { - /** Name of field */ - std::string name; - /** Value of field (max length 1000) */ - std::string value; - /** True if the field is to be displayed inline */ - bool is_inline; -}; - -/** - * @brief A rich embed for display within a dpp::message - */ -struct DPP_EXPORT embed { - /** Optional: title of embed */ - std::string title; - /** Optional: type of embed (always "rich" for webhook embeds) */ - std::string type; - /** Optional: description of embed */ - std::string description; - /** Optional: url of embed */ - std::string url; - /** Optional: timestamp of embed content */ - time_t timestamp; - /** Optional: color code of the embed */ - uint32_t color; - /** Optional: footer information */ - std::optional footer; - /** Optional: image information */ - std::optional image; - /** Optional: thumbnail information */ - std::optional thumbnail; - /** Optional: video information (can't send these) */ - std::optional video; - /** Optional: provider information (can't send these) */ - std::optional provider; - /** Optional: author information */ - std::optional author; - /** Optional: fields information */ - std::vector fields; - - /** Constructor */ - embed(); - - /** Constructor to build embed from json object - * @param j JSON to read content from - */ - embed(nlohmann::json* j); - - /** Destructor */ - ~embed(); - - /** Set embed title. Returns the embed itself so these method calls may be "chained" - * @param text The text of the title. It will be truncated to the maximum length of 256 UTF-8 characters. - * @return A reference to self - */ - embed& set_title(const std::string &text); - - /** Set embed description. Returns the embed itself so these method calls may be "chained" - * @param text The text of the title. It will be truncated to the maximum length of 4096 UTF-8 characters. - * @return A reference to self - */ - embed& set_description(const std::string &text); - - /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" - * @param f the footer to set - * @return A reference to self - */ - embed& set_footer(const embed_footer& f); - - /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" - * @param text string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. - * @param icon_url an url to set as footer icon url - * @return A reference to self - */ - embed& set_footer(const std::string& text, const std::string& icon_url); - - /** Set embed colour. Returns the embed itself so these method calls may be "chained" - * @param col The colour of the embed - * @return A reference to self - */ - embed& set_color(uint32_t col); - - /** Set embed timestamp. Returns the embed itself so these method calls may be "chained" - * @param tstamp The timestamp to show in the footer, should be in UTC - * @return A reference to self - */ - embed& set_timestamp(time_t tstamp); - - /** Set embed url. Returns the embed itself so these method calls may be "chained" - * @param url the url of the embed - * @return A reference to self - */ - embed& set_url(const std::string &url); - - /** Add an embed field. Returns the embed itself so these method calls may be "chained" - * @param name The name of the field. It will be truncated to the maximum length of 256 UTF-8 characters. - * @param value The value of the field. It will be truncated to the maximum length of 1024 UTF-8 characters. - * @param is_inline Whether or not to display the field 'inline' or on its own line - * @return A reference to self - */ - embed& add_field(const std::string& name, const std::string &value, bool is_inline = false); - - /** Set embed author. Returns the embed itself so these method calls may be "chained" - * @param a The author to set - * @return A reference to self - */ - embed& set_author(const dpp::embed_author& a); - - /** Set embed author. Returns the embed itself so these method calls may be "chained" - * @param name The name of the author. It will be truncated to the maximum length of 256 UTF-8 characters. - * @param url The url of the author - * @param icon_url The icon URL of the author - * @return A reference to self - */ - embed& set_author(const std::string& name, const std::string& url, const std::string& icon_url); - - /** Set embed provider. Returns the embed itself so these method calls may be "chained" - * @param name The provider name. It will be truncated to the maximum length of 256 UTF-8 characters. - * @param url The provider url - * @return A reference to self - */ - embed& set_provider(const std::string& name, const std::string& url); - - /** Set embed image. Returns the embed itself so these method calls may be "chained" - * @param url The embed image URL - * @return A reference to self - */ - embed& set_image(const std::string& url); - - /** Set embed video. Returns the embed itself so these method calls may be "chained" - * @param url The embed video url - * @return A reference to self - */ - embed& set_video(const std::string& url); - - /** Set embed thumbnail. Returns the embed itself so these method calls may be "chained" - * @param url The embed thumbnail url - * @return A reference to self - */ - embed& set_thumbnail(const std::string& url); -}; - -/** - * @brief Represents a reaction to a dpp::message - */ -struct DPP_EXPORT reaction { - /** Number of times this reaction has been added */ - uint32_t count; - /** Reaction was from the bot's id */ - bool me; - /** ID of emoji for reaction */ - snowflake emoji_id; - /** Name of emoji, if applicable */ - std::string emoji_name; - - /** - * @brief Constructs a new reaction object. - */ - reaction(); - - /** - * @brief Constructs a new reaction object from a JSON object. - * @param j The JSON to read data from - */ - reaction(nlohmann::json* j); - - /** - * @brief Destructs the reaction object. - */ - ~reaction() = default; -}; - -/** - * @brief Represents an attachment in a dpp::message - */ -struct DPP_EXPORT attachment { - /** ID of attachment */ - snowflake id; - /** Size of the attachment in bytes */ - uint32_t size; - /** File name of the attachment */ - std::string filename; - /** Optional: Description of the attachment (max 1024 characters) */ - std::string description; - /** URL which points to the attachment */ - std::string url; - /** Proxied URL which points to the attachment */ - std::string proxy_url; - /** Width of the attachment, if applicable */ - uint32_t width; - /** Height of the attachment, if applicable */ - uint32_t height; - /** MIME type of the attachment, if applicable */ - std::string content_type; - /** Whether this attachment is ephemeral, if applicable */ - bool ephemeral; - /** Owning message */ - struct message* owner; - - /** - * @brief Constructs a new attachment object. - * @param o Owning dpp::message object - */ - attachment(struct message* o); - - /** - * @brief Constructs a new attachment object from a JSON object. - * @param o Owning dpp::message object - * @param j JSON to read information from - */ - attachment(struct message* o, nlohmann::json* j); - - /** - * @brief Destructs the attachment object. - */ - ~attachment() = default; - - /** - * @brief Download this attachment - * @param callback A callback which is called when the download completes. - * @note The content of the file will be in the http_info.body parameter of the - * callback parameter. - * @throw dpp::logic_exception If there is no owner associated with this attachment that - * itself has an owning cluster, this method will throw a dpp::logic_exception when called. - */ - void download(http_completion_event callback) const; -}; - -/** - * @brief Represents the type of a sticker - */ -enum sticker_type : uint8_t { - /// Nitro pack sticker - st_standard = 1, - /// Guild sticker - st_guild = 2 -}; - -/** - * @brief The file format (png, apng, lottie) of a sticker - */ -enum sticker_format : uint8_t { - sf_png = 1, - sf_apng = 2, - sf_lottie = 3 -}; - -/** - * @brief Represents stickers received in messages - */ -struct DPP_EXPORT sticker : public managed, public json_interface { - /** Optional: for standard stickers, id of the pack the sticker is from - */ - snowflake pack_id; - /** The name of the sticker */ - std::string name; - /// description of the sticker (may be empty) - std::string description; - /** for guild stickers, the Discord name of a unicode emoji representing the sticker's expression. - * for standard stickers, a comma-separated list of related expressions. - */ - std::string tags; - /** - * @brief Asset ID - * @deprecated now an empty string but still sent by discord. - * While discord still send this empty string value we will still have a field - * here in the library. - */ - std::string asset; - /** The type of sticker */ - sticker_type type; - /// type of sticker format - sticker_format format_type; - /// Optional: whether this guild sticker can be used, may be false due to loss of Server Boosts - bool available; - /// Optional: id of the guild that owns this sticker - snowflake guild_id; - /// Optional: the user that uploaded the guild sticker - user sticker_user; - /// Optional: the standard sticker's sort order within its pack - uint8_t sort_value; - /** Name of file to upload (when adding or editing a sticker) */ - std::string filename; - /** File content to upload (raw binary) */ - std::string filecontent; - - /** - * @brief Construct a new sticker object - */ - sticker(); - - virtual ~sticker() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - sticker& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_id True if the ID is to be set in the JSON structure - * @return The JSON text of the invite - */ - virtual std::string build_json(bool with_id = true) const; - - /** - * @brief Get the sticker url - * - * @param accept_lottie Whether to allow that [lottie](https://airbnb.io/lottie/#/) (json format) can be returned or not - * @return std::string The sticker url or an empty string when its a lottie and accept_lottie is false - */ - std::string get_url(bool accept_lottie = true) const; - - /** - * @brief Set the filename - * - * @param fn filename - * @return message& reference to self - */ - sticker& set_filename(const std::string &fn); - - /** - * @brief Set the file content - * - * @param fc raw file content contained in std::string - * @return message& reference to self - */ - sticker& set_file_content(const std::string &fc); - -}; - -/** - * @brief Represents a sticker pack (the built in groups of stickers that all nitro users get to use) - */ -struct DPP_EXPORT sticker_pack : public managed, public json_interface { - /// the stickers in the pack - std::map stickers; - /// name of the sticker pack - std::string name; - /// id of the pack's SKU - snowflake sku_id; - /// Optional: id of a sticker in the pack which is shown as the pack's icon - snowflake cover_sticker_id; - /// description of the sticker pack - std::string description; - /// id of the sticker pack's banner image - snowflake banner_asset_id; - - /** - * @brief Construct a new sticker pack object - */ - sticker_pack(); - - virtual ~sticker_pack() = default; - - /** Read class values from json object - * @param j A json object to read from - * @return A reference to self - */ - sticker_pack& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_id True if the ID is to be set in the JSON structure - * @return The JSON text of the invite - */ - virtual std::string build_json(bool with_id = true) const; - -}; - -/** - * @brief Bitmask flags for a dpp::message - */ -enum message_flags : uint16_t { - /// this message has been published to subscribed channels (via Channel Following) - m_crossposted = 1 << 0, - /// this message originated from a message in another channel (via Channel Following) - m_is_crosspost = 1 << 1, - /// do not include any embeds when serializing this message - m_suppress_embeds = 1 << 2, - /// the source message for this crosspost has been deleted (via Channel Following) - m_source_message_deleted = 1 << 3, - /// this message came from the urgent message system - m_urgent = 1 << 4, - /// this message has an associated thread, with the same id as the message - m_has_thread = 1 << 5, - /// this message is only visible to the user who invoked the Interaction - m_ephemeral = 1 << 6, - /// this message is an Interaction Response and the bot is "thinking" - m_loading = 1 << 7, - /// this message failed to mention some roles and add their members to the thread - m_thread_mention_failed = 1 << 8, -}; - -/** - * @brief Represents possible values for the dpp::embed type field. - * These are loosely defined by the API docs and do not influence how the client renders embeds. - * The only type a bot can send is dpp::embed_type::emt_rich. - */ -namespace embed_type { - /** - * @brief Rich text - */ - const std::string emt_rich = "rich"; - /** - * @brief Image - */ - const std::string emt_image = "image"; - /** - * @brief Video link - */ - const std::string emt_video = "video"; - /** - * @brief Animated gif - */ - const std::string emt_gifv = "gifv"; - /** - * @brief Article - */ - const std::string emt_article = "article"; - /** - * @brief Link URL - */ - const std::string emt_link = "link"; - /** - * @brief Auto moderation filter - */ - const std::string emt_automod = "auto_moderation_message"; -}; - -/** - * @brief Message types for dpp::message::type - */ -enum message_type { - /// Default - mt_default = 0, - /// Add recipient - mt_recipient_add = 1, - /// Remove recipient - mt_recipient_remove = 2, - /// Call - mt_call = 3, - /// Channel name change - mt_channel_name_change = 4, - /// Channel icon change - mt_channel_icon_change = 5, - /// Message pinned - mt_channel_pinned_message = 6, - /// Member joined - mt_guild_member_join = 7, - /// Boost - mt_user_premium_guild_subscription = 8, - /// Boost level 1 - mt_user_premium_guild_subscription_tier_1 = 9, - /// Boost level 2 - mt_user_premium_guild_subscription_tier_2 = 10, - /// Boost level 3 - mt_user_premium_guild_subscription_tier_3 = 11, - /// Follow channel - mt_channel_follow_add = 12, - /// Disqualified from discovery - mt_guild_discovery_disqualified = 14, - /// Re-qualified for discovery - mt_guild_discovery_requalified = 15, - /// Discovery grace period warning 1 - mt_guild_discovery_grace_period_initial_warning = 16, - /// Discovery grace period warning 2 - mt_guild_discovery_grace_period_final_warning = 17, - /// Thread Created - mt_thread_created = 18, - /// Reply - mt_reply = 19, - /// Application command - mt_application_command = 20, - /// Thread starter message - mt_thread_starter_message = 21, - /// Invite reminder - mt_guild_invite_reminder = 22, - /// Context Menu Command - mt_context_menu_command = 23, - /// Auto moderation action - mt_auto_moderation_action = 24, -}; - -/** - * @brief Represents the caching policy of a cache in the library. - */ -enum cache_policy_setting_t { - /** - * @brief request aggressively on seeing new guilds, and also store missing data from messages. - * This is the default behaviour and the least memory-efficient option. Memory usage will increase - * over time, initially quite rapidly, and then linearly over time. It is the least cpu-intensive - * setting. - */ - cp_aggressive = 0, - /** - * @brief only cache when there is relevant activity, e.g. a message to the bot. - * This is a good middle-ground, memory usage will increase linearly over time. - */ - cp_lazy = 1, - /** - * @brief Don't cache anything. Fill details when we see them. - * This is the most memory-efficient option but consumes more CPU time - */ - cp_none = 2 -}; - -/** - * @brief Represents the caching policy of the cluster. - * - * Channels and guilds are always cached as these caches are used - * internally by the library. The memory usage of these is minimal. - * - * All default to 'aggressive' which means to actively attempt to cache, - * going out of the way to fill the caches completely. On large bots this - * can take a LOT of RAM. - */ -struct DPP_EXPORT cache_policy_t { - /** - * @brief Caching policy for users and guild members - */ - cache_policy_setting_t user_policy = cp_aggressive; - - /** - * @brief Caching policy for emojis - */ - cache_policy_setting_t emoji_policy = cp_aggressive; - - /** - * @brief Caching policy for roles - */ - cache_policy_setting_t role_policy = cp_aggressive; -}; - -/** - * @brief Represents messages sent and received on Discord - */ -struct DPP_EXPORT message : public managed { - /** id of the channel the message was sent in */ - snowflake channel_id; - /** Optional: id of the guild the message was sent in */ - snowflake guild_id; - /** the author of this message (not guaranteed to be a valid user) */ - user author; - /** Optional: member properties for this message's author */ - guild_member member; - /** contents of the message */ - std::string content; - /** message components */ - std::vector components; - /** when this message was sent */ - time_t sent; - /** when this message was edited (may be 0 if never edited) */ - time_t edited; - /** users specifically mentioned in the message */ - std::vector> mentions; - /** roles specifically mentioned in this message (only IDs currently)*/ - std::vector mention_roles; - /** Channels mentioned in the message. (Discord: not all types supported) - * Discord: Only textual channels that are visible to everyone in a lurkable guild will ever be included. Only crossposted messages (via Channel Following) currently include mention_channels at all. (includes ID, Guild ID, Type, Name)*/ - std::vector mention_channels; - /** any attached files */ - std::vector attachments; - /** zero or more dpp::embed objects */ - std::vector embeds; - /** Optional: reactions to the message */ - std::vector reactions; - /** Optional: used for validating a message was sent */ - std::string nonce; - /** Optional: if the message is generated by a webhook, its id will be here otherwise the field will be 0 */ - snowflake webhook_id; - /** Stickers */ - std::vector stickers; - - /** Name of file to upload (for use server-side in discord's url) */ - std::vector filename; - - /** File content to upload (raw binary) */ - std::vector filecontent; - - /** - * @brief Reference to another message, e.g. a reply - */ - struct message_ref { - /// id of the originating message - snowflake message_id; - /// id of the originating message's channel - snowflake channel_id; - /// id of the originating message's guild - snowflake guild_id; - /// when sending, whether to error if the referenced message doesn't exist instead of sending as a normal (non-reply) message, default true - bool fail_if_not_exists; - } message_reference; - - /** - * @brief Reference to an interaction - */ - struct message_interaction_struct{ - /// id of the interaction - snowflake id; - /// type of interaction - uint8_t type; - /// name of the application command - std::string name; - /// the user who invoked the interaction - user usr; - } interaction; - - /** - * @brief Allowed mentions details - */ - struct allowed_ref { - /** - * @brief Set to true to parse user mentions in the text. Default is false - */ - bool parse_users; - /** - * @brief Set to true to at-everyone and at-here mentions in the text. Default is false - */ - bool parse_everyone; - /** - * @brief Set to true to parse role mentions in the text. Default is false - */ - bool parse_roles; - /** - * @brief Set to true to mention the user who sent the message this one is replying to. Default is false - */ - bool replied_user; - /** - * @brief List of users to allow pings for - */ - std::vector users; - /** - * @brief List of roles to allow pings for - */ - std::vector roles; - } allowed_mentions; - - /** - * @brief The cluster which created this message object - */ - class cluster* owner; - - /** Message type */ - message_type type; - - /** Flags. Made of bits in dpp::message_flags */ - uint16_t flags; - - /** whether this message is pinned */ - bool pinned; - /** whether this was a TTS message */ - bool tts; - /** whether this message mentions everyone */ - bool mention_everyone; - - /** - * @brief Construct a new message object - */ - message(); - - /** - * @brief Construct a new message object - * @param o Owning cluster, passed down to various things such as dpp::attachment. - * Owning cluster is optional (can be nullptr) and if nulled, will prevent some functions - * such as attachment::download from functioning (they will throw, if used) - */ - message(class cluster* o); - - /** - * @brief Destroy the message object - */ - virtual ~message(); - - /** - * @brief Construct a new message object with a channel and content - * - * @param channel_id The channel to send the message to - * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @param type The message type to create - */ - message(snowflake channel_id, const std::string &content, message_type type = mt_default); - - /** - * @brief Construct a new message object with a channel and content - * - * @param channel_id The channel to send the message to - * @param _embed An embed to send - */ - message(snowflake channel_id, const embed & _embed); - - /** - * @brief Construct a new message object with content - * - * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @param type The message type to create - */ - message(const std::string &content, message_type type = mt_default); - - /** - * @brief Set the original message reference for replies/crossposts - * - * @param _message_id message id to reply to - * @param _guild_id guild id to reply to (optional) - * @param _channel_id channel id to reply to (optional) - * @param fail_if_not_exists true if the message send should fail if these values are invalid (optional) - * @return message& reference to self - */ - message& set_reference(snowflake _message_id, snowflake _guild_id = 0, snowflake _channel_id = 0, bool fail_if_not_exists = false); - - /** - * @brief Set the allowed mentions object for pings on the message - * - * @param _parse_users whether or not to parse users in the message content or embeds - * @param _parse_roles whether or not to parse roles in the message content or embeds - * @param _parse_everyone whether or not to parse everyone/here in the message content or embeds - * @param _replied_user if set to true and this is a reply, then ping the user we reply to - * @param users list of user ids to allow pings for - * @param roles list of role ids to allow pings for - * @return message& reference to self - */ - message& set_allowed_mentions(bool _parse_users, bool _parse_roles, bool _parse_everyone, bool _replied_user, const std::vector &users, const std::vector &roles); - - /** Fill this object from json. - * @param j JSON object to fill from - * @param cp Cache policy for user records, whether or not we cache users when a message is received - * @return A reference to self - */ - message& fill_from_json(nlohmann::json* j, cache_policy_t cp = {cp_aggressive, cp_aggressive, cp_aggressive}); - - /** Build JSON from this object. - * @param with_id True if the ID is to be included in the built JSON - * @param is_interaction_response Set to true if this message is intended to be included in an interaction response. - * This will exclude some fields that are not valid in interactions at this time. - * @return The JSON text of the message - */ - virtual std::string build_json(bool with_id = false, bool is_interaction_response = false) const; - - /** - * @brief Returns true if the message was crossposted to other servers - * - * @return true if crossposted - */ - bool is_crossposted() const; - - /** - * @brief Returns true if posted from other servers announcement channel via webhook - * - * @return true if posted from other server - */ - bool is_crosspost() const; - - /** - * @brief True if embeds have been removed - * - * @return true if embeds removed - */ - bool suppress_embeds() const; - - /** - * @brief True if source message was deleted - * - * @return true if source message deleted - */ - bool is_source_message_deleted() const; - - /** - * @brief True if urgent - * - * @return true if urgent - */ - bool is_urgent() const; - - /** - * @brief True if has thread attached - * - * @return true if has thread attached - */ - bool has_thread() const; - - /** - * @brief True if ephemeral (visible only to issuer of a slash command) - * - * @return true if ephemeral - */ - bool is_ephemeral() const; - - /** - * @brief True if loading - * - * @return true if loading - */ - bool is_loading() const; - - /** - * @brief Returns true if this message failed to mention some roles and add their members to the thread - * - * @return true if this message failed to mention some roles and add their members to the thread - */ - bool is_thread_mention_failed() const; - - /** - * @brief Add a component (button) to message - * - * @param c component to add - * @return message& reference to self - */ - message& add_component(const component& c); - - /** - * @brief Add an embed to message - * - * @param e embed to add - * @return message& reference to self - */ - message& add_embed(const embed& e); - - /** - * @brief Set the flags - * - * @param f flags to set from dpp::message_flags - * @return message& reference to self - */ - message& set_flags(uint16_t f); - - /** - * @brief Set the message type - * - * @param t type to set - * @return message& reference to self - */ - message& set_type(message_type t); - - /** - * @brief Set the filename of the last file in list - * - * @param fn filename - * @return message& reference to self - * @deprecated Use message::add_file instead - */ - message& set_filename(const std::string &fn); - - /** - * @brief Set the file content of the last file in list - * - * @param fc raw file content contained in std::string - * @return message& reference to self - * @deprecated Use message::add_file instead - */ - message& set_file_content(const std::string &fc); - - /** - * @brief Add a file to the message - * - * @param filename filename - * @param filecontent raw file content contained in std::string - * @return message& reference to self - */ - message& add_file(const std::string &filename, const std::string &filecontent); - - /** - * @brief Set the message content - * - * @param c message content. It will be truncated to the maximum length of 4000 UTF-8 characters. - * @return message& reference to self - */ - message& set_content(const std::string &c); - - /** - * @brief Set the channel id - * - * @param _channel_id channel id - * @return message& reference to self - */ - message& set_channel_id(snowflake _channel_id); - - /** - * @brief Set the channel id - * - * @param _guild_id channel id - * @return message& reference to self - */ - message& set_guild_id(snowflake _guild_id); - - /** - * @brief Returns true if the message is from a DM - * - * @return true if message is a DM - */ - bool is_dm() const; -}; - -/** A group of messages */ -typedef std::unordered_map message_map; - -/** A group of stickers */ -typedef std::unordered_map sticker_map; - -/** A group of sticker packs */ -typedef std::unordered_map sticker_pack_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the type of a component + */ +enum component_type : uint8_t { + /// Action row, a container for other components + cot_action_row = 1, + /// Clickable button + cot_button = 2, + /// Select menu for picking from defined text options + cot_selectmenu = 3, + /// Text input + cot_text = 4, + /// Select menu for users + cot_user_selectmenu = 5, + /// Select menu for roles + cot_role_selectmenu = 6, + /// Select menu for mentionables (users and roles) + cot_mentionable_selectmenu = 7, + /// Select menu for channels + cot_channel_selectmenu = 8, +}; + +/** + * @brief Types of text input + */ +enum text_style_type : uint8_t { + /// Intended for short single-line text. + text_short = 1, + /// Intended for much longer inputs. + text_paragraph = 2, +}; + +/** + * @brief Represents the style of a button + */ +enum component_style : uint8_t { + /// Blurple + cos_primary = 1, + /// Grey + cos_secondary, + /// Green + cos_success, + /// Red + cos_danger, + /// An external hyperlink to a website + cos_link +}; + +/** + * @brief An option for a select component + */ +struct DPP_EXPORT select_option : public json_interface { + /** + * @brief Label for option + */ + std::string label; + /** + * @brief Value for option + */ + std::string value; + /** + * @brief Description of option + */ + std::string description; + /** + * @brief True if option is the default option + */ + bool is_default; + /** + * @brief Emoji definition. To set an emoji on your button + * you must set one of either the name or id fields. + * The easiest way is to use the component::set_emoji + * method. + */ + struct inner_select_emoji { + /** + * @brief Set the name field to the name of the emoji. + * For built in unicode emojis, set this to the + * actual unicode value of the emoji e.g. "😄" + * and not for example ":smile:" + */ + std::string name; + /** + * @brief The emoji ID value for emojis that are custom + * ones belonging to a guild. The same rules apply + * as with other emojis, that the bot must be on + * the guild where the emoji resides and it must + * be available for use (e.g. not disabled due to + * lack of boosts etc) + */ + dpp::snowflake id = 0; + /** + * @brief True if the emoji is animated. Only applies to + * custom emojis. + */ + bool animated = false; + } emoji; + + /** + * @brief Construct a new select option object + */ + select_option(); + + /** + * @brief Destructs the select option object. + */ + virtual ~select_option() = default; + + /** + * @brief Construct a new select option object + * + * @param label Label of option + * @param value Value of option + * @param description Description of option + */ + select_option(const std::string &label, const std::string &value, const std::string &description = ""); + + /** + * @brief Set the label + * + * @param l the user-facing name of the option. It will be truncated to the maximum length of 100 UTF-8 characters. + * @return select_option& reference to self for chaining + */ + select_option& set_label(const std::string &l); + + /** + * @brief Set the value + * + * @param v value to set. It will be truncated to the maximum length of 100 UTF-8 characters. + * @return select_option& reference to self for chaining + */ + select_option& set_value(const std::string &v); + + /** + * @brief Set the description + * + * @param d description to set. It will be truncated to the maximum length of 100 UTF-8 characters. + * @return select_option& reference to self for chaining + */ + select_option& set_description(const std::string &d); + + /** + * @brief Set the emoji + * + * @param n emoji name + * @param id emoji id for custom emojis + * @param animated true if animated emoji + * @return select_option& reference to self for chaining + */ + select_option& set_emoji(const std::string &n, dpp::snowflake id = 0, bool animated = false); + + /** + * @brief Set the option as default + * + * @param def true to set the option as default + * @return select_option& reference to self for chaining + */ + select_option& set_default(bool def); + + /** + * @brief Set the emoji as animated + * + * @param anim true if animated + * @return select_option& reference to self for chaining + */ + select_option& set_animated(bool anim); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + select_option& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief Represents the component object. + * A component is a clickable button or drop down list + * within a discord message, where the buttons emit + * on_button_click events when the user interacts with + * them. + * + * You should generally define one component object and + * then insert one or more additional components into it + * using component::add_component(), so that the parent + * object is an action row and the child objects are buttons. + */ +class DPP_EXPORT component : public json_interface { +public: + /** Component type, either a button or action row + */ + component_type type; + + /** Sub components, buttons on an action row + */ + std::vector components; + + /** Component label (for buttons, text inputs). + * Maximum of 80 characters. + */ + std::string label; + + /** Component style (for buttons) + */ + component_style style; + + /** + * @brief Text style (for text inputs) + */ + text_style_type text_style; + + /** Component id (for buttons, menus, text inputs). + * Maximum of 100 characters. + */ + std::string custom_id; + + /** URL for link types (dpp::cos_link). + * Maximum of 512 characters. + */ + std::string url; + + /** Placeholder text for select menus and text inputs (max 150 characters) + */ + std::string placeholder; + + /** Minimum number of items that must be chosen for a select menu. + * Default is -1 to not set this + */ + int32_t min_values; + + /** Maximum number of items that can be chosen for a select menu. + * Default is -1 to not set this + */ + int32_t max_values; + + /** Minimum length for text input (0-4000) + */ + int32_t min_length; + + /** Maximum length for text input (1-4000) + */ + int32_t max_length; + + /** Select options for select menus. Only required and available for select menus of type dpp::cot_selectmenu + */ + std::vector options; + + /** List of channel types (dpp::channel_type) to include in the channel select component (dpp::cot_channel_selectmenu) + */ + std::vector channel_types; + + /** Disabled flag (for buttons) + */ + bool disabled; + + /** Whether the text input is required to be filled + */ + bool required; + + /** Value of the modal (filled or valid when populated from an + * on_form_submit event, or from the set_value function) + */ + std::variant value; + + /** Emoji definition. To set an emoji on your button + * you must set one of either the name or id fields. + * The easiest way is to use the component::set_emoji + * method. + */ + struct inner_emoji { + /** Set the name field to the name of the emoji. + * For built in unicode emojis, set this to the + * actual unicode value of the emoji e.g. "😄" + * and not for example ":smile:" + */ + std::string name; + /** The emoji ID value for emojis that are custom + * ones belonging to a guild. The same rules apply + * as with other emojis, that the bot must be on + * the guild where the emoji resides and it must + * be available for use (e.g. not disabled due to + * lack of boosts etc) + */ + dpp::snowflake id; + /** True if the emoji is animated. Only applies to + * custom emojis. + */ + bool animated; + } emoji; + + /** Constructor + */ + component(); + + /** Destructor + */ + virtual ~component() = default; + + /** + * @brief Add a channel type to include in the channel select component (dpp::cot_channel_selectmenu) + * + * @param ct The dpp::channel_type + * @return component& reference to self + */ + component& add_channel_type(uint8_t ct); + + /** + * @brief Set the type of the component. Button components + * (type dpp::cot_button) should always be contained within + * an action row (type dpp::cot_action_row). As described + * below, many of the other methods automatically set this + * to the correct type so usually you should not need to + * manually call component::set_type(). + * + * @param ct The component type + * @return component& reference to self + */ + component& set_type(component_type ct); + + /** + * @brief Set the text style of a text component + * @note Sets type to `cot_text` + * + * @param ts Text style type to set + * @return component& reference to self + */ + component& set_text_style(text_style_type ts); + + /** + * @brief Set the label of the component, e.g. button text. + * For action rows, this field is ignored. Setting the + * label will auto-set the type to dpp::cot_button. + * + * @param label Label text to set. It will be truncated to the maximum length of 80 UTF-8 characters. + * @return component& Reference to self + */ + component& set_label(const std::string &label); + + /** + * @brief Set the default value of the text input component. + * For action rows, this field is ignored. Setting the + * value will auto-set the type to dpp::cot_text. + * + * @param val Value text to set. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @return component& Reference to self + */ + component& set_default_value(const std::string &val); + + /** + * @brief Set the url for dpp::cos_link types. + * Calling this function sets the style to dpp::cos_link + * and the type to dpp::cot_button. + * + * @param url URL to set. It will be truncated to the maximum length of 512 UTF-8 characters. + * @return component& reference to self. + */ + component& set_url(const std::string &url); + + /** + * @brief Set the style of the component, e.g. button colour. + * For action rows, this field is ignored. Setting the + * style will auto-set the type to dpp::cot_button. + * + * @param cs Component style to set + * @return component& reference to self + */ + component& set_style(component_style cs); + + /** + * @brief Set the id of the component. + * For action rows, this field is ignored. Setting the + * id will auto-set the type to dpp::cot_button. + * + * @param id Custom ID string to set. This ID will be sent + * for any on_button_click events related to the button. + * @note The maximum length of the Custom ID is 100 UTF-8 codepoints. + * If your Custom ID is longer than this, it will be truncated. + * @return component& Reference to self + */ + component& set_id(const std::string &id); + + /** + * @brief Set the component to disabled. + * Defaults to false on all created components. + * + * @param disable True to disable, false to disable. + * @return component& Reference to self + */ + component& set_disabled(bool disable); + + /** + * @brief Set if this component is required. + * Defaults to false on all created components. + * + * @param require True to require this, false to make it optional. + * @return component& Reference to self + */ + component& set_required(bool require); + + /** + * @brief Set the placeholder + * + * @param placeholder placeholder string. It will be truncated to the + * maximum length of 150 UTF-8 characters for select menus, and 100 UTF-8 + * characters for modals. + * @return component& Reference to self + */ + component& set_placeholder(const std::string &placeholder); + + /** + * @brief Set the min value + * + * @param min_values min value to set + * @return component& Reference to self + */ + component& set_min_values(uint32_t min_values); + + /** + * @brief Set the max value + * + * @param max_values max value to set (0 - 25) + * @return component& Reference to self + */ + component& set_max_values(uint32_t max_values); + + /** + * @brief Set the min length of text input + * + * @param min_l min value to set (0 - 25) + * @return component& Reference to self + */ + component& set_min_length(uint32_t min_l); + + /** + * @brief Set the max length of text input + * + * @param max_l max value to set + * @return component& Reference to self + */ + component& set_max_length(uint32_t max_l); + + /** + * @brief Add a select option + * + * @param option option to add + * @return component& Reference to self + */ + component& add_select_option(const select_option &option); + + /** + * @brief Add a sub-component, only valid for action rows. + * Adding subcomponents to a component will automatically + * set this component's type to dpp::cot_action_row. + * + * @param c The sub-component to add + * @return component& reference to self + */ + component& add_component(const component& c); + + /** + * @brief Set the emoji of the current sub-component. + * Only valid for buttons. Adding an emoji to a component + * will automatically set this components type to + * dpp::cot_button. One or both of name and id must be set. + * For a built in unicode emoji, you only need set name, + * and should set it to a unicode character e.g. "😄". + * For custom emojis, set the name to the name of the emoji + * on the guild, and the id to the emoji's ID. + * Setting the animated boolean is only valid for custom + * emojis. + * + * @param name Emoji name, or unicode character to use + * @param id Emoji id, for custom emojis only. + * @param animated True if the custom emoji is animated. + * @return component& Reference to self + */ + component& set_emoji(const std::string& name, dpp::snowflake id = 0, bool animated = false); + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + component& fill_from_json(nlohmann::json* j); + +}; + +/** + * @brief A footer in a dpp::embed + */ +struct DPP_EXPORT embed_footer { + /** Footer text */ + std::string text; + /** Footer icon url */ + std::string icon_url; + /** Proxied icon url */ + std::string proxy_url; + + /** Set footer's text. Returns footer itself so these methods may be "chained" + * @param t string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. + * @return A reference to self + */ + embed_footer& set_text(const std::string& t); + + /** Set footer's icon url. Returns footer itself so these methods may be "chained" + * @param i url to set as footer icon url + * @return A reference to self + */ + embed_footer& set_icon(const std::string& i); + + /** Set footer's proxied icon url. Returns footer itself so these methods may be "chained" + * @param p url to set as footer proxied icon url + * @return A reference to self + */ + embed_footer& set_proxy(const std::string& p); +}; + +/** + * @brief An video, image or thumbnail in a dpp::embed + */ +struct DPP_EXPORT embed_image { + /** URL to image or video */ + std::string url; + /** Proxied image url */ + std::string proxy_url; + /** Height (calculated by discord) */ + std::string height; + /** Width (calculated by discord) */ + std::string width; +}; + +/** + * @brief Embed provider in a dpp::embed. Received from discord but cannot be sent + */ +struct DPP_EXPORT embed_provider { + /** Provider name */ + std::string name; + /** Provider URL */ + std::string url; +}; + +/** + * @brief Author within a dpp::embed object + */ +struct DPP_EXPORT embed_author { + /** Author name */ + std::string name; + /** Author url */ + std::string url; + /** Author icon url */ + std::string icon_url; + /** Proxied icon url */ + std::string proxy_icon_url; +}; + +/** + * @brief A dpp::embed may contain zero or more fields + */ +struct DPP_EXPORT embed_field { + /** Name of field */ + std::string name; + /** Value of field (max length 1000) */ + std::string value; + /** True if the field is to be displayed inline */ + bool is_inline; +}; + +/** + * @brief A rich embed for display within a dpp::message + */ +struct DPP_EXPORT embed { + /** Optional: title of embed */ + std::string title; + /** Optional: type of embed (always "rich" for webhook embeds) */ + std::string type; + /** Optional: description of embed */ + std::string description; + /** Optional: url of embed */ + std::string url; + /** Optional: timestamp of embed content */ + time_t timestamp; + /** Optional: color code of the embed */ + uint32_t color; + /** Optional: footer information */ + std::optional footer; + /** Optional: image information */ + std::optional image; + /** Optional: thumbnail information */ + std::optional thumbnail; + /** Optional: video information (can't send these) */ + std::optional video; + /** Optional: provider information (can't send these) */ + std::optional provider; + /** Optional: author information */ + std::optional author; + /** Optional: fields information */ + std::vector fields; + + /** Constructor */ + embed(); + + /** Constructor to build embed from json object + * @param j JSON to read content from + */ + embed(nlohmann::json* j); + + /** Destructor */ + ~embed(); + + /** Set embed title. Returns the embed itself so these method calls may be "chained" + * @param text The text of the title. It will be truncated to the maximum length of 256 UTF-8 characters. + * @return A reference to self + */ + embed& set_title(const std::string &text); + + /** Set embed description. Returns the embed itself so these method calls may be "chained" + * @param text The text of the title. It will be truncated to the maximum length of 4096 UTF-8 characters. + * @return A reference to self + */ + embed& set_description(const std::string &text); + + /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" + * @param f the footer to set + * @return A reference to self + */ + embed& set_footer(const embed_footer& f); + + /** Set the footer of the embed. Returns the embed itself so these method calls may be "chained" + * @param text string to set as footer text. It will be truncated to the maximum length of 2048 UTF-8 characters. + * @param icon_url an url to set as footer icon url + * @return A reference to self + */ + embed& set_footer(const std::string& text, const std::string& icon_url); + + /** Set embed colour. Returns the embed itself so these method calls may be "chained" + * @param col The colour of the embed + * @return A reference to self + */ + embed& set_color(uint32_t col); + + /** Set embed timestamp. Returns the embed itself so these method calls may be "chained" + * @param tstamp The timestamp to show in the footer, should be in UTC + * @return A reference to self + */ + embed& set_timestamp(time_t tstamp); + + /** Set embed url. Returns the embed itself so these method calls may be "chained" + * @param url the url of the embed + * @return A reference to self + */ + embed& set_url(const std::string &url); + + /** Add an embed field. Returns the embed itself so these method calls may be "chained" + * @param name The name of the field. It will be truncated to the maximum length of 256 UTF-8 characters. + * @param value The value of the field. It will be truncated to the maximum length of 1024 UTF-8 characters. + * @param is_inline Whether or not to display the field 'inline' or on its own line + * @return A reference to self + */ + embed& add_field(const std::string& name, const std::string &value, bool is_inline = false); + + /** Set embed author. Returns the embed itself so these method calls may be "chained" + * @param a The author to set + * @return A reference to self + */ + embed& set_author(const dpp::embed_author& a); + + /** Set embed author. Returns the embed itself so these method calls may be "chained" + * @param name The name of the author. It will be truncated to the maximum length of 256 UTF-8 characters. + * @param url The url of the author + * @param icon_url The icon URL of the author + * @return A reference to self + */ + embed& set_author(const std::string& name, const std::string& url, const std::string& icon_url); + + /** Set embed provider. Returns the embed itself so these method calls may be "chained" + * @param name The provider name. It will be truncated to the maximum length of 256 UTF-8 characters. + * @param url The provider url + * @return A reference to self + */ + embed& set_provider(const std::string& name, const std::string& url); + + /** Set embed image. Returns the embed itself so these method calls may be "chained" + * @param url The embed image URL + * @return A reference to self + */ + embed& set_image(const std::string& url); + + /** Set embed video. Returns the embed itself so these method calls may be "chained" + * @param url The embed video url + * @return A reference to self + */ + embed& set_video(const std::string& url); + + /** Set embed thumbnail. Returns the embed itself so these method calls may be "chained" + * @param url The embed thumbnail url + * @return A reference to self + */ + embed& set_thumbnail(const std::string& url); +}; + +/** + * @brief Represents a reaction to a dpp::message + */ +struct DPP_EXPORT reaction { + /** Number of times this reaction has been added */ + uint32_t count; + /** Reaction was from the bot's id */ + bool me; + /** ID of emoji for reaction */ + snowflake emoji_id; + /** Name of emoji, if applicable */ + std::string emoji_name; + + /** + * @brief Constructs a new reaction object. + */ + reaction(); + + /** + * @brief Constructs a new reaction object from a JSON object. + * @param j The JSON to read data from + */ + reaction(nlohmann::json* j); + + /** + * @brief Destructs the reaction object. + */ + ~reaction() = default; +}; + +/** + * @brief Represents an attachment in a dpp::message + */ +struct DPP_EXPORT attachment { + /** ID of attachment */ + snowflake id; + /** Size of the attachment in bytes */ + uint32_t size; + /** File name of the attachment */ + std::string filename; + /** Optional: Description of the attachment (max 1024 characters) */ + std::string description; + /** URL which points to the attachment */ + std::string url; + /** Proxied URL which points to the attachment */ + std::string proxy_url; + /** Width of the attachment, if applicable */ + uint32_t width; + /** Height of the attachment, if applicable */ + uint32_t height; + /** MIME type of the attachment, if applicable */ + std::string content_type; + /** Whether this attachment is ephemeral, if applicable */ + bool ephemeral; + /** Owning message */ + struct message* owner; + + /** + * @brief Constructs a new attachment object. + * @param o Owning dpp::message object + */ + attachment(struct message* o); + + /** + * @brief Constructs a new attachment object from a JSON object. + * @param o Owning dpp::message object + * @param j JSON to read information from + */ + attachment(struct message* o, nlohmann::json* j); + + /** + * @brief Destructs the attachment object. + */ + ~attachment() = default; + + /** + * @brief Download this attachment + * @param callback A callback which is called when the download completes. + * @note The content of the file will be in the http_info.body parameter of the + * callback parameter. + * @throw dpp::logic_exception If there is no owner associated with this attachment that + * itself has an owning cluster, this method will throw a dpp::logic_exception when called. + */ + void download(http_completion_event callback) const; +}; + +/** + * @brief Represents the type of a sticker + */ +enum sticker_type : uint8_t { + /// Nitro pack sticker + st_standard = 1, + /// Guild sticker + st_guild = 2 +}; + +/** + * @brief The file format (png, apng, lottie) of a sticker + */ +enum sticker_format : uint8_t { + sf_png = 1, + sf_apng = 2, + sf_lottie = 3 +}; + +/** + * @brief Represents stickers received in messages + */ +struct DPP_EXPORT sticker : public managed, public json_interface { + /** Optional: for standard stickers, id of the pack the sticker is from + */ + snowflake pack_id; + /** The name of the sticker */ + std::string name; + /// description of the sticker (may be empty) + std::string description; + /** for guild stickers, the Discord name of a unicode emoji representing the sticker's expression. + * for standard stickers, a comma-separated list of related expressions. + */ + std::string tags; + /** + * @brief Asset ID + * @deprecated now an empty string but still sent by discord. + * While discord still send this empty string value we will still have a field + * here in the library. + */ + std::string asset; + /** The type of sticker */ + sticker_type type; + /// type of sticker format + sticker_format format_type; + /// Optional: whether this guild sticker can be used, may be false due to loss of Server Boosts + bool available; + /// Optional: id of the guild that owns this sticker + snowflake guild_id; + /// Optional: the user that uploaded the guild sticker + user sticker_user; + /// Optional: the standard sticker's sort order within its pack + uint8_t sort_value; + /** Name of file to upload (when adding or editing a sticker) */ + std::string filename; + /** File content to upload (raw binary) */ + std::string filecontent; + + /** + * @brief Construct a new sticker object + */ + sticker(); + + virtual ~sticker() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + sticker& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id True if the ID is to be set in the JSON structure + * @return The JSON text of the invite + */ + virtual std::string build_json(bool with_id = true) const; + + /** + * @brief Get the sticker url + * + * @param accept_lottie Whether to allow that [lottie](https://airbnb.io/lottie/#/) (json format) can be returned or not + * @return std::string The sticker url or an empty string when its a lottie and accept_lottie is false + */ + std::string get_url(bool accept_lottie = true) const; + + /** + * @brief Set the filename + * + * @param fn filename + * @return message& reference to self + */ + sticker& set_filename(const std::string &fn); + + /** + * @brief Set the file content + * + * @param fc raw file content contained in std::string + * @return message& reference to self + */ + sticker& set_file_content(const std::string &fc); + +}; + +/** + * @brief Represents a sticker pack (the built in groups of stickers that all nitro users get to use) + */ +struct DPP_EXPORT sticker_pack : public managed, public json_interface { + /// the stickers in the pack + std::map stickers; + /// name of the sticker pack + std::string name; + /// id of the pack's SKU + snowflake sku_id; + /// Optional: id of a sticker in the pack which is shown as the pack's icon + snowflake cover_sticker_id; + /// description of the sticker pack + std::string description; + /// id of the sticker pack's banner image + snowflake banner_asset_id; + + /** + * @brief Construct a new sticker pack object + */ + sticker_pack(); + + virtual ~sticker_pack() = default; + + /** Read class values from json object + * @param j A json object to read from + * @return A reference to self + */ + sticker_pack& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_id True if the ID is to be set in the JSON structure + * @return The JSON text of the invite + */ + virtual std::string build_json(bool with_id = true) const; + +}; + +/** + * @brief Bitmask flags for a dpp::message + */ +enum message_flags : uint16_t { + /// this message has been published to subscribed channels (via Channel Following) + m_crossposted = 1 << 0, + /// this message originated from a message in another channel (via Channel Following) + m_is_crosspost = 1 << 1, + /// do not include any embeds when serializing this message + m_suppress_embeds = 1 << 2, + /// the source message for this crosspost has been deleted (via Channel Following) + m_source_message_deleted = 1 << 3, + /// this message came from the urgent message system + m_urgent = 1 << 4, + /// this message has an associated thread, with the same id as the message + m_has_thread = 1 << 5, + /// this message is only visible to the user who invoked the Interaction + m_ephemeral = 1 << 6, + /// this message is an Interaction Response and the bot is "thinking" + m_loading = 1 << 7, + /// this message failed to mention some roles and add their members to the thread + m_thread_mention_failed = 1 << 8, +}; + +/** + * @brief Represents possible values for the dpp::embed type field. + * These are loosely defined by the API docs and do not influence how the client renders embeds. + * The only type a bot can send is dpp::embed_type::emt_rich. + */ +namespace embed_type { + /** + * @brief Rich text + */ + const std::string emt_rich = "rich"; + /** + * @brief Image + */ + const std::string emt_image = "image"; + /** + * @brief Video link + */ + const std::string emt_video = "video"; + /** + * @brief Animated gif + */ + const std::string emt_gifv = "gifv"; + /** + * @brief Article + */ + const std::string emt_article = "article"; + /** + * @brief Link URL + */ + const std::string emt_link = "link"; + /** + * @brief Auto moderation filter + */ + const std::string emt_automod = "auto_moderation_message"; +}; + +/** + * @brief Message types for dpp::message::type + */ +enum message_type { + /// Default + mt_default = 0, + /// Add recipient + mt_recipient_add = 1, + /// Remove recipient + mt_recipient_remove = 2, + /// Call + mt_call = 3, + /// Channel name change + mt_channel_name_change = 4, + /// Channel icon change + mt_channel_icon_change = 5, + /// Message pinned + mt_channel_pinned_message = 6, + /// Member joined + mt_guild_member_join = 7, + /// Boost + mt_user_premium_guild_subscription = 8, + /// Boost level 1 + mt_user_premium_guild_subscription_tier_1 = 9, + /// Boost level 2 + mt_user_premium_guild_subscription_tier_2 = 10, + /// Boost level 3 + mt_user_premium_guild_subscription_tier_3 = 11, + /// Follow channel + mt_channel_follow_add = 12, + /// Disqualified from discovery + mt_guild_discovery_disqualified = 14, + /// Re-qualified for discovery + mt_guild_discovery_requalified = 15, + /// Discovery grace period warning 1 + mt_guild_discovery_grace_period_initial_warning = 16, + /// Discovery grace period warning 2 + mt_guild_discovery_grace_period_final_warning = 17, + /// Thread Created + mt_thread_created = 18, + /// Reply + mt_reply = 19, + /// Application command + mt_application_command = 20, + /// Thread starter message + mt_thread_starter_message = 21, + /// Invite reminder + mt_guild_invite_reminder = 22, + /// Context Menu Command + mt_context_menu_command = 23, + /// Auto moderation action + mt_auto_moderation_action = 24, +}; + +/** + * @brief Represents the caching policy of a cache in the library. + */ +enum cache_policy_setting_t { + /** + * @brief request aggressively on seeing new guilds, and also store missing data from messages. + * This is the default behaviour and the least memory-efficient option. Memory usage will increase + * over time, initially quite rapidly, and then linearly over time. It is the least cpu-intensive + * setting. + */ + cp_aggressive = 0, + /** + * @brief only cache when there is relevant activity, e.g. a message to the bot. + * This is a good middle-ground, memory usage will increase linearly over time. + */ + cp_lazy = 1, + /** + * @brief Don't cache anything. Fill details when we see them. + * This is the most memory-efficient option but consumes more CPU time + */ + cp_none = 2 +}; + +/** + * @brief Represents the caching policy of the cluster. + * + * Channels and guilds are always cached as these caches are used + * internally by the library. The memory usage of these is minimal. + * + * All default to 'aggressive' which means to actively attempt to cache, + * going out of the way to fill the caches completely. On large bots this + * can take a LOT of RAM. + */ +struct DPP_EXPORT cache_policy_t { + /** + * @brief Caching policy for users and guild members + */ + cache_policy_setting_t user_policy = cp_aggressive; + + /** + * @brief Caching policy for emojis + */ + cache_policy_setting_t emoji_policy = cp_aggressive; + + /** + * @brief Caching policy for roles + */ + cache_policy_setting_t role_policy = cp_aggressive; +}; + +/** + * @brief Represents messages sent and received on Discord + */ +struct DPP_EXPORT message : public managed { + /** id of the channel the message was sent in */ + snowflake channel_id; + /** Optional: id of the guild the message was sent in */ + snowflake guild_id; + /** the author of this message (not guaranteed to be a valid user) */ + user author; + /** Optional: member properties for this message's author */ + guild_member member; + /** contents of the message */ + std::string content; + /** message components */ + std::vector components; + /** when this message was sent */ + time_t sent; + /** when this message was edited (may be 0 if never edited) */ + time_t edited; + /** users specifically mentioned in the message */ + std::vector> mentions; + /** roles specifically mentioned in this message (only IDs currently)*/ + std::vector mention_roles; + /** Channels mentioned in the message. (Discord: not all types supported) + * Discord: Only textual channels that are visible to everyone in a lurkable guild will ever be included. Only crossposted messages (via Channel Following) currently include mention_channels at all. (includes ID, Guild ID, Type, Name)*/ + std::vector mention_channels; + /** any attached files */ + std::vector attachments; + /** zero or more dpp::embed objects */ + std::vector embeds; + /** Optional: reactions to the message */ + std::vector reactions; + /** Optional: used for validating a message was sent */ + std::string nonce; + /** Optional: if the message is generated by a webhook, its id will be here otherwise the field will be 0 */ + snowflake webhook_id; + /** Stickers */ + std::vector stickers; + + /** Name of file to upload (for use server-side in discord's url) */ + std::vector filename; + + /** File content to upload (raw binary) */ + std::vector filecontent; + + /** + * @brief Reference to another message, e.g. a reply + */ + struct message_ref { + /// id of the originating message + snowflake message_id; + /// id of the originating message's channel + snowflake channel_id; + /// id of the originating message's guild + snowflake guild_id; + /// when sending, whether to error if the referenced message doesn't exist instead of sending as a normal (non-reply) message, default true + bool fail_if_not_exists; + } message_reference; + + /** + * @brief Reference to an interaction + */ + struct message_interaction_struct{ + /// id of the interaction + snowflake id; + /// type of interaction + uint8_t type; + /// name of the application command + std::string name; + /// the user who invoked the interaction + user usr; + } interaction; + + /** + * @brief Allowed mentions details + */ + struct allowed_ref { + /** + * @brief Set to true to parse user mentions in the text. Default is false + */ + bool parse_users; + /** + * @brief Set to true to at-everyone and at-here mentions in the text. Default is false + */ + bool parse_everyone; + /** + * @brief Set to true to parse role mentions in the text. Default is false + */ + bool parse_roles; + /** + * @brief Set to true to mention the user who sent the message this one is replying to. Default is false + */ + bool replied_user; + /** + * @brief List of users to allow pings for + */ + std::vector users; + /** + * @brief List of roles to allow pings for + */ + std::vector roles; + } allowed_mentions; + + /** + * @brief The cluster which created this message object + */ + class cluster* owner; + + /** Message type */ + message_type type; + + /** Flags. Made of bits in dpp::message_flags */ + uint16_t flags; + + /** whether this message is pinned */ + bool pinned; + /** whether this was a TTS message */ + bool tts; + /** whether this message mentions everyone */ + bool mention_everyone; + + /** + * @brief Construct a new message object + */ + message(); + + /** + * @brief Construct a new message object + * @param o Owning cluster, passed down to various things such as dpp::attachment. + * Owning cluster is optional (can be nullptr) and if nulled, will prevent some functions + * such as attachment::download from functioning (they will throw, if used) + */ + message(class cluster* o); + + /** + * @brief Destroy the message object + */ + virtual ~message(); + + /** + * @brief Construct a new message object with a channel and content + * + * @param channel_id The channel to send the message to + * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @param type The message type to create + */ + message(snowflake channel_id, const std::string &content, message_type type = mt_default); + + /** + * @brief Construct a new message object with a channel and content + * + * @param channel_id The channel to send the message to + * @param _embed An embed to send + */ + message(snowflake channel_id, const embed & _embed); + + /** + * @brief Construct a new message object with content + * + * @param content The content of the message. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @param type The message type to create + */ + message(const std::string &content, message_type type = mt_default); + + /** + * @brief Set the original message reference for replies/crossposts + * + * @param _message_id message id to reply to + * @param _guild_id guild id to reply to (optional) + * @param _channel_id channel id to reply to (optional) + * @param fail_if_not_exists true if the message send should fail if these values are invalid (optional) + * @return message& reference to self + */ + message& set_reference(snowflake _message_id, snowflake _guild_id = 0, snowflake _channel_id = 0, bool fail_if_not_exists = false); + + /** + * @brief Set the allowed mentions object for pings on the message + * + * @param _parse_users whether or not to parse users in the message content or embeds + * @param _parse_roles whether or not to parse roles in the message content or embeds + * @param _parse_everyone whether or not to parse everyone/here in the message content or embeds + * @param _replied_user if set to true and this is a reply, then ping the user we reply to + * @param users list of user ids to allow pings for + * @param roles list of role ids to allow pings for + * @return message& reference to self + */ + message& set_allowed_mentions(bool _parse_users, bool _parse_roles, bool _parse_everyone, bool _replied_user, const std::vector &users, const std::vector &roles); + + /** Fill this object from json. + * @param j JSON object to fill from + * @param cp Cache policy for user records, whether or not we cache users when a message is received + * @return A reference to self + */ + message& fill_from_json(nlohmann::json* j, cache_policy_t cp = {cp_aggressive, cp_aggressive, cp_aggressive}); + + /** Build JSON from this object. + * @param with_id True if the ID is to be included in the built JSON + * @param is_interaction_response Set to true if this message is intended to be included in an interaction response. + * This will exclude some fields that are not valid in interactions at this time. + * @return The JSON text of the message + */ + virtual std::string build_json(bool with_id = false, bool is_interaction_response = false) const; + + /** + * @brief Returns true if the message was crossposted to other servers + * + * @return true if crossposted + */ + bool is_crossposted() const; + + /** + * @brief Returns true if posted from other servers announcement channel via webhook + * + * @return true if posted from other server + */ + bool is_crosspost() const; + + /** + * @brief True if embeds have been removed + * + * @return true if embeds removed + */ + bool suppress_embeds() const; + + /** + * @brief True if source message was deleted + * + * @return true if source message deleted + */ + bool is_source_message_deleted() const; + + /** + * @brief True if urgent + * + * @return true if urgent + */ + bool is_urgent() const; + + /** + * @brief True if has thread attached + * + * @return true if has thread attached + */ + bool has_thread() const; + + /** + * @brief True if ephemeral (visible only to issuer of a slash command) + * + * @return true if ephemeral + */ + bool is_ephemeral() const; + + /** + * @brief True if loading + * + * @return true if loading + */ + bool is_loading() const; + + /** + * @brief Returns true if this message failed to mention some roles and add their members to the thread + * + * @return true if this message failed to mention some roles and add their members to the thread + */ + bool is_thread_mention_failed() const; + + /** + * @brief Add a component (button) to message + * + * @param c component to add + * @return message& reference to self + */ + message& add_component(const component& c); + + /** + * @brief Add an embed to message + * + * @param e embed to add + * @return message& reference to self + */ + message& add_embed(const embed& e); + + /** + * @brief Set the flags + * + * @param f flags to set from dpp::message_flags + * @return message& reference to self + */ + message& set_flags(uint16_t f); + + /** + * @brief Set the message type + * + * @param t type to set + * @return message& reference to self + */ + message& set_type(message_type t); + + /** + * @brief Set the filename of the last file in list + * + * @param fn filename + * @return message& reference to self + * @deprecated Use message::add_file instead + */ + message& set_filename(const std::string &fn); + + /** + * @brief Set the file content of the last file in list + * + * @param fc raw file content contained in std::string + * @return message& reference to self + * @deprecated Use message::add_file instead + */ + message& set_file_content(const std::string &fc); + + /** + * @brief Add a file to the message + * + * @param filename filename + * @param filecontent raw file content contained in std::string + * @return message& reference to self + */ + message& add_file(const std::string &filename, const std::string &filecontent); + + /** + * @brief Set the message content + * + * @param c message content. It will be truncated to the maximum length of 4000 UTF-8 characters. + * @return message& reference to self + */ + message& set_content(const std::string &c); + + /** + * @brief Set the channel id + * + * @param _channel_id channel id + * @return message& reference to self + */ + message& set_channel_id(snowflake _channel_id); + + /** + * @brief Set the channel id + * + * @param _guild_id channel id + * @return message& reference to self + */ + message& set_guild_id(snowflake _guild_id); + + /** + * @brief Returns true if the message is from a DM + * + * @return true if message is a DM + */ + bool is_dm() const; +}; + +/** A group of messages */ +typedef std::unordered_map message_map; + +/** A group of stickers */ +typedef std::unordered_map sticker_map; + +/** A group of sticker packs */ +typedef std::unordered_map sticker_pack_map; + +}; diff --git a/3rdParty/dpp/misc-enum.h b/3rdParty/dpp/misc-enum.h index 19ef2a1edf..0e488470bb 100644 --- a/3rdParty/dpp/misc-enum.h +++ b/3rdParty/dpp/misc-enum.h @@ -1,53 +1,53 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include - -namespace dpp { - - /** @brief Supported image types for profile pictures */ - enum image_type { - /// image/png - i_png, - /// image/jpeg - i_jpg, - /// image/gif - i_gif - }; - - /** @brief Log levels */ - enum loglevel { - /// Trace - ll_trace = 0, - /// Debug - ll_debug, - /// Information - ll_info, - /// Warning - ll_warning, - /// Error - ll_error, - /// Critical - ll_critical - }; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + + /** @brief Supported image types for profile pictures */ + enum image_type { + /// image/png + i_png, + /// image/jpeg + i_jpg, + /// image/gif + i_gif + }; + + /** @brief Log levels */ + enum loglevel { + /// Trace + ll_trace = 0, + /// Debug + ll_debug, + /// Information + ll_info, + /// Warning + ll_warning, + /// Error + ll_error, + /// Critical + ll_critical + }; + +}; diff --git a/3rdParty/dpp/nlohmann/json.hpp b/3rdParty/dpp/nlohmann/json.hpp index 9b6728a2bc..6f74deae67 100644 --- a/3rdParty/dpp/nlohmann/json.hpp +++ b/3rdParty/dpp/nlohmann/json.hpp @@ -1 +1 @@ -#include "3rdParty/nlohmann/json.hpp" +#include "3rdParty/nlohmann/json.hpp" diff --git a/3rdParty/dpp/nlohmann/json_fwd.hpp b/3rdParty/dpp/nlohmann/json_fwd.hpp index 9163963745..d34c8afd10 100644 --- a/3rdParty/dpp/nlohmann/json_fwd.hpp +++ b/3rdParty/dpp/nlohmann/json_fwd.hpp @@ -1 +1 @@ -#include "3rdParty/nlohmann/json_fwd.hpp" +#include "3rdParty/nlohmann/json_fwd.hpp" diff --git a/3rdParty/dpp/once.h b/3rdParty/dpp/once.h index f77339673f..0c1a8ce670 100644 --- a/3rdParty/dpp/once.h +++ b/3rdParty/dpp/once.h @@ -1,46 +1,46 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include - -namespace dpp { - - /** - * @brief Run some code within an if() statement only once. - * - * Use this template like this: - * - * ``` - * if (dpp::run_once()) { - * // Your code here - * } - * ``` - * - * @tparam T any unique 'tag' identifier name - * @return auto a true/false return to say if we should execute or not - */ - template auto run_once() { - static auto called = false; - return !std::exchange(called, true); - }; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include + +namespace dpp { + + /** + * @brief Run some code within an if() statement only once. + * + * Use this template like this: + * + * ``` + * if (dpp::run_once()) { + * // Your code here + * } + * ``` + * + * @tparam T any unique 'tag' identifier name + * @return auto a true/false return to say if we should execute or not + */ + template auto run_once() { + static auto called = false; + return !std::exchange(called, true); + }; + +}; diff --git a/3rdParty/dpp/permissions.h b/3rdParty/dpp/permissions.h index 2f8b1fe310..caf248fc76 100644 --- a/3rdParty/dpp/permissions.h +++ b/3rdParty/dpp/permissions.h @@ -1,204 +1,204 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the various discord permissions - */ -enum permissions : uint64_t { - p_create_instant_invite = 0x00000000001, //!< allows creation of instant invites - p_kick_members = 0x00000000002, //!< allows kicking members - p_ban_members = 0x00000000004, //!< allows banning members - p_administrator = 0x00000000008, //!< allows all permissions and bypasses channel permission overwrites - p_manage_channels = 0x00000000010, //!< allows management and editing of channels - p_manage_guild = 0x00000000020, //!< allows management and editing of the guild - p_add_reactions = 0x00000000040, //!< allows for the addition of reactions to messages - p_view_audit_log = 0x00000000080, //!< allows for viewing of audit logs - p_priority_speaker = 0x00000000100, //!< allows for using priority speaker in a voice channel - p_stream = 0x00000000200, //!< allows the user to go live - p_view_channel = 0x00000000400, //!< allows guild members to view a channel, which includes reading messages in text channels and joining voice channels - p_send_messages = 0x00000000800, //!< allows for sending messages in a channel - p_send_tts_messages = 0x00000001000, //!< allows for sending of /tts messages - p_manage_messages = 0x00000002000, //!< allows for deletion of other users messages - p_embed_links = 0x00000004000, //!< links sent by users with this permission will be auto-embedded - p_attach_files = 0x00000008000, //!< allows for uploading images and files - p_read_message_history = 0x00000010000, //!< allows for reading of message history - p_mention_everyone = 0x00000020000, //!< allows for using the everyone and the here tag to notify users in a channel - p_use_external_emojis = 0x00000040000, //!< allows the usage of custom emojis from other servers - p_view_guild_insights = 0x00000080000, //!< allows for viewing guild insights - p_connect = 0x00000100000, //!< allows for joining of a voice channel - p_speak = 0x00000200000, //!< allows for speaking in a voice channel - p_mute_members = 0x00000400000, //!< allows for muting members in a voice channel - p_deafen_members = 0x00000800000, //!< allows for deafening of members in a voice channel - p_move_members = 0x00001000000, //!< allows for moving of members between voice channels - p_use_vad = 0x00002000000, //!< allows for using voice-activity-detection in a voice channel - p_change_nickname = 0x00004000000, //!< allows for modification of own nickname - p_manage_nicknames = 0x00008000000, //!< allows for modification of other users nicknames - p_manage_roles = 0x00010000000, //!< allows management and editing of roles - p_manage_webhooks = 0x00020000000, //!< allows management and editing of webhooks - p_manage_emojis_and_stickers = 0x00040000000, //!< allows management and editing of emojis and stickers - p_use_application_commands = 0x00080000000, //!< allows members to use application commands, including slash commands and context menus - p_request_to_speak = 0x00100000000, //!< allows for requesting to speak in stage channels. (Discord: This permission is under active development and may be changed or removed.) - p_manage_events = 0x00200000000, //!< allows for management (creation, updating, deleting, starting) of scheduled events - p_manage_threads = 0x00400000000, //!< allows for deleting and archiving threads, and viewing all private threads - p_create_public_threads = 0x00800000000, //!< allows for creating public and announcement threads - p_create_private_threads = 0x01000000000, //!< allows for creating private threads - p_use_external_stickers = 0x02000000000, //!< allows the usage of custom stickers from other servers - p_send_messages_in_threads = 0x04000000000, //!< allows for sending messages in threads - p_use_embedded_activities = 0x08000000000, //!< allows for using activities (applications with the EMBEDDED flag) in a voice channel - p_moderate_members = 0x10000000000, //!< allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels -}; - -/** - * @brief Represents the various discord permissions - * @deprecated Use dpp::permissions instead. - */ -using role_permissions = permissions; - -/** - * @brief Represents a permission bitmask (refer to enum dpp::permissions) which are hold in an uint64_t - */ -class DPP_EXPORT permission { -protected: - /** - * @brief The permission bitmask value - */ - uint64_t value; - -public: - /** - * @brief Construct a permission object - * @param value A permission bitmask - */ - permission(const uint64_t& value); - - /** - * @brief Construct a permission object - */ - permission(); - - /** - * @brief For acting like an integer - * @return The permission bitmask value - */ - operator uint64_t() const; - - /** - * @brief For acting like an integer - * @return A reference to the permission bitmask value - */ - operator uint64_t &(); - - /** - * @brief For building json - * @return The permission bitmask value as a string - */ - operator nlohmann::json() const; - - /** - * @brief Check for permission flags set. It uses the Bitwise AND operator - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to check for - * - * **Example:** - * - * ```cpp - * bool is_mod = permission.has(dpp::p_kick_members, dpp::p_ban_members); - * // Returns true if the permission bitmask contains p_kick_members and p_ban_members - * ``` - * - * @return bool True if it has all the given permissions - */ - template - bool has(T... values) const { - return (value & (0 | ... | values)) == (0 | ... | values); - } - - /** - * @brief Add a permission with the Bitwise OR operation - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to add - * - * **Example:** - * - * ```cpp - * permission.add(dpp::p_view_channel, dpp::p_send_messages); - * // Adds p_view_channel and p_send_messages to the permission bitmask - * ``` - * - * @return permission& reference to self for chaining - */ - template - typename std::enable_if<(std::is_convertible::value && ...), permission&>::type - add(T... values) { - value |= (0 | ... | values); - return *this; - } - - /** - * @brief Assign a permission. This will reset the bitmask to the new value. - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to set - * - * **Example:** - * - * ```cpp - * permission.set(dpp::p_view_channel, dpp::p_send_messages); - * ``` - * - * @return permission& reference to self for chaining - */ - template - typename std::enable_if<(std::is_convertible::value && ...), permission&>::type - set(T... values) { - value = (0 | ... | values); - return *this; - } - - /** - * @brief Remove a permission with the Bitwise NOT operation - * @tparam T one or more uint64_t permission bits - * @param values The permissions (from dpp::permissions) to remove - * - * **Example:** - * - * ```cpp - * permission.remove(dpp::p_view_channel, dpp::p_send_messages); - * // Removes p_view_channel and p_send_messages permission - * ``` - * - * @return permission& reference to self for chaining - */ - template - typename std::enable_if<(std::is_convertible::value && ...), permission&>::type - remove(T... values) { - value &= ~(0 | ... | values); - return *this; - } -}; - -} +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the various discord permissions + */ +enum permissions : uint64_t { + p_create_instant_invite = 0x00000000001, //!< allows creation of instant invites + p_kick_members = 0x00000000002, //!< allows kicking members + p_ban_members = 0x00000000004, //!< allows banning members + p_administrator = 0x00000000008, //!< allows all permissions and bypasses channel permission overwrites + p_manage_channels = 0x00000000010, //!< allows management and editing of channels + p_manage_guild = 0x00000000020, //!< allows management and editing of the guild + p_add_reactions = 0x00000000040, //!< allows for the addition of reactions to messages + p_view_audit_log = 0x00000000080, //!< allows for viewing of audit logs + p_priority_speaker = 0x00000000100, //!< allows for using priority speaker in a voice channel + p_stream = 0x00000000200, //!< allows the user to go live + p_view_channel = 0x00000000400, //!< allows guild members to view a channel, which includes reading messages in text channels and joining voice channels + p_send_messages = 0x00000000800, //!< allows for sending messages in a channel + p_send_tts_messages = 0x00000001000, //!< allows for sending of /tts messages + p_manage_messages = 0x00000002000, //!< allows for deletion of other users messages + p_embed_links = 0x00000004000, //!< links sent by users with this permission will be auto-embedded + p_attach_files = 0x00000008000, //!< allows for uploading images and files + p_read_message_history = 0x00000010000, //!< allows for reading of message history + p_mention_everyone = 0x00000020000, //!< allows for using the everyone and the here tag to notify users in a channel + p_use_external_emojis = 0x00000040000, //!< allows the usage of custom emojis from other servers + p_view_guild_insights = 0x00000080000, //!< allows for viewing guild insights + p_connect = 0x00000100000, //!< allows for joining of a voice channel + p_speak = 0x00000200000, //!< allows for speaking in a voice channel + p_mute_members = 0x00000400000, //!< allows for muting members in a voice channel + p_deafen_members = 0x00000800000, //!< allows for deafening of members in a voice channel + p_move_members = 0x00001000000, //!< allows for moving of members between voice channels + p_use_vad = 0x00002000000, //!< allows for using voice-activity-detection in a voice channel + p_change_nickname = 0x00004000000, //!< allows for modification of own nickname + p_manage_nicknames = 0x00008000000, //!< allows for modification of other users nicknames + p_manage_roles = 0x00010000000, //!< allows management and editing of roles + p_manage_webhooks = 0x00020000000, //!< allows management and editing of webhooks + p_manage_emojis_and_stickers = 0x00040000000, //!< allows management and editing of emojis and stickers + p_use_application_commands = 0x00080000000, //!< allows members to use application commands, including slash commands and context menus + p_request_to_speak = 0x00100000000, //!< allows for requesting to speak in stage channels. (Discord: This permission is under active development and may be changed or removed.) + p_manage_events = 0x00200000000, //!< allows for management (creation, updating, deleting, starting) of scheduled events + p_manage_threads = 0x00400000000, //!< allows for deleting and archiving threads, and viewing all private threads + p_create_public_threads = 0x00800000000, //!< allows for creating public and announcement threads + p_create_private_threads = 0x01000000000, //!< allows for creating private threads + p_use_external_stickers = 0x02000000000, //!< allows the usage of custom stickers from other servers + p_send_messages_in_threads = 0x04000000000, //!< allows for sending messages in threads + p_use_embedded_activities = 0x08000000000, //!< allows for using activities (applications with the EMBEDDED flag) in a voice channel + p_moderate_members = 0x10000000000, //!< allows for timing out users to prevent them from sending or reacting to messages in chat and threads, and from speaking in voice and stage channels +}; + +/** + * @brief Represents the various discord permissions + * @deprecated Use dpp::permissions instead. + */ +using role_permissions = permissions; + +/** + * @brief Represents a permission bitmask (refer to enum dpp::permissions) which are hold in an uint64_t + */ +class DPP_EXPORT permission { +protected: + /** + * @brief The permission bitmask value + */ + uint64_t value; + +public: + /** + * @brief Construct a permission object + * @param value A permission bitmask + */ + permission(const uint64_t& value); + + /** + * @brief Construct a permission object + */ + permission(); + + /** + * @brief For acting like an integer + * @return The permission bitmask value + */ + operator uint64_t() const; + + /** + * @brief For acting like an integer + * @return A reference to the permission bitmask value + */ + operator uint64_t &(); + + /** + * @brief For building json + * @return The permission bitmask value as a string + */ + operator nlohmann::json() const; + + /** + * @brief Check for permission flags set. It uses the Bitwise AND operator + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to check for + * + * **Example:** + * + * ```cpp + * bool is_mod = permission.has(dpp::p_kick_members, dpp::p_ban_members); + * // Returns true if the permission bitmask contains p_kick_members and p_ban_members + * ``` + * + * @return bool True if it has all the given permissions + */ + template + bool has(T... values) const { + return (value & (0 | ... | values)) == (0 | ... | values); + } + + /** + * @brief Add a permission with the Bitwise OR operation + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to add + * + * **Example:** + * + * ```cpp + * permission.add(dpp::p_view_channel, dpp::p_send_messages); + * // Adds p_view_channel and p_send_messages to the permission bitmask + * ``` + * + * @return permission& reference to self for chaining + */ + template + typename std::enable_if<(std::is_convertible::value && ...), permission&>::type + add(T... values) { + value |= (0 | ... | values); + return *this; + } + + /** + * @brief Assign a permission. This will reset the bitmask to the new value. + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to set + * + * **Example:** + * + * ```cpp + * permission.set(dpp::p_view_channel, dpp::p_send_messages); + * ``` + * + * @return permission& reference to self for chaining + */ + template + typename std::enable_if<(std::is_convertible::value && ...), permission&>::type + set(T... values) { + value = (0 | ... | values); + return *this; + } + + /** + * @brief Remove a permission with the Bitwise NOT operation + * @tparam T one or more uint64_t permission bits + * @param values The permissions (from dpp::permissions) to remove + * + * **Example:** + * + * ```cpp + * permission.remove(dpp::p_view_channel, dpp::p_send_messages); + * // Removes p_view_channel and p_send_messages permission + * ``` + * + * @return permission& reference to self for chaining + */ + template + typename std::enable_if<(std::is_convertible::value && ...), permission&>::type + remove(T... values) { + value &= ~(0 | ... | values); + return *this; + } +}; + +} diff --git a/3rdParty/dpp/presence.h b/3rdParty/dpp/presence.h index 23c389420f..e018f92ecb 100644 --- a/3rdParty/dpp/presence.h +++ b/3rdParty/dpp/presence.h @@ -1,384 +1,384 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Presence flags bitmask - */ -enum presence_flags { - /// Desktop: Online - p_desktop_online = 0b00000001, - /// Desktop: DND - p_desktop_dnd = 0b00000010, - /// Desktop: Idle - p_desktop_idle = 0b00000011, - /// Web: Online - p_web_online = 0b00000100, - /// Web: DND - p_web_dnd = 0b00001000, - /// Web: Idle - p_web_idle = 0b00001100, - /// Mobile: Online - p_mobile_online = 0b00010000, - /// Mobile: DND - p_mobile_dnd = 0b00100000, - /// Mobile: Idle - p_mobile_idle = 0b00110000, - /// General: Online - p_status_online = 0b01000000, - /// General: DND - p_status_dnd = 0b10000000, - /// General: Idle - p_status_idle = 0b11000000 -}; - -/** - * @brief Online presence status values - */ -enum presence_status : uint8_t { - /// Offline - ps_offline = 0, - /// Online - ps_online = 1, - /// DND - ps_dnd = 2, - /// Idle - ps_idle = 3 -}; - -/** - * @brief Bit shift for desktop status - */ -#define PF_SHIFT_DESKTOP 0 -/** Bit shift for web status */ -#define PF_SHIFT_WEB 2 -/** Bit shift for mobile status */ -#define PF_SHIFT_MOBILE 4 -/** Bit shift for main status */ -#define PF_SHIFT_MAIN 6 -/** Bit mask for status */ -#define PF_STATUS_MASK 0b00000011 -/** Bit mask for clearing desktop status */ -#define PF_CLEAR_DESKTOP 0b11111100 -/** Bit mask for clearing web status */ -#define PF_CLEAR_WEB 0b11110011 -/** Bit mask for clearing mobile status */ -#define PF_CLEAR_MOBILE 0b11001111 -/** Bit mask for clearing main status */ -#define PF_CLEAR_STATUS 0b00111111 - -/** - * @brief Game types - */ -enum activity_type : uint8_t { - /// "Playing ..." - at_game = 0, - /// "Streaming ..." - at_streaming = 1, - /// "Listening to..." - at_listening = 2, - /// "Watching..." - at_watching = 3, - /// "Emoji..." - at_custom = 4, - /// "Competing in..." - at_competing = 5 -}; - -/** - * @brief Activity types for rich presence - */ -enum activity_flags { - /// In an instance - af_instance = 0b000000001, - /// Joining - af_join = 0b000000010, - /// Spectating - af_spectate = 0b000000100, - /// Sending join request - af_join_request = 0b000001000, - /// Synchronising - af_sync = 0b000010000, - /// Playing - af_play = 0b000100000, - /// Party privacy friends - af_party_privacy_friends = 0b001000000, - /// Party privacy voice channel - af_party_privacy_voice_channel = 0b010000000, - /// Embedded - af_embedded = 0b100000000 -}; - -/** - * @brief An activity button is a custom button shown in the rich presence. Can be to join a game or whatever - */ -struct DPP_EXPORT activity_button { -public: - /** The text shown on the button (1-32 characters) - */ - std::string label; - /** The url opened when clicking the button (1-512 characters). It's may be empty - * - * @note Bots cannot access the activity button URLs. - */ - std::string url; - - /** Constructor */ - activity_button() = default; -}; - -/** - * @brief An activity asset are the images and the hover text displayed in the rich presence - */ -struct DPP_EXPORT activity_assets { -public: - /** The large asset image which usually contain snowflake ID or prefixed image ID - */ - std::string large_image; - /** Text displayed when hovering over the large image of the activity - */ - std::string large_text; - /** The small asset image which usually contain snowflake ID or prefixed image ID - */ - std::string small_image; - /** Text displayed when hovering over the small image of the activity - */ - std::string small_text; - - /** Constructor */ - activity_assets() = default; -}; - -/** - * @brief Secrets for Rich Presence joining and spectating - */ -struct DPP_EXPORT activity_secrets { -public: - /** The secret for joining a party - */ - std::string join; - /** The secret for spectating a game - */ - std::string spectate; - /** The secret for a specific instanced match - */ - std::string match; - - /** Constructor */ - activity_secrets() = default; -}; - -/** - * @brief Information for the current party of the player - */ -struct DPP_EXPORT activity_party { -public: - /** The ID of the party - */ - snowflake id; - /** The party's current size. Used to show the party's current size - */ - int32_t current_size; - /** The party's maximum size. Used to show the party's maximum size - */ - int32_t maximum_size; - - /** Constructor */ - activity_party(); -}; - -/** - * @brief An activity is a representation of what a user is doing. It might be a game, or a website, or a movie. Whatever. - */ -class DPP_EXPORT activity { -public: - /** Name of activity - * e.g. "Fortnite" - */ - std::string name; - /** State of activity or the custom user status. - * e.g. "Waiting in lobby" - */ - std::string state; - /** What the player is currently doing - */ - std::string details; - /** Images for the presence and their hover texts - */ - activity_assets assets; - /** URL. - * Only applicable for certain sites such a YouTube - * Alias: details - */ - std::string url; - /** The custom buttons shown in the Rich Presence (max 2) - */ - std::vector buttons; - /** The emoji used for the custom status - */ - dpp::emoji emoji; - /** Information of the current party if there is one - */ - activity_party party; - /** Secrets for rich presence joining and spectating - */ - activity_secrets secrets; - /** Activity type - */ - activity_type type; - /** Time activity was created - */ - time_t created_at; - /** Start time. e.g. when game was started - */ - time_t start; - /** End time, e.g. for songs on spotify - */ - time_t end; - /** Creating application (e.g. a linked account on the user's client) - */ - snowflake application_id; - /** Flags bitmask from dpp::activity_flags - */ - uint8_t flags; - /** Whether or not the activity is an instanced game session - */ - bool is_instance; - - /** - * @brief Get the assets large image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. - * - * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. - * @return image url or empty string - */ - std::string get_large_asset_url(uint16_t size = 0) const; - - /** - * @brief Get the assets small image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. - * - * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. - * @return image url or empty string - */ - std::string get_small_asset_url(uint16_t size = 0) const; - - activity(); - - /** - * @brief Construct a new activity - * - * @param typ activity type - * @param nam Name of the activity - * @param stat State of the activity - * @param url_ url of the activity, only works for certain sites, such as YouTube - */ - activity(const activity_type typ, const std::string& nam, const std::string& stat, const std::string& url_); -}; - -/** - * @brief Represents user presence, e.g. what game they are playing and if they are online - */ -class DPP_EXPORT presence : public json_interface { -public: - /** The user the presence applies to */ - snowflake user_id; - - /** Guild ID. Apparently, Discord supports this internally but the client doesn't... */ - snowflake guild_id; - - /** Flags bitmask containing dpp::presence_flags */ - uint8_t flags; - - /** List of activities */ - std::vector activities; - - /** Constructor */ - presence(); - - /** - * @brief Construct a new presence object with some parameters for sending to a websocket - * - * @param status Status of the activity - * @param type Type of activity - * @param activity_description Description of the activity - */ - presence(presence_status status, activity_type type, const std::string& activity_description); - - /** - * @brief Construct a new presence object with some parameters for sending to a websocket. - * - * @param status Status of the activity - * @param a Activity itself - */ - presence(presence_status status, const activity& a); - - /** Destructor */ - ~presence(); - - /** Fill this object from json. - * @param j JSON object to fill from - * @return A reference to self - */ - presence& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * - * Note: This excludes any part of the presence object that are not valid for websockets and bots, - * and includes websocket opcode 3. You will not get what you expect if you call this on a user's - * presence received from on_presence_update or on_guild_create! - * - * @param with_id Add ID to output - * @return The JSON text of the presence - */ - virtual std::string build_json(bool with_id = false) const; - - /** The users status on desktop - * @return The user's status on desktop - */ - presence_status desktop_status() const; - - /** The user's status on web - * @return The user's status on web - */ - presence_status web_status() const; - - /** The user's status on mobile - * @return The user's status on mobile - */ - presence_status mobile_status() const; - - /** The user's status as shown to other users - * @return The user's status as shown to other users - */ - presence_status status() const; -}; - -/** A container of presences */ -typedef std::unordered_map presence_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Presence flags bitmask + */ +enum presence_flags { + /// Desktop: Online + p_desktop_online = 0b00000001, + /// Desktop: DND + p_desktop_dnd = 0b00000010, + /// Desktop: Idle + p_desktop_idle = 0b00000011, + /// Web: Online + p_web_online = 0b00000100, + /// Web: DND + p_web_dnd = 0b00001000, + /// Web: Idle + p_web_idle = 0b00001100, + /// Mobile: Online + p_mobile_online = 0b00010000, + /// Mobile: DND + p_mobile_dnd = 0b00100000, + /// Mobile: Idle + p_mobile_idle = 0b00110000, + /// General: Online + p_status_online = 0b01000000, + /// General: DND + p_status_dnd = 0b10000000, + /// General: Idle + p_status_idle = 0b11000000 +}; + +/** + * @brief Online presence status values + */ +enum presence_status : uint8_t { + /// Offline + ps_offline = 0, + /// Online + ps_online = 1, + /// DND + ps_dnd = 2, + /// Idle + ps_idle = 3 +}; + +/** + * @brief Bit shift for desktop status + */ +#define PF_SHIFT_DESKTOP 0 +/** Bit shift for web status */ +#define PF_SHIFT_WEB 2 +/** Bit shift for mobile status */ +#define PF_SHIFT_MOBILE 4 +/** Bit shift for main status */ +#define PF_SHIFT_MAIN 6 +/** Bit mask for status */ +#define PF_STATUS_MASK 0b00000011 +/** Bit mask for clearing desktop status */ +#define PF_CLEAR_DESKTOP 0b11111100 +/** Bit mask for clearing web status */ +#define PF_CLEAR_WEB 0b11110011 +/** Bit mask for clearing mobile status */ +#define PF_CLEAR_MOBILE 0b11001111 +/** Bit mask for clearing main status */ +#define PF_CLEAR_STATUS 0b00111111 + +/** + * @brief Game types + */ +enum activity_type : uint8_t { + /// "Playing ..." + at_game = 0, + /// "Streaming ..." + at_streaming = 1, + /// "Listening to..." + at_listening = 2, + /// "Watching..." + at_watching = 3, + /// "Emoji..." + at_custom = 4, + /// "Competing in..." + at_competing = 5 +}; + +/** + * @brief Activity types for rich presence + */ +enum activity_flags { + /// In an instance + af_instance = 0b000000001, + /// Joining + af_join = 0b000000010, + /// Spectating + af_spectate = 0b000000100, + /// Sending join request + af_join_request = 0b000001000, + /// Synchronising + af_sync = 0b000010000, + /// Playing + af_play = 0b000100000, + /// Party privacy friends + af_party_privacy_friends = 0b001000000, + /// Party privacy voice channel + af_party_privacy_voice_channel = 0b010000000, + /// Embedded + af_embedded = 0b100000000 +}; + +/** + * @brief An activity button is a custom button shown in the rich presence. Can be to join a game or whatever + */ +struct DPP_EXPORT activity_button { +public: + /** The text shown on the button (1-32 characters) + */ + std::string label; + /** The url opened when clicking the button (1-512 characters). It's may be empty + * + * @note Bots cannot access the activity button URLs. + */ + std::string url; + + /** Constructor */ + activity_button() = default; +}; + +/** + * @brief An activity asset are the images and the hover text displayed in the rich presence + */ +struct DPP_EXPORT activity_assets { +public: + /** The large asset image which usually contain snowflake ID or prefixed image ID + */ + std::string large_image; + /** Text displayed when hovering over the large image of the activity + */ + std::string large_text; + /** The small asset image which usually contain snowflake ID or prefixed image ID + */ + std::string small_image; + /** Text displayed when hovering over the small image of the activity + */ + std::string small_text; + + /** Constructor */ + activity_assets() = default; +}; + +/** + * @brief Secrets for Rich Presence joining and spectating + */ +struct DPP_EXPORT activity_secrets { +public: + /** The secret for joining a party + */ + std::string join; + /** The secret for spectating a game + */ + std::string spectate; + /** The secret for a specific instanced match + */ + std::string match; + + /** Constructor */ + activity_secrets() = default; +}; + +/** + * @brief Information for the current party of the player + */ +struct DPP_EXPORT activity_party { +public: + /** The ID of the party + */ + snowflake id; + /** The party's current size. Used to show the party's current size + */ + int32_t current_size; + /** The party's maximum size. Used to show the party's maximum size + */ + int32_t maximum_size; + + /** Constructor */ + activity_party(); +}; + +/** + * @brief An activity is a representation of what a user is doing. It might be a game, or a website, or a movie. Whatever. + */ +class DPP_EXPORT activity { +public: + /** Name of activity + * e.g. "Fortnite" + */ + std::string name; + /** State of activity or the custom user status. + * e.g. "Waiting in lobby" + */ + std::string state; + /** What the player is currently doing + */ + std::string details; + /** Images for the presence and their hover texts + */ + activity_assets assets; + /** URL. + * Only applicable for certain sites such a YouTube + * Alias: details + */ + std::string url; + /** The custom buttons shown in the Rich Presence (max 2) + */ + std::vector buttons; + /** The emoji used for the custom status + */ + dpp::emoji emoji; + /** Information of the current party if there is one + */ + activity_party party; + /** Secrets for rich presence joining and spectating + */ + activity_secrets secrets; + /** Activity type + */ + activity_type type; + /** Time activity was created + */ + time_t created_at; + /** Start time. e.g. when game was started + */ + time_t start; + /** End time, e.g. for songs on spotify + */ + time_t end; + /** Creating application (e.g. a linked account on the user's client) + */ + snowflake application_id; + /** Flags bitmask from dpp::activity_flags + */ + uint8_t flags; + /** Whether or not the activity is an instanced game session + */ + bool is_instance; + + /** + * @brief Get the assets large image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. + * + * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. + * @return image url or empty string + */ + std::string get_large_asset_url(uint16_t size = 0) const; + + /** + * @brief Get the assets small image url if they have one, otherwise returns an empty string. In case of prefixed image IDs (mp:{image_id}) it returns an empty string. + * + * @param size The size of the image in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized image is returned. + * @return image url or empty string + */ + std::string get_small_asset_url(uint16_t size = 0) const; + + activity(); + + /** + * @brief Construct a new activity + * + * @param typ activity type + * @param nam Name of the activity + * @param stat State of the activity + * @param url_ url of the activity, only works for certain sites, such as YouTube + */ + activity(const activity_type typ, const std::string& nam, const std::string& stat, const std::string& url_); +}; + +/** + * @brief Represents user presence, e.g. what game they are playing and if they are online + */ +class DPP_EXPORT presence : public json_interface { +public: + /** The user the presence applies to */ + snowflake user_id; + + /** Guild ID. Apparently, Discord supports this internally but the client doesn't... */ + snowflake guild_id; + + /** Flags bitmask containing dpp::presence_flags */ + uint8_t flags; + + /** List of activities */ + std::vector activities; + + /** Constructor */ + presence(); + + /** + * @brief Construct a new presence object with some parameters for sending to a websocket + * + * @param status Status of the activity + * @param type Type of activity + * @param activity_description Description of the activity + */ + presence(presence_status status, activity_type type, const std::string& activity_description); + + /** + * @brief Construct a new presence object with some parameters for sending to a websocket. + * + * @param status Status of the activity + * @param a Activity itself + */ + presence(presence_status status, const activity& a); + + /** Destructor */ + ~presence(); + + /** Fill this object from json. + * @param j JSON object to fill from + * @return A reference to self + */ + presence& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * + * Note: This excludes any part of the presence object that are not valid for websockets and bots, + * and includes websocket opcode 3. You will not get what you expect if you call this on a user's + * presence received from on_presence_update or on_guild_create! + * + * @param with_id Add ID to output + * @return The JSON text of the presence + */ + virtual std::string build_json(bool with_id = false) const; + + /** The users status on desktop + * @return The user's status on desktop + */ + presence_status desktop_status() const; + + /** The user's status on web + * @return The user's status on web + */ + presence_status web_status() const; + + /** The user's status on mobile + * @return The user's status on mobile + */ + presence_status mobile_status() const; + + /** The user's status as shown to other users + * @return The user's status as shown to other users + */ + presence_status status() const; +}; + +/** A container of presences */ +typedef std::unordered_map presence_map; + +}; diff --git a/3rdParty/dpp/prune.h b/3rdParty/dpp/prune.h index 23f335fc25..fe3d843908 100644 --- a/3rdParty/dpp/prune.h +++ b/3rdParty/dpp/prune.h @@ -1,63 +1,63 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Defines a request to count prunable users, or start a prune operation - */ -struct DPP_EXPORT prune : public json_interface { - /** - * Destroy this prune object - */ - virtual ~prune() = default; - - /** Number of days to include in the prune - */ - uint32_t days = 0; - /** Roles to include in the prune (empty to include everyone) - */ - std::vector include_roles; - /** True if the count of pruneable users should be returned - * (discord recommend not using this on big guilds) - */ - bool compute_prune_count; - - /** Fill this object from json. - * @param j JSON object to fill from - * @return A reference to self - */ - prune& fill_from_json(nlohmann::json* j); - - /** Build JSON from this object. - * @param with_prune_count True if the prune count boolean is to be set in the built JSON - * @return The JSON text of the prune object - */ - virtual std::string build_json(bool with_prune_count = false) const; - -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines a request to count prunable users, or start a prune operation + */ +struct DPP_EXPORT prune : public json_interface { + /** + * Destroy this prune object + */ + virtual ~prune() = default; + + /** Number of days to include in the prune + */ + uint32_t days = 0; + /** Roles to include in the prune (empty to include everyone) + */ + std::vector include_roles; + /** True if the count of pruneable users should be returned + * (discord recommend not using this on big guilds) + */ + bool compute_prune_count; + + /** Fill this object from json. + * @param j JSON object to fill from + * @return A reference to self + */ + prune& fill_from_json(nlohmann::json* j); + + /** Build JSON from this object. + * @param with_prune_count True if the prune count boolean is to be set in the built JSON + * @return The JSON text of the prune object + */ + virtual std::string build_json(bool with_prune_count = false) const; + +}; + +}; diff --git a/3rdParty/dpp/queues.h b/3rdParty/dpp/queues.h index ae5ee6e4c3..e3e5a650a4 100644 --- a/3rdParty/dpp/queues.h +++ b/3rdParty/dpp/queues.h @@ -1,457 +1,457 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Error values. Most of these are currently unused in https_client. - */ -enum http_error { - /// Request successful - h_success = 0, - /// Status unknown - h_unknown, - /// Connect failed - h_connection, - /// Invalid local ip address - h_bind_ip_address, - /// Read error - h_read, - /// Write error - h_write, - /// Too many 30x redirects - h_exceed_redirect_count, - /// Request cancelled - h_canceled, - /// SSL connection error - h_ssl_connection, - /// SSL cert loading error - h_ssl_loading_certs, - /// SSL server verification error - h_ssl_server_verification, - /// Unsupported multipart boundary characters - h_unsupported_multipart_boundary_chars, - /// Compression error - h_compression, -}; - -/** - * @brief The result of any HTTP request. Contains the headers, vital - * rate limit figures, and returned request body. - */ -struct DPP_EXPORT http_request_completion_t { - /** @brief HTTP headers of response */ - std::map headers; - /** @brief HTTP status, e.g. 200 = OK, 404 = Not found, 429 = Rate limited */ - uint16_t status = 0; - /** @brief Error status (e.g. if the request could not connect at all) */ - http_error error = h_success; - /** @brief Ratelimit bucket */ - std::string ratelimit_bucket; - /** @brief Ratelimit limit of requests */ - uint64_t ratelimit_limit = 0; - /** @brief Ratelimit remaining requests */ - uint64_t ratelimit_remaining = 0; - /** @brief Ratelimit reset after (seconds) */ - uint64_t ratelimit_reset_after = 0; - /** @brief Ratelimit retry after (seconds) */ - uint64_t ratelimit_retry_after = 0; - /** @brief True if this request has caused us to be globally rate limited */ - bool ratelimit_global = false; - /** @brief Reply body */ - std::string body; - /** @brief Ping latency */ - double latency; -}; - -/** - * @brief Results of HTTP requests are called back to these std::function types. - * @note Returned http_completion_events are called ASYNCHRONOUSLY in your - * code which means they execute in a separate thread. The completion events - * arrive in order. - */ -typedef std::function http_completion_event; - -/** - * @brief Various types of http method supported by the Discord API - */ -enum http_method { - /// GET - m_get, - /// POST - m_post, - /// PUT - m_put, - /// PATCH - m_patch, - /// DELETE - m_delete -}; - -/** - * @brief A HTTP request. - * - * You should instantiate one of these objects via its constructor, - * and pass a pointer to it into an instance of request_queue. Although you can - * directly call the run() method of the object and it will make a HTTP call, be - * aware that if you do this, it will be a **BLOCKING call** (not asynchronous) and - * will not respect rate limits, as both of these functions are managed by the - * request_queue class. - */ -class DPP_EXPORT http_request { - /** @brief Completion callback */ - http_completion_event complete_handler; - /** @brief True if request has been made */ - bool completed; - /** @brief True for requests that are not going to discord (rate limits code skipped) */ - bool non_discord; -public: - /** @brief Endpoint name e.g. /api/users */ - std::string endpoint; - /** @brief Major and minor parameters */ - std::string parameters; - /** @brief Postdata for POST and PUT */ - std::string postdata; - /** @brief HTTP method for request */ - http_method method; - /** @brief Audit log reason for Discord requests, if non-empty */ - std::string reason; - /** @brief Upload file name (server side) */ - std::vector file_name; - /** @brief Upload file contents (binary) */ - std::vector file_content; - /** @brief Request mime type */ - std::string mimetype; - /** @brief Request headers (non-discord requests only) */ - std::multimap req_headers; - /** @brief Waiting for rate limit to expire */ - bool waiting; - - /** - * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). - * @param _endpoint The API endpoint, e.g. /api/guilds - * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id - * @param completion completion event to call when done - * @param _postdata Data to send in POST and PUT requests - * @param method The HTTP method to use from dpp::http_method - * @param audit_reason Audit log reason to send, empty to send none - * @param filename The filename (server side) of any uploaded file - * @param filecontent The binary content of any uploaded file for the request - */ - http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::string &filename = "", const std::string &filecontent = ""); - - /** - * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). - * @param _endpoint The API endpoint, e.g. /api/guilds - * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id - * @param completion completion event to call when done - * @param _postdata Data to send in POST and PUT requests - * @param method The HTTP method to use from dpp::http_method - * @param audit_reason Audit log reason to send, empty to send none - * @param filename The filename (server side) of any uploaded file - * @param filecontent The binary content of any uploaded file for the request - */ - http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::vector &filename = {}, const std::vector &filecontent = {}); - - /** - * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). - * @param _url Raw HTTP url - * @param completion completion event to call when done - * @param method The HTTP method to use from dpp::http_method - * @param _postdata Data to send in POST and PUT requests - * @param _mimetype POST data mime type - * @param _headers HTTP headers to send - */ - http_request(const std::string &_url, http_completion_event completion, http_method method = m_get, const std::string &_postdata = "", const std::string &_mimetype = "text/plain", const std::multimap &_headers = {}); - - /** - * @brief Destroy the http request object - */ - ~http_request(); - - /** - * @brief Call the completion callback, if the request is complete. - * @param c callback to call - */ - void complete(const http_request_completion_t &c); - - /** - * @brief Execute the HTTP request and mark the request complete. - * @param owner creating cluster - */ - http_request_completion_t run(class cluster* owner); - - /** @brief Returns true if the request is complete */ - bool is_completed(); -}; - -/** - * @brief A rate limit bucket. The library builds one of these for - * each endpoint. - */ -struct DPP_EXPORT bucket_t { - /** @brief Request limit */ - uint64_t limit; - /** @brief Requests remaining */ - uint64_t remaining; - /** @brief Ratelimit of this bucket resets after this many seconds */ - uint64_t reset_after; - /** @brief Ratelimit of this bucket can be retried after this many seconds */ - uint64_t retry_after; - /** @brief Timestamp this buckets counters were updated */ - time_t timestamp; -}; - - -/** - * @brief Represents a thread in the thread pool handling requests to HTTP(S) servers. - * There are several of these, the total defined by a constant in queues.cpp, and each - * one will always receive requests for the same rate limit bucket based on its endpoint - * portion of the url. This makes rate limit handling reliable and easy to manage. - * Each of these also has its own mutex, so that requests are less likely to block while - * waiting for internal containers to be usable. - */ -class DPP_EXPORT in_thread { -private: - /** - * @brief True if ending - */ - bool terminating; - - /** - * @brief Request queue that owns this in_thread - */ - class request_queue* requests; - - /** - * @brief The cluster that owns this in_thread - */ - class cluster* creator; - - /** - * @brief Inbound queue mutex thread safety - */ - std::shared_mutex in_mutex; - - /** - * @brief Inbound queue thread - */ - std::thread* in_thr; - - /** - * @brief Inbound queue condition, signalled when there are requests to fulfill - */ - std::condition_variable in_ready; - - /** - * @brief Ratelimit bucket counters - */ - std::map buckets; - - /** - * @brief Queue of requests to be made - */ - std::map> requests_in; - - /** - * @brief Inbound queue thread loop - * @param index Thread index - */ - void in_loop(uint32_t index); -public: - /** - * @brief Construct a new in thread object - * - * @param owner Owning cluster - * @param req_q Owning request queue - * @param index Thread index number - */ - in_thread(class cluster* owner, class request_queue* req_q, uint32_t index); - - /** - * @brief Destroy the in thread object - * This will end the thread that is owned by this object by joining it. - */ - ~in_thread(); - - /** - * @brief Post a http_request to this thread. - * - * @param req http_request to post. The pointer will be freed when it has - * been executed. - */ - void post_request(http_request* req); -}; - -/** - * @brief The request_queue class manages rate limits and marshalls HTTP requests that have - * been built as http_request objects. - * - * It ensures asynchronous delivery of events and queueing of requests. - * - * It will spawn two threads, one to make outbound HTTP requests and push the returned - * results into a queue, and the second to call the callback methods with these results. - * They are separated so that if the user decides to take a long time processing a reply - * in their callback it won't affect when other requests are sent, and if a HTTP request - * takes a long time due to latency, it won't hold up user processing. - * - * There are usually two request_queue objects in each dpp::cluster, one of which is used - * internally for the various REST methods to Discord such as sending messages, and the other - * used to support user REST calls via dpp::cluster::request(). - */ -class DPP_EXPORT request_queue { -protected: - /** - * @brief Required so in_thread can access these member variables - */ - friend class in_thread; - - /** - * @brief The cluster that owns this request_queue - */ - class cluster* creator; - - /** - * @brief Outbound queue mutex thread safety - */ - std::shared_mutex out_mutex; - - /** - * @brief Outbound queue thread - * Note that although there are many 'in queues', which handle the HTTP requests, - * there is only ever one 'out queue' which dispatches the results to the caller. - * This is to simplify thread management in bots that use the library, as less mutexing - * and thread safety boilerplate is required. - */ - std::thread* out_thread; - - /** - * @brief Outbound queue condition, signalled when there are requests completed to call callbacks for - */ - std::condition_variable out_ready; - - /** - * @brief Completed requests queue - */ - std::queue> responses_out; - - /** - * @brief A vector of inbound request threads forming a pool. - * There are a set number of these defined by a constant in queues.cpp. A request is always placed - * on the same element in this vector, based upon its url, so that two conditions are satisfied: - * 1) Any requests for the same ratelimit bucket are handled by the same thread in the pool so that - * they do not create unnecessary 429 errors, - * 2) Requests for different endpoints go into different buckets, so that they may be requested in parallel - * A global ratelimit event pauses all threads in the pool. These are few and far between. - */ - std::vector requests_in; - - /** - * @brief Completed requests to delete - */ - std::multimap> responses_to_delete; - - /** - * @brief Set to true if the threads should terminate - */ - bool terminating; - - /** - * @brief True if globally rate limited - makes the entire request thread wait - */ - bool globally_ratelimited; - - /** - * @brief How many seconds we are globally rate limited for, if globally_ratelimited is true - */ - uint64_t globally_limited_for; - - /** - * @brief Number of request threads in the thread pool - */ - uint32_t in_thread_pool_size; - - /** - * @brief Outbound queue thread loop - */ - void out_loop(); -public: - - /** - * @brief constructor - * @param owner The creating cluster. - * @param request_threads The number of http request threads to allocate to the threadpool. - * By default eight threads are allocated. - * Side effects: Creates threads for the queue - */ - request_queue(class cluster* owner, uint32_t request_threads = 8); - - /** - * @brief Add more request threads to the library at runtime. - * @note You should do this at a quiet time when there are few requests happening. - * This will reorganise the hashing used to place requests into the thread pool so if you do - * this while the bot is busy there is a small chance of receiving "429 rate limited" errors. - * @param request_threads Number of threads to add. It is not possible to scale down at runtime. - * @return reference to self - */ - request_queue& add_request_threads(uint32_t request_threads); - - /** - * @brief Get the request thread count - * @return uint32_t number of request threads that are active - */ - uint32_t get_request_thread_count() const; - - /** - * @brief Destroy the request queue object. - * Side effects: Joins and deletes queue threads - */ - ~request_queue(); - - /** - * @brief Put a http_request into the request queue. You should ALWAYS "new" an object - * to pass to here -- don't submit an object that's on the stack! - * @note Will use a simple hash function to determine which of the 'in queues' to place - * this request onto. - * @param req request to add - * @return reference to self - */ - request_queue& post_request(http_request *req); - - /** - * @brief Returns true if the bot is currently globally rate limited - * @return true if globally rate limited - */ - bool is_globally_ratelimited() const; -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Error values. Most of these are currently unused in https_client. + */ +enum http_error { + /// Request successful + h_success = 0, + /// Status unknown + h_unknown, + /// Connect failed + h_connection, + /// Invalid local ip address + h_bind_ip_address, + /// Read error + h_read, + /// Write error + h_write, + /// Too many 30x redirects + h_exceed_redirect_count, + /// Request cancelled + h_canceled, + /// SSL connection error + h_ssl_connection, + /// SSL cert loading error + h_ssl_loading_certs, + /// SSL server verification error + h_ssl_server_verification, + /// Unsupported multipart boundary characters + h_unsupported_multipart_boundary_chars, + /// Compression error + h_compression, +}; + +/** + * @brief The result of any HTTP request. Contains the headers, vital + * rate limit figures, and returned request body. + */ +struct DPP_EXPORT http_request_completion_t { + /** @brief HTTP headers of response */ + std::map headers; + /** @brief HTTP status, e.g. 200 = OK, 404 = Not found, 429 = Rate limited */ + uint16_t status = 0; + /** @brief Error status (e.g. if the request could not connect at all) */ + http_error error = h_success; + /** @brief Ratelimit bucket */ + std::string ratelimit_bucket; + /** @brief Ratelimit limit of requests */ + uint64_t ratelimit_limit = 0; + /** @brief Ratelimit remaining requests */ + uint64_t ratelimit_remaining = 0; + /** @brief Ratelimit reset after (seconds) */ + uint64_t ratelimit_reset_after = 0; + /** @brief Ratelimit retry after (seconds) */ + uint64_t ratelimit_retry_after = 0; + /** @brief True if this request has caused us to be globally rate limited */ + bool ratelimit_global = false; + /** @brief Reply body */ + std::string body; + /** @brief Ping latency */ + double latency; +}; + +/** + * @brief Results of HTTP requests are called back to these std::function types. + * @note Returned http_completion_events are called ASYNCHRONOUSLY in your + * code which means they execute in a separate thread. The completion events + * arrive in order. + */ +typedef std::function http_completion_event; + +/** + * @brief Various types of http method supported by the Discord API + */ +enum http_method { + /// GET + m_get, + /// POST + m_post, + /// PUT + m_put, + /// PATCH + m_patch, + /// DELETE + m_delete +}; + +/** + * @brief A HTTP request. + * + * You should instantiate one of these objects via its constructor, + * and pass a pointer to it into an instance of request_queue. Although you can + * directly call the run() method of the object and it will make a HTTP call, be + * aware that if you do this, it will be a **BLOCKING call** (not asynchronous) and + * will not respect rate limits, as both of these functions are managed by the + * request_queue class. + */ +class DPP_EXPORT http_request { + /** @brief Completion callback */ + http_completion_event complete_handler; + /** @brief True if request has been made */ + bool completed; + /** @brief True for requests that are not going to discord (rate limits code skipped) */ + bool non_discord; +public: + /** @brief Endpoint name e.g. /api/users */ + std::string endpoint; + /** @brief Major and minor parameters */ + std::string parameters; + /** @brief Postdata for POST and PUT */ + std::string postdata; + /** @brief HTTP method for request */ + http_method method; + /** @brief Audit log reason for Discord requests, if non-empty */ + std::string reason; + /** @brief Upload file name (server side) */ + std::vector file_name; + /** @brief Upload file contents (binary) */ + std::vector file_content; + /** @brief Request mime type */ + std::string mimetype; + /** @brief Request headers (non-discord requests only) */ + std::multimap req_headers; + /** @brief Waiting for rate limit to expire */ + bool waiting; + + /** + * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _endpoint The API endpoint, e.g. /api/guilds + * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id + * @param completion completion event to call when done + * @param _postdata Data to send in POST and PUT requests + * @param method The HTTP method to use from dpp::http_method + * @param audit_reason Audit log reason to send, empty to send none + * @param filename The filename (server side) of any uploaded file + * @param filecontent The binary content of any uploaded file for the request + */ + http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::string &filename = "", const std::string &filecontent = ""); + + /** + * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _endpoint The API endpoint, e.g. /api/guilds + * @param _parameters Major and minor parameters for the endpoint e.g. a user id or guild id + * @param completion completion event to call when done + * @param _postdata Data to send in POST and PUT requests + * @param method The HTTP method to use from dpp::http_method + * @param audit_reason Audit log reason to send, empty to send none + * @param filename The filename (server side) of any uploaded file + * @param filecontent The binary content of any uploaded file for the request + */ + http_request(const std::string &_endpoint, const std::string &_parameters, http_completion_event completion, const std::string &_postdata = "", http_method method = m_get, const std::string &audit_reason = "", const std::vector &filename = {}, const std::vector &filecontent = {}); + + /** + * @brief Constructor. When constructing one of these objects it should be passed to request_queue::post_request(). + * @param _url Raw HTTP url + * @param completion completion event to call when done + * @param method The HTTP method to use from dpp::http_method + * @param _postdata Data to send in POST and PUT requests + * @param _mimetype POST data mime type + * @param _headers HTTP headers to send + */ + http_request(const std::string &_url, http_completion_event completion, http_method method = m_get, const std::string &_postdata = "", const std::string &_mimetype = "text/plain", const std::multimap &_headers = {}); + + /** + * @brief Destroy the http request object + */ + ~http_request(); + + /** + * @brief Call the completion callback, if the request is complete. + * @param c callback to call + */ + void complete(const http_request_completion_t &c); + + /** + * @brief Execute the HTTP request and mark the request complete. + * @param owner creating cluster + */ + http_request_completion_t run(class cluster* owner); + + /** @brief Returns true if the request is complete */ + bool is_completed(); +}; + +/** + * @brief A rate limit bucket. The library builds one of these for + * each endpoint. + */ +struct DPP_EXPORT bucket_t { + /** @brief Request limit */ + uint64_t limit; + /** @brief Requests remaining */ + uint64_t remaining; + /** @brief Ratelimit of this bucket resets after this many seconds */ + uint64_t reset_after; + /** @brief Ratelimit of this bucket can be retried after this many seconds */ + uint64_t retry_after; + /** @brief Timestamp this buckets counters were updated */ + time_t timestamp; +}; + + +/** + * @brief Represents a thread in the thread pool handling requests to HTTP(S) servers. + * There are several of these, the total defined by a constant in queues.cpp, and each + * one will always receive requests for the same rate limit bucket based on its endpoint + * portion of the url. This makes rate limit handling reliable and easy to manage. + * Each of these also has its own mutex, so that requests are less likely to block while + * waiting for internal containers to be usable. + */ +class DPP_EXPORT in_thread { +private: + /** + * @brief True if ending + */ + bool terminating; + + /** + * @brief Request queue that owns this in_thread + */ + class request_queue* requests; + + /** + * @brief The cluster that owns this in_thread + */ + class cluster* creator; + + /** + * @brief Inbound queue mutex thread safety + */ + std::shared_mutex in_mutex; + + /** + * @brief Inbound queue thread + */ + std::thread* in_thr; + + /** + * @brief Inbound queue condition, signalled when there are requests to fulfill + */ + std::condition_variable in_ready; + + /** + * @brief Ratelimit bucket counters + */ + std::map buckets; + + /** + * @brief Queue of requests to be made + */ + std::map> requests_in; + + /** + * @brief Inbound queue thread loop + * @param index Thread index + */ + void in_loop(uint32_t index); +public: + /** + * @brief Construct a new in thread object + * + * @param owner Owning cluster + * @param req_q Owning request queue + * @param index Thread index number + */ + in_thread(class cluster* owner, class request_queue* req_q, uint32_t index); + + /** + * @brief Destroy the in thread object + * This will end the thread that is owned by this object by joining it. + */ + ~in_thread(); + + /** + * @brief Post a http_request to this thread. + * + * @param req http_request to post. The pointer will be freed when it has + * been executed. + */ + void post_request(http_request* req); +}; + +/** + * @brief The request_queue class manages rate limits and marshalls HTTP requests that have + * been built as http_request objects. + * + * It ensures asynchronous delivery of events and queueing of requests. + * + * It will spawn two threads, one to make outbound HTTP requests and push the returned + * results into a queue, and the second to call the callback methods with these results. + * They are separated so that if the user decides to take a long time processing a reply + * in their callback it won't affect when other requests are sent, and if a HTTP request + * takes a long time due to latency, it won't hold up user processing. + * + * There are usually two request_queue objects in each dpp::cluster, one of which is used + * internally for the various REST methods to Discord such as sending messages, and the other + * used to support user REST calls via dpp::cluster::request(). + */ +class DPP_EXPORT request_queue { +protected: + /** + * @brief Required so in_thread can access these member variables + */ + friend class in_thread; + + /** + * @brief The cluster that owns this request_queue + */ + class cluster* creator; + + /** + * @brief Outbound queue mutex thread safety + */ + std::shared_mutex out_mutex; + + /** + * @brief Outbound queue thread + * Note that although there are many 'in queues', which handle the HTTP requests, + * there is only ever one 'out queue' which dispatches the results to the caller. + * This is to simplify thread management in bots that use the library, as less mutexing + * and thread safety boilerplate is required. + */ + std::thread* out_thread; + + /** + * @brief Outbound queue condition, signalled when there are requests completed to call callbacks for + */ + std::condition_variable out_ready; + + /** + * @brief Completed requests queue + */ + std::queue> responses_out; + + /** + * @brief A vector of inbound request threads forming a pool. + * There are a set number of these defined by a constant in queues.cpp. A request is always placed + * on the same element in this vector, based upon its url, so that two conditions are satisfied: + * 1) Any requests for the same ratelimit bucket are handled by the same thread in the pool so that + * they do not create unnecessary 429 errors, + * 2) Requests for different endpoints go into different buckets, so that they may be requested in parallel + * A global ratelimit event pauses all threads in the pool. These are few and far between. + */ + std::vector requests_in; + + /** + * @brief Completed requests to delete + */ + std::multimap> responses_to_delete; + + /** + * @brief Set to true if the threads should terminate + */ + bool terminating; + + /** + * @brief True if globally rate limited - makes the entire request thread wait + */ + bool globally_ratelimited; + + /** + * @brief How many seconds we are globally rate limited for, if globally_ratelimited is true + */ + uint64_t globally_limited_for; + + /** + * @brief Number of request threads in the thread pool + */ + uint32_t in_thread_pool_size; + + /** + * @brief Outbound queue thread loop + */ + void out_loop(); +public: + + /** + * @brief constructor + * @param owner The creating cluster. + * @param request_threads The number of http request threads to allocate to the threadpool. + * By default eight threads are allocated. + * Side effects: Creates threads for the queue + */ + request_queue(class cluster* owner, uint32_t request_threads = 8); + + /** + * @brief Add more request threads to the library at runtime. + * @note You should do this at a quiet time when there are few requests happening. + * This will reorganise the hashing used to place requests into the thread pool so if you do + * this while the bot is busy there is a small chance of receiving "429 rate limited" errors. + * @param request_threads Number of threads to add. It is not possible to scale down at runtime. + * @return reference to self + */ + request_queue& add_request_threads(uint32_t request_threads); + + /** + * @brief Get the request thread count + * @return uint32_t number of request threads that are active + */ + uint32_t get_request_thread_count() const; + + /** + * @brief Destroy the request queue object. + * Side effects: Joins and deletes queue threads + */ + ~request_queue(); + + /** + * @brief Put a http_request into the request queue. You should ALWAYS "new" an object + * to pass to here -- don't submit an object that's on the stack! + * @note Will use a simple hash function to determine which of the 'in queues' to place + * this request onto. + * @param req request to add + * @return reference to self + */ + request_queue& post_request(http_request *req); + + /** + * @brief Returns true if the bot is currently globally rate limited + * @return true if globally rate limited + */ + bool is_globally_ratelimited() const; +}; + +}; diff --git a/3rdParty/dpp/restrequest.h b/3rdParty/dpp/restrequest.h index 74ca431f6e..f97f070684 100644 --- a/3rdParty/dpp/restrequest.h +++ b/3rdParty/dpp/restrequest.h @@ -1,205 +1,205 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Templated REST request helper to save on typing - * - * @tparam T type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - if (callback) { - callback(confirmation_callback_t(c, T().fill_from_json(&j), http)); - } - }); -}; - -/** - * @brief Templated REST request helper to save on typing (specialised for message) - * - * @tparam T type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - if (callback) { - callback(confirmation_callback_t(c, message(c).fill_from_json(&j), http)); - } - }); -}; - -/** - * @brief Templated REST request helper to save on typing (specialised for confirmation) - * - * @tparam T type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - if (callback) { - callback(confirmation_callback_t(c, confirmation(), http)); - } - }); -}; - -/** - * @brief Templated REST request helper to save on typing (for returned lists) - * - * @tparam T singular type to return in lambda callback - * @tparam T map type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param key Key name of elements in the json list - * @param callback Callback lambda - */ -template inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key = "id") { - c->post_rest(basepath, major, minor, method, postdata, [c, key, callback](json &j, const http_request_completion_t& http) { - std::unordered_map list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list[snowflake_not_null(&curr_item, key.c_str())] = T().fill_from_json(&curr_item); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} - -/** - * @brief Templated REST request helper to save on typing (for returned lists, specialised for invites) - * - * @tparam T singular type to return in lambda callback - * @tparam T map type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param key Key name of elements in the json list - * @param callback Callback lambda - */ -template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - std::unordered_map list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list[string_not_null(&curr_item, "code")] = invite().fill_from_json(&curr_item); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} -/** - * @brief Templated REST request helper to save on typing (for returned lists, specialised for voiceregions) - * - * @tparam T singular type to return in lambda callback - * @tparam T map type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param key Key name of elements in the json list - * @param callback Callback lambda - */ -template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - std::unordered_map list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list[string_not_null(&curr_item, "id")] = voiceregion().fill_from_json(&curr_item); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} - -/** - * @brief Templated REST request helper to save on typing (for returned vectors) - * - * @tparam T singular type to return in lambda callback - * @tparam T vector type to return in lambda callback - * @param c calling cluster - * @param basepath base path for API call - * @param major major API function - * @param minor minor API function - * @param method HTTP method - * @param postdata Post data or empty string - * @param callback Callback lambda - */ -template inline void rest_request_vector(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { - c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { - std::vector list; - confirmation_callback_t e(c, confirmation(), http); - if (!e.is_error()) { - for (auto & curr_item : j) { - list.push_back(T().fill_from_json(&curr_item)); - } - } - if (callback) { - callback(confirmation_callback_t(c, list, http)); - } - }); -} - - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Templated REST request helper to save on typing + * + * @tparam T type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t(c, T().fill_from_json(&j), http)); + } + }); +}; + +/** + * @brief Templated REST request helper to save on typing (specialised for message) + * + * @tparam T type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t(c, message(c).fill_from_json(&j), http)); + } + }); +}; + +/** + * @brief Templated REST request helper to save on typing (specialised for confirmation) + * + * @tparam T type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template<> inline void rest_request(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + if (callback) { + callback(confirmation_callback_t(c, confirmation(), http)); + } + }); +}; + +/** + * @brief Templated REST request helper to save on typing (for returned lists) + * + * @tparam T singular type to return in lambda callback + * @tparam T map type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param key Key name of elements in the json list + * @param callback Callback lambda + */ +template inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key = "id") { + c->post_rest(basepath, major, minor, method, postdata, [c, key, callback](json &j, const http_request_completion_t& http) { + std::unordered_map list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list[snowflake_not_null(&curr_item, key.c_str())] = T().fill_from_json(&curr_item); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} + +/** + * @brief Templated REST request helper to save on typing (for returned lists, specialised for invites) + * + * @tparam T singular type to return in lambda callback + * @tparam T map type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param key Key name of elements in the json list + * @param callback Callback lambda + */ +template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + std::unordered_map list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list[string_not_null(&curr_item, "code")] = invite().fill_from_json(&curr_item); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} +/** + * @brief Templated REST request helper to save on typing (for returned lists, specialised for voiceregions) + * + * @tparam T singular type to return in lambda callback + * @tparam T map type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param key Key name of elements in the json list + * @param callback Callback lambda + */ +template<> inline void rest_request_list(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback, const std::string& key) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + std::unordered_map list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list[string_not_null(&curr_item, "id")] = voiceregion().fill_from_json(&curr_item); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} + +/** + * @brief Templated REST request helper to save on typing (for returned vectors) + * + * @tparam T singular type to return in lambda callback + * @tparam T vector type to return in lambda callback + * @param c calling cluster + * @param basepath base path for API call + * @param major major API function + * @param minor minor API function + * @param method HTTP method + * @param postdata Post data or empty string + * @param callback Callback lambda + */ +template inline void rest_request_vector(dpp::cluster* c, const char* basepath, const std::string &major, const std::string &minor, http_method method, const std::string& postdata, command_completion_event_t callback) { + c->post_rest(basepath, major, minor, method, postdata, [c, callback](json &j, const http_request_completion_t& http) { + std::vector list; + confirmation_callback_t e(c, confirmation(), http); + if (!e.is_error()) { + for (auto & curr_item : j) { + list.push_back(T().fill_from_json(&curr_item)); + } + } + if (callback) { + callback(confirmation_callback_t(c, list, http)); + } + }); +} + + }; \ No newline at end of file diff --git a/3rdParty/dpp/restresults.h b/3rdParty/dpp/restresults.h index 8a5afb4c59..58c2e926ed 100644 --- a/3rdParty/dpp/restresults.h +++ b/3rdParty/dpp/restresults.h @@ -1,316 +1,316 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -using json = nlohmann::json; - -namespace dpp { - -#ifdef _WIN32 - #ifdef _DEBUG - extern "C" DPP_EXPORT void you_are_using_a_debug_build_of_dpp_on_a_release_project(); - #else - extern "C" DPP_EXPORT void you_are_using_a_release_build_of_dpp_on_a_debug_project(); - #endif -#endif - -struct DPP_EXPORT version_checker { - version_checker() { - #ifdef _WIN32 - #ifdef _DEBUG - you_are_using_a_debug_build_of_dpp_on_a_release_project(); - #else - you_are_using_a_release_build_of_dpp_on_a_debug_project(); - #endif - #endif - } -}; - -static version_checker dpp_vc; - - -/** - * @brief A list of shards - */ -typedef std::map shard_list; - -/** - * @brief Represents the various information from the 'get gateway bot' api call - */ -struct DPP_EXPORT gateway { - /// Gateway websocket url - std::string url; - - /// Number of suggested shards to start - uint32_t shards; - - /// Total number of sessions that can be started - uint32_t session_start_total; - - /// How many sessions are left - uint32_t session_start_remaining; - - /// How many seconds until the session start quota resets - uint32_t session_start_reset_after; - - /// How many sessions can be started at the same time - uint32_t session_start_max_concurrency; - - /** - * @brief Construct a new gateway object - * - * @param j JSON data to construct from - */ - gateway(nlohmann::json* j); - - /** - * @brief Construct a new gateway object - */ - gateway(); - - /** - * @brief Fill this object from json - * - * @param j json to fill from - * @return gateway& reference to self - */ - gateway& fill_from_json(nlohmann::json* j); -}; - -/** - * @brief Confirmation object represents any true or false simple REST request - * - */ -struct DPP_EXPORT confirmation { - bool success; -}; - -/** - * @brief A container for types that can be returned for a REST API call - * - */ -typedef std::variant< - application_role_connection, - application_role_connection_metadata_list, - confirmation, - message, - message_map, - user, - user_identified, - user_map, - guild_member, - guild_member_map, - channel, - channel_map, - thread_member, - thread_member_map, - guild, - guild_map, - guild_command_permissions, - guild_command_permissions_map, - role, - role_map, - invite, - invite_map, - dtemplate, - dtemplate_map, - emoji, - emoji_map, - ban, - ban_map, - voiceregion, - voiceregion_map, - integration, - integration_map, - webhook, - webhook_map, - prune, - guild_widget, - gateway, - interaction, - interaction_response, - auditlog, - slashcommand, - slashcommand_map, - stage_instance, - sticker, - sticker_map, - sticker_pack, - sticker_pack_map, - application, - application_map, - connection, - connection_map, - thread, - thread_map, - scheduled_event, - scheduled_event_map, - event_member, - event_member_map, - automod_rule, - automod_rule_map - > confirmable_t; - -/** - * @brief The details of a field in an error response - */ -struct DPP_EXPORT error_detail { - /** - * @brief Object name which is in error - */ - std::string object; - /** - * @brief Field name which is in error - */ - std::string field; - /** - * @brief Error code - */ - std::string code; - /** - * @brief Error reason (full message) - */ - std::string reason; -}; - -/** - * @brief The full details of an error from a REST response - */ -struct DPP_EXPORT error_info { - /** - * @brief Error code - */ - uint32_t code = 0; - /** - * @brief Error message - * - */ - std::string message; - /** - * @brief Field specific error descriptions - */ - std::vector errors; -}; - -/** - * @brief The results of a REST call wrapped in a convenient struct - */ -struct DPP_EXPORT confirmation_callback_t { - /** Information about the HTTP call used to make the request */ - http_request_completion_t http_info; - - /** Value returned, wrapped in variant */ - confirmable_t value; - - /** Owner/creator of the callback object */ - const class cluster* bot; - - /** - * @brief Construct a new confirmation callback t object - */ - confirmation_callback_t() = default; - - /** - * @brief Construct a new confirmation callback t object - * - * @param creator owning cluster object - */ - confirmation_callback_t(cluster* creator); - - /** - * @brief Construct a new confirmation callback object - * - * @param _http The HTTP metadata from the REST call - */ - confirmation_callback_t(const http_request_completion_t& _http); - - /** - * @brief Construct a new confirmation callback object - * - * @param creator owning cluster object - * @param _value The value to encapsulate in the confirmable_t - * @param _http The HTTP metadata from the REST call - */ - confirmation_callback_t(cluster* creator, const confirmable_t& _value, const http_request_completion_t& _http); - - /** - * @brief Returns true if the call resulted in an error rather than a legitimate value in the - * confirmation_callback_t::value member. - * - * @return true There was an error who's details can be obtained by get_error() - * @return false There was no error - */ - bool is_error() const; - - /** - * @brief Get the error_info object. - * The error_info object contains the details of any REST error, if there is an error - * (to find out if there is an error check confirmation_callback_t::is_error()) - * - * @return error_info The details of the error message - */ - error_info get_error() const; - - /** - * @brief Get the stored value via std::get - * @tparam T type to get - * @return stored value as type T - */ - template - T get() const { - return std::get(value); - } -}; - -/** - * @brief A callback upon command completion - */ -typedef std::function command_completion_event_t; - -/** - * @brief Automatically JSON encoded HTTP result - */ -typedef std::function json_encode_t; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using json = nlohmann::json; + +namespace dpp { + +#ifdef _WIN32 + #ifdef _DEBUG + extern "C" DPP_EXPORT void you_are_using_a_debug_build_of_dpp_on_a_release_project(); + #else + extern "C" DPP_EXPORT void you_are_using_a_release_build_of_dpp_on_a_debug_project(); + #endif +#endif + +struct DPP_EXPORT version_checker { + version_checker() { + #ifdef _WIN32 + #ifdef _DEBUG + you_are_using_a_debug_build_of_dpp_on_a_release_project(); + #else + you_are_using_a_release_build_of_dpp_on_a_debug_project(); + #endif + #endif + } +}; + +static version_checker dpp_vc; + + +/** + * @brief A list of shards + */ +typedef std::map shard_list; + +/** + * @brief Represents the various information from the 'get gateway bot' api call + */ +struct DPP_EXPORT gateway { + /// Gateway websocket url + std::string url; + + /// Number of suggested shards to start + uint32_t shards; + + /// Total number of sessions that can be started + uint32_t session_start_total; + + /// How many sessions are left + uint32_t session_start_remaining; + + /// How many seconds until the session start quota resets + uint32_t session_start_reset_after; + + /// How many sessions can be started at the same time + uint32_t session_start_max_concurrency; + + /** + * @brief Construct a new gateway object + * + * @param j JSON data to construct from + */ + gateway(nlohmann::json* j); + + /** + * @brief Construct a new gateway object + */ + gateway(); + + /** + * @brief Fill this object from json + * + * @param j json to fill from + * @return gateway& reference to self + */ + gateway& fill_from_json(nlohmann::json* j); +}; + +/** + * @brief Confirmation object represents any true or false simple REST request + * + */ +struct DPP_EXPORT confirmation { + bool success; +}; + +/** + * @brief A container for types that can be returned for a REST API call + * + */ +typedef std::variant< + application_role_connection, + application_role_connection_metadata_list, + confirmation, + message, + message_map, + user, + user_identified, + user_map, + guild_member, + guild_member_map, + channel, + channel_map, + thread_member, + thread_member_map, + guild, + guild_map, + guild_command_permissions, + guild_command_permissions_map, + role, + role_map, + invite, + invite_map, + dtemplate, + dtemplate_map, + emoji, + emoji_map, + ban, + ban_map, + voiceregion, + voiceregion_map, + integration, + integration_map, + webhook, + webhook_map, + prune, + guild_widget, + gateway, + interaction, + interaction_response, + auditlog, + slashcommand, + slashcommand_map, + stage_instance, + sticker, + sticker_map, + sticker_pack, + sticker_pack_map, + application, + application_map, + connection, + connection_map, + thread, + thread_map, + scheduled_event, + scheduled_event_map, + event_member, + event_member_map, + automod_rule, + automod_rule_map + > confirmable_t; + +/** + * @brief The details of a field in an error response + */ +struct DPP_EXPORT error_detail { + /** + * @brief Object name which is in error + */ + std::string object; + /** + * @brief Field name which is in error + */ + std::string field; + /** + * @brief Error code + */ + std::string code; + /** + * @brief Error reason (full message) + */ + std::string reason; +}; + +/** + * @brief The full details of an error from a REST response + */ +struct DPP_EXPORT error_info { + /** + * @brief Error code + */ + uint32_t code = 0; + /** + * @brief Error message + * + */ + std::string message; + /** + * @brief Field specific error descriptions + */ + std::vector errors; +}; + +/** + * @brief The results of a REST call wrapped in a convenient struct + */ +struct DPP_EXPORT confirmation_callback_t { + /** Information about the HTTP call used to make the request */ + http_request_completion_t http_info; + + /** Value returned, wrapped in variant */ + confirmable_t value; + + /** Owner/creator of the callback object */ + const class cluster* bot; + + /** + * @brief Construct a new confirmation callback t object + */ + confirmation_callback_t() = default; + + /** + * @brief Construct a new confirmation callback t object + * + * @param creator owning cluster object + */ + confirmation_callback_t(cluster* creator); + + /** + * @brief Construct a new confirmation callback object + * + * @param _http The HTTP metadata from the REST call + */ + confirmation_callback_t(const http_request_completion_t& _http); + + /** + * @brief Construct a new confirmation callback object + * + * @param creator owning cluster object + * @param _value The value to encapsulate in the confirmable_t + * @param _http The HTTP metadata from the REST call + */ + confirmation_callback_t(cluster* creator, const confirmable_t& _value, const http_request_completion_t& _http); + + /** + * @brief Returns true if the call resulted in an error rather than a legitimate value in the + * confirmation_callback_t::value member. + * + * @return true There was an error who's details can be obtained by get_error() + * @return false There was no error + */ + bool is_error() const; + + /** + * @brief Get the error_info object. + * The error_info object contains the details of any REST error, if there is an error + * (to find out if there is an error check confirmation_callback_t::is_error()) + * + * @return error_info The details of the error message + */ + error_info get_error() const; + + /** + * @brief Get the stored value via std::get + * @tparam T type to get + * @return stored value as type T + */ + template + T get() const { + return std::get(value); + } +}; + +/** + * @brief A callback upon command completion + */ +typedef std::function command_completion_event_t; + +/** + * @brief Automatically JSON encoded HTTP result + */ +typedef std::function json_encode_t; +}; diff --git a/3rdParty/dpp/role.h b/3rdParty/dpp/role.h index 1508c8d913..bfd1ab951c 100644 --- a/3rdParty/dpp/role.h +++ b/3rdParty/dpp/role.h @@ -1,648 +1,648 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** Various flags related to dpp::role */ -enum role_flags : uint8_t { - r_hoist = 0b00000001, //!< Hoisted role - r_managed = 0b00000010, //!< Managed role (introduced by a bot or application) - r_mentionable = 0b00000100, //!< Mentionable with a ping - r_premium_subscriber = 0b00001000, //!< This is set for the role given to nitro -}; - -/** - * @brief Represents a role within a dpp::guild. - * Roles are combined via logical OR of the permission bitmasks, then channel-specific overrides - * can be applied on top, deny types apply a logic NOT to the bit mask, and allows apply a logical OR. - * @note Every guild has at least one role, called the 'everyone' role, which always has the same role - * ID as the guild's ID. This is the base permission set applied to all users where no other role or override - * applies, and is the starting value of the bit mask looped through to calculate channel permissions. - */ -class DPP_EXPORT role : public managed, public json_interface { -public: - /** - * @brief Role name - * Between 1 and 100 characters. - */ - std::string name; - /** - * @brief Guild ID - */ - snowflake guild_id; - /** - * @brief Role colour. - * A colour of 0 means no colour. If you want a black role, - * you must use the value 0x000001. - */ - uint32_t colour; - /** Role position */ - uint8_t position; - /** Role permissions bitmask values from dpp::permissions */ - permission permissions; - /** Role flags from dpp::role_flags */ - uint8_t flags; - /** Integration id if any (e.g. role is a bot's role created when it was invited) */ - snowflake integration_id; - /** Bot id if any (e.g. role is a bot's role created when it was invited) */ - snowflake bot_id; - /** The unicode emoji used for the role's icon, can be an empty string */ - std::string unicode_emoji; - /** The role icon hash, can be an empty string */ - utility::iconhash icon; - /** Image data for the role icon (if any) */ - std::string* image_data; - - /** - * @brief Construct a new role object - */ - role(); - - /** - * @brief Destroy the role object - */ - virtual ~role(); - - /** - * @brief Create a mentionable role. - * @param id The ID of the role. - * @return std::string The formatted mention of the role. - */ - static std::string get_mention(const snowflake& id); - - /** - * @brief Set the name of the role - * Maximum length: 100 - * Minimum length: 1 - * @param n Name to set - * @return role& reference to self - * @throw dpp::exception thrown if role length is less than 1 character - */ - role& set_name(const std::string& n); - - /** - * @brief Set the colour - * - * @param c Colour to set - * @note There is an americanised version of this method, role::set_color(). - * @return role& reference to self - */ - role& set_colour(uint32_t c); - - /** - * @brief Set the color - * - * @param c Colour to set - * @note This is an alias of role::set_colour for American spelling. - * @return role& reference to self - */ - role& set_color(uint32_t c); - - /** - * @brief Set the flags - * - * @param f Flags to set from dpp::role_flags - * @return role& reference to self - */ - role& set_flags(uint8_t f); - - /** - * @brief Set the integration id - * - * @param i Integration ID to set - * @return role& reference to self - */ - role& set_integration_id(snowflake i); - - /** - * @brief Set the bot id - * - * @param b Bot ID to set - * @return role& reference to self - */ - role& set_bot_id(snowflake b); - - /** - * @brief Set the guild id - * - * @param gid Guild ID to set - * @return role& reference to self - */ - role& set_guild_id(snowflake gid); - - /** - * @brief Fill this role from json. - * - * @param j The json data - * @return A reference to self - */ - role& fill_from_json(nlohmann::json* j); - - /** - * @brief Fill this role from json. - * - * @param guild_id the guild id to place in the json - * @param j The json data - * @return A reference to self - */ - role& fill_from_json(snowflake guild_id, nlohmann::json* j); - - /** - * @brief Build a json string from this object. - * - * @param with_id true if the ID is to be included in the json text - * @return The json of the role - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Get the mention/ping for the role - * - * @return std::string mention - */ - std::string get_mention() const; - - /** - * @brief Returns the role's icon if they have one, otherwise returns an empty string - * - * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized icon is returned. - * @return std::string icon url or empty string - */ - std::string get_icon_url(uint16_t size = 0) const; - - /** - * @brief Load an image into the object as base64 - * - * @param image_blob Image binary data - * @param type Type of image - * @return emoji& Reference to self - */ - role& load_image(const std::string &image_blob, const image_type type); - - /** - * @brief Operator less than, used for checking if a role is below another. - * - * @param lhs first role to compare - * @param rhs second role to compare - * @return true if lhs is less than rhs - */ - friend inline bool operator< (const role& lhs, const role& rhs) - { - return lhs.position < rhs.position; - } - - /** - * @brief Operator greater than, used for checking if a role is above another. - * - * @param lhs first role to compare - * @param rhs second role to compare - * @return true if lhs is greater than rhs - */ - friend inline bool operator> (const role& lhs, const role& rhs) - { - return lhs.position > rhs.position; - } - - /** - * @brief Operator equals, used for checking if a role is ranked equal to another. - * - * @param other role to compare - * @return true if is equal to other - */ - inline bool operator== (const role& other) const - { - return this->position == other.position; - } - - /** - * @brief Operator not equals, used for checking if a role is ranked equal to another. - * - * @param other role to compare - * @return true if is not equal to other - */ - inline bool operator!= (const role& other) const - { - return this->position != other.position; - } - - /** - * @brief True if the role is hoisted - * @return bool Role appears separated from others in the member list - */ - bool is_hoisted() const; - /** - * @brief True if the role is mentionable - * @return bool Role is mentionable - */ - bool is_mentionable() const; - /** - * @brief True if the role is managed (belongs to a bot or application) - * @return bool True if the role is managed (introduced for a bot or other application by Discord) - */ - bool is_managed() const; - /** - * @brief True if has create instant invite permission - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the instant invite permission or is administrator. - */ - bool has_create_instant_invite() const; - /** - * @brief True if has the kick members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the kick members permission or is administrator. - */ - bool has_kick_members() const; - /** - * @brief True if has the ban members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the ban members permission or is administrator. - */ - bool has_ban_members() const; - /** - * @brief True if has the administrator permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the administrator permission or is administrator. - */ - bool has_administrator() const; - /** - * @brief True if has the manage channels permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage channels permission or is administrator. - */ - bool has_manage_channels() const; - /** - * @brief True if has the manage guild permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage guild permission or is administrator. - */ - bool has_manage_guild() const; - /** - * @brief True if has the add reactions permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the add reactions permission or is administrator. - */ - bool has_add_reactions() const; - /** - * @brief True if has the view audit log permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the view audit log permission or is administrator. - */ - bool has_view_audit_log() const; - /** - * @brief True if has the priority speaker permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the priority speaker permission or is administrator. - */ - bool has_priority_speaker() const; - /** - * @brief True if has the stream permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the stream permission or is administrator. - */ - bool has_stream() const; - /** - * @brief True if has the view channel permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the view channel permission or is administrator. - */ - bool has_view_channel() const; - /** - * @brief True if has the send messages permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the send messages permission or is administrator. - */ - bool has_send_messages() const; - /** - * @brief True if has the send TTS messages permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the send TTS messages permission or is administrator. - */ - bool has_send_tts_messages() const; - /** - * @brief True if has the manage messages permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage messages permission or is administrator. - */ - bool has_manage_messages() const; - /** - * @brief True if has the embed links permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the embed links permission or is administrator. - */ - bool has_embed_links() const; - /** - * @brief True if has the attach files permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the attach files permission or is administrator. - */ - bool has_attach_files() const; - /** - * @brief True if has the read message history permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the read message history permission or is administrator. - */ - bool has_read_message_history() const; - /** - * @brief True if has the mention \@everyone and \@here permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the mention \@everyone and \@here permission or is administrator. - */ - bool has_mention_everyone() const; - /** - * @brief True if has the use external emojis permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the use external emojis permission or is administrator. - */ - bool has_use_external_emojis() const; - /** - * @brief True if has the view guild insights permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the view guild insights permission or is administrator. - */ - bool has_view_guild_insights() const; - /** - * @brief True if has the connect voice permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the connect voice permission or is administrator. - */ - bool has_connect() const; - /** - * @brief True if has the speak permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the speak permission or is administrator. - */ - bool has_speak() const; - /** - * @brief True if has the mute members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the mute members permission or is administrator. - */ - bool has_mute_members() const; - /** - * @brief True if has the deafen members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the deafen members permission or is administrator. - */ - bool has_deafen_members() const; - /** - * @brief True if has the move members permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the move members permission or is administrator. - */ - bool has_move_members() const; - /** True if has use voice activity detection permission */ - bool has_use_vad() const; - /** - * @brief True if has the change nickname permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the change nickname permission or is administrator. - */ - bool has_change_nickname() const; - /** - * @brief True if has the manage nicknames permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage nicknames permission or is administrator. - */ - bool has_manage_nicknames() const; - /** - * @brief True if has the manage roles permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage roles permission or is administrator. - */ - bool has_manage_roles() const; - /** - * @brief True if has the manage webhooks permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage webhooks permission or is administrator. - */ - bool has_manage_webhooks() const; - /** - * @brief True if has the manage emojis and stickers permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage emojis and stickers permission or is administrator. - */ - bool has_manage_emojis_and_stickers() const; - /** - * @brief True if has the use application commands permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the use application commands permission or is administrator. - */ - bool has_use_application_commands() const; - /** - * @brief True if has the request to speak permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the request to speak permission or is administrator. - */ - bool has_request_to_speak() const; - /** - * @brief True if has the manage threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage threads permission or is administrator. - */ - bool has_manage_threads() const; - /** - * @brief True if has the create public threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the create public threads permission or is administrator. - */ - bool has_create_public_threads() const; - /** - * @brief True if has the create private threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the create private threads permission or is administrator. - */ - bool has_create_private_threads() const; - /** - * @brief True if has the use external stickers permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the use external stickers permission or is administrator. - */ - bool has_use_external_stickers() const; - /** - * @brief True if has the send messages in threads permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the send messages in threads permission or is administrator. - */ - bool has_send_messages_in_threads() const; - /** - * @brief True if has the start embedded activities permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the start embedded activities permission or is administrator. - */ - bool has_use_embedded_activities() const; - /** - * @brief True if has the manage events permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the manage events permission or is administrator. - */ - bool has_manage_events() const; - /** - * @brief True if has the moderate users permission. - * @note Having the administrator permission causes this method to always return true - * Channel specific overrides may apply to permissions. - * @return bool True if user has the moderate users permission or is administrator. - */ - bool has_moderate_members() const; - - /** - * @brief Get guild members who have this role - * @note This method requires user/members cache to be active - * @return members_container List of members who have this role - */ - members_container get_members() const; -}; - -/** - * @brief Application Role Connection Metadata Type - * - * @note Each metadata type offers a comparison operation that allows guilds to configure role requirements based on metadata values stored by the bot. Bots specify a `metadata value` for each user and guilds specify the required `guild's configured value` within the guild role settings. - */ -enum application_role_connection_metadata_type : uint8_t { - rc_integer_less_than_or_equal = 1, //!< The metadata value (integer) is less than or equal to the guild's configured value (integer) - rc_integer_greater_than_or_equal = 2, //!< The metadata value (integer) is greater than or equal to the guild's configured value (integer) - rc_integer_equal = 3, //!< The metadata value (integer) is equal to the guild's configured value (integer) - rc_integer_not_equal = 4, //!< The metadata value (integer) is not equal to the guild's configured value (integer) - rc_datetime_less_than_or_equal = 5, //!< The metadata value (ISO8601 string) is less than or equal to the guild's configured value (integer; days before current date) - rc_datetime_greater_than_or_equal = 6, //!< The metadata value (ISO8601 string) is greater than or equal to the guild's configured value (integer; days before current date) - rc_boolean_equal = 7, //!< The metadata value (integer) is equal to the guild's configured value (integer; 1) - rc_boolean_not_equal = 8, //!< The metadata value (integer) is not equal to the guild's configured value (integer; 1) -}; - -/** - * @brief Application Role Connection Metadata. Represents a role connection metadata for an dpp::application - */ -class DPP_EXPORT application_role_connection_metadata : public json_interface { -public: - application_role_connection_metadata_type type; //!< Type of metadata value - std::string key; //!< Dictionary key for the metadata field (must be `a-z`, `0-9`, or `_` characters; max 50 characters) - std::string name; //!< Name of the metadata field (max 100 characters) - std::map name_localizations; //!< Translations of the name - std::string description; //!< Description of the metadata field (max 200 characters) - std::map description_localizations; //!< Translations of the description - - /** - * Constructor - */ - application_role_connection_metadata(); - - virtual ~application_role_connection_metadata() = default; - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - application_role_connection_metadata& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** - * @brief The application role connection that an application has attached to a user. - */ -class DPP_EXPORT application_role_connection : public json_interface { -public: - std::string platform_name; //!< Optional: The vanity name of the platform a bot has connected (max 50 characters) - std::string platform_username; //!< Optional: The username on the platform a bot has connected (max 100 characters) - std::variant metadata; //!< Optional: Object mapping application role connection metadata keys to their stringified value (max 100 characters) for the user on the platform a bot has connected - - /** - * Constructor - */ - application_role_connection(); - - virtual ~application_role_connection() = default; - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - application_role_connection& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** A group of roles */ -typedef std::unordered_map role_map; - -/** A group of application_role_connection_metadata objects */ -typedef std::vector application_role_connection_metadata_list; - -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** Various flags related to dpp::role */ +enum role_flags : uint8_t { + r_hoist = 0b00000001, //!< Hoisted role + r_managed = 0b00000010, //!< Managed role (introduced by a bot or application) + r_mentionable = 0b00000100, //!< Mentionable with a ping + r_premium_subscriber = 0b00001000, //!< This is set for the role given to nitro +}; + +/** + * @brief Represents a role within a dpp::guild. + * Roles are combined via logical OR of the permission bitmasks, then channel-specific overrides + * can be applied on top, deny types apply a logic NOT to the bit mask, and allows apply a logical OR. + * @note Every guild has at least one role, called the 'everyone' role, which always has the same role + * ID as the guild's ID. This is the base permission set applied to all users where no other role or override + * applies, and is the starting value of the bit mask looped through to calculate channel permissions. + */ +class DPP_EXPORT role : public managed, public json_interface { +public: + /** + * @brief Role name + * Between 1 and 100 characters. + */ + std::string name; + /** + * @brief Guild ID + */ + snowflake guild_id; + /** + * @brief Role colour. + * A colour of 0 means no colour. If you want a black role, + * you must use the value 0x000001. + */ + uint32_t colour; + /** Role position */ + uint8_t position; + /** Role permissions bitmask values from dpp::permissions */ + permission permissions; + /** Role flags from dpp::role_flags */ + uint8_t flags; + /** Integration id if any (e.g. role is a bot's role created when it was invited) */ + snowflake integration_id; + /** Bot id if any (e.g. role is a bot's role created when it was invited) */ + snowflake bot_id; + /** The unicode emoji used for the role's icon, can be an empty string */ + std::string unicode_emoji; + /** The role icon hash, can be an empty string */ + utility::iconhash icon; + /** Image data for the role icon (if any) */ + std::string* image_data; + + /** + * @brief Construct a new role object + */ + role(); + + /** + * @brief Destroy the role object + */ + virtual ~role(); + + /** + * @brief Create a mentionable role. + * @param id The ID of the role. + * @return std::string The formatted mention of the role. + */ + static std::string get_mention(const snowflake& id); + + /** + * @brief Set the name of the role + * Maximum length: 100 + * Minimum length: 1 + * @param n Name to set + * @return role& reference to self + * @throw dpp::exception thrown if role length is less than 1 character + */ + role& set_name(const std::string& n); + + /** + * @brief Set the colour + * + * @param c Colour to set + * @note There is an americanised version of this method, role::set_color(). + * @return role& reference to self + */ + role& set_colour(uint32_t c); + + /** + * @brief Set the color + * + * @param c Colour to set + * @note This is an alias of role::set_colour for American spelling. + * @return role& reference to self + */ + role& set_color(uint32_t c); + + /** + * @brief Set the flags + * + * @param f Flags to set from dpp::role_flags + * @return role& reference to self + */ + role& set_flags(uint8_t f); + + /** + * @brief Set the integration id + * + * @param i Integration ID to set + * @return role& reference to self + */ + role& set_integration_id(snowflake i); + + /** + * @brief Set the bot id + * + * @param b Bot ID to set + * @return role& reference to self + */ + role& set_bot_id(snowflake b); + + /** + * @brief Set the guild id + * + * @param gid Guild ID to set + * @return role& reference to self + */ + role& set_guild_id(snowflake gid); + + /** + * @brief Fill this role from json. + * + * @param j The json data + * @return A reference to self + */ + role& fill_from_json(nlohmann::json* j); + + /** + * @brief Fill this role from json. + * + * @param guild_id the guild id to place in the json + * @param j The json data + * @return A reference to self + */ + role& fill_from_json(snowflake guild_id, nlohmann::json* j); + + /** + * @brief Build a json string from this object. + * + * @param with_id true if the ID is to be included in the json text + * @return The json of the role + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Get the mention/ping for the role + * + * @return std::string mention + */ + std::string get_mention() const; + + /** + * @brief Returns the role's icon if they have one, otherwise returns an empty string + * + * @param size The size of the icon in pixels. It can be any power of two between 16 and 4096. If not specified, the default sized icon is returned. + * @return std::string icon url or empty string + */ + std::string get_icon_url(uint16_t size = 0) const; + + /** + * @brief Load an image into the object as base64 + * + * @param image_blob Image binary data + * @param type Type of image + * @return emoji& Reference to self + */ + role& load_image(const std::string &image_blob, const image_type type); + + /** + * @brief Operator less than, used for checking if a role is below another. + * + * @param lhs first role to compare + * @param rhs second role to compare + * @return true if lhs is less than rhs + */ + friend inline bool operator< (const role& lhs, const role& rhs) + { + return lhs.position < rhs.position; + } + + /** + * @brief Operator greater than, used for checking if a role is above another. + * + * @param lhs first role to compare + * @param rhs second role to compare + * @return true if lhs is greater than rhs + */ + friend inline bool operator> (const role& lhs, const role& rhs) + { + return lhs.position > rhs.position; + } + + /** + * @brief Operator equals, used for checking if a role is ranked equal to another. + * + * @param other role to compare + * @return true if is equal to other + */ + inline bool operator== (const role& other) const + { + return this->position == other.position; + } + + /** + * @brief Operator not equals, used for checking if a role is ranked equal to another. + * + * @param other role to compare + * @return true if is not equal to other + */ + inline bool operator!= (const role& other) const + { + return this->position != other.position; + } + + /** + * @brief True if the role is hoisted + * @return bool Role appears separated from others in the member list + */ + bool is_hoisted() const; + /** + * @brief True if the role is mentionable + * @return bool Role is mentionable + */ + bool is_mentionable() const; + /** + * @brief True if the role is managed (belongs to a bot or application) + * @return bool True if the role is managed (introduced for a bot or other application by Discord) + */ + bool is_managed() const; + /** + * @brief True if has create instant invite permission + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the instant invite permission or is administrator. + */ + bool has_create_instant_invite() const; + /** + * @brief True if has the kick members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the kick members permission or is administrator. + */ + bool has_kick_members() const; + /** + * @brief True if has the ban members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the ban members permission or is administrator. + */ + bool has_ban_members() const; + /** + * @brief True if has the administrator permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the administrator permission or is administrator. + */ + bool has_administrator() const; + /** + * @brief True if has the manage channels permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage channels permission or is administrator. + */ + bool has_manage_channels() const; + /** + * @brief True if has the manage guild permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage guild permission or is administrator. + */ + bool has_manage_guild() const; + /** + * @brief True if has the add reactions permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the add reactions permission or is administrator. + */ + bool has_add_reactions() const; + /** + * @brief True if has the view audit log permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the view audit log permission or is administrator. + */ + bool has_view_audit_log() const; + /** + * @brief True if has the priority speaker permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the priority speaker permission or is administrator. + */ + bool has_priority_speaker() const; + /** + * @brief True if has the stream permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the stream permission or is administrator. + */ + bool has_stream() const; + /** + * @brief True if has the view channel permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the view channel permission or is administrator. + */ + bool has_view_channel() const; + /** + * @brief True if has the send messages permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the send messages permission or is administrator. + */ + bool has_send_messages() const; + /** + * @brief True if has the send TTS messages permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the send TTS messages permission or is administrator. + */ + bool has_send_tts_messages() const; + /** + * @brief True if has the manage messages permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage messages permission or is administrator. + */ + bool has_manage_messages() const; + /** + * @brief True if has the embed links permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the embed links permission or is administrator. + */ + bool has_embed_links() const; + /** + * @brief True if has the attach files permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the attach files permission or is administrator. + */ + bool has_attach_files() const; + /** + * @brief True if has the read message history permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the read message history permission or is administrator. + */ + bool has_read_message_history() const; + /** + * @brief True if has the mention \@everyone and \@here permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the mention \@everyone and \@here permission or is administrator. + */ + bool has_mention_everyone() const; + /** + * @brief True if has the use external emojis permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the use external emojis permission or is administrator. + */ + bool has_use_external_emojis() const; + /** + * @brief True if has the view guild insights permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the view guild insights permission or is administrator. + */ + bool has_view_guild_insights() const; + /** + * @brief True if has the connect voice permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the connect voice permission or is administrator. + */ + bool has_connect() const; + /** + * @brief True if has the speak permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the speak permission or is administrator. + */ + bool has_speak() const; + /** + * @brief True if has the mute members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the mute members permission or is administrator. + */ + bool has_mute_members() const; + /** + * @brief True if has the deafen members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the deafen members permission or is administrator. + */ + bool has_deafen_members() const; + /** + * @brief True if has the move members permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the move members permission or is administrator. + */ + bool has_move_members() const; + /** True if has use voice activity detection permission */ + bool has_use_vad() const; + /** + * @brief True if has the change nickname permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the change nickname permission or is administrator. + */ + bool has_change_nickname() const; + /** + * @brief True if has the manage nicknames permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage nicknames permission or is administrator. + */ + bool has_manage_nicknames() const; + /** + * @brief True if has the manage roles permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage roles permission or is administrator. + */ + bool has_manage_roles() const; + /** + * @brief True if has the manage webhooks permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage webhooks permission or is administrator. + */ + bool has_manage_webhooks() const; + /** + * @brief True if has the manage emojis and stickers permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage emojis and stickers permission or is administrator. + */ + bool has_manage_emojis_and_stickers() const; + /** + * @brief True if has the use application commands permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the use application commands permission or is administrator. + */ + bool has_use_application_commands() const; + /** + * @brief True if has the request to speak permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the request to speak permission or is administrator. + */ + bool has_request_to_speak() const; + /** + * @brief True if has the manage threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage threads permission or is administrator. + */ + bool has_manage_threads() const; + /** + * @brief True if has the create public threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the create public threads permission or is administrator. + */ + bool has_create_public_threads() const; + /** + * @brief True if has the create private threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the create private threads permission or is administrator. + */ + bool has_create_private_threads() const; + /** + * @brief True if has the use external stickers permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the use external stickers permission or is administrator. + */ + bool has_use_external_stickers() const; + /** + * @brief True if has the send messages in threads permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the send messages in threads permission or is administrator. + */ + bool has_send_messages_in_threads() const; + /** + * @brief True if has the start embedded activities permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the start embedded activities permission or is administrator. + */ + bool has_use_embedded_activities() const; + /** + * @brief True if has the manage events permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the manage events permission or is administrator. + */ + bool has_manage_events() const; + /** + * @brief True if has the moderate users permission. + * @note Having the administrator permission causes this method to always return true + * Channel specific overrides may apply to permissions. + * @return bool True if user has the moderate users permission or is administrator. + */ + bool has_moderate_members() const; + + /** + * @brief Get guild members who have this role + * @note This method requires user/members cache to be active + * @return members_container List of members who have this role + */ + members_container get_members() const; +}; + +/** + * @brief Application Role Connection Metadata Type + * + * @note Each metadata type offers a comparison operation that allows guilds to configure role requirements based on metadata values stored by the bot. Bots specify a `metadata value` for each user and guilds specify the required `guild's configured value` within the guild role settings. + */ +enum application_role_connection_metadata_type : uint8_t { + rc_integer_less_than_or_equal = 1, //!< The metadata value (integer) is less than or equal to the guild's configured value (integer) + rc_integer_greater_than_or_equal = 2, //!< The metadata value (integer) is greater than or equal to the guild's configured value (integer) + rc_integer_equal = 3, //!< The metadata value (integer) is equal to the guild's configured value (integer) + rc_integer_not_equal = 4, //!< The metadata value (integer) is not equal to the guild's configured value (integer) + rc_datetime_less_than_or_equal = 5, //!< The metadata value (ISO8601 string) is less than or equal to the guild's configured value (integer; days before current date) + rc_datetime_greater_than_or_equal = 6, //!< The metadata value (ISO8601 string) is greater than or equal to the guild's configured value (integer; days before current date) + rc_boolean_equal = 7, //!< The metadata value (integer) is equal to the guild's configured value (integer; 1) + rc_boolean_not_equal = 8, //!< The metadata value (integer) is not equal to the guild's configured value (integer; 1) +}; + +/** + * @brief Application Role Connection Metadata. Represents a role connection metadata for an dpp::application + */ +class DPP_EXPORT application_role_connection_metadata : public json_interface { +public: + application_role_connection_metadata_type type; //!< Type of metadata value + std::string key; //!< Dictionary key for the metadata field (must be `a-z`, `0-9`, or `_` characters; max 50 characters) + std::string name; //!< Name of the metadata field (max 100 characters) + std::map name_localizations; //!< Translations of the name + std::string description; //!< Description of the metadata field (max 200 characters) + std::map description_localizations; //!< Translations of the description + + /** + * Constructor + */ + application_role_connection_metadata(); + + virtual ~application_role_connection_metadata() = default; + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + application_role_connection_metadata& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** + * @brief The application role connection that an application has attached to a user. + */ +class DPP_EXPORT application_role_connection : public json_interface { +public: + std::string platform_name; //!< Optional: The vanity name of the platform a bot has connected (max 50 characters) + std::string platform_username; //!< Optional: The username on the platform a bot has connected (max 100 characters) + std::variant metadata; //!< Optional: Object mapping application role connection metadata keys to their stringified value (max 100 characters) for the user on the platform a bot has connected + + /** + * Constructor + */ + application_role_connection(); + + virtual ~application_role_connection() = default; + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + application_role_connection& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** A group of roles */ +typedef std::unordered_map role_map; + +/** A group of application_role_connection_metadata objects */ +typedef std::vector application_role_connection_metadata_list; + +}; + diff --git a/3rdParty/dpp/scheduled_event.h b/3rdParty/dpp/scheduled_event.h index ceec00d79f..5e8a63ec97 100644 --- a/3rdParty/dpp/scheduled_event.h +++ b/3rdParty/dpp/scheduled_event.h @@ -1,224 +1,224 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the privacy of an event - */ -enum event_privacy_level : uint8_t { - /// The event is visible to only guild members. - ep_guild_only = 2 -}; - -/** - * @brief Event entity types - */ -enum event_entity_type : uint8_t { - /// A stage instance - eet_stage_instance = 1, - /// A voice channel - eet_voice = 2, - /// External to discord, or a text channel etc - eet_external = 3 -}; - -/** - * @brief Event status types - */ -enum event_status : uint8_t { - /// Scheduled - es_scheduled = 1, - /// Active now - es_active = 2, - /// Completed - es_completed = 3, - /// Cancelled - es_cancelled = 4 -}; - -/** - * @brief Entities for the event - */ -struct DPP_EXPORT event_entities { - /// location of the event - std::string location; -}; - -/** - * @brief Represents a guild member/user who has registered interest in an event - * - */ -struct DPP_EXPORT event_member { - /** - * @brief Event ID associated with - */ - snowflake guild_scheduled_event_id; - /** - * @brief User details of associated user - * - */ - dpp::user user; - /** - * @brief Member details of user on the associated guild - */ - dpp::guild_member member; -}; - -/** - * @brief A scheduled event - */ -struct DPP_EXPORT scheduled_event : public managed, public json_interface { - snowflake guild_id; //!< the guild id which the scheduled event belongs to - snowflake channel_id; //!< the channel id in which the scheduled event will be hosted, or null if scheduled entity type is EXTERNAL (may be empty) - snowflake creator_id; //!< Optional: the id of the user that created the scheduled event - std::string name; //!< the name of the scheduled event - std::string description; //!< Optional: the description of the scheduled event (1-1000 characters) - std::string image; //!< the image of the scheduled event (may be empty) - time_t scheduled_start_time; //!< the time the scheduled event will start - time_t scheduled_end_time; //!< the time the scheduled event will end, or null if the event does not have a scheduled time to end (may be empty) - event_privacy_level privacy_level; //!< the privacy level of the scheduled event - event_status status; //!< the status of the scheduled event - event_entity_type entity_type; //!< the type of hosting entity associated with a scheduled event, e.g. voice channel or stage channel - snowflake entity_id; //!< any additional id of the hosting entity associated with event, e.g. stage instance id) (may be empty) - event_entities entity_metadata; //!< the entity metadata for the scheduled event (may be empty) - user creator; //!< Optional: the creator of the scheduled event - uint32_t user_count; //!< Optional: the number of users subscribed to the scheduled event - - /** - * @brief Create a scheduled_event object - */ - scheduled_event(); - - /** - * @brief Destroy the scheduled_event object - */ - ~scheduled_event() = default; - - /** - * @brief Set the name of the event - * Minimum length: 1, Maximum length: 100 - * @param n event name - * @return scheduled_event& reference to self - * @throw dpp::length_error if length < 1 - */ - scheduled_event& set_name(const std::string& n); - - /** - * @brief Set the description of the event - * Minimum length: 1 (if set), Maximum length: 100 - * @param d event description - * @return scheduled_event& reference to self - * @throw dpp::length_error if length < 1 - */ - scheduled_event& set_description(const std::string& d); - - /** - * @brief Clear the description of the event - * @return scheduled_event& reference to self - */ - scheduled_event& clear_description(); - - /** - * @brief Set the location of the event. - * Minimum length: 1, Maximum length: 1000 - * @note Clears channel_id - * @param l event location - * @return scheduled_event& reference to self - * @throw dpp::length_error if length < 1 - */ - scheduled_event& set_location(const std::string& l); - - /** - * @brief Set the voice channel id of the event - * @note clears location - * @param c channel ID - * @return scheduled_event& reference to self - */ - scheduled_event& set_channel_id(snowflake c); - - /** - * @brief Set the creator id of the event - * @param c creator user ID - * @return scheduled_event& reference to self - */ - scheduled_event& set_creator_id(snowflake c); - - /** - * @brief Set the status of the event - * @param s status to set - * @return scheduled_event& reference to self - * @throw dpp::logic_exception if status change is not valid - */ - scheduled_event& set_status(event_status s); - - /** - * @brief Set the start time of the event - * @param t starting time - * @return scheduled_event& reference to self - * @throw dpp::length_error if time is before now - */ - scheduled_event& set_start_time(time_t t); - - /** - * @brief Set the end time of the event - * @param t ending time - * @return scheduled_event& reference to self - * @throw dpp::length_error if time is before now - */ - scheduled_event& set_end_time(time_t t); - - /** - * @brief Serialise a scheduled_event object from json - * - * @return scheduled_event& a reference to self - */ - scheduled_event& fill_from_json(const nlohmann::json* j); - - /** - * @brief Build json for this object - * @param with_id Include id field in json - * - * @return std::string Dumped json of this object - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** - * @brief A group of scheduled events - */ -typedef std::unordered_map scheduled_event_map; - -/** - * @brief A group of scheduled event members - */ -typedef std::unordered_map event_member_map; - - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the privacy of an event + */ +enum event_privacy_level : uint8_t { + /// The event is visible to only guild members. + ep_guild_only = 2 +}; + +/** + * @brief Event entity types + */ +enum event_entity_type : uint8_t { + /// A stage instance + eet_stage_instance = 1, + /// A voice channel + eet_voice = 2, + /// External to discord, or a text channel etc + eet_external = 3 +}; + +/** + * @brief Event status types + */ +enum event_status : uint8_t { + /// Scheduled + es_scheduled = 1, + /// Active now + es_active = 2, + /// Completed + es_completed = 3, + /// Cancelled + es_cancelled = 4 +}; + +/** + * @brief Entities for the event + */ +struct DPP_EXPORT event_entities { + /// location of the event + std::string location; +}; + +/** + * @brief Represents a guild member/user who has registered interest in an event + * + */ +struct DPP_EXPORT event_member { + /** + * @brief Event ID associated with + */ + snowflake guild_scheduled_event_id; + /** + * @brief User details of associated user + * + */ + dpp::user user; + /** + * @brief Member details of user on the associated guild + */ + dpp::guild_member member; +}; + +/** + * @brief A scheduled event + */ +struct DPP_EXPORT scheduled_event : public managed, public json_interface { + snowflake guild_id; //!< the guild id which the scheduled event belongs to + snowflake channel_id; //!< the channel id in which the scheduled event will be hosted, or null if scheduled entity type is EXTERNAL (may be empty) + snowflake creator_id; //!< Optional: the id of the user that created the scheduled event + std::string name; //!< the name of the scheduled event + std::string description; //!< Optional: the description of the scheduled event (1-1000 characters) + std::string image; //!< the image of the scheduled event (may be empty) + time_t scheduled_start_time; //!< the time the scheduled event will start + time_t scheduled_end_time; //!< the time the scheduled event will end, or null if the event does not have a scheduled time to end (may be empty) + event_privacy_level privacy_level; //!< the privacy level of the scheduled event + event_status status; //!< the status of the scheduled event + event_entity_type entity_type; //!< the type of hosting entity associated with a scheduled event, e.g. voice channel or stage channel + snowflake entity_id; //!< any additional id of the hosting entity associated with event, e.g. stage instance id) (may be empty) + event_entities entity_metadata; //!< the entity metadata for the scheduled event (may be empty) + user creator; //!< Optional: the creator of the scheduled event + uint32_t user_count; //!< Optional: the number of users subscribed to the scheduled event + + /** + * @brief Create a scheduled_event object + */ + scheduled_event(); + + /** + * @brief Destroy the scheduled_event object + */ + ~scheduled_event() = default; + + /** + * @brief Set the name of the event + * Minimum length: 1, Maximum length: 100 + * @param n event name + * @return scheduled_event& reference to self + * @throw dpp::length_error if length < 1 + */ + scheduled_event& set_name(const std::string& n); + + /** + * @brief Set the description of the event + * Minimum length: 1 (if set), Maximum length: 100 + * @param d event description + * @return scheduled_event& reference to self + * @throw dpp::length_error if length < 1 + */ + scheduled_event& set_description(const std::string& d); + + /** + * @brief Clear the description of the event + * @return scheduled_event& reference to self + */ + scheduled_event& clear_description(); + + /** + * @brief Set the location of the event. + * Minimum length: 1, Maximum length: 1000 + * @note Clears channel_id + * @param l event location + * @return scheduled_event& reference to self + * @throw dpp::length_error if length < 1 + */ + scheduled_event& set_location(const std::string& l); + + /** + * @brief Set the voice channel id of the event + * @note clears location + * @param c channel ID + * @return scheduled_event& reference to self + */ + scheduled_event& set_channel_id(snowflake c); + + /** + * @brief Set the creator id of the event + * @param c creator user ID + * @return scheduled_event& reference to self + */ + scheduled_event& set_creator_id(snowflake c); + + /** + * @brief Set the status of the event + * @param s status to set + * @return scheduled_event& reference to self + * @throw dpp::logic_exception if status change is not valid + */ + scheduled_event& set_status(event_status s); + + /** + * @brief Set the start time of the event + * @param t starting time + * @return scheduled_event& reference to self + * @throw dpp::length_error if time is before now + */ + scheduled_event& set_start_time(time_t t); + + /** + * @brief Set the end time of the event + * @param t ending time + * @return scheduled_event& reference to self + * @throw dpp::length_error if time is before now + */ + scheduled_event& set_end_time(time_t t); + + /** + * @brief Serialise a scheduled_event object from json + * + * @return scheduled_event& a reference to self + */ + scheduled_event& fill_from_json(const nlohmann::json* j); + + /** + * @brief Build json for this object + * @param with_id Include id field in json + * + * @return std::string Dumped json of this object + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** + * @brief A group of scheduled events + */ +typedef std::unordered_map scheduled_event_map; + +/** + * @brief A group of scheduled event members + */ +typedef std::unordered_map event_member_map; + + +}; diff --git a/3rdParty/dpp/snowflake.h b/3rdParty/dpp/snowflake.h index 033b1d10f5..2eb0205d1c 100644 --- a/3rdParty/dpp/snowflake.h +++ b/3rdParty/dpp/snowflake.h @@ -1,196 +1,196 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -/** - * @brief The main namespace for D++ functions. classes and types - */ -namespace dpp { - -/** @brief A container for a 64 bit unsigned value representing many things on discord. - * This value is known in distributed computing as a snowflake value. - * - * Snowflakes are: - * - * - Performant (very fast to generate at source and to compare in code) - * - Uncoordinated (allowing high availability across clusters, data centres etc) - * - Time ordered (newer snowflakes have higher IDs) - * - Directly Sortable (due to time ordering) - * - Compact (64 bit numbers, not 128 bit, or string) - * - * An identical format of snowflake is used by Twitter, Instagram and several other platforms. - * - * @see https://en.wikipedia.org/wiki/Snowflake_ID - * @see https://github.com/twitter-archive/snowflake/tree/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231 - */ -class DPP_EXPORT snowflake final { - friend struct std::hash; -protected: - /** - * @brief The snowflake value - */ - uint64_t value; - -public: - /** - * @brief Construct a snowflake object - * @param value A snowflake value - */ - snowflake(const uint64_t& value); - - /** - * @brief Construct a snowflake object - * @param value A snowflake value - */ - snowflake(const std::string& string_value); - - /** - * @brief Construct a snowflake object - */ - snowflake(); - - /** - * @brief Destroy the snowflake object - */ - ~snowflake() = default; - - /** - * @brief For acting like an integer - * @return The snowflake value - */ - operator uint64_t() const; - - /** - * @brief Returns true if the snowflake holds an empty value (is 0) - * - * @return true if empty (zero) - */ - inline bool empty() const - { - return value == 0; - } - - /** - * @brief Operator less than, used for maps/unordered maps - * when the snowflake is a key value. - * - * @param lhs fist snowflake to compare - * @param rhs second snowflake to compare - * @return true if lhs is less than rhs - */ - friend inline bool operator< (const snowflake& lhs, const snowflake& rhs) - { - return lhs.value < rhs.value; - } - - /** - * @brief Assign from std::string - * - * @param snowflake_val string to assign from. - */ - snowflake& operator=(const std::string &snowflake_val); - - /** - * @brief Assign from std::string - * - * @param snowflake_val value to assign from. - */ - snowflake& operator=(const uint64_t &snowflake_val); - - /** - * @brief Check if one snowflake value is equal to another - * - * @param other other snowflake to compare - * @return True if the snowflake objects match - */ - bool operator==(const snowflake& other) const; - - /** - * @brief Check if one snowflake value is equal to a uint64_t - * - * @param other other snowflake to compare - * @return True if the snowflake objects match - */ - bool operator==(const uint64_t& other) const; - - /** - * @brief For acting like an integer - * @return A reference to the snowflake value - */ - operator uint64_t &(); - - /** - * @brief For building json - * @return The snowflake value as a string - */ - operator nlohmann::json() const; - - /** - * @brief Get the creation time of this snowflake according to Discord. - * - * @return double creation time inferred from the snowflake ID. - * The minimum possible value is the first second of 2015. - */ - double get_creation_time() const; - - /** - * @brief Get the worker id that produced this snowflake value - * - * @return uint8_t worker id - */ - uint8_t get_worker_id() const; - - /** - * @brief Get the process id that produced this snowflake value - * - * @return uint8_t process id - */ - uint8_t get_process_id() const; - - /** - * @brief Get the increment, which is incremented for every snowflake - * created over the one millisecond resolution in the timestamp. - * - * @return uint64_t millisecond increment - */ - uint16_t get_increment() const; -}; - -}; - -template<> -struct std::hash -{ - /** - * @brief Hashing function for dpp::slowflake - * Used by std::unordered_map. This just calls std::hash. - * - * @param s Snowflake value to hash - * @return std::size_t hash value - */ - std::size_t operator()(dpp::snowflake const& s) const noexcept { - return std::hash{}(s.value); - } -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +/** + * @brief The main namespace for D++ functions. classes and types + */ +namespace dpp { + +/** @brief A container for a 64 bit unsigned value representing many things on discord. + * This value is known in distributed computing as a snowflake value. + * + * Snowflakes are: + * + * - Performant (very fast to generate at source and to compare in code) + * - Uncoordinated (allowing high availability across clusters, data centres etc) + * - Time ordered (newer snowflakes have higher IDs) + * - Directly Sortable (due to time ordering) + * - Compact (64 bit numbers, not 128 bit, or string) + * + * An identical format of snowflake is used by Twitter, Instagram and several other platforms. + * + * @see https://en.wikipedia.org/wiki/Snowflake_ID + * @see https://github.com/twitter-archive/snowflake/tree/b3f6a3c6ca8e1b6847baa6ff42bf72201e2c2231 + */ +class DPP_EXPORT snowflake final { + friend struct std::hash; +protected: + /** + * @brief The snowflake value + */ + uint64_t value; + +public: + /** + * @brief Construct a snowflake object + * @param value A snowflake value + */ + snowflake(const uint64_t& value); + + /** + * @brief Construct a snowflake object + * @param value A snowflake value + */ + snowflake(const std::string& string_value); + + /** + * @brief Construct a snowflake object + */ + snowflake(); + + /** + * @brief Destroy the snowflake object + */ + ~snowflake() = default; + + /** + * @brief For acting like an integer + * @return The snowflake value + */ + operator uint64_t() const; + + /** + * @brief Returns true if the snowflake holds an empty value (is 0) + * + * @return true if empty (zero) + */ + inline bool empty() const + { + return value == 0; + } + + /** + * @brief Operator less than, used for maps/unordered maps + * when the snowflake is a key value. + * + * @param lhs fist snowflake to compare + * @param rhs second snowflake to compare + * @return true if lhs is less than rhs + */ + friend inline bool operator< (const snowflake& lhs, const snowflake& rhs) + { + return lhs.value < rhs.value; + } + + /** + * @brief Assign from std::string + * + * @param snowflake_val string to assign from. + */ + snowflake& operator=(const std::string &snowflake_val); + + /** + * @brief Assign from std::string + * + * @param snowflake_val value to assign from. + */ + snowflake& operator=(const uint64_t &snowflake_val); + + /** + * @brief Check if one snowflake value is equal to another + * + * @param other other snowflake to compare + * @return True if the snowflake objects match + */ + bool operator==(const snowflake& other) const; + + /** + * @brief Check if one snowflake value is equal to a uint64_t + * + * @param other other snowflake to compare + * @return True if the snowflake objects match + */ + bool operator==(const uint64_t& other) const; + + /** + * @brief For acting like an integer + * @return A reference to the snowflake value + */ + operator uint64_t &(); + + /** + * @brief For building json + * @return The snowflake value as a string + */ + operator nlohmann::json() const; + + /** + * @brief Get the creation time of this snowflake according to Discord. + * + * @return double creation time inferred from the snowflake ID. + * The minimum possible value is the first second of 2015. + */ + double get_creation_time() const; + + /** + * @brief Get the worker id that produced this snowflake value + * + * @return uint8_t worker id + */ + uint8_t get_worker_id() const; + + /** + * @brief Get the process id that produced this snowflake value + * + * @return uint8_t process id + */ + uint8_t get_process_id() const; + + /** + * @brief Get the increment, which is incremented for every snowflake + * created over the one millisecond resolution in the timestamp. + * + * @return uint64_t millisecond increment + */ + uint16_t get_increment() const; +}; + +}; + +template<> +struct std::hash +{ + /** + * @brief Hashing function for dpp::slowflake + * Used by std::unordered_map. This just calls std::hash. + * + * @param s Snowflake value to hash + * @return std::size_t hash value + */ + std::size_t operator()(dpp::snowflake const& s) const noexcept { + return std::hash{}(s.value); + } +}; diff --git a/3rdParty/dpp/socket.h b/3rdParty/dpp/socket.h index 21be6da1b7..7f1ccc3fc1 100644 --- a/3rdParty/dpp/socket.h +++ b/3rdParty/dpp/socket.h @@ -1,30 +1,30 @@ -#pragma once - -#ifndef _WIN32 -#ifndef SOCKET -#define SOCKET int -#endif -#endif - -namespace dpp -{ - /** - * @brief Represents a socket file descriptor. - * This is used to ensure parity between windows and unix-like systems. - */ - typedef SOCKET socket; -} - -#ifndef SOCKET_ERROR -/** - * @brief Represents a socket in error state - */ -#define SOCKET_ERROR -1 -#endif - -#ifndef INVALID_SOCKET -/** - * @brief Represents a socket which is not yet assigned - */ -#define INVALID_SOCKET ~0 +#pragma once + +#ifndef _WIN32 +#ifndef SOCKET +#define SOCKET int +#endif +#endif + +namespace dpp +{ + /** + * @brief Represents a socket file descriptor. + * This is used to ensure parity between windows and unix-like systems. + */ + typedef SOCKET socket; +} + +#ifndef SOCKET_ERROR +/** + * @brief Represents a socket in error state + */ +#define SOCKET_ERROR -1 +#endif + +#ifndef INVALID_SOCKET +/** + * @brief Represents a socket which is not yet assigned + */ +#define INVALID_SOCKET ~0 #endif \ No newline at end of file diff --git a/3rdParty/dpp/sslclient.h b/3rdParty/dpp/sslclient.h index 8d07048a5f..daf4a2b1dc 100644 --- a/3rdParty/dpp/sslclient.h +++ b/3rdParty/dpp/sslclient.h @@ -1,252 +1,252 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief This is an opaque class containing openssl library specific structures. - * We define it this way so that the public facing D++ library doesn't require - * the openssl headers be available to build against it. - */ -class openssl_connection; - -/** - * @brief A callback for socket status - */ -typedef std::function socket_callback_t; - -/** - * @brief A socket notification callback - */ -typedef std::function socket_notification_t; - -/** - * @brief Close a socket - * - * @param sfd Socket to close - * @return false on error, true on success - */ -bool close_socket(dpp::socket sfd); - -/** - * @brief Set a socket to blocking or non-blocking IO - * - * @param sockfd socket to act upon - * @return false on error, true on success - */ -bool set_nonblocking(dpp::socket sockfd, bool non_blocking); - -/** - * @brief Implements a simple non-blocking SSL stream client. - * - * @note although the design is non-blocking the run() method will - * execute in an infinite loop until the socket disconnects. This is intended - * to be run within a std::thread. - */ -class DPP_EXPORT ssl_client -{ -protected: - /** - * @brief Input buffer received from socket - */ - std::string buffer; - - /** - * @brief Output buffer for sending to socket - */ - std::string obuffer; - - /** - * @brief True if in nonblocking mode. The socket switches to nonblocking mode - * once ReadLoop is called. - */ - bool nonblocking; - - /** - * @brief Raw file descriptor of connection - */ - dpp::socket sfd; - - /** - * @brief Openssl opaque contexts - */ - openssl_connection* ssl; - - /** - * @brief SSL cipher in use - */ - std::string cipher; - - /** - * @brief For timers - */ - time_t last_tick; - - /** - * @brief Hostname connected to - */ - std::string hostname; - - /** - * @brief Port connected to - */ - std::string port; - - /** - * @brief Bytes out - */ - uint64_t bytes_out; - - /** - * @brief Bytes in - */ - uint64_t bytes_in; - - /** - * @brief True for a plain text connection - */ - bool plaintext; - - /** - * @brief True if we are establishing a new connection, false if otherwise. - */ - bool make_new; - - - /** - * @brief Called every second - */ - virtual void one_second_timer(); - - /** - * @brief Start SSL connection and connect to TCP endpoint - * @throw dpp::exception Failed to initialise connection - */ - virtual void connect(); -public: - /** - * @brief Get the bytes out objectGet total bytes sent - * @return uint64_t bytes sent - */ - uint64_t get_bytes_out(); - - /** - * @brief Get total bytes received - * @return uint64_t bytes received - */ - uint64_t get_bytes_in(); - - /** - * @brief Get SSL cipher name - * @return std::string ssl cipher name - */ - std::string get_cipher(); - - /** - * @brief Attaching an additional file descriptor to this function will send notifications when there is data to read. - * - * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! - * Returning -1 means that you don't want to be notified. - */ - socket_callback_t custom_readable_fd; - - /** - * @brief Attaching an additional file descriptor to this function will send notifications when you are able to write - * to the socket. - * - * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! You should toggle this - * to -1 when you do not have anything to write otherwise it'll keep triggering repeatedly (it is level triggered). - */ - socket_callback_t custom_writeable_fd; - - /** - * @brief This event will be called when you can read from the custom fd - */ - socket_notification_t custom_readable_ready; - - /** - * @brief This event will be called when you can write to a custom fd - */ - socket_notification_t custom_writeable_ready; - - /** - * @brief True if we are keeping the connection alive after it has finished - */ - bool keepalive; - - /** - * @brief Connect to a specified host and port. Throws std::runtime_error on fatal error. - * @param _hostname The hostname to connect to - * @param _port the Port number to connect to - * @param plaintext_downgrade Set to true to connect using plaintext only, without initialising SSL. - * @param reuse Attempt to reuse previous connections for this hostname and port, if available - * Note that no Discord endpoints will function when downgraded. This option is provided only for - * connection to non-Discord addresses such as within dpp::cluster::request(). - * @throw dpp::exception Failed to initialise connection - */ - ssl_client(const std::string &_hostname, const std::string &_port = "443", bool plaintext_downgrade = false, bool reuse = false); - - /** - * @brief Nonblocking I/O loop - * @throw std::exception Any std::exception (or derivative) thrown from read_loop() causes reconnection of the shard - */ - void read_loop(); - - /** - * @brief Destroy the ssl_client object - */ - virtual ~ssl_client(); - - /** - * @brief Handle input from the input buffer. This function will be called until - * all data in the buffer has been processed and the buffer is empty. - * @param buffer the buffer content. Will be modified removing any processed front elements - * @return bool True if the socket should remain connected - */ - virtual bool handle_buffer(std::string &buffer); - - /** - * @brief Write to the output buffer. - * @param data Data to be written to the buffer - * @note The data may not be written immediately and may be written at a later time to the socket. - */ - virtual void write(const std::string &data); - - /** - * @brief Close socket connection - */ - virtual void close(); - - /** - * @brief Log a message - * @param severity severity of log message - * @param msg Log message to send - */ - virtual void log(dpp::loglevel severity, const std::string &msg) const; -}; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief This is an opaque class containing openssl library specific structures. + * We define it this way so that the public facing D++ library doesn't require + * the openssl headers be available to build against it. + */ +class openssl_connection; + +/** + * @brief A callback for socket status + */ +typedef std::function socket_callback_t; + +/** + * @brief A socket notification callback + */ +typedef std::function socket_notification_t; + +/** + * @brief Close a socket + * + * @param sfd Socket to close + * @return false on error, true on success + */ +bool close_socket(dpp::socket sfd); + +/** + * @brief Set a socket to blocking or non-blocking IO + * + * @param sockfd socket to act upon + * @return false on error, true on success + */ +bool set_nonblocking(dpp::socket sockfd, bool non_blocking); + +/** + * @brief Implements a simple non-blocking SSL stream client. + * + * @note although the design is non-blocking the run() method will + * execute in an infinite loop until the socket disconnects. This is intended + * to be run within a std::thread. + */ +class DPP_EXPORT ssl_client +{ +protected: + /** + * @brief Input buffer received from socket + */ + std::string buffer; + + /** + * @brief Output buffer for sending to socket + */ + std::string obuffer; + + /** + * @brief True if in nonblocking mode. The socket switches to nonblocking mode + * once ReadLoop is called. + */ + bool nonblocking; + + /** + * @brief Raw file descriptor of connection + */ + dpp::socket sfd; + + /** + * @brief Openssl opaque contexts + */ + openssl_connection* ssl; + + /** + * @brief SSL cipher in use + */ + std::string cipher; + + /** + * @brief For timers + */ + time_t last_tick; + + /** + * @brief Hostname connected to + */ + std::string hostname; + + /** + * @brief Port connected to + */ + std::string port; + + /** + * @brief Bytes out + */ + uint64_t bytes_out; + + /** + * @brief Bytes in + */ + uint64_t bytes_in; + + /** + * @brief True for a plain text connection + */ + bool plaintext; + + /** + * @brief True if we are establishing a new connection, false if otherwise. + */ + bool make_new; + + + /** + * @brief Called every second + */ + virtual void one_second_timer(); + + /** + * @brief Start SSL connection and connect to TCP endpoint + * @throw dpp::exception Failed to initialise connection + */ + virtual void connect(); +public: + /** + * @brief Get the bytes out objectGet total bytes sent + * @return uint64_t bytes sent + */ + uint64_t get_bytes_out(); + + /** + * @brief Get total bytes received + * @return uint64_t bytes received + */ + uint64_t get_bytes_in(); + + /** + * @brief Get SSL cipher name + * @return std::string ssl cipher name + */ + std::string get_cipher(); + + /** + * @brief Attaching an additional file descriptor to this function will send notifications when there is data to read. + * + * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! + * Returning -1 means that you don't want to be notified. + */ + socket_callback_t custom_readable_fd; + + /** + * @brief Attaching an additional file descriptor to this function will send notifications when you are able to write + * to the socket. + * + * NOTE: Only hook this if you NEED it as it can increase CPU usage of the thread! You should toggle this + * to -1 when you do not have anything to write otherwise it'll keep triggering repeatedly (it is level triggered). + */ + socket_callback_t custom_writeable_fd; + + /** + * @brief This event will be called when you can read from the custom fd + */ + socket_notification_t custom_readable_ready; + + /** + * @brief This event will be called when you can write to a custom fd + */ + socket_notification_t custom_writeable_ready; + + /** + * @brief True if we are keeping the connection alive after it has finished + */ + bool keepalive; + + /** + * @brief Connect to a specified host and port. Throws std::runtime_error on fatal error. + * @param _hostname The hostname to connect to + * @param _port the Port number to connect to + * @param plaintext_downgrade Set to true to connect using plaintext only, without initialising SSL. + * @param reuse Attempt to reuse previous connections for this hostname and port, if available + * Note that no Discord endpoints will function when downgraded. This option is provided only for + * connection to non-Discord addresses such as within dpp::cluster::request(). + * @throw dpp::exception Failed to initialise connection + */ + ssl_client(const std::string &_hostname, const std::string &_port = "443", bool plaintext_downgrade = false, bool reuse = false); + + /** + * @brief Nonblocking I/O loop + * @throw std::exception Any std::exception (or derivative) thrown from read_loop() causes reconnection of the shard + */ + void read_loop(); + + /** + * @brief Destroy the ssl_client object + */ + virtual ~ssl_client(); + + /** + * @brief Handle input from the input buffer. This function will be called until + * all data in the buffer has been processed and the buffer is empty. + * @param buffer the buffer content. Will be modified removing any processed front elements + * @return bool True if the socket should remain connected + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Write to the output buffer. + * @param data Data to be written to the buffer + * @note The data may not be written immediately and may be written at a later time to the socket. + */ + virtual void write(const std::string &data); + + /** + * @brief Close socket connection + */ + virtual void close(); + + /** + * @brief Log a message + * @param severity severity of log message + * @param msg Log message to send + */ + virtual void log(dpp::loglevel severity, const std::string &msg) const; +}; + +}; diff --git a/3rdParty/dpp/stage_instance.h b/3rdParty/dpp/stage_instance.h index 6137320348..90a134f9eb 100644 --- a/3rdParty/dpp/stage_instance.h +++ b/3rdParty/dpp/stage_instance.h @@ -1,86 +1,86 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents the privacy of a stage instance - */ -enum stage_privacy_level : uint8_t { - /// The Stage instance is visible publicly, such as on Stage Discovery. - sp_public = 1, - /// The Stage instance is visible to only guild members. - sp_guild_only = 2 -}; - -/** - * @brief A stage instance. - * Stage instances are like a conference facility, with moderators/speakers and listeners. - */ -struct DPP_EXPORT stage_instance : public managed, public json_interface { - /// The guild id of the associated Stage channel - snowflake guild_id; - /// The id of the associated Stage channel - snowflake channel_id; - /// The topic of the Stage instance (1-120 characters) - std::string topic; - /// The privacy level of the Stage instance - stage_privacy_level privacy_level; - /// Whether or not Stage Discovery is disabled - bool discoverable_disabled; - - /** - * @brief Create a stage_instance object - */ - stage_instance(); - - /** - * @brief Destroy the stage_instance object - */ - ~stage_instance() = default; - - /** - * @brief Serialise a stage_instance object rom json - * - * @return stage_instance& a reference to self - */ - stage_instance& fill_from_json(const nlohmann::json* j); - - /** - * @brief Build json for this object - * - * @param with_id include ID - * @return std::string Dumped json of this object - */ - virtual std::string build_json(bool with_id = false) const; -}; - -/** A group of stage instances */ -typedef std::unordered_map stage_instance_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents the privacy of a stage instance + */ +enum stage_privacy_level : uint8_t { + /// The Stage instance is visible publicly, such as on Stage Discovery. + sp_public = 1, + /// The Stage instance is visible to only guild members. + sp_guild_only = 2 +}; + +/** + * @brief A stage instance. + * Stage instances are like a conference facility, with moderators/speakers and listeners. + */ +struct DPP_EXPORT stage_instance : public managed, public json_interface { + /// The guild id of the associated Stage channel + snowflake guild_id; + /// The id of the associated Stage channel + snowflake channel_id; + /// The topic of the Stage instance (1-120 characters) + std::string topic; + /// The privacy level of the Stage instance + stage_privacy_level privacy_level; + /// Whether or not Stage Discovery is disabled + bool discoverable_disabled; + + /** + * @brief Create a stage_instance object + */ + stage_instance(); + + /** + * @brief Destroy the stage_instance object + */ + ~stage_instance() = default; + + /** + * @brief Serialise a stage_instance object rom json + * + * @return stage_instance& a reference to self + */ + stage_instance& fill_from_json(const nlohmann::json* j); + + /** + * @brief Build json for this object + * + * @param with_id include ID + * @return std::string Dumped json of this object + */ + virtual std::string build_json(bool with_id = false) const; +}; + +/** A group of stage instances */ +typedef std::unordered_map stage_instance_map; + +}; diff --git a/3rdParty/dpp/stringops.h b/3rdParty/dpp/stringops.h index c749f1f370..856ff30103 100644 --- a/3rdParty/dpp/stringops.h +++ b/3rdParty/dpp/stringops.h @@ -1,212 +1,212 @@ -/************************************************************************************ - * - * D++ - A Lightweight C++ Library for Discord - * - * stringops.h taken from TriviaBot - * - * Copyright 2004 Craig Edwards - * - * Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { -/** - * @brief Convert a string to lowercase using tolower() - * - * @tparam T type of string - * @param s String to lowercase - * @return std::basic_string lowercased string - */ -template std::basic_string lowercase(const std::basic_string& s) -{ - std::basic_string s2 = s; - std::transform(s2.begin(), s2.end(), s2.begin(), tolower); - return s2; -} - -/** - * @brief Convert a string to uppercase using toupper() - * - * @tparam T type of string - * @param s String to uppercase - * @return std::basic_string uppercased string - */ -template std::basic_string uppercase(const std::basic_string& s) -{ - std::basic_string s2 = s; - std::transform(s2.begin(), s2.end(), s2.begin(), toupper); - return s2; -} - -/** - * @brief trim from end of string (right) - * - * @param s String to trim - * @return std::string trimmed string - */ -inline std::string rtrim(std::string s) -{ - s.erase(s.find_last_not_of(" \t\n\r\f\v") + 1); - return s; -} - -/** - * @brief trim from beginning of string (left) - * - * @param s string to trim - * @return std::string trimmed string - */ -inline std::string ltrim(std::string s) -{ - s.erase(0, s.find_first_not_of(" \t\n\r\f\v")); - return s; -} - -/** - * @brief Trim from both ends of string (right then left) - * - * @param s string to trim - * @return std::string trimmed string - */ -inline std::string trim(std::string s) -{ - return ltrim(rtrim(s)); -} - -/** - * @brief Add commas to a string (or dots) based on current locale server-side - * - * @tparam T type of numeric value - * @param value Value - * @return std::string number with commas added - */ -template std::string comma(T value) -{ - std::stringstream ss; - ss.imbue(std::locale("")); - ss << std::fixed << value; - return ss.str(); -} - -/** - * @brief Convert any value from a string to another type using stringstream. - * The optional second parameter indicates the format of the input string, - * e.g. std::dec for decimal, std::hex for hex, std::oct for octal. - * - * @tparam T Type to convert to - * @param s String to convert from - * @param f Numeric base, e.g. `std::dec` or `std::hex` - * @return T Returned numeric value - */ -template T from_string(const std::string &s, std::ios_base & (*f)(std::ios_base&)) -{ - T t; - std::istringstream iss(s); - iss >> f, iss >> t; - return t; -} - -/** - * @brief Convert any value from a string to another type using stringstream. - * - * @tparam T Type to convert to - * @param s String to convert from - * @return T Returned numeric value - * - * @note Base 10 for numeric conversions. - */ -template T from_string(const std::string &s) -{ - T t; - std::istringstream iss(s); - iss >> t; - return t; -} - -/** - * @brief Specialised conversion of uint64_t from string - * - * @tparam int64_t - * @param s string to convert - * @return uint64_t return value - */ -template uint64_t from_string(const std::string &s) -{ - return std::stoull(s, 0, 10); -} - -/** - * @brief Specialised conversion of uint32_t from string - * - * @tparam uint32_t - * @param s string to convert - * @return uint32_t return value - */ -template uint32_t from_string(const std::string &s) -{ - return std::stoul(s, 0, 10); -} - -/** - * @brief Specialised conversion of int from string - * - * @tparam int - * @param s string to convert - * @return int return value - */ -template int from_string(const std::string &s) -{ - return std::stoi(s, 0, 10); -} - -/** - * @brief Convert a numeric value to hex - * - * @tparam T numeric type - * @param i numeric value - * @return std::string value in hex, the length will be 2* the raw size of the type - */ -template std::string to_hex(T i) -{ - std::stringstream stream; - stream << std::setfill('0') << std::setw(sizeof(T)*2) << std::hex << i; - return stream.str(); -} - -/** - * @brief Format a numeric type as a string with leading zeroes - * - * @tparam T numeric type - * @param i numeric value - * @param width width of type including the leading zeroes - * @return std::string resultant string with leading zeroes - */ -template std::string leading_zeroes(T i, size_t width) -{ - std::stringstream stream; - stream << std::setfill('0') << std::setw(width) << std::dec << i; - return stream.str(); -} - -}; +/************************************************************************************ + * + * D++ - A Lightweight C++ Library for Discord + * + * stringops.h taken from TriviaBot + * + * Copyright 2004 Craig Edwards + * + * Core based on Sporks, the Learning Discord Bot, Craig Edwards (c) 2019. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { +/** + * @brief Convert a string to lowercase using tolower() + * + * @tparam T type of string + * @param s String to lowercase + * @return std::basic_string lowercased string + */ +template std::basic_string lowercase(const std::basic_string& s) +{ + std::basic_string s2 = s; + std::transform(s2.begin(), s2.end(), s2.begin(), tolower); + return s2; +} + +/** + * @brief Convert a string to uppercase using toupper() + * + * @tparam T type of string + * @param s String to uppercase + * @return std::basic_string uppercased string + */ +template std::basic_string uppercase(const std::basic_string& s) +{ + std::basic_string s2 = s; + std::transform(s2.begin(), s2.end(), s2.begin(), toupper); + return s2; +} + +/** + * @brief trim from end of string (right) + * + * @param s String to trim + * @return std::string trimmed string + */ +inline std::string rtrim(std::string s) +{ + s.erase(s.find_last_not_of(" \t\n\r\f\v") + 1); + return s; +} + +/** + * @brief trim from beginning of string (left) + * + * @param s string to trim + * @return std::string trimmed string + */ +inline std::string ltrim(std::string s) +{ + s.erase(0, s.find_first_not_of(" \t\n\r\f\v")); + return s; +} + +/** + * @brief Trim from both ends of string (right then left) + * + * @param s string to trim + * @return std::string trimmed string + */ +inline std::string trim(std::string s) +{ + return ltrim(rtrim(s)); +} + +/** + * @brief Add commas to a string (or dots) based on current locale server-side + * + * @tparam T type of numeric value + * @param value Value + * @return std::string number with commas added + */ +template std::string comma(T value) +{ + std::stringstream ss; + ss.imbue(std::locale("")); + ss << std::fixed << value; + return ss.str(); +} + +/** + * @brief Convert any value from a string to another type using stringstream. + * The optional second parameter indicates the format of the input string, + * e.g. std::dec for decimal, std::hex for hex, std::oct for octal. + * + * @tparam T Type to convert to + * @param s String to convert from + * @param f Numeric base, e.g. `std::dec` or `std::hex` + * @return T Returned numeric value + */ +template T from_string(const std::string &s, std::ios_base & (*f)(std::ios_base&)) +{ + T t; + std::istringstream iss(s); + iss >> f, iss >> t; + return t; +} + +/** + * @brief Convert any value from a string to another type using stringstream. + * + * @tparam T Type to convert to + * @param s String to convert from + * @return T Returned numeric value + * + * @note Base 10 for numeric conversions. + */ +template T from_string(const std::string &s) +{ + T t; + std::istringstream iss(s); + iss >> t; + return t; +} + +/** + * @brief Specialised conversion of uint64_t from string + * + * @tparam int64_t + * @param s string to convert + * @return uint64_t return value + */ +template uint64_t from_string(const std::string &s) +{ + return std::stoull(s, 0, 10); +} + +/** + * @brief Specialised conversion of uint32_t from string + * + * @tparam uint32_t + * @param s string to convert + * @return uint32_t return value + */ +template uint32_t from_string(const std::string &s) +{ + return std::stoul(s, 0, 10); +} + +/** + * @brief Specialised conversion of int from string + * + * @tparam int + * @param s string to convert + * @return int return value + */ +template int from_string(const std::string &s) +{ + return std::stoi(s, 0, 10); +} + +/** + * @brief Convert a numeric value to hex + * + * @tparam T numeric type + * @param i numeric value + * @return std::string value in hex, the length will be 2* the raw size of the type + */ +template std::string to_hex(T i) +{ + std::stringstream stream; + stream << std::setfill('0') << std::setw(sizeof(T)*2) << std::hex << i; + return stream.str(); +} + +/** + * @brief Format a numeric type as a string with leading zeroes + * + * @tparam T numeric type + * @param i numeric value + * @param width width of type including the leading zeroes + * @return std::string resultant string with leading zeroes + */ +template std::string leading_zeroes(T i, size_t width) +{ + std::stringstream stream; + stream << std::setfill('0') << std::setw(width) << std::dec << i; + return stream.str(); +} + +}; diff --git a/3rdParty/dpp/sync.h b/3rdParty/dpp/sync.h index e4d278fb5b..a837103782 100644 --- a/3rdParty/dpp/sync.h +++ b/3rdParty/dpp/sync.h @@ -1,80 +1,80 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2022 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - - /** - * @brief Call a D++ REST function synchronously. - * - * Synchronously calling a REST function means *IT WILL BLOCK* - This is a Bad Thing™ and strongly discouraged. - * There are very few circumstances you actually need this. If you do need to use this, you'll know it. - * - * Example: - * - * ```cpp - * dpp::message m = dpp::sync(&bot, &dpp::cluster::message_create, dpp::message(channel_id, "moo.")); - * ``` - * - * @warning As previously mentioned, this template will block. It is ill-advised to call this outside of - * a separate thread and this should never be directly used in any event such as dpp::cluster::on_interaction_create! - * @tparam T type of expected return value, should match up with the method called - * @tparam F Type of class method in dpp::cluster to call. - * @tparam Ts Function parameters in method call - * @param c A pointer to dpp::cluster object - * @param func pointer to class method in dpp::cluster to call. This can call any - * dpp::cluster member function who's last parameter is a dpp::command_completion_event_t callback type. - * @param args Zero or more arguments for the method call - * @return An instantiated object of type T - * @throw dpp::rest_exception On failure of the method call, an exception is thrown - */ - template T sync(class cluster* c, F func, Ts&&... args) { - std::promise _p; - std::future _f = _p.get_future(); - /* (obj ->* func) is the obscure syntax for calling a method pointer on an object instance */ - (c ->* func)(std::forward(args)..., [&_p](const auto& cc) { - try { - if (cc.is_error()) { - throw dpp::rest_exception(cc.get_error().message); - } else { - try { - _p.set_value(std::get(cc.value)); - } catch (const std::exception& e) { - throw dpp::rest_exception(e.what()); - } - } - } catch (const dpp::rest_exception&) { - _p.set_exception(std::current_exception()); - } - }); - - /* Blocking calling thread until rest request is completed. - * Exceptions encountered on the other thread are re-thrown. - */ - return _f.get(); - } - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2022 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + + /** + * @brief Call a D++ REST function synchronously. + * + * Synchronously calling a REST function means *IT WILL BLOCK* - This is a Bad Thing™ and strongly discouraged. + * There are very few circumstances you actually need this. If you do need to use this, you'll know it. + * + * Example: + * + * ```cpp + * dpp::message m = dpp::sync(&bot, &dpp::cluster::message_create, dpp::message(channel_id, "moo.")); + * ``` + * + * @warning As previously mentioned, this template will block. It is ill-advised to call this outside of + * a separate thread and this should never be directly used in any event such as dpp::cluster::on_interaction_create! + * @tparam T type of expected return value, should match up with the method called + * @tparam F Type of class method in dpp::cluster to call. + * @tparam Ts Function parameters in method call + * @param c A pointer to dpp::cluster object + * @param func pointer to class method in dpp::cluster to call. This can call any + * dpp::cluster member function who's last parameter is a dpp::command_completion_event_t callback type. + * @param args Zero or more arguments for the method call + * @return An instantiated object of type T + * @throw dpp::rest_exception On failure of the method call, an exception is thrown + */ + template T sync(class cluster* c, F func, Ts&&... args) { + std::promise _p; + std::future _f = _p.get_future(); + /* (obj ->* func) is the obscure syntax for calling a method pointer on an object instance */ + (c ->* func)(std::forward(args)..., [&_p](const auto& cc) { + try { + if (cc.is_error()) { + throw dpp::rest_exception(cc.get_error().message); + } else { + try { + _p.set_value(std::get(cc.value)); + } catch (const std::exception& e) { + throw dpp::rest_exception(e.what()); + } + } + } catch (const dpp::rest_exception&) { + _p.set_exception(std::current_exception()); + } + }); + + /* Blocking calling thread until rest request is completed. + * Exceptions encountered on the other thread are re-thrown. + */ + return _f.get(); + } + +}; diff --git a/3rdParty/dpp/sysdep.h b/3rdParty/dpp/sysdep.h index d706d7b8f5..8971c30870 100644 --- a/3rdParty/dpp/sysdep.h +++ b/3rdParty/dpp/sysdep.h @@ -1,120 +1,120 @@ -/* - * Discord erlpack - tidied up for D++, Craig Edwards 2021. - * - * MessagePack system dependencies modified for erlpack. - * - * Copyright (C) 2008-2010 FURUHASHI Sadayuki - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#pragma once - -#include -#include -#include -#include -#if defined(__linux__) -#include -#endif - -#ifdef _WIN32 - -#ifdef __cplusplus -/* numeric_limits::min,max */ -#ifdef max -#undef max -#endif -#ifdef min -#undef min -#endif -#endif - -#else -#include /* __BYTE_ORDER */ -#endif - -#if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) -#if __BYTE_ORDER == __LITTLE_ENDIAN -#define __LITTLE_ENDIAN__ -#elif __BYTE_ORDER == __BIG_ENDIAN -#define __BIG_ENDIAN__ -#elif _WIN32 -#define __LITTLE_ENDIAN__ -#endif -#endif - - -#ifdef __LITTLE_ENDIAN__ - -#ifdef _WIN32 -# if defined(ntohs) -# define etf_byte_order_16(x) ntohs(x) -# elif defined(_byteswap_ushort) || (defined(_MSC_VER) && _MSC_VER >= 1400) -# define etf_byte_order_16(x) ((uint16_t)_byteswap_ushort((unsigned short)x)) -# else -# define etf_byte_order_16(x) ( \ - ((((uint16_t)x) << 8) ) | \ - ((((uint16_t)x) >> 8) ) ) -# endif -#else -# define etf_byte_order_16(x) ntohs(x) -#endif - -#ifdef _WIN32 -# if defined(ntohl) -# define etf_byte_order_32(x) ntohl(x) -# elif defined(_byteswap_ulong) || (defined(_MSC_VER) && _MSC_VER >= 1400) -# define etf_byte_order_32(x) ((uint32_t)_byteswap_ulong((unsigned long)x)) -# else -# define etf_byte_order_32(x) \ - ( ((((uint32_t)x) << 24) ) | \ - ((((uint32_t)x) << 8) & 0x00ff0000U ) | \ - ((((uint32_t)x) >> 8) & 0x0000ff00U ) | \ - ((((uint32_t)x) >> 24) ) ) -# endif -#else -# define etf_byte_order_32(x) ntohl(x) -#endif - -#if defined(_byteswap_uint64) || (defined(_MSC_VER) && _MSC_VER >= 1400) -# define etf_byte_order_64(x) (_byteswap_uint64(x)) -#elif defined(bswap_64) -# define etf_byte_order_64(x) bswap_64(x) -#elif defined(__DARWIN_OSSwapInt64) -# define etf_byte_order_64(x) __DARWIN_OSSwapInt64(x) -#elif defined(__linux__) -# define etf_byte_order_64(x) be64toh(x) -#else -# define etf_byte_order_64(x) \ - ( ((((uint64_t)x) << 56) ) | \ - ((((uint64_t)x) << 40) & 0x00ff000000000000ULL ) | \ - ((((uint64_t)x) << 24) & 0x0000ff0000000000ULL ) | \ - ((((uint64_t)x) << 8) & 0x000000ff00000000ULL ) | \ - ((((uint64_t)x) >> 8) & 0x00000000ff000000ULL ) | \ - ((((uint64_t)x) >> 24) & 0x0000000000ff0000ULL ) | \ - ((((uint64_t)x) >> 40) & 0x000000000000ff00ULL ) | \ - ((((uint64_t)x) >> 56) ) ) -#endif - -#else -#define etf_byte_order_16(x) (x) -#define etf_byte_order_32(x) (x) -#define etf_byte_order_64(x) (x) -#endif - -#define store_16_bits(to, num) \ - do { uint16_t val = etf_byte_order_16(num); memcpy(to, &val, 2); } while(0) -#define store_32_bits(to, num) \ - do { uint32_t val = etf_byte_order_32(num); memcpy(to, &val, 4); } while(0) -#define store_64_bits(to, num) \ - do { uint64_t val = etf_byte_order_64(num); memcpy(to, &val, 8); } while(0) +/* + * Discord erlpack - tidied up for D++, Craig Edwards 2021. + * + * MessagePack system dependencies modified for erlpack. + * + * Copyright (C) 2008-2010 FURUHASHI Sadayuki + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#pragma once + +#include +#include +#include +#include +#if defined(__linux__) +#include +#endif + +#ifdef _WIN32 + +#ifdef __cplusplus +/* numeric_limits::min,max */ +#ifdef max +#undef max +#endif +#ifdef min +#undef min +#endif +#endif + +#else +#include /* __BYTE_ORDER */ +#endif + +#if !defined(__LITTLE_ENDIAN__) && !defined(__BIG_ENDIAN__) +#if __BYTE_ORDER == __LITTLE_ENDIAN +#define __LITTLE_ENDIAN__ +#elif __BYTE_ORDER == __BIG_ENDIAN +#define __BIG_ENDIAN__ +#elif _WIN32 +#define __LITTLE_ENDIAN__ +#endif +#endif + + +#ifdef __LITTLE_ENDIAN__ + +#ifdef _WIN32 +# if defined(ntohs) +# define etf_byte_order_16(x) ntohs(x) +# elif defined(_byteswap_ushort) || (defined(_MSC_VER) && _MSC_VER >= 1400) +# define etf_byte_order_16(x) ((uint16_t)_byteswap_ushort((unsigned short)x)) +# else +# define etf_byte_order_16(x) ( \ + ((((uint16_t)x) << 8) ) | \ + ((((uint16_t)x) >> 8) ) ) +# endif +#else +# define etf_byte_order_16(x) ntohs(x) +#endif + +#ifdef _WIN32 +# if defined(ntohl) +# define etf_byte_order_32(x) ntohl(x) +# elif defined(_byteswap_ulong) || (defined(_MSC_VER) && _MSC_VER >= 1400) +# define etf_byte_order_32(x) ((uint32_t)_byteswap_ulong((unsigned long)x)) +# else +# define etf_byte_order_32(x) \ + ( ((((uint32_t)x) << 24) ) | \ + ((((uint32_t)x) << 8) & 0x00ff0000U ) | \ + ((((uint32_t)x) >> 8) & 0x0000ff00U ) | \ + ((((uint32_t)x) >> 24) ) ) +# endif +#else +# define etf_byte_order_32(x) ntohl(x) +#endif + +#if defined(_byteswap_uint64) || (defined(_MSC_VER) && _MSC_VER >= 1400) +# define etf_byte_order_64(x) (_byteswap_uint64(x)) +#elif defined(bswap_64) +# define etf_byte_order_64(x) bswap_64(x) +#elif defined(__DARWIN_OSSwapInt64) +# define etf_byte_order_64(x) __DARWIN_OSSwapInt64(x) +#elif defined(__linux__) +# define etf_byte_order_64(x) be64toh(x) +#else +# define etf_byte_order_64(x) \ + ( ((((uint64_t)x) << 56) ) | \ + ((((uint64_t)x) << 40) & 0x00ff000000000000ULL ) | \ + ((((uint64_t)x) << 24) & 0x0000ff0000000000ULL ) | \ + ((((uint64_t)x) << 8) & 0x000000ff00000000ULL ) | \ + ((((uint64_t)x) >> 8) & 0x00000000ff000000ULL ) | \ + ((((uint64_t)x) >> 24) & 0x0000000000ff0000ULL ) | \ + ((((uint64_t)x) >> 40) & 0x000000000000ff00ULL ) | \ + ((((uint64_t)x) >> 56) ) ) +#endif + +#else +#define etf_byte_order_16(x) (x) +#define etf_byte_order_32(x) (x) +#define etf_byte_order_64(x) (x) +#endif + +#define store_16_bits(to, num) \ + do { uint16_t val = etf_byte_order_16(num); memcpy(to, &val, 2); } while(0) +#define store_32_bits(to, num) \ + do { uint32_t val = etf_byte_order_32(num); memcpy(to, &val, 4); } while(0) +#define store_64_bits(to, num) \ + do { uint64_t val = etf_byte_order_64(num); memcpy(to, &val, 8); } while(0) diff --git a/3rdParty/dpp/timed_listener.h b/3rdParty/dpp/timed_listener.h index 2316a7797a..467f0046e0 100644 --- a/3rdParty/dpp/timed_listener.h +++ b/3rdParty/dpp/timed_listener.h @@ -1,95 +1,95 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief A timed_listener is a way to temporarily attach to an event for a specific timeframe, then detach when complete. - * A lambda may also be optionally called when the timeout is reached. Destructing the timed_listener detaches any attached - * event listeners, and cancels any created timers, but does not call any timeout lambda. - * - * @tparam attached_event Event within cluster to attach to within the cluster::dispatch member (dpp::dispatcher object) - * @tparam listening_function Definition of lambda function that matches up with the attached_event. - */ -template class timed_listener -{ -private: - /// Owning cluster - cluster* owner; - - /// Duration of listen - time_t duration; - - /// Reference to attached event in cluster - //event_router_t on_thread_member_update; - attached_event& ev; - - /// Timer handle - timer th; - - /// Event handle - event_handle listener_handle; - -public: - /** - * @brief Construct a new timed listener object - * - * @param cl Owning cluster - * @param _duration Duration of timed event in seconds - * @param event Event to hook, e.g. cluster.on_message_create - * @param on_end An optional void() lambda to trigger when the timed_listener times out. - * Calling the destructor before the timeout is reached does not call this lambda. - * @param listener Lambda to receive events. Type must match up properly with that passed into the 'event' parameter. - */ - timed_listener(cluster* cl, uint64_t _duration, attached_event& event, listening_function listener, timer_callback_t on_end = {}) - : owner(cl), duration(_duration), ev(event) - { - /* Attach event */ - listener_handle = ev(listener); - /* Create timer */ - th = cl->start_timer([this](dpp::timer timer_handle) { - /* Timer has finished, detach it from event. - * Only allowed to tick once. - */ - ev.detach(listener_handle); - owner->stop_timer(th); - }, duration, on_end); - } - - /** - * @brief Destroy the timed listener object - */ - ~timed_listener() { - /* Stop timer and detach event, but do not call on_end */ - ev.detach(listener_handle); - owner->stop_timer(th); - } -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief A timed_listener is a way to temporarily attach to an event for a specific timeframe, then detach when complete. + * A lambda may also be optionally called when the timeout is reached. Destructing the timed_listener detaches any attached + * event listeners, and cancels any created timers, but does not call any timeout lambda. + * + * @tparam attached_event Event within cluster to attach to within the cluster::dispatch member (dpp::dispatcher object) + * @tparam listening_function Definition of lambda function that matches up with the attached_event. + */ +template class timed_listener +{ +private: + /// Owning cluster + cluster* owner; + + /// Duration of listen + time_t duration; + + /// Reference to attached event in cluster + //event_router_t on_thread_member_update; + attached_event& ev; + + /// Timer handle + timer th; + + /// Event handle + event_handle listener_handle; + +public: + /** + * @brief Construct a new timed listener object + * + * @param cl Owning cluster + * @param _duration Duration of timed event in seconds + * @param event Event to hook, e.g. cluster.on_message_create + * @param on_end An optional void() lambda to trigger when the timed_listener times out. + * Calling the destructor before the timeout is reached does not call this lambda. + * @param listener Lambda to receive events. Type must match up properly with that passed into the 'event' parameter. + */ + timed_listener(cluster* cl, uint64_t _duration, attached_event& event, listening_function listener, timer_callback_t on_end = {}) + : owner(cl), duration(_duration), ev(event) + { + /* Attach event */ + listener_handle = ev(listener); + /* Create timer */ + th = cl->start_timer([this](dpp::timer timer_handle) { + /* Timer has finished, detach it from event. + * Only allowed to tick once. + */ + ev.detach(listener_handle); + owner->stop_timer(th); + }, duration, on_end); + } + + /** + * @brief Destroy the timed listener object + */ + ~timed_listener() { + /* Stop timer and detach event, but do not call on_end */ + ev.detach(listener_handle); + owner->stop_timer(th); + } +}; + }; \ No newline at end of file diff --git a/3rdParty/dpp/timer.h b/3rdParty/dpp/timer.h index fdc8b536b6..92c5a05db1 100644 --- a/3rdParty/dpp/timer.h +++ b/3rdParty/dpp/timer.h @@ -1,124 +1,124 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Represents a timer handle. - * Returned from cluster::start_timer and used by cluster::stop_timer. - * This is obtained from a simple incrementing value, internally. - */ -typedef size_t timer; - -/** - * @brief The type for a timer callback - */ -typedef std::function timer_callback_t; - -/** - * @brief Used internally to store state of active timers - */ -struct DPP_EXPORT timer_t { - /** - * @brief Timer handle - */ - timer handle; - /** - * @brief Next timer tick as unix epoch - */ - time_t next_tick; - /** - * @brief Frequency between ticks - */ - uint64_t frequency; - /** - * @brief Lambda to call on tick - */ - timer_callback_t on_tick; - /** - * @brief Lambda to call on stop (optional) - */ - timer_callback_t on_stop; -}; - -/** - * @brief A map of timers, ordered by earliest first so that map::begin() is always the - * soonest to be due. - */ -typedef std::multimap timer_next_t; - -/** - * @brief A map of timers stored by handle - */ -typedef std::unordered_map timer_reg_t; - -/** - * @brief Trigger a timed event once. - * The provided callback is called only once. - */ -class DPP_EXPORT oneshot_timer -{ -private: - /// Owning cluster - class cluster* owner; - /// Timer handle - timer th; -public: - /** - * @brief Construct a new oneshot timer object - * - * @param cl cluster owner - * @param duration duration before firing - * @param callback callback to call on firing - */ - oneshot_timer(class cluster* cl, uint64_t duration, timer_callback_t callback); - - /** - * @brief Get the handle for the created one-shot timer - * - * @return timer handle for use with stop_timer - */ - timer get_handle(); - - /** - * @brief Cancel the one shot timer immediately. - * Callback function is not called. - */ - void cancel(); - - /** - * @brief Destroy the oneshot timer object - */ - ~oneshot_timer(); -}; - - - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Represents a timer handle. + * Returned from cluster::start_timer and used by cluster::stop_timer. + * This is obtained from a simple incrementing value, internally. + */ +typedef size_t timer; + +/** + * @brief The type for a timer callback + */ +typedef std::function timer_callback_t; + +/** + * @brief Used internally to store state of active timers + */ +struct DPP_EXPORT timer_t { + /** + * @brief Timer handle + */ + timer handle; + /** + * @brief Next timer tick as unix epoch + */ + time_t next_tick; + /** + * @brief Frequency between ticks + */ + uint64_t frequency; + /** + * @brief Lambda to call on tick + */ + timer_callback_t on_tick; + /** + * @brief Lambda to call on stop (optional) + */ + timer_callback_t on_stop; +}; + +/** + * @brief A map of timers, ordered by earliest first so that map::begin() is always the + * soonest to be due. + */ +typedef std::multimap timer_next_t; + +/** + * @brief A map of timers stored by handle + */ +typedef std::unordered_map timer_reg_t; + +/** + * @brief Trigger a timed event once. + * The provided callback is called only once. + */ +class DPP_EXPORT oneshot_timer +{ +private: + /// Owning cluster + class cluster* owner; + /// Timer handle + timer th; +public: + /** + * @brief Construct a new oneshot timer object + * + * @param cl cluster owner + * @param duration duration before firing + * @param callback callback to call on firing + */ + oneshot_timer(class cluster* cl, uint64_t duration, timer_callback_t callback); + + /** + * @brief Get the handle for the created one-shot timer + * + * @return timer handle for use with stop_timer + */ + timer get_handle(); + + /** + * @brief Cancel the one shot timer immediately. + * Callback function is not called. + */ + void cancel(); + + /** + * @brief Destroy the oneshot timer object + */ + ~oneshot_timer(); +}; + + + +}; diff --git a/3rdParty/dpp/user.h b/3rdParty/dpp/user.h index c582f443c3..4ff03664cd 100644 --- a/3rdParty/dpp/user.h +++ b/3rdParty/dpp/user.h @@ -1,371 +1,371 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Various bitmask flags used to represent information about a dpp::user - */ -enum user_flags : uint32_t { - /// User is a bot - u_bot = 0b00000000000000000000001, - /// User is a system user (Clyde!) - u_system = 0b00000000000000000000010, - /// User has multi-factor authentication enabled - u_mfa_enabled = 0b00000000000000000000100, - /// User is verified (verified email address) - u_verified = 0b00000000000000000001000, - /// User has full nitro - u_nitro_full = 0b00000000000000000010000, - /// User has nitro classic - u_nitro_classic = 0b00000000000000000100000, - /// User is discord staff - u_discord_employee = 0b00000000000000001000000, - /// User owns a partnered server - u_partnered_owner = 0b00000000000000010000000, - /// User is a member of hypesquad events - u_hypesquad_events = 0b00000000000000100000000, - /// User has BugHunter level 1 - u_bughunter_1 = 0b00000000000001000000000, - /// User is a member of House Bravery - u_house_bravery = 0b00000000000010000000000, - /// User is a member of House Brilliance - u_house_brilliance = 0b00000000000100000000000, - /// User is a member of House Balance - u_house_balance = 0b00000000001000000000000, - /// User is an early supporter - u_early_supporter = 0b00000000010000000000000, - /// User is a team user - u_team_user = 0b00000000100000000000000, - /// User is has Bug Hunter level 2 - u_bughunter_2 = 0b00000001000000000000000, - /// User is a verified bot - u_verified_bot = 0b00000010000000000000000, - /// User has the Early Verified Bot Developer badge - u_verified_bot_dev = 0b00000100000000000000000, - /// User's icon is animated - u_animated_icon = 0b00001000000000000000000, - /// User is a certified moderator - u_certified_moderator = 0b00010000000000000000000, - /// User is a bot using HTTP interactions (shows online even when not connected to a websocket) - u_bot_http_interactions = 0b00100000000000000000000, - /// User has nitro basic - u_nitro_basic = 0b01000000000000000000000, - /// User has the active developer badge - u_active_developer = 0b10000000000000000000000, -}; - -/** - * @brief Represents a user on discord. May or may not be a member of a dpp::guild. - */ -class DPP_EXPORT user : public managed, public json_interface { -public: - /** Discord username */ - std::string username; - /** Avatar hash */ - utility::iconhash avatar; - /** Flags built from a bitmask of values in dpp::user_flags */ - uint32_t flags; - /** Discriminator (aka tag), 4 digits usually displayed with leading zeroes. - * - * @note To print the discriminator with leading zeroes, use format_username() - */ - uint16_t discriminator; - /** Reference count of how many guilds this user is in */ - uint8_t refcount; - - /** - * @brief Construct a new user object - */ - user(); - - /** - * @brief Destroy the user object - */ - virtual ~user(); - - /** - * @brief Create a mentionable user. - * @param id The ID of the user. - * @return std::string The formatted mention of the user. - */ - static std::string get_mention(const snowflake& id); - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - user& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = true) const; - - /** - * @brief Get the avatar url of the user object - * - * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized avatar is returned. - * @return std::string avatar url. If the user doesn't have an avatar, the default user avatar url is returned - */ - std::string get_avatar_url(uint16_t size = 0) const; - - /** - * @brief Return a ping/mention for the user - * - * @return std::string mention - */ - std::string get_mention() const; - - /** - * @brief Return true if user has the active Developer badge - * - * @return true if has active developer - */ - bool is_active_developer() const; - /** - * @brief User is a bot - * - * @return True if the user is a bot - */ - bool is_bot() const; - /** - * @brief User is a system user (Clyde) - * - * @return true if user is a system user - */ - bool is_system() const; - /** - * @brief User has multi-factor authentication enabled - * - * @return true if multi-factor is enabled - */ - bool is_mfa_enabled() const; - /** - * @brief Return true if user has verified account - * - * @return true if verified - */ - bool is_verified() const; - /** - * @brief Return true if user has full nitro. - * This is mutually exclusive with full nitro. - * - * @return true if user has full nitro - */ - bool has_nitro_full() const; - /** - * @brief Return true if user has nitro classic. - * This is mutually exclusive with nitro classic. - * - * @return true if user has nitro classic - */ - bool has_nitro_classic() const; - /** - * @brief Return true if user has nitro basic. - * This is mutually exclusive with nitro basic. - * - * @return true if user has nitro basic - */ - bool has_nitro_basic() const; - /** - * @brief Return true if user is a discord employee - * - * @return true if user is discord staff - */ - bool is_discord_employee() const; - /** - * @brief Return true if user owns a partnered server - * - * @return true if user has partnered server - */ - bool is_partnered_owner() const; - /** - * @brief Return true if user has hypesquad events - * - * @return true if has hypesquad events - */ - bool has_hypesquad_events() const; - /** - * @brief Return true if user has the bughunter level 1 badge - * - * @return true if has bughunter level 1 - */ - bool is_bughunter_1() const; - /** - * @brief Return true if user is in house bravery - * - * @return true if in house bravery - */ - bool is_house_bravery() const; - /** - * @brief Return true if user is in house brilliance - * - * @return true if in house brilliance - */ - bool is_house_brilliance() const; - /** - * @brief Return true if user is in house balance - * - * @return true if in house brilliance - */ - bool is_house_balance() const; - /** - * @brief Return true if user is an early supporter - * - * @return true if early supporter - */ - bool is_early_supporter() const; - /** - * @brief Return true if user is a team user - * - * @return true if a team user - */ - bool is_team_user() const; - /** - * @brief Return true if user has the bughunter level 2 badge - * - * @return true if has bughunter level 2 - */ - bool is_bughunter_2() const; - /** - * @brief Return true if user has the verified bot badge - * - * @return true if verified bot - */ - bool is_verified_bot() const; - /** - * @brief Return true if user is an early verified bot developer - * - * @return true if verified bot developer - */ - bool is_verified_bot_dev() const; - /** - * @brief Return true if user is a certified moderator - * - * @return true if certified moderator - */ - bool is_certified_moderator() const; - /** - * @brief Return true if user is a bot which exclusively uses HTTP interactions. - * Bots using HTTP interactions are always considered online even when not connected to a websocket. - * - * @return true if is a http interactions only bot - */ - bool is_bot_http_interactions() const; - /** - * @brief Return true if user has an animated icon - * - * @return true if icon is animated (gif) - */ - bool has_animated_icon() const; - - /** - * @brief Format a username into user#discriminator - * - * For example Brain#0001 - * - * @return Formatted username and discriminator - */ - std::string format_username() const; -}; - -/** - * @brief A user with additional fields only available via the oauth2 identify scope. - * These are not included in dpp::user as additional scopes are needed to fetch them - * which bots do not normally have. - */ -class DPP_EXPORT user_identified : public user, public json_interface { -public: - std::string locale; //!< Optional: the user's chosen language option identify - std::string email; //!< Optional: the user's email email (may be empty) - utility::iconhash banner; //!< Optional: the user's banner hash identify (may be empty) - uint32_t accent_color; //!< Optional: the user's banner color encoded as an integer representation of hexadecimal color code identify (may be empty) - bool verified; //!< Optional: whether the email on this account has been verified email - - /** Fill this record from json. - * @param j The json to fill this record from - * @return Reference to self - */ - user_identified& fill_from_json(nlohmann::json* j); - - /** - * @brief Convert to JSON string - * - * @param with_id include ID in output - * @return std::string JSON output - */ - virtual std::string build_json(bool with_id = true) const; - - /** - * @brief Construct a new user identified object - */ - user_identified(); - - /** - * @brief Destroy the user identified object - */ - virtual ~user_identified(); - - /** - * @brief Get the user identified's banner url if they have one, otherwise returns an empty string - * - * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. - * @return std::string banner url or empty string - */ - std::string get_banner_url(uint16_t size = 0) const; - -}; - -/** - * @brief helper function to deserialize a user from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param u user to be deserialized - */ -void from_json(const nlohmann::json& j, user& u); - -/** - * @brief helper function to deserialize a user_identified from json - * - * @see https://github.com/nlohmann/json#arbitrary-types-conversions - * - * @param j output json object - * @param u user to be deserialized - */ -void from_json(const nlohmann::json& j, user_identified& u); - -/** A group of users */ -typedef std::unordered_map user_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Various bitmask flags used to represent information about a dpp::user + */ +enum user_flags : uint32_t { + /// User is a bot + u_bot = 0b00000000000000000000001, + /// User is a system user (Clyde!) + u_system = 0b00000000000000000000010, + /// User has multi-factor authentication enabled + u_mfa_enabled = 0b00000000000000000000100, + /// User is verified (verified email address) + u_verified = 0b00000000000000000001000, + /// User has full nitro + u_nitro_full = 0b00000000000000000010000, + /// User has nitro classic + u_nitro_classic = 0b00000000000000000100000, + /// User is discord staff + u_discord_employee = 0b00000000000000001000000, + /// User owns a partnered server + u_partnered_owner = 0b00000000000000010000000, + /// User is a member of hypesquad events + u_hypesquad_events = 0b00000000000000100000000, + /// User has BugHunter level 1 + u_bughunter_1 = 0b00000000000001000000000, + /// User is a member of House Bravery + u_house_bravery = 0b00000000000010000000000, + /// User is a member of House Brilliance + u_house_brilliance = 0b00000000000100000000000, + /// User is a member of House Balance + u_house_balance = 0b00000000001000000000000, + /// User is an early supporter + u_early_supporter = 0b00000000010000000000000, + /// User is a team user + u_team_user = 0b00000000100000000000000, + /// User is has Bug Hunter level 2 + u_bughunter_2 = 0b00000001000000000000000, + /// User is a verified bot + u_verified_bot = 0b00000010000000000000000, + /// User has the Early Verified Bot Developer badge + u_verified_bot_dev = 0b00000100000000000000000, + /// User's icon is animated + u_animated_icon = 0b00001000000000000000000, + /// User is a certified moderator + u_certified_moderator = 0b00010000000000000000000, + /// User is a bot using HTTP interactions (shows online even when not connected to a websocket) + u_bot_http_interactions = 0b00100000000000000000000, + /// User has nitro basic + u_nitro_basic = 0b01000000000000000000000, + /// User has the active developer badge + u_active_developer = 0b10000000000000000000000, +}; + +/** + * @brief Represents a user on discord. May or may not be a member of a dpp::guild. + */ +class DPP_EXPORT user : public managed, public json_interface { +public: + /** Discord username */ + std::string username; + /** Avatar hash */ + utility::iconhash avatar; + /** Flags built from a bitmask of values in dpp::user_flags */ + uint32_t flags; + /** Discriminator (aka tag), 4 digits usually displayed with leading zeroes. + * + * @note To print the discriminator with leading zeroes, use format_username() + */ + uint16_t discriminator; + /** Reference count of how many guilds this user is in */ + uint8_t refcount; + + /** + * @brief Construct a new user object + */ + user(); + + /** + * @brief Destroy the user object + */ + virtual ~user(); + + /** + * @brief Create a mentionable user. + * @param id The ID of the user. + * @return std::string The formatted mention of the user. + */ + static std::string get_mention(const snowflake& id); + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + user& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = true) const; + + /** + * @brief Get the avatar url of the user object + * + * @param size The size of the avatar in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized avatar is returned. + * @return std::string avatar url. If the user doesn't have an avatar, the default user avatar url is returned + */ + std::string get_avatar_url(uint16_t size = 0) const; + + /** + * @brief Return a ping/mention for the user + * + * @return std::string mention + */ + std::string get_mention() const; + + /** + * @brief Return true if user has the active Developer badge + * + * @return true if has active developer + */ + bool is_active_developer() const; + /** + * @brief User is a bot + * + * @return True if the user is a bot + */ + bool is_bot() const; + /** + * @brief User is a system user (Clyde) + * + * @return true if user is a system user + */ + bool is_system() const; + /** + * @brief User has multi-factor authentication enabled + * + * @return true if multi-factor is enabled + */ + bool is_mfa_enabled() const; + /** + * @brief Return true if user has verified account + * + * @return true if verified + */ + bool is_verified() const; + /** + * @brief Return true if user has full nitro. + * This is mutually exclusive with full nitro. + * + * @return true if user has full nitro + */ + bool has_nitro_full() const; + /** + * @brief Return true if user has nitro classic. + * This is mutually exclusive with nitro classic. + * + * @return true if user has nitro classic + */ + bool has_nitro_classic() const; + /** + * @brief Return true if user has nitro basic. + * This is mutually exclusive with nitro basic. + * + * @return true if user has nitro basic + */ + bool has_nitro_basic() const; + /** + * @brief Return true if user is a discord employee + * + * @return true if user is discord staff + */ + bool is_discord_employee() const; + /** + * @brief Return true if user owns a partnered server + * + * @return true if user has partnered server + */ + bool is_partnered_owner() const; + /** + * @brief Return true if user has hypesquad events + * + * @return true if has hypesquad events + */ + bool has_hypesquad_events() const; + /** + * @brief Return true if user has the bughunter level 1 badge + * + * @return true if has bughunter level 1 + */ + bool is_bughunter_1() const; + /** + * @brief Return true if user is in house bravery + * + * @return true if in house bravery + */ + bool is_house_bravery() const; + /** + * @brief Return true if user is in house brilliance + * + * @return true if in house brilliance + */ + bool is_house_brilliance() const; + /** + * @brief Return true if user is in house balance + * + * @return true if in house brilliance + */ + bool is_house_balance() const; + /** + * @brief Return true if user is an early supporter + * + * @return true if early supporter + */ + bool is_early_supporter() const; + /** + * @brief Return true if user is a team user + * + * @return true if a team user + */ + bool is_team_user() const; + /** + * @brief Return true if user has the bughunter level 2 badge + * + * @return true if has bughunter level 2 + */ + bool is_bughunter_2() const; + /** + * @brief Return true if user has the verified bot badge + * + * @return true if verified bot + */ + bool is_verified_bot() const; + /** + * @brief Return true if user is an early verified bot developer + * + * @return true if verified bot developer + */ + bool is_verified_bot_dev() const; + /** + * @brief Return true if user is a certified moderator + * + * @return true if certified moderator + */ + bool is_certified_moderator() const; + /** + * @brief Return true if user is a bot which exclusively uses HTTP interactions. + * Bots using HTTP interactions are always considered online even when not connected to a websocket. + * + * @return true if is a http interactions only bot + */ + bool is_bot_http_interactions() const; + /** + * @brief Return true if user has an animated icon + * + * @return true if icon is animated (gif) + */ + bool has_animated_icon() const; + + /** + * @brief Format a username into user#discriminator + * + * For example Brain#0001 + * + * @return Formatted username and discriminator + */ + std::string format_username() const; +}; + +/** + * @brief A user with additional fields only available via the oauth2 identify scope. + * These are not included in dpp::user as additional scopes are needed to fetch them + * which bots do not normally have. + */ +class DPP_EXPORT user_identified : public user, public json_interface { +public: + std::string locale; //!< Optional: the user's chosen language option identify + std::string email; //!< Optional: the user's email email (may be empty) + utility::iconhash banner; //!< Optional: the user's banner hash identify (may be empty) + uint32_t accent_color; //!< Optional: the user's banner color encoded as an integer representation of hexadecimal color code identify (may be empty) + bool verified; //!< Optional: whether the email on this account has been verified email + + /** Fill this record from json. + * @param j The json to fill this record from + * @return Reference to self + */ + user_identified& fill_from_json(nlohmann::json* j); + + /** + * @brief Convert to JSON string + * + * @param with_id include ID in output + * @return std::string JSON output + */ + virtual std::string build_json(bool with_id = true) const; + + /** + * @brief Construct a new user identified object + */ + user_identified(); + + /** + * @brief Destroy the user identified object + */ + virtual ~user_identified(); + + /** + * @brief Get the user identified's banner url if they have one, otherwise returns an empty string + * + * @param size The size of the banner in pixels. It can be any power of two between 16 and 4096. if not specified, the default sized banner is returned. + * @return std::string banner url or empty string + */ + std::string get_banner_url(uint16_t size = 0) const; + +}; + +/** + * @brief helper function to deserialize a user from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param u user to be deserialized + */ +void from_json(const nlohmann::json& j, user& u); + +/** + * @brief helper function to deserialize a user_identified from json + * + * @see https://github.com/nlohmann/json#arbitrary-types-conversions + * + * @param j output json object + * @param u user to be deserialized + */ +void from_json(const nlohmann::json& j, user_identified& u); + +/** A group of users */ +typedef std::unordered_map user_map; + +}; diff --git a/3rdParty/dpp/utility.h b/3rdParty/dpp/utility.h index a4c17f6051..963e9d0161 100644 --- a/3rdParty/dpp/utility.h +++ b/3rdParty/dpp/utility.h @@ -1,487 +1,487 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include - -/** - * @brief The main namespace for D++ functions, classes and types - */ -namespace dpp { - /** - * @brief Utility helper functions, generally for logging, running programs, time/date manipulation, etc - */ - namespace utility { - - /** - * @brief Timestamp formats for dpp::utility::timestamp() - * - * @note These values are the actual character values specified by the Discord API - * and should not be changed unless the Discord API changes the specification! - * They have been sorted into numerical order of their ASCII value to keep C++ happy. - */ - enum time_format : uint8_t { - /// "20 April 2021" - Long Date - tf_long_date = 'D', - /// "Tuesday, 20 April 2021 16:20" - Long Date/Time - tf_long_datetime = 'F', - /// "2 months ago" - Relative Time - tf_relative_time = 'R', - /// "16:20:30" - Long Time - tf_long_time = 'T', - /// "20/04/2021" - Short Date - tf_short_date = 'd', - /// "20 April 2021 16:20" - Short Date/Time - tf_short_datetime = 'f', - /// "16:20" - Short Time - tf_short_time = 't', - }; - - /** - * @brief The base URL for CDN content such as profile pictures and guild icons. - */ - const std::string cdn_host = "https://cdn.discordapp.com"; - - /** - * @brief Callback for the results of a command executed via dpp::utility::exec - */ - typedef std::function cmd_result_t; - - /** - * @brief Run a commandline program asynchronously. The command line program - * is spawned in a separate std::thread, and when complete, its output from - * stdout is passed to the callback function in its string parameter. For example - * ``` - * dpp::utility::exec("/bin/ls", {"-al"}, [](const std::string& output) { - * std::cout << "Output of 'ls -al': " << output << "\n"; - * }); - * ``` - * - * @param cmd The command to run. - * @param parameters Command line parameters. Each will be escaped using `std::quoted`. - * @param callback The callback to call on completion. - */ - void DPP_EXPORT exec(const std::string& cmd, std::vector parameters = {}, cmd_result_t callback = {}); - - /** - * @brief Return a mentionable timestamp (used in a message). These timestamps will display the given timestamp in the user's timezone and locale. - * - * @param ts Time stamp to convert - * @param tf Format of timestamp using dpp::utility::time_format - * @return std::string The formatted timestamp - */ - std::string DPP_EXPORT timestamp(time_t ts, time_format tf = tf_short_datetime); - - /** - * @brief Returns current date and time - * - * @return std::string Current date and time in "Y-m-d H:M:S" format - */ - std::string DPP_EXPORT current_date_time(); - /** - * @brief Convert a dpp::loglevel enum value to a string - * - * @param in log level to convert - * @return std::string string form of log level - */ - std::string DPP_EXPORT loglevel(dpp::loglevel in); - - /** - * @brief Store a 128 bit icon hash (profile picture, server icon etc) - * as a 128 bit binary value made of two uint64_t. - * Has a constructor to build one from a string, and a method to fetch - * the value back in string form. - */ - struct DPP_EXPORT iconhash { - - uint64_t first; //!< High 64 bits - uint64_t second; //!< Low 64 bits - - /** - * @brief Construct a new iconhash object - * @param _first Leftmost portion of the hash value - * @param _second Rightmost portion of the hash value - */ - iconhash(uint64_t _first = 0, uint64_t _second = 0); - - /** - * @brief Construct a new iconhash object - */ - iconhash(const iconhash&); - - /** - * @brief Destroy the iconhash object - */ - ~iconhash(); - - /** - * @brief Construct a new iconhash object - * - * @param hash String hash to construct from. - * Must contain a 32 character hex string. - * - * @throws std::length_error if the provided - * string is not exactly 32 characters long. - */ - iconhash(const std::string &hash); - - /** - * @brief Assign from std::string - * - * @param assignment string to assign from. - * - * @throws std::length_error if the provided - * string is not exactly 32 characters long. - */ - iconhash& operator=(const std::string &assignment); - - /** - * @brief Check if one iconhash is equal to another - * - * @param other other iconhash to compare - * @return True if the iconhash objects match - */ - bool operator==(const iconhash& other) const; - - /** - * @brief Change value of iconhash object - * - * @param hash String hash to change to. - * Must contain a 32 character hex string. - * - * @throws std::length_error if the provided - * string is not exactly 32 characters long. - */ - void set(const std::string &hash); - - /** - * @brief Convert iconhash back to 32 character - * string value. - * - * @return std::string Hash value - */ - std::string to_string() const; - }; - - /** - * @brief Return the current time with fractions of seconds. - * This is a unix epoch time with the fractional seconds part - * after the decimal place. - * - * @return double time with fractional seconds - */ - double DPP_EXPORT time_f(); - - /** - * @brief Returns true if D++ was built with voice support - * - * @return bool True if voice support is compiled in (libsodium/libopus) - */ - bool DPP_EXPORT has_voice(); - - /** - * @brief Convert a byte count to display value - * - * @param c number of bytes - * @return std::string display value suffixed with M, G, T where necessary - */ - std::string DPP_EXPORT bytes(uint64_t c); - - /** - * @brief A class used to represent an uptime in hours, minutes, - * seconds and days, with helper functions to convert from time_t - * and display as a string. - */ - struct DPP_EXPORT uptime { - uint16_t days; //!< Number of days - uint8_t hours; //!< Number of hours - uint8_t mins; //!< Number of minutes - uint8_t secs; //!< Number of seconds - - /** - * @brief Construct a new uptime object - */ - uptime(); - - /** - * @brief Construct a new uptime object - * - * @param diff A time_t to initialise the object from - */ - uptime(time_t diff); - - /** - * @brief Construct a new uptime object - * - * @param diff A time_t to initialise the object from - */ - uptime(double diff); - - /** - * @brief Get uptime as string - * - * @return std::string Uptime as string - */ - std::string to_string() const; - - /** - * @brief Get uptime as seconds - * - * @return uint64_t Uptime as seconds - */ - uint64_t to_secs() const; - - /** - * @brief Get uptime as milliseconds - * - * @return uint64_t Uptime as milliseconds - */ - uint64_t to_msecs() const; - }; - - /** - * @brief Convert doubles to RGB for sending in embeds - * - * @param red red value, between 0 and 1 inclusive - * @param green green value, between 0 and 1 inclusive - * @param blue blue value, between 0 and 1 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT rgb(double red, double green, double blue); - - /** - * @brief Convert ints to RGB for sending in embeds - * - * @param red red value, between 0 and 255 inclusive - * @param green green value, between 0 and 255 inclusive - * @param blue blue value, between 0 and 255 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT rgb(int red, int green, int blue); - - /** - * @brief Convert doubles to CMYK for sending in embeds - * - * @param c cyan value, between 0 and 1 inclusive - * @param m magenta value, between 0 and 1 inclusive - * @param y yellow value, between 0 and 1 inclusive - * @param k key (black) value, between 0 and 1 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT cmyk(double c, double m, double y, double k); - - /** - * @brief Convert ints to CMYK for sending in embeds - * - * @param c cyan value, between 0 and 255 inclusive - * @param m magenta value, between 0 and 255 inclusive - * @param y yellow value, between 0 and 255 inclusive - * @param k key (black) value, between 0 and 255 inclusive - * @return uint32_t returned integer colour value - */ - uint32_t DPP_EXPORT cmyk(int c, int m, int y, int k); - - /** - * @brief Output hex values of a section of memory for debugging - * - * @param data The start of the data to display - * @param length The length of data to display - */ - std::string DPP_EXPORT debug_dump(uint8_t* data, size_t length); - - /** - * @brief Returns the length of a UTF-8 string in codepoints - * - * @param str string to count length of - * @return size_t length of string (0 for invalid utf8) - */ - size_t DPP_EXPORT utf8len(const std::string &str); - - /** - * @brief Return substring of a UTF-8 encoded string in codepoints - * - * @param str string to return substring from - * @param start start codepoint offset - * @param length length in codepoints - * @return std::string Substring in UTF-8 or empty string if invalid UTF-8 passed in - */ - std::string DPP_EXPORT utf8substr(const std::string& str, std::string::size_type start, std::string::size_type length); - - /** - * @brief Read a whole file into a std::string. - * Be sure you have enough memory to read the file, if you are reading a large file. - * @note Be aware this function can block! If you are regularly reading large files, consider caching them. - * @param filename The path to the file to read - * @return std::string The file contents - * @throw dpp::exception on failure to read the entire file - */ - std::string DPP_EXPORT read_file(const std::string& filename); - - /** - * @brief Validate a string value - * In the event the length of the string is less than _min, then an exception of type dpp:length_exception - * will be thrown. If the string is longer than _max UTF8 codepoints it will be truncated to fit. - * - * @param value The value to validate - * @param _min Minimum length - * @param _max Maximum length - * @param exception_message Exception message to throw if value length < _min - * @return std::string Validated string, truncated if necessary. - * @throw dpp::length_exception if value UTF8 length < _min - */ - std::string DPP_EXPORT validate(const std::string& value, size_t _min, size_t _max, const std::string& exception_message); - - /** - * @brief Return the url parameter for an avatar size, or empty if the size is 0 - * - * @param size size to generate url parameter for - * @return std::string url parameter - */ - std::string DPP_EXPORT avatar_size(uint32_t size); - - /** - * @brief Split (tokenize) a string into a vector, using the given separators - * - * @param in Input string - * @param sep Separator characters - * @return std::vector Tokenized strings - */ - std::vector DPP_EXPORT tokenize(std::string const &in, const char* sep = "\r\n"); - - /** - * @brief Create a bot invite - * - * @param bot_id Bot ID - * @param permissions Permission bitmask of the bot to invite - * @param scopes Scopes to use - * @return Invite URL - */ - std::string DPP_EXPORT bot_invite_url(const snowflake bot_id, const uint64_t permissions = 0, const std::vector& scopes = {"bot", "applications.commands"}); - - /** - * @brief Escapes Discord's markdown sequences in a string - * - * @param text Text to escape - * @param escape_code_blocks If set to false, then code blocks are not escaped. - * This means that you can still use a code block, and the text within will be left as-is. - * If set to true, code blocks will also be escaped so that ` symbol may be used as a normal - * character. - * @return std::string The text with the markdown special characters escaped with a backslash - */ - std::string DPP_EXPORT markdown_escape(const std::string& text, bool escape_code_blocks = false); - - /** - * @brief Encodes a url parameter similar to [php urlencode()](https://www.php.net/manual/en/function.urlencode.php) - * - * @param value String to encode - * @return std::string URL encoded string - */ - std::string DPP_EXPORT url_encode(const std::string &value); - - /** - * @brief Create a mentionable slashcommand (used in a message). - * @param command_id The ID of the slashcommand - * @param command_name The command name - * @param subcommand Optional: The subcommand name (for mentioning a subcommand) - * @return std::string The formatted mention - */ - std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand = ""); - - /** - * @brief Create a mentionable slashcommand (used in a message). - * @param command_id The ID of the slashcommand - * @param command_name The command name - * @param subcommand_group The subcommand group name - * @param subcommand The subcommand name - * @return std::string The formatted mention of the slashcommand with its subcommand - */ - std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand_group, const std::string &subcommand); - - /** - * @brief Create a mentionable user. - * @param id The ID of the user. - * @return std::string The formatted mention of the user. - */ - std::string DPP_EXPORT user_mention(const snowflake& id); - - /** - * @brief Create a mentionable channel. - * @param id The ID of the channel. - * @return std::string The formatted mention of the channel. - */ - std::string DPP_EXPORT channel_mention(const snowflake& id); - - /** - * @brief Create a mentionable emoji - * @param name The name of the emoji. - * @param id The ID of the emoji. - * @param is_animated is emoji animated. - * @return std::string The formatted mention of the emoji. - */ - std::string DPP_EXPORT emoji_mention(const std::string& name, const snowflake& id, bool is_animated = false); - - /** - * @brief Create a mentionable role. - * @param id The ID of the role. - * @return std::string The formatted mention of the role. - */ - std::string DPP_EXPORT role_mention(const snowflake& id); - - /** - * @brief Returns the library's version string - * - * @return std::string version - */ - std::string DPP_EXPORT version(); - - /** - * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. - * Entries with empty key names or values are omitted. - * - * @param parameters parameters to create a url query string for - * @return std::string A correctly encoded url query string - */ - std::string DPP_EXPORT make_url_parameters(const std::map& parameters); - - /** - * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. - * Entries with empty key names or zero values are omitted. - * - * @param parameters parameters to create a url query string for - * @return std::string A correctly encoded url query string - */ - std::string DPP_EXPORT make_url_parameters(const std::map& parameters); - - /** - * @brief Set the name of the current thread for debugging and statistical reporting - * - * @param name New name to set - */ - void DPP_EXPORT set_thread_name(const std::string& name); - - }; -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * @brief The main namespace for D++ functions, classes and types + */ +namespace dpp { + /** + * @brief Utility helper functions, generally for logging, running programs, time/date manipulation, etc + */ + namespace utility { + + /** + * @brief Timestamp formats for dpp::utility::timestamp() + * + * @note These values are the actual character values specified by the Discord API + * and should not be changed unless the Discord API changes the specification! + * They have been sorted into numerical order of their ASCII value to keep C++ happy. + */ + enum time_format : uint8_t { + /// "20 April 2021" - Long Date + tf_long_date = 'D', + /// "Tuesday, 20 April 2021 16:20" - Long Date/Time + tf_long_datetime = 'F', + /// "2 months ago" - Relative Time + tf_relative_time = 'R', + /// "16:20:30" - Long Time + tf_long_time = 'T', + /// "20/04/2021" - Short Date + tf_short_date = 'd', + /// "20 April 2021 16:20" - Short Date/Time + tf_short_datetime = 'f', + /// "16:20" - Short Time + tf_short_time = 't', + }; + + /** + * @brief The base URL for CDN content such as profile pictures and guild icons. + */ + const std::string cdn_host = "https://cdn.discordapp.com"; + + /** + * @brief Callback for the results of a command executed via dpp::utility::exec + */ + typedef std::function cmd_result_t; + + /** + * @brief Run a commandline program asynchronously. The command line program + * is spawned in a separate std::thread, and when complete, its output from + * stdout is passed to the callback function in its string parameter. For example + * ``` + * dpp::utility::exec("/bin/ls", {"-al"}, [](const std::string& output) { + * std::cout << "Output of 'ls -al': " << output << "\n"; + * }); + * ``` + * + * @param cmd The command to run. + * @param parameters Command line parameters. Each will be escaped using `std::quoted`. + * @param callback The callback to call on completion. + */ + void DPP_EXPORT exec(const std::string& cmd, std::vector parameters = {}, cmd_result_t callback = {}); + + /** + * @brief Return a mentionable timestamp (used in a message). These timestamps will display the given timestamp in the user's timezone and locale. + * + * @param ts Time stamp to convert + * @param tf Format of timestamp using dpp::utility::time_format + * @return std::string The formatted timestamp + */ + std::string DPP_EXPORT timestamp(time_t ts, time_format tf = tf_short_datetime); + + /** + * @brief Returns current date and time + * + * @return std::string Current date and time in "Y-m-d H:M:S" format + */ + std::string DPP_EXPORT current_date_time(); + /** + * @brief Convert a dpp::loglevel enum value to a string + * + * @param in log level to convert + * @return std::string string form of log level + */ + std::string DPP_EXPORT loglevel(dpp::loglevel in); + + /** + * @brief Store a 128 bit icon hash (profile picture, server icon etc) + * as a 128 bit binary value made of two uint64_t. + * Has a constructor to build one from a string, and a method to fetch + * the value back in string form. + */ + struct DPP_EXPORT iconhash { + + uint64_t first; //!< High 64 bits + uint64_t second; //!< Low 64 bits + + /** + * @brief Construct a new iconhash object + * @param _first Leftmost portion of the hash value + * @param _second Rightmost portion of the hash value + */ + iconhash(uint64_t _first = 0, uint64_t _second = 0); + + /** + * @brief Construct a new iconhash object + */ + iconhash(const iconhash&); + + /** + * @brief Destroy the iconhash object + */ + ~iconhash(); + + /** + * @brief Construct a new iconhash object + * + * @param hash String hash to construct from. + * Must contain a 32 character hex string. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + iconhash(const std::string &hash); + + /** + * @brief Assign from std::string + * + * @param assignment string to assign from. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + iconhash& operator=(const std::string &assignment); + + /** + * @brief Check if one iconhash is equal to another + * + * @param other other iconhash to compare + * @return True if the iconhash objects match + */ + bool operator==(const iconhash& other) const; + + /** + * @brief Change value of iconhash object + * + * @param hash String hash to change to. + * Must contain a 32 character hex string. + * + * @throws std::length_error if the provided + * string is not exactly 32 characters long. + */ + void set(const std::string &hash); + + /** + * @brief Convert iconhash back to 32 character + * string value. + * + * @return std::string Hash value + */ + std::string to_string() const; + }; + + /** + * @brief Return the current time with fractions of seconds. + * This is a unix epoch time with the fractional seconds part + * after the decimal place. + * + * @return double time with fractional seconds + */ + double DPP_EXPORT time_f(); + + /** + * @brief Returns true if D++ was built with voice support + * + * @return bool True if voice support is compiled in (libsodium/libopus) + */ + bool DPP_EXPORT has_voice(); + + /** + * @brief Convert a byte count to display value + * + * @param c number of bytes + * @return std::string display value suffixed with M, G, T where necessary + */ + std::string DPP_EXPORT bytes(uint64_t c); + + /** + * @brief A class used to represent an uptime in hours, minutes, + * seconds and days, with helper functions to convert from time_t + * and display as a string. + */ + struct DPP_EXPORT uptime { + uint16_t days; //!< Number of days + uint8_t hours; //!< Number of hours + uint8_t mins; //!< Number of minutes + uint8_t secs; //!< Number of seconds + + /** + * @brief Construct a new uptime object + */ + uptime(); + + /** + * @brief Construct a new uptime object + * + * @param diff A time_t to initialise the object from + */ + uptime(time_t diff); + + /** + * @brief Construct a new uptime object + * + * @param diff A time_t to initialise the object from + */ + uptime(double diff); + + /** + * @brief Get uptime as string + * + * @return std::string Uptime as string + */ + std::string to_string() const; + + /** + * @brief Get uptime as seconds + * + * @return uint64_t Uptime as seconds + */ + uint64_t to_secs() const; + + /** + * @brief Get uptime as milliseconds + * + * @return uint64_t Uptime as milliseconds + */ + uint64_t to_msecs() const; + }; + + /** + * @brief Convert doubles to RGB for sending in embeds + * + * @param red red value, between 0 and 1 inclusive + * @param green green value, between 0 and 1 inclusive + * @param blue blue value, between 0 and 1 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT rgb(double red, double green, double blue); + + /** + * @brief Convert ints to RGB for sending in embeds + * + * @param red red value, between 0 and 255 inclusive + * @param green green value, between 0 and 255 inclusive + * @param blue blue value, between 0 and 255 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT rgb(int red, int green, int blue); + + /** + * @brief Convert doubles to CMYK for sending in embeds + * + * @param c cyan value, between 0 and 1 inclusive + * @param m magenta value, between 0 and 1 inclusive + * @param y yellow value, between 0 and 1 inclusive + * @param k key (black) value, between 0 and 1 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT cmyk(double c, double m, double y, double k); + + /** + * @brief Convert ints to CMYK for sending in embeds + * + * @param c cyan value, between 0 and 255 inclusive + * @param m magenta value, between 0 and 255 inclusive + * @param y yellow value, between 0 and 255 inclusive + * @param k key (black) value, between 0 and 255 inclusive + * @return uint32_t returned integer colour value + */ + uint32_t DPP_EXPORT cmyk(int c, int m, int y, int k); + + /** + * @brief Output hex values of a section of memory for debugging + * + * @param data The start of the data to display + * @param length The length of data to display + */ + std::string DPP_EXPORT debug_dump(uint8_t* data, size_t length); + + /** + * @brief Returns the length of a UTF-8 string in codepoints + * + * @param str string to count length of + * @return size_t length of string (0 for invalid utf8) + */ + size_t DPP_EXPORT utf8len(const std::string &str); + + /** + * @brief Return substring of a UTF-8 encoded string in codepoints + * + * @param str string to return substring from + * @param start start codepoint offset + * @param length length in codepoints + * @return std::string Substring in UTF-8 or empty string if invalid UTF-8 passed in + */ + std::string DPP_EXPORT utf8substr(const std::string& str, std::string::size_type start, std::string::size_type length); + + /** + * @brief Read a whole file into a std::string. + * Be sure you have enough memory to read the file, if you are reading a large file. + * @note Be aware this function can block! If you are regularly reading large files, consider caching them. + * @param filename The path to the file to read + * @return std::string The file contents + * @throw dpp::exception on failure to read the entire file + */ + std::string DPP_EXPORT read_file(const std::string& filename); + + /** + * @brief Validate a string value + * In the event the length of the string is less than _min, then an exception of type dpp:length_exception + * will be thrown. If the string is longer than _max UTF8 codepoints it will be truncated to fit. + * + * @param value The value to validate + * @param _min Minimum length + * @param _max Maximum length + * @param exception_message Exception message to throw if value length < _min + * @return std::string Validated string, truncated if necessary. + * @throw dpp::length_exception if value UTF8 length < _min + */ + std::string DPP_EXPORT validate(const std::string& value, size_t _min, size_t _max, const std::string& exception_message); + + /** + * @brief Return the url parameter for an avatar size, or empty if the size is 0 + * + * @param size size to generate url parameter for + * @return std::string url parameter + */ + std::string DPP_EXPORT avatar_size(uint32_t size); + + /** + * @brief Split (tokenize) a string into a vector, using the given separators + * + * @param in Input string + * @param sep Separator characters + * @return std::vector Tokenized strings + */ + std::vector DPP_EXPORT tokenize(std::string const &in, const char* sep = "\r\n"); + + /** + * @brief Create a bot invite + * + * @param bot_id Bot ID + * @param permissions Permission bitmask of the bot to invite + * @param scopes Scopes to use + * @return Invite URL + */ + std::string DPP_EXPORT bot_invite_url(const snowflake bot_id, const uint64_t permissions = 0, const std::vector& scopes = {"bot", "applications.commands"}); + + /** + * @brief Escapes Discord's markdown sequences in a string + * + * @param text Text to escape + * @param escape_code_blocks If set to false, then code blocks are not escaped. + * This means that you can still use a code block, and the text within will be left as-is. + * If set to true, code blocks will also be escaped so that ` symbol may be used as a normal + * character. + * @return std::string The text with the markdown special characters escaped with a backslash + */ + std::string DPP_EXPORT markdown_escape(const std::string& text, bool escape_code_blocks = false); + + /** + * @brief Encodes a url parameter similar to [php urlencode()](https://www.php.net/manual/en/function.urlencode.php) + * + * @param value String to encode + * @return std::string URL encoded string + */ + std::string DPP_EXPORT url_encode(const std::string &value); + + /** + * @brief Create a mentionable slashcommand (used in a message). + * @param command_id The ID of the slashcommand + * @param command_name The command name + * @param subcommand Optional: The subcommand name (for mentioning a subcommand) + * @return std::string The formatted mention + */ + std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand = ""); + + /** + * @brief Create a mentionable slashcommand (used in a message). + * @param command_id The ID of the slashcommand + * @param command_name The command name + * @param subcommand_group The subcommand group name + * @param subcommand The subcommand name + * @return std::string The formatted mention of the slashcommand with its subcommand + */ + std::string DPP_EXPORT slashcommand_mention(snowflake command_id, const std::string &command_name, const std::string &subcommand_group, const std::string &subcommand); + + /** + * @brief Create a mentionable user. + * @param id The ID of the user. + * @return std::string The formatted mention of the user. + */ + std::string DPP_EXPORT user_mention(const snowflake& id); + + /** + * @brief Create a mentionable channel. + * @param id The ID of the channel. + * @return std::string The formatted mention of the channel. + */ + std::string DPP_EXPORT channel_mention(const snowflake& id); + + /** + * @brief Create a mentionable emoji + * @param name The name of the emoji. + * @param id The ID of the emoji. + * @param is_animated is emoji animated. + * @return std::string The formatted mention of the emoji. + */ + std::string DPP_EXPORT emoji_mention(const std::string& name, const snowflake& id, bool is_animated = false); + + /** + * @brief Create a mentionable role. + * @param id The ID of the role. + * @return std::string The formatted mention of the role. + */ + std::string DPP_EXPORT role_mention(const snowflake& id); + + /** + * @brief Returns the library's version string + * + * @return std::string version + */ + std::string DPP_EXPORT version(); + + /** + * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. + * Entries with empty key names or values are omitted. + * + * @param parameters parameters to create a url query string for + * @return std::string A correctly encoded url query string + */ + std::string DPP_EXPORT make_url_parameters(const std::map& parameters); + + /** + * @brief Build a URL parameter string e.g. "?a=b&c=d&e=f" from a map of key/value pairs. + * Entries with empty key names or zero values are omitted. + * + * @param parameters parameters to create a url query string for + * @return std::string A correctly encoded url query string + */ + std::string DPP_EXPORT make_url_parameters(const std::map& parameters); + + /** + * @brief Set the name of the current thread for debugging and statistical reporting + * + * @param name New name to set + */ + void DPP_EXPORT set_thread_name(const std::string& name); + + }; +}; diff --git a/3rdParty/dpp/version.h b/3rdParty/dpp/version.h index dbc615b2f7..bb8d69338a 100644 --- a/3rdParty/dpp/version.h +++ b/3rdParty/dpp/version.h @@ -1,31 +1,31 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -#if !defined(DPP_VERSION_LONG) -#define DPP_VERSION_LONG 0x00100022 -#define DPP_VERSION_SHORT 100022 -#define DPP_VERSION_TEXT "D++ 10.0.22 (01-Nov-2022)" - -#define DPP_VERSION_MAJOR ((DPP_VERSION_LONG & 0x00ff0000) >> 16) -#define DPP_VERSION_MINOR ((DPP_VERSION_LONG & 0x0000ff00) >> 8) -#define DPP_VERSION_PATCH (DPP_VERSION_LONG & 0x000000ff) -#endif +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +#if !defined(DPP_VERSION_LONG) +#define DPP_VERSION_LONG 0x00100022 +#define DPP_VERSION_SHORT 100022 +#define DPP_VERSION_TEXT "D++ 10.0.22 (01-Nov-2022)" + +#define DPP_VERSION_MAJOR ((DPP_VERSION_LONG & 0x00ff0000) >> 16) +#define DPP_VERSION_MINOR ((DPP_VERSION_LONG & 0x0000ff00) >> 8) +#define DPP_VERSION_PATCH (DPP_VERSION_LONG & 0x000000ff) +#endif diff --git a/3rdParty/dpp/voiceregion.h b/3rdParty/dpp/voiceregion.h index 39c88057aa..1ca805b06a 100644 --- a/3rdParty/dpp/voiceregion.h +++ b/3rdParty/dpp/voiceregion.h @@ -1,119 +1,119 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Flags related to a voice region - */ -enum voiceregion_flags { - v_optimal = 0x00000001, - v_deprecated = 0x00000010, - v_custom = 0x00000100, - v_vip = 0x00001000 -}; - -/** - * @brief Represents a voice region on discord - */ -class DPP_EXPORT voiceregion : public json_interface { -public: - /** - * @brief Voice server ID - */ - std::string id; - - /** - * @brief Voice server name - */ - std::string name; - - /** - * @brief Flags bitmap - */ - uint8_t flags; - - /** - * @brief Construct a new voiceregion object - */ - voiceregion(); - - /** - * @brief Destroy the voiceregion object - */ - virtual ~voiceregion() = default; - - /** - * @brief Fill object properties from JSON - * - * @param j JSON to fill from - * @return voiceregion& Reference to self - */ - voiceregion& fill_from_json(nlohmann::json* j); - - /** - * @brief Build a json string for this object - * - * @param with_id Add ID to output - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief True if is the optimal voice server - * - * @return true if optimal - */ - bool is_optimal() const; - - /** - * @brief True if is a deprecated voice server - * - * @return true if deprecated - */ - bool is_deprecated() const; - - /** - * @brief True if is a custom voice server - * - * @return true if custom - */ - bool is_custom() const; - - /** - * @brief True if is a VIP voice server - * - * @return true if VIP - */ - bool is_vip() const; -}; - -/** - * @brief A group of voice regions - */ -typedef std::unordered_map voiceregion_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Flags related to a voice region + */ +enum voiceregion_flags { + v_optimal = 0x00000001, + v_deprecated = 0x00000010, + v_custom = 0x00000100, + v_vip = 0x00001000 +}; + +/** + * @brief Represents a voice region on discord + */ +class DPP_EXPORT voiceregion : public json_interface { +public: + /** + * @brief Voice server ID + */ + std::string id; + + /** + * @brief Voice server name + */ + std::string name; + + /** + * @brief Flags bitmap + */ + uint8_t flags; + + /** + * @brief Construct a new voiceregion object + */ + voiceregion(); + + /** + * @brief Destroy the voiceregion object + */ + virtual ~voiceregion() = default; + + /** + * @brief Fill object properties from JSON + * + * @param j JSON to fill from + * @return voiceregion& Reference to self + */ + voiceregion& fill_from_json(nlohmann::json* j); + + /** + * @brief Build a json string for this object + * + * @param with_id Add ID to output + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief True if is the optimal voice server + * + * @return true if optimal + */ + bool is_optimal() const; + + /** + * @brief True if is a deprecated voice server + * + * @return true if deprecated + */ + bool is_deprecated() const; + + /** + * @brief True if is a custom voice server + * + * @return true if custom + */ + bool is_custom() const; + + /** + * @brief True if is a VIP voice server + * + * @return true if VIP + */ + bool is_vip() const; +}; + +/** + * @brief A group of voice regions + */ +typedef std::unordered_map voiceregion_map; + +}; diff --git a/3rdParty/dpp/voicestate.h b/3rdParty/dpp/voicestate.h index 82eebbe378..6edabe6307 100644 --- a/3rdParty/dpp/voicestate.h +++ b/3rdParty/dpp/voicestate.h @@ -1,110 +1,110 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Bit mask flags relating to voice states - */ -enum voicestate_flags { - vs_deaf = 0b00000001, //!< Deafened by the server - vs_mute = 0b00000010, //!< Muted by the server - vs_self_mute = 0b00000100, //!< Locally Muted - vs_self_deaf = 0b00001000, //!< Locally deafened - vs_self_stream = 0b00010000, //!< Whether this user is streaming using "Go Live" - vs_self_video = 0b00100000, //!< Whether this user's camera is enabled - vs_suppress = 0b01000000 //!< Whether this user's permission to speak is denied -}; - -/** - * @brief Represents the voice state of a user on a guild - * These are stored in the dpp::guild object, and accessible there, - * or via dpp::channel::get_voice_members - */ -class DPP_EXPORT voicestate : public json_interface { -public: - class discord_client* shard; //!< Owning shard - snowflake guild_id; //!< Optional: the guild id this voice state is for - snowflake channel_id; //!< the channel id this user is connected to (may be empty) - snowflake user_id; //!< the user id this voice state is for - std::string session_id; //!< the session id for this voice state - uint8_t flags; //!< Voice state flags (see dpp::voicestate_flags) - time_t request_to_speak; //!< The time at which the user requested to speak, or 0 - - /** - * @brief Construct a new voicestate object - */ - voicestate(); - - /** - * @brief Destroy the voicestate object - */ - virtual ~voicestate() = default; - - /** - * @brief Fill voicestate object from json data - * - * @param j JSON data to fill from - * @return voicestate& Reference to self - */ - voicestate& fill_from_json(nlohmann::json* j); - - /** - * @brief Build json representation of the object - * - * @param with_id Add ID to output - * @return std::string JSON string - */ - virtual std::string build_json(bool with_id = false) const; - - /// Return true if the user is deafened by the server - bool is_deaf() const; - - /// Return true if the user is muted by the server - bool is_mute() const; - - /// Return true if user muted themselves - bool is_self_mute() const; - - /// Return true if user deafened themselves - bool is_self_deaf() const; - - /// Return true if the user is streaming using "Go Live" - bool self_stream() const; - - /// Return true if the user's camera is enabled - bool self_video() const; - - /// Return true if user is suppressed. - /// "HELP HELP I'M BEING SUPPRESSED!" - bool is_suppressed() const; -}; - -/** A container of voicestates */ -typedef std::unordered_map voicestate_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Bit mask flags relating to voice states + */ +enum voicestate_flags { + vs_deaf = 0b00000001, //!< Deafened by the server + vs_mute = 0b00000010, //!< Muted by the server + vs_self_mute = 0b00000100, //!< Locally Muted + vs_self_deaf = 0b00001000, //!< Locally deafened + vs_self_stream = 0b00010000, //!< Whether this user is streaming using "Go Live" + vs_self_video = 0b00100000, //!< Whether this user's camera is enabled + vs_suppress = 0b01000000 //!< Whether this user's permission to speak is denied +}; + +/** + * @brief Represents the voice state of a user on a guild + * These are stored in the dpp::guild object, and accessible there, + * or via dpp::channel::get_voice_members + */ +class DPP_EXPORT voicestate : public json_interface { +public: + class discord_client* shard; //!< Owning shard + snowflake guild_id; //!< Optional: the guild id this voice state is for + snowflake channel_id; //!< the channel id this user is connected to (may be empty) + snowflake user_id; //!< the user id this voice state is for + std::string session_id; //!< the session id for this voice state + uint8_t flags; //!< Voice state flags (see dpp::voicestate_flags) + time_t request_to_speak; //!< The time at which the user requested to speak, or 0 + + /** + * @brief Construct a new voicestate object + */ + voicestate(); + + /** + * @brief Destroy the voicestate object + */ + virtual ~voicestate() = default; + + /** + * @brief Fill voicestate object from json data + * + * @param j JSON data to fill from + * @return voicestate& Reference to self + */ + voicestate& fill_from_json(nlohmann::json* j); + + /** + * @brief Build json representation of the object + * + * @param with_id Add ID to output + * @return std::string JSON string + */ + virtual std::string build_json(bool with_id = false) const; + + /// Return true if the user is deafened by the server + bool is_deaf() const; + + /// Return true if the user is muted by the server + bool is_mute() const; + + /// Return true if user muted themselves + bool is_self_mute() const; + + /// Return true if user deafened themselves + bool is_self_deaf() const; + + /// Return true if the user is streaming using "Go Live" + bool self_stream() const; + + /// Return true if the user's camera is enabled + bool self_video() const; + + /// Return true if user is suppressed. + /// "HELP HELP I'M BEING SUPPRESSED!" + bool is_suppressed() const; +}; + +/** A container of voicestates */ +typedef std::unordered_map voicestate_map; + +}; diff --git a/3rdParty/dpp/webhook.h b/3rdParty/dpp/webhook.h index 003f0b6cf8..98fa1767fc 100644 --- a/3rdParty/dpp/webhook.h +++ b/3rdParty/dpp/webhook.h @@ -1,113 +1,113 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Defines types of webhook - */ -enum webhook_type { - w_incoming = 1, //!< Incoming webhook - w_channel_follower = 2 //!< Channel following webhook -}; - -/** - * @brief Represents a discord webhook - */ -class DPP_EXPORT webhook : public managed, public json_interface { -public: - uint8_t type; //!< the type of the webhook - snowflake guild_id; //!< Optional: the guild id this webhook is for - snowflake channel_id; //!< the channel id this webhook is for - snowflake user_id; //!< Optional: the user this webhook was created by (not returned when getting a webhook with its token) - std::string name; //!< the default name of the webhook (may be empty) - std::string avatar; //!< the default avatar of the webhook (may be empty) - std::string token; //!< Optional: the secure token of the webhook (returned for Incoming Webhooks) - snowflake application_id; //!< the bot/OAuth2 application that created this webhook (may be empty) - std::string* image_data; //!< base64 encoded image data if uploading a new image - - /** - * @brief Construct a new webhook object - */ - webhook(); - - /** - * @brief Construct a new webhook object using the Webhook URL provided by Discord - * - * @param webhook_url a fully qualified web address of an existing webhook - */ - webhook(const std::string& webhook_url); - - /** - * @brief Construct a new webhook object using the webhook ID and the webhook token - * - * @param webhook_id id taken from a link of an existing webhook - * @param webhook_token token taken from a link of an existing webhook - */ - webhook(const snowflake webhook_id, const std::string& webhook_token); - - /** - * @brief Destroy the webhook object - */ - ~webhook(); - - /** - * @brief Fill in object from json data - * - * @param j JSON data - * @return webhook& Reference to self - */ - webhook& fill_from_json(nlohmann::json* j); - - /** - * @brief Build JSON string from object - * - * @param with_id Include the ID of the webhook in the json - * @return std::string JSON encoded object - */ - virtual std::string build_json(bool with_id = false) const; - - /** - * @brief Base64 encode image data and allocate it to image_data - * - * @param image_blob Binary image data - * @param type Image type - * @param is_base64_encoded True if the image data is already base64 encoded - * @return webhook& Reference to self - * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes - */ - webhook& load_image(const std::string &image_blob, const image_type type, bool is_base64_encoded = false); -}; - -/** - * @brief A group of webhooks - */ -typedef std::unordered_map webhook_map; - -}; +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Defines types of webhook + */ +enum webhook_type { + w_incoming = 1, //!< Incoming webhook + w_channel_follower = 2 //!< Channel following webhook +}; + +/** + * @brief Represents a discord webhook + */ +class DPP_EXPORT webhook : public managed, public json_interface { +public: + uint8_t type; //!< the type of the webhook + snowflake guild_id; //!< Optional: the guild id this webhook is for + snowflake channel_id; //!< the channel id this webhook is for + snowflake user_id; //!< Optional: the user this webhook was created by (not returned when getting a webhook with its token) + std::string name; //!< the default name of the webhook (may be empty) + std::string avatar; //!< the default avatar of the webhook (may be empty) + std::string token; //!< Optional: the secure token of the webhook (returned for Incoming Webhooks) + snowflake application_id; //!< the bot/OAuth2 application that created this webhook (may be empty) + std::string* image_data; //!< base64 encoded image data if uploading a new image + + /** + * @brief Construct a new webhook object + */ + webhook(); + + /** + * @brief Construct a new webhook object using the Webhook URL provided by Discord + * + * @param webhook_url a fully qualified web address of an existing webhook + */ + webhook(const std::string& webhook_url); + + /** + * @brief Construct a new webhook object using the webhook ID and the webhook token + * + * @param webhook_id id taken from a link of an existing webhook + * @param webhook_token token taken from a link of an existing webhook + */ + webhook(const snowflake webhook_id, const std::string& webhook_token); + + /** + * @brief Destroy the webhook object + */ + ~webhook(); + + /** + * @brief Fill in object from json data + * + * @param j JSON data + * @return webhook& Reference to self + */ + webhook& fill_from_json(nlohmann::json* j); + + /** + * @brief Build JSON string from object + * + * @param with_id Include the ID of the webhook in the json + * @return std::string JSON encoded object + */ + virtual std::string build_json(bool with_id = false) const; + + /** + * @brief Base64 encode image data and allocate it to image_data + * + * @param image_blob Binary image data + * @param type Image type + * @param is_base64_encoded True if the image data is already base64 encoded + * @return webhook& Reference to self + * @throw dpp::exception Image data is larger than the maximum size of 256 kilobytes + */ + webhook& load_image(const std::string &image_blob, const image_type type, bool is_base64_encoded = false); +}; + +/** + * @brief A group of webhooks + */ +typedef std::unordered_map webhook_map; + +}; diff --git a/3rdParty/dpp/win32_safe_warnings.h b/3rdParty/dpp/win32_safe_warnings.h index c4a09d21ea..104b6660bb 100644 --- a/3rdParty/dpp/win32_safe_warnings.h +++ b/3rdParty/dpp/win32_safe_warnings.h @@ -1,32 +1,32 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once - -/* This file contains pragmas to disable warnings on win32 builds with msvc only. - * It is only included during build of D++ itself, and not when including the headers - * into a user's project. - * - * Before adding a warning here please be ABSOLUTELY SURE it is one we cannot easily fix - * and is to be silenced, thrown into the sarlacc pit to be eaten for 1000 years... - */ - -_Pragma("warning( disable : 4251 )"); // 4251 warns when we export classes or structures with stl member variables -_Pragma("warning( disable : 5105 )"); // 5105 is to do with macro warnings +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once + +/* This file contains pragmas to disable warnings on win32 builds with msvc only. + * It is only included during build of D++ itself, and not when including the headers + * into a user's project. + * + * Before adding a warning here please be ABSOLUTELY SURE it is one we cannot easily fix + * and is to be silenced, thrown into the sarlacc pit to be eaten for 1000 years... + */ + +_Pragma("warning( disable : 4251 )"); // 4251 warns when we export classes or structures with stl member variables +_Pragma("warning( disable : 5105 )"); // 5105 is to do with macro warnings diff --git a/3rdParty/dpp/wsclient.h b/3rdParty/dpp/wsclient.h index 6c1b919046..6f05840f5c 100644 --- a/3rdParty/dpp/wsclient.h +++ b/3rdParty/dpp/wsclient.h @@ -1,212 +1,212 @@ -/************************************************************************************ - * - * D++, A Lightweight C++ library for Discord - * - * Copyright 2021 Craig Edwards and D++ contributors - * (https://github.com/brainboxdotcc/DPP/graphs/contributors) - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - ************************************************************************************/ -#pragma once -#include -#include -#include -#include -#include -#include - -namespace dpp { - -/** - * @brief Websocket protocol types available on Discord - */ -enum websocket_protocol_t : uint8_t { - /** - * @brief JSON data, text, UTF-8 character set - */ - ws_json = 0, - /** - * @brief Erlang Term Format (ETF) binary protocol - */ - ws_etf = 1 -}; - -/** - * @brief Websocket connection status - */ -enum ws_state : uint8_t { - /** - * @brief Sending/receiving HTTP headers, acting as a standard HTTP connection. - * This is the state prior to receiving "HTTP/1.1 101 Switching Protocols" from the - * server side. - */ - HTTP_HEADERS, - - /** - * @brief Connected as a websocket, and "upgraded". Now talking using binary frames. - */ - CONNECTED -}; - -/** - * @brief Low-level websocket opcodes for frames - */ -enum ws_opcode : uint8_t -{ - OP_CONTINUATION = 0x00, //!< Continuation - OP_TEXT = 0x01, //!< Text frame - OP_BINARY = 0x02, //!< Binary frame - OP_CLOSE = 0x08, //!< Close notification with close code - OP_PING = 0x09, //!< Low level ping - OP_PONG = 0x0a //!< Low level pong -}; - -/** - * @brief Implements a websocket client based on the SSL client - */ -class DPP_EXPORT websocket_client : public ssl_client -{ - /** - * @brief Connection key used in the HTTP headers - */ - std::string key; - - /** - * @brief Current websocket state - */ - ws_state state; - - /** - * @brief Path part of URL for websocket - */ - std::string path; - - /** - * @brief Data opcode, represents the type of frames we send - */ - ws_opcode data_opcode; - - /** - * @brief HTTP headers received on connecting/upgrading - */ - std::map http_headers; - - /** - * @brief Parse headers for a websocket frame from the buffer. - * @param buffer The buffer to operate on. Will modify the string removing completed items from the head of the queue - * @return true if a complete header has been received - */ - bool parseheader(std::string &buffer); - - /** - * @brief Unpack a frame and pass completed frames up the stack. - * @param buffer The buffer to operate on. Gets modified to remove completed frames on the head of the buffer - * @param offset The offset to start at (reserved for future use) - * @param first True if is the first element (reserved for future use) - * @return true if a complete frame has been received - */ - bool unpack(std::string &buffer, uint32_t offset, bool first = true); - - /** - * @brief Fill a header for outbound messages - * @param outbuf The raw frame to fill - * @param sendlength The size of the data to encapsulate - * @param opcode the ws_opcode to send in the header - * @return size of filled header - */ - size_t fill_header(unsigned char* outbuf, size_t sendlength, ws_opcode opcode); - - /** - * @brief Handle ping and pong requests. - * @param ping True if this is a ping, false if it is a pong - * @param payload The ping payload, to be returned as-is for a ping - */ - void handle_ping_pong(bool ping, const std::string &payload); - -protected: - - /** - * @brief (Re)connect - */ - virtual void connect(); - - /** - * @brief Get websocket state - * @return websocket state - */ - ws_state get_state(); - -public: - - /** - * @brief Connect to a specific websocket server. - * @param hostname Hostname to connect to - * @param port Port to connect to - * @param urlpath The URL path components of the HTTP request to send - * @param opcode The encoding type to use, either OP_BINARY or OP_TEXT - * @note Voice websockets only support OP_TEXT, and other websockets must be - * OP_BINARY if you are going to send ETF. - */ - websocket_client(const std::string &hostname, const std::string &port = "443", const std::string &urlpath = "", ws_opcode opcode = OP_BINARY); - - /** - * @brief Destroy the websocket client object - */ - virtual ~websocket_client(); - - /** - * @brief Write to websocket. Encapsulates data in frames if the status is CONNECTED. - * @param data The data to send. - */ - virtual void write(const std::string &data); - - /** - * @brief Processes incoming frames from the SSL socket input buffer. - * @param buffer The buffer contents. Can modify this value removing the head elements when processed. - */ - virtual bool handle_buffer(std::string &buffer); - - /** - * @brief Close websocket - */ - virtual void close(); - - /** - * @brief Receives raw frame content only without headers - * - * @param buffer The buffer contents - * @return True if the frame was successfully handled. False if no valid frame is in the buffer. - */ - virtual bool handle_frame(const std::string &buffer); - - /** - * @brief Called upon error frame. - * - * @param errorcode The error code from the websocket server - */ - virtual void error(uint32_t errorcode); - - /** - * @brief Fires every second from the underlying socket I/O loop, used for sending websocket pings - */ - virtual void one_second_timer(); - - /** - * @brief Send OP_CLOSE error code 1000 to the other side of the connection. - * This indicates graceful close. - */ - void send_close_packet(); -}; - +/************************************************************************************ + * + * D++, A Lightweight C++ library for Discord + * + * Copyright 2021 Craig Edwards and D++ contributors + * (https://github.com/brainboxdotcc/DPP/graphs/contributors) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ************************************************************************************/ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace dpp { + +/** + * @brief Websocket protocol types available on Discord + */ +enum websocket_protocol_t : uint8_t { + /** + * @brief JSON data, text, UTF-8 character set + */ + ws_json = 0, + /** + * @brief Erlang Term Format (ETF) binary protocol + */ + ws_etf = 1 +}; + +/** + * @brief Websocket connection status + */ +enum ws_state : uint8_t { + /** + * @brief Sending/receiving HTTP headers, acting as a standard HTTP connection. + * This is the state prior to receiving "HTTP/1.1 101 Switching Protocols" from the + * server side. + */ + HTTP_HEADERS, + + /** + * @brief Connected as a websocket, and "upgraded". Now talking using binary frames. + */ + CONNECTED +}; + +/** + * @brief Low-level websocket opcodes for frames + */ +enum ws_opcode : uint8_t +{ + OP_CONTINUATION = 0x00, //!< Continuation + OP_TEXT = 0x01, //!< Text frame + OP_BINARY = 0x02, //!< Binary frame + OP_CLOSE = 0x08, //!< Close notification with close code + OP_PING = 0x09, //!< Low level ping + OP_PONG = 0x0a //!< Low level pong +}; + +/** + * @brief Implements a websocket client based on the SSL client + */ +class DPP_EXPORT websocket_client : public ssl_client +{ + /** + * @brief Connection key used in the HTTP headers + */ + std::string key; + + /** + * @brief Current websocket state + */ + ws_state state; + + /** + * @brief Path part of URL for websocket + */ + std::string path; + + /** + * @brief Data opcode, represents the type of frames we send + */ + ws_opcode data_opcode; + + /** + * @brief HTTP headers received on connecting/upgrading + */ + std::map http_headers; + + /** + * @brief Parse headers for a websocket frame from the buffer. + * @param buffer The buffer to operate on. Will modify the string removing completed items from the head of the queue + * @return true if a complete header has been received + */ + bool parseheader(std::string &buffer); + + /** + * @brief Unpack a frame and pass completed frames up the stack. + * @param buffer The buffer to operate on. Gets modified to remove completed frames on the head of the buffer + * @param offset The offset to start at (reserved for future use) + * @param first True if is the first element (reserved for future use) + * @return true if a complete frame has been received + */ + bool unpack(std::string &buffer, uint32_t offset, bool first = true); + + /** + * @brief Fill a header for outbound messages + * @param outbuf The raw frame to fill + * @param sendlength The size of the data to encapsulate + * @param opcode the ws_opcode to send in the header + * @return size of filled header + */ + size_t fill_header(unsigned char* outbuf, size_t sendlength, ws_opcode opcode); + + /** + * @brief Handle ping and pong requests. + * @param ping True if this is a ping, false if it is a pong + * @param payload The ping payload, to be returned as-is for a ping + */ + void handle_ping_pong(bool ping, const std::string &payload); + +protected: + + /** + * @brief (Re)connect + */ + virtual void connect(); + + /** + * @brief Get websocket state + * @return websocket state + */ + ws_state get_state(); + +public: + + /** + * @brief Connect to a specific websocket server. + * @param hostname Hostname to connect to + * @param port Port to connect to + * @param urlpath The URL path components of the HTTP request to send + * @param opcode The encoding type to use, either OP_BINARY or OP_TEXT + * @note Voice websockets only support OP_TEXT, and other websockets must be + * OP_BINARY if you are going to send ETF. + */ + websocket_client(const std::string &hostname, const std::string &port = "443", const std::string &urlpath = "", ws_opcode opcode = OP_BINARY); + + /** + * @brief Destroy the websocket client object + */ + virtual ~websocket_client(); + + /** + * @brief Write to websocket. Encapsulates data in frames if the status is CONNECTED. + * @param data The data to send. + */ + virtual void write(const std::string &data); + + /** + * @brief Processes incoming frames from the SSL socket input buffer. + * @param buffer The buffer contents. Can modify this value removing the head elements when processed. + */ + virtual bool handle_buffer(std::string &buffer); + + /** + * @brief Close websocket + */ + virtual void close(); + + /** + * @brief Receives raw frame content only without headers + * + * @param buffer The buffer contents + * @return True if the frame was successfully handled. False if no valid frame is in the buffer. + */ + virtual bool handle_frame(const std::string &buffer); + + /** + * @brief Called upon error frame. + * + * @param errorcode The error code from the websocket server + */ + virtual void error(uint32_t errorcode); + + /** + * @brief Fires every second from the underlying socket I/O loop, used for sending websocket pings + */ + virtual void one_second_timer(); + + /** + * @brief Send OP_CLOSE error code 1000 to the other side of the connection. + * This indicates graceful close. + */ + void send_close_packet(); +}; + }; \ No newline at end of file diff --git a/3rdParty/nlohmann/json.hpp b/3rdParty/nlohmann/json.hpp index 880d7d9d45..cb27e05811 100644 --- a/3rdParty/nlohmann/json.hpp +++ b/3rdParty/nlohmann/json.hpp @@ -1,22091 +1,22091 @@ -/* - __ _____ _____ _____ - __| | __| | | | JSON for Modern C++ -| | |__ | | | | | | version 3.10.5 -|_____|_____|_____|_|___| https://github.com/nlohmann/json - -Licensed under the MIT License . -SPDX-License-Identifier: MIT -Copyright (c) 2013-2022 Niels Lohmann . - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -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 Software. - -THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -/****************************************************************************\ - * Note on documentation: The source files contain links to the online * - * documentation of the public API at https://json.nlohmann.me. This URL * - * contains the most recent documentation and should also be applicable to * - * previous versions; documentation for deprecated functions is not * - * removed, but marked deprecated. See "Generate documentation" section in * - * file doc/README.md. * -\****************************************************************************/ - -#ifndef INCLUDE_NLOHMANN_JSON_HPP_ -#define INCLUDE_NLOHMANN_JSON_HPP_ - -#define NLOHMANN_JSON_VERSION_MAJOR 3 -#define NLOHMANN_JSON_VERSION_MINOR 10 -#define NLOHMANN_JSON_VERSION_PATCH 5 - -#include // all_of, find, for_each -#include // nullptr_t, ptrdiff_t, size_t -#include // hash, less -#include // initializer_list -#ifndef JSON_NO_IO - #include // istream, ostream -#endif // JSON_NO_IO -#include // random_access_iterator_tag -#include // unique_ptr -#include // accumulate -#include // string, stoi, to_string -#include // declval, forward, move, pair, swap -#include // vector - -// #include - - -#include -#include - -// #include - - -#include // transform -#include // array -#include // forward_list -#include // inserter, front_inserter, end -#include // map -#include // string -#include // tuple, make_tuple -#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible -#include // unordered_map -#include // pair, declval -#include // valarray - -// #include - - -#include // exception -#include // runtime_error -#include // to_string -#include // vector - -// #include - - -#include // array -#include // size_t -#include // uint8_t -#include // string - -namespace nlohmann -{ -namespace detail -{ -/////////////////////////// -// JSON type enumeration // -/////////////////////////// - -/*! -@brief the JSON type enumeration - -This enumeration collects the different JSON types. It is internally used to -distinguish the stored values, and the functions @ref basic_json::is_null(), -@ref basic_json::is_object(), @ref basic_json::is_array(), -@ref basic_json::is_string(), @ref basic_json::is_boolean(), -@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), -@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), -@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and -@ref basic_json::is_structured() rely on it. - -@note There are three enumeration entries (number_integer, number_unsigned, and -number_float), because the library distinguishes these three types for numbers: -@ref basic_json::number_unsigned_t is used for unsigned integers, -@ref basic_json::number_integer_t is used for signed integers, and -@ref basic_json::number_float_t is used for floating-point numbers or to -approximate integers which do not fit in the limits of their respective type. - -@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON -value with the default value for a given type - -@since version 1.0.0 -*/ -enum class value_t : std::uint8_t -{ - null, ///< null value - object, ///< object (unordered set of name/value pairs) - array, ///< array (ordered collection of values) - string, ///< string value - boolean, ///< boolean value - number_integer, ///< number value (signed integer) - number_unsigned, ///< number value (unsigned integer) - number_float, ///< number value (floating-point) - binary, ///< binary array (ordered collection of bytes) - discarded ///< discarded by the parser callback function -}; - -/*! -@brief comparison operator for JSON types - -Returns an ordering that is similar to Python: -- order: null < boolean < number < object < array < string < binary -- furthermore, each type is not smaller than itself -- discarded values are not comparable -- binary is represented as a b"" string in python and directly comparable to a - string; however, making a binary array directly comparable with a string would - be surprising behavior in a JSON file. - -@since version 1.0.0 -*/ -inline bool operator<(const value_t lhs, const value_t rhs) noexcept -{ - static constexpr std::array order = {{ - 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, - 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, - 6 /* binary */ - } - }; - - const auto l_index = static_cast(lhs); - const auto r_index = static_cast(rhs); - return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; -} -} // namespace detail -} // namespace nlohmann - -// #include - - -#include -// #include - - -#include // declval, pair -// #include - - -/* Hedley - https://nemequ.github.io/hedley - * Created by Evan Nemerson - * - * To the extent possible under law, the author(s) have dedicated all - * copyright and related and neighboring rights to this software to - * the public domain worldwide. This software is distributed without - * any warranty. - * - * For details, see . - * SPDX-License-Identifier: CC0-1.0 - */ - -#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) -#if defined(JSON_HEDLEY_VERSION) - #undef JSON_HEDLEY_VERSION -#endif -#define JSON_HEDLEY_VERSION 15 - -#if defined(JSON_HEDLEY_STRINGIFY_EX) - #undef JSON_HEDLEY_STRINGIFY_EX -#endif -#define JSON_HEDLEY_STRINGIFY_EX(x) #x - -#if defined(JSON_HEDLEY_STRINGIFY) - #undef JSON_HEDLEY_STRINGIFY -#endif -#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) - -#if defined(JSON_HEDLEY_CONCAT_EX) - #undef JSON_HEDLEY_CONCAT_EX -#endif -#define JSON_HEDLEY_CONCAT_EX(a,b) a##b - -#if defined(JSON_HEDLEY_CONCAT) - #undef JSON_HEDLEY_CONCAT -#endif -#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) - -#if defined(JSON_HEDLEY_CONCAT3_EX) - #undef JSON_HEDLEY_CONCAT3_EX -#endif -#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c - -#if defined(JSON_HEDLEY_CONCAT3) - #undef JSON_HEDLEY_CONCAT3 -#endif -#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) - -#if defined(JSON_HEDLEY_VERSION_ENCODE) - #undef JSON_HEDLEY_VERSION_ENCODE -#endif -#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) - -#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) - #undef JSON_HEDLEY_VERSION_DECODE_MAJOR -#endif -#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) - -#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) - #undef JSON_HEDLEY_VERSION_DECODE_MINOR -#endif -#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) - -#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) - #undef JSON_HEDLEY_VERSION_DECODE_REVISION -#endif -#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) - -#if defined(JSON_HEDLEY_GNUC_VERSION) - #undef JSON_HEDLEY_GNUC_VERSION -#endif -#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) - #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#elif defined(__GNUC__) - #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) -#endif - -#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) - #undef JSON_HEDLEY_GNUC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_GNUC_VERSION) - #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_MSVC_VERSION) - #undef JSON_HEDLEY_MSVC_VERSION -#endif -#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) -#elif defined(_MSC_FULL_VER) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) -#elif defined(_MSC_VER) && !defined(__ICL) - #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) -#endif - -#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) - #undef JSON_HEDLEY_MSVC_VERSION_CHECK -#endif -#if !defined(JSON_HEDLEY_MSVC_VERSION) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) -#elif defined(_MSC_VER) && (_MSC_VER >= 1400) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) -#elif defined(_MSC_VER) && (_MSC_VER >= 1200) - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) -#else - #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) -#endif - -#if defined(JSON_HEDLEY_INTEL_VERSION) - #undef JSON_HEDLEY_INTEL_VERSION -#endif -#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) - #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) -#elif defined(__INTEL_COMPILER) && !defined(__ICL) - #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) -#endif - -#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) - #undef JSON_HEDLEY_INTEL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_INTEL_VERSION) - #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_INTEL_CL_VERSION) - #undef JSON_HEDLEY_INTEL_CL_VERSION -#endif -#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) - #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) -#endif - -#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) - #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_INTEL_CL_VERSION) - #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_PGI_VERSION) - #undef JSON_HEDLEY_PGI_VERSION -#endif -#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) - #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) -#endif - -#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) - #undef JSON_HEDLEY_PGI_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_PGI_VERSION) - #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_SUNPRO_VERSION) - #undef JSON_HEDLEY_SUNPRO_VERSION -#endif -#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) -#elif defined(__SUNPRO_C) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) -#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) -#elif defined(__SUNPRO_CC) - #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) -#endif - -#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) - #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_SUNPRO_VERSION) - #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) - #undef JSON_HEDLEY_EMSCRIPTEN_VERSION -#endif -#if defined(__EMSCRIPTEN__) - #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) -#endif - -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) - #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) - #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_ARM_VERSION) - #undef JSON_HEDLEY_ARM_VERSION -#endif -#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) - #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) -#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) - #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) -#endif - -#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) - #undef JSON_HEDLEY_ARM_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_ARM_VERSION) - #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_IBM_VERSION) - #undef JSON_HEDLEY_IBM_VERSION -#endif -#if defined(__ibmxl__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) -#elif defined(__xlC__) && defined(__xlC_ver__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) -#elif defined(__xlC__) - #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) -#endif - -#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) - #undef JSON_HEDLEY_IBM_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_IBM_VERSION) - #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_VERSION) - #undef JSON_HEDLEY_TI_VERSION -#endif -#if \ - defined(__TI_COMPILER_VERSION__) && \ - ( \ - defined(__TMS470__) || defined(__TI_ARM__) || \ - defined(__MSP430__) || \ - defined(__TMS320C2000__) \ - ) -#if (__TI_COMPILER_VERSION__ >= 16000000) - #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif -#endif - -#if defined(JSON_HEDLEY_TI_VERSION_CHECK) - #undef JSON_HEDLEY_TI_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_VERSION) - #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL2000_VERSION) - #undef JSON_HEDLEY_TI_CL2000_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) - #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL2000_VERSION) - #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL430_VERSION) - #undef JSON_HEDLEY_TI_CL430_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) - #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL430_VERSION) - #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) - #undef JSON_HEDLEY_TI_ARMCL_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) - #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) - #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) - #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL6X_VERSION) - #undef JSON_HEDLEY_TI_CL6X_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) - #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL6X_VERSION) - #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CL7X_VERSION) - #undef JSON_HEDLEY_TI_CL7X_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) - #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CL7X_VERSION) - #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) - #undef JSON_HEDLEY_TI_CLPRU_VERSION -#endif -#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) - #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) -#endif - -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) - #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) - #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_CRAY_VERSION) - #undef JSON_HEDLEY_CRAY_VERSION -#endif -#if defined(_CRAYC) - #if defined(_RELEASE_PATCHLEVEL) - #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) - #else - #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) - #endif -#endif - -#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) - #undef JSON_HEDLEY_CRAY_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_CRAY_VERSION) - #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_IAR_VERSION) - #undef JSON_HEDLEY_IAR_VERSION -#endif -#if defined(__IAR_SYSTEMS_ICC__) - #if __VER__ > 1000 - #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) - #else - #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) - #endif -#endif - -#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) - #undef JSON_HEDLEY_IAR_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_IAR_VERSION) - #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_TINYC_VERSION) - #undef JSON_HEDLEY_TINYC_VERSION -#endif -#if defined(__TINYC__) - #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) -#endif - -#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) - #undef JSON_HEDLEY_TINYC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_TINYC_VERSION) - #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_DMC_VERSION) - #undef JSON_HEDLEY_DMC_VERSION -#endif -#if defined(__DMC__) - #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) -#endif - -#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) - #undef JSON_HEDLEY_DMC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_DMC_VERSION) - #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_COMPCERT_VERSION) - #undef JSON_HEDLEY_COMPCERT_VERSION -#endif -#if defined(__COMPCERT_VERSION__) - #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) -#endif - -#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) - #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_COMPCERT_VERSION) - #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_PELLES_VERSION) - #undef JSON_HEDLEY_PELLES_VERSION -#endif -#if defined(__POCC__) - #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) -#endif - -#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) - #undef JSON_HEDLEY_PELLES_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_PELLES_VERSION) - #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_MCST_LCC_VERSION) - #undef JSON_HEDLEY_MCST_LCC_VERSION -#endif -#if defined(__LCC__) && defined(__LCC_MINOR__) - #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) -#endif - -#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) - #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_MCST_LCC_VERSION) - #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_GCC_VERSION) - #undef JSON_HEDLEY_GCC_VERSION -#endif -#if \ - defined(JSON_HEDLEY_GNUC_VERSION) && \ - !defined(__clang__) && \ - !defined(JSON_HEDLEY_INTEL_VERSION) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_ARM_VERSION) && \ - !defined(JSON_HEDLEY_CRAY_VERSION) && \ - !defined(JSON_HEDLEY_TI_VERSION) && \ - !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ - !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ - !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ - !defined(__COMPCERT__) && \ - !defined(JSON_HEDLEY_MCST_LCC_VERSION) - #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION -#endif - -#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) - #undef JSON_HEDLEY_GCC_VERSION_CHECK -#endif -#if defined(JSON_HEDLEY_GCC_VERSION) - #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) -#else - #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) -#endif - -#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_ATTRIBUTE -#endif -#if \ - defined(__has_attribute) && \ - ( \ - (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ - ) -# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) -#else -# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE -#endif -#if defined(__has_attribute) - #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE -#endif -#if defined(__has_attribute) - #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE -#endif -#if \ - defined(__has_cpp_attribute) && \ - defined(__cplusplus) && \ - (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) - #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS -#endif -#if !defined(__cplusplus) || !defined(__has_cpp_attribute) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) -#elif \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_IAR_VERSION) && \ - (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ - (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) -#else - #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE -#endif -#if defined(__has_cpp_attribute) && defined(__cplusplus) - #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE -#endif -#if defined(__has_cpp_attribute) && defined(__cplusplus) - #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_BUILTIN) - #undef JSON_HEDLEY_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) -#else - #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) - #undef JSON_HEDLEY_GNUC_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) -#else - #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) - #undef JSON_HEDLEY_GCC_HAS_BUILTIN -#endif -#if defined(__has_builtin) - #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) -#else - #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_FEATURE) - #undef JSON_HEDLEY_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) -#else - #define JSON_HEDLEY_HAS_FEATURE(feature) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) - #undef JSON_HEDLEY_GNUC_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) -#else - #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) - #undef JSON_HEDLEY_GCC_HAS_FEATURE -#endif -#if defined(__has_feature) - #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) -#else - #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_EXTENSION) - #undef JSON_HEDLEY_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) -#else - #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) - #undef JSON_HEDLEY_GNUC_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) -#else - #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) - #undef JSON_HEDLEY_GCC_HAS_EXTENSION -#endif -#if defined(__has_extension) - #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) -#else - #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE -#endif -#if defined(__has_declspec_attribute) - #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) -#else - #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_HAS_WARNING) - #undef JSON_HEDLEY_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) -#else - #define JSON_HEDLEY_HAS_WARNING(warning) (0) -#endif - -#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) - #undef JSON_HEDLEY_GNUC_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) -#else - #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_GCC_HAS_WARNING) - #undef JSON_HEDLEY_GCC_HAS_WARNING -#endif -#if defined(__has_warning) - #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) -#else - #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ - defined(__clang__) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ - (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) - #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_PRAGMA(value) __pragma(value) -#else - #define JSON_HEDLEY_PRAGMA(value) -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) - #undef JSON_HEDLEY_DIAGNOSTIC_PUSH -#endif -#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) - #undef JSON_HEDLEY_DIAGNOSTIC_POP -#endif -#if defined(__clang__) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) - #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) -#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) - #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") - #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") -#else - #define JSON_HEDLEY_DIAGNOSTIC_PUSH - #define JSON_HEDLEY_DIAGNOSTIC_POP -#endif - -/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for - HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ -#endif -#if defined(__cplusplus) -# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") -# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") -# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ - _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# endif -# else -# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ - xpr \ - JSON_HEDLEY_DIAGNOSTIC_POP -# endif -# endif -#endif -#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x -#endif - -#if defined(JSON_HEDLEY_CONST_CAST) - #undef JSON_HEDLEY_CONST_CAST -#endif -#if defined(__cplusplus) -# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) -#elif \ - JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ - ((T) (expr)); \ - JSON_HEDLEY_DIAGNOSTIC_POP \ - })) -#else -# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_REINTERPRET_CAST) - #undef JSON_HEDLEY_REINTERPRET_CAST -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) -#else - #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_STATIC_CAST) - #undef JSON_HEDLEY_STATIC_CAST -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) -#else - #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) -#endif - -#if defined(JSON_HEDLEY_CPP_CAST) - #undef JSON_HEDLEY_CPP_CAST -#endif -#if defined(__cplusplus) -# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") -# define JSON_HEDLEY_CPP_CAST(T, expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ - ((T) (expr)) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) -# define JSON_HEDLEY_CPP_CAST(T, expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("diag_suppress=Pe137") \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) -# endif -#else -# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") -#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") -#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") -#elif \ - JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") -#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#endif - -#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) - #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") -#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") -#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) -#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") -#else - #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#endif - -#if defined(JSON_HEDLEY_DEPRECATED) - #undef JSON_HEDLEY_DEPRECATED -#endif -#if defined(JSON_HEDLEY_DEPRECATED_FOR) - #undef JSON_HEDLEY_DEPRECATED_FOR -#endif -#if \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) -#elif \ - (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) -#elif defined(__cplusplus) && (__cplusplus >= 201402L) - #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") -#else - #define JSON_HEDLEY_DEPRECATED(since) - #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) -#endif - -#if defined(JSON_HEDLEY_UNAVAILABLE) - #undef JSON_HEDLEY_UNAVAILABLE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) -#else - #define JSON_HEDLEY_UNAVAILABLE(available_since) -#endif - -#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) - #undef JSON_HEDLEY_WARN_UNUSED_RESULT -#endif -#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) - #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) -#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) - #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) - #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) -#elif defined(_Check_return_) /* SAL */ - #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ -#else - #define JSON_HEDLEY_WARN_UNUSED_RESULT - #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) -#endif - -#if defined(JSON_HEDLEY_SENTINEL) - #undef JSON_HEDLEY_SENTINEL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) -#else - #define JSON_HEDLEY_SENTINEL(position) -#endif - -#if defined(JSON_HEDLEY_NO_RETURN) - #undef JSON_HEDLEY_NO_RETURN -#endif -#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_NO_RETURN __noreturn -#elif \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L - #define JSON_HEDLEY_NO_RETURN _Noreturn -#elif defined(__cplusplus) && (__cplusplus >= 201103L) - #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) - #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") -#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) - #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) - #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) -#else - #define JSON_HEDLEY_NO_RETURN -#endif - -#if defined(JSON_HEDLEY_NO_ESCAPE) - #undef JSON_HEDLEY_NO_ESCAPE -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) - #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) -#else - #define JSON_HEDLEY_NO_ESCAPE -#endif - -#if defined(JSON_HEDLEY_UNREACHABLE) - #undef JSON_HEDLEY_UNREACHABLE -#endif -#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) - #undef JSON_HEDLEY_UNREACHABLE_RETURN -#endif -#if defined(JSON_HEDLEY_ASSUME) - #undef JSON_HEDLEY_ASSUME -#endif -#if \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_ASSUME(expr) __assume(expr) -#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) - #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) -#elif \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) - #if defined(__cplusplus) - #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) - #else - #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) - #endif -#endif -#if \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() -#elif defined(JSON_HEDLEY_ASSUME) - #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) -#endif -#if !defined(JSON_HEDLEY_ASSUME) - #if defined(JSON_HEDLEY_UNREACHABLE) - #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) - #else - #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) - #endif -#endif -#if defined(JSON_HEDLEY_UNREACHABLE) - #if \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) - #else - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() - #endif -#else - #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) -#endif -#if !defined(JSON_HEDLEY_UNREACHABLE) - #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) -#endif - -JSON_HEDLEY_DIAGNOSTIC_PUSH -#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") - #pragma clang diagnostic ignored "-Wpedantic" -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) - #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" -#endif -#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) - #if defined(__clang__) - #pragma clang diagnostic ignored "-Wvariadic-macros" - #elif defined(JSON_HEDLEY_GCC_VERSION) - #pragma GCC diagnostic ignored "-Wvariadic-macros" - #endif -#endif -#if defined(JSON_HEDLEY_NON_NULL) - #undef JSON_HEDLEY_NON_NULL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) - #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) -#else - #define JSON_HEDLEY_NON_NULL(...) -#endif -JSON_HEDLEY_DIAGNOSTIC_POP - -#if defined(JSON_HEDLEY_PRINTF_FORMAT) - #undef JSON_HEDLEY_PRINTF_FORMAT -#endif -#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) -#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) -#elif \ - JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) -#else - #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) -#endif - -#if defined(JSON_HEDLEY_CONSTEXPR) - #undef JSON_HEDLEY_CONSTEXPR -#endif -#if defined(__cplusplus) - #if __cplusplus >= 201103L - #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) - #endif -#endif -#if !defined(JSON_HEDLEY_CONSTEXPR) - #define JSON_HEDLEY_CONSTEXPR -#endif - -#if defined(JSON_HEDLEY_PREDICT) - #undef JSON_HEDLEY_PREDICT -#endif -#if defined(JSON_HEDLEY_LIKELY) - #undef JSON_HEDLEY_LIKELY -#endif -#if defined(JSON_HEDLEY_UNLIKELY) - #undef JSON_HEDLEY_UNLIKELY -#endif -#if defined(JSON_HEDLEY_UNPREDICTABLE) - #undef JSON_HEDLEY_UNPREDICTABLE -#endif -#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) - #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) -#endif -#if \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) -# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) -# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) -#elif \ - (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ - (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ - (__extension__ ({ \ - double hedley_probability_ = (probability); \ - ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ - })) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ - (__extension__ ({ \ - double hedley_probability_ = (probability); \ - ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ - })) -# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) -# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) -#else -# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) -# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) -# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) -# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) -# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) -#endif -#if !defined(JSON_HEDLEY_UNPREDICTABLE) - #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) -#endif - -#if defined(JSON_HEDLEY_MALLOC) - #undef JSON_HEDLEY_MALLOC -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_MALLOC __declspec(restrict) -#else - #define JSON_HEDLEY_MALLOC -#endif - -#if defined(JSON_HEDLEY_PURE) - #undef JSON_HEDLEY_PURE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PURE __attribute__((__pure__)) -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) -# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") -#elif defined(__cplusplus) && \ - ( \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ - ) -# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") -#else -# define JSON_HEDLEY_PURE -#endif - -#if defined(JSON_HEDLEY_CONST) - #undef JSON_HEDLEY_CONST -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_CONST __attribute__((__const__)) -#elif \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) - #define JSON_HEDLEY_CONST _Pragma("no_side_effect") -#else - #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE -#endif - -#if defined(JSON_HEDLEY_RESTRICT) - #undef JSON_HEDLEY_RESTRICT -#endif -#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) - #define JSON_HEDLEY_RESTRICT restrict -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ - defined(__clang__) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_RESTRICT __restrict -#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) - #define JSON_HEDLEY_RESTRICT _Restrict -#else - #define JSON_HEDLEY_RESTRICT -#endif - -#if defined(JSON_HEDLEY_INLINE) - #undef JSON_HEDLEY_INLINE -#endif -#if \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ - (defined(__cplusplus) && (__cplusplus >= 199711L)) - #define JSON_HEDLEY_INLINE inline -#elif \ - defined(JSON_HEDLEY_GCC_VERSION) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) - #define JSON_HEDLEY_INLINE __inline__ -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_INLINE __inline -#else - #define JSON_HEDLEY_INLINE -#endif - -#if defined(JSON_HEDLEY_ALWAYS_INLINE) - #undef JSON_HEDLEY_ALWAYS_INLINE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) -# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_ALWAYS_INLINE __forceinline -#elif defined(__cplusplus) && \ - ( \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ - ) -# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) -# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") -#else -# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE -#endif - -#if defined(JSON_HEDLEY_NEVER_INLINE) - #undef JSON_HEDLEY_NEVER_INLINE -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ - JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ - (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ - (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ - (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ - JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ - JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ - JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) - #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) -#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") -#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) - #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") -#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) - #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) - #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) -#else - #define JSON_HEDLEY_NEVER_INLINE -#endif - -#if defined(JSON_HEDLEY_PRIVATE) - #undef JSON_HEDLEY_PRIVATE -#endif -#if defined(JSON_HEDLEY_PUBLIC) - #undef JSON_HEDLEY_PUBLIC -#endif -#if defined(JSON_HEDLEY_IMPORT) - #undef JSON_HEDLEY_IMPORT -#endif -#if defined(_WIN32) || defined(__CYGWIN__) -# define JSON_HEDLEY_PRIVATE -# define JSON_HEDLEY_PUBLIC __declspec(dllexport) -# define JSON_HEDLEY_IMPORT __declspec(dllimport) -#else -# if \ - JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - ( \ - defined(__TI_EABI__) && \ - ( \ - (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ - ) \ - ) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) -# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) -# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) -# else -# define JSON_HEDLEY_PRIVATE -# define JSON_HEDLEY_PUBLIC -# endif -# define JSON_HEDLEY_IMPORT extern -#endif - -#if defined(JSON_HEDLEY_NO_THROW) - #undef JSON_HEDLEY_NO_THROW -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) - #define JSON_HEDLEY_NO_THROW __declspec(nothrow) -#else - #define JSON_HEDLEY_NO_THROW -#endif - -#if defined(JSON_HEDLEY_FALL_THROUGH) - #undef JSON_HEDLEY_FALL_THROUGH -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) - #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) -#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) - #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) -#elif defined(__fallthrough) /* SAL */ - #define JSON_HEDLEY_FALL_THROUGH __fallthrough -#else - #define JSON_HEDLEY_FALL_THROUGH -#endif - -#if defined(JSON_HEDLEY_RETURNS_NON_NULL) - #undef JSON_HEDLEY_RETURNS_NON_NULL -#endif -#if \ - JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) -#elif defined(_Ret_notnull_) /* SAL */ - #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ -#else - #define JSON_HEDLEY_RETURNS_NON_NULL -#endif - -#if defined(JSON_HEDLEY_ARRAY_PARAM) - #undef JSON_HEDLEY_ARRAY_PARAM -#endif -#if \ - defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ - !defined(__STDC_NO_VLA__) && \ - !defined(__cplusplus) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_TINYC_VERSION) - #define JSON_HEDLEY_ARRAY_PARAM(name) (name) -#else - #define JSON_HEDLEY_ARRAY_PARAM(name) -#endif - -#if defined(JSON_HEDLEY_IS_CONSTANT) - #undef JSON_HEDLEY_IS_CONSTANT -#endif -#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) - #undef JSON_HEDLEY_REQUIRE_CONSTEXPR -#endif -/* JSON_HEDLEY_IS_CONSTEXPR_ is for - HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ -#if defined(JSON_HEDLEY_IS_CONSTEXPR_) - #undef JSON_HEDLEY_IS_CONSTEXPR_ -#endif -#if \ - JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ - (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) - #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) -#endif -#if !defined(__cplusplus) -# if \ - JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ - JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ - JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) -#if defined(__INTPTR_TYPE__) - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) -#else - #include - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) -#endif -# elif \ - ( \ - defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ - !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ - !defined(JSON_HEDLEY_PGI_VERSION) && \ - !defined(JSON_HEDLEY_IAR_VERSION)) || \ - (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ - JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ - JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) -#if defined(__INTPTR_TYPE__) - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) -#else - #include - #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) -#endif -# elif \ - defined(JSON_HEDLEY_GCC_VERSION) || \ - defined(JSON_HEDLEY_INTEL_VERSION) || \ - defined(JSON_HEDLEY_TINYC_VERSION) || \ - defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ - JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ - defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ - defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ - defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ - defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ - defined(__clang__) -# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ - sizeof(void) != \ - sizeof(*( \ - 1 ? \ - ((void*) ((expr) * 0L) ) : \ -((struct { char v[sizeof(void) * 2]; } *) 1) \ - ) \ - ) \ - ) -# endif -#endif -#if defined(JSON_HEDLEY_IS_CONSTEXPR_) - #if !defined(JSON_HEDLEY_IS_CONSTANT) - #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) - #endif - #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) -#else - #if !defined(JSON_HEDLEY_IS_CONSTANT) - #define JSON_HEDLEY_IS_CONSTANT(expr) (0) - #endif - #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) -#endif - -#if defined(JSON_HEDLEY_BEGIN_C_DECLS) - #undef JSON_HEDLEY_BEGIN_C_DECLS -#endif -#if defined(JSON_HEDLEY_END_C_DECLS) - #undef JSON_HEDLEY_END_C_DECLS -#endif -#if defined(JSON_HEDLEY_C_DECL) - #undef JSON_HEDLEY_C_DECL -#endif -#if defined(__cplusplus) - #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { - #define JSON_HEDLEY_END_C_DECLS } - #define JSON_HEDLEY_C_DECL extern "C" -#else - #define JSON_HEDLEY_BEGIN_C_DECLS - #define JSON_HEDLEY_END_C_DECLS - #define JSON_HEDLEY_C_DECL -#endif - -#if defined(JSON_HEDLEY_STATIC_ASSERT) - #undef JSON_HEDLEY_STATIC_ASSERT -#endif -#if \ - !defined(__cplusplus) && ( \ - (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ - (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ - JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ - defined(_Static_assert) \ - ) -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) -#elif \ - (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ - JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) -#else -# define JSON_HEDLEY_STATIC_ASSERT(expr, message) -#endif - -#if defined(JSON_HEDLEY_NULL) - #undef JSON_HEDLEY_NULL -#endif -#if defined(__cplusplus) - #if __cplusplus >= 201103L - #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) - #elif defined(NULL) - #define JSON_HEDLEY_NULL NULL - #else - #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) - #endif -#elif defined(NULL) - #define JSON_HEDLEY_NULL NULL -#else - #define JSON_HEDLEY_NULL ((void*) 0) -#endif - -#if defined(JSON_HEDLEY_MESSAGE) - #undef JSON_HEDLEY_MESSAGE -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") -# define JSON_HEDLEY_MESSAGE(msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ - JSON_HEDLEY_PRAGMA(message msg) \ - JSON_HEDLEY_DIAGNOSTIC_POP -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) -#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) -#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) -# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#else -# define JSON_HEDLEY_MESSAGE(msg) -#endif - -#if defined(JSON_HEDLEY_WARNING) - #undef JSON_HEDLEY_WARNING -#endif -#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") -# define JSON_HEDLEY_WARNING(msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ - JSON_HEDLEY_PRAGMA(clang warning msg) \ - JSON_HEDLEY_DIAGNOSTIC_POP -#elif \ - JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ - JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ - JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) -#elif \ - JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) -#else -# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) -#endif - -#if defined(JSON_HEDLEY_REQUIRE) - #undef JSON_HEDLEY_REQUIRE -#endif -#if defined(JSON_HEDLEY_REQUIRE_MSG) - #undef JSON_HEDLEY_REQUIRE_MSG -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) -# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") -# define JSON_HEDLEY_REQUIRE(expr) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((diagnose_if(!(expr), #expr, "error"))) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ - __attribute__((diagnose_if(!(expr), msg, "error"))) \ - JSON_HEDLEY_DIAGNOSTIC_POP -# else -# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) -# endif -#else -# define JSON_HEDLEY_REQUIRE(expr) -# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) -#endif - -#if defined(JSON_HEDLEY_FLAGS) - #undef JSON_HEDLEY_FLAGS -#endif -#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) - #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) -#else - #define JSON_HEDLEY_FLAGS -#endif - -#if defined(JSON_HEDLEY_FLAGS_CAST) - #undef JSON_HEDLEY_FLAGS_CAST -#endif -#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) -# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ - JSON_HEDLEY_DIAGNOSTIC_PUSH \ - _Pragma("warning(disable:188)") \ - ((T) (expr)); \ - JSON_HEDLEY_DIAGNOSTIC_POP \ - })) -#else -# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) -#endif - -#if defined(JSON_HEDLEY_EMPTY_BASES) - #undef JSON_HEDLEY_EMPTY_BASES -#endif -#if \ - (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ - JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) - #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) -#else - #define JSON_HEDLEY_EMPTY_BASES -#endif - -/* Remaining macros are deprecated. */ - -#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) - #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK -#endif -#if defined(__clang__) - #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) -#else - #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) -#endif - -#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) - #undef JSON_HEDLEY_CLANG_HAS_BUILTIN -#endif -#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) - -#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) - #undef JSON_HEDLEY_CLANG_HAS_FEATURE -#endif -#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) - -#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) - #undef JSON_HEDLEY_CLANG_HAS_EXTENSION -#endif -#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) - -#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) - #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE -#endif -#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) - -#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) - #undef JSON_HEDLEY_CLANG_HAS_WARNING -#endif -#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) - -#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ - -// #include - - -#include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template struct make_void -{ - using type = void; -}; -template using void_t = typename make_void::type; -} // namespace detail -} // namespace nlohmann - - -// https://en.cppreference.com/w/cpp/experimental/is_detected -namespace nlohmann -{ -namespace detail -{ -struct nonesuch -{ - nonesuch() = delete; - ~nonesuch() = delete; - nonesuch(nonesuch const&) = delete; - nonesuch(nonesuch const&&) = delete; - void operator=(nonesuch const&) = delete; - void operator=(nonesuch&&) = delete; -}; - -template class Op, - class... Args> -struct detector -{ - using value_t = std::false_type; - using type = Default; -}; - -template class Op, class... Args> -struct detector>, Op, Args...> -{ - using value_t = std::true_type; - using type = Op; -}; - -template class Op, class... Args> -using is_detected = typename detector::value_t; - -template class Op, class... Args> -struct is_detected_lazy : is_detected { }; - -template class Op, class... Args> -using detected_t = typename detector::type; - -template class Op, class... Args> -using detected_or = detector; - -template class Op, class... Args> -using detected_or_t = typename detected_or::type; - -template class Op, class... Args> -using is_detected_exact = std::is_same>; - -template class Op, class... Args> -using is_detected_convertible = - std::is_convertible, To>; -} // namespace detail -} // namespace nlohmann - - -// This file contains all internal macro definitions -// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them - -// exclude unsupported compilers -#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) - #if defined(__clang__) - #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 - #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) - #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 - #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" - #endif - #endif -#endif - -// C++ language standard detection -// if the user manually specified the used c++ version this is skipped -#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) - #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) - #define JSON_HAS_CPP_20 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 - #define JSON_HAS_CPP_17 - #define JSON_HAS_CPP_14 - #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) - #define JSON_HAS_CPP_14 - #endif - // the cpp 11 flag is always specified because it is the minimal required version - #define JSON_HAS_CPP_11 -#endif - -#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) - #ifdef JSON_HAS_CPP_17 - #if defined(__cpp_lib_filesystem) - #define JSON_HAS_FILESYSTEM 1 - #elif defined(__cpp_lib_experimental_filesystem) - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #elif !defined(__has_include) - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #elif __has_include() - #define JSON_HAS_FILESYSTEM 1 - #elif __has_include() - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 - #endif - - // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ - #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support - #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support - #if defined(__clang_major__) && __clang_major__ < 7 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support - #if defined(_MSC_VER) && _MSC_VER < 1940 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before iOS 13 - #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - - // no filesystem support before macOS Catalina - #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 - #undef JSON_HAS_FILESYSTEM - #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #endif - #endif -#endif - -#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM - #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 -#endif - -#ifndef JSON_HAS_FILESYSTEM - #define JSON_HAS_FILESYSTEM 0 -#endif - -// disable documentation warnings on clang -#if defined(__clang__) - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wdocumentation" - #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" -#endif - -// allow disabling exceptions -#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) - #define JSON_THROW(exception) throw exception - #define JSON_TRY try - #define JSON_CATCH(exception) catch(exception) - #define JSON_INTERNAL_CATCH(exception) catch(exception) -#else - #include - #define JSON_THROW(exception) std::abort() - #define JSON_TRY if(true) - #define JSON_CATCH(exception) if(false) - #define JSON_INTERNAL_CATCH(exception) if(false) -#endif - -// override exception macros -#if defined(JSON_THROW_USER) - #undef JSON_THROW - #define JSON_THROW JSON_THROW_USER -#endif -#if defined(JSON_TRY_USER) - #undef JSON_TRY - #define JSON_TRY JSON_TRY_USER -#endif -#if defined(JSON_CATCH_USER) - #undef JSON_CATCH - #define JSON_CATCH JSON_CATCH_USER - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_CATCH_USER -#endif -#if defined(JSON_INTERNAL_CATCH_USER) - #undef JSON_INTERNAL_CATCH - #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER -#endif - -// allow overriding assert -#if !defined(JSON_ASSERT) - #include // assert - #define JSON_ASSERT(x) assert(x) -#endif - -// allow to access some private functions (needed by the test suite) -#if defined(JSON_TESTS_PRIVATE) - #define JSON_PRIVATE_UNLESS_TESTED public -#else - #define JSON_PRIVATE_UNLESS_TESTED private -#endif - -/*! -@brief macro to briefly define a mapping between an enum and JSON -@def NLOHMANN_JSON_SERIALIZE_ENUM -@since version 3.4.0 -*/ -#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ - template \ - inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ - { \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [e](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.first == e; \ - }); \ - j = ((it != std::end(m)) ? it : std::begin(m))->second; \ - } \ - template \ - inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ - { \ - static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ - static const std::pair m[] = __VA_ARGS__; \ - auto it = std::find_if(std::begin(m), std::end(m), \ - [&j](const std::pair& ej_pair) -> bool \ - { \ - return ej_pair.second == j; \ - }); \ - e = ((it != std::end(m)) ? it : std::begin(m))->first; \ - } - -// Ugly macros to avoid uglier copy-paste when specializing basic_json. They -// may be removed in the future once the class is split. - -#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ - template class ObjectType, \ - template class ArrayType, \ - class StringType, class BooleanType, class NumberIntegerType, \ - class NumberUnsignedType, class NumberFloatType, \ - template class AllocatorType, \ - template class JSONSerializer, \ - class BinaryType> - -#define NLOHMANN_BASIC_JSON_TPL \ - basic_json - -// Macros to simplify conversion from/to types - -#define NLOHMANN_JSON_EXPAND( x ) x -#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME -#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ - NLOHMANN_JSON_PASTE64, \ - NLOHMANN_JSON_PASTE63, \ - NLOHMANN_JSON_PASTE62, \ - NLOHMANN_JSON_PASTE61, \ - NLOHMANN_JSON_PASTE60, \ - NLOHMANN_JSON_PASTE59, \ - NLOHMANN_JSON_PASTE58, \ - NLOHMANN_JSON_PASTE57, \ - NLOHMANN_JSON_PASTE56, \ - NLOHMANN_JSON_PASTE55, \ - NLOHMANN_JSON_PASTE54, \ - NLOHMANN_JSON_PASTE53, \ - NLOHMANN_JSON_PASTE52, \ - NLOHMANN_JSON_PASTE51, \ - NLOHMANN_JSON_PASTE50, \ - NLOHMANN_JSON_PASTE49, \ - NLOHMANN_JSON_PASTE48, \ - NLOHMANN_JSON_PASTE47, \ - NLOHMANN_JSON_PASTE46, \ - NLOHMANN_JSON_PASTE45, \ - NLOHMANN_JSON_PASTE44, \ - NLOHMANN_JSON_PASTE43, \ - NLOHMANN_JSON_PASTE42, \ - NLOHMANN_JSON_PASTE41, \ - NLOHMANN_JSON_PASTE40, \ - NLOHMANN_JSON_PASTE39, \ - NLOHMANN_JSON_PASTE38, \ - NLOHMANN_JSON_PASTE37, \ - NLOHMANN_JSON_PASTE36, \ - NLOHMANN_JSON_PASTE35, \ - NLOHMANN_JSON_PASTE34, \ - NLOHMANN_JSON_PASTE33, \ - NLOHMANN_JSON_PASTE32, \ - NLOHMANN_JSON_PASTE31, \ - NLOHMANN_JSON_PASTE30, \ - NLOHMANN_JSON_PASTE29, \ - NLOHMANN_JSON_PASTE28, \ - NLOHMANN_JSON_PASTE27, \ - NLOHMANN_JSON_PASTE26, \ - NLOHMANN_JSON_PASTE25, \ - NLOHMANN_JSON_PASTE24, \ - NLOHMANN_JSON_PASTE23, \ - NLOHMANN_JSON_PASTE22, \ - NLOHMANN_JSON_PASTE21, \ - NLOHMANN_JSON_PASTE20, \ - NLOHMANN_JSON_PASTE19, \ - NLOHMANN_JSON_PASTE18, \ - NLOHMANN_JSON_PASTE17, \ - NLOHMANN_JSON_PASTE16, \ - NLOHMANN_JSON_PASTE15, \ - NLOHMANN_JSON_PASTE14, \ - NLOHMANN_JSON_PASTE13, \ - NLOHMANN_JSON_PASTE12, \ - NLOHMANN_JSON_PASTE11, \ - NLOHMANN_JSON_PASTE10, \ - NLOHMANN_JSON_PASTE9, \ - NLOHMANN_JSON_PASTE8, \ - NLOHMANN_JSON_PASTE7, \ - NLOHMANN_JSON_PASTE6, \ - NLOHMANN_JSON_PASTE5, \ - NLOHMANN_JSON_PASTE4, \ - NLOHMANN_JSON_PASTE3, \ - NLOHMANN_JSON_PASTE2, \ - NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) -#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) -#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) -#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) -#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) -#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) -#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) -#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) -#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) -#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) -#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) -#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) -#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) -#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) -#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) -#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) -#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) -#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) -#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) -#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) -#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) -#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) -#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) -#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) -#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) -#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) -#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) -#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) -#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) -#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) -#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) -#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) -#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) -#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) -#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) -#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) -#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) -#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) -#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) -#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) -#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) -#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) -#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) -#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) -#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) -#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) -#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) -#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) -#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) -#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) -#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) -#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) -#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) -#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) -#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) -#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) -#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) -#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) -#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) -#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) -#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) -#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) -#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) -#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) - -#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; -#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_INTRUSIVE -@since version 3.9.0 -*/ -#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ - friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - -/*! -@brief macro -@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE -@since version 3.9.0 -*/ -#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ - inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ - inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } - - -// inspired from https://stackoverflow.com/a/26745591 -// allows to call any std function as if (e.g. with begin): -// using std::begin; begin(x); -// -// it allows using the detected idiom to retrieve the return type -// of such an expression -#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ - namespace detail { \ - using std::std_name; \ - \ - template \ - using result_of_##std_name = decltype(std_name(std::declval()...)); \ - } \ - \ - namespace detail2 { \ - struct std_name##_tag \ - { \ - }; \ - \ - template \ - std_name##_tag std_name(T&&...); \ - \ - template \ - using result_of_##std_name = decltype(std_name(std::declval()...)); \ - \ - template \ - struct would_call_std_##std_name \ - { \ - static constexpr auto const value = ::nlohmann::detail:: \ - is_detected_exact::value; \ - }; \ - } /* namespace detail2 */ \ - \ - template \ - struct would_call_std_##std_name : detail2::would_call_std_##std_name \ - { \ - } - -#ifndef JSON_USE_IMPLICIT_CONVERSIONS - #define JSON_USE_IMPLICIT_CONVERSIONS 1 -#endif - -#if JSON_USE_IMPLICIT_CONVERSIONS - #define JSON_EXPLICIT -#else - #define JSON_EXPLICIT explicit -#endif - -#ifndef JSON_DIAGNOSTICS - #define JSON_DIAGNOSTICS 0 -#endif - - -namespace nlohmann -{ -namespace detail -{ - -/*! -@brief replace all occurrences of a substring by another string - -@param[in,out] s the string to manipulate; changed so that all - occurrences of @a f are replaced with @a t -@param[in] f the substring to replace with @a t -@param[in] t the string to replace @a f - -@pre The search string @a f must not be empty. **This precondition is -enforced with an assertion.** - -@since version 2.0.0 -*/ -inline void replace_substring(std::string& s, const std::string& f, - const std::string& t) -{ - JSON_ASSERT(!f.empty()); - for (auto pos = s.find(f); // find first occurrence of f - pos != std::string::npos; // make sure f was found - s.replace(pos, f.size(), t), // replace with t, and - pos = s.find(f, pos + t.size())) // find next occurrence of f - {} -} - -/*! - * @brief string escaping as described in RFC 6901 (Sect. 4) - * @param[in] s string to escape - * @return escaped string - * - * Note the order of escaping "~" to "~0" and "/" to "~1" is important. - */ -inline std::string escape(std::string s) -{ - replace_substring(s, "~", "~0"); - replace_substring(s, "/", "~1"); - return s; -} - -/*! - * @brief string unescaping as described in RFC 6901 (Sect. 4) - * @param[in] s string to unescape - * @return unescaped string - * - * Note the order of escaping "~1" to "/" and "~0" to "~" is important. - */ -static void unescape(std::string& s) -{ - replace_substring(s, "~1", "/"); - replace_substring(s, "~0", "~"); -} - -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // size_t - -namespace nlohmann -{ -namespace detail -{ -/// struct to capture the start position of the current token -struct position_t -{ - /// the total number of characters read - std::size_t chars_read_total = 0; - /// the number of characters read in the current line - std::size_t chars_read_current_line = 0; - /// the number of lines read - std::size_t lines_read = 0; - - /// conversion to size_t to preserve SAX interface - constexpr operator size_t() const - { - return chars_read_total; - } -}; - -} // namespace detail -} // namespace nlohmann - -// #include - - -namespace nlohmann -{ -namespace detail -{ -//////////////// -// exceptions // -//////////////// - -/// @brief general exception of the @ref basic_json class -/// @sa https://json.nlohmann.me/api/basic_json/exception/ -class exception : public std::exception -{ - public: - /// returns the explanatory string - const char* what() const noexcept override - { - return m.what(); - } - - /// the id of the exception - const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) - - protected: - JSON_HEDLEY_NON_NULL(3) - exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) - - static std::string name(const std::string& ename, int id_) - { - return "[json.exception." + ename + "." + std::to_string(id_) + "] "; - } - - template - static std::string diagnostics(const BasicJsonType& leaf_element) - { -#if JSON_DIAGNOSTICS - std::vector tokens; - for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) - { - switch (current->m_parent->type()) - { - case value_t::array: - { - for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) - { - if (¤t->m_parent->m_value.array->operator[](i) == current) - { - tokens.emplace_back(std::to_string(i)); - break; - } - } - break; - } - - case value_t::object: - { - for (const auto& element : *current->m_parent->m_value.object) - { - if (&element.second == current) - { - tokens.emplace_back(element.first.c_str()); - break; - } - } - break; - } - - case value_t::null: // LCOV_EXCL_LINE - case value_t::string: // LCOV_EXCL_LINE - case value_t::boolean: // LCOV_EXCL_LINE - case value_t::number_integer: // LCOV_EXCL_LINE - case value_t::number_unsigned: // LCOV_EXCL_LINE - case value_t::number_float: // LCOV_EXCL_LINE - case value_t::binary: // LCOV_EXCL_LINE - case value_t::discarded: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - break; // LCOV_EXCL_LINE - } - } - - if (tokens.empty()) - { - return ""; - } - - return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, - [](const std::string & a, const std::string & b) - { - return a + "/" + detail::escape(b); - }) + ") "; -#else - static_cast(leaf_element); - return ""; -#endif - } - - private: - /// an exception object as storage for error messages - std::runtime_error m; -}; - -/// @brief exception indicating a parse error -/// @sa https://json.nlohmann.me/api/basic_json/parse_error/ -class parse_error : public exception -{ - public: - /*! - @brief create a parse error exception - @param[in] id_ the id of the exception - @param[in] pos the position where the error occurred (or with - chars_read_total=0 if the position cannot be - determined) - @param[in] what_arg the explanatory string - @return parse_error object - */ - template - static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - position_string(pos) + ": " + exception::diagnostics(context) + what_arg; - return {id_, pos.chars_read_total, w.c_str()}; - } - - template - static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("parse_error", id_) + "parse error" + - (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + - ": " + exception::diagnostics(context) + what_arg; - return {id_, byte_, w.c_str()}; - } - - /*! - @brief byte index of the parse error - - The byte index of the last read character in the input file. - - @note For an input with n bytes, 1 is the index of the first character and - n+1 is the index of the terminating null byte or the end of file. - This also holds true when reading a byte vector (CBOR or MessagePack). - */ - const std::size_t byte; - - private: - parse_error(int id_, std::size_t byte_, const char* what_arg) - : exception(id_, what_arg), byte(byte_) {} - - static std::string position_string(const position_t& pos) - { - return " at line " + std::to_string(pos.lines_read + 1) + - ", column " + std::to_string(pos.chars_read_current_line); - } -}; - -/// @brief exception indicating errors with iterators -/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ -class invalid_iterator : public exception -{ - public: - template - static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - invalid_iterator(int id_, const char* what_arg) - : exception(id_, what_arg) {} -}; - -/// @brief exception indicating executing a member function with a wrong type -/// @sa https://json.nlohmann.me/api/basic_json/type_error/ -class type_error : public exception -{ - public: - template - static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/// @brief exception indicating access out of the defined range -/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ -class out_of_range : public exception -{ - public: - template - static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -/// @brief exception indicating other library errors -/// @sa https://json.nlohmann.me/api/basic_json/other_error/ -class other_error : public exception -{ - public: - template - static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) - { - std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; - return {id_, w.c_str()}; - } - - private: - JSON_HEDLEY_NON_NULL(3) - other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} -}; - -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // size_t -#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type -#include // index_sequence, make_index_sequence, index_sequence_for - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -template -using uncvref_t = typename std::remove_cv::type>::type; - -#ifdef JSON_HAS_CPP_14 - -// the following utilities are natively available in C++14 -using std::enable_if_t; -using std::index_sequence; -using std::make_index_sequence; -using std::index_sequence_for; - -#else - -// alias templates to reduce boilerplate -template -using enable_if_t = typename std::enable_if::type; - -// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h -// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. - -//// START OF CODE FROM GOOGLE ABSEIL - -// integer_sequence -// -// Class template representing a compile-time integer sequence. An instantiation -// of `integer_sequence` has a sequence of integers encoded in its -// type through its template arguments (which is a common need when -// working with C++11 variadic templates). `absl::integer_sequence` is designed -// to be a drop-in replacement for C++14's `std::integer_sequence`. -// -// Example: -// -// template< class T, T... Ints > -// void user_function(integer_sequence); -// -// int main() -// { -// // user_function's `T` will be deduced to `int` and `Ints...` -// // will be deduced to `0, 1, 2, 3, 4`. -// user_function(make_integer_sequence()); -// } -template -struct integer_sequence -{ - using value_type = T; - static constexpr std::size_t size() noexcept - { - return sizeof...(Ints); - } -}; - -// index_sequence -// -// A helper template for an `integer_sequence` of `size_t`, -// `absl::index_sequence` is designed to be a drop-in replacement for C++14's -// `std::index_sequence`. -template -using index_sequence = integer_sequence; - -namespace utility_internal -{ - -template -struct Extend; - -// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. -template -struct Extend, SeqSize, 0> -{ - using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; -}; - -template -struct Extend, SeqSize, 1> -{ - using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; -}; - -// Recursion helper for 'make_integer_sequence'. -// 'Gen::type' is an alias for 'integer_sequence'. -template -struct Gen -{ - using type = - typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; -}; - -template -struct Gen -{ - using type = integer_sequence; -}; - -} // namespace utility_internal - -// Compile-time sequences of integers - -// make_integer_sequence -// -// This template alias is equivalent to -// `integer_sequence`, and is designed to be a drop-in -// replacement for C++14's `std::make_integer_sequence`. -template -using make_integer_sequence = typename utility_internal::Gen::type; - -// make_index_sequence -// -// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, -// and is designed to be a drop-in replacement for C++14's -// `std::make_index_sequence`. -template -using make_index_sequence = make_integer_sequence; - -// index_sequence_for -// -// Converts a typename pack into an index sequence of the same length, and -// is designed to be a drop-in replacement for C++14's -// `std::index_sequence_for()` -template -using index_sequence_for = make_index_sequence; - -//// END OF CODE FROM GOOGLE ABSEIL - -#endif - -// dispatch utility (taken from ranges-v3) -template struct priority_tag : priority_tag < N - 1 > {}; -template<> struct priority_tag<0> {}; - -// taken from ranges-v3 -template -struct static_const -{ - static constexpr T value{}; -}; - -template -constexpr T static_const::value; // NOLINT(readability-redundant-declaration) - -} // namespace detail -} // namespace nlohmann - -// #include - - -namespace nlohmann -{ -namespace detail -{ -// dispatching helper struct -template struct identity_tag {}; -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // numeric_limits -#include // false_type, is_constructible, is_integral, is_same, true_type -#include // declval -#include // tuple - -// #include - - -// #include - - -#include // random_access_iterator_tag - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -struct iterator_types {}; - -template -struct iterator_types < - It, - void_t> -{ - using difference_type = typename It::difference_type; - using value_type = typename It::value_type; - using pointer = typename It::pointer; - using reference = typename It::reference; - using iterator_category = typename It::iterator_category; -}; - -// This is required as some compilers implement std::iterator_traits in a way that -// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. -template -struct iterator_traits -{ -}; - -template -struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> - : iterator_types -{ -}; - -template -struct iterator_traits::value>> -{ - using iterator_category = std::random_access_iterator_tag; - using value_type = T; - using difference_type = ptrdiff_t; - using pointer = T*; - using reference = T&; -}; -} // namespace detail -} // namespace nlohmann - -// #include - - -// #include - - -namespace nlohmann -{ -NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); -} // namespace nlohmann - -// #include - - -// #include - - -namespace nlohmann -{ -NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); -} // namespace nlohmann - -// #include - -// #include - -// #include -#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ -#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ - -#include // int64_t, uint64_t -#include // map -#include // allocator -#include // string -#include // vector - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -/*! -@brief default JSONSerializer template argument - -This serializer ignores the template arguments and uses ADL -([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) -for serialization. -*/ -template -struct adl_serializer; - -/// a class to store JSON values -/// @sa https://json.nlohmann.me/api/basic_json/ -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer, - class BinaryType = std::vector> -class basic_json; - -/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document -/// @sa https://json.nlohmann.me/api/json_pointer/ -template -class json_pointer; - -/*! -@brief default specialization -@sa https://json.nlohmann.me/api/json/ -*/ -using json = basic_json<>; - -/// @brief a minimal map-like container that preserves insertion order -/// @sa https://json.nlohmann.me/api/ordered_map/ -template -struct ordered_map; - -/// @brief specialization that maintains the insertion order of object keys -/// @sa https://json.nlohmann.me/api/ordered_json/ -using ordered_json = basic_json; - -} // namespace nlohmann - -#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ - - -namespace nlohmann -{ -/*! -@brief detail namespace with internal helper functions - -This namespace collects functions that should not be exposed, -implementations of some @ref basic_json methods, and meta-programming helpers. - -@since version 2.1.0 -*/ -namespace detail -{ -///////////// -// helpers // -///////////// - -// Note to maintainers: -// -// Every trait in this file expects a non CV-qualified type. -// The only exceptions are in the 'aliases for detected' section -// (i.e. those of the form: decltype(T::member_function(std::declval()))) -// -// In this case, T has to be properly CV-qualified to constraint the function arguments -// (e.g. to_json(BasicJsonType&, const T&)) - -template struct is_basic_json : std::false_type {}; - -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct is_basic_json : std::true_type {}; - -////////////////////// -// json_ref helpers // -////////////////////// - -template -class json_ref; - -template -struct is_json_ref : std::false_type {}; - -template -struct is_json_ref> : std::true_type {}; - -////////////////////////// -// aliases for detected // -////////////////////////// - -template -using mapped_type_t = typename T::mapped_type; - -template -using key_type_t = typename T::key_type; - -template -using value_type_t = typename T::value_type; - -template -using difference_type_t = typename T::difference_type; - -template -using pointer_t = typename T::pointer; - -template -using reference_t = typename T::reference; - -template -using iterator_category_t = typename T::iterator_category; - -template -using to_json_function = decltype(T::to_json(std::declval()...)); - -template -using from_json_function = decltype(T::from_json(std::declval()...)); - -template -using get_template_function = decltype(std::declval().template get()); - -// trait checking if JSONSerializer::from_json(json const&, udt&) exists -template -struct has_from_json : std::false_type {}; - -// trait checking if j.get is valid -// use this trait instead of std::is_constructible or std::is_convertible, -// both rely on, or make use of implicit conversions, and thus fail when T -// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) -template -struct is_getable -{ - static constexpr bool value = is_detected::value; -}; - -template -struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -// This trait checks if JSONSerializer::from_json(json const&) exists -// this overload is used for non-default-constructible user-defined-types -template -struct has_non_default_from_json : std::false_type {}; - -template -struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - -// This trait checks if BasicJsonType::json_serializer::to_json exists -// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. -template -struct has_to_json : std::false_type {}; - -template -struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> -{ - using serializer = typename BasicJsonType::template json_serializer; - - static constexpr bool value = - is_detected_exact::value; -}; - - -/////////////////// -// is_ functions // -/////////////////// - -// https://en.cppreference.com/w/cpp/types/conjunction -template struct conjunction : std::true_type { }; -template struct conjunction : B1 { }; -template -struct conjunction -: std::conditional, B1>::type {}; - -// https://en.cppreference.com/w/cpp/types/negation -template struct negation : std::integral_constant < bool, !B::value > { }; - -// Reimplementation of is_constructible and is_default_constructible, due to them being broken for -// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). -// This causes compile errors in e.g. clang 3.5 or gcc 4.9. -template -struct is_default_constructible : std::is_default_constructible {}; - -template -struct is_default_constructible> - : conjunction, is_default_constructible> {}; - -template -struct is_default_constructible> - : conjunction, is_default_constructible> {}; - -template -struct is_default_constructible> - : conjunction...> {}; - -template -struct is_default_constructible> - : conjunction...> {}; - - -template -struct is_constructible : std::is_constructible {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - -template -struct is_constructible> : is_default_constructible> {}; - - -template -struct is_iterator_traits : std::false_type {}; - -template -struct is_iterator_traits> -{ - private: - using traits = iterator_traits; - - public: - static constexpr auto value = - is_detected::value && - is_detected::value && - is_detected::value && - is_detected::value && - is_detected::value; -}; - -template -struct is_range -{ - private: - using t_ref = typename std::add_lvalue_reference::type; - - using iterator = detected_t; - using sentinel = detected_t; - - // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator - // and https://en.cppreference.com/w/cpp/iterator/sentinel_for - // but reimplementing these would be too much work, as a lot of other concepts are used underneath - static constexpr auto is_iterator_begin = - is_iterator_traits>::value; - - public: - static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; -}; - -template -using iterator_t = enable_if_t::value, result_of_begin())>>; - -template -using range_value_t = value_type_t>>; - -// The following implementation of is_complete_type is taken from -// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ -// and is written by Xiang Fan who agreed to using it in this library. - -template -struct is_complete_type : std::false_type {}; - -template -struct is_complete_type : std::true_type {}; - -template -struct is_compatible_object_type_impl : std::false_type {}; - -template -struct is_compatible_object_type_impl < - BasicJsonType, CompatibleObjectType, - enable_if_t < is_detected::value&& - is_detected::value >> -{ - using object_t = typename BasicJsonType::object_t; - - // macOS's is_constructible does not play well with nonesuch... - static constexpr bool value = - is_constructible::value && - is_constructible::value; -}; - -template -struct is_compatible_object_type - : is_compatible_object_type_impl {}; - -template -struct is_constructible_object_type_impl : std::false_type {}; - -template -struct is_constructible_object_type_impl < - BasicJsonType, ConstructibleObjectType, - enable_if_t < is_detected::value&& - is_detected::value >> -{ - using object_t = typename BasicJsonType::object_t; - - static constexpr bool value = - (is_default_constructible::value && - (std::is_move_assignable::value || - std::is_copy_assignable::value) && - (is_constructible::value && - std::is_same < - typename object_t::mapped_type, - typename ConstructibleObjectType::mapped_type >::value)) || - (has_from_json::value || - has_non_default_from_json < - BasicJsonType, - typename ConstructibleObjectType::mapped_type >::value); -}; - -template -struct is_constructible_object_type - : is_constructible_object_type_impl {}; - -template -struct is_compatible_string_type -{ - static constexpr auto value = - is_constructible::value; -}; - -template -struct is_constructible_string_type -{ - static constexpr auto value = - is_constructible::value; -}; - -template -struct is_compatible_array_type_impl : std::false_type {}; - -template -struct is_compatible_array_type_impl < - BasicJsonType, CompatibleArrayType, - enable_if_t < - is_detected::value&& - is_iterator_traits>>::value&& -// special case for types like std::filesystem::path whose iterator's value_type are themselves -// c.f. https://github.com/nlohmann/json/pull/3073 - !std::is_same>::value >> -{ - static constexpr bool value = - is_constructible>::value; -}; - -template -struct is_compatible_array_type - : is_compatible_array_type_impl {}; - -template -struct is_constructible_array_type_impl : std::false_type {}; - -template -struct is_constructible_array_type_impl < - BasicJsonType, ConstructibleArrayType, - enable_if_t::value >> - : std::true_type {}; - -template -struct is_constructible_array_type_impl < - BasicJsonType, ConstructibleArrayType, - enable_if_t < !std::is_same::value&& - !is_compatible_string_type::value&& - is_default_constructible::value&& -(std::is_move_assignable::value || - std::is_copy_assignable::value)&& -is_detected::value&& -is_iterator_traits>>::value&& -is_detected::value&& -// special case for types like std::filesystem::path whose iterator's value_type are themselves -// c.f. https://github.com/nlohmann/json/pull/3073 -!std::is_same>::value&& - is_complete_type < - detected_t>::value >> -{ - using value_type = range_value_t; - - static constexpr bool value = - std::is_same::value || - has_from_json::value || - has_non_default_from_json < - BasicJsonType, - value_type >::value; -}; - -template -struct is_constructible_array_type - : is_constructible_array_type_impl {}; - -template -struct is_compatible_integer_type_impl : std::false_type {}; - -template -struct is_compatible_integer_type_impl < - RealIntegerType, CompatibleNumberIntegerType, - enable_if_t < std::is_integral::value&& - std::is_integral::value&& - !std::is_same::value >> -{ - // is there an assert somewhere on overflows? - using RealLimits = std::numeric_limits; - using CompatibleLimits = std::numeric_limits; - - static constexpr auto value = - is_constructible::value && - CompatibleLimits::is_integer && - RealLimits::is_signed == CompatibleLimits::is_signed; -}; - -template -struct is_compatible_integer_type - : is_compatible_integer_type_impl {}; - -template -struct is_compatible_type_impl: std::false_type {}; - -template -struct is_compatible_type_impl < - BasicJsonType, CompatibleType, - enable_if_t::value >> -{ - static constexpr bool value = - has_to_json::value; -}; - -template -struct is_compatible_type - : is_compatible_type_impl {}; - -template -struct is_constructible_tuple : std::false_type {}; - -template -struct is_constructible_tuple> : conjunction...> {}; - -// a naive helper to check if a type is an ordered_map (exploits the fact that -// ordered_map inherits capacity() from std::vector) -template -struct is_ordered_map -{ - using one = char; - - struct two - { - char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - }; - - template static one test( decltype(&C::capacity) ) ; - template static two test(...); - - enum { value = sizeof(test(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) -}; - -// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324) -template < typename T, typename U, enable_if_t < !std::is_same::value, int > = 0 > -T conditional_static_cast(U value) -{ - return static_cast(value); -} - -template::value, int> = 0> -T conditional_static_cast(U value) -{ - return value; -} - -} // namespace detail -} // namespace nlohmann - -// #include - - -#if JSON_HAS_EXPERIMENTAL_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::experimental::filesystem; -} // namespace nlohmann::detail -#elif JSON_HAS_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::filesystem; -} // namespace nlohmann::detail -#endif - -namespace nlohmann -{ -namespace detail -{ -template -void from_json(const BasicJsonType& j, typename std::nullptr_t& n) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_null())) - { - JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); - } - n = nullptr; -} - -// overloads for basic_json template parameters -template < typename BasicJsonType, typename ArithmeticType, - enable_if_t < std::is_arithmetic::value&& - !std::is_same::value, - int > = 0 > -void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) -{ - switch (static_cast(j)) - { - case value_t::number_unsigned: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_integer: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_float: - { - val = static_cast(*j.template get_ptr()); - break; - } - - case value_t::null: - case value_t::object: - case value_t::array: - case value_t::string: - case value_t::boolean: - case value_t::binary: - case value_t::discarded: - default: - JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); - } -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) - { - JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); - } - b = *j.template get_ptr(); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); - } - s = *j.template get_ptr(); -} - -template < - typename BasicJsonType, typename ConstructibleStringType, - enable_if_t < - is_constructible_string_type::value&& - !std::is_same::value, - int > = 0 > -void from_json(const BasicJsonType& j, ConstructibleStringType& s) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); - } - - s = *j.template get_ptr(); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) -{ - get_arithmetic_value(j, val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) -{ - get_arithmetic_value(j, val); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) -{ - get_arithmetic_value(j, val); -} - -template::value, int> = 0> -void from_json(const BasicJsonType& j, EnumType& e) -{ - typename std::underlying_type::type val; - get_arithmetic_value(j, val); - e = static_cast(val); -} - -// forward_list doesn't have an insert method -template::value, int> = 0> -void from_json(const BasicJsonType& j, std::forward_list& l) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - l.clear(); - std::transform(j.rbegin(), j.rend(), - std::front_inserter(l), [](const BasicJsonType & i) - { - return i.template get(); - }); -} - -// valarray doesn't have an insert method -template::value, int> = 0> -void from_json(const BasicJsonType& j, std::valarray& l) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - l.resize(j.size()); - std::transform(j.begin(), j.end(), std::begin(l), - [](const BasicJsonType & elem) - { - return elem.template get(); - }); -} - -template -auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) --> decltype(j.template get(), void()) -{ - for (std::size_t i = 0; i < N; ++i) - { - arr[i] = j.at(i).template get(); - } -} - -template -void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) -{ - arr = *j.template get_ptr(); -} - -template -auto from_json_array_impl(const BasicJsonType& j, std::array& arr, - priority_tag<2> /*unused*/) --> decltype(j.template get(), void()) -{ - for (std::size_t i = 0; i < N; ++i) - { - arr[i] = j.at(i).template get(); - } -} - -template::value, - int> = 0> -auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) --> decltype( - arr.reserve(std::declval()), - j.template get(), - void()) -{ - using std::end; - - ConstructibleArrayType ret; - ret.reserve(j.size()); - std::transform(j.begin(), j.end(), - std::inserter(ret, end(ret)), [](const BasicJsonType & i) - { - // get() returns *this, this won't call a from_json - // method when value_type is BasicJsonType - return i.template get(); - }); - arr = std::move(ret); -} - -template::value, - int> = 0> -void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, - priority_tag<0> /*unused*/) -{ - using std::end; - - ConstructibleArrayType ret; - std::transform( - j.begin(), j.end(), std::inserter(ret, end(ret)), - [](const BasicJsonType & i) - { - // get() returns *this, this won't call a from_json - // method when value_type is BasicJsonType - return i.template get(); - }); - arr = std::move(ret); -} - -template < typename BasicJsonType, typename ConstructibleArrayType, - enable_if_t < - is_constructible_array_type::value&& - !is_constructible_object_type::value&& - !is_constructible_string_type::value&& - !std::is_same::value&& - !is_basic_json::value, - int > = 0 > -auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) --> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), -j.template get(), -void()) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - - from_json_array_impl(j, arr, priority_tag<3> {}); -} - -template < typename BasicJsonType, typename T, std::size_t... Idx > -std::array from_json_inplace_array_impl(BasicJsonType&& j, - identity_tag> /*unused*/, index_sequence /*unused*/) -{ - return { { std::forward(j).at(Idx).template get()... } }; -} - -template < typename BasicJsonType, typename T, std::size_t N > -auto from_json(BasicJsonType&& j, identity_tag> tag) --> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - - return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); -} - -template -void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) - { - JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); - } - - bin = *j.template get_ptr(); -} - -template::value, int> = 0> -void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_object())) - { - JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); - } - - ConstructibleObjectType ret; - const auto* inner_object = j.template get_ptr(); - using value_type = typename ConstructibleObjectType::value_type; - std::transform( - inner_object->begin(), inner_object->end(), - std::inserter(ret, ret.begin()), - [](typename BasicJsonType::object_t::value_type const & p) - { - return value_type(p.first, p.second.template get()); - }); - obj = std::move(ret); -} - -// overload for arithmetic types, not chosen for basic_json template arguments -// (BooleanType, etc..); note: Is it really necessary to provide explicit -// overloads for boolean_t etc. in case of a custom BooleanType which is not -// an arithmetic type? -template < typename BasicJsonType, typename ArithmeticType, - enable_if_t < - std::is_arithmetic::value&& - !std::is_same::value&& - !std::is_same::value&& - !std::is_same::value&& - !std::is_same::value, - int > = 0 > -void from_json(const BasicJsonType& j, ArithmeticType& val) -{ - switch (static_cast(j)) - { - case value_t::number_unsigned: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_integer: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::number_float: - { - val = static_cast(*j.template get_ptr()); - break; - } - case value_t::boolean: - { - val = static_cast(*j.template get_ptr()); - break; - } - - case value_t::null: - case value_t::object: - case value_t::array: - case value_t::string: - case value_t::binary: - case value_t::discarded: - default: - JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); - } -} - -template -std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) -{ - return std::make_tuple(std::forward(j).at(Idx).template get()...); -} - -template < typename BasicJsonType, class A1, class A2 > -std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) -{ - return {std::forward(j).at(0).template get(), - std::forward(j).at(1).template get()}; -} - -template -void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) -{ - p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); -} - -template -std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) -{ - return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); -} - -template -void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) -{ - t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); -} - -template -auto from_json(BasicJsonType&& j, TupleRelated&& t) --> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - - return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); -} - -template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, - typename = enable_if_t < !std::is_constructible < - typename BasicJsonType::string_t, Key >::value >> -void from_json(const BasicJsonType& j, std::map& m) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - m.clear(); - for (const auto& p : j) - { - if (JSON_HEDLEY_UNLIKELY(!p.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); - } - m.emplace(p.at(0).template get(), p.at(1).template get()); - } -} - -template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, - typename = enable_if_t < !std::is_constructible < - typename BasicJsonType::string_t, Key >::value >> -void from_json(const BasicJsonType& j, std::unordered_map& m) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); - } - m.clear(); - for (const auto& p : j) - { - if (JSON_HEDLEY_UNLIKELY(!p.is_array())) - { - JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); - } - m.emplace(p.at(0).template get(), p.at(1).template get()); - } -} - -#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM -template -void from_json(const BasicJsonType& j, std_fs::path& p) -{ - if (JSON_HEDLEY_UNLIKELY(!j.is_string())) - { - JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); - } - p = *j.template get_ptr(); -} -#endif - -struct from_json_fn -{ - template - auto operator()(const BasicJsonType& j, T&& val) const - noexcept(noexcept(from_json(j, std::forward(val)))) - -> decltype(from_json(j, std::forward(val))) - { - return from_json(j, std::forward(val)); - } -}; -} // namespace detail - -/// namespace to hold default `from_json` function -/// to see why this is required: -/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html -namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) -{ -constexpr const auto& from_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) -} // namespace -} // namespace nlohmann - -// #include - - -#include // copy -#include // begin, end -#include // string -#include // tuple, get -#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type -#include // move, forward, declval, pair -#include // valarray -#include // vector - -// #include - -// #include - - -#include // size_t -#include // input_iterator_tag -#include // string, to_string -#include // tuple_size, get, tuple_element -#include // move - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -void int_to_string( string_type& target, std::size_t value ) -{ - // For ADL - using std::to_string; - target = to_string(value); -} -template class iteration_proxy_value -{ - public: - using difference_type = std::ptrdiff_t; - using value_type = iteration_proxy_value; - using pointer = value_type * ; - using reference = value_type & ; - using iterator_category = std::input_iterator_tag; - using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; - - private: - /// the iterator - IteratorType anchor; - /// an index for arrays (used to create key names) - std::size_t array_index = 0; - /// last stringified array index - mutable std::size_t array_index_last = 0; - /// a string representation of the array index - mutable string_type array_index_str = "0"; - /// an empty string (to return a reference for primitive values) - const string_type empty_str{}; - - public: - explicit iteration_proxy_value(IteratorType it) noexcept - : anchor(std::move(it)) - {} - - /// dereference operator (needed for range-based for) - iteration_proxy_value& operator*() - { - return *this; - } - - /// increment operator (needed for range-based for) - iteration_proxy_value& operator++() - { - ++anchor; - ++array_index; - - return *this; - } - - /// equality operator (needed for InputIterator) - bool operator==(const iteration_proxy_value& o) const - { - return anchor == o.anchor; - } - - /// inequality operator (needed for range-based for) - bool operator!=(const iteration_proxy_value& o) const - { - return anchor != o.anchor; - } - - /// return key of the iterator - const string_type& key() const - { - JSON_ASSERT(anchor.m_object != nullptr); - - switch (anchor.m_object->type()) - { - // use integer array index as key - case value_t::array: - { - if (array_index != array_index_last) - { - int_to_string( array_index_str, array_index ); - array_index_last = array_index; - } - return array_index_str; - } - - // use key from the object - case value_t::object: - return anchor.key(); - - // use an empty key for all primitive types - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return empty_str; - } - } - - /// return value of the iterator - typename IteratorType::reference value() const - { - return anchor.value(); - } -}; - -/// proxy class for the items() function -template class iteration_proxy -{ - private: - /// the container to iterate - typename IteratorType::reference container; - - public: - /// construct iteration proxy from a container - explicit iteration_proxy(typename IteratorType::reference cont) noexcept - : container(cont) {} - - /// return iterator begin (needed for range-based for) - iteration_proxy_value begin() noexcept - { - return iteration_proxy_value(container.begin()); - } - - /// return iterator end (needed for range-based for) - iteration_proxy_value end() noexcept - { - return iteration_proxy_value(container.end()); - } -}; -// Structured Bindings Support -// For further reference see https://blog.tartanllama.xyz/structured-bindings/ -// And see https://github.com/nlohmann/json/pull/1391 -template = 0> -auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) -{ - return i.key(); -} -// Structured Bindings Support -// For further reference see https://blog.tartanllama.xyz/structured-bindings/ -// And see https://github.com/nlohmann/json/pull/1391 -template = 0> -auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) -{ - return i.value(); -} -} // namespace detail -} // namespace nlohmann - -// The Addition to the STD Namespace is required to add -// Structured Bindings Support to the iteration_proxy_value class -// For further reference see https://blog.tartanllama.xyz/structured-bindings/ -// And see https://github.com/nlohmann/json/pull/1391 -namespace std -{ -#if defined(__clang__) - // Fix: https://github.com/nlohmann/json/issues/1401 - #pragma clang diagnostic push - #pragma clang diagnostic ignored "-Wmismatched-tags" -#endif -template -class tuple_size<::nlohmann::detail::iteration_proxy_value> - : public std::integral_constant {}; - -template -class tuple_element> -{ - public: - using type = decltype( - get(std::declval < - ::nlohmann::detail::iteration_proxy_value> ())); -}; -#if defined(__clang__) - #pragma clang diagnostic pop -#endif -} // namespace std - -// #include - -// #include - -// #include - - -#if JSON_HAS_EXPERIMENTAL_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::experimental::filesystem; -} // namespace nlohmann::detail -#elif JSON_HAS_FILESYSTEM -#include -namespace nlohmann::detail -{ -namespace std_fs = std::filesystem; -} // namespace nlohmann::detail -#endif - -namespace nlohmann -{ -namespace detail -{ -////////////////// -// constructors // -////////////////// - -/* - * Note all external_constructor<>::construct functions need to call - * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an - * allocated value (e.g., a string). See bug issue - * https://github.com/nlohmann/json/issues/2865 for more information. - */ - -template struct external_constructor; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::boolean; - j.m_value = b; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::string; - j.m_value = s; - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::string; - j.m_value = std::move(s); - j.assert_invariant(); - } - - template < typename BasicJsonType, typename CompatibleStringType, - enable_if_t < !std::is_same::value, - int > = 0 > - static void construct(BasicJsonType& j, const CompatibleStringType& str) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::string; - j.m_value.string = j.template create(str); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::binary; - j.m_value = typename BasicJsonType::binary_t(b); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::binary; - j.m_value = typename BasicJsonType::binary_t(std::move(b)); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::number_float; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::number_unsigned; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::number_integer; - j.m_value = val; - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = arr; - j.set_parents(); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = std::move(arr); - j.set_parents(); - j.assert_invariant(); - } - - template < typename BasicJsonType, typename CompatibleArrayType, - enable_if_t < !std::is_same::value, - int > = 0 > - static void construct(BasicJsonType& j, const CompatibleArrayType& arr) - { - using std::begin; - using std::end; - - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value.array = j.template create(begin(arr), end(arr)); - j.set_parents(); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, const std::vector& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->reserve(arr.size()); - for (const bool x : arr) - { - j.m_value.array->push_back(x); - j.set_parent(j.m_value.array->back()); - } - j.assert_invariant(); - } - - template::value, int> = 0> - static void construct(BasicJsonType& j, const std::valarray& arr) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::array; - j.m_value = value_t::array; - j.m_value.array->resize(arr.size()); - if (arr.size() > 0) - { - std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); - } - j.set_parents(); - j.assert_invariant(); - } -}; - -template<> -struct external_constructor -{ - template - static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::object; - j.m_value = obj; - j.set_parents(); - j.assert_invariant(); - } - - template - static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) - { - j.m_value.destroy(j.m_type); - j.m_type = value_t::object; - j.m_value = std::move(obj); - j.set_parents(); - j.assert_invariant(); - } - - template < typename BasicJsonType, typename CompatibleObjectType, - enable_if_t < !std::is_same::value, int > = 0 > - static void construct(BasicJsonType& j, const CompatibleObjectType& obj) - { - using std::begin; - using std::end; - - j.m_value.destroy(j.m_type); - j.m_type = value_t::object; - j.m_value.object = j.template create(begin(obj), end(obj)); - j.set_parents(); - j.assert_invariant(); - } -}; - -///////////// -// to_json // -///////////// - -template::value, int> = 0> -void to_json(BasicJsonType& j, T b) noexcept -{ - external_constructor::construct(j, b); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const CompatibleString& s) -{ - external_constructor::construct(j, s); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) -{ - external_constructor::construct(j, std::move(s)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, FloatType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept -{ - external_constructor::construct(j, static_cast(val)); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, EnumType e) noexcept -{ - using underlying_type = typename std::underlying_type::type; - external_constructor::construct(j, static_cast(e)); -} - -template -void to_json(BasicJsonType& j, const std::vector& e) -{ - external_constructor::construct(j, e); -} - -template < typename BasicJsonType, typename CompatibleArrayType, - enable_if_t < is_compatible_array_type::value&& - !is_compatible_object_type::value&& - !is_compatible_string_type::value&& - !std::is_same::value&& - !is_basic_json::value, - int > = 0 > -void to_json(BasicJsonType& j, const CompatibleArrayType& arr) -{ - external_constructor::construct(j, arr); -} - -template -void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) -{ - external_constructor::construct(j, bin); -} - -template::value, int> = 0> -void to_json(BasicJsonType& j, const std::valarray& arr) -{ - external_constructor::construct(j, std::move(arr)); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) -{ - external_constructor::construct(j, std::move(arr)); -} - -template < typename BasicJsonType, typename CompatibleObjectType, - enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > -void to_json(BasicJsonType& j, const CompatibleObjectType& obj) -{ - external_constructor::construct(j, obj); -} - -template -void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) -{ - external_constructor::construct(j, std::move(obj)); -} - -template < - typename BasicJsonType, typename T, std::size_t N, - enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - int > = 0 > -void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -{ - external_constructor::construct(j, arr); -} - -template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > -void to_json(BasicJsonType& j, const std::pair& p) -{ - j = { p.first, p.second }; -} - -// for https://github.com/nlohmann/json/pull/1134 -template>::value, int> = 0> -void to_json(BasicJsonType& j, const T& b) -{ - j = { {b.key(), b.value()} }; -} - -template -void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) -{ - j = { std::get(t)... }; -} - -template::value, int > = 0> -void to_json(BasicJsonType& j, const T& t) -{ - to_json_tuple_impl(j, t, make_index_sequence::value> {}); -} - -#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM -template -void to_json(BasicJsonType& j, const std_fs::path& p) -{ - j = p.string(); -} -#endif - -struct to_json_fn -{ - template - auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) - -> decltype(to_json(j, std::forward(val)), void()) - { - return to_json(j, std::forward(val)); - } -}; -} // namespace detail - -/// namespace to hold default `to_json` function -/// to see why this is required: -/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html -namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) -{ -constexpr const auto& to_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) -} // namespace -} // namespace nlohmann - -// #include - -// #include - - -namespace nlohmann -{ - -/// @sa https://json.nlohmann.me/api/adl_serializer/ -template -struct adl_serializer -{ - /// @brief convert a JSON value to any value type - /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ - template - static auto from_json(BasicJsonType && j, TargetType& val) noexcept( - noexcept(::nlohmann::from_json(std::forward(j), val))) - -> decltype(::nlohmann::from_json(std::forward(j), val), void()) - { - ::nlohmann::from_json(std::forward(j), val); - } - - /// @brief convert a JSON value to any value type - /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ - template - static auto from_json(BasicJsonType && j) noexcept( - noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) - -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) - { - return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); - } - - /// @brief convert any value type to a JSON value - /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ - template - static auto to_json(BasicJsonType& j, TargetType && val) noexcept( - noexcept(::nlohmann::to_json(j, std::forward(val)))) - -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) - { - ::nlohmann::to_json(j, std::forward(val)); - } -}; -} // namespace nlohmann - -// #include - - -#include // uint8_t, uint64_t -#include // tie -#include // move - -namespace nlohmann -{ - -/// @brief an internal type for a backed binary type -/// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ -template -class byte_container_with_subtype : public BinaryType -{ - public: - using container_type = BinaryType; - using subtype_type = std::uint64_t; - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype() noexcept(noexcept(container_type())) - : container_type() - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) - : container_type(b) - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) - : container_type(std::move(b)) - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) - : container_type(b) - , m_subtype(subtype_) - , m_has_subtype(true) - {} - - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ - byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) - : container_type(std::move(b)) - , m_subtype(subtype_) - , m_has_subtype(true) - {} - - bool operator==(const byte_container_with_subtype& rhs) const - { - return std::tie(static_cast(*this), m_subtype, m_has_subtype) == - std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); - } - - bool operator!=(const byte_container_with_subtype& rhs) const - { - return !(rhs == *this); - } - - /// @brief sets the binary subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ - void set_subtype(subtype_type subtype_) noexcept - { - m_subtype = subtype_; - m_has_subtype = true; - } - - /// @brief return the binary subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ - constexpr subtype_type subtype() const noexcept - { - return m_has_subtype ? m_subtype : static_cast(-1); - } - - /// @brief return whether the value has a subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ - constexpr bool has_subtype() const noexcept - { - return m_has_subtype; - } - - /// @brief clears the binary subtype - /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ - void clear_subtype() noexcept - { - m_subtype = 0; - m_has_subtype = false; - } - - private: - subtype_type m_subtype = 0; - bool m_has_subtype = false; -}; - -} // namespace nlohmann - -// #include - -// #include - -// #include - -// #include - - -#include // uint8_t -#include // size_t -#include // hash - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -// boost::hash_combine -inline std::size_t combine(std::size_t seed, std::size_t h) noexcept -{ - seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); - return seed; -} - -/*! -@brief hash a JSON value - -The hash function tries to rely on std::hash where possible. Furthermore, the -type of the JSON value is taken into account to have different hash values for -null, 0, 0U, and false, etc. - -@tparam BasicJsonType basic_json specialization -@param j JSON value to hash -@return hash value of j -*/ -template -std::size_t hash(const BasicJsonType& j) -{ - using string_t = typename BasicJsonType::string_t; - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - - const auto type = static_cast(j.type()); - switch (j.type()) - { - case BasicJsonType::value_t::null: - case BasicJsonType::value_t::discarded: - { - return combine(type, 0); - } - - case BasicJsonType::value_t::object: - { - auto seed = combine(type, j.size()); - for (const auto& element : j.items()) - { - const auto h = std::hash {}(element.key()); - seed = combine(seed, h); - seed = combine(seed, hash(element.value())); - } - return seed; - } - - case BasicJsonType::value_t::array: - { - auto seed = combine(type, j.size()); - for (const auto& element : j) - { - seed = combine(seed, hash(element)); - } - return seed; - } - - case BasicJsonType::value_t::string: - { - const auto h = std::hash {}(j.template get_ref()); - return combine(type, h); - } - - case BasicJsonType::value_t::boolean: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::number_integer: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::number_unsigned: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::number_float: - { - const auto h = std::hash {}(j.template get()); - return combine(type, h); - } - - case BasicJsonType::value_t::binary: - { - auto seed = combine(type, j.get_binary().size()); - const auto h = std::hash {}(j.get_binary().has_subtype()); - seed = combine(seed, h); - seed = combine(seed, static_cast(j.get_binary().subtype())); - for (const auto byte : j.get_binary()) - { - seed = combine(seed, std::hash {}(byte)); - } - return seed; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - return 0; // LCOV_EXCL_LINE - } -} - -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // generate_n -#include // array -#include // ldexp -#include // size_t -#include // uint8_t, uint16_t, uint32_t, uint64_t -#include // snprintf -#include // memcpy -#include // back_inserter -#include // numeric_limits -#include // char_traits, string -#include // make_pair, move -#include // vector - -// #include - -// #include - - -#include // array -#include // size_t -#include // strlen -#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next -#include // shared_ptr, make_shared, addressof -#include // accumulate -#include // string, char_traits -#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer -#include // pair, declval - -#ifndef JSON_NO_IO - #include // FILE * - #include // istream -#endif // JSON_NO_IO - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/// the supported input formats -enum class input_format_t { json, cbor, msgpack, ubjson, bson }; - -//////////////////// -// input adapters // -//////////////////// - -#ifndef JSON_NO_IO -/*! -Input adapter for stdio file access. This adapter read only 1 byte and do not use any - buffer. This adapter is a very low level adapter. -*/ -class file_input_adapter -{ - public: - using char_type = char; - - JSON_HEDLEY_NON_NULL(2) - explicit file_input_adapter(std::FILE* f) noexcept - : m_file(f) - {} - - // make class move-only - file_input_adapter(const file_input_adapter&) = delete; - file_input_adapter(file_input_adapter&&) noexcept = default; - file_input_adapter& operator=(const file_input_adapter&) = delete; - file_input_adapter& operator=(file_input_adapter&&) = delete; - ~file_input_adapter() = default; - - std::char_traits::int_type get_character() noexcept - { - return std::fgetc(m_file); - } - - private: - /// the file pointer to read from - std::FILE* m_file; -}; - - -/*! -Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at -beginning of input. Does not support changing the underlying std::streambuf -in mid-input. Maintains underlying std::istream and std::streambuf to support -subsequent use of standard std::istream operations to process any input -characters following those used in parsing the JSON input. Clears the -std::istream flags; any input errors (e.g., EOF) will be detected by the first -subsequent call for input from the std::istream. -*/ -class input_stream_adapter -{ - public: - using char_type = char; - - ~input_stream_adapter() - { - // clear stream flags; we use underlying streambuf I/O, do not - // maintain ifstream flags, except eof - if (is != nullptr) - { - is->clear(is->rdstate() & std::ios::eofbit); - } - } - - explicit input_stream_adapter(std::istream& i) - : is(&i), sb(i.rdbuf()) - {} - - // delete because of pointer members - input_stream_adapter(const input_stream_adapter&) = delete; - input_stream_adapter& operator=(input_stream_adapter&) = delete; - input_stream_adapter& operator=(input_stream_adapter&&) = delete; - - input_stream_adapter(input_stream_adapter&& rhs) noexcept - : is(rhs.is), sb(rhs.sb) - { - rhs.is = nullptr; - rhs.sb = nullptr; - } - - // std::istream/std::streambuf use std::char_traits::to_int_type, to - // ensure that std::char_traits::eof() and the character 0xFF do not - // end up as the same value, e.g. 0xFFFFFFFF. - std::char_traits::int_type get_character() - { - auto res = sb->sbumpc(); - // set eof manually, as we don't use the istream interface. - if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) - { - is->clear(is->rdstate() | std::ios::eofbit); - } - return res; - } - - private: - /// the associated input stream - std::istream* is = nullptr; - std::streambuf* sb = nullptr; -}; -#endif // JSON_NO_IO - -// General-purpose iterator-based adapter. It might not be as fast as -// theoretically possible for some containers, but it is extremely versatile. -template -class iterator_input_adapter -{ - public: - using char_type = typename std::iterator_traits::value_type; - - iterator_input_adapter(IteratorType first, IteratorType last) - : current(std::move(first)), end(std::move(last)) - {} - - typename std::char_traits::int_type get_character() - { - if (JSON_HEDLEY_LIKELY(current != end)) - { - auto result = std::char_traits::to_int_type(*current); - std::advance(current, 1); - return result; - } - - return std::char_traits::eof(); - } - - private: - IteratorType current; - IteratorType end; - - template - friend struct wide_string_input_helper; - - bool empty() const - { - return current == end; - } -}; - - -template -struct wide_string_input_helper; - -template -struct wide_string_input_helper -{ - // UTF-32 - static void fill_buffer(BaseInputAdapter& input, - std::array::int_type, 4>& utf8_bytes, - size_t& utf8_bytes_index, - size_t& utf8_bytes_filled) - { - utf8_bytes_index = 0; - - if (JSON_HEDLEY_UNLIKELY(input.empty())) - { - utf8_bytes[0] = std::char_traits::eof(); - utf8_bytes_filled = 1; - } - else - { - // get the current character - const auto wc = input.get_character(); - - // UTF-32 to UTF-8 encoding - if (wc < 0x80) - { - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - else if (wc <= 0x7FF) - { - utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); - utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 2; - } - else if (wc <= 0xFFFF) - { - utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 3; - } - else if (wc <= 0x10FFFF) - { - utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); - utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 4; - } - else - { - // unknown character - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - } - } -}; - -template -struct wide_string_input_helper -{ - // UTF-16 - static void fill_buffer(BaseInputAdapter& input, - std::array::int_type, 4>& utf8_bytes, - size_t& utf8_bytes_index, - size_t& utf8_bytes_filled) - { - utf8_bytes_index = 0; - - if (JSON_HEDLEY_UNLIKELY(input.empty())) - { - utf8_bytes[0] = std::char_traits::eof(); - utf8_bytes_filled = 1; - } - else - { - // get the current character - const auto wc = input.get_character(); - - // UTF-16 to UTF-8 encoding - if (wc < 0x80) - { - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - else if (wc <= 0x7FF) - { - utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); - utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 2; - } - else if (0xD800 > wc || wc >= 0xE000) - { - utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); - utf8_bytes_filled = 3; - } - else - { - if (JSON_HEDLEY_UNLIKELY(!input.empty())) - { - const auto wc2 = static_cast(input.get_character()); - const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); - utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); - utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); - utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); - utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); - utf8_bytes_filled = 4; - } - else - { - utf8_bytes[0] = static_cast::int_type>(wc); - utf8_bytes_filled = 1; - } - } - } - } -}; - -// Wraps another input apdater to convert wide character types into individual bytes. -template -class wide_string_input_adapter -{ - public: - using char_type = char; - - wide_string_input_adapter(BaseInputAdapter base) - : base_adapter(base) {} - - typename std::char_traits::int_type get_character() noexcept - { - // check if buffer needs to be filled - if (utf8_bytes_index == utf8_bytes_filled) - { - fill_buffer(); - - JSON_ASSERT(utf8_bytes_filled > 0); - JSON_ASSERT(utf8_bytes_index == 0); - } - - // use buffer - JSON_ASSERT(utf8_bytes_filled > 0); - JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); - return utf8_bytes[utf8_bytes_index++]; - } - - private: - BaseInputAdapter base_adapter; - - template - void fill_buffer() - { - wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); - } - - /// a buffer for UTF-8 bytes - std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; - - /// index to the utf8_codes array for the next valid byte - std::size_t utf8_bytes_index = 0; - /// number of valid bytes in the utf8_codes array - std::size_t utf8_bytes_filled = 0; -}; - - -template -struct iterator_input_adapter_factory -{ - using iterator_type = IteratorType; - using char_type = typename std::iterator_traits::value_type; - using adapter_type = iterator_input_adapter; - - static adapter_type create(IteratorType first, IteratorType last) - { - return adapter_type(std::move(first), std::move(last)); - } -}; - -template -struct is_iterator_of_multibyte -{ - using value_type = typename std::iterator_traits::value_type; - enum - { - value = sizeof(value_type) > 1 - }; -}; - -template -struct iterator_input_adapter_factory::value>> -{ - using iterator_type = IteratorType; - using char_type = typename std::iterator_traits::value_type; - using base_adapter_type = iterator_input_adapter; - using adapter_type = wide_string_input_adapter; - - static adapter_type create(IteratorType first, IteratorType last) - { - return adapter_type(base_adapter_type(std::move(first), std::move(last))); - } -}; - -// General purpose iterator-based input -template -typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) -{ - using factory_type = iterator_input_adapter_factory; - return factory_type::create(first, last); -} - -// Convenience shorthand from container to iterator -// Enables ADL on begin(container) and end(container) -// Encloses the using declarations in namespace for not to leak them to outside scope - -namespace container_input_adapter_factory_impl -{ - -using std::begin; -using std::end; - -template -struct container_input_adapter_factory {}; - -template -struct container_input_adapter_factory< ContainerType, - void_t()), end(std::declval()))>> - { - using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); - - static adapter_type create(const ContainerType& container) -{ - return input_adapter(begin(container), end(container)); -} - }; - -} // namespace container_input_adapter_factory_impl - -template -typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) -{ - return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); -} - -#ifndef JSON_NO_IO -// Special cases with fast paths -inline file_input_adapter input_adapter(std::FILE* file) -{ - return file_input_adapter(file); -} - -inline input_stream_adapter input_adapter(std::istream& stream) -{ - return input_stream_adapter(stream); -} - -inline input_stream_adapter input_adapter(std::istream&& stream) -{ - return input_stream_adapter(stream); -} -#endif // JSON_NO_IO - -using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); - -// Null-delimited strings, and the like. -template < typename CharT, - typename std::enable_if < - std::is_pointer::value&& - !std::is_array::value&& - std::is_integral::type>::value&& - sizeof(typename std::remove_pointer::type) == 1, - int >::type = 0 > -contiguous_bytes_input_adapter input_adapter(CharT b) -{ - auto length = std::strlen(reinterpret_cast(b)); - const auto* ptr = reinterpret_cast(b); - return input_adapter(ptr, ptr + length); -} - -template -auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -{ - return input_adapter(array, array + N); -} - -// This class only handles inputs of input_buffer_adapter type. -// It's required so that expressions like {ptr, len} can be implicitly cast -// to the correct adapter. -class span_input_adapter -{ - public: - template < typename CharT, - typename std::enable_if < - std::is_pointer::value&& - std::is_integral::type>::value&& - sizeof(typename std::remove_pointer::type) == 1, - int >::type = 0 > - span_input_adapter(CharT b, std::size_t l) - : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} - - template::iterator_category, std::random_access_iterator_tag>::value, - int>::type = 0> - span_input_adapter(IteratorType first, IteratorType last) - : ia(input_adapter(first, last)) {} - - contiguous_bytes_input_adapter&& get() - { - return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) - } - - private: - contiguous_bytes_input_adapter ia; -}; -} // namespace detail -} // namespace nlohmann - -// #include - - -#include -#include // string -#include // move -#include // vector - -// #include - -// #include - - -namespace nlohmann -{ - -/*! -@brief SAX interface - -This class describes the SAX interface used by @ref nlohmann::json::sax_parse. -Each function is called in different situations while the input is parsed. The -boolean return value informs the parser whether to continue processing the -input. -*/ -template -struct json_sax -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - - /*! - @brief a null value was read - @return whether parsing should proceed - */ - virtual bool null() = 0; - - /*! - @brief a boolean value was read - @param[in] val boolean value - @return whether parsing should proceed - */ - virtual bool boolean(bool val) = 0; - - /*! - @brief an integer number was read - @param[in] val integer value - @return whether parsing should proceed - */ - virtual bool number_integer(number_integer_t val) = 0; - - /*! - @brief an unsigned integer number was read - @param[in] val unsigned integer value - @return whether parsing should proceed - */ - virtual bool number_unsigned(number_unsigned_t val) = 0; - - /*! - @brief a floating-point number was read - @param[in] val floating-point value - @param[in] s raw token value - @return whether parsing should proceed - */ - virtual bool number_float(number_float_t val, const string_t& s) = 0; - - /*! - @brief a string value was read - @param[in] val string value - @return whether parsing should proceed - @note It is safe to move the passed string value. - */ - virtual bool string(string_t& val) = 0; - - /*! - @brief a binary value was read - @param[in] val binary value - @return whether parsing should proceed - @note It is safe to move the passed binary value. - */ - virtual bool binary(binary_t& val) = 0; - - /*! - @brief the beginning of an object was read - @param[in] elements number of object elements or -1 if unknown - @return whether parsing should proceed - @note binary formats may report the number of elements - */ - virtual bool start_object(std::size_t elements) = 0; - - /*! - @brief an object key was read - @param[in] val object key - @return whether parsing should proceed - @note It is safe to move the passed string. - */ - virtual bool key(string_t& val) = 0; - - /*! - @brief the end of an object was read - @return whether parsing should proceed - */ - virtual bool end_object() = 0; - - /*! - @brief the beginning of an array was read - @param[in] elements number of array elements or -1 if unknown - @return whether parsing should proceed - @note binary formats may report the number of elements - */ - virtual bool start_array(std::size_t elements) = 0; - - /*! - @brief the end of an array was read - @return whether parsing should proceed - */ - virtual bool end_array() = 0; - - /*! - @brief a parse error occurred - @param[in] position the position in the input where the error occurs - @param[in] last_token the last read token - @param[in] ex an exception object describing the error - @return whether parsing should proceed (must return false) - */ - virtual bool parse_error(std::size_t position, - const std::string& last_token, - const detail::exception& ex) = 0; - - json_sax() = default; - json_sax(const json_sax&) = default; - json_sax(json_sax&&) noexcept = default; - json_sax& operator=(const json_sax&) = default; - json_sax& operator=(json_sax&&) noexcept = default; - virtual ~json_sax() = default; -}; - - -namespace detail -{ -/*! -@brief SAX implementation to create a JSON value from SAX events - -This class implements the @ref json_sax interface and processes the SAX events -to create a JSON value which makes it basically a DOM parser. The structure or -hierarchy of the JSON value is managed by the stack `ref_stack` which contains -a pointer to the respective array or object for each recursion depth. - -After successful parsing, the value that is passed by reference to the -constructor contains the parsed value. - -@tparam BasicJsonType the JSON type -*/ -template -class json_sax_dom_parser -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - - /*! - @param[in,out] r reference to a JSON value that is manipulated while - parsing - @param[in] allow_exceptions_ whether parse errors yield exceptions - */ - explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) - : root(r), allow_exceptions(allow_exceptions_) - {} - - // make class move-only - json_sax_dom_parser(const json_sax_dom_parser&) = delete; - json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; - json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~json_sax_dom_parser() = default; - - bool null() - { - handle_value(nullptr); - return true; - } - - bool boolean(bool val) - { - handle_value(val); - return true; - } - - bool number_integer(number_integer_t val) - { - handle_value(val); - return true; - } - - bool number_unsigned(number_unsigned_t val) - { - handle_value(val); - return true; - } - - bool number_float(number_float_t val, const string_t& /*unused*/) - { - handle_value(val); - return true; - } - - bool string(string_t& val) - { - handle_value(val); - return true; - } - - bool binary(binary_t& val) - { - handle_value(std::move(val)); - return true; - } - - bool start_object(std::size_t len) - { - ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); - - if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool key(string_t& val) - { - // add null at given key and store the reference for later - object_element = &(ref_stack.back()->m_value.object->operator[](val)); - return true; - } - - bool end_object() - { - ref_stack.back()->set_parents(); - ref_stack.pop_back(); - return true; - } - - bool start_array(std::size_t len) - { - ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); - - if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool end_array() - { - ref_stack.back()->set_parents(); - ref_stack.pop_back(); - return true; - } - - template - bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, - const Exception& ex) - { - errored = true; - static_cast(ex); - if (allow_exceptions) - { - JSON_THROW(ex); - } - return false; - } - - constexpr bool is_errored() const - { - return errored; - } - - private: - /*! - @invariant If the ref stack is empty, then the passed value will be the new - root. - @invariant If the ref stack contains a value, then it is an array or an - object to which we can add elements - */ - template - JSON_HEDLEY_RETURNS_NON_NULL - BasicJsonType* handle_value(Value&& v) - { - if (ref_stack.empty()) - { - root = BasicJsonType(std::forward(v)); - return &root; - } - - JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); - - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->emplace_back(std::forward(v)); - return &(ref_stack.back()->m_value.array->back()); - } - - JSON_ASSERT(ref_stack.back()->is_object()); - JSON_ASSERT(object_element); - *object_element = BasicJsonType(std::forward(v)); - return object_element; - } - - /// the parsed JSON value - BasicJsonType& root; - /// stack to model hierarchy of values - std::vector ref_stack {}; - /// helper to hold the reference for the next object element - BasicJsonType* object_element = nullptr; - /// whether a syntax error occurred - bool errored = false; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; -}; - -template -class json_sax_dom_callback_parser -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using parser_callback_t = typename BasicJsonType::parser_callback_t; - using parse_event_t = typename BasicJsonType::parse_event_t; - - json_sax_dom_callback_parser(BasicJsonType& r, - const parser_callback_t cb, - const bool allow_exceptions_ = true) - : root(r), callback(cb), allow_exceptions(allow_exceptions_) - { - keep_stack.push_back(true); - } - - // make class move-only - json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; - json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; - json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~json_sax_dom_callback_parser() = default; - - bool null() - { - handle_value(nullptr); - return true; - } - - bool boolean(bool val) - { - handle_value(val); - return true; - } - - bool number_integer(number_integer_t val) - { - handle_value(val); - return true; - } - - bool number_unsigned(number_unsigned_t val) - { - handle_value(val); - return true; - } - - bool number_float(number_float_t val, const string_t& /*unused*/) - { - handle_value(val); - return true; - } - - bool string(string_t& val) - { - handle_value(val); - return true; - } - - bool binary(binary_t& val) - { - handle_value(std::move(val)); - return true; - } - - bool start_object(std::size_t len) - { - // check callback for object start - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); - keep_stack.push_back(keep); - - auto val = handle_value(BasicJsonType::value_t::object, true); - ref_stack.push_back(val.second); - - // check object limit - if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool key(string_t& val) - { - BasicJsonType k = BasicJsonType(val); - - // check callback for key - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); - key_keep_stack.push_back(keep); - - // add discarded value at given key and store the reference for later - if (keep && ref_stack.back()) - { - object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); - } - - return true; - } - - bool end_object() - { - if (ref_stack.back()) - { - if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) - { - // discard object - *ref_stack.back() = discarded; - } - else - { - ref_stack.back()->set_parents(); - } - } - - JSON_ASSERT(!ref_stack.empty()); - JSON_ASSERT(!keep_stack.empty()); - ref_stack.pop_back(); - keep_stack.pop_back(); - - if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) - { - // remove discarded value - for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) - { - if (it->is_discarded()) - { - ref_stack.back()->erase(it); - break; - } - } - } - - return true; - } - - bool start_array(std::size_t len) - { - const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); - keep_stack.push_back(keep); - - auto val = handle_value(BasicJsonType::value_t::array, true); - ref_stack.push_back(val.second); - - // check array limit - if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) - { - JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); - } - - return true; - } - - bool end_array() - { - bool keep = true; - - if (ref_stack.back()) - { - keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); - if (keep) - { - ref_stack.back()->set_parents(); - } - else - { - // discard array - *ref_stack.back() = discarded; - } - } - - JSON_ASSERT(!ref_stack.empty()); - JSON_ASSERT(!keep_stack.empty()); - ref_stack.pop_back(); - keep_stack.pop_back(); - - // remove discarded value - if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->pop_back(); - } - - return true; - } - - template - bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, - const Exception& ex) - { - errored = true; - static_cast(ex); - if (allow_exceptions) - { - JSON_THROW(ex); - } - return false; - } - - constexpr bool is_errored() const - { - return errored; - } - - private: - /*! - @param[in] v value to add to the JSON value we build during parsing - @param[in] skip_callback whether we should skip calling the callback - function; this is required after start_array() and - start_object() SAX events, because otherwise we would call the - callback function with an empty array or object, respectively. - - @invariant If the ref stack is empty, then the passed value will be the new - root. - @invariant If the ref stack contains a value, then it is an array or an - object to which we can add elements - - @return pair of boolean (whether value should be kept) and pointer (to the - passed value in the ref_stack hierarchy; nullptr if not kept) - */ - template - std::pair handle_value(Value&& v, const bool skip_callback = false) - { - JSON_ASSERT(!keep_stack.empty()); - - // do not handle this value if we know it would be added to a discarded - // container - if (!keep_stack.back()) - { - return {false, nullptr}; - } - - // create value - auto value = BasicJsonType(std::forward(v)); - - // check callback - const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); - - // do not handle this value if we just learnt it shall be discarded - if (!keep) - { - return {false, nullptr}; - } - - if (ref_stack.empty()) - { - root = std::move(value); - return {true, &root}; - } - - // skip this value if we already decided to skip the parent - // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) - if (!ref_stack.back()) - { - return {false, nullptr}; - } - - // we now only expect arrays and objects - JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); - - // array - if (ref_stack.back()->is_array()) - { - ref_stack.back()->m_value.array->emplace_back(std::move(value)); - return {true, &(ref_stack.back()->m_value.array->back())}; - } - - // object - JSON_ASSERT(ref_stack.back()->is_object()); - // check if we should store an element for the current key - JSON_ASSERT(!key_keep_stack.empty()); - const bool store_element = key_keep_stack.back(); - key_keep_stack.pop_back(); - - if (!store_element) - { - return {false, nullptr}; - } - - JSON_ASSERT(object_element); - *object_element = std::move(value); - return {true, object_element}; - } - - /// the parsed JSON value - BasicJsonType& root; - /// stack to model hierarchy of values - std::vector ref_stack {}; - /// stack to manage which values to keep - std::vector keep_stack {}; - /// stack to manage which object keys to keep - std::vector key_keep_stack {}; - /// helper to hold the reference for the next object element - BasicJsonType* object_element = nullptr; - /// whether a syntax error occurred - bool errored = false; - /// callback function - const parser_callback_t callback = nullptr; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; - /// a discarded value for the callback - BasicJsonType discarded = BasicJsonType::value_t::discarded; -}; - -template -class json_sax_acceptor -{ - public: - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - - bool null() - { - return true; - } - - bool boolean(bool /*unused*/) - { - return true; - } - - bool number_integer(number_integer_t /*unused*/) - { - return true; - } - - bool number_unsigned(number_unsigned_t /*unused*/) - { - return true; - } - - bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) - { - return true; - } - - bool string(string_t& /*unused*/) - { - return true; - } - - bool binary(binary_t& /*unused*/) - { - return true; - } - - bool start_object(std::size_t /*unused*/ = static_cast(-1)) - { - return true; - } - - bool key(string_t& /*unused*/) - { - return true; - } - - bool end_object() - { - return true; - } - - bool start_array(std::size_t /*unused*/ = static_cast(-1)) - { - return true; - } - - bool end_array() - { - return true; - } - - bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) - { - return false; - } -}; -} // namespace detail - -} // namespace nlohmann - -// #include - - -#include // array -#include // localeconv -#include // size_t -#include // snprintf -#include // strtof, strtod, strtold, strtoll, strtoull -#include // initializer_list -#include // char_traits, string -#include // move -#include // vector - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/////////// -// lexer // -/////////// - -template -class lexer_base -{ - public: - /// token types for the parser - enum class token_type - { - uninitialized, ///< indicating the scanner is uninitialized - literal_true, ///< the `true` literal - literal_false, ///< the `false` literal - literal_null, ///< the `null` literal - value_string, ///< a string -- use get_string() for actual value - value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value - value_integer, ///< a signed integer -- use get_number_integer() for actual value - value_float, ///< an floating point number -- use get_number_float() for actual value - begin_array, ///< the character for array begin `[` - begin_object, ///< the character for object begin `{` - end_array, ///< the character for array end `]` - end_object, ///< the character for object end `}` - name_separator, ///< the name separator `:` - value_separator, ///< the value separator `,` - parse_error, ///< indicating a parse error - end_of_input, ///< indicating the end of the input buffer - literal_or_value ///< a literal or the begin of a value (only for diagnostics) - }; - - /// return name of values of type token_type (only used for errors) - JSON_HEDLEY_RETURNS_NON_NULL - JSON_HEDLEY_CONST - static const char* token_type_name(const token_type t) noexcept - { - switch (t) - { - case token_type::uninitialized: - return ""; - case token_type::literal_true: - return "true literal"; - case token_type::literal_false: - return "false literal"; - case token_type::literal_null: - return "null literal"; - case token_type::value_string: - return "string literal"; - case token_type::value_unsigned: - case token_type::value_integer: - case token_type::value_float: - return "number literal"; - case token_type::begin_array: - return "'['"; - case token_type::begin_object: - return "'{'"; - case token_type::end_array: - return "']'"; - case token_type::end_object: - return "'}'"; - case token_type::name_separator: - return "':'"; - case token_type::value_separator: - return "','"; - case token_type::parse_error: - return ""; - case token_type::end_of_input: - return "end of input"; - case token_type::literal_or_value: - return "'[', '{', or a literal"; - // LCOV_EXCL_START - default: // catch non-enum values - return "unknown token"; - // LCOV_EXCL_STOP - } - } -}; -/*! -@brief lexical analysis - -This class organizes the lexical analysis during JSON deserialization. -*/ -template -class lexer : public lexer_base -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using char_type = typename InputAdapterType::char_type; - using char_int_type = typename std::char_traits::int_type; - - public: - using token_type = typename lexer_base::token_type; - - explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept - : ia(std::move(adapter)) - , ignore_comments(ignore_comments_) - , decimal_point_char(static_cast(get_decimal_point())) - {} - - // delete because of pointer members - lexer(const lexer&) = delete; - lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - lexer& operator=(lexer&) = delete; - lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~lexer() = default; - - private: - ///////////////////// - // locales - ///////////////////// - - /// return the locale-dependent decimal point - JSON_HEDLEY_PURE - static char get_decimal_point() noexcept - { - const auto* loc = localeconv(); - JSON_ASSERT(loc != nullptr); - return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); - } - - ///////////////////// - // scan functions - ///////////////////// - - /*! - @brief get codepoint from 4 hex characters following `\u` - - For input "\u c1 c2 c3 c4" the codepoint is: - (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 - = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) - - Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' - must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The - conversion is done by subtracting the offset (0x30, 0x37, and 0x57) - between the ASCII value of the character and the desired integer value. - - @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or - non-hex character) - */ - int get_codepoint() - { - // this function only makes sense after reading `\u` - JSON_ASSERT(current == 'u'); - int codepoint = 0; - - const auto factors = { 12u, 8u, 4u, 0u }; - for (const auto factor : factors) - { - get(); - - if (current >= '0' && current <= '9') - { - codepoint += static_cast((static_cast(current) - 0x30u) << factor); - } - else if (current >= 'A' && current <= 'F') - { - codepoint += static_cast((static_cast(current) - 0x37u) << factor); - } - else if (current >= 'a' && current <= 'f') - { - codepoint += static_cast((static_cast(current) - 0x57u) << factor); - } - else - { - return -1; - } - } - - JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); - return codepoint; - } - - /*! - @brief check if the next byte(s) are inside a given range - - Adds the current byte and, for each passed range, reads a new byte and - checks if it is inside the range. If a violation was detected, set up an - error message and return false. Otherwise, return true. - - @param[in] ranges list of integers; interpreted as list of pairs of - inclusive lower and upper bound, respectively - - @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, - 1, 2, or 3 pairs. This precondition is enforced by an assertion. - - @return true if and only if no range violation was detected - */ - bool next_byte_in_range(std::initializer_list ranges) - { - JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); - add(current); - - for (auto range = ranges.begin(); range != ranges.end(); ++range) - { - get(); - if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) - { - add(current); - } - else - { - error_message = "invalid string: ill-formed UTF-8 byte"; - return false; - } - } - - return true; - } - - /*! - @brief scan a string literal - - This function scans a string according to Sect. 7 of RFC 8259. While - scanning, bytes are escaped and copied into buffer token_buffer. Then the - function returns successfully, token_buffer is *not* null-terminated (as it - may contain \0 bytes), and token_buffer.size() is the number of bytes in the - string. - - @return token_type::value_string if string could be successfully scanned, - token_type::parse_error otherwise - - @note In case of errors, variable error_message contains a textual - description. - */ - token_type scan_string() - { - // reset token_buffer (ignore opening quote) - reset(); - - // we entered the function by reading an open quote - JSON_ASSERT(current == '\"'); - - while (true) - { - // get next character - switch (get()) - { - // end of file while parsing string - case std::char_traits::eof(): - { - error_message = "invalid string: missing closing quote"; - return token_type::parse_error; - } - - // closing quote - case '\"': - { - return token_type::value_string; - } - - // escapes - case '\\': - { - switch (get()) - { - // quotation mark - case '\"': - add('\"'); - break; - // reverse solidus - case '\\': - add('\\'); - break; - // solidus - case '/': - add('/'); - break; - // backspace - case 'b': - add('\b'); - break; - // form feed - case 'f': - add('\f'); - break; - // line feed - case 'n': - add('\n'); - break; - // carriage return - case 'r': - add('\r'); - break; - // tab - case 't': - add('\t'); - break; - - // unicode escapes - case 'u': - { - const int codepoint1 = get_codepoint(); - int codepoint = codepoint1; // start with codepoint1 - - if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) - { - error_message = "invalid string: '\\u' must be followed by 4 hex digits"; - return token_type::parse_error; - } - - // check if code point is a high surrogate - if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) - { - // expect next \uxxxx entry - if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) - { - const int codepoint2 = get_codepoint(); - - if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) - { - error_message = "invalid string: '\\u' must be followed by 4 hex digits"; - return token_type::parse_error; - } - - // check if codepoint2 is a low surrogate - if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) - { - // overwrite codepoint - codepoint = static_cast( - // high surrogate occupies the most significant 22 bits - (static_cast(codepoint1) << 10u) - // low surrogate occupies the least significant 15 bits - + static_cast(codepoint2) - // there is still the 0xD800, 0xDC00 and 0x10000 noise - // in the result, so we have to subtract with: - // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - - 0x35FDC00u); - } - else - { - error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; - return token_type::parse_error; - } - } - else - { - error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; - return token_type::parse_error; - } - } - else - { - if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) - { - error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; - return token_type::parse_error; - } - } - - // result of the above calculation yields a proper codepoint - JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); - - // translate codepoint into bytes - if (codepoint < 0x80) - { - // 1-byte characters: 0xxxxxxx (ASCII) - add(static_cast(codepoint)); - } - else if (codepoint <= 0x7FF) - { - // 2-byte characters: 110xxxxx 10xxxxxx - add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); - add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); - } - else if (codepoint <= 0xFFFF) - { - // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx - add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); - add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); - add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); - } - else - { - // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); - add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); - add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); - add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); - } - - break; - } - - // other characters after escape - default: - error_message = "invalid string: forbidden character after backslash"; - return token_type::parse_error; - } - - break; - } - - // invalid control characters - case 0x00: - { - error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; - return token_type::parse_error; - } - - case 0x01: - { - error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; - return token_type::parse_error; - } - - case 0x02: - { - error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; - return token_type::parse_error; - } - - case 0x03: - { - error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; - return token_type::parse_error; - } - - case 0x04: - { - error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; - return token_type::parse_error; - } - - case 0x05: - { - error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; - return token_type::parse_error; - } - - case 0x06: - { - error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; - return token_type::parse_error; - } - - case 0x07: - { - error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; - return token_type::parse_error; - } - - case 0x08: - { - error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; - return token_type::parse_error; - } - - case 0x09: - { - error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; - return token_type::parse_error; - } - - case 0x0A: - { - error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; - return token_type::parse_error; - } - - case 0x0B: - { - error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; - return token_type::parse_error; - } - - case 0x0C: - { - error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; - return token_type::parse_error; - } - - case 0x0D: - { - error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; - return token_type::parse_error; - } - - case 0x0E: - { - error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; - return token_type::parse_error; - } - - case 0x0F: - { - error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; - return token_type::parse_error; - } - - case 0x10: - { - error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; - return token_type::parse_error; - } - - case 0x11: - { - error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; - return token_type::parse_error; - } - - case 0x12: - { - error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; - return token_type::parse_error; - } - - case 0x13: - { - error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; - return token_type::parse_error; - } - - case 0x14: - { - error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; - return token_type::parse_error; - } - - case 0x15: - { - error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; - return token_type::parse_error; - } - - case 0x16: - { - error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; - return token_type::parse_error; - } - - case 0x17: - { - error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; - return token_type::parse_error; - } - - case 0x18: - { - error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; - return token_type::parse_error; - } - - case 0x19: - { - error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; - return token_type::parse_error; - } - - case 0x1A: - { - error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; - return token_type::parse_error; - } - - case 0x1B: - { - error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; - return token_type::parse_error; - } - - case 0x1C: - { - error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; - return token_type::parse_error; - } - - case 0x1D: - { - error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; - return token_type::parse_error; - } - - case 0x1E: - { - error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; - return token_type::parse_error; - } - - case 0x1F: - { - error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; - return token_type::parse_error; - } - - // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) - case 0x20: - case 0x21: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: - case 0x59: - case 0x5A: - case 0x5B: - case 0x5D: - case 0x5E: - case 0x5F: - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: - case 0x79: - case 0x7A: - case 0x7B: - case 0x7C: - case 0x7D: - case 0x7E: - case 0x7F: - { - add(current); - break; - } - - // U+0080..U+07FF: bytes C2..DF 80..BF - case 0xC2: - case 0xC3: - case 0xC4: - case 0xC5: - case 0xC6: - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCB: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xD3: - case 0xD4: - case 0xD5: - case 0xD6: - case 0xD7: - case 0xD8: - case 0xD9: - case 0xDA: - case 0xDB: - case 0xDC: - case 0xDD: - case 0xDE: - case 0xDF: - { - if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) - { - return token_type::parse_error; - } - break; - } - - // U+0800..U+0FFF: bytes E0 A0..BF 80..BF - case 0xE0: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF - // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF - case 0xE1: - case 0xE2: - case 0xE3: - case 0xE4: - case 0xE5: - case 0xE6: - case 0xE7: - case 0xE8: - case 0xE9: - case 0xEA: - case 0xEB: - case 0xEC: - case 0xEE: - case 0xEF: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+D000..U+D7FF: bytes ED 80..9F 80..BF - case 0xED: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF - case 0xF0: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF - case 0xF1: - case 0xF2: - case 0xF3: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF - case 0xF4: - { - if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) - { - return token_type::parse_error; - } - break; - } - - // remaining bytes (80..C1 and F5..FF) are ill-formed - default: - { - error_message = "invalid string: ill-formed UTF-8 byte"; - return token_type::parse_error; - } - } - } - } - - /*! - * @brief scan a comment - * @return whether comment could be scanned successfully - */ - bool scan_comment() - { - switch (get()) - { - // single-line comments skip input until a newline or EOF is read - case '/': - { - while (true) - { - switch (get()) - { - case '\n': - case '\r': - case std::char_traits::eof(): - case '\0': - return true; - - default: - break; - } - } - } - - // multi-line comments skip input until */ is read - case '*': - { - while (true) - { - switch (get()) - { - case std::char_traits::eof(): - case '\0': - { - error_message = "invalid comment; missing closing '*/'"; - return false; - } - - case '*': - { - switch (get()) - { - case '/': - return true; - - default: - { - unget(); - continue; - } - } - } - - default: - continue; - } - } - } - - // unexpected character after reading '/' - default: - { - error_message = "invalid comment; expecting '/' or '*' after '/'"; - return false; - } - } - } - - JSON_HEDLEY_NON_NULL(2) - static void strtof(float& f, const char* str, char** endptr) noexcept - { - f = std::strtof(str, endptr); - } - - JSON_HEDLEY_NON_NULL(2) - static void strtof(double& f, const char* str, char** endptr) noexcept - { - f = std::strtod(str, endptr); - } - - JSON_HEDLEY_NON_NULL(2) - static void strtof(long double& f, const char* str, char** endptr) noexcept - { - f = std::strtold(str, endptr); - } - - /*! - @brief scan a number literal - - This function scans a string according to Sect. 6 of RFC 8259. - - The function is realized with a deterministic finite state machine derived - from the grammar described in RFC 8259. Starting in state "init", the - input is read and used to determined the next state. Only state "done" - accepts the number. State "error" is a trap state to model errors. In the - table below, "anything" means any character but the ones listed before. - - state | 0 | 1-9 | e E | + | - | . | anything - ---------|----------|----------|----------|---------|---------|----------|----------- - init | zero | any1 | [error] | [error] | minus | [error] | [error] - minus | zero | any1 | [error] | [error] | [error] | [error] | [error] - zero | done | done | exponent | done | done | decimal1 | done - any1 | any1 | any1 | exponent | done | done | decimal1 | done - decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] - decimal2 | decimal2 | decimal2 | exponent | done | done | done | done - exponent | any2 | any2 | [error] | sign | sign | [error] | [error] - sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] - any2 | any2 | any2 | done | done | done | done | done - - The state machine is realized with one label per state (prefixed with - "scan_number_") and `goto` statements between them. The state machine - contains cycles, but any cycle can be left when EOF is read. Therefore, - the function is guaranteed to terminate. - - During scanning, the read bytes are stored in token_buffer. This string is - then converted to a signed integer, an unsigned integer, or a - floating-point number. - - @return token_type::value_unsigned, token_type::value_integer, or - token_type::value_float if number could be successfully scanned, - token_type::parse_error otherwise - - @note The scanner is independent of the current locale. Internally, the - locale's decimal point is used instead of `.` to work with the - locale-dependent converters. - */ - token_type scan_number() // lgtm [cpp/use-of-goto] - { - // reset token_buffer to store the number's bytes - reset(); - - // the type of the parsed number; initially set to unsigned; will be - // changed if minus sign, decimal point or exponent is read - token_type number_type = token_type::value_unsigned; - - // state (init): we just found out we need to scan a number - switch (current) - { - case '-': - { - add(current); - goto scan_number_minus; - } - - case '0': - { - add(current); - goto scan_number_zero; - } - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - // all other characters are rejected outside scan_number() - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - -scan_number_minus: - // state: we just parsed a leading minus sign - number_type = token_type::value_integer; - switch (get()) - { - case '0': - { - add(current); - goto scan_number_zero; - } - - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - default: - { - error_message = "invalid number; expected digit after '-'"; - return token_type::parse_error; - } - } - -scan_number_zero: - // state: we just parse a zero (maybe with a leading minus sign) - switch (get()) - { - case '.': - { - add(decimal_point_char); - goto scan_number_decimal1; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_any1: - // state: we just parsed a number 0-9 (maybe with a leading minus sign) - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any1; - } - - case '.': - { - add(decimal_point_char); - goto scan_number_decimal1; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_decimal1: - // state: we just parsed a decimal point - number_type = token_type::value_float; - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_decimal2; - } - - default: - { - error_message = "invalid number; expected digit after '.'"; - return token_type::parse_error; - } - } - -scan_number_decimal2: - // we just parsed at least one number after a decimal point - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_decimal2; - } - - case 'e': - case 'E': - { - add(current); - goto scan_number_exponent; - } - - default: - goto scan_number_done; - } - -scan_number_exponent: - // we just parsed an exponent - number_type = token_type::value_float; - switch (get()) - { - case '+': - case '-': - { - add(current); - goto scan_number_sign; - } - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - { - error_message = - "invalid number; expected '+', '-', or digit after exponent"; - return token_type::parse_error; - } - } - -scan_number_sign: - // we just parsed an exponent sign - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - { - error_message = "invalid number; expected digit after exponent sign"; - return token_type::parse_error; - } - } - -scan_number_any2: - // we just parsed a number after the exponent or exponent sign - switch (get()) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - add(current); - goto scan_number_any2; - } - - default: - goto scan_number_done; - } - -scan_number_done: - // unget the character after the number (we only read it to know that - // we are done scanning a number) - unget(); - - char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - errno = 0; - - // try to parse integers first and fall back to floats - if (number_type == token_type::value_unsigned) - { - const auto x = std::strtoull(token_buffer.data(), &endptr, 10); - - // we checked the number format before - JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); - - if (errno == 0) - { - value_unsigned = static_cast(x); - if (value_unsigned == x) - { - return token_type::value_unsigned; - } - } - } - else if (number_type == token_type::value_integer) - { - const auto x = std::strtoll(token_buffer.data(), &endptr, 10); - - // we checked the number format before - JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); - - if (errno == 0) - { - value_integer = static_cast(x); - if (value_integer == x) - { - return token_type::value_integer; - } - } - } - - // this code is reached if we parse a floating-point number or if an - // integer conversion above failed - strtof(value_float, token_buffer.data(), &endptr); - - // we checked the number format before - JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); - - return token_type::value_float; - } - - /*! - @param[in] literal_text the literal text to expect - @param[in] length the length of the passed literal text - @param[in] return_type the token type to return on success - */ - JSON_HEDLEY_NON_NULL(2) - token_type scan_literal(const char_type* literal_text, const std::size_t length, - token_type return_type) - { - JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); - for (std::size_t i = 1; i < length; ++i) - { - if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) - { - error_message = "invalid literal"; - return token_type::parse_error; - } - } - return return_type; - } - - ///////////////////// - // input management - ///////////////////// - - /// reset token_buffer; current character is beginning of token - void reset() noexcept - { - token_buffer.clear(); - token_string.clear(); - token_string.push_back(std::char_traits::to_char_type(current)); - } - - /* - @brief get next character from the input - - This function provides the interface to the used input adapter. It does - not throw in case the input reached EOF, but returns a - `std::char_traits::eof()` in that case. Stores the scanned characters - for use in error messages. - - @return character read from the input - */ - char_int_type get() - { - ++position.chars_read_total; - ++position.chars_read_current_line; - - if (next_unget) - { - // just reset the next_unget variable and work with current - next_unget = false; - } - else - { - current = ia.get_character(); - } - - if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) - { - token_string.push_back(std::char_traits::to_char_type(current)); - } - - if (current == '\n') - { - ++position.lines_read; - position.chars_read_current_line = 0; - } - - return current; - } - - /*! - @brief unget current character (read it again on next get) - - We implement unget by setting variable next_unget to true. The input is not - changed - we just simulate ungetting by modifying chars_read_total, - chars_read_current_line, and token_string. The next call to get() will - behave as if the unget character is read again. - */ - void unget() - { - next_unget = true; - - --position.chars_read_total; - - // in case we "unget" a newline, we have to also decrement the lines_read - if (position.chars_read_current_line == 0) - { - if (position.lines_read > 0) - { - --position.lines_read; - } - } - else - { - --position.chars_read_current_line; - } - - if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) - { - JSON_ASSERT(!token_string.empty()); - token_string.pop_back(); - } - } - - /// add a character to token_buffer - void add(char_int_type c) - { - token_buffer.push_back(static_cast(c)); - } - - public: - ///////////////////// - // value getters - ///////////////////// - - /// return integer value - constexpr number_integer_t get_number_integer() const noexcept - { - return value_integer; - } - - /// return unsigned integer value - constexpr number_unsigned_t get_number_unsigned() const noexcept - { - return value_unsigned; - } - - /// return floating-point value - constexpr number_float_t get_number_float() const noexcept - { - return value_float; - } - - /// return current string value (implicitly resets the token; useful only once) - string_t& get_string() - { - return token_buffer; - } - - ///////////////////// - // diagnostics - ///////////////////// - - /// return position of last read token - constexpr position_t get_position() const noexcept - { - return position; - } - - /// return the last read token (for errors only). Will never contain EOF - /// (an arbitrary value that is not a valid char value, often -1), because - /// 255 may legitimately occur. May contain NUL, which should be escaped. - std::string get_token_string() const - { - // escape control characters - std::string result; - for (const auto c : token_string) - { - if (static_cast(c) <= '\x1F') - { - // escape control characters - std::array cs{{}}; - static_cast((std::snprintf)(cs.data(), cs.size(), "", static_cast(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - result += cs.data(); - } - else - { - // add character as is - result.push_back(static_cast(c)); - } - } - - return result; - } - - /// return syntax error message - JSON_HEDLEY_RETURNS_NON_NULL - constexpr const char* get_error_message() const noexcept - { - return error_message; - } - - ///////////////////// - // actual scanner - ///////////////////// - - /*! - @brief skip the UTF-8 byte order mark - @return true iff there is no BOM or the correct BOM has been skipped - */ - bool skip_bom() - { - if (get() == 0xEF) - { - // check if we completely parse the BOM - return get() == 0xBB && get() == 0xBF; - } - - // the first character is not the beginning of the BOM; unget it to - // process is later - unget(); - return true; - } - - void skip_whitespace() - { - do - { - get(); - } - while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); - } - - token_type scan() - { - // initially, skip the BOM - if (position.chars_read_total == 0 && !skip_bom()) - { - error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; - return token_type::parse_error; - } - - // read next character and ignore whitespace - skip_whitespace(); - - // ignore comments - while (ignore_comments && current == '/') - { - if (!scan_comment()) - { - return token_type::parse_error; - } - - // skip following whitespace - skip_whitespace(); - } - - switch (current) - { - // structural characters - case '[': - return token_type::begin_array; - case ']': - return token_type::end_array; - case '{': - return token_type::begin_object; - case '}': - return token_type::end_object; - case ':': - return token_type::name_separator; - case ',': - return token_type::value_separator; - - // literals - case 't': - { - std::array true_literal = {{static_cast('t'), static_cast('r'), static_cast('u'), static_cast('e')}}; - return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); - } - case 'f': - { - std::array false_literal = {{static_cast('f'), static_cast('a'), static_cast('l'), static_cast('s'), static_cast('e')}}; - return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); - } - case 'n': - { - std::array null_literal = {{static_cast('n'), static_cast('u'), static_cast('l'), static_cast('l')}}; - return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); - } - - // string - case '\"': - return scan_string(); - - // number - case '-': - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - return scan_number(); - - // end of input (the null byte is needed when parsing from - // string literals) - case '\0': - case std::char_traits::eof(): - return token_type::end_of_input; - - // error - default: - error_message = "invalid literal"; - return token_type::parse_error; - } - } - - private: - /// input adapter - InputAdapterType ia; - - /// whether comments should be ignored (true) or signaled as errors (false) - const bool ignore_comments = false; - - /// the current character - char_int_type current = std::char_traits::eof(); - - /// whether the next get() call should just return current - bool next_unget = false; - - /// the start position of the current token - position_t position {}; - - /// raw input token string (for error messages) - std::vector token_string {}; - - /// buffer for variable-length tokens (numbers, strings) - string_t token_buffer {}; - - /// a description of occurred lexer errors - const char* error_message = ""; - - // number values - number_integer_t value_integer = 0; - number_unsigned_t value_unsigned = 0; - number_float_t value_float = 0; - - /// the decimal point - const char_int_type decimal_point_char = '.'; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // size_t -#include // declval -#include // string - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -using null_function_t = decltype(std::declval().null()); - -template -using boolean_function_t = - decltype(std::declval().boolean(std::declval())); - -template -using number_integer_function_t = - decltype(std::declval().number_integer(std::declval())); - -template -using number_unsigned_function_t = - decltype(std::declval().number_unsigned(std::declval())); - -template -using number_float_function_t = decltype(std::declval().number_float( - std::declval(), std::declval())); - -template -using string_function_t = - decltype(std::declval().string(std::declval())); - -template -using binary_function_t = - decltype(std::declval().binary(std::declval())); - -template -using start_object_function_t = - decltype(std::declval().start_object(std::declval())); - -template -using key_function_t = - decltype(std::declval().key(std::declval())); - -template -using end_object_function_t = decltype(std::declval().end_object()); - -template -using start_array_function_t = - decltype(std::declval().start_array(std::declval())); - -template -using end_array_function_t = decltype(std::declval().end_array()); - -template -using parse_error_function_t = decltype(std::declval().parse_error( - std::declval(), std::declval(), - std::declval())); - -template -struct is_sax -{ - private: - static_assert(is_basic_json::value, - "BasicJsonType must be of type basic_json<...>"); - - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using exception_t = typename BasicJsonType::exception; - - public: - static constexpr bool value = - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value && - is_detected_exact::value; -}; - -template -struct is_sax_static_asserts -{ - private: - static_assert(is_basic_json::value, - "BasicJsonType must be of type basic_json<...>"); - - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using exception_t = typename BasicJsonType::exception; - - public: - static_assert(is_detected_exact::value, - "Missing/invalid function: bool null()"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool boolean(bool)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool boolean(bool)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool number_integer(number_integer_t)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool string(string_t&)"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool binary(binary_t&)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool start_object(std::size_t)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool key(string_t&)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool end_object()"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool start_array(std::size_t)"); - static_assert(is_detected_exact::value, - "Missing/invalid function: bool end_array()"); - static_assert( - is_detected_exact::value, - "Missing/invalid function: bool parse_error(std::size_t, const " - "std::string&, const exception&)"); -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -/// how to treat CBOR tags -enum class cbor_tag_handler_t -{ - error, ///< throw a parse_error exception in case of a tag - ignore, ///< ignore tags - store ///< store tags as binary type -}; - -/*! -@brief determine system byte order - -@return true if and only if system's byte order is little endian - -@note from https://stackoverflow.com/a/1001328/266378 -*/ -static inline bool little_endianness(int num = 1) noexcept -{ - return *reinterpret_cast(&num) == 1; -} - - -/////////////////// -// binary reader // -/////////////////// - -/*! -@brief deserialization of CBOR, MessagePack, and UBJSON values -*/ -template> -class binary_reader -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using json_sax_t = SAX; - using char_type = typename InputAdapterType::char_type; - using char_int_type = typename std::char_traits::int_type; - - public: - /*! - @brief create a binary reader - - @param[in] adapter input adapter to read from - */ - explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) - { - (void)detail::is_sax_static_asserts {}; - } - - // make class move-only - binary_reader(const binary_reader&) = delete; - binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - binary_reader& operator=(const binary_reader&) = delete; - binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) - ~binary_reader() = default; - - /*! - @param[in] format the binary format to parse - @param[in] sax_ a SAX event processor - @param[in] strict whether to expect the input to be consumed completed - @param[in] tag_handler how to treat CBOR tags - - @return whether parsing was successful - */ - JSON_HEDLEY_NON_NULL(3) - bool sax_parse(const input_format_t format, - json_sax_t* sax_, - const bool strict = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - sax = sax_; - bool result = false; - - switch (format) - { - case input_format_t::bson: - result = parse_bson_internal(); - break; - - case input_format_t::cbor: - result = parse_cbor_internal(true, tag_handler); - break; - - case input_format_t::msgpack: - result = parse_msgpack_internal(); - break; - - case input_format_t::ubjson: - result = parse_ubjson_internal(); - break; - - case input_format_t::json: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - - // strict mode: next byte must be EOF - if (result && strict) - { - if (format == input_format_t::ubjson) - { - get_ignore_noop(); - } - else - { - get(); - } - - if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) - { - return sax->parse_error(chars_read, get_token_string(), - parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); - } - } - - return result; - } - - private: - ////////// - // BSON // - ////////// - - /*! - @brief Reads in a BSON-object and passes it to the SAX-parser. - @return whether a valid BSON-value was passed to the SAX parser - */ - bool parse_bson_internal() - { - std::int32_t document_size{}; - get_number(input_format_t::bson, document_size); - - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) - { - return false; - } - - return sax->end_object(); - } - - /*! - @brief Parses a C-style string from the BSON input. - @param[in,out] result A reference to the string variable where the read - string is to be stored. - @return `true` if the \x00-byte indicating the end of the string was - encountered before the EOF; false` indicates an unexpected EOF. - */ - bool get_bson_cstr(string_t& result) - { - auto out = std::back_inserter(result); - while (true) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) - { - return false; - } - if (current == 0x00) - { - return true; - } - *out++ = static_cast(current); - } - } - - /*! - @brief Parses a zero-terminated string of length @a len from the BSON - input. - @param[in] len The length (including the zero-byte at the end) of the - string to be read. - @param[in,out] result A reference to the string variable where the read - string is to be stored. - @tparam NumberType The type of the length @a len - @pre len >= 1 - @return `true` if the string was successfully parsed - */ - template - bool get_bson_string(const NumberType len, string_t& result) - { - if (JSON_HEDLEY_UNLIKELY(len < 1)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); - } - - return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); - } - - /*! - @brief Parses a byte array input of length @a len from the BSON input. - @param[in] len The length of the byte array to be read. - @param[in,out] result A reference to the binary variable where the read - array is to be stored. - @tparam NumberType The type of the length @a len - @pre len >= 0 - @return `true` if the byte array was successfully parsed - */ - template - bool get_bson_binary(const NumberType len, binary_t& result) - { - if (JSON_HEDLEY_UNLIKELY(len < 0)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); - } - - // All BSON binary values have a subtype - std::uint8_t subtype{}; - get_number(input_format_t::bson, subtype); - result.set_subtype(subtype); - - return get_binary(input_format_t::bson, len, result); - } - - /*! - @brief Read a BSON document element of the given @a element_type. - @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html - @param[in] element_type_parse_position The position in the input stream, - where the `element_type` was read. - @warning Not all BSON element types are supported yet. An unsupported - @a element_type will give rise to a parse_error.114: - Unsupported BSON record type 0x... - @return whether a valid BSON-object/array was passed to the SAX parser - */ - bool parse_bson_element_internal(const char_int_type element_type, - const std::size_t element_type_parse_position) - { - switch (element_type) - { - case 0x01: // double - { - double number{}; - return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); - } - - case 0x02: // string - { - std::int32_t len{}; - string_t value; - return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); - } - - case 0x03: // object - { - return parse_bson_internal(); - } - - case 0x04: // array - { - return parse_bson_array(); - } - - case 0x05: // binary - { - std::int32_t len{}; - binary_t value; - return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); - } - - case 0x08: // boolean - { - return sax->boolean(get() != 0); - } - - case 0x0A: // null - { - return sax->null(); - } - - case 0x10: // int32 - { - std::int32_t value{}; - return get_number(input_format_t::bson, value) && sax->number_integer(value); - } - - case 0x12: // int64 - { - std::int64_t value{}; - return get_number(input_format_t::bson, value) && sax->number_integer(value); - } - - default: // anything else not supported (yet) - { - std::array cr{{}}; - static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); - } - } - } - - /*! - @brief Read a BSON element list (as specified in the BSON-spec) - - The same binary layout is used for objects and arrays, hence it must be - indicated with the argument @a is_array which one is expected - (true --> array, false --> object). - - @param[in] is_array Determines if the element list being read is to be - treated as an object (@a is_array == false), or as an - array (@a is_array == true). - @return whether a valid BSON-object/array was passed to the SAX parser - */ - bool parse_bson_element_list(const bool is_array) - { - string_t key; - - while (auto element_type = get()) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) - { - return false; - } - - const std::size_t element_type_parse_position = chars_read; - if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) - { - return false; - } - - if (!is_array && !sax->key(key)) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) - { - return false; - } - - // get_bson_cstr only appends - key.clear(); - } - - return true; - } - - /*! - @brief Reads an array from the BSON input and passes it to the SAX-parser. - @return whether a valid BSON-array was passed to the SAX parser - */ - bool parse_bson_array() - { - std::int32_t document_size{}; - get_number(input_format_t::bson, document_size); - - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) - { - return false; - } - - return sax->end_array(); - } - - ////////// - // CBOR // - ////////// - - /*! - @param[in] get_char whether a new character should be retrieved from the - input (true) or whether the last read character should - be considered instead (false) - @param[in] tag_handler how CBOR tags should be treated - - @return whether a valid CBOR value was passed to the SAX parser - */ - bool parse_cbor_internal(const bool get_char, - const cbor_tag_handler_t tag_handler) - { - switch (get_char ? get() : current) - { - // EOF - case std::char_traits::eof(): - return unexpect_eof(input_format_t::cbor, "value"); - - // Integer 0x00..0x17 (0..23) - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - return sax->number_unsigned(static_cast(current)); - - case 0x18: // Unsigned integer (one-byte uint8_t follows) - { - std::uint8_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - case 0x19: // Unsigned integer (two-byte uint16_t follows) - { - std::uint16_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - case 0x1A: // Unsigned integer (four-byte uint32_t follows) - { - std::uint32_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - case 0x1B: // Unsigned integer (eight-byte uint64_t follows) - { - std::uint64_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); - } - - // Negative integer -1-0x00..-1-0x17 (-1..-24) - case 0x20: - case 0x21: - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - return sax->number_integer(static_cast(0x20 - 1 - current)); - - case 0x38: // Negative integer (one-byte uint8_t follows) - { - std::uint8_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); - } - - case 0x39: // Negative integer -1-n (two-byte uint16_t follows) - { - std::uint16_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); - } - - case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) - { - std::uint32_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); - } - - case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) - { - std::uint64_t number{}; - return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - - static_cast(number)); - } - - // Binary data (0x00..0x17 bytes follow) - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: // Binary data (one-byte uint8_t for n follows) - case 0x59: // Binary data (two-byte uint16_t for n follow) - case 0x5A: // Binary data (four-byte uint32_t for n follow) - case 0x5B: // Binary data (eight-byte uint64_t for n follow) - case 0x5F: // Binary data (indefinite length) - { - binary_t b; - return get_cbor_binary(b) && sax->binary(b); - } - - // UTF-8 string (0x00..0x17 bytes follow) - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: // UTF-8 string (one-byte uint8_t for n follows) - case 0x79: // UTF-8 string (two-byte uint16_t for n follow) - case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) - case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) - case 0x7F: // UTF-8 string (indefinite length) - { - string_t s; - return get_cbor_string(s) && sax->string(s); - } - - // array (0x00..0x17 data items follow) - case 0x80: - case 0x81: - case 0x82: - case 0x83: - case 0x84: - case 0x85: - case 0x86: - case 0x87: - case 0x88: - case 0x89: - case 0x8A: - case 0x8B: - case 0x8C: - case 0x8D: - case 0x8E: - case 0x8F: - case 0x90: - case 0x91: - case 0x92: - case 0x93: - case 0x94: - case 0x95: - case 0x96: - case 0x97: - return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); - - case 0x98: // array (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); - } - - case 0x99: // array (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); - } - - case 0x9A: // array (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); - } - - case 0x9B: // array (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast(len), tag_handler); - } - - case 0x9F: // array (indefinite length) - return get_cbor_array(static_cast(-1), tag_handler); - - // map (0x00..0x17 pairs of data items follow) - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); - - case 0xB8: // map (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); - } - - case 0xB9: // map (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); - } - - case 0xBA: // map (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); - } - - case 0xBB: // map (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast(len), tag_handler); - } - - case 0xBF: // map (indefinite length) - return get_cbor_object(static_cast(-1), tag_handler); - - case 0xC6: // tagged item - case 0xC7: - case 0xC8: - case 0xC9: - case 0xCA: - case 0xCB: - case 0xCC: - case 0xCD: - case 0xCE: - case 0xCF: - case 0xD0: - case 0xD1: - case 0xD2: - case 0xD3: - case 0xD4: - case 0xD8: // tagged item (1 bytes follow) - case 0xD9: // tagged item (2 bytes follow) - case 0xDA: // tagged item (4 bytes follow) - case 0xDB: // tagged item (8 bytes follow) - { - switch (tag_handler) - { - case cbor_tag_handler_t::error: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - - case cbor_tag_handler_t::ignore: - { - // ignore binary subtype - switch (current) - { - case 0xD8: - { - std::uint8_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - case 0xD9: - { - std::uint16_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - case 0xDA: - { - std::uint32_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - case 0xDB: - { - std::uint64_t subtype_to_ignore{}; - get_number(input_format_t::cbor, subtype_to_ignore); - break; - } - default: - break; - } - return parse_cbor_internal(true, tag_handler); - } - - case cbor_tag_handler_t::store: - { - binary_t b; - // use binary subtype and store in binary container - switch (current) - { - case 0xD8: - { - std::uint8_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - case 0xD9: - { - std::uint16_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - case 0xDA: - { - std::uint32_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - case 0xDB: - { - std::uint64_t subtype{}; - get_number(input_format_t::cbor, subtype); - b.set_subtype(detail::conditional_static_cast(subtype)); - break; - } - default: - return parse_cbor_internal(true, tag_handler); - } - get(); - return get_cbor_binary(b) && sax->binary(b); - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - return false; // LCOV_EXCL_LINE - } - } - - case 0xF4: // false - return sax->boolean(false); - - case 0xF5: // true - return sax->boolean(true); - - case 0xF6: // null - return sax->null(); - - case 0xF9: // Half-Precision Float (two-byte IEEE 754) - { - const auto byte1_raw = get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) - { - return false; - } - const auto byte2_raw = get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) - { - return false; - } - - const auto byte1 = static_cast(byte1_raw); - const auto byte2 = static_cast(byte2_raw); - - // code from RFC 7049, Appendix D, Figure 3: - // As half-precision floating-point numbers were only added - // to IEEE 754 in 2008, today's programming platforms often - // still only have limited support for them. It is very - // easy to include at least decoding support for them even - // without such support. An example of a small decoder for - // half-precision floating-point numbers in the C language - // is shown in Fig. 3. - const auto half = static_cast((byte1 << 8u) + byte2); - const double val = [&half] - { - const int exp = (half >> 10u) & 0x1Fu; - const unsigned int mant = half & 0x3FFu; - JSON_ASSERT(0 <= exp&& exp <= 32); - JSON_ASSERT(mant <= 1024); - switch (exp) - { - case 0: - return std::ldexp(mant, -24); - case 31: - return (mant == 0) - ? std::numeric_limits::infinity() - : std::numeric_limits::quiet_NaN(); - default: - return std::ldexp(mant + 1024, exp - 25); - } - }(); - return sax->number_float((half & 0x8000u) != 0 - ? static_cast(-val) - : static_cast(val), ""); - } - - case 0xFA: // Single-Precision Float (four-byte IEEE 754) - { - float number{}; - return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); - } - - case 0xFB: // Double-Precision Float (eight-byte IEEE 754) - { - double number{}; - return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); - } - - default: // anything else (0xFF is handled inside the other types) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - } - } - - /*! - @brief reads a CBOR string - - This function first reads starting bytes to determine the expected - string length and then copies this number of bytes into a string. - Additionally, CBOR's strings with indefinite lengths are supported. - - @param[out] result created string - - @return whether string creation completed - */ - bool get_cbor_string(string_t& result) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) - { - return false; - } - - switch (current) - { - // UTF-8 string (0x00..0x17 bytes follow) - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - { - return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); - } - - case 0x78: // UTF-8 string (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x79: // UTF-8 string (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); - } - - case 0x7F: // UTF-8 string (indefinite length) - { - while (get() != 0xFF) - { - string_t chunk; - if (!get_cbor_string(chunk)) - { - return false; - } - result.append(chunk); - } - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); - } - } - } - - /*! - @brief reads a CBOR byte array - - This function first reads starting bytes to determine the expected - byte array length and then copies this number of bytes into the byte array. - Additionally, CBOR's byte arrays with indefinite lengths are supported. - - @param[out] result created byte array - - @return whether byte array creation completed - */ - bool get_cbor_binary(binary_t& result) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) - { - return false; - } - - switch (current) - { - // Binary data (0x00..0x17 bytes follow) - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - { - return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); - } - - case 0x58: // Binary data (one-byte uint8_t for n follows) - { - std::uint8_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x59: // Binary data (two-byte uint16_t for n follow) - { - std::uint16_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x5A: // Binary data (four-byte uint32_t for n follow) - { - std::uint32_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x5B: // Binary data (eight-byte uint64_t for n follow) - { - std::uint64_t len{}; - return get_number(input_format_t::cbor, len) && - get_binary(input_format_t::cbor, len, result); - } - - case 0x5F: // Binary data (indefinite length) - { - while (get() != 0xFF) - { - binary_t chunk; - if (!get_cbor_binary(chunk)) - { - return false; - } - result.insert(result.end(), chunk.begin(), chunk.end()); - } - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); - } - } - } - - /*! - @param[in] len the length of the array or static_cast(-1) for an - array of indefinite size - @param[in] tag_handler how CBOR tags should be treated - @return whether array creation completed - */ - bool get_cbor_array(const std::size_t len, - const cbor_tag_handler_t tag_handler) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) - { - return false; - } - - if (len != static_cast(-1)) - { - for (std::size_t i = 0; i < len; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) - { - return false; - } - } - } - else - { - while (get() != 0xFF) - { - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) - { - return false; - } - } - } - - return sax->end_array(); - } - - /*! - @param[in] len the length of the object or static_cast(-1) for an - object of indefinite size - @param[in] tag_handler how CBOR tags should be treated - @return whether object creation completed - */ - bool get_cbor_object(const std::size_t len, - const cbor_tag_handler_t tag_handler) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) - { - return false; - } - - if (len != 0) - { - string_t key; - if (len != static_cast(-1)) - { - for (std::size_t i = 0; i < len; ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) - { - return false; - } - key.clear(); - } - } - else - { - while (get() != 0xFF) - { - if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) - { - return false; - } - key.clear(); - } - } - } - - return sax->end_object(); - } - - ///////////// - // MsgPack // - ///////////// - - /*! - @return whether a valid MessagePack value was passed to the SAX parser - */ - bool parse_msgpack_internal() - { - switch (get()) - { - // EOF - case std::char_traits::eof(): - return unexpect_eof(input_format_t::msgpack, "value"); - - // positive fixint - case 0x00: - case 0x01: - case 0x02: - case 0x03: - case 0x04: - case 0x05: - case 0x06: - case 0x07: - case 0x08: - case 0x09: - case 0x0A: - case 0x0B: - case 0x0C: - case 0x0D: - case 0x0E: - case 0x0F: - case 0x10: - case 0x11: - case 0x12: - case 0x13: - case 0x14: - case 0x15: - case 0x16: - case 0x17: - case 0x18: - case 0x19: - case 0x1A: - case 0x1B: - case 0x1C: - case 0x1D: - case 0x1E: - case 0x1F: - case 0x20: - case 0x21: - case 0x22: - case 0x23: - case 0x24: - case 0x25: - case 0x26: - case 0x27: - case 0x28: - case 0x29: - case 0x2A: - case 0x2B: - case 0x2C: - case 0x2D: - case 0x2E: - case 0x2F: - case 0x30: - case 0x31: - case 0x32: - case 0x33: - case 0x34: - case 0x35: - case 0x36: - case 0x37: - case 0x38: - case 0x39: - case 0x3A: - case 0x3B: - case 0x3C: - case 0x3D: - case 0x3E: - case 0x3F: - case 0x40: - case 0x41: - case 0x42: - case 0x43: - case 0x44: - case 0x45: - case 0x46: - case 0x47: - case 0x48: - case 0x49: - case 0x4A: - case 0x4B: - case 0x4C: - case 0x4D: - case 0x4E: - case 0x4F: - case 0x50: - case 0x51: - case 0x52: - case 0x53: - case 0x54: - case 0x55: - case 0x56: - case 0x57: - case 0x58: - case 0x59: - case 0x5A: - case 0x5B: - case 0x5C: - case 0x5D: - case 0x5E: - case 0x5F: - case 0x60: - case 0x61: - case 0x62: - case 0x63: - case 0x64: - case 0x65: - case 0x66: - case 0x67: - case 0x68: - case 0x69: - case 0x6A: - case 0x6B: - case 0x6C: - case 0x6D: - case 0x6E: - case 0x6F: - case 0x70: - case 0x71: - case 0x72: - case 0x73: - case 0x74: - case 0x75: - case 0x76: - case 0x77: - case 0x78: - case 0x79: - case 0x7A: - case 0x7B: - case 0x7C: - case 0x7D: - case 0x7E: - case 0x7F: - return sax->number_unsigned(static_cast(current)); - - // fixmap - case 0x80: - case 0x81: - case 0x82: - case 0x83: - case 0x84: - case 0x85: - case 0x86: - case 0x87: - case 0x88: - case 0x89: - case 0x8A: - case 0x8B: - case 0x8C: - case 0x8D: - case 0x8E: - case 0x8F: - return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); - - // fixarray - case 0x90: - case 0x91: - case 0x92: - case 0x93: - case 0x94: - case 0x95: - case 0x96: - case 0x97: - case 0x98: - case 0x99: - case 0x9A: - case 0x9B: - case 0x9C: - case 0x9D: - case 0x9E: - case 0x9F: - return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); - - // fixstr - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBC: - case 0xBD: - case 0xBE: - case 0xBF: - case 0xD9: // str 8 - case 0xDA: // str 16 - case 0xDB: // str 32 - { - string_t s; - return get_msgpack_string(s) && sax->string(s); - } - - case 0xC0: // nil - return sax->null(); - - case 0xC2: // false - return sax->boolean(false); - - case 0xC3: // true - return sax->boolean(true); - - case 0xC4: // bin 8 - case 0xC5: // bin 16 - case 0xC6: // bin 32 - case 0xC7: // ext 8 - case 0xC8: // ext 16 - case 0xC9: // ext 32 - case 0xD4: // fixext 1 - case 0xD5: // fixext 2 - case 0xD6: // fixext 4 - case 0xD7: // fixext 8 - case 0xD8: // fixext 16 - { - binary_t b; - return get_msgpack_binary(b) && sax->binary(b); - } - - case 0xCA: // float 32 - { - float number{}; - return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); - } - - case 0xCB: // float 64 - { - double number{}; - return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); - } - - case 0xCC: // uint 8 - { - std::uint8_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xCD: // uint 16 - { - std::uint16_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xCE: // uint 32 - { - std::uint32_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xCF: // uint 64 - { - std::uint64_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); - } - - case 0xD0: // int 8 - { - std::int8_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xD1: // int 16 - { - std::int16_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xD2: // int 32 - { - std::int32_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xD3: // int 64 - { - std::int64_t number{}; - return get_number(input_format_t::msgpack, number) && sax->number_integer(number); - } - - case 0xDC: // array 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); - } - - case 0xDD: // array 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); - } - - case 0xDE: // map 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); - } - - case 0xDF: // map 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); - } - - // negative fixint - case 0xE0: - case 0xE1: - case 0xE2: - case 0xE3: - case 0xE4: - case 0xE5: - case 0xE6: - case 0xE7: - case 0xE8: - case 0xE9: - case 0xEA: - case 0xEB: - case 0xEC: - case 0xED: - case 0xEE: - case 0xEF: - case 0xF0: - case 0xF1: - case 0xF2: - case 0xF3: - case 0xF4: - case 0xF5: - case 0xF6: - case 0xF7: - case 0xF8: - case 0xF9: - case 0xFA: - case 0xFB: - case 0xFC: - case 0xFD: - case 0xFE: - case 0xFF: - return sax->number_integer(static_cast(current)); - - default: // anything else - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - } - } - - /*! - @brief reads a MessagePack string - - This function first reads starting bytes to determine the expected - string length and then copies this number of bytes into a string. - - @param[out] result created string - - @return whether string creation completed - */ - bool get_msgpack_string(string_t& result) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) - { - return false; - } - - switch (current) - { - // fixstr - case 0xA0: - case 0xA1: - case 0xA2: - case 0xA3: - case 0xA4: - case 0xA5: - case 0xA6: - case 0xA7: - case 0xA8: - case 0xA9: - case 0xAA: - case 0xAB: - case 0xAC: - case 0xAD: - case 0xAE: - case 0xAF: - case 0xB0: - case 0xB1: - case 0xB2: - case 0xB3: - case 0xB4: - case 0xB5: - case 0xB6: - case 0xB7: - case 0xB8: - case 0xB9: - case 0xBA: - case 0xBB: - case 0xBC: - case 0xBD: - case 0xBE: - case 0xBF: - { - return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); - } - - case 0xD9: // str 8 - { - std::uint8_t len{}; - return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); - } - - case 0xDA: // str 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); - } - - case 0xDB: // str 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); - } - } - } - - /*! - @brief reads a MessagePack byte array - - This function first reads starting bytes to determine the expected - byte array length and then copies this number of bytes into a byte array. - - @param[out] result created byte array - - @return whether byte array creation completed - */ - bool get_msgpack_binary(binary_t& result) - { - // helper function to set the subtype - auto assign_and_return_true = [&result](std::int8_t subtype) - { - result.set_subtype(static_cast(subtype)); - return true; - }; - - switch (current) - { - case 0xC4: // bin 8 - { - std::uint8_t len{}; - return get_number(input_format_t::msgpack, len) && - get_binary(input_format_t::msgpack, len, result); - } - - case 0xC5: // bin 16 - { - std::uint16_t len{}; - return get_number(input_format_t::msgpack, len) && - get_binary(input_format_t::msgpack, len, result); - } - - case 0xC6: // bin 32 - { - std::uint32_t len{}; - return get_number(input_format_t::msgpack, len) && - get_binary(input_format_t::msgpack, len, result); - } - - case 0xC7: // ext 8 - { - std::uint8_t len{}; - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, len) && - get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, len, result) && - assign_and_return_true(subtype); - } - - case 0xC8: // ext 16 - { - std::uint16_t len{}; - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, len) && - get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, len, result) && - assign_and_return_true(subtype); - } - - case 0xC9: // ext 32 - { - std::uint32_t len{}; - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, len) && - get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, len, result) && - assign_and_return_true(subtype); - } - - case 0xD4: // fixext 1 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 1, result) && - assign_and_return_true(subtype); - } - - case 0xD5: // fixext 2 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 2, result) && - assign_and_return_true(subtype); - } - - case 0xD6: // fixext 4 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 4, result) && - assign_and_return_true(subtype); - } - - case 0xD7: // fixext 8 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 8, result) && - assign_and_return_true(subtype); - } - - case 0xD8: // fixext 16 - { - std::int8_t subtype{}; - return get_number(input_format_t::msgpack, subtype) && - get_binary(input_format_t::msgpack, 16, result) && - assign_and_return_true(subtype); - } - - default: // LCOV_EXCL_LINE - return false; // LCOV_EXCL_LINE - } - } - - /*! - @param[in] len the length of the array - @return whether array creation completed - */ - bool get_msgpack_array(const std::size_t len) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) - { - return false; - } - - for (std::size_t i = 0; i < len; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) - { - return false; - } - } - - return sax->end_array(); - } - - /*! - @param[in] len the length of the object - @return whether object creation completed - */ - bool get_msgpack_object(const std::size_t len) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) - { - return false; - } - - string_t key; - for (std::size_t i = 0; i < len; ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) - { - return false; - } - - if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) - { - return false; - } - key.clear(); - } - - return sax->end_object(); - } - - //////////// - // UBJSON // - //////////// - - /*! - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether a valid UBJSON value was passed to the SAX parser - */ - bool parse_ubjson_internal(const bool get_char = true) - { - return get_ubjson_value(get_char ? get_ignore_noop() : current); - } - - /*! - @brief reads a UBJSON string - - This function is either called after reading the 'S' byte explicitly - indicating a string, or in case of an object key where the 'S' byte can be - left out. - - @param[out] result created string - @param[in] get_char whether a new character should be retrieved from the - input (true, default) or whether the last read - character should be considered instead - - @return whether string creation completed - */ - bool get_ubjson_string(string_t& result, const bool get_char = true) - { - if (get_char) - { - get(); // TODO(niels): may we ignore N here? - } - - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) - { - return false; - } - - switch (current) - { - case 'U': - { - std::uint8_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'i': - { - std::int8_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'I': - { - std::int16_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'l': - { - std::int32_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - case 'L': - { - std::int64_t len{}; - return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); - } - - default: - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); - } - } - - /*! - @param[out] result determined size - @return whether size determination completed - */ - bool get_ubjson_size_value(std::size_t& result) - { - switch (get_ignore_noop()) - { - case 'U': - { - std::uint8_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'i': - { - std::int8_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char - return true; - } - - case 'I': - { - std::int16_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'l': - { - std::int32_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - case 'L': - { - std::int64_t number{}; - if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) - { - return false; - } - result = static_cast(number); - return true; - } - - default: - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); - } - } - } - - /*! - @brief determine the type and size for a container - - In the optimized UBJSON format, a type and a size can be provided to allow - for a more compact representation. - - @param[out] result pair of the size and the type - - @return whether pair creation completed - */ - bool get_ubjson_size_type(std::pair& result) - { - result.first = string_t::npos; // size - result.second = 0; // type - - get_ignore_noop(); - - if (current == '$') - { - result.second = get(); // must not ignore 'N', because 'N' maybe the type - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) - { - return false; - } - - get_ignore_noop(); - if (JSON_HEDLEY_UNLIKELY(current != '#')) - { - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) - { - return false; - } - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); - } - - return get_ubjson_size_value(result.first); - } - - if (current == '#') - { - return get_ubjson_size_value(result.first); - } - - return true; - } - - /*! - @param prefix the previously read or set type prefix - @return whether value creation completed - */ - bool get_ubjson_value(const char_int_type prefix) - { - switch (prefix) - { - case std::char_traits::eof(): // EOF - return unexpect_eof(input_format_t::ubjson, "value"); - - case 'T': // true - return sax->boolean(true); - case 'F': // false - return sax->boolean(false); - - case 'Z': // null - return sax->null(); - - case 'U': - { - std::uint8_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); - } - - case 'i': - { - std::int8_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'I': - { - std::int16_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'l': - { - std::int32_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'L': - { - std::int64_t number{}; - return get_number(input_format_t::ubjson, number) && sax->number_integer(number); - } - - case 'd': - { - float number{}; - return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); - } - - case 'D': - { - double number{}; - return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); - } - - case 'H': - { - return get_ubjson_high_precision_number(); - } - - case 'C': // char - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(current > 127)) - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); - } - string_t s(1, static_cast(current)); - return sax->string(s); - } - - case 'S': // string - { - string_t s; - return get_ubjson_string(s) && sax->string(s); - } - - case '[': // array - return get_ubjson_array(); - - case '{': // object - return get_ubjson_object(); - - default: // anything else - { - auto last_token = get_token_string(); - return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); - } - } - } - - /*! - @return whether array creation completed - */ - bool get_ubjson_array() - { - std::pair size_and_type; - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) - { - return false; - } - - if (size_and_type.first != string_t::npos) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) - { - return false; - } - - if (size_and_type.second != 0) - { - if (size_and_type.second != 'N') - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) - { - return false; - } - } - } - } - else - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) - { - return false; - } - } - } - } - else - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) - { - return false; - } - - while (current != ']') - { - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) - { - return false; - } - get_ignore_noop(); - } - } - - return sax->end_array(); - } - - /*! - @return whether object creation completed - */ - bool get_ubjson_object() - { - std::pair size_and_type; - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) - { - return false; - } - - string_t key; - if (size_and_type.first != string_t::npos) - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) - { - return false; - } - - if (size_and_type.second != 0) - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) - { - return false; - } - key.clear(); - } - } - else - { - for (std::size_t i = 0; i < size_and_type.first; ++i) - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) - { - return false; - } - key.clear(); - } - } - } - else - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) - { - return false; - } - - while (current != '}') - { - if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) - { - return false; - } - if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) - { - return false; - } - get_ignore_noop(); - key.clear(); - } - } - - return sax->end_object(); - } - - // Note, no reader for UBJSON binary types is implemented because they do - // not exist - - bool get_ubjson_high_precision_number() - { - // get size of following number string - std::size_t size{}; - auto res = get_ubjson_size_value(size); - if (JSON_HEDLEY_UNLIKELY(!res)) - { - return res; - } - - // get number string - std::vector number_vector; - for (std::size_t i = 0; i < size; ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) - { - return false; - } - number_vector.push_back(static_cast(current)); - } - - // parse number string - using ia_type = decltype(detail::input_adapter(number_vector)); - auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); - const auto result_number = number_lexer.scan(); - const auto number_string = number_lexer.get_token_string(); - const auto result_remainder = number_lexer.scan(); - - using token_type = typename detail::lexer_base::token_type; - - if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) - { - return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); - } - - switch (result_number) - { - case token_type::value_integer: - return sax->number_integer(number_lexer.get_number_integer()); - case token_type::value_unsigned: - return sax->number_unsigned(number_lexer.get_number_unsigned()); - case token_type::value_float: - return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); - case token_type::uninitialized: - case token_type::literal_true: - case token_type::literal_false: - case token_type::literal_null: - case token_type::value_string: - case token_type::begin_array: - case token_type::begin_object: - case token_type::end_array: - case token_type::end_object: - case token_type::name_separator: - case token_type::value_separator: - case token_type::parse_error: - case token_type::end_of_input: - case token_type::literal_or_value: - default: - return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); - } - } - - /////////////////////// - // Utility functions // - /////////////////////// - - /*! - @brief get next character from the input - - This function provides the interface to the used input adapter. It does - not throw in case the input reached EOF, but returns a -'ve valued - `std::char_traits::eof()` in that case. - - @return character read from the input - */ - char_int_type get() - { - ++chars_read; - return current = ia.get_character(); - } - - /*! - @return character read from the input after ignoring all 'N' entries - */ - char_int_type get_ignore_noop() - { - do - { - get(); - } - while (current == 'N'); - - return current; - } - - /* - @brief read a number from the input - - @tparam NumberType the type of the number - @param[in] format the current format (for diagnostics) - @param[out] result number of type @a NumberType - - @return whether conversion completed - - @note This function needs to respect the system's endianness, because - bytes in CBOR, MessagePack, and UBJSON are stored in network order - (big endian) and therefore need reordering on little endian systems. - */ - template - bool get_number(const input_format_t format, NumberType& result) - { - // step 1: read input into array with system's byte order - std::array vec{}; - for (std::size_t i = 0; i < sizeof(NumberType); ++i) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) - { - return false; - } - - // reverse byte order prior to conversion if necessary - if (is_little_endian != InputIsLittleEndian) - { - vec[sizeof(NumberType) - i - 1] = static_cast(current); - } - else - { - vec[i] = static_cast(current); // LCOV_EXCL_LINE - } - } - - // step 2: convert array into number of type T and return - std::memcpy(&result, vec.data(), sizeof(NumberType)); - return true; - } - - /*! - @brief create a string by reading characters from the input - - @tparam NumberType the type of the number - @param[in] format the current format (for diagnostics) - @param[in] len number of characters to read - @param[out] result string created by reading @a len bytes - - @return whether string creation completed - - @note We can not reserve @a len bytes for the result, because @a len - may be too large. Usually, @ref unexpect_eof() detects the end of - the input before we run out of string memory. - */ - template - bool get_string(const input_format_t format, - const NumberType len, - string_t& result) - { - bool success = true; - for (NumberType i = 0; i < len; i++) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) - { - success = false; - break; - } - result.push_back(static_cast(current)); - } - return success; - } - - /*! - @brief create a byte array by reading bytes from the input - - @tparam NumberType the type of the number - @param[in] format the current format (for diagnostics) - @param[in] len number of bytes to read - @param[out] result byte array created by reading @a len bytes - - @return whether byte array creation completed - - @note We can not reserve @a len bytes for the result, because @a len - may be too large. Usually, @ref unexpect_eof() detects the end of - the input before we run out of memory. - */ - template - bool get_binary(const input_format_t format, - const NumberType len, - binary_t& result) - { - bool success = true; - for (NumberType i = 0; i < len; i++) - { - get(); - if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) - { - success = false; - break; - } - result.push_back(static_cast(current)); - } - return success; - } - - /*! - @param[in] format the current format (for diagnostics) - @param[in] context further context information (for diagnostics) - @return whether the last read character is not EOF - */ - JSON_HEDLEY_NON_NULL(3) - bool unexpect_eof(const input_format_t format, const char* context) const - { - if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) - { - return sax->parse_error(chars_read, "", - parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); - } - return true; - } - - /*! - @return a string representation of the last read byte - */ - std::string get_token_string() const - { - std::array cr{{}}; - static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - return std::string{cr.data()}; - } - - /*! - @param[in] format the current format - @param[in] detail a detailed error message - @param[in] context further context information - @return a message string to use in the parse_error exceptions - */ - std::string exception_message(const input_format_t format, - const std::string& detail, - const std::string& context) const - { - std::string error_msg = "syntax error while parsing "; - - switch (format) - { - case input_format_t::cbor: - error_msg += "CBOR"; - break; - - case input_format_t::msgpack: - error_msg += "MessagePack"; - break; - - case input_format_t::ubjson: - error_msg += "UBJSON"; - break; - - case input_format_t::bson: - error_msg += "BSON"; - break; - - case input_format_t::json: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - - return error_msg + " " + context + ": " + detail; - } - - private: - /// input adapter - InputAdapterType ia; - - /// the current character - char_int_type current = std::char_traits::eof(); - - /// the number of characters read - std::size_t chars_read = 0; - - /// whether we can assume little endianness - const bool is_little_endian = little_endianness(); - - /// the SAX parser - json_sax_t* sax = nullptr; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - - -#include // isfinite -#include // uint8_t -#include // function -#include // string -#include // move -#include // vector - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -//////////// -// parser // -//////////// - -enum class parse_event_t : std::uint8_t -{ - /// the parser read `{` and started to process a JSON object - object_start, - /// the parser read `}` and finished processing a JSON object - object_end, - /// the parser read `[` and started to process a JSON array - array_start, - /// the parser read `]` and finished processing a JSON array - array_end, - /// the parser read a key of a value in an object - key, - /// the parser finished reading a JSON value - value -}; - -template -using parser_callback_t = - std::function; - -/*! -@brief syntax analysis - -This class implements a recursive descent parser. -*/ -template -class parser -{ - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using number_float_t = typename BasicJsonType::number_float_t; - using string_t = typename BasicJsonType::string_t; - using lexer_t = lexer; - using token_type = typename lexer_t::token_type; - - public: - /// a parser reading from an input adapter - explicit parser(InputAdapterType&& adapter, - const parser_callback_t cb = nullptr, - const bool allow_exceptions_ = true, - const bool skip_comments = false) - : callback(cb) - , m_lexer(std::move(adapter), skip_comments) - , allow_exceptions(allow_exceptions_) - { - // read first token - get_token(); - } - - /*! - @brief public parser interface - - @param[in] strict whether to expect the last token to be EOF - @param[in,out] result parsed JSON value - - @throw parse_error.101 in case of an unexpected token - @throw parse_error.102 if to_unicode fails or surrogate error - @throw parse_error.103 if to_unicode fails - */ - void parse(const bool strict, BasicJsonType& result) - { - if (callback) - { - json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); - sax_parse_internal(&sdp); - - // in strict mode, input must be completely read - if (strict && (get_token() != token_type::end_of_input)) - { - sdp.parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), - exception_message(token_type::end_of_input, "value"), BasicJsonType())); - } - - // in case of an error, return discarded value - if (sdp.is_errored()) - { - result = value_t::discarded; - return; - } - - // set top-level value to null if it was discarded by the callback - // function - if (result.is_discarded()) - { - result = nullptr; - } - } - else - { - json_sax_dom_parser sdp(result, allow_exceptions); - sax_parse_internal(&sdp); - - // in strict mode, input must be completely read - if (strict && (get_token() != token_type::end_of_input)) - { - sdp.parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); - } - - // in case of an error, return discarded value - if (sdp.is_errored()) - { - result = value_t::discarded; - return; - } - } - - result.assert_invariant(); - } - - /*! - @brief public accept interface - - @param[in] strict whether to expect the last token to be EOF - @return whether the input is a proper JSON text - */ - bool accept(const bool strict = true) - { - json_sax_acceptor sax_acceptor; - return sax_parse(&sax_acceptor, strict); - } - - template - JSON_HEDLEY_NON_NULL(2) - bool sax_parse(SAX* sax, const bool strict = true) - { - (void)detail::is_sax_static_asserts {}; - const bool result = sax_parse_internal(sax); - - // strict mode: next byte must be EOF - if (result && strict && (get_token() != token_type::end_of_input)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); - } - - return result; - } - - private: - template - JSON_HEDLEY_NON_NULL(2) - bool sax_parse_internal(SAX* sax) - { - // stack to remember the hierarchy of structured values we are parsing - // true = array; false = object - std::vector states; - // value to avoid a goto (see comment where set to true) - bool skip_to_state_evaluation = false; - - while (true) - { - if (!skip_to_state_evaluation) - { - // invariant: get_token() was called before each iteration - switch (last_token) - { - case token_type::begin_object: - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) - { - return false; - } - - // closing } -> we are done - if (get_token() == token_type::end_object) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) - { - return false; - } - break; - } - - // parse key - if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); - } - if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) - { - return false; - } - - // parse separator (:) - if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); - } - - // remember we are now inside an object - states.push_back(false); - - // parse values - get_token(); - continue; - } - - case token_type::begin_array: - { - if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) - { - return false; - } - - // closing ] -> we are done - if (get_token() == token_type::end_array) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) - { - return false; - } - break; - } - - // remember we are now inside an array - states.push_back(true); - - // parse values (no need to call get_token) - continue; - } - - case token_type::value_float: - { - const auto res = m_lexer.get_number_float(); - - if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); - } - - if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) - { - return false; - } - - break; - } - - case token_type::literal_false: - { - if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) - { - return false; - } - break; - } - - case token_type::literal_null: - { - if (JSON_HEDLEY_UNLIKELY(!sax->null())) - { - return false; - } - break; - } - - case token_type::literal_true: - { - if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) - { - return false; - } - break; - } - - case token_type::value_integer: - { - if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) - { - return false; - } - break; - } - - case token_type::value_string: - { - if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) - { - return false; - } - break; - } - - case token_type::value_unsigned: - { - if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) - { - return false; - } - break; - } - - case token_type::parse_error: - { - // using "uninitialized" to avoid "expected" message - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); - } - - case token_type::uninitialized: - case token_type::end_array: - case token_type::end_object: - case token_type::name_separator: - case token_type::value_separator: - case token_type::end_of_input: - case token_type::literal_or_value: - default: // the last token was unexpected - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); - } - } - } - else - { - skip_to_state_evaluation = false; - } - - // we reached this line after we successfully parsed a value - if (states.empty()) - { - // empty stack: we reached the end of the hierarchy: done - return true; - } - - if (states.back()) // array - { - // comma -> next value - if (get_token() == token_type::value_separator) - { - // parse a new value - get_token(); - continue; - } - - // closing ] - if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) - { - return false; - } - - // We are done with this array. Before we can parse a - // new value, we need to evaluate the new state first. - // By setting skip_to_state_evaluation to false, we - // are effectively jumping to the beginning of this if. - JSON_ASSERT(!states.empty()); - states.pop_back(); - skip_to_state_evaluation = true; - continue; - } - - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); - } - - // states.back() is false -> object - - // comma -> next value - if (get_token() == token_type::value_separator) - { - // parse key - if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); - } - - if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) - { - return false; - } - - // parse separator (:) - if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) - { - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); - } - - // parse values - get_token(); - continue; - } - - // closing } - if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) - { - if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) - { - return false; - } - - // We are done with this object. Before we can parse a - // new value, we need to evaluate the new state first. - // By setting skip_to_state_evaluation to false, we - // are effectively jumping to the beginning of this if. - JSON_ASSERT(!states.empty()); - states.pop_back(); - skip_to_state_evaluation = true; - continue; - } - - return sax->parse_error(m_lexer.get_position(), - m_lexer.get_token_string(), - parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); - } - } - - /// get next token from lexer - token_type get_token() - { - return last_token = m_lexer.scan(); - } - - std::string exception_message(const token_type expected, const std::string& context) - { - std::string error_msg = "syntax error "; - - if (!context.empty()) - { - error_msg += "while parsing " + context + " "; - } - - error_msg += "- "; - - if (last_token == token_type::parse_error) - { - error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + - m_lexer.get_token_string() + "'"; - } - else - { - error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); - } - - if (expected != token_type::uninitialized) - { - error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); - } - - return error_msg; - } - - private: - /// callback function - const parser_callback_t callback = nullptr; - /// the type of the last read token - token_type last_token = token_type::uninitialized; - /// the lexer - lexer_t m_lexer; - /// whether to throw exceptions in case of errors - const bool allow_exceptions = true; -}; - -} // namespace detail -} // namespace nlohmann - -// #include - - -// #include - - -#include // ptrdiff_t -#include // numeric_limits - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/* -@brief an iterator for primitive JSON types - -This class models an iterator for primitive JSON types (boolean, number, -string). It's only purpose is to allow the iterator/const_iterator classes -to "iterate" over primitive values. Internally, the iterator is modeled by -a `difference_type` variable. Value begin_value (`0`) models the begin, -end_value (`1`) models past the end. -*/ -class primitive_iterator_t -{ - private: - using difference_type = std::ptrdiff_t; - static constexpr difference_type begin_value = 0; - static constexpr difference_type end_value = begin_value + 1; - - JSON_PRIVATE_UNLESS_TESTED: - /// iterator as signed integer type - difference_type m_it = (std::numeric_limits::min)(); - - public: - constexpr difference_type get_value() const noexcept - { - return m_it; - } - - /// set iterator to a defined beginning - void set_begin() noexcept - { - m_it = begin_value; - } - - /// set iterator to a defined past the end - void set_end() noexcept - { - m_it = end_value; - } - - /// return whether the iterator can be dereferenced - constexpr bool is_begin() const noexcept - { - return m_it == begin_value; - } - - /// return whether the iterator is at end - constexpr bool is_end() const noexcept - { - return m_it == end_value; - } - - friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it == rhs.m_it; - } - - friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it < rhs.m_it; - } - - primitive_iterator_t operator+(difference_type n) noexcept - { - auto result = *this; - result += n; - return result; - } - - friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept - { - return lhs.m_it - rhs.m_it; - } - - primitive_iterator_t& operator++() noexcept - { - ++m_it; - return *this; - } - - primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) - { - auto result = *this; - ++m_it; - return result; - } - - primitive_iterator_t& operator--() noexcept - { - --m_it; - return *this; - } - - primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) - { - auto result = *this; - --m_it; - return result; - } - - primitive_iterator_t& operator+=(difference_type n) noexcept - { - m_it += n; - return *this; - } - - primitive_iterator_t& operator-=(difference_type n) noexcept - { - m_it -= n; - return *this; - } -}; -} // namespace detail -} // namespace nlohmann - - -namespace nlohmann -{ -namespace detail -{ -/*! -@brief an iterator value - -@note This structure could easily be a union, but MSVC currently does not allow -unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. -*/ -template struct internal_iterator -{ - /// iterator for JSON objects - typename BasicJsonType::object_t::iterator object_iterator {}; - /// iterator for JSON arrays - typename BasicJsonType::array_t::iterator array_iterator {}; - /// generic iterator for all other types - primitive_iterator_t primitive_iterator {}; -}; -} // namespace detail -} // namespace nlohmann - -// #include - - -#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next -#include // conditional, is_const, remove_const - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -// forward declare, to be able to friend it later on -template class iteration_proxy; -template class iteration_proxy_value; - -/*! -@brief a template for a bidirectional iterator for the @ref basic_json class -This class implements a both iterators (iterator and const_iterator) for the -@ref basic_json class. -@note An iterator is called *initialized* when a pointer to a JSON value has - been set (e.g., by a constructor or a copy assignment). If the iterator is - default-constructed, it is *uninitialized* and most methods are undefined. - **The library uses assertions to detect calls on uninitialized iterators.** -@requirement The class satisfies the following concept requirements: -- -[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): - The iterator that can be moved can be moved in both directions (i.e. - incremented and decremented). -@since version 1.0.0, simplified in version 2.0.9, change to bidirectional - iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) -*/ -template -class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) -{ - /// the iterator with BasicJsonType of different const-ness - using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; - /// allow basic_json to access private members - friend other_iter_impl; - friend BasicJsonType; - friend iteration_proxy; - friend iteration_proxy_value; - - using object_t = typename BasicJsonType::object_t; - using array_t = typename BasicJsonType::array_t; - // make sure BasicJsonType is basic_json or const basic_json - static_assert(is_basic_json::type>::value, - "iter_impl only accepts (const) basic_json"); - - public: - - /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. - /// The C++ Standard has never required user-defined iterators to derive from std::iterator. - /// A user-defined iterator should provide publicly accessible typedefs named - /// iterator_category, value_type, difference_type, pointer, and reference. - /// Note that value_type is required to be non-const, even for constant iterators. - using iterator_category = std::bidirectional_iterator_tag; - - /// the type of the values when the iterator is dereferenced - using value_type = typename BasicJsonType::value_type; - /// a type to represent differences between iterators - using difference_type = typename BasicJsonType::difference_type; - /// defines a pointer to the type iterated over (value_type) - using pointer = typename std::conditional::value, - typename BasicJsonType::const_pointer, - typename BasicJsonType::pointer>::type; - /// defines a reference to the type iterated over (value_type) - using reference = - typename std::conditional::value, - typename BasicJsonType::const_reference, - typename BasicJsonType::reference>::type; - - iter_impl() = default; - ~iter_impl() = default; - iter_impl(iter_impl&&) noexcept = default; - iter_impl& operator=(iter_impl&&) noexcept = default; - - /*! - @brief constructor for a given JSON instance - @param[in] object pointer to a JSON object for this iterator - @pre object != nullptr - @post The iterator is initialized; i.e. `m_object != nullptr`. - */ - explicit iter_impl(pointer object) noexcept : m_object(object) - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = typename object_t::iterator(); - break; - } - - case value_t::array: - { - m_it.array_iterator = typename array_t::iterator(); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator = primitive_iterator_t(); - break; - } - } - } - - /*! - @note The conventional copy constructor and copy assignment are implicitly - defined. Combined with the following converting constructor and - assignment, they support: (1) copy from iterator to iterator, (2) - copy from const iterator to const iterator, and (3) conversion from - iterator to const iterator. However conversion from const iterator - to iterator is not defined. - */ - - /*! - @brief const copy constructor - @param[in] other const iterator to copy from - @note This copy constructor had to be defined explicitly to circumvent a bug - occurring on msvc v19.0 compiler (VS 2015) debug build. For more - information refer to: https://github.com/nlohmann/json/issues/1608 - */ - iter_impl(const iter_impl& other) noexcept - : m_object(other.m_object), m_it(other.m_it) - {} - - /*! - @brief converting assignment - @param[in] other const iterator to copy from - @return const/non-const iterator - @note It is not checked whether @a other is initialized. - */ - iter_impl& operator=(const iter_impl& other) noexcept - { - if (&other != this) - { - m_object = other.m_object; - m_it = other.m_it; - } - return *this; - } - - /*! - @brief converting constructor - @param[in] other non-const iterator to copy from - @note It is not checked whether @a other is initialized. - */ - iter_impl(const iter_impl::type>& other) noexcept - : m_object(other.m_object), m_it(other.m_it) - {} - - /*! - @brief converting assignment - @param[in] other non-const iterator to copy from - @return const/non-const iterator - @note It is not checked whether @a other is initialized. - */ - iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) - { - m_object = other.m_object; - m_it = other.m_it; - return *this; - } - - JSON_PRIVATE_UNLESS_TESTED: - /*! - @brief set the iterator to the first value - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - void set_begin() noexcept - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = m_object->m_value.object->begin(); - break; - } - - case value_t::array: - { - m_it.array_iterator = m_object->m_value.array->begin(); - break; - } - - case value_t::null: - { - // set to end so begin()==end() is true: null is empty - m_it.primitive_iterator.set_end(); - break; - } - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator.set_begin(); - break; - } - } - } - - /*! - @brief set the iterator past the last value - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - void set_end() noexcept - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - m_it.object_iterator = m_object->m_value.object->end(); - break; - } - - case value_t::array: - { - m_it.array_iterator = m_object->m_value.array->end(); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator.set_end(); - break; - } - } - } - - public: - /*! - @brief return a reference to the value pointed to by the iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference operator*() const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); - return m_it.object_iterator->second; - } - - case value_t::array: - { - JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); - return *m_it.array_iterator; - } - - case value_t::null: - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) - { - return *m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - } - } - } - - /*! - @brief dereference the iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - pointer operator->() const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); - return &(m_it.object_iterator->second); - } - - case value_t::array: - { - JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); - return &*m_it.array_iterator; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) - { - return m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - } - } - } - - /*! - @brief post-increment (it++) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl const operator++(int) // NOLINT(readability-const-return-type) - { - auto result = *this; - ++(*this); - return result; - } - - /*! - @brief pre-increment (++it) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator++() - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - std::advance(m_it.object_iterator, 1); - break; - } - - case value_t::array: - { - std::advance(m_it.array_iterator, 1); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - ++m_it.primitive_iterator; - break; - } - } - - return *this; - } - - /*! - @brief post-decrement (it--) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl const operator--(int) // NOLINT(readability-const-return-type) - { - auto result = *this; - --(*this); - return result; - } - - /*! - @brief pre-decrement (--it) - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator--() - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - { - std::advance(m_it.object_iterator, -1); - break; - } - - case value_t::array: - { - std::advance(m_it.array_iterator, -1); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - --m_it.primitive_iterator; - break; - } - } - - return *this; - } - - /*! - @brief comparison: equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > - bool operator==(const IterImpl& other) const - { - // if objects are not the same, the comparison is undefined - if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) - { - JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); - } - - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - return (m_it.object_iterator == other.m_it.object_iterator); - - case value_t::array: - return (m_it.array_iterator == other.m_it.array_iterator); - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return (m_it.primitive_iterator == other.m_it.primitive_iterator); - } - } - - /*! - @brief comparison: not equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > - bool operator!=(const IterImpl& other) const - { - return !operator==(other); - } - - /*! - @brief comparison: smaller - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator<(const iter_impl& other) const - { - // if objects are not the same, the comparison is undefined - if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) - { - JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); - } - - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); - - case value_t::array: - return (m_it.array_iterator < other.m_it.array_iterator); - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return (m_it.primitive_iterator < other.m_it.primitive_iterator); - } - } - - /*! - @brief comparison: less than or equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator<=(const iter_impl& other) const - { - return !other.operator < (*this); - } - - /*! - @brief comparison: greater than - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator>(const iter_impl& other) const - { - return !operator<=(other); - } - - /*! - @brief comparison: greater than or equal - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - bool operator>=(const iter_impl& other) const - { - return !operator<(other); - } - - /*! - @brief add to iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator+=(difference_type i) - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); - - case value_t::array: - { - std::advance(m_it.array_iterator, i); - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - m_it.primitive_iterator += i; - break; - } - } - - return *this; - } - - /*! - @brief subtract from iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl& operator-=(difference_type i) - { - return operator+=(-i); - } - - /*! - @brief add to iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl operator+(difference_type i) const - { - auto result = *this; - result += i; - return result; - } - - /*! - @brief addition of distance and iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - friend iter_impl operator+(difference_type i, const iter_impl& it) - { - auto result = it; - result += i; - return result; - } - - /*! - @brief subtract from iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - iter_impl operator-(difference_type i) const - { - auto result = *this; - result -= i; - return result; - } - - /*! - @brief return difference - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - difference_type operator-(const iter_impl& other) const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); - - case value_t::array: - return m_it.array_iterator - other.m_it.array_iterator; - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - return m_it.primitive_iterator - other.m_it.primitive_iterator; - } - } - - /*! - @brief access to successor - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference operator[](difference_type n) const - { - JSON_ASSERT(m_object != nullptr); - - switch (m_object->m_type) - { - case value_t::object: - JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); - - case value_t::array: - return *std::next(m_it.array_iterator, n); - - case value_t::null: - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) - { - return *m_object; - } - - JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); - } - } - } - - /*! - @brief return the key of an object iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - const typename object_t::key_type& key() const - { - JSON_ASSERT(m_object != nullptr); - - if (JSON_HEDLEY_LIKELY(m_object->is_object())) - { - return m_it.object_iterator->first; - } - - JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); - } - - /*! - @brief return the value of an iterator - @pre The iterator is initialized; i.e. `m_object != nullptr`. - */ - reference value() const - { - return operator*(); - } - - JSON_PRIVATE_UNLESS_TESTED: - /// associated JSON instance - pointer m_object = nullptr; - /// the actual iterator of the associated instance - internal_iterator::type> m_it {}; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // ptrdiff_t -#include // reverse_iterator -#include // declval - -namespace nlohmann -{ -namespace detail -{ -////////////////////// -// reverse_iterator // -////////////////////// - -/*! -@brief a template for a reverse iterator class - -@tparam Base the base iterator type to reverse. Valid types are @ref -iterator (to create @ref reverse_iterator) and @ref const_iterator (to -create @ref const_reverse_iterator). - -@requirement The class satisfies the following concept requirements: -- -[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): - The iterator that can be moved can be moved in both directions (i.e. - incremented and decremented). -- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): - It is possible to write to the pointed-to element (only if @a Base is - @ref iterator). - -@since version 1.0.0 -*/ -template -class json_reverse_iterator : public std::reverse_iterator -{ - public: - using difference_type = std::ptrdiff_t; - /// shortcut to the reverse iterator adapter - using base_iterator = std::reverse_iterator; - /// the reference type for the pointed-to element - using reference = typename Base::reference; - - /// create reverse iterator from iterator - explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept - : base_iterator(it) {} - - /// create reverse iterator from base class - explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} - - /// post-increment (it++) - json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) - { - return static_cast(base_iterator::operator++(1)); - } - - /// pre-increment (++it) - json_reverse_iterator& operator++() - { - return static_cast(base_iterator::operator++()); - } - - /// post-decrement (it--) - json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) - { - return static_cast(base_iterator::operator--(1)); - } - - /// pre-decrement (--it) - json_reverse_iterator& operator--() - { - return static_cast(base_iterator::operator--()); - } - - /// add to iterator - json_reverse_iterator& operator+=(difference_type i) - { - return static_cast(base_iterator::operator+=(i)); - } - - /// add to iterator - json_reverse_iterator operator+(difference_type i) const - { - return static_cast(base_iterator::operator+(i)); - } - - /// subtract from iterator - json_reverse_iterator operator-(difference_type i) const - { - return static_cast(base_iterator::operator-(i)); - } - - /// return difference - difference_type operator-(const json_reverse_iterator& other) const - { - return base_iterator(*this) - base_iterator(other); - } - - /// access to successor - reference operator[](difference_type n) const - { - return *(this->operator+(n)); - } - - /// return the key of an object iterator - auto key() const -> decltype(std::declval().key()) - { - auto it = --this->base(); - return it.key(); - } - - /// return the value of an iterator - reference value() const - { - auto it = --this->base(); - return it.operator * (); - } -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // all_of -#include // isdigit -#include // max -#include // accumulate -#include // string -#include // move -#include // vector - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ - -/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document -/// @sa https://json.nlohmann.me/api/json_pointer/ -template -class json_pointer -{ - // allow basic_json to access private members - NLOHMANN_BASIC_JSON_TPL_DECLARATION - friend class basic_json; - - public: - /// @brief create JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ - explicit json_pointer(const std::string& s = "") - : reference_tokens(split(s)) - {} - - /// @brief return a string representation of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ - std::string to_string() const - { - return std::accumulate(reference_tokens.begin(), reference_tokens.end(), - std::string{}, - [](const std::string & a, const std::string & b) - { - return a + "/" + detail::escape(b); - }); - } - - /// @brief return a string representation of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/ - operator std::string() const - { - return to_string(); - } - - /// @brief append another JSON pointer at the end of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - json_pointer& operator/=(const json_pointer& ptr) - { - reference_tokens.insert(reference_tokens.end(), - ptr.reference_tokens.begin(), - ptr.reference_tokens.end()); - return *this; - } - - /// @brief append an unescaped reference token at the end of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - json_pointer& operator/=(std::string token) - { - push_back(std::move(token)); - return *this; - } - - /// @brief append an array index at the end of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ - json_pointer& operator/=(std::size_t array_idx) - { - return *this /= std::to_string(array_idx); - } - - /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ - friend json_pointer operator/(const json_pointer& lhs, - const json_pointer& rhs) - { - return json_pointer(lhs) /= rhs; - } - - /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ - friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param) - { - return json_pointer(lhs) /= std::move(token); - } - - /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ - friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) - { - return json_pointer(lhs) /= array_idx; - } - - /// @brief returns the parent of this JSON pointer - /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ - json_pointer parent_pointer() const - { - if (empty()) - { - return *this; - } - - json_pointer res = *this; - res.pop_back(); - return res; - } - - /// @brief remove last reference token - /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ - void pop_back() - { - if (JSON_HEDLEY_UNLIKELY(empty())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); - } - - reference_tokens.pop_back(); - } - - /// @brief return last reference token - /// @sa https://json.nlohmann.me/api/json_pointer/back/ - const std::string& back() const - { - if (JSON_HEDLEY_UNLIKELY(empty())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); - } - - return reference_tokens.back(); - } - - /// @brief append an unescaped token at the end of the reference pointer - /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ - void push_back(const std::string& token) - { - reference_tokens.push_back(token); - } - - /// @brief append an unescaped token at the end of the reference pointer - /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ - void push_back(std::string&& token) - { - reference_tokens.push_back(std::move(token)); - } - - /// @brief return whether pointer points to the root document - /// @sa https://json.nlohmann.me/api/json_pointer/empty/ - bool empty() const noexcept - { - return reference_tokens.empty(); - } - - private: - /*! - @param[in] s reference token to be converted into an array index - - @return integer representation of @a s - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index begins not with a digit - @throw out_of_range.404 if string @a s could not be converted to an integer - @throw out_of_range.410 if an array index exceeds size_type - */ - static typename BasicJsonType::size_type array_index(const std::string& s) - { - using size_type = typename BasicJsonType::size_type; - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) - { - JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); - } - - // error condition (cf. RFC 6901, Sect. 4) - if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) - { - JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); - } - - std::size_t processed_chars = 0; - unsigned long long res = 0; // NOLINT(runtime/int) - JSON_TRY - { - res = std::stoull(s, &processed_chars); - } - JSON_CATCH(std::out_of_range&) - { - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); - } - - // check if the string was completely read - if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) - { - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); - } - - // only triggered on special platforms (like 32bit), see also - // https://github.com/nlohmann/json/pull/2203 - if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) - { - JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE - } - - return static_cast(res); - } - - JSON_PRIVATE_UNLESS_TESTED: - json_pointer top() const - { - if (JSON_HEDLEY_UNLIKELY(empty())) - { - JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); - } - - json_pointer result = *this; - result.reference_tokens = {reference_tokens[0]}; - return result; - } - - private: - /*! - @brief create and return a reference to the pointed to value - - @complexity Linear in the number of reference tokens. - - @throw parse_error.109 if array index is not a number - @throw type_error.313 if value cannot be unflattened - */ - BasicJsonType& get_and_create(BasicJsonType& j) const - { - auto* result = &j; - - // in case no reference tokens exist, return a reference to the JSON value - // j which will be overwritten by a primitive value - for (const auto& reference_token : reference_tokens) - { - switch (result->type()) - { - case detail::value_t::null: - { - if (reference_token == "0") - { - // start a new array if reference token is 0 - result = &result->operator[](0); - } - else - { - // start a new object otherwise - result = &result->operator[](reference_token); - } - break; - } - - case detail::value_t::object: - { - // create an entry in the object - result = &result->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - // create an entry in the array - result = &result->operator[](array_index(reference_token)); - break; - } - - /* - The following code is only reached if there exists a reference - token _and_ the current value is primitive. In this case, we have - an error situation, because primitive values may only occur as - single value; that is, with an empty list of reference tokens. - */ - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); - } - } - - return *result; - } - - /*! - @brief return a reference to the pointed to value - - @note This version does not throw if a value is not present, but tries to - create nested values instead. For instance, calling this function - with pointer `"/this/that"` on a null value is equivalent to calling - `operator[]("this").operator[]("that")` on that value, effectively - changing the null value to an object. - - @param[in] ptr a JSON value - - @return reference to the JSON value pointed to by the JSON pointer - - @complexity Linear in the length of the JSON pointer. - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - BasicJsonType& get_unchecked(BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - // convert null values to arrays or objects before continuing - if (ptr->is_null()) - { - // check if reference token is a number - const bool nums = - std::all_of(reference_token.begin(), reference_token.end(), - [](const unsigned char x) - { - return std::isdigit(x); - }); - - // change value to array for numbers or "-" or to object otherwise - *ptr = (nums || reference_token == "-") - ? detail::value_t::array - : detail::value_t::object; - } - - switch (ptr->type()) - { - case detail::value_t::object: - { - // use unchecked object access - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (reference_token == "-") - { - // explicitly treat "-" as index beyond the end - ptr = &ptr->operator[](ptr->m_value.array->size()); - } - else - { - // convert array index to number; unchecked access - ptr = &ptr->operator[](array_index(reference_token)); - } - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - BasicJsonType& get_checked(BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - // note: at performs range check - ptr = &ptr->at(reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range", *ptr)); - } - - // note: at performs range check - ptr = &ptr->at(array_index(reference_token)); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @brief return a const reference to the pointed to value - - @param[in] ptr a JSON value - - @return const reference to the JSON value pointed to by the JSON - pointer - - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - // use unchecked object access - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" cannot be used for const access - JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); - } - - // use unchecked array access - ptr = &ptr->operator[](array_index(reference_token)); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - @throw out_of_range.402 if the array index '-' is used - @throw out_of_range.404 if the JSON pointer can not be resolved - */ - const BasicJsonType& get_checked(const BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - // note: at performs range check - ptr = &ptr->at(reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - JSON_THROW(detail::out_of_range::create(402, - "array index '-' (" + std::to_string(ptr->m_value.array->size()) + - ") is out of range", *ptr)); - } - - // note: at performs range check - ptr = &ptr->at(array_index(reference_token)); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); - } - } - - return *ptr; - } - - /*! - @throw parse_error.106 if an array index begins with '0' - @throw parse_error.109 if an array index was not a number - */ - bool contains(const BasicJsonType* ptr) const - { - for (const auto& reference_token : reference_tokens) - { - switch (ptr->type()) - { - case detail::value_t::object: - { - if (!ptr->contains(reference_token)) - { - // we did not find the key in the object - return false; - } - - ptr = &ptr->operator[](reference_token); - break; - } - - case detail::value_t::array: - { - if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) - { - // "-" always fails the range check - return false; - } - if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) - { - // invalid char - return false; - } - if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) - { - if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) - { - // first char should be between '1' and '9' - return false; - } - for (std::size_t i = 1; i < reference_token.size(); i++) - { - if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) - { - // other char should be between '0' and '9' - return false; - } - } - } - - const auto idx = array_index(reference_token); - if (idx >= ptr->size()) - { - // index out of range - return false; - } - - ptr = &ptr->operator[](idx); - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - { - // we do not expect primitive values if there is still a - // reference token to process - return false; - } - } - } - - // no reference token left means we found a primitive value - return true; - } - - /*! - @brief split the string input to reference tokens - - @note This function is only called by the json_pointer constructor. - All exceptions below are documented there. - - @throw parse_error.107 if the pointer is not empty or begins with '/' - @throw parse_error.108 if character '~' is not followed by '0' or '1' - */ - static std::vector split(const std::string& reference_string) - { - std::vector result; - - // special case: empty reference string -> no reference tokens - if (reference_string.empty()) - { - return result; - } - - // check if nonempty reference string begins with slash - if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) - { - JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); - } - - // extract the reference tokens: - // - slash: position of the last read slash (or end of string) - // - start: position after the previous slash - for ( - // search for the first slash after the first character - std::size_t slash = reference_string.find_first_of('/', 1), - // set the beginning of the first reference token - start = 1; - // we can stop if start == 0 (if slash == std::string::npos) - start != 0; - // set the beginning of the next reference token - // (will eventually be 0 if slash == std::string::npos) - start = (slash == std::string::npos) ? 0 : slash + 1, - // find next slash - slash = reference_string.find_first_of('/', start)) - { - // use the text between the beginning of the reference token - // (start) and the last slash (slash). - auto reference_token = reference_string.substr(start, slash - start); - - // check reference tokens are properly escaped - for (std::size_t pos = reference_token.find_first_of('~'); - pos != std::string::npos; - pos = reference_token.find_first_of('~', pos + 1)) - { - JSON_ASSERT(reference_token[pos] == '~'); - - // ~ must be followed by 0 or 1 - if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || - (reference_token[pos + 1] != '0' && - reference_token[pos + 1] != '1'))) - { - JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); - } - } - - // finally, store the reference token - detail::unescape(reference_token); - result.push_back(reference_token); - } - - return result; - } - - private: - /*! - @param[in] reference_string the reference string to the current value - @param[in] value the value to consider - @param[in,out] result the result object to insert values to - - @note Empty objects or arrays are flattened to `null`. - */ - static void flatten(const std::string& reference_string, - const BasicJsonType& value, - BasicJsonType& result) - { - switch (value.type()) - { - case detail::value_t::array: - { - if (value.m_value.array->empty()) - { - // flatten empty array as null - result[reference_string] = nullptr; - } - else - { - // iterate array and use index as reference string - for (std::size_t i = 0; i < value.m_value.array->size(); ++i) - { - flatten(reference_string + "/" + std::to_string(i), - value.m_value.array->operator[](i), result); - } - } - break; - } - - case detail::value_t::object: - { - if (value.m_value.object->empty()) - { - // flatten empty object as null - result[reference_string] = nullptr; - } - else - { - // iterate object and use keys as reference string - for (const auto& element : *value.m_value.object) - { - flatten(reference_string + "/" + detail::escape(element.first), element.second, result); - } - } - break; - } - - case detail::value_t::null: - case detail::value_t::string: - case detail::value_t::boolean: - case detail::value_t::number_integer: - case detail::value_t::number_unsigned: - case detail::value_t::number_float: - case detail::value_t::binary: - case detail::value_t::discarded: - default: - { - // add primitive value with its reference string - result[reference_string] = value; - break; - } - } - } - - /*! - @param[in] value flattened JSON - - @return unflattened JSON - - @throw parse_error.109 if array index is not a number - @throw type_error.314 if value is not an object - @throw type_error.315 if object values are not primitive - @throw type_error.313 if value cannot be unflattened - */ - static BasicJsonType - unflatten(const BasicJsonType& value) - { - if (JSON_HEDLEY_UNLIKELY(!value.is_object())) - { - JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); - } - - BasicJsonType result; - - // iterate the JSON object values - for (const auto& element : *value.m_value.object) - { - if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) - { - JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); - } - - // assign value to reference pointed to by JSON pointer; Note that if - // the JSON pointer is "" (i.e., points to the whole value), function - // get_and_create returns a reference to result itself. An assignment - // will then create a primitive value. - json_pointer(element.first).get_and_create(result) = element.second; - } - - return result; - } - - /*! - @brief compares two JSON pointers for equality - - @param[in] lhs JSON pointer to compare - @param[in] rhs JSON pointer to compare - @return whether @a lhs is equal to @a rhs - - @complexity Linear in the length of the JSON pointer - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - */ - friend bool operator==(json_pointer const& lhs, - json_pointer const& rhs) noexcept - { - return lhs.reference_tokens == rhs.reference_tokens; - } - - /*! - @brief compares two JSON pointers for inequality - - @param[in] lhs JSON pointer to compare - @param[in] rhs JSON pointer to compare - @return whether @a lhs is not equal @a rhs - - @complexity Linear in the length of the JSON pointer - - @exceptionsafety No-throw guarantee: this function never throws exceptions. - */ - friend bool operator!=(json_pointer const& lhs, - json_pointer const& rhs) noexcept - { - return !(lhs == rhs); - } - - /// the reference tokens - std::vector reference_tokens; -}; -} // namespace nlohmann - -// #include - - -#include -#include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -template -class json_ref -{ - public: - using value_type = BasicJsonType; - - json_ref(value_type&& value) - : owned_value(std::move(value)) - {} - - json_ref(const value_type& value) - : value_ref(&value) - {} - - json_ref(std::initializer_list init) - : owned_value(init) - {} - - template < - class... Args, - enable_if_t::value, int> = 0 > - json_ref(Args && ... args) - : owned_value(std::forward(args)...) - {} - - // class should be movable only - json_ref(json_ref&&) noexcept = default; - json_ref(const json_ref&) = delete; - json_ref& operator=(const json_ref&) = delete; - json_ref& operator=(json_ref&&) = delete; - ~json_ref() = default; - - value_type moved_or_copied() const - { - if (value_ref == nullptr) - { - return std::move(owned_value); - } - return *value_ref; - } - - value_type const& operator*() const - { - return value_ref ? *value_ref : owned_value; - } - - value_type const* operator->() const - { - return &** this; - } - - private: - mutable value_type owned_value = nullptr; - value_type const* value_ref = nullptr; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - -// #include - -// #include - - -#include // reverse -#include // array -#include // isnan, isinf -#include // uint8_t, uint16_t, uint32_t, uint64_t -#include // memcpy -#include // numeric_limits -#include // string -#include // move - -// #include - -// #include - -// #include - - -#include // copy -#include // size_t -#include // back_inserter -#include // shared_ptr, make_shared -#include // basic_string -#include // vector - -#ifndef JSON_NO_IO - #include // streamsize - #include // basic_ostream -#endif // JSON_NO_IO - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/// abstract output adapter interface -template struct output_adapter_protocol -{ - virtual void write_character(CharType c) = 0; - virtual void write_characters(const CharType* s, std::size_t length) = 0; - virtual ~output_adapter_protocol() = default; - - output_adapter_protocol() = default; - output_adapter_protocol(const output_adapter_protocol&) = default; - output_adapter_protocol(output_adapter_protocol&&) noexcept = default; - output_adapter_protocol& operator=(const output_adapter_protocol&) = default; - output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; -}; - -/// a type to simplify interfaces -template -using output_adapter_t = std::shared_ptr>; - -/// output adapter for byte vectors -template> -class output_vector_adapter : public output_adapter_protocol -{ - public: - explicit output_vector_adapter(std::vector& vec) noexcept - : v(vec) - {} - - void write_character(CharType c) override - { - v.push_back(c); - } - - JSON_HEDLEY_NON_NULL(2) - void write_characters(const CharType* s, std::size_t length) override - { - std::copy(s, s + length, std::back_inserter(v)); - } - - private: - std::vector& v; -}; - -#ifndef JSON_NO_IO -/// output adapter for output streams -template -class output_stream_adapter : public output_adapter_protocol -{ - public: - explicit output_stream_adapter(std::basic_ostream& s) noexcept - : stream(s) - {} - - void write_character(CharType c) override - { - stream.put(c); - } - - JSON_HEDLEY_NON_NULL(2) - void write_characters(const CharType* s, std::size_t length) override - { - stream.write(s, static_cast(length)); - } - - private: - std::basic_ostream& stream; -}; -#endif // JSON_NO_IO - -/// output adapter for basic_string -template> -class output_string_adapter : public output_adapter_protocol -{ - public: - explicit output_string_adapter(StringType& s) noexcept - : str(s) - {} - - void write_character(CharType c) override - { - str.push_back(c); - } - - JSON_HEDLEY_NON_NULL(2) - void write_characters(const CharType* s, std::size_t length) override - { - str.append(s, length); - } - - private: - StringType& str; -}; - -template> -class output_adapter -{ - public: - template> - output_adapter(std::vector& vec) - : oa(std::make_shared>(vec)) {} - -#ifndef JSON_NO_IO - output_adapter(std::basic_ostream& s) - : oa(std::make_shared>(s)) {} -#endif // JSON_NO_IO - - output_adapter(StringType& s) - : oa(std::make_shared>(s)) {} - - operator output_adapter_t() - { - return oa; - } - - private: - output_adapter_t oa = nullptr; -}; -} // namespace detail -} // namespace nlohmann - - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// binary writer // -/////////////////// - -/*! -@brief serialization to CBOR and MessagePack values -*/ -template -class binary_writer -{ - using string_t = typename BasicJsonType::string_t; - using binary_t = typename BasicJsonType::binary_t; - using number_float_t = typename BasicJsonType::number_float_t; - - public: - /*! - @brief create a binary writer - - @param[in] adapter output adapter to write to - */ - explicit binary_writer(output_adapter_t adapter) : oa(std::move(adapter)) - { - JSON_ASSERT(oa); - } - - /*! - @param[in] j JSON value to serialize - @pre j.type() == value_t::object - */ - void write_bson(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::object: - { - write_bson_object(*j.m_value.object); - break; - } - - case value_t::null: - case value_t::array: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j)); - } - } - } - - /*! - @param[in] j JSON value to serialize - */ - void write_cbor(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::null: - { - oa->write_character(to_char_type(0xF6)); - break; - } - - case value_t::boolean: - { - oa->write_character(j.m_value.boolean - ? to_char_type(0xF5) - : to_char_type(0xF4)); - break; - } - - case value_t::number_integer: - { - if (j.m_value.number_integer >= 0) - { - // CBOR does not differentiate between positive signed - // integers and unsigned integers. Therefore, we used the - // code from the value_t::number_unsigned case here. - if (j.m_value.number_integer <= 0x17) - { - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x18)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x19)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x1A)); - write_number(static_cast(j.m_value.number_integer)); - } - else - { - oa->write_character(to_char_type(0x1B)); - write_number(static_cast(j.m_value.number_integer)); - } - } - else - { - // The conversions below encode the sign in the first - // byte, and the value is converted to a positive number. - const auto positive_number = -1 - j.m_value.number_integer; - if (j.m_value.number_integer >= -24) - { - write_number(static_cast(0x20 + positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x38)); - write_number(static_cast(positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x39)); - write_number(static_cast(positive_number)); - } - else if (positive_number <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x3A)); - write_number(static_cast(positive_number)); - } - else - { - oa->write_character(to_char_type(0x3B)); - write_number(static_cast(positive_number)); - } - } - break; - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned <= 0x17) - { - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x18)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x19)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x1A)); - write_number(static_cast(j.m_value.number_unsigned)); - } - else - { - oa->write_character(to_char_type(0x1B)); - write_number(static_cast(j.m_value.number_unsigned)); - } - break; - } - - case value_t::number_float: - { - if (std::isnan(j.m_value.number_float)) - { - // NaN is 0xf97e00 in CBOR - oa->write_character(to_char_type(0xF9)); - oa->write_character(to_char_type(0x7E)); - oa->write_character(to_char_type(0x00)); - } - else if (std::isinf(j.m_value.number_float)) - { - // Infinity is 0xf97c00, -Infinity is 0xf9fc00 - oa->write_character(to_char_type(0xf9)); - oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); - oa->write_character(to_char_type(0x00)); - } - else - { - write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); - } - break; - } - - case value_t::string: - { - // step 1: write control byte and the string length - const auto N = j.m_value.string->size(); - if (N <= 0x17) - { - write_number(static_cast(0x60 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x78)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x79)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x7A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x7B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write the string - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - // step 1: write control byte and the array size - const auto N = j.m_value.array->size(); - if (N <= 0x17) - { - write_number(static_cast(0x80 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x98)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x99)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x9A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x9B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - for (const auto& el : *j.m_value.array) - { - write_cbor(el); - } - break; - } - - case value_t::binary: - { - if (j.m_value.binary->has_subtype()) - { - if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xd8)); - write_number(static_cast(j.m_value.binary->subtype())); - } - else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xd9)); - write_number(static_cast(j.m_value.binary->subtype())); - } - else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xda)); - write_number(static_cast(j.m_value.binary->subtype())); - } - else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) - { - write_number(static_cast(0xdb)); - write_number(static_cast(j.m_value.binary->subtype())); - } - } - - // step 1: write control byte and the binary array size - const auto N = j.m_value.binary->size(); - if (N <= 0x17) - { - write_number(static_cast(0x40 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x58)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x59)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x5A)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0x5B)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - oa->write_characters( - reinterpret_cast(j.m_value.binary->data()), - N); - - break; - } - - case value_t::object: - { - // step 1: write control byte and the object size - const auto N = j.m_value.object->size(); - if (N <= 0x17) - { - write_number(static_cast(0xA0 + N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xB8)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xB9)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xBA)); - write_number(static_cast(N)); - } - // LCOV_EXCL_START - else if (N <= (std::numeric_limits::max)()) - { - oa->write_character(to_char_type(0xBB)); - write_number(static_cast(N)); - } - // LCOV_EXCL_STOP - - // step 2: write each element - for (const auto& el : *j.m_value.object) - { - write_cbor(el.first); - write_cbor(el.second); - } - break; - } - - case value_t::discarded: - default: - break; - } - } - - /*! - @param[in] j JSON value to serialize - */ - void write_msgpack(const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::null: // nil - { - oa->write_character(to_char_type(0xC0)); - break; - } - - case value_t::boolean: // true and false - { - oa->write_character(j.m_value.boolean - ? to_char_type(0xC3) - : to_char_type(0xC2)); - break; - } - - case value_t::number_integer: - { - if (j.m_value.number_integer >= 0) - { - // MessagePack does not differentiate between positive - // signed integers and unsigned integers. Therefore, we used - // the code from the value_t::number_unsigned case here. - if (j.m_value.number_unsigned < 128) - { - // positive fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 8 - oa->write_character(to_char_type(0xCC)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 16 - oa->write_character(to_char_type(0xCD)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 32 - oa->write_character(to_char_type(0xCE)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 64 - oa->write_character(to_char_type(0xCF)); - write_number(static_cast(j.m_value.number_integer)); - } - } - else - { - if (j.m_value.number_integer >= -32) - { - // negative fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 8 - oa->write_character(to_char_type(0xD0)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 16 - oa->write_character(to_char_type(0xD1)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 32 - oa->write_character(to_char_type(0xD2)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_integer >= (std::numeric_limits::min)() && - j.m_value.number_integer <= (std::numeric_limits::max)()) - { - // int 64 - oa->write_character(to_char_type(0xD3)); - write_number(static_cast(j.m_value.number_integer)); - } - } - break; - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned < 128) - { - // positive fixnum - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 8 - oa->write_character(to_char_type(0xCC)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 16 - oa->write_character(to_char_type(0xCD)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 32 - oa->write_character(to_char_type(0xCE)); - write_number(static_cast(j.m_value.number_integer)); - } - else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) - { - // uint 64 - oa->write_character(to_char_type(0xCF)); - write_number(static_cast(j.m_value.number_integer)); - } - break; - } - - case value_t::number_float: - { - write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); - break; - } - - case value_t::string: - { - // step 1: write control byte and the string length - const auto N = j.m_value.string->size(); - if (N <= 31) - { - // fixstr - write_number(static_cast(0xA0 | N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 8 - oa->write_character(to_char_type(0xD9)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 16 - oa->write_character(to_char_type(0xDA)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // str 32 - oa->write_character(to_char_type(0xDB)); - write_number(static_cast(N)); - } - - // step 2: write the string - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - // step 1: write control byte and the array size - const auto N = j.m_value.array->size(); - if (N <= 15) - { - // fixarray - write_number(static_cast(0x90 | N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // array 16 - oa->write_character(to_char_type(0xDC)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // array 32 - oa->write_character(to_char_type(0xDD)); - write_number(static_cast(N)); - } - - // step 2: write each element - for (const auto& el : *j.m_value.array) - { - write_msgpack(el); - } - break; - } - - case value_t::binary: - { - // step 0: determine if the binary type has a set subtype to - // determine whether or not to use the ext or fixext types - const bool use_ext = j.m_value.binary->has_subtype(); - - // step 1: write control byte and the byte string length - const auto N = j.m_value.binary->size(); - if (N <= (std::numeric_limits::max)()) - { - std::uint8_t output_type{}; - bool fixed = true; - if (use_ext) - { - switch (N) - { - case 1: - output_type = 0xD4; // fixext 1 - break; - case 2: - output_type = 0xD5; // fixext 2 - break; - case 4: - output_type = 0xD6; // fixext 4 - break; - case 8: - output_type = 0xD7; // fixext 8 - break; - case 16: - output_type = 0xD8; // fixext 16 - break; - default: - output_type = 0xC7; // ext 8 - fixed = false; - break; - } - - } - else - { - output_type = 0xC4; // bin 8 - fixed = false; - } - - oa->write_character(to_char_type(output_type)); - if (!fixed) - { - write_number(static_cast(N)); - } - } - else if (N <= (std::numeric_limits::max)()) - { - std::uint8_t output_type = use_ext - ? 0xC8 // ext 16 - : 0xC5; // bin 16 - - oa->write_character(to_char_type(output_type)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - std::uint8_t output_type = use_ext - ? 0xC9 // ext 32 - : 0xC6; // bin 32 - - oa->write_character(to_char_type(output_type)); - write_number(static_cast(N)); - } - - // step 1.5: if this is an ext type, write the subtype - if (use_ext) - { - write_number(static_cast(j.m_value.binary->subtype())); - } - - // step 2: write the byte string - oa->write_characters( - reinterpret_cast(j.m_value.binary->data()), - N); - - break; - } - - case value_t::object: - { - // step 1: write control byte and the object size - const auto N = j.m_value.object->size(); - if (N <= 15) - { - // fixmap - write_number(static_cast(0x80 | (N & 0xF))); - } - else if (N <= (std::numeric_limits::max)()) - { - // map 16 - oa->write_character(to_char_type(0xDE)); - write_number(static_cast(N)); - } - else if (N <= (std::numeric_limits::max)()) - { - // map 32 - oa->write_character(to_char_type(0xDF)); - write_number(static_cast(N)); - } - - // step 2: write each element - for (const auto& el : *j.m_value.object) - { - write_msgpack(el.first); - write_msgpack(el.second); - } - break; - } - - case value_t::discarded: - default: - break; - } - } - - /*! - @param[in] j JSON value to serialize - @param[in] use_count whether to use '#' prefixes (optimized format) - @param[in] use_type whether to use '$' prefixes (optimized format) - @param[in] add_prefix whether prefixes need to be used for this value - */ - void write_ubjson(const BasicJsonType& j, const bool use_count, - const bool use_type, const bool add_prefix = true) - { - switch (j.type()) - { - case value_t::null: - { - if (add_prefix) - { - oa->write_character(to_char_type('Z')); - } - break; - } - - case value_t::boolean: - { - if (add_prefix) - { - oa->write_character(j.m_value.boolean - ? to_char_type('T') - : to_char_type('F')); - } - break; - } - - case value_t::number_integer: - { - write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); - break; - } - - case value_t::number_unsigned: - { - write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); - break; - } - - case value_t::number_float: - { - write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); - break; - } - - case value_t::string: - { - if (add_prefix) - { - oa->write_character(to_char_type('S')); - } - write_number_with_ubjson_prefix(j.m_value.string->size(), true); - oa->write_characters( - reinterpret_cast(j.m_value.string->c_str()), - j.m_value.string->size()); - break; - } - - case value_t::array: - { - if (add_prefix) - { - oa->write_character(to_char_type('[')); - } - - bool prefix_required = true; - if (use_type && !j.m_value.array->empty()) - { - JSON_ASSERT(use_count); - const CharType first_prefix = ubjson_prefix(j.front()); - const bool same_prefix = std::all_of(j.begin() + 1, j.end(), - [this, first_prefix](const BasicJsonType & v) - { - return ubjson_prefix(v) == first_prefix; - }); - - if (same_prefix) - { - prefix_required = false; - oa->write_character(to_char_type('$')); - oa->write_character(first_prefix); - } - } - - if (use_count) - { - oa->write_character(to_char_type('#')); - write_number_with_ubjson_prefix(j.m_value.array->size(), true); - } - - for (const auto& el : *j.m_value.array) - { - write_ubjson(el, use_count, use_type, prefix_required); - } - - if (!use_count) - { - oa->write_character(to_char_type(']')); - } - - break; - } - - case value_t::binary: - { - if (add_prefix) - { - oa->write_character(to_char_type('[')); - } - - if (use_type && !j.m_value.binary->empty()) - { - JSON_ASSERT(use_count); - oa->write_character(to_char_type('$')); - oa->write_character('U'); - } - - if (use_count) - { - oa->write_character(to_char_type('#')); - write_number_with_ubjson_prefix(j.m_value.binary->size(), true); - } - - if (use_type) - { - oa->write_characters( - reinterpret_cast(j.m_value.binary->data()), - j.m_value.binary->size()); - } - else - { - for (size_t i = 0; i < j.m_value.binary->size(); ++i) - { - oa->write_character(to_char_type('U')); - oa->write_character(j.m_value.binary->data()[i]); - } - } - - if (!use_count) - { - oa->write_character(to_char_type(']')); - } - - break; - } - - case value_t::object: - { - if (add_prefix) - { - oa->write_character(to_char_type('{')); - } - - bool prefix_required = true; - if (use_type && !j.m_value.object->empty()) - { - JSON_ASSERT(use_count); - const CharType first_prefix = ubjson_prefix(j.front()); - const bool same_prefix = std::all_of(j.begin(), j.end(), - [this, first_prefix](const BasicJsonType & v) - { - return ubjson_prefix(v) == first_prefix; - }); - - if (same_prefix) - { - prefix_required = false; - oa->write_character(to_char_type('$')); - oa->write_character(first_prefix); - } - } - - if (use_count) - { - oa->write_character(to_char_type('#')); - write_number_with_ubjson_prefix(j.m_value.object->size(), true); - } - - for (const auto& el : *j.m_value.object) - { - write_number_with_ubjson_prefix(el.first.size(), true); - oa->write_characters( - reinterpret_cast(el.first.c_str()), - el.first.size()); - write_ubjson(el.second, use_count, use_type, prefix_required); - } - - if (!use_count) - { - oa->write_character(to_char_type('}')); - } - - break; - } - - case value_t::discarded: - default: - break; - } - } - - private: - ////////// - // BSON // - ////////// - - /*! - @return The size of a BSON document entry header, including the id marker - and the entry name size (and its null-terminator). - */ - static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) - { - const auto it = name.find(static_cast(0)); - if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) - { - JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); - static_cast(j); - } - - return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; - } - - /*! - @brief Writes the given @a element_type and @a name to the output adapter - */ - void write_bson_entry_header(const string_t& name, - const std::uint8_t element_type) - { - oa->write_character(to_char_type(element_type)); // boolean - oa->write_characters( - reinterpret_cast(name.c_str()), - name.size() + 1u); - } - - /*! - @brief Writes a BSON element with key @a name and boolean value @a value - */ - void write_bson_boolean(const string_t& name, - const bool value) - { - write_bson_entry_header(name, 0x08); - oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); - } - - /*! - @brief Writes a BSON element with key @a name and double value @a value - */ - void write_bson_double(const string_t& name, - const double value) - { - write_bson_entry_header(name, 0x01); - write_number(value); - } - - /*! - @return The size of the BSON-encoded string in @a value - */ - static std::size_t calc_bson_string_size(const string_t& value) - { - return sizeof(std::int32_t) + value.size() + 1ul; - } - - /*! - @brief Writes a BSON element with key @a name and string value @a value - */ - void write_bson_string(const string_t& name, - const string_t& value) - { - write_bson_entry_header(name, 0x02); - - write_number(static_cast(value.size() + 1ul)); - oa->write_characters( - reinterpret_cast(value.c_str()), - value.size() + 1); - } - - /*! - @brief Writes a BSON element with key @a name and null value - */ - void write_bson_null(const string_t& name) - { - write_bson_entry_header(name, 0x0A); - } - - /*! - @return The size of the BSON-encoded integer @a value - */ - static std::size_t calc_bson_integer_size(const std::int64_t value) - { - return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() - ? sizeof(std::int32_t) - : sizeof(std::int64_t); - } - - /*! - @brief Writes a BSON element with key @a name and integer @a value - */ - void write_bson_integer(const string_t& name, - const std::int64_t value) - { - if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) - { - write_bson_entry_header(name, 0x10); // int32 - write_number(static_cast(value)); - } - else - { - write_bson_entry_header(name, 0x12); // int64 - write_number(static_cast(value)); - } - } - - /*! - @return The size of the BSON-encoded unsigned integer in @a j - */ - static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept - { - return (value <= static_cast((std::numeric_limits::max)())) - ? sizeof(std::int32_t) - : sizeof(std::int64_t); - } - - /*! - @brief Writes a BSON element with key @a name and unsigned @a value - */ - void write_bson_unsigned(const string_t& name, - const BasicJsonType& j) - { - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - write_bson_entry_header(name, 0x10 /* int32 */); - write_number(static_cast(j.m_value.number_unsigned)); - } - else if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - write_bson_entry_header(name, 0x12 /* int64 */); - write_number(static_cast(j.m_value.number_unsigned)); - } - else - { - JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); - } - } - - /*! - @brief Writes a BSON element with key @a name and object @a value - */ - void write_bson_object_entry(const string_t& name, - const typename BasicJsonType::object_t& value) - { - write_bson_entry_header(name, 0x03); // object - write_bson_object(value); - } - - /*! - @return The size of the BSON-encoded array @a value - */ - static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) - { - std::size_t array_index = 0ul; - - const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) - { - return result + calc_bson_element_size(std::to_string(array_index++), el); - }); - - return sizeof(std::int32_t) + embedded_document_size + 1ul; - } - - /*! - @return The size of the BSON-encoded binary array @a value - */ - static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) - { - return sizeof(std::int32_t) + value.size() + 1ul; - } - - /*! - @brief Writes a BSON element with key @a name and array @a value - */ - void write_bson_array(const string_t& name, - const typename BasicJsonType::array_t& value) - { - write_bson_entry_header(name, 0x04); // array - write_number(static_cast(calc_bson_array_size(value))); - - std::size_t array_index = 0ul; - - for (const auto& el : value) - { - write_bson_element(std::to_string(array_index++), el); - } - - oa->write_character(to_char_type(0x00)); - } - - /*! - @brief Writes a BSON element with key @a name and binary value @a value - */ - void write_bson_binary(const string_t& name, - const binary_t& value) - { - write_bson_entry_header(name, 0x05); - - write_number(static_cast(value.size())); - write_number(value.has_subtype() ? static_cast(value.subtype()) : static_cast(0x00)); - - oa->write_characters(reinterpret_cast(value.data()), value.size()); - } - - /*! - @brief Calculates the size necessary to serialize the JSON value @a j with its @a name - @return The calculated size for the BSON document entry for @a j with the given @a name. - */ - static std::size_t calc_bson_element_size(const string_t& name, - const BasicJsonType& j) - { - const auto header_size = calc_bson_entry_header_size(name, j); - switch (j.type()) - { - case value_t::object: - return header_size + calc_bson_object_size(*j.m_value.object); - - case value_t::array: - return header_size + calc_bson_array_size(*j.m_value.array); - - case value_t::binary: - return header_size + calc_bson_binary_size(*j.m_value.binary); - - case value_t::boolean: - return header_size + 1ul; - - case value_t::number_float: - return header_size + 8ul; - - case value_t::number_integer: - return header_size + calc_bson_integer_size(j.m_value.number_integer); - - case value_t::number_unsigned: - return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); - - case value_t::string: - return header_size + calc_bson_string_size(*j.m_value.string); - - case value_t::null: - return header_size + 0ul; - - // LCOV_EXCL_START - case value_t::discarded: - default: - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) - return 0ul; - // LCOV_EXCL_STOP - } - } - - /*! - @brief Serializes the JSON value @a j to BSON and associates it with the - key @a name. - @param name The name to associate with the JSON entity @a j within the - current BSON document - */ - void write_bson_element(const string_t& name, - const BasicJsonType& j) - { - switch (j.type()) - { - case value_t::object: - return write_bson_object_entry(name, *j.m_value.object); - - case value_t::array: - return write_bson_array(name, *j.m_value.array); - - case value_t::binary: - return write_bson_binary(name, *j.m_value.binary); - - case value_t::boolean: - return write_bson_boolean(name, j.m_value.boolean); - - case value_t::number_float: - return write_bson_double(name, j.m_value.number_float); - - case value_t::number_integer: - return write_bson_integer(name, j.m_value.number_integer); - - case value_t::number_unsigned: - return write_bson_unsigned(name, j); - - case value_t::string: - return write_bson_string(name, *j.m_value.string); - - case value_t::null: - return write_bson_null(name); - - // LCOV_EXCL_START - case value_t::discarded: - default: - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) - return; - // LCOV_EXCL_STOP - } - } - - /*! - @brief Calculates the size of the BSON serialization of the given - JSON-object @a j. - @param[in] value JSON value to serialize - @pre value.type() == value_t::object - */ - static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) - { - std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast(0), - [](size_t result, const typename BasicJsonType::object_t::value_type & el) - { - return result += calc_bson_element_size(el.first, el.second); - }); - - return sizeof(std::int32_t) + document_size + 1ul; - } - - /*! - @param[in] value JSON value to serialize - @pre value.type() == value_t::object - */ - void write_bson_object(const typename BasicJsonType::object_t& value) - { - write_number(static_cast(calc_bson_object_size(value))); - - for (const auto& el : value) - { - write_bson_element(el.first, el.second); - } - - oa->write_character(to_char_type(0x00)); - } - - ////////// - // CBOR // - ////////// - - static constexpr CharType get_cbor_float_prefix(float /*unused*/) - { - return to_char_type(0xFA); // Single-Precision Float - } - - static constexpr CharType get_cbor_float_prefix(double /*unused*/) - { - return to_char_type(0xFB); // Double-Precision Float - } - - ///////////// - // MsgPack // - ///////////// - - static constexpr CharType get_msgpack_float_prefix(float /*unused*/) - { - return to_char_type(0xCA); // float 32 - } - - static constexpr CharType get_msgpack_float_prefix(double /*unused*/) - { - return to_char_type(0xCB); // float 64 - } - - //////////// - // UBJSON // - //////////// - - // UBJSON: write number (floating point) - template::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if (add_prefix) - { - oa->write_character(get_ubjson_float_prefix(n)); - } - write_number(n); - } - - // UBJSON: write number (unsigned integer) - template::value, int>::type = 0> - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('i')); // int8 - } - write_number(static_cast(n)); - } - else if (n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('U')); // uint8 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('I')); // int16 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('l')); // int32 - } - write_number(static_cast(n)); - } - else if (n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('L')); // int64 - } - write_number(static_cast(n)); - } - else - { - if (add_prefix) - { - oa->write_character(to_char_type('H')); // high-precision number - } - - const auto number = BasicJsonType(n).dump(); - write_number_with_ubjson_prefix(number.size(), true); - for (std::size_t i = 0; i < number.size(); ++i) - { - oa->write_character(to_char_type(static_cast(number[i]))); - } - } - } - - // UBJSON: write number (signed integer) - template < typename NumberType, typename std::enable_if < - std::is_signed::value&& - !std::is_floating_point::value, int >::type = 0 > - void write_number_with_ubjson_prefix(const NumberType n, - const bool add_prefix) - { - if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('i')); // int8 - } - write_number(static_cast(n)); - } - else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) - { - if (add_prefix) - { - oa->write_character(to_char_type('U')); // uint8 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('I')); // int16 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('l')); // int32 - } - write_number(static_cast(n)); - } - else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) - { - if (add_prefix) - { - oa->write_character(to_char_type('L')); // int64 - } - write_number(static_cast(n)); - } - // LCOV_EXCL_START - else - { - if (add_prefix) - { - oa->write_character(to_char_type('H')); // high-precision number - } - - const auto number = BasicJsonType(n).dump(); - write_number_with_ubjson_prefix(number.size(), true); - for (std::size_t i = 0; i < number.size(); ++i) - { - oa->write_character(to_char_type(static_cast(number[i]))); - } - } - // LCOV_EXCL_STOP - } - - /*! - @brief determine the type prefix of container values - */ - CharType ubjson_prefix(const BasicJsonType& j) const noexcept - { - switch (j.type()) - { - case value_t::null: - return 'Z'; - - case value_t::boolean: - return j.m_value.boolean ? 'T' : 'F'; - - case value_t::number_integer: - { - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'i'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'U'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'I'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'l'; - } - if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) - { - return 'L'; - } - // anything else is treated as high-precision number - return 'H'; // LCOV_EXCL_LINE - } - - case value_t::number_unsigned: - { - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'i'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'U'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'I'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'l'; - } - if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) - { - return 'L'; - } - // anything else is treated as high-precision number - return 'H'; // LCOV_EXCL_LINE - } - - case value_t::number_float: - return get_ubjson_float_prefix(j.m_value.number_float); - - case value_t::string: - return 'S'; - - case value_t::array: // fallthrough - case value_t::binary: - return '['; - - case value_t::object: - return '{'; - - case value_t::discarded: - default: // discarded values - return 'N'; - } - } - - static constexpr CharType get_ubjson_float_prefix(float /*unused*/) - { - return 'd'; // float 32 - } - - static constexpr CharType get_ubjson_float_prefix(double /*unused*/) - { - return 'D'; // float 64 - } - - /////////////////////// - // Utility functions // - /////////////////////// - - /* - @brief write a number to output input - @param[in] n number of type @a NumberType - @tparam NumberType the type of the number - @tparam OutputIsLittleEndian Set to true if output data is - required to be little endian - - @note This function needs to respect the system's endianness, because bytes - in CBOR, MessagePack, and UBJSON are stored in network order (big - endian) and therefore need reordering on little endian systems. - */ - template - void write_number(const NumberType n) - { - // step 1: write number to array of length NumberType - std::array vec{}; - std::memcpy(vec.data(), &n, sizeof(NumberType)); - - // step 2: write array to output (with possible reordering) - if (is_little_endian != OutputIsLittleEndian) - { - // reverse byte order prior to conversion if necessary - std::reverse(vec.begin(), vec.end()); - } - - oa->write_characters(vec.data(), sizeof(NumberType)); - } - - void write_compact_float(const number_float_t n, detail::input_format_t format) - { -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && - static_cast(n) <= static_cast((std::numeric_limits::max)()) && - static_cast(static_cast(n)) == static_cast(n)) - { - oa->write_character(format == detail::input_format_t::cbor - ? get_cbor_float_prefix(static_cast(n)) - : get_msgpack_float_prefix(static_cast(n))); - write_number(static_cast(n)); - } - else - { - oa->write_character(format == detail::input_format_t::cbor - ? get_cbor_float_prefix(n) - : get_msgpack_float_prefix(n)); - write_number(n); - } -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - } - - public: - // The following to_char_type functions are implement the conversion - // between uint8_t and CharType. In case CharType is not unsigned, - // such a conversion is required to allow values greater than 128. - // See for a discussion. - template < typename C = CharType, - enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > - static constexpr CharType to_char_type(std::uint8_t x) noexcept - { - return *reinterpret_cast(&x); - } - - template < typename C = CharType, - enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > - static CharType to_char_type(std::uint8_t x) noexcept - { - static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); - static_assert(std::is_trivial::value, "CharType must be trivial"); - CharType result; - std::memcpy(&result, &x, sizeof(x)); - return result; - } - - template::value>* = nullptr> - static constexpr CharType to_char_type(std::uint8_t x) noexcept - { - return x; - } - - template < typename InputCharType, typename C = CharType, - enable_if_t < - std::is_signed::value && - std::is_signed::value && - std::is_same::type>::value - > * = nullptr > - static constexpr CharType to_char_type(InputCharType x) noexcept - { - return x; - } - - private: - /// whether we can assume little endianness - const bool is_little_endian = little_endianness(); - - /// the output - output_adapter_t oa = nullptr; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - - -#include // reverse, remove, fill, find, none_of -#include // array -#include // localeconv, lconv -#include // labs, isfinite, isnan, signbit -#include // size_t, ptrdiff_t -#include // uint8_t -#include // snprintf -#include // numeric_limits -#include // string, char_traits -#include // setfill, setw -#include // stringstream -#include // is_same -#include // move - -// #include - - -#include // array -#include // signbit, isfinite -#include // intN_t, uintN_t -#include // memcpy, memmove -#include // numeric_limits -#include // conditional - -// #include - - -namespace nlohmann -{ -namespace detail -{ - -/*! -@brief implements the Grisu2 algorithm for binary to decimal floating-point -conversion. - -This implementation is a slightly modified version of the reference -implementation which may be obtained from -http://florian.loitsch.com/publications (bench.tar.gz). - -The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. - -For a detailed description of the algorithm see: - -[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with - Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming - Language Design and Implementation, PLDI 2010 -[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", - Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language - Design and Implementation, PLDI 1996 -*/ -namespace dtoa_impl -{ - -template -Target reinterpret_bits(const Source source) -{ - static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); - - Target target; - std::memcpy(&target, &source, sizeof(Source)); - return target; -} - -struct diyfp // f * 2^e -{ - static constexpr int kPrecision = 64; // = q - - std::uint64_t f = 0; - int e = 0; - - constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} - - /*! - @brief returns x - y - @pre x.e == y.e and x.f >= y.f - */ - static diyfp sub(const diyfp& x, const diyfp& y) noexcept - { - JSON_ASSERT(x.e == y.e); - JSON_ASSERT(x.f >= y.f); - - return {x.f - y.f, x.e}; - } - - /*! - @brief returns x * y - @note The result is rounded. (Only the upper q bits are returned.) - */ - static diyfp mul(const diyfp& x, const diyfp& y) noexcept - { - static_assert(kPrecision == 64, "internal error"); - - // Computes: - // f = round((x.f * y.f) / 2^q) - // e = x.e + y.e + q - - // Emulate the 64-bit * 64-bit multiplication: - // - // p = u * v - // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) - // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) - // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) - // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) - // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) - // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) - // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) - // - // (Since Q might be larger than 2^32 - 1) - // - // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) - // - // (Q_hi + H does not overflow a 64-bit int) - // - // = p_lo + 2^64 p_hi - - const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; - const std::uint64_t u_hi = x.f >> 32u; - const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; - const std::uint64_t v_hi = y.f >> 32u; - - const std::uint64_t p0 = u_lo * v_lo; - const std::uint64_t p1 = u_lo * v_hi; - const std::uint64_t p2 = u_hi * v_lo; - const std::uint64_t p3 = u_hi * v_hi; - - const std::uint64_t p0_hi = p0 >> 32u; - const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; - const std::uint64_t p1_hi = p1 >> 32u; - const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; - const std::uint64_t p2_hi = p2 >> 32u; - - std::uint64_t Q = p0_hi + p1_lo + p2_lo; - - // The full product might now be computed as - // - // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) - // p_lo = p0_lo + (Q << 32) - // - // But in this particular case here, the full p_lo is not required. - // Effectively we only need to add the highest bit in p_lo to p_hi (and - // Q_hi + 1 does not overflow). - - Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up - - const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); - - return {h, x.e + y.e + 64}; - } - - /*! - @brief normalize x such that the significand is >= 2^(q-1) - @pre x.f != 0 - */ - static diyfp normalize(diyfp x) noexcept - { - JSON_ASSERT(x.f != 0); - - while ((x.f >> 63u) == 0) - { - x.f <<= 1u; - x.e--; - } - - return x; - } - - /*! - @brief normalize x such that the result has the exponent E - @pre e >= x.e and the upper e - x.e bits of x.f must be zero. - */ - static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept - { - const int delta = x.e - target_exponent; - - JSON_ASSERT(delta >= 0); - JSON_ASSERT(((x.f << delta) >> delta) == x.f); - - return {x.f << delta, target_exponent}; - } -}; - -struct boundaries -{ - diyfp w; - diyfp minus; - diyfp plus; -}; - -/*! -Compute the (normalized) diyfp representing the input number 'value' and its -boundaries. - -@pre value must be finite and positive -*/ -template -boundaries compute_boundaries(FloatType value) -{ - JSON_ASSERT(std::isfinite(value)); - JSON_ASSERT(value > 0); - - // Convert the IEEE representation into a diyfp. - // - // If v is denormal: - // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) - // If v is normalized: - // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) - - static_assert(std::numeric_limits::is_iec559, - "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); - - constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) - constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); - constexpr int kMinExp = 1 - kBias; - constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) - - using bits_type = typename std::conditional::type; - - const auto bits = static_cast(reinterpret_bits(value)); - const std::uint64_t E = bits >> (kPrecision - 1); - const std::uint64_t F = bits & (kHiddenBit - 1); - - const bool is_denormal = E == 0; - const diyfp v = is_denormal - ? diyfp(F, kMinExp) - : diyfp(F + kHiddenBit, static_cast(E) - kBias); - - // Compute the boundaries m- and m+ of the floating-point value - // v = f * 2^e. - // - // Determine v- and v+, the floating-point predecessor and successor if v, - // respectively. - // - // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) - // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) - // - // v+ = v + 2^e - // - // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ - // between m- and m+ round to v, regardless of how the input rounding - // algorithm breaks ties. - // - // ---+-------------+-------------+-------------+-------------+--- (A) - // v- m- v m+ v+ - // - // -----------------+------+------+-------------+-------------+--- (B) - // v- m- v m+ v+ - - const bool lower_boundary_is_closer = F == 0 && E > 1; - const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); - const diyfp m_minus = lower_boundary_is_closer - ? diyfp(4 * v.f - 1, v.e - 2) // (B) - : diyfp(2 * v.f - 1, v.e - 1); // (A) - - // Determine the normalized w+ = m+. - const diyfp w_plus = diyfp::normalize(m_plus); - - // Determine w- = m- such that e_(w-) = e_(w+). - const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); - - return {diyfp::normalize(v), w_minus, w_plus}; -} - -// Given normalized diyfp w, Grisu needs to find a (normalized) cached -// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies -// within a certain range [alpha, gamma] (Definition 3.2 from [1]) -// -// alpha <= e = e_c + e_w + q <= gamma -// -// or -// -// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q -// <= f_c * f_w * 2^gamma -// -// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies -// -// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma -// -// or -// -// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) -// -// The choice of (alpha,gamma) determines the size of the table and the form of -// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well -// in practice: -// -// The idea is to cut the number c * w = f * 2^e into two parts, which can be -// processed independently: An integral part p1, and a fractional part p2: -// -// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e -// = (f div 2^-e) + (f mod 2^-e) * 2^e -// = p1 + p2 * 2^e -// -// The conversion of p1 into decimal form requires a series of divisions and -// modulos by (a power of) 10. These operations are faster for 32-bit than for -// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be -// achieved by choosing -// -// -e >= 32 or e <= -32 := gamma -// -// In order to convert the fractional part -// -// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... -// -// into decimal form, the fraction is repeatedly multiplied by 10 and the digits -// d[-i] are extracted in order: -// -// (10 * p2) div 2^-e = d[-1] -// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... -// -// The multiplication by 10 must not overflow. It is sufficient to choose -// -// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. -// -// Since p2 = f mod 2^-e < 2^-e, -// -// -e <= 60 or e >= -60 := alpha - -constexpr int kAlpha = -60; -constexpr int kGamma = -32; - -struct cached_power // c = f * 2^e ~= 10^k -{ - std::uint64_t f; - int e; - int k; -}; - -/*! -For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached -power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c -satisfies (Definition 3.2 from [1]) - - alpha <= e_c + e + q <= gamma. -*/ -inline cached_power get_cached_power_for_binary_exponent(int e) -{ - // Now - // - // alpha <= e_c + e + q <= gamma (1) - // ==> f_c * 2^alpha <= c * 2^e * 2^q - // - // and since the c's are normalized, 2^(q-1) <= f_c, - // - // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) - // ==> 2^(alpha - e - 1) <= c - // - // If c were an exact power of ten, i.e. c = 10^k, one may determine k as - // - // k = ceil( log_10( 2^(alpha - e - 1) ) ) - // = ceil( (alpha - e - 1) * log_10(2) ) - // - // From the paper: - // "In theory the result of the procedure could be wrong since c is rounded, - // and the computation itself is approximated [...]. In practice, however, - // this simple function is sufficient." - // - // For IEEE double precision floating-point numbers converted into - // normalized diyfp's w = f * 2^e, with q = 64, - // - // e >= -1022 (min IEEE exponent) - // -52 (p - 1) - // -52 (p - 1, possibly normalize denormal IEEE numbers) - // -11 (normalize the diyfp) - // = -1137 - // - // and - // - // e <= +1023 (max IEEE exponent) - // -52 (p - 1) - // -11 (normalize the diyfp) - // = 960 - // - // This binary exponent range [-1137,960] results in a decimal exponent - // range [-307,324]. One does not need to store a cached power for each - // k in this range. For each such k it suffices to find a cached power - // such that the exponent of the product lies in [alpha,gamma]. - // This implies that the difference of the decimal exponents of adjacent - // table entries must be less than or equal to - // - // floor( (gamma - alpha) * log_10(2) ) = 8. - // - // (A smaller distance gamma-alpha would require a larger table.) - - // NB: - // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. - - constexpr int kCachedPowersMinDecExp = -300; - constexpr int kCachedPowersDecStep = 8; - - static constexpr std::array kCachedPowers = - { - { - { 0xAB70FE17C79AC6CA, -1060, -300 }, - { 0xFF77B1FCBEBCDC4F, -1034, -292 }, - { 0xBE5691EF416BD60C, -1007, -284 }, - { 0x8DD01FAD907FFC3C, -980, -276 }, - { 0xD3515C2831559A83, -954, -268 }, - { 0x9D71AC8FADA6C9B5, -927, -260 }, - { 0xEA9C227723EE8BCB, -901, -252 }, - { 0xAECC49914078536D, -874, -244 }, - { 0x823C12795DB6CE57, -847, -236 }, - { 0xC21094364DFB5637, -821, -228 }, - { 0x9096EA6F3848984F, -794, -220 }, - { 0xD77485CB25823AC7, -768, -212 }, - { 0xA086CFCD97BF97F4, -741, -204 }, - { 0xEF340A98172AACE5, -715, -196 }, - { 0xB23867FB2A35B28E, -688, -188 }, - { 0x84C8D4DFD2C63F3B, -661, -180 }, - { 0xC5DD44271AD3CDBA, -635, -172 }, - { 0x936B9FCEBB25C996, -608, -164 }, - { 0xDBAC6C247D62A584, -582, -156 }, - { 0xA3AB66580D5FDAF6, -555, -148 }, - { 0xF3E2F893DEC3F126, -529, -140 }, - { 0xB5B5ADA8AAFF80B8, -502, -132 }, - { 0x87625F056C7C4A8B, -475, -124 }, - { 0xC9BCFF6034C13053, -449, -116 }, - { 0x964E858C91BA2655, -422, -108 }, - { 0xDFF9772470297EBD, -396, -100 }, - { 0xA6DFBD9FB8E5B88F, -369, -92 }, - { 0xF8A95FCF88747D94, -343, -84 }, - { 0xB94470938FA89BCF, -316, -76 }, - { 0x8A08F0F8BF0F156B, -289, -68 }, - { 0xCDB02555653131B6, -263, -60 }, - { 0x993FE2C6D07B7FAC, -236, -52 }, - { 0xE45C10C42A2B3B06, -210, -44 }, - { 0xAA242499697392D3, -183, -36 }, - { 0xFD87B5F28300CA0E, -157, -28 }, - { 0xBCE5086492111AEB, -130, -20 }, - { 0x8CBCCC096F5088CC, -103, -12 }, - { 0xD1B71758E219652C, -77, -4 }, - { 0x9C40000000000000, -50, 4 }, - { 0xE8D4A51000000000, -24, 12 }, - { 0xAD78EBC5AC620000, 3, 20 }, - { 0x813F3978F8940984, 30, 28 }, - { 0xC097CE7BC90715B3, 56, 36 }, - { 0x8F7E32CE7BEA5C70, 83, 44 }, - { 0xD5D238A4ABE98068, 109, 52 }, - { 0x9F4F2726179A2245, 136, 60 }, - { 0xED63A231D4C4FB27, 162, 68 }, - { 0xB0DE65388CC8ADA8, 189, 76 }, - { 0x83C7088E1AAB65DB, 216, 84 }, - { 0xC45D1DF942711D9A, 242, 92 }, - { 0x924D692CA61BE758, 269, 100 }, - { 0xDA01EE641A708DEA, 295, 108 }, - { 0xA26DA3999AEF774A, 322, 116 }, - { 0xF209787BB47D6B85, 348, 124 }, - { 0xB454E4A179DD1877, 375, 132 }, - { 0x865B86925B9BC5C2, 402, 140 }, - { 0xC83553C5C8965D3D, 428, 148 }, - { 0x952AB45CFA97A0B3, 455, 156 }, - { 0xDE469FBD99A05FE3, 481, 164 }, - { 0xA59BC234DB398C25, 508, 172 }, - { 0xF6C69A72A3989F5C, 534, 180 }, - { 0xB7DCBF5354E9BECE, 561, 188 }, - { 0x88FCF317F22241E2, 588, 196 }, - { 0xCC20CE9BD35C78A5, 614, 204 }, - { 0x98165AF37B2153DF, 641, 212 }, - { 0xE2A0B5DC971F303A, 667, 220 }, - { 0xA8D9D1535CE3B396, 694, 228 }, - { 0xFB9B7CD9A4A7443C, 720, 236 }, - { 0xBB764C4CA7A44410, 747, 244 }, - { 0x8BAB8EEFB6409C1A, 774, 252 }, - { 0xD01FEF10A657842C, 800, 260 }, - { 0x9B10A4E5E9913129, 827, 268 }, - { 0xE7109BFBA19C0C9D, 853, 276 }, - { 0xAC2820D9623BF429, 880, 284 }, - { 0x80444B5E7AA7CF85, 907, 292 }, - { 0xBF21E44003ACDD2D, 933, 300 }, - { 0x8E679C2F5E44FF8F, 960, 308 }, - { 0xD433179D9C8CB841, 986, 316 }, - { 0x9E19DB92B4E31BA9, 1013, 324 }, - } - }; - - // This computation gives exactly the same results for k as - // k = ceil((kAlpha - e - 1) * 0.30102999566398114) - // for |e| <= 1500, but doesn't require floating-point operations. - // NB: log_10(2) ~= 78913 / 2^18 - JSON_ASSERT(e >= -1500); - JSON_ASSERT(e <= 1500); - const int f = kAlpha - e - 1; - const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); - - const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; - JSON_ASSERT(index >= 0); - JSON_ASSERT(static_cast(index) < kCachedPowers.size()); - - const cached_power cached = kCachedPowers[static_cast(index)]; - JSON_ASSERT(kAlpha <= cached.e + e + 64); - JSON_ASSERT(kGamma >= cached.e + e + 64); - - return cached; -} - -/*! -For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. -For n == 0, returns 1 and sets pow10 := 1. -*/ -inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) -{ - // LCOV_EXCL_START - if (n >= 1000000000) - { - pow10 = 1000000000; - return 10; - } - // LCOV_EXCL_STOP - if (n >= 100000000) - { - pow10 = 100000000; - return 9; - } - if (n >= 10000000) - { - pow10 = 10000000; - return 8; - } - if (n >= 1000000) - { - pow10 = 1000000; - return 7; - } - if (n >= 100000) - { - pow10 = 100000; - return 6; - } - if (n >= 10000) - { - pow10 = 10000; - return 5; - } - if (n >= 1000) - { - pow10 = 1000; - return 4; - } - if (n >= 100) - { - pow10 = 100; - return 3; - } - if (n >= 10) - { - pow10 = 10; - return 2; - } - - pow10 = 1; - return 1; -} - -inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, - std::uint64_t rest, std::uint64_t ten_k) -{ - JSON_ASSERT(len >= 1); - JSON_ASSERT(dist <= delta); - JSON_ASSERT(rest <= delta); - JSON_ASSERT(ten_k > 0); - - // <--------------------------- delta ----> - // <---- dist ---------> - // --------------[------------------+-------------------]-------------- - // M- w M+ - // - // ten_k - // <------> - // <---- rest ----> - // --------------[------------------+----+--------------]-------------- - // w V - // = buf * 10^k - // - // ten_k represents a unit-in-the-last-place in the decimal representation - // stored in buf. - // Decrement buf by ten_k while this takes buf closer to w. - - // The tests are written in this order to avoid overflow in unsigned - // integer arithmetic. - - while (rest < dist - && delta - rest >= ten_k - && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) - { - JSON_ASSERT(buf[len - 1] != '0'); - buf[len - 1]--; - rest += ten_k; - } -} - -/*! -Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. -M- and M+ must be normalized and share the same exponent -60 <= e <= -32. -*/ -inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, - diyfp M_minus, diyfp w, diyfp M_plus) -{ - static_assert(kAlpha >= -60, "internal error"); - static_assert(kGamma <= -32, "internal error"); - - // Generates the digits (and the exponent) of a decimal floating-point - // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's - // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. - // - // <--------------------------- delta ----> - // <---- dist ---------> - // --------------[------------------+-------------------]-------------- - // M- w M+ - // - // Grisu2 generates the digits of M+ from left to right and stops as soon as - // V is in [M-,M+]. - - JSON_ASSERT(M_plus.e >= kAlpha); - JSON_ASSERT(M_plus.e <= kGamma); - - std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) - std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) - - // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): - // - // M+ = f * 2^e - // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e - // = ((p1 ) * 2^-e + (p2 )) * 2^e - // = p1 + p2 * 2^e - - const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); - - auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) - std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e - - // 1) - // - // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] - - JSON_ASSERT(p1 > 0); - - std::uint32_t pow10{}; - const int k = find_largest_pow10(p1, pow10); - - // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) - // - // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) - // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) - // - // M+ = p1 + p2 * 2^e - // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e - // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e - // = d[k-1] * 10^(k-1) + ( rest) * 2^e - // - // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) - // - // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] - // - // but stop as soon as - // - // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e - - int n = k; - while (n > 0) - { - // Invariants: - // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) - // pow10 = 10^(n-1) <= p1 < 10^n - // - const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) - const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) - // - // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e - // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) - // - JSON_ASSERT(d <= 9); - buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d - // - // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) - // - p1 = r; - n--; - // - // M+ = buffer * 10^n + (p1 + p2 * 2^e) - // pow10 = 10^n - // - - // Now check if enough digits have been generated. - // Compute - // - // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e - // - // Note: - // Since rest and delta share the same exponent e, it suffices to - // compare the significands. - const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; - if (rest <= delta) - { - // V = buffer * 10^n, with M- <= V <= M+. - - decimal_exponent += n; - - // We may now just stop. But instead look if the buffer could be - // decremented to bring V closer to w. - // - // pow10 = 10^n is now 1 ulp in the decimal representation V. - // The rounding procedure works with diyfp's with an implicit - // exponent of e. - // - // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e - // - const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; - grisu2_round(buffer, length, dist, delta, rest, ten_n); - - return; - } - - pow10 /= 10; - // - // pow10 = 10^(n-1) <= p1 < 10^n - // Invariants restored. - } - - // 2) - // - // The digits of the integral part have been generated: - // - // M+ = d[k-1]...d[1]d[0] + p2 * 2^e - // = buffer + p2 * 2^e - // - // Now generate the digits of the fractional part p2 * 2^e. - // - // Note: - // No decimal point is generated: the exponent is adjusted instead. - // - // p2 actually represents the fraction - // - // p2 * 2^e - // = p2 / 2^-e - // = d[-1] / 10^1 + d[-2] / 10^2 + ... - // - // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) - // - // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m - // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) - // - // using - // - // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) - // = ( d) * 2^-e + ( r) - // - // or - // 10^m * p2 * 2^e = d + r * 2^e - // - // i.e. - // - // M+ = buffer + p2 * 2^e - // = buffer + 10^-m * (d + r * 2^e) - // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e - // - // and stop as soon as 10^-m * r * 2^e <= delta * 2^e - - JSON_ASSERT(p2 > delta); - - int m = 0; - for (;;) - { - // Invariant: - // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e - // = buffer * 10^-m + 10^-m * (p2 ) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e - // - JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); - p2 *= 10; - const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e - const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e - // - // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e - // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) - // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e - // - JSON_ASSERT(d <= 9); - buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d - // - // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e - // - p2 = r; - m++; - // - // M+ = buffer * 10^-m + 10^-m * p2 * 2^e - // Invariant restored. - - // Check if enough digits have been generated. - // - // 10^-m * p2 * 2^e <= delta * 2^e - // p2 * 2^e <= 10^m * delta * 2^e - // p2 <= 10^m * delta - delta *= 10; - dist *= 10; - if (p2 <= delta) - { - break; - } - } - - // V = buffer * 10^-m, with M- <= V <= M+. - - decimal_exponent -= m; - - // 1 ulp in the decimal representation is now 10^-m. - // Since delta and dist are now scaled by 10^m, we need to do the - // same with ulp in order to keep the units in sync. - // - // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e - // - const std::uint64_t ten_m = one.f; - grisu2_round(buffer, length, dist, delta, p2, ten_m); - - // By construction this algorithm generates the shortest possible decimal - // number (Loitsch, Theorem 6.2) which rounds back to w. - // For an input number of precision p, at least - // - // N = 1 + ceil(p * log_10(2)) - // - // decimal digits are sufficient to identify all binary floating-point - // numbers (Matula, "In-and-Out conversions"). - // This implies that the algorithm does not produce more than N decimal - // digits. - // - // N = 17 for p = 53 (IEEE double precision) - // N = 9 for p = 24 (IEEE single precision) -} - -/*! -v = buf * 10^decimal_exponent -len is the length of the buffer (number of decimal digits) -The buffer must be large enough, i.e. >= max_digits10. -*/ -JSON_HEDLEY_NON_NULL(1) -inline void grisu2(char* buf, int& len, int& decimal_exponent, - diyfp m_minus, diyfp v, diyfp m_plus) -{ - JSON_ASSERT(m_plus.e == m_minus.e); - JSON_ASSERT(m_plus.e == v.e); - - // --------(-----------------------+-----------------------)-------- (A) - // m- v m+ - // - // --------------------(-----------+-----------------------)-------- (B) - // m- v m+ - // - // First scale v (and m- and m+) such that the exponent is in the range - // [alpha, gamma]. - - const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); - - const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k - - // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] - const diyfp w = diyfp::mul(v, c_minus_k); - const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); - const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); - - // ----(---+---)---------------(---+---)---------------(---+---)---- - // w- w w+ - // = c*m- = c*v = c*m+ - // - // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and - // w+ are now off by a small amount. - // In fact: - // - // w - v * 10^k < 1 ulp - // - // To account for this inaccuracy, add resp. subtract 1 ulp. - // - // --------+---[---------------(---+---)---------------]---+-------- - // w- M- w M+ w+ - // - // Now any number in [M-, M+] (bounds included) will round to w when input, - // regardless of how the input rounding algorithm breaks ties. - // - // And digit_gen generates the shortest possible such number in [M-, M+]. - // Note that this does not mean that Grisu2 always generates the shortest - // possible number in the interval (m-, m+). - const diyfp M_minus(w_minus.f + 1, w_minus.e); - const diyfp M_plus (w_plus.f - 1, w_plus.e ); - - decimal_exponent = -cached.k; // = -(-k) = k - - grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); -} - -/*! -v = buf * 10^decimal_exponent -len is the length of the buffer (number of decimal digits) -The buffer must be large enough, i.e. >= max_digits10. -*/ -template -JSON_HEDLEY_NON_NULL(1) -void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) -{ - static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, - "internal error: not enough precision"); - - JSON_ASSERT(std::isfinite(value)); - JSON_ASSERT(value > 0); - - // If the neighbors (and boundaries) of 'value' are always computed for double-precision - // numbers, all float's can be recovered using strtod (and strtof). However, the resulting - // decimal representations are not exactly "short". - // - // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) - // says "value is converted to a string as if by std::sprintf in the default ("C") locale" - // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' - // does. - // On the other hand, the documentation for 'std::to_chars' requires that "parsing the - // representation using the corresponding std::from_chars function recovers value exactly". That - // indicates that single precision floating-point numbers should be recovered using - // 'std::strtof'. - // - // NB: If the neighbors are computed for single-precision numbers, there is a single float - // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision - // value is off by 1 ulp. -#if 0 - const boundaries w = compute_boundaries(static_cast(value)); -#else - const boundaries w = compute_boundaries(value); -#endif - - grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); -} - -/*! -@brief appends a decimal representation of e to buf -@return a pointer to the element following the exponent. -@pre -1000 < e < 1000 -*/ -JSON_HEDLEY_NON_NULL(1) -JSON_HEDLEY_RETURNS_NON_NULL -inline char* append_exponent(char* buf, int e) -{ - JSON_ASSERT(e > -1000); - JSON_ASSERT(e < 1000); - - if (e < 0) - { - e = -e; - *buf++ = '-'; - } - else - { - *buf++ = '+'; - } - - auto k = static_cast(e); - if (k < 10) - { - // Always print at least two digits in the exponent. - // This is for compatibility with printf("%g"). - *buf++ = '0'; - *buf++ = static_cast('0' + k); - } - else if (k < 100) - { - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - else - { - *buf++ = static_cast('0' + k / 100); - k %= 100; - *buf++ = static_cast('0' + k / 10); - k %= 10; - *buf++ = static_cast('0' + k); - } - - return buf; -} - -/*! -@brief prettify v = buf * 10^decimal_exponent - -If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point -notation. Otherwise it will be printed in exponential notation. - -@pre min_exp < 0 -@pre max_exp > 0 -*/ -JSON_HEDLEY_NON_NULL(1) -JSON_HEDLEY_RETURNS_NON_NULL -inline char* format_buffer(char* buf, int len, int decimal_exponent, - int min_exp, int max_exp) -{ - JSON_ASSERT(min_exp < 0); - JSON_ASSERT(max_exp > 0); - - const int k = len; - const int n = len + decimal_exponent; - - // v = buf * 10^(n-k) - // k is the length of the buffer (number of decimal digits) - // n is the position of the decimal point relative to the start of the buffer. - - if (k <= n && n <= max_exp) - { - // digits[000] - // len <= max_exp + 2 - - std::memset(buf + k, '0', static_cast(n) - static_cast(k)); - // Make it look like a floating-point number (#362, #378) - buf[n + 0] = '.'; - buf[n + 1] = '0'; - return buf + (static_cast(n) + 2); - } - - if (0 < n && n <= max_exp) - { - // dig.its - // len <= max_digits10 + 1 - - JSON_ASSERT(k > n); - - std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); - buf[n] = '.'; - return buf + (static_cast(k) + 1U); - } - - if (min_exp < n && n <= 0) - { - // 0.[000]digits - // len <= 2 + (-min_exp - 1) + max_digits10 - - std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); - buf[0] = '0'; - buf[1] = '.'; - std::memset(buf + 2, '0', static_cast(-n)); - return buf + (2U + static_cast(-n) + static_cast(k)); - } - - if (k == 1) - { - // dE+123 - // len <= 1 + 5 - - buf += 1; - } - else - { - // d.igitsE+123 - // len <= max_digits10 + 1 + 5 - - std::memmove(buf + 2, buf + 1, static_cast(k) - 1); - buf[1] = '.'; - buf += 1 + static_cast(k); - } - - *buf++ = 'e'; - return append_exponent(buf, n - 1); -} - -} // namespace dtoa_impl - -/*! -@brief generates a decimal representation of the floating-point number value in [first, last). - -The format of the resulting decimal representation is similar to printf's %g -format. Returns an iterator pointing past-the-end of the decimal representation. - -@note The input number must be finite, i.e. NaN's and Inf's are not supported. -@note The buffer must be large enough. -@note The result is NOT null-terminated. -*/ -template -JSON_HEDLEY_NON_NULL(1, 2) -JSON_HEDLEY_RETURNS_NON_NULL -char* to_chars(char* first, const char* last, FloatType value) -{ - static_cast(last); // maybe unused - fix warning - JSON_ASSERT(std::isfinite(value)); - - // Use signbit(value) instead of (value < 0) since signbit works for -0. - if (std::signbit(value)) - { - value = -value; - *first++ = '-'; - } - -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - if (value == 0) // +-0 - { - *first++ = '0'; - // Make it look like a floating-point number (#362, #378) - *first++ = '.'; - *first++ = '0'; - return first; - } -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - - JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); - - // Compute v = buffer * 10^decimal_exponent. - // The decimal digits are stored in the buffer, which needs to be interpreted - // as an unsigned decimal integer. - // len is the length of the buffer, i.e. the number of decimal digits. - int len = 0; - int decimal_exponent = 0; - dtoa_impl::grisu2(first, len, decimal_exponent, value); - - JSON_ASSERT(len <= std::numeric_limits::max_digits10); - - // Format the buffer like printf("%.*g", prec, value) - constexpr int kMinExp = -4; - // Use digits10 here to increase compatibility with version 2. - constexpr int kMaxExp = std::numeric_limits::digits10; - - JSON_ASSERT(last - first >= kMaxExp + 2); - JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); - JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); - - return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); -} - -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - -// #include - -// #include - -// #include - - -namespace nlohmann -{ -namespace detail -{ -/////////////////// -// serialization // -/////////////////// - -/// how to treat decoding errors -enum class error_handler_t -{ - strict, ///< throw a type_error exception in case of invalid UTF-8 - replace, ///< replace invalid UTF-8 sequences with U+FFFD - ignore ///< ignore invalid UTF-8 sequences -}; - -template -class serializer -{ - using string_t = typename BasicJsonType::string_t; - using number_float_t = typename BasicJsonType::number_float_t; - using number_integer_t = typename BasicJsonType::number_integer_t; - using number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using binary_char_t = typename BasicJsonType::binary_t::value_type; - static constexpr std::uint8_t UTF8_ACCEPT = 0; - static constexpr std::uint8_t UTF8_REJECT = 1; - - public: - /*! - @param[in] s output stream to serialize to - @param[in] ichar indentation character to use - @param[in] error_handler_ how to react on decoding errors - */ - serializer(output_adapter_t s, const char ichar, - error_handler_t error_handler_ = error_handler_t::strict) - : o(std::move(s)) - , loc(std::localeconv()) - , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) - , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) - , indent_char(ichar) - , indent_string(512, indent_char) - , error_handler(error_handler_) - {} - - // delete because of pointer members - serializer(const serializer&) = delete; - serializer& operator=(const serializer&) = delete; - serializer(serializer&&) = delete; - serializer& operator=(serializer&&) = delete; - ~serializer() = default; - - /*! - @brief internal implementation of the serialization function - - This function is called by the public member function dump and organizes - the serialization internally. The indentation level is propagated as - additional parameter. In case of arrays and objects, the function is - called recursively. - - - strings and object keys are escaped using `escape_string()` - - integer numbers are converted implicitly via `operator<<` - - floating-point numbers are converted to a string using `"%g"` format - - binary values are serialized as objects containing the subtype and the - byte array - - @param[in] val value to serialize - @param[in] pretty_print whether the output shall be pretty-printed - @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters - in the output are escaped with `\uXXXX` sequences, and the result consists - of ASCII characters only. - @param[in] indent_step the indent level - @param[in] current_indent the current indent level (only used internally) - */ - void dump(const BasicJsonType& val, - const bool pretty_print, - const bool ensure_ascii, - const unsigned int indent_step, - const unsigned int current_indent = 0) - { - switch (val.m_type) - { - case value_t::object: - { - if (val.m_value.object->empty()) - { - o->write_characters("{}", 2); - return; - } - - if (pretty_print) - { - o->write_characters("{\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - // first n-1 elements - auto i = val.m_value.object->cbegin(); - for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) - { - o->write_characters(indent_string.c_str(), new_indent); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\": ", 3); - dump(i->second, true, ensure_ascii, indent_step, new_indent); - o->write_characters(",\n", 2); - } - - // last element - JSON_ASSERT(i != val.m_value.object->cend()); - JSON_ASSERT(std::next(i) == val.m_value.object->cend()); - o->write_characters(indent_string.c_str(), new_indent); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\": ", 3); - dump(i->second, true, ensure_ascii, indent_step, new_indent); - - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character('}'); - } - else - { - o->write_character('{'); - - // first n-1 elements - auto i = val.m_value.object->cbegin(); - for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) - { - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\":", 2); - dump(i->second, false, ensure_ascii, indent_step, current_indent); - o->write_character(','); - } - - // last element - JSON_ASSERT(i != val.m_value.object->cend()); - JSON_ASSERT(std::next(i) == val.m_value.object->cend()); - o->write_character('\"'); - dump_escaped(i->first, ensure_ascii); - o->write_characters("\":", 2); - dump(i->second, false, ensure_ascii, indent_step, current_indent); - - o->write_character('}'); - } - - return; - } - - case value_t::array: - { - if (val.m_value.array->empty()) - { - o->write_characters("[]", 2); - return; - } - - if (pretty_print) - { - o->write_characters("[\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - // first n-1 elements - for (auto i = val.m_value.array->cbegin(); - i != val.m_value.array->cend() - 1; ++i) - { - o->write_characters(indent_string.c_str(), new_indent); - dump(*i, true, ensure_ascii, indent_step, new_indent); - o->write_characters(",\n", 2); - } - - // last element - JSON_ASSERT(!val.m_value.array->empty()); - o->write_characters(indent_string.c_str(), new_indent); - dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); - - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character(']'); - } - else - { - o->write_character('['); - - // first n-1 elements - for (auto i = val.m_value.array->cbegin(); - i != val.m_value.array->cend() - 1; ++i) - { - dump(*i, false, ensure_ascii, indent_step, current_indent); - o->write_character(','); - } - - // last element - JSON_ASSERT(!val.m_value.array->empty()); - dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); - - o->write_character(']'); - } - - return; - } - - case value_t::string: - { - o->write_character('\"'); - dump_escaped(*val.m_value.string, ensure_ascii); - o->write_character('\"'); - return; - } - - case value_t::binary: - { - if (pretty_print) - { - o->write_characters("{\n", 2); - - // variable to hold indentation for recursive calls - const auto new_indent = current_indent + indent_step; - if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) - { - indent_string.resize(indent_string.size() * 2, ' '); - } - - o->write_characters(indent_string.c_str(), new_indent); - - o->write_characters("\"bytes\": [", 10); - - if (!val.m_value.binary->empty()) - { - for (auto i = val.m_value.binary->cbegin(); - i != val.m_value.binary->cend() - 1; ++i) - { - dump_integer(*i); - o->write_characters(", ", 2); - } - dump_integer(val.m_value.binary->back()); - } - - o->write_characters("],\n", 3); - o->write_characters(indent_string.c_str(), new_indent); - - o->write_characters("\"subtype\": ", 11); - if (val.m_value.binary->has_subtype()) - { - dump_integer(val.m_value.binary->subtype()); - } - else - { - o->write_characters("null", 4); - } - o->write_character('\n'); - o->write_characters(indent_string.c_str(), current_indent); - o->write_character('}'); - } - else - { - o->write_characters("{\"bytes\":[", 10); - - if (!val.m_value.binary->empty()) - { - for (auto i = val.m_value.binary->cbegin(); - i != val.m_value.binary->cend() - 1; ++i) - { - dump_integer(*i); - o->write_character(','); - } - dump_integer(val.m_value.binary->back()); - } - - o->write_characters("],\"subtype\":", 12); - if (val.m_value.binary->has_subtype()) - { - dump_integer(val.m_value.binary->subtype()); - o->write_character('}'); - } - else - { - o->write_characters("null}", 5); - } - } - return; - } - - case value_t::boolean: - { - if (val.m_value.boolean) - { - o->write_characters("true", 4); - } - else - { - o->write_characters("false", 5); - } - return; - } - - case value_t::number_integer: - { - dump_integer(val.m_value.number_integer); - return; - } - - case value_t::number_unsigned: - { - dump_integer(val.m_value.number_unsigned); - return; - } - - case value_t::number_float: - { - dump_float(val.m_value.number_float); - return; - } - - case value_t::discarded: - { - o->write_characters("", 11); - return; - } - - case value_t::null: - { - o->write_characters("null", 4); - return; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - } - - JSON_PRIVATE_UNLESS_TESTED: - /*! - @brief dump escaped string - - Escape a string by replacing certain special characters by a sequence of an - escape character (backslash) and another character and other control - characters by a sequence of "\u" followed by a four-digit hex - representation. The escaped string is written to output stream @a o. - - @param[in] s the string to escape - @param[in] ensure_ascii whether to escape non-ASCII characters with - \uXXXX sequences - - @complexity Linear in the length of string @a s. - */ - void dump_escaped(const string_t& s, const bool ensure_ascii) - { - std::uint32_t codepoint{}; - std::uint8_t state = UTF8_ACCEPT; - std::size_t bytes = 0; // number of bytes written to string_buffer - - // number of bytes written at the point of the last valid byte - std::size_t bytes_after_last_accept = 0; - std::size_t undumped_chars = 0; - - for (std::size_t i = 0; i < s.size(); ++i) - { - const auto byte = static_cast(s[i]); - - switch (decode(state, codepoint, byte)) - { - case UTF8_ACCEPT: // decode found a new code point - { - switch (codepoint) - { - case 0x08: // backspace - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'b'; - break; - } - - case 0x09: // horizontal tab - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 't'; - break; - } - - case 0x0A: // newline - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'n'; - break; - } - - case 0x0C: // formfeed - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'f'; - break; - } - - case 0x0D: // carriage return - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'r'; - break; - } - - case 0x22: // quotation mark - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = '\"'; - break; - } - - case 0x5C: // reverse solidus - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = '\\'; - break; - } - - default: - { - // escape control characters (0x00..0x1F) or, if - // ensure_ascii parameter is used, non-ASCII characters - if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) - { - if (codepoint <= 0xFFFF) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - static_cast((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", - static_cast(codepoint))); - bytes += 6; - } - else - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - static_cast((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", - static_cast(0xD7C0u + (codepoint >> 10u)), - static_cast(0xDC00u + (codepoint & 0x3FFu)))); - bytes += 12; - } - } - else - { - // copy byte to buffer (all previous bytes - // been copied have in default case above) - string_buffer[bytes++] = s[i]; - } - break; - } - } - - // write buffer and reset index; there must be 13 bytes - // left, as this is the maximal number of bytes to be - // written ("\uxxxx\uxxxx\0") for one code point - if (string_buffer.size() - bytes < 13) - { - o->write_characters(string_buffer.data(), bytes); - bytes = 0; - } - - // remember the byte position of this accept - bytes_after_last_accept = bytes; - undumped_chars = 0; - break; - } - - case UTF8_REJECT: // decode found invalid UTF-8 byte - { - switch (error_handler) - { - case error_handler_t::strict: - { - std::stringstream ss; - ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0); - JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType())); - } - - case error_handler_t::ignore: - case error_handler_t::replace: - { - // in case we saw this character the first time, we - // would like to read it again, because the byte - // may be OK for itself, but just not OK for the - // previous sequence - if (undumped_chars > 0) - { - --i; - } - - // reset length buffer to the last accepted index; - // thus removing/ignoring the invalid characters - bytes = bytes_after_last_accept; - - if (error_handler == error_handler_t::replace) - { - // add a replacement character - if (ensure_ascii) - { - string_buffer[bytes++] = '\\'; - string_buffer[bytes++] = 'u'; - string_buffer[bytes++] = 'f'; - string_buffer[bytes++] = 'f'; - string_buffer[bytes++] = 'f'; - string_buffer[bytes++] = 'd'; - } - else - { - string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); - string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); - string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); - } - - // write buffer and reset index; there must be 13 bytes - // left, as this is the maximal number of bytes to be - // written ("\uxxxx\uxxxx\0") for one code point - if (string_buffer.size() - bytes < 13) - { - o->write_characters(string_buffer.data(), bytes); - bytes = 0; - } - - bytes_after_last_accept = bytes; - } - - undumped_chars = 0; - - // continue processing the string - state = UTF8_ACCEPT; - break; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - break; - } - - default: // decode found yet incomplete multi-byte code point - { - if (!ensure_ascii) - { - // code point will not be escaped - copy byte to buffer - string_buffer[bytes++] = s[i]; - } - ++undumped_chars; - break; - } - } - } - - // we finished processing the string - if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) - { - // write buffer - if (bytes > 0) - { - o->write_characters(string_buffer.data(), bytes); - } - } - else - { - // we finish reading, but do not accept: string was incomplete - switch (error_handler) - { - case error_handler_t::strict: - { - std::stringstream ss; - ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast(s.back()) | 0); - JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType())); - } - - case error_handler_t::ignore: - { - // write all accepted bytes - o->write_characters(string_buffer.data(), bytes_after_last_accept); - break; - } - - case error_handler_t::replace: - { - // write all accepted bytes - o->write_characters(string_buffer.data(), bytes_after_last_accept); - // add a replacement character - if (ensure_ascii) - { - o->write_characters("\\ufffd", 6); - } - else - { - o->write_characters("\xEF\xBF\xBD", 3); - } - break; - } - - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - } - } - - private: - /*! - @brief count digits - - Count the number of decimal (base 10) digits for an input unsigned integer. - - @param[in] x unsigned integer number to count its digits - @return number of decimal digits - */ - inline unsigned int count_digits(number_unsigned_t x) noexcept - { - unsigned int n_digits = 1; - for (;;) - { - if (x < 10) - { - return n_digits; - } - if (x < 100) - { - return n_digits + 1; - } - if (x < 1000) - { - return n_digits + 2; - } - if (x < 10000) - { - return n_digits + 3; - } - x = x / 10000u; - n_digits += 4; - } - } - - // templates to avoid warnings about useless casts - template ::value, int> = 0> - bool is_negative_number(NumberType x) - { - return x < 0; - } - - template < typename NumberType, enable_if_t ::value, int > = 0 > - bool is_negative_number(NumberType /*unused*/) - { - return false; - } - - /*! - @brief dump an integer - - Dump a given integer to output stream @a o. Works internally with - @a number_buffer. - - @param[in] x integer number (signed or unsigned) to dump - @tparam NumberType either @a number_integer_t or @a number_unsigned_t - */ - template < typename NumberType, detail::enable_if_t < - std::is_integral::value || - std::is_same::value || - std::is_same::value || - std::is_same::value, - int > = 0 > - void dump_integer(NumberType x) - { - static constexpr std::array, 100> digits_to_99 - { - { - {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, - {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, - {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, - {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, - {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, - {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, - {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, - {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, - {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, - {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, - } - }; - - // special case for "0" - if (x == 0) - { - o->write_character('0'); - return; - } - - // use a pointer to fill the buffer - auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) - - number_unsigned_t abs_value; - - unsigned int n_chars{}; - - if (is_negative_number(x)) - { - *buffer_ptr = '-'; - abs_value = remove_sign(static_cast(x)); - - // account one more byte for the minus sign - n_chars = 1 + count_digits(abs_value); - } - else - { - abs_value = static_cast(x); - n_chars = count_digits(abs_value); - } - - // spare 1 byte for '\0' - JSON_ASSERT(n_chars < number_buffer.size() - 1); - - // jump to the end to generate the string from backward, - // so we later avoid reversing the result - buffer_ptr += n_chars; - - // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu - // See: https://www.youtube.com/watch?v=o4-CwDo2zpg - while (abs_value >= 100) - { - const auto digits_index = static_cast((abs_value % 100)); - abs_value /= 100; - *(--buffer_ptr) = digits_to_99[digits_index][1]; - *(--buffer_ptr) = digits_to_99[digits_index][0]; - } - - if (abs_value >= 10) - { - const auto digits_index = static_cast(abs_value); - *(--buffer_ptr) = digits_to_99[digits_index][1]; - *(--buffer_ptr) = digits_to_99[digits_index][0]; - } - else - { - *(--buffer_ptr) = static_cast('0' + abs_value); - } - - o->write_characters(number_buffer.data(), n_chars); - } - - /*! - @brief dump a floating-point number - - Dump a given floating-point number to output stream @a o. Works internally - with @a number_buffer. - - @param[in] x floating-point number to dump - */ - void dump_float(number_float_t x) - { - // NaN / inf - if (!std::isfinite(x)) - { - o->write_characters("null", 4); - return; - } - - // If number_float_t is an IEEE-754 single or double precision number, - // use the Grisu2 algorithm to produce short numbers which are - // guaranteed to round-trip, using strtof and strtod, resp. - // - // NB: The test below works if == . - static constexpr bool is_ieee_single_or_double - = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || - (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); - - dump_float(x, std::integral_constant()); - } - - void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) - { - auto* begin = number_buffer.data(); - auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); - - o->write_characters(begin, static_cast(end - begin)); - } - - void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) - { - // get number of digits for a float -> text -> float round-trip - static constexpr auto d = std::numeric_limits::max_digits10; - - // the actual conversion - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) - std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); - - // negative value indicates an error - JSON_ASSERT(len > 0); - // check if buffer was large enough - JSON_ASSERT(static_cast(len) < number_buffer.size()); - - // erase thousands separator - if (thousands_sep != '\0') - { - // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 - const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); - std::fill(end, number_buffer.end(), '\0'); - JSON_ASSERT((end - number_buffer.begin()) <= len); - len = (end - number_buffer.begin()); - } - - // convert decimal point to '.' - if (decimal_point != '\0' && decimal_point != '.') - { - // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081 - const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); - if (dec_pos != number_buffer.end()) - { - *dec_pos = '.'; - } - } - - o->write_characters(number_buffer.data(), static_cast(len)); - - // determine if we need to append ".0" - const bool value_is_int_like = - std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, - [](char c) - { - return c == '.' || c == 'e'; - }); - - if (value_is_int_like) - { - o->write_characters(".0", 2); - } - } - - /*! - @brief check whether a string is UTF-8 encoded - - The function checks each byte of a string whether it is UTF-8 encoded. The - result of the check is stored in the @a state parameter. The function must - be called initially with state 0 (accept). State 1 means the string must - be rejected, because the current byte is not allowed. If the string is - completely processed, but the state is non-zero, the string ended - prematurely; that is, the last byte indicated more bytes should have - followed. - - @param[in,out] state the state of the decoding - @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) - @param[in] byte next byte to decode - @return new state - - @note The function has been edited: a std::array is used. - - @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann - @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ - */ - static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept - { - static const std::array utf8d = - { - { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F - 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF - 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF - 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF - 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF - 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 - 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 - 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 - 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 - } - }; - - JSON_ASSERT(byte < utf8d.size()); - const std::uint8_t type = utf8d[byte]; - - codep = (state != UTF8_ACCEPT) - ? (byte & 0x3fu) | (codep << 6u) - : (0xFFu >> type) & (byte); - - std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); - JSON_ASSERT(index < 400); - state = utf8d[index]; - return state; - } - - /* - * Overload to make the compiler happy while it is instantiating - * dump_integer for number_unsigned_t. - * Must never be called. - */ - number_unsigned_t remove_sign(number_unsigned_t x) - { - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - return x; // LCOV_EXCL_LINE - } - - /* - * Helper function for dump_integer - * - * This function takes a negative signed integer and returns its absolute - * value as unsigned integer. The plus/minus shuffling is necessary as we can - * not directly remove the sign of an arbitrary signed integer as the - * absolute values of INT_MIN and INT_MAX are usually not the same. See - * #1708 for details. - */ - inline number_unsigned_t remove_sign(number_integer_t x) noexcept - { - JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression) - return static_cast(-(x + 1)) + 1; - } - - private: - /// the output of the serializer - output_adapter_t o = nullptr; - - /// a (hopefully) large enough character buffer - std::array number_buffer{{}}; - - /// the locale - const std::lconv* loc = nullptr; - /// the locale's thousand separator character - const char thousands_sep = '\0'; - /// the locale's decimal point character - const char decimal_point = '\0'; - - /// string buffer - std::array string_buffer{{}}; - - /// the indentation character - const char indent_char; - /// the indentation string - string_t indent_string; - - /// error_handler how to react on decoding errors - const error_handler_t error_handler; -}; -} // namespace detail -} // namespace nlohmann - -// #include - -// #include - -// #include - - -#include // less -#include // initializer_list -#include // input_iterator_tag, iterator_traits -#include // allocator -#include // for out_of_range -#include // enable_if, is_convertible -#include // pair -#include // vector - -// #include - - -namespace nlohmann -{ - -/// ordered_map: a minimal map-like container that preserves insertion order -/// for use within nlohmann::basic_json -template , - class Allocator = std::allocator>> - struct ordered_map : std::vector, Allocator> -{ - using key_type = Key; - using mapped_type = T; - using Container = std::vector, Allocator>; - using iterator = typename Container::iterator; - using const_iterator = typename Container::const_iterator; - using size_type = typename Container::size_type; - using value_type = typename Container::value_type; - - // Explicit constructors instead of `using Container::Container` - // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) - ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} - template - ordered_map(It first, It last, const Allocator& alloc = Allocator()) - : Container{first, last, alloc} {} - ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) - : Container{init, alloc} {} - - std::pair emplace(const key_type& key, T&& t) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return {it, false}; - } - } - Container::emplace_back(key, t); - return {--this->end(), true}; - } - - T& operator[](const Key& key) - { - return emplace(key, T{}).first->second; - } - - const T& operator[](const Key& key) const - { - return at(key); - } - - T& at(const Key& key) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it->second; - } - } - - JSON_THROW(std::out_of_range("key not found")); - } - - const T& at(const Key& key) const - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it->second; - } - } - - JSON_THROW(std::out_of_range("key not found")); - } - - size_type erase(const Key& key) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - // Since we cannot move const Keys, re-construct them in place - for (auto next = it; ++next != this->end(); ++it) - { - it->~value_type(); // Destroy but keep allocation - new (&*it) value_type{std::move(*next)}; - } - Container::pop_back(); - return 1; - } - } - return 0; - } - - iterator erase(iterator pos) - { - return erase(pos, std::next(pos)); - } - - iterator erase(iterator first, iterator last) - { - const auto elements_affected = std::distance(first, last); - const auto offset = std::distance(Container::begin(), first); - - // This is the start situation. We need to delete elements_affected - // elements (3 in this example: e, f, g), and need to return an - // iterator past the last deleted element (h in this example). - // Note that offset is the distance from the start of the vector - // to first. We will need this later. - - // [ a, b, c, d, e, f, g, h, i, j ] - // ^ ^ - // first last - - // Since we cannot move const Keys, we re-construct them in place. - // We start at first and re-construct (viz. copy) the elements from - // the back of the vector. Example for first iteration: - - // ,--------. - // v | destroy e and re-construct with h - // [ a, b, c, d, e, f, g, h, i, j ] - // ^ ^ - // it it + elements_affected - - for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) - { - it->~value_type(); // destroy but keep allocation - new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it - } - - // [ a, b, c, d, h, i, j, h, i, j ] - // ^ ^ - // first last - - // remove the unneeded elements at the end of the vector - Container::resize(this->size() - static_cast(elements_affected)); - - // [ a, b, c, d, h, i, j ] - // ^ ^ - // first last - - // first is now pointing past the last deleted element, but we cannot - // use this iterator, because it may have been invalidated by the - // resize call. Instead, we can return begin() + offset. - return Container::begin() + offset; - } - - size_type count(const Key& key) const - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return 1; - } - } - return 0; - } - - iterator find(const Key& key) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it; - } - } - return Container::end(); - } - - const_iterator find(const Key& key) const - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == key) - { - return it; - } - } - return Container::end(); - } - - std::pair insert( value_type&& value ) - { - return emplace(value.first, std::move(value.second)); - } - - std::pair insert( const value_type& value ) - { - for (auto it = this->begin(); it != this->end(); ++it) - { - if (it->first == value.first) - { - return {it, false}; - } - } - Container::push_back(value); - return {--this->end(), true}; - } - - template - using require_input_iter = typename std::enable_if::iterator_category, - std::input_iterator_tag>::value>::type; - - template> - void insert(InputIt first, InputIt last) - { - for (auto it = first; it != last; ++it) - { - insert(*it); - } - } -}; - -} // namespace nlohmann - - -#if defined(JSON_HAS_CPP_17) - #include -#endif - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ - -/*! -@brief a class to store JSON values - -@internal -@invariant The member variables @a m_value and @a m_type have the following -relationship: -- If `m_type == value_t::object`, then `m_value.object != nullptr`. -- If `m_type == value_t::array`, then `m_value.array != nullptr`. -- If `m_type == value_t::string`, then `m_value.string != nullptr`. -The invariants are checked by member function assert_invariant(). - -@note ObjectType trick from https://stackoverflow.com/a/9860911 -@endinternal - -@since version 1.0.0 - -@nosubgrouping -*/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) -{ - private: - template friend struct detail::external_constructor; - friend ::nlohmann::json_pointer; - - template - friend class ::nlohmann::detail::parser; - friend ::nlohmann::detail::serializer; - template - friend class ::nlohmann::detail::iter_impl; - template - friend class ::nlohmann::detail::binary_writer; - template - friend class ::nlohmann::detail::binary_reader; - template - friend class ::nlohmann::detail::json_sax_dom_parser; - template - friend class ::nlohmann::detail::json_sax_dom_callback_parser; - friend class ::nlohmann::detail::exception; - - /// workaround type for MSVC - using basic_json_t = NLOHMANN_BASIC_JSON_TPL; - - JSON_PRIVATE_UNLESS_TESTED: - // convenience aliases for types residing in namespace detail; - using lexer = ::nlohmann::detail::lexer_base; - - template - static ::nlohmann::detail::parser parser( - InputAdapterType adapter, - detail::parser_callback_tcb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false - ) - { - return ::nlohmann::detail::parser(std::move(adapter), - std::move(cb), allow_exceptions, ignore_comments); - } - - private: - using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; - template - using internal_iterator = ::nlohmann::detail::internal_iterator; - template - using iter_impl = ::nlohmann::detail::iter_impl; - template - using iteration_proxy = ::nlohmann::detail::iteration_proxy; - template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; - - template - using output_adapter_t = ::nlohmann::detail::output_adapter_t; - - template - using binary_reader = ::nlohmann::detail::binary_reader; - template using binary_writer = ::nlohmann::detail::binary_writer; - - JSON_PRIVATE_UNLESS_TESTED: - using serializer = ::nlohmann::detail::serializer; - - public: - using value_t = detail::value_t; - /// JSON Pointer, see @ref nlohmann::json_pointer - using json_pointer = ::nlohmann::json_pointer; - template - using json_serializer = JSONSerializer; - /// how to treat decoding errors - using error_handler_t = detail::error_handler_t; - /// how to treat CBOR tags - using cbor_tag_handler_t = detail::cbor_tag_handler_t; - /// helper type for initializer lists of basic_json values - using initializer_list_t = std::initializer_list>; - - using input_format_t = detail::input_format_t; - /// SAX interface type, see @ref nlohmann::json_sax - using json_sax_t = json_sax; - - //////////////// - // exceptions // - //////////////// - - /// @name exceptions - /// Classes to implement user-defined exceptions. - /// @{ - - using exception = detail::exception; - using parse_error = detail::parse_error; - using invalid_iterator = detail::invalid_iterator; - using type_error = detail::type_error; - using out_of_range = detail::out_of_range; - using other_error = detail::other_error; - - /// @} - - - ///////////////////// - // container types // - ///////////////////// - - /// @name container types - /// The canonic container types to use @ref basic_json like any other STL - /// container. - /// @{ - - /// the type of elements in a basic_json container - using value_type = basic_json; - - /// the type of an element reference - using reference = value_type&; - /// the type of an element const reference - using const_reference = const value_type&; - - /// a type to represent differences between iterators - using difference_type = std::ptrdiff_t; - /// a type to represent container sizes - using size_type = std::size_t; - - /// the allocator type - using allocator_type = AllocatorType; - - /// the type of an element pointer - using pointer = typename std::allocator_traits::pointer; - /// the type of an element const pointer - using const_pointer = typename std::allocator_traits::const_pointer; - - /// an iterator for a basic_json container - using iterator = iter_impl; - /// a const iterator for a basic_json container - using const_iterator = iter_impl; - /// a reverse iterator for a basic_json container - using reverse_iterator = json_reverse_iterator; - /// a const reverse iterator for a basic_json container - using const_reverse_iterator = json_reverse_iterator; - - /// @} - - - /// @brief returns the allocator associated with the container - /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/ - static allocator_type get_allocator() - { - return allocator_type(); - } - - /// @brief returns version information on the library - /// @sa https://json.nlohmann.me/api/basic_json/meta/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json meta() - { - basic_json result; - - result["copyright"] = "(C) 2013-2022 Niels Lohmann"; - result["name"] = "JSON for Modern C++"; - result["url"] = "https://github.com/nlohmann/json"; - result["version"]["string"] = - std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + - std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + - std::to_string(NLOHMANN_JSON_VERSION_PATCH); - result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; - result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; - result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; - -#ifdef _WIN32 - result["platform"] = "win32"; -#elif defined __linux__ - result["platform"] = "linux"; -#elif defined __APPLE__ - result["platform"] = "apple"; -#elif defined __unix__ - result["platform"] = "unix"; -#else - result["platform"] = "unknown"; -#endif - -#if defined(__ICC) || defined(__INTEL_COMPILER) - result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; -#elif defined(__clang__) - result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; -#elif defined(__GNUC__) || defined(__GNUG__) - result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; -#elif defined(__HP_cc) || defined(__HP_aCC) - result["compiler"] = "hp" -#elif defined(__IBMCPP__) - result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; -#elif defined(_MSC_VER) - result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; -#elif defined(__PGI) - result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; -#elif defined(__SUNPRO_CC) - result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; -#else - result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; -#endif - -#ifdef __cplusplus - result["compiler"]["c++"] = std::to_string(__cplusplus); -#else - result["compiler"]["c++"] = "unknown"; -#endif - return result; - } - - - /////////////////////////// - // JSON value data types // - /////////////////////////// - - /// @name JSON value data types - /// The data types to store a JSON value. These types are derived from - /// the template arguments passed to class @ref basic_json. - /// @{ - - /// @brief object key comparator type - /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/ -#if defined(JSON_HAS_CPP_14) - // Use transparent comparator if possible, combined with perfect forwarding - // on find() and count() calls prevents unnecessary string construction. - using object_comparator_t = std::less<>; -#else - using object_comparator_t = std::less; -#endif - - /// @brief a type for an object - /// @sa https://json.nlohmann.me/api/basic_json/object_t/ - using object_t = ObjectType>>; - - /// @brief a type for an array - /// @sa https://json.nlohmann.me/api/basic_json/array_t/ - using array_t = ArrayType>; - - /// @brief a type for a string - /// @sa https://json.nlohmann.me/api/basic_json/string_t/ - using string_t = StringType; - - /// @brief a type for a boolean - /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/ - using boolean_t = BooleanType; - - /// @brief a type for a number (integer) - /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/ - using number_integer_t = NumberIntegerType; - - /// @brief a type for a number (unsigned) - /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/ - using number_unsigned_t = NumberUnsignedType; - - /// @brief a type for a number (floating-point) - /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/ - using number_float_t = NumberFloatType; - - /// @brief a type for a packed binary type - /// @sa https://json.nlohmann.me/api/basic_json/binary_t/ - using binary_t = nlohmann::byte_container_with_subtype; - - /// @} - - private: - - /// helper for exception-safe object creation - template - JSON_HEDLEY_RETURNS_NON_NULL - static T* create(Args&& ... args) - { - AllocatorType alloc; - using AllocatorTraits = std::allocator_traits>; - - auto deleter = [&](T * obj) - { - AllocatorTraits::deallocate(alloc, obj, 1); - }; - std::unique_ptr obj(AllocatorTraits::allocate(alloc, 1), deleter); - AllocatorTraits::construct(alloc, obj.get(), std::forward(args)...); - JSON_ASSERT(obj != nullptr); - return obj.release(); - } - - //////////////////////// - // JSON value storage // - //////////////////////// - - JSON_PRIVATE_UNLESS_TESTED: - /*! - @brief a JSON value - - The actual storage for a JSON value of the @ref basic_json class. This - union combines the different storage types for the JSON value types - defined in @ref value_t. - - JSON type | value_t type | used type - --------- | --------------- | ------------------------ - object | object | pointer to @ref object_t - array | array | pointer to @ref array_t - string | string | pointer to @ref string_t - boolean | boolean | @ref boolean_t - number | number_integer | @ref number_integer_t - number | number_unsigned | @ref number_unsigned_t - number | number_float | @ref number_float_t - binary | binary | pointer to @ref binary_t - null | null | *no value is stored* - - @note Variable-length types (objects, arrays, and strings) are stored as - pointers. The size of the union should not exceed 64 bits if the default - value types are used. - - @since version 1.0.0 - */ - union json_value - { - /// object (stored with pointer to save storage) - object_t* object; - /// array (stored with pointer to save storage) - array_t* array; - /// string (stored with pointer to save storage) - string_t* string; - /// binary (stored with pointer to save storage) - binary_t* binary; - /// boolean - boolean_t boolean; - /// number (integer) - number_integer_t number_integer; - /// number (unsigned integer) - number_unsigned_t number_unsigned; - /// number (floating-point) - number_float_t number_float; - - /// default constructor (for null values) - json_value() = default; - /// constructor for booleans - json_value(boolean_t v) noexcept : boolean(v) {} - /// constructor for numbers (integer) - json_value(number_integer_t v) noexcept : number_integer(v) {} - /// constructor for numbers (unsigned) - json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} - /// constructor for numbers (floating-point) - json_value(number_float_t v) noexcept : number_float(v) {} - /// constructor for empty values of a given type - json_value(value_t t) - { - switch (t) - { - case value_t::object: - { - object = create(); - break; - } - - case value_t::array: - { - array = create(); - break; - } - - case value_t::string: - { - string = create(""); - break; - } - - case value_t::binary: - { - binary = create(); - break; - } - - case value_t::boolean: - { - boolean = static_cast(false); - break; - } - - case value_t::number_integer: - { - number_integer = static_cast(0); - break; - } - - case value_t::number_unsigned: - { - number_unsigned = static_cast(0); - break; - } - - case value_t::number_float: - { - number_float = static_cast(0.0); - break; - } - - case value_t::null: - { - object = nullptr; // silence warning, see #821 - break; - } - - case value_t::discarded: - default: - { - object = nullptr; // silence warning, see #821 - if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) - { - JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE - } - break; - } - } - } - - /// constructor for strings - json_value(const string_t& value) : string(create(value)) {} - - /// constructor for rvalue strings - json_value(string_t&& value) : string(create(std::move(value))) {} - - /// constructor for objects - json_value(const object_t& value) : object(create(value)) {} - - /// constructor for rvalue objects - json_value(object_t&& value) : object(create(std::move(value))) {} - - /// constructor for arrays - json_value(const array_t& value) : array(create(value)) {} - - /// constructor for rvalue arrays - json_value(array_t&& value) : array(create(std::move(value))) {} - - /// constructor for binary arrays - json_value(const typename binary_t::container_type& value) : binary(create(value)) {} - - /// constructor for rvalue binary arrays - json_value(typename binary_t::container_type&& value) : binary(create(std::move(value))) {} - - /// constructor for binary arrays (internal type) - json_value(const binary_t& value) : binary(create(value)) {} - - /// constructor for rvalue binary arrays (internal type) - json_value(binary_t&& value) : binary(create(std::move(value))) {} - - void destroy(value_t t) - { - if (t == value_t::array || t == value_t::object) - { - // flatten the current json_value to a heap-allocated stack - std::vector stack; - - // move the top-level items to stack - if (t == value_t::array) - { - stack.reserve(array->size()); - std::move(array->begin(), array->end(), std::back_inserter(stack)); - } - else - { - stack.reserve(object->size()); - for (auto&& it : *object) - { - stack.push_back(std::move(it.second)); - } - } - - while (!stack.empty()) - { - // move the last item to local variable to be processed - basic_json current_item(std::move(stack.back())); - stack.pop_back(); - - // if current_item is array/object, move - // its children to the stack to be processed later - if (current_item.is_array()) - { - std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); - - current_item.m_value.array->clear(); - } - else if (current_item.is_object()) - { - for (auto&& it : *current_item.m_value.object) - { - stack.push_back(std::move(it.second)); - } - - current_item.m_value.object->clear(); - } - - // it's now safe that current_item get destructed - // since it doesn't have any children - } - } - - switch (t) - { - case value_t::object: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, object); - std::allocator_traits::deallocate(alloc, object, 1); - break; - } - - case value_t::array: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, array); - std::allocator_traits::deallocate(alloc, array, 1); - break; - } - - case value_t::string: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, string); - std::allocator_traits::deallocate(alloc, string, 1); - break; - } - - case value_t::binary: - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, binary); - std::allocator_traits::deallocate(alloc, binary, 1); - break; - } - - case value_t::null: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::discarded: - default: - { - break; - } - } - } - }; - - private: - /*! - @brief checks the class invariants - - This function asserts the class invariants. It needs to be called at the - end of every constructor to make sure that created objects respect the - invariant. Furthermore, it has to be called each time the type of a JSON - value is changed, because the invariant expresses a relationship between - @a m_type and @a m_value. - - Furthermore, the parent relation is checked for arrays and objects: If - @a check_parents true and the value is an array or object, then the - container's elements must have the current value as parent. - - @param[in] check_parents whether the parent relation should be checked. - The value is true by default and should only be set to false - during destruction of objects when the invariant does not - need to hold. - */ - void assert_invariant(bool check_parents = true) const noexcept - { - JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); - JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); - JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); - JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); - -#if JSON_DIAGNOSTICS - JSON_TRY - { - // cppcheck-suppress assertWithSideEffect - JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) - { - return j.m_parent == this; - })); - } - JSON_CATCH(...) {} // LCOV_EXCL_LINE -#endif - static_cast(check_parents); - } - - void set_parents() - { -#if JSON_DIAGNOSTICS - switch (m_type) - { - case value_t::array: - { - for (auto& element : *m_value.array) - { - element.m_parent = this; - } - break; - } - - case value_t::object: - { - for (auto& element : *m_value.object) - { - element.second.m_parent = this; - } - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - break; - } -#endif - } - - iterator set_parents(iterator it, typename iterator::difference_type count_set_parents) - { -#if JSON_DIAGNOSTICS - for (typename iterator::difference_type i = 0; i < count_set_parents; ++i) - { - (it + i)->m_parent = this; - } -#else - static_cast(count_set_parents); -#endif - return it; - } - - reference set_parent(reference j, std::size_t old_capacity = static_cast(-1)) - { -#if JSON_DIAGNOSTICS - if (old_capacity != static_cast(-1)) - { - // see https://github.com/nlohmann/json/issues/2838 - JSON_ASSERT(type() == value_t::array); - if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) - { - // capacity has changed: update all parents - set_parents(); - return j; - } - } - - // ordered_json uses a vector internally, so pointers could have - // been invalidated; see https://github.com/nlohmann/json/issues/2962 -#ifdef JSON_HEDLEY_MSVC_VERSION -#pragma warning(push ) -#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr -#endif - if (detail::is_ordered_map::value) - { - set_parents(); - return j; - } -#ifdef JSON_HEDLEY_MSVC_VERSION -#pragma warning( pop ) -#endif - - j.m_parent = this; -#else - static_cast(j); - static_cast(old_capacity); -#endif - return j; - } - - public: - ////////////////////////// - // JSON parser callback // - ////////////////////////// - - /// @brief parser event types - /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/ - using parse_event_t = detail::parse_event_t; - - /// @brief per-element parser callback type - /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/ - using parser_callback_t = detail::parser_callback_t; - - ////////////////// - // constructors // - ////////////////// - - /// @name constructors and destructors - /// Constructors of class @ref basic_json, copy/move constructor, copy - /// assignment, static functions creating objects, and the destructor. - /// @{ - - /// @brief create an empty value with a given type - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(const value_t v) - : m_type(v), m_value(v) - { - assert_invariant(); - } - - /// @brief create a null object - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(std::nullptr_t = nullptr) noexcept - : basic_json(value_t::null) - { - assert_invariant(); - } - - /// @brief create a JSON value from compatible types - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - template < typename CompatibleType, - typename U = detail::uncvref_t, - detail::enable_if_t < - !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > - basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) - JSONSerializer::to_json(std::declval(), - std::forward(val)))) - { - JSONSerializer::to_json(*this, std::forward(val)); - set_parents(); - assert_invariant(); - } - - /// @brief create a JSON value from an existing one - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - template < typename BasicJsonType, - detail::enable_if_t < - detail::is_basic_json::value&& !std::is_same::value, int > = 0 > - basic_json(const BasicJsonType& val) - { - using other_boolean_t = typename BasicJsonType::boolean_t; - using other_number_float_t = typename BasicJsonType::number_float_t; - using other_number_integer_t = typename BasicJsonType::number_integer_t; - using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; - using other_string_t = typename BasicJsonType::string_t; - using other_object_t = typename BasicJsonType::object_t; - using other_array_t = typename BasicJsonType::array_t; - using other_binary_t = typename BasicJsonType::binary_t; - - switch (val.type()) - { - case value_t::boolean: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_float: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_integer: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::number_unsigned: - JSONSerializer::to_json(*this, val.template get()); - break; - case value_t::string: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::object: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::array: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::binary: - JSONSerializer::to_json(*this, val.template get_ref()); - break; - case value_t::null: - *this = nullptr; - break; - case value_t::discarded: - m_type = value_t::discarded; - break; - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - set_parents(); - assert_invariant(); - } - - /// @brief create a container (array or object) from an initializer list - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(initializer_list_t init, - bool type_deduction = true, - value_t manual_type = value_t::array) - { - // check if each element is an array with two elements whose first - // element is a string - bool is_an_object = std::all_of(init.begin(), init.end(), - [](const detail::json_ref& element_ref) - { - return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); - }); - - // adjust type if type deduction is not wanted - if (!type_deduction) - { - // if array is wanted, do not create an object though possible - if (manual_type == value_t::array) - { - is_an_object = false; - } - - // if object is wanted but impossible, throw an exception - if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) - { - JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); - } - } - - if (is_an_object) - { - // the initializer list is a list of pairs -> create object - m_type = value_t::object; - m_value = value_t::object; - - for (auto& element_ref : init) - { - auto element = element_ref.moved_or_copied(); - m_value.object->emplace( - std::move(*((*element.m_value.array)[0].m_value.string)), - std::move((*element.m_value.array)[1])); - } - } - else - { - // the initializer list describes an array -> create array - m_type = value_t::array; - m_value.array = create(init.begin(), init.end()); - } - - set_parents(); - assert_invariant(); - } - - /// @brief explicitly create a binary array (without subtype) - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(const typename binary_t::container_type& init) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = init; - return res; - } - - /// @brief explicitly create a binary array (with subtype) - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = binary_t(init, subtype); - return res; - } - - /// @brief explicitly create a binary array - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(typename binary_t::container_type&& init) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = std::move(init); - return res; - } - - /// @brief explicitly create a binary array (with subtype) - /// @sa https://json.nlohmann.me/api/basic_json/binary/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) - { - auto res = basic_json(); - res.m_type = value_t::binary; - res.m_value = binary_t(std::move(init), subtype); - return res; - } - - /// @brief explicitly create an array from an initializer list - /// @sa https://json.nlohmann.me/api/basic_json/array/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json array(initializer_list_t init = {}) - { - return basic_json(init, false, value_t::array); - } - - /// @brief explicitly create an object from an initializer list - /// @sa https://json.nlohmann.me/api/basic_json/object/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json object(initializer_list_t init = {}) - { - return basic_json(init, false, value_t::object); - } - - /// @brief construct an array with count copies of given value - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(size_type cnt, const basic_json& val) - : m_type(value_t::array) - { - m_value.array = create(cnt, val); - set_parents(); - assert_invariant(); - } - - /// @brief construct a JSON container given an iterator range - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - template < class InputIT, typename std::enable_if < - std::is_same::value || - std::is_same::value, int >::type = 0 > - basic_json(InputIT first, InputIT last) - { - JSON_ASSERT(first.m_object != nullptr); - JSON_ASSERT(last.m_object != nullptr); - - // make sure iterator fits the current value - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); - } - - // copy type from first iterator - m_type = first.m_object->m_type; - - // check if iterator range is complete for primitive values - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - { - if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() - || !last.m_it.primitive_iterator.is_end())) - { - JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); - } - break; - } - - case value_t::null: - case value_t::object: - case value_t::array: - case value_t::binary: - case value_t::discarded: - default: - break; - } - - switch (m_type) - { - case value_t::number_integer: - { - m_value.number_integer = first.m_object->m_value.number_integer; - break; - } - - case value_t::number_unsigned: - { - m_value.number_unsigned = first.m_object->m_value.number_unsigned; - break; - } - - case value_t::number_float: - { - m_value.number_float = first.m_object->m_value.number_float; - break; - } - - case value_t::boolean: - { - m_value.boolean = first.m_object->m_value.boolean; - break; - } - - case value_t::string: - { - m_value = *first.m_object->m_value.string; - break; - } - - case value_t::object: - { - m_value.object = create(first.m_it.object_iterator, - last.m_it.object_iterator); - break; - } - - case value_t::array: - { - m_value.array = create(first.m_it.array_iterator, - last.m_it.array_iterator); - break; - } - - case value_t::binary: - { - m_value = *first.m_object->m_value.binary; - break; - } - - case value_t::null: - case value_t::discarded: - default: - JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); - } - - set_parents(); - assert_invariant(); - } - - - /////////////////////////////////////// - // other constructors and destructor // - /////////////////////////////////////// - - template, - std::is_same>::value, int> = 0 > - basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} - - /// @brief copy constructor - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(const basic_json& other) - : m_type(other.m_type) - { - // check of passed value is valid - other.assert_invariant(); - - switch (m_type) - { - case value_t::object: - { - m_value = *other.m_value.object; - break; - } - - case value_t::array: - { - m_value = *other.m_value.array; - break; - } - - case value_t::string: - { - m_value = *other.m_value.string; - break; - } - - case value_t::boolean: - { - m_value = other.m_value.boolean; - break; - } - - case value_t::number_integer: - { - m_value = other.m_value.number_integer; - break; - } - - case value_t::number_unsigned: - { - m_value = other.m_value.number_unsigned; - break; - } - - case value_t::number_float: - { - m_value = other.m_value.number_float; - break; - } - - case value_t::binary: - { - m_value = *other.m_value.binary; - break; - } - - case value_t::null: - case value_t::discarded: - default: - break; - } - - set_parents(); - assert_invariant(); - } - - /// @brief move constructor - /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ - basic_json(basic_json&& other) noexcept - : m_type(std::move(other.m_type)), - m_value(std::move(other.m_value)) - { - // check that passed value is valid - other.assert_invariant(false); - - // invalidate payload - other.m_type = value_t::null; - other.m_value = {}; - - set_parents(); - assert_invariant(); - } - - /// @brief copy assignment - /// @sa https://json.nlohmann.me/api/basic_json/operator=/ - basic_json& operator=(basic_json other) noexcept ( - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value - ) - { - // check that passed value is valid - other.assert_invariant(); - - using std::swap; - swap(m_type, other.m_type); - swap(m_value, other.m_value); - - set_parents(); - assert_invariant(); - return *this; - } - - /// @brief destructor - /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/ - ~basic_json() noexcept - { - assert_invariant(false); - m_value.destroy(m_type); - } - - /// @} - - public: - /////////////////////// - // object inspection // - /////////////////////// - - /// @name object inspection - /// Functions to inspect the type of a JSON value. - /// @{ - - /// @brief serialization - /// @sa https://json.nlohmann.me/api/basic_json/dump/ - string_t dump(const int indent = -1, - const char indent_char = ' ', - const bool ensure_ascii = false, - const error_handler_t error_handler = error_handler_t::strict) const - { - string_t result; - serializer s(detail::output_adapter(result), indent_char, error_handler); - - if (indent >= 0) - { - s.dump(*this, true, ensure_ascii, static_cast(indent)); - } - else - { - s.dump(*this, false, ensure_ascii, 0); - } - - return result; - } - - /// @brief return the type of the JSON value (explicit) - /// @sa https://json.nlohmann.me/api/basic_json/type/ - constexpr value_t type() const noexcept - { - return m_type; - } - - /// @brief return whether type is primitive - /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/ - constexpr bool is_primitive() const noexcept - { - return is_null() || is_string() || is_boolean() || is_number() || is_binary(); - } - - /// @brief return whether type is structured - /// @sa https://json.nlohmann.me/api/basic_json/is_structured/ - constexpr bool is_structured() const noexcept - { - return is_array() || is_object(); - } - - /// @brief return whether value is null - /// @sa https://json.nlohmann.me/api/basic_json/is_null/ - constexpr bool is_null() const noexcept - { - return m_type == value_t::null; - } - - /// @brief return whether value is a boolean - /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/ - constexpr bool is_boolean() const noexcept - { - return m_type == value_t::boolean; - } - - /// @brief return whether value is a number - /// @sa https://json.nlohmann.me/api/basic_json/is_number/ - constexpr bool is_number() const noexcept - { - return is_number_integer() || is_number_float(); - } - - /// @brief return whether value is an integer number - /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/ - constexpr bool is_number_integer() const noexcept - { - return m_type == value_t::number_integer || m_type == value_t::number_unsigned; - } - - /// @brief return whether value is an unsigned integer number - /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/ - constexpr bool is_number_unsigned() const noexcept - { - return m_type == value_t::number_unsigned; - } - - /// @brief return whether value is a floating-point number - /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/ - constexpr bool is_number_float() const noexcept - { - return m_type == value_t::number_float; - } - - /// @brief return whether value is an object - /// @sa https://json.nlohmann.me/api/basic_json/is_object/ - constexpr bool is_object() const noexcept - { - return m_type == value_t::object; - } - - /// @brief return whether value is an array - /// @sa https://json.nlohmann.me/api/basic_json/is_array/ - constexpr bool is_array() const noexcept - { - return m_type == value_t::array; - } - - /// @brief return whether value is a string - /// @sa https://json.nlohmann.me/api/basic_json/is_string/ - constexpr bool is_string() const noexcept - { - return m_type == value_t::string; - } - - /// @brief return whether value is a binary array - /// @sa https://json.nlohmann.me/api/basic_json/is_binary/ - constexpr bool is_binary() const noexcept - { - return m_type == value_t::binary; - } - - /// @brief return whether value is discarded - /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/ - constexpr bool is_discarded() const noexcept - { - return m_type == value_t::discarded; - } - - /// @brief return the type of the JSON value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/ - constexpr operator value_t() const noexcept - { - return m_type; - } - - /// @} - - private: - ////////////////// - // value access // - ////////////////// - - /// get a boolean (explicit) - boolean_t get_impl(boolean_t* /*unused*/) const - { - if (JSON_HEDLEY_LIKELY(is_boolean())) - { - return m_value.boolean; - } - - JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); - } - - /// get a pointer to the value (object) - object_t* get_impl_ptr(object_t* /*unused*/) noexcept - { - return is_object() ? m_value.object : nullptr; - } - - /// get a pointer to the value (object) - constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept - { - return is_object() ? m_value.object : nullptr; - } - - /// get a pointer to the value (array) - array_t* get_impl_ptr(array_t* /*unused*/) noexcept - { - return is_array() ? m_value.array : nullptr; - } - - /// get a pointer to the value (array) - constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept - { - return is_array() ? m_value.array : nullptr; - } - - /// get a pointer to the value (string) - string_t* get_impl_ptr(string_t* /*unused*/) noexcept - { - return is_string() ? m_value.string : nullptr; - } - - /// get a pointer to the value (string) - constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept - { - return is_string() ? m_value.string : nullptr; - } - - /// get a pointer to the value (boolean) - boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept - { - return is_boolean() ? &m_value.boolean : nullptr; - } - - /// get a pointer to the value (boolean) - constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept - { - return is_boolean() ? &m_value.boolean : nullptr; - } - - /// get a pointer to the value (integer number) - number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept - { - return is_number_integer() ? &m_value.number_integer : nullptr; - } - - /// get a pointer to the value (integer number) - constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept - { - return is_number_integer() ? &m_value.number_integer : nullptr; - } - - /// get a pointer to the value (unsigned number) - number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept - { - return is_number_unsigned() ? &m_value.number_unsigned : nullptr; - } - - /// get a pointer to the value (unsigned number) - constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept - { - return is_number_unsigned() ? &m_value.number_unsigned : nullptr; - } - - /// get a pointer to the value (floating-point number) - number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept - { - return is_number_float() ? &m_value.number_float : nullptr; - } - - /// get a pointer to the value (floating-point number) - constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept - { - return is_number_float() ? &m_value.number_float : nullptr; - } - - /// get a pointer to the value (binary) - binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept - { - return is_binary() ? m_value.binary : nullptr; - } - - /// get a pointer to the value (binary) - constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept - { - return is_binary() ? m_value.binary : nullptr; - } - - /*! - @brief helper function to implement get_ref() - - This function helps to implement get_ref() without code duplication for - const and non-const overloads - - @tparam ThisType will be deduced as `basic_json` or `const basic_json` - - @throw type_error.303 if ReferenceType does not match underlying value - type of the current JSON - */ - template - static ReferenceType get_ref_impl(ThisType& obj) - { - // delegate the call to get_ptr<>() - auto* ptr = obj.template get_ptr::type>(); - - if (JSON_HEDLEY_LIKELY(ptr != nullptr)) - { - return *ptr; - } - - JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); - } - - public: - /// @name value access - /// Direct access to the stored value of a JSON value. - /// @{ - - /// @brief get a pointer value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ - template::value, int>::type = 0> - auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) - { - // delegate the call to get_impl_ptr<>() - return get_impl_ptr(static_cast(nullptr)); - } - - /// @brief get a pointer value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ - template < typename PointerType, typename std::enable_if < - std::is_pointer::value&& - std::is_const::type>::value, int >::type = 0 > - constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) - { - // delegate the call to get_impl_ptr<>() const - return get_impl_ptr(static_cast(nullptr)); - } - - private: - /*! - @brief get a value (explicit) - - Explicit type conversion between the JSON value and a compatible value - which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) - and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). - The value is converted by calling the @ref json_serializer - `from_json()` method. - - The function is equivalent to executing - @code {.cpp} - ValueType ret; - JSONSerializer::from_json(*this, ret); - return ret; - @endcode - - This overloads is chosen if: - - @a ValueType is not @ref basic_json, - - @ref json_serializer has a `from_json()` method of the form - `void from_json(const basic_json&, ValueType&)`, and - - @ref json_serializer does not have a `from_json()` method of - the form `ValueType from_json(const basic_json&)` - - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @a ValueType - - @throw what @ref json_serializer `from_json()` method throws - - @liveexample{The example below shows several conversions from JSON values - to other types. There a few things to note: (1) Floating-point numbers can - be converted to integers\, (2) A JSON array can be converted to a standard - `std::vector`\, (3) A JSON object can be converted to C++ - associative containers such as `std::unordered_map`.,get__ValueType_const} - - @since version 2.1.0 - */ - template < typename ValueType, - detail::enable_if_t < - detail::is_default_constructible::value&& - detail::has_from_json::value, - int > = 0 > - ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( - JSONSerializer::from_json(std::declval(), std::declval()))) - { - auto ret = ValueType(); - JSONSerializer::from_json(*this, ret); - return ret; - } - - /*! - @brief get a value (explicit); special case - - Explicit type conversion between the JSON value and a compatible value - which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) - and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). - The value is converted by calling the @ref json_serializer - `from_json()` method. - - The function is equivalent to executing - @code {.cpp} - return JSONSerializer::from_json(*this); - @endcode - - This overloads is chosen if: - - @a ValueType is not @ref basic_json and - - @ref json_serializer has a `from_json()` method of the form - `ValueType from_json(const basic_json&)` - - @note If @ref json_serializer has both overloads of - `from_json()`, this one is chosen. - - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @a ValueType - - @throw what @ref json_serializer `from_json()` method throws - - @since version 2.1.0 - */ - template < typename ValueType, - detail::enable_if_t < - detail::has_non_default_from_json::value, - int > = 0 > - ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( - JSONSerializer::from_json(std::declval()))) - { - return JSONSerializer::from_json(*this); - } - - /*! - @brief get special-case overload - - This overloads converts the current @ref basic_json in a different - @ref basic_json type - - @tparam BasicJsonType == @ref basic_json - - @return a copy of *this, converted into @a BasicJsonType - - @complexity Depending on the implementation of the called `from_json()` - method. - - @since version 3.2.0 - */ - template < typename BasicJsonType, - detail::enable_if_t < - detail::is_basic_json::value, - int > = 0 > - BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const - { - return *this; - } - - /*! - @brief get special-case overload - - This overloads avoids a lot of template boilerplate, it can be seen as the - identity method - - @tparam BasicJsonType == @ref basic_json - - @return a copy of *this - - @complexity Constant. - - @since version 2.1.0 - */ - template::value, - int> = 0> - basic_json get_impl(detail::priority_tag<3> /*unused*/) const - { - return *this; - } - - /*! - @brief get a pointer value (explicit) - @copydoc get() - */ - template::value, - int> = 0> - constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept - -> decltype(std::declval().template get_ptr()) - { - // delegate the call to get_ptr - return get_ptr(); - } - - public: - /*! - @brief get a (pointer) value (explicit) - - Performs explicit type conversion between the JSON value and a compatible value if required. - - - If the requested type is a pointer to the internally stored JSON value that pointer is returned. - No copies are made. - - - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible - from the current @ref basic_json. - - - Otherwise the value is converted by calling the @ref json_serializer `from_json()` - method. - - @tparam ValueTypeCV the provided value type - @tparam ValueType the returned value type - - @return copy of the JSON value, converted to @tparam ValueType if necessary - - @throw what @ref json_serializer `from_json()` method throws if conversion is required - - @since version 2.1.0 - */ - template < typename ValueTypeCV, typename ValueType = detail::uncvref_t> -#if defined(JSON_HAS_CPP_14) - constexpr -#endif - auto get() const noexcept( - noexcept(std::declval().template get_impl(detail::priority_tag<4> {}))) - -> decltype(std::declval().template get_impl(detail::priority_tag<4> {})) - { - // we cannot static_assert on ValueTypeCV being non-const, because - // there is support for get(), which is why we - // still need the uncvref - static_assert(!std::is_reference::value, - "get() cannot be used with reference types, you might want to use get_ref()"); - return get_impl(detail::priority_tag<4> {}); - } - - /*! - @brief get a pointer value (explicit) - - Explicit pointer access to the internally stored JSON value. No copies are - made. - - @warning The pointer becomes invalid if the underlying JSON object - changes. - - @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref - object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, - @ref number_unsigned_t, or @ref number_float_t. - - @return pointer to the internally stored JSON value if the requested - pointer type @a PointerType fits to the JSON value; `nullptr` otherwise - - @complexity Constant. - - @liveexample{The example below shows how pointers to internal values of a - JSON value can be requested. Note that no type conversions are made and a - `nullptr` is returned if the value and the requested pointer type does not - match.,get__PointerType} - - @sa see @ref get_ptr() for explicit pointer-member access - - @since version 1.0.0 - */ - template::value, int>::type = 0> - auto get() noexcept -> decltype(std::declval().template get_ptr()) - { - // delegate the call to get_ptr - return get_ptr(); - } - - /// @brief get a value (explicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_to/ - template < typename ValueType, - detail::enable_if_t < - !detail::is_basic_json::value&& - detail::has_from_json::value, - int > = 0 > - ValueType & get_to(ValueType& v) const noexcept(noexcept( - JSONSerializer::from_json(std::declval(), v))) - { - JSONSerializer::from_json(*this, v); - return v; - } - - // specialization to allow calling get_to with a basic_json value - // see https://github.com/nlohmann/json/issues/2175 - template::value, - int> = 0> - ValueType & get_to(ValueType& v) const - { - v = *this; - return v; - } - - template < - typename T, std::size_t N, - typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - detail::enable_if_t < - detail::has_from_json::value, int > = 0 > - Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) - noexcept(noexcept(JSONSerializer::from_json( - std::declval(), v))) - { - JSONSerializer::from_json(*this, v); - return v; - } - - /// @brief get a reference value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ - template::value, int>::type = 0> - ReferenceType get_ref() - { - // delegate call to get_ref_impl - return get_ref_impl(*this); - } - - /// @brief get a reference value (implicit) - /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ - template < typename ReferenceType, typename std::enable_if < - std::is_reference::value&& - std::is_const::type>::value, int >::type = 0 > - ReferenceType get_ref() const - { - // delegate call to get_ref_impl - return get_ref_impl(*this); - } - - /*! - @brief get a value (implicit) - - Implicit type conversion between the JSON value and a compatible value. - The call is realized by calling @ref get() const. - - @tparam ValueType non-pointer type compatible to the JSON value, for - instance `int` for JSON integer numbers, `bool` for JSON booleans, or - `std::vector` types for JSON arrays. The character type of @ref string_t - as well as an initializer list of this type is excluded to avoid - ambiguities as these types implicitly convert to `std::string`. - - @return copy of the JSON value, converted to type @a ValueType - - @throw type_error.302 in case passed type @a ValueType is incompatible - to the JSON value type (e.g., the JSON value is of type boolean, but a - string is requested); see example below - - @complexity Linear in the size of the JSON value. - - @liveexample{The example below shows several conversions from JSON values - to other types. There a few things to note: (1) Floating-point numbers can - be converted to integers\, (2) A JSON array can be converted to a standard - `std::vector`\, (3) A JSON object can be converted to C++ - associative containers such as `std::unordered_map`.,operator__ValueType} - - @since version 1.0.0 - */ - template < typename ValueType, typename std::enable_if < - detail::conjunction < - detail::negation>, - detail::negation>>, - detail::negation>, - detail::negation>, - detail::negation>>, - -#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) - detail::negation>, -#endif - detail::is_detected_lazy - >::value, int >::type = 0 > - JSON_EXPLICIT operator ValueType() const - { - // delegate the call to get<>() const - return get(); - } - - /// @brief get a binary value - /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ - binary_t& get_binary() - { - if (!is_binary()) - { - JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); - } - - return *get_ptr(); - } - - /// @brief get a binary value - /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ - const binary_t& get_binary() const - { - if (!is_binary()) - { - JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); - } - - return *get_ptr(); - } - - /// @} - - - //////////////////// - // element access // - //////////////////// - - /// @name element access - /// Access to the JSON value. - /// @{ - - /// @brief access specified array element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - reference at(size_type idx) - { - // at only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - JSON_TRY - { - return set_parent(m_value.array->at(idx)); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified array element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - const_reference at(size_type idx) const - { - // at only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - JSON_TRY - { - return m_value.array->at(idx); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified object element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - reference at(const typename object_t::key_type& key) - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_TRY - { - return set_parent(m_value.object->at(key)); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified object element with bounds checking - /// @sa https://json.nlohmann.me/api/basic_json/at/ - const_reference at(const typename object_t::key_type& key) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_TRY - { - return m_value.object->at(key); - } - JSON_CATCH (std::out_of_range&) - { - // create better exception explanation - JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); - } - } - else - { - JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); - } - } - - /// @brief access specified array element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - reference operator[](size_type idx) - { - // implicitly convert null value to an empty array - if (is_null()) - { - m_type = value_t::array; - m_value.array = create(); - assert_invariant(); - } - - // operator[] only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - // fill up array with null values if given idx is outside range - if (idx >= m_value.array->size()) - { -#if JSON_DIAGNOSTICS - // remember array size & capacity before resizing - const auto old_size = m_value.array->size(); - const auto old_capacity = m_value.array->capacity(); -#endif - m_value.array->resize(idx + 1); - -#if JSON_DIAGNOSTICS - if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) - { - // capacity has changed: update all parents - set_parents(); - } - else - { - // set parent for values added above - set_parents(begin() + static_cast(old_size), static_cast(idx + 1 - old_size)); - } -#endif - assert_invariant(); - } - - return m_value.array->operator[](idx); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified array element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - const_reference operator[](size_type idx) const - { - // const operator[] only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - return m_value.array->operator[](idx); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - reference operator[](const typename object_t::key_type& key) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - // operator[] only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - return set_parent(m_value.object->operator[](key)); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - const_reference operator[](const typename object_t::key_type& key) const - { - // const operator[] only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); - return m_value.object->find(key)->second; - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - template - JSON_HEDLEY_NON_NULL(2) - reference operator[](T* key) - { - // implicitly convert null to object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - return set_parent(m_value.object->operator[](key)); - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - template - JSON_HEDLEY_NON_NULL(2) - const_reference operator[](T* key) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); - return m_value.object->find(key)->second; - } - - JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - /// using std::is_convertible in a std::enable_if will fail when using explicit conversions - template < class ValueType, typename std::enable_if < - detail::is_getable::value - && !std::is_same::value, int >::type = 0 > - ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - // if key is found, return value and given default value otherwise - const auto it = find(key); - if (it != end()) - { - return it->template get(); - } - - return default_value; - } - - JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - /// overload for a default value of type const char* - string_t value(const typename object_t::key_type& key, const char* default_value) const - { - return value(key, string_t(default_value)); - } - - /// @brief access specified object element via JSON Pointer with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - template::value, int>::type = 0> - ValueType value(const json_pointer& ptr, const ValueType& default_value) const - { - // at only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - // if pointer resolves a value, return it or use default value - JSON_TRY - { - return ptr.get_checked(this).template get(); - } - JSON_INTERNAL_CATCH (out_of_range&) - { - return default_value; - } - } - - JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); - } - - /// @brief access specified object element via JSON Pointer with default value - /// @sa https://json.nlohmann.me/api/basic_json/value/ - /// overload for a default value of type const char* - JSON_HEDLEY_NON_NULL(3) - string_t value(const json_pointer& ptr, const char* default_value) const - { - return value(ptr, string_t(default_value)); - } - - /// @brief access the first element - /// @sa https://json.nlohmann.me/api/basic_json/front/ - reference front() - { - return *begin(); - } - - /// @brief access the first element - /// @sa https://json.nlohmann.me/api/basic_json/front/ - const_reference front() const - { - return *cbegin(); - } - - /// @brief access the last element - /// @sa https://json.nlohmann.me/api/basic_json/back/ - reference back() - { - auto tmp = end(); - --tmp; - return *tmp; - } - - /// @brief access the last element - /// @sa https://json.nlohmann.me/api/basic_json/back/ - const_reference back() const - { - auto tmp = cend(); - --tmp; - return *tmp; - } - - /// @brief remove element given an iterator - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - template < class IteratorType, typename std::enable_if < - std::is_same::value || - std::is_same::value, int >::type - = 0 > - IteratorType erase(IteratorType pos) - { - // make sure iterator fits the current value - if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - IteratorType result = end(); - - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - case value_t::binary: - { - if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) - { - JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); - } - - if (is_string()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.string); - std::allocator_traits::deallocate(alloc, m_value.string, 1); - m_value.string = nullptr; - } - else if (is_binary()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.binary); - std::allocator_traits::deallocate(alloc, m_value.binary, 1); - m_value.binary = nullptr; - } - - m_type = value_t::null; - assert_invariant(); - break; - } - - case value_t::object: - { - result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); - break; - } - - case value_t::array: - { - result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); - break; - } - - case value_t::null: - case value_t::discarded: - default: - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - - return result; - } - - /// @brief remove elements given an iterator range - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - template < class IteratorType, typename std::enable_if < - std::is_same::value || - std::is_same::value, int >::type - = 0 > - IteratorType erase(IteratorType first, IteratorType last) - { - // make sure iterator fits the current value - if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) - { - JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); - } - - IteratorType result = end(); - - switch (m_type) - { - case value_t::boolean: - case value_t::number_float: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::string: - case value_t::binary: - { - if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() - || !last.m_it.primitive_iterator.is_end())) - { - JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); - } - - if (is_string()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.string); - std::allocator_traits::deallocate(alloc, m_value.string, 1); - m_value.string = nullptr; - } - else if (is_binary()) - { - AllocatorType alloc; - std::allocator_traits::destroy(alloc, m_value.binary); - std::allocator_traits::deallocate(alloc, m_value.binary, 1); - m_value.binary = nullptr; - } - - m_type = value_t::null; - assert_invariant(); - break; - } - - case value_t::object: - { - result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, - last.m_it.object_iterator); - break; - } - - case value_t::array: - { - result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, - last.m_it.array_iterator); - break; - } - - case value_t::null: - case value_t::discarded: - default: - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - - return result; - } - - /// @brief remove element from a JSON object given a key - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - size_type erase(const typename object_t::key_type& key) - { - // this erase only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - return m_value.object->erase(key); - } - - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - - /// @brief remove element from a JSON array given an index - /// @sa https://json.nlohmann.me/api/basic_json/erase/ - void erase(const size_type idx) - { - // this erase only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - if (JSON_HEDLEY_UNLIKELY(idx >= size())) - { - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); - } - - m_value.array->erase(m_value.array->begin() + static_cast(idx)); - } - else - { - JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); - } - } - - /// @} - - - //////////// - // lookup // - //////////// - - /// @name lookup - /// @{ - - /// @brief find an element in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/find/ - template - iterator find(KeyT&& key) - { - auto result = end(); - - if (is_object()) - { - result.m_it.object_iterator = m_value.object->find(std::forward(key)); - } - - return result; - } - - /// @brief find an element in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/find/ - template - const_iterator find(KeyT&& key) const - { - auto result = cend(); - - if (is_object()) - { - result.m_it.object_iterator = m_value.object->find(std::forward(key)); - } - - return result; - } - - /// @brief returns the number of occurrences of a key in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/count/ - template - size_type count(KeyT&& key) const - { - // return 0 for all nonobject types - return is_object() ? m_value.object->count(std::forward(key)) : 0; - } - - /// @brief check the existence of an element in a JSON object - /// @sa https://json.nlohmann.me/api/basic_json/contains/ - template < typename KeyT, typename std::enable_if < - !std::is_same::type, json_pointer>::value, int >::type = 0 > - bool contains(KeyT && key) const - { - return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); - } - - /// @brief check the existence of an element in a JSON object given a JSON pointer - /// @sa https://json.nlohmann.me/api/basic_json/contains/ - bool contains(const json_pointer& ptr) const - { - return ptr.contains(this); - } - - /// @} - - - /////////////// - // iterators // - /////////////// - - /// @name iterators - /// @{ - - /// @brief returns an iterator to the first element - /// @sa https://json.nlohmann.me/api/basic_json/begin/ - iterator begin() noexcept - { - iterator result(this); - result.set_begin(); - return result; - } - - /// @brief returns an iterator to the first element - /// @sa https://json.nlohmann.me/api/basic_json/begin/ - const_iterator begin() const noexcept - { - return cbegin(); - } - - /// @brief returns a const iterator to the first element - /// @sa https://json.nlohmann.me/api/basic_json/cbegin/ - const_iterator cbegin() const noexcept - { - const_iterator result(this); - result.set_begin(); - return result; - } - - /// @brief returns an iterator to one past the last element - /// @sa https://json.nlohmann.me/api/basic_json/end/ - iterator end() noexcept - { - iterator result(this); - result.set_end(); - return result; - } - - /// @brief returns an iterator to one past the last element - /// @sa https://json.nlohmann.me/api/basic_json/end/ - const_iterator end() const noexcept - { - return cend(); - } - - /// @brief returns an iterator to one past the last element - /// @sa https://json.nlohmann.me/api/basic_json/cend/ - const_iterator cend() const noexcept - { - const_iterator result(this); - result.set_end(); - return result; - } - - /// @brief returns an iterator to the reverse-beginning - /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ - reverse_iterator rbegin() noexcept - { - return reverse_iterator(end()); - } - - /// @brief returns an iterator to the reverse-beginning - /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ - const_reverse_iterator rbegin() const noexcept - { - return crbegin(); - } - - /// @brief returns an iterator to the reverse-end - /// @sa https://json.nlohmann.me/api/basic_json/rend/ - reverse_iterator rend() noexcept - { - return reverse_iterator(begin()); - } - - /// @brief returns an iterator to the reverse-end - /// @sa https://json.nlohmann.me/api/basic_json/rend/ - const_reverse_iterator rend() const noexcept - { - return crend(); - } - - /// @brief returns a const reverse iterator to the last element - /// @sa https://json.nlohmann.me/api/basic_json/crbegin/ - const_reverse_iterator crbegin() const noexcept - { - return const_reverse_iterator(cend()); - } - - /// @brief returns a const reverse iterator to one before the first - /// @sa https://json.nlohmann.me/api/basic_json/crend/ - const_reverse_iterator crend() const noexcept - { - return const_reverse_iterator(cbegin()); - } - - public: - /// @brief wrapper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - /// @deprecated This function is deprecated since 3.1.0 and will be removed in - /// version 4.0.0 of the library. Please use @ref items() instead; - /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. - JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) - static iteration_proxy iterator_wrapper(reference ref) noexcept - { - return ref.items(); - } - - /// @brief wrapper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - /// @deprecated This function is deprecated since 3.1.0 and will be removed in - /// version 4.0.0 of the library. Please use @ref items() instead; - /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. - JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) - static iteration_proxy iterator_wrapper(const_reference ref) noexcept - { - return ref.items(); - } - - /// @brief helper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - iteration_proxy items() noexcept - { - return iteration_proxy(*this); - } - - /// @brief helper to access iterator member functions in range-based for - /// @sa https://json.nlohmann.me/api/basic_json/items/ - iteration_proxy items() const noexcept - { - return iteration_proxy(*this); - } - - /// @} - - - ////////////// - // capacity // - ////////////// - - /// @name capacity - /// @{ - - /// @brief checks whether the container is empty. - /// @sa https://json.nlohmann.me/api/basic_json/empty/ - bool empty() const noexcept - { - switch (m_type) - { - case value_t::null: - { - // null values are empty - return true; - } - - case value_t::array: - { - // delegate call to array_t::empty() - return m_value.array->empty(); - } - - case value_t::object: - { - // delegate call to object_t::empty() - return m_value.object->empty(); - } - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // all other types are nonempty - return false; - } - } - } - - /// @brief returns the number of elements - /// @sa https://json.nlohmann.me/api/basic_json/size/ - size_type size() const noexcept - { - switch (m_type) - { - case value_t::null: - { - // null values are empty - return 0; - } - - case value_t::array: - { - // delegate call to array_t::size() - return m_value.array->size(); - } - - case value_t::object: - { - // delegate call to object_t::size() - return m_value.object->size(); - } - - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // all other types have size 1 - return 1; - } - } - } - - /// @brief returns the maximum possible number of elements - /// @sa https://json.nlohmann.me/api/basic_json/max_size/ - size_type max_size() const noexcept - { - switch (m_type) - { - case value_t::array: - { - // delegate call to array_t::max_size() - return m_value.array->max_size(); - } - - case value_t::object: - { - // delegate call to object_t::max_size() - return m_value.object->max_size(); - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // all other types have max_size() == size() - return size(); - } - } - } - - /// @} - - - /////////////// - // modifiers // - /////////////// - - /// @name modifiers - /// @{ - - /// @brief clears the contents - /// @sa https://json.nlohmann.me/api/basic_json/clear/ - void clear() noexcept - { - switch (m_type) - { - case value_t::number_integer: - { - m_value.number_integer = 0; - break; - } - - case value_t::number_unsigned: - { - m_value.number_unsigned = 0; - break; - } - - case value_t::number_float: - { - m_value.number_float = 0.0; - break; - } - - case value_t::boolean: - { - m_value.boolean = false; - break; - } - - case value_t::string: - { - m_value.string->clear(); - break; - } - - case value_t::binary: - { - m_value.binary->clear(); - break; - } - - case value_t::array: - { - m_value.array->clear(); - break; - } - - case value_t::object: - { - m_value.object->clear(); - break; - } - - case value_t::null: - case value_t::discarded: - default: - break; - } - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(basic_json&& val) - { - // push_back only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array (move semantics) - const auto old_capacity = m_value.array->capacity(); - m_value.array->push_back(std::move(val)); - set_parent(m_value.array->back(), old_capacity); - // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(basic_json&& val) - { - push_back(std::move(val)); - return *this; - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(const basic_json& val) - { - // push_back only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array - const auto old_capacity = m_value.array->capacity(); - m_value.array->push_back(val); - set_parent(m_value.array->back(), old_capacity); - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(const basic_json& val) - { - push_back(val); - return *this; - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(const typename object_t::value_type& val) - { - // push_back only works for null objects or objects - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) - { - JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // add element to object - auto res = m_value.object->insert(val); - set_parent(res.first->second); - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(const typename object_t::value_type& val) - { - push_back(val); - return *this; - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/push_back/ - void push_back(initializer_list_t init) - { - if (is_object() && init.size() == 2 && (*init.begin())->is_string()) - { - basic_json&& key = init.begin()->moved_or_copied(); - push_back(typename object_t::value_type( - std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); - } - else - { - push_back(basic_json(init)); - } - } - - /// @brief add an object to an object - /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ - reference operator+=(initializer_list_t init) - { - push_back(init); - return *this; - } - - /// @brief add an object to an array - /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/ - template - reference emplace_back(Args&& ... args) - { - // emplace_back only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) - { - JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); - } - - // transform null object into an array - if (is_null()) - { - m_type = value_t::array; - m_value = value_t::array; - assert_invariant(); - } - - // add element to array (perfect forwarding) - const auto old_capacity = m_value.array->capacity(); - m_value.array->emplace_back(std::forward(args)...); - return set_parent(m_value.array->back(), old_capacity); - } - - /// @brief add an object to an object if key does not exist - /// @sa https://json.nlohmann.me/api/basic_json/emplace/ - template - std::pair emplace(Args&& ... args) - { - // emplace only works for null objects or arrays - if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) - { - JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); - } - - // transform null object into an object - if (is_null()) - { - m_type = value_t::object; - m_value = value_t::object; - assert_invariant(); - } - - // add element to array (perfect forwarding) - auto res = m_value.object->emplace(std::forward(args)...); - set_parent(res.first->second); - - // create result iterator and set iterator to the result of emplace - auto it = begin(); - it.m_it.object_iterator = res.first; - - // return pair of iterator and boolean - return {it, res.second}; - } - - /// Helper for insertion of an iterator - /// @note: This uses std::distance to support GCC 4.8, - /// see https://github.com/nlohmann/json/pull/1257 - template - iterator insert_iterator(const_iterator pos, Args&& ... args) - { - iterator result(this); - JSON_ASSERT(m_value.array != nullptr); - - auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); - m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); - result.m_it.array_iterator = m_value.array->begin() + insert_pos; - - // This could have been written as: - // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); - // but the return value of insert is missing in GCC 4.8, so it is written this way instead. - - set_parents(); - return result; - } - - /// @brief inserts element into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, const basic_json& val) - { - // insert only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, val); - } - - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - /// @brief inserts element into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, basic_json&& val) - { - return insert(pos, val); - } - - /// @brief inserts copies of element into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, size_type cnt, const basic_json& val) - { - // insert only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, cnt, val); - } - - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - /// @brief inserts range of elements into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, const_iterator first, const_iterator last) - { - // insert only works for arrays - if (JSON_HEDLEY_UNLIKELY(!is_array())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // check if range iterators belong to the same JSON object - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); - } - - if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) - { - JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); - } - - /// @brief inserts elements from initializer list into array - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - iterator insert(const_iterator pos, initializer_list_t ilist) - { - // insert only works for arrays - if (JSON_HEDLEY_UNLIKELY(!is_array())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - // check if iterator pos fits to this JSON value - if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) - { - JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); - } - - // insert to array and return iterator - return insert_iterator(pos, ilist.begin(), ilist.end()); - } - - /// @brief inserts range of elements into object - /// @sa https://json.nlohmann.me/api/basic_json/insert/ - void insert(const_iterator first, const_iterator last) - { - // insert only works for objects - if (JSON_HEDLEY_UNLIKELY(!is_object())) - { - JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); - } - - // check if range iterators belong to the same JSON object - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); - } - - // passed iterators must belong to objects - if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) - { - JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); - } - - m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); - } - - /// @brief updates a JSON object from another object, overwriting existing keys - /// @sa https://json.nlohmann.me/api/basic_json/update/ - void update(const_reference j, bool merge_objects = false) - { - update(j.begin(), j.end(), merge_objects); - } - - /// @brief updates a JSON object from another object, overwriting existing keys - /// @sa https://json.nlohmann.me/api/basic_json/update/ - void update(const_iterator first, const_iterator last, bool merge_objects = false) - { - // implicitly convert null value to an empty object - if (is_null()) - { - m_type = value_t::object; - m_value.object = create(); - assert_invariant(); - } - - if (JSON_HEDLEY_UNLIKELY(!is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); - } - - // check if range iterators belong to the same JSON object - if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) - { - JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); - } - - // passed iterators must belong to objects - if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) - { - JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object)); - } - - for (auto it = first; it != last; ++it) - { - if (merge_objects && it.value().is_object()) - { - auto it2 = m_value.object->find(it.key()); - if (it2 != m_value.object->end()) - { - it2->second.update(it.value(), true); - continue; - } - } - m_value.object->operator[](it.key()) = it.value(); -#if JSON_DIAGNOSTICS - m_value.object->operator[](it.key()).m_parent = this; -#endif - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(reference other) noexcept ( - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value - ) - { - std::swap(m_type, other.m_type); - std::swap(m_value, other.m_value); - - set_parents(); - other.set_parents(); - assert_invariant(); - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - friend void swap(reference left, reference right) noexcept ( - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value&& - std::is_nothrow_move_constructible::value&& - std::is_nothrow_move_assignable::value - ) - { - left.swap(right); - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(array_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for arrays - if (JSON_HEDLEY_LIKELY(is_array())) - { - std::swap(*(m_value.array), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(object_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for objects - if (JSON_HEDLEY_LIKELY(is_object())) - { - std::swap(*(m_value.object), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(string_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for strings - if (JSON_HEDLEY_LIKELY(is_string())) - { - std::swap(*(m_value.string), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(binary_t& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for strings - if (JSON_HEDLEY_LIKELY(is_binary())) - { - std::swap(*(m_value.binary), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @brief exchanges the values - /// @sa https://json.nlohmann.me/api/basic_json/swap/ - void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) - { - // swap only works for strings - if (JSON_HEDLEY_LIKELY(is_binary())) - { - std::swap(*(m_value.binary), other); - } - else - { - JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); - } - } - - /// @} - - public: - ////////////////////////////////////////// - // lexicographical comparison operators // - ////////////////////////////////////////// - - /// @name lexicographical comparison operators - /// @{ - - /// @brief comparison: equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ - friend bool operator==(const_reference lhs, const_reference rhs) noexcept - { -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" -#endif - const auto lhs_type = lhs.type(); - const auto rhs_type = rhs.type(); - - if (lhs_type == rhs_type) - { - switch (lhs_type) - { - case value_t::array: - return *lhs.m_value.array == *rhs.m_value.array; - - case value_t::object: - return *lhs.m_value.object == *rhs.m_value.object; - - case value_t::null: - return true; - - case value_t::string: - return *lhs.m_value.string == *rhs.m_value.string; - - case value_t::boolean: - return lhs.m_value.boolean == rhs.m_value.boolean; - - case value_t::number_integer: - return lhs.m_value.number_integer == rhs.m_value.number_integer; - - case value_t::number_unsigned: - return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; - - case value_t::number_float: - return lhs.m_value.number_float == rhs.m_value.number_float; - - case value_t::binary: - return *lhs.m_value.binary == *rhs.m_value.binary; - - case value_t::discarded: - default: - return false; - } - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) - { - return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) - { - return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); - } - - return false; -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif - } - - /// @brief comparison: equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ - template::value, int>::type = 0> - friend bool operator==(const_reference lhs, ScalarType rhs) noexcept - { - return lhs == basic_json(rhs); - } - - /// @brief comparison: equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ - template::value, int>::type = 0> - friend bool operator==(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) == rhs; - } - - /// @brief comparison: not equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ - friend bool operator!=(const_reference lhs, const_reference rhs) noexcept - { - return !(lhs == rhs); - } - - /// @brief comparison: not equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ - template::value, int>::type = 0> - friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept - { - return lhs != basic_json(rhs); - } - - /// @brief comparison: not equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ - template::value, int>::type = 0> - friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) != rhs; - } - - /// @brief comparison: less than - /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ - friend bool operator<(const_reference lhs, const_reference rhs) noexcept - { - const auto lhs_type = lhs.type(); - const auto rhs_type = rhs.type(); - - if (lhs_type == rhs_type) - { - switch (lhs_type) - { - case value_t::array: - // note parentheses are necessary, see - // https://github.com/nlohmann/json/issues/1530 - return (*lhs.m_value.array) < (*rhs.m_value.array); - - case value_t::object: - return (*lhs.m_value.object) < (*rhs.m_value.object); - - case value_t::null: - return false; - - case value_t::string: - return (*lhs.m_value.string) < (*rhs.m_value.string); - - case value_t::boolean: - return (lhs.m_value.boolean) < (rhs.m_value.boolean); - - case value_t::number_integer: - return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); - - case value_t::number_unsigned: - return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); - - case value_t::number_float: - return (lhs.m_value.number_float) < (rhs.m_value.number_float); - - case value_t::binary: - return (*lhs.m_value.binary) < (*rhs.m_value.binary); - - case value_t::discarded: - default: - return false; - } - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) - { - return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) - { - return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; - } - else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) - { - return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); - } - else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) - { - return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; - } - - // We only reach this line if we cannot compare values. In that case, - // we compare types. Note we have to call the operator explicitly, - // because MSVC has problems otherwise. - return operator<(lhs_type, rhs_type); - } - - /// @brief comparison: less than - /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ - template::value, int>::type = 0> - friend bool operator<(const_reference lhs, ScalarType rhs) noexcept - { - return lhs < basic_json(rhs); - } - - /// @brief comparison: less than - /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ - template::value, int>::type = 0> - friend bool operator<(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) < rhs; - } - - /// @brief comparison: less than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ - friend bool operator<=(const_reference lhs, const_reference rhs) noexcept - { - return !(rhs < lhs); - } - - /// @brief comparison: less than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ - template::value, int>::type = 0> - friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept - { - return lhs <= basic_json(rhs); - } - - /// @brief comparison: less than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ - template::value, int>::type = 0> - friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) <= rhs; - } - - /// @brief comparison: greater than - /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ - friend bool operator>(const_reference lhs, const_reference rhs) noexcept - { - return !(lhs <= rhs); - } - - /// @brief comparison: greater than - /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ - template::value, int>::type = 0> - friend bool operator>(const_reference lhs, ScalarType rhs) noexcept - { - return lhs > basic_json(rhs); - } - - /// @brief comparison: greater than - /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ - template::value, int>::type = 0> - friend bool operator>(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) > rhs; - } - - /// @brief comparison: greater than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ - friend bool operator>=(const_reference lhs, const_reference rhs) noexcept - { - return !(lhs < rhs); - } - - /// @brief comparison: greater than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ - template::value, int>::type = 0> - friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept - { - return lhs >= basic_json(rhs); - } - - /// @brief comparison: greater than or equal - /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ - template::value, int>::type = 0> - friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept - { - return basic_json(lhs) >= rhs; - } - - /// @} - - /////////////////// - // serialization // - /////////////////// - - /// @name serialization - /// @{ -#ifndef JSON_NO_IO - /// @brief serialize to stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ - friend std::ostream& operator<<(std::ostream& o, const basic_json& j) - { - // read width member and use it as indentation parameter if nonzero - const bool pretty_print = o.width() > 0; - const auto indentation = pretty_print ? o.width() : 0; - - // reset width to 0 for subsequent calls to this stream - o.width(0); - - // do the actual serialization - serializer s(detail::output_adapter(o), o.fill()); - s.dump(j, pretty_print, false, static_cast(indentation)); - return o; - } - - /// @brief serialize to stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ - /// @deprecated This function is deprecated since 3.0.0 and will be removed in - /// version 4.0.0 of the library. Please use - /// operator<<(std::ostream&, const basic_json&) instead; that is, - /// replace calls like `j >> o;` with `o << j;`. - JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) - friend std::ostream& operator>>(const basic_json& j, std::ostream& o) - { - return o << j; - } -#endif // JSON_NO_IO - /// @} - - - ///////////////////// - // deserialization // - ///////////////////// - - /// @name deserialization - /// @{ - - /// @brief deserialize from a compatible input - /// @sa https://json.nlohmann.me/api/basic_json/parse/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json parse(InputType&& i, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false) - { - basic_json result; - parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); - return result; - } - - /// @brief deserialize from a pair of character iterators - /// @sa https://json.nlohmann.me/api/basic_json/parse/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json parse(IteratorType first, - IteratorType last, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false) - { - basic_json result; - parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); - return result; - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) - static basic_json parse(detail::span_input_adapter&& i, - const parser_callback_t cb = nullptr, - const bool allow_exceptions = true, - const bool ignore_comments = false) - { - basic_json result; - parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); - return result; - } - - /// @brief check if the input is valid JSON - /// @sa https://json.nlohmann.me/api/basic_json/accept/ - template - static bool accept(InputType&& i, - const bool ignore_comments = false) - { - return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); - } - - /// @brief check if the input is valid JSON - /// @sa https://json.nlohmann.me/api/basic_json/accept/ - template - static bool accept(IteratorType first, IteratorType last, - const bool ignore_comments = false) - { - return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) - static bool accept(detail::span_input_adapter&& i, - const bool ignore_comments = false) - { - return parser(i.get(), nullptr, false, ignore_comments).accept(true); - } - - /// @brief generate SAX events - /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ - template - JSON_HEDLEY_NON_NULL(2) - static bool sax_parse(InputType&& i, SAX* sax, - input_format_t format = input_format_t::json, - const bool strict = true, - const bool ignore_comments = false) - { - auto ia = detail::input_adapter(std::forward(i)); - return format == input_format_t::json - ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) - : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); - } - - /// @brief generate SAX events - /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ - template - JSON_HEDLEY_NON_NULL(3) - static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, - input_format_t format = input_format_t::json, - const bool strict = true, - const bool ignore_comments = false) - { - auto ia = detail::input_adapter(std::move(first), std::move(last)); - return format == input_format_t::json - ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) - : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); - } - - /// @brief generate SAX events - /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ - /// @deprecated This function is deprecated since 3.8.0 and will be removed in - /// version 4.0.0 of the library. Please use - /// sax_parse(ptr, ptr + len) instead. - template - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) - JSON_HEDLEY_NON_NULL(2) - static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, - input_format_t format = input_format_t::json, - const bool strict = true, - const bool ignore_comments = false) - { - auto ia = i.get(); - return format == input_format_t::json - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); - } -#ifndef JSON_NO_IO - /// @brief deserialize from stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ - /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in - /// version 4.0.0 of the library. Please use - /// operator>>(std::istream&, basic_json&) instead; that is, - /// replace calls like `j << i;` with `i >> j;`. - JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) - friend std::istream& operator<<(basic_json& j, std::istream& i) - { - return operator>>(i, j); - } - - /// @brief deserialize from stream - /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ - friend std::istream& operator>>(std::istream& i, basic_json& j) - { - parser(detail::input_adapter(i)).parse(false, j); - return i; - } -#endif // JSON_NO_IO - /// @} - - /////////////////////////// - // convenience functions // - /////////////////////////// - - /// @brief return the type as string - /// @sa https://json.nlohmann.me/api/basic_json/type_name/ - JSON_HEDLEY_RETURNS_NON_NULL - const char* type_name() const noexcept - { - switch (m_type) - { - case value_t::null: - return "null"; - case value_t::object: - return "object"; - case value_t::array: - return "array"; - case value_t::string: - return "string"; - case value_t::boolean: - return "boolean"; - case value_t::binary: - return "binary"; - case value_t::discarded: - return "discarded"; - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - default: - return "number"; - } - } - - - JSON_PRIVATE_UNLESS_TESTED: - ////////////////////// - // member variables // - ////////////////////// - - /// the type of the current element - value_t m_type = value_t::null; - - /// the value of the current element - json_value m_value = {}; - -#if JSON_DIAGNOSTICS - /// a pointer to a parent value (for debugging purposes) - basic_json* m_parent = nullptr; -#endif - - ////////////////////////////////////////// - // binary serialization/deserialization // - ////////////////////////////////////////// - - /// @name binary serialization/deserialization support - /// @{ - - public: - /// @brief create a CBOR serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ - static std::vector to_cbor(const basic_json& j) - { - std::vector result; - to_cbor(j, result); - return result; - } - - /// @brief create a CBOR serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ - static void to_cbor(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_cbor(j); - } - - /// @brief create a CBOR serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ - static void to_cbor(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_cbor(j); - } - - /// @brief create a MessagePack serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ - static std::vector to_msgpack(const basic_json& j) - { - std::vector result; - to_msgpack(j, result); - return result; - } - - /// @brief create a MessagePack serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ - static void to_msgpack(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_msgpack(j); - } - - /// @brief create a MessagePack serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ - static void to_msgpack(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_msgpack(j); - } - - /// @brief create a UBJSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ - static std::vector to_ubjson(const basic_json& j, - const bool use_size = false, - const bool use_type = false) - { - std::vector result; - to_ubjson(j, result, use_size, use_type); - return result; - } - - /// @brief create a UBJSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ - static void to_ubjson(const basic_json& j, detail::output_adapter o, - const bool use_size = false, const bool use_type = false) - { - binary_writer(o).write_ubjson(j, use_size, use_type); - } - - /// @brief create a UBJSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ - static void to_ubjson(const basic_json& j, detail::output_adapter o, - const bool use_size = false, const bool use_type = false) - { - binary_writer(o).write_ubjson(j, use_size, use_type); - } - - /// @brief create a BSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ - static std::vector to_bson(const basic_json& j) - { - std::vector result; - to_bson(j, result); - return result; - } - - /// @brief create a BSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ - static void to_bson(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_bson(j); - } - - /// @brief create a BSON serialization of a given JSON value - /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ - static void to_bson(const basic_json& j, detail::output_adapter o) - { - binary_writer(o).write_bson(j); - } - - /// @brief create a JSON value from an input in CBOR format - /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_cbor(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in CBOR format - /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_cbor(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) - static basic_json from_cbor(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); - } - - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) - static basic_json from_cbor(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true, - const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in MessagePack format - /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_msgpack(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in MessagePack format - /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_msgpack(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) - static basic_json from_msgpack(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true) - { - return from_msgpack(ptr, ptr + len, strict, allow_exceptions); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) - static basic_json from_msgpack(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in UBJSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_ubjson(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in UBJSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_ubjson(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) - static basic_json from_ubjson(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true) - { - return from_ubjson(ptr, ptr + len, strict, allow_exceptions); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) - static basic_json from_ubjson(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in BSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_bson(InputType&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::forward(i)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - /// @brief create a JSON value from an input in BSON format - /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ - template - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json from_bson(IteratorType first, IteratorType last, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = detail::input_adapter(std::move(first), std::move(last)); - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - - template - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) - static basic_json from_bson(const T* ptr, std::size_t len, - const bool strict = true, - const bool allow_exceptions = true) - { - return from_bson(ptr, ptr + len, strict, allow_exceptions); - } - - JSON_HEDLEY_WARN_UNUSED_RESULT - JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) - static basic_json from_bson(detail::span_input_adapter&& i, - const bool strict = true, - const bool allow_exceptions = true) - { - basic_json result; - detail::json_sax_dom_parser sdp(result, allow_exceptions); - auto ia = i.get(); - // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) - const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); - return res ? result : basic_json(value_t::discarded); - } - /// @} - - ////////////////////////// - // JSON Pointer support // - ////////////////////////// - - /// @name JSON Pointer functions - /// @{ - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - reference operator[](const json_pointer& ptr) - { - return ptr.get_unchecked(this); - } - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ - const_reference operator[](const json_pointer& ptr) const - { - return ptr.get_unchecked(this); - } - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/at/ - reference at(const json_pointer& ptr) - { - return ptr.get_checked(this); - } - - /// @brief access specified element via JSON Pointer - /// @sa https://json.nlohmann.me/api/basic_json/at/ - const_reference at(const json_pointer& ptr) const - { - return ptr.get_checked(this); - } - - /// @brief return flattened JSON value - /// @sa https://json.nlohmann.me/api/basic_json/flatten/ - basic_json flatten() const - { - basic_json result(value_t::object); - json_pointer::flatten("", *this, result); - return result; - } - - /// @brief unflatten a previously flattened JSON value - /// @sa https://json.nlohmann.me/api/basic_json/unflatten/ - basic_json unflatten() const - { - return json_pointer::unflatten(*this); - } - - /// @} - - ////////////////////////// - // JSON Patch functions // - ////////////////////////// - - /// @name JSON Patch functions - /// @{ - - /// @brief applies a JSON patch - /// @sa https://json.nlohmann.me/api/basic_json/patch/ - basic_json patch(const basic_json& json_patch) const - { - // make a working copy to apply the patch to - basic_json result = *this; - - // the valid JSON Patch operations - enum class patch_operations {add, remove, replace, move, copy, test, invalid}; - - const auto get_op = [](const std::string & op) - { - if (op == "add") - { - return patch_operations::add; - } - if (op == "remove") - { - return patch_operations::remove; - } - if (op == "replace") - { - return patch_operations::replace; - } - if (op == "move") - { - return patch_operations::move; - } - if (op == "copy") - { - return patch_operations::copy; - } - if (op == "test") - { - return patch_operations::test; - } - - return patch_operations::invalid; - }; - - // wrapper for "add" operation; add value at ptr - const auto operation_add = [&result](json_pointer & ptr, basic_json val) - { - // adding to the root of the target document means replacing it - if (ptr.empty()) - { - result = val; - return; - } - - // make sure the top element of the pointer exists - json_pointer top_pointer = ptr.top(); - if (top_pointer != ptr) - { - result.at(top_pointer); - } - - // get reference to parent of JSON pointer ptr - const auto last_path = ptr.back(); - ptr.pop_back(); - basic_json& parent = result[ptr]; - - switch (parent.m_type) - { - case value_t::null: - case value_t::object: - { - // use operator[] to add value - parent[last_path] = val; - break; - } - - case value_t::array: - { - if (last_path == "-") - { - // special case: append to back - parent.push_back(val); - } - else - { - const auto idx = json_pointer::array_index(last_path); - if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) - { - // avoid undefined behavior - JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); - } - - // default case: insert add offset - parent.insert(parent.begin() + static_cast(idx), val); - } - break; - } - - // if there exists a parent it cannot be primitive - case value_t::string: // LCOV_EXCL_LINE - case value_t::boolean: // LCOV_EXCL_LINE - case value_t::number_integer: // LCOV_EXCL_LINE - case value_t::number_unsigned: // LCOV_EXCL_LINE - case value_t::number_float: // LCOV_EXCL_LINE - case value_t::binary: // LCOV_EXCL_LINE - case value_t::discarded: // LCOV_EXCL_LINE - default: // LCOV_EXCL_LINE - JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE - } - }; - - // wrapper for "remove" operation; remove value at ptr - const auto operation_remove = [this, &result](json_pointer & ptr) - { - // get reference to parent of JSON pointer ptr - const auto last_path = ptr.back(); - ptr.pop_back(); - basic_json& parent = result.at(ptr); - - // remove child - if (parent.is_object()) - { - // perform range check - auto it = parent.find(last_path); - if (JSON_HEDLEY_LIKELY(it != parent.end())) - { - parent.erase(it); - } - else - { - JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); - } - } - else if (parent.is_array()) - { - // note erase performs range check - parent.erase(json_pointer::array_index(last_path)); - } - }; - - // type check: top level value must be an array - if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) - { - JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); - } - - // iterate and apply the operations - for (const auto& val : json_patch) - { - // wrapper to get a value for an operation - const auto get_value = [&val](const std::string & op, - const std::string & member, - bool string_type) -> basic_json & - { - // find value - auto it = val.m_value.object->find(member); - - // context-sensitive error message - const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; - - // check if desired value is present - if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) - { - // NOLINTNEXTLINE(performance-inefficient-string-concatenation) - JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); - } - - // check if result is of type string - if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) - { - // NOLINTNEXTLINE(performance-inefficient-string-concatenation) - JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); - } - - // no error: return value - return it->second; - }; - - // type check: every element of the array must be an object - if (JSON_HEDLEY_UNLIKELY(!val.is_object())) - { - JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); - } - - // collect mandatory members - const auto op = get_value("op", "op", true).template get(); - const auto path = get_value(op, "path", true).template get(); - json_pointer ptr(path); - - switch (get_op(op)) - { - case patch_operations::add: - { - operation_add(ptr, get_value("add", "value", false)); - break; - } - - case patch_operations::remove: - { - operation_remove(ptr); - break; - } - - case patch_operations::replace: - { - // the "path" location must exist - use at() - result.at(ptr) = get_value("replace", "value", false); - break; - } - - case patch_operations::move: - { - const auto from_path = get_value("move", "from", true).template get(); - json_pointer from_ptr(from_path); - - // the "from" location must exist - use at() - basic_json v = result.at(from_ptr); - - // The move operation is functionally identical to a - // "remove" operation on the "from" location, followed - // immediately by an "add" operation at the target - // location with the value that was just removed. - operation_remove(from_ptr); - operation_add(ptr, v); - break; - } - - case patch_operations::copy: - { - const auto from_path = get_value("copy", "from", true).template get(); - const json_pointer from_ptr(from_path); - - // the "from" location must exist - use at() - basic_json v = result.at(from_ptr); - - // The copy is functionally identical to an "add" - // operation at the target location using the value - // specified in the "from" member. - operation_add(ptr, v); - break; - } - - case patch_operations::test: - { - bool success = false; - JSON_TRY - { - // check if "value" matches the one at "path" - // the "path" location must exist - use at() - success = (result.at(ptr) == get_value("test", "value", false)); - } - JSON_INTERNAL_CATCH (out_of_range&) - { - // ignore out of range errors: success remains false - } - - // throw an exception if test fails - if (JSON_HEDLEY_UNLIKELY(!success)) - { - JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); - } - - break; - } - - case patch_operations::invalid: - default: - { - // op must be "add", "remove", "replace", "move", "copy", or - // "test" - JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); - } - } - } - - return result; - } - - /// @brief creates a diff as a JSON patch - /// @sa https://json.nlohmann.me/api/basic_json/diff/ - JSON_HEDLEY_WARN_UNUSED_RESULT - static basic_json diff(const basic_json& source, const basic_json& target, - const std::string& path = "") - { - // the patch - basic_json result(value_t::array); - - // if the values are the same, return empty patch - if (source == target) - { - return result; - } - - if (source.type() != target.type()) - { - // different types: replace value - result.push_back( - { - {"op", "replace"}, {"path", path}, {"value", target} - }); - return result; - } - - switch (source.type()) - { - case value_t::array: - { - // first pass: traverse common elements - std::size_t i = 0; - while (i < source.size() && i < target.size()) - { - // recursive call to compare array values at index i - auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); - result.insert(result.end(), temp_diff.begin(), temp_diff.end()); - ++i; - } - - // We now reached the end of at least one array - // in a second pass, traverse the remaining elements - - // remove my remaining elements - const auto end_index = static_cast(result.size()); - while (i < source.size()) - { - // add operations in reverse order to avoid invalid - // indices - result.insert(result.begin() + end_index, object( - { - {"op", "remove"}, - {"path", path + "/" + std::to_string(i)} - })); - ++i; - } - - // add other remaining elements - while (i < target.size()) - { - result.push_back( - { - {"op", "add"}, - {"path", path + "/-"}, - {"value", target[i]} - }); - ++i; - } - - break; - } - - case value_t::object: - { - // first pass: traverse this object's elements - for (auto it = source.cbegin(); it != source.cend(); ++it) - { - // escape the key name to be used in a JSON patch - const auto path_key = path + "/" + detail::escape(it.key()); - - if (target.find(it.key()) != target.end()) - { - // recursive call to compare object values at key it - auto temp_diff = diff(it.value(), target[it.key()], path_key); - result.insert(result.end(), temp_diff.begin(), temp_diff.end()); - } - else - { - // found a key that is not in o -> remove it - result.push_back(object( - { - {"op", "remove"}, {"path", path_key} - })); - } - } - - // second pass: traverse other object's elements - for (auto it = target.cbegin(); it != target.cend(); ++it) - { - if (source.find(it.key()) == source.end()) - { - // found a key that is not in this -> add it - const auto path_key = path + "/" + detail::escape(it.key()); - result.push_back( - { - {"op", "add"}, {"path", path_key}, - {"value", it.value()} - }); - } - } - - break; - } - - case value_t::null: - case value_t::string: - case value_t::boolean: - case value_t::number_integer: - case value_t::number_unsigned: - case value_t::number_float: - case value_t::binary: - case value_t::discarded: - default: - { - // both primitive type: replace value - result.push_back( - { - {"op", "replace"}, {"path", path}, {"value", target} - }); - break; - } - } - - return result; - } - - /// @} - - //////////////////////////////// - // JSON Merge Patch functions // - //////////////////////////////// - - /// @name JSON Merge Patch functions - /// @{ - - /// @brief applies a JSON Merge Patch - /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/ - void merge_patch(const basic_json& apply_patch) - { - if (apply_patch.is_object()) - { - if (!is_object()) - { - *this = object(); - } - for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) - { - if (it.value().is_null()) - { - erase(it.key()); - } - else - { - operator[](it.key()).merge_patch(it.value()); - } - } - } - else - { - *this = apply_patch; - } - } - - /// @} -}; - -/// @brief user-defined to_string function for JSON values -/// @sa https://json.nlohmann.me/api/basic_json/to_string/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) -{ - return j.dump(); -} - -} // namespace nlohmann - -/////////////////////// -// nonmember support // -/////////////////////// - -namespace std // NOLINT(cert-dcl58-cpp) -{ - -/// @brief hash value for JSON objects -/// @sa https://json.nlohmann.me/api/basic_json/std_hash/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -struct hash -{ - std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const - { - return nlohmann::detail::hash(j); - } -}; - -// specialization for std::less -template<> -struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679 -{ - /*! - @brief compare two value_t enum values - @since version 3.0.0 - */ - bool operator()(nlohmann::detail::value_t lhs, - nlohmann::detail::value_t rhs) const noexcept - { - return nlohmann::detail::operator<(lhs, rhs); - } -}; - -// C++20 prohibit function specialization in the std namespace. -#ifndef JSON_HAS_CPP_20 - -/// @brief exchanges the values of two JSON objects -/// @sa https://json.nlohmann.me/api/basic_json/std_swap/ -NLOHMANN_BASIC_JSON_TPL_DECLARATION -inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) - is_nothrow_move_constructible::value&& // NOLINT(misc-redundant-expression) - is_nothrow_move_assignable::value) -{ - j1.swap(j2); -} - -#endif - -} // namespace std - -/// @brief user-defined string literal for JSON values -/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/ -JSON_HEDLEY_NON_NULL(1) -inline nlohmann::json operator "" _json(const char* s, std::size_t n) -{ - return nlohmann::json::parse(s, s + n); -} - -/// @brief user-defined string literal for JSON pointer -/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/ -JSON_HEDLEY_NON_NULL(1) -inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) -{ - return nlohmann::json::json_pointer(std::string(s, n)); -} - -// #include - - -// restore clang diagnostic settings -#if defined(__clang__) - #pragma clang diagnostic pop -#endif - -// clean up -#undef JSON_ASSERT -#undef JSON_INTERNAL_CATCH -#undef JSON_CATCH -#undef JSON_THROW -#undef JSON_TRY -#undef JSON_PRIVATE_UNLESS_TESTED -#undef JSON_HAS_CPP_11 -#undef JSON_HAS_CPP_14 -#undef JSON_HAS_CPP_17 -#undef JSON_HAS_CPP_20 -#undef JSON_HAS_FILESYSTEM -#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM -#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION -#undef NLOHMANN_BASIC_JSON_TPL -#undef JSON_EXPLICIT -#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL - -// #include - - -#undef JSON_HEDLEY_ALWAYS_INLINE -#undef JSON_HEDLEY_ARM_VERSION -#undef JSON_HEDLEY_ARM_VERSION_CHECK -#undef JSON_HEDLEY_ARRAY_PARAM -#undef JSON_HEDLEY_ASSUME -#undef JSON_HEDLEY_BEGIN_C_DECLS -#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE -#undef JSON_HEDLEY_CLANG_HAS_BUILTIN -#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_CLANG_HAS_EXTENSION -#undef JSON_HEDLEY_CLANG_HAS_FEATURE -#undef JSON_HEDLEY_CLANG_HAS_WARNING -#undef JSON_HEDLEY_COMPCERT_VERSION -#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK -#undef JSON_HEDLEY_CONCAT -#undef JSON_HEDLEY_CONCAT3 -#undef JSON_HEDLEY_CONCAT3_EX -#undef JSON_HEDLEY_CONCAT_EX -#undef JSON_HEDLEY_CONST -#undef JSON_HEDLEY_CONSTEXPR -#undef JSON_HEDLEY_CONST_CAST -#undef JSON_HEDLEY_CPP_CAST -#undef JSON_HEDLEY_CRAY_VERSION -#undef JSON_HEDLEY_CRAY_VERSION_CHECK -#undef JSON_HEDLEY_C_DECL -#undef JSON_HEDLEY_DEPRECATED -#undef JSON_HEDLEY_DEPRECATED_FOR -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS -#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION -#undef JSON_HEDLEY_DIAGNOSTIC_POP -#undef JSON_HEDLEY_DIAGNOSTIC_PUSH -#undef JSON_HEDLEY_DMC_VERSION -#undef JSON_HEDLEY_DMC_VERSION_CHECK -#undef JSON_HEDLEY_EMPTY_BASES -#undef JSON_HEDLEY_EMSCRIPTEN_VERSION -#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK -#undef JSON_HEDLEY_END_C_DECLS -#undef JSON_HEDLEY_FLAGS -#undef JSON_HEDLEY_FLAGS_CAST -#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE -#undef JSON_HEDLEY_GCC_HAS_BUILTIN -#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_GCC_HAS_EXTENSION -#undef JSON_HEDLEY_GCC_HAS_FEATURE -#undef JSON_HEDLEY_GCC_HAS_WARNING -#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK -#undef JSON_HEDLEY_GCC_VERSION -#undef JSON_HEDLEY_GCC_VERSION_CHECK -#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE -#undef JSON_HEDLEY_GNUC_HAS_BUILTIN -#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_GNUC_HAS_EXTENSION -#undef JSON_HEDLEY_GNUC_HAS_FEATURE -#undef JSON_HEDLEY_GNUC_HAS_WARNING -#undef JSON_HEDLEY_GNUC_VERSION -#undef JSON_HEDLEY_GNUC_VERSION_CHECK -#undef JSON_HEDLEY_HAS_ATTRIBUTE -#undef JSON_HEDLEY_HAS_BUILTIN -#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE -#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS -#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE -#undef JSON_HEDLEY_HAS_EXTENSION -#undef JSON_HEDLEY_HAS_FEATURE -#undef JSON_HEDLEY_HAS_WARNING -#undef JSON_HEDLEY_IAR_VERSION -#undef JSON_HEDLEY_IAR_VERSION_CHECK -#undef JSON_HEDLEY_IBM_VERSION -#undef JSON_HEDLEY_IBM_VERSION_CHECK -#undef JSON_HEDLEY_IMPORT -#undef JSON_HEDLEY_INLINE -#undef JSON_HEDLEY_INTEL_CL_VERSION -#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK -#undef JSON_HEDLEY_INTEL_VERSION -#undef JSON_HEDLEY_INTEL_VERSION_CHECK -#undef JSON_HEDLEY_IS_CONSTANT -#undef JSON_HEDLEY_IS_CONSTEXPR_ -#undef JSON_HEDLEY_LIKELY -#undef JSON_HEDLEY_MALLOC -#undef JSON_HEDLEY_MCST_LCC_VERSION -#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK -#undef JSON_HEDLEY_MESSAGE -#undef JSON_HEDLEY_MSVC_VERSION -#undef JSON_HEDLEY_MSVC_VERSION_CHECK -#undef JSON_HEDLEY_NEVER_INLINE -#undef JSON_HEDLEY_NON_NULL -#undef JSON_HEDLEY_NO_ESCAPE -#undef JSON_HEDLEY_NO_RETURN -#undef JSON_HEDLEY_NO_THROW -#undef JSON_HEDLEY_NULL -#undef JSON_HEDLEY_PELLES_VERSION -#undef JSON_HEDLEY_PELLES_VERSION_CHECK -#undef JSON_HEDLEY_PGI_VERSION -#undef JSON_HEDLEY_PGI_VERSION_CHECK -#undef JSON_HEDLEY_PREDICT -#undef JSON_HEDLEY_PRINTF_FORMAT -#undef JSON_HEDLEY_PRIVATE -#undef JSON_HEDLEY_PUBLIC -#undef JSON_HEDLEY_PURE -#undef JSON_HEDLEY_REINTERPRET_CAST -#undef JSON_HEDLEY_REQUIRE -#undef JSON_HEDLEY_REQUIRE_CONSTEXPR -#undef JSON_HEDLEY_REQUIRE_MSG -#undef JSON_HEDLEY_RESTRICT -#undef JSON_HEDLEY_RETURNS_NON_NULL -#undef JSON_HEDLEY_SENTINEL -#undef JSON_HEDLEY_STATIC_ASSERT -#undef JSON_HEDLEY_STATIC_CAST -#undef JSON_HEDLEY_STRINGIFY -#undef JSON_HEDLEY_STRINGIFY_EX -#undef JSON_HEDLEY_SUNPRO_VERSION -#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK -#undef JSON_HEDLEY_TINYC_VERSION -#undef JSON_HEDLEY_TINYC_VERSION_CHECK -#undef JSON_HEDLEY_TI_ARMCL_VERSION -#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL2000_VERSION -#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL430_VERSION -#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL6X_VERSION -#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK -#undef JSON_HEDLEY_TI_CL7X_VERSION -#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK -#undef JSON_HEDLEY_TI_CLPRU_VERSION -#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK -#undef JSON_HEDLEY_TI_VERSION -#undef JSON_HEDLEY_TI_VERSION_CHECK -#undef JSON_HEDLEY_UNAVAILABLE -#undef JSON_HEDLEY_UNLIKELY -#undef JSON_HEDLEY_UNPREDICTABLE -#undef JSON_HEDLEY_UNREACHABLE -#undef JSON_HEDLEY_UNREACHABLE_RETURN -#undef JSON_HEDLEY_VERSION -#undef JSON_HEDLEY_VERSION_DECODE_MAJOR -#undef JSON_HEDLEY_VERSION_DECODE_MINOR -#undef JSON_HEDLEY_VERSION_DECODE_REVISION -#undef JSON_HEDLEY_VERSION_ENCODE -#undef JSON_HEDLEY_WARNING -#undef JSON_HEDLEY_WARN_UNUSED_RESULT -#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG -#undef JSON_HEDLEY_FALL_THROUGH - - - -#endif // INCLUDE_NLOHMANN_JSON_HPP_ +/* + __ _____ _____ _____ + __| | __| | | | JSON for Modern C++ +| | |__ | | | | | | version 3.10.5 +|_____|_____|_____|_|___| https://github.com/nlohmann/json + +Licensed under the MIT License . +SPDX-License-Identifier: MIT +Copyright (c) 2013-2022 Niels Lohmann . + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +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 Software. + +THE SOFTWARE IS 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 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file doc/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#define NLOHMANN_JSON_VERSION_MAJOR 3 +#define NLOHMANN_JSON_VERSION_MINOR 10 +#define NLOHMANN_JSON_VERSION_PATCH 5 + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include + + +#include +#include + +// #include + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include + + +#include // exception +#include // runtime_error +#include // to_string +#include // vector + +// #include + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +namespace nlohmann +{ +namespace detail +{ +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +} +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +// #include + + +#include // declval, pair +// #include + + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + * + * To the extent possible under law, the author(s) have dedicated all + * copyright and related and neighboring rights to this software to + * the public domain worldwide. This software is distributed without + * any warranty. + * + * For details, see . + * SPDX-License-Identifier: CC0-1.0 + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + +// #include + + +#include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; +} // namespace detail +} // namespace nlohmann + + +// https://en.cppreference.com/w/cpp/experimental/is_detected +namespace nlohmann +{ +namespace detail +{ +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; +} // namespace detail +} // namespace nlohmann + + +// This file contains all internal macro definitions +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1940 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +inline void replace_substring(std::string& s, const std::string& f, + const std::string& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != std::string::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +inline std::string escape(std::string s) +{ + replace_substring(s, "~", "~0"); + replace_substring(s, "/", "~1"); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +static void unescape(std::string& s) +{ + replace_substring(s, "~1", "/"); + replace_substring(s, "~0", "~"); +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // size_t + +namespace nlohmann +{ +namespace detail +{ +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////////// +// exceptions // +//////////////// + +/// @brief general exception of the @ref basic_json class +/// @sa https://json.nlohmann.me/api/basic_json/exception/ +class exception : public std::exception +{ + public: + /// returns the explanatory string + const char* what() const noexcept override + { + return m.what(); + } + + /// the id of the exception + const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) + + protected: + JSON_HEDLEY_NON_NULL(3) + exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) + + static std::string name(const std::string& ename, int id_) + { + return "[json.exception." + ename + "." + std::to_string(id_) + "] "; + } + + template + static std::string diagnostics(const BasicJsonType& leaf_element) + { +#if JSON_DIAGNOSTICS + std::vector tokens; + for (const auto* current = &leaf_element; current->m_parent != nullptr; current = current->m_parent) + { + switch (current->m_parent->type()) + { + case value_t::array: + { + for (std::size_t i = 0; i < current->m_parent->m_value.array->size(); ++i) + { + if (¤t->m_parent->m_value.array->operator[](i) == current) + { + tokens.emplace_back(std::to_string(i)); + break; + } + } + break; + } + + case value_t::object: + { + for (const auto& element : *current->m_parent->m_value.object) + { + if (&element.second == current) + { + tokens.emplace_back(element.first.c_str()); + break; + } + } + break; + } + + case value_t::null: // LCOV_EXCL_LINE + case value_t::string: // LCOV_EXCL_LINE + case value_t::boolean: // LCOV_EXCL_LINE + case value_t::number_integer: // LCOV_EXCL_LINE + case value_t::number_unsigned: // LCOV_EXCL_LINE + case value_t::number_float: // LCOV_EXCL_LINE + case value_t::binary: // LCOV_EXCL_LINE + case value_t::discarded: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + break; // LCOV_EXCL_LINE + } + } + + if (tokens.empty()) + { + return ""; + } + + return "(" + std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + detail::escape(b); + }) + ") "; +#else + static_cast(leaf_element); + return ""; +#endif + } + + private: + /// an exception object as storage for error messages + std::runtime_error m; +}; + +/// @brief exception indicating a parse error +/// @sa https://json.nlohmann.me/api/basic_json/parse_error/ +class parse_error : public exception +{ + public: + /*! + @brief create a parse error exception + @param[in] id_ the id of the exception + @param[in] pos the position where the error occurred (or with + chars_read_total=0 if the position cannot be + determined) + @param[in] what_arg the explanatory string + @return parse_error object + */ + template + static parse_error create(int id_, const position_t& pos, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + position_string(pos) + ": " + exception::diagnostics(context) + what_arg; + return {id_, pos.chars_read_total, w.c_str()}; + } + + template + static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("parse_error", id_) + "parse error" + + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + + ": " + exception::diagnostics(context) + what_arg; + return {id_, byte_, w.c_str()}; + } + + /*! + @brief byte index of the parse error + + The byte index of the last read character in the input file. + + @note For an input with n bytes, 1 is the index of the first character and + n+1 is the index of the terminating null byte or the end of file. + This also holds true when reading a byte vector (CBOR or MessagePack). + */ + const std::size_t byte; + + private: + parse_error(int id_, std::size_t byte_, const char* what_arg) + : exception(id_, what_arg), byte(byte_) {} + + static std::string position_string(const position_t& pos) + { + return " at line " + std::to_string(pos.lines_read + 1) + + ", column " + std::to_string(pos.chars_read_current_line); + } +}; + +/// @brief exception indicating errors with iterators +/// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ +class invalid_iterator : public exception +{ + public: + template + static invalid_iterator create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("invalid_iterator", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + invalid_iterator(int id_, const char* what_arg) + : exception(id_, what_arg) {} +}; + +/// @brief exception indicating executing a member function with a wrong type +/// @sa https://json.nlohmann.me/api/basic_json/type_error/ +class type_error : public exception +{ + public: + template + static type_error create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("type_error", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/// @brief exception indicating access out of the defined range +/// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ +class out_of_range : public exception +{ + public: + template + static out_of_range create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("out_of_range", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +/// @brief exception indicating other library errors +/// @sa https://json.nlohmann.me/api/basic_json/other_error/ +class other_error : public exception +{ + public: + template + static other_error create(int id_, const std::string& what_arg, const BasicJsonType& context) + { + std::string w = exception::name("other_error", id_) + exception::diagnostics(context) + what_arg; + return {id_, w.c_str()}; + } + + private: + JSON_HEDLEY_NON_NULL(3) + other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} +}; + +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static constexpr T value{}; +}; + +template +constexpr T static_const::value; // NOLINT(readability-redundant-declaration) + +} // namespace detail +} // namespace nlohmann + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// dispatching helper struct +template struct identity_tag {}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple + +// #include + + +// #include + + +#include // random_access_iterator_tag + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +// #include + + +namespace nlohmann +{ +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); +} // namespace nlohmann + +// #include + + +// #include + + +namespace nlohmann +{ +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); +} // namespace nlohmann + +// #include + +// #include + +// #include +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +/// a class to store JSON values +/// @sa https://json.nlohmann.me/api/basic_json/ +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document +/// @sa https://json.nlohmann.me/api/json_pointer/ +template +class json_pointer; + +/*! +@brief default specialization +@sa https://json.nlohmann.me/api/json/ +*/ +using json = basic_json<>; + +/// @brief a minimal map-like container that preserves insertion order +/// @sa https://json.nlohmann.me/api/ordered_map/ +template +struct ordered_map; + +/// @brief specialization that maintains the insertion order of object keys +/// @sa https://json.nlohmann.me/api/ordered_json/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +namespace nlohmann +{ +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B1 { }; +template +struct conjunction +: std::conditional, B1>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +// a naive helper to check if a type is an ordered_map (exploits the fact that +// ordered_map inherits capacity() from std::vector) +template +struct is_ordered_map +{ + using one = char; + + struct two + { + char x[2]; // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + }; + + template static one test( decltype(&C::capacity) ) ; + template static two test(...); + + enum { value = sizeof(test(nullptr)) == sizeof(char) }; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) +}; + +// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324) +template < typename T, typename U, enable_if_t < !std::is_same::value, int > = 0 > +T conditional_static_cast(U value) +{ + return static_cast(value); +} + +template::value, int> = 0> +T conditional_static_cast(U value) +{ + return value; +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#if JSON_HAS_EXPERIMENTAL_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::experimental::filesystem; +} // namespace nlohmann::detail +#elif JSON_HAS_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::filesystem; +} // namespace nlohmann::detail +#endif + +namespace nlohmann +{ +namespace detail +{ +template +void from_json(const BasicJsonType& j, typename std::nullptr_t& n) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_null())) + { + JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()), j)); + } + n = nullptr; +} + +// overloads for basic_json template parameters +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < std::is_arithmetic::value&& + !std::is_same::value, + int > = 0 > +void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + + case value_t::null: + case value_t::object: + case value_t::array: + case value_t::string: + case value_t::boolean: + case value_t::binary: + case value_t::discarded: + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); + } +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) + { + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()), j)); + } + b = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + s = *j.template get_ptr(); +} + +template < + typename BasicJsonType, typename ConstructibleStringType, + enable_if_t < + is_constructible_string_type::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ConstructibleStringType& s) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + + s = *j.template get_ptr(); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) +{ + get_arithmetic_value(j, val); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) +{ + get_arithmetic_value(j, val); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, EnumType& e) +{ + typename std::underlying_type::type val; + get_arithmetic_value(j, val); + e = static_cast(val); +} + +// forward_list doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::forward_list& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + l.clear(); + std::transform(j.rbegin(), j.rend(), + std::front_inserter(l), [](const BasicJsonType & i) + { + return i.template get(); + }); +} + +// valarray doesn't have an insert method +template::value, int> = 0> +void from_json(const BasicJsonType& j, std::valarray& l) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + l.resize(j.size()); + std::transform(j.begin(), j.end(), std::begin(l), + [](const BasicJsonType & elem) + { + return elem.template get(); + }); +} + +template +auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template +void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) +{ + arr = *j.template get_ptr(); +} + +template +auto from_json_array_impl(const BasicJsonType& j, std::array& arr, + priority_tag<2> /*unused*/) +-> decltype(j.template get(), void()) +{ + for (std::size_t i = 0; i < N; ++i) + { + arr[i] = j.at(i).template get(); + } +} + +template::value, + int> = 0> +auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) +-> decltype( + arr.reserve(std::declval()), + j.template get(), + void()) +{ + using std::end; + + ConstructibleArrayType ret; + ret.reserve(j.size()); + std::transform(j.begin(), j.end(), + std::inserter(ret, end(ret)), [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template::value, + int> = 0> +void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, + priority_tag<0> /*unused*/) +{ + using std::end; + + ConstructibleArrayType ret; + std::transform( + j.begin(), j.end(), std::inserter(ret, end(ret)), + [](const BasicJsonType & i) + { + // get() returns *this, this won't call a from_json + // method when value_type is BasicJsonType + return i.template get(); + }); + arr = std::move(ret); +} + +template < typename BasicJsonType, typename ConstructibleArrayType, + enable_if_t < + is_constructible_array_type::value&& + !is_constructible_object_type::value&& + !is_constructible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) +-> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), +j.template get(), +void()) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + from_json_array_impl(j, arr, priority_tag<3> {}); +} + +template < typename BasicJsonType, typename T, std::size_t... Idx > +std::array from_json_inplace_array_impl(BasicJsonType&& j, + identity_tag> /*unused*/, index_sequence /*unused*/) +{ + return { { std::forward(j).at(Idx).template get()... } }; +} + +template < typename BasicJsonType, typename T, std::size_t N > +auto from_json(BasicJsonType&& j, identity_tag> tag) +-> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); +} + +template +void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(j.type_name()), j)); + } + + bin = *j.template get_ptr(); +} + +template::value, int> = 0> +void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_object())) + { + JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()), j)); + } + + ConstructibleObjectType ret; + const auto* inner_object = j.template get_ptr(); + using value_type = typename ConstructibleObjectType::value_type; + std::transform( + inner_object->begin(), inner_object->end(), + std::inserter(ret, ret.begin()), + [](typename BasicJsonType::object_t::value_type const & p) + { + return value_type(p.first, p.second.template get()); + }); + obj = std::move(ret); +} + +// overload for arithmetic types, not chosen for basic_json template arguments +// (BooleanType, etc..); note: Is it really necessary to provide explicit +// overloads for boolean_t etc. in case of a custom BooleanType which is not +// an arithmetic type? +template < typename BasicJsonType, typename ArithmeticType, + enable_if_t < + std::is_arithmetic::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value&& + !std::is_same::value, + int > = 0 > +void from_json(const BasicJsonType& j, ArithmeticType& val) +{ + switch (static_cast(j)) + { + case value_t::number_unsigned: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_integer: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::number_float: + { + val = static_cast(*j.template get_ptr()); + break; + } + case value_t::boolean: + { + val = static_cast(*j.template get_ptr()); + break; + } + + case value_t::null: + case value_t::object: + case value_t::array: + case value_t::string: + case value_t::binary: + case value_t::discarded: + default: + JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()), j)); + } +} + +template +std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) +{ + return std::make_tuple(std::forward(j).at(Idx).template get()...); +} + +template < typename BasicJsonType, class A1, class A2 > +std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) +{ + return {std::forward(j).at(0).template get(), + std::forward(j).at(1).template get()}; +} + +template +void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) +{ + p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); +} + +template +std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) +{ + return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); +} + +template +void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) +{ + t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); +} + +template +auto from_json(BasicJsonType&& j, TupleRelated&& t) +-> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + + return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); +} + +template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, + typename = enable_if_t < !std::is_constructible < + typename BasicJsonType::string_t, Key >::value >> +void from_json(const BasicJsonType& j, std::unordered_map& m) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()), j)); + } + m.clear(); + for (const auto& p : j) + { + if (JSON_HEDLEY_UNLIKELY(!p.is_array())) + { + JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()), j)); + } + m.emplace(p.at(0).template get(), p.at(1).template get()); + } +} + +#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM +template +void from_json(const BasicJsonType& j, std_fs::path& p) +{ + if (JSON_HEDLEY_UNLIKELY(!j.is_string())) + { + JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()), j)); + } + p = *j.template get_ptr(); +} +#endif + +struct from_json_fn +{ + template + auto operator()(const BasicJsonType& j, T&& val) const + noexcept(noexcept(from_json(j, std::forward(val)))) + -> decltype(from_json(j, std::forward(val))) + { + return from_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `from_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) +{ +constexpr const auto& from_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) +} // namespace +} // namespace nlohmann + +// #include + + +#include // copy +#include // begin, end +#include // string +#include // tuple, get +#include // is_same, is_constructible, is_floating_point, is_enum, underlying_type +#include // move, forward, declval, pair +#include // valarray +#include // vector + +// #include + +// #include + + +#include // size_t +#include // input_iterator_tag +#include // string, to_string +#include // tuple_size, get, tuple_element +#include // move + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +void int_to_string( string_type& target, std::size_t value ) +{ + // For ADL + using std::to_string; + target = to_string(value); +} +template class iteration_proxy_value +{ + public: + using difference_type = std::ptrdiff_t; + using value_type = iteration_proxy_value; + using pointer = value_type * ; + using reference = value_type & ; + using iterator_category = std::input_iterator_tag; + using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; + + private: + /// the iterator + IteratorType anchor; + /// an index for arrays (used to create key names) + std::size_t array_index = 0; + /// last stringified array index + mutable std::size_t array_index_last = 0; + /// a string representation of the array index + mutable string_type array_index_str = "0"; + /// an empty string (to return a reference for primitive values) + const string_type empty_str{}; + + public: + explicit iteration_proxy_value(IteratorType it) noexcept + : anchor(std::move(it)) + {} + + /// dereference operator (needed for range-based for) + iteration_proxy_value& operator*() + { + return *this; + } + + /// increment operator (needed for range-based for) + iteration_proxy_value& operator++() + { + ++anchor; + ++array_index; + + return *this; + } + + /// equality operator (needed for InputIterator) + bool operator==(const iteration_proxy_value& o) const + { + return anchor == o.anchor; + } + + /// inequality operator (needed for range-based for) + bool operator!=(const iteration_proxy_value& o) const + { + return anchor != o.anchor; + } + + /// return key of the iterator + const string_type& key() const + { + JSON_ASSERT(anchor.m_object != nullptr); + + switch (anchor.m_object->type()) + { + // use integer array index as key + case value_t::array: + { + if (array_index != array_index_last) + { + int_to_string( array_index_str, array_index ); + array_index_last = array_index; + } + return array_index_str; + } + + // use key from the object + case value_t::object: + return anchor.key(); + + // use an empty key for all primitive types + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return empty_str; + } + } + + /// return value of the iterator + typename IteratorType::reference value() const + { + return anchor.value(); + } +}; + +/// proxy class for the items() function +template class iteration_proxy +{ + private: + /// the container to iterate + typename IteratorType::reference container; + + public: + /// construct iteration proxy from a container + explicit iteration_proxy(typename IteratorType::reference cont) noexcept + : container(cont) {} + + /// return iterator begin (needed for range-based for) + iteration_proxy_value begin() noexcept + { + return iteration_proxy_value(container.begin()); + } + + /// return iterator end (needed for range-based for) + iteration_proxy_value end() noexcept + { + return iteration_proxy_value(container.end()); + } +}; +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) +{ + return i.key(); +} +// Structured Bindings Support +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +template = 0> +auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) +{ + return i.value(); +} +} // namespace detail +} // namespace nlohmann + +// The Addition to the STD Namespace is required to add +// Structured Bindings Support to the iteration_proxy_value class +// For further reference see https://blog.tartanllama.xyz/structured-bindings/ +// And see https://github.com/nlohmann/json/pull/1391 +namespace std +{ +#if defined(__clang__) + // Fix: https://github.com/nlohmann/json/issues/1401 + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wmismatched-tags" +#endif +template +class tuple_size<::nlohmann::detail::iteration_proxy_value> + : public std::integral_constant {}; + +template +class tuple_element> +{ + public: + using type = decltype( + get(std::declval < + ::nlohmann::detail::iteration_proxy_value> ())); +}; +#if defined(__clang__) + #pragma clang diagnostic pop +#endif +} // namespace std + +// #include + +// #include + +// #include + + +#if JSON_HAS_EXPERIMENTAL_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::experimental::filesystem; +} // namespace nlohmann::detail +#elif JSON_HAS_FILESYSTEM +#include +namespace nlohmann::detail +{ +namespace std_fs = std::filesystem; +} // namespace nlohmann::detail +#endif + +namespace nlohmann +{ +namespace detail +{ +////////////////// +// constructors // +////////////////// + +/* + * Note all external_constructor<>::construct functions need to call + * j.m_value.destroy(j.m_type) to avoid a memory leak in case j contains an + * allocated value (e.g., a string). See bug issue + * https://github.com/nlohmann/json/issues/2865 for more information. + */ + +template struct external_constructor; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::boolean; + j.m_value = b; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::string; + j.m_value = s; + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::string; + j.m_value = std::move(s); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleStringType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleStringType& str) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::string; + j.m_value.string = j.template create(str); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::binary; + j.m_value = typename BasicJsonType::binary_t(b); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::binary; + j.m_value = typename BasicJsonType::binary_t(std::move(b)); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::number_float; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::number_unsigned; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::number_integer; + j.m_value = val; + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = arr; + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = std::move(arr); + j.set_parents(); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < !std::is_same::value, + int > = 0 > + static void construct(BasicJsonType& j, const CompatibleArrayType& arr) + { + using std::begin; + using std::end; + + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value.array = j.template create(begin(arr), end(arr)); + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, const std::vector& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->reserve(arr.size()); + for (const bool x : arr) + { + j.m_value.array->push_back(x); + j.set_parent(j.m_value.array->back()); + } + j.assert_invariant(); + } + + template::value, int> = 0> + static void construct(BasicJsonType& j, const std::valarray& arr) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::array; + j.m_value = value_t::array; + j.m_value.array->resize(arr.size()); + if (arr.size() > 0) + { + std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); + } + j.set_parents(); + j.assert_invariant(); + } +}; + +template<> +struct external_constructor +{ + template + static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::object; + j.m_value = obj; + j.set_parents(); + j.assert_invariant(); + } + + template + static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) + { + j.m_value.destroy(j.m_type); + j.m_type = value_t::object; + j.m_value = std::move(obj); + j.set_parents(); + j.assert_invariant(); + } + + template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < !std::is_same::value, int > = 0 > + static void construct(BasicJsonType& j, const CompatibleObjectType& obj) + { + using std::begin; + using std::end; + + j.m_value.destroy(j.m_type); + j.m_type = value_t::object; + j.m_value.object = j.template create(begin(obj), end(obj)); + j.set_parents(); + j.assert_invariant(); + } +}; + +///////////// +// to_json // +///////////// + +template::value, int> = 0> +void to_json(BasicJsonType& j, T b) noexcept +{ + external_constructor::construct(j, b); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const CompatibleString& s) +{ + external_constructor::construct(j, s); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) +{ + external_constructor::construct(j, std::move(s)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, FloatType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept +{ + external_constructor::construct(j, static_cast(val)); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, EnumType e) noexcept +{ + using underlying_type = typename std::underlying_type::type; + external_constructor::construct(j, static_cast(e)); +} + +template +void to_json(BasicJsonType& j, const std::vector& e) +{ + external_constructor::construct(j, e); +} + +template < typename BasicJsonType, typename CompatibleArrayType, + enable_if_t < is_compatible_array_type::value&& + !is_compatible_object_type::value&& + !is_compatible_string_type::value&& + !std::is_same::value&& + !is_basic_json::value, + int > = 0 > +void to_json(BasicJsonType& j, const CompatibleArrayType& arr) +{ + external_constructor::construct(j, arr); +} + +template +void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) +{ + external_constructor::construct(j, bin); +} + +template::value, int> = 0> +void to_json(BasicJsonType& j, const std::valarray& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) +{ + external_constructor::construct(j, std::move(arr)); +} + +template < typename BasicJsonType, typename CompatibleObjectType, + enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > +void to_json(BasicJsonType& j, const CompatibleObjectType& obj) +{ + external_constructor::construct(j, obj); +} + +template +void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) +{ + external_constructor::construct(j, std::move(obj)); +} + +template < + typename BasicJsonType, typename T, std::size_t N, + enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + int > = 0 > +void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +{ + external_constructor::construct(j, arr); +} + +template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > +void to_json(BasicJsonType& j, const std::pair& p) +{ + j = { p.first, p.second }; +} + +// for https://github.com/nlohmann/json/pull/1134 +template>::value, int> = 0> +void to_json(BasicJsonType& j, const T& b) +{ + j = { {b.key(), b.value()} }; +} + +template +void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) +{ + j = { std::get(t)... }; +} + +template::value, int > = 0> +void to_json(BasicJsonType& j, const T& t) +{ + to_json_tuple_impl(j, t, make_index_sequence::value> {}); +} + +#if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM +template +void to_json(BasicJsonType& j, const std_fs::path& p) +{ + j = p.string(); +} +#endif + +struct to_json_fn +{ + template + auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) + -> decltype(to_json(j, std::forward(val)), void()) + { + return to_json(j, std::forward(val)); + } +}; +} // namespace detail + +/// namespace to hold default `to_json` function +/// to see why this is required: +/// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html +namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) +{ +constexpr const auto& to_json = detail::static_const::value; // NOLINT(misc-definitions-in-headers) +} // namespace +} // namespace nlohmann + +// #include + +// #include + + +namespace nlohmann +{ + +/// @sa https://json.nlohmann.me/api/adl_serializer/ +template +struct adl_serializer +{ + /// @brief convert a JSON value to any value type + /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ + template + static auto from_json(BasicJsonType && j, TargetType& val) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), val))) + -> decltype(::nlohmann::from_json(std::forward(j), val), void()) + { + ::nlohmann::from_json(std::forward(j), val); + } + + /// @brief convert a JSON value to any value type + /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ + template + static auto from_json(BasicJsonType && j) noexcept( + noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) + -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) + { + return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); + } + + /// @brief convert any value type to a JSON value + /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ + template + static auto to_json(BasicJsonType& j, TargetType && val) noexcept( + noexcept(::nlohmann::to_json(j, std::forward(val)))) + -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) + { + ::nlohmann::to_json(j, std::forward(val)); + } +}; +} // namespace nlohmann + +// #include + + +#include // uint8_t, uint64_t +#include // tie +#include // move + +namespace nlohmann +{ + +/// @brief an internal type for a backed binary type +/// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ +template +class byte_container_with_subtype : public BinaryType +{ + public: + using container_type = BinaryType; + using subtype_type = std::uint64_t; + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype() noexcept(noexcept(container_type())) + : container_type() + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) + : container_type(b) + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) + : container_type(b) + , m_subtype(subtype_) + , m_has_subtype(true) + {} + + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ + byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) + : container_type(std::move(b)) + , m_subtype(subtype_) + , m_has_subtype(true) + {} + + bool operator==(const byte_container_with_subtype& rhs) const + { + return std::tie(static_cast(*this), m_subtype, m_has_subtype) == + std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); + } + + bool operator!=(const byte_container_with_subtype& rhs) const + { + return !(rhs == *this); + } + + /// @brief sets the binary subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ + void set_subtype(subtype_type subtype_) noexcept + { + m_subtype = subtype_; + m_has_subtype = true; + } + + /// @brief return the binary subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ + constexpr subtype_type subtype() const noexcept + { + return m_has_subtype ? m_subtype : static_cast(-1); + } + + /// @brief return whether the value has a subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ + constexpr bool has_subtype() const noexcept + { + return m_has_subtype; + } + + /// @brief clears the binary subtype + /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ + void clear_subtype() noexcept + { + m_subtype = 0; + m_has_subtype = false; + } + + private: + subtype_type m_subtype = 0; + bool m_has_subtype = false; +}; + +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + + +#include // uint8_t +#include // size_t +#include // hash + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +// boost::hash_combine +inline std::size_t combine(std::size_t seed, std::size_t h) noexcept +{ + seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); + return seed; +} + +/*! +@brief hash a JSON value + +The hash function tries to rely on std::hash where possible. Furthermore, the +type of the JSON value is taken into account to have different hash values for +null, 0, 0U, and false, etc. + +@tparam BasicJsonType basic_json specialization +@param j JSON value to hash +@return hash value of j +*/ +template +std::size_t hash(const BasicJsonType& j) +{ + using string_t = typename BasicJsonType::string_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + + const auto type = static_cast(j.type()); + switch (j.type()) + { + case BasicJsonType::value_t::null: + case BasicJsonType::value_t::discarded: + { + return combine(type, 0); + } + + case BasicJsonType::value_t::object: + { + auto seed = combine(type, j.size()); + for (const auto& element : j.items()) + { + const auto h = std::hash {}(element.key()); + seed = combine(seed, h); + seed = combine(seed, hash(element.value())); + } + return seed; + } + + case BasicJsonType::value_t::array: + { + auto seed = combine(type, j.size()); + for (const auto& element : j) + { + seed = combine(seed, hash(element)); + } + return seed; + } + + case BasicJsonType::value_t::string: + { + const auto h = std::hash {}(j.template get_ref()); + return combine(type, h); + } + + case BasicJsonType::value_t::boolean: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_integer: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_unsigned: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::number_float: + { + const auto h = std::hash {}(j.template get()); + return combine(type, h); + } + + case BasicJsonType::value_t::binary: + { + auto seed = combine(type, j.get_binary().size()); + const auto h = std::hash {}(j.get_binary().has_subtype()); + seed = combine(seed, h); + seed = combine(seed, static_cast(j.get_binary().subtype())); + for (const auto byte : j.get_binary()) + { + seed = combine(seed, std::hash {}(byte)); + } + return seed; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return 0; // LCOV_EXCL_LINE + } +} + +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // generate_n +#include // array +#include // ldexp +#include // size_t +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // snprintf +#include // memcpy +#include // back_inserter +#include // numeric_limits +#include // char_traits, string +#include // make_pair, move +#include // vector + +// #include + +// #include + + +#include // array +#include // size_t +#include // strlen +#include // begin, end, iterator_traits, random_access_iterator_tag, distance, next +#include // shared_ptr, make_shared, addressof +#include // accumulate +#include // string, char_traits +#include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer +#include // pair, declval + +#ifndef JSON_NO_IO + #include // FILE * + #include // istream +#endif // JSON_NO_IO + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// the supported input formats +enum class input_format_t { json, cbor, msgpack, ubjson, bson }; + +//////////////////// +// input adapters // +//////////////////// + +#ifndef JSON_NO_IO +/*! +Input adapter for stdio file access. This adapter read only 1 byte and do not use any + buffer. This adapter is a very low level adapter. +*/ +class file_input_adapter +{ + public: + using char_type = char; + + JSON_HEDLEY_NON_NULL(2) + explicit file_input_adapter(std::FILE* f) noexcept + : m_file(f) + {} + + // make class move-only + file_input_adapter(const file_input_adapter&) = delete; + file_input_adapter(file_input_adapter&&) noexcept = default; + file_input_adapter& operator=(const file_input_adapter&) = delete; + file_input_adapter& operator=(file_input_adapter&&) = delete; + ~file_input_adapter() = default; + + std::char_traits::int_type get_character() noexcept + { + return std::fgetc(m_file); + } + + private: + /// the file pointer to read from + std::FILE* m_file; +}; + + +/*! +Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at +beginning of input. Does not support changing the underlying std::streambuf +in mid-input. Maintains underlying std::istream and std::streambuf to support +subsequent use of standard std::istream operations to process any input +characters following those used in parsing the JSON input. Clears the +std::istream flags; any input errors (e.g., EOF) will be detected by the first +subsequent call for input from the std::istream. +*/ +class input_stream_adapter +{ + public: + using char_type = char; + + ~input_stream_adapter() + { + // clear stream flags; we use underlying streambuf I/O, do not + // maintain ifstream flags, except eof + if (is != nullptr) + { + is->clear(is->rdstate() & std::ios::eofbit); + } + } + + explicit input_stream_adapter(std::istream& i) + : is(&i), sb(i.rdbuf()) + {} + + // delete because of pointer members + input_stream_adapter(const input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&) = delete; + input_stream_adapter& operator=(input_stream_adapter&&) = delete; + + input_stream_adapter(input_stream_adapter&& rhs) noexcept + : is(rhs.is), sb(rhs.sb) + { + rhs.is = nullptr; + rhs.sb = nullptr; + } + + // std::istream/std::streambuf use std::char_traits::to_int_type, to + // ensure that std::char_traits::eof() and the character 0xFF do not + // end up as the same value, e.g. 0xFFFFFFFF. + std::char_traits::int_type get_character() + { + auto res = sb->sbumpc(); + // set eof manually, as we don't use the istream interface. + if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) + { + is->clear(is->rdstate() | std::ios::eofbit); + } + return res; + } + + private: + /// the associated input stream + std::istream* is = nullptr; + std::streambuf* sb = nullptr; +}; +#endif // JSON_NO_IO + +// General-purpose iterator-based adapter. It might not be as fast as +// theoretically possible for some containers, but it is extremely versatile. +template +class iterator_input_adapter +{ + public: + using char_type = typename std::iterator_traits::value_type; + + iterator_input_adapter(IteratorType first, IteratorType last) + : current(std::move(first)), end(std::move(last)) + {} + + typename std::char_traits::int_type get_character() + { + if (JSON_HEDLEY_LIKELY(current != end)) + { + auto result = std::char_traits::to_int_type(*current); + std::advance(current, 1); + return result; + } + + return std::char_traits::eof(); + } + + private: + IteratorType current; + IteratorType end; + + template + friend struct wide_string_input_helper; + + bool empty() const + { + return current == end; + } +}; + + +template +struct wide_string_input_helper; + +template +struct wide_string_input_helper +{ + // UTF-32 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-32 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (wc <= 0xFFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else if (wc <= 0x10FFFF) + { + utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + // unknown character + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } +}; + +template +struct wide_string_input_helper +{ + // UTF-16 + static void fill_buffer(BaseInputAdapter& input, + std::array::int_type, 4>& utf8_bytes, + size_t& utf8_bytes_index, + size_t& utf8_bytes_filled) + { + utf8_bytes_index = 0; + + if (JSON_HEDLEY_UNLIKELY(input.empty())) + { + utf8_bytes[0] = std::char_traits::eof(); + utf8_bytes_filled = 1; + } + else + { + // get the current character + const auto wc = input.get_character(); + + // UTF-16 to UTF-8 encoding + if (wc < 0x80) + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + else if (wc <= 0x7FF) + { + utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 2; + } + else if (0xD800 > wc || wc >= 0xE000) + { + utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); + utf8_bytes_filled = 3; + } + else + { + if (JSON_HEDLEY_UNLIKELY(!input.empty())) + { + const auto wc2 = static_cast(input.get_character()); + const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); + utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); + utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); + utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); + utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); + utf8_bytes_filled = 4; + } + else + { + utf8_bytes[0] = static_cast::int_type>(wc); + utf8_bytes_filled = 1; + } + } + } + } +}; + +// Wraps another input apdater to convert wide character types into individual bytes. +template +class wide_string_input_adapter +{ + public: + using char_type = char; + + wide_string_input_adapter(BaseInputAdapter base) + : base_adapter(base) {} + + typename std::char_traits::int_type get_character() noexcept + { + // check if buffer needs to be filled + if (utf8_bytes_index == utf8_bytes_filled) + { + fill_buffer(); + + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index == 0); + } + + // use buffer + JSON_ASSERT(utf8_bytes_filled > 0); + JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); + return utf8_bytes[utf8_bytes_index++]; + } + + private: + BaseInputAdapter base_adapter; + + template + void fill_buffer() + { + wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); + } + + /// a buffer for UTF-8 bytes + std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; + + /// index to the utf8_codes array for the next valid byte + std::size_t utf8_bytes_index = 0; + /// number of valid bytes in the utf8_codes array + std::size_t utf8_bytes_filled = 0; +}; + + +template +struct iterator_input_adapter_factory +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using adapter_type = iterator_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(std::move(first), std::move(last)); + } +}; + +template +struct is_iterator_of_multibyte +{ + using value_type = typename std::iterator_traits::value_type; + enum + { + value = sizeof(value_type) > 1 + }; +}; + +template +struct iterator_input_adapter_factory::value>> +{ + using iterator_type = IteratorType; + using char_type = typename std::iterator_traits::value_type; + using base_adapter_type = iterator_input_adapter; + using adapter_type = wide_string_input_adapter; + + static adapter_type create(IteratorType first, IteratorType last) + { + return adapter_type(base_adapter_type(std::move(first), std::move(last))); + } +}; + +// General purpose iterator-based input +template +typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) +{ + using factory_type = iterator_input_adapter_factory; + return factory_type::create(first, last); +} + +// Convenience shorthand from container to iterator +// Enables ADL on begin(container) and end(container) +// Encloses the using declarations in namespace for not to leak them to outside scope + +namespace container_input_adapter_factory_impl +{ + +using std::begin; +using std::end; + +template +struct container_input_adapter_factory {}; + +template +struct container_input_adapter_factory< ContainerType, + void_t()), end(std::declval()))>> + { + using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); + + static adapter_type create(const ContainerType& container) +{ + return input_adapter(begin(container), end(container)); +} + }; + +} // namespace container_input_adapter_factory_impl + +template +typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) +{ + return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); +} + +#ifndef JSON_NO_IO +// Special cases with fast paths +inline file_input_adapter input_adapter(std::FILE* file) +{ + return file_input_adapter(file); +} + +inline input_stream_adapter input_adapter(std::istream& stream) +{ + return input_stream_adapter(stream); +} + +inline input_stream_adapter input_adapter(std::istream&& stream) +{ + return input_stream_adapter(stream); +} +#endif // JSON_NO_IO + +using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); + +// Null-delimited strings, and the like. +template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + !std::is_array::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > +contiguous_bytes_input_adapter input_adapter(CharT b) +{ + auto length = std::strlen(reinterpret_cast(b)); + const auto* ptr = reinterpret_cast(b); + return input_adapter(ptr, ptr + length); +} + +template +auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) +{ + return input_adapter(array, array + N); +} + +// This class only handles inputs of input_buffer_adapter type. +// It's required so that expressions like {ptr, len} can be implicitly cast +// to the correct adapter. +class span_input_adapter +{ + public: + template < typename CharT, + typename std::enable_if < + std::is_pointer::value&& + std::is_integral::type>::value&& + sizeof(typename std::remove_pointer::type) == 1, + int >::type = 0 > + span_input_adapter(CharT b, std::size_t l) + : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} + + template::iterator_category, std::random_access_iterator_tag>::value, + int>::type = 0> + span_input_adapter(IteratorType first, IteratorType last) + : ia(input_adapter(first, last)) {} + + contiguous_bytes_input_adapter&& get() + { + return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) + } + + private: + contiguous_bytes_input_adapter ia; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include +#include // string +#include // move +#include // vector + +// #include + +// #include + + +namespace nlohmann +{ + +/*! +@brief SAX interface + +This class describes the SAX interface used by @ref nlohmann::json::sax_parse. +Each function is called in different situations while the input is parsed. The +boolean return value informs the parser whether to continue processing the +input. +*/ +template +struct json_sax +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @brief a null value was read + @return whether parsing should proceed + */ + virtual bool null() = 0; + + /*! + @brief a boolean value was read + @param[in] val boolean value + @return whether parsing should proceed + */ + virtual bool boolean(bool val) = 0; + + /*! + @brief an integer number was read + @param[in] val integer value + @return whether parsing should proceed + */ + virtual bool number_integer(number_integer_t val) = 0; + + /*! + @brief an unsigned integer number was read + @param[in] val unsigned integer value + @return whether parsing should proceed + */ + virtual bool number_unsigned(number_unsigned_t val) = 0; + + /*! + @brief a floating-point number was read + @param[in] val floating-point value + @param[in] s raw token value + @return whether parsing should proceed + */ + virtual bool number_float(number_float_t val, const string_t& s) = 0; + + /*! + @brief a string value was read + @param[in] val string value + @return whether parsing should proceed + @note It is safe to move the passed string value. + */ + virtual bool string(string_t& val) = 0; + + /*! + @brief a binary value was read + @param[in] val binary value + @return whether parsing should proceed + @note It is safe to move the passed binary value. + */ + virtual bool binary(binary_t& val) = 0; + + /*! + @brief the beginning of an object was read + @param[in] elements number of object elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_object(std::size_t elements) = 0; + + /*! + @brief an object key was read + @param[in] val object key + @return whether parsing should proceed + @note It is safe to move the passed string. + */ + virtual bool key(string_t& val) = 0; + + /*! + @brief the end of an object was read + @return whether parsing should proceed + */ + virtual bool end_object() = 0; + + /*! + @brief the beginning of an array was read + @param[in] elements number of array elements or -1 if unknown + @return whether parsing should proceed + @note binary formats may report the number of elements + */ + virtual bool start_array(std::size_t elements) = 0; + + /*! + @brief the end of an array was read + @return whether parsing should proceed + */ + virtual bool end_array() = 0; + + /*! + @brief a parse error occurred + @param[in] position the position in the input where the error occurs + @param[in] last_token the last read token + @param[in] ex an exception object describing the error + @return whether parsing should proceed (must return false) + */ + virtual bool parse_error(std::size_t position, + const std::string& last_token, + const detail::exception& ex) = 0; + + json_sax() = default; + json_sax(const json_sax&) = default; + json_sax(json_sax&&) noexcept = default; + json_sax& operator=(const json_sax&) = default; + json_sax& operator=(json_sax&&) noexcept = default; + virtual ~json_sax() = default; +}; + + +namespace detail +{ +/*! +@brief SAX implementation to create a JSON value from SAX events + +This class implements the @ref json_sax interface and processes the SAX events +to create a JSON value which makes it basically a DOM parser. The structure or +hierarchy of the JSON value is managed by the stack `ref_stack` which contains +a pointer to the respective array or object for each recursion depth. + +After successful parsing, the value that is passed by reference to the +constructor contains the parsed value. + +@tparam BasicJsonType the JSON type +*/ +template +class json_sax_dom_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + /*! + @param[in,out] r reference to a JSON value that is manipulated while + parsing + @param[in] allow_exceptions_ whether parse errors yield exceptions + */ + explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) + : root(r), allow_exceptions(allow_exceptions_) + {} + + // make class move-only + json_sax_dom_parser(const json_sax_dom_parser&) = delete; + json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; + json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~json_sax_dom_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); + + if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool key(string_t& val) + { + // add null at given key and store the reference for later + object_element = &(ref_stack.back()->m_value.object->operator[](val)); + return true; + } + + bool end_object() + { + ref_stack.back()->set_parents(); + ref_stack.pop_back(); + return true; + } + + bool start_array(std::size_t len) + { + ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); + + if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool end_array() + { + ref_stack.back()->set_parents(); + ref_stack.pop_back(); + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + */ + template + JSON_HEDLEY_RETURNS_NON_NULL + BasicJsonType* handle_value(Value&& v) + { + if (ref_stack.empty()) + { + root = BasicJsonType(std::forward(v)); + return &root; + } + + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::forward(v)); + return &(ref_stack.back()->m_value.array->back()); + } + + JSON_ASSERT(ref_stack.back()->is_object()); + JSON_ASSERT(object_element); + *object_element = BasicJsonType(std::forward(v)); + return object_element; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +template +class json_sax_dom_callback_parser +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using parser_callback_t = typename BasicJsonType::parser_callback_t; + using parse_event_t = typename BasicJsonType::parse_event_t; + + json_sax_dom_callback_parser(BasicJsonType& r, + const parser_callback_t cb, + const bool allow_exceptions_ = true) + : root(r), callback(cb), allow_exceptions(allow_exceptions_) + { + keep_stack.push_back(true); + } + + // make class move-only + json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; + json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~json_sax_dom_callback_parser() = default; + + bool null() + { + handle_value(nullptr); + return true; + } + + bool boolean(bool val) + { + handle_value(val); + return true; + } + + bool number_integer(number_integer_t val) + { + handle_value(val); + return true; + } + + bool number_unsigned(number_unsigned_t val) + { + handle_value(val); + return true; + } + + bool number_float(number_float_t val, const string_t& /*unused*/) + { + handle_value(val); + return true; + } + + bool string(string_t& val) + { + handle_value(val); + return true; + } + + bool binary(binary_t& val) + { + handle_value(std::move(val)); + return true; + } + + bool start_object(std::size_t len) + { + // check callback for object start + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::object, true); + ref_stack.push_back(val.second); + + // check object limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool key(string_t& val) + { + BasicJsonType k = BasicJsonType(val); + + // check callback for key + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); + key_keep_stack.push_back(keep); + + // add discarded value at given key and store the reference for later + if (keep && ref_stack.back()) + { + object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); + } + + return true; + } + + bool end_object() + { + if (ref_stack.back()) + { + if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) + { + // discard object + *ref_stack.back() = discarded; + } + else + { + ref_stack.back()->set_parents(); + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) + { + // remove discarded value + for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) + { + if (it->is_discarded()) + { + ref_stack.back()->erase(it); + break; + } + } + } + + return true; + } + + bool start_array(std::size_t len) + { + const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); + keep_stack.push_back(keep); + + auto val = handle_value(BasicJsonType::value_t::array, true); + ref_stack.push_back(val.second); + + // check array limit + if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) + { + JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len), *ref_stack.back())); + } + + return true; + } + + bool end_array() + { + bool keep = true; + + if (ref_stack.back()) + { + keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); + if (keep) + { + ref_stack.back()->set_parents(); + } + else + { + // discard array + *ref_stack.back() = discarded; + } + } + + JSON_ASSERT(!ref_stack.empty()); + JSON_ASSERT(!keep_stack.empty()); + ref_stack.pop_back(); + keep_stack.pop_back(); + + // remove discarded value + if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->pop_back(); + } + + return true; + } + + template + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, + const Exception& ex) + { + errored = true; + static_cast(ex); + if (allow_exceptions) + { + JSON_THROW(ex); + } + return false; + } + + constexpr bool is_errored() const + { + return errored; + } + + private: + /*! + @param[in] v value to add to the JSON value we build during parsing + @param[in] skip_callback whether we should skip calling the callback + function; this is required after start_array() and + start_object() SAX events, because otherwise we would call the + callback function with an empty array or object, respectively. + + @invariant If the ref stack is empty, then the passed value will be the new + root. + @invariant If the ref stack contains a value, then it is an array or an + object to which we can add elements + + @return pair of boolean (whether value should be kept) and pointer (to the + passed value in the ref_stack hierarchy; nullptr if not kept) + */ + template + std::pair handle_value(Value&& v, const bool skip_callback = false) + { + JSON_ASSERT(!keep_stack.empty()); + + // do not handle this value if we know it would be added to a discarded + // container + if (!keep_stack.back()) + { + return {false, nullptr}; + } + + // create value + auto value = BasicJsonType(std::forward(v)); + + // check callback + const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); + + // do not handle this value if we just learnt it shall be discarded + if (!keep) + { + return {false, nullptr}; + } + + if (ref_stack.empty()) + { + root = std::move(value); + return {true, &root}; + } + + // skip this value if we already decided to skip the parent + // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) + if (!ref_stack.back()) + { + return {false, nullptr}; + } + + // we now only expect arrays and objects + JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); + + // array + if (ref_stack.back()->is_array()) + { + ref_stack.back()->m_value.array->emplace_back(std::move(value)); + return {true, &(ref_stack.back()->m_value.array->back())}; + } + + // object + JSON_ASSERT(ref_stack.back()->is_object()); + // check if we should store an element for the current key + JSON_ASSERT(!key_keep_stack.empty()); + const bool store_element = key_keep_stack.back(); + key_keep_stack.pop_back(); + + if (!store_element) + { + return {false, nullptr}; + } + + JSON_ASSERT(object_element); + *object_element = std::move(value); + return {true, object_element}; + } + + /// the parsed JSON value + BasicJsonType& root; + /// stack to model hierarchy of values + std::vector ref_stack {}; + /// stack to manage which values to keep + std::vector keep_stack {}; + /// stack to manage which object keys to keep + std::vector key_keep_stack {}; + /// helper to hold the reference for the next object element + BasicJsonType* object_element = nullptr; + /// whether a syntax error occurred + bool errored = false; + /// callback function + const parser_callback_t callback = nullptr; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; + /// a discarded value for the callback + BasicJsonType discarded = BasicJsonType::value_t::discarded; +}; + +template +class json_sax_acceptor +{ + public: + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + + bool null() + { + return true; + } + + bool boolean(bool /*unused*/) + { + return true; + } + + bool number_integer(number_integer_t /*unused*/) + { + return true; + } + + bool number_unsigned(number_unsigned_t /*unused*/) + { + return true; + } + + bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) + { + return true; + } + + bool string(string_t& /*unused*/) + { + return true; + } + + bool binary(binary_t& /*unused*/) + { + return true; + } + + bool start_object(std::size_t /*unused*/ = static_cast(-1)) + { + return true; + } + + bool key(string_t& /*unused*/) + { + return true; + } + + bool end_object() + { + return true; + } + + bool start_array(std::size_t /*unused*/ = static_cast(-1)) + { + return true; + } + + bool end_array() + { + return true; + } + + bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) + { + return false; + } +}; +} // namespace detail + +} // namespace nlohmann + +// #include + + +#include // array +#include // localeconv +#include // size_t +#include // snprintf +#include // strtof, strtod, strtold, strtoll, strtoull +#include // initializer_list +#include // char_traits, string +#include // move +#include // vector + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////// +// lexer // +/////////// + +template +class lexer_base +{ + public: + /// token types for the parser + enum class token_type + { + uninitialized, ///< indicating the scanner is uninitialized + literal_true, ///< the `true` literal + literal_false, ///< the `false` literal + literal_null, ///< the `null` literal + value_string, ///< a string -- use get_string() for actual value + value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value + value_integer, ///< a signed integer -- use get_number_integer() for actual value + value_float, ///< an floating point number -- use get_number_float() for actual value + begin_array, ///< the character for array begin `[` + begin_object, ///< the character for object begin `{` + end_array, ///< the character for array end `]` + end_object, ///< the character for object end `}` + name_separator, ///< the name separator `:` + value_separator, ///< the value separator `,` + parse_error, ///< indicating a parse error + end_of_input, ///< indicating the end of the input buffer + literal_or_value ///< a literal or the begin of a value (only for diagnostics) + }; + + /// return name of values of type token_type (only used for errors) + JSON_HEDLEY_RETURNS_NON_NULL + JSON_HEDLEY_CONST + static const char* token_type_name(const token_type t) noexcept + { + switch (t) + { + case token_type::uninitialized: + return ""; + case token_type::literal_true: + return "true literal"; + case token_type::literal_false: + return "false literal"; + case token_type::literal_null: + return "null literal"; + case token_type::value_string: + return "string literal"; + case token_type::value_unsigned: + case token_type::value_integer: + case token_type::value_float: + return "number literal"; + case token_type::begin_array: + return "'['"; + case token_type::begin_object: + return "'{'"; + case token_type::end_array: + return "']'"; + case token_type::end_object: + return "'}'"; + case token_type::name_separator: + return "':'"; + case token_type::value_separator: + return "','"; + case token_type::parse_error: + return ""; + case token_type::end_of_input: + return "end of input"; + case token_type::literal_or_value: + return "'[', '{', or a literal"; + // LCOV_EXCL_START + default: // catch non-enum values + return "unknown token"; + // LCOV_EXCL_STOP + } + } +}; +/*! +@brief lexical analysis + +This class organizes the lexical analysis during JSON deserialization. +*/ +template +class lexer : public lexer_base +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + using token_type = typename lexer_base::token_type; + + explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept + : ia(std::move(adapter)) + , ignore_comments(ignore_comments_) + , decimal_point_char(static_cast(get_decimal_point())) + {} + + // delete because of pointer members + lexer(const lexer&) = delete; + lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + lexer& operator=(lexer&) = delete; + lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~lexer() = default; + + private: + ///////////////////// + // locales + ///////////////////// + + /// return the locale-dependent decimal point + JSON_HEDLEY_PURE + static char get_decimal_point() noexcept + { + const auto* loc = localeconv(); + JSON_ASSERT(loc != nullptr); + return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); + } + + ///////////////////// + // scan functions + ///////////////////// + + /*! + @brief get codepoint from 4 hex characters following `\u` + + For input "\u c1 c2 c3 c4" the codepoint is: + (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 + = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) + + Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' + must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The + conversion is done by subtracting the offset (0x30, 0x37, and 0x57) + between the ASCII value of the character and the desired integer value. + + @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or + non-hex character) + */ + int get_codepoint() + { + // this function only makes sense after reading `\u` + JSON_ASSERT(current == 'u'); + int codepoint = 0; + + const auto factors = { 12u, 8u, 4u, 0u }; + for (const auto factor : factors) + { + get(); + + if (current >= '0' && current <= '9') + { + codepoint += static_cast((static_cast(current) - 0x30u) << factor); + } + else if (current >= 'A' && current <= 'F') + { + codepoint += static_cast((static_cast(current) - 0x37u) << factor); + } + else if (current >= 'a' && current <= 'f') + { + codepoint += static_cast((static_cast(current) - 0x57u) << factor); + } + else + { + return -1; + } + } + + JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); + return codepoint; + } + + /*! + @brief check if the next byte(s) are inside a given range + + Adds the current byte and, for each passed range, reads a new byte and + checks if it is inside the range. If a violation was detected, set up an + error message and return false. Otherwise, return true. + + @param[in] ranges list of integers; interpreted as list of pairs of + inclusive lower and upper bound, respectively + + @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, + 1, 2, or 3 pairs. This precondition is enforced by an assertion. + + @return true if and only if no range violation was detected + */ + bool next_byte_in_range(std::initializer_list ranges) + { + JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); + add(current); + + for (auto range = ranges.begin(); range != ranges.end(); ++range) + { + get(); + if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) + { + add(current); + } + else + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return false; + } + } + + return true; + } + + /*! + @brief scan a string literal + + This function scans a string according to Sect. 7 of RFC 8259. While + scanning, bytes are escaped and copied into buffer token_buffer. Then the + function returns successfully, token_buffer is *not* null-terminated (as it + may contain \0 bytes), and token_buffer.size() is the number of bytes in the + string. + + @return token_type::value_string if string could be successfully scanned, + token_type::parse_error otherwise + + @note In case of errors, variable error_message contains a textual + description. + */ + token_type scan_string() + { + // reset token_buffer (ignore opening quote) + reset(); + + // we entered the function by reading an open quote + JSON_ASSERT(current == '\"'); + + while (true) + { + // get next character + switch (get()) + { + // end of file while parsing string + case std::char_traits::eof(): + { + error_message = "invalid string: missing closing quote"; + return token_type::parse_error; + } + + // closing quote + case '\"': + { + return token_type::value_string; + } + + // escapes + case '\\': + { + switch (get()) + { + // quotation mark + case '\"': + add('\"'); + break; + // reverse solidus + case '\\': + add('\\'); + break; + // solidus + case '/': + add('/'); + break; + // backspace + case 'b': + add('\b'); + break; + // form feed + case 'f': + add('\f'); + break; + // line feed + case 'n': + add('\n'); + break; + // carriage return + case 'r': + add('\r'); + break; + // tab + case 't': + add('\t'); + break; + + // unicode escapes + case 'u': + { + const int codepoint1 = get_codepoint(); + int codepoint = codepoint1; // start with codepoint1 + + if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if code point is a high surrogate + if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) + { + // expect next \uxxxx entry + if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) + { + const int codepoint2 = get_codepoint(); + + if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) + { + error_message = "invalid string: '\\u' must be followed by 4 hex digits"; + return token_type::parse_error; + } + + // check if codepoint2 is a low surrogate + if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) + { + // overwrite codepoint + codepoint = static_cast( + // high surrogate occupies the most significant 22 bits + (static_cast(codepoint1) << 10u) + // low surrogate occupies the least significant 15 bits + + static_cast(codepoint2) + // there is still the 0xD800, 0xDC00 and 0x10000 noise + // in the result, so we have to subtract with: + // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 + - 0x35FDC00u); + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; + return token_type::parse_error; + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) + { + error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; + return token_type::parse_error; + } + } + + // result of the above calculation yields a proper codepoint + JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); + + // translate codepoint into bytes + if (codepoint < 0x80) + { + // 1-byte characters: 0xxxxxxx (ASCII) + add(static_cast(codepoint)); + } + else if (codepoint <= 0x7FF) + { + // 2-byte characters: 110xxxxx 10xxxxxx + add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else if (codepoint <= 0xFFFF) + { + // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx + add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + else + { + // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); + add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); + add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); + } + + break; + } + + // other characters after escape + default: + error_message = "invalid string: forbidden character after backslash"; + return token_type::parse_error; + } + + break; + } + + // invalid control characters + case 0x00: + { + error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; + return token_type::parse_error; + } + + case 0x01: + { + error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; + return token_type::parse_error; + } + + case 0x02: + { + error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; + return token_type::parse_error; + } + + case 0x03: + { + error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; + return token_type::parse_error; + } + + case 0x04: + { + error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; + return token_type::parse_error; + } + + case 0x05: + { + error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; + return token_type::parse_error; + } + + case 0x06: + { + error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; + return token_type::parse_error; + } + + case 0x07: + { + error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; + return token_type::parse_error; + } + + case 0x08: + { + error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; + return token_type::parse_error; + } + + case 0x09: + { + error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; + return token_type::parse_error; + } + + case 0x0A: + { + error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; + return token_type::parse_error; + } + + case 0x0B: + { + error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; + return token_type::parse_error; + } + + case 0x0C: + { + error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; + return token_type::parse_error; + } + + case 0x0D: + { + error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; + return token_type::parse_error; + } + + case 0x0E: + { + error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; + return token_type::parse_error; + } + + case 0x0F: + { + error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; + return token_type::parse_error; + } + + case 0x10: + { + error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; + return token_type::parse_error; + } + + case 0x11: + { + error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; + return token_type::parse_error; + } + + case 0x12: + { + error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; + return token_type::parse_error; + } + + case 0x13: + { + error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; + return token_type::parse_error; + } + + case 0x14: + { + error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; + return token_type::parse_error; + } + + case 0x15: + { + error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; + return token_type::parse_error; + } + + case 0x16: + { + error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; + return token_type::parse_error; + } + + case 0x17: + { + error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; + return token_type::parse_error; + } + + case 0x18: + { + error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; + return token_type::parse_error; + } + + case 0x19: + { + error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; + return token_type::parse_error; + } + + case 0x1A: + { + error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; + return token_type::parse_error; + } + + case 0x1B: + { + error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; + return token_type::parse_error; + } + + case 0x1C: + { + error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; + return token_type::parse_error; + } + + case 0x1D: + { + error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; + return token_type::parse_error; + } + + case 0x1E: + { + error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; + return token_type::parse_error; + } + + case 0x1F: + { + error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; + return token_type::parse_error; + } + + // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) + case 0x20: + case 0x21: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + { + add(current); + break; + } + + // U+0080..U+07FF: bytes C2..DF 80..BF + case 0xC2: + case 0xC3: + case 0xC4: + case 0xC5: + case 0xC6: + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD5: + case 0xD6: + case 0xD7: + case 0xD8: + case 0xD9: + case 0xDA: + case 0xDB: + case 0xDC: + case 0xDD: + case 0xDE: + case 0xDF: + { + if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) + { + return token_type::parse_error; + } + break; + } + + // U+0800..U+0FFF: bytes E0 A0..BF 80..BF + case 0xE0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF + // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xEE: + case 0xEF: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+D000..U+D7FF: bytes ED 80..9F 80..BF + case 0xED: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF + case 0xF0: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF + case 0xF1: + case 0xF2: + case 0xF3: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF + case 0xF4: + { + if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) + { + return token_type::parse_error; + } + break; + } + + // remaining bytes (80..C1 and F5..FF) are ill-formed + default: + { + error_message = "invalid string: ill-formed UTF-8 byte"; + return token_type::parse_error; + } + } + } + } + + /*! + * @brief scan a comment + * @return whether comment could be scanned successfully + */ + bool scan_comment() + { + switch (get()) + { + // single-line comments skip input until a newline or EOF is read + case '/': + { + while (true) + { + switch (get()) + { + case '\n': + case '\r': + case std::char_traits::eof(): + case '\0': + return true; + + default: + break; + } + } + } + + // multi-line comments skip input until */ is read + case '*': + { + while (true) + { + switch (get()) + { + case std::char_traits::eof(): + case '\0': + { + error_message = "invalid comment; missing closing '*/'"; + return false; + } + + case '*': + { + switch (get()) + { + case '/': + return true; + + default: + { + unget(); + continue; + } + } + } + + default: + continue; + } + } + } + + // unexpected character after reading '/' + default: + { + error_message = "invalid comment; expecting '/' or '*' after '/'"; + return false; + } + } + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(float& f, const char* str, char** endptr) noexcept + { + f = std::strtof(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(double& f, const char* str, char** endptr) noexcept + { + f = std::strtod(str, endptr); + } + + JSON_HEDLEY_NON_NULL(2) + static void strtof(long double& f, const char* str, char** endptr) noexcept + { + f = std::strtold(str, endptr); + } + + /*! + @brief scan a number literal + + This function scans a string according to Sect. 6 of RFC 8259. + + The function is realized with a deterministic finite state machine derived + from the grammar described in RFC 8259. Starting in state "init", the + input is read and used to determined the next state. Only state "done" + accepts the number. State "error" is a trap state to model errors. In the + table below, "anything" means any character but the ones listed before. + + state | 0 | 1-9 | e E | + | - | . | anything + ---------|----------|----------|----------|---------|---------|----------|----------- + init | zero | any1 | [error] | [error] | minus | [error] | [error] + minus | zero | any1 | [error] | [error] | [error] | [error] | [error] + zero | done | done | exponent | done | done | decimal1 | done + any1 | any1 | any1 | exponent | done | done | decimal1 | done + decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] + decimal2 | decimal2 | decimal2 | exponent | done | done | done | done + exponent | any2 | any2 | [error] | sign | sign | [error] | [error] + sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] + any2 | any2 | any2 | done | done | done | done | done + + The state machine is realized with one label per state (prefixed with + "scan_number_") and `goto` statements between them. The state machine + contains cycles, but any cycle can be left when EOF is read. Therefore, + the function is guaranteed to terminate. + + During scanning, the read bytes are stored in token_buffer. This string is + then converted to a signed integer, an unsigned integer, or a + floating-point number. + + @return token_type::value_unsigned, token_type::value_integer, or + token_type::value_float if number could be successfully scanned, + token_type::parse_error otherwise + + @note The scanner is independent of the current locale. Internally, the + locale's decimal point is used instead of `.` to work with the + locale-dependent converters. + */ + token_type scan_number() // lgtm [cpp/use-of-goto] + { + // reset token_buffer to store the number's bytes + reset(); + + // the type of the parsed number; initially set to unsigned; will be + // changed if minus sign, decimal point or exponent is read + token_type number_type = token_type::value_unsigned; + + // state (init): we just found out we need to scan a number + switch (current) + { + case '-': + { + add(current); + goto scan_number_minus; + } + + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + // all other characters are rejected outside scan_number() + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + +scan_number_minus: + // state: we just parsed a leading minus sign + number_type = token_type::value_integer; + switch (get()) + { + case '0': + { + add(current); + goto scan_number_zero; + } + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + default: + { + error_message = "invalid number; expected digit after '-'"; + return token_type::parse_error; + } + } + +scan_number_zero: + // state: we just parse a zero (maybe with a leading minus sign) + switch (get()) + { + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_any1: + // state: we just parsed a number 0-9 (maybe with a leading minus sign) + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any1; + } + + case '.': + { + add(decimal_point_char); + goto scan_number_decimal1; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_decimal1: + // state: we just parsed a decimal point + number_type = token_type::value_float; + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + default: + { + error_message = "invalid number; expected digit after '.'"; + return token_type::parse_error; + } + } + +scan_number_decimal2: + // we just parsed at least one number after a decimal point + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_decimal2; + } + + case 'e': + case 'E': + { + add(current); + goto scan_number_exponent; + } + + default: + goto scan_number_done; + } + +scan_number_exponent: + // we just parsed an exponent + number_type = token_type::value_float; + switch (get()) + { + case '+': + case '-': + { + add(current); + goto scan_number_sign; + } + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = + "invalid number; expected '+', '-', or digit after exponent"; + return token_type::parse_error; + } + } + +scan_number_sign: + // we just parsed an exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + { + error_message = "invalid number; expected digit after exponent sign"; + return token_type::parse_error; + } + } + +scan_number_any2: + // we just parsed a number after the exponent or exponent sign + switch (get()) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + add(current); + goto scan_number_any2; + } + + default: + goto scan_number_done; + } + +scan_number_done: + // unget the character after the number (we only read it to know that + // we are done scanning a number) + unget(); + + char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + errno = 0; + + // try to parse integers first and fall back to floats + if (number_type == token_type::value_unsigned) + { + const auto x = std::strtoull(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_unsigned = static_cast(x); + if (value_unsigned == x) + { + return token_type::value_unsigned; + } + } + } + else if (number_type == token_type::value_integer) + { + const auto x = std::strtoll(token_buffer.data(), &endptr, 10); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + if (errno == 0) + { + value_integer = static_cast(x); + if (value_integer == x) + { + return token_type::value_integer; + } + } + } + + // this code is reached if we parse a floating-point number or if an + // integer conversion above failed + strtof(value_float, token_buffer.data(), &endptr); + + // we checked the number format before + JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); + + return token_type::value_float; + } + + /*! + @param[in] literal_text the literal text to expect + @param[in] length the length of the passed literal text + @param[in] return_type the token type to return on success + */ + JSON_HEDLEY_NON_NULL(2) + token_type scan_literal(const char_type* literal_text, const std::size_t length, + token_type return_type) + { + JSON_ASSERT(std::char_traits::to_char_type(current) == literal_text[0]); + for (std::size_t i = 1; i < length; ++i) + { + if (JSON_HEDLEY_UNLIKELY(std::char_traits::to_char_type(get()) != literal_text[i])) + { + error_message = "invalid literal"; + return token_type::parse_error; + } + } + return return_type; + } + + ///////////////////// + // input management + ///////////////////// + + /// reset token_buffer; current character is beginning of token + void reset() noexcept + { + token_buffer.clear(); + token_string.clear(); + token_string.push_back(std::char_traits::to_char_type(current)); + } + + /* + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a + `std::char_traits::eof()` in that case. Stores the scanned characters + for use in error messages. + + @return character read from the input + */ + char_int_type get() + { + ++position.chars_read_total; + ++position.chars_read_current_line; + + if (next_unget) + { + // just reset the next_unget variable and work with current + next_unget = false; + } + else + { + current = ia.get_character(); + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + token_string.push_back(std::char_traits::to_char_type(current)); + } + + if (current == '\n') + { + ++position.lines_read; + position.chars_read_current_line = 0; + } + + return current; + } + + /*! + @brief unget current character (read it again on next get) + + We implement unget by setting variable next_unget to true. The input is not + changed - we just simulate ungetting by modifying chars_read_total, + chars_read_current_line, and token_string. The next call to get() will + behave as if the unget character is read again. + */ + void unget() + { + next_unget = true; + + --position.chars_read_total; + + // in case we "unget" a newline, we have to also decrement the lines_read + if (position.chars_read_current_line == 0) + { + if (position.lines_read > 0) + { + --position.lines_read; + } + } + else + { + --position.chars_read_current_line; + } + + if (JSON_HEDLEY_LIKELY(current != std::char_traits::eof())) + { + JSON_ASSERT(!token_string.empty()); + token_string.pop_back(); + } + } + + /// add a character to token_buffer + void add(char_int_type c) + { + token_buffer.push_back(static_cast(c)); + } + + public: + ///////////////////// + // value getters + ///////////////////// + + /// return integer value + constexpr number_integer_t get_number_integer() const noexcept + { + return value_integer; + } + + /// return unsigned integer value + constexpr number_unsigned_t get_number_unsigned() const noexcept + { + return value_unsigned; + } + + /// return floating-point value + constexpr number_float_t get_number_float() const noexcept + { + return value_float; + } + + /// return current string value (implicitly resets the token; useful only once) + string_t& get_string() + { + return token_buffer; + } + + ///////////////////// + // diagnostics + ///////////////////// + + /// return position of last read token + constexpr position_t get_position() const noexcept + { + return position; + } + + /// return the last read token (for errors only). Will never contain EOF + /// (an arbitrary value that is not a valid char value, often -1), because + /// 255 may legitimately occur. May contain NUL, which should be escaped. + std::string get_token_string() const + { + // escape control characters + std::string result; + for (const auto c : token_string) + { + if (static_cast(c) <= '\x1F') + { + // escape control characters + std::array cs{{}}; + static_cast((std::snprintf)(cs.data(), cs.size(), "", static_cast(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + result += cs.data(); + } + else + { + // add character as is + result.push_back(static_cast(c)); + } + } + + return result; + } + + /// return syntax error message + JSON_HEDLEY_RETURNS_NON_NULL + constexpr const char* get_error_message() const noexcept + { + return error_message; + } + + ///////////////////// + // actual scanner + ///////////////////// + + /*! + @brief skip the UTF-8 byte order mark + @return true iff there is no BOM or the correct BOM has been skipped + */ + bool skip_bom() + { + if (get() == 0xEF) + { + // check if we completely parse the BOM + return get() == 0xBB && get() == 0xBF; + } + + // the first character is not the beginning of the BOM; unget it to + // process is later + unget(); + return true; + } + + void skip_whitespace() + { + do + { + get(); + } + while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); + } + + token_type scan() + { + // initially, skip the BOM + if (position.chars_read_total == 0 && !skip_bom()) + { + error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; + return token_type::parse_error; + } + + // read next character and ignore whitespace + skip_whitespace(); + + // ignore comments + while (ignore_comments && current == '/') + { + if (!scan_comment()) + { + return token_type::parse_error; + } + + // skip following whitespace + skip_whitespace(); + } + + switch (current) + { + // structural characters + case '[': + return token_type::begin_array; + case ']': + return token_type::end_array; + case '{': + return token_type::begin_object; + case '}': + return token_type::end_object; + case ':': + return token_type::name_separator; + case ',': + return token_type::value_separator; + + // literals + case 't': + { + std::array true_literal = {{static_cast('t'), static_cast('r'), static_cast('u'), static_cast('e')}}; + return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); + } + case 'f': + { + std::array false_literal = {{static_cast('f'), static_cast('a'), static_cast('l'), static_cast('s'), static_cast('e')}}; + return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); + } + case 'n': + { + std::array null_literal = {{static_cast('n'), static_cast('u'), static_cast('l'), static_cast('l')}}; + return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); + } + + // string + case '\"': + return scan_string(); + + // number + case '-': + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + return scan_number(); + + // end of input (the null byte is needed when parsing from + // string literals) + case '\0': + case std::char_traits::eof(): + return token_type::end_of_input; + + // error + default: + error_message = "invalid literal"; + return token_type::parse_error; + } + } + + private: + /// input adapter + InputAdapterType ia; + + /// whether comments should be ignored (true) or signaled as errors (false) + const bool ignore_comments = false; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// whether the next get() call should just return current + bool next_unget = false; + + /// the start position of the current token + position_t position {}; + + /// raw input token string (for error messages) + std::vector token_string {}; + + /// buffer for variable-length tokens (numbers, strings) + string_t token_buffer {}; + + /// a description of occurred lexer errors + const char* error_message = ""; + + // number values + number_integer_t value_integer = 0; + number_unsigned_t value_unsigned = 0; + number_float_t value_float = 0; + + /// the decimal point + const char_int_type decimal_point_char = '.'; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // size_t +#include // declval +#include // string + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +using null_function_t = decltype(std::declval().null()); + +template +using boolean_function_t = + decltype(std::declval().boolean(std::declval())); + +template +using number_integer_function_t = + decltype(std::declval().number_integer(std::declval())); + +template +using number_unsigned_function_t = + decltype(std::declval().number_unsigned(std::declval())); + +template +using number_float_function_t = decltype(std::declval().number_float( + std::declval(), std::declval())); + +template +using string_function_t = + decltype(std::declval().string(std::declval())); + +template +using binary_function_t = + decltype(std::declval().binary(std::declval())); + +template +using start_object_function_t = + decltype(std::declval().start_object(std::declval())); + +template +using key_function_t = + decltype(std::declval().key(std::declval())); + +template +using end_object_function_t = decltype(std::declval().end_object()); + +template +using start_array_function_t = + decltype(std::declval().start_array(std::declval())); + +template +using end_array_function_t = decltype(std::declval().end_array()); + +template +using parse_error_function_t = decltype(std::declval().parse_error( + std::declval(), std::declval(), + std::declval())); + +template +struct is_sax +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static constexpr bool value = + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value && + is_detected_exact::value; +}; + +template +struct is_sax_static_asserts +{ + private: + static_assert(is_basic_json::value, + "BasicJsonType must be of type basic_json<...>"); + + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using exception_t = typename BasicJsonType::exception; + + public: + static_assert(is_detected_exact::value, + "Missing/invalid function: bool null()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool boolean(bool)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_integer(number_integer_t)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool string(string_t&)"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool binary(binary_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_object(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool key(string_t&)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_object()"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool start_array(std::size_t)"); + static_assert(is_detected_exact::value, + "Missing/invalid function: bool end_array()"); + static_assert( + is_detected_exact::value, + "Missing/invalid function: bool parse_error(std::size_t, const " + "std::string&, const exception&)"); +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/// how to treat CBOR tags +enum class cbor_tag_handler_t +{ + error, ///< throw a parse_error exception in case of a tag + ignore, ///< ignore tags + store ///< store tags as binary type +}; + +/*! +@brief determine system byte order + +@return true if and only if system's byte order is little endian + +@note from https://stackoverflow.com/a/1001328/266378 +*/ +static inline bool little_endianness(int num = 1) noexcept +{ + return *reinterpret_cast(&num) == 1; +} + + +/////////////////// +// binary reader // +/////////////////// + +/*! +@brief deserialization of CBOR, MessagePack, and UBJSON values +*/ +template> +class binary_reader +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using json_sax_t = SAX; + using char_type = typename InputAdapterType::char_type; + using char_int_type = typename std::char_traits::int_type; + + public: + /*! + @brief create a binary reader + + @param[in] adapter input adapter to read from + */ + explicit binary_reader(InputAdapterType&& adapter) noexcept : ia(std::move(adapter)) + { + (void)detail::is_sax_static_asserts {}; + } + + // make class move-only + binary_reader(const binary_reader&) = delete; + binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + binary_reader& operator=(const binary_reader&) = delete; + binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) + ~binary_reader() = default; + + /*! + @param[in] format the binary format to parse + @param[in] sax_ a SAX event processor + @param[in] strict whether to expect the input to be consumed completed + @param[in] tag_handler how to treat CBOR tags + + @return whether parsing was successful + */ + JSON_HEDLEY_NON_NULL(3) + bool sax_parse(const input_format_t format, + json_sax_t* sax_, + const bool strict = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + sax = sax_; + bool result = false; + + switch (format) + { + case input_format_t::bson: + result = parse_bson_internal(); + break; + + case input_format_t::cbor: + result = parse_cbor_internal(true, tag_handler); + break; + + case input_format_t::msgpack: + result = parse_msgpack_internal(); + break; + + case input_format_t::ubjson: + result = parse_ubjson_internal(); + break; + + case input_format_t::json: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + + // strict mode: next byte must be EOF + if (result && strict) + { + if (format == input_format_t::ubjson) + { + get_ignore_noop(); + } + else + { + get(); + } + + if (JSON_HEDLEY_UNLIKELY(current != std::char_traits::eof())) + { + return sax->parse_error(chars_read, get_token_string(), + parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"), BasicJsonType())); + } + } + + return result; + } + + private: + ////////// + // BSON // + ////////// + + /*! + @brief Reads in a BSON-object and passes it to the SAX-parser. + @return whether a valid BSON-value was passed to the SAX parser + */ + bool parse_bson_internal() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) + { + return false; + } + + return sax->end_object(); + } + + /*! + @brief Parses a C-style string from the BSON input. + @param[in,out] result A reference to the string variable where the read + string is to be stored. + @return `true` if the \x00-byte indicating the end of the string was + encountered before the EOF; false` indicates an unexpected EOF. + */ + bool get_bson_cstr(string_t& result) + { + auto out = std::back_inserter(result); + while (true) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) + { + return false; + } + if (current == 0x00) + { + return true; + } + *out++ = static_cast(current); + } + } + + /*! + @brief Parses a zero-terminated string of length @a len from the BSON + input. + @param[in] len The length (including the zero-byte at the end) of the + string to be read. + @param[in,out] result A reference to the string variable where the read + string is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 1 + @return `true` if the string was successfully parsed + */ + template + bool get_bson_string(const NumberType len, string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 1)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"), BasicJsonType())); + } + + return get_string(input_format_t::bson, len - static_cast(1), result) && get() != std::char_traits::eof(); + } + + /*! + @brief Parses a byte array input of length @a len from the BSON input. + @param[in] len The length of the byte array to be read. + @param[in,out] result A reference to the binary variable where the read + array is to be stored. + @tparam NumberType The type of the length @a len + @pre len >= 0 + @return `true` if the byte array was successfully parsed + */ + template + bool get_bson_binary(const NumberType len, binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(len < 0)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "byte array length cannot be negative, is " + std::to_string(len), "binary"), BasicJsonType())); + } + + // All BSON binary values have a subtype + std::uint8_t subtype{}; + get_number(input_format_t::bson, subtype); + result.set_subtype(subtype); + + return get_binary(input_format_t::bson, len, result); + } + + /*! + @brief Read a BSON document element of the given @a element_type. + @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html + @param[in] element_type_parse_position The position in the input stream, + where the `element_type` was read. + @warning Not all BSON element types are supported yet. An unsupported + @a element_type will give rise to a parse_error.114: + Unsupported BSON record type 0x... + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_internal(const char_int_type element_type, + const std::size_t element_type_parse_position) + { + switch (element_type) + { + case 0x01: // double + { + double number{}; + return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); + } + + case 0x02: // string + { + std::int32_t len{}; + string_t value; + return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); + } + + case 0x03: // object + { + return parse_bson_internal(); + } + + case 0x04: // array + { + return parse_bson_array(); + } + + case 0x05: // binary + { + std::int32_t len{}; + binary_t value; + return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); + } + + case 0x08: // boolean + { + return sax->boolean(get() != 0); + } + + case 0x0A: // null + { + return sax->null(); + } + + case 0x10: // int32 + { + std::int32_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + case 0x12: // int64 + { + std::int64_t value{}; + return get_number(input_format_t::bson, value) && sax->number_integer(value); + } + + default: // anything else not supported (yet) + { + std::array cr{{}}; + static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + return sax->parse_error(element_type_parse_position, std::string(cr.data()), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr.data()), BasicJsonType())); + } + } + } + + /*! + @brief Read a BSON element list (as specified in the BSON-spec) + + The same binary layout is used for objects and arrays, hence it must be + indicated with the argument @a is_array which one is expected + (true --> array, false --> object). + + @param[in] is_array Determines if the element list being read is to be + treated as an object (@a is_array == false), or as an + array (@a is_array == true). + @return whether a valid BSON-object/array was passed to the SAX parser + */ + bool parse_bson_element_list(const bool is_array) + { + string_t key; + + while (auto element_type = get()) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) + { + return false; + } + + const std::size_t element_type_parse_position = chars_read; + if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) + { + return false; + } + + if (!is_array && !sax->key(key)) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) + { + return false; + } + + // get_bson_cstr only appends + key.clear(); + } + + return true; + } + + /*! + @brief Reads an array from the BSON input and passes it to the SAX-parser. + @return whether a valid BSON-array was passed to the SAX parser + */ + bool parse_bson_array() + { + std::int32_t document_size{}; + get_number(input_format_t::bson, document_size); + + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) + { + return false; + } + + return sax->end_array(); + } + + ////////// + // CBOR // + ////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true) or whether the last read character should + be considered instead (false) + @param[in] tag_handler how CBOR tags should be treated + + @return whether a valid CBOR value was passed to the SAX parser + */ + bool parse_cbor_internal(const bool get_char, + const cbor_tag_handler_t tag_handler) + { + switch (get_char ? get() : current) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::cbor, "value"); + + // Integer 0x00..0x17 (0..23) + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + return sax->number_unsigned(static_cast(current)); + + case 0x18: // Unsigned integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x19: // Unsigned integer (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1A: // Unsigned integer (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + case 0x1B: // Unsigned integer (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); + } + + // Negative integer -1-0x00..-1-0x17 (-1..-24) + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + return sax->number_integer(static_cast(0x20 - 1 - current)); + + case 0x38: // Negative integer (one-byte uint8_t follows) + { + std::uint8_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x39: // Negative integer -1-n (two-byte uint16_t follows) + { + std::uint16_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) + { + std::uint32_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); + } + + case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) + { + std::uint64_t number{}; + return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) + - static_cast(number)); + } + + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: // Binary data (one-byte uint8_t for n follows) + case 0x59: // Binary data (two-byte uint16_t for n follow) + case 0x5A: // Binary data (four-byte uint32_t for n follow) + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + case 0x5F: // Binary data (indefinite length) + { + binary_t b; + return get_cbor_binary(b) && sax->binary(b); + } + + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + case 0x7F: // UTF-8 string (indefinite length) + { + string_t s; + return get_cbor_string(s) && sax->string(s); + } + + // array (0x00..0x17 data items follow) + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + return get_cbor_array(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0x98: // array (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x99: // array (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9A: // array (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); + } + + case 0x9B: // array (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_array(detail::conditional_static_cast(len), tag_handler); + } + + case 0x9F: // array (indefinite length) + return get_cbor_array(static_cast(-1), tag_handler); + + // map (0x00..0x17 pairs of data items follow) + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + return get_cbor_object(static_cast(static_cast(current) & 0x1Fu), tag_handler); + + case 0xB8: // map (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xB9: // map (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBA: // map (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); + } + + case 0xBB: // map (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_cbor_object(detail::conditional_static_cast(len), tag_handler); + } + + case 0xBF: // map (indefinite length) + return get_cbor_object(static_cast(-1), tag_handler); + + case 0xC6: // tagged item + case 0xC7: + case 0xC8: + case 0xC9: + case 0xCA: + case 0xCB: + case 0xCC: + case 0xCD: + case 0xCE: + case 0xCF: + case 0xD0: + case 0xD1: + case 0xD2: + case 0xD3: + case 0xD4: + case 0xD8: // tagged item (1 bytes follow) + case 0xD9: // tagged item (2 bytes follow) + case 0xDA: // tagged item (4 bytes follow) + case 0xDB: // tagged item (8 bytes follow) + { + switch (tag_handler) + { + case cbor_tag_handler_t::error: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + + case cbor_tag_handler_t::ignore: + { + // ignore binary subtype + switch (current) + { + case 0xD8: + { + std::uint8_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + case 0xD9: + { + std::uint16_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + case 0xDA: + { + std::uint32_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + case 0xDB: + { + std::uint64_t subtype_to_ignore{}; + get_number(input_format_t::cbor, subtype_to_ignore); + break; + } + default: + break; + } + return parse_cbor_internal(true, tag_handler); + } + + case cbor_tag_handler_t::store: + { + binary_t b; + // use binary subtype and store in binary container + switch (current) + { + case 0xD8: + { + std::uint8_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + case 0xD9: + { + std::uint16_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + case 0xDA: + { + std::uint32_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + case 0xDB: + { + std::uint64_t subtype{}; + get_number(input_format_t::cbor, subtype); + b.set_subtype(detail::conditional_static_cast(subtype)); + break; + } + default: + return parse_cbor_internal(true, tag_handler); + } + get(); + return get_cbor_binary(b) && sax->binary(b); + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + case 0xF4: // false + return sax->boolean(false); + + case 0xF5: // true + return sax->boolean(true); + + case 0xF6: // null + return sax->null(); + + case 0xF9: // Half-Precision Float (two-byte IEEE 754) + { + const auto byte1_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + const auto byte2_raw = get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) + { + return false; + } + + const auto byte1 = static_cast(byte1_raw); + const auto byte2 = static_cast(byte2_raw); + + // code from RFC 7049, Appendix D, Figure 3: + // As half-precision floating-point numbers were only added + // to IEEE 754 in 2008, today's programming platforms often + // still only have limited support for them. It is very + // easy to include at least decoding support for them even + // without such support. An example of a small decoder for + // half-precision floating-point numbers in the C language + // is shown in Fig. 3. + const auto half = static_cast((byte1 << 8u) + byte2); + const double val = [&half] + { + const int exp = (half >> 10u) & 0x1Fu; + const unsigned int mant = half & 0x3FFu; + JSON_ASSERT(0 <= exp&& exp <= 32); + JSON_ASSERT(mant <= 1024); + switch (exp) + { + case 0: + return std::ldexp(mant, -24); + case 31: + return (mant == 0) + ? std::numeric_limits::infinity() + : std::numeric_limits::quiet_NaN(); + default: + return std::ldexp(mant + 1024, exp - 25); + } + }(); + return sax->number_float((half & 0x8000u) != 0 + ? static_cast(-val) + : static_cast(val), ""); + } + + case 0xFA: // Single-Precision Float (four-byte IEEE 754) + { + float number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + case 0xFB: // Double-Precision Float (eight-byte IEEE 754) + { + double number{}; + return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); + } + + default: // anything else (0xFF is handled inside the other types) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @brief reads a CBOR string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + Additionally, CBOR's strings with indefinite lengths are supported. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_cbor_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) + { + return false; + } + + switch (current) + { + // UTF-8 string (0x00..0x17 bytes follow) + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + { + return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x78: // UTF-8 string (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x79: // UTF-8 string (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); + } + + case 0x7F: // UTF-8 string (indefinite length) + { + while (get() != 0xFF) + { + string_t chunk; + if (!get_cbor_string(chunk)) + { + return false; + } + result.append(chunk); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + } + + /*! + @brief reads a CBOR byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into the byte array. + Additionally, CBOR's byte arrays with indefinite lengths are supported. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_cbor_binary(binary_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) + { + return false; + } + + switch (current) + { + // Binary data (0x00..0x17 bytes follow) + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + { + return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); + } + + case 0x58: // Binary data (one-byte uint8_t for n follows) + { + std::uint8_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x59: // Binary data (two-byte uint16_t for n follow) + { + std::uint16_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5A: // Binary data (four-byte uint32_t for n follow) + { + std::uint32_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5B: // Binary data (eight-byte uint64_t for n follow) + { + std::uint64_t len{}; + return get_number(input_format_t::cbor, len) && + get_binary(input_format_t::cbor, len, result); + } + + case 0x5F: // Binary data (indefinite length) + { + while (get() != 0xFF) + { + binary_t chunk; + if (!get_cbor_binary(chunk)) + { + return false; + } + result.insert(result.end(), chunk.begin(), chunk.end()); + } + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x" + last_token, "binary"), BasicJsonType())); + } + } + } + + /*! + @param[in] len the length of the array or static_cast(-1) for an + array of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether array creation completed + */ + bool get_cbor_array(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + if (len != static_cast(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) + { + return false; + } + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object or static_cast(-1) for an + object of indefinite size + @param[in] tag_handler how CBOR tags should be treated + @return whether object creation completed + */ + bool get_cbor_object(const std::size_t len, + const cbor_tag_handler_t tag_handler) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + if (len != 0) + { + string_t key; + if (len != static_cast(-1)) + { + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + else + { + while (get() != 0xFF) + { + if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) + { + return false; + } + key.clear(); + } + } + } + + return sax->end_object(); + } + + ///////////// + // MsgPack // + ///////////// + + /*! + @return whether a valid MessagePack value was passed to the SAX parser + */ + bool parse_msgpack_internal() + { + switch (get()) + { + // EOF + case std::char_traits::eof(): + return unexpect_eof(input_format_t::msgpack, "value"); + + // positive fixint + case 0x00: + case 0x01: + case 0x02: + case 0x03: + case 0x04: + case 0x05: + case 0x06: + case 0x07: + case 0x08: + case 0x09: + case 0x0A: + case 0x0B: + case 0x0C: + case 0x0D: + case 0x0E: + case 0x0F: + case 0x10: + case 0x11: + case 0x12: + case 0x13: + case 0x14: + case 0x15: + case 0x16: + case 0x17: + case 0x18: + case 0x19: + case 0x1A: + case 0x1B: + case 0x1C: + case 0x1D: + case 0x1E: + case 0x1F: + case 0x20: + case 0x21: + case 0x22: + case 0x23: + case 0x24: + case 0x25: + case 0x26: + case 0x27: + case 0x28: + case 0x29: + case 0x2A: + case 0x2B: + case 0x2C: + case 0x2D: + case 0x2E: + case 0x2F: + case 0x30: + case 0x31: + case 0x32: + case 0x33: + case 0x34: + case 0x35: + case 0x36: + case 0x37: + case 0x38: + case 0x39: + case 0x3A: + case 0x3B: + case 0x3C: + case 0x3D: + case 0x3E: + case 0x3F: + case 0x40: + case 0x41: + case 0x42: + case 0x43: + case 0x44: + case 0x45: + case 0x46: + case 0x47: + case 0x48: + case 0x49: + case 0x4A: + case 0x4B: + case 0x4C: + case 0x4D: + case 0x4E: + case 0x4F: + case 0x50: + case 0x51: + case 0x52: + case 0x53: + case 0x54: + case 0x55: + case 0x56: + case 0x57: + case 0x58: + case 0x59: + case 0x5A: + case 0x5B: + case 0x5C: + case 0x5D: + case 0x5E: + case 0x5F: + case 0x60: + case 0x61: + case 0x62: + case 0x63: + case 0x64: + case 0x65: + case 0x66: + case 0x67: + case 0x68: + case 0x69: + case 0x6A: + case 0x6B: + case 0x6C: + case 0x6D: + case 0x6E: + case 0x6F: + case 0x70: + case 0x71: + case 0x72: + case 0x73: + case 0x74: + case 0x75: + case 0x76: + case 0x77: + case 0x78: + case 0x79: + case 0x7A: + case 0x7B: + case 0x7C: + case 0x7D: + case 0x7E: + case 0x7F: + return sax->number_unsigned(static_cast(current)); + + // fixmap + case 0x80: + case 0x81: + case 0x82: + case 0x83: + case 0x84: + case 0x85: + case 0x86: + case 0x87: + case 0x88: + case 0x89: + case 0x8A: + case 0x8B: + case 0x8C: + case 0x8D: + case 0x8E: + case 0x8F: + return get_msgpack_object(static_cast(static_cast(current) & 0x0Fu)); + + // fixarray + case 0x90: + case 0x91: + case 0x92: + case 0x93: + case 0x94: + case 0x95: + case 0x96: + case 0x97: + case 0x98: + case 0x99: + case 0x9A: + case 0x9B: + case 0x9C: + case 0x9D: + case 0x9E: + case 0x9F: + return get_msgpack_array(static_cast(static_cast(current) & 0x0Fu)); + + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + case 0xD9: // str 8 + case 0xDA: // str 16 + case 0xDB: // str 32 + { + string_t s; + return get_msgpack_string(s) && sax->string(s); + } + + case 0xC0: // nil + return sax->null(); + + case 0xC2: // false + return sax->boolean(false); + + case 0xC3: // true + return sax->boolean(true); + + case 0xC4: // bin 8 + case 0xC5: // bin 16 + case 0xC6: // bin 32 + case 0xC7: // ext 8 + case 0xC8: // ext 16 + case 0xC9: // ext 32 + case 0xD4: // fixext 1 + case 0xD5: // fixext 2 + case 0xD6: // fixext 4 + case 0xD7: // fixext 8 + case 0xD8: // fixext 16 + { + binary_t b; + return get_msgpack_binary(b) && sax->binary(b); + } + + case 0xCA: // float 32 + { + float number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCB: // float 64 + { + double number{}; + return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); + } + + case 0xCC: // uint 8 + { + std::uint8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCD: // uint 16 + { + std::uint16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCE: // uint 32 + { + std::uint32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xCF: // uint 64 + { + std::uint64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); + } + + case 0xD0: // int 8 + { + std::int8_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD1: // int 16 + { + std::int16_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD2: // int 32 + { + std::int32_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xD3: // int 64 + { + std::int64_t number{}; + return get_number(input_format_t::msgpack, number) && sax->number_integer(number); + } + + case 0xDC: // array 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDD: // array 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); + } + + case 0xDE: // map 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + case 0xDF: // map 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); + } + + // negative fixint + case 0xE0: + case 0xE1: + case 0xE2: + case 0xE3: + case 0xE4: + case 0xE5: + case 0xE6: + case 0xE7: + case 0xE8: + case 0xE9: + case 0xEA: + case 0xEB: + case 0xEC: + case 0xED: + case 0xEE: + case 0xEF: + case 0xF0: + case 0xF1: + case 0xF2: + case 0xF3: + case 0xF4: + case 0xF5: + case 0xF6: + case 0xF7: + case 0xF8: + case 0xF9: + case 0xFA: + case 0xFB: + case 0xFC: + case 0xFD: + case 0xFE: + case 0xFF: + return sax->number_integer(static_cast(current)); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @brief reads a MessagePack string + + This function first reads starting bytes to determine the expected + string length and then copies this number of bytes into a string. + + @param[out] result created string + + @return whether string creation completed + */ + bool get_msgpack_string(string_t& result) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) + { + return false; + } + + switch (current) + { + // fixstr + case 0xA0: + case 0xA1: + case 0xA2: + case 0xA3: + case 0xA4: + case 0xA5: + case 0xA6: + case 0xA7: + case 0xA8: + case 0xA9: + case 0xAA: + case 0xAB: + case 0xAC: + case 0xAD: + case 0xAE: + case 0xAF: + case 0xB0: + case 0xB1: + case 0xB2: + case 0xB3: + case 0xB4: + case 0xB5: + case 0xB6: + case 0xB7: + case 0xB8: + case 0xB9: + case 0xBA: + case 0xBB: + case 0xBC: + case 0xBD: + case 0xBE: + case 0xBF: + { + return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); + } + + case 0xD9: // str 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDA: // str 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + case 0xDB: // str 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + } + + /*! + @brief reads a MessagePack byte array + + This function first reads starting bytes to determine the expected + byte array length and then copies this number of bytes into a byte array. + + @param[out] result created byte array + + @return whether byte array creation completed + */ + bool get_msgpack_binary(binary_t& result) + { + // helper function to set the subtype + auto assign_and_return_true = [&result](std::int8_t subtype) + { + result.set_subtype(static_cast(subtype)); + return true; + }; + + switch (current) + { + case 0xC4: // bin 8 + { + std::uint8_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC5: // bin 16 + { + std::uint16_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC6: // bin 32 + { + std::uint32_t len{}; + return get_number(input_format_t::msgpack, len) && + get_binary(input_format_t::msgpack, len, result); + } + + case 0xC7: // ext 8 + { + std::uint8_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC8: // ext 16 + { + std::uint16_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xC9: // ext 32 + { + std::uint32_t len{}; + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, len) && + get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, len, result) && + assign_and_return_true(subtype); + } + + case 0xD4: // fixext 1 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 1, result) && + assign_and_return_true(subtype); + } + + case 0xD5: // fixext 2 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 2, result) && + assign_and_return_true(subtype); + } + + case 0xD6: // fixext 4 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 4, result) && + assign_and_return_true(subtype); + } + + case 0xD7: // fixext 8 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 8, result) && + assign_and_return_true(subtype); + } + + case 0xD8: // fixext 16 + { + std::int8_t subtype{}; + return get_number(input_format_t::msgpack, subtype) && + get_binary(input_format_t::msgpack, 16, result) && + assign_and_return_true(subtype); + } + + default: // LCOV_EXCL_LINE + return false; // LCOV_EXCL_LINE + } + } + + /*! + @param[in] len the length of the array + @return whether array creation completed + */ + bool get_msgpack_array(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) + { + return false; + } + + for (std::size_t i = 0; i < len; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + } + + return sax->end_array(); + } + + /*! + @param[in] len the length of the object + @return whether object creation completed + */ + bool get_msgpack_object(const std::size_t len) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) + { + return false; + } + + string_t key; + for (std::size_t i = 0; i < len; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) + { + return false; + } + + if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) + { + return false; + } + key.clear(); + } + + return sax->end_object(); + } + + //////////// + // UBJSON // + //////////// + + /*! + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether a valid UBJSON value was passed to the SAX parser + */ + bool parse_ubjson_internal(const bool get_char = true) + { + return get_ubjson_value(get_char ? get_ignore_noop() : current); + } + + /*! + @brief reads a UBJSON string + + This function is either called after reading the 'S' byte explicitly + indicating a string, or in case of an object key where the 'S' byte can be + left out. + + @param[out] result created string + @param[in] get_char whether a new character should be retrieved from the + input (true, default) or whether the last read + character should be considered instead + + @return whether string creation completed + */ + bool get_ubjson_string(string_t& result, const bool get_char = true) + { + if (get_char) + { + get(); // TODO(niels): may we ignore N here? + } + + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + + switch (current) + { + case 'U': + { + std::uint8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'i': + { + std::int8_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'I': + { + std::int16_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'l': + { + std::int32_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + case 'L': + { + std::int64_t len{}; + return get_number(input_format_t::ubjson, len) && get_string(input_format_t::ubjson, len, result); + } + + default: + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"), BasicJsonType())); + } + } + + /*! + @param[out] result determined size + @return whether size determination completed + */ + bool get_ubjson_size_value(std::size_t& result) + { + switch (get_ignore_noop()) + { + case 'U': + { + std::uint8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'i': + { + std::int8_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char + return true; + } + + case 'I': + { + std::int16_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'l': + { + std::int32_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + case 'L': + { + std::int64_t number{}; + if (JSON_HEDLEY_UNLIKELY(!get_number(input_format_t::ubjson, number))) + { + return false; + } + result = static_cast(number); + return true; + } + + default: + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"), BasicJsonType())); + } + } + } + + /*! + @brief determine the type and size for a container + + In the optimized UBJSON format, a type and a size can be provided to allow + for a more compact representation. + + @param[out] result pair of the size and the type + + @return whether pair creation completed + */ + bool get_ubjson_size_type(std::pair& result) + { + result.first = string_t::npos; // size + result.second = 0; // type + + get_ignore_noop(); + + if (current == '$') + { + result.second = get(); // must not ignore 'N', because 'N' maybe the type + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "type"))) + { + return false; + } + + get_ignore_noop(); + if (JSON_HEDLEY_UNLIKELY(current != '#')) + { + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "value"))) + { + return false; + } + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"), BasicJsonType())); + } + + return get_ubjson_size_value(result.first); + } + + if (current == '#') + { + return get_ubjson_size_value(result.first); + } + + return true; + } + + /*! + @param prefix the previously read or set type prefix + @return whether value creation completed + */ + bool get_ubjson_value(const char_int_type prefix) + { + switch (prefix) + { + case std::char_traits::eof(): // EOF + return unexpect_eof(input_format_t::ubjson, "value"); + + case 'T': // true + return sax->boolean(true); + case 'F': // false + return sax->boolean(false); + + case 'Z': // null + return sax->null(); + + case 'U': + { + std::uint8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_unsigned(number); + } + + case 'i': + { + std::int8_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'I': + { + std::int16_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'l': + { + std::int32_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'L': + { + std::int64_t number{}; + return get_number(input_format_t::ubjson, number) && sax->number_integer(number); + } + + case 'd': + { + float number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'D': + { + double number{}; + return get_number(input_format_t::ubjson, number) && sax->number_float(static_cast(number), ""); + } + + case 'H': + { + return get_ubjson_high_precision_number(); + } + + case 'C': // char + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "char"))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(current > 127)) + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"), BasicJsonType())); + } + string_t s(1, static_cast(current)); + return sax->string(s); + } + + case 'S': // string + { + string_t s; + return get_ubjson_string(s) && sax->string(s); + } + + case '[': // array + return get_ubjson_array(); + + case '{': // object + return get_ubjson_object(); + + default: // anything else + { + auto last_token = get_token_string(); + return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"), BasicJsonType())); + } + } + } + + /*! + @return whether array creation completed + */ + bool get_ubjson_array() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + if (size_and_type.second != 'N') + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + } + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) + { + return false; + } + + while (current != ']') + { + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) + { + return false; + } + get_ignore_noop(); + } + } + + return sax->end_array(); + } + + /*! + @return whether object creation completed + */ + bool get_ubjson_object() + { + std::pair size_and_type; + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) + { + return false; + } + + string_t key; + if (size_and_type.first != string_t::npos) + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) + { + return false; + } + + if (size_and_type.second != 0) + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) + { + return false; + } + key.clear(); + } + } + else + { + for (std::size_t i = 0; i < size_and_type.first; ++i) + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + key.clear(); + } + } + } + else + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) + { + return false; + } + + while (current != '}') + { + if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) + { + return false; + } + if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) + { + return false; + } + get_ignore_noop(); + key.clear(); + } + } + + return sax->end_object(); + } + + // Note, no reader for UBJSON binary types is implemented because they do + // not exist + + bool get_ubjson_high_precision_number() + { + // get size of following number string + std::size_t size{}; + auto res = get_ubjson_size_value(size); + if (JSON_HEDLEY_UNLIKELY(!res)) + { + return res; + } + + // get number string + std::vector number_vector; + for (std::size_t i = 0; i < size; ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::ubjson, "number"))) + { + return false; + } + number_vector.push_back(static_cast(current)); + } + + // parse number string + using ia_type = decltype(detail::input_adapter(number_vector)); + auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); + const auto result_number = number_lexer.scan(); + const auto number_string = number_lexer.get_token_string(); + const auto result_remainder = number_lexer.scan(); + + using token_type = typename detail::lexer_base::token_type; + + if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) + { + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); + } + + switch (result_number) + { + case token_type::value_integer: + return sax->number_integer(number_lexer.get_number_integer()); + case token_type::value_unsigned: + return sax->number_unsigned(number_lexer.get_number_unsigned()); + case token_type::value_float: + return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); + case token_type::uninitialized: + case token_type::literal_true: + case token_type::literal_false: + case token_type::literal_null: + case token_type::value_string: + case token_type::begin_array: + case token_type::begin_object: + case token_type::end_array: + case token_type::end_object: + case token_type::name_separator: + case token_type::value_separator: + case token_type::parse_error: + case token_type::end_of_input: + case token_type::literal_or_value: + default: + return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format_t::ubjson, "invalid number text: " + number_lexer.get_token_string(), "high-precision number"), BasicJsonType())); + } + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /*! + @brief get next character from the input + + This function provides the interface to the used input adapter. It does + not throw in case the input reached EOF, but returns a -'ve valued + `std::char_traits::eof()` in that case. + + @return character read from the input + */ + char_int_type get() + { + ++chars_read; + return current = ia.get_character(); + } + + /*! + @return character read from the input after ignoring all 'N' entries + */ + char_int_type get_ignore_noop() + { + do + { + get(); + } + while (current == 'N'); + + return current; + } + + /* + @brief read a number from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[out] result number of type @a NumberType + + @return whether conversion completed + + @note This function needs to respect the system's endianness, because + bytes in CBOR, MessagePack, and UBJSON are stored in network order + (big endian) and therefore need reordering on little endian systems. + */ + template + bool get_number(const input_format_t format, NumberType& result) + { + // step 1: read input into array with system's byte order + std::array vec{}; + for (std::size_t i = 0; i < sizeof(NumberType); ++i) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) + { + return false; + } + + // reverse byte order prior to conversion if necessary + if (is_little_endian != InputIsLittleEndian) + { + vec[sizeof(NumberType) - i - 1] = static_cast(current); + } + else + { + vec[i] = static_cast(current); // LCOV_EXCL_LINE + } + } + + // step 2: convert array into number of type T and return + std::memcpy(&result, vec.data(), sizeof(NumberType)); + return true; + } + + /*! + @brief create a string by reading characters from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of characters to read + @param[out] result string created by reading @a len bytes + + @return whether string creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of string memory. + */ + template + bool get_string(const input_format_t format, + const NumberType len, + string_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @brief create a byte array by reading bytes from the input + + @tparam NumberType the type of the number + @param[in] format the current format (for diagnostics) + @param[in] len number of bytes to read + @param[out] result byte array created by reading @a len bytes + + @return whether byte array creation completed + + @note We can not reserve @a len bytes for the result, because @a len + may be too large. Usually, @ref unexpect_eof() detects the end of + the input before we run out of memory. + */ + template + bool get_binary(const input_format_t format, + const NumberType len, + binary_t& result) + { + bool success = true; + for (NumberType i = 0; i < len; i++) + { + get(); + if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) + { + success = false; + break; + } + result.push_back(static_cast(current)); + } + return success; + } + + /*! + @param[in] format the current format (for diagnostics) + @param[in] context further context information (for diagnostics) + @return whether the last read character is not EOF + */ + JSON_HEDLEY_NON_NULL(3) + bool unexpect_eof(const input_format_t format, const char* context) const + { + if (JSON_HEDLEY_UNLIKELY(current == std::char_traits::eof())) + { + return sax->parse_error(chars_read, "", + parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), BasicJsonType())); + } + return true; + } + + /*! + @return a string representation of the last read byte + */ + std::string get_token_string() const + { + std::array cr{{}}; + static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + return std::string{cr.data()}; + } + + /*! + @param[in] format the current format + @param[in] detail a detailed error message + @param[in] context further context information + @return a message string to use in the parse_error exceptions + */ + std::string exception_message(const input_format_t format, + const std::string& detail, + const std::string& context) const + { + std::string error_msg = "syntax error while parsing "; + + switch (format) + { + case input_format_t::cbor: + error_msg += "CBOR"; + break; + + case input_format_t::msgpack: + error_msg += "MessagePack"; + break; + + case input_format_t::ubjson: + error_msg += "UBJSON"; + break; + + case input_format_t::bson: + error_msg += "BSON"; + break; + + case input_format_t::json: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + + return error_msg + " " + context + ": " + detail; + } + + private: + /// input adapter + InputAdapterType ia; + + /// the current character + char_int_type current = std::char_traits::eof(); + + /// the number of characters read + std::size_t chars_read = 0; + + /// whether we can assume little endianness + const bool is_little_endian = little_endianness(); + + /// the SAX parser + json_sax_t* sax = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // isfinite +#include // uint8_t +#include // function +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +//////////// +// parser // +//////////// + +enum class parse_event_t : std::uint8_t +{ + /// the parser read `{` and started to process a JSON object + object_start, + /// the parser read `}` and finished processing a JSON object + object_end, + /// the parser read `[` and started to process a JSON array + array_start, + /// the parser read `]` and finished processing a JSON array + array_end, + /// the parser read a key of a value in an object + key, + /// the parser finished reading a JSON value + value +}; + +template +using parser_callback_t = + std::function; + +/*! +@brief syntax analysis + +This class implements a recursive descent parser. +*/ +template +class parser +{ + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using number_float_t = typename BasicJsonType::number_float_t; + using string_t = typename BasicJsonType::string_t; + using lexer_t = lexer; + using token_type = typename lexer_t::token_type; + + public: + /// a parser reading from an input adapter + explicit parser(InputAdapterType&& adapter, + const parser_callback_t cb = nullptr, + const bool allow_exceptions_ = true, + const bool skip_comments = false) + : callback(cb) + , m_lexer(std::move(adapter), skip_comments) + , allow_exceptions(allow_exceptions_) + { + // read first token + get_token(); + } + + /*! + @brief public parser interface + + @param[in] strict whether to expect the last token to be EOF + @param[in,out] result parsed JSON value + + @throw parse_error.101 in case of an unexpected token + @throw parse_error.102 if to_unicode fails or surrogate error + @throw parse_error.103 if to_unicode fails + */ + void parse(const bool strict, BasicJsonType& result) + { + if (callback) + { + json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); + sax_parse_internal(&sdp); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), + exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + + // set top-level value to null if it was discarded by the callback + // function + if (result.is_discarded()) + { + result = nullptr; + } + } + else + { + json_sax_dom_parser sdp(result, allow_exceptions); + sax_parse_internal(&sdp); + + // in strict mode, input must be completely read + if (strict && (get_token() != token_type::end_of_input)) + { + sdp.parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + // in case of an error, return discarded value + if (sdp.is_errored()) + { + result = value_t::discarded; + return; + } + } + + result.assert_invariant(); + } + + /*! + @brief public accept interface + + @param[in] strict whether to expect the last token to be EOF + @return whether the input is a proper JSON text + */ + bool accept(const bool strict = true) + { + json_sax_acceptor sax_acceptor; + return sax_parse(&sax_acceptor, strict); + } + + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse(SAX* sax, const bool strict = true) + { + (void)detail::is_sax_static_asserts {}; + const bool result = sax_parse_internal(sax); + + // strict mode: next byte must be EOF + if (result && strict && (get_token() != token_type::end_of_input)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), BasicJsonType())); + } + + return result; + } + + private: + template + JSON_HEDLEY_NON_NULL(2) + bool sax_parse_internal(SAX* sax) + { + // stack to remember the hierarchy of structured values we are parsing + // true = array; false = object + std::vector states; + // value to avoid a goto (see comment where set to true) + bool skip_to_state_evaluation = false; + + while (true) + { + if (!skip_to_state_evaluation) + { + // invariant: get_token() was called before each iteration + switch (last_token) + { + case token_type::begin_object: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) + { + return false; + } + + // closing } -> we are done + if (get_token() == token_type::end_object) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + break; + } + + // parse key + if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); + } + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); + } + + // remember we are now inside an object + states.push_back(false); + + // parse values + get_token(); + continue; + } + + case token_type::begin_array: + { + if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) + { + return false; + } + + // closing ] -> we are done + if (get_token() == token_type::end_array) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + break; + } + + // remember we are now inside an array + states.push_back(true); + + // parse values (no need to call get_token) + continue; + } + + case token_type::value_float: + { + const auto res = m_lexer.get_number_float(); + + if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'", BasicJsonType())); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) + { + return false; + } + + break; + } + + case token_type::literal_false: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) + { + return false; + } + break; + } + + case token_type::literal_null: + { + if (JSON_HEDLEY_UNLIKELY(!sax->null())) + { + return false; + } + break; + } + + case token_type::literal_true: + { + if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) + { + return false; + } + break; + } + + case token_type::value_integer: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) + { + return false; + } + break; + } + + case token_type::value_string: + { + if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) + { + return false; + } + break; + } + + case token_type::value_unsigned: + { + if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) + { + return false; + } + break; + } + + case token_type::parse_error: + { + // using "uninitialized" to avoid "expected" message + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), BasicJsonType())); + } + + case token_type::uninitialized: + case token_type::end_array: + case token_type::end_object: + case token_type::name_separator: + case token_type::value_separator: + case token_type::end_of_input: + case token_type::literal_or_value: + default: // the last token was unexpected + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), BasicJsonType())); + } + } + } + else + { + skip_to_state_evaluation = false; + } + + // we reached this line after we successfully parsed a value + if (states.empty()) + { + // empty stack: we reached the end of the hierarchy: done + return true; + } + + if (states.back()) // array + { + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse a new value + get_token(); + continue; + } + + // closing ] + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) + { + return false; + } + + // We are done with this array. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), BasicJsonType())); + } + + // states.back() is false -> object + + // comma -> next value + if (get_token() == token_type::value_separator) + { + // parse key + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), BasicJsonType())); + } + + if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) + { + return false; + } + + // parse separator (:) + if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) + { + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), BasicJsonType())); + } + + // parse values + get_token(); + continue; + } + + // closing } + if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) + { + if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) + { + return false; + } + + // We are done with this object. Before we can parse a + // new value, we need to evaluate the new state first. + // By setting skip_to_state_evaluation to false, we + // are effectively jumping to the beginning of this if. + JSON_ASSERT(!states.empty()); + states.pop_back(); + skip_to_state_evaluation = true; + continue; + } + + return sax->parse_error(m_lexer.get_position(), + m_lexer.get_token_string(), + parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), BasicJsonType())); + } + } + + /// get next token from lexer + token_type get_token() + { + return last_token = m_lexer.scan(); + } + + std::string exception_message(const token_type expected, const std::string& context) + { + std::string error_msg = "syntax error "; + + if (!context.empty()) + { + error_msg += "while parsing " + context + " "; + } + + error_msg += "- "; + + if (last_token == token_type::parse_error) + { + error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + + m_lexer.get_token_string() + "'"; + } + else + { + error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); + } + + if (expected != token_type::uninitialized) + { + error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); + } + + return error_msg; + } + + private: + /// callback function + const parser_callback_t callback = nullptr; + /// the type of the last read token + token_type last_token = token_type::uninitialized; + /// the lexer + lexer_t m_lexer; + /// whether to throw exceptions in case of errors + const bool allow_exceptions = true; +}; + +} // namespace detail +} // namespace nlohmann + +// #include + + +// #include + + +#include // ptrdiff_t +#include // numeric_limits + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/* +@brief an iterator for primitive JSON types + +This class models an iterator for primitive JSON types (boolean, number, +string). It's only purpose is to allow the iterator/const_iterator classes +to "iterate" over primitive values. Internally, the iterator is modeled by +a `difference_type` variable. Value begin_value (`0`) models the begin, +end_value (`1`) models past the end. +*/ +class primitive_iterator_t +{ + private: + using difference_type = std::ptrdiff_t; + static constexpr difference_type begin_value = 0; + static constexpr difference_type end_value = begin_value + 1; + + JSON_PRIVATE_UNLESS_TESTED: + /// iterator as signed integer type + difference_type m_it = (std::numeric_limits::min)(); + + public: + constexpr difference_type get_value() const noexcept + { + return m_it; + } + + /// set iterator to a defined beginning + void set_begin() noexcept + { + m_it = begin_value; + } + + /// set iterator to a defined past the end + void set_end() noexcept + { + m_it = end_value; + } + + /// return whether the iterator can be dereferenced + constexpr bool is_begin() const noexcept + { + return m_it == begin_value; + } + + /// return whether the iterator is at end + constexpr bool is_end() const noexcept + { + return m_it == end_value; + } + + friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it == rhs.m_it; + } + + friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it < rhs.m_it; + } + + primitive_iterator_t operator+(difference_type n) noexcept + { + auto result = *this; + result += n; + return result; + } + + friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept + { + return lhs.m_it - rhs.m_it; + } + + primitive_iterator_t& operator++() noexcept + { + ++m_it; + return *this; + } + + primitive_iterator_t const operator++(int) noexcept // NOLINT(readability-const-return-type) + { + auto result = *this; + ++m_it; + return result; + } + + primitive_iterator_t& operator--() noexcept + { + --m_it; + return *this; + } + + primitive_iterator_t const operator--(int) noexcept // NOLINT(readability-const-return-type) + { + auto result = *this; + --m_it; + return result; + } + + primitive_iterator_t& operator+=(difference_type n) noexcept + { + m_it += n; + return *this; + } + + primitive_iterator_t& operator-=(difference_type n) noexcept + { + m_it -= n; + return *this; + } +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/*! +@brief an iterator value + +@note This structure could easily be a union, but MSVC currently does not allow +unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. +*/ +template struct internal_iterator +{ + /// iterator for JSON objects + typename BasicJsonType::object_t::iterator object_iterator {}; + /// iterator for JSON arrays + typename BasicJsonType::array_t::iterator array_iterator {}; + /// generic iterator for all other types + primitive_iterator_t primitive_iterator {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + + +#include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next +#include // conditional, is_const, remove_const + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +// forward declare, to be able to friend it later on +template class iteration_proxy; +template class iteration_proxy_value; + +/*! +@brief a template for a bidirectional iterator for the @ref basic_json class +This class implements a both iterators (iterator and const_iterator) for the +@ref basic_json class. +@note An iterator is called *initialized* when a pointer to a JSON value has + been set (e.g., by a constructor or a copy assignment). If the iterator is + default-constructed, it is *uninitialized* and most methods are undefined. + **The library uses assertions to detect calls on uninitialized iterators.** +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +@since version 1.0.0, simplified in version 2.0.9, change to bidirectional + iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) +*/ +template +class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) +{ + /// the iterator with BasicJsonType of different const-ness + using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; + /// allow basic_json to access private members + friend other_iter_impl; + friend BasicJsonType; + friend iteration_proxy; + friend iteration_proxy_value; + + using object_t = typename BasicJsonType::object_t; + using array_t = typename BasicJsonType::array_t; + // make sure BasicJsonType is basic_json or const basic_json + static_assert(is_basic_json::type>::value, + "iter_impl only accepts (const) basic_json"); + + public: + + /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. + /// The C++ Standard has never required user-defined iterators to derive from std::iterator. + /// A user-defined iterator should provide publicly accessible typedefs named + /// iterator_category, value_type, difference_type, pointer, and reference. + /// Note that value_type is required to be non-const, even for constant iterators. + using iterator_category = std::bidirectional_iterator_tag; + + /// the type of the values when the iterator is dereferenced + using value_type = typename BasicJsonType::value_type; + /// a type to represent differences between iterators + using difference_type = typename BasicJsonType::difference_type; + /// defines a pointer to the type iterated over (value_type) + using pointer = typename std::conditional::value, + typename BasicJsonType::const_pointer, + typename BasicJsonType::pointer>::type; + /// defines a reference to the type iterated over (value_type) + using reference = + typename std::conditional::value, + typename BasicJsonType::const_reference, + typename BasicJsonType::reference>::type; + + iter_impl() = default; + ~iter_impl() = default; + iter_impl(iter_impl&&) noexcept = default; + iter_impl& operator=(iter_impl&&) noexcept = default; + + /*! + @brief constructor for a given JSON instance + @param[in] object pointer to a JSON object for this iterator + @pre object != nullptr + @post The iterator is initialized; i.e. `m_object != nullptr`. + */ + explicit iter_impl(pointer object) noexcept : m_object(object) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = typename object_t::iterator(); + break; + } + + case value_t::array: + { + m_it.array_iterator = typename array_t::iterator(); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator = primitive_iterator_t(); + break; + } + } + } + + /*! + @note The conventional copy constructor and copy assignment are implicitly + defined. Combined with the following converting constructor and + assignment, they support: (1) copy from iterator to iterator, (2) + copy from const iterator to const iterator, and (3) conversion from + iterator to const iterator. However conversion from const iterator + to iterator is not defined. + */ + + /*! + @brief const copy constructor + @param[in] other const iterator to copy from + @note This copy constructor had to be defined explicitly to circumvent a bug + occurring on msvc v19.0 compiler (VS 2015) debug build. For more + information refer to: https://github.com/nlohmann/json/issues/1608 + */ + iter_impl(const iter_impl& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl& other) noexcept + { + if (&other != this) + { + m_object = other.m_object; + m_it = other.m_it; + } + return *this; + } + + /*! + @brief converting constructor + @param[in] other non-const iterator to copy from + @note It is not checked whether @a other is initialized. + */ + iter_impl(const iter_impl::type>& other) noexcept + : m_object(other.m_object), m_it(other.m_it) + {} + + /*! + @brief converting assignment + @param[in] other non-const iterator to copy from + @return const/non-const iterator + @note It is not checked whether @a other is initialized. + */ + iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) + { + m_object = other.m_object; + m_it = other.m_it; + return *this; + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief set the iterator to the first value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_begin() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->begin(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->begin(); + break; + } + + case value_t::null: + { + // set to end so begin()==end() is true: null is empty + m_it.primitive_iterator.set_end(); + break; + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator.set_begin(); + break; + } + } + } + + /*! + @brief set the iterator past the last value + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + void set_end() noexcept + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + m_it.object_iterator = m_object->m_value.object->end(); + break; + } + + case value_t::array: + { + m_it.array_iterator = m_object->m_value.array->end(); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator.set_end(); + break; + } + } + } + + public: + /*! + @brief return a reference to the value pointed to by the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator*() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return m_it.object_iterator->second; + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return *m_it.array_iterator; + } + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief dereference the iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + pointer operator->() const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + JSON_ASSERT(m_it.object_iterator != m_object->m_value.object->end()); + return &(m_it.object_iterator->second); + } + + case value_t::array: + { + JSON_ASSERT(m_it.array_iterator != m_object->m_value.array->end()); + return &*m_it.array_iterator; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) + { + return m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief post-increment (it++) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator++(int) // NOLINT(readability-const-return-type) + { + auto result = *this; + ++(*this); + return result; + } + + /*! + @brief pre-increment (++it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator++() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, 1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, 1); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + ++m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief post-decrement (it--) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl const operator--(int) // NOLINT(readability-const-return-type) + { + auto result = *this; + --(*this); + return result; + } + + /*! + @brief pre-decrement (--it) + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator--() + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + { + std::advance(m_it.object_iterator, -1); + break; + } + + case value_t::array: + { + std::advance(m_it.array_iterator, -1); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + --m_it.primitive_iterator; + break; + } + } + + return *this; + } + + /*! + @brief comparison: equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > + bool operator==(const IterImpl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + return (m_it.object_iterator == other.m_it.object_iterator); + + case value_t::array: + return (m_it.array_iterator == other.m_it.array_iterator); + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return (m_it.primitive_iterator == other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: not equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > + bool operator!=(const IterImpl& other) const + { + return !operator==(other); + } + + /*! + @brief comparison: smaller + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<(const iter_impl& other) const + { + // if objects are not the same, the comparison is undefined + if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) + { + JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", *m_object)); + } + + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", *m_object)); + + case value_t::array: + return (m_it.array_iterator < other.m_it.array_iterator); + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return (m_it.primitive_iterator < other.m_it.primitive_iterator); + } + } + + /*! + @brief comparison: less than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator<=(const iter_impl& other) const + { + return !other.operator < (*this); + } + + /*! + @brief comparison: greater than + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>(const iter_impl& other) const + { + return !operator<=(other); + } + + /*! + @brief comparison: greater than or equal + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + bool operator>=(const iter_impl& other) const + { + return !operator<(other); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator+=(difference_type i) + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); + + case value_t::array: + { + std::advance(m_it.array_iterator, i); + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + m_it.primitive_iterator += i; + break; + } + } + + return *this; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl& operator-=(difference_type i) + { + return operator+=(-i); + } + + /*! + @brief add to iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator+(difference_type i) const + { + auto result = *this; + result += i; + return result; + } + + /*! + @brief addition of distance and iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + friend iter_impl operator+(difference_type i, const iter_impl& it) + { + auto result = it; + result += i; + return result; + } + + /*! + @brief subtract from iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + iter_impl operator-(difference_type i) const + { + auto result = *this; + result -= i; + return result; + } + + /*! + @brief return difference + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + difference_type operator-(const iter_impl& other) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", *m_object)); + + case value_t::array: + return m_it.array_iterator - other.m_it.array_iterator; + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + return m_it.primitive_iterator - other.m_it.primitive_iterator; + } + } + + /*! + @brief access to successor + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference operator[](difference_type n) const + { + JSON_ASSERT(m_object != nullptr); + + switch (m_object->m_type) + { + case value_t::object: + JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", *m_object)); + + case value_t::array: + return *std::next(m_it.array_iterator, n); + + case value_t::null: + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) + { + return *m_object; + } + + JSON_THROW(invalid_iterator::create(214, "cannot get value", *m_object)); + } + } + } + + /*! + @brief return the key of an object iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + const typename object_t::key_type& key() const + { + JSON_ASSERT(m_object != nullptr); + + if (JSON_HEDLEY_LIKELY(m_object->is_object())) + { + return m_it.object_iterator->first; + } + + JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", *m_object)); + } + + /*! + @brief return the value of an iterator + @pre The iterator is initialized; i.e. `m_object != nullptr`. + */ + reference value() const + { + return operator*(); + } + + JSON_PRIVATE_UNLESS_TESTED: + /// associated JSON instance + pointer m_object = nullptr; + /// the actual iterator of the associated instance + internal_iterator::type> m_it {}; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // ptrdiff_t +#include // reverse_iterator +#include // declval + +namespace nlohmann +{ +namespace detail +{ +////////////////////// +// reverse_iterator // +////////////////////// + +/*! +@brief a template for a reverse iterator class + +@tparam Base the base iterator type to reverse. Valid types are @ref +iterator (to create @ref reverse_iterator) and @ref const_iterator (to +create @ref const_reverse_iterator). + +@requirement The class satisfies the following concept requirements: +- +[BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): + The iterator that can be moved can be moved in both directions (i.e. + incremented and decremented). +- [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): + It is possible to write to the pointed-to element (only if @a Base is + @ref iterator). + +@since version 1.0.0 +*/ +template +class json_reverse_iterator : public std::reverse_iterator +{ + public: + using difference_type = std::ptrdiff_t; + /// shortcut to the reverse iterator adapter + using base_iterator = std::reverse_iterator; + /// the reference type for the pointed-to element + using reference = typename Base::reference; + + /// create reverse iterator from iterator + explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept + : base_iterator(it) {} + + /// create reverse iterator from base class + explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} + + /// post-increment (it++) + json_reverse_iterator const operator++(int) // NOLINT(readability-const-return-type) + { + return static_cast(base_iterator::operator++(1)); + } + + /// pre-increment (++it) + json_reverse_iterator& operator++() + { + return static_cast(base_iterator::operator++()); + } + + /// post-decrement (it--) + json_reverse_iterator const operator--(int) // NOLINT(readability-const-return-type) + { + return static_cast(base_iterator::operator--(1)); + } + + /// pre-decrement (--it) + json_reverse_iterator& operator--() + { + return static_cast(base_iterator::operator--()); + } + + /// add to iterator + json_reverse_iterator& operator+=(difference_type i) + { + return static_cast(base_iterator::operator+=(i)); + } + + /// add to iterator + json_reverse_iterator operator+(difference_type i) const + { + return static_cast(base_iterator::operator+(i)); + } + + /// subtract from iterator + json_reverse_iterator operator-(difference_type i) const + { + return static_cast(base_iterator::operator-(i)); + } + + /// return difference + difference_type operator-(const json_reverse_iterator& other) const + { + return base_iterator(*this) - base_iterator(other); + } + + /// access to successor + reference operator[](difference_type n) const + { + return *(this->operator+(n)); + } + + /// return the key of an object iterator + auto key() const -> decltype(std::declval().key()) + { + auto it = --this->base(); + return it.key(); + } + + /// return the value of an iterator + reference value() const + { + auto it = --this->base(); + return it.operator * (); + } +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // all_of +#include // isdigit +#include // max +#include // accumulate +#include // string +#include // move +#include // vector + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ + +/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document +/// @sa https://json.nlohmann.me/api/json_pointer/ +template +class json_pointer +{ + // allow basic_json to access private members + NLOHMANN_BASIC_JSON_TPL_DECLARATION + friend class basic_json; + + public: + /// @brief create JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ + explicit json_pointer(const std::string& s = "") + : reference_tokens(split(s)) + {} + + /// @brief return a string representation of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ + std::string to_string() const + { + return std::accumulate(reference_tokens.begin(), reference_tokens.end(), + std::string{}, + [](const std::string & a, const std::string & b) + { + return a + "/" + detail::escape(b); + }); + } + + /// @brief return a string representation of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/ + operator std::string() const + { + return to_string(); + } + + /// @brief append another JSON pointer at the end of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ + json_pointer& operator/=(const json_pointer& ptr) + { + reference_tokens.insert(reference_tokens.end(), + ptr.reference_tokens.begin(), + ptr.reference_tokens.end()); + return *this; + } + + /// @brief append an unescaped reference token at the end of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ + json_pointer& operator/=(std::string token) + { + push_back(std::move(token)); + return *this; + } + + /// @brief append an array index at the end of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ + json_pointer& operator/=(std::size_t array_idx) + { + return *this /= std::to_string(array_idx); + } + + /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ + friend json_pointer operator/(const json_pointer& lhs, + const json_pointer& rhs) + { + return json_pointer(lhs) /= rhs; + } + + /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ + friend json_pointer operator/(const json_pointer& lhs, std::string token) // NOLINT(performance-unnecessary-value-param) + { + return json_pointer(lhs) /= std::move(token); + } + + /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ + friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) + { + return json_pointer(lhs) /= array_idx; + } + + /// @brief returns the parent of this JSON pointer + /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ + json_pointer parent_pointer() const + { + if (empty()) + { + return *this; + } + + json_pointer res = *this; + res.pop_back(); + return res; + } + + /// @brief remove last reference token + /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ + void pop_back() + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + reference_tokens.pop_back(); + } + + /// @brief return last reference token + /// @sa https://json.nlohmann.me/api/json_pointer/back/ + const std::string& back() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + return reference_tokens.back(); + } + + /// @brief append an unescaped token at the end of the reference pointer + /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ + void push_back(const std::string& token) + { + reference_tokens.push_back(token); + } + + /// @brief append an unescaped token at the end of the reference pointer + /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ + void push_back(std::string&& token) + { + reference_tokens.push_back(std::move(token)); + } + + /// @brief return whether pointer points to the root document + /// @sa https://json.nlohmann.me/api/json_pointer/empty/ + bool empty() const noexcept + { + return reference_tokens.empty(); + } + + private: + /*! + @param[in] s reference token to be converted into an array index + + @return integer representation of @a s + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index begins not with a digit + @throw out_of_range.404 if string @a s could not be converted to an integer + @throw out_of_range.410 if an array index exceeds size_type + */ + static typename BasicJsonType::size_type array_index(const std::string& s) + { + using size_type = typename BasicJsonType::size_type; + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) + { + JSON_THROW(detail::parse_error::create(106, 0, "array index '" + s + "' must not begin with '0'", BasicJsonType())); + } + + // error condition (cf. RFC 6901, Sect. 4) + if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) + { + JSON_THROW(detail::parse_error::create(109, 0, "array index '" + s + "' is not a number", BasicJsonType())); + } + + std::size_t processed_chars = 0; + unsigned long long res = 0; // NOLINT(runtime/int) + JSON_TRY + { + res = std::stoull(s, &processed_chars); + } + JSON_CATCH(std::out_of_range&) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); + } + + // check if the string was completely read + if (JSON_HEDLEY_UNLIKELY(processed_chars != s.size())) + { + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'", BasicJsonType())); + } + + // only triggered on special platforms (like 32bit), see also + // https://github.com/nlohmann/json/pull/2203 + if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) + { + JSON_THROW(detail::out_of_range::create(410, "array index " + s + " exceeds size_type", BasicJsonType())); // LCOV_EXCL_LINE + } + + return static_cast(res); + } + + JSON_PRIVATE_UNLESS_TESTED: + json_pointer top() const + { + if (JSON_HEDLEY_UNLIKELY(empty())) + { + JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", BasicJsonType())); + } + + json_pointer result = *this; + result.reference_tokens = {reference_tokens[0]}; + return result; + } + + private: + /*! + @brief create and return a reference to the pointed to value + + @complexity Linear in the number of reference tokens. + + @throw parse_error.109 if array index is not a number + @throw type_error.313 if value cannot be unflattened + */ + BasicJsonType& get_and_create(BasicJsonType& j) const + { + auto* result = &j; + + // in case no reference tokens exist, return a reference to the JSON value + // j which will be overwritten by a primitive value + for (const auto& reference_token : reference_tokens) + { + switch (result->type()) + { + case detail::value_t::null: + { + if (reference_token == "0") + { + // start a new array if reference token is 0 + result = &result->operator[](0); + } + else + { + // start a new object otherwise + result = &result->operator[](reference_token); + } + break; + } + + case detail::value_t::object: + { + // create an entry in the object + result = &result->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + // create an entry in the array + result = &result->operator[](array_index(reference_token)); + break; + } + + /* + The following code is only reached if there exists a reference + token _and_ the current value is primitive. In this case, we have + an error situation, because primitive values may only occur as + single value; that is, with an empty list of reference tokens. + */ + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", j)); + } + } + + return *result; + } + + /*! + @brief return a reference to the pointed to value + + @note This version does not throw if a value is not present, but tries to + create nested values instead. For instance, calling this function + with pointer `"/this/that"` on a null value is equivalent to calling + `operator[]("this").operator[]("that")` on that value, effectively + changing the null value to an object. + + @param[in] ptr a JSON value + + @return reference to the JSON value pointed to by the JSON pointer + + @complexity Linear in the length of the JSON pointer. + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_unchecked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + // convert null values to arrays or objects before continuing + if (ptr->is_null()) + { + // check if reference token is a number + const bool nums = + std::all_of(reference_token.begin(), reference_token.end(), + [](const unsigned char x) + { + return std::isdigit(x); + }); + + // change value to array for numbers or "-" or to object otherwise + *ptr = (nums || reference_token == "-") + ? detail::value_t::array + : detail::value_t::object; + } + + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (reference_token == "-") + { + // explicitly treat "-" as index beyond the end + ptr = &ptr->operator[](ptr->m_value.array->size()); + } + else + { + // convert array index to number; unchecked access + ptr = &ptr->operator[](array_index(reference_token)); + } + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + BasicJsonType& get_checked(BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range", *ptr)); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @brief return a const reference to the pointed to value + + @param[in] ptr a JSON value + + @return const reference to the JSON value pointed to by the JSON + pointer + + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // use unchecked object access + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" cannot be used for const access + JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range", *ptr)); + } + + // use unchecked array access + ptr = &ptr->operator[](array_index(reference_token)); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + @throw out_of_range.402 if the array index '-' is used + @throw out_of_range.404 if the JSON pointer can not be resolved + */ + const BasicJsonType& get_checked(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + // note: at performs range check + ptr = &ptr->at(reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + JSON_THROW(detail::out_of_range::create(402, + "array index '-' (" + std::to_string(ptr->m_value.array->size()) + + ") is out of range", *ptr)); + } + + // note: at performs range check + ptr = &ptr->at(array_index(reference_token)); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'", *ptr)); + } + } + + return *ptr; + } + + /*! + @throw parse_error.106 if an array index begins with '0' + @throw parse_error.109 if an array index was not a number + */ + bool contains(const BasicJsonType* ptr) const + { + for (const auto& reference_token : reference_tokens) + { + switch (ptr->type()) + { + case detail::value_t::object: + { + if (!ptr->contains(reference_token)) + { + // we did not find the key in the object + return false; + } + + ptr = &ptr->operator[](reference_token); + break; + } + + case detail::value_t::array: + { + if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) + { + // "-" always fails the range check + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) + { + // invalid char + return false; + } + if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) + { + if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) + { + // first char should be between '1' and '9' + return false; + } + for (std::size_t i = 1; i < reference_token.size(); i++) + { + if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) + { + // other char should be between '0' and '9' + return false; + } + } + } + + const auto idx = array_index(reference_token); + if (idx >= ptr->size()) + { + // index out of range + return false; + } + + ptr = &ptr->operator[](idx); + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + { + // we do not expect primitive values if there is still a + // reference token to process + return false; + } + } + } + + // no reference token left means we found a primitive value + return true; + } + + /*! + @brief split the string input to reference tokens + + @note This function is only called by the json_pointer constructor. + All exceptions below are documented there. + + @throw parse_error.107 if the pointer is not empty or begins with '/' + @throw parse_error.108 if character '~' is not followed by '0' or '1' + */ + static std::vector split(const std::string& reference_string) + { + std::vector result; + + // special case: empty reference string -> no reference tokens + if (reference_string.empty()) + { + return result; + } + + // check if nonempty reference string begins with slash + if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) + { + JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'", BasicJsonType())); + } + + // extract the reference tokens: + // - slash: position of the last read slash (or end of string) + // - start: position after the previous slash + for ( + // search for the first slash after the first character + std::size_t slash = reference_string.find_first_of('/', 1), + // set the beginning of the first reference token + start = 1; + // we can stop if start == 0 (if slash == std::string::npos) + start != 0; + // set the beginning of the next reference token + // (will eventually be 0 if slash == std::string::npos) + start = (slash == std::string::npos) ? 0 : slash + 1, + // find next slash + slash = reference_string.find_first_of('/', start)) + { + // use the text between the beginning of the reference token + // (start) and the last slash (slash). + auto reference_token = reference_string.substr(start, slash - start); + + // check reference tokens are properly escaped + for (std::size_t pos = reference_token.find_first_of('~'); + pos != std::string::npos; + pos = reference_token.find_first_of('~', pos + 1)) + { + JSON_ASSERT(reference_token[pos] == '~'); + + // ~ must be followed by 0 or 1 + if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || + (reference_token[pos + 1] != '0' && + reference_token[pos + 1] != '1'))) + { + JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", BasicJsonType())); + } + } + + // finally, store the reference token + detail::unescape(reference_token); + result.push_back(reference_token); + } + + return result; + } + + private: + /*! + @param[in] reference_string the reference string to the current value + @param[in] value the value to consider + @param[in,out] result the result object to insert values to + + @note Empty objects or arrays are flattened to `null`. + */ + static void flatten(const std::string& reference_string, + const BasicJsonType& value, + BasicJsonType& result) + { + switch (value.type()) + { + case detail::value_t::array: + { + if (value.m_value.array->empty()) + { + // flatten empty array as null + result[reference_string] = nullptr; + } + else + { + // iterate array and use index as reference string + for (std::size_t i = 0; i < value.m_value.array->size(); ++i) + { + flatten(reference_string + "/" + std::to_string(i), + value.m_value.array->operator[](i), result); + } + } + break; + } + + case detail::value_t::object: + { + if (value.m_value.object->empty()) + { + // flatten empty object as null + result[reference_string] = nullptr; + } + else + { + // iterate object and use keys as reference string + for (const auto& element : *value.m_value.object) + { + flatten(reference_string + "/" + detail::escape(element.first), element.second, result); + } + } + break; + } + + case detail::value_t::null: + case detail::value_t::string: + case detail::value_t::boolean: + case detail::value_t::number_integer: + case detail::value_t::number_unsigned: + case detail::value_t::number_float: + case detail::value_t::binary: + case detail::value_t::discarded: + default: + { + // add primitive value with its reference string + result[reference_string] = value; + break; + } + } + } + + /*! + @param[in] value flattened JSON + + @return unflattened JSON + + @throw parse_error.109 if array index is not a number + @throw type_error.314 if value is not an object + @throw type_error.315 if object values are not primitive + @throw type_error.313 if value cannot be unflattened + */ + static BasicJsonType + unflatten(const BasicJsonType& value) + { + if (JSON_HEDLEY_UNLIKELY(!value.is_object())) + { + JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", value)); + } + + BasicJsonType result; + + // iterate the JSON object values + for (const auto& element : *value.m_value.object) + { + if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) + { + JSON_THROW(detail::type_error::create(315, "values in object must be primitive", element.second)); + } + + // assign value to reference pointed to by JSON pointer; Note that if + // the JSON pointer is "" (i.e., points to the whole value), function + // get_and_create returns a reference to result itself. An assignment + // will then create a primitive value. + json_pointer(element.first).get_and_create(result) = element.second; + } + + return result; + } + + /*! + @brief compares two JSON pointers for equality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is equal to @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator==(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return lhs.reference_tokens == rhs.reference_tokens; + } + + /*! + @brief compares two JSON pointers for inequality + + @param[in] lhs JSON pointer to compare + @param[in] rhs JSON pointer to compare + @return whether @a lhs is not equal @a rhs + + @complexity Linear in the length of the JSON pointer + + @exceptionsafety No-throw guarantee: this function never throws exceptions. + */ + friend bool operator!=(json_pointer const& lhs, + json_pointer const& rhs) noexcept + { + return !(lhs == rhs); + } + + /// the reference tokens + std::vector reference_tokens; +}; +} // namespace nlohmann + +// #include + + +#include +#include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +template +class json_ref +{ + public: + using value_type = BasicJsonType; + + json_ref(value_type&& value) + : owned_value(std::move(value)) + {} + + json_ref(const value_type& value) + : value_ref(&value) + {} + + json_ref(std::initializer_list init) + : owned_value(init) + {} + + template < + class... Args, + enable_if_t::value, int> = 0 > + json_ref(Args && ... args) + : owned_value(std::forward(args)...) + {} + + // class should be movable only + json_ref(json_ref&&) noexcept = default; + json_ref(const json_ref&) = delete; + json_ref& operator=(const json_ref&) = delete; + json_ref& operator=(json_ref&&) = delete; + ~json_ref() = default; + + value_type moved_or_copied() const + { + if (value_ref == nullptr) + { + return std::move(owned_value); + } + return *value_ref; + } + + value_type const& operator*() const + { + return value_ref ? *value_ref : owned_value; + } + + value_type const* operator->() const + { + return &** this; + } + + private: + mutable value_type owned_value = nullptr; + value_type const* value_ref = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + + +#include // reverse +#include // array +#include // isnan, isinf +#include // uint8_t, uint16_t, uint32_t, uint64_t +#include // memcpy +#include // numeric_limits +#include // string +#include // move + +// #include + +// #include + +// #include + + +#include // copy +#include // size_t +#include // back_inserter +#include // shared_ptr, make_shared +#include // basic_string +#include // vector + +#ifndef JSON_NO_IO + #include // streamsize + #include // basic_ostream +#endif // JSON_NO_IO + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/// abstract output adapter interface +template struct output_adapter_protocol +{ + virtual void write_character(CharType c) = 0; + virtual void write_characters(const CharType* s, std::size_t length) = 0; + virtual ~output_adapter_protocol() = default; + + output_adapter_protocol() = default; + output_adapter_protocol(const output_adapter_protocol&) = default; + output_adapter_protocol(output_adapter_protocol&&) noexcept = default; + output_adapter_protocol& operator=(const output_adapter_protocol&) = default; + output_adapter_protocol& operator=(output_adapter_protocol&&) noexcept = default; +}; + +/// a type to simplify interfaces +template +using output_adapter_t = std::shared_ptr>; + +/// output adapter for byte vectors +template> +class output_vector_adapter : public output_adapter_protocol +{ + public: + explicit output_vector_adapter(std::vector& vec) noexcept + : v(vec) + {} + + void write_character(CharType c) override + { + v.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + std::copy(s, s + length, std::back_inserter(v)); + } + + private: + std::vector& v; +}; + +#ifndef JSON_NO_IO +/// output adapter for output streams +template +class output_stream_adapter : public output_adapter_protocol +{ + public: + explicit output_stream_adapter(std::basic_ostream& s) noexcept + : stream(s) + {} + + void write_character(CharType c) override + { + stream.put(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + stream.write(s, static_cast(length)); + } + + private: + std::basic_ostream& stream; +}; +#endif // JSON_NO_IO + +/// output adapter for basic_string +template> +class output_string_adapter : public output_adapter_protocol +{ + public: + explicit output_string_adapter(StringType& s) noexcept + : str(s) + {} + + void write_character(CharType c) override + { + str.push_back(c); + } + + JSON_HEDLEY_NON_NULL(2) + void write_characters(const CharType* s, std::size_t length) override + { + str.append(s, length); + } + + private: + StringType& str; +}; + +template> +class output_adapter +{ + public: + template> + output_adapter(std::vector& vec) + : oa(std::make_shared>(vec)) {} + +#ifndef JSON_NO_IO + output_adapter(std::basic_ostream& s) + : oa(std::make_shared>(s)) {} +#endif // JSON_NO_IO + + output_adapter(StringType& s) + : oa(std::make_shared>(s)) {} + + operator output_adapter_t() + { + return oa; + } + + private: + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// binary writer // +/////////////////// + +/*! +@brief serialization to CBOR and MessagePack values +*/ +template +class binary_writer +{ + using string_t = typename BasicJsonType::string_t; + using binary_t = typename BasicJsonType::binary_t; + using number_float_t = typename BasicJsonType::number_float_t; + + public: + /*! + @brief create a binary writer + + @param[in] adapter output adapter to write to + */ + explicit binary_writer(output_adapter_t adapter) : oa(std::move(adapter)) + { + JSON_ASSERT(oa); + } + + /*! + @param[in] j JSON value to serialize + @pre j.type() == value_t::object + */ + void write_bson(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + { + write_bson_object(*j.m_value.object); + break; + } + + case value_t::null: + case value_t::array: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()), j)); + } + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_cbor(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: + { + oa->write_character(to_char_type(0xF6)); + break; + } + + case value_t::boolean: + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xF5) + : to_char_type(0xF4)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // CBOR does not differentiate between positive signed + // integers and unsigned integers. Therefore, we used the + // code from the value_t::number_unsigned case here. + if (j.m_value.number_integer <= 0x17) + { + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_integer)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + // The conversions below encode the sign in the first + // byte, and the value is converted to a positive number. + const auto positive_number = -1 - j.m_value.number_integer; + if (j.m_value.number_integer >= -24) + { + write_number(static_cast(0x20 + positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x38)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x39)); + write_number(static_cast(positive_number)); + } + else if (positive_number <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x3A)); + write_number(static_cast(positive_number)); + } + else + { + oa->write_character(to_char_type(0x3B)); + write_number(static_cast(positive_number)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= 0x17) + { + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x18)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x19)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x1A)); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + oa->write_character(to_char_type(0x1B)); + write_number(static_cast(j.m_value.number_unsigned)); + } + break; + } + + case value_t::number_float: + { + if (std::isnan(j.m_value.number_float)) + { + // NaN is 0xf97e00 in CBOR + oa->write_character(to_char_type(0xF9)); + oa->write_character(to_char_type(0x7E)); + oa->write_character(to_char_type(0x00)); + } + else if (std::isinf(j.m_value.number_float)) + { + // Infinity is 0xf97c00, -Infinity is 0xf9fc00 + oa->write_character(to_char_type(0xf9)); + oa->write_character(j.m_value.number_float > 0 ? to_char_type(0x7C) : to_char_type(0xFC)); + oa->write_character(to_char_type(0x00)); + } + else + { + write_compact_float(j.m_value.number_float, detail::input_format_t::cbor); + } + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 0x17) + { + write_number(static_cast(0x60 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x78)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x79)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x7B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 0x17) + { + write_number(static_cast(0x80 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x98)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x99)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x9B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_cbor(el); + } + break; + } + + case value_t::binary: + { + if (j.m_value.binary->has_subtype()) + { + if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xd8)); + write_number(static_cast(j.m_value.binary->subtype())); + } + else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xd9)); + write_number(static_cast(j.m_value.binary->subtype())); + } + else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xda)); + write_number(static_cast(j.m_value.binary->subtype())); + } + else if (j.m_value.binary->subtype() <= (std::numeric_limits::max)()) + { + write_number(static_cast(0xdb)); + write_number(static_cast(j.m_value.binary->subtype())); + } + } + + // step 1: write control byte and the binary array size + const auto N = j.m_value.binary->size(); + if (N <= 0x17) + { + write_number(static_cast(0x40 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x58)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x59)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5A)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0x5B)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 0x17) + { + write_number(static_cast(0xA0 + N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB8)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xB9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBA)); + write_number(static_cast(N)); + } + // LCOV_EXCL_START + else if (N <= (std::numeric_limits::max)()) + { + oa->write_character(to_char_type(0xBB)); + write_number(static_cast(N)); + } + // LCOV_EXCL_STOP + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_cbor(el.first); + write_cbor(el.second); + } + break; + } + + case value_t::discarded: + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + */ + void write_msgpack(const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::null: // nil + { + oa->write_character(to_char_type(0xC0)); + break; + } + + case value_t::boolean: // true and false + { + oa->write_character(j.m_value.boolean + ? to_char_type(0xC3) + : to_char_type(0xC2)); + break; + } + + case value_t::number_integer: + { + if (j.m_value.number_integer >= 0) + { + // MessagePack does not differentiate between positive + // signed integers and unsigned integers. Therefore, we used + // the code from the value_t::number_unsigned case here. + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + } + else + { + if (j.m_value.number_integer >= -32) + { + // negative fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 8 + oa->write_character(to_char_type(0xD0)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 16 + oa->write_character(to_char_type(0xD1)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 32 + oa->write_character(to_char_type(0xD2)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_integer >= (std::numeric_limits::min)() && + j.m_value.number_integer <= (std::numeric_limits::max)()) + { + // int 64 + oa->write_character(to_char_type(0xD3)); + write_number(static_cast(j.m_value.number_integer)); + } + } + break; + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned < 128) + { + // positive fixnum + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 8 + oa->write_character(to_char_type(0xCC)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 16 + oa->write_character(to_char_type(0xCD)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 32 + oa->write_character(to_char_type(0xCE)); + write_number(static_cast(j.m_value.number_integer)); + } + else if (j.m_value.number_unsigned <= (std::numeric_limits::max)()) + { + // uint 64 + oa->write_character(to_char_type(0xCF)); + write_number(static_cast(j.m_value.number_integer)); + } + break; + } + + case value_t::number_float: + { + write_compact_float(j.m_value.number_float, detail::input_format_t::msgpack); + break; + } + + case value_t::string: + { + // step 1: write control byte and the string length + const auto N = j.m_value.string->size(); + if (N <= 31) + { + // fixstr + write_number(static_cast(0xA0 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 8 + oa->write_character(to_char_type(0xD9)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 16 + oa->write_character(to_char_type(0xDA)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // str 32 + oa->write_character(to_char_type(0xDB)); + write_number(static_cast(N)); + } + + // step 2: write the string + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + // step 1: write control byte and the array size + const auto N = j.m_value.array->size(); + if (N <= 15) + { + // fixarray + write_number(static_cast(0x90 | N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 16 + oa->write_character(to_char_type(0xDC)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // array 32 + oa->write_character(to_char_type(0xDD)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.array) + { + write_msgpack(el); + } + break; + } + + case value_t::binary: + { + // step 0: determine if the binary type has a set subtype to + // determine whether or not to use the ext or fixext types + const bool use_ext = j.m_value.binary->has_subtype(); + + // step 1: write control byte and the byte string length + const auto N = j.m_value.binary->size(); + if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type{}; + bool fixed = true; + if (use_ext) + { + switch (N) + { + case 1: + output_type = 0xD4; // fixext 1 + break; + case 2: + output_type = 0xD5; // fixext 2 + break; + case 4: + output_type = 0xD6; // fixext 4 + break; + case 8: + output_type = 0xD7; // fixext 8 + break; + case 16: + output_type = 0xD8; // fixext 16 + break; + default: + output_type = 0xC7; // ext 8 + fixed = false; + break; + } + + } + else + { + output_type = 0xC4; // bin 8 + fixed = false; + } + + oa->write_character(to_char_type(output_type)); + if (!fixed) + { + write_number(static_cast(N)); + } + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC8 // ext 16 + : 0xC5; // bin 16 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + std::uint8_t output_type = use_ext + ? 0xC9 // ext 32 + : 0xC6; // bin 32 + + oa->write_character(to_char_type(output_type)); + write_number(static_cast(N)); + } + + // step 1.5: if this is an ext type, write the subtype + if (use_ext) + { + write_number(static_cast(j.m_value.binary->subtype())); + } + + // step 2: write the byte string + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + N); + + break; + } + + case value_t::object: + { + // step 1: write control byte and the object size + const auto N = j.m_value.object->size(); + if (N <= 15) + { + // fixmap + write_number(static_cast(0x80 | (N & 0xF))); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 16 + oa->write_character(to_char_type(0xDE)); + write_number(static_cast(N)); + } + else if (N <= (std::numeric_limits::max)()) + { + // map 32 + oa->write_character(to_char_type(0xDF)); + write_number(static_cast(N)); + } + + // step 2: write each element + for (const auto& el : *j.m_value.object) + { + write_msgpack(el.first); + write_msgpack(el.second); + } + break; + } + + case value_t::discarded: + default: + break; + } + } + + /*! + @param[in] j JSON value to serialize + @param[in] use_count whether to use '#' prefixes (optimized format) + @param[in] use_type whether to use '$' prefixes (optimized format) + @param[in] add_prefix whether prefixes need to be used for this value + */ + void write_ubjson(const BasicJsonType& j, const bool use_count, + const bool use_type, const bool add_prefix = true) + { + switch (j.type()) + { + case value_t::null: + { + if (add_prefix) + { + oa->write_character(to_char_type('Z')); + } + break; + } + + case value_t::boolean: + { + if (add_prefix) + { + oa->write_character(j.m_value.boolean + ? to_char_type('T') + : to_char_type('F')); + } + break; + } + + case value_t::number_integer: + { + write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); + break; + } + + case value_t::number_unsigned: + { + write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); + break; + } + + case value_t::number_float: + { + write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); + break; + } + + case value_t::string: + { + if (add_prefix) + { + oa->write_character(to_char_type('S')); + } + write_number_with_ubjson_prefix(j.m_value.string->size(), true); + oa->write_characters( + reinterpret_cast(j.m_value.string->c_str()), + j.m_value.string->size()); + break; + } + + case value_t::array: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.array->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin() + 1, j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.array->size(), true); + } + + for (const auto& el : *j.m_value.array) + { + write_ubjson(el, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::binary: + { + if (add_prefix) + { + oa->write_character(to_char_type('[')); + } + + if (use_type && !j.m_value.binary->empty()) + { + JSON_ASSERT(use_count); + oa->write_character(to_char_type('$')); + oa->write_character('U'); + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.binary->size(), true); + } + + if (use_type) + { + oa->write_characters( + reinterpret_cast(j.m_value.binary->data()), + j.m_value.binary->size()); + } + else + { + for (size_t i = 0; i < j.m_value.binary->size(); ++i) + { + oa->write_character(to_char_type('U')); + oa->write_character(j.m_value.binary->data()[i]); + } + } + + if (!use_count) + { + oa->write_character(to_char_type(']')); + } + + break; + } + + case value_t::object: + { + if (add_prefix) + { + oa->write_character(to_char_type('{')); + } + + bool prefix_required = true; + if (use_type && !j.m_value.object->empty()) + { + JSON_ASSERT(use_count); + const CharType first_prefix = ubjson_prefix(j.front()); + const bool same_prefix = std::all_of(j.begin(), j.end(), + [this, first_prefix](const BasicJsonType & v) + { + return ubjson_prefix(v) == first_prefix; + }); + + if (same_prefix) + { + prefix_required = false; + oa->write_character(to_char_type('$')); + oa->write_character(first_prefix); + } + } + + if (use_count) + { + oa->write_character(to_char_type('#')); + write_number_with_ubjson_prefix(j.m_value.object->size(), true); + } + + for (const auto& el : *j.m_value.object) + { + write_number_with_ubjson_prefix(el.first.size(), true); + oa->write_characters( + reinterpret_cast(el.first.c_str()), + el.first.size()); + write_ubjson(el.second, use_count, use_type, prefix_required); + } + + if (!use_count) + { + oa->write_character(to_char_type('}')); + } + + break; + } + + case value_t::discarded: + default: + break; + } + } + + private: + ////////// + // BSON // + ////////// + + /*! + @return The size of a BSON document entry header, including the id marker + and the entry name size (and its null-terminator). + */ + static std::size_t calc_bson_entry_header_size(const string_t& name, const BasicJsonType& j) + { + const auto it = name.find(static_cast(0)); + if (JSON_HEDLEY_UNLIKELY(it != BasicJsonType::string_t::npos)) + { + JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")", j)); + static_cast(j); + } + + return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; + } + + /*! + @brief Writes the given @a element_type and @a name to the output adapter + */ + void write_bson_entry_header(const string_t& name, + const std::uint8_t element_type) + { + oa->write_character(to_char_type(element_type)); // boolean + oa->write_characters( + reinterpret_cast(name.c_str()), + name.size() + 1u); + } + + /*! + @brief Writes a BSON element with key @a name and boolean value @a value + */ + void write_bson_boolean(const string_t& name, + const bool value) + { + write_bson_entry_header(name, 0x08); + oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and double value @a value + */ + void write_bson_double(const string_t& name, + const double value) + { + write_bson_entry_header(name, 0x01); + write_number(value); + } + + /*! + @return The size of the BSON-encoded string in @a value + */ + static std::size_t calc_bson_string_size(const string_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and string value @a value + */ + void write_bson_string(const string_t& name, + const string_t& value) + { + write_bson_entry_header(name, 0x02); + + write_number(static_cast(value.size() + 1ul)); + oa->write_characters( + reinterpret_cast(value.c_str()), + value.size() + 1); + } + + /*! + @brief Writes a BSON element with key @a name and null value + */ + void write_bson_null(const string_t& name) + { + write_bson_entry_header(name, 0x0A); + } + + /*! + @return The size of the BSON-encoded integer @a value + */ + static std::size_t calc_bson_integer_size(const std::int64_t value) + { + return (std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)() + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and integer @a value + */ + void write_bson_integer(const string_t& name, + const std::int64_t value) + { + if ((std::numeric_limits::min)() <= value && value <= (std::numeric_limits::max)()) + { + write_bson_entry_header(name, 0x10); // int32 + write_number(static_cast(value)); + } + else + { + write_bson_entry_header(name, 0x12); // int64 + write_number(static_cast(value)); + } + } + + /*! + @return The size of the BSON-encoded unsigned integer in @a j + */ + static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept + { + return (value <= static_cast((std::numeric_limits::max)())) + ? sizeof(std::int32_t) + : sizeof(std::int64_t); + } + + /*! + @brief Writes a BSON element with key @a name and unsigned @a value + */ + void write_bson_unsigned(const string_t& name, + const BasicJsonType& j) + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x10 /* int32 */); + write_number(static_cast(j.m_value.number_unsigned)); + } + else if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + write_bson_entry_header(name, 0x12 /* int64 */); + write_number(static_cast(j.m_value.number_unsigned)); + } + else + { + JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(j.m_value.number_unsigned) + " cannot be represented by BSON as it does not fit int64", j)); + } + } + + /*! + @brief Writes a BSON element with key @a name and object @a value + */ + void write_bson_object_entry(const string_t& name, + const typename BasicJsonType::object_t& value) + { + write_bson_entry_header(name, 0x03); // object + write_bson_object(value); + } + + /*! + @return The size of the BSON-encoded array @a value + */ + static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) + { + std::size_t array_index = 0ul; + + const std::size_t embedded_document_size = std::accumulate(std::begin(value), std::end(value), static_cast(0), [&array_index](std::size_t result, const typename BasicJsonType::array_t::value_type & el) + { + return result + calc_bson_element_size(std::to_string(array_index++), el); + }); + + return sizeof(std::int32_t) + embedded_document_size + 1ul; + } + + /*! + @return The size of the BSON-encoded binary array @a value + */ + static std::size_t calc_bson_binary_size(const typename BasicJsonType::binary_t& value) + { + return sizeof(std::int32_t) + value.size() + 1ul; + } + + /*! + @brief Writes a BSON element with key @a name and array @a value + */ + void write_bson_array(const string_t& name, + const typename BasicJsonType::array_t& value) + { + write_bson_entry_header(name, 0x04); // array + write_number(static_cast(calc_bson_array_size(value))); + + std::size_t array_index = 0ul; + + for (const auto& el : value) + { + write_bson_element(std::to_string(array_index++), el); + } + + oa->write_character(to_char_type(0x00)); + } + + /*! + @brief Writes a BSON element with key @a name and binary value @a value + */ + void write_bson_binary(const string_t& name, + const binary_t& value) + { + write_bson_entry_header(name, 0x05); + + write_number(static_cast(value.size())); + write_number(value.has_subtype() ? static_cast(value.subtype()) : static_cast(0x00)); + + oa->write_characters(reinterpret_cast(value.data()), value.size()); + } + + /*! + @brief Calculates the size necessary to serialize the JSON value @a j with its @a name + @return The calculated size for the BSON document entry for @a j with the given @a name. + */ + static std::size_t calc_bson_element_size(const string_t& name, + const BasicJsonType& j) + { + const auto header_size = calc_bson_entry_header_size(name, j); + switch (j.type()) + { + case value_t::object: + return header_size + calc_bson_object_size(*j.m_value.object); + + case value_t::array: + return header_size + calc_bson_array_size(*j.m_value.array); + + case value_t::binary: + return header_size + calc_bson_binary_size(*j.m_value.binary); + + case value_t::boolean: + return header_size + 1ul; + + case value_t::number_float: + return header_size + 8ul; + + case value_t::number_integer: + return header_size + calc_bson_integer_size(j.m_value.number_integer); + + case value_t::number_unsigned: + return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); + + case value_t::string: + return header_size + calc_bson_string_size(*j.m_value.string); + + case value_t::null: + return header_size + 0ul; + + // LCOV_EXCL_START + case value_t::discarded: + default: + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) + return 0ul; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Serializes the JSON value @a j to BSON and associates it with the + key @a name. + @param name The name to associate with the JSON entity @a j within the + current BSON document + */ + void write_bson_element(const string_t& name, + const BasicJsonType& j) + { + switch (j.type()) + { + case value_t::object: + return write_bson_object_entry(name, *j.m_value.object); + + case value_t::array: + return write_bson_array(name, *j.m_value.array); + + case value_t::binary: + return write_bson_binary(name, *j.m_value.binary); + + case value_t::boolean: + return write_bson_boolean(name, j.m_value.boolean); + + case value_t::number_float: + return write_bson_double(name, j.m_value.number_float); + + case value_t::number_integer: + return write_bson_integer(name, j.m_value.number_integer); + + case value_t::number_unsigned: + return write_bson_unsigned(name, j); + + case value_t::string: + return write_bson_string(name, *j.m_value.string); + + case value_t::null: + return write_bson_null(name); + + // LCOV_EXCL_START + case value_t::discarded: + default: + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) + return; + // LCOV_EXCL_STOP + } + } + + /*! + @brief Calculates the size of the BSON serialization of the given + JSON-object @a j. + @param[in] value JSON value to serialize + @pre value.type() == value_t::object + */ + static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) + { + std::size_t document_size = std::accumulate(value.begin(), value.end(), static_cast(0), + [](size_t result, const typename BasicJsonType::object_t::value_type & el) + { + return result += calc_bson_element_size(el.first, el.second); + }); + + return sizeof(std::int32_t) + document_size + 1ul; + } + + /*! + @param[in] value JSON value to serialize + @pre value.type() == value_t::object + */ + void write_bson_object(const typename BasicJsonType::object_t& value) + { + write_number(static_cast(calc_bson_object_size(value))); + + for (const auto& el : value) + { + write_bson_element(el.first, el.second); + } + + oa->write_character(to_char_type(0x00)); + } + + ////////// + // CBOR // + ////////// + + static constexpr CharType get_cbor_float_prefix(float /*unused*/) + { + return to_char_type(0xFA); // Single-Precision Float + } + + static constexpr CharType get_cbor_float_prefix(double /*unused*/) + { + return to_char_type(0xFB); // Double-Precision Float + } + + ///////////// + // MsgPack // + ///////////// + + static constexpr CharType get_msgpack_float_prefix(float /*unused*/) + { + return to_char_type(0xCA); // float 32 + } + + static constexpr CharType get_msgpack_float_prefix(double /*unused*/) + { + return to_char_type(0xCB); // float 64 + } + + //////////// + // UBJSON // + //////////// + + // UBJSON: write number (floating point) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (add_prefix) + { + oa->write_character(get_ubjson_float_prefix(n)); + } + write_number(n); + } + + // UBJSON: write number (unsigned integer) + template::value, int>::type = 0> + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if (n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + } + + // UBJSON: write number (signed integer) + template < typename NumberType, typename std::enable_if < + std::is_signed::value&& + !std::is_floating_point::value, int >::type = 0 > + void write_number_with_ubjson_prefix(const NumberType n, + const bool add_prefix) + { + if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('i')); // int8 + } + write_number(static_cast(n)); + } + else if (static_cast((std::numeric_limits::min)()) <= n && n <= static_cast((std::numeric_limits::max)())) + { + if (add_prefix) + { + oa->write_character(to_char_type('U')); // uint8 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('I')); // int16 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('l')); // int32 + } + write_number(static_cast(n)); + } + else if ((std::numeric_limits::min)() <= n && n <= (std::numeric_limits::max)()) + { + if (add_prefix) + { + oa->write_character(to_char_type('L')); // int64 + } + write_number(static_cast(n)); + } + // LCOV_EXCL_START + else + { + if (add_prefix) + { + oa->write_character(to_char_type('H')); // high-precision number + } + + const auto number = BasicJsonType(n).dump(); + write_number_with_ubjson_prefix(number.size(), true); + for (std::size_t i = 0; i < number.size(); ++i) + { + oa->write_character(to_char_type(static_cast(number[i]))); + } + } + // LCOV_EXCL_STOP + } + + /*! + @brief determine the type prefix of container values + */ + CharType ubjson_prefix(const BasicJsonType& j) const noexcept + { + switch (j.type()) + { + case value_t::null: + return 'Z'; + + case value_t::boolean: + return j.m_value.boolean ? 'T' : 'F'; + + case value_t::number_integer: + { + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'i'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'U'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'I'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'l'; + } + if ((std::numeric_limits::min)() <= j.m_value.number_integer && j.m_value.number_integer <= (std::numeric_limits::max)()) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_unsigned: + { + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'i'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'U'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'I'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'l'; + } + if (j.m_value.number_unsigned <= static_cast((std::numeric_limits::max)())) + { + return 'L'; + } + // anything else is treated as high-precision number + return 'H'; // LCOV_EXCL_LINE + } + + case value_t::number_float: + return get_ubjson_float_prefix(j.m_value.number_float); + + case value_t::string: + return 'S'; + + case value_t::array: // fallthrough + case value_t::binary: + return '['; + + case value_t::object: + return '{'; + + case value_t::discarded: + default: // discarded values + return 'N'; + } + } + + static constexpr CharType get_ubjson_float_prefix(float /*unused*/) + { + return 'd'; // float 32 + } + + static constexpr CharType get_ubjson_float_prefix(double /*unused*/) + { + return 'D'; // float 64 + } + + /////////////////////// + // Utility functions // + /////////////////////// + + /* + @brief write a number to output input + @param[in] n number of type @a NumberType + @tparam NumberType the type of the number + @tparam OutputIsLittleEndian Set to true if output data is + required to be little endian + + @note This function needs to respect the system's endianness, because bytes + in CBOR, MessagePack, and UBJSON are stored in network order (big + endian) and therefore need reordering on little endian systems. + */ + template + void write_number(const NumberType n) + { + // step 1: write number to array of length NumberType + std::array vec{}; + std::memcpy(vec.data(), &n, sizeof(NumberType)); + + // step 2: write array to output (with possible reordering) + if (is_little_endian != OutputIsLittleEndian) + { + // reverse byte order prior to conversion if necessary + std::reverse(vec.begin(), vec.end()); + } + + oa->write_characters(vec.data(), sizeof(NumberType)); + } + + void write_compact_float(const number_float_t n, detail::input_format_t format) + { +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (static_cast(n) >= static_cast(std::numeric_limits::lowest()) && + static_cast(n) <= static_cast((std::numeric_limits::max)()) && + static_cast(static_cast(n)) == static_cast(n)) + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(static_cast(n)) + : get_msgpack_float_prefix(static_cast(n))); + write_number(static_cast(n)); + } + else + { + oa->write_character(format == detail::input_format_t::cbor + ? get_cbor_float_prefix(n) + : get_msgpack_float_prefix(n)); + write_number(n); + } +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + } + + public: + // The following to_char_type functions are implement the conversion + // between uint8_t and CharType. In case CharType is not unsigned, + // such a conversion is required to allow values greater than 128. + // See for a discussion. + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_signed::value > * = nullptr > + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return *reinterpret_cast(&x); + } + + template < typename C = CharType, + enable_if_t < std::is_signed::value && std::is_unsigned::value > * = nullptr > + static CharType to_char_type(std::uint8_t x) noexcept + { + static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); + static_assert(std::is_trivial::value, "CharType must be trivial"); + CharType result; + std::memcpy(&result, &x, sizeof(x)); + return result; + } + + template::value>* = nullptr> + static constexpr CharType to_char_type(std::uint8_t x) noexcept + { + return x; + } + + template < typename InputCharType, typename C = CharType, + enable_if_t < + std::is_signed::value && + std::is_signed::value && + std::is_same::type>::value + > * = nullptr > + static constexpr CharType to_char_type(InputCharType x) noexcept + { + return x; + } + + private: + /// whether we can assume little endianness + const bool is_little_endian = little_endianness(); + + /// the output + output_adapter_t oa = nullptr; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + + +#include // reverse, remove, fill, find, none_of +#include // array +#include // localeconv, lconv +#include // labs, isfinite, isnan, signbit +#include // size_t, ptrdiff_t +#include // uint8_t +#include // snprintf +#include // numeric_limits +#include // string, char_traits +#include // setfill, setw +#include // stringstream +#include // is_same +#include // move + +// #include + + +#include // array +#include // signbit, isfinite +#include // intN_t, uintN_t +#include // memcpy, memmove +#include // numeric_limits +#include // conditional + +// #include + + +namespace nlohmann +{ +namespace detail +{ + +/*! +@brief implements the Grisu2 algorithm for binary to decimal floating-point +conversion. + +This implementation is a slightly modified version of the reference +implementation which may be obtained from +http://florian.loitsch.com/publications (bench.tar.gz). + +The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. + +For a detailed description of the algorithm see: + +[1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with + Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming + Language Design and Implementation, PLDI 2010 +[2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", + Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language + Design and Implementation, PLDI 1996 +*/ +namespace dtoa_impl +{ + +template +Target reinterpret_bits(const Source source) +{ + static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); + + Target target; + std::memcpy(&target, &source, sizeof(Source)); + return target; +} + +struct diyfp // f * 2^e +{ + static constexpr int kPrecision = 64; // = q + + std::uint64_t f = 0; + int e = 0; + + constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} + + /*! + @brief returns x - y + @pre x.e == y.e and x.f >= y.f + */ + static diyfp sub(const diyfp& x, const diyfp& y) noexcept + { + JSON_ASSERT(x.e == y.e); + JSON_ASSERT(x.f >= y.f); + + return {x.f - y.f, x.e}; + } + + /*! + @brief returns x * y + @note The result is rounded. (Only the upper q bits are returned.) + */ + static diyfp mul(const diyfp& x, const diyfp& y) noexcept + { + static_assert(kPrecision == 64, "internal error"); + + // Computes: + // f = round((x.f * y.f) / 2^q) + // e = x.e + y.e + q + + // Emulate the 64-bit * 64-bit multiplication: + // + // p = u * v + // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) + // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) + // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) + // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) + // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) + // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) + // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) + // + // (Since Q might be larger than 2^32 - 1) + // + // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) + // + // (Q_hi + H does not overflow a 64-bit int) + // + // = p_lo + 2^64 p_hi + + const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; + const std::uint64_t u_hi = x.f >> 32u; + const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; + const std::uint64_t v_hi = y.f >> 32u; + + const std::uint64_t p0 = u_lo * v_lo; + const std::uint64_t p1 = u_lo * v_hi; + const std::uint64_t p2 = u_hi * v_lo; + const std::uint64_t p3 = u_hi * v_hi; + + const std::uint64_t p0_hi = p0 >> 32u; + const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; + const std::uint64_t p1_hi = p1 >> 32u; + const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; + const std::uint64_t p2_hi = p2 >> 32u; + + std::uint64_t Q = p0_hi + p1_lo + p2_lo; + + // The full product might now be computed as + // + // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) + // p_lo = p0_lo + (Q << 32) + // + // But in this particular case here, the full p_lo is not required. + // Effectively we only need to add the highest bit in p_lo to p_hi (and + // Q_hi + 1 does not overflow). + + Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up + + const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); + + return {h, x.e + y.e + 64}; + } + + /*! + @brief normalize x such that the significand is >= 2^(q-1) + @pre x.f != 0 + */ + static diyfp normalize(diyfp x) noexcept + { + JSON_ASSERT(x.f != 0); + + while ((x.f >> 63u) == 0) + { + x.f <<= 1u; + x.e--; + } + + return x; + } + + /*! + @brief normalize x such that the result has the exponent E + @pre e >= x.e and the upper e - x.e bits of x.f must be zero. + */ + static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept + { + const int delta = x.e - target_exponent; + + JSON_ASSERT(delta >= 0); + JSON_ASSERT(((x.f << delta) >> delta) == x.f); + + return {x.f << delta, target_exponent}; + } +}; + +struct boundaries +{ + diyfp w; + diyfp minus; + diyfp plus; +}; + +/*! +Compute the (normalized) diyfp representing the input number 'value' and its +boundaries. + +@pre value must be finite and positive +*/ +template +boundaries compute_boundaries(FloatType value) +{ + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // Convert the IEEE representation into a diyfp. + // + // If v is denormal: + // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) + // If v is normalized: + // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) + + static_assert(std::numeric_limits::is_iec559, + "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); + + constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) + constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); + constexpr int kMinExp = 1 - kBias; + constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) + + using bits_type = typename std::conditional::type; + + const auto bits = static_cast(reinterpret_bits(value)); + const std::uint64_t E = bits >> (kPrecision - 1); + const std::uint64_t F = bits & (kHiddenBit - 1); + + const bool is_denormal = E == 0; + const diyfp v = is_denormal + ? diyfp(F, kMinExp) + : diyfp(F + kHiddenBit, static_cast(E) - kBias); + + // Compute the boundaries m- and m+ of the floating-point value + // v = f * 2^e. + // + // Determine v- and v+, the floating-point predecessor and successor if v, + // respectively. + // + // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) + // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) + // + // v+ = v + 2^e + // + // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ + // between m- and m+ round to v, regardless of how the input rounding + // algorithm breaks ties. + // + // ---+-------------+-------------+-------------+-------------+--- (A) + // v- m- v m+ v+ + // + // -----------------+------+------+-------------+-------------+--- (B) + // v- m- v m+ v+ + + const bool lower_boundary_is_closer = F == 0 && E > 1; + const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); + const diyfp m_minus = lower_boundary_is_closer + ? diyfp(4 * v.f - 1, v.e - 2) // (B) + : diyfp(2 * v.f - 1, v.e - 1); // (A) + + // Determine the normalized w+ = m+. + const diyfp w_plus = diyfp::normalize(m_plus); + + // Determine w- = m- such that e_(w-) = e_(w+). + const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); + + return {diyfp::normalize(v), w_minus, w_plus}; +} + +// Given normalized diyfp w, Grisu needs to find a (normalized) cached +// power-of-ten c, such that the exponent of the product c * w = f * 2^e lies +// within a certain range [alpha, gamma] (Definition 3.2 from [1]) +// +// alpha <= e = e_c + e_w + q <= gamma +// +// or +// +// f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q +// <= f_c * f_w * 2^gamma +// +// Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies +// +// 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma +// +// or +// +// 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) +// +// The choice of (alpha,gamma) determines the size of the table and the form of +// the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well +// in practice: +// +// The idea is to cut the number c * w = f * 2^e into two parts, which can be +// processed independently: An integral part p1, and a fractional part p2: +// +// f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e +// = (f div 2^-e) + (f mod 2^-e) * 2^e +// = p1 + p2 * 2^e +// +// The conversion of p1 into decimal form requires a series of divisions and +// modulos by (a power of) 10. These operations are faster for 32-bit than for +// 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be +// achieved by choosing +// +// -e >= 32 or e <= -32 := gamma +// +// In order to convert the fractional part +// +// p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... +// +// into decimal form, the fraction is repeatedly multiplied by 10 and the digits +// d[-i] are extracted in order: +// +// (10 * p2) div 2^-e = d[-1] +// (10 * p2) mod 2^-e = d[-2] / 10^1 + ... +// +// The multiplication by 10 must not overflow. It is sufficient to choose +// +// 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. +// +// Since p2 = f mod 2^-e < 2^-e, +// +// -e <= 60 or e >= -60 := alpha + +constexpr int kAlpha = -60; +constexpr int kGamma = -32; + +struct cached_power // c = f * 2^e ~= 10^k +{ + std::uint64_t f; + int e; + int k; +}; + +/*! +For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached +power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c +satisfies (Definition 3.2 from [1]) + + alpha <= e_c + e + q <= gamma. +*/ +inline cached_power get_cached_power_for_binary_exponent(int e) +{ + // Now + // + // alpha <= e_c + e + q <= gamma (1) + // ==> f_c * 2^alpha <= c * 2^e * 2^q + // + // and since the c's are normalized, 2^(q-1) <= f_c, + // + // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) + // ==> 2^(alpha - e - 1) <= c + // + // If c were an exact power of ten, i.e. c = 10^k, one may determine k as + // + // k = ceil( log_10( 2^(alpha - e - 1) ) ) + // = ceil( (alpha - e - 1) * log_10(2) ) + // + // From the paper: + // "In theory the result of the procedure could be wrong since c is rounded, + // and the computation itself is approximated [...]. In practice, however, + // this simple function is sufficient." + // + // For IEEE double precision floating-point numbers converted into + // normalized diyfp's w = f * 2^e, with q = 64, + // + // e >= -1022 (min IEEE exponent) + // -52 (p - 1) + // -52 (p - 1, possibly normalize denormal IEEE numbers) + // -11 (normalize the diyfp) + // = -1137 + // + // and + // + // e <= +1023 (max IEEE exponent) + // -52 (p - 1) + // -11 (normalize the diyfp) + // = 960 + // + // This binary exponent range [-1137,960] results in a decimal exponent + // range [-307,324]. One does not need to store a cached power for each + // k in this range. For each such k it suffices to find a cached power + // such that the exponent of the product lies in [alpha,gamma]. + // This implies that the difference of the decimal exponents of adjacent + // table entries must be less than or equal to + // + // floor( (gamma - alpha) * log_10(2) ) = 8. + // + // (A smaller distance gamma-alpha would require a larger table.) + + // NB: + // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. + + constexpr int kCachedPowersMinDecExp = -300; + constexpr int kCachedPowersDecStep = 8; + + static constexpr std::array kCachedPowers = + { + { + { 0xAB70FE17C79AC6CA, -1060, -300 }, + { 0xFF77B1FCBEBCDC4F, -1034, -292 }, + { 0xBE5691EF416BD60C, -1007, -284 }, + { 0x8DD01FAD907FFC3C, -980, -276 }, + { 0xD3515C2831559A83, -954, -268 }, + { 0x9D71AC8FADA6C9B5, -927, -260 }, + { 0xEA9C227723EE8BCB, -901, -252 }, + { 0xAECC49914078536D, -874, -244 }, + { 0x823C12795DB6CE57, -847, -236 }, + { 0xC21094364DFB5637, -821, -228 }, + { 0x9096EA6F3848984F, -794, -220 }, + { 0xD77485CB25823AC7, -768, -212 }, + { 0xA086CFCD97BF97F4, -741, -204 }, + { 0xEF340A98172AACE5, -715, -196 }, + { 0xB23867FB2A35B28E, -688, -188 }, + { 0x84C8D4DFD2C63F3B, -661, -180 }, + { 0xC5DD44271AD3CDBA, -635, -172 }, + { 0x936B9FCEBB25C996, -608, -164 }, + { 0xDBAC6C247D62A584, -582, -156 }, + { 0xA3AB66580D5FDAF6, -555, -148 }, + { 0xF3E2F893DEC3F126, -529, -140 }, + { 0xB5B5ADA8AAFF80B8, -502, -132 }, + { 0x87625F056C7C4A8B, -475, -124 }, + { 0xC9BCFF6034C13053, -449, -116 }, + { 0x964E858C91BA2655, -422, -108 }, + { 0xDFF9772470297EBD, -396, -100 }, + { 0xA6DFBD9FB8E5B88F, -369, -92 }, + { 0xF8A95FCF88747D94, -343, -84 }, + { 0xB94470938FA89BCF, -316, -76 }, + { 0x8A08F0F8BF0F156B, -289, -68 }, + { 0xCDB02555653131B6, -263, -60 }, + { 0x993FE2C6D07B7FAC, -236, -52 }, + { 0xE45C10C42A2B3B06, -210, -44 }, + { 0xAA242499697392D3, -183, -36 }, + { 0xFD87B5F28300CA0E, -157, -28 }, + { 0xBCE5086492111AEB, -130, -20 }, + { 0x8CBCCC096F5088CC, -103, -12 }, + { 0xD1B71758E219652C, -77, -4 }, + { 0x9C40000000000000, -50, 4 }, + { 0xE8D4A51000000000, -24, 12 }, + { 0xAD78EBC5AC620000, 3, 20 }, + { 0x813F3978F8940984, 30, 28 }, + { 0xC097CE7BC90715B3, 56, 36 }, + { 0x8F7E32CE7BEA5C70, 83, 44 }, + { 0xD5D238A4ABE98068, 109, 52 }, + { 0x9F4F2726179A2245, 136, 60 }, + { 0xED63A231D4C4FB27, 162, 68 }, + { 0xB0DE65388CC8ADA8, 189, 76 }, + { 0x83C7088E1AAB65DB, 216, 84 }, + { 0xC45D1DF942711D9A, 242, 92 }, + { 0x924D692CA61BE758, 269, 100 }, + { 0xDA01EE641A708DEA, 295, 108 }, + { 0xA26DA3999AEF774A, 322, 116 }, + { 0xF209787BB47D6B85, 348, 124 }, + { 0xB454E4A179DD1877, 375, 132 }, + { 0x865B86925B9BC5C2, 402, 140 }, + { 0xC83553C5C8965D3D, 428, 148 }, + { 0x952AB45CFA97A0B3, 455, 156 }, + { 0xDE469FBD99A05FE3, 481, 164 }, + { 0xA59BC234DB398C25, 508, 172 }, + { 0xF6C69A72A3989F5C, 534, 180 }, + { 0xB7DCBF5354E9BECE, 561, 188 }, + { 0x88FCF317F22241E2, 588, 196 }, + { 0xCC20CE9BD35C78A5, 614, 204 }, + { 0x98165AF37B2153DF, 641, 212 }, + { 0xE2A0B5DC971F303A, 667, 220 }, + { 0xA8D9D1535CE3B396, 694, 228 }, + { 0xFB9B7CD9A4A7443C, 720, 236 }, + { 0xBB764C4CA7A44410, 747, 244 }, + { 0x8BAB8EEFB6409C1A, 774, 252 }, + { 0xD01FEF10A657842C, 800, 260 }, + { 0x9B10A4E5E9913129, 827, 268 }, + { 0xE7109BFBA19C0C9D, 853, 276 }, + { 0xAC2820D9623BF429, 880, 284 }, + { 0x80444B5E7AA7CF85, 907, 292 }, + { 0xBF21E44003ACDD2D, 933, 300 }, + { 0x8E679C2F5E44FF8F, 960, 308 }, + { 0xD433179D9C8CB841, 986, 316 }, + { 0x9E19DB92B4E31BA9, 1013, 324 }, + } + }; + + // This computation gives exactly the same results for k as + // k = ceil((kAlpha - e - 1) * 0.30102999566398114) + // for |e| <= 1500, but doesn't require floating-point operations. + // NB: log_10(2) ~= 78913 / 2^18 + JSON_ASSERT(e >= -1500); + JSON_ASSERT(e <= 1500); + const int f = kAlpha - e - 1; + const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); + + const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; + JSON_ASSERT(index >= 0); + JSON_ASSERT(static_cast(index) < kCachedPowers.size()); + + const cached_power cached = kCachedPowers[static_cast(index)]; + JSON_ASSERT(kAlpha <= cached.e + e + 64); + JSON_ASSERT(kGamma >= cached.e + e + 64); + + return cached; +} + +/*! +For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. +For n == 0, returns 1 and sets pow10 := 1. +*/ +inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) +{ + // LCOV_EXCL_START + if (n >= 1000000000) + { + pow10 = 1000000000; + return 10; + } + // LCOV_EXCL_STOP + if (n >= 100000000) + { + pow10 = 100000000; + return 9; + } + if (n >= 10000000) + { + pow10 = 10000000; + return 8; + } + if (n >= 1000000) + { + pow10 = 1000000; + return 7; + } + if (n >= 100000) + { + pow10 = 100000; + return 6; + } + if (n >= 10000) + { + pow10 = 10000; + return 5; + } + if (n >= 1000) + { + pow10 = 1000; + return 4; + } + if (n >= 100) + { + pow10 = 100; + return 3; + } + if (n >= 10) + { + pow10 = 10; + return 2; + } + + pow10 = 1; + return 1; +} + +inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, + std::uint64_t rest, std::uint64_t ten_k) +{ + JSON_ASSERT(len >= 1); + JSON_ASSERT(dist <= delta); + JSON_ASSERT(rest <= delta); + JSON_ASSERT(ten_k > 0); + + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // ten_k + // <------> + // <---- rest ----> + // --------------[------------------+----+--------------]-------------- + // w V + // = buf * 10^k + // + // ten_k represents a unit-in-the-last-place in the decimal representation + // stored in buf. + // Decrement buf by ten_k while this takes buf closer to w. + + // The tests are written in this order to avoid overflow in unsigned + // integer arithmetic. + + while (rest < dist + && delta - rest >= ten_k + && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) + { + JSON_ASSERT(buf[len - 1] != '0'); + buf[len - 1]--; + rest += ten_k; + } +} + +/*! +Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. +M- and M+ must be normalized and share the same exponent -60 <= e <= -32. +*/ +inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, + diyfp M_minus, diyfp w, diyfp M_plus) +{ + static_assert(kAlpha >= -60, "internal error"); + static_assert(kGamma <= -32, "internal error"); + + // Generates the digits (and the exponent) of a decimal floating-point + // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's + // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. + // + // <--------------------------- delta ----> + // <---- dist ---------> + // --------------[------------------+-------------------]-------------- + // M- w M+ + // + // Grisu2 generates the digits of M+ from left to right and stops as soon as + // V is in [M-,M+]. + + JSON_ASSERT(M_plus.e >= kAlpha); + JSON_ASSERT(M_plus.e <= kGamma); + + std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) + std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) + + // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): + // + // M+ = f * 2^e + // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e + // = ((p1 ) * 2^-e + (p2 )) * 2^e + // = p1 + p2 * 2^e + + const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); + + auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) + std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e + + // 1) + // + // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] + + JSON_ASSERT(p1 > 0); + + std::uint32_t pow10{}; + const int k = find_largest_pow10(p1, pow10); + + // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) + // + // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) + // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) + // + // M+ = p1 + p2 * 2^e + // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e + // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e + // = d[k-1] * 10^(k-1) + ( rest) * 2^e + // + // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) + // + // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] + // + // but stop as soon as + // + // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e + + int n = k; + while (n > 0) + { + // Invariants: + // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) + // pow10 = 10^(n-1) <= p1 < 10^n + // + const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) + const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) + // + // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e + // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) + // + p1 = r; + n--; + // + // M+ = buffer * 10^n + (p1 + p2 * 2^e) + // pow10 = 10^n + // + + // Now check if enough digits have been generated. + // Compute + // + // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e + // + // Note: + // Since rest and delta share the same exponent e, it suffices to + // compare the significands. + const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; + if (rest <= delta) + { + // V = buffer * 10^n, with M- <= V <= M+. + + decimal_exponent += n; + + // We may now just stop. But instead look if the buffer could be + // decremented to bring V closer to w. + // + // pow10 = 10^n is now 1 ulp in the decimal representation V. + // The rounding procedure works with diyfp's with an implicit + // exponent of e. + // + // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e + // + const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; + grisu2_round(buffer, length, dist, delta, rest, ten_n); + + return; + } + + pow10 /= 10; + // + // pow10 = 10^(n-1) <= p1 < 10^n + // Invariants restored. + } + + // 2) + // + // The digits of the integral part have been generated: + // + // M+ = d[k-1]...d[1]d[0] + p2 * 2^e + // = buffer + p2 * 2^e + // + // Now generate the digits of the fractional part p2 * 2^e. + // + // Note: + // No decimal point is generated: the exponent is adjusted instead. + // + // p2 actually represents the fraction + // + // p2 * 2^e + // = p2 / 2^-e + // = d[-1] / 10^1 + d[-2] / 10^2 + ... + // + // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) + // + // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m + // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) + // + // using + // + // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) + // = ( d) * 2^-e + ( r) + // + // or + // 10^m * p2 * 2^e = d + r * 2^e + // + // i.e. + // + // M+ = buffer + p2 * 2^e + // = buffer + 10^-m * (d + r * 2^e) + // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e + // + // and stop as soon as 10^-m * r * 2^e <= delta * 2^e + + JSON_ASSERT(p2 > delta); + + int m = 0; + for (;;) + { + // Invariant: + // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e + // = buffer * 10^-m + 10^-m * (p2 ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e + // + JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); + p2 *= 10; + const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e + const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e + // + // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e + // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) + // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + JSON_ASSERT(d <= 9); + buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d + // + // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e + // + p2 = r; + m++; + // + // M+ = buffer * 10^-m + 10^-m * p2 * 2^e + // Invariant restored. + + // Check if enough digits have been generated. + // + // 10^-m * p2 * 2^e <= delta * 2^e + // p2 * 2^e <= 10^m * delta * 2^e + // p2 <= 10^m * delta + delta *= 10; + dist *= 10; + if (p2 <= delta) + { + break; + } + } + + // V = buffer * 10^-m, with M- <= V <= M+. + + decimal_exponent -= m; + + // 1 ulp in the decimal representation is now 10^-m. + // Since delta and dist are now scaled by 10^m, we need to do the + // same with ulp in order to keep the units in sync. + // + // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e + // + const std::uint64_t ten_m = one.f; + grisu2_round(buffer, length, dist, delta, p2, ten_m); + + // By construction this algorithm generates the shortest possible decimal + // number (Loitsch, Theorem 6.2) which rounds back to w. + // For an input number of precision p, at least + // + // N = 1 + ceil(p * log_10(2)) + // + // decimal digits are sufficient to identify all binary floating-point + // numbers (Matula, "In-and-Out conversions"). + // This implies that the algorithm does not produce more than N decimal + // digits. + // + // N = 17 for p = 53 (IEEE double precision) + // N = 9 for p = 24 (IEEE single precision) +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +JSON_HEDLEY_NON_NULL(1) +inline void grisu2(char* buf, int& len, int& decimal_exponent, + diyfp m_minus, diyfp v, diyfp m_plus) +{ + JSON_ASSERT(m_plus.e == m_minus.e); + JSON_ASSERT(m_plus.e == v.e); + + // --------(-----------------------+-----------------------)-------- (A) + // m- v m+ + // + // --------------------(-----------+-----------------------)-------- (B) + // m- v m+ + // + // First scale v (and m- and m+) such that the exponent is in the range + // [alpha, gamma]. + + const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); + + const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k + + // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] + const diyfp w = diyfp::mul(v, c_minus_k); + const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); + const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); + + // ----(---+---)---------------(---+---)---------------(---+---)---- + // w- w w+ + // = c*m- = c*v = c*m+ + // + // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and + // w+ are now off by a small amount. + // In fact: + // + // w - v * 10^k < 1 ulp + // + // To account for this inaccuracy, add resp. subtract 1 ulp. + // + // --------+---[---------------(---+---)---------------]---+-------- + // w- M- w M+ w+ + // + // Now any number in [M-, M+] (bounds included) will round to w when input, + // regardless of how the input rounding algorithm breaks ties. + // + // And digit_gen generates the shortest possible such number in [M-, M+]. + // Note that this does not mean that Grisu2 always generates the shortest + // possible number in the interval (m-, m+). + const diyfp M_minus(w_minus.f + 1, w_minus.e); + const diyfp M_plus (w_plus.f - 1, w_plus.e ); + + decimal_exponent = -cached.k; // = -(-k) = k + + grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); +} + +/*! +v = buf * 10^decimal_exponent +len is the length of the buffer (number of decimal digits) +The buffer must be large enough, i.e. >= max_digits10. +*/ +template +JSON_HEDLEY_NON_NULL(1) +void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) +{ + static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, + "internal error: not enough precision"); + + JSON_ASSERT(std::isfinite(value)); + JSON_ASSERT(value > 0); + + // If the neighbors (and boundaries) of 'value' are always computed for double-precision + // numbers, all float's can be recovered using strtod (and strtof). However, the resulting + // decimal representations are not exactly "short". + // + // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) + // says "value is converted to a string as if by std::sprintf in the default ("C") locale" + // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' + // does. + // On the other hand, the documentation for 'std::to_chars' requires that "parsing the + // representation using the corresponding std::from_chars function recovers value exactly". That + // indicates that single precision floating-point numbers should be recovered using + // 'std::strtof'. + // + // NB: If the neighbors are computed for single-precision numbers, there is a single float + // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision + // value is off by 1 ulp. +#if 0 + const boundaries w = compute_boundaries(static_cast(value)); +#else + const boundaries w = compute_boundaries(value); +#endif + + grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); +} + +/*! +@brief appends a decimal representation of e to buf +@return a pointer to the element following the exponent. +@pre -1000 < e < 1000 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* append_exponent(char* buf, int e) +{ + JSON_ASSERT(e > -1000); + JSON_ASSERT(e < 1000); + + if (e < 0) + { + e = -e; + *buf++ = '-'; + } + else + { + *buf++ = '+'; + } + + auto k = static_cast(e); + if (k < 10) + { + // Always print at least two digits in the exponent. + // This is for compatibility with printf("%g"). + *buf++ = '0'; + *buf++ = static_cast('0' + k); + } + else if (k < 100) + { + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + else + { + *buf++ = static_cast('0' + k / 100); + k %= 100; + *buf++ = static_cast('0' + k / 10); + k %= 10; + *buf++ = static_cast('0' + k); + } + + return buf; +} + +/*! +@brief prettify v = buf * 10^decimal_exponent + +If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point +notation. Otherwise it will be printed in exponential notation. + +@pre min_exp < 0 +@pre max_exp > 0 +*/ +JSON_HEDLEY_NON_NULL(1) +JSON_HEDLEY_RETURNS_NON_NULL +inline char* format_buffer(char* buf, int len, int decimal_exponent, + int min_exp, int max_exp) +{ + JSON_ASSERT(min_exp < 0); + JSON_ASSERT(max_exp > 0); + + const int k = len; + const int n = len + decimal_exponent; + + // v = buf * 10^(n-k) + // k is the length of the buffer (number of decimal digits) + // n is the position of the decimal point relative to the start of the buffer. + + if (k <= n && n <= max_exp) + { + // digits[000] + // len <= max_exp + 2 + + std::memset(buf + k, '0', static_cast(n) - static_cast(k)); + // Make it look like a floating-point number (#362, #378) + buf[n + 0] = '.'; + buf[n + 1] = '0'; + return buf + (static_cast(n) + 2); + } + + if (0 < n && n <= max_exp) + { + // dig.its + // len <= max_digits10 + 1 + + JSON_ASSERT(k > n); + + std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); + buf[n] = '.'; + return buf + (static_cast(k) + 1U); + } + + if (min_exp < n && n <= 0) + { + // 0.[000]digits + // len <= 2 + (-min_exp - 1) + max_digits10 + + std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); + buf[0] = '0'; + buf[1] = '.'; + std::memset(buf + 2, '0', static_cast(-n)); + return buf + (2U + static_cast(-n) + static_cast(k)); + } + + if (k == 1) + { + // dE+123 + // len <= 1 + 5 + + buf += 1; + } + else + { + // d.igitsE+123 + // len <= max_digits10 + 1 + 5 + + std::memmove(buf + 2, buf + 1, static_cast(k) - 1); + buf[1] = '.'; + buf += 1 + static_cast(k); + } + + *buf++ = 'e'; + return append_exponent(buf, n - 1); +} + +} // namespace dtoa_impl + +/*! +@brief generates a decimal representation of the floating-point number value in [first, last). + +The format of the resulting decimal representation is similar to printf's %g +format. Returns an iterator pointing past-the-end of the decimal representation. + +@note The input number must be finite, i.e. NaN's and Inf's are not supported. +@note The buffer must be large enough. +@note The result is NOT null-terminated. +*/ +template +JSON_HEDLEY_NON_NULL(1, 2) +JSON_HEDLEY_RETURNS_NON_NULL +char* to_chars(char* first, const char* last, FloatType value) +{ + static_cast(last); // maybe unused - fix warning + JSON_ASSERT(std::isfinite(value)); + + // Use signbit(value) instead of (value < 0) since signbit works for -0. + if (std::signbit(value)) + { + value = -value; + *first++ = '-'; + } + +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + if (value == 0) // +-0 + { + *first++ = '0'; + // Make it look like a floating-point number (#362, #378) + *first++ = '.'; + *first++ = '0'; + return first; + } +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); + + // Compute v = buffer * 10^decimal_exponent. + // The decimal digits are stored in the buffer, which needs to be interpreted + // as an unsigned decimal integer. + // len is the length of the buffer, i.e. the number of decimal digits. + int len = 0; + int decimal_exponent = 0; + dtoa_impl::grisu2(first, len, decimal_exponent, value); + + JSON_ASSERT(len <= std::numeric_limits::max_digits10); + + // Format the buffer like printf("%.*g", prec, value) + constexpr int kMinExp = -4; + // Use digits10 here to increase compatibility with version 2. + constexpr int kMaxExp = std::numeric_limits::digits10; + + JSON_ASSERT(last - first >= kMaxExp + 2); + JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); + JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); + + return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); +} + +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + +// #include + +// #include + +// #include + + +namespace nlohmann +{ +namespace detail +{ +/////////////////// +// serialization // +/////////////////// + +/// how to treat decoding errors +enum class error_handler_t +{ + strict, ///< throw a type_error exception in case of invalid UTF-8 + replace, ///< replace invalid UTF-8 sequences with U+FFFD + ignore ///< ignore invalid UTF-8 sequences +}; + +template +class serializer +{ + using string_t = typename BasicJsonType::string_t; + using number_float_t = typename BasicJsonType::number_float_t; + using number_integer_t = typename BasicJsonType::number_integer_t; + using number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using binary_char_t = typename BasicJsonType::binary_t::value_type; + static constexpr std::uint8_t UTF8_ACCEPT = 0; + static constexpr std::uint8_t UTF8_REJECT = 1; + + public: + /*! + @param[in] s output stream to serialize to + @param[in] ichar indentation character to use + @param[in] error_handler_ how to react on decoding errors + */ + serializer(output_adapter_t s, const char ichar, + error_handler_t error_handler_ = error_handler_t::strict) + : o(std::move(s)) + , loc(std::localeconv()) + , thousands_sep(loc->thousands_sep == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->thousands_sep))) + , decimal_point(loc->decimal_point == nullptr ? '\0' : std::char_traits::to_char_type(* (loc->decimal_point))) + , indent_char(ichar) + , indent_string(512, indent_char) + , error_handler(error_handler_) + {} + + // delete because of pointer members + serializer(const serializer&) = delete; + serializer& operator=(const serializer&) = delete; + serializer(serializer&&) = delete; + serializer& operator=(serializer&&) = delete; + ~serializer() = default; + + /*! + @brief internal implementation of the serialization function + + This function is called by the public member function dump and organizes + the serialization internally. The indentation level is propagated as + additional parameter. In case of arrays and objects, the function is + called recursively. + + - strings and object keys are escaped using `escape_string()` + - integer numbers are converted implicitly via `operator<<` + - floating-point numbers are converted to a string using `"%g"` format + - binary values are serialized as objects containing the subtype and the + byte array + + @param[in] val value to serialize + @param[in] pretty_print whether the output shall be pretty-printed + @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters + in the output are escaped with `\uXXXX` sequences, and the result consists + of ASCII characters only. + @param[in] indent_step the indent level + @param[in] current_indent the current indent level (only used internally) + */ + void dump(const BasicJsonType& val, + const bool pretty_print, + const bool ensure_ascii, + const unsigned int indent_step, + const unsigned int current_indent = 0) + { + switch (val.m_type) + { + case value_t::object: + { + if (val.m_value.object->empty()) + { + o->write_characters("{}", 2); + return; + } + + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_characters(indent_string.c_str(), new_indent); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\": ", 3); + dump(i->second, true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_character('{'); + + // first n-1 elements + auto i = val.m_value.object->cbegin(); + for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) + { + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(i != val.m_value.object->cend()); + JSON_ASSERT(std::next(i) == val.m_value.object->cend()); + o->write_character('\"'); + dump_escaped(i->first, ensure_ascii); + o->write_characters("\":", 2); + dump(i->second, false, ensure_ascii, indent_step, current_indent); + + o->write_character('}'); + } + + return; + } + + case value_t::array: + { + if (val.m_value.array->empty()) + { + o->write_characters("[]", 2); + return; + } + + if (pretty_print) + { + o->write_characters("[\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + o->write_characters(indent_string.c_str(), new_indent); + dump(*i, true, ensure_ascii, indent_step, new_indent); + o->write_characters(",\n", 2); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + o->write_characters(indent_string.c_str(), new_indent); + dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); + + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character(']'); + } + else + { + o->write_character('['); + + // first n-1 elements + for (auto i = val.m_value.array->cbegin(); + i != val.m_value.array->cend() - 1; ++i) + { + dump(*i, false, ensure_ascii, indent_step, current_indent); + o->write_character(','); + } + + // last element + JSON_ASSERT(!val.m_value.array->empty()); + dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); + + o->write_character(']'); + } + + return; + } + + case value_t::string: + { + o->write_character('\"'); + dump_escaped(*val.m_value.string, ensure_ascii); + o->write_character('\"'); + return; + } + + case value_t::binary: + { + if (pretty_print) + { + o->write_characters("{\n", 2); + + // variable to hold indentation for recursive calls + const auto new_indent = current_indent + indent_step; + if (JSON_HEDLEY_UNLIKELY(indent_string.size() < new_indent)) + { + indent_string.resize(indent_string.size() * 2, ' '); + } + + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"bytes\": [", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_characters(", ", 2); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\n", 3); + o->write_characters(indent_string.c_str(), new_indent); + + o->write_characters("\"subtype\": ", 11); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + } + else + { + o->write_characters("null", 4); + } + o->write_character('\n'); + o->write_characters(indent_string.c_str(), current_indent); + o->write_character('}'); + } + else + { + o->write_characters("{\"bytes\":[", 10); + + if (!val.m_value.binary->empty()) + { + for (auto i = val.m_value.binary->cbegin(); + i != val.m_value.binary->cend() - 1; ++i) + { + dump_integer(*i); + o->write_character(','); + } + dump_integer(val.m_value.binary->back()); + } + + o->write_characters("],\"subtype\":", 12); + if (val.m_value.binary->has_subtype()) + { + dump_integer(val.m_value.binary->subtype()); + o->write_character('}'); + } + else + { + o->write_characters("null}", 5); + } + } + return; + } + + case value_t::boolean: + { + if (val.m_value.boolean) + { + o->write_characters("true", 4); + } + else + { + o->write_characters("false", 5); + } + return; + } + + case value_t::number_integer: + { + dump_integer(val.m_value.number_integer); + return; + } + + case value_t::number_unsigned: + { + dump_integer(val.m_value.number_unsigned); + return; + } + + case value_t::number_float: + { + dump_float(val.m_value.number_float); + return; + } + + case value_t::discarded: + { + o->write_characters("", 11); + return; + } + + case value_t::null: + { + o->write_characters("null", 4); + return; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + } + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief dump escaped string + + Escape a string by replacing certain special characters by a sequence of an + escape character (backslash) and another character and other control + characters by a sequence of "\u" followed by a four-digit hex + representation. The escaped string is written to output stream @a o. + + @param[in] s the string to escape + @param[in] ensure_ascii whether to escape non-ASCII characters with + \uXXXX sequences + + @complexity Linear in the length of string @a s. + */ + void dump_escaped(const string_t& s, const bool ensure_ascii) + { + std::uint32_t codepoint{}; + std::uint8_t state = UTF8_ACCEPT; + std::size_t bytes = 0; // number of bytes written to string_buffer + + // number of bytes written at the point of the last valid byte + std::size_t bytes_after_last_accept = 0; + std::size_t undumped_chars = 0; + + for (std::size_t i = 0; i < s.size(); ++i) + { + const auto byte = static_cast(s[i]); + + switch (decode(state, codepoint, byte)) + { + case UTF8_ACCEPT: // decode found a new code point + { + switch (codepoint) + { + case 0x08: // backspace + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'b'; + break; + } + + case 0x09: // horizontal tab + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 't'; + break; + } + + case 0x0A: // newline + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'n'; + break; + } + + case 0x0C: // formfeed + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'f'; + break; + } + + case 0x0D: // carriage return + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'r'; + break; + } + + case 0x22: // quotation mark + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\"'; + break; + } + + case 0x5C: // reverse solidus + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = '\\'; + break; + } + + default: + { + // escape control characters (0x00..0x1F) or, if + // ensure_ascii parameter is used, non-ASCII characters + if ((codepoint <= 0x1F) || (ensure_ascii && (codepoint >= 0x7F))) + { + if (codepoint <= 0xFFFF) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + static_cast((std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", + static_cast(codepoint))); + bytes += 6; + } + else + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + static_cast((std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", + static_cast(0xD7C0u + (codepoint >> 10u)), + static_cast(0xDC00u + (codepoint & 0x3FFu)))); + bytes += 12; + } + } + else + { + // copy byte to buffer (all previous bytes + // been copied have in default case above) + string_buffer[bytes++] = s[i]; + } + break; + } + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + // remember the byte position of this accept + bytes_after_last_accept = bytes; + undumped_chars = 0; + break; + } + + case UTF8_REJECT: // decode found invalid UTF-8 byte + { + switch (error_handler) + { + case error_handler_t::strict: + { + std::stringstream ss; + ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (byte | 0); + JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + ss.str(), BasicJsonType())); + } + + case error_handler_t::ignore: + case error_handler_t::replace: + { + // in case we saw this character the first time, we + // would like to read it again, because the byte + // may be OK for itself, but just not OK for the + // previous sequence + if (undumped_chars > 0) + { + --i; + } + + // reset length buffer to the last accepted index; + // thus removing/ignoring the invalid characters + bytes = bytes_after_last_accept; + + if (error_handler == error_handler_t::replace) + { + // add a replacement character + if (ensure_ascii) + { + string_buffer[bytes++] = '\\'; + string_buffer[bytes++] = 'u'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'f'; + string_buffer[bytes++] = 'd'; + } + else + { + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xEF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBF'); + string_buffer[bytes++] = detail::binary_writer::to_char_type('\xBD'); + } + + // write buffer and reset index; there must be 13 bytes + // left, as this is the maximal number of bytes to be + // written ("\uxxxx\uxxxx\0") for one code point + if (string_buffer.size() - bytes < 13) + { + o->write_characters(string_buffer.data(), bytes); + bytes = 0; + } + + bytes_after_last_accept = bytes; + } + + undumped_chars = 0; + + // continue processing the string + state = UTF8_ACCEPT; + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + break; + } + + default: // decode found yet incomplete multi-byte code point + { + if (!ensure_ascii) + { + // code point will not be escaped - copy byte to buffer + string_buffer[bytes++] = s[i]; + } + ++undumped_chars; + break; + } + } + } + + // we finished processing the string + if (JSON_HEDLEY_LIKELY(state == UTF8_ACCEPT)) + { + // write buffer + if (bytes > 0) + { + o->write_characters(string_buffer.data(), bytes); + } + } + else + { + // we finish reading, but do not accept: string was incomplete + switch (error_handler) + { + case error_handler_t::strict: + { + std::stringstream ss; + ss << std::uppercase << std::setfill('0') << std::setw(2) << std::hex << (static_cast(s.back()) | 0); + JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + ss.str(), BasicJsonType())); + } + + case error_handler_t::ignore: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + break; + } + + case error_handler_t::replace: + { + // write all accepted bytes + o->write_characters(string_buffer.data(), bytes_after_last_accept); + // add a replacement character + if (ensure_ascii) + { + o->write_characters("\\ufffd", 6); + } + else + { + o->write_characters("\xEF\xBF\xBD", 3); + } + break; + } + + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + } + } + + private: + /*! + @brief count digits + + Count the number of decimal (base 10) digits for an input unsigned integer. + + @param[in] x unsigned integer number to count its digits + @return number of decimal digits + */ + inline unsigned int count_digits(number_unsigned_t x) noexcept + { + unsigned int n_digits = 1; + for (;;) + { + if (x < 10) + { + return n_digits; + } + if (x < 100) + { + return n_digits + 1; + } + if (x < 1000) + { + return n_digits + 2; + } + if (x < 10000) + { + return n_digits + 3; + } + x = x / 10000u; + n_digits += 4; + } + } + + // templates to avoid warnings about useless casts + template ::value, int> = 0> + bool is_negative_number(NumberType x) + { + return x < 0; + } + + template < typename NumberType, enable_if_t ::value, int > = 0 > + bool is_negative_number(NumberType /*unused*/) + { + return false; + } + + /*! + @brief dump an integer + + Dump a given integer to output stream @a o. Works internally with + @a number_buffer. + + @param[in] x integer number (signed or unsigned) to dump + @tparam NumberType either @a number_integer_t or @a number_unsigned_t + */ + template < typename NumberType, detail::enable_if_t < + std::is_integral::value || + std::is_same::value || + std::is_same::value || + std::is_same::value, + int > = 0 > + void dump_integer(NumberType x) + { + static constexpr std::array, 100> digits_to_99 + { + { + {{'0', '0'}}, {{'0', '1'}}, {{'0', '2'}}, {{'0', '3'}}, {{'0', '4'}}, {{'0', '5'}}, {{'0', '6'}}, {{'0', '7'}}, {{'0', '8'}}, {{'0', '9'}}, + {{'1', '0'}}, {{'1', '1'}}, {{'1', '2'}}, {{'1', '3'}}, {{'1', '4'}}, {{'1', '5'}}, {{'1', '6'}}, {{'1', '7'}}, {{'1', '8'}}, {{'1', '9'}}, + {{'2', '0'}}, {{'2', '1'}}, {{'2', '2'}}, {{'2', '3'}}, {{'2', '4'}}, {{'2', '5'}}, {{'2', '6'}}, {{'2', '7'}}, {{'2', '8'}}, {{'2', '9'}}, + {{'3', '0'}}, {{'3', '1'}}, {{'3', '2'}}, {{'3', '3'}}, {{'3', '4'}}, {{'3', '5'}}, {{'3', '6'}}, {{'3', '7'}}, {{'3', '8'}}, {{'3', '9'}}, + {{'4', '0'}}, {{'4', '1'}}, {{'4', '2'}}, {{'4', '3'}}, {{'4', '4'}}, {{'4', '5'}}, {{'4', '6'}}, {{'4', '7'}}, {{'4', '8'}}, {{'4', '9'}}, + {{'5', '0'}}, {{'5', '1'}}, {{'5', '2'}}, {{'5', '3'}}, {{'5', '4'}}, {{'5', '5'}}, {{'5', '6'}}, {{'5', '7'}}, {{'5', '8'}}, {{'5', '9'}}, + {{'6', '0'}}, {{'6', '1'}}, {{'6', '2'}}, {{'6', '3'}}, {{'6', '4'}}, {{'6', '5'}}, {{'6', '6'}}, {{'6', '7'}}, {{'6', '8'}}, {{'6', '9'}}, + {{'7', '0'}}, {{'7', '1'}}, {{'7', '2'}}, {{'7', '3'}}, {{'7', '4'}}, {{'7', '5'}}, {{'7', '6'}}, {{'7', '7'}}, {{'7', '8'}}, {{'7', '9'}}, + {{'8', '0'}}, {{'8', '1'}}, {{'8', '2'}}, {{'8', '3'}}, {{'8', '4'}}, {{'8', '5'}}, {{'8', '6'}}, {{'8', '7'}}, {{'8', '8'}}, {{'8', '9'}}, + {{'9', '0'}}, {{'9', '1'}}, {{'9', '2'}}, {{'9', '3'}}, {{'9', '4'}}, {{'9', '5'}}, {{'9', '6'}}, {{'9', '7'}}, {{'9', '8'}}, {{'9', '9'}}, + } + }; + + // special case for "0" + if (x == 0) + { + o->write_character('0'); + return; + } + + // use a pointer to fill the buffer + auto buffer_ptr = number_buffer.begin(); // NOLINT(llvm-qualified-auto,readability-qualified-auto,cppcoreguidelines-pro-type-vararg,hicpp-vararg) + + number_unsigned_t abs_value; + + unsigned int n_chars{}; + + if (is_negative_number(x)) + { + *buffer_ptr = '-'; + abs_value = remove_sign(static_cast(x)); + + // account one more byte for the minus sign + n_chars = 1 + count_digits(abs_value); + } + else + { + abs_value = static_cast(x); + n_chars = count_digits(abs_value); + } + + // spare 1 byte for '\0' + JSON_ASSERT(n_chars < number_buffer.size() - 1); + + // jump to the end to generate the string from backward, + // so we later avoid reversing the result + buffer_ptr += n_chars; + + // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu + // See: https://www.youtube.com/watch?v=o4-CwDo2zpg + while (abs_value >= 100) + { + const auto digits_index = static_cast((abs_value % 100)); + abs_value /= 100; + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + + if (abs_value >= 10) + { + const auto digits_index = static_cast(abs_value); + *(--buffer_ptr) = digits_to_99[digits_index][1]; + *(--buffer_ptr) = digits_to_99[digits_index][0]; + } + else + { + *(--buffer_ptr) = static_cast('0' + abs_value); + } + + o->write_characters(number_buffer.data(), n_chars); + } + + /*! + @brief dump a floating-point number + + Dump a given floating-point number to output stream @a o. Works internally + with @a number_buffer. + + @param[in] x floating-point number to dump + */ + void dump_float(number_float_t x) + { + // NaN / inf + if (!std::isfinite(x)) + { + o->write_characters("null", 4); + return; + } + + // If number_float_t is an IEEE-754 single or double precision number, + // use the Grisu2 algorithm to produce short numbers which are + // guaranteed to round-trip, using strtof and strtod, resp. + // + // NB: The test below works if == . + static constexpr bool is_ieee_single_or_double + = (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 24 && std::numeric_limits::max_exponent == 128) || + (std::numeric_limits::is_iec559 && std::numeric_limits::digits == 53 && std::numeric_limits::max_exponent == 1024); + + dump_float(x, std::integral_constant()); + } + + void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) + { + auto* begin = number_buffer.data(); + auto* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); + + o->write_characters(begin, static_cast(end - begin)); + } + + void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) + { + // get number of digits for a float -> text -> float round-trip + static constexpr auto d = std::numeric_limits::max_digits10; + + // the actual conversion + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg,hicpp-vararg) + std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); + + // negative value indicates an error + JSON_ASSERT(len > 0); + // check if buffer was large enough + JSON_ASSERT(static_cast(len) < number_buffer.size()); + + // erase thousands separator + if (thousands_sep != '\0') + { + // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::remove returns an iterator, see https://github.com/nlohmann/json/issues/3081 + const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); + std::fill(end, number_buffer.end(), '\0'); + JSON_ASSERT((end - number_buffer.begin()) <= len); + len = (end - number_buffer.begin()); + } + + // convert decimal point to '.' + if (decimal_point != '\0' && decimal_point != '.') + { + // NOLINTNEXTLINE(readability-qualified-auto,llvm-qualified-auto): std::find returns an iterator, see https://github.com/nlohmann/json/issues/3081 + const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); + if (dec_pos != number_buffer.end()) + { + *dec_pos = '.'; + } + } + + o->write_characters(number_buffer.data(), static_cast(len)); + + // determine if we need to append ".0" + const bool value_is_int_like = + std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, + [](char c) + { + return c == '.' || c == 'e'; + }); + + if (value_is_int_like) + { + o->write_characters(".0", 2); + } + } + + /*! + @brief check whether a string is UTF-8 encoded + + The function checks each byte of a string whether it is UTF-8 encoded. The + result of the check is stored in the @a state parameter. The function must + be called initially with state 0 (accept). State 1 means the string must + be rejected, because the current byte is not allowed. If the string is + completely processed, but the state is non-zero, the string ended + prematurely; that is, the last byte indicated more bytes should have + followed. + + @param[in,out] state the state of the decoding + @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) + @param[in] byte next byte to decode + @return new state + + @note The function has been edited: a std::array is used. + + @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann + @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ + */ + static std::uint8_t decode(std::uint8_t& state, std::uint32_t& codep, const std::uint8_t byte) noexcept + { + static const std::array utf8d = + { + { + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF + 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF + 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF + 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF + 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 + 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 + 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 + 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 + } + }; + + JSON_ASSERT(byte < utf8d.size()); + const std::uint8_t type = utf8d[byte]; + + codep = (state != UTF8_ACCEPT) + ? (byte & 0x3fu) | (codep << 6u) + : (0xFFu >> type) & (byte); + + std::size_t index = 256u + static_cast(state) * 16u + static_cast(type); + JSON_ASSERT(index < 400); + state = utf8d[index]; + return state; + } + + /* + * Overload to make the compiler happy while it is instantiating + * dump_integer for number_unsigned_t. + * Must never be called. + */ + number_unsigned_t remove_sign(number_unsigned_t x) + { + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + return x; // LCOV_EXCL_LINE + } + + /* + * Helper function for dump_integer + * + * This function takes a negative signed integer and returns its absolute + * value as unsigned integer. The plus/minus shuffling is necessary as we can + * not directly remove the sign of an arbitrary signed integer as the + * absolute values of INT_MIN and INT_MAX are usually not the same. See + * #1708 for details. + */ + inline number_unsigned_t remove_sign(number_integer_t x) noexcept + { + JSON_ASSERT(x < 0 && x < (std::numeric_limits::max)()); // NOLINT(misc-redundant-expression) + return static_cast(-(x + 1)) + 1; + } + + private: + /// the output of the serializer + output_adapter_t o = nullptr; + + /// a (hopefully) large enough character buffer + std::array number_buffer{{}}; + + /// the locale + const std::lconv* loc = nullptr; + /// the locale's thousand separator character + const char thousands_sep = '\0'; + /// the locale's decimal point character + const char decimal_point = '\0'; + + /// string buffer + std::array string_buffer{{}}; + + /// the indentation character + const char indent_char; + /// the indentation string + string_t indent_string; + + /// error_handler how to react on decoding errors + const error_handler_t error_handler; +}; +} // namespace detail +} // namespace nlohmann + +// #include + +// #include + +// #include + + +#include // less +#include // initializer_list +#include // input_iterator_tag, iterator_traits +#include // allocator +#include // for out_of_range +#include // enable_if, is_convertible +#include // pair +#include // vector + +// #include + + +namespace nlohmann +{ + +/// ordered_map: a minimal map-like container that preserves insertion order +/// for use within nlohmann::basic_json +template , + class Allocator = std::allocator>> + struct ordered_map : std::vector, Allocator> +{ + using key_type = Key; + using mapped_type = T; + using Container = std::vector, Allocator>; + using iterator = typename Container::iterator; + using const_iterator = typename Container::const_iterator; + using size_type = typename Container::size_type; + using value_type = typename Container::value_type; + + // Explicit constructors instead of `using Container::Container` + // otherwise older compilers choke on it (GCC <= 5.5, xcode <= 9.4) + ordered_map(const Allocator& alloc = Allocator()) : Container{alloc} {} + template + ordered_map(It first, It last, const Allocator& alloc = Allocator()) + : Container{first, last, alloc} {} + ordered_map(std::initializer_list init, const Allocator& alloc = Allocator() ) + : Container{init, alloc} {} + + std::pair emplace(const key_type& key, T&& t) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return {it, false}; + } + } + Container::emplace_back(key, t); + return {--this->end(), true}; + } + + T& operator[](const Key& key) + { + return emplace(key, T{}).first->second; + } + + const T& operator[](const Key& key) const + { + return at(key); + } + + T& at(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + JSON_THROW(std::out_of_range("key not found")); + } + + const T& at(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it->second; + } + } + + JSON_THROW(std::out_of_range("key not found")); + } + + size_type erase(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + // Since we cannot move const Keys, re-construct them in place + for (auto next = it; ++next != this->end(); ++it) + { + it->~value_type(); // Destroy but keep allocation + new (&*it) value_type{std::move(*next)}; + } + Container::pop_back(); + return 1; + } + } + return 0; + } + + iterator erase(iterator pos) + { + return erase(pos, std::next(pos)); + } + + iterator erase(iterator first, iterator last) + { + const auto elements_affected = std::distance(first, last); + const auto offset = std::distance(Container::begin(), first); + + // This is the start situation. We need to delete elements_affected + // elements (3 in this example: e, f, g), and need to return an + // iterator past the last deleted element (h in this example). + // Note that offset is the distance from the start of the vector + // to first. We will need this later. + + // [ a, b, c, d, e, f, g, h, i, j ] + // ^ ^ + // first last + + // Since we cannot move const Keys, we re-construct them in place. + // We start at first and re-construct (viz. copy) the elements from + // the back of the vector. Example for first iteration: + + // ,--------. + // v | destroy e and re-construct with h + // [ a, b, c, d, e, f, g, h, i, j ] + // ^ ^ + // it it + elements_affected + + for (auto it = first; std::next(it, elements_affected) != Container::end(); ++it) + { + it->~value_type(); // destroy but keep allocation + new (&*it) value_type{std::move(*std::next(it, elements_affected))}; // "move" next element to it + } + + // [ a, b, c, d, h, i, j, h, i, j ] + // ^ ^ + // first last + + // remove the unneeded elements at the end of the vector + Container::resize(this->size() - static_cast(elements_affected)); + + // [ a, b, c, d, h, i, j ] + // ^ ^ + // first last + + // first is now pointing past the last deleted element, but we cannot + // use this iterator, because it may have been invalidated by the + // resize call. Instead, we can return begin() + offset. + return Container::begin() + offset; + } + + size_type count(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return 1; + } + } + return 0; + } + + iterator find(const Key& key) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + const_iterator find(const Key& key) const + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == key) + { + return it; + } + } + return Container::end(); + } + + std::pair insert( value_type&& value ) + { + return emplace(value.first, std::move(value.second)); + } + + std::pair insert( const value_type& value ) + { + for (auto it = this->begin(); it != this->end(); ++it) + { + if (it->first == value.first) + { + return {it, false}; + } + } + Container::push_back(value); + return {--this->end(), true}; + } + + template + using require_input_iter = typename std::enable_if::iterator_category, + std::input_iterator_tag>::value>::type; + + template> + void insert(InputIt first, InputIt last) + { + for (auto it = first; it != last; ++it) + { + insert(*it); + } + } +}; + +} // namespace nlohmann + + +#if defined(JSON_HAS_CPP_17) + #include +#endif + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ + +/*! +@brief a class to store JSON values + +@internal +@invariant The member variables @a m_value and @a m_type have the following +relationship: +- If `m_type == value_t::object`, then `m_value.object != nullptr`. +- If `m_type == value_t::array`, then `m_value.array != nullptr`. +- If `m_type == value_t::string`, then `m_value.string != nullptr`. +The invariants are checked by member function assert_invariant(). + +@note ObjectType trick from https://stackoverflow.com/a/9860911 +@endinternal + +@since version 1.0.0 + +@nosubgrouping +*/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +class basic_json // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) +{ + private: + template friend struct detail::external_constructor; + friend ::nlohmann::json_pointer; + + template + friend class ::nlohmann::detail::parser; + friend ::nlohmann::detail::serializer; + template + friend class ::nlohmann::detail::iter_impl; + template + friend class ::nlohmann::detail::binary_writer; + template + friend class ::nlohmann::detail::binary_reader; + template + friend class ::nlohmann::detail::json_sax_dom_parser; + template + friend class ::nlohmann::detail::json_sax_dom_callback_parser; + friend class ::nlohmann::detail::exception; + + /// workaround type for MSVC + using basic_json_t = NLOHMANN_BASIC_JSON_TPL; + + JSON_PRIVATE_UNLESS_TESTED: + // convenience aliases for types residing in namespace detail; + using lexer = ::nlohmann::detail::lexer_base; + + template + static ::nlohmann::detail::parser parser( + InputAdapterType adapter, + detail::parser_callback_tcb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false + ) + { + return ::nlohmann::detail::parser(std::move(adapter), + std::move(cb), allow_exceptions, ignore_comments); + } + + private: + using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; + template + using internal_iterator = ::nlohmann::detail::internal_iterator; + template + using iter_impl = ::nlohmann::detail::iter_impl; + template + using iteration_proxy = ::nlohmann::detail::iteration_proxy; + template using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator; + + template + using output_adapter_t = ::nlohmann::detail::output_adapter_t; + + template + using binary_reader = ::nlohmann::detail::binary_reader; + template using binary_writer = ::nlohmann::detail::binary_writer; + + JSON_PRIVATE_UNLESS_TESTED: + using serializer = ::nlohmann::detail::serializer; + + public: + using value_t = detail::value_t; + /// JSON Pointer, see @ref nlohmann::json_pointer + using json_pointer = ::nlohmann::json_pointer; + template + using json_serializer = JSONSerializer; + /// how to treat decoding errors + using error_handler_t = detail::error_handler_t; + /// how to treat CBOR tags + using cbor_tag_handler_t = detail::cbor_tag_handler_t; + /// helper type for initializer lists of basic_json values + using initializer_list_t = std::initializer_list>; + + using input_format_t = detail::input_format_t; + /// SAX interface type, see @ref nlohmann::json_sax + using json_sax_t = json_sax; + + //////////////// + // exceptions // + //////////////// + + /// @name exceptions + /// Classes to implement user-defined exceptions. + /// @{ + + using exception = detail::exception; + using parse_error = detail::parse_error; + using invalid_iterator = detail::invalid_iterator; + using type_error = detail::type_error; + using out_of_range = detail::out_of_range; + using other_error = detail::other_error; + + /// @} + + + ///////////////////// + // container types // + ///////////////////// + + /// @name container types + /// The canonic container types to use @ref basic_json like any other STL + /// container. + /// @{ + + /// the type of elements in a basic_json container + using value_type = basic_json; + + /// the type of an element reference + using reference = value_type&; + /// the type of an element const reference + using const_reference = const value_type&; + + /// a type to represent differences between iterators + using difference_type = std::ptrdiff_t; + /// a type to represent container sizes + using size_type = std::size_t; + + /// the allocator type + using allocator_type = AllocatorType; + + /// the type of an element pointer + using pointer = typename std::allocator_traits::pointer; + /// the type of an element const pointer + using const_pointer = typename std::allocator_traits::const_pointer; + + /// an iterator for a basic_json container + using iterator = iter_impl; + /// a const iterator for a basic_json container + using const_iterator = iter_impl; + /// a reverse iterator for a basic_json container + using reverse_iterator = json_reverse_iterator; + /// a const reverse iterator for a basic_json container + using const_reverse_iterator = json_reverse_iterator; + + /// @} + + + /// @brief returns the allocator associated with the container + /// @sa https://json.nlohmann.me/api/basic_json/get_allocator/ + static allocator_type get_allocator() + { + return allocator_type(); + } + + /// @brief returns version information on the library + /// @sa https://json.nlohmann.me/api/basic_json/meta/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json meta() + { + basic_json result; + + result["copyright"] = "(C) 2013-2022 Niels Lohmann"; + result["name"] = "JSON for Modern C++"; + result["url"] = "https://github.com/nlohmann/json"; + result["version"]["string"] = + std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + + std::to_string(NLOHMANN_JSON_VERSION_PATCH); + result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; + result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; + result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; + +#ifdef _WIN32 + result["platform"] = "win32"; +#elif defined __linux__ + result["platform"] = "linux"; +#elif defined __APPLE__ + result["platform"] = "apple"; +#elif defined __unix__ + result["platform"] = "unix"; +#else + result["platform"] = "unknown"; +#endif + +#if defined(__ICC) || defined(__INTEL_COMPILER) + result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; +#elif defined(__clang__) + result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; +#elif defined(__GNUC__) || defined(__GNUG__) + result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; +#elif defined(__HP_cc) || defined(__HP_aCC) + result["compiler"] = "hp" +#elif defined(__IBMCPP__) + result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; +#elif defined(_MSC_VER) + result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; +#elif defined(__PGI) + result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; +#elif defined(__SUNPRO_CC) + result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; +#else + result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; +#endif + +#ifdef __cplusplus + result["compiler"]["c++"] = std::to_string(__cplusplus); +#else + result["compiler"]["c++"] = "unknown"; +#endif + return result; + } + + + /////////////////////////// + // JSON value data types // + /////////////////////////// + + /// @name JSON value data types + /// The data types to store a JSON value. These types are derived from + /// the template arguments passed to class @ref basic_json. + /// @{ + + /// @brief object key comparator type + /// @sa https://json.nlohmann.me/api/basic_json/object_comparator_t/ +#if defined(JSON_HAS_CPP_14) + // Use transparent comparator if possible, combined with perfect forwarding + // on find() and count() calls prevents unnecessary string construction. + using object_comparator_t = std::less<>; +#else + using object_comparator_t = std::less; +#endif + + /// @brief a type for an object + /// @sa https://json.nlohmann.me/api/basic_json/object_t/ + using object_t = ObjectType>>; + + /// @brief a type for an array + /// @sa https://json.nlohmann.me/api/basic_json/array_t/ + using array_t = ArrayType>; + + /// @brief a type for a string + /// @sa https://json.nlohmann.me/api/basic_json/string_t/ + using string_t = StringType; + + /// @brief a type for a boolean + /// @sa https://json.nlohmann.me/api/basic_json/boolean_t/ + using boolean_t = BooleanType; + + /// @brief a type for a number (integer) + /// @sa https://json.nlohmann.me/api/basic_json/number_integer_t/ + using number_integer_t = NumberIntegerType; + + /// @brief a type for a number (unsigned) + /// @sa https://json.nlohmann.me/api/basic_json/number_unsigned_t/ + using number_unsigned_t = NumberUnsignedType; + + /// @brief a type for a number (floating-point) + /// @sa https://json.nlohmann.me/api/basic_json/number_float_t/ + using number_float_t = NumberFloatType; + + /// @brief a type for a packed binary type + /// @sa https://json.nlohmann.me/api/basic_json/binary_t/ + using binary_t = nlohmann::byte_container_with_subtype; + + /// @} + + private: + + /// helper for exception-safe object creation + template + JSON_HEDLEY_RETURNS_NON_NULL + static T* create(Args&& ... args) + { + AllocatorType alloc; + using AllocatorTraits = std::allocator_traits>; + + auto deleter = [&](T * obj) + { + AllocatorTraits::deallocate(alloc, obj, 1); + }; + std::unique_ptr obj(AllocatorTraits::allocate(alloc, 1), deleter); + AllocatorTraits::construct(alloc, obj.get(), std::forward(args)...); + JSON_ASSERT(obj != nullptr); + return obj.release(); + } + + //////////////////////// + // JSON value storage // + //////////////////////// + + JSON_PRIVATE_UNLESS_TESTED: + /*! + @brief a JSON value + + The actual storage for a JSON value of the @ref basic_json class. This + union combines the different storage types for the JSON value types + defined in @ref value_t. + + JSON type | value_t type | used type + --------- | --------------- | ------------------------ + object | object | pointer to @ref object_t + array | array | pointer to @ref array_t + string | string | pointer to @ref string_t + boolean | boolean | @ref boolean_t + number | number_integer | @ref number_integer_t + number | number_unsigned | @ref number_unsigned_t + number | number_float | @ref number_float_t + binary | binary | pointer to @ref binary_t + null | null | *no value is stored* + + @note Variable-length types (objects, arrays, and strings) are stored as + pointers. The size of the union should not exceed 64 bits if the default + value types are used. + + @since version 1.0.0 + */ + union json_value + { + /// object (stored with pointer to save storage) + object_t* object; + /// array (stored with pointer to save storage) + array_t* array; + /// string (stored with pointer to save storage) + string_t* string; + /// binary (stored with pointer to save storage) + binary_t* binary; + /// boolean + boolean_t boolean; + /// number (integer) + number_integer_t number_integer; + /// number (unsigned integer) + number_unsigned_t number_unsigned; + /// number (floating-point) + number_float_t number_float; + + /// default constructor (for null values) + json_value() = default; + /// constructor for booleans + json_value(boolean_t v) noexcept : boolean(v) {} + /// constructor for numbers (integer) + json_value(number_integer_t v) noexcept : number_integer(v) {} + /// constructor for numbers (unsigned) + json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} + /// constructor for numbers (floating-point) + json_value(number_float_t v) noexcept : number_float(v) {} + /// constructor for empty values of a given type + json_value(value_t t) + { + switch (t) + { + case value_t::object: + { + object = create(); + break; + } + + case value_t::array: + { + array = create(); + break; + } + + case value_t::string: + { + string = create(""); + break; + } + + case value_t::binary: + { + binary = create(); + break; + } + + case value_t::boolean: + { + boolean = static_cast(false); + break; + } + + case value_t::number_integer: + { + number_integer = static_cast(0); + break; + } + + case value_t::number_unsigned: + { + number_unsigned = static_cast(0); + break; + } + + case value_t::number_float: + { + number_float = static_cast(0.0); + break; + } + + case value_t::null: + { + object = nullptr; // silence warning, see #821 + break; + } + + case value_t::discarded: + default: + { + object = nullptr; // silence warning, see #821 + if (JSON_HEDLEY_UNLIKELY(t == value_t::null)) + { + JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.10.5", basic_json())); // LCOV_EXCL_LINE + } + break; + } + } + } + + /// constructor for strings + json_value(const string_t& value) : string(create(value)) {} + + /// constructor for rvalue strings + json_value(string_t&& value) : string(create(std::move(value))) {} + + /// constructor for objects + json_value(const object_t& value) : object(create(value)) {} + + /// constructor for rvalue objects + json_value(object_t&& value) : object(create(std::move(value))) {} + + /// constructor for arrays + json_value(const array_t& value) : array(create(value)) {} + + /// constructor for rvalue arrays + json_value(array_t&& value) : array(create(std::move(value))) {} + + /// constructor for binary arrays + json_value(const typename binary_t::container_type& value) : binary(create(value)) {} + + /// constructor for rvalue binary arrays + json_value(typename binary_t::container_type&& value) : binary(create(std::move(value))) {} + + /// constructor for binary arrays (internal type) + json_value(const binary_t& value) : binary(create(value)) {} + + /// constructor for rvalue binary arrays (internal type) + json_value(binary_t&& value) : binary(create(std::move(value))) {} + + void destroy(value_t t) + { + if (t == value_t::array || t == value_t::object) + { + // flatten the current json_value to a heap-allocated stack + std::vector stack; + + // move the top-level items to stack + if (t == value_t::array) + { + stack.reserve(array->size()); + std::move(array->begin(), array->end(), std::back_inserter(stack)); + } + else + { + stack.reserve(object->size()); + for (auto&& it : *object) + { + stack.push_back(std::move(it.second)); + } + } + + while (!stack.empty()) + { + // move the last item to local variable to be processed + basic_json current_item(std::move(stack.back())); + stack.pop_back(); + + // if current_item is array/object, move + // its children to the stack to be processed later + if (current_item.is_array()) + { + std::move(current_item.m_value.array->begin(), current_item.m_value.array->end(), std::back_inserter(stack)); + + current_item.m_value.array->clear(); + } + else if (current_item.is_object()) + { + for (auto&& it : *current_item.m_value.object) + { + stack.push_back(std::move(it.second)); + } + + current_item.m_value.object->clear(); + } + + // it's now safe that current_item get destructed + // since it doesn't have any children + } + } + + switch (t) + { + case value_t::object: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, object); + std::allocator_traits::deallocate(alloc, object, 1); + break; + } + + case value_t::array: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, array); + std::allocator_traits::deallocate(alloc, array, 1); + break; + } + + case value_t::string: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, string); + std::allocator_traits::deallocate(alloc, string, 1); + break; + } + + case value_t::binary: + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, binary); + std::allocator_traits::deallocate(alloc, binary, 1); + break; + } + + case value_t::null: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::discarded: + default: + { + break; + } + } + } + }; + + private: + /*! + @brief checks the class invariants + + This function asserts the class invariants. It needs to be called at the + end of every constructor to make sure that created objects respect the + invariant. Furthermore, it has to be called each time the type of a JSON + value is changed, because the invariant expresses a relationship between + @a m_type and @a m_value. + + Furthermore, the parent relation is checked for arrays and objects: If + @a check_parents true and the value is an array or object, then the + container's elements must have the current value as parent. + + @param[in] check_parents whether the parent relation should be checked. + The value is true by default and should only be set to false + during destruction of objects when the invariant does not + need to hold. + */ + void assert_invariant(bool check_parents = true) const noexcept + { + JSON_ASSERT(m_type != value_t::object || m_value.object != nullptr); + JSON_ASSERT(m_type != value_t::array || m_value.array != nullptr); + JSON_ASSERT(m_type != value_t::string || m_value.string != nullptr); + JSON_ASSERT(m_type != value_t::binary || m_value.binary != nullptr); + +#if JSON_DIAGNOSTICS + JSON_TRY + { + // cppcheck-suppress assertWithSideEffect + JSON_ASSERT(!check_parents || !is_structured() || std::all_of(begin(), end(), [this](const basic_json & j) + { + return j.m_parent == this; + })); + } + JSON_CATCH(...) {} // LCOV_EXCL_LINE +#endif + static_cast(check_parents); + } + + void set_parents() + { +#if JSON_DIAGNOSTICS + switch (m_type) + { + case value_t::array: + { + for (auto& element : *m_value.array) + { + element.m_parent = this; + } + break; + } + + case value_t::object: + { + for (auto& element : *m_value.object) + { + element.second.m_parent = this; + } + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + break; + } +#endif + } + + iterator set_parents(iterator it, typename iterator::difference_type count_set_parents) + { +#if JSON_DIAGNOSTICS + for (typename iterator::difference_type i = 0; i < count_set_parents; ++i) + { + (it + i)->m_parent = this; + } +#else + static_cast(count_set_parents); +#endif + return it; + } + + reference set_parent(reference j, std::size_t old_capacity = static_cast(-1)) + { +#if JSON_DIAGNOSTICS + if (old_capacity != static_cast(-1)) + { + // see https://github.com/nlohmann/json/issues/2838 + JSON_ASSERT(type() == value_t::array); + if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) + { + // capacity has changed: update all parents + set_parents(); + return j; + } + } + + // ordered_json uses a vector internally, so pointers could have + // been invalidated; see https://github.com/nlohmann/json/issues/2962 +#ifdef JSON_HEDLEY_MSVC_VERSION +#pragma warning(push ) +#pragma warning(disable : 4127) // ignore warning to replace if with if constexpr +#endif + if (detail::is_ordered_map::value) + { + set_parents(); + return j; + } +#ifdef JSON_HEDLEY_MSVC_VERSION +#pragma warning( pop ) +#endif + + j.m_parent = this; +#else + static_cast(j); + static_cast(old_capacity); +#endif + return j; + } + + public: + ////////////////////////// + // JSON parser callback // + ////////////////////////// + + /// @brief parser event types + /// @sa https://json.nlohmann.me/api/basic_json/parse_event_t/ + using parse_event_t = detail::parse_event_t; + + /// @brief per-element parser callback type + /// @sa https://json.nlohmann.me/api/basic_json/parser_callback_t/ + using parser_callback_t = detail::parser_callback_t; + + ////////////////// + // constructors // + ////////////////// + + /// @name constructors and destructors + /// Constructors of class @ref basic_json, copy/move constructor, copy + /// assignment, static functions creating objects, and the destructor. + /// @{ + + /// @brief create an empty value with a given type + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(const value_t v) + : m_type(v), m_value(v) + { + assert_invariant(); + } + + /// @brief create a null object + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(std::nullptr_t = nullptr) noexcept + : basic_json(value_t::null) + { + assert_invariant(); + } + + /// @brief create a JSON value from compatible types + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + template < typename CompatibleType, + typename U = detail::uncvref_t, + detail::enable_if_t < + !detail::is_basic_json::value && detail::is_compatible_type::value, int > = 0 > + basic_json(CompatibleType && val) noexcept(noexcept( // NOLINT(bugprone-forwarding-reference-overload,bugprone-exception-escape) + JSONSerializer::to_json(std::declval(), + std::forward(val)))) + { + JSONSerializer::to_json(*this, std::forward(val)); + set_parents(); + assert_invariant(); + } + + /// @brief create a JSON value from an existing one + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value&& !std::is_same::value, int > = 0 > + basic_json(const BasicJsonType& val) + { + using other_boolean_t = typename BasicJsonType::boolean_t; + using other_number_float_t = typename BasicJsonType::number_float_t; + using other_number_integer_t = typename BasicJsonType::number_integer_t; + using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; + using other_string_t = typename BasicJsonType::string_t; + using other_object_t = typename BasicJsonType::object_t; + using other_array_t = typename BasicJsonType::array_t; + using other_binary_t = typename BasicJsonType::binary_t; + + switch (val.type()) + { + case value_t::boolean: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_float: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_integer: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::number_unsigned: + JSONSerializer::to_json(*this, val.template get()); + break; + case value_t::string: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::object: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::array: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::binary: + JSONSerializer::to_json(*this, val.template get_ref()); + break; + case value_t::null: + *this = nullptr; + break; + case value_t::discarded: + m_type = value_t::discarded; + break; + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + set_parents(); + assert_invariant(); + } + + /// @brief create a container (array or object) from an initializer list + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(initializer_list_t init, + bool type_deduction = true, + value_t manual_type = value_t::array) + { + // check if each element is an array with two elements whose first + // element is a string + bool is_an_object = std::all_of(init.begin(), init.end(), + [](const detail::json_ref& element_ref) + { + return element_ref->is_array() && element_ref->size() == 2 && (*element_ref)[0].is_string(); + }); + + // adjust type if type deduction is not wanted + if (!type_deduction) + { + // if array is wanted, do not create an object though possible + if (manual_type == value_t::array) + { + is_an_object = false; + } + + // if object is wanted but impossible, throw an exception + if (JSON_HEDLEY_UNLIKELY(manual_type == value_t::object && !is_an_object)) + { + JSON_THROW(type_error::create(301, "cannot create object from initializer list", basic_json())); + } + } + + if (is_an_object) + { + // the initializer list is a list of pairs -> create object + m_type = value_t::object; + m_value = value_t::object; + + for (auto& element_ref : init) + { + auto element = element_ref.moved_or_copied(); + m_value.object->emplace( + std::move(*((*element.m_value.array)[0].m_value.string)), + std::move((*element.m_value.array)[1])); + } + } + else + { + // the initializer list describes an array -> create array + m_type = value_t::array; + m_value.array = create(init.begin(), init.end()); + } + + set_parents(); + assert_invariant(); + } + + /// @brief explicitly create a binary array (without subtype) + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = init; + return res; + } + + /// @brief explicitly create a binary array (with subtype) + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(const typename binary_t::container_type& init, typename binary_t::subtype_type subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(init, subtype); + return res; + } + + /// @brief explicitly create a binary array + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = std::move(init); + return res; + } + + /// @brief explicitly create a binary array (with subtype) + /// @sa https://json.nlohmann.me/api/basic_json/binary/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json binary(typename binary_t::container_type&& init, typename binary_t::subtype_type subtype) + { + auto res = basic_json(); + res.m_type = value_t::binary; + res.m_value = binary_t(std::move(init), subtype); + return res; + } + + /// @brief explicitly create an array from an initializer list + /// @sa https://json.nlohmann.me/api/basic_json/array/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json array(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::array); + } + + /// @brief explicitly create an object from an initializer list + /// @sa https://json.nlohmann.me/api/basic_json/object/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json object(initializer_list_t init = {}) + { + return basic_json(init, false, value_t::object); + } + + /// @brief construct an array with count copies of given value + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(size_type cnt, const basic_json& val) + : m_type(value_t::array) + { + m_value.array = create(cnt, val); + set_parents(); + assert_invariant(); + } + + /// @brief construct a JSON container given an iterator range + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + template < class InputIT, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type = 0 > + basic_json(InputIT first, InputIT last) + { + JSON_ASSERT(first.m_object != nullptr); + JSON_ASSERT(last.m_object != nullptr); + + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(201, "iterators are not compatible", basic_json())); + } + + // copy type from first iterator + m_type = first.m_object->m_type; + + // check if iterator range is complete for primitive values + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + { + if (JSON_HEDLEY_UNLIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range", *first.m_object)); + } + break; + } + + case value_t::null: + case value_t::object: + case value_t::array: + case value_t::binary: + case value_t::discarded: + default: + break; + } + + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = first.m_object->m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = first.m_object->m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value.number_float = first.m_object->m_value.number_float; + break; + } + + case value_t::boolean: + { + m_value.boolean = first.m_object->m_value.boolean; + break; + } + + case value_t::string: + { + m_value = *first.m_object->m_value.string; + break; + } + + case value_t::object: + { + m_value.object = create(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + m_value.array = create(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + case value_t::binary: + { + m_value = *first.m_object->m_value.binary; + break; + } + + case value_t::null: + case value_t::discarded: + default: + JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()), *first.m_object)); + } + + set_parents(); + assert_invariant(); + } + + + /////////////////////////////////////// + // other constructors and destructor // + /////////////////////////////////////// + + template, + std::is_same>::value, int> = 0 > + basic_json(const JsonRef& ref) : basic_json(ref.moved_or_copied()) {} + + /// @brief copy constructor + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(const basic_json& other) + : m_type(other.m_type) + { + // check of passed value is valid + other.assert_invariant(); + + switch (m_type) + { + case value_t::object: + { + m_value = *other.m_value.object; + break; + } + + case value_t::array: + { + m_value = *other.m_value.array; + break; + } + + case value_t::string: + { + m_value = *other.m_value.string; + break; + } + + case value_t::boolean: + { + m_value = other.m_value.boolean; + break; + } + + case value_t::number_integer: + { + m_value = other.m_value.number_integer; + break; + } + + case value_t::number_unsigned: + { + m_value = other.m_value.number_unsigned; + break; + } + + case value_t::number_float: + { + m_value = other.m_value.number_float; + break; + } + + case value_t::binary: + { + m_value = *other.m_value.binary; + break; + } + + case value_t::null: + case value_t::discarded: + default: + break; + } + + set_parents(); + assert_invariant(); + } + + /// @brief move constructor + /// @sa https://json.nlohmann.me/api/basic_json/basic_json/ + basic_json(basic_json&& other) noexcept + : m_type(std::move(other.m_type)), + m_value(std::move(other.m_value)) + { + // check that passed value is valid + other.assert_invariant(false); + + // invalidate payload + other.m_type = value_t::null; + other.m_value = {}; + + set_parents(); + assert_invariant(); + } + + /// @brief copy assignment + /// @sa https://json.nlohmann.me/api/basic_json/operator=/ + basic_json& operator=(basic_json other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + // check that passed value is valid + other.assert_invariant(); + + using std::swap; + swap(m_type, other.m_type); + swap(m_value, other.m_value); + + set_parents(); + assert_invariant(); + return *this; + } + + /// @brief destructor + /// @sa https://json.nlohmann.me/api/basic_json/~basic_json/ + ~basic_json() noexcept + { + assert_invariant(false); + m_value.destroy(m_type); + } + + /// @} + + public: + /////////////////////// + // object inspection // + /////////////////////// + + /// @name object inspection + /// Functions to inspect the type of a JSON value. + /// @{ + + /// @brief serialization + /// @sa https://json.nlohmann.me/api/basic_json/dump/ + string_t dump(const int indent = -1, + const char indent_char = ' ', + const bool ensure_ascii = false, + const error_handler_t error_handler = error_handler_t::strict) const + { + string_t result; + serializer s(detail::output_adapter(result), indent_char, error_handler); + + if (indent >= 0) + { + s.dump(*this, true, ensure_ascii, static_cast(indent)); + } + else + { + s.dump(*this, false, ensure_ascii, 0); + } + + return result; + } + + /// @brief return the type of the JSON value (explicit) + /// @sa https://json.nlohmann.me/api/basic_json/type/ + constexpr value_t type() const noexcept + { + return m_type; + } + + /// @brief return whether type is primitive + /// @sa https://json.nlohmann.me/api/basic_json/is_primitive/ + constexpr bool is_primitive() const noexcept + { + return is_null() || is_string() || is_boolean() || is_number() || is_binary(); + } + + /// @brief return whether type is structured + /// @sa https://json.nlohmann.me/api/basic_json/is_structured/ + constexpr bool is_structured() const noexcept + { + return is_array() || is_object(); + } + + /// @brief return whether value is null + /// @sa https://json.nlohmann.me/api/basic_json/is_null/ + constexpr bool is_null() const noexcept + { + return m_type == value_t::null; + } + + /// @brief return whether value is a boolean + /// @sa https://json.nlohmann.me/api/basic_json/is_boolean/ + constexpr bool is_boolean() const noexcept + { + return m_type == value_t::boolean; + } + + /// @brief return whether value is a number + /// @sa https://json.nlohmann.me/api/basic_json/is_number/ + constexpr bool is_number() const noexcept + { + return is_number_integer() || is_number_float(); + } + + /// @brief return whether value is an integer number + /// @sa https://json.nlohmann.me/api/basic_json/is_number_integer/ + constexpr bool is_number_integer() const noexcept + { + return m_type == value_t::number_integer || m_type == value_t::number_unsigned; + } + + /// @brief return whether value is an unsigned integer number + /// @sa https://json.nlohmann.me/api/basic_json/is_number_unsigned/ + constexpr bool is_number_unsigned() const noexcept + { + return m_type == value_t::number_unsigned; + } + + /// @brief return whether value is a floating-point number + /// @sa https://json.nlohmann.me/api/basic_json/is_number_float/ + constexpr bool is_number_float() const noexcept + { + return m_type == value_t::number_float; + } + + /// @brief return whether value is an object + /// @sa https://json.nlohmann.me/api/basic_json/is_object/ + constexpr bool is_object() const noexcept + { + return m_type == value_t::object; + } + + /// @brief return whether value is an array + /// @sa https://json.nlohmann.me/api/basic_json/is_array/ + constexpr bool is_array() const noexcept + { + return m_type == value_t::array; + } + + /// @brief return whether value is a string + /// @sa https://json.nlohmann.me/api/basic_json/is_string/ + constexpr bool is_string() const noexcept + { + return m_type == value_t::string; + } + + /// @brief return whether value is a binary array + /// @sa https://json.nlohmann.me/api/basic_json/is_binary/ + constexpr bool is_binary() const noexcept + { + return m_type == value_t::binary; + } + + /// @brief return whether value is discarded + /// @sa https://json.nlohmann.me/api/basic_json/is_discarded/ + constexpr bool is_discarded() const noexcept + { + return m_type == value_t::discarded; + } + + /// @brief return the type of the JSON value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/operator_value_t/ + constexpr operator value_t() const noexcept + { + return m_type; + } + + /// @} + + private: + ////////////////// + // value access // + ////////////////// + + /// get a boolean (explicit) + boolean_t get_impl(boolean_t* /*unused*/) const + { + if (JSON_HEDLEY_LIKELY(is_boolean())) + { + return m_value.boolean; + } + + JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()), *this)); + } + + /// get a pointer to the value (object) + object_t* get_impl_ptr(object_t* /*unused*/) noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (object) + constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept + { + return is_object() ? m_value.object : nullptr; + } + + /// get a pointer to the value (array) + array_t* get_impl_ptr(array_t* /*unused*/) noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (array) + constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept + { + return is_array() ? m_value.array : nullptr; + } + + /// get a pointer to the value (string) + string_t* get_impl_ptr(string_t* /*unused*/) noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (string) + constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept + { + return is_string() ? m_value.string : nullptr; + } + + /// get a pointer to the value (boolean) + boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (boolean) + constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept + { + return is_boolean() ? &m_value.boolean : nullptr; + } + + /// get a pointer to the value (integer number) + number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (integer number) + constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept + { + return is_number_integer() ? &m_value.number_integer : nullptr; + } + + /// get a pointer to the value (unsigned number) + number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (unsigned number) + constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept + { + return is_number_unsigned() ? &m_value.number_unsigned : nullptr; + } + + /// get a pointer to the value (floating-point number) + number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (floating-point number) + constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept + { + return is_number_float() ? &m_value.number_float : nullptr; + } + + /// get a pointer to the value (binary) + binary_t* get_impl_ptr(binary_t* /*unused*/) noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /// get a pointer to the value (binary) + constexpr const binary_t* get_impl_ptr(const binary_t* /*unused*/) const noexcept + { + return is_binary() ? m_value.binary : nullptr; + } + + /*! + @brief helper function to implement get_ref() + + This function helps to implement get_ref() without code duplication for + const and non-const overloads + + @tparam ThisType will be deduced as `basic_json` or `const basic_json` + + @throw type_error.303 if ReferenceType does not match underlying value + type of the current JSON + */ + template + static ReferenceType get_ref_impl(ThisType& obj) + { + // delegate the call to get_ptr<>() + auto* ptr = obj.template get_ptr::type>(); + + if (JSON_HEDLEY_LIKELY(ptr != nullptr)) + { + return *ptr; + } + + JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()), obj)); + } + + public: + /// @name value access + /// Direct access to the stored value of a JSON value. + /// @{ + + /// @brief get a pointer value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ + template::value, int>::type = 0> + auto get_ptr() noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() + return get_impl_ptr(static_cast(nullptr)); + } + + /// @brief get a pointer value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ptr/ + template < typename PointerType, typename std::enable_if < + std::is_pointer::value&& + std::is_const::type>::value, int >::type = 0 > + constexpr auto get_ptr() const noexcept -> decltype(std::declval().get_impl_ptr(std::declval())) + { + // delegate the call to get_impl_ptr<>() const + return get_impl_ptr(static_cast(nullptr)); + } + + private: + /*! + @brief get a value (explicit) + + Explicit type conversion between the JSON value and a compatible value + which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + ValueType ret; + JSONSerializer::from_json(*this, ret); + return ret; + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json, + - @ref json_serializer has a `from_json()` method of the form + `void from_json(const basic_json&, ValueType&)`, and + - @ref json_serializer does not have a `from_json()` method of + the form `ValueType from_json(const basic_json&)` + + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,get__ValueType_const} + + @since version 2.1.0 + */ + template < typename ValueType, + detail::enable_if_t < + detail::is_default_constructible::value&& + detail::has_from_json::value, + int > = 0 > + ValueType get_impl(detail::priority_tag<0> /*unused*/) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), std::declval()))) + { + auto ret = ValueType(); + JSONSerializer::from_json(*this, ret); + return ret; + } + + /*! + @brief get a value (explicit); special case + + Explicit type conversion between the JSON value and a compatible value + which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) + and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). + The value is converted by calling the @ref json_serializer + `from_json()` method. + + The function is equivalent to executing + @code {.cpp} + return JSONSerializer::from_json(*this); + @endcode + + This overloads is chosen if: + - @a ValueType is not @ref basic_json and + - @ref json_serializer has a `from_json()` method of the form + `ValueType from_json(const basic_json&)` + + @note If @ref json_serializer has both overloads of + `from_json()`, this one is chosen. + + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @a ValueType + + @throw what @ref json_serializer `from_json()` method throws + + @since version 2.1.0 + */ + template < typename ValueType, + detail::enable_if_t < + detail::has_non_default_from_json::value, + int > = 0 > + ValueType get_impl(detail::priority_tag<1> /*unused*/) const noexcept(noexcept( + JSONSerializer::from_json(std::declval()))) + { + return JSONSerializer::from_json(*this); + } + + /*! + @brief get special-case overload + + This overloads converts the current @ref basic_json in a different + @ref basic_json type + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this, converted into @a BasicJsonType + + @complexity Depending on the implementation of the called `from_json()` + method. + + @since version 3.2.0 + */ + template < typename BasicJsonType, + detail::enable_if_t < + detail::is_basic_json::value, + int > = 0 > + BasicJsonType get_impl(detail::priority_tag<2> /*unused*/) const + { + return *this; + } + + /*! + @brief get special-case overload + + This overloads avoids a lot of template boilerplate, it can be seen as the + identity method + + @tparam BasicJsonType == @ref basic_json + + @return a copy of *this + + @complexity Constant. + + @since version 2.1.0 + */ + template::value, + int> = 0> + basic_json get_impl(detail::priority_tag<3> /*unused*/) const + { + return *this; + } + + /*! + @brief get a pointer value (explicit) + @copydoc get() + */ + template::value, + int> = 0> + constexpr auto get_impl(detail::priority_tag<4> /*unused*/) const noexcept + -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + public: + /*! + @brief get a (pointer) value (explicit) + + Performs explicit type conversion between the JSON value and a compatible value if required. + + - If the requested type is a pointer to the internally stored JSON value that pointer is returned. + No copies are made. + + - If the requested type is the current @ref basic_json, or a different @ref basic_json convertible + from the current @ref basic_json. + + - Otherwise the value is converted by calling the @ref json_serializer `from_json()` + method. + + @tparam ValueTypeCV the provided value type + @tparam ValueType the returned value type + + @return copy of the JSON value, converted to @tparam ValueType if necessary + + @throw what @ref json_serializer `from_json()` method throws if conversion is required + + @since version 2.1.0 + */ + template < typename ValueTypeCV, typename ValueType = detail::uncvref_t> +#if defined(JSON_HAS_CPP_14) + constexpr +#endif + auto get() const noexcept( + noexcept(std::declval().template get_impl(detail::priority_tag<4> {}))) + -> decltype(std::declval().template get_impl(detail::priority_tag<4> {})) + { + // we cannot static_assert on ValueTypeCV being non-const, because + // there is support for get(), which is why we + // still need the uncvref + static_assert(!std::is_reference::value, + "get() cannot be used with reference types, you might want to use get_ref()"); + return get_impl(detail::priority_tag<4> {}); + } + + /*! + @brief get a pointer value (explicit) + + Explicit pointer access to the internally stored JSON value. No copies are + made. + + @warning The pointer becomes invalid if the underlying JSON object + changes. + + @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref + object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, + @ref number_unsigned_t, or @ref number_float_t. + + @return pointer to the internally stored JSON value if the requested + pointer type @a PointerType fits to the JSON value; `nullptr` otherwise + + @complexity Constant. + + @liveexample{The example below shows how pointers to internal values of a + JSON value can be requested. Note that no type conversions are made and a + `nullptr` is returned if the value and the requested pointer type does not + match.,get__PointerType} + + @sa see @ref get_ptr() for explicit pointer-member access + + @since version 1.0.0 + */ + template::value, int>::type = 0> + auto get() noexcept -> decltype(std::declval().template get_ptr()) + { + // delegate the call to get_ptr + return get_ptr(); + } + + /// @brief get a value (explicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_to/ + template < typename ValueType, + detail::enable_if_t < + !detail::is_basic_json::value&& + detail::has_from_json::value, + int > = 0 > + ValueType & get_to(ValueType& v) const noexcept(noexcept( + JSONSerializer::from_json(std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + // specialization to allow calling get_to with a basic_json value + // see https://github.com/nlohmann/json/issues/2175 + template::value, + int> = 0> + ValueType & get_to(ValueType& v) const + { + v = *this; + return v; + } + + template < + typename T, std::size_t N, + typename Array = T (&)[N], // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + detail::enable_if_t < + detail::has_from_json::value, int > = 0 > + Array get_to(T (&v)[N]) const // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) + noexcept(noexcept(JSONSerializer::from_json( + std::declval(), v))) + { + JSONSerializer::from_json(*this, v); + return v; + } + + /// @brief get a reference value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ + template::value, int>::type = 0> + ReferenceType get_ref() + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /// @brief get a reference value (implicit) + /// @sa https://json.nlohmann.me/api/basic_json/get_ref/ + template < typename ReferenceType, typename std::enable_if < + std::is_reference::value&& + std::is_const::type>::value, int >::type = 0 > + ReferenceType get_ref() const + { + // delegate call to get_ref_impl + return get_ref_impl(*this); + } + + /*! + @brief get a value (implicit) + + Implicit type conversion between the JSON value and a compatible value. + The call is realized by calling @ref get() const. + + @tparam ValueType non-pointer type compatible to the JSON value, for + instance `int` for JSON integer numbers, `bool` for JSON booleans, or + `std::vector` types for JSON arrays. The character type of @ref string_t + as well as an initializer list of this type is excluded to avoid + ambiguities as these types implicitly convert to `std::string`. + + @return copy of the JSON value, converted to type @a ValueType + + @throw type_error.302 in case passed type @a ValueType is incompatible + to the JSON value type (e.g., the JSON value is of type boolean, but a + string is requested); see example below + + @complexity Linear in the size of the JSON value. + + @liveexample{The example below shows several conversions from JSON values + to other types. There a few things to note: (1) Floating-point numbers can + be converted to integers\, (2) A JSON array can be converted to a standard + `std::vector`\, (3) A JSON object can be converted to C++ + associative containers such as `std::unordered_map`.,operator__ValueType} + + @since version 1.0.0 + */ + template < typename ValueType, typename std::enable_if < + detail::conjunction < + detail::negation>, + detail::negation>>, + detail::negation>, + detail::negation>, + detail::negation>>, + +#if defined(JSON_HAS_CPP_17) && (defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1910 && _MSC_VER <= 1914)) + detail::negation>, +#endif + detail::is_detected_lazy + >::value, int >::type = 0 > + JSON_EXPLICIT operator ValueType() const + { + // delegate the call to get<>() const + return get(); + } + + /// @brief get a binary value + /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ + binary_t& get_binary() + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); + } + + return *get_ptr(); + } + + /// @brief get a binary value + /// @sa https://json.nlohmann.me/api/basic_json/get_binary/ + const binary_t& get_binary() const + { + if (!is_binary()) + { + JSON_THROW(type_error::create(302, "type must be binary, but is " + std::string(type_name()), *this)); + } + + return *get_ptr(); + } + + /// @} + + + //////////////////// + // element access // + //////////////////// + + /// @name element access + /// Access to the JSON value. + /// @{ + + /// @brief access specified array element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + reference at(size_type idx) + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return set_parent(m_value.array->at(idx)); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified array element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + const_reference at(size_type idx) const + { + // at only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + JSON_TRY + { + return m_value.array->at(idx); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified object element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + reference at(const typename object_t::key_type& key) + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return set_parent(m_value.object->at(key)); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified object element with bounds checking + /// @sa https://json.nlohmann.me/api/basic_json/at/ + const_reference at(const typename object_t::key_type& key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_TRY + { + return m_value.object->at(key); + } + JSON_CATCH (std::out_of_range&) + { + // create better exception explanation + JSON_THROW(out_of_range::create(403, "key '" + key + "' not found", *this)); + } + } + else + { + JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()), *this)); + } + } + + /// @brief access specified array element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + reference operator[](size_type idx) + { + // implicitly convert null value to an empty array + if (is_null()) + { + m_type = value_t::array; + m_value.array = create(); + assert_invariant(); + } + + // operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // fill up array with null values if given idx is outside range + if (idx >= m_value.array->size()) + { +#if JSON_DIAGNOSTICS + // remember array size & capacity before resizing + const auto old_size = m_value.array->size(); + const auto old_capacity = m_value.array->capacity(); +#endif + m_value.array->resize(idx + 1); + +#if JSON_DIAGNOSTICS + if (JSON_HEDLEY_UNLIKELY(m_value.array->capacity() != old_capacity)) + { + // capacity has changed: update all parents + set_parents(); + } + else + { + // set parent for values added above + set_parents(begin() + static_cast(old_size), static_cast(idx + 1 - old_size)); + } +#endif + assert_invariant(); + } + + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified array element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + const_reference operator[](size_type idx) const + { + // const operator[] only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + return m_value.array->operator[](idx); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + reference operator[](const typename object_t::key_type& key) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + // operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return set_parent(m_value.object->operator[](key)); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + const_reference operator[](const typename object_t::key_type& key) const + { + // const operator[] only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + template + JSON_HEDLEY_NON_NULL(2) + reference operator[](T* key) + { + // implicitly convert null to object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return set_parent(m_value.object->operator[](key)); + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + template + JSON_HEDLEY_NON_NULL(2) + const_reference operator[](T* key) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + JSON_ASSERT(m_value.object->find(key) != m_value.object->end()); + return m_value.object->find(key)->second; + } + + JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + /// using std::is_convertible in a std::enable_if will fail when using explicit conversions + template < class ValueType, typename std::enable_if < + detail::is_getable::value + && !std::is_same::value, int >::type = 0 > + ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if key is found, return value and given default value otherwise + const auto it = find(key); + if (it != end()) + { + return it->template get(); + } + + return default_value; + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + /// overload for a default value of type const char* + string_t value(const typename object_t::key_type& key, const char* default_value) const + { + return value(key, string_t(default_value)); + } + + /// @brief access specified object element via JSON Pointer with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + template::value, int>::type = 0> + ValueType value(const json_pointer& ptr, const ValueType& default_value) const + { + // at only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + // if pointer resolves a value, return it or use default value + JSON_TRY + { + return ptr.get_checked(this).template get(); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + return default_value; + } + } + + JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()), *this)); + } + + /// @brief access specified object element via JSON Pointer with default value + /// @sa https://json.nlohmann.me/api/basic_json/value/ + /// overload for a default value of type const char* + JSON_HEDLEY_NON_NULL(3) + string_t value(const json_pointer& ptr, const char* default_value) const + { + return value(ptr, string_t(default_value)); + } + + /// @brief access the first element + /// @sa https://json.nlohmann.me/api/basic_json/front/ + reference front() + { + return *begin(); + } + + /// @brief access the first element + /// @sa https://json.nlohmann.me/api/basic_json/front/ + const_reference front() const + { + return *cbegin(); + } + + /// @brief access the last element + /// @sa https://json.nlohmann.me/api/basic_json/back/ + reference back() + { + auto tmp = end(); + --tmp; + return *tmp; + } + + /// @brief access the last element + /// @sa https://json.nlohmann.me/api/basic_json/back/ + const_reference back() const + { + auto tmp = cend(); + --tmp; + return *tmp; + } + + /// @brief remove element given an iterator + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType pos) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != pos.m_object)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_UNLIKELY(!pos.m_it.primitive_iterator.is_begin())) + { + JSON_THROW(invalid_iterator::create(205, "iterator out of range", *this)); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); + break; + } + + case value_t::null: + case value_t::discarded: + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + return result; + } + + /// @brief remove elements given an iterator range + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + template < class IteratorType, typename std::enable_if < + std::is_same::value || + std::is_same::value, int >::type + = 0 > + IteratorType erase(IteratorType first, IteratorType last) + { + // make sure iterator fits the current value + if (JSON_HEDLEY_UNLIKELY(this != first.m_object || this != last.m_object)) + { + JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value", *this)); + } + + IteratorType result = end(); + + switch (m_type) + { + case value_t::boolean: + case value_t::number_float: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::string: + case value_t::binary: + { + if (JSON_HEDLEY_LIKELY(!first.m_it.primitive_iterator.is_begin() + || !last.m_it.primitive_iterator.is_end())) + { + JSON_THROW(invalid_iterator::create(204, "iterators out of range", *this)); + } + + if (is_string()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.string); + std::allocator_traits::deallocate(alloc, m_value.string, 1); + m_value.string = nullptr; + } + else if (is_binary()) + { + AllocatorType alloc; + std::allocator_traits::destroy(alloc, m_value.binary); + std::allocator_traits::deallocate(alloc, m_value.binary, 1); + m_value.binary = nullptr; + } + + m_type = value_t::null; + assert_invariant(); + break; + } + + case value_t::object: + { + result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, + last.m_it.object_iterator); + break; + } + + case value_t::array: + { + result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, + last.m_it.array_iterator); + break; + } + + case value_t::null: + case value_t::discarded: + default: + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + return result; + } + + /// @brief remove element from a JSON object given a key + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + size_type erase(const typename object_t::key_type& key) + { + // this erase only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + return m_value.object->erase(key); + } + + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + + /// @brief remove element from a JSON array given an index + /// @sa https://json.nlohmann.me/api/basic_json/erase/ + void erase(const size_type idx) + { + // this erase only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + if (JSON_HEDLEY_UNLIKELY(idx >= size())) + { + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", *this)); + } + + m_value.array->erase(m_value.array->begin() + static_cast(idx)); + } + else + { + JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()), *this)); + } + } + + /// @} + + + //////////// + // lookup // + //////////// + + /// @name lookup + /// @{ + + /// @brief find an element in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/find/ + template + iterator find(KeyT&& key) + { + auto result = end(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /// @brief find an element in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/find/ + template + const_iterator find(KeyT&& key) const + { + auto result = cend(); + + if (is_object()) + { + result.m_it.object_iterator = m_value.object->find(std::forward(key)); + } + + return result; + } + + /// @brief returns the number of occurrences of a key in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/count/ + template + size_type count(KeyT&& key) const + { + // return 0 for all nonobject types + return is_object() ? m_value.object->count(std::forward(key)) : 0; + } + + /// @brief check the existence of an element in a JSON object + /// @sa https://json.nlohmann.me/api/basic_json/contains/ + template < typename KeyT, typename std::enable_if < + !std::is_same::type, json_pointer>::value, int >::type = 0 > + bool contains(KeyT && key) const + { + return is_object() && m_value.object->find(std::forward(key)) != m_value.object->end(); + } + + /// @brief check the existence of an element in a JSON object given a JSON pointer + /// @sa https://json.nlohmann.me/api/basic_json/contains/ + bool contains(const json_pointer& ptr) const + { + return ptr.contains(this); + } + + /// @} + + + /////////////// + // iterators // + /////////////// + + /// @name iterators + /// @{ + + /// @brief returns an iterator to the first element + /// @sa https://json.nlohmann.me/api/basic_json/begin/ + iterator begin() noexcept + { + iterator result(this); + result.set_begin(); + return result; + } + + /// @brief returns an iterator to the first element + /// @sa https://json.nlohmann.me/api/basic_json/begin/ + const_iterator begin() const noexcept + { + return cbegin(); + } + + /// @brief returns a const iterator to the first element + /// @sa https://json.nlohmann.me/api/basic_json/cbegin/ + const_iterator cbegin() const noexcept + { + const_iterator result(this); + result.set_begin(); + return result; + } + + /// @brief returns an iterator to one past the last element + /// @sa https://json.nlohmann.me/api/basic_json/end/ + iterator end() noexcept + { + iterator result(this); + result.set_end(); + return result; + } + + /// @brief returns an iterator to one past the last element + /// @sa https://json.nlohmann.me/api/basic_json/end/ + const_iterator end() const noexcept + { + return cend(); + } + + /// @brief returns an iterator to one past the last element + /// @sa https://json.nlohmann.me/api/basic_json/cend/ + const_iterator cend() const noexcept + { + const_iterator result(this); + result.set_end(); + return result; + } + + /// @brief returns an iterator to the reverse-beginning + /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ + reverse_iterator rbegin() noexcept + { + return reverse_iterator(end()); + } + + /// @brief returns an iterator to the reverse-beginning + /// @sa https://json.nlohmann.me/api/basic_json/rbegin/ + const_reverse_iterator rbegin() const noexcept + { + return crbegin(); + } + + /// @brief returns an iterator to the reverse-end + /// @sa https://json.nlohmann.me/api/basic_json/rend/ + reverse_iterator rend() noexcept + { + return reverse_iterator(begin()); + } + + /// @brief returns an iterator to the reverse-end + /// @sa https://json.nlohmann.me/api/basic_json/rend/ + const_reverse_iterator rend() const noexcept + { + return crend(); + } + + /// @brief returns a const reverse iterator to the last element + /// @sa https://json.nlohmann.me/api/basic_json/crbegin/ + const_reverse_iterator crbegin() const noexcept + { + return const_reverse_iterator(cend()); + } + + /// @brief returns a const reverse iterator to one before the first + /// @sa https://json.nlohmann.me/api/basic_json/crend/ + const_reverse_iterator crend() const noexcept + { + return const_reverse_iterator(cbegin()); + } + + public: + /// @brief wrapper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + /// @deprecated This function is deprecated since 3.1.0 and will be removed in + /// version 4.0.0 of the library. Please use @ref items() instead; + /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(reference ref) noexcept + { + return ref.items(); + } + + /// @brief wrapper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + /// @deprecated This function is deprecated since 3.1.0 and will be removed in + /// version 4.0.0 of the library. Please use @ref items() instead; + /// that is, replace `json::iterator_wrapper(j)` with `j.items()`. + JSON_HEDLEY_DEPRECATED_FOR(3.1.0, items()) + static iteration_proxy iterator_wrapper(const_reference ref) noexcept + { + return ref.items(); + } + + /// @brief helper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + iteration_proxy items() noexcept + { + return iteration_proxy(*this); + } + + /// @brief helper to access iterator member functions in range-based for + /// @sa https://json.nlohmann.me/api/basic_json/items/ + iteration_proxy items() const noexcept + { + return iteration_proxy(*this); + } + + /// @} + + + ////////////// + // capacity // + ////////////// + + /// @name capacity + /// @{ + + /// @brief checks whether the container is empty. + /// @sa https://json.nlohmann.me/api/basic_json/empty/ + bool empty() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return true; + } + + case value_t::array: + { + // delegate call to array_t::empty() + return m_value.array->empty(); + } + + case value_t::object: + { + // delegate call to object_t::empty() + return m_value.object->empty(); + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // all other types are nonempty + return false; + } + } + } + + /// @brief returns the number of elements + /// @sa https://json.nlohmann.me/api/basic_json/size/ + size_type size() const noexcept + { + switch (m_type) + { + case value_t::null: + { + // null values are empty + return 0; + } + + case value_t::array: + { + // delegate call to array_t::size() + return m_value.array->size(); + } + + case value_t::object: + { + // delegate call to object_t::size() + return m_value.object->size(); + } + + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // all other types have size 1 + return 1; + } + } + } + + /// @brief returns the maximum possible number of elements + /// @sa https://json.nlohmann.me/api/basic_json/max_size/ + size_type max_size() const noexcept + { + switch (m_type) + { + case value_t::array: + { + // delegate call to array_t::max_size() + return m_value.array->max_size(); + } + + case value_t::object: + { + // delegate call to object_t::max_size() + return m_value.object->max_size(); + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // all other types have max_size() == size() + return size(); + } + } + } + + /// @} + + + /////////////// + // modifiers // + /////////////// + + /// @name modifiers + /// @{ + + /// @brief clears the contents + /// @sa https://json.nlohmann.me/api/basic_json/clear/ + void clear() noexcept + { + switch (m_type) + { + case value_t::number_integer: + { + m_value.number_integer = 0; + break; + } + + case value_t::number_unsigned: + { + m_value.number_unsigned = 0; + break; + } + + case value_t::number_float: + { + m_value.number_float = 0.0; + break; + } + + case value_t::boolean: + { + m_value.boolean = false; + break; + } + + case value_t::string: + { + m_value.string->clear(); + break; + } + + case value_t::binary: + { + m_value.binary->clear(); + break; + } + + case value_t::array: + { + m_value.array->clear(); + break; + } + + case value_t::object: + { + m_value.object->clear(); + break; + } + + case value_t::null: + case value_t::discarded: + default: + break; + } + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(basic_json&& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (move semantics) + const auto old_capacity = m_value.array->capacity(); + m_value.array->push_back(std::move(val)); + set_parent(m_value.array->back(), old_capacity); + // if val is moved from, basic_json move constructor marks it null, so we do not call the destructor + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(basic_json&& val) + { + push_back(std::move(val)); + return *this; + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(const basic_json& val) + { + // push_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array + const auto old_capacity = m_value.array->capacity(); + m_value.array->push_back(val); + set_parent(m_value.array->back(), old_capacity); + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(const basic_json& val) + { + push_back(val); + return *this; + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(const typename object_t::value_type& val) + { + // push_back only works for null objects or objects + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to object + auto res = m_value.object->insert(val); + set_parent(res.first->second); + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(const typename object_t::value_type& val) + { + push_back(val); + return *this; + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/push_back/ + void push_back(initializer_list_t init) + { + if (is_object() && init.size() == 2 && (*init.begin())->is_string()) + { + basic_json&& key = init.begin()->moved_or_copied(); + push_back(typename object_t::value_type( + std::move(key.get_ref()), (init.begin() + 1)->moved_or_copied())); + } + else + { + push_back(basic_json(init)); + } + } + + /// @brief add an object to an object + /// @sa https://json.nlohmann.me/api/basic_json/operator+=/ + reference operator+=(initializer_list_t init) + { + push_back(init); + return *this; + } + + /// @brief add an object to an array + /// @sa https://json.nlohmann.me/api/basic_json/emplace_back/ + template + reference emplace_back(Args&& ... args) + { + // emplace_back only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_array()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()), *this)); + } + + // transform null object into an array + if (is_null()) + { + m_type = value_t::array; + m_value = value_t::array; + assert_invariant(); + } + + // add element to array (perfect forwarding) + const auto old_capacity = m_value.array->capacity(); + m_value.array->emplace_back(std::forward(args)...); + return set_parent(m_value.array->back(), old_capacity); + } + + /// @brief add an object to an object if key does not exist + /// @sa https://json.nlohmann.me/api/basic_json/emplace/ + template + std::pair emplace(Args&& ... args) + { + // emplace only works for null objects or arrays + if (JSON_HEDLEY_UNLIKELY(!(is_null() || is_object()))) + { + JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()), *this)); + } + + // transform null object into an object + if (is_null()) + { + m_type = value_t::object; + m_value = value_t::object; + assert_invariant(); + } + + // add element to array (perfect forwarding) + auto res = m_value.object->emplace(std::forward(args)...); + set_parent(res.first->second); + + // create result iterator and set iterator to the result of emplace + auto it = begin(); + it.m_it.object_iterator = res.first; + + // return pair of iterator and boolean + return {it, res.second}; + } + + /// Helper for insertion of an iterator + /// @note: This uses std::distance to support GCC 4.8, + /// see https://github.com/nlohmann/json/pull/1257 + template + iterator insert_iterator(const_iterator pos, Args&& ... args) + { + iterator result(this); + JSON_ASSERT(m_value.array != nullptr); + + auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); + m_value.array->insert(pos.m_it.array_iterator, std::forward(args)...); + result.m_it.array_iterator = m_value.array->begin() + insert_pos; + + // This could have been written as: + // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); + // but the return value of insert is missing in GCC 4.8, so it is written this way instead. + + set_parents(); + return result; + } + + /// @brief inserts element into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, val); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + /// @brief inserts element into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, basic_json&& val) + { + return insert(pos, val); + } + + /// @brief inserts copies of element into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, size_type cnt, const basic_json& val) + { + // insert only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, cnt, val); + } + + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + /// @brief inserts range of elements into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, const_iterator first, const_iterator last) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + if (JSON_HEDLEY_UNLIKELY(first.m_object == this)) + { + JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); + } + + /// @brief inserts elements from initializer list into array + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + iterator insert(const_iterator pos, initializer_list_t ilist) + { + // insert only works for arrays + if (JSON_HEDLEY_UNLIKELY(!is_array())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if iterator pos fits to this JSON value + if (JSON_HEDLEY_UNLIKELY(pos.m_object != this)) + { + JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value", *this)); + } + + // insert to array and return iterator + return insert_iterator(pos, ilist.begin(), ilist.end()); + } + + /// @brief inserts range of elements into object + /// @sa https://json.nlohmann.me/api/basic_json/insert/ + void insert(const_iterator first, const_iterator last) + { + // insert only works for objects + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()), *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) + { + JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects", *this)); + } + + m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); + } + + /// @brief updates a JSON object from another object, overwriting existing keys + /// @sa https://json.nlohmann.me/api/basic_json/update/ + void update(const_reference j, bool merge_objects = false) + { + update(j.begin(), j.end(), merge_objects); + } + + /// @brief updates a JSON object from another object, overwriting existing keys + /// @sa https://json.nlohmann.me/api/basic_json/update/ + void update(const_iterator first, const_iterator last, bool merge_objects = false) + { + // implicitly convert null value to an empty object + if (is_null()) + { + m_type = value_t::object; + m_value.object = create(); + assert_invariant(); + } + + if (JSON_HEDLEY_UNLIKELY(!is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()), *this)); + } + + // check if range iterators belong to the same JSON object + if (JSON_HEDLEY_UNLIKELY(first.m_object != last.m_object)) + { + JSON_THROW(invalid_iterator::create(210, "iterators do not fit", *this)); + } + + // passed iterators must belong to objects + if (JSON_HEDLEY_UNLIKELY(!first.m_object->is_object())) + { + JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(first.m_object->type_name()), *first.m_object)); + } + + for (auto it = first; it != last; ++it) + { + if (merge_objects && it.value().is_object()) + { + auto it2 = m_value.object->find(it.key()); + if (it2 != m_value.object->end()) + { + it2->second.update(it.value(), true); + continue; + } + } + m_value.object->operator[](it.key()) = it.value(); +#if JSON_DIAGNOSTICS + m_value.object->operator[](it.key()).m_parent = this; +#endif + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(reference other) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + std::swap(m_type, other.m_type); + std::swap(m_value, other.m_value); + + set_parents(); + other.set_parents(); + assert_invariant(); + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + friend void swap(reference left, reference right) noexcept ( + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value&& + std::is_nothrow_move_constructible::value&& + std::is_nothrow_move_assignable::value + ) + { + left.swap(right); + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(array_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for arrays + if (JSON_HEDLEY_LIKELY(is_array())) + { + std::swap(*(m_value.array), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(object_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for objects + if (JSON_HEDLEY_LIKELY(is_object())) + { + std::swap(*(m_value.object), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(string_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_string())) + { + std::swap(*(m_value.string), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(binary_t& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @brief exchanges the values + /// @sa https://json.nlohmann.me/api/basic_json/swap/ + void swap(typename binary_t::container_type& other) // NOLINT(bugprone-exception-escape) + { + // swap only works for strings + if (JSON_HEDLEY_LIKELY(is_binary())) + { + std::swap(*(m_value.binary), other); + } + else + { + JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()), *this)); + } + } + + /// @} + + public: + ////////////////////////////////////////// + // lexicographical comparison operators // + ////////////////////////////////////////// + + /// @name lexicographical comparison operators + /// @{ + + /// @brief comparison: equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ + friend bool operator==(const_reference lhs, const_reference rhs) noexcept + { +#ifdef __GNUC__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wfloat-equal" +#endif + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + return *lhs.m_value.array == *rhs.m_value.array; + + case value_t::object: + return *lhs.m_value.object == *rhs.m_value.object; + + case value_t::null: + return true; + + case value_t::string: + return *lhs.m_value.string == *rhs.m_value.string; + + case value_t::boolean: + return lhs.m_value.boolean == rhs.m_value.boolean; + + case value_t::number_integer: + return lhs.m_value.number_integer == rhs.m_value.number_integer; + + case value_t::number_unsigned: + return lhs.m_value.number_unsigned == rhs.m_value.number_unsigned; + + case value_t::number_float: + return lhs.m_value.number_float == rhs.m_value.number_float; + + case value_t::binary: + return *lhs.m_value.binary == *rhs.m_value.binary; + + case value_t::discarded: + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float == static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) == rhs.m_value.number_integer; + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer == static_cast(rhs.m_value.number_unsigned); + } + + return false; +#ifdef __GNUC__ +#pragma GCC diagnostic pop +#endif + } + + /// @brief comparison: equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ + template::value, int>::type = 0> + friend bool operator==(const_reference lhs, ScalarType rhs) noexcept + { + return lhs == basic_json(rhs); + } + + /// @brief comparison: equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_eq/ + template::value, int>::type = 0> + friend bool operator==(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) == rhs; + } + + /// @brief comparison: not equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ + friend bool operator!=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs == rhs); + } + + /// @brief comparison: not equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ + template::value, int>::type = 0> + friend bool operator!=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs != basic_json(rhs); + } + + /// @brief comparison: not equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ne/ + template::value, int>::type = 0> + friend bool operator!=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) != rhs; + } + + /// @brief comparison: less than + /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ + friend bool operator<(const_reference lhs, const_reference rhs) noexcept + { + const auto lhs_type = lhs.type(); + const auto rhs_type = rhs.type(); + + if (lhs_type == rhs_type) + { + switch (lhs_type) + { + case value_t::array: + // note parentheses are necessary, see + // https://github.com/nlohmann/json/issues/1530 + return (*lhs.m_value.array) < (*rhs.m_value.array); + + case value_t::object: + return (*lhs.m_value.object) < (*rhs.m_value.object); + + case value_t::null: + return false; + + case value_t::string: + return (*lhs.m_value.string) < (*rhs.m_value.string); + + case value_t::boolean: + return (lhs.m_value.boolean) < (rhs.m_value.boolean); + + case value_t::number_integer: + return (lhs.m_value.number_integer) < (rhs.m_value.number_integer); + + case value_t::number_unsigned: + return (lhs.m_value.number_unsigned) < (rhs.m_value.number_unsigned); + + case value_t::number_float: + return (lhs.m_value.number_float) < (rhs.m_value.number_float); + + case value_t::binary: + return (*lhs.m_value.binary) < (*rhs.m_value.binary); + + case value_t::discarded: + default: + return false; + } + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_integer) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_integer) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_integer); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_float) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_float; + } + else if (lhs_type == value_t::number_float && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_float < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_integer && rhs_type == value_t::number_unsigned) + { + return lhs.m_value.number_integer < static_cast(rhs.m_value.number_unsigned); + } + else if (lhs_type == value_t::number_unsigned && rhs_type == value_t::number_integer) + { + return static_cast(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; + } + + // We only reach this line if we cannot compare values. In that case, + // we compare types. Note we have to call the operator explicitly, + // because MSVC has problems otherwise. + return operator<(lhs_type, rhs_type); + } + + /// @brief comparison: less than + /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ + template::value, int>::type = 0> + friend bool operator<(const_reference lhs, ScalarType rhs) noexcept + { + return lhs < basic_json(rhs); + } + + /// @brief comparison: less than + /// @sa https://json.nlohmann.me/api/basic_json/operator_lt/ + template::value, int>::type = 0> + friend bool operator<(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) < rhs; + } + + /// @brief comparison: less than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ + friend bool operator<=(const_reference lhs, const_reference rhs) noexcept + { + return !(rhs < lhs); + } + + /// @brief comparison: less than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ + template::value, int>::type = 0> + friend bool operator<=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs <= basic_json(rhs); + } + + /// @brief comparison: less than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_le/ + template::value, int>::type = 0> + friend bool operator<=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) <= rhs; + } + + /// @brief comparison: greater than + /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ + friend bool operator>(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs <= rhs); + } + + /// @brief comparison: greater than + /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ + template::value, int>::type = 0> + friend bool operator>(const_reference lhs, ScalarType rhs) noexcept + { + return lhs > basic_json(rhs); + } + + /// @brief comparison: greater than + /// @sa https://json.nlohmann.me/api/basic_json/operator_gt/ + template::value, int>::type = 0> + friend bool operator>(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) > rhs; + } + + /// @brief comparison: greater than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ + friend bool operator>=(const_reference lhs, const_reference rhs) noexcept + { + return !(lhs < rhs); + } + + /// @brief comparison: greater than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ + template::value, int>::type = 0> + friend bool operator>=(const_reference lhs, ScalarType rhs) noexcept + { + return lhs >= basic_json(rhs); + } + + /// @brief comparison: greater than or equal + /// @sa https://json.nlohmann.me/api/basic_json/operator_ge/ + template::value, int>::type = 0> + friend bool operator>=(ScalarType lhs, const_reference rhs) noexcept + { + return basic_json(lhs) >= rhs; + } + + /// @} + + /////////////////// + // serialization // + /////////////////// + + /// @name serialization + /// @{ +#ifndef JSON_NO_IO + /// @brief serialize to stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ + friend std::ostream& operator<<(std::ostream& o, const basic_json& j) + { + // read width member and use it as indentation parameter if nonzero + const bool pretty_print = o.width() > 0; + const auto indentation = pretty_print ? o.width() : 0; + + // reset width to 0 for subsequent calls to this stream + o.width(0); + + // do the actual serialization + serializer s(detail::output_adapter(o), o.fill()); + s.dump(j, pretty_print, false, static_cast(indentation)); + return o; + } + + /// @brief serialize to stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ + /// @deprecated This function is deprecated since 3.0.0 and will be removed in + /// version 4.0.0 of the library. Please use + /// operator<<(std::ostream&, const basic_json&) instead; that is, + /// replace calls like `j >> o;` with `o << j;`. + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator<<(std::ostream&, const basic_json&)) + friend std::ostream& operator>>(const basic_json& j, std::ostream& o) + { + return o << j; + } +#endif // JSON_NO_IO + /// @} + + + ///////////////////// + // deserialization // + ///////////////////// + + /// @name deserialization + /// @{ + + /// @brief deserialize from a compatible input + /// @sa https://json.nlohmann.me/api/basic_json/parse/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(InputType&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::forward(i)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /// @brief deserialize from a pair of character iterators + /// @sa https://json.nlohmann.me/api/basic_json/parse/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json parse(IteratorType first, + IteratorType last, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(detail::input_adapter(std::move(first), std::move(last)), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, parse(ptr, ptr + len)) + static basic_json parse(detail::span_input_adapter&& i, + const parser_callback_t cb = nullptr, + const bool allow_exceptions = true, + const bool ignore_comments = false) + { + basic_json result; + parser(i.get(), cb, allow_exceptions, ignore_comments).parse(true, result); + return result; + } + + /// @brief check if the input is valid JSON + /// @sa https://json.nlohmann.me/api/basic_json/accept/ + template + static bool accept(InputType&& i, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::forward(i)), nullptr, false, ignore_comments).accept(true); + } + + /// @brief check if the input is valid JSON + /// @sa https://json.nlohmann.me/api/basic_json/accept/ + template + static bool accept(IteratorType first, IteratorType last, + const bool ignore_comments = false) + { + return parser(detail::input_adapter(std::move(first), std::move(last)), nullptr, false, ignore_comments).accept(true); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, accept(ptr, ptr + len)) + static bool accept(detail::span_input_adapter&& i, + const bool ignore_comments = false) + { + return parser(i.get(), nullptr, false, ignore_comments).accept(true); + } + + /// @brief generate SAX events + /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ + template + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(InputType&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::forward(i)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + /// @brief generate SAX events + /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ + template + JSON_HEDLEY_NON_NULL(3) + static bool sax_parse(IteratorType first, IteratorType last, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = detail::input_adapter(std::move(first), std::move(last)); + return format == input_format_t::json + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } + + /// @brief generate SAX events + /// @sa https://json.nlohmann.me/api/basic_json/sax_parse/ + /// @deprecated This function is deprecated since 3.8.0 and will be removed in + /// version 4.0.0 of the library. Please use + /// sax_parse(ptr, ptr + len) instead. + template + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, sax_parse(ptr, ptr + len, ...)) + JSON_HEDLEY_NON_NULL(2) + static bool sax_parse(detail::span_input_adapter&& i, SAX* sax, + input_format_t format = input_format_t::json, + const bool strict = true, + const bool ignore_comments = false) + { + auto ia = i.get(); + return format == input_format_t::json + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + ? parser(std::move(ia), nullptr, true, ignore_comments).sax_parse(sax, strict) + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + : detail::binary_reader(std::move(ia)).sax_parse(format, sax, strict); + } +#ifndef JSON_NO_IO + /// @brief deserialize from stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ + /// @deprecated This stream operator is deprecated since 3.0.0 and will be removed in + /// version 4.0.0 of the library. Please use + /// operator>>(std::istream&, basic_json&) instead; that is, + /// replace calls like `j << i;` with `i >> j;`. + JSON_HEDLEY_DEPRECATED_FOR(3.0.0, operator>>(std::istream&, basic_json&)) + friend std::istream& operator<<(basic_json& j, std::istream& i) + { + return operator>>(i, j); + } + + /// @brief deserialize from stream + /// @sa https://json.nlohmann.me/api/basic_json/operator_gtgt/ + friend std::istream& operator>>(std::istream& i, basic_json& j) + { + parser(detail::input_adapter(i)).parse(false, j); + return i; + } +#endif // JSON_NO_IO + /// @} + + /////////////////////////// + // convenience functions // + /////////////////////////// + + /// @brief return the type as string + /// @sa https://json.nlohmann.me/api/basic_json/type_name/ + JSON_HEDLEY_RETURNS_NON_NULL + const char* type_name() const noexcept + { + switch (m_type) + { + case value_t::null: + return "null"; + case value_t::object: + return "object"; + case value_t::array: + return "array"; + case value_t::string: + return "string"; + case value_t::boolean: + return "boolean"; + case value_t::binary: + return "binary"; + case value_t::discarded: + return "discarded"; + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + default: + return "number"; + } + } + + + JSON_PRIVATE_UNLESS_TESTED: + ////////////////////// + // member variables // + ////////////////////// + + /// the type of the current element + value_t m_type = value_t::null; + + /// the value of the current element + json_value m_value = {}; + +#if JSON_DIAGNOSTICS + /// a pointer to a parent value (for debugging purposes) + basic_json* m_parent = nullptr; +#endif + + ////////////////////////////////////////// + // binary serialization/deserialization // + ////////////////////////////////////////// + + /// @name binary serialization/deserialization support + /// @{ + + public: + /// @brief create a CBOR serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ + static std::vector to_cbor(const basic_json& j) + { + std::vector result; + to_cbor(j, result); + return result; + } + + /// @brief create a CBOR serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + /// @brief create a CBOR serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_cbor/ + static void to_cbor(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_cbor(j); + } + + /// @brief create a MessagePack serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ + static std::vector to_msgpack(const basic_json& j) + { + std::vector result; + to_msgpack(j, result); + return result; + } + + /// @brief create a MessagePack serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + /// @brief create a MessagePack serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_msgpack/ + static void to_msgpack(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_msgpack(j); + } + + /// @brief create a UBJSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ + static std::vector to_ubjson(const basic_json& j, + const bool use_size = false, + const bool use_type = false) + { + std::vector result; + to_ubjson(j, result, use_size, use_type); + return result; + } + + /// @brief create a UBJSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + /// @brief create a UBJSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_ubjson/ + static void to_ubjson(const basic_json& j, detail::output_adapter o, + const bool use_size = false, const bool use_type = false) + { + binary_writer(o).write_ubjson(j, use_size, use_type); + } + + /// @brief create a BSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ + static std::vector to_bson(const basic_json& j) + { + std::vector result; + to_bson(j, result); + return result; + } + + /// @brief create a BSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + /// @brief create a BSON serialization of a given JSON value + /// @sa https://json.nlohmann.me/api/basic_json/to_bson/ + static void to_bson(const basic_json& j, detail::output_adapter o) + { + binary_writer(o).write_bson(j); + } + + /// @brief create a JSON value from an input in CBOR format + /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in CBOR format + /// @sa https://json.nlohmann.me/api/basic_json/from_cbor/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_cbor(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + return from_cbor(ptr, ptr + len, strict, allow_exceptions, tag_handler); + } + + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_cbor(ptr, ptr + len)) + static basic_json from_cbor(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true, + const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::cbor, &sdp, strict, tag_handler); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in MessagePack format + /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in MessagePack format + /// @sa https://json.nlohmann.me/api/basic_json/from_msgpack/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_msgpack(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_msgpack(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_msgpack(ptr, ptr + len)) + static basic_json from_msgpack(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::msgpack, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in UBJSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in UBJSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_ubjson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_ubjson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_ubjson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_ubjson(ptr, ptr + len)) + static basic_json from_ubjson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::ubjson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in BSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(InputType&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::forward(i)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + /// @brief create a JSON value from an input in BSON format + /// @sa https://json.nlohmann.me/api/basic_json/from_bson/ + template + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json from_bson(IteratorType first, IteratorType last, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = detail::input_adapter(std::move(first), std::move(last)); + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + + template + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(const T* ptr, std::size_t len, + const bool strict = true, + const bool allow_exceptions = true) + { + return from_bson(ptr, ptr + len, strict, allow_exceptions); + } + + JSON_HEDLEY_WARN_UNUSED_RESULT + JSON_HEDLEY_DEPRECATED_FOR(3.8.0, from_bson(ptr, ptr + len)) + static basic_json from_bson(detail::span_input_adapter&& i, + const bool strict = true, + const bool allow_exceptions = true) + { + basic_json result; + detail::json_sax_dom_parser sdp(result, allow_exceptions); + auto ia = i.get(); + // NOLINTNEXTLINE(hicpp-move-const-arg,performance-move-const-arg) + const bool res = binary_reader(std::move(ia)).sax_parse(input_format_t::bson, &sdp, strict); + return res ? result : basic_json(value_t::discarded); + } + /// @} + + ////////////////////////// + // JSON Pointer support // + ////////////////////////// + + /// @name JSON Pointer functions + /// @{ + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + reference operator[](const json_pointer& ptr) + { + return ptr.get_unchecked(this); + } + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/operator%5B%5D/ + const_reference operator[](const json_pointer& ptr) const + { + return ptr.get_unchecked(this); + } + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/at/ + reference at(const json_pointer& ptr) + { + return ptr.get_checked(this); + } + + /// @brief access specified element via JSON Pointer + /// @sa https://json.nlohmann.me/api/basic_json/at/ + const_reference at(const json_pointer& ptr) const + { + return ptr.get_checked(this); + } + + /// @brief return flattened JSON value + /// @sa https://json.nlohmann.me/api/basic_json/flatten/ + basic_json flatten() const + { + basic_json result(value_t::object); + json_pointer::flatten("", *this, result); + return result; + } + + /// @brief unflatten a previously flattened JSON value + /// @sa https://json.nlohmann.me/api/basic_json/unflatten/ + basic_json unflatten() const + { + return json_pointer::unflatten(*this); + } + + /// @} + + ////////////////////////// + // JSON Patch functions // + ////////////////////////// + + /// @name JSON Patch functions + /// @{ + + /// @brief applies a JSON patch + /// @sa https://json.nlohmann.me/api/basic_json/patch/ + basic_json patch(const basic_json& json_patch) const + { + // make a working copy to apply the patch to + basic_json result = *this; + + // the valid JSON Patch operations + enum class patch_operations {add, remove, replace, move, copy, test, invalid}; + + const auto get_op = [](const std::string & op) + { + if (op == "add") + { + return patch_operations::add; + } + if (op == "remove") + { + return patch_operations::remove; + } + if (op == "replace") + { + return patch_operations::replace; + } + if (op == "move") + { + return patch_operations::move; + } + if (op == "copy") + { + return patch_operations::copy; + } + if (op == "test") + { + return patch_operations::test; + } + + return patch_operations::invalid; + }; + + // wrapper for "add" operation; add value at ptr + const auto operation_add = [&result](json_pointer & ptr, basic_json val) + { + // adding to the root of the target document means replacing it + if (ptr.empty()) + { + result = val; + return; + } + + // make sure the top element of the pointer exists + json_pointer top_pointer = ptr.top(); + if (top_pointer != ptr) + { + result.at(top_pointer); + } + + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result[ptr]; + + switch (parent.m_type) + { + case value_t::null: + case value_t::object: + { + // use operator[] to add value + parent[last_path] = val; + break; + } + + case value_t::array: + { + if (last_path == "-") + { + // special case: append to back + parent.push_back(val); + } + else + { + const auto idx = json_pointer::array_index(last_path); + if (JSON_HEDLEY_UNLIKELY(idx > parent.size())) + { + // avoid undefined behavior + JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range", parent)); + } + + // default case: insert add offset + parent.insert(parent.begin() + static_cast(idx), val); + } + break; + } + + // if there exists a parent it cannot be primitive + case value_t::string: // LCOV_EXCL_LINE + case value_t::boolean: // LCOV_EXCL_LINE + case value_t::number_integer: // LCOV_EXCL_LINE + case value_t::number_unsigned: // LCOV_EXCL_LINE + case value_t::number_float: // LCOV_EXCL_LINE + case value_t::binary: // LCOV_EXCL_LINE + case value_t::discarded: // LCOV_EXCL_LINE + default: // LCOV_EXCL_LINE + JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE + } + }; + + // wrapper for "remove" operation; remove value at ptr + const auto operation_remove = [this, &result](json_pointer & ptr) + { + // get reference to parent of JSON pointer ptr + const auto last_path = ptr.back(); + ptr.pop_back(); + basic_json& parent = result.at(ptr); + + // remove child + if (parent.is_object()) + { + // perform range check + auto it = parent.find(last_path); + if (JSON_HEDLEY_LIKELY(it != parent.end())) + { + parent.erase(it); + } + else + { + JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found", *this)); + } + } + else if (parent.is_array()) + { + // note erase performs range check + parent.erase(json_pointer::array_index(last_path)); + } + }; + + // type check: top level value must be an array + if (JSON_HEDLEY_UNLIKELY(!json_patch.is_array())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", json_patch)); + } + + // iterate and apply the operations + for (const auto& val : json_patch) + { + // wrapper to get a value for an operation + const auto get_value = [&val](const std::string & op, + const std::string & member, + bool string_type) -> basic_json & + { + // find value + auto it = val.m_value.object->find(member); + + // context-sensitive error message + const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; + + // check if desired value is present + if (JSON_HEDLEY_UNLIKELY(it == val.m_value.object->end())) + { + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'", val)); + } + + // check if result is of type string + if (JSON_HEDLEY_UNLIKELY(string_type && !it->second.is_string())) + { + // NOLINTNEXTLINE(performance-inefficient-string-concatenation) + JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'", val)); + } + + // no error: return value + return it->second; + }; + + // type check: every element of the array must be an object + if (JSON_HEDLEY_UNLIKELY(!val.is_object())) + { + JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects", val)); + } + + // collect mandatory members + const auto op = get_value("op", "op", true).template get(); + const auto path = get_value(op, "path", true).template get(); + json_pointer ptr(path); + + switch (get_op(op)) + { + case patch_operations::add: + { + operation_add(ptr, get_value("add", "value", false)); + break; + } + + case patch_operations::remove: + { + operation_remove(ptr); + break; + } + + case patch_operations::replace: + { + // the "path" location must exist - use at() + result.at(ptr) = get_value("replace", "value", false); + break; + } + + case patch_operations::move: + { + const auto from_path = get_value("move", "from", true).template get(); + json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The move operation is functionally identical to a + // "remove" operation on the "from" location, followed + // immediately by an "add" operation at the target + // location with the value that was just removed. + operation_remove(from_ptr); + operation_add(ptr, v); + break; + } + + case patch_operations::copy: + { + const auto from_path = get_value("copy", "from", true).template get(); + const json_pointer from_ptr(from_path); + + // the "from" location must exist - use at() + basic_json v = result.at(from_ptr); + + // The copy is functionally identical to an "add" + // operation at the target location using the value + // specified in the "from" member. + operation_add(ptr, v); + break; + } + + case patch_operations::test: + { + bool success = false; + JSON_TRY + { + // check if "value" matches the one at "path" + // the "path" location must exist - use at() + success = (result.at(ptr) == get_value("test", "value", false)); + } + JSON_INTERNAL_CATCH (out_of_range&) + { + // ignore out of range errors: success remains false + } + + // throw an exception if test fails + if (JSON_HEDLEY_UNLIKELY(!success)) + { + JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump(), val)); + } + + break; + } + + case patch_operations::invalid: + default: + { + // op must be "add", "remove", "replace", "move", "copy", or + // "test" + JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid", val)); + } + } + } + + return result; + } + + /// @brief creates a diff as a JSON patch + /// @sa https://json.nlohmann.me/api/basic_json/diff/ + JSON_HEDLEY_WARN_UNUSED_RESULT + static basic_json diff(const basic_json& source, const basic_json& target, + const std::string& path = "") + { + // the patch + basic_json result(value_t::array); + + // if the values are the same, return empty patch + if (source == target) + { + return result; + } + + if (source.type() != target.type()) + { + // different types: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + return result; + } + + switch (source.type()) + { + case value_t::array: + { + // first pass: traverse common elements + std::size_t i = 0; + while (i < source.size() && i < target.size()) + { + // recursive call to compare array values at index i + auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + ++i; + } + + // We now reached the end of at least one array + // in a second pass, traverse the remaining elements + + // remove my remaining elements + const auto end_index = static_cast(result.size()); + while (i < source.size()) + { + // add operations in reverse order to avoid invalid + // indices + result.insert(result.begin() + end_index, object( + { + {"op", "remove"}, + {"path", path + "/" + std::to_string(i)} + })); + ++i; + } + + // add other remaining elements + while (i < target.size()) + { + result.push_back( + { + {"op", "add"}, + {"path", path + "/-"}, + {"value", target[i]} + }); + ++i; + } + + break; + } + + case value_t::object: + { + // first pass: traverse this object's elements + for (auto it = source.cbegin(); it != source.cend(); ++it) + { + // escape the key name to be used in a JSON patch + const auto path_key = path + "/" + detail::escape(it.key()); + + if (target.find(it.key()) != target.end()) + { + // recursive call to compare object values at key it + auto temp_diff = diff(it.value(), target[it.key()], path_key); + result.insert(result.end(), temp_diff.begin(), temp_diff.end()); + } + else + { + // found a key that is not in o -> remove it + result.push_back(object( + { + {"op", "remove"}, {"path", path_key} + })); + } + } + + // second pass: traverse other object's elements + for (auto it = target.cbegin(); it != target.cend(); ++it) + { + if (source.find(it.key()) == source.end()) + { + // found a key that is not in this -> add it + const auto path_key = path + "/" + detail::escape(it.key()); + result.push_back( + { + {"op", "add"}, {"path", path_key}, + {"value", it.value()} + }); + } + } + + break; + } + + case value_t::null: + case value_t::string: + case value_t::boolean: + case value_t::number_integer: + case value_t::number_unsigned: + case value_t::number_float: + case value_t::binary: + case value_t::discarded: + default: + { + // both primitive type: replace value + result.push_back( + { + {"op", "replace"}, {"path", path}, {"value", target} + }); + break; + } + } + + return result; + } + + /// @} + + //////////////////////////////// + // JSON Merge Patch functions // + //////////////////////////////// + + /// @name JSON Merge Patch functions + /// @{ + + /// @brief applies a JSON Merge Patch + /// @sa https://json.nlohmann.me/api/basic_json/merge_patch/ + void merge_patch(const basic_json& apply_patch) + { + if (apply_patch.is_object()) + { + if (!is_object()) + { + *this = object(); + } + for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) + { + if (it.value().is_null()) + { + erase(it.key()); + } + else + { + operator[](it.key()).merge_patch(it.value()); + } + } + } + else + { + *this = apply_patch; + } + } + + /// @} +}; + +/// @brief user-defined to_string function for JSON values +/// @sa https://json.nlohmann.me/api/basic_json/to_string/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +std::string to_string(const NLOHMANN_BASIC_JSON_TPL& j) +{ + return j.dump(); +} + +} // namespace nlohmann + +/////////////////////// +// nonmember support // +/////////////////////// + +namespace std // NOLINT(cert-dcl58-cpp) +{ + +/// @brief hash value for JSON objects +/// @sa https://json.nlohmann.me/api/basic_json/std_hash/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct hash +{ + std::size_t operator()(const nlohmann::NLOHMANN_BASIC_JSON_TPL& j) const + { + return nlohmann::detail::hash(j); + } +}; + +// specialization for std::less +template<> +struct less< ::nlohmann::detail::value_t> // do not remove the space after '<', see https://github.com/nlohmann/json/pull/679 +{ + /*! + @brief compare two value_t enum values + @since version 3.0.0 + */ + bool operator()(nlohmann::detail::value_t lhs, + nlohmann::detail::value_t rhs) const noexcept + { + return nlohmann::detail::operator<(lhs, rhs); + } +}; + +// C++20 prohibit function specialization in the std namespace. +#ifndef JSON_HAS_CPP_20 + +/// @brief exchanges the values of two JSON objects +/// @sa https://json.nlohmann.me/api/basic_json/std_swap/ +NLOHMANN_BASIC_JSON_TPL_DECLARATION +inline void swap(nlohmann::NLOHMANN_BASIC_JSON_TPL& j1, nlohmann::NLOHMANN_BASIC_JSON_TPL& j2) noexcept( // NOLINT(readability-inconsistent-declaration-parameter-name) + is_nothrow_move_constructible::value&& // NOLINT(misc-redundant-expression) + is_nothrow_move_assignable::value) +{ + j1.swap(j2); +} + +#endif + +} // namespace std + +/// @brief user-defined string literal for JSON values +/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json operator "" _json(const char* s, std::size_t n) +{ + return nlohmann::json::parse(s, s + n); +} + +/// @brief user-defined string literal for JSON pointer +/// @sa https://json.nlohmann.me/api/basic_json/operator_literal_json_pointer/ +JSON_HEDLEY_NON_NULL(1) +inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) +{ + return nlohmann::json::json_pointer(std::string(s, n)); +} + +// #include + + +// restore clang diagnostic settings +#if defined(__clang__) + #pragma clang diagnostic pop +#endif + +// clean up +#undef JSON_ASSERT +#undef JSON_INTERNAL_CATCH +#undef JSON_CATCH +#undef JSON_THROW +#undef JSON_TRY +#undef JSON_PRIVATE_UNLESS_TESTED +#undef JSON_HAS_CPP_11 +#undef JSON_HAS_CPP_14 +#undef JSON_HAS_CPP_17 +#undef JSON_HAS_CPP_20 +#undef JSON_HAS_FILESYSTEM +#undef JSON_HAS_EXPERIMENTAL_FILESYSTEM +#undef NLOHMANN_BASIC_JSON_TPL_DECLARATION +#undef NLOHMANN_BASIC_JSON_TPL +#undef JSON_EXPLICIT +#undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL + +// #include + + +#undef JSON_HEDLEY_ALWAYS_INLINE +#undef JSON_HEDLEY_ARM_VERSION +#undef JSON_HEDLEY_ARM_VERSION_CHECK +#undef JSON_HEDLEY_ARRAY_PARAM +#undef JSON_HEDLEY_ASSUME +#undef JSON_HEDLEY_BEGIN_C_DECLS +#undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#undef JSON_HEDLEY_CLANG_HAS_FEATURE +#undef JSON_HEDLEY_CLANG_HAS_WARNING +#undef JSON_HEDLEY_COMPCERT_VERSION +#undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#undef JSON_HEDLEY_CONCAT +#undef JSON_HEDLEY_CONCAT3 +#undef JSON_HEDLEY_CONCAT3_EX +#undef JSON_HEDLEY_CONCAT_EX +#undef JSON_HEDLEY_CONST +#undef JSON_HEDLEY_CONSTEXPR +#undef JSON_HEDLEY_CONST_CAST +#undef JSON_HEDLEY_CPP_CAST +#undef JSON_HEDLEY_CRAY_VERSION +#undef JSON_HEDLEY_CRAY_VERSION_CHECK +#undef JSON_HEDLEY_C_DECL +#undef JSON_HEDLEY_DEPRECATED +#undef JSON_HEDLEY_DEPRECATED_FOR +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#undef JSON_HEDLEY_DIAGNOSTIC_POP +#undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#undef JSON_HEDLEY_DMC_VERSION +#undef JSON_HEDLEY_DMC_VERSION_CHECK +#undef JSON_HEDLEY_EMPTY_BASES +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#undef JSON_HEDLEY_END_C_DECLS +#undef JSON_HEDLEY_FLAGS +#undef JSON_HEDLEY_FLAGS_CAST +#undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_BUILTIN +#undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GCC_HAS_EXTENSION +#undef JSON_HEDLEY_GCC_HAS_FEATURE +#undef JSON_HEDLEY_GCC_HAS_WARNING +#undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#undef JSON_HEDLEY_GCC_VERSION +#undef JSON_HEDLEY_GCC_VERSION_CHECK +#undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#undef JSON_HEDLEY_GNUC_HAS_FEATURE +#undef JSON_HEDLEY_GNUC_HAS_WARNING +#undef JSON_HEDLEY_GNUC_VERSION +#undef JSON_HEDLEY_GNUC_VERSION_CHECK +#undef JSON_HEDLEY_HAS_ATTRIBUTE +#undef JSON_HEDLEY_HAS_BUILTIN +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#undef JSON_HEDLEY_HAS_EXTENSION +#undef JSON_HEDLEY_HAS_FEATURE +#undef JSON_HEDLEY_HAS_WARNING +#undef JSON_HEDLEY_IAR_VERSION +#undef JSON_HEDLEY_IAR_VERSION_CHECK +#undef JSON_HEDLEY_IBM_VERSION +#undef JSON_HEDLEY_IBM_VERSION_CHECK +#undef JSON_HEDLEY_IMPORT +#undef JSON_HEDLEY_INLINE +#undef JSON_HEDLEY_INTEL_CL_VERSION +#undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#undef JSON_HEDLEY_INTEL_VERSION +#undef JSON_HEDLEY_INTEL_VERSION_CHECK +#undef JSON_HEDLEY_IS_CONSTANT +#undef JSON_HEDLEY_IS_CONSTEXPR_ +#undef JSON_HEDLEY_LIKELY +#undef JSON_HEDLEY_MALLOC +#undef JSON_HEDLEY_MCST_LCC_VERSION +#undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#undef JSON_HEDLEY_MESSAGE +#undef JSON_HEDLEY_MSVC_VERSION +#undef JSON_HEDLEY_MSVC_VERSION_CHECK +#undef JSON_HEDLEY_NEVER_INLINE +#undef JSON_HEDLEY_NON_NULL +#undef JSON_HEDLEY_NO_ESCAPE +#undef JSON_HEDLEY_NO_RETURN +#undef JSON_HEDLEY_NO_THROW +#undef JSON_HEDLEY_NULL +#undef JSON_HEDLEY_PELLES_VERSION +#undef JSON_HEDLEY_PELLES_VERSION_CHECK +#undef JSON_HEDLEY_PGI_VERSION +#undef JSON_HEDLEY_PGI_VERSION_CHECK +#undef JSON_HEDLEY_PREDICT +#undef JSON_HEDLEY_PRINTF_FORMAT +#undef JSON_HEDLEY_PRIVATE +#undef JSON_HEDLEY_PUBLIC +#undef JSON_HEDLEY_PURE +#undef JSON_HEDLEY_REINTERPRET_CAST +#undef JSON_HEDLEY_REQUIRE +#undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#undef JSON_HEDLEY_REQUIRE_MSG +#undef JSON_HEDLEY_RESTRICT +#undef JSON_HEDLEY_RETURNS_NON_NULL +#undef JSON_HEDLEY_SENTINEL +#undef JSON_HEDLEY_STATIC_ASSERT +#undef JSON_HEDLEY_STATIC_CAST +#undef JSON_HEDLEY_STRINGIFY +#undef JSON_HEDLEY_STRINGIFY_EX +#undef JSON_HEDLEY_SUNPRO_VERSION +#undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#undef JSON_HEDLEY_TINYC_VERSION +#undef JSON_HEDLEY_TINYC_VERSION_CHECK +#undef JSON_HEDLEY_TI_ARMCL_VERSION +#undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL2000_VERSION +#undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL430_VERSION +#undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL6X_VERSION +#undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CL7X_VERSION +#undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#undef JSON_HEDLEY_TI_CLPRU_VERSION +#undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#undef JSON_HEDLEY_TI_VERSION +#undef JSON_HEDLEY_TI_VERSION_CHECK +#undef JSON_HEDLEY_UNAVAILABLE +#undef JSON_HEDLEY_UNLIKELY +#undef JSON_HEDLEY_UNPREDICTABLE +#undef JSON_HEDLEY_UNREACHABLE +#undef JSON_HEDLEY_UNREACHABLE_RETURN +#undef JSON_HEDLEY_VERSION +#undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#undef JSON_HEDLEY_VERSION_DECODE_MINOR +#undef JSON_HEDLEY_VERSION_DECODE_REVISION +#undef JSON_HEDLEY_VERSION_ENCODE +#undef JSON_HEDLEY_WARNING +#undef JSON_HEDLEY_WARN_UNUSED_RESULT +#undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#undef JSON_HEDLEY_FALL_THROUGH + + + +#endif // INCLUDE_NLOHMANN_JSON_HPP_ diff --git a/3rdParty/nlohmann/json_fwd.hpp b/3rdParty/nlohmann/json_fwd.hpp index bdcc45b660..2d5ba384be 100644 --- a/3rdParty/nlohmann/json_fwd.hpp +++ b/3rdParty/nlohmann/json_fwd.hpp @@ -1,64 +1,64 @@ -#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ -#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ - -#include // int64_t, uint64_t -#include // map -#include // allocator -#include // string -#include // vector - -/*! -@brief namespace for Niels Lohmann -@see https://github.com/nlohmann -@since version 1.0.0 -*/ -namespace nlohmann -{ -/*! -@brief default JSONSerializer template argument - -This serializer ignores the template arguments and uses ADL -([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) -for serialization. -*/ -template -struct adl_serializer; - -/// a class to store JSON values -/// @sa https://json.nlohmann.me/api/basic_json/ -template class ObjectType = - std::map, - template class ArrayType = std::vector, - class StringType = std::string, class BooleanType = bool, - class NumberIntegerType = std::int64_t, - class NumberUnsignedType = std::uint64_t, - class NumberFloatType = double, - template class AllocatorType = std::allocator, - template class JSONSerializer = - adl_serializer, - class BinaryType = std::vector> -class basic_json; - -/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document -/// @sa https://json.nlohmann.me/api/json_pointer/ -template -class json_pointer; - -/*! -@brief default specialization -@sa https://json.nlohmann.me/api/json/ -*/ -using json = basic_json<>; - -/// @brief a minimal map-like container that preserves insertion order -/// @sa https://json.nlohmann.me/api/ordered_map/ -template -struct ordered_map; - -/// @brief specialization that maintains the insertion order of object keys -/// @sa https://json.nlohmann.me/api/ordered_json/ -using ordered_json = basic_json; - -} // namespace nlohmann - -#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ +#define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + +#include // int64_t, uint64_t +#include // map +#include // allocator +#include // string +#include // vector + +/*! +@brief namespace for Niels Lohmann +@see https://github.com/nlohmann +@since version 1.0.0 +*/ +namespace nlohmann +{ +/*! +@brief default JSONSerializer template argument + +This serializer ignores the template arguments and uses ADL +([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) +for serialization. +*/ +template +struct adl_serializer; + +/// a class to store JSON values +/// @sa https://json.nlohmann.me/api/basic_json/ +template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> +class basic_json; + +/// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document +/// @sa https://json.nlohmann.me/api/json_pointer/ +template +class json_pointer; + +/*! +@brief default specialization +@sa https://json.nlohmann.me/api/json/ +*/ +using json = basic_json<>; + +/// @brief a minimal map-like container that preserves insertion order +/// @sa https://json.nlohmann.me/api/ordered_map/ +template +struct ordered_map; + +/// @brief specialization that maintains the insertion order of object keys +/// @sa https://json.nlohmann.me/api/ordered_json/ +using ordered_json = basic_json; + +} // namespace nlohmann + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ diff --git a/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp b/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp index a0245b81b1..f44dacbedf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/calib3d.hpp @@ -1,4146 +1,4146 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CALIB3D_HPP -#define OPENCV_CALIB3D_HPP - -#include "opencv2/core.hpp" -#include "opencv2/core/types.hpp" -#include "opencv2/features2d.hpp" -#include "opencv2/core/affine.hpp" -#include "opencv2/core/utils/logger.hpp" - -/** - @defgroup calib3d Camera Calibration and 3D Reconstruction - -The functions in this section use a so-called pinhole camera model. The view of a scene -is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective -transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are -represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will -find a brief introduction to projective geometry, homogeneous vectors and homogeneous -transformations at the end of this section's introduction. For more succinct notation, we often drop -the 'homogeneous' and say vector instead of homogeneous vector. - -The distortion-free projective transformation given by a pinhole camera model is shown below. - -\f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f] - -where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system, -\f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix, -\f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from -world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's -arbitrary scaling and not part of the camera model. - -The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated -as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e. - -\f[p = A P_c.\f] - -The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are -expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the -image center: - -\f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f] - -and thus - -\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f] - -The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can -be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the -camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided, -respectively) by the same factor. - -The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective -transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points -represented in camera coordinates to 2D points in the image plane and represented in normalized -camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$: - -\f[Z_c \begin{bmatrix} -x' \\ -y' \\ -1 -\end{bmatrix} = \begin{bmatrix} -1 & 0 & 0 & 0 \\ -0 & 1 & 0 & 0 \\ -0 & 0 & 1 & 0 -\end{bmatrix} -\begin{bmatrix} -X_c \\ -Y_c \\ -Z_c \\ -1 -\end{bmatrix}.\f] - -The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and -represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem -\f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we -obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by - -\f[P_c = \begin{bmatrix} -R & t \\ -0 & 1 -\end{bmatrix} P_w,\f] - -This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a -3-by-1 translation vector: - -\f[\begin{bmatrix} -R & t \\ -0 & 1 -\end{bmatrix} = \begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z \\ -0 & 0 & 0 & 1 -\end{bmatrix}, -\f] - -and therefore - -\f[\begin{bmatrix} -X_c \\ -Y_c \\ -Z_c \\ -1 -\end{bmatrix} = \begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z \\ -0 & 0 & 0 & 1 -\end{bmatrix} -\begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix}.\f] - -Combining the projective transformation and the homogeneous transformation, we obtain the projective -transformation that maps 3D points in world coordinates into 2D points in the image plane and in -normalized camera coordinates: - -\f[Z_c \begin{bmatrix} -x' \\ -y' \\ -1 -\end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix} = \begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z -\end{bmatrix} -\begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix},\f] - -with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out -\f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as - -\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} -\begin{bmatrix} -r_{11} & r_{12} & r_{13} & t_x \\ -r_{21} & r_{22} & r_{23} & t_y \\ -r_{31} & r_{32} & r_{33} & t_z -\end{bmatrix} -\begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix}.\f] - -If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following, - -\f[\begin{bmatrix} -u \\ -v -\end{bmatrix} = \begin{bmatrix} -f_x X_c/Z_c + c_x \\ -f_y Y_c/Z_c + c_y -\end{bmatrix}\f] - -with - -\f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix} -R|t -\end{bmatrix} \begin{bmatrix} -X_w \\ -Y_w \\ -Z_w \\ -1 -\end{bmatrix}.\f] - -The following figure illustrates the pinhole camera model. - -![Pinhole camera model](pics/pinhole_camera_model.png) - -Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion. -So, the above model is extended as: - -\f[\begin{bmatrix} -u \\ -v -\end{bmatrix} = \begin{bmatrix} -f_x x'' + c_x \\ -f_y y'' + c_y -\end{bmatrix}\f] - -where - -\f[\begin{bmatrix} -x'' \\ -y'' -\end{bmatrix} = \begin{bmatrix} -x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\ -y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ -\end{bmatrix}\f] - -with - -\f[r^2 = x'^2 + y'^2\f] - -and - -\f[\begin{bmatrix} -x'\\ -y' -\end{bmatrix} = \begin{bmatrix} -X_c/Z_c \\ -Y_c/Z_c -\end{bmatrix},\f] - -if \f$Z_c \ne 0\f$. - -The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$ -,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$, -are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV. - -The next figures show two common types of radial distortion: barrel distortion -(\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing) -and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing). -Radial distortion is always monotonic for real lenses, -and if the estimator produces a non-monotonic result, -this should be considered a calibration failure. -More generally, radial distortion must be monotonic and the distortion function must be bijective. -A failed estimation result may look deceptively good near the image center -but will work poorly in e.g. AR/SFM applications. -The optimization method used in OpenCV camera calibration does not include these constraints as -the framework does not support the required integer programming and polynomial inequalities. -See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information. - -![](pics/distortion_examples.png) -![](pics/distortion_examples2.png) - -In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the -camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or -triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and -\f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07. - -\f[\begin{bmatrix} -u \\ -v -\end{bmatrix} = \begin{bmatrix} -f_x x''' + c_x \\ -f_y y''' + c_y -\end{bmatrix},\f] - -where - -\f[s\vecthree{x'''}{y'''}{1} = -\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)} -{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} -{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f] - -and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter -\f$\tau_x\f$ and \f$\tau_y\f$, respectively, - -\f[ -R(\tau_x, \tau_y) = -\vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)} -\vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} = -\vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)} -{0}{\cos(\tau_x)}{\sin(\tau_x)} -{\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}. -\f] - -In the functions below the coefficients are passed or returned as - -\f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f] - -vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion -coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera -parameters. And they remain the same regardless of the captured image resolution. If, for example, a -camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion -coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$, -\f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately. - -The functions below use the above model to do the following: - -- Project 3D points to the image plane given intrinsic and extrinsic parameters. -- Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their -projections. -- Estimate intrinsic and extrinsic camera parameters from several views of a known calibration -pattern (every view is described by several 3D-2D point correspondences). -- Estimate the relative position and orientation of the stereo camera "heads" and compute the -*rectification* transformation that makes the camera optical axes parallel. - - Homogeneous Coordinates
-Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use -allows to represent points at infinity by finite coordinates and simplifies formulas when compared -to the cartesian counterparts, e.g. they have the advantage that affine transformations can be -expressed as linear homogeneous transformation. - -One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian -vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is: - -\f[\begin{bmatrix} -X \\ -Y \\ -Z -\end{bmatrix} \rightarrow \begin{bmatrix} -X \\ -Y \\ -Z \\ -1 -\end{bmatrix}.\f] - -For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector -by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by: - -\f[\begin{bmatrix} -X \\ -Y \\ -W -\end{bmatrix} \rightarrow \begin{bmatrix} -X / W \\ -Y / W -\end{bmatrix},\f] - -if \f$W \ne 0\f$. - -Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent -the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective -transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical -observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are -projected to the same image point, e.g. all points along the red ray in the image of the pinhole -camera model above would be mapped to the same image coordinate. This property is also the source -for the scale ambiguity s in the equation of the pinhole camera model. - -As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by -\f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system -0 to coordinate system 1 becomes: - -\f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix} -R & t \\ -0 & 1 -\end{bmatrix} P_{h_0}.\f] - -@note - - Many functions in this module take a camera intrinsic matrix as an input parameter. Although all - functions assume the same structure of this parameter, they may name it differently. The - parameter's description, however, will be clear in that a camera intrinsic matrix with the structure - shown above is required. - - A calibration sample for 3 cameras in a horizontal position can be found at - opencv_source_code/samples/cpp/3calibration.cpp - - A calibration sample based on a sequence of images can be found at - opencv_source_code/samples/cpp/calibration.cpp - - A calibration sample in order to do 3D reconstruction can be found at - opencv_source_code/samples/cpp/build3dmodel.cpp - - A calibration example on stereo calibration can be found at - opencv_source_code/samples/cpp/stereo_calib.cpp - - A calibration example on stereo matching can be found at - opencv_source_code/samples/cpp/stereo_match.cpp - - (Python) A camera calibration sample can be found at - opencv_source_code/samples/python/calibrate.py - - @{ - @defgroup calib3d_fisheye Fisheye camera model - - Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the - matrix X) The coordinate vector of P in the camera reference frame is: - - \f[Xc = R X + T\f] - - where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y - and z the 3 coordinates of Xc: - - \f[\begin{array}{l} x = Xc_1 \\ y = Xc_2 \\ z = Xc_3 \end{array} \f] - - The pinhole projection coordinates of P is [a; b] where - - \f[\begin{array}{l} a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r) \end{array} \f] - - Fisheye distortion: - - \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f] - - The distorted point coordinates are [x'; y'] where - - \f[\begin{array}{l} x' = (\theta_d / r) a \\ y' = (\theta_d / r) b \end{array} \f] - - Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where: - - \f[\begin{array}{l} u = f_x (x' + \alpha y') + c_x \\ - v = f_y y' + c_y \end{array} \f] - - Summary: - Generic camera model @cite Kannala2006 with perspective projection and without distortion correction - - @} - */ - -namespace cv -{ - -//! @addtogroup calib3d -//! @{ - -//! type of the robust estimation algorithm -enum { LMEDS = 4, //!< least-median of squares algorithm - RANSAC = 8, //!< RANSAC algorithm - RHO = 16, //!< RHO algorithm - USAC_DEFAULT = 32, //!< USAC algorithm, default settings - USAC_PARALLEL = 33, //!< USAC, parallel version - USAC_FM_8PTS = 34, //!< USAC, fundamental matrix 8 points - USAC_FAST = 35, //!< USAC, fast settings - USAC_ACCURATE = 36, //!< USAC, accurate settings - USAC_PROSAC = 37, //!< USAC, sorted points, runs PROSAC - USAC_MAGSAC = 38 //!< USAC, runs MAGSAC++ - }; - -enum SolvePnPMethod { - SOLVEPNP_ITERATIVE = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n - //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n - //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition. - SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp - SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete - SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n - //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct - SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n - //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive - SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17 - SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n - //!< Object points must be coplanar. - SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n - //!< This is a special case suitable for marker pose estimation.\n - //!< 4 coplanar object points must be defined in the following order: - //!< - point 0: [-squareLength / 2, squareLength / 2, 0] - //!< - point 1: [ squareLength / 2, squareLength / 2, 0] - //!< - point 2: [ squareLength / 2, -squareLength / 2, 0] - //!< - point 3: [-squareLength / 2, -squareLength / 2, 0] - SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP -#ifndef CV_DOXYGEN - SOLVEPNP_MAX_COUNT //!< Used for count -#endif -}; - -enum { CALIB_CB_ADAPTIVE_THRESH = 1, - CALIB_CB_NORMALIZE_IMAGE = 2, - CALIB_CB_FILTER_QUADS = 4, - CALIB_CB_FAST_CHECK = 8, - CALIB_CB_EXHAUSTIVE = 16, - CALIB_CB_ACCURACY = 32, - CALIB_CB_LARGER = 64, - CALIB_CB_MARKER = 128, - CALIB_CB_PLAIN = 256 - }; - -enum { CALIB_CB_SYMMETRIC_GRID = 1, - CALIB_CB_ASYMMETRIC_GRID = 2, - CALIB_CB_CLUSTERING = 4 - }; - -enum { CALIB_NINTRINSIC = 18, - CALIB_USE_INTRINSIC_GUESS = 0x00001, - CALIB_FIX_ASPECT_RATIO = 0x00002, - CALIB_FIX_PRINCIPAL_POINT = 0x00004, - CALIB_ZERO_TANGENT_DIST = 0x00008, - CALIB_FIX_FOCAL_LENGTH = 0x00010, - CALIB_FIX_K1 = 0x00020, - CALIB_FIX_K2 = 0x00040, - CALIB_FIX_K3 = 0x00080, - CALIB_FIX_K4 = 0x00800, - CALIB_FIX_K5 = 0x01000, - CALIB_FIX_K6 = 0x02000, - CALIB_RATIONAL_MODEL = 0x04000, - CALIB_THIN_PRISM_MODEL = 0x08000, - CALIB_FIX_S1_S2_S3_S4 = 0x10000, - CALIB_TILTED_MODEL = 0x40000, - CALIB_FIX_TAUX_TAUY = 0x80000, - CALIB_USE_QR = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise - CALIB_FIX_TANGENT_DIST = 0x200000, - // only for stereo - CALIB_FIX_INTRINSIC = 0x00100, - CALIB_SAME_FOCAL_LENGTH = 0x00200, - // for stereo rectification - CALIB_ZERO_DISPARITY = 0x00400, - CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise - CALIB_USE_EXTRINSIC_GUESS = (1 << 22) //!< for stereoCalibrate - }; - -//! the algorithm for finding fundamental matrix -enum { FM_7POINT = 1, //!< 7-point algorithm - FM_8POINT = 2, //!< 8-point algorithm - FM_LMEDS = 4, //!< least-median algorithm. 7-point algorithm is used. - FM_RANSAC = 8 //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used. - }; - -enum HandEyeCalibrationMethod -{ - CALIB_HAND_EYE_TSAI = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89 - CALIB_HAND_EYE_PARK = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94 - CALIB_HAND_EYE_HORAUD = 2, //!< Hand-eye Calibration @cite Horaud95 - CALIB_HAND_EYE_ANDREFF = 3, //!< On-line Hand-Eye Calibration @cite Andreff99 - CALIB_HAND_EYE_DANIILIDIS = 4 //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98 -}; - -enum RobotWorldHandEyeCalibrationMethod -{ - CALIB_ROBOT_WORLD_HAND_EYE_SHAH = 0, //!< Solving the robot-world/hand-eye calibration problem using the kronecker product @cite Shah2013SolvingTR - CALIB_ROBOT_WORLD_HAND_EYE_LI = 1 //!< Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product @cite Li2010SimultaneousRA -}; - -enum SamplingMethod { SAMPLING_UNIFORM=0, SAMPLING_PROGRESSIVE_NAPSAC=1, SAMPLING_NAPSAC=2, - SAMPLING_PROSAC=3 }; -enum LocalOptimMethod {LOCAL_OPTIM_NULL=0, LOCAL_OPTIM_INNER_LO=1, LOCAL_OPTIM_INNER_AND_ITER_LO=2, - LOCAL_OPTIM_GC=3, LOCAL_OPTIM_SIGMA=4}; -enum ScoreMethod {SCORE_METHOD_RANSAC=0, SCORE_METHOD_MSAC=1, SCORE_METHOD_MAGSAC=2, SCORE_METHOD_LMEDS=3}; -enum NeighborSearchMethod { NEIGH_FLANN_KNN=0, NEIGH_GRID=1, NEIGH_FLANN_RADIUS=2 }; -enum PolishingMethod { NONE_POLISHER=0, LSQ_POLISHER=1, MAGSAC=2, COV_POLISHER=3 }; - -struct CV_EXPORTS_W_SIMPLE UsacParams -{ // in alphabetical order - CV_WRAP UsacParams(); - CV_PROP_RW double confidence; - CV_PROP_RW bool isParallel; - CV_PROP_RW int loIterations; - CV_PROP_RW LocalOptimMethod loMethod; - CV_PROP_RW int loSampleSize; - CV_PROP_RW int maxIterations; - CV_PROP_RW NeighborSearchMethod neighborsSearch; - CV_PROP_RW int randomGeneratorState; - CV_PROP_RW SamplingMethod sampler; - CV_PROP_RW ScoreMethod score; - CV_PROP_RW double threshold; - CV_PROP_RW PolishingMethod final_polisher; - CV_PROP_RW int final_polisher_iterations; -}; - -/** @brief Converts a rotation matrix to a rotation vector or vice versa. - -@param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). -@param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. -@param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial -derivatives of the output array components with respect to the input array components. - -\f[\begin{array}{l} \theta \leftarrow norm(r) \\ r \leftarrow r/ \theta \\ R = \cos(\theta) I + (1- \cos{\theta} ) r r^T + \sin(\theta) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f] - -Inverse transformation can be also done easily, since - -\f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f] - -A rotation vector is a convenient and most compact representation of a rotation matrix (since any -rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry -optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP . - -@note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate -can be found in: - - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF - -@note Useful information on SE(3) and Lie Groups can be found in: - - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial - - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17 - - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML - */ -CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() ); - - - -/** Levenberg-Marquardt solver. Starting with the specified vector of parameters it - optimizes the target vector criteria "err" - (finds local minima of each target vector component absolute value). - - When needed, it calls user-provided callback. -*/ -class CV_EXPORTS LMSolver : public Algorithm -{ -public: - class CV_EXPORTS Callback - { - public: - virtual ~Callback() {} - /** - computes error and Jacobian for the specified vector of parameters - - @param param the current vector of parameters - @param err output vector of errors: err_i = actual_f_i - ideal_f_i - @param J output Jacobian: J_ij = d(ideal_f_i)/d(param_j) - - when J=noArray(), it means that it does not need to be computed. - Dimensionality of error vector and param vector can be different. - The callback should explicitly allocate (with "create" method) each output array - (unless it's noArray()). - */ - virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0; - }; - - /** - Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point. - The final vector of parameters (whether the algorithm converged or not) is stored at the same - vector. The method returns the number of iterations used. If it's equal to the previously specified - maxIters, there is a big chance the algorithm did not converge. - - @param param initial/final vector of parameters. - - Note that the dimensionality of parameter space is defined by the size of param vector, - and the dimensionality of optimized criteria is defined by the size of err vector - computed by the callback. - */ - virtual int run(InputOutputArray param) const = 0; - - /** - Sets the maximum number of iterations - @param maxIters the number of iterations - */ - virtual void setMaxIters(int maxIters) = 0; - /** - Retrieves the current maximum number of iterations - */ - virtual int getMaxIters() const = 0; - - /** - Creates Levenberg-Marquard solver - - @param cb callback - @param maxIters maximum number of iterations that can be further - modified using setMaxIters() method. - */ - static Ptr create(const Ptr& cb, int maxIters); - static Ptr create(const Ptr& cb, int maxIters, double eps); -}; - - - -/** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp -An example program about pose estimation from coplanar points - -Check @ref tutorial_homography "the corresponding tutorial" for more details -*/ - -/** @brief Finds a perspective transformation between two planes. - -@param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2 -or vector\ . -@param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or -a vector\ . -@param method Method used to compute a homography matrix. The following methods are possible: -- **0** - a regular method using all the points, i.e., the least squares method -- @ref RANSAC - RANSAC-based robust method -- @ref LMEDS - Least-Median robust method -- @ref RHO - PROSAC-based robust method -@param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier -(used in the RANSAC and RHO methods only). That is, if -\f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} \cdot \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f] -then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels, -it usually makes sense to set this parameter somewhere in the range of 1 to 10. -@param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input -mask values are ignored. -@param maxIters The maximum number of RANSAC iterations. -@param confidence Confidence level, between 0 and 1. - -The function finds and returns the perspective transformation \f$H\f$ between the source and the -destination planes: - -\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] - -so that the back-projection error - -\f[\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2\f] - -is minimized. If the parameter method is set to the default value 0, the function uses all the point -pairs to compute an initial homography estimate with a simple least-squares scheme. - -However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective -transformation (that is, there are some outliers), this initial estimate will be poor. In this case, -you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different -random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix -using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the -computed homography (which is the number of inliers for RANSAC or the least median re-projection error for -LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and -the mask of inliers/outliers. - -Regardless of the method, robust or not, the computed homography matrix is refined further (using -inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the -re-projection error even more. - -The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to -distinguish inliers from outliers. The method LMeDS does not need any threshold but it works -correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the -noise is rather small, use the default method (method=0). - -The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is -determined up to a scale. If \f$h_{33}\f$ is non-zero, the matrix is normalized so that \f$h_{33}=1\f$. -@note Whenever an \f$H\f$ matrix cannot be estimated, an empty one will be returned. - -@sa -getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective, -perspectiveTransform - */ -CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, - int method = 0, double ransacReprojThreshold = 3, - OutputArray mask=noArray(), const int maxIters = 2000, - const double confidence = 0.995); - -/** @overload */ -CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, - OutputArray mask, int method = 0, double ransacReprojThreshold = 3 ); - - -CV_EXPORTS_W Mat findHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask, - const UsacParams ¶ms); - -/** @brief Computes an RQ decomposition of 3x3 matrices. - -@param src 3x3 input matrix. -@param mtxR Output 3x3 upper-triangular matrix. -@param mtxQ Output 3x3 orthogonal matrix. -@param Qx Optional output 3x3 rotation matrix around x-axis. -@param Qy Optional output 3x3 rotation matrix around y-axis. -@param Qz Optional output 3x3 rotation matrix around z-axis. - -The function computes a RQ decomposition using the given rotations. This function is used in -#decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera -and a rotation matrix. - -It optionally returns three rotation matrices, one for each axis, and the three Euler angles in -degrees (as the return value) that could be used in OpenGL. Note, there is always more than one -sequence of rotations about the three principal axes that results in the same orientation of an -object, e.g. see @cite Slabaugh . Returned three rotation matrices and corresponding three Euler angles -are only one of the possible solutions. - */ -CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, - OutputArray Qx = noArray(), - OutputArray Qy = noArray(), - OutputArray Qz = noArray()); - -/** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix. - -@param projMatrix 3x4 input projection matrix P. -@param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$. -@param rotMatrix Output 3x3 external rotation matrix R. -@param transVect Output 4x1 translation vector T. -@param rotMatrixX Optional 3x3 rotation matrix around x-axis. -@param rotMatrixY Optional 3x3 rotation matrix around y-axis. -@param rotMatrixZ Optional 3x3 rotation matrix around z-axis. -@param eulerAngles Optional three-element vector containing three Euler angles of rotation in -degrees. - -The function computes a decomposition of a projection matrix into a calibration and a rotation -matrix and the position of a camera. - -It optionally returns three rotation matrices, one for each axis, and three Euler angles that could -be used in OpenGL. Note, there is always more than one sequence of rotations about the three -principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned -three rotation matrices and corresponding three Euler angles are only one of the possible solutions. - -The function is based on #RQDecomp3x3 . - */ -CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, - OutputArray rotMatrix, OutputArray transVect, - OutputArray rotMatrixX = noArray(), - OutputArray rotMatrixY = noArray(), - OutputArray rotMatrixZ = noArray(), - OutputArray eulerAngles =noArray() ); - -/** @brief Computes partial derivatives of the matrix product for each multiplied matrix. - -@param A First multiplied matrix. -@param B Second multiplied matrix. -@param dABdA First output derivative matrix d(A\*B)/dA of size -\f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ . -@param dABdB Second output derivative matrix d(A\*B)/dB of size -\f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ . - -The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to -the elements of each of the two input matrices. The function is used to compute the Jacobian -matrices in #stereoCalibrate but can also be used in any other similar optimization function. - */ -CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB ); - -/** @brief Combines two rotation-and-shift transformations. - -@param rvec1 First rotation vector. -@param tvec1 First translation vector. -@param rvec2 Second rotation vector. -@param tvec2 Second translation vector. -@param rvec3 Output rotation vector of the superposition. -@param tvec3 Output translation vector of the superposition. -@param dr3dr1 Optional output derivative of rvec3 with regard to rvec1 -@param dr3dt1 Optional output derivative of rvec3 with regard to tvec1 -@param dr3dr2 Optional output derivative of rvec3 with regard to rvec2 -@param dr3dt2 Optional output derivative of rvec3 with regard to tvec2 -@param dt3dr1 Optional output derivative of tvec3 with regard to rvec1 -@param dt3dt1 Optional output derivative of tvec3 with regard to tvec1 -@param dt3dr2 Optional output derivative of tvec3 with regard to rvec2 -@param dt3dt2 Optional output derivative of tvec3 with regard to tvec2 - -The functions compute: - -\f[\begin{array}{l} \texttt{rvec3} = \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right ) \\ \texttt{tvec3} = \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \texttt{tvec1} + \texttt{tvec2} \end{array} ,\f] - -where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and -\f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See #Rodrigues for details. - -Also, the functions can compute the derivatives of the output vectors with regards to the input -vectors (see #matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in -your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a -function that contains a matrix multiplication. - */ -CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1, - InputArray rvec2, InputArray tvec2, - OutputArray rvec3, OutputArray tvec3, - OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(), - OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(), - OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(), - OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() ); - -/** @brief Projects 3D points to an image plane. - -@param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3 -1-channel or 1xN/Nx1 3-channel (or vector\ ), where N is the number of points in the view. -@param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of -basis from world to camera coordinate system, see @ref calibrateCamera for details. -@param tvec The translation vector, see parameter description above. -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed. -@param imagePoints Output array of image points, 1xN/Nx1 2-channel, or -vector\ . -@param jacobian Optional output 2Nx(10+\) jacobian matrix of derivatives of image -points with respect to components of the rotation vector, translation vector, focal lengths, -coordinates of the principal point and the distortion coefficients. In the old interface different -components of the jacobian are returned via different output parameters. -@param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the -function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the -jacobian matrix. - -The function computes the 2D projections of 3D points to the image plane, given intrinsic and -extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial -derivatives of image points coordinates (as functions of all the input parameters) with respect to -the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global -optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself -can also be used to compute a re-projection error, given the current intrinsic and extrinsic -parameters. - -@note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix, -or by passing zero distortion coefficients, one can get various useful partial cases of the -function. This means, one can compute the distorted coordinates for a sparse set of points or apply -a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup. - */ -CV_EXPORTS_W void projectPoints( InputArray objectPoints, - InputArray rvec, InputArray tvec, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray imagePoints, - OutputArray jacobian = noArray(), - double aspectRatio = 0 ); - -/** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp -An example program about homography from the camera displacement - -Check @ref tutorial_homography "the corresponding tutorial" for more details -*/ - -/** @brief Finds an object pose from 3D-2D point correspondences. - -@see @ref calib3d_solvePnP - -This function returns the rotation and the translation vectors that transform a 3D point expressed in the object -coordinate frame to the camera coordinate frame, using different methods: -- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. -- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. -- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. -Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] -- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or -1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. -@param tvec Output translation vector. -@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses -the provided rvec and tvec values as initial approximations of the rotation and translation -vectors, respectively, and further optimizes them. -@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags - -More information about Perspective-n-Points is described in @ref calib3d_solvePnP - -@note - - An example of how to use solvePnP for planar augmented reality can be found at - opencv_source_code/samples/python/plane_ar.py - - If you are using Python: - - Numpy array slices won't work as input because solvePnP requires contiguous - arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of - modules/calib3d/src/solvepnp.cpp version 2.4.9) - - The P3P algorithm requires image points to be in an array of shape (N,1,2) due - to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) - which requires 2-channel information. - - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of - it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = - np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) - - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are - unstable and sometimes give completely wrong results. If you pass one of these two - flags, @ref SOLVEPNP_EPNP method will be used instead. - - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P - methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions - of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). - - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points - are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the - global solution to converge. - - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. - - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. - Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] - - With @ref SOLVEPNP_SQPNP input points must be >= 3 - */ -CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE ); - -/** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or -1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. -@param tvec Output translation vector. -@param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses -the provided rvec and tvec values as initial approximations of the rotation and translation -vectors, respectively, and further optimizes them. -@param iterationsCount Number of iterations. -@param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value -is the maximum allowed distance between the observed and computed point projections to consider it -an inlier. -@param confidence The probability that the algorithm produces a useful result. -@param inliers Output vector that contains indices of inliers in objectPoints and imagePoints . -@param flags Method for solving a PnP problem (see @ref solvePnP ). - -The function estimates an object pose given a set of object points, their corresponding image -projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such -a pose that minimizes reprojection error, that is, the sum of squared distances between the observed -projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC -makes the function resistant to outliers. - -@note - - An example of how to use solvePNPRansac for object detection can be found at - opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/ - - The default method used to estimate the camera pose for the Minimal Sample Sets step - is #SOLVEPNP_EPNP. Exceptions are: - - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used. - - if the number of input points is equal to 4, #SOLVEPNP_P3P is used. - - The method used to estimate the camera pose using all the inliers is defined by the - flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case, - the method #SOLVEPNP_EPNP will be used instead. - */ -CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess = false, int iterationsCount = 100, - float reprojectionError = 8.0, double confidence = 0.99, - OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE ); - - -/* -Finds rotation and translation vector. -If cameraMatrix is given then run P3P. Otherwise run linear P6P and output cameraMatrix too. -*/ -CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, - InputOutputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, OutputArray inliers, - const UsacParams ¶ms=UsacParams()); - -/** @brief Finds an object pose from 3 3D-2D point correspondences. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or -1x3/3x1 3-channel. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel. - vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from -the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions. -@param tvecs Output translation vectors. -@param flags Method for solving a P3P problem: -- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang -"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete). -- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis. -"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17). - -The function estimates the object pose given 3 object points, their corresponding image -projections, as well as the camera intrinsic matrix and the distortion coefficients. - -@note -The solutions are sorted by reprojection errors (lowest to highest). - */ -CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - int flags ); - -/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame -to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, -where N is the number of points. vector\ can also be passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can also be passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. Input values are used as an initial solution. -@param tvec Input/Output translation vector. Input values are used as an initial solution. -@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. - -The function refines the object pose given at least 3 object points, their corresponding image -projections, an initial solution for the rotation and translation vector, -as well as the camera intrinsic matrix and the distortion coefficients. -The function minimizes the projection error with respect to the rotation and the translation vectors, according -to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process. - */ -CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - InputOutputArray rvec, InputOutputArray tvec, - TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON)); - -/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame -to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. - -@see @ref calib3d_solvePnP - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, -where N is the number of points. vector\ can also be passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can also be passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. Input values are used as an initial solution. -@param tvec Input/Output translation vector. Input values are used as an initial solution. -@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. -@param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$ -gain in the Damped Gauss-Newton formulation. - -The function refines the object pose given at least 3 object points, their corresponding image -projections, an initial solution for the rotation and translation vector, -as well as the camera intrinsic matrix and the distortion coefficients. -The function minimizes the projection error with respect to the rotation and the translation vectors, using a -virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme. - */ -CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - InputOutputArray rvec, InputOutputArray tvec, - TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON), - double VVSlambda = 1); - -/** @brief Finds an object pose from 3D-2D point correspondences. - -@see @ref calib3d_solvePnP - -This function returns a list of all the possible solutions (a solution is a -couple), depending on the number of input points and the chosen method: -- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): 3 or 4 input points. Number of returned solutions can be between 0 and 4 with 3 input points. -- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions. -- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. -Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] -- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. -Only 1 solution is returned. - -@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or -1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. -@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, -where N is the number of points. vector\ can be also passed here. -@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from -the model coordinate system to the camera coordinate system. -@param tvecs Vector of output translation vectors. -@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses -the provided rvec and tvec values as initial approximations of the rotation and translation -vectors, respectively, and further optimizes them. -@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags -@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE -and useExtrinsicGuess is set to true. -@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE -and useExtrinsicGuess is set to true. -@param reprojectionError Optional vector of reprojection error, that is the RMS error -(\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points -and the 3D object points projected with the estimated pose. - -More information is described in @ref calib3d_solvePnP - -@note - - An example of how to use solvePnP for planar augmented reality can be found at - opencv_source_code/samples/python/plane_ar.py - - If you are using Python: - - Numpy array slices won't work as input because solvePnP requires contiguous - arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of - modules/calib3d/src/solvepnp.cpp version 2.4.9) - - The P3P algorithm requires image points to be in an array of shape (N,1,2) due - to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) - which requires 2-channel information. - - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of - it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = - np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) - - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are - unstable and sometimes give completely wrong results. If you pass one of these two - flags, @ref SOLVEPNP_EPNP method will be used instead. - - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P - methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions - of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). - - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points - are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the - global solution to converge. - - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. - - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. - Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] - */ -CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE, - InputArray rvec = noArray(), InputArray tvec = noArray(), - OutputArray reprojectionError = noArray() ); - -/** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences. - -@param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern -coordinate space. In the old interface all the per-view vectors are concatenated. See -#calibrateCamera for details. -@param imagePoints Vector of vectors of the projections of the calibration pattern points. In the -old interface all the per-view vectors are concatenated. -@param imageSize Image size in pixels used to initialize the principal point. -@param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently. -Otherwise, \f$f_x = f_y \cdot \texttt{aspectRatio}\f$ . - -The function estimates and returns an initial camera intrinsic matrix for the camera calibration process. -Currently, the function only supports planar calibration patterns, which are patterns where each -object point has z-coordinate =0. - */ -CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, - Size imageSize, double aspectRatio = 1.0 ); - -/** @brief Finds the positions of internal corners of the chessboard. - -@param image Source chessboard view. It must be an 8-bit grayscale or color image. -@param patternSize Number of inner corners per a chessboard row and column -( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). -@param corners Output array of detected corners. -@param flags Various operation flags that can be zero or a combination of the following values: -- @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black -and white, rather than a fixed threshold level (computed from the average image brightness). -- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with #equalizeHist before -applying fixed or adaptive thresholding. -- @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter, -square-like shape) to filter out false quads extracted at the contour retrieval stage. -- @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners, -and shortcut the call if none is found. This can drastically speed up the call in the -degenerate condition when no chessboard is observed. -- @ref CALIB_CB_PLAIN All other flags are ignored. The input image is taken as is. -No image processing is done to improve to find the checkerboard. This has the effect of speeding up the -execution of the function but could lead to not recognizing the checkerboard if the image -is not previously binarized in the appropriate manner. - -The function attempts to determine whether the input image is a view of the chessboard pattern and -locate the internal chessboard corners. The function returns a non-zero value if all of the corners -are found and they are placed in a certain order (row by row, left to right in every row). -Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, -a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black -squares touch each other. The detected coordinates are approximate, and to determine their positions -more accurately, the function calls #cornerSubPix. You also may use the function #cornerSubPix with -different parameters if returned coordinates are not accurate enough. - -Sample usage of detecting and drawing chessboard corners: : -@code - Size patternsize(8,6); //interior number of corners - Mat gray = ....; //source image - vector corners; //this will be filled by the detected corners - - //CALIB_CB_FAST_CHECK saves a lot of time on images - //that do not contain any chessboard corners - bool patternfound = findChessboardCorners(gray, patternsize, corners, - CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE - + CALIB_CB_FAST_CHECK); - - if(patternfound) - cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), - TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); - - drawChessboardCorners(img, patternsize, Mat(corners), patternfound); -@endcode -@note The function requires white space (like a square-thick border, the wider the better) around -the board to make the detection more robust in various environments. Otherwise, if there is no -border and the background is dark, the outer black squares cannot be segmented properly and so the -square grouping and ordering algorithm fails. - -Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. - */ -CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, - int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE ); - -/* - Checks whether the image contains chessboard of the specific size or not. - If yes, nonzero value is returned. -*/ -CV_EXPORTS_W bool checkChessboard(InputArray img, Size size); - -/** @brief Finds the positions of internal corners of the chessboard using a sector based approach. - -@param image Source chessboard view. It must be an 8-bit grayscale or color image. -@param patternSize Number of inner corners per a chessboard row and column -( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). -@param corners Output array of detected corners. -@param flags Various operation flags that can be zero or a combination of the following values: -- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before detection. -- @ref CALIB_CB_EXHAUSTIVE Run an exhaustive search to improve detection rate. -- @ref CALIB_CB_ACCURACY Up sample input image to improve sub-pixel accuracy due to aliasing effects. -- @ref CALIB_CB_LARGER The detected pattern is allowed to be larger than patternSize (see description). -- @ref CALIB_CB_MARKER The detected pattern must have a marker (see description). -This should be used if an accurate camera calibration is required. -@param meta Optional output arrray of detected corners (CV_8UC1 and size = cv::Size(columns,rows)). -Each entry stands for one corner of the pattern and can have one of the following values: -- 0 = no meta data attached -- 1 = left-top corner of a black cell -- 2 = left-top corner of a white cell -- 3 = left-top corner of a black cell with a white marker dot -- 4 = left-top corner of a white cell with a black marker dot (pattern origin in case of markers otherwise first corner) - -The function is analog to #findChessboardCorners but uses a localized radon -transformation approximated by box filters being more robust to all sort of -noise, faster on larger images and is able to directly return the sub-pixel -position of the internal chessboard corners. The Method is based on the paper -@cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for -Calibration" demonstrating that the returned sub-pixel positions are more -accurate than the one returned by cornerSubPix allowing a precise camera -calibration for demanding applications. - -In the case, the flags @ref CALIB_CB_LARGER or @ref CALIB_CB_MARKER are given, -the result can be recovered from the optional meta array. Both flags are -helpful to use calibration patterns exceeding the field of view of the camera. -These oversized patterns allow more accurate calibrations as corners can be -utilized, which are as close as possible to the image borders. For a -consistent coordinate system across all images, the optional marker (see image -below) can be used to move the origin of the board to the location where the -black circle is located. - -@note The function requires a white boarder with roughly the same width as one -of the checkerboard fields around the whole board to improve the detection in -various environments. In addition, because of the localized radon -transformation it is beneficial to use round corners for the field corners -which are located on the outside of the board. The following figure illustrates -a sample checkerboard optimized for the detection. However, any other checkerboard -can be used as well. - -Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. -![Checkerboard](pics/checkerboard_radon.png) - */ -CV_EXPORTS_AS(findChessboardCornersSBWithMeta) -bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners, - int flags,OutputArray meta); -/** @overload */ -CV_EXPORTS_W inline -bool findChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners, - int flags = 0) -{ - return findChessboardCornersSB(image, patternSize, corners, flags, noArray()); -} - -/** @brief Estimates the sharpness of a detected chessboard. - -Image sharpness, as well as brightness, are a critical parameter for accuracte -camera calibration. For accessing these parameters for filtering out -problematic calibraiton images, this method calculates edge profiles by traveling from -black to white chessboard cell centers. Based on this, the number of pixels is -calculated required to transit from black to white. This width of the -transition area is a good indication of how sharp the chessboard is imaged -and should be below ~3.0 pixels. - -@param image Gray image used to find chessboard corners -@param patternSize Size of a found chessboard pattern -@param corners Corners found by #findChessboardCornersSB -@param rise_distance Rise distance 0.8 means 10% ... 90% of the final signal strength -@param vertical By default edge responses for horizontal lines are calculated -@param sharpness Optional output array with a sharpness value for calculated edge responses (see description) - -The optional sharpness array is of type CV_32FC1 and has for each calculated -profile one row with the following five entries: -* 0 = x coordinate of the underlying edge in the image -* 1 = y coordinate of the underlying edge in the image -* 2 = width of the transition area (sharpness) -* 3 = signal strength in the black cell (min brightness) -* 4 = signal strength in the white cell (max brightness) - -@return Scalar(average sharpness, average min brightness, average max brightness,0) -*/ -CV_EXPORTS_W Scalar estimateChessboardSharpness(InputArray image, Size patternSize, InputArray corners, - float rise_distance=0.8F,bool vertical=false, - OutputArray sharpness=noArray()); - - -//! finds subpixel-accurate positions of the chessboard corners -CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size ); - -/** @brief Renders the detected chessboard corners. - -@param image Destination image. It must be an 8-bit color image. -@param patternSize Number of inner corners per a chessboard row and column -(patternSize = cv::Size(points_per_row,points_per_column)). -@param corners Array of detected corners, the output of #findChessboardCorners. -@param patternWasFound Parameter indicating whether the complete board was found or not. The -return value of #findChessboardCorners should be passed here. - -The function draws individual chessboard corners detected either as red circles if the board was not -found, or as colored corners connected with lines if the board was found. - */ -CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize, - InputArray corners, bool patternWasFound ); - -/** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP - -@param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered. -@param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters. -\f$\cameramatrix{A}\f$ -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed. -@param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from -the model coordinate system to the camera coordinate system. -@param tvec Translation vector. -@param length Length of the painted axes in the same unit than tvec (usually in meters). -@param thickness Line thickness of the painted axes. - -This function draws the axes of the world/object coordinate system w.r.t. to the camera frame. -OX is drawn in red, OY in green and OZ in blue. - */ -CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, - InputArray rvec, InputArray tvec, float length, int thickness=3); - -struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters -{ - CV_WRAP CirclesGridFinderParameters(); - CV_PROP_RW cv::Size2f densityNeighborhoodSize; - CV_PROP_RW float minDensity; - CV_PROP_RW int kmeansAttempts; - CV_PROP_RW int minDistanceToAddKeypoint; - CV_PROP_RW int keypointScale; - CV_PROP_RW float minGraphConfidence; - CV_PROP_RW float vertexGain; - CV_PROP_RW float vertexPenalty; - CV_PROP_RW float existingVertexGain; - CV_PROP_RW float edgeGain; - CV_PROP_RW float edgePenalty; - CV_PROP_RW float convexHullFactor; - CV_PROP_RW float minRNGEdgeSwitchDist; - - enum GridType - { - SYMMETRIC_GRID, ASYMMETRIC_GRID - }; - GridType gridType; - - CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING. - CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING. -}; - -#ifndef DISABLE_OPENCV_3_COMPATIBILITY -typedef CirclesGridFinderParameters CirclesGridFinderParameters2; -#endif - -/** @brief Finds centers in the grid of circles. - -@param image grid view of input circles; it must be an 8-bit grayscale or color image. -@param patternSize number of circles per row and column -( patternSize = Size(points_per_row, points_per_colum) ). -@param centers output array of detected centers. -@param flags various operation flags that can be one of the following values: -- @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles. -- @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles. -- @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to -perspective distortions but much more sensitive to background clutter. -@param blobDetector feature detector that finds blobs like dark circles on light background. - If `blobDetector` is NULL then `image` represents Point2f array of candidates. -@param parameters struct for finding circles in a grid pattern. - -The function attempts to determine whether the input image contains a grid of circles. If it is, the -function locates centers of the circles. The function returns a non-zero value if all of the centers -have been found and they have been placed in a certain order (row by row, left to right in every -row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. - -Sample usage of detecting and drawing the centers of circles: : -@code - Size patternsize(7,7); //number of centers - Mat gray = ...; //source image - vector centers; //this will be filled by the detected centers - - bool patternfound = findCirclesGrid(gray, patternsize, centers); - - drawChessboardCorners(img, patternsize, Mat(centers), patternfound); -@endcode -@note The function requires white space (like a square-thick border, the wider the better) around -the board to make the detection more robust in various environments. - */ -CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, - OutputArray centers, int flags, - const Ptr &blobDetector, - const CirclesGridFinderParameters& parameters); - -/** @overload */ -CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, - OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID, - const Ptr &blobDetector = SimpleBlobDetector::create()); - -/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration -pattern. - -@param objectPoints In the new interface it is a vector of vectors of calibration pattern points in -the calibration pattern coordinate space (e.g. std::vector>). The outer -vector contains as many elements as the number of pattern views. If the same calibration pattern -is shown in each view and it is fully visible, all the vectors will be the same. Although, it is -possible to use partially occluded patterns or even different patterns in different views. Then, -the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's -XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig. -In the old interface all the vectors of object points from different views are concatenated -together. -@param imagePoints In the new interface it is a vector of vectors of the projections of calibration -pattern points (e.g. std::vector>). imagePoints.size() and -objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal, -respectively. In the old interface all the vectors of object points from different views are -concatenated together. -@param imageSize Size of the image used only to initialize the camera intrinsic matrix. -@param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix -\f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS -and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH -are specified, some or all of fx, fy, cx, cy must be initialized before calling the function. -@param distCoeffs Input/output vector of distortion coefficients -\f$\distcoeffs\f$. -@param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view -(e.g. std::vector>). That is, each i-th rotation vector together with the corresponding -i-th translation vector (see the next output parameter description) brings the calibration pattern -from the object coordinate space (in which object points are specified) to the camera coordinate -space. In more technical terms, the tuple of the i-th rotation and translation vector performs -a change of basis from object coordinate space to camera coordinate space. Due to its duality, this -tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate -space. -@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter -describtion above. -@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic -parameters. Order of deviations values: -\f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3, - s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero. -@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic -parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is -the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors. - @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. -@param flags Different flags that may be zero or a combination of the following values: -- @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of -fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image -center ( imageSize is used), and focal distances are computed in a least-squares fashion. -Note, that if intrinsic parameters are known, there is no need to use this function just to -estimate extrinsic parameters. Use @ref solvePnP instead. -- @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global -optimization. It stays at the center or at a different location specified when - @ref CALIB_USE_INTRINSIC_GUESS is set too. -- @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The -ratio fx/fy stays the same as in the input cameraMatrix . When - @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are -ignored, only their ratio is computed and used further. -- @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set -to zeros and stay zero. -- @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if - @ref CALIB_USE_INTRINSIC_GUESS is set. -- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion -coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is -set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the rational model and return 8 coefficients or more. -- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the thin prism model and return 12 coefficients or more. -- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the tilted sensor model and return 14 coefficients. -- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -@param criteria Termination criteria for the iterative optimization algorithm. - -@return the overall RMS re-projection error. - -The function estimates the intrinsic camera parameters and extrinsic parameters for each of the -views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object -points and their corresponding 2D projections in each view must be specified. That may be achieved -by using an object with known geometry and easily detectable feature points. Such an object is -called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as -a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic -parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration -patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also -be used as long as initial cameraMatrix is provided. - -The algorithm performs the following steps: - -- Compute the initial intrinsic parameters (the option only available for planar calibration - patterns) or read them from the input parameters. The distortion coefficients are all set to - zeros initially unless some of CALIB_FIX_K? are specified. - -- Estimate the initial camera pose as if the intrinsic parameters have been already known. This is - done using @ref solvePnP . - -- Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, - that is, the total sum of squared distances between the observed feature points imagePoints and - the projected (using the current estimates for camera parameters and the poses) object points - objectPoints. See @ref projectPoints for details. - -@note - If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration, - and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and - \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and - \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols) - instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners. - -@note - The function may throw exceptions, if unsupported combination of parameters is provided or - the system is underconstrained. - -@sa - calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, - undistort - */ -CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - OutputArray stdDeviationsIntrinsics, - OutputArray stdDeviationsExtrinsics, - OutputArray perViewErrors, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @overload */ -CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern. - -This function is an extension of #calibrateCamera with the method of releasing object which was -proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar -targets (calibration plates), this method can dramatically improve the precision of the estimated -camera parameters. Both the object-releasing method and standard method are supported by this -function. Use the parameter **iFixedPoint** for method selection. In the internal implementation, -#calibrateCamera is a wrapper for this function. - -@param objectPoints Vector of vectors of calibration pattern points in the calibration pattern -coordinate space. See #calibrateCamera for details. If the method of releasing object to be used, -the identical calibration board must be used in each view and it must be fully visible, and all -objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration -target has to be rigid, or at least static if the camera (rather than the calibration target) is -shifted for grabbing images.** -@param imagePoints Vector of vectors of the projections of calibration pattern points. See -#calibrateCamera for details. -@param imageSize Size of the image used only to initialize the intrinsic camera matrix. -@param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as -a switch for calibration method selection. If object-releasing method to be used, pass in the -parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will -make standard calibration method selected. Usually the top-right corner point of the calibration -board grid is recommended to be fixed when object-releasing method being utilized. According to -\cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front -and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and -newObjPoints are only possible if coordinates of these three fixed points are accurate enough. -@param cameraMatrix Output 3x3 floating-point camera matrix. See #calibrateCamera for details. -@param distCoeffs Output vector of distortion coefficients. See #calibrateCamera for details. -@param rvecs Output vector of rotation vectors estimated for each pattern view. See #calibrateCamera -for details. -@param tvecs Output vector of translation vectors estimated for each pattern view. -@param newObjPoints The updated output vector of calibration pattern points. The coordinates might -be scaled based on three fixed points. The returned coordinates are accurate only if the above -mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter -is ignored with standard calibration method. -@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters. -See #calibrateCamera for details. -@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters. -See #calibrateCamera for details. -@param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates -of calibration pattern points. It has the same size and order as objectPoints[0] vector. This -parameter is ignored with standard calibration method. - @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. -@param flags Different flags that may be zero or a combination of some predefined values. See -#calibrateCamera for details. If the method of releasing object is used, the calibration time may -be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially -less precise and less stable in some rare cases. -@param criteria Termination criteria for the iterative optimization algorithm. - -@return the overall RMS re-projection error. - -The function estimates the intrinsic camera parameters and extrinsic parameters for each of the -views. The algorithm is based on @cite Zhang2000, @cite BouguetMCT and @cite strobl2011iccv. See -#calibrateCamera for other detailed explanations. -@sa - calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort - */ -CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - OutputArray newObjPoints, - OutputArray stdDeviationsIntrinsics, - OutputArray stdDeviationsExtrinsics, - OutputArray stdDeviationsObjPoints, - OutputArray perViewErrors, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @overload */ -CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, - InputOutputArray cameraMatrix, InputOutputArray distCoeffs, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, - OutputArray newObjPoints, - int flags = 0, TermCriteria criteria = TermCriteria( - TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); - -/** @brief Computes useful camera characteristics from the camera intrinsic matrix. - -@param cameraMatrix Input camera intrinsic matrix that can be estimated by #calibrateCamera or -#stereoCalibrate . -@param imageSize Input image size in pixels. -@param apertureWidth Physical width in mm of the sensor. -@param apertureHeight Physical height in mm of the sensor. -@param fovx Output field of view in degrees along the horizontal sensor axis. -@param fovy Output field of view in degrees along the vertical sensor axis. -@param focalLength Focal length of the lens in mm. -@param principalPoint Principal point in mm. -@param aspectRatio \f$f_y/f_x\f$ - -The function computes various useful camera characteristics from the previously estimated camera -matrix. - -@note - Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for - the chessboard pitch (it can thus be any value). - */ -CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize, - double apertureWidth, double apertureHeight, - CV_OUT double& fovx, CV_OUT double& fovy, - CV_OUT double& focalLength, CV_OUT Point2d& principalPoint, - CV_OUT double& aspectRatio ); - -/** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters -for each of the two cameras and the extrinsic parameters between the two cameras. - -@param objectPoints Vector of vectors of the calibration pattern points. The same structure as -in @ref calibrateCamera. For each pattern view, both cameras need to see the same object -points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be -equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to -be equal for each i. -@param imagePoints1 Vector of vectors of the projections of the calibration pattern points, -observed by the first camera. The same structure as in @ref calibrateCamera. -@param imagePoints2 Vector of vectors of the projections of the calibration pattern points, -observed by the second camera. The same structure as in @ref calibrateCamera. -@param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in -@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. -@param distCoeffs1 Input/output vector of distortion coefficients, the same as in -@ref calibrateCamera. -@param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for -cameraMatrix1. -@param distCoeffs2 Input/output lens distortion coefficients for the second camera. See -description for distCoeffs1. -@param imageSize Size of the image used only to initialize the camera intrinsic matrices. -@param R Output rotation matrix. Together with the translation vector T, this matrix brings -points given in the first camera's coordinate system to points in the second camera's -coordinate system. In more technical terms, the tuple of R and T performs a change of basis -from the first camera's coordinate system to the second camera's coordinate system. Due to its -duality, this tuple is equivalent to the position of the first camera with respect to the -second camera coordinate system. -@param T Output translation vector, see description above. -@param E Output essential matrix. -@param F Output fundamental matrix. -@param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the -coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each -i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter -description) brings the calibration pattern from the object coordinate space (in which object points are -specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, -the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space -to camera coordinate space of the first camera of the stereo pair. -@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description -of previous output parameter ( rvecs ). -@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. -@param flags Different flags that may be zero or a combination of the following values: -- @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F -matrices are estimated. -- @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters -according to the specified flags. Initial values are provided by the user. -- @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further. -Otherwise R and T are initialized to the median value of the pattern views (each dimension separately). -- @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization. -- @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ . -- @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$ -. -- @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ . -- @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to -zeros and fix there. -- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial -distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, -the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward -compatibility, this extra flag should be explicitly specified to make the calibration -function use the rational model and return 8 coefficients. If the flag is not set, the -function computes and returns only 5 distortion coefficients. -- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the thin prism model and return 12 coefficients. If the flag is not -set, the function computes and returns only 5 distortion coefficients. -- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the -backward compatibility, this extra flag should be explicitly specified to make the -calibration function use the tilted sensor model and return 14 coefficients. If the flag is not -set, the function computes and returns only 5 distortion coefficients. -- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during -the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the -supplied distCoeffs matrix is used. Otherwise, it is set to 0. -@param criteria Termination criteria for the iterative optimization algorithm. - -The function estimates the transformation between two cameras making a stereo pair. If one computes -the poses of an object relative to the first camera and to the second camera, -( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the -relative position and orientation between the two cameras are fixed, then those poses definitely -relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the -two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is -given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that: - -\f[R_2=R R_1\f] -\f[T_2=R T_1 + T.\f] - -Therefore, one can compute the coordinate representation of a 3D point for the second camera's -coordinate system when given the point's coordinate representation in the first camera's coordinate -system: - -\f[\begin{bmatrix} -X_2 \\ -Y_2 \\ -Z_2 \\ -1 -\end{bmatrix} = \begin{bmatrix} -R & T \\ -0 & 1 -\end{bmatrix} \begin{bmatrix} -X_1 \\ -Y_1 \\ -Z_1 \\ -1 -\end{bmatrix}.\f] - - -Optionally, it computes the essential matrix E: - -\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f] - -where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ . -And the function can also compute the fundamental matrix F: - -\f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f] - -Besides the stereo-related information, the function can also perform a full calibration of each of -the two cameras. However, due to the high dimensionality of the parameter space and noise in the -input data, the function can diverge from the correct solution. If the intrinsic parameters can be -estimated with high accuracy for each of the cameras individually (for example, using -#calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the -function along with the computed intrinsic parameters. Otherwise, if all the parameters are -estimated at once, it makes sense to restrict some parameters, for example, pass - @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a -reasonable assumption. - -Similarly to #calibrateCamera, the function minimizes the total re-projection error for all the -points in all the available views from both cameras. The function returns the final value of the -re-projection error. - */ -CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, - OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); - -/// @overload -CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F, - int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); - -/// @overload -CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, - InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, - InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, - Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, - OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); - -/** @brief Computes rectification transforms for each head of a calibrated stereo camera. - -@param cameraMatrix1 First camera intrinsic matrix. -@param distCoeffs1 First camera distortion parameters. -@param cameraMatrix2 Second camera intrinsic matrix. -@param distCoeffs2 Second camera distortion parameters. -@param imageSize Size of the image used for stereo calibration. -@param R Rotation matrix from the coordinate system of the first camera to the second camera, -see @ref stereoCalibrate. -@param T Translation vector from the coordinate system of the first camera to the second camera, -see @ref stereoCalibrate. -@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix -brings points given in the unrectified first camera's coordinate system to points in the rectified -first camera's coordinate system. In more technical terms, it performs a change of basis from the -unrectified first camera's coordinate system to the rectified first camera's coordinate system. -@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix -brings points given in the unrectified second camera's coordinate system to points in the rectified -second camera's coordinate system. In more technical terms, it performs a change of basis from the -unrectified second camera's coordinate system to the rectified second camera's coordinate system. -@param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first -camera, i.e. it projects points given in the rectified first camera coordinate system into the -rectified first camera's image. -@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second -camera, i.e. it projects points given in the rectified first camera coordinate system into the -rectified second camera's image. -@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D). -@param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set, -the function makes the principal points of each camera have the same pixel coordinates in the -rectified views. And if the flag is not set, the function may still shift the images in the -horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the -useful image area. -@param alpha Free scaling parameter. If it is -1 or absent, the function performs the default -scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified -images are zoomed and shifted so that only valid pixels are visible (no black areas after -rectification). alpha=1 means that the rectified image is decimated and shifted so that all the -pixels from the original images from the cameras are retained in the rectified images (no source -image pixels are lost). Any intermediate value yields an intermediate result between -those two extreme cases. -@param newImageSize New image resolution after rectification. The same size should be passed to -#initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) -is passed (default), it is set to the original imageSize . Setting it to a larger value can help you -preserve details in the original image, especially when there is a big radial distortion. -@param validPixROI1 Optional output rectangles inside the rectified images where all the pixels -are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller -(see the picture below). -@param validPixROI2 Optional output rectangles inside the rectified images where all the pixels -are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller -(see the picture below). - -The function computes the rotation matrices for each camera that (virtually) make both camera image -planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies -the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate -as input. As output, it provides two rotation matrices and also two projection matrices in the new -coordinates. The function distinguishes the following two cases: - -- **Horizontal stereo**: the first and the second camera views are shifted relative to each other - mainly along the x-axis (with possible small vertical shift). In the rectified images, the - corresponding epipolar lines in the left and right cameras are horizontal and have the same - y-coordinate. P1 and P2 look like: - - \f[\texttt{P1} = \begin{bmatrix} - f & 0 & cx_1 & 0 \\ - 0 & f & cy & 0 \\ - 0 & 0 & 1 & 0 - \end{bmatrix}\f] - - \f[\texttt{P2} = \begin{bmatrix} - f & 0 & cx_2 & T_x \cdot f \\ - 0 & f & cy & 0 \\ - 0 & 0 & 1 & 0 - \end{bmatrix} ,\f] - - \f[\texttt{Q} = \begin{bmatrix} - 1 & 0 & 0 & -cx_1 \\ - 0 & 1 & 0 & -cy \\ - 0 & 0 & 0 & f \\ - 0 & 0 & -\frac{1}{T_x} & \frac{cx_1 - cx_2}{T_x} - \end{bmatrix} \f] - - where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if - @ref CALIB_ZERO_DISPARITY is set. - -- **Vertical stereo**: the first and the second camera views are shifted relative to each other - mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar - lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like: - - \f[\texttt{P1} = \begin{bmatrix} - f & 0 & cx & 0 \\ - 0 & f & cy_1 & 0 \\ - 0 & 0 & 1 & 0 - \end{bmatrix}\f] - - \f[\texttt{P2} = \begin{bmatrix} - f & 0 & cx & 0 \\ - 0 & f & cy_2 & T_y \cdot f \\ - 0 & 0 & 1 & 0 - \end{bmatrix},\f] - - \f[\texttt{Q} = \begin{bmatrix} - 1 & 0 & 0 & -cx \\ - 0 & 1 & 0 & -cy_1 \\ - 0 & 0 & 0 & f \\ - 0 & 0 & -\frac{1}{T_y} & \frac{cy_1 - cy_2}{T_y} - \end{bmatrix} \f] - - where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if - @ref CALIB_ZERO_DISPARITY is set. - -As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera -matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to -initialize the rectification map for each camera. - -See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through -the corresponding image regions. This means that the images are well rectified, which is what most -stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that -their interiors are all valid pixels. - -![image](pics/stereo_undistort.jpg) - */ -CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - Size imageSize, InputArray R, InputArray T, - OutputArray R1, OutputArray R2, - OutputArray P1, OutputArray P2, - OutputArray Q, int flags = CALIB_ZERO_DISPARITY, - double alpha = -1, Size newImageSize = Size(), - CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 ); - -/** @brief Computes a rectification transform for an uncalibrated stereo camera. - -@param points1 Array of feature points in the first image. -@param points2 The corresponding points in the second image. The same formats as in -#findFundamentalMat are supported. -@param F Input fundamental matrix. It can be computed from the same set of point pairs using -#findFundamentalMat . -@param imgSize Size of the image. -@param H1 Output rectification homography matrix for the first image. -@param H2 Output rectification homography matrix for the second image. -@param threshold Optional threshold used to filter out the outliers. If the parameter is greater -than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points -for which \f$|\texttt{points2[i]}^T \cdot \texttt{F} \cdot \texttt{points1[i]}|>\texttt{threshold}\f$ ) -are rejected prior to computing the homographies. Otherwise, all the points are considered inliers. - -The function computes the rectification transformations without knowing intrinsic parameters of the -cameras and their relative position in the space, which explains the suffix "uncalibrated". Another -related difference from #stereoRectify is that the function outputs not the rectification -transformations in the object (3D) space, but the planar perspective transformations encoded by the -homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 . - -@note - While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily - depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, - it would be better to correct it before computing the fundamental matrix and calling this - function. For example, distortion coefficients can be estimated for each head of stereo camera - separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or - just the point coordinates can be corrected with #undistortPoints . - */ -CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2, - InputArray F, Size imgSize, - OutputArray H1, OutputArray H2, - double threshold = 5 ); - -//! computes the rectification transformations for 3-head camera, where all the heads are on the same line. -CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - InputArray cameraMatrix3, InputArray distCoeffs3, - InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3, - Size imageSize, InputArray R12, InputArray T12, - InputArray R13, InputArray T13, - OutputArray R1, OutputArray R2, OutputArray R3, - OutputArray P1, OutputArray P2, OutputArray P3, - OutputArray Q, double alpha, Size newImgSize, - CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); - -/** @brief Returns the new camera intrinsic matrix based on the free scaling parameter. - -@param cameraMatrix Input camera intrinsic matrix. -@param distCoeffs Input vector of distortion coefficients -\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are -assumed. -@param imageSize Original image size. -@param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are -valid) and 1 (when all the source image pixels are retained in the undistorted image). See -#stereoRectify for details. -@param newImgSize Image size after rectification. By default, it is set to imageSize . -@param validPixROI Optional output rectangle that outlines all-good-pixels region in the -undistorted image. See roi1, roi2 description in #stereoRectify . -@param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the -principal point should be at the image center or not. By default, the principal point is chosen to -best fit a subset of the source image (determined by alpha) to the corrected image. -@return new_camera_matrix Output new camera intrinsic matrix. - -The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter. -By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original -image pixels if there is valuable information in the corners alpha=1 , or get something in between. -When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to -"virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion -coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to -#initUndistortRectifyMap to produce the maps for #remap . - */ -CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, double alpha, Size newImgSize = Size(), - CV_OUT Rect* validPixROI = 0, - bool centerPrincipalPoint = false); - -/** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$ - -@param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from gripper frame to robot base frame. -@param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from gripper frame to robot base frame. -@param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from calibration target frame to camera frame. -@param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from calibration target frame to camera frame. -@param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point -expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). -@param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point -expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). -@param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod - -The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the -rotation then the translation (separable solutions) and the following methods are implemented: - - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89 - - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94 - - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95 - -Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), -with the following implemented methods: - - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99 - - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98 - -The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye") -mounted on a robot gripper ("hand") has to be estimated. This configuration is called eye-in-hand. - -The eye-to-hand configuration consists in a static camera observing a calibration pattern mounted on the robot -end-effector. The transformation from the camera to the robot base frame can then be estimated by inputting -the suitable transformations to the function, see below. - -![](pics/hand-eye_figure.png) - -The calibration procedure is the following: - - a static calibration pattern is used to estimate the transformation between the target frame - and the camera frame - - the robot gripper is moved in order to acquire several poses - - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for - instance the robot kinematics -\f[ - \begin{bmatrix} - X_b\\ - Y_b\\ - Z_b\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} -\f] - - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using - for instance a pose estimation method (PnP) from 2D-3D point correspondences -\f[ - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_t\\ - Y_t\\ - Z_t\\ - 1 - \end{bmatrix} -\f] - -The Hand-Eye calibration procedure returns the following homogeneous transformation -\f[ - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} -\f] - -This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation: - - for an eye-in-hand configuration -\f[ - \begin{align*} - ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= - \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ - - (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &= - \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ - - \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ - \end{align*} -\f] - - - for an eye-to-hand configuration -\f[ - \begin{align*} - ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= - \hspace{0.1em} ^{g}{\textrm{T}_b}^{(2)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ - - (^{g}{\textrm{T}_b}^{(2)})^{-1} \hspace{0.2em} ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c &= - \hspace{0.1em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ - - \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ - \end{align*} -\f] - -\note -Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration). -\note -A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation. -So at least 3 different poses are required, but it is strongly recommended to use many more poses. - - */ -CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base, - InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam, - OutputArray R_cam2gripper, OutputArray t_cam2gripper, - HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI ); - -/** @brief Computes Robot-World/Hand-Eye calibration: \f$_{}^{w}\textrm{T}_b\f$ and \f$_{}^{c}\textrm{T}_g\f$ - -@param[in] R_world2cam Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from world frame to the camera frame. -@param[in] t_world2cam Translation part extracted from the homogeneous matrix that transforms a point -expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from world frame to the camera frame. -@param[in] R_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). -This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, -for all the transformations from robot base frame to the gripper frame. -@param[in] t_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). -This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations -from robot base frame to the gripper frame. -@param[out] R_base2world Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). -@param[out] t_base2world Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point -expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). -@param[out] R_gripper2cam Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). -@param[out] t_gripper2cam Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point -expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). -@param[in] method One of the implemented Robot-World/Hand-Eye calibration method, see cv::RobotWorldHandEyeCalibrationMethod - -The function performs the Robot-World/Hand-Eye calibration using various methods. One approach consists in estimating the -rotation then the translation (separable solutions): - - M. Shah, Solving the robot-world/hand-eye calibration problem using the kronecker product \cite Shah2013SolvingTR - -Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), -with the following implemented method: - - A. Li, L. Wang, and D. Wu, Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product \cite Li2010SimultaneousRA - -The following picture describes the Robot-World/Hand-Eye calibration problem where the transformations between a robot and a world frame -and between a robot gripper ("hand") and a camera ("eye") mounted at the robot end-effector have to be estimated. - -![](pics/robot-world_hand-eye_figure.png) - -The calibration procedure is the following: - - a static calibration pattern is used to estimate the transformation between the target frame - and the camera frame - - the robot gripper is moved in order to acquire several poses - - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for - instance the robot kinematics -\f[ - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{g}\textrm{R}_b & _{}^{g}\textrm{t}_b \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_b\\ - Y_b\\ - Z_b\\ - 1 - \end{bmatrix} -\f] - - for each pose, the homogeneous transformation between the calibration target frame (the world frame) and the camera frame is recorded using - for instance a pose estimation method (PnP) from 2D-3D point correspondences -\f[ - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{c}\textrm{R}_w & _{}^{c}\textrm{t}_w \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_w\\ - Y_w\\ - Z_w\\ - 1 - \end{bmatrix} -\f] - -The Robot-World/Hand-Eye calibration procedure returns the following homogeneous transformations -\f[ - \begin{bmatrix} - X_w\\ - Y_w\\ - Z_w\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{w}\textrm{R}_b & _{}^{w}\textrm{t}_b \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_b\\ - Y_b\\ - Z_b\\ - 1 - \end{bmatrix} -\f] -\f[ - \begin{bmatrix} - X_c\\ - Y_c\\ - Z_c\\ - 1 - \end{bmatrix} - = - \begin{bmatrix} - _{}^{c}\textrm{R}_g & _{}^{c}\textrm{t}_g \\ - 0_{1 \times 3} & 1 - \end{bmatrix} - \begin{bmatrix} - X_g\\ - Y_g\\ - Z_g\\ - 1 - \end{bmatrix} -\f] - -This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{Z}\mathbf{B}\f$ equation, with: - - \f$\mathbf{A} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_w\f$ - - \f$\mathbf{X} \Leftrightarrow \hspace{0.1em} _{}^{w}\textrm{T}_b\f$ - - \f$\mathbf{Z} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_g\f$ - - \f$\mathbf{B} \Leftrightarrow \hspace{0.1em} _{}^{g}\textrm{T}_b\f$ - -\note -At least 3 measurements are required (input vectors size must be greater or equal to 3). - - */ -CV_EXPORTS_W void calibrateRobotWorldHandEye( InputArrayOfArrays R_world2cam, InputArrayOfArrays t_world2cam, - InputArrayOfArrays R_base2gripper, InputArrayOfArrays t_base2gripper, - OutputArray R_base2world, OutputArray t_base2world, - OutputArray R_gripper2cam, OutputArray t_gripper2cam, - RobotWorldHandEyeCalibrationMethod method=CALIB_ROBOT_WORLD_HAND_EYE_SHAH ); - -/** @brief Converts points from Euclidean to homogeneous space. - -@param src Input vector of N-dimensional points. -@param dst Output vector of N+1-dimensional points. - -The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of -point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1). - */ -CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); - -/** @brief Converts points from homogeneous to Euclidean space. - -@param src Input vector of N-dimensional points. -@param dst Output vector of N-1-dimensional points. - -The function converts points homogeneous to Euclidean space using perspective projection. That is, -each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the -output point coordinates will be (0,0,0,...). - */ -CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); - -/** @brief Converts points to/from homogeneous coordinates. - -@param src Input array or vector of 2D, 3D, or 4D points. -@param dst Output vector of 2D, 3D, or 4D points. - -The function converts 2D or 3D points from/to homogeneous coordinates by calling either -#convertPointsToHomogeneous or #convertPointsFromHomogeneous. - -@note The function is obsolete. Use one of the previous two functions instead. - */ -CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); - -/** @brief Calculates a fundamental matrix from the corresponding points in two images. - -@param points1 Array of N points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param method Method for computing a fundamental matrix. -- @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$ -- @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$ -- @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$ -- @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$ -@param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level -of confidence (probability) that the estimated matrix is correct. -@param[out] mask optional output mask -@param maxIters The maximum number of robust method iterations. - -The epipolar geometry is described by the following equation: - -\f[[p_2; 1]^T F [p_1; 1] = 0\f] - -where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the -second images, respectively. - -The function calculates the fundamental matrix using one of four methods listed above and returns -the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point -algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3 -matrices sequentially). - -The calculated fundamental matrix may be passed further to #computeCorrespondEpilines that finds the -epipolar lines corresponding to the specified points. It can also be passed to -#stereoRectifyUncalibrated to compute the rectification transformation. : -@code - // Example. Estimation of fundamental matrix using the RANSAC algorithm - int point_count = 100; - vector points1(point_count); - vector points2(point_count); - - // initialize the points here ... - for( int i = 0; i < point_count; i++ ) - { - points1[i] = ...; - points2[i] = ...; - } - - Mat fundamental_matrix = - findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); -@endcode - */ -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - int method, double ransacReprojThreshold, double confidence, - int maxIters, OutputArray mask = noArray() ); - -/** @overload */ -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - int method = FM_RANSAC, - double ransacReprojThreshold = 3., double confidence = 0.99, - OutputArray mask = noArray() ); - -/** @overload */ -CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, - OutputArray mask, int method = FM_RANSAC, - double ransacReprojThreshold = 3., double confidence = 0.99 ); - - -CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, - OutputArray mask, const UsacParams ¶ms); - -/** @brief Calculates an essential matrix from the corresponding points in two images. - -@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should -be floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1. -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -Note that this function assumes that points1 and points2 are feature points from cameras with the -same camera intrinsic matrix. If this assumption does not hold for your use case, use another -function overload or #undistortPoints with `P = cv::NoArray()` for both cameras to transform image -points to normalized image coordinates, which are valid for the identity camera intrinsic matrix. -When passing these coordinates, pass the identity matrix for this parameter. -@param method Method for computing an essential matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 -for the other points. The array is computed only in the RANSAC and LMedS methods. -@param maxIters The maximum number of robust method iterations. - -This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . -@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: - -\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] - -where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the -second images, respectively. The result of this function may be passed further to -#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. - */ -CV_EXPORTS_W -Mat findEssentialMat( - InputArray points1, InputArray points2, - InputArray cameraMatrix, int method = RANSAC, - double prob = 0.999, double threshold = 1.0, - int maxIters = 1000, OutputArray mask = noArray() -); - -/** @overload */ -CV_EXPORTS -Mat findEssentialMat( - InputArray points1, InputArray points2, - InputArray cameraMatrix, int method, - double prob, double threshold, - OutputArray mask -); // TODO remove from OpenCV 5.0 - -/** @overload -@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should -be floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param focal focal length of the camera. Note that this function assumes that points1 and points2 -are feature points from cameras with same focal length and principal point. -@param pp principal point of the camera. -@param method Method for computing a fundamental matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 -for the other points. The array is computed only in the RANSAC and LMedS methods. -@param maxIters The maximum number of robust method iterations. - -This function differs from the one above that it computes camera intrinsic matrix from focal length and -principal point: - -\f[A = -\begin{bmatrix} -f & 0 & x_{pp} \\ -0 & f & y_{pp} \\ -0 & 0 & 1 -\end{bmatrix}\f] - */ -CV_EXPORTS_W -Mat findEssentialMat( - InputArray points1, InputArray points2, - double focal = 1.0, Point2d pp = Point2d(0, 0), - int method = RANSAC, double prob = 0.999, - double threshold = 1.0, int maxIters = 1000, - OutputArray mask = noArray() -); - -/** @overload */ -CV_EXPORTS -Mat findEssentialMat( - InputArray points1, InputArray points2, - double focal, Point2d pp, - int method, double prob, - double threshold, OutputArray mask -); // TODO remove from OpenCV 5.0 - -/** @brief Calculates an essential matrix from the corresponding points in two images from potentially two different cameras. - -@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should -be floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1. -@param cameraMatrix1 Camera matrix for the first camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param cameraMatrix2 Camera matrix for the second camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs1 Input vector of distortion coefficients for the first camera -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param distCoeffs2 Input vector of distortion coefficients for the second camera -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param method Method for computing an essential matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 -for the other points. The array is computed only in the RANSAC and LMedS methods. - -This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . -@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: - -\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] - -where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the -second images, respectively. The result of this function may be passed further to -#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. - */ -CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, - InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - int method = RANSAC, - double prob = 0.999, double threshold = 1.0, - OutputArray mask = noArray() ); - - -CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, - InputArray cameraMatrix1, InputArray cameraMatrix2, - InputArray dist_coeff1, InputArray dist_coeff2, OutputArray mask, - const UsacParams ¶ms); - -/** @brief Decompose an essential matrix to possible rotations and translation. - -@param E The input essential matrix. -@param R1 One possible rotation matrix. -@param R2 Another possible rotation matrix. -@param t One possible translation. - -This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In -general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$, -\f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$. - -If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image -points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples -\f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first -camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one -can only get the direction of the translation. For this reason, the translation t is returned with -unit length. - */ -CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t ); - -/** @brief Recovers the relative camera rotation and the translation from corresponding points in two images from two different cameras, using cheirality check. Returns the number of -inliers that pass the check. - -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param cameraMatrix1 Input/output camera matrix for the first camera, the same as in -@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. -@param distCoeffs1 Input/output vector of distortion coefficients, the same as in -@ref calibrateCamera. -@param cameraMatrix2 Input/output camera matrix for the first camera, the same as in -@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. -@param distCoeffs2 Input/output vector of distortion coefficients, the same as in -@ref calibrateCamera. -@param E The output essential matrix. -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -described below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param method Method for computing an essential matrix. -- @ref RANSAC for the RANSAC algorithm. -- @ref LMEDS for the LMedS algorithm. -@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of -confidence (probability) that the estimated matrix is correct. -@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar -line in pixels, beyond which the point is considered an outlier and is not used for computing the -final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the -point localization, image resolution, and the image noise. -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the cheirality check. - -This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies -possible pose hypotheses by doing cheirality check. The cheirality check means that the -triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. - -This function can be used to process the output E and mask from @ref findEssentialMat. In this -scenario, points1 and points2 are the same input for findEssentialMat.: -@code - // Example. Estimation of fundamental matrix using the RANSAC algorithm - int point_count = 100; - vector points1(point_count); - vector points2(point_count); - - // initialize the points here ... - for( int i = 0; i < point_count; i++ ) - { - points1[i] = ...; - points2[i] = ...; - } - - // Input: camera calibration of both cameras, for example using intrinsic chessboard calibration. - Mat cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2; - - // Output: Essential matrix, relative rotation and relative translation. - Mat E, R, t, mask; - - recoverPose(points1, points2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, E, R, t, mask); -@endcode - */ -CV_EXPORTS_W int recoverPose( InputArray points1, InputArray points2, - InputArray cameraMatrix1, InputArray distCoeffs1, - InputArray cameraMatrix2, InputArray distCoeffs2, - OutputArray E, OutputArray R, OutputArray t, - int method = cv::RANSAC, double prob = 0.999, double threshold = 1.0, - InputOutputArray mask = noArray()); - -/** @brief Recovers the relative camera rotation and the translation from an estimated essential -matrix and the corresponding points in two images, using chirality check. Returns the number of -inliers that pass the check. - -@param E The input essential matrix. -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -Note that this function assumes that points1 and points2 are feature points from cameras with the -same camera intrinsic matrix. -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -described below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the chirality check. - -This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies -possible pose hypotheses by doing chirality check. The chirality check means that the -triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. - -This function can be used to process the output E and mask from @ref findEssentialMat. In this -scenario, points1 and points2 are the same input for #findEssentialMat : -@code - // Example. Estimation of fundamental matrix using the RANSAC algorithm - int point_count = 100; - vector points1(point_count); - vector points2(point_count); - - // initialize the points here ... - for( int i = 0; i < point_count; i++ ) - { - points1[i] = ...; - points2[i] = ...; - } - - // cametra matrix with both focal lengths = 1, and principal point = (0, 0) - Mat cameraMatrix = Mat::eye(3, 3, CV_64F); - - Mat E, R, t, mask; - - E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask); - recoverPose(E, points1, points2, cameraMatrix, R, t, mask); -@endcode - */ -CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, - InputArray cameraMatrix, OutputArray R, OutputArray t, - InputOutputArray mask = noArray() ); - -/** @overload -@param E The input essential matrix. -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1 . -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -description below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param focal Focal length of the camera. Note that this function assumes that points1 and points2 -are feature points from cameras with same focal length and principal point. -@param pp principal point of the camera. -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the chirality check. - -This function differs from the one above that it computes camera intrinsic matrix from focal length and -principal point: - -\f[A = -\begin{bmatrix} -f & 0 & x_{pp} \\ -0 & f & y_{pp} \\ -0 & 0 & 1 -\end{bmatrix}\f] - */ -CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, - OutputArray R, OutputArray t, - double focal = 1.0, Point2d pp = Point2d(0, 0), - InputOutputArray mask = noArray() ); - -/** @overload -@param E The input essential matrix. -@param points1 Array of N 2D points from the first image. The point coordinates should be -floating-point (single or double precision). -@param points2 Array of the second image points of the same size and format as points1. -@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . -Note that this function assumes that points1 and points2 are feature points from cameras with the -same camera intrinsic matrix. -@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple -that performs a change of basis from the first camera's coordinate system to the second camera's -coordinate system. Note that, in general, t can not be used for this tuple, see the parameter -description below. -@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and -therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit -length. -@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite -points). -@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks -inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to -recover pose. In the output mask only inliers which pass the chirality check. -@param triangulatedPoints 3D points which were reconstructed by triangulation. - -This function differs from the one above that it outputs the triangulated 3D point that are used for -the chirality check. - */ -CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, - InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(), - OutputArray triangulatedPoints = noArray()); - -/** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image. - -@param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or -vector\ . -@param whichImage Index of the image (1 or 2) that contains the points . -@param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify . -@param lines Output vector of the epipolar lines corresponding to the points in the other image. -Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ . - -For every point in one of the two images of a stereo pair, the function finds the equation of the -corresponding epipolar line in the other image. - -From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second -image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as: - -\f[l^{(2)}_i = F p^{(1)}_i\f] - -And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as: - -\f[l^{(1)}_i = F^T p^{(2)}_i\f] - -Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ . - */ -CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage, - InputArray F, OutputArray lines ); - -/** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using -their observations with a stereo camera. - -@param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points -given in the world's coordinate system into the first image. -@param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points -given in the world's coordinate system into the second image. -@param projPoints1 2xN array of feature points in the first image. In the case of the c++ version, -it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. -@param projPoints2 2xN array of corresponding points in the second image. In the case of the c++ -version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. -@param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are -returned in the world's coordinate system. - -@note - Keep in mind that all input data should be of float type in order for this function to work. - -@note - If the projection matrices from @ref stereoRectify are used, then the returned points are - represented in the first camera's rectified coordinate system. - -@sa - reprojectImageTo3D - */ -CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, - InputArray projPoints1, InputArray projPoints2, - OutputArray points4D ); - -/** @brief Refines coordinates of corresponding points. - -@param F 3x3 fundamental matrix. -@param points1 1xN array containing the first set of points. -@param points2 1xN array containing the second set of points. -@param newPoints1 The optimized points1. -@param newPoints2 The optimized points2. - -The function implements the Optimal Triangulation Method (see Multiple View Geometry @cite HartleyZ00 for details). -For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it -computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric -error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the -geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint -\f$newPoints2^T \cdot F \cdot newPoints1 = 0\f$ . - */ -CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, - OutputArray newPoints1, OutputArray newPoints2 ); - -/** @brief Filters off small noise blobs (speckles) in the disparity map - -@param img The input 16-bit signed disparity image -@param newVal The disparity value used to paint-off the speckles -@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not -affected by the algorithm -@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same -blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point -disparity map, where disparity values are multiplied by 16, this scale factor should be taken into -account when specifying this parameter value. -@param buf The optional temporary buffer to avoid memory allocation within the function. - */ -CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, - int maxSpeckleSize, double maxDiff, - InputOutputArray buf = noArray() ); - -//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by #stereoRectify) -CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2, - int minDisparity, int numberOfDisparities, - int blockSize ); - -//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm -CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost, - int minDisparity, int numberOfDisparities, - int disp12MaxDisp = 1 ); - -/** @brief Reprojects a disparity image to 3D space. - -@param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit -floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no -fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or -@ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before -being used here. -@param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of -_3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one -uses Q obtained by @ref stereoRectify, then the returned points are represented in the first -camera's rectified coordinate system. -@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with -@ref stereoRectify. -@param handleMissingValues Indicates, whether the function should handle missing values (i.e. -points where the disparity was not computed). If handleMissingValues=true, then pixels with the -minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed -to 3D points with a very large Z value (currently set to 10000). -@param ddepth The optional output array depth. If it is -1, the output image will have CV_32F -depth. ddepth can also be set to CV_16S, CV_32S or CV_32F. - -The function transforms a single-channel disparity map to a 3-channel image representing a 3D -surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it -computes: - -\f[\begin{bmatrix} -X \\ -Y \\ -Z \\ -W -\end{bmatrix} = Q \begin{bmatrix} -x \\ -y \\ -\texttt{disparity} (x,y) \\ -1 -\end{bmatrix}.\f] - -@sa - To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform. - */ -CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, - OutputArray _3dImage, InputArray Q, - bool handleMissingValues = false, - int ddepth = -1 ); - -/** @brief Calculates the Sampson Distance between two points. - -The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as: -\f[ -sd( \texttt{pt1} , \texttt{pt2} )= -\frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2} -{((\texttt{F} \cdot \texttt{pt1})(0))^2 + -((\texttt{F} \cdot \texttt{pt1})(1))^2 + -((\texttt{F}^t \cdot \texttt{pt2})(0))^2 + -((\texttt{F}^t \cdot \texttt{pt2})(1))^2} -\f] -The fundamental matrix may be calculated using the #findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details. -@param pt1 first homogeneous 2d point -@param pt2 second homogeneous 2d point -@param F fundamental matrix -@return The computed Sampson distance. -*/ -CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F); - -/** @brief Computes an optimal affine transformation between two 3D point sets. - -It computes -\f[ -\begin{bmatrix} -x\\ -y\\ -z\\ -\end{bmatrix} -= -\begin{bmatrix} -a_{11} & a_{12} & a_{13}\\ -a_{21} & a_{22} & a_{23}\\ -a_{31} & a_{32} & a_{33}\\ -\end{bmatrix} -\begin{bmatrix} -X\\ -Y\\ -Z\\ -\end{bmatrix} -+ -\begin{bmatrix} -b_1\\ -b_2\\ -b_3\\ -\end{bmatrix} -\f] - -@param src First input 3D point set containing \f$(X,Y,Z)\f$. -@param dst Second input 3D point set containing \f$(x,y,z)\f$. -@param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form -\f[ -\begin{bmatrix} -a_{11} & a_{12} & a_{13} & b_1\\ -a_{21} & a_{22} & a_{23} & b_2\\ -a_{31} & a_{32} & a_{33} & b_3\\ -\end{bmatrix} -\f] -@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). -@param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as -an inlier. -@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything -between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation -significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. - -The function estimates an optimal 3D affine transformation between two 3D point sets using the -RANSAC algorithm. - */ -CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, - OutputArray out, OutputArray inliers, - double ransacThreshold = 3, double confidence = 0.99); - -/** @brief Computes an optimal affine transformation between two 3D point sets. - -It computes \f$R,s,t\f$ minimizing \f$\sum{i} dst_i - c \cdot R \cdot src_i \f$ -where \f$R\f$ is a 3x3 rotation matrix, \f$t\f$ is a 3x1 translation vector and \f$s\f$ is a -scalar size value. This is an implementation of the algorithm by Umeyama \cite umeyama1991least . -The estimated affine transform has a homogeneous scale which is a subclass of affine -transformations with 7 degrees of freedom. The paired point sets need to comprise at least 3 -points each. - -@param src First input 3D point set. -@param dst Second input 3D point set. -@param scale If null is passed, the scale parameter c will be assumed to be 1.0. -Else the pointed-to variable will be set to the optimal scale. -@param force_rotation If true, the returned rotation will never be a reflection. -This might be unwanted, e.g. when optimizing a transform between a right- and a -left-handed coordinate system. -@return 3D affine transformation matrix \f$3 \times 4\f$ of the form -\f[T = -\begin{bmatrix} -R & t\\ -\end{bmatrix} -\f] - - */ -CV_EXPORTS_W cv::Mat estimateAffine3D(InputArray src, InputArray dst, - CV_OUT double* scale = nullptr, bool force_rotation = true); - -/** @brief Computes an optimal translation between two 3D point sets. - * - * It computes - * \f[ - * \begin{bmatrix} - * x\\ - * y\\ - * z\\ - * \end{bmatrix} - * = - * \begin{bmatrix} - * X\\ - * Y\\ - * Z\\ - * \end{bmatrix} - * + - * \begin{bmatrix} - * b_1\\ - * b_2\\ - * b_3\\ - * \end{bmatrix} - * \f] - * - * @param src First input 3D point set containing \f$(X,Y,Z)\f$. - * @param dst Second input 3D point set containing \f$(x,y,z)\f$. - * @param out Output 3D translation vector \f$3 \times 1\f$ of the form - * \f[ - * \begin{bmatrix} - * b_1 \\ - * b_2 \\ - * b_3 \\ - * \end{bmatrix} - * \f] - * @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). - * @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as - * an inlier. - * @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything - * between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation - * significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. - * - * The function estimates an optimal 3D translation between two 3D point sets using the - * RANSAC algorithm. - * */ -CV_EXPORTS_W int estimateTranslation3D(InputArray src, InputArray dst, - OutputArray out, OutputArray inliers, - double ransacThreshold = 3, double confidence = 0.99); - -/** @brief Computes an optimal affine transformation between two 2D point sets. - -It computes -\f[ -\begin{bmatrix} -x\\ -y\\ -\end{bmatrix} -= -\begin{bmatrix} -a_{11} & a_{12}\\ -a_{21} & a_{22}\\ -\end{bmatrix} -\begin{bmatrix} -X\\ -Y\\ -\end{bmatrix} -+ -\begin{bmatrix} -b_1\\ -b_2\\ -\end{bmatrix} -\f] - -@param from First input 2D point set containing \f$(X,Y)\f$. -@param to Second input 2D point set containing \f$(x,y)\f$. -@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). -@param method Robust method used to compute transformation. The following methods are possible: -- @ref RANSAC - RANSAC-based robust method -- @ref LMEDS - Least-Median robust method -RANSAC is the default method. -@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider -a point as an inlier. Applies only to RANSAC. -@param maxIters The maximum number of robust method iterations. -@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything -between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation -significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. -@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). -Passing 0 will disable refining, so the output matrix will be output of robust method. - -@return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation -could not be estimated. The returned matrix has the following form: -\f[ -\begin{bmatrix} -a_{11} & a_{12} & b_1\\ -a_{21} & a_{22} & b_2\\ -\end{bmatrix} -\f] - -The function estimates an optimal 2D affine transformation between two 2D point sets using the -selected robust algorithm. - -The computed transformation is then refined further (using only inliers) with the -Levenberg-Marquardt method to reduce the re-projection error even more. - -@note -The RANSAC method can handle practically any ratio of outliers but needs a threshold to -distinguish inliers from outliers. The method LMeDS does not need any threshold but it works -correctly only when there are more than 50% of inliers. - -@sa estimateAffinePartial2D, getAffineTransform -*/ -CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(), - int method = RANSAC, double ransacReprojThreshold = 3, - size_t maxIters = 2000, double confidence = 0.99, - size_t refineIters = 10); - - -CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray pts1, InputArray pts2, OutputArray inliers, - const UsacParams ¶ms); - -/** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between -two 2D point sets. - -@param from First input 2D point set. -@param to Second input 2D point set. -@param inliers Output vector indicating which points are inliers. -@param method Robust method used to compute transformation. The following methods are possible: -- @ref RANSAC - RANSAC-based robust method -- @ref LMEDS - Least-Median robust method -RANSAC is the default method. -@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider -a point as an inlier. Applies only to RANSAC. -@param maxIters The maximum number of robust method iterations. -@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything -between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation -significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. -@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). -Passing 0 will disable refining, so the output matrix will be output of robust method. - -@return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or -empty matrix if transformation could not be estimated. - -The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to -combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust -estimation. - -The computed transformation is then refined further (using only inliers) with the -Levenberg-Marquardt method to reduce the re-projection error even more. - -Estimated transformation matrix is: -\f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\ - \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y -\end{bmatrix} \f] -Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are -translations in \f$ x, y \f$ axes respectively. - -@note -The RANSAC method can handle practically any ratio of outliers but need a threshold to -distinguish inliers from outliers. The method LMeDS does not need any threshold but it works -correctly only when there are more than 50% of inliers. - -@sa estimateAffine2D, getAffineTransform -*/ -CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(), - int method = RANSAC, double ransacReprojThreshold = 3, - size_t maxIters = 2000, double confidence = 0.99, - size_t refineIters = 10); - -/** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp -An example program with homography decomposition. - -Check @ref tutorial_homography "the corresponding tutorial" for more details. -*/ - -/** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s). - -@param H The input homography matrix between two images. -@param K The input camera intrinsic matrix. -@param rotations Array of rotation matrices. -@param translations Array of translation matrices. -@param normals Array of plane normal matrices. - -This function extracts relative camera motion between two views of a planar object and returns up to -four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of -the homography matrix H is described in detail in @cite Malis2007. - -If the homography H, induced by the plane, gives the constraint -\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points -\f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and -translations[k] is a change of basis from the source camera's coordinate system to the destination -camera's coordinate system. However, by decomposing H, one can only get the translation normalized -by the (typically unknown) depth of the scene, i.e. its direction but with normalized length. - -If point correspondences are available, at least two solutions may further be invalidated, by -applying positive depth constraint, i.e. all points must be in front of the camera. - */ -CV_EXPORTS_W int decomposeHomographyMat(InputArray H, - InputArray K, - OutputArrayOfArrays rotations, - OutputArrayOfArrays translations, - OutputArrayOfArrays normals); - -/** @brief Filters homography decompositions based on additional information. - -@param rotations Vector of rotation matrices. -@param normals Vector of plane normal matrices. -@param beforePoints Vector of (rectified) visible reference points before the homography is applied -@param afterPoints Vector of (rectified) visible reference points after the homography is applied -@param possibleSolutions Vector of int indices representing the viable solution set after filtering -@param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function - -This function is intended to filter the output of the #decomposeHomographyMat based on additional -information as described in @cite Malis2007 . The summary of the method: the #decomposeHomographyMat function -returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the -sets of points visible in the camera frame before and after the homography transformation is applied, -we can determine which are the true potential solutions and which are the opposites by verifying which -homographies are consistent with all visible reference points being in front of the camera. The inputs -are left unchanged; the filtered solution set is returned as indices into the existing one. - -*/ -CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations, - InputArrayOfArrays normals, - InputArray beforePoints, - InputArray afterPoints, - OutputArray possibleSolutions, - InputArray pointsMask = noArray()); - -/** @brief The base class for stereo correspondence algorithms. - */ -class CV_EXPORTS_W StereoMatcher : public Algorithm -{ -public: - enum { DISP_SHIFT = 4, - DISP_SCALE = (1 << DISP_SHIFT) - }; - - /** @brief Computes disparity map for the specified stereo pair - - @param left Left 8-bit single-channel image. - @param right Right image of the same size and the same type as the left one. - @param disparity Output disparity map. It has the same size as the input images. Some algorithms, - like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value - has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map. - */ - CV_WRAP virtual void compute( InputArray left, InputArray right, - OutputArray disparity ) = 0; - - CV_WRAP virtual int getMinDisparity() const = 0; - CV_WRAP virtual void setMinDisparity(int minDisparity) = 0; - - CV_WRAP virtual int getNumDisparities() const = 0; - CV_WRAP virtual void setNumDisparities(int numDisparities) = 0; - - CV_WRAP virtual int getBlockSize() const = 0; - CV_WRAP virtual void setBlockSize(int blockSize) = 0; - - CV_WRAP virtual int getSpeckleWindowSize() const = 0; - CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0; - - CV_WRAP virtual int getSpeckleRange() const = 0; - CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0; - - CV_WRAP virtual int getDisp12MaxDiff() const = 0; - CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0; -}; - - -/** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and -contributed to OpenCV by K. Konolige. - */ -class CV_EXPORTS_W StereoBM : public StereoMatcher -{ -public: - enum { PREFILTER_NORMALIZED_RESPONSE = 0, - PREFILTER_XSOBEL = 1 - }; - - CV_WRAP virtual int getPreFilterType() const = 0; - CV_WRAP virtual void setPreFilterType(int preFilterType) = 0; - - CV_WRAP virtual int getPreFilterSize() const = 0; - CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0; - - CV_WRAP virtual int getPreFilterCap() const = 0; - CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; - - CV_WRAP virtual int getTextureThreshold() const = 0; - CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0; - - CV_WRAP virtual int getUniquenessRatio() const = 0; - CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; - - CV_WRAP virtual int getSmallerBlockSize() const = 0; - CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0; - - CV_WRAP virtual Rect getROI1() const = 0; - CV_WRAP virtual void setROI1(Rect roi1) = 0; - - CV_WRAP virtual Rect getROI2() const = 0; - CV_WRAP virtual void setROI2(Rect roi2) = 0; - - /** @brief Creates StereoBM object - - @param numDisparities the disparity search range. For each pixel algorithm will find the best - disparity from 0 (default minimum disparity) to numDisparities. The search range can then be - shifted by changing the minimum disparity. - @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd - (as the block is centered at the current pixel). Larger block size implies smoother, though less - accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher - chance for algorithm to find a wrong correspondence. - - The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for - a specific stereo pair. - */ - CV_WRAP static Ptr create(int numDisparities = 0, int blockSize = 21); -}; - -/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original -one as follows: - -- By default, the algorithm is single-pass, which means that you consider only 5 directions -instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the -algorithm but beware that it may consume a lot of memory. -- The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the -blocks to single pixels. -- Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi -sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. -- Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for -example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness -check, quadratic interpolation and speckle filtering). - -@note - - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found - at opencv_source_code/samples/python/stereo_match.py - */ -class CV_EXPORTS_W StereoSGBM : public StereoMatcher -{ -public: - enum - { - MODE_SGBM = 0, - MODE_HH = 1, - MODE_SGBM_3WAY = 2, - MODE_HH4 = 3 - }; - - CV_WRAP virtual int getPreFilterCap() const = 0; - CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; - - CV_WRAP virtual int getUniquenessRatio() const = 0; - CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; - - CV_WRAP virtual int getP1() const = 0; - CV_WRAP virtual void setP1(int P1) = 0; - - CV_WRAP virtual int getP2() const = 0; - CV_WRAP virtual void setP2(int P2) = 0; - - CV_WRAP virtual int getMode() const = 0; - CV_WRAP virtual void setMode(int mode) = 0; - - /** @brief Creates StereoSGBM object - - @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes - rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. - @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than - zero. In the current implementation, this parameter must be divisible by 16. - @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be - somewhere in the 3..11 range. - @param P1 The first parameter controlling the disparity smoothness. See below. - @param P2 The second parameter controlling the disparity smoothness. The larger the values are, - the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 - between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor - pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good - P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and - 32\*number_of_image_channels\*blockSize\*blockSize , respectively). - @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right - disparity check. Set it to a non-positive value to disable the check. - @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first - computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. - The result values are passed to the Birchfield-Tomasi pixel cost function. - @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function - value should "win" the second best value to consider the found match correct. Normally, a value - within the 5-15 range is good enough. - @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles - and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the - 50-200 range. - @param speckleRange Maximum disparity variation within each connected component. If you do speckle - filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. - Normally, 1 or 2 is good enough. - @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming - algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and - huge for HD-size pictures. By default, it is set to false . - - The first constructor initializes StereoSGBM with all the default parameters. So, you only have to - set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter - to a custom value. - */ - CV_WRAP static Ptr create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3, - int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, - int preFilterCap = 0, int uniquenessRatio = 0, - int speckleWindowSize = 0, int speckleRange = 0, - int mode = StereoSGBM::MODE_SGBM); -}; - - -//! cv::undistort mode -enum UndistortTypes -{ - PROJ_SPHERICAL_ORTHO = 0, - PROJ_SPHERICAL_EQRECT = 1 -}; - -/** @brief Transforms an image to compensate for lens distortion. - -The function transforms an image to compensate radial and tangential lens distortion. - -The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap -(with bilinear interpolation). See the former function for details of the transformation being -performed. - -Those pixels in the destination image, for which there is no correspondent pixels in the source -image, are filled with zeros (black color). - -A particular subset of the source image that will be visible in the corrected image can be regulated -by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate -newCameraMatrix depending on your requirements. - -The camera matrix and the distortion parameters can be determined using #calibrateCamera. If -the resolution of images is different from the resolution used at the calibration stage, \f$f_x, -f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain -the same. - -@param src Input (distorted) image. -@param dst Output (corrected) image that has the same size and type as src . -@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as -cameraMatrix but you may additionally scale and shift the result by using a different matrix. - */ -CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, - InputArray cameraMatrix, - InputArray distCoeffs, - InputArray newCameraMatrix = noArray() ); - -/** @brief Computes the undistortion and rectification transformation map. - -The function computes the joint undistortion and rectification transformation and represents the -result in the form of maps for #remap. The undistorted image looks like original, as if it is -captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a -monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by -#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera, -newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . - -Also, this new camera is oriented differently in the coordinate space, according to R. That, for -example, helps to align two heads of a stereo camera so that the epipolar lines on both images -become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera). - -The function actually builds the maps for the inverse mapping algorithm that is used by #remap. That -is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function -computes the corresponding coordinates in the source image (that is, in the original image from -camera). The following process is applied: -\f[ -\begin{array}{l} -x \leftarrow (u - {c'}_x)/{f'}_x \\ -y \leftarrow (v - {c'}_y)/{f'}_y \\ -{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ -x' \leftarrow X/W \\ -y' \leftarrow Y/W \\ -r^2 \leftarrow x'^2 + y'^2 \\ -x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} -+ 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\ -y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} -+ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ -s\vecthree{x'''}{y'''}{1} = -\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} -{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} -{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ -map_x(u,v) \leftarrow x''' f_x + c_x \\ -map_y(u,v) \leftarrow y''' f_y + c_y -\end{array} -\f] -where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -are the distortion coefficients. - -In case of a stereo camera, this function is called twice: once for each camera head, after -#stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera -was not calibrated, it is still possible to compute the rectification transformations directly from -the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes -homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D -space. R can be computed from H as -\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] -where cameraMatrix can be chosen arbitrarily. - -@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 , -computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation -is assumed. In #initUndistortRectifyMap R assumed to be an identity matrix. -@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. -@param size Undistorted image size. -@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps -@param map1 The first output map. -@param map2 The second output map. - */ -CV_EXPORTS_W -void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs, - InputArray R, InputArray newCameraMatrix, - Size size, int m1type, OutputArray map1, OutputArray map2); - -/** @brief Computes the projection and inverse-rectification transformation map. In essense, this is the inverse of -#initUndistortRectifyMap to accomodate stereo-rectification of projectors ('inverse-cameras') in projector-camera pairs. - -The function computes the joint projection and inverse rectification transformation and represents the -result in the form of maps for #remap. The projected image looks like a distorted version of the original which, -once projected by a projector, should visually match the original. In case of a monocular camera, newCameraMatrix -is usually equal to cameraMatrix, or it can be computed by -#getOptimalNewCameraMatrix for a better control over scaling. In case of a projector-camera pair, -newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . - -The projector is oriented differently in the coordinate space, according to R. In case of projector-camera pairs, -this helps align the projector (in the same manner as #initUndistortRectifyMap for the camera) to create a stereo-rectified pair. This -allows epipolar lines on both images to become horizontal and have the same y-coordinate (in case of a horizontally aligned projector-camera pair). - -The function builds the maps for the inverse mapping algorithm that is used by #remap. That -is, for each pixel \f$(u, v)\f$ in the destination (projected and inverse-rectified) image, the function -computes the corresponding coordinates in the source image (that is, in the original digital image). The following process is applied: - -\f[ -\begin{array}{l} -\text{newCameraMatrix}\\ -x \leftarrow (u - {c'}_x)/{f'}_x \\ -y \leftarrow (v - {c'}_y)/{f'}_y \\ - -\\\text{Undistortion} -\\\scriptsize{\textit{though equation shown is for radial undistortion, function implements cv::undistortPoints()}}\\ -r^2 \leftarrow x^2 + y^2 \\ -\theta \leftarrow \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}\\ -x' \leftarrow \frac{x}{\theta} \\ -y' \leftarrow \frac{y}{\theta} \\ - -\\\text{Rectification}\\ -{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ -x'' \leftarrow X/W \\ -y'' \leftarrow Y/W \\ - -\\\text{cameraMatrix}\\ -map_x(u,v) \leftarrow x'' f_x + c_x \\ -map_y(u,v) \leftarrow y'' f_y + c_y -\end{array} -\f] -where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -are the distortion coefficients vector distCoeffs. - -In case of a stereo-rectified projector-camera pair, this function is called for the projector while #initUndistortRectifyMap is called for the camera head. -This is done after #stereoRectify, which in turn is called after #stereoCalibrate. If the projector-camera pair -is not calibrated, it is still possible to compute the rectification transformations directly from -the fundamental matrix using #stereoRectifyUncalibrated. For the projector and camera, the function computes -homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D -space. R can be computed from H as -\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] -where cameraMatrix can be chosen arbitrarily. - -@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2, -computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation -is assumed. -@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. -@param size Distorted image size. -@param m1type Type of the first output map. Can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps -@param map1 The first output map for #remap. -@param map2 The second output map for #remap. - */ -CV_EXPORTS_W -void initInverseRectificationMap( InputArray cameraMatrix, InputArray distCoeffs, - InputArray R, InputArray newCameraMatrix, - const Size& size, int m1type, OutputArray map1, OutputArray map2 ); - -//! initializes maps for #remap for wide-angle -CV_EXPORTS -float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, int destImageWidth, - int m1type, OutputArray map1, OutputArray map2, - enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); -static inline -float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, - Size imageSize, int destImageWidth, - int m1type, OutputArray map1, OutputArray map2, - int projType, double alpha = 0) -{ - return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth, - m1type, map1, map2, (UndistortTypes)projType, alpha); -} - -/** @brief Returns the default new camera matrix. - -The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when -centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true). - -In the latter case, the new camera matrix will be: - -\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f] - -where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively. - -By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not -move the principal point. However, when you work with stereo, it is important to move the principal -points in both views to the same y-coordinate (which is required by most of stereo correspondence -algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for -each view where the principal points are located at the center. - -@param cameraMatrix Input camera matrix. -@param imgsize Camera view image size in pixels. -@param centerPrincipalPoint Location of the principal point in the new camera matrix. The -parameter indicates whether this location should be at the image center or not. - */ -CV_EXPORTS_W -Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(), - bool centerPrincipalPoint = false); - -/** @brief Computes the ideal point coordinates from the observed point coordinates. - -The function is similar to #undistort and #initUndistortRectifyMap but it operates on a -sparse set of points instead of a raster image. Also the function performs a reverse transformation -to #projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a -planar object, it does, up to a translation vector, if the proper R is specified. - -For each observed point coordinate \f$(u, v)\f$ the function computes: -\f[ -\begin{array}{l} -x^{"} \leftarrow (u - c_x)/f_x \\ -y^{"} \leftarrow (v - c_y)/f_y \\ -(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\ -{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ -x \leftarrow X/W \\ -y \leftarrow Y/W \\ -\text{only performed if P is specified:} \\ -u' \leftarrow x {f'}_x + {c'}_x \\ -v' \leftarrow y {f'}_y + {c'}_y -\end{array} -\f] - -where *undistort* is an approximate iterative algorithm that estimates the normalized original -point coordinates out of the normalized distorted point coordinates ("normalized" means that the -coordinates do not depend on the camera matrix). - -The function can be used for both a stereo camera head or a monocular camera (when R is empty). -@param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or -vector\ ). -@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\ ) after undistortion and reverse perspective -transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates. -@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . -@param distCoeffs Input vector of distortion coefficients -\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ -of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. -@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by -#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used. -@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by -#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used. - */ -CV_EXPORTS_W -void undistortPoints(InputArray src, OutputArray dst, - InputArray cameraMatrix, InputArray distCoeffs, - InputArray R = noArray(), InputArray P = noArray()); -/** @overload - @note Default version of #undistortPoints does 5 iterations to compute undistorted points. - */ -CV_EXPORTS_AS(undistortPointsIter) -void undistortPoints(InputArray src, OutputArray dst, - InputArray cameraMatrix, InputArray distCoeffs, - InputArray R, InputArray P, TermCriteria criteria); - -/** - * @brief Compute undistorted image points position - * - * @param src Observed points position, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or -CV_64FC2) (or vector\ ). - * @param dst Output undistorted points position (1xN/Nx1 2-channel or vector\ ). - * @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . - * @param distCoeffs Distortion coefficients - */ -CV_EXPORTS_W -void undistortImagePoints(InputArray src, OutputArray dst, InputArray cameraMatrix, - InputArray distCoeffs, - TermCriteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, - 0.01)); - -//! @} calib3d - -/** @brief The methods in this namespace use a so-called fisheye camera model. - @ingroup calib3d_fisheye -*/ -namespace fisheye -{ -//! @addtogroup calib3d_fisheye -//! @{ - - enum{ - CALIB_USE_INTRINSIC_GUESS = 1 << 0, - CALIB_RECOMPUTE_EXTRINSIC = 1 << 1, - CALIB_CHECK_COND = 1 << 2, - CALIB_FIX_SKEW = 1 << 3, - CALIB_FIX_K1 = 1 << 4, - CALIB_FIX_K2 = 1 << 5, - CALIB_FIX_K3 = 1 << 6, - CALIB_FIX_K4 = 1 << 7, - CALIB_FIX_INTRINSIC = 1 << 8, - CALIB_FIX_PRINCIPAL_POINT = 1 << 9, - CALIB_ZERO_DISPARITY = 1 << 10, - CALIB_FIX_FOCAL_LENGTH = 1 << 11 - }; - - /** @brief Projects points using fisheye model - - @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\ ), where N is - the number of points in the view. - @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or - vector\. - @param affine - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param alpha The skew coefficient. - @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect - to components of the focal lengths, coordinates of the principal point, distortion coefficients, - rotation vector, translation vector, and the skew. In the old interface different components of - the jacobian are returned via different output parameters. - - The function computes projections of 3D points to the image plane given intrinsic and extrinsic - camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of - image points coordinates (as functions of all the input parameters) with respect to the particular - parameters, intrinsic and/or extrinsic. - */ - CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine, - InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); - - /** @overload */ - CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, - InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); - - /** @brief Distorts 2D points using fisheye model. - - @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is - the number of points in the view. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param alpha The skew coefficient. - @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . - - Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity. - This means if you want to distort image points you have to multiply them with \f$K^{-1}\f$ or - use another function overload. - */ - CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0); - - /** @overload - Overload of distortPoints function to handle cases when undistorted points are obtained with non-identity - camera matrix, e.g. output of #estimateNewCameraMatrixForUndistortRectify. - @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is - the number of points in the view. - @param Kundistorted Camera intrinsic matrix used as new camera matrix for undistortion. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param alpha The skew coefficient. - @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . - @sa estimateNewCameraMatrixForUndistortRectify - */ - CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray Kundistorted, InputArray K, InputArray D, double alpha = 0); - - /** @brief Undistorts 2D points using fisheye model - - @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is the - number of points in the view. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 - 1-channel or 1x1 3-channel - @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) - @param criteria Termination criteria - @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . - */ - CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted, - InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray(), - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8)); - - /** @brief Computes undistortion and rectification maps for image transform by #remap. If D is empty zero - distortion is used, if R or P is empty identity matrixes are used. - - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 - 1-channel or 1x1 3-channel - @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) - @param size Undistorted image size. - @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See #convertMaps - for details. - @param map1 The first output map. - @param map2 The second output map. - */ - CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P, - const cv::Size& size, int m1type, OutputArray map1, OutputArray map2); - - /** @brief Transforms an image to compensate for fisheye lens distortion. - - @param distorted image with fisheye lens distortion. - @param undistorted Output image with compensated fisheye lens distortion. - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you - may additionally scale and shift the result by using a different matrix. - @param new_size the new size - - The function transforms an image to compensate radial and tangential lens distortion. - - The function is simply a combination of #fisheye::initUndistortRectifyMap (with unity R ) and #remap - (with bilinear interpolation). See the former function for details of the transformation being - performed. - - See below the results of undistortImage. - - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3, - k_4, k_5, k_6) of distortion were optimized under calibration) - - b\) result of #fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2, - k_3, k_4) of fisheye distortion were optimized under calibration) - - c\) original image was captured with fisheye lens - - Pictures a) and b) almost the same. But if we consider points of image located far from the center - of image, we can notice that on image a) these points are distorted. - - ![image](pics/fisheye_undistorted.jpg) - */ - CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted, - InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size()); - - /** @brief Estimates new camera intrinsic matrix for undistortion or rectification. - - @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. - @param image_size Size of the image - @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 - 1-channel or 1x1 3-channel - @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) - @param balance Sets the new focal length in range between the min focal length and the max focal - length. Balance is in range of [0, 1]. - @param new_size the new size - @param fov_scale Divisor for new focal length. - */ - CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R, - OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0); - - /** @brief Performs camera calibration - - @param objectPoints vector of vectors of calibration pattern points in the calibration pattern - coordinate space. - @param imagePoints vector of vectors of the projections of calibration pattern points. - imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to - objectPoints[i].size() for each i. - @param image_size Size of the image used only to initialize the camera intrinsic matrix. - @param K Output 3x3 floating-point camera intrinsic matrix - \f$\cameramatrix{A}\f$ . If - @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be - initialized before calling the function. - @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$. - @param rvecs Output vector of rotation vectors (see @ref Rodrigues ) estimated for each pattern view. - That is, each k-th rotation vector together with the corresponding k-th translation vector (see - the next output parameter description) brings the calibration pattern from the model coordinate - space (in which object points are specified) to the world coordinate space, that is, a real - position of the calibration pattern in the k-th pattern view (k=0.. *M* -1). - @param tvecs Output vector of translation vectors estimated for each pattern view. - @param flags Different flags that may be zero or a combination of the following values: - - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of - fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image - center ( imageSize is used), and focal distances are computed in a least-squares fashion. - - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration - of intrinsic optimization. - - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. - - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. - - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients - are set to zeros and stay zero. - - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global -optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. - - @ref fisheye::CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global -optimization. It is the \f$max(width,height)/\pi\f$ or the provided \f$f_x\f$, \f$f_y\f$ when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. - @param criteria Termination criteria for the iterative optimization algorithm. - */ - CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size, - InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - /** @brief Stereo rectification for fisheye camera model - - @param K1 First camera intrinsic matrix. - @param D1 First camera distortion parameters. - @param K2 Second camera intrinsic matrix. - @param D2 Second camera distortion parameters. - @param imageSize Size of the image used for stereo calibration. - @param R Rotation matrix between the coordinate systems of the first and the second - cameras. - @param tvec Translation vector between coordinate systems of the cameras. - @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. - @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. - @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first - camera. - @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second - camera. - @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see #reprojectImageTo3D ). - @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set, - the function makes the principal points of each camera have the same pixel coordinates in the - rectified views. And if the flag is not set, the function may still shift the images in the - horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the - useful image area. - @param newImageSize New image resolution after rectification. The same size should be passed to - #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) - is passed (default), it is set to the original imageSize . Setting it to larger value can help you - preserve details in the original image, especially when there is a big radial distortion. - @param balance Sets the new focal length in range between the min focal length and the max focal - length. Balance is in range of [0, 1]. - @param fov_scale Divisor for new focal length. - */ - CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec, - OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(), - double balance = 0.0, double fov_scale = 1.0); - - /** @brief Performs stereo calibration - - @param objectPoints Vector of vectors of the calibration pattern points. - @param imagePoints1 Vector of vectors of the projections of the calibration pattern points, - observed by the first camera. - @param imagePoints2 Vector of vectors of the projections of the calibration pattern points, - observed by the second camera. - @param K1 Input/output first camera intrinsic matrix: - \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If - any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified, - some or all of the matrix components must be initialized. - @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements. - @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 . - @param D2 Input/output lens distortion coefficients for the second camera. The parameter is - similar to D1 . - @param imageSize Size of the image used only to initialize camera intrinsic matrix. - @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems. - @param T Output translation vector between the coordinate systems of the cameras. - @param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the - coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each - i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter - description) brings the calibration pattern from the object coordinate space (in which object points are - specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, - the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space - to camera coordinate space of the first camera of the stereo pair. - @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description - of previous output parameter ( rvecs ). - @param flags Different flags that may be zero or a combination of the following values: - - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices - are estimated. - - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of - fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image - center (imageSize is used), and focal distances are computed in a least-squares fashion. - - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration - of intrinsic optimization. - - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. - - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. - - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay - zero. - @param criteria Termination criteria for the iterative optimization algorithm. - */ - CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, - OutputArray R, OutputArray T, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = fisheye::CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - /// @overload - CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, - InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, - OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); - - /** - @brief Finds an object pose from 3D-2D point correspondences for fisheye camera moodel. - - @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or - 1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. - @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, - where N is the number of points. vector\ can be also passed here. - @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . - @param distCoeffs Input vector of distortion coefficients (4x1/1x4). - @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from - the model coordinate system to the camera coordinate system. - @param tvec Output translation vector. - @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses - the provided rvec and tvec values as initial approximations of the rotation and translation - vectors, respectively, and further optimizes them. - @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags - This function returns the rotation and the translation vectors that transform a 3D point expressed in the object - coordinate frame to the camera coordinate frame, using different methods: - - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. - - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. - - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. - Number of input points must be 4. Object points must be defined in the following order: - - point 0: [-squareLength / 2, squareLength / 2, 0] - - point 1: [ squareLength / 2, squareLength / 2, 0] - - point 2: [ squareLength / 2, -squareLength / 2, 0] - - point 3: [-squareLength / 2, -squareLength / 2, 0] - - for all the other flags, number of input points must be >= 4 and object points can be in any configuration. - @param criteria Termination criteria for internal undistortPoints call. - The function interally undistorts points with @ref undistortPoints and call @ref cv::solvePnP, - thus the input are very similar. More information about Perspective-n-Points is described in @ref calib3d_solvePnP - for more information. - */ - CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, - InputArray cameraMatrix, InputArray distCoeffs, - OutputArray rvec, OutputArray tvec, - bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE, - TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8) - ); - -//! @} calib3d_fisheye -} // end namespace fisheye - -} //end namespace cv - -#if 0 //def __cplusplus -////////////////////////////////////////////////////////////////////////////////////////// -class CV_EXPORTS CvLevMarq -{ -public: - CvLevMarq(); - CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - ~CvLevMarq(); - void init( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); - bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); - - void clear(); - void step(); - enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; - - cv::Ptr mask; - cv::Ptr prevParam; - cv::Ptr param; - cv::Ptr J; - cv::Ptr err; - cv::Ptr JtJ; - cv::Ptr JtJN; - cv::Ptr JtErr; - cv::Ptr JtJV; - cv::Ptr JtJW; - double prevErrNorm, errNorm; - int lambdaLg10; - CvTermCriteria criteria; - int state; - int iters; - bool completeSymmFlag; - int solveMethod; -}; -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CALIB3D_HPP +#define OPENCV_CALIB3D_HPP + +#include "opencv2/core.hpp" +#include "opencv2/core/types.hpp" +#include "opencv2/features2d.hpp" +#include "opencv2/core/affine.hpp" +#include "opencv2/core/utils/logger.hpp" + +/** + @defgroup calib3d Camera Calibration and 3D Reconstruction + +The functions in this section use a so-called pinhole camera model. The view of a scene +is obtained by projecting a scene's 3D point \f$P_w\f$ into the image plane using a perspective +transformation which forms the corresponding pixel \f$p\f$. Both \f$P_w\f$ and \f$p\f$ are +represented in homogeneous coordinates, i.e. as 3D and 2D homogeneous vector respectively. You will +find a brief introduction to projective geometry, homogeneous vectors and homogeneous +transformations at the end of this section's introduction. For more succinct notation, we often drop +the 'homogeneous' and say vector instead of homogeneous vector. + +The distortion-free projective transformation given by a pinhole camera model is shown below. + +\f[s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w,\f] + +where \f$P_w\f$ is a 3D point expressed with respect to the world coordinate system, +\f$p\f$ is a 2D pixel in the image plane, \f$A\f$ is the camera intrinsic matrix, +\f$R\f$ and \f$t\f$ are the rotation and translation that describe the change of coordinates from +world to camera coordinate systems (or camera frame) and \f$s\f$ is the projective transformation's +arbitrary scaling and not part of the camera model. + +The camera intrinsic matrix \f$A\f$ (notation used as in @cite Zhang2000 and also generally notated +as \f$K\f$) projects 3D points given in the camera coordinate system to 2D pixel coordinates, i.e. + +\f[p = A P_c.\f] + +The camera intrinsic matrix \f$A\f$ is composed of the focal lengths \f$f_x\f$ and \f$f_y\f$, which are +expressed in pixel units, and the principal point \f$(c_x, c_y)\f$, that is usually close to the +image center: + +\f[A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1},\f] + +and thus + +\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} \vecthree{X_c}{Y_c}{Z_c}.\f] + +The matrix of intrinsic parameters does not depend on the scene viewed. So, once estimated, it can +be re-used as long as the focal length is fixed (in case of a zoom lens). Thus, if an image from the +camera is scaled by a factor, all of these parameters need to be scaled (multiplied/divided, +respectively) by the same factor. + +The joint rotation-translation matrix \f$[R|t]\f$ is the matrix product of a projective +transformation and a homogeneous transformation. The 3-by-4 projective transformation maps 3D points +represented in camera coordinates to 2D points in the image plane and represented in normalized +camera coordinates \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$: + +\f[Z_c \begin{bmatrix} +x' \\ +y' \\ +1 +\end{bmatrix} = \begin{bmatrix} +1 & 0 & 0 & 0 \\ +0 & 1 & 0 & 0 \\ +0 & 0 & 1 & 0 +\end{bmatrix} +\begin{bmatrix} +X_c \\ +Y_c \\ +Z_c \\ +1 +\end{bmatrix}.\f] + +The homogeneous transformation is encoded by the extrinsic parameters \f$R\f$ and \f$t\f$ and +represents the change of basis from world coordinate system \f$w\f$ to the camera coordinate sytem +\f$c\f$. Thus, given the representation of the point \f$P\f$ in world coordinates, \f$P_w\f$, we +obtain \f$P\f$'s representation in the camera coordinate system, \f$P_c\f$, by + +\f[P_c = \begin{bmatrix} +R & t \\ +0 & 1 +\end{bmatrix} P_w,\f] + +This homogeneous transformation is composed out of \f$R\f$, a 3-by-3 rotation matrix, and \f$t\f$, a +3-by-1 translation vector: + +\f[\begin{bmatrix} +R & t \\ +0 & 1 +\end{bmatrix} = \begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z \\ +0 & 0 & 0 & 1 +\end{bmatrix}, +\f] + +and therefore + +\f[\begin{bmatrix} +X_c \\ +Y_c \\ +Z_c \\ +1 +\end{bmatrix} = \begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z \\ +0 & 0 & 0 & 1 +\end{bmatrix} +\begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix}.\f] + +Combining the projective transformation and the homogeneous transformation, we obtain the projective +transformation that maps 3D points in world coordinates into 2D points in the image plane and in +normalized camera coordinates: + +\f[Z_c \begin{bmatrix} +x' \\ +y' \\ +1 +\end{bmatrix} = \begin{bmatrix} R|t \end{bmatrix} \begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix} = \begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z +\end{bmatrix} +\begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix},\f] + +with \f$x' = X_c / Z_c\f$ and \f$y' = Y_c / Z_c\f$. Putting the equations for instrincs and extrinsics together, we can write out +\f$s \; p = A \begin{bmatrix} R|t \end{bmatrix} P_w\f$ as + +\f[s \vecthree{u}{v}{1} = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1} +\begin{bmatrix} +r_{11} & r_{12} & r_{13} & t_x \\ +r_{21} & r_{22} & r_{23} & t_y \\ +r_{31} & r_{32} & r_{33} & t_z +\end{bmatrix} +\begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix}.\f] + +If \f$Z_c \ne 0\f$, the transformation above is equivalent to the following, + +\f[\begin{bmatrix} +u \\ +v +\end{bmatrix} = \begin{bmatrix} +f_x X_c/Z_c + c_x \\ +f_y Y_c/Z_c + c_y +\end{bmatrix}\f] + +with + +\f[\vecthree{X_c}{Y_c}{Z_c} = \begin{bmatrix} +R|t +\end{bmatrix} \begin{bmatrix} +X_w \\ +Y_w \\ +Z_w \\ +1 +\end{bmatrix}.\f] + +The following figure illustrates the pinhole camera model. + +![Pinhole camera model](pics/pinhole_camera_model.png) + +Real lenses usually have some distortion, mostly radial distortion, and slight tangential distortion. +So, the above model is extended as: + +\f[\begin{bmatrix} +u \\ +v +\end{bmatrix} = \begin{bmatrix} +f_x x'' + c_x \\ +f_y y'' + c_y +\end{bmatrix}\f] + +where + +\f[\begin{bmatrix} +x'' \\ +y'' +\end{bmatrix} = \begin{bmatrix} +x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2 p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4 \\ +y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ +\end{bmatrix}\f] + +with + +\f[r^2 = x'^2 + y'^2\f] + +and + +\f[\begin{bmatrix} +x'\\ +y' +\end{bmatrix} = \begin{bmatrix} +X_c/Z_c \\ +Y_c/Z_c +\end{bmatrix},\f] + +if \f$Z_c \ne 0\f$. + +The distortion parameters are the radial coefficients \f$k_1\f$, \f$k_2\f$, \f$k_3\f$, \f$k_4\f$, \f$k_5\f$, and \f$k_6\f$ +,\f$p_1\f$ and \f$p_2\f$ are the tangential distortion coefficients, and \f$s_1\f$, \f$s_2\f$, \f$s_3\f$, and \f$s_4\f$, +are the thin prism distortion coefficients. Higher-order coefficients are not considered in OpenCV. + +The next figures show two common types of radial distortion: barrel distortion +(\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically decreasing) +and pincushion distortion (\f$ 1 + k_1 r^2 + k_2 r^4 + k_3 r^6 \f$ monotonically increasing). +Radial distortion is always monotonic for real lenses, +and if the estimator produces a non-monotonic result, +this should be considered a calibration failure. +More generally, radial distortion must be monotonic and the distortion function must be bijective. +A failed estimation result may look deceptively good near the image center +but will work poorly in e.g. AR/SFM applications. +The optimization method used in OpenCV camera calibration does not include these constraints as +the framework does not support the required integer programming and polynomial inequalities. +See [issue #15992](https://github.com/opencv/opencv/issues/15992) for additional information. + +![](pics/distortion_examples.png) +![](pics/distortion_examples2.png) + +In some cases, the image sensor may be tilted in order to focus an oblique plane in front of the +camera (Scheimpflug principle). This can be useful for particle image velocimetry (PIV) or +triangulation with a laser fan. The tilt causes a perspective distortion of \f$x''\f$ and +\f$y''\f$. This distortion can be modeled in the following way, see e.g. @cite Louhichi07. + +\f[\begin{bmatrix} +u \\ +v +\end{bmatrix} = \begin{bmatrix} +f_x x''' + c_x \\ +f_y y''' + c_y +\end{bmatrix},\f] + +where + +\f[s\vecthree{x'''}{y'''}{1} = +\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}(\tau_x, \tau_y)} +{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} +{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\f] + +and the matrix \f$R(\tau_x, \tau_y)\f$ is defined by two rotations with angular parameter +\f$\tau_x\f$ and \f$\tau_y\f$, respectively, + +\f[ +R(\tau_x, \tau_y) = +\vecthreethree{\cos(\tau_y)}{0}{-\sin(\tau_y)}{0}{1}{0}{\sin(\tau_y)}{0}{\cos(\tau_y)} +\vecthreethree{1}{0}{0}{0}{\cos(\tau_x)}{\sin(\tau_x)}{0}{-\sin(\tau_x)}{\cos(\tau_x)} = +\vecthreethree{\cos(\tau_y)}{\sin(\tau_y)\sin(\tau_x)}{-\sin(\tau_y)\cos(\tau_x)} +{0}{\cos(\tau_x)}{\sin(\tau_x)} +{\sin(\tau_y)}{-\cos(\tau_y)\sin(\tau_x)}{\cos(\tau_y)\cos(\tau_x)}. +\f] + +In the functions below the coefficients are passed or returned as + +\f[(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f] + +vector. That is, if the vector contains four elements, it means that \f$k_3=0\f$ . The distortion +coefficients do not depend on the scene viewed. Thus, they also belong to the intrinsic camera +parameters. And they remain the same regardless of the captured image resolution. If, for example, a +camera has been calibrated on images of 320 x 240 resolution, absolutely the same distortion +coefficients can be used for 640 x 480 images from the same camera while \f$f_x\f$, \f$f_y\f$, +\f$c_x\f$, and \f$c_y\f$ need to be scaled appropriately. + +The functions below use the above model to do the following: + +- Project 3D points to the image plane given intrinsic and extrinsic parameters. +- Compute extrinsic parameters given intrinsic parameters, a few 3D points, and their +projections. +- Estimate intrinsic and extrinsic camera parameters from several views of a known calibration +pattern (every view is described by several 3D-2D point correspondences). +- Estimate the relative position and orientation of the stereo camera "heads" and compute the +*rectification* transformation that makes the camera optical axes parallel. + + Homogeneous Coordinates
+Homogeneous Coordinates are a system of coordinates that are used in projective geometry. Their use +allows to represent points at infinity by finite coordinates and simplifies formulas when compared +to the cartesian counterparts, e.g. they have the advantage that affine transformations can be +expressed as linear homogeneous transformation. + +One obtains the homogeneous vector \f$P_h\f$ by appending a 1 along an n-dimensional cartesian +vector \f$P\f$ e.g. for a 3D cartesian vector the mapping \f$P \rightarrow P_h\f$ is: + +\f[\begin{bmatrix} +X \\ +Y \\ +Z +\end{bmatrix} \rightarrow \begin{bmatrix} +X \\ +Y \\ +Z \\ +1 +\end{bmatrix}.\f] + +For the inverse mapping \f$P_h \rightarrow P\f$, one divides all elements of the homogeneous vector +by its last element, e.g. for a 3D homogeneous vector one gets its 2D cartesian counterpart by: + +\f[\begin{bmatrix} +X \\ +Y \\ +W +\end{bmatrix} \rightarrow \begin{bmatrix} +X / W \\ +Y / W +\end{bmatrix},\f] + +if \f$W \ne 0\f$. + +Due to this mapping, all multiples \f$k P_h\f$, for \f$k \ne 0\f$, of a homogeneous point represent +the same point \f$P_h\f$. An intuitive understanding of this property is that under a projective +transformation, all multiples of \f$P_h\f$ are mapped to the same point. This is the physical +observation one does for pinhole cameras, as all points along a ray through the camera's pinhole are +projected to the same image point, e.g. all points along the red ray in the image of the pinhole +camera model above would be mapped to the same image coordinate. This property is also the source +for the scale ambiguity s in the equation of the pinhole camera model. + +As mentioned, by using homogeneous coordinates we can express any change of basis parameterized by +\f$R\f$ and \f$t\f$ as a linear transformation, e.g. for the change of basis from coordinate system +0 to coordinate system 1 becomes: + +\f[P_1 = R P_0 + t \rightarrow P_{h_1} = \begin{bmatrix} +R & t \\ +0 & 1 +\end{bmatrix} P_{h_0}.\f] + +@note + - Many functions in this module take a camera intrinsic matrix as an input parameter. Although all + functions assume the same structure of this parameter, they may name it differently. The + parameter's description, however, will be clear in that a camera intrinsic matrix with the structure + shown above is required. + - A calibration sample for 3 cameras in a horizontal position can be found at + opencv_source_code/samples/cpp/3calibration.cpp + - A calibration sample based on a sequence of images can be found at + opencv_source_code/samples/cpp/calibration.cpp + - A calibration sample in order to do 3D reconstruction can be found at + opencv_source_code/samples/cpp/build3dmodel.cpp + - A calibration example on stereo calibration can be found at + opencv_source_code/samples/cpp/stereo_calib.cpp + - A calibration example on stereo matching can be found at + opencv_source_code/samples/cpp/stereo_match.cpp + - (Python) A camera calibration sample can be found at + opencv_source_code/samples/python/calibrate.py + + @{ + @defgroup calib3d_fisheye Fisheye camera model + + Definitions: Let P be a point in 3D of coordinates X in the world reference frame (stored in the + matrix X) The coordinate vector of P in the camera reference frame is: + + \f[Xc = R X + T\f] + + where R is the rotation matrix corresponding to the rotation vector om: R = rodrigues(om); call x, y + and z the 3 coordinates of Xc: + + \f[\begin{array}{l} x = Xc_1 \\ y = Xc_2 \\ z = Xc_3 \end{array} \f] + + The pinhole projection coordinates of P is [a; b] where + + \f[\begin{array}{l} a = x / z \ and \ b = y / z \\ r^2 = a^2 + b^2 \\ \theta = atan(r) \end{array} \f] + + Fisheye distortion: + + \f[\theta_d = \theta (1 + k_1 \theta^2 + k_2 \theta^4 + k_3 \theta^6 + k_4 \theta^8)\f] + + The distorted point coordinates are [x'; y'] where + + \f[\begin{array}{l} x' = (\theta_d / r) a \\ y' = (\theta_d / r) b \end{array} \f] + + Finally, conversion into pixel coordinates: The final pixel coordinates vector [u; v] where: + + \f[\begin{array}{l} u = f_x (x' + \alpha y') + c_x \\ + v = f_y y' + c_y \end{array} \f] + + Summary: + Generic camera model @cite Kannala2006 with perspective projection and without distortion correction + + @} + */ + +namespace cv +{ + +//! @addtogroup calib3d +//! @{ + +//! type of the robust estimation algorithm +enum { LMEDS = 4, //!< least-median of squares algorithm + RANSAC = 8, //!< RANSAC algorithm + RHO = 16, //!< RHO algorithm + USAC_DEFAULT = 32, //!< USAC algorithm, default settings + USAC_PARALLEL = 33, //!< USAC, parallel version + USAC_FM_8PTS = 34, //!< USAC, fundamental matrix 8 points + USAC_FAST = 35, //!< USAC, fast settings + USAC_ACCURATE = 36, //!< USAC, accurate settings + USAC_PROSAC = 37, //!< USAC, sorted points, runs PROSAC + USAC_MAGSAC = 38 //!< USAC, runs MAGSAC++ + }; + +enum SolvePnPMethod { + SOLVEPNP_ITERATIVE = 0, //!< Pose refinement using non-linear Levenberg-Marquardt minimization scheme @cite Madsen04 @cite Eade13 \n + //!< Initial solution for non-planar "objectPoints" needs at least 6 points and uses the DLT algorithm. \n + //!< Initial solution for planar "objectPoints" needs at least 4 points and uses pose from homography decomposition. + SOLVEPNP_EPNP = 1, //!< EPnP: Efficient Perspective-n-Point Camera Pose Estimation @cite lepetit2009epnp + SOLVEPNP_P3P = 2, //!< Complete Solution Classification for the Perspective-Three-Point Problem @cite gao2003complete + SOLVEPNP_DLS = 3, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n + //!< A Direct Least-Squares (DLS) Method for PnP @cite hesch2011direct + SOLVEPNP_UPNP = 4, //!< **Broken implementation. Using this flag will fallback to EPnP.** \n + //!< Exhaustive Linearization for Robust Camera Pose and Focal Length Estimation @cite penate2013exhaustive + SOLVEPNP_AP3P = 5, //!< An Efficient Algebraic Solution to the Perspective-Three-Point Problem @cite Ke17 + SOLVEPNP_IPPE = 6, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n + //!< Object points must be coplanar. + SOLVEPNP_IPPE_SQUARE = 7, //!< Infinitesimal Plane-Based Pose Estimation @cite Collins14 \n + //!< This is a special case suitable for marker pose estimation.\n + //!< 4 coplanar object points must be defined in the following order: + //!< - point 0: [-squareLength / 2, squareLength / 2, 0] + //!< - point 1: [ squareLength / 2, squareLength / 2, 0] + //!< - point 2: [ squareLength / 2, -squareLength / 2, 0] + //!< - point 3: [-squareLength / 2, -squareLength / 2, 0] + SOLVEPNP_SQPNP = 8, //!< SQPnP: A Consistently Fast and Globally OptimalSolution to the Perspective-n-Point Problem @cite Terzakis2020SQPnP +#ifndef CV_DOXYGEN + SOLVEPNP_MAX_COUNT //!< Used for count +#endif +}; + +enum { CALIB_CB_ADAPTIVE_THRESH = 1, + CALIB_CB_NORMALIZE_IMAGE = 2, + CALIB_CB_FILTER_QUADS = 4, + CALIB_CB_FAST_CHECK = 8, + CALIB_CB_EXHAUSTIVE = 16, + CALIB_CB_ACCURACY = 32, + CALIB_CB_LARGER = 64, + CALIB_CB_MARKER = 128, + CALIB_CB_PLAIN = 256 + }; + +enum { CALIB_CB_SYMMETRIC_GRID = 1, + CALIB_CB_ASYMMETRIC_GRID = 2, + CALIB_CB_CLUSTERING = 4 + }; + +enum { CALIB_NINTRINSIC = 18, + CALIB_USE_INTRINSIC_GUESS = 0x00001, + CALIB_FIX_ASPECT_RATIO = 0x00002, + CALIB_FIX_PRINCIPAL_POINT = 0x00004, + CALIB_ZERO_TANGENT_DIST = 0x00008, + CALIB_FIX_FOCAL_LENGTH = 0x00010, + CALIB_FIX_K1 = 0x00020, + CALIB_FIX_K2 = 0x00040, + CALIB_FIX_K3 = 0x00080, + CALIB_FIX_K4 = 0x00800, + CALIB_FIX_K5 = 0x01000, + CALIB_FIX_K6 = 0x02000, + CALIB_RATIONAL_MODEL = 0x04000, + CALIB_THIN_PRISM_MODEL = 0x08000, + CALIB_FIX_S1_S2_S3_S4 = 0x10000, + CALIB_TILTED_MODEL = 0x40000, + CALIB_FIX_TAUX_TAUY = 0x80000, + CALIB_USE_QR = 0x100000, //!< use QR instead of SVD decomposition for solving. Faster but potentially less precise + CALIB_FIX_TANGENT_DIST = 0x200000, + // only for stereo + CALIB_FIX_INTRINSIC = 0x00100, + CALIB_SAME_FOCAL_LENGTH = 0x00200, + // for stereo rectification + CALIB_ZERO_DISPARITY = 0x00400, + CALIB_USE_LU = (1 << 17), //!< use LU instead of SVD decomposition for solving. much faster but potentially less precise + CALIB_USE_EXTRINSIC_GUESS = (1 << 22) //!< for stereoCalibrate + }; + +//! the algorithm for finding fundamental matrix +enum { FM_7POINT = 1, //!< 7-point algorithm + FM_8POINT = 2, //!< 8-point algorithm + FM_LMEDS = 4, //!< least-median algorithm. 7-point algorithm is used. + FM_RANSAC = 8 //!< RANSAC algorithm. It needs at least 15 points. 7-point algorithm is used. + }; + +enum HandEyeCalibrationMethod +{ + CALIB_HAND_EYE_TSAI = 0, //!< A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/Eye Calibration @cite Tsai89 + CALIB_HAND_EYE_PARK = 1, //!< Robot Sensor Calibration: Solving AX = XB on the Euclidean Group @cite Park94 + CALIB_HAND_EYE_HORAUD = 2, //!< Hand-eye Calibration @cite Horaud95 + CALIB_HAND_EYE_ANDREFF = 3, //!< On-line Hand-Eye Calibration @cite Andreff99 + CALIB_HAND_EYE_DANIILIDIS = 4 //!< Hand-Eye Calibration Using Dual Quaternions @cite Daniilidis98 +}; + +enum RobotWorldHandEyeCalibrationMethod +{ + CALIB_ROBOT_WORLD_HAND_EYE_SHAH = 0, //!< Solving the robot-world/hand-eye calibration problem using the kronecker product @cite Shah2013SolvingTR + CALIB_ROBOT_WORLD_HAND_EYE_LI = 1 //!< Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product @cite Li2010SimultaneousRA +}; + +enum SamplingMethod { SAMPLING_UNIFORM=0, SAMPLING_PROGRESSIVE_NAPSAC=1, SAMPLING_NAPSAC=2, + SAMPLING_PROSAC=3 }; +enum LocalOptimMethod {LOCAL_OPTIM_NULL=0, LOCAL_OPTIM_INNER_LO=1, LOCAL_OPTIM_INNER_AND_ITER_LO=2, + LOCAL_OPTIM_GC=3, LOCAL_OPTIM_SIGMA=4}; +enum ScoreMethod {SCORE_METHOD_RANSAC=0, SCORE_METHOD_MSAC=1, SCORE_METHOD_MAGSAC=2, SCORE_METHOD_LMEDS=3}; +enum NeighborSearchMethod { NEIGH_FLANN_KNN=0, NEIGH_GRID=1, NEIGH_FLANN_RADIUS=2 }; +enum PolishingMethod { NONE_POLISHER=0, LSQ_POLISHER=1, MAGSAC=2, COV_POLISHER=3 }; + +struct CV_EXPORTS_W_SIMPLE UsacParams +{ // in alphabetical order + CV_WRAP UsacParams(); + CV_PROP_RW double confidence; + CV_PROP_RW bool isParallel; + CV_PROP_RW int loIterations; + CV_PROP_RW LocalOptimMethod loMethod; + CV_PROP_RW int loSampleSize; + CV_PROP_RW int maxIterations; + CV_PROP_RW NeighborSearchMethod neighborsSearch; + CV_PROP_RW int randomGeneratorState; + CV_PROP_RW SamplingMethod sampler; + CV_PROP_RW ScoreMethod score; + CV_PROP_RW double threshold; + CV_PROP_RW PolishingMethod final_polisher; + CV_PROP_RW int final_polisher_iterations; +}; + +/** @brief Converts a rotation matrix to a rotation vector or vice versa. + +@param src Input rotation vector (3x1 or 1x3) or rotation matrix (3x3). +@param dst Output rotation matrix (3x3) or rotation vector (3x1 or 1x3), respectively. +@param jacobian Optional output Jacobian matrix, 3x9 or 9x3, which is a matrix of partial +derivatives of the output array components with respect to the input array components. + +\f[\begin{array}{l} \theta \leftarrow norm(r) \\ r \leftarrow r/ \theta \\ R = \cos(\theta) I + (1- \cos{\theta} ) r r^T + \sin(\theta) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} \end{array}\f] + +Inverse transformation can be also done easily, since + +\f[\sin ( \theta ) \vecthreethree{0}{-r_z}{r_y}{r_z}{0}{-r_x}{-r_y}{r_x}{0} = \frac{R - R^T}{2}\f] + +A rotation vector is a convenient and most compact representation of a rotation matrix (since any +rotation matrix has just 3 degrees of freedom). The representation is used in the global 3D geometry +optimization procedures like @ref calibrateCamera, @ref stereoCalibrate, or @ref solvePnP . + +@note More information about the computation of the derivative of a 3D rotation matrix with respect to its exponential coordinate +can be found in: + - A Compact Formula for the Derivative of a 3-D Rotation in Exponential Coordinates, Guillermo Gallego, Anthony J. Yezzi @cite Gallego2014ACF + +@note Useful information on SE(3) and Lie Groups can be found in: + - A tutorial on SE(3) transformation parameterizations and on-manifold optimization, Jose-Luis Blanco @cite blanco2010tutorial + - Lie Groups for 2D and 3D Transformation, Ethan Eade @cite Eade17 + - A micro Lie theory for state estimation in robotics, Joan Solà, Jérémie Deray, Dinesh Atchuthan @cite Sol2018AML + */ +CV_EXPORTS_W void Rodrigues( InputArray src, OutputArray dst, OutputArray jacobian = noArray() ); + + + +/** Levenberg-Marquardt solver. Starting with the specified vector of parameters it + optimizes the target vector criteria "err" + (finds local minima of each target vector component absolute value). + + When needed, it calls user-provided callback. +*/ +class CV_EXPORTS LMSolver : public Algorithm +{ +public: + class CV_EXPORTS Callback + { + public: + virtual ~Callback() {} + /** + computes error and Jacobian for the specified vector of parameters + + @param param the current vector of parameters + @param err output vector of errors: err_i = actual_f_i - ideal_f_i + @param J output Jacobian: J_ij = d(ideal_f_i)/d(param_j) + + when J=noArray(), it means that it does not need to be computed. + Dimensionality of error vector and param vector can be different. + The callback should explicitly allocate (with "create" method) each output array + (unless it's noArray()). + */ + virtual bool compute(InputArray param, OutputArray err, OutputArray J) const = 0; + }; + + /** + Runs Levenberg-Marquardt algorithm using the passed vector of parameters as the start point. + The final vector of parameters (whether the algorithm converged or not) is stored at the same + vector. The method returns the number of iterations used. If it's equal to the previously specified + maxIters, there is a big chance the algorithm did not converge. + + @param param initial/final vector of parameters. + + Note that the dimensionality of parameter space is defined by the size of param vector, + and the dimensionality of optimized criteria is defined by the size of err vector + computed by the callback. + */ + virtual int run(InputOutputArray param) const = 0; + + /** + Sets the maximum number of iterations + @param maxIters the number of iterations + */ + virtual void setMaxIters(int maxIters) = 0; + /** + Retrieves the current maximum number of iterations + */ + virtual int getMaxIters() const = 0; + + /** + Creates Levenberg-Marquard solver + + @param cb callback + @param maxIters maximum number of iterations that can be further + modified using setMaxIters() method. + */ + static Ptr create(const Ptr& cb, int maxIters); + static Ptr create(const Ptr& cb, int maxIters, double eps); +}; + + + +/** @example samples/cpp/tutorial_code/features2D/Homography/pose_from_homography.cpp +An example program about pose estimation from coplanar points + +Check @ref tutorial_homography "the corresponding tutorial" for more details +*/ + +/** @brief Finds a perspective transformation between two planes. + +@param srcPoints Coordinates of the points in the original plane, a matrix of the type CV_32FC2 +or vector\ . +@param dstPoints Coordinates of the points in the target plane, a matrix of the type CV_32FC2 or +a vector\ . +@param method Method used to compute a homography matrix. The following methods are possible: +- **0** - a regular method using all the points, i.e., the least squares method +- @ref RANSAC - RANSAC-based robust method +- @ref LMEDS - Least-Median robust method +- @ref RHO - PROSAC-based robust method +@param ransacReprojThreshold Maximum allowed reprojection error to treat a point pair as an inlier +(used in the RANSAC and RHO methods only). That is, if +\f[\| \texttt{dstPoints} _i - \texttt{convertPointsHomogeneous} ( \texttt{H} \cdot \texttt{srcPoints} _i) \|_2 > \texttt{ransacReprojThreshold}\f] +then the point \f$i\f$ is considered as an outlier. If srcPoints and dstPoints are measured in pixels, +it usually makes sense to set this parameter somewhere in the range of 1 to 10. +@param mask Optional output mask set by a robust method ( RANSAC or LMeDS ). Note that the input +mask values are ignored. +@param maxIters The maximum number of RANSAC iterations. +@param confidence Confidence level, between 0 and 1. + +The function finds and returns the perspective transformation \f$H\f$ between the source and the +destination planes: + +\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] + +so that the back-projection error + +\f[\sum _i \left ( x'_i- \frac{h_{11} x_i + h_{12} y_i + h_{13}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2+ \left ( y'_i- \frac{h_{21} x_i + h_{22} y_i + h_{23}}{h_{31} x_i + h_{32} y_i + h_{33}} \right )^2\f] + +is minimized. If the parameter method is set to the default value 0, the function uses all the point +pairs to compute an initial homography estimate with a simple least-squares scheme. + +However, if not all of the point pairs ( \f$srcPoints_i\f$, \f$dstPoints_i\f$ ) fit the rigid perspective +transformation (that is, there are some outliers), this initial estimate will be poor. In this case, +you can use one of the three robust methods. The methods RANSAC, LMeDS and RHO try many different +random subsets of the corresponding point pairs (of four pairs each, collinear pairs are discarded), estimate the homography matrix +using this subset and a simple least-squares algorithm, and then compute the quality/goodness of the +computed homography (which is the number of inliers for RANSAC or the least median re-projection error for +LMeDS). The best subset is then used to produce the initial estimate of the homography matrix and +the mask of inliers/outliers. + +Regardless of the method, robust or not, the computed homography matrix is refined further (using +inliers only in case of a robust method) with the Levenberg-Marquardt method to reduce the +re-projection error even more. + +The methods RANSAC and RHO can handle practically any ratio of outliers but need a threshold to +distinguish inliers from outliers. The method LMeDS does not need any threshold but it works +correctly only when there are more than 50% of inliers. Finally, if there are no outliers and the +noise is rather small, use the default method (method=0). + +The function is used to find initial intrinsic and extrinsic matrices. Homography matrix is +determined up to a scale. If \f$h_{33}\f$ is non-zero, the matrix is normalized so that \f$h_{33}=1\f$. +@note Whenever an \f$H\f$ matrix cannot be estimated, an empty one will be returned. + +@sa +getAffineTransform, estimateAffine2D, estimateAffinePartial2D, getPerspectiveTransform, warpPerspective, +perspectiveTransform + */ +CV_EXPORTS_W Mat findHomography( InputArray srcPoints, InputArray dstPoints, + int method = 0, double ransacReprojThreshold = 3, + OutputArray mask=noArray(), const int maxIters = 2000, + const double confidence = 0.995); + +/** @overload */ +CV_EXPORTS Mat findHomography( InputArray srcPoints, InputArray dstPoints, + OutputArray mask, int method = 0, double ransacReprojThreshold = 3 ); + + +CV_EXPORTS_W Mat findHomography(InputArray srcPoints, InputArray dstPoints, OutputArray mask, + const UsacParams ¶ms); + +/** @brief Computes an RQ decomposition of 3x3 matrices. + +@param src 3x3 input matrix. +@param mtxR Output 3x3 upper-triangular matrix. +@param mtxQ Output 3x3 orthogonal matrix. +@param Qx Optional output 3x3 rotation matrix around x-axis. +@param Qy Optional output 3x3 rotation matrix around y-axis. +@param Qz Optional output 3x3 rotation matrix around z-axis. + +The function computes a RQ decomposition using the given rotations. This function is used in +#decomposeProjectionMatrix to decompose the left 3x3 submatrix of a projection matrix into a camera +and a rotation matrix. + +It optionally returns three rotation matrices, one for each axis, and the three Euler angles in +degrees (as the return value) that could be used in OpenGL. Note, there is always more than one +sequence of rotations about the three principal axes that results in the same orientation of an +object, e.g. see @cite Slabaugh . Returned three rotation matrices and corresponding three Euler angles +are only one of the possible solutions. + */ +CV_EXPORTS_W Vec3d RQDecomp3x3( InputArray src, OutputArray mtxR, OutputArray mtxQ, + OutputArray Qx = noArray(), + OutputArray Qy = noArray(), + OutputArray Qz = noArray()); + +/** @brief Decomposes a projection matrix into a rotation matrix and a camera intrinsic matrix. + +@param projMatrix 3x4 input projection matrix P. +@param cameraMatrix Output 3x3 camera intrinsic matrix \f$\cameramatrix{A}\f$. +@param rotMatrix Output 3x3 external rotation matrix R. +@param transVect Output 4x1 translation vector T. +@param rotMatrixX Optional 3x3 rotation matrix around x-axis. +@param rotMatrixY Optional 3x3 rotation matrix around y-axis. +@param rotMatrixZ Optional 3x3 rotation matrix around z-axis. +@param eulerAngles Optional three-element vector containing three Euler angles of rotation in +degrees. + +The function computes a decomposition of a projection matrix into a calibration and a rotation +matrix and the position of a camera. + +It optionally returns three rotation matrices, one for each axis, and three Euler angles that could +be used in OpenGL. Note, there is always more than one sequence of rotations about the three +principal axes that results in the same orientation of an object, e.g. see @cite Slabaugh . Returned +three rotation matrices and corresponding three Euler angles are only one of the possible solutions. + +The function is based on #RQDecomp3x3 . + */ +CV_EXPORTS_W void decomposeProjectionMatrix( InputArray projMatrix, OutputArray cameraMatrix, + OutputArray rotMatrix, OutputArray transVect, + OutputArray rotMatrixX = noArray(), + OutputArray rotMatrixY = noArray(), + OutputArray rotMatrixZ = noArray(), + OutputArray eulerAngles =noArray() ); + +/** @brief Computes partial derivatives of the matrix product for each multiplied matrix. + +@param A First multiplied matrix. +@param B Second multiplied matrix. +@param dABdA First output derivative matrix d(A\*B)/dA of size +\f$\texttt{A.rows*B.cols} \times {A.rows*A.cols}\f$ . +@param dABdB Second output derivative matrix d(A\*B)/dB of size +\f$\texttt{A.rows*B.cols} \times {B.rows*B.cols}\f$ . + +The function computes partial derivatives of the elements of the matrix product \f$A*B\f$ with regard to +the elements of each of the two input matrices. The function is used to compute the Jacobian +matrices in #stereoCalibrate but can also be used in any other similar optimization function. + */ +CV_EXPORTS_W void matMulDeriv( InputArray A, InputArray B, OutputArray dABdA, OutputArray dABdB ); + +/** @brief Combines two rotation-and-shift transformations. + +@param rvec1 First rotation vector. +@param tvec1 First translation vector. +@param rvec2 Second rotation vector. +@param tvec2 Second translation vector. +@param rvec3 Output rotation vector of the superposition. +@param tvec3 Output translation vector of the superposition. +@param dr3dr1 Optional output derivative of rvec3 with regard to rvec1 +@param dr3dt1 Optional output derivative of rvec3 with regard to tvec1 +@param dr3dr2 Optional output derivative of rvec3 with regard to rvec2 +@param dr3dt2 Optional output derivative of rvec3 with regard to tvec2 +@param dt3dr1 Optional output derivative of tvec3 with regard to rvec1 +@param dt3dt1 Optional output derivative of tvec3 with regard to tvec1 +@param dt3dr2 Optional output derivative of tvec3 with regard to rvec2 +@param dt3dt2 Optional output derivative of tvec3 with regard to tvec2 + +The functions compute: + +\f[\begin{array}{l} \texttt{rvec3} = \mathrm{rodrigues} ^{-1} \left ( \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \mathrm{rodrigues} ( \texttt{rvec1} ) \right ) \\ \texttt{tvec3} = \mathrm{rodrigues} ( \texttt{rvec2} ) \cdot \texttt{tvec1} + \texttt{tvec2} \end{array} ,\f] + +where \f$\mathrm{rodrigues}\f$ denotes a rotation vector to a rotation matrix transformation, and +\f$\mathrm{rodrigues}^{-1}\f$ denotes the inverse transformation. See #Rodrigues for details. + +Also, the functions can compute the derivatives of the output vectors with regards to the input +vectors (see #matMulDeriv ). The functions are used inside #stereoCalibrate but can also be used in +your own code where Levenberg-Marquardt or another gradient-based solver is used to optimize a +function that contains a matrix multiplication. + */ +CV_EXPORTS_W void composeRT( InputArray rvec1, InputArray tvec1, + InputArray rvec2, InputArray tvec2, + OutputArray rvec3, OutputArray tvec3, + OutputArray dr3dr1 = noArray(), OutputArray dr3dt1 = noArray(), + OutputArray dr3dr2 = noArray(), OutputArray dr3dt2 = noArray(), + OutputArray dt3dr1 = noArray(), OutputArray dt3dt1 = noArray(), + OutputArray dt3dr2 = noArray(), OutputArray dt3dt2 = noArray() ); + +/** @brief Projects 3D points to an image plane. + +@param objectPoints Array of object points expressed wrt. the world coordinate frame. A 3xN/Nx3 +1-channel or 1xN/Nx1 3-channel (or vector\ ), where N is the number of points in the view. +@param rvec The rotation vector (@ref Rodrigues) that, together with tvec, performs a change of +basis from world to camera coordinate system, see @ref calibrateCamera for details. +@param tvec The translation vector, see parameter description above. +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$ . If the vector is empty, the zero distortion coefficients are assumed. +@param imagePoints Output array of image points, 1xN/Nx1 2-channel, or +vector\ . +@param jacobian Optional output 2Nx(10+\) jacobian matrix of derivatives of image +points with respect to components of the rotation vector, translation vector, focal lengths, +coordinates of the principal point and the distortion coefficients. In the old interface different +components of the jacobian are returned via different output parameters. +@param aspectRatio Optional "fixed aspect ratio" parameter. If the parameter is not 0, the +function assumes that the aspect ratio (\f$f_x / f_y\f$) is fixed and correspondingly adjusts the +jacobian matrix. + +The function computes the 2D projections of 3D points to the image plane, given intrinsic and +extrinsic camera parameters. Optionally, the function computes Jacobians -matrices of partial +derivatives of image points coordinates (as functions of all the input parameters) with respect to +the particular parameters, intrinsic and/or extrinsic. The Jacobians are used during the global +optimization in @ref calibrateCamera, @ref solvePnP, and @ref stereoCalibrate. The function itself +can also be used to compute a re-projection error, given the current intrinsic and extrinsic +parameters. + +@note By setting rvec = tvec = \f$[0, 0, 0]\f$, or by setting cameraMatrix to a 3x3 identity matrix, +or by passing zero distortion coefficients, one can get various useful partial cases of the +function. This means, one can compute the distorted coordinates for a sparse set of points or apply +a perspective transformation (and also compute the derivatives) in the ideal zero-distortion setup. + */ +CV_EXPORTS_W void projectPoints( InputArray objectPoints, + InputArray rvec, InputArray tvec, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray imagePoints, + OutputArray jacobian = noArray(), + double aspectRatio = 0 ); + +/** @example samples/cpp/tutorial_code/features2D/Homography/homography_from_camera_displacement.cpp +An example program about homography from the camera displacement + +Check @ref tutorial_homography "the corresponding tutorial" for more details +*/ + +/** @brief Finds an object pose from 3D-2D point correspondences. + +@see @ref calib3d_solvePnP + +This function returns the rotation and the translation vectors that transform a 3D point expressed in the object +coordinate frame to the camera coordinate frame, using different methods: +- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. +- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. +- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. +Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] +- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or +1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. +@param tvec Output translation vector. +@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses +the provided rvec and tvec values as initial approximations of the rotation and translation +vectors, respectively, and further optimizes them. +@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags + +More information about Perspective-n-Points is described in @ref calib3d_solvePnP + +@note + - An example of how to use solvePnP for planar augmented reality can be found at + opencv_source_code/samples/python/plane_ar.py + - If you are using Python: + - Numpy array slices won't work as input because solvePnP requires contiguous + arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of + modules/calib3d/src/solvepnp.cpp version 2.4.9) + - The P3P algorithm requires image points to be in an array of shape (N,1,2) due + to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) + which requires 2-channel information. + - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of + it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = + np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) + - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are + unstable and sometimes give completely wrong results. If you pass one of these two + flags, @ref SOLVEPNP_EPNP method will be used instead. + - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P + methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions + of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). + - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points + are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the + global solution to converge. + - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. + - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. + Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] + - With @ref SOLVEPNP_SQPNP input points must be >= 3 + */ +CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, + bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE ); + +/** @brief Finds an object pose from 3D-2D point correspondences using the RANSAC scheme. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or +1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. +@param tvec Output translation vector. +@param useExtrinsicGuess Parameter used for @ref SOLVEPNP_ITERATIVE. If true (1), the function uses +the provided rvec and tvec values as initial approximations of the rotation and translation +vectors, respectively, and further optimizes them. +@param iterationsCount Number of iterations. +@param reprojectionError Inlier threshold value used by the RANSAC procedure. The parameter value +is the maximum allowed distance between the observed and computed point projections to consider it +an inlier. +@param confidence The probability that the algorithm produces a useful result. +@param inliers Output vector that contains indices of inliers in objectPoints and imagePoints . +@param flags Method for solving a PnP problem (see @ref solvePnP ). + +The function estimates an object pose given a set of object points, their corresponding image +projections, as well as the camera intrinsic matrix and the distortion coefficients. This function finds such +a pose that minimizes reprojection error, that is, the sum of squared distances between the observed +projections imagePoints and the projected (using @ref projectPoints ) objectPoints. The use of RANSAC +makes the function resistant to outliers. + +@note + - An example of how to use solvePNPRansac for object detection can be found at + opencv_source_code/samples/cpp/tutorial_code/calib3d/real_time_pose_estimation/ + - The default method used to estimate the camera pose for the Minimal Sample Sets step + is #SOLVEPNP_EPNP. Exceptions are: + - if you choose #SOLVEPNP_P3P or #SOLVEPNP_AP3P, these methods will be used. + - if the number of input points is equal to 4, #SOLVEPNP_P3P is used. + - The method used to estimate the camera pose using all the inliers is defined by the + flags parameters unless it is equal to #SOLVEPNP_P3P or #SOLVEPNP_AP3P. In this case, + the method #SOLVEPNP_EPNP will be used instead. + */ +CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, + bool useExtrinsicGuess = false, int iterationsCount = 100, + float reprojectionError = 8.0, double confidence = 0.99, + OutputArray inliers = noArray(), int flags = SOLVEPNP_ITERATIVE ); + + +/* +Finds rotation and translation vector. +If cameraMatrix is given then run P3P. Otherwise run linear P6P and output cameraMatrix too. +*/ +CV_EXPORTS_W bool solvePnPRansac( InputArray objectPoints, InputArray imagePoints, + InputOutputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, OutputArray inliers, + const UsacParams ¶ms=UsacParams()); + +/** @brief Finds an object pose from 3 3D-2D point correspondences. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, 3x3 1-channel or +1x3/3x1 3-channel. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, 3x2 1-channel or 1x3/3x1 2-channel. + vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvecs Output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from +the model coordinate system to the camera coordinate system. A P3P problem has up to 4 solutions. +@param tvecs Output translation vectors. +@param flags Method for solving a P3P problem: +- @ref SOLVEPNP_P3P Method is based on the paper of X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang +"Complete Solution Classification for the Perspective-Three-Point Problem" (@cite gao2003complete). +- @ref SOLVEPNP_AP3P Method is based on the paper of T. Ke and S. Roumeliotis. +"An Efficient Algebraic Solution to the Perspective-Three-Point Problem" (@cite Ke17). + +The function estimates the object pose given 3 object points, their corresponding image +projections, as well as the camera intrinsic matrix and the distortion coefficients. + +@note +The solutions are sorted by reprojection errors (lowest to highest). + */ +CV_EXPORTS_W int solveP3P( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + int flags ); + +/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame +to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, +where N is the number of points. vector\ can also be passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can also be passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. Input values are used as an initial solution. +@param tvec Input/Output translation vector. Input values are used as an initial solution. +@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. + +The function refines the object pose given at least 3 object points, their corresponding image +projections, an initial solution for the rotation and translation vector, +as well as the camera intrinsic matrix and the distortion coefficients. +The function minimizes the projection error with respect to the rotation and the translation vectors, according +to a Levenberg-Marquardt iterative minimization @cite Madsen04 @cite Eade13 process. + */ +CV_EXPORTS_W void solvePnPRefineLM( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + InputOutputArray rvec, InputOutputArray tvec, + TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON)); + +/** @brief Refine a pose (the translation and the rotation that transform a 3D point expressed in the object coordinate frame +to the camera coordinate frame) from a 3D-2D point correspondences and starting from an initial solution. + +@see @ref calib3d_solvePnP + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or 1xN/Nx1 3-channel, +where N is the number of points. vector\ can also be passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can also be passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvec Input/Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. Input values are used as an initial solution. +@param tvec Input/Output translation vector. Input values are used as an initial solution. +@param criteria Criteria when to stop the Levenberg-Marquard iterative algorithm. +@param VVSlambda Gain for the virtual visual servoing control law, equivalent to the \f$\alpha\f$ +gain in the Damped Gauss-Newton formulation. + +The function refines the object pose given at least 3 object points, their corresponding image +projections, an initial solution for the rotation and translation vector, +as well as the camera intrinsic matrix and the distortion coefficients. +The function minimizes the projection error with respect to the rotation and the translation vectors, using a +virtual visual servoing (VVS) @cite Chaumette06 @cite Marchand16 scheme. + */ +CV_EXPORTS_W void solvePnPRefineVVS( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + InputOutputArray rvec, InputOutputArray tvec, + TermCriteria criteria = TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 20, FLT_EPSILON), + double VVSlambda = 1); + +/** @brief Finds an object pose from 3D-2D point correspondences. + +@see @ref calib3d_solvePnP + +This function returns a list of all the possible solutions (a solution is a +couple), depending on the number of input points and the chosen method: +- P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): 3 or 4 input points. Number of returned solutions can be between 0 and 4 with 3 input points. +- @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. Returns 2 solutions. +- @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. +Number of input points must be 4 and 2 solutions are returned. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] +- for all the other flags, number of input points must be >= 4 and object points can be in any configuration. +Only 1 solution is returned. + +@param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or +1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. +@param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, +where N is the number of points. vector\ can be also passed here. +@param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param rvecs Vector of output rotation vectors (see @ref Rodrigues ) that, together with tvecs, brings points from +the model coordinate system to the camera coordinate system. +@param tvecs Vector of output translation vectors. +@param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses +the provided rvec and tvec values as initial approximations of the rotation and translation +vectors, respectively, and further optimizes them. +@param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags +@param rvec Rotation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE +and useExtrinsicGuess is set to true. +@param tvec Translation vector used to initialize an iterative PnP refinement algorithm, when flag is @ref SOLVEPNP_ITERATIVE +and useExtrinsicGuess is set to true. +@param reprojectionError Optional vector of reprojection error, that is the RMS error +(\f$ \text{RMSE} = \sqrt{\frac{\sum_{i}^{N} \left ( \hat{y_i} - y_i \right )^2}{N}} \f$) between the input image points +and the 3D object points projected with the estimated pose. + +More information is described in @ref calib3d_solvePnP + +@note + - An example of how to use solvePnP for planar augmented reality can be found at + opencv_source_code/samples/python/plane_ar.py + - If you are using Python: + - Numpy array slices won't work as input because solvePnP requires contiguous + arrays (enforced by the assertion using cv::Mat::checkVector() around line 55 of + modules/calib3d/src/solvepnp.cpp version 2.4.9) + - The P3P algorithm requires image points to be in an array of shape (N,1,2) due + to its calling of #undistortPoints (around line 75 of modules/calib3d/src/solvepnp.cpp version 2.4.9) + which requires 2-channel information. + - Thus, given some data D = np.array(...) where D.shape = (N,M), in order to use a subset of + it as, e.g., imagePoints, one must effectively copy it into a new array: imagePoints = + np.ascontiguousarray(D[:,:2]).reshape((N,1,2)) + - The methods @ref SOLVEPNP_DLS and @ref SOLVEPNP_UPNP cannot be used as the current implementations are + unstable and sometimes give completely wrong results. If you pass one of these two + flags, @ref SOLVEPNP_EPNP method will be used instead. + - The minimum number of points is 4 in the general case. In the case of @ref SOLVEPNP_P3P and @ref SOLVEPNP_AP3P + methods, it is required to use exactly 4 points (the first 3 points are used to estimate all the solutions + of the P3P problem, the last one is used to retain the best solution that minimizes the reprojection error). + - With @ref SOLVEPNP_ITERATIVE method and `useExtrinsicGuess=true`, the minimum number of points is 3 (3 points + are sufficient to compute a pose but there are up to 4 solutions). The initial solution should be close to the + global solution to converge. + - With @ref SOLVEPNP_IPPE input points must be >= 4 and object points must be coplanar. + - With @ref SOLVEPNP_IPPE_SQUARE this is a special case suitable for marker pose estimation. + Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] + */ +CV_EXPORTS_W int solvePnPGeneric( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + bool useExtrinsicGuess = false, SolvePnPMethod flags = SOLVEPNP_ITERATIVE, + InputArray rvec = noArray(), InputArray tvec = noArray(), + OutputArray reprojectionError = noArray() ); + +/** @brief Finds an initial camera intrinsic matrix from 3D-2D point correspondences. + +@param objectPoints Vector of vectors of the calibration pattern points in the calibration pattern +coordinate space. In the old interface all the per-view vectors are concatenated. See +#calibrateCamera for details. +@param imagePoints Vector of vectors of the projections of the calibration pattern points. In the +old interface all the per-view vectors are concatenated. +@param imageSize Image size in pixels used to initialize the principal point. +@param aspectRatio If it is zero or negative, both \f$f_x\f$ and \f$f_y\f$ are estimated independently. +Otherwise, \f$f_x = f_y \cdot \texttt{aspectRatio}\f$ . + +The function estimates and returns an initial camera intrinsic matrix for the camera calibration process. +Currently, the function only supports planar calibration patterns, which are patterns where each +object point has z-coordinate =0. + */ +CV_EXPORTS_W Mat initCameraMatrix2D( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, + Size imageSize, double aspectRatio = 1.0 ); + +/** @brief Finds the positions of internal corners of the chessboard. + +@param image Source chessboard view. It must be an 8-bit grayscale or color image. +@param patternSize Number of inner corners per a chessboard row and column +( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). +@param corners Output array of detected corners. +@param flags Various operation flags that can be zero or a combination of the following values: +- @ref CALIB_CB_ADAPTIVE_THRESH Use adaptive thresholding to convert the image to black +and white, rather than a fixed threshold level (computed from the average image brightness). +- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with #equalizeHist before +applying fixed or adaptive thresholding. +- @ref CALIB_CB_FILTER_QUADS Use additional criteria (like contour area, perimeter, +square-like shape) to filter out false quads extracted at the contour retrieval stage. +- @ref CALIB_CB_FAST_CHECK Run a fast check on the image that looks for chessboard corners, +and shortcut the call if none is found. This can drastically speed up the call in the +degenerate condition when no chessboard is observed. +- @ref CALIB_CB_PLAIN All other flags are ignored. The input image is taken as is. +No image processing is done to improve to find the checkerboard. This has the effect of speeding up the +execution of the function but could lead to not recognizing the checkerboard if the image +is not previously binarized in the appropriate manner. + +The function attempts to determine whether the input image is a view of the chessboard pattern and +locate the internal chessboard corners. The function returns a non-zero value if all of the corners +are found and they are placed in a certain order (row by row, left to right in every row). +Otherwise, if the function fails to find all the corners or reorder them, it returns 0. For example, +a regular chessboard has 8 x 8 squares and 7 x 7 internal corners, that is, points where the black +squares touch each other. The detected coordinates are approximate, and to determine their positions +more accurately, the function calls #cornerSubPix. You also may use the function #cornerSubPix with +different parameters if returned coordinates are not accurate enough. + +Sample usage of detecting and drawing chessboard corners: : +@code + Size patternsize(8,6); //interior number of corners + Mat gray = ....; //source image + vector corners; //this will be filled by the detected corners + + //CALIB_CB_FAST_CHECK saves a lot of time on images + //that do not contain any chessboard corners + bool patternfound = findChessboardCorners(gray, patternsize, corners, + CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE + + CALIB_CB_FAST_CHECK); + + if(patternfound) + cornerSubPix(gray, corners, Size(11, 11), Size(-1, -1), + TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); + + drawChessboardCorners(img, patternsize, Mat(corners), patternfound); +@endcode +@note The function requires white space (like a square-thick border, the wider the better) around +the board to make the detection more robust in various environments. Otherwise, if there is no +border and the background is dark, the outer black squares cannot be segmented properly and so the +square grouping and ordering algorithm fails. + +Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. + */ +CV_EXPORTS_W bool findChessboardCorners( InputArray image, Size patternSize, OutputArray corners, + int flags = CALIB_CB_ADAPTIVE_THRESH + CALIB_CB_NORMALIZE_IMAGE ); + +/* + Checks whether the image contains chessboard of the specific size or not. + If yes, nonzero value is returned. +*/ +CV_EXPORTS_W bool checkChessboard(InputArray img, Size size); + +/** @brief Finds the positions of internal corners of the chessboard using a sector based approach. + +@param image Source chessboard view. It must be an 8-bit grayscale or color image. +@param patternSize Number of inner corners per a chessboard row and column +( patternSize = cv::Size(points_per_row,points_per_colum) = cv::Size(columns,rows) ). +@param corners Output array of detected corners. +@param flags Various operation flags that can be zero or a combination of the following values: +- @ref CALIB_CB_NORMALIZE_IMAGE Normalize the image gamma with equalizeHist before detection. +- @ref CALIB_CB_EXHAUSTIVE Run an exhaustive search to improve detection rate. +- @ref CALIB_CB_ACCURACY Up sample input image to improve sub-pixel accuracy due to aliasing effects. +- @ref CALIB_CB_LARGER The detected pattern is allowed to be larger than patternSize (see description). +- @ref CALIB_CB_MARKER The detected pattern must have a marker (see description). +This should be used if an accurate camera calibration is required. +@param meta Optional output arrray of detected corners (CV_8UC1 and size = cv::Size(columns,rows)). +Each entry stands for one corner of the pattern and can have one of the following values: +- 0 = no meta data attached +- 1 = left-top corner of a black cell +- 2 = left-top corner of a white cell +- 3 = left-top corner of a black cell with a white marker dot +- 4 = left-top corner of a white cell with a black marker dot (pattern origin in case of markers otherwise first corner) + +The function is analog to #findChessboardCorners but uses a localized radon +transformation approximated by box filters being more robust to all sort of +noise, faster on larger images and is able to directly return the sub-pixel +position of the internal chessboard corners. The Method is based on the paper +@cite duda2018 "Accurate Detection and Localization of Checkerboard Corners for +Calibration" demonstrating that the returned sub-pixel positions are more +accurate than the one returned by cornerSubPix allowing a precise camera +calibration for demanding applications. + +In the case, the flags @ref CALIB_CB_LARGER or @ref CALIB_CB_MARKER are given, +the result can be recovered from the optional meta array. Both flags are +helpful to use calibration patterns exceeding the field of view of the camera. +These oversized patterns allow more accurate calibrations as corners can be +utilized, which are as close as possible to the image borders. For a +consistent coordinate system across all images, the optional marker (see image +below) can be used to move the origin of the board to the location where the +black circle is located. + +@note The function requires a white boarder with roughly the same width as one +of the checkerboard fields around the whole board to improve the detection in +various environments. In addition, because of the localized radon +transformation it is beneficial to use round corners for the field corners +which are located on the outside of the board. The following figure illustrates +a sample checkerboard optimized for the detection. However, any other checkerboard +can be used as well. + +Use gen_pattern.py (@ref tutorial_camera_calibration_pattern) to create checkerboard. +![Checkerboard](pics/checkerboard_radon.png) + */ +CV_EXPORTS_AS(findChessboardCornersSBWithMeta) +bool findChessboardCornersSB(InputArray image,Size patternSize, OutputArray corners, + int flags,OutputArray meta); +/** @overload */ +CV_EXPORTS_W inline +bool findChessboardCornersSB(InputArray image, Size patternSize, OutputArray corners, + int flags = 0) +{ + return findChessboardCornersSB(image, patternSize, corners, flags, noArray()); +} + +/** @brief Estimates the sharpness of a detected chessboard. + +Image sharpness, as well as brightness, are a critical parameter for accuracte +camera calibration. For accessing these parameters for filtering out +problematic calibraiton images, this method calculates edge profiles by traveling from +black to white chessboard cell centers. Based on this, the number of pixels is +calculated required to transit from black to white. This width of the +transition area is a good indication of how sharp the chessboard is imaged +and should be below ~3.0 pixels. + +@param image Gray image used to find chessboard corners +@param patternSize Size of a found chessboard pattern +@param corners Corners found by #findChessboardCornersSB +@param rise_distance Rise distance 0.8 means 10% ... 90% of the final signal strength +@param vertical By default edge responses for horizontal lines are calculated +@param sharpness Optional output array with a sharpness value for calculated edge responses (see description) + +The optional sharpness array is of type CV_32FC1 and has for each calculated +profile one row with the following five entries: +* 0 = x coordinate of the underlying edge in the image +* 1 = y coordinate of the underlying edge in the image +* 2 = width of the transition area (sharpness) +* 3 = signal strength in the black cell (min brightness) +* 4 = signal strength in the white cell (max brightness) + +@return Scalar(average sharpness, average min brightness, average max brightness,0) +*/ +CV_EXPORTS_W Scalar estimateChessboardSharpness(InputArray image, Size patternSize, InputArray corners, + float rise_distance=0.8F,bool vertical=false, + OutputArray sharpness=noArray()); + + +//! finds subpixel-accurate positions of the chessboard corners +CV_EXPORTS_W bool find4QuadCornerSubpix( InputArray img, InputOutputArray corners, Size region_size ); + +/** @brief Renders the detected chessboard corners. + +@param image Destination image. It must be an 8-bit color image. +@param patternSize Number of inner corners per a chessboard row and column +(patternSize = cv::Size(points_per_row,points_per_column)). +@param corners Array of detected corners, the output of #findChessboardCorners. +@param patternWasFound Parameter indicating whether the complete board was found or not. The +return value of #findChessboardCorners should be passed here. + +The function draws individual chessboard corners detected either as red circles if the board was not +found, or as colored corners connected with lines if the board was found. + */ +CV_EXPORTS_W void drawChessboardCorners( InputOutputArray image, Size patternSize, + InputArray corners, bool patternWasFound ); + +/** @brief Draw axes of the world/object coordinate system from pose estimation. @sa solvePnP + +@param image Input/output image. It must have 1 or 3 channels. The number of channels is not altered. +@param cameraMatrix Input 3x3 floating-point matrix of camera intrinsic parameters. +\f$\cameramatrix{A}\f$ +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is empty, the zero distortion coefficients are assumed. +@param rvec Rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from +the model coordinate system to the camera coordinate system. +@param tvec Translation vector. +@param length Length of the painted axes in the same unit than tvec (usually in meters). +@param thickness Line thickness of the painted axes. + +This function draws the axes of the world/object coordinate system w.r.t. to the camera frame. +OX is drawn in red, OY in green and OZ in blue. + */ +CV_EXPORTS_W void drawFrameAxes(InputOutputArray image, InputArray cameraMatrix, InputArray distCoeffs, + InputArray rvec, InputArray tvec, float length, int thickness=3); + +struct CV_EXPORTS_W_SIMPLE CirclesGridFinderParameters +{ + CV_WRAP CirclesGridFinderParameters(); + CV_PROP_RW cv::Size2f densityNeighborhoodSize; + CV_PROP_RW float minDensity; + CV_PROP_RW int kmeansAttempts; + CV_PROP_RW int minDistanceToAddKeypoint; + CV_PROP_RW int keypointScale; + CV_PROP_RW float minGraphConfidence; + CV_PROP_RW float vertexGain; + CV_PROP_RW float vertexPenalty; + CV_PROP_RW float existingVertexGain; + CV_PROP_RW float edgeGain; + CV_PROP_RW float edgePenalty; + CV_PROP_RW float convexHullFactor; + CV_PROP_RW float minRNGEdgeSwitchDist; + + enum GridType + { + SYMMETRIC_GRID, ASYMMETRIC_GRID + }; + GridType gridType; + + CV_PROP_RW float squareSize; //!< Distance between two adjacent points. Used by CALIB_CB_CLUSTERING. + CV_PROP_RW float maxRectifiedDistance; //!< Max deviation from prediction. Used by CALIB_CB_CLUSTERING. +}; + +#ifndef DISABLE_OPENCV_3_COMPATIBILITY +typedef CirclesGridFinderParameters CirclesGridFinderParameters2; +#endif + +/** @brief Finds centers in the grid of circles. + +@param image grid view of input circles; it must be an 8-bit grayscale or color image. +@param patternSize number of circles per row and column +( patternSize = Size(points_per_row, points_per_colum) ). +@param centers output array of detected centers. +@param flags various operation flags that can be one of the following values: +- @ref CALIB_CB_SYMMETRIC_GRID uses symmetric pattern of circles. +- @ref CALIB_CB_ASYMMETRIC_GRID uses asymmetric pattern of circles. +- @ref CALIB_CB_CLUSTERING uses a special algorithm for grid detection. It is more robust to +perspective distortions but much more sensitive to background clutter. +@param blobDetector feature detector that finds blobs like dark circles on light background. + If `blobDetector` is NULL then `image` represents Point2f array of candidates. +@param parameters struct for finding circles in a grid pattern. + +The function attempts to determine whether the input image contains a grid of circles. If it is, the +function locates centers of the circles. The function returns a non-zero value if all of the centers +have been found and they have been placed in a certain order (row by row, left to right in every +row). Otherwise, if the function fails to find all the corners or reorder them, it returns 0. + +Sample usage of detecting and drawing the centers of circles: : +@code + Size patternsize(7,7); //number of centers + Mat gray = ...; //source image + vector centers; //this will be filled by the detected centers + + bool patternfound = findCirclesGrid(gray, patternsize, centers); + + drawChessboardCorners(img, patternsize, Mat(centers), patternfound); +@endcode +@note The function requires white space (like a square-thick border, the wider the better) around +the board to make the detection more robust in various environments. + */ +CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, + OutputArray centers, int flags, + const Ptr &blobDetector, + const CirclesGridFinderParameters& parameters); + +/** @overload */ +CV_EXPORTS_W bool findCirclesGrid( InputArray image, Size patternSize, + OutputArray centers, int flags = CALIB_CB_SYMMETRIC_GRID, + const Ptr &blobDetector = SimpleBlobDetector::create()); + +/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration +pattern. + +@param objectPoints In the new interface it is a vector of vectors of calibration pattern points in +the calibration pattern coordinate space (e.g. std::vector>). The outer +vector contains as many elements as the number of pattern views. If the same calibration pattern +is shown in each view and it is fully visible, all the vectors will be the same. Although, it is +possible to use partially occluded patterns or even different patterns in different views. Then, +the vectors will be different. Although the points are 3D, they all lie in the calibration pattern's +XY coordinate plane (thus 0 in the Z-coordinate), if the used calibration pattern is a planar rig. +In the old interface all the vectors of object points from different views are concatenated +together. +@param imagePoints In the new interface it is a vector of vectors of the projections of calibration +pattern points (e.g. std::vector>). imagePoints.size() and +objectPoints.size(), and imagePoints[i].size() and objectPoints[i].size() for each i, must be equal, +respectively. In the old interface all the vectors of object points from different views are +concatenated together. +@param imageSize Size of the image used only to initialize the camera intrinsic matrix. +@param cameraMatrix Input/output 3x3 floating-point camera intrinsic matrix +\f$\cameramatrix{A}\f$ . If @ref CALIB_USE_INTRINSIC_GUESS +and/or @ref CALIB_FIX_ASPECT_RATIO, @ref CALIB_FIX_PRINCIPAL_POINT or @ref CALIB_FIX_FOCAL_LENGTH +are specified, some or all of fx, fy, cx, cy must be initialized before calling the function. +@param distCoeffs Input/output vector of distortion coefficients +\f$\distcoeffs\f$. +@param rvecs Output vector of rotation vectors (@ref Rodrigues ) estimated for each pattern view +(e.g. std::vector>). That is, each i-th rotation vector together with the corresponding +i-th translation vector (see the next output parameter description) brings the calibration pattern +from the object coordinate space (in which object points are specified) to the camera coordinate +space. In more technical terms, the tuple of the i-th rotation and translation vector performs +a change of basis from object coordinate space to camera coordinate space. Due to its duality, this +tuple is equivalent to the position of the calibration pattern with respect to the camera coordinate +space. +@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter +describtion above. +@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic +parameters. Order of deviations values: +\f$(f_x, f_y, c_x, c_y, k_1, k_2, p_1, p_2, k_3, k_4, k_5, k_6 , s_1, s_2, s_3, + s_4, \tau_x, \tau_y)\f$ If one of parameters is not estimated, it's deviation is equals to zero. +@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic +parameters. Order of deviations values: \f$(R_0, T_0, \dotsc , R_{M - 1}, T_{M - 1})\f$ where M is +the number of pattern views. \f$R_i, T_i\f$ are concatenated 1x3 vectors. + @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. +@param flags Different flags that may be zero or a combination of the following values: +- @ref CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of +fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image +center ( imageSize is used), and focal distances are computed in a least-squares fashion. +Note, that if intrinsic parameters are known, there is no need to use this function just to +estimate extrinsic parameters. Use @ref solvePnP instead. +- @ref CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global +optimization. It stays at the center or at a different location specified when + @ref CALIB_USE_INTRINSIC_GUESS is set too. +- @ref CALIB_FIX_ASPECT_RATIO The functions consider only fy as a free parameter. The +ratio fx/fy stays the same as in the input cameraMatrix . When + @ref CALIB_USE_INTRINSIC_GUESS is not set, the actual input values of fx and fy are +ignored, only their ratio is computed and used further. +- @ref CALIB_ZERO_TANGENT_DIST Tangential distortion coefficients \f$(p_1, p_2)\f$ are set +to zeros and stay zero. +- @ref CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global optimization if + @ref CALIB_USE_INTRINSIC_GUESS is set. +- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 The corresponding radial distortion +coefficient is not changed during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is +set, the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_RATIONAL_MODEL Coefficients k4, k5, and k6 are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the rational model and return 8 coefficients or more. +- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the thin prism model and return 12 coefficients or more. +- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the tilted sensor model and return 14 coefficients. +- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +@param criteria Termination criteria for the iterative optimization algorithm. + +@return the overall RMS re-projection error. + +The function estimates the intrinsic camera parameters and extrinsic parameters for each of the +views. The algorithm is based on @cite Zhang2000 and @cite BouguetMCT . The coordinates of 3D object +points and their corresponding 2D projections in each view must be specified. That may be achieved +by using an object with known geometry and easily detectable feature points. Such an object is +called a calibration rig or calibration pattern, and OpenCV has built-in support for a chessboard as +a calibration rig (see @ref findChessboardCorners). Currently, initialization of intrinsic +parameters (when @ref CALIB_USE_INTRINSIC_GUESS is not set) is only implemented for planar calibration +patterns (where Z-coordinates of the object points must be all zeros). 3D calibration rigs can also +be used as long as initial cameraMatrix is provided. + +The algorithm performs the following steps: + +- Compute the initial intrinsic parameters (the option only available for planar calibration + patterns) or read them from the input parameters. The distortion coefficients are all set to + zeros initially unless some of CALIB_FIX_K? are specified. + +- Estimate the initial camera pose as if the intrinsic parameters have been already known. This is + done using @ref solvePnP . + +- Run the global Levenberg-Marquardt optimization algorithm to minimize the reprojection error, + that is, the total sum of squared distances between the observed feature points imagePoints and + the projected (using the current estimates for camera parameters and the poses) object points + objectPoints. See @ref projectPoints for details. + +@note + If you use a non-square (i.e. non-N-by-N) grid and @ref findChessboardCorners for calibration, + and @ref calibrateCamera returns bad values (zero distortion coefficients, \f$c_x\f$ and + \f$c_y\f$ very far from the image center, and/or large differences between \f$f_x\f$ and + \f$f_y\f$ (ratios of 10:1 or more)), then you are probably using patternSize=cvSize(rows,cols) + instead of using patternSize=cvSize(cols,rows) in @ref findChessboardCorners. + +@note + The function may throw exceptions, if unsupported combination of parameters is provided or + the system is underconstrained. + +@sa + calibrateCameraRO, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, + undistort + */ +CV_EXPORTS_AS(calibrateCameraExtended) double calibrateCamera( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + OutputArray stdDeviationsIntrinsics, + OutputArray stdDeviationsExtrinsics, + OutputArray perViewErrors, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @overload */ +CV_EXPORTS_W double calibrateCamera( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @brief Finds the camera intrinsic and extrinsic parameters from several views of a calibration pattern. + +This function is an extension of #calibrateCamera with the method of releasing object which was +proposed in @cite strobl2011iccv. In many common cases with inaccurate, unmeasured, roughly planar +targets (calibration plates), this method can dramatically improve the precision of the estimated +camera parameters. Both the object-releasing method and standard method are supported by this +function. Use the parameter **iFixedPoint** for method selection. In the internal implementation, +#calibrateCamera is a wrapper for this function. + +@param objectPoints Vector of vectors of calibration pattern points in the calibration pattern +coordinate space. See #calibrateCamera for details. If the method of releasing object to be used, +the identical calibration board must be used in each view and it must be fully visible, and all +objectPoints[i] must be the same and all points should be roughly close to a plane. **The calibration +target has to be rigid, or at least static if the camera (rather than the calibration target) is +shifted for grabbing images.** +@param imagePoints Vector of vectors of the projections of calibration pattern points. See +#calibrateCamera for details. +@param imageSize Size of the image used only to initialize the intrinsic camera matrix. +@param iFixedPoint The index of the 3D object point in objectPoints[0] to be fixed. It also acts as +a switch for calibration method selection. If object-releasing method to be used, pass in the +parameter in the range of [1, objectPoints[0].size()-2], otherwise a value out of this range will +make standard calibration method selected. Usually the top-right corner point of the calibration +board grid is recommended to be fixed when object-releasing method being utilized. According to +\cite strobl2011iccv, two other points are also fixed. In this implementation, objectPoints[0].front +and objectPoints[0].back.z are used. With object-releasing method, accurate rvecs, tvecs and +newObjPoints are only possible if coordinates of these three fixed points are accurate enough. +@param cameraMatrix Output 3x3 floating-point camera matrix. See #calibrateCamera for details. +@param distCoeffs Output vector of distortion coefficients. See #calibrateCamera for details. +@param rvecs Output vector of rotation vectors estimated for each pattern view. See #calibrateCamera +for details. +@param tvecs Output vector of translation vectors estimated for each pattern view. +@param newObjPoints The updated output vector of calibration pattern points. The coordinates might +be scaled based on three fixed points. The returned coordinates are accurate only if the above +mentioned three fixed points are accurate. If not needed, noArray() can be passed in. This parameter +is ignored with standard calibration method. +@param stdDeviationsIntrinsics Output vector of standard deviations estimated for intrinsic parameters. +See #calibrateCamera for details. +@param stdDeviationsExtrinsics Output vector of standard deviations estimated for extrinsic parameters. +See #calibrateCamera for details. +@param stdDeviationsObjPoints Output vector of standard deviations estimated for refined coordinates +of calibration pattern points. It has the same size and order as objectPoints[0] vector. This +parameter is ignored with standard calibration method. + @param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. +@param flags Different flags that may be zero or a combination of some predefined values. See +#calibrateCamera for details. If the method of releasing object is used, the calibration time may +be much longer. CALIB_USE_QR or CALIB_USE_LU could be used for faster calibration with potentially +less precise and less stable in some rare cases. +@param criteria Termination criteria for the iterative optimization algorithm. + +@return the overall RMS re-projection error. + +The function estimates the intrinsic camera parameters and extrinsic parameters for each of the +views. The algorithm is based on @cite Zhang2000, @cite BouguetMCT and @cite strobl2011iccv. See +#calibrateCamera for other detailed explanations. +@sa + calibrateCamera, findChessboardCorners, solvePnP, initCameraMatrix2D, stereoCalibrate, undistort + */ +CV_EXPORTS_AS(calibrateCameraROExtended) double calibrateCameraRO( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + OutputArray newObjPoints, + OutputArray stdDeviationsIntrinsics, + OutputArray stdDeviationsExtrinsics, + OutputArray stdDeviationsObjPoints, + OutputArray perViewErrors, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @overload */ +CV_EXPORTS_W double calibrateCameraRO( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints, Size imageSize, int iFixedPoint, + InputOutputArray cameraMatrix, InputOutputArray distCoeffs, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, + OutputArray newObjPoints, + int flags = 0, TermCriteria criteria = TermCriteria( + TermCriteria::COUNT + TermCriteria::EPS, 30, DBL_EPSILON) ); + +/** @brief Computes useful camera characteristics from the camera intrinsic matrix. + +@param cameraMatrix Input camera intrinsic matrix that can be estimated by #calibrateCamera or +#stereoCalibrate . +@param imageSize Input image size in pixels. +@param apertureWidth Physical width in mm of the sensor. +@param apertureHeight Physical height in mm of the sensor. +@param fovx Output field of view in degrees along the horizontal sensor axis. +@param fovy Output field of view in degrees along the vertical sensor axis. +@param focalLength Focal length of the lens in mm. +@param principalPoint Principal point in mm. +@param aspectRatio \f$f_y/f_x\f$ + +The function computes various useful camera characteristics from the previously estimated camera +matrix. + +@note + Do keep in mind that the unity measure 'mm' stands for whatever unit of measure one chooses for + the chessboard pitch (it can thus be any value). + */ +CV_EXPORTS_W void calibrationMatrixValues( InputArray cameraMatrix, Size imageSize, + double apertureWidth, double apertureHeight, + CV_OUT double& fovx, CV_OUT double& fovy, + CV_OUT double& focalLength, CV_OUT Point2d& principalPoint, + CV_OUT double& aspectRatio ); + +/** @brief Calibrates a stereo camera set up. This function finds the intrinsic parameters +for each of the two cameras and the extrinsic parameters between the two cameras. + +@param objectPoints Vector of vectors of the calibration pattern points. The same structure as +in @ref calibrateCamera. For each pattern view, both cameras need to see the same object +points. Therefore, objectPoints.size(), imagePoints1.size(), and imagePoints2.size() need to be +equal as well as objectPoints[i].size(), imagePoints1[i].size(), and imagePoints2[i].size() need to +be equal for each i. +@param imagePoints1 Vector of vectors of the projections of the calibration pattern points, +observed by the first camera. The same structure as in @ref calibrateCamera. +@param imagePoints2 Vector of vectors of the projections of the calibration pattern points, +observed by the second camera. The same structure as in @ref calibrateCamera. +@param cameraMatrix1 Input/output camera intrinsic matrix for the first camera, the same as in +@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. +@param distCoeffs1 Input/output vector of distortion coefficients, the same as in +@ref calibrateCamera. +@param cameraMatrix2 Input/output second camera intrinsic matrix for the second camera. See description for +cameraMatrix1. +@param distCoeffs2 Input/output lens distortion coefficients for the second camera. See +description for distCoeffs1. +@param imageSize Size of the image used only to initialize the camera intrinsic matrices. +@param R Output rotation matrix. Together with the translation vector T, this matrix brings +points given in the first camera's coordinate system to points in the second camera's +coordinate system. In more technical terms, the tuple of R and T performs a change of basis +from the first camera's coordinate system to the second camera's coordinate system. Due to its +duality, this tuple is equivalent to the position of the first camera with respect to the +second camera coordinate system. +@param T Output translation vector, see description above. +@param E Output essential matrix. +@param F Output fundamental matrix. +@param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the +coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each +i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter +description) brings the calibration pattern from the object coordinate space (in which object points are +specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, +the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space +to camera coordinate space of the first camera of the stereo pair. +@param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description +of previous output parameter ( rvecs ). +@param perViewErrors Output vector of the RMS re-projection error estimated for each pattern view. +@param flags Different flags that may be zero or a combination of the following values: +- @ref CALIB_FIX_INTRINSIC Fix cameraMatrix? and distCoeffs? so that only R, T, E, and F +matrices are estimated. +- @ref CALIB_USE_INTRINSIC_GUESS Optimize some or all of the intrinsic parameters +according to the specified flags. Initial values are provided by the user. +- @ref CALIB_USE_EXTRINSIC_GUESS R and T contain valid initial values that are optimized further. +Otherwise R and T are initialized to the median value of the pattern views (each dimension separately). +- @ref CALIB_FIX_PRINCIPAL_POINT Fix the principal points during the optimization. +- @ref CALIB_FIX_FOCAL_LENGTH Fix \f$f^{(j)}_x\f$ and \f$f^{(j)}_y\f$ . +- @ref CALIB_FIX_ASPECT_RATIO Optimize \f$f^{(j)}_y\f$ . Fix the ratio \f$f^{(j)}_x/f^{(j)}_y\f$ +. +- @ref CALIB_SAME_FOCAL_LENGTH Enforce \f$f^{(0)}_x=f^{(1)}_x\f$ and \f$f^{(0)}_y=f^{(1)}_y\f$ . +- @ref CALIB_ZERO_TANGENT_DIST Set tangential distortion coefficients for each camera to +zeros and fix there. +- @ref CALIB_FIX_K1,..., @ref CALIB_FIX_K6 Do not change the corresponding radial +distortion coefficient during the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, +the coefficient from the supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_RATIONAL_MODEL Enable coefficients k4, k5, and k6. To provide the backward +compatibility, this extra flag should be explicitly specified to make the calibration +function use the rational model and return 8 coefficients. If the flag is not set, the +function computes and returns only 5 distortion coefficients. +- @ref CALIB_THIN_PRISM_MODEL Coefficients s1, s2, s3 and s4 are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the thin prism model and return 12 coefficients. If the flag is not +set, the function computes and returns only 5 distortion coefficients. +- @ref CALIB_FIX_S1_S2_S3_S4 The thin prism distortion coefficients are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +- @ref CALIB_TILTED_MODEL Coefficients tauX and tauY are enabled. To provide the +backward compatibility, this extra flag should be explicitly specified to make the +calibration function use the tilted sensor model and return 14 coefficients. If the flag is not +set, the function computes and returns only 5 distortion coefficients. +- @ref CALIB_FIX_TAUX_TAUY The coefficients of the tilted sensor model are not changed during +the optimization. If @ref CALIB_USE_INTRINSIC_GUESS is set, the coefficient from the +supplied distCoeffs matrix is used. Otherwise, it is set to 0. +@param criteria Termination criteria for the iterative optimization algorithm. + +The function estimates the transformation between two cameras making a stereo pair. If one computes +the poses of an object relative to the first camera and to the second camera, +( \f$R_1\f$,\f$T_1\f$ ) and (\f$R_2\f$,\f$T_2\f$), respectively, for a stereo camera where the +relative position and orientation between the two cameras are fixed, then those poses definitely +relate to each other. This means, if the relative position and orientation (\f$R\f$,\f$T\f$) of the +two cameras is known, it is possible to compute (\f$R_2\f$,\f$T_2\f$) when (\f$R_1\f$,\f$T_1\f$) is +given. This is what the described function does. It computes (\f$R\f$,\f$T\f$) such that: + +\f[R_2=R R_1\f] +\f[T_2=R T_1 + T.\f] + +Therefore, one can compute the coordinate representation of a 3D point for the second camera's +coordinate system when given the point's coordinate representation in the first camera's coordinate +system: + +\f[\begin{bmatrix} +X_2 \\ +Y_2 \\ +Z_2 \\ +1 +\end{bmatrix} = \begin{bmatrix} +R & T \\ +0 & 1 +\end{bmatrix} \begin{bmatrix} +X_1 \\ +Y_1 \\ +Z_1 \\ +1 +\end{bmatrix}.\f] + + +Optionally, it computes the essential matrix E: + +\f[E= \vecthreethree{0}{-T_2}{T_1}{T_2}{0}{-T_0}{-T_1}{T_0}{0} R\f] + +where \f$T_i\f$ are components of the translation vector \f$T\f$ : \f$T=[T_0, T_1, T_2]^T\f$ . +And the function can also compute the fundamental matrix F: + +\f[F = cameraMatrix2^{-T}\cdot E \cdot cameraMatrix1^{-1}\f] + +Besides the stereo-related information, the function can also perform a full calibration of each of +the two cameras. However, due to the high dimensionality of the parameter space and noise in the +input data, the function can diverge from the correct solution. If the intrinsic parameters can be +estimated with high accuracy for each of the cameras individually (for example, using +#calibrateCamera ), you are recommended to do so and then pass @ref CALIB_FIX_INTRINSIC flag to the +function along with the computed intrinsic parameters. Otherwise, if all the parameters are +estimated at once, it makes sense to restrict some parameters, for example, pass + @ref CALIB_SAME_FOCAL_LENGTH and @ref CALIB_ZERO_TANGENT_DIST flags, which is usually a +reasonable assumption. + +Similarly to #calibrateCamera, the function minimizes the total re-projection error for all the +points in all the available views from both cameras. The function returns the final value of the +re-projection error. + */ +CV_EXPORTS_AS(stereoCalibrateExtended) double stereoCalibrate( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, + OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); + +/// @overload +CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, OutputArray R,OutputArray T, OutputArray E, OutputArray F, + int flags = CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); + +/// @overload +CV_EXPORTS_W double stereoCalibrate( InputArrayOfArrays objectPoints, + InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray cameraMatrix1, InputOutputArray distCoeffs1, + InputOutputArray cameraMatrix2, InputOutputArray distCoeffs2, + Size imageSize, InputOutputArray R, InputOutputArray T, OutputArray E, OutputArray F, + OutputArray perViewErrors, int flags = CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 1e-6) ); + +/** @brief Computes rectification transforms for each head of a calibrated stereo camera. + +@param cameraMatrix1 First camera intrinsic matrix. +@param distCoeffs1 First camera distortion parameters. +@param cameraMatrix2 Second camera intrinsic matrix. +@param distCoeffs2 Second camera distortion parameters. +@param imageSize Size of the image used for stereo calibration. +@param R Rotation matrix from the coordinate system of the first camera to the second camera, +see @ref stereoCalibrate. +@param T Translation vector from the coordinate system of the first camera to the second camera, +see @ref stereoCalibrate. +@param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. This matrix +brings points given in the unrectified first camera's coordinate system to points in the rectified +first camera's coordinate system. In more technical terms, it performs a change of basis from the +unrectified first camera's coordinate system to the rectified first camera's coordinate system. +@param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. This matrix +brings points given in the unrectified second camera's coordinate system to points in the rectified +second camera's coordinate system. In more technical terms, it performs a change of basis from the +unrectified second camera's coordinate system to the rectified second camera's coordinate system. +@param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first +camera, i.e. it projects points given in the rectified first camera coordinate system into the +rectified first camera's image. +@param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second +camera, i.e. it projects points given in the rectified first camera coordinate system into the +rectified second camera's image. +@param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see @ref reprojectImageTo3D). +@param flags Operation flags that may be zero or @ref CALIB_ZERO_DISPARITY . If the flag is set, +the function makes the principal points of each camera have the same pixel coordinates in the +rectified views. And if the flag is not set, the function may still shift the images in the +horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the +useful image area. +@param alpha Free scaling parameter. If it is -1 or absent, the function performs the default +scaling. Otherwise, the parameter should be between 0 and 1. alpha=0 means that the rectified +images are zoomed and shifted so that only valid pixels are visible (no black areas after +rectification). alpha=1 means that the rectified image is decimated and shifted so that all the +pixels from the original images from the cameras are retained in the rectified images (no source +image pixels are lost). Any intermediate value yields an intermediate result between +those two extreme cases. +@param newImageSize New image resolution after rectification. The same size should be passed to +#initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) +is passed (default), it is set to the original imageSize . Setting it to a larger value can help you +preserve details in the original image, especially when there is a big radial distortion. +@param validPixROI1 Optional output rectangles inside the rectified images where all the pixels +are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller +(see the picture below). +@param validPixROI2 Optional output rectangles inside the rectified images where all the pixels +are valid. If alpha=0 , the ROIs cover the whole images. Otherwise, they are likely to be smaller +(see the picture below). + +The function computes the rotation matrices for each camera that (virtually) make both camera image +planes the same plane. Consequently, this makes all the epipolar lines parallel and thus simplifies +the dense stereo correspondence problem. The function takes the matrices computed by #stereoCalibrate +as input. As output, it provides two rotation matrices and also two projection matrices in the new +coordinates. The function distinguishes the following two cases: + +- **Horizontal stereo**: the first and the second camera views are shifted relative to each other + mainly along the x-axis (with possible small vertical shift). In the rectified images, the + corresponding epipolar lines in the left and right cameras are horizontal and have the same + y-coordinate. P1 and P2 look like: + + \f[\texttt{P1} = \begin{bmatrix} + f & 0 & cx_1 & 0 \\ + 0 & f & cy & 0 \\ + 0 & 0 & 1 & 0 + \end{bmatrix}\f] + + \f[\texttt{P2} = \begin{bmatrix} + f & 0 & cx_2 & T_x \cdot f \\ + 0 & f & cy & 0 \\ + 0 & 0 & 1 & 0 + \end{bmatrix} ,\f] + + \f[\texttt{Q} = \begin{bmatrix} + 1 & 0 & 0 & -cx_1 \\ + 0 & 1 & 0 & -cy \\ + 0 & 0 & 0 & f \\ + 0 & 0 & -\frac{1}{T_x} & \frac{cx_1 - cx_2}{T_x} + \end{bmatrix} \f] + + where \f$T_x\f$ is a horizontal shift between the cameras and \f$cx_1=cx_2\f$ if + @ref CALIB_ZERO_DISPARITY is set. + +- **Vertical stereo**: the first and the second camera views are shifted relative to each other + mainly in the vertical direction (and probably a bit in the horizontal direction too). The epipolar + lines in the rectified images are vertical and have the same x-coordinate. P1 and P2 look like: + + \f[\texttt{P1} = \begin{bmatrix} + f & 0 & cx & 0 \\ + 0 & f & cy_1 & 0 \\ + 0 & 0 & 1 & 0 + \end{bmatrix}\f] + + \f[\texttt{P2} = \begin{bmatrix} + f & 0 & cx & 0 \\ + 0 & f & cy_2 & T_y \cdot f \\ + 0 & 0 & 1 & 0 + \end{bmatrix},\f] + + \f[\texttt{Q} = \begin{bmatrix} + 1 & 0 & 0 & -cx \\ + 0 & 1 & 0 & -cy_1 \\ + 0 & 0 & 0 & f \\ + 0 & 0 & -\frac{1}{T_y} & \frac{cy_1 - cy_2}{T_y} + \end{bmatrix} \f] + + where \f$T_y\f$ is a vertical shift between the cameras and \f$cy_1=cy_2\f$ if + @ref CALIB_ZERO_DISPARITY is set. + +As you can see, the first three columns of P1 and P2 will effectively be the new "rectified" camera +matrices. The matrices, together with R1 and R2 , can then be passed to #initUndistortRectifyMap to +initialize the rectification map for each camera. + +See below the screenshot from the stereo_calib.cpp sample. Some red horizontal lines pass through +the corresponding image regions. This means that the images are well rectified, which is what most +stereo correspondence algorithms rely on. The green rectangles are roi1 and roi2 . You see that +their interiors are all valid pixels. + +![image](pics/stereo_undistort.jpg) + */ +CV_EXPORTS_W void stereoRectify( InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + Size imageSize, InputArray R, InputArray T, + OutputArray R1, OutputArray R2, + OutputArray P1, OutputArray P2, + OutputArray Q, int flags = CALIB_ZERO_DISPARITY, + double alpha = -1, Size newImageSize = Size(), + CV_OUT Rect* validPixROI1 = 0, CV_OUT Rect* validPixROI2 = 0 ); + +/** @brief Computes a rectification transform for an uncalibrated stereo camera. + +@param points1 Array of feature points in the first image. +@param points2 The corresponding points in the second image. The same formats as in +#findFundamentalMat are supported. +@param F Input fundamental matrix. It can be computed from the same set of point pairs using +#findFundamentalMat . +@param imgSize Size of the image. +@param H1 Output rectification homography matrix for the first image. +@param H2 Output rectification homography matrix for the second image. +@param threshold Optional threshold used to filter out the outliers. If the parameter is greater +than zero, all the point pairs that do not comply with the epipolar geometry (that is, the points +for which \f$|\texttt{points2[i]}^T \cdot \texttt{F} \cdot \texttt{points1[i]}|>\texttt{threshold}\f$ ) +are rejected prior to computing the homographies. Otherwise, all the points are considered inliers. + +The function computes the rectification transformations without knowing intrinsic parameters of the +cameras and their relative position in the space, which explains the suffix "uncalibrated". Another +related difference from #stereoRectify is that the function outputs not the rectification +transformations in the object (3D) space, but the planar perspective transformations encoded by the +homography matrices H1 and H2 . The function implements the algorithm @cite Hartley99 . + +@note + While the algorithm does not need to know the intrinsic parameters of the cameras, it heavily + depends on the epipolar geometry. Therefore, if the camera lenses have a significant distortion, + it would be better to correct it before computing the fundamental matrix and calling this + function. For example, distortion coefficients can be estimated for each head of stereo camera + separately by using #calibrateCamera . Then, the images can be corrected using #undistort , or + just the point coordinates can be corrected with #undistortPoints . + */ +CV_EXPORTS_W bool stereoRectifyUncalibrated( InputArray points1, InputArray points2, + InputArray F, Size imgSize, + OutputArray H1, OutputArray H2, + double threshold = 5 ); + +//! computes the rectification transformations for 3-head camera, where all the heads are on the same line. +CV_EXPORTS_W float rectify3Collinear( InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + InputArray cameraMatrix3, InputArray distCoeffs3, + InputArrayOfArrays imgpt1, InputArrayOfArrays imgpt3, + Size imageSize, InputArray R12, InputArray T12, + InputArray R13, InputArray T13, + OutputArray R1, OutputArray R2, OutputArray R3, + OutputArray P1, OutputArray P2, OutputArray P3, + OutputArray Q, double alpha, Size newImgSize, + CV_OUT Rect* roi1, CV_OUT Rect* roi2, int flags ); + +/** @brief Returns the new camera intrinsic matrix based on the free scaling parameter. + +@param cameraMatrix Input camera intrinsic matrix. +@param distCoeffs Input vector of distortion coefficients +\f$\distcoeffs\f$. If the vector is NULL/empty, the zero distortion coefficients are +assumed. +@param imageSize Original image size. +@param alpha Free scaling parameter between 0 (when all the pixels in the undistorted image are +valid) and 1 (when all the source image pixels are retained in the undistorted image). See +#stereoRectify for details. +@param newImgSize Image size after rectification. By default, it is set to imageSize . +@param validPixROI Optional output rectangle that outlines all-good-pixels region in the +undistorted image. See roi1, roi2 description in #stereoRectify . +@param centerPrincipalPoint Optional flag that indicates whether in the new camera intrinsic matrix the +principal point should be at the image center or not. By default, the principal point is chosen to +best fit a subset of the source image (determined by alpha) to the corrected image. +@return new_camera_matrix Output new camera intrinsic matrix. + +The function computes and returns the optimal new camera intrinsic matrix based on the free scaling parameter. +By varying this parameter, you may retrieve only sensible pixels alpha=0 , keep all the original +image pixels if there is valuable information in the corners alpha=1 , or get something in between. +When alpha\>0 , the undistorted result is likely to have some black pixels corresponding to +"virtual" pixels outside of the captured distorted image. The original camera intrinsic matrix, distortion +coefficients, the computed new camera intrinsic matrix, and newImageSize should be passed to +#initUndistortRectifyMap to produce the maps for #remap . + */ +CV_EXPORTS_W Mat getOptimalNewCameraMatrix( InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, double alpha, Size newImgSize = Size(), + CV_OUT Rect* validPixROI = 0, + bool centerPrincipalPoint = false); + +/** @brief Computes Hand-Eye calibration: \f$_{}^{g}\textrm{T}_c\f$ + +@param[in] R_gripper2base Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from gripper frame to robot base frame. +@param[in] t_gripper2base Translation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the robot base frame (\f$_{}^{b}\textrm{T}_g\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from gripper frame to robot base frame. +@param[in] R_target2cam Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from calibration target frame to camera frame. +@param[in] t_target2cam Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the target frame to the camera frame (\f$_{}^{c}\textrm{T}_t\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from calibration target frame to camera frame. +@param[out] R_cam2gripper Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point +expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). +@param[out] t_cam2gripper Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point +expressed in the camera frame to the gripper frame (\f$_{}^{g}\textrm{T}_c\f$). +@param[in] method One of the implemented Hand-Eye calibration method, see cv::HandEyeCalibrationMethod + +The function performs the Hand-Eye calibration using various methods. One approach consists in estimating the +rotation then the translation (separable solutions) and the following methods are implemented: + - R. Tsai, R. Lenz A New Technique for Fully Autonomous and Efficient 3D Robotics Hand/EyeCalibration \cite Tsai89 + - F. Park, B. Martin Robot Sensor Calibration: Solving AX = XB on the Euclidean Group \cite Park94 + - R. Horaud, F. Dornaika Hand-Eye Calibration \cite Horaud95 + +Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), +with the following implemented methods: + - N. Andreff, R. Horaud, B. Espiau On-line Hand-Eye Calibration \cite Andreff99 + - K. Daniilidis Hand-Eye Calibration Using Dual Quaternions \cite Daniilidis98 + +The following picture describes the Hand-Eye calibration problem where the transformation between a camera ("eye") +mounted on a robot gripper ("hand") has to be estimated. This configuration is called eye-in-hand. + +The eye-to-hand configuration consists in a static camera observing a calibration pattern mounted on the robot +end-effector. The transformation from the camera to the robot base frame can then be estimated by inputting +the suitable transformations to the function, see below. + +![](pics/hand-eye_figure.png) + +The calibration procedure is the following: + - a static calibration pattern is used to estimate the transformation between the target frame + and the camera frame + - the robot gripper is moved in order to acquire several poses + - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for + instance the robot kinematics +\f[ + \begin{bmatrix} + X_b\\ + Y_b\\ + Z_b\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{b}\textrm{R}_g & _{}^{b}\textrm{t}_g \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} +\f] + - for each pose, the homogeneous transformation between the calibration target frame and the camera frame is recorded using + for instance a pose estimation method (PnP) from 2D-3D point correspondences +\f[ + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{c}\textrm{R}_t & _{}^{c}\textrm{t}_t \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_t\\ + Y_t\\ + Z_t\\ + 1 + \end{bmatrix} +\f] + +The Hand-Eye calibration procedure returns the following homogeneous transformation +\f[ + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{g}\textrm{R}_c & _{}^{g}\textrm{t}_c \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} +\f] + +This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{X}\mathbf{B}\f$ equation: + - for an eye-in-hand configuration +\f[ + \begin{align*} + ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= + \hspace{0.1em} ^{b}{\textrm{T}_g}^{(2)} \hspace{0.2em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ + + (^{b}{\textrm{T}_g}^{(2)})^{-1} \hspace{0.2em} ^{b}{\textrm{T}_g}^{(1)} \hspace{0.2em} ^{g}\textrm{T}_c &= + \hspace{0.1em} ^{g}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ + + \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ + \end{align*} +\f] + + - for an eye-to-hand configuration +\f[ + \begin{align*} + ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(1)} &= + \hspace{0.1em} ^{g}{\textrm{T}_b}^{(2)} \hspace{0.2em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} \\ + + (^{g}{\textrm{T}_b}^{(2)})^{-1} \hspace{0.2em} ^{g}{\textrm{T}_b}^{(1)} \hspace{0.2em} ^{b}\textrm{T}_c &= + \hspace{0.1em} ^{b}\textrm{T}_c \hspace{0.2em} ^{c}{\textrm{T}_t}^{(2)} (^{c}{\textrm{T}_t}^{(1)})^{-1} \\ + + \textrm{A}_i \textrm{X} &= \textrm{X} \textrm{B}_i \\ + \end{align*} +\f] + +\note +Additional information can be found on this [website](http://campar.in.tum.de/Chair/HandEyeCalibration). +\note +A minimum of 2 motions with non parallel rotation axes are necessary to determine the hand-eye transformation. +So at least 3 different poses are required, but it is strongly recommended to use many more poses. + + */ +CV_EXPORTS_W void calibrateHandEye( InputArrayOfArrays R_gripper2base, InputArrayOfArrays t_gripper2base, + InputArrayOfArrays R_target2cam, InputArrayOfArrays t_target2cam, + OutputArray R_cam2gripper, OutputArray t_cam2gripper, + HandEyeCalibrationMethod method=CALIB_HAND_EYE_TSAI ); + +/** @brief Computes Robot-World/Hand-Eye calibration: \f$_{}^{w}\textrm{T}_b\f$ and \f$_{}^{c}\textrm{T}_g\f$ + +@param[in] R_world2cam Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from world frame to the camera frame. +@param[in] t_world2cam Translation part extracted from the homogeneous matrix that transforms a point +expressed in the world frame to the camera frame (\f$_{}^{c}\textrm{T}_w\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from world frame to the camera frame. +@param[in] R_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). +This is a vector (`vector`) that contains the rotation, `(3x3)` rotation matrices or `(3x1)` rotation vectors, +for all the transformations from robot base frame to the gripper frame. +@param[in] t_base2gripper Rotation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the gripper frame (\f$_{}^{g}\textrm{T}_b\f$). +This is a vector (`vector`) that contains the `(3x1)` translation vectors for all the transformations +from robot base frame to the gripper frame. +@param[out] R_base2world Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). +@param[out] t_base2world Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point +expressed in the robot base frame to the world frame (\f$_{}^{w}\textrm{T}_b\f$). +@param[out] R_gripper2cam Estimated `(3x3)` rotation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). +@param[out] t_gripper2cam Estimated `(3x1)` translation part extracted from the homogeneous matrix that transforms a point +expressed in the gripper frame to the camera frame (\f$_{}^{c}\textrm{T}_g\f$). +@param[in] method One of the implemented Robot-World/Hand-Eye calibration method, see cv::RobotWorldHandEyeCalibrationMethod + +The function performs the Robot-World/Hand-Eye calibration using various methods. One approach consists in estimating the +rotation then the translation (separable solutions): + - M. Shah, Solving the robot-world/hand-eye calibration problem using the kronecker product \cite Shah2013SolvingTR + +Another approach consists in estimating simultaneously the rotation and the translation (simultaneous solutions), +with the following implemented method: + - A. Li, L. Wang, and D. Wu, Simultaneous robot-world and hand-eye calibration using dual-quaternions and kronecker product \cite Li2010SimultaneousRA + +The following picture describes the Robot-World/Hand-Eye calibration problem where the transformations between a robot and a world frame +and between a robot gripper ("hand") and a camera ("eye") mounted at the robot end-effector have to be estimated. + +![](pics/robot-world_hand-eye_figure.png) + +The calibration procedure is the following: + - a static calibration pattern is used to estimate the transformation between the target frame + and the camera frame + - the robot gripper is moved in order to acquire several poses + - for each pose, the homogeneous transformation between the gripper frame and the robot base frame is recorded using for + instance the robot kinematics +\f[ + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{g}\textrm{R}_b & _{}^{g}\textrm{t}_b \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_b\\ + Y_b\\ + Z_b\\ + 1 + \end{bmatrix} +\f] + - for each pose, the homogeneous transformation between the calibration target frame (the world frame) and the camera frame is recorded using + for instance a pose estimation method (PnP) from 2D-3D point correspondences +\f[ + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{c}\textrm{R}_w & _{}^{c}\textrm{t}_w \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_w\\ + Y_w\\ + Z_w\\ + 1 + \end{bmatrix} +\f] + +The Robot-World/Hand-Eye calibration procedure returns the following homogeneous transformations +\f[ + \begin{bmatrix} + X_w\\ + Y_w\\ + Z_w\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{w}\textrm{R}_b & _{}^{w}\textrm{t}_b \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_b\\ + Y_b\\ + Z_b\\ + 1 + \end{bmatrix} +\f] +\f[ + \begin{bmatrix} + X_c\\ + Y_c\\ + Z_c\\ + 1 + \end{bmatrix} + = + \begin{bmatrix} + _{}^{c}\textrm{R}_g & _{}^{c}\textrm{t}_g \\ + 0_{1 \times 3} & 1 + \end{bmatrix} + \begin{bmatrix} + X_g\\ + Y_g\\ + Z_g\\ + 1 + \end{bmatrix} +\f] + +This problem is also known as solving the \f$\mathbf{A}\mathbf{X}=\mathbf{Z}\mathbf{B}\f$ equation, with: + - \f$\mathbf{A} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_w\f$ + - \f$\mathbf{X} \Leftrightarrow \hspace{0.1em} _{}^{w}\textrm{T}_b\f$ + - \f$\mathbf{Z} \Leftrightarrow \hspace{0.1em} _{}^{c}\textrm{T}_g\f$ + - \f$\mathbf{B} \Leftrightarrow \hspace{0.1em} _{}^{g}\textrm{T}_b\f$ + +\note +At least 3 measurements are required (input vectors size must be greater or equal to 3). + + */ +CV_EXPORTS_W void calibrateRobotWorldHandEye( InputArrayOfArrays R_world2cam, InputArrayOfArrays t_world2cam, + InputArrayOfArrays R_base2gripper, InputArrayOfArrays t_base2gripper, + OutputArray R_base2world, OutputArray t_base2world, + OutputArray R_gripper2cam, OutputArray t_gripper2cam, + RobotWorldHandEyeCalibrationMethod method=CALIB_ROBOT_WORLD_HAND_EYE_SHAH ); + +/** @brief Converts points from Euclidean to homogeneous space. + +@param src Input vector of N-dimensional points. +@param dst Output vector of N+1-dimensional points. + +The function converts points from Euclidean to homogeneous space by appending 1's to the tuple of +point coordinates. That is, each point (x1, x2, ..., xn) is converted to (x1, x2, ..., xn, 1). + */ +CV_EXPORTS_W void convertPointsToHomogeneous( InputArray src, OutputArray dst ); + +/** @brief Converts points from homogeneous to Euclidean space. + +@param src Input vector of N-dimensional points. +@param dst Output vector of N-1-dimensional points. + +The function converts points homogeneous to Euclidean space using perspective projection. That is, +each point (x1, x2, ... x(n-1), xn) is converted to (x1/xn, x2/xn, ..., x(n-1)/xn). When xn=0, the +output point coordinates will be (0,0,0,...). + */ +CV_EXPORTS_W void convertPointsFromHomogeneous( InputArray src, OutputArray dst ); + +/** @brief Converts points to/from homogeneous coordinates. + +@param src Input array or vector of 2D, 3D, or 4D points. +@param dst Output vector of 2D, 3D, or 4D points. + +The function converts 2D or 3D points from/to homogeneous coordinates by calling either +#convertPointsToHomogeneous or #convertPointsFromHomogeneous. + +@note The function is obsolete. Use one of the previous two functions instead. + */ +CV_EXPORTS void convertPointsHomogeneous( InputArray src, OutputArray dst ); + +/** @brief Calculates a fundamental matrix from the corresponding points in two images. + +@param points1 Array of N points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param method Method for computing a fundamental matrix. +- @ref FM_7POINT for a 7-point algorithm. \f$N = 7\f$ +- @ref FM_8POINT for an 8-point algorithm. \f$N \ge 8\f$ +- @ref FM_RANSAC for the RANSAC algorithm. \f$N \ge 8\f$ +- @ref FM_LMEDS for the LMedS algorithm. \f$N \ge 8\f$ +@param ransacReprojThreshold Parameter used only for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param confidence Parameter used for the RANSAC and LMedS methods only. It specifies a desirable level +of confidence (probability) that the estimated matrix is correct. +@param[out] mask optional output mask +@param maxIters The maximum number of robust method iterations. + +The epipolar geometry is described by the following equation: + +\f[[p_2; 1]^T F [p_1; 1] = 0\f] + +where \f$F\f$ is a fundamental matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the +second images, respectively. + +The function calculates the fundamental matrix using one of four methods listed above and returns +the found fundamental matrix. Normally just one matrix is found. But in case of the 7-point +algorithm, the function may return up to 3 solutions ( \f$9 \times 3\f$ matrix that stores all 3 +matrices sequentially). + +The calculated fundamental matrix may be passed further to #computeCorrespondEpilines that finds the +epipolar lines corresponding to the specified points. It can also be passed to +#stereoRectifyUncalibrated to compute the rectification transformation. : +@code + // Example. Estimation of fundamental matrix using the RANSAC algorithm + int point_count = 100; + vector points1(point_count); + vector points2(point_count); + + // initialize the points here ... + for( int i = 0; i < point_count; i++ ) + { + points1[i] = ...; + points2[i] = ...; + } + + Mat fundamental_matrix = + findFundamentalMat(points1, points2, FM_RANSAC, 3, 0.99); +@endcode + */ +CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, + int method, double ransacReprojThreshold, double confidence, + int maxIters, OutputArray mask = noArray() ); + +/** @overload */ +CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, + int method = FM_RANSAC, + double ransacReprojThreshold = 3., double confidence = 0.99, + OutputArray mask = noArray() ); + +/** @overload */ +CV_EXPORTS Mat findFundamentalMat( InputArray points1, InputArray points2, + OutputArray mask, int method = FM_RANSAC, + double ransacReprojThreshold = 3., double confidence = 0.99 ); + + +CV_EXPORTS_W Mat findFundamentalMat( InputArray points1, InputArray points2, + OutputArray mask, const UsacParams ¶ms); + +/** @brief Calculates an essential matrix from the corresponding points in two images. + +@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should +be floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1. +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +Note that this function assumes that points1 and points2 are feature points from cameras with the +same camera intrinsic matrix. If this assumption does not hold for your use case, use another +function overload or #undistortPoints with `P = cv::NoArray()` for both cameras to transform image +points to normalized image coordinates, which are valid for the identity camera intrinsic matrix. +When passing these coordinates, pass the identity matrix for this parameter. +@param method Method for computing an essential matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 +for the other points. The array is computed only in the RANSAC and LMedS methods. +@param maxIters The maximum number of robust method iterations. + +This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . +@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: + +\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] + +where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the +second images, respectively. The result of this function may be passed further to +#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. + */ +CV_EXPORTS_W +Mat findEssentialMat( + InputArray points1, InputArray points2, + InputArray cameraMatrix, int method = RANSAC, + double prob = 0.999, double threshold = 1.0, + int maxIters = 1000, OutputArray mask = noArray() +); + +/** @overload */ +CV_EXPORTS +Mat findEssentialMat( + InputArray points1, InputArray points2, + InputArray cameraMatrix, int method, + double prob, double threshold, + OutputArray mask +); // TODO remove from OpenCV 5.0 + +/** @overload +@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should +be floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param focal focal length of the camera. Note that this function assumes that points1 and points2 +are feature points from cameras with same focal length and principal point. +@param pp principal point of the camera. +@param method Method for computing a fundamental matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 +for the other points. The array is computed only in the RANSAC and LMedS methods. +@param maxIters The maximum number of robust method iterations. + +This function differs from the one above that it computes camera intrinsic matrix from focal length and +principal point: + +\f[A = +\begin{bmatrix} +f & 0 & x_{pp} \\ +0 & f & y_{pp} \\ +0 & 0 & 1 +\end{bmatrix}\f] + */ +CV_EXPORTS_W +Mat findEssentialMat( + InputArray points1, InputArray points2, + double focal = 1.0, Point2d pp = Point2d(0, 0), + int method = RANSAC, double prob = 0.999, + double threshold = 1.0, int maxIters = 1000, + OutputArray mask = noArray() +); + +/** @overload */ +CV_EXPORTS +Mat findEssentialMat( + InputArray points1, InputArray points2, + double focal, Point2d pp, + int method, double prob, + double threshold, OutputArray mask +); // TODO remove from OpenCV 5.0 + +/** @brief Calculates an essential matrix from the corresponding points in two images from potentially two different cameras. + +@param points1 Array of N (N \>= 5) 2D points from the first image. The point coordinates should +be floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1. +@param cameraMatrix1 Camera matrix for the first camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param cameraMatrix2 Camera matrix for the second camera \f$K = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs1 Input vector of distortion coefficients for the first camera +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param distCoeffs2 Input vector of distortion coefficients for the second camera +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param method Method for computing an essential matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param mask Output array of N elements, every element of which is set to 0 for outliers and to 1 +for the other points. The array is computed only in the RANSAC and LMedS methods. + +This function estimates essential matrix based on the five-point algorithm solver in @cite Nister03 . +@cite SteweniusCFS is also a related. The epipolar geometry is described by the following equation: + +\f[[p_2; 1]^T K^{-T} E K^{-1} [p_1; 1] = 0\f] + +where \f$E\f$ is an essential matrix, \f$p_1\f$ and \f$p_2\f$ are corresponding points in the first and the +second images, respectively. The result of this function may be passed further to +#decomposeEssentialMat or #recoverPose to recover the relative pose between cameras. + */ +CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, + InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + int method = RANSAC, + double prob = 0.999, double threshold = 1.0, + OutputArray mask = noArray() ); + + +CV_EXPORTS_W Mat findEssentialMat( InputArray points1, InputArray points2, + InputArray cameraMatrix1, InputArray cameraMatrix2, + InputArray dist_coeff1, InputArray dist_coeff2, OutputArray mask, + const UsacParams ¶ms); + +/** @brief Decompose an essential matrix to possible rotations and translation. + +@param E The input essential matrix. +@param R1 One possible rotation matrix. +@param R2 Another possible rotation matrix. +@param t One possible translation. + +This function decomposes the essential matrix E using svd decomposition @cite HartleyZ00. In +general, four possible poses exist for the decomposition of E. They are \f$[R_1, t]\f$, +\f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$. + +If E gives the epipolar constraint \f$[p_2; 1]^T A^{-T} E A^{-1} [p_1; 1] = 0\f$ between the image +points \f$p_1\f$ in the first image and \f$p_2\f$ in second image, then any of the tuples +\f$[R_1, t]\f$, \f$[R_1, -t]\f$, \f$[R_2, t]\f$, \f$[R_2, -t]\f$ is a change of basis from the first +camera's coordinate system to the second camera's coordinate system. However, by decomposing E, one +can only get the direction of the translation. For this reason, the translation t is returned with +unit length. + */ +CV_EXPORTS_W void decomposeEssentialMat( InputArray E, OutputArray R1, OutputArray R2, OutputArray t ); + +/** @brief Recovers the relative camera rotation and the translation from corresponding points in two images from two different cameras, using cheirality check. Returns the number of +inliers that pass the check. + +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param cameraMatrix1 Input/output camera matrix for the first camera, the same as in +@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. +@param distCoeffs1 Input/output vector of distortion coefficients, the same as in +@ref calibrateCamera. +@param cameraMatrix2 Input/output camera matrix for the first camera, the same as in +@ref calibrateCamera. Furthermore, for the stereo case, additional flags may be used, see below. +@param distCoeffs2 Input/output vector of distortion coefficients, the same as in +@ref calibrateCamera. +@param E The output essential matrix. +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +described below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param method Method for computing an essential matrix. +- @ref RANSAC for the RANSAC algorithm. +- @ref LMEDS for the LMedS algorithm. +@param prob Parameter used for the RANSAC or LMedS methods only. It specifies a desirable level of +confidence (probability) that the estimated matrix is correct. +@param threshold Parameter used for RANSAC. It is the maximum distance from a point to an epipolar +line in pixels, beyond which the point is considered an outlier and is not used for computing the +final fundamental matrix. It can be set to something like 1-3, depending on the accuracy of the +point localization, image resolution, and the image noise. +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for then given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the cheirality check. + +This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies +possible pose hypotheses by doing cheirality check. The cheirality check means that the +triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. + +This function can be used to process the output E and mask from @ref findEssentialMat. In this +scenario, points1 and points2 are the same input for findEssentialMat.: +@code + // Example. Estimation of fundamental matrix using the RANSAC algorithm + int point_count = 100; + vector points1(point_count); + vector points2(point_count); + + // initialize the points here ... + for( int i = 0; i < point_count; i++ ) + { + points1[i] = ...; + points2[i] = ...; + } + + // Input: camera calibration of both cameras, for example using intrinsic chessboard calibration. + Mat cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2; + + // Output: Essential matrix, relative rotation and relative translation. + Mat E, R, t, mask; + + recoverPose(points1, points2, cameraMatrix1, distCoeffs1, cameraMatrix2, distCoeffs2, E, R, t, mask); +@endcode + */ +CV_EXPORTS_W int recoverPose( InputArray points1, InputArray points2, + InputArray cameraMatrix1, InputArray distCoeffs1, + InputArray cameraMatrix2, InputArray distCoeffs2, + OutputArray E, OutputArray R, OutputArray t, + int method = cv::RANSAC, double prob = 0.999, double threshold = 1.0, + InputOutputArray mask = noArray()); + +/** @brief Recovers the relative camera rotation and the translation from an estimated essential +matrix and the corresponding points in two images, using chirality check. Returns the number of +inliers that pass the check. + +@param E The input essential matrix. +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +Note that this function assumes that points1 and points2 are feature points from cameras with the +same camera intrinsic matrix. +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +described below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the chirality check. + +This function decomposes an essential matrix using @ref decomposeEssentialMat and then verifies +possible pose hypotheses by doing chirality check. The chirality check means that the +triangulated 3D points should have positive depth. Some details can be found in @cite Nister03. + +This function can be used to process the output E and mask from @ref findEssentialMat. In this +scenario, points1 and points2 are the same input for #findEssentialMat : +@code + // Example. Estimation of fundamental matrix using the RANSAC algorithm + int point_count = 100; + vector points1(point_count); + vector points2(point_count); + + // initialize the points here ... + for( int i = 0; i < point_count; i++ ) + { + points1[i] = ...; + points2[i] = ...; + } + + // cametra matrix with both focal lengths = 1, and principal point = (0, 0) + Mat cameraMatrix = Mat::eye(3, 3, CV_64F); + + Mat E, R, t, mask; + + E = findEssentialMat(points1, points2, cameraMatrix, RANSAC, 0.999, 1.0, mask); + recoverPose(E, points1, points2, cameraMatrix, R, t, mask); +@endcode + */ +CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, + InputArray cameraMatrix, OutputArray R, OutputArray t, + InputOutputArray mask = noArray() ); + +/** @overload +@param E The input essential matrix. +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1 . +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +description below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param focal Focal length of the camera. Note that this function assumes that points1 and points2 +are feature points from cameras with same focal length and principal point. +@param pp principal point of the camera. +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the chirality check. + +This function differs from the one above that it computes camera intrinsic matrix from focal length and +principal point: + +\f[A = +\begin{bmatrix} +f & 0 & x_{pp} \\ +0 & f & y_{pp} \\ +0 & 0 & 1 +\end{bmatrix}\f] + */ +CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, + OutputArray R, OutputArray t, + double focal = 1.0, Point2d pp = Point2d(0, 0), + InputOutputArray mask = noArray() ); + +/** @overload +@param E The input essential matrix. +@param points1 Array of N 2D points from the first image. The point coordinates should be +floating-point (single or double precision). +@param points2 Array of the second image points of the same size and format as points1. +@param cameraMatrix Camera intrinsic matrix \f$\cameramatrix{A}\f$ . +Note that this function assumes that points1 and points2 are feature points from cameras with the +same camera intrinsic matrix. +@param R Output rotation matrix. Together with the translation vector, this matrix makes up a tuple +that performs a change of basis from the first camera's coordinate system to the second camera's +coordinate system. Note that, in general, t can not be used for this tuple, see the parameter +description below. +@param t Output translation vector. This vector is obtained by @ref decomposeEssentialMat and +therefore is only known up to scale, i.e. t is the direction of the translation vector and has unit +length. +@param distanceThresh threshold distance which is used to filter out far away points (i.e. infinite +points). +@param mask Input/output mask for inliers in points1 and points2. If it is not empty, then it marks +inliers in points1 and points2 for the given essential matrix E. Only these inliers will be used to +recover pose. In the output mask only inliers which pass the chirality check. +@param triangulatedPoints 3D points which were reconstructed by triangulation. + +This function differs from the one above that it outputs the triangulated 3D point that are used for +the chirality check. + */ +CV_EXPORTS_W int recoverPose( InputArray E, InputArray points1, InputArray points2, + InputArray cameraMatrix, OutputArray R, OutputArray t, double distanceThresh, InputOutputArray mask = noArray(), + OutputArray triangulatedPoints = noArray()); + +/** @brief For points in an image of a stereo pair, computes the corresponding epilines in the other image. + +@param points Input points. \f$N \times 1\f$ or \f$1 \times N\f$ matrix of type CV_32FC2 or +vector\ . +@param whichImage Index of the image (1 or 2) that contains the points . +@param F Fundamental matrix that can be estimated using #findFundamentalMat or #stereoRectify . +@param lines Output vector of the epipolar lines corresponding to the points in the other image. +Each line \f$ax + by + c=0\f$ is encoded by 3 numbers \f$(a, b, c)\f$ . + +For every point in one of the two images of a stereo pair, the function finds the equation of the +corresponding epipolar line in the other image. + +From the fundamental matrix definition (see #findFundamentalMat ), line \f$l^{(2)}_i\f$ in the second +image for the point \f$p^{(1)}_i\f$ in the first image (when whichImage=1 ) is computed as: + +\f[l^{(2)}_i = F p^{(1)}_i\f] + +And vice versa, when whichImage=2, \f$l^{(1)}_i\f$ is computed from \f$p^{(2)}_i\f$ as: + +\f[l^{(1)}_i = F^T p^{(2)}_i\f] + +Line coefficients are defined up to a scale. They are normalized so that \f$a_i^2+b_i^2=1\f$ . + */ +CV_EXPORTS_W void computeCorrespondEpilines( InputArray points, int whichImage, + InputArray F, OutputArray lines ); + +/** @brief This function reconstructs 3-dimensional points (in homogeneous coordinates) by using +their observations with a stereo camera. + +@param projMatr1 3x4 projection matrix of the first camera, i.e. this matrix projects 3D points +given in the world's coordinate system into the first image. +@param projMatr2 3x4 projection matrix of the second camera, i.e. this matrix projects 3D points +given in the world's coordinate system into the second image. +@param projPoints1 2xN array of feature points in the first image. In the case of the c++ version, +it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. +@param projPoints2 2xN array of corresponding points in the second image. In the case of the c++ +version, it can be also a vector of feature points or two-channel matrix of size 1xN or Nx1. +@param points4D 4xN array of reconstructed points in homogeneous coordinates. These points are +returned in the world's coordinate system. + +@note + Keep in mind that all input data should be of float type in order for this function to work. + +@note + If the projection matrices from @ref stereoRectify are used, then the returned points are + represented in the first camera's rectified coordinate system. + +@sa + reprojectImageTo3D + */ +CV_EXPORTS_W void triangulatePoints( InputArray projMatr1, InputArray projMatr2, + InputArray projPoints1, InputArray projPoints2, + OutputArray points4D ); + +/** @brief Refines coordinates of corresponding points. + +@param F 3x3 fundamental matrix. +@param points1 1xN array containing the first set of points. +@param points2 1xN array containing the second set of points. +@param newPoints1 The optimized points1. +@param newPoints2 The optimized points2. + +The function implements the Optimal Triangulation Method (see Multiple View Geometry @cite HartleyZ00 for details). +For each given point correspondence points1[i] \<-\> points2[i], and a fundamental matrix F, it +computes the corrected correspondences newPoints1[i] \<-\> newPoints2[i] that minimize the geometric +error \f$d(points1[i], newPoints1[i])^2 + d(points2[i],newPoints2[i])^2\f$ (where \f$d(a,b)\f$ is the +geometric distance between points \f$a\f$ and \f$b\f$ ) subject to the epipolar constraint +\f$newPoints2^T \cdot F \cdot newPoints1 = 0\f$ . + */ +CV_EXPORTS_W void correctMatches( InputArray F, InputArray points1, InputArray points2, + OutputArray newPoints1, OutputArray newPoints2 ); + +/** @brief Filters off small noise blobs (speckles) in the disparity map + +@param img The input 16-bit signed disparity image +@param newVal The disparity value used to paint-off the speckles +@param maxSpeckleSize The maximum speckle size to consider it a speckle. Larger blobs are not +affected by the algorithm +@param maxDiff Maximum difference between neighbor disparity pixels to put them into the same +blob. Note that since StereoBM, StereoSGBM and may be other algorithms return a fixed-point +disparity map, where disparity values are multiplied by 16, this scale factor should be taken into +account when specifying this parameter value. +@param buf The optional temporary buffer to avoid memory allocation within the function. + */ +CV_EXPORTS_W void filterSpeckles( InputOutputArray img, double newVal, + int maxSpeckleSize, double maxDiff, + InputOutputArray buf = noArray() ); + +//! computes valid disparity ROI from the valid ROIs of the rectified images (that are returned by #stereoRectify) +CV_EXPORTS_W Rect getValidDisparityROI( Rect roi1, Rect roi2, + int minDisparity, int numberOfDisparities, + int blockSize ); + +//! validates disparity using the left-right check. The matrix "cost" should be computed by the stereo correspondence algorithm +CV_EXPORTS_W void validateDisparity( InputOutputArray disparity, InputArray cost, + int minDisparity, int numberOfDisparities, + int disp12MaxDisp = 1 ); + +/** @brief Reprojects a disparity image to 3D space. + +@param disparity Input single-channel 8-bit unsigned, 16-bit signed, 32-bit signed or 32-bit +floating-point disparity image. The values of 8-bit / 16-bit signed formats are assumed to have no +fractional bits. If the disparity is 16-bit signed format, as computed by @ref StereoBM or +@ref StereoSGBM and maybe other algorithms, it should be divided by 16 (and scaled to float) before +being used here. +@param _3dImage Output 3-channel floating-point image of the same size as disparity. Each element of +_3dImage(x,y) contains 3D coordinates of the point (x,y) computed from the disparity map. If one +uses Q obtained by @ref stereoRectify, then the returned points are represented in the first +camera's rectified coordinate system. +@param Q \f$4 \times 4\f$ perspective transformation matrix that can be obtained with +@ref stereoRectify. +@param handleMissingValues Indicates, whether the function should handle missing values (i.e. +points where the disparity was not computed). If handleMissingValues=true, then pixels with the +minimal disparity that corresponds to the outliers (see StereoMatcher::compute ) are transformed +to 3D points with a very large Z value (currently set to 10000). +@param ddepth The optional output array depth. If it is -1, the output image will have CV_32F +depth. ddepth can also be set to CV_16S, CV_32S or CV_32F. + +The function transforms a single-channel disparity map to a 3-channel image representing a 3D +surface. That is, for each pixel (x,y) and the corresponding disparity d=disparity(x,y) , it +computes: + +\f[\begin{bmatrix} +X \\ +Y \\ +Z \\ +W +\end{bmatrix} = Q \begin{bmatrix} +x \\ +y \\ +\texttt{disparity} (x,y) \\ +1 +\end{bmatrix}.\f] + +@sa + To reproject a sparse set of points {(x,y,d),...} to 3D space, use perspectiveTransform. + */ +CV_EXPORTS_W void reprojectImageTo3D( InputArray disparity, + OutputArray _3dImage, InputArray Q, + bool handleMissingValues = false, + int ddepth = -1 ); + +/** @brief Calculates the Sampson Distance between two points. + +The function cv::sampsonDistance calculates and returns the first order approximation of the geometric error as: +\f[ +sd( \texttt{pt1} , \texttt{pt2} )= +\frac{(\texttt{pt2}^t \cdot \texttt{F} \cdot \texttt{pt1})^2} +{((\texttt{F} \cdot \texttt{pt1})(0))^2 + +((\texttt{F} \cdot \texttt{pt1})(1))^2 + +((\texttt{F}^t \cdot \texttt{pt2})(0))^2 + +((\texttt{F}^t \cdot \texttt{pt2})(1))^2} +\f] +The fundamental matrix may be calculated using the #findFundamentalMat function. See @cite HartleyZ00 11.4.3 for details. +@param pt1 first homogeneous 2d point +@param pt2 second homogeneous 2d point +@param F fundamental matrix +@return The computed Sampson distance. +*/ +CV_EXPORTS_W double sampsonDistance(InputArray pt1, InputArray pt2, InputArray F); + +/** @brief Computes an optimal affine transformation between two 3D point sets. + +It computes +\f[ +\begin{bmatrix} +x\\ +y\\ +z\\ +\end{bmatrix} += +\begin{bmatrix} +a_{11} & a_{12} & a_{13}\\ +a_{21} & a_{22} & a_{23}\\ +a_{31} & a_{32} & a_{33}\\ +\end{bmatrix} +\begin{bmatrix} +X\\ +Y\\ +Z\\ +\end{bmatrix} ++ +\begin{bmatrix} +b_1\\ +b_2\\ +b_3\\ +\end{bmatrix} +\f] + +@param src First input 3D point set containing \f$(X,Y,Z)\f$. +@param dst Second input 3D point set containing \f$(x,y,z)\f$. +@param out Output 3D affine transformation matrix \f$3 \times 4\f$ of the form +\f[ +\begin{bmatrix} +a_{11} & a_{12} & a_{13} & b_1\\ +a_{21} & a_{22} & a_{23} & b_2\\ +a_{31} & a_{32} & a_{33} & b_3\\ +\end{bmatrix} +\f] +@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). +@param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as +an inlier. +@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything +between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation +significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. + +The function estimates an optimal 3D affine transformation between two 3D point sets using the +RANSAC algorithm. + */ +CV_EXPORTS_W int estimateAffine3D(InputArray src, InputArray dst, + OutputArray out, OutputArray inliers, + double ransacThreshold = 3, double confidence = 0.99); + +/** @brief Computes an optimal affine transformation between two 3D point sets. + +It computes \f$R,s,t\f$ minimizing \f$\sum{i} dst_i - c \cdot R \cdot src_i \f$ +where \f$R\f$ is a 3x3 rotation matrix, \f$t\f$ is a 3x1 translation vector and \f$s\f$ is a +scalar size value. This is an implementation of the algorithm by Umeyama \cite umeyama1991least . +The estimated affine transform has a homogeneous scale which is a subclass of affine +transformations with 7 degrees of freedom. The paired point sets need to comprise at least 3 +points each. + +@param src First input 3D point set. +@param dst Second input 3D point set. +@param scale If null is passed, the scale parameter c will be assumed to be 1.0. +Else the pointed-to variable will be set to the optimal scale. +@param force_rotation If true, the returned rotation will never be a reflection. +This might be unwanted, e.g. when optimizing a transform between a right- and a +left-handed coordinate system. +@return 3D affine transformation matrix \f$3 \times 4\f$ of the form +\f[T = +\begin{bmatrix} +R & t\\ +\end{bmatrix} +\f] + + */ +CV_EXPORTS_W cv::Mat estimateAffine3D(InputArray src, InputArray dst, + CV_OUT double* scale = nullptr, bool force_rotation = true); + +/** @brief Computes an optimal translation between two 3D point sets. + * + * It computes + * \f[ + * \begin{bmatrix} + * x\\ + * y\\ + * z\\ + * \end{bmatrix} + * = + * \begin{bmatrix} + * X\\ + * Y\\ + * Z\\ + * \end{bmatrix} + * + + * \begin{bmatrix} + * b_1\\ + * b_2\\ + * b_3\\ + * \end{bmatrix} + * \f] + * + * @param src First input 3D point set containing \f$(X,Y,Z)\f$. + * @param dst Second input 3D point set containing \f$(x,y,z)\f$. + * @param out Output 3D translation vector \f$3 \times 1\f$ of the form + * \f[ + * \begin{bmatrix} + * b_1 \\ + * b_2 \\ + * b_3 \\ + * \end{bmatrix} + * \f] + * @param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). + * @param ransacThreshold Maximum reprojection error in the RANSAC algorithm to consider a point as + * an inlier. + * @param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything + * between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation + * significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. + * + * The function estimates an optimal 3D translation between two 3D point sets using the + * RANSAC algorithm. + * */ +CV_EXPORTS_W int estimateTranslation3D(InputArray src, InputArray dst, + OutputArray out, OutputArray inliers, + double ransacThreshold = 3, double confidence = 0.99); + +/** @brief Computes an optimal affine transformation between two 2D point sets. + +It computes +\f[ +\begin{bmatrix} +x\\ +y\\ +\end{bmatrix} += +\begin{bmatrix} +a_{11} & a_{12}\\ +a_{21} & a_{22}\\ +\end{bmatrix} +\begin{bmatrix} +X\\ +Y\\ +\end{bmatrix} ++ +\begin{bmatrix} +b_1\\ +b_2\\ +\end{bmatrix} +\f] + +@param from First input 2D point set containing \f$(X,Y)\f$. +@param to Second input 2D point set containing \f$(x,y)\f$. +@param inliers Output vector indicating which points are inliers (1-inlier, 0-outlier). +@param method Robust method used to compute transformation. The following methods are possible: +- @ref RANSAC - RANSAC-based robust method +- @ref LMEDS - Least-Median robust method +RANSAC is the default method. +@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider +a point as an inlier. Applies only to RANSAC. +@param maxIters The maximum number of robust method iterations. +@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything +between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation +significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. +@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). +Passing 0 will disable refining, so the output matrix will be output of robust method. + +@return Output 2D affine transformation matrix \f$2 \times 3\f$ or empty matrix if transformation +could not be estimated. The returned matrix has the following form: +\f[ +\begin{bmatrix} +a_{11} & a_{12} & b_1\\ +a_{21} & a_{22} & b_2\\ +\end{bmatrix} +\f] + +The function estimates an optimal 2D affine transformation between two 2D point sets using the +selected robust algorithm. + +The computed transformation is then refined further (using only inliers) with the +Levenberg-Marquardt method to reduce the re-projection error even more. + +@note +The RANSAC method can handle practically any ratio of outliers but needs a threshold to +distinguish inliers from outliers. The method LMeDS does not need any threshold but it works +correctly only when there are more than 50% of inliers. + +@sa estimateAffinePartial2D, getAffineTransform +*/ +CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray from, InputArray to, OutputArray inliers = noArray(), + int method = RANSAC, double ransacReprojThreshold = 3, + size_t maxIters = 2000, double confidence = 0.99, + size_t refineIters = 10); + + +CV_EXPORTS_W cv::Mat estimateAffine2D(InputArray pts1, InputArray pts2, OutputArray inliers, + const UsacParams ¶ms); + +/** @brief Computes an optimal limited affine transformation with 4 degrees of freedom between +two 2D point sets. + +@param from First input 2D point set. +@param to Second input 2D point set. +@param inliers Output vector indicating which points are inliers. +@param method Robust method used to compute transformation. The following methods are possible: +- @ref RANSAC - RANSAC-based robust method +- @ref LMEDS - Least-Median robust method +RANSAC is the default method. +@param ransacReprojThreshold Maximum reprojection error in the RANSAC algorithm to consider +a point as an inlier. Applies only to RANSAC. +@param maxIters The maximum number of robust method iterations. +@param confidence Confidence level, between 0 and 1, for the estimated transformation. Anything +between 0.95 and 0.99 is usually good enough. Values too close to 1 can slow down the estimation +significantly. Values lower than 0.8-0.9 can result in an incorrectly estimated transformation. +@param refineIters Maximum number of iterations of refining algorithm (Levenberg-Marquardt). +Passing 0 will disable refining, so the output matrix will be output of robust method. + +@return Output 2D affine transformation (4 degrees of freedom) matrix \f$2 \times 3\f$ or +empty matrix if transformation could not be estimated. + +The function estimates an optimal 2D affine transformation with 4 degrees of freedom limited to +combinations of translation, rotation, and uniform scaling. Uses the selected algorithm for robust +estimation. + +The computed transformation is then refined further (using only inliers) with the +Levenberg-Marquardt method to reduce the re-projection error even more. + +Estimated transformation matrix is: +\f[ \begin{bmatrix} \cos(\theta) \cdot s & -\sin(\theta) \cdot s & t_x \\ + \sin(\theta) \cdot s & \cos(\theta) \cdot s & t_y +\end{bmatrix} \f] +Where \f$ \theta \f$ is the rotation angle, \f$ s \f$ the scaling factor and \f$ t_x, t_y \f$ are +translations in \f$ x, y \f$ axes respectively. + +@note +The RANSAC method can handle practically any ratio of outliers but need a threshold to +distinguish inliers from outliers. The method LMeDS does not need any threshold but it works +correctly only when there are more than 50% of inliers. + +@sa estimateAffine2D, getAffineTransform +*/ +CV_EXPORTS_W cv::Mat estimateAffinePartial2D(InputArray from, InputArray to, OutputArray inliers = noArray(), + int method = RANSAC, double ransacReprojThreshold = 3, + size_t maxIters = 2000, double confidence = 0.99, + size_t refineIters = 10); + +/** @example samples/cpp/tutorial_code/features2D/Homography/decompose_homography.cpp +An example program with homography decomposition. + +Check @ref tutorial_homography "the corresponding tutorial" for more details. +*/ + +/** @brief Decompose a homography matrix to rotation(s), translation(s) and plane normal(s). + +@param H The input homography matrix between two images. +@param K The input camera intrinsic matrix. +@param rotations Array of rotation matrices. +@param translations Array of translation matrices. +@param normals Array of plane normal matrices. + +This function extracts relative camera motion between two views of a planar object and returns up to +four mathematical solution tuples of rotation, translation, and plane normal. The decomposition of +the homography matrix H is described in detail in @cite Malis2007. + +If the homography H, induced by the plane, gives the constraint +\f[s_i \vecthree{x'_i}{y'_i}{1} \sim H \vecthree{x_i}{y_i}{1}\f] on the source image points +\f$p_i\f$ and the destination image points \f$p'_i\f$, then the tuple of rotations[k] and +translations[k] is a change of basis from the source camera's coordinate system to the destination +camera's coordinate system. However, by decomposing H, one can only get the translation normalized +by the (typically unknown) depth of the scene, i.e. its direction but with normalized length. + +If point correspondences are available, at least two solutions may further be invalidated, by +applying positive depth constraint, i.e. all points must be in front of the camera. + */ +CV_EXPORTS_W int decomposeHomographyMat(InputArray H, + InputArray K, + OutputArrayOfArrays rotations, + OutputArrayOfArrays translations, + OutputArrayOfArrays normals); + +/** @brief Filters homography decompositions based on additional information. + +@param rotations Vector of rotation matrices. +@param normals Vector of plane normal matrices. +@param beforePoints Vector of (rectified) visible reference points before the homography is applied +@param afterPoints Vector of (rectified) visible reference points after the homography is applied +@param possibleSolutions Vector of int indices representing the viable solution set after filtering +@param pointsMask optional Mat/Vector of 8u type representing the mask for the inliers as given by the #findHomography function + +This function is intended to filter the output of the #decomposeHomographyMat based on additional +information as described in @cite Malis2007 . The summary of the method: the #decomposeHomographyMat function +returns 2 unique solutions and their "opposites" for a total of 4 solutions. If we have access to the +sets of points visible in the camera frame before and after the homography transformation is applied, +we can determine which are the true potential solutions and which are the opposites by verifying which +homographies are consistent with all visible reference points being in front of the camera. The inputs +are left unchanged; the filtered solution set is returned as indices into the existing one. + +*/ +CV_EXPORTS_W void filterHomographyDecompByVisibleRefpoints(InputArrayOfArrays rotations, + InputArrayOfArrays normals, + InputArray beforePoints, + InputArray afterPoints, + OutputArray possibleSolutions, + InputArray pointsMask = noArray()); + +/** @brief The base class for stereo correspondence algorithms. + */ +class CV_EXPORTS_W StereoMatcher : public Algorithm +{ +public: + enum { DISP_SHIFT = 4, + DISP_SCALE = (1 << DISP_SHIFT) + }; + + /** @brief Computes disparity map for the specified stereo pair + + @param left Left 8-bit single-channel image. + @param right Right image of the same size and the same type as the left one. + @param disparity Output disparity map. It has the same size as the input images. Some algorithms, + like StereoBM or StereoSGBM compute 16-bit fixed-point disparity map (where each disparity value + has 4 fractional bits), whereas other algorithms output 32-bit floating-point disparity map. + */ + CV_WRAP virtual void compute( InputArray left, InputArray right, + OutputArray disparity ) = 0; + + CV_WRAP virtual int getMinDisparity() const = 0; + CV_WRAP virtual void setMinDisparity(int minDisparity) = 0; + + CV_WRAP virtual int getNumDisparities() const = 0; + CV_WRAP virtual void setNumDisparities(int numDisparities) = 0; + + CV_WRAP virtual int getBlockSize() const = 0; + CV_WRAP virtual void setBlockSize(int blockSize) = 0; + + CV_WRAP virtual int getSpeckleWindowSize() const = 0; + CV_WRAP virtual void setSpeckleWindowSize(int speckleWindowSize) = 0; + + CV_WRAP virtual int getSpeckleRange() const = 0; + CV_WRAP virtual void setSpeckleRange(int speckleRange) = 0; + + CV_WRAP virtual int getDisp12MaxDiff() const = 0; + CV_WRAP virtual void setDisp12MaxDiff(int disp12MaxDiff) = 0; +}; + + +/** @brief Class for computing stereo correspondence using the block matching algorithm, introduced and +contributed to OpenCV by K. Konolige. + */ +class CV_EXPORTS_W StereoBM : public StereoMatcher +{ +public: + enum { PREFILTER_NORMALIZED_RESPONSE = 0, + PREFILTER_XSOBEL = 1 + }; + + CV_WRAP virtual int getPreFilterType() const = 0; + CV_WRAP virtual void setPreFilterType(int preFilterType) = 0; + + CV_WRAP virtual int getPreFilterSize() const = 0; + CV_WRAP virtual void setPreFilterSize(int preFilterSize) = 0; + + CV_WRAP virtual int getPreFilterCap() const = 0; + CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; + + CV_WRAP virtual int getTextureThreshold() const = 0; + CV_WRAP virtual void setTextureThreshold(int textureThreshold) = 0; + + CV_WRAP virtual int getUniquenessRatio() const = 0; + CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; + + CV_WRAP virtual int getSmallerBlockSize() const = 0; + CV_WRAP virtual void setSmallerBlockSize(int blockSize) = 0; + + CV_WRAP virtual Rect getROI1() const = 0; + CV_WRAP virtual void setROI1(Rect roi1) = 0; + + CV_WRAP virtual Rect getROI2() const = 0; + CV_WRAP virtual void setROI2(Rect roi2) = 0; + + /** @brief Creates StereoBM object + + @param numDisparities the disparity search range. For each pixel algorithm will find the best + disparity from 0 (default minimum disparity) to numDisparities. The search range can then be + shifted by changing the minimum disparity. + @param blockSize the linear size of the blocks compared by the algorithm. The size should be odd + (as the block is centered at the current pixel). Larger block size implies smoother, though less + accurate disparity map. Smaller block size gives more detailed disparity map, but there is higher + chance for algorithm to find a wrong correspondence. + + The function create StereoBM object. You can then call StereoBM::compute() to compute disparity for + a specific stereo pair. + */ + CV_WRAP static Ptr create(int numDisparities = 0, int blockSize = 21); +}; + +/** @brief The class implements the modified H. Hirschmuller algorithm @cite HH08 that differs from the original +one as follows: + +- By default, the algorithm is single-pass, which means that you consider only 5 directions +instead of 8. Set mode=StereoSGBM::MODE_HH in createStereoSGBM to run the full variant of the +algorithm but beware that it may consume a lot of memory. +- The algorithm matches blocks, not individual pixels. Though, setting blockSize=1 reduces the +blocks to single pixels. +- Mutual information cost function is not implemented. Instead, a simpler Birchfield-Tomasi +sub-pixel metric from @cite BT98 is used. Though, the color images are supported as well. +- Some pre- and post- processing steps from K. Konolige algorithm StereoBM are included, for +example: pre-filtering (StereoBM::PREFILTER_XSOBEL type) and post-filtering (uniqueness +check, quadratic interpolation and speckle filtering). + +@note + - (Python) An example illustrating the use of the StereoSGBM matching algorithm can be found + at opencv_source_code/samples/python/stereo_match.py + */ +class CV_EXPORTS_W StereoSGBM : public StereoMatcher +{ +public: + enum + { + MODE_SGBM = 0, + MODE_HH = 1, + MODE_SGBM_3WAY = 2, + MODE_HH4 = 3 + }; + + CV_WRAP virtual int getPreFilterCap() const = 0; + CV_WRAP virtual void setPreFilterCap(int preFilterCap) = 0; + + CV_WRAP virtual int getUniquenessRatio() const = 0; + CV_WRAP virtual void setUniquenessRatio(int uniquenessRatio) = 0; + + CV_WRAP virtual int getP1() const = 0; + CV_WRAP virtual void setP1(int P1) = 0; + + CV_WRAP virtual int getP2() const = 0; + CV_WRAP virtual void setP2(int P2) = 0; + + CV_WRAP virtual int getMode() const = 0; + CV_WRAP virtual void setMode(int mode) = 0; + + /** @brief Creates StereoSGBM object + + @param minDisparity Minimum possible disparity value. Normally, it is zero but sometimes + rectification algorithms can shift images, so this parameter needs to be adjusted accordingly. + @param numDisparities Maximum disparity minus minimum disparity. The value is always greater than + zero. In the current implementation, this parameter must be divisible by 16. + @param blockSize Matched block size. It must be an odd number \>=1 . Normally, it should be + somewhere in the 3..11 range. + @param P1 The first parameter controlling the disparity smoothness. See below. + @param P2 The second parameter controlling the disparity smoothness. The larger the values are, + the smoother the disparity is. P1 is the penalty on the disparity change by plus or minus 1 + between neighbor pixels. P2 is the penalty on the disparity change by more than 1 between neighbor + pixels. The algorithm requires P2 \> P1 . See stereo_match.cpp sample where some reasonably good + P1 and P2 values are shown (like 8\*number_of_image_channels\*blockSize\*blockSize and + 32\*number_of_image_channels\*blockSize\*blockSize , respectively). + @param disp12MaxDiff Maximum allowed difference (in integer pixel units) in the left-right + disparity check. Set it to a non-positive value to disable the check. + @param preFilterCap Truncation value for the prefiltered image pixels. The algorithm first + computes x-derivative at each pixel and clips its value by [-preFilterCap, preFilterCap] interval. + The result values are passed to the Birchfield-Tomasi pixel cost function. + @param uniquenessRatio Margin in percentage by which the best (minimum) computed cost function + value should "win" the second best value to consider the found match correct. Normally, a value + within the 5-15 range is good enough. + @param speckleWindowSize Maximum size of smooth disparity regions to consider their noise speckles + and invalidate. Set it to 0 to disable speckle filtering. Otherwise, set it somewhere in the + 50-200 range. + @param speckleRange Maximum disparity variation within each connected component. If you do speckle + filtering, set the parameter to a positive value, it will be implicitly multiplied by 16. + Normally, 1 or 2 is good enough. + @param mode Set it to StereoSGBM::MODE_HH to run the full-scale two-pass dynamic programming + algorithm. It will consume O(W\*H\*numDisparities) bytes, which is large for 640x480 stereo and + huge for HD-size pictures. By default, it is set to false . + + The first constructor initializes StereoSGBM with all the default parameters. So, you only have to + set StereoSGBM::numDisparities at minimum. The second constructor enables you to set each parameter + to a custom value. + */ + CV_WRAP static Ptr create(int minDisparity = 0, int numDisparities = 16, int blockSize = 3, + int P1 = 0, int P2 = 0, int disp12MaxDiff = 0, + int preFilterCap = 0, int uniquenessRatio = 0, + int speckleWindowSize = 0, int speckleRange = 0, + int mode = StereoSGBM::MODE_SGBM); +}; + + +//! cv::undistort mode +enum UndistortTypes +{ + PROJ_SPHERICAL_ORTHO = 0, + PROJ_SPHERICAL_EQRECT = 1 +}; + +/** @brief Transforms an image to compensate for lens distortion. + +The function transforms an image to compensate radial and tangential lens distortion. + +The function is simply a combination of #initUndistortRectifyMap (with unity R ) and #remap +(with bilinear interpolation). See the former function for details of the transformation being +performed. + +Those pixels in the destination image, for which there is no correspondent pixels in the source +image, are filled with zeros (black color). + +A particular subset of the source image that will be visible in the corrected image can be regulated +by newCameraMatrix. You can use #getOptimalNewCameraMatrix to compute the appropriate +newCameraMatrix depending on your requirements. + +The camera matrix and the distortion parameters can be determined using #calibrateCamera. If +the resolution of images is different from the resolution used at the calibration stage, \f$f_x, +f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain +the same. + +@param src Input (distorted) image. +@param dst Output (corrected) image that has the same size and type as src . +@param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as +cameraMatrix but you may additionally scale and shift the result by using a different matrix. + */ +CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, + InputArray cameraMatrix, + InputArray distCoeffs, + InputArray newCameraMatrix = noArray() ); + +/** @brief Computes the undistortion and rectification transformation map. + +The function computes the joint undistortion and rectification transformation and represents the +result in the form of maps for #remap. The undistorted image looks like original, as if it is +captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a +monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by +#getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera, +newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . + +Also, this new camera is oriented differently in the coordinate space, according to R. That, for +example, helps to align two heads of a stereo camera so that the epipolar lines on both images +become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera). + +The function actually builds the maps for the inverse mapping algorithm that is used by #remap. That +is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function +computes the corresponding coordinates in the source image (that is, in the original image from +camera). The following process is applied: +\f[ +\begin{array}{l} +x \leftarrow (u - {c'}_x)/{f'}_x \\ +y \leftarrow (v - {c'}_y)/{f'}_y \\ +{[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ +x' \leftarrow X/W \\ +y' \leftarrow Y/W \\ +r^2 \leftarrow x'^2 + y'^2 \\ +x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} ++ 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\ +y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} ++ p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ +s\vecthree{x'''}{y'''}{1} = +\vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} +{0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} +{0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ +map_x(u,v) \leftarrow x''' f_x + c_x \\ +map_y(u,v) \leftarrow y''' f_y + c_y +\end{array} +\f] +where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +are the distortion coefficients. + +In case of a stereo camera, this function is called twice: once for each camera head, after +#stereoRectify, which in its turn is called after #stereoCalibrate. But if the stereo camera +was not calibrated, it is still possible to compute the rectification transformations directly from +the fundamental matrix using #stereoRectifyUncalibrated. For each camera, the function computes +homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D +space. R can be computed from H as +\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] +where cameraMatrix can be chosen arbitrarily. + +@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 , +computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation +is assumed. In #initUndistortRectifyMap R assumed to be an identity matrix. +@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. +@param size Undistorted image size. +@param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps +@param map1 The first output map. +@param map2 The second output map. + */ +CV_EXPORTS_W +void initUndistortRectifyMap(InputArray cameraMatrix, InputArray distCoeffs, + InputArray R, InputArray newCameraMatrix, + Size size, int m1type, OutputArray map1, OutputArray map2); + +/** @brief Computes the projection and inverse-rectification transformation map. In essense, this is the inverse of +#initUndistortRectifyMap to accomodate stereo-rectification of projectors ('inverse-cameras') in projector-camera pairs. + +The function computes the joint projection and inverse rectification transformation and represents the +result in the form of maps for #remap. The projected image looks like a distorted version of the original which, +once projected by a projector, should visually match the original. In case of a monocular camera, newCameraMatrix +is usually equal to cameraMatrix, or it can be computed by +#getOptimalNewCameraMatrix for a better control over scaling. In case of a projector-camera pair, +newCameraMatrix is normally set to P1 or P2 computed by #stereoRectify . + +The projector is oriented differently in the coordinate space, according to R. In case of projector-camera pairs, +this helps align the projector (in the same manner as #initUndistortRectifyMap for the camera) to create a stereo-rectified pair. This +allows epipolar lines on both images to become horizontal and have the same y-coordinate (in case of a horizontally aligned projector-camera pair). + +The function builds the maps for the inverse mapping algorithm that is used by #remap. That +is, for each pixel \f$(u, v)\f$ in the destination (projected and inverse-rectified) image, the function +computes the corresponding coordinates in the source image (that is, in the original digital image). The following process is applied: + +\f[ +\begin{array}{l} +\text{newCameraMatrix}\\ +x \leftarrow (u - {c'}_x)/{f'}_x \\ +y \leftarrow (v - {c'}_y)/{f'}_y \\ + +\\\text{Undistortion} +\\\scriptsize{\textit{though equation shown is for radial undistortion, function implements cv::undistortPoints()}}\\ +r^2 \leftarrow x^2 + y^2 \\ +\theta \leftarrow \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6}\\ +x' \leftarrow \frac{x}{\theta} \\ +y' \leftarrow \frac{y}{\theta} \\ + +\\\text{Rectification}\\ +{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ +x'' \leftarrow X/W \\ +y'' \leftarrow Y/W \\ + +\\\text{cameraMatrix}\\ +map_x(u,v) \leftarrow x'' f_x + c_x \\ +map_y(u,v) \leftarrow y'' f_y + c_y +\end{array} +\f] +where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +are the distortion coefficients vector distCoeffs. + +In case of a stereo-rectified projector-camera pair, this function is called for the projector while #initUndistortRectifyMap is called for the camera head. +This is done after #stereoRectify, which in turn is called after #stereoCalibrate. If the projector-camera pair +is not calibrated, it is still possible to compute the rectification transformations directly from +the fundamental matrix using #stereoRectifyUncalibrated. For the projector and camera, the function computes +homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D +space. R can be computed from H as +\f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] +where cameraMatrix can be chosen arbitrarily. + +@param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2, +computed by #stereoRectify can be passed here. If the matrix is empty, the identity transformation +is assumed. +@param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. +@param size Distorted image size. +@param m1type Type of the first output map. Can be CV_32FC1, CV_32FC2 or CV_16SC2, see #convertMaps +@param map1 The first output map for #remap. +@param map2 The second output map for #remap. + */ +CV_EXPORTS_W +void initInverseRectificationMap( InputArray cameraMatrix, InputArray distCoeffs, + InputArray R, InputArray newCameraMatrix, + const Size& size, int m1type, OutputArray map1, OutputArray map2 ); + +//! initializes maps for #remap for wide-angle +CV_EXPORTS +float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, int destImageWidth, + int m1type, OutputArray map1, OutputArray map2, + enum UndistortTypes projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); +static inline +float initWideAngleProjMap(InputArray cameraMatrix, InputArray distCoeffs, + Size imageSize, int destImageWidth, + int m1type, OutputArray map1, OutputArray map2, + int projType, double alpha = 0) +{ + return initWideAngleProjMap(cameraMatrix, distCoeffs, imageSize, destImageWidth, + m1type, map1, map2, (UndistortTypes)projType, alpha); +} + +/** @brief Returns the default new camera matrix. + +The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when +centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true). + +In the latter case, the new camera matrix will be: + +\f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f] + +where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively. + +By default, the undistortion functions in OpenCV (see #initUndistortRectifyMap, #undistort) do not +move the principal point. However, when you work with stereo, it is important to move the principal +points in both views to the same y-coordinate (which is required by most of stereo correspondence +algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for +each view where the principal points are located at the center. + +@param cameraMatrix Input camera matrix. +@param imgsize Camera view image size in pixels. +@param centerPrincipalPoint Location of the principal point in the new camera matrix. The +parameter indicates whether this location should be at the image center or not. + */ +CV_EXPORTS_W +Mat getDefaultNewCameraMatrix(InputArray cameraMatrix, Size imgsize = Size(), + bool centerPrincipalPoint = false); + +/** @brief Computes the ideal point coordinates from the observed point coordinates. + +The function is similar to #undistort and #initUndistortRectifyMap but it operates on a +sparse set of points instead of a raster image. Also the function performs a reverse transformation +to #projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a +planar object, it does, up to a translation vector, if the proper R is specified. + +For each observed point coordinate \f$(u, v)\f$ the function computes: +\f[ +\begin{array}{l} +x^{"} \leftarrow (u - c_x)/f_x \\ +y^{"} \leftarrow (v - c_y)/f_y \\ +(x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\ +{[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ +x \leftarrow X/W \\ +y \leftarrow Y/W \\ +\text{only performed if P is specified:} \\ +u' \leftarrow x {f'}_x + {c'}_x \\ +v' \leftarrow y {f'}_y + {c'}_y +\end{array} +\f] + +where *undistort* is an approximate iterative algorithm that estimates the normalized original +point coordinates out of the normalized distorted point coordinates ("normalized" means that the +coordinates do not depend on the camera matrix). + +The function can be used for both a stereo camera head or a monocular camera (when R is empty). +@param src Observed point coordinates, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or CV_64FC2) (or +vector\ ). +@param dst Output ideal point coordinates (1xN/Nx1 2-channel or vector\ ) after undistortion and reverse perspective +transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates. +@param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . +@param distCoeffs Input vector of distortion coefficients +\f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ +of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. +@param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by +#stereoRectify can be passed here. If the matrix is empty, the identity transformation is used. +@param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by +#stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used. + */ +CV_EXPORTS_W +void undistortPoints(InputArray src, OutputArray dst, + InputArray cameraMatrix, InputArray distCoeffs, + InputArray R = noArray(), InputArray P = noArray()); +/** @overload + @note Default version of #undistortPoints does 5 iterations to compute undistorted points. + */ +CV_EXPORTS_AS(undistortPointsIter) +void undistortPoints(InputArray src, OutputArray dst, + InputArray cameraMatrix, InputArray distCoeffs, + InputArray R, InputArray P, TermCriteria criteria); + +/** + * @brief Compute undistorted image points position + * + * @param src Observed points position, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel (CV_32FC2 or +CV_64FC2) (or vector\ ). + * @param dst Output undistorted points position (1xN/Nx1 2-channel or vector\ ). + * @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . + * @param distCoeffs Distortion coefficients + */ +CV_EXPORTS_W +void undistortImagePoints(InputArray src, OutputArray dst, InputArray cameraMatrix, + InputArray distCoeffs, + TermCriteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 5, + 0.01)); + +//! @} calib3d + +/** @brief The methods in this namespace use a so-called fisheye camera model. + @ingroup calib3d_fisheye +*/ +namespace fisheye +{ +//! @addtogroup calib3d_fisheye +//! @{ + + enum{ + CALIB_USE_INTRINSIC_GUESS = 1 << 0, + CALIB_RECOMPUTE_EXTRINSIC = 1 << 1, + CALIB_CHECK_COND = 1 << 2, + CALIB_FIX_SKEW = 1 << 3, + CALIB_FIX_K1 = 1 << 4, + CALIB_FIX_K2 = 1 << 5, + CALIB_FIX_K3 = 1 << 6, + CALIB_FIX_K4 = 1 << 7, + CALIB_FIX_INTRINSIC = 1 << 8, + CALIB_FIX_PRINCIPAL_POINT = 1 << 9, + CALIB_ZERO_DISPARITY = 1 << 10, + CALIB_FIX_FOCAL_LENGTH = 1 << 11 + }; + + /** @brief Projects points using fisheye model + + @param objectPoints Array of object points, 1xN/Nx1 3-channel (or vector\ ), where N is + the number of points in the view. + @param imagePoints Output array of image points, 2xN/Nx2 1-channel or 1xN/Nx1 2-channel, or + vector\. + @param affine + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param alpha The skew coefficient. + @param jacobian Optional output 2Nx15 jacobian matrix of derivatives of image points with respect + to components of the focal lengths, coordinates of the principal point, distortion coefficients, + rotation vector, translation vector, and the skew. In the old interface different components of + the jacobian are returned via different output parameters. + + The function computes projections of 3D points to the image plane given intrinsic and extrinsic + camera parameters. Optionally, the function computes Jacobians - matrices of partial derivatives of + image points coordinates (as functions of all the input parameters) with respect to the particular + parameters, intrinsic and/or extrinsic. + */ + CV_EXPORTS void projectPoints(InputArray objectPoints, OutputArray imagePoints, const Affine3d& affine, + InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); + + /** @overload */ + CV_EXPORTS_W void projectPoints(InputArray objectPoints, OutputArray imagePoints, InputArray rvec, InputArray tvec, + InputArray K, InputArray D, double alpha = 0, OutputArray jacobian = noArray()); + + /** @brief Distorts 2D points using fisheye model. + + @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is + the number of points in the view. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param alpha The skew coefficient. + @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . + + Note that the function assumes the camera intrinsic matrix of the undistorted points to be identity. + This means if you want to distort image points you have to multiply them with \f$K^{-1}\f$ or + use another function overload. + */ + CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray K, InputArray D, double alpha = 0); + + /** @overload + Overload of distortPoints function to handle cases when undistorted points are obtained with non-identity + camera matrix, e.g. output of #estimateNewCameraMatrixForUndistortRectify. + @param undistorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is + the number of points in the view. + @param Kundistorted Camera intrinsic matrix used as new camera matrix for undistortion. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param alpha The skew coefficient. + @param distorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . + @sa estimateNewCameraMatrixForUndistortRectify + */ + CV_EXPORTS_W void distortPoints(InputArray undistorted, OutputArray distorted, InputArray Kundistorted, InputArray K, InputArray D, double alpha = 0); + + /** @brief Undistorts 2D points using fisheye model + + @param distorted Array of object points, 1xN/Nx1 2-channel (or vector\ ), where N is the + number of points in the view. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + 1-channel or 1x1 3-channel + @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) + @param criteria Termination criteria + @param undistorted Output array of image points, 1xN/Nx1 2-channel, or vector\ . + */ + CV_EXPORTS_W void undistortPoints(InputArray distorted, OutputArray undistorted, + InputArray K, InputArray D, InputArray R = noArray(), InputArray P = noArray(), + TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8)); + + /** @brief Computes undistortion and rectification maps for image transform by #remap. If D is empty zero + distortion is used, if R or P is empty identity matrixes are used. + + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + 1-channel or 1x1 3-channel + @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) + @param size Undistorted image size. + @param m1type Type of the first output map that can be CV_32FC1 or CV_16SC2 . See #convertMaps + for details. + @param map1 The first output map. + @param map2 The second output map. + */ + CV_EXPORTS_W void initUndistortRectifyMap(InputArray K, InputArray D, InputArray R, InputArray P, + const cv::Size& size, int m1type, OutputArray map1, OutputArray map2); + + /** @brief Transforms an image to compensate for fisheye lens distortion. + + @param distorted image with fisheye lens distortion. + @param undistorted Output image with compensated fisheye lens distortion. + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param Knew Camera intrinsic matrix of the distorted image. By default, it is the identity matrix but you + may additionally scale and shift the result by using a different matrix. + @param new_size the new size + + The function transforms an image to compensate radial and tangential lens distortion. + + The function is simply a combination of #fisheye::initUndistortRectifyMap (with unity R ) and #remap + (with bilinear interpolation). See the former function for details of the transformation being + performed. + + See below the results of undistortImage. + - a\) result of undistort of perspective camera model (all possible coefficients (k_1, k_2, k_3, + k_4, k_5, k_6) of distortion were optimized under calibration) + - b\) result of #fisheye::undistortImage of fisheye camera model (all possible coefficients (k_1, k_2, + k_3, k_4) of fisheye distortion were optimized under calibration) + - c\) original image was captured with fisheye lens + + Pictures a) and b) almost the same. But if we consider points of image located far from the center + of image, we can notice that on image a) these points are distorted. + + ![image](pics/fisheye_undistorted.jpg) + */ + CV_EXPORTS_W void undistortImage(InputArray distorted, OutputArray undistorted, + InputArray K, InputArray D, InputArray Knew = cv::noArray(), const Size& new_size = Size()); + + /** @brief Estimates new camera intrinsic matrix for undistortion or rectification. + + @param K Camera intrinsic matrix \f$\cameramatrix{K}\f$. + @param image_size Size of the image + @param D Input vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param R Rectification transformation in the object space: 3x3 1-channel, or vector: 3x1/1x3 + 1-channel or 1x1 3-channel + @param P New camera intrinsic matrix (3x3) or new projection matrix (3x4) + @param balance Sets the new focal length in range between the min focal length and the max focal + length. Balance is in range of [0, 1]. + @param new_size the new size + @param fov_scale Divisor for new focal length. + */ + CV_EXPORTS_W void estimateNewCameraMatrixForUndistortRectify(InputArray K, InputArray D, const Size &image_size, InputArray R, + OutputArray P, double balance = 0.0, const Size& new_size = Size(), double fov_scale = 1.0); + + /** @brief Performs camera calibration + + @param objectPoints vector of vectors of calibration pattern points in the calibration pattern + coordinate space. + @param imagePoints vector of vectors of the projections of calibration pattern points. + imagePoints.size() and objectPoints.size() and imagePoints[i].size() must be equal to + objectPoints[i].size() for each i. + @param image_size Size of the image used only to initialize the camera intrinsic matrix. + @param K Output 3x3 floating-point camera intrinsic matrix + \f$\cameramatrix{A}\f$ . If + @ref fisheye::CALIB_USE_INTRINSIC_GUESS is specified, some or all of fx, fy, cx, cy must be + initialized before calling the function. + @param D Output vector of distortion coefficients \f$\distcoeffsfisheye\f$. + @param rvecs Output vector of rotation vectors (see @ref Rodrigues ) estimated for each pattern view. + That is, each k-th rotation vector together with the corresponding k-th translation vector (see + the next output parameter description) brings the calibration pattern from the model coordinate + space (in which object points are specified) to the world coordinate space, that is, a real + position of the calibration pattern in the k-th pattern view (k=0.. *M* -1). + @param tvecs Output vector of translation vectors estimated for each pattern view. + @param flags Different flags that may be zero or a combination of the following values: + - @ref fisheye::CALIB_USE_INTRINSIC_GUESS cameraMatrix contains valid initial values of + fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image + center ( imageSize is used), and focal distances are computed in a least-squares fashion. + - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration + of intrinsic optimization. + - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. + - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. + - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients + are set to zeros and stay zero. + - @ref fisheye::CALIB_FIX_PRINCIPAL_POINT The principal point is not changed during the global +optimization. It stays at the center or at a different location specified when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. + - @ref fisheye::CALIB_FIX_FOCAL_LENGTH The focal length is not changed during the global +optimization. It is the \f$max(width,height)/\pi\f$ or the provided \f$f_x\f$, \f$f_y\f$ when @ref fisheye::CALIB_USE_INTRINSIC_GUESS is set too. + @param criteria Termination criteria for the iterative optimization algorithm. + */ + CV_EXPORTS_W double calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, const Size& image_size, + InputOutputArray K, InputOutputArray D, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = 0, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); + + /** @brief Stereo rectification for fisheye camera model + + @param K1 First camera intrinsic matrix. + @param D1 First camera distortion parameters. + @param K2 Second camera intrinsic matrix. + @param D2 Second camera distortion parameters. + @param imageSize Size of the image used for stereo calibration. + @param R Rotation matrix between the coordinate systems of the first and the second + cameras. + @param tvec Translation vector between coordinate systems of the cameras. + @param R1 Output 3x3 rectification transform (rotation matrix) for the first camera. + @param R2 Output 3x3 rectification transform (rotation matrix) for the second camera. + @param P1 Output 3x4 projection matrix in the new (rectified) coordinate systems for the first + camera. + @param P2 Output 3x4 projection matrix in the new (rectified) coordinate systems for the second + camera. + @param Q Output \f$4 \times 4\f$ disparity-to-depth mapping matrix (see #reprojectImageTo3D ). + @param flags Operation flags that may be zero or @ref fisheye::CALIB_ZERO_DISPARITY . If the flag is set, + the function makes the principal points of each camera have the same pixel coordinates in the + rectified views. And if the flag is not set, the function may still shift the images in the + horizontal or vertical direction (depending on the orientation of epipolar lines) to maximize the + useful image area. + @param newImageSize New image resolution after rectification. The same size should be passed to + #initUndistortRectifyMap (see the stereo_calib.cpp sample in OpenCV samples directory). When (0,0) + is passed (default), it is set to the original imageSize . Setting it to larger value can help you + preserve details in the original image, especially when there is a big radial distortion. + @param balance Sets the new focal length in range between the min focal length and the max focal + length. Balance is in range of [0, 1]. + @param fov_scale Divisor for new focal length. + */ + CV_EXPORTS_W void stereoRectify(InputArray K1, InputArray D1, InputArray K2, InputArray D2, const Size &imageSize, InputArray R, InputArray tvec, + OutputArray R1, OutputArray R2, OutputArray P1, OutputArray P2, OutputArray Q, int flags, const Size &newImageSize = Size(), + double balance = 0.0, double fov_scale = 1.0); + + /** @brief Performs stereo calibration + + @param objectPoints Vector of vectors of the calibration pattern points. + @param imagePoints1 Vector of vectors of the projections of the calibration pattern points, + observed by the first camera. + @param imagePoints2 Vector of vectors of the projections of the calibration pattern points, + observed by the second camera. + @param K1 Input/output first camera intrinsic matrix: + \f$\vecthreethree{f_x^{(j)}}{0}{c_x^{(j)}}{0}{f_y^{(j)}}{c_y^{(j)}}{0}{0}{1}\f$ , \f$j = 0,\, 1\f$ . If + any of @ref fisheye::CALIB_USE_INTRINSIC_GUESS , @ref fisheye::CALIB_FIX_INTRINSIC are specified, + some or all of the matrix components must be initialized. + @param D1 Input/output vector of distortion coefficients \f$\distcoeffsfisheye\f$ of 4 elements. + @param K2 Input/output second camera intrinsic matrix. The parameter is similar to K1 . + @param D2 Input/output lens distortion coefficients for the second camera. The parameter is + similar to D1 . + @param imageSize Size of the image used only to initialize camera intrinsic matrix. + @param R Output rotation matrix between the 1st and the 2nd camera coordinate systems. + @param T Output translation vector between the coordinate systems of the cameras. + @param rvecs Output vector of rotation vectors ( @ref Rodrigues ) estimated for each pattern view in the + coordinate system of the first camera of the stereo pair (e.g. std::vector). More in detail, each + i-th rotation vector together with the corresponding i-th translation vector (see the next output parameter + description) brings the calibration pattern from the object coordinate space (in which object points are + specified) to the camera coordinate space of the first camera of the stereo pair. In more technical terms, + the tuple of the i-th rotation and translation vector performs a change of basis from object coordinate space + to camera coordinate space of the first camera of the stereo pair. + @param tvecs Output vector of translation vectors estimated for each pattern view, see parameter description + of previous output parameter ( rvecs ). + @param flags Different flags that may be zero or a combination of the following values: + - @ref fisheye::CALIB_FIX_INTRINSIC Fix K1, K2? and D1, D2? so that only R, T matrices + are estimated. + - @ref fisheye::CALIB_USE_INTRINSIC_GUESS K1, K2 contains valid initial values of + fx, fy, cx, cy that are optimized further. Otherwise, (cx, cy) is initially set to the image + center (imageSize is used), and focal distances are computed in a least-squares fashion. + - @ref fisheye::CALIB_RECOMPUTE_EXTRINSIC Extrinsic will be recomputed after each iteration + of intrinsic optimization. + - @ref fisheye::CALIB_CHECK_COND The functions will check validity of condition number. + - @ref fisheye::CALIB_FIX_SKEW Skew coefficient (alpha) is set to zero and stay zero. + - @ref fisheye::CALIB_FIX_K1,..., @ref fisheye::CALIB_FIX_K4 Selected distortion coefficients are set to zeros and stay + zero. + @param criteria Termination criteria for the iterative optimization algorithm. + */ + CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, + OutputArray R, OutputArray T, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags = fisheye::CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); + + /// @overload + CV_EXPORTS_W double stereoCalibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints1, InputArrayOfArrays imagePoints2, + InputOutputArray K1, InputOutputArray D1, InputOutputArray K2, InputOutputArray D2, Size imageSize, + OutputArray R, OutputArray T, int flags = fisheye::CALIB_FIX_INTRINSIC, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT + TermCriteria::EPS, 100, DBL_EPSILON)); + + /** + @brief Finds an object pose from 3D-2D point correspondences for fisheye camera moodel. + + @param objectPoints Array of object points in the object coordinate space, Nx3 1-channel or + 1xN/Nx1 3-channel, where N is the number of points. vector\ can be also passed here. + @param imagePoints Array of corresponding image points, Nx2 1-channel or 1xN/Nx1 2-channel, + where N is the number of points. vector\ can be also passed here. + @param cameraMatrix Input camera intrinsic matrix \f$\cameramatrix{A}\f$ . + @param distCoeffs Input vector of distortion coefficients (4x1/1x4). + @param rvec Output rotation vector (see @ref Rodrigues ) that, together with tvec, brings points from + the model coordinate system to the camera coordinate system. + @param tvec Output translation vector. + @param useExtrinsicGuess Parameter used for #SOLVEPNP_ITERATIVE. If true (1), the function uses + the provided rvec and tvec values as initial approximations of the rotation and translation + vectors, respectively, and further optimizes them. + @param flags Method for solving a PnP problem: see @ref calib3d_solvePnP_flags + This function returns the rotation and the translation vectors that transform a 3D point expressed in the object + coordinate frame to the camera coordinate frame, using different methods: + - P3P methods (@ref SOLVEPNP_P3P, @ref SOLVEPNP_AP3P): need 4 input points to return a unique solution. + - @ref SOLVEPNP_IPPE Input points must be >= 4 and object points must be coplanar. + - @ref SOLVEPNP_IPPE_SQUARE Special case suitable for marker pose estimation. + Number of input points must be 4. Object points must be defined in the following order: + - point 0: [-squareLength / 2, squareLength / 2, 0] + - point 1: [ squareLength / 2, squareLength / 2, 0] + - point 2: [ squareLength / 2, -squareLength / 2, 0] + - point 3: [-squareLength / 2, -squareLength / 2, 0] + - for all the other flags, number of input points must be >= 4 and object points can be in any configuration. + @param criteria Termination criteria for internal undistortPoints call. + The function interally undistorts points with @ref undistortPoints and call @ref cv::solvePnP, + thus the input are very similar. More information about Perspective-n-Points is described in @ref calib3d_solvePnP + for more information. + */ + CV_EXPORTS_W bool solvePnP( InputArray objectPoints, InputArray imagePoints, + InputArray cameraMatrix, InputArray distCoeffs, + OutputArray rvec, OutputArray tvec, + bool useExtrinsicGuess = false, int flags = SOLVEPNP_ITERATIVE, + TermCriteria criteria = TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 10, 1e-8) + ); + +//! @} calib3d_fisheye +} // end namespace fisheye + +} //end namespace cv + +#if 0 //def __cplusplus +////////////////////////////////////////////////////////////////////////////////////////// +class CV_EXPORTS CvLevMarq +{ +public: + CvLevMarq(); + CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + ~CvLevMarq(); + void init( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); + bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); + + void clear(); + void step(); + enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; + + cv::Ptr mask; + cv::Ptr prevParam; + cv::Ptr param; + cv::Ptr J; + cv::Ptr err; + cv::Ptr JtJ; + cv::Ptr JtJN; + cv::Ptr JtErr; + cv::Ptr JtJV; + cv::Ptr JtJW; + double prevErrNorm, errNorm; + int lambdaLg10; + CvTermCriteria criteria; + int state; + int iters; + bool completeSymmFlag; + int solveMethod; +}; +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp index 9cae7f4cdd..b3da45edd5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/calib3d.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/calib3d.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h index d3072cc00c..e2af07b2e2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/calib3d/calib3d_c.h @@ -1,150 +1,150 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CALIB3D_C_H -#define OPENCV_CALIB3D_C_H - -#include "opencv2/core/types_c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/* Calculates fundamental matrix given a set of corresponding points */ -#define CV_FM_7POINT 1 -#define CV_FM_8POINT 2 - -#define CV_LMEDS 4 -#define CV_RANSAC 8 - -#define CV_FM_LMEDS_ONLY CV_LMEDS -#define CV_FM_RANSAC_ONLY CV_RANSAC -#define CV_FM_LMEDS CV_LMEDS -#define CV_FM_RANSAC CV_RANSAC - -enum -{ - CV_ITERATIVE = 0, - CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" - CV_P3P = 2, // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" - CV_DLS = 3 // Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP" -}; - -#define CV_CALIB_CB_ADAPTIVE_THRESH 1 -#define CV_CALIB_CB_NORMALIZE_IMAGE 2 -#define CV_CALIB_CB_FILTER_QUADS 4 -#define CV_CALIB_CB_FAST_CHECK 8 - -#define CV_CALIB_USE_INTRINSIC_GUESS 1 -#define CV_CALIB_FIX_ASPECT_RATIO 2 -#define CV_CALIB_FIX_PRINCIPAL_POINT 4 -#define CV_CALIB_ZERO_TANGENT_DIST 8 -#define CV_CALIB_FIX_FOCAL_LENGTH 16 -#define CV_CALIB_FIX_K1 32 -#define CV_CALIB_FIX_K2 64 -#define CV_CALIB_FIX_K3 128 -#define CV_CALIB_FIX_K4 2048 -#define CV_CALIB_FIX_K5 4096 -#define CV_CALIB_FIX_K6 8192 -#define CV_CALIB_RATIONAL_MODEL 16384 -#define CV_CALIB_THIN_PRISM_MODEL 32768 -#define CV_CALIB_FIX_S1_S2_S3_S4 65536 -#define CV_CALIB_TILTED_MODEL 262144 -#define CV_CALIB_FIX_TAUX_TAUY 524288 -#define CV_CALIB_FIX_TANGENT_DIST 2097152 - -#define CV_CALIB_NINTRINSIC 18 - -#define CV_CALIB_FIX_INTRINSIC 256 -#define CV_CALIB_SAME_FOCAL_LENGTH 512 - -#define CV_CALIB_ZERO_DISPARITY 1024 - -/* stereo correspondence parameters and functions */ -#define CV_STEREO_BM_NORMALIZED_RESPONSE 0 -#define CV_STEREO_BM_XSOBEL 1 - -#ifdef __cplusplus -} // extern "C" - -////////////////////////////////////////////////////////////////////////////////////////// -class CV_EXPORTS CvLevMarq -{ -public: - CvLevMarq(); - CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - ~CvLevMarq(); - void init( int nparams, int nerrs, CvTermCriteria criteria= - cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), - bool completeSymmFlag=false ); - bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); - bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); - - void clear(); - void step(); - enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; - - cv::Ptr mask; - cv::Ptr prevParam; - cv::Ptr param; - cv::Ptr J; - cv::Ptr err; - cv::Ptr JtJ; - cv::Ptr JtJN; - cv::Ptr JtErr; - cv::Ptr JtJV; - cv::Ptr JtJW; - double prevErrNorm, errNorm; - int lambdaLg10; - CvTermCriteria criteria; - int state; - int iters; - bool completeSymmFlag; - int solveMethod; -}; - -#endif - -#endif /* OPENCV_CALIB3D_C_H */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CALIB3D_C_H +#define OPENCV_CALIB3D_C_H + +#include "opencv2/core/types_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Calculates fundamental matrix given a set of corresponding points */ +#define CV_FM_7POINT 1 +#define CV_FM_8POINT 2 + +#define CV_LMEDS 4 +#define CV_RANSAC 8 + +#define CV_FM_LMEDS_ONLY CV_LMEDS +#define CV_FM_RANSAC_ONLY CV_RANSAC +#define CV_FM_LMEDS CV_LMEDS +#define CV_FM_RANSAC CV_RANSAC + +enum +{ + CV_ITERATIVE = 0, + CV_EPNP = 1, // F.Moreno-Noguer, V.Lepetit and P.Fua "EPnP: Efficient Perspective-n-Point Camera Pose Estimation" + CV_P3P = 2, // X.S. Gao, X.-R. Hou, J. Tang, H.-F. Chang; "Complete Solution Classification for the Perspective-Three-Point Problem" + CV_DLS = 3 // Joel A. Hesch and Stergios I. Roumeliotis. "A Direct Least-Squares (DLS) Method for PnP" +}; + +#define CV_CALIB_CB_ADAPTIVE_THRESH 1 +#define CV_CALIB_CB_NORMALIZE_IMAGE 2 +#define CV_CALIB_CB_FILTER_QUADS 4 +#define CV_CALIB_CB_FAST_CHECK 8 + +#define CV_CALIB_USE_INTRINSIC_GUESS 1 +#define CV_CALIB_FIX_ASPECT_RATIO 2 +#define CV_CALIB_FIX_PRINCIPAL_POINT 4 +#define CV_CALIB_ZERO_TANGENT_DIST 8 +#define CV_CALIB_FIX_FOCAL_LENGTH 16 +#define CV_CALIB_FIX_K1 32 +#define CV_CALIB_FIX_K2 64 +#define CV_CALIB_FIX_K3 128 +#define CV_CALIB_FIX_K4 2048 +#define CV_CALIB_FIX_K5 4096 +#define CV_CALIB_FIX_K6 8192 +#define CV_CALIB_RATIONAL_MODEL 16384 +#define CV_CALIB_THIN_PRISM_MODEL 32768 +#define CV_CALIB_FIX_S1_S2_S3_S4 65536 +#define CV_CALIB_TILTED_MODEL 262144 +#define CV_CALIB_FIX_TAUX_TAUY 524288 +#define CV_CALIB_FIX_TANGENT_DIST 2097152 + +#define CV_CALIB_NINTRINSIC 18 + +#define CV_CALIB_FIX_INTRINSIC 256 +#define CV_CALIB_SAME_FOCAL_LENGTH 512 + +#define CV_CALIB_ZERO_DISPARITY 1024 + +/* stereo correspondence parameters and functions */ +#define CV_STEREO_BM_NORMALIZED_RESPONSE 0 +#define CV_STEREO_BM_XSOBEL 1 + +#ifdef __cplusplus +} // extern "C" + +////////////////////////////////////////////////////////////////////////////////////////// +class CV_EXPORTS CvLevMarq +{ +public: + CvLevMarq(); + CvLevMarq( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + ~CvLevMarq(); + void init( int nparams, int nerrs, CvTermCriteria criteria= + cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER,30,DBL_EPSILON), + bool completeSymmFlag=false ); + bool update( const CvMat*& param, CvMat*& J, CvMat*& err ); + bool updateAlt( const CvMat*& param, CvMat*& JtJ, CvMat*& JtErr, double*& errNorm ); + + void clear(); + void step(); + enum { DONE=0, STARTED=1, CALC_J=2, CHECK_ERR=3 }; + + cv::Ptr mask; + cv::Ptr prevParam; + cv::Ptr param; + cv::Ptr J; + cv::Ptr err; + cv::Ptr JtJ; + cv::Ptr JtJN; + cv::Ptr JtErr; + cv::Ptr JtJV; + cv::Ptr JtJW; + double prevErrNorm, errNorm; + int lambdaLg10; + CvTermCriteria criteria; + int state; + int iters; + bool completeSymmFlag; + int solveMethod; +}; + +#endif + +#endif /* OPENCV_CALIB3D_C_H */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core.hpp b/3rdParty/opencv-4.11.0/opencv2/core.hpp index cafa7bda27..d134273753 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core.hpp @@ -1,3419 +1,3419 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2015, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. -// Copyright (C) 2015, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_HPP -#define OPENCV_CORE_HPP - -#ifndef __cplusplus -# error core.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/base.hpp" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/traits.hpp" -#include "opencv2/core/matx.hpp" -#include "opencv2/core/types.hpp" -#include "opencv2/core/mat.hpp" -#include "opencv2/core/persistence.hpp" - -/** -@defgroup core Core functionality - -The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations, -and utility functions that other modules depend on. It’s essential for handling image data, -performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem. - -@{ - @defgroup core_basic Basic structures - @defgroup core_array Operations on arrays - @defgroup core_async Asynchronous API - @defgroup core_xml XML/YAML/JSON Persistence - @defgroup core_cluster Clustering - @defgroup core_utils Utility and system functions and macros - @{ - @defgroup core_logging Logging facilities - @defgroup core_utils_sse SSE utilities - @defgroup core_utils_neon NEON utilities - @defgroup core_utils_vsx VSX utilities - @defgroup core_utils_softfloat Softfloat support - @defgroup core_utils_samples Utility functions for OpenCV samples - @} - @defgroup core_opengl OpenGL interoperability - @defgroup core_optim Optimization Algorithms - @defgroup core_directx DirectX interoperability - @defgroup core_eigen Eigen support - @defgroup core_opencl OpenCL support - @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability - @defgroup core_hal Hardware Acceleration Layer - @{ - @defgroup core_hal_functions Functions - @defgroup core_hal_interface Interface - @defgroup core_hal_intrin Universal intrinsics - @{ - @defgroup core_hal_intrin_impl Private implementation helpers - @} - @defgroup core_lowlevel_api Low-level API for external libraries / plugins - @} - @defgroup core_parallel Parallel Processing - @{ - @defgroup core_parallel_backend Parallel backends API - @} - @defgroup core_quaternion Quaternion -@} - */ - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -/*! @brief Class passed to an error. - -This class encapsulates all or almost all necessary -information about the error happened in the program. The exception is -usually constructed and thrown implicitly via CV_Error and CV_Error_ macros. -@see error - */ -class CV_EXPORTS Exception : public std::exception -{ -public: - /*! - Default constructor - */ - Exception(); - /*! - Full constructor. Normally the constructor is not called explicitly. - Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. - */ - Exception(int _code, const String& _err, const String& _func, const String& _file, int _line); - virtual ~Exception() CV_NOEXCEPT; - - /*! - \return the error description and the context as a text string. - */ - virtual const char *what() const CV_NOEXCEPT CV_OVERRIDE; - void formatMessage(); - - String msg; ///< the formatted error message - - int code; ///< error code @see CVStatus - String err; ///< error description - String func; ///< function name. Available only when the compiler supports getting it - String file; ///< source file name where the error has occurred - int line; ///< line number in the source file where the error has occurred -}; - -/*! @brief Signals an error and raises the exception. - -By default the function prints information about the error to stderr, -then it either stops if cv::setBreakOnError() had been called before or raises the exception. -It is possible to alternate error processing by using #redirectError(). -@param exc the exception raisen. -@deprecated drop this version - */ -CV_EXPORTS CV_NORETURN void error(const Exception& exc); - -enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently - SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted - //!< independently; this flag and the previous one are - //!< mutually exclusive. - SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending - //!< order. - SORT_DESCENDING = 16 //!< each matrix row is sorted in the - //!< descending order; this flag and the previous one are also - //!< mutually exclusive. - }; - -//! @} core_utils - -//! @addtogroup core_array -//! @{ - -//! Covariation flags -enum CovarFlags { - /** The output covariance matrix is calculated as: - \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f] - The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used - for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for - face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true - covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of - the "scrambled" covariance matrix. */ - COVAR_SCRAMBLED = 0, - /**The output covariance matrix is calculated as: - \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f] - covar will be a square matrix of the same size as the total number of elements in each input - vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/ - COVAR_NORMAL = 1, - /** If the flag is specified, the function does not calculate mean from - the input vectors but, instead, uses the passed mean vector. This is useful if mean has been - pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In - this case, mean is not a mean vector of the input sub-set of vectors but rather the mean - vector of the whole set.*/ - COVAR_USE_AVG = 2, - /** If the flag is specified, the covariance matrix is scaled. In the - "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the - total number of elements in each input vector. By default (if the flag is not specified), the - covariance matrix is not scaled ( scale=1 ).*/ - COVAR_SCALE = 4, - /** If the flag is - specified, all the input vectors are stored as rows of the samples matrix. mean should be a - single-row vector in this case.*/ - COVAR_ROWS = 8, - /** If the flag is - specified, all the input vectors are stored as columns of the samples matrix. mean should be a - single-column vector in this case.*/ - COVAR_COLS = 16 -}; - -enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix. - REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. - REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. - REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. - REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix. - }; - -/** @brief Swaps two matrices -*/ -CV_EXPORTS void swap(Mat& a, Mat& b); -/** @overload */ -CV_EXPORTS void swap( UMat& a, UMat& b ); - -/** @brief Computes the source location of an extrapolated pixel. - -The function computes and returns the coordinate of a donor pixel corresponding to the specified -extrapolated pixel when using the specified extrapolation border mode. For example, if you use -cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and -want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img, it -looks like: -@code{.cpp} - float val = img.at(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), - borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); -@endcode -Normally, the function is not called directly. It is used inside filtering functions and also in -copyMakeBorder. -@param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len -@param len Length of the array along the corresponding axis. -@param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and -#BORDER_ISOLATED. When borderType==#BORDER_CONSTANT, the function always returns -1, regardless -of p and len. - -@sa copyMakeBorder -*/ -CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType); - -/** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp -An example using copyMakeBorder function. -Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details -*/ - -/** @brief Forms a border around an image. - -The function copies the source image into the middle of the destination image. The areas to the -left, to the right, above and below the copied source image will be filled with extrapolated -pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but -what other more complex functions, including your own, may do to simplify image boundary handling. - -The function supports the mode when src is already in the middle of dst . In this case, the -function does not copy src itself but simply constructs the border, for example: - -@code{.cpp} - // let border be the same in all directions - int border=2; - // constructs a larger image to fit both the image and the border - Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); - // select the middle part of it w/o copying data - Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); - // convert image from RGB to grayscale - cvtColor(rgb, gray, COLOR_RGB2GRAY); - // form a border in-place - copyMakeBorder(gray, gray_buf, border, border, - border, border, BORDER_REPLICATE); - // now do some custom filtering ... - ... -@endcode -@note When the source image is a part (ROI) of a bigger image, the function will try to use the -pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as -if src was not a ROI, use borderType | #BORDER_ISOLATED. - -@param src Source image. -@param dst Destination image of the same type as src and the size Size(src.cols+left+right, -src.rows+top+bottom) . -@param top the top pixels -@param bottom the bottom pixels -@param left the left pixels -@param right Parameter specifying how many pixels in each direction from the source image rectangle -to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs -to be built. -@param borderType Border type. See borderInterpolate for details. -@param value Border value if borderType==BORDER_CONSTANT . - -@sa borderInterpolate -*/ -CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst, - int top, int bottom, int left, int right, - int borderType, const Scalar& value = Scalar() ); - -/** @brief Calculates the per-element sum of two arrays or an array and a scalar. - -The function add calculates: -- Sum of two arrays when both input arrays have the same size and the same number of channels: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] -- Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of -elements as `src1.channels()`: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] -- Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of -elements as `src2.channels()`: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] -where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each -channel is processed independently. - -The first function in the list above can be replaced with matrix expressions: -@code{.cpp} - dst = src1 + src2; - dst += src1; // equivalent to add(dst, src1, dst); -@endcode -The input arrays and the output array can all have the same or different depths. For example, you -can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit -floating-point array. Depth of the output array is determined by the dtype parameter. In the second -and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can -be set to the default -1. In this case, the output array will have the same depth as the input -array, be it src1, src2 or both. -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`add(src,X)` means `add(src,(X,X,X,X))`. -`add(src,(X,))` means `add(src,(X,0,0,0))`. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and number of channels as the input array(s); the -depth is defined by dtype or src1/src2. -@param mask optional operation mask - 8-bit single channel array, that specifies elements of the -output array to be changed. -@param dtype optional depth of the output array (see the discussion below). -@sa subtract, addWeighted, scaleAdd, Mat::convertTo -*/ -CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, - InputArray mask = noArray(), int dtype = -1); - -/** @brief Calculates the per-element difference between two arrays or array and a scalar. - -The function subtract calculates: -- Difference between two arrays, when both input arrays have the same size and the same number of -channels: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] -- Difference between an array and a scalar, when src2 is constructed from Scalar or has the same -number of elements as `src1.channels()`: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] -- Difference between a scalar and an array, when src1 is constructed from Scalar or has the same -number of elements as `src2.channels()`: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] -- The reverse difference between a scalar and an array in the case of `SubRS`: - \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f] -where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each -channel is processed independently. - -The first function in the list above can be replaced with matrix expressions: -@code{.cpp} - dst = src1 - src2; - dst -= src1; // equivalent to subtract(dst, src1, dst); -@endcode -The input arrays and the output array can all have the same or different depths. For example, you -can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of -the output array is determined by dtype parameter. In the second and third cases above, as well as -in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this -case the output array will have the same depth as the input array, be it src1, src2 or both. -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`subtract(src,X)` means `subtract(src,(X,X,X,X))`. -`subtract(src,(X,))` means `subtract(src,(X,0,0,0))`. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array of the same size and the same number of channels as the input array. -@param mask optional operation mask; this is an 8-bit single channel array that specifies elements -of the output array to be changed. -@param dtype optional depth of the output array -@sa add, addWeighted, scaleAdd, Mat::convertTo - */ -CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, - InputArray mask = noArray(), int dtype = -1); - - -/** @brief Calculates the per-element scaled product of two arrays. - -The function multiply calculates the per-element product of two arrays: - -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] - -There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul . - -For a not-per-element matrix product, see gemm . - -@note Saturation is not applied when the output array has the depth -CV_32S. You may even get result of an incorrect sign in the case of -overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`multiply(src,X)` means `multiply(src,(X,X,X,X))`. -`multiply(src,(X,))` means `multiply(src,(X,0,0,0))`. -@param src1 first input array. -@param src2 second input array of the same size and the same type as src1. -@param dst output array of the same size and type as src1. -@param scale optional scale factor. -@param dtype optional depth of the output array -@sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, -Mat::convertTo -*/ -CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, - OutputArray dst, double scale = 1, int dtype = -1); - -/** @brief Performs per-element division of two arrays or a scalar by an array. - -The function cv::divide divides one array by another: -\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] -or a scalar by an array when there is no src1 : -\f[\texttt{dst(I) = saturate(scale/src2(I))}\f] - -Different channels of multi-channel arrays are processed independently. - -For integer types when src2(I) is zero, dst(I) will also be zero. - -@note In case of floating point data there is no special defined behavior for zero src2(I) values. -Regular floating-point division is used. -Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values). - -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`divide(src,X)` means `divide(src,(X,X,X,X))`. -`divide(src,(X,))` means `divide(src,(X,0,0,0))`. -@param src1 first input array. -@param src2 second input array of the same size and type as src1. -@param scale scalar factor. -@param dst output array of the same size and type as src2. -@param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in -case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). -@sa multiply, add, subtract -*/ -CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, - double scale = 1, int dtype = -1); - -/** @overload */ -CV_EXPORTS_W void divide(double scale, InputArray src2, - OutputArray dst, int dtype = -1); - -/** @brief Calculates the sum of a scaled array and another array. - -The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY -or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates -the sum of a scaled array and another array: -\f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f] -The function can also be emulated with a matrix expression, for example: -@code{.cpp} - Mat A(3, 3, CV_64F); - ... - A.row(0) = A.row(1)*2 + A.row(2); -@endcode -@param src1 first input array. -@param alpha scale factor for the first array. -@param src2 second input array of the same size and type as src1. -@param dst output array of the same size and type as src1. -@sa add, addWeighted, subtract, Mat::dot, Mat::convertTo -*/ -CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); - -/** @brief Calculates the weighted sum of two arrays. - -The function addWeighted calculates the weighted sum of two arrays as follows: -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] -where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each -channel is processed independently. -The function can be replaced with a matrix expression: -@code{.cpp} - dst = src1*alpha + src2*beta + gamma; -@endcode -@note Saturation is not applied when the output array has the depth CV_32S. You may even get -result of an incorrect sign in the case of overflow. -@param src1 first input array. -@param alpha weight of the first array elements. -@param src2 second input array of the same size and channel number as src1. -@param beta weight of the second array elements. -@param gamma scalar added to each sum. -@param dst output array that has the same size and number of channels as the input arrays. -@param dtype optional depth of the output array; when both input arrays have the same depth, dtype -can be set to -1, which will be equivalent to src1.depth(). -@sa add, subtract, scaleAdd, Mat::convertTo -*/ -CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, - double beta, double gamma, OutputArray dst, int dtype = -1); - -/** @brief Scales, calculates absolute values, and converts the result to 8-bit. - -On each element of the input array, the function convertScaleAbs -performs three operations sequentially: scaling, taking an absolute -value, conversion to an unsigned 8-bit type: -\f[\texttt{dst} (I)= \texttt{saturate\_cast} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f] -In case of multi-channel arrays, the function processes each channel -independently. When the output is not 8-bit, the operation can be -emulated by calling the Mat::convertTo method (or by using matrix -expressions) and then by calculating an absolute value of the result. -For example: -@code{.cpp} - Mat_ A(30,30); - randu(A, Scalar(-100), Scalar(100)); - Mat_ B = A*5 + 3; - B = abs(B); - // Mat_ B = abs(A*5+3) will also do the job, - // but it will allocate a temporary matrix -@endcode -@param src input array. -@param dst output array. -@param alpha optional scale factor. -@param beta optional delta added to the scaled values. -@sa Mat::convertTo, cv::abs(const Mat&) -*/ -CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, - double alpha = 1, double beta = 0); - -/** @brief Converts an array to half precision floating number. - -This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data. -There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or -CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error. -The format of half precision floating point is defined in IEEE 754-2008. - -@param src input array. -@param dst output array. - -@deprecated Use Mat::convertTo with CV_16F instead. -*/ -CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst); - -/** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp -Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details -*/ - -/** @brief Performs a look-up table transform of an array. - -The function LUT fills the output array with values from the look-up table. Indices of the entries -are taken from the input array. That is, the function processes each element of src as follows: -\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f] -where -\f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f] -@param src input array of 8-bit elements. -@param lut look-up table of 256 elements; in case of multi-channel input array, the table should -either have a single channel (in this case the same table is used for all channels) or the same -number of channels as in the input array. -@param dst output array of the same size and number of channels as src, and the same depth as lut. -@sa convertScaleAbs, Mat::convertTo -*/ -CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst); - -/** @brief Calculates the sum of array elements. - -The function cv::sum calculates and returns the sum of array elements, -independently for each channel. -@param src input array that must have from 1 to 4 channels. -@sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce -*/ -CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); - -/** @brief Checks for the presence of at least one non-zero array element. - -The function returns whether there are non-zero elements in src - -The function do not work with multi-channel arrays. If you need to check non-zero array -elements across all the channels, use Mat::reshape first to reinterpret the array as -single-channel. Or you may extract the particular channel using either extractImageCOI, or -mixChannels, or split. - -@note -- If the location of non-zero array elements is important, @ref findNonZero is helpful. -- If the count of non-zero array elements is important, @ref countNonZero is helpful. -@param src single-channel array. -@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix -@sa findNonZero, countNonZero -*/ -CV_EXPORTS_W bool hasNonZero( InputArray src ); - -/** @brief Counts non-zero array elements. - -The function returns the number of non-zero elements in src : -\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] - -The function do not work with multi-channel arrays. If you need to count non-zero array -elements across all the channels, use Mat::reshape first to reinterpret the array as -single-channel. Or you may extract the particular channel using either extractImageCOI, or -mixChannels, or split. - -@note -- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. -- If the location of non-zero array elements is important, @ref findNonZero is helpful. -@param src single-channel array. -@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix -@sa findNonZero, hasNonZero -*/ -CV_EXPORTS_W int countNonZero( InputArray src ); - -/** @brief Returns the list of locations of non-zero pixels - -Given a binary matrix (likely returned from an operation such -as threshold(), compare(), >, ==, etc, return all of -the non-zero indices as a cv::Mat or std::vector (x,y) -For example: -@code{.cpp} - cv::Mat binaryImage; // input, binary image - cv::Mat locations; // output, locations of non-zero pixels - cv::findNonZero(binaryImage, locations); - - // access pixel coordinates - Point pnt = locations.at(i); -@endcode -or -@code{.cpp} - cv::Mat binaryImage; // input, binary image - vector locations; // output, locations of non-zero pixels - cv::findNonZero(binaryImage, locations); - - // access pixel coordinates - Point pnt = locations[i]; -@endcode - -The function do not work with multi-channel arrays. If you need to find non-zero -elements across all the channels, use Mat::reshape first to reinterpret the array as -single-channel. Or you may extract the particular channel using either extractImageCOI, or -mixChannels, or split. - -@note -- If only count of non-zero array elements is important, @ref countNonZero is helpful. -- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. -@param src single-channel array -@param idx the output array, type of cv::Mat or std::vector, corresponding to non-zero indices in the input -@sa countNonZero, hasNonZero -*/ -CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); - -/** @brief Calculates an average (mean) of array elements. - -The function cv::mean calculates the mean value M of array elements, -independently for each channel, and return it: -\f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f] -When all the mask elements are 0's, the function returns Scalar::all(0) -@param src input array that should have from 1 to 4 channels so that the result can be stored in -Scalar_ . -@param mask optional operation mask. -@sa countNonZero, meanStdDev, norm, minMaxLoc -*/ -CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray()); - -/** Calculates a mean and standard deviation of array elements. - -The function cv::meanStdDev calculates the mean and the standard deviation M -of array elements independently for each channel and returns it via the -output parameters: -\f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f] -When all the mask elements are 0's, the function returns -mean=stddev=Scalar::all(0). -@note The calculated standard deviation is only the diagonal of the -complete normalized covariance matrix. If the full matrix is needed, you -can reshape the multi-channel array M x N to the single-channel array -M\*N x mtx.channels() (only possible when the matrix is continuous) and -then pass the matrix to calcCovarMatrix . -@param src input array that should have from 1 to 4 channels so that the results can be stored in -Scalar_ 's. -@param mean output parameter: calculated mean value. -@param stddev output parameter: calculated standard deviation. -@param mask optional operation mask. -@sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix -*/ -CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, - InputArray mask=noArray()); - -/** @brief Calculates the absolute norm of an array. - -This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ - \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ - \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ - \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ - \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. -\f} -The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$. -It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$. -![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) - -When the mask parameter is specified and it is not empty, the norm is - -If normType is not specified, #NORM_L2 is used. -calculated only over the region specified by the mask. - -Multi-channel input arrays are treated as single-channel arrays, that is, -the results for all channels are combined. - -Hamming norms can only be calculated with CV_8U depth arrays. - -@param src1 first input array. -@param normType type of the norm (see #NormTypes). -@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. -*/ -CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); - -/** @brief Calculates an absolute difference norm or a relative difference norm. - -This version of cv::norm calculates the absolute difference norm -or the relative difference norm of arrays src1 and src2. -The type of norm to calculate is specified using #NormTypes. - -@param src1 first input array. -@param src2 second input array of the same size and the same type as src1. -@param normType type of the norm (see #NormTypes). -@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. -*/ -CV_EXPORTS_W double norm(InputArray src1, InputArray src2, - int normType = NORM_L2, InputArray mask = noArray()); -/** @overload -@param src first input array. -@param normType type of the norm (see #NormTypes). -*/ -CV_EXPORTS double norm( const SparseMat& src, int normType ); - -/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. - -This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), -between two input arrays src1 and src2. The arrays must have the same type. - -The PSNR is calculated as follows: - -\f[ -\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } -\f] - -where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) -and MSE is the mean squared error between the two arrays. - -@param src1 first input array. -@param src2 second input array of the same size as src1. -@param R the maximum pixel value (255 by default) - - */ -CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.); - -/** @brief naive nearest neighbor finder - -see http://en.wikipedia.org/wiki/Nearest_neighbor_search -@todo document - */ -CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, - OutputArray dist, int dtype, OutputArray nidx, - int normType = NORM_L2, int K = 0, - InputArray mask = noArray(), int update = 0, - bool crosscheck = false); - -/** @brief Normalizes the norm or value range of an array. - -The function cv::normalize normalizes scale and shift the input array elements so that -\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] -(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that -\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] - -when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be -normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this -sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or -min-max but modify the whole array, you can use norm and Mat::convertTo. - -In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, -the range transformation for sparse matrices is not allowed since it can shift the zero level. - -Possible usage with some positive example data: -@code{.cpp} - vector positiveData = { 2.0, 8.0, 10.0 }; - vector normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; - - // Norm to probability (total count) - // sum(numbers) = 20.0 - // 2.0 0.1 (2.0/20.0) - // 8.0 0.4 (8.0/20.0) - // 10.0 0.5 (10.0/20.0) - normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); - - // Norm to unit vector: ||positiveData|| = 1.0 - // 2.0 0.15 - // 8.0 0.62 - // 10.0 0.77 - normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); - - // Norm to max element - // 2.0 0.2 (2.0/10.0) - // 8.0 0.8 (8.0/10.0) - // 10.0 1.0 (10.0/10.0) - normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); - - // Norm to range [0.0;1.0] - // 2.0 0.0 (shift to left border) - // 8.0 0.75 (6.0/8.0) - // 10.0 1.0 (shift to right border) - normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); -@endcode - -@param src input array. -@param dst output array of the same size as src . -@param alpha norm value to normalize to or the lower range boundary in case of the range -normalization. -@param beta upper range boundary in case of the range normalization; it is not used for the norm -normalization. -@param norm_type normalization type (see cv::NormTypes). -@param dtype when negative, the output array has the same type as src; otherwise, it has the same -number of channels as src and the depth =CV_MAT_DEPTH(dtype). -@param mask optional operation mask. -@sa norm, Mat::convertTo, SparseMat::convertTo -*/ -CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, - int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); - -/** @overload -@param src input array. -@param dst output array of the same size as src . -@param alpha norm value to normalize to or the lower range boundary in case of the range -normalization. -@param normType normalization type (see cv::NormTypes). -*/ -CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); - -/** @brief Finds the global minimum and maximum in an array. - -The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The -extrema are searched across the whole array or, if mask is not an empty array, in the specified -array region. - -In C++, if the input is multi-channel, you should omit the minLoc, maxLoc, and mask arguments -(i.e. leave them as NULL, NULL, and noArray() respectively). These arguments are not -supported for multi-channel input arrays. If working with multi-channel input and you -need the minLoc, maxLoc, or mask arguments, then use Mat::reshape first to reinterpret -the array as single-channel. Alternatively, you can extract the particular channel using either -extractImageCOI, mixChannels, or split. - -In Python, multi-channel input is not supported at all due to a limitation in the -binding generation process (there is no way to set minLoc and maxLoc to NULL). A -workaround is to operate on each channel individually or to use NumPy to achieve the same -functionality. - -@param src input single-channel array. -@param minVal pointer to the returned minimum value; NULL is used if not required. -@param maxVal pointer to the returned maximum value; NULL is used if not required. -@param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required. -@param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required. -@param mask optional mask used to select a sub-array. -@sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape -*/ -CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, - CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, - CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); - -/** - * @brief Finds indices of min elements along provided axis - * - * @note - * - If input or output array is not continuous, this function will create an internal copy. - * - NaN handling is left unspecified, see patchNaNs(). - * - The returned index is always in bounds of input matrix. - * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. - * @param lastIndex whether to get the index of first or last occurrence of min. - * @param axis axis to reduce along. - * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce - */ -CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false); - -/** - * @brief Finds indices of max elements along provided axis - * - * @note - * - If input or output array is not continuous, this function will create an internal copy. - * - NaN handling is left unspecified, see patchNaNs(). - * - The returned index is always in bounds of input matrix. - * - * @param src input single-channel array. - * @param dst output array of type CV_32SC1 with the same dimensionality as src, - * except for axis being reduced - it should be set to 1. - * @param lastIndex whether to get the index of first or last occurrence of max. - * @param axis axis to reduce along. - * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce - */ -CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false); - -/** @brief Finds the global minimum and maximum in an array - -The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The -extremums are searched across the whole array or, if mask is not an empty array, in the specified -array region. In case of a sparse matrix, the minimum is found among non-zero elements -only. Multi-channel input is supported without mask and extremums indexes (should be nullptr). -@note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is -a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2 -dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be -(i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be -(0,j1)/(0,j2)). -@param src input single-channel array. -@param minVal pointer to the returned minimum value; NULL is used if not required. -@param maxVal pointer to the returned maximum value; NULL is used if not required. -@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; -Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element -in each dimension are stored there sequentially. -@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. -@param mask specified array region -*/ -CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0, - int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); - -/** @overload -@param a input single-channel array. -@param minVal pointer to the returned minimum value; NULL is used if not required. -@param maxVal pointer to the returned maximum value; NULL is used if not required. -@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; -Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element -in each dimension are stored there sequentially. -@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. -*/ -CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, - double* maxVal, int* minIdx = 0, int* maxIdx = 0); - -/** @brief Reduces a matrix to a vector. - -The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of -1D vectors and performing the specified operation on the vectors until a single row/column is -obtained. For example, the function can be used to compute horizontal and vertical projections of a -raster image. In case of #REDUCE_MAX and #REDUCE_MIN, the output image should have the same type as the source one. -In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG, the output may have a larger element bit-depth to preserve accuracy. -And multi-channel arrays are also supported in these two reduction modes. - -The following code demonstrates its usage for a single channel matrix. -@snippet snippets/core_reduce.cpp example - -And the following code demonstrates its usage for a two-channel matrix. -@snippet snippets/core_reduce.cpp example2 - -@param src input 2D matrix. -@param dst output vector. Its size and type is defined by dim and dtype parameters. -@param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to -a single row. 1 means that the matrix is reduced to a single column. -@param rtype reduction operation that could be one of #ReduceTypes -@param dtype when negative, the output vector will have the same type as the input matrix, -otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). -@sa repeat, reduceArgMin, reduceArgMax -*/ -CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); - -/** @brief Creates one multi-channel array out of several single-channel ones. - -The function cv::merge merges several arrays to make a single multi-channel array. That is, each -element of the output array will be a concatenation of the elements of the input arrays, where -elements of i-th input array are treated as mv[i].channels()-element vectors. - -The function cv::split does the reverse operation. If you need to shuffle channels in some other -advanced way, use cv::mixChannels. - -The following example shows how to merge 3 single channel matrices into a single 3-channel matrix. -@snippet snippets/core_merge.cpp example - -@param mv input array of matrices to be merged; all the matrices in mv must have the same -size and the same depth. -@param count number of input matrices when mv is a plain C array; it must be greater than zero. -@param dst output array of the same size and the same depth as mv[0]; The number of channels will -be equal to the parameter count. -@sa mixChannels, split, Mat::reshape -*/ -CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); - -/** @overload -@param mv input vector of matrices to be merged; all the matrices in mv must have the same -size and the same depth. -@param dst output array of the same size and the same depth as mv[0]; The number of channels will -be the total number of channels in the matrix array. - */ -CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); - -/** @brief Divides a multi-channel array into several single-channel arrays. - -The function cv::split splits a multi-channel array into separate single-channel arrays: -\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] -If you need to extract a single channel or do some other sophisticated channel permutation, use -mixChannels. - -The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices. -@snippet snippets/core_split.cpp example - -@param src input multi-channel array. -@param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are -reallocated, if needed. -@sa merge, mixChannels, cvtColor -*/ -CV_EXPORTS void split(const Mat& src, Mat* mvbegin); - -/** @overload -@param m input multi-channel array. -@param mv output vector of arrays; the arrays themselves are reallocated, if needed. -*/ -CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); - -/** @brief Copies specified channels from input arrays to the specified channels of -output arrays. - -The function cv::mixChannels provides an advanced mechanism for shuffling image channels. - -cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels. - -In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R -channels swapped) and a separate alpha-channel image: -@code{.cpp} - Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) ); - Mat bgr( bgra.rows, bgra.cols, CV_8UC3 ); - Mat alpha( bgra.rows, bgra.cols, CV_8UC1 ); - - // forming an array of matrices is a quite efficient operation, - // because the matrix data is not copied, only the headers - Mat out[] = { bgr, alpha }; - // bgra[0] -> bgr[2], bgra[1] -> bgr[1], - // bgra[2] -> bgr[0], bgra[3] -> alpha[0] - int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; - mixChannels( &bgra, 1, out, 2, from_to, 4 ); -@endcode -@note Unlike many other new-style C++ functions in OpenCV (see the introduction section and -Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the -function. -@param src input array or vector of matrices; all of the matrices must have the same size and the -same depth. -@param nsrcs number of matrices in `src`. -@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and -depth must be the same as in `src[0]`. -@param ndsts number of matrices in `dst`. -@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is -a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in -dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to -src[0].channels()-1, the second input image channels are indexed from src[0].channels() to -src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image -channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is -filled with zero . -@param npairs number of index pairs in `fromTo`. -@sa split, merge, extractChannel, insertChannel, cvtColor -*/ -CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, - const int* fromTo, size_t npairs); - -/** @overload -@param src input array or vector of matrices; all of the matrices must have the same size and the -same depth. -@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and -depth must be the same as in src[0]. -@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is -a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in -dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to -src[0].channels()-1, the second input image channels are indexed from src[0].channels() to -src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image -channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is -filled with zero . -@param npairs number of index pairs in fromTo. -*/ -CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, - const int* fromTo, size_t npairs); - -/** @overload -@param src input array or vector of matrices; all of the matrices must have the same size and the -same depth. -@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and -depth must be the same as in src[0]. -@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is -a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in -dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to -src[0].channels()-1, the second input image channels are indexed from src[0].channels() to -src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image -channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is -filled with zero . -*/ -CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, - const std::vector& fromTo); - -/** @brief Extracts a single channel from src (coi is 0-based index) -@param src input array -@param dst output array -@param coi index of channel to extract -@sa mixChannels, split -*/ -CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); - -/** @brief Inserts a single channel to dst (coi is 0-based index) -@param src input array -@param dst output array -@param coi index of channel for insertion -@sa mixChannels, merge -*/ -CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); - -/** @brief Flips a 2D array around vertical, horizontal, or both axes. - -The function cv::flip flips the array in one of three different ways (row -and column indices are 0-based): -\f[\texttt{dst} _{ij} = -\left\{ -\begin{array}{l l} -\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ -\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ -\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ -\end{array} -\right.\f] -The example scenarios of using the function are the following: -* Vertical flipping of the image (flipCode == 0) to switch between - top-left and bottom-left image origin. This is a typical operation - in video processing on Microsoft Windows\* OS. -* Horizontal flipping of the image with the subsequent horizontal - shift and absolute difference calculation to check for a - vertical-axis symmetry (flipCode \> 0). -* Simultaneous horizontal and vertical flipping of the image with - the subsequent shift and absolute difference calculation to check - for a central symmetry (flipCode \< 0). -* Reversing the order of point arrays (flipCode \> 0 or - flipCode == 0). -@param src input array. -@param dst output array of the same size and type as src. -@param flipCode a flag to specify how to flip the array; 0 means -flipping around the x-axis and positive value (for example, 1) means -flipping around y-axis. Negative value (for example, -1) means flipping -around both axes. -@sa transpose, repeat, completeSymm -*/ -CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); - -/** @brief Flips a n-dimensional at given axis - * @param src input array - * @param dst output array that has the same shape of src - * @param axis axis that performs a flip on. 0 <= axis < src.dims. - */ -CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis); - -/** @brief Broadcast the given Mat to the given shape. - * @param src input array - * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported. - * @param dst output array that has the given shape - */ -CV_EXPORTS_W void broadcast(InputArray src, InputArray shape, OutputArray dst); - -enum RotateFlags { - ROTATE_90_CLOCKWISE = 0, //! A = (cv::Mat_(3, 2) << 1, 4, - 2, 5, - 3, 6); - cv::Mat_ B = (cv::Mat_(3, 2) << 7, 10, - 8, 11, - 9, 12); - - cv::Mat C; - cv::hconcat(A, B, C); - //C: - //[1, 4, 7, 10; - // 2, 5, 8, 11; - // 3, 6, 9, 12] - @endcode - @param src1 first input array to be considered for horizontal concatenation. - @param src2 second input array to be considered for horizontal concatenation. - @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. - */ -CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); -/** @overload - @code{.cpp} - std::vector matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), - cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), - cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; - - cv::Mat out; - cv::hconcat( matrices, out ); - //out: - //[1, 2, 3; - // 1, 2, 3; - // 1, 2, 3; - // 1, 2, 3] - @endcode - @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. - @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. -same depth. - */ -CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); - -/** @brief Applies vertical concatenation to given matrices. - -The function vertically concatenates two or more cv::Mat matrices (with the same number of cols). -@code{.cpp} - cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; - - cv::Mat out; - cv::vconcat( matArray, 3, out ); - //out: - //[1, 1, 1, 1; - // 2, 2, 2, 2; - // 3, 3, 3, 3] -@endcode -@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. -@param nsrc number of matrices in src. -@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. -@sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray) -*/ -CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); -/** @overload - @code{.cpp} - cv::Mat_ A = (cv::Mat_(3, 2) << 1, 7, - 2, 8, - 3, 9); - cv::Mat_ B = (cv::Mat_(3, 2) << 4, 10, - 5, 11, - 6, 12); - - cv::Mat C; - cv::vconcat(A, B, C); - //C: - //[1, 7; - // 2, 8; - // 3, 9; - // 4, 10; - // 5, 11; - // 6, 12] - @endcode - @param src1 first input array to be considered for vertical concatenation. - @param src2 second input array to be considered for vertical concatenation. - @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. - */ -CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); -/** @overload - @code{.cpp} - std::vector matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), - cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; - - cv::Mat out; - cv::vconcat( matrices, out ); - //out: - //[1, 1, 1, 1; - // 2, 2, 2, 2; - // 3, 3, 3, 3] - @endcode - @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth - @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. -same depth. - */ -CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); - -/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2) -Calculates the per-element bit-wise conjunction of two arrays or an -array and a scalar. - -The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: -* Two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -* An array and a scalar when src2 is constructed from Scalar or has - the same number of elements as `src1.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] -* A scalar and an array when src1 is constructed from Scalar or has - the same number of elements as `src2.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -In case of floating-point arrays, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel arrays, each channel is processed -independently. In the second and third cases above, the scalar is first -converted to the array type. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as the input -arrays. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask = noArray()); - -/** @brief Calculates the per-element bit-wise disjunction of two arrays or an -array and a scalar. - -The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: -* Two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -* An array and a scalar when src2 is constructed from Scalar or has - the same number of elements as `src1.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] -* A scalar and an array when src1 is constructed from Scalar or has - the same number of elements as `src2.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -In case of floating-point arrays, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel arrays, each channel is processed -independently. In the second and third cases above, the scalar is first -converted to the array type. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as the input -arrays. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask = noArray()); - -/** @brief Calculates the per-element bit-wise "exclusive or" operation on two -arrays or an array and a scalar. - -The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" -operation for: -* Two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -* An array and a scalar when src2 is constructed from Scalar or has - the same number of elements as `src1.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] -* A scalar and an array when src1 is constructed from Scalar or has - the same number of elements as `src2.channels()`: - \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] -In case of floating-point arrays, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel arrays, each channel is processed -independently. In the 2nd and 3rd cases above, the scalar is first -converted to the array type. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as the input -arrays. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, - OutputArray dst, InputArray mask = noArray()); - -/** @brief Inverts every bit of an array. - -The function cv::bitwise_not calculates per-element bit-wise inversion of the input -array: -\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] -In case of a floating-point input array, its machine-specific bit -representation (usually IEEE754-compliant) is used for the operation. In -case of multi-channel arrays, each channel is processed independently. -@param src input array. -@param dst output array that has the same size and type as the input -array. -@param mask optional operation mask, 8-bit single channel array, that -specifies elements of the output array to be changed. -*/ -CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, - InputArray mask = noArray()); - -/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar. - -The function cv::absdiff calculates: -* Absolute difference between two arrays when they have the same - size and type: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] -* Absolute difference between an array and a scalar when the second - array is constructed from Scalar or has as many elements as the - number of channels in `src1`: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f] -* Absolute difference between a scalar and an array when the first - array is constructed from Scalar or has as many elements as the - number of channels in `src2`: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f] - where I is a multi-dimensional index of array elements. In case of - multi-channel arrays, each channel is processed independently. -@note Saturation is not applied when the arrays have the depth CV_32S. -You may even get a negative value in the case of overflow. -@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. -`absdiff(src,X)` means `absdiff(src,(X,X,X,X))`. -`absdiff(src,(X,))` means `absdiff(src,(X,0,0,0))`. -@param src1 first input array or a scalar. -@param src2 second input array or a scalar. -@param dst output array that has the same size and type as input arrays. -@sa cv::abs(const Mat&) -*/ -CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); - -/** @brief This is an overloaded member function, provided for convenience (python) -Copies the matrix to another one. -When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. -@param src source matrix. -@param dst Destination matrix. If it does not have a proper size or type before the operation, it is -reallocated. -@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix -elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. -*/ - -void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask); -/** @brief Checks if array elements lie between the elements of two other arrays. - -The function checks the range as follows: -- For every element of a single-channel input array: - \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f] -- For two-channel arrays: - \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f] -- and so forth. - -That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the -specified 1D, 2D, 3D, ... box and 0 otherwise. - -When the lower and/or upper boundary parameters are scalars, the indexes -(I) at lowerb and upperb in the above formulas should be omitted. -@param src first input array. -@param lowerb inclusive lower boundary array or a scalar. -@param upperb inclusive upper boundary array or a scalar. -@param dst output array of the same size as src and CV_8U type. -*/ -CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, - InputArray upperb, OutputArray dst); - -/** @brief Performs the per-element comparison of two arrays or an array and scalar value. - -The function compares: -* Elements of two arrays when src1 and src2 have the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f] -* Elements of src1 with a scalar src2 when src2 is constructed from - Scalar or has a single element: - \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f] -* src1 with elements of src2 when src1 is constructed from Scalar or - has a single element: - \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f] -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: -@code{.cpp} - Mat dst1 = src1 >= src2; - Mat dst2 = src1 < 8; - ... -@endcode -@param src1 first input array or a scalar; when it is an array, it must have a single channel. -@param src2 second input array or a scalar; when it is an array, it must have a single channel. -@param dst output array of type ref CV_8U that has the same size and the same number of channels as - the input arrays. -@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) -@sa checkRange, min, max, threshold -*/ -CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); - -/** @brief Calculates per-element minimum of two arrays or an array and a scalar. - -The function cv::min calculates the per-element minimum of two arrays: -\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] -or array and a scalar: -\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f] -@param src1 first input array. -@param src2 second input array of the same size and type as src1. -@param dst output array of the same size and type as src1. -@sa max, compare, inRange, minMaxLoc -*/ -CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst); - -/** @brief Calculates per-element maximum of two arrays or an array and a scalar. - -The function cv::max calculates the per-element maximum of two arrays: -\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] -or array and a scalar: -\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f] -@param src1 first input array. -@param src2 second input array of the same size and type as src1 . -@param dst output array of the same size and type as src1. -@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions -*/ -CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); -/** @overload -needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) -*/ -CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst); - -/** @brief Calculates a square root of array elements. - -The function cv::sqrt calculates a square root of each input array element. -In case of multi-channel arrays, each channel is processed -independently. The accuracy is approximately the same as of the built-in -std::sqrt . -@param src input floating-point array. -@param dst output array of the same size and type as src. -*/ -CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); - -/** @brief Raises every array element to a power. - -The function cv::pow raises every element of the input array to power : -\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f] - -So, for a non-integer power exponent, the absolute values of input array -elements are used. However, it is possible to get true values for -negative values using some extra operations. In the example below, -computing the 5th root of array src shows: -@code{.cpp} - Mat mask = src < 0; - pow(src, 1./5, dst); - subtract(Scalar::all(0), dst, dst, mask); -@endcode -For some values of power, such as integer values, 0.5 and -0.5, -specialized faster algorithms are used. - -Special values (NaN, Inf) are not handled. -@param src input array. -@param power exponent of power. -@param dst output array of the same size and type as src. -@sa sqrt, exp, log, cartToPolar, polarToCart -*/ -CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); - -/** @brief Calculates the exponent of every array element. - -The function cv::exp calculates the exponent of every element of the input -array: -\f[\texttt{dst} [I] = e^{ src(I) }\f] - -The maximum relative error is about 7e-6 for single-precision input and -less than 1e-10 for double-precision input. Currently, the function -converts denormalized values to zeros on output. Special values (NaN, -Inf) are not handled. -@param src input array. -@param dst output array of the same size and type as src. -@sa log, cartToPolar, polarToCart, phase, pow, sqrt, magnitude -*/ -CV_EXPORTS_W void exp(InputArray src, OutputArray dst); - -/** @brief Calculates the natural logarithm of every array element. - -The function cv::log calculates the natural logarithm of every element of the input array: -\f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f] - -Output on zero, negative and special (NaN, Inf) values is undefined. - -@param src input array. -@param dst output array of the same size and type as src . -@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude -*/ -CV_EXPORTS_W void log(InputArray src, OutputArray dst); - -/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. - -The function cv::polarToCart calculates the Cartesian coordinates of each 2D -vector represented by the corresponding elements of magnitude and angle: -\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] - -The relative accuracy of the estimated coordinates is about 1e-6. -@param magnitude input floating-point array of magnitudes of 2D vectors; -it can be an empty matrix (=Mat()), in this case, the function assumes -that all the magnitudes are =1; if it is not empty, it must have the -same size and type as angle. -@param angle input floating-point array of angles of 2D vectors. -@param x output array of x-coordinates of 2D vectors; it has the same -size and type as angle. -@param y output array of y-coordinates of 2D vectors; it has the same -size and type as angle. -@param angleInDegrees when true, the input angles are measured in -degrees, otherwise, they are measured in radians. -@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt -*/ -CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, - OutputArray x, OutputArray y, bool angleInDegrees = false); - -/** @brief Calculates the magnitude and angle of 2D vectors. - -The function cv::cartToPolar calculates either the magnitude, angle, or both -for every 2D vector (x(I),y(I)): -\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] - -The angles are calculated with accuracy about 0.3 degrees. For the point -(0,0), the angle is set to 0. -@param x array of x-coordinates; this must be a single-precision or -double-precision floating-point array. -@param y array of y-coordinates, that must have the same size and same type as x. -@param magnitude output array of magnitudes of the same size and type as x. -@param angle output array of angles that has the same size and type as -x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). -@param angleInDegrees a flag, indicating whether the angles are measured -in radians (which is by default), or in degrees. -@sa Sobel, Scharr -*/ -CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, - OutputArray magnitude, OutputArray angle, - bool angleInDegrees = false); - -/** @brief Calculates the rotation angle of 2D vectors. - -The function cv::phase calculates the rotation angle of each 2D vector that -is formed from the corresponding elements of x and y : -\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] - -The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , -the corresponding angle(I) is set to 0. -@param x input floating-point array of x-coordinates of 2D vectors. -@param y input array of y-coordinates of 2D vectors; it must have the -same size and the same type as x. -@param angle output array of vector angles; it has the same size and -same type as x . -@param angleInDegrees when true, the function calculates the angle in -degrees, otherwise, they are measured in radians. -*/ -CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, - bool angleInDegrees = false); - -/** @brief Calculates the magnitude of 2D vectors. - -The function cv::magnitude calculates the magnitude of 2D vectors formed -from the corresponding elements of x and y arrays: -\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f] -@param x floating-point array of x-coordinates of the vectors. -@param y floating-point array of y-coordinates of the vectors; it must -have the same size as x. -@param magnitude output array of the same size and type as x. -@sa cartToPolar, polarToCart, phase, sqrt -*/ -CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); - -/** @brief Checks every element of an input array for invalid values. - -The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \> --DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and -maxVal. In case of multi-channel arrays, each channel is processed independently. If some values -are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the -function either returns false (when quiet=true) or throws an exception. -@param a input array. -@param quiet a flag, indicating whether the functions quietly return false when the array elements -are out of range or they throw an exception. -@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims -elements. -@param minVal inclusive lower boundary of valid values range. -@param maxVal exclusive upper boundary of valid values range. -*/ -CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, - double minVal = -DBL_MAX, double maxVal = DBL_MAX); - -/** @brief Replaces NaNs by given number -@param a input/output matrix (CV_32F type). -@param val value to convert the NaNs -*/ -CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0); - -/** @brief Performs generalized matrix multiplication. - -The function cv::gemm performs generalized matrix multiplication similar to the -gemm functions in BLAS level 3. For example, -`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)` -corresponds to -\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f] - -In case of complex (two-channel) data, performed a complex matrix -multiplication. - -The function can be replaced with a matrix expression. For example, the -above call can be replaced with: -@code{.cpp} - dst = alpha*src1.t()*src2 + beta*src3.t(); -@endcode -@param src1 first multiplied input matrix that could be real(CV_32FC1, -CV_64FC1) or complex(CV_32FC2, CV_64FC2). -@param src2 second multiplied input matrix of the same type as src1. -@param alpha weight of the matrix product. -@param src3 third optional delta matrix added to the matrix product; it -should have the same type as src1 and src2. -@param beta weight of src3. -@param dst output matrix; it has the proper size and the same type as -input matrices. -@param flags operation flags (cv::GemmFlags) -@sa mulTransposed, transform -*/ -CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, - InputArray src3, double beta, OutputArray dst, int flags = 0); - -/** @brief Calculates the product of a matrix and its transposition. - -The function cv::mulTransposed calculates the product of src and its -transposition: -\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f] -if aTa=true, and -\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f] -otherwise. The function is used to calculate the covariance matrix. With -zero delta, it can be used as a faster substitute for general matrix -product A\*B when B=A' -@param src input single-channel matrix. Note that unlike gemm, the -function can multiply not only floating-point matrices. -@param dst output square matrix. -@param aTa Flag specifying the multiplication ordering. See the -description below. -@param delta Optional delta matrix subtracted from src before the -multiplication. When the matrix is empty ( delta=noArray() ), it is -assumed to be zero, that is, nothing is subtracted. If it has the same -size as src, it is simply subtracted. Otherwise, it is "repeated" (see -repeat ) to cover the full src and then subtracted. Type of the delta -matrix, when it is not empty, must be the same as the type of created -output matrix. See the dtype parameter description below. -@param scale Optional scale factor for the matrix product. -@param dtype Optional type of the output matrix. When it is negative, -the output matrix will have the same type as src . Otherwise, it will be -type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . -@sa calcCovarMatrix, gemm, repeat, reduce -*/ -CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, - InputArray delta = noArray(), - double scale = 1, int dtype = -1 ); - -/** @brief Transposes a matrix. - -The function cv::transpose transposes the matrix src : -\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] -@note No complex conjugation is done in case of a complex matrix. It -should be done separately if needed. -@param src input array. -@param dst output array of the same type as src. -*/ -CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); - -/** @brief Transpose for n-dimensional matrices. - * - * @note Input should be continuous single-channel matrix. - * @param src input array. - * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src. - * The i'th axis of dst will correspond to the axis numbered order[i] of the input. - * @param dst output array of the same type as src. - */ -CV_EXPORTS_W void transposeND(InputArray src, const std::vector& order, OutputArray dst); - -/** @brief Performs the matrix transformation of every array element. - -The function cv::transform performs the matrix transformation of every -element of the array src and stores the results in dst : -\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f] -(when m.cols=src.channels() ), or -\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f] -(when m.cols=src.channels()+1 ) - -Every element of the N -channel array src is interpreted as N -element -vector that is transformed using the M x N or M x (N+1) matrix m to -M-element vector - the corresponding element of the output array dst . - -The function may be used for geometrical transformation of -N -dimensional points, arbitrary linear color space transformation (such -as various kinds of RGB to YUV transforms), shuffling the image -channels, and so forth. -@param src input array that must have as many channels (1 to 4) as -m.cols or m.cols-1. -@param dst output array of the same size and depth as src; it has as -many channels as m.rows. -@param m transformation 2x2 or 2x3 floating-point matrix. -@sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective -*/ -CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); - -/** @brief Performs the perspective matrix transformation of vectors. - -The function cv::perspectiveTransform transforms every element of src by -treating it as a 2D or 3D vector, in the following way: -\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f] -where -\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f] -and -\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f] - -Here a 3D vector transformation is shown. In case of a 2D vector -transformation, the z component is omitted. - -@note The function transforms a sparse set of 2D or 3D vectors. If you -want to transform an image using perspective transformation, use -warpPerspective . If you have an inverse problem, that is, you want to -compute the most probable perspective transformation out of several -pairs of corresponding points, you can use getPerspectiveTransform or -findHomography . -@param src input two-channel or three-channel floating-point array; each -element is a 2D/3D vector to be transformed. -@param dst output array of the same size and type as src. -@param m 3x3 or 4x4 floating-point transformation matrix. -@sa transform, warpPerspective, getPerspectiveTransform, findHomography -*/ -CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); - -/** @brief Copies the lower or the upper half of a square matrix to its another half. - -The function cv::completeSymm copies the lower or the upper half of a square matrix to -its another half. The matrix diagonal remains unchanged: - - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if - lowerToUpper=false - - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if - lowerToUpper=true - -@param m input-output floating-point square matrix. -@param lowerToUpper operation flag; if true, the lower half is copied to -the upper half. Otherwise, the upper half is copied to the lower half. -@sa flip, transpose -*/ -CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false); - -/** @brief Initializes a scaled identity matrix. - -The function cv::setIdentity initializes a scaled identity matrix: -\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f] - -The function can also be emulated using the matrix initializers and the -matrix expressions: -@code - Mat A = Mat::eye(4, 3, CV_32F)*5; - // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] -@endcode -@param mtx matrix to initialize (not necessarily square). -@param s value to assign to diagonal elements. -@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= -*/ -CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); - -/** @brief Returns the determinant of a square floating-point matrix. - -The function cv::determinant calculates and returns the determinant of the -specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the -direct method is used. For larger matrices, the function uses LU -factorization with partial pivoting. - -For symmetric positively-determined matrices, it is also possible to use -eigen decomposition to calculate the determinant. -@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and -square size. -@sa trace, invert, solve, eigen, @ref MatrixExpressions -*/ -CV_EXPORTS_W double determinant(InputArray mtx); - -/** @brief Returns the trace of a matrix. - -The function cv::trace returns the sum of the diagonal elements of the -matrix mtx . -\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f] -@param mtx input matrix. -*/ -CV_EXPORTS_W Scalar trace(InputArray mtx); - -/** @brief Finds the inverse or pseudo-inverse of a matrix. - -The function cv::invert inverts the matrix src and stores the result in dst -. When the matrix src is singular or non-square, the function calculates -the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is -minimal, where I is an identity matrix. - -In case of the #DECOMP_LU method, the function returns non-zero value if -the inverse has been successfully calculated and 0 if src is singular. - -In case of the #DECOMP_SVD method, the function returns the inverse -condition number of src (the ratio of the smallest singular value to the -largest singular value) and 0 if src is singular. The SVD method -calculates a pseudo-inverse matrix if src is singular. - -Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with -non-singular square matrices that should also be symmetrical and -positively defined. In this case, the function stores the inverted -matrix in dst and returns non-zero. Otherwise, it returns 0. - -@param src input floating-point M x N matrix. -@param dst output matrix of N x M size and the same type as src. -@param flags inversion method (cv::DecompTypes) -@sa solve, SVD -*/ -CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); - -/** @brief Solves one or more linear systems or least-squares problems. - -The function cv::solve solves a linear system or least-squares problem (the -latter is possible with SVD or QR methods, or by specifying the flag -#DECOMP_NORMAL ): -\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f] - -If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 -if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise, -it returns 0. In the latter case, dst is not valid. Other methods find a -pseudo-solution in case of a singular left-hand side part. - -@note If you want to find a unity-norm solution of an under-defined -singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve -will not do the work. Use SVD::solveZ instead. - -@param src1 input matrix on the left-hand side of the system. -@param src2 input matrix on the right-hand side of the system. -@param dst output solution. -@param flags solution (matrix inversion) method (#DecompTypes) -@sa invert, SVD, eigen -*/ -CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, - OutputArray dst, int flags = DECOMP_LU); - -/** @brief Sorts each row or each column of a matrix. - -The function cv::sort sorts each matrix row or each matrix column in -ascending or descending order. So you should pass two operation flags to -get desired behaviour. If you want to sort matrix rows or columns -lexicographically, you can use STL std::sort generic function with the -proper comparison predicate. - -@param src input single-channel array. -@param dst output array of the same size and type as src. -@param flags operation flags, a combination of #SortFlags -@sa sortIdx, randShuffle -*/ -CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); - -/** @brief Sorts each row or each column of a matrix. - -The function cv::sortIdx sorts each matrix row or each matrix column in the -ascending or descending order. So you should pass two operation flags to -get desired behaviour. Instead of reordering the elements themselves, it -stores the indices of sorted elements in the output array. For example: -@code - Mat A = Mat::eye(3,3,CV_32F), B; - sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); - // B will probably contain - // (because of equal elements in A some permutations are possible): - // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] -@endcode -@param src input single-channel array. -@param dst output integer array of the same size as src. -@param flags operation flags that could be a combination of cv::SortFlags -@sa sort, randShuffle -*/ -CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); - -/** @brief Finds the real roots of a cubic equation. - -The function solveCubic finds the real roots of a cubic equation: -- if coeffs is a 4-element vector: -\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f] -- if coeffs is a 3-element vector: -\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f] - -The roots are stored in the roots array. -@param coeffs equation coefficients, an array of 3 or 4 elements. -@param roots output array of real roots that has 1 or 3 elements. -@return number of real roots. It can be 0, 1 or 2. -*/ -CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); - -/** @brief Finds the real or complex roots of a polynomial equation. - -The function cv::solvePoly finds real and complex roots of a polynomial equation: -\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f] -@param coeffs array of polynomial coefficients. -@param roots output (complex) array of roots. -@param maxIters maximum number of iterations the algorithm does. -*/ -CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300); - -/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix. - -The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric -matrix src: -@code - src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() -@endcode - -@note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. - -@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical -(src ^T^ == src). -@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored -in the descending order. -@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the -eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding -eigenvalues. -@sa eigenNonSymmetric, completeSymm, PCA -*/ -CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues, - OutputArray eigenvectors = noArray()); - -/** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only). - -@note Assumes real eigenvalues. - -The function calculates eigenvalues and eigenvectors (optional) of the square matrix src: -@code - src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() -@endcode - -@param src input matrix (CV_32FC1 or CV_64FC1 type). -@param eigenvalues output vector of eigenvalues (type is the same type as src). -@param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. -@sa eigen -*/ -CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues, - OutputArray eigenvectors); - -/** @brief Calculates the covariance matrix of a set of vectors. - -The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of -the set of input vectors. -@param samples samples stored as separate matrices -@param nsamples number of samples -@param covar output covariance matrix of the type ctype and square size. -@param mean input or output (depending on the flags) array as the average value of the input vectors. -@param flags operation flags as a combination of #CovarFlags -@param ctype type of the matrixl; it equals 'CV_64F' by default. -@sa PCA, mulTransposed, Mahalanobis -@todo InputArrayOfArrays -*/ -CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, - int flags, int ctype = CV_64F); - -/** @overload -@note use #COVAR_ROWS or #COVAR_COLS flag -@param samples samples stored as rows/columns of a single matrix. -@param covar output covariance matrix of the type ctype and square size. -@param mean input or output (depending on the flags) array as the average value of the input vectors. -@param flags operation flags as a combination of #CovarFlags -@param ctype type of the matrixl; it equals 'CV_64F' by default. -*/ -CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, - InputOutputArray mean, int flags, int ctype = CV_64F); - -/** wrap PCA::operator() */ -CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, int maxComponents = 0); - -/** wrap PCA::operator() and add eigenvalues output parameter */ -CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, OutputArray eigenvalues, - int maxComponents = 0); - -/** wrap PCA::operator() */ -CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, double retainedVariance); - -/** wrap PCA::operator() and add eigenvalues output parameter */ -CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, - OutputArray eigenvectors, OutputArray eigenvalues, - double retainedVariance); - -/** wrap PCA::project */ -CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result); - -/** wrap PCA::backProject */ -CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, - InputArray eigenvectors, OutputArray result); - -/** wrap SVD::compute */ -CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); - -/** wrap SVD::backSubst */ -CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, - InputArray rhs, OutputArray dst ); - -/** @brief Calculates the Mahalanobis distance between two vectors. - -The function cv::Mahalanobis calculates and returns the weighted distance between two vectors: -\f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f] -The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using -the invert function (preferably using the #DECOMP_SVD method, as the most accurate). -@param v1 first 1D input vector. -@param v2 second 1D input vector. -@param icovar inverse covariance matrix. -*/ -CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); - -/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. - -The function cv::dft performs one of the following: -- Forward the Fourier transform of a 1D vector of N elements: - \f[Y = F^{(N)} \cdot X,\f] - where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$ -- Inverse the Fourier transform of a 1D vector of N elements: - \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f] - where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$ -- Forward the 2D Fourier transform of a M x N matrix: - \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f] -- Inverse the 2D Fourier transform of a M x N matrix: - \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f] - -In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input -spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* -(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here -is how 2D *CCS* spectrum looks: -\f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f] - -In case of 1D transform of a real vector, the output looks like the first row of the matrix above. - -So, the function chooses an operation mode depending on the flags and size of the input array: -- If #DFT_ROWS is set or the input array has a single row or single column, the function - performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set. - Otherwise, it performs a 2D transform. -- If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or - 2D transform: - - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as - input. - - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as - input. In case of 2D transform, it uses the packed format as shown above. In case of a - single 1D transform, it looks like the first row of the matrix above. In case of - multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix - looks like the first row of the matrix above. -- If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the - output is a complex array of the same size as input. The function performs a forward or - inverse 1D or 2D transform of the whole input array or each row of the input array - independently, depending on the flags DFT_INVERSE and DFT_ROWS. -- When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT - is set, the output is a real array of the same size as input. The function performs a 1D or 2D - inverse transformation of the whole input array or each individual row, depending on the flags - #DFT_INVERSE and #DFT_ROWS. - -If #DFT_SCALE is set, the scaling is done after the transformation. - -Unlike dct, the function supports arrays of arbitrary size. But only those arrays are processed -efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the -current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize -method. - -The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: -@code - void convolveDFT(InputArray A, InputArray B, OutputArray C) - { - // reallocate the output array if needed - C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type()); - Size dftSize; - // calculate the size of DFT transform - dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); - dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); - - // allocate temporary buffers and initialize them with 0's - Mat tempA(dftSize, A.type(), Scalar::all(0)); - Mat tempB(dftSize, B.type(), Scalar::all(0)); - - // copy A and B to the top-left corners of tempA and tempB, respectively - Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); - A.copyTo(roiA); - Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); - B.copyTo(roiB); - - // now transform the padded A & B in-place; - // use "nonzeroRows" hint for faster processing - dft(tempA, tempA, 0, A.rows); - dft(tempB, tempB, 0, B.rows); - - // multiply the spectrums; - // the function handles packed spectrum representations well - mulSpectrums(tempA, tempB, tempA); - - // transform the product back from the frequency domain. - // Even though all the result rows will be non-zero, - // you need only the first C.rows of them, and thus you - // pass nonzeroRows == C.rows - dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); - - // now copy the result back to C. - tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); - - // all the temporary buffers will be deallocated automatically - } -@endcode -To optimize this sample, consider the following approaches: -- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to - the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole - tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols) - rightmost columns of the matrices. -- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B - is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts. - To do this, you need to split the output array C into multiple tiles. For each tile, estimate - which parts of A and B are required to calculate convolution in this tile. If the tiles in C are - too small, the speed will decrease a lot because of repeated work. In the ultimate case, when - each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution - algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and - there is also a slowdown because of bad cache locality. So, there is an optimal tile size - somewhere in the middle. -- If different tiles in C can be calculated in parallel and, thus, the convolution is done by - parts, the loop can be threaded. - -All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by -using them, you can get the performance even better than with the above theoretically optimal -implementation. Though, those two functions actually calculate cross-correlation, not convolution, -so you need to "flip" the second convolution operand B vertically and horizontally using flip . -@note -- An example using the discrete fourier transform can be found at - opencv_source_code/samples/cpp/dft.cpp -- (Python) An example using the dft functionality to perform Wiener deconvolution can be found - at opencv_source/samples/python/deconvolution.py -- (Python) An example rearranging the quadrants of a Fourier image can be found at - opencv_source/samples/python/dft.py -@param src input array that could be real or complex. -@param dst output array whose size and type depends on the flags . -@param flags transformation flags, representing a combination of the #DftFlags -@param nonzeroRows when the parameter is not zero, the function assumes that only the first -nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the -output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the -rows more efficiently and save some time; this technique is very useful for calculating array -cross-correlation or convolution using DFT. -@sa dct, getOptimalDFTSize, mulSpectrums, filter2D, matchTemplate, flip, cartToPolar, -magnitude, phase -*/ -CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); - -/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. - -idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . -@note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of -dft or idft explicitly to make these transforms mutually inverse. -@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize -@param src input floating-point real or complex array. -@param dst output array whose size and type depend on the flags. -@param flags operation flags (see dft and #DftFlags). -@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see -the convolution sample in dft description. -*/ -CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); - -/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array. - -The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D -floating-point array: -- Forward Cosine transform of a 1D vector of N elements: - \f[Y = C^{(N)} \cdot X\f] - where - \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f] - and - \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*. -- Inverse Cosine transform of a 1D vector of N elements: - \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f] - (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ ) -- Forward 2D Cosine transform of M x N matrix: - \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f] -- Inverse 2D Cosine transform of M x N matrix: - \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f] - -The function chooses the mode of operation by looking at the flags and size of the input array: -- If (flags & #DCT_INVERSE) == 0, the function does a forward 1D or 2D transform. Otherwise, it - is an inverse 1D or 2D transform. -- If (flags & #DCT_ROWS) != 0, the function performs a 1D transform of each row. -- If the array is a single column or a single row, the function performs a 1D transform. -- If none of the above is true, the function performs a 2D transform. - -@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you -can pad the array when necessary. -Also, the function performance depends very much, and not monotonically, on the array size (see -getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT -of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as: -@code - size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } - N1 = getOptimalDCTSize(N); -@endcode -@param src input floating-point array. -@param dst output array of the same size and type as src . -@param flags transformation flags as a combination of cv::DftFlags (DCT_*) -@sa dft, getOptimalDFTSize, idct -*/ -CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0); - -/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. - -idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). -@param src input floating-point single-channel array. -@param dst output array of the same size and type as src. -@param flags operation flags. -@sa dct, dft, idft, getOptimalDFTSize -*/ -CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0); - -/** @brief Performs the per-element multiplication of two Fourier spectrums. - -The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex -matrices that are results of a real or complex Fourier transform. - -The function, together with dft and idft, may be used to calculate convolution (pass conjB=false ) -or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are -simply multiplied (per element) with an optional conjugation of the second-array elements. When the -arrays are real, they are assumed to be CCS-packed (see dft for details). -@param a first input array. -@param b second input array of the same size and type as src1 . -@param c output array of the same size and type as src1 . -@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that -each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. -@param conjB optional flag that conjugates the second input array before the multiplication (true) -or not (false). -*/ -CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, - int flags, bool conjB = false); - -/** @brief Returns the optimal DFT size for a given vector size. - -DFT performance is not a monotonic function of a vector size. Therefore, when you calculate -convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to -pad the input data with zeros to get a bit larger array that can be transformed much faster than the -original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. -Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) -are also processed quite efficiently. - -The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize -so that the DFT of a vector of size N can be processed efficiently. In the current implementation N -= 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. - -The function returns a negative number if vecsize is too large (very close to INT_MAX ). - -While the function cannot be used directly to estimate the optimal vector size for DCT transform -(since the current DCT implementation supports only even-size vectors), it can be easily processed -as getOptimalDFTSize((vecsize+1)/2)\*2. -@param vecsize vector size. -@sa dft, dct, idft, idct, mulSpectrums -*/ -CV_EXPORTS_W int getOptimalDFTSize(int vecsize); - -/** @brief Returns the default random number generator. - -The function cv::theRNG returns the default random number generator. For each thread, there is a -separate random number generator, so you can use the function safely in multi-thread environments. -If you just need to get a single random number using this generator or initialize an array, you can -use randu or randn instead. But if you are going to generate many random numbers inside a loop, it -is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() . -@sa RNG, randu, randn -*/ -CV_EXPORTS RNG& theRNG(); - -/** @brief Sets state of default random number generator. - -The function cv::setRNGSeed sets state of default random number generator to custom value. -@param seed new state for default random number generator -@sa RNG, randu, randn -*/ -CV_EXPORTS_W void setRNGSeed(int seed); - -/** @brief Generates a single uniformly-distributed random number or an array of random numbers. - -Non-template variant of the function fills the matrix dst with uniformly-distributed -random numbers from the specified range: -\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f] -@param dst output array of random numbers; the array must be pre-allocated. -@param low inclusive lower boundary of the generated random numbers. -@param high exclusive upper boundary of the generated random numbers. -@sa RNG, randn, theRNG -*/ -CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); - -/** @brief Fills the array with normally distributed random numbers. - -The function cv::randn fills the matrix dst with normally distributed random numbers with the specified -mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the -value range of the output array data type. -@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. -@param mean mean value (expectation) of the generated random numbers. -@param stddev standard deviation of the generated random numbers; it can be either a vector (in -which case a diagonal standard deviation matrix is assumed) or a square matrix. -@sa RNG, randu -*/ -CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); - -/** @brief Shuffles the array elements randomly. - -The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and -swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . -@param dst input/output numerical 1D array. -@param iterFactor scale factor that determines the number of random swap operations (see the details -below). -@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used -instead. -@sa RNG, sort -*/ -CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0); - -/** @brief Principal Component Analysis - -The class is used to calculate a special basis for a set of vectors. The -basis will consist of eigenvectors of the covariance matrix calculated -from the input set of vectors. The class %PCA can also transform -vectors to/from the new coordinate space defined by the basis. Usually, -in this new coordinate system, each vector from the original set (and -any linear combination of such vectors) can be quite accurately -approximated by taking its first few components, corresponding to the -eigenvectors of the largest eigenvalues of the covariance matrix. -Geometrically it means that you calculate a projection of the vector to -a subspace formed by a few eigenvectors corresponding to the dominant -eigenvalues of the covariance matrix. And usually such a projection is -very close to the original vector. So, you can represent the original -vector from a high-dimensional space with a much shorter vector -consisting of the projected vector's coordinates in the subspace. Such a -transformation is also known as Karhunen-Loeve Transform, or KLT. -See http://en.wikipedia.org/wiki/Principal_component_analysis - -The sample below is the function that takes two matrices. The first -function stores a set of vectors (a row per vector) that is used to -calculate PCA. The second function stores another "test" set of vectors -(a row per vector). First, these vectors are compressed with PCA, then -reconstructed back, and then the reconstruction error norm is computed -and printed for each vector. : - -@code{.cpp} -using namespace cv; - -PCA compressPCA(const Mat& pcaset, int maxComponents, - const Mat& testset, Mat& compressed) -{ - PCA pca(pcaset, // pass the data - Mat(), // we do not have a pre-computed mean vector, - // so let the PCA engine to compute it - PCA::DATA_AS_ROW, // indicate that the vectors - // are stored as matrix rows - // (use PCA::DATA_AS_COL if the vectors are - // the matrix columns) - maxComponents // specify, how many principal components to retain - ); - // if there is no test data, just return the computed basis, ready-to-use - if( !testset.data ) - return pca; - CV_Assert( testset.cols == pcaset.cols ); - - compressed.create(testset.rows, maxComponents, testset.type()); - - Mat reconstructed; - for( int i = 0; i < testset.rows; i++ ) - { - Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; - // compress the vector, the result will be stored - // in the i-th row of the output matrix - pca.project(vec, coeffs); - // and then reconstruct it - pca.backProject(coeffs, reconstructed); - // and measure the error - printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); - } - return pca; -} -@endcode -@sa calcCovarMatrix, mulTransposed, SVD, dft, dct -*/ -class CV_EXPORTS PCA -{ -public: - enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows - DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns - USE_AVG = 2 //! - }; - - /** @brief default constructor - - The default constructor initializes an empty %PCA structure. The other - constructors initialize the structure and call PCA::operator()(). - */ - PCA(); - - /** @overload - @param data input samples stored as matrix rows or matrix columns. - @param mean optional mean value; if the matrix is empty (@c noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout (PCA::Flags) - @param maxComponents maximum number of components that %PCA should - retain; by default, all the components are retained. - */ - PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0); - - /** @overload - @param data input samples stored as matrix rows or matrix columns. - @param mean optional mean value; if the matrix is empty (noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout (PCA::Flags) - @param retainedVariance Percentage of variance that PCA should retain. - Using this parameter will let the PCA decided how many components to - retain but it will always keep at least 2. - */ - PCA(InputArray data, InputArray mean, int flags, double retainedVariance); - - /** @brief performs %PCA - - The operator performs %PCA of the supplied dataset. It is safe to reuse - the same PCA structure for multiple datasets. That is, if the structure - has been previously used with another dataset, the existing internal - data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref - mean are allocated and computed. - - The computed @ref eigenvalues are sorted from the largest to the smallest and - the corresponding @ref eigenvectors are stored as eigenvectors rows. - - @param data input samples stored as the matrix rows or as the matrix - columns. - @param mean optional mean value; if the matrix is empty (noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout. (Flags) - @param maxComponents maximum number of components that PCA should - retain; by default, all the components are retained. - */ - PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0); - - /** @overload - @param data input samples stored as the matrix rows or as the matrix - columns. - @param mean optional mean value; if the matrix is empty (noArray()), - the mean is computed from the data. - @param flags operation flags; currently the parameter is only used to - specify the data layout. (PCA::Flags) - @param retainedVariance Percentage of variance that %PCA should retain. - Using this parameter will let the %PCA decided how many components to - retain but it will always keep at least 2. - */ - PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance); - - /** @brief Projects vector(s) to the principal component subspace. - - The methods project one or more vectors to the principal component - subspace, where each vector projection is represented by coefficients in - the principal component basis. The first form of the method returns the - matrix that the second form writes to the result. So the first form can - be used as a part of expression while the second form can be more - efficient in a processing loop. - @param vec input vector(s); must have the same dimensionality and the - same layout as the input data used at %PCA phase, that is, if - DATA_AS_ROW are specified, then `vec.cols==data.cols` - (vector dimensionality) and `vec.rows` is the number of vectors to - project, and the same is true for the PCA::DATA_AS_COL case. - */ - Mat project(InputArray vec) const; - - /** @overload - @param vec input vector(s); must have the same dimensionality and the - same layout as the input data used at PCA phase, that is, if - DATA_AS_ROW are specified, then `vec.cols==data.cols` - (vector dimensionality) and `vec.rows` is the number of vectors to - project, and the same is true for the PCA::DATA_AS_COL case. - @param result output vectors; in case of PCA::DATA_AS_COL, the - output matrix has as many columns as the number of input vectors, this - means that `result.cols==vec.cols` and the number of rows match the - number of principal components (for example, `maxComponents` parameter - passed to the constructor). - */ - void project(InputArray vec, OutputArray result) const; - - /** @brief Reconstructs vectors from their PC projections. - - The methods are inverse operations to PCA::project. They take PC - coordinates of projected vectors and reconstruct the original vectors. - Unless all the principal components have been retained, the - reconstructed vectors are different from the originals. But typically, - the difference is small if the number of components is large enough (but - still much smaller than the original vector dimensionality). As a - result, PCA is used. - @param vec coordinates of the vectors in the principal component - subspace, the layout and size are the same as of PCA::project output - vectors. - */ - Mat backProject(InputArray vec) const; - - /** @overload - @param vec coordinates of the vectors in the principal component - subspace, the layout and size are the same as of PCA::project output - vectors. - @param result reconstructed vectors; the layout and size are the same as - of PCA::project input vectors. - */ - void backProject(InputArray vec, OutputArray result) const; - - /** @brief write PCA objects - - Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage - */ - void write(FileStorage& fs) const; - - /** @brief load PCA objects - - Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode - */ - void read(const FileNode& fn); - - Mat eigenvectors; //!< eigenvectors of the covariation matrix - Mat eigenvalues; //!< eigenvalues of the covariation matrix - Mat mean; //!< mean value subtracted before the projection and added after the back projection -}; - -/** @example samples/cpp/pca.cpp -An example using %PCA for dimensionality reduction while maintaining an amount of variance -*/ - -/** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp -Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details -*/ - -/** -@brief Linear Discriminant Analysis -@todo document this class -*/ -class CV_EXPORTS LDA -{ -public: - /** @brief constructor - Initializes a LDA with num_components (default 0). - */ - explicit LDA(int num_components = 0); - - /** Initializes and performs a Discriminant Analysis with Fisher's - Optimization Criterion on given data in src and corresponding labels - in labels. If 0 (or less) number of components are given, they are - automatically determined for given data in computation. - */ - LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0); - - /** Serializes this object to a given filename. - */ - void save(const String& filename) const; - - /** Deserializes this object from a given filename. - */ - void load(const String& filename); - - /** Serializes this object to a given cv::FileStorage. - */ - void save(FileStorage& fs) const; - - /** Deserializes this object from a given cv::FileStorage. - */ - void load(const FileStorage& node); - - /** destructor - */ - ~LDA(); - - /** Compute the discriminants for data in src (row aligned) and labels. - */ - void compute(InputArrayOfArrays src, InputArray labels); - - /** Projects samples into the LDA subspace. - src may be one or more row aligned samples. - */ - Mat project(InputArray src); - - /** Reconstructs projections from the LDA subspace. - src may be one or more row aligned projections. - */ - Mat reconstruct(InputArray src); - - /** Returns the eigenvectors of this LDA. - */ - Mat eigenvectors() const { return _eigenvectors; } - - /** Returns the eigenvalues of this LDA. - */ - Mat eigenvalues() const { return _eigenvalues; } - - static Mat subspaceProject(InputArray W, InputArray mean, InputArray src); - static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); - -protected: - int _num_components; - Mat _eigenvectors; - Mat _eigenvalues; - void lda(InputArrayOfArrays src, InputArray labels); -}; - -/** @brief Singular Value Decomposition - -Class for computing Singular Value Decomposition of a floating-point -matrix. The Singular Value Decomposition is used to solve least-square -problems, under-determined linear systems, invert matrices, compute -condition numbers, and so on. - -If you want to compute a condition number of a matrix or an absolute value of -its determinant, you do not need `u` and `vt`. You can pass -flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u -and vt must be computed, which is not necessary most of the time. - -@sa invert, solve, eigen, determinant -*/ -class CV_EXPORTS SVD -{ -public: - enum Flags { - /** allow the algorithm to modify the decomposed matrix; it can save space and speed up - processing. currently ignored. */ - MODIFY_A = 1, - /** indicates that only a vector of singular values `w` is to be processed, while u and vt - will be set to empty matrices */ - NO_UV = 2, - /** when the matrix is not square, by default the algorithm produces u and vt matrices of - sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is - specified, u and vt will be full-size square orthogonal matrices.*/ - FULL_UV = 4 - }; - - /** @brief the default constructor - - initializes an empty SVD structure - */ - SVD(); - - /** @overload - initializes an empty SVD structure and then calls SVD::operator() - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param flags operation flags (SVD::Flags) - */ - SVD( InputArray src, int flags = 0 ); - - /** @brief the operator that performs SVD. The previously allocated u, w and vt are released. - - The operator performs the singular value decomposition of the supplied - matrix. The u,`vt` , and the vector of singular values w are stored in - the structure. The same SVD structure can be reused many times with - different matrices. Each time, if needed, the previous u,`vt` , and w - are reclaimed and the new matrices are created, which is all handled by - Mat::create. - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param flags operation flags (SVD::Flags) - */ - SVD& operator ()( InputArray src, int flags = 0 ); - - /** @brief decomposes matrix and stores the results to user-provided matrices - - The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor - and SVD::operator(), they store the results to the user-provided - matrices: - - @code{.cpp} - Mat A, w, u, vt; - SVD::compute(A, w, u, vt); - @endcode - - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param w calculated singular values - @param u calculated left singular vectors - @param vt transposed matrix of right singular vectors - @param flags operation flags - see SVD::Flags. - */ - static void compute( InputArray src, OutputArray w, - OutputArray u, OutputArray vt, int flags = 0 ); - - /** @overload - computes singular values of a matrix - @param src decomposed matrix. The depth has to be CV_32F or CV_64F. - @param w calculated singular values - @param flags operation flags - see SVD::Flags. - */ - static void compute( InputArray src, OutputArray w, int flags = 0 ); - - /** @brief performs back substitution - */ - static void backSubst( InputArray w, InputArray u, - InputArray vt, InputArray rhs, - OutputArray dst ); - - /** @brief solves an under-determined singular linear system - - The method finds a unit-length solution x of a singular linear system - A\*x = 0. Depending on the rank of A, there can be no solutions, a - single solution or an infinite number of solutions. In general, the - algorithm solves the following problem: - \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f] - @param src left-hand-side matrix. - @param dst found solution. - */ - static void solveZ( InputArray src, OutputArray dst ); - - /** @brief performs a singular value back substitution. - - The method calculates a back substitution for the specified right-hand - side: - - \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f] - - Using this technique you can either get a very accurate solution of the - convenient linear system, or the best (in the least-squares terms) - pseudo-solution of an overdetermined linear system. - - @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to - be solved, where A has been previously decomposed. - - @param dst found solution of the system. - - @note Explicit SVD with the further back substitution only makes sense - if you need to solve many linear systems with the same left-hand side - (for example, src ). If all you need is to solve a single system - (possibly with multiple rhs immediately available), simply call solve - add pass #DECOMP_SVD there. It does absolutely the same thing. - */ - void backSubst( InputArray rhs, OutputArray dst ) const; - - /** @todo document */ - template static - void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); - - /** @todo document */ - template static - void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); - - /** @todo document */ - template static - void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); - - Mat u, w, vt; -}; - -/** @brief Random Number Generator - -Random number generator. It encapsulates the state (currently, a 64-bit -integer) and has methods to return scalar random values and to fill -arrays with random values. Currently it supports uniform and Gaussian -(normal) distributions. The generator uses Multiply-With-Carry -algorithm, introduced by G. Marsaglia ( - ). -Gaussian-distribution random numbers are generated using the Ziggurat -algorithm ( ), -introduced by G. Marsaglia and W. W. Tsang. -*/ -class CV_EXPORTS RNG -{ -public: - enum { UNIFORM = 0, - NORMAL = 1 - }; - - /** @brief constructor - - These are the RNG constructors. The first form sets the state to some - pre-defined value, equal to 2\*\*32-1 in the current implementation. The - second form sets the state to the specified value. If you passed state=0 - , the constructor uses the above default value instead to avoid the - singular random number sequence, consisting of all zeros. - */ - RNG(); - /** @overload - @param state 64-bit value used to initialize the RNG. - */ - RNG(uint64 state); - /**The method updates the state using the MWC algorithm and returns the - next 32-bit random number.*/ - unsigned next(); - - /**Each of the methods updates the state using the MWC algorithm and - returns the next random number of the specified type. In case of integer - types, the returned number is from the available value range for the - specified type. In case of floating-point types, the returned value is - from [0,1) range. - */ - operator uchar(); - /** @overload */ - operator schar(); - /** @overload */ - operator ushort(); - /** @overload */ - operator short(); - /** @overload */ - operator unsigned(); - /** @overload */ - operator int(); - /** @overload */ - operator float(); - /** @overload */ - operator double(); - - /** @brief returns a random integer sampled uniformly from [0, N). - - The methods transform the state using the MWC algorithm and return the - next random number. The first form is equivalent to RNG::next . The - second form returns the random number modulo N, which means that the - result is in the range [0, N) . - */ - unsigned operator ()(); - /** @overload - @param N upper non-inclusive boundary of the returned random number. - */ - unsigned operator ()(unsigned N); - - /** @brief returns uniformly distributed integer random number from [a,b) range - - The methods transform the state using the MWC algorithm and return the - next uniformly-distributed random number of the specified type, deduced - from the input parameter type, from the range [a, b) . There is a nuance - illustrated by the following sample: - - @code{.cpp} - RNG rng; - - // always produces 0 - double a = rng.uniform(0, 1); - - // produces double from [0, 1) - double a1 = rng.uniform((double)0, (double)1); - - // produces float from [0, 1) - float b = rng.uniform(0.f, 1.f); - - // produces double from [0, 1) - double c = rng.uniform(0., 1.); - - // may cause compiler error because of ambiguity: - // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)? - double d = rng.uniform(0, 0.999999); - @endcode - - The compiler does not take into account the type of the variable to - which you assign the result of RNG::uniform . The only thing that - matters to the compiler is the type of a and b parameters. So, if you - want a floating-point random number, but the range boundaries are - integer numbers, either put dots in the end, if they are constants, or - use explicit type cast operators, as in the a1 initialization above. - @param a lower inclusive boundary of the returned random number. - @param b upper non-inclusive boundary of the returned random number. - */ - int uniform(int a, int b); - /** @overload */ - float uniform(float a, float b); - /** @overload */ - double uniform(double a, double b); - - /** @brief Fills arrays with random numbers. - - @param mat 2D or N-dimensional matrix; currently matrices with more than - 4 channels are not supported by the methods, use Mat::reshape as a - possible workaround. - @param distType distribution type, RNG::UNIFORM or RNG::NORMAL. - @param a first distribution parameter; in case of the uniform - distribution, this is an inclusive lower boundary, in case of the normal - distribution, this is a mean value. - @param b second distribution parameter; in case of the uniform - distribution, this is a non-inclusive upper boundary, in case of the - normal distribution, this is a standard deviation (diagonal of the - standard deviation matrix or the full standard deviation matrix). - @param saturateRange pre-saturation flag; for uniform distribution only; - if true, the method will first convert a and b to the acceptable value - range (according to the mat datatype) and then will generate uniformly - distributed random numbers within the range [saturate(a), saturate(b)), - if saturateRange=false, the method will generate uniformly distributed - random numbers in the original range [a, b) and then will saturate them, - it means, for example, that - theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely - produce array mostly filled with 0's and 255's, since the range (0, 255) - is significantly smaller than [-DBL_MAX, DBL_MAX). - - Each of the methods fills the matrix with the random values from the - specified distribution. As the new numbers are generated, the RNG state - is updated accordingly. In case of multiple-channel images, every - channel is filled independently, which means that RNG cannot generate - samples from the multi-dimensional Gaussian distribution with - non-diagonal covariance matrix directly. To do that, the method - generates samples from multi-dimensional standard Gaussian distribution - with zero mean and identity covariation matrix, and then transforms them - using transform to get samples from the specified Gaussian distribution. - */ - void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false ); - - /** @brief Returns the next random number sampled from the Gaussian distribution - @param sigma standard deviation of the distribution. - - The method transforms the state using the MWC algorithm and returns the - next random number from the Gaussian distribution N(0,sigma) . That is, - the mean value of the returned random numbers is zero and the standard - deviation is the specified sigma . - */ - double gaussian(double sigma); - - uint64 state; - - bool operator ==(const RNG& other) const; -}; - -/** @brief Mersenne Twister random number generator - -Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c -@todo document -*/ -class CV_EXPORTS RNG_MT19937 -{ -public: - RNG_MT19937(); - RNG_MT19937(unsigned s); - void seed(unsigned s); - - unsigned next(); - - operator int(); - operator unsigned(); - operator float(); - operator double(); - - unsigned operator ()(unsigned N); - unsigned operator ()(); - - /** @brief returns uniformly distributed integer random number from [a,b) range*/ - int uniform(int a, int b); - /** @brief returns uniformly distributed floating-point random number from [a,b) range*/ - float uniform(float a, float b); - /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/ - double uniform(double a, double b); - -private: - enum PeriodParameters {N = 624, M = 397}; - unsigned state[N]; - int mti; -}; - -//! @} core_array - -//! @addtogroup core_cluster -//! @{ - -//! k-means flags -enum KmeansFlags { - /** Select random initial centers in each attempt.*/ - KMEANS_RANDOM_CENTERS = 0, - /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/ - KMEANS_PP_CENTERS = 2, - /** During the first (and possibly the only) attempt, use the - user-supplied labels instead of computing them from the initial centers. For the second and - further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag - to specify the exact method.*/ - KMEANS_USE_INITIAL_LABELS = 1 -}; - -/** @example samples/cpp/kmeans.cpp -An example on k-means clustering -*/ - -/** @brief Finds centers of clusters and groups input samples around the clusters. - -The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters -and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a -0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix. - -@note -- (Python) An example on k-means clustering can be found at - opencv_source_code/samples/python/kmeans.py -@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. -Examples of this array can be: -- Mat points(count, 2, CV_32F); -- Mat points(count, 1, CV_32FC2); -- Mat points(1, count, CV_32FC2); -- std::vector\ points(sampleCount); -@param K Number of clusters to split the set by. -@param bestLabels Input/output integer array that stores the cluster indices for every sample. -@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or -the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster -centers moves by less than criteria.epsilon on some iteration, the algorithm stops. -@param attempts Flag to specify the number of times the algorithm is executed using different -initial labellings. The algorithm returns the labels that yield the best compactness (see the last -function parameter). -@param flags Flag that can take values of cv::KmeansFlags -@param centers Output matrix of the cluster centers, one row per each cluster center. -@return The function returns the compactness measure that is computed as -\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] -after every attempt. The best (minimum) value is chosen and the corresponding labels and the -compactness value are returned by the function. Basically, you can use only the core of the -function, set the number of attempts to 1, initialize labels each time using a custom algorithm, -pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best -(most-compact) clustering. -*/ -CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels, - TermCriteria criteria, int attempts, - int flags, OutputArray centers = noArray() ); - -//! @} core_cluster - -//! @addtogroup core_basic -//! @{ - -/////////////////////////////// Formatted output of cv::Mat /////////////////////////// - -/** @todo document */ -class CV_EXPORTS Formatted -{ -public: - virtual const char* next() = 0; - virtual void reset() = 0; - virtual ~Formatted(); -}; - -/** @todo document */ -class CV_EXPORTS Formatter -{ -public: - enum FormatType { - FMT_DEFAULT = 0, - FMT_MATLAB = 1, - FMT_CSV = 2, - FMT_PYTHON = 3, - FMT_NUMPY = 4, - FMT_C = 5 - }; - - virtual ~Formatter(); - - virtual Ptr format(const Mat& mtx) const = 0; - - virtual void set16fPrecision(int p = 4) = 0; - virtual void set32fPrecision(int p = 8) = 0; - virtual void set64fPrecision(int p = 16) = 0; - virtual void setMultiline(bool ml = true) = 0; - - static Ptr get(Formatter::FormatType fmt = FMT_DEFAULT); - -}; - -static inline -String& operator << (String& out, Ptr fmtd) -{ - fmtd->reset(); - for(const char* str = fmtd->next(); str; str = fmtd->next()) - out += cv::String(str); - return out; -} - -static inline -String& operator << (String& out, const Mat& mtx) -{ - return out << Formatter::get()->format(mtx); -} - -//////////////////////////////////////// Algorithm //////////////////////////////////// - -class CV_EXPORTS Algorithm; - -template struct ParamType {}; - - -/** @brief This is a base class for all more or less complex algorithms in OpenCV - -especially for classes of algorithms, for which there can be multiple implementations. The examples -are stereo correspondence (for which there are algorithms like block matching, semi-global block -matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians -models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck -etc.). - -Here is example of SimpleBlobDetector use in your application via Algorithm interface: -@snippet snippets/core_various.cpp Algorithm -*/ -class CV_EXPORTS_W Algorithm -{ -public: - Algorithm(); - virtual ~Algorithm(); - - /** @brief Clears the algorithm state - */ - CV_WRAP virtual void clear() {} - - /** @brief Stores algorithm parameters in a file storage - */ - CV_WRAP virtual void write(FileStorage& fs) const { CV_UNUSED(fs); } - - /** - * @overload - */ - CV_WRAP void write(FileStorage& fs, const String& name) const; -#if CV_VERSION_MAJOR < 5 - /** @deprecated */ - void write(const Ptr& fs, const String& name = String()) const; -#endif - - /** @brief Reads algorithm parameters from a file storage - */ - CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); } - - /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read - */ - CV_WRAP virtual bool empty() const { return false; } - - /** @brief Reads algorithm from the file node - - This is static template method of Algorithm. It's usage is following (in the case of SVM): - @code - cv::FileStorage fsRead("example.xml", FileStorage::READ); - Ptr svm = Algorithm::read(fsRead.root()); - @endcode - In order to make this method work, the derived class must overwrite Algorithm::read(const - FileNode& fn) and also have static create() method without parameters - (or with all the optional parameters) - */ - template static Ptr<_Tp> read(const FileNode& fn) - { - Ptr<_Tp> obj = _Tp::create(); - obj->read(fn); - return !obj->empty() ? obj : Ptr<_Tp>(); - } - - /** @brief Loads algorithm from the file - - @param filename Name of the file to read. - @param objname The optional name of the node to read (if empty, the first top-level node will be used) - - This is static template method of Algorithm. It's usage is following (in the case of SVM): - @code - Ptr svm = Algorithm::load("my_svm_model.xml"); - @endcode - In order to make this method work, the derived class must overwrite Algorithm::read(const - FileNode& fn). - */ - template static Ptr<_Tp> load(const String& filename, const String& objname=String()) - { - FileStorage fs(filename, FileStorage::READ); - CV_Assert(fs.isOpened()); - FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; - if (fn.empty()) return Ptr<_Tp>(); - Ptr<_Tp> obj = _Tp::create(); - obj->read(fn); - return !obj->empty() ? obj : Ptr<_Tp>(); - } - - /** @brief Loads algorithm from a String - - @param strModel The string variable containing the model you want to load. - @param objname The optional name of the node to read (if empty, the first top-level node will be used) - - This is static template method of Algorithm. It's usage is following (in the case of SVM): - @code - Ptr svm = Algorithm::loadFromString(myStringModel); - @endcode - */ - template static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String()) - { - FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY); - FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; - Ptr<_Tp> obj = _Tp::create(); - obj->read(fn); - return !obj->empty() ? obj : Ptr<_Tp>(); - } - - /** Saves the algorithm to a file. - In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */ - CV_WRAP virtual void save(const String& filename) const; - - /** Returns the algorithm string identifier. - This string is used as top level xml/yml node tag when the object is saved to a file or string. */ - CV_WRAP virtual String getDefaultName() const; - -protected: - void writeFormat(FileStorage& fs) const; -}; - -enum struct Param { - INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, - UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12 -}; - - - -template<> struct ParamType -{ - typedef bool const_param_type; - typedef bool member_type; - - static const Param type = Param::BOOLEAN; -}; - -template<> struct ParamType -{ - typedef int const_param_type; - typedef int member_type; - - static const Param type = Param::INT; -}; - -template<> struct ParamType -{ - typedef double const_param_type; - typedef double member_type; - - static const Param type = Param::REAL; -}; - -template<> struct ParamType -{ - typedef const String& const_param_type; - typedef String member_type; - - static const Param type = Param::STRING; -}; - -template<> struct ParamType -{ - typedef const Mat& const_param_type; - typedef Mat member_type; - - static const Param type = Param::MAT; -}; - -template<> struct ParamType > -{ - typedef const std::vector& const_param_type; - typedef std::vector member_type; - - static const Param type = Param::MAT_VECTOR; -}; - -template<> struct ParamType -{ - typedef const Ptr& const_param_type; - typedef Ptr member_type; - - static const Param type = Param::ALGORITHM; -}; - -template<> struct ParamType -{ - typedef float const_param_type; - typedef float member_type; - - static const Param type = Param::FLOAT; -}; - -template<> struct ParamType -{ - typedef unsigned const_param_type; - typedef unsigned member_type; - - static const Param type = Param::UNSIGNED_INT; -}; - -template<> struct ParamType -{ - typedef uint64 const_param_type; - typedef uint64 member_type; - - static const Param type = Param::UINT64; -}; - -template<> struct ParamType -{ - typedef uchar const_param_type; - typedef uchar member_type; - - static const Param type = Param::UCHAR; -}; - -template<> struct ParamType -{ - typedef const Scalar& const_param_type; - typedef Scalar member_type; - - static const Param type = Param::SCALAR; -}; - -template -struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type> -{ - typedef typename std::underlying_type<_Tp>::type const_param_type; - typedef typename std::underlying_type<_Tp>::type member_type; - - static const Param type = Param::INT; -}; - -//! @} core_basic - -} //namespace cv - -#include "opencv2/core/operations.hpp" -#include "opencv2/core/cvstd.inl.hpp" -#include "opencv2/core/utility.hpp" -#include "opencv2/core/optim.hpp" -#include "opencv2/core/ovx.hpp" - -#endif /*OPENCV_CORE_HPP*/ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2015, Intel Corporation, all rights reserved. +// Copyright (C) 2009-2011, Willow Garage Inc., all rights reserved. +// Copyright (C) 2015, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_HPP +#define OPENCV_CORE_HPP + +#ifndef __cplusplus +# error core.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/base.hpp" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/traits.hpp" +#include "opencv2/core/matx.hpp" +#include "opencv2/core/types.hpp" +#include "opencv2/core/mat.hpp" +#include "opencv2/core/persistence.hpp" + +/** +@defgroup core Core functionality + +The Core module is the backbone of OpenCV, offering fundamental data structures, matrix operations, +and utility functions that other modules depend on. It’s essential for handling image data, +performing mathematical computations, and managing memory efficiently within the OpenCV ecosystem. + +@{ + @defgroup core_basic Basic structures + @defgroup core_array Operations on arrays + @defgroup core_async Asynchronous API + @defgroup core_xml XML/YAML/JSON Persistence + @defgroup core_cluster Clustering + @defgroup core_utils Utility and system functions and macros + @{ + @defgroup core_logging Logging facilities + @defgroup core_utils_sse SSE utilities + @defgroup core_utils_neon NEON utilities + @defgroup core_utils_vsx VSX utilities + @defgroup core_utils_softfloat Softfloat support + @defgroup core_utils_samples Utility functions for OpenCV samples + @} + @defgroup core_opengl OpenGL interoperability + @defgroup core_optim Optimization Algorithms + @defgroup core_directx DirectX interoperability + @defgroup core_eigen Eigen support + @defgroup core_opencl OpenCL support + @defgroup core_va_intel Intel VA-API/OpenCL (CL-VA) interoperability + @defgroup core_hal Hardware Acceleration Layer + @{ + @defgroup core_hal_functions Functions + @defgroup core_hal_interface Interface + @defgroup core_hal_intrin Universal intrinsics + @{ + @defgroup core_hal_intrin_impl Private implementation helpers + @} + @defgroup core_lowlevel_api Low-level API for external libraries / plugins + @} + @defgroup core_parallel Parallel Processing + @{ + @defgroup core_parallel_backend Parallel backends API + @} + @defgroup core_quaternion Quaternion +@} + */ + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +/*! @brief Class passed to an error. + +This class encapsulates all or almost all necessary +information about the error happened in the program. The exception is +usually constructed and thrown implicitly via CV_Error and CV_Error_ macros. +@see error + */ +class CV_EXPORTS Exception : public std::exception +{ +public: + /*! + Default constructor + */ + Exception(); + /*! + Full constructor. Normally the constructor is not called explicitly. + Instead, the macros CV_Error(), CV_Error_() and CV_Assert() are used. + */ + Exception(int _code, const String& _err, const String& _func, const String& _file, int _line); + virtual ~Exception() CV_NOEXCEPT; + + /*! + \return the error description and the context as a text string. + */ + virtual const char *what() const CV_NOEXCEPT CV_OVERRIDE; + void formatMessage(); + + String msg; ///< the formatted error message + + int code; ///< error code @see CVStatus + String err; ///< error description + String func; ///< function name. Available only when the compiler supports getting it + String file; ///< source file name where the error has occurred + int line; ///< line number in the source file where the error has occurred +}; + +/*! @brief Signals an error and raises the exception. + +By default the function prints information about the error to stderr, +then it either stops if cv::setBreakOnError() had been called before or raises the exception. +It is possible to alternate error processing by using #redirectError(). +@param exc the exception raisen. +@deprecated drop this version + */ +CV_EXPORTS CV_NORETURN void error(const Exception& exc); + +enum SortFlags { SORT_EVERY_ROW = 0, //!< each matrix row is sorted independently + SORT_EVERY_COLUMN = 1, //!< each matrix column is sorted + //!< independently; this flag and the previous one are + //!< mutually exclusive. + SORT_ASCENDING = 0, //!< each matrix row is sorted in the ascending + //!< order. + SORT_DESCENDING = 16 //!< each matrix row is sorted in the + //!< descending order; this flag and the previous one are also + //!< mutually exclusive. + }; + +//! @} core_utils + +//! @addtogroup core_array +//! @{ + +//! Covariation flags +enum CovarFlags { + /** The output covariance matrix is calculated as: + \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...],\f] + The covariance matrix will be nsamples x nsamples. Such an unusual covariance matrix is used + for fast PCA of a set of very large vectors (see, for example, the EigenFaces technique for + face recognition). Eigenvalues of this "scrambled" matrix match the eigenvalues of the true + covariance matrix. The "true" eigenvectors can be easily calculated from the eigenvectors of + the "scrambled" covariance matrix. */ + COVAR_SCRAMBLED = 0, + /**The output covariance matrix is calculated as: + \f[\texttt{scale} \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...] \cdot [ \texttt{vects} [0]- \texttt{mean} , \texttt{vects} [1]- \texttt{mean} ,...]^T,\f] + covar will be a square matrix of the same size as the total number of elements in each input + vector. One and only one of #COVAR_SCRAMBLED and #COVAR_NORMAL must be specified.*/ + COVAR_NORMAL = 1, + /** If the flag is specified, the function does not calculate mean from + the input vectors but, instead, uses the passed mean vector. This is useful if mean has been + pre-calculated or known in advance, or if the covariance matrix is calculated by parts. In + this case, mean is not a mean vector of the input sub-set of vectors but rather the mean + vector of the whole set.*/ + COVAR_USE_AVG = 2, + /** If the flag is specified, the covariance matrix is scaled. In the + "normal" mode, scale is 1./nsamples . In the "scrambled" mode, scale is the reciprocal of the + total number of elements in each input vector. By default (if the flag is not specified), the + covariance matrix is not scaled ( scale=1 ).*/ + COVAR_SCALE = 4, + /** If the flag is + specified, all the input vectors are stored as rows of the samples matrix. mean should be a + single-row vector in this case.*/ + COVAR_ROWS = 8, + /** If the flag is + specified, all the input vectors are stored as columns of the samples matrix. mean should be a + single-column vector in this case.*/ + COVAR_COLS = 16 +}; + +enum ReduceTypes { REDUCE_SUM = 0, //!< the output is the sum of all rows/columns of the matrix. + REDUCE_AVG = 1, //!< the output is the mean vector of all rows/columns of the matrix. + REDUCE_MAX = 2, //!< the output is the maximum (column/row-wise) of all rows/columns of the matrix. + REDUCE_MIN = 3, //!< the output is the minimum (column/row-wise) of all rows/columns of the matrix. + REDUCE_SUM2 = 4 //!< the output is the sum of all squared rows/columns of the matrix. + }; + +/** @brief Swaps two matrices +*/ +CV_EXPORTS void swap(Mat& a, Mat& b); +/** @overload */ +CV_EXPORTS void swap( UMat& a, UMat& b ); + +/** @brief Computes the source location of an extrapolated pixel. + +The function computes and returns the coordinate of a donor pixel corresponding to the specified +extrapolated pixel when using the specified extrapolation border mode. For example, if you use +cv::BORDER_WRAP mode in the horizontal direction, cv::BORDER_REFLECT_101 in the vertical direction and +want to compute value of the "virtual" pixel Point(-5, 100) in a floating-point image img, it +looks like: +@code{.cpp} + float val = img.at(borderInterpolate(100, img.rows, cv::BORDER_REFLECT_101), + borderInterpolate(-5, img.cols, cv::BORDER_WRAP)); +@endcode +Normally, the function is not called directly. It is used inside filtering functions and also in +copyMakeBorder. +@param p 0-based coordinate of the extrapolated pixel along one of the axes, likely \<0 or \>= len +@param len Length of the array along the corresponding axis. +@param borderType Border type, one of the #BorderTypes, except for #BORDER_TRANSPARENT and +#BORDER_ISOLATED. When borderType==#BORDER_CONSTANT, the function always returns -1, regardless +of p and len. + +@sa copyMakeBorder +*/ +CV_EXPORTS_W int borderInterpolate(int p, int len, int borderType); + +/** @example samples/cpp/tutorial_code/ImgTrans/copyMakeBorder_demo.cpp +An example using copyMakeBorder function. +Check @ref tutorial_copyMakeBorder "the corresponding tutorial" for more details +*/ + +/** @brief Forms a border around an image. + +The function copies the source image into the middle of the destination image. The areas to the +left, to the right, above and below the copied source image will be filled with extrapolated +pixels. This is not what filtering functions based on it do (they extrapolate pixels on-fly), but +what other more complex functions, including your own, may do to simplify image boundary handling. + +The function supports the mode when src is already in the middle of dst . In this case, the +function does not copy src itself but simply constructs the border, for example: + +@code{.cpp} + // let border be the same in all directions + int border=2; + // constructs a larger image to fit both the image and the border + Mat gray_buf(rgb.rows + border*2, rgb.cols + border*2, rgb.depth()); + // select the middle part of it w/o copying data + Mat gray(gray_canvas, Rect(border, border, rgb.cols, rgb.rows)); + // convert image from RGB to grayscale + cvtColor(rgb, gray, COLOR_RGB2GRAY); + // form a border in-place + copyMakeBorder(gray, gray_buf, border, border, + border, border, BORDER_REPLICATE); + // now do some custom filtering ... + ... +@endcode +@note When the source image is a part (ROI) of a bigger image, the function will try to use the +pixels outside of the ROI to form a border. To disable this feature and always do extrapolation, as +if src was not a ROI, use borderType | #BORDER_ISOLATED. + +@param src Source image. +@param dst Destination image of the same type as src and the size Size(src.cols+left+right, +src.rows+top+bottom) . +@param top the top pixels +@param bottom the bottom pixels +@param left the left pixels +@param right Parameter specifying how many pixels in each direction from the source image rectangle +to extrapolate. For example, top=1, bottom=1, left=1, right=1 mean that 1 pixel-wide border needs +to be built. +@param borderType Border type. See borderInterpolate for details. +@param value Border value if borderType==BORDER_CONSTANT . + +@sa borderInterpolate +*/ +CV_EXPORTS_W void copyMakeBorder(InputArray src, OutputArray dst, + int top, int bottom, int left, int right, + int borderType, const Scalar& value = Scalar() ); + +/** @brief Calculates the per-element sum of two arrays or an array and a scalar. + +The function add calculates: +- Sum of two arrays when both input arrays have the same size and the same number of channels: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] +- Sum of an array and a scalar when src2 is constructed from Scalar or has the same number of +elements as `src1.channels()`: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] +- Sum of a scalar and an array when src1 is constructed from Scalar or has the same number of +elements as `src2.channels()`: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} + \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] +where `I` is a multi-dimensional index of array elements. In case of multi-channel arrays, each +channel is processed independently. + +The first function in the list above can be replaced with matrix expressions: +@code{.cpp} + dst = src1 + src2; + dst += src1; // equivalent to add(dst, src1, dst); +@endcode +The input arrays and the output array can all have the same or different depths. For example, you +can add a 16-bit unsigned array to a 8-bit signed array and store the sum as a 32-bit +floating-point array. Depth of the output array is determined by the dtype parameter. In the second +and third cases above, as well as in the first case, when src1.depth() == src2.depth(), dtype can +be set to the default -1. In this case, the output array will have the same depth as the input +array, be it src1, src2 or both. +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`add(src,X)` means `add(src,(X,X,X,X))`. +`add(src,(X,))` means `add(src,(X,0,0,0))`. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and number of channels as the input array(s); the +depth is defined by dtype or src1/src2. +@param mask optional operation mask - 8-bit single channel array, that specifies elements of the +output array to be changed. +@param dtype optional depth of the output array (see the discussion below). +@sa subtract, addWeighted, scaleAdd, Mat::convertTo +*/ +CV_EXPORTS_W void add(InputArray src1, InputArray src2, OutputArray dst, + InputArray mask = noArray(), int dtype = -1); + +/** @brief Calculates the per-element difference between two arrays or array and a scalar. + +The function subtract calculates: +- Difference between two arrays, when both input arrays have the same size and the same number of +channels: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] +- Difference between an array and a scalar, when src2 is constructed from Scalar or has the same +number of elements as `src1.channels()`: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) - \texttt{src2} ) \quad \texttt{if mask}(I) \ne0\f] +- Difference between a scalar and an array, when src1 is constructed from Scalar or has the same +number of elements as `src2.channels()`: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1} - \texttt{src2}(I) ) \quad \texttt{if mask}(I) \ne0\f] +- The reverse difference between a scalar and an array in the case of `SubRS`: + \f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src2} - \texttt{src1}(I) ) \quad \texttt{if mask}(I) \ne0\f] +where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each +channel is processed independently. + +The first function in the list above can be replaced with matrix expressions: +@code{.cpp} + dst = src1 - src2; + dst -= src1; // equivalent to subtract(dst, src1, dst); +@endcode +The input arrays and the output array can all have the same or different depths. For example, you +can subtract to 8-bit unsigned arrays and store the difference in a 16-bit signed array. Depth of +the output array is determined by dtype parameter. In the second and third cases above, as well as +in the first case, when src1.depth() == src2.depth(), dtype can be set to the default -1. In this +case the output array will have the same depth as the input array, be it src1, src2 or both. +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`subtract(src,X)` means `subtract(src,(X,X,X,X))`. +`subtract(src,(X,))` means `subtract(src,(X,0,0,0))`. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array of the same size and the same number of channels as the input array. +@param mask optional operation mask; this is an 8-bit single channel array that specifies elements +of the output array to be changed. +@param dtype optional depth of the output array +@sa add, addWeighted, scaleAdd, Mat::convertTo + */ +CV_EXPORTS_W void subtract(InputArray src1, InputArray src2, OutputArray dst, + InputArray mask = noArray(), int dtype = -1); + + +/** @brief Calculates the per-element scaled product of two arrays. + +The function multiply calculates the per-element product of two arrays: + +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] + +There is also a @ref MatrixExpressions -friendly variant of the first function. See Mat::mul . + +For a not-per-element matrix product, see gemm . + +@note Saturation is not applied when the output array has the depth +CV_32S. You may even get result of an incorrect sign in the case of +overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`multiply(src,X)` means `multiply(src,(X,X,X,X))`. +`multiply(src,(X,))` means `multiply(src,(X,0,0,0))`. +@param src1 first input array. +@param src2 second input array of the same size and the same type as src1. +@param dst output array of the same size and type as src1. +@param scale optional scale factor. +@param dtype optional depth of the output array +@sa add, subtract, divide, scaleAdd, addWeighted, accumulate, accumulateProduct, accumulateSquare, +Mat::convertTo +*/ +CV_EXPORTS_W void multiply(InputArray src1, InputArray src2, + OutputArray dst, double scale = 1, int dtype = -1); + +/** @brief Performs per-element division of two arrays or a scalar by an array. + +The function cv::divide divides one array by another: +\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] +or a scalar by an array when there is no src1 : +\f[\texttt{dst(I) = saturate(scale/src2(I))}\f] + +Different channels of multi-channel arrays are processed independently. + +For integer types when src2(I) is zero, dst(I) will also be zero. + +@note In case of floating point data there is no special defined behavior for zero src2(I) values. +Regular floating-point division is used. +Expect correct IEEE-754 behaviour for floating-point data (with NaN, Inf result values). + +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`divide(src,X)` means `divide(src,(X,X,X,X))`. +`divide(src,(X,))` means `divide(src,(X,0,0,0))`. +@param src1 first input array. +@param src2 second input array of the same size and type as src1. +@param scale scalar factor. +@param dst output array of the same size and type as src2. +@param dtype optional depth of the output array; if -1, dst will have depth src2.depth(), but in +case of an array-by-array division, you can only pass -1 when src1.depth()==src2.depth(). +@sa multiply, add, subtract +*/ +CV_EXPORTS_W void divide(InputArray src1, InputArray src2, OutputArray dst, + double scale = 1, int dtype = -1); + +/** @overload */ +CV_EXPORTS_W void divide(double scale, InputArray src2, + OutputArray dst, int dtype = -1); + +/** @brief Calculates the sum of a scaled array and another array. + +The function scaleAdd is one of the classical primitive linear algebra operations, known as DAXPY +or SAXPY in [BLAS](http://en.wikipedia.org/wiki/Basic_Linear_Algebra_Subprograms). It calculates +the sum of a scaled array and another array: +\f[\texttt{dst} (I)= \texttt{scale} \cdot \texttt{src1} (I) + \texttt{src2} (I)\f] +The function can also be emulated with a matrix expression, for example: +@code{.cpp} + Mat A(3, 3, CV_64F); + ... + A.row(0) = A.row(1)*2 + A.row(2); +@endcode +@param src1 first input array. +@param alpha scale factor for the first array. +@param src2 second input array of the same size and type as src1. +@param dst output array of the same size and type as src1. +@sa add, addWeighted, subtract, Mat::dot, Mat::convertTo +*/ +CV_EXPORTS_W void scaleAdd(InputArray src1, double alpha, InputArray src2, OutputArray dst); + +/** @brief Calculates the weighted sum of two arrays. + +The function addWeighted calculates the weighted sum of two arrays as follows: +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] +where I is a multi-dimensional index of array elements. In case of multi-channel arrays, each +channel is processed independently. +The function can be replaced with a matrix expression: +@code{.cpp} + dst = src1*alpha + src2*beta + gamma; +@endcode +@note Saturation is not applied when the output array has the depth CV_32S. You may even get +result of an incorrect sign in the case of overflow. +@param src1 first input array. +@param alpha weight of the first array elements. +@param src2 second input array of the same size and channel number as src1. +@param beta weight of the second array elements. +@param gamma scalar added to each sum. +@param dst output array that has the same size and number of channels as the input arrays. +@param dtype optional depth of the output array; when both input arrays have the same depth, dtype +can be set to -1, which will be equivalent to src1.depth(). +@sa add, subtract, scaleAdd, Mat::convertTo +*/ +CV_EXPORTS_W void addWeighted(InputArray src1, double alpha, InputArray src2, + double beta, double gamma, OutputArray dst, int dtype = -1); + +/** @brief Scales, calculates absolute values, and converts the result to 8-bit. + +On each element of the input array, the function convertScaleAbs +performs three operations sequentially: scaling, taking an absolute +value, conversion to an unsigned 8-bit type: +\f[\texttt{dst} (I)= \texttt{saturate\_cast} (| \texttt{src} (I)* \texttt{alpha} + \texttt{beta} |)\f] +In case of multi-channel arrays, the function processes each channel +independently. When the output is not 8-bit, the operation can be +emulated by calling the Mat::convertTo method (or by using matrix +expressions) and then by calculating an absolute value of the result. +For example: +@code{.cpp} + Mat_ A(30,30); + randu(A, Scalar(-100), Scalar(100)); + Mat_ B = A*5 + 3; + B = abs(B); + // Mat_ B = abs(A*5+3) will also do the job, + // but it will allocate a temporary matrix +@endcode +@param src input array. +@param dst output array. +@param alpha optional scale factor. +@param beta optional delta added to the scaled values. +@sa Mat::convertTo, cv::abs(const Mat&) +*/ +CV_EXPORTS_W void convertScaleAbs(InputArray src, OutputArray dst, + double alpha = 1, double beta = 0); + +/** @brief Converts an array to half precision floating number. + +This function converts FP32 (single precision floating point) from/to FP16 (half precision floating point). CV_16S format is used to represent FP16 data. +There are two use modes (src -> dst): CV_32F -> CV_16S and CV_16S -> CV_32F. The input array has to have type of CV_32F or +CV_16S to represent the bit depth. If the input array is neither of them, the function will raise an error. +The format of half precision floating point is defined in IEEE 754-2008. + +@param src input array. +@param dst output array. + +@deprecated Use Mat::convertTo with CV_16F instead. +*/ +CV_EXPORTS_W void convertFp16(InputArray src, OutputArray dst); + +/** @example samples/cpp/tutorial_code/core/how_to_scan_images/how_to_scan_images.cpp +Check @ref tutorial_how_to_scan_images "the corresponding tutorial" for more details +*/ + +/** @brief Performs a look-up table transform of an array. + +The function LUT fills the output array with values from the look-up table. Indices of the entries +are taken from the input array. That is, the function processes each element of src as follows: +\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I) + d)}\f] +where +\f[d = \fork{0}{if \(\texttt{src}\) has depth \(\texttt{CV_8U}\)}{128}{if \(\texttt{src}\) has depth \(\texttt{CV_8S}\)}\f] +@param src input array of 8-bit elements. +@param lut look-up table of 256 elements; in case of multi-channel input array, the table should +either have a single channel (in this case the same table is used for all channels) or the same +number of channels as in the input array. +@param dst output array of the same size and number of channels as src, and the same depth as lut. +@sa convertScaleAbs, Mat::convertTo +*/ +CV_EXPORTS_W void LUT(InputArray src, InputArray lut, OutputArray dst); + +/** @brief Calculates the sum of array elements. + +The function cv::sum calculates and returns the sum of array elements, +independently for each channel. +@param src input array that must have from 1 to 4 channels. +@sa countNonZero, mean, meanStdDev, norm, minMaxLoc, reduce +*/ +CV_EXPORTS_AS(sumElems) Scalar sum(InputArray src); + +/** @brief Checks for the presence of at least one non-zero array element. + +The function returns whether there are non-zero elements in src + +The function do not work with multi-channel arrays. If you need to check non-zero array +elements across all the channels, use Mat::reshape first to reinterpret the array as +single-channel. Or you may extract the particular channel using either extractImageCOI, or +mixChannels, or split. + +@note +- If the location of non-zero array elements is important, @ref findNonZero is helpful. +- If the count of non-zero array elements is important, @ref countNonZero is helpful. +@param src single-channel array. +@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix +@sa findNonZero, countNonZero +*/ +CV_EXPORTS_W bool hasNonZero( InputArray src ); + +/** @brief Counts non-zero array elements. + +The function returns the number of non-zero elements in src : +\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] + +The function do not work with multi-channel arrays. If you need to count non-zero array +elements across all the channels, use Mat::reshape first to reinterpret the array as +single-channel. Or you may extract the particular channel using either extractImageCOI, or +mixChannels, or split. + +@note +- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. +- If the location of non-zero array elements is important, @ref findNonZero is helpful. +@param src single-channel array. +@sa mean, meanStdDev, norm, minMaxLoc, calcCovarMatrix +@sa findNonZero, hasNonZero +*/ +CV_EXPORTS_W int countNonZero( InputArray src ); + +/** @brief Returns the list of locations of non-zero pixels + +Given a binary matrix (likely returned from an operation such +as threshold(), compare(), >, ==, etc, return all of +the non-zero indices as a cv::Mat or std::vector (x,y) +For example: +@code{.cpp} + cv::Mat binaryImage; // input, binary image + cv::Mat locations; // output, locations of non-zero pixels + cv::findNonZero(binaryImage, locations); + + // access pixel coordinates + Point pnt = locations.at(i); +@endcode +or +@code{.cpp} + cv::Mat binaryImage; // input, binary image + vector locations; // output, locations of non-zero pixels + cv::findNonZero(binaryImage, locations); + + // access pixel coordinates + Point pnt = locations[i]; +@endcode + +The function do not work with multi-channel arrays. If you need to find non-zero +elements across all the channels, use Mat::reshape first to reinterpret the array as +single-channel. Or you may extract the particular channel using either extractImageCOI, or +mixChannels, or split. + +@note +- If only count of non-zero array elements is important, @ref countNonZero is helpful. +- If only whether there are non-zero elements is important, @ref hasNonZero is helpful. +@param src single-channel array +@param idx the output array, type of cv::Mat or std::vector, corresponding to non-zero indices in the input +@sa countNonZero, hasNonZero +*/ +CV_EXPORTS_W void findNonZero( InputArray src, OutputArray idx ); + +/** @brief Calculates an average (mean) of array elements. + +The function cv::mean calculates the mean value M of array elements, +independently for each channel, and return it: +\f[\begin{array}{l} N = \sum _{I: \; \texttt{mask} (I) \ne 0} 1 \\ M_c = \left ( \sum _{I: \; \texttt{mask} (I) \ne 0}{ \texttt{mtx} (I)_c} \right )/N \end{array}\f] +When all the mask elements are 0's, the function returns Scalar::all(0) +@param src input array that should have from 1 to 4 channels so that the result can be stored in +Scalar_ . +@param mask optional operation mask. +@sa countNonZero, meanStdDev, norm, minMaxLoc +*/ +CV_EXPORTS_W Scalar mean(InputArray src, InputArray mask = noArray()); + +/** Calculates a mean and standard deviation of array elements. + +The function cv::meanStdDev calculates the mean and the standard deviation M +of array elements independently for each channel and returns it via the +output parameters: +\f[\begin{array}{l} N = \sum _{I, \texttt{mask} (I) \ne 0} 1 \\ \texttt{mean} _c = \frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \texttt{src} (I)_c}{N} \\ \texttt{stddev} _c = \sqrt{\frac{\sum_{ I: \; \texttt{mask}(I) \ne 0} \left ( \texttt{src} (I)_c - \texttt{mean} _c \right )^2}{N}} \end{array}\f] +When all the mask elements are 0's, the function returns +mean=stddev=Scalar::all(0). +@note The calculated standard deviation is only the diagonal of the +complete normalized covariance matrix. If the full matrix is needed, you +can reshape the multi-channel array M x N to the single-channel array +M\*N x mtx.channels() (only possible when the matrix is continuous) and +then pass the matrix to calcCovarMatrix . +@param src input array that should have from 1 to 4 channels so that the results can be stored in +Scalar_ 's. +@param mean output parameter: calculated mean value. +@param stddev output parameter: calculated standard deviation. +@param mask optional operation mask. +@sa countNonZero, mean, norm, minMaxLoc, calcCovarMatrix +*/ +CV_EXPORTS_W void meanStdDev(InputArray src, OutputArray mean, OutputArray stddev, + InputArray mask=noArray()); + +/** @brief Calculates the absolute norm of an array. + +This version of #norm calculates the absolute norm of src1. The type of norm to calculate is specified using #NormTypes. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{1}, L_{2} \f$ and \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ + \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ + \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ + \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ + \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. +\f} +The following graphic shows all values for the three norm functions \f$\| r(x) \|_{L_1}, \| r(x) \|_{L_2}\f$ and \f$\| r(x) \|_{L_\infty}\f$. +It is notable that the \f$ L_{1} \f$ norm forms the upper and the \f$ L_{\infty} \f$ norm forms the lower border for the example function \f$ r(x) \f$. +![Graphs for the different norm functions from the above example](pics/NormTypes_OneArray_1-2-INF.png) + +When the mask parameter is specified and it is not empty, the norm is + +If normType is not specified, #NORM_L2 is used. +calculated only over the region specified by the mask. + +Multi-channel input arrays are treated as single-channel arrays, that is, +the results for all channels are combined. + +Hamming norms can only be calculated with CV_8U depth arrays. + +@param src1 first input array. +@param normType type of the norm (see #NormTypes). +@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. +*/ +CV_EXPORTS_W double norm(InputArray src1, int normType = NORM_L2, InputArray mask = noArray()); + +/** @brief Calculates an absolute difference norm or a relative difference norm. + +This version of cv::norm calculates the absolute difference norm +or the relative difference norm of arrays src1 and src2. +The type of norm to calculate is specified using #NormTypes. + +@param src1 first input array. +@param src2 second input array of the same size and the same type as src1. +@param normType type of the norm (see #NormTypes). +@param mask optional operation mask; it must have the same size as src1 and CV_8UC1 type. +*/ +CV_EXPORTS_W double norm(InputArray src1, InputArray src2, + int normType = NORM_L2, InputArray mask = noArray()); +/** @overload +@param src first input array. +@param normType type of the norm (see #NormTypes). +*/ +CV_EXPORTS double norm( const SparseMat& src, int normType ); + +/** @brief Computes the Peak Signal-to-Noise Ratio (PSNR) image quality metric. + +This function calculates the Peak Signal-to-Noise Ratio (PSNR) image quality metric in decibels (dB), +between two input arrays src1 and src2. The arrays must have the same type. + +The PSNR is calculated as follows: + +\f[ +\texttt{PSNR} = 10 \cdot \log_{10}{\left( \frac{R^2}{MSE} \right) } +\f] + +where R is the maximum integer value of depth (e.g. 255 in the case of CV_8U data) +and MSE is the mean squared error between the two arrays. + +@param src1 first input array. +@param src2 second input array of the same size as src1. +@param R the maximum pixel value (255 by default) + + */ +CV_EXPORTS_W double PSNR(InputArray src1, InputArray src2, double R=255.); + +/** @brief naive nearest neighbor finder + +see http://en.wikipedia.org/wiki/Nearest_neighbor_search +@todo document + */ +CV_EXPORTS_W void batchDistance(InputArray src1, InputArray src2, + OutputArray dist, int dtype, OutputArray nidx, + int normType = NORM_L2, int K = 0, + InputArray mask = noArray(), int update = 0, + bool crosscheck = false); + +/** @brief Normalizes the norm or value range of an array. + +The function cv::normalize normalizes scale and shift the input array elements so that +\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] +(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that +\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] + +when normType=NORM_MINMAX (for dense arrays only). The optional mask specifies a sub-array to be +normalized. This means that the norm or min-n-max are calculated over the sub-array, and then this +sub-array is modified to be normalized. If you want to only use the mask to calculate the norm or +min-max but modify the whole array, you can use norm and Mat::convertTo. + +In case of sparse matrices, only the non-zero values are analyzed and transformed. Because of this, +the range transformation for sparse matrices is not allowed since it can shift the zero level. + +Possible usage with some positive example data: +@code{.cpp} + vector positiveData = { 2.0, 8.0, 10.0 }; + vector normalizedData_l1, normalizedData_l2, normalizedData_inf, normalizedData_minmax; + + // Norm to probability (total count) + // sum(numbers) = 20.0 + // 2.0 0.1 (2.0/20.0) + // 8.0 0.4 (8.0/20.0) + // 10.0 0.5 (10.0/20.0) + normalize(positiveData, normalizedData_l1, 1.0, 0.0, NORM_L1); + + // Norm to unit vector: ||positiveData|| = 1.0 + // 2.0 0.15 + // 8.0 0.62 + // 10.0 0.77 + normalize(positiveData, normalizedData_l2, 1.0, 0.0, NORM_L2); + + // Norm to max element + // 2.0 0.2 (2.0/10.0) + // 8.0 0.8 (8.0/10.0) + // 10.0 1.0 (10.0/10.0) + normalize(positiveData, normalizedData_inf, 1.0, 0.0, NORM_INF); + + // Norm to range [0.0;1.0] + // 2.0 0.0 (shift to left border) + // 8.0 0.75 (6.0/8.0) + // 10.0 1.0 (shift to right border) + normalize(positiveData, normalizedData_minmax, 1.0, 0.0, NORM_MINMAX); +@endcode + +@param src input array. +@param dst output array of the same size as src . +@param alpha norm value to normalize to or the lower range boundary in case of the range +normalization. +@param beta upper range boundary in case of the range normalization; it is not used for the norm +normalization. +@param norm_type normalization type (see cv::NormTypes). +@param dtype when negative, the output array has the same type as src; otherwise, it has the same +number of channels as src and the depth =CV_MAT_DEPTH(dtype). +@param mask optional operation mask. +@sa norm, Mat::convertTo, SparseMat::convertTo +*/ +CV_EXPORTS_W void normalize( InputArray src, InputOutputArray dst, double alpha = 1, double beta = 0, + int norm_type = NORM_L2, int dtype = -1, InputArray mask = noArray()); + +/** @overload +@param src input array. +@param dst output array of the same size as src . +@param alpha norm value to normalize to or the lower range boundary in case of the range +normalization. +@param normType normalization type (see cv::NormTypes). +*/ +CV_EXPORTS void normalize( const SparseMat& src, SparseMat& dst, double alpha, int normType ); + +/** @brief Finds the global minimum and maximum in an array. + +The function cv::minMaxLoc finds the minimum and maximum element values and their positions. The +extrema are searched across the whole array or, if mask is not an empty array, in the specified +array region. + +In C++, if the input is multi-channel, you should omit the minLoc, maxLoc, and mask arguments +(i.e. leave them as NULL, NULL, and noArray() respectively). These arguments are not +supported for multi-channel input arrays. If working with multi-channel input and you +need the minLoc, maxLoc, or mask arguments, then use Mat::reshape first to reinterpret +the array as single-channel. Alternatively, you can extract the particular channel using either +extractImageCOI, mixChannels, or split. + +In Python, multi-channel input is not supported at all due to a limitation in the +binding generation process (there is no way to set minLoc and maxLoc to NULL). A +workaround is to operate on each channel individually or to use NumPy to achieve the same +functionality. + +@param src input single-channel array. +@param minVal pointer to the returned minimum value; NULL is used if not required. +@param maxVal pointer to the returned maximum value; NULL is used if not required. +@param minLoc pointer to the returned minimum location (in 2D case); NULL is used if not required. +@param maxLoc pointer to the returned maximum location (in 2D case); NULL is used if not required. +@param mask optional mask used to select a sub-array. +@sa max, min, reduceArgMin, reduceArgMax, compare, inRange, extractImageCOI, mixChannels, split, Mat::reshape +*/ +CV_EXPORTS_W void minMaxLoc(InputArray src, CV_OUT double* minVal, + CV_OUT double* maxVal = 0, CV_OUT Point* minLoc = 0, + CV_OUT Point* maxLoc = 0, InputArray mask = noArray()); + +/** + * @brief Finds indices of min elements along provided axis + * + * @note + * - If input or output array is not continuous, this function will create an internal copy. + * - NaN handling is left unspecified, see patchNaNs(). + * - The returned index is always in bounds of input matrix. + * + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. + * @param lastIndex whether to get the index of first or last occurrence of min. + * @param axis axis to reduce along. + * @sa reduceArgMax, minMaxLoc, min, max, compare, reduce + */ +CV_EXPORTS_W void reduceArgMin(InputArray src, OutputArray dst, int axis, bool lastIndex = false); + +/** + * @brief Finds indices of max elements along provided axis + * + * @note + * - If input or output array is not continuous, this function will create an internal copy. + * - NaN handling is left unspecified, see patchNaNs(). + * - The returned index is always in bounds of input matrix. + * + * @param src input single-channel array. + * @param dst output array of type CV_32SC1 with the same dimensionality as src, + * except for axis being reduced - it should be set to 1. + * @param lastIndex whether to get the index of first or last occurrence of max. + * @param axis axis to reduce along. + * @sa reduceArgMin, minMaxLoc, min, max, compare, reduce + */ +CV_EXPORTS_W void reduceArgMax(InputArray src, OutputArray dst, int axis, bool lastIndex = false); + +/** @brief Finds the global minimum and maximum in an array + +The function cv::minMaxIdx finds the minimum and maximum element values and their positions. The +extremums are searched across the whole array or, if mask is not an empty array, in the specified +array region. In case of a sparse matrix, the minimum is found among non-zero elements +only. Multi-channel input is supported without mask and extremums indexes (should be nullptr). +@note When minIdx is not NULL, it must have at least 2 elements (as well as maxIdx), even if src is +a single-row or single-column matrix. In OpenCV (following MATLAB) each array has at least 2 +dimensions, i.e. single-column matrix is Mx1 matrix (and therefore minIdx/maxIdx will be +(i1,0)/(i2,0)) and single-row matrix is 1xN matrix (and therefore minIdx/maxIdx will be +(0,j1)/(0,j2)). +@param src input single-channel array. +@param minVal pointer to the returned minimum value; NULL is used if not required. +@param maxVal pointer to the returned maximum value; NULL is used if not required. +@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; +Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element +in each dimension are stored there sequentially. +@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. +@param mask specified array region +*/ +CV_EXPORTS void minMaxIdx(InputArray src, double* minVal, double* maxVal = 0, + int* minIdx = 0, int* maxIdx = 0, InputArray mask = noArray()); + +/** @overload +@param a input single-channel array. +@param minVal pointer to the returned minimum value; NULL is used if not required. +@param maxVal pointer to the returned maximum value; NULL is used if not required. +@param minIdx pointer to the returned minimum location (in nD case); NULL is used if not required; +Otherwise, it must point to an array of src.dims elements, the coordinates of the minimum element +in each dimension are stored there sequentially. +@param maxIdx pointer to the returned maximum location (in nD case). NULL is used if not required. +*/ +CV_EXPORTS void minMaxLoc(const SparseMat& a, double* minVal, + double* maxVal, int* minIdx = 0, int* maxIdx = 0); + +/** @brief Reduces a matrix to a vector. + +The function #reduce reduces the matrix to a vector by treating the matrix rows/columns as a set of +1D vectors and performing the specified operation on the vectors until a single row/column is +obtained. For example, the function can be used to compute horizontal and vertical projections of a +raster image. In case of #REDUCE_MAX and #REDUCE_MIN, the output image should have the same type as the source one. +In case of #REDUCE_SUM, #REDUCE_SUM2 and #REDUCE_AVG, the output may have a larger element bit-depth to preserve accuracy. +And multi-channel arrays are also supported in these two reduction modes. + +The following code demonstrates its usage for a single channel matrix. +@snippet snippets/core_reduce.cpp example + +And the following code demonstrates its usage for a two-channel matrix. +@snippet snippets/core_reduce.cpp example2 + +@param src input 2D matrix. +@param dst output vector. Its size and type is defined by dim and dtype parameters. +@param dim dimension index along which the matrix is reduced. 0 means that the matrix is reduced to +a single row. 1 means that the matrix is reduced to a single column. +@param rtype reduction operation that could be one of #ReduceTypes +@param dtype when negative, the output vector will have the same type as the input matrix, +otherwise, its type will be CV_MAKE_TYPE(CV_MAT_DEPTH(dtype), src.channels()). +@sa repeat, reduceArgMin, reduceArgMax +*/ +CV_EXPORTS_W void reduce(InputArray src, OutputArray dst, int dim, int rtype, int dtype = -1); + +/** @brief Creates one multi-channel array out of several single-channel ones. + +The function cv::merge merges several arrays to make a single multi-channel array. That is, each +element of the output array will be a concatenation of the elements of the input arrays, where +elements of i-th input array are treated as mv[i].channels()-element vectors. + +The function cv::split does the reverse operation. If you need to shuffle channels in some other +advanced way, use cv::mixChannels. + +The following example shows how to merge 3 single channel matrices into a single 3-channel matrix. +@snippet snippets/core_merge.cpp example + +@param mv input array of matrices to be merged; all the matrices in mv must have the same +size and the same depth. +@param count number of input matrices when mv is a plain C array; it must be greater than zero. +@param dst output array of the same size and the same depth as mv[0]; The number of channels will +be equal to the parameter count. +@sa mixChannels, split, Mat::reshape +*/ +CV_EXPORTS void merge(const Mat* mv, size_t count, OutputArray dst); + +/** @overload +@param mv input vector of matrices to be merged; all the matrices in mv must have the same +size and the same depth. +@param dst output array of the same size and the same depth as mv[0]; The number of channels will +be the total number of channels in the matrix array. + */ +CV_EXPORTS_W void merge(InputArrayOfArrays mv, OutputArray dst); + +/** @brief Divides a multi-channel array into several single-channel arrays. + +The function cv::split splits a multi-channel array into separate single-channel arrays: +\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] +If you need to extract a single channel or do some other sophisticated channel permutation, use +mixChannels. + +The following example demonstrates how to split a 3-channel matrix into 3 single channel matrices. +@snippet snippets/core_split.cpp example + +@param src input multi-channel array. +@param mvbegin output array; the number of arrays must match src.channels(); the arrays themselves are +reallocated, if needed. +@sa merge, mixChannels, cvtColor +*/ +CV_EXPORTS void split(const Mat& src, Mat* mvbegin); + +/** @overload +@param m input multi-channel array. +@param mv output vector of arrays; the arrays themselves are reallocated, if needed. +*/ +CV_EXPORTS_W void split(InputArray m, OutputArrayOfArrays mv); + +/** @brief Copies specified channels from input arrays to the specified channels of +output arrays. + +The function cv::mixChannels provides an advanced mechanism for shuffling image channels. + +cv::split,cv::merge,cv::extractChannel,cv::insertChannel and some forms of cv::cvtColor are partial cases of cv::mixChannels. + +In the example below, the code splits a 4-channel BGRA image into a 3-channel BGR (with B and R +channels swapped) and a separate alpha-channel image: +@code{.cpp} + Mat bgra( 100, 100, CV_8UC4, Scalar(255,0,0,255) ); + Mat bgr( bgra.rows, bgra.cols, CV_8UC3 ); + Mat alpha( bgra.rows, bgra.cols, CV_8UC1 ); + + // forming an array of matrices is a quite efficient operation, + // because the matrix data is not copied, only the headers + Mat out[] = { bgr, alpha }; + // bgra[0] -> bgr[2], bgra[1] -> bgr[1], + // bgra[2] -> bgr[0], bgra[3] -> alpha[0] + int from_to[] = { 0,2, 1,1, 2,0, 3,3 }; + mixChannels( &bgra, 1, out, 2, from_to, 4 ); +@endcode +@note Unlike many other new-style C++ functions in OpenCV (see the introduction section and +Mat::create ), cv::mixChannels requires the output arrays to be pre-allocated before calling the +function. +@param src input array or vector of matrices; all of the matrices must have the same size and the +same depth. +@param nsrcs number of matrices in `src`. +@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and +depth must be the same as in `src[0]`. +@param ndsts number of matrices in `dst`. +@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is +a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in +dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to +src[0].channels()-1, the second input image channels are indexed from src[0].channels() to +src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image +channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is +filled with zero . +@param npairs number of index pairs in `fromTo`. +@sa split, merge, extractChannel, insertChannel, cvtColor +*/ +CV_EXPORTS void mixChannels(const Mat* src, size_t nsrcs, Mat* dst, size_t ndsts, + const int* fromTo, size_t npairs); + +/** @overload +@param src input array or vector of matrices; all of the matrices must have the same size and the +same depth. +@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and +depth must be the same as in src[0]. +@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is +a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in +dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to +src[0].channels()-1, the second input image channels are indexed from src[0].channels() to +src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image +channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is +filled with zero . +@param npairs number of index pairs in fromTo. +*/ +CV_EXPORTS void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, + const int* fromTo, size_t npairs); + +/** @overload +@param src input array or vector of matrices; all of the matrices must have the same size and the +same depth. +@param dst output array or vector of matrices; all the matrices **must be allocated**; their size and +depth must be the same as in src[0]. +@param fromTo array of index pairs specifying which channels are copied and where; fromTo[k\*2] is +a 0-based index of the input channel in src, fromTo[k\*2+1] is an index of the output channel in +dst; the continuous channel numbering is used: the first input image channels are indexed from 0 to +src[0].channels()-1, the second input image channels are indexed from src[0].channels() to +src[0].channels() + src[1].channels()-1, and so on, the same scheme is used for the output image +channels; as a special case, when fromTo[k\*2] is negative, the corresponding output channel is +filled with zero . +*/ +CV_EXPORTS_W void mixChannels(InputArrayOfArrays src, InputOutputArrayOfArrays dst, + const std::vector& fromTo); + +/** @brief Extracts a single channel from src (coi is 0-based index) +@param src input array +@param dst output array +@param coi index of channel to extract +@sa mixChannels, split +*/ +CV_EXPORTS_W void extractChannel(InputArray src, OutputArray dst, int coi); + +/** @brief Inserts a single channel to dst (coi is 0-based index) +@param src input array +@param dst output array +@param coi index of channel for insertion +@sa mixChannels, merge +*/ +CV_EXPORTS_W void insertChannel(InputArray src, InputOutputArray dst, int coi); + +/** @brief Flips a 2D array around vertical, horizontal, or both axes. + +The function cv::flip flips the array in one of three different ways (row +and column indices are 0-based): +\f[\texttt{dst} _{ij} = +\left\{ +\begin{array}{l l} +\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ +\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ +\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ +\end{array} +\right.\f] +The example scenarios of using the function are the following: +* Vertical flipping of the image (flipCode == 0) to switch between + top-left and bottom-left image origin. This is a typical operation + in video processing on Microsoft Windows\* OS. +* Horizontal flipping of the image with the subsequent horizontal + shift and absolute difference calculation to check for a + vertical-axis symmetry (flipCode \> 0). +* Simultaneous horizontal and vertical flipping of the image with + the subsequent shift and absolute difference calculation to check + for a central symmetry (flipCode \< 0). +* Reversing the order of point arrays (flipCode \> 0 or + flipCode == 0). +@param src input array. +@param dst output array of the same size and type as src. +@param flipCode a flag to specify how to flip the array; 0 means +flipping around the x-axis and positive value (for example, 1) means +flipping around y-axis. Negative value (for example, -1) means flipping +around both axes. +@sa transpose, repeat, completeSymm +*/ +CV_EXPORTS_W void flip(InputArray src, OutputArray dst, int flipCode); + +/** @brief Flips a n-dimensional at given axis + * @param src input array + * @param dst output array that has the same shape of src + * @param axis axis that performs a flip on. 0 <= axis < src.dims. + */ +CV_EXPORTS_W void flipND(InputArray src, OutputArray dst, int axis); + +/** @brief Broadcast the given Mat to the given shape. + * @param src input array + * @param shape target shape. Should be a list of CV_32S numbers. Note that negative values are not supported. + * @param dst output array that has the given shape + */ +CV_EXPORTS_W void broadcast(InputArray src, InputArray shape, OutputArray dst); + +enum RotateFlags { + ROTATE_90_CLOCKWISE = 0, //! A = (cv::Mat_(3, 2) << 1, 4, + 2, 5, + 3, 6); + cv::Mat_ B = (cv::Mat_(3, 2) << 7, 10, + 8, 11, + 9, 12); + + cv::Mat C; + cv::hconcat(A, B, C); + //C: + //[1, 4, 7, 10; + // 2, 5, 8, 11; + // 3, 6, 9, 12] + @endcode + @param src1 first input array to be considered for horizontal concatenation. + @param src2 second input array to be considered for horizontal concatenation. + @param dst output array. It has the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. + */ +CV_EXPORTS void hconcat(InputArray src1, InputArray src2, OutputArray dst); +/** @overload + @code{.cpp} + std::vector matrices = { cv::Mat(4, 1, CV_8UC1, cv::Scalar(1)), + cv::Mat(4, 1, CV_8UC1, cv::Scalar(2)), + cv::Mat(4, 1, CV_8UC1, cv::Scalar(3)),}; + + cv::Mat out; + cv::hconcat( matrices, out ); + //out: + //[1, 2, 3; + // 1, 2, 3; + // 1, 2, 3; + // 1, 2, 3] + @endcode + @param src input array or vector of matrices. all of the matrices must have the same number of rows and the same depth. + @param dst output array. It has the same number of rows and depth as the src, and the sum of cols of the src. +same depth. + */ +CV_EXPORTS_W void hconcat(InputArrayOfArrays src, OutputArray dst); + +/** @brief Applies vertical concatenation to given matrices. + +The function vertically concatenates two or more cv::Mat matrices (with the same number of cols). +@code{.cpp} + cv::Mat matArray[] = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; + + cv::Mat out; + cv::vconcat( matArray, 3, out ); + //out: + //[1, 1, 1, 1; + // 2, 2, 2, 2; + // 3, 3, 3, 3] +@endcode +@param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth. +@param nsrc number of matrices in src. +@param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. +@sa cv::hconcat(const Mat*, size_t, OutputArray), @sa cv::hconcat(InputArrayOfArrays, OutputArray) and @sa cv::hconcat(InputArray, InputArray, OutputArray) +*/ +CV_EXPORTS void vconcat(const Mat* src, size_t nsrc, OutputArray dst); +/** @overload + @code{.cpp} + cv::Mat_ A = (cv::Mat_(3, 2) << 1, 7, + 2, 8, + 3, 9); + cv::Mat_ B = (cv::Mat_(3, 2) << 4, 10, + 5, 11, + 6, 12); + + cv::Mat C; + cv::vconcat(A, B, C); + //C: + //[1, 7; + // 2, 8; + // 3, 9; + // 4, 10; + // 5, 11; + // 6, 12] + @endcode + @param src1 first input array to be considered for vertical concatenation. + @param src2 second input array to be considered for vertical concatenation. + @param dst output array. It has the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. + */ +CV_EXPORTS void vconcat(InputArray src1, InputArray src2, OutputArray dst); +/** @overload + @code{.cpp} + std::vector matrices = { cv::Mat(1, 4, CV_8UC1, cv::Scalar(1)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(2)), + cv::Mat(1, 4, CV_8UC1, cv::Scalar(3)),}; + + cv::Mat out; + cv::vconcat( matrices, out ); + //out: + //[1, 1, 1, 1; + // 2, 2, 2, 2; + // 3, 3, 3, 3] + @endcode + @param src input array or vector of matrices. all of the matrices must have the same number of cols and the same depth + @param dst output array. It has the same number of cols and depth as the src, and the sum of rows of the src. +same depth. + */ +CV_EXPORTS_W void vconcat(InputArrayOfArrays src, OutputArray dst); + +/** @brief computes bitwise conjunction of the two arrays (dst = src1 & src2) +Calculates the per-element bit-wise conjunction of two arrays or an +array and a scalar. + +The function cv::bitwise_and calculates the per-element bit-wise logical conjunction for: +* Two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +* An array and a scalar when src2 is constructed from Scalar or has + the same number of elements as `src1.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} (I) \wedge \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] +* A scalar and an array when src1 is constructed from Scalar or has + the same number of elements as `src2.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} \wedge \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +In case of floating-point arrays, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel arrays, each channel is processed +independently. In the second and third cases above, the scalar is first +converted to the array type. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as the input +arrays. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_and(InputArray src1, InputArray src2, + OutputArray dst, InputArray mask = noArray()); + +/** @brief Calculates the per-element bit-wise disjunction of two arrays or an +array and a scalar. + +The function cv::bitwise_or calculates the per-element bit-wise logical disjunction for: +* Two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +* An array and a scalar when src2 is constructed from Scalar or has + the same number of elements as `src1.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} (I) \vee \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] +* A scalar and an array when src1 is constructed from Scalar or has + the same number of elements as `src2.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} \vee \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +In case of floating-point arrays, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel arrays, each channel is processed +independently. In the second and third cases above, the scalar is first +converted to the array type. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as the input +arrays. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_or(InputArray src1, InputArray src2, + OutputArray dst, InputArray mask = noArray()); + +/** @brief Calculates the per-element bit-wise "exclusive or" operation on two +arrays or an array and a scalar. + +The function cv::bitwise_xor calculates the per-element bit-wise logical "exclusive-or" +operation for: +* Two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +* An array and a scalar when src2 is constructed from Scalar or has + the same number of elements as `src1.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} (I) \oplus \texttt{src2} \quad \texttt{if mask} (I) \ne0\f] +* A scalar and an array when src1 is constructed from Scalar or has + the same number of elements as `src2.channels()`: + \f[\texttt{dst} (I) = \texttt{src1} \oplus \texttt{src2} (I) \quad \texttt{if mask} (I) \ne0\f] +In case of floating-point arrays, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel arrays, each channel is processed +independently. In the 2nd and 3rd cases above, the scalar is first +converted to the array type. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as the input +arrays. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_xor(InputArray src1, InputArray src2, + OutputArray dst, InputArray mask = noArray()); + +/** @brief Inverts every bit of an array. + +The function cv::bitwise_not calculates per-element bit-wise inversion of the input +array: +\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] +In case of a floating-point input array, its machine-specific bit +representation (usually IEEE754-compliant) is used for the operation. In +case of multi-channel arrays, each channel is processed independently. +@param src input array. +@param dst output array that has the same size and type as the input +array. +@param mask optional operation mask, 8-bit single channel array, that +specifies elements of the output array to be changed. +*/ +CV_EXPORTS_W void bitwise_not(InputArray src, OutputArray dst, + InputArray mask = noArray()); + +/** @brief Calculates the per-element absolute difference between two arrays or between an array and a scalar. + +The function cv::absdiff calculates: +* Absolute difference between two arrays when they have the same + size and type: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] +* Absolute difference between an array and a scalar when the second + array is constructed from Scalar or has as many elements as the + number of channels in `src1`: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2} |)\f] +* Absolute difference between a scalar and an array when the first + array is constructed from Scalar or has as many elements as the + number of channels in `src2`: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1} - \texttt{src2}(I) |)\f] + where I is a multi-dimensional index of array elements. In case of + multi-channel arrays, each channel is processed independently. +@note Saturation is not applied when the arrays have the depth CV_32S. +You may even get a negative value in the case of overflow. +@note (Python) Be careful to difference behaviour between src1/src2 are single number and they are tuple/array. +`absdiff(src,X)` means `absdiff(src,(X,X,X,X))`. +`absdiff(src,(X,))` means `absdiff(src,(X,0,0,0))`. +@param src1 first input array or a scalar. +@param src2 second input array or a scalar. +@param dst output array that has the same size and type as input arrays. +@sa cv::abs(const Mat&) +*/ +CV_EXPORTS_W void absdiff(InputArray src1, InputArray src2, OutputArray dst); + +/** @brief This is an overloaded member function, provided for convenience (python) +Copies the matrix to another one. +When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, the newly allocated matrix is initialized with all zeros before copying the data. +@param src source matrix. +@param dst Destination matrix. If it does not have a proper size or type before the operation, it is +reallocated. +@param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix +elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. +*/ + +void CV_EXPORTS_W copyTo(InputArray src, OutputArray dst, InputArray mask); +/** @brief Checks if array elements lie between the elements of two other arrays. + +The function checks the range as follows: +- For every element of a single-channel input array: + \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0\f] +- For two-channel arrays: + \f[\texttt{dst} (I)= \texttt{lowerb} (I)_0 \leq \texttt{src} (I)_0 \leq \texttt{upperb} (I)_0 \land \texttt{lowerb} (I)_1 \leq \texttt{src} (I)_1 \leq \texttt{upperb} (I)_1\f] +- and so forth. + +That is, dst (I) is set to 255 (all 1 -bits) if src (I) is within the +specified 1D, 2D, 3D, ... box and 0 otherwise. + +When the lower and/or upper boundary parameters are scalars, the indexes +(I) at lowerb and upperb in the above formulas should be omitted. +@param src first input array. +@param lowerb inclusive lower boundary array or a scalar. +@param upperb inclusive upper boundary array or a scalar. +@param dst output array of the same size as src and CV_8U type. +*/ +CV_EXPORTS_W void inRange(InputArray src, InputArray lowerb, + InputArray upperb, OutputArray dst); + +/** @brief Performs the per-element comparison of two arrays or an array and scalar value. + +The function compares: +* Elements of two arrays when src1 and src2 have the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) \,\texttt{cmpop}\, \texttt{src2} (I)\f] +* Elements of src1 with a scalar src2 when src2 is constructed from + Scalar or has a single element: + \f[\texttt{dst} (I) = \texttt{src1}(I) \,\texttt{cmpop}\, \texttt{src2}\f] +* src1 with elements of src2 when src1 is constructed from Scalar or + has a single element: + \f[\texttt{dst} (I) = \texttt{src1} \,\texttt{cmpop}\, \texttt{src2} (I)\f] +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: +@code{.cpp} + Mat dst1 = src1 >= src2; + Mat dst2 = src1 < 8; + ... +@endcode +@param src1 first input array or a scalar; when it is an array, it must have a single channel. +@param src2 second input array or a scalar; when it is an array, it must have a single channel. +@param dst output array of type ref CV_8U that has the same size and the same number of channels as + the input arrays. +@param cmpop a flag, that specifies correspondence between the arrays (cv::CmpTypes) +@sa checkRange, min, max, threshold +*/ +CV_EXPORTS_W void compare(InputArray src1, InputArray src2, OutputArray dst, int cmpop); + +/** @brief Calculates per-element minimum of two arrays or an array and a scalar. + +The function cv::min calculates the per-element minimum of two arrays: +\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] +or array and a scalar: +\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{value} )\f] +@param src1 first input array. +@param src2 second input array of the same size and type as src1. +@param dst output array of the same size and type as src1. +@sa max, compare, inRange, minMaxLoc +*/ +CV_EXPORTS_W void min(InputArray src1, InputArray src2, OutputArray dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void min(const Mat& src1, const Mat& src2, Mat& dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void min(const UMat& src1, const UMat& src2, UMat& dst); + +/** @brief Calculates per-element maximum of two arrays or an array and a scalar. + +The function cv::max calculates the per-element maximum of two arrays: +\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] +or array and a scalar: +\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{value} )\f] +@param src1 first input array. +@param src2 second input array of the same size and type as src1 . +@param dst output array of the same size and type as src1. +@sa min, compare, inRange, minMaxLoc, @ref MatrixExpressions +*/ +CV_EXPORTS_W void max(InputArray src1, InputArray src2, OutputArray dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void max(const Mat& src1, const Mat& src2, Mat& dst); +/** @overload +needed to avoid conflicts with const _Tp& std::min(const _Tp&, const _Tp&, _Compare) +*/ +CV_EXPORTS void max(const UMat& src1, const UMat& src2, UMat& dst); + +/** @brief Calculates a square root of array elements. + +The function cv::sqrt calculates a square root of each input array element. +In case of multi-channel arrays, each channel is processed +independently. The accuracy is approximately the same as of the built-in +std::sqrt . +@param src input floating-point array. +@param dst output array of the same size and type as src. +*/ +CV_EXPORTS_W void sqrt(InputArray src, OutputArray dst); + +/** @brief Raises every array element to a power. + +The function cv::pow raises every element of the input array to power : +\f[\texttt{dst} (I) = \fork{\texttt{src}(I)^{power}}{if \(\texttt{power}\) is integer}{|\texttt{src}(I)|^{power}}{otherwise}\f] + +So, for a non-integer power exponent, the absolute values of input array +elements are used. However, it is possible to get true values for +negative values using some extra operations. In the example below, +computing the 5th root of array src shows: +@code{.cpp} + Mat mask = src < 0; + pow(src, 1./5, dst); + subtract(Scalar::all(0), dst, dst, mask); +@endcode +For some values of power, such as integer values, 0.5 and -0.5, +specialized faster algorithms are used. + +Special values (NaN, Inf) are not handled. +@param src input array. +@param power exponent of power. +@param dst output array of the same size and type as src. +@sa sqrt, exp, log, cartToPolar, polarToCart +*/ +CV_EXPORTS_W void pow(InputArray src, double power, OutputArray dst); + +/** @brief Calculates the exponent of every array element. + +The function cv::exp calculates the exponent of every element of the input +array: +\f[\texttt{dst} [I] = e^{ src(I) }\f] + +The maximum relative error is about 7e-6 for single-precision input and +less than 1e-10 for double-precision input. Currently, the function +converts denormalized values to zeros on output. Special values (NaN, +Inf) are not handled. +@param src input array. +@param dst output array of the same size and type as src. +@sa log, cartToPolar, polarToCart, phase, pow, sqrt, magnitude +*/ +CV_EXPORTS_W void exp(InputArray src, OutputArray dst); + +/** @brief Calculates the natural logarithm of every array element. + +The function cv::log calculates the natural logarithm of every element of the input array: +\f[\texttt{dst} (I) = \log (\texttt{src}(I)) \f] + +Output on zero, negative and special (NaN, Inf) values is undefined. + +@param src input array. +@param dst output array of the same size and type as src . +@sa exp, cartToPolar, polarToCart, phase, pow, sqrt, magnitude +*/ +CV_EXPORTS_W void log(InputArray src, OutputArray dst); + +/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. + +The function cv::polarToCart calculates the Cartesian coordinates of each 2D +vector represented by the corresponding elements of magnitude and angle: +\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] + +The relative accuracy of the estimated coordinates is about 1e-6. +@param magnitude input floating-point array of magnitudes of 2D vectors; +it can be an empty matrix (=Mat()), in this case, the function assumes +that all the magnitudes are =1; if it is not empty, it must have the +same size and type as angle. +@param angle input floating-point array of angles of 2D vectors. +@param x output array of x-coordinates of 2D vectors; it has the same +size and type as angle. +@param y output array of y-coordinates of 2D vectors; it has the same +size and type as angle. +@param angleInDegrees when true, the input angles are measured in +degrees, otherwise, they are measured in radians. +@sa cartToPolar, magnitude, phase, exp, log, pow, sqrt +*/ +CV_EXPORTS_W void polarToCart(InputArray magnitude, InputArray angle, + OutputArray x, OutputArray y, bool angleInDegrees = false); + +/** @brief Calculates the magnitude and angle of 2D vectors. + +The function cv::cartToPolar calculates either the magnitude, angle, or both +for every 2D vector (x(I),y(I)): +\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] + +The angles are calculated with accuracy about 0.3 degrees. For the point +(0,0), the angle is set to 0. +@param x array of x-coordinates; this must be a single-precision or +double-precision floating-point array. +@param y array of y-coordinates, that must have the same size and same type as x. +@param magnitude output array of magnitudes of the same size and type as x. +@param angle output array of angles that has the same size and type as +x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). +@param angleInDegrees a flag, indicating whether the angles are measured +in radians (which is by default), or in degrees. +@sa Sobel, Scharr +*/ +CV_EXPORTS_W void cartToPolar(InputArray x, InputArray y, + OutputArray magnitude, OutputArray angle, + bool angleInDegrees = false); + +/** @brief Calculates the rotation angle of 2D vectors. + +The function cv::phase calculates the rotation angle of each 2D vector that +is formed from the corresponding elements of x and y : +\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] + +The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , +the corresponding angle(I) is set to 0. +@param x input floating-point array of x-coordinates of 2D vectors. +@param y input array of y-coordinates of 2D vectors; it must have the +same size and the same type as x. +@param angle output array of vector angles; it has the same size and +same type as x . +@param angleInDegrees when true, the function calculates the angle in +degrees, otherwise, they are measured in radians. +*/ +CV_EXPORTS_W void phase(InputArray x, InputArray y, OutputArray angle, + bool angleInDegrees = false); + +/** @brief Calculates the magnitude of 2D vectors. + +The function cv::magnitude calculates the magnitude of 2D vectors formed +from the corresponding elements of x and y arrays: +\f[\texttt{dst} (I) = \sqrt{\texttt{x}(I)^2 + \texttt{y}(I)^2}\f] +@param x floating-point array of x-coordinates of the vectors. +@param y floating-point array of y-coordinates of the vectors; it must +have the same size as x. +@param magnitude output array of the same size and type as x. +@sa cartToPolar, polarToCart, phase, sqrt +*/ +CV_EXPORTS_W void magnitude(InputArray x, InputArray y, OutputArray magnitude); + +/** @brief Checks every element of an input array for invalid values. + +The function cv::checkRange checks that every array element is neither NaN nor infinite. When minVal \> +-DBL_MAX and maxVal \< DBL_MAX, the function also checks that each value is between minVal and +maxVal. In case of multi-channel arrays, each channel is processed independently. If some values +are out of range, position of the first outlier is stored in pos (when pos != NULL). Then, the +function either returns false (when quiet=true) or throws an exception. +@param a input array. +@param quiet a flag, indicating whether the functions quietly return false when the array elements +are out of range or they throw an exception. +@param pos optional output parameter, when not NULL, must be a pointer to array of src.dims +elements. +@param minVal inclusive lower boundary of valid values range. +@param maxVal exclusive upper boundary of valid values range. +*/ +CV_EXPORTS_W bool checkRange(InputArray a, bool quiet = true, CV_OUT Point* pos = 0, + double minVal = -DBL_MAX, double maxVal = DBL_MAX); + +/** @brief Replaces NaNs by given number +@param a input/output matrix (CV_32F type). +@param val value to convert the NaNs +*/ +CV_EXPORTS_W void patchNaNs(InputOutputArray a, double val = 0); + +/** @brief Performs generalized matrix multiplication. + +The function cv::gemm performs generalized matrix multiplication similar to the +gemm functions in BLAS level 3. For example, +`gemm(src1, src2, alpha, src3, beta, dst, GEMM_1_T + GEMM_3_T)` +corresponds to +\f[\texttt{dst} = \texttt{alpha} \cdot \texttt{src1} ^T \cdot \texttt{src2} + \texttt{beta} \cdot \texttt{src3} ^T\f] + +In case of complex (two-channel) data, performed a complex matrix +multiplication. + +The function can be replaced with a matrix expression. For example, the +above call can be replaced with: +@code{.cpp} + dst = alpha*src1.t()*src2 + beta*src3.t(); +@endcode +@param src1 first multiplied input matrix that could be real(CV_32FC1, +CV_64FC1) or complex(CV_32FC2, CV_64FC2). +@param src2 second multiplied input matrix of the same type as src1. +@param alpha weight of the matrix product. +@param src3 third optional delta matrix added to the matrix product; it +should have the same type as src1 and src2. +@param beta weight of src3. +@param dst output matrix; it has the proper size and the same type as +input matrices. +@param flags operation flags (cv::GemmFlags) +@sa mulTransposed, transform +*/ +CV_EXPORTS_W void gemm(InputArray src1, InputArray src2, double alpha, + InputArray src3, double beta, OutputArray dst, int flags = 0); + +/** @brief Calculates the product of a matrix and its transposition. + +The function cv::mulTransposed calculates the product of src and its +transposition: +\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} )^T ( \texttt{src} - \texttt{delta} )\f] +if aTa=true, and +\f[\texttt{dst} = \texttt{scale} ( \texttt{src} - \texttt{delta} ) ( \texttt{src} - \texttt{delta} )^T\f] +otherwise. The function is used to calculate the covariance matrix. With +zero delta, it can be used as a faster substitute for general matrix +product A\*B when B=A' +@param src input single-channel matrix. Note that unlike gemm, the +function can multiply not only floating-point matrices. +@param dst output square matrix. +@param aTa Flag specifying the multiplication ordering. See the +description below. +@param delta Optional delta matrix subtracted from src before the +multiplication. When the matrix is empty ( delta=noArray() ), it is +assumed to be zero, that is, nothing is subtracted. If it has the same +size as src, it is simply subtracted. Otherwise, it is "repeated" (see +repeat ) to cover the full src and then subtracted. Type of the delta +matrix, when it is not empty, must be the same as the type of created +output matrix. See the dtype parameter description below. +@param scale Optional scale factor for the matrix product. +@param dtype Optional type of the output matrix. When it is negative, +the output matrix will have the same type as src . Otherwise, it will be +type=CV_MAT_DEPTH(dtype) that should be either CV_32F or CV_64F . +@sa calcCovarMatrix, gemm, repeat, reduce +*/ +CV_EXPORTS_W void mulTransposed( InputArray src, OutputArray dst, bool aTa, + InputArray delta = noArray(), + double scale = 1, int dtype = -1 ); + +/** @brief Transposes a matrix. + +The function cv::transpose transposes the matrix src : +\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] +@note No complex conjugation is done in case of a complex matrix. It +should be done separately if needed. +@param src input array. +@param dst output array of the same type as src. +*/ +CV_EXPORTS_W void transpose(InputArray src, OutputArray dst); + +/** @brief Transpose for n-dimensional matrices. + * + * @note Input should be continuous single-channel matrix. + * @param src input array. + * @param order a permutation of [0,1,..,N-1] where N is the number of axes of src. + * The i'th axis of dst will correspond to the axis numbered order[i] of the input. + * @param dst output array of the same type as src. + */ +CV_EXPORTS_W void transposeND(InputArray src, const std::vector& order, OutputArray dst); + +/** @brief Performs the matrix transformation of every array element. + +The function cv::transform performs the matrix transformation of every +element of the array src and stores the results in dst : +\f[\texttt{dst} (I) = \texttt{m} \cdot \texttt{src} (I)\f] +(when m.cols=src.channels() ), or +\f[\texttt{dst} (I) = \texttt{m} \cdot [ \texttt{src} (I); 1]\f] +(when m.cols=src.channels()+1 ) + +Every element of the N -channel array src is interpreted as N -element +vector that is transformed using the M x N or M x (N+1) matrix m to +M-element vector - the corresponding element of the output array dst . + +The function may be used for geometrical transformation of +N -dimensional points, arbitrary linear color space transformation (such +as various kinds of RGB to YUV transforms), shuffling the image +channels, and so forth. +@param src input array that must have as many channels (1 to 4) as +m.cols or m.cols-1. +@param dst output array of the same size and depth as src; it has as +many channels as m.rows. +@param m transformation 2x2 or 2x3 floating-point matrix. +@sa perspectiveTransform, getAffineTransform, estimateAffine2D, warpAffine, warpPerspective +*/ +CV_EXPORTS_W void transform(InputArray src, OutputArray dst, InputArray m ); + +/** @brief Performs the perspective matrix transformation of vectors. + +The function cv::perspectiveTransform transforms every element of src by +treating it as a 2D or 3D vector, in the following way: +\f[(x, y, z) \rightarrow (x'/w, y'/w, z'/w)\f] +where +\f[(x', y', z', w') = \texttt{mat} \cdot \begin{bmatrix} x & y & z & 1 \end{bmatrix}\f] +and +\f[w = \fork{w'}{if \(w' \ne 0\)}{\infty}{otherwise}\f] + +Here a 3D vector transformation is shown. In case of a 2D vector +transformation, the z component is omitted. + +@note The function transforms a sparse set of 2D or 3D vectors. If you +want to transform an image using perspective transformation, use +warpPerspective . If you have an inverse problem, that is, you want to +compute the most probable perspective transformation out of several +pairs of corresponding points, you can use getPerspectiveTransform or +findHomography . +@param src input two-channel or three-channel floating-point array; each +element is a 2D/3D vector to be transformed. +@param dst output array of the same size and type as src. +@param m 3x3 or 4x4 floating-point transformation matrix. +@sa transform, warpPerspective, getPerspectiveTransform, findHomography +*/ +CV_EXPORTS_W void perspectiveTransform(InputArray src, OutputArray dst, InputArray m ); + +/** @brief Copies the lower or the upper half of a square matrix to its another half. + +The function cv::completeSymm copies the lower or the upper half of a square matrix to +its another half. The matrix diagonal remains unchanged: + - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i > j\f$ if + lowerToUpper=false + - \f$\texttt{m}_{ij}=\texttt{m}_{ji}\f$ for \f$i < j\f$ if + lowerToUpper=true + +@param m input-output floating-point square matrix. +@param lowerToUpper operation flag; if true, the lower half is copied to +the upper half. Otherwise, the upper half is copied to the lower half. +@sa flip, transpose +*/ +CV_EXPORTS_W void completeSymm(InputOutputArray m, bool lowerToUpper = false); + +/** @brief Initializes a scaled identity matrix. + +The function cv::setIdentity initializes a scaled identity matrix: +\f[\texttt{mtx} (i,j)= \fork{\texttt{value}}{ if \(i=j\)}{0}{otherwise}\f] + +The function can also be emulated using the matrix initializers and the +matrix expressions: +@code + Mat A = Mat::eye(4, 3, CV_32F)*5; + // A will be set to [[5, 0, 0], [0, 5, 0], [0, 0, 5], [0, 0, 0]] +@endcode +@param mtx matrix to initialize (not necessarily square). +@param s value to assign to diagonal elements. +@sa Mat::zeros, Mat::ones, Mat::setTo, Mat::operator= +*/ +CV_EXPORTS_W void setIdentity(InputOutputArray mtx, const Scalar& s = Scalar(1)); + +/** @brief Returns the determinant of a square floating-point matrix. + +The function cv::determinant calculates and returns the determinant of the +specified matrix. For small matrices ( mtx.cols=mtx.rows\<=3 ), the +direct method is used. For larger matrices, the function uses LU +factorization with partial pivoting. + +For symmetric positively-determined matrices, it is also possible to use +eigen decomposition to calculate the determinant. +@param mtx input matrix that must have CV_32FC1 or CV_64FC1 type and +square size. +@sa trace, invert, solve, eigen, @ref MatrixExpressions +*/ +CV_EXPORTS_W double determinant(InputArray mtx); + +/** @brief Returns the trace of a matrix. + +The function cv::trace returns the sum of the diagonal elements of the +matrix mtx . +\f[\mathrm{tr} ( \texttt{mtx} ) = \sum _i \texttt{mtx} (i,i)\f] +@param mtx input matrix. +*/ +CV_EXPORTS_W Scalar trace(InputArray mtx); + +/** @brief Finds the inverse or pseudo-inverse of a matrix. + +The function cv::invert inverts the matrix src and stores the result in dst +. When the matrix src is singular or non-square, the function calculates +the pseudo-inverse matrix (the dst matrix) so that norm(src\*dst - I) is +minimal, where I is an identity matrix. + +In case of the #DECOMP_LU method, the function returns non-zero value if +the inverse has been successfully calculated and 0 if src is singular. + +In case of the #DECOMP_SVD method, the function returns the inverse +condition number of src (the ratio of the smallest singular value to the +largest singular value) and 0 if src is singular. The SVD method +calculates a pseudo-inverse matrix if src is singular. + +Similarly to #DECOMP_LU, the method #DECOMP_CHOLESKY works only with +non-singular square matrices that should also be symmetrical and +positively defined. In this case, the function stores the inverted +matrix in dst and returns non-zero. Otherwise, it returns 0. + +@param src input floating-point M x N matrix. +@param dst output matrix of N x M size and the same type as src. +@param flags inversion method (cv::DecompTypes) +@sa solve, SVD +*/ +CV_EXPORTS_W double invert(InputArray src, OutputArray dst, int flags = DECOMP_LU); + +/** @brief Solves one or more linear systems or least-squares problems. + +The function cv::solve solves a linear system or least-squares problem (the +latter is possible with SVD or QR methods, or by specifying the flag +#DECOMP_NORMAL ): +\f[\texttt{dst} = \arg \min _X \| \texttt{src1} \cdot \texttt{X} - \texttt{src2} \|\f] + +If #DECOMP_LU or #DECOMP_CHOLESKY method is used, the function returns 1 +if src1 (or \f$\texttt{src1}^T\texttt{src1}\f$ ) is non-singular. Otherwise, +it returns 0. In the latter case, dst is not valid. Other methods find a +pseudo-solution in case of a singular left-hand side part. + +@note If you want to find a unity-norm solution of an under-defined +singular system \f$\texttt{src1}\cdot\texttt{dst}=0\f$ , the function solve +will not do the work. Use SVD::solveZ instead. + +@param src1 input matrix on the left-hand side of the system. +@param src2 input matrix on the right-hand side of the system. +@param dst output solution. +@param flags solution (matrix inversion) method (#DecompTypes) +@sa invert, SVD, eigen +*/ +CV_EXPORTS_W bool solve(InputArray src1, InputArray src2, + OutputArray dst, int flags = DECOMP_LU); + +/** @brief Sorts each row or each column of a matrix. + +The function cv::sort sorts each matrix row or each matrix column in +ascending or descending order. So you should pass two operation flags to +get desired behaviour. If you want to sort matrix rows or columns +lexicographically, you can use STL std::sort generic function with the +proper comparison predicate. + +@param src input single-channel array. +@param dst output array of the same size and type as src. +@param flags operation flags, a combination of #SortFlags +@sa sortIdx, randShuffle +*/ +CV_EXPORTS_W void sort(InputArray src, OutputArray dst, int flags); + +/** @brief Sorts each row or each column of a matrix. + +The function cv::sortIdx sorts each matrix row or each matrix column in the +ascending or descending order. So you should pass two operation flags to +get desired behaviour. Instead of reordering the elements themselves, it +stores the indices of sorted elements in the output array. For example: +@code + Mat A = Mat::eye(3,3,CV_32F), B; + sortIdx(A, B, SORT_EVERY_ROW + SORT_ASCENDING); + // B will probably contain + // (because of equal elements in A some permutations are possible): + // [[1, 2, 0], [0, 2, 1], [0, 1, 2]] +@endcode +@param src input single-channel array. +@param dst output integer array of the same size as src. +@param flags operation flags that could be a combination of cv::SortFlags +@sa sort, randShuffle +*/ +CV_EXPORTS_W void sortIdx(InputArray src, OutputArray dst, int flags); + +/** @brief Finds the real roots of a cubic equation. + +The function solveCubic finds the real roots of a cubic equation: +- if coeffs is a 4-element vector: +\f[\texttt{coeffs} [0] x^3 + \texttt{coeffs} [1] x^2 + \texttt{coeffs} [2] x + \texttt{coeffs} [3] = 0\f] +- if coeffs is a 3-element vector: +\f[x^3 + \texttt{coeffs} [0] x^2 + \texttt{coeffs} [1] x + \texttt{coeffs} [2] = 0\f] + +The roots are stored in the roots array. +@param coeffs equation coefficients, an array of 3 or 4 elements. +@param roots output array of real roots that has 1 or 3 elements. +@return number of real roots. It can be 0, 1 or 2. +*/ +CV_EXPORTS_W int solveCubic(InputArray coeffs, OutputArray roots); + +/** @brief Finds the real or complex roots of a polynomial equation. + +The function cv::solvePoly finds real and complex roots of a polynomial equation: +\f[\texttt{coeffs} [n] x^{n} + \texttt{coeffs} [n-1] x^{n-1} + ... + \texttt{coeffs} [1] x + \texttt{coeffs} [0] = 0\f] +@param coeffs array of polynomial coefficients. +@param roots output (complex) array of roots. +@param maxIters maximum number of iterations the algorithm does. +*/ +CV_EXPORTS_W double solvePoly(InputArray coeffs, OutputArray roots, int maxIters = 300); + +/** @brief Calculates eigenvalues and eigenvectors of a symmetric matrix. + +The function cv::eigen calculates just eigenvalues, or eigenvalues and eigenvectors of the symmetric +matrix src: +@code + src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() +@endcode + +@note Use cv::eigenNonSymmetric for calculation of real eigenvalues and eigenvectors of non-symmetric matrix. + +@param src input matrix that must have CV_32FC1 or CV_64FC1 type, square size and be symmetrical +(src ^T^ == src). +@param eigenvalues output vector of eigenvalues of the same type as src; the eigenvalues are stored +in the descending order. +@param eigenvectors output matrix of eigenvectors; it has the same size and type as src; the +eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding +eigenvalues. +@sa eigenNonSymmetric, completeSymm, PCA +*/ +CV_EXPORTS_W bool eigen(InputArray src, OutputArray eigenvalues, + OutputArray eigenvectors = noArray()); + +/** @brief Calculates eigenvalues and eigenvectors of a non-symmetric matrix (real eigenvalues only). + +@note Assumes real eigenvalues. + +The function calculates eigenvalues and eigenvectors (optional) of the square matrix src: +@code + src*eigenvectors.row(i).t() = eigenvalues.at(i)*eigenvectors.row(i).t() +@endcode + +@param src input matrix (CV_32FC1 or CV_64FC1 type). +@param eigenvalues output vector of eigenvalues (type is the same type as src). +@param eigenvectors output matrix of eigenvectors (type is the same type as src). The eigenvectors are stored as subsequent matrix rows, in the same order as the corresponding eigenvalues. +@sa eigen +*/ +CV_EXPORTS_W void eigenNonSymmetric(InputArray src, OutputArray eigenvalues, + OutputArray eigenvectors); + +/** @brief Calculates the covariance matrix of a set of vectors. + +The function cv::calcCovarMatrix calculates the covariance matrix and, optionally, the mean vector of +the set of input vectors. +@param samples samples stored as separate matrices +@param nsamples number of samples +@param covar output covariance matrix of the type ctype and square size. +@param mean input or output (depending on the flags) array as the average value of the input vectors. +@param flags operation flags as a combination of #CovarFlags +@param ctype type of the matrixl; it equals 'CV_64F' by default. +@sa PCA, mulTransposed, Mahalanobis +@todo InputArrayOfArrays +*/ +CV_EXPORTS void calcCovarMatrix( const Mat* samples, int nsamples, Mat& covar, Mat& mean, + int flags, int ctype = CV_64F); + +/** @overload +@note use #COVAR_ROWS or #COVAR_COLS flag +@param samples samples stored as rows/columns of a single matrix. +@param covar output covariance matrix of the type ctype and square size. +@param mean input or output (depending on the flags) array as the average value of the input vectors. +@param flags operation flags as a combination of #CovarFlags +@param ctype type of the matrixl; it equals 'CV_64F' by default. +*/ +CV_EXPORTS_W void calcCovarMatrix( InputArray samples, OutputArray covar, + InputOutputArray mean, int flags, int ctype = CV_64F); + +/** wrap PCA::operator() */ +CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, int maxComponents = 0); + +/** wrap PCA::operator() and add eigenvalues output parameter */ +CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, OutputArray eigenvalues, + int maxComponents = 0); + +/** wrap PCA::operator() */ +CV_EXPORTS_W void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, double retainedVariance); + +/** wrap PCA::operator() and add eigenvalues output parameter */ +CV_EXPORTS_AS(PCACompute2) void PCACompute(InputArray data, InputOutputArray mean, + OutputArray eigenvectors, OutputArray eigenvalues, + double retainedVariance); + +/** wrap PCA::project */ +CV_EXPORTS_W void PCAProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result); + +/** wrap PCA::backProject */ +CV_EXPORTS_W void PCABackProject(InputArray data, InputArray mean, + InputArray eigenvectors, OutputArray result); + +/** wrap SVD::compute */ +CV_EXPORTS_W void SVDecomp( InputArray src, OutputArray w, OutputArray u, OutputArray vt, int flags = 0 ); + +/** wrap SVD::backSubst */ +CV_EXPORTS_W void SVBackSubst( InputArray w, InputArray u, InputArray vt, + InputArray rhs, OutputArray dst ); + +/** @brief Calculates the Mahalanobis distance between two vectors. + +The function cv::Mahalanobis calculates and returns the weighted distance between two vectors: +\f[d( \texttt{vec1} , \texttt{vec2} )= \sqrt{\sum_{i,j}{\texttt{icovar(i,j)}\cdot(\texttt{vec1}(I)-\texttt{vec2}(I))\cdot(\texttt{vec1(j)}-\texttt{vec2(j)})} }\f] +The covariance matrix may be calculated using the #calcCovarMatrix function and then inverted using +the invert function (preferably using the #DECOMP_SVD method, as the most accurate). +@param v1 first 1D input vector. +@param v2 second 1D input vector. +@param icovar inverse covariance matrix. +*/ +CV_EXPORTS_W double Mahalanobis(InputArray v1, InputArray v2, InputArray icovar); + +/** @brief Performs a forward or inverse Discrete Fourier transform of a 1D or 2D floating-point array. + +The function cv::dft performs one of the following: +- Forward the Fourier transform of a 1D vector of N elements: + \f[Y = F^{(N)} \cdot X,\f] + where \f$F^{(N)}_{jk}=\exp(-2\pi i j k/N)\f$ and \f$i=\sqrt{-1}\f$ +- Inverse the Fourier transform of a 1D vector of N elements: + \f[\begin{array}{l} X'= \left (F^{(N)} \right )^{-1} \cdot Y = \left (F^{(N)} \right )^* \cdot y \\ X = (1/N) \cdot X, \end{array}\f] + where \f$F^*=\left(\textrm{Re}(F^{(N)})-\textrm{Im}(F^{(N)})\right)^T\f$ +- Forward the 2D Fourier transform of a M x N matrix: + \f[Y = F^{(M)} \cdot X \cdot F^{(N)}\f] +- Inverse the 2D Fourier transform of a M x N matrix: + \f[\begin{array}{l} X'= \left (F^{(M)} \right )^* \cdot Y \cdot \left (F^{(N)} \right )^* \\ X = \frac{1}{M \cdot N} \cdot X' \end{array}\f] + +In case of real (single-channel) data, the output spectrum of the forward Fourier transform or input +spectrum of the inverse Fourier transform can be represented in a packed format called *CCS* +(complex-conjugate-symmetrical). It was borrowed from IPL (Intel\* Image Processing Library). Here +is how 2D *CCS* spectrum looks: +\f[\begin{bmatrix} Re Y_{0,0} & Re Y_{0,1} & Im Y_{0,1} & Re Y_{0,2} & Im Y_{0,2} & \cdots & Re Y_{0,N/2-1} & Im Y_{0,N/2-1} & Re Y_{0,N/2} \\ Re Y_{1,0} & Re Y_{1,1} & Im Y_{1,1} & Re Y_{1,2} & Im Y_{1,2} & \cdots & Re Y_{1,N/2-1} & Im Y_{1,N/2-1} & Re Y_{1,N/2} \\ Im Y_{1,0} & Re Y_{2,1} & Im Y_{2,1} & Re Y_{2,2} & Im Y_{2,2} & \cdots & Re Y_{2,N/2-1} & Im Y_{2,N/2-1} & Im Y_{1,N/2} \\ \hdotsfor{9} \\ Re Y_{M/2-1,0} & Re Y_{M-3,1} & Im Y_{M-3,1} & \hdotsfor{3} & Re Y_{M-3,N/2-1} & Im Y_{M-3,N/2-1}& Re Y_{M/2-1,N/2} \\ Im Y_{M/2-1,0} & Re Y_{M-2,1} & Im Y_{M-2,1} & \hdotsfor{3} & Re Y_{M-2,N/2-1} & Im Y_{M-2,N/2-1}& Im Y_{M/2-1,N/2} \\ Re Y_{M/2,0} & Re Y_{M-1,1} & Im Y_{M-1,1} & \hdotsfor{3} & Re Y_{M-1,N/2-1} & Im Y_{M-1,N/2-1}& Re Y_{M/2,N/2} \end{bmatrix}\f] + +In case of 1D transform of a real vector, the output looks like the first row of the matrix above. + +So, the function chooses an operation mode depending on the flags and size of the input array: +- If #DFT_ROWS is set or the input array has a single row or single column, the function + performs a 1D forward or inverse transform of each row of a matrix when #DFT_ROWS is set. + Otherwise, it performs a 2D transform. +- If the input array is real and #DFT_INVERSE is not set, the function performs a forward 1D or + 2D transform: + - When #DFT_COMPLEX_OUTPUT is set, the output is a complex matrix of the same size as + input. + - When #DFT_COMPLEX_OUTPUT is not set, the output is a real matrix of the same size as + input. In case of 2D transform, it uses the packed format as shown above. In case of a + single 1D transform, it looks like the first row of the matrix above. In case of + multiple 1D transforms (when using the #DFT_ROWS flag), each row of the output matrix + looks like the first row of the matrix above. +- If the input array is complex and either #DFT_INVERSE or #DFT_REAL_OUTPUT are not set, the + output is a complex array of the same size as input. The function performs a forward or + inverse 1D or 2D transform of the whole input array or each row of the input array + independently, depending on the flags DFT_INVERSE and DFT_ROWS. +- When #DFT_INVERSE is set and the input array is real, or it is complex but #DFT_REAL_OUTPUT + is set, the output is a real array of the same size as input. The function performs a 1D or 2D + inverse transformation of the whole input array or each individual row, depending on the flags + #DFT_INVERSE and #DFT_ROWS. + +If #DFT_SCALE is set, the scaling is done after the transformation. + +Unlike dct, the function supports arrays of arbitrary size. But only those arrays are processed +efficiently, whose sizes can be factorized in a product of small prime numbers (2, 3, and 5 in the +current implementation). Such an efficient DFT size can be calculated using the getOptimalDFTSize +method. + +The sample below illustrates how to calculate a DFT-based convolution of two 2D real arrays: +@code + void convolveDFT(InputArray A, InputArray B, OutputArray C) + { + // reallocate the output array if needed + C.create(abs(A.rows - B.rows)+1, abs(A.cols - B.cols)+1, A.type()); + Size dftSize; + // calculate the size of DFT transform + dftSize.width = getOptimalDFTSize(A.cols + B.cols - 1); + dftSize.height = getOptimalDFTSize(A.rows + B.rows - 1); + + // allocate temporary buffers and initialize them with 0's + Mat tempA(dftSize, A.type(), Scalar::all(0)); + Mat tempB(dftSize, B.type(), Scalar::all(0)); + + // copy A and B to the top-left corners of tempA and tempB, respectively + Mat roiA(tempA, Rect(0,0,A.cols,A.rows)); + A.copyTo(roiA); + Mat roiB(tempB, Rect(0,0,B.cols,B.rows)); + B.copyTo(roiB); + + // now transform the padded A & B in-place; + // use "nonzeroRows" hint for faster processing + dft(tempA, tempA, 0, A.rows); + dft(tempB, tempB, 0, B.rows); + + // multiply the spectrums; + // the function handles packed spectrum representations well + mulSpectrums(tempA, tempB, tempA); + + // transform the product back from the frequency domain. + // Even though all the result rows will be non-zero, + // you need only the first C.rows of them, and thus you + // pass nonzeroRows == C.rows + dft(tempA, tempA, DFT_INVERSE + DFT_SCALE, C.rows); + + // now copy the result back to C. + tempA(Rect(0, 0, C.cols, C.rows)).copyTo(C); + + // all the temporary buffers will be deallocated automatically + } +@endcode +To optimize this sample, consider the following approaches: +- Since nonzeroRows != 0 is passed to the forward transform calls and since A and B are copied to + the top-left corners of tempA and tempB, respectively, it is not necessary to clear the whole + tempA and tempB. It is only necessary to clear the tempA.cols - A.cols ( tempB.cols - B.cols) + rightmost columns of the matrices. +- This DFT-based convolution does not have to be applied to the whole big arrays, especially if B + is significantly smaller than A or vice versa. Instead, you can calculate convolution by parts. + To do this, you need to split the output array C into multiple tiles. For each tile, estimate + which parts of A and B are required to calculate convolution in this tile. If the tiles in C are + too small, the speed will decrease a lot because of repeated work. In the ultimate case, when + each tile in C is a single pixel, the algorithm becomes equivalent to the naive convolution + algorithm. If the tiles are too big, the temporary arrays tempA and tempB become too big and + there is also a slowdown because of bad cache locality. So, there is an optimal tile size + somewhere in the middle. +- If different tiles in C can be calculated in parallel and, thus, the convolution is done by + parts, the loop can be threaded. + +All of the above improvements have been implemented in #matchTemplate and #filter2D . Therefore, by +using them, you can get the performance even better than with the above theoretically optimal +implementation. Though, those two functions actually calculate cross-correlation, not convolution, +so you need to "flip" the second convolution operand B vertically and horizontally using flip . +@note +- An example using the discrete fourier transform can be found at + opencv_source_code/samples/cpp/dft.cpp +- (Python) An example using the dft functionality to perform Wiener deconvolution can be found + at opencv_source/samples/python/deconvolution.py +- (Python) An example rearranging the quadrants of a Fourier image can be found at + opencv_source/samples/python/dft.py +@param src input array that could be real or complex. +@param dst output array whose size and type depends on the flags . +@param flags transformation flags, representing a combination of the #DftFlags +@param nonzeroRows when the parameter is not zero, the function assumes that only the first +nonzeroRows rows of the input array (#DFT_INVERSE is not set) or only the first nonzeroRows of the +output array (#DFT_INVERSE is set) contain non-zeros, thus, the function can handle the rest of the +rows more efficiently and save some time; this technique is very useful for calculating array +cross-correlation or convolution using DFT. +@sa dct, getOptimalDFTSize, mulSpectrums, filter2D, matchTemplate, flip, cartToPolar, +magnitude, phase +*/ +CV_EXPORTS_W void dft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); + +/** @brief Calculates the inverse Discrete Fourier Transform of a 1D or 2D array. + +idft(src, dst, flags) is equivalent to dft(src, dst, flags | #DFT_INVERSE) . +@note None of dft and idft scales the result by default. So, you should pass #DFT_SCALE to one of +dft or idft explicitly to make these transforms mutually inverse. +@sa dft, dct, idct, mulSpectrums, getOptimalDFTSize +@param src input floating-point real or complex array. +@param dst output array whose size and type depend on the flags. +@param flags operation flags (see dft and #DftFlags). +@param nonzeroRows number of dst rows to process; the rest of the rows have undefined content (see +the convolution sample in dft description. +*/ +CV_EXPORTS_W void idft(InputArray src, OutputArray dst, int flags = 0, int nonzeroRows = 0); + +/** @brief Performs a forward or inverse discrete Cosine transform of 1D or 2D array. + +The function cv::dct performs a forward or inverse discrete Cosine transform (DCT) of a 1D or 2D +floating-point array: +- Forward Cosine transform of a 1D vector of N elements: + \f[Y = C^{(N)} \cdot X\f] + where + \f[C^{(N)}_{jk}= \sqrt{\alpha_j/N} \cos \left ( \frac{\pi(2k+1)j}{2N} \right )\f] + and + \f$\alpha_0=1\f$, \f$\alpha_j=2\f$ for *j \> 0*. +- Inverse Cosine transform of a 1D vector of N elements: + \f[X = \left (C^{(N)} \right )^{-1} \cdot Y = \left (C^{(N)} \right )^T \cdot Y\f] + (since \f$C^{(N)}\f$ is an orthogonal matrix, \f$C^{(N)} \cdot \left(C^{(N)}\right)^T = I\f$ ) +- Forward 2D Cosine transform of M x N matrix: + \f[Y = C^{(N)} \cdot X \cdot \left (C^{(N)} \right )^T\f] +- Inverse 2D Cosine transform of M x N matrix: + \f[X = \left (C^{(N)} \right )^T \cdot X \cdot C^{(N)}\f] + +The function chooses the mode of operation by looking at the flags and size of the input array: +- If (flags & #DCT_INVERSE) == 0, the function does a forward 1D or 2D transform. Otherwise, it + is an inverse 1D or 2D transform. +- If (flags & #DCT_ROWS) != 0, the function performs a 1D transform of each row. +- If the array is a single column or a single row, the function performs a 1D transform. +- If none of the above is true, the function performs a 2D transform. + +@note Currently dct supports even-size arrays (2, 4, 6 ...). For data analysis and approximation, you +can pad the array when necessary. +Also, the function performance depends very much, and not monotonically, on the array size (see +getOptimalDFTSize ). In the current implementation DCT of a vector of size N is calculated via DFT +of a vector of size N/2 . Thus, the optimal DCT size N1 \>= N can be calculated as: +@code + size_t getOptimalDCTSize(size_t N) { return 2*getOptimalDFTSize((N+1)/2); } + N1 = getOptimalDCTSize(N); +@endcode +@param src input floating-point array. +@param dst output array of the same size and type as src . +@param flags transformation flags as a combination of cv::DftFlags (DCT_*) +@sa dft, getOptimalDFTSize, idct +*/ +CV_EXPORTS_W void dct(InputArray src, OutputArray dst, int flags = 0); + +/** @brief Calculates the inverse Discrete Cosine Transform of a 1D or 2D array. + +idct(src, dst, flags) is equivalent to dct(src, dst, flags | DCT_INVERSE). +@param src input floating-point single-channel array. +@param dst output array of the same size and type as src. +@param flags operation flags. +@sa dct, dft, idft, getOptimalDFTSize +*/ +CV_EXPORTS_W void idct(InputArray src, OutputArray dst, int flags = 0); + +/** @brief Performs the per-element multiplication of two Fourier spectrums. + +The function cv::mulSpectrums performs the per-element multiplication of the two CCS-packed or complex +matrices that are results of a real or complex Fourier transform. + +The function, together with dft and idft, may be used to calculate convolution (pass conjB=false ) +or correlation (pass conjB=true ) of two arrays rapidly. When the arrays are complex, they are +simply multiplied (per element) with an optional conjugation of the second-array elements. When the +arrays are real, they are assumed to be CCS-packed (see dft for details). +@param a first input array. +@param b second input array of the same size and type as src1 . +@param c output array of the same size and type as src1 . +@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that +each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. +@param conjB optional flag that conjugates the second input array before the multiplication (true) +or not (false). +*/ +CV_EXPORTS_W void mulSpectrums(InputArray a, InputArray b, OutputArray c, + int flags, bool conjB = false); + +/** @brief Returns the optimal DFT size for a given vector size. + +DFT performance is not a monotonic function of a vector size. Therefore, when you calculate +convolution of two arrays or perform the spectral analysis of an array, it usually makes sense to +pad the input data with zeros to get a bit larger array that can be transformed much faster than the +original one. Arrays whose size is a power-of-two (2, 4, 8, 16, 32, ...) are the fastest to process. +Though, the arrays whose size is a product of 2's, 3's, and 5's (for example, 300 = 5\*5\*3\*2\*2) +are also processed quite efficiently. + +The function cv::getOptimalDFTSize returns the minimum number N that is greater than or equal to vecsize +so that the DFT of a vector of size N can be processed efficiently. In the current implementation N += 2 ^p^ \* 3 ^q^ \* 5 ^r^ for some integer p, q, r. + +The function returns a negative number if vecsize is too large (very close to INT_MAX ). + +While the function cannot be used directly to estimate the optimal vector size for DCT transform +(since the current DCT implementation supports only even-size vectors), it can be easily processed +as getOptimalDFTSize((vecsize+1)/2)\*2. +@param vecsize vector size. +@sa dft, dct, idft, idct, mulSpectrums +*/ +CV_EXPORTS_W int getOptimalDFTSize(int vecsize); + +/** @brief Returns the default random number generator. + +The function cv::theRNG returns the default random number generator. For each thread, there is a +separate random number generator, so you can use the function safely in multi-thread environments. +If you just need to get a single random number using this generator or initialize an array, you can +use randu or randn instead. But if you are going to generate many random numbers inside a loop, it +is much faster to use this function to retrieve the generator and then use RNG::operator _Tp() . +@sa RNG, randu, randn +*/ +CV_EXPORTS RNG& theRNG(); + +/** @brief Sets state of default random number generator. + +The function cv::setRNGSeed sets state of default random number generator to custom value. +@param seed new state for default random number generator +@sa RNG, randu, randn +*/ +CV_EXPORTS_W void setRNGSeed(int seed); + +/** @brief Generates a single uniformly-distributed random number or an array of random numbers. + +Non-template variant of the function fills the matrix dst with uniformly-distributed +random numbers from the specified range: +\f[\texttt{low} _c \leq \texttt{dst} (I)_c < \texttt{high} _c\f] +@param dst output array of random numbers; the array must be pre-allocated. +@param low inclusive lower boundary of the generated random numbers. +@param high exclusive upper boundary of the generated random numbers. +@sa RNG, randn, theRNG +*/ +CV_EXPORTS_W void randu(InputOutputArray dst, InputArray low, InputArray high); + +/** @brief Fills the array with normally distributed random numbers. + +The function cv::randn fills the matrix dst with normally distributed random numbers with the specified +mean vector and the standard deviation matrix. The generated random numbers are clipped to fit the +value range of the output array data type. +@param dst output array of random numbers; the array must be pre-allocated and have 1 to 4 channels. +@param mean mean value (expectation) of the generated random numbers. +@param stddev standard deviation of the generated random numbers; it can be either a vector (in +which case a diagonal standard deviation matrix is assumed) or a square matrix. +@sa RNG, randu +*/ +CV_EXPORTS_W void randn(InputOutputArray dst, InputArray mean, InputArray stddev); + +/** @brief Shuffles the array elements randomly. + +The function cv::randShuffle shuffles the specified 1D array by randomly choosing pairs of elements and +swapping them. The number of such swap operations will be dst.rows\*dst.cols\*iterFactor . +@param dst input/output numerical 1D array. +@param iterFactor scale factor that determines the number of random swap operations (see the details +below). +@param rng optional random number generator used for shuffling; if it is zero, theRNG () is used +instead. +@sa RNG, sort +*/ +CV_EXPORTS_W void randShuffle(InputOutputArray dst, double iterFactor = 1., RNG* rng = 0); + +/** @brief Principal Component Analysis + +The class is used to calculate a special basis for a set of vectors. The +basis will consist of eigenvectors of the covariance matrix calculated +from the input set of vectors. The class %PCA can also transform +vectors to/from the new coordinate space defined by the basis. Usually, +in this new coordinate system, each vector from the original set (and +any linear combination of such vectors) can be quite accurately +approximated by taking its first few components, corresponding to the +eigenvectors of the largest eigenvalues of the covariance matrix. +Geometrically it means that you calculate a projection of the vector to +a subspace formed by a few eigenvectors corresponding to the dominant +eigenvalues of the covariance matrix. And usually such a projection is +very close to the original vector. So, you can represent the original +vector from a high-dimensional space with a much shorter vector +consisting of the projected vector's coordinates in the subspace. Such a +transformation is also known as Karhunen-Loeve Transform, or KLT. +See http://en.wikipedia.org/wiki/Principal_component_analysis + +The sample below is the function that takes two matrices. The first +function stores a set of vectors (a row per vector) that is used to +calculate PCA. The second function stores another "test" set of vectors +(a row per vector). First, these vectors are compressed with PCA, then +reconstructed back, and then the reconstruction error norm is computed +and printed for each vector. : + +@code{.cpp} +using namespace cv; + +PCA compressPCA(const Mat& pcaset, int maxComponents, + const Mat& testset, Mat& compressed) +{ + PCA pca(pcaset, // pass the data + Mat(), // we do not have a pre-computed mean vector, + // so let the PCA engine to compute it + PCA::DATA_AS_ROW, // indicate that the vectors + // are stored as matrix rows + // (use PCA::DATA_AS_COL if the vectors are + // the matrix columns) + maxComponents // specify, how many principal components to retain + ); + // if there is no test data, just return the computed basis, ready-to-use + if( !testset.data ) + return pca; + CV_Assert( testset.cols == pcaset.cols ); + + compressed.create(testset.rows, maxComponents, testset.type()); + + Mat reconstructed; + for( int i = 0; i < testset.rows; i++ ) + { + Mat vec = testset.row(i), coeffs = compressed.row(i), reconstructed; + // compress the vector, the result will be stored + // in the i-th row of the output matrix + pca.project(vec, coeffs); + // and then reconstruct it + pca.backProject(coeffs, reconstructed); + // and measure the error + printf("%d. diff = %g\n", i, norm(vec, reconstructed, NORM_L2)); + } + return pca; +} +@endcode +@sa calcCovarMatrix, mulTransposed, SVD, dft, dct +*/ +class CV_EXPORTS PCA +{ +public: + enum Flags { DATA_AS_ROW = 0, //!< indicates that the input samples are stored as matrix rows + DATA_AS_COL = 1, //!< indicates that the input samples are stored as matrix columns + USE_AVG = 2 //! + }; + + /** @brief default constructor + + The default constructor initializes an empty %PCA structure. The other + constructors initialize the structure and call PCA::operator()(). + */ + PCA(); + + /** @overload + @param data input samples stored as matrix rows or matrix columns. + @param mean optional mean value; if the matrix is empty (@c noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout (PCA::Flags) + @param maxComponents maximum number of components that %PCA should + retain; by default, all the components are retained. + */ + PCA(InputArray data, InputArray mean, int flags, int maxComponents = 0); + + /** @overload + @param data input samples stored as matrix rows or matrix columns. + @param mean optional mean value; if the matrix is empty (noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout (PCA::Flags) + @param retainedVariance Percentage of variance that PCA should retain. + Using this parameter will let the PCA decided how many components to + retain but it will always keep at least 2. + */ + PCA(InputArray data, InputArray mean, int flags, double retainedVariance); + + /** @brief performs %PCA + + The operator performs %PCA of the supplied dataset. It is safe to reuse + the same PCA structure for multiple datasets. That is, if the structure + has been previously used with another dataset, the existing internal + data is reclaimed and the new @ref eigenvalues, @ref eigenvectors and @ref + mean are allocated and computed. + + The computed @ref eigenvalues are sorted from the largest to the smallest and + the corresponding @ref eigenvectors are stored as eigenvectors rows. + + @param data input samples stored as the matrix rows or as the matrix + columns. + @param mean optional mean value; if the matrix is empty (noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout. (Flags) + @param maxComponents maximum number of components that PCA should + retain; by default, all the components are retained. + */ + PCA& operator()(InputArray data, InputArray mean, int flags, int maxComponents = 0); + + /** @overload + @param data input samples stored as the matrix rows or as the matrix + columns. + @param mean optional mean value; if the matrix is empty (noArray()), + the mean is computed from the data. + @param flags operation flags; currently the parameter is only used to + specify the data layout. (PCA::Flags) + @param retainedVariance Percentage of variance that %PCA should retain. + Using this parameter will let the %PCA decided how many components to + retain but it will always keep at least 2. + */ + PCA& operator()(InputArray data, InputArray mean, int flags, double retainedVariance); + + /** @brief Projects vector(s) to the principal component subspace. + + The methods project one or more vectors to the principal component + subspace, where each vector projection is represented by coefficients in + the principal component basis. The first form of the method returns the + matrix that the second form writes to the result. So the first form can + be used as a part of expression while the second form can be more + efficient in a processing loop. + @param vec input vector(s); must have the same dimensionality and the + same layout as the input data used at %PCA phase, that is, if + DATA_AS_ROW are specified, then `vec.cols==data.cols` + (vector dimensionality) and `vec.rows` is the number of vectors to + project, and the same is true for the PCA::DATA_AS_COL case. + */ + Mat project(InputArray vec) const; + + /** @overload + @param vec input vector(s); must have the same dimensionality and the + same layout as the input data used at PCA phase, that is, if + DATA_AS_ROW are specified, then `vec.cols==data.cols` + (vector dimensionality) and `vec.rows` is the number of vectors to + project, and the same is true for the PCA::DATA_AS_COL case. + @param result output vectors; in case of PCA::DATA_AS_COL, the + output matrix has as many columns as the number of input vectors, this + means that `result.cols==vec.cols` and the number of rows match the + number of principal components (for example, `maxComponents` parameter + passed to the constructor). + */ + void project(InputArray vec, OutputArray result) const; + + /** @brief Reconstructs vectors from their PC projections. + + The methods are inverse operations to PCA::project. They take PC + coordinates of projected vectors and reconstruct the original vectors. + Unless all the principal components have been retained, the + reconstructed vectors are different from the originals. But typically, + the difference is small if the number of components is large enough (but + still much smaller than the original vector dimensionality). As a + result, PCA is used. + @param vec coordinates of the vectors in the principal component + subspace, the layout and size are the same as of PCA::project output + vectors. + */ + Mat backProject(InputArray vec) const; + + /** @overload + @param vec coordinates of the vectors in the principal component + subspace, the layout and size are the same as of PCA::project output + vectors. + @param result reconstructed vectors; the layout and size are the same as + of PCA::project input vectors. + */ + void backProject(InputArray vec, OutputArray result) const; + + /** @brief write PCA objects + + Writes @ref eigenvalues @ref eigenvectors and @ref mean to specified FileStorage + */ + void write(FileStorage& fs) const; + + /** @brief load PCA objects + + Loads @ref eigenvalues @ref eigenvectors and @ref mean from specified FileNode + */ + void read(const FileNode& fn); + + Mat eigenvectors; //!< eigenvectors of the covariation matrix + Mat eigenvalues; //!< eigenvalues of the covariation matrix + Mat mean; //!< mean value subtracted before the projection and added after the back projection +}; + +/** @example samples/cpp/pca.cpp +An example using %PCA for dimensionality reduction while maintaining an amount of variance +*/ + +/** @example samples/cpp/tutorial_code/ml/introduction_to_pca/introduction_to_pca.cpp +Check @ref tutorial_introduction_to_pca "the corresponding tutorial" for more details +*/ + +/** +@brief Linear Discriminant Analysis +@todo document this class +*/ +class CV_EXPORTS LDA +{ +public: + /** @brief constructor + Initializes a LDA with num_components (default 0). + */ + explicit LDA(int num_components = 0); + + /** Initializes and performs a Discriminant Analysis with Fisher's + Optimization Criterion on given data in src and corresponding labels + in labels. If 0 (or less) number of components are given, they are + automatically determined for given data in computation. + */ + LDA(InputArrayOfArrays src, InputArray labels, int num_components = 0); + + /** Serializes this object to a given filename. + */ + void save(const String& filename) const; + + /** Deserializes this object from a given filename. + */ + void load(const String& filename); + + /** Serializes this object to a given cv::FileStorage. + */ + void save(FileStorage& fs) const; + + /** Deserializes this object from a given cv::FileStorage. + */ + void load(const FileStorage& node); + + /** destructor + */ + ~LDA(); + + /** Compute the discriminants for data in src (row aligned) and labels. + */ + void compute(InputArrayOfArrays src, InputArray labels); + + /** Projects samples into the LDA subspace. + src may be one or more row aligned samples. + */ + Mat project(InputArray src); + + /** Reconstructs projections from the LDA subspace. + src may be one or more row aligned projections. + */ + Mat reconstruct(InputArray src); + + /** Returns the eigenvectors of this LDA. + */ + Mat eigenvectors() const { return _eigenvectors; } + + /** Returns the eigenvalues of this LDA. + */ + Mat eigenvalues() const { return _eigenvalues; } + + static Mat subspaceProject(InputArray W, InputArray mean, InputArray src); + static Mat subspaceReconstruct(InputArray W, InputArray mean, InputArray src); + +protected: + int _num_components; + Mat _eigenvectors; + Mat _eigenvalues; + void lda(InputArrayOfArrays src, InputArray labels); +}; + +/** @brief Singular Value Decomposition + +Class for computing Singular Value Decomposition of a floating-point +matrix. The Singular Value Decomposition is used to solve least-square +problems, under-determined linear systems, invert matrices, compute +condition numbers, and so on. + +If you want to compute a condition number of a matrix or an absolute value of +its determinant, you do not need `u` and `vt`. You can pass +flags=SVD::NO_UV|... . Another flag SVD::FULL_UV indicates that full-size u +and vt must be computed, which is not necessary most of the time. + +@sa invert, solve, eigen, determinant +*/ +class CV_EXPORTS SVD +{ +public: + enum Flags { + /** allow the algorithm to modify the decomposed matrix; it can save space and speed up + processing. currently ignored. */ + MODIFY_A = 1, + /** indicates that only a vector of singular values `w` is to be processed, while u and vt + will be set to empty matrices */ + NO_UV = 2, + /** when the matrix is not square, by default the algorithm produces u and vt matrices of + sufficiently large size for the further A reconstruction; if, however, FULL_UV flag is + specified, u and vt will be full-size square orthogonal matrices.*/ + FULL_UV = 4 + }; + + /** @brief the default constructor + + initializes an empty SVD structure + */ + SVD(); + + /** @overload + initializes an empty SVD structure and then calls SVD::operator() + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param flags operation flags (SVD::Flags) + */ + SVD( InputArray src, int flags = 0 ); + + /** @brief the operator that performs SVD. The previously allocated u, w and vt are released. + + The operator performs the singular value decomposition of the supplied + matrix. The u,`vt` , and the vector of singular values w are stored in + the structure. The same SVD structure can be reused many times with + different matrices. Each time, if needed, the previous u,`vt` , and w + are reclaimed and the new matrices are created, which is all handled by + Mat::create. + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param flags operation flags (SVD::Flags) + */ + SVD& operator ()( InputArray src, int flags = 0 ); + + /** @brief decomposes matrix and stores the results to user-provided matrices + + The methods/functions perform SVD of matrix. Unlike SVD::SVD constructor + and SVD::operator(), they store the results to the user-provided + matrices: + + @code{.cpp} + Mat A, w, u, vt; + SVD::compute(A, w, u, vt); + @endcode + + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param w calculated singular values + @param u calculated left singular vectors + @param vt transposed matrix of right singular vectors + @param flags operation flags - see SVD::Flags. + */ + static void compute( InputArray src, OutputArray w, + OutputArray u, OutputArray vt, int flags = 0 ); + + /** @overload + computes singular values of a matrix + @param src decomposed matrix. The depth has to be CV_32F or CV_64F. + @param w calculated singular values + @param flags operation flags - see SVD::Flags. + */ + static void compute( InputArray src, OutputArray w, int flags = 0 ); + + /** @brief performs back substitution + */ + static void backSubst( InputArray w, InputArray u, + InputArray vt, InputArray rhs, + OutputArray dst ); + + /** @brief solves an under-determined singular linear system + + The method finds a unit-length solution x of a singular linear system + A\*x = 0. Depending on the rank of A, there can be no solutions, a + single solution or an infinite number of solutions. In general, the + algorithm solves the following problem: + \f[dst = \arg \min _{x: \| x \| =1} \| src \cdot x \|\f] + @param src left-hand-side matrix. + @param dst found solution. + */ + static void solveZ( InputArray src, OutputArray dst ); + + /** @brief performs a singular value back substitution. + + The method calculates a back substitution for the specified right-hand + side: + + \f[\texttt{x} = \texttt{vt} ^T \cdot diag( \texttt{w} )^{-1} \cdot \texttt{u} ^T \cdot \texttt{rhs} \sim \texttt{A} ^{-1} \cdot \texttt{rhs}\f] + + Using this technique you can either get a very accurate solution of the + convenient linear system, or the best (in the least-squares terms) + pseudo-solution of an overdetermined linear system. + + @param rhs right-hand side of a linear system (u\*w\*v')\*dst = rhs to + be solved, where A has been previously decomposed. + + @param dst found solution of the system. + + @note Explicit SVD with the further back substitution only makes sense + if you need to solve many linear systems with the same left-hand side + (for example, src ). If all you need is to solve a single system + (possibly with multiple rhs immediately available), simply call solve + add pass #DECOMP_SVD there. It does absolutely the same thing. + */ + void backSubst( InputArray rhs, OutputArray dst ) const; + + /** @todo document */ + template static + void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ); + + /** @todo document */ + template static + void compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ); + + /** @todo document */ + template static + void backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, Matx<_Tp, n, nb>& dst ); + + Mat u, w, vt; +}; + +/** @brief Random Number Generator + +Random number generator. It encapsulates the state (currently, a 64-bit +integer) and has methods to return scalar random values and to fill +arrays with random values. Currently it supports uniform and Gaussian +(normal) distributions. The generator uses Multiply-With-Carry +algorithm, introduced by G. Marsaglia ( + ). +Gaussian-distribution random numbers are generated using the Ziggurat +algorithm ( ), +introduced by G. Marsaglia and W. W. Tsang. +*/ +class CV_EXPORTS RNG +{ +public: + enum { UNIFORM = 0, + NORMAL = 1 + }; + + /** @brief constructor + + These are the RNG constructors. The first form sets the state to some + pre-defined value, equal to 2\*\*32-1 in the current implementation. The + second form sets the state to the specified value. If you passed state=0 + , the constructor uses the above default value instead to avoid the + singular random number sequence, consisting of all zeros. + */ + RNG(); + /** @overload + @param state 64-bit value used to initialize the RNG. + */ + RNG(uint64 state); + /**The method updates the state using the MWC algorithm and returns the + next 32-bit random number.*/ + unsigned next(); + + /**Each of the methods updates the state using the MWC algorithm and + returns the next random number of the specified type. In case of integer + types, the returned number is from the available value range for the + specified type. In case of floating-point types, the returned value is + from [0,1) range. + */ + operator uchar(); + /** @overload */ + operator schar(); + /** @overload */ + operator ushort(); + /** @overload */ + operator short(); + /** @overload */ + operator unsigned(); + /** @overload */ + operator int(); + /** @overload */ + operator float(); + /** @overload */ + operator double(); + + /** @brief returns a random integer sampled uniformly from [0, N). + + The methods transform the state using the MWC algorithm and return the + next random number. The first form is equivalent to RNG::next . The + second form returns the random number modulo N, which means that the + result is in the range [0, N) . + */ + unsigned operator ()(); + /** @overload + @param N upper non-inclusive boundary of the returned random number. + */ + unsigned operator ()(unsigned N); + + /** @brief returns uniformly distributed integer random number from [a,b) range + + The methods transform the state using the MWC algorithm and return the + next uniformly-distributed random number of the specified type, deduced + from the input parameter type, from the range [a, b) . There is a nuance + illustrated by the following sample: + + @code{.cpp} + RNG rng; + + // always produces 0 + double a = rng.uniform(0, 1); + + // produces double from [0, 1) + double a1 = rng.uniform((double)0, (double)1); + + // produces float from [0, 1) + float b = rng.uniform(0.f, 1.f); + + // produces double from [0, 1) + double c = rng.uniform(0., 1.); + + // may cause compiler error because of ambiguity: + // RNG::uniform(0, (int)0.999999)? or RNG::uniform((double)0, 0.99999)? + double d = rng.uniform(0, 0.999999); + @endcode + + The compiler does not take into account the type of the variable to + which you assign the result of RNG::uniform . The only thing that + matters to the compiler is the type of a and b parameters. So, if you + want a floating-point random number, but the range boundaries are + integer numbers, either put dots in the end, if they are constants, or + use explicit type cast operators, as in the a1 initialization above. + @param a lower inclusive boundary of the returned random number. + @param b upper non-inclusive boundary of the returned random number. + */ + int uniform(int a, int b); + /** @overload */ + float uniform(float a, float b); + /** @overload */ + double uniform(double a, double b); + + /** @brief Fills arrays with random numbers. + + @param mat 2D or N-dimensional matrix; currently matrices with more than + 4 channels are not supported by the methods, use Mat::reshape as a + possible workaround. + @param distType distribution type, RNG::UNIFORM or RNG::NORMAL. + @param a first distribution parameter; in case of the uniform + distribution, this is an inclusive lower boundary, in case of the normal + distribution, this is a mean value. + @param b second distribution parameter; in case of the uniform + distribution, this is a non-inclusive upper boundary, in case of the + normal distribution, this is a standard deviation (diagonal of the + standard deviation matrix or the full standard deviation matrix). + @param saturateRange pre-saturation flag; for uniform distribution only; + if true, the method will first convert a and b to the acceptable value + range (according to the mat datatype) and then will generate uniformly + distributed random numbers within the range [saturate(a), saturate(b)), + if saturateRange=false, the method will generate uniformly distributed + random numbers in the original range [a, b) and then will saturate them, + it means, for example, that + theRNG().fill(mat_8u, RNG::UNIFORM, -DBL_MAX, DBL_MAX) will likely + produce array mostly filled with 0's and 255's, since the range (0, 255) + is significantly smaller than [-DBL_MAX, DBL_MAX). + + Each of the methods fills the matrix with the random values from the + specified distribution. As the new numbers are generated, the RNG state + is updated accordingly. In case of multiple-channel images, every + channel is filled independently, which means that RNG cannot generate + samples from the multi-dimensional Gaussian distribution with + non-diagonal covariance matrix directly. To do that, the method + generates samples from multi-dimensional standard Gaussian distribution + with zero mean and identity covariation matrix, and then transforms them + using transform to get samples from the specified Gaussian distribution. + */ + void fill( InputOutputArray mat, int distType, InputArray a, InputArray b, bool saturateRange = false ); + + /** @brief Returns the next random number sampled from the Gaussian distribution + @param sigma standard deviation of the distribution. + + The method transforms the state using the MWC algorithm and returns the + next random number from the Gaussian distribution N(0,sigma) . That is, + the mean value of the returned random numbers is zero and the standard + deviation is the specified sigma . + */ + double gaussian(double sigma); + + uint64 state; + + bool operator ==(const RNG& other) const; +}; + +/** @brief Mersenne Twister random number generator + +Inspired by http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/MT2002/CODES/mt19937ar.c +@todo document +*/ +class CV_EXPORTS RNG_MT19937 +{ +public: + RNG_MT19937(); + RNG_MT19937(unsigned s); + void seed(unsigned s); + + unsigned next(); + + operator int(); + operator unsigned(); + operator float(); + operator double(); + + unsigned operator ()(unsigned N); + unsigned operator ()(); + + /** @brief returns uniformly distributed integer random number from [a,b) range*/ + int uniform(int a, int b); + /** @brief returns uniformly distributed floating-point random number from [a,b) range*/ + float uniform(float a, float b); + /** @brief returns uniformly distributed double-precision floating-point random number from [a,b) range*/ + double uniform(double a, double b); + +private: + enum PeriodParameters {N = 624, M = 397}; + unsigned state[N]; + int mti; +}; + +//! @} core_array + +//! @addtogroup core_cluster +//! @{ + +//! k-means flags +enum KmeansFlags { + /** Select random initial centers in each attempt.*/ + KMEANS_RANDOM_CENTERS = 0, + /** Use kmeans++ center initialization by Arthur and Vassilvitskii [Arthur2007].*/ + KMEANS_PP_CENTERS = 2, + /** During the first (and possibly the only) attempt, use the + user-supplied labels instead of computing them from the initial centers. For the second and + further attempts, use the random or semi-random centers. Use one of KMEANS_\*_CENTERS flag + to specify the exact method.*/ + KMEANS_USE_INITIAL_LABELS = 1 +}; + +/** @example samples/cpp/kmeans.cpp +An example on k-means clustering +*/ + +/** @brief Finds centers of clusters and groups input samples around the clusters. + +The function kmeans implements a k-means algorithm that finds the centers of cluster_count clusters +and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ contains a +0-based cluster index for the sample stored in the \f$i^{th}\f$ row of the samples matrix. + +@note +- (Python) An example on k-means clustering can be found at + opencv_source_code/samples/python/kmeans.py +@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. +Examples of this array can be: +- Mat points(count, 2, CV_32F); +- Mat points(count, 1, CV_32FC2); +- Mat points(1, count, CV_32FC2); +- std::vector\ points(sampleCount); +@param K Number of clusters to split the set by. +@param bestLabels Input/output integer array that stores the cluster indices for every sample. +@param criteria The algorithm termination criteria, that is, the maximum number of iterations and/or +the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of the cluster +centers moves by less than criteria.epsilon on some iteration, the algorithm stops. +@param attempts Flag to specify the number of times the algorithm is executed using different +initial labellings. The algorithm returns the labels that yield the best compactness (see the last +function parameter). +@param flags Flag that can take values of cv::KmeansFlags +@param centers Output matrix of the cluster centers, one row per each cluster center. +@return The function returns the compactness measure that is computed as +\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] +after every attempt. The best (minimum) value is chosen and the corresponding labels and the +compactness value are returned by the function. Basically, you can use only the core of the +function, set the number of attempts to 1, initialize labels each time using a custom algorithm, +pass them with the ( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best +(most-compact) clustering. +*/ +CV_EXPORTS_W double kmeans( InputArray data, int K, InputOutputArray bestLabels, + TermCriteria criteria, int attempts, + int flags, OutputArray centers = noArray() ); + +//! @} core_cluster + +//! @addtogroup core_basic +//! @{ + +/////////////////////////////// Formatted output of cv::Mat /////////////////////////// + +/** @todo document */ +class CV_EXPORTS Formatted +{ +public: + virtual const char* next() = 0; + virtual void reset() = 0; + virtual ~Formatted(); +}; + +/** @todo document */ +class CV_EXPORTS Formatter +{ +public: + enum FormatType { + FMT_DEFAULT = 0, + FMT_MATLAB = 1, + FMT_CSV = 2, + FMT_PYTHON = 3, + FMT_NUMPY = 4, + FMT_C = 5 + }; + + virtual ~Formatter(); + + virtual Ptr format(const Mat& mtx) const = 0; + + virtual void set16fPrecision(int p = 4) = 0; + virtual void set32fPrecision(int p = 8) = 0; + virtual void set64fPrecision(int p = 16) = 0; + virtual void setMultiline(bool ml = true) = 0; + + static Ptr get(Formatter::FormatType fmt = FMT_DEFAULT); + +}; + +static inline +String& operator << (String& out, Ptr fmtd) +{ + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + out += cv::String(str); + return out; +} + +static inline +String& operator << (String& out, const Mat& mtx) +{ + return out << Formatter::get()->format(mtx); +} + +//////////////////////////////////////// Algorithm //////////////////////////////////// + +class CV_EXPORTS Algorithm; + +template struct ParamType {}; + + +/** @brief This is a base class for all more or less complex algorithms in OpenCV + +especially for classes of algorithms, for which there can be multiple implementations. The examples +are stereo correspondence (for which there are algorithms like block matching, semi-global block +matching, graph-cut etc.), background subtraction (which can be done using mixture-of-gaussians +models, codebook-based algorithm etc.), optical flow (block matching, Lucas-Kanade, Horn-Schunck +etc.). + +Here is example of SimpleBlobDetector use in your application via Algorithm interface: +@snippet snippets/core_various.cpp Algorithm +*/ +class CV_EXPORTS_W Algorithm +{ +public: + Algorithm(); + virtual ~Algorithm(); + + /** @brief Clears the algorithm state + */ + CV_WRAP virtual void clear() {} + + /** @brief Stores algorithm parameters in a file storage + */ + CV_WRAP virtual void write(FileStorage& fs) const { CV_UNUSED(fs); } + + /** + * @overload + */ + CV_WRAP void write(FileStorage& fs, const String& name) const; +#if CV_VERSION_MAJOR < 5 + /** @deprecated */ + void write(const Ptr& fs, const String& name = String()) const; +#endif + + /** @brief Reads algorithm parameters from a file storage + */ + CV_WRAP virtual void read(const FileNode& fn) { CV_UNUSED(fn); } + + /** @brief Returns true if the Algorithm is empty (e.g. in the very beginning or after unsuccessful read + */ + CV_WRAP virtual bool empty() const { return false; } + + /** @brief Reads algorithm from the file node + + This is static template method of Algorithm. It's usage is following (in the case of SVM): + @code + cv::FileStorage fsRead("example.xml", FileStorage::READ); + Ptr svm = Algorithm::read(fsRead.root()); + @endcode + In order to make this method work, the derived class must overwrite Algorithm::read(const + FileNode& fn) and also have static create() method without parameters + (or with all the optional parameters) + */ + template static Ptr<_Tp> read(const FileNode& fn) + { + Ptr<_Tp> obj = _Tp::create(); + obj->read(fn); + return !obj->empty() ? obj : Ptr<_Tp>(); + } + + /** @brief Loads algorithm from the file + + @param filename Name of the file to read. + @param objname The optional name of the node to read (if empty, the first top-level node will be used) + + This is static template method of Algorithm. It's usage is following (in the case of SVM): + @code + Ptr svm = Algorithm::load("my_svm_model.xml"); + @endcode + In order to make this method work, the derived class must overwrite Algorithm::read(const + FileNode& fn). + */ + template static Ptr<_Tp> load(const String& filename, const String& objname=String()) + { + FileStorage fs(filename, FileStorage::READ); + CV_Assert(fs.isOpened()); + FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; + if (fn.empty()) return Ptr<_Tp>(); + Ptr<_Tp> obj = _Tp::create(); + obj->read(fn); + return !obj->empty() ? obj : Ptr<_Tp>(); + } + + /** @brief Loads algorithm from a String + + @param strModel The string variable containing the model you want to load. + @param objname The optional name of the node to read (if empty, the first top-level node will be used) + + This is static template method of Algorithm. It's usage is following (in the case of SVM): + @code + Ptr svm = Algorithm::loadFromString(myStringModel); + @endcode + */ + template static Ptr<_Tp> loadFromString(const String& strModel, const String& objname=String()) + { + FileStorage fs(strModel, FileStorage::READ + FileStorage::MEMORY); + FileNode fn = objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]; + Ptr<_Tp> obj = _Tp::create(); + obj->read(fn); + return !obj->empty() ? obj : Ptr<_Tp>(); + } + + /** Saves the algorithm to a file. + In order to make this method work, the derived class must implement Algorithm::write(FileStorage& fs). */ + CV_WRAP virtual void save(const String& filename) const; + + /** Returns the algorithm string identifier. + This string is used as top level xml/yml node tag when the object is saved to a file or string. */ + CV_WRAP virtual String getDefaultName() const; + +protected: + void writeFormat(FileStorage& fs) const; +}; + +enum struct Param { + INT=0, BOOLEAN=1, REAL=2, STRING=3, MAT=4, MAT_VECTOR=5, ALGORITHM=6, FLOAT=7, + UNSIGNED_INT=8, UINT64=9, UCHAR=11, SCALAR=12 +}; + + + +template<> struct ParamType +{ + typedef bool const_param_type; + typedef bool member_type; + + static const Param type = Param::BOOLEAN; +}; + +template<> struct ParamType +{ + typedef int const_param_type; + typedef int member_type; + + static const Param type = Param::INT; +}; + +template<> struct ParamType +{ + typedef double const_param_type; + typedef double member_type; + + static const Param type = Param::REAL; +}; + +template<> struct ParamType +{ + typedef const String& const_param_type; + typedef String member_type; + + static const Param type = Param::STRING; +}; + +template<> struct ParamType +{ + typedef const Mat& const_param_type; + typedef Mat member_type; + + static const Param type = Param::MAT; +}; + +template<> struct ParamType > +{ + typedef const std::vector& const_param_type; + typedef std::vector member_type; + + static const Param type = Param::MAT_VECTOR; +}; + +template<> struct ParamType +{ + typedef const Ptr& const_param_type; + typedef Ptr member_type; + + static const Param type = Param::ALGORITHM; +}; + +template<> struct ParamType +{ + typedef float const_param_type; + typedef float member_type; + + static const Param type = Param::FLOAT; +}; + +template<> struct ParamType +{ + typedef unsigned const_param_type; + typedef unsigned member_type; + + static const Param type = Param::UNSIGNED_INT; +}; + +template<> struct ParamType +{ + typedef uint64 const_param_type; + typedef uint64 member_type; + + static const Param type = Param::UINT64; +}; + +template<> struct ParamType +{ + typedef uchar const_param_type; + typedef uchar member_type; + + static const Param type = Param::UCHAR; +}; + +template<> struct ParamType +{ + typedef const Scalar& const_param_type; + typedef Scalar member_type; + + static const Param type = Param::SCALAR; +}; + +template +struct ParamType<_Tp, typename std::enable_if< std::is_enum<_Tp>::value >::type> +{ + typedef typename std::underlying_type<_Tp>::type const_param_type; + typedef typename std::underlying_type<_Tp>::type member_type; + + static const Param type = Param::INT; +}; + +//! @} core_basic + +} //namespace cv + +#include "opencv2/core/operations.hpp" +#include "opencv2/core/cvstd.inl.hpp" +#include "opencv2/core/utility.hpp" +#include "opencv2/core/optim.hpp" +#include "opencv2/core/ovx.hpp" + +#endif /*OPENCV_CORE_HPP*/ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp b/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp index bb5774231c..1aebf2b507 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/affine.hpp @@ -1,678 +1,678 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_AFFINE3_HPP -#define OPENCV_CORE_AFFINE3_HPP - -#ifdef __cplusplus - -#include - -namespace cv -{ - -//! @addtogroup core_eigen -//! @{ - - /** @brief Affine transform - * - * It represents a 4x4 homogeneous transformation matrix \f$T\f$ - * - * \f[T = - * \begin{bmatrix} - * R & t\\ - * 0 & 1\\ - * \end{bmatrix} - * \f] - * - * where \f$R\f$ is a 3x3 rotation matrix and \f$t\f$ is a 3x1 translation vector. - * - * You can specify \f$R\f$ either by a 3x3 rotation matrix or by a 3x1 rotation vector, - * which is converted to a 3x3 rotation matrix by the Rodrigues formula. - * - * To construct a matrix \f$T\f$ representing first rotation around the axis \f$r\f$ with rotation - * angle \f$|r|\f$ in radian (right hand rule) and then translation by the vector \f$t\f$, you can use - * - * @code - * cv::Vec3f r, t; - * cv::Affine3f T(r, t); - * @endcode - * - * If you already have the rotation matrix \f$R\f$, then you can use - * - * @code - * cv::Matx33f R; - * cv::Affine3f T(R, t); - * @endcode - * - * To extract the rotation matrix \f$R\f$ from \f$T\f$, use - * - * @code - * cv::Matx33f R = T.rotation(); - * @endcode - * - * To extract the translation vector \f$t\f$ from \f$T\f$, use - * - * @code - * cv::Vec3f t = T.translation(); - * @endcode - * - * To extract the rotation vector \f$r\f$ from \f$T\f$, use - * - * @code - * cv::Vec3f r = T.rvec(); - * @endcode - * - * Note that since the mapping from rotation vectors to rotation matrices - * is many to one. The returned rotation vector is not necessarily the one - * you used before to set the matrix. - * - * If you have two transformations \f$T = T_1 * T_2\f$, use - * - * @code - * cv::Affine3f T, T1, T2; - * T = T2.concatenate(T1); - * @endcode - * - * To get the inverse transform of \f$T\f$, use - * - * @code - * cv::Affine3f T, T_inv; - * T_inv = T.inv(); - * @endcode - * - */ - template - class Affine3 - { - public: - typedef T float_type; - typedef Matx Mat3; - typedef Matx Mat4; - typedef Vec Vec3; - - //! Default constructor. It represents a 4x4 identity matrix. - Affine3(); - - //! Augmented affine matrix - Affine3(const Mat4& affine); - - /** - * The resulting 4x4 matrix is - * - * \f[ - * \begin{bmatrix} - * R & t\\ - * 0 & 1\\ - * \end{bmatrix} - * \f] - * - * @param R 3x3 rotation matrix. - * @param t 3x1 translation vector. - */ - Affine3(const Mat3& R, const Vec3& t = Vec3::all(0)); - - /** - * Rodrigues vector. - * - * The last row of the current matrix is set to [0,0,0,1]. - * - * @param rvec 3x1 rotation vector. Its direction indicates the rotation axis and its length - * indicates the rotation angle in radian (using right hand rule). - * @param t 3x1 translation vector. - */ - Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0)); - - /** - * Combines all constructors above. Supports 4x4, 3x4, 3x3, 1x3, 3x1 sizes of data matrix. - * - * The last row of the current matrix is set to [0,0,0,1] when data is not 4x4. - * - * @param data 1-channel matrix. - * when it is 4x4, it is copied to the current matrix and t is not used. - * When it is 3x4, it is copied to the upper part 3x4 of the current matrix and t is not used. - * When it is 3x3, it is copied to the upper left 3x3 part of the current matrix. - * When it is 3x1 or 1x3, it is treated as a rotation vector and the Rodrigues formula is used - * to compute a 3x3 rotation matrix. - * @param t 3x1 translation vector. It is used only when data is neither 4x4 nor 3x4. - */ - explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0)); - - //! From 16-element array - explicit Affine3(const float_type* vals); - - //! Create an 4x4 identity transform - static Affine3 Identity(); - - /** - * Rotation matrix. - * - * Copy the rotation matrix to the upper left 3x3 part of the current matrix. - * The remaining elements of the current matrix are not changed. - * - * @param R 3x3 rotation matrix. - * - */ - void rotation(const Mat3& R); - - /** - * Rodrigues vector. - * - * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. - * - * @param rvec 3x1 rotation vector. The direction indicates the rotation axis and - * its length indicates the rotation angle in radian (using the right thumb convention). - */ - void rotation(const Vec3& rvec); - - /** - * Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix. - * - * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. - * - * @param data 1-channel matrix. - * When it is a 3x3 matrix, it sets the upper left 3x3 part of the current matrix. - * When it is a 1x3 or 3x1 matrix, it is used as a rotation vector. The Rodrigues formula - * is used to compute the rotation matrix and sets the upper left 3x3 part of the current matrix. - */ - void rotation(const Mat& data); - - /** - * Copy the 3x3 matrix L to the upper left part of the current matrix - * - * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. - * - * @param L 3x3 matrix. - */ - void linear(const Mat3& L); - - /** - * Copy t to the first three elements of the last column of the current matrix - * - * It sets the upper right 3x1 part of the matrix. The remaining part is unaffected. - * - * @param t 3x1 translation vector. - */ - void translation(const Vec3& t); - - //! @return the upper left 3x3 part - Mat3 rotation() const; - - //! @return the upper left 3x3 part - Mat3 linear() const; - - //! @return the upper right 3x1 part - Vec3 translation() const; - - //! Rodrigues vector. - //! @return a vector representing the upper left 3x3 rotation matrix of the current matrix. - //! @warning Since the mapping between rotation vectors and rotation matrices is many to one, - //! this function returns only one rotation vector that represents the current rotation matrix, - //! which is not necessarily the same one set by `rotation(const Vec3& rvec)`. - Vec3 rvec() const; - - //! @return the inverse of the current matrix. - Affine3 inv(int method = cv::DECOMP_SVD) const; - - //! a.rotate(R) is equivalent to Affine(R, 0) * a; - Affine3 rotate(const Mat3& R) const; - - //! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a; - Affine3 rotate(const Vec3& rvec) const; - - //! a.translate(t) is equivalent to Affine(E, t) * a, where E is an identity matrix - Affine3 translate(const Vec3& t) const; - - //! a.concatenate(affine) is equivalent to affine * a; - Affine3 concatenate(const Affine3& affine) const; - - template operator Affine3() const; - - template Affine3 cast() const; - - Mat4 matrix; - -#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H - Affine3(const Eigen::Transform& affine); - Affine3(const Eigen::Transform& affine); - operator Eigen::Transform() const; - operator Eigen::Transform() const; -#endif - }; - - template static - Affine3 operator*(const Affine3& affine1, const Affine3& affine2); - - //! V is a 3-element vector with member fields x, y and z - template static - V operator*(const Affine3& affine, const V& vector); - - typedef Affine3 Affine3f; - typedef Affine3 Affine3d; - - static Vec3f operator*(const Affine3f& affine, const Vec3f& vector); - static Vec3d operator*(const Affine3d& affine, const Vec3d& vector); - - template class DataType< Affine3<_Tp> > - { - public: - typedef Affine3<_Tp> value_type; - typedef Affine3::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 16, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; - }; - - namespace traits { - template - struct Depth< Affine3<_Tp> > { enum { value = Depth<_Tp>::value }; }; - template - struct Type< Affine3<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 16) }; }; - } // namespace - -//! @} core - -} - -//! @cond IGNORED - -/////////////////////////////////////////////////////////////////////////////////// -// Implementation - -template inline -cv::Affine3::Affine3() - : matrix(Mat4::eye()) -{} - -template inline -cv::Affine3::Affine3(const Mat4& affine) - : matrix(affine) -{} - -template inline -cv::Affine3::Affine3(const Mat3& R, const Vec3& t) -{ - rotation(R); - translation(t); - matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; - matrix.val[15] = 1; -} - -template inline -cv::Affine3::Affine3(const Vec3& _rvec, const Vec3& t) -{ - rotation(_rvec); - translation(t); - matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; - matrix.val[15] = 1; -} - -template inline -cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) -{ - CV_Assert(data.type() == cv::traits::Type::value); - CV_Assert(data.channels() == 1); - - if (data.cols == 4 && data.rows == 4) - { - data.copyTo(matrix); - return; - } - else if (data.cols == 4 && data.rows == 3) - { - rotation(data(Rect(0, 0, 3, 3))); - translation(data(Rect(3, 0, 1, 3))); - } - else - { - rotation(data); - translation(t); - } - - matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; - matrix.val[15] = 1; -} - -template inline -cv::Affine3::Affine3(const float_type* vals) : matrix(vals) -{} - -template inline -cv::Affine3 cv::Affine3::Identity() -{ - return Affine3(cv::Affine3::Mat4::eye()); -} - -template inline -void cv::Affine3::rotation(const Mat3& R) -{ - linear(R); -} - -template inline -void cv::Affine3::rotation(const Vec3& _rvec) -{ - double theta = norm(_rvec); - - if (theta < DBL_EPSILON) - rotation(Mat3::eye()); - else - { - double c = std::cos(theta); - double s = std::sin(theta); - double c1 = 1. - c; - double itheta = (theta != 0) ? 1./theta : 0.; - - Point3_ r = _rvec*itheta; - - Mat3 rrt( r.x*r.x, r.x*r.y, r.x*r.z, r.x*r.y, r.y*r.y, r.y*r.z, r.x*r.z, r.y*r.z, r.z*r.z ); - Mat3 r_x( 0, -r.z, r.y, r.z, 0, -r.x, -r.y, r.x, 0 ); - - // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] - // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] - Mat3 R = c*Mat3::eye() + c1*rrt + s*r_x; - - rotation(R); - } -} - -//Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix; -template inline -void cv::Affine3::rotation(const cv::Mat& data) -{ - CV_Assert(data.type() == cv::traits::Type::value); - CV_Assert(data.channels() == 1); - - if (data.cols == 3 && data.rows == 3) - { - Mat3 R; - data.copyTo(R); - rotation(R); - } - else if ((data.cols == 3 && data.rows == 1) || (data.cols == 1 && data.rows == 3)) - { - Vec3 _rvec; - data.reshape(1, 3).copyTo(_rvec); - rotation(_rvec); - } - else - CV_Error(Error::StsError, "Input matrix can only be 3x3, 1x3 or 3x1"); -} - -template inline -void cv::Affine3::linear(const Mat3& L) -{ - matrix.val[0] = L.val[0]; matrix.val[1] = L.val[1]; matrix.val[ 2] = L.val[2]; - matrix.val[4] = L.val[3]; matrix.val[5] = L.val[4]; matrix.val[ 6] = L.val[5]; - matrix.val[8] = L.val[6]; matrix.val[9] = L.val[7]; matrix.val[10] = L.val[8]; -} - -template inline -void cv::Affine3::translation(const Vec3& t) -{ - matrix.val[3] = t[0]; matrix.val[7] = t[1]; matrix.val[11] = t[2]; -} - -template inline -typename cv::Affine3::Mat3 cv::Affine3::rotation() const -{ - return linear(); -} - -template inline -typename cv::Affine3::Mat3 cv::Affine3::linear() const -{ - typename cv::Affine3::Mat3 R; - R.val[0] = matrix.val[0]; R.val[1] = matrix.val[1]; R.val[2] = matrix.val[ 2]; - R.val[3] = matrix.val[4]; R.val[4] = matrix.val[5]; R.val[5] = matrix.val[ 6]; - R.val[6] = matrix.val[8]; R.val[7] = matrix.val[9]; R.val[8] = matrix.val[10]; - return R; -} - -template inline -typename cv::Affine3::Vec3 cv::Affine3::translation() const -{ - return Vec3(matrix.val[3], matrix.val[7], matrix.val[11]); -} - -template inline -typename cv::Affine3::Vec3 cv::Affine3::rvec() const -{ - cv::Vec3d w; - cv::Matx33d u, vt, R = rotation(); - cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); - R = u * vt; - - double rx = R.val[7] - R.val[5]; - double ry = R.val[2] - R.val[6]; - double rz = R.val[3] - R.val[1]; - - double s = std::sqrt((rx*rx + ry*ry + rz*rz)*0.25); - double c = (R.val[0] + R.val[4] + R.val[8] - 1) * 0.5; - c = c > 1.0 ? 1.0 : c < -1.0 ? -1.0 : c; - double theta = std::acos(c); - - if( s < 1e-5 ) - { - if( c > 0 ) - rx = ry = rz = 0; - else - { - double t; - t = (R.val[0] + 1) * 0.5; - rx = std::sqrt(std::max(t, 0.0)); - t = (R.val[4] + 1) * 0.5; - ry = std::sqrt(std::max(t, 0.0)) * (R.val[1] < 0 ? -1.0 : 1.0); - t = (R.val[8] + 1) * 0.5; - rz = std::sqrt(std::max(t, 0.0)) * (R.val[2] < 0 ? -1.0 : 1.0); - - if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R.val[5] > 0) != (ry*rz > 0) ) - rz = -rz; - theta /= std::sqrt(rx*rx + ry*ry + rz*rz); - rx *= theta; - ry *= theta; - rz *= theta; - } - } - else - { - double vth = 1/(2*s); - vth *= theta; - rx *= vth; ry *= vth; rz *= vth; - } - - return cv::Vec3d(rx, ry, rz); -} - -template inline -cv::Affine3 cv::Affine3::inv(int method) const -{ - return matrix.inv(method); -} - -template inline -cv::Affine3 cv::Affine3::rotate(const Mat3& R) const -{ - Mat3 Lc = linear(); - Vec3 tc = translation(); - Mat4 result; - result.val[12] = result.val[13] = result.val[14] = 0; - result.val[15] = 1; - - for(int j = 0; j < 3; ++j) - { - for(int i = 0; i < 3; ++i) - { - float_type value = 0; - for(int k = 0; k < 3; ++k) - value += R(j, k) * Lc(k, i); - result(j, i) = value; - } - - result(j, 3) = R.row(j).dot(tc.t()); - } - return result; -} - -template inline -cv::Affine3 cv::Affine3::rotate(const Vec3& _rvec) const -{ - return rotate(Affine3f(_rvec).rotation()); -} - -template inline -cv::Affine3 cv::Affine3::translate(const Vec3& t) const -{ - Mat4 m = matrix; - m.val[ 3] += t[0]; - m.val[ 7] += t[1]; - m.val[11] += t[2]; - return m; -} - -template inline -cv::Affine3 cv::Affine3::concatenate(const Affine3& affine) const -{ - return (*this).rotate(affine.rotation()).translate(affine.translation()); -} - -template template inline -cv::Affine3::operator Affine3() const -{ - return Affine3(matrix); -} - -template template inline -cv::Affine3 cv::Affine3::cast() const -{ - return Affine3(matrix); -} - -template inline -cv::Affine3 cv::operator*(const cv::Affine3& affine1, const cv::Affine3& affine2) -{ - return affine2.concatenate(affine1); -} - -template inline -V cv::operator*(const cv::Affine3& affine, const V& v) -{ - const typename Affine3::Mat4& m = affine.matrix; - - V r; - r.x = m.val[0] * v.x + m.val[1] * v.y + m.val[ 2] * v.z + m.val[ 3]; - r.y = m.val[4] * v.x + m.val[5] * v.y + m.val[ 6] * v.z + m.val[ 7]; - r.z = m.val[8] * v.x + m.val[9] * v.y + m.val[10] * v.z + m.val[11]; - return r; -} - -static inline -cv::Vec3f cv::operator*(const cv::Affine3f& affine, const cv::Vec3f& v) -{ - const cv::Matx44f& m = affine.matrix; - cv::Vec3f r; - r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; - r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; - r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; - return r; -} - -static inline -cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v) -{ - const cv::Matx44d& m = affine.matrix; - cv::Vec3d r; - r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; - r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; - r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; - return r; -} - - - -#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H - -template inline -cv::Affine3::Affine3(const Eigen::Transform& affine) -{ - cv::Mat(4, 4, cv::traits::Type::value, affine.matrix().data()).copyTo(matrix); -} - -template inline -cv::Affine3::Affine3(const Eigen::Transform& affine) -{ - Eigen::Transform a = affine; - cv::Mat(4, 4, cv::traits::Type::value, a.matrix().data()).copyTo(matrix); -} - -template inline -cv::Affine3::operator Eigen::Transform() const -{ - Eigen::Transform r; - cv::Mat hdr(4, 4, cv::traits::Type::value, r.matrix().data()); - cv::Mat(matrix, false).copyTo(hdr); - return r; -} - -template inline -cv::Affine3::operator Eigen::Transform() const -{ - return this->operator Eigen::Transform(); -} - -#endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */ - -//! @endcond - -#endif /* __cplusplus */ - -#endif /* OPENCV_CORE_AFFINE3_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_AFFINE3_HPP +#define OPENCV_CORE_AFFINE3_HPP + +#ifdef __cplusplus + +#include + +namespace cv +{ + +//! @addtogroup core_eigen +//! @{ + + /** @brief Affine transform + * + * It represents a 4x4 homogeneous transformation matrix \f$T\f$ + * + * \f[T = + * \begin{bmatrix} + * R & t\\ + * 0 & 1\\ + * \end{bmatrix} + * \f] + * + * where \f$R\f$ is a 3x3 rotation matrix and \f$t\f$ is a 3x1 translation vector. + * + * You can specify \f$R\f$ either by a 3x3 rotation matrix or by a 3x1 rotation vector, + * which is converted to a 3x3 rotation matrix by the Rodrigues formula. + * + * To construct a matrix \f$T\f$ representing first rotation around the axis \f$r\f$ with rotation + * angle \f$|r|\f$ in radian (right hand rule) and then translation by the vector \f$t\f$, you can use + * + * @code + * cv::Vec3f r, t; + * cv::Affine3f T(r, t); + * @endcode + * + * If you already have the rotation matrix \f$R\f$, then you can use + * + * @code + * cv::Matx33f R; + * cv::Affine3f T(R, t); + * @endcode + * + * To extract the rotation matrix \f$R\f$ from \f$T\f$, use + * + * @code + * cv::Matx33f R = T.rotation(); + * @endcode + * + * To extract the translation vector \f$t\f$ from \f$T\f$, use + * + * @code + * cv::Vec3f t = T.translation(); + * @endcode + * + * To extract the rotation vector \f$r\f$ from \f$T\f$, use + * + * @code + * cv::Vec3f r = T.rvec(); + * @endcode + * + * Note that since the mapping from rotation vectors to rotation matrices + * is many to one. The returned rotation vector is not necessarily the one + * you used before to set the matrix. + * + * If you have two transformations \f$T = T_1 * T_2\f$, use + * + * @code + * cv::Affine3f T, T1, T2; + * T = T2.concatenate(T1); + * @endcode + * + * To get the inverse transform of \f$T\f$, use + * + * @code + * cv::Affine3f T, T_inv; + * T_inv = T.inv(); + * @endcode + * + */ + template + class Affine3 + { + public: + typedef T float_type; + typedef Matx Mat3; + typedef Matx Mat4; + typedef Vec Vec3; + + //! Default constructor. It represents a 4x4 identity matrix. + Affine3(); + + //! Augmented affine matrix + Affine3(const Mat4& affine); + + /** + * The resulting 4x4 matrix is + * + * \f[ + * \begin{bmatrix} + * R & t\\ + * 0 & 1\\ + * \end{bmatrix} + * \f] + * + * @param R 3x3 rotation matrix. + * @param t 3x1 translation vector. + */ + Affine3(const Mat3& R, const Vec3& t = Vec3::all(0)); + + /** + * Rodrigues vector. + * + * The last row of the current matrix is set to [0,0,0,1]. + * + * @param rvec 3x1 rotation vector. Its direction indicates the rotation axis and its length + * indicates the rotation angle in radian (using right hand rule). + * @param t 3x1 translation vector. + */ + Affine3(const Vec3& rvec, const Vec3& t = Vec3::all(0)); + + /** + * Combines all constructors above. Supports 4x4, 3x4, 3x3, 1x3, 3x1 sizes of data matrix. + * + * The last row of the current matrix is set to [0,0,0,1] when data is not 4x4. + * + * @param data 1-channel matrix. + * when it is 4x4, it is copied to the current matrix and t is not used. + * When it is 3x4, it is copied to the upper part 3x4 of the current matrix and t is not used. + * When it is 3x3, it is copied to the upper left 3x3 part of the current matrix. + * When it is 3x1 or 1x3, it is treated as a rotation vector and the Rodrigues formula is used + * to compute a 3x3 rotation matrix. + * @param t 3x1 translation vector. It is used only when data is neither 4x4 nor 3x4. + */ + explicit Affine3(const Mat& data, const Vec3& t = Vec3::all(0)); + + //! From 16-element array + explicit Affine3(const float_type* vals); + + //! Create an 4x4 identity transform + static Affine3 Identity(); + + /** + * Rotation matrix. + * + * Copy the rotation matrix to the upper left 3x3 part of the current matrix. + * The remaining elements of the current matrix are not changed. + * + * @param R 3x3 rotation matrix. + * + */ + void rotation(const Mat3& R); + + /** + * Rodrigues vector. + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param rvec 3x1 rotation vector. The direction indicates the rotation axis and + * its length indicates the rotation angle in radian (using the right thumb convention). + */ + void rotation(const Vec3& rvec); + + /** + * Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix. + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param data 1-channel matrix. + * When it is a 3x3 matrix, it sets the upper left 3x3 part of the current matrix. + * When it is a 1x3 or 3x1 matrix, it is used as a rotation vector. The Rodrigues formula + * is used to compute the rotation matrix and sets the upper left 3x3 part of the current matrix. + */ + void rotation(const Mat& data); + + /** + * Copy the 3x3 matrix L to the upper left part of the current matrix + * + * It sets the upper left 3x3 part of the matrix. The remaining part is unaffected. + * + * @param L 3x3 matrix. + */ + void linear(const Mat3& L); + + /** + * Copy t to the first three elements of the last column of the current matrix + * + * It sets the upper right 3x1 part of the matrix. The remaining part is unaffected. + * + * @param t 3x1 translation vector. + */ + void translation(const Vec3& t); + + //! @return the upper left 3x3 part + Mat3 rotation() const; + + //! @return the upper left 3x3 part + Mat3 linear() const; + + //! @return the upper right 3x1 part + Vec3 translation() const; + + //! Rodrigues vector. + //! @return a vector representing the upper left 3x3 rotation matrix of the current matrix. + //! @warning Since the mapping between rotation vectors and rotation matrices is many to one, + //! this function returns only one rotation vector that represents the current rotation matrix, + //! which is not necessarily the same one set by `rotation(const Vec3& rvec)`. + Vec3 rvec() const; + + //! @return the inverse of the current matrix. + Affine3 inv(int method = cv::DECOMP_SVD) const; + + //! a.rotate(R) is equivalent to Affine(R, 0) * a; + Affine3 rotate(const Mat3& R) const; + + //! a.rotate(rvec) is equivalent to Affine(rvec, 0) * a; + Affine3 rotate(const Vec3& rvec) const; + + //! a.translate(t) is equivalent to Affine(E, t) * a, where E is an identity matrix + Affine3 translate(const Vec3& t) const; + + //! a.concatenate(affine) is equivalent to affine * a; + Affine3 concatenate(const Affine3& affine) const; + + template operator Affine3() const; + + template Affine3 cast() const; + + Mat4 matrix; + +#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H + Affine3(const Eigen::Transform& affine); + Affine3(const Eigen::Transform& affine); + operator Eigen::Transform() const; + operator Eigen::Transform() const; +#endif + }; + + template static + Affine3 operator*(const Affine3& affine1, const Affine3& affine2); + + //! V is a 3-element vector with member fields x, y and z + template static + V operator*(const Affine3& affine, const V& vector); + + typedef Affine3 Affine3f; + typedef Affine3 Affine3d; + + static Vec3f operator*(const Affine3f& affine, const Vec3f& vector); + static Vec3d operator*(const Affine3d& affine, const Vec3d& vector); + + template class DataType< Affine3<_Tp> > + { + public: + typedef Affine3<_Tp> value_type; + typedef Affine3::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 16, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; + }; + + namespace traits { + template + struct Depth< Affine3<_Tp> > { enum { value = Depth<_Tp>::value }; }; + template + struct Type< Affine3<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 16) }; }; + } // namespace + +//! @} core + +} + +//! @cond IGNORED + +/////////////////////////////////////////////////////////////////////////////////// +// Implementation + +template inline +cv::Affine3::Affine3() + : matrix(Mat4::eye()) +{} + +template inline +cv::Affine3::Affine3(const Mat4& affine) + : matrix(affine) +{} + +template inline +cv::Affine3::Affine3(const Mat3& R, const Vec3& t) +{ + rotation(R); + translation(t); + matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; + matrix.val[15] = 1; +} + +template inline +cv::Affine3::Affine3(const Vec3& _rvec, const Vec3& t) +{ + rotation(_rvec); + translation(t); + matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; + matrix.val[15] = 1; +} + +template inline +cv::Affine3::Affine3(const cv::Mat& data, const Vec3& t) +{ + CV_Assert(data.type() == cv::traits::Type::value); + CV_Assert(data.channels() == 1); + + if (data.cols == 4 && data.rows == 4) + { + data.copyTo(matrix); + return; + } + else if (data.cols == 4 && data.rows == 3) + { + rotation(data(Rect(0, 0, 3, 3))); + translation(data(Rect(3, 0, 1, 3))); + } + else + { + rotation(data); + translation(t); + } + + matrix.val[12] = matrix.val[13] = matrix.val[14] = 0; + matrix.val[15] = 1; +} + +template inline +cv::Affine3::Affine3(const float_type* vals) : matrix(vals) +{} + +template inline +cv::Affine3 cv::Affine3::Identity() +{ + return Affine3(cv::Affine3::Mat4::eye()); +} + +template inline +void cv::Affine3::rotation(const Mat3& R) +{ + linear(R); +} + +template inline +void cv::Affine3::rotation(const Vec3& _rvec) +{ + double theta = norm(_rvec); + + if (theta < DBL_EPSILON) + rotation(Mat3::eye()); + else + { + double c = std::cos(theta); + double s = std::sin(theta); + double c1 = 1. - c; + double itheta = (theta != 0) ? 1./theta : 0.; + + Point3_ r = _rvec*itheta; + + Mat3 rrt( r.x*r.x, r.x*r.y, r.x*r.z, r.x*r.y, r.y*r.y, r.y*r.z, r.x*r.z, r.y*r.z, r.z*r.z ); + Mat3 r_x( 0, -r.z, r.y, r.z, 0, -r.x, -r.y, r.x, 0 ); + + // R = cos(theta)*I + (1 - cos(theta))*r*rT + sin(theta)*[r_x] + // where [r_x] is [0 -rz ry; rz 0 -rx; -ry rx 0] + Mat3 R = c*Mat3::eye() + c1*rrt + s*r_x; + + rotation(R); + } +} + +//Combines rotation methods above. Supports 3x3, 1x3, 3x1 sizes of data matrix; +template inline +void cv::Affine3::rotation(const cv::Mat& data) +{ + CV_Assert(data.type() == cv::traits::Type::value); + CV_Assert(data.channels() == 1); + + if (data.cols == 3 && data.rows == 3) + { + Mat3 R; + data.copyTo(R); + rotation(R); + } + else if ((data.cols == 3 && data.rows == 1) || (data.cols == 1 && data.rows == 3)) + { + Vec3 _rvec; + data.reshape(1, 3).copyTo(_rvec); + rotation(_rvec); + } + else + CV_Error(Error::StsError, "Input matrix can only be 3x3, 1x3 or 3x1"); +} + +template inline +void cv::Affine3::linear(const Mat3& L) +{ + matrix.val[0] = L.val[0]; matrix.val[1] = L.val[1]; matrix.val[ 2] = L.val[2]; + matrix.val[4] = L.val[3]; matrix.val[5] = L.val[4]; matrix.val[ 6] = L.val[5]; + matrix.val[8] = L.val[6]; matrix.val[9] = L.val[7]; matrix.val[10] = L.val[8]; +} + +template inline +void cv::Affine3::translation(const Vec3& t) +{ + matrix.val[3] = t[0]; matrix.val[7] = t[1]; matrix.val[11] = t[2]; +} + +template inline +typename cv::Affine3::Mat3 cv::Affine3::rotation() const +{ + return linear(); +} + +template inline +typename cv::Affine3::Mat3 cv::Affine3::linear() const +{ + typename cv::Affine3::Mat3 R; + R.val[0] = matrix.val[0]; R.val[1] = matrix.val[1]; R.val[2] = matrix.val[ 2]; + R.val[3] = matrix.val[4]; R.val[4] = matrix.val[5]; R.val[5] = matrix.val[ 6]; + R.val[6] = matrix.val[8]; R.val[7] = matrix.val[9]; R.val[8] = matrix.val[10]; + return R; +} + +template inline +typename cv::Affine3::Vec3 cv::Affine3::translation() const +{ + return Vec3(matrix.val[3], matrix.val[7], matrix.val[11]); +} + +template inline +typename cv::Affine3::Vec3 cv::Affine3::rvec() const +{ + cv::Vec3d w; + cv::Matx33d u, vt, R = rotation(); + cv::SVD::compute(R, w, u, vt, cv::SVD::FULL_UV + cv::SVD::MODIFY_A); + R = u * vt; + + double rx = R.val[7] - R.val[5]; + double ry = R.val[2] - R.val[6]; + double rz = R.val[3] - R.val[1]; + + double s = std::sqrt((rx*rx + ry*ry + rz*rz)*0.25); + double c = (R.val[0] + R.val[4] + R.val[8] - 1) * 0.5; + c = c > 1.0 ? 1.0 : c < -1.0 ? -1.0 : c; + double theta = std::acos(c); + + if( s < 1e-5 ) + { + if( c > 0 ) + rx = ry = rz = 0; + else + { + double t; + t = (R.val[0] + 1) * 0.5; + rx = std::sqrt(std::max(t, 0.0)); + t = (R.val[4] + 1) * 0.5; + ry = std::sqrt(std::max(t, 0.0)) * (R.val[1] < 0 ? -1.0 : 1.0); + t = (R.val[8] + 1) * 0.5; + rz = std::sqrt(std::max(t, 0.0)) * (R.val[2] < 0 ? -1.0 : 1.0); + + if( fabs(rx) < fabs(ry) && fabs(rx) < fabs(rz) && (R.val[5] > 0) != (ry*rz > 0) ) + rz = -rz; + theta /= std::sqrt(rx*rx + ry*ry + rz*rz); + rx *= theta; + ry *= theta; + rz *= theta; + } + } + else + { + double vth = 1/(2*s); + vth *= theta; + rx *= vth; ry *= vth; rz *= vth; + } + + return cv::Vec3d(rx, ry, rz); +} + +template inline +cv::Affine3 cv::Affine3::inv(int method) const +{ + return matrix.inv(method); +} + +template inline +cv::Affine3 cv::Affine3::rotate(const Mat3& R) const +{ + Mat3 Lc = linear(); + Vec3 tc = translation(); + Mat4 result; + result.val[12] = result.val[13] = result.val[14] = 0; + result.val[15] = 1; + + for(int j = 0; j < 3; ++j) + { + for(int i = 0; i < 3; ++i) + { + float_type value = 0; + for(int k = 0; k < 3; ++k) + value += R(j, k) * Lc(k, i); + result(j, i) = value; + } + + result(j, 3) = R.row(j).dot(tc.t()); + } + return result; +} + +template inline +cv::Affine3 cv::Affine3::rotate(const Vec3& _rvec) const +{ + return rotate(Affine3f(_rvec).rotation()); +} + +template inline +cv::Affine3 cv::Affine3::translate(const Vec3& t) const +{ + Mat4 m = matrix; + m.val[ 3] += t[0]; + m.val[ 7] += t[1]; + m.val[11] += t[2]; + return m; +} + +template inline +cv::Affine3 cv::Affine3::concatenate(const Affine3& affine) const +{ + return (*this).rotate(affine.rotation()).translate(affine.translation()); +} + +template template inline +cv::Affine3::operator Affine3() const +{ + return Affine3(matrix); +} + +template template inline +cv::Affine3 cv::Affine3::cast() const +{ + return Affine3(matrix); +} + +template inline +cv::Affine3 cv::operator*(const cv::Affine3& affine1, const cv::Affine3& affine2) +{ + return affine2.concatenate(affine1); +} + +template inline +V cv::operator*(const cv::Affine3& affine, const V& v) +{ + const typename Affine3::Mat4& m = affine.matrix; + + V r; + r.x = m.val[0] * v.x + m.val[1] * v.y + m.val[ 2] * v.z + m.val[ 3]; + r.y = m.val[4] * v.x + m.val[5] * v.y + m.val[ 6] * v.z + m.val[ 7]; + r.z = m.val[8] * v.x + m.val[9] * v.y + m.val[10] * v.z + m.val[11]; + return r; +} + +static inline +cv::Vec3f cv::operator*(const cv::Affine3f& affine, const cv::Vec3f& v) +{ + const cv::Matx44f& m = affine.matrix; + cv::Vec3f r; + r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; + r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; + r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; + return r; +} + +static inline +cv::Vec3d cv::operator*(const cv::Affine3d& affine, const cv::Vec3d& v) +{ + const cv::Matx44d& m = affine.matrix; + cv::Vec3d r; + r.val[0] = m.val[0] * v[0] + m.val[1] * v[1] + m.val[ 2] * v[2] + m.val[ 3]; + r.val[1] = m.val[4] * v[0] + m.val[5] * v[1] + m.val[ 6] * v[2] + m.val[ 7]; + r.val[2] = m.val[8] * v[0] + m.val[9] * v[1] + m.val[10] * v[2] + m.val[11]; + return r; +} + + + +#if defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H + +template inline +cv::Affine3::Affine3(const Eigen::Transform& affine) +{ + cv::Mat(4, 4, cv::traits::Type::value, affine.matrix().data()).copyTo(matrix); +} + +template inline +cv::Affine3::Affine3(const Eigen::Transform& affine) +{ + Eigen::Transform a = affine; + cv::Mat(4, 4, cv::traits::Type::value, a.matrix().data()).copyTo(matrix); +} + +template inline +cv::Affine3::operator Eigen::Transform() const +{ + Eigen::Transform r; + cv::Mat hdr(4, 4, cv::traits::Type::value, r.matrix().data()); + cv::Mat(matrix, false).copyTo(hdr); + return r; +} + +template inline +cv::Affine3::operator Eigen::Transform() const +{ + return this->operator Eigen::Transform(); +} + +#endif /* defined EIGEN_WORLD_VERSION && defined EIGEN_GEOMETRY_MODULE_H */ + +//! @endcond + +#endif /* __cplusplus */ + +#endif /* OPENCV_CORE_AFFINE3_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/async.hpp b/3rdParty/opencv-4.11.0/opencv2/core/async.hpp index 4c56354d28..98868a130b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/async.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/async.hpp @@ -1,101 +1,101 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ASYNC_HPP -#define OPENCV_CORE_ASYNC_HPP - -#include - -//#include -#include - -namespace cv { - -/** @addtogroup core_async - -@{ -*/ - - -/** @brief Returns result of asynchronous operations - -Object has attached asynchronous state. -Assignment operator doesn't clone asynchronous state (it is shared between all instances). - -Result can be fetched via get() method only once. - -*/ -class CV_EXPORTS_W AsyncArray -{ -public: - ~AsyncArray() CV_NOEXCEPT; - CV_WRAP AsyncArray() CV_NOEXCEPT; - AsyncArray(const AsyncArray& o) CV_NOEXCEPT; - AsyncArray& operator=(const AsyncArray& o) CV_NOEXCEPT; - CV_WRAP void release() CV_NOEXCEPT; - - /** Fetch the result. - @param[out] dst destination array - - Waits for result until container has valid result. - Throws exception if exception was stored as a result. - - Throws exception on invalid container state. - - @note Result or stored exception can be fetched only once. - */ - CV_WRAP void get(OutputArray dst) const; - - /** Retrieving the result with timeout - @param[out] dst destination array - @param[in] timeoutNs timeout in nanoseconds, -1 for infinite wait - - @returns true if result is ready, false if the timeout has expired - - @note Result or stored exception can be fetched only once. - */ - bool get(OutputArray dst, int64 timeoutNs) const; - - CV_WRAP inline - bool get(OutputArray dst, double timeoutNs) const { return get(dst, (int64)timeoutNs); } - - bool wait_for(int64 timeoutNs) const; - - CV_WRAP inline - bool wait_for(double timeoutNs) const { return wait_for((int64)timeoutNs); } - - CV_WRAP bool valid() const CV_NOEXCEPT; - - inline AsyncArray(AsyncArray&& o) { p = o.p; o.p = NULL; } - inline AsyncArray& operator=(AsyncArray&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } - - template - inline bool get(OutputArray dst, const std::chrono::duration<_Rep, _Period>& timeout) - { - return get(dst, (int64)(std::chrono::nanoseconds(timeout).count())); - } - - template - inline bool wait_for(const std::chrono::duration<_Rep, _Period>& timeout) - { - return wait_for((int64)(std::chrono::nanoseconds(timeout).count())); - } - -#if 0 - std::future getFutureMat() const; - std::future getFutureUMat() const; -#endif - - - // PImpl - struct Impl; friend struct Impl; - inline void* _getImpl() const CV_NOEXCEPT { return p; } -protected: - Impl* p; -}; - - -//! @} -} // namespace -#endif // OPENCV_CORE_ASYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ASYNC_HPP +#define OPENCV_CORE_ASYNC_HPP + +#include + +//#include +#include + +namespace cv { + +/** @addtogroup core_async + +@{ +*/ + + +/** @brief Returns result of asynchronous operations + +Object has attached asynchronous state. +Assignment operator doesn't clone asynchronous state (it is shared between all instances). + +Result can be fetched via get() method only once. + +*/ +class CV_EXPORTS_W AsyncArray +{ +public: + ~AsyncArray() CV_NOEXCEPT; + CV_WRAP AsyncArray() CV_NOEXCEPT; + AsyncArray(const AsyncArray& o) CV_NOEXCEPT; + AsyncArray& operator=(const AsyncArray& o) CV_NOEXCEPT; + CV_WRAP void release() CV_NOEXCEPT; + + /** Fetch the result. + @param[out] dst destination array + + Waits for result until container has valid result. + Throws exception if exception was stored as a result. + + Throws exception on invalid container state. + + @note Result or stored exception can be fetched only once. + */ + CV_WRAP void get(OutputArray dst) const; + + /** Retrieving the result with timeout + @param[out] dst destination array + @param[in] timeoutNs timeout in nanoseconds, -1 for infinite wait + + @returns true if result is ready, false if the timeout has expired + + @note Result or stored exception can be fetched only once. + */ + bool get(OutputArray dst, int64 timeoutNs) const; + + CV_WRAP inline + bool get(OutputArray dst, double timeoutNs) const { return get(dst, (int64)timeoutNs); } + + bool wait_for(int64 timeoutNs) const; + + CV_WRAP inline + bool wait_for(double timeoutNs) const { return wait_for((int64)timeoutNs); } + + CV_WRAP bool valid() const CV_NOEXCEPT; + + inline AsyncArray(AsyncArray&& o) { p = o.p; o.p = NULL; } + inline AsyncArray& operator=(AsyncArray&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } + + template + inline bool get(OutputArray dst, const std::chrono::duration<_Rep, _Period>& timeout) + { + return get(dst, (int64)(std::chrono::nanoseconds(timeout).count())); + } + + template + inline bool wait_for(const std::chrono::duration<_Rep, _Period>& timeout) + { + return wait_for((int64)(std::chrono::nanoseconds(timeout).count())); + } + +#if 0 + std::future getFutureMat() const; + std::future getFutureUMat() const; +#endif + + + // PImpl + struct Impl; friend struct Impl; + inline void* _getImpl() const CV_NOEXCEPT { return p; } +protected: + Impl* p; +}; + + +//! @} +} // namespace +#endif // OPENCV_CORE_ASYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/base.hpp b/3rdParty/opencv-4.11.0/opencv2/core/base.hpp index 4e810931cb..5e63ae3700 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/base.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/base.hpp @@ -1,682 +1,682 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2014, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_BASE_HPP -#define OPENCV_CORE_BASE_HPP - -#ifndef __cplusplus -# error base.hpp header must be compiled as C++ -#endif - -#include "opencv2/opencv_modules.hpp" - -#include -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" - -namespace cv -{ - -//! @addtogroup core_utils -//! @{ - -namespace Error { -//! error codes -enum Code { - StsOk= 0, //!< everything is ok - StsBackTrace= -1, //!< pseudo error for back trace - StsError= -2, //!< unknown /unspecified error - StsInternal= -3, //!< internal error (bad state) - StsNoMem= -4, //!< insufficient memory - StsBadArg= -5, //!< function arg/param is bad - StsBadFunc= -6, //!< unsupported function - StsNoConv= -7, //!< iteration didn't converge - StsAutoTrace= -8, //!< tracing - HeaderIsNull= -9, //!< image header is NULL - BadImageSize= -10, //!< image size is invalid - BadOffset= -11, //!< offset is invalid - BadDataPtr= -12, //!< - BadStep= -13, //!< image step is wrong, this may happen for a non-continuous matrix. - BadModelOrChSeq= -14, //!< - BadNumChannels= -15, //!< bad number of channels, for example, some functions accept only single channel matrices. - BadNumChannel1U= -16, //!< - BadDepth= -17, //!< input image depth is not supported by the function - BadAlphaChannel= -18, //!< - BadOrder= -19, //!< number of dimensions is out of range - BadOrigin= -20, //!< incorrect input origin - BadAlign= -21, //!< incorrect input align - BadCallBack= -22, //!< - BadTileSize= -23, //!< - BadCOI= -24, //!< input COI is not supported - BadROISize= -25, //!< incorrect input roi - MaskIsTiled= -26, //!< - StsNullPtr= -27, //!< null pointer - StsVecLengthErr= -28, //!< incorrect vector length - StsFilterStructContentErr= -29, //!< incorrect filter structure content - StsKernelStructContentErr= -30, //!< incorrect transform kernel content - StsFilterOffsetErr= -31, //!< incorrect filter offset value - StsBadSize= -201, //!< the input/output structure size is incorrect - StsDivByZero= -202, //!< division by zero - StsInplaceNotSupported= -203, //!< in-place operation is not supported - StsObjectNotFound= -204, //!< request can't be completed - StsUnmatchedFormats= -205, //!< formats of input/output arrays differ - StsBadFlag= -206, //!< flag is wrong or not supported - StsBadPoint= -207, //!< bad CvPoint - StsBadMask= -208, //!< bad format of mask (neither 8uC1 nor 8sC1) - StsUnmatchedSizes= -209, //!< sizes of input/output structures do not match - StsUnsupportedFormat= -210, //!< the data format/type is not supported by the function - StsOutOfRange= -211, //!< some of parameters are out of range - StsParseError= -212, //!< invalid syntax/structure of the parsed file - StsNotImplemented= -213, //!< the requested function/feature is not implemented - StsBadMemBlock= -214, //!< an allocated block has been corrupted - StsAssert= -215, //!< assertion failed - GpuNotSupported= -216, //!< no CUDA support - GpuApiCallError= -217, //!< GPU API call error - OpenGlNotSupported= -218, //!< no OpenGL support - OpenGlApiCallError= -219, //!< OpenGL API call error - OpenCLApiCallError= -220, //!< OpenCL API call error - OpenCLDoubleNotSupported= -221, - OpenCLInitError= -222, //!< OpenCL initialization error - OpenCLNoAMDBlasFft= -223 -}; -} //Error - -//! @} core_utils - -//! @addtogroup core_array -//! @{ - -//! matrix decomposition types -enum DecompTypes { - /** Gaussian elimination with the optimal pivot element chosen. */ - DECOMP_LU = 0, - /** singular value decomposition (SVD) method; the system can be over-defined and/or the matrix - src1 can be singular */ - DECOMP_SVD = 1, - /** eigenvalue decomposition; the matrix src1 must be symmetrical */ - DECOMP_EIG = 2, - /** Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical and positively - defined */ - DECOMP_CHOLESKY = 3, - /** QR factorization; the system can be over-defined and/or the matrix src1 can be singular */ - DECOMP_QR = 4, - /** while all the previous flags are mutually exclusive, this flag can be used together with - any of the previous; it means that the normal equations - \f$\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}\f$ are - solved instead of the original system - \f$\texttt{src1}\cdot\texttt{dst}=\texttt{src2}\f$ */ - DECOMP_NORMAL = 16 -}; - -/** norm types - -src1 and src2 denote input arrays. -*/ - -enum NormTypes { - /** - \f[ - norm = \forkthree - {\|\texttt{src1}\|_{L_{\infty}} = \max _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } - {\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } - {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_INF}\) } - \f] - */ - NORM_INF = 1, - /** - \f[ - norm = \forkthree - {\| \texttt{src1} \| _{L_1} = \sum _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\)} - { \| \texttt{src1} - \texttt{src2} \| _{L_1} = \sum _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } - { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L1}\) } - \f]*/ - NORM_L1 = 2, - /** - \f[ - norm = \forkthree - { \| \texttt{src1} \| _{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } - { \| \texttt{src1} - \texttt{src2} \| _{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } - { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2}\) } - \f] - */ - NORM_L2 = 4, - /** - \f[ - norm = \forkthree - { \| \texttt{src1} \| _{L_2} ^{2} = \sum_I \texttt{src1}(I)^2} {if \(\texttt{normType} = \texttt{NORM_L2SQR}\)} - { \| \texttt{src1} - \texttt{src2} \| _{L_2} ^{2} = \sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2 }{if \(\texttt{normType} = \texttt{NORM_L2SQR}\) } - { \left(\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}\right)^2 }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2SQR}\) } - \f] - */ - NORM_L2SQR = 5, - /** - In the case of one input array, calculates the Hamming distance of the array from zero, - In the case of two input arrays, calculates the Hamming distance between the arrays. - */ - NORM_HAMMING = 6, - /** - Similar to NORM_HAMMING, but in the calculation, each two bits of the input sequence will - be added and treated as a single bit to be used in the same calculation as NORM_HAMMING. - */ - NORM_HAMMING2 = 7, - NORM_TYPE_MASK = 7, //!< bit-mask which can be used to separate norm type from norm flags - NORM_RELATIVE = 8, //!< flag - NORM_MINMAX = 32 //!< flag - }; - -//! comparison types -enum CmpTypes { CMP_EQ = 0, //!< src1 is equal to src2. - CMP_GT = 1, //!< src1 is greater than src2. - CMP_GE = 2, //!< src1 is greater than or equal to src2. - CMP_LT = 3, //!< src1 is less than src2. - CMP_LE = 4, //!< src1 is less than or equal to src2. - CMP_NE = 5 //!< src1 is unequal to src2. - }; - -//! generalized matrix multiplication flags -enum GemmFlags { GEMM_1_T = 1, //!< transposes src1 - GEMM_2_T = 2, //!< transposes src2 - GEMM_3_T = 4 //!< transposes src3 - }; - -enum DftFlags { - /** performs an inverse 1D or 2D transform instead of the default forward - transform. */ - DFT_INVERSE = 1, - /** scales the result: divide it by the number of array elements. Normally, it is - combined with DFT_INVERSE. */ - DFT_SCALE = 2, - /** performs a forward or inverse transform of every individual row of the input - matrix; this flag enables you to transform multiple vectors simultaneously and can be used to - decrease the overhead (which is sometimes several times larger than the processing itself) to - perform 3D and higher-dimensional transformations and so forth.*/ - DFT_ROWS = 4, - /** performs a forward transformation of 1D or 2D real array; the result, - though being a complex array, has complex-conjugate symmetry (*CCS*, see the function - description below for details), and such an array can be packed into a real array of the same - size as input, which is the fastest option and which is what the function does by default; - however, you may wish to get a full complex array (for simpler spectrum analysis, and so on) - - pass the flag to enable the function to produce a full-size complex output array. */ - DFT_COMPLEX_OUTPUT = 16, - /** performs an inverse transformation of a 1D or 2D complex array; the - result is normally a complex array of the same size, however, if the input array has - conjugate-complex symmetry (for example, it is a result of forward transformation with - DFT_COMPLEX_OUTPUT flag), the output is a real array; while the function itself does not - check whether the input is symmetrical or not, you can pass the flag and then the function - will assume the symmetry and produce the real output array (note that when the input is packed - into a real array and inverse transformation is executed, the function treats the input as a - packed complex-conjugate symmetrical array, and the output will also be a real array). */ - DFT_REAL_OUTPUT = 32, - /** specifies that input is complex input. If this flag is set, the input must have 2 channels. - On the other hand, for backwards compatibility reason, if input has 2 channels, input is - already considered complex. */ - DFT_COMPLEX_INPUT = 64, - /** performs an inverse 1D or 2D transform instead of the default forward transform. */ - DCT_INVERSE = DFT_INVERSE, - /** performs a forward or inverse transform of every individual row of the input - matrix. This flag enables you to transform multiple vectors simultaneously and can be used to - decrease the overhead (which is sometimes several times larger than the processing itself) to - perform 3D and higher-dimensional transforms and so forth.*/ - DCT_ROWS = DFT_ROWS -}; - -//! Various border types, image boundaries are denoted with `|` -//! @see borderInterpolate, copyMakeBorder -enum BorderTypes { - BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` - BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` - BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` - BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` - BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` - BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` - Treats outliers as transparent. - - BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_ISOLATED = 16 //!< Interpolation restricted within the ROI boundaries. -}; - -//! @} core_array - -//! @addtogroup core_utils -//! @{ - -/*! @brief Signals an error and raises the exception. - -By default the function prints information about the error to stderr, -then it either stops if setBreakOnError() had been called before or raises the exception. -It is possible to alternate error processing by using redirectError(). -@param code - error code (Error::Code) -@param err - error description -@param func - function name. Available only when the compiler supports getting it -@param file - source file name where the error has occurred -@param line - line number in the source file where the error has occurred -@see CV_Error, CV_Error_, CV_Assert, CV_DbgAssert - */ -CV_EXPORTS CV_NORETURN void error(int code, const String& err, const char* func, const char* file, int line); - -/*! @brief Signals an error and terminate application. - -By default the function prints information about the error to stderr, then it terminates application -with std::terminate. The function is designed for invariants check in functions and methods with -noexcept attribute. -@param code - error code (Error::Code) -@param err - error description -@param func - function name. Available only when the compiler supports getting it -@param file - source file name where the error has occurred -@param line - line number in the source file where the error has occurred -@see CV_AssertTerminate - */ -CV_EXPORTS CV_NORETURN void terminate(int code, const String& err, const char* func, const char* file, int line) CV_NOEXCEPT; - - -#ifdef CV_STATIC_ANALYSIS - -// In practice, some macro are not processed correctly (noreturn is not detected). -// We need to use simplified definition for them. -#define CV_Error(code, msg) do { (void)(code); (void)(msg); abort(); } while (0) -#define CV_Error_(code, args) do { (void)(code); (void)(cv::format args); abort(); } while (0) -#define CV_Assert( expr ) do { if (!(expr)) abort(); } while (0) - -#else // CV_STATIC_ANALYSIS - -/** @brief Call the error handler. - -Currently, the error handler prints the error code and the error message to the standard -error stream `stderr`. In the Debug configuration, it then provokes memory access violation, so that -the execution stack and all the parameters can be analyzed by the debugger. In the Release -configuration, the exception is thrown. - -@param code one of Error::Code -@param msg error message -*/ -#define CV_Error( code, msg ) cv::error( code, msg, CV_Func, __FILE__, __LINE__ ) - -/** @brief Call the error handler. - -This macro can be used to construct an error message on-fly to include some dynamic information, -for example: -@code - // note the extra parentheses around the formatted text message - CV_Error_(Error::StsOutOfRange, - ("the value at (%d, %d)=%g is out of range", badPt.x, badPt.y, badValue)); -@endcode -@param code one of Error::Code -@param args printf-like formatted error message in parentheses -*/ -#define CV_Error_( code, args ) cv::error( code, cv::format args, CV_Func, __FILE__, __LINE__ ) - -/** @brief Checks a condition at runtime and throws exception if it fails - -The macros CV_Assert (and CV_DbgAssert(expr)) evaluate the specified expression. If it is 0, the macros -raise an error (see cv::error). The macro CV_Assert checks the condition in both Debug and Release -configurations while CV_DbgAssert is only retained in the Debug configuration. -CV_AssertTerminate is analog of CV_Assert for invariants check in functions with noexcept attribute. -It does not throw exception, but terminates the application. -*/ -#define CV_Assert( expr ) do { if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0) -#define CV_AssertTerminate( expr ) do { if(!!(expr)) ; else cv::terminate( #expr, CV_Func, __FILE__, __LINE__ ); } while(0) - -#endif // CV_STATIC_ANALYSIS - -//! @cond IGNORED -#if !defined(__OPENCV_BUILD) // TODO: backward compatibility only -#ifndef CV_ErrorNoReturn -#define CV_ErrorNoReturn CV_Error -#endif -#ifndef CV_ErrorNoReturn_ -#define CV_ErrorNoReturn_ CV_Error_ -#endif -#endif - -#define CV_Assert_1 CV_Assert -#define CV_Assert_2( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_1( __VA_ARGS__ )) -#define CV_Assert_3( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_2( __VA_ARGS__ )) -#define CV_Assert_4( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_3( __VA_ARGS__ )) -#define CV_Assert_5( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_4( __VA_ARGS__ )) -#define CV_Assert_6( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_5( __VA_ARGS__ )) -#define CV_Assert_7( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_6( __VA_ARGS__ )) -#define CV_Assert_8( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_7( __VA_ARGS__ )) -#define CV_Assert_9( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_8( __VA_ARGS__ )) -#define CV_Assert_10( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_9( __VA_ARGS__ )) - -#define CV_Assert_N(...) do { __CV_EXPAND(__CV_CAT(CV_Assert_, __CV_VA_NUM_ARGS(__VA_ARGS__)) (__VA_ARGS__)); } while(0) - -//! @endcond - -#if defined _DEBUG || defined CV_STATIC_ANALYSIS -# define CV_DbgAssert(expr) CV_Assert(expr) -#else -/** replaced with CV_Assert(expr) in Debug configuration */ -# define CV_DbgAssert(expr) -#endif - -/* - * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor - * bit count of A exclusive XOR'ed with B - */ -struct CV_EXPORTS Hamming -{ - static const NormTypes normType = NORM_HAMMING; - typedef unsigned char ValueType; - typedef int ResultType; - - /** this will count the bits in a ^ b - */ - ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const; -}; - -typedef Hamming HammingLUT; - -/////////////////////////////////// inline norms //////////////////////////////////// - -template inline _Tp cv_abs(_Tp x) { return std::abs(x); } -inline int cv_abs(uchar x) { return x; } -inline int cv_abs(schar x) { return std::abs(x); } -inline int cv_abs(ushort x) { return x; } -inline int cv_abs(short x) { return std::abs(x); } - -template static inline -_AccTp normL2Sqr(const _Tp* a, int n) -{ - _AccTp s = 0; - int i=0; -#if CV_ENABLE_UNROLLED - for( ; i <= n - 4; i += 4 ) - { - _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; - s += v0*v0 + v1*v1 + v2*v2 + v3*v3; - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = a[i]; - s += v*v; - } - return s; -} - -template static inline -_AccTp normL1(const _Tp* a, int n) -{ - _AccTp s = 0; - int i = 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - s += (_AccTp)cv_abs(a[i]) + (_AccTp)cv_abs(a[i+1]) + - (_AccTp)cv_abs(a[i+2]) + (_AccTp)cv_abs(a[i+3]); - } -#endif - for( ; i < n; i++ ) - s += cv_abs(a[i]); - return s; -} - -template static inline -_AccTp normInf(const _Tp* a, int n) -{ - _AccTp s = 0; - for( int i = 0; i < n; i++ ) - s = std::max(s, (_AccTp)cv_abs(a[i])); - return s; -} - -template static inline -_AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - int i= 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); - s += v0*v0 + v1*v1 + v2*v2 + v3*v3; - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = _AccTp(a[i] - b[i]); - s += v*v; - } - return s; -} - -static inline float normL2Sqr(const float* a, const float* b, int n) -{ - float s = 0.f; - for( int i = 0; i < n; i++ ) - { - float v = a[i] - b[i]; - s += v*v; - } - return s; -} - -template static inline -_AccTp normL1(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - int i= 0; -#if CV_ENABLE_UNROLLED - for(; i <= n - 4; i += 4 ) - { - _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); - s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); - } -#endif - for( ; i < n; i++ ) - { - _AccTp v = _AccTp(a[i] - b[i]); - s += std::abs(v); - } - return s; -} - -inline float normL1(const float* a, const float* b, int n) -{ - float s = 0.f; - for( int i = 0; i < n; i++ ) - { - s += std::abs(a[i] - b[i]); - } - return s; -} - -inline int normL1(const uchar* a, const uchar* b, int n) -{ - int s = 0; - for( int i = 0; i < n; i++ ) - { - s += std::abs(a[i] - b[i]); - } - return s; -} - -template static inline -_AccTp normInf(const _Tp* a, const _Tp* b, int n) -{ - _AccTp s = 0; - for( int i = 0; i < n; i++ ) - { - _AccTp v0 = a[i] - b[i]; - s = std::max(s, std::abs(v0)); - } - return s; -} - -/** @brief Computes the cube root of an argument. - - The function cubeRoot computes \f$\sqrt[3]{\texttt{val}}\f$. Negative arguments are handled correctly. - NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for - single-precision data. - @param val A function argument. - */ -CV_EXPORTS_W float cubeRoot(float val); - -/** @overload - -cubeRoot with argument of `double` type calls `std::cbrt(double)` -*/ -static inline -double cubeRoot(double val) -{ - return std::cbrt(val); -} - -/** @brief Calculates the angle of a 2D vector in degrees. - - The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured - in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. - @param x x-coordinate of the vector. - @param y y-coordinate of the vector. - */ -CV_EXPORTS_W float fastAtan2(float y, float x); - -/** proxy for hal::LU */ -CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); -/** proxy for hal::LU */ -CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); -/** proxy for hal::Cholesky */ -CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); -/** proxy for hal::Cholesky */ -CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); - -////////////////// forward declarations for important OpenCV types ////////////////// - -//! @cond IGNORED - -template class Vec; -template class Matx; - -template class Complex; -template class Point_; -template class Point3_; -template class Size_; -template class Rect_; -template class Scalar_; - -class CV_EXPORTS RotatedRect; -class CV_EXPORTS Range; -class CV_EXPORTS TermCriteria; -class CV_EXPORTS KeyPoint; -class CV_EXPORTS DMatch; -class CV_EXPORTS RNG; - -class CV_EXPORTS Mat; -class CV_EXPORTS MatExpr; - -class CV_EXPORTS UMat; - -class CV_EXPORTS SparseMat; -typedef Mat MatND; - -template class Mat_; -template class SparseMat_; - -class CV_EXPORTS MatConstIterator; -class CV_EXPORTS SparseMatIterator; -class CV_EXPORTS SparseMatConstIterator; -template class MatIterator_; -template class MatConstIterator_; -template class SparseMatIterator_; -template class SparseMatConstIterator_; - -namespace ogl -{ - class CV_EXPORTS Buffer; - class CV_EXPORTS Texture2D; - class CV_EXPORTS Arrays; -} - -namespace cuda -{ - class CV_EXPORTS GpuMat; - class CV_EXPORTS HostMem; - class CV_EXPORTS Stream; - class CV_EXPORTS Event; -} - -namespace cudev -{ - template class GpuMat_; -} - -namespace ipp -{ -CV_EXPORTS unsigned long long getIppFeatures(); -CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL, - int line = 0); -CV_EXPORTS int getIppStatus(); -CV_EXPORTS String getIppErrorLocation(); -CV_EXPORTS_W bool useIPP(); -CV_EXPORTS_W void setUseIPP(bool flag); -CV_EXPORTS_W String getIppVersion(); - -// IPP Not-Exact mode. This function may force use of IPP then both IPP and OpenCV provide proper results -// but have internal accuracy differences which have too much direct or indirect impact on accuracy tests. -CV_EXPORTS_W bool useIPP_NotExact(); -CV_EXPORTS_W void setUseIPP_NotExact(bool flag); -#ifndef DISABLE_OPENCV_3_COMPATIBILITY -static inline bool useIPP_NE() { return useIPP_NotExact(); } -static inline void setUseIPP_NE(bool flag) { setUseIPP_NotExact(flag); } -#endif - -} // ipp - -//! @endcond - -//! @} core_utils - - - - -} // cv - -#include "opencv2/core/neon_utils.hpp" -#include "opencv2/core/vsx_utils.hpp" -#include "opencv2/core/check.hpp" - -#endif //OPENCV_CORE_BASE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2014, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_BASE_HPP +#define OPENCV_CORE_BASE_HPP + +#ifndef __cplusplus +# error base.hpp header must be compiled as C++ +#endif + +#include "opencv2/opencv_modules.hpp" + +#include +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" + +namespace cv +{ + +//! @addtogroup core_utils +//! @{ + +namespace Error { +//! error codes +enum Code { + StsOk= 0, //!< everything is ok + StsBackTrace= -1, //!< pseudo error for back trace + StsError= -2, //!< unknown /unspecified error + StsInternal= -3, //!< internal error (bad state) + StsNoMem= -4, //!< insufficient memory + StsBadArg= -5, //!< function arg/param is bad + StsBadFunc= -6, //!< unsupported function + StsNoConv= -7, //!< iteration didn't converge + StsAutoTrace= -8, //!< tracing + HeaderIsNull= -9, //!< image header is NULL + BadImageSize= -10, //!< image size is invalid + BadOffset= -11, //!< offset is invalid + BadDataPtr= -12, //!< + BadStep= -13, //!< image step is wrong, this may happen for a non-continuous matrix. + BadModelOrChSeq= -14, //!< + BadNumChannels= -15, //!< bad number of channels, for example, some functions accept only single channel matrices. + BadNumChannel1U= -16, //!< + BadDepth= -17, //!< input image depth is not supported by the function + BadAlphaChannel= -18, //!< + BadOrder= -19, //!< number of dimensions is out of range + BadOrigin= -20, //!< incorrect input origin + BadAlign= -21, //!< incorrect input align + BadCallBack= -22, //!< + BadTileSize= -23, //!< + BadCOI= -24, //!< input COI is not supported + BadROISize= -25, //!< incorrect input roi + MaskIsTiled= -26, //!< + StsNullPtr= -27, //!< null pointer + StsVecLengthErr= -28, //!< incorrect vector length + StsFilterStructContentErr= -29, //!< incorrect filter structure content + StsKernelStructContentErr= -30, //!< incorrect transform kernel content + StsFilterOffsetErr= -31, //!< incorrect filter offset value + StsBadSize= -201, //!< the input/output structure size is incorrect + StsDivByZero= -202, //!< division by zero + StsInplaceNotSupported= -203, //!< in-place operation is not supported + StsObjectNotFound= -204, //!< request can't be completed + StsUnmatchedFormats= -205, //!< formats of input/output arrays differ + StsBadFlag= -206, //!< flag is wrong or not supported + StsBadPoint= -207, //!< bad CvPoint + StsBadMask= -208, //!< bad format of mask (neither 8uC1 nor 8sC1) + StsUnmatchedSizes= -209, //!< sizes of input/output structures do not match + StsUnsupportedFormat= -210, //!< the data format/type is not supported by the function + StsOutOfRange= -211, //!< some of parameters are out of range + StsParseError= -212, //!< invalid syntax/structure of the parsed file + StsNotImplemented= -213, //!< the requested function/feature is not implemented + StsBadMemBlock= -214, //!< an allocated block has been corrupted + StsAssert= -215, //!< assertion failed + GpuNotSupported= -216, //!< no CUDA support + GpuApiCallError= -217, //!< GPU API call error + OpenGlNotSupported= -218, //!< no OpenGL support + OpenGlApiCallError= -219, //!< OpenGL API call error + OpenCLApiCallError= -220, //!< OpenCL API call error + OpenCLDoubleNotSupported= -221, + OpenCLInitError= -222, //!< OpenCL initialization error + OpenCLNoAMDBlasFft= -223 +}; +} //Error + +//! @} core_utils + +//! @addtogroup core_array +//! @{ + +//! matrix decomposition types +enum DecompTypes { + /** Gaussian elimination with the optimal pivot element chosen. */ + DECOMP_LU = 0, + /** singular value decomposition (SVD) method; the system can be over-defined and/or the matrix + src1 can be singular */ + DECOMP_SVD = 1, + /** eigenvalue decomposition; the matrix src1 must be symmetrical */ + DECOMP_EIG = 2, + /** Cholesky \f$LL^T\f$ factorization; the matrix src1 must be symmetrical and positively + defined */ + DECOMP_CHOLESKY = 3, + /** QR factorization; the system can be over-defined and/or the matrix src1 can be singular */ + DECOMP_QR = 4, + /** while all the previous flags are mutually exclusive, this flag can be used together with + any of the previous; it means that the normal equations + \f$\texttt{src1}^T\cdot\texttt{src1}\cdot\texttt{dst}=\texttt{src1}^T\texttt{src2}\f$ are + solved instead of the original system + \f$\texttt{src1}\cdot\texttt{dst}=\texttt{src2}\f$ */ + DECOMP_NORMAL = 16 +}; + +/** norm types + +src1 and src2 denote input arrays. +*/ + +enum NormTypes { + /** + \f[ + norm = \forkthree + {\|\texttt{src1}\|_{L_{\infty}} = \max _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } + {\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} = \max _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_INF}\) } + {\frac{\|\texttt{src1}-\texttt{src2}\|_{L_{\infty}} }{\|\texttt{src2}\|_{L_{\infty}} }}{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_INF}\) } + \f] + */ + NORM_INF = 1, + /** + \f[ + norm = \forkthree + {\| \texttt{src1} \| _{L_1} = \sum _I | \texttt{src1} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\)} + { \| \texttt{src1} - \texttt{src2} \| _{L_1} = \sum _I | \texttt{src1} (I) - \texttt{src2} (I)|}{if \(\texttt{normType} = \texttt{NORM_L1}\) } + { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_1} }{\|\texttt{src2}\|_{L_1}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L1}\) } + \f]*/ + NORM_L1 = 2, + /** + \f[ + norm = \forkthree + { \| \texttt{src1} \| _{L_2} = \sqrt{\sum_I \texttt{src1}(I)^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } + { \| \texttt{src1} - \texttt{src2} \| _{L_2} = \sqrt{\sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2} }{if \(\texttt{normType} = \texttt{NORM_L2}\) } + { \frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}} }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2}\) } + \f] + */ + NORM_L2 = 4, + /** + \f[ + norm = \forkthree + { \| \texttt{src1} \| _{L_2} ^{2} = \sum_I \texttt{src1}(I)^2} {if \(\texttt{normType} = \texttt{NORM_L2SQR}\)} + { \| \texttt{src1} - \texttt{src2} \| _{L_2} ^{2} = \sum_I (\texttt{src1}(I) - \texttt{src2}(I))^2 }{if \(\texttt{normType} = \texttt{NORM_L2SQR}\) } + { \left(\frac{\|\texttt{src1}-\texttt{src2}\|_{L_2} }{\|\texttt{src2}\|_{L_2}}\right)^2 }{if \(\texttt{normType} = \texttt{NORM_RELATIVE | NORM_L2SQR}\) } + \f] + */ + NORM_L2SQR = 5, + /** + In the case of one input array, calculates the Hamming distance of the array from zero, + In the case of two input arrays, calculates the Hamming distance between the arrays. + */ + NORM_HAMMING = 6, + /** + Similar to NORM_HAMMING, but in the calculation, each two bits of the input sequence will + be added and treated as a single bit to be used in the same calculation as NORM_HAMMING. + */ + NORM_HAMMING2 = 7, + NORM_TYPE_MASK = 7, //!< bit-mask which can be used to separate norm type from norm flags + NORM_RELATIVE = 8, //!< flag + NORM_MINMAX = 32 //!< flag + }; + +//! comparison types +enum CmpTypes { CMP_EQ = 0, //!< src1 is equal to src2. + CMP_GT = 1, //!< src1 is greater than src2. + CMP_GE = 2, //!< src1 is greater than or equal to src2. + CMP_LT = 3, //!< src1 is less than src2. + CMP_LE = 4, //!< src1 is less than or equal to src2. + CMP_NE = 5 //!< src1 is unequal to src2. + }; + +//! generalized matrix multiplication flags +enum GemmFlags { GEMM_1_T = 1, //!< transposes src1 + GEMM_2_T = 2, //!< transposes src2 + GEMM_3_T = 4 //!< transposes src3 + }; + +enum DftFlags { + /** performs an inverse 1D or 2D transform instead of the default forward + transform. */ + DFT_INVERSE = 1, + /** scales the result: divide it by the number of array elements. Normally, it is + combined with DFT_INVERSE. */ + DFT_SCALE = 2, + /** performs a forward or inverse transform of every individual row of the input + matrix; this flag enables you to transform multiple vectors simultaneously and can be used to + decrease the overhead (which is sometimes several times larger than the processing itself) to + perform 3D and higher-dimensional transformations and so forth.*/ + DFT_ROWS = 4, + /** performs a forward transformation of 1D or 2D real array; the result, + though being a complex array, has complex-conjugate symmetry (*CCS*, see the function + description below for details), and such an array can be packed into a real array of the same + size as input, which is the fastest option and which is what the function does by default; + however, you may wish to get a full complex array (for simpler spectrum analysis, and so on) - + pass the flag to enable the function to produce a full-size complex output array. */ + DFT_COMPLEX_OUTPUT = 16, + /** performs an inverse transformation of a 1D or 2D complex array; the + result is normally a complex array of the same size, however, if the input array has + conjugate-complex symmetry (for example, it is a result of forward transformation with + DFT_COMPLEX_OUTPUT flag), the output is a real array; while the function itself does not + check whether the input is symmetrical or not, you can pass the flag and then the function + will assume the symmetry and produce the real output array (note that when the input is packed + into a real array and inverse transformation is executed, the function treats the input as a + packed complex-conjugate symmetrical array, and the output will also be a real array). */ + DFT_REAL_OUTPUT = 32, + /** specifies that input is complex input. If this flag is set, the input must have 2 channels. + On the other hand, for backwards compatibility reason, if input has 2 channels, input is + already considered complex. */ + DFT_COMPLEX_INPUT = 64, + /** performs an inverse 1D or 2D transform instead of the default forward transform. */ + DCT_INVERSE = DFT_INVERSE, + /** performs a forward or inverse transform of every individual row of the input + matrix. This flag enables you to transform multiple vectors simultaneously and can be used to + decrease the overhead (which is sometimes several times larger than the processing itself) to + perform 3D and higher-dimensional transforms and so forth.*/ + DCT_ROWS = DFT_ROWS +}; + +//! Various border types, image boundaries are denoted with `|` +//! @see borderInterpolate, copyMakeBorder +enum BorderTypes { + BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` + BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` + BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` + BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` + BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` + BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` - Treats outliers as transparent. + + BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_ISOLATED = 16 //!< Interpolation restricted within the ROI boundaries. +}; + +//! @} core_array + +//! @addtogroup core_utils +//! @{ + +/*! @brief Signals an error and raises the exception. + +By default the function prints information about the error to stderr, +then it either stops if setBreakOnError() had been called before or raises the exception. +It is possible to alternate error processing by using redirectError(). +@param code - error code (Error::Code) +@param err - error description +@param func - function name. Available only when the compiler supports getting it +@param file - source file name where the error has occurred +@param line - line number in the source file where the error has occurred +@see CV_Error, CV_Error_, CV_Assert, CV_DbgAssert + */ +CV_EXPORTS CV_NORETURN void error(int code, const String& err, const char* func, const char* file, int line); + +/*! @brief Signals an error and terminate application. + +By default the function prints information about the error to stderr, then it terminates application +with std::terminate. The function is designed for invariants check in functions and methods with +noexcept attribute. +@param code - error code (Error::Code) +@param err - error description +@param func - function name. Available only when the compiler supports getting it +@param file - source file name where the error has occurred +@param line - line number in the source file where the error has occurred +@see CV_AssertTerminate + */ +CV_EXPORTS CV_NORETURN void terminate(int code, const String& err, const char* func, const char* file, int line) CV_NOEXCEPT; + + +#ifdef CV_STATIC_ANALYSIS + +// In practice, some macro are not processed correctly (noreturn is not detected). +// We need to use simplified definition for them. +#define CV_Error(code, msg) do { (void)(code); (void)(msg); abort(); } while (0) +#define CV_Error_(code, args) do { (void)(code); (void)(cv::format args); abort(); } while (0) +#define CV_Assert( expr ) do { if (!(expr)) abort(); } while (0) + +#else // CV_STATIC_ANALYSIS + +/** @brief Call the error handler. + +Currently, the error handler prints the error code and the error message to the standard +error stream `stderr`. In the Debug configuration, it then provokes memory access violation, so that +the execution stack and all the parameters can be analyzed by the debugger. In the Release +configuration, the exception is thrown. + +@param code one of Error::Code +@param msg error message +*/ +#define CV_Error( code, msg ) cv::error( code, msg, CV_Func, __FILE__, __LINE__ ) + +/** @brief Call the error handler. + +This macro can be used to construct an error message on-fly to include some dynamic information, +for example: +@code + // note the extra parentheses around the formatted text message + CV_Error_(Error::StsOutOfRange, + ("the value at (%d, %d)=%g is out of range", badPt.x, badPt.y, badValue)); +@endcode +@param code one of Error::Code +@param args printf-like formatted error message in parentheses +*/ +#define CV_Error_( code, args ) cv::error( code, cv::format args, CV_Func, __FILE__, __LINE__ ) + +/** @brief Checks a condition at runtime and throws exception if it fails + +The macros CV_Assert (and CV_DbgAssert(expr)) evaluate the specified expression. If it is 0, the macros +raise an error (see cv::error). The macro CV_Assert checks the condition in both Debug and Release +configurations while CV_DbgAssert is only retained in the Debug configuration. +CV_AssertTerminate is analog of CV_Assert for invariants check in functions with noexcept attribute. +It does not throw exception, but terminates the application. +*/ +#define CV_Assert( expr ) do { if(!!(expr)) ; else cv::error( cv::Error::StsAssert, #expr, CV_Func, __FILE__, __LINE__ ); } while(0) +#define CV_AssertTerminate( expr ) do { if(!!(expr)) ; else cv::terminate( #expr, CV_Func, __FILE__, __LINE__ ); } while(0) + +#endif // CV_STATIC_ANALYSIS + +//! @cond IGNORED +#if !defined(__OPENCV_BUILD) // TODO: backward compatibility only +#ifndef CV_ErrorNoReturn +#define CV_ErrorNoReturn CV_Error +#endif +#ifndef CV_ErrorNoReturn_ +#define CV_ErrorNoReturn_ CV_Error_ +#endif +#endif + +#define CV_Assert_1 CV_Assert +#define CV_Assert_2( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_1( __VA_ARGS__ )) +#define CV_Assert_3( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_2( __VA_ARGS__ )) +#define CV_Assert_4( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_3( __VA_ARGS__ )) +#define CV_Assert_5( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_4( __VA_ARGS__ )) +#define CV_Assert_6( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_5( __VA_ARGS__ )) +#define CV_Assert_7( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_6( __VA_ARGS__ )) +#define CV_Assert_8( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_7( __VA_ARGS__ )) +#define CV_Assert_9( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_8( __VA_ARGS__ )) +#define CV_Assert_10( expr, ... ) CV_Assert_1(expr); __CV_EXPAND(CV_Assert_9( __VA_ARGS__ )) + +#define CV_Assert_N(...) do { __CV_EXPAND(__CV_CAT(CV_Assert_, __CV_VA_NUM_ARGS(__VA_ARGS__)) (__VA_ARGS__)); } while(0) + +//! @endcond + +#if defined _DEBUG || defined CV_STATIC_ANALYSIS +# define CV_DbgAssert(expr) CV_Assert(expr) +#else +/** replaced with CV_Assert(expr) in Debug configuration */ +# define CV_DbgAssert(expr) +#endif + +/* + * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor + * bit count of A exclusive XOR'ed with B + */ +struct CV_EXPORTS Hamming +{ + static const NormTypes normType = NORM_HAMMING; + typedef unsigned char ValueType; + typedef int ResultType; + + /** this will count the bits in a ^ b + */ + ResultType operator()( const unsigned char* a, const unsigned char* b, int size ) const; +}; + +typedef Hamming HammingLUT; + +/////////////////////////////////// inline norms //////////////////////////////////// + +template inline _Tp cv_abs(_Tp x) { return std::abs(x); } +inline int cv_abs(uchar x) { return x; } +inline int cv_abs(schar x) { return std::abs(x); } +inline int cv_abs(ushort x) { return x; } +inline int cv_abs(short x) { return std::abs(x); } + +template static inline +_AccTp normL2Sqr(const _Tp* a, int n) +{ + _AccTp s = 0; + int i=0; +#if CV_ENABLE_UNROLLED + for( ; i <= n - 4; i += 4 ) + { + _AccTp v0 = a[i], v1 = a[i+1], v2 = a[i+2], v3 = a[i+3]; + s += v0*v0 + v1*v1 + v2*v2 + v3*v3; + } +#endif + for( ; i < n; i++ ) + { + _AccTp v = a[i]; + s += v*v; + } + return s; +} + +template static inline +_AccTp normL1(const _Tp* a, int n) +{ + _AccTp s = 0; + int i = 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) + { + s += (_AccTp)cv_abs(a[i]) + (_AccTp)cv_abs(a[i+1]) + + (_AccTp)cv_abs(a[i+2]) + (_AccTp)cv_abs(a[i+3]); + } +#endif + for( ; i < n; i++ ) + s += cv_abs(a[i]); + return s; +} + +template static inline +_AccTp normInf(const _Tp* a, int n) +{ + _AccTp s = 0; + for( int i = 0; i < n; i++ ) + s = std::max(s, (_AccTp)cv_abs(a[i])); + return s; +} + +template static inline +_AccTp normL2Sqr(const _Tp* a, const _Tp* b, int n) +{ + _AccTp s = 0; + int i= 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) + { + _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); + s += v0*v0 + v1*v1 + v2*v2 + v3*v3; + } +#endif + for( ; i < n; i++ ) + { + _AccTp v = _AccTp(a[i] - b[i]); + s += v*v; + } + return s; +} + +static inline float normL2Sqr(const float* a, const float* b, int n) +{ + float s = 0.f; + for( int i = 0; i < n; i++ ) + { + float v = a[i] - b[i]; + s += v*v; + } + return s; +} + +template static inline +_AccTp normL1(const _Tp* a, const _Tp* b, int n) +{ + _AccTp s = 0; + int i= 0; +#if CV_ENABLE_UNROLLED + for(; i <= n - 4; i += 4 ) + { + _AccTp v0 = _AccTp(a[i] - b[i]), v1 = _AccTp(a[i+1] - b[i+1]), v2 = _AccTp(a[i+2] - b[i+2]), v3 = _AccTp(a[i+3] - b[i+3]); + s += std::abs(v0) + std::abs(v1) + std::abs(v2) + std::abs(v3); + } +#endif + for( ; i < n; i++ ) + { + _AccTp v = _AccTp(a[i] - b[i]); + s += std::abs(v); + } + return s; +} + +inline float normL1(const float* a, const float* b, int n) +{ + float s = 0.f; + for( int i = 0; i < n; i++ ) + { + s += std::abs(a[i] - b[i]); + } + return s; +} + +inline int normL1(const uchar* a, const uchar* b, int n) +{ + int s = 0; + for( int i = 0; i < n; i++ ) + { + s += std::abs(a[i] - b[i]); + } + return s; +} + +template static inline +_AccTp normInf(const _Tp* a, const _Tp* b, int n) +{ + _AccTp s = 0; + for( int i = 0; i < n; i++ ) + { + _AccTp v0 = a[i] - b[i]; + s = std::max(s, std::abs(v0)); + } + return s; +} + +/** @brief Computes the cube root of an argument. + + The function cubeRoot computes \f$\sqrt[3]{\texttt{val}}\f$. Negative arguments are handled correctly. + NaN and Inf are not handled. The accuracy approaches the maximum possible accuracy for + single-precision data. + @param val A function argument. + */ +CV_EXPORTS_W float cubeRoot(float val); + +/** @overload + +cubeRoot with argument of `double` type calls `std::cbrt(double)` +*/ +static inline +double cubeRoot(double val) +{ + return std::cbrt(val); +} + +/** @brief Calculates the angle of a 2D vector in degrees. + + The function fastAtan2 calculates the full-range angle of an input 2D vector. The angle is measured + in degrees and varies from 0 to 360 degrees. The accuracy is about 0.3 degrees. + @param x x-coordinate of the vector. + @param y y-coordinate of the vector. + */ +CV_EXPORTS_W float fastAtan2(float y, float x); + +/** proxy for hal::LU */ +CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); +/** proxy for hal::LU */ +CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); +/** proxy for hal::Cholesky */ +CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); +/** proxy for hal::Cholesky */ +CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); + +////////////////// forward declarations for important OpenCV types ////////////////// + +//! @cond IGNORED + +template class Vec; +template class Matx; + +template class Complex; +template class Point_; +template class Point3_; +template class Size_; +template class Rect_; +template class Scalar_; + +class CV_EXPORTS RotatedRect; +class CV_EXPORTS Range; +class CV_EXPORTS TermCriteria; +class CV_EXPORTS KeyPoint; +class CV_EXPORTS DMatch; +class CV_EXPORTS RNG; + +class CV_EXPORTS Mat; +class CV_EXPORTS MatExpr; + +class CV_EXPORTS UMat; + +class CV_EXPORTS SparseMat; +typedef Mat MatND; + +template class Mat_; +template class SparseMat_; + +class CV_EXPORTS MatConstIterator; +class CV_EXPORTS SparseMatIterator; +class CV_EXPORTS SparseMatConstIterator; +template class MatIterator_; +template class MatConstIterator_; +template class SparseMatIterator_; +template class SparseMatConstIterator_; + +namespace ogl +{ + class CV_EXPORTS Buffer; + class CV_EXPORTS Texture2D; + class CV_EXPORTS Arrays; +} + +namespace cuda +{ + class CV_EXPORTS GpuMat; + class CV_EXPORTS HostMem; + class CV_EXPORTS Stream; + class CV_EXPORTS Event; +} + +namespace cudev +{ + template class GpuMat_; +} + +namespace ipp +{ +CV_EXPORTS unsigned long long getIppFeatures(); +CV_EXPORTS void setIppStatus(int status, const char * const funcname = NULL, const char * const filename = NULL, + int line = 0); +CV_EXPORTS int getIppStatus(); +CV_EXPORTS String getIppErrorLocation(); +CV_EXPORTS_W bool useIPP(); +CV_EXPORTS_W void setUseIPP(bool flag); +CV_EXPORTS_W String getIppVersion(); + +// IPP Not-Exact mode. This function may force use of IPP then both IPP and OpenCV provide proper results +// but have internal accuracy differences which have too much direct or indirect impact on accuracy tests. +CV_EXPORTS_W bool useIPP_NotExact(); +CV_EXPORTS_W void setUseIPP_NotExact(bool flag); +#ifndef DISABLE_OPENCV_3_COMPATIBILITY +static inline bool useIPP_NE() { return useIPP_NotExact(); } +static inline void setUseIPP_NE(bool flag) { setUseIPP_NotExact(flag); } +#endif + +} // ipp + +//! @endcond + +//! @} core_utils + + + + +} // cv + +#include "opencv2/core/neon_utils.hpp" +#include "opencv2/core/vsx_utils.hpp" +#include "opencv2/core/check.hpp" + +#endif //OPENCV_CORE_BASE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp index 0e18693e24..9c8f9e0f2b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/bindings_utils.hpp @@ -1,357 +1,357 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_BINDINGS_UTILS_HPP -#define OPENCV_CORE_BINDINGS_UTILS_HPP - -#include -#include -#include - -#include - -namespace cv { namespace utils { -//! @addtogroup core_utils -//! @{ - -CV_EXPORTS_W String dumpInputArray(InputArray argument); - -CV_EXPORTS_W String dumpInputArrayOfArrays(InputArrayOfArrays argument); - -CV_EXPORTS_W String dumpInputOutputArray(InputOutputArray argument); - -CV_EXPORTS_W String dumpInputOutputArrayOfArrays(InputOutputArrayOfArrays argument); - -CV_WRAP static inline -String dumpBool(bool argument) -{ - return (argument) ? String("Bool: True") : String("Bool: False"); -} - -CV_WRAP static inline -String dumpInt(int argument) -{ - return cv::format("Int: %d", argument); -} - -CV_WRAP static inline -String dumpInt64(int64 argument) -{ - std::ostringstream oss("Int64: ", std::ios::ate); - oss << argument; - return oss.str(); -} - -CV_WRAP static inline -String dumpSizeT(size_t argument) -{ - std::ostringstream oss("size_t: ", std::ios::ate); - oss << argument; - return oss.str(); -} - -CV_WRAP static inline -String dumpFloat(float argument) -{ - return cv::format("Float: %.2f", argument); -} - -CV_WRAP static inline -String dumpDouble(double argument) -{ - return cv::format("Double: %.2f", argument); -} - -CV_WRAP static inline -String dumpCString(const char* argument) -{ - return cv::format("String: %s", argument); -} - -CV_WRAP static inline -String dumpString(const String& argument) -{ - return cv::format("String: %s", argument.c_str()); -} - -CV_WRAP static inline -String dumpRect(const Rect& argument) -{ - return format("rect: (x=%d, y=%d, w=%d, h=%d)", argument.x, argument.y, - argument.width, argument.height); -} - -CV_WRAP static inline -String dumpTermCriteria(const TermCriteria& argument) -{ - return format("term_criteria: (type=%d, max_count=%d, epsilon=%lf", - argument.type, argument.maxCount, argument.epsilon); -} - -CV_WRAP static inline -String dumpRotatedRect(const RotatedRect& argument) -{ - return format("rotated_rect: (c_x=%f, c_y=%f, w=%f, h=%f, a=%f)", - argument.center.x, argument.center.y, argument.size.width, - argument.size.height, argument.angle); -} - -CV_WRAP static inline -String dumpRange(const Range& argument) -{ - if (argument == Range::all()) - { - return "range: all"; - } - else - { - return format("range: (s=%d, e=%d)", argument.start, argument.end); - } -} - -CV_EXPORTS_W String dumpVectorOfInt(const std::vector& vec); - -CV_EXPORTS_W String dumpVectorOfDouble(const std::vector& vec); - -CV_EXPORTS_W String dumpVectorOfRect(const std::vector& vec); - - -//! @cond IGNORED - -CV_WRAP static inline -String testOverloadResolution(int value, const Point& point = Point(42, 24)) -{ - return format("overload (int=%d, point=(x=%d, y=%d))", value, point.x, - point.y); -} - -CV_WRAP static inline -String testOverloadResolution(const Rect& rect) -{ - return format("overload (rect=(x=%d, y=%d, w=%d, h=%d))", rect.x, rect.y, - rect.width, rect.height); -} - -CV_WRAP static inline -RotatedRect testRotatedRect(float x, float y, float w, float h, float angle) -{ - return RotatedRect(Point2f(x, y), Size2f(w, h), angle); -} - -CV_WRAP static inline -std::vector testRotatedRectVector(float x, float y, float w, float h, float angle) -{ - std::vector result; - for (int i = 0; i < 10; i++) - result.push_back(RotatedRect(Point2f(x + i, y + 2 * i), Size2f(w, h), angle + 10 * i)); - return result; -} - -CV_WRAP static inline -int testOverwriteNativeMethod(int argument) -{ - return argument; -} - -CV_WRAP static inline -String testReservedKeywordConversion(int positional_argument, int lambda = 2, int from = 3) -{ - return format("arg=%d, lambda=%d, from=%d", positional_argument, lambda, from); -} - -CV_WRAP static inline -void generateVectorOfRect(size_t len, CV_OUT std::vector& vec) -{ - vec.resize(len); - if (len > 0) - { - RNG rng(12345); - Mat tmp(static_cast(len), 1, CV_32SC4); - rng.fill(tmp, RNG::UNIFORM, 10, 20); - tmp.copyTo(vec); - } -} - -CV_WRAP static inline -void generateVectorOfInt(size_t len, CV_OUT std::vector& vec) -{ - vec.resize(len); - if (len > 0) - { - RNG rng(554433); - Mat tmp(static_cast(len), 1, CV_32SC1); - rng.fill(tmp, RNG::UNIFORM, -10, 10); - tmp.copyTo(vec); - } -} - -CV_WRAP static inline -void generateVectorOfMat(size_t len, int rows, int cols, int dtype, CV_OUT std::vector& vec) -{ - vec.resize(len); - if (len > 0) - { - RNG rng(65431); - for (size_t i = 0; i < len; ++i) - { - vec[i].create(rows, cols, dtype); - rng.fill(vec[i], RNG::UNIFORM, 0, 10); - } - } -} - -CV_WRAP static inline -void testRaiseGeneralException() -{ - throw std::runtime_error("exception text"); -} - -CV_WRAP static inline -AsyncArray testAsyncArray(InputArray argument) -{ - AsyncPromise p; - p.setValue(argument); - return p.getArrayResult(); -} - -CV_WRAP static inline -AsyncArray testAsyncException() -{ - AsyncPromise p; - try - { - CV_Error(Error::StsOk, "Test: Generated async error"); - } - catch (const cv::Exception& e) - { - p.setException(e); - } - return p.getArrayResult(); -} - -CV_WRAP static inline -String dumpVec2i(const cv::Vec2i value = cv::Vec2i(42, 24)) { - return format("Vec2i(%d, %d)", value[0], value[1]); -} - -struct CV_EXPORTS_W_SIMPLE ClassWithKeywordProperties { - CV_PROP_RW int lambda; - CV_PROP int except; - - CV_WRAP explicit ClassWithKeywordProperties(int lambda_arg = 24, int except_arg = 42) - { - lambda = lambda_arg; - except = except_arg; - } -}; - -struct CV_EXPORTS_W_PARAMS FunctionParams -{ - CV_PROP_RW int lambda = -1; - CV_PROP_RW float sigma = 0.0f; - - FunctionParams& setLambda(int value) CV_NOEXCEPT - { - lambda = value; - return *this; - } - - FunctionParams& setSigma(float value) CV_NOEXCEPT - { - sigma = value; - return *this; - } -}; - -CV_WRAP static inline String -copyMatAndDumpNamedArguments(InputArray src, OutputArray dst, - const FunctionParams& params = FunctionParams()) -{ - src.copyTo(dst); - return format("lambda=%d, sigma=%.1f", params.lambda, - params.sigma); -} - -namespace nested { -CV_WRAP static inline bool testEchoBooleanFunction(bool flag) { - return flag; -} - -class CV_EXPORTS_W CV_WRAP_AS(ExportClassName) OriginalClassName -{ -public: - struct CV_EXPORTS_W_SIMPLE Params - { - CV_PROP_RW int int_value; - CV_PROP_RW float float_value; - - CV_WRAP explicit Params(int int_param = 123, float float_param = 3.5f) - { - int_value = int_param; - float_value = float_param; - } - }; - - explicit OriginalClassName(const OriginalClassName::Params& params = OriginalClassName::Params()) - { - params_ = params; - } - - CV_WRAP int getIntParam() const - { - return params_.int_value; - } - - CV_WRAP float getFloatParam() const - { - return params_.float_value; - } - - CV_WRAP static std::string originalName() - { - return "OriginalClassName"; - } - - CV_WRAP static Ptr - create(const OriginalClassName::Params& params = OriginalClassName::Params()) - { - return makePtr(params); - } - -private: - OriginalClassName::Params params_; -}; - -typedef OriginalClassName::Params OriginalClassName_Params; -} // namespace nested - -//! @endcond IGNORED - -namespace fs { - CV_EXPORTS_W cv::String getCacheDirectoryForDownloads(); -} // namespace fs - -//! @} // core_utils -} // namespace cv::utils - -//! @cond IGNORED - -CV_WRAP static inline -int setLogLevel(int level) -{ - // NB: Binding generators doesn't work with enums properly yet, so we define separate overload here - return cv::utils::logging::setLogLevel((cv::utils::logging::LogLevel)level); -} - -CV_WRAP static inline -int getLogLevel() -{ - return cv::utils::logging::getLogLevel(); -} - -//! @endcond IGNORED - -} // namespaces cv / utils - -#endif // OPENCV_CORE_BINDINGS_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_BINDINGS_UTILS_HPP +#define OPENCV_CORE_BINDINGS_UTILS_HPP + +#include +#include +#include + +#include + +namespace cv { namespace utils { +//! @addtogroup core_utils +//! @{ + +CV_EXPORTS_W String dumpInputArray(InputArray argument); + +CV_EXPORTS_W String dumpInputArrayOfArrays(InputArrayOfArrays argument); + +CV_EXPORTS_W String dumpInputOutputArray(InputOutputArray argument); + +CV_EXPORTS_W String dumpInputOutputArrayOfArrays(InputOutputArrayOfArrays argument); + +CV_WRAP static inline +String dumpBool(bool argument) +{ + return (argument) ? String("Bool: True") : String("Bool: False"); +} + +CV_WRAP static inline +String dumpInt(int argument) +{ + return cv::format("Int: %d", argument); +} + +CV_WRAP static inline +String dumpInt64(int64 argument) +{ + std::ostringstream oss("Int64: ", std::ios::ate); + oss << argument; + return oss.str(); +} + +CV_WRAP static inline +String dumpSizeT(size_t argument) +{ + std::ostringstream oss("size_t: ", std::ios::ate); + oss << argument; + return oss.str(); +} + +CV_WRAP static inline +String dumpFloat(float argument) +{ + return cv::format("Float: %.2f", argument); +} + +CV_WRAP static inline +String dumpDouble(double argument) +{ + return cv::format("Double: %.2f", argument); +} + +CV_WRAP static inline +String dumpCString(const char* argument) +{ + return cv::format("String: %s", argument); +} + +CV_WRAP static inline +String dumpString(const String& argument) +{ + return cv::format("String: %s", argument.c_str()); +} + +CV_WRAP static inline +String dumpRect(const Rect& argument) +{ + return format("rect: (x=%d, y=%d, w=%d, h=%d)", argument.x, argument.y, + argument.width, argument.height); +} + +CV_WRAP static inline +String dumpTermCriteria(const TermCriteria& argument) +{ + return format("term_criteria: (type=%d, max_count=%d, epsilon=%lf", + argument.type, argument.maxCount, argument.epsilon); +} + +CV_WRAP static inline +String dumpRotatedRect(const RotatedRect& argument) +{ + return format("rotated_rect: (c_x=%f, c_y=%f, w=%f, h=%f, a=%f)", + argument.center.x, argument.center.y, argument.size.width, + argument.size.height, argument.angle); +} + +CV_WRAP static inline +String dumpRange(const Range& argument) +{ + if (argument == Range::all()) + { + return "range: all"; + } + else + { + return format("range: (s=%d, e=%d)", argument.start, argument.end); + } +} + +CV_EXPORTS_W String dumpVectorOfInt(const std::vector& vec); + +CV_EXPORTS_W String dumpVectorOfDouble(const std::vector& vec); + +CV_EXPORTS_W String dumpVectorOfRect(const std::vector& vec); + + +//! @cond IGNORED + +CV_WRAP static inline +String testOverloadResolution(int value, const Point& point = Point(42, 24)) +{ + return format("overload (int=%d, point=(x=%d, y=%d))", value, point.x, + point.y); +} + +CV_WRAP static inline +String testOverloadResolution(const Rect& rect) +{ + return format("overload (rect=(x=%d, y=%d, w=%d, h=%d))", rect.x, rect.y, + rect.width, rect.height); +} + +CV_WRAP static inline +RotatedRect testRotatedRect(float x, float y, float w, float h, float angle) +{ + return RotatedRect(Point2f(x, y), Size2f(w, h), angle); +} + +CV_WRAP static inline +std::vector testRotatedRectVector(float x, float y, float w, float h, float angle) +{ + std::vector result; + for (int i = 0; i < 10; i++) + result.push_back(RotatedRect(Point2f(x + i, y + 2 * i), Size2f(w, h), angle + 10 * i)); + return result; +} + +CV_WRAP static inline +int testOverwriteNativeMethod(int argument) +{ + return argument; +} + +CV_WRAP static inline +String testReservedKeywordConversion(int positional_argument, int lambda = 2, int from = 3) +{ + return format("arg=%d, lambda=%d, from=%d", positional_argument, lambda, from); +} + +CV_WRAP static inline +void generateVectorOfRect(size_t len, CV_OUT std::vector& vec) +{ + vec.resize(len); + if (len > 0) + { + RNG rng(12345); + Mat tmp(static_cast(len), 1, CV_32SC4); + rng.fill(tmp, RNG::UNIFORM, 10, 20); + tmp.copyTo(vec); + } +} + +CV_WRAP static inline +void generateVectorOfInt(size_t len, CV_OUT std::vector& vec) +{ + vec.resize(len); + if (len > 0) + { + RNG rng(554433); + Mat tmp(static_cast(len), 1, CV_32SC1); + rng.fill(tmp, RNG::UNIFORM, -10, 10); + tmp.copyTo(vec); + } +} + +CV_WRAP static inline +void generateVectorOfMat(size_t len, int rows, int cols, int dtype, CV_OUT std::vector& vec) +{ + vec.resize(len); + if (len > 0) + { + RNG rng(65431); + for (size_t i = 0; i < len; ++i) + { + vec[i].create(rows, cols, dtype); + rng.fill(vec[i], RNG::UNIFORM, 0, 10); + } + } +} + +CV_WRAP static inline +void testRaiseGeneralException() +{ + throw std::runtime_error("exception text"); +} + +CV_WRAP static inline +AsyncArray testAsyncArray(InputArray argument) +{ + AsyncPromise p; + p.setValue(argument); + return p.getArrayResult(); +} + +CV_WRAP static inline +AsyncArray testAsyncException() +{ + AsyncPromise p; + try + { + CV_Error(Error::StsOk, "Test: Generated async error"); + } + catch (const cv::Exception& e) + { + p.setException(e); + } + return p.getArrayResult(); +} + +CV_WRAP static inline +String dumpVec2i(const cv::Vec2i value = cv::Vec2i(42, 24)) { + return format("Vec2i(%d, %d)", value[0], value[1]); +} + +struct CV_EXPORTS_W_SIMPLE ClassWithKeywordProperties { + CV_PROP_RW int lambda; + CV_PROP int except; + + CV_WRAP explicit ClassWithKeywordProperties(int lambda_arg = 24, int except_arg = 42) + { + lambda = lambda_arg; + except = except_arg; + } +}; + +struct CV_EXPORTS_W_PARAMS FunctionParams +{ + CV_PROP_RW int lambda = -1; + CV_PROP_RW float sigma = 0.0f; + + FunctionParams& setLambda(int value) CV_NOEXCEPT + { + lambda = value; + return *this; + } + + FunctionParams& setSigma(float value) CV_NOEXCEPT + { + sigma = value; + return *this; + } +}; + +CV_WRAP static inline String +copyMatAndDumpNamedArguments(InputArray src, OutputArray dst, + const FunctionParams& params = FunctionParams()) +{ + src.copyTo(dst); + return format("lambda=%d, sigma=%.1f", params.lambda, + params.sigma); +} + +namespace nested { +CV_WRAP static inline bool testEchoBooleanFunction(bool flag) { + return flag; +} + +class CV_EXPORTS_W CV_WRAP_AS(ExportClassName) OriginalClassName +{ +public: + struct CV_EXPORTS_W_SIMPLE Params + { + CV_PROP_RW int int_value; + CV_PROP_RW float float_value; + + CV_WRAP explicit Params(int int_param = 123, float float_param = 3.5f) + { + int_value = int_param; + float_value = float_param; + } + }; + + explicit OriginalClassName(const OriginalClassName::Params& params = OriginalClassName::Params()) + { + params_ = params; + } + + CV_WRAP int getIntParam() const + { + return params_.int_value; + } + + CV_WRAP float getFloatParam() const + { + return params_.float_value; + } + + CV_WRAP static std::string originalName() + { + return "OriginalClassName"; + } + + CV_WRAP static Ptr + create(const OriginalClassName::Params& params = OriginalClassName::Params()) + { + return makePtr(params); + } + +private: + OriginalClassName::Params params_; +}; + +typedef OriginalClassName::Params OriginalClassName_Params; +} // namespace nested + +//! @endcond IGNORED + +namespace fs { + CV_EXPORTS_W cv::String getCacheDirectoryForDownloads(); +} // namespace fs + +//! @} // core_utils +} // namespace cv::utils + +//! @cond IGNORED + +CV_WRAP static inline +int setLogLevel(int level) +{ + // NB: Binding generators doesn't work with enums properly yet, so we define separate overload here + return cv::utils::logging::setLogLevel((cv::utils::logging::LogLevel)level); +} + +CV_WRAP static inline +int getLogLevel() +{ + return cv::utils::logging::getLogLevel(); +} + +//! @endcond IGNORED + +} // namespaces cv / utils + +#endif // OPENCV_CORE_BINDINGS_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp b/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp index 5322c87953..e835ad025c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/bufferpool.hpp @@ -1,40 +1,40 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. - -#ifndef OPENCV_CORE_BUFFER_POOL_HPP -#define OPENCV_CORE_BUFFER_POOL_HPP - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4265) -#endif - -namespace cv -{ - -//! @addtogroup core_opencl -//! @{ - -class BufferPoolController -{ -protected: - ~BufferPoolController() { } -public: - virtual size_t getReservedSize() const = 0; - virtual size_t getMaxReservedSize() const = 0; - virtual void setMaxReservedSize(size_t size) = 0; - virtual void freeAllReservedBuffers() = 0; -}; - -//! @} - -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif // OPENCV_CORE_BUFFER_POOL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. + +#ifndef OPENCV_CORE_BUFFER_POOL_HPP +#define OPENCV_CORE_BUFFER_POOL_HPP + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4265) +#endif + +namespace cv +{ + +//! @addtogroup core_opencl +//! @{ + +class BufferPoolController +{ +protected: + ~BufferPoolController() { } +public: + virtual size_t getReservedSize() const = 0; + virtual size_t getMaxReservedSize() const = 0; + virtual void setMaxReservedSize(size_t size) = 0; + virtual void freeAllReservedBuffers() = 0; +}; + +//! @} + +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif // OPENCV_CORE_BUFFER_POOL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/check.hpp b/3rdParty/opencv-4.11.0/opencv2/core/check.hpp index dc1dd70820..aa1a839f70 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/check.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/check.hpp @@ -1,173 +1,173 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_CHECK_HPP -#define OPENCV_CORE_CHECK_HPP - -#include - -namespace cv { - -/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or "" */ -CV_EXPORTS const char* depthToString(int depth); - -/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or "" */ -CV_EXPORTS String typeToString(int type); - - -//! @cond IGNORED -namespace detail { - -/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or NULL */ -CV_EXPORTS const char* depthToString_(int depth); - -/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or cv::String() */ -CV_EXPORTS cv::String typeToString_(int type); - -enum TestOp { - TEST_CUSTOM = 0, - TEST_EQ = 1, - TEST_NE = 2, - TEST_LE = 3, - TEST_LT = 4, - TEST_GE = 5, - TEST_GT = 6, - CV__LAST_TEST_OP -}; - -struct CheckContext { - const char* func; - const char* file; - int line; - enum TestOp testOp; - const char* message; - const char* p1_str; - const char* p2_str; -}; - -#ifndef CV__CHECK_FILENAME -# define CV__CHECK_FILENAME __FILE__ -#endif - -#ifndef CV__CHECK_FUNCTION -# if defined _MSC_VER -# define CV__CHECK_FUNCTION __FUNCSIG__ -# elif defined __GNUC__ -# define CV__CHECK_FUNCTION __PRETTY_FUNCTION__ -# else -# define CV__CHECK_FUNCTION "" -# endif -#endif - -#define CV__CHECK_LOCATION_VARNAME(id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_check_, id), __LINE__) -#define CV__DEFINE_CHECK_CONTEXT(id, message, testOp, p1_str, p2_str) \ - static const cv::detail::CheckContext CV__CHECK_LOCATION_VARNAME(id) = \ - { CV__CHECK_FUNCTION, CV__CHECK_FILENAME, __LINE__, testOp, "" message, "" p1_str, "" p2_str } - -CV_EXPORTS void CV_NORETURN check_failed_auto(const bool v1, const bool v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const int v1, const int v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v1, const size_t v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const float v1, const float v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const double v1, const double v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v1, const Size_ v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v1, const int v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v1, const int v2, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v1, const int v2, const CheckContext& ctx); - -CV_EXPORTS void CV_NORETURN check_failed_true(const bool v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_false(const bool v, const CheckContext& ctx); - -CV_EXPORTS void CV_NORETURN check_failed_auto(const int v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const float v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const double v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_auto(const std::string& v1, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v, const CheckContext& ctx); -CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v, const CheckContext& ctx); - - -#define CV__TEST_EQ(v1, v2) ((v1) == (v2)) -#define CV__TEST_NE(v1, v2) ((v1) != (v2)) -#define CV__TEST_LE(v1, v2) ((v1) <= (v2)) -#define CV__TEST_LT(v1, v2) ((v1) < (v2)) -#define CV__TEST_GE(v1, v2) ((v1) >= (v2)) -#define CV__TEST_GT(v1, v2) ((v1) > (v2)) - -#define CV__CHECK(id, op, type, v1, v2, v1_str, v2_str, msg_str) do { \ - if(CV__TEST_##op((v1), (v2))) ; else { \ - CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_ ## op, v1_str, v2_str); \ - cv::detail::check_failed_ ## type((v1), (v2), CV__CHECK_LOCATION_VARNAME(id)); \ - } \ -} while (0) - -#define CV__CHECK_CUSTOM_TEST(id, type, v, test_expr, v_str, test_expr_str, msg_str) do { \ - if(!!(test_expr)) ; else { \ - CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_CUSTOM, v_str, test_expr_str); \ - cv::detail::check_failed_ ## type((v), CV__CHECK_LOCATION_VARNAME(id)); \ - } \ -} while (0) - -} // namespace -//! @endcond - - -/// Supported values of these types: int, float, double -#define CV_CheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) -#define CV_CheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) - -/// Check with additional "decoding" of type values in error message -#define CV_CheckTypeEQ(t1, t2, msg) CV__CHECK(_, EQ, MatType, t1, t2, #t1, #t2, msg) -/// Check with additional "decoding" of depth values in error message -#define CV_CheckDepthEQ(d1, d2, msg) CV__CHECK(_, EQ, MatDepth, d1, d2, #d1, #d2, msg) - -#define CV_CheckChannelsEQ(c1, c2, msg) CV__CHECK(_, EQ, MatChannels, c1, c2, #c1, #c2, msg) - -/// Example: type == CV_8UC1 || type == CV_8UC3 -#define CV_CheckType(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatType, t, (test_expr), #t, #test_expr, msg) - -/// Example: depth == CV_32F || depth == CV_64F -#define CV_CheckDepth(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatDepth, t, (test_expr), #t, #test_expr, msg) - -/// Example: channel == 1 || channel == 3 -#define CV_CheckChannels(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatChannels, t, (test_expr), #t, #test_expr, msg) - -/// Example: v == A || v == B -#define CV_Check(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) - -/// Example: v == true -#define CV_CheckTrue(v, msg) CV__CHECK_CUSTOM_TEST(_, true, v, v, #v, "", msg) - -/// Example: v == false -#define CV_CheckFalse(v, msg) CV__CHECK_CUSTOM_TEST(_, false, v, (!(v)), #v, "", msg) - -/// Some complex conditions: CV_Check(src2, src2.empty() || (src2.type() == src1.type() && src2.size() == src1.size()), "src2 should have same size/type as src1") -// TODO define pretty-printers - -#ifndef NDEBUG -#define CV_DbgCheck(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) -#define CV_DbgCheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) -#define CV_DbgCheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) -#else -#define CV_DbgCheck(v, test_expr, msg) do { } while (0) -#define CV_DbgCheckEQ(v1, v2, msg) do { } while (0) -#define CV_DbgCheckNE(v1, v2, msg) do { } while (0) -#define CV_DbgCheckLE(v1, v2, msg) do { } while (0) -#define CV_DbgCheckLT(v1, v2, msg) do { } while (0) -#define CV_DbgCheckGE(v1, v2, msg) do { } while (0) -#define CV_DbgCheckGT(v1, v2, msg) do { } while (0) -#endif - -} // namespace - -#endif // OPENCV_CORE_CHECK_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_CHECK_HPP +#define OPENCV_CORE_CHECK_HPP + +#include + +namespace cv { + +/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or "" */ +CV_EXPORTS const char* depthToString(int depth); + +/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or "" */ +CV_EXPORTS String typeToString(int type); + + +//! @cond IGNORED +namespace detail { + +/** Returns string of cv::Mat depth value: CV_8U -> "CV_8U" or NULL */ +CV_EXPORTS const char* depthToString_(int depth); + +/** Returns string of cv::Mat depth value: CV_8UC3 -> "CV_8UC3" or cv::String() */ +CV_EXPORTS cv::String typeToString_(int type); + +enum TestOp { + TEST_CUSTOM = 0, + TEST_EQ = 1, + TEST_NE = 2, + TEST_LE = 3, + TEST_LT = 4, + TEST_GE = 5, + TEST_GT = 6, + CV__LAST_TEST_OP +}; + +struct CheckContext { + const char* func; + const char* file; + int line; + enum TestOp testOp; + const char* message; + const char* p1_str; + const char* p2_str; +}; + +#ifndef CV__CHECK_FILENAME +# define CV__CHECK_FILENAME __FILE__ +#endif + +#ifndef CV__CHECK_FUNCTION +# if defined _MSC_VER +# define CV__CHECK_FUNCTION __FUNCSIG__ +# elif defined __GNUC__ +# define CV__CHECK_FUNCTION __PRETTY_FUNCTION__ +# else +# define CV__CHECK_FUNCTION "" +# endif +#endif + +#define CV__CHECK_LOCATION_VARNAME(id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_check_, id), __LINE__) +#define CV__DEFINE_CHECK_CONTEXT(id, message, testOp, p1_str, p2_str) \ + static const cv::detail::CheckContext CV__CHECK_LOCATION_VARNAME(id) = \ + { CV__CHECK_FUNCTION, CV__CHECK_FILENAME, __LINE__, testOp, "" message, "" p1_str, "" p2_str } + +CV_EXPORTS void CV_NORETURN check_failed_auto(const bool v1, const bool v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const int v1, const int v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v1, const size_t v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const float v1, const float v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const double v1, const double v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v1, const Size_ v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v1, const int v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v1, const int v2, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v1, const int v2, const CheckContext& ctx); + +CV_EXPORTS void CV_NORETURN check_failed_true(const bool v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_false(const bool v, const CheckContext& ctx); + +CV_EXPORTS void CV_NORETURN check_failed_auto(const int v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const size_t v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const float v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const double v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const Size_ v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_auto(const std::string& v1, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatDepth(const int v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatType(const int v, const CheckContext& ctx); +CV_EXPORTS void CV_NORETURN check_failed_MatChannels(const int v, const CheckContext& ctx); + + +#define CV__TEST_EQ(v1, v2) ((v1) == (v2)) +#define CV__TEST_NE(v1, v2) ((v1) != (v2)) +#define CV__TEST_LE(v1, v2) ((v1) <= (v2)) +#define CV__TEST_LT(v1, v2) ((v1) < (v2)) +#define CV__TEST_GE(v1, v2) ((v1) >= (v2)) +#define CV__TEST_GT(v1, v2) ((v1) > (v2)) + +#define CV__CHECK(id, op, type, v1, v2, v1_str, v2_str, msg_str) do { \ + if(CV__TEST_##op((v1), (v2))) ; else { \ + CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_ ## op, v1_str, v2_str); \ + cv::detail::check_failed_ ## type((v1), (v2), CV__CHECK_LOCATION_VARNAME(id)); \ + } \ +} while (0) + +#define CV__CHECK_CUSTOM_TEST(id, type, v, test_expr, v_str, test_expr_str, msg_str) do { \ + if(!!(test_expr)) ; else { \ + CV__DEFINE_CHECK_CONTEXT(id, msg_str, cv::detail::TEST_CUSTOM, v_str, test_expr_str); \ + cv::detail::check_failed_ ## type((v), CV__CHECK_LOCATION_VARNAME(id)); \ + } \ +} while (0) + +} // namespace +//! @endcond + + +/// Supported values of these types: int, float, double +#define CV_CheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) +#define CV_CheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) + +/// Check with additional "decoding" of type values in error message +#define CV_CheckTypeEQ(t1, t2, msg) CV__CHECK(_, EQ, MatType, t1, t2, #t1, #t2, msg) +/// Check with additional "decoding" of depth values in error message +#define CV_CheckDepthEQ(d1, d2, msg) CV__CHECK(_, EQ, MatDepth, d1, d2, #d1, #d2, msg) + +#define CV_CheckChannelsEQ(c1, c2, msg) CV__CHECK(_, EQ, MatChannels, c1, c2, #c1, #c2, msg) + +/// Example: type == CV_8UC1 || type == CV_8UC3 +#define CV_CheckType(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatType, t, (test_expr), #t, #test_expr, msg) + +/// Example: depth == CV_32F || depth == CV_64F +#define CV_CheckDepth(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatDepth, t, (test_expr), #t, #test_expr, msg) + +/// Example: channel == 1 || channel == 3 +#define CV_CheckChannels(t, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, MatChannels, t, (test_expr), #t, #test_expr, msg) + +/// Example: v == A || v == B +#define CV_Check(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) + +/// Example: v == true +#define CV_CheckTrue(v, msg) CV__CHECK_CUSTOM_TEST(_, true, v, v, #v, "", msg) + +/// Example: v == false +#define CV_CheckFalse(v, msg) CV__CHECK_CUSTOM_TEST(_, false, v, (!(v)), #v, "", msg) + +/// Some complex conditions: CV_Check(src2, src2.empty() || (src2.type() == src1.type() && src2.size() == src1.size()), "src2 should have same size/type as src1") +// TODO define pretty-printers + +#ifndef NDEBUG +#define CV_DbgCheck(v, test_expr, msg) CV__CHECK_CUSTOM_TEST(_, auto, v, (test_expr), #v, #test_expr, msg) +#define CV_DbgCheckEQ(v1, v2, msg) CV__CHECK(_, EQ, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckNE(v1, v2, msg) CV__CHECK(_, NE, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckLE(v1, v2, msg) CV__CHECK(_, LE, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckLT(v1, v2, msg) CV__CHECK(_, LT, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckGE(v1, v2, msg) CV__CHECK(_, GE, auto, v1, v2, #v1, #v2, msg) +#define CV_DbgCheckGT(v1, v2, msg) CV__CHECK(_, GT, auto, v1, v2, #v1, #v2, msg) +#else +#define CV_DbgCheck(v, test_expr, msg) do { } while (0) +#define CV_DbgCheckEQ(v1, v2, msg) do { } while (0) +#define CV_DbgCheckNE(v1, v2, msg) do { } while (0) +#define CV_DbgCheckLE(v1, v2, msg) do { } while (0) +#define CV_DbgCheckLT(v1, v2, msg) do { } while (0) +#define CV_DbgCheckGE(v1, v2, msg) do { } while (0) +#define CV_DbgCheckGT(v1, v2, msg) do { } while (0) +#endif + +} // namespace + +#endif // OPENCV_CORE_CHECK_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/core.hpp b/3rdParty/opencv-4.11.0/opencv2/core/core.hpp index 3a884c3909..438918359b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/core.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/core.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/core.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/core/core_c.h b/3rdParty/opencv-4.11.0/opencv2/core/core_c.h index 7ed5cf221b..7b686b86f3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/core_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/core_c.h @@ -1,3128 +1,3128 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - - -#ifndef OPENCV_CORE_C_H -#define OPENCV_CORE_C_H - -#include "opencv2/core/types_c.h" - -#ifdef __cplusplus -/* disable MSVC warning C4190 / clang-cl -Wreturn-type-c-linkage: - 'function' has C-linkage specified, but returns UDT 'typename' - which is incompatible with C - - It is OK to disable it because we only extend few plain structures with - C++ constructors for simpler interoperability with C++ API of the library -*/ -# if defined(__clang__) - // handle clang on Linux and clang-cl (i. e. clang on Windows) first -# pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" -# elif defined(_MSC_VER) - // then handle MSVC -# pragma warning(disable:4190) -# endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup core_c - @{ -*/ - -/****************************************************************************************\ -* Array allocation, deallocation, initialization and access to elements * -\****************************************************************************************/ - -/** `malloc` wrapper. - If there is no enough memory, the function - (as well as other OpenCV functions that call cvAlloc) - raises an error. */ -CVAPI(void*) cvAlloc( size_t size ); - -/** `free` wrapper. - Here and further all the memory releasing functions - (that all call cvFree) take double pointer in order to - to clear pointer to the data after releasing it. - Passing pointer to NULL pointer is Ok: nothing happens in this case -*/ -CVAPI(void) cvFree_( void* ptr ); -#define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) - -/** @brief Creates an image header but does not allocate the image data. - -@param size Image width and height -@param depth Image depth (see cvCreateImage ) -@param channels Number of channels (see cvCreateImage ) - */ -CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); - -/** @brief Initializes an image header that was previously allocated. - -The returned IplImage\* points to the initialized header. -@param image Image header to initialize -@param size Image width and height -@param depth Image depth (see cvCreateImage ) -@param channels Number of channels (see cvCreateImage ) -@param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL -@param align Alignment for image rows, typically 4 or 8 bytes - */ -CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, - int channels, int origin CV_DEFAULT(0), - int align CV_DEFAULT(4)); - -/** @brief Creates an image header and allocates the image data. - -This function call is equivalent to the following code: -@code - header = cvCreateImageHeader(size, depth, channels); - cvCreateData(header); -@endcode -@param size Image width and height -@param depth Bit depth of image elements. See IplImage for valid depths. -@param channels Number of channels per pixel. See IplImage for details. This function only creates -images with interleaved channels. - */ -CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); - -/** @brief Deallocates an image header. - -This call is an analogue of : -@code - if(image ) - { - iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); - *image = 0; - } -@endcode -but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). -@param image Double pointer to the image header - */ -CVAPI(void) cvReleaseImageHeader( IplImage** image ); - -/** @brief Deallocates the image header and the image data. - -This call is a shortened form of : -@code - if(*image ) - { - cvReleaseData(*image); - cvReleaseImageHeader(image); - } -@endcode -@param image Double pointer to the image header -*/ -CVAPI(void) cvReleaseImage( IplImage** image ); - -/** Creates a copy of IPL image (widthStep may differ) */ -CVAPI(IplImage*) cvCloneImage( const IplImage* image ); - -/** @brief Sets the channel of interest in an IplImage. - -If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do -*not* support the COI setting, so to process an individual image/matrix channel one may copy (via -cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result -back (via cvCopy or cvMerge) if needed. -@param image A pointer to the image header -@param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, -etc. Note that the channel indices become 1-based. - */ -CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); - -/** @brief Returns the index of the channel of interest. - -Returns the channel of interest of in an IplImage. Returned values correspond to the coi in -cvSetImageCOI. -@param image A pointer to the image header - */ -CVAPI(int) cvGetImageCOI( const IplImage* image ); - -/** @brief Sets an image Region Of Interest (ROI) for a given rectangle. - -If the original image ROI was NULL and the rect is not the whole image, the ROI structure is -allocated. - -Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For -example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the -ROI, not the original image. -@param image A pointer to the image header -@param rect The ROI rectangle - */ -CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); - -/** @brief Resets the image ROI to include the entire image and releases the ROI structure. - -This produces a similar result to the following, but in addition it releases the ROI structure. : -@code - cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); - cvSetImageCOI(image, 0); -@endcode -@param image A pointer to the image header - */ -CVAPI(void) cvResetImageROI( IplImage* image ); - -/** @brief Returns the image ROI. - -If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. -@param image A pointer to the image header - */ -CVAPI(CvRect) cvGetImageROI( const IplImage* image ); - -/** @brief Creates a matrix header but does not allocate the matrix data. - -The function allocates a new matrix header and returns a pointer to it. The matrix data can then be -allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type Type of the matrix elements, see cvCreateMat - */ -CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); - -#define CV_AUTOSTEP 0x7fffffff - -/** @brief Initializes a pre-allocated matrix header. - -This function is often used to process raw data with OpenCV matrix functions. For example, the -following code computes the matrix product of two matrices, stored as ordinary arrays: -@code - double a[] = { 1, 2, 3, 4, - 5, 6, 7, 8, - 9, 10, 11, 12 }; - - double b[] = { 1, 5, 9, - 2, 6, 10, - 3, 7, 11, - 4, 8, 12 }; - - double c[9]; - CvMat Ma, Mb, Mc ; - - cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); - cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); - cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); - - cvMatMulAdd(&Ma, &Mb, 0, &Mc); - // the c array now contains the product of a (3x4) and b (4x3) -@endcode -@param mat A pointer to the matrix header to be initialized -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type Type of the matrix elements, see cvCreateMat . -@param data Optional: data pointer assigned to the matrix header -@param step Optional: full row width in bytes of the assigned data. By default, the minimal -possible step is used which assumes there are no gaps between subsequent rows of the matrix. - */ -CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, - int type, void* data CV_DEFAULT(NULL), - int step CV_DEFAULT(CV_AUTOSTEP) ); - -/** @brief Creates a matrix header and allocates the matrix data. - -The function call is equivalent to the following code: -@code - CvMat* mat = cvCreateMatHeader(rows, cols, type); - cvCreateData(mat); -@endcode -@param rows Number of rows in the matrix -@param cols Number of columns in the matrix -@param type The type of the matrix elements in the form -CV_\\C\ , where S=signed, U=unsigned, F=float. For -example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ -32SC2 means the elements are 32-bit signed and there are 2 channels. - */ -CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); - -/** @brief Deallocates a matrix. - -The function decrements the matrix data reference counter and deallocates matrix header. If the data -reference counter is 0, it also deallocates the data. : -@code - if(*mat ) - cvDecRefData(*mat); - cvFree((void**)mat); -@endcode -@param mat Double pointer to the matrix - */ -CVAPI(void) cvReleaseMat( CvMat** mat ); - -/** @brief Decrements an array data reference counter. - -The function decrements the data reference counter in a CvMat or CvMatND if the reference counter - -pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current -implementation the reference counter is not NULL only if the data was allocated using the -cvCreateData function. The counter will be NULL in other cases such as: external data was assigned -to the header using cvSetData, header is part of a larger matrix or image, or the header was -converted from an image or n-dimensional matrix header. -@param arr Pointer to an array header - */ -CV_INLINE void cvDecRefData( CvArr* arr ) -{ - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - mat->data.ptr = NULL; - if( mat->refcount != NULL && --*mat->refcount == 0 ) - cvFree( &mat->refcount ); - mat->refcount = NULL; - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - mat->data.ptr = NULL; - if( mat->refcount != NULL && --*mat->refcount == 0 ) - cvFree( &mat->refcount ); - mat->refcount = NULL; - } -} - -/** @brief Increments array data reference counter. - -The function increments CvMat or CvMatND data reference counter and returns the new counter value if -the reference counter pointer is not NULL, otherwise it returns zero. -@param arr Array header - */ -CV_INLINE int cvIncRefData( CvArr* arr ) -{ - int refcount = 0; - if( CV_IS_MAT( arr )) - { - CvMat* mat = (CvMat*)arr; - if( mat->refcount != NULL ) - refcount = ++*mat->refcount; - } - else if( CV_IS_MATND( arr )) - { - CvMatND* mat = (CvMatND*)arr; - if( mat->refcount != NULL ) - refcount = ++*mat->refcount; - } - return refcount; -} - - -/** Creates an exact copy of the input matrix (except, may be, step value) */ -CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); - - -/** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. - -The function returns header, corresponding to a specified rectangle of the input array. In other - -words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is -taken into account by the function so the sub-array of ROI is actually extracted. -@param arr Input array -@param submat Pointer to the resultant sub-array header -@param rect Zero-based coordinates of the rectangle of interest - */ -CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); -#define cvGetSubArr cvGetSubRect - -/** @brief Returns array row or row span. - -The function returns the header, corresponding to a specified row/row span of the input array. -cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param start_row Zero-based index of the starting row (inclusive) of the span -@param end_row Zero-based index of the ending row (exclusive) of the span -@param delta_row Index step in the row span. That is, the function extracts every delta_row -th -row from start_row and up to (but not including) end_row . - */ -CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, - int start_row, int end_row, - int delta_row CV_DEFAULT(1)); - -/** @overload -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param row Zero-based index of the selected row -*/ -CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) -{ - return cvGetRows( arr, submat, row, row + 1, 1 ); -} - - -/** @brief Returns one of more array columns. - -The function returns the header, corresponding to a specified column span of the input array. That - -is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. -If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for -cvGetCols(arr, submat, col, col+1). -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param start_col Zero-based index of the starting column (inclusive) of the span -@param end_col Zero-based index of the ending column (exclusive) of the span - */ -CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, - int start_col, int end_col ); - -/** @overload -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param col Zero-based index of the selected column -*/ -CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) -{ - return cvGetCols( arr, submat, col, col + 1 ); -} - -/** @brief Returns one of array diagonals. - -The function returns the header, corresponding to a specified diagonal of the input array. -@param arr Input array -@param submat Pointer to the resulting sub-array header -@param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 -corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so -forth. - */ -CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, - int diag CV_DEFAULT(0)); - -/** low-level scalar <-> raw data conversion functions */ -CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, - int extend_to_12 CV_DEFAULT(0) ); - -CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); - -/** @brief Creates a new matrix header but does not allocate the matrix data. - -The function allocates a header for a multi-dimensional dense array. The array data can further be -allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. -@param dims Number of array dimensions -@param sizes Array of dimension sizes -@param type Type of array elements, see cvCreateMat - */ -CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); - -/** @brief Creates the header and allocates the data for a multi-dimensional dense array. - -This function call is equivalent to the following code: -@code - CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); - cvCreateData(mat); -@endcode -@param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be -changed at build time). -@param sizes Array of dimension sizes. -@param type Type of array elements, see cvCreateMat . - */ -CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); - -/** @brief Initializes a pre-allocated multi-dimensional array header. - -@param mat A pointer to the array header to be initialized -@param dims The number of array dimensions -@param sizes An array of dimension sizes -@param type Type of array elements, see cvCreateMat -@param data Optional data pointer assigned to the matrix header - */ -CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, - int type, void* data CV_DEFAULT(NULL) ); - -/** @brief Deallocates a multi-dimensional array. - -The function decrements the array data reference counter and releases the array header. If the -reference counter reaches 0, it also deallocates the data. : -@code - if(*mat ) - cvDecRefData(*mat); - cvFree((void**)mat); -@endcode -@param mat Double pointer to the array - */ -CV_INLINE void cvReleaseMatND( CvMatND** mat ) -{ - cvReleaseMat( (CvMat**)mat ); -} - -/** Creates a copy of CvMatND (except, may be, steps) */ -CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); - -/** @brief Creates sparse array. - -The function allocates a multi-dimensional sparse array. Initially the array contain no elements, -that is PtrND and other related functions will return 0 for every index. -@param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is -practically unlimited (up to \f$2^{16}\f$ ). -@param sizes Array of dimension sizes -@param type Type of array elements. The same as for CvMat - */ -CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); - -/** @brief Deallocates sparse array. - -The function releases the sparse array and clears the array pointer upon exit. -@param mat Double pointer to the array - */ -CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); - -/** Creates a copy of CvSparseMat (except, may be, zero items) */ -CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); - -/** @brief Initializes sparse array elements iterator. - -The function initializes iterator of sparse array elements and returns pointer to the first element, -or NULL if the array is empty. -@param mat Input array -@param mat_iterator Initialized iterator - */ -CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, - CvSparseMatIterator* mat_iterator ); - -/** @brief Returns the next sparse matrix element - -The function moves iterator to the next sparse matrix element and returns pointer to it. In the -current version there is no any particular order of the elements, because they are stored in the -hash table. The sample below demonstrates how to iterate through the sparse matrix: -@code - // print all the non-zero sparse matrix elements and compute their sum - double sum = 0; - int i, dims = cvGetDims(sparsemat); - CvSparseMatIterator it; - CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); - - for(; node != 0; node = cvGetNextSparseNode(&it)) - { - int* idx = CV_NODE_IDX(array, node); - float val = *(float*)CV_NODE_VAL(array, node); - printf("M"); - for(i = 0; i < dims; i++ ) - printf("[%d]", idx[i]); - printf("=%g\n", val); - - sum += val; - } - - printf("nTotal sum = %g\n", sum); -@endcode -@param mat_iterator Sparse array iterator - */ -CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) -{ - if( mat_iterator->node->next ) - return mat_iterator->node = mat_iterator->node->next; - else - { - int idx; - for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) - { - CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; - if( node ) - { - mat_iterator->curidx = idx; - return mat_iterator->node = node; - } - } - return NULL; - } -} - - -#define CV_MAX_ARR 10 - -/** matrix iterator: used for n-ary operations on dense arrays */ -typedef struct CvNArrayIterator -{ - int count; /**< number of arrays */ - int dims; /**< number of dimensions to iterate */ - CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ - uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ - int stack[CV_MAX_DIM]; /**< for internal use */ - CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the - matrices that are processed */ -} -CvNArrayIterator; - -#define CV_NO_DEPTH_CHECK 1 -#define CV_NO_CN_CHECK 2 -#define CV_NO_SIZE_CHECK 4 - -/** initializes iterator that traverses through several arrays simultaneously - (the function together with cvNextArraySlice is used for - N-ari element-wise operations) */ -CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, - const CvArr* mask, CvMatND* stubs, - CvNArrayIterator* array_iterator, - int flags CV_DEFAULT(0) ); - -/** returns zero value if iteration is finished, non-zero (slice length) otherwise */ -CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); - - -/** @brief Returns type of array elements. - -The function returns type of the array elements. In the case of IplImage the type is converted to -CvMat-like representation. For example, if the image has been created as: -@code - IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); -@endcode -The code cvGetElemType(img) will return CV_8UC3. -@param arr Input array - */ -CVAPI(int) cvGetElemType( const CvArr* arr ); - -/** @brief Return number of array dimensions - -The function returns the array dimensionality and the array of dimension sizes. In the case of -IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the -following code calculates total number of array elements: -@code - int sizes[CV_MAX_DIM]; - int i, total = 1; - int dims = cvGetDims(arr, size); - for(i = 0; i < dims; i++ ) - total *= sizes[i]; -@endcode -@param arr Input array -@param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows -(height) goes first, number of columns (width) next. - */ -CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); - - -/** @brief Returns array size along the specified dimension. - -@param arr Input array -@param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of -columns; for images 0 means height, 1 means width) - */ -CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); - - -/** @brief Return pointer to a particular array element. - -The functions return a pointer to a specific array element. Number of array dimension should match -to the number of indices passed to the function except for cvPtr1D function that can be used for -sequential access to 1D, 2D or nD dense arrays. - -The functions can be used for sparse arrays as well - if the requested node does not exist they -create it and set it to zero. - -All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet -, cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param type Optional output parameter: type of matrix elements - */ -CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); -/** @overload */ -CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); -/** @overload */ -CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, - int* type CV_DEFAULT(NULL)); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param type Optional output parameter: type of matrix elements -@param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter -means that the requested element is created if it does not exist already. -@param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, -the function does not recalculate the node hash value, but takes it from the specified location. -It is useful for speeding up pair-wise operations (TODO: provide an example) -*/ -CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), - int create_node CV_DEFAULT(1), - unsigned* precalc_hashval CV_DEFAULT(NULL)); - -/** @brief Return a specific array element. - -The functions return a specific array element. In the case of a sparse array the functions return 0 -if the requested node does not exist (no new node is created by the functions). -@param arr Input array -@param idx0 The first zero-based component of the element index - */ -CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); -/** @overload */ -CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); -/** @overload */ -CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); -/** @overload -@param arr Input array -@param idx Array of the element indices -*/ -CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); - -/** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. - -Returns a specific element of a single-channel array. If the array has multiple channels, a runtime -error is raised. Note that Get?D functions can be used safely for both single-channel and -multiple-channel arrays though they are a bit slower. - -In the case of a sparse array the functions return 0 if the requested node does not exist (no new -node is created by the functions). -@param arr Input array. Must have a single channel. -@param idx0 The first zero-based component of the element index - */ -CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); -/** @overload */ -CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); -/** @overload */ -CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); -/** @overload -@param arr Input array. Must have a single channel. -@param idx Array of the element indices -*/ -CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); - -/** @brief Change the particular array element. - -The functions assign the new value to a particular array element. In the case of a sparse array the -functions create the node if it does not exist yet. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param value The assigned value - */ -CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); -/** @overload */ -CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); -/** @overload */ -CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param value The assigned value -*/ -CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); - -/** @brief Change a specific array element. - -The functions assign a new value to a specific element of a single-channel array. If the array has -multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for -both single-channel and multiple-channel arrays, though they are a bit slower. - -In the case of a sparse array the functions create the node if it does not yet exist. -@param arr Input array -@param idx0 The first zero-based component of the element index -@param value The assigned value - */ -CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); -/** @overload */ -CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); -/** @overload */ -CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, - int idx1, int idx2, double value ); -/** @overload -@param arr Input array -@param idx Array of the element indices -@param value The assigned value -*/ -CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); - -/** clears element of ND dense array, - in case of sparse arrays it deletes the specified node */ -CVAPI(void) cvClearND( CvArr* arr, const int* idx ); - -/** @brief Returns matrix header for arbitrary array. - -The function returns a matrix header for the input array that can be a matrix - CvMat, an image - -IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if -allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of -IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI -and returns &header. Because COI is not supported by CvMat, it is returned separately. - -The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same -code. Input array must have non-zero data pointer, otherwise the function will report an error. - -@note If the input array is IplImage with planar data layout and COI set, the function returns the -pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures -with planar data layout, even though OpenCV does not support such images. -@param arr Input array -@param header Pointer to CvMat structure used as a temporary buffer -@param coi Optional output parameter for storing COI -@param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and -returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or -more than 2 dimensions). The CvMatND array must be continuous. -@sa cvGetImage, cvarrToMat. - */ -CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, - int* coi CV_DEFAULT(NULL), - int allowND CV_DEFAULT(0)); - -/** @brief Returns image header for arbitrary array. - -The function returns the image header for the input array that can be a matrix (CvMat) or image -(IplImage). In the case of an image the function simply returns the input pointer. In the case of -CvMat it initializes an image_header structure with the parameters of the input matrix. Note that -if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using -this function, we will get different headers if the ROI is set in the original image. -@param arr Input array -@param image_header Pointer to IplImage structure used as a temporary buffer - */ -CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); - - -/** @brief Changes the shape of a multi-dimensional array without copying the data. - -The function is an advanced version of cvReshape that can work with multi-dimensional arrays as -well (though it can work with ordinary images and matrices) and change the number of dimensions. - -Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: -@code - IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); - IplImage gray_img_hdr, *gray_img; - gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); - ... - int size[] = { 2, 2, 2 }; - CvMatND* mat = cvCreateMatND(3, size, CV_32F); - CvMat row_header, *row; - row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); -@endcode -In C, the header file for this function includes a convenient macro cvReshapeND that does away with -the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples -may be replaced as follow: -@code - gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); - ... - row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); -@endcode -@param arr Input array -@param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND -output headers -@param header Output header to be filled -@param new_cn New number of channels. new_cn = 0 means that the number of channels remains -unchanged. -@param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions -remains the same. -@param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the -total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not -used. - */ -CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, - int sizeof_header, CvArr* header, - int new_cn, int new_dims, int* new_sizes ); - -#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ - cvReshapeMatND( (arr), sizeof(*(header)), (header), \ - (new_cn), (new_dims), (new_sizes)) - -/** @brief Changes shape of matrix/image without copying data. - -The function initializes the CvMat header so that it points to the same data as the original array -but has a different shape - different number of channels, different number of rows, or both. - -The following example code creates one image buffer and two image headers, the first is for a -320x240x3 image and the second is for a 960x240x1 image: -@code - IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); - CvMat gray_mat_hdr; - IplImage gray_img_hdr, *gray_img; - cvReshape(color_img, &gray_mat_hdr, 1); - gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); -@endcode -And the next example converts a 3x3 matrix to a single 1x9 vector: -@code - CvMat* mat = cvCreateMat(3, 3, CV_32F); - CvMat row_header, *row; - row = cvReshape(mat, &row_header, 0, 1); -@endcode -@param arr Input array -@param header Output header to be filled -@param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains -unchanged. -@param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains -unchanged unless it needs to be changed according to new_cn value. -*/ -CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, - int new_cn, int new_rows CV_DEFAULT(0) ); - -/** Repeats source 2d array several times in both horizontal and - vertical direction to fill destination array */ -CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); - -/** @brief Allocates array data - -The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of -matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless -CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used -to allocate the data. -@param arr Array header - */ -CVAPI(void) cvCreateData( CvArr* arr ); - -/** @brief Releases array data. - -The function releases the array data. In the case of CvMat or CvMatND it simply calls -cvDecRefData(), that is the function can not deallocate external data. See also the note to -cvCreateData . -@param arr Array header - */ -CVAPI(void) cvReleaseData( CvArr* arr ); - -/** @brief Assigns user data to the array header. - -The function assigns user data to the array header. Header should be initialized before using -cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, -cvInitImageHeader or cvInitMatNDHeader. -@param arr Array header -@param data User data -@param step Full row length in bytes - */ -CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); - -/** @brief Retrieves low-level information about the array. - -The function fills output variables with low-level information about the array data. All output - -parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with -ROI set, the parameters of ROI are returned. - -The following example shows how to get access to array elements. It computes absolute values of the -array elements : -@code - float* data; - int step; - CvSize size; - - cvGetRawData(array, (uchar**)&data, &step, &size); - step /= sizeof(data[0]); - - for(int y = 0; y < size.height; y++, data += step ) - for(int x = 0; x < size.width; x++ ) - data[x] = (float)fabs(data[x]); -@endcode -@param arr Array header -@param data Output pointer to the whole image origin or ROI origin if ROI is set -@param step Output full row length in bytes -@param roi_size Output ROI size - */ -CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, - int* step CV_DEFAULT(NULL), - CvSize* roi_size CV_DEFAULT(NULL)); - -/** @brief Returns size of matrix or image ROI. - -The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the -input matrix or image. In the case of image the size of ROI is returned. -@param arr array header - */ -CVAPI(CvSize) cvGetSize( const CvArr* arr ); - -/** @brief Copies one array to another. - -The function copies selected elements from an input array to an output array: - -\f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] - -If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays -must have the same type, the same number of dimensions, and the same size. The function can also -copy sparse arrays (mask is not supported in this case). -@param src The source array -@param dst The destination array -@param mask Operation mask, 8-bit single channel array; specifies elements of the destination array -to be changed - */ -CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Sets every element of an array to a given value. - -The function copies the scalar value to every selected element of the destination array: -\f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] -If array arr is of IplImage type, then is ROI used, but COI must not be set. -@param arr The destination array -@param value Fill value -@param mask Operation mask, 8-bit single channel array; specifies elements of the destination -array to be changed - */ -CVAPI(void) cvSet( CvArr* arr, CvScalar value, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Clears the array. - -The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), -cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the -elements are removed. -@param arr Array to be cleared - */ -CVAPI(void) cvSetZero( CvArr* arr ); -#define cvZero cvSetZero - - -/** Splits a multi-channel array into the set of single-channel arrays or - extracts particular [color] plane */ -CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, - CvArr* dst2, CvArr* dst3 ); - -/** Merges a set of single-channel arrays into the single multi-channel array - or inserts one particular [color] plane to the array */ -CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, - const CvArr* src2, const CvArr* src3, - CvArr* dst ); - -/** Copies several channels from input arrays to - certain channels of output arrays */ -CVAPI(void) cvMixChannels( const CvArr** src, int src_count, - CvArr** dst, int dst_count, - const int* from_to, int pair_count ); - -/** @brief Converts one array to another with optional linear transformation. - -The function has several different purposes, and thus has several different names. It copies one -array to another with optional scaling, which is performed first, and/or optional type conversion, -performed after: - -\f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] - -All the channels of multi-channel arrays are processed independently. - -The type of conversion is done with rounding and saturation, that is if the result of scaling + -conversion can not be represented exactly by a value of the destination array element type, it is -set to the nearest representable value on the real axis. -@param src Source array -@param dst Destination array -@param scale Scale factor -@param shift Value added to the scaled source array elements - */ -CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, - double scale CV_DEFAULT(1), - double shift CV_DEFAULT(0) ); -#define cvCvtScale cvConvertScale -#define cvScale cvConvertScale -#define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) - - -/** Performs linear transformation on every source array element, - stores absolute value of the result: - dst(x,y,c) = abs(scale*src(x,y,c)+shift). - destination array must have 8u type. - In other cases one may use cvConvertScale + cvAbsDiffS */ -CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, - double scale CV_DEFAULT(1), - double shift CV_DEFAULT(0) ); -#define cvCvtScaleAbs cvConvertScaleAbs - - -/** checks termination criteria validity and - sets eps to default_eps (if it is not set), - max_iter to default_max_iters (if it is not set) -*/ -CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, - double default_eps, - int default_max_iters ); - -/****************************************************************************************\ -* Arithmetic, logic and comparison operations * -\****************************************************************************************/ - -/** dst(mask) = src1(mask) + src2(mask) */ -CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src(mask) + value */ -CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src1(mask) - src2(mask) */ -CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(mask) = src(mask) - value = src(mask) + (-value) */ -CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)) -{ - cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), - dst, mask ); -} - -/** dst(mask) = value - src(mask) */ -CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, - const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) * src2(idx) * scale - (scaled element-wise multiplication of 2 arrays) */ -CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, - CvArr* dst, double scale CV_DEFAULT(1) ); - -/** element-wise division/inversion with scaling: - dst(idx) = src1(idx) * scale / src2(idx) - or dst(idx) = scale / src2(idx) if src1 == 0 */ -CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, - CvArr* dst, double scale CV_DEFAULT(1)); - -/** dst = src1 * scale + src2 */ -CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, - const CvArr* src2, CvArr* dst ); -#define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) - -/** dst = src1 * alpha + src2 * beta + gamma */ -CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, - const CvArr* src2, double beta, - double gamma, CvArr* dst ); - -/** @brief Calculates the dot product of two arrays in Euclidean metrics. - -The function calculates and returns the Euclidean dot product of two arrays. - -\f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] - -In the case of multiple channel arrays, the results for all channels are accumulated. In particular, -cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can -process multi-dimensional arrays, row by row, layer by layer, and so on. -@param src1 The first source array -@param src2 The second source array - */ -CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); - -/** dst(idx) = src1(idx) & src2(idx) */ -CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) & value */ -CVAPI(void) cvAndS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) | src2(idx) */ -CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) | value */ -CVAPI(void) cvOrS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src1(idx) ^ src2(idx) */ -CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = src(idx) ^ value */ -CVAPI(void) cvXorS( const CvArr* src, CvScalar value, - CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); - -/** dst(idx) = ~src(idx) */ -CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); - -/** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ -CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, - const CvArr* upper, CvArr* dst ); - -/** dst(idx) = lower <= src(idx) < upper */ -CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, - CvScalar upper, CvArr* dst ); - -#define CV_CMP_EQ 0 -#define CV_CMP_GT 1 -#define CV_CMP_GE 2 -#define CV_CMP_LT 3 -#define CV_CMP_LE 4 -#define CV_CMP_NE 5 - -/** The comparison operation support single-channel arrays only. - Destination image should be 8uC1 or 8sC1 */ - -/** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ -CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); - -/** dst(idx) = src1(idx) _cmp_op_ value */ -CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); - -/** dst(idx) = min(src1(idx),src2(idx)) */ -CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** dst(idx) = max(src1(idx),src2(idx)) */ -CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** dst(idx) = min(src(idx),value) */ -CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); - -/** dst(idx) = max(src(idx),value) */ -CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); - -/** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ -CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ -CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); -#define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) - -/****************************************************************************************\ -* Math operations * -\****************************************************************************************/ - -/** Does cartesian->polar coordinates conversion. - Either of output components (magnitude or angle) is optional */ -CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, - CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), - int angle_in_degrees CV_DEFAULT(0)); - -/** Does polar->cartesian coordinates conversion. - Either of output components (magnitude or angle) is optional. - If magnitude is missing it is assumed to be all 1's */ -CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, - CvArr* x, CvArr* y, - int angle_in_degrees CV_DEFAULT(0)); - -/** Does powering: dst(idx) = src(idx)^power */ -CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); - -/** Does exponention: dst(idx) = exp(src(idx)). - Overflow is not handled yet. Underflow is handled. - Maximal relative error is ~7e-6 for single-precision input */ -CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); - -/** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). - Logarithm of 0 gives large negative number(~-700) - Maximal relative error is ~3e-7 for single-precision output -*/ -CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); - -/** Fast arctangent calculation */ -CVAPI(float) cvFastArctan( float y, float x ); - -/** Fast cubic root calculation */ -CVAPI(float) cvCbrt( float value ); - -#define CV_CHECK_RANGE 1 -#define CV_CHECK_QUIET 2 -/** Checks array values for NaNs, Infs or simply for too large numbers - (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, - no runtime errors is raised (function returns zero value in case of "bad" values). - Otherwise cvError is called */ -CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), - double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); -#define cvCheckArray cvCheckArr - -#define CV_RAND_UNI 0 -#define CV_RAND_NORMAL 1 - -/** @brief Fills an array with random numbers and updates the RNG state. - -The function fills the destination array with uniformly or normally distributed random numbers. -@param rng CvRNG state initialized by cvRNG -@param arr The destination array -@param dist_type Distribution type -> - **CV_RAND_UNI** uniform distribution -> - **CV_RAND_NORMAL** normal or Gaussian distribution -@param param1 The first parameter of the distribution. In the case of a uniform distribution it is -the inclusive lower boundary of the random numbers range. In the case of a normal distribution it -is the mean value of the random numbers. -@param param2 The second parameter of the distribution. In the case of a uniform distribution it -is the exclusive upper boundary of the random numbers range. In the case of a normal distribution -it is the standard deviation of the random numbers. -@sa randu, randn, RNG::fill. - */ -CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, - CvScalar param1, CvScalar param2 ); - -CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng, - double iter_factor CV_DEFAULT(1.)); - -#define CV_SORT_EVERY_ROW 0 -#define CV_SORT_EVERY_COLUMN 1 -#define CV_SORT_ASCENDING 0 -#define CV_SORT_DESCENDING 16 - -CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), - CvArr* idxmat CV_DEFAULT(NULL), - int flags CV_DEFAULT(0)); - -/** Finds real roots of a cubic equation */ -CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); - -/** Finds all real and complex roots of a polynomial equation */ -CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, - int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); - -/****************************************************************************************\ -* Matrix operations * -\****************************************************************************************/ - -/** @brief Calculates the cross product of two 3D vectors. - -The function calculates the cross product of two 3D vectors: -\f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] -or: -\f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] -@param src1 The first source vector -@param src2 The second source vector -@param dst The destination vector - */ -CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); - -/** Matrix transform: dst = A*B + C, C is optional */ -#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) -#define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) - -#define CV_GEMM_A_T 1 -#define CV_GEMM_B_T 2 -#define CV_GEMM_C_T 4 -/** Extended matrix transform: - dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ -CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, - const CvArr* src3, double beta, CvArr* dst, - int tABC CV_DEFAULT(0)); -#define cvMatMulAddEx cvGEMM - -/** Transforms each element of source array and stores - resultant vectors in destination array */ -CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, - const CvMat* transmat, - const CvMat* shiftvec CV_DEFAULT(NULL)); -#define cvMatMulAddS cvTransform - -/** Does perspective transform on every element of input array */ -CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, - const CvMat* mat ); - -/** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ -CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, - const CvArr* delta CV_DEFAULT(NULL), - double scale CV_DEFAULT(1.) ); - -/** Transposes matrix. Square matrices can be transposed in-place */ -CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); -#define cvT cvTranspose - -/** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ -CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); - -/** Mirror array data around horizontal (flip=0), - vertical (flip=1) or both(flip=-1) axises: - cvFlip(src) flips images vertically and sequences horizontally (inplace) */ -CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), - int flip_mode CV_DEFAULT(0)); -#define cvMirror cvFlip - - -#define CV_SVD_MODIFY_A 1 -#define CV_SVD_U_T 2 -#define CV_SVD_V_T 4 - -/** Performs Singular Value Decomposition of a matrix */ -CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), - CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); - -/** Performs Singular Value Back Substitution (solves A*X = B): - flags must be the same as in cvSVD */ -CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, - const CvArr* V, const CvArr* B, - CvArr* X, int flags ); - -#define CV_LU 0 -#define CV_SVD 1 -#define CV_SVD_SYM 2 -#define CV_CHOLESKY 3 -#define CV_QR 4 -#define CV_NORMAL 16 - -/** Inverts matrix */ -CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, - int method CV_DEFAULT(CV_LU)); -#define cvInv cvInvert - -/** Solves linear system (src1)*(dst) = (src2) - (returns 0 if src1 is a singular and CV_LU method is used) */ -CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, - int method CV_DEFAULT(CV_LU)); - -/** Calculates determinant of input matrix */ -CVAPI(double) cvDet( const CvArr* mat ); - -/** Calculates trace of the matrix (sum of elements on the main diagonal) */ -CVAPI(CvScalar) cvTrace( const CvArr* mat ); - -/** Finds eigen values and vectors of a symmetric matrix */ -CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, - double eps CV_DEFAULT(0), - int lowindex CV_DEFAULT(-1), - int highindex CV_DEFAULT(-1)); - -///* Finds selected eigen values and vectors of a symmetric matrix */ -//CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, -// int lowindex, int highindex ); - -/** Makes an identity matrix (mat_ij = i == j) */ -CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); - -/** Fills matrix with given range of numbers */ -CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); - -/** @anchor core_c_CovarFlags -@name Flags for cvCalcCovarMatrix -@see cvCalcCovarMatrix - @{ -*/ - -/** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ -#define CV_COVAR_SCRAMBLED 0 - -/** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ -#define CV_COVAR_NORMAL 1 - -/** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead - (useful for calculating covariance matrix by parts) */ -#define CV_COVAR_USE_AVG 2 - -/** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ -#define CV_COVAR_SCALE 4 - -/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ -#define CV_COVAR_ROWS 8 - -/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ -#define CV_COVAR_COLS 16 - -/** @} */ - -/** Calculates covariation matrix for a set of vectors -@see @ref core_c_CovarFlags "flags" -*/ -CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, - CvArr* cov_mat, CvArr* avg, int flags ); - -#define CV_PCA_DATA_AS_ROW 0 -#define CV_PCA_DATA_AS_COL 1 -#define CV_PCA_USE_AVG 2 -CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, - CvArr* eigenvals, CvArr* eigenvects, int flags ); - -CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, - const CvArr* eigenvects, CvArr* result ); - -CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, - const CvArr* eigenvects, CvArr* result ); - -/** Calculates Mahalanobis(weighted) distance */ -CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); -#define cvMahalonobis cvMahalanobis - -/****************************************************************************************\ -* Array Statistics * -\****************************************************************************************/ - -/** Finds sum of array elements */ -CVAPI(CvScalar) cvSum( const CvArr* arr ); - -/** Calculates number of non-zero pixels */ -CVAPI(int) cvCountNonZero( const CvArr* arr ); - -/** Calculates mean value of array elements */ -CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); - -/** Calculates mean and standard deviation of pixel values */ -CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** Finds global minimum, maximum and their positions */ -CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, - CvPoint* min_loc CV_DEFAULT(NULL), - CvPoint* max_loc CV_DEFAULT(NULL), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @anchor core_c_NormFlags - @name Flags for cvNorm and cvNormalize - @{ -*/ -#define CV_C 1 -#define CV_L1 2 -#define CV_L2 4 -#define CV_NORM_MASK 7 -#define CV_RELATIVE 8 -#define CV_DIFF 16 -#define CV_MINMAX 32 - -#define CV_DIFF_C (CV_DIFF | CV_C) -#define CV_DIFF_L1 (CV_DIFF | CV_L1) -#define CV_DIFF_L2 (CV_DIFF | CV_L2) -#define CV_RELATIVE_C (CV_RELATIVE | CV_C) -#define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) -#define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) -/** @} */ - -/** Finds norm, difference norm or relative difference norm for an array (or two arrays) -@see ref core_c_NormFlags "flags" -*/ -CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), - int norm_type CV_DEFAULT(CV_L2), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @see ref core_c_NormFlags "flags" */ -CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, - double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), - int norm_type CV_DEFAULT(CV_L2), - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @anchor core_c_ReduceFlags - @name Flags for cvReduce - @{ -*/ -#define CV_REDUCE_SUM 0 -#define CV_REDUCE_AVG 1 -#define CV_REDUCE_MAX 2 -#define CV_REDUCE_MIN 3 -/** @} */ - -/** @see @ref core_c_ReduceFlags "flags" */ -CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), - int op CV_DEFAULT(CV_REDUCE_SUM) ); - -/****************************************************************************************\ -* Discrete Linear Transforms and Related Functions * -\****************************************************************************************/ - -/** @anchor core_c_DftFlags - @name Flags for cvDFT, cvDCT and cvMulSpectrums - @{ - */ -#define CV_DXT_FORWARD 0 -#define CV_DXT_INVERSE 1 -#define CV_DXT_SCALE 2 /**< divide result by size of array */ -#define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) -#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE -#define CV_DXT_ROWS 4 /**< transform each row individually */ -#define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ -/** @} */ - -/** Discrete Fourier Transform: - complex->complex, - real->ccs (forward), - ccs->real (inverse) -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, - int nonzero_rows CV_DEFAULT(0) ); -#define cvFFT cvDFT - -/** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, - CvArr* dst, int flags ); - -/** Finds optimal DFT vector size >= size0 */ -CVAPI(int) cvGetOptimalDFTSize( int size0 ); - -/** Discrete Cosine Transform -@see core_c_DftFlags "flags" -*/ -CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); - -/****************************************************************************************\ -* Dynamic data structures * -\****************************************************************************************/ - -/** Calculates length of sequence slice (with support of negative indices). */ -CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); - - -/** Creates new memory storage. - block_size == 0 means that default, - somewhat optimal size, is used (currently, it is 64K) */ -CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); - - -/** Creates a memory storage that will borrow memory blocks from parent storage */ -CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); - - -/** Releases memory storage. All the children of a parent must be released before - the parent. A child storage returns all the blocks to parent when it is released */ -CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); - - -/** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) - to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... - do not free any memory. - A child storage returns all the blocks to the parent when it is cleared */ -CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); - -/** Remember a storage "free memory" position */ -CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); - -/** Restore a storage "free memory" position */ -CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); - -/** Allocates continuous buffer of the specified size in the storage */ -CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); - -/** Allocates string in memory storage */ -//CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, -// int len CV_DEFAULT(-1) ); - -/** Creates new empty sequence that will reside in the specified storage */ -CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, - size_t elem_size, CvMemStorage* storage ); - -/** Changes default size (granularity) of sequence blocks. - The default size is ~1Kbyte */ -CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); - - -/** Adds new element to the end of sequence. Returns pointer to the element */ -CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); - - -/** Adds new element to the beginning of sequence. Returns pointer to it */ -CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); - - -/** Removes the last element from sequence and optionally saves it */ -CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); - - -/** Removes the first element from sequence and optioanally saves it */ -CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); - - -#define CV_FRONT 1 -#define CV_BACK 0 -/** Adds several new elements to the end of sequence */ -CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, - int count, int in_front CV_DEFAULT(0) ); - -/** Removes several elements from the end of sequence and optionally saves them */ -CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, - int count, int in_front CV_DEFAULT(0) ); - -/** Inserts a new element in the middle of sequence. - cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ -CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, - const void* element CV_DEFAULT(NULL)); - -/** Removes specified sequence element */ -CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); - - -/** Removes all the elements from the sequence. The freed memory - can be reused later only by the same sequence unless cvClearMemStorage - or cvRestoreMemStoragePos is called */ -CVAPI(void) cvClearSeq( CvSeq* seq ); - - -/** Retrieves pointer to specified sequence element. - Negative indices are supported and mean counting from the end - (e.g -1 means the last sequence element) */ -CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); - -/** Calculates index of the specified sequence element. - Returns -1 if element does not belong to the sequence */ -CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, - CvSeqBlock** block CV_DEFAULT(NULL) ); - -/** Initializes sequence writer. The new elements will be added to the end of sequence */ -CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); - - -/** Combination of cvCreateSeq and cvStartAppendToSeq */ -CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, - int elem_size, CvMemStorage* storage, - CvSeqWriter* writer ); - -/** Closes sequence writer, updates sequence header and returns pointer - to the resultant sequence - (which may be useful if the sequence was created using cvStartWriteSeq)) -*/ -CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); - - -/** Updates sequence header. May be useful to get access to some of previously - written elements via cvGetSeqElem or sequence reader */ -CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); - - -/** Initializes sequence reader. - The sequence can be read in forward or backward direction */ -CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, - int reverse CV_DEFAULT(0) ); - - -/** Returns current sequence reader position (currently observed sequence element) */ -CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); - - -/** Changes sequence reader position. It may seek to an absolute or - to relative to the current position */ -CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, - int is_relative CV_DEFAULT(0)); - -/** Copies sequence content to a continuous piece of memory */ -CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, - CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); - -/** Creates sequence header for array. - After that all the operations on sequences that do not alter the content - can be applied to the resultant sequence */ -CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, - int elem_size, void* elements, int total, - CvSeq* seq, CvSeqBlock* block ); - -/** Extracts sequence slice (with or without copying sequence elements) */ -CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, - CvMemStorage* storage CV_DEFAULT(NULL), - int copy_data CV_DEFAULT(0)); - -CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) -{ - return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); -} - -/** Removes sequence slice */ -CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); - -/** Inserts a sequence or array into another sequence */ -CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); - -/** a < b ? -1 : a > b ? 1 : 0 */ -typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); - -/** Sorts sequence in-place given element comparison function */ -CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); - -/** Finds element in a [sorted] sequence */ -CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, - int is_sorted, int* elem_idx, - void* userdata CV_DEFAULT(NULL) ); - -/** Reverses order of sequence elements in-place */ -CVAPI(void) cvSeqInvert( CvSeq* seq ); - -/** Splits sequence into one or more equivalence classes using the specified criteria */ -CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, - CvSeq** labels, CvCmpFunc is_equal, void* userdata ); - -/************ Internal sequence functions ************/ -CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); -CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); - - -/** Creates a new set */ -CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, - int elem_size, CvMemStorage* storage ); - -/** Adds new element to the set and returns pointer to it */ -CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), - CvSetElem** inserted_elem CV_DEFAULT(NULL) ); - -/** Fast variant of cvSetAdd */ -CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) -{ - CvSetElem* elem = set_header->free_elems; - if( elem ) - { - set_header->free_elems = elem->next_free; - elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; - set_header->active_count++; - } - else - cvSetAdd( set_header, NULL, &elem ); - return elem; -} - -/** Removes set element given its pointer */ -CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) -{ - CvSetElem* _elem = (CvSetElem*)elem; - assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); - _elem->next_free = set_header->free_elems; - _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; - set_header->free_elems = _elem; - set_header->active_count--; -} - -/** Removes element from the set by its index */ -CVAPI(void) cvSetRemove( CvSet* set_header, int index ); - -/** Returns a set element by index. If the element doesn't belong to the set, - NULL is returned */ -CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) -{ - CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); - return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; -} - -/** Removes all the elements from the set */ -CVAPI(void) cvClearSet( CvSet* set_header ); - -/** Creates new graph */ -CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, - int vtx_size, int edge_size, - CvMemStorage* storage ); - -/** Adds new vertex to the graph */ -CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), - CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); - - -/** Removes vertex from the graph together with all incident edges */ -CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); -CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); - - -/** Link two vertices specified by indices or pointers if they - are not connected or return pointer to already existing edge - connecting the vertices. - Functions return 1 if a new edge was created, 0 otherwise */ -CVAPI(int) cvGraphAddEdge( CvGraph* graph, - int start_idx, int end_idx, - const CvGraphEdge* edge CV_DEFAULT(NULL), - CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); - -CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, - CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, - const CvGraphEdge* edge CV_DEFAULT(NULL), - CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); - -/** Remove edge connecting two vertices */ -CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); -CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, - CvGraphVtx* end_vtx ); - -/** Find edge connecting two vertices */ -CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); -CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, - const CvGraphVtx* start_vtx, - const CvGraphVtx* end_vtx ); -#define cvGraphFindEdge cvFindGraphEdge -#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr - -/** Remove all vertices and edges from the graph */ -CVAPI(void) cvClearGraph( CvGraph* graph ); - - -/** Count number of edges incident to the vertex */ -CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); -CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); - - -/** Retrieves graph vertex by given index */ -#define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) - -/** Retrieves index of a graph vertex given its pointer */ -#define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) - -/** Retrieves index of a graph edge given its pointer */ -#define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) - -#define cvGraphGetVtxCount( graph ) ((graph)->active_count) -#define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) - -#define CV_GRAPH_VERTEX 1 -#define CV_GRAPH_TREE_EDGE 2 -#define CV_GRAPH_BACK_EDGE 4 -#define CV_GRAPH_FORWARD_EDGE 8 -#define CV_GRAPH_CROSS_EDGE 16 -#define CV_GRAPH_ANY_EDGE 30 -#define CV_GRAPH_NEW_TREE 32 -#define CV_GRAPH_BACKTRACKING 64 -#define CV_GRAPH_OVER -1 - -#define CV_GRAPH_ALL_ITEMS -1 - -/** flags for graph vertices and edges */ -#define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) -#define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ - (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) -#define CV_IS_GRAPH_EDGE_VISITED(edge) \ - (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) -#define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) -#define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) - -typedef struct CvGraphScanner -{ - CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ - CvGraphVtx* dst; /* current graph edge destination vertex */ - CvGraphEdge* edge; /* current edge */ - - CvGraph* graph; /* the graph */ - CvSeq* stack; /* the graph vertex stack */ - int index; /* the lower bound of certainly visited vertices */ - int mask; /* event mask */ -} -CvGraphScanner; - -/** Creates new graph scanner. */ -CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, - CvGraphVtx* vtx CV_DEFAULT(NULL), - int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); - -/** Releases graph scanner. */ -CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); - -/** Get next graph element */ -CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); - -/** Creates a copy of graph */ -CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); - - -/** Does look-up transformation. Elements of the source array - (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ -CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); - - -/******************* Iteration through the sequence tree *****************/ -typedef struct CvTreeNodeIterator -{ - const void* node; - int level; - int max_level; -} -CvTreeNodeIterator; - -CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, - const void* first, int max_level ); -CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); -CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); - -/** Inserts sequence into tree with specified "parent" sequence. - If parent is equal to frame (e.g. the most external contour), - then added contour will have null pointer to parent. */ -CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); - -/** Removes contour from tree (together with the contour children). */ -CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); - -/** Gathers pointers to all the sequences, - accessible from the `first`, to the single sequence */ -CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, - CvMemStorage* storage ); - -/** The function implements the K-means algorithm for clustering an array of sample - vectors in a specified number of classes */ -#define CV_KMEANS_USE_INITIAL_LABELS 1 -CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, - CvTermCriteria termcrit, int attempts CV_DEFAULT(1), - CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0), - CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) ); - -/****************************************************************************************\ -* System functions * -\****************************************************************************************/ - -/** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ -CVAPI(int) cvUseOptimized( int on_off ); - -typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) - (int,int,int,char*,char*,int,int,int,int,int, - IplROI*,IplImage*,void*,IplTileInfo*); -typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); -typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); -typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); -typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); - -/** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. - -Normally, the function is not called directly. Instead, a simple macro -CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers -to IPL allocation functions. : -@code - ... - CV_TURN_ON_IPL_COMPATIBILITY() - ... -@endcode -@param create_header pointer to a function, creating IPL image header. -@param allocate_data pointer to a function, allocating IPL image data. -@param deallocate pointer to a function, deallocating IPL image. -@param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). -@param clone_image pointer to a function, cloning an IPL image. - */ -CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, - Cv_iplAllocateImageData allocate_data, - Cv_iplDeallocate deallocate, - Cv_iplCreateROI create_roi, - Cv_iplCloneImage clone_image ); - -#define CV_TURN_ON_IPL_COMPATIBILITY() \ - cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ - iplDeallocate, iplCreateROI, iplCloneImage ) - -/****************************************************************************************\ -* Data Persistence * -\****************************************************************************************/ - -#if 0 -/********************************** High-level functions ********************************/ - -/** @brief Opens file storage for reading or writing data. - -The function opens file storage for reading or writing data. In the latter case, a new file is -created or an existing file is rewritten. The type of the read or written file is determined by the -filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON. - -At the same time, it also supports adding parameters like "example.xml?base64". - -The function returns a pointer to the CvFileStorage structure. -If the file cannot be opened then the function returns NULL. -@param filename Name of the file associated with the storage -@param memstorage Memory storage used for temporary data and for -: storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory - storage is created and used. -@param flags Can be one of the following: -> - **CV_STORAGE_READ** the storage is open for reading -> - **CV_STORAGE_WRITE** the storage is open for writing - (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64) -@param encoding - */ -CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, - int flags, const char* encoding CV_DEFAULT(NULL) ); - -/** @brief Releases file storage. - -The function closes the file associated with the storage and releases all the temporary structures. -It must be called after all I/O operations with the storage are finished. -@param fs Double pointer to the released file storage - */ -CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); - -/** returns attribute value or 0 (NULL) if there is no such attribute */ -CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); - -/** @brief Starts writing a new structure. - -The function starts writing a compound structure (collection) that can be a sequence or a map. After -all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should -be called. The function can be used to group some objects or to implement the write function for a -some user object (see CvTypeInfo). -@param fs File storage -@param name Name of the written structure. The structure can be accessed by this name when the -storage is read. -@param struct_flags A combination one of the following values: -- **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), - that is, its elements do not have a name. -- **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that - is, all its elements have names. -One and only one of the two above flags must be specified -- **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that - the structure is written as a flow (not as a block), which is more compact. It is - recommended to use this flag for structures or arrays whose elements are all scalars. -@param type_name Optional parameter - the object type name. In - case of XML it is written as a type_id attribute of the structure opening tag. In the case of - YAML it is written after a colon following the structure name (see the example in - CvFileStorage description). In case of JSON it is written as a name/value pair. - Mainly it is used with user objects. When the storage is read, the - encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). -@param attributes This parameter is not used in the current implementation - */ -CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, - int struct_flags, const char* type_name CV_DEFAULT(NULL), - CvAttrList attributes CV_DEFAULT(cvAttrList())); - -/** @brief Finishes writing to a file node collection. -@param fs File storage -@sa cvStartWriteStruct. - */ -CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); - -/** @brief Writes an integer value. - -The function writes a single integer value (with or without a name) to the file storage. -@param fs File storage -@param name Name of the written value. Should be NULL if and only if the parent structure is a -sequence. -@param value The written value - */ -CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); - -/** @brief Writes a floating-point value. - -The function writes a single floating-point value (with or without a name) to file storage. Special -values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. - -The following example shows how to use the low-level writing functions to store custom structures, -such as termination criteria, without registering a new type. : -@code - void write_termcriteria( CvFileStorage* fs, const char* struct_name, - CvTermCriteria* termcrit ) - { - cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); - cvWriteComment( fs, "termination criteria", 1 ); // just a description - if( termcrit->type & CV_TERMCRIT_ITER ) - cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); - if( termcrit->type & CV_TERMCRIT_EPS ) - cvWriteReal( fs, "accuracy", termcrit->epsilon ); - cvEndWriteStruct( fs ); - } -@endcode -@param fs File storage -@param name Name of the written value. Should be NULL if and only if the parent structure is a -sequence. -@param value The written value -*/ -CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); - -/** @brief Writes a text string. - -The function writes a text string to file storage. -@param fs File storage -@param name Name of the written string . Should be NULL if and only if the parent structure is a -sequence. -@param str The written text string -@param quote If non-zero, the written string is put in quotes, regardless of whether they are -required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when -the string starts with a digit or contains spaces). - */ -CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, - const char* str, int quote CV_DEFAULT(0) ); - -/** @brief Writes a comment. - -The function writes a comment into file storage. The comments are skipped when the storage is read. -@param fs File storage -@param comment The written comment, single-line or multi-line -@param eol_comment If non-zero, the function tries to put the comment at the end of current line. -If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current -line, the comment starts a new line. - */ -CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, - int eol_comment ); - -/** @brief Writes an object to file storage. - -The function writes an object to file storage. First, the appropriate type info is found using -cvTypeOf. Then, the write method associated with the type info is called. - -Attributes are used to customize the writing procedure. The standard types support the following -attributes (all the dt attributes have the same format as in cvWriteRawData): - --# CvSeq - - **header_dt** description of user fields of the sequence header that follow CvSeq, or - CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or - point sequence) - - **dt** description of the sequence elements. - - **recursive** if the attribute is present and is not equal to "0" or "false", the whole - tree of sequences (contours) is stored. --# CvGraph - - **header_dt** description of user fields of the graph header that follows CvGraph; - - **vertex_dt** description of user fields of graph vertices - - **edge_dt** description of user fields of graph edges (note that the edge weight is - always written, so there is no need to specify it explicitly) - -Below is the code that creates the YAML file shown in the CvFileStorage description: -@code - #include "cxcore.h" - - int main( int argc, char** argv ) - { - CvMat* mat = cvCreateMat( 3, 3, CV_32F ); - CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); - - cvSetIdentity( mat ); - cvWrite( fs, "A", mat, cvAttrList(0,0) ); - - cvReleaseFileStorage( &fs ); - cvReleaseMat( &mat ); - return 0; - } -@endcode -@param fs File storage -@param name Name of the written object. Should be NULL if and only if the parent structure is a -sequence. -@param ptr Pointer to the object -@param attributes The attributes of the object. They are specific for each particular type (see -the discussion below). - */ -CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, - CvAttrList attributes CV_DEFAULT(cvAttrList())); - -/** @brief Starts the next stream. - -The function finishes the currently written stream and starts the next stream. In the case of XML -the file with multiple streams looks like this: -@code{.xml} - - - - - - - ... -@endcode -The YAML file will look like this: -@code{.yaml} - %YAML 1.0 - # stream #1 data - ... - --- - # stream #2 data -@endcode -This is useful for concatenating files or for resuming the writing process. -@param fs File storage - */ -CVAPI(void) cvStartNextStream( CvFileStorage* fs ); - -/** @brief Writes multiple numbers. - -The function writes an array, whose elements consist of single or multiple numbers. The function -call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single -call is more efficient. Note that because none of the elements have a name, they should be written -to a sequence rather than a map. -@param fs File storage -@param src Pointer to the written array -@param len Number of the array elements to write -@param dt Specification of each array element, see @ref format_spec "format specification" - */ -CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, - int len, const char* dt ); - -/** @brief Writes multiple numbers in Base64. - -If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used, -this function will be the same as cvWriteRawData. If neither, the main -difference is that it outputs a sequence in Base64 encoding rather than -in plain text. - -This function can only be used to write a sequence with a type "binary". - -@param fs File storage -@param src Pointer to the written array -@param len Number of the array elements to write -@param dt Specification of each array element, see @ref format_spec "format specification" -*/ -CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src, - int len, const char* dt ); - -/** @brief Returns a unique pointer for a given name. - -The function returns a unique pointer for each particular file node name. This pointer can be then -passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares -text strings by comparing pointers rather than the strings' content. - -Consider the following example where an array of points is encoded as a sequence of 2-entry maps: -@code - points: - - { x: 10, y: 10 } - - { x: 20, y: 20 } - - { x: 30, y: 30 } - # ... -@endcode -Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : -@code - #include "cxcore.h" - - int main( int argc, char** argv ) - { - CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); - CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); - CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); - CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); - - if( CV_NODE_IS_SEQ(points->tag) ) - { - CvSeq* seq = points->data.seq; - int i, total = seq->total; - CvSeqReader reader; - cvStartReadSeq( seq, &reader, 0 ); - for( i = 0; i < total; i++ ) - { - CvFileNode* pt = (CvFileNode*)reader.ptr; - #if 1 // faster variant - CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); - CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); - assert( xnode && CV_NODE_IS_INT(xnode->tag) && - ynode && CV_NODE_IS_INT(ynode->tag)); - int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); - int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); - #elif 1 // slower variant; does not use x_key & y_key - CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); - CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); - assert( xnode && CV_NODE_IS_INT(xnode->tag) && - ynode && CV_NODE_IS_INT(ynode->tag)); - int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); - int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); - #else // the slowest yet the easiest to use variant - int x = cvReadIntByName( fs, pt, "x", 0 ); - int y = cvReadIntByName( fs, pt, "y", 0 ); - #endif - CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); - printf(" - } - } - cvReleaseFileStorage( &fs ); - return 0; - } -@endcode -Please note that whatever method of accessing a map you are using, it is still much slower than -using plain sequences; for example, in the above example, it is more efficient to encode the points -as pairs of integers in a single numeric sequence. -@param fs File storage -@param name Literal node name -@param len Length of the name (if it is known apriori), or -1 if it needs to be calculated -@param create_missing Flag that specifies, whether an absent key should be added into the hash table -*/ -CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, - int len CV_DEFAULT(-1), - int create_missing CV_DEFAULT(0)); - -/** @brief Retrieves one of the top-level nodes of the file storage. - -The function returns one of the top-level file nodes. The top-level nodes do not have a name, they -correspond to the streams that are stored one after another in the file storage. If the index is out -of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by -subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. -This function can be used as a base for recursive traversal of the file storage. -@param fs File storage -@param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, -there is only one stream in the file; however, there can be several. - */ -CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, - int stream_index CV_DEFAULT(0) ); - -/** @brief Finds a node in a map or file storage. - -The function finds a file node. It is a faster version of cvGetFileNodeByName (see -cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. If both map and -key are NULLs, the function returns the root file node - a map that contains top-level nodes. -@param key Unique pointer to the node name, retrieved with cvGetHashedKey -@param create_missing Flag that specifies whether an absent node should be added to the map - */ -CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, - const CvStringHashNode* key, - int create_missing CV_DEFAULT(0) ); - -/** @brief Finds a node in a map or file storage. - -The function finds a file node by name. The node is searched either in map or, if the pointer is -NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or -sequence reader) for sequences, it is possible to navigate through the file storage. To speed up -multiple queries for a certain key (e.g., in the case of an array of structures) one may use a -combination of cvGetHashedKey and cvGetFileNode. -@param fs File storage -@param map The parent map. If it is NULL, the function searches in all the top-level nodes -(streams), starting with the first one. -@param name The file node name - */ -CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, - const CvFileNode* map, - const char* name ); - -/** @brief Retrieves an integer value from a file node. - -The function returns an integer that is represented by the file node. If the file node is NULL, the -default_value is returned (thus, it is convenient to call the function right after cvGetFileNode -without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is -returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer -and returned. Otherwise the error is reported. -@param node File node -@param default_value The value that is returned if node is NULL - */ -CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) -{ - return !node ? default_value : - CV_NODE_IS_INT(node->tag) ? node->data.i : - CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; -} - -/** @brief Finds a file node and returns its value. - -The function is a simple superposition of cvGetFileNodeByName and cvReadInt. -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param default_value The value that is returned if the file node is not found - */ -CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, - const char* name, int default_value CV_DEFAULT(0) ) -{ - return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); -} - -/** @brief Retrieves a floating-point value from a file node. - -The function returns a floating-point value that is represented by the file node. If the file node -is NULL, the default_value is returned (thus, it is convenient to call the function right after -cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , -then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f -is converted to floating-point and returned. Otherwise the result is not determined. -@param node File node -@param default_value The value that is returned if node is NULL - */ -CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) -{ - return !node ? default_value : - CV_NODE_IS_INT(node->tag) ? (double)node->data.i : - CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; -} - -/** @brief Finds a file node and returns its value. - -The function is a simple superposition of cvGetFileNodeByName and cvReadReal . -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param default_value The value that is returned if the file node is not found - */ -CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, - const char* name, double default_value CV_DEFAULT(0.) ) -{ - return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); -} - -/** @brief Retrieves a text string from a file node. - -The function returns a text string that is represented by the file node. If the file node is NULL, -the default_value is returned (thus, it is convenient to call the function right after -cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then -node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. -@param node File node -@param default_value The value that is returned if node is NULL - */ -CV_INLINE const char* cvReadString( const CvFileNode* node, - const char* default_value CV_DEFAULT(NULL) ) -{ - return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; -} - -/** @brief Finds a file node by its name and returns its value. - -The function is a simple superposition of cvGetFileNodeByName and cvReadString . -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param default_value The value that is returned if the file node is not found - */ -CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, - const char* name, const char* default_value CV_DEFAULT(NULL) ) -{ - return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value ); -} - - -/** @brief Decodes an object and returns a pointer to it. - -The function decodes a user object (creates an object in a native representation from the file -storage subtree) and returns it. The object to be decoded must be an instance of a registered type -that supports the read method (see CvTypeInfo). The type of the object is determined by the type -name that is encoded in the file. If the object is a dynamic structure, it is created either in -memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary -memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is -not a dynamic structure, it is created in a heap and should be released with a specialized function -or by using the generic cvRelease. -@param fs File storage -@param node The root object node -@param attributes Unused parameter - */ -CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, - CvAttrList* attributes CV_DEFAULT(NULL)); - -/** @brief Finds an object by name and decodes it. - -The function is a simple superposition of cvGetFileNodeByName and cvRead. -@param fs File storage -@param map The parent map. If it is NULL, the function searches a top-level node. -@param name The node name -@param attributes Unused parameter - */ -CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, - const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) -{ - return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes ); -} - - -/** @brief Initializes the file node sequence reader. - -The function initializes the sequence reader to read data from a file node. The initialized reader -can be then passed to cvReadRawDataSlice. -@param fs File storage -@param src The file node (a sequence) to read numbers from -@param reader Pointer to the sequence reader - */ -CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, - CvSeqReader* reader ); - -/** @brief Initializes file node sequence reader. - -The function reads one or more elements from the file node, representing a sequence, to a -user-specified array. The total number of read sequence elements is a product of total and the -number of components in each array element. For example, if dt=2if, the function will read total\*3 -sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read -repeatedly by repositioning the reader using cvSetSeqReaderPos. -@param fs File storage -@param reader The sequence reader. Initialize it with cvStartReadRawData . -@param count The number of elements to read -@param dst Pointer to the destination array -@param dt Specification of each array element. It has the same format as in cvWriteRawData . - */ -CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, - int count, void* dst, const char* dt ); - -/** @brief Reads multiple numbers. - -The function reads elements from a file node that represents a sequence of scalars. -@param fs File storage -@param src The file node (a sequence) to read numbers from -@param dst Pointer to the destination array -@param dt Specification of each array element. It has the same format as in cvWriteRawData . - */ -CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, - void* dst, const char* dt ); - -/** @brief Writes a file node to another file storage. - -The function writes a copy of a file node to file storage. Possible applications of the function are -merging several file storages into one and conversion between XML, YAML and JSON formats. -@param fs Destination file storage -@param new_node_name New name of the file node in the destination file storage. To keep the -existing name, use cvcvGetFileNodeName -@param node The written node -@param embed If the written node is a collection and this parameter is not zero, no extra level of -hierarchy is created. Instead, all the elements of node are written into the currently written -structure. Of course, map elements can only be embedded into another map, and sequence elements -can only be embedded into another sequence. - */ -CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, - const CvFileNode* node, int embed ); - -/** @brief Returns the name of a file node. - -The function returns the name of a file node or NULL, if the file node does not have a name or if -node is NULL. -@param node File node - */ -CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); - -/*********************************** Adding own types ***********************************/ - -/** @brief Registers a new type. - -The function registers a new type, which is described by info . The function creates a copy of the -structure, so the user should delete it after calling the function. -@param info Type info structure - */ -CVAPI(void) cvRegisterType( const CvTypeInfo* info ); - -/** @brief Unregisters the type. - -The function unregisters a type with a specified name. If the name is unknown, it is possible to -locate the type info by an instance of the type using cvTypeOf or by iterating the type list, -starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). -@param type_name Name of an unregistered type - */ -CVAPI(void) cvUnregisterType( const char* type_name ); - -/** @brief Returns the beginning of a type list. - -The function returns the first type in the list of registered types. Navigation through the list can -be done via the prev and next fields of the CvTypeInfo structure. - */ -CVAPI(CvTypeInfo*) cvFirstType(void); - -/** @brief Finds a type by its name. - -The function finds a registered type by its name. It returns NULL if there is no type with the -specified name. -@param type_name Type name - */ -CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); - -/** @brief Returns the type of an object. - -The function finds the type of a given object. It iterates through the list of registered types and -calls the is_instance function/method for every type info structure with that object until one of -them returns non-zero or until the whole list has been traversed. In the latter case, the function -returns NULL. -@param struct_ptr The object pointer - */ -CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); - -#endif - -/** @brief Releases an object. - - The function finds the type of a given object and calls release with the double pointer. - @param struct_ptr Double pointer to the object - */ -CVAPI(void) cvRelease( void** struct_ptr ); - -/** @brief Makes a clone of an object. - -The function finds the type of a given object and calls clone with the passed object. Of course, if -you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific -function, like cvCloneMat. -@param struct_ptr The object to clone - */ -CVAPI(void*) cvClone( const void* struct_ptr ); - -/*********************************** Measuring Execution Time ***************************/ - -/** helper functions for RNG initialization and accurate time measurement: - uses internal clock counter on x86 */ -CVAPI(int64) cvGetTickCount( void ); -CVAPI(double) cvGetTickFrequency( void ); - -/*********************************** CPU capabilities ***********************************/ - -CVAPI(int) cvCheckHardwareSupport(int feature); - -/*********************************** Multi-Threading ************************************/ - -/** retrieve/set the number of threads used in OpenMP implementations */ -CVAPI(int) cvGetNumThreads( void ); -CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); -/** get index of the thread being executed */ -CVAPI(int) cvGetThreadNum( void ); - - -/********************************** Error Handling **************************************/ - -/** Get current OpenCV error status */ -CVAPI(int) cvGetErrStatus( void ); - -/** Sets error status silently */ -CVAPI(void) cvSetErrStatus( int status ); - -#define CV_ErrModeLeaf 0 /* Print error and exit program */ -#define CV_ErrModeParent 1 /* Print error and continue */ -#define CV_ErrModeSilent 2 /* Don't print and continue */ - -/** Retrieves current error processing mode */ -CVAPI(int) cvGetErrMode( void ); - -/** Sets error processing mode, returns previously used mode */ -CVAPI(int) cvSetErrMode( int mode ); - -/** Sets error status and performs some additional actions (displaying message box, - writing message to stderr, terminating application etc.) - depending on the current error mode */ -CVAPI(void) cvError( int status, const char* func_name, - const char* err_msg, const char* file_name, int line ); - -/** Retrieves textual description of the error given its code */ -CVAPI(const char*) cvErrorStr( int status ); - -/** Retrieves detailed information about the last error occurred */ -CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, - const char** filename, int* line ); - -/** Maps IPP error codes to the counterparts from OpenCV */ -CVAPI(int) cvErrorFromIppStatus( int ipp_status ); - -typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, - const char* err_msg, const char* file_name, int line, void* userdata ); - -/** Assigns a new error-handling function */ -CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, - void* userdata CV_DEFAULT(NULL), - void** prev_userdata CV_DEFAULT(NULL) ); - -/** Output nothing */ -CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - -/** Output to console(fprintf(stderr,...)) */ -CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - -/** Output to MessageBox(WIN32) */ -CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, - const char* file_name, int line, void* userdata ); - -#define OPENCV_ERROR(status,func,context) \ -cvError((status),(func),(context),__FILE__,__LINE__) - -#define OPENCV_ASSERT(expr,func,context) \ -{if (! (expr)) \ -{OPENCV_ERROR(CV_StsInternal,(func),(context));}} - -#define OPENCV_CALL( Func ) \ -{ \ -Func; \ -} - - -/** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ -#ifdef CV_NO_FUNC_NAMES -#define CV_FUNCNAME( Name ) -#define cvFuncName "" -#else -#define CV_FUNCNAME( Name ) \ -static char cvFuncName[] = Name -#endif - - -/** - CV_ERROR macro unconditionally raises error with passed code and message. - After raising error, control will be transferred to the exit label. - */ -#define CV_ERROR( Code, Msg ) \ -{ \ - cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ - __CV_EXIT__; \ -} - -/** - CV_CHECK macro checks error status after CV (or IPL) - function call. If error detected, control will be transferred to the exit - label. - */ -#define CV_CHECK() \ -{ \ - if( cvGetErrStatus() < 0 ) \ - CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ -} - - -/** - CV_CALL macro calls CV (or IPL) function, checks error status and - signals a error if the function failed. Useful in "parent node" - error processing mode - */ -#define CV_CALL( Func ) \ -{ \ - Func; \ - CV_CHECK(); \ -} - - -/** Runtime assertion macro */ -#define CV_ASSERT( Condition ) \ -{ \ - if( !(Condition) ) \ - CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ -} - -#define __CV_BEGIN__ { -#define __CV_END__ goto exit; exit: ; } -#define __CV_EXIT__ goto exit - -/** @} core_c */ - -#ifdef __cplusplus -} // extern "C" -#endif - -#ifdef __cplusplus - -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @addtogroup core_c_glue -//! @{ - -/////////////////////////////////////////// glue /////////////////////////////////////////// - -//! converts array (CvMat or IplImage) to cv::Mat -CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, - bool allowND=true, int coiMode=0, - AutoBuffer* buf=0); - -static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) -{ - return cvarrToMat(arr, copyData, true, coiMode); -} - - -//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. -CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); -//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage -CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); - - - -////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// - -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMat* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(IplImage* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMatND* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; }; - -////////////// convenient wrappers for operating old-style dynamic structures ////////////// - -template class SeqIterator; - -typedef Ptr MemStorage; - -/*! - Template Sequence Class derived from CvSeq - - The class provides more convenient access to sequence elements, - STL-style operations and iterators. - - \note The class is targeted for simple data types, - i.e. no constructors or destructors - are called for the sequence elements. -*/ -template class Seq -{ -public: - typedef SeqIterator<_Tp> iterator; - typedef SeqIterator<_Tp> const_iterator; - - //! the default constructor - Seq(); - //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. - Seq(const CvSeq* seq); - //! creates the empty sequence that resides in the specified storage - Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); - //! returns read-write reference to the specified element - _Tp& operator [](int idx); - //! returns read-only reference to the specified element - const _Tp& operator[](int idx) const; - //! returns iterator pointing to the beginning of the sequence - SeqIterator<_Tp> begin() const; - //! returns iterator pointing to the element following the last sequence element - SeqIterator<_Tp> end() const; - //! returns the number of elements in the sequence - size_t size() const; - //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) - int type() const; - //! returns the depth of sequence elements (CV_8U ... CV_64F) - int depth() const; - //! returns the number of channels in each sequence element - int channels() const; - //! returns the size of each sequence element - size_t elemSize() const; - //! returns index of the specified sequence element - size_t index(const _Tp& elem) const; - //! appends the specified element to the end of the sequence - void push_back(const _Tp& elem); - //! appends the specified element to the front of the sequence - void push_front(const _Tp& elem); - //! appends zero or more elements to the end of the sequence - void push_back(const _Tp* elems, size_t count); - //! appends zero or more elements to the front of the sequence - void push_front(const _Tp* elems, size_t count); - //! inserts the specified element to the specified position - void insert(int idx, const _Tp& elem); - //! inserts zero or more elements to the specified position - void insert(int idx, const _Tp* elems, size_t count); - //! removes element at the specified position - void remove(int idx); - //! removes the specified subsequence - void remove(const Range& r); - - //! returns reference to the first sequence element - _Tp& front(); - //! returns read-only reference to the first sequence element - const _Tp& front() const; - //! returns reference to the last sequence element - _Tp& back(); - //! returns read-only reference to the last sequence element - const _Tp& back() const; - //! returns true iff the sequence contains no elements - bool empty() const; - - //! removes all the elements from the sequence - void clear(); - //! removes the first element from the sequence - void pop_front(); - //! removes the last element from the sequence - void pop_back(); - //! removes zero or more elements from the beginning of the sequence - void pop_front(_Tp* elems, size_t count); - //! removes zero or more elements from the end of the sequence - void pop_back(_Tp* elems, size_t count); - - //! copies the whole sequence or the sequence slice to the specified vector - void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; - //! returns the vector containing all the sequence elements - operator std::vector<_Tp>() const; - - CvSeq* seq; -}; - - -/*! - STL-style Sequence Iterator inherited from the CvSeqReader structure -*/ -template class SeqIterator : public CvSeqReader -{ -public: - //! the default constructor - SeqIterator(); - //! the constructor setting the iterator to the beginning or to the end of the sequence - SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); - //! positions the iterator within the sequence - void seek(size_t pos); - //! reports the current iterator position - size_t tell() const; - //! returns reference to the current sequence element - _Tp& operator *(); - //! returns read-only reference to the current sequence element - const _Tp& operator *() const; - //! moves iterator to the next sequence element - SeqIterator& operator ++(); - //! moves iterator to the next sequence element - SeqIterator operator ++(int) const; - //! moves iterator to the previous sequence element - SeqIterator& operator --(); - //! moves iterator to the previous sequence element - SeqIterator operator --(int) const; - - //! moves iterator forward by the specified offset (possibly negative) - SeqIterator& operator +=(int); - //! moves iterator backward by the specified offset (possibly negative) - SeqIterator& operator -=(int); - - // this is index of the current element module seq->total*2 - // (to distinguish between 0 and seq->total) - int index; -}; - - - -// bridge C++ => C Seq API -CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); -CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); -CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); -CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); -CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, - int count, int in_front=0 ); -CV_EXPORTS void seqRemove( CvSeq* seq, int index ); -CV_EXPORTS void clearSeq( CvSeq* seq ); -CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); -CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); -CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); - -template inline Seq<_Tp>::Seq() : seq(0) {} -template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) -{ - CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); -} - -template inline Seq<_Tp>::Seq( MemStorage& storage, - int headerSize ) -{ - CV_Assert(headerSize >= (int)sizeof(CvSeq)); - seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); -} - -template inline _Tp& Seq<_Tp>::operator [](int idx) -{ return *(_Tp*)getSeqElem(seq, idx); } - -template inline const _Tp& Seq<_Tp>::operator [](int idx) const -{ return *(_Tp*)getSeqElem(seq, idx); } - -template inline SeqIterator<_Tp> Seq<_Tp>::begin() const -{ return SeqIterator<_Tp>(*this); } - -template inline SeqIterator<_Tp> Seq<_Tp>::end() const -{ return SeqIterator<_Tp>(*this, true); } - -template inline size_t Seq<_Tp>::size() const -{ return seq ? seq->total : 0; } - -template inline int Seq<_Tp>::type() const -{ return seq ? CV_MAT_TYPE(seq->flags) : 0; } - -template inline int Seq<_Tp>::depth() const -{ return seq ? CV_MAT_DEPTH(seq->flags) : 0; } - -template inline int Seq<_Tp>::channels() const -{ return seq ? CV_MAT_CN(seq->flags) : 0; } - -template inline size_t Seq<_Tp>::elemSize() const -{ return seq ? seq->elem_size : 0; } - -template inline size_t Seq<_Tp>::index(const _Tp& elem) const -{ return cvSeqElemIdx(seq, &elem); } - -template inline void Seq<_Tp>::push_back(const _Tp& elem) -{ cvSeqPush(seq, &elem); } - -template inline void Seq<_Tp>::push_front(const _Tp& elem) -{ cvSeqPushFront(seq, &elem); } - -template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 0); } - -template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) -{ cvSeqPushMulti(seq, elem, (int)count, 1); } - -template inline _Tp& Seq<_Tp>::back() -{ return *(_Tp*)getSeqElem(seq, -1); } - -template inline const _Tp& Seq<_Tp>::back() const -{ return *(const _Tp*)getSeqElem(seq, -1); } - -template inline _Tp& Seq<_Tp>::front() -{ return *(_Tp*)getSeqElem(seq, 0); } - -template inline const _Tp& Seq<_Tp>::front() const -{ return *(const _Tp*)getSeqElem(seq, 0); } - -template inline bool Seq<_Tp>::empty() const -{ return !seq || seq->total == 0; } - -template inline void Seq<_Tp>::clear() -{ if(seq) clearSeq(seq); } - -template inline void Seq<_Tp>::pop_back() -{ seqPop(seq); } - -template inline void Seq<_Tp>::pop_front() -{ seqPopFront(seq); } - -template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 0); } - -template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) -{ seqPopMulti(seq, elem, (int)count, 1); } - -template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) -{ seqInsert(seq, idx, &elem); } - -template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) -{ - CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); - seqInsertSlice(seq, idx, &m); -} - -template inline void Seq<_Tp>::remove(int idx) -{ seqRemove(seq, idx); } - -template inline void Seq<_Tp>::remove(const Range& r) -{ seqRemoveSlice(seq, cvSlice(r.start, r.end)); } - -template inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const -{ - size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; - vec.resize(len); - if( seq && len ) - cvCvtSeqToArray(seq, &vec[0], cvSlice(range)); -} - -template inline Seq<_Tp>::operator std::vector<_Tp>() const -{ - std::vector<_Tp> vec; - copyTo(vec); - return vec; -} - -template inline SeqIterator<_Tp>::SeqIterator() -{ memset(this, 0, sizeof(*this)); } - -template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) -{ - cvStartReadSeq(_seq.seq, this); - index = seekEnd ? _seq.seq->total : 0; -} - -template inline void SeqIterator<_Tp>::seek(size_t pos) -{ - cvSetSeqReaderPos(this, (int)pos, false); - index = pos; -} - -template inline size_t SeqIterator<_Tp>::tell() const -{ return index; } - -template inline _Tp& SeqIterator<_Tp>::operator *() -{ return *(_Tp*)ptr; } - -template inline const _Tp& SeqIterator<_Tp>::operator *() const -{ return *(const _Tp*)ptr; } - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() -{ - CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); - if( ++index >= seq->total*2 ) - index = 0; - return *this; -} - -template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const -{ - SeqIterator<_Tp> it = *this; - ++*this; - return it; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() -{ - CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); - if( --index < 0 ) - index = seq->total*2-1; - return *this; -} - -template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const -{ - SeqIterator<_Tp> it = *this; - --*this; - return it; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) -{ - cvSetSeqReaderPos(this, delta, 1); - index += delta; - int n = seq->total*2; - if( index < 0 ) - index += n; - if( index >= n ) - index -= n; - return *this; -} - -template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) -{ - return (*this += -delta); -} - -template inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - ptrdiff_t delta = a.index - b.index, n = a.seq->total; - if( delta > n || delta < -n ) - delta += delta < 0 ? n : -n; - return delta; -} - -template inline bool operator == (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - return a.seq == b.seq && a.index == b.index; -} - -template inline bool operator != (const SeqIterator<_Tp>& a, - const SeqIterator<_Tp>& b) -{ - return !(a == b); -} - -//! @} - -} // cv - -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + + +#ifndef OPENCV_CORE_C_H +#define OPENCV_CORE_C_H + +#include "opencv2/core/types_c.h" + +#ifdef __cplusplus +/* disable MSVC warning C4190 / clang-cl -Wreturn-type-c-linkage: + 'function' has C-linkage specified, but returns UDT 'typename' + which is incompatible with C + + It is OK to disable it because we only extend few plain structures with + C++ constructors for simpler interoperability with C++ API of the library +*/ +# if defined(__clang__) + // handle clang on Linux and clang-cl (i. e. clang on Windows) first +# pragma GCC diagnostic ignored "-Wreturn-type-c-linkage" +# elif defined(_MSC_VER) + // then handle MSVC +# pragma warning(disable:4190) +# endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup core_c + @{ +*/ + +/****************************************************************************************\ +* Array allocation, deallocation, initialization and access to elements * +\****************************************************************************************/ + +/** `malloc` wrapper. + If there is no enough memory, the function + (as well as other OpenCV functions that call cvAlloc) + raises an error. */ +CVAPI(void*) cvAlloc( size_t size ); + +/** `free` wrapper. + Here and further all the memory releasing functions + (that all call cvFree) take double pointer in order to + to clear pointer to the data after releasing it. + Passing pointer to NULL pointer is Ok: nothing happens in this case +*/ +CVAPI(void) cvFree_( void* ptr ); +#define cvFree(ptr) (cvFree_(*(ptr)), *(ptr)=0) + +/** @brief Creates an image header but does not allocate the image data. + +@param size Image width and height +@param depth Image depth (see cvCreateImage ) +@param channels Number of channels (see cvCreateImage ) + */ +CVAPI(IplImage*) cvCreateImageHeader( CvSize size, int depth, int channels ); + +/** @brief Initializes an image header that was previously allocated. + +The returned IplImage\* points to the initialized header. +@param image Image header to initialize +@param size Image width and height +@param depth Image depth (see cvCreateImage ) +@param channels Number of channels (see cvCreateImage ) +@param origin Top-left IPL_ORIGIN_TL or bottom-left IPL_ORIGIN_BL +@param align Alignment for image rows, typically 4 or 8 bytes + */ +CVAPI(IplImage*) cvInitImageHeader( IplImage* image, CvSize size, int depth, + int channels, int origin CV_DEFAULT(0), + int align CV_DEFAULT(4)); + +/** @brief Creates an image header and allocates the image data. + +This function call is equivalent to the following code: +@code + header = cvCreateImageHeader(size, depth, channels); + cvCreateData(header); +@endcode +@param size Image width and height +@param depth Bit depth of image elements. See IplImage for valid depths. +@param channels Number of channels per pixel. See IplImage for details. This function only creates +images with interleaved channels. + */ +CVAPI(IplImage*) cvCreateImage( CvSize size, int depth, int channels ); + +/** @brief Deallocates an image header. + +This call is an analogue of : +@code + if(image ) + { + iplDeallocate(*image, IPL_IMAGE_HEADER | IPL_IMAGE_ROI); + *image = 0; + } +@endcode +but it does not use IPL functions by default (see the CV_TURN_ON_IPL_COMPATIBILITY macro). +@param image Double pointer to the image header + */ +CVAPI(void) cvReleaseImageHeader( IplImage** image ); + +/** @brief Deallocates the image header and the image data. + +This call is a shortened form of : +@code + if(*image ) + { + cvReleaseData(*image); + cvReleaseImageHeader(image); + } +@endcode +@param image Double pointer to the image header +*/ +CVAPI(void) cvReleaseImage( IplImage** image ); + +/** Creates a copy of IPL image (widthStep may differ) */ +CVAPI(IplImage*) cvCloneImage( const IplImage* image ); + +/** @brief Sets the channel of interest in an IplImage. + +If the ROI is set to NULL and the coi is *not* 0, the ROI is allocated. Most OpenCV functions do +*not* support the COI setting, so to process an individual image/matrix channel one may copy (via +cvCopy or cvSplit) the channel to a separate image/matrix, process it and then copy the result +back (via cvCopy or cvMerge) if needed. +@param image A pointer to the image header +@param coi The channel of interest. 0 - all channels are selected, 1 - first channel is selected, +etc. Note that the channel indices become 1-based. + */ +CVAPI(void) cvSetImageCOI( IplImage* image, int coi ); + +/** @brief Returns the index of the channel of interest. + +Returns the channel of interest of in an IplImage. Returned values correspond to the coi in +cvSetImageCOI. +@param image A pointer to the image header + */ +CVAPI(int) cvGetImageCOI( const IplImage* image ); + +/** @brief Sets an image Region Of Interest (ROI) for a given rectangle. + +If the original image ROI was NULL and the rect is not the whole image, the ROI structure is +allocated. + +Most OpenCV functions support the use of ROI and treat the image rectangle as a separate image. For +example, all of the pixel coordinates are counted from the top-left (or bottom-left) corner of the +ROI, not the original image. +@param image A pointer to the image header +@param rect The ROI rectangle + */ +CVAPI(void) cvSetImageROI( IplImage* image, CvRect rect ); + +/** @brief Resets the image ROI to include the entire image and releases the ROI structure. + +This produces a similar result to the following, but in addition it releases the ROI structure. : +@code + cvSetImageROI(image, cvRect(0, 0, image->width, image->height )); + cvSetImageCOI(image, 0); +@endcode +@param image A pointer to the image header + */ +CVAPI(void) cvResetImageROI( IplImage* image ); + +/** @brief Returns the image ROI. + +If there is no ROI set, cvRect(0,0,image-\>width,image-\>height) is returned. +@param image A pointer to the image header + */ +CVAPI(CvRect) cvGetImageROI( const IplImage* image ); + +/** @brief Creates a matrix header but does not allocate the matrix data. + +The function allocates a new matrix header and returns a pointer to it. The matrix data can then be +allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. +@param rows Number of rows in the matrix +@param cols Number of columns in the matrix +@param type Type of the matrix elements, see cvCreateMat + */ +CVAPI(CvMat*) cvCreateMatHeader( int rows, int cols, int type ); + +#define CV_AUTOSTEP 0x7fffffff + +/** @brief Initializes a pre-allocated matrix header. + +This function is often used to process raw data with OpenCV matrix functions. For example, the +following code computes the matrix product of two matrices, stored as ordinary arrays: +@code + double a[] = { 1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12 }; + + double b[] = { 1, 5, 9, + 2, 6, 10, + 3, 7, 11, + 4, 8, 12 }; + + double c[9]; + CvMat Ma, Mb, Mc ; + + cvInitMatHeader(&Ma, 3, 4, CV_64FC1, a); + cvInitMatHeader(&Mb, 4, 3, CV_64FC1, b); + cvInitMatHeader(&Mc, 3, 3, CV_64FC1, c); + + cvMatMulAdd(&Ma, &Mb, 0, &Mc); + // the c array now contains the product of a (3x4) and b (4x3) +@endcode +@param mat A pointer to the matrix header to be initialized +@param rows Number of rows in the matrix +@param cols Number of columns in the matrix +@param type Type of the matrix elements, see cvCreateMat . +@param data Optional: data pointer assigned to the matrix header +@param step Optional: full row width in bytes of the assigned data. By default, the minimal +possible step is used which assumes there are no gaps between subsequent rows of the matrix. + */ +CVAPI(CvMat*) cvInitMatHeader( CvMat* mat, int rows, int cols, + int type, void* data CV_DEFAULT(NULL), + int step CV_DEFAULT(CV_AUTOSTEP) ); + +/** @brief Creates a matrix header and allocates the matrix data. + +The function call is equivalent to the following code: +@code + CvMat* mat = cvCreateMatHeader(rows, cols, type); + cvCreateData(mat); +@endcode +@param rows Number of rows in the matrix +@param cols Number of columns in the matrix +@param type The type of the matrix elements in the form +CV_\\C\ , where S=signed, U=unsigned, F=float. For +example, CV _ 8UC1 means the elements are 8-bit unsigned and the there is 1 channel, and CV _ +32SC2 means the elements are 32-bit signed and there are 2 channels. + */ +CVAPI(CvMat*) cvCreateMat( int rows, int cols, int type ); + +/** @brief Deallocates a matrix. + +The function decrements the matrix data reference counter and deallocates matrix header. If the data +reference counter is 0, it also deallocates the data. : +@code + if(*mat ) + cvDecRefData(*mat); + cvFree((void**)mat); +@endcode +@param mat Double pointer to the matrix + */ +CVAPI(void) cvReleaseMat( CvMat** mat ); + +/** @brief Decrements an array data reference counter. + +The function decrements the data reference counter in a CvMat or CvMatND if the reference counter + +pointer is not NULL. If the counter reaches zero, the data is deallocated. In the current +implementation the reference counter is not NULL only if the data was allocated using the +cvCreateData function. The counter will be NULL in other cases such as: external data was assigned +to the header using cvSetData, header is part of a larger matrix or image, or the header was +converted from an image or n-dimensional matrix header. +@param arr Pointer to an array header + */ +CV_INLINE void cvDecRefData( CvArr* arr ) +{ + if( CV_IS_MAT( arr )) + { + CvMat* mat = (CvMat*)arr; + mat->data.ptr = NULL; + if( mat->refcount != NULL && --*mat->refcount == 0 ) + cvFree( &mat->refcount ); + mat->refcount = NULL; + } + else if( CV_IS_MATND( arr )) + { + CvMatND* mat = (CvMatND*)arr; + mat->data.ptr = NULL; + if( mat->refcount != NULL && --*mat->refcount == 0 ) + cvFree( &mat->refcount ); + mat->refcount = NULL; + } +} + +/** @brief Increments array data reference counter. + +The function increments CvMat or CvMatND data reference counter and returns the new counter value if +the reference counter pointer is not NULL, otherwise it returns zero. +@param arr Array header + */ +CV_INLINE int cvIncRefData( CvArr* arr ) +{ + int refcount = 0; + if( CV_IS_MAT( arr )) + { + CvMat* mat = (CvMat*)arr; + if( mat->refcount != NULL ) + refcount = ++*mat->refcount; + } + else if( CV_IS_MATND( arr )) + { + CvMatND* mat = (CvMatND*)arr; + if( mat->refcount != NULL ) + refcount = ++*mat->refcount; + } + return refcount; +} + + +/** Creates an exact copy of the input matrix (except, may be, step value) */ +CVAPI(CvMat*) cvCloneMat( const CvMat* mat ); + + +/** @brief Returns matrix header corresponding to the rectangular sub-array of input image or matrix. + +The function returns header, corresponding to a specified rectangle of the input array. In other + +words, it allows the user to treat a rectangular part of input array as a stand-alone array. ROI is +taken into account by the function so the sub-array of ROI is actually extracted. +@param arr Input array +@param submat Pointer to the resultant sub-array header +@param rect Zero-based coordinates of the rectangle of interest + */ +CVAPI(CvMat*) cvGetSubRect( const CvArr* arr, CvMat* submat, CvRect rect ); +#define cvGetSubArr cvGetSubRect + +/** @brief Returns array row or row span. + +The function returns the header, corresponding to a specified row/row span of the input array. +cvGetRow(arr, submat, row) is a shortcut for cvGetRows(arr, submat, row, row+1). +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param start_row Zero-based index of the starting row (inclusive) of the span +@param end_row Zero-based index of the ending row (exclusive) of the span +@param delta_row Index step in the row span. That is, the function extracts every delta_row -th +row from start_row and up to (but not including) end_row . + */ +CVAPI(CvMat*) cvGetRows( const CvArr* arr, CvMat* submat, + int start_row, int end_row, + int delta_row CV_DEFAULT(1)); + +/** @overload +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param row Zero-based index of the selected row +*/ +CV_INLINE CvMat* cvGetRow( const CvArr* arr, CvMat* submat, int row ) +{ + return cvGetRows( arr, submat, row, row + 1, 1 ); +} + + +/** @brief Returns one of more array columns. + +The function returns the header, corresponding to a specified column span of the input array. That + +is, no data is copied. Therefore, any modifications of the submatrix will affect the original array. +If you need to copy the columns, use cvCloneMat. cvGetCol(arr, submat, col) is a shortcut for +cvGetCols(arr, submat, col, col+1). +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param start_col Zero-based index of the starting column (inclusive) of the span +@param end_col Zero-based index of the ending column (exclusive) of the span + */ +CVAPI(CvMat*) cvGetCols( const CvArr* arr, CvMat* submat, + int start_col, int end_col ); + +/** @overload +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param col Zero-based index of the selected column +*/ +CV_INLINE CvMat* cvGetCol( const CvArr* arr, CvMat* submat, int col ) +{ + return cvGetCols( arr, submat, col, col + 1 ); +} + +/** @brief Returns one of array diagonals. + +The function returns the header, corresponding to a specified diagonal of the input array. +@param arr Input array +@param submat Pointer to the resulting sub-array header +@param diag Index of the array diagonal. Zero value corresponds to the main diagonal, -1 +corresponds to the diagonal above the main, 1 corresponds to the diagonal below the main, and so +forth. + */ +CVAPI(CvMat*) cvGetDiag( const CvArr* arr, CvMat* submat, + int diag CV_DEFAULT(0)); + +/** low-level scalar <-> raw data conversion functions */ +CVAPI(void) cvScalarToRawData( const CvScalar* scalar, void* data, int type, + int extend_to_12 CV_DEFAULT(0) ); + +CVAPI(void) cvRawDataToScalar( const void* data, int type, CvScalar* scalar ); + +/** @brief Creates a new matrix header but does not allocate the matrix data. + +The function allocates a header for a multi-dimensional dense array. The array data can further be +allocated using cvCreateData or set explicitly to user-allocated data via cvSetData. +@param dims Number of array dimensions +@param sizes Array of dimension sizes +@param type Type of array elements, see cvCreateMat + */ +CVAPI(CvMatND*) cvCreateMatNDHeader( int dims, const int* sizes, int type ); + +/** @brief Creates the header and allocates the data for a multi-dimensional dense array. + +This function call is equivalent to the following code: +@code + CvMatND* mat = cvCreateMatNDHeader(dims, sizes, type); + cvCreateData(mat); +@endcode +@param dims Number of array dimensions. This must not exceed CV_MAX_DIM (32 by default, but can be +changed at build time). +@param sizes Array of dimension sizes. +@param type Type of array elements, see cvCreateMat . + */ +CVAPI(CvMatND*) cvCreateMatND( int dims, const int* sizes, int type ); + +/** @brief Initializes a pre-allocated multi-dimensional array header. + +@param mat A pointer to the array header to be initialized +@param dims The number of array dimensions +@param sizes An array of dimension sizes +@param type Type of array elements, see cvCreateMat +@param data Optional data pointer assigned to the matrix header + */ +CVAPI(CvMatND*) cvInitMatNDHeader( CvMatND* mat, int dims, const int* sizes, + int type, void* data CV_DEFAULT(NULL) ); + +/** @brief Deallocates a multi-dimensional array. + +The function decrements the array data reference counter and releases the array header. If the +reference counter reaches 0, it also deallocates the data. : +@code + if(*mat ) + cvDecRefData(*mat); + cvFree((void**)mat); +@endcode +@param mat Double pointer to the array + */ +CV_INLINE void cvReleaseMatND( CvMatND** mat ) +{ + cvReleaseMat( (CvMat**)mat ); +} + +/** Creates a copy of CvMatND (except, may be, steps) */ +CVAPI(CvMatND*) cvCloneMatND( const CvMatND* mat ); + +/** @brief Creates sparse array. + +The function allocates a multi-dimensional sparse array. Initially the array contain no elements, +that is PtrND and other related functions will return 0 for every index. +@param dims Number of array dimensions. In contrast to the dense matrix, the number of dimensions is +practically unlimited (up to \f$2^{16}\f$ ). +@param sizes Array of dimension sizes +@param type Type of array elements. The same as for CvMat + */ +CVAPI(CvSparseMat*) cvCreateSparseMat( int dims, const int* sizes, int type ); + +/** @brief Deallocates sparse array. + +The function releases the sparse array and clears the array pointer upon exit. +@param mat Double pointer to the array + */ +CVAPI(void) cvReleaseSparseMat( CvSparseMat** mat ); + +/** Creates a copy of CvSparseMat (except, may be, zero items) */ +CVAPI(CvSparseMat*) cvCloneSparseMat( const CvSparseMat* mat ); + +/** @brief Initializes sparse array elements iterator. + +The function initializes iterator of sparse array elements and returns pointer to the first element, +or NULL if the array is empty. +@param mat Input array +@param mat_iterator Initialized iterator + */ +CVAPI(CvSparseNode*) cvInitSparseMatIterator( const CvSparseMat* mat, + CvSparseMatIterator* mat_iterator ); + +/** @brief Returns the next sparse matrix element + +The function moves iterator to the next sparse matrix element and returns pointer to it. In the +current version there is no any particular order of the elements, because they are stored in the +hash table. The sample below demonstrates how to iterate through the sparse matrix: +@code + // print all the non-zero sparse matrix elements and compute their sum + double sum = 0; + int i, dims = cvGetDims(sparsemat); + CvSparseMatIterator it; + CvSparseNode* node = cvInitSparseMatIterator(sparsemat, &it); + + for(; node != 0; node = cvGetNextSparseNode(&it)) + { + int* idx = CV_NODE_IDX(array, node); + float val = *(float*)CV_NODE_VAL(array, node); + printf("M"); + for(i = 0; i < dims; i++ ) + printf("[%d]", idx[i]); + printf("=%g\n", val); + + sum += val; + } + + printf("nTotal sum = %g\n", sum); +@endcode +@param mat_iterator Sparse array iterator + */ +CV_INLINE CvSparseNode* cvGetNextSparseNode( CvSparseMatIterator* mat_iterator ) +{ + if( mat_iterator->node->next ) + return mat_iterator->node = mat_iterator->node->next; + else + { + int idx; + for( idx = ++mat_iterator->curidx; idx < mat_iterator->mat->hashsize; idx++ ) + { + CvSparseNode* node = (CvSparseNode*)mat_iterator->mat->hashtable[idx]; + if( node ) + { + mat_iterator->curidx = idx; + return mat_iterator->node = node; + } + } + return NULL; + } +} + + +#define CV_MAX_ARR 10 + +/** matrix iterator: used for n-ary operations on dense arrays */ +typedef struct CvNArrayIterator +{ + int count; /**< number of arrays */ + int dims; /**< number of dimensions to iterate */ + CvSize size; /**< maximal common linear size: { width = size, height = 1 } */ + uchar* ptr[CV_MAX_ARR]; /**< pointers to the array slices */ + int stack[CV_MAX_DIM]; /**< for internal use */ + CvMatND* hdr[CV_MAX_ARR]; /**< pointers to the headers of the + matrices that are processed */ +} +CvNArrayIterator; + +#define CV_NO_DEPTH_CHECK 1 +#define CV_NO_CN_CHECK 2 +#define CV_NO_SIZE_CHECK 4 + +/** initializes iterator that traverses through several arrays simultaneously + (the function together with cvNextArraySlice is used for + N-ari element-wise operations) */ +CVAPI(int) cvInitNArrayIterator( int count, CvArr** arrs, + const CvArr* mask, CvMatND* stubs, + CvNArrayIterator* array_iterator, + int flags CV_DEFAULT(0) ); + +/** returns zero value if iteration is finished, non-zero (slice length) otherwise */ +CVAPI(int) cvNextNArraySlice( CvNArrayIterator* array_iterator ); + + +/** @brief Returns type of array elements. + +The function returns type of the array elements. In the case of IplImage the type is converted to +CvMat-like representation. For example, if the image has been created as: +@code + IplImage* img = cvCreateImage(cvSize(640, 480), IPL_DEPTH_8U, 3); +@endcode +The code cvGetElemType(img) will return CV_8UC3. +@param arr Input array + */ +CVAPI(int) cvGetElemType( const CvArr* arr ); + +/** @brief Return number of array dimensions + +The function returns the array dimensionality and the array of dimension sizes. In the case of +IplImage or CvMat it always returns 2 regardless of number of image/matrix rows. For example, the +following code calculates total number of array elements: +@code + int sizes[CV_MAX_DIM]; + int i, total = 1; + int dims = cvGetDims(arr, size); + for(i = 0; i < dims; i++ ) + total *= sizes[i]; +@endcode +@param arr Input array +@param sizes Optional output vector of the array dimension sizes. For 2d arrays the number of rows +(height) goes first, number of columns (width) next. + */ +CVAPI(int) cvGetDims( const CvArr* arr, int* sizes CV_DEFAULT(NULL) ); + + +/** @brief Returns array size along the specified dimension. + +@param arr Input array +@param index Zero-based dimension index (for matrices 0 means number of rows, 1 means number of +columns; for images 0 means height, 1 means width) + */ +CVAPI(int) cvGetDimSize( const CvArr* arr, int index ); + + +/** @brief Return pointer to a particular array element. + +The functions return a pointer to a specific array element. Number of array dimension should match +to the number of indices passed to the function except for cvPtr1D function that can be used for +sequential access to 1D, 2D or nD dense arrays. + +The functions can be used for sparse arrays as well - if the requested node does not exist they +create it and set it to zero. + +All these as well as other functions accessing array elements ( cvGetND , cvGetRealND , cvSet +, cvSetND , cvSetRealND ) raise an error in case if the element index is out of range. +@param arr Input array +@param idx0 The first zero-based component of the element index +@param type Optional output parameter: type of matrix elements + */ +CVAPI(uchar*) cvPtr1D( const CvArr* arr, int idx0, int* type CV_DEFAULT(NULL)); +/** @overload */ +CVAPI(uchar*) cvPtr2D( const CvArr* arr, int idx0, int idx1, int* type CV_DEFAULT(NULL) ); +/** @overload */ +CVAPI(uchar*) cvPtr3D( const CvArr* arr, int idx0, int idx1, int idx2, + int* type CV_DEFAULT(NULL)); +/** @overload +@param arr Input array +@param idx Array of the element indices +@param type Optional output parameter: type of matrix elements +@param create_node Optional input parameter for sparse matrices. Non-zero value of the parameter +means that the requested element is created if it does not exist already. +@param precalc_hashval Optional input parameter for sparse matrices. If the pointer is not NULL, +the function does not recalculate the node hash value, but takes it from the specified location. +It is useful for speeding up pair-wise operations (TODO: provide an example) +*/ +CVAPI(uchar*) cvPtrND( const CvArr* arr, const int* idx, int* type CV_DEFAULT(NULL), + int create_node CV_DEFAULT(1), + unsigned* precalc_hashval CV_DEFAULT(NULL)); + +/** @brief Return a specific array element. + +The functions return a specific array element. In the case of a sparse array the functions return 0 +if the requested node does not exist (no new node is created by the functions). +@param arr Input array +@param idx0 The first zero-based component of the element index + */ +CVAPI(CvScalar) cvGet1D( const CvArr* arr, int idx0 ); +/** @overload */ +CVAPI(CvScalar) cvGet2D( const CvArr* arr, int idx0, int idx1 ); +/** @overload */ +CVAPI(CvScalar) cvGet3D( const CvArr* arr, int idx0, int idx1, int idx2 ); +/** @overload +@param arr Input array +@param idx Array of the element indices +*/ +CVAPI(CvScalar) cvGetND( const CvArr* arr, const int* idx ); + +/** @brief Return a specific element of single-channel 1D, 2D, 3D or nD array. + +Returns a specific element of a single-channel array. If the array has multiple channels, a runtime +error is raised. Note that Get?D functions can be used safely for both single-channel and +multiple-channel arrays though they are a bit slower. + +In the case of a sparse array the functions return 0 if the requested node does not exist (no new +node is created by the functions). +@param arr Input array. Must have a single channel. +@param idx0 The first zero-based component of the element index + */ +CVAPI(double) cvGetReal1D( const CvArr* arr, int idx0 ); +/** @overload */ +CVAPI(double) cvGetReal2D( const CvArr* arr, int idx0, int idx1 ); +/** @overload */ +CVAPI(double) cvGetReal3D( const CvArr* arr, int idx0, int idx1, int idx2 ); +/** @overload +@param arr Input array. Must have a single channel. +@param idx Array of the element indices +*/ +CVAPI(double) cvGetRealND( const CvArr* arr, const int* idx ); + +/** @brief Change the particular array element. + +The functions assign the new value to a particular array element. In the case of a sparse array the +functions create the node if it does not exist yet. +@param arr Input array +@param idx0 The first zero-based component of the element index +@param value The assigned value + */ +CVAPI(void) cvSet1D( CvArr* arr, int idx0, CvScalar value ); +/** @overload */ +CVAPI(void) cvSet2D( CvArr* arr, int idx0, int idx1, CvScalar value ); +/** @overload */ +CVAPI(void) cvSet3D( CvArr* arr, int idx0, int idx1, int idx2, CvScalar value ); +/** @overload +@param arr Input array +@param idx Array of the element indices +@param value The assigned value +*/ +CVAPI(void) cvSetND( CvArr* arr, const int* idx, CvScalar value ); + +/** @brief Change a specific array element. + +The functions assign a new value to a specific element of a single-channel array. If the array has +multiple channels, a runtime error is raised. Note that the Set\*D function can be used safely for +both single-channel and multiple-channel arrays, though they are a bit slower. + +In the case of a sparse array the functions create the node if it does not yet exist. +@param arr Input array +@param idx0 The first zero-based component of the element index +@param value The assigned value + */ +CVAPI(void) cvSetReal1D( CvArr* arr, int idx0, double value ); +/** @overload */ +CVAPI(void) cvSetReal2D( CvArr* arr, int idx0, int idx1, double value ); +/** @overload */ +CVAPI(void) cvSetReal3D( CvArr* arr, int idx0, + int idx1, int idx2, double value ); +/** @overload +@param arr Input array +@param idx Array of the element indices +@param value The assigned value +*/ +CVAPI(void) cvSetRealND( CvArr* arr, const int* idx, double value ); + +/** clears element of ND dense array, + in case of sparse arrays it deletes the specified node */ +CVAPI(void) cvClearND( CvArr* arr, const int* idx ); + +/** @brief Returns matrix header for arbitrary array. + +The function returns a matrix header for the input array that can be a matrix - CvMat, an image - +IplImage, or a multi-dimensional dense array - CvMatND (the third option is allowed only if +allowND != 0) . In the case of matrix the function simply returns the input pointer. In the case of +IplImage\* or CvMatND it initializes the header structure with parameters of the current image ROI +and returns &header. Because COI is not supported by CvMat, it is returned separately. + +The function provides an easy way to handle both types of arrays - IplImage and CvMat using the same +code. Input array must have non-zero data pointer, otherwise the function will report an error. + +@note If the input array is IplImage with planar data layout and COI set, the function returns the +pointer to the selected plane and COI == 0. This feature allows user to process IplImage structures +with planar data layout, even though OpenCV does not support such images. +@param arr Input array +@param header Pointer to CvMat structure used as a temporary buffer +@param coi Optional output parameter for storing COI +@param allowND If non-zero, the function accepts multi-dimensional dense arrays (CvMatND\*) and +returns 2D matrix (if CvMatND has two dimensions) or 1D matrix (when CvMatND has 1 dimension or +more than 2 dimensions). The CvMatND array must be continuous. +@sa cvGetImage, cvarrToMat. + */ +CVAPI(CvMat*) cvGetMat( const CvArr* arr, CvMat* header, + int* coi CV_DEFAULT(NULL), + int allowND CV_DEFAULT(0)); + +/** @brief Returns image header for arbitrary array. + +The function returns the image header for the input array that can be a matrix (CvMat) or image +(IplImage). In the case of an image the function simply returns the input pointer. In the case of +CvMat it initializes an image_header structure with the parameters of the input matrix. Note that +if we transform IplImage to CvMat using cvGetMat and then transform CvMat back to IplImage using +this function, we will get different headers if the ROI is set in the original image. +@param arr Input array +@param image_header Pointer to IplImage structure used as a temporary buffer + */ +CVAPI(IplImage*) cvGetImage( const CvArr* arr, IplImage* image_header ); + + +/** @brief Changes the shape of a multi-dimensional array without copying the data. + +The function is an advanced version of cvReshape that can work with multi-dimensional arrays as +well (though it can work with ordinary images and matrices) and change the number of dimensions. + +Below are the two samples from the cvReshape description rewritten using cvReshapeMatND: +@code + IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); + IplImage gray_img_hdr, *gray_img; + gray_img = (IplImage*)cvReshapeMatND(color_img, sizeof(gray_img_hdr), &gray_img_hdr, 1, 0, 0); + ... + int size[] = { 2, 2, 2 }; + CvMatND* mat = cvCreateMatND(3, size, CV_32F); + CvMat row_header, *row; + row = (CvMat*)cvReshapeMatND(mat, sizeof(row_header), &row_header, 0, 1, 0); +@endcode +In C, the header file for this function includes a convenient macro cvReshapeND that does away with +the sizeof_header parameter. So, the lines containing the call to cvReshapeMatND in the examples +may be replaced as follow: +@code + gray_img = (IplImage*)cvReshapeND(color_img, &gray_img_hdr, 1, 0, 0); + ... + row = (CvMat*)cvReshapeND(mat, &row_header, 0, 1, 0); +@endcode +@param arr Input array +@param sizeof_header Size of output header to distinguish between IplImage, CvMat and CvMatND +output headers +@param header Output header to be filled +@param new_cn New number of channels. new_cn = 0 means that the number of channels remains +unchanged. +@param new_dims New number of dimensions. new_dims = 0 means that the number of dimensions +remains the same. +@param new_sizes Array of new dimension sizes. Only new_dims-1 values are used, because the +total number of elements must remain the same. Thus, if new_dims = 1, new_sizes array is not +used. + */ +CVAPI(CvArr*) cvReshapeMatND( const CvArr* arr, + int sizeof_header, CvArr* header, + int new_cn, int new_dims, int* new_sizes ); + +#define cvReshapeND( arr, header, new_cn, new_dims, new_sizes ) \ + cvReshapeMatND( (arr), sizeof(*(header)), (header), \ + (new_cn), (new_dims), (new_sizes)) + +/** @brief Changes shape of matrix/image without copying data. + +The function initializes the CvMat header so that it points to the same data as the original array +but has a different shape - different number of channels, different number of rows, or both. + +The following example code creates one image buffer and two image headers, the first is for a +320x240x3 image and the second is for a 960x240x1 image: +@code + IplImage* color_img = cvCreateImage(cvSize(320,240), IPL_DEPTH_8U, 3); + CvMat gray_mat_hdr; + IplImage gray_img_hdr, *gray_img; + cvReshape(color_img, &gray_mat_hdr, 1); + gray_img = cvGetImage(&gray_mat_hdr, &gray_img_hdr); +@endcode +And the next example converts a 3x3 matrix to a single 1x9 vector: +@code + CvMat* mat = cvCreateMat(3, 3, CV_32F); + CvMat row_header, *row; + row = cvReshape(mat, &row_header, 0, 1); +@endcode +@param arr Input array +@param header Output header to be filled +@param new_cn New number of channels. 'new_cn = 0' means that the number of channels remains +unchanged. +@param new_rows New number of rows. 'new_rows = 0' means that the number of rows remains +unchanged unless it needs to be changed according to new_cn value. +*/ +CVAPI(CvMat*) cvReshape( const CvArr* arr, CvMat* header, + int new_cn, int new_rows CV_DEFAULT(0) ); + +/** Repeats source 2d array several times in both horizontal and + vertical direction to fill destination array */ +CVAPI(void) cvRepeat( const CvArr* src, CvArr* dst ); + +/** @brief Allocates array data + +The function allocates image, matrix or multi-dimensional dense array data. Note that in the case of +matrix types OpenCV allocation functions are used. In the case of IplImage they are used unless +CV_TURN_ON_IPL_COMPATIBILITY() has been called before. In the latter case IPL functions are used +to allocate the data. +@param arr Array header + */ +CVAPI(void) cvCreateData( CvArr* arr ); + +/** @brief Releases array data. + +The function releases the array data. In the case of CvMat or CvMatND it simply calls +cvDecRefData(), that is the function can not deallocate external data. See also the note to +cvCreateData . +@param arr Array header + */ +CVAPI(void) cvReleaseData( CvArr* arr ); + +/** @brief Assigns user data to the array header. + +The function assigns user data to the array header. Header should be initialized before using +cvCreateMatHeader, cvCreateImageHeader, cvCreateMatNDHeader, cvInitMatHeader, +cvInitImageHeader or cvInitMatNDHeader. +@param arr Array header +@param data User data +@param step Full row length in bytes + */ +CVAPI(void) cvSetData( CvArr* arr, void* data, int step ); + +/** @brief Retrieves low-level information about the array. + +The function fills output variables with low-level information about the array data. All output + +parameters are optional, so some of the pointers may be set to NULL. If the array is IplImage with +ROI set, the parameters of ROI are returned. + +The following example shows how to get access to array elements. It computes absolute values of the +array elements : +@code + float* data; + int step; + CvSize size; + + cvGetRawData(array, (uchar**)&data, &step, &size); + step /= sizeof(data[0]); + + for(int y = 0; y < size.height; y++, data += step ) + for(int x = 0; x < size.width; x++ ) + data[x] = (float)fabs(data[x]); +@endcode +@param arr Array header +@param data Output pointer to the whole image origin or ROI origin if ROI is set +@param step Output full row length in bytes +@param roi_size Output ROI size + */ +CVAPI(void) cvGetRawData( const CvArr* arr, uchar** data, + int* step CV_DEFAULT(NULL), + CvSize* roi_size CV_DEFAULT(NULL)); + +/** @brief Returns size of matrix or image ROI. + +The function returns number of rows (CvSize::height) and number of columns (CvSize::width) of the +input matrix or image. In the case of image the size of ROI is returned. +@param arr array header + */ +CVAPI(CvSize) cvGetSize( const CvArr* arr ); + +/** @brief Copies one array to another. + +The function copies selected elements from an input array to an output array: + +\f[\texttt{dst} (I)= \texttt{src} (I) \quad \text{if} \quad \texttt{mask} (I) \ne 0.\f] + +If any of the passed arrays is of IplImage type, then its ROI and COI fields are used. Both arrays +must have the same type, the same number of dimensions, and the same size. The function can also +copy sparse arrays (mask is not supported in this case). +@param src The source array +@param dst The destination array +@param mask Operation mask, 8-bit single channel array; specifies elements of the destination array +to be changed + */ +CVAPI(void) cvCopy( const CvArr* src, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Sets every element of an array to a given value. + +The function copies the scalar value to every selected element of the destination array: +\f[\texttt{arr} (I)= \texttt{value} \quad \text{if} \quad \texttt{mask} (I) \ne 0\f] +If array arr is of IplImage type, then is ROI used, but COI must not be set. +@param arr The destination array +@param value Fill value +@param mask Operation mask, 8-bit single channel array; specifies elements of the destination +array to be changed + */ +CVAPI(void) cvSet( CvArr* arr, CvScalar value, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Clears the array. + +The function clears the array. In the case of dense arrays (CvMat, CvMatND or IplImage), +cvZero(array) is equivalent to cvSet(array,cvScalarAll(0),0). In the case of sparse arrays all the +elements are removed. +@param arr Array to be cleared + */ +CVAPI(void) cvSetZero( CvArr* arr ); +#define cvZero cvSetZero + + +/** Splits a multi-channel array into the set of single-channel arrays or + extracts particular [color] plane */ +CVAPI(void) cvSplit( const CvArr* src, CvArr* dst0, CvArr* dst1, + CvArr* dst2, CvArr* dst3 ); + +/** Merges a set of single-channel arrays into the single multi-channel array + or inserts one particular [color] plane to the array */ +CVAPI(void) cvMerge( const CvArr* src0, const CvArr* src1, + const CvArr* src2, const CvArr* src3, + CvArr* dst ); + +/** Copies several channels from input arrays to + certain channels of output arrays */ +CVAPI(void) cvMixChannels( const CvArr** src, int src_count, + CvArr** dst, int dst_count, + const int* from_to, int pair_count ); + +/** @brief Converts one array to another with optional linear transformation. + +The function has several different purposes, and thus has several different names. It copies one +array to another with optional scaling, which is performed first, and/or optional type conversion, +performed after: + +\f[\texttt{dst} (I) = \texttt{scale} \texttt{src} (I) + ( \texttt{shift} _0, \texttt{shift} _1,...)\f] + +All the channels of multi-channel arrays are processed independently. + +The type of conversion is done with rounding and saturation, that is if the result of scaling + +conversion can not be represented exactly by a value of the destination array element type, it is +set to the nearest representable value on the real axis. +@param src Source array +@param dst Destination array +@param scale Scale factor +@param shift Value added to the scaled source array elements + */ +CVAPI(void) cvConvertScale( const CvArr* src, CvArr* dst, + double scale CV_DEFAULT(1), + double shift CV_DEFAULT(0) ); +#define cvCvtScale cvConvertScale +#define cvScale cvConvertScale +#define cvConvert( src, dst ) cvConvertScale( (src), (dst), 1, 0 ) + + +/** Performs linear transformation on every source array element, + stores absolute value of the result: + dst(x,y,c) = abs(scale*src(x,y,c)+shift). + destination array must have 8u type. + In other cases one may use cvConvertScale + cvAbsDiffS */ +CVAPI(void) cvConvertScaleAbs( const CvArr* src, CvArr* dst, + double scale CV_DEFAULT(1), + double shift CV_DEFAULT(0) ); +#define cvCvtScaleAbs cvConvertScaleAbs + + +/** checks termination criteria validity and + sets eps to default_eps (if it is not set), + max_iter to default_max_iters (if it is not set) +*/ +CVAPI(CvTermCriteria) cvCheckTermCriteria( CvTermCriteria criteria, + double default_eps, + int default_max_iters ); + +/****************************************************************************************\ +* Arithmetic, logic and comparison operations * +\****************************************************************************************/ + +/** dst(mask) = src1(mask) + src2(mask) */ +CVAPI(void) cvAdd( const CvArr* src1, const CvArr* src2, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(mask) = src(mask) + value */ +CVAPI(void) cvAddS( const CvArr* src, CvScalar value, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(mask) = src1(mask) - src2(mask) */ +CVAPI(void) cvSub( const CvArr* src1, const CvArr* src2, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(mask) = src(mask) - value = src(mask) + (-value) */ +CV_INLINE void cvSubS( const CvArr* src, CvScalar value, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)) +{ + cvAddS( src, cvScalar( -value.val[0], -value.val[1], -value.val[2], -value.val[3]), + dst, mask ); +} + +/** dst(mask) = value - src(mask) */ +CVAPI(void) cvSubRS( const CvArr* src, CvScalar value, CvArr* dst, + const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src1(idx) * src2(idx) * scale + (scaled element-wise multiplication of 2 arrays) */ +CVAPI(void) cvMul( const CvArr* src1, const CvArr* src2, + CvArr* dst, double scale CV_DEFAULT(1) ); + +/** element-wise division/inversion with scaling: + dst(idx) = src1(idx) * scale / src2(idx) + or dst(idx) = scale / src2(idx) if src1 == 0 */ +CVAPI(void) cvDiv( const CvArr* src1, const CvArr* src2, + CvArr* dst, double scale CV_DEFAULT(1)); + +/** dst = src1 * scale + src2 */ +CVAPI(void) cvScaleAdd( const CvArr* src1, CvScalar scale, + const CvArr* src2, CvArr* dst ); +#define cvAXPY( A, real_scalar, B, C ) cvScaleAdd(A, cvRealScalar(real_scalar), B, C) + +/** dst = src1 * alpha + src2 * beta + gamma */ +CVAPI(void) cvAddWeighted( const CvArr* src1, double alpha, + const CvArr* src2, double beta, + double gamma, CvArr* dst ); + +/** @brief Calculates the dot product of two arrays in Euclidean metrics. + +The function calculates and returns the Euclidean dot product of two arrays. + +\f[src1 \bullet src2 = \sum _I ( \texttt{src1} (I) \texttt{src2} (I))\f] + +In the case of multiple channel arrays, the results for all channels are accumulated. In particular, +cvDotProduct(a,a) where a is a complex vector, will return \f$||\texttt{a}||^2\f$. The function can +process multi-dimensional arrays, row by row, layer by layer, and so on. +@param src1 The first source array +@param src2 The second source array + */ +CVAPI(double) cvDotProduct( const CvArr* src1, const CvArr* src2 ); + +/** dst(idx) = src1(idx) & src2(idx) */ +CVAPI(void) cvAnd( const CvArr* src1, const CvArr* src2, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src(idx) & value */ +CVAPI(void) cvAndS( const CvArr* src, CvScalar value, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src1(idx) | src2(idx) */ +CVAPI(void) cvOr( const CvArr* src1, const CvArr* src2, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src(idx) | value */ +CVAPI(void) cvOrS( const CvArr* src, CvScalar value, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src1(idx) ^ src2(idx) */ +CVAPI(void) cvXor( const CvArr* src1, const CvArr* src2, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = src(idx) ^ value */ +CVAPI(void) cvXorS( const CvArr* src, CvScalar value, + CvArr* dst, const CvArr* mask CV_DEFAULT(NULL)); + +/** dst(idx) = ~src(idx) */ +CVAPI(void) cvNot( const CvArr* src, CvArr* dst ); + +/** dst(idx) = lower(idx) <= src(idx) < upper(idx) */ +CVAPI(void) cvInRange( const CvArr* src, const CvArr* lower, + const CvArr* upper, CvArr* dst ); + +/** dst(idx) = lower <= src(idx) < upper */ +CVAPI(void) cvInRangeS( const CvArr* src, CvScalar lower, + CvScalar upper, CvArr* dst ); + +#define CV_CMP_EQ 0 +#define CV_CMP_GT 1 +#define CV_CMP_GE 2 +#define CV_CMP_LT 3 +#define CV_CMP_LE 4 +#define CV_CMP_NE 5 + +/** The comparison operation support single-channel arrays only. + Destination image should be 8uC1 or 8sC1 */ + +/** dst(idx) = src1(idx) _cmp_op_ src2(idx) */ +CVAPI(void) cvCmp( const CvArr* src1, const CvArr* src2, CvArr* dst, int cmp_op ); + +/** dst(idx) = src1(idx) _cmp_op_ value */ +CVAPI(void) cvCmpS( const CvArr* src, double value, CvArr* dst, int cmp_op ); + +/** dst(idx) = min(src1(idx),src2(idx)) */ +CVAPI(void) cvMin( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** dst(idx) = max(src1(idx),src2(idx)) */ +CVAPI(void) cvMax( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** dst(idx) = min(src(idx),value) */ +CVAPI(void) cvMinS( const CvArr* src, double value, CvArr* dst ); + +/** dst(idx) = max(src(idx),value) */ +CVAPI(void) cvMaxS( const CvArr* src, double value, CvArr* dst ); + +/** dst(x,y,c) = abs(src1(x,y,c) - src2(x,y,c)) */ +CVAPI(void) cvAbsDiff( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** dst(x,y,c) = abs(src(x,y,c) - value(c)) */ +CVAPI(void) cvAbsDiffS( const CvArr* src, CvArr* dst, CvScalar value ); +#define cvAbs( src, dst ) cvAbsDiffS( (src), (dst), cvScalarAll(0)) + +/****************************************************************************************\ +* Math operations * +\****************************************************************************************/ + +/** Does cartesian->polar coordinates conversion. + Either of output components (magnitude or angle) is optional */ +CVAPI(void) cvCartToPolar( const CvArr* x, const CvArr* y, + CvArr* magnitude, CvArr* angle CV_DEFAULT(NULL), + int angle_in_degrees CV_DEFAULT(0)); + +/** Does polar->cartesian coordinates conversion. + Either of output components (magnitude or angle) is optional. + If magnitude is missing it is assumed to be all 1's */ +CVAPI(void) cvPolarToCart( const CvArr* magnitude, const CvArr* angle, + CvArr* x, CvArr* y, + int angle_in_degrees CV_DEFAULT(0)); + +/** Does powering: dst(idx) = src(idx)^power */ +CVAPI(void) cvPow( const CvArr* src, CvArr* dst, double power ); + +/** Does exponention: dst(idx) = exp(src(idx)). + Overflow is not handled yet. Underflow is handled. + Maximal relative error is ~7e-6 for single-precision input */ +CVAPI(void) cvExp( const CvArr* src, CvArr* dst ); + +/** Calculates natural logarithms: dst(idx) = log(abs(src(idx))). + Logarithm of 0 gives large negative number(~-700) + Maximal relative error is ~3e-7 for single-precision output +*/ +CVAPI(void) cvLog( const CvArr* src, CvArr* dst ); + +/** Fast arctangent calculation */ +CVAPI(float) cvFastArctan( float y, float x ); + +/** Fast cubic root calculation */ +CVAPI(float) cvCbrt( float value ); + +#define CV_CHECK_RANGE 1 +#define CV_CHECK_QUIET 2 +/** Checks array values for NaNs, Infs or simply for too large numbers + (if CV_CHECK_RANGE is set). If CV_CHECK_QUIET is set, + no runtime errors is raised (function returns zero value in case of "bad" values). + Otherwise cvError is called */ +CVAPI(int) cvCheckArr( const CvArr* arr, int flags CV_DEFAULT(0), + double min_val CV_DEFAULT(0), double max_val CV_DEFAULT(0)); +#define cvCheckArray cvCheckArr + +#define CV_RAND_UNI 0 +#define CV_RAND_NORMAL 1 + +/** @brief Fills an array with random numbers and updates the RNG state. + +The function fills the destination array with uniformly or normally distributed random numbers. +@param rng CvRNG state initialized by cvRNG +@param arr The destination array +@param dist_type Distribution type +> - **CV_RAND_UNI** uniform distribution +> - **CV_RAND_NORMAL** normal or Gaussian distribution +@param param1 The first parameter of the distribution. In the case of a uniform distribution it is +the inclusive lower boundary of the random numbers range. In the case of a normal distribution it +is the mean value of the random numbers. +@param param2 The second parameter of the distribution. In the case of a uniform distribution it +is the exclusive upper boundary of the random numbers range. In the case of a normal distribution +it is the standard deviation of the random numbers. +@sa randu, randn, RNG::fill. + */ +CVAPI(void) cvRandArr( CvRNG* rng, CvArr* arr, int dist_type, + CvScalar param1, CvScalar param2 ); + +CVAPI(void) cvRandShuffle( CvArr* mat, CvRNG* rng, + double iter_factor CV_DEFAULT(1.)); + +#define CV_SORT_EVERY_ROW 0 +#define CV_SORT_EVERY_COLUMN 1 +#define CV_SORT_ASCENDING 0 +#define CV_SORT_DESCENDING 16 + +CVAPI(void) cvSort( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), + CvArr* idxmat CV_DEFAULT(NULL), + int flags CV_DEFAULT(0)); + +/** Finds real roots of a cubic equation */ +CVAPI(int) cvSolveCubic( const CvMat* coeffs, CvMat* roots ); + +/** Finds all real and complex roots of a polynomial equation */ +CVAPI(void) cvSolvePoly(const CvMat* coeffs, CvMat *roots2, + int maxiter CV_DEFAULT(20), int fig CV_DEFAULT(100)); + +/****************************************************************************************\ +* Matrix operations * +\****************************************************************************************/ + +/** @brief Calculates the cross product of two 3D vectors. + +The function calculates the cross product of two 3D vectors: +\f[\texttt{dst} = \texttt{src1} \times \texttt{src2}\f] +or: +\f[\begin{array}{l} \texttt{dst} _1 = \texttt{src1} _2 \texttt{src2} _3 - \texttt{src1} _3 \texttt{src2} _2 \\ \texttt{dst} _2 = \texttt{src1} _3 \texttt{src2} _1 - \texttt{src1} _1 \texttt{src2} _3 \\ \texttt{dst} _3 = \texttt{src1} _1 \texttt{src2} _2 - \texttt{src1} _2 \texttt{src2} _1 \end{array}\f] +@param src1 The first source vector +@param src2 The second source vector +@param dst The destination vector + */ +CVAPI(void) cvCrossProduct( const CvArr* src1, const CvArr* src2, CvArr* dst ); + +/** Matrix transform: dst = A*B + C, C is optional */ +#define cvMatMulAdd( src1, src2, src3, dst ) cvGEMM( (src1), (src2), 1., (src3), 1., (dst), 0 ) +#define cvMatMul( src1, src2, dst ) cvMatMulAdd( (src1), (src2), NULL, (dst)) + +#define CV_GEMM_A_T 1 +#define CV_GEMM_B_T 2 +#define CV_GEMM_C_T 4 +/** Extended matrix transform: + dst = alpha*op(A)*op(B) + beta*op(C), where op(X) is X or X^T */ +CVAPI(void) cvGEMM( const CvArr* src1, const CvArr* src2, double alpha, + const CvArr* src3, double beta, CvArr* dst, + int tABC CV_DEFAULT(0)); +#define cvMatMulAddEx cvGEMM + +/** Transforms each element of source array and stores + resultant vectors in destination array */ +CVAPI(void) cvTransform( const CvArr* src, CvArr* dst, + const CvMat* transmat, + const CvMat* shiftvec CV_DEFAULT(NULL)); +#define cvMatMulAddS cvTransform + +/** Does perspective transform on every element of input array */ +CVAPI(void) cvPerspectiveTransform( const CvArr* src, CvArr* dst, + const CvMat* mat ); + +/** Calculates (A-delta)*(A-delta)^T (order=0) or (A-delta)^T*(A-delta) (order=1) */ +CVAPI(void) cvMulTransposed( const CvArr* src, CvArr* dst, int order, + const CvArr* delta CV_DEFAULT(NULL), + double scale CV_DEFAULT(1.) ); + +/** Transposes matrix. Square matrices can be transposed in-place */ +CVAPI(void) cvTranspose( const CvArr* src, CvArr* dst ); +#define cvT cvTranspose + +/** Completes the symmetric matrix from the lower (LtoR=0) or from the upper (LtoR!=0) part */ +CVAPI(void) cvCompleteSymm( CvMat* matrix, int LtoR CV_DEFAULT(0) ); + +/** Mirror array data around horizontal (flip=0), + vertical (flip=1) or both(flip=-1) axises: + cvFlip(src) flips images vertically and sequences horizontally (inplace) */ +CVAPI(void) cvFlip( const CvArr* src, CvArr* dst CV_DEFAULT(NULL), + int flip_mode CV_DEFAULT(0)); +#define cvMirror cvFlip + + +#define CV_SVD_MODIFY_A 1 +#define CV_SVD_U_T 2 +#define CV_SVD_V_T 4 + +/** Performs Singular Value Decomposition of a matrix */ +CVAPI(void) cvSVD( CvArr* A, CvArr* W, CvArr* U CV_DEFAULT(NULL), + CvArr* V CV_DEFAULT(NULL), int flags CV_DEFAULT(0)); + +/** Performs Singular Value Back Substitution (solves A*X = B): + flags must be the same as in cvSVD */ +CVAPI(void) cvSVBkSb( const CvArr* W, const CvArr* U, + const CvArr* V, const CvArr* B, + CvArr* X, int flags ); + +#define CV_LU 0 +#define CV_SVD 1 +#define CV_SVD_SYM 2 +#define CV_CHOLESKY 3 +#define CV_QR 4 +#define CV_NORMAL 16 + +/** Inverts matrix */ +CVAPI(double) cvInvert( const CvArr* src, CvArr* dst, + int method CV_DEFAULT(CV_LU)); +#define cvInv cvInvert + +/** Solves linear system (src1)*(dst) = (src2) + (returns 0 if src1 is a singular and CV_LU method is used) */ +CVAPI(int) cvSolve( const CvArr* src1, const CvArr* src2, CvArr* dst, + int method CV_DEFAULT(CV_LU)); + +/** Calculates determinant of input matrix */ +CVAPI(double) cvDet( const CvArr* mat ); + +/** Calculates trace of the matrix (sum of elements on the main diagonal) */ +CVAPI(CvScalar) cvTrace( const CvArr* mat ); + +/** Finds eigen values and vectors of a symmetric matrix */ +CVAPI(void) cvEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, + double eps CV_DEFAULT(0), + int lowindex CV_DEFAULT(-1), + int highindex CV_DEFAULT(-1)); + +///* Finds selected eigen values and vectors of a symmetric matrix */ +//CVAPI(void) cvSelectedEigenVV( CvArr* mat, CvArr* evects, CvArr* evals, +// int lowindex, int highindex ); + +/** Makes an identity matrix (mat_ij = i == j) */ +CVAPI(void) cvSetIdentity( CvArr* mat, CvScalar value CV_DEFAULT(cvRealScalar(1)) ); + +/** Fills matrix with given range of numbers */ +CVAPI(CvArr*) cvRange( CvArr* mat, double start, double end ); + +/** @anchor core_c_CovarFlags +@name Flags for cvCalcCovarMatrix +@see cvCalcCovarMatrix + @{ +*/ + +/** flag for cvCalcCovarMatrix, transpose([v1-avg, v2-avg,...]) * [v1-avg,v2-avg,...] */ +#define CV_COVAR_SCRAMBLED 0 + +/** flag for cvCalcCovarMatrix, [v1-avg, v2-avg,...] * transpose([v1-avg,v2-avg,...]) */ +#define CV_COVAR_NORMAL 1 + +/** flag for cvCalcCovarMatrix, do not calc average (i.e. mean vector) - use the input vector instead + (useful for calculating covariance matrix by parts) */ +#define CV_COVAR_USE_AVG 2 + +/** flag for cvCalcCovarMatrix, scale the covariance matrix coefficients by number of the vectors */ +#define CV_COVAR_SCALE 4 + +/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its rows */ +#define CV_COVAR_ROWS 8 + +/** flag for cvCalcCovarMatrix, all the input vectors are stored in a single matrix, as its columns */ +#define CV_COVAR_COLS 16 + +/** @} */ + +/** Calculates covariation matrix for a set of vectors +@see @ref core_c_CovarFlags "flags" +*/ +CVAPI(void) cvCalcCovarMatrix( const CvArr** vects, int count, + CvArr* cov_mat, CvArr* avg, int flags ); + +#define CV_PCA_DATA_AS_ROW 0 +#define CV_PCA_DATA_AS_COL 1 +#define CV_PCA_USE_AVG 2 +CVAPI(void) cvCalcPCA( const CvArr* data, CvArr* mean, + CvArr* eigenvals, CvArr* eigenvects, int flags ); + +CVAPI(void) cvProjectPCA( const CvArr* data, const CvArr* mean, + const CvArr* eigenvects, CvArr* result ); + +CVAPI(void) cvBackProjectPCA( const CvArr* proj, const CvArr* mean, + const CvArr* eigenvects, CvArr* result ); + +/** Calculates Mahalanobis(weighted) distance */ +CVAPI(double) cvMahalanobis( const CvArr* vec1, const CvArr* vec2, const CvArr* mat ); +#define cvMahalonobis cvMahalanobis + +/****************************************************************************************\ +* Array Statistics * +\****************************************************************************************/ + +/** Finds sum of array elements */ +CVAPI(CvScalar) cvSum( const CvArr* arr ); + +/** Calculates number of non-zero pixels */ +CVAPI(int) cvCountNonZero( const CvArr* arr ); + +/** Calculates mean value of array elements */ +CVAPI(CvScalar) cvAvg( const CvArr* arr, const CvArr* mask CV_DEFAULT(NULL) ); + +/** Calculates mean and standard deviation of pixel values */ +CVAPI(void) cvAvgSdv( const CvArr* arr, CvScalar* mean, CvScalar* std_dev, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** Finds global minimum, maximum and their positions */ +CVAPI(void) cvMinMaxLoc( const CvArr* arr, double* min_val, double* max_val, + CvPoint* min_loc CV_DEFAULT(NULL), + CvPoint* max_loc CV_DEFAULT(NULL), + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @anchor core_c_NormFlags + @name Flags for cvNorm and cvNormalize + @{ +*/ +#define CV_C 1 +#define CV_L1 2 +#define CV_L2 4 +#define CV_NORM_MASK 7 +#define CV_RELATIVE 8 +#define CV_DIFF 16 +#define CV_MINMAX 32 + +#define CV_DIFF_C (CV_DIFF | CV_C) +#define CV_DIFF_L1 (CV_DIFF | CV_L1) +#define CV_DIFF_L2 (CV_DIFF | CV_L2) +#define CV_RELATIVE_C (CV_RELATIVE | CV_C) +#define CV_RELATIVE_L1 (CV_RELATIVE | CV_L1) +#define CV_RELATIVE_L2 (CV_RELATIVE | CV_L2) +/** @} */ + +/** Finds norm, difference norm or relative difference norm for an array (or two arrays) +@see ref core_c_NormFlags "flags" +*/ +CVAPI(double) cvNorm( const CvArr* arr1, const CvArr* arr2 CV_DEFAULT(NULL), + int norm_type CV_DEFAULT(CV_L2), + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @see ref core_c_NormFlags "flags" */ +CVAPI(void) cvNormalize( const CvArr* src, CvArr* dst, + double a CV_DEFAULT(1.), double b CV_DEFAULT(0.), + int norm_type CV_DEFAULT(CV_L2), + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @anchor core_c_ReduceFlags + @name Flags for cvReduce + @{ +*/ +#define CV_REDUCE_SUM 0 +#define CV_REDUCE_AVG 1 +#define CV_REDUCE_MAX 2 +#define CV_REDUCE_MIN 3 +/** @} */ + +/** @see @ref core_c_ReduceFlags "flags" */ +CVAPI(void) cvReduce( const CvArr* src, CvArr* dst, int dim CV_DEFAULT(-1), + int op CV_DEFAULT(CV_REDUCE_SUM) ); + +/****************************************************************************************\ +* Discrete Linear Transforms and Related Functions * +\****************************************************************************************/ + +/** @anchor core_c_DftFlags + @name Flags for cvDFT, cvDCT and cvMulSpectrums + @{ + */ +#define CV_DXT_FORWARD 0 +#define CV_DXT_INVERSE 1 +#define CV_DXT_SCALE 2 /**< divide result by size of array */ +#define CV_DXT_INV_SCALE (CV_DXT_INVERSE + CV_DXT_SCALE) +#define CV_DXT_INVERSE_SCALE CV_DXT_INV_SCALE +#define CV_DXT_ROWS 4 /**< transform each row individually */ +#define CV_DXT_MUL_CONJ 8 /**< conjugate the second argument of cvMulSpectrums */ +/** @} */ + +/** Discrete Fourier Transform: + complex->complex, + real->ccs (forward), + ccs->real (inverse) +@see core_c_DftFlags "flags" +*/ +CVAPI(void) cvDFT( const CvArr* src, CvArr* dst, int flags, + int nonzero_rows CV_DEFAULT(0) ); +#define cvFFT cvDFT + +/** Multiply results of DFTs: DFT(X)*DFT(Y) or DFT(X)*conj(DFT(Y)) +@see core_c_DftFlags "flags" +*/ +CVAPI(void) cvMulSpectrums( const CvArr* src1, const CvArr* src2, + CvArr* dst, int flags ); + +/** Finds optimal DFT vector size >= size0 */ +CVAPI(int) cvGetOptimalDFTSize( int size0 ); + +/** Discrete Cosine Transform +@see core_c_DftFlags "flags" +*/ +CVAPI(void) cvDCT( const CvArr* src, CvArr* dst, int flags ); + +/****************************************************************************************\ +* Dynamic data structures * +\****************************************************************************************/ + +/** Calculates length of sequence slice (with support of negative indices). */ +CVAPI(int) cvSliceLength( CvSlice slice, const CvSeq* seq ); + + +/** Creates new memory storage. + block_size == 0 means that default, + somewhat optimal size, is used (currently, it is 64K) */ +CVAPI(CvMemStorage*) cvCreateMemStorage( int block_size CV_DEFAULT(0)); + + +/** Creates a memory storage that will borrow memory blocks from parent storage */ +CVAPI(CvMemStorage*) cvCreateChildMemStorage( CvMemStorage* parent ); + + +/** Releases memory storage. All the children of a parent must be released before + the parent. A child storage returns all the blocks to parent when it is released */ +CVAPI(void) cvReleaseMemStorage( CvMemStorage** storage ); + + +/** Clears memory storage. This is the only way(!!!) (besides cvRestoreMemStoragePos) + to reuse memory allocated for the storage - cvClearSeq,cvClearSet ... + do not free any memory. + A child storage returns all the blocks to the parent when it is cleared */ +CVAPI(void) cvClearMemStorage( CvMemStorage* storage ); + +/** Remember a storage "free memory" position */ +CVAPI(void) cvSaveMemStoragePos( const CvMemStorage* storage, CvMemStoragePos* pos ); + +/** Restore a storage "free memory" position */ +CVAPI(void) cvRestoreMemStoragePos( CvMemStorage* storage, CvMemStoragePos* pos ); + +/** Allocates continuous buffer of the specified size in the storage */ +CVAPI(void*) cvMemStorageAlloc( CvMemStorage* storage, size_t size ); + +/** Allocates string in memory storage */ +//CVAPI(CvString) cvMemStorageAllocString( CvMemStorage* storage, const char* ptr, +// int len CV_DEFAULT(-1) ); + +/** Creates new empty sequence that will reside in the specified storage */ +CVAPI(CvSeq*) cvCreateSeq( int seq_flags, size_t header_size, + size_t elem_size, CvMemStorage* storage ); + +/** Changes default size (granularity) of sequence blocks. + The default size is ~1Kbyte */ +CVAPI(void) cvSetSeqBlockSize( CvSeq* seq, int delta_elems ); + + +/** Adds new element to the end of sequence. Returns pointer to the element */ +CVAPI(schar*) cvSeqPush( CvSeq* seq, const void* element CV_DEFAULT(NULL)); + + +/** Adds new element to the beginning of sequence. Returns pointer to it */ +CVAPI(schar*) cvSeqPushFront( CvSeq* seq, const void* element CV_DEFAULT(NULL)); + + +/** Removes the last element from sequence and optionally saves it */ +CVAPI(void) cvSeqPop( CvSeq* seq, void* element CV_DEFAULT(NULL)); + + +/** Removes the first element from sequence and optioanally saves it */ +CVAPI(void) cvSeqPopFront( CvSeq* seq, void* element CV_DEFAULT(NULL)); + + +#define CV_FRONT 1 +#define CV_BACK 0 +/** Adds several new elements to the end of sequence */ +CVAPI(void) cvSeqPushMulti( CvSeq* seq, const void* elements, + int count, int in_front CV_DEFAULT(0) ); + +/** Removes several elements from the end of sequence and optionally saves them */ +CVAPI(void) cvSeqPopMulti( CvSeq* seq, void* elements, + int count, int in_front CV_DEFAULT(0) ); + +/** Inserts a new element in the middle of sequence. + cvSeqInsert(seq,0,elem) == cvSeqPushFront(seq,elem) */ +CVAPI(schar*) cvSeqInsert( CvSeq* seq, int before_index, + const void* element CV_DEFAULT(NULL)); + +/** Removes specified sequence element */ +CVAPI(void) cvSeqRemove( CvSeq* seq, int index ); + + +/** Removes all the elements from the sequence. The freed memory + can be reused later only by the same sequence unless cvClearMemStorage + or cvRestoreMemStoragePos is called */ +CVAPI(void) cvClearSeq( CvSeq* seq ); + + +/** Retrieves pointer to specified sequence element. + Negative indices are supported and mean counting from the end + (e.g -1 means the last sequence element) */ +CVAPI(schar*) cvGetSeqElem( const CvSeq* seq, int index ); + +/** Calculates index of the specified sequence element. + Returns -1 if element does not belong to the sequence */ +CVAPI(int) cvSeqElemIdx( const CvSeq* seq, const void* element, + CvSeqBlock** block CV_DEFAULT(NULL) ); + +/** Initializes sequence writer. The new elements will be added to the end of sequence */ +CVAPI(void) cvStartAppendToSeq( CvSeq* seq, CvSeqWriter* writer ); + + +/** Combination of cvCreateSeq and cvStartAppendToSeq */ +CVAPI(void) cvStartWriteSeq( int seq_flags, int header_size, + int elem_size, CvMemStorage* storage, + CvSeqWriter* writer ); + +/** Closes sequence writer, updates sequence header and returns pointer + to the resultant sequence + (which may be useful if the sequence was created using cvStartWriteSeq)) +*/ +CVAPI(CvSeq*) cvEndWriteSeq( CvSeqWriter* writer ); + + +/** Updates sequence header. May be useful to get access to some of previously + written elements via cvGetSeqElem or sequence reader */ +CVAPI(void) cvFlushSeqWriter( CvSeqWriter* writer ); + + +/** Initializes sequence reader. + The sequence can be read in forward or backward direction */ +CVAPI(void) cvStartReadSeq( const CvSeq* seq, CvSeqReader* reader, + int reverse CV_DEFAULT(0) ); + + +/** Returns current sequence reader position (currently observed sequence element) */ +CVAPI(int) cvGetSeqReaderPos( CvSeqReader* reader ); + + +/** Changes sequence reader position. It may seek to an absolute or + to relative to the current position */ +CVAPI(void) cvSetSeqReaderPos( CvSeqReader* reader, int index, + int is_relative CV_DEFAULT(0)); + +/** Copies sequence content to a continuous piece of memory */ +CVAPI(void*) cvCvtSeqToArray( const CvSeq* seq, void* elements, + CvSlice slice CV_DEFAULT(CV_WHOLE_SEQ) ); + +/** Creates sequence header for array. + After that all the operations on sequences that do not alter the content + can be applied to the resultant sequence */ +CVAPI(CvSeq*) cvMakeSeqHeaderForArray( int seq_type, int header_size, + int elem_size, void* elements, int total, + CvSeq* seq, CvSeqBlock* block ); + +/** Extracts sequence slice (with or without copying sequence elements) */ +CVAPI(CvSeq*) cvSeqSlice( const CvSeq* seq, CvSlice slice, + CvMemStorage* storage CV_DEFAULT(NULL), + int copy_data CV_DEFAULT(0)); + +CV_INLINE CvSeq* cvCloneSeq( const CvSeq* seq, CvMemStorage* storage CV_DEFAULT(NULL)) +{ + return cvSeqSlice( seq, CV_WHOLE_SEQ, storage, 1 ); +} + +/** Removes sequence slice */ +CVAPI(void) cvSeqRemoveSlice( CvSeq* seq, CvSlice slice ); + +/** Inserts a sequence or array into another sequence */ +CVAPI(void) cvSeqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); + +/** a < b ? -1 : a > b ? 1 : 0 */ +typedef int (CV_CDECL* CvCmpFunc)(const void* a, const void* b, void* userdata ); + +/** Sorts sequence in-place given element comparison function */ +CVAPI(void) cvSeqSort( CvSeq* seq, CvCmpFunc func, void* userdata CV_DEFAULT(NULL) ); + +/** Finds element in a [sorted] sequence */ +CVAPI(schar*) cvSeqSearch( CvSeq* seq, const void* elem, CvCmpFunc func, + int is_sorted, int* elem_idx, + void* userdata CV_DEFAULT(NULL) ); + +/** Reverses order of sequence elements in-place */ +CVAPI(void) cvSeqInvert( CvSeq* seq ); + +/** Splits sequence into one or more equivalence classes using the specified criteria */ +CVAPI(int) cvSeqPartition( const CvSeq* seq, CvMemStorage* storage, + CvSeq** labels, CvCmpFunc is_equal, void* userdata ); + +/************ Internal sequence functions ************/ +CVAPI(void) cvChangeSeqBlock( void* reader, int direction ); +CVAPI(void) cvCreateSeqBlock( CvSeqWriter* writer ); + + +/** Creates a new set */ +CVAPI(CvSet*) cvCreateSet( int set_flags, int header_size, + int elem_size, CvMemStorage* storage ); + +/** Adds new element to the set and returns pointer to it */ +CVAPI(int) cvSetAdd( CvSet* set_header, CvSetElem* elem CV_DEFAULT(NULL), + CvSetElem** inserted_elem CV_DEFAULT(NULL) ); + +/** Fast variant of cvSetAdd */ +CV_INLINE CvSetElem* cvSetNew( CvSet* set_header ) +{ + CvSetElem* elem = set_header->free_elems; + if( elem ) + { + set_header->free_elems = elem->next_free; + elem->flags = elem->flags & CV_SET_ELEM_IDX_MASK; + set_header->active_count++; + } + else + cvSetAdd( set_header, NULL, &elem ); + return elem; +} + +/** Removes set element given its pointer */ +CV_INLINE void cvSetRemoveByPtr( CvSet* set_header, void* elem ) +{ + CvSetElem* _elem = (CvSetElem*)elem; + assert( _elem->flags >= 0 /*&& (elem->flags & CV_SET_ELEM_IDX_MASK) < set_header->total*/ ); + _elem->next_free = set_header->free_elems; + _elem->flags = (_elem->flags & CV_SET_ELEM_IDX_MASK) | CV_SET_ELEM_FREE_FLAG; + set_header->free_elems = _elem; + set_header->active_count--; +} + +/** Removes element from the set by its index */ +CVAPI(void) cvSetRemove( CvSet* set_header, int index ); + +/** Returns a set element by index. If the element doesn't belong to the set, + NULL is returned */ +CV_INLINE CvSetElem* cvGetSetElem( const CvSet* set_header, int idx ) +{ + CvSetElem* elem = (CvSetElem*)(void *)cvGetSeqElem( (CvSeq*)set_header, idx ); + return elem && CV_IS_SET_ELEM( elem ) ? elem : 0; +} + +/** Removes all the elements from the set */ +CVAPI(void) cvClearSet( CvSet* set_header ); + +/** Creates new graph */ +CVAPI(CvGraph*) cvCreateGraph( int graph_flags, int header_size, + int vtx_size, int edge_size, + CvMemStorage* storage ); + +/** Adds new vertex to the graph */ +CVAPI(int) cvGraphAddVtx( CvGraph* graph, const CvGraphVtx* vtx CV_DEFAULT(NULL), + CvGraphVtx** inserted_vtx CV_DEFAULT(NULL) ); + + +/** Removes vertex from the graph together with all incident edges */ +CVAPI(int) cvGraphRemoveVtx( CvGraph* graph, int index ); +CVAPI(int) cvGraphRemoveVtxByPtr( CvGraph* graph, CvGraphVtx* vtx ); + + +/** Link two vertices specified by indices or pointers if they + are not connected or return pointer to already existing edge + connecting the vertices. + Functions return 1 if a new edge was created, 0 otherwise */ +CVAPI(int) cvGraphAddEdge( CvGraph* graph, + int start_idx, int end_idx, + const CvGraphEdge* edge CV_DEFAULT(NULL), + CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); + +CVAPI(int) cvGraphAddEdgeByPtr( CvGraph* graph, + CvGraphVtx* start_vtx, CvGraphVtx* end_vtx, + const CvGraphEdge* edge CV_DEFAULT(NULL), + CvGraphEdge** inserted_edge CV_DEFAULT(NULL) ); + +/** Remove edge connecting two vertices */ +CVAPI(void) cvGraphRemoveEdge( CvGraph* graph, int start_idx, int end_idx ); +CVAPI(void) cvGraphRemoveEdgeByPtr( CvGraph* graph, CvGraphVtx* start_vtx, + CvGraphVtx* end_vtx ); + +/** Find edge connecting two vertices */ +CVAPI(CvGraphEdge*) cvFindGraphEdge( const CvGraph* graph, int start_idx, int end_idx ); +CVAPI(CvGraphEdge*) cvFindGraphEdgeByPtr( const CvGraph* graph, + const CvGraphVtx* start_vtx, + const CvGraphVtx* end_vtx ); +#define cvGraphFindEdge cvFindGraphEdge +#define cvGraphFindEdgeByPtr cvFindGraphEdgeByPtr + +/** Remove all vertices and edges from the graph */ +CVAPI(void) cvClearGraph( CvGraph* graph ); + + +/** Count number of edges incident to the vertex */ +CVAPI(int) cvGraphVtxDegree( const CvGraph* graph, int vtx_idx ); +CVAPI(int) cvGraphVtxDegreeByPtr( const CvGraph* graph, const CvGraphVtx* vtx ); + + +/** Retrieves graph vertex by given index */ +#define cvGetGraphVtx( graph, idx ) (CvGraphVtx*)cvGetSetElem((CvSet*)(graph), (idx)) + +/** Retrieves index of a graph vertex given its pointer */ +#define cvGraphVtxIdx( graph, vtx ) ((vtx)->flags & CV_SET_ELEM_IDX_MASK) + +/** Retrieves index of a graph edge given its pointer */ +#define cvGraphEdgeIdx( graph, edge ) ((edge)->flags & CV_SET_ELEM_IDX_MASK) + +#define cvGraphGetVtxCount( graph ) ((graph)->active_count) +#define cvGraphGetEdgeCount( graph ) ((graph)->edges->active_count) + +#define CV_GRAPH_VERTEX 1 +#define CV_GRAPH_TREE_EDGE 2 +#define CV_GRAPH_BACK_EDGE 4 +#define CV_GRAPH_FORWARD_EDGE 8 +#define CV_GRAPH_CROSS_EDGE 16 +#define CV_GRAPH_ANY_EDGE 30 +#define CV_GRAPH_NEW_TREE 32 +#define CV_GRAPH_BACKTRACKING 64 +#define CV_GRAPH_OVER -1 + +#define CV_GRAPH_ALL_ITEMS -1 + +/** flags for graph vertices and edges */ +#define CV_GRAPH_ITEM_VISITED_FLAG (1 << 30) +#define CV_IS_GRAPH_VERTEX_VISITED(vtx) \ + (((CvGraphVtx*)(vtx))->flags & CV_GRAPH_ITEM_VISITED_FLAG) +#define CV_IS_GRAPH_EDGE_VISITED(edge) \ + (((CvGraphEdge*)(edge))->flags & CV_GRAPH_ITEM_VISITED_FLAG) +#define CV_GRAPH_SEARCH_TREE_NODE_FLAG (1 << 29) +#define CV_GRAPH_FORWARD_EDGE_FLAG (1 << 28) + +typedef struct CvGraphScanner +{ + CvGraphVtx* vtx; /* current graph vertex (or current edge origin) */ + CvGraphVtx* dst; /* current graph edge destination vertex */ + CvGraphEdge* edge; /* current edge */ + + CvGraph* graph; /* the graph */ + CvSeq* stack; /* the graph vertex stack */ + int index; /* the lower bound of certainly visited vertices */ + int mask; /* event mask */ +} +CvGraphScanner; + +/** Creates new graph scanner. */ +CVAPI(CvGraphScanner*) cvCreateGraphScanner( CvGraph* graph, + CvGraphVtx* vtx CV_DEFAULT(NULL), + int mask CV_DEFAULT(CV_GRAPH_ALL_ITEMS)); + +/** Releases graph scanner. */ +CVAPI(void) cvReleaseGraphScanner( CvGraphScanner** scanner ); + +/** Get next graph element */ +CVAPI(int) cvNextGraphItem( CvGraphScanner* scanner ); + +/** Creates a copy of graph */ +CVAPI(CvGraph*) cvCloneGraph( const CvGraph* graph, CvMemStorage* storage ); + + +/** Does look-up transformation. Elements of the source array + (that should be 8uC1 or 8sC1) are used as indexes in lutarr 256-element table */ +CVAPI(void) cvLUT( const CvArr* src, CvArr* dst, const CvArr* lut ); + + +/******************* Iteration through the sequence tree *****************/ +typedef struct CvTreeNodeIterator +{ + const void* node; + int level; + int max_level; +} +CvTreeNodeIterator; + +CVAPI(void) cvInitTreeNodeIterator( CvTreeNodeIterator* tree_iterator, + const void* first, int max_level ); +CVAPI(void*) cvNextTreeNode( CvTreeNodeIterator* tree_iterator ); +CVAPI(void*) cvPrevTreeNode( CvTreeNodeIterator* tree_iterator ); + +/** Inserts sequence into tree with specified "parent" sequence. + If parent is equal to frame (e.g. the most external contour), + then added contour will have null pointer to parent. */ +CVAPI(void) cvInsertNodeIntoTree( void* node, void* parent, void* frame ); + +/** Removes contour from tree (together with the contour children). */ +CVAPI(void) cvRemoveNodeFromTree( void* node, void* frame ); + +/** Gathers pointers to all the sequences, + accessible from the `first`, to the single sequence */ +CVAPI(CvSeq*) cvTreeToNodeSeq( const void* first, int header_size, + CvMemStorage* storage ); + +/** The function implements the K-means algorithm for clustering an array of sample + vectors in a specified number of classes */ +#define CV_KMEANS_USE_INITIAL_LABELS 1 +CVAPI(int) cvKMeans2( const CvArr* samples, int cluster_count, CvArr* labels, + CvTermCriteria termcrit, int attempts CV_DEFAULT(1), + CvRNG* rng CV_DEFAULT(0), int flags CV_DEFAULT(0), + CvArr* _centers CV_DEFAULT(0), double* compactness CV_DEFAULT(0) ); + +/****************************************************************************************\ +* System functions * +\****************************************************************************************/ + +/** Loads optimized functions from IPP, MKL etc. or switches back to pure C code */ +CVAPI(int) cvUseOptimized( int on_off ); + +typedef IplImage* (CV_STDCALL* Cv_iplCreateImageHeader) + (int,int,int,char*,char*,int,int,int,int,int, + IplROI*,IplImage*,void*,IplTileInfo*); +typedef void (CV_STDCALL* Cv_iplAllocateImageData)(IplImage*,int,int); +typedef void (CV_STDCALL* Cv_iplDeallocate)(IplImage*,int); +typedef IplROI* (CV_STDCALL* Cv_iplCreateROI)(int,int,int,int,int); +typedef IplImage* (CV_STDCALL* Cv_iplCloneImage)(const IplImage*); + +/** @brief Makes OpenCV use IPL functions for allocating IplImage and IplROI structures. + +Normally, the function is not called directly. Instead, a simple macro +CV_TURN_ON_IPL_COMPATIBILITY() is used that calls cvSetIPLAllocators and passes there pointers +to IPL allocation functions. : +@code + ... + CV_TURN_ON_IPL_COMPATIBILITY() + ... +@endcode +@param create_header pointer to a function, creating IPL image header. +@param allocate_data pointer to a function, allocating IPL image data. +@param deallocate pointer to a function, deallocating IPL image. +@param create_roi pointer to a function, creating IPL image ROI (i.e. Region of Interest). +@param clone_image pointer to a function, cloning an IPL image. + */ +CVAPI(void) cvSetIPLAllocators( Cv_iplCreateImageHeader create_header, + Cv_iplAllocateImageData allocate_data, + Cv_iplDeallocate deallocate, + Cv_iplCreateROI create_roi, + Cv_iplCloneImage clone_image ); + +#define CV_TURN_ON_IPL_COMPATIBILITY() \ + cvSetIPLAllocators( iplCreateImageHeader, iplAllocateImage, \ + iplDeallocate, iplCreateROI, iplCloneImage ) + +/****************************************************************************************\ +* Data Persistence * +\****************************************************************************************/ + +#if 0 +/********************************** High-level functions ********************************/ + +/** @brief Opens file storage for reading or writing data. + +The function opens file storage for reading or writing data. In the latter case, a new file is +created or an existing file is rewritten. The type of the read or written file is determined by the +filename extension: .xml for XML, .yml or .yaml for YAML and .json for JSON. + +At the same time, it also supports adding parameters like "example.xml?base64". + +The function returns a pointer to the CvFileStorage structure. +If the file cannot be opened then the function returns NULL. +@param filename Name of the file associated with the storage +@param memstorage Memory storage used for temporary data and for +: storing dynamic structures, such as CvSeq or CvGraph . If it is NULL, a temporary memory + storage is created and used. +@param flags Can be one of the following: +> - **CV_STORAGE_READ** the storage is open for reading +> - **CV_STORAGE_WRITE** the storage is open for writing + (use **CV_STORAGE_WRITE | CV_STORAGE_WRITE_BASE64** to write rawdata in Base64) +@param encoding + */ +CVAPI(CvFileStorage*) cvOpenFileStorage( const char* filename, CvMemStorage* memstorage, + int flags, const char* encoding CV_DEFAULT(NULL) ); + +/** @brief Releases file storage. + +The function closes the file associated with the storage and releases all the temporary structures. +It must be called after all I/O operations with the storage are finished. +@param fs Double pointer to the released file storage + */ +CVAPI(void) cvReleaseFileStorage( CvFileStorage** fs ); + +/** returns attribute value or 0 (NULL) if there is no such attribute */ +CVAPI(const char*) cvAttrValue( const CvAttrList* attr, const char* attr_name ); + +/** @brief Starts writing a new structure. + +The function starts writing a compound structure (collection) that can be a sequence or a map. After +all the structure fields, which can be scalars or structures, are written, cvEndWriteStruct should +be called. The function can be used to group some objects or to implement the write function for a +some user object (see CvTypeInfo). +@param fs File storage +@param name Name of the written structure. The structure can be accessed by this name when the +storage is read. +@param struct_flags A combination one of the following values: +- **CV_NODE_SEQ** the written structure is a sequence (see discussion of CvFileStorage ), + that is, its elements do not have a name. +- **CV_NODE_MAP** the written structure is a map (see discussion of CvFileStorage ), that + is, all its elements have names. +One and only one of the two above flags must be specified +- **CV_NODE_FLOW** the optional flag that makes sense only for YAML streams. It means that + the structure is written as a flow (not as a block), which is more compact. It is + recommended to use this flag for structures or arrays whose elements are all scalars. +@param type_name Optional parameter - the object type name. In + case of XML it is written as a type_id attribute of the structure opening tag. In the case of + YAML it is written after a colon following the structure name (see the example in + CvFileStorage description). In case of JSON it is written as a name/value pair. + Mainly it is used with user objects. When the storage is read, the + encoded type name is used to determine the object type (see CvTypeInfo and cvFindType ). +@param attributes This parameter is not used in the current implementation + */ +CVAPI(void) cvStartWriteStruct( CvFileStorage* fs, const char* name, + int struct_flags, const char* type_name CV_DEFAULT(NULL), + CvAttrList attributes CV_DEFAULT(cvAttrList())); + +/** @brief Finishes writing to a file node collection. +@param fs File storage +@sa cvStartWriteStruct. + */ +CVAPI(void) cvEndWriteStruct( CvFileStorage* fs ); + +/** @brief Writes an integer value. + +The function writes a single integer value (with or without a name) to the file storage. +@param fs File storage +@param name Name of the written value. Should be NULL if and only if the parent structure is a +sequence. +@param value The written value + */ +CVAPI(void) cvWriteInt( CvFileStorage* fs, const char* name, int value ); + +/** @brief Writes a floating-point value. + +The function writes a single floating-point value (with or without a name) to file storage. Special +values are encoded as follows: NaN (Not A Number) as .NaN, infinity as +.Inf or -.Inf. + +The following example shows how to use the low-level writing functions to store custom structures, +such as termination criteria, without registering a new type. : +@code + void write_termcriteria( CvFileStorage* fs, const char* struct_name, + CvTermCriteria* termcrit ) + { + cvStartWriteStruct( fs, struct_name, CV_NODE_MAP, NULL, cvAttrList(0,0)); + cvWriteComment( fs, "termination criteria", 1 ); // just a description + if( termcrit->type & CV_TERMCRIT_ITER ) + cvWriteInteger( fs, "max_iterations", termcrit->max_iter ); + if( termcrit->type & CV_TERMCRIT_EPS ) + cvWriteReal( fs, "accuracy", termcrit->epsilon ); + cvEndWriteStruct( fs ); + } +@endcode +@param fs File storage +@param name Name of the written value. Should be NULL if and only if the parent structure is a +sequence. +@param value The written value +*/ +CVAPI(void) cvWriteReal( CvFileStorage* fs, const char* name, double value ); + +/** @brief Writes a text string. + +The function writes a text string to file storage. +@param fs File storage +@param name Name of the written string . Should be NULL if and only if the parent structure is a +sequence. +@param str The written text string +@param quote If non-zero, the written string is put in quotes, regardless of whether they are +required. Otherwise, if the flag is zero, quotes are used only when they are required (e.g. when +the string starts with a digit or contains spaces). + */ +CVAPI(void) cvWriteString( CvFileStorage* fs, const char* name, + const char* str, int quote CV_DEFAULT(0) ); + +/** @brief Writes a comment. + +The function writes a comment into file storage. The comments are skipped when the storage is read. +@param fs File storage +@param comment The written comment, single-line or multi-line +@param eol_comment If non-zero, the function tries to put the comment at the end of current line. +If the flag is zero, if the comment is multi-line, or if it does not fit at the end of the current +line, the comment starts a new line. + */ +CVAPI(void) cvWriteComment( CvFileStorage* fs, const char* comment, + int eol_comment ); + +/** @brief Writes an object to file storage. + +The function writes an object to file storage. First, the appropriate type info is found using +cvTypeOf. Then, the write method associated with the type info is called. + +Attributes are used to customize the writing procedure. The standard types support the following +attributes (all the dt attributes have the same format as in cvWriteRawData): + +-# CvSeq + - **header_dt** description of user fields of the sequence header that follow CvSeq, or + CvChain (if the sequence is a Freeman chain) or CvContour (if the sequence is a contour or + point sequence) + - **dt** description of the sequence elements. + - **recursive** if the attribute is present and is not equal to "0" or "false", the whole + tree of sequences (contours) is stored. +-# CvGraph + - **header_dt** description of user fields of the graph header that follows CvGraph; + - **vertex_dt** description of user fields of graph vertices + - **edge_dt** description of user fields of graph edges (note that the edge weight is + always written, so there is no need to specify it explicitly) + +Below is the code that creates the YAML file shown in the CvFileStorage description: +@code + #include "cxcore.h" + + int main( int argc, char** argv ) + { + CvMat* mat = cvCreateMat( 3, 3, CV_32F ); + CvFileStorage* fs = cvOpenFileStorage( "example.yml", 0, CV_STORAGE_WRITE ); + + cvSetIdentity( mat ); + cvWrite( fs, "A", mat, cvAttrList(0,0) ); + + cvReleaseFileStorage( &fs ); + cvReleaseMat( &mat ); + return 0; + } +@endcode +@param fs File storage +@param name Name of the written object. Should be NULL if and only if the parent structure is a +sequence. +@param ptr Pointer to the object +@param attributes The attributes of the object. They are specific for each particular type (see +the discussion below). + */ +CVAPI(void) cvWrite( CvFileStorage* fs, const char* name, const void* ptr, + CvAttrList attributes CV_DEFAULT(cvAttrList())); + +/** @brief Starts the next stream. + +The function finishes the currently written stream and starts the next stream. In the case of XML +the file with multiple streams looks like this: +@code{.xml} + + + + + + + ... +@endcode +The YAML file will look like this: +@code{.yaml} + %YAML 1.0 + # stream #1 data + ... + --- + # stream #2 data +@endcode +This is useful for concatenating files or for resuming the writing process. +@param fs File storage + */ +CVAPI(void) cvStartNextStream( CvFileStorage* fs ); + +/** @brief Writes multiple numbers. + +The function writes an array, whose elements consist of single or multiple numbers. The function +call can be replaced with a loop containing a few cvWriteInt and cvWriteReal calls, but a single +call is more efficient. Note that because none of the elements have a name, they should be written +to a sequence rather than a map. +@param fs File storage +@param src Pointer to the written array +@param len Number of the array elements to write +@param dt Specification of each array element, see @ref format_spec "format specification" + */ +CVAPI(void) cvWriteRawData( CvFileStorage* fs, const void* src, + int len, const char* dt ); + +/** @brief Writes multiple numbers in Base64. + +If either CV_STORAGE_WRITE_BASE64 or cv::FileStorage::WRITE_BASE64 is used, +this function will be the same as cvWriteRawData. If neither, the main +difference is that it outputs a sequence in Base64 encoding rather than +in plain text. + +This function can only be used to write a sequence with a type "binary". + +@param fs File storage +@param src Pointer to the written array +@param len Number of the array elements to write +@param dt Specification of each array element, see @ref format_spec "format specification" +*/ +CVAPI(void) cvWriteRawDataBase64( CvFileStorage* fs, const void* src, + int len, const char* dt ); + +/** @brief Returns a unique pointer for a given name. + +The function returns a unique pointer for each particular file node name. This pointer can be then +passed to the cvGetFileNode function that is faster than cvGetFileNodeByName because it compares +text strings by comparing pointers rather than the strings' content. + +Consider the following example where an array of points is encoded as a sequence of 2-entry maps: +@code + points: + - { x: 10, y: 10 } + - { x: 20, y: 20 } + - { x: 30, y: 30 } + # ... +@endcode +Then, it is possible to get hashed "x" and "y" pointers to speed up decoding of the points. : +@code + #include "cxcore.h" + + int main( int argc, char** argv ) + { + CvFileStorage* fs = cvOpenFileStorage( "points.yml", 0, CV_STORAGE_READ ); + CvStringHashNode* x_key = cvGetHashedNode( fs, "x", -1, 1 ); + CvStringHashNode* y_key = cvGetHashedNode( fs, "y", -1, 1 ); + CvFileNode* points = cvGetFileNodeByName( fs, 0, "points" ); + + if( CV_NODE_IS_SEQ(points->tag) ) + { + CvSeq* seq = points->data.seq; + int i, total = seq->total; + CvSeqReader reader; + cvStartReadSeq( seq, &reader, 0 ); + for( i = 0; i < total; i++ ) + { + CvFileNode* pt = (CvFileNode*)reader.ptr; + #if 1 // faster variant + CvFileNode* xnode = cvGetFileNode( fs, pt, x_key, 0 ); + CvFileNode* ynode = cvGetFileNode( fs, pt, y_key, 0 ); + assert( xnode && CV_NODE_IS_INT(xnode->tag) && + ynode && CV_NODE_IS_INT(ynode->tag)); + int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); + int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); + #elif 1 // slower variant; does not use x_key & y_key + CvFileNode* xnode = cvGetFileNodeByName( fs, pt, "x" ); + CvFileNode* ynode = cvGetFileNodeByName( fs, pt, "y" ); + assert( xnode && CV_NODE_IS_INT(xnode->tag) && + ynode && CV_NODE_IS_INT(ynode->tag)); + int x = xnode->data.i; // or x = cvReadInt( xnode, 0 ); + int y = ynode->data.i; // or y = cvReadInt( ynode, 0 ); + #else // the slowest yet the easiest to use variant + int x = cvReadIntByName( fs, pt, "x", 0 ); + int y = cvReadIntByName( fs, pt, "y", 0 ); + #endif + CV_NEXT_SEQ_ELEM( seq->elem_size, reader ); + printf(" + } + } + cvReleaseFileStorage( &fs ); + return 0; + } +@endcode +Please note that whatever method of accessing a map you are using, it is still much slower than +using plain sequences; for example, in the above example, it is more efficient to encode the points +as pairs of integers in a single numeric sequence. +@param fs File storage +@param name Literal node name +@param len Length of the name (if it is known apriori), or -1 if it needs to be calculated +@param create_missing Flag that specifies, whether an absent key should be added into the hash table +*/ +CVAPI(CvStringHashNode*) cvGetHashedKey( CvFileStorage* fs, const char* name, + int len CV_DEFAULT(-1), + int create_missing CV_DEFAULT(0)); + +/** @brief Retrieves one of the top-level nodes of the file storage. + +The function returns one of the top-level file nodes. The top-level nodes do not have a name, they +correspond to the streams that are stored one after another in the file storage. If the index is out +of range, the function returns a NULL pointer, so all the top-level nodes can be iterated by +subsequent calls to the function with stream_index=0,1,..., until the NULL pointer is returned. +This function can be used as a base for recursive traversal of the file storage. +@param fs File storage +@param stream_index Zero-based index of the stream. See cvStartNextStream . In most cases, +there is only one stream in the file; however, there can be several. + */ +CVAPI(CvFileNode*) cvGetRootFileNode( const CvFileStorage* fs, + int stream_index CV_DEFAULT(0) ); + +/** @brief Finds a node in a map or file storage. + +The function finds a file node. It is a faster version of cvGetFileNodeByName (see +cvGetHashedKey discussion). Also, the function can insert a new node, if it is not in the map yet. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. If both map and +key are NULLs, the function returns the root file node - a map that contains top-level nodes. +@param key Unique pointer to the node name, retrieved with cvGetHashedKey +@param create_missing Flag that specifies whether an absent node should be added to the map + */ +CVAPI(CvFileNode*) cvGetFileNode( CvFileStorage* fs, CvFileNode* map, + const CvStringHashNode* key, + int create_missing CV_DEFAULT(0) ); + +/** @brief Finds a node in a map or file storage. + +The function finds a file node by name. The node is searched either in map or, if the pointer is +NULL, among the top-level file storage nodes. Using this function for maps and cvGetSeqElem (or +sequence reader) for sequences, it is possible to navigate through the file storage. To speed up +multiple queries for a certain key (e.g., in the case of an array of structures) one may use a +combination of cvGetHashedKey and cvGetFileNode. +@param fs File storage +@param map The parent map. If it is NULL, the function searches in all the top-level nodes +(streams), starting with the first one. +@param name The file node name + */ +CVAPI(CvFileNode*) cvGetFileNodeByName( const CvFileStorage* fs, + const CvFileNode* map, + const char* name ); + +/** @brief Retrieves an integer value from a file node. + +The function returns an integer that is represented by the file node. If the file node is NULL, the +default_value is returned (thus, it is convenient to call the function right after cvGetFileNode +without checking for a NULL pointer). If the file node has type CV_NODE_INT, then node-\>data.i is +returned. If the file node has type CV_NODE_REAL, then node-\>data.f is converted to an integer +and returned. Otherwise the error is reported. +@param node File node +@param default_value The value that is returned if node is NULL + */ +CV_INLINE int cvReadInt( const CvFileNode* node, int default_value CV_DEFAULT(0) ) +{ + return !node ? default_value : + CV_NODE_IS_INT(node->tag) ? node->data.i : + CV_NODE_IS_REAL(node->tag) ? cvRound(node->data.f) : 0x7fffffff; +} + +/** @brief Finds a file node and returns its value. + +The function is a simple superposition of cvGetFileNodeByName and cvReadInt. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ +CV_INLINE int cvReadIntByName( const CvFileStorage* fs, const CvFileNode* map, + const char* name, int default_value CV_DEFAULT(0) ) +{ + return cvReadInt( cvGetFileNodeByName( fs, map, name ), default_value ); +} + +/** @brief Retrieves a floating-point value from a file node. + +The function returns a floating-point value that is represented by the file node. If the file node +is NULL, the default_value is returned (thus, it is convenient to call the function right after +cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_REAL , +then node-\>data.f is returned. If the file node has type CV_NODE_INT , then node-:math:\>data.f +is converted to floating-point and returned. Otherwise the result is not determined. +@param node File node +@param default_value The value that is returned if node is NULL + */ +CV_INLINE double cvReadReal( const CvFileNode* node, double default_value CV_DEFAULT(0.) ) +{ + return !node ? default_value : + CV_NODE_IS_INT(node->tag) ? (double)node->data.i : + CV_NODE_IS_REAL(node->tag) ? node->data.f : 1e300; +} + +/** @brief Finds a file node and returns its value. + +The function is a simple superposition of cvGetFileNodeByName and cvReadReal . +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ +CV_INLINE double cvReadRealByName( const CvFileStorage* fs, const CvFileNode* map, + const char* name, double default_value CV_DEFAULT(0.) ) +{ + return cvReadReal( cvGetFileNodeByName( fs, map, name ), default_value ); +} + +/** @brief Retrieves a text string from a file node. + +The function returns a text string that is represented by the file node. If the file node is NULL, +the default_value is returned (thus, it is convenient to call the function right after +cvGetFileNode without checking for a NULL pointer). If the file node has type CV_NODE_STR , then +node-:math:\>data.str.ptr is returned. Otherwise the result is not determined. +@param node File node +@param default_value The value that is returned if node is NULL + */ +CV_INLINE const char* cvReadString( const CvFileNode* node, + const char* default_value CV_DEFAULT(NULL) ) +{ + return !node ? default_value : CV_NODE_IS_STRING(node->tag) ? node->data.str.ptr : 0; +} + +/** @brief Finds a file node by its name and returns its value. + +The function is a simple superposition of cvGetFileNodeByName and cvReadString . +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param default_value The value that is returned if the file node is not found + */ +CV_INLINE const char* cvReadStringByName( const CvFileStorage* fs, const CvFileNode* map, + const char* name, const char* default_value CV_DEFAULT(NULL) ) +{ + return cvReadString( cvGetFileNodeByName( fs, map, name ), default_value ); +} + + +/** @brief Decodes an object and returns a pointer to it. + +The function decodes a user object (creates an object in a native representation from the file +storage subtree) and returns it. The object to be decoded must be an instance of a registered type +that supports the read method (see CvTypeInfo). The type of the object is determined by the type +name that is encoded in the file. If the object is a dynamic structure, it is created either in +memory storage and passed to cvOpenFileStorage or, if a NULL pointer was passed, in temporary +memory storage, which is released when cvReleaseFileStorage is called. Otherwise, if the object is +not a dynamic structure, it is created in a heap and should be released with a specialized function +or by using the generic cvRelease. +@param fs File storage +@param node The root object node +@param attributes Unused parameter + */ +CVAPI(void*) cvRead( CvFileStorage* fs, CvFileNode* node, + CvAttrList* attributes CV_DEFAULT(NULL)); + +/** @brief Finds an object by name and decodes it. + +The function is a simple superposition of cvGetFileNodeByName and cvRead. +@param fs File storage +@param map The parent map. If it is NULL, the function searches a top-level node. +@param name The node name +@param attributes Unused parameter + */ +CV_INLINE void* cvReadByName( CvFileStorage* fs, const CvFileNode* map, + const char* name, CvAttrList* attributes CV_DEFAULT(NULL) ) +{ + return cvRead( fs, cvGetFileNodeByName( fs, map, name ), attributes ); +} + + +/** @brief Initializes the file node sequence reader. + +The function initializes the sequence reader to read data from a file node. The initialized reader +can be then passed to cvReadRawDataSlice. +@param fs File storage +@param src The file node (a sequence) to read numbers from +@param reader Pointer to the sequence reader + */ +CVAPI(void) cvStartReadRawData( const CvFileStorage* fs, const CvFileNode* src, + CvSeqReader* reader ); + +/** @brief Initializes file node sequence reader. + +The function reads one or more elements from the file node, representing a sequence, to a +user-specified array. The total number of read sequence elements is a product of total and the +number of components in each array element. For example, if dt=2if, the function will read total\*3 +sequence elements. As with any sequence, some parts of the file node sequence can be skipped or read +repeatedly by repositioning the reader using cvSetSeqReaderPos. +@param fs File storage +@param reader The sequence reader. Initialize it with cvStartReadRawData . +@param count The number of elements to read +@param dst Pointer to the destination array +@param dt Specification of each array element. It has the same format as in cvWriteRawData . + */ +CVAPI(void) cvReadRawDataSlice( const CvFileStorage* fs, CvSeqReader* reader, + int count, void* dst, const char* dt ); + +/** @brief Reads multiple numbers. + +The function reads elements from a file node that represents a sequence of scalars. +@param fs File storage +@param src The file node (a sequence) to read numbers from +@param dst Pointer to the destination array +@param dt Specification of each array element. It has the same format as in cvWriteRawData . + */ +CVAPI(void) cvReadRawData( const CvFileStorage* fs, const CvFileNode* src, + void* dst, const char* dt ); + +/** @brief Writes a file node to another file storage. + +The function writes a copy of a file node to file storage. Possible applications of the function are +merging several file storages into one and conversion between XML, YAML and JSON formats. +@param fs Destination file storage +@param new_node_name New name of the file node in the destination file storage. To keep the +existing name, use cvcvGetFileNodeName +@param node The written node +@param embed If the written node is a collection and this parameter is not zero, no extra level of +hierarchy is created. Instead, all the elements of node are written into the currently written +structure. Of course, map elements can only be embedded into another map, and sequence elements +can only be embedded into another sequence. + */ +CVAPI(void) cvWriteFileNode( CvFileStorage* fs, const char* new_node_name, + const CvFileNode* node, int embed ); + +/** @brief Returns the name of a file node. + +The function returns the name of a file node or NULL, if the file node does not have a name or if +node is NULL. +@param node File node + */ +CVAPI(const char*) cvGetFileNodeName( const CvFileNode* node ); + +/*********************************** Adding own types ***********************************/ + +/** @brief Registers a new type. + +The function registers a new type, which is described by info . The function creates a copy of the +structure, so the user should delete it after calling the function. +@param info Type info structure + */ +CVAPI(void) cvRegisterType( const CvTypeInfo* info ); + +/** @brief Unregisters the type. + +The function unregisters a type with a specified name. If the name is unknown, it is possible to +locate the type info by an instance of the type using cvTypeOf or by iterating the type list, +starting from cvFirstType, and then calling cvUnregisterType(info-\>typeName). +@param type_name Name of an unregistered type + */ +CVAPI(void) cvUnregisterType( const char* type_name ); + +/** @brief Returns the beginning of a type list. + +The function returns the first type in the list of registered types. Navigation through the list can +be done via the prev and next fields of the CvTypeInfo structure. + */ +CVAPI(CvTypeInfo*) cvFirstType(void); + +/** @brief Finds a type by its name. + +The function finds a registered type by its name. It returns NULL if there is no type with the +specified name. +@param type_name Type name + */ +CVAPI(CvTypeInfo*) cvFindType( const char* type_name ); + +/** @brief Returns the type of an object. + +The function finds the type of a given object. It iterates through the list of registered types and +calls the is_instance function/method for every type info structure with that object until one of +them returns non-zero or until the whole list has been traversed. In the latter case, the function +returns NULL. +@param struct_ptr The object pointer + */ +CVAPI(CvTypeInfo*) cvTypeOf( const void* struct_ptr ); + +#endif + +/** @brief Releases an object. + + The function finds the type of a given object and calls release with the double pointer. + @param struct_ptr Double pointer to the object + */ +CVAPI(void) cvRelease( void** struct_ptr ); + +/** @brief Makes a clone of an object. + +The function finds the type of a given object and calls clone with the passed object. Of course, if +you know the object type, for example, struct_ptr is CvMat\*, it is faster to call the specific +function, like cvCloneMat. +@param struct_ptr The object to clone + */ +CVAPI(void*) cvClone( const void* struct_ptr ); + +/*********************************** Measuring Execution Time ***************************/ + +/** helper functions for RNG initialization and accurate time measurement: + uses internal clock counter on x86 */ +CVAPI(int64) cvGetTickCount( void ); +CVAPI(double) cvGetTickFrequency( void ); + +/*********************************** CPU capabilities ***********************************/ + +CVAPI(int) cvCheckHardwareSupport(int feature); + +/*********************************** Multi-Threading ************************************/ + +/** retrieve/set the number of threads used in OpenMP implementations */ +CVAPI(int) cvGetNumThreads( void ); +CVAPI(void) cvSetNumThreads( int threads CV_DEFAULT(0) ); +/** get index of the thread being executed */ +CVAPI(int) cvGetThreadNum( void ); + + +/********************************** Error Handling **************************************/ + +/** Get current OpenCV error status */ +CVAPI(int) cvGetErrStatus( void ); + +/** Sets error status silently */ +CVAPI(void) cvSetErrStatus( int status ); + +#define CV_ErrModeLeaf 0 /* Print error and exit program */ +#define CV_ErrModeParent 1 /* Print error and continue */ +#define CV_ErrModeSilent 2 /* Don't print and continue */ + +/** Retrieves current error processing mode */ +CVAPI(int) cvGetErrMode( void ); + +/** Sets error processing mode, returns previously used mode */ +CVAPI(int) cvSetErrMode( int mode ); + +/** Sets error status and performs some additional actions (displaying message box, + writing message to stderr, terminating application etc.) + depending on the current error mode */ +CVAPI(void) cvError( int status, const char* func_name, + const char* err_msg, const char* file_name, int line ); + +/** Retrieves textual description of the error given its code */ +CVAPI(const char*) cvErrorStr( int status ); + +/** Retrieves detailed information about the last error occurred */ +CVAPI(int) cvGetErrInfo( const char** errcode_desc, const char** description, + const char** filename, int* line ); + +/** Maps IPP error codes to the counterparts from OpenCV */ +CVAPI(int) cvErrorFromIppStatus( int ipp_status ); + +typedef int (CV_CDECL *CvErrorCallback)( int status, const char* func_name, + const char* err_msg, const char* file_name, int line, void* userdata ); + +/** Assigns a new error-handling function */ +CVAPI(CvErrorCallback) cvRedirectError( CvErrorCallback error_handler, + void* userdata CV_DEFAULT(NULL), + void** prev_userdata CV_DEFAULT(NULL) ); + +/** Output nothing */ +CVAPI(int) cvNulDevReport( int status, const char* func_name, const char* err_msg, + const char* file_name, int line, void* userdata ); + +/** Output to console(fprintf(stderr,...)) */ +CVAPI(int) cvStdErrReport( int status, const char* func_name, const char* err_msg, + const char* file_name, int line, void* userdata ); + +/** Output to MessageBox(WIN32) */ +CVAPI(int) cvGuiBoxReport( int status, const char* func_name, const char* err_msg, + const char* file_name, int line, void* userdata ); + +#define OPENCV_ERROR(status,func,context) \ +cvError((status),(func),(context),__FILE__,__LINE__) + +#define OPENCV_ASSERT(expr,func,context) \ +{if (! (expr)) \ +{OPENCV_ERROR(CV_StsInternal,(func),(context));}} + +#define OPENCV_CALL( Func ) \ +{ \ +Func; \ +} + + +/** CV_FUNCNAME macro defines icvFuncName constant which is used by CV_ERROR macro */ +#ifdef CV_NO_FUNC_NAMES +#define CV_FUNCNAME( Name ) +#define cvFuncName "" +#else +#define CV_FUNCNAME( Name ) \ +static char cvFuncName[] = Name +#endif + + +/** + CV_ERROR macro unconditionally raises error with passed code and message. + After raising error, control will be transferred to the exit label. + */ +#define CV_ERROR( Code, Msg ) \ +{ \ + cvError( (Code), cvFuncName, Msg, __FILE__, __LINE__ ); \ + __CV_EXIT__; \ +} + +/** + CV_CHECK macro checks error status after CV (or IPL) + function call. If error detected, control will be transferred to the exit + label. + */ +#define CV_CHECK() \ +{ \ + if( cvGetErrStatus() < 0 ) \ + CV_ERROR( CV_StsBackTrace, "Inner function failed." ); \ +} + + +/** + CV_CALL macro calls CV (or IPL) function, checks error status and + signals a error if the function failed. Useful in "parent node" + error processing mode + */ +#define CV_CALL( Func ) \ +{ \ + Func; \ + CV_CHECK(); \ +} + + +/** Runtime assertion macro */ +#define CV_ASSERT( Condition ) \ +{ \ + if( !(Condition) ) \ + CV_ERROR( CV_StsInternal, "Assertion: " #Condition " failed" ); \ +} + +#define __CV_BEGIN__ { +#define __CV_END__ goto exit; exit: ; } +#define __CV_EXIT__ goto exit + +/** @} core_c */ + +#ifdef __cplusplus +} // extern "C" +#endif + +#ifdef __cplusplus + +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @addtogroup core_c_glue +//! @{ + +/////////////////////////////////////////// glue /////////////////////////////////////////// + +//! converts array (CvMat or IplImage) to cv::Mat +CV_EXPORTS Mat cvarrToMat(const CvArr* arr, bool copyData=false, + bool allowND=true, int coiMode=0, + AutoBuffer* buf=0); + +static inline Mat cvarrToMatND(const CvArr* arr, bool copyData=false, int coiMode=0) +{ + return cvarrToMat(arr, copyData, true, coiMode); +} + + +//! extracts Channel of Interest from CvMat or IplImage and makes cv::Mat out of it. +CV_EXPORTS void extractImageCOI(const CvArr* arr, OutputArray coiimg, int coi=-1); +//! inserts single-channel cv::Mat into a multi-channel CvMat or IplImage +CV_EXPORTS void insertImageCOI(InputArray coiimg, CvArr* arr, int coi=-1); + + + +////// specialized implementations of DefaultDeleter::operator() for classic OpenCV types ////// + +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMat* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(IplImage* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMatND* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvSparseMat* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvMemStorage* obj) const; }; + +////////////// convenient wrappers for operating old-style dynamic structures ////////////// + +template class SeqIterator; + +typedef Ptr MemStorage; + +/*! + Template Sequence Class derived from CvSeq + + The class provides more convenient access to sequence elements, + STL-style operations and iterators. + + \note The class is targeted for simple data types, + i.e. no constructors or destructors + are called for the sequence elements. +*/ +template class Seq +{ +public: + typedef SeqIterator<_Tp> iterator; + typedef SeqIterator<_Tp> const_iterator; + + //! the default constructor + Seq(); + //! the constructor for wrapping CvSeq structure. The real element type in CvSeq should match _Tp. + Seq(const CvSeq* seq); + //! creates the empty sequence that resides in the specified storage + Seq(MemStorage& storage, int headerSize = sizeof(CvSeq)); + //! returns read-write reference to the specified element + _Tp& operator [](int idx); + //! returns read-only reference to the specified element + const _Tp& operator[](int idx) const; + //! returns iterator pointing to the beginning of the sequence + SeqIterator<_Tp> begin() const; + //! returns iterator pointing to the element following the last sequence element + SeqIterator<_Tp> end() const; + //! returns the number of elements in the sequence + size_t size() const; + //! returns the type of sequence elements (CV_8UC1 ... CV_64FC(CV_CN_MAX) ...) + int type() const; + //! returns the depth of sequence elements (CV_8U ... CV_64F) + int depth() const; + //! returns the number of channels in each sequence element + int channels() const; + //! returns the size of each sequence element + size_t elemSize() const; + //! returns index of the specified sequence element + size_t index(const _Tp& elem) const; + //! appends the specified element to the end of the sequence + void push_back(const _Tp& elem); + //! appends the specified element to the front of the sequence + void push_front(const _Tp& elem); + //! appends zero or more elements to the end of the sequence + void push_back(const _Tp* elems, size_t count); + //! appends zero or more elements to the front of the sequence + void push_front(const _Tp* elems, size_t count); + //! inserts the specified element to the specified position + void insert(int idx, const _Tp& elem); + //! inserts zero or more elements to the specified position + void insert(int idx, const _Tp* elems, size_t count); + //! removes element at the specified position + void remove(int idx); + //! removes the specified subsequence + void remove(const Range& r); + + //! returns reference to the first sequence element + _Tp& front(); + //! returns read-only reference to the first sequence element + const _Tp& front() const; + //! returns reference to the last sequence element + _Tp& back(); + //! returns read-only reference to the last sequence element + const _Tp& back() const; + //! returns true iff the sequence contains no elements + bool empty() const; + + //! removes all the elements from the sequence + void clear(); + //! removes the first element from the sequence + void pop_front(); + //! removes the last element from the sequence + void pop_back(); + //! removes zero or more elements from the beginning of the sequence + void pop_front(_Tp* elems, size_t count); + //! removes zero or more elements from the end of the sequence + void pop_back(_Tp* elems, size_t count); + + //! copies the whole sequence or the sequence slice to the specified vector + void copyTo(std::vector<_Tp>& vec, const Range& range=Range::all()) const; + //! returns the vector containing all the sequence elements + operator std::vector<_Tp>() const; + + CvSeq* seq; +}; + + +/*! + STL-style Sequence Iterator inherited from the CvSeqReader structure +*/ +template class SeqIterator : public CvSeqReader +{ +public: + //! the default constructor + SeqIterator(); + //! the constructor setting the iterator to the beginning or to the end of the sequence + SeqIterator(const Seq<_Tp>& seq, bool seekEnd=false); + //! positions the iterator within the sequence + void seek(size_t pos); + //! reports the current iterator position + size_t tell() const; + //! returns reference to the current sequence element + _Tp& operator *(); + //! returns read-only reference to the current sequence element + const _Tp& operator *() const; + //! moves iterator to the next sequence element + SeqIterator& operator ++(); + //! moves iterator to the next sequence element + SeqIterator operator ++(int) const; + //! moves iterator to the previous sequence element + SeqIterator& operator --(); + //! moves iterator to the previous sequence element + SeqIterator operator --(int) const; + + //! moves iterator forward by the specified offset (possibly negative) + SeqIterator& operator +=(int); + //! moves iterator backward by the specified offset (possibly negative) + SeqIterator& operator -=(int); + + // this is index of the current element module seq->total*2 + // (to distinguish between 0 and seq->total) + int index; +}; + + + +// bridge C++ => C Seq API +CV_EXPORTS schar* seqPush( CvSeq* seq, const void* element=0); +CV_EXPORTS schar* seqPushFront( CvSeq* seq, const void* element=0); +CV_EXPORTS void seqPop( CvSeq* seq, void* element=0); +CV_EXPORTS void seqPopFront( CvSeq* seq, void* element=0); +CV_EXPORTS void seqPopMulti( CvSeq* seq, void* elements, + int count, int in_front=0 ); +CV_EXPORTS void seqRemove( CvSeq* seq, int index ); +CV_EXPORTS void clearSeq( CvSeq* seq ); +CV_EXPORTS schar* getSeqElem( const CvSeq* seq, int index ); +CV_EXPORTS void seqRemoveSlice( CvSeq* seq, CvSlice slice ); +CV_EXPORTS void seqInsertSlice( CvSeq* seq, int before_index, const CvArr* from_arr ); + +template inline Seq<_Tp>::Seq() : seq(0) {} +template inline Seq<_Tp>::Seq( const CvSeq* _seq ) : seq((CvSeq*)_seq) +{ + CV_Assert(!_seq || _seq->elem_size == sizeof(_Tp)); +} + +template inline Seq<_Tp>::Seq( MemStorage& storage, + int headerSize ) +{ + CV_Assert(headerSize >= (int)sizeof(CvSeq)); + seq = cvCreateSeq(DataType<_Tp>::type, headerSize, sizeof(_Tp), storage); +} + +template inline _Tp& Seq<_Tp>::operator [](int idx) +{ return *(_Tp*)getSeqElem(seq, idx); } + +template inline const _Tp& Seq<_Tp>::operator [](int idx) const +{ return *(_Tp*)getSeqElem(seq, idx); } + +template inline SeqIterator<_Tp> Seq<_Tp>::begin() const +{ return SeqIterator<_Tp>(*this); } + +template inline SeqIterator<_Tp> Seq<_Tp>::end() const +{ return SeqIterator<_Tp>(*this, true); } + +template inline size_t Seq<_Tp>::size() const +{ return seq ? seq->total : 0; } + +template inline int Seq<_Tp>::type() const +{ return seq ? CV_MAT_TYPE(seq->flags) : 0; } + +template inline int Seq<_Tp>::depth() const +{ return seq ? CV_MAT_DEPTH(seq->flags) : 0; } + +template inline int Seq<_Tp>::channels() const +{ return seq ? CV_MAT_CN(seq->flags) : 0; } + +template inline size_t Seq<_Tp>::elemSize() const +{ return seq ? seq->elem_size : 0; } + +template inline size_t Seq<_Tp>::index(const _Tp& elem) const +{ return cvSeqElemIdx(seq, &elem); } + +template inline void Seq<_Tp>::push_back(const _Tp& elem) +{ cvSeqPush(seq, &elem); } + +template inline void Seq<_Tp>::push_front(const _Tp& elem) +{ cvSeqPushFront(seq, &elem); } + +template inline void Seq<_Tp>::push_back(const _Tp* elem, size_t count) +{ cvSeqPushMulti(seq, elem, (int)count, 0); } + +template inline void Seq<_Tp>::push_front(const _Tp* elem, size_t count) +{ cvSeqPushMulti(seq, elem, (int)count, 1); } + +template inline _Tp& Seq<_Tp>::back() +{ return *(_Tp*)getSeqElem(seq, -1); } + +template inline const _Tp& Seq<_Tp>::back() const +{ return *(const _Tp*)getSeqElem(seq, -1); } + +template inline _Tp& Seq<_Tp>::front() +{ return *(_Tp*)getSeqElem(seq, 0); } + +template inline const _Tp& Seq<_Tp>::front() const +{ return *(const _Tp*)getSeqElem(seq, 0); } + +template inline bool Seq<_Tp>::empty() const +{ return !seq || seq->total == 0; } + +template inline void Seq<_Tp>::clear() +{ if(seq) clearSeq(seq); } + +template inline void Seq<_Tp>::pop_back() +{ seqPop(seq); } + +template inline void Seq<_Tp>::pop_front() +{ seqPopFront(seq); } + +template inline void Seq<_Tp>::pop_back(_Tp* elem, size_t count) +{ seqPopMulti(seq, elem, (int)count, 0); } + +template inline void Seq<_Tp>::pop_front(_Tp* elem, size_t count) +{ seqPopMulti(seq, elem, (int)count, 1); } + +template inline void Seq<_Tp>::insert(int idx, const _Tp& elem) +{ seqInsert(seq, idx, &elem); } + +template inline void Seq<_Tp>::insert(int idx, const _Tp* elems, size_t count) +{ + CvMat m = cvMat(1, count, DataType<_Tp>::type, elems); + seqInsertSlice(seq, idx, &m); +} + +template inline void Seq<_Tp>::remove(int idx) +{ seqRemove(seq, idx); } + +template inline void Seq<_Tp>::remove(const Range& r) +{ seqRemoveSlice(seq, cvSlice(r.start, r.end)); } + +template inline void Seq<_Tp>::copyTo(std::vector<_Tp>& vec, const Range& range) const +{ + size_t len = !seq ? 0 : range == Range::all() ? seq->total : range.end - range.start; + vec.resize(len); + if( seq && len ) + cvCvtSeqToArray(seq, &vec[0], cvSlice(range)); +} + +template inline Seq<_Tp>::operator std::vector<_Tp>() const +{ + std::vector<_Tp> vec; + copyTo(vec); + return vec; +} + +template inline SeqIterator<_Tp>::SeqIterator() +{ memset(this, 0, sizeof(*this)); } + +template inline SeqIterator<_Tp>::SeqIterator(const Seq<_Tp>& _seq, bool seekEnd) +{ + cvStartReadSeq(_seq.seq, this); + index = seekEnd ? _seq.seq->total : 0; +} + +template inline void SeqIterator<_Tp>::seek(size_t pos) +{ + cvSetSeqReaderPos(this, (int)pos, false); + index = pos; +} + +template inline size_t SeqIterator<_Tp>::tell() const +{ return index; } + +template inline _Tp& SeqIterator<_Tp>::operator *() +{ return *(_Tp*)ptr; } + +template inline const _Tp& SeqIterator<_Tp>::operator *() const +{ return *(const _Tp*)ptr; } + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator ++() +{ + CV_NEXT_SEQ_ELEM(sizeof(_Tp), *this); + if( ++index >= seq->total*2 ) + index = 0; + return *this; +} + +template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator ++(int) const +{ + SeqIterator<_Tp> it = *this; + ++*this; + return it; +} + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator --() +{ + CV_PREV_SEQ_ELEM(sizeof(_Tp), *this); + if( --index < 0 ) + index = seq->total*2-1; + return *this; +} + +template inline SeqIterator<_Tp> SeqIterator<_Tp>::operator --(int) const +{ + SeqIterator<_Tp> it = *this; + --*this; + return it; +} + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator +=(int delta) +{ + cvSetSeqReaderPos(this, delta, 1); + index += delta; + int n = seq->total*2; + if( index < 0 ) + index += n; + if( index >= n ) + index -= n; + return *this; +} + +template inline SeqIterator<_Tp>& SeqIterator<_Tp>::operator -=(int delta) +{ + return (*this += -delta); +} + +template inline ptrdiff_t operator - (const SeqIterator<_Tp>& a, + const SeqIterator<_Tp>& b) +{ + ptrdiff_t delta = a.index - b.index, n = a.seq->total; + if( delta > n || delta < -n ) + delta += delta < 0 ? n : -n; + return delta; +} + +template inline bool operator == (const SeqIterator<_Tp>& a, + const SeqIterator<_Tp>& b) +{ + return a.seq == b.seq && a.index == b.index; +} + +template inline bool operator != (const SeqIterator<_Tp>& a, + const SeqIterator<_Tp>& b) +{ + return !(a == b); +} + +//! @} + +} // cv + +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp index 53898171f2..8191c00783 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda.hpp @@ -1,1339 +1,1339 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CUDA_HPP -#define OPENCV_CORE_CUDA_HPP - -#ifndef __cplusplus -# error cuda.hpp header must be compiled as C++ -#endif - -#include "opencv2/core.hpp" -#include "opencv2/core/cuda_types.hpp" - -/** - @defgroup cuda CUDA-accelerated Computer Vision - @{ - @defgroup cudacore Core part - @{ - @defgroup cudacore_init Initialization and Information - @defgroup cudacore_struct Data Structures - @} - @} - */ - -namespace cv { namespace cuda { - -//! @addtogroup cudacore_struct -//! @{ - -//=================================================================================== -// GpuMat -//=================================================================================== - -/** @brief Base storage class for GPU memory with reference counting. - -Its interface matches the Mat interface with the following limitations: - -- no arbitrary dimensions support (only 2D) -- no functions that return references to their data (because references on GPU are not valid for - CPU) -- no expression templates technique support - -Beware that the latter limitation may lead to overloaded matrix operators that cause memory -allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be -passed directly to the kernel. - -@note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are -aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix. - -@note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely -on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory -release function returns error if the CUDA context has been destroyed before. - -Some member functions are described as a "Blocking Call" while some are described as a -"Non-Blocking Call". Blocking functions are synchronous to host. It is guaranteed that the GPU -operation is finished when the function returns. However, non-blocking functions are asynchronous to -host. Those functions may return even if the GPU operation is not finished. - -Compared to their blocking counterpart, non-blocking functions accept Stream as an additional -argument. If a non-default stream is passed, the GPU operation may overlap with operations in other -streams. - -@sa Mat - */ -class CV_EXPORTS_W GpuMat -{ -public: - class CV_EXPORTS_W Allocator - { - public: - virtual ~Allocator() {} - - // allocator must fill data, step and refcount fields - virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0; - virtual void free(GpuMat* mat) = 0; - }; - - //! default allocator - CV_WRAP static GpuMat::Allocator* defaultAllocator(); - CV_WRAP static void setDefaultAllocator(GpuMat::Allocator* allocator); - CV_WRAP static GpuMat::Allocator* getStdAllocator(); - - //! default constructor - CV_WRAP explicit GpuMat(GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! constructs GpuMat of the specified size and type - CV_WRAP GpuMat(int rows, int cols, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - CV_WRAP GpuMat(Size size, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! constructs GpuMat and fills it with the specified value _s - CV_WRAP GpuMat(int rows, int cols, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - CV_WRAP GpuMat(Size size, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! copy constructor - CV_WRAP GpuMat(const GpuMat& m); - - //! constructor for GpuMat headers pointing to user-allocated data - GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); - GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); - - //! creates a GpuMat header for a part of the bigger matrix - CV_WRAP GpuMat(const GpuMat& m, Range rowRange, Range colRange); - CV_WRAP GpuMat(const GpuMat& m, Rect roi); - - //! builds GpuMat from host memory (Blocking call) - CV_WRAP explicit GpuMat(InputArray arr, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); - - //! destructor - calls release() - ~GpuMat(); - - //! assignment operators - GpuMat& operator =(const GpuMat& m); - - //! allocates new GpuMat data unless the GpuMat already has specified size and type - CV_WRAP void create(int rows, int cols, int type); - CV_WRAP void create(Size size, int type); - - //! decreases reference counter, deallocate the data when reference counter reaches 0 - CV_WRAP void release(); - - //! swaps with other smart pointer - CV_WRAP void swap(GpuMat& mat); - - /** @brief Performs data upload to GpuMat (Blocking call) - - This function copies data from host memory to device memory. As being a blocking call, it is - guaranteed that the copy operation is finished when this function returns. - */ - CV_WRAP void upload(InputArray arr); - - /** @brief Performs data upload to GpuMat (Non-Blocking call) - - This function copies data from host memory to device memory. As being a non-blocking call, this - function may return even if the copy operation is not finished. - - The copy operation may be overlapped with operations in other non-default streams if \p stream is - not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. - */ - CV_WRAP void upload(InputArray arr, Stream& stream); - - /** @brief Performs data download from GpuMat (Blocking call) - - This function copies data from device memory to host memory. As being a blocking call, it is - guaranteed that the copy operation is finished when this function returns. - */ - CV_WRAP void download(OutputArray dst) const; - - /** @brief Performs data download from GpuMat (Non-Blocking call) - - This function copies data from device memory to host memory. As being a non-blocking call, this - function may return even if the copy operation is not finished. - - The copy operation may be overlapped with operations in other non-default streams if \p stream is - not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. - */ - CV_WRAP void download(OutputArray dst, Stream& stream) const; - - //! returns deep copy of the GpuMat, i.e. the data is copied - CV_WRAP GpuMat clone() const; - - //! copies the GpuMat content to device memory (Blocking call) - void copyTo(OutputArray dst) const; - //! bindings overload which copies the GpuMat content to device memory (Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst) const { - copyTo(static_cast(dst)); - } - - //! copies the GpuMat content to device memory (Non-Blocking call) - void copyTo(OutputArray dst, Stream& stream) const; - //! bindings overload which copies the GpuMat content to device memory (Non-Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst, Stream& stream) const { - copyTo(static_cast(dst), stream); - } - - //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) - void copyTo(OutputArray dst, InputArray mask) const; - //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask) const { - copyTo(static_cast(dst), static_cast(mask)); - } - - //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) - void copyTo(OutputArray dst, InputArray mask, Stream& stream) const; - //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) - CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask, Stream& stream) const { - copyTo(static_cast(dst), static_cast(mask), stream); - } - - //! sets some of the GpuMat elements to s (Blocking call) - CV_WRAP GpuMat& setTo(Scalar s); - - //! sets some of the GpuMat elements to s (Non-Blocking call) - CV_WRAP GpuMat& setTo(Scalar s, Stream& stream); - - //! sets some of the GpuMat elements to s, according to the mask (Blocking call) - CV_WRAP GpuMat& setTo(Scalar s, InputArray mask); - - //! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call) - CV_WRAP GpuMat& setTo(Scalar s, InputArray mask, Stream& stream); - - //! converts GpuMat to another datatype (Blocking call) - void convertTo(OutputArray dst, int rtype) const; - - //! converts GpuMat to another datatype (Non-Blocking call) - void convertTo(OutputArray dst, int rtype, Stream& stream) const; - //! bindings overload which converts GpuMat to another datatype (Non-Blocking call) - CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, Stream& stream) const { - convertTo(static_cast(dst), rtype, stream); - } - - //! converts GpuMat to another datatype with scaling (Blocking call) - void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const; - //! bindings overload which converts GpuMat to another datatype with scaling(Blocking call) - CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha = 1.0, double beta = 0.0) const { - convertTo(static_cast(dst), rtype, alpha, beta); - } - - //! converts GpuMat to another datatype with scaling (Non-Blocking call) - void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const; - - //! converts GpuMat to another datatype with scaling (Non-Blocking call) - void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const; - //! bindings overload which converts GpuMat to another datatype with scaling (Non-Blocking call) - CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha, double beta, Stream& stream) const { - convertTo(static_cast(dst), rtype, alpha, beta, stream); - } - - CV_WRAP void assignTo(GpuMat& m, int type = -1) const; - - //! returns pointer to y-th row - uchar* ptr(int y = 0); - const uchar* ptr(int y = 0) const; - - //! template version of the above method - template _Tp* ptr(int y = 0); - template const _Tp* ptr(int y = 0) const; - - template operator PtrStepSz<_Tp>() const; - template operator PtrStep<_Tp>() const; - - //! returns a new GpuMat header for the specified row - CV_WRAP GpuMat row(int y) const; - - //! returns a new GpuMat header for the specified column - CV_WRAP GpuMat col(int x) const; - - //! ... for the specified row span - CV_WRAP GpuMat rowRange(int startrow, int endrow) const; - CV_WRAP GpuMat rowRange(Range r) const; - - //! ... for the specified column span - CV_WRAP GpuMat colRange(int startcol, int endcol) const; - CV_WRAP GpuMat colRange(Range r) const; - - //! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.) - GpuMat operator ()(Range rowRange, Range colRange) const; - GpuMat operator ()(Rect roi) const; - - //! creates alternative GpuMat header for the same data, with different - //! number of channels and/or different number of rows - CV_WRAP GpuMat reshape(int cn, int rows = 0) const; - - //! locates GpuMat header within a parent GpuMat - CV_WRAP void locateROI(Size& wholeSize, Point& ofs) const; - - //! moves/resizes the current GpuMat ROI inside the parent GpuMat - CV_WRAP GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright); - - //! returns true iff the GpuMat data is continuous - //! (i.e. when there are no gaps between successive rows) - CV_WRAP bool isContinuous() const; - - //! returns element size in bytes - CV_WRAP size_t elemSize() const; - - //! returns the size of element channel in bytes - CV_WRAP size_t elemSize1() const; - - //! returns element type - CV_WRAP int type() const; - - //! returns element type - CV_WRAP int depth() const; - - //! returns number of channels - CV_WRAP int channels() const; - - //! returns step/elemSize1() - CV_WRAP size_t step1() const; - - //! returns GpuMat size : width == number of columns, height == number of rows - CV_WRAP Size size() const; - - //! returns true if GpuMat data is NULL - CV_WRAP bool empty() const; - - // returns pointer to cuda memory - CV_WRAP void* cudaPtr() const; - - //! internal use method: updates the continuity flag - CV_WRAP void updateContinuityFlag(); - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - - //! the number of rows and columns - int rows, cols; - - //! a distance between successive rows in bytes; includes the gap if any - CV_PROP size_t step; - - //! pointer to the data - uchar* data; - - //! pointer to the reference counter; - //! when GpuMat points to user-allocated data, the pointer is NULL - int* refcount; - - //! helper fields used in locateROI and adjustROI - uchar* datastart; - const uchar* dataend; - - //! allocator - Allocator* allocator; -}; - -struct CV_EXPORTS_W GpuData -{ - explicit GpuData(size_t _size); - ~GpuData(); - - GpuData(const GpuData&) = delete; - GpuData& operator=(const GpuData&) = delete; - - GpuData(GpuData&&) = delete; - GpuData& operator=(GpuData&&) = delete; - - uchar* data; - size_t size; -}; - -class CV_EXPORTS_W GpuMatND -{ -public: - using SizeArray = std::vector; - using StepArray = std::vector; - using IndexArray = std::vector; - - //! destructor - ~GpuMatND(); - - //! default constructor - GpuMatND(); - - /** @overload - @param size Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - GpuMatND(SizeArray size, int type); - - /** @overload - @param size Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param step Array of _size.size() or _size.size()-1 steps in case of a multi-dimensional array - (if specified, the last step must be equal to the element size, otherwise it will be added as such). - If not specified, the matrix is assumed to be continuous. - */ - GpuMatND(SizeArray size, int type, void* data, StepArray step = StepArray()); - - /** @brief Allocates GPU memory. - Suppose there is some GPU memory already allocated. In that case, this method may choose to reuse that - GPU memory under the specific condition: it must be of the same size and type, not externally allocated, - the GPU memory is continuous(i.e., isContinuous() is true), and is not a sub-matrix of another GpuMatND - (i.e., isSubmatrix() is false). In other words, this method guarantees that the GPU memory allocated by - this method is always continuous and is not a sub-region of another GpuMatND. - */ - void create(SizeArray size, int type); - - void release(); - - void swap(GpuMatND& m) noexcept; - - /** @brief Creates a full copy of the array and the underlying data. - The method creates a full copy of the array. It mimics the behavior of Mat::clone(), i.e. - the original step is not taken into account. So, the array copy is a continuous array - occupying total()\*elemSize() bytes. - */ - GpuMatND clone() const; - - /** @overload - This overload is non-blocking, so it may return even if the copy operation is not finished. - */ - GpuMatND clone(Stream& stream) const; - - /** @brief Extracts a sub-matrix. - The operator makes a new header for the specified sub-array of \*this. - The operator is an O(1) operation, that is, no matrix data is copied. - @param ranges Array of selected ranges along each dimension. - */ - GpuMatND operator()(const std::vector& ranges) const; - - /** @brief Creates a GpuMat header for a 2D plane part of an n-dim matrix. - @note The returned GpuMat is constructed with the constructor for user-allocated data. - That is, It does not perform reference counting. - @note This function does not increment this GpuMatND's reference counter. - */ - GpuMat createGpuMatHeader(IndexArray idx, Range rowRange, Range colRange) const; - - /** @overload - Creates a GpuMat header if this GpuMatND is effectively 2D. - @note The returned GpuMat is constructed with the constructor for user-allocated data. - That is, It does not perform reference counting. - @note This function does not increment this GpuMatND's reference counter. - */ - GpuMat createGpuMatHeader() const; - - /** @brief Extracts a 2D plane part of an n-dim matrix. - It differs from createGpuMatHeader(IndexArray, Range, Range) in that it clones a part of this - GpuMatND to the returned GpuMat. - @note This operator does not increment this GpuMatND's reference counter; - */ - GpuMat operator()(IndexArray idx, Range rowRange, Range colRange) const; - - /** @brief Extracts a 2D plane part of an n-dim matrix if this GpuMatND is effectively 2D. - It differs from createGpuMatHeader() in that it clones a part of this GpuMatND. - @note This operator does not increment this GpuMatND's reference counter; - */ - operator GpuMat() const; - - GpuMatND(const GpuMatND&) = default; - GpuMatND& operator=(const GpuMatND&) = default; - -#if defined(__GNUC__) && __GNUC__ < 5 - // error: function '...' defaulted on its first declaration with an exception-specification - // that differs from the implicit declaration '...' - - GpuMatND(GpuMatND&&) = default; - GpuMatND& operator=(GpuMatND&&) = default; -#else - GpuMatND(GpuMatND&&) noexcept = default; - GpuMatND& operator=(GpuMatND&&) noexcept = default; -#endif - - void upload(InputArray src); - void upload(InputArray src, Stream& stream); - void download(OutputArray dst) const; - void download(OutputArray dst, Stream& stream) const; - - //! returns true iff the GpuMatND data is continuous - //! (i.e. when there are no gaps between successive rows) - bool isContinuous() const; - - //! returns true if the matrix is a sub-matrix of another matrix - bool isSubmatrix() const; - - //! returns element size in bytes - size_t elemSize() const; - - //! returns the size of element channel in bytes - size_t elemSize1() const; - - //! returns true if data is null - bool empty() const; - - //! returns true if not empty and points to external(user-allocated) gpu memory - bool external() const; - - //! returns pointer to the first byte of the GPU memory - uchar* getDevicePtr() const; - - //! returns the total number of array elements - size_t total() const; - - //! returns the size of underlying memory in bytes - size_t totalMemSize() const; - - //! returns element type - int type() const; - -private: - //! internal use - void setFields(SizeArray size, int type, StepArray step = StepArray()); - -public: - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - - //! matrix dimensionality - int dims; - - //! shape of this array - SizeArray size; - - /*! step values - Their semantics is identical to the semantics of step for Mat. - */ - StepArray step; - -private: - /*! internal use - If this GpuMatND holds external memory, this is empty. - */ - std::shared_ptr data_; - - /*! internal use - If this GpuMatND manages memory with reference counting, this value is - always equal to data_->data. If this GpuMatND holds external memory, - data_ is empty and data points to the external memory. - */ - uchar* data; - - /*! internal use - If this GpuMatND is a sub-matrix of a larger matrix, this value is the - difference of the first byte between the sub-matrix and the whole matrix. - */ - size_t offset; -}; - -/** @brief Creates a continuous matrix. - -@param rows Row count. -@param cols Column count. -@param type Type of the matrix. -@param arr Destination matrix. This parameter changes only if it has a proper type and area ( -\f$\texttt{rows} \times \texttt{cols}\f$ ). - -Matrix is called continuous if its elements are stored continuously, that is, without gaps at the -end of each row. - */ -CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr); - -/** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type. - -@param rows Minimum desired number of rows. -@param cols Minimum desired number of columns. -@param type Desired matrix type. -@param arr Destination matrix. - -The function does not reallocate memory if the matrix has proper attributes already. - */ -CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr); - -/** @brief Bindings overload to create a GpuMat from existing GPU memory. -@param rows Row count. -@param cols Column count. -@param type Type of the matrix. -@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. -@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. -@note Overload for generation of bindings only, not exported or intended for use internally from C++. - */ -CV_EXPORTS_W GpuMat inline createGpuMatFromCudaMemory(int rows, int cols, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { - return GpuMat(rows, cols, type, reinterpret_cast(cudaMemoryAddress), step); -} - - /** @overload -@param size 2D array size: Size(cols, rows). In the Size() constructor, the number of rows and the number of columns go in the reverse order. -@param type Type of the matrix. -@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. -@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. -@note Overload for generation of bindings only, not exported or intended for use internally from C++. - */ -CV_EXPORTS_W inline GpuMat createGpuMatFromCudaMemory(Size size, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { - return GpuMat(size, type, reinterpret_cast(cudaMemoryAddress), step); -} - -/** @brief BufferPool for use with CUDA streams - -BufferPool utilizes Stream's allocator to create new buffers for GpuMat's. It is -only useful when enabled with #setBufferPoolUsage. - -@code - setBufferPoolUsage(true); -@endcode - -@note #setBufferPoolUsage must be called \em before any Stream declaration. - -Users may specify custom allocator for Stream and may implement their own stream based -functions utilizing the same underlying GPU memory management. - -If custom allocator is not specified, BufferPool utilizes StackAllocator by -default. StackAllocator allocates a chunk of GPU device memory beforehand, -and when GpuMat is declared later on, it is given the pre-allocated memory. -This kind of strategy reduces the number of calls for memory allocating APIs -such as cudaMalloc or cudaMallocPitch. - -Below is an example that utilizes BufferPool with StackAllocator: - -@code - #include - - using namespace cv; - using namespace cv::cuda - - int main() - { - setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool - setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) - - Stream stream1, stream2; // Each stream uses 1 stack - BufferPool pool1(stream1), pool2(stream2); - - GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB - GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full - - GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB - GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB - - cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); - cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); - } -@endcode - -If we allocate another GpuMat on pool1 in the above example, it will be carried out by -the DefaultAllocator since the stack for pool1 is full. - -@code - GpuMat d_add1 = pool1.getBuffer(1024, 1024, CV_8UC1); // Stack for pool1 is full, memory is allocated with DefaultAllocator -@endcode - -If a third stream is declared in the above example, allocating with #getBuffer -within that stream will also be carried out by the DefaultAllocator because we've run out of -stacks. - -@code - Stream stream3; // Only 2 stacks were allocated, we've run out of stacks - BufferPool pool3(stream3); - GpuMat d_src3 = pool3.getBuffer(1024, 1024, CV_8UC1); // Memory is allocated with DefaultAllocator -@endcode - -@warning When utilizing StackAllocator, deallocation order is important. - -Just like a stack, deallocation must be done in LIFO order. Below is an example of -erroneous usage that violates LIFO rule. If OpenCV is compiled in Debug mode, this -sample code will emit CV_Assert error. - -@code - int main() - { - setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool - Stream stream; // A default size (10 MB) stack is allocated to this stream - BufferPool pool(stream); - - GpuMat mat1 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat1 (1MB) - GpuMat mat2 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat2 (1MB) - - mat1.release(); // erroneous usage : mat2 must be deallocated before mat1 - } -@endcode - -Since C++ local variables are destroyed in the reverse order of construction, -the code sample below satisfies the LIFO rule. Local GpuMat's are deallocated -and the corresponding memory is automatically returned to the pool for later usage. - -@code - int main() - { - setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool - setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) - - Stream stream1, stream2; // Each stream uses 1 stack - BufferPool pool1(stream1), pool2(stream2); - - for (int i = 0; i < 10; i++) - { - GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB - GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full - - GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB - GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB - - d_src1.setTo(Scalar(i), stream1); - d_src2.setTo(Scalar(i), stream2); - - cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); - cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); - // The order of destruction of the local variables is: - // d_dst2 => d_src2 => d_dst1 => d_src1 - // LIFO rule is satisfied, this code runs without error - } - } -@endcode - */ -class CV_EXPORTS_W BufferPool -{ -public: - - //! Gets the BufferPool for the given stream. - CV_WRAP explicit BufferPool(Stream& stream); - - //! Allocates a new GpuMat of given size and type. - CV_WRAP GpuMat getBuffer(int rows, int cols, int type); - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - //! Allocates a new GpuMat of given size and type. - CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - //! Returns the allocator associated with the stream. - CV_WRAP Ptr getAllocator() const { return allocator_; } - -private: - Ptr allocator_; -}; - -//! BufferPool management (must be called before Stream creation) -CV_EXPORTS_W void setBufferPoolUsage(bool on); -CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount); - -//=================================================================================== -// HostMem -//=================================================================================== - -/** @brief Class with reference counting wrapping special memory type allocation functions from CUDA. - -Its interface is also Mat-like but with additional memory type parameters. - -- **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous - uploading/downloading data from/to GPU. -- **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU - address space, if supported. -- **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are - used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache - utilization. - -@note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2 -Pinned Memory APIs* document or *CUDA C Programming Guide*. - */ -class CV_EXPORTS_W HostMem -{ -public: - enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 }; - - static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - HostMem(const HostMem& m); - - CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - //! creates from host memory with coping data - CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); - - ~HostMem(); - - HostMem& operator =(const HostMem& m); - - //! swaps with other smart pointer - CV_WRAP void swap(HostMem& b); - - //! returns deep copy of the matrix, i.e. the data is copied - CV_WRAP HostMem clone() const; - - //! allocates new matrix data unless the matrix already has specified size and type. - CV_WRAP void create(int rows, int cols, int type); - void create(Size size, int type); - - //! creates alternative HostMem header for the same data, with different - //! number of channels and/or different number of rows - CV_WRAP HostMem reshape(int cn, int rows = 0) const; - - //! decrements reference counter and released memory if needed. - void release(); - - //! returns matrix header with disabled reference counting for HostMem data. - CV_WRAP Mat createMatHeader() const; - - /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting - for it. - - This can be done only if memory was allocated with the SHARED flag and if it is supported by the - hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which - eliminates an extra copy. - */ - GpuMat createGpuMatHeader() const; - - // Please see cv::Mat for descriptions - CV_WRAP bool isContinuous() const; - CV_WRAP size_t elemSize() const; - CV_WRAP size_t elemSize1() const; - CV_WRAP int type() const; - CV_WRAP int depth() const; - CV_WRAP int channels() const; - CV_WRAP size_t step1() const; - CV_WRAP Size size() const; - CV_WRAP bool empty() const; - - // Please see cv::Mat for descriptions - int flags; - int rows, cols; - CV_PROP size_t step; - - uchar* data; - int* refcount; - - uchar* datastart; - const uchar* dataend; - - AllocType alloc_type; -}; - -/** @brief Page-locks the memory of matrix and maps it for the device(s). - -@param m Input matrix. - */ -CV_EXPORTS_W void registerPageLocked(Mat& m); - -/** @brief Unmaps the memory of matrix and makes it pageable again. - -@param m Input matrix. - */ -CV_EXPORTS_W void unregisterPageLocked(Mat& m); - -//=================================================================================== -// Stream -//=================================================================================== - -/** @brief This class encapsulates a queue of asynchronous calls. - -@note Currently, you may face problems if an operation is enqueued twice with different data. Some -functions use the constant GPU memory, and next call may update the memory before the previous one -has been finished. But calling different operations asynchronously is safe because each operation -has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are -also safe. - -@note The Stream class is not thread-safe. Please use different Stream objects for different CPU threads. - -@code -void thread1() -{ - cv::cuda::Stream stream1; - cv::cuda::func1(..., stream1); -} - -void thread2() -{ - cv::cuda::Stream stream2; - cv::cuda::func2(..., stream2); -} -@endcode - -@note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user. -In multi-threading environment the stream objects must be passed explicitly (see previous note). - */ -class CV_EXPORTS_W Stream -{ - typedef void (Stream::*bool_type)() const; - void this_type_does_not_support_comparisons() const {} - -public: - typedef void (*StreamCallback)(int status, void* userData); - - //! creates a new asynchronous stream - CV_WRAP Stream(); - - //! creates a new asynchronous stream with custom allocator - CV_WRAP Stream(const Ptr& allocator); - - /** @brief creates a new Stream using the cudaFlags argument to determine the behaviors of the stream - - @note The cudaFlags parameter is passed to the underlying api cudaStreamCreateWithFlags() and - supports the same parameter values. - @code - // creates an OpenCV cuda::Stream that manages an asynchronous, non-blocking, - // non-default CUDA stream - cv::cuda::Stream cvStream(cudaStreamNonBlocking); - @endcode - */ - CV_WRAP Stream(const size_t cudaFlags); - - /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false. - */ - CV_WRAP bool queryIfComplete() const; - - /** @brief Blocks the current CPU thread until all operations in the stream are complete. - */ - CV_WRAP void waitForCompletion(); - - /** @brief Makes a compute stream wait on an event. - */ - CV_WRAP void waitEvent(const Event& event); - - /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have - completed. - - @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization - that may depend on outstanding device work or other callbacks that are not mandated to run earlier. - Callbacks without a mandated order (in independent streams) execute in undefined order and may be - serialized. - */ - void enqueueHostCallback(StreamCallback callback, void* userData); - - //! return Stream object for default CUDA stream - CV_WRAP static Stream& Null(); - - //! returns true if stream object is not default (!= 0) - operator bool_type() const; - - //! return Pointer to CUDA stream - CV_WRAP void* cudaPtr() const; - - class Impl; - -private: - Ptr impl_; - Stream(const Ptr& impl); - - friend struct StreamAccessor; - friend class BufferPool; - friend class DefaultDeviceInitializer; -}; - - -/** @brief Bindings overload to create a Stream object from the address stored in an existing CUDA Runtime API stream pointer (cudaStream_t). -@param cudaStreamMemoryAddress Memory address stored in a CUDA Runtime API stream pointer (cudaStream_t). The created Stream object does not perform any allocation or deallocation and simply wraps existing raw CUDA Runtime API stream pointer. -@note Overload for generation of bindings only, not exported or intended for use internally from C++. - */ -CV_EXPORTS_W Stream wrapStream(size_t cudaStreamMemoryAddress); - -class CV_EXPORTS_W Event -{ -public: - enum CreateFlags - { - DEFAULT = 0x00, /**< Default event flag */ - BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */ - DISABLE_TIMING = 0x02, /**< Event will not record timing data */ - INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */ - }; - - CV_WRAP explicit Event(const Event::CreateFlags flags = Event::CreateFlags::DEFAULT); - - //! records an event - CV_WRAP void record(Stream& stream = Stream::Null()); - - //! queries an event's status - CV_WRAP bool queryIfComplete() const; - - //! waits for an event to complete - CV_WRAP void waitForCompletion(); - - //! computes the elapsed time between events - CV_WRAP static float elapsedTime(const Event& start, const Event& end); - - class Impl; - -private: - Ptr impl_; - Event(const Ptr& impl); - - friend struct EventAccessor; -}; -CV_ENUM_FLAGS(Event::CreateFlags) - -//! @} cudacore_struct - -//=================================================================================== -// Initialization & Info -//=================================================================================== - -//! @addtogroup cudacore_init -//! @{ - -/** @brief Returns the number of installed CUDA-enabled devices. - -Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support, -this function returns 0. If the CUDA driver is not installed, or is incompatible, this function -returns -1. - */ -CV_EXPORTS_W int getCudaEnabledDeviceCount(); - -/** @brief Sets a device and initializes it for the current thread. - -@param device System index of a CUDA device starting with 0. - -If the call of this function is omitted, a default device is initialized at the fist CUDA usage. - */ -CV_EXPORTS_W void setDevice(int device); - -/** @brief Returns the current device index set by cuda::setDevice or initialized by default. - */ -CV_EXPORTS_W int getDevice(); - -/** @brief Explicitly destroys and cleans up all resources associated with the current device in the current -process. - -Any subsequent API call to this device will reinitialize the device. - */ -CV_EXPORTS_W void resetDevice(); - -/** @brief Enumeration providing CUDA computing features. - */ -enum FeatureSet -{ - FEATURE_SET_COMPUTE_10 = 10, - FEATURE_SET_COMPUTE_11 = 11, - FEATURE_SET_COMPUTE_12 = 12, - FEATURE_SET_COMPUTE_13 = 13, - FEATURE_SET_COMPUTE_20 = 20, - FEATURE_SET_COMPUTE_21 = 21, - FEATURE_SET_COMPUTE_30 = 30, - FEATURE_SET_COMPUTE_32 = 32, - FEATURE_SET_COMPUTE_35 = 35, - FEATURE_SET_COMPUTE_50 = 50, - - GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, - SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, - NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13, - WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30, - DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35 -}; - -//! checks whether current device supports the given feature -CV_EXPORTS bool deviceSupports(FeatureSet feature_set); - -/** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was -built for. - -According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute -capability can always be compiled to binary code of greater or equal compute capability". - */ -class CV_EXPORTS_W TargetArchs -{ -public: - /** @brief The following method checks whether the module was built with the support of the given feature: - - @param feature_set Features to be checked. See :ocvcuda::FeatureSet. - */ - static bool builtWith(FeatureSet feature_set); - - /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA - code for the given architecture(s): - - @param major Major compute capability version. - @param minor Minor compute capability version. - */ - CV_WRAP static bool has(int major, int minor); - CV_WRAP static bool hasPtx(int major, int minor); - CV_WRAP static bool hasBin(int major, int minor); - - CV_WRAP static bool hasEqualOrLessPtx(int major, int minor); - CV_WRAP static bool hasEqualOrGreater(int major, int minor); - CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor); - CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor); -}; - -/** @brief Class providing functionality for querying the specified GPU properties. - */ -class CV_EXPORTS_W DeviceInfo -{ -public: - //! creates DeviceInfo object for the current GPU - CV_WRAP DeviceInfo(); - - /** @brief The constructors. - - @param device_id System index of the CUDA device starting with 0. - - Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it - constructs an object for the current device. - */ - CV_WRAP DeviceInfo(int device_id); - - /** @brief Returns system index of the CUDA device starting with 0. - */ - CV_WRAP int deviceID() const; - - //! ASCII string identifying device - const char* name() const; - - //! global memory available on device in bytes - CV_WRAP size_t totalGlobalMem() const; - - //! shared memory available per block in bytes - CV_WRAP size_t sharedMemPerBlock() const; - - //! 32-bit registers available per block - CV_WRAP int regsPerBlock() const; - - //! warp size in threads - CV_WRAP int warpSize() const; - - //! maximum pitch in bytes allowed by memory copies - CV_WRAP size_t memPitch() const; - - //! maximum number of threads per block - CV_WRAP int maxThreadsPerBlock() const; - - //! maximum size of each dimension of a block - CV_WRAP Vec3i maxThreadsDim() const; - - //! maximum size of each dimension of a grid - CV_WRAP Vec3i maxGridSize() const; - - //! clock frequency in kilohertz - CV_WRAP int clockRate() const; - - //! constant memory available on device in bytes - CV_WRAP size_t totalConstMem() const; - - //! major compute capability - CV_WRAP int majorVersion() const; - - //! minor compute capability - CV_WRAP int minorVersion() const; - - //! alignment requirement for textures - CV_WRAP size_t textureAlignment() const; - - //! pitch alignment requirement for texture references bound to pitched memory - CV_WRAP size_t texturePitchAlignment() const; - - //! number of multiprocessors on device - CV_WRAP int multiProcessorCount() const; - - //! specified whether there is a run time limit on kernels - CV_WRAP bool kernelExecTimeoutEnabled() const; - - //! device is integrated as opposed to discrete - CV_WRAP bool integrated() const; - - //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer - CV_WRAP bool canMapHostMemory() const; - - enum ComputeMode - { - ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */ - ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */ - ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */ - ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */ - }; - - //! compute mode - CV_WRAP DeviceInfo::ComputeMode computeMode() const; - - //! maximum 1D texture size - CV_WRAP int maxTexture1D() const; - - //! maximum 1D mipmapped texture size - CV_WRAP int maxTexture1DMipmap() const; - - //! maximum size for 1D textures bound to linear memory - CV_WRAP int maxTexture1DLinear() const; - - //! maximum 2D texture dimensions - CV_WRAP Vec2i maxTexture2D() const; - - //! maximum 2D mipmapped texture dimensions - CV_WRAP Vec2i maxTexture2DMipmap() const; - - //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory - CV_WRAP Vec3i maxTexture2DLinear() const; - - //! maximum 2D texture dimensions if texture gather operations have to be performed - CV_WRAP Vec2i maxTexture2DGather() const; - - //! maximum 3D texture dimensions - CV_WRAP Vec3i maxTexture3D() const; - - //! maximum Cubemap texture dimensions - CV_WRAP int maxTextureCubemap() const; - - //! maximum 1D layered texture dimensions - CV_WRAP Vec2i maxTexture1DLayered() const; - - //! maximum 2D layered texture dimensions - CV_WRAP Vec3i maxTexture2DLayered() const; - - //! maximum Cubemap layered texture dimensions - CV_WRAP Vec2i maxTextureCubemapLayered() const; - - //! maximum 1D surface size - CV_WRAP int maxSurface1D() const; - - //! maximum 2D surface dimensions - CV_WRAP Vec2i maxSurface2D() const; - - //! maximum 3D surface dimensions - CV_WRAP Vec3i maxSurface3D() const; - - //! maximum 1D layered surface dimensions - CV_WRAP Vec2i maxSurface1DLayered() const; - - //! maximum 2D layered surface dimensions - CV_WRAP Vec3i maxSurface2DLayered() const; - - //! maximum Cubemap surface dimensions - CV_WRAP int maxSurfaceCubemap() const; - - //! maximum Cubemap layered surface dimensions - CV_WRAP Vec2i maxSurfaceCubemapLayered() const; - - //! alignment requirements for surfaces - CV_WRAP size_t surfaceAlignment() const; - - //! device can possibly execute multiple kernels concurrently - CV_WRAP bool concurrentKernels() const; - - //! device has ECC support enabled - CV_WRAP bool ECCEnabled() const; - - //! PCI bus ID of the device - CV_WRAP int pciBusID() const; - - //! PCI device ID of the device - CV_WRAP int pciDeviceID() const; - - //! PCI domain ID of the device - CV_WRAP int pciDomainID() const; - - //! true if device is a Tesla device using TCC driver, false otherwise - CV_WRAP bool tccDriver() const; - - //! number of asynchronous engines - CV_WRAP int asyncEngineCount() const; - - //! device shares a unified address space with the host - CV_WRAP bool unifiedAddressing() const; - - //! peak memory clock frequency in kilohertz - CV_WRAP int memoryClockRate() const; - - //! global memory bus width in bits - CV_WRAP int memoryBusWidth() const; - - //! size of L2 cache in bytes - CV_WRAP int l2CacheSize() const; - - //! maximum resident threads per multiprocessor - CV_WRAP int maxThreadsPerMultiProcessor() const; - - //! gets free and total device memory - CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const; - CV_WRAP size_t freeMemory() const; - CV_WRAP size_t totalMemory() const; - - /** @brief Provides information on CUDA feature support. - - @param feature_set Features to be checked. See cuda::FeatureSet. - - This function returns true if the device has the specified CUDA feature. Otherwise, it returns false - */ - bool supports(FeatureSet feature_set) const; - - /** @brief Checks the CUDA module and device compatibility. - - This function returns true if the CUDA module can be run on the specified device. Otherwise, it - returns false . - */ - CV_WRAP bool isCompatible() const; - -private: - int device_id_; -}; - -CV_EXPORTS_W void printCudaDeviceInfo(int device); -CV_EXPORTS_W void printShortCudaDeviceInfo(int device); - -/** @brief Converts an array to half precision floating number. - -@param _src input array. -@param _dst output array. -@param stream Stream for the asynchronous version. -@sa convertFp16 -*/ -CV_EXPORTS void convertFp16(InputArray _src, OutputArray _dst, Stream& stream = Stream::Null()); - -//! @} cudacore_init - -}} // namespace cv { namespace cuda { - - -#include "opencv2/core/cuda.inl.hpp" - -#endif /* OPENCV_CORE_CUDA_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CUDA_HPP +#define OPENCV_CORE_CUDA_HPP + +#ifndef __cplusplus +# error cuda.hpp header must be compiled as C++ +#endif + +#include "opencv2/core.hpp" +#include "opencv2/core/cuda_types.hpp" + +/** + @defgroup cuda CUDA-accelerated Computer Vision + @{ + @defgroup cudacore Core part + @{ + @defgroup cudacore_init Initialization and Information + @defgroup cudacore_struct Data Structures + @} + @} + */ + +namespace cv { namespace cuda { + +//! @addtogroup cudacore_struct +//! @{ + +//=================================================================================== +// GpuMat +//=================================================================================== + +/** @brief Base storage class for GPU memory with reference counting. + +Its interface matches the Mat interface with the following limitations: + +- no arbitrary dimensions support (only 2D) +- no functions that return references to their data (because references on GPU are not valid for + CPU) +- no expression templates technique support + +Beware that the latter limitation may lead to overloaded matrix operators that cause memory +allocations. The GpuMat class is convertible to cuda::PtrStepSz and cuda::PtrStep so it can be +passed directly to the kernel. + +@note In contrast with Mat, in most cases GpuMat::isContinuous() == false . This means that rows are +aligned to a size depending on the hardware. Single-row GpuMat is always a continuous matrix. + +@note You are not recommended to leave static or global GpuMat variables allocated, that is, to rely +on its destructor. The destruction order of such variables and CUDA context is undefined. GPU memory +release function returns error if the CUDA context has been destroyed before. + +Some member functions are described as a "Blocking Call" while some are described as a +"Non-Blocking Call". Blocking functions are synchronous to host. It is guaranteed that the GPU +operation is finished when the function returns. However, non-blocking functions are asynchronous to +host. Those functions may return even if the GPU operation is not finished. + +Compared to their blocking counterpart, non-blocking functions accept Stream as an additional +argument. If a non-default stream is passed, the GPU operation may overlap with operations in other +streams. + +@sa Mat + */ +class CV_EXPORTS_W GpuMat +{ +public: + class CV_EXPORTS_W Allocator + { + public: + virtual ~Allocator() {} + + // allocator must fill data, step and refcount fields + virtual bool allocate(GpuMat* mat, int rows, int cols, size_t elemSize) = 0; + virtual void free(GpuMat* mat) = 0; + }; + + //! default allocator + CV_WRAP static GpuMat::Allocator* defaultAllocator(); + CV_WRAP static void setDefaultAllocator(GpuMat::Allocator* allocator); + CV_WRAP static GpuMat::Allocator* getStdAllocator(); + + //! default constructor + CV_WRAP explicit GpuMat(GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! constructs GpuMat of the specified size and type + CV_WRAP GpuMat(int rows, int cols, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + CV_WRAP GpuMat(Size size, int type, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! constructs GpuMat and fills it with the specified value _s + CV_WRAP GpuMat(int rows, int cols, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + CV_WRAP GpuMat(Size size, int type, Scalar s, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! copy constructor + CV_WRAP GpuMat(const GpuMat& m); + + //! constructor for GpuMat headers pointing to user-allocated data + GpuMat(int rows, int cols, int type, void* data, size_t step = Mat::AUTO_STEP); + GpuMat(Size size, int type, void* data, size_t step = Mat::AUTO_STEP); + + //! creates a GpuMat header for a part of the bigger matrix + CV_WRAP GpuMat(const GpuMat& m, Range rowRange, Range colRange); + CV_WRAP GpuMat(const GpuMat& m, Rect roi); + + //! builds GpuMat from host memory (Blocking call) + CV_WRAP explicit GpuMat(InputArray arr, GpuMat::Allocator* allocator = GpuMat::defaultAllocator()); + + //! destructor - calls release() + ~GpuMat(); + + //! assignment operators + GpuMat& operator =(const GpuMat& m); + + //! allocates new GpuMat data unless the GpuMat already has specified size and type + CV_WRAP void create(int rows, int cols, int type); + CV_WRAP void create(Size size, int type); + + //! decreases reference counter, deallocate the data when reference counter reaches 0 + CV_WRAP void release(); + + //! swaps with other smart pointer + CV_WRAP void swap(GpuMat& mat); + + /** @brief Performs data upload to GpuMat (Blocking call) + + This function copies data from host memory to device memory. As being a blocking call, it is + guaranteed that the copy operation is finished when this function returns. + */ + CV_WRAP void upload(InputArray arr); + + /** @brief Performs data upload to GpuMat (Non-Blocking call) + + This function copies data from host memory to device memory. As being a non-blocking call, this + function may return even if the copy operation is not finished. + + The copy operation may be overlapped with operations in other non-default streams if \p stream is + not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. + */ + CV_WRAP void upload(InputArray arr, Stream& stream); + + /** @brief Performs data download from GpuMat (Blocking call) + + This function copies data from device memory to host memory. As being a blocking call, it is + guaranteed that the copy operation is finished when this function returns. + */ + CV_WRAP void download(OutputArray dst) const; + + /** @brief Performs data download from GpuMat (Non-Blocking call) + + This function copies data from device memory to host memory. As being a non-blocking call, this + function may return even if the copy operation is not finished. + + The copy operation may be overlapped with operations in other non-default streams if \p stream is + not the default stream and \p dst is HostMem allocated with HostMem::PAGE_LOCKED option. + */ + CV_WRAP void download(OutputArray dst, Stream& stream) const; + + //! returns deep copy of the GpuMat, i.e. the data is copied + CV_WRAP GpuMat clone() const; + + //! copies the GpuMat content to device memory (Blocking call) + void copyTo(OutputArray dst) const; + //! bindings overload which copies the GpuMat content to device memory (Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst) const { + copyTo(static_cast(dst)); + } + + //! copies the GpuMat content to device memory (Non-Blocking call) + void copyTo(OutputArray dst, Stream& stream) const; + //! bindings overload which copies the GpuMat content to device memory (Non-Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst, Stream& stream) const { + copyTo(static_cast(dst), stream); + } + + //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) + void copyTo(OutputArray dst, InputArray mask) const; + //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask) const { + copyTo(static_cast(dst), static_cast(mask)); + } + + //! copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) + void copyTo(OutputArray dst, InputArray mask, Stream& stream) const; + //! bindings overload which copies those GpuMat elements to "m" that are marked with non-zero mask elements (Non-Blocking call) + CV_WRAP void copyTo(CV_OUT GpuMat& dst, GpuMat& mask, Stream& stream) const { + copyTo(static_cast(dst), static_cast(mask), stream); + } + + //! sets some of the GpuMat elements to s (Blocking call) + CV_WRAP GpuMat& setTo(Scalar s); + + //! sets some of the GpuMat elements to s (Non-Blocking call) + CV_WRAP GpuMat& setTo(Scalar s, Stream& stream); + + //! sets some of the GpuMat elements to s, according to the mask (Blocking call) + CV_WRAP GpuMat& setTo(Scalar s, InputArray mask); + + //! sets some of the GpuMat elements to s, according to the mask (Non-Blocking call) + CV_WRAP GpuMat& setTo(Scalar s, InputArray mask, Stream& stream); + + //! converts GpuMat to another datatype (Blocking call) + void convertTo(OutputArray dst, int rtype) const; + + //! converts GpuMat to another datatype (Non-Blocking call) + void convertTo(OutputArray dst, int rtype, Stream& stream) const; + //! bindings overload which converts GpuMat to another datatype (Non-Blocking call) + CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, Stream& stream) const { + convertTo(static_cast(dst), rtype, stream); + } + + //! converts GpuMat to another datatype with scaling (Blocking call) + void convertTo(OutputArray dst, int rtype, double alpha, double beta = 0.0) const; + //! bindings overload which converts GpuMat to another datatype with scaling(Blocking call) + CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha = 1.0, double beta = 0.0) const { + convertTo(static_cast(dst), rtype, alpha, beta); + } + + //! converts GpuMat to another datatype with scaling (Non-Blocking call) + void convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const; + + //! converts GpuMat to another datatype with scaling (Non-Blocking call) + void convertTo(OutputArray dst, int rtype, double alpha, double beta, Stream& stream) const; + //! bindings overload which converts GpuMat to another datatype with scaling (Non-Blocking call) + CV_WRAP void convertTo(CV_OUT GpuMat& dst, int rtype, double alpha, double beta, Stream& stream) const { + convertTo(static_cast(dst), rtype, alpha, beta, stream); + } + + CV_WRAP void assignTo(GpuMat& m, int type = -1) const; + + //! returns pointer to y-th row + uchar* ptr(int y = 0); + const uchar* ptr(int y = 0) const; + + //! template version of the above method + template _Tp* ptr(int y = 0); + template const _Tp* ptr(int y = 0) const; + + template operator PtrStepSz<_Tp>() const; + template operator PtrStep<_Tp>() const; + + //! returns a new GpuMat header for the specified row + CV_WRAP GpuMat row(int y) const; + + //! returns a new GpuMat header for the specified column + CV_WRAP GpuMat col(int x) const; + + //! ... for the specified row span + CV_WRAP GpuMat rowRange(int startrow, int endrow) const; + CV_WRAP GpuMat rowRange(Range r) const; + + //! ... for the specified column span + CV_WRAP GpuMat colRange(int startcol, int endcol) const; + CV_WRAP GpuMat colRange(Range r) const; + + //! extracts a rectangular sub-GpuMat (this is a generalized form of row, rowRange etc.) + GpuMat operator ()(Range rowRange, Range colRange) const; + GpuMat operator ()(Rect roi) const; + + //! creates alternative GpuMat header for the same data, with different + //! number of channels and/or different number of rows + CV_WRAP GpuMat reshape(int cn, int rows = 0) const; + + //! locates GpuMat header within a parent GpuMat + CV_WRAP void locateROI(Size& wholeSize, Point& ofs) const; + + //! moves/resizes the current GpuMat ROI inside the parent GpuMat + CV_WRAP GpuMat& adjustROI(int dtop, int dbottom, int dleft, int dright); + + //! returns true iff the GpuMat data is continuous + //! (i.e. when there are no gaps between successive rows) + CV_WRAP bool isContinuous() const; + + //! returns element size in bytes + CV_WRAP size_t elemSize() const; + + //! returns the size of element channel in bytes + CV_WRAP size_t elemSize1() const; + + //! returns element type + CV_WRAP int type() const; + + //! returns element type + CV_WRAP int depth() const; + + //! returns number of channels + CV_WRAP int channels() const; + + //! returns step/elemSize1() + CV_WRAP size_t step1() const; + + //! returns GpuMat size : width == number of columns, height == number of rows + CV_WRAP Size size() const; + + //! returns true if GpuMat data is NULL + CV_WRAP bool empty() const; + + // returns pointer to cuda memory + CV_WRAP void* cudaPtr() const; + + //! internal use method: updates the continuity flag + CV_WRAP void updateContinuityFlag(); + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! the number of rows and columns + int rows, cols; + + //! a distance between successive rows in bytes; includes the gap if any + CV_PROP size_t step; + + //! pointer to the data + uchar* data; + + //! pointer to the reference counter; + //! when GpuMat points to user-allocated data, the pointer is NULL + int* refcount; + + //! helper fields used in locateROI and adjustROI + uchar* datastart; + const uchar* dataend; + + //! allocator + Allocator* allocator; +}; + +struct CV_EXPORTS_W GpuData +{ + explicit GpuData(size_t _size); + ~GpuData(); + + GpuData(const GpuData&) = delete; + GpuData& operator=(const GpuData&) = delete; + + GpuData(GpuData&&) = delete; + GpuData& operator=(GpuData&&) = delete; + + uchar* data; + size_t size; +}; + +class CV_EXPORTS_W GpuMatND +{ +public: + using SizeArray = std::vector; + using StepArray = std::vector; + using IndexArray = std::vector; + + //! destructor + ~GpuMatND(); + + //! default constructor + GpuMatND(); + + /** @overload + @param size Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + GpuMatND(SizeArray size, int type); + + /** @overload + @param size Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_16FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Array of _size.size() or _size.size()-1 steps in case of a multi-dimensional array + (if specified, the last step must be equal to the element size, otherwise it will be added as such). + If not specified, the matrix is assumed to be continuous. + */ + GpuMatND(SizeArray size, int type, void* data, StepArray step = StepArray()); + + /** @brief Allocates GPU memory. + Suppose there is some GPU memory already allocated. In that case, this method may choose to reuse that + GPU memory under the specific condition: it must be of the same size and type, not externally allocated, + the GPU memory is continuous(i.e., isContinuous() is true), and is not a sub-matrix of another GpuMatND + (i.e., isSubmatrix() is false). In other words, this method guarantees that the GPU memory allocated by + this method is always continuous and is not a sub-region of another GpuMatND. + */ + void create(SizeArray size, int type); + + void release(); + + void swap(GpuMatND& m) noexcept; + + /** @brief Creates a full copy of the array and the underlying data. + The method creates a full copy of the array. It mimics the behavior of Mat::clone(), i.e. + the original step is not taken into account. So, the array copy is a continuous array + occupying total()\*elemSize() bytes. + */ + GpuMatND clone() const; + + /** @overload + This overload is non-blocking, so it may return even if the copy operation is not finished. + */ + GpuMatND clone(Stream& stream) const; + + /** @brief Extracts a sub-matrix. + The operator makes a new header for the specified sub-array of \*this. + The operator is an O(1) operation, that is, no matrix data is copied. + @param ranges Array of selected ranges along each dimension. + */ + GpuMatND operator()(const std::vector& ranges) const; + + /** @brief Creates a GpuMat header for a 2D plane part of an n-dim matrix. + @note The returned GpuMat is constructed with the constructor for user-allocated data. + That is, It does not perform reference counting. + @note This function does not increment this GpuMatND's reference counter. + */ + GpuMat createGpuMatHeader(IndexArray idx, Range rowRange, Range colRange) const; + + /** @overload + Creates a GpuMat header if this GpuMatND is effectively 2D. + @note The returned GpuMat is constructed with the constructor for user-allocated data. + That is, It does not perform reference counting. + @note This function does not increment this GpuMatND's reference counter. + */ + GpuMat createGpuMatHeader() const; + + /** @brief Extracts a 2D plane part of an n-dim matrix. + It differs from createGpuMatHeader(IndexArray, Range, Range) in that it clones a part of this + GpuMatND to the returned GpuMat. + @note This operator does not increment this GpuMatND's reference counter; + */ + GpuMat operator()(IndexArray idx, Range rowRange, Range colRange) const; + + /** @brief Extracts a 2D plane part of an n-dim matrix if this GpuMatND is effectively 2D. + It differs from createGpuMatHeader() in that it clones a part of this GpuMatND. + @note This operator does not increment this GpuMatND's reference counter; + */ + operator GpuMat() const; + + GpuMatND(const GpuMatND&) = default; + GpuMatND& operator=(const GpuMatND&) = default; + +#if defined(__GNUC__) && __GNUC__ < 5 + // error: function '...' defaulted on its first declaration with an exception-specification + // that differs from the implicit declaration '...' + + GpuMatND(GpuMatND&&) = default; + GpuMatND& operator=(GpuMatND&&) = default; +#else + GpuMatND(GpuMatND&&) noexcept = default; + GpuMatND& operator=(GpuMatND&&) noexcept = default; +#endif + + void upload(InputArray src); + void upload(InputArray src, Stream& stream); + void download(OutputArray dst) const; + void download(OutputArray dst, Stream& stream) const; + + //! returns true iff the GpuMatND data is continuous + //! (i.e. when there are no gaps between successive rows) + bool isContinuous() const; + + //! returns true if the matrix is a sub-matrix of another matrix + bool isSubmatrix() const; + + //! returns element size in bytes + size_t elemSize() const; + + //! returns the size of element channel in bytes + size_t elemSize1() const; + + //! returns true if data is null + bool empty() const; + + //! returns true if not empty and points to external(user-allocated) gpu memory + bool external() const; + + //! returns pointer to the first byte of the GPU memory + uchar* getDevicePtr() const; + + //! returns the total number of array elements + size_t total() const; + + //! returns the size of underlying memory in bytes + size_t totalMemSize() const; + + //! returns element type + int type() const; + +private: + //! internal use + void setFields(SizeArray size, int type, StepArray step = StepArray()); + +public: + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! matrix dimensionality + int dims; + + //! shape of this array + SizeArray size; + + /*! step values + Their semantics is identical to the semantics of step for Mat. + */ + StepArray step; + +private: + /*! internal use + If this GpuMatND holds external memory, this is empty. + */ + std::shared_ptr data_; + + /*! internal use + If this GpuMatND manages memory with reference counting, this value is + always equal to data_->data. If this GpuMatND holds external memory, + data_ is empty and data points to the external memory. + */ + uchar* data; + + /*! internal use + If this GpuMatND is a sub-matrix of a larger matrix, this value is the + difference of the first byte between the sub-matrix and the whole matrix. + */ + size_t offset; +}; + +/** @brief Creates a continuous matrix. + +@param rows Row count. +@param cols Column count. +@param type Type of the matrix. +@param arr Destination matrix. This parameter changes only if it has a proper type and area ( +\f$\texttt{rows} \times \texttt{cols}\f$ ). + +Matrix is called continuous if its elements are stored continuously, that is, without gaps at the +end of each row. + */ +CV_EXPORTS_W void createContinuous(int rows, int cols, int type, OutputArray arr); + +/** @brief Ensures that the size of a matrix is big enough and the matrix has a proper type. + +@param rows Minimum desired number of rows. +@param cols Minimum desired number of columns. +@param type Desired matrix type. +@param arr Destination matrix. + +The function does not reallocate memory if the matrix has proper attributes already. + */ +CV_EXPORTS_W void ensureSizeIsEnough(int rows, int cols, int type, OutputArray arr); + +/** @brief Bindings overload to create a GpuMat from existing GPU memory. +@param rows Row count. +@param cols Column count. +@param type Type of the matrix. +@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. +@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. +@note Overload for generation of bindings only, not exported or intended for use internally from C++. + */ +CV_EXPORTS_W GpuMat inline createGpuMatFromCudaMemory(int rows, int cols, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { + return GpuMat(rows, cols, type, reinterpret_cast(cudaMemoryAddress), step); +} + + /** @overload +@param size 2D array size: Size(cols, rows). In the Size() constructor, the number of rows and the number of columns go in the reverse order. +@param type Type of the matrix. +@param cudaMemoryAddress Address of the allocated GPU memory on the device. This does not allocate matrix data. Instead, it just initializes the matrix header that points to the specified \a cudaMemoryAddress, which means that no data is copied. This operation is very efficient and can be used to process external data using OpenCV functions. The external data is not automatically deallocated, so you should take care of it. +@param step Number of bytes each matrix row occupies. The value should include the padding bytes at the end of each row, if any. If the parameter is missing (set to Mat::AUTO_STEP ), no padding is assumed and the actual step is calculated as cols*elemSize(). See GpuMat::elemSize. +@note Overload for generation of bindings only, not exported or intended for use internally from C++. + */ +CV_EXPORTS_W inline GpuMat createGpuMatFromCudaMemory(Size size, int type, size_t cudaMemoryAddress, size_t step = Mat::AUTO_STEP) { + return GpuMat(size, type, reinterpret_cast(cudaMemoryAddress), step); +} + +/** @brief BufferPool for use with CUDA streams + +BufferPool utilizes Stream's allocator to create new buffers for GpuMat's. It is +only useful when enabled with #setBufferPoolUsage. + +@code + setBufferPoolUsage(true); +@endcode + +@note #setBufferPoolUsage must be called \em before any Stream declaration. + +Users may specify custom allocator for Stream and may implement their own stream based +functions utilizing the same underlying GPU memory management. + +If custom allocator is not specified, BufferPool utilizes StackAllocator by +default. StackAllocator allocates a chunk of GPU device memory beforehand, +and when GpuMat is declared later on, it is given the pre-allocated memory. +This kind of strategy reduces the number of calls for memory allocating APIs +such as cudaMalloc or cudaMallocPitch. + +Below is an example that utilizes BufferPool with StackAllocator: + +@code + #include + + using namespace cv; + using namespace cv::cuda + + int main() + { + setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool + setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) + + Stream stream1, stream2; // Each stream uses 1 stack + BufferPool pool1(stream1), pool2(stream2); + + GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB + GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full + + GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB + GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB + + cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); + cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); + } +@endcode + +If we allocate another GpuMat on pool1 in the above example, it will be carried out by +the DefaultAllocator since the stack for pool1 is full. + +@code + GpuMat d_add1 = pool1.getBuffer(1024, 1024, CV_8UC1); // Stack for pool1 is full, memory is allocated with DefaultAllocator +@endcode + +If a third stream is declared in the above example, allocating with #getBuffer +within that stream will also be carried out by the DefaultAllocator because we've run out of +stacks. + +@code + Stream stream3; // Only 2 stacks were allocated, we've run out of stacks + BufferPool pool3(stream3); + GpuMat d_src3 = pool3.getBuffer(1024, 1024, CV_8UC1); // Memory is allocated with DefaultAllocator +@endcode + +@warning When utilizing StackAllocator, deallocation order is important. + +Just like a stack, deallocation must be done in LIFO order. Below is an example of +erroneous usage that violates LIFO rule. If OpenCV is compiled in Debug mode, this +sample code will emit CV_Assert error. + +@code + int main() + { + setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool + Stream stream; // A default size (10 MB) stack is allocated to this stream + BufferPool pool(stream); + + GpuMat mat1 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat1 (1MB) + GpuMat mat2 = pool.getBuffer(1024, 1024, CV_8UC1); // Allocate mat2 (1MB) + + mat1.release(); // erroneous usage : mat2 must be deallocated before mat1 + } +@endcode + +Since C++ local variables are destroyed in the reverse order of construction, +the code sample below satisfies the LIFO rule. Local GpuMat's are deallocated +and the corresponding memory is automatically returned to the pool for later usage. + +@code + int main() + { + setBufferPoolUsage(true); // Tell OpenCV that we are going to utilize BufferPool + setBufferPoolConfig(getDevice(), 1024 * 1024 * 64, 2); // Allocate 64 MB, 2 stacks (default is 10 MB, 5 stacks) + + Stream stream1, stream2; // Each stream uses 1 stack + BufferPool pool1(stream1), pool2(stream2); + + for (int i = 0; i < 10; i++) + { + GpuMat d_src1 = pool1.getBuffer(4096, 4096, CV_8UC1); // 16MB + GpuMat d_dst1 = pool1.getBuffer(4096, 4096, CV_8UC3); // 48MB, pool1 is now full + + GpuMat d_src2 = pool2.getBuffer(1024, 1024, CV_8UC1); // 1MB + GpuMat d_dst2 = pool2.getBuffer(1024, 1024, CV_8UC3); // 3MB + + d_src1.setTo(Scalar(i), stream1); + d_src2.setTo(Scalar(i), stream2); + + cvtColor(d_src1, d_dst1, cv::COLOR_GRAY2BGR, 0, stream1); + cvtColor(d_src2, d_dst2, cv::COLOR_GRAY2BGR, 0, stream2); + // The order of destruction of the local variables is: + // d_dst2 => d_src2 => d_dst1 => d_src1 + // LIFO rule is satisfied, this code runs without error + } + } +@endcode + */ +class CV_EXPORTS_W BufferPool +{ +public: + + //! Gets the BufferPool for the given stream. + CV_WRAP explicit BufferPool(Stream& stream); + + //! Allocates a new GpuMat of given size and type. + CV_WRAP GpuMat getBuffer(int rows, int cols, int type); + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + //! Allocates a new GpuMat of given size and type. + CV_WRAP GpuMat getBuffer(Size size, int type) { return getBuffer(size.height, size.width, type); } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + //! Returns the allocator associated with the stream. + CV_WRAP Ptr getAllocator() const { return allocator_; } + +private: + Ptr allocator_; +}; + +//! BufferPool management (must be called before Stream creation) +CV_EXPORTS_W void setBufferPoolUsage(bool on); +CV_EXPORTS_W void setBufferPoolConfig(int deviceId, size_t stackSize, int stackCount); + +//=================================================================================== +// HostMem +//=================================================================================== + +/** @brief Class with reference counting wrapping special memory type allocation functions from CUDA. + +Its interface is also Mat-like but with additional memory type parameters. + +- **PAGE_LOCKED** sets a page locked memory type used commonly for fast and asynchronous + uploading/downloading data from/to GPU. +- **SHARED** specifies a zero copy memory allocation that enables mapping the host memory to GPU + address space, if supported. +- **WRITE_COMBINED** sets the write combined buffer that is not cached by CPU. Such buffers are + used to supply GPU with data when GPU only reads it. The advantage is a better CPU cache + utilization. + +@note Allocation size of such memory types is usually limited. For more details, see *CUDA 2.2 +Pinned Memory APIs* document or *CUDA C Programming Guide*. + */ +class CV_EXPORTS_W HostMem +{ +public: + enum AllocType { PAGE_LOCKED = 1, SHARED = 2, WRITE_COMBINED = 4 }; + + static MatAllocator* getAllocator(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + CV_WRAP explicit HostMem(HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + HostMem(const HostMem& m); + + CV_WRAP HostMem(int rows, int cols, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + CV_WRAP HostMem(Size size, int type, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + //! creates from host memory with coping data + CV_WRAP explicit HostMem(InputArray arr, HostMem::AllocType alloc_type = HostMem::AllocType::PAGE_LOCKED); + + ~HostMem(); + + HostMem& operator =(const HostMem& m); + + //! swaps with other smart pointer + CV_WRAP void swap(HostMem& b); + + //! returns deep copy of the matrix, i.e. the data is copied + CV_WRAP HostMem clone() const; + + //! allocates new matrix data unless the matrix already has specified size and type. + CV_WRAP void create(int rows, int cols, int type); + void create(Size size, int type); + + //! creates alternative HostMem header for the same data, with different + //! number of channels and/or different number of rows + CV_WRAP HostMem reshape(int cn, int rows = 0) const; + + //! decrements reference counter and released memory if needed. + void release(); + + //! returns matrix header with disabled reference counting for HostMem data. + CV_WRAP Mat createMatHeader() const; + + /** @brief Maps CPU memory to GPU address space and creates the cuda::GpuMat header without reference counting + for it. + + This can be done only if memory was allocated with the SHARED flag and if it is supported by the + hardware. Laptops often share video and CPU memory, so address spaces can be mapped, which + eliminates an extra copy. + */ + GpuMat createGpuMatHeader() const; + + // Please see cv::Mat for descriptions + CV_WRAP bool isContinuous() const; + CV_WRAP size_t elemSize() const; + CV_WRAP size_t elemSize1() const; + CV_WRAP int type() const; + CV_WRAP int depth() const; + CV_WRAP int channels() const; + CV_WRAP size_t step1() const; + CV_WRAP Size size() const; + CV_WRAP bool empty() const; + + // Please see cv::Mat for descriptions + int flags; + int rows, cols; + CV_PROP size_t step; + + uchar* data; + int* refcount; + + uchar* datastart; + const uchar* dataend; + + AllocType alloc_type; +}; + +/** @brief Page-locks the memory of matrix and maps it for the device(s). + +@param m Input matrix. + */ +CV_EXPORTS_W void registerPageLocked(Mat& m); + +/** @brief Unmaps the memory of matrix and makes it pageable again. + +@param m Input matrix. + */ +CV_EXPORTS_W void unregisterPageLocked(Mat& m); + +//=================================================================================== +// Stream +//=================================================================================== + +/** @brief This class encapsulates a queue of asynchronous calls. + +@note Currently, you may face problems if an operation is enqueued twice with different data. Some +functions use the constant GPU memory, and next call may update the memory before the previous one +has been finished. But calling different operations asynchronously is safe because each operation +has its own constant buffer. Memory copy/upload/download/set operations to the buffers you hold are +also safe. + +@note The Stream class is not thread-safe. Please use different Stream objects for different CPU threads. + +@code +void thread1() +{ + cv::cuda::Stream stream1; + cv::cuda::func1(..., stream1); +} + +void thread2() +{ + cv::cuda::Stream stream2; + cv::cuda::func2(..., stream2); +} +@endcode + +@note By default all CUDA routines are launched in Stream::Null() object, if the stream is not specified by user. +In multi-threading environment the stream objects must be passed explicitly (see previous note). + */ +class CV_EXPORTS_W Stream +{ + typedef void (Stream::*bool_type)() const; + void this_type_does_not_support_comparisons() const {} + +public: + typedef void (*StreamCallback)(int status, void* userData); + + //! creates a new asynchronous stream + CV_WRAP Stream(); + + //! creates a new asynchronous stream with custom allocator + CV_WRAP Stream(const Ptr& allocator); + + /** @brief creates a new Stream using the cudaFlags argument to determine the behaviors of the stream + + @note The cudaFlags parameter is passed to the underlying api cudaStreamCreateWithFlags() and + supports the same parameter values. + @code + // creates an OpenCV cuda::Stream that manages an asynchronous, non-blocking, + // non-default CUDA stream + cv::cuda::Stream cvStream(cudaStreamNonBlocking); + @endcode + */ + CV_WRAP Stream(const size_t cudaFlags); + + /** @brief Returns true if the current stream queue is finished. Otherwise, it returns false. + */ + CV_WRAP bool queryIfComplete() const; + + /** @brief Blocks the current CPU thread until all operations in the stream are complete. + */ + CV_WRAP void waitForCompletion(); + + /** @brief Makes a compute stream wait on an event. + */ + CV_WRAP void waitEvent(const Event& event); + + /** @brief Adds a callback to be called on the host after all currently enqueued items in the stream have + completed. + + @note Callbacks must not make any CUDA API calls. Callbacks must not perform any synchronization + that may depend on outstanding device work or other callbacks that are not mandated to run earlier. + Callbacks without a mandated order (in independent streams) execute in undefined order and may be + serialized. + */ + void enqueueHostCallback(StreamCallback callback, void* userData); + + //! return Stream object for default CUDA stream + CV_WRAP static Stream& Null(); + + //! returns true if stream object is not default (!= 0) + operator bool_type() const; + + //! return Pointer to CUDA stream + CV_WRAP void* cudaPtr() const; + + class Impl; + +private: + Ptr impl_; + Stream(const Ptr& impl); + + friend struct StreamAccessor; + friend class BufferPool; + friend class DefaultDeviceInitializer; +}; + + +/** @brief Bindings overload to create a Stream object from the address stored in an existing CUDA Runtime API stream pointer (cudaStream_t). +@param cudaStreamMemoryAddress Memory address stored in a CUDA Runtime API stream pointer (cudaStream_t). The created Stream object does not perform any allocation or deallocation and simply wraps existing raw CUDA Runtime API stream pointer. +@note Overload for generation of bindings only, not exported or intended for use internally from C++. + */ +CV_EXPORTS_W Stream wrapStream(size_t cudaStreamMemoryAddress); + +class CV_EXPORTS_W Event +{ +public: + enum CreateFlags + { + DEFAULT = 0x00, /**< Default event flag */ + BLOCKING_SYNC = 0x01, /**< Event uses blocking synchronization */ + DISABLE_TIMING = 0x02, /**< Event will not record timing data */ + INTERPROCESS = 0x04 /**< Event is suitable for interprocess use. DisableTiming must be set */ + }; + + CV_WRAP explicit Event(const Event::CreateFlags flags = Event::CreateFlags::DEFAULT); + + //! records an event + CV_WRAP void record(Stream& stream = Stream::Null()); + + //! queries an event's status + CV_WRAP bool queryIfComplete() const; + + //! waits for an event to complete + CV_WRAP void waitForCompletion(); + + //! computes the elapsed time between events + CV_WRAP static float elapsedTime(const Event& start, const Event& end); + + class Impl; + +private: + Ptr impl_; + Event(const Ptr& impl); + + friend struct EventAccessor; +}; +CV_ENUM_FLAGS(Event::CreateFlags) + +//! @} cudacore_struct + +//=================================================================================== +// Initialization & Info +//=================================================================================== + +//! @addtogroup cudacore_init +//! @{ + +/** @brief Returns the number of installed CUDA-enabled devices. + +Use this function before any other CUDA functions calls. If OpenCV is compiled without CUDA support, +this function returns 0. If the CUDA driver is not installed, or is incompatible, this function +returns -1. + */ +CV_EXPORTS_W int getCudaEnabledDeviceCount(); + +/** @brief Sets a device and initializes it for the current thread. + +@param device System index of a CUDA device starting with 0. + +If the call of this function is omitted, a default device is initialized at the fist CUDA usage. + */ +CV_EXPORTS_W void setDevice(int device); + +/** @brief Returns the current device index set by cuda::setDevice or initialized by default. + */ +CV_EXPORTS_W int getDevice(); + +/** @brief Explicitly destroys and cleans up all resources associated with the current device in the current +process. + +Any subsequent API call to this device will reinitialize the device. + */ +CV_EXPORTS_W void resetDevice(); + +/** @brief Enumeration providing CUDA computing features. + */ +enum FeatureSet +{ + FEATURE_SET_COMPUTE_10 = 10, + FEATURE_SET_COMPUTE_11 = 11, + FEATURE_SET_COMPUTE_12 = 12, + FEATURE_SET_COMPUTE_13 = 13, + FEATURE_SET_COMPUTE_20 = 20, + FEATURE_SET_COMPUTE_21 = 21, + FEATURE_SET_COMPUTE_30 = 30, + FEATURE_SET_COMPUTE_32 = 32, + FEATURE_SET_COMPUTE_35 = 35, + FEATURE_SET_COMPUTE_50 = 50, + + GLOBAL_ATOMICS = FEATURE_SET_COMPUTE_11, + SHARED_ATOMICS = FEATURE_SET_COMPUTE_12, + NATIVE_DOUBLE = FEATURE_SET_COMPUTE_13, + WARP_SHUFFLE_FUNCTIONS = FEATURE_SET_COMPUTE_30, + DYNAMIC_PARALLELISM = FEATURE_SET_COMPUTE_35 +}; + +//! checks whether current device supports the given feature +CV_EXPORTS bool deviceSupports(FeatureSet feature_set); + +/** @brief Class providing a set of static methods to check what NVIDIA\* card architecture the CUDA module was +built for. + +According to the CUDA C Programming Guide Version 3.2: "PTX code produced for some specific compute +capability can always be compiled to binary code of greater or equal compute capability". + */ +class CV_EXPORTS_W TargetArchs +{ +public: + /** @brief The following method checks whether the module was built with the support of the given feature: + + @param feature_set Features to be checked. See :ocvcuda::FeatureSet. + */ + static bool builtWith(FeatureSet feature_set); + + /** @brief There is a set of methods to check whether the module contains intermediate (PTX) or binary CUDA + code for the given architecture(s): + + @param major Major compute capability version. + @param minor Minor compute capability version. + */ + CV_WRAP static bool has(int major, int minor); + CV_WRAP static bool hasPtx(int major, int minor); + CV_WRAP static bool hasBin(int major, int minor); + + CV_WRAP static bool hasEqualOrLessPtx(int major, int minor); + CV_WRAP static bool hasEqualOrGreater(int major, int minor); + CV_WRAP static bool hasEqualOrGreaterPtx(int major, int minor); + CV_WRAP static bool hasEqualOrGreaterBin(int major, int minor); +}; + +/** @brief Class providing functionality for querying the specified GPU properties. + */ +class CV_EXPORTS_W DeviceInfo +{ +public: + //! creates DeviceInfo object for the current GPU + CV_WRAP DeviceInfo(); + + /** @brief The constructors. + + @param device_id System index of the CUDA device starting with 0. + + Constructs the DeviceInfo object for the specified device. If device_id parameter is missed, it + constructs an object for the current device. + */ + CV_WRAP DeviceInfo(int device_id); + + /** @brief Returns system index of the CUDA device starting with 0. + */ + CV_WRAP int deviceID() const; + + //! ASCII string identifying device + const char* name() const; + + //! global memory available on device in bytes + CV_WRAP size_t totalGlobalMem() const; + + //! shared memory available per block in bytes + CV_WRAP size_t sharedMemPerBlock() const; + + //! 32-bit registers available per block + CV_WRAP int regsPerBlock() const; + + //! warp size in threads + CV_WRAP int warpSize() const; + + //! maximum pitch in bytes allowed by memory copies + CV_WRAP size_t memPitch() const; + + //! maximum number of threads per block + CV_WRAP int maxThreadsPerBlock() const; + + //! maximum size of each dimension of a block + CV_WRAP Vec3i maxThreadsDim() const; + + //! maximum size of each dimension of a grid + CV_WRAP Vec3i maxGridSize() const; + + //! clock frequency in kilohertz + CV_WRAP int clockRate() const; + + //! constant memory available on device in bytes + CV_WRAP size_t totalConstMem() const; + + //! major compute capability + CV_WRAP int majorVersion() const; + + //! minor compute capability + CV_WRAP int minorVersion() const; + + //! alignment requirement for textures + CV_WRAP size_t textureAlignment() const; + + //! pitch alignment requirement for texture references bound to pitched memory + CV_WRAP size_t texturePitchAlignment() const; + + //! number of multiprocessors on device + CV_WRAP int multiProcessorCount() const; + + //! specified whether there is a run time limit on kernels + CV_WRAP bool kernelExecTimeoutEnabled() const; + + //! device is integrated as opposed to discrete + CV_WRAP bool integrated() const; + + //! device can map host memory with cudaHostAlloc/cudaHostGetDevicePointer + CV_WRAP bool canMapHostMemory() const; + + enum ComputeMode + { + ComputeModeDefault, /**< default compute mode (Multiple threads can use cudaSetDevice with this device) */ + ComputeModeExclusive, /**< compute-exclusive-thread mode (Only one thread in one process will be able to use cudaSetDevice with this device) */ + ComputeModeProhibited, /**< compute-prohibited mode (No threads can use cudaSetDevice with this device) */ + ComputeModeExclusiveProcess /**< compute-exclusive-process mode (Many threads in one process will be able to use cudaSetDevice with this device) */ + }; + + //! compute mode + CV_WRAP DeviceInfo::ComputeMode computeMode() const; + + //! maximum 1D texture size + CV_WRAP int maxTexture1D() const; + + //! maximum 1D mipmapped texture size + CV_WRAP int maxTexture1DMipmap() const; + + //! maximum size for 1D textures bound to linear memory + CV_WRAP int maxTexture1DLinear() const; + + //! maximum 2D texture dimensions + CV_WRAP Vec2i maxTexture2D() const; + + //! maximum 2D mipmapped texture dimensions + CV_WRAP Vec2i maxTexture2DMipmap() const; + + //! maximum dimensions (width, height, pitch) for 2D textures bound to pitched memory + CV_WRAP Vec3i maxTexture2DLinear() const; + + //! maximum 2D texture dimensions if texture gather operations have to be performed + CV_WRAP Vec2i maxTexture2DGather() const; + + //! maximum 3D texture dimensions + CV_WRAP Vec3i maxTexture3D() const; + + //! maximum Cubemap texture dimensions + CV_WRAP int maxTextureCubemap() const; + + //! maximum 1D layered texture dimensions + CV_WRAP Vec2i maxTexture1DLayered() const; + + //! maximum 2D layered texture dimensions + CV_WRAP Vec3i maxTexture2DLayered() const; + + //! maximum Cubemap layered texture dimensions + CV_WRAP Vec2i maxTextureCubemapLayered() const; + + //! maximum 1D surface size + CV_WRAP int maxSurface1D() const; + + //! maximum 2D surface dimensions + CV_WRAP Vec2i maxSurface2D() const; + + //! maximum 3D surface dimensions + CV_WRAP Vec3i maxSurface3D() const; + + //! maximum 1D layered surface dimensions + CV_WRAP Vec2i maxSurface1DLayered() const; + + //! maximum 2D layered surface dimensions + CV_WRAP Vec3i maxSurface2DLayered() const; + + //! maximum Cubemap surface dimensions + CV_WRAP int maxSurfaceCubemap() const; + + //! maximum Cubemap layered surface dimensions + CV_WRAP Vec2i maxSurfaceCubemapLayered() const; + + //! alignment requirements for surfaces + CV_WRAP size_t surfaceAlignment() const; + + //! device can possibly execute multiple kernels concurrently + CV_WRAP bool concurrentKernels() const; + + //! device has ECC support enabled + CV_WRAP bool ECCEnabled() const; + + //! PCI bus ID of the device + CV_WRAP int pciBusID() const; + + //! PCI device ID of the device + CV_WRAP int pciDeviceID() const; + + //! PCI domain ID of the device + CV_WRAP int pciDomainID() const; + + //! true if device is a Tesla device using TCC driver, false otherwise + CV_WRAP bool tccDriver() const; + + //! number of asynchronous engines + CV_WRAP int asyncEngineCount() const; + + //! device shares a unified address space with the host + CV_WRAP bool unifiedAddressing() const; + + //! peak memory clock frequency in kilohertz + CV_WRAP int memoryClockRate() const; + + //! global memory bus width in bits + CV_WRAP int memoryBusWidth() const; + + //! size of L2 cache in bytes + CV_WRAP int l2CacheSize() const; + + //! maximum resident threads per multiprocessor + CV_WRAP int maxThreadsPerMultiProcessor() const; + + //! gets free and total device memory + CV_WRAP void queryMemory(size_t& totalMemory, size_t& freeMemory) const; + CV_WRAP size_t freeMemory() const; + CV_WRAP size_t totalMemory() const; + + /** @brief Provides information on CUDA feature support. + + @param feature_set Features to be checked. See cuda::FeatureSet. + + This function returns true if the device has the specified CUDA feature. Otherwise, it returns false + */ + bool supports(FeatureSet feature_set) const; + + /** @brief Checks the CUDA module and device compatibility. + + This function returns true if the CUDA module can be run on the specified device. Otherwise, it + returns false . + */ + CV_WRAP bool isCompatible() const; + +private: + int device_id_; +}; + +CV_EXPORTS_W void printCudaDeviceInfo(int device); +CV_EXPORTS_W void printShortCudaDeviceInfo(int device); + +/** @brief Converts an array to half precision floating number. + +@param _src input array. +@param _dst output array. +@param stream Stream for the asynchronous version. +@sa convertFp16 +*/ +CV_EXPORTS void convertFp16(InputArray _src, OutputArray _dst, Stream& stream = Stream::Null()); + +//! @} cudacore_init + +}} // namespace cv { namespace cuda { + + +#include "opencv2/core/cuda.inl.hpp" + +#endif /* OPENCV_CORE_CUDA_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp index 9eae299806..9390b3a529 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda.inl.hpp @@ -1,763 +1,763 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CUDAINL_HPP -#define OPENCV_CORE_CUDAINL_HPP - -#include "opencv2/core/cuda.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { - -//=================================================================================== -// GpuMat -//=================================================================================== - -inline -GpuMat::GpuMat(Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{} - -inline -GpuMat::GpuMat(int rows_, int cols_, int type_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (rows_ > 0 && cols_ > 0) - create(rows_, cols_, type_); -} - -inline -GpuMat::GpuMat(Size size_, int type_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (size_.height > 0 && size_.width > 0) - create(size_.height, size_.width, type_); -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -GpuMat::GpuMat(int rows_, int cols_, int type_, Scalar s_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (rows_ > 0 && cols_ > 0) - { - create(rows_, cols_, type_); - setTo(s_); - } -} - -inline -GpuMat::GpuMat(Size size_, int type_, Scalar s_, Allocator* allocator_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - if (size_.height > 0 && size_.width > 0) - { - create(size_.height, size_.width, type_); - setTo(s_); - } -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -GpuMat::GpuMat(const GpuMat& m) - : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), allocator(m.allocator) -{ - if (refcount) - CV_XADD(refcount, 1); -} - -inline -GpuMat::GpuMat(InputArray arr, Allocator* allocator_) : - flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) -{ - upload(arr); -} - -inline -GpuMat::~GpuMat() -{ - release(); -} - -inline -GpuMat& GpuMat::operator =(const GpuMat& m) -{ - if (this != &m) - { - GpuMat temp(m); - swap(temp); - } - - return *this; -} - -inline -void GpuMat::create(Size size_, int type_) -{ - create(size_.height, size_.width, type_); -} - -inline -void GpuMat::swap(GpuMat& b) -{ - std::swap(flags, b.flags); - std::swap(rows, b.rows); - std::swap(cols, b.cols); - std::swap(step, b.step); - std::swap(data, b.data); - std::swap(datastart, b.datastart); - std::swap(dataend, b.dataend); - std::swap(refcount, b.refcount); - std::swap(allocator, b.allocator); -} - -inline -GpuMat GpuMat::clone() const -{ - GpuMat m; - copyTo(m); - return m; -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -void GpuMat::copyTo(OutputArray dst, InputArray mask) const -{ - copyTo(dst, mask, Stream::Null()); -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -GpuMat& GpuMat::setTo(Scalar s) -{ - return setTo(s, Stream::Null()); -} - -inline -GpuMat& GpuMat::setTo(Scalar s, InputArray mask) -{ - return setTo(s, mask, Stream::Null()); -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -void GpuMat::convertTo(OutputArray dst, int rtype) const -{ - convertTo(dst, rtype, Stream::Null()); -} - -inline -void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, double beta) const -{ - convertTo(dst, rtype, alpha, beta, Stream::Null()); -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const -{ - convertTo(dst, rtype, alpha, 0.0, stream); -} - -inline -void GpuMat::assignTo(GpuMat& m, int _type) const -{ - if (_type < 0) - m = *this; - else - convertTo(m, _type); -} - -inline -uchar* GpuMat::ptr(int y) -{ - CV_DbgAssert( (unsigned)y < (unsigned)rows ); - return data + step * y; -} - -inline -const uchar* GpuMat::ptr(int y) const -{ - CV_DbgAssert( (unsigned)y < (unsigned)rows ); - return data + step * y; -} - -template inline -_Tp* GpuMat::ptr(int y) -{ - return (_Tp*)ptr(y); -} - -template inline -const _Tp* GpuMat::ptr(int y) const -{ - return (const _Tp*)ptr(y); -} - -template inline -GpuMat::operator PtrStepSz() const -{ - return PtrStepSz(rows, cols, (T*)data, step); -} - -template inline -GpuMat::operator PtrStep() const -{ - return PtrStep((T*)data, step); -} - -inline -GpuMat GpuMat::row(int y) const -{ - return GpuMat(*this, Range(y, y+1), Range::all()); -} - -inline -GpuMat GpuMat::col(int x) const -{ - return GpuMat(*this, Range::all(), Range(x, x+1)); -} - -inline -GpuMat GpuMat::rowRange(int startrow, int endrow) const -{ - return GpuMat(*this, Range(startrow, endrow), Range::all()); -} - -inline -GpuMat GpuMat::rowRange(Range r) const -{ - return GpuMat(*this, r, Range::all()); -} - -inline -GpuMat GpuMat::colRange(int startcol, int endcol) const -{ - return GpuMat(*this, Range::all(), Range(startcol, endcol)); -} - -inline -GpuMat GpuMat::colRange(Range r) const -{ - return GpuMat(*this, Range::all(), r); -} - -inline -GpuMat GpuMat::operator ()(Range rowRange_, Range colRange_) const -{ - return GpuMat(*this, rowRange_, colRange_); -} - -inline -GpuMat GpuMat::operator ()(Rect roi) const -{ - return GpuMat(*this, roi); -} - -inline -bool GpuMat::isContinuous() const -{ - return (flags & Mat::CONTINUOUS_FLAG) != 0; -} - -inline -size_t GpuMat::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t GpuMat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int GpuMat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int GpuMat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int GpuMat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -size_t GpuMat::step1() const -{ - return step / elemSize1(); -} - -inline -Size GpuMat::size() const -{ - return Size(cols, rows); -} - -inline -bool GpuMat::empty() const -{ - return data == 0; -} - -inline -void* GpuMat::cudaPtr() const -{ - return data; -} - -static inline -GpuMat createContinuous(int rows, int cols, int type) -{ - GpuMat m; - createContinuous(rows, cols, type, m); - return m; -} - -static inline -void createContinuous(Size size, int type, OutputArray arr) -{ - createContinuous(size.height, size.width, type, arr); -} - -static inline -GpuMat createContinuous(Size size, int type) -{ - GpuMat m; - createContinuous(size, type, m); - return m; -} - -static inline -void ensureSizeIsEnough(Size size, int type, OutputArray arr) -{ - ensureSizeIsEnough(size.height, size.width, type, arr); -} - -static inline -void swap(GpuMat& a, GpuMat& b) -{ - a.swap(b); -} - -//=================================================================================== -// GpuMatND -//=================================================================================== - -inline -GpuMatND::GpuMatND() : - flags(0), dims(0), data(nullptr), offset(0) -{ -} - -inline -GpuMatND::GpuMatND(SizeArray _size, int _type) : - flags(0), dims(0), data(nullptr), offset(0) -{ - create(std::move(_size), _type); -} - -inline -void GpuMatND::swap(GpuMatND& m) noexcept -{ - std::swap(*this, m); -} - -inline -bool GpuMatND::isContinuous() const -{ - return (flags & Mat::CONTINUOUS_FLAG) != 0; -} - -inline -bool GpuMatND::isSubmatrix() const -{ - return (flags & Mat::SUBMATRIX_FLAG) != 0; -} - -inline -size_t GpuMatND::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t GpuMatND::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -bool GpuMatND::empty() const -{ - return data == nullptr; -} - -inline -bool GpuMatND::external() const -{ - return !empty() && data_.use_count() == 0; -} - -inline -uchar* GpuMatND::getDevicePtr() const -{ - return data + offset; -} - -inline -size_t GpuMatND::total() const -{ - size_t p = 1; - for(auto s : size) - p *= s; - return p; -} - -inline -size_t GpuMatND::totalMemSize() const -{ - return size[0] * step[0]; -} - -inline -int GpuMatND::type() const -{ - return CV_MAT_TYPE(flags); -} - -//=================================================================================== -// HostMem -//=================================================================================== - -inline -HostMem::HostMem(AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ -} - -inline -HostMem::HostMem(const HostMem& m) - : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type) -{ - if( refcount ) - CV_XADD(refcount, 1); -} - -inline -HostMem::HostMem(int rows_, int cols_, int type_, AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ - if (rows_ > 0 && cols_ > 0) - create(rows_, cols_, type_); -} - -inline -HostMem::HostMem(Size size_, int type_, AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ - if (size_.height > 0 && size_.width > 0) - create(size_.height, size_.width, type_); -} - -inline -HostMem::HostMem(InputArray arr, AllocType alloc_type_) - : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) -{ - arr.getMat().copyTo(*this); -} - -inline -HostMem::~HostMem() -{ - release(); -} - -inline -HostMem& HostMem::operator =(const HostMem& m) -{ - if (this != &m) - { - HostMem temp(m); - swap(temp); - } - - return *this; -} - -inline -void HostMem::swap(HostMem& b) -{ - std::swap(flags, b.flags); - std::swap(rows, b.rows); - std::swap(cols, b.cols); - std::swap(step, b.step); - std::swap(data, b.data); - std::swap(datastart, b.datastart); - std::swap(dataend, b.dataend); - std::swap(refcount, b.refcount); - std::swap(alloc_type, b.alloc_type); -} - -inline -HostMem HostMem::clone() const -{ - HostMem m(size(), type(), alloc_type); - createMatHeader().copyTo(m); - return m; -} - -inline -void HostMem::create(Size size_, int type_) -{ - create(size_.height, size_.width, type_); -} - -inline -Mat HostMem::createMatHeader() const -{ - return Mat(size(), type(), data, step); -} - -inline -bool HostMem::isContinuous() const -{ - return (flags & Mat::CONTINUOUS_FLAG) != 0; -} - -inline -size_t HostMem::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t HostMem::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int HostMem::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int HostMem::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int HostMem::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -size_t HostMem::step1() const -{ - return step / elemSize1(); -} - -inline -Size HostMem::size() const -{ - return Size(cols, rows); -} - -inline -bool HostMem::empty() const -{ - return data == 0; -} - -static inline -void swap(HostMem& a, HostMem& b) -{ - a.swap(b); -} - -//=================================================================================== -// Stream -//=================================================================================== - -inline -Stream::Stream(const Ptr& impl) - : impl_(impl) -{ -} - -//=================================================================================== -// Event -//=================================================================================== - -inline -Event::Event(const Ptr& impl) - : impl_(impl) -{ -} - -//=================================================================================== -// Initialization & Info -//=================================================================================== - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -bool TargetArchs::has(int major, int minor) -{ - return hasPtx(major, minor) || hasBin(major, minor); -} - -inline -bool TargetArchs::hasEqualOrGreater(int major, int minor) -{ - return hasEqualOrGreaterPtx(major, minor) || hasEqualOrGreaterBin(major, minor); -} - -inline -DeviceInfo::DeviceInfo() -{ - device_id_ = getDevice(); -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -DeviceInfo::DeviceInfo(int device_id) -{ - CV_Assert( device_id >= 0 && device_id < getCudaEnabledDeviceCount() ); - device_id_ = device_id; -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -int DeviceInfo::deviceID() const -{ - return device_id_; -} - -inline -size_t DeviceInfo::freeMemory() const -{ - size_t _totalMemory = 0, _freeMemory = 0; - queryMemory(_totalMemory, _freeMemory); - return _freeMemory; -} - -inline -size_t DeviceInfo::totalMemory() const -{ - size_t _totalMemory = 0, _freeMemory = 0; - queryMemory(_totalMemory, _freeMemory); - return _totalMemory; -} - -inline -bool DeviceInfo::supports(FeatureSet feature_set) const -{ - int version = majorVersion() * 10 + minorVersion(); - return version >= feature_set; -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - -}} // namespace cv { namespace cuda { - -//=================================================================================== -// Mat -//=================================================================================== - -namespace cv { - -inline -Mat::Mat(const cuda::GpuMat& m) - : flags(0), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) -{ - m.download(*this); -} - -} - -//! @endcond - -#endif // OPENCV_CORE_CUDAINL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CUDAINL_HPP +#define OPENCV_CORE_CUDAINL_HPP + +#include "opencv2/core/cuda.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { + +//=================================================================================== +// GpuMat +//=================================================================================== + +inline +GpuMat::GpuMat(Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{} + +inline +GpuMat::GpuMat(int rows_, int cols_, int type_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (rows_ > 0 && cols_ > 0) + create(rows_, cols_, type_); +} + +inline +GpuMat::GpuMat(Size size_, int type_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (size_.height > 0 && size_.width > 0) + create(size_.height, size_.width, type_); +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +GpuMat::GpuMat(int rows_, int cols_, int type_, Scalar s_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (rows_ > 0 && cols_ > 0) + { + create(rows_, cols_, type_); + setTo(s_); + } +} + +inline +GpuMat::GpuMat(Size size_, int type_, Scalar s_, Allocator* allocator_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + if (size_.height > 0 && size_.width > 0) + { + create(size_.height, size_.width, type_); + setTo(s_); + } +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +GpuMat::GpuMat(const GpuMat& m) + : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), allocator(m.allocator) +{ + if (refcount) + CV_XADD(refcount, 1); +} + +inline +GpuMat::GpuMat(InputArray arr, Allocator* allocator_) : + flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), allocator(allocator_) +{ + upload(arr); +} + +inline +GpuMat::~GpuMat() +{ + release(); +} + +inline +GpuMat& GpuMat::operator =(const GpuMat& m) +{ + if (this != &m) + { + GpuMat temp(m); + swap(temp); + } + + return *this; +} + +inline +void GpuMat::create(Size size_, int type_) +{ + create(size_.height, size_.width, type_); +} + +inline +void GpuMat::swap(GpuMat& b) +{ + std::swap(flags, b.flags); + std::swap(rows, b.rows); + std::swap(cols, b.cols); + std::swap(step, b.step); + std::swap(data, b.data); + std::swap(datastart, b.datastart); + std::swap(dataend, b.dataend); + std::swap(refcount, b.refcount); + std::swap(allocator, b.allocator); +} + +inline +GpuMat GpuMat::clone() const +{ + GpuMat m; + copyTo(m); + return m; +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +void GpuMat::copyTo(OutputArray dst, InputArray mask) const +{ + copyTo(dst, mask, Stream::Null()); +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +GpuMat& GpuMat::setTo(Scalar s) +{ + return setTo(s, Stream::Null()); +} + +inline +GpuMat& GpuMat::setTo(Scalar s, InputArray mask) +{ + return setTo(s, mask, Stream::Null()); +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +void GpuMat::convertTo(OutputArray dst, int rtype) const +{ + convertTo(dst, rtype, Stream::Null()); +} + +inline +void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, double beta) const +{ + convertTo(dst, rtype, alpha, beta, Stream::Null()); +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +void GpuMat::convertTo(OutputArray dst, int rtype, double alpha, Stream& stream) const +{ + convertTo(dst, rtype, alpha, 0.0, stream); +} + +inline +void GpuMat::assignTo(GpuMat& m, int _type) const +{ + if (_type < 0) + m = *this; + else + convertTo(m, _type); +} + +inline +uchar* GpuMat::ptr(int y) +{ + CV_DbgAssert( (unsigned)y < (unsigned)rows ); + return data + step * y; +} + +inline +const uchar* GpuMat::ptr(int y) const +{ + CV_DbgAssert( (unsigned)y < (unsigned)rows ); + return data + step * y; +} + +template inline +_Tp* GpuMat::ptr(int y) +{ + return (_Tp*)ptr(y); +} + +template inline +const _Tp* GpuMat::ptr(int y) const +{ + return (const _Tp*)ptr(y); +} + +template inline +GpuMat::operator PtrStepSz() const +{ + return PtrStepSz(rows, cols, (T*)data, step); +} + +template inline +GpuMat::operator PtrStep() const +{ + return PtrStep((T*)data, step); +} + +inline +GpuMat GpuMat::row(int y) const +{ + return GpuMat(*this, Range(y, y+1), Range::all()); +} + +inline +GpuMat GpuMat::col(int x) const +{ + return GpuMat(*this, Range::all(), Range(x, x+1)); +} + +inline +GpuMat GpuMat::rowRange(int startrow, int endrow) const +{ + return GpuMat(*this, Range(startrow, endrow), Range::all()); +} + +inline +GpuMat GpuMat::rowRange(Range r) const +{ + return GpuMat(*this, r, Range::all()); +} + +inline +GpuMat GpuMat::colRange(int startcol, int endcol) const +{ + return GpuMat(*this, Range::all(), Range(startcol, endcol)); +} + +inline +GpuMat GpuMat::colRange(Range r) const +{ + return GpuMat(*this, Range::all(), r); +} + +inline +GpuMat GpuMat::operator ()(Range rowRange_, Range colRange_) const +{ + return GpuMat(*this, rowRange_, colRange_); +} + +inline +GpuMat GpuMat::operator ()(Rect roi) const +{ + return GpuMat(*this, roi); +} + +inline +bool GpuMat::isContinuous() const +{ + return (flags & Mat::CONTINUOUS_FLAG) != 0; +} + +inline +size_t GpuMat::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t GpuMat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int GpuMat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int GpuMat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int GpuMat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +size_t GpuMat::step1() const +{ + return step / elemSize1(); +} + +inline +Size GpuMat::size() const +{ + return Size(cols, rows); +} + +inline +bool GpuMat::empty() const +{ + return data == 0; +} + +inline +void* GpuMat::cudaPtr() const +{ + return data; +} + +static inline +GpuMat createContinuous(int rows, int cols, int type) +{ + GpuMat m; + createContinuous(rows, cols, type, m); + return m; +} + +static inline +void createContinuous(Size size, int type, OutputArray arr) +{ + createContinuous(size.height, size.width, type, arr); +} + +static inline +GpuMat createContinuous(Size size, int type) +{ + GpuMat m; + createContinuous(size, type, m); + return m; +} + +static inline +void ensureSizeIsEnough(Size size, int type, OutputArray arr) +{ + ensureSizeIsEnough(size.height, size.width, type, arr); +} + +static inline +void swap(GpuMat& a, GpuMat& b) +{ + a.swap(b); +} + +//=================================================================================== +// GpuMatND +//=================================================================================== + +inline +GpuMatND::GpuMatND() : + flags(0), dims(0), data(nullptr), offset(0) +{ +} + +inline +GpuMatND::GpuMatND(SizeArray _size, int _type) : + flags(0), dims(0), data(nullptr), offset(0) +{ + create(std::move(_size), _type); +} + +inline +void GpuMatND::swap(GpuMatND& m) noexcept +{ + std::swap(*this, m); +} + +inline +bool GpuMatND::isContinuous() const +{ + return (flags & Mat::CONTINUOUS_FLAG) != 0; +} + +inline +bool GpuMatND::isSubmatrix() const +{ + return (flags & Mat::SUBMATRIX_FLAG) != 0; +} + +inline +size_t GpuMatND::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t GpuMatND::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +bool GpuMatND::empty() const +{ + return data == nullptr; +} + +inline +bool GpuMatND::external() const +{ + return !empty() && data_.use_count() == 0; +} + +inline +uchar* GpuMatND::getDevicePtr() const +{ + return data + offset; +} + +inline +size_t GpuMatND::total() const +{ + size_t p = 1; + for(auto s : size) + p *= s; + return p; +} + +inline +size_t GpuMatND::totalMemSize() const +{ + return size[0] * step[0]; +} + +inline +int GpuMatND::type() const +{ + return CV_MAT_TYPE(flags); +} + +//=================================================================================== +// HostMem +//=================================================================================== + +inline +HostMem::HostMem(AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ +} + +inline +HostMem::HostMem(const HostMem& m) + : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type) +{ + if( refcount ) + CV_XADD(refcount, 1); +} + +inline +HostMem::HostMem(int rows_, int cols_, int type_, AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ + if (rows_ > 0 && cols_ > 0) + create(rows_, cols_, type_); +} + +inline +HostMem::HostMem(Size size_, int type_, AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ + if (size_.height > 0 && size_.width > 0) + create(size_.height, size_.width, type_); +} + +inline +HostMem::HostMem(InputArray arr, AllocType alloc_type_) + : flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(alloc_type_) +{ + arr.getMat().copyTo(*this); +} + +inline +HostMem::~HostMem() +{ + release(); +} + +inline +HostMem& HostMem::operator =(const HostMem& m) +{ + if (this != &m) + { + HostMem temp(m); + swap(temp); + } + + return *this; +} + +inline +void HostMem::swap(HostMem& b) +{ + std::swap(flags, b.flags); + std::swap(rows, b.rows); + std::swap(cols, b.cols); + std::swap(step, b.step); + std::swap(data, b.data); + std::swap(datastart, b.datastart); + std::swap(dataend, b.dataend); + std::swap(refcount, b.refcount); + std::swap(alloc_type, b.alloc_type); +} + +inline +HostMem HostMem::clone() const +{ + HostMem m(size(), type(), alloc_type); + createMatHeader().copyTo(m); + return m; +} + +inline +void HostMem::create(Size size_, int type_) +{ + create(size_.height, size_.width, type_); +} + +inline +Mat HostMem::createMatHeader() const +{ + return Mat(size(), type(), data, step); +} + +inline +bool HostMem::isContinuous() const +{ + return (flags & Mat::CONTINUOUS_FLAG) != 0; +} + +inline +size_t HostMem::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t HostMem::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int HostMem::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int HostMem::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int HostMem::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +size_t HostMem::step1() const +{ + return step / elemSize1(); +} + +inline +Size HostMem::size() const +{ + return Size(cols, rows); +} + +inline +bool HostMem::empty() const +{ + return data == 0; +} + +static inline +void swap(HostMem& a, HostMem& b) +{ + a.swap(b); +} + +//=================================================================================== +// Stream +//=================================================================================== + +inline +Stream::Stream(const Ptr& impl) + : impl_(impl) +{ +} + +//=================================================================================== +// Event +//=================================================================================== + +inline +Event::Event(const Ptr& impl) + : impl_(impl) +{ +} + +//=================================================================================== +// Initialization & Info +//=================================================================================== + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +bool TargetArchs::has(int major, int minor) +{ + return hasPtx(major, minor) || hasBin(major, minor); +} + +inline +bool TargetArchs::hasEqualOrGreater(int major, int minor) +{ + return hasEqualOrGreaterPtx(major, minor) || hasEqualOrGreaterBin(major, minor); +} + +inline +DeviceInfo::DeviceInfo() +{ + device_id_ = getDevice(); +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +DeviceInfo::DeviceInfo(int device_id) +{ + CV_Assert( device_id >= 0 && device_id < getCudaEnabledDeviceCount() ); + device_id_ = device_id; +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +int DeviceInfo::deviceID() const +{ + return device_id_; +} + +inline +size_t DeviceInfo::freeMemory() const +{ + size_t _totalMemory = 0, _freeMemory = 0; + queryMemory(_totalMemory, _freeMemory); + return _freeMemory; +} + +inline +size_t DeviceInfo::totalMemory() const +{ + size_t _totalMemory = 0, _freeMemory = 0; + queryMemory(_totalMemory, _freeMemory); + return _totalMemory; +} + +inline +bool DeviceInfo::supports(FeatureSet feature_set) const +{ + int version = majorVersion() * 10 + minorVersion(); + return version >= feature_set; +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + +}} // namespace cv { namespace cuda { + +//=================================================================================== +// Mat +//=================================================================================== + +namespace cv { + +inline +Mat::Mat(const cuda::GpuMat& m) + : flags(0), dims(0), rows(0), cols(0), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows) +{ + m.download(*this); +} + +} + +//! @endcond + +#endif // OPENCV_CORE_CUDAINL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp index f64d9edd69..c277f0ea9c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/block.hpp @@ -1,211 +1,211 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_DEVICE_BLOCK_HPP -#define OPENCV_CUDA_DEVICE_BLOCK_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct Block - { - static __device__ __forceinline__ unsigned int id() - { - return blockIdx.x; - } - - static __device__ __forceinline__ unsigned int stride() - { - return blockDim.x * blockDim.y * blockDim.z; - } - - static __device__ __forceinline__ void sync() - { - __syncthreads(); - } - - static __device__ __forceinline__ int flattenedThreadId() - { - return threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; - } - - template - static __device__ __forceinline__ void fill(It beg, It end, const T& value) - { - int STRIDE = stride(); - It t = beg + flattenedThreadId(); - - for(; t < end; t += STRIDE) - *t = value; - } - - template - static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) - { - int STRIDE = stride(); - int tid = flattenedThreadId(); - value += tid; - - for(OutIt t = beg + tid; t < end; t += STRIDE, value += STRIDE) - *t = value; - } - - template - static __device__ __forceinline__ void copy(InIt beg, InIt end, OutIt out) - { - int STRIDE = stride(); - InIt t = beg + flattenedThreadId(); - OutIt o = out + (t - beg); - - for(; t < end; t += STRIDE, o += STRIDE) - *o = *t; - } - - template - static __device__ __forceinline__ void transform(InIt beg, InIt end, OutIt out, UnOp op) - { - int STRIDE = stride(); - InIt t = beg + flattenedThreadId(); - OutIt o = out + (t - beg); - - for(; t < end; t += STRIDE, o += STRIDE) - *o = op(*t); - } - - template - static __device__ __forceinline__ void transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) - { - int STRIDE = stride(); - InIt1 t1 = beg1 + flattenedThreadId(); - InIt2 t2 = beg2 + flattenedThreadId(); - OutIt o = out + (t1 - beg1); - - for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, o += STRIDE) - *o = op(*t1, *t2); - } - - template - static __device__ __forceinline__ void reduce(volatile T* buffer, BinOp op) - { - int tid = flattenedThreadId(); - T val = buffer[tid]; - - if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } - if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } - if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } - if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } - - if (tid < 32) - { - if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } - if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } - if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } - if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } - if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } - if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } - } - } - - template - static __device__ __forceinline__ T reduce(volatile T* buffer, T init, BinOp op) - { - int tid = flattenedThreadId(); - T val = buffer[tid] = init; - __syncthreads(); - - if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } - if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } - if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } - if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } - - if (tid < 32) - { - if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } - if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } - if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } - if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } - if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } - if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } - } - __syncthreads(); - return buffer[0]; - } - - template - static __device__ __forceinline__ void reduce_n(T* data, unsigned int n, BinOp op) - { - int ftid = flattenedThreadId(); - int sft = stride(); - - if (sft < n) - { - for (unsigned int i = sft + ftid; i < n; i += sft) - data[ftid] = op(data[ftid], data[i]); - - __syncthreads(); - - n = sft; - } - - while (n > 1) - { - unsigned int half = n/2; - - if (ftid < half) - data[ftid] = op(data[ftid], data[n - ftid - 1]); - - __syncthreads(); - - n = n - half; - } - } - }; -}}} - -//! @endcond - -#endif /* OPENCV_CUDA_DEVICE_BLOCK_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_DEVICE_BLOCK_HPP +#define OPENCV_CUDA_DEVICE_BLOCK_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct Block + { + static __device__ __forceinline__ unsigned int id() + { + return blockIdx.x; + } + + static __device__ __forceinline__ unsigned int stride() + { + return blockDim.x * blockDim.y * blockDim.z; + } + + static __device__ __forceinline__ void sync() + { + __syncthreads(); + } + + static __device__ __forceinline__ int flattenedThreadId() + { + return threadIdx.z * blockDim.x * blockDim.y + threadIdx.y * blockDim.x + threadIdx.x; + } + + template + static __device__ __forceinline__ void fill(It beg, It end, const T& value) + { + int STRIDE = stride(); + It t = beg + flattenedThreadId(); + + for(; t < end; t += STRIDE) + *t = value; + } + + template + static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) + { + int STRIDE = stride(); + int tid = flattenedThreadId(); + value += tid; + + for(OutIt t = beg + tid; t < end; t += STRIDE, value += STRIDE) + *t = value; + } + + template + static __device__ __forceinline__ void copy(InIt beg, InIt end, OutIt out) + { + int STRIDE = stride(); + InIt t = beg + flattenedThreadId(); + OutIt o = out + (t - beg); + + for(; t < end; t += STRIDE, o += STRIDE) + *o = *t; + } + + template + static __device__ __forceinline__ void transform(InIt beg, InIt end, OutIt out, UnOp op) + { + int STRIDE = stride(); + InIt t = beg + flattenedThreadId(); + OutIt o = out + (t - beg); + + for(; t < end; t += STRIDE, o += STRIDE) + *o = op(*t); + } + + template + static __device__ __forceinline__ void transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) + { + int STRIDE = stride(); + InIt1 t1 = beg1 + flattenedThreadId(); + InIt2 t2 = beg2 + flattenedThreadId(); + OutIt o = out + (t1 - beg1); + + for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, o += STRIDE) + *o = op(*t1, *t2); + } + + template + static __device__ __forceinline__ void reduce(volatile T* buffer, BinOp op) + { + int tid = flattenedThreadId(); + T val = buffer[tid]; + + if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } + if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } + if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } + if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } + + if (tid < 32) + { + if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } + if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } + if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } + if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } + if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } + if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } + } + } + + template + static __device__ __forceinline__ T reduce(volatile T* buffer, T init, BinOp op) + { + int tid = flattenedThreadId(); + T val = buffer[tid] = init; + __syncthreads(); + + if (CTA_SIZE >= 1024) { if (tid < 512) buffer[tid] = val = op(val, buffer[tid + 512]); __syncthreads(); } + if (CTA_SIZE >= 512) { if (tid < 256) buffer[tid] = val = op(val, buffer[tid + 256]); __syncthreads(); } + if (CTA_SIZE >= 256) { if (tid < 128) buffer[tid] = val = op(val, buffer[tid + 128]); __syncthreads(); } + if (CTA_SIZE >= 128) { if (tid < 64) buffer[tid] = val = op(val, buffer[tid + 64]); __syncthreads(); } + + if (tid < 32) + { + if (CTA_SIZE >= 64) { buffer[tid] = val = op(val, buffer[tid + 32]); } + if (CTA_SIZE >= 32) { buffer[tid] = val = op(val, buffer[tid + 16]); } + if (CTA_SIZE >= 16) { buffer[tid] = val = op(val, buffer[tid + 8]); } + if (CTA_SIZE >= 8) { buffer[tid] = val = op(val, buffer[tid + 4]); } + if (CTA_SIZE >= 4) { buffer[tid] = val = op(val, buffer[tid + 2]); } + if (CTA_SIZE >= 2) { buffer[tid] = val = op(val, buffer[tid + 1]); } + } + __syncthreads(); + return buffer[0]; + } + + template + static __device__ __forceinline__ void reduce_n(T* data, unsigned int n, BinOp op) + { + int ftid = flattenedThreadId(); + int sft = stride(); + + if (sft < n) + { + for (unsigned int i = sft + ftid; i < n; i += sft) + data[ftid] = op(data[ftid], data[i]); + + __syncthreads(); + + n = sft; + } + + while (n > 1) + { + unsigned int half = n/2; + + if (ftid < half) + data[ftid] = op(data[ftid], data[n - ftid - 1]); + + __syncthreads(); + + n = n - half; + } + } + }; +}}} + +//! @endcond + +#endif /* OPENCV_CUDA_DEVICE_BLOCK_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp index 62864c4857..874f705baf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/border_interpolate.hpp @@ -1,722 +1,722 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_BORDER_INTERPOLATE_HPP -#define OPENCV_CUDA_BORDER_INTERPOLATE_HPP - -#include "saturate_cast.hpp" -#include "vec_traits.hpp" -#include "vec_math.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - ////////////////////////////////////////////////////////////// - // BrdConstant - - template struct BrdRowConstant - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowConstant(int width_, const D& val_ = VecTraits::all(0)) : width(width_), val(val_) {} - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return x >= 0 ? saturate_cast(data[x]) : val; - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return x < width ? saturate_cast(data[x]) : val; - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return (x >= 0 && x < width) ? saturate_cast(data[x]) : val; - } - - int width; - D val; - }; - - template struct BrdColConstant - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColConstant(int height_, const D& val_ = VecTraits::all(0)) : height(height_), val(val_) {} - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return y >= 0 ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return y < height ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return (y >= 0 && y < height) ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; - } - - int height; - D val; - }; - - template struct BrdConstant - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdConstant(int height_, int width_, const D& val_ = VecTraits::all(0)) : height(height_), width(width_), val(val_) - { - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(((const T*)((const uchar*)data + y * step))[x]) : val; - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; - } - - int height; - int width; - D val; - }; - - ////////////////////////////////////////////////////////////// - // BrdReplicate - - template struct BrdRowReplicate - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowReplicate(int width) : last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdRowReplicate(int width, U) : last_col(width - 1) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::max(x, 0); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::min(x, last_col); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int last_col; - }; - - template struct BrdColReplicate - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColReplicate(int height) : last_row(height - 1) {} - template __host__ __device__ __forceinline__ BrdColReplicate(int height, U) : last_row(height - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::max(y, 0); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::min(y, last_row); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const T*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const T*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const T*)((const char*)data + idx_row(y) * step)); - } - - int last_row; - }; - - template struct BrdReplicate - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdReplicate(int height, int width) : last_row(height - 1), last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdReplicate(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::max(y, 0); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::min(y, last_row); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::max(x, 0); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::min(x, last_col); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int last_row; - int last_col; - }; - - ////////////////////////////////////////////////////////////// - // BrdReflect101 - - template struct BrdRowReflect101 - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowReflect101(int width) : last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdRowReflect101(int width, U) : last_col(width - 1) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::abs(x) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int last_col; - }; - - template struct BrdColReflect101 - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColReflect101(int height) : last_row(height - 1) {} - template __host__ __device__ __forceinline__ BrdColReflect101(int height, U) : last_row(height - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::abs(y) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); - } - - int last_row; - }; - - template struct BrdReflect101 - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdReflect101(int height, int width) : last_row(height - 1), last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdReflect101(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return ::abs(y) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return ::abs(x) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int last_row; - int last_col; - }; - - ////////////////////////////////////////////////////////////// - // BrdReflect - - template struct BrdRowReflect - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowReflect(int width) : last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdRowReflect(int width, U) : last_col(width - 1) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (::abs(x) - (x < 0)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return ::abs(last_col - ::abs(last_col - x) + (x > last_col)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_high(::abs(x) - (x < 0)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int last_col; - }; - - template struct BrdColReflect - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColReflect(int height) : last_row(height - 1) {} - template __host__ __device__ __forceinline__ BrdColReflect(int height, U) : last_row(height - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (::abs(y) - (y < 0)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return ::abs(last_row - ::abs(last_row - y) + (y > last_row)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_high(::abs(y) - (y < 0)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); - } - - int last_row; - }; - - template struct BrdReflect - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdReflect(int height, int width) : last_row(height - 1), last_col(width - 1) {} - template __host__ __device__ __forceinline__ BrdReflect(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (::abs(y) - (y < 0)) % (last_row + 1); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return /*::abs*/(last_row - ::abs(last_row - y) + (y > last_row)) /*% (last_row + 1)*/; - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_low(idx_row_high(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (::abs(x) - (x < 0)) % (last_col + 1); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return (last_col - ::abs(last_col - x) + (x > last_col)); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_low(idx_col_high(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int last_row; - int last_col; - }; - - ////////////////////////////////////////////////////////////// - // BrdWrap - - template struct BrdRowWrap - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdRowWrap(int width_) : width(width_) {} - template __host__ __device__ __forceinline__ BrdRowWrap(int width_, U) : width(width_) {} - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (x >= 0) * x + (x < 0) * (x - ((x - width + 1) / width) * width); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return (x < width) * x + (x >= width) * (x % width); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_high(idx_col_low(x)); - } - - template __device__ __forceinline__ D at_low(int x, const T* data) const - { - return saturate_cast(data[idx_col_low(x)]); - } - - template __device__ __forceinline__ D at_high(int x, const T* data) const - { - return saturate_cast(data[idx_col_high(x)]); - } - - template __device__ __forceinline__ D at(int x, const T* data) const - { - return saturate_cast(data[idx_col(x)]); - } - - int width; - }; - - template struct BrdColWrap - { - typedef D result_type; - - explicit __host__ __device__ __forceinline__ BrdColWrap(int height_) : height(height_) {} - template __host__ __device__ __forceinline__ BrdColWrap(int height_, U) : height(height_) {} - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (y >= 0) * y + (y < 0) * (y - ((y - height + 1) / height) * height); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return (y < height) * y + (y >= height) * (y % height); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_high(idx_row_low(y)); - } - - template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); - } - - template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); - } - - template __device__ __forceinline__ D at(int y, const T* data, size_t step) const - { - return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); - } - - int height; - }; - - template struct BrdWrap - { - typedef D result_type; - - __host__ __device__ __forceinline__ BrdWrap(int height_, int width_) : - height(height_), width(width_) - { - } - template - __host__ __device__ __forceinline__ BrdWrap(int height_, int width_, U) : - height(height_), width(width_) - { - } - - __device__ __forceinline__ int idx_row_low(int y) const - { - return (y >= 0) ? y : (y - ((y - height + 1) / height) * height); - } - - __device__ __forceinline__ int idx_row_high(int y) const - { - return (y < height) ? y : (y % height); - } - - __device__ __forceinline__ int idx_row(int y) const - { - return idx_row_high(idx_row_low(y)); - } - - __device__ __forceinline__ int idx_col_low(int x) const - { - return (x >= 0) ? x : (x - ((x - width + 1) / width) * width); - } - - __device__ __forceinline__ int idx_col_high(int x) const - { - return (x < width) ? x : (x % width); - } - - __device__ __forceinline__ int idx_col(int x) const - { - return idx_col_high(idx_col_low(x)); - } - - template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const - { - return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); - } - - template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const - { - return saturate_cast(src(idx_row(y), idx_col(x))); - } - - int height; - int width; - }; - - ////////////////////////////////////////////////////////////// - // BorderReader - - template struct BorderReader - { - typedef typename B::result_type elem_type; - typedef typename Ptr2D::index_type index_type; - - __host__ __device__ __forceinline__ BorderReader(const Ptr2D& ptr_, const B& b_) : ptr(ptr_), b(b_) {} - - __device__ __forceinline__ elem_type operator ()(index_type y, index_type x) const - { - return b.at(y, x, ptr); - } - - Ptr2D ptr; - B b; - }; - - // under win32 there is some bug with templated types that passed as kernel parameters - // with this specialization all works fine - template struct BorderReader< Ptr2D, BrdConstant > - { - typedef typename BrdConstant::result_type elem_type; - typedef typename Ptr2D::index_type index_type; - - __host__ __device__ __forceinline__ BorderReader(const Ptr2D& src_, const BrdConstant& b) : - src(src_), height(b.height), width(b.width), val(b.val) - { - } - - __device__ __forceinline__ D operator ()(index_type y, index_type x) const - { - return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; - } - - Ptr2D src; - int height; - int width; - D val; - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_BORDER_INTERPOLATE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_BORDER_INTERPOLATE_HPP +#define OPENCV_CUDA_BORDER_INTERPOLATE_HPP + +#include "saturate_cast.hpp" +#include "vec_traits.hpp" +#include "vec_math.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + ////////////////////////////////////////////////////////////// + // BrdConstant + + template struct BrdRowConstant + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowConstant(int width_, const D& val_ = VecTraits::all(0)) : width(width_), val(val_) {} + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return x >= 0 ? saturate_cast(data[x]) : val; + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return x < width ? saturate_cast(data[x]) : val; + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return (x >= 0 && x < width) ? saturate_cast(data[x]) : val; + } + + int width; + D val; + }; + + template struct BrdColConstant + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColConstant(int height_, const D& val_ = VecTraits::all(0)) : height(height_), val(val_) {} + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return y >= 0 ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return y < height ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return (y >= 0 && y < height) ? saturate_cast(*(const T*)((const char*)data + y * step)) : val; + } + + int height; + D val; + }; + + template struct BrdConstant + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdConstant(int height_, int width_, const D& val_ = VecTraits::all(0)) : height(height_), width(width_), val(val_) + { + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(((const T*)((const uchar*)data + y * step))[x]) : val; + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; + } + + int height; + int width; + D val; + }; + + ////////////////////////////////////////////////////////////// + // BrdReplicate + + template struct BrdRowReplicate + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowReplicate(int width) : last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdRowReplicate(int width, U) : last_col(width - 1) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::max(x, 0); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::min(x, last_col); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int last_col; + }; + + template struct BrdColReplicate + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColReplicate(int height) : last_row(height - 1) {} + template __host__ __device__ __forceinline__ BrdColReplicate(int height, U) : last_row(height - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::max(y, 0); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::min(y, last_row); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const T*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const T*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const T*)((const char*)data + idx_row(y) * step)); + } + + int last_row; + }; + + template struct BrdReplicate + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdReplicate(int height, int width) : last_row(height - 1), last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdReplicate(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::max(y, 0); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::min(y, last_row); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::max(x, 0); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::min(x, last_col); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int last_row; + int last_col; + }; + + ////////////////////////////////////////////////////////////// + // BrdReflect101 + + template struct BrdRowReflect101 + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowReflect101(int width) : last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdRowReflect101(int width, U) : last_col(width - 1) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::abs(x) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int last_col; + }; + + template struct BrdColReflect101 + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColReflect101(int height) : last_row(height - 1) {} + template __host__ __device__ __forceinline__ BrdColReflect101(int height, U) : last_row(height - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::abs(y) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); + } + + int last_row; + }; + + template struct BrdReflect101 + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdReflect101(int height, int width) : last_row(height - 1), last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdReflect101(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return ::abs(y) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::abs(last_row - ::abs(last_row - y)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return ::abs(x) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::abs(last_col - ::abs(last_col - x)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int last_row; + int last_col; + }; + + ////////////////////////////////////////////////////////////// + // BrdReflect + + template struct BrdRowReflect + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowReflect(int width) : last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdRowReflect(int width, U) : last_col(width - 1) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (::abs(x) - (x < 0)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return ::abs(last_col - ::abs(last_col - x) + (x > last_col)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_high(::abs(x) - (x < 0)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int last_col; + }; + + template struct BrdColReflect + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColReflect(int height) : last_row(height - 1) {} + template __host__ __device__ __forceinline__ BrdColReflect(int height, U) : last_row(height - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (::abs(y) - (y < 0)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return ::abs(last_row - ::abs(last_row - y) + (y > last_row)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_high(::abs(y) - (y < 0)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); + } + + int last_row; + }; + + template struct BrdReflect + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdReflect(int height, int width) : last_row(height - 1), last_col(width - 1) {} + template __host__ __device__ __forceinline__ BrdReflect(int height, int width, U) : last_row(height - 1), last_col(width - 1) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (::abs(y) - (y < 0)) % (last_row + 1); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return /*::abs*/(last_row - ::abs(last_row - y) + (y > last_row)) /*% (last_row + 1)*/; + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_low(idx_row_high(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (::abs(x) - (x < 0)) % (last_col + 1); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return (last_col - ::abs(last_col - x) + (x > last_col)); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_low(idx_col_high(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int last_row; + int last_col; + }; + + ////////////////////////////////////////////////////////////// + // BrdWrap + + template struct BrdRowWrap + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdRowWrap(int width_) : width(width_) {} + template __host__ __device__ __forceinline__ BrdRowWrap(int width_, U) : width(width_) {} + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (x >= 0) * x + (x < 0) * (x - ((x - width + 1) / width) * width); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return (x < width) * x + (x >= width) * (x % width); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_high(idx_col_low(x)); + } + + template __device__ __forceinline__ D at_low(int x, const T* data) const + { + return saturate_cast(data[idx_col_low(x)]); + } + + template __device__ __forceinline__ D at_high(int x, const T* data) const + { + return saturate_cast(data[idx_col_high(x)]); + } + + template __device__ __forceinline__ D at(int x, const T* data) const + { + return saturate_cast(data[idx_col(x)]); + } + + int width; + }; + + template struct BrdColWrap + { + typedef D result_type; + + explicit __host__ __device__ __forceinline__ BrdColWrap(int height_) : height(height_) {} + template __host__ __device__ __forceinline__ BrdColWrap(int height_, U) : height(height_) {} + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (y >= 0) * y + (y < 0) * (y - ((y - height + 1) / height) * height); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return (y < height) * y + (y >= height) * (y % height); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_high(idx_row_low(y)); + } + + template __device__ __forceinline__ D at_low(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_low(y) * step)); + } + + template __device__ __forceinline__ D at_high(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row_high(y) * step)); + } + + template __device__ __forceinline__ D at(int y, const T* data, size_t step) const + { + return saturate_cast(*(const D*)((const char*)data + idx_row(y) * step)); + } + + int height; + }; + + template struct BrdWrap + { + typedef D result_type; + + __host__ __device__ __forceinline__ BrdWrap(int height_, int width_) : + height(height_), width(width_) + { + } + template + __host__ __device__ __forceinline__ BrdWrap(int height_, int width_, U) : + height(height_), width(width_) + { + } + + __device__ __forceinline__ int idx_row_low(int y) const + { + return (y >= 0) ? y : (y - ((y - height + 1) / height) * height); + } + + __device__ __forceinline__ int idx_row_high(int y) const + { + return (y < height) ? y : (y % height); + } + + __device__ __forceinline__ int idx_row(int y) const + { + return idx_row_high(idx_row_low(y)); + } + + __device__ __forceinline__ int idx_col_low(int x) const + { + return (x >= 0) ? x : (x - ((x - width + 1) / width) * width); + } + + __device__ __forceinline__ int idx_col_high(int x) const + { + return (x < width) ? x : (x % width); + } + + __device__ __forceinline__ int idx_col(int x) const + { + return idx_col_high(idx_col_low(x)); + } + + template __device__ __forceinline__ D at(int y, int x, const T* data, size_t step) const + { + return saturate_cast(((const T*)((const char*)data + idx_row(y) * step))[idx_col(x)]); + } + + template __device__ __forceinline__ D at(typename Ptr2D::index_type y, typename Ptr2D::index_type x, const Ptr2D& src) const + { + return saturate_cast(src(idx_row(y), idx_col(x))); + } + + int height; + int width; + }; + + ////////////////////////////////////////////////////////////// + // BorderReader + + template struct BorderReader + { + typedef typename B::result_type elem_type; + typedef typename Ptr2D::index_type index_type; + + __host__ __device__ __forceinline__ BorderReader(const Ptr2D& ptr_, const B& b_) : ptr(ptr_), b(b_) {} + + __device__ __forceinline__ elem_type operator ()(index_type y, index_type x) const + { + return b.at(y, x, ptr); + } + + Ptr2D ptr; + B b; + }; + + // under win32 there is some bug with templated types that passed as kernel parameters + // with this specialization all works fine + template struct BorderReader< Ptr2D, BrdConstant > + { + typedef typename BrdConstant::result_type elem_type; + typedef typename Ptr2D::index_type index_type; + + __host__ __device__ __forceinline__ BorderReader(const Ptr2D& src_, const BrdConstant& b) : + src(src_), height(b.height), width(b.width), val(b.val) + { + } + + __device__ __forceinline__ D operator ()(index_type y, index_type x) const + { + return (x >= 0 && x < width && y >= 0 && y < height) ? saturate_cast(src(y, x)) : val; + } + + Ptr2D src; + int height; + int width; + D val; + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_BORDER_INTERPOLATE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp index 0b9fb84b7c..dcce280214 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/color.hpp @@ -1,309 +1,309 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_COLOR_HPP -#define OPENCV_CUDA_COLOR_HPP - -#include "detail/color_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - // All OPENCV_CUDA_IMPLEMENT_*_TRAITS(ColorSpace1_to_ColorSpace2, ...) macros implements - // template class ColorSpace1_to_ColorSpace2_traits - // { - // typedef ... functor_type; - // static __host__ __device__ functor_type create_functor(); - // }; - - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgba, 4, 4, 2) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr555, 3, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr565, 3, 0, 6) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr555, 3, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr565, 3, 2, 6) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr555, 4, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr565, 4, 0, 6) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr555, 4, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr565, 4, 2, 6) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgb, 3, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgb, 3, 2, 6) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgr, 3, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgr, 3, 0, 6) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgba, 4, 2, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgba, 4, 2, 6) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgra, 4, 0, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgra, 4, 0, 6) - - #undef OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgr, 3) - OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgra, 4) - - #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr555, 5) - OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr565, 6) - - #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr555_to_gray, 5) - OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr565_to_gray, 6) - - #undef OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgb_to_gray, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgr_to_gray, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgba_to_gray, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgra_to_gray, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS - - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS - - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS - - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS - - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls4, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls4, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls4, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls4, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS - - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgb, 3, 3, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgba, 3, 4, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgb, 4, 3, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgba, 4, 4, 2) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgr, 3, 3, 0) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgra, 3, 4, 0) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgr, 4, 3, 0) - OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgra, 4, 4, 0) - - #undef OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab4, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab4, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab4, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab4, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab4, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab4, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab4, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab4, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS - - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgb, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgb, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgba, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgba, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgr, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgr, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgra, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgra, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgb, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgb, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgba, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgba, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgr, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgr, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgra, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgra, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS - - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv4, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv4, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv4, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv4, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv4, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv4, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv4, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv4, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS - - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgb, 3, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgb, 4, 3, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgba, 3, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgba, 4, 4, true, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgr, 3, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgr, 4, 3, true, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgra, 3, 4, true, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgra, 4, 4, true, 0) - - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgb, 3, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgb, 4, 3, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgba, 3, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgba, 4, 4, false, 2) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgr, 3, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgr, 4, 3, false, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgra, 3, 4, false, 0) - OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgra, 4, 4, false, 0) - - #undef OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_COLOR_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_COLOR_HPP +#define OPENCV_CUDA_COLOR_HPP + +#include "detail/color_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + // All OPENCV_CUDA_IMPLEMENT_*_TRAITS(ColorSpace1_to_ColorSpace2, ...) macros implements + // template class ColorSpace1_to_ColorSpace2_traits + // { + // typedef ... functor_type; + // static __host__ __device__ functor_type create_functor(); + // }; + + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgr_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(bgra_to_rgba, 4, 4, 2) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr555, 3, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgr_to_bgr565, 3, 0, 6) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr555, 3, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgb_to_bgr565, 3, 2, 6) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr555, 4, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(bgra_to_bgr565, 4, 0, 6) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr555, 4, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(rgba_to_bgr565, 4, 2, 6) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgb, 3, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgb, 3, 2, 6) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgr, 3, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgr, 3, 0, 6) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_rgba, 4, 2, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_rgba, 4, 2, 6) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr555_to_bgra, 4, 0, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(bgr565_to_bgra, 4, 0, 6) + + #undef OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgr, 3) + OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(gray_to_bgra, 4) + + #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr555, 5) + OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(gray_to_bgr565, 6) + + #undef OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr555_to_gray, 5) + OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(bgr565_to_gray, 6) + + #undef OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgb_to_gray, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgr_to_gray, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(rgba_to_gray, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(bgra_to_gray, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgb_to_yuv4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(rgba_to_yuv4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgr_to_yuv4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(bgra_to_yuv4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS + + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(yuv4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgb_to_YCrCb4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(rgba_to_YCrCb4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgr_to_YCrCb4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(bgra_to_YCrCb4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS + + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(YCrCb4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgb_to_xyz4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(rgba_to_xyz4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgr_to_xyz4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(bgra_to_xyz4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS + + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(xyz4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgb_to_hsv4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(rgba_to_hsv4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgr_to_hsv4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(bgra_to_hsv4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS + + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(hsv4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgb_to_hls4, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(rgba_to_hls4, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgr_to_hls4, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(bgra_to_hls4, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS + + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgb, 3, 3, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_rgba, 3, 4, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgb, 4, 3, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_rgba, 4, 4, 2) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgr, 3, 3, 0) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls_to_bgra, 3, 4, 0) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgr, 4, 3, 0) + OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(hls4_to_bgra, 4, 4, 0) + + #undef OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgb_to_lab4, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(rgba_to_lab4, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgr_to_lab4, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(bgra_to_lab4, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgb_to_lab4, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lrgba_to_lab4, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgr_to_lab4, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(lbgra_to_lab4, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS + + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgb, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgb, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_rgba, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_rgba, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgr, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgr, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_bgra, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_bgra, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgb, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgb, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lrgba, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lrgba, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgr, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgr, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab_to_lbgra, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(lab4_to_lbgra, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS + + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgb_to_luv4, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(rgba_to_luv4, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgr_to_luv4, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(bgra_to_luv4, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgb_to_luv4, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lrgba_to_luv4, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgr_to_luv4, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(lbgra_to_luv4, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS + + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgb, 3, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgb, 4, 3, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_rgba, 3, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_rgba, 4, 4, true, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgr, 3, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgr, 4, 3, true, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_bgra, 3, 4, true, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_bgra, 4, 4, true, 0) + + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgb, 3, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgb, 4, 3, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lrgba, 3, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lrgba, 4, 4, false, 2) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgr, 3, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgr, 4, 3, false, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv_to_lbgra, 3, 4, false, 0) + OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(luv4_to_lbgra, 4, 4, false, 0) + + #undef OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_COLOR_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp index 58cf9d8579..1e1d5de1b0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/common.hpp @@ -1,131 +1,131 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_COMMON_HPP -#define OPENCV_CUDA_COMMON_HPP - -#include -#include "opencv2/core/cuda_types.hpp" -#include "opencv2/core/cvdef.h" -#include "opencv2/core/base.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -#ifndef CV_PI_F - #ifndef CV_PI - #define CV_PI_F 3.14159265f - #else - #define CV_PI_F ((float)CV_PI) - #endif -#endif - -namespace cv { namespace cuda { - static inline void checkCudaError(cudaError_t err, const char* file, const int line, const char* func) - { - if (cudaSuccess != err) { - cudaGetLastError(); // reset the last stored error to cudaSuccess - cv::error(cv::Error::GpuApiCallError, cudaGetErrorString(err), func, file, line); - } - } -}} - -#ifndef cudaSafeCall - #define cudaSafeCall(expr) cv::cuda::checkCudaError(expr, __FILE__, __LINE__, CV_Func) -#endif - -namespace cv { namespace cuda -{ - template static inline bool isAligned(const T* ptr, size_t size) - { - return reinterpret_cast(ptr) % size == 0; - } - - static inline bool isAligned(size_t step, size_t size) - { - return step % size == 0; - } -}} - -namespace cv { namespace cuda -{ - namespace device - { - __host__ __device__ __forceinline__ int divUp(int total, int grain) - { - return (total + grain - 1) / grain; - } - -#if (CUDART_VERSION >= 12000) - template inline void createTextureObjectPitch2D(cudaTextureObject_t*, PtrStepSz&, const cudaTextureDesc&) { - CV_Error(cv::Error::GpuNotSupported, "Function removed in CUDA SDK 12"); } -#else - //TODO: remove from OpenCV 5.x - template inline void bindTexture(const textureReference* tex, const PtrStepSz& img) - { - cudaChannelFormatDesc desc = cudaCreateChannelDesc(); - cudaSafeCall( cudaBindTexture2D(0, tex, img.ptr(), &desc, img.cols, img.rows, img.step) ); - } - - template inline void createTextureObjectPitch2D(cudaTextureObject_t* tex, PtrStepSz& img, const cudaTextureDesc& texDesc) - { - cudaResourceDesc resDesc; - memset(&resDesc, 0, sizeof(resDesc)); - resDesc.resType = cudaResourceTypePitch2D; - resDesc.res.pitch2D.devPtr = static_cast(img.ptr()); - resDesc.res.pitch2D.height = img.rows; - resDesc.res.pitch2D.width = img.cols; - resDesc.res.pitch2D.pitchInBytes = img.step; - resDesc.res.pitch2D.desc = cudaCreateChannelDesc(); - - cudaSafeCall( cudaCreateTextureObject(tex, &resDesc, &texDesc, NULL) ); - } -#endif - } -}} - -//! @endcond - -#endif // OPENCV_CUDA_COMMON_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_COMMON_HPP +#define OPENCV_CUDA_COMMON_HPP + +#include +#include "opencv2/core/cuda_types.hpp" +#include "opencv2/core/cvdef.h" +#include "opencv2/core/base.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +#ifndef CV_PI_F + #ifndef CV_PI + #define CV_PI_F 3.14159265f + #else + #define CV_PI_F ((float)CV_PI) + #endif +#endif + +namespace cv { namespace cuda { + static inline void checkCudaError(cudaError_t err, const char* file, const int line, const char* func) + { + if (cudaSuccess != err) { + cudaGetLastError(); // reset the last stored error to cudaSuccess + cv::error(cv::Error::GpuApiCallError, cudaGetErrorString(err), func, file, line); + } + } +}} + +#ifndef cudaSafeCall + #define cudaSafeCall(expr) cv::cuda::checkCudaError(expr, __FILE__, __LINE__, CV_Func) +#endif + +namespace cv { namespace cuda +{ + template static inline bool isAligned(const T* ptr, size_t size) + { + return reinterpret_cast(ptr) % size == 0; + } + + static inline bool isAligned(size_t step, size_t size) + { + return step % size == 0; + } +}} + +namespace cv { namespace cuda +{ + namespace device + { + __host__ __device__ __forceinline__ int divUp(int total, int grain) + { + return (total + grain - 1) / grain; + } + +#if (CUDART_VERSION >= 12000) + template inline void createTextureObjectPitch2D(cudaTextureObject_t*, PtrStepSz&, const cudaTextureDesc&) { + CV_Error(cv::Error::GpuNotSupported, "Function removed in CUDA SDK 12"); } +#else + //TODO: remove from OpenCV 5.x + template inline void bindTexture(const textureReference* tex, const PtrStepSz& img) + { + cudaChannelFormatDesc desc = cudaCreateChannelDesc(); + cudaSafeCall( cudaBindTexture2D(0, tex, img.ptr(), &desc, img.cols, img.rows, img.step) ); + } + + template inline void createTextureObjectPitch2D(cudaTextureObject_t* tex, PtrStepSz& img, const cudaTextureDesc& texDesc) + { + cudaResourceDesc resDesc; + memset(&resDesc, 0, sizeof(resDesc)); + resDesc.resType = cudaResourceTypePitch2D; + resDesc.res.pitch2D.devPtr = static_cast(img.ptr()); + resDesc.res.pitch2D.height = img.rows; + resDesc.res.pitch2D.width = img.cols; + resDesc.res.pitch2D.pitchInBytes = img.step; + resDesc.res.pitch2D.desc = cudaCreateChannelDesc(); + + cudaSafeCall( cudaCreateTextureObject(tex, &resDesc, &texDesc, NULL) ); + } +#endif + } +}} + +//! @endcond + +#endif // OPENCV_CUDA_COMMON_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp index 46eb4e0f81..6820d0fd64 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/datamov_utils.hpp @@ -1,113 +1,113 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_DATAMOV_UTILS_HPP -#define OPENCV_CUDA_DATAMOV_UTILS_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 200 - - // for Fermi memory space is detected automatically - template struct ForceGlob - { - __device__ __forceinline__ static void Load(const T* ptr, int offset, T& val) { val = ptr[offset]; } - }; - - #else // __CUDA_ARCH__ >= 200 - - #if defined(_WIN64) || defined(__LP64__) - // 64-bit register modifier for inlined asm - #define OPENCV_CUDA_ASM_PTR "l" - #else - // 32-bit register modifier for inlined asm - #define OPENCV_CUDA_ASM_PTR "r" - #endif - - template struct ForceGlob; - - #define OPENCV_CUDA_DEFINE_FORCE_GLOB(base_type, ptx_type, reg_mod) \ - template <> struct ForceGlob \ - { \ - __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ - { \ - asm("ld.global."#ptx_type" %0, [%1];" : "="#reg_mod(val) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ - } \ - }; - - #define OPENCV_CUDA_DEFINE_FORCE_GLOB_B(base_type, ptx_type) \ - template <> struct ForceGlob \ - { \ - __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ - { \ - asm("ld.global."#ptx_type" %0, [%1];" : "=r"(*reinterpret_cast(&val)) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ - } \ - }; - - OPENCV_CUDA_DEFINE_FORCE_GLOB_B(uchar, u8) - OPENCV_CUDA_DEFINE_FORCE_GLOB_B(schar, s8) - OPENCV_CUDA_DEFINE_FORCE_GLOB_B(char, b8) - OPENCV_CUDA_DEFINE_FORCE_GLOB (ushort, u16, h) - OPENCV_CUDA_DEFINE_FORCE_GLOB (short, s16, h) - OPENCV_CUDA_DEFINE_FORCE_GLOB (uint, u32, r) - OPENCV_CUDA_DEFINE_FORCE_GLOB (int, s32, r) - OPENCV_CUDA_DEFINE_FORCE_GLOB (float, f32, f) - OPENCV_CUDA_DEFINE_FORCE_GLOB (double, f64, d) - - #undef OPENCV_CUDA_DEFINE_FORCE_GLOB - #undef OPENCV_CUDA_DEFINE_FORCE_GLOB_B - #undef OPENCV_CUDA_ASM_PTR - - #endif // __CUDA_ARCH__ >= 200 -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_DATAMOV_UTILS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_DATAMOV_UTILS_HPP +#define OPENCV_CUDA_DATAMOV_UTILS_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 200 + + // for Fermi memory space is detected automatically + template struct ForceGlob + { + __device__ __forceinline__ static void Load(const T* ptr, int offset, T& val) { val = ptr[offset]; } + }; + + #else // __CUDA_ARCH__ >= 200 + + #if defined(_WIN64) || defined(__LP64__) + // 64-bit register modifier for inlined asm + #define OPENCV_CUDA_ASM_PTR "l" + #else + // 32-bit register modifier for inlined asm + #define OPENCV_CUDA_ASM_PTR "r" + #endif + + template struct ForceGlob; + + #define OPENCV_CUDA_DEFINE_FORCE_GLOB(base_type, ptx_type, reg_mod) \ + template <> struct ForceGlob \ + { \ + __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ + { \ + asm("ld.global."#ptx_type" %0, [%1];" : "="#reg_mod(val) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ + } \ + }; + + #define OPENCV_CUDA_DEFINE_FORCE_GLOB_B(base_type, ptx_type) \ + template <> struct ForceGlob \ + { \ + __device__ __forceinline__ static void Load(const base_type* ptr, int offset, base_type& val) \ + { \ + asm("ld.global."#ptx_type" %0, [%1];" : "=r"(*reinterpret_cast(&val)) : OPENCV_CUDA_ASM_PTR(ptr + offset)); \ + } \ + }; + + OPENCV_CUDA_DEFINE_FORCE_GLOB_B(uchar, u8) + OPENCV_CUDA_DEFINE_FORCE_GLOB_B(schar, s8) + OPENCV_CUDA_DEFINE_FORCE_GLOB_B(char, b8) + OPENCV_CUDA_DEFINE_FORCE_GLOB (ushort, u16, h) + OPENCV_CUDA_DEFINE_FORCE_GLOB (short, s16, h) + OPENCV_CUDA_DEFINE_FORCE_GLOB (uint, u32, r) + OPENCV_CUDA_DEFINE_FORCE_GLOB (int, s32, r) + OPENCV_CUDA_DEFINE_FORCE_GLOB (float, f32, f) + OPENCV_CUDA_DEFINE_FORCE_GLOB (double, f64, d) + + #undef OPENCV_CUDA_DEFINE_FORCE_GLOB + #undef OPENCV_CUDA_DEFINE_FORCE_GLOB_B + #undef OPENCV_CUDA_ASM_PTR + + #endif // __CUDA_ARCH__ >= 200 +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_DATAMOV_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp index fbe8c82dc7..f4b4796571 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/color_detail.hpp @@ -1,2018 +1,2018 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_COLOR_DETAIL_HPP -#define OPENCV_CUDA_COLOR_DETAIL_HPP - -#include "../common.hpp" -#include "../vec_traits.hpp" -#include "../saturate_cast.hpp" -#include "../limits.hpp" -#include "../functional.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - #ifndef CV_DESCALE - #define CV_DESCALE(x, n) (((x) + (1 << ((n)-1))) >> (n)) - #endif - - namespace color_detail - { - template struct ColorChannel - { - typedef float worktype_f; - static __device__ __forceinline__ T max() { return numeric_limits::max(); } - static __device__ __forceinline__ T half() { return (T)(max()/2 + 1); } - }; - - template<> struct ColorChannel - { - typedef float worktype_f; - static __device__ __forceinline__ float max() { return 1.f; } - static __device__ __forceinline__ float half() { return 0.5f; } - }; - - template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) - { - } - - template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) - { - vec.w = val; - } - - template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) - { - return ColorChannel::max(); - } - - template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) - { - return vec.w; - } - - //constants for conversion from/to RGB and Gray, YUV, YCrCb according to BT.601 - constexpr float B2YF = 0.114f; - constexpr float G2YF = 0.587f; - constexpr float R2YF = 0.299f; - - //to YCbCr - constexpr float YCBF = 0.564f; // == 1/2/(1-B2YF) - constexpr float YCRF = 0.713f; // == 1/2/(1-R2YF) - const int YCBI = 9241; // == YCBF*16384 - const int YCRI = 11682; // == YCRF*16384 - //to YUV - constexpr float B2UF = 0.492f; - constexpr float R2VF = 0.877f; - const int B2UI = 8061; // == B2UF*16384 - const int R2VI = 14369; // == R2VF*16384 - //from YUV - constexpr float U2BF = 2.032f; - constexpr float U2GF = -0.395f; - constexpr float V2GF = -0.581f; - constexpr float V2RF = 1.140f; - const int U2BI = 33292; - const int U2GI = -6472; - const int V2GI = -9519; - const int V2RI = 18678; - //from YCrCb - constexpr float CB2BF = 1.773f; - constexpr float CB2GF = -0.344f; - constexpr float CR2GF = -0.714f; - constexpr float CR2RF = 1.403f; - const int CB2BI = 29049; - const int CB2GI = -5636; - const int CR2GI = -11698; - const int CR2RI = 22987; - - enum - { - yuv_shift = 14, - xyz_shift = 12, - gray_shift = 15, - R2Y = 4899, - G2Y = 9617, - B2Y = 1868, - RY15 = 9798, // == R2YF*32768 + 0.5 - GY15 = 19235, // == G2YF*32768 + 0.5 - BY15 = 3735, // == B2YF*32768 + 0.5 - BLOCK_SIZE = 256 - }; - } - -////////////////// Various 3/4-channel to 3/4-channel RGB transformations ///////////////// - - namespace color_detail - { - template struct RGB2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - dst.x = (&src.x)[bidx]; - dst.y = src.y; - dst.z = (&src.x)[bidx^2]; - setAlpha(dst, getAlpha(src)); - - return dst; - } - - __host__ __device__ __forceinline__ RGB2RGB() {} - __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} - }; - - template <> struct RGB2RGB : unary_function - { - __device__ uint operator()(uint src) const - { - uint dst = 0; - - dst |= (0xffu & (src >> 16)); - dst |= (0xffu & (src >> 8)) << 8; - dst |= (0xffu & (src)) << 16; - dst |= (0xffu & (src >> 24)) << 24; - - return dst; - } - - __host__ __device__ __forceinline__ RGB2RGB() {} - __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -/////////// Transforming 16-bit (565 or 555) RGB to/from 24/32-bit (888[8]) RGB ////////// - - namespace color_detail - { - template struct RGB2RGB5x5Converter; - template struct RGB2RGB5x5Converter<6, bidx> - { - static __device__ __forceinline__ ushort cvt(const uchar3& src) - { - return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~3) << 3) | (((&src.x)[bidx^2] & ~7) << 8)); - } - - static __device__ __forceinline__ ushort cvt(uint src) - { - uint b = 0xffu & (src >> (bidx * 8)); - uint g = 0xffu & (src >> 8); - uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - return (ushort)((b >> 3) | ((g & ~3) << 3) | ((r & ~7) << 8)); - } - }; - - template struct RGB2RGB5x5Converter<5, bidx> - { - static __device__ __forceinline__ ushort cvt(const uchar3& src) - { - return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~7) << 2) | (((&src.x)[bidx^2] & ~7) << 7)); - } - - static __device__ __forceinline__ ushort cvt(uint src) - { - uint b = 0xffu & (src >> (bidx * 8)); - uint g = 0xffu & (src >> 8); - uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - uint a = 0xffu & (src >> 24); - return (ushort)((b >> 3) | ((g & ~7) << 2) | ((r & ~7) << 7) | (a * 0x8000)); - } - }; - - template struct RGB2RGB5x5; - - template struct RGB2RGB5x5<3, bidx,green_bits> : unary_function - { - __device__ __forceinline__ ushort operator()(const uchar3& src) const - { - return RGB2RGB5x5Converter::cvt(src); - } - - __host__ __device__ __forceinline__ RGB2RGB5x5() {} - __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} - }; - - template struct RGB2RGB5x5<4, bidx,green_bits> : unary_function - { - __device__ __forceinline__ ushort operator()(uint src) const - { - return RGB2RGB5x5Converter::cvt(src); - } - - __host__ __device__ __forceinline__ RGB2RGB5x5() {} - __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(name, scn, bidx, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2RGB5x5 functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template struct RGB5x52RGBConverter; - - template struct RGB5x52RGBConverter<5, bidx> - { - static __device__ __forceinline__ void cvt(uint src, uchar3& dst) - { - (&dst.x)[bidx] = src << 3; - dst.y = (src >> 2) & ~7; - (&dst.x)[bidx ^ 2] = (src >> 7) & ~7; - } - - static __device__ __forceinline__ void cvt(uint src, uint& dst) - { - dst = 0; - - dst |= (0xffu & (src << 3)) << (bidx * 8); - dst |= (0xffu & ((src >> 2) & ~7)) << 8; - dst |= (0xffu & ((src >> 7) & ~7)) << ((bidx ^ 2) * 8); - dst |= ((src & 0x8000) * 0xffu) << 24; - } - }; - - template struct RGB5x52RGBConverter<6, bidx> - { - static __device__ __forceinline__ void cvt(uint src, uchar3& dst) - { - (&dst.x)[bidx] = src << 3; - dst.y = (src >> 3) & ~3; - (&dst.x)[bidx ^ 2] = (src >> 8) & ~7; - } - - static __device__ __forceinline__ void cvt(uint src, uint& dst) - { - dst = 0xffu << 24; - - dst |= (0xffu & (src << 3)) << (bidx * 8); - dst |= (0xffu &((src >> 3) & ~3)) << 8; - dst |= (0xffu & ((src >> 8) & ~7)) << ((bidx ^ 2) * 8); - } - }; - - template struct RGB5x52RGB; - - template struct RGB5x52RGB<3, bidx, green_bits> : unary_function - { - __device__ __forceinline__ uchar3 operator()(ushort src) const - { - uchar3 dst; - RGB5x52RGBConverter::cvt(src, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB5x52RGB() {} - __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} - - }; - - template struct RGB5x52RGB<4, bidx, green_bits> : unary_function - { - __device__ __forceinline__ uint operator()(ushort src) const - { - uint dst; - RGB5x52RGBConverter::cvt(src, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB5x52RGB() {} - __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(name, dcn, bidx, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB5x52RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////// Grayscale to Color //////////////////////////////// - - namespace color_detail - { - template struct Gray2RGB : unary_function::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(T src) const - { - typename TypeVec::vec_type dst; - - dst.z = dst.y = dst.x = src; - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ Gray2RGB() {} - __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} - }; - - template <> struct Gray2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - uint dst = 0xffu << 24; - - dst |= src; - dst |= src << 8; - dst |= src << 16; - - return dst; - } - __host__ __device__ __forceinline__ Gray2RGB() {} - __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(name, dcn) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Gray2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template struct Gray2RGB5x5Converter; - template<> struct Gray2RGB5x5Converter<6> - { - static __device__ __forceinline__ ushort cvt(uint t) - { - return (ushort)((t >> 3) | ((t & ~3) << 3) | ((t & ~7) << 8)); - } - }; - - template<> struct Gray2RGB5x5Converter<5> - { - static __device__ __forceinline__ ushort cvt(uint t) - { - t >>= 3; - return (ushort)(t | (t << 5) | (t << 10)); - } - }; - - template struct Gray2RGB5x5 : unary_function - { - __device__ __forceinline__ ushort operator()(uint src) const - { - return Gray2RGB5x5Converter::cvt(src); - } - - __host__ __device__ __forceinline__ Gray2RGB5x5() {} - __host__ __device__ __forceinline__ Gray2RGB5x5(const Gray2RGB5x5&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(name, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Gray2RGB5x5 functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////// Color to Grayscale //////////////////////////////// - - namespace color_detail - { - template struct RGB5x52GrayConverter; - template <> struct RGB5x52GrayConverter<6> - { - static __device__ __forceinline__ uchar cvt(uint t) - { - return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 3) & 0xfc) * GY15 + ((t >> 8) & 0xf8) * RY15, gray_shift); - } - }; - - template <> struct RGB5x52GrayConverter<5> - { - static __device__ __forceinline__ uchar cvt(uint t) - { - return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 2) & 0xf8) * GY15 + ((t >> 7) & 0xf8) * RY15, gray_shift); - } - }; - - template struct RGB5x52Gray : unary_function - { - __device__ __forceinline__ uchar operator()(uint src) const - { - return RGB5x52GrayConverter::cvt(src); - } - __host__ __device__ __forceinline__ RGB5x52Gray() {} - __host__ __device__ __forceinline__ RGB5x52Gray(const RGB5x52Gray&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(name, green_bits) \ - struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB5x52Gray functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template static __device__ __forceinline__ T RGB2GrayConvert(const T* src) - { - return (T)CV_DESCALE((unsigned)(src[bidx] * BY15 + src[1] * GY15 + src[bidx^2] * RY15), gray_shift); - } - - template static __device__ __forceinline__ uchar RGB2GrayConvert(uint src) - { - uint b = 0xffu & (src >> (bidx * 8)); - uint g = 0xffu & (src >> 8); - uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - return CV_DESCALE((uint)(b * BY15 + g * GY15 + r * RY15), gray_shift); - } - - template static __device__ __forceinline__ float RGB2GrayConvert(const float* src) - { - return src[bidx] * B2YF + src[1] * G2YF + src[bidx^2] * R2YF; - } - - template struct RGB2Gray : unary_function::vec_type, T> - { - __device__ __forceinline__ T operator()(const typename TypeVec::vec_type& src) const - { - return RGB2GrayConvert(&src.x); - } - __host__ __device__ __forceinline__ RGB2Gray() {} - __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} - }; - - template struct RGB2Gray : unary_function - { - __device__ __forceinline__ uchar operator()(uint src) const - { - return RGB2GrayConvert(src); - } - __host__ __device__ __forceinline__ RGB2Gray() {} - __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(name, scn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2Gray functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> YUV ////////////////////////////////////// - - namespace color_detail - { - __constant__ float c_RGB2YUVCoeffs_f[5] = { B2YF, G2YF, R2YF, B2UF, R2VF }; - __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, B2UI, R2VI }; - - template static __device__ void RGB2YUVConvert(const T* src, D& dst) - { - const int delta = ColorChannel::half() * (1 << yuv_shift); - - const int Y = CV_DESCALE(src[0] * c_RGB2YUVCoeffs_i[bidx^2] + src[1] * c_RGB2YUVCoeffs_i[1] + src[2] * c_RGB2YUVCoeffs_i[bidx], yuv_shift); - const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YUVCoeffs_i[3] + delta, yuv_shift); - const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YUVCoeffs_i[4] + delta, yuv_shift); - - dst.x = saturate_cast(Y); - dst.y = saturate_cast(Cr); - dst.z = saturate_cast(Cb); - } - - template static __device__ __forceinline__ void RGB2YUVConvert(const float* src, D& dst) - { - dst.x = src[0] * c_RGB2YUVCoeffs_f[bidx^2] + src[1] * c_RGB2YUVCoeffs_f[1] + src[2] * c_RGB2YUVCoeffs_f[bidx]; - dst.y = (src[bidx^2] - dst.x) * c_RGB2YUVCoeffs_f[3] + ColorChannel::half(); - dst.z = (src[bidx] - dst.x) * c_RGB2YUVCoeffs_f[4] + ColorChannel::half(); - } - - template struct RGB2YUV - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - RGB2YUVConvert(&src.x, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB2YUV() {} - __host__ __device__ __forceinline__ RGB2YUV(const RGB2YUV&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2YUV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_YUV2RGBCoeffs_f[5] = { U2BF, U2GF, V2GF, V2RF }; - __constant__ int c_YUV2RGBCoeffs_i[5] = { U2BI, U2GI, V2GI, V2RI }; - - template static __device__ void YUV2RGBConvert(const T& src, D* dst) - { - const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); - - const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] - + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); - - const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); - - dst[bidx] = saturate_cast(b); - dst[1] = saturate_cast(g); - dst[bidx^2] = saturate_cast(r); - } - - template static __device__ uint YUV2RGBConvert(uint src) - { - const int x = 0xff & (src); - const int y = 0xff & (src >> 8); - const int z = 0xff & (src >> 16); - - const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); - - const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] - + (y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); - - const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(b) << (bidx * 8); - dst |= saturate_cast(g) << 8; - dst |= saturate_cast(r) << ((bidx ^ 2) * 8); - - return dst; - } - - template static __device__ __forceinline__ void YUV2RGBConvert(const T& src, float* dst) - { - dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[3]; - - dst[1] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[2] - + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[1]; - - dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[0]; - } - - template struct YUV2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - YUV2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ YUV2RGB() {} - __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} - }; - - template struct YUV2RGB : unary_function - { - __device__ __forceinline__ uint operator ()(uint src) const - { - return YUV2RGBConvert(src); - } - __host__ __device__ __forceinline__ YUV2RGB() {} - __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::YUV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> YCrCb ////////////////////////////////////// - - namespace color_detail - { - __constant__ float c_RGB2YCrCbCoeffs_f[5] = {R2YF, G2YF, B2YF, YCRF, YCBF}; - __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, YCRI, YCBI}; - - template static __device__ void RGB2YCrCbConvert(const T* src, D& dst) - { - const int delta = ColorChannel::half() * (1 << yuv_shift); - - const int Y = CV_DESCALE(src[0] * c_RGB2YCrCbCoeffs_i[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_i[1] + src[2] * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); - const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); - const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); - - dst.x = saturate_cast(Y); - dst.y = saturate_cast(Cr); - dst.z = saturate_cast(Cb); - } - - template static __device__ uint RGB2YCrCbConvert(uint src) - { - const int delta = ColorChannel::half() * (1 << yuv_shift); - - const int Y = CV_DESCALE((0xffu & src) * c_RGB2YCrCbCoeffs_i[bidx^2] + (0xffu & (src >> 8)) * c_RGB2YCrCbCoeffs_i[1] + (0xffu & (src >> 16)) * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); - const int Cr = CV_DESCALE(((0xffu & (src >> ((bidx ^ 2) * 8))) - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); - const int Cb = CV_DESCALE(((0xffu & (src >> (bidx * 8))) - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); - - uint dst = 0; - - dst |= saturate_cast(Y); - dst |= saturate_cast(Cr) << 8; - dst |= saturate_cast(Cb) << 16; - - return dst; - } - - template static __device__ __forceinline__ void RGB2YCrCbConvert(const float* src, D& dst) - { - dst.x = src[0] * c_RGB2YCrCbCoeffs_f[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_f[1] + src[2] * c_RGB2YCrCbCoeffs_f[bidx]; - dst.y = (src[bidx^2] - dst.x) * c_RGB2YCrCbCoeffs_f[3] + ColorChannel::half(); - dst.z = (src[bidx] - dst.x) * c_RGB2YCrCbCoeffs_f[4] + ColorChannel::half(); - } - - template struct RGB2YCrCb - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - RGB2YCrCbConvert(&src.x, dst); - return dst; - } - __host__ __device__ __forceinline__ RGB2YCrCb() {} - __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} - }; - - template struct RGB2YCrCb : unary_function - { - __device__ __forceinline__ uint operator ()(uint src) const - { - return RGB2YCrCbConvert(src); - } - - __host__ __device__ __forceinline__ RGB2YCrCb() {} - __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2YCrCb functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_YCrCb2RGBCoeffs_f[5] = {CR2RF, CR2GF, CB2GF, CB2BF}; - __constant__ int c_YCrCb2RGBCoeffs_i[5] = {CR2RI, CR2GI, CB2GI, CB2BI}; - - template static __device__ void YCrCb2RGBConvert(const T& src, D* dst) - { - const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); - const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); - const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); - - dst[bidx] = saturate_cast(b); - dst[1] = saturate_cast(g); - dst[bidx^2] = saturate_cast(r); - } - - template static __device__ uint YCrCb2RGBConvert(uint src) - { - const int x = 0xff & (src); - const int y = 0xff & (src >> 8); - const int z = 0xff & (src >> 16); - - const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); - const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); - const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(b) << (bidx * 8); - dst |= saturate_cast(g) << 8; - dst |= saturate_cast(r) << ((bidx ^ 2) * 8); - - return dst; - } - - template __device__ __forceinline__ void YCrCb2RGBConvert(const T& src, float* dst) - { - dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[3]; - dst[1] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[1]; - dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[0]; - } - - template struct YCrCb2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - YCrCb2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ YCrCb2RGB() {} - __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} - }; - - template struct YCrCb2RGB : unary_function - { - __device__ __forceinline__ uint operator ()(uint src) const - { - return YCrCb2RGBConvert(src); - } - __host__ __device__ __forceinline__ YCrCb2RGB() {} - __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::YCrCb2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -////////////////////////////////////// RGB <-> XYZ /////////////////////////////////////// - - namespace color_detail - { - __constant__ float c_RGB2XYZ_D65f[9] = { 0.412453f, 0.357580f, 0.180423f, 0.212671f, 0.715160f, 0.072169f, 0.019334f, 0.119193f, 0.950227f }; - __constant__ int c_RGB2XYZ_D65i[9] = { 1689, 1465, 739, 871, 2929, 296, 79, 488, 3892 }; - - template static __device__ __forceinline__ void RGB2XYZConvert(const T* src, D& dst) - { - dst.z = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[6] + src[1] * c_RGB2XYZ_D65i[7] + src[bidx] * c_RGB2XYZ_D65i[8], xyz_shift)); - dst.x = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[0] + src[1] * c_RGB2XYZ_D65i[1] + src[bidx] * c_RGB2XYZ_D65i[2], xyz_shift)); - dst.y = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[3] + src[1] * c_RGB2XYZ_D65i[4] + src[bidx] * c_RGB2XYZ_D65i[5], xyz_shift)); - } - - template static __device__ __forceinline__ uint RGB2XYZConvert(uint src) - { - const uint b = 0xffu & (src >> (bidx * 8)); - const uint g = 0xffu & (src >> 8); - const uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); - - const uint x = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[0] + g * c_RGB2XYZ_D65i[1] + b * c_RGB2XYZ_D65i[2], xyz_shift)); - const uint y = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[3] + g * c_RGB2XYZ_D65i[4] + b * c_RGB2XYZ_D65i[5], xyz_shift)); - const uint z = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[6] + g * c_RGB2XYZ_D65i[7] + b * c_RGB2XYZ_D65i[8], xyz_shift)); - - uint dst = 0; - - dst |= x; - dst |= y << 8; - dst |= z << 16; - - return dst; - } - - template static __device__ __forceinline__ void RGB2XYZConvert(const float* src, D& dst) - { - dst.x = src[bidx^2] * c_RGB2XYZ_D65f[0] + src[1] * c_RGB2XYZ_D65f[1] + src[bidx] * c_RGB2XYZ_D65f[2]; - dst.y = src[bidx^2] * c_RGB2XYZ_D65f[3] + src[1] * c_RGB2XYZ_D65f[4] + src[bidx] * c_RGB2XYZ_D65f[5]; - dst.z = src[bidx^2] * c_RGB2XYZ_D65f[6] + src[1] * c_RGB2XYZ_D65f[7] + src[bidx] * c_RGB2XYZ_D65f[8]; - } - - template struct RGB2XYZ - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2XYZConvert(&src.x, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2XYZ() {} - __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} - }; - - template struct RGB2XYZ : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return RGB2XYZConvert(src); - } - __host__ __device__ __forceinline__ RGB2XYZ() {} - __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2XYZ functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_XYZ2sRGB_D65f[9] = { 3.240479f, -1.53715f, -0.498535f, -0.969256f, 1.875991f, 0.041556f, 0.055648f, -0.204043f, 1.057311f }; - __constant__ int c_XYZ2sRGB_D65i[9] = { 13273, -6296, -2042, -3970, 7684, 170, 228, -836, 4331 }; - - template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, D* dst) - { - dst[bidx^2] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[0] + src.y * c_XYZ2sRGB_D65i[1] + src.z * c_XYZ2sRGB_D65i[2], xyz_shift)); - dst[1] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[3] + src.y * c_XYZ2sRGB_D65i[4] + src.z * c_XYZ2sRGB_D65i[5], xyz_shift)); - dst[bidx] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[6] + src.y * c_XYZ2sRGB_D65i[7] + src.z * c_XYZ2sRGB_D65i[8], xyz_shift)); - } - - template static __device__ __forceinline__ uint XYZ2RGBConvert(uint src) - { - const int x = 0xff & src; - const int y = 0xff & (src >> 8); - const int z = 0xff & (src >> 16); - - const uint r = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[0] + y * c_XYZ2sRGB_D65i[1] + z * c_XYZ2sRGB_D65i[2], xyz_shift)); - const uint g = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[3] + y * c_XYZ2sRGB_D65i[4] + z * c_XYZ2sRGB_D65i[5], xyz_shift)); - const uint b = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[6] + y * c_XYZ2sRGB_D65i[7] + z * c_XYZ2sRGB_D65i[8], xyz_shift)); - - uint dst = 0xffu << 24; - - dst |= b << (bidx * 8); - dst |= g << 8; - dst |= r << ((bidx ^ 2) * 8); - - return dst; - } - - template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, float* dst) - { - dst[bidx^2] = src.x * c_XYZ2sRGB_D65f[0] + src.y * c_XYZ2sRGB_D65f[1] + src.z * c_XYZ2sRGB_D65f[2]; - dst[1] = src.x * c_XYZ2sRGB_D65f[3] + src.y * c_XYZ2sRGB_D65f[4] + src.z * c_XYZ2sRGB_D65f[5]; - dst[bidx] = src.x * c_XYZ2sRGB_D65f[6] + src.y * c_XYZ2sRGB_D65f[7] + src.z * c_XYZ2sRGB_D65f[8]; - } - - template struct XYZ2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - XYZ2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ XYZ2RGB() {} - __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} - }; - - template struct XYZ2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return XYZ2RGBConvert(src); - } - __host__ __device__ __forceinline__ XYZ2RGB() {} - __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::XYZ2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -////////////////////////////////////// RGB <-> HSV /////////////////////////////////////// - - namespace color_detail - { - __constant__ int c_HsvDivTable [256] = {0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096}; - __constant__ int c_HsvDivTable180[256] = {0, 122880, 61440, 40960, 30720, 24576, 20480, 17554, 15360, 13653, 12288, 11171, 10240, 9452, 8777, 8192, 7680, 7228, 6827, 6467, 6144, 5851, 5585, 5343, 5120, 4915, 4726, 4551, 4389, 4237, 4096, 3964, 3840, 3724, 3614, 3511, 3413, 3321, 3234, 3151, 3072, 2997, 2926, 2858, 2793, 2731, 2671, 2614, 2560, 2508, 2458, 2409, 2363, 2318, 2276, 2234, 2194, 2156, 2119, 2083, 2048, 2014, 1982, 1950, 1920, 1890, 1862, 1834, 1807, 1781, 1755, 1731, 1707, 1683, 1661, 1638, 1617, 1596, 1575, 1555, 1536, 1517, 1499, 1480, 1463, 1446, 1429, 1412, 1396, 1381, 1365, 1350, 1336, 1321, 1307, 1293, 1280, 1267, 1254, 1241, 1229, 1217, 1205, 1193, 1182, 1170, 1159, 1148, 1138, 1127, 1117, 1107, 1097, 1087, 1078, 1069, 1059, 1050, 1041, 1033, 1024, 1016, 1007, 999, 991, 983, 975, 968, 960, 953, 945, 938, 931, 924, 917, 910, 904, 897, 890, 884, 878, 871, 865, 859, 853, 847, 842, 836, 830, 825, 819, 814, 808, 803, 798, 793, 788, 783, 778, 773, 768, 763, 759, 754, 749, 745, 740, 736, 731, 727, 723, 719, 714, 710, 706, 702, 698, 694, 690, 686, 683, 679, 675, 671, 668, 664, 661, 657, 654, 650, 647, 643, 640, 637, 633, 630, 627, 624, 621, 617, 614, 611, 608, 605, 602, 599, 597, 594, 591, 588, 585, 582, 580, 577, 574, 572, 569, 566, 564, 561, 559, 556, 554, 551, 549, 546, 544, 541, 539, 537, 534, 532, 530, 527, 525, 523, 521, 518, 516, 514, 512, 510, 508, 506, 504, 502, 500, 497, 495, 493, 492, 490, 488, 486, 484, 482}; - __constant__ int c_HsvDivTable256[256] = {0, 174763, 87381, 58254, 43691, 34953, 29127, 24966, 21845, 19418, 17476, 15888, 14564, 13443, 12483, 11651, 10923, 10280, 9709, 9198, 8738, 8322, 7944, 7598, 7282, 6991, 6722, 6473, 6242, 6026, 5825, 5638, 5461, 5296, 5140, 4993, 4855, 4723, 4599, 4481, 4369, 4263, 4161, 4064, 3972, 3884, 3799, 3718, 3641, 3567, 3495, 3427, 3361, 3297, 3236, 3178, 3121, 3066, 3013, 2962, 2913, 2865, 2819, 2774, 2731, 2689, 2648, 2608, 2570, 2533, 2497, 2461, 2427, 2394, 2362, 2330, 2300, 2270, 2241, 2212, 2185, 2158, 2131, 2106, 2081, 2056, 2032, 2009, 1986, 1964, 1942, 1920, 1900, 1879, 1859, 1840, 1820, 1802, 1783, 1765, 1748, 1730, 1713, 1697, 1680, 1664, 1649, 1633, 1618, 1603, 1589, 1574, 1560, 1547, 1533, 1520, 1507, 1494, 1481, 1469, 1456, 1444, 1432, 1421, 1409, 1398, 1387, 1376, 1365, 1355, 1344, 1334, 1324, 1314, 1304, 1295, 1285, 1276, 1266, 1257, 1248, 1239, 1231, 1222, 1214, 1205, 1197, 1189, 1181, 1173, 1165, 1157, 1150, 1142, 1135, 1128, 1120, 1113, 1106, 1099, 1092, 1085, 1079, 1072, 1066, 1059, 1053, 1046, 1040, 1034, 1028, 1022, 1016, 1010, 1004, 999, 993, 987, 982, 976, 971, 966, 960, 955, 950, 945, 940, 935, 930, 925, 920, 915, 910, 906, 901, 896, 892, 887, 883, 878, 874, 869, 865, 861, 857, 853, 848, 844, 840, 836, 832, 828, 824, 820, 817, 813, 809, 805, 802, 798, 794, 791, 787, 784, 780, 777, 773, 770, 767, 763, 760, 757, 753, 750, 747, 744, 741, 737, 734, 731, 728, 725, 722, 719, 716, 713, 710, 708, 705, 702, 699, 696, 694, 691, 688, 685}; - - template static __device__ void RGB2HSVConvert(const uchar* src, D& dst) - { - const int hsv_shift = 12; - const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; - - int b = src[bidx], g = src[1], r = src[bidx^2]; - int h, s, v = b; - int vmin = b, diff; - int vr, vg; - - v = ::max(v, g); - v = ::max(v, r); - vmin = ::min(vmin, g); - vmin = ::min(vmin, r); - - diff = v - vmin; - vr = (v == r) * -1; - vg = (v == g) * -1; - - s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; - h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); - h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; - h += (h < 0) * hr; - - dst.x = saturate_cast(h); - dst.y = (uchar)s; - dst.z = (uchar)v; - } - - template static __device__ uint RGB2HSVConvert(uint src) - { - const int hsv_shift = 12; - const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; - - const int b = 0xff & (src >> (bidx * 8)); - const int g = 0xff & (src >> 8); - const int r = 0xff & (src >> ((bidx ^ 2) * 8)); - - int h, s, v = b; - int vmin = b, diff; - int vr, vg; - - v = ::max(v, g); - v = ::max(v, r); - vmin = ::min(vmin, g); - vmin = ::min(vmin, r); - - diff = v - vmin; - vr = (v == r) * -1; - vg = (v == g) * -1; - - s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; - h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); - h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; - h += (h < 0) * hr; - - uint dst = 0; - - dst |= saturate_cast(h); - dst |= (0xffu & s) << 8; - dst |= (0xffu & v) << 16; - - return dst; - } - - template static __device__ void RGB2HSVConvert(const float* src, D& dst) - { - const float hscale = hr * (1.f / 360.f); - - float b = src[bidx], g = src[1], r = src[bidx^2]; - float h, s, v; - - float vmin, diff; - - v = vmin = r; - v = fmax(v, g); - v = fmax(v, b); - vmin = fmin(vmin, g); - vmin = fmin(vmin, b); - - diff = v - vmin; - s = diff / (float)(::fabs(v) + numeric_limits::epsilon()); - diff = (float)(60. / (diff + numeric_limits::epsilon())); - - h = (v == r) * (g - b) * diff; - h += (v != r && v == g) * ((b - r) * diff + 120.f); - h += (v != r && v != g) * ((r - g) * diff + 240.f); - h += (h < 0) * 360.f; - - dst.x = h * hscale; - dst.y = s; - dst.z = v; - } - - template struct RGB2HSV - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2HSVConvert(&src.x, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2HSV() {} - __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} - }; - - template struct RGB2HSV : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return RGB2HSVConvert(src); - } - __host__ __device__ __forceinline__ RGB2HSV() {} - __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ int c_HsvSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; - - template static __device__ void HSV2RGBConvert(const T& src, float* dst) - { - const float hscale = 6.f / hr; - - float h = src.x, s = src.y, v = src.z; - float b = v, g = v, r = v; - - if (s != 0) - { - h *= hscale; - - if( h < 0 ) - do h += 6; while( h < 0 ); - else if( h >= 6 ) - do h -= 6; while( h >= 6 ); - - int sector = __float2int_rd(h); - h -= sector; - - if ( (unsigned)sector >= 6u ) - { - sector = 0; - h = 0.f; - } - - float tab[4]; - tab[0] = v; - tab[1] = v * (1.f - s); - tab[2] = v * (1.f - s * h); - tab[3] = v * (1.f - s * (1.f - h)); - - b = tab[c_HsvSectorData[sector][0]]; - g = tab[c_HsvSectorData[sector][1]]; - r = tab[c_HsvSectorData[sector][2]]; - } - - dst[bidx] = b; - dst[1] = g; - dst[bidx^2] = r; - } - - template static __device__ void HSV2RGBConvert(const T& src, uchar* dst) - { - float3 buf; - - buf.x = src.x; - buf.y = src.y * (1.f / 255.f); - buf.z = src.z * (1.f / 255.f); - - HSV2RGBConvert(buf, &buf.x); - - dst[0] = saturate_cast(buf.x * 255.f); - dst[1] = saturate_cast(buf.y * 255.f); - dst[2] = saturate_cast(buf.z * 255.f); - } - - template static __device__ uint HSV2RGBConvert(uint src) - { - float3 buf; - - buf.x = src & 0xff; - buf.y = ((src >> 8) & 0xff) * (1.f/255.f); - buf.z = ((src >> 16) & 0xff) * (1.f/255.f); - - HSV2RGBConvert(buf, &buf.x); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(buf.x * 255.f); - dst |= saturate_cast(buf.y * 255.f) << 8; - dst |= saturate_cast(buf.z * 255.f) << 16; - - return dst; - } - - template struct HSV2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - HSV2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ HSV2RGB() {} - __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} - }; - - template struct HSV2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return HSV2RGBConvert(src); - } - __host__ __device__ __forceinline__ HSV2RGB() {} - __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -/////////////////////////////////////// RGB <-> HLS //////////////////////////////////////// - - namespace color_detail - { - template static __device__ void RGB2HLSConvert(const float* src, D& dst) - { - const float hscale = hr * (1.f / 360.f); - - float b = src[bidx], g = src[1], r = src[bidx^2]; - float h = 0.f, s = 0.f, l; - float vmin, vmax, diff; - - vmax = vmin = r; - vmax = fmax(vmax, g); - vmax = fmax(vmax, b); - vmin = fmin(vmin, g); - vmin = fmin(vmin, b); - - diff = vmax - vmin; - l = (vmax + vmin) * 0.5f; - - if (diff > numeric_limits::epsilon()) - { - s = (l < 0.5f) * diff / (vmax + vmin); - s += (l >= 0.5f) * diff / (2.0f - vmax - vmin); - - diff = 60.f / diff; - - h = (vmax == r) * (g - b) * diff; - h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f); - h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f); - h += (h < 0.f) * 360.f; - } - - dst.x = h * hscale; - dst.y = l; - dst.z = s; - } - - template static __device__ void RGB2HLSConvert(const uchar* src, D& dst) - { - float3 buf; - - buf.x = src[0] * (1.f / 255.f); - buf.y = src[1] * (1.f / 255.f); - buf.z = src[2] * (1.f / 255.f); - - RGB2HLSConvert(&buf.x, buf); - - dst.x = saturate_cast(buf.x); - dst.y = saturate_cast(buf.y*255.f); - dst.z = saturate_cast(buf.z*255.f); - } - - template static __device__ uint RGB2HLSConvert(uint src) - { - float3 buf; - - buf.x = (0xff & src) * (1.f / 255.f); - buf.y = (0xff & (src >> 8)) * (1.f / 255.f); - buf.z = (0xff & (src >> 16)) * (1.f / 255.f); - - RGB2HLSConvert(&buf.x, buf); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(buf.x); - dst |= saturate_cast(buf.y * 255.f) << 8; - dst |= saturate_cast(buf.z * 255.f) << 16; - - return dst; - } - - template struct RGB2HLS - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2HLSConvert(&src.x, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2HLS() {} - __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} - }; - - template struct RGB2HLS : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return RGB2HLSConvert(src); - } - __host__ __device__ __forceinline__ RGB2HLS() {} - __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ int c_HlsSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; - - template static __device__ void HLS2RGBConvert(const T& src, float* dst) - { - const float hscale = 6.0f / hr; - - float h = src.x, l = src.y, s = src.z; - float b = l, g = l, r = l; - - if (s != 0) - { - float p2 = (l <= 0.5f) * l * (1 + s); - p2 += (l > 0.5f) * (l + s - l * s); - float p1 = 2 * l - p2; - - h *= hscale; - - if( h < 0 ) - do h += 6; while( h < 0 ); - else if( h >= 6 ) - do h -= 6; while( h >= 6 ); - - int sector; - sector = __float2int_rd(h); - - h -= sector; - - float tab[4]; - tab[0] = p2; - tab[1] = p1; - tab[2] = p1 + (p2 - p1) * (1 - h); - tab[3] = p1 + (p2 - p1) * h; - - b = tab[c_HlsSectorData[sector][0]]; - g = tab[c_HlsSectorData[sector][1]]; - r = tab[c_HlsSectorData[sector][2]]; - } - - dst[bidx] = b; - dst[1] = g; - dst[bidx^2] = r; - } - - template static __device__ void HLS2RGBConvert(const T& src, uchar* dst) - { - float3 buf; - - buf.x = src.x; - buf.y = src.y * (1.f / 255.f); - buf.z = src.z * (1.f / 255.f); - - HLS2RGBConvert(buf, &buf.x); - - dst[0] = saturate_cast(buf.x * 255.f); - dst[1] = saturate_cast(buf.y * 255.f); - dst[2] = saturate_cast(buf.z * 255.f); - } - - template static __device__ uint HLS2RGBConvert(uint src) - { - float3 buf; - - buf.x = 0xff & src; - buf.y = (0xff & (src >> 8)) * (1.f / 255.f); - buf.z = (0xff & (src >> 16)) * (1.f / 255.f); - - HLS2RGBConvert(buf, &buf.x); - - uint dst = 0xffu << 24; - - dst |= saturate_cast(buf.x * 255.f); - dst |= saturate_cast(buf.y * 255.f) << 8; - dst |= saturate_cast(buf.z * 255.f) << 16; - - return dst; - } - - template struct HLS2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - HLS2RGBConvert(src, &dst.x); - setAlpha(dst, ColorChannel::max()); - - return dst; - } - __host__ __device__ __forceinline__ HLS2RGB() {} - __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} - }; - - template struct HLS2RGB : unary_function - { - __device__ __forceinline__ uint operator()(uint src) const - { - return HLS2RGBConvert(src); - } - __host__ __device__ __forceinline__ HLS2RGB() {} - __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(name, scn, dcn, bidx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; \ - template <> struct name ## _full_traits \ - { \ - typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> Lab ///////////////////////////////////// - - namespace color_detail - { - enum - { - LAB_CBRT_TAB_SIZE = 1024, - GAMMA_TAB_SIZE = 1024, - lab_shift = xyz_shift, - gamma_shift = 3, - lab_shift2 = (lab_shift + gamma_shift), - LAB_CBRT_TAB_SIZE_B = (256 * 3 / 2 * (1 << gamma_shift)) - }; - - __constant__ ushort c_sRGBGammaTab_b[] = {0,1,1,2,2,3,4,4,5,6,6,7,8,8,9,10,11,11,12,13,14,15,16,17,19,20,21,22,24,25,26,28,29,31,33,34,36,38,40,41,43,45,47,49,51,54,56,58,60,63,65,68,70,73,75,78,81,83,86,89,92,95,98,101,105,108,111,115,118,121,125,129,132,136,140,144,147,151,155,160,164,168,172,176,181,185,190,194,199,204,209,213,218,223,228,233,239,244,249,255,260,265,271,277,282,288,294,300,306,312,318,324,331,337,343,350,356,363,370,376,383,390,397,404,411,418,426,433,440,448,455,463,471,478,486,494,502,510,518,527,535,543,552,560,569,578,586,595,604,613,622,631,641,650,659,669,678,688,698,707,717,727,737,747,757,768,778,788,799,809,820,831,842,852,863,875,886,897,908,920,931,943,954,966,978,990,1002,1014,1026,1038,1050,1063,1075,1088,1101,1113,1126,1139,1152,1165,1178,1192,1205,1218,1232,1245,1259,1273,1287,1301,1315,1329,1343,1357,1372,1386,1401,1415,1430,1445,1460,1475,1490,1505,1521,1536,1551,1567,1583,1598,1614,1630,1646,1662,1678,1695,1711,1728,1744,1761,1778,1794,1811,1828,1846,1863,1880,1897,1915,1933,1950,1968,1986,2004,2022,2040}; - - __device__ __forceinline__ int LabCbrt_b(int i) - { - float x = i * (1.f / (255.f * (1 << gamma_shift))); - return (1 << lab_shift2) * (x < 0.008856f ? x * 7.787f + 0.13793103448275862f : ::cbrtf(x)); - } - - template - __device__ __forceinline__ void RGB2LabConvert_b(const T& src, D& dst) - { - const int Lscale = (116 * 255 + 50) / 100; - const int Lshift = -((16 * 255 * (1 << lab_shift2) + 50) / 100); - - int B = blueIdx == 0 ? src.x : src.z; - int G = src.y; - int R = blueIdx == 0 ? src.z : src.x; - - if (srgb) - { - B = c_sRGBGammaTab_b[B]; - G = c_sRGBGammaTab_b[G]; - R = c_sRGBGammaTab_b[R]; - } - else - { - B <<= 3; - G <<= 3; - R <<= 3; - } - - int fX = LabCbrt_b(CV_DESCALE(B * 778 + G * 1541 + R * 1777, lab_shift)); - int fY = LabCbrt_b(CV_DESCALE(B * 296 + G * 2929 + R * 871, lab_shift)); - int fZ = LabCbrt_b(CV_DESCALE(B * 3575 + G * 448 + R * 73, lab_shift)); - - int L = CV_DESCALE(Lscale * fY + Lshift, lab_shift2); - int a = CV_DESCALE(500 * (fX - fY) + 128 * (1 << lab_shift2), lab_shift2); - int b = CV_DESCALE(200 * (fY - fZ) + 128 * (1 << lab_shift2), lab_shift2); - - dst.x = saturate_cast(L); - dst.y = saturate_cast(a); - dst.z = saturate_cast(b); - } - - __device__ __forceinline__ float splineInterpolate(float x, const float* tab, int n) - { - int ix = ::min(::max(int(x), 0), n-1); - x -= ix; - tab += ix * 4; - return ((tab[3] * x + tab[2]) * x + tab[1]) * x + tab[0]; - } - - __constant__ float c_sRGBGammaTab[] = {0,7.55853e-05,0.,-7.51331e-13,7.55853e-05,7.55853e-05,-2.25399e-12,3.75665e-12,0.000151171,7.55853e-05,9.01597e-12,-6.99932e-12,0.000226756,7.55853e-05,-1.1982e-11,2.41277e-12,0.000302341,7.55853e-05,-4.74369e-12,1.19001e-11,0.000377927,7.55853e-05,3.09568e-11,-2.09095e-11,0.000453512,7.55853e-05,-3.17718e-11,1.35303e-11,0.000529097,7.55853e-05,8.81905e-12,-4.10782e-12,0.000604683,7.55853e-05,-3.50439e-12,2.90097e-12,0.000680268,7.55853e-05,5.19852e-12,-7.49607e-12,0.000755853,7.55853e-05,-1.72897e-11,2.70833e-11,0.000831439,7.55854e-05,6.39602e-11,-4.26295e-11,0.000907024,7.55854e-05,-6.39282e-11,2.70193e-11,0.000982609,7.55853e-05,1.71298e-11,-7.24017e-12,0.00105819,7.55853e-05,-4.59077e-12,1.94137e-12,0.00113378,7.55853e-05,1.23333e-12,-5.25291e-13,0.00120937,7.55853e-05,-3.42545e-13,1.59799e-13,0.00128495,7.55853e-05,1.36852e-13,-1.13904e-13,0.00136054,7.55853e-05,-2.04861e-13,2.95818e-13,0.00143612,7.55853e-05,6.82594e-13,-1.06937e-12,0.00151171,7.55853e-05,-2.52551e-12,3.98166e-12,0.00158729,7.55853e-05,9.41946e-12,-1.48573e-11,0.00166288,7.55853e-05,-3.51523e-11,5.54474e-11,0.00173846,7.55854e-05,1.3119e-10,-9.0517e-11,0.00181405,7.55854e-05,-1.40361e-10,7.37899e-11,0.00188963,7.55853e-05,8.10085e-11,-8.82272e-11,0.00196522,7.55852e-05,-1.83673e-10,1.62704e-10,0.0020408,7.55853e-05,3.04438e-10,-2.13341e-10,0.00211639,7.55853e-05,-3.35586e-10,2.25e-10,0.00219197,7.55853e-05,3.39414e-10,-2.20997e-10,0.00226756,7.55853e-05,-3.23576e-10,1.93326e-10,0.00234315,7.55853e-05,2.564e-10,-8.66446e-11,0.00241873,7.55855e-05,-3.53328e-12,-7.9578e-11,0.00249432,7.55853e-05,-2.42267e-10,1.72126e-10,0.0025699,7.55853e-05,2.74111e-10,-1.43265e-10,0.00264549,7.55854e-05,-1.55683e-10,-6.47292e-11,0.00272107,7.55849e-05,-3.4987e-10,8.67842e-10,0.00279666,7.55868e-05,2.25366e-09,-3.8723e-09,0.00287224,7.55797e-05,-9.36325e-09,1.5087e-08,0.00294783,7.56063e-05,3.58978e-08,-5.69415e-08,0.00302341,7.55072e-05,-1.34927e-07,2.13144e-07,0.003099,7.58768e-05,5.04507e-07,1.38713e-07,0.00317552,7.7302e-05,9.20646e-07,-1.55186e-07,0.00325359,7.86777e-05,4.55087e-07,4.26813e-08,0.00333276,7.97159e-05,5.83131e-07,-1.06495e-08,0.00341305,8.08502e-05,5.51182e-07,3.87467e-09,0.00349446,8.19642e-05,5.62806e-07,-1.92586e-10,0.00357698,8.30892e-05,5.62228e-07,1.0866e-09,0.00366063,8.4217e-05,5.65488e-07,5.02818e-10,0.00374542,8.53494e-05,5.66997e-07,8.60211e-10,0.00383133,8.6486e-05,5.69577e-07,7.13044e-10,0.00391839,8.76273e-05,5.71716e-07,4.78527e-10,0.00400659,8.87722e-05,5.73152e-07,1.09818e-09,0.00409594,8.99218e-05,5.76447e-07,2.50964e-10,0.00418644,9.10754e-05,5.772e-07,1.15762e-09,0.00427809,9.22333e-05,5.80672e-07,2.40865e-10,0.0043709,9.33954e-05,5.81395e-07,1.13854e-09,0.00446488,9.45616e-05,5.84811e-07,3.27267e-10,0.00456003,9.57322e-05,5.85792e-07,8.1197e-10,0.00465635,9.69062e-05,5.88228e-07,6.15823e-10,0.00475384,9.80845e-05,5.90076e-07,9.15747e-10,0.00485252,9.92674e-05,5.92823e-07,3.778e-10,0.00495238,0.000100454,5.93956e-07,8.32623e-10,0.00505343,0.000101645,5.96454e-07,4.82695e-10,0.00515567,0.000102839,5.97902e-07,9.61904e-10,0.00525911,0.000104038,6.00788e-07,3.26281e-10,0.00536375,0.00010524,6.01767e-07,9.926e-10,0.00546959,0.000106447,6.04745e-07,3.59933e-10,0.00557664,0.000107657,6.05824e-07,8.2728e-10,0.0056849,0.000108871,6.08306e-07,5.21898e-10,0.00579438,0.00011009,6.09872e-07,8.10492e-10,0.00590508,0.000111312,6.12303e-07,4.27046e-10,0.00601701,0.000112538,6.13585e-07,7.40878e-10,0.00613016,0.000113767,6.15807e-07,8.00469e-10,0.00624454,0.000115001,6.18209e-07,2.48178e-10,0.00636016,0.000116238,6.18953e-07,1.00073e-09,0.00647702,0.000117479,6.21955e-07,4.05654e-10,0.00659512,0.000118724,6.23172e-07,6.36192e-10,0.00671447,0.000119973,6.25081e-07,7.74927e-10,0.00683507,0.000121225,6.27406e-07,4.54975e-10,0.00695692,0.000122481,6.28771e-07,6.64841e-10,0.00708003,0.000123741,6.30765e-07,6.10972e-10,0.00720441,0.000125004,6.32598e-07,6.16543e-10,0.00733004,0.000126271,6.34448e-07,6.48204e-10,0.00745695,0.000127542,6.36392e-07,5.15835e-10,0.00758513,0.000128816,6.3794e-07,5.48103e-10,0.00771458,0.000130094,6.39584e-07,1.01706e-09,0.00784532,0.000131376,6.42635e-07,4.0283e-11,0.00797734,0.000132661,6.42756e-07,6.84471e-10,0.00811064,0.000133949,6.4481e-07,9.47144e-10,0.00824524,0.000135241,6.47651e-07,1.83472e-10,0.00838112,0.000136537,6.48201e-07,1.11296e-09,0.00851831,0.000137837,6.5154e-07,2.13163e-11,0.0086568,0.00013914,6.51604e-07,6.64462e-10,0.00879659,0.000140445,6.53598e-07,1.04613e-09,0.00893769,0.000141756,6.56736e-07,-1.92377e-10,0.0090801,0.000143069,6.56159e-07,1.58601e-09,0.00922383,0.000144386,6.60917e-07,-5.63754e-10,0.00936888,0.000145706,6.59226e-07,1.60033e-09,0.00951524,0.000147029,6.64027e-07,-2.49543e-10,0.00966294,0.000148356,6.63278e-07,1.26043e-09,0.00981196,0.000149687,6.67059e-07,-1.35572e-10,0.00996231,0.00015102,6.66653e-07,1.14458e-09,0.010114,0.000152357,6.70086e-07,2.13864e-10,0.010267,0.000153698,6.70728e-07,7.93856e-10,0.0104214,0.000155042,6.73109e-07,3.36077e-10,0.0105771,0.000156389,6.74118e-07,6.55765e-10,0.0107342,0.000157739,6.76085e-07,7.66211e-10,0.0108926,0.000159094,6.78384e-07,4.66116e-12,0.0110524,0.000160451,6.78398e-07,1.07775e-09,0.0112135,0.000161811,6.81631e-07,3.41023e-10,0.011376,0.000163175,6.82654e-07,3.5205e-10,0.0115398,0.000164541,6.8371e-07,1.04473e-09,0.0117051,0.000165912,6.86844e-07,1.25757e-10,0.0118717,0.000167286,6.87222e-07,3.14818e-10,0.0120396,0.000168661,6.88166e-07,1.40886e-09,0.012209,0.000170042,6.92393e-07,-3.62244e-10,0.0123797,0.000171425,6.91306e-07,9.71397e-10,0.0125518,0.000172811,6.9422e-07,2.02003e-10,0.0127253,0.0001742,6.94826e-07,1.01448e-09,0.0129002,0.000175593,6.97869e-07,3.96653e-10,0.0130765,0.00017699,6.99059e-07,1.92927e-10,0.0132542,0.000178388,6.99638e-07,6.94305e-10,0.0134333,0.00017979,7.01721e-07,7.55108e-10,0.0136138,0.000181195,7.03986e-07,1.05918e-11,0.0137957,0.000182603,7.04018e-07,1.06513e-09,0.013979,0.000184015,7.07214e-07,3.85512e-10,0.0141637,0.00018543,7.0837e-07,1.86769e-10,0.0143499,0.000186848,7.0893e-07,7.30116e-10,0.0145374,0.000188268,7.11121e-07,6.17983e-10,0.0147264,0.000189692,7.12975e-07,5.23282e-10,0.0149168,0.000191119,7.14545e-07,8.28398e-11,0.0151087,0.000192549,7.14793e-07,1.0081e-09,0.0153019,0.000193981,7.17817e-07,5.41244e-10,0.0154966,0.000195418,7.19441e-07,-3.7907e-10,0.0156928,0.000196856,7.18304e-07,1.90641e-09,0.0158903,0.000198298,7.24023e-07,-7.27387e-10,0.0160893,0.000199744,7.21841e-07,1.00317e-09,0.0162898,0.000201191,7.24851e-07,4.39949e-10,0.0164917,0.000202642,7.2617e-07,9.6234e-10,0.0166951,0.000204097,7.29057e-07,-5.64019e-10,0.0168999,0.000205554,7.27365e-07,1.29374e-09,0.0171062,0.000207012,7.31247e-07,9.77025e-10,0.017314,0.000208478,7.34178e-07,-1.47651e-09,0.0175232,0.000209942,7.29748e-07,3.06636e-09,0.0177338,0.00021141,7.38947e-07,-1.47573e-09,0.017946,0.000212884,7.3452e-07,9.7386e-10,0.0181596,0.000214356,7.37442e-07,1.30562e-09,0.0183747,0.000215835,7.41358e-07,-6.08376e-10,0.0185913,0.000217315,7.39533e-07,1.12785e-09,0.0188093,0.000218798,7.42917e-07,-1.77711e-10,0.0190289,0.000220283,7.42384e-07,1.44562e-09,0.0192499,0.000221772,7.46721e-07,-1.68825e-11,0.0194724,0.000223266,7.4667e-07,4.84533e-10,0.0196964,0.000224761,7.48124e-07,-5.85298e-11,0.0199219,0.000226257,7.47948e-07,1.61217e-09,0.0201489,0.000227757,7.52785e-07,-8.02136e-10,0.0203775,0.00022926,7.50378e-07,1.59637e-09,0.0206075,0.000230766,7.55167e-07,4.47168e-12,0.020839,0.000232276,7.55181e-07,2.48387e-10,0.021072,0.000233787,7.55926e-07,8.6474e-10,0.0213066,0.000235302,7.5852e-07,1.78299e-11,0.0215426,0.000236819,7.58573e-07,9.26567e-10,0.0217802,0.000238339,7.61353e-07,1.34529e-12,0.0220193,0.000239862,7.61357e-07,9.30659e-10,0.0222599,0.000241387,7.64149e-07,1.34529e-12,0.0225021,0.000242915,7.64153e-07,9.26567e-10,0.0227458,0.000244447,7.66933e-07,1.76215e-11,0.022991,0.00024598,7.66986e-07,8.65536e-10,0.0232377,0.000247517,7.69582e-07,2.45677e-10,0.023486,0.000249057,7.70319e-07,1.44193e-11,0.0237358,0.000250598,7.70363e-07,1.55918e-09,0.0239872,0.000252143,7.7504e-07,-6.63173e-10,0.0242401,0.000253691,7.73051e-07,1.09357e-09,0.0244946,0.000255241,7.76331e-07,1.41919e-11,0.0247506,0.000256793,7.76374e-07,7.12248e-10,0.0250082,0.000258348,7.78511e-07,8.62049e-10,0.0252673,0.000259908,7.81097e-07,-4.35061e-10,0.025528,0.000261469,7.79792e-07,8.7825e-10,0.0257902,0.000263031,7.82426e-07,6.47181e-10,0.0260541,0.000264598,7.84368e-07,2.58448e-10,0.0263194,0.000266167,7.85143e-07,1.81558e-10,0.0265864,0.000267738,7.85688e-07,8.78041e-10,0.0268549,0.000269312,7.88322e-07,3.15102e-11,0.027125,0.000270889,7.88417e-07,8.58525e-10,0.0273967,0.000272468,7.90992e-07,2.59812e-10,0.02767,0.000274051,7.91772e-07,-3.5224e-11,0.0279448,0.000275634,7.91666e-07,1.74377e-09,0.0282212,0.000277223,7.96897e-07,-1.35196e-09,0.0284992,0.000278813,7.92841e-07,1.80141e-09,0.0287788,0.000280404,7.98246e-07,-2.65629e-10,0.0290601,0.000281999,7.97449e-07,1.12374e-09,0.0293428,0.000283598,8.0082e-07,-5.04106e-10,0.0296272,0.000285198,7.99308e-07,8.92764e-10,0.0299132,0.000286799,8.01986e-07,6.58379e-10,0.0302008,0.000288405,8.03961e-07,1.98971e-10,0.0304901,0.000290014,8.04558e-07,4.08382e-10,0.0307809,0.000291624,8.05783e-07,3.01839e-11,0.0310733,0.000293236,8.05874e-07,1.33343e-09,0.0313673,0.000294851,8.09874e-07,2.2419e-10,0.031663,0.000296472,8.10547e-07,-3.67606e-10,0.0319603,0.000298092,8.09444e-07,1.24624e-09,0.0322592,0.000299714,8.13182e-07,-8.92025e-10,0.0325597,0.000301338,8.10506e-07,2.32183e-09,0.0328619,0.000302966,8.17472e-07,-9.44719e-10,0.0331657,0.000304598,8.14638e-07,1.45703e-09,0.0334711,0.000306232,8.19009e-07,-1.15805e-09,0.0337781,0.000307866,8.15535e-07,3.17507e-09,0.0340868,0.000309507,8.2506e-07,-4.09161e-09,0.0343971,0.000311145,8.12785e-07,5.74079e-09,0.0347091,0.000312788,8.30007e-07,-3.97034e-09,0.0350227,0.000314436,8.18096e-07,2.68985e-09,0.035338,0.00031608,8.26166e-07,6.61676e-10,0.0356549,0.000317734,8.28151e-07,-1.61123e-09,0.0359734,0.000319386,8.23317e-07,2.05786e-09,0.0362936,0.000321038,8.29491e-07,8.30388e-10,0.0366155,0.0003227,8.31982e-07,-1.65424e-09,0.036939,0.000324359,8.27019e-07,2.06129e-09,0.0372642,0.000326019,8.33203e-07,8.59719e-10,0.0375911,0.000327688,8.35782e-07,-1.77488e-09,0.0379196,0.000329354,8.30458e-07,2.51464e-09,0.0382498,0.000331023,8.38002e-07,-8.33135e-10,0.0385817,0.000332696,8.35502e-07,8.17825e-10,0.0389152,0.00033437,8.37956e-07,1.28718e-09,0.0392504,0.00033605,8.41817e-07,-2.2413e-09,0.0395873,0.000337727,8.35093e-07,3.95265e-09,0.0399258,0.000339409,8.46951e-07,-2.39332e-09,0.0402661,0.000341095,8.39771e-07,1.89533e-09,0.040608,0.000342781,8.45457e-07,-1.46271e-09,0.0409517,0.000344467,8.41069e-07,3.95554e-09,0.041297,0.000346161,8.52936e-07,-3.18369e-09,0.041644,0.000347857,8.43385e-07,1.32873e-09,0.0419927,0.000349548,8.47371e-07,1.59402e-09,0.0423431,0.000351248,8.52153e-07,-2.54336e-10,0.0426952,0.000352951,8.5139e-07,-5.76676e-10,0.043049,0.000354652,8.4966e-07,2.56114e-09,0.0434045,0.000356359,8.57343e-07,-2.21744e-09,0.0437617,0.000358067,8.50691e-07,2.58344e-09,0.0441206,0.000359776,8.58441e-07,-6.65826e-10,0.0444813,0.000361491,8.56444e-07,7.99218e-11,0.0448436,0.000363204,8.56684e-07,3.46063e-10,0.0452077,0.000364919,8.57722e-07,2.26116e-09,0.0455734,0.000366641,8.64505e-07,-1.94005e-09,0.045941,0.000368364,8.58685e-07,1.77384e-09,0.0463102,0.000370087,8.64007e-07,-1.43005e-09,0.0466811,0.000371811,8.59717e-07,3.94634e-09,0.0470538,0.000373542,8.71556e-07,-3.17946e-09,0.0474282,0.000375276,8.62017e-07,1.32104e-09,0.0478043,0.000377003,8.6598e-07,1.62045e-09,0.0481822,0.00037874,8.70842e-07,-3.52297e-10,0.0485618,0.000380481,8.69785e-07,-2.11211e-10,0.0489432,0.00038222,8.69151e-07,1.19716e-09,0.0493263,0.000383962,8.72743e-07,-8.52026e-10,0.0497111,0.000385705,8.70187e-07,2.21092e-09,0.0500977,0.000387452,8.76819e-07,-5.41339e-10,0.050486,0.000389204,8.75195e-07,-4.5361e-11,0.0508761,0.000390954,8.75059e-07,7.22669e-10,0.0512679,0.000392706,8.77227e-07,8.79936e-10,0.0516615,0.000394463,8.79867e-07,-5.17048e-10,0.0520568,0.000396222,8.78316e-07,1.18833e-09,0.0524539,0.000397982,8.81881e-07,-5.11022e-10,0.0528528,0.000399744,8.80348e-07,8.55683e-10,0.0532534,0.000401507,8.82915e-07,8.13562e-10,0.0536558,0.000403276,8.85356e-07,-3.84603e-10,0.05406,0.000405045,8.84202e-07,7.24962e-10,0.0544659,0.000406816,8.86377e-07,1.20986e-09,0.0548736,0.000408592,8.90006e-07,-1.83896e-09,0.0552831,0.000410367,8.84489e-07,2.42071e-09,0.0556944,0.000412143,8.91751e-07,-3.93413e-10,0.0561074,0.000413925,8.90571e-07,-8.46967e-10,0.0565222,0.000415704,8.8803e-07,3.78122e-09,0.0569388,0.000417491,8.99374e-07,-3.1021e-09,0.0573572,0.000419281,8.90068e-07,1.17658e-09,0.0577774,0.000421064,8.93597e-07,2.12117e-09,0.0581993,0.000422858,8.99961e-07,-2.21068e-09,0.0586231,0.000424651,8.93329e-07,2.9961e-09,0.0590486,0.000426447,9.02317e-07,-2.32311e-09,0.059476,0.000428244,8.95348e-07,2.57122e-09,0.0599051,0.000430043,9.03062e-07,-5.11098e-10,0.0603361,0.000431847,9.01528e-07,-5.27166e-10,0.0607688,0.000433649,8.99947e-07,2.61984e-09,0.0612034,0.000435457,9.07806e-07,-2.50141e-09,0.0616397,0.000437265,9.00302e-07,3.66045e-09,0.0620779,0.000439076,9.11283e-07,-4.68977e-09,0.0625179,0.000440885,8.97214e-07,7.64783e-09,0.0629597,0.000442702,9.20158e-07,-7.27499e-09,0.0634033,0.000444521,8.98333e-07,6.55113e-09,0.0638487,0.000446337,9.17986e-07,-4.02844e-09,0.0642959,0.000448161,9.05901e-07,2.11196e-09,0.064745,0.000449979,9.12236e-07,3.03125e-09,0.0651959,0.000451813,9.2133e-07,-6.78648e-09,0.0656486,0.000453635,9.00971e-07,9.21375e-09,0.0661032,0.000455464,9.28612e-07,-7.71684e-09,0.0665596,0.000457299,9.05462e-07,6.7522e-09,0.0670178,0.00045913,9.25718e-07,-4.3907e-09,0.0674778,0.000460968,9.12546e-07,3.36e-09,0.0679397,0.000462803,9.22626e-07,-1.59876e-09,0.0684034,0.000464644,9.1783e-07,3.0351e-09,0.068869,0.000466488,9.26935e-07,-3.09101e-09,0.0693364,0.000468333,9.17662e-07,1.8785e-09,0.0698057,0.000470174,9.23298e-07,3.02733e-09,0.0702768,0.00047203,9.3238e-07,-6.53722e-09,0.0707497,0.000473875,9.12768e-07,8.22054e-09,0.0712245,0.000475725,9.37429e-07,-3.99325e-09,0.0717012,0.000477588,9.2545e-07,3.01839e-10,0.0721797,0.00047944,9.26355e-07,2.78597e-09,0.0726601,0.000481301,9.34713e-07,-3.99507e-09,0.0731423,0.000483158,9.22728e-07,5.7435e-09,0.0736264,0.000485021,9.39958e-07,-4.07776e-09,0.0741123,0.000486888,9.27725e-07,3.11695e-09,0.0746002,0.000488753,9.37076e-07,-9.39394e-10,0.0750898,0.000490625,9.34258e-07,6.4055e-10,0.0755814,0.000492495,9.3618e-07,-1.62265e-09,0.0760748,0.000494363,9.31312e-07,5.84995e-09,0.0765701,0.000496243,9.48861e-07,-6.87601e-09,0.0770673,0.00049812,9.28233e-07,6.75296e-09,0.0775664,0.000499997,9.48492e-07,-5.23467e-09,0.0780673,0.000501878,9.32788e-07,6.73523e-09,0.0785701,0.000503764,9.52994e-07,-6.80514e-09,0.0790748,0.000505649,9.32578e-07,5.5842e-09,0.0795814,0.000507531,9.49331e-07,-6.30583e-10,0.0800899,0.000509428,9.47439e-07,-3.0618e-09,0.0806003,0.000511314,9.38254e-07,5.4273e-09,0.0811125,0.000513206,9.54536e-07,-3.74627e-09,0.0816267,0.000515104,9.43297e-07,2.10713e-09,0.0821427,0.000516997,9.49618e-07,2.76839e-09,0.0826607,0.000518905,9.57924e-07,-5.73006e-09,0.0831805,0.000520803,9.40733e-07,5.25072e-09,0.0837023,0.0005227,9.56486e-07,-3.71718e-10,0.084226,0.000524612,9.5537e-07,-3.76404e-09,0.0847515,0.000526512,9.44078e-07,7.97735e-09,0.085279,0.000528424,9.6801e-07,-5.79367e-09,0.0858084,0.000530343,9.50629e-07,2.96268e-10,0.0863397,0.000532245,9.51518e-07,4.6086e-09,0.0868729,0.000534162,9.65344e-07,-3.82947e-09,0.087408,0.000536081,9.53856e-07,3.25861e-09,0.087945,0.000537998,9.63631e-07,-1.7543e-09,0.088484,0.00053992,9.58368e-07,3.75849e-09,0.0890249,0.000541848,9.69644e-07,-5.82891e-09,0.0895677,0.00054377,9.52157e-07,4.65593e-09,0.0901124,0.000545688,9.66125e-07,2.10643e-09,0.0906591,0.000547627,9.72444e-07,-5.63099e-09,0.0912077,0.000549555,9.55551e-07,5.51627e-09,0.0917582,0.000551483,9.721e-07,-1.53292e-09,0.0923106,0.000553422,9.67501e-07,6.15311e-10,0.092865,0.000555359,9.69347e-07,-9.28291e-10,0.0934213,0.000557295,9.66562e-07,3.09774e-09,0.0939796,0.000559237,9.75856e-07,-4.01186e-09,0.0945398,0.000561177,9.6382e-07,5.49892e-09,0.095102,0.000563121,9.80317e-07,-3.08258e-09,0.0956661,0.000565073,9.71069e-07,-6.19176e-10,0.0962321,0.000567013,9.69212e-07,5.55932e-09,0.0968001,0.000568968,9.8589e-07,-6.71704e-09,0.09737,0.00057092,9.65738e-07,6.40762e-09,0.0979419,0.00057287,9.84961e-07,-4.0122e-09,0.0985158,0.000574828,9.72925e-07,2.19059e-09,0.0990916,0.000576781,9.79496e-07,2.70048e-09,0.0996693,0.000578748,9.87598e-07,-5.54193e-09,0.100249,0.000580706,9.70972e-07,4.56597e-09,0.100831,0.000582662,9.8467e-07,2.17923e-09,0.101414,0.000584638,9.91208e-07,-5.83232e-09,0.102,0.000586603,9.73711e-07,6.24884e-09,0.102588,0.000588569,9.92457e-07,-4.26178e-09,0.103177,0.000590541,9.79672e-07,3.34781e-09,0.103769,0.00059251,9.89715e-07,-1.67904e-09,0.104362,0.000594485,9.84678e-07,3.36839e-09,0.104958,0.000596464,9.94783e-07,-4.34397e-09,0.105555,0.000598441,9.81751e-07,6.55696e-09,0.106155,0.000600424,1.00142e-06,-6.98272e-09,0.106756,0.000602406,9.80474e-07,6.4728e-09,0.107359,0.000604386,9.99893e-07,-4.00742e-09,0.107965,0.000606374,9.8787e-07,2.10654e-09,0.108572,0.000608356,9.9419e-07,3.0318e-09,0.109181,0.000610353,1.00329e-06,-6.7832e-09,0.109793,0.00061234,9.82936e-07,9.1998e-09,0.110406,0.000614333,1.01054e-06,-7.6642e-09,0.111021,0.000616331,9.87543e-07,6.55579e-09,0.111639,0.000618326,1.00721e-06,-3.65791e-09,0.112258,0.000620329,9.96236e-07,6.25467e-10,0.112879,0.000622324,9.98113e-07,1.15593e-09,0.113503,0.000624323,1.00158e-06,2.20158e-09,0.114128,0.000626333,1.00819e-06,-2.51191e-09,0.114755,0.000628342,1.00065e-06,3.95517e-10,0.115385,0.000630345,1.00184e-06,9.29807e-10,0.116016,0.000632351,1.00463e-06,3.33599e-09,0.116649,0.00063437,1.01463e-06,-6.82329e-09,0.117285,0.000636379,9.94163e-07,9.05595e-09,0.117922,0.000638395,1.02133e-06,-7.04862e-09,0.118562,0.000640416,1.00019e-06,4.23737e-09,0.119203,0.000642429,1.0129e-06,-2.45033e-09,0.119847,0.000644448,1.00555e-06,5.56395e-09,0.120492,0.000646475,1.02224e-06,-4.9043e-09,0.121139,0.000648505,1.00753e-06,-8.47952e-10,0.121789,0.000650518,1.00498e-06,8.29622e-09,0.122441,0.000652553,1.02987e-06,-9.98538e-09,0.123094,0.000654582,9.99914e-07,9.2936e-09,0.12375,0.00065661,1.02779e-06,-4.83707e-09,0.124407,0.000658651,1.01328e-06,2.60411e-09,0.125067,0.000660685,1.0211e-06,-5.57945e-09,0.125729,0.000662711,1.00436e-06,1.22631e-08,0.126392,0.000664756,1.04115e-06,-1.36704e-08,0.127058,0.000666798,1.00014e-06,1.26161e-08,0.127726,0.000668836,1.03798e-06,-6.99155e-09,0.128396,0.000670891,1.01701e-06,4.48836e-10,0.129068,0.000672926,1.01836e-06,5.19606e-09,0.129742,0.000674978,1.03394e-06,-6.3319e-09,0.130418,0.000677027,1.01495e-06,5.2305e-09,0.131096,0.000679073,1.03064e-06,3.11123e-10,0.131776,0.000681135,1.03157e-06,-6.47511e-09,0.132458,0.000683179,1.01215e-06,1.06882e-08,0.133142,0.000685235,1.04421e-06,-6.47519e-09,0.133829,0.000687304,1.02479e-06,3.11237e-10,0.134517,0.000689355,1.02572e-06,5.23035e-09,0.135207,0.000691422,1.04141e-06,-6.3316e-09,0.1359,0.000693486,1.02242e-06,5.19484e-09,0.136594,0.000695546,1.038e-06,4.53497e-10,0.137291,0.000697623,1.03936e-06,-7.00891e-09,0.137989,0.000699681,1.01834e-06,1.2681e-08,0.13869,0.000701756,1.05638e-06,-1.39128e-08,0.139393,0.000703827,1.01464e-06,1.31679e-08,0.140098,0.000705896,1.05414e-06,-8.95659e-09,0.140805,0.000707977,1.02727e-06,7.75742e-09,0.141514,0.000710055,1.05055e-06,-7.17182e-09,0.142225,0.000712135,1.02903e-06,6.02862e-09,0.142938,0.000714211,1.04712e-06,-2.04163e-09,0.143653,0.000716299,1.04099e-06,2.13792e-09,0.144371,0.000718387,1.04741e-06,-6.51009e-09,0.14509,0.000720462,1.02787e-06,9.00123e-09,0.145812,0.000722545,1.05488e-06,3.07523e-10,0.146535,0.000724656,1.0558e-06,-1.02312e-08,0.147261,0.000726737,1.02511e-06,1.0815e-08,0.147989,0.000728819,1.05755e-06,-3.22681e-09,0.148719,0.000730925,1.04787e-06,2.09244e-09,0.14945,0.000733027,1.05415e-06,-5.143e-09,0.150185,0.00073512,1.03872e-06,3.57844e-09,0.150921,0.000737208,1.04946e-06,5.73027e-09,0.151659,0.000739324,1.06665e-06,-1.15983e-08,0.152399,0.000741423,1.03185e-06,1.08605e-08,0.153142,0.000743519,1.06443e-06,-2.04106e-09,0.153886,0.000745642,1.05831e-06,-2.69642e-09,0.154633,0.00074775,1.05022e-06,-2.07425e-09,0.155382,0.000749844,1.044e-06,1.09934e-08,0.156133,0.000751965,1.07698e-06,-1.20972e-08,0.156886,0.000754083,1.04069e-06,7.59288e-09,0.157641,0.000756187,1.06347e-06,-3.37305e-09,0.158398,0.000758304,1.05335e-06,5.89921e-09,0.159158,0.000760428,1.07104e-06,-5.32248e-09,0.159919,0.000762554,1.05508e-06,4.8927e-10,0.160683,0.000764666,1.05654e-06,3.36547e-09,0.161448,0.000766789,1.06664e-06,9.50081e-10,0.162216,0.000768925,1.06949e-06,-7.16568e-09,0.162986,0.000771043,1.04799e-06,1.28114e-08,0.163758,0.000773177,1.08643e-06,-1.42774e-08,0.164533,0.000775307,1.0436e-06,1.44956e-08,0.165309,0.000777438,1.08708e-06,-1.39025e-08,0.166087,0.00077957,1.04538e-06,1.13118e-08,0.166868,0.000781695,1.07931e-06,-1.54224e-09,0.167651,0.000783849,1.07468e-06,-5.14312e-09,0.168436,0.000785983,1.05925e-06,7.21381e-09,0.169223,0.000788123,1.0809e-06,-8.81096e-09,0.170012,0.000790259,1.05446e-06,1.31289e-08,0.170803,0.000792407,1.09385e-06,-1.39022e-08,0.171597,0.000794553,1.05214e-06,1.26775e-08,0.172392,0.000796695,1.09018e-06,-7.00557e-09,0.17319,0.000798855,1.06916e-06,4.43796e-10,0.17399,0.000800994,1.07049e-06,5.23031e-09,0.174792,0.000803151,1.08618e-06,-6.46397e-09,0.175596,0.000805304,1.06679e-06,5.72444e-09,0.176403,0.000807455,1.08396e-06,-1.53254e-09,0.177211,0.000809618,1.07937e-06,4.05673e-10,0.178022,0.000811778,1.08058e-06,-9.01916e-11,0.178835,0.000813939,1.08031e-06,-4.49821e-11,0.17965,0.000816099,1.08018e-06,2.70234e-10,0.180467,0.00081826,1.08099e-06,-1.03603e-09,0.181286,0.000820419,1.07788e-06,3.87392e-09,0.182108,0.000822587,1.0895e-06,4.41522e-10,0.182932,0.000824767,1.09083e-06,-5.63997e-09,0.183758,0.000826932,1.07391e-06,7.21707e-09,0.184586,0.000829101,1.09556e-06,-8.32718e-09,0.185416,0.000831267,1.07058e-06,1.11907e-08,0.186248,0.000833442,1.10415e-06,-6.63336e-09,0.187083,0.00083563,1.08425e-06,4.41484e-10,0.187919,0.0008378,1.08557e-06,4.86754e-09,0.188758,0.000839986,1.10017e-06,-5.01041e-09,0.189599,0.000842171,1.08514e-06,2.72811e-10,0.190443,0.000844342,1.08596e-06,3.91916e-09,0.191288,0.000846526,1.09772e-06,-1.04819e-09,0.192136,0.000848718,1.09457e-06,2.73531e-10,0.192985,0.000850908,1.0954e-06,-4.58916e-11,0.193837,0.000853099,1.09526e-06,-9.01158e-11,0.194692,0.000855289,1.09499e-06,4.06506e-10,0.195548,0.00085748,1.09621e-06,-1.53595e-09,0.196407,0.000859668,1.0916e-06,5.73717e-09,0.197267,0.000861869,1.10881e-06,-6.51164e-09,0.19813,0.000864067,1.08928e-06,5.40831e-09,0.198995,0.000866261,1.1055e-06,-2.20401e-10,0.199863,0.000868472,1.10484e-06,-4.52652e-09,0.200732,0.000870668,1.09126e-06,3.42508e-09,0.201604,0.000872861,1.10153e-06,5.72762e-09,0.202478,0.000875081,1.11872e-06,-1.14344e-08,0.203354,0.000877284,1.08441e-06,1.02076e-08,0.204233,0.000879484,1.11504e-06,4.06355e-10,0.205113,0.000881715,1.11626e-06,-1.18329e-08,0.205996,0.000883912,1.08076e-06,1.71227e-08,0.206881,0.000886125,1.13213e-06,-1.19546e-08,0.207768,0.000888353,1.09626e-06,8.93465e-10,0.208658,0.000890548,1.09894e-06,8.38062e-09,0.209549,0.000892771,1.12408e-06,-4.61353e-09,0.210443,0.000895006,1.11024e-06,-4.82756e-09,0.211339,0.000897212,1.09576e-06,9.02245e-09,0.212238,0.00089943,1.12283e-06,-1.45997e-09,0.213138,0.000901672,1.11845e-06,-3.18255e-09,0.214041,0.000903899,1.1089e-06,-7.11073e-10,0.214946,0.000906115,1.10677e-06,6.02692e-09,0.215853,0.000908346,1.12485e-06,-8.49548e-09,0.216763,0.00091057,1.09936e-06,1.30537e-08,0.217675,0.000912808,1.13852e-06,-1.3917e-08,0.218588,0.000915044,1.09677e-06,1.28121e-08,0.219505,0.000917276,1.13521e-06,-7.5288e-09,0.220423,0.000919523,1.11262e-06,2.40205e-09,0.221344,0.000921756,1.11983e-06,-2.07941e-09,0.222267,0.000923989,1.11359e-06,5.91551e-09,0.223192,0.000926234,1.13134e-06,-6.68149e-09,0.224119,0.000928477,1.11129e-06,5.90929e-09,0.225049,0.000930717,1.12902e-06,-2.05436e-09,0.22598,0.000932969,1.12286e-06,2.30807e-09,0.226915,0.000935222,1.12978e-06,-7.17796e-09,0.227851,0.00093746,1.10825e-06,1.15028e-08,0.228789,0.000939711,1.14276e-06,-9.03083e-09,0.22973,0.000941969,1.11566e-06,9.71932e-09,0.230673,0.00094423,1.14482e-06,-1.49452e-08,0.231619,0.000946474,1.09998e-06,2.02591e-08,0.232566,0.000948735,1.16076e-06,-2.13879e-08,0.233516,0.000950993,1.0966e-06,2.05888e-08,0.234468,0.000953247,1.15837e-06,-1.62642e-08,0.235423,0.000955515,1.10957e-06,1.46658e-08,0.236379,0.000957779,1.15357e-06,-1.25966e-08,0.237338,0.000960048,1.11578e-06,5.91793e-09,0.238299,0.000962297,1.13353e-06,3.82602e-09,0.239263,0.000964576,1.14501e-06,-6.3208e-09,0.240229,0.000966847,1.12605e-06,6.55613e-09,0.241197,0.000969119,1.14572e-06,-5.00268e-09,0.242167,0.000971395,1.13071e-06,-1.44659e-09,0.243139,0.000973652,1.12637e-06,1.07891e-08,0.244114,0.000975937,1.15874e-06,-1.19073e-08,0.245091,0.000978219,1.12302e-06,7.03782e-09,0.246071,0.000980486,1.14413e-06,-1.34276e-09,0.247052,0.00098277,1.1401e-06,-1.66669e-09,0.248036,0.000985046,1.1351e-06,8.00935e-09,0.249022,0.00098734,1.15913e-06,-1.54694e-08,0.250011,0.000989612,1.11272e-06,2.4066e-08,0.251002,0.000991909,1.18492e-06,-2.11901e-08,0.251995,0.000994215,1.12135e-06,1.08973e-09,0.25299,0.000996461,1.12462e-06,1.68311e-08,0.253988,0.000998761,1.17511e-06,-8.8094e-09,0.254987,0.00100109,1.14868e-06,-1.13958e-08,0.25599,0.00100335,1.1145e-06,2.45902e-08,0.256994,0.00100565,1.18827e-06,-2.73603e-08,0.258001,0.00100795,1.10618e-06,2.52464e-08,0.25901,0.00101023,1.18192e-06,-1.40207e-08,0.260021,0.00101256,1.13986e-06,1.03387e-09,0.261035,0.00101484,1.14296e-06,9.8853e-09,0.262051,0.00101715,1.17262e-06,-1.07726e-08,0.263069,0.00101947,1.1403e-06,3.40272e-09,0.26409,0.00102176,1.15051e-06,-2.83827e-09,0.265113,0.00102405,1.142e-06,7.95039e-09,0.266138,0.00102636,1.16585e-06,8.39047e-10,0.267166,0.00102869,1.16836e-06,-1.13066e-08,0.268196,0.00103099,1.13444e-06,1.4585e-08,0.269228,0.00103331,1.1782e-06,-1.72314e-08,0.270262,0.00103561,1.1265e-06,2.45382e-08,0.271299,0.00103794,1.20012e-06,-2.13166e-08,0.272338,0.00104028,1.13617e-06,1.12364e-09,0.273379,0.00104255,1.13954e-06,1.68221e-08,0.274423,0.00104488,1.19001e-06,-8.80736e-09,0.275469,0.00104723,1.16358e-06,-1.13948e-08,0.276518,0.00104953,1.1294e-06,2.45839e-08,0.277568,0.00105186,1.20315e-06,-2.73361e-08,0.278621,0.00105418,1.12114e-06,2.51559e-08,0.279677,0.0010565,1.19661e-06,-1.36832e-08,0.280734,0.00105885,1.15556e-06,-2.25706e-10,0.281794,0.00106116,1.15488e-06,1.45862e-08,0.282857,0.00106352,1.19864e-06,-2.83167e-08,0.283921,0.00106583,1.11369e-06,3.90759e-08,0.284988,0.00106817,1.23092e-06,-3.85801e-08,0.286058,0.00107052,1.11518e-06,2.58375e-08,0.287129,0.00107283,1.19269e-06,-5.16498e-09,0.288203,0.0010752,1.1772e-06,-5.17768e-09,0.28928,0.00107754,1.16167e-06,-3.92671e-09,0.290358,0.00107985,1.14988e-06,2.08846e-08,0.29144,0.00108221,1.21254e-06,-2.00072e-08,0.292523,0.00108458,1.15252e-06,-4.60659e-10,0.293609,0.00108688,1.15114e-06,2.18499e-08,0.294697,0.00108925,1.21669e-06,-2.73343e-08,0.295787,0.0010916,1.13468e-06,2.78826e-08,0.29688,0.00109395,1.21833e-06,-2.45915e-08,0.297975,0.00109632,1.14456e-06,1.08787e-08,0.299073,0.00109864,1.17719e-06,1.08788e-08,0.300172,0.00110102,1.20983e-06,-2.45915e-08,0.301275,0.00110337,1.13605e-06,2.78828e-08,0.302379,0.00110573,1.2197e-06,-2.73348e-08,0.303486,0.00110808,1.1377e-06,2.18518e-08,0.304595,0.00111042,1.20325e-06,-4.67556e-10,0.305707,0.00111283,1.20185e-06,-1.99816e-08,0.306821,0.00111517,1.14191e-06,2.07891e-08,0.307937,0.00111752,1.20427e-06,-3.57026e-09,0.309056,0.00111992,1.19356e-06,-6.50797e-09,0.310177,0.00112228,1.17404e-06,-2.00165e-10,0.3113,0.00112463,1.17344e-06,7.30874e-09,0.312426,0.001127,1.19536e-06,7.67424e-10,0.313554,0.00112939,1.19767e-06,-1.03784e-08,0.314685,0.00113176,1.16653e-06,1.09437e-08,0.315818,0.00113412,1.19936e-06,-3.59406e-09,0.316953,0.00113651,1.18858e-06,3.43251e-09,0.318091,0.0011389,1.19888e-06,-1.0136e-08,0.319231,0.00114127,1.16847e-06,7.30915e-09,0.320374,0.00114363,1.1904e-06,1.07018e-08,0.321518,0.00114604,1.2225e-06,-2.03137e-08,0.322666,0.00114842,1.16156e-06,1.09484e-08,0.323815,0.00115078,1.19441e-06,6.32224e-09,0.324967,0.00115319,1.21337e-06,-6.43509e-09,0.326122,0.00115559,1.19407e-06,-1.03842e-08,0.327278,0.00115795,1.16291e-06,1.81697e-08,0.328438,0.00116033,1.21742e-06,-2.6901e-09,0.329599,0.00116276,1.20935e-06,-7.40939e-09,0.330763,0.00116515,1.18713e-06,2.52533e-09,0.331929,0.00116754,1.1947e-06,-2.69191e-09,0.333098,0.00116992,1.18663e-06,8.24218e-09,0.334269,0.00117232,1.21135e-06,-4.74377e-10,0.335443,0.00117474,1.20993e-06,-6.34471e-09,0.336619,0.00117714,1.1909e-06,-3.94922e-09,0.337797,0.00117951,1.17905e-06,2.21417e-08,0.338978,0.00118193,1.24547e-06,-2.50128e-08,0.340161,0.00118435,1.17043e-06,1.8305e-08,0.341346,0.00118674,1.22535e-06,-1.84048e-08,0.342534,0.00118914,1.17013e-06,2.55121e-08,0.343725,0.00119156,1.24667e-06,-2.40389e-08,0.344917,0.00119398,1.17455e-06,1.10389e-08,0.346113,0.00119636,1.20767e-06,9.68574e-09,0.34731,0.0011988,1.23673e-06,-1.99797e-08,0.34851,0.00120122,1.17679e-06,1.06284e-08,0.349713,0.0012036,1.20867e-06,7.26868e-09,0.350917,0.00120604,1.23048e-06,-9.90072e-09,0.352125,0.00120847,1.20078e-06,2.53177e-09,0.353334,0.00121088,1.20837e-06,-2.26199e-10,0.354546,0.0012133,1.20769e-06,-1.62705e-09,0.355761,0.00121571,1.20281e-06,6.73435e-09,0.356978,0.00121813,1.22302e-06,4.49207e-09,0.358197,0.00122059,1.23649e-06,-2.47027e-08,0.359419,0.00122299,1.16238e-06,3.47142e-08,0.360643,0.00122542,1.26653e-06,-2.47472e-08,0.36187,0.00122788,1.19229e-06,4.66965e-09,0.363099,0.00123028,1.20629e-06,6.06872e-09,0.36433,0.00123271,1.2245e-06,8.57729e-10,0.365564,0.00123516,1.22707e-06,-9.49952e-09,0.366801,0.00123759,1.19858e-06,7.33792e-09,0.36804,0.00124001,1.22059e-06,9.95025e-09,0.369281,0.00124248,1.25044e-06,-1.73366e-08,0.370525,0.00124493,1.19843e-06,-2.08464e-10,0.371771,0.00124732,1.1978e-06,1.81704e-08,0.373019,0.00124977,1.25232e-06,-1.28683e-08,0.37427,0.00125224,1.21371e-06,3.50042e-09,0.375524,0.00125468,1.22421e-06,-1.1335e-09,0.37678,0.00125712,1.22081e-06,1.03345e-09,0.378038,0.00125957,1.22391e-06,-3.00023e-09,0.379299,0.00126201,1.21491e-06,1.09676e-08,0.380562,0.00126447,1.24781e-06,-1.10676e-08,0.381828,0.00126693,1.21461e-06,3.50042e-09,0.383096,0.00126937,1.22511e-06,-2.93403e-09,0.384366,0.00127181,1.21631e-06,8.23574e-09,0.385639,0.00127427,1.24102e-06,-2.06607e-10,0.386915,0.00127675,1.2404e-06,-7.40935e-09,0.388193,0.00127921,1.21817e-06,4.1761e-11,0.389473,0.00128165,1.21829e-06,7.24223e-09,0.390756,0.0012841,1.24002e-06,7.91564e-10,0.392042,0.00128659,1.2424e-06,-1.04086e-08,0.393329,0.00128904,1.21117e-06,1.10405e-08,0.39462,0.0012915,1.24429e-06,-3.951e-09,0.395912,0.00129397,1.23244e-06,4.7634e-09,0.397208,0.00129645,1.24673e-06,-1.51025e-08,0.398505,0.0012989,1.20142e-06,2.58443e-08,0.399805,0.00130138,1.27895e-06,-2.86702e-08,0.401108,0.00130385,1.19294e-06,2.92318e-08,0.402413,0.00130632,1.28064e-06,-2.86524e-08,0.403721,0.0013088,1.19468e-06,2.57731e-08,0.405031,0.00131127,1.272e-06,-1.48355e-08,0.406343,0.00131377,1.2275e-06,3.76652e-09,0.407658,0.00131623,1.23879e-06,-2.30784e-10,0.408976,0.00131871,1.2381e-06,-2.84331e-09,0.410296,0.00132118,1.22957e-06,1.16041e-08,0.411618,0.00132367,1.26438e-06,-1.37708e-08,0.412943,0.00132616,1.22307e-06,1.36768e-08,0.41427,0.00132865,1.2641e-06,-1.1134e-08,0.4156,0.00133114,1.2307e-06,1.05714e-09,0.416933,0.00133361,1.23387e-06,6.90538e-09,0.418267,0.00133609,1.25459e-06,1.12372e-09,0.419605,0.00133861,1.25796e-06,-1.14002e-08,0.420945,0.00134109,1.22376e-06,1.46747e-08,0.422287,0.00134358,1.26778e-06,-1.7496e-08,0.423632,0.00134606,1.21529e-06,2.5507e-08,0.424979,0.00134857,1.29182e-06,-2.49272e-08,0.426329,0.00135108,1.21703e-06,1.45972e-08,0.427681,0.00135356,1.26083e-06,-3.65935e-09,0.429036,0.00135607,1.24985e-06,4.00178e-11,0.430393,0.00135857,1.24997e-06,3.49917e-09,0.431753,0.00136108,1.26047e-06,-1.40366e-08,0.433116,0.00136356,1.21836e-06,2.28448e-08,0.43448,0.00136606,1.28689e-06,-1.77378e-08,0.435848,0.00136858,1.23368e-06,1.83043e-08,0.437218,0.0013711,1.28859e-06,-2.56769e-08,0.43859,0.0013736,1.21156e-06,2.47987e-08,0.439965,0.0013761,1.28595e-06,-1.39133e-08,0.441342,0.00137863,1.24421e-06,1.05202e-09,0.442722,0.00138112,1.24737e-06,9.70507e-09,0.444104,0.00138365,1.27649e-06,-1.00698e-08,0.445489,0.00138617,1.24628e-06,7.72123e-10,0.446877,0.00138867,1.24859e-06,6.98132e-09,0.448267,0.00139118,1.26954e-06,1.10477e-09,0.449659,0.00139373,1.27285e-06,-1.14003e-08,0.451054,0.00139624,1.23865e-06,1.4694e-08,0.452452,0.00139876,1.28273e-06,-1.75734e-08,0.453852,0.00140127,1.23001e-06,2.5797e-08,0.455254,0.00140381,1.3074e-06,-2.60097e-08,0.456659,0.00140635,1.22937e-06,1.86371e-08,0.458067,0.00140886,1.28529e-06,-1.8736e-08,0.459477,0.00141137,1.22908e-06,2.65048e-08,0.46089,0.00141391,1.30859e-06,-2.76784e-08,0.462305,0.00141645,1.22556e-06,2.46043e-08,0.463722,0.00141897,1.29937e-06,-1.11341e-08,0.465143,0.00142154,1.26597e-06,-9.87033e-09,0.466565,0.00142404,1.23636e-06,2.08131e-08,0.467991,0.00142657,1.2988e-06,-1.37773e-08,0.469419,0.00142913,1.25746e-06,4.49378e-09,0.470849,0.00143166,1.27094e-06,-4.19781e-09,0.472282,0.00143419,1.25835e-06,1.22975e-08,0.473717,0.00143674,1.29524e-06,-1.51902e-08,0.475155,0.00143929,1.24967e-06,1.86608e-08,0.476596,0.00144184,1.30566e-06,-2.96506e-08,0.478039,0.00144436,1.2167e-06,4.03368e-08,0.479485,0.00144692,1.33771e-06,-4.22896e-08,0.480933,0.00144947,1.21085e-06,3.94148e-08,0.482384,0.00145201,1.32909e-06,-2.59626e-08,0.483837,0.00145459,1.2512e-06,4.83124e-09,0.485293,0.0014571,1.2657e-06,6.63757e-09,0.486751,0.00145966,1.28561e-06,-1.57911e-09,0.488212,0.00146222,1.28087e-06,-3.21468e-10,0.489676,0.00146478,1.27991e-06,2.86517e-09,0.491142,0.00146735,1.2885e-06,-1.11392e-08,0.49261,0.00146989,1.25508e-06,1.18893e-08,0.494081,0.00147244,1.29075e-06,-6.61574e-09,0.495555,0.001475,1.27091e-06,1.45736e-08,0.497031,0.00147759,1.31463e-06,-2.18759e-08,0.49851,0.00148015,1.249e-06,1.33252e-08,0.499992,0.00148269,1.28897e-06,-1.62277e-09,0.501476,0.00148526,1.28411e-06,-6.83421e-09,0.502962,0.00148781,1.2636e-06,2.89596e-08,0.504451,0.00149042,1.35048e-06,-4.93997e-08,0.505943,0.00149298,1.20228e-06,4.94299e-08,0.507437,0.00149553,1.35057e-06,-2.91107e-08,0.508934,0.00149814,1.26324e-06,7.40848e-09,0.510434,0.00150069,1.28547e-06,-5.23187e-10,0.511936,0.00150326,1.2839e-06,-5.31585e-09,0.51344,0.00150581,1.26795e-06,2.17866e-08,0.514947,0.00150841,1.33331e-06,-2.22257e-08,0.516457,0.00151101,1.26663e-06,7.51178e-09,0.517969,0.00151357,1.28917e-06,-7.82128e-09,0.519484,0.00151613,1.2657e-06,2.37733e-08,0.521002,0.00151873,1.33702e-06,-2.76674e-08,0.522522,0.00152132,1.25402e-06,2.72917e-08,0.524044,0.00152391,1.3359e-06,-2.18949e-08,0.525569,0.00152652,1.27021e-06,6.83372e-10,0.527097,0.00152906,1.27226e-06,1.91613e-08,0.528628,0.00153166,1.32974e-06,-1.77241e-08,0.53016,0.00153427,1.27657e-06,-7.86963e-09,0.531696,0.0015368,1.25296e-06,4.92027e-08,0.533234,0.00153945,1.40057e-06,-6.9732e-08,0.534775,0.00154204,1.19138e-06,5.09114e-08,0.536318,0.00154458,1.34411e-06,-1.4704e-08,0.537864,0.00154722,1.3e-06,7.9048e-09,0.539413,0.00154984,1.32371e-06,-1.69152e-08,0.540964,0.00155244,1.27297e-06,1.51355e-10,0.542517,0.00155499,1.27342e-06,1.63099e-08,0.544074,0.00155758,1.32235e-06,-5.78647e-09,0.545633,0.00156021,1.30499e-06,6.83599e-09,0.547194,0.00156284,1.3255e-06,-2.15575e-08,0.548758,0.00156543,1.26083e-06,1.97892e-08,0.550325,0.00156801,1.32019e-06,2.00525e-09,0.551894,0.00157065,1.32621e-06,-2.78103e-08,0.553466,0.00157322,1.24278e-06,4.96314e-08,0.555041,0.00157586,1.39167e-06,-5.1506e-08,0.556618,0.00157849,1.23716e-06,3.71835e-08,0.558198,0.00158107,1.34871e-06,-3.76233e-08,0.55978,0.00158366,1.23584e-06,5.37052e-08,0.561365,0.00158629,1.39695e-06,-5.79884e-08,0.562953,0.00158891,1.22299e-06,5.90392e-08,0.564543,0.00159153,1.4001e-06,-5.89592e-08,0.566136,0.00159416,1.22323e-06,5.7588e-08,0.567731,0.00159678,1.39599e-06,-5.21835e-08,0.569329,0.00159941,1.23944e-06,3.19369e-08,0.57093,0.00160199,1.33525e-06,-1.59594e-08,0.572533,0.00160461,1.28737e-06,3.19006e-08,0.574139,0.00160728,1.38307e-06,-5.20383e-08,0.575748,0.00160989,1.22696e-06,5.70431e-08,0.577359,0.00161251,1.39809e-06,-5.69247e-08,0.578973,0.00161514,1.22731e-06,5.14463e-08,0.580589,0.00161775,1.38165e-06,-2.9651e-08,0.582208,0.00162042,1.2927e-06,7.55339e-09,0.58383,0.00162303,1.31536e-06,-5.62636e-10,0.585455,0.00162566,1.31367e-06,-5.30281e-09,0.587081,0.00162827,1.29776e-06,2.17738e-08,0.588711,0.00163093,1.36309e-06,-2.21875e-08,0.590343,0.00163359,1.29652e-06,7.37164e-09,0.591978,0.00163621,1.31864e-06,-7.29907e-09,0.593616,0.00163882,1.29674e-06,2.18247e-08,0.595256,0.00164148,1.36221e-06,-2.03952e-08,0.596899,0.00164414,1.30103e-06,1.51241e-10,0.598544,0.00164675,1.30148e-06,1.97902e-08,0.600192,0.00164941,1.36085e-06,-1.97074e-08,0.601843,0.00165207,1.30173e-06,-5.65175e-10,0.603496,0.00165467,1.30004e-06,2.1968e-08,0.605152,0.00165734,1.36594e-06,-2.77024e-08,0.606811,0.00165999,1.28283e-06,2.92369e-08,0.608472,0.00166264,1.37054e-06,-2.96407e-08,0.610136,0.00166529,1.28162e-06,2.97215e-08,0.611803,0.00166795,1.37079e-06,-2.96408e-08,0.613472,0.0016706,1.28186e-06,2.92371e-08,0.615144,0.00167325,1.36957e-06,-2.77031e-08,0.616819,0.00167591,1.28647e-06,2.19708e-08,0.618496,0.00167855,1.35238e-06,-5.75407e-10,0.620176,0.00168125,1.35065e-06,-1.9669e-08,0.621858,0.00168389,1.29164e-06,1.96468e-08,0.623544,0.00168653,1.35058e-06,6.86403e-10,0.625232,0.00168924,1.35264e-06,-2.23924e-08,0.626922,0.00169187,1.28547e-06,2.92788e-08,0.628615,0.00169453,1.3733e-06,-3.51181e-08,0.630311,0.00169717,1.26795e-06,5.15889e-08,0.63201,0.00169987,1.42272e-06,-5.2028e-08,0.633711,0.00170255,1.26663e-06,3.73139e-08,0.635415,0.0017052,1.37857e-06,-3.76227e-08,0.637121,0.00170784,1.2657e-06,5.35722e-08,0.63883,0.00171054,1.42642e-06,-5.74567e-08,0.640542,0.00171322,1.25405e-06,5.70456e-08,0.642257,0.0017159,1.42519e-06,-5.15163e-08,0.643974,0.00171859,1.27064e-06,2.98103e-08,0.645694,0.00172122,1.36007e-06,-8.12016e-09,0.647417,0.00172392,1.33571e-06,2.67039e-09,0.649142,0.0017266,1.34372e-06,-2.56152e-09,0.65087,0.00172928,1.33604e-06,7.57571e-09,0.6526,0.00173197,1.35876e-06,-2.77413e-08,0.654334,0.00173461,1.27554e-06,4.3785e-08,0.65607,0.00173729,1.40689e-06,-2.81896e-08,0.657808,0.00174002,1.32233e-06,9.36893e-09,0.65955,0.00174269,1.35043e-06,-9.28617e-09,0.661294,0.00174536,1.32257e-06,2.77757e-08,0.66304,0.00174809,1.4059e-06,-4.2212e-08,0.66479,0.00175078,1.27926e-06,2.1863e-08,0.666542,0.0017534,1.34485e-06,1.43648e-08,0.668297,0.00175613,1.38795e-06,-1.97177e-08,0.670054,0.00175885,1.3288e-06,4.90115e-09,0.671814,0.00176152,1.3435e-06,1.13232e-10,0.673577,0.00176421,1.34384e-06,-5.3542e-09,0.675343,0.00176688,1.32778e-06,2.13035e-08,0.677111,0.0017696,1.39169e-06,-2.02553e-08,0.678882,0.00177232,1.33092e-06,1.13005e-10,0.680656,0.00177499,1.33126e-06,1.98031e-08,0.682432,0.00177771,1.39067e-06,-1.97211e-08,0.684211,0.00178043,1.33151e-06,-5.2349e-10,0.685993,0.00178309,1.32994e-06,2.18151e-08,0.687777,0.00178582,1.39538e-06,-2.71325e-08,0.689564,0.00178853,1.31398e-06,2.71101e-08,0.691354,0.00179124,1.39531e-06,-2.17035e-08,0.693147,0.00179396,1.3302e-06,9.92865e-11,0.694942,0.00179662,1.3305e-06,2.13063e-08,0.69674,0.00179935,1.39442e-06,-2.57198e-08,0.698541,0.00180206,1.31726e-06,2.19682e-08,0.700344,0.00180476,1.38317e-06,-2.54852e-09,0.70215,0.00180752,1.37552e-06,-1.17741e-08,0.703959,0.00181023,1.3402e-06,-9.95999e-09,0.705771,0.00181288,1.31032e-06,5.16141e-08,0.707585,0.00181566,1.46516e-06,-7.72869e-08,0.709402,0.00181836,1.2333e-06,7.87197e-08,0.711222,0.00182106,1.46946e-06,-5.87781e-08,0.713044,0.00182382,1.29312e-06,3.71834e-08,0.714869,0.00182652,1.40467e-06,-3.03511e-08,0.716697,0.00182924,1.31362e-06,2.46161e-08,0.718528,0.00183194,1.38747e-06,-8.5087e-09,0.720361,0.00183469,1.36194e-06,9.41892e-09,0.722197,0.00183744,1.3902e-06,-2.91671e-08,0.724036,0.00184014,1.3027e-06,4.76448e-08,0.725878,0.00184288,1.44563e-06,-4.22028e-08,0.727722,0.00184565,1.31902e-06,1.95682e-09,0.729569,0.00184829,1.3249e-06,3.43754e-08,0.731419,0.00185104,1.42802e-06,-2.0249e-08,0.733271,0.00185384,1.36727e-06,-1.29838e-08,0.735126,0.00185654,1.32832e-06,1.25794e-08,0.736984,0.00185923,1.36606e-06,2.22711e-08,0.738845,0.00186203,1.43287e-06,-4.20594e-08,0.740708,0.00186477,1.3067e-06,2.67571e-08,0.742574,0.00186746,1.38697e-06,-5.36424e-09,0.744443,0.00187022,1.37087e-06,-5.30023e-09,0.746315,0.00187295,1.35497e-06,2.65653e-08,0.748189,0.00187574,1.43467e-06,-4.13564e-08,0.750066,0.00187848,1.3106e-06,1.9651e-08,0.751946,0.00188116,1.36955e-06,2.23572e-08,0.753828,0.00188397,1.43663e-06,-4.9475e-08,0.755714,0.00188669,1.2882e-06,5.63335e-08,0.757602,0.00188944,1.4572e-06,-5.66499e-08,0.759493,0.00189218,1.28725e-06,5.10567e-08,0.761386,0.00189491,1.44042e-06,-2.83677e-08,0.763283,0.00189771,1.35532e-06,2.80962e-09,0.765182,0.00190042,1.36375e-06,1.71293e-08,0.767083,0.0019032,1.41513e-06,-1.17221e-08,0.768988,0.001906,1.37997e-06,-2.98453e-08,0.770895,0.00190867,1.29043e-06,7.14987e-08,0.772805,0.00191146,1.50493e-06,-7.73354e-08,0.774718,0.00191424,1.27292e-06,5.90292e-08,0.776634,0.00191697,1.45001e-06,-3.9572e-08,0.778552,0.00191975,1.33129e-06,3.9654e-08,0.780473,0.00192253,1.45026e-06,-5.94395e-08,0.782397,0.00192525,1.27194e-06,7.88945e-08,0.784324,0.00192803,1.50862e-06,-7.73249e-08,0.786253,0.00193082,1.27665e-06,5.15913e-08,0.788185,0.00193352,1.43142e-06,-9.83099e-09,0.79012,0.00193636,1.40193e-06,-1.22672e-08,0.792058,0.00193912,1.36513e-06,-7.05275e-10,0.793999,0.00194185,1.36301e-06,1.50883e-08,0.795942,0.00194462,1.40828e-06,-4.33147e-11,0.797888,0.00194744,1.40815e-06,-1.49151e-08,0.799837,0.00195021,1.3634e-06,9.93244e-11,0.801788,0.00195294,1.3637e-06,1.45179e-08,0.803743,0.00195571,1.40725e-06,1.43363e-09,0.8057,0.00195853,1.41155e-06,-2.02525e-08,0.80766,0.00196129,1.35079e-06,1.99718e-08,0.809622,0.00196405,1.41071e-06,-3.01649e-11,0.811588,0.00196687,1.41062e-06,-1.9851e-08,0.813556,0.00196964,1.35107e-06,1.98296e-08,0.815527,0.0019724,1.41056e-06,1.37485e-10,0.817501,0.00197522,1.41097e-06,-2.03796e-08,0.819477,0.00197798,1.34983e-06,2.17763e-08,0.821457,0.00198074,1.41516e-06,-7.12085e-09,0.823439,0.00198355,1.3938e-06,6.70707e-09,0.825424,0.00198636,1.41392e-06,-1.97074e-08,0.827412,0.00198913,1.35479e-06,1.25179e-08,0.829402,0.00199188,1.39235e-06,2.92405e-08,0.831396,0.00199475,1.48007e-06,-6.98755e-08,0.833392,0.0019975,1.27044e-06,7.14477e-08,0.835391,0.00200026,1.48479e-06,-3.71014e-08,0.837392,0.00200311,1.37348e-06,1.73533e-08,0.839397,0.00200591,1.42554e-06,-3.23118e-08,0.841404,0.00200867,1.32861e-06,5.2289e-08,0.843414,0.00201148,1.48547e-06,-5.76348e-08,0.845427,0.00201428,1.31257e-06,5.9041e-08,0.847443,0.00201708,1.48969e-06,-5.93197e-08,0.849461,0.00201988,1.31173e-06,5.90289e-08,0.851482,0.00202268,1.48882e-06,-5.75864e-08,0.853507,0.00202549,1.31606e-06,5.21075e-08,0.855533,0.00202828,1.47238e-06,-3.16344e-08,0.857563,0.00203113,1.37748e-06,1.48257e-08,0.859596,0.00203393,1.42196e-06,-2.76684e-08,0.861631,0.00203669,1.33895e-06,3.62433e-08,0.863669,0.00203947,1.44768e-06,1.90463e-09,0.86571,0.00204237,1.45339e-06,-4.38617e-08,0.867754,0.00204515,1.32181e-06,5.43328e-08,0.8698,0.00204796,1.48481e-06,-5.42603e-08,0.87185,0.00205076,1.32203e-06,4.34989e-08,0.873902,0.00205354,1.45252e-06,-5.26029e-10,0.875957,0.00205644,1.45095e-06,-4.13949e-08,0.878015,0.00205922,1.32676e-06,4.68962e-08,0.880075,0.00206201,1.46745e-06,-2.69807e-08,0.882139,0.00206487,1.38651e-06,1.42181e-09,0.884205,0.00206764,1.39077e-06,2.12935e-08,0.886274,0.00207049,1.45465e-06,-2.69912e-08,0.888346,0.00207332,1.37368e-06,2.70664e-08,0.890421,0.00207615,1.45488e-06,-2.16698e-08,0.892498,0.00207899,1.38987e-06,8.14756e-12,0.894579,0.00208177,1.38989e-06,2.16371e-08,0.896662,0.00208462,1.45481e-06,-2.6952e-08,0.898748,0.00208744,1.37395e-06,2.65663e-08,0.900837,0.00209027,1.45365e-06,-1.97084e-08,0.902928,0.00209312,1.39452e-06,-7.33731e-09,0.905023,0.00209589,1.37251e-06,4.90578e-08,0.90712,0.00209878,1.51968e-06,-6.96845e-08,0.90922,0.00210161,1.31063e-06,5.08664e-08,0.911323,0.00210438,1.46323e-06,-1.45717e-08,0.913429,0.00210727,1.41952e-06,7.42038e-09,0.915538,0.00211013,1.44178e-06,-1.51097e-08,0.917649,0.00211297,1.39645e-06,-6.58618e-09,0.919764,0.00211574,1.37669e-06,4.14545e-08,0.921881,0.00211862,1.50105e-06,-4.00222e-08,0.924001,0.0021215,1.38099e-06,-5.7518e-10,0.926124,0.00212426,1.37926e-06,4.23229e-08,0.92825,0.00212714,1.50623e-06,-4.9507e-08,0.930378,0.00213001,1.35771e-06,3.64958e-08,0.93251,0.00213283,1.4672e-06,-3.68713e-08,0.934644,0.00213566,1.35658e-06,5.13848e-08,0.936781,0.00213852,1.51074e-06,-4.94585e-08,0.938921,0.0021414,1.36236e-06,2.72399e-08,0.941064,0.0021442,1.44408e-06,1.0372e-10,0.943209,0.00214709,1.44439e-06,-2.76547e-08,0.945358,0.0021499,1.36143e-06,5.09106e-08,0.947509,0.00215277,1.51416e-06,-5.67784e-08,0.949663,0.00215563,1.34382e-06,5.69935e-08,0.95182,0.00215849,1.5148e-06,-5.19861e-08,0.95398,0.00216136,1.35885e-06,3.17417e-08,0.956143,0.00216418,1.45407e-06,-1.53758e-08,0.958309,0.00216704,1.40794e-06,2.97615e-08,0.960477,0.00216994,1.49723e-06,-4.40657e-08,0.962649,0.00217281,1.36503e-06,2.72919e-08,0.964823,0.00217562,1.44691e-06,-5.49729e-09,0.967,0.0021785,1.43041e-06,-5.30273e-09,0.96918,0.00218134,1.41451e-06,2.67084e-08,0.971363,0.00218425,1.49463e-06,-4.19265e-08,0.973548,0.00218711,1.36885e-06,2.17881e-08,0.975737,0.00218992,1.43422e-06,1.43789e-08,0.977928,0.00219283,1.47735e-06,-1.96989e-08,0.980122,0.00219572,1.41826e-06,4.81221e-09,0.98232,0.00219857,1.43269e-06,4.50048e-10,0.98452,0.00220144,1.43404e-06,-6.61237e-09,0.986722,0.00220429,1.41421e-06,2.59993e-08,0.988928,0.0022072,1.4922e-06,-3.77803e-08,0.991137,0.00221007,1.37886e-06,5.9127e-09,0.993348,0.00221284,1.3966e-06,1.33339e-07,0.995563,0.00221604,1.79662e-06,-5.98872e-07,0.99778,0.00222015,0.,0.}; - - template - __device__ __forceinline__ void RGB2LabConvert_f(const T& src, D& dst) - { - const float _1_3 = 1.0f / 3.0f; - const float _a = 16.0f / 116.0f; - - float B = blueIdx == 0 ? src.x : src.z; - float G = src.y; - float R = blueIdx == 0 ? src.z : src.x; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - } - - float X = B * 0.189828f + G * 0.376219f + R * 0.433953f; - float Y = B * 0.072169f + G * 0.715160f + R * 0.212671f; - float Z = B * 0.872766f + G * 0.109477f + R * 0.017758f; - - float FX = X > 0.008856f ? ::powf(X, _1_3) : (7.787f * X + _a); - float FY = Y > 0.008856f ? ::powf(Y, _1_3) : (7.787f * Y + _a); - float FZ = Z > 0.008856f ? ::powf(Z, _1_3) : (7.787f * Z + _a); - - float L = Y > 0.008856f ? (116.f * FY - 16.f) : (903.3f * Y); - float a = 500.f * (FX - FY); - float b = 200.f * (FY - FZ); - - dst.x = L; - dst.y = a; - dst.z = b; - } - - template struct RGB2Lab; - template - struct RGB2Lab - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LabConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Lab() {} - __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} - }; - template - struct RGB2Lab - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LabConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Lab() {} - __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2Lab functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - __constant__ float c_sRGBInvGammaTab[] = {0,0.0126255,0.,-8.33961e-06,0.0126172,0.0126005,-2.50188e-05,4.1698e-05,0.0252344,0.0126756,0.000100075,-0.000158451,0.0378516,0.0124004,-0.000375277,-0.000207393,0.0496693,0.0110276,-0.000997456,0.00016837,0.0598678,0.00953783,-0.000492346,2.07235e-05,0.068934,0.00861531,-0.000430176,3.62876e-05,0.0771554,0.00786382,-0.000321313,1.87625e-05,0.0847167,0.00727748,-0.000265025,1.53594e-05,0.0917445,0.00679351,-0.000218947,1.10545e-05,0.0983301,0.00638877,-0.000185784,8.66984e-06,0.104542,0.00604322,-0.000159774,6.82996e-06,0.110432,0.00574416,-0.000139284,5.51008e-06,0.116042,0.00548212,-0.000122754,4.52322e-06,0.121406,0.00525018,-0.000109184,3.75557e-06,0.126551,0.00504308,-9.79177e-05,3.17134e-06,0.131499,0.00485676,-8.84037e-05,2.68469e-06,0.13627,0.004688,-8.03496e-05,2.31725e-06,0.14088,0.00453426,-7.33978e-05,2.00868e-06,0.145343,0.00439349,-6.73718e-05,1.74775e-06,0.149671,0.00426399,-6.21286e-05,1.53547e-06,0.153875,0.00414434,-5.75222e-05,1.364e-06,0.157963,0.00403338,-5.34301e-05,1.20416e-06,0.161944,0.00393014,-4.98177e-05,1.09114e-06,0.165825,0.00383377,-4.65443e-05,9.57987e-07,0.169613,0.00374356,-4.36703e-05,8.88359e-07,0.173314,0.00365888,-4.10052e-05,7.7849e-07,0.176933,0.00357921,-3.86697e-05,7.36254e-07,0.180474,0.00350408,-3.6461e-05,6.42534e-07,0.183942,0.00343308,-3.45334e-05,6.12614e-07,0.187342,0.00336586,-3.26955e-05,5.42894e-07,0.190675,0.00330209,-3.10669e-05,5.08967e-07,0.193947,0.00324149,-2.954e-05,4.75977e-07,0.197159,0.00318383,-2.8112e-05,4.18343e-07,0.200315,0.00312887,-2.6857e-05,4.13651e-07,0.203418,0.00307639,-2.5616e-05,3.70847e-07,0.206469,0.00302627,-2.45035e-05,3.3813e-07,0.209471,0.00297828,-2.34891e-05,3.32999e-07,0.212426,0.0029323,-2.24901e-05,2.96826e-07,0.215336,0.00288821,-2.15996e-05,2.82736e-07,0.218203,0.00284586,-2.07514e-05,2.70961e-07,0.221029,0.00280517,-1.99385e-05,2.42744e-07,0.223814,0.00276602,-1.92103e-05,2.33277e-07,0.226561,0.0027283,-1.85105e-05,2.2486e-07,0.229271,0.00269195,-1.78359e-05,2.08383e-07,0.231945,0.00265691,-1.72108e-05,1.93305e-07,0.234585,0.00262307,-1.66308e-05,1.80687e-07,0.237192,0.00259035,-1.60888e-05,1.86632e-07,0.239766,0.00255873,-1.55289e-05,1.60569e-07,0.24231,0.00252815,-1.50472e-05,1.54566e-07,0.244823,0.00249852,-1.45835e-05,1.59939e-07,0.247307,0.00246983,-1.41037e-05,1.29549e-07,0.249763,0.00244202,-1.3715e-05,1.41429e-07,0.252191,0.00241501,-1.32907e-05,1.39198e-07,0.254593,0.00238885,-1.28731e-05,1.06444e-07,0.256969,0.00236342,-1.25538e-05,1.2048e-07,0.25932,0.00233867,-1.21924e-05,1.26892e-07,0.261647,0.00231467,-1.18117e-05,8.72084e-08,0.26395,0.00229131,-1.15501e-05,1.20323e-07,0.26623,0.00226857,-1.11891e-05,8.71514e-08,0.268487,0.00224645,-1.09276e-05,9.73165e-08,0.270723,0.00222489,-1.06357e-05,8.98259e-08,0.272937,0.00220389,-1.03662e-05,7.98218e-08,0.275131,0.00218339,-1.01267e-05,9.75254e-08,0.277304,0.00216343,-9.83416e-06,6.65195e-08,0.279458,0.00214396,-9.63461e-06,8.34313e-08,0.281592,0.00212494,-9.38431e-06,7.65919e-08,0.283708,0.00210641,-9.15454e-06,5.7236e-08,0.285805,0.00208827,-8.98283e-06,8.18939e-08,0.287885,0.00207055,-8.73715e-06,6.2224e-08,0.289946,0.00205326,-8.55047e-06,5.66388e-08,0.291991,0.00203633,-8.38056e-06,6.88491e-08,0.294019,0.00201978,-8.17401e-06,5.53955e-08,0.296031,0.00200359,-8.00782e-06,6.71971e-08,0.298027,0.00198778,-7.80623e-06,3.34439e-08,0.300007,0.00197227,-7.7059e-06,6.7248e-08,0.301971,0.00195706,-7.50416e-06,5.51915e-08,0.303921,0.00194221,-7.33858e-06,3.98124e-08,0.305856,0.00192766,-7.21915e-06,5.37795e-08,0.307776,0.00191338,-7.05781e-06,4.30919e-08,0.309683,0.00189939,-6.92853e-06,4.20744e-08,0.311575,0.00188566,-6.80231e-06,5.68321e-08,0.313454,0.00187223,-6.63181e-06,2.86195e-08,0.31532,0.00185905,-6.54595e-06,3.73075e-08,0.317172,0.00184607,-6.43403e-06,6.05684e-08,0.319012,0.00183338,-6.25233e-06,1.84426e-08,0.320839,0.00182094,-6.197e-06,4.44757e-08,0.322654,0.00180867,-6.06357e-06,4.20729e-08,0.324456,0.00179667,-5.93735e-06,2.56511e-08,0.326247,0.00178488,-5.8604e-06,3.41368e-08,0.328026,0.00177326,-5.75799e-06,4.64177e-08,0.329794,0.00176188,-5.61874e-06,1.86107e-08,0.33155,0.0017507,-5.5629e-06,2.81511e-08,0.333295,0.00173966,-5.47845e-06,4.75987e-08,0.335029,0.00172884,-5.33565e-06,1.98726e-08,0.336753,0.00171823,-5.27604e-06,2.19226e-08,0.338466,0.00170775,-5.21027e-06,4.14483e-08,0.340169,0.00169745,-5.08592e-06,2.09017e-08,0.341861,0.00168734,-5.02322e-06,2.39561e-08,0.343543,0.00167737,-4.95135e-06,3.22852e-08,0.345216,0.00166756,-4.85449e-06,2.57173e-08,0.346878,0.00165793,-4.77734e-06,1.38569e-08,0.348532,0.00164841,-4.73577e-06,3.80634e-08,0.350175,0.00163906,-4.62158e-06,1.27043e-08,0.35181,0.00162985,-4.58347e-06,3.03279e-08,0.353435,0.00162078,-4.49249e-06,1.49961e-08,0.355051,0.00161184,-4.4475e-06,2.88977e-08,0.356659,0.00160303,-4.3608e-06,1.84241e-08,0.358257,0.00159436,-4.30553e-06,1.6616e-08,0.359848,0.0015858,-4.25568e-06,3.43218e-08,0.361429,0.00157739,-4.15272e-06,-4.89172e-09,0.363002,0.00156907,-4.16739e-06,4.48498e-08,0.364567,0.00156087,-4.03284e-06,4.30676e-09,0.366124,0.00155282,-4.01992e-06,2.73303e-08,0.367673,0.00154486,-3.93793e-06,5.58036e-09,0.369214,0.001537,-3.92119e-06,3.97554e-08,0.370747,0.00152928,-3.80193e-06,-1.55904e-08,0.372272,0.00152163,-3.8487e-06,5.24081e-08,0.37379,0.00151409,-3.69147e-06,-1.52272e-08,0.375301,0.00150666,-3.73715e-06,3.83028e-08,0.376804,0.0014993,-3.62225e-06,1.10278e-08,0.378299,0.00149209,-3.58916e-06,6.99326e-09,0.379788,0.00148493,-3.56818e-06,2.06038e-08,0.381269,0.00147786,-3.50637e-06,2.98009e-08,0.382744,0.00147093,-3.41697e-06,-2.05978e-08,0.384211,0.00146404,-3.47876e-06,5.25899e-08,0.385672,0.00145724,-3.32099e-06,-1.09471e-08,0.387126,0.00145056,-3.35383e-06,2.10009e-08,0.388573,0.00144392,-3.29083e-06,1.63501e-08,0.390014,0.00143739,-3.24178e-06,3.00641e-09,0.391448,0.00143091,-3.23276e-06,3.12282e-08,0.392875,0.00142454,-3.13908e-06,-8.70932e-09,0.394297,0.00141824,-3.16521e-06,3.34114e-08,0.395712,0.00141201,-3.06497e-06,-5.72754e-09,0.397121,0.00140586,-3.08215e-06,1.9301e-08,0.398524,0.00139975,-3.02425e-06,1.7931e-08,0.39992,0.00139376,-2.97046e-06,-1.61822e-09,0.401311,0.00138781,-2.97531e-06,1.83442e-08,0.402696,0.00138192,-2.92028e-06,1.76485e-08,0.404075,0.00137613,-2.86733e-06,4.68617e-10,0.405448,0.00137039,-2.86593e-06,1.02794e-08,0.406816,0.00136469,-2.83509e-06,1.80179e-08,0.408178,0.00135908,-2.78104e-06,7.05594e-09,0.409534,0.00135354,-2.75987e-06,1.33633e-08,0.410885,0.00134806,-2.71978e-06,-9.04568e-10,0.41223,0.00134261,-2.72249e-06,2.0057e-08,0.41357,0.00133723,-2.66232e-06,1.00841e-08,0.414905,0.00133194,-2.63207e-06,-7.88835e-10,0.416234,0.00132667,-2.63444e-06,2.28734e-08,0.417558,0.00132147,-2.56582e-06,-1.29785e-09,0.418877,0.00131633,-2.56971e-06,1.21205e-08,0.420191,0.00131123,-2.53335e-06,1.24202e-08,0.421499,0.0013062,-2.49609e-06,-2.19681e-09,0.422803,0.0013012,-2.50268e-06,2.61696e-08,0.424102,0.00129628,-2.42417e-06,-1.30747e-08,0.425396,0.00129139,-2.46339e-06,2.6129e-08,0.426685,0.00128654,-2.38501e-06,-2.03454e-09,0.427969,0.00128176,-2.39111e-06,1.18115e-08,0.429248,0.00127702,-2.35567e-06,1.43932e-08,0.430523,0.00127235,-2.31249e-06,-9.77965e-09,0.431793,0.00126769,-2.34183e-06,2.47253e-08,0.433058,0.00126308,-2.26766e-06,2.85278e-10,0.434319,0.00125855,-2.2668e-06,3.93614e-09,0.435575,0.00125403,-2.25499e-06,1.37722e-08,0.436827,0.00124956,-2.21368e-06,5.79803e-10,0.438074,0.00124513,-2.21194e-06,1.37112e-08,0.439317,0.00124075,-2.1708e-06,4.17973e-09,0.440556,0.00123642,-2.15826e-06,-6.27703e-10,0.44179,0.0012321,-2.16015e-06,2.81332e-08,0.44302,0.00122787,-2.07575e-06,-2.24985e-08,0.444246,0.00122365,-2.14324e-06,3.20586e-08,0.445467,0.00121946,-2.04707e-06,-1.6329e-08,0.446685,0.00121532,-2.09605e-06,3.32573e-08,0.447898,0.00121122,-1.99628e-06,-2.72927e-08,0.449107,0.00120715,-2.07816e-06,4.6111e-08,0.450312,0.00120313,-1.93983e-06,-3.79416e-08,0.451514,0.00119914,-2.05365e-06,4.60507e-08,0.452711,0.00119517,-1.9155e-06,-2.7052e-08,0.453904,0.00119126,-1.99666e-06,3.23551e-08,0.455093,0.00118736,-1.89959e-06,-1.29613e-08,0.456279,0.00118352,-1.93848e-06,1.94905e-08,0.45746,0.0011797,-1.88e-06,-5.39588e-09,0.458638,0.00117593,-1.89619e-06,2.09282e-09,0.459812,0.00117214,-1.88991e-06,2.68267e-08,0.460982,0.00116844,-1.80943e-06,-1.99925e-08,0.462149,0.00116476,-1.86941e-06,2.3341e-08,0.463312,0.00116109,-1.79939e-06,-1.37674e-08,0.464471,0.00115745,-1.84069e-06,3.17287e-08,0.465627,0.00115387,-1.7455e-06,-2.37407e-08,0.466779,0.00115031,-1.81673e-06,3.34315e-08,0.467927,0.00114677,-1.71643e-06,-2.05786e-08,0.469073,0.00114328,-1.77817e-06,1.90802e-08,0.470214,0.00113978,-1.72093e-06,3.86247e-09,0.471352,0.00113635,-1.70934e-06,-4.72759e-09,0.472487,0.00113292,-1.72352e-06,1.50478e-08,0.473618,0.00112951,-1.67838e-06,4.14108e-09,0.474746,0.00112617,-1.66595e-06,-1.80986e-09,0.47587,0.00112283,-1.67138e-06,3.09816e-09,0.476991,0.0011195,-1.66209e-06,1.92198e-08,0.478109,0.00111623,-1.60443e-06,-2.03726e-08,0.479224,0.00111296,-1.66555e-06,3.2468e-08,0.480335,0.00110973,-1.56814e-06,-2.00922e-08,0.481443,0.00110653,-1.62842e-06,1.80983e-08,0.482548,0.00110333,-1.57413e-06,7.30362e-09,0.48365,0.0011002,-1.55221e-06,-1.75107e-08,0.484749,0.00109705,-1.60475e-06,3.29373e-08,0.485844,0.00109393,-1.50594e-06,-2.48315e-08,0.486937,0.00109085,-1.58043e-06,3.65865e-08,0.488026,0.0010878,-1.47067e-06,-3.21078e-08,0.489112,0.00108476,-1.56699e-06,3.22397e-08,0.490195,0.00108172,-1.47027e-06,-7.44391e-09,0.491276,0.00107876,-1.49261e-06,-2.46428e-09,0.492353,0.00107577,-1.5e-06,1.73011e-08,0.493427,0.00107282,-1.4481e-06,-7.13552e-09,0.494499,0.0010699,-1.4695e-06,1.1241e-08,0.495567,0.001067,-1.43578e-06,-8.02637e-09,0.496633,0.0010641,-1.45986e-06,2.08645e-08,0.497695,0.00106124,-1.39726e-06,-1.58271e-08,0.498755,0.0010584,-1.44475e-06,1.26415e-08,0.499812,0.00105555,-1.40682e-06,2.48655e-08,0.500866,0.00105281,-1.33222e-06,-5.24988e-08,0.501918,0.00104999,-1.48972e-06,6.59206e-08,0.502966,0.00104721,-1.29196e-06,-3.237e-08,0.504012,0.00104453,-1.38907e-06,3.95479e-09,0.505055,0.00104176,-1.3772e-06,1.65509e-08,0.506096,0.00103905,-1.32755e-06,-1.05539e-08,0.507133,0.00103637,-1.35921e-06,2.56648e-08,0.508168,0.00103373,-1.28222e-06,-3.25007e-08,0.509201,0.00103106,-1.37972e-06,4.47336e-08,0.51023,0.00102844,-1.24552e-06,-2.72245e-08,0.511258,0.00102587,-1.32719e-06,4.55952e-09,0.512282,0.00102323,-1.31352e-06,8.98645e-09,0.513304,0.00102063,-1.28656e-06,1.90992e-08,0.514323,0.00101811,-1.22926e-06,-2.57786e-08,0.51534,0.00101557,-1.30659e-06,2.44104e-08,0.516355,0.00101303,-1.23336e-06,-1.22581e-08,0.517366,0.00101053,-1.27014e-06,2.4622e-08,0.518376,0.00100806,-1.19627e-06,-2.66253e-08,0.519383,0.00100559,-1.27615e-06,2.22744e-08,0.520387,0.00100311,-1.20932e-06,-2.8679e-09,0.521389,0.00100068,-1.21793e-06,-1.08029e-08,0.522388,0.000998211,-1.25034e-06,4.60795e-08,0.523385,0.000995849,-1.1121e-06,-5.4306e-08,0.52438,0.000993462,-1.27502e-06,5.19354e-08,0.525372,0.000991067,-1.11921e-06,-3.42262e-08,0.526362,0.000988726,-1.22189e-06,2.53646e-08,0.52735,0.000986359,-1.14579e-06,-7.62782e-09,0.528335,0.000984044,-1.16868e-06,5.14668e-09,0.529318,0.000981722,-1.15324e-06,-1.29589e-08,0.530298,0.000979377,-1.19211e-06,4.66888e-08,0.531276,0.000977133,-1.05205e-06,-5.45868e-08,0.532252,0.000974865,-1.21581e-06,5.24495e-08,0.533226,0.000972591,-1.05846e-06,-3.60019e-08,0.534198,0.000970366,-1.16647e-06,3.19537e-08,0.535167,0.000968129,-1.07061e-06,-3.2208e-08,0.536134,0.000965891,-1.16723e-06,3.72738e-08,0.537099,0.000963668,-1.05541e-06,2.32205e-09,0.538061,0.000961564,-1.04844e-06,-4.65618e-08,0.539022,0.000959328,-1.18813e-06,6.47159e-08,0.53998,0.000957146,-9.93979e-07,-3.3488e-08,0.540936,0.000955057,-1.09444e-06,9.63166e-09,0.54189,0.000952897,-1.06555e-06,-5.03871e-09,0.542842,0.000950751,-1.08066e-06,1.05232e-08,0.543792,0.000948621,-1.04909e-06,2.25503e-08,0.544739,0.000946591,-9.81444e-07,-4.11195e-08,0.545685,0.000944504,-1.1048e-06,2.27182e-08,0.546628,0.000942363,-1.03665e-06,9.85146e-09,0.54757,0.000940319,-1.00709e-06,-2.51938e-09,0.548509,0.000938297,-1.01465e-06,2.25858e-10,0.549446,0.000936269,-1.01397e-06,1.61598e-09,0.550381,0.000934246,-1.00913e-06,-6.68983e-09,0.551315,0.000932207,-1.0292e-06,2.51434e-08,0.552246,0.000930224,-9.53765e-07,-3.42793e-08,0.553175,0.000928214,-1.0566e-06,5.23688e-08,0.554102,0.000926258,-8.99497e-07,-5.59865e-08,0.555028,0.000924291,-1.06746e-06,5.23679e-08,0.555951,0.000922313,-9.10352e-07,-3.42763e-08,0.556872,0.00092039,-1.01318e-06,2.51326e-08,0.557792,0.000918439,-9.37783e-07,-6.64954e-09,0.558709,0.000916543,-9.57732e-07,1.46554e-09,0.559625,0.000914632,-9.53335e-07,7.87281e-10,0.560538,0.000912728,-9.50973e-07,-4.61466e-09,0.56145,0.000910812,-9.64817e-07,1.76713e-08,0.56236,0.000908935,-9.11804e-07,-6.46564e-09,0.563268,0.000907092,-9.312e-07,8.19121e-09,0.564174,0.000905255,-9.06627e-07,-2.62992e-08,0.565078,0.000903362,-9.85524e-07,3.74007e-08,0.565981,0.000901504,-8.73322e-07,-4.0942e-09,0.566882,0.000899745,-8.85605e-07,-2.1024e-08,0.56778,0.00089791,-9.48677e-07,2.85854e-08,0.568677,0.000896099,-8.62921e-07,-3.3713e-08,0.569573,0.000894272,-9.64059e-07,4.6662e-08,0.570466,0.000892484,-8.24073e-07,-3.37258e-08,0.571358,0.000890734,-9.25251e-07,2.86365e-08,0.572247,0.00088897,-8.39341e-07,-2.12155e-08,0.573135,0.000887227,-9.02988e-07,-3.37913e-09,0.574022,0.000885411,-9.13125e-07,3.47319e-08,0.574906,0.000883689,-8.08929e-07,-1.63394e-08,0.575789,0.000882022,-8.57947e-07,-2.8979e-08,0.57667,0.00088022,-9.44885e-07,7.26509e-08,0.57755,0.000878548,-7.26932e-07,-8.28106e-08,0.578427,0.000876845,-9.75364e-07,7.97774e-08,0.579303,0.000875134,-7.36032e-07,-5.74849e-08,0.580178,0.00087349,-9.08486e-07,3.09529e-08,0.58105,0.000871765,-8.15628e-07,-6.72206e-09,0.581921,0.000870114,-8.35794e-07,-4.06451e-09,0.582791,0.00086843,-8.47987e-07,2.29799e-08,0.583658,0.000866803,-7.79048e-07,-2.82503e-08,0.584524,0.00086516,-8.63799e-07,3.04167e-08,0.585388,0.000863524,-7.72548e-07,-3.38119e-08,0.586251,0.000861877,-8.73984e-07,4.52264e-08,0.587112,0.000860265,-7.38305e-07,-2.78842e-08,0.587972,0.000858705,-8.21958e-07,6.70567e-09,0.58883,0.000857081,-8.01841e-07,1.06161e-09,0.589686,0.000855481,-7.98656e-07,-1.09521e-08,0.590541,0.00085385,-8.31512e-07,4.27468e-08,0.591394,0.000852316,-7.03272e-07,-4.08257e-08,0.592245,0.000850787,-8.25749e-07,1.34677e-09,0.593095,0.000849139,-8.21709e-07,3.54387e-08,0.593944,0.000847602,-7.15393e-07,-2.38924e-08,0.59479,0.0008461,-7.8707e-07,5.26143e-10,0.595636,0.000844527,-7.85491e-07,2.17879e-08,0.596479,0.000843021,-7.20127e-07,-2.80733e-08,0.597322,0.000841497,-8.04347e-07,3.09005e-08,0.598162,0.000839981,-7.11646e-07,-3.5924e-08,0.599002,0.00083845,-8.19418e-07,5.3191e-08,0.599839,0.000836971,-6.59845e-07,-5.76307e-08,0.600676,0.000835478,-8.32737e-07,5.81227e-08,0.60151,0.000833987,-6.58369e-07,-5.56507e-08,0.602344,0.000832503,-8.25321e-07,4.52706e-08,0.603175,0.000830988,-6.89509e-07,-6.22236e-09,0.604006,0.000829591,-7.08176e-07,-2.03811e-08,0.604834,0.000828113,-7.6932e-07,2.8142e-08,0.605662,0.000826659,-6.84894e-07,-3.25822e-08,0.606488,0.000825191,-7.8264e-07,4.25823e-08,0.607312,0.000823754,-6.54893e-07,-1.85376e-08,0.608135,0.000822389,-7.10506e-07,-2.80365e-08,0.608957,0.000820883,-7.94616e-07,7.1079e-08,0.609777,0.000819507,-5.81379e-07,-7.74655e-08,0.610596,0.000818112,-8.13775e-07,5.9969e-08,0.611413,0.000816665,-6.33868e-07,-4.32013e-08,0.612229,0.000815267,-7.63472e-07,5.32313e-08,0.613044,0.0008139,-6.03778e-07,-5.05148e-08,0.613857,0.000812541,-7.55323e-07,2.96187e-08,0.614669,0.000811119,-6.66466e-07,-8.35545e-09,0.615479,0.000809761,-6.91533e-07,3.80301e-09,0.616288,0.00080839,-6.80124e-07,-6.85666e-09,0.617096,0.000807009,-7.00694e-07,2.36237e-08,0.617903,0.000805678,-6.29822e-07,-2.80336e-08,0.618708,0.000804334,-7.13923e-07,2.8906e-08,0.619511,0.000802993,-6.27205e-07,-2.79859e-08,0.620314,0.000801655,-7.11163e-07,2.34329e-08,0.621114,0.000800303,-6.40864e-07,-6.14108e-09,0.621914,0.000799003,-6.59287e-07,1.13151e-09,0.622712,0.000797688,-6.55893e-07,1.61507e-09,0.62351,0.000796381,-6.51048e-07,-7.59186e-09,0.624305,0.000795056,-6.73823e-07,2.87524e-08,0.6251,0.000793794,-5.87566e-07,-4.7813e-08,0.625893,0.000792476,-7.31005e-07,4.32901e-08,0.626685,0.000791144,-6.01135e-07,-6.13814e-09,0.627475,0.000789923,-6.19549e-07,-1.87376e-08,0.628264,0.000788628,-6.75762e-07,2.14837e-08,0.629052,0.000787341,-6.11311e-07,-7.59265e-09,0.629839,0.000786095,-6.34089e-07,8.88692e-09,0.630625,0.000784854,-6.07428e-07,-2.7955e-08,0.631409,0.000783555,-6.91293e-07,4.33285e-08,0.632192,0.000782302,-5.61307e-07,-2.61497e-08,0.632973,0.000781101,-6.39757e-07,1.6658e-09,0.633754,0.000779827,-6.34759e-07,1.94866e-08,0.634533,0.000778616,-5.76299e-07,-2.00076e-08,0.635311,0.000777403,-6.36322e-07,9.39091e-10,0.636088,0.000776133,-6.33505e-07,1.62512e-08,0.636863,0.000774915,-5.84751e-07,-6.33937e-09,0.637638,0.000773726,-6.03769e-07,9.10609e-09,0.638411,0.000772546,-5.76451e-07,-3.00849e-08,0.639183,0.000771303,-6.66706e-07,5.1629e-08,0.639953,0.000770125,-5.11819e-07,-5.7222e-08,0.640723,0.000768929,-6.83485e-07,5.80497e-08,0.641491,0.000767736,-5.09336e-07,-5.57674e-08,0.642259,0.000766551,-6.76638e-07,4.58105e-08,0.643024,0.000765335,-5.39206e-07,-8.26541e-09,0.643789,0.000764231,-5.64002e-07,-1.27488e-08,0.644553,0.000763065,-6.02249e-07,-3.44168e-10,0.645315,0.00076186,-6.03281e-07,1.41254e-08,0.646077,0.000760695,-5.60905e-07,3.44727e-09,0.646837,0.000759584,-5.50563e-07,-2.79144e-08,0.647596,0.000758399,-6.34307e-07,4.86057e-08,0.648354,0.000757276,-4.88489e-07,-4.72989e-08,0.64911,0.000756158,-6.30386e-07,2.13807e-08,0.649866,0.000754961,-5.66244e-07,2.13808e-08,0.65062,0.000753893,-5.02102e-07,-4.7299e-08,0.651374,0.000752746,-6.43999e-07,4.86059e-08,0.652126,0.000751604,-4.98181e-07,-2.79154e-08,0.652877,0.000750524,-5.81927e-07,3.45089e-09,0.653627,0.000749371,-5.71575e-07,1.41119e-08,0.654376,0.00074827,-5.29239e-07,-2.93748e-10,0.655123,0.00074721,-5.3012e-07,-1.29368e-08,0.65587,0.000746111,-5.68931e-07,-7.56355e-09,0.656616,0.000744951,-5.91621e-07,4.3191e-08,0.65736,0.000743897,-4.62048e-07,-4.59911e-08,0.658103,0.000742835,-6.00022e-07,2.15642e-08,0.658846,0.0007417,-5.35329e-07,1.93389e-08,0.659587,0.000740687,-4.77312e-07,-3.93152e-08,0.660327,0.000739615,-5.95258e-07,1.87126e-08,0.661066,0.00073848,-5.3912e-07,2.40695e-08,0.661804,0.000737474,-4.66912e-07,-5.53859e-08,0.662541,0.000736374,-6.33069e-07,7.82648e-08,0.663277,0.000735343,-3.98275e-07,-7.88593e-08,0.664012,0.00073431,-6.34853e-07,5.83585e-08,0.664745,0.000733215,-4.59777e-07,-3.53656e-08,0.665478,0.000732189,-5.65874e-07,2.34994e-08,0.66621,0.000731128,-4.95376e-07,9.72743e-10,0.66694,0.00073014,-4.92458e-07,-2.73903e-08,0.66767,0.000729073,-5.74629e-07,4.89839e-08,0.668398,0.000728071,-4.27677e-07,-4.93359e-08,0.669126,0.000727068,-5.75685e-07,2.91504e-08,0.669853,0.000726004,-4.88234e-07,-7.66109e-09,0.670578,0.000725004,-5.11217e-07,1.49392e-09,0.671303,0.000723986,-5.06735e-07,1.68533e-09,0.672026,0.000722978,-5.01679e-07,-8.23525e-09,0.672749,0.00072195,-5.26385e-07,3.12556e-08,0.67347,0.000720991,-4.32618e-07,-5.71825e-08,0.674191,0.000719954,-6.04166e-07,7.8265e-08,0.67491,0.00071898,-3.69371e-07,-7.70634e-08,0.675628,0.00071801,-6.00561e-07,5.11747e-08,0.676346,0.000716963,-4.47037e-07,-8.42615e-09,0.677062,0.000716044,-4.72315e-07,-1.747e-08,0.677778,0.000715046,-5.24725e-07,1.87015e-08,0.678493,0.000714053,-4.68621e-07,2.26856e-09,0.679206,0.000713123,-4.61815e-07,-2.77758e-08,0.679919,0.000712116,-5.45142e-07,4.92298e-08,0.68063,0.000711173,-3.97453e-07,-4.99339e-08,0.681341,0.000710228,-5.47255e-07,3.12967e-08,0.682051,0.000709228,-4.53365e-07,-1.56481e-08,0.68276,0.000708274,-5.00309e-07,3.12958e-08,0.683467,0.000707367,-4.06422e-07,-4.99303e-08,0.684174,0.000706405,-5.56213e-07,4.9216e-08,0.68488,0.00070544,-4.08565e-07,-2.77245e-08,0.685585,0.00070454,-4.91738e-07,2.07748e-09,0.686289,0.000703562,-4.85506e-07,1.94146e-08,0.686992,0.00070265,-4.27262e-07,-2.01314e-08,0.687695,0.000701735,-4.87656e-07,1.50616e-09,0.688396,0.000700764,-4.83137e-07,1.41067e-08,0.689096,0.00069984,-4.40817e-07,1.67168e-09,0.689795,0.000698963,-4.35802e-07,-2.07934e-08,0.690494,0.000698029,-4.98182e-07,2.18972e-08,0.691192,0.000697099,-4.32491e-07,-7.19092e-09,0.691888,0.000696212,-4.54064e-07,6.86642e-09,0.692584,0.000695325,-4.33464e-07,-2.02747e-08,0.693279,0.000694397,-4.94288e-07,1.46279e-08,0.693973,0.000693452,-4.50405e-07,2.13678e-08,0.694666,0.000692616,-3.86301e-07,-4.04945e-08,0.695358,0.000691721,-5.07785e-07,2.14009e-08,0.696049,0.00069077,-4.43582e-07,1.44955e-08,0.69674,0.000689926,-4.00096e-07,-1.97783e-08,0.697429,0.000689067,-4.5943e-07,5.01296e-09,0.698118,0.000688163,-4.44392e-07,-2.73521e-10,0.698805,0.000687273,-4.45212e-07,-3.91893e-09,0.699492,0.000686371,-4.56969e-07,1.59493e-08,0.700178,0.000685505,-4.09121e-07,-2.73351e-10,0.700863,0.000684686,-4.09941e-07,-1.4856e-08,0.701548,0.000683822,-4.54509e-07,9.25979e-11,0.702231,0.000682913,-4.54231e-07,1.44855e-08,0.702913,0.000682048,-4.10775e-07,1.56992e-09,0.703595,0.000681231,-4.06065e-07,-2.07652e-08,0.704276,0.000680357,-4.68361e-07,2.18864e-08,0.704956,0.000679486,-4.02701e-07,-7.17595e-09,0.705635,0.000678659,-4.24229e-07,6.81748e-09,0.706313,0.000677831,-4.03777e-07,-2.0094e-08,0.70699,0.000676963,-4.64059e-07,1.39538e-08,0.707667,0.000676077,-4.22197e-07,2.38835e-08,0.708343,0.000675304,-3.50547e-07,-4.98831e-08,0.709018,0.000674453,-5.00196e-07,5.64395e-08,0.709692,0.000673622,-3.30878e-07,-5.66657e-08,0.710365,0.00067279,-5.00875e-07,5.1014e-08,0.711037,0.000671942,-3.47833e-07,-2.81809e-08,0.711709,0.000671161,-4.32376e-07,2.10513e-09,0.712379,0.000670303,-4.2606e-07,1.97604e-08,0.713049,0.00066951,-3.66779e-07,-2.15422e-08,0.713718,0.000668712,-4.31406e-07,6.8038e-09,0.714387,0.000667869,-4.10994e-07,-5.67295e-09,0.715054,0.00066703,-4.28013e-07,1.5888e-08,0.715721,0.000666222,-3.80349e-07,1.72576e-09,0.716387,0.000665467,-3.75172e-07,-2.27911e-08,0.717052,0.000664648,-4.43545e-07,2.9834e-08,0.717716,0.00066385,-3.54043e-07,-3.69401e-08,0.718379,0.000663031,-4.64864e-07,5.83219e-08,0.719042,0.000662277,-2.89898e-07,-7.71382e-08,0.719704,0.000661465,-5.21313e-07,7.14171e-08,0.720365,0.000660637,-3.07061e-07,-2.97161e-08,0.721025,0.000659934,-3.96209e-07,-1.21575e-08,0.721685,0.000659105,-4.32682e-07,1.87412e-08,0.722343,0.000658296,-3.76458e-07,-3.2029e-09,0.723001,0.000657533,-3.86067e-07,-5.9296e-09,0.723659,0.000656743,-4.03856e-07,2.69213e-08,0.724315,0.000656016,-3.23092e-07,-4.21511e-08,0.724971,0.000655244,-4.49545e-07,2.24737e-08,0.725625,0.000654412,-3.82124e-07,1.18611e-08,0.726279,0.000653683,-3.46541e-07,-1.03132e-08,0.726933,0.000652959,-3.7748e-07,-3.02128e-08,0.727585,0.000652114,-4.68119e-07,7.15597e-08,0.728237,0.000651392,-2.5344e-07,-7.72119e-08,0.728888,0.000650654,-4.85075e-07,5.8474e-08,0.729538,0.000649859,-3.09654e-07,-3.74746e-08,0.730188,0.000649127,-4.22077e-07,3.18197e-08,0.730837,0.000648379,-3.26618e-07,-3.01997e-08,0.731485,0.000647635,-4.17217e-07,2.93747e-08,0.732132,0.000646888,-3.29093e-07,-2.76943e-08,0.732778,0.000646147,-4.12176e-07,2.17979e-08,0.733424,0.000645388,-3.46783e-07,1.07292e-10,0.734069,0.000644695,-3.46461e-07,-2.22271e-08,0.734713,0.000643935,-4.13142e-07,2.91963e-08,0.735357,0.000643197,-3.25553e-07,-3.49536e-08,0.736,0.000642441,-4.30414e-07,5.10133e-08,0.736642,0.000641733,-2.77374e-07,-4.98904e-08,0.737283,0.000641028,-4.27045e-07,2.93392e-08,0.737924,0.000640262,-3.39028e-07,-7.86156e-09,0.738564,0.000639561,-3.62612e-07,2.10703e-09,0.739203,0.000638842,-3.56291e-07,-5.6653e-10,0.739842,0.000638128,-3.57991e-07,1.59086e-10,0.740479,0.000637412,-3.57513e-07,-6.98321e-11,0.741116,0.000636697,-3.57723e-07,1.20214e-10,0.741753,0.000635982,-3.57362e-07,-4.10987e-10,0.742388,0.000635266,-3.58595e-07,1.5237e-09,0.743023,0.000634553,-3.54024e-07,-5.68376e-09,0.743657,0.000633828,-3.71075e-07,2.12113e-08,0.744291,0.00063315,-3.07441e-07,-1.95569e-08,0.744924,0.000632476,-3.66112e-07,-2.58816e-09,0.745556,0.000631736,-3.73877e-07,2.99096e-08,0.746187,0.000631078,-2.84148e-07,-5.74454e-08,0.746818,0.000630337,-4.56484e-07,8.06629e-08,0.747448,0.000629666,-2.14496e-07,-8.63922e-08,0.748077,0.000628978,-4.73672e-07,8.60918e-08,0.748706,0.000628289,-2.15397e-07,-7.91613e-08,0.749334,0.000627621,-4.5288e-07,5.17393e-08,0.749961,0.00062687,-2.97663e-07,-8.58662e-09,0.750588,0.000626249,-3.23422e-07,-1.73928e-08,0.751214,0.00062555,-3.75601e-07,1.85532e-08,0.751839,0.000624855,-3.19941e-07,2.78479e-09,0.752463,0.000624223,-3.11587e-07,-2.96923e-08,0.753087,0.000623511,-4.00664e-07,5.63799e-08,0.75371,0.000622879,-2.31524e-07,-7.66179e-08,0.754333,0.000622186,-4.61378e-07,7.12778e-08,0.754955,0.000621477,-2.47545e-07,-2.96794e-08,0.755576,0.000620893,-3.36583e-07,-1.21648e-08,0.756196,0.000620183,-3.73077e-07,1.87339e-08,0.756816,0.000619493,-3.16875e-07,-3.16622e-09,0.757435,0.00061885,-3.26374e-07,-6.0691e-09,0.758054,0.000618179,-3.44581e-07,2.74426e-08,0.758672,0.000617572,-2.62254e-07,-4.40968e-08,0.759289,0.000616915,-3.94544e-07,2.97352e-08,0.759906,0.000616215,-3.05338e-07,-1.52393e-08,0.760522,0.000615559,-3.51056e-07,3.12221e-08,0.761137,0.000614951,-2.5739e-07,-5.00443e-08,0.761751,0.000614286,-4.07523e-07,4.9746e-08,0.762365,0.00061362,-2.58285e-07,-2.97303e-08,0.762979,0.000613014,-3.47476e-07,9.57079e-09,0.763591,0.000612348,-3.18764e-07,-8.55287e-09,0.764203,0.000611685,-3.44422e-07,2.46407e-08,0.764815,0.00061107,-2.705e-07,-3.04053e-08,0.765426,0.000610437,-3.61716e-07,3.73759e-08,0.766036,0.000609826,-2.49589e-07,-5.94935e-08,0.766645,0.000609149,-4.28069e-07,8.13889e-08,0.767254,0.000608537,-1.83902e-07,-8.72483e-08,0.767862,0.000607907,-4.45647e-07,8.87901e-08,0.76847,0.000607282,-1.79277e-07,-8.90983e-08,0.769077,0.000606656,-4.46572e-07,8.87892e-08,0.769683,0.000606029,-1.80204e-07,-8.72446e-08,0.770289,0.000605407,-4.41938e-07,8.13752e-08,0.770894,0.000604768,-1.97812e-07,-5.94423e-08,0.771498,0.000604194,-3.76139e-07,3.71848e-08,0.772102,0.000603553,-2.64585e-07,-2.96922e-08,0.772705,0.000602935,-3.53661e-07,2.19793e-08,0.773308,0.000602293,-2.87723e-07,1.37955e-09,0.77391,0.000601722,-2.83585e-07,-2.74976e-08,0.774512,0.000601072,-3.66077e-07,4.9006e-08,0.775112,0.000600487,-2.19059e-07,-4.93171e-08,0.775712,0.000599901,-3.67011e-07,2.90531e-08,0.776312,0.000599254,-2.79851e-07,-7.29081e-09,0.776911,0.000598673,-3.01724e-07,1.10077e-10,0.777509,0.00059807,-3.01393e-07,6.85053e-09,0.778107,0.000597487,-2.80842e-07,-2.75123e-08,0.778704,0.000596843,-3.63379e-07,4.35939e-08,0.779301,0.000596247,-2.32597e-07,-2.7654e-08,0.779897,0.000595699,-3.15559e-07,7.41741e-09,0.780492,0.00059509,-2.93307e-07,-2.01562e-09,0.781087,0.000594497,-2.99354e-07,6.45059e-10,0.781681,0.000593901,-2.97418e-07,-5.64635e-10,0.782275,0.000593304,-2.99112e-07,1.61347e-09,0.782868,0.000592711,-2.94272e-07,-5.88926e-09,0.78346,0.000592105,-3.1194e-07,2.19436e-08,0.784052,0.000591546,-2.46109e-07,-2.22805e-08,0.784643,0.000590987,-3.1295e-07,7.57368e-09,0.785234,0.000590384,-2.90229e-07,-8.01428e-09,0.785824,0.00058978,-3.14272e-07,2.44834e-08,0.786414,0.000589225,-2.40822e-07,-3.03148e-08,0.787003,0.000588652,-3.31766e-07,3.7171e-08,0.787591,0.0005881,-2.20253e-07,-5.87646e-08,0.788179,0.000587483,-3.96547e-07,7.86782e-08,0.788766,0.000586926,-1.60512e-07,-7.71342e-08,0.789353,0.000586374,-3.91915e-07,5.10444e-08,0.789939,0.000585743,-2.38782e-07,-7.83422e-09,0.790524,0.000585242,-2.62284e-07,-1.97076e-08,0.791109,0.000584658,-3.21407e-07,2.70598e-08,0.791693,0.000584097,-2.40228e-07,-2.89269e-08,0.792277,0.000583529,-3.27008e-07,2.90431e-08,0.792861,0.000582963,-2.39879e-07,-2.76409e-08,0.793443,0.0005824,-3.22802e-07,2.1916e-08,0.794025,0.00058182,-2.57054e-07,-4.18368e-10,0.794607,0.000581305,-2.58309e-07,-2.02425e-08,0.795188,0.000580727,-3.19036e-07,2.17838e-08,0.795768,0.000580155,-2.53685e-07,-7.28814e-09,0.796348,0.000579625,-2.75549e-07,7.36871e-09,0.796928,0.000579096,-2.53443e-07,-2.21867e-08,0.797506,0.000578523,-3.20003e-07,2.17736e-08,0.798085,0.000577948,-2.54683e-07,-5.30296e-09,0.798662,0.000577423,-2.70592e-07,-5.61698e-10,0.799239,0.00057688,-2.72277e-07,7.54977e-09,0.799816,0.000576358,-2.49627e-07,-2.96374e-08,0.800392,0.00057577,-3.38539e-07,5.1395e-08,0.800968,0.000575247,-1.84354e-07,-5.67335e-08,0.801543,0.000574708,-3.54555e-07,5.63297e-08,0.802117,0.000574168,-1.85566e-07,-4.93759e-08,0.802691,0.000573649,-3.33693e-07,2.19646e-08,0.803264,0.000573047,-2.678e-07,2.1122e-08,0.803837,0.000572575,-2.04433e-07,-4.68482e-08,0.804409,0.000572026,-3.44978e-07,4.70613e-08,0.804981,0.000571477,-2.03794e-07,-2.21877e-08,0.805552,0.000571003,-2.70357e-07,-1.79153e-08,0.806123,0.000570408,-3.24103e-07,3.42443e-08,0.806693,0.000569863,-2.2137e-07,1.47556e-10,0.807263,0.000569421,-2.20928e-07,-3.48345e-08,0.807832,0.000568874,-3.25431e-07,1.99812e-08,0.808401,0.000568283,-2.65487e-07,1.45143e-08,0.808969,0.000567796,-2.21945e-07,-1.84338e-08,0.809536,0.000567297,-2.77246e-07,-3.83608e-10,0.810103,0.000566741,-2.78397e-07,1.99683e-08,0.81067,0.000566244,-2.18492e-07,-1.98848e-08,0.811236,0.000565747,-2.78146e-07,-3.38976e-11,0.811801,0.000565191,-2.78248e-07,2.00204e-08,0.812366,0.000564695,-2.18187e-07,-2.04429e-08,0.812931,0.000564197,-2.79516e-07,2.1467e-09,0.813495,0.000563644,-2.73076e-07,1.18561e-08,0.814058,0.000563134,-2.37507e-07,1.00334e-08,0.814621,0.000562689,-2.07407e-07,-5.19898e-08,0.815183,0.000562118,-3.63376e-07,7.87163e-08,0.815745,0.000561627,-1.27227e-07,-8.40616e-08,0.816306,0.000561121,-3.79412e-07,7.87163e-08,0.816867,0.000560598,-1.43263e-07,-5.19898e-08,0.817428,0.000560156,-2.99233e-07,1.00335e-08,0.817988,0.000559587,-2.69132e-07,1.18559e-08,0.818547,0.000559085,-2.33564e-07,2.14764e-09,0.819106,0.000558624,-2.27122e-07,-2.04464e-08,0.819664,0.000558108,-2.88461e-07,2.00334e-08,0.820222,0.000557591,-2.28361e-07,-8.24277e-11,0.820779,0.000557135,-2.28608e-07,-1.97037e-08,0.821336,0.000556618,-2.87719e-07,1.92925e-08,0.821893,0.000556101,-2.29841e-07,2.13831e-09,0.822448,0.000555647,-2.23427e-07,-2.78458e-08,0.823004,0.000555117,-3.06964e-07,4.96402e-08,0.823559,0.000554652,-1.58043e-07,-5.15058e-08,0.824113,0.000554181,-3.12561e-07,3.71737e-08,0.824667,0.000553668,-2.0104e-07,-3.75844e-08,0.82522,0.000553153,-3.13793e-07,5.35592e-08,0.825773,0.000552686,-1.53115e-07,-5.74431e-08,0.826326,0.000552207,-3.25444e-07,5.7004e-08,0.826878,0.000551728,-1.54433e-07,-5.13635e-08,0.827429,0.000551265,-3.08523e-07,2.92406e-08,0.82798,0.000550735,-2.20801e-07,-5.99424e-09,0.828531,0.000550276,-2.38784e-07,-5.26363e-09,0.829081,0.000549782,-2.54575e-07,2.70488e-08,0.82963,0.000549354,-1.73429e-07,-4.33268e-08,0.83018,0.000548878,-3.03409e-07,2.7049e-08,0.830728,0.000548352,-2.22262e-07,-5.26461e-09,0.831276,0.000547892,-2.38056e-07,-5.99057e-09,0.831824,0.000547397,-2.56027e-07,2.92269e-08,0.832371,0.000546973,-1.68347e-07,-5.13125e-08,0.832918,0.000546482,-3.22284e-07,5.68139e-08,0.833464,0.000546008,-1.51843e-07,-5.67336e-08,0.83401,0.000545534,-3.22043e-07,5.09113e-08,0.834555,0.000545043,-1.6931e-07,-2.77022e-08,0.8351,0.000544621,-2.52416e-07,2.92924e-10,0.835644,0.000544117,-2.51537e-07,2.65305e-08,0.836188,0.000543694,-1.71946e-07,-4.68105e-08,0.836732,0.00054321,-3.12377e-07,4.15021e-08,0.837275,0.000542709,-1.87871e-07,1.13355e-11,0.837817,0.000542334,-1.87837e-07,-4.15474e-08,0.838359,0.000541833,-3.12479e-07,4.69691e-08,0.838901,0.000541349,-1.71572e-07,-2.71196e-08,0.839442,0.000540925,-2.52931e-07,1.90462e-09,0.839983,0.000540425,-2.47217e-07,1.95011e-08,0.840523,0.000539989,-1.88713e-07,-2.03045e-08,0.841063,0.00053955,-2.49627e-07,2.11216e-09,0.841602,0.000539057,-2.4329e-07,1.18558e-08,0.842141,0.000538606,-2.07723e-07,1.00691e-08,0.842679,0.000538221,-1.77516e-07,-5.21324e-08,0.843217,0.00053771,-3.33913e-07,7.92513e-08,0.843755,0.00053728,-9.6159e-08,-8.60587e-08,0.844292,0.000536829,-3.54335e-07,8.61696e-08,0.844828,0.000536379,-9.58263e-08,-7.98057e-08,0.845364,0.000535948,-3.35243e-07,5.42394e-08,0.8459,0.00053544,-1.72525e-07,-1.79426e-08,0.846435,0.000535041,-2.26353e-07,1.75308e-08,0.84697,0.000534641,-1.73761e-07,-5.21806e-08,0.847505,0.000534137,-3.30302e-07,7.19824e-08,0.848038,0.000533692,-1.14355e-07,-5.69349e-08,0.848572,0.000533293,-2.8516e-07,3.65479e-08,0.849105,0.000532832,-1.75516e-07,-2.96519e-08,0.849638,0.000532392,-2.64472e-07,2.2455e-08,0.85017,0.000531931,-1.97107e-07,-5.63451e-10,0.850702,0.000531535,-1.98797e-07,-2.02011e-08,0.851233,0.000531077,-2.59401e-07,2.17634e-08,0.851764,0.000530623,-1.94111e-07,-7.24794e-09,0.852294,0.000530213,-2.15854e-07,7.22832e-09,0.852824,0.000529803,-1.94169e-07,-2.16653e-08,0.853354,0.00052935,-2.59165e-07,1.98283e-08,0.853883,0.000528891,-1.9968e-07,1.95678e-09,0.854412,0.000528497,-1.9381e-07,-2.76554e-08,0.85494,0.000528027,-2.76776e-07,4.90603e-08,0.855468,0.00052762,-1.29596e-07,-4.93764e-08,0.855995,0.000527213,-2.77725e-07,2.92361e-08,0.856522,0.000526745,-1.90016e-07,-7.96341e-09,0.857049,0.000526341,-2.13907e-07,2.61752e-09,0.857575,0.000525922,-2.06054e-07,-2.50665e-09,0.8581,0.000525502,-2.13574e-07,7.40906e-09,0.858626,0.000525097,-1.91347e-07,-2.71296e-08,0.859151,0.000524633,-2.72736e-07,4.15048e-08,0.859675,0.000524212,-1.48221e-07,-1.96802e-08,0.860199,0.000523856,-2.07262e-07,-2.23886e-08,0.860723,0.000523375,-2.74428e-07,4.96299e-08,0.861246,0.000522975,-1.25538e-07,-5.69216e-08,0.861769,0.000522553,-2.96303e-07,5.88473e-08,0.862291,0.000522137,-1.19761e-07,-5.92584e-08,0.862813,0.00052172,-2.97536e-07,5.8977e-08,0.863334,0.000521301,-1.20605e-07,-5.74403e-08,0.863855,0.000520888,-2.92926e-07,5.15751e-08,0.864376,0.000520457,-1.38201e-07,-2.96506e-08,0.864896,0.000520091,-2.27153e-07,7.42277e-09,0.865416,0.000519659,-2.04885e-07,-4.05057e-11,0.865936,0.00051925,-2.05006e-07,-7.26074e-09,0.866455,0.000518818,-2.26788e-07,2.90835e-08,0.866973,0.000518451,-1.39538e-07,-4.94686e-08,0.867492,0.000518024,-2.87944e-07,4.95814e-08,0.868009,0.000517597,-1.39199e-07,-2.96479e-08,0.868527,0.000517229,-2.28143e-07,9.40539e-09,0.869044,0.000516801,-1.99927e-07,-7.9737e-09,0.86956,0.000516378,-2.23848e-07,2.24894e-08,0.870077,0.000515997,-1.5638e-07,-2.23793e-08,0.870592,0.000515617,-2.23517e-07,7.42302e-09,0.871108,0.000515193,-2.01248e-07,-7.31283e-09,0.871623,0.000514768,-2.23187e-07,2.18283e-08,0.872137,0.000514387,-1.57702e-07,-2.03959e-08,0.872652,0.000514011,-2.1889e-07,1.50711e-10,0.873165,0.000513573,-2.18437e-07,1.97931e-08,0.873679,0.000513196,-1.59058e-07,-1.97183e-08,0.874192,0.000512819,-2.18213e-07,-5.24324e-10,0.874704,0.000512381,-2.19786e-07,2.18156e-08,0.875217,0.000512007,-1.54339e-07,-2.71336e-08,0.875728,0.000511616,-2.3574e-07,2.71141e-08,0.87624,0.000511226,-1.54398e-07,-2.17182e-08,0.876751,0.000510852,-2.19552e-07,1.54131e-10,0.877262,0.000510414,-2.1909e-07,2.11017e-08,0.877772,0.000510039,-1.55785e-07,-2.49562e-08,0.878282,0.000509652,-2.30654e-07,1.91183e-08,0.878791,0.000509248,-1.73299e-07,8.08751e-09,0.8793,0.000508926,-1.49036e-07,-5.14684e-08,0.879809,0.000508474,-3.03441e-07,7.85766e-08,0.880317,0.000508103,-6.77112e-08,-8.40242e-08,0.880825,0.000507715,-3.19784e-07,7.87063e-08,0.881333,0.000507312,-8.36649e-08,-5.19871e-08,0.88184,0.000506988,-2.39626e-07,1.00327e-08,0.882346,0.000506539,-2.09528e-07,1.18562e-08,0.882853,0.000506156,-1.73959e-07,2.14703e-09,0.883359,0.000505814,-1.67518e-07,-2.04444e-08,0.883864,0.000505418,-2.28851e-07,2.00258e-08,0.88437,0.00050502,-1.68774e-07,-5.42855e-11,0.884874,0.000504682,-1.68937e-07,-1.98087e-08,0.885379,0.000504285,-2.28363e-07,1.96842e-08,0.885883,0.000503887,-1.6931e-07,6.76342e-10,0.886387,0.000503551,-1.67281e-07,-2.23896e-08,0.88689,0.000503149,-2.3445e-07,2.92774e-08,0.887393,0.000502768,-1.46618e-07,-3.51152e-08,0.887896,0.00050237,-2.51963e-07,5.15787e-08,0.888398,0.00050202,-9.72271e-08,-5.19903e-08,0.8889,0.00050167,-2.53198e-07,3.71732e-08,0.889401,0.000501275,-1.41678e-07,-3.70978e-08,0.889902,0.00050088,-2.52972e-07,5.16132e-08,0.890403,0.000500529,-9.81321e-08,-5.01459e-08,0.890903,0.000500183,-2.4857e-07,2.9761e-08,0.891403,0.000499775,-1.59287e-07,-9.29351e-09,0.891903,0.000499428,-1.87167e-07,7.41301e-09,0.892402,0.000499076,-1.64928e-07,-2.03585e-08,0.892901,0.000498685,-2.26004e-07,1.44165e-08,0.893399,0.000498276,-1.82754e-07,2.22974e-08,0.893898,0.000497978,-1.15862e-07,-4.40013e-08,0.894395,0.000497614,-2.47866e-07,3.44985e-08,0.894893,0.000497222,-1.44371e-07,-3.43882e-08,0.89539,0.00049683,-2.47535e-07,4.34497e-08,0.895886,0.000496465,-1.17186e-07,-2.02012e-08,0.896383,0.00049617,-1.7779e-07,-2.22497e-08,0.896879,0.000495748,-2.44539e-07,4.95952e-08,0.897374,0.000495408,-9.57532e-08,-5.69217e-08,0.89787,0.000495045,-2.66518e-07,5.88823e-08,0.898364,0.000494689,-8.98713e-08,-5.93983e-08,0.898859,0.000494331,-2.68066e-07,5.95017e-08,0.899353,0.000493973,-8.95613e-08,-5.9399e-08,0.899847,0.000493616,-2.67758e-07,5.8885e-08,0.90034,0.000493257,-9.11033e-08,-5.69317e-08,0.900833,0.000492904,-2.61898e-07,4.96326e-08,0.901326,0.000492529,-1.13001e-07,-2.23893e-08,0.901819,0.000492236,-1.80169e-07,-1.968e-08,0.902311,0.000491817,-2.39209e-07,4.15047e-08,0.902802,0.000491463,-1.14694e-07,-2.71296e-08,0.903293,0.000491152,-1.96083e-07,7.409e-09,0.903784,0.000490782,-1.73856e-07,-2.50645e-09,0.904275,0.000490427,-1.81376e-07,2.61679e-09,0.904765,0.000490072,-1.73525e-07,-7.96072e-09,0.905255,0.000489701,-1.97407e-07,2.92261e-08,0.905745,0.000489394,-1.09729e-07,-4.93389e-08,0.906234,0.000489027,-2.57746e-07,4.89204e-08,0.906723,0.000488658,-1.10985e-07,-2.71333e-08,0.907211,0.000488354,-1.92385e-07,8.30861e-12,0.907699,0.00048797,-1.9236e-07,2.71001e-08,0.908187,0.000487666,-1.1106e-07,-4.88041e-08,0.908675,0.000487298,-2.57472e-07,4.89069e-08,0.909162,0.000486929,-1.10751e-07,-2.76143e-08,0.909649,0.000486625,-1.93594e-07,1.9457e-09,0.910135,0.000486244,-1.87757e-07,1.98315e-08,0.910621,0.000485928,-1.28262e-07,-2.16671e-08,0.911107,0.000485606,-1.93264e-07,7.23216e-09,0.911592,0.000485241,-1.71567e-07,-7.26152e-09,0.912077,0.000484877,-1.93352e-07,2.18139e-08,0.912562,0.000484555,-1.2791e-07,-2.03895e-08,0.913047,0.000484238,-1.89078e-07,1.39494e-10,0.913531,0.000483861,-1.8866e-07,1.98315e-08,0.914014,0.000483543,-1.29165e-07,-1.98609e-08,0.914498,0.000483225,-1.88748e-07,7.39912e-12,0.914981,0.000482847,-1.88726e-07,1.98313e-08,0.915463,0.000482529,-1.29232e-07,-1.9728e-08,0.915946,0.000482212,-1.88416e-07,-5.24035e-10,0.916428,0.000481833,-1.89988e-07,2.18241e-08,0.916909,0.000481519,-1.24516e-07,-2.71679e-08,0.917391,0.000481188,-2.06019e-07,2.72427e-08,0.917872,0.000480858,-1.24291e-07,-2.21985e-08,0.918353,0.000480543,-1.90886e-07,1.94644e-09,0.918833,0.000480167,-1.85047e-07,1.44127e-08,0.919313,0.00047984,-1.41809e-07,7.39438e-12,0.919793,0.000479556,-1.41787e-07,-1.44423e-08,0.920272,0.000479229,-1.85114e-07,-1.84291e-09,0.920751,0.000478854,-1.90642e-07,2.18139e-08,0.92123,0.000478538,-1.25201e-07,-2.58081e-08,0.921708,0.00047821,-2.02625e-07,2.18139e-08,0.922186,0.00047787,-1.37183e-07,-1.84291e-09,0.922664,0.00047759,-1.42712e-07,-1.44423e-08,0.923141,0.000477262,-1.86039e-07,7.34701e-12,0.923618,0.00047689,-1.86017e-07,1.44129e-08,0.924095,0.000476561,-1.42778e-07,1.94572e-09,0.924572,0.000476281,-1.36941e-07,-2.21958e-08,0.925048,0.000475941,-2.03528e-07,2.72327e-08,0.925523,0.000475615,-1.2183e-07,-2.71304e-08,0.925999,0.00047529,-2.03221e-07,2.16843e-08,0.926474,0.000474949,-1.38168e-07,-2.16005e-12,0.926949,0.000474672,-1.38175e-07,-2.16756e-08,0.927423,0.000474331,-2.03202e-07,2.71001e-08,0.927897,0.000474006,-1.21902e-07,-2.71201e-08,0.928371,0.000473681,-2.03262e-07,2.17757e-08,0.928845,0.00047334,-1.37935e-07,-3.78028e-10,0.929318,0.000473063,-1.39069e-07,-2.02636e-08,0.929791,0.000472724,-1.9986e-07,2.18276e-08,0.930263,0.000472389,-1.34377e-07,-7.44231e-09,0.930736,0.000472098,-1.56704e-07,7.94165e-09,0.931208,0.000471809,-1.32879e-07,-2.43243e-08,0.931679,0.00047147,-2.05851e-07,2.97508e-08,0.932151,0.000471148,-1.16599e-07,-3.50742e-08,0.932622,0.000470809,-2.21822e-07,5.09414e-08,0.933092,0.000470518,-6.89976e-08,-4.94821e-08,0.933563,0.000470232,-2.17444e-07,2.77775e-08,0.934033,0.00046988,-1.34111e-07,-2.02351e-09,0.934502,0.000469606,-1.40182e-07,-1.96835e-08,0.934972,0.000469267,-1.99232e-07,2.11529e-08,0.935441,0.000468932,-1.35774e-07,-5.32332e-09,0.93591,0.000468644,-1.51743e-07,1.40413e-10,0.936378,0.000468341,-1.51322e-07,4.76166e-09,0.936846,0.000468053,-1.37037e-07,-1.9187e-08,0.937314,0.000467721,-1.94598e-07,1.23819e-08,0.937782,0.000467369,-1.57453e-07,2.92642e-08,0.938249,0.000467142,-6.96601e-08,-6.98342e-08,0.938716,0.000466793,-2.79163e-07,7.12586e-08,0.939183,0.000466449,-6.53869e-08,-3.63863e-08,0.939649,0.000466209,-1.74546e-07,1.46818e-08,0.940115,0.000465904,-1.305e-07,-2.2341e-08,0.940581,0.000465576,-1.97523e-07,1.50774e-08,0.941046,0.000465226,-1.52291e-07,2.16359e-08,0.941511,0.000464986,-8.73832e-08,-4.20162e-08,0.941976,0.000464685,-2.13432e-07,2.72198e-08,0.942441,0.00046434,-1.31773e-07,-7.2581e-09,0.942905,0.000464055,-1.53547e-07,1.81263e-09,0.943369,0.000463753,-1.48109e-07,7.58386e-12,0.943832,0.000463457,-1.48086e-07,-1.84298e-09,0.944296,0.000463155,-1.53615e-07,7.36433e-09,0.944759,0.00046287,-1.31522e-07,-2.76143e-08,0.945221,0.000462524,-2.14365e-07,4.34883e-08,0.945684,0.000462226,-8.39003e-08,-2.71297e-08,0.946146,0.000461977,-1.65289e-07,5.42595e-09,0.946608,0.000461662,-1.49012e-07,5.42593e-09,0.947069,0.000461381,-1.32734e-07,-2.71297e-08,0.94753,0.000461034,-2.14123e-07,4.34881e-08,0.947991,0.000460736,-8.36585e-08,-2.76134e-08,0.948452,0.000460486,-1.66499e-07,7.36083e-09,0.948912,0.000460175,-1.44416e-07,-1.82993e-09,0.949372,0.000459881,-1.49906e-07,-4.11073e-11,0.949832,0.000459581,-1.50029e-07,1.99434e-09,0.950291,0.000459287,-1.44046e-07,-7.93627e-09,0.950751,0.000458975,-1.67855e-07,2.97507e-08,0.951209,0.000458728,-7.86029e-08,-5.1462e-08,0.951668,0.000458417,-2.32989e-07,5.6888e-08,0.952126,0.000458121,-6.2325e-08,-5.68806e-08,0.952584,0.000457826,-2.32967e-07,5.14251e-08,0.953042,0.000457514,-7.86914e-08,-2.96107e-08,0.953499,0.000457268,-1.67523e-07,7.41296e-09,0.953956,0.000456955,-1.45285e-07,-4.11262e-11,0.954413,0.000456665,-1.45408e-07,-7.24847e-09,0.95487,0.000456352,-1.67153e-07,2.9035e-08,0.955326,0.000456105,-8.00484e-08,-4.92869e-08,0.955782,0.000455797,-2.27909e-07,4.89032e-08,0.956238,0.000455488,-8.11994e-08,-2.71166e-08,0.956693,0.000455244,-1.62549e-07,-4.13678e-11,0.957148,0.000454919,-1.62673e-07,2.72821e-08,0.957603,0.000454675,-8.0827e-08,-4.94824e-08,0.958057,0.000454365,-2.29274e-07,5.14382e-08,0.958512,0.000454061,-7.49597e-08,-3.7061e-08,0.958965,0.0004538,-1.86143e-07,3.72013e-08,0.959419,0.000453539,-7.45389e-08,-5.21396e-08,0.959873,0.000453234,-2.30958e-07,5.21476e-08,0.960326,0.000452928,-7.45146e-08,-3.72416e-08,0.960778,0.000452667,-1.8624e-07,3.72143e-08,0.961231,0.000452407,-7.45967e-08,-5.20109e-08,0.961683,0.000452101,-2.30629e-07,5.16199e-08,0.962135,0.000451795,-7.57696e-08,-3.52595e-08,0.962587,0.000451538,-1.81548e-07,2.98133e-08,0.963038,0.000451264,-9.2108e-08,-2.43892e-08,0.963489,0.000451007,-1.65276e-07,8.13892e-09,0.96394,0.000450701,-1.40859e-07,-8.16647e-09,0.964391,0.000450394,-1.65358e-07,2.45269e-08,0.964841,0.000450137,-9.17775e-08,-3.03367e-08,0.965291,0.000449863,-1.82787e-07,3.7215e-08,0.965741,0.000449609,-7.11424e-08,-5.89188e-08,0.96619,0.00044929,-2.47899e-07,7.92509e-08,0.966639,0.000449032,-1.01462e-08,-7.92707e-08,0.967088,0.000448773,-2.47958e-07,5.90181e-08,0.967537,0.000448455,-7.0904e-08,-3.75925e-08,0.967985,0.0004482,-1.83681e-07,3.17471e-08,0.968433,0.000447928,-8.84401e-08,-2.97913e-08,0.968881,0.000447662,-1.77814e-07,2.78133e-08,0.969329,0.000447389,-9.4374e-08,-2.18572e-08,0.969776,0.000447135,-1.59946e-07,1.10134e-11,0.970223,0.000446815,-1.59913e-07,2.18132e-08,0.97067,0.000446561,-9.44732e-08,-2.76591e-08,0.971116,0.000446289,-1.7745e-07,2.92185e-08,0.971562,0.000446022,-8.97948e-08,-2.96104e-08,0.972008,0.000445753,-1.78626e-07,2.96185e-08,0.972454,0.000445485,-8.97706e-08,-2.92588e-08,0.972899,0.000445218,-1.77547e-07,2.78123e-08,0.973344,0.000444946,-9.41103e-08,-2.23856e-08,0.973789,0.000444691,-1.61267e-07,2.12559e-09,0.974233,0.000444374,-1.5489e-07,1.38833e-08,0.974678,0.000444106,-1.13241e-07,1.94591e-09,0.975122,0.000443886,-1.07403e-07,-2.16669e-08,0.975565,0.000443606,-1.72404e-07,2.5117e-08,0.976009,0.000443336,-9.70526e-08,-1.91963e-08,0.976452,0.000443085,-1.54642e-07,-7.93627e-09,0.976895,0.000442752,-1.7845e-07,5.09414e-08,0.977338,0.000442548,-2.56262e-08,-7.66201e-08,0.97778,0.000442266,-2.55486e-07,7.67249e-08,0.978222,0.000441986,-2.53118e-08,-5.14655e-08,0.978664,0.000441781,-1.79708e-07,9.92773e-09,0.979106,0.000441451,-1.49925e-07,1.17546e-08,0.979547,0.000441186,-1.14661e-07,2.65868e-09,0.979988,0.000440965,-1.06685e-07,-2.23893e-08,0.980429,0.000440684,-1.73853e-07,2.72939e-08,0.980869,0.000440419,-9.19716e-08,-2.71816e-08,0.98131,0.000440153,-1.73516e-07,2.18278e-08,0.98175,0.000439872,-1.08033e-07,-5.24833e-10,0.982189,0.000439654,-1.09607e-07,-1.97284e-08,0.982629,0.000439376,-1.68793e-07,1.98339e-08,0.983068,0.000439097,-1.09291e-07,-2.62901e-12,0.983507,0.000438879,-1.09299e-07,-1.98234e-08,0.983946,0.000438601,-1.68769e-07,1.96916e-08,0.984384,0.000438322,-1.09694e-07,6.6157e-10,0.984823,0.000438105,-1.0771e-07,-2.23379e-08,0.985261,0.000437823,-1.74723e-07,2.90855e-08,0.985698,0.00043756,-8.74669e-08,-3.43992e-08,0.986136,0.000437282,-1.90665e-07,4.89068e-08,0.986573,0.000437048,-4.39442e-08,-4.20188e-08,0.98701,0.000436834,-1.7e-07,-4.11073e-11,0.987446,0.000436494,-1.70124e-07,4.21832e-08,0.987883,0.00043628,-4.35742e-08,-4.94824e-08,0.988319,0.000436044,-1.92021e-07,3.6537e-08,0.988755,0.00043577,-8.24102e-08,-3.70611e-08,0.989191,0.000435494,-1.93593e-07,5.21026e-08,0.989626,0.000435263,-3.72855e-08,-5.21402e-08,0.990061,0.000435032,-1.93706e-07,3.7249e-08,0.990496,0.000434756,-8.19592e-08,-3.72512e-08,0.990931,0.000434481,-1.93713e-07,5.21511e-08,0.991365,0.00043425,-3.72595e-08,-5.21439e-08,0.991799,0.000434019,-1.93691e-07,3.72152e-08,0.992233,0.000433743,-8.20456e-08,-3.71123e-08,0.992667,0.000433468,-1.93382e-07,5.16292e-08,0.9931,0.000433236,-3.84947e-08,-5.01953e-08,0.993533,0.000433008,-1.89081e-07,2.99427e-08,0.993966,0.00043272,-9.92525e-08,-9.9708e-09,0.994399,0.000432491,-1.29165e-07,9.94051e-09,0.994831,0.000432263,-9.93434e-08,-2.97912e-08,0.995263,0.000431975,-1.88717e-07,4.96198e-08,0.995695,0.000431746,-3.98578e-08,-4.94785e-08,0.996127,0.000431518,-1.88293e-07,2.9085e-08,0.996558,0.000431229,-1.01038e-07,-7.25675e-09,0.996989,0.000431005,-1.22809e-07,-5.79945e-11,0.99742,0.000430759,-1.22983e-07,7.48873e-09,0.997851,0.000430536,-1.00516e-07,-2.98969e-08,0.998281,0.000430245,-1.90207e-07,5.24942e-08,0.998711,0.000430022,-3.27246e-08,-6.08706e-08,0.999141,0.000429774,-2.15336e-07,7.17788e-08,0.999571,0.000429392,0.,0.}; - - template - __device__ __forceinline__ void Lab2RGBConvert_f(const T& src, D& dst) - { - const float lThresh = 0.008856f * 903.3f; - const float fThresh = 7.787f * 0.008856f + 16.0f / 116.0f; - - float Y, fy; - - if (src.x <= lThresh) - { - Y = src.x / 903.3f; - fy = 7.787f * Y + 16.0f / 116.0f; - } - else - { - fy = (src.x + 16.0f) / 116.0f; - Y = fy * fy * fy; - } - - float X = src.y / 500.0f + fy; - float Z = fy - src.z / 200.0f; - - if (X <= fThresh) - X = (X - 16.0f / 116.0f) / 7.787f; - else - X = X * X * X; - - if (Z <= fThresh) - Z = (Z - 16.0f / 116.0f) / 7.787f; - else - Z = Z * Z * Z; - - float B = 0.052891f * X - 0.204043f * Y + 1.151152f * Z; - float G = -0.921235f * X + 1.875991f * Y + 0.045244f * Z; - float R = 3.079933f * X - 1.537150f * Y - 0.542782f * Z; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - } - - dst.x = blueIdx == 0 ? B : R; - dst.y = G; - dst.z = blueIdx == 0 ? R : B; - setAlpha(dst, ColorChannel::max()); - } - - template - __device__ __forceinline__ void Lab2RGBConvert_b(const T& src, D& dst) - { - float3 srcf, dstf; - - srcf.x = src.x * (100.f / 255.f); - srcf.y = src.y - 128; - srcf.z = src.z - 128; - - Lab2RGBConvert_f(srcf, dstf); - - dst.x = saturate_cast(dstf.x * 255.f); - dst.y = saturate_cast(dstf.y * 255.f); - dst.z = saturate_cast(dstf.z * 255.f); - setAlpha(dst, ColorChannel::max()); - } - - template struct Lab2RGB; - template - struct Lab2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Lab2RGBConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Lab2RGB() {} - __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} - }; - template - struct Lab2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Lab2RGBConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Lab2RGB() {} - __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Lab2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - -///////////////////////////////////// RGB <-> Luv ///////////////////////////////////// - - namespace color_detail - { - __constant__ float c_LabCbrtTab[] = {0.137931,0.0114066,0.,1.18859e-07,0.149338,0.011407,3.56578e-07,-5.79396e-07,0.160745,0.0114059,-1.38161e-06,2.16892e-06,0.172151,0.0114097,5.12516e-06,-8.0814e-06,0.183558,0.0113957,-1.9119e-05,3.01567e-05,0.194965,0.0114479,7.13509e-05,-0.000112545,0.206371,0.011253,-0.000266285,-0.000106493,0.217252,0.0104009,-0.000585765,7.32149e-05,0.22714,0.00944906,-0.00036612,1.21917e-05,0.236235,0.0087534,-0.000329545,2.01753e-05,0.244679,0.00815483,-0.000269019,1.24435e-05,0.252577,0.00765412,-0.000231689,1.05618e-05,0.26001,0.00722243,-0.000200003,8.26662e-06,0.267041,0.00684723,-0.000175203,6.76746e-06,0.27372,0.00651712,-0.000154901,5.61192e-06,0.280088,0.00622416,-0.000138065,4.67009e-06,0.286179,0.00596204,-0.000124055,3.99012e-06,0.292021,0.0057259,-0.000112085,3.36032e-06,0.297638,0.00551181,-0.000102004,2.95338e-06,0.30305,0.00531666,-9.31435e-05,2.52875e-06,0.308277,0.00513796,-8.55572e-05,2.22022e-06,0.313331,0.00497351,-7.88966e-05,1.97163e-06,0.318228,0.00482163,-7.29817e-05,1.7248e-06,0.322978,0.00468084,-6.78073e-05,1.55998e-06,0.327593,0.0045499,-6.31274e-05,1.36343e-06,0.332081,0.00442774,-5.90371e-05,1.27136e-06,0.336451,0.00431348,-5.5223e-05,1.09111e-06,0.34071,0.00420631,-5.19496e-05,1.0399e-06,0.344866,0.00410553,-4.88299e-05,9.18347e-07,0.348923,0.00401062,-4.60749e-05,8.29942e-07,0.352889,0.00392096,-4.35851e-05,7.98478e-07,0.356767,0.00383619,-4.11896e-05,6.84917e-07,0.360562,0.00375586,-3.91349e-05,6.63976e-07,0.36428,0.00367959,-3.7143e-05,5.93086e-07,0.367923,0.00360708,-3.53637e-05,5.6976e-07,0.371495,0.00353806,-3.36544e-05,4.95533e-07,0.375,0.00347224,-3.21678e-05,4.87951e-07,0.378441,0.00340937,-3.0704e-05,4.4349e-07,0.38182,0.00334929,-2.93735e-05,4.20297e-07,0.38514,0.0032918,-2.81126e-05,3.7872e-07,0.388404,0.00323671,-2.69764e-05,3.596e-07,0.391614,0.00318384,-2.58976e-05,3.5845e-07,0.394772,0.00313312,-2.48223e-05,2.92765e-07,0.397881,0.00308435,-2.3944e-05,3.18232e-07,0.400942,0.00303742,-2.29893e-05,2.82046e-07,0.403957,0.00299229,-2.21432e-05,2.52315e-07,0.406927,0.00294876,-2.13862e-05,2.58416e-07,0.409855,0.00290676,-2.0611e-05,2.33939e-07,0.412741,0.00286624,-1.99092e-05,2.36342e-07,0.415587,0.00282713,-1.92001e-05,1.916e-07,0.418396,0.00278931,-1.86253e-05,2.1915e-07,0.421167,0.00275271,-1.79679e-05,1.83498e-07,0.423901,0.00271733,-1.74174e-05,1.79343e-07,0.426602,0.00268303,-1.68794e-05,1.72013e-07,0.429268,0.00264979,-1.63633e-05,1.75686e-07,0.431901,0.00261759,-1.58363e-05,1.3852e-07,0.434503,0.00258633,-1.54207e-05,1.64304e-07,0.437074,0.00255598,-1.49278e-05,1.28136e-07,0.439616,0.00252651,-1.45434e-05,1.57618e-07,0.442128,0.0024979,-1.40705e-05,1.0566e-07,0.444612,0.00247007,-1.37535e-05,1.34998e-07,0.447068,0.00244297,-1.33485e-05,1.29207e-07,0.449498,0.00241666,-1.29609e-05,9.32347e-08,0.451902,0.00239102,-1.26812e-05,1.23703e-07,0.45428,0.00236603,-1.23101e-05,9.74072e-08,0.456634,0.0023417,-1.20179e-05,1.12518e-07,0.458964,0.002318,-1.16803e-05,7.83681e-08,0.46127,0.00229488,-1.14452e-05,1.10452e-07,0.463554,0.00227232,-1.11139e-05,7.58719e-08,0.465815,0.00225032,-1.08863e-05,9.2699e-08,0.468055,0.00222882,-1.06082e-05,8.97738e-08,0.470273,0.00220788,-1.03388e-05,5.4845e-08,0.47247,0.00218736,-1.01743e-05,1.0808e-07,0.474648,0.00216734,-9.85007e-06,4.9277e-08,0.476805,0.00214779,-9.70224e-06,8.22408e-08,0.478943,0.00212863,-9.45551e-06,6.87942e-08,0.481063,0.00210993,-9.24913e-06,5.98144e-08,0.483163,0.00209161,-9.06969e-06,7.93789e-08,0.485246,0.00207371,-8.83155e-06,3.99032e-08,0.487311,0.00205616,-8.71184e-06,8.88325e-08,0.489358,0.002039,-8.44534e-06,2.20004e-08,0.491389,0.00202218,-8.37934e-06,9.13872e-08,0.493403,0.0020057,-8.10518e-06,2.96829e-08,0.495401,0.00198957,-8.01613e-06,5.81028e-08,0.497382,0.00197372,-7.84183e-06,6.5731e-08,0.499348,0.00195823,-7.64463e-06,3.66019e-08,0.501299,0.00194305,-7.53483e-06,2.62811e-08,0.503234,0.00192806,-7.45598e-06,9.66907e-08,0.505155,0.00191344,-7.16591e-06,4.18928e-09,0.507061,0.00189912,-7.15334e-06,6.53665e-08,0.508953,0.00188501,-6.95724e-06,3.23686e-08,0.510831,0.00187119,-6.86014e-06,4.35774e-08,0.512696,0.0018576,-6.72941e-06,3.17406e-08,0.514547,0.00184424,-6.63418e-06,6.78785e-08,0.516384,0.00183117,-6.43055e-06,-5.23126e-09,0.518209,0.0018183,-6.44624e-06,7.22562e-08,0.520021,0.00180562,-6.22947e-06,1.42292e-08,0.52182,0.0017932,-6.18679e-06,4.9641e-08,0.523607,0.00178098,-6.03786e-06,2.56259e-08,0.525382,0.00176898,-5.96099e-06,2.66696e-08,0.527145,0.00175714,-5.88098e-06,4.65094e-08,0.528897,0.00174552,-5.74145e-06,2.57114e-08,0.530637,0.00173411,-5.66431e-06,2.94588e-08,0.532365,0.00172287,-5.57594e-06,3.52667e-08,0.534082,0.00171182,-5.47014e-06,8.28868e-09,0.535789,0.00170091,-5.44527e-06,5.07871e-08,0.537484,0.00169017,-5.29291e-06,2.69817e-08,0.539169,0.00167967,-5.21197e-06,2.01009e-08,0.540844,0.0016693,-5.15166e-06,1.18237e-08,0.542508,0.00165903,-5.11619e-06,5.18135e-08,0.544162,0.00164896,-4.96075e-06,1.9341e-08,0.545806,0.00163909,-4.90273e-06,-9.96867e-09,0.54744,0.00162926,-4.93263e-06,8.01382e-08,0.549064,0.00161963,-4.69222e-06,-1.25601e-08,0.550679,0.00161021,-4.7299e-06,2.97067e-08,0.552285,0.00160084,-4.64078e-06,1.29426e-08,0.553881,0.0015916,-4.60195e-06,3.77327e-08,0.555468,0.00158251,-4.48875e-06,1.49412e-08,0.557046,0.00157357,-4.44393e-06,2.17118e-08,0.558615,0.00156475,-4.3788e-06,1.74206e-08,0.560176,0.00155605,-4.32653e-06,2.78152e-08,0.561727,0.00154748,-4.24309e-06,-9.47239e-09,0.563271,0.00153896,-4.27151e-06,6.9679e-08,0.564805,0.00153063,-4.06247e-06,-3.08246e-08,0.566332,0.00152241,-4.15494e-06,5.36188e-08,0.56785,0.00151426,-3.99409e-06,-4.83594e-09,0.56936,0.00150626,-4.00859e-06,2.53293e-08,0.570863,0.00149832,-3.93261e-06,2.27286e-08,0.572357,0.00149052,-3.86442e-06,2.96541e-09,0.573844,0.0014828,-3.85552e-06,2.50147e-08,0.575323,0.00147516,-3.78048e-06,1.61842e-08,0.576794,0.00146765,-3.73193e-06,2.94582e-08,0.578258,0.00146028,-3.64355e-06,-1.48076e-08,0.579715,0.00145295,-3.68798e-06,2.97724e-08,0.581164,0.00144566,-3.59866e-06,1.49272e-08,0.582606,0.00143851,-3.55388e-06,2.97285e-08,0.584041,0.00143149,-3.46469e-06,-1.46323e-08,0.585469,0.00142451,-3.50859e-06,2.88004e-08,0.58689,0.00141758,-3.42219e-06,1.864e-08,0.588304,0.00141079,-3.36627e-06,1.58482e-08,0.589712,0.00140411,-3.31872e-06,-2.24279e-08,0.591112,0.00139741,-3.38601e-06,7.38639e-08,0.592507,0.00139085,-3.16441e-06,-3.46088e-08,0.593894,0.00138442,-3.26824e-06,4.96675e-09,0.595275,0.0013779,-3.25334e-06,7.4346e-08,0.59665,0.00137162,-3.0303e-06,-6.39319e-08,0.598019,0.00136536,-3.2221e-06,6.21725e-08,0.599381,0.00135911,-3.03558e-06,-5.94423e-09,0.600737,0.00135302,-3.05341e-06,2.12091e-08,0.602087,0.00134697,-2.98979e-06,-1.92876e-08,0.603431,0.00134094,-3.04765e-06,5.5941e-08,0.604769,0.00133501,-2.87983e-06,-2.56622e-08,0.606101,0.00132917,-2.95681e-06,4.67078e-08,0.607427,0.0013234,-2.81669e-06,-4.19592e-08,0.608748,0.00131764,-2.94257e-06,6.15243e-08,0.610062,0.00131194,-2.75799e-06,-2.53244e-08,0.611372,0.00130635,-2.83397e-06,3.97739e-08,0.612675,0.0013008,-2.71465e-06,-1.45618e-08,0.613973,0.00129533,-2.75833e-06,1.84733e-08,0.615266,0.00128986,-2.70291e-06,2.73606e-10,0.616553,0.00128446,-2.70209e-06,4.00367e-08,0.617835,0.00127918,-2.58198e-06,-4.12113e-08,0.619111,0.00127389,-2.70561e-06,6.52039e-08,0.620383,0.00126867,-2.51e-06,-4.07901e-08,0.621649,0.00126353,-2.63237e-06,3.83516e-08,0.62291,0.00125838,-2.51732e-06,6.59315e-09,0.624166,0.00125337,-2.49754e-06,-5.11939e-09,0.625416,0.00124836,-2.5129e-06,1.38846e-08,0.626662,0.00124337,-2.47124e-06,9.18514e-09,0.627903,0.00123846,-2.44369e-06,8.97952e-09,0.629139,0.0012336,-2.41675e-06,1.45012e-08,0.63037,0.00122881,-2.37325e-06,-7.37949e-09,0.631597,0.00122404,-2.39538e-06,1.50169e-08,0.632818,0.00121929,-2.35033e-06,6.91648e-09,0.634035,0.00121461,-2.32958e-06,1.69219e-08,0.635248,0.00121,-2.27882e-06,-1.49997e-08,0.636455,0.0012054,-2.32382e-06,4.30769e-08,0.637659,0.00120088,-2.19459e-06,-3.80986e-08,0.638857,0.00119638,-2.30888e-06,4.97134e-08,0.640051,0.00119191,-2.15974e-06,-4.15463e-08,0.641241,0.00118747,-2.28438e-06,5.68667e-08,0.642426,0.00118307,-2.11378e-06,-7.10641e-09,0.643607,0.00117882,-2.1351e-06,-2.8441e-08,0.644784,0.00117446,-2.22042e-06,6.12658e-08,0.645956,0.00117021,-2.03663e-06,-3.78083e-08,0.647124,0.00116602,-2.15005e-06,3.03627e-08,0.648288,0.00116181,-2.05896e-06,-2.40379e-08,0.649448,0.00115762,-2.13108e-06,6.57887e-08,0.650603,0.00115356,-1.93371e-06,-6.03028e-08,0.651755,0.00114951,-2.11462e-06,5.62134e-08,0.652902,0.00114545,-1.94598e-06,-4.53417e-08,0.654046,0.00114142,-2.082e-06,6.55489e-08,0.655185,0.00113745,-1.88536e-06,-3.80396e-08,0.656321,0.00113357,-1.99948e-06,2.70049e-08,0.657452,0.00112965,-1.91846e-06,-1.03755e-08,0.65858,0.00112578,-1.94959e-06,1.44973e-08,0.659704,0.00112192,-1.9061e-06,1.1991e-08,0.660824,0.00111815,-1.87012e-06,-2.85634e-09,0.66194,0.0011144,-1.87869e-06,-5.65782e-10,0.663053,0.00111064,-1.88039e-06,5.11947e-09,0.664162,0.0011069,-1.86503e-06,3.96924e-08,0.665267,0.00110328,-1.74595e-06,-4.46795e-08,0.666368,0.00109966,-1.87999e-06,1.98161e-08,0.667466,0.00109596,-1.82054e-06,2.502e-08,0.66856,0.00109239,-1.74548e-06,-6.86593e-10,0.669651,0.0010889,-1.74754e-06,-2.22739e-08,0.670738,0.00108534,-1.81437e-06,3.01776e-08,0.671821,0.0010818,-1.72383e-06,2.07732e-08,0.672902,0.00107841,-1.66151e-06,-5.36658e-08,0.673978,0.00107493,-1.82251e-06,7.46802e-08,0.675051,0.00107151,-1.59847e-06,-6.62411e-08,0.676121,0.00106811,-1.79719e-06,7.10748e-08,0.677188,0.00106473,-1.58397e-06,-3.92441e-08,0.678251,0.00106145,-1.7017e-06,2.62973e-08,0.679311,0.00105812,-1.62281e-06,-6.34035e-09,0.680367,0.00105486,-1.64183e-06,-9.36249e-10,0.68142,0.00105157,-1.64464e-06,1.00854e-08,0.68247,0.00104831,-1.61438e-06,2.01995e-08,0.683517,0.00104514,-1.55378e-06,-3.1279e-08,0.68456,0.00104194,-1.64762e-06,4.53114e-08,0.685601,0.00103878,-1.51169e-06,-3.07573e-08,0.686638,0.00103567,-1.60396e-06,1.81133e-08,0.687672,0.00103251,-1.54962e-06,1.79085e-08,0.688703,0.00102947,-1.49589e-06,-3.01428e-08,0.689731,0.00102639,-1.58632e-06,4.30583e-08,0.690756,0.00102334,-1.45715e-06,-2.28814e-08,0.691778,0.00102036,-1.52579e-06,-1.11373e-08,0.692797,0.00101727,-1.5592e-06,6.74305e-08,0.693812,0.00101436,-1.35691e-06,-7.97709e-08,0.694825,0.0010114,-1.59622e-06,7.28391e-08,0.695835,0.00100843,-1.37771e-06,-3.27715e-08,0.696842,0.00100558,-1.47602e-06,-1.35807e-09,0.697846,0.00100262,-1.48009e-06,3.82037e-08,0.698847,0.000999775,-1.36548e-06,-3.22474e-08,0.699846,0.000996948,-1.46223e-06,3.11809e-08,0.700841,0.000994117,-1.36868e-06,-3.28714e-08,0.701834,0.000991281,-1.4673e-06,4.07001e-08,0.702824,0.000988468,-1.3452e-06,-1.07197e-08,0.703811,0.000985746,-1.37736e-06,2.17866e-09,0.704795,0.000982998,-1.37082e-06,2.00521e-09,0.705777,0.000980262,-1.3648e-06,-1.01996e-08,0.706756,0.000977502,-1.3954e-06,3.87931e-08,0.707732,0.000974827,-1.27902e-06,-2.57632e-08,0.708706,0.000972192,-1.35631e-06,4.65513e-09,0.709676,0.000969493,-1.34235e-06,7.14257e-09,0.710645,0.00096683,-1.32092e-06,2.63791e-08,0.71161,0.000964267,-1.24178e-06,-5.30543e-08,0.712573,0.000961625,-1.40095e-06,6.66289e-08,0.713533,0.000959023,-1.20106e-06,-3.46474e-08,0.714491,0.000956517,-1.305e-06,1.23559e-08,0.715446,0.000953944,-1.26793e-06,-1.47763e-08,0.716399,0.000951364,-1.31226e-06,4.67494e-08,0.717349,0.000948879,-1.17201e-06,-5.3012e-08,0.718297,0.000946376,-1.33105e-06,4.60894e-08,0.719242,0.000943852,-1.19278e-06,-1.21366e-08,0.720185,0.00094143,-1.22919e-06,2.45673e-09,0.721125,0.000938979,-1.22182e-06,2.30966e-09,0.722063,0.000936543,-1.21489e-06,-1.16954e-08,0.722998,0.000934078,-1.24998e-06,4.44718e-08,0.723931,0.000931711,-1.11656e-06,-4.69823e-08,0.724861,0.000929337,-1.25751e-06,2.4248e-08,0.725789,0.000926895,-1.18477e-06,9.5949e-09,0.726715,0.000924554,-1.15598e-06,-3.02286e-09,0.727638,0.000922233,-1.16505e-06,2.49649e-09,0.72856,0.00091991,-1.15756e-06,-6.96321e-09,0.729478,0.000917575,-1.17845e-06,2.53564e-08,0.730395,0.000915294,-1.10238e-06,-3.48578e-08,0.731309,0.000912984,-1.20695e-06,5.44704e-08,0.732221,0.000910734,-1.04354e-06,-6.38144e-08,0.73313,0.000908455,-1.23499e-06,8.15781e-08,0.734038,0.00090623,-9.90253e-07,-8.3684e-08,0.734943,0.000903999,-1.2413e-06,7.43441e-08,0.735846,0.000901739,-1.01827e-06,-3.48787e-08,0.736746,0.000899598,-1.12291e-06,5.56596e-09,0.737645,0.000897369,-1.10621e-06,1.26148e-08,0.738541,0.000895194,-1.06837e-06,3.57935e-09,0.739435,0.000893068,-1.05763e-06,-2.69322e-08,0.740327,0.000890872,-1.13842e-06,4.45448e-08,0.741217,0.000888729,-1.00479e-06,-3.20376e-08,0.742105,0.000886623,-1.1009e-06,2.40011e-08,0.74299,0.000884493,-1.0289e-06,-4.36209e-09,0.743874,0.000882422,-1.04199e-06,-6.55268e-09,0.744755,0.000880319,-1.06164e-06,3.05728e-08,0.745634,0.000878287,-9.69926e-07,-5.61338e-08,0.746512,0.000876179,-1.13833e-06,7.4753e-08,0.747387,0.000874127,-9.14068e-07,-6.40644e-08,0.74826,0.000872106,-1.10626e-06,6.22955e-08,0.749131,0.000870081,-9.19375e-07,-6.59083e-08,0.75,0.000868044,-1.1171e-06,8.21284e-08,0.750867,0.000866056,-8.70714e-07,-8.37915e-08,0.751732,0.000864064,-1.12209e-06,7.42237e-08,0.752595,0.000862042,-8.99418e-07,-3.42894e-08,0.753456,0.00086014,-1.00229e-06,3.32955e-09,0.754315,0.000858146,-9.92297e-07,2.09712e-08,0.755173,0.000856224,-9.29384e-07,-2.76096e-08,0.756028,0.000854282,-1.01221e-06,2.98627e-08,0.756881,0.000852348,-9.22625e-07,-3.22365e-08,0.757733,0.000850406,-1.01933e-06,3.94786e-08,0.758582,0.000848485,-9.00898e-07,-6.46833e-09,0.75943,0.000846664,-9.20303e-07,-1.36052e-08,0.760275,0.000844783,-9.61119e-07,1.28447e-09,0.761119,0.000842864,-9.57266e-07,8.4674e-09,0.761961,0.000840975,-9.31864e-07,2.44506e-08,0.762801,0.000839185,-8.58512e-07,-4.6665e-08,0.763639,0.000837328,-9.98507e-07,4.30001e-08,0.764476,0.00083546,-8.69507e-07,-6.12609e-09,0.76531,0.000833703,-8.87885e-07,-1.84959e-08,0.766143,0.000831871,-9.43372e-07,2.05052e-08,0.766974,0.000830046,-8.81857e-07,-3.92026e-09,0.767803,0.000828271,-8.93618e-07,-4.82426e-09,0.768631,0.000826469,-9.0809e-07,2.32172e-08,0.769456,0.000824722,-8.38439e-07,-2.84401e-08,0.77028,0.00082296,-9.23759e-07,3.09386e-08,0.771102,0.000821205,-8.30943e-07,-3.57099e-08,0.771922,0.000819436,-9.38073e-07,5.22963e-08,0.772741,0.000817717,-7.81184e-07,-5.42658e-08,0.773558,0.000815992,-9.43981e-07,4.55579e-08,0.774373,0.000814241,-8.07308e-07,-8.75656e-09,0.775186,0.0008126,-8.33578e-07,-1.05315e-08,0.775998,0.000810901,-8.65172e-07,-8.72188e-09,0.776808,0.000809145,-8.91338e-07,4.54191e-08,0.777616,0.000807498,-7.5508e-07,-5.37454e-08,0.778423,0.000805827,-9.16317e-07,5.03532e-08,0.779228,0.000804145,-7.65257e-07,-2.84584e-08,0.780031,0.000802529,-8.50632e-07,3.87579e-09,0.780833,0.00080084,-8.39005e-07,1.29552e-08,0.781633,0.0007992,-8.00139e-07,3.90804e-09,0.782432,0.000797612,-7.88415e-07,-2.85874e-08,0.783228,0.000795949,-8.74177e-07,5.0837e-08,0.784023,0.000794353,-7.21666e-07,-5.55513e-08,0.784817,0.000792743,-8.8832e-07,5.21587e-08,0.785609,0.000791123,-7.31844e-07,-3.38744e-08,0.786399,0.000789558,-8.33467e-07,2.37342e-08,0.787188,0.000787962,-7.62264e-07,-1.45775e-09,0.787975,0.000786433,-7.66638e-07,-1.79034e-08,0.788761,0.000784846,-8.20348e-07,1.34665e-08,0.789545,0.000783246,-7.79948e-07,2.3642e-08,0.790327,0.000781757,-7.09022e-07,-4.84297e-08,0.791108,0.000780194,-8.54311e-07,5.08674e-08,0.791888,0.000778638,-7.01709e-07,-3.58303e-08,0.792666,0.000777127,-8.092e-07,3.28493e-08,0.793442,0.000775607,-7.10652e-07,-3.59624e-08,0.794217,0.000774078,-8.1854e-07,5.13959e-08,0.79499,0.000772595,-6.64352e-07,-5.04121e-08,0.795762,0.000771115,-8.15588e-07,3.10431e-08,0.796532,0.000769577,-7.22459e-07,-1.41557e-08,0.797301,0.00076809,-7.64926e-07,2.55795e-08,0.798069,0.000766636,-6.88187e-07,-2.85578e-08,0.798835,0.000765174,-7.73861e-07,2.90472e-08,0.799599,0.000763714,-6.86719e-07,-2.80262e-08,0.800362,0.000762256,-7.70798e-07,2.34531e-08,0.801123,0.000760785,-7.00438e-07,-6.18144e-09,0.801884,0.000759366,-7.18983e-07,1.27263e-09,0.802642,0.000757931,-7.15165e-07,1.09101e-09,0.803399,0.000756504,-7.11892e-07,-5.63675e-09,0.804155,0.000755064,-7.28802e-07,2.14559e-08,0.80491,0.00075367,-6.64434e-07,-2.05821e-08,0.805663,0.00075228,-7.26181e-07,1.26812e-09,0.806414,0.000750831,-7.22377e-07,1.55097e-08,0.807164,0.000749433,-6.75848e-07,-3.70216e-09,0.807913,0.00074807,-6.86954e-07,-7.0105e-10,0.80866,0.000746694,-6.89057e-07,6.5063e-09,0.809406,0.000745336,-6.69538e-07,-2.53242e-08,0.810151,0.000743921,-7.45511e-07,3.51858e-08,0.810894,0.000742535,-6.39953e-07,3.79034e-09,0.811636,0.000741267,-6.28582e-07,-5.03471e-08,0.812377,0.000739858,-7.79624e-07,7.83886e-08,0.813116,0.000738534,-5.44458e-07,-8.43935e-08,0.813854,0.000737192,-7.97638e-07,8.03714e-08,0.81459,0.000735838,-5.56524e-07,-5.82784e-08,0.815325,0.00073455,-7.31359e-07,3.35329e-08,0.816059,0.000733188,-6.3076e-07,-1.62486e-08,0.816792,0.000731878,-6.79506e-07,3.14614e-08,0.817523,0.000730613,-5.85122e-07,-4.99925e-08,0.818253,0.000729293,-7.35099e-07,4.92994e-08,0.818982,0.000727971,-5.87201e-07,-2.79959e-08,0.819709,0.000726712,-6.71189e-07,3.07959e-09,0.820435,0.000725379,-6.6195e-07,1.56777e-08,0.82116,0.000724102,-6.14917e-07,-6.18564e-09,0.821883,0.000722854,-6.33474e-07,9.06488e-09,0.822606,0.000721614,-6.06279e-07,-3.00739e-08,0.823327,0.000720311,-6.96501e-07,5.16262e-08,0.824046,0.000719073,-5.41623e-07,-5.72214e-08,0.824765,0.000717818,-7.13287e-07,5.80503e-08,0.825482,0.000716566,-5.39136e-07,-5.57703e-08,0.826198,0.00071532,-7.06447e-07,4.58215e-08,0.826912,0.000714045,-5.68983e-07,-8.30636e-09,0.827626,0.000712882,-5.93902e-07,-1.25961e-08,0.828338,0.000711656,-6.3169e-07,-9.13985e-10,0.829049,0.00071039,-6.34432e-07,1.62519e-08,0.829759,0.00070917,-5.85676e-07,-4.48904e-09,0.830468,0.000707985,-5.99143e-07,1.70418e-09,0.831175,0.000706792,-5.9403e-07,-2.32768e-09,0.831881,0.000705597,-6.01014e-07,7.60648e-09,0.832586,0.000704418,-5.78194e-07,-2.80982e-08,0.83329,0.000703177,-6.62489e-07,4.51817e-08,0.833993,0.000701988,-5.26944e-07,-3.34192e-08,0.834694,0.000700834,-6.27201e-07,2.88904e-08,0.835394,0.000699666,-5.4053e-07,-2.25378e-08,0.836093,0.000698517,-6.08143e-07,1.65589e-09,0.836791,0.000697306,-6.03176e-07,1.59142e-08,0.837488,0.000696147,-5.55433e-07,-5.70801e-09,0.838184,0.000695019,-5.72557e-07,6.91792e-09,0.838878,0.000693895,-5.51803e-07,-2.19637e-08,0.839571,0.000692725,-6.17694e-07,2.13321e-08,0.840263,0.000691554,-5.53698e-07,-3.75996e-09,0.840954,0.000690435,-5.64978e-07,-6.29219e-09,0.841644,0.000689287,-5.83855e-07,2.89287e-08,0.842333,0.000688206,-4.97068e-07,-4.98181e-08,0.843021,0.000687062,-6.46523e-07,5.11344e-08,0.843707,0.000685922,-4.9312e-07,-3.55102e-08,0.844393,0.00068483,-5.9965e-07,3.13019e-08,0.845077,0.000683724,-5.05745e-07,-3.00925e-08,0.84576,0.000682622,-5.96022e-07,2.94636e-08,0.846442,0.000681519,-5.07631e-07,-2.81572e-08,0.847123,0.000680419,-5.92103e-07,2.35606e-08,0.847803,0.000679306,-5.21421e-07,-6.48045e-09,0.848482,0.000678243,-5.40863e-07,2.36124e-09,0.849159,0.000677169,-5.33779e-07,-2.96461e-09,0.849836,0.000676092,-5.42673e-07,9.49728e-09,0.850512,0.000675035,-5.14181e-07,-3.50245e-08,0.851186,0.000673902,-6.19254e-07,7.09959e-08,0.851859,0.000672876,-4.06267e-07,-7.01453e-08,0.852532,0.000671853,-6.16703e-07,3.07714e-08,0.853203,0.000670712,-5.24388e-07,6.66423e-09,0.853873,0.000669684,-5.04396e-07,2.17629e-09,0.854542,0.000668681,-4.97867e-07,-1.53693e-08,0.855211,0.000667639,-5.43975e-07,-3.03752e-10,0.855878,0.000666551,-5.44886e-07,1.65844e-08,0.856544,0.000665511,-4.95133e-07,-6.42907e-09,0.857209,0.000664501,-5.1442e-07,9.13195e-09,0.857873,0.0006635,-4.87024e-07,-3.00987e-08,0.858536,0.000662435,-5.7732e-07,5.16584e-08,0.859198,0.000661436,-4.22345e-07,-5.73255e-08,0.859859,0.000660419,-5.94322e-07,5.84343e-08,0.860518,0.000659406,-4.19019e-07,-5.72022e-08,0.861177,0.000658396,-5.90626e-07,5.11653e-08,0.861835,0.000657368,-4.3713e-07,-2.82495e-08,0.862492,0.000656409,-5.21878e-07,2.22788e-09,0.863148,0.000655372,-5.15195e-07,1.9338e-08,0.863803,0.0006544,-4.5718e-07,-1.99754e-08,0.864457,0.000653425,-5.17107e-07,9.59024e-10,0.86511,0.000652394,-5.1423e-07,1.61393e-08,0.865762,0.000651414,-4.65812e-07,-5.91149e-09,0.866413,0.000650465,-4.83546e-07,7.50665e-09,0.867063,0.00064952,-4.61026e-07,-2.4115e-08,0.867712,0.000648526,-5.33371e-07,2.93486e-08,0.86836,0.000647547,-4.45325e-07,-3.36748e-08,0.869007,0.000646555,-5.4635e-07,4.57461e-08,0.869653,0.0006456,-4.09112e-07,-3.01002e-08,0.870298,0.000644691,-4.99412e-07,1.50501e-08,0.870942,0.000643738,-4.54262e-07,-3.01002e-08,0.871585,0.000642739,-5.44563e-07,4.57461e-08,0.872228,0.000641787,-4.07324e-07,-3.36748e-08,0.872869,0.000640871,-5.08349e-07,2.93486e-08,0.873509,0.000639943,-4.20303e-07,-2.4115e-08,0.874149,0.00063903,-4.92648e-07,7.50655e-09,0.874787,0.000638067,-4.70128e-07,-5.91126e-09,0.875425,0.000637109,-4.87862e-07,1.61385e-08,0.876062,0.000636182,-4.39447e-07,9.61961e-10,0.876697,0.000635306,-4.36561e-07,-1.99863e-08,0.877332,0.000634373,-4.9652e-07,1.93785e-08,0.877966,0.000633438,-4.38384e-07,2.07697e-09,0.878599,0.000632567,-4.32153e-07,-2.76864e-08,0.879231,0.00063162,-5.15212e-07,4.90641e-08,0.879862,0.000630737,-3.6802e-07,-4.93606e-08,0.880493,0.000629852,-5.16102e-07,2.9169e-08,0.881122,0.000628908,-4.28595e-07,-7.71083e-09,0.881751,0.000628027,-4.51727e-07,1.6744e-09,0.882378,0.000627129,-4.46704e-07,1.01317e-09,0.883005,0.000626239,-4.43665e-07,-5.72703e-09,0.883631,0.000625334,-4.60846e-07,2.1895e-08,0.884255,0.000624478,-3.95161e-07,-2.22481e-08,0.88488,0.000623621,-4.61905e-07,7.4928e-09,0.885503,0.00062272,-4.39427e-07,-7.72306e-09,0.886125,0.000621818,-4.62596e-07,2.33995e-08,0.886746,0.000620963,-3.92398e-07,-2.62704e-08,0.887367,0.000620099,-4.71209e-07,2.20775e-08,0.887987,0.000619223,-4.04976e-07,-2.43496e-09,0.888605,0.000618406,-4.12281e-07,-1.23377e-08,0.889223,0.000617544,-4.49294e-07,-7.81876e-09,0.88984,0.000616622,-4.72751e-07,4.36128e-08,0.890457,0.000615807,-3.41912e-07,-4.7423e-08,0.891072,0.000614981,-4.84181e-07,2.68698e-08,0.891687,0.000614093,-4.03572e-07,-4.51384e-10,0.8923,0.000613285,-4.04926e-07,-2.50643e-08,0.892913,0.0006124,-4.80119e-07,4.11038e-08,0.893525,0.000611563,-3.56808e-07,-2.01414e-08,0.894136,0.000610789,-4.17232e-07,-2.01426e-08,0.894747,0.000609894,-4.7766e-07,4.11073e-08,0.895356,0.000609062,-3.54338e-07,-2.50773e-08,0.895965,0.000608278,-4.2957e-07,-4.02954e-10,0.896573,0.000607418,-4.30779e-07,2.66891e-08,0.89718,0.000606636,-3.50711e-07,-4.67489e-08,0.897786,0.000605795,-4.90958e-07,4.10972e-08,0.898391,0.000604936,-3.67666e-07,1.56948e-09,0.898996,0.000604205,-3.62958e-07,-4.73751e-08,0.8996,0.000603337,-5.05083e-07,6.87214e-08,0.900202,0.000602533,-2.98919e-07,-4.86966e-08,0.900805,0.000601789,-4.45009e-07,6.85589e-09,0.901406,0.00060092,-4.24441e-07,2.1273e-08,0.902007,0.000600135,-3.60622e-07,-3.23434e-08,0.902606,0.000599317,-4.57652e-07,4.84959e-08,0.903205,0.000598547,-3.12164e-07,-4.24309e-08,0.903803,0.000597795,-4.39457e-07,2.01844e-09,0.904401,0.000596922,-4.33402e-07,3.43571e-08,0.904997,0.000596159,-3.30331e-07,-2.02374e-08,0.905593,0.000595437,-3.91043e-07,-1.30123e-08,0.906188,0.000594616,-4.3008e-07,1.26819e-08,0.906782,0.000593794,-3.92034e-07,2.18894e-08,0.907376,0.000593076,-3.26366e-07,-4.06349e-08,0.907968,0.000592301,-4.4827e-07,2.1441e-08,0.90856,0.000591469,-3.83947e-07,1.44754e-08,0.909151,0.000590744,-3.40521e-07,-1.97379e-08,0.909742,0.000590004,-3.99735e-07,4.87161e-09,0.910331,0.000589219,-3.8512e-07,2.51532e-10,0.91092,0.00058845,-3.84366e-07,-5.87776e-09,0.911508,0.000587663,-4.01999e-07,2.32595e-08,0.912096,0.000586929,-3.3222e-07,-2.75554e-08,0.912682,0.000586182,-4.14887e-07,2.73573e-08,0.913268,0.000585434,-3.32815e-07,-2.22692e-08,0.913853,0.000584702,-3.99622e-07,2.11486e-09,0.914437,0.000583909,-3.93278e-07,1.38098e-08,0.915021,0.000583164,-3.51848e-07,2.25042e-09,0.915604,0.000582467,-3.45097e-07,-2.28115e-08,0.916186,0.000581708,-4.13531e-07,2.93911e-08,0.916767,0.000580969,-3.25358e-07,-3.51481e-08,0.917348,0.000580213,-4.30803e-07,5.15967e-08,0.917928,0.000579506,-2.76012e-07,-5.20296e-08,0.918507,0.000578798,-4.32101e-07,3.73124e-08,0.919085,0.000578046,-3.20164e-07,-3.76154e-08,0.919663,0.000577293,-4.3301e-07,5.35447e-08,0.92024,0.000576587,-2.72376e-07,-5.7354e-08,0.920816,0.000575871,-4.44438e-07,5.66621e-08,0.921391,0.000575152,-2.74452e-07,-5.00851e-08,0.921966,0.000574453,-4.24707e-07,2.4469e-08,0.92254,0.000573677,-3.513e-07,1.18138e-08,0.923114,0.000573009,-3.15859e-07,-1.21195e-08,0.923686,0.000572341,-3.52217e-07,-2.29403e-08,0.924258,0.000571568,-4.21038e-07,4.4276e-08,0.924829,0.000570859,-2.8821e-07,-3.49546e-08,0.9254,0.000570178,-3.93074e-07,3.59377e-08,0.92597,0.000569499,-2.85261e-07,-4.91915e-08,0.926539,0.000568781,-4.32835e-07,4.16189e-08,0.927107,0.00056804,-3.07979e-07,1.92523e-09,0.927675,0.00056743,-3.02203e-07,-4.93198e-08,0.928242,0.000566678,-4.50162e-07,7.61447e-08,0.928809,0.000566006,-2.21728e-07,-7.6445e-08,0.929374,0.000565333,-4.51063e-07,5.08216e-08,0.929939,0.000564583,-2.98599e-07,-7.63212e-09,0.930503,0.000563963,-3.21495e-07,-2.02931e-08,0.931067,0.000563259,-3.82374e-07,2.92001e-08,0.93163,0.000562582,-2.94774e-07,-3.69025e-08,0.932192,0.000561882,-4.05482e-07,5.88053e-08,0.932754,0.000561247,-2.29066e-07,-7.91094e-08,0.933315,0.000560552,-4.66394e-07,7.88184e-08,0.933875,0.000559856,-2.29939e-07,-5.73501e-08,0.934434,0.000559224,-4.01989e-07,3.13727e-08,0.934993,0.000558514,-3.07871e-07,-8.53611e-09,0.935551,0.000557873,-3.33479e-07,2.77175e-09,0.936109,0.000557214,-3.25164e-07,-2.55091e-09,0.936666,0.000556556,-3.32817e-07,7.43188e-09,0.937222,0.000555913,-3.10521e-07,-2.71766e-08,0.937778,0.00055521,-3.92051e-07,4.167e-08,0.938333,0.000554551,-2.67041e-07,-2.02941e-08,0.938887,0.000553956,-3.27923e-07,-2.00984e-08,0.93944,0.00055324,-3.88218e-07,4.10828e-08,0.939993,0.000552587,-2.6497e-07,-2.50237e-08,0.940546,0.000551982,-3.40041e-07,-5.92583e-10,0.941097,0.0005513,-3.41819e-07,2.7394e-08,0.941648,0.000550698,-2.59637e-07,-4.93788e-08,0.942199,0.000550031,-4.07773e-07,5.09119e-08,0.942748,0.000549368,-2.55038e-07,-3.50595e-08,0.943297,0.000548753,-3.60216e-07,2.97214e-08,0.943846,0.000548122,-2.71052e-07,-2.42215e-08,0.944394,0.000547507,-3.43716e-07,7.55985e-09,0.944941,0.000546842,-3.21037e-07,-6.01796e-09,0.945487,0.000546182,-3.3909e-07,1.65119e-08,0.946033,0.000545553,-2.89555e-07,-4.2498e-10,0.946578,0.000544973,-2.9083e-07,-1.4812e-08,0.947123,0.000544347,-3.35266e-07,6.83068e-11,0.947667,0.000543676,-3.35061e-07,1.45388e-08,0.94821,0.00054305,-2.91444e-07,1.38123e-09,0.948753,0.000542471,-2.87301e-07,-2.00637e-08,0.949295,0.000541836,-3.47492e-07,1.92688e-08,0.949837,0.000541199,-2.89685e-07,2.59298e-09,0.950378,0.000540628,-2.81906e-07,-2.96407e-08,0.950918,0.000539975,-3.70829e-07,5.63652e-08,0.951458,0.000539402,-2.01733e-07,-7.66107e-08,0.951997,0.000538769,-4.31565e-07,7.12638e-08,0.952535,0.00053812,-2.17774e-07,-2.96305e-08,0.953073,0.000537595,-3.06665e-07,-1.23464e-08,0.95361,0.000536945,-3.43704e-07,1.94114e-08,0.954147,0.000536316,-2.8547e-07,-5.69451e-09,0.954683,0.000535728,-3.02554e-07,3.36666e-09,0.955219,0.000535133,-2.92454e-07,-7.77208e-09,0.955753,0.000534525,-3.1577e-07,2.77216e-08,0.956288,0.000533976,-2.32605e-07,-4.35097e-08,0.956821,0.00053338,-3.63134e-07,2.7108e-08,0.957354,0.000532735,-2.8181e-07,-5.31772e-09,0.957887,0.000532156,-2.97764e-07,-5.83718e-09,0.958419,0.000531543,-3.15275e-07,2.86664e-08,0.95895,0.000530998,-2.29276e-07,-4.9224e-08,0.959481,0.000530392,-3.76948e-07,4.90201e-08,0.960011,0.000529785,-2.29887e-07,-2.76471e-08,0.96054,0.000529243,-3.12829e-07,1.96385e-09,0.961069,0.000528623,-3.06937e-07,1.97917e-08,0.961598,0.000528068,-2.47562e-07,-2.15261e-08,0.962125,0.000527508,-3.1214e-07,6.70795e-09,0.962653,0.000526904,-2.92016e-07,-5.30573e-09,0.963179,0.000526304,-3.07934e-07,1.4515e-08,0.963705,0.000525732,-2.64389e-07,6.85048e-09,0.964231,0.000525224,-2.43837e-07,-4.19169e-08,0.964756,0.00052461,-3.69588e-07,4.1608e-08,0.96528,0.000523996,-2.44764e-07,-5.30598e-09,0.965804,0.000523491,-2.60682e-07,-2.03841e-08,0.966327,0.000522908,-3.21834e-07,2.72378e-08,0.966849,0.000522346,-2.40121e-07,-2.89625e-08,0.967371,0.000521779,-3.27008e-07,2.90075e-08,0.967893,0.000521212,-2.39986e-07,-2.74629e-08,0.968414,0.00052065,-3.22374e-07,2.12396e-08,0.968934,0.000520069,-2.58656e-07,2.10922e-09,0.969454,0.000519558,-2.52328e-07,-2.96765e-08,0.969973,0.000518964,-3.41357e-07,5.6992e-08,0.970492,0.000518452,-1.70382e-07,-7.90821e-08,0.97101,0.000517874,-4.07628e-07,8.05224e-08,0.971528,0.000517301,-1.66061e-07,-6.41937e-08,0.972045,0.000516776,-3.58642e-07,5.70429e-08,0.972561,0.00051623,-1.87513e-07,-4.47686e-08,0.973077,0.00051572,-3.21819e-07,2.82237e-09,0.973593,0.000515085,-3.13352e-07,3.34792e-08,0.974108,0.000514559,-2.12914e-07,-1.75298e-08,0.974622,0.000514081,-2.65503e-07,-2.29648e-08,0.975136,0.000513481,-3.34398e-07,4.97843e-08,0.975649,0.000512961,-1.85045e-07,-5.6963e-08,0.976162,0.00051242,-3.55934e-07,5.88585e-08,0.976674,0.000511885,-1.79359e-07,-5.92616e-08,0.977185,0.000511348,-3.57143e-07,5.89785e-08,0.977696,0.000510811,-1.80208e-07,-5.74433e-08,0.978207,0.000510278,-3.52538e-07,5.15854e-08,0.978717,0.000509728,-1.97781e-07,-2.9689e-08,0.979226,0.000509243,-2.86848e-07,7.56591e-09,0.979735,0.000508692,-2.64151e-07,-5.74649e-10,0.980244,0.000508162,-2.65875e-07,-5.26732e-09,0.980752,0.000507615,-2.81677e-07,2.16439e-08,0.981259,0.000507116,-2.16745e-07,-2.17037e-08,0.981766,0.000506618,-2.81856e-07,5.56636e-09,0.982272,0.000506071,-2.65157e-07,-5.61689e-10,0.982778,0.000505539,-2.66842e-07,-3.31963e-09,0.983283,0.000504995,-2.76801e-07,1.38402e-08,0.983788,0.000504483,-2.3528e-07,7.56339e-09,0.984292,0.000504035,-2.1259e-07,-4.40938e-08,0.984796,0.000503478,-3.44871e-07,4.96026e-08,0.985299,0.000502937,-1.96064e-07,-3.51071e-08,0.985802,0.000502439,-3.01385e-07,3.12212e-08,0.986304,0.00050193,-2.07721e-07,-3.0173e-08,0.986806,0.000501424,-2.9824e-07,2.9866e-08,0.987307,0.000500917,-2.08642e-07,-2.96865e-08,0.987808,0.000500411,-2.97702e-07,2.92753e-08,0.988308,0.000499903,-2.09876e-07,-2.78101e-08,0.988807,0.0004994,-2.93306e-07,2.23604e-08,0.989307,0.000498881,-2.26225e-07,-2.02681e-09,0.989805,0.000498422,-2.32305e-07,-1.42531e-08,0.990303,0.000497915,-2.75065e-07,-5.65232e-10,0.990801,0.000497363,-2.76761e-07,1.65141e-08,0.991298,0.000496859,-2.27218e-07,-5.88639e-09,0.991795,0.000496387,-2.44878e-07,7.0315e-09,0.992291,0.000495918,-2.23783e-07,-2.22396e-08,0.992787,0.000495404,-2.90502e-07,2.23224e-08,0.993282,0.00049489,-2.23535e-07,-7.44543e-09,0.993776,0.000494421,-2.45871e-07,7.45924e-09,0.994271,0.000493951,-2.23493e-07,-2.23915e-08,0.994764,0.000493437,-2.90668e-07,2.25021e-08,0.995257,0.000492923,-2.23161e-07,-8.01218e-09,0.99575,0.000492453,-2.47198e-07,9.54669e-09,0.996242,0.000491987,-2.18558e-07,-3.01746e-08,0.996734,0.000491459,-3.09082e-07,5.1547e-08,0.997225,0.000490996,-1.54441e-07,-5.68039e-08,0.997716,0.000490517,-3.24853e-07,5.64594e-08,0.998206,0.000490036,-1.55474e-07,-4.98245e-08,0.998696,0.000489576,-3.04948e-07,2.36292e-08,0.999186,0.000489037,-2.3406e-07,1.49121e-08,0.999674,0.000488613,-1.89324e-07,-2.3673e-08,1.00016,0.000488164,-2.60343e-07,2.01754e-08,1.00065,0.000487704,-1.99816e-07,-5.70288e-08,1.00114,0.000487133,-3.70903e-07,8.87303e-08,1.00162,0.000486657,-1.04712e-07,-5.94737e-08,1.00211,0.000486269,-2.83133e-07,2.99553e-08,1.0026,0.000485793,-1.93267e-07,-6.03474e-08,1.00308,0.000485225,-3.74309e-07,9.2225e-08,1.00357,0.000484754,-9.76345e-08,-7.0134e-08,1.00405,0.000484348,-3.08036e-07,6.91016e-08,1.00454,0.000483939,-1.00731e-07,-8.70633e-08,1.00502,0.000483476,-3.61921e-07,4.07328e-08,1.0055,0.000482875,-2.39723e-07,4.33413e-08,1.00599,0.000482525,-1.09699e-07,-9.48886e-08,1.00647,0.000482021,-3.94365e-07,9.77947e-08,1.00695,0.000481526,-1.00981e-07,-5.78713e-08,1.00743,0.00048115,-2.74595e-07,1.44814e-08,1.00791,0.000480645,-2.31151e-07,-5.42665e-11,1.00839,0.000480182,-2.31314e-07,-1.42643e-08,1.00887,0.000479677,-2.74106e-07,5.71115e-08,1.00935,0.0004793,-1.02772e-07,-9.49724e-08,1.00983,0.000478809,-3.87689e-07,8.43596e-08,1.01031,0.000478287,-1.3461e-07,-4.04755e-09,1.01079,0.000478006,-1.46753e-07,-6.81694e-08,1.01127,0.000477508,-3.51261e-07,3.83067e-08,1.01174,0.00047692,-2.36341e-07,3.41521e-08,1.01222,0.00047655,-1.33885e-07,-5.57058e-08,1.0127,0.000476115,-3.01002e-07,6.94616e-08,1.01317,0.000475721,-9.26174e-08,-1.02931e-07,1.01365,0.000475227,-4.01412e-07,1.03846e-07,1.01412,0.000474736,-8.98751e-08,-7.40321e-08,1.0146,0.000474334,-3.11971e-07,7.30735e-08,1.01507,0.00047393,-9.27508e-08,-9.90527e-08,1.01554,0.000473447,-3.89909e-07,8.47188e-08,1.01602,0.000472921,-1.35753e-07,-1.40381e-09,1.01649,0.000472645,-1.39964e-07,-7.91035e-08,1.01696,0.000472128,-3.77275e-07,7.93993e-08,1.01744,0.000471612,-1.39077e-07,-7.52607e-11,1.01791,0.000471334,-1.39302e-07,-7.90983e-08,1.01838,0.000470818,-3.76597e-07,7.80499e-08,1.01885,0.000470299,-1.42448e-07,5.31733e-09,1.01932,0.00047003,-1.26496e-07,-9.93193e-08,1.01979,0.000469479,-4.24453e-07,1.53541e-07,1.02026,0.00046909,3.617e-08,-1.57217e-07,1.02073,0.000468691,-4.35482e-07,1.177e-07,1.02119,0.000468173,-8.23808e-08,-7.51659e-08,1.02166,0.000467783,-3.07878e-07,6.37538e-08,1.02213,0.000467358,-1.16617e-07,-6.064e-08,1.0226,0.000466943,-2.98537e-07,5.9597e-08,1.02306,0.000466525,-1.19746e-07,-5.85386e-08,1.02353,0.00046611,-2.95362e-07,5.53482e-08,1.024,0.000465685,-1.29317e-07,-4.36449e-08,1.02446,0.000465296,-2.60252e-07,2.20268e-11,1.02493,0.000464775,-2.60186e-07,4.35568e-08,1.02539,0.000464386,-1.29516e-07,-5.50398e-08,1.02586,0.000463961,-2.94635e-07,5.73932e-08,1.02632,0.000463544,-1.22456e-07,-5.53236e-08,1.02678,0.000463133,-2.88426e-07,4.46921e-08,1.02725,0.000462691,-1.5435e-07,-4.23534e-09,1.02771,0.000462369,-1.67056e-07,-2.77507e-08,1.02817,0.000461952,-2.50308e-07,-3.97101e-09,1.02863,0.000461439,-2.62221e-07,4.36348e-08,1.02909,0.000461046,-1.31317e-07,-5.13589e-08,1.02955,0.000460629,-2.85394e-07,4.25913e-08,1.03001,0.000460186,-1.5762e-07,2.0285e-10,1.03047,0.000459871,-1.57011e-07,-4.34027e-08,1.03093,0.000459427,-2.87219e-07,5.41987e-08,1.03139,0.000459015,-1.24623e-07,-5.4183e-08,1.03185,0.000458604,-2.87172e-07,4.33239e-08,1.03231,0.000458159,-1.572e-07,9.65817e-11,1.03277,0.000457845,-1.56911e-07,-4.37103e-08,1.03323,0.0004574,-2.88041e-07,5.55351e-08,1.03368,0.000456991,-1.21436e-07,-5.9221e-08,1.03414,0.00045657,-2.99099e-07,6.21394e-08,1.0346,0.000456158,-1.1268e-07,-7.01275e-08,1.03505,0.000455723,-3.23063e-07,9.91614e-08,1.03551,0.000455374,-2.55788e-08,-8.80996e-08,1.03596,0.000455058,-2.89878e-07,1.48184e-08,1.03642,0.000454523,-2.45422e-07,2.88258e-08,1.03687,0.000454119,-1.58945e-07,-1.09125e-08,1.03733,0.000453768,-1.91682e-07,1.48241e-08,1.03778,0.000453429,-1.4721e-07,-4.83838e-08,1.03823,0.00045299,-2.92361e-07,5.95019e-08,1.03869,0.000452584,-1.13856e-07,-7.04146e-08,1.03914,0.000452145,-3.25099e-07,1.02947e-07,1.03959,0.000451803,-1.62583e-08,-1.02955e-07,1.04004,0.000451462,-3.25123e-07,7.04544e-08,1.04049,0.000451023,-1.1376e-07,-5.96534e-08,1.04094,0.000450616,-2.9272e-07,4.89499e-08,1.04139,0.000450178,-1.45871e-07,-1.69369e-08,1.04184,0.000449835,-1.96681e-07,1.87977e-08,1.04229,0.000449498,-1.40288e-07,-5.82539e-08,1.04274,0.000449043,-3.1505e-07,9.50087e-08,1.04319,0.000448698,-3.00238e-08,-8.33623e-08,1.04364,0.000448388,-2.80111e-07,2.20363e-11,1.04409,0.000447828,-2.80045e-07,8.32742e-08,1.04454,0.000447517,-3.02221e-08,-9.47002e-08,1.04498,0.000447173,-3.14323e-07,5.7108e-08,1.04543,0.000446716,-1.42999e-07,-1.45225e-08,1.04588,0.000446386,-1.86566e-07,9.82022e-10,1.04632,0.000446016,-1.8362e-07,1.05944e-08,1.04677,0.00044568,-1.51837e-07,-4.33597e-08,1.04721,0.000445247,-2.81916e-07,4.36352e-08,1.04766,0.000444814,-1.51011e-07,-1.19717e-08,1.0481,0.000444476,-1.86926e-07,4.25158e-09,1.04855,0.000444115,-1.74171e-07,-5.03461e-09,1.04899,0.000443751,-1.89275e-07,1.58868e-08,1.04944,0.00044342,-1.41614e-07,-5.85127e-08,1.04988,0.000442961,-3.17152e-07,9.89548e-08,1.05032,0.000442624,-2.0288e-08,-9.88878e-08,1.05076,0.000442287,-3.16951e-07,5.81779e-08,1.05121,0.000441827,-1.42418e-07,-1.46144e-08,1.05165,0.000441499,-1.86261e-07,2.79892e-10,1.05209,0.000441127,-1.85421e-07,1.34949e-08,1.05253,0.000440797,-1.44937e-07,-5.42594e-08,1.05297,0.000440344,-3.07715e-07,8.43335e-08,1.05341,0.000439982,-5.47146e-08,-4.46558e-08,1.05385,0.000439738,-1.88682e-07,-2.49193e-08,1.05429,0.000439286,-2.6344e-07,2.5124e-08,1.05473,0.000438835,-1.88068e-07,4.36328e-08,1.05517,0.000438589,-5.71699e-08,-8.04459e-08,1.05561,0.000438234,-2.98508e-07,3.97324e-08,1.05605,0.000437756,-1.79311e-07,4.07258e-08,1.05648,0.000437519,-5.71332e-08,-8.34263e-08,1.05692,0.000437155,-3.07412e-07,5.45608e-08,1.05736,0.000436704,-1.4373e-07,-1.56078e-08,1.05779,0.000436369,-1.90553e-07,7.87043e-09,1.05823,0.000436012,-1.66942e-07,-1.58739e-08,1.05867,0.00043563,-2.14563e-07,5.56251e-08,1.0591,0.000435368,-4.76881e-08,-8.74172e-08,1.05954,0.000435011,-3.0994e-07,5.56251e-08,1.05997,0.000434558,-1.43064e-07,-1.58739e-08,1.06041,0.000434224,-1.90686e-07,7.87042e-09,1.06084,0.000433866,-1.67075e-07,-1.56078e-08,1.06127,0.000433485,-2.13898e-07,5.45609e-08,1.06171,0.000433221,-5.02157e-08,-8.34263e-08,1.06214,0.00043287,-3.00495e-07,4.07258e-08,1.06257,0.000432391,-1.78317e-07,3.97325e-08,1.063,0.000432154,-5.91198e-08,-8.04464e-08,1.06344,0.000431794,-3.00459e-07,4.36347e-08,1.06387,0.000431324,-1.69555e-07,2.5117e-08,1.0643,0.000431061,-9.42041e-08,-2.48934e-08,1.06473,0.000430798,-1.68884e-07,-4.47527e-08,1.06516,0.000430326,-3.03142e-07,8.46951e-08,1.06559,0.000429973,-4.90573e-08,-5.56089e-08,1.06602,0.000429708,-2.15884e-07,1.85314e-08,1.06645,0.000429332,-1.6029e-07,-1.85166e-08,1.06688,0.000428956,-2.1584e-07,5.5535e-08,1.06731,0.000428691,-4.92347e-08,-8.44142e-08,1.06774,0.000428339,-3.02477e-07,4.37032e-08,1.06816,0.000427865,-1.71368e-07,2.88107e-08,1.06859,0.000427609,-8.49356e-08,-3.97367e-08,1.06902,0.00042732,-2.04146e-07,1.09267e-08,1.06945,0.000426945,-1.71365e-07,-3.97023e-09,1.06987,0.00042659,-1.83276e-07,4.9542e-09,1.0703,0.000426238,-1.68414e-07,-1.58466e-08,1.07073,0.000425854,-2.15953e-07,5.84321e-08,1.07115,0.000425597,-4.0657e-08,-9.86725e-08,1.07158,0.00042522,-3.36674e-07,9.78392e-08,1.072,0.00042484,-4.31568e-08,-5.42658e-08,1.07243,0.000424591,-2.05954e-07,1.45377e-11,1.07285,0.000424179,-2.0591e-07,5.42076e-08,1.07328,0.00042393,-4.32877e-08,-9.76357e-08,1.0737,0.00042355,-3.36195e-07,9.79165e-08,1.07412,0.000423172,-4.24451e-08,-5.56118e-08,1.07455,0.00042292,-2.09281e-07,5.32143e-09,1.07497,0.000422518,-1.93316e-07,3.43261e-08,1.07539,0.000422234,-9.0338e-08,-2.34165e-08,1.07581,0.000421983,-1.60588e-07,-5.98692e-08,1.07623,0.000421482,-3.40195e-07,1.43684e-07,1.07666,0.000421233,9.08574e-08,-1.5724e-07,1.07708,0.000420943,-3.80862e-07,1.27647e-07,1.0775,0.000420564,2.0791e-09,-1.1493e-07,1.07792,0.000420223,-3.4271e-07,9.36534e-08,1.07834,0.000419819,-6.17499e-08,-2.12653e-08,1.07876,0.000419632,-1.25546e-07,-8.59219e-09,1.07918,0.000419355,-1.51322e-07,-6.35752e-08,1.0796,0.000418861,-3.42048e-07,1.43684e-07,1.08002,0.000418608,8.90034e-08,-1.53532e-07,1.08043,0.000418326,-3.71593e-07,1.12817e-07,1.08085,0.000417921,-3.31414e-08,-5.93184e-08,1.08127,0.000417677,-2.11097e-07,5.24697e-09,1.08169,0.00041727,-1.95356e-07,3.83305e-08,1.0821,0.000416995,-8.03642e-08,-3.93597e-08,1.08252,0.000416716,-1.98443e-07,-1.0094e-10,1.08294,0.000416319,-1.98746e-07,3.97635e-08,1.08335,0.00041604,-7.94557e-08,-3.97437e-08,1.08377,0.000415762,-1.98687e-07,1.94215e-12,1.08419,0.000415365,-1.98681e-07,3.97359e-08,1.0846,0.000415087,-7.94732e-08,-3.97362e-08,1.08502,0.000414809,-1.98682e-07,-4.31063e-13,1.08543,0.000414411,-1.98683e-07,3.97379e-08,1.08584,0.000414133,-7.94694e-08,-3.97418e-08,1.08626,0.000413855,-1.98695e-07,2.00563e-11,1.08667,0.000413458,-1.98635e-07,3.96616e-08,1.08709,0.000413179,-7.965e-08,-3.9457e-08,1.0875,0.000412902,-1.98021e-07,-1.04281e-09,1.08791,0.000412502,-2.01149e-07,4.36282e-08,1.08832,0.000412231,-7.02648e-08,-5.42608e-08,1.08874,0.000411928,-2.33047e-07,5.42057e-08,1.08915,0.000411624,-7.04301e-08,-4.33527e-08,1.08956,0.000411353,-2.00488e-07,-4.07378e-12,1.08997,0.000410952,-2.005e-07,4.3369e-08,1.09038,0.000410681,-7.03934e-08,-5.42627e-08,1.09079,0.000410378,-2.33182e-07,5.44726e-08,1.0912,0.000410075,-6.97637e-08,-4.44186e-08,1.09161,0.000409802,-2.03019e-07,3.99235e-09,1.09202,0.000409408,-1.91042e-07,2.84491e-08,1.09243,0.000409111,-1.05695e-07,1.42043e-09,1.09284,0.000408904,-1.01434e-07,-3.41308e-08,1.09325,0.000408599,-2.03826e-07,1.58937e-08,1.09366,0.000408239,-1.56145e-07,-2.94438e-08,1.09406,0.000407838,-2.44476e-07,1.01881e-07,1.09447,0.000407655,6.11676e-08,-1.39663e-07,1.09488,0.000407358,-3.57822e-07,9.91432e-08,1.09529,0.00040694,-6.03921e-08,-1.84912e-08,1.09569,0.000406764,-1.15866e-07,-2.51785e-08,1.0961,0.000406457,-1.91401e-07,-4.03115e-12,1.09651,0.000406074,-1.91413e-07,2.51947e-08,1.09691,0.000405767,-1.15829e-07,1.84346e-08,1.09732,0.00040559,-6.05254e-08,-9.89332e-08,1.09772,0.000405172,-3.57325e-07,1.3888e-07,1.09813,0.000404874,5.93136e-08,-9.8957e-08,1.09853,0.000404696,-2.37557e-07,1.853e-08,1.09894,0.000404277,-1.81968e-07,2.48372e-08,1.09934,0.000403987,-1.07456e-07,1.33047e-09,1.09975,0.000403776,-1.03465e-07,-3.01591e-08,1.10015,0.000403479,-1.93942e-07,9.66054e-11,1.10055,0.000403091,-1.93652e-07,2.97727e-08,1.10096,0.000402793,-1.04334e-07,2.19273e-11,1.10136,0.000402585,-1.04268e-07,-2.98604e-08,1.10176,0.000402287,-1.93849e-07,2.10325e-10,1.10216,0.0004019,-1.93218e-07,2.90191e-08,1.10256,0.0004016,-1.06161e-07,2.92264e-09,1.10297,0.000401397,-9.73931e-08,-4.07096e-08,1.10337,0.00040108,-2.19522e-07,4.07067e-08,1.10377,0.000400763,-9.7402e-08,-2.90783e-09,1.10417,0.000400559,-1.06126e-07,-2.90754e-08,1.10457,0.00040026,-1.93352e-07,9.00021e-14,1.10497,0.000399873,-1.93351e-07,2.9075e-08,1.10537,0.000399574,-1.06126e-07,2.90902e-09,1.10577,0.00039937,-9.73992e-08,-4.07111e-08,1.10617,0.000399053,-2.19533e-07,4.07262e-08,1.10657,0.000398736,-9.73541e-08,-2.98424e-09,1.10697,0.000398533,-1.06307e-07,-2.87892e-08,1.10736,0.000398234,-1.92674e-07,-1.06824e-09,1.10776,0.000397845,-1.95879e-07,3.30622e-08,1.10816,0.000397552,-9.66926e-08,-1.19712e-08,1.10856,0.000397323,-1.32606e-07,1.48225e-08,1.10895,0.000397102,-8.81387e-08,-4.73187e-08,1.10935,0.000396784,-2.30095e-07,5.52429e-08,1.10975,0.00039649,-6.4366e-08,-5.44437e-08,1.11014,0.000396198,-2.27697e-07,4.33226e-08,1.11054,0.000395872,-9.77293e-08,3.62656e-10,1.11094,0.000395678,-9.66414e-08,-4.47732e-08,1.11133,0.00039535,-2.30961e-07,5.95208e-08,1.11173,0.000395067,-5.23985e-08,-7.41008e-08,1.11212,0.00039474,-2.74701e-07,1.17673e-07,1.11252,0.000394543,7.83181e-08,-1.58172e-07,1.11291,0.000394225,-3.96199e-07,1.57389e-07,1.1133,0.000393905,7.59679e-08,-1.13756e-07,1.1137,0.000393716,-2.653e-07,5.92165e-08,1.11409,0.000393363,-8.76507e-08,-3.90074e-09,1.11449,0.000393176,-9.93529e-08,-4.36136e-08,1.11488,0.000392846,-2.30194e-07,5.91457e-08,1.11527,0.000392563,-5.27564e-08,-7.376e-08,1.11566,0.000392237,-2.74037e-07,1.16685e-07,1.11606,0.000392039,7.60189e-08,-1.54562e-07,1.11645,0.000391727,-3.87667e-07,1.43935e-07,1.11684,0.000391384,4.4137e-08,-6.35487e-08,1.11723,0.000391281,-1.46509e-07,-8.94896e-09,1.11762,0.000390961,-1.73356e-07,-1.98647e-08,1.11801,0.000390555,-2.3295e-07,8.8408e-08,1.1184,0.000390354,3.22736e-08,-9.53486e-08,1.11879,0.000390133,-2.53772e-07,5.45677e-08,1.11918,0.000389789,-9.0069e-08,-3.71296e-09,1.11957,0.000389598,-1.01208e-07,-3.97159e-08,1.11996,0.000389276,-2.20355e-07,4.33671e-08,1.12035,0.000388966,-9.02542e-08,-1.45431e-08,1.12074,0.000388741,-1.33883e-07,1.48052e-08,1.12113,0.000388518,-8.94678e-08,-4.46778e-08,1.12152,0.000388205,-2.23501e-07,4.46966e-08,1.12191,0.000387892,-8.94114e-08,-1.48992e-08,1.12229,0.000387669,-1.34109e-07,1.49003e-08,1.12268,0.000387445,-8.94082e-08,-4.47019e-08,1.12307,0.000387132,-2.23514e-07,4.4698e-08,1.12345,0.000386819,-8.942e-08,-1.48806e-08,1.12384,0.000386596,-1.34062e-07,1.48245e-08,1.12423,0.000386372,-8.95885e-08,-4.44172e-08,1.12461,0.00038606,-2.2284e-07,4.36351e-08,1.125,0.000385745,-9.19348e-08,-1.09139e-08,1.12539,0.000385528,-1.24677e-07,2.05584e-11,1.12577,0.000385279,-1.24615e-07,1.08317e-08,1.12616,0.000385062,-9.21198e-08,-4.33473e-08,1.12654,0.000384748,-2.22162e-07,4.33481e-08,1.12693,0.000384434,-9.21174e-08,-1.08356e-08,1.12731,0.000384217,-1.24624e-07,-5.50907e-12,1.12769,0.000383968,-1.24641e-07,1.08577e-08,1.12808,0.000383751,-9.20679e-08,-4.34252e-08,1.12846,0.000383437,-2.22343e-07,4.36337e-08,1.12884,0.000383123,-9.14422e-08,-1.19005e-08,1.12923,0.000382904,-1.27144e-07,3.96813e-09,1.12961,0.000382662,-1.15239e-07,-3.97207e-09,1.12999,0.000382419,-1.27155e-07,1.19201e-08,1.13038,0.000382201,-9.1395e-08,-4.37085e-08,1.13076,0.000381887,-2.2252e-07,4.37046e-08,1.13114,0.000381573,-9.14068e-08,-1.19005e-08,1.13152,0.000381355,-1.27108e-07,3.89734e-09,1.1319,0.000381112,-1.15416e-07,-3.68887e-09,1.13228,0.00038087,-1.26483e-07,1.08582e-08,1.13266,0.00038065,-9.39083e-08,-3.97438e-08,1.13304,0.000380343,-2.1314e-07,2.89076e-08,1.13342,0.000380003,-1.26417e-07,4.33225e-08,1.1338,0.00037988,3.55072e-09,-8.29883e-08,1.13418,0.000379638,-2.45414e-07,5.0212e-08,1.13456,0.000379298,-9.47781e-08,1.34964e-09,1.13494,0.000379113,-9.07292e-08,-5.56105e-08,1.13532,0.000378764,-2.57561e-07,1.01883e-07,1.1357,0.000378555,4.80889e-08,-1.13504e-07,1.13608,0.000378311,-2.92423e-07,1.13713e-07,1.13646,0.000378067,4.87176e-08,-1.02931e-07,1.13683,0.000377856,-2.60076e-07,5.95923e-08,1.13721,0.000377514,-8.12988e-08,-1.62288e-08,1.13759,0.000377303,-1.29985e-07,5.32278e-09,1.13797,0.000377059,-1.14017e-07,-5.06237e-09,1.13834,0.000376816,-1.29204e-07,1.49267e-08,1.13872,0.000376602,-8.44237e-08,-5.46444e-08,1.1391,0.000376269,-2.48357e-07,8.44417e-08,1.13947,0.000376026,4.96815e-09,-4.47039e-08,1.13985,0.000375902,-1.29143e-07,-2.48355e-08,1.14023,0.000375569,-2.0365e-07,2.48368e-08,1.1406,0.000375236,-1.2914e-07,4.46977e-08,1.14098,0.000375112,4.95341e-09,-8.44184e-08,1.14135,0.000374869,-2.48302e-07,5.45572e-08,1.14173,0.000374536,-8.463e-08,-1.46013e-08,1.1421,0.000374323,-1.28434e-07,3.8478e-09,1.14247,0.000374077,-1.1689e-07,-7.89941e-10,1.14285,0.000373841,-1.1926e-07,-6.88042e-10,1.14322,0.0003736,-1.21324e-07,3.54213e-09,1.1436,0.000373368,-1.10698e-07,-1.34805e-08,1.14397,0.000373107,-1.51139e-07,5.03798e-08,1.14434,0.000372767,0.,0.}; - - template - __device__ __forceinline__ void RGB2LuvConvert_f(const T& src, D& dst) - { - const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); - const float _un = 13 * (4 * 0.950456f * _d); - const float _vn = 13 * (9 * _d); - - float B = blueIdx == 0 ? src.x : src.z; - float G = src.y; - float R = blueIdx == 0 ? src.z : src.x; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); - } - - float X = R * 0.412453f + G * 0.357580f + B * 0.180423f; - float Y = R * 0.212671f + G * 0.715160f + B * 0.072169f; - float Z = R * 0.019334f + G * 0.119193f + B * 0.950227f; - - float L = splineInterpolate(Y * (LAB_CBRT_TAB_SIZE / 1.5f), c_LabCbrtTab, LAB_CBRT_TAB_SIZE); - L = 116.f * L - 16.f; - - const float d = (4 * 13) / ::fmaxf(X + 15 * Y + 3 * Z, numeric_limits::epsilon()); - float u = L * (X * d - _un); - float v = L * ((9 * 0.25f) * Y * d - _vn); - - dst.x = L; - dst.y = u; - dst.z = v; - } - - template - __device__ __forceinline__ void RGB2LuvConvert_b(const T& src, D& dst) - { - float3 srcf, dstf; - - srcf.x = src.x * (1.f / 255.f); - srcf.y = src.y * (1.f / 255.f); - srcf.z = src.z * (1.f / 255.f); - - RGB2LuvConvert_f(srcf, dstf); - - dst.x = saturate_cast(dstf.x * 2.55f); - dst.y = saturate_cast(dstf.y * 0.72033898305084743f + 96.525423728813564f); - dst.z = saturate_cast(dstf.z * 0.9732824427480916f + 136.259541984732824f); - } - - template struct RGB2Luv; - template - struct RGB2Luv - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LuvConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Luv() {} - __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} - }; - template - struct RGB2Luv - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - RGB2LuvConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ RGB2Luv() {} - __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::RGB2Luv functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - namespace color_detail - { - template - __device__ __forceinline__ void Luv2RGBConvert_f(const T& src, D& dst) - { - const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); - const float _un = 4 * 0.950456f * _d; - const float _vn = 9 * _d; - - float L = src.x; - float u = src.y; - float v = src.z; - - float Y = (L + 16.f) * (1.f / 116.f); - Y = Y * Y * Y; - - float d = (1.f / 13.f) / L; - u = u * d + _un; - v = v * d + _vn; - - float iv = 1.f / v; - float X = 2.25f * u * Y * iv; - float Z = (12 - 3 * u - 20 * v) * Y * 0.25f * iv; - - float B = 0.055648f * X - 0.204043f * Y + 1.057311f * Z; - float G = -0.969256f * X + 1.875991f * Y + 0.041556f * Z; - float R = 3.240479f * X - 1.537150f * Y - 0.498535f * Z; - - if (srgb) - { - B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); - } - - dst.x = blueIdx == 0 ? B : R; - dst.y = G; - dst.z = blueIdx == 0 ? R : B; - setAlpha(dst, ColorChannel::max()); - } - - template - __device__ __forceinline__ void Luv2RGBConvert_b(const T& src, D& dst) - { - float3 srcf, dstf; - - srcf.x = src.x * (100.f / 255.f); - srcf.y = src.y * 1.388235294117647f - 134.f; - srcf.z = src.z * 1.027450980392157f - 140.f; - - Luv2RGBConvert_f(srcf, dstf); - - dst.x = saturate_cast(dstf.x * 255.f); - dst.y = saturate_cast(dstf.y * 255.f); - dst.z = saturate_cast(dstf.z * 255.f); - setAlpha(dst, ColorChannel::max()); - } - - template struct Luv2RGB; - template - struct Luv2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Luv2RGBConvert_b(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Luv2RGB() {} - __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} - }; - template - struct Luv2RGB - : unary_function::vec_type, typename TypeVec::vec_type> - { - __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const - { - typename TypeVec::vec_type dst; - - Luv2RGBConvert_f(src, dst); - - return dst; - } - __host__ __device__ __forceinline__ Luv2RGB() {} - __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} - }; - } - -#define OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ - template struct name ## _traits \ - { \ - typedef ::cv::cuda::device::color_detail::Luv2RGB functor_type; \ - static __host__ __device__ __forceinline__ functor_type create_functor() \ - { \ - return functor_type(); \ - } \ - }; - - #undef CV_DESCALE - -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_COLOR_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_COLOR_DETAIL_HPP +#define OPENCV_CUDA_COLOR_DETAIL_HPP + +#include "../common.hpp" +#include "../vec_traits.hpp" +#include "../saturate_cast.hpp" +#include "../limits.hpp" +#include "../functional.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + #ifndef CV_DESCALE + #define CV_DESCALE(x, n) (((x) + (1 << ((n)-1))) >> (n)) + #endif + + namespace color_detail + { + template struct ColorChannel + { + typedef float worktype_f; + static __device__ __forceinline__ T max() { return numeric_limits::max(); } + static __device__ __forceinline__ T half() { return (T)(max()/2 + 1); } + }; + + template<> struct ColorChannel + { + typedef float worktype_f; + static __device__ __forceinline__ float max() { return 1.f; } + static __device__ __forceinline__ float half() { return 0.5f; } + }; + + template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) + { + } + + template static __device__ __forceinline__ void setAlpha(typename TypeVec::vec_type& vec, T val) + { + vec.w = val; + } + + template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) + { + return ColorChannel::max(); + } + + template static __device__ __forceinline__ T getAlpha(const typename TypeVec::vec_type& vec) + { + return vec.w; + } + + //constants for conversion from/to RGB and Gray, YUV, YCrCb according to BT.601 + constexpr float B2YF = 0.114f; + constexpr float G2YF = 0.587f; + constexpr float R2YF = 0.299f; + + //to YCbCr + constexpr float YCBF = 0.564f; // == 1/2/(1-B2YF) + constexpr float YCRF = 0.713f; // == 1/2/(1-R2YF) + const int YCBI = 9241; // == YCBF*16384 + const int YCRI = 11682; // == YCRF*16384 + //to YUV + constexpr float B2UF = 0.492f; + constexpr float R2VF = 0.877f; + const int B2UI = 8061; // == B2UF*16384 + const int R2VI = 14369; // == R2VF*16384 + //from YUV + constexpr float U2BF = 2.032f; + constexpr float U2GF = -0.395f; + constexpr float V2GF = -0.581f; + constexpr float V2RF = 1.140f; + const int U2BI = 33292; + const int U2GI = -6472; + const int V2GI = -9519; + const int V2RI = 18678; + //from YCrCb + constexpr float CB2BF = 1.773f; + constexpr float CB2GF = -0.344f; + constexpr float CR2GF = -0.714f; + constexpr float CR2RF = 1.403f; + const int CB2BI = 29049; + const int CB2GI = -5636; + const int CR2GI = -11698; + const int CR2RI = 22987; + + enum + { + yuv_shift = 14, + xyz_shift = 12, + gray_shift = 15, + R2Y = 4899, + G2Y = 9617, + B2Y = 1868, + RY15 = 9798, // == R2YF*32768 + 0.5 + GY15 = 19235, // == G2YF*32768 + 0.5 + BY15 = 3735, // == B2YF*32768 + 0.5 + BLOCK_SIZE = 256 + }; + } + +////////////////// Various 3/4-channel to 3/4-channel RGB transformations ///////////////// + + namespace color_detail + { + template struct RGB2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + dst.x = (&src.x)[bidx]; + dst.y = src.y; + dst.z = (&src.x)[bidx^2]; + setAlpha(dst, getAlpha(src)); + + return dst; + } + + __host__ __device__ __forceinline__ RGB2RGB() {} + __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} + }; + + template <> struct RGB2RGB : unary_function + { + __device__ uint operator()(uint src) const + { + uint dst = 0; + + dst |= (0xffu & (src >> 16)); + dst |= (0xffu & (src >> 8)) << 8; + dst |= (0xffu & (src)) << 16; + dst |= (0xffu & (src >> 24)) << 24; + + return dst; + } + + __host__ __device__ __forceinline__ RGB2RGB() {} + __host__ __device__ __forceinline__ RGB2RGB(const RGB2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +/////////// Transforming 16-bit (565 or 555) RGB to/from 24/32-bit (888[8]) RGB ////////// + + namespace color_detail + { + template struct RGB2RGB5x5Converter; + template struct RGB2RGB5x5Converter<6, bidx> + { + static __device__ __forceinline__ ushort cvt(const uchar3& src) + { + return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~3) << 3) | (((&src.x)[bidx^2] & ~7) << 8)); + } + + static __device__ __forceinline__ ushort cvt(uint src) + { + uint b = 0xffu & (src >> (bidx * 8)); + uint g = 0xffu & (src >> 8); + uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + return (ushort)((b >> 3) | ((g & ~3) << 3) | ((r & ~7) << 8)); + } + }; + + template struct RGB2RGB5x5Converter<5, bidx> + { + static __device__ __forceinline__ ushort cvt(const uchar3& src) + { + return (ushort)(((&src.x)[bidx] >> 3) | ((src.y & ~7) << 2) | (((&src.x)[bidx^2] & ~7) << 7)); + } + + static __device__ __forceinline__ ushort cvt(uint src) + { + uint b = 0xffu & (src >> (bidx * 8)); + uint g = 0xffu & (src >> 8); + uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + uint a = 0xffu & (src >> 24); + return (ushort)((b >> 3) | ((g & ~7) << 2) | ((r & ~7) << 7) | (a * 0x8000)); + } + }; + + template struct RGB2RGB5x5; + + template struct RGB2RGB5x5<3, bidx,green_bits> : unary_function + { + __device__ __forceinline__ ushort operator()(const uchar3& src) const + { + return RGB2RGB5x5Converter::cvt(src); + } + + __host__ __device__ __forceinline__ RGB2RGB5x5() {} + __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} + }; + + template struct RGB2RGB5x5<4, bidx,green_bits> : unary_function + { + __device__ __forceinline__ ushort operator()(uint src) const + { + return RGB2RGB5x5Converter::cvt(src); + } + + __host__ __device__ __forceinline__ RGB2RGB5x5() {} + __host__ __device__ __forceinline__ RGB2RGB5x5(const RGB2RGB5x5&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2RGB5x5_TRAITS(name, scn, bidx, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2RGB5x5 functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template struct RGB5x52RGBConverter; + + template struct RGB5x52RGBConverter<5, bidx> + { + static __device__ __forceinline__ void cvt(uint src, uchar3& dst) + { + (&dst.x)[bidx] = src << 3; + dst.y = (src >> 2) & ~7; + (&dst.x)[bidx ^ 2] = (src >> 7) & ~7; + } + + static __device__ __forceinline__ void cvt(uint src, uint& dst) + { + dst = 0; + + dst |= (0xffu & (src << 3)) << (bidx * 8); + dst |= (0xffu & ((src >> 2) & ~7)) << 8; + dst |= (0xffu & ((src >> 7) & ~7)) << ((bidx ^ 2) * 8); + dst |= ((src & 0x8000) * 0xffu) << 24; + } + }; + + template struct RGB5x52RGBConverter<6, bidx> + { + static __device__ __forceinline__ void cvt(uint src, uchar3& dst) + { + (&dst.x)[bidx] = src << 3; + dst.y = (src >> 3) & ~3; + (&dst.x)[bidx ^ 2] = (src >> 8) & ~7; + } + + static __device__ __forceinline__ void cvt(uint src, uint& dst) + { + dst = 0xffu << 24; + + dst |= (0xffu & (src << 3)) << (bidx * 8); + dst |= (0xffu &((src >> 3) & ~3)) << 8; + dst |= (0xffu & ((src >> 8) & ~7)) << ((bidx ^ 2) * 8); + } + }; + + template struct RGB5x52RGB; + + template struct RGB5x52RGB<3, bidx, green_bits> : unary_function + { + __device__ __forceinline__ uchar3 operator()(ushort src) const + { + uchar3 dst; + RGB5x52RGBConverter::cvt(src, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB5x52RGB() {} + __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} + + }; + + template struct RGB5x52RGB<4, bidx, green_bits> : unary_function + { + __device__ __forceinline__ uint operator()(ushort src) const + { + uint dst; + RGB5x52RGBConverter::cvt(src, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB5x52RGB() {} + __host__ __device__ __forceinline__ RGB5x52RGB(const RGB5x52RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB5x52RGB_TRAITS(name, dcn, bidx, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB5x52RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////// Grayscale to Color //////////////////////////////// + + namespace color_detail + { + template struct Gray2RGB : unary_function::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(T src) const + { + typename TypeVec::vec_type dst; + + dst.z = dst.y = dst.x = src; + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ Gray2RGB() {} + __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} + }; + + template <> struct Gray2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + uint dst = 0xffu << 24; + + dst |= src; + dst |= src << 8; + dst |= src << 16; + + return dst; + } + __host__ __device__ __forceinline__ Gray2RGB() {} + __host__ __device__ __forceinline__ Gray2RGB(const Gray2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB_TRAITS(name, dcn) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Gray2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template struct Gray2RGB5x5Converter; + template<> struct Gray2RGB5x5Converter<6> + { + static __device__ __forceinline__ ushort cvt(uint t) + { + return (ushort)((t >> 3) | ((t & ~3) << 3) | ((t & ~7) << 8)); + } + }; + + template<> struct Gray2RGB5x5Converter<5> + { + static __device__ __forceinline__ ushort cvt(uint t) + { + t >>= 3; + return (ushort)(t | (t << 5) | (t << 10)); + } + }; + + template struct Gray2RGB5x5 : unary_function + { + __device__ __forceinline__ ushort operator()(uint src) const + { + return Gray2RGB5x5Converter::cvt(src); + } + + __host__ __device__ __forceinline__ Gray2RGB5x5() {} + __host__ __device__ __forceinline__ Gray2RGB5x5(const Gray2RGB5x5&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_GRAY2RGB5x5_TRAITS(name, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Gray2RGB5x5 functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////// Color to Grayscale //////////////////////////////// + + namespace color_detail + { + template struct RGB5x52GrayConverter; + template <> struct RGB5x52GrayConverter<6> + { + static __device__ __forceinline__ uchar cvt(uint t) + { + return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 3) & 0xfc) * GY15 + ((t >> 8) & 0xf8) * RY15, gray_shift); + } + }; + + template <> struct RGB5x52GrayConverter<5> + { + static __device__ __forceinline__ uchar cvt(uint t) + { + return (uchar)CV_DESCALE(((t << 3) & 0xf8) * BY15 + ((t >> 2) & 0xf8) * GY15 + ((t >> 7) & 0xf8) * RY15, gray_shift); + } + }; + + template struct RGB5x52Gray : unary_function + { + __device__ __forceinline__ uchar operator()(uint src) const + { + return RGB5x52GrayConverter::cvt(src); + } + __host__ __device__ __forceinline__ RGB5x52Gray() {} + __host__ __device__ __forceinline__ RGB5x52Gray(const RGB5x52Gray&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB5x52GRAY_TRAITS(name, green_bits) \ + struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB5x52Gray functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template static __device__ __forceinline__ T RGB2GrayConvert(const T* src) + { + return (T)CV_DESCALE((unsigned)(src[bidx] * BY15 + src[1] * GY15 + src[bidx^2] * RY15), gray_shift); + } + + template static __device__ __forceinline__ uchar RGB2GrayConvert(uint src) + { + uint b = 0xffu & (src >> (bidx * 8)); + uint g = 0xffu & (src >> 8); + uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + return CV_DESCALE((uint)(b * BY15 + g * GY15 + r * RY15), gray_shift); + } + + template static __device__ __forceinline__ float RGB2GrayConvert(const float* src) + { + return src[bidx] * B2YF + src[1] * G2YF + src[bidx^2] * R2YF; + } + + template struct RGB2Gray : unary_function::vec_type, T> + { + __device__ __forceinline__ T operator()(const typename TypeVec::vec_type& src) const + { + return RGB2GrayConvert(&src.x); + } + __host__ __device__ __forceinline__ RGB2Gray() {} + __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} + }; + + template struct RGB2Gray : unary_function + { + __device__ __forceinline__ uchar operator()(uint src) const + { + return RGB2GrayConvert(src); + } + __host__ __device__ __forceinline__ RGB2Gray() {} + __host__ __device__ __forceinline__ RGB2Gray(const RGB2Gray&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2GRAY_TRAITS(name, scn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2Gray functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> YUV ////////////////////////////////////// + + namespace color_detail + { + __constant__ float c_RGB2YUVCoeffs_f[5] = { B2YF, G2YF, R2YF, B2UF, R2VF }; + __constant__ int c_RGB2YUVCoeffs_i[5] = { B2Y, G2Y, R2Y, B2UI, R2VI }; + + template static __device__ void RGB2YUVConvert(const T* src, D& dst) + { + const int delta = ColorChannel::half() * (1 << yuv_shift); + + const int Y = CV_DESCALE(src[0] * c_RGB2YUVCoeffs_i[bidx^2] + src[1] * c_RGB2YUVCoeffs_i[1] + src[2] * c_RGB2YUVCoeffs_i[bidx], yuv_shift); + const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YUVCoeffs_i[3] + delta, yuv_shift); + const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YUVCoeffs_i[4] + delta, yuv_shift); + + dst.x = saturate_cast(Y); + dst.y = saturate_cast(Cr); + dst.z = saturate_cast(Cb); + } + + template static __device__ __forceinline__ void RGB2YUVConvert(const float* src, D& dst) + { + dst.x = src[0] * c_RGB2YUVCoeffs_f[bidx^2] + src[1] * c_RGB2YUVCoeffs_f[1] + src[2] * c_RGB2YUVCoeffs_f[bidx]; + dst.y = (src[bidx^2] - dst.x) * c_RGB2YUVCoeffs_f[3] + ColorChannel::half(); + dst.z = (src[bidx] - dst.x) * c_RGB2YUVCoeffs_f[4] + ColorChannel::half(); + } + + template struct RGB2YUV + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + RGB2YUVConvert(&src.x, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB2YUV() {} + __host__ __device__ __forceinline__ RGB2YUV(const RGB2YUV&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2YUV_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2YUV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_YUV2RGBCoeffs_f[5] = { U2BF, U2GF, V2GF, V2RF }; + __constant__ int c_YUV2RGBCoeffs_i[5] = { U2BI, U2GI, V2GI, V2RI }; + + template static __device__ void YUV2RGBConvert(const T& src, D* dst) + { + const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); + + const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] + + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); + + const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); + + dst[bidx] = saturate_cast(b); + dst[1] = saturate_cast(g); + dst[bidx^2] = saturate_cast(r); + } + + template static __device__ uint YUV2RGBConvert(uint src) + { + const int x = 0xff & (src); + const int y = 0xff & (src >> 8); + const int z = 0xff & (src >> 16); + + const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[3], yuv_shift); + + const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YUV2RGBCoeffs_i[2] + + (y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[1], yuv_shift); + + const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YUV2RGBCoeffs_i[0], yuv_shift); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(b) << (bidx * 8); + dst |= saturate_cast(g) << 8; + dst |= saturate_cast(r) << ((bidx ^ 2) * 8); + + return dst; + } + + template static __device__ __forceinline__ void YUV2RGBConvert(const T& src, float* dst) + { + dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[3]; + + dst[1] = src.x + (src.z - ColorChannel::half()) * c_YUV2RGBCoeffs_f[2] + + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[1]; + + dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YUV2RGBCoeffs_f[0]; + } + + template struct YUV2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + YUV2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ YUV2RGB() {} + __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} + }; + + template struct YUV2RGB : unary_function + { + __device__ __forceinline__ uint operator ()(uint src) const + { + return YUV2RGBConvert(src); + } + __host__ __device__ __forceinline__ YUV2RGB() {} + __host__ __device__ __forceinline__ YUV2RGB(const YUV2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_YUV2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::YUV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> YCrCb ////////////////////////////////////// + + namespace color_detail + { + __constant__ float c_RGB2YCrCbCoeffs_f[5] = {R2YF, G2YF, B2YF, YCRF, YCBF}; + __constant__ int c_RGB2YCrCbCoeffs_i[5] = {R2Y, G2Y, B2Y, YCRI, YCBI}; + + template static __device__ void RGB2YCrCbConvert(const T* src, D& dst) + { + const int delta = ColorChannel::half() * (1 << yuv_shift); + + const int Y = CV_DESCALE(src[0] * c_RGB2YCrCbCoeffs_i[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_i[1] + src[2] * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); + const int Cr = CV_DESCALE((src[bidx^2] - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); + const int Cb = CV_DESCALE((src[bidx] - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); + + dst.x = saturate_cast(Y); + dst.y = saturate_cast(Cr); + dst.z = saturate_cast(Cb); + } + + template static __device__ uint RGB2YCrCbConvert(uint src) + { + const int delta = ColorChannel::half() * (1 << yuv_shift); + + const int Y = CV_DESCALE((0xffu & src) * c_RGB2YCrCbCoeffs_i[bidx^2] + (0xffu & (src >> 8)) * c_RGB2YCrCbCoeffs_i[1] + (0xffu & (src >> 16)) * c_RGB2YCrCbCoeffs_i[bidx], yuv_shift); + const int Cr = CV_DESCALE(((0xffu & (src >> ((bidx ^ 2) * 8))) - Y) * c_RGB2YCrCbCoeffs_i[3] + delta, yuv_shift); + const int Cb = CV_DESCALE(((0xffu & (src >> (bidx * 8))) - Y) * c_RGB2YCrCbCoeffs_i[4] + delta, yuv_shift); + + uint dst = 0; + + dst |= saturate_cast(Y); + dst |= saturate_cast(Cr) << 8; + dst |= saturate_cast(Cb) << 16; + + return dst; + } + + template static __device__ __forceinline__ void RGB2YCrCbConvert(const float* src, D& dst) + { + dst.x = src[0] * c_RGB2YCrCbCoeffs_f[bidx^2] + src[1] * c_RGB2YCrCbCoeffs_f[1] + src[2] * c_RGB2YCrCbCoeffs_f[bidx]; + dst.y = (src[bidx^2] - dst.x) * c_RGB2YCrCbCoeffs_f[3] + ColorChannel::half(); + dst.z = (src[bidx] - dst.x) * c_RGB2YCrCbCoeffs_f[4] + ColorChannel::half(); + } + + template struct RGB2YCrCb + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + RGB2YCrCbConvert(&src.x, dst); + return dst; + } + __host__ __device__ __forceinline__ RGB2YCrCb() {} + __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} + }; + + template struct RGB2YCrCb : unary_function + { + __device__ __forceinline__ uint operator ()(uint src) const + { + return RGB2YCrCbConvert(src); + } + + __host__ __device__ __forceinline__ RGB2YCrCb() {} + __host__ __device__ __forceinline__ RGB2YCrCb(const RGB2YCrCb&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2YCrCb_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2YCrCb functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_YCrCb2RGBCoeffs_f[5] = {CR2RF, CR2GF, CB2GF, CB2BF}; + __constant__ int c_YCrCb2RGBCoeffs_i[5] = {CR2RI, CR2GI, CB2GI, CB2BI}; + + template static __device__ void YCrCb2RGBConvert(const T& src, D* dst) + { + const int b = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); + const int g = src.x + CV_DESCALE((src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); + const int r = src.x + CV_DESCALE((src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); + + dst[bidx] = saturate_cast(b); + dst[1] = saturate_cast(g); + dst[bidx^2] = saturate_cast(r); + } + + template static __device__ uint YCrCb2RGBConvert(uint src) + { + const int x = 0xff & (src); + const int y = 0xff & (src >> 8); + const int z = 0xff & (src >> 16); + + const int b = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[3], yuv_shift); + const int g = x + CV_DESCALE((z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[2] + (y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[1], yuv_shift); + const int r = x + CV_DESCALE((y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_i[0], yuv_shift); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(b) << (bidx * 8); + dst |= saturate_cast(g) << 8; + dst |= saturate_cast(r) << ((bidx ^ 2) * 8); + + return dst; + } + + template __device__ __forceinline__ void YCrCb2RGBConvert(const T& src, float* dst) + { + dst[bidx] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[3]; + dst[1] = src.x + (src.z - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[2] + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[1]; + dst[bidx^2] = src.x + (src.y - ColorChannel::half()) * c_YCrCb2RGBCoeffs_f[0]; + } + + template struct YCrCb2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + YCrCb2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ YCrCb2RGB() {} + __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} + }; + + template struct YCrCb2RGB : unary_function + { + __device__ __forceinline__ uint operator ()(uint src) const + { + return YCrCb2RGBConvert(src); + } + __host__ __device__ __forceinline__ YCrCb2RGB() {} + __host__ __device__ __forceinline__ YCrCb2RGB(const YCrCb2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_YCrCb2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::YCrCb2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +////////////////////////////////////// RGB <-> XYZ /////////////////////////////////////// + + namespace color_detail + { + __constant__ float c_RGB2XYZ_D65f[9] = { 0.412453f, 0.357580f, 0.180423f, 0.212671f, 0.715160f, 0.072169f, 0.019334f, 0.119193f, 0.950227f }; + __constant__ int c_RGB2XYZ_D65i[9] = { 1689, 1465, 739, 871, 2929, 296, 79, 488, 3892 }; + + template static __device__ __forceinline__ void RGB2XYZConvert(const T* src, D& dst) + { + dst.z = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[6] + src[1] * c_RGB2XYZ_D65i[7] + src[bidx] * c_RGB2XYZ_D65i[8], xyz_shift)); + dst.x = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[0] + src[1] * c_RGB2XYZ_D65i[1] + src[bidx] * c_RGB2XYZ_D65i[2], xyz_shift)); + dst.y = saturate_cast(CV_DESCALE(src[bidx^2] * c_RGB2XYZ_D65i[3] + src[1] * c_RGB2XYZ_D65i[4] + src[bidx] * c_RGB2XYZ_D65i[5], xyz_shift)); + } + + template static __device__ __forceinline__ uint RGB2XYZConvert(uint src) + { + const uint b = 0xffu & (src >> (bidx * 8)); + const uint g = 0xffu & (src >> 8); + const uint r = 0xffu & (src >> ((bidx ^ 2) * 8)); + + const uint x = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[0] + g * c_RGB2XYZ_D65i[1] + b * c_RGB2XYZ_D65i[2], xyz_shift)); + const uint y = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[3] + g * c_RGB2XYZ_D65i[4] + b * c_RGB2XYZ_D65i[5], xyz_shift)); + const uint z = saturate_cast(CV_DESCALE(r * c_RGB2XYZ_D65i[6] + g * c_RGB2XYZ_D65i[7] + b * c_RGB2XYZ_D65i[8], xyz_shift)); + + uint dst = 0; + + dst |= x; + dst |= y << 8; + dst |= z << 16; + + return dst; + } + + template static __device__ __forceinline__ void RGB2XYZConvert(const float* src, D& dst) + { + dst.x = src[bidx^2] * c_RGB2XYZ_D65f[0] + src[1] * c_RGB2XYZ_D65f[1] + src[bidx] * c_RGB2XYZ_D65f[2]; + dst.y = src[bidx^2] * c_RGB2XYZ_D65f[3] + src[1] * c_RGB2XYZ_D65f[4] + src[bidx] * c_RGB2XYZ_D65f[5]; + dst.z = src[bidx^2] * c_RGB2XYZ_D65f[6] + src[1] * c_RGB2XYZ_D65f[7] + src[bidx] * c_RGB2XYZ_D65f[8]; + } + + template struct RGB2XYZ + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2XYZConvert(&src.x, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2XYZ() {} + __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} + }; + + template struct RGB2XYZ : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return RGB2XYZConvert(src); + } + __host__ __device__ __forceinline__ RGB2XYZ() {} + __host__ __device__ __forceinline__ RGB2XYZ(const RGB2XYZ&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2XYZ_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2XYZ functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_XYZ2sRGB_D65f[9] = { 3.240479f, -1.53715f, -0.498535f, -0.969256f, 1.875991f, 0.041556f, 0.055648f, -0.204043f, 1.057311f }; + __constant__ int c_XYZ2sRGB_D65i[9] = { 13273, -6296, -2042, -3970, 7684, 170, 228, -836, 4331 }; + + template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, D* dst) + { + dst[bidx^2] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[0] + src.y * c_XYZ2sRGB_D65i[1] + src.z * c_XYZ2sRGB_D65i[2], xyz_shift)); + dst[1] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[3] + src.y * c_XYZ2sRGB_D65i[4] + src.z * c_XYZ2sRGB_D65i[5], xyz_shift)); + dst[bidx] = saturate_cast(CV_DESCALE(src.x * c_XYZ2sRGB_D65i[6] + src.y * c_XYZ2sRGB_D65i[7] + src.z * c_XYZ2sRGB_D65i[8], xyz_shift)); + } + + template static __device__ __forceinline__ uint XYZ2RGBConvert(uint src) + { + const int x = 0xff & src; + const int y = 0xff & (src >> 8); + const int z = 0xff & (src >> 16); + + const uint r = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[0] + y * c_XYZ2sRGB_D65i[1] + z * c_XYZ2sRGB_D65i[2], xyz_shift)); + const uint g = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[3] + y * c_XYZ2sRGB_D65i[4] + z * c_XYZ2sRGB_D65i[5], xyz_shift)); + const uint b = saturate_cast(CV_DESCALE(x * c_XYZ2sRGB_D65i[6] + y * c_XYZ2sRGB_D65i[7] + z * c_XYZ2sRGB_D65i[8], xyz_shift)); + + uint dst = 0xffu << 24; + + dst |= b << (bidx * 8); + dst |= g << 8; + dst |= r << ((bidx ^ 2) * 8); + + return dst; + } + + template static __device__ __forceinline__ void XYZ2RGBConvert(const T& src, float* dst) + { + dst[bidx^2] = src.x * c_XYZ2sRGB_D65f[0] + src.y * c_XYZ2sRGB_D65f[1] + src.z * c_XYZ2sRGB_D65f[2]; + dst[1] = src.x * c_XYZ2sRGB_D65f[3] + src.y * c_XYZ2sRGB_D65f[4] + src.z * c_XYZ2sRGB_D65f[5]; + dst[bidx] = src.x * c_XYZ2sRGB_D65f[6] + src.y * c_XYZ2sRGB_D65f[7] + src.z * c_XYZ2sRGB_D65f[8]; + } + + template struct XYZ2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + XYZ2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ XYZ2RGB() {} + __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} + }; + + template struct XYZ2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return XYZ2RGBConvert(src); + } + __host__ __device__ __forceinline__ XYZ2RGB() {} + __host__ __device__ __forceinline__ XYZ2RGB(const XYZ2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_XYZ2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::XYZ2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +////////////////////////////////////// RGB <-> HSV /////////////////////////////////////// + + namespace color_detail + { + __constant__ int c_HsvDivTable [256] = {0, 1044480, 522240, 348160, 261120, 208896, 174080, 149211, 130560, 116053, 104448, 94953, 87040, 80345, 74606, 69632, 65280, 61440, 58027, 54973, 52224, 49737, 47476, 45412, 43520, 41779, 40172, 38684, 37303, 36017, 34816, 33693, 32640, 31651, 30720, 29842, 29013, 28229, 27486, 26782, 26112, 25475, 24869, 24290, 23738, 23211, 22706, 22223, 21760, 21316, 20890, 20480, 20086, 19707, 19342, 18991, 18651, 18324, 18008, 17703, 17408, 17123, 16846, 16579, 16320, 16069, 15825, 15589, 15360, 15137, 14921, 14711, 14507, 14308, 14115, 13926, 13743, 13565, 13391, 13221, 13056, 12895, 12738, 12584, 12434, 12288, 12145, 12006, 11869, 11736, 11605, 11478, 11353, 11231, 11111, 10995, 10880, 10768, 10658, 10550, 10445, 10341, 10240, 10141, 10043, 9947, 9854, 9761, 9671, 9582, 9495, 9410, 9326, 9243, 9162, 9082, 9004, 8927, 8852, 8777, 8704, 8632, 8561, 8492, 8423, 8356, 8290, 8224, 8160, 8097, 8034, 7973, 7913, 7853, 7795, 7737, 7680, 7624, 7569, 7514, 7461, 7408, 7355, 7304, 7253, 7203, 7154, 7105, 7057, 7010, 6963, 6917, 6872, 6827, 6782, 6739, 6695, 6653, 6611, 6569, 6528, 6487, 6447, 6408, 6369, 6330, 6292, 6254, 6217, 6180, 6144, 6108, 6073, 6037, 6003, 5968, 5935, 5901, 5868, 5835, 5803, 5771, 5739, 5708, 5677, 5646, 5615, 5585, 5556, 5526, 5497, 5468, 5440, 5412, 5384, 5356, 5329, 5302, 5275, 5249, 5222, 5196, 5171, 5145, 5120, 5095, 5070, 5046, 5022, 4998, 4974, 4950, 4927, 4904, 4881, 4858, 4836, 4813, 4791, 4769, 4748, 4726, 4705, 4684, 4663, 4642, 4622, 4601, 4581, 4561, 4541, 4522, 4502, 4483, 4464, 4445, 4426, 4407, 4389, 4370, 4352, 4334, 4316, 4298, 4281, 4263, 4246, 4229, 4212, 4195, 4178, 4161, 4145, 4128, 4112, 4096}; + __constant__ int c_HsvDivTable180[256] = {0, 122880, 61440, 40960, 30720, 24576, 20480, 17554, 15360, 13653, 12288, 11171, 10240, 9452, 8777, 8192, 7680, 7228, 6827, 6467, 6144, 5851, 5585, 5343, 5120, 4915, 4726, 4551, 4389, 4237, 4096, 3964, 3840, 3724, 3614, 3511, 3413, 3321, 3234, 3151, 3072, 2997, 2926, 2858, 2793, 2731, 2671, 2614, 2560, 2508, 2458, 2409, 2363, 2318, 2276, 2234, 2194, 2156, 2119, 2083, 2048, 2014, 1982, 1950, 1920, 1890, 1862, 1834, 1807, 1781, 1755, 1731, 1707, 1683, 1661, 1638, 1617, 1596, 1575, 1555, 1536, 1517, 1499, 1480, 1463, 1446, 1429, 1412, 1396, 1381, 1365, 1350, 1336, 1321, 1307, 1293, 1280, 1267, 1254, 1241, 1229, 1217, 1205, 1193, 1182, 1170, 1159, 1148, 1138, 1127, 1117, 1107, 1097, 1087, 1078, 1069, 1059, 1050, 1041, 1033, 1024, 1016, 1007, 999, 991, 983, 975, 968, 960, 953, 945, 938, 931, 924, 917, 910, 904, 897, 890, 884, 878, 871, 865, 859, 853, 847, 842, 836, 830, 825, 819, 814, 808, 803, 798, 793, 788, 783, 778, 773, 768, 763, 759, 754, 749, 745, 740, 736, 731, 727, 723, 719, 714, 710, 706, 702, 698, 694, 690, 686, 683, 679, 675, 671, 668, 664, 661, 657, 654, 650, 647, 643, 640, 637, 633, 630, 627, 624, 621, 617, 614, 611, 608, 605, 602, 599, 597, 594, 591, 588, 585, 582, 580, 577, 574, 572, 569, 566, 564, 561, 559, 556, 554, 551, 549, 546, 544, 541, 539, 537, 534, 532, 530, 527, 525, 523, 521, 518, 516, 514, 512, 510, 508, 506, 504, 502, 500, 497, 495, 493, 492, 490, 488, 486, 484, 482}; + __constant__ int c_HsvDivTable256[256] = {0, 174763, 87381, 58254, 43691, 34953, 29127, 24966, 21845, 19418, 17476, 15888, 14564, 13443, 12483, 11651, 10923, 10280, 9709, 9198, 8738, 8322, 7944, 7598, 7282, 6991, 6722, 6473, 6242, 6026, 5825, 5638, 5461, 5296, 5140, 4993, 4855, 4723, 4599, 4481, 4369, 4263, 4161, 4064, 3972, 3884, 3799, 3718, 3641, 3567, 3495, 3427, 3361, 3297, 3236, 3178, 3121, 3066, 3013, 2962, 2913, 2865, 2819, 2774, 2731, 2689, 2648, 2608, 2570, 2533, 2497, 2461, 2427, 2394, 2362, 2330, 2300, 2270, 2241, 2212, 2185, 2158, 2131, 2106, 2081, 2056, 2032, 2009, 1986, 1964, 1942, 1920, 1900, 1879, 1859, 1840, 1820, 1802, 1783, 1765, 1748, 1730, 1713, 1697, 1680, 1664, 1649, 1633, 1618, 1603, 1589, 1574, 1560, 1547, 1533, 1520, 1507, 1494, 1481, 1469, 1456, 1444, 1432, 1421, 1409, 1398, 1387, 1376, 1365, 1355, 1344, 1334, 1324, 1314, 1304, 1295, 1285, 1276, 1266, 1257, 1248, 1239, 1231, 1222, 1214, 1205, 1197, 1189, 1181, 1173, 1165, 1157, 1150, 1142, 1135, 1128, 1120, 1113, 1106, 1099, 1092, 1085, 1079, 1072, 1066, 1059, 1053, 1046, 1040, 1034, 1028, 1022, 1016, 1010, 1004, 999, 993, 987, 982, 976, 971, 966, 960, 955, 950, 945, 940, 935, 930, 925, 920, 915, 910, 906, 901, 896, 892, 887, 883, 878, 874, 869, 865, 861, 857, 853, 848, 844, 840, 836, 832, 828, 824, 820, 817, 813, 809, 805, 802, 798, 794, 791, 787, 784, 780, 777, 773, 770, 767, 763, 760, 757, 753, 750, 747, 744, 741, 737, 734, 731, 728, 725, 722, 719, 716, 713, 710, 708, 705, 702, 699, 696, 694, 691, 688, 685}; + + template static __device__ void RGB2HSVConvert(const uchar* src, D& dst) + { + const int hsv_shift = 12; + const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; + + int b = src[bidx], g = src[1], r = src[bidx^2]; + int h, s, v = b; + int vmin = b, diff; + int vr, vg; + + v = ::max(v, g); + v = ::max(v, r); + vmin = ::min(vmin, g); + vmin = ::min(vmin, r); + + diff = v - vmin; + vr = (v == r) * -1; + vg = (v == g) * -1; + + s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; + h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); + h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; + h += (h < 0) * hr; + + dst.x = saturate_cast(h); + dst.y = (uchar)s; + dst.z = (uchar)v; + } + + template static __device__ uint RGB2HSVConvert(uint src) + { + const int hsv_shift = 12; + const int* hdiv_table = hr == 180 ? c_HsvDivTable180 : c_HsvDivTable256; + + const int b = 0xff & (src >> (bidx * 8)); + const int g = 0xff & (src >> 8); + const int r = 0xff & (src >> ((bidx ^ 2) * 8)); + + int h, s, v = b; + int vmin = b, diff; + int vr, vg; + + v = ::max(v, g); + v = ::max(v, r); + vmin = ::min(vmin, g); + vmin = ::min(vmin, r); + + diff = v - vmin; + vr = (v == r) * -1; + vg = (v == g) * -1; + + s = (diff * c_HsvDivTable[v] + (1 << (hsv_shift-1))) >> hsv_shift; + h = (vr & (g - b)) + (~vr & ((vg & (b - r + 2 * diff)) + ((~vg) & (r - g + 4 * diff)))); + h = (h * hdiv_table[diff] + (1 << (hsv_shift-1))) >> hsv_shift; + h += (h < 0) * hr; + + uint dst = 0; + + dst |= saturate_cast(h); + dst |= (0xffu & s) << 8; + dst |= (0xffu & v) << 16; + + return dst; + } + + template static __device__ void RGB2HSVConvert(const float* src, D& dst) + { + const float hscale = hr * (1.f / 360.f); + + float b = src[bidx], g = src[1], r = src[bidx^2]; + float h, s, v; + + float vmin, diff; + + v = vmin = r; + v = fmax(v, g); + v = fmax(v, b); + vmin = fmin(vmin, g); + vmin = fmin(vmin, b); + + diff = v - vmin; + s = diff / (float)(::fabs(v) + numeric_limits::epsilon()); + diff = (float)(60. / (diff + numeric_limits::epsilon())); + + h = (v == r) * (g - b) * diff; + h += (v != r && v == g) * ((b - r) * diff + 120.f); + h += (v != r && v != g) * ((r - g) * diff + 240.f); + h += (h < 0) * 360.f; + + dst.x = h * hscale; + dst.y = s; + dst.z = v; + } + + template struct RGB2HSV + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2HSVConvert(&src.x, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2HSV() {} + __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} + }; + + template struct RGB2HSV : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return RGB2HSVConvert(src); + } + __host__ __device__ __forceinline__ RGB2HSV() {} + __host__ __device__ __forceinline__ RGB2HSV(const RGB2HSV&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2HSV_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HSV functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ int c_HsvSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; + + template static __device__ void HSV2RGBConvert(const T& src, float* dst) + { + const float hscale = 6.f / hr; + + float h = src.x, s = src.y, v = src.z; + float b = v, g = v, r = v; + + if (s != 0) + { + h *= hscale; + + if( h < 0 ) + do h += 6; while( h < 0 ); + else if( h >= 6 ) + do h -= 6; while( h >= 6 ); + + int sector = __float2int_rd(h); + h -= sector; + + if ( (unsigned)sector >= 6u ) + { + sector = 0; + h = 0.f; + } + + float tab[4]; + tab[0] = v; + tab[1] = v * (1.f - s); + tab[2] = v * (1.f - s * h); + tab[3] = v * (1.f - s * (1.f - h)); + + b = tab[c_HsvSectorData[sector][0]]; + g = tab[c_HsvSectorData[sector][1]]; + r = tab[c_HsvSectorData[sector][2]]; + } + + dst[bidx] = b; + dst[1] = g; + dst[bidx^2] = r; + } + + template static __device__ void HSV2RGBConvert(const T& src, uchar* dst) + { + float3 buf; + + buf.x = src.x; + buf.y = src.y * (1.f / 255.f); + buf.z = src.z * (1.f / 255.f); + + HSV2RGBConvert(buf, &buf.x); + + dst[0] = saturate_cast(buf.x * 255.f); + dst[1] = saturate_cast(buf.y * 255.f); + dst[2] = saturate_cast(buf.z * 255.f); + } + + template static __device__ uint HSV2RGBConvert(uint src) + { + float3 buf; + + buf.x = src & 0xff; + buf.y = ((src >> 8) & 0xff) * (1.f/255.f); + buf.z = ((src >> 16) & 0xff) * (1.f/255.f); + + HSV2RGBConvert(buf, &buf.x); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(buf.x * 255.f); + dst |= saturate_cast(buf.y * 255.f) << 8; + dst |= saturate_cast(buf.z * 255.f) << 16; + + return dst; + } + + template struct HSV2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + HSV2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ HSV2RGB() {} + __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} + }; + + template struct HSV2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return HSV2RGBConvert(src); + } + __host__ __device__ __forceinline__ HSV2RGB() {} + __host__ __device__ __forceinline__ HSV2RGB(const HSV2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_HSV2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HSV2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +/////////////////////////////////////// RGB <-> HLS //////////////////////////////////////// + + namespace color_detail + { + template static __device__ void RGB2HLSConvert(const float* src, D& dst) + { + const float hscale = hr * (1.f / 360.f); + + float b = src[bidx], g = src[1], r = src[bidx^2]; + float h = 0.f, s = 0.f, l; + float vmin, vmax, diff; + + vmax = vmin = r; + vmax = fmax(vmax, g); + vmax = fmax(vmax, b); + vmin = fmin(vmin, g); + vmin = fmin(vmin, b); + + diff = vmax - vmin; + l = (vmax + vmin) * 0.5f; + + if (diff > numeric_limits::epsilon()) + { + s = (l < 0.5f) * diff / (vmax + vmin); + s += (l >= 0.5f) * diff / (2.0f - vmax - vmin); + + diff = 60.f / diff; + + h = (vmax == r) * (g - b) * diff; + h += (vmax != r && vmax == g) * ((b - r) * diff + 120.f); + h += (vmax != r && vmax != g) * ((r - g) * diff + 240.f); + h += (h < 0.f) * 360.f; + } + + dst.x = h * hscale; + dst.y = l; + dst.z = s; + } + + template static __device__ void RGB2HLSConvert(const uchar* src, D& dst) + { + float3 buf; + + buf.x = src[0] * (1.f / 255.f); + buf.y = src[1] * (1.f / 255.f); + buf.z = src[2] * (1.f / 255.f); + + RGB2HLSConvert(&buf.x, buf); + + dst.x = saturate_cast(buf.x); + dst.y = saturate_cast(buf.y*255.f); + dst.z = saturate_cast(buf.z*255.f); + } + + template static __device__ uint RGB2HLSConvert(uint src) + { + float3 buf; + + buf.x = (0xff & src) * (1.f / 255.f); + buf.y = (0xff & (src >> 8)) * (1.f / 255.f); + buf.z = (0xff & (src >> 16)) * (1.f / 255.f); + + RGB2HLSConvert(&buf.x, buf); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(buf.x); + dst |= saturate_cast(buf.y * 255.f) << 8; + dst |= saturate_cast(buf.z * 255.f) << 16; + + return dst; + } + + template struct RGB2HLS + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2HLSConvert(&src.x, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2HLS() {} + __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} + }; + + template struct RGB2HLS : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return RGB2HLSConvert(src); + } + __host__ __device__ __forceinline__ RGB2HLS() {} + __host__ __device__ __forceinline__ RGB2HLS(const RGB2HLS&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2HLS_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2HLS functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ int c_HlsSectorData[6][3] = { {1,3,0}, {1,0,2}, {3,0,1}, {0,2,1}, {0,1,3}, {2,1,0} }; + + template static __device__ void HLS2RGBConvert(const T& src, float* dst) + { + const float hscale = 6.0f / hr; + + float h = src.x, l = src.y, s = src.z; + float b = l, g = l, r = l; + + if (s != 0) + { + float p2 = (l <= 0.5f) * l * (1 + s); + p2 += (l > 0.5f) * (l + s - l * s); + float p1 = 2 * l - p2; + + h *= hscale; + + if( h < 0 ) + do h += 6; while( h < 0 ); + else if( h >= 6 ) + do h -= 6; while( h >= 6 ); + + int sector; + sector = __float2int_rd(h); + + h -= sector; + + float tab[4]; + tab[0] = p2; + tab[1] = p1; + tab[2] = p1 + (p2 - p1) * (1 - h); + tab[3] = p1 + (p2 - p1) * h; + + b = tab[c_HlsSectorData[sector][0]]; + g = tab[c_HlsSectorData[sector][1]]; + r = tab[c_HlsSectorData[sector][2]]; + } + + dst[bidx] = b; + dst[1] = g; + dst[bidx^2] = r; + } + + template static __device__ void HLS2RGBConvert(const T& src, uchar* dst) + { + float3 buf; + + buf.x = src.x; + buf.y = src.y * (1.f / 255.f); + buf.z = src.z * (1.f / 255.f); + + HLS2RGBConvert(buf, &buf.x); + + dst[0] = saturate_cast(buf.x * 255.f); + dst[1] = saturate_cast(buf.y * 255.f); + dst[2] = saturate_cast(buf.z * 255.f); + } + + template static __device__ uint HLS2RGBConvert(uint src) + { + float3 buf; + + buf.x = 0xff & src; + buf.y = (0xff & (src >> 8)) * (1.f / 255.f); + buf.z = (0xff & (src >> 16)) * (1.f / 255.f); + + HLS2RGBConvert(buf, &buf.x); + + uint dst = 0xffu << 24; + + dst |= saturate_cast(buf.x * 255.f); + dst |= saturate_cast(buf.y * 255.f) << 8; + dst |= saturate_cast(buf.z * 255.f) << 16; + + return dst; + } + + template struct HLS2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + HLS2RGBConvert(src, &dst.x); + setAlpha(dst, ColorChannel::max()); + + return dst; + } + __host__ __device__ __forceinline__ HLS2RGB() {} + __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} + }; + + template struct HLS2RGB : unary_function + { + __device__ __forceinline__ uint operator()(uint src) const + { + return HLS2RGBConvert(src); + } + __host__ __device__ __forceinline__ HLS2RGB() {} + __host__ __device__ __forceinline__ HLS2RGB(const HLS2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_HLS2RGB_TRAITS(name, scn, dcn, bidx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; \ + template <> struct name ## _full_traits \ + { \ + typedef ::cv::cuda::device::color_detail::HLS2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> Lab ///////////////////////////////////// + + namespace color_detail + { + enum + { + LAB_CBRT_TAB_SIZE = 1024, + GAMMA_TAB_SIZE = 1024, + lab_shift = xyz_shift, + gamma_shift = 3, + lab_shift2 = (lab_shift + gamma_shift), + LAB_CBRT_TAB_SIZE_B = (256 * 3 / 2 * (1 << gamma_shift)) + }; + + __constant__ ushort c_sRGBGammaTab_b[] = {0,1,1,2,2,3,4,4,5,6,6,7,8,8,9,10,11,11,12,13,14,15,16,17,19,20,21,22,24,25,26,28,29,31,33,34,36,38,40,41,43,45,47,49,51,54,56,58,60,63,65,68,70,73,75,78,81,83,86,89,92,95,98,101,105,108,111,115,118,121,125,129,132,136,140,144,147,151,155,160,164,168,172,176,181,185,190,194,199,204,209,213,218,223,228,233,239,244,249,255,260,265,271,277,282,288,294,300,306,312,318,324,331,337,343,350,356,363,370,376,383,390,397,404,411,418,426,433,440,448,455,463,471,478,486,494,502,510,518,527,535,543,552,560,569,578,586,595,604,613,622,631,641,650,659,669,678,688,698,707,717,727,737,747,757,768,778,788,799,809,820,831,842,852,863,875,886,897,908,920,931,943,954,966,978,990,1002,1014,1026,1038,1050,1063,1075,1088,1101,1113,1126,1139,1152,1165,1178,1192,1205,1218,1232,1245,1259,1273,1287,1301,1315,1329,1343,1357,1372,1386,1401,1415,1430,1445,1460,1475,1490,1505,1521,1536,1551,1567,1583,1598,1614,1630,1646,1662,1678,1695,1711,1728,1744,1761,1778,1794,1811,1828,1846,1863,1880,1897,1915,1933,1950,1968,1986,2004,2022,2040}; + + __device__ __forceinline__ int LabCbrt_b(int i) + { + float x = i * (1.f / (255.f * (1 << gamma_shift))); + return (1 << lab_shift2) * (x < 0.008856f ? x * 7.787f + 0.13793103448275862f : ::cbrtf(x)); + } + + template + __device__ __forceinline__ void RGB2LabConvert_b(const T& src, D& dst) + { + const int Lscale = (116 * 255 + 50) / 100; + const int Lshift = -((16 * 255 * (1 << lab_shift2) + 50) / 100); + + int B = blueIdx == 0 ? src.x : src.z; + int G = src.y; + int R = blueIdx == 0 ? src.z : src.x; + + if (srgb) + { + B = c_sRGBGammaTab_b[B]; + G = c_sRGBGammaTab_b[G]; + R = c_sRGBGammaTab_b[R]; + } + else + { + B <<= 3; + G <<= 3; + R <<= 3; + } + + int fX = LabCbrt_b(CV_DESCALE(B * 778 + G * 1541 + R * 1777, lab_shift)); + int fY = LabCbrt_b(CV_DESCALE(B * 296 + G * 2929 + R * 871, lab_shift)); + int fZ = LabCbrt_b(CV_DESCALE(B * 3575 + G * 448 + R * 73, lab_shift)); + + int L = CV_DESCALE(Lscale * fY + Lshift, lab_shift2); + int a = CV_DESCALE(500 * (fX - fY) + 128 * (1 << lab_shift2), lab_shift2); + int b = CV_DESCALE(200 * (fY - fZ) + 128 * (1 << lab_shift2), lab_shift2); + + dst.x = saturate_cast(L); + dst.y = saturate_cast(a); + dst.z = saturate_cast(b); + } + + __device__ __forceinline__ float splineInterpolate(float x, const float* tab, int n) + { + int ix = ::min(::max(int(x), 0), n-1); + x -= ix; + tab += ix * 4; + return ((tab[3] * x + tab[2]) * x + tab[1]) * x + tab[0]; + } + + __constant__ float c_sRGBGammaTab[] = {0,7.55853e-05,0.,-7.51331e-13,7.55853e-05,7.55853e-05,-2.25399e-12,3.75665e-12,0.000151171,7.55853e-05,9.01597e-12,-6.99932e-12,0.000226756,7.55853e-05,-1.1982e-11,2.41277e-12,0.000302341,7.55853e-05,-4.74369e-12,1.19001e-11,0.000377927,7.55853e-05,3.09568e-11,-2.09095e-11,0.000453512,7.55853e-05,-3.17718e-11,1.35303e-11,0.000529097,7.55853e-05,8.81905e-12,-4.10782e-12,0.000604683,7.55853e-05,-3.50439e-12,2.90097e-12,0.000680268,7.55853e-05,5.19852e-12,-7.49607e-12,0.000755853,7.55853e-05,-1.72897e-11,2.70833e-11,0.000831439,7.55854e-05,6.39602e-11,-4.26295e-11,0.000907024,7.55854e-05,-6.39282e-11,2.70193e-11,0.000982609,7.55853e-05,1.71298e-11,-7.24017e-12,0.00105819,7.55853e-05,-4.59077e-12,1.94137e-12,0.00113378,7.55853e-05,1.23333e-12,-5.25291e-13,0.00120937,7.55853e-05,-3.42545e-13,1.59799e-13,0.00128495,7.55853e-05,1.36852e-13,-1.13904e-13,0.00136054,7.55853e-05,-2.04861e-13,2.95818e-13,0.00143612,7.55853e-05,6.82594e-13,-1.06937e-12,0.00151171,7.55853e-05,-2.52551e-12,3.98166e-12,0.00158729,7.55853e-05,9.41946e-12,-1.48573e-11,0.00166288,7.55853e-05,-3.51523e-11,5.54474e-11,0.00173846,7.55854e-05,1.3119e-10,-9.0517e-11,0.00181405,7.55854e-05,-1.40361e-10,7.37899e-11,0.00188963,7.55853e-05,8.10085e-11,-8.82272e-11,0.00196522,7.55852e-05,-1.83673e-10,1.62704e-10,0.0020408,7.55853e-05,3.04438e-10,-2.13341e-10,0.00211639,7.55853e-05,-3.35586e-10,2.25e-10,0.00219197,7.55853e-05,3.39414e-10,-2.20997e-10,0.00226756,7.55853e-05,-3.23576e-10,1.93326e-10,0.00234315,7.55853e-05,2.564e-10,-8.66446e-11,0.00241873,7.55855e-05,-3.53328e-12,-7.9578e-11,0.00249432,7.55853e-05,-2.42267e-10,1.72126e-10,0.0025699,7.55853e-05,2.74111e-10,-1.43265e-10,0.00264549,7.55854e-05,-1.55683e-10,-6.47292e-11,0.00272107,7.55849e-05,-3.4987e-10,8.67842e-10,0.00279666,7.55868e-05,2.25366e-09,-3.8723e-09,0.00287224,7.55797e-05,-9.36325e-09,1.5087e-08,0.00294783,7.56063e-05,3.58978e-08,-5.69415e-08,0.00302341,7.55072e-05,-1.34927e-07,2.13144e-07,0.003099,7.58768e-05,5.04507e-07,1.38713e-07,0.00317552,7.7302e-05,9.20646e-07,-1.55186e-07,0.00325359,7.86777e-05,4.55087e-07,4.26813e-08,0.00333276,7.97159e-05,5.83131e-07,-1.06495e-08,0.00341305,8.08502e-05,5.51182e-07,3.87467e-09,0.00349446,8.19642e-05,5.62806e-07,-1.92586e-10,0.00357698,8.30892e-05,5.62228e-07,1.0866e-09,0.00366063,8.4217e-05,5.65488e-07,5.02818e-10,0.00374542,8.53494e-05,5.66997e-07,8.60211e-10,0.00383133,8.6486e-05,5.69577e-07,7.13044e-10,0.00391839,8.76273e-05,5.71716e-07,4.78527e-10,0.00400659,8.87722e-05,5.73152e-07,1.09818e-09,0.00409594,8.99218e-05,5.76447e-07,2.50964e-10,0.00418644,9.10754e-05,5.772e-07,1.15762e-09,0.00427809,9.22333e-05,5.80672e-07,2.40865e-10,0.0043709,9.33954e-05,5.81395e-07,1.13854e-09,0.00446488,9.45616e-05,5.84811e-07,3.27267e-10,0.00456003,9.57322e-05,5.85792e-07,8.1197e-10,0.00465635,9.69062e-05,5.88228e-07,6.15823e-10,0.00475384,9.80845e-05,5.90076e-07,9.15747e-10,0.00485252,9.92674e-05,5.92823e-07,3.778e-10,0.00495238,0.000100454,5.93956e-07,8.32623e-10,0.00505343,0.000101645,5.96454e-07,4.82695e-10,0.00515567,0.000102839,5.97902e-07,9.61904e-10,0.00525911,0.000104038,6.00788e-07,3.26281e-10,0.00536375,0.00010524,6.01767e-07,9.926e-10,0.00546959,0.000106447,6.04745e-07,3.59933e-10,0.00557664,0.000107657,6.05824e-07,8.2728e-10,0.0056849,0.000108871,6.08306e-07,5.21898e-10,0.00579438,0.00011009,6.09872e-07,8.10492e-10,0.00590508,0.000111312,6.12303e-07,4.27046e-10,0.00601701,0.000112538,6.13585e-07,7.40878e-10,0.00613016,0.000113767,6.15807e-07,8.00469e-10,0.00624454,0.000115001,6.18209e-07,2.48178e-10,0.00636016,0.000116238,6.18953e-07,1.00073e-09,0.00647702,0.000117479,6.21955e-07,4.05654e-10,0.00659512,0.000118724,6.23172e-07,6.36192e-10,0.00671447,0.000119973,6.25081e-07,7.74927e-10,0.00683507,0.000121225,6.27406e-07,4.54975e-10,0.00695692,0.000122481,6.28771e-07,6.64841e-10,0.00708003,0.000123741,6.30765e-07,6.10972e-10,0.00720441,0.000125004,6.32598e-07,6.16543e-10,0.00733004,0.000126271,6.34448e-07,6.48204e-10,0.00745695,0.000127542,6.36392e-07,5.15835e-10,0.00758513,0.000128816,6.3794e-07,5.48103e-10,0.00771458,0.000130094,6.39584e-07,1.01706e-09,0.00784532,0.000131376,6.42635e-07,4.0283e-11,0.00797734,0.000132661,6.42756e-07,6.84471e-10,0.00811064,0.000133949,6.4481e-07,9.47144e-10,0.00824524,0.000135241,6.47651e-07,1.83472e-10,0.00838112,0.000136537,6.48201e-07,1.11296e-09,0.00851831,0.000137837,6.5154e-07,2.13163e-11,0.0086568,0.00013914,6.51604e-07,6.64462e-10,0.00879659,0.000140445,6.53598e-07,1.04613e-09,0.00893769,0.000141756,6.56736e-07,-1.92377e-10,0.0090801,0.000143069,6.56159e-07,1.58601e-09,0.00922383,0.000144386,6.60917e-07,-5.63754e-10,0.00936888,0.000145706,6.59226e-07,1.60033e-09,0.00951524,0.000147029,6.64027e-07,-2.49543e-10,0.00966294,0.000148356,6.63278e-07,1.26043e-09,0.00981196,0.000149687,6.67059e-07,-1.35572e-10,0.00996231,0.00015102,6.66653e-07,1.14458e-09,0.010114,0.000152357,6.70086e-07,2.13864e-10,0.010267,0.000153698,6.70728e-07,7.93856e-10,0.0104214,0.000155042,6.73109e-07,3.36077e-10,0.0105771,0.000156389,6.74118e-07,6.55765e-10,0.0107342,0.000157739,6.76085e-07,7.66211e-10,0.0108926,0.000159094,6.78384e-07,4.66116e-12,0.0110524,0.000160451,6.78398e-07,1.07775e-09,0.0112135,0.000161811,6.81631e-07,3.41023e-10,0.011376,0.000163175,6.82654e-07,3.5205e-10,0.0115398,0.000164541,6.8371e-07,1.04473e-09,0.0117051,0.000165912,6.86844e-07,1.25757e-10,0.0118717,0.000167286,6.87222e-07,3.14818e-10,0.0120396,0.000168661,6.88166e-07,1.40886e-09,0.012209,0.000170042,6.92393e-07,-3.62244e-10,0.0123797,0.000171425,6.91306e-07,9.71397e-10,0.0125518,0.000172811,6.9422e-07,2.02003e-10,0.0127253,0.0001742,6.94826e-07,1.01448e-09,0.0129002,0.000175593,6.97869e-07,3.96653e-10,0.0130765,0.00017699,6.99059e-07,1.92927e-10,0.0132542,0.000178388,6.99638e-07,6.94305e-10,0.0134333,0.00017979,7.01721e-07,7.55108e-10,0.0136138,0.000181195,7.03986e-07,1.05918e-11,0.0137957,0.000182603,7.04018e-07,1.06513e-09,0.013979,0.000184015,7.07214e-07,3.85512e-10,0.0141637,0.00018543,7.0837e-07,1.86769e-10,0.0143499,0.000186848,7.0893e-07,7.30116e-10,0.0145374,0.000188268,7.11121e-07,6.17983e-10,0.0147264,0.000189692,7.12975e-07,5.23282e-10,0.0149168,0.000191119,7.14545e-07,8.28398e-11,0.0151087,0.000192549,7.14793e-07,1.0081e-09,0.0153019,0.000193981,7.17817e-07,5.41244e-10,0.0154966,0.000195418,7.19441e-07,-3.7907e-10,0.0156928,0.000196856,7.18304e-07,1.90641e-09,0.0158903,0.000198298,7.24023e-07,-7.27387e-10,0.0160893,0.000199744,7.21841e-07,1.00317e-09,0.0162898,0.000201191,7.24851e-07,4.39949e-10,0.0164917,0.000202642,7.2617e-07,9.6234e-10,0.0166951,0.000204097,7.29057e-07,-5.64019e-10,0.0168999,0.000205554,7.27365e-07,1.29374e-09,0.0171062,0.000207012,7.31247e-07,9.77025e-10,0.017314,0.000208478,7.34178e-07,-1.47651e-09,0.0175232,0.000209942,7.29748e-07,3.06636e-09,0.0177338,0.00021141,7.38947e-07,-1.47573e-09,0.017946,0.000212884,7.3452e-07,9.7386e-10,0.0181596,0.000214356,7.37442e-07,1.30562e-09,0.0183747,0.000215835,7.41358e-07,-6.08376e-10,0.0185913,0.000217315,7.39533e-07,1.12785e-09,0.0188093,0.000218798,7.42917e-07,-1.77711e-10,0.0190289,0.000220283,7.42384e-07,1.44562e-09,0.0192499,0.000221772,7.46721e-07,-1.68825e-11,0.0194724,0.000223266,7.4667e-07,4.84533e-10,0.0196964,0.000224761,7.48124e-07,-5.85298e-11,0.0199219,0.000226257,7.47948e-07,1.61217e-09,0.0201489,0.000227757,7.52785e-07,-8.02136e-10,0.0203775,0.00022926,7.50378e-07,1.59637e-09,0.0206075,0.000230766,7.55167e-07,4.47168e-12,0.020839,0.000232276,7.55181e-07,2.48387e-10,0.021072,0.000233787,7.55926e-07,8.6474e-10,0.0213066,0.000235302,7.5852e-07,1.78299e-11,0.0215426,0.000236819,7.58573e-07,9.26567e-10,0.0217802,0.000238339,7.61353e-07,1.34529e-12,0.0220193,0.000239862,7.61357e-07,9.30659e-10,0.0222599,0.000241387,7.64149e-07,1.34529e-12,0.0225021,0.000242915,7.64153e-07,9.26567e-10,0.0227458,0.000244447,7.66933e-07,1.76215e-11,0.022991,0.00024598,7.66986e-07,8.65536e-10,0.0232377,0.000247517,7.69582e-07,2.45677e-10,0.023486,0.000249057,7.70319e-07,1.44193e-11,0.0237358,0.000250598,7.70363e-07,1.55918e-09,0.0239872,0.000252143,7.7504e-07,-6.63173e-10,0.0242401,0.000253691,7.73051e-07,1.09357e-09,0.0244946,0.000255241,7.76331e-07,1.41919e-11,0.0247506,0.000256793,7.76374e-07,7.12248e-10,0.0250082,0.000258348,7.78511e-07,8.62049e-10,0.0252673,0.000259908,7.81097e-07,-4.35061e-10,0.025528,0.000261469,7.79792e-07,8.7825e-10,0.0257902,0.000263031,7.82426e-07,6.47181e-10,0.0260541,0.000264598,7.84368e-07,2.58448e-10,0.0263194,0.000266167,7.85143e-07,1.81558e-10,0.0265864,0.000267738,7.85688e-07,8.78041e-10,0.0268549,0.000269312,7.88322e-07,3.15102e-11,0.027125,0.000270889,7.88417e-07,8.58525e-10,0.0273967,0.000272468,7.90992e-07,2.59812e-10,0.02767,0.000274051,7.91772e-07,-3.5224e-11,0.0279448,0.000275634,7.91666e-07,1.74377e-09,0.0282212,0.000277223,7.96897e-07,-1.35196e-09,0.0284992,0.000278813,7.92841e-07,1.80141e-09,0.0287788,0.000280404,7.98246e-07,-2.65629e-10,0.0290601,0.000281999,7.97449e-07,1.12374e-09,0.0293428,0.000283598,8.0082e-07,-5.04106e-10,0.0296272,0.000285198,7.99308e-07,8.92764e-10,0.0299132,0.000286799,8.01986e-07,6.58379e-10,0.0302008,0.000288405,8.03961e-07,1.98971e-10,0.0304901,0.000290014,8.04558e-07,4.08382e-10,0.0307809,0.000291624,8.05783e-07,3.01839e-11,0.0310733,0.000293236,8.05874e-07,1.33343e-09,0.0313673,0.000294851,8.09874e-07,2.2419e-10,0.031663,0.000296472,8.10547e-07,-3.67606e-10,0.0319603,0.000298092,8.09444e-07,1.24624e-09,0.0322592,0.000299714,8.13182e-07,-8.92025e-10,0.0325597,0.000301338,8.10506e-07,2.32183e-09,0.0328619,0.000302966,8.17472e-07,-9.44719e-10,0.0331657,0.000304598,8.14638e-07,1.45703e-09,0.0334711,0.000306232,8.19009e-07,-1.15805e-09,0.0337781,0.000307866,8.15535e-07,3.17507e-09,0.0340868,0.000309507,8.2506e-07,-4.09161e-09,0.0343971,0.000311145,8.12785e-07,5.74079e-09,0.0347091,0.000312788,8.30007e-07,-3.97034e-09,0.0350227,0.000314436,8.18096e-07,2.68985e-09,0.035338,0.00031608,8.26166e-07,6.61676e-10,0.0356549,0.000317734,8.28151e-07,-1.61123e-09,0.0359734,0.000319386,8.23317e-07,2.05786e-09,0.0362936,0.000321038,8.29491e-07,8.30388e-10,0.0366155,0.0003227,8.31982e-07,-1.65424e-09,0.036939,0.000324359,8.27019e-07,2.06129e-09,0.0372642,0.000326019,8.33203e-07,8.59719e-10,0.0375911,0.000327688,8.35782e-07,-1.77488e-09,0.0379196,0.000329354,8.30458e-07,2.51464e-09,0.0382498,0.000331023,8.38002e-07,-8.33135e-10,0.0385817,0.000332696,8.35502e-07,8.17825e-10,0.0389152,0.00033437,8.37956e-07,1.28718e-09,0.0392504,0.00033605,8.41817e-07,-2.2413e-09,0.0395873,0.000337727,8.35093e-07,3.95265e-09,0.0399258,0.000339409,8.46951e-07,-2.39332e-09,0.0402661,0.000341095,8.39771e-07,1.89533e-09,0.040608,0.000342781,8.45457e-07,-1.46271e-09,0.0409517,0.000344467,8.41069e-07,3.95554e-09,0.041297,0.000346161,8.52936e-07,-3.18369e-09,0.041644,0.000347857,8.43385e-07,1.32873e-09,0.0419927,0.000349548,8.47371e-07,1.59402e-09,0.0423431,0.000351248,8.52153e-07,-2.54336e-10,0.0426952,0.000352951,8.5139e-07,-5.76676e-10,0.043049,0.000354652,8.4966e-07,2.56114e-09,0.0434045,0.000356359,8.57343e-07,-2.21744e-09,0.0437617,0.000358067,8.50691e-07,2.58344e-09,0.0441206,0.000359776,8.58441e-07,-6.65826e-10,0.0444813,0.000361491,8.56444e-07,7.99218e-11,0.0448436,0.000363204,8.56684e-07,3.46063e-10,0.0452077,0.000364919,8.57722e-07,2.26116e-09,0.0455734,0.000366641,8.64505e-07,-1.94005e-09,0.045941,0.000368364,8.58685e-07,1.77384e-09,0.0463102,0.000370087,8.64007e-07,-1.43005e-09,0.0466811,0.000371811,8.59717e-07,3.94634e-09,0.0470538,0.000373542,8.71556e-07,-3.17946e-09,0.0474282,0.000375276,8.62017e-07,1.32104e-09,0.0478043,0.000377003,8.6598e-07,1.62045e-09,0.0481822,0.00037874,8.70842e-07,-3.52297e-10,0.0485618,0.000380481,8.69785e-07,-2.11211e-10,0.0489432,0.00038222,8.69151e-07,1.19716e-09,0.0493263,0.000383962,8.72743e-07,-8.52026e-10,0.0497111,0.000385705,8.70187e-07,2.21092e-09,0.0500977,0.000387452,8.76819e-07,-5.41339e-10,0.050486,0.000389204,8.75195e-07,-4.5361e-11,0.0508761,0.000390954,8.75059e-07,7.22669e-10,0.0512679,0.000392706,8.77227e-07,8.79936e-10,0.0516615,0.000394463,8.79867e-07,-5.17048e-10,0.0520568,0.000396222,8.78316e-07,1.18833e-09,0.0524539,0.000397982,8.81881e-07,-5.11022e-10,0.0528528,0.000399744,8.80348e-07,8.55683e-10,0.0532534,0.000401507,8.82915e-07,8.13562e-10,0.0536558,0.000403276,8.85356e-07,-3.84603e-10,0.05406,0.000405045,8.84202e-07,7.24962e-10,0.0544659,0.000406816,8.86377e-07,1.20986e-09,0.0548736,0.000408592,8.90006e-07,-1.83896e-09,0.0552831,0.000410367,8.84489e-07,2.42071e-09,0.0556944,0.000412143,8.91751e-07,-3.93413e-10,0.0561074,0.000413925,8.90571e-07,-8.46967e-10,0.0565222,0.000415704,8.8803e-07,3.78122e-09,0.0569388,0.000417491,8.99374e-07,-3.1021e-09,0.0573572,0.000419281,8.90068e-07,1.17658e-09,0.0577774,0.000421064,8.93597e-07,2.12117e-09,0.0581993,0.000422858,8.99961e-07,-2.21068e-09,0.0586231,0.000424651,8.93329e-07,2.9961e-09,0.0590486,0.000426447,9.02317e-07,-2.32311e-09,0.059476,0.000428244,8.95348e-07,2.57122e-09,0.0599051,0.000430043,9.03062e-07,-5.11098e-10,0.0603361,0.000431847,9.01528e-07,-5.27166e-10,0.0607688,0.000433649,8.99947e-07,2.61984e-09,0.0612034,0.000435457,9.07806e-07,-2.50141e-09,0.0616397,0.000437265,9.00302e-07,3.66045e-09,0.0620779,0.000439076,9.11283e-07,-4.68977e-09,0.0625179,0.000440885,8.97214e-07,7.64783e-09,0.0629597,0.000442702,9.20158e-07,-7.27499e-09,0.0634033,0.000444521,8.98333e-07,6.55113e-09,0.0638487,0.000446337,9.17986e-07,-4.02844e-09,0.0642959,0.000448161,9.05901e-07,2.11196e-09,0.064745,0.000449979,9.12236e-07,3.03125e-09,0.0651959,0.000451813,9.2133e-07,-6.78648e-09,0.0656486,0.000453635,9.00971e-07,9.21375e-09,0.0661032,0.000455464,9.28612e-07,-7.71684e-09,0.0665596,0.000457299,9.05462e-07,6.7522e-09,0.0670178,0.00045913,9.25718e-07,-4.3907e-09,0.0674778,0.000460968,9.12546e-07,3.36e-09,0.0679397,0.000462803,9.22626e-07,-1.59876e-09,0.0684034,0.000464644,9.1783e-07,3.0351e-09,0.068869,0.000466488,9.26935e-07,-3.09101e-09,0.0693364,0.000468333,9.17662e-07,1.8785e-09,0.0698057,0.000470174,9.23298e-07,3.02733e-09,0.0702768,0.00047203,9.3238e-07,-6.53722e-09,0.0707497,0.000473875,9.12768e-07,8.22054e-09,0.0712245,0.000475725,9.37429e-07,-3.99325e-09,0.0717012,0.000477588,9.2545e-07,3.01839e-10,0.0721797,0.00047944,9.26355e-07,2.78597e-09,0.0726601,0.000481301,9.34713e-07,-3.99507e-09,0.0731423,0.000483158,9.22728e-07,5.7435e-09,0.0736264,0.000485021,9.39958e-07,-4.07776e-09,0.0741123,0.000486888,9.27725e-07,3.11695e-09,0.0746002,0.000488753,9.37076e-07,-9.39394e-10,0.0750898,0.000490625,9.34258e-07,6.4055e-10,0.0755814,0.000492495,9.3618e-07,-1.62265e-09,0.0760748,0.000494363,9.31312e-07,5.84995e-09,0.0765701,0.000496243,9.48861e-07,-6.87601e-09,0.0770673,0.00049812,9.28233e-07,6.75296e-09,0.0775664,0.000499997,9.48492e-07,-5.23467e-09,0.0780673,0.000501878,9.32788e-07,6.73523e-09,0.0785701,0.000503764,9.52994e-07,-6.80514e-09,0.0790748,0.000505649,9.32578e-07,5.5842e-09,0.0795814,0.000507531,9.49331e-07,-6.30583e-10,0.0800899,0.000509428,9.47439e-07,-3.0618e-09,0.0806003,0.000511314,9.38254e-07,5.4273e-09,0.0811125,0.000513206,9.54536e-07,-3.74627e-09,0.0816267,0.000515104,9.43297e-07,2.10713e-09,0.0821427,0.000516997,9.49618e-07,2.76839e-09,0.0826607,0.000518905,9.57924e-07,-5.73006e-09,0.0831805,0.000520803,9.40733e-07,5.25072e-09,0.0837023,0.0005227,9.56486e-07,-3.71718e-10,0.084226,0.000524612,9.5537e-07,-3.76404e-09,0.0847515,0.000526512,9.44078e-07,7.97735e-09,0.085279,0.000528424,9.6801e-07,-5.79367e-09,0.0858084,0.000530343,9.50629e-07,2.96268e-10,0.0863397,0.000532245,9.51518e-07,4.6086e-09,0.0868729,0.000534162,9.65344e-07,-3.82947e-09,0.087408,0.000536081,9.53856e-07,3.25861e-09,0.087945,0.000537998,9.63631e-07,-1.7543e-09,0.088484,0.00053992,9.58368e-07,3.75849e-09,0.0890249,0.000541848,9.69644e-07,-5.82891e-09,0.0895677,0.00054377,9.52157e-07,4.65593e-09,0.0901124,0.000545688,9.66125e-07,2.10643e-09,0.0906591,0.000547627,9.72444e-07,-5.63099e-09,0.0912077,0.000549555,9.55551e-07,5.51627e-09,0.0917582,0.000551483,9.721e-07,-1.53292e-09,0.0923106,0.000553422,9.67501e-07,6.15311e-10,0.092865,0.000555359,9.69347e-07,-9.28291e-10,0.0934213,0.000557295,9.66562e-07,3.09774e-09,0.0939796,0.000559237,9.75856e-07,-4.01186e-09,0.0945398,0.000561177,9.6382e-07,5.49892e-09,0.095102,0.000563121,9.80317e-07,-3.08258e-09,0.0956661,0.000565073,9.71069e-07,-6.19176e-10,0.0962321,0.000567013,9.69212e-07,5.55932e-09,0.0968001,0.000568968,9.8589e-07,-6.71704e-09,0.09737,0.00057092,9.65738e-07,6.40762e-09,0.0979419,0.00057287,9.84961e-07,-4.0122e-09,0.0985158,0.000574828,9.72925e-07,2.19059e-09,0.0990916,0.000576781,9.79496e-07,2.70048e-09,0.0996693,0.000578748,9.87598e-07,-5.54193e-09,0.100249,0.000580706,9.70972e-07,4.56597e-09,0.100831,0.000582662,9.8467e-07,2.17923e-09,0.101414,0.000584638,9.91208e-07,-5.83232e-09,0.102,0.000586603,9.73711e-07,6.24884e-09,0.102588,0.000588569,9.92457e-07,-4.26178e-09,0.103177,0.000590541,9.79672e-07,3.34781e-09,0.103769,0.00059251,9.89715e-07,-1.67904e-09,0.104362,0.000594485,9.84678e-07,3.36839e-09,0.104958,0.000596464,9.94783e-07,-4.34397e-09,0.105555,0.000598441,9.81751e-07,6.55696e-09,0.106155,0.000600424,1.00142e-06,-6.98272e-09,0.106756,0.000602406,9.80474e-07,6.4728e-09,0.107359,0.000604386,9.99893e-07,-4.00742e-09,0.107965,0.000606374,9.8787e-07,2.10654e-09,0.108572,0.000608356,9.9419e-07,3.0318e-09,0.109181,0.000610353,1.00329e-06,-6.7832e-09,0.109793,0.00061234,9.82936e-07,9.1998e-09,0.110406,0.000614333,1.01054e-06,-7.6642e-09,0.111021,0.000616331,9.87543e-07,6.55579e-09,0.111639,0.000618326,1.00721e-06,-3.65791e-09,0.112258,0.000620329,9.96236e-07,6.25467e-10,0.112879,0.000622324,9.98113e-07,1.15593e-09,0.113503,0.000624323,1.00158e-06,2.20158e-09,0.114128,0.000626333,1.00819e-06,-2.51191e-09,0.114755,0.000628342,1.00065e-06,3.95517e-10,0.115385,0.000630345,1.00184e-06,9.29807e-10,0.116016,0.000632351,1.00463e-06,3.33599e-09,0.116649,0.00063437,1.01463e-06,-6.82329e-09,0.117285,0.000636379,9.94163e-07,9.05595e-09,0.117922,0.000638395,1.02133e-06,-7.04862e-09,0.118562,0.000640416,1.00019e-06,4.23737e-09,0.119203,0.000642429,1.0129e-06,-2.45033e-09,0.119847,0.000644448,1.00555e-06,5.56395e-09,0.120492,0.000646475,1.02224e-06,-4.9043e-09,0.121139,0.000648505,1.00753e-06,-8.47952e-10,0.121789,0.000650518,1.00498e-06,8.29622e-09,0.122441,0.000652553,1.02987e-06,-9.98538e-09,0.123094,0.000654582,9.99914e-07,9.2936e-09,0.12375,0.00065661,1.02779e-06,-4.83707e-09,0.124407,0.000658651,1.01328e-06,2.60411e-09,0.125067,0.000660685,1.0211e-06,-5.57945e-09,0.125729,0.000662711,1.00436e-06,1.22631e-08,0.126392,0.000664756,1.04115e-06,-1.36704e-08,0.127058,0.000666798,1.00014e-06,1.26161e-08,0.127726,0.000668836,1.03798e-06,-6.99155e-09,0.128396,0.000670891,1.01701e-06,4.48836e-10,0.129068,0.000672926,1.01836e-06,5.19606e-09,0.129742,0.000674978,1.03394e-06,-6.3319e-09,0.130418,0.000677027,1.01495e-06,5.2305e-09,0.131096,0.000679073,1.03064e-06,3.11123e-10,0.131776,0.000681135,1.03157e-06,-6.47511e-09,0.132458,0.000683179,1.01215e-06,1.06882e-08,0.133142,0.000685235,1.04421e-06,-6.47519e-09,0.133829,0.000687304,1.02479e-06,3.11237e-10,0.134517,0.000689355,1.02572e-06,5.23035e-09,0.135207,0.000691422,1.04141e-06,-6.3316e-09,0.1359,0.000693486,1.02242e-06,5.19484e-09,0.136594,0.000695546,1.038e-06,4.53497e-10,0.137291,0.000697623,1.03936e-06,-7.00891e-09,0.137989,0.000699681,1.01834e-06,1.2681e-08,0.13869,0.000701756,1.05638e-06,-1.39128e-08,0.139393,0.000703827,1.01464e-06,1.31679e-08,0.140098,0.000705896,1.05414e-06,-8.95659e-09,0.140805,0.000707977,1.02727e-06,7.75742e-09,0.141514,0.000710055,1.05055e-06,-7.17182e-09,0.142225,0.000712135,1.02903e-06,6.02862e-09,0.142938,0.000714211,1.04712e-06,-2.04163e-09,0.143653,0.000716299,1.04099e-06,2.13792e-09,0.144371,0.000718387,1.04741e-06,-6.51009e-09,0.14509,0.000720462,1.02787e-06,9.00123e-09,0.145812,0.000722545,1.05488e-06,3.07523e-10,0.146535,0.000724656,1.0558e-06,-1.02312e-08,0.147261,0.000726737,1.02511e-06,1.0815e-08,0.147989,0.000728819,1.05755e-06,-3.22681e-09,0.148719,0.000730925,1.04787e-06,2.09244e-09,0.14945,0.000733027,1.05415e-06,-5.143e-09,0.150185,0.00073512,1.03872e-06,3.57844e-09,0.150921,0.000737208,1.04946e-06,5.73027e-09,0.151659,0.000739324,1.06665e-06,-1.15983e-08,0.152399,0.000741423,1.03185e-06,1.08605e-08,0.153142,0.000743519,1.06443e-06,-2.04106e-09,0.153886,0.000745642,1.05831e-06,-2.69642e-09,0.154633,0.00074775,1.05022e-06,-2.07425e-09,0.155382,0.000749844,1.044e-06,1.09934e-08,0.156133,0.000751965,1.07698e-06,-1.20972e-08,0.156886,0.000754083,1.04069e-06,7.59288e-09,0.157641,0.000756187,1.06347e-06,-3.37305e-09,0.158398,0.000758304,1.05335e-06,5.89921e-09,0.159158,0.000760428,1.07104e-06,-5.32248e-09,0.159919,0.000762554,1.05508e-06,4.8927e-10,0.160683,0.000764666,1.05654e-06,3.36547e-09,0.161448,0.000766789,1.06664e-06,9.50081e-10,0.162216,0.000768925,1.06949e-06,-7.16568e-09,0.162986,0.000771043,1.04799e-06,1.28114e-08,0.163758,0.000773177,1.08643e-06,-1.42774e-08,0.164533,0.000775307,1.0436e-06,1.44956e-08,0.165309,0.000777438,1.08708e-06,-1.39025e-08,0.166087,0.00077957,1.04538e-06,1.13118e-08,0.166868,0.000781695,1.07931e-06,-1.54224e-09,0.167651,0.000783849,1.07468e-06,-5.14312e-09,0.168436,0.000785983,1.05925e-06,7.21381e-09,0.169223,0.000788123,1.0809e-06,-8.81096e-09,0.170012,0.000790259,1.05446e-06,1.31289e-08,0.170803,0.000792407,1.09385e-06,-1.39022e-08,0.171597,0.000794553,1.05214e-06,1.26775e-08,0.172392,0.000796695,1.09018e-06,-7.00557e-09,0.17319,0.000798855,1.06916e-06,4.43796e-10,0.17399,0.000800994,1.07049e-06,5.23031e-09,0.174792,0.000803151,1.08618e-06,-6.46397e-09,0.175596,0.000805304,1.06679e-06,5.72444e-09,0.176403,0.000807455,1.08396e-06,-1.53254e-09,0.177211,0.000809618,1.07937e-06,4.05673e-10,0.178022,0.000811778,1.08058e-06,-9.01916e-11,0.178835,0.000813939,1.08031e-06,-4.49821e-11,0.17965,0.000816099,1.08018e-06,2.70234e-10,0.180467,0.00081826,1.08099e-06,-1.03603e-09,0.181286,0.000820419,1.07788e-06,3.87392e-09,0.182108,0.000822587,1.0895e-06,4.41522e-10,0.182932,0.000824767,1.09083e-06,-5.63997e-09,0.183758,0.000826932,1.07391e-06,7.21707e-09,0.184586,0.000829101,1.09556e-06,-8.32718e-09,0.185416,0.000831267,1.07058e-06,1.11907e-08,0.186248,0.000833442,1.10415e-06,-6.63336e-09,0.187083,0.00083563,1.08425e-06,4.41484e-10,0.187919,0.0008378,1.08557e-06,4.86754e-09,0.188758,0.000839986,1.10017e-06,-5.01041e-09,0.189599,0.000842171,1.08514e-06,2.72811e-10,0.190443,0.000844342,1.08596e-06,3.91916e-09,0.191288,0.000846526,1.09772e-06,-1.04819e-09,0.192136,0.000848718,1.09457e-06,2.73531e-10,0.192985,0.000850908,1.0954e-06,-4.58916e-11,0.193837,0.000853099,1.09526e-06,-9.01158e-11,0.194692,0.000855289,1.09499e-06,4.06506e-10,0.195548,0.00085748,1.09621e-06,-1.53595e-09,0.196407,0.000859668,1.0916e-06,5.73717e-09,0.197267,0.000861869,1.10881e-06,-6.51164e-09,0.19813,0.000864067,1.08928e-06,5.40831e-09,0.198995,0.000866261,1.1055e-06,-2.20401e-10,0.199863,0.000868472,1.10484e-06,-4.52652e-09,0.200732,0.000870668,1.09126e-06,3.42508e-09,0.201604,0.000872861,1.10153e-06,5.72762e-09,0.202478,0.000875081,1.11872e-06,-1.14344e-08,0.203354,0.000877284,1.08441e-06,1.02076e-08,0.204233,0.000879484,1.11504e-06,4.06355e-10,0.205113,0.000881715,1.11626e-06,-1.18329e-08,0.205996,0.000883912,1.08076e-06,1.71227e-08,0.206881,0.000886125,1.13213e-06,-1.19546e-08,0.207768,0.000888353,1.09626e-06,8.93465e-10,0.208658,0.000890548,1.09894e-06,8.38062e-09,0.209549,0.000892771,1.12408e-06,-4.61353e-09,0.210443,0.000895006,1.11024e-06,-4.82756e-09,0.211339,0.000897212,1.09576e-06,9.02245e-09,0.212238,0.00089943,1.12283e-06,-1.45997e-09,0.213138,0.000901672,1.11845e-06,-3.18255e-09,0.214041,0.000903899,1.1089e-06,-7.11073e-10,0.214946,0.000906115,1.10677e-06,6.02692e-09,0.215853,0.000908346,1.12485e-06,-8.49548e-09,0.216763,0.00091057,1.09936e-06,1.30537e-08,0.217675,0.000912808,1.13852e-06,-1.3917e-08,0.218588,0.000915044,1.09677e-06,1.28121e-08,0.219505,0.000917276,1.13521e-06,-7.5288e-09,0.220423,0.000919523,1.11262e-06,2.40205e-09,0.221344,0.000921756,1.11983e-06,-2.07941e-09,0.222267,0.000923989,1.11359e-06,5.91551e-09,0.223192,0.000926234,1.13134e-06,-6.68149e-09,0.224119,0.000928477,1.11129e-06,5.90929e-09,0.225049,0.000930717,1.12902e-06,-2.05436e-09,0.22598,0.000932969,1.12286e-06,2.30807e-09,0.226915,0.000935222,1.12978e-06,-7.17796e-09,0.227851,0.00093746,1.10825e-06,1.15028e-08,0.228789,0.000939711,1.14276e-06,-9.03083e-09,0.22973,0.000941969,1.11566e-06,9.71932e-09,0.230673,0.00094423,1.14482e-06,-1.49452e-08,0.231619,0.000946474,1.09998e-06,2.02591e-08,0.232566,0.000948735,1.16076e-06,-2.13879e-08,0.233516,0.000950993,1.0966e-06,2.05888e-08,0.234468,0.000953247,1.15837e-06,-1.62642e-08,0.235423,0.000955515,1.10957e-06,1.46658e-08,0.236379,0.000957779,1.15357e-06,-1.25966e-08,0.237338,0.000960048,1.11578e-06,5.91793e-09,0.238299,0.000962297,1.13353e-06,3.82602e-09,0.239263,0.000964576,1.14501e-06,-6.3208e-09,0.240229,0.000966847,1.12605e-06,6.55613e-09,0.241197,0.000969119,1.14572e-06,-5.00268e-09,0.242167,0.000971395,1.13071e-06,-1.44659e-09,0.243139,0.000973652,1.12637e-06,1.07891e-08,0.244114,0.000975937,1.15874e-06,-1.19073e-08,0.245091,0.000978219,1.12302e-06,7.03782e-09,0.246071,0.000980486,1.14413e-06,-1.34276e-09,0.247052,0.00098277,1.1401e-06,-1.66669e-09,0.248036,0.000985046,1.1351e-06,8.00935e-09,0.249022,0.00098734,1.15913e-06,-1.54694e-08,0.250011,0.000989612,1.11272e-06,2.4066e-08,0.251002,0.000991909,1.18492e-06,-2.11901e-08,0.251995,0.000994215,1.12135e-06,1.08973e-09,0.25299,0.000996461,1.12462e-06,1.68311e-08,0.253988,0.000998761,1.17511e-06,-8.8094e-09,0.254987,0.00100109,1.14868e-06,-1.13958e-08,0.25599,0.00100335,1.1145e-06,2.45902e-08,0.256994,0.00100565,1.18827e-06,-2.73603e-08,0.258001,0.00100795,1.10618e-06,2.52464e-08,0.25901,0.00101023,1.18192e-06,-1.40207e-08,0.260021,0.00101256,1.13986e-06,1.03387e-09,0.261035,0.00101484,1.14296e-06,9.8853e-09,0.262051,0.00101715,1.17262e-06,-1.07726e-08,0.263069,0.00101947,1.1403e-06,3.40272e-09,0.26409,0.00102176,1.15051e-06,-2.83827e-09,0.265113,0.00102405,1.142e-06,7.95039e-09,0.266138,0.00102636,1.16585e-06,8.39047e-10,0.267166,0.00102869,1.16836e-06,-1.13066e-08,0.268196,0.00103099,1.13444e-06,1.4585e-08,0.269228,0.00103331,1.1782e-06,-1.72314e-08,0.270262,0.00103561,1.1265e-06,2.45382e-08,0.271299,0.00103794,1.20012e-06,-2.13166e-08,0.272338,0.00104028,1.13617e-06,1.12364e-09,0.273379,0.00104255,1.13954e-06,1.68221e-08,0.274423,0.00104488,1.19001e-06,-8.80736e-09,0.275469,0.00104723,1.16358e-06,-1.13948e-08,0.276518,0.00104953,1.1294e-06,2.45839e-08,0.277568,0.00105186,1.20315e-06,-2.73361e-08,0.278621,0.00105418,1.12114e-06,2.51559e-08,0.279677,0.0010565,1.19661e-06,-1.36832e-08,0.280734,0.00105885,1.15556e-06,-2.25706e-10,0.281794,0.00106116,1.15488e-06,1.45862e-08,0.282857,0.00106352,1.19864e-06,-2.83167e-08,0.283921,0.00106583,1.11369e-06,3.90759e-08,0.284988,0.00106817,1.23092e-06,-3.85801e-08,0.286058,0.00107052,1.11518e-06,2.58375e-08,0.287129,0.00107283,1.19269e-06,-5.16498e-09,0.288203,0.0010752,1.1772e-06,-5.17768e-09,0.28928,0.00107754,1.16167e-06,-3.92671e-09,0.290358,0.00107985,1.14988e-06,2.08846e-08,0.29144,0.00108221,1.21254e-06,-2.00072e-08,0.292523,0.00108458,1.15252e-06,-4.60659e-10,0.293609,0.00108688,1.15114e-06,2.18499e-08,0.294697,0.00108925,1.21669e-06,-2.73343e-08,0.295787,0.0010916,1.13468e-06,2.78826e-08,0.29688,0.00109395,1.21833e-06,-2.45915e-08,0.297975,0.00109632,1.14456e-06,1.08787e-08,0.299073,0.00109864,1.17719e-06,1.08788e-08,0.300172,0.00110102,1.20983e-06,-2.45915e-08,0.301275,0.00110337,1.13605e-06,2.78828e-08,0.302379,0.00110573,1.2197e-06,-2.73348e-08,0.303486,0.00110808,1.1377e-06,2.18518e-08,0.304595,0.00111042,1.20325e-06,-4.67556e-10,0.305707,0.00111283,1.20185e-06,-1.99816e-08,0.306821,0.00111517,1.14191e-06,2.07891e-08,0.307937,0.00111752,1.20427e-06,-3.57026e-09,0.309056,0.00111992,1.19356e-06,-6.50797e-09,0.310177,0.00112228,1.17404e-06,-2.00165e-10,0.3113,0.00112463,1.17344e-06,7.30874e-09,0.312426,0.001127,1.19536e-06,7.67424e-10,0.313554,0.00112939,1.19767e-06,-1.03784e-08,0.314685,0.00113176,1.16653e-06,1.09437e-08,0.315818,0.00113412,1.19936e-06,-3.59406e-09,0.316953,0.00113651,1.18858e-06,3.43251e-09,0.318091,0.0011389,1.19888e-06,-1.0136e-08,0.319231,0.00114127,1.16847e-06,7.30915e-09,0.320374,0.00114363,1.1904e-06,1.07018e-08,0.321518,0.00114604,1.2225e-06,-2.03137e-08,0.322666,0.00114842,1.16156e-06,1.09484e-08,0.323815,0.00115078,1.19441e-06,6.32224e-09,0.324967,0.00115319,1.21337e-06,-6.43509e-09,0.326122,0.00115559,1.19407e-06,-1.03842e-08,0.327278,0.00115795,1.16291e-06,1.81697e-08,0.328438,0.00116033,1.21742e-06,-2.6901e-09,0.329599,0.00116276,1.20935e-06,-7.40939e-09,0.330763,0.00116515,1.18713e-06,2.52533e-09,0.331929,0.00116754,1.1947e-06,-2.69191e-09,0.333098,0.00116992,1.18663e-06,8.24218e-09,0.334269,0.00117232,1.21135e-06,-4.74377e-10,0.335443,0.00117474,1.20993e-06,-6.34471e-09,0.336619,0.00117714,1.1909e-06,-3.94922e-09,0.337797,0.00117951,1.17905e-06,2.21417e-08,0.338978,0.00118193,1.24547e-06,-2.50128e-08,0.340161,0.00118435,1.17043e-06,1.8305e-08,0.341346,0.00118674,1.22535e-06,-1.84048e-08,0.342534,0.00118914,1.17013e-06,2.55121e-08,0.343725,0.00119156,1.24667e-06,-2.40389e-08,0.344917,0.00119398,1.17455e-06,1.10389e-08,0.346113,0.00119636,1.20767e-06,9.68574e-09,0.34731,0.0011988,1.23673e-06,-1.99797e-08,0.34851,0.00120122,1.17679e-06,1.06284e-08,0.349713,0.0012036,1.20867e-06,7.26868e-09,0.350917,0.00120604,1.23048e-06,-9.90072e-09,0.352125,0.00120847,1.20078e-06,2.53177e-09,0.353334,0.00121088,1.20837e-06,-2.26199e-10,0.354546,0.0012133,1.20769e-06,-1.62705e-09,0.355761,0.00121571,1.20281e-06,6.73435e-09,0.356978,0.00121813,1.22302e-06,4.49207e-09,0.358197,0.00122059,1.23649e-06,-2.47027e-08,0.359419,0.00122299,1.16238e-06,3.47142e-08,0.360643,0.00122542,1.26653e-06,-2.47472e-08,0.36187,0.00122788,1.19229e-06,4.66965e-09,0.363099,0.00123028,1.20629e-06,6.06872e-09,0.36433,0.00123271,1.2245e-06,8.57729e-10,0.365564,0.00123516,1.22707e-06,-9.49952e-09,0.366801,0.00123759,1.19858e-06,7.33792e-09,0.36804,0.00124001,1.22059e-06,9.95025e-09,0.369281,0.00124248,1.25044e-06,-1.73366e-08,0.370525,0.00124493,1.19843e-06,-2.08464e-10,0.371771,0.00124732,1.1978e-06,1.81704e-08,0.373019,0.00124977,1.25232e-06,-1.28683e-08,0.37427,0.00125224,1.21371e-06,3.50042e-09,0.375524,0.00125468,1.22421e-06,-1.1335e-09,0.37678,0.00125712,1.22081e-06,1.03345e-09,0.378038,0.00125957,1.22391e-06,-3.00023e-09,0.379299,0.00126201,1.21491e-06,1.09676e-08,0.380562,0.00126447,1.24781e-06,-1.10676e-08,0.381828,0.00126693,1.21461e-06,3.50042e-09,0.383096,0.00126937,1.22511e-06,-2.93403e-09,0.384366,0.00127181,1.21631e-06,8.23574e-09,0.385639,0.00127427,1.24102e-06,-2.06607e-10,0.386915,0.00127675,1.2404e-06,-7.40935e-09,0.388193,0.00127921,1.21817e-06,4.1761e-11,0.389473,0.00128165,1.21829e-06,7.24223e-09,0.390756,0.0012841,1.24002e-06,7.91564e-10,0.392042,0.00128659,1.2424e-06,-1.04086e-08,0.393329,0.00128904,1.21117e-06,1.10405e-08,0.39462,0.0012915,1.24429e-06,-3.951e-09,0.395912,0.00129397,1.23244e-06,4.7634e-09,0.397208,0.00129645,1.24673e-06,-1.51025e-08,0.398505,0.0012989,1.20142e-06,2.58443e-08,0.399805,0.00130138,1.27895e-06,-2.86702e-08,0.401108,0.00130385,1.19294e-06,2.92318e-08,0.402413,0.00130632,1.28064e-06,-2.86524e-08,0.403721,0.0013088,1.19468e-06,2.57731e-08,0.405031,0.00131127,1.272e-06,-1.48355e-08,0.406343,0.00131377,1.2275e-06,3.76652e-09,0.407658,0.00131623,1.23879e-06,-2.30784e-10,0.408976,0.00131871,1.2381e-06,-2.84331e-09,0.410296,0.00132118,1.22957e-06,1.16041e-08,0.411618,0.00132367,1.26438e-06,-1.37708e-08,0.412943,0.00132616,1.22307e-06,1.36768e-08,0.41427,0.00132865,1.2641e-06,-1.1134e-08,0.4156,0.00133114,1.2307e-06,1.05714e-09,0.416933,0.00133361,1.23387e-06,6.90538e-09,0.418267,0.00133609,1.25459e-06,1.12372e-09,0.419605,0.00133861,1.25796e-06,-1.14002e-08,0.420945,0.00134109,1.22376e-06,1.46747e-08,0.422287,0.00134358,1.26778e-06,-1.7496e-08,0.423632,0.00134606,1.21529e-06,2.5507e-08,0.424979,0.00134857,1.29182e-06,-2.49272e-08,0.426329,0.00135108,1.21703e-06,1.45972e-08,0.427681,0.00135356,1.26083e-06,-3.65935e-09,0.429036,0.00135607,1.24985e-06,4.00178e-11,0.430393,0.00135857,1.24997e-06,3.49917e-09,0.431753,0.00136108,1.26047e-06,-1.40366e-08,0.433116,0.00136356,1.21836e-06,2.28448e-08,0.43448,0.00136606,1.28689e-06,-1.77378e-08,0.435848,0.00136858,1.23368e-06,1.83043e-08,0.437218,0.0013711,1.28859e-06,-2.56769e-08,0.43859,0.0013736,1.21156e-06,2.47987e-08,0.439965,0.0013761,1.28595e-06,-1.39133e-08,0.441342,0.00137863,1.24421e-06,1.05202e-09,0.442722,0.00138112,1.24737e-06,9.70507e-09,0.444104,0.00138365,1.27649e-06,-1.00698e-08,0.445489,0.00138617,1.24628e-06,7.72123e-10,0.446877,0.00138867,1.24859e-06,6.98132e-09,0.448267,0.00139118,1.26954e-06,1.10477e-09,0.449659,0.00139373,1.27285e-06,-1.14003e-08,0.451054,0.00139624,1.23865e-06,1.4694e-08,0.452452,0.00139876,1.28273e-06,-1.75734e-08,0.453852,0.00140127,1.23001e-06,2.5797e-08,0.455254,0.00140381,1.3074e-06,-2.60097e-08,0.456659,0.00140635,1.22937e-06,1.86371e-08,0.458067,0.00140886,1.28529e-06,-1.8736e-08,0.459477,0.00141137,1.22908e-06,2.65048e-08,0.46089,0.00141391,1.30859e-06,-2.76784e-08,0.462305,0.00141645,1.22556e-06,2.46043e-08,0.463722,0.00141897,1.29937e-06,-1.11341e-08,0.465143,0.00142154,1.26597e-06,-9.87033e-09,0.466565,0.00142404,1.23636e-06,2.08131e-08,0.467991,0.00142657,1.2988e-06,-1.37773e-08,0.469419,0.00142913,1.25746e-06,4.49378e-09,0.470849,0.00143166,1.27094e-06,-4.19781e-09,0.472282,0.00143419,1.25835e-06,1.22975e-08,0.473717,0.00143674,1.29524e-06,-1.51902e-08,0.475155,0.00143929,1.24967e-06,1.86608e-08,0.476596,0.00144184,1.30566e-06,-2.96506e-08,0.478039,0.00144436,1.2167e-06,4.03368e-08,0.479485,0.00144692,1.33771e-06,-4.22896e-08,0.480933,0.00144947,1.21085e-06,3.94148e-08,0.482384,0.00145201,1.32909e-06,-2.59626e-08,0.483837,0.00145459,1.2512e-06,4.83124e-09,0.485293,0.0014571,1.2657e-06,6.63757e-09,0.486751,0.00145966,1.28561e-06,-1.57911e-09,0.488212,0.00146222,1.28087e-06,-3.21468e-10,0.489676,0.00146478,1.27991e-06,2.86517e-09,0.491142,0.00146735,1.2885e-06,-1.11392e-08,0.49261,0.00146989,1.25508e-06,1.18893e-08,0.494081,0.00147244,1.29075e-06,-6.61574e-09,0.495555,0.001475,1.27091e-06,1.45736e-08,0.497031,0.00147759,1.31463e-06,-2.18759e-08,0.49851,0.00148015,1.249e-06,1.33252e-08,0.499992,0.00148269,1.28897e-06,-1.62277e-09,0.501476,0.00148526,1.28411e-06,-6.83421e-09,0.502962,0.00148781,1.2636e-06,2.89596e-08,0.504451,0.00149042,1.35048e-06,-4.93997e-08,0.505943,0.00149298,1.20228e-06,4.94299e-08,0.507437,0.00149553,1.35057e-06,-2.91107e-08,0.508934,0.00149814,1.26324e-06,7.40848e-09,0.510434,0.00150069,1.28547e-06,-5.23187e-10,0.511936,0.00150326,1.2839e-06,-5.31585e-09,0.51344,0.00150581,1.26795e-06,2.17866e-08,0.514947,0.00150841,1.33331e-06,-2.22257e-08,0.516457,0.00151101,1.26663e-06,7.51178e-09,0.517969,0.00151357,1.28917e-06,-7.82128e-09,0.519484,0.00151613,1.2657e-06,2.37733e-08,0.521002,0.00151873,1.33702e-06,-2.76674e-08,0.522522,0.00152132,1.25402e-06,2.72917e-08,0.524044,0.00152391,1.3359e-06,-2.18949e-08,0.525569,0.00152652,1.27021e-06,6.83372e-10,0.527097,0.00152906,1.27226e-06,1.91613e-08,0.528628,0.00153166,1.32974e-06,-1.77241e-08,0.53016,0.00153427,1.27657e-06,-7.86963e-09,0.531696,0.0015368,1.25296e-06,4.92027e-08,0.533234,0.00153945,1.40057e-06,-6.9732e-08,0.534775,0.00154204,1.19138e-06,5.09114e-08,0.536318,0.00154458,1.34411e-06,-1.4704e-08,0.537864,0.00154722,1.3e-06,7.9048e-09,0.539413,0.00154984,1.32371e-06,-1.69152e-08,0.540964,0.00155244,1.27297e-06,1.51355e-10,0.542517,0.00155499,1.27342e-06,1.63099e-08,0.544074,0.00155758,1.32235e-06,-5.78647e-09,0.545633,0.00156021,1.30499e-06,6.83599e-09,0.547194,0.00156284,1.3255e-06,-2.15575e-08,0.548758,0.00156543,1.26083e-06,1.97892e-08,0.550325,0.00156801,1.32019e-06,2.00525e-09,0.551894,0.00157065,1.32621e-06,-2.78103e-08,0.553466,0.00157322,1.24278e-06,4.96314e-08,0.555041,0.00157586,1.39167e-06,-5.1506e-08,0.556618,0.00157849,1.23716e-06,3.71835e-08,0.558198,0.00158107,1.34871e-06,-3.76233e-08,0.55978,0.00158366,1.23584e-06,5.37052e-08,0.561365,0.00158629,1.39695e-06,-5.79884e-08,0.562953,0.00158891,1.22299e-06,5.90392e-08,0.564543,0.00159153,1.4001e-06,-5.89592e-08,0.566136,0.00159416,1.22323e-06,5.7588e-08,0.567731,0.00159678,1.39599e-06,-5.21835e-08,0.569329,0.00159941,1.23944e-06,3.19369e-08,0.57093,0.00160199,1.33525e-06,-1.59594e-08,0.572533,0.00160461,1.28737e-06,3.19006e-08,0.574139,0.00160728,1.38307e-06,-5.20383e-08,0.575748,0.00160989,1.22696e-06,5.70431e-08,0.577359,0.00161251,1.39809e-06,-5.69247e-08,0.578973,0.00161514,1.22731e-06,5.14463e-08,0.580589,0.00161775,1.38165e-06,-2.9651e-08,0.582208,0.00162042,1.2927e-06,7.55339e-09,0.58383,0.00162303,1.31536e-06,-5.62636e-10,0.585455,0.00162566,1.31367e-06,-5.30281e-09,0.587081,0.00162827,1.29776e-06,2.17738e-08,0.588711,0.00163093,1.36309e-06,-2.21875e-08,0.590343,0.00163359,1.29652e-06,7.37164e-09,0.591978,0.00163621,1.31864e-06,-7.29907e-09,0.593616,0.00163882,1.29674e-06,2.18247e-08,0.595256,0.00164148,1.36221e-06,-2.03952e-08,0.596899,0.00164414,1.30103e-06,1.51241e-10,0.598544,0.00164675,1.30148e-06,1.97902e-08,0.600192,0.00164941,1.36085e-06,-1.97074e-08,0.601843,0.00165207,1.30173e-06,-5.65175e-10,0.603496,0.00165467,1.30004e-06,2.1968e-08,0.605152,0.00165734,1.36594e-06,-2.77024e-08,0.606811,0.00165999,1.28283e-06,2.92369e-08,0.608472,0.00166264,1.37054e-06,-2.96407e-08,0.610136,0.00166529,1.28162e-06,2.97215e-08,0.611803,0.00166795,1.37079e-06,-2.96408e-08,0.613472,0.0016706,1.28186e-06,2.92371e-08,0.615144,0.00167325,1.36957e-06,-2.77031e-08,0.616819,0.00167591,1.28647e-06,2.19708e-08,0.618496,0.00167855,1.35238e-06,-5.75407e-10,0.620176,0.00168125,1.35065e-06,-1.9669e-08,0.621858,0.00168389,1.29164e-06,1.96468e-08,0.623544,0.00168653,1.35058e-06,6.86403e-10,0.625232,0.00168924,1.35264e-06,-2.23924e-08,0.626922,0.00169187,1.28547e-06,2.92788e-08,0.628615,0.00169453,1.3733e-06,-3.51181e-08,0.630311,0.00169717,1.26795e-06,5.15889e-08,0.63201,0.00169987,1.42272e-06,-5.2028e-08,0.633711,0.00170255,1.26663e-06,3.73139e-08,0.635415,0.0017052,1.37857e-06,-3.76227e-08,0.637121,0.00170784,1.2657e-06,5.35722e-08,0.63883,0.00171054,1.42642e-06,-5.74567e-08,0.640542,0.00171322,1.25405e-06,5.70456e-08,0.642257,0.0017159,1.42519e-06,-5.15163e-08,0.643974,0.00171859,1.27064e-06,2.98103e-08,0.645694,0.00172122,1.36007e-06,-8.12016e-09,0.647417,0.00172392,1.33571e-06,2.67039e-09,0.649142,0.0017266,1.34372e-06,-2.56152e-09,0.65087,0.00172928,1.33604e-06,7.57571e-09,0.6526,0.00173197,1.35876e-06,-2.77413e-08,0.654334,0.00173461,1.27554e-06,4.3785e-08,0.65607,0.00173729,1.40689e-06,-2.81896e-08,0.657808,0.00174002,1.32233e-06,9.36893e-09,0.65955,0.00174269,1.35043e-06,-9.28617e-09,0.661294,0.00174536,1.32257e-06,2.77757e-08,0.66304,0.00174809,1.4059e-06,-4.2212e-08,0.66479,0.00175078,1.27926e-06,2.1863e-08,0.666542,0.0017534,1.34485e-06,1.43648e-08,0.668297,0.00175613,1.38795e-06,-1.97177e-08,0.670054,0.00175885,1.3288e-06,4.90115e-09,0.671814,0.00176152,1.3435e-06,1.13232e-10,0.673577,0.00176421,1.34384e-06,-5.3542e-09,0.675343,0.00176688,1.32778e-06,2.13035e-08,0.677111,0.0017696,1.39169e-06,-2.02553e-08,0.678882,0.00177232,1.33092e-06,1.13005e-10,0.680656,0.00177499,1.33126e-06,1.98031e-08,0.682432,0.00177771,1.39067e-06,-1.97211e-08,0.684211,0.00178043,1.33151e-06,-5.2349e-10,0.685993,0.00178309,1.32994e-06,2.18151e-08,0.687777,0.00178582,1.39538e-06,-2.71325e-08,0.689564,0.00178853,1.31398e-06,2.71101e-08,0.691354,0.00179124,1.39531e-06,-2.17035e-08,0.693147,0.00179396,1.3302e-06,9.92865e-11,0.694942,0.00179662,1.3305e-06,2.13063e-08,0.69674,0.00179935,1.39442e-06,-2.57198e-08,0.698541,0.00180206,1.31726e-06,2.19682e-08,0.700344,0.00180476,1.38317e-06,-2.54852e-09,0.70215,0.00180752,1.37552e-06,-1.17741e-08,0.703959,0.00181023,1.3402e-06,-9.95999e-09,0.705771,0.00181288,1.31032e-06,5.16141e-08,0.707585,0.00181566,1.46516e-06,-7.72869e-08,0.709402,0.00181836,1.2333e-06,7.87197e-08,0.711222,0.00182106,1.46946e-06,-5.87781e-08,0.713044,0.00182382,1.29312e-06,3.71834e-08,0.714869,0.00182652,1.40467e-06,-3.03511e-08,0.716697,0.00182924,1.31362e-06,2.46161e-08,0.718528,0.00183194,1.38747e-06,-8.5087e-09,0.720361,0.00183469,1.36194e-06,9.41892e-09,0.722197,0.00183744,1.3902e-06,-2.91671e-08,0.724036,0.00184014,1.3027e-06,4.76448e-08,0.725878,0.00184288,1.44563e-06,-4.22028e-08,0.727722,0.00184565,1.31902e-06,1.95682e-09,0.729569,0.00184829,1.3249e-06,3.43754e-08,0.731419,0.00185104,1.42802e-06,-2.0249e-08,0.733271,0.00185384,1.36727e-06,-1.29838e-08,0.735126,0.00185654,1.32832e-06,1.25794e-08,0.736984,0.00185923,1.36606e-06,2.22711e-08,0.738845,0.00186203,1.43287e-06,-4.20594e-08,0.740708,0.00186477,1.3067e-06,2.67571e-08,0.742574,0.00186746,1.38697e-06,-5.36424e-09,0.744443,0.00187022,1.37087e-06,-5.30023e-09,0.746315,0.00187295,1.35497e-06,2.65653e-08,0.748189,0.00187574,1.43467e-06,-4.13564e-08,0.750066,0.00187848,1.3106e-06,1.9651e-08,0.751946,0.00188116,1.36955e-06,2.23572e-08,0.753828,0.00188397,1.43663e-06,-4.9475e-08,0.755714,0.00188669,1.2882e-06,5.63335e-08,0.757602,0.00188944,1.4572e-06,-5.66499e-08,0.759493,0.00189218,1.28725e-06,5.10567e-08,0.761386,0.00189491,1.44042e-06,-2.83677e-08,0.763283,0.00189771,1.35532e-06,2.80962e-09,0.765182,0.00190042,1.36375e-06,1.71293e-08,0.767083,0.0019032,1.41513e-06,-1.17221e-08,0.768988,0.001906,1.37997e-06,-2.98453e-08,0.770895,0.00190867,1.29043e-06,7.14987e-08,0.772805,0.00191146,1.50493e-06,-7.73354e-08,0.774718,0.00191424,1.27292e-06,5.90292e-08,0.776634,0.00191697,1.45001e-06,-3.9572e-08,0.778552,0.00191975,1.33129e-06,3.9654e-08,0.780473,0.00192253,1.45026e-06,-5.94395e-08,0.782397,0.00192525,1.27194e-06,7.88945e-08,0.784324,0.00192803,1.50862e-06,-7.73249e-08,0.786253,0.00193082,1.27665e-06,5.15913e-08,0.788185,0.00193352,1.43142e-06,-9.83099e-09,0.79012,0.00193636,1.40193e-06,-1.22672e-08,0.792058,0.00193912,1.36513e-06,-7.05275e-10,0.793999,0.00194185,1.36301e-06,1.50883e-08,0.795942,0.00194462,1.40828e-06,-4.33147e-11,0.797888,0.00194744,1.40815e-06,-1.49151e-08,0.799837,0.00195021,1.3634e-06,9.93244e-11,0.801788,0.00195294,1.3637e-06,1.45179e-08,0.803743,0.00195571,1.40725e-06,1.43363e-09,0.8057,0.00195853,1.41155e-06,-2.02525e-08,0.80766,0.00196129,1.35079e-06,1.99718e-08,0.809622,0.00196405,1.41071e-06,-3.01649e-11,0.811588,0.00196687,1.41062e-06,-1.9851e-08,0.813556,0.00196964,1.35107e-06,1.98296e-08,0.815527,0.0019724,1.41056e-06,1.37485e-10,0.817501,0.00197522,1.41097e-06,-2.03796e-08,0.819477,0.00197798,1.34983e-06,2.17763e-08,0.821457,0.00198074,1.41516e-06,-7.12085e-09,0.823439,0.00198355,1.3938e-06,6.70707e-09,0.825424,0.00198636,1.41392e-06,-1.97074e-08,0.827412,0.00198913,1.35479e-06,1.25179e-08,0.829402,0.00199188,1.39235e-06,2.92405e-08,0.831396,0.00199475,1.48007e-06,-6.98755e-08,0.833392,0.0019975,1.27044e-06,7.14477e-08,0.835391,0.00200026,1.48479e-06,-3.71014e-08,0.837392,0.00200311,1.37348e-06,1.73533e-08,0.839397,0.00200591,1.42554e-06,-3.23118e-08,0.841404,0.00200867,1.32861e-06,5.2289e-08,0.843414,0.00201148,1.48547e-06,-5.76348e-08,0.845427,0.00201428,1.31257e-06,5.9041e-08,0.847443,0.00201708,1.48969e-06,-5.93197e-08,0.849461,0.00201988,1.31173e-06,5.90289e-08,0.851482,0.00202268,1.48882e-06,-5.75864e-08,0.853507,0.00202549,1.31606e-06,5.21075e-08,0.855533,0.00202828,1.47238e-06,-3.16344e-08,0.857563,0.00203113,1.37748e-06,1.48257e-08,0.859596,0.00203393,1.42196e-06,-2.76684e-08,0.861631,0.00203669,1.33895e-06,3.62433e-08,0.863669,0.00203947,1.44768e-06,1.90463e-09,0.86571,0.00204237,1.45339e-06,-4.38617e-08,0.867754,0.00204515,1.32181e-06,5.43328e-08,0.8698,0.00204796,1.48481e-06,-5.42603e-08,0.87185,0.00205076,1.32203e-06,4.34989e-08,0.873902,0.00205354,1.45252e-06,-5.26029e-10,0.875957,0.00205644,1.45095e-06,-4.13949e-08,0.878015,0.00205922,1.32676e-06,4.68962e-08,0.880075,0.00206201,1.46745e-06,-2.69807e-08,0.882139,0.00206487,1.38651e-06,1.42181e-09,0.884205,0.00206764,1.39077e-06,2.12935e-08,0.886274,0.00207049,1.45465e-06,-2.69912e-08,0.888346,0.00207332,1.37368e-06,2.70664e-08,0.890421,0.00207615,1.45488e-06,-2.16698e-08,0.892498,0.00207899,1.38987e-06,8.14756e-12,0.894579,0.00208177,1.38989e-06,2.16371e-08,0.896662,0.00208462,1.45481e-06,-2.6952e-08,0.898748,0.00208744,1.37395e-06,2.65663e-08,0.900837,0.00209027,1.45365e-06,-1.97084e-08,0.902928,0.00209312,1.39452e-06,-7.33731e-09,0.905023,0.00209589,1.37251e-06,4.90578e-08,0.90712,0.00209878,1.51968e-06,-6.96845e-08,0.90922,0.00210161,1.31063e-06,5.08664e-08,0.911323,0.00210438,1.46323e-06,-1.45717e-08,0.913429,0.00210727,1.41952e-06,7.42038e-09,0.915538,0.00211013,1.44178e-06,-1.51097e-08,0.917649,0.00211297,1.39645e-06,-6.58618e-09,0.919764,0.00211574,1.37669e-06,4.14545e-08,0.921881,0.00211862,1.50105e-06,-4.00222e-08,0.924001,0.0021215,1.38099e-06,-5.7518e-10,0.926124,0.00212426,1.37926e-06,4.23229e-08,0.92825,0.00212714,1.50623e-06,-4.9507e-08,0.930378,0.00213001,1.35771e-06,3.64958e-08,0.93251,0.00213283,1.4672e-06,-3.68713e-08,0.934644,0.00213566,1.35658e-06,5.13848e-08,0.936781,0.00213852,1.51074e-06,-4.94585e-08,0.938921,0.0021414,1.36236e-06,2.72399e-08,0.941064,0.0021442,1.44408e-06,1.0372e-10,0.943209,0.00214709,1.44439e-06,-2.76547e-08,0.945358,0.0021499,1.36143e-06,5.09106e-08,0.947509,0.00215277,1.51416e-06,-5.67784e-08,0.949663,0.00215563,1.34382e-06,5.69935e-08,0.95182,0.00215849,1.5148e-06,-5.19861e-08,0.95398,0.00216136,1.35885e-06,3.17417e-08,0.956143,0.00216418,1.45407e-06,-1.53758e-08,0.958309,0.00216704,1.40794e-06,2.97615e-08,0.960477,0.00216994,1.49723e-06,-4.40657e-08,0.962649,0.00217281,1.36503e-06,2.72919e-08,0.964823,0.00217562,1.44691e-06,-5.49729e-09,0.967,0.0021785,1.43041e-06,-5.30273e-09,0.96918,0.00218134,1.41451e-06,2.67084e-08,0.971363,0.00218425,1.49463e-06,-4.19265e-08,0.973548,0.00218711,1.36885e-06,2.17881e-08,0.975737,0.00218992,1.43422e-06,1.43789e-08,0.977928,0.00219283,1.47735e-06,-1.96989e-08,0.980122,0.00219572,1.41826e-06,4.81221e-09,0.98232,0.00219857,1.43269e-06,4.50048e-10,0.98452,0.00220144,1.43404e-06,-6.61237e-09,0.986722,0.00220429,1.41421e-06,2.59993e-08,0.988928,0.0022072,1.4922e-06,-3.77803e-08,0.991137,0.00221007,1.37886e-06,5.9127e-09,0.993348,0.00221284,1.3966e-06,1.33339e-07,0.995563,0.00221604,1.79662e-06,-5.98872e-07,0.99778,0.00222015,0.,0.}; + + template + __device__ __forceinline__ void RGB2LabConvert_f(const T& src, D& dst) + { + const float _1_3 = 1.0f / 3.0f; + const float _a = 16.0f / 116.0f; + + float B = blueIdx == 0 ? src.x : src.z; + float G = src.y; + float R = blueIdx == 0 ? src.z : src.x; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + } + + float X = B * 0.189828f + G * 0.376219f + R * 0.433953f; + float Y = B * 0.072169f + G * 0.715160f + R * 0.212671f; + float Z = B * 0.872766f + G * 0.109477f + R * 0.017758f; + + float FX = X > 0.008856f ? ::powf(X, _1_3) : (7.787f * X + _a); + float FY = Y > 0.008856f ? ::powf(Y, _1_3) : (7.787f * Y + _a); + float FZ = Z > 0.008856f ? ::powf(Z, _1_3) : (7.787f * Z + _a); + + float L = Y > 0.008856f ? (116.f * FY - 16.f) : (903.3f * Y); + float a = 500.f * (FX - FY); + float b = 200.f * (FY - FZ); + + dst.x = L; + dst.y = a; + dst.z = b; + } + + template struct RGB2Lab; + template + struct RGB2Lab + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LabConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Lab() {} + __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} + }; + template + struct RGB2Lab + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LabConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Lab() {} + __host__ __device__ __forceinline__ RGB2Lab(const RGB2Lab&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2Lab_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2Lab functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + __constant__ float c_sRGBInvGammaTab[] = {0,0.0126255,0.,-8.33961e-06,0.0126172,0.0126005,-2.50188e-05,4.1698e-05,0.0252344,0.0126756,0.000100075,-0.000158451,0.0378516,0.0124004,-0.000375277,-0.000207393,0.0496693,0.0110276,-0.000997456,0.00016837,0.0598678,0.00953783,-0.000492346,2.07235e-05,0.068934,0.00861531,-0.000430176,3.62876e-05,0.0771554,0.00786382,-0.000321313,1.87625e-05,0.0847167,0.00727748,-0.000265025,1.53594e-05,0.0917445,0.00679351,-0.000218947,1.10545e-05,0.0983301,0.00638877,-0.000185784,8.66984e-06,0.104542,0.00604322,-0.000159774,6.82996e-06,0.110432,0.00574416,-0.000139284,5.51008e-06,0.116042,0.00548212,-0.000122754,4.52322e-06,0.121406,0.00525018,-0.000109184,3.75557e-06,0.126551,0.00504308,-9.79177e-05,3.17134e-06,0.131499,0.00485676,-8.84037e-05,2.68469e-06,0.13627,0.004688,-8.03496e-05,2.31725e-06,0.14088,0.00453426,-7.33978e-05,2.00868e-06,0.145343,0.00439349,-6.73718e-05,1.74775e-06,0.149671,0.00426399,-6.21286e-05,1.53547e-06,0.153875,0.00414434,-5.75222e-05,1.364e-06,0.157963,0.00403338,-5.34301e-05,1.20416e-06,0.161944,0.00393014,-4.98177e-05,1.09114e-06,0.165825,0.00383377,-4.65443e-05,9.57987e-07,0.169613,0.00374356,-4.36703e-05,8.88359e-07,0.173314,0.00365888,-4.10052e-05,7.7849e-07,0.176933,0.00357921,-3.86697e-05,7.36254e-07,0.180474,0.00350408,-3.6461e-05,6.42534e-07,0.183942,0.00343308,-3.45334e-05,6.12614e-07,0.187342,0.00336586,-3.26955e-05,5.42894e-07,0.190675,0.00330209,-3.10669e-05,5.08967e-07,0.193947,0.00324149,-2.954e-05,4.75977e-07,0.197159,0.00318383,-2.8112e-05,4.18343e-07,0.200315,0.00312887,-2.6857e-05,4.13651e-07,0.203418,0.00307639,-2.5616e-05,3.70847e-07,0.206469,0.00302627,-2.45035e-05,3.3813e-07,0.209471,0.00297828,-2.34891e-05,3.32999e-07,0.212426,0.0029323,-2.24901e-05,2.96826e-07,0.215336,0.00288821,-2.15996e-05,2.82736e-07,0.218203,0.00284586,-2.07514e-05,2.70961e-07,0.221029,0.00280517,-1.99385e-05,2.42744e-07,0.223814,0.00276602,-1.92103e-05,2.33277e-07,0.226561,0.0027283,-1.85105e-05,2.2486e-07,0.229271,0.00269195,-1.78359e-05,2.08383e-07,0.231945,0.00265691,-1.72108e-05,1.93305e-07,0.234585,0.00262307,-1.66308e-05,1.80687e-07,0.237192,0.00259035,-1.60888e-05,1.86632e-07,0.239766,0.00255873,-1.55289e-05,1.60569e-07,0.24231,0.00252815,-1.50472e-05,1.54566e-07,0.244823,0.00249852,-1.45835e-05,1.59939e-07,0.247307,0.00246983,-1.41037e-05,1.29549e-07,0.249763,0.00244202,-1.3715e-05,1.41429e-07,0.252191,0.00241501,-1.32907e-05,1.39198e-07,0.254593,0.00238885,-1.28731e-05,1.06444e-07,0.256969,0.00236342,-1.25538e-05,1.2048e-07,0.25932,0.00233867,-1.21924e-05,1.26892e-07,0.261647,0.00231467,-1.18117e-05,8.72084e-08,0.26395,0.00229131,-1.15501e-05,1.20323e-07,0.26623,0.00226857,-1.11891e-05,8.71514e-08,0.268487,0.00224645,-1.09276e-05,9.73165e-08,0.270723,0.00222489,-1.06357e-05,8.98259e-08,0.272937,0.00220389,-1.03662e-05,7.98218e-08,0.275131,0.00218339,-1.01267e-05,9.75254e-08,0.277304,0.00216343,-9.83416e-06,6.65195e-08,0.279458,0.00214396,-9.63461e-06,8.34313e-08,0.281592,0.00212494,-9.38431e-06,7.65919e-08,0.283708,0.00210641,-9.15454e-06,5.7236e-08,0.285805,0.00208827,-8.98283e-06,8.18939e-08,0.287885,0.00207055,-8.73715e-06,6.2224e-08,0.289946,0.00205326,-8.55047e-06,5.66388e-08,0.291991,0.00203633,-8.38056e-06,6.88491e-08,0.294019,0.00201978,-8.17401e-06,5.53955e-08,0.296031,0.00200359,-8.00782e-06,6.71971e-08,0.298027,0.00198778,-7.80623e-06,3.34439e-08,0.300007,0.00197227,-7.7059e-06,6.7248e-08,0.301971,0.00195706,-7.50416e-06,5.51915e-08,0.303921,0.00194221,-7.33858e-06,3.98124e-08,0.305856,0.00192766,-7.21915e-06,5.37795e-08,0.307776,0.00191338,-7.05781e-06,4.30919e-08,0.309683,0.00189939,-6.92853e-06,4.20744e-08,0.311575,0.00188566,-6.80231e-06,5.68321e-08,0.313454,0.00187223,-6.63181e-06,2.86195e-08,0.31532,0.00185905,-6.54595e-06,3.73075e-08,0.317172,0.00184607,-6.43403e-06,6.05684e-08,0.319012,0.00183338,-6.25233e-06,1.84426e-08,0.320839,0.00182094,-6.197e-06,4.44757e-08,0.322654,0.00180867,-6.06357e-06,4.20729e-08,0.324456,0.00179667,-5.93735e-06,2.56511e-08,0.326247,0.00178488,-5.8604e-06,3.41368e-08,0.328026,0.00177326,-5.75799e-06,4.64177e-08,0.329794,0.00176188,-5.61874e-06,1.86107e-08,0.33155,0.0017507,-5.5629e-06,2.81511e-08,0.333295,0.00173966,-5.47845e-06,4.75987e-08,0.335029,0.00172884,-5.33565e-06,1.98726e-08,0.336753,0.00171823,-5.27604e-06,2.19226e-08,0.338466,0.00170775,-5.21027e-06,4.14483e-08,0.340169,0.00169745,-5.08592e-06,2.09017e-08,0.341861,0.00168734,-5.02322e-06,2.39561e-08,0.343543,0.00167737,-4.95135e-06,3.22852e-08,0.345216,0.00166756,-4.85449e-06,2.57173e-08,0.346878,0.00165793,-4.77734e-06,1.38569e-08,0.348532,0.00164841,-4.73577e-06,3.80634e-08,0.350175,0.00163906,-4.62158e-06,1.27043e-08,0.35181,0.00162985,-4.58347e-06,3.03279e-08,0.353435,0.00162078,-4.49249e-06,1.49961e-08,0.355051,0.00161184,-4.4475e-06,2.88977e-08,0.356659,0.00160303,-4.3608e-06,1.84241e-08,0.358257,0.00159436,-4.30553e-06,1.6616e-08,0.359848,0.0015858,-4.25568e-06,3.43218e-08,0.361429,0.00157739,-4.15272e-06,-4.89172e-09,0.363002,0.00156907,-4.16739e-06,4.48498e-08,0.364567,0.00156087,-4.03284e-06,4.30676e-09,0.366124,0.00155282,-4.01992e-06,2.73303e-08,0.367673,0.00154486,-3.93793e-06,5.58036e-09,0.369214,0.001537,-3.92119e-06,3.97554e-08,0.370747,0.00152928,-3.80193e-06,-1.55904e-08,0.372272,0.00152163,-3.8487e-06,5.24081e-08,0.37379,0.00151409,-3.69147e-06,-1.52272e-08,0.375301,0.00150666,-3.73715e-06,3.83028e-08,0.376804,0.0014993,-3.62225e-06,1.10278e-08,0.378299,0.00149209,-3.58916e-06,6.99326e-09,0.379788,0.00148493,-3.56818e-06,2.06038e-08,0.381269,0.00147786,-3.50637e-06,2.98009e-08,0.382744,0.00147093,-3.41697e-06,-2.05978e-08,0.384211,0.00146404,-3.47876e-06,5.25899e-08,0.385672,0.00145724,-3.32099e-06,-1.09471e-08,0.387126,0.00145056,-3.35383e-06,2.10009e-08,0.388573,0.00144392,-3.29083e-06,1.63501e-08,0.390014,0.00143739,-3.24178e-06,3.00641e-09,0.391448,0.00143091,-3.23276e-06,3.12282e-08,0.392875,0.00142454,-3.13908e-06,-8.70932e-09,0.394297,0.00141824,-3.16521e-06,3.34114e-08,0.395712,0.00141201,-3.06497e-06,-5.72754e-09,0.397121,0.00140586,-3.08215e-06,1.9301e-08,0.398524,0.00139975,-3.02425e-06,1.7931e-08,0.39992,0.00139376,-2.97046e-06,-1.61822e-09,0.401311,0.00138781,-2.97531e-06,1.83442e-08,0.402696,0.00138192,-2.92028e-06,1.76485e-08,0.404075,0.00137613,-2.86733e-06,4.68617e-10,0.405448,0.00137039,-2.86593e-06,1.02794e-08,0.406816,0.00136469,-2.83509e-06,1.80179e-08,0.408178,0.00135908,-2.78104e-06,7.05594e-09,0.409534,0.00135354,-2.75987e-06,1.33633e-08,0.410885,0.00134806,-2.71978e-06,-9.04568e-10,0.41223,0.00134261,-2.72249e-06,2.0057e-08,0.41357,0.00133723,-2.66232e-06,1.00841e-08,0.414905,0.00133194,-2.63207e-06,-7.88835e-10,0.416234,0.00132667,-2.63444e-06,2.28734e-08,0.417558,0.00132147,-2.56582e-06,-1.29785e-09,0.418877,0.00131633,-2.56971e-06,1.21205e-08,0.420191,0.00131123,-2.53335e-06,1.24202e-08,0.421499,0.0013062,-2.49609e-06,-2.19681e-09,0.422803,0.0013012,-2.50268e-06,2.61696e-08,0.424102,0.00129628,-2.42417e-06,-1.30747e-08,0.425396,0.00129139,-2.46339e-06,2.6129e-08,0.426685,0.00128654,-2.38501e-06,-2.03454e-09,0.427969,0.00128176,-2.39111e-06,1.18115e-08,0.429248,0.00127702,-2.35567e-06,1.43932e-08,0.430523,0.00127235,-2.31249e-06,-9.77965e-09,0.431793,0.00126769,-2.34183e-06,2.47253e-08,0.433058,0.00126308,-2.26766e-06,2.85278e-10,0.434319,0.00125855,-2.2668e-06,3.93614e-09,0.435575,0.00125403,-2.25499e-06,1.37722e-08,0.436827,0.00124956,-2.21368e-06,5.79803e-10,0.438074,0.00124513,-2.21194e-06,1.37112e-08,0.439317,0.00124075,-2.1708e-06,4.17973e-09,0.440556,0.00123642,-2.15826e-06,-6.27703e-10,0.44179,0.0012321,-2.16015e-06,2.81332e-08,0.44302,0.00122787,-2.07575e-06,-2.24985e-08,0.444246,0.00122365,-2.14324e-06,3.20586e-08,0.445467,0.00121946,-2.04707e-06,-1.6329e-08,0.446685,0.00121532,-2.09605e-06,3.32573e-08,0.447898,0.00121122,-1.99628e-06,-2.72927e-08,0.449107,0.00120715,-2.07816e-06,4.6111e-08,0.450312,0.00120313,-1.93983e-06,-3.79416e-08,0.451514,0.00119914,-2.05365e-06,4.60507e-08,0.452711,0.00119517,-1.9155e-06,-2.7052e-08,0.453904,0.00119126,-1.99666e-06,3.23551e-08,0.455093,0.00118736,-1.89959e-06,-1.29613e-08,0.456279,0.00118352,-1.93848e-06,1.94905e-08,0.45746,0.0011797,-1.88e-06,-5.39588e-09,0.458638,0.00117593,-1.89619e-06,2.09282e-09,0.459812,0.00117214,-1.88991e-06,2.68267e-08,0.460982,0.00116844,-1.80943e-06,-1.99925e-08,0.462149,0.00116476,-1.86941e-06,2.3341e-08,0.463312,0.00116109,-1.79939e-06,-1.37674e-08,0.464471,0.00115745,-1.84069e-06,3.17287e-08,0.465627,0.00115387,-1.7455e-06,-2.37407e-08,0.466779,0.00115031,-1.81673e-06,3.34315e-08,0.467927,0.00114677,-1.71643e-06,-2.05786e-08,0.469073,0.00114328,-1.77817e-06,1.90802e-08,0.470214,0.00113978,-1.72093e-06,3.86247e-09,0.471352,0.00113635,-1.70934e-06,-4.72759e-09,0.472487,0.00113292,-1.72352e-06,1.50478e-08,0.473618,0.00112951,-1.67838e-06,4.14108e-09,0.474746,0.00112617,-1.66595e-06,-1.80986e-09,0.47587,0.00112283,-1.67138e-06,3.09816e-09,0.476991,0.0011195,-1.66209e-06,1.92198e-08,0.478109,0.00111623,-1.60443e-06,-2.03726e-08,0.479224,0.00111296,-1.66555e-06,3.2468e-08,0.480335,0.00110973,-1.56814e-06,-2.00922e-08,0.481443,0.00110653,-1.62842e-06,1.80983e-08,0.482548,0.00110333,-1.57413e-06,7.30362e-09,0.48365,0.0011002,-1.55221e-06,-1.75107e-08,0.484749,0.00109705,-1.60475e-06,3.29373e-08,0.485844,0.00109393,-1.50594e-06,-2.48315e-08,0.486937,0.00109085,-1.58043e-06,3.65865e-08,0.488026,0.0010878,-1.47067e-06,-3.21078e-08,0.489112,0.00108476,-1.56699e-06,3.22397e-08,0.490195,0.00108172,-1.47027e-06,-7.44391e-09,0.491276,0.00107876,-1.49261e-06,-2.46428e-09,0.492353,0.00107577,-1.5e-06,1.73011e-08,0.493427,0.00107282,-1.4481e-06,-7.13552e-09,0.494499,0.0010699,-1.4695e-06,1.1241e-08,0.495567,0.001067,-1.43578e-06,-8.02637e-09,0.496633,0.0010641,-1.45986e-06,2.08645e-08,0.497695,0.00106124,-1.39726e-06,-1.58271e-08,0.498755,0.0010584,-1.44475e-06,1.26415e-08,0.499812,0.00105555,-1.40682e-06,2.48655e-08,0.500866,0.00105281,-1.33222e-06,-5.24988e-08,0.501918,0.00104999,-1.48972e-06,6.59206e-08,0.502966,0.00104721,-1.29196e-06,-3.237e-08,0.504012,0.00104453,-1.38907e-06,3.95479e-09,0.505055,0.00104176,-1.3772e-06,1.65509e-08,0.506096,0.00103905,-1.32755e-06,-1.05539e-08,0.507133,0.00103637,-1.35921e-06,2.56648e-08,0.508168,0.00103373,-1.28222e-06,-3.25007e-08,0.509201,0.00103106,-1.37972e-06,4.47336e-08,0.51023,0.00102844,-1.24552e-06,-2.72245e-08,0.511258,0.00102587,-1.32719e-06,4.55952e-09,0.512282,0.00102323,-1.31352e-06,8.98645e-09,0.513304,0.00102063,-1.28656e-06,1.90992e-08,0.514323,0.00101811,-1.22926e-06,-2.57786e-08,0.51534,0.00101557,-1.30659e-06,2.44104e-08,0.516355,0.00101303,-1.23336e-06,-1.22581e-08,0.517366,0.00101053,-1.27014e-06,2.4622e-08,0.518376,0.00100806,-1.19627e-06,-2.66253e-08,0.519383,0.00100559,-1.27615e-06,2.22744e-08,0.520387,0.00100311,-1.20932e-06,-2.8679e-09,0.521389,0.00100068,-1.21793e-06,-1.08029e-08,0.522388,0.000998211,-1.25034e-06,4.60795e-08,0.523385,0.000995849,-1.1121e-06,-5.4306e-08,0.52438,0.000993462,-1.27502e-06,5.19354e-08,0.525372,0.000991067,-1.11921e-06,-3.42262e-08,0.526362,0.000988726,-1.22189e-06,2.53646e-08,0.52735,0.000986359,-1.14579e-06,-7.62782e-09,0.528335,0.000984044,-1.16868e-06,5.14668e-09,0.529318,0.000981722,-1.15324e-06,-1.29589e-08,0.530298,0.000979377,-1.19211e-06,4.66888e-08,0.531276,0.000977133,-1.05205e-06,-5.45868e-08,0.532252,0.000974865,-1.21581e-06,5.24495e-08,0.533226,0.000972591,-1.05846e-06,-3.60019e-08,0.534198,0.000970366,-1.16647e-06,3.19537e-08,0.535167,0.000968129,-1.07061e-06,-3.2208e-08,0.536134,0.000965891,-1.16723e-06,3.72738e-08,0.537099,0.000963668,-1.05541e-06,2.32205e-09,0.538061,0.000961564,-1.04844e-06,-4.65618e-08,0.539022,0.000959328,-1.18813e-06,6.47159e-08,0.53998,0.000957146,-9.93979e-07,-3.3488e-08,0.540936,0.000955057,-1.09444e-06,9.63166e-09,0.54189,0.000952897,-1.06555e-06,-5.03871e-09,0.542842,0.000950751,-1.08066e-06,1.05232e-08,0.543792,0.000948621,-1.04909e-06,2.25503e-08,0.544739,0.000946591,-9.81444e-07,-4.11195e-08,0.545685,0.000944504,-1.1048e-06,2.27182e-08,0.546628,0.000942363,-1.03665e-06,9.85146e-09,0.54757,0.000940319,-1.00709e-06,-2.51938e-09,0.548509,0.000938297,-1.01465e-06,2.25858e-10,0.549446,0.000936269,-1.01397e-06,1.61598e-09,0.550381,0.000934246,-1.00913e-06,-6.68983e-09,0.551315,0.000932207,-1.0292e-06,2.51434e-08,0.552246,0.000930224,-9.53765e-07,-3.42793e-08,0.553175,0.000928214,-1.0566e-06,5.23688e-08,0.554102,0.000926258,-8.99497e-07,-5.59865e-08,0.555028,0.000924291,-1.06746e-06,5.23679e-08,0.555951,0.000922313,-9.10352e-07,-3.42763e-08,0.556872,0.00092039,-1.01318e-06,2.51326e-08,0.557792,0.000918439,-9.37783e-07,-6.64954e-09,0.558709,0.000916543,-9.57732e-07,1.46554e-09,0.559625,0.000914632,-9.53335e-07,7.87281e-10,0.560538,0.000912728,-9.50973e-07,-4.61466e-09,0.56145,0.000910812,-9.64817e-07,1.76713e-08,0.56236,0.000908935,-9.11804e-07,-6.46564e-09,0.563268,0.000907092,-9.312e-07,8.19121e-09,0.564174,0.000905255,-9.06627e-07,-2.62992e-08,0.565078,0.000903362,-9.85524e-07,3.74007e-08,0.565981,0.000901504,-8.73322e-07,-4.0942e-09,0.566882,0.000899745,-8.85605e-07,-2.1024e-08,0.56778,0.00089791,-9.48677e-07,2.85854e-08,0.568677,0.000896099,-8.62921e-07,-3.3713e-08,0.569573,0.000894272,-9.64059e-07,4.6662e-08,0.570466,0.000892484,-8.24073e-07,-3.37258e-08,0.571358,0.000890734,-9.25251e-07,2.86365e-08,0.572247,0.00088897,-8.39341e-07,-2.12155e-08,0.573135,0.000887227,-9.02988e-07,-3.37913e-09,0.574022,0.000885411,-9.13125e-07,3.47319e-08,0.574906,0.000883689,-8.08929e-07,-1.63394e-08,0.575789,0.000882022,-8.57947e-07,-2.8979e-08,0.57667,0.00088022,-9.44885e-07,7.26509e-08,0.57755,0.000878548,-7.26932e-07,-8.28106e-08,0.578427,0.000876845,-9.75364e-07,7.97774e-08,0.579303,0.000875134,-7.36032e-07,-5.74849e-08,0.580178,0.00087349,-9.08486e-07,3.09529e-08,0.58105,0.000871765,-8.15628e-07,-6.72206e-09,0.581921,0.000870114,-8.35794e-07,-4.06451e-09,0.582791,0.00086843,-8.47987e-07,2.29799e-08,0.583658,0.000866803,-7.79048e-07,-2.82503e-08,0.584524,0.00086516,-8.63799e-07,3.04167e-08,0.585388,0.000863524,-7.72548e-07,-3.38119e-08,0.586251,0.000861877,-8.73984e-07,4.52264e-08,0.587112,0.000860265,-7.38305e-07,-2.78842e-08,0.587972,0.000858705,-8.21958e-07,6.70567e-09,0.58883,0.000857081,-8.01841e-07,1.06161e-09,0.589686,0.000855481,-7.98656e-07,-1.09521e-08,0.590541,0.00085385,-8.31512e-07,4.27468e-08,0.591394,0.000852316,-7.03272e-07,-4.08257e-08,0.592245,0.000850787,-8.25749e-07,1.34677e-09,0.593095,0.000849139,-8.21709e-07,3.54387e-08,0.593944,0.000847602,-7.15393e-07,-2.38924e-08,0.59479,0.0008461,-7.8707e-07,5.26143e-10,0.595636,0.000844527,-7.85491e-07,2.17879e-08,0.596479,0.000843021,-7.20127e-07,-2.80733e-08,0.597322,0.000841497,-8.04347e-07,3.09005e-08,0.598162,0.000839981,-7.11646e-07,-3.5924e-08,0.599002,0.00083845,-8.19418e-07,5.3191e-08,0.599839,0.000836971,-6.59845e-07,-5.76307e-08,0.600676,0.000835478,-8.32737e-07,5.81227e-08,0.60151,0.000833987,-6.58369e-07,-5.56507e-08,0.602344,0.000832503,-8.25321e-07,4.52706e-08,0.603175,0.000830988,-6.89509e-07,-6.22236e-09,0.604006,0.000829591,-7.08176e-07,-2.03811e-08,0.604834,0.000828113,-7.6932e-07,2.8142e-08,0.605662,0.000826659,-6.84894e-07,-3.25822e-08,0.606488,0.000825191,-7.8264e-07,4.25823e-08,0.607312,0.000823754,-6.54893e-07,-1.85376e-08,0.608135,0.000822389,-7.10506e-07,-2.80365e-08,0.608957,0.000820883,-7.94616e-07,7.1079e-08,0.609777,0.000819507,-5.81379e-07,-7.74655e-08,0.610596,0.000818112,-8.13775e-07,5.9969e-08,0.611413,0.000816665,-6.33868e-07,-4.32013e-08,0.612229,0.000815267,-7.63472e-07,5.32313e-08,0.613044,0.0008139,-6.03778e-07,-5.05148e-08,0.613857,0.000812541,-7.55323e-07,2.96187e-08,0.614669,0.000811119,-6.66466e-07,-8.35545e-09,0.615479,0.000809761,-6.91533e-07,3.80301e-09,0.616288,0.00080839,-6.80124e-07,-6.85666e-09,0.617096,0.000807009,-7.00694e-07,2.36237e-08,0.617903,0.000805678,-6.29822e-07,-2.80336e-08,0.618708,0.000804334,-7.13923e-07,2.8906e-08,0.619511,0.000802993,-6.27205e-07,-2.79859e-08,0.620314,0.000801655,-7.11163e-07,2.34329e-08,0.621114,0.000800303,-6.40864e-07,-6.14108e-09,0.621914,0.000799003,-6.59287e-07,1.13151e-09,0.622712,0.000797688,-6.55893e-07,1.61507e-09,0.62351,0.000796381,-6.51048e-07,-7.59186e-09,0.624305,0.000795056,-6.73823e-07,2.87524e-08,0.6251,0.000793794,-5.87566e-07,-4.7813e-08,0.625893,0.000792476,-7.31005e-07,4.32901e-08,0.626685,0.000791144,-6.01135e-07,-6.13814e-09,0.627475,0.000789923,-6.19549e-07,-1.87376e-08,0.628264,0.000788628,-6.75762e-07,2.14837e-08,0.629052,0.000787341,-6.11311e-07,-7.59265e-09,0.629839,0.000786095,-6.34089e-07,8.88692e-09,0.630625,0.000784854,-6.07428e-07,-2.7955e-08,0.631409,0.000783555,-6.91293e-07,4.33285e-08,0.632192,0.000782302,-5.61307e-07,-2.61497e-08,0.632973,0.000781101,-6.39757e-07,1.6658e-09,0.633754,0.000779827,-6.34759e-07,1.94866e-08,0.634533,0.000778616,-5.76299e-07,-2.00076e-08,0.635311,0.000777403,-6.36322e-07,9.39091e-10,0.636088,0.000776133,-6.33505e-07,1.62512e-08,0.636863,0.000774915,-5.84751e-07,-6.33937e-09,0.637638,0.000773726,-6.03769e-07,9.10609e-09,0.638411,0.000772546,-5.76451e-07,-3.00849e-08,0.639183,0.000771303,-6.66706e-07,5.1629e-08,0.639953,0.000770125,-5.11819e-07,-5.7222e-08,0.640723,0.000768929,-6.83485e-07,5.80497e-08,0.641491,0.000767736,-5.09336e-07,-5.57674e-08,0.642259,0.000766551,-6.76638e-07,4.58105e-08,0.643024,0.000765335,-5.39206e-07,-8.26541e-09,0.643789,0.000764231,-5.64002e-07,-1.27488e-08,0.644553,0.000763065,-6.02249e-07,-3.44168e-10,0.645315,0.00076186,-6.03281e-07,1.41254e-08,0.646077,0.000760695,-5.60905e-07,3.44727e-09,0.646837,0.000759584,-5.50563e-07,-2.79144e-08,0.647596,0.000758399,-6.34307e-07,4.86057e-08,0.648354,0.000757276,-4.88489e-07,-4.72989e-08,0.64911,0.000756158,-6.30386e-07,2.13807e-08,0.649866,0.000754961,-5.66244e-07,2.13808e-08,0.65062,0.000753893,-5.02102e-07,-4.7299e-08,0.651374,0.000752746,-6.43999e-07,4.86059e-08,0.652126,0.000751604,-4.98181e-07,-2.79154e-08,0.652877,0.000750524,-5.81927e-07,3.45089e-09,0.653627,0.000749371,-5.71575e-07,1.41119e-08,0.654376,0.00074827,-5.29239e-07,-2.93748e-10,0.655123,0.00074721,-5.3012e-07,-1.29368e-08,0.65587,0.000746111,-5.68931e-07,-7.56355e-09,0.656616,0.000744951,-5.91621e-07,4.3191e-08,0.65736,0.000743897,-4.62048e-07,-4.59911e-08,0.658103,0.000742835,-6.00022e-07,2.15642e-08,0.658846,0.0007417,-5.35329e-07,1.93389e-08,0.659587,0.000740687,-4.77312e-07,-3.93152e-08,0.660327,0.000739615,-5.95258e-07,1.87126e-08,0.661066,0.00073848,-5.3912e-07,2.40695e-08,0.661804,0.000737474,-4.66912e-07,-5.53859e-08,0.662541,0.000736374,-6.33069e-07,7.82648e-08,0.663277,0.000735343,-3.98275e-07,-7.88593e-08,0.664012,0.00073431,-6.34853e-07,5.83585e-08,0.664745,0.000733215,-4.59777e-07,-3.53656e-08,0.665478,0.000732189,-5.65874e-07,2.34994e-08,0.66621,0.000731128,-4.95376e-07,9.72743e-10,0.66694,0.00073014,-4.92458e-07,-2.73903e-08,0.66767,0.000729073,-5.74629e-07,4.89839e-08,0.668398,0.000728071,-4.27677e-07,-4.93359e-08,0.669126,0.000727068,-5.75685e-07,2.91504e-08,0.669853,0.000726004,-4.88234e-07,-7.66109e-09,0.670578,0.000725004,-5.11217e-07,1.49392e-09,0.671303,0.000723986,-5.06735e-07,1.68533e-09,0.672026,0.000722978,-5.01679e-07,-8.23525e-09,0.672749,0.00072195,-5.26385e-07,3.12556e-08,0.67347,0.000720991,-4.32618e-07,-5.71825e-08,0.674191,0.000719954,-6.04166e-07,7.8265e-08,0.67491,0.00071898,-3.69371e-07,-7.70634e-08,0.675628,0.00071801,-6.00561e-07,5.11747e-08,0.676346,0.000716963,-4.47037e-07,-8.42615e-09,0.677062,0.000716044,-4.72315e-07,-1.747e-08,0.677778,0.000715046,-5.24725e-07,1.87015e-08,0.678493,0.000714053,-4.68621e-07,2.26856e-09,0.679206,0.000713123,-4.61815e-07,-2.77758e-08,0.679919,0.000712116,-5.45142e-07,4.92298e-08,0.68063,0.000711173,-3.97453e-07,-4.99339e-08,0.681341,0.000710228,-5.47255e-07,3.12967e-08,0.682051,0.000709228,-4.53365e-07,-1.56481e-08,0.68276,0.000708274,-5.00309e-07,3.12958e-08,0.683467,0.000707367,-4.06422e-07,-4.99303e-08,0.684174,0.000706405,-5.56213e-07,4.9216e-08,0.68488,0.00070544,-4.08565e-07,-2.77245e-08,0.685585,0.00070454,-4.91738e-07,2.07748e-09,0.686289,0.000703562,-4.85506e-07,1.94146e-08,0.686992,0.00070265,-4.27262e-07,-2.01314e-08,0.687695,0.000701735,-4.87656e-07,1.50616e-09,0.688396,0.000700764,-4.83137e-07,1.41067e-08,0.689096,0.00069984,-4.40817e-07,1.67168e-09,0.689795,0.000698963,-4.35802e-07,-2.07934e-08,0.690494,0.000698029,-4.98182e-07,2.18972e-08,0.691192,0.000697099,-4.32491e-07,-7.19092e-09,0.691888,0.000696212,-4.54064e-07,6.86642e-09,0.692584,0.000695325,-4.33464e-07,-2.02747e-08,0.693279,0.000694397,-4.94288e-07,1.46279e-08,0.693973,0.000693452,-4.50405e-07,2.13678e-08,0.694666,0.000692616,-3.86301e-07,-4.04945e-08,0.695358,0.000691721,-5.07785e-07,2.14009e-08,0.696049,0.00069077,-4.43582e-07,1.44955e-08,0.69674,0.000689926,-4.00096e-07,-1.97783e-08,0.697429,0.000689067,-4.5943e-07,5.01296e-09,0.698118,0.000688163,-4.44392e-07,-2.73521e-10,0.698805,0.000687273,-4.45212e-07,-3.91893e-09,0.699492,0.000686371,-4.56969e-07,1.59493e-08,0.700178,0.000685505,-4.09121e-07,-2.73351e-10,0.700863,0.000684686,-4.09941e-07,-1.4856e-08,0.701548,0.000683822,-4.54509e-07,9.25979e-11,0.702231,0.000682913,-4.54231e-07,1.44855e-08,0.702913,0.000682048,-4.10775e-07,1.56992e-09,0.703595,0.000681231,-4.06065e-07,-2.07652e-08,0.704276,0.000680357,-4.68361e-07,2.18864e-08,0.704956,0.000679486,-4.02701e-07,-7.17595e-09,0.705635,0.000678659,-4.24229e-07,6.81748e-09,0.706313,0.000677831,-4.03777e-07,-2.0094e-08,0.70699,0.000676963,-4.64059e-07,1.39538e-08,0.707667,0.000676077,-4.22197e-07,2.38835e-08,0.708343,0.000675304,-3.50547e-07,-4.98831e-08,0.709018,0.000674453,-5.00196e-07,5.64395e-08,0.709692,0.000673622,-3.30878e-07,-5.66657e-08,0.710365,0.00067279,-5.00875e-07,5.1014e-08,0.711037,0.000671942,-3.47833e-07,-2.81809e-08,0.711709,0.000671161,-4.32376e-07,2.10513e-09,0.712379,0.000670303,-4.2606e-07,1.97604e-08,0.713049,0.00066951,-3.66779e-07,-2.15422e-08,0.713718,0.000668712,-4.31406e-07,6.8038e-09,0.714387,0.000667869,-4.10994e-07,-5.67295e-09,0.715054,0.00066703,-4.28013e-07,1.5888e-08,0.715721,0.000666222,-3.80349e-07,1.72576e-09,0.716387,0.000665467,-3.75172e-07,-2.27911e-08,0.717052,0.000664648,-4.43545e-07,2.9834e-08,0.717716,0.00066385,-3.54043e-07,-3.69401e-08,0.718379,0.000663031,-4.64864e-07,5.83219e-08,0.719042,0.000662277,-2.89898e-07,-7.71382e-08,0.719704,0.000661465,-5.21313e-07,7.14171e-08,0.720365,0.000660637,-3.07061e-07,-2.97161e-08,0.721025,0.000659934,-3.96209e-07,-1.21575e-08,0.721685,0.000659105,-4.32682e-07,1.87412e-08,0.722343,0.000658296,-3.76458e-07,-3.2029e-09,0.723001,0.000657533,-3.86067e-07,-5.9296e-09,0.723659,0.000656743,-4.03856e-07,2.69213e-08,0.724315,0.000656016,-3.23092e-07,-4.21511e-08,0.724971,0.000655244,-4.49545e-07,2.24737e-08,0.725625,0.000654412,-3.82124e-07,1.18611e-08,0.726279,0.000653683,-3.46541e-07,-1.03132e-08,0.726933,0.000652959,-3.7748e-07,-3.02128e-08,0.727585,0.000652114,-4.68119e-07,7.15597e-08,0.728237,0.000651392,-2.5344e-07,-7.72119e-08,0.728888,0.000650654,-4.85075e-07,5.8474e-08,0.729538,0.000649859,-3.09654e-07,-3.74746e-08,0.730188,0.000649127,-4.22077e-07,3.18197e-08,0.730837,0.000648379,-3.26618e-07,-3.01997e-08,0.731485,0.000647635,-4.17217e-07,2.93747e-08,0.732132,0.000646888,-3.29093e-07,-2.76943e-08,0.732778,0.000646147,-4.12176e-07,2.17979e-08,0.733424,0.000645388,-3.46783e-07,1.07292e-10,0.734069,0.000644695,-3.46461e-07,-2.22271e-08,0.734713,0.000643935,-4.13142e-07,2.91963e-08,0.735357,0.000643197,-3.25553e-07,-3.49536e-08,0.736,0.000642441,-4.30414e-07,5.10133e-08,0.736642,0.000641733,-2.77374e-07,-4.98904e-08,0.737283,0.000641028,-4.27045e-07,2.93392e-08,0.737924,0.000640262,-3.39028e-07,-7.86156e-09,0.738564,0.000639561,-3.62612e-07,2.10703e-09,0.739203,0.000638842,-3.56291e-07,-5.6653e-10,0.739842,0.000638128,-3.57991e-07,1.59086e-10,0.740479,0.000637412,-3.57513e-07,-6.98321e-11,0.741116,0.000636697,-3.57723e-07,1.20214e-10,0.741753,0.000635982,-3.57362e-07,-4.10987e-10,0.742388,0.000635266,-3.58595e-07,1.5237e-09,0.743023,0.000634553,-3.54024e-07,-5.68376e-09,0.743657,0.000633828,-3.71075e-07,2.12113e-08,0.744291,0.00063315,-3.07441e-07,-1.95569e-08,0.744924,0.000632476,-3.66112e-07,-2.58816e-09,0.745556,0.000631736,-3.73877e-07,2.99096e-08,0.746187,0.000631078,-2.84148e-07,-5.74454e-08,0.746818,0.000630337,-4.56484e-07,8.06629e-08,0.747448,0.000629666,-2.14496e-07,-8.63922e-08,0.748077,0.000628978,-4.73672e-07,8.60918e-08,0.748706,0.000628289,-2.15397e-07,-7.91613e-08,0.749334,0.000627621,-4.5288e-07,5.17393e-08,0.749961,0.00062687,-2.97663e-07,-8.58662e-09,0.750588,0.000626249,-3.23422e-07,-1.73928e-08,0.751214,0.00062555,-3.75601e-07,1.85532e-08,0.751839,0.000624855,-3.19941e-07,2.78479e-09,0.752463,0.000624223,-3.11587e-07,-2.96923e-08,0.753087,0.000623511,-4.00664e-07,5.63799e-08,0.75371,0.000622879,-2.31524e-07,-7.66179e-08,0.754333,0.000622186,-4.61378e-07,7.12778e-08,0.754955,0.000621477,-2.47545e-07,-2.96794e-08,0.755576,0.000620893,-3.36583e-07,-1.21648e-08,0.756196,0.000620183,-3.73077e-07,1.87339e-08,0.756816,0.000619493,-3.16875e-07,-3.16622e-09,0.757435,0.00061885,-3.26374e-07,-6.0691e-09,0.758054,0.000618179,-3.44581e-07,2.74426e-08,0.758672,0.000617572,-2.62254e-07,-4.40968e-08,0.759289,0.000616915,-3.94544e-07,2.97352e-08,0.759906,0.000616215,-3.05338e-07,-1.52393e-08,0.760522,0.000615559,-3.51056e-07,3.12221e-08,0.761137,0.000614951,-2.5739e-07,-5.00443e-08,0.761751,0.000614286,-4.07523e-07,4.9746e-08,0.762365,0.00061362,-2.58285e-07,-2.97303e-08,0.762979,0.000613014,-3.47476e-07,9.57079e-09,0.763591,0.000612348,-3.18764e-07,-8.55287e-09,0.764203,0.000611685,-3.44422e-07,2.46407e-08,0.764815,0.00061107,-2.705e-07,-3.04053e-08,0.765426,0.000610437,-3.61716e-07,3.73759e-08,0.766036,0.000609826,-2.49589e-07,-5.94935e-08,0.766645,0.000609149,-4.28069e-07,8.13889e-08,0.767254,0.000608537,-1.83902e-07,-8.72483e-08,0.767862,0.000607907,-4.45647e-07,8.87901e-08,0.76847,0.000607282,-1.79277e-07,-8.90983e-08,0.769077,0.000606656,-4.46572e-07,8.87892e-08,0.769683,0.000606029,-1.80204e-07,-8.72446e-08,0.770289,0.000605407,-4.41938e-07,8.13752e-08,0.770894,0.000604768,-1.97812e-07,-5.94423e-08,0.771498,0.000604194,-3.76139e-07,3.71848e-08,0.772102,0.000603553,-2.64585e-07,-2.96922e-08,0.772705,0.000602935,-3.53661e-07,2.19793e-08,0.773308,0.000602293,-2.87723e-07,1.37955e-09,0.77391,0.000601722,-2.83585e-07,-2.74976e-08,0.774512,0.000601072,-3.66077e-07,4.9006e-08,0.775112,0.000600487,-2.19059e-07,-4.93171e-08,0.775712,0.000599901,-3.67011e-07,2.90531e-08,0.776312,0.000599254,-2.79851e-07,-7.29081e-09,0.776911,0.000598673,-3.01724e-07,1.10077e-10,0.777509,0.00059807,-3.01393e-07,6.85053e-09,0.778107,0.000597487,-2.80842e-07,-2.75123e-08,0.778704,0.000596843,-3.63379e-07,4.35939e-08,0.779301,0.000596247,-2.32597e-07,-2.7654e-08,0.779897,0.000595699,-3.15559e-07,7.41741e-09,0.780492,0.00059509,-2.93307e-07,-2.01562e-09,0.781087,0.000594497,-2.99354e-07,6.45059e-10,0.781681,0.000593901,-2.97418e-07,-5.64635e-10,0.782275,0.000593304,-2.99112e-07,1.61347e-09,0.782868,0.000592711,-2.94272e-07,-5.88926e-09,0.78346,0.000592105,-3.1194e-07,2.19436e-08,0.784052,0.000591546,-2.46109e-07,-2.22805e-08,0.784643,0.000590987,-3.1295e-07,7.57368e-09,0.785234,0.000590384,-2.90229e-07,-8.01428e-09,0.785824,0.00058978,-3.14272e-07,2.44834e-08,0.786414,0.000589225,-2.40822e-07,-3.03148e-08,0.787003,0.000588652,-3.31766e-07,3.7171e-08,0.787591,0.0005881,-2.20253e-07,-5.87646e-08,0.788179,0.000587483,-3.96547e-07,7.86782e-08,0.788766,0.000586926,-1.60512e-07,-7.71342e-08,0.789353,0.000586374,-3.91915e-07,5.10444e-08,0.789939,0.000585743,-2.38782e-07,-7.83422e-09,0.790524,0.000585242,-2.62284e-07,-1.97076e-08,0.791109,0.000584658,-3.21407e-07,2.70598e-08,0.791693,0.000584097,-2.40228e-07,-2.89269e-08,0.792277,0.000583529,-3.27008e-07,2.90431e-08,0.792861,0.000582963,-2.39879e-07,-2.76409e-08,0.793443,0.0005824,-3.22802e-07,2.1916e-08,0.794025,0.00058182,-2.57054e-07,-4.18368e-10,0.794607,0.000581305,-2.58309e-07,-2.02425e-08,0.795188,0.000580727,-3.19036e-07,2.17838e-08,0.795768,0.000580155,-2.53685e-07,-7.28814e-09,0.796348,0.000579625,-2.75549e-07,7.36871e-09,0.796928,0.000579096,-2.53443e-07,-2.21867e-08,0.797506,0.000578523,-3.20003e-07,2.17736e-08,0.798085,0.000577948,-2.54683e-07,-5.30296e-09,0.798662,0.000577423,-2.70592e-07,-5.61698e-10,0.799239,0.00057688,-2.72277e-07,7.54977e-09,0.799816,0.000576358,-2.49627e-07,-2.96374e-08,0.800392,0.00057577,-3.38539e-07,5.1395e-08,0.800968,0.000575247,-1.84354e-07,-5.67335e-08,0.801543,0.000574708,-3.54555e-07,5.63297e-08,0.802117,0.000574168,-1.85566e-07,-4.93759e-08,0.802691,0.000573649,-3.33693e-07,2.19646e-08,0.803264,0.000573047,-2.678e-07,2.1122e-08,0.803837,0.000572575,-2.04433e-07,-4.68482e-08,0.804409,0.000572026,-3.44978e-07,4.70613e-08,0.804981,0.000571477,-2.03794e-07,-2.21877e-08,0.805552,0.000571003,-2.70357e-07,-1.79153e-08,0.806123,0.000570408,-3.24103e-07,3.42443e-08,0.806693,0.000569863,-2.2137e-07,1.47556e-10,0.807263,0.000569421,-2.20928e-07,-3.48345e-08,0.807832,0.000568874,-3.25431e-07,1.99812e-08,0.808401,0.000568283,-2.65487e-07,1.45143e-08,0.808969,0.000567796,-2.21945e-07,-1.84338e-08,0.809536,0.000567297,-2.77246e-07,-3.83608e-10,0.810103,0.000566741,-2.78397e-07,1.99683e-08,0.81067,0.000566244,-2.18492e-07,-1.98848e-08,0.811236,0.000565747,-2.78146e-07,-3.38976e-11,0.811801,0.000565191,-2.78248e-07,2.00204e-08,0.812366,0.000564695,-2.18187e-07,-2.04429e-08,0.812931,0.000564197,-2.79516e-07,2.1467e-09,0.813495,0.000563644,-2.73076e-07,1.18561e-08,0.814058,0.000563134,-2.37507e-07,1.00334e-08,0.814621,0.000562689,-2.07407e-07,-5.19898e-08,0.815183,0.000562118,-3.63376e-07,7.87163e-08,0.815745,0.000561627,-1.27227e-07,-8.40616e-08,0.816306,0.000561121,-3.79412e-07,7.87163e-08,0.816867,0.000560598,-1.43263e-07,-5.19898e-08,0.817428,0.000560156,-2.99233e-07,1.00335e-08,0.817988,0.000559587,-2.69132e-07,1.18559e-08,0.818547,0.000559085,-2.33564e-07,2.14764e-09,0.819106,0.000558624,-2.27122e-07,-2.04464e-08,0.819664,0.000558108,-2.88461e-07,2.00334e-08,0.820222,0.000557591,-2.28361e-07,-8.24277e-11,0.820779,0.000557135,-2.28608e-07,-1.97037e-08,0.821336,0.000556618,-2.87719e-07,1.92925e-08,0.821893,0.000556101,-2.29841e-07,2.13831e-09,0.822448,0.000555647,-2.23427e-07,-2.78458e-08,0.823004,0.000555117,-3.06964e-07,4.96402e-08,0.823559,0.000554652,-1.58043e-07,-5.15058e-08,0.824113,0.000554181,-3.12561e-07,3.71737e-08,0.824667,0.000553668,-2.0104e-07,-3.75844e-08,0.82522,0.000553153,-3.13793e-07,5.35592e-08,0.825773,0.000552686,-1.53115e-07,-5.74431e-08,0.826326,0.000552207,-3.25444e-07,5.7004e-08,0.826878,0.000551728,-1.54433e-07,-5.13635e-08,0.827429,0.000551265,-3.08523e-07,2.92406e-08,0.82798,0.000550735,-2.20801e-07,-5.99424e-09,0.828531,0.000550276,-2.38784e-07,-5.26363e-09,0.829081,0.000549782,-2.54575e-07,2.70488e-08,0.82963,0.000549354,-1.73429e-07,-4.33268e-08,0.83018,0.000548878,-3.03409e-07,2.7049e-08,0.830728,0.000548352,-2.22262e-07,-5.26461e-09,0.831276,0.000547892,-2.38056e-07,-5.99057e-09,0.831824,0.000547397,-2.56027e-07,2.92269e-08,0.832371,0.000546973,-1.68347e-07,-5.13125e-08,0.832918,0.000546482,-3.22284e-07,5.68139e-08,0.833464,0.000546008,-1.51843e-07,-5.67336e-08,0.83401,0.000545534,-3.22043e-07,5.09113e-08,0.834555,0.000545043,-1.6931e-07,-2.77022e-08,0.8351,0.000544621,-2.52416e-07,2.92924e-10,0.835644,0.000544117,-2.51537e-07,2.65305e-08,0.836188,0.000543694,-1.71946e-07,-4.68105e-08,0.836732,0.00054321,-3.12377e-07,4.15021e-08,0.837275,0.000542709,-1.87871e-07,1.13355e-11,0.837817,0.000542334,-1.87837e-07,-4.15474e-08,0.838359,0.000541833,-3.12479e-07,4.69691e-08,0.838901,0.000541349,-1.71572e-07,-2.71196e-08,0.839442,0.000540925,-2.52931e-07,1.90462e-09,0.839983,0.000540425,-2.47217e-07,1.95011e-08,0.840523,0.000539989,-1.88713e-07,-2.03045e-08,0.841063,0.00053955,-2.49627e-07,2.11216e-09,0.841602,0.000539057,-2.4329e-07,1.18558e-08,0.842141,0.000538606,-2.07723e-07,1.00691e-08,0.842679,0.000538221,-1.77516e-07,-5.21324e-08,0.843217,0.00053771,-3.33913e-07,7.92513e-08,0.843755,0.00053728,-9.6159e-08,-8.60587e-08,0.844292,0.000536829,-3.54335e-07,8.61696e-08,0.844828,0.000536379,-9.58263e-08,-7.98057e-08,0.845364,0.000535948,-3.35243e-07,5.42394e-08,0.8459,0.00053544,-1.72525e-07,-1.79426e-08,0.846435,0.000535041,-2.26353e-07,1.75308e-08,0.84697,0.000534641,-1.73761e-07,-5.21806e-08,0.847505,0.000534137,-3.30302e-07,7.19824e-08,0.848038,0.000533692,-1.14355e-07,-5.69349e-08,0.848572,0.000533293,-2.8516e-07,3.65479e-08,0.849105,0.000532832,-1.75516e-07,-2.96519e-08,0.849638,0.000532392,-2.64472e-07,2.2455e-08,0.85017,0.000531931,-1.97107e-07,-5.63451e-10,0.850702,0.000531535,-1.98797e-07,-2.02011e-08,0.851233,0.000531077,-2.59401e-07,2.17634e-08,0.851764,0.000530623,-1.94111e-07,-7.24794e-09,0.852294,0.000530213,-2.15854e-07,7.22832e-09,0.852824,0.000529803,-1.94169e-07,-2.16653e-08,0.853354,0.00052935,-2.59165e-07,1.98283e-08,0.853883,0.000528891,-1.9968e-07,1.95678e-09,0.854412,0.000528497,-1.9381e-07,-2.76554e-08,0.85494,0.000528027,-2.76776e-07,4.90603e-08,0.855468,0.00052762,-1.29596e-07,-4.93764e-08,0.855995,0.000527213,-2.77725e-07,2.92361e-08,0.856522,0.000526745,-1.90016e-07,-7.96341e-09,0.857049,0.000526341,-2.13907e-07,2.61752e-09,0.857575,0.000525922,-2.06054e-07,-2.50665e-09,0.8581,0.000525502,-2.13574e-07,7.40906e-09,0.858626,0.000525097,-1.91347e-07,-2.71296e-08,0.859151,0.000524633,-2.72736e-07,4.15048e-08,0.859675,0.000524212,-1.48221e-07,-1.96802e-08,0.860199,0.000523856,-2.07262e-07,-2.23886e-08,0.860723,0.000523375,-2.74428e-07,4.96299e-08,0.861246,0.000522975,-1.25538e-07,-5.69216e-08,0.861769,0.000522553,-2.96303e-07,5.88473e-08,0.862291,0.000522137,-1.19761e-07,-5.92584e-08,0.862813,0.00052172,-2.97536e-07,5.8977e-08,0.863334,0.000521301,-1.20605e-07,-5.74403e-08,0.863855,0.000520888,-2.92926e-07,5.15751e-08,0.864376,0.000520457,-1.38201e-07,-2.96506e-08,0.864896,0.000520091,-2.27153e-07,7.42277e-09,0.865416,0.000519659,-2.04885e-07,-4.05057e-11,0.865936,0.00051925,-2.05006e-07,-7.26074e-09,0.866455,0.000518818,-2.26788e-07,2.90835e-08,0.866973,0.000518451,-1.39538e-07,-4.94686e-08,0.867492,0.000518024,-2.87944e-07,4.95814e-08,0.868009,0.000517597,-1.39199e-07,-2.96479e-08,0.868527,0.000517229,-2.28143e-07,9.40539e-09,0.869044,0.000516801,-1.99927e-07,-7.9737e-09,0.86956,0.000516378,-2.23848e-07,2.24894e-08,0.870077,0.000515997,-1.5638e-07,-2.23793e-08,0.870592,0.000515617,-2.23517e-07,7.42302e-09,0.871108,0.000515193,-2.01248e-07,-7.31283e-09,0.871623,0.000514768,-2.23187e-07,2.18283e-08,0.872137,0.000514387,-1.57702e-07,-2.03959e-08,0.872652,0.000514011,-2.1889e-07,1.50711e-10,0.873165,0.000513573,-2.18437e-07,1.97931e-08,0.873679,0.000513196,-1.59058e-07,-1.97183e-08,0.874192,0.000512819,-2.18213e-07,-5.24324e-10,0.874704,0.000512381,-2.19786e-07,2.18156e-08,0.875217,0.000512007,-1.54339e-07,-2.71336e-08,0.875728,0.000511616,-2.3574e-07,2.71141e-08,0.87624,0.000511226,-1.54398e-07,-2.17182e-08,0.876751,0.000510852,-2.19552e-07,1.54131e-10,0.877262,0.000510414,-2.1909e-07,2.11017e-08,0.877772,0.000510039,-1.55785e-07,-2.49562e-08,0.878282,0.000509652,-2.30654e-07,1.91183e-08,0.878791,0.000509248,-1.73299e-07,8.08751e-09,0.8793,0.000508926,-1.49036e-07,-5.14684e-08,0.879809,0.000508474,-3.03441e-07,7.85766e-08,0.880317,0.000508103,-6.77112e-08,-8.40242e-08,0.880825,0.000507715,-3.19784e-07,7.87063e-08,0.881333,0.000507312,-8.36649e-08,-5.19871e-08,0.88184,0.000506988,-2.39626e-07,1.00327e-08,0.882346,0.000506539,-2.09528e-07,1.18562e-08,0.882853,0.000506156,-1.73959e-07,2.14703e-09,0.883359,0.000505814,-1.67518e-07,-2.04444e-08,0.883864,0.000505418,-2.28851e-07,2.00258e-08,0.88437,0.00050502,-1.68774e-07,-5.42855e-11,0.884874,0.000504682,-1.68937e-07,-1.98087e-08,0.885379,0.000504285,-2.28363e-07,1.96842e-08,0.885883,0.000503887,-1.6931e-07,6.76342e-10,0.886387,0.000503551,-1.67281e-07,-2.23896e-08,0.88689,0.000503149,-2.3445e-07,2.92774e-08,0.887393,0.000502768,-1.46618e-07,-3.51152e-08,0.887896,0.00050237,-2.51963e-07,5.15787e-08,0.888398,0.00050202,-9.72271e-08,-5.19903e-08,0.8889,0.00050167,-2.53198e-07,3.71732e-08,0.889401,0.000501275,-1.41678e-07,-3.70978e-08,0.889902,0.00050088,-2.52972e-07,5.16132e-08,0.890403,0.000500529,-9.81321e-08,-5.01459e-08,0.890903,0.000500183,-2.4857e-07,2.9761e-08,0.891403,0.000499775,-1.59287e-07,-9.29351e-09,0.891903,0.000499428,-1.87167e-07,7.41301e-09,0.892402,0.000499076,-1.64928e-07,-2.03585e-08,0.892901,0.000498685,-2.26004e-07,1.44165e-08,0.893399,0.000498276,-1.82754e-07,2.22974e-08,0.893898,0.000497978,-1.15862e-07,-4.40013e-08,0.894395,0.000497614,-2.47866e-07,3.44985e-08,0.894893,0.000497222,-1.44371e-07,-3.43882e-08,0.89539,0.00049683,-2.47535e-07,4.34497e-08,0.895886,0.000496465,-1.17186e-07,-2.02012e-08,0.896383,0.00049617,-1.7779e-07,-2.22497e-08,0.896879,0.000495748,-2.44539e-07,4.95952e-08,0.897374,0.000495408,-9.57532e-08,-5.69217e-08,0.89787,0.000495045,-2.66518e-07,5.88823e-08,0.898364,0.000494689,-8.98713e-08,-5.93983e-08,0.898859,0.000494331,-2.68066e-07,5.95017e-08,0.899353,0.000493973,-8.95613e-08,-5.9399e-08,0.899847,0.000493616,-2.67758e-07,5.8885e-08,0.90034,0.000493257,-9.11033e-08,-5.69317e-08,0.900833,0.000492904,-2.61898e-07,4.96326e-08,0.901326,0.000492529,-1.13001e-07,-2.23893e-08,0.901819,0.000492236,-1.80169e-07,-1.968e-08,0.902311,0.000491817,-2.39209e-07,4.15047e-08,0.902802,0.000491463,-1.14694e-07,-2.71296e-08,0.903293,0.000491152,-1.96083e-07,7.409e-09,0.903784,0.000490782,-1.73856e-07,-2.50645e-09,0.904275,0.000490427,-1.81376e-07,2.61679e-09,0.904765,0.000490072,-1.73525e-07,-7.96072e-09,0.905255,0.000489701,-1.97407e-07,2.92261e-08,0.905745,0.000489394,-1.09729e-07,-4.93389e-08,0.906234,0.000489027,-2.57746e-07,4.89204e-08,0.906723,0.000488658,-1.10985e-07,-2.71333e-08,0.907211,0.000488354,-1.92385e-07,8.30861e-12,0.907699,0.00048797,-1.9236e-07,2.71001e-08,0.908187,0.000487666,-1.1106e-07,-4.88041e-08,0.908675,0.000487298,-2.57472e-07,4.89069e-08,0.909162,0.000486929,-1.10751e-07,-2.76143e-08,0.909649,0.000486625,-1.93594e-07,1.9457e-09,0.910135,0.000486244,-1.87757e-07,1.98315e-08,0.910621,0.000485928,-1.28262e-07,-2.16671e-08,0.911107,0.000485606,-1.93264e-07,7.23216e-09,0.911592,0.000485241,-1.71567e-07,-7.26152e-09,0.912077,0.000484877,-1.93352e-07,2.18139e-08,0.912562,0.000484555,-1.2791e-07,-2.03895e-08,0.913047,0.000484238,-1.89078e-07,1.39494e-10,0.913531,0.000483861,-1.8866e-07,1.98315e-08,0.914014,0.000483543,-1.29165e-07,-1.98609e-08,0.914498,0.000483225,-1.88748e-07,7.39912e-12,0.914981,0.000482847,-1.88726e-07,1.98313e-08,0.915463,0.000482529,-1.29232e-07,-1.9728e-08,0.915946,0.000482212,-1.88416e-07,-5.24035e-10,0.916428,0.000481833,-1.89988e-07,2.18241e-08,0.916909,0.000481519,-1.24516e-07,-2.71679e-08,0.917391,0.000481188,-2.06019e-07,2.72427e-08,0.917872,0.000480858,-1.24291e-07,-2.21985e-08,0.918353,0.000480543,-1.90886e-07,1.94644e-09,0.918833,0.000480167,-1.85047e-07,1.44127e-08,0.919313,0.00047984,-1.41809e-07,7.39438e-12,0.919793,0.000479556,-1.41787e-07,-1.44423e-08,0.920272,0.000479229,-1.85114e-07,-1.84291e-09,0.920751,0.000478854,-1.90642e-07,2.18139e-08,0.92123,0.000478538,-1.25201e-07,-2.58081e-08,0.921708,0.00047821,-2.02625e-07,2.18139e-08,0.922186,0.00047787,-1.37183e-07,-1.84291e-09,0.922664,0.00047759,-1.42712e-07,-1.44423e-08,0.923141,0.000477262,-1.86039e-07,7.34701e-12,0.923618,0.00047689,-1.86017e-07,1.44129e-08,0.924095,0.000476561,-1.42778e-07,1.94572e-09,0.924572,0.000476281,-1.36941e-07,-2.21958e-08,0.925048,0.000475941,-2.03528e-07,2.72327e-08,0.925523,0.000475615,-1.2183e-07,-2.71304e-08,0.925999,0.00047529,-2.03221e-07,2.16843e-08,0.926474,0.000474949,-1.38168e-07,-2.16005e-12,0.926949,0.000474672,-1.38175e-07,-2.16756e-08,0.927423,0.000474331,-2.03202e-07,2.71001e-08,0.927897,0.000474006,-1.21902e-07,-2.71201e-08,0.928371,0.000473681,-2.03262e-07,2.17757e-08,0.928845,0.00047334,-1.37935e-07,-3.78028e-10,0.929318,0.000473063,-1.39069e-07,-2.02636e-08,0.929791,0.000472724,-1.9986e-07,2.18276e-08,0.930263,0.000472389,-1.34377e-07,-7.44231e-09,0.930736,0.000472098,-1.56704e-07,7.94165e-09,0.931208,0.000471809,-1.32879e-07,-2.43243e-08,0.931679,0.00047147,-2.05851e-07,2.97508e-08,0.932151,0.000471148,-1.16599e-07,-3.50742e-08,0.932622,0.000470809,-2.21822e-07,5.09414e-08,0.933092,0.000470518,-6.89976e-08,-4.94821e-08,0.933563,0.000470232,-2.17444e-07,2.77775e-08,0.934033,0.00046988,-1.34111e-07,-2.02351e-09,0.934502,0.000469606,-1.40182e-07,-1.96835e-08,0.934972,0.000469267,-1.99232e-07,2.11529e-08,0.935441,0.000468932,-1.35774e-07,-5.32332e-09,0.93591,0.000468644,-1.51743e-07,1.40413e-10,0.936378,0.000468341,-1.51322e-07,4.76166e-09,0.936846,0.000468053,-1.37037e-07,-1.9187e-08,0.937314,0.000467721,-1.94598e-07,1.23819e-08,0.937782,0.000467369,-1.57453e-07,2.92642e-08,0.938249,0.000467142,-6.96601e-08,-6.98342e-08,0.938716,0.000466793,-2.79163e-07,7.12586e-08,0.939183,0.000466449,-6.53869e-08,-3.63863e-08,0.939649,0.000466209,-1.74546e-07,1.46818e-08,0.940115,0.000465904,-1.305e-07,-2.2341e-08,0.940581,0.000465576,-1.97523e-07,1.50774e-08,0.941046,0.000465226,-1.52291e-07,2.16359e-08,0.941511,0.000464986,-8.73832e-08,-4.20162e-08,0.941976,0.000464685,-2.13432e-07,2.72198e-08,0.942441,0.00046434,-1.31773e-07,-7.2581e-09,0.942905,0.000464055,-1.53547e-07,1.81263e-09,0.943369,0.000463753,-1.48109e-07,7.58386e-12,0.943832,0.000463457,-1.48086e-07,-1.84298e-09,0.944296,0.000463155,-1.53615e-07,7.36433e-09,0.944759,0.00046287,-1.31522e-07,-2.76143e-08,0.945221,0.000462524,-2.14365e-07,4.34883e-08,0.945684,0.000462226,-8.39003e-08,-2.71297e-08,0.946146,0.000461977,-1.65289e-07,5.42595e-09,0.946608,0.000461662,-1.49012e-07,5.42593e-09,0.947069,0.000461381,-1.32734e-07,-2.71297e-08,0.94753,0.000461034,-2.14123e-07,4.34881e-08,0.947991,0.000460736,-8.36585e-08,-2.76134e-08,0.948452,0.000460486,-1.66499e-07,7.36083e-09,0.948912,0.000460175,-1.44416e-07,-1.82993e-09,0.949372,0.000459881,-1.49906e-07,-4.11073e-11,0.949832,0.000459581,-1.50029e-07,1.99434e-09,0.950291,0.000459287,-1.44046e-07,-7.93627e-09,0.950751,0.000458975,-1.67855e-07,2.97507e-08,0.951209,0.000458728,-7.86029e-08,-5.1462e-08,0.951668,0.000458417,-2.32989e-07,5.6888e-08,0.952126,0.000458121,-6.2325e-08,-5.68806e-08,0.952584,0.000457826,-2.32967e-07,5.14251e-08,0.953042,0.000457514,-7.86914e-08,-2.96107e-08,0.953499,0.000457268,-1.67523e-07,7.41296e-09,0.953956,0.000456955,-1.45285e-07,-4.11262e-11,0.954413,0.000456665,-1.45408e-07,-7.24847e-09,0.95487,0.000456352,-1.67153e-07,2.9035e-08,0.955326,0.000456105,-8.00484e-08,-4.92869e-08,0.955782,0.000455797,-2.27909e-07,4.89032e-08,0.956238,0.000455488,-8.11994e-08,-2.71166e-08,0.956693,0.000455244,-1.62549e-07,-4.13678e-11,0.957148,0.000454919,-1.62673e-07,2.72821e-08,0.957603,0.000454675,-8.0827e-08,-4.94824e-08,0.958057,0.000454365,-2.29274e-07,5.14382e-08,0.958512,0.000454061,-7.49597e-08,-3.7061e-08,0.958965,0.0004538,-1.86143e-07,3.72013e-08,0.959419,0.000453539,-7.45389e-08,-5.21396e-08,0.959873,0.000453234,-2.30958e-07,5.21476e-08,0.960326,0.000452928,-7.45146e-08,-3.72416e-08,0.960778,0.000452667,-1.8624e-07,3.72143e-08,0.961231,0.000452407,-7.45967e-08,-5.20109e-08,0.961683,0.000452101,-2.30629e-07,5.16199e-08,0.962135,0.000451795,-7.57696e-08,-3.52595e-08,0.962587,0.000451538,-1.81548e-07,2.98133e-08,0.963038,0.000451264,-9.2108e-08,-2.43892e-08,0.963489,0.000451007,-1.65276e-07,8.13892e-09,0.96394,0.000450701,-1.40859e-07,-8.16647e-09,0.964391,0.000450394,-1.65358e-07,2.45269e-08,0.964841,0.000450137,-9.17775e-08,-3.03367e-08,0.965291,0.000449863,-1.82787e-07,3.7215e-08,0.965741,0.000449609,-7.11424e-08,-5.89188e-08,0.96619,0.00044929,-2.47899e-07,7.92509e-08,0.966639,0.000449032,-1.01462e-08,-7.92707e-08,0.967088,0.000448773,-2.47958e-07,5.90181e-08,0.967537,0.000448455,-7.0904e-08,-3.75925e-08,0.967985,0.0004482,-1.83681e-07,3.17471e-08,0.968433,0.000447928,-8.84401e-08,-2.97913e-08,0.968881,0.000447662,-1.77814e-07,2.78133e-08,0.969329,0.000447389,-9.4374e-08,-2.18572e-08,0.969776,0.000447135,-1.59946e-07,1.10134e-11,0.970223,0.000446815,-1.59913e-07,2.18132e-08,0.97067,0.000446561,-9.44732e-08,-2.76591e-08,0.971116,0.000446289,-1.7745e-07,2.92185e-08,0.971562,0.000446022,-8.97948e-08,-2.96104e-08,0.972008,0.000445753,-1.78626e-07,2.96185e-08,0.972454,0.000445485,-8.97706e-08,-2.92588e-08,0.972899,0.000445218,-1.77547e-07,2.78123e-08,0.973344,0.000444946,-9.41103e-08,-2.23856e-08,0.973789,0.000444691,-1.61267e-07,2.12559e-09,0.974233,0.000444374,-1.5489e-07,1.38833e-08,0.974678,0.000444106,-1.13241e-07,1.94591e-09,0.975122,0.000443886,-1.07403e-07,-2.16669e-08,0.975565,0.000443606,-1.72404e-07,2.5117e-08,0.976009,0.000443336,-9.70526e-08,-1.91963e-08,0.976452,0.000443085,-1.54642e-07,-7.93627e-09,0.976895,0.000442752,-1.7845e-07,5.09414e-08,0.977338,0.000442548,-2.56262e-08,-7.66201e-08,0.97778,0.000442266,-2.55486e-07,7.67249e-08,0.978222,0.000441986,-2.53118e-08,-5.14655e-08,0.978664,0.000441781,-1.79708e-07,9.92773e-09,0.979106,0.000441451,-1.49925e-07,1.17546e-08,0.979547,0.000441186,-1.14661e-07,2.65868e-09,0.979988,0.000440965,-1.06685e-07,-2.23893e-08,0.980429,0.000440684,-1.73853e-07,2.72939e-08,0.980869,0.000440419,-9.19716e-08,-2.71816e-08,0.98131,0.000440153,-1.73516e-07,2.18278e-08,0.98175,0.000439872,-1.08033e-07,-5.24833e-10,0.982189,0.000439654,-1.09607e-07,-1.97284e-08,0.982629,0.000439376,-1.68793e-07,1.98339e-08,0.983068,0.000439097,-1.09291e-07,-2.62901e-12,0.983507,0.000438879,-1.09299e-07,-1.98234e-08,0.983946,0.000438601,-1.68769e-07,1.96916e-08,0.984384,0.000438322,-1.09694e-07,6.6157e-10,0.984823,0.000438105,-1.0771e-07,-2.23379e-08,0.985261,0.000437823,-1.74723e-07,2.90855e-08,0.985698,0.00043756,-8.74669e-08,-3.43992e-08,0.986136,0.000437282,-1.90665e-07,4.89068e-08,0.986573,0.000437048,-4.39442e-08,-4.20188e-08,0.98701,0.000436834,-1.7e-07,-4.11073e-11,0.987446,0.000436494,-1.70124e-07,4.21832e-08,0.987883,0.00043628,-4.35742e-08,-4.94824e-08,0.988319,0.000436044,-1.92021e-07,3.6537e-08,0.988755,0.00043577,-8.24102e-08,-3.70611e-08,0.989191,0.000435494,-1.93593e-07,5.21026e-08,0.989626,0.000435263,-3.72855e-08,-5.21402e-08,0.990061,0.000435032,-1.93706e-07,3.7249e-08,0.990496,0.000434756,-8.19592e-08,-3.72512e-08,0.990931,0.000434481,-1.93713e-07,5.21511e-08,0.991365,0.00043425,-3.72595e-08,-5.21439e-08,0.991799,0.000434019,-1.93691e-07,3.72152e-08,0.992233,0.000433743,-8.20456e-08,-3.71123e-08,0.992667,0.000433468,-1.93382e-07,5.16292e-08,0.9931,0.000433236,-3.84947e-08,-5.01953e-08,0.993533,0.000433008,-1.89081e-07,2.99427e-08,0.993966,0.00043272,-9.92525e-08,-9.9708e-09,0.994399,0.000432491,-1.29165e-07,9.94051e-09,0.994831,0.000432263,-9.93434e-08,-2.97912e-08,0.995263,0.000431975,-1.88717e-07,4.96198e-08,0.995695,0.000431746,-3.98578e-08,-4.94785e-08,0.996127,0.000431518,-1.88293e-07,2.9085e-08,0.996558,0.000431229,-1.01038e-07,-7.25675e-09,0.996989,0.000431005,-1.22809e-07,-5.79945e-11,0.99742,0.000430759,-1.22983e-07,7.48873e-09,0.997851,0.000430536,-1.00516e-07,-2.98969e-08,0.998281,0.000430245,-1.90207e-07,5.24942e-08,0.998711,0.000430022,-3.27246e-08,-6.08706e-08,0.999141,0.000429774,-2.15336e-07,7.17788e-08,0.999571,0.000429392,0.,0.}; + + template + __device__ __forceinline__ void Lab2RGBConvert_f(const T& src, D& dst) + { + const float lThresh = 0.008856f * 903.3f; + const float fThresh = 7.787f * 0.008856f + 16.0f / 116.0f; + + float Y, fy; + + if (src.x <= lThresh) + { + Y = src.x / 903.3f; + fy = 7.787f * Y + 16.0f / 116.0f; + } + else + { + fy = (src.x + 16.0f) / 116.0f; + Y = fy * fy * fy; + } + + float X = src.y / 500.0f + fy; + float Z = fy - src.z / 200.0f; + + if (X <= fThresh) + X = (X - 16.0f / 116.0f) / 7.787f; + else + X = X * X * X; + + if (Z <= fThresh) + Z = (Z - 16.0f / 116.0f) / 7.787f; + else + Z = Z * Z * Z; + + float B = 0.052891f * X - 0.204043f * Y + 1.151152f * Z; + float G = -0.921235f * X + 1.875991f * Y + 0.045244f * Z; + float R = 3.079933f * X - 1.537150f * Y - 0.542782f * Z; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + } + + dst.x = blueIdx == 0 ? B : R; + dst.y = G; + dst.z = blueIdx == 0 ? R : B; + setAlpha(dst, ColorChannel::max()); + } + + template + __device__ __forceinline__ void Lab2RGBConvert_b(const T& src, D& dst) + { + float3 srcf, dstf; + + srcf.x = src.x * (100.f / 255.f); + srcf.y = src.y - 128; + srcf.z = src.z - 128; + + Lab2RGBConvert_f(srcf, dstf); + + dst.x = saturate_cast(dstf.x * 255.f); + dst.y = saturate_cast(dstf.y * 255.f); + dst.z = saturate_cast(dstf.z * 255.f); + setAlpha(dst, ColorChannel::max()); + } + + template struct Lab2RGB; + template + struct Lab2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Lab2RGBConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Lab2RGB() {} + __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} + }; + template + struct Lab2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Lab2RGBConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Lab2RGB() {} + __host__ __device__ __forceinline__ Lab2RGB(const Lab2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_Lab2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Lab2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + +///////////////////////////////////// RGB <-> Luv ///////////////////////////////////// + + namespace color_detail + { + __constant__ float c_LabCbrtTab[] = {0.137931,0.0114066,0.,1.18859e-07,0.149338,0.011407,3.56578e-07,-5.79396e-07,0.160745,0.0114059,-1.38161e-06,2.16892e-06,0.172151,0.0114097,5.12516e-06,-8.0814e-06,0.183558,0.0113957,-1.9119e-05,3.01567e-05,0.194965,0.0114479,7.13509e-05,-0.000112545,0.206371,0.011253,-0.000266285,-0.000106493,0.217252,0.0104009,-0.000585765,7.32149e-05,0.22714,0.00944906,-0.00036612,1.21917e-05,0.236235,0.0087534,-0.000329545,2.01753e-05,0.244679,0.00815483,-0.000269019,1.24435e-05,0.252577,0.00765412,-0.000231689,1.05618e-05,0.26001,0.00722243,-0.000200003,8.26662e-06,0.267041,0.00684723,-0.000175203,6.76746e-06,0.27372,0.00651712,-0.000154901,5.61192e-06,0.280088,0.00622416,-0.000138065,4.67009e-06,0.286179,0.00596204,-0.000124055,3.99012e-06,0.292021,0.0057259,-0.000112085,3.36032e-06,0.297638,0.00551181,-0.000102004,2.95338e-06,0.30305,0.00531666,-9.31435e-05,2.52875e-06,0.308277,0.00513796,-8.55572e-05,2.22022e-06,0.313331,0.00497351,-7.88966e-05,1.97163e-06,0.318228,0.00482163,-7.29817e-05,1.7248e-06,0.322978,0.00468084,-6.78073e-05,1.55998e-06,0.327593,0.0045499,-6.31274e-05,1.36343e-06,0.332081,0.00442774,-5.90371e-05,1.27136e-06,0.336451,0.00431348,-5.5223e-05,1.09111e-06,0.34071,0.00420631,-5.19496e-05,1.0399e-06,0.344866,0.00410553,-4.88299e-05,9.18347e-07,0.348923,0.00401062,-4.60749e-05,8.29942e-07,0.352889,0.00392096,-4.35851e-05,7.98478e-07,0.356767,0.00383619,-4.11896e-05,6.84917e-07,0.360562,0.00375586,-3.91349e-05,6.63976e-07,0.36428,0.00367959,-3.7143e-05,5.93086e-07,0.367923,0.00360708,-3.53637e-05,5.6976e-07,0.371495,0.00353806,-3.36544e-05,4.95533e-07,0.375,0.00347224,-3.21678e-05,4.87951e-07,0.378441,0.00340937,-3.0704e-05,4.4349e-07,0.38182,0.00334929,-2.93735e-05,4.20297e-07,0.38514,0.0032918,-2.81126e-05,3.7872e-07,0.388404,0.00323671,-2.69764e-05,3.596e-07,0.391614,0.00318384,-2.58976e-05,3.5845e-07,0.394772,0.00313312,-2.48223e-05,2.92765e-07,0.397881,0.00308435,-2.3944e-05,3.18232e-07,0.400942,0.00303742,-2.29893e-05,2.82046e-07,0.403957,0.00299229,-2.21432e-05,2.52315e-07,0.406927,0.00294876,-2.13862e-05,2.58416e-07,0.409855,0.00290676,-2.0611e-05,2.33939e-07,0.412741,0.00286624,-1.99092e-05,2.36342e-07,0.415587,0.00282713,-1.92001e-05,1.916e-07,0.418396,0.00278931,-1.86253e-05,2.1915e-07,0.421167,0.00275271,-1.79679e-05,1.83498e-07,0.423901,0.00271733,-1.74174e-05,1.79343e-07,0.426602,0.00268303,-1.68794e-05,1.72013e-07,0.429268,0.00264979,-1.63633e-05,1.75686e-07,0.431901,0.00261759,-1.58363e-05,1.3852e-07,0.434503,0.00258633,-1.54207e-05,1.64304e-07,0.437074,0.00255598,-1.49278e-05,1.28136e-07,0.439616,0.00252651,-1.45434e-05,1.57618e-07,0.442128,0.0024979,-1.40705e-05,1.0566e-07,0.444612,0.00247007,-1.37535e-05,1.34998e-07,0.447068,0.00244297,-1.33485e-05,1.29207e-07,0.449498,0.00241666,-1.29609e-05,9.32347e-08,0.451902,0.00239102,-1.26812e-05,1.23703e-07,0.45428,0.00236603,-1.23101e-05,9.74072e-08,0.456634,0.0023417,-1.20179e-05,1.12518e-07,0.458964,0.002318,-1.16803e-05,7.83681e-08,0.46127,0.00229488,-1.14452e-05,1.10452e-07,0.463554,0.00227232,-1.11139e-05,7.58719e-08,0.465815,0.00225032,-1.08863e-05,9.2699e-08,0.468055,0.00222882,-1.06082e-05,8.97738e-08,0.470273,0.00220788,-1.03388e-05,5.4845e-08,0.47247,0.00218736,-1.01743e-05,1.0808e-07,0.474648,0.00216734,-9.85007e-06,4.9277e-08,0.476805,0.00214779,-9.70224e-06,8.22408e-08,0.478943,0.00212863,-9.45551e-06,6.87942e-08,0.481063,0.00210993,-9.24913e-06,5.98144e-08,0.483163,0.00209161,-9.06969e-06,7.93789e-08,0.485246,0.00207371,-8.83155e-06,3.99032e-08,0.487311,0.00205616,-8.71184e-06,8.88325e-08,0.489358,0.002039,-8.44534e-06,2.20004e-08,0.491389,0.00202218,-8.37934e-06,9.13872e-08,0.493403,0.0020057,-8.10518e-06,2.96829e-08,0.495401,0.00198957,-8.01613e-06,5.81028e-08,0.497382,0.00197372,-7.84183e-06,6.5731e-08,0.499348,0.00195823,-7.64463e-06,3.66019e-08,0.501299,0.00194305,-7.53483e-06,2.62811e-08,0.503234,0.00192806,-7.45598e-06,9.66907e-08,0.505155,0.00191344,-7.16591e-06,4.18928e-09,0.507061,0.00189912,-7.15334e-06,6.53665e-08,0.508953,0.00188501,-6.95724e-06,3.23686e-08,0.510831,0.00187119,-6.86014e-06,4.35774e-08,0.512696,0.0018576,-6.72941e-06,3.17406e-08,0.514547,0.00184424,-6.63418e-06,6.78785e-08,0.516384,0.00183117,-6.43055e-06,-5.23126e-09,0.518209,0.0018183,-6.44624e-06,7.22562e-08,0.520021,0.00180562,-6.22947e-06,1.42292e-08,0.52182,0.0017932,-6.18679e-06,4.9641e-08,0.523607,0.00178098,-6.03786e-06,2.56259e-08,0.525382,0.00176898,-5.96099e-06,2.66696e-08,0.527145,0.00175714,-5.88098e-06,4.65094e-08,0.528897,0.00174552,-5.74145e-06,2.57114e-08,0.530637,0.00173411,-5.66431e-06,2.94588e-08,0.532365,0.00172287,-5.57594e-06,3.52667e-08,0.534082,0.00171182,-5.47014e-06,8.28868e-09,0.535789,0.00170091,-5.44527e-06,5.07871e-08,0.537484,0.00169017,-5.29291e-06,2.69817e-08,0.539169,0.00167967,-5.21197e-06,2.01009e-08,0.540844,0.0016693,-5.15166e-06,1.18237e-08,0.542508,0.00165903,-5.11619e-06,5.18135e-08,0.544162,0.00164896,-4.96075e-06,1.9341e-08,0.545806,0.00163909,-4.90273e-06,-9.96867e-09,0.54744,0.00162926,-4.93263e-06,8.01382e-08,0.549064,0.00161963,-4.69222e-06,-1.25601e-08,0.550679,0.00161021,-4.7299e-06,2.97067e-08,0.552285,0.00160084,-4.64078e-06,1.29426e-08,0.553881,0.0015916,-4.60195e-06,3.77327e-08,0.555468,0.00158251,-4.48875e-06,1.49412e-08,0.557046,0.00157357,-4.44393e-06,2.17118e-08,0.558615,0.00156475,-4.3788e-06,1.74206e-08,0.560176,0.00155605,-4.32653e-06,2.78152e-08,0.561727,0.00154748,-4.24309e-06,-9.47239e-09,0.563271,0.00153896,-4.27151e-06,6.9679e-08,0.564805,0.00153063,-4.06247e-06,-3.08246e-08,0.566332,0.00152241,-4.15494e-06,5.36188e-08,0.56785,0.00151426,-3.99409e-06,-4.83594e-09,0.56936,0.00150626,-4.00859e-06,2.53293e-08,0.570863,0.00149832,-3.93261e-06,2.27286e-08,0.572357,0.00149052,-3.86442e-06,2.96541e-09,0.573844,0.0014828,-3.85552e-06,2.50147e-08,0.575323,0.00147516,-3.78048e-06,1.61842e-08,0.576794,0.00146765,-3.73193e-06,2.94582e-08,0.578258,0.00146028,-3.64355e-06,-1.48076e-08,0.579715,0.00145295,-3.68798e-06,2.97724e-08,0.581164,0.00144566,-3.59866e-06,1.49272e-08,0.582606,0.00143851,-3.55388e-06,2.97285e-08,0.584041,0.00143149,-3.46469e-06,-1.46323e-08,0.585469,0.00142451,-3.50859e-06,2.88004e-08,0.58689,0.00141758,-3.42219e-06,1.864e-08,0.588304,0.00141079,-3.36627e-06,1.58482e-08,0.589712,0.00140411,-3.31872e-06,-2.24279e-08,0.591112,0.00139741,-3.38601e-06,7.38639e-08,0.592507,0.00139085,-3.16441e-06,-3.46088e-08,0.593894,0.00138442,-3.26824e-06,4.96675e-09,0.595275,0.0013779,-3.25334e-06,7.4346e-08,0.59665,0.00137162,-3.0303e-06,-6.39319e-08,0.598019,0.00136536,-3.2221e-06,6.21725e-08,0.599381,0.00135911,-3.03558e-06,-5.94423e-09,0.600737,0.00135302,-3.05341e-06,2.12091e-08,0.602087,0.00134697,-2.98979e-06,-1.92876e-08,0.603431,0.00134094,-3.04765e-06,5.5941e-08,0.604769,0.00133501,-2.87983e-06,-2.56622e-08,0.606101,0.00132917,-2.95681e-06,4.67078e-08,0.607427,0.0013234,-2.81669e-06,-4.19592e-08,0.608748,0.00131764,-2.94257e-06,6.15243e-08,0.610062,0.00131194,-2.75799e-06,-2.53244e-08,0.611372,0.00130635,-2.83397e-06,3.97739e-08,0.612675,0.0013008,-2.71465e-06,-1.45618e-08,0.613973,0.00129533,-2.75833e-06,1.84733e-08,0.615266,0.00128986,-2.70291e-06,2.73606e-10,0.616553,0.00128446,-2.70209e-06,4.00367e-08,0.617835,0.00127918,-2.58198e-06,-4.12113e-08,0.619111,0.00127389,-2.70561e-06,6.52039e-08,0.620383,0.00126867,-2.51e-06,-4.07901e-08,0.621649,0.00126353,-2.63237e-06,3.83516e-08,0.62291,0.00125838,-2.51732e-06,6.59315e-09,0.624166,0.00125337,-2.49754e-06,-5.11939e-09,0.625416,0.00124836,-2.5129e-06,1.38846e-08,0.626662,0.00124337,-2.47124e-06,9.18514e-09,0.627903,0.00123846,-2.44369e-06,8.97952e-09,0.629139,0.0012336,-2.41675e-06,1.45012e-08,0.63037,0.00122881,-2.37325e-06,-7.37949e-09,0.631597,0.00122404,-2.39538e-06,1.50169e-08,0.632818,0.00121929,-2.35033e-06,6.91648e-09,0.634035,0.00121461,-2.32958e-06,1.69219e-08,0.635248,0.00121,-2.27882e-06,-1.49997e-08,0.636455,0.0012054,-2.32382e-06,4.30769e-08,0.637659,0.00120088,-2.19459e-06,-3.80986e-08,0.638857,0.00119638,-2.30888e-06,4.97134e-08,0.640051,0.00119191,-2.15974e-06,-4.15463e-08,0.641241,0.00118747,-2.28438e-06,5.68667e-08,0.642426,0.00118307,-2.11378e-06,-7.10641e-09,0.643607,0.00117882,-2.1351e-06,-2.8441e-08,0.644784,0.00117446,-2.22042e-06,6.12658e-08,0.645956,0.00117021,-2.03663e-06,-3.78083e-08,0.647124,0.00116602,-2.15005e-06,3.03627e-08,0.648288,0.00116181,-2.05896e-06,-2.40379e-08,0.649448,0.00115762,-2.13108e-06,6.57887e-08,0.650603,0.00115356,-1.93371e-06,-6.03028e-08,0.651755,0.00114951,-2.11462e-06,5.62134e-08,0.652902,0.00114545,-1.94598e-06,-4.53417e-08,0.654046,0.00114142,-2.082e-06,6.55489e-08,0.655185,0.00113745,-1.88536e-06,-3.80396e-08,0.656321,0.00113357,-1.99948e-06,2.70049e-08,0.657452,0.00112965,-1.91846e-06,-1.03755e-08,0.65858,0.00112578,-1.94959e-06,1.44973e-08,0.659704,0.00112192,-1.9061e-06,1.1991e-08,0.660824,0.00111815,-1.87012e-06,-2.85634e-09,0.66194,0.0011144,-1.87869e-06,-5.65782e-10,0.663053,0.00111064,-1.88039e-06,5.11947e-09,0.664162,0.0011069,-1.86503e-06,3.96924e-08,0.665267,0.00110328,-1.74595e-06,-4.46795e-08,0.666368,0.00109966,-1.87999e-06,1.98161e-08,0.667466,0.00109596,-1.82054e-06,2.502e-08,0.66856,0.00109239,-1.74548e-06,-6.86593e-10,0.669651,0.0010889,-1.74754e-06,-2.22739e-08,0.670738,0.00108534,-1.81437e-06,3.01776e-08,0.671821,0.0010818,-1.72383e-06,2.07732e-08,0.672902,0.00107841,-1.66151e-06,-5.36658e-08,0.673978,0.00107493,-1.82251e-06,7.46802e-08,0.675051,0.00107151,-1.59847e-06,-6.62411e-08,0.676121,0.00106811,-1.79719e-06,7.10748e-08,0.677188,0.00106473,-1.58397e-06,-3.92441e-08,0.678251,0.00106145,-1.7017e-06,2.62973e-08,0.679311,0.00105812,-1.62281e-06,-6.34035e-09,0.680367,0.00105486,-1.64183e-06,-9.36249e-10,0.68142,0.00105157,-1.64464e-06,1.00854e-08,0.68247,0.00104831,-1.61438e-06,2.01995e-08,0.683517,0.00104514,-1.55378e-06,-3.1279e-08,0.68456,0.00104194,-1.64762e-06,4.53114e-08,0.685601,0.00103878,-1.51169e-06,-3.07573e-08,0.686638,0.00103567,-1.60396e-06,1.81133e-08,0.687672,0.00103251,-1.54962e-06,1.79085e-08,0.688703,0.00102947,-1.49589e-06,-3.01428e-08,0.689731,0.00102639,-1.58632e-06,4.30583e-08,0.690756,0.00102334,-1.45715e-06,-2.28814e-08,0.691778,0.00102036,-1.52579e-06,-1.11373e-08,0.692797,0.00101727,-1.5592e-06,6.74305e-08,0.693812,0.00101436,-1.35691e-06,-7.97709e-08,0.694825,0.0010114,-1.59622e-06,7.28391e-08,0.695835,0.00100843,-1.37771e-06,-3.27715e-08,0.696842,0.00100558,-1.47602e-06,-1.35807e-09,0.697846,0.00100262,-1.48009e-06,3.82037e-08,0.698847,0.000999775,-1.36548e-06,-3.22474e-08,0.699846,0.000996948,-1.46223e-06,3.11809e-08,0.700841,0.000994117,-1.36868e-06,-3.28714e-08,0.701834,0.000991281,-1.4673e-06,4.07001e-08,0.702824,0.000988468,-1.3452e-06,-1.07197e-08,0.703811,0.000985746,-1.37736e-06,2.17866e-09,0.704795,0.000982998,-1.37082e-06,2.00521e-09,0.705777,0.000980262,-1.3648e-06,-1.01996e-08,0.706756,0.000977502,-1.3954e-06,3.87931e-08,0.707732,0.000974827,-1.27902e-06,-2.57632e-08,0.708706,0.000972192,-1.35631e-06,4.65513e-09,0.709676,0.000969493,-1.34235e-06,7.14257e-09,0.710645,0.00096683,-1.32092e-06,2.63791e-08,0.71161,0.000964267,-1.24178e-06,-5.30543e-08,0.712573,0.000961625,-1.40095e-06,6.66289e-08,0.713533,0.000959023,-1.20106e-06,-3.46474e-08,0.714491,0.000956517,-1.305e-06,1.23559e-08,0.715446,0.000953944,-1.26793e-06,-1.47763e-08,0.716399,0.000951364,-1.31226e-06,4.67494e-08,0.717349,0.000948879,-1.17201e-06,-5.3012e-08,0.718297,0.000946376,-1.33105e-06,4.60894e-08,0.719242,0.000943852,-1.19278e-06,-1.21366e-08,0.720185,0.00094143,-1.22919e-06,2.45673e-09,0.721125,0.000938979,-1.22182e-06,2.30966e-09,0.722063,0.000936543,-1.21489e-06,-1.16954e-08,0.722998,0.000934078,-1.24998e-06,4.44718e-08,0.723931,0.000931711,-1.11656e-06,-4.69823e-08,0.724861,0.000929337,-1.25751e-06,2.4248e-08,0.725789,0.000926895,-1.18477e-06,9.5949e-09,0.726715,0.000924554,-1.15598e-06,-3.02286e-09,0.727638,0.000922233,-1.16505e-06,2.49649e-09,0.72856,0.00091991,-1.15756e-06,-6.96321e-09,0.729478,0.000917575,-1.17845e-06,2.53564e-08,0.730395,0.000915294,-1.10238e-06,-3.48578e-08,0.731309,0.000912984,-1.20695e-06,5.44704e-08,0.732221,0.000910734,-1.04354e-06,-6.38144e-08,0.73313,0.000908455,-1.23499e-06,8.15781e-08,0.734038,0.00090623,-9.90253e-07,-8.3684e-08,0.734943,0.000903999,-1.2413e-06,7.43441e-08,0.735846,0.000901739,-1.01827e-06,-3.48787e-08,0.736746,0.000899598,-1.12291e-06,5.56596e-09,0.737645,0.000897369,-1.10621e-06,1.26148e-08,0.738541,0.000895194,-1.06837e-06,3.57935e-09,0.739435,0.000893068,-1.05763e-06,-2.69322e-08,0.740327,0.000890872,-1.13842e-06,4.45448e-08,0.741217,0.000888729,-1.00479e-06,-3.20376e-08,0.742105,0.000886623,-1.1009e-06,2.40011e-08,0.74299,0.000884493,-1.0289e-06,-4.36209e-09,0.743874,0.000882422,-1.04199e-06,-6.55268e-09,0.744755,0.000880319,-1.06164e-06,3.05728e-08,0.745634,0.000878287,-9.69926e-07,-5.61338e-08,0.746512,0.000876179,-1.13833e-06,7.4753e-08,0.747387,0.000874127,-9.14068e-07,-6.40644e-08,0.74826,0.000872106,-1.10626e-06,6.22955e-08,0.749131,0.000870081,-9.19375e-07,-6.59083e-08,0.75,0.000868044,-1.1171e-06,8.21284e-08,0.750867,0.000866056,-8.70714e-07,-8.37915e-08,0.751732,0.000864064,-1.12209e-06,7.42237e-08,0.752595,0.000862042,-8.99418e-07,-3.42894e-08,0.753456,0.00086014,-1.00229e-06,3.32955e-09,0.754315,0.000858146,-9.92297e-07,2.09712e-08,0.755173,0.000856224,-9.29384e-07,-2.76096e-08,0.756028,0.000854282,-1.01221e-06,2.98627e-08,0.756881,0.000852348,-9.22625e-07,-3.22365e-08,0.757733,0.000850406,-1.01933e-06,3.94786e-08,0.758582,0.000848485,-9.00898e-07,-6.46833e-09,0.75943,0.000846664,-9.20303e-07,-1.36052e-08,0.760275,0.000844783,-9.61119e-07,1.28447e-09,0.761119,0.000842864,-9.57266e-07,8.4674e-09,0.761961,0.000840975,-9.31864e-07,2.44506e-08,0.762801,0.000839185,-8.58512e-07,-4.6665e-08,0.763639,0.000837328,-9.98507e-07,4.30001e-08,0.764476,0.00083546,-8.69507e-07,-6.12609e-09,0.76531,0.000833703,-8.87885e-07,-1.84959e-08,0.766143,0.000831871,-9.43372e-07,2.05052e-08,0.766974,0.000830046,-8.81857e-07,-3.92026e-09,0.767803,0.000828271,-8.93618e-07,-4.82426e-09,0.768631,0.000826469,-9.0809e-07,2.32172e-08,0.769456,0.000824722,-8.38439e-07,-2.84401e-08,0.77028,0.00082296,-9.23759e-07,3.09386e-08,0.771102,0.000821205,-8.30943e-07,-3.57099e-08,0.771922,0.000819436,-9.38073e-07,5.22963e-08,0.772741,0.000817717,-7.81184e-07,-5.42658e-08,0.773558,0.000815992,-9.43981e-07,4.55579e-08,0.774373,0.000814241,-8.07308e-07,-8.75656e-09,0.775186,0.0008126,-8.33578e-07,-1.05315e-08,0.775998,0.000810901,-8.65172e-07,-8.72188e-09,0.776808,0.000809145,-8.91338e-07,4.54191e-08,0.777616,0.000807498,-7.5508e-07,-5.37454e-08,0.778423,0.000805827,-9.16317e-07,5.03532e-08,0.779228,0.000804145,-7.65257e-07,-2.84584e-08,0.780031,0.000802529,-8.50632e-07,3.87579e-09,0.780833,0.00080084,-8.39005e-07,1.29552e-08,0.781633,0.0007992,-8.00139e-07,3.90804e-09,0.782432,0.000797612,-7.88415e-07,-2.85874e-08,0.783228,0.000795949,-8.74177e-07,5.0837e-08,0.784023,0.000794353,-7.21666e-07,-5.55513e-08,0.784817,0.000792743,-8.8832e-07,5.21587e-08,0.785609,0.000791123,-7.31844e-07,-3.38744e-08,0.786399,0.000789558,-8.33467e-07,2.37342e-08,0.787188,0.000787962,-7.62264e-07,-1.45775e-09,0.787975,0.000786433,-7.66638e-07,-1.79034e-08,0.788761,0.000784846,-8.20348e-07,1.34665e-08,0.789545,0.000783246,-7.79948e-07,2.3642e-08,0.790327,0.000781757,-7.09022e-07,-4.84297e-08,0.791108,0.000780194,-8.54311e-07,5.08674e-08,0.791888,0.000778638,-7.01709e-07,-3.58303e-08,0.792666,0.000777127,-8.092e-07,3.28493e-08,0.793442,0.000775607,-7.10652e-07,-3.59624e-08,0.794217,0.000774078,-8.1854e-07,5.13959e-08,0.79499,0.000772595,-6.64352e-07,-5.04121e-08,0.795762,0.000771115,-8.15588e-07,3.10431e-08,0.796532,0.000769577,-7.22459e-07,-1.41557e-08,0.797301,0.00076809,-7.64926e-07,2.55795e-08,0.798069,0.000766636,-6.88187e-07,-2.85578e-08,0.798835,0.000765174,-7.73861e-07,2.90472e-08,0.799599,0.000763714,-6.86719e-07,-2.80262e-08,0.800362,0.000762256,-7.70798e-07,2.34531e-08,0.801123,0.000760785,-7.00438e-07,-6.18144e-09,0.801884,0.000759366,-7.18983e-07,1.27263e-09,0.802642,0.000757931,-7.15165e-07,1.09101e-09,0.803399,0.000756504,-7.11892e-07,-5.63675e-09,0.804155,0.000755064,-7.28802e-07,2.14559e-08,0.80491,0.00075367,-6.64434e-07,-2.05821e-08,0.805663,0.00075228,-7.26181e-07,1.26812e-09,0.806414,0.000750831,-7.22377e-07,1.55097e-08,0.807164,0.000749433,-6.75848e-07,-3.70216e-09,0.807913,0.00074807,-6.86954e-07,-7.0105e-10,0.80866,0.000746694,-6.89057e-07,6.5063e-09,0.809406,0.000745336,-6.69538e-07,-2.53242e-08,0.810151,0.000743921,-7.45511e-07,3.51858e-08,0.810894,0.000742535,-6.39953e-07,3.79034e-09,0.811636,0.000741267,-6.28582e-07,-5.03471e-08,0.812377,0.000739858,-7.79624e-07,7.83886e-08,0.813116,0.000738534,-5.44458e-07,-8.43935e-08,0.813854,0.000737192,-7.97638e-07,8.03714e-08,0.81459,0.000735838,-5.56524e-07,-5.82784e-08,0.815325,0.00073455,-7.31359e-07,3.35329e-08,0.816059,0.000733188,-6.3076e-07,-1.62486e-08,0.816792,0.000731878,-6.79506e-07,3.14614e-08,0.817523,0.000730613,-5.85122e-07,-4.99925e-08,0.818253,0.000729293,-7.35099e-07,4.92994e-08,0.818982,0.000727971,-5.87201e-07,-2.79959e-08,0.819709,0.000726712,-6.71189e-07,3.07959e-09,0.820435,0.000725379,-6.6195e-07,1.56777e-08,0.82116,0.000724102,-6.14917e-07,-6.18564e-09,0.821883,0.000722854,-6.33474e-07,9.06488e-09,0.822606,0.000721614,-6.06279e-07,-3.00739e-08,0.823327,0.000720311,-6.96501e-07,5.16262e-08,0.824046,0.000719073,-5.41623e-07,-5.72214e-08,0.824765,0.000717818,-7.13287e-07,5.80503e-08,0.825482,0.000716566,-5.39136e-07,-5.57703e-08,0.826198,0.00071532,-7.06447e-07,4.58215e-08,0.826912,0.000714045,-5.68983e-07,-8.30636e-09,0.827626,0.000712882,-5.93902e-07,-1.25961e-08,0.828338,0.000711656,-6.3169e-07,-9.13985e-10,0.829049,0.00071039,-6.34432e-07,1.62519e-08,0.829759,0.00070917,-5.85676e-07,-4.48904e-09,0.830468,0.000707985,-5.99143e-07,1.70418e-09,0.831175,0.000706792,-5.9403e-07,-2.32768e-09,0.831881,0.000705597,-6.01014e-07,7.60648e-09,0.832586,0.000704418,-5.78194e-07,-2.80982e-08,0.83329,0.000703177,-6.62489e-07,4.51817e-08,0.833993,0.000701988,-5.26944e-07,-3.34192e-08,0.834694,0.000700834,-6.27201e-07,2.88904e-08,0.835394,0.000699666,-5.4053e-07,-2.25378e-08,0.836093,0.000698517,-6.08143e-07,1.65589e-09,0.836791,0.000697306,-6.03176e-07,1.59142e-08,0.837488,0.000696147,-5.55433e-07,-5.70801e-09,0.838184,0.000695019,-5.72557e-07,6.91792e-09,0.838878,0.000693895,-5.51803e-07,-2.19637e-08,0.839571,0.000692725,-6.17694e-07,2.13321e-08,0.840263,0.000691554,-5.53698e-07,-3.75996e-09,0.840954,0.000690435,-5.64978e-07,-6.29219e-09,0.841644,0.000689287,-5.83855e-07,2.89287e-08,0.842333,0.000688206,-4.97068e-07,-4.98181e-08,0.843021,0.000687062,-6.46523e-07,5.11344e-08,0.843707,0.000685922,-4.9312e-07,-3.55102e-08,0.844393,0.00068483,-5.9965e-07,3.13019e-08,0.845077,0.000683724,-5.05745e-07,-3.00925e-08,0.84576,0.000682622,-5.96022e-07,2.94636e-08,0.846442,0.000681519,-5.07631e-07,-2.81572e-08,0.847123,0.000680419,-5.92103e-07,2.35606e-08,0.847803,0.000679306,-5.21421e-07,-6.48045e-09,0.848482,0.000678243,-5.40863e-07,2.36124e-09,0.849159,0.000677169,-5.33779e-07,-2.96461e-09,0.849836,0.000676092,-5.42673e-07,9.49728e-09,0.850512,0.000675035,-5.14181e-07,-3.50245e-08,0.851186,0.000673902,-6.19254e-07,7.09959e-08,0.851859,0.000672876,-4.06267e-07,-7.01453e-08,0.852532,0.000671853,-6.16703e-07,3.07714e-08,0.853203,0.000670712,-5.24388e-07,6.66423e-09,0.853873,0.000669684,-5.04396e-07,2.17629e-09,0.854542,0.000668681,-4.97867e-07,-1.53693e-08,0.855211,0.000667639,-5.43975e-07,-3.03752e-10,0.855878,0.000666551,-5.44886e-07,1.65844e-08,0.856544,0.000665511,-4.95133e-07,-6.42907e-09,0.857209,0.000664501,-5.1442e-07,9.13195e-09,0.857873,0.0006635,-4.87024e-07,-3.00987e-08,0.858536,0.000662435,-5.7732e-07,5.16584e-08,0.859198,0.000661436,-4.22345e-07,-5.73255e-08,0.859859,0.000660419,-5.94322e-07,5.84343e-08,0.860518,0.000659406,-4.19019e-07,-5.72022e-08,0.861177,0.000658396,-5.90626e-07,5.11653e-08,0.861835,0.000657368,-4.3713e-07,-2.82495e-08,0.862492,0.000656409,-5.21878e-07,2.22788e-09,0.863148,0.000655372,-5.15195e-07,1.9338e-08,0.863803,0.0006544,-4.5718e-07,-1.99754e-08,0.864457,0.000653425,-5.17107e-07,9.59024e-10,0.86511,0.000652394,-5.1423e-07,1.61393e-08,0.865762,0.000651414,-4.65812e-07,-5.91149e-09,0.866413,0.000650465,-4.83546e-07,7.50665e-09,0.867063,0.00064952,-4.61026e-07,-2.4115e-08,0.867712,0.000648526,-5.33371e-07,2.93486e-08,0.86836,0.000647547,-4.45325e-07,-3.36748e-08,0.869007,0.000646555,-5.4635e-07,4.57461e-08,0.869653,0.0006456,-4.09112e-07,-3.01002e-08,0.870298,0.000644691,-4.99412e-07,1.50501e-08,0.870942,0.000643738,-4.54262e-07,-3.01002e-08,0.871585,0.000642739,-5.44563e-07,4.57461e-08,0.872228,0.000641787,-4.07324e-07,-3.36748e-08,0.872869,0.000640871,-5.08349e-07,2.93486e-08,0.873509,0.000639943,-4.20303e-07,-2.4115e-08,0.874149,0.00063903,-4.92648e-07,7.50655e-09,0.874787,0.000638067,-4.70128e-07,-5.91126e-09,0.875425,0.000637109,-4.87862e-07,1.61385e-08,0.876062,0.000636182,-4.39447e-07,9.61961e-10,0.876697,0.000635306,-4.36561e-07,-1.99863e-08,0.877332,0.000634373,-4.9652e-07,1.93785e-08,0.877966,0.000633438,-4.38384e-07,2.07697e-09,0.878599,0.000632567,-4.32153e-07,-2.76864e-08,0.879231,0.00063162,-5.15212e-07,4.90641e-08,0.879862,0.000630737,-3.6802e-07,-4.93606e-08,0.880493,0.000629852,-5.16102e-07,2.9169e-08,0.881122,0.000628908,-4.28595e-07,-7.71083e-09,0.881751,0.000628027,-4.51727e-07,1.6744e-09,0.882378,0.000627129,-4.46704e-07,1.01317e-09,0.883005,0.000626239,-4.43665e-07,-5.72703e-09,0.883631,0.000625334,-4.60846e-07,2.1895e-08,0.884255,0.000624478,-3.95161e-07,-2.22481e-08,0.88488,0.000623621,-4.61905e-07,7.4928e-09,0.885503,0.00062272,-4.39427e-07,-7.72306e-09,0.886125,0.000621818,-4.62596e-07,2.33995e-08,0.886746,0.000620963,-3.92398e-07,-2.62704e-08,0.887367,0.000620099,-4.71209e-07,2.20775e-08,0.887987,0.000619223,-4.04976e-07,-2.43496e-09,0.888605,0.000618406,-4.12281e-07,-1.23377e-08,0.889223,0.000617544,-4.49294e-07,-7.81876e-09,0.88984,0.000616622,-4.72751e-07,4.36128e-08,0.890457,0.000615807,-3.41912e-07,-4.7423e-08,0.891072,0.000614981,-4.84181e-07,2.68698e-08,0.891687,0.000614093,-4.03572e-07,-4.51384e-10,0.8923,0.000613285,-4.04926e-07,-2.50643e-08,0.892913,0.0006124,-4.80119e-07,4.11038e-08,0.893525,0.000611563,-3.56808e-07,-2.01414e-08,0.894136,0.000610789,-4.17232e-07,-2.01426e-08,0.894747,0.000609894,-4.7766e-07,4.11073e-08,0.895356,0.000609062,-3.54338e-07,-2.50773e-08,0.895965,0.000608278,-4.2957e-07,-4.02954e-10,0.896573,0.000607418,-4.30779e-07,2.66891e-08,0.89718,0.000606636,-3.50711e-07,-4.67489e-08,0.897786,0.000605795,-4.90958e-07,4.10972e-08,0.898391,0.000604936,-3.67666e-07,1.56948e-09,0.898996,0.000604205,-3.62958e-07,-4.73751e-08,0.8996,0.000603337,-5.05083e-07,6.87214e-08,0.900202,0.000602533,-2.98919e-07,-4.86966e-08,0.900805,0.000601789,-4.45009e-07,6.85589e-09,0.901406,0.00060092,-4.24441e-07,2.1273e-08,0.902007,0.000600135,-3.60622e-07,-3.23434e-08,0.902606,0.000599317,-4.57652e-07,4.84959e-08,0.903205,0.000598547,-3.12164e-07,-4.24309e-08,0.903803,0.000597795,-4.39457e-07,2.01844e-09,0.904401,0.000596922,-4.33402e-07,3.43571e-08,0.904997,0.000596159,-3.30331e-07,-2.02374e-08,0.905593,0.000595437,-3.91043e-07,-1.30123e-08,0.906188,0.000594616,-4.3008e-07,1.26819e-08,0.906782,0.000593794,-3.92034e-07,2.18894e-08,0.907376,0.000593076,-3.26366e-07,-4.06349e-08,0.907968,0.000592301,-4.4827e-07,2.1441e-08,0.90856,0.000591469,-3.83947e-07,1.44754e-08,0.909151,0.000590744,-3.40521e-07,-1.97379e-08,0.909742,0.000590004,-3.99735e-07,4.87161e-09,0.910331,0.000589219,-3.8512e-07,2.51532e-10,0.91092,0.00058845,-3.84366e-07,-5.87776e-09,0.911508,0.000587663,-4.01999e-07,2.32595e-08,0.912096,0.000586929,-3.3222e-07,-2.75554e-08,0.912682,0.000586182,-4.14887e-07,2.73573e-08,0.913268,0.000585434,-3.32815e-07,-2.22692e-08,0.913853,0.000584702,-3.99622e-07,2.11486e-09,0.914437,0.000583909,-3.93278e-07,1.38098e-08,0.915021,0.000583164,-3.51848e-07,2.25042e-09,0.915604,0.000582467,-3.45097e-07,-2.28115e-08,0.916186,0.000581708,-4.13531e-07,2.93911e-08,0.916767,0.000580969,-3.25358e-07,-3.51481e-08,0.917348,0.000580213,-4.30803e-07,5.15967e-08,0.917928,0.000579506,-2.76012e-07,-5.20296e-08,0.918507,0.000578798,-4.32101e-07,3.73124e-08,0.919085,0.000578046,-3.20164e-07,-3.76154e-08,0.919663,0.000577293,-4.3301e-07,5.35447e-08,0.92024,0.000576587,-2.72376e-07,-5.7354e-08,0.920816,0.000575871,-4.44438e-07,5.66621e-08,0.921391,0.000575152,-2.74452e-07,-5.00851e-08,0.921966,0.000574453,-4.24707e-07,2.4469e-08,0.92254,0.000573677,-3.513e-07,1.18138e-08,0.923114,0.000573009,-3.15859e-07,-1.21195e-08,0.923686,0.000572341,-3.52217e-07,-2.29403e-08,0.924258,0.000571568,-4.21038e-07,4.4276e-08,0.924829,0.000570859,-2.8821e-07,-3.49546e-08,0.9254,0.000570178,-3.93074e-07,3.59377e-08,0.92597,0.000569499,-2.85261e-07,-4.91915e-08,0.926539,0.000568781,-4.32835e-07,4.16189e-08,0.927107,0.00056804,-3.07979e-07,1.92523e-09,0.927675,0.00056743,-3.02203e-07,-4.93198e-08,0.928242,0.000566678,-4.50162e-07,7.61447e-08,0.928809,0.000566006,-2.21728e-07,-7.6445e-08,0.929374,0.000565333,-4.51063e-07,5.08216e-08,0.929939,0.000564583,-2.98599e-07,-7.63212e-09,0.930503,0.000563963,-3.21495e-07,-2.02931e-08,0.931067,0.000563259,-3.82374e-07,2.92001e-08,0.93163,0.000562582,-2.94774e-07,-3.69025e-08,0.932192,0.000561882,-4.05482e-07,5.88053e-08,0.932754,0.000561247,-2.29066e-07,-7.91094e-08,0.933315,0.000560552,-4.66394e-07,7.88184e-08,0.933875,0.000559856,-2.29939e-07,-5.73501e-08,0.934434,0.000559224,-4.01989e-07,3.13727e-08,0.934993,0.000558514,-3.07871e-07,-8.53611e-09,0.935551,0.000557873,-3.33479e-07,2.77175e-09,0.936109,0.000557214,-3.25164e-07,-2.55091e-09,0.936666,0.000556556,-3.32817e-07,7.43188e-09,0.937222,0.000555913,-3.10521e-07,-2.71766e-08,0.937778,0.00055521,-3.92051e-07,4.167e-08,0.938333,0.000554551,-2.67041e-07,-2.02941e-08,0.938887,0.000553956,-3.27923e-07,-2.00984e-08,0.93944,0.00055324,-3.88218e-07,4.10828e-08,0.939993,0.000552587,-2.6497e-07,-2.50237e-08,0.940546,0.000551982,-3.40041e-07,-5.92583e-10,0.941097,0.0005513,-3.41819e-07,2.7394e-08,0.941648,0.000550698,-2.59637e-07,-4.93788e-08,0.942199,0.000550031,-4.07773e-07,5.09119e-08,0.942748,0.000549368,-2.55038e-07,-3.50595e-08,0.943297,0.000548753,-3.60216e-07,2.97214e-08,0.943846,0.000548122,-2.71052e-07,-2.42215e-08,0.944394,0.000547507,-3.43716e-07,7.55985e-09,0.944941,0.000546842,-3.21037e-07,-6.01796e-09,0.945487,0.000546182,-3.3909e-07,1.65119e-08,0.946033,0.000545553,-2.89555e-07,-4.2498e-10,0.946578,0.000544973,-2.9083e-07,-1.4812e-08,0.947123,0.000544347,-3.35266e-07,6.83068e-11,0.947667,0.000543676,-3.35061e-07,1.45388e-08,0.94821,0.00054305,-2.91444e-07,1.38123e-09,0.948753,0.000542471,-2.87301e-07,-2.00637e-08,0.949295,0.000541836,-3.47492e-07,1.92688e-08,0.949837,0.000541199,-2.89685e-07,2.59298e-09,0.950378,0.000540628,-2.81906e-07,-2.96407e-08,0.950918,0.000539975,-3.70829e-07,5.63652e-08,0.951458,0.000539402,-2.01733e-07,-7.66107e-08,0.951997,0.000538769,-4.31565e-07,7.12638e-08,0.952535,0.00053812,-2.17774e-07,-2.96305e-08,0.953073,0.000537595,-3.06665e-07,-1.23464e-08,0.95361,0.000536945,-3.43704e-07,1.94114e-08,0.954147,0.000536316,-2.8547e-07,-5.69451e-09,0.954683,0.000535728,-3.02554e-07,3.36666e-09,0.955219,0.000535133,-2.92454e-07,-7.77208e-09,0.955753,0.000534525,-3.1577e-07,2.77216e-08,0.956288,0.000533976,-2.32605e-07,-4.35097e-08,0.956821,0.00053338,-3.63134e-07,2.7108e-08,0.957354,0.000532735,-2.8181e-07,-5.31772e-09,0.957887,0.000532156,-2.97764e-07,-5.83718e-09,0.958419,0.000531543,-3.15275e-07,2.86664e-08,0.95895,0.000530998,-2.29276e-07,-4.9224e-08,0.959481,0.000530392,-3.76948e-07,4.90201e-08,0.960011,0.000529785,-2.29887e-07,-2.76471e-08,0.96054,0.000529243,-3.12829e-07,1.96385e-09,0.961069,0.000528623,-3.06937e-07,1.97917e-08,0.961598,0.000528068,-2.47562e-07,-2.15261e-08,0.962125,0.000527508,-3.1214e-07,6.70795e-09,0.962653,0.000526904,-2.92016e-07,-5.30573e-09,0.963179,0.000526304,-3.07934e-07,1.4515e-08,0.963705,0.000525732,-2.64389e-07,6.85048e-09,0.964231,0.000525224,-2.43837e-07,-4.19169e-08,0.964756,0.00052461,-3.69588e-07,4.1608e-08,0.96528,0.000523996,-2.44764e-07,-5.30598e-09,0.965804,0.000523491,-2.60682e-07,-2.03841e-08,0.966327,0.000522908,-3.21834e-07,2.72378e-08,0.966849,0.000522346,-2.40121e-07,-2.89625e-08,0.967371,0.000521779,-3.27008e-07,2.90075e-08,0.967893,0.000521212,-2.39986e-07,-2.74629e-08,0.968414,0.00052065,-3.22374e-07,2.12396e-08,0.968934,0.000520069,-2.58656e-07,2.10922e-09,0.969454,0.000519558,-2.52328e-07,-2.96765e-08,0.969973,0.000518964,-3.41357e-07,5.6992e-08,0.970492,0.000518452,-1.70382e-07,-7.90821e-08,0.97101,0.000517874,-4.07628e-07,8.05224e-08,0.971528,0.000517301,-1.66061e-07,-6.41937e-08,0.972045,0.000516776,-3.58642e-07,5.70429e-08,0.972561,0.00051623,-1.87513e-07,-4.47686e-08,0.973077,0.00051572,-3.21819e-07,2.82237e-09,0.973593,0.000515085,-3.13352e-07,3.34792e-08,0.974108,0.000514559,-2.12914e-07,-1.75298e-08,0.974622,0.000514081,-2.65503e-07,-2.29648e-08,0.975136,0.000513481,-3.34398e-07,4.97843e-08,0.975649,0.000512961,-1.85045e-07,-5.6963e-08,0.976162,0.00051242,-3.55934e-07,5.88585e-08,0.976674,0.000511885,-1.79359e-07,-5.92616e-08,0.977185,0.000511348,-3.57143e-07,5.89785e-08,0.977696,0.000510811,-1.80208e-07,-5.74433e-08,0.978207,0.000510278,-3.52538e-07,5.15854e-08,0.978717,0.000509728,-1.97781e-07,-2.9689e-08,0.979226,0.000509243,-2.86848e-07,7.56591e-09,0.979735,0.000508692,-2.64151e-07,-5.74649e-10,0.980244,0.000508162,-2.65875e-07,-5.26732e-09,0.980752,0.000507615,-2.81677e-07,2.16439e-08,0.981259,0.000507116,-2.16745e-07,-2.17037e-08,0.981766,0.000506618,-2.81856e-07,5.56636e-09,0.982272,0.000506071,-2.65157e-07,-5.61689e-10,0.982778,0.000505539,-2.66842e-07,-3.31963e-09,0.983283,0.000504995,-2.76801e-07,1.38402e-08,0.983788,0.000504483,-2.3528e-07,7.56339e-09,0.984292,0.000504035,-2.1259e-07,-4.40938e-08,0.984796,0.000503478,-3.44871e-07,4.96026e-08,0.985299,0.000502937,-1.96064e-07,-3.51071e-08,0.985802,0.000502439,-3.01385e-07,3.12212e-08,0.986304,0.00050193,-2.07721e-07,-3.0173e-08,0.986806,0.000501424,-2.9824e-07,2.9866e-08,0.987307,0.000500917,-2.08642e-07,-2.96865e-08,0.987808,0.000500411,-2.97702e-07,2.92753e-08,0.988308,0.000499903,-2.09876e-07,-2.78101e-08,0.988807,0.0004994,-2.93306e-07,2.23604e-08,0.989307,0.000498881,-2.26225e-07,-2.02681e-09,0.989805,0.000498422,-2.32305e-07,-1.42531e-08,0.990303,0.000497915,-2.75065e-07,-5.65232e-10,0.990801,0.000497363,-2.76761e-07,1.65141e-08,0.991298,0.000496859,-2.27218e-07,-5.88639e-09,0.991795,0.000496387,-2.44878e-07,7.0315e-09,0.992291,0.000495918,-2.23783e-07,-2.22396e-08,0.992787,0.000495404,-2.90502e-07,2.23224e-08,0.993282,0.00049489,-2.23535e-07,-7.44543e-09,0.993776,0.000494421,-2.45871e-07,7.45924e-09,0.994271,0.000493951,-2.23493e-07,-2.23915e-08,0.994764,0.000493437,-2.90668e-07,2.25021e-08,0.995257,0.000492923,-2.23161e-07,-8.01218e-09,0.99575,0.000492453,-2.47198e-07,9.54669e-09,0.996242,0.000491987,-2.18558e-07,-3.01746e-08,0.996734,0.000491459,-3.09082e-07,5.1547e-08,0.997225,0.000490996,-1.54441e-07,-5.68039e-08,0.997716,0.000490517,-3.24853e-07,5.64594e-08,0.998206,0.000490036,-1.55474e-07,-4.98245e-08,0.998696,0.000489576,-3.04948e-07,2.36292e-08,0.999186,0.000489037,-2.3406e-07,1.49121e-08,0.999674,0.000488613,-1.89324e-07,-2.3673e-08,1.00016,0.000488164,-2.60343e-07,2.01754e-08,1.00065,0.000487704,-1.99816e-07,-5.70288e-08,1.00114,0.000487133,-3.70903e-07,8.87303e-08,1.00162,0.000486657,-1.04712e-07,-5.94737e-08,1.00211,0.000486269,-2.83133e-07,2.99553e-08,1.0026,0.000485793,-1.93267e-07,-6.03474e-08,1.00308,0.000485225,-3.74309e-07,9.2225e-08,1.00357,0.000484754,-9.76345e-08,-7.0134e-08,1.00405,0.000484348,-3.08036e-07,6.91016e-08,1.00454,0.000483939,-1.00731e-07,-8.70633e-08,1.00502,0.000483476,-3.61921e-07,4.07328e-08,1.0055,0.000482875,-2.39723e-07,4.33413e-08,1.00599,0.000482525,-1.09699e-07,-9.48886e-08,1.00647,0.000482021,-3.94365e-07,9.77947e-08,1.00695,0.000481526,-1.00981e-07,-5.78713e-08,1.00743,0.00048115,-2.74595e-07,1.44814e-08,1.00791,0.000480645,-2.31151e-07,-5.42665e-11,1.00839,0.000480182,-2.31314e-07,-1.42643e-08,1.00887,0.000479677,-2.74106e-07,5.71115e-08,1.00935,0.0004793,-1.02772e-07,-9.49724e-08,1.00983,0.000478809,-3.87689e-07,8.43596e-08,1.01031,0.000478287,-1.3461e-07,-4.04755e-09,1.01079,0.000478006,-1.46753e-07,-6.81694e-08,1.01127,0.000477508,-3.51261e-07,3.83067e-08,1.01174,0.00047692,-2.36341e-07,3.41521e-08,1.01222,0.00047655,-1.33885e-07,-5.57058e-08,1.0127,0.000476115,-3.01002e-07,6.94616e-08,1.01317,0.000475721,-9.26174e-08,-1.02931e-07,1.01365,0.000475227,-4.01412e-07,1.03846e-07,1.01412,0.000474736,-8.98751e-08,-7.40321e-08,1.0146,0.000474334,-3.11971e-07,7.30735e-08,1.01507,0.00047393,-9.27508e-08,-9.90527e-08,1.01554,0.000473447,-3.89909e-07,8.47188e-08,1.01602,0.000472921,-1.35753e-07,-1.40381e-09,1.01649,0.000472645,-1.39964e-07,-7.91035e-08,1.01696,0.000472128,-3.77275e-07,7.93993e-08,1.01744,0.000471612,-1.39077e-07,-7.52607e-11,1.01791,0.000471334,-1.39302e-07,-7.90983e-08,1.01838,0.000470818,-3.76597e-07,7.80499e-08,1.01885,0.000470299,-1.42448e-07,5.31733e-09,1.01932,0.00047003,-1.26496e-07,-9.93193e-08,1.01979,0.000469479,-4.24453e-07,1.53541e-07,1.02026,0.00046909,3.617e-08,-1.57217e-07,1.02073,0.000468691,-4.35482e-07,1.177e-07,1.02119,0.000468173,-8.23808e-08,-7.51659e-08,1.02166,0.000467783,-3.07878e-07,6.37538e-08,1.02213,0.000467358,-1.16617e-07,-6.064e-08,1.0226,0.000466943,-2.98537e-07,5.9597e-08,1.02306,0.000466525,-1.19746e-07,-5.85386e-08,1.02353,0.00046611,-2.95362e-07,5.53482e-08,1.024,0.000465685,-1.29317e-07,-4.36449e-08,1.02446,0.000465296,-2.60252e-07,2.20268e-11,1.02493,0.000464775,-2.60186e-07,4.35568e-08,1.02539,0.000464386,-1.29516e-07,-5.50398e-08,1.02586,0.000463961,-2.94635e-07,5.73932e-08,1.02632,0.000463544,-1.22456e-07,-5.53236e-08,1.02678,0.000463133,-2.88426e-07,4.46921e-08,1.02725,0.000462691,-1.5435e-07,-4.23534e-09,1.02771,0.000462369,-1.67056e-07,-2.77507e-08,1.02817,0.000461952,-2.50308e-07,-3.97101e-09,1.02863,0.000461439,-2.62221e-07,4.36348e-08,1.02909,0.000461046,-1.31317e-07,-5.13589e-08,1.02955,0.000460629,-2.85394e-07,4.25913e-08,1.03001,0.000460186,-1.5762e-07,2.0285e-10,1.03047,0.000459871,-1.57011e-07,-4.34027e-08,1.03093,0.000459427,-2.87219e-07,5.41987e-08,1.03139,0.000459015,-1.24623e-07,-5.4183e-08,1.03185,0.000458604,-2.87172e-07,4.33239e-08,1.03231,0.000458159,-1.572e-07,9.65817e-11,1.03277,0.000457845,-1.56911e-07,-4.37103e-08,1.03323,0.0004574,-2.88041e-07,5.55351e-08,1.03368,0.000456991,-1.21436e-07,-5.9221e-08,1.03414,0.00045657,-2.99099e-07,6.21394e-08,1.0346,0.000456158,-1.1268e-07,-7.01275e-08,1.03505,0.000455723,-3.23063e-07,9.91614e-08,1.03551,0.000455374,-2.55788e-08,-8.80996e-08,1.03596,0.000455058,-2.89878e-07,1.48184e-08,1.03642,0.000454523,-2.45422e-07,2.88258e-08,1.03687,0.000454119,-1.58945e-07,-1.09125e-08,1.03733,0.000453768,-1.91682e-07,1.48241e-08,1.03778,0.000453429,-1.4721e-07,-4.83838e-08,1.03823,0.00045299,-2.92361e-07,5.95019e-08,1.03869,0.000452584,-1.13856e-07,-7.04146e-08,1.03914,0.000452145,-3.25099e-07,1.02947e-07,1.03959,0.000451803,-1.62583e-08,-1.02955e-07,1.04004,0.000451462,-3.25123e-07,7.04544e-08,1.04049,0.000451023,-1.1376e-07,-5.96534e-08,1.04094,0.000450616,-2.9272e-07,4.89499e-08,1.04139,0.000450178,-1.45871e-07,-1.69369e-08,1.04184,0.000449835,-1.96681e-07,1.87977e-08,1.04229,0.000449498,-1.40288e-07,-5.82539e-08,1.04274,0.000449043,-3.1505e-07,9.50087e-08,1.04319,0.000448698,-3.00238e-08,-8.33623e-08,1.04364,0.000448388,-2.80111e-07,2.20363e-11,1.04409,0.000447828,-2.80045e-07,8.32742e-08,1.04454,0.000447517,-3.02221e-08,-9.47002e-08,1.04498,0.000447173,-3.14323e-07,5.7108e-08,1.04543,0.000446716,-1.42999e-07,-1.45225e-08,1.04588,0.000446386,-1.86566e-07,9.82022e-10,1.04632,0.000446016,-1.8362e-07,1.05944e-08,1.04677,0.00044568,-1.51837e-07,-4.33597e-08,1.04721,0.000445247,-2.81916e-07,4.36352e-08,1.04766,0.000444814,-1.51011e-07,-1.19717e-08,1.0481,0.000444476,-1.86926e-07,4.25158e-09,1.04855,0.000444115,-1.74171e-07,-5.03461e-09,1.04899,0.000443751,-1.89275e-07,1.58868e-08,1.04944,0.00044342,-1.41614e-07,-5.85127e-08,1.04988,0.000442961,-3.17152e-07,9.89548e-08,1.05032,0.000442624,-2.0288e-08,-9.88878e-08,1.05076,0.000442287,-3.16951e-07,5.81779e-08,1.05121,0.000441827,-1.42418e-07,-1.46144e-08,1.05165,0.000441499,-1.86261e-07,2.79892e-10,1.05209,0.000441127,-1.85421e-07,1.34949e-08,1.05253,0.000440797,-1.44937e-07,-5.42594e-08,1.05297,0.000440344,-3.07715e-07,8.43335e-08,1.05341,0.000439982,-5.47146e-08,-4.46558e-08,1.05385,0.000439738,-1.88682e-07,-2.49193e-08,1.05429,0.000439286,-2.6344e-07,2.5124e-08,1.05473,0.000438835,-1.88068e-07,4.36328e-08,1.05517,0.000438589,-5.71699e-08,-8.04459e-08,1.05561,0.000438234,-2.98508e-07,3.97324e-08,1.05605,0.000437756,-1.79311e-07,4.07258e-08,1.05648,0.000437519,-5.71332e-08,-8.34263e-08,1.05692,0.000437155,-3.07412e-07,5.45608e-08,1.05736,0.000436704,-1.4373e-07,-1.56078e-08,1.05779,0.000436369,-1.90553e-07,7.87043e-09,1.05823,0.000436012,-1.66942e-07,-1.58739e-08,1.05867,0.00043563,-2.14563e-07,5.56251e-08,1.0591,0.000435368,-4.76881e-08,-8.74172e-08,1.05954,0.000435011,-3.0994e-07,5.56251e-08,1.05997,0.000434558,-1.43064e-07,-1.58739e-08,1.06041,0.000434224,-1.90686e-07,7.87042e-09,1.06084,0.000433866,-1.67075e-07,-1.56078e-08,1.06127,0.000433485,-2.13898e-07,5.45609e-08,1.06171,0.000433221,-5.02157e-08,-8.34263e-08,1.06214,0.00043287,-3.00495e-07,4.07258e-08,1.06257,0.000432391,-1.78317e-07,3.97325e-08,1.063,0.000432154,-5.91198e-08,-8.04464e-08,1.06344,0.000431794,-3.00459e-07,4.36347e-08,1.06387,0.000431324,-1.69555e-07,2.5117e-08,1.0643,0.000431061,-9.42041e-08,-2.48934e-08,1.06473,0.000430798,-1.68884e-07,-4.47527e-08,1.06516,0.000430326,-3.03142e-07,8.46951e-08,1.06559,0.000429973,-4.90573e-08,-5.56089e-08,1.06602,0.000429708,-2.15884e-07,1.85314e-08,1.06645,0.000429332,-1.6029e-07,-1.85166e-08,1.06688,0.000428956,-2.1584e-07,5.5535e-08,1.06731,0.000428691,-4.92347e-08,-8.44142e-08,1.06774,0.000428339,-3.02477e-07,4.37032e-08,1.06816,0.000427865,-1.71368e-07,2.88107e-08,1.06859,0.000427609,-8.49356e-08,-3.97367e-08,1.06902,0.00042732,-2.04146e-07,1.09267e-08,1.06945,0.000426945,-1.71365e-07,-3.97023e-09,1.06987,0.00042659,-1.83276e-07,4.9542e-09,1.0703,0.000426238,-1.68414e-07,-1.58466e-08,1.07073,0.000425854,-2.15953e-07,5.84321e-08,1.07115,0.000425597,-4.0657e-08,-9.86725e-08,1.07158,0.00042522,-3.36674e-07,9.78392e-08,1.072,0.00042484,-4.31568e-08,-5.42658e-08,1.07243,0.000424591,-2.05954e-07,1.45377e-11,1.07285,0.000424179,-2.0591e-07,5.42076e-08,1.07328,0.00042393,-4.32877e-08,-9.76357e-08,1.0737,0.00042355,-3.36195e-07,9.79165e-08,1.07412,0.000423172,-4.24451e-08,-5.56118e-08,1.07455,0.00042292,-2.09281e-07,5.32143e-09,1.07497,0.000422518,-1.93316e-07,3.43261e-08,1.07539,0.000422234,-9.0338e-08,-2.34165e-08,1.07581,0.000421983,-1.60588e-07,-5.98692e-08,1.07623,0.000421482,-3.40195e-07,1.43684e-07,1.07666,0.000421233,9.08574e-08,-1.5724e-07,1.07708,0.000420943,-3.80862e-07,1.27647e-07,1.0775,0.000420564,2.0791e-09,-1.1493e-07,1.07792,0.000420223,-3.4271e-07,9.36534e-08,1.07834,0.000419819,-6.17499e-08,-2.12653e-08,1.07876,0.000419632,-1.25546e-07,-8.59219e-09,1.07918,0.000419355,-1.51322e-07,-6.35752e-08,1.0796,0.000418861,-3.42048e-07,1.43684e-07,1.08002,0.000418608,8.90034e-08,-1.53532e-07,1.08043,0.000418326,-3.71593e-07,1.12817e-07,1.08085,0.000417921,-3.31414e-08,-5.93184e-08,1.08127,0.000417677,-2.11097e-07,5.24697e-09,1.08169,0.00041727,-1.95356e-07,3.83305e-08,1.0821,0.000416995,-8.03642e-08,-3.93597e-08,1.08252,0.000416716,-1.98443e-07,-1.0094e-10,1.08294,0.000416319,-1.98746e-07,3.97635e-08,1.08335,0.00041604,-7.94557e-08,-3.97437e-08,1.08377,0.000415762,-1.98687e-07,1.94215e-12,1.08419,0.000415365,-1.98681e-07,3.97359e-08,1.0846,0.000415087,-7.94732e-08,-3.97362e-08,1.08502,0.000414809,-1.98682e-07,-4.31063e-13,1.08543,0.000414411,-1.98683e-07,3.97379e-08,1.08584,0.000414133,-7.94694e-08,-3.97418e-08,1.08626,0.000413855,-1.98695e-07,2.00563e-11,1.08667,0.000413458,-1.98635e-07,3.96616e-08,1.08709,0.000413179,-7.965e-08,-3.9457e-08,1.0875,0.000412902,-1.98021e-07,-1.04281e-09,1.08791,0.000412502,-2.01149e-07,4.36282e-08,1.08832,0.000412231,-7.02648e-08,-5.42608e-08,1.08874,0.000411928,-2.33047e-07,5.42057e-08,1.08915,0.000411624,-7.04301e-08,-4.33527e-08,1.08956,0.000411353,-2.00488e-07,-4.07378e-12,1.08997,0.000410952,-2.005e-07,4.3369e-08,1.09038,0.000410681,-7.03934e-08,-5.42627e-08,1.09079,0.000410378,-2.33182e-07,5.44726e-08,1.0912,0.000410075,-6.97637e-08,-4.44186e-08,1.09161,0.000409802,-2.03019e-07,3.99235e-09,1.09202,0.000409408,-1.91042e-07,2.84491e-08,1.09243,0.000409111,-1.05695e-07,1.42043e-09,1.09284,0.000408904,-1.01434e-07,-3.41308e-08,1.09325,0.000408599,-2.03826e-07,1.58937e-08,1.09366,0.000408239,-1.56145e-07,-2.94438e-08,1.09406,0.000407838,-2.44476e-07,1.01881e-07,1.09447,0.000407655,6.11676e-08,-1.39663e-07,1.09488,0.000407358,-3.57822e-07,9.91432e-08,1.09529,0.00040694,-6.03921e-08,-1.84912e-08,1.09569,0.000406764,-1.15866e-07,-2.51785e-08,1.0961,0.000406457,-1.91401e-07,-4.03115e-12,1.09651,0.000406074,-1.91413e-07,2.51947e-08,1.09691,0.000405767,-1.15829e-07,1.84346e-08,1.09732,0.00040559,-6.05254e-08,-9.89332e-08,1.09772,0.000405172,-3.57325e-07,1.3888e-07,1.09813,0.000404874,5.93136e-08,-9.8957e-08,1.09853,0.000404696,-2.37557e-07,1.853e-08,1.09894,0.000404277,-1.81968e-07,2.48372e-08,1.09934,0.000403987,-1.07456e-07,1.33047e-09,1.09975,0.000403776,-1.03465e-07,-3.01591e-08,1.10015,0.000403479,-1.93942e-07,9.66054e-11,1.10055,0.000403091,-1.93652e-07,2.97727e-08,1.10096,0.000402793,-1.04334e-07,2.19273e-11,1.10136,0.000402585,-1.04268e-07,-2.98604e-08,1.10176,0.000402287,-1.93849e-07,2.10325e-10,1.10216,0.0004019,-1.93218e-07,2.90191e-08,1.10256,0.0004016,-1.06161e-07,2.92264e-09,1.10297,0.000401397,-9.73931e-08,-4.07096e-08,1.10337,0.00040108,-2.19522e-07,4.07067e-08,1.10377,0.000400763,-9.7402e-08,-2.90783e-09,1.10417,0.000400559,-1.06126e-07,-2.90754e-08,1.10457,0.00040026,-1.93352e-07,9.00021e-14,1.10497,0.000399873,-1.93351e-07,2.9075e-08,1.10537,0.000399574,-1.06126e-07,2.90902e-09,1.10577,0.00039937,-9.73992e-08,-4.07111e-08,1.10617,0.000399053,-2.19533e-07,4.07262e-08,1.10657,0.000398736,-9.73541e-08,-2.98424e-09,1.10697,0.000398533,-1.06307e-07,-2.87892e-08,1.10736,0.000398234,-1.92674e-07,-1.06824e-09,1.10776,0.000397845,-1.95879e-07,3.30622e-08,1.10816,0.000397552,-9.66926e-08,-1.19712e-08,1.10856,0.000397323,-1.32606e-07,1.48225e-08,1.10895,0.000397102,-8.81387e-08,-4.73187e-08,1.10935,0.000396784,-2.30095e-07,5.52429e-08,1.10975,0.00039649,-6.4366e-08,-5.44437e-08,1.11014,0.000396198,-2.27697e-07,4.33226e-08,1.11054,0.000395872,-9.77293e-08,3.62656e-10,1.11094,0.000395678,-9.66414e-08,-4.47732e-08,1.11133,0.00039535,-2.30961e-07,5.95208e-08,1.11173,0.000395067,-5.23985e-08,-7.41008e-08,1.11212,0.00039474,-2.74701e-07,1.17673e-07,1.11252,0.000394543,7.83181e-08,-1.58172e-07,1.11291,0.000394225,-3.96199e-07,1.57389e-07,1.1133,0.000393905,7.59679e-08,-1.13756e-07,1.1137,0.000393716,-2.653e-07,5.92165e-08,1.11409,0.000393363,-8.76507e-08,-3.90074e-09,1.11449,0.000393176,-9.93529e-08,-4.36136e-08,1.11488,0.000392846,-2.30194e-07,5.91457e-08,1.11527,0.000392563,-5.27564e-08,-7.376e-08,1.11566,0.000392237,-2.74037e-07,1.16685e-07,1.11606,0.000392039,7.60189e-08,-1.54562e-07,1.11645,0.000391727,-3.87667e-07,1.43935e-07,1.11684,0.000391384,4.4137e-08,-6.35487e-08,1.11723,0.000391281,-1.46509e-07,-8.94896e-09,1.11762,0.000390961,-1.73356e-07,-1.98647e-08,1.11801,0.000390555,-2.3295e-07,8.8408e-08,1.1184,0.000390354,3.22736e-08,-9.53486e-08,1.11879,0.000390133,-2.53772e-07,5.45677e-08,1.11918,0.000389789,-9.0069e-08,-3.71296e-09,1.11957,0.000389598,-1.01208e-07,-3.97159e-08,1.11996,0.000389276,-2.20355e-07,4.33671e-08,1.12035,0.000388966,-9.02542e-08,-1.45431e-08,1.12074,0.000388741,-1.33883e-07,1.48052e-08,1.12113,0.000388518,-8.94678e-08,-4.46778e-08,1.12152,0.000388205,-2.23501e-07,4.46966e-08,1.12191,0.000387892,-8.94114e-08,-1.48992e-08,1.12229,0.000387669,-1.34109e-07,1.49003e-08,1.12268,0.000387445,-8.94082e-08,-4.47019e-08,1.12307,0.000387132,-2.23514e-07,4.4698e-08,1.12345,0.000386819,-8.942e-08,-1.48806e-08,1.12384,0.000386596,-1.34062e-07,1.48245e-08,1.12423,0.000386372,-8.95885e-08,-4.44172e-08,1.12461,0.00038606,-2.2284e-07,4.36351e-08,1.125,0.000385745,-9.19348e-08,-1.09139e-08,1.12539,0.000385528,-1.24677e-07,2.05584e-11,1.12577,0.000385279,-1.24615e-07,1.08317e-08,1.12616,0.000385062,-9.21198e-08,-4.33473e-08,1.12654,0.000384748,-2.22162e-07,4.33481e-08,1.12693,0.000384434,-9.21174e-08,-1.08356e-08,1.12731,0.000384217,-1.24624e-07,-5.50907e-12,1.12769,0.000383968,-1.24641e-07,1.08577e-08,1.12808,0.000383751,-9.20679e-08,-4.34252e-08,1.12846,0.000383437,-2.22343e-07,4.36337e-08,1.12884,0.000383123,-9.14422e-08,-1.19005e-08,1.12923,0.000382904,-1.27144e-07,3.96813e-09,1.12961,0.000382662,-1.15239e-07,-3.97207e-09,1.12999,0.000382419,-1.27155e-07,1.19201e-08,1.13038,0.000382201,-9.1395e-08,-4.37085e-08,1.13076,0.000381887,-2.2252e-07,4.37046e-08,1.13114,0.000381573,-9.14068e-08,-1.19005e-08,1.13152,0.000381355,-1.27108e-07,3.89734e-09,1.1319,0.000381112,-1.15416e-07,-3.68887e-09,1.13228,0.00038087,-1.26483e-07,1.08582e-08,1.13266,0.00038065,-9.39083e-08,-3.97438e-08,1.13304,0.000380343,-2.1314e-07,2.89076e-08,1.13342,0.000380003,-1.26417e-07,4.33225e-08,1.1338,0.00037988,3.55072e-09,-8.29883e-08,1.13418,0.000379638,-2.45414e-07,5.0212e-08,1.13456,0.000379298,-9.47781e-08,1.34964e-09,1.13494,0.000379113,-9.07292e-08,-5.56105e-08,1.13532,0.000378764,-2.57561e-07,1.01883e-07,1.1357,0.000378555,4.80889e-08,-1.13504e-07,1.13608,0.000378311,-2.92423e-07,1.13713e-07,1.13646,0.000378067,4.87176e-08,-1.02931e-07,1.13683,0.000377856,-2.60076e-07,5.95923e-08,1.13721,0.000377514,-8.12988e-08,-1.62288e-08,1.13759,0.000377303,-1.29985e-07,5.32278e-09,1.13797,0.000377059,-1.14017e-07,-5.06237e-09,1.13834,0.000376816,-1.29204e-07,1.49267e-08,1.13872,0.000376602,-8.44237e-08,-5.46444e-08,1.1391,0.000376269,-2.48357e-07,8.44417e-08,1.13947,0.000376026,4.96815e-09,-4.47039e-08,1.13985,0.000375902,-1.29143e-07,-2.48355e-08,1.14023,0.000375569,-2.0365e-07,2.48368e-08,1.1406,0.000375236,-1.2914e-07,4.46977e-08,1.14098,0.000375112,4.95341e-09,-8.44184e-08,1.14135,0.000374869,-2.48302e-07,5.45572e-08,1.14173,0.000374536,-8.463e-08,-1.46013e-08,1.1421,0.000374323,-1.28434e-07,3.8478e-09,1.14247,0.000374077,-1.1689e-07,-7.89941e-10,1.14285,0.000373841,-1.1926e-07,-6.88042e-10,1.14322,0.0003736,-1.21324e-07,3.54213e-09,1.1436,0.000373368,-1.10698e-07,-1.34805e-08,1.14397,0.000373107,-1.51139e-07,5.03798e-08,1.14434,0.000372767,0.,0.}; + + template + __device__ __forceinline__ void RGB2LuvConvert_f(const T& src, D& dst) + { + const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); + const float _un = 13 * (4 * 0.950456f * _d); + const float _vn = 13 * (9 * _d); + + float B = blueIdx == 0 ? src.x : src.z; + float G = src.y; + float R = blueIdx == 0 ? src.z : src.x; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBGammaTab, GAMMA_TAB_SIZE); + } + + float X = R * 0.412453f + G * 0.357580f + B * 0.180423f; + float Y = R * 0.212671f + G * 0.715160f + B * 0.072169f; + float Z = R * 0.019334f + G * 0.119193f + B * 0.950227f; + + float L = splineInterpolate(Y * (LAB_CBRT_TAB_SIZE / 1.5f), c_LabCbrtTab, LAB_CBRT_TAB_SIZE); + L = 116.f * L - 16.f; + + const float d = (4 * 13) / ::fmaxf(X + 15 * Y + 3 * Z, numeric_limits::epsilon()); + float u = L * (X * d - _un); + float v = L * ((9 * 0.25f) * Y * d - _vn); + + dst.x = L; + dst.y = u; + dst.z = v; + } + + template + __device__ __forceinline__ void RGB2LuvConvert_b(const T& src, D& dst) + { + float3 srcf, dstf; + + srcf.x = src.x * (1.f / 255.f); + srcf.y = src.y * (1.f / 255.f); + srcf.z = src.z * (1.f / 255.f); + + RGB2LuvConvert_f(srcf, dstf); + + dst.x = saturate_cast(dstf.x * 2.55f); + dst.y = saturate_cast(dstf.y * 0.72033898305084743f + 96.525423728813564f); + dst.z = saturate_cast(dstf.z * 0.9732824427480916f + 136.259541984732824f); + } + + template struct RGB2Luv; + template + struct RGB2Luv + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LuvConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Luv() {} + __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} + }; + template + struct RGB2Luv + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + RGB2LuvConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ RGB2Luv() {} + __host__ __device__ __forceinline__ RGB2Luv(const RGB2Luv&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_RGB2Luv_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::RGB2Luv functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + namespace color_detail + { + template + __device__ __forceinline__ void Luv2RGBConvert_f(const T& src, D& dst) + { + const float _d = 1.f / (0.950456f + 15 + 1.088754f * 3); + const float _un = 4 * 0.950456f * _d; + const float _vn = 9 * _d; + + float L = src.x; + float u = src.y; + float v = src.z; + + float Y = (L + 16.f) * (1.f / 116.f); + Y = Y * Y * Y; + + float d = (1.f / 13.f) / L; + u = u * d + _un; + v = v * d + _vn; + + float iv = 1.f / v; + float X = 2.25f * u * Y * iv; + float Z = (12 - 3 * u - 20 * v) * Y * 0.25f * iv; + + float B = 0.055648f * X - 0.204043f * Y + 1.057311f * Z; + float G = -0.969256f * X + 1.875991f * Y + 0.041556f * Z; + float R = 3.240479f * X - 1.537150f * Y - 0.498535f * Z; + + if (srgb) + { + B = splineInterpolate(B * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + G = splineInterpolate(G * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + R = splineInterpolate(R * GAMMA_TAB_SIZE, c_sRGBInvGammaTab, GAMMA_TAB_SIZE); + } + + dst.x = blueIdx == 0 ? B : R; + dst.y = G; + dst.z = blueIdx == 0 ? R : B; + setAlpha(dst, ColorChannel::max()); + } + + template + __device__ __forceinline__ void Luv2RGBConvert_b(const T& src, D& dst) + { + float3 srcf, dstf; + + srcf.x = src.x * (100.f / 255.f); + srcf.y = src.y * 1.388235294117647f - 134.f; + srcf.z = src.z * 1.027450980392157f - 140.f; + + Luv2RGBConvert_f(srcf, dstf); + + dst.x = saturate_cast(dstf.x * 255.f); + dst.y = saturate_cast(dstf.y * 255.f); + dst.z = saturate_cast(dstf.z * 255.f); + setAlpha(dst, ColorChannel::max()); + } + + template struct Luv2RGB; + template + struct Luv2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Luv2RGBConvert_b(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Luv2RGB() {} + __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} + }; + template + struct Luv2RGB + : unary_function::vec_type, typename TypeVec::vec_type> + { + __device__ __forceinline__ typename TypeVec::vec_type operator ()(const typename TypeVec::vec_type& src) const + { + typename TypeVec::vec_type dst; + + Luv2RGBConvert_f(src, dst); + + return dst; + } + __host__ __device__ __forceinline__ Luv2RGB() {} + __host__ __device__ __forceinline__ Luv2RGB(const Luv2RGB&) {} + }; + } + +#define OPENCV_CUDA_IMPLEMENT_Luv2RGB_TRAITS(name, scn, dcn, srgb, blueIdx) \ + template struct name ## _traits \ + { \ + typedef ::cv::cuda::device::color_detail::Luv2RGB functor_type; \ + static __host__ __device__ __forceinline__ functor_type create_functor() \ + { \ + return functor_type(); \ + } \ + }; + + #undef CV_DESCALE + +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_COLOR_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp index 507e6b334d..05a672c3dc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce.hpp @@ -1,394 +1,394 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_REDUCE_DETAIL_HPP -#define OPENCV_CUDA_REDUCE_DETAIL_HPP - -#include -#include "../warp.hpp" -#include "../warp_shuffle.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace reduce_detail - { - template struct GetType; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) - { - thrust::get(smem)[tid] = thrust::get(val); - - For::loadToSmem(smem, val, tid); - } - template - static __device__ void loadFromSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) - { - thrust::get(val) = thrust::get(smem)[tid]; - - For::loadFromSmem(smem, val, tid); - } - - template - static __device__ void merge(const PointerTuple& smem, const ValTuple& val, unsigned int tid, unsigned int delta, const OpTuple& op) - { - typename GetType::type>::type reg = thrust::get(smem)[tid + delta]; - thrust::get(smem)[tid] = thrust::get(val) = thrust::get(op)(thrust::get(val), reg); - - For::merge(smem, val, tid, delta, op); - } - template - static __device__ void mergeShfl(const ValTuple& val, unsigned int delta, unsigned int width, const OpTuple& op) - { - typename GetType::type>::type reg = shfl_down(thrust::get(val), delta, width); - thrust::get(val) = thrust::get(op)(thrust::get(val), reg); - - For::mergeShfl(val, delta, width, op); - } - }; - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple&, const ValTuple&, unsigned int) - { - } - template - static __device__ void loadFromSmem(const PointerTuple&, const ValTuple&, unsigned int) - { - } - - template - static __device__ void merge(const PointerTuple&, const ValTuple&, unsigned int, unsigned int, const OpTuple&) - { - } - template - static __device__ void mergeShfl(const ValTuple&, unsigned int, unsigned int, const OpTuple&) - { - } - }; - - template - __device__ __forceinline__ void loadToSmem(volatile T* smem, T& val, unsigned int tid) - { - smem[tid] = val; - } - template - __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& val, unsigned int tid) - { - val = smem[tid]; - } - - template - __device__ __forceinline__ void merge(volatile T* smem, T& val, unsigned int tid, unsigned int delta, const Op& op) - { - T reg = smem[tid + delta]; - smem[tid] = val = op(val, reg); - } - - template - __device__ __forceinline__ void mergeShfl(T& val, unsigned int delta, unsigned int width, const Op& op) - { - T reg = shfl_down(val, delta, width); - val = op(val, reg); - } - -#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void merge(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid, - unsigned int delta, - const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); - } - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, - unsigned int delta, - unsigned int width, - const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); - } -#else - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); - } - - template - __device__ __forceinline__ void merge(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, unsigned int delta, const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); - } - - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, unsigned int delta, unsigned int width, const thrust::tuple& op) - { - For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); - } -#endif - template struct Generic - { - template - static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) - { - loadToSmem(smem, val, tid); - if (N >= 32) - __syncthreads(); - - if (N >= 2048) - { - if (tid < 1024) - merge(smem, val, tid, 1024, op); - - __syncthreads(); - } - if (N >= 1024) - { - if (tid < 512) - merge(smem, val, tid, 512, op); - - __syncthreads(); - } - if (N >= 512) - { - if (tid < 256) - merge(smem, val, tid, 256, op); - - __syncthreads(); - } - if (N >= 256) - { - if (tid < 128) - merge(smem, val, tid, 128, op); - - __syncthreads(); - } - if (N >= 128) - { - if (tid < 64) - merge(smem, val, tid, 64, op); - - __syncthreads(); - } - if (N >= 64) - { - if (tid < 32) - merge(smem, val, tid, 32, op); - } - - if (tid < 16) - { - merge(smem, val, tid, 16, op); - merge(smem, val, tid, 8, op); - merge(smem, val, tid, 4, op); - merge(smem, val, tid, 2, op); - merge(smem, val, tid, 1, op); - } - } - }; - - template - struct Unroll - { - static __device__ void loopShfl(Reference val, Op op, unsigned int N) - { - mergeShfl(val, I, N, op); - Unroll::loopShfl(val, op, N); - } - static __device__ void loop(Pointer smem, Reference val, unsigned int tid, Op op) - { - merge(smem, val, tid, I, op); - Unroll::loop(smem, val, tid, op); - } - }; - template - struct Unroll<0, Pointer, Reference, Op> - { - static __device__ void loopShfl(Reference, Op, unsigned int) - { - } - static __device__ void loop(Pointer, Reference, unsigned int, Op) - { - } - }; - - template struct WarpOptimized - { - template - static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - CV_UNUSED(smem); - CV_UNUSED(tid); - - Unroll::loopShfl(val, op, N); - #else - loadToSmem(smem, val, tid); - - if (tid < N / 2) - Unroll::loop(smem, val, tid, op); - #endif - } - }; - - template struct GenericOptimized32 - { - enum { M = N / 32 }; - - template - static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) - { - const unsigned int laneId = Warp::laneId(); - - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - Unroll<16, Pointer, Reference, Op>::loopShfl(val, op, warpSize); - - if (laneId == 0) - loadToSmem(smem, val, tid / 32); - #else - loadToSmem(smem, val, tid); - - if (laneId < 16) - Unroll<16, Pointer, Reference, Op>::loop(smem, val, tid, op); - - __syncthreads(); - - if (laneId == 0) - loadToSmem(smem, val, tid / 32); - #endif - - __syncthreads(); - - loadFromSmem(smem, val, tid); - - if (tid < 32) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - Unroll::loopShfl(val, op, M); - #else - Unroll::loop(smem, val, tid, op); - #endif - } - } - }; - - template struct StaticIf; - template struct StaticIf - { - typedef T1 type; - }; - template struct StaticIf - { - typedef T2 type; - }; - - template struct IsPowerOf2 - { - enum { value = ((N != 0) && !(N & (N - 1))) }; - }; - - template struct Dispatcher - { - typedef typename StaticIf< - (N <= 32) && IsPowerOf2::value, - WarpOptimized, - typename StaticIf< - (N <= 1024) && IsPowerOf2::value, - GenericOptimized32, - Generic - >::type - >::type reductor; - }; - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_REDUCE_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_REDUCE_DETAIL_HPP +#define OPENCV_CUDA_REDUCE_DETAIL_HPP + +#include +#include "../warp.hpp" +#include "../warp_shuffle.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace reduce_detail + { + template struct GetType; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) + { + thrust::get(smem)[tid] = thrust::get(val); + + For::loadToSmem(smem, val, tid); + } + template + static __device__ void loadFromSmem(const PointerTuple& smem, const ValTuple& val, unsigned int tid) + { + thrust::get(val) = thrust::get(smem)[tid]; + + For::loadFromSmem(smem, val, tid); + } + + template + static __device__ void merge(const PointerTuple& smem, const ValTuple& val, unsigned int tid, unsigned int delta, const OpTuple& op) + { + typename GetType::type>::type reg = thrust::get(smem)[tid + delta]; + thrust::get(smem)[tid] = thrust::get(val) = thrust::get(op)(thrust::get(val), reg); + + For::merge(smem, val, tid, delta, op); + } + template + static __device__ void mergeShfl(const ValTuple& val, unsigned int delta, unsigned int width, const OpTuple& op) + { + typename GetType::type>::type reg = shfl_down(thrust::get(val), delta, width); + thrust::get(val) = thrust::get(op)(thrust::get(val), reg); + + For::mergeShfl(val, delta, width, op); + } + }; + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple&, const ValTuple&, unsigned int) + { + } + template + static __device__ void loadFromSmem(const PointerTuple&, const ValTuple&, unsigned int) + { + } + + template + static __device__ void merge(const PointerTuple&, const ValTuple&, unsigned int, unsigned int, const OpTuple&) + { + } + template + static __device__ void mergeShfl(const ValTuple&, unsigned int, unsigned int, const OpTuple&) + { + } + }; + + template + __device__ __forceinline__ void loadToSmem(volatile T* smem, T& val, unsigned int tid) + { + smem[tid] = val; + } + template + __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& val, unsigned int tid) + { + val = smem[tid]; + } + + template + __device__ __forceinline__ void merge(volatile T* smem, T& val, unsigned int tid, unsigned int delta, const Op& op) + { + T reg = smem[tid + delta]; + smem[tid] = val = op(val, reg); + } + + template + __device__ __forceinline__ void mergeShfl(T& val, unsigned int delta, unsigned int width, const Op& op) + { + T reg = shfl_down(val, delta, width); + val = op(val, reg); + } + +#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void merge(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid, + unsigned int delta, + const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); + } + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, + unsigned int delta, + unsigned int width, + const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); + } +#else + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, val, tid); + } + + template + __device__ __forceinline__ void merge(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, unsigned int delta, const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::merge(smem, val, tid, delta, op); + } + + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& val, unsigned int delta, unsigned int width, const thrust::tuple& op) + { + For<0, thrust::tuple_size >::value>::mergeShfl(val, delta, width, op); + } +#endif + template struct Generic + { + template + static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) + { + loadToSmem(smem, val, tid); + if (N >= 32) + __syncthreads(); + + if (N >= 2048) + { + if (tid < 1024) + merge(smem, val, tid, 1024, op); + + __syncthreads(); + } + if (N >= 1024) + { + if (tid < 512) + merge(smem, val, tid, 512, op); + + __syncthreads(); + } + if (N >= 512) + { + if (tid < 256) + merge(smem, val, tid, 256, op); + + __syncthreads(); + } + if (N >= 256) + { + if (tid < 128) + merge(smem, val, tid, 128, op); + + __syncthreads(); + } + if (N >= 128) + { + if (tid < 64) + merge(smem, val, tid, 64, op); + + __syncthreads(); + } + if (N >= 64) + { + if (tid < 32) + merge(smem, val, tid, 32, op); + } + + if (tid < 16) + { + merge(smem, val, tid, 16, op); + merge(smem, val, tid, 8, op); + merge(smem, val, tid, 4, op); + merge(smem, val, tid, 2, op); + merge(smem, val, tid, 1, op); + } + } + }; + + template + struct Unroll + { + static __device__ void loopShfl(Reference val, Op op, unsigned int N) + { + mergeShfl(val, I, N, op); + Unroll::loopShfl(val, op, N); + } + static __device__ void loop(Pointer smem, Reference val, unsigned int tid, Op op) + { + merge(smem, val, tid, I, op); + Unroll::loop(smem, val, tid, op); + } + }; + template + struct Unroll<0, Pointer, Reference, Op> + { + static __device__ void loopShfl(Reference, Op, unsigned int) + { + } + static __device__ void loop(Pointer, Reference, unsigned int, Op) + { + } + }; + + template struct WarpOptimized + { + template + static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + CV_UNUSED(smem); + CV_UNUSED(tid); + + Unroll::loopShfl(val, op, N); + #else + loadToSmem(smem, val, tid); + + if (tid < N / 2) + Unroll::loop(smem, val, tid, op); + #endif + } + }; + + template struct GenericOptimized32 + { + enum { M = N / 32 }; + + template + static __device__ void reduce(Pointer smem, Reference val, unsigned int tid, Op op) + { + const unsigned int laneId = Warp::laneId(); + + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + Unroll<16, Pointer, Reference, Op>::loopShfl(val, op, warpSize); + + if (laneId == 0) + loadToSmem(smem, val, tid / 32); + #else + loadToSmem(smem, val, tid); + + if (laneId < 16) + Unroll<16, Pointer, Reference, Op>::loop(smem, val, tid, op); + + __syncthreads(); + + if (laneId == 0) + loadToSmem(smem, val, tid / 32); + #endif + + __syncthreads(); + + loadFromSmem(smem, val, tid); + + if (tid < 32) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + Unroll::loopShfl(val, op, M); + #else + Unroll::loop(smem, val, tid, op); + #endif + } + } + }; + + template struct StaticIf; + template struct StaticIf + { + typedef T1 type; + }; + template struct StaticIf + { + typedef T2 type; + }; + + template struct IsPowerOf2 + { + enum { value = ((N != 0) && !(N & (N - 1))) }; + }; + + template struct Dispatcher + { + typedef typename StaticIf< + (N <= 32) && IsPowerOf2::value, + WarpOptimized, + typename StaticIf< + (N <= 1024) && IsPowerOf2::value, + GenericOptimized32, + Generic + >::type + >::type reductor; + }; + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_REDUCE_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp index 535f9d8ed0..4a248c8365 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/reduce_key_val.hpp @@ -1,567 +1,567 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP -#define OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP - -#include -#include "../warp.hpp" -#include "../warp_shuffle.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace reduce_key_val_detail - { - template struct GetType; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - template struct GetType - { - typedef T type; - }; - - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) - { - thrust::get(smem)[tid] = thrust::get(data); - - For::loadToSmem(smem, data, tid); - } - template - static __device__ void loadFromSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) - { - thrust::get(data) = thrust::get(smem)[tid]; - - For::loadFromSmem(smem, data, tid); - } - - template - static __device__ void copyShfl(const ReferenceTuple& val, unsigned int delta, int width) - { - thrust::get(val) = shfl_down(thrust::get(val), delta, width); - - For::copyShfl(val, delta, width); - } - template - static __device__ void copy(const PointerTuple& svals, const ReferenceTuple& val, unsigned int tid, unsigned int delta) - { - thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; - - For::copy(svals, val, tid, delta); - } - - template - static __device__ void mergeShfl(const KeyReferenceTuple& key, const ValReferenceTuple& val, const CmpTuple& cmp, unsigned int delta, int width) - { - typename GetType::type>::type reg = shfl_down(thrust::get(key), delta, width); - - if (thrust::get(cmp)(reg, thrust::get(key))) - { - thrust::get(key) = reg; - thrust::get(val) = shfl_down(thrust::get(val), delta, width); - } - - For::mergeShfl(key, val, cmp, delta, width); - } - template - static __device__ void merge(const KeyPointerTuple& skeys, const KeyReferenceTuple& key, - const ValPointerTuple& svals, const ValReferenceTuple& val, - const CmpTuple& cmp, - unsigned int tid, unsigned int delta) - { - typename GetType::type>::type reg = thrust::get(skeys)[tid + delta]; - - if (thrust::get(cmp)(reg, thrust::get(key))) - { - thrust::get(skeys)[tid] = thrust::get(key) = reg; - thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; - } - - For::merge(skeys, key, svals, val, cmp, tid, delta); - } - }; - template - struct For - { - template - static __device__ void loadToSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) - { - } - template - static __device__ void loadFromSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) - { - } - - template - static __device__ void copyShfl(const ReferenceTuple&, unsigned int, int) - { - } - template - static __device__ void copy(const PointerTuple&, const ReferenceTuple&, unsigned int, unsigned int) - { - } - - template - static __device__ void mergeShfl(const KeyReferenceTuple&, const ValReferenceTuple&, const CmpTuple&, unsigned int, int) - { - } - template - static __device__ void merge(const KeyPointerTuple&, const KeyReferenceTuple&, - const ValPointerTuple&, const ValReferenceTuple&, - const CmpTuple&, - unsigned int, unsigned int) - { - } - }; - - ////////////////////////////////////////////////////// - // loadToSmem - - template - __device__ __forceinline__ void loadToSmem(volatile T* smem, T& data, unsigned int tid) - { - smem[tid] = data; - } - template - __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& data, unsigned int tid) - { - data = smem[tid]; - } - -#if (CUDART_VERSION < 12040) - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, - const thrust::tuple& data, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); - } - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, - const thrust::tuple& data, - unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); - } -#else - template - __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); - } - template - __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) - { - For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); - } -#endif - - template - __device__ __forceinline__ void copyValsShfl(V& val, unsigned int delta, int width) - { - val = shfl_down(val, delta, width); - } - template - __device__ __forceinline__ void copyVals(volatile V* svals, V& val, unsigned int tid, unsigned int delta) - { - svals[tid] = val = svals[tid + delta]; - } - - template - __device__ __forceinline__ void mergeShfl(K& key, V& val, const Cmp& cmp, unsigned int delta, int width) - { - K reg = shfl_down(key, delta, width); - - if (cmp(reg, key)) - { - key = reg; - copyValsShfl(val, delta, width); - } - } - template - __device__ __forceinline__ void merge(volatile K* skeys, K& key, volatile V* svals, V& val, const Cmp& cmp, unsigned int tid, unsigned int delta) - { - K reg = skeys[tid + delta]; - - if (cmp(reg, key)) - { - skeys[tid] = key = reg; - copyVals(svals, val, tid, delta); - } - } - -#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 - template - __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, - unsigned int delta, - int width) - { - For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); - } - template - __device__ __forceinline__ void copyVals(const thrust::tuple& svals, - const thrust::tuple& val, - unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); - } - - template - __device__ __forceinline__ void mergeShfl(K& key, - const thrust::tuple& val, - const Cmp& cmp, - unsigned int delta, int width) - { - K reg = shfl_down(key, delta, width); - - if (cmp(reg, key)) - { - key = reg; - copyValsShfl(val, delta, width); - } - } - template - __device__ __forceinline__ void merge(volatile K* skeys, K& key, - const thrust::tuple& svals, - const thrust::tuple& val, - const Cmp& cmp, unsigned int tid, unsigned int delta) - { - K reg = skeys[tid + delta]; - - if (cmp(reg, key)) - { - skeys[tid] = key = reg; - copyVals(svals, val, tid, delta); - } - } - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int delta, int width) - { - For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); - } - template - __device__ __forceinline__ void merge(const thrust::tuple& skeys, - const thrust::tuple& key, - const thrust::tuple& svals, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); - } -#else - template - __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, unsigned int delta, int width) - { - For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); - } - template - __device__ __forceinline__ void copyVals(const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); - } - - template - __device__ __forceinline__ void mergeShfl(K& key, const thrust::tuple& val, const Cmp& cmp, unsigned int delta, int width) - { - K reg = shfl_down(key, delta, width); - - if (cmp(reg, key)) - { - key = reg; - copyValsShfl(val, delta, width); - } - } - template - __device__ __forceinline__ void merge(volatile K* skeys, K& key, const thrust::tuple& svals, - const thrust::tuple& val, const Cmp& cmp, unsigned int tid, unsigned int delta) - { - K reg = skeys[tid + delta]; - - if (cmp(reg, key)) - { - skeys[tid] = key = reg; - copyVals(svals, val, tid, delta); - } - } - template - __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int delta, int width) - { - For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); - } - template - __device__ __forceinline__ void merge(const thrust::tuple& skeys, - const thrust::tuple& key, - const thrust::tuple& svals, - const thrust::tuple& val, - const thrust::tuple& cmp, - unsigned int tid, unsigned int delta) - { - For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); - } - -#endif - ////////////////////////////////////////////////////// - // Generic - - template struct Generic - { - template - static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - loadToSmem(skeys, key, tid); - loadValsToSmem(svals, val, tid); - if (N >= 32) - __syncthreads(); - - if (N >= 2048) - { - if (tid < 1024) - merge(skeys, key, svals, val, cmp, tid, 1024); - - __syncthreads(); - } - if (N >= 1024) - { - if (tid < 512) - merge(skeys, key, svals, val, cmp, tid, 512); - - __syncthreads(); - } - if (N >= 512) - { - if (tid < 256) - merge(skeys, key, svals, val, cmp, tid, 256); - - __syncthreads(); - } - if (N >= 256) - { - if (tid < 128) - merge(skeys, key, svals, val, cmp, tid, 128); - - __syncthreads(); - } - if (N >= 128) - { - if (tid < 64) - merge(skeys, key, svals, val, cmp, tid, 64); - - __syncthreads(); - } - if (N >= 64) - { - if (tid < 32) - merge(skeys, key, svals, val, cmp, tid, 32); - } - - if (tid < 16) - { - merge(skeys, key, svals, val, cmp, tid, 16); - merge(skeys, key, svals, val, cmp, tid, 8); - merge(skeys, key, svals, val, cmp, tid, 4); - merge(skeys, key, svals, val, cmp, tid, 2); - merge(skeys, key, svals, val, cmp, tid, 1); - } - } - }; - - template - struct Unroll - { - static __device__ void loopShfl(KR key, VR val, Cmp cmp, unsigned int N) - { - mergeShfl(key, val, cmp, I, N); - Unroll::loopShfl(key, val, cmp, N); - } - static __device__ void loop(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - merge(skeys, key, svals, val, cmp, tid, I); - Unroll::loop(skeys, key, svals, val, tid, cmp); - } - }; - template - struct Unroll<0, KP, KR, VP, VR, Cmp> - { - static __device__ void loopShfl(KR, VR, Cmp, unsigned int) - { - } - static __device__ void loop(KP, KR, VP, VR, unsigned int, Cmp) - { - } - }; - - template struct WarpOptimized - { - template - static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - #if 0 // __CUDA_ARCH__ >= 300 - CV_UNUSED(skeys); - CV_UNUSED(svals); - CV_UNUSED(tid); - - Unroll::loopShfl(key, val, cmp, N); - #else - loadToSmem(skeys, key, tid); - loadToSmem(svals, val, tid); - - if (tid < N / 2) - Unroll::loop(skeys, key, svals, val, tid, cmp); - #endif - } - }; - - template struct GenericOptimized32 - { - enum { M = N / 32 }; - - template - static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) - { - const unsigned int laneId = Warp::laneId(); - - #if 0 // __CUDA_ARCH__ >= 300 - Unroll<16, KP, KR, VP, VR, Cmp>::loopShfl(key, val, cmp, warpSize); - - if (laneId == 0) - { - loadToSmem(skeys, key, tid / 32); - loadToSmem(svals, val, tid / 32); - } - #else - loadToSmem(skeys, key, tid); - loadToSmem(svals, val, tid); - - if (laneId < 16) - Unroll<16, KP, KR, VP, VR, Cmp>::loop(skeys, key, svals, val, tid, cmp); - - __syncthreads(); - - if (laneId == 0) - { - loadToSmem(skeys, key, tid / 32); - loadToSmem(svals, val, tid / 32); - } - #endif - - __syncthreads(); - - loadFromSmem(skeys, key, tid); - - if (tid < 32) - { - #if 0 // __CUDA_ARCH__ >= 300 - loadFromSmem(svals, val, tid); - - Unroll::loopShfl(key, val, cmp, M); - #else - Unroll::loop(skeys, key, svals, val, tid, cmp); - #endif - } - } - }; - - template struct StaticIf; - template struct StaticIf - { - typedef T1 type; - }; - template struct StaticIf - { - typedef T2 type; - }; - - template struct IsPowerOf2 - { - enum { value = ((N != 0) && !(N & (N - 1))) }; - }; - - template struct Dispatcher - { - typedef typename StaticIf< - (N <= 32) && IsPowerOf2::value, - WarpOptimized, - typename StaticIf< - (N <= 1024) && IsPowerOf2::value, - GenericOptimized32, - Generic - >::type - >::type reductor; - }; - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP +#define OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP + +#include +#include "../warp.hpp" +#include "../warp_shuffle.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace reduce_key_val_detail + { + template struct GetType; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + template struct GetType + { + typedef T type; + }; + + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) + { + thrust::get(smem)[tid] = thrust::get(data); + + For::loadToSmem(smem, data, tid); + } + template + static __device__ void loadFromSmem(const PointerTuple& smem, const ReferenceTuple& data, unsigned int tid) + { + thrust::get(data) = thrust::get(smem)[tid]; + + For::loadFromSmem(smem, data, tid); + } + + template + static __device__ void copyShfl(const ReferenceTuple& val, unsigned int delta, int width) + { + thrust::get(val) = shfl_down(thrust::get(val), delta, width); + + For::copyShfl(val, delta, width); + } + template + static __device__ void copy(const PointerTuple& svals, const ReferenceTuple& val, unsigned int tid, unsigned int delta) + { + thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; + + For::copy(svals, val, tid, delta); + } + + template + static __device__ void mergeShfl(const KeyReferenceTuple& key, const ValReferenceTuple& val, const CmpTuple& cmp, unsigned int delta, int width) + { + typename GetType::type>::type reg = shfl_down(thrust::get(key), delta, width); + + if (thrust::get(cmp)(reg, thrust::get(key))) + { + thrust::get(key) = reg; + thrust::get(val) = shfl_down(thrust::get(val), delta, width); + } + + For::mergeShfl(key, val, cmp, delta, width); + } + template + static __device__ void merge(const KeyPointerTuple& skeys, const KeyReferenceTuple& key, + const ValPointerTuple& svals, const ValReferenceTuple& val, + const CmpTuple& cmp, + unsigned int tid, unsigned int delta) + { + typename GetType::type>::type reg = thrust::get(skeys)[tid + delta]; + + if (thrust::get(cmp)(reg, thrust::get(key))) + { + thrust::get(skeys)[tid] = thrust::get(key) = reg; + thrust::get(svals)[tid] = thrust::get(val) = thrust::get(svals)[tid + delta]; + } + + For::merge(skeys, key, svals, val, cmp, tid, delta); + } + }; + template + struct For + { + template + static __device__ void loadToSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) + { + } + template + static __device__ void loadFromSmem(const PointerTuple&, const ReferenceTuple&, unsigned int) + { + } + + template + static __device__ void copyShfl(const ReferenceTuple&, unsigned int, int) + { + } + template + static __device__ void copy(const PointerTuple&, const ReferenceTuple&, unsigned int, unsigned int) + { + } + + template + static __device__ void mergeShfl(const KeyReferenceTuple&, const ValReferenceTuple&, const CmpTuple&, unsigned int, int) + { + } + template + static __device__ void merge(const KeyPointerTuple&, const KeyReferenceTuple&, + const ValPointerTuple&, const ValReferenceTuple&, + const CmpTuple&, + unsigned int, unsigned int) + { + } + }; + + ////////////////////////////////////////////////////// + // loadToSmem + + template + __device__ __forceinline__ void loadToSmem(volatile T* smem, T& data, unsigned int tid) + { + smem[tid] = data; + } + template + __device__ __forceinline__ void loadFromSmem(volatile T* smem, T& data, unsigned int tid) + { + data = smem[tid]; + } + +#if (CUDART_VERSION < 12040) + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, + const thrust::tuple& data, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); + } + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, + const thrust::tuple& data, + unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); + } +#else + template + __device__ __forceinline__ void loadToSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadToSmem(smem, data, tid); + } + template + __device__ __forceinline__ void loadFromSmem(const thrust::tuple& smem, const thrust::tuple& data, unsigned int tid) + { + For<0, thrust::tuple_size >::value>::loadFromSmem(smem, data, tid); + } +#endif + + template + __device__ __forceinline__ void copyValsShfl(V& val, unsigned int delta, int width) + { + val = shfl_down(val, delta, width); + } + template + __device__ __forceinline__ void copyVals(volatile V* svals, V& val, unsigned int tid, unsigned int delta) + { + svals[tid] = val = svals[tid + delta]; + } + + template + __device__ __forceinline__ void mergeShfl(K& key, V& val, const Cmp& cmp, unsigned int delta, int width) + { + K reg = shfl_down(key, delta, width); + + if (cmp(reg, key)) + { + key = reg; + copyValsShfl(val, delta, width); + } + } + template + __device__ __forceinline__ void merge(volatile K* skeys, K& key, volatile V* svals, V& val, const Cmp& cmp, unsigned int tid, unsigned int delta) + { + K reg = skeys[tid + delta]; + + if (cmp(reg, key)) + { + skeys[tid] = key = reg; + copyVals(svals, val, tid, delta); + } + } + +#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 + template + __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, + unsigned int delta, + int width) + { + For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); + } + template + __device__ __forceinline__ void copyVals(const thrust::tuple& svals, + const thrust::tuple& val, + unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); + } + + template + __device__ __forceinline__ void mergeShfl(K& key, + const thrust::tuple& val, + const Cmp& cmp, + unsigned int delta, int width) + { + K reg = shfl_down(key, delta, width); + + if (cmp(reg, key)) + { + key = reg; + copyValsShfl(val, delta, width); + } + } + template + __device__ __forceinline__ void merge(volatile K* skeys, K& key, + const thrust::tuple& svals, + const thrust::tuple& val, + const Cmp& cmp, unsigned int tid, unsigned int delta) + { + K reg = skeys[tid + delta]; + + if (cmp(reg, key)) + { + skeys[tid] = key = reg; + copyVals(svals, val, tid, delta); + } + } + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int delta, int width) + { + For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); + } + template + __device__ __forceinline__ void merge(const thrust::tuple& skeys, + const thrust::tuple& key, + const thrust::tuple& svals, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); + } +#else + template + __device__ __forceinline__ void copyValsShfl(const thrust::tuple& val, unsigned int delta, int width) + { + For<0, thrust::tuple_size >::value>::copyShfl(val, delta, width); + } + template + __device__ __forceinline__ void copyVals(const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::copy(svals, val, tid, delta); + } + + template + __device__ __forceinline__ void mergeShfl(K& key, const thrust::tuple& val, const Cmp& cmp, unsigned int delta, int width) + { + K reg = shfl_down(key, delta, width); + + if (cmp(reg, key)) + { + key = reg; + copyValsShfl(val, delta, width); + } + } + template + __device__ __forceinline__ void merge(volatile K* skeys, K& key, const thrust::tuple& svals, + const thrust::tuple& val, const Cmp& cmp, unsigned int tid, unsigned int delta) + { + K reg = skeys[tid + delta]; + + if (cmp(reg, key)) + { + skeys[tid] = key = reg; + copyVals(svals, val, tid, delta); + } + } + template + __device__ __forceinline__ void mergeShfl(const thrust::tuple& key, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int delta, int width) + { + For<0, thrust::tuple_size >::value>::mergeShfl(key, val, cmp, delta, width); + } + template + __device__ __forceinline__ void merge(const thrust::tuple& skeys, + const thrust::tuple& key, + const thrust::tuple& svals, + const thrust::tuple& val, + const thrust::tuple& cmp, + unsigned int tid, unsigned int delta) + { + For<0, thrust::tuple_size >::value>::merge(skeys, key, svals, val, cmp, tid, delta); + } + +#endif + ////////////////////////////////////////////////////// + // Generic + + template struct Generic + { + template + static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + loadToSmem(skeys, key, tid); + loadValsToSmem(svals, val, tid); + if (N >= 32) + __syncthreads(); + + if (N >= 2048) + { + if (tid < 1024) + merge(skeys, key, svals, val, cmp, tid, 1024); + + __syncthreads(); + } + if (N >= 1024) + { + if (tid < 512) + merge(skeys, key, svals, val, cmp, tid, 512); + + __syncthreads(); + } + if (N >= 512) + { + if (tid < 256) + merge(skeys, key, svals, val, cmp, tid, 256); + + __syncthreads(); + } + if (N >= 256) + { + if (tid < 128) + merge(skeys, key, svals, val, cmp, tid, 128); + + __syncthreads(); + } + if (N >= 128) + { + if (tid < 64) + merge(skeys, key, svals, val, cmp, tid, 64); + + __syncthreads(); + } + if (N >= 64) + { + if (tid < 32) + merge(skeys, key, svals, val, cmp, tid, 32); + } + + if (tid < 16) + { + merge(skeys, key, svals, val, cmp, tid, 16); + merge(skeys, key, svals, val, cmp, tid, 8); + merge(skeys, key, svals, val, cmp, tid, 4); + merge(skeys, key, svals, val, cmp, tid, 2); + merge(skeys, key, svals, val, cmp, tid, 1); + } + } + }; + + template + struct Unroll + { + static __device__ void loopShfl(KR key, VR val, Cmp cmp, unsigned int N) + { + mergeShfl(key, val, cmp, I, N); + Unroll::loopShfl(key, val, cmp, N); + } + static __device__ void loop(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + merge(skeys, key, svals, val, cmp, tid, I); + Unroll::loop(skeys, key, svals, val, tid, cmp); + } + }; + template + struct Unroll<0, KP, KR, VP, VR, Cmp> + { + static __device__ void loopShfl(KR, VR, Cmp, unsigned int) + { + } + static __device__ void loop(KP, KR, VP, VR, unsigned int, Cmp) + { + } + }; + + template struct WarpOptimized + { + template + static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + #if 0 // __CUDA_ARCH__ >= 300 + CV_UNUSED(skeys); + CV_UNUSED(svals); + CV_UNUSED(tid); + + Unroll::loopShfl(key, val, cmp, N); + #else + loadToSmem(skeys, key, tid); + loadToSmem(svals, val, tid); + + if (tid < N / 2) + Unroll::loop(skeys, key, svals, val, tid, cmp); + #endif + } + }; + + template struct GenericOptimized32 + { + enum { M = N / 32 }; + + template + static __device__ void reduce(KP skeys, KR key, VP svals, VR val, unsigned int tid, Cmp cmp) + { + const unsigned int laneId = Warp::laneId(); + + #if 0 // __CUDA_ARCH__ >= 300 + Unroll<16, KP, KR, VP, VR, Cmp>::loopShfl(key, val, cmp, warpSize); + + if (laneId == 0) + { + loadToSmem(skeys, key, tid / 32); + loadToSmem(svals, val, tid / 32); + } + #else + loadToSmem(skeys, key, tid); + loadToSmem(svals, val, tid); + + if (laneId < 16) + Unroll<16, KP, KR, VP, VR, Cmp>::loop(skeys, key, svals, val, tid, cmp); + + __syncthreads(); + + if (laneId == 0) + { + loadToSmem(skeys, key, tid / 32); + loadToSmem(svals, val, tid / 32); + } + #endif + + __syncthreads(); + + loadFromSmem(skeys, key, tid); + + if (tid < 32) + { + #if 0 // __CUDA_ARCH__ >= 300 + loadFromSmem(svals, val, tid); + + Unroll::loopShfl(key, val, cmp, M); + #else + Unroll::loop(skeys, key, svals, val, tid, cmp); + #endif + } + } + }; + + template struct StaticIf; + template struct StaticIf + { + typedef T1 type; + }; + template struct StaticIf + { + typedef T2 type; + }; + + template struct IsPowerOf2 + { + enum { value = ((N != 0) && !(N & (N - 1))) }; + }; + + template struct Dispatcher + { + typedef typename StaticIf< + (N <= 32) && IsPowerOf2::value, + WarpOptimized, + typename StaticIf< + (N <= 1024) && IsPowerOf2::value, + GenericOptimized32, + Generic + >::type + >::type reductor; + }; + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_PRED_VAL_REDUCE_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp index e04e5b45aa..1919848827 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/transform_detail.hpp @@ -1,392 +1,392 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_TRANSFORM_DETAIL_HPP -#define OPENCV_CUDA_TRANSFORM_DETAIL_HPP - -#include "../common.hpp" -#include "../vec_traits.hpp" -#include "../functional.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace transform_detail - { - //! Read Write Traits - - template struct UnaryReadWriteTraits - { - typedef typename TypeVec::vec_type read_type; - typedef typename TypeVec::vec_type write_type; - }; - - template struct BinaryReadWriteTraits - { - typedef typename TypeVec::vec_type read_type1; - typedef typename TypeVec::vec_type read_type2; - typedef typename TypeVec::vec_type write_type; - }; - - //! Transform kernels - - template struct OpUnroller; - template <> struct OpUnroller<1> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - } - }; - template <> struct OpUnroller<2> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src.y); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src1.y, src2.y); - } - }; - template <> struct OpUnroller<3> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src.z); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src1.y, src2.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src1.z, src2.z); - } - }; - template <> struct OpUnroller<4> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src.z); - if (mask(y, x_shifted + 3)) - dst.w = op(src.w); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.x = op(src1.x, src2.x); - if (mask(y, x_shifted + 1)) - dst.y = op(src1.y, src2.y); - if (mask(y, x_shifted + 2)) - dst.z = op(src1.z, src2.z); - if (mask(y, x_shifted + 3)) - dst.w = op(src1.w, src2.w); - } - }; - template <> struct OpUnroller<8> - { - template - static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.a0 = op(src.a0); - if (mask(y, x_shifted + 1)) - dst.a1 = op(src.a1); - if (mask(y, x_shifted + 2)) - dst.a2 = op(src.a2); - if (mask(y, x_shifted + 3)) - dst.a3 = op(src.a3); - if (mask(y, x_shifted + 4)) - dst.a4 = op(src.a4); - if (mask(y, x_shifted + 5)) - dst.a5 = op(src.a5); - if (mask(y, x_shifted + 6)) - dst.a6 = op(src.a6); - if (mask(y, x_shifted + 7)) - dst.a7 = op(src.a7); - } - - template - static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) - { - if (mask(y, x_shifted)) - dst.a0 = op(src1.a0, src2.a0); - if (mask(y, x_shifted + 1)) - dst.a1 = op(src1.a1, src2.a1); - if (mask(y, x_shifted + 2)) - dst.a2 = op(src1.a2, src2.a2); - if (mask(y, x_shifted + 3)) - dst.a3 = op(src1.a3, src2.a3); - if (mask(y, x_shifted + 4)) - dst.a4 = op(src1.a4, src2.a4); - if (mask(y, x_shifted + 5)) - dst.a5 = op(src1.a5, src2.a5); - if (mask(y, x_shifted + 6)) - dst.a6 = op(src1.a6, src2.a6); - if (mask(y, x_shifted + 7)) - dst.a7 = op(src1.a7, src2.a7); - } - }; - - template - static __global__ void transformSmart(const PtrStepSz src_, PtrStep dst_, const Mask mask, const UnOp op) - { - typedef TransformFunctorTraits ft; - typedef typename UnaryReadWriteTraits::read_type read_type; - typedef typename UnaryReadWriteTraits::write_type write_type; - - const int x = threadIdx.x + blockIdx.x * blockDim.x; - const int y = threadIdx.y + blockIdx.y * blockDim.y; - const int x_shifted = x * ft::smart_shift; - - if (y < src_.rows) - { - const T* src = src_.ptr(y); - D* dst = dst_.ptr(y); - - if (x_shifted + ft::smart_shift - 1 < src_.cols) - { - const read_type src_n_el = ((const read_type*)src)[x]; - OpUnroller::unroll(src_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); - } - else - { - for (int real_x = x_shifted; real_x < src_.cols; ++real_x) - { - if (mask(y, real_x)) - dst[real_x] = op(src[real_x]); - } - } - } - } - - template - __global__ static void transformSimple(const PtrStepSz src, PtrStep dst, const Mask mask, const UnOp op) - { - const int x = blockDim.x * blockIdx.x + threadIdx.x; - const int y = blockDim.y * blockIdx.y + threadIdx.y; - - if (x < src.cols && y < src.rows && mask(y, x)) - { - dst.ptr(y)[x] = op(src.ptr(y)[x]); - } - } - - template - static __global__ void transformSmart(const PtrStepSz src1_, const PtrStep src2_, PtrStep dst_, - const Mask mask, const BinOp op) - { - typedef TransformFunctorTraits ft; - typedef typename BinaryReadWriteTraits::read_type1 read_type1; - typedef typename BinaryReadWriteTraits::read_type2 read_type2; - typedef typename BinaryReadWriteTraits::write_type write_type; - - const int x = threadIdx.x + blockIdx.x * blockDim.x; - const int y = threadIdx.y + blockIdx.y * blockDim.y; - const int x_shifted = x * ft::smart_shift; - - if (y < src1_.rows) - { - const T1* src1 = src1_.ptr(y); - const T2* src2 = src2_.ptr(y); - D* dst = dst_.ptr(y); - - if (x_shifted + ft::smart_shift - 1 < src1_.cols) - { - const read_type1 src1_n_el = ((const read_type1*)src1)[x]; - const read_type2 src2_n_el = ((const read_type2*)src2)[x]; - - OpUnroller::unroll(src1_n_el, src2_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); - } - else - { - for (int real_x = x_shifted; real_x < src1_.cols; ++real_x) - { - if (mask(y, real_x)) - dst[real_x] = op(src1[real_x], src2[real_x]); - } - } - } - } - - template - static __global__ void transformSimple(const PtrStepSz src1, const PtrStep src2, PtrStep dst, - const Mask mask, const BinOp op) - { - const int x = blockDim.x * blockIdx.x + threadIdx.x; - const int y = blockDim.y * blockIdx.y + threadIdx.y; - - if (x < src1.cols && y < src1.rows && mask(y, x)) - { - const T1 src1_data = src1.ptr(y)[x]; - const T2 src2_data = src2.ptr(y)[x]; - dst.ptr(y)[x] = op(src1_data, src2_data); - } - } - - template struct TransformDispatcher; - template<> struct TransformDispatcher - { - template - static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); - const dim3 grid(divUp(src.cols, threads.x), divUp(src.rows, threads.y), 1); - - transformSimple<<>>(src, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - - template - static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); - const dim3 grid(divUp(src1.cols, threads.x), divUp(src1.rows, threads.y), 1); - - transformSimple<<>>(src1, src2, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - }; - template<> struct TransformDispatcher - { - template - static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - CV_StaticAssert(ft::smart_shift != 1, ""); - - if (!isAligned(src.data, ft::smart_shift * sizeof(T)) || !isAligned(src.step, ft::smart_shift * sizeof(T)) || - !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) - { - TransformDispatcher::call(src, dst, op, mask, stream); - return; - } - - const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); - const dim3 grid(divUp(src.cols, threads.x * ft::smart_shift), divUp(src.rows, threads.y), 1); - - transformSmart<<>>(src, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - - template - static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - - CV_StaticAssert(ft::smart_shift != 1, ""); - - if (!isAligned(src1.data, ft::smart_shift * sizeof(T1)) || !isAligned(src1.step, ft::smart_shift * sizeof(T1)) || - !isAligned(src2.data, ft::smart_shift * sizeof(T2)) || !isAligned(src2.step, ft::smart_shift * sizeof(T2)) || - !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) - { - TransformDispatcher::call(src1, src2, dst, op, mask, stream); - return; - } - - const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); - const dim3 grid(divUp(src1.cols, threads.x * ft::smart_shift), divUp(src1.rows, threads.y), 1); - - transformSmart<<>>(src1, src2, dst, mask, op); - cudaSafeCall( cudaGetLastError() ); - - if (stream == 0) - cudaSafeCall( cudaDeviceSynchronize() ); - } - }; - } // namespace transform_detail -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_TRANSFORM_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_TRANSFORM_DETAIL_HPP +#define OPENCV_CUDA_TRANSFORM_DETAIL_HPP + +#include "../common.hpp" +#include "../vec_traits.hpp" +#include "../functional.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace transform_detail + { + //! Read Write Traits + + template struct UnaryReadWriteTraits + { + typedef typename TypeVec::vec_type read_type; + typedef typename TypeVec::vec_type write_type; + }; + + template struct BinaryReadWriteTraits + { + typedef typename TypeVec::vec_type read_type1; + typedef typename TypeVec::vec_type read_type2; + typedef typename TypeVec::vec_type write_type; + }; + + //! Transform kernels + + template struct OpUnroller; + template <> struct OpUnroller<1> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + } + }; + template <> struct OpUnroller<2> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src.y); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src1.y, src2.y); + } + }; + template <> struct OpUnroller<3> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src.z); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src1.y, src2.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src1.z, src2.z); + } + }; + template <> struct OpUnroller<4> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src.z); + if (mask(y, x_shifted + 3)) + dst.w = op(src.w); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.x = op(src1.x, src2.x); + if (mask(y, x_shifted + 1)) + dst.y = op(src1.y, src2.y); + if (mask(y, x_shifted + 2)) + dst.z = op(src1.z, src2.z); + if (mask(y, x_shifted + 3)) + dst.w = op(src1.w, src2.w); + } + }; + template <> struct OpUnroller<8> + { + template + static __device__ __forceinline__ void unroll(const T& src, D& dst, const Mask& mask, const UnOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.a0 = op(src.a0); + if (mask(y, x_shifted + 1)) + dst.a1 = op(src.a1); + if (mask(y, x_shifted + 2)) + dst.a2 = op(src.a2); + if (mask(y, x_shifted + 3)) + dst.a3 = op(src.a3); + if (mask(y, x_shifted + 4)) + dst.a4 = op(src.a4); + if (mask(y, x_shifted + 5)) + dst.a5 = op(src.a5); + if (mask(y, x_shifted + 6)) + dst.a6 = op(src.a6); + if (mask(y, x_shifted + 7)) + dst.a7 = op(src.a7); + } + + template + static __device__ __forceinline__ void unroll(const T1& src1, const T2& src2, D& dst, const Mask& mask, const BinOp& op, int x_shifted, int y) + { + if (mask(y, x_shifted)) + dst.a0 = op(src1.a0, src2.a0); + if (mask(y, x_shifted + 1)) + dst.a1 = op(src1.a1, src2.a1); + if (mask(y, x_shifted + 2)) + dst.a2 = op(src1.a2, src2.a2); + if (mask(y, x_shifted + 3)) + dst.a3 = op(src1.a3, src2.a3); + if (mask(y, x_shifted + 4)) + dst.a4 = op(src1.a4, src2.a4); + if (mask(y, x_shifted + 5)) + dst.a5 = op(src1.a5, src2.a5); + if (mask(y, x_shifted + 6)) + dst.a6 = op(src1.a6, src2.a6); + if (mask(y, x_shifted + 7)) + dst.a7 = op(src1.a7, src2.a7); + } + }; + + template + static __global__ void transformSmart(const PtrStepSz src_, PtrStep dst_, const Mask mask, const UnOp op) + { + typedef TransformFunctorTraits ft; + typedef typename UnaryReadWriteTraits::read_type read_type; + typedef typename UnaryReadWriteTraits::write_type write_type; + + const int x = threadIdx.x + blockIdx.x * blockDim.x; + const int y = threadIdx.y + blockIdx.y * blockDim.y; + const int x_shifted = x * ft::smart_shift; + + if (y < src_.rows) + { + const T* src = src_.ptr(y); + D* dst = dst_.ptr(y); + + if (x_shifted + ft::smart_shift - 1 < src_.cols) + { + const read_type src_n_el = ((const read_type*)src)[x]; + OpUnroller::unroll(src_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); + } + else + { + for (int real_x = x_shifted; real_x < src_.cols; ++real_x) + { + if (mask(y, real_x)) + dst[real_x] = op(src[real_x]); + } + } + } + } + + template + __global__ static void transformSimple(const PtrStepSz src, PtrStep dst, const Mask mask, const UnOp op) + { + const int x = blockDim.x * blockIdx.x + threadIdx.x; + const int y = blockDim.y * blockIdx.y + threadIdx.y; + + if (x < src.cols && y < src.rows && mask(y, x)) + { + dst.ptr(y)[x] = op(src.ptr(y)[x]); + } + } + + template + static __global__ void transformSmart(const PtrStepSz src1_, const PtrStep src2_, PtrStep dst_, + const Mask mask, const BinOp op) + { + typedef TransformFunctorTraits ft; + typedef typename BinaryReadWriteTraits::read_type1 read_type1; + typedef typename BinaryReadWriteTraits::read_type2 read_type2; + typedef typename BinaryReadWriteTraits::write_type write_type; + + const int x = threadIdx.x + blockIdx.x * blockDim.x; + const int y = threadIdx.y + blockIdx.y * blockDim.y; + const int x_shifted = x * ft::smart_shift; + + if (y < src1_.rows) + { + const T1* src1 = src1_.ptr(y); + const T2* src2 = src2_.ptr(y); + D* dst = dst_.ptr(y); + + if (x_shifted + ft::smart_shift - 1 < src1_.cols) + { + const read_type1 src1_n_el = ((const read_type1*)src1)[x]; + const read_type2 src2_n_el = ((const read_type2*)src2)[x]; + + OpUnroller::unroll(src1_n_el, src2_n_el, ((write_type*)dst)[x], mask, op, x_shifted, y); + } + else + { + for (int real_x = x_shifted; real_x < src1_.cols; ++real_x) + { + if (mask(y, real_x)) + dst[real_x] = op(src1[real_x], src2[real_x]); + } + } + } + } + + template + static __global__ void transformSimple(const PtrStepSz src1, const PtrStep src2, PtrStep dst, + const Mask mask, const BinOp op) + { + const int x = blockDim.x * blockIdx.x + threadIdx.x; + const int y = blockDim.y * blockIdx.y + threadIdx.y; + + if (x < src1.cols && y < src1.rows && mask(y, x)) + { + const T1 src1_data = src1.ptr(y)[x]; + const T2 src2_data = src2.ptr(y)[x]; + dst.ptr(y)[x] = op(src1_data, src2_data); + } + } + + template struct TransformDispatcher; + template<> struct TransformDispatcher + { + template + static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); + const dim3 grid(divUp(src.cols, threads.x), divUp(src.rows, threads.y), 1); + + transformSimple<<>>(src, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + + template + static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + const dim3 threads(ft::simple_block_dim_x, ft::simple_block_dim_y, 1); + const dim3 grid(divUp(src1.cols, threads.x), divUp(src1.rows, threads.y), 1); + + transformSimple<<>>(src1, src2, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + }; + template<> struct TransformDispatcher + { + template + static void call(PtrStepSz src, PtrStepSz dst, UnOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + CV_StaticAssert(ft::smart_shift != 1, ""); + + if (!isAligned(src.data, ft::smart_shift * sizeof(T)) || !isAligned(src.step, ft::smart_shift * sizeof(T)) || + !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) + { + TransformDispatcher::call(src, dst, op, mask, stream); + return; + } + + const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); + const dim3 grid(divUp(src.cols, threads.x * ft::smart_shift), divUp(src.rows, threads.y), 1); + + transformSmart<<>>(src, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + + template + static void call(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, Mask mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + + CV_StaticAssert(ft::smart_shift != 1, ""); + + if (!isAligned(src1.data, ft::smart_shift * sizeof(T1)) || !isAligned(src1.step, ft::smart_shift * sizeof(T1)) || + !isAligned(src2.data, ft::smart_shift * sizeof(T2)) || !isAligned(src2.step, ft::smart_shift * sizeof(T2)) || + !isAligned(dst.data, ft::smart_shift * sizeof(D)) || !isAligned(dst.step, ft::smart_shift * sizeof(D))) + { + TransformDispatcher::call(src1, src2, dst, op, mask, stream); + return; + } + + const dim3 threads(ft::smart_block_dim_x, ft::smart_block_dim_y, 1); + const dim3 grid(divUp(src1.cols, threads.x * ft::smart_shift), divUp(src1.rows, threads.y), 1); + + transformSmart<<>>(src1, src2, dst, mask, op); + cudaSafeCall( cudaGetLastError() ); + + if (stream == 0) + cudaSafeCall( cudaDeviceSynchronize() ); + } + }; + } // namespace transform_detail +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_TRANSFORM_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp index da62978d19..a78bd2c0d8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/type_traits_detail.hpp @@ -1,191 +1,191 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP -#define OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP - -#include "../common.hpp" -#include "../vec_traits.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace type_traits_detail - { - template struct Select { typedef T1 type; }; - template struct Select { typedef T2 type; }; - - template struct IsSignedIntergral { enum {value = 0}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - template <> struct IsSignedIntergral { enum {value = 1}; }; - - template struct IsUnsignedIntegral { enum {value = 0}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - template <> struct IsUnsignedIntegral { enum {value = 1}; }; - - template struct IsIntegral { enum {value = IsSignedIntergral::value || IsUnsignedIntegral::value}; }; - template <> struct IsIntegral { enum {value = 1}; }; - template <> struct IsIntegral { enum {value = 1}; }; - - template struct IsFloat { enum {value = 0}; }; - template <> struct IsFloat { enum {value = 1}; }; - template <> struct IsFloat { enum {value = 1}; }; - - template struct IsVec { enum {value = 0}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - template <> struct IsVec { enum {value = 1}; }; - - template struct AddParameterType { typedef const U& type; }; - template struct AddParameterType { typedef U& type; }; - template <> struct AddParameterType { typedef void type; }; - - template struct ReferenceTraits - { - enum { value = false }; - typedef U type; - }; - template struct ReferenceTraits - { - enum { value = true }; - typedef U type; - }; - - template struct PointerTraits - { - enum { value = false }; - typedef void type; - }; - template struct PointerTraits - { - enum { value = true }; - typedef U type; - }; - template struct PointerTraits - { - enum { value = true }; - typedef U type; - }; - - template struct UnConst - { - typedef U type; - enum { value = 0 }; - }; - template struct UnConst - { - typedef U type; - enum { value = 1 }; - }; - template struct UnConst - { - typedef U& type; - enum { value = 1 }; - }; - - template struct UnVolatile - { - typedef U type; - enum { value = 0 }; - }; - template struct UnVolatile - { - typedef U type; - enum { value = 1 }; - }; - template struct UnVolatile - { - typedef U& type; - enum { value = 1 }; - }; - } // namespace type_traits_detail -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP +#define OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP + +#include "../common.hpp" +#include "../vec_traits.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace type_traits_detail + { + template struct Select { typedef T1 type; }; + template struct Select { typedef T2 type; }; + + template struct IsSignedIntergral { enum {value = 0}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + template <> struct IsSignedIntergral { enum {value = 1}; }; + + template struct IsUnsignedIntegral { enum {value = 0}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + template <> struct IsUnsignedIntegral { enum {value = 1}; }; + + template struct IsIntegral { enum {value = IsSignedIntergral::value || IsUnsignedIntegral::value}; }; + template <> struct IsIntegral { enum {value = 1}; }; + template <> struct IsIntegral { enum {value = 1}; }; + + template struct IsFloat { enum {value = 0}; }; + template <> struct IsFloat { enum {value = 1}; }; + template <> struct IsFloat { enum {value = 1}; }; + + template struct IsVec { enum {value = 0}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + template <> struct IsVec { enum {value = 1}; }; + + template struct AddParameterType { typedef const U& type; }; + template struct AddParameterType { typedef U& type; }; + template <> struct AddParameterType { typedef void type; }; + + template struct ReferenceTraits + { + enum { value = false }; + typedef U type; + }; + template struct ReferenceTraits + { + enum { value = true }; + typedef U type; + }; + + template struct PointerTraits + { + enum { value = false }; + typedef void type; + }; + template struct PointerTraits + { + enum { value = true }; + typedef U type; + }; + template struct PointerTraits + { + enum { value = true }; + typedef U type; + }; + + template struct UnConst + { + typedef U type; + enum { value = 0 }; + }; + template struct UnConst + { + typedef U type; + enum { value = 1 }; + }; + template struct UnConst + { + typedef U& type; + enum { value = 1 }; + }; + + template struct UnVolatile + { + typedef U type; + enum { value = 0 }; + }; + template struct UnVolatile + { + typedef U type; + enum { value = 1 }; + }; + template struct UnVolatile + { + typedef U& type; + enum { value = 1 }; + }; + } // namespace type_traits_detail +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_TYPE_TRAITS_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp index 74604f8302..8283a99560 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/detail/vec_distance_detail.hpp @@ -1,121 +1,121 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP -#define OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP - -#include "../datamov_utils.hpp" - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - namespace vec_distance_detail - { - template struct UnrollVecDiffCached - { - template - static __device__ void calcCheck(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int ind) - { - if (ind < len) - { - T1 val1 = *vecCached++; - - T2 val2; - ForceGlob::Load(vecGlob, ind, val2); - - dist.reduceIter(val1, val2); - - UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, ind + THREAD_DIM); - } - } - - template - static __device__ void calcWithoutCheck(const T1* vecCached, const T2* vecGlob, Dist& dist) - { - T1 val1 = *vecCached++; - - T2 val2; - ForceGlob::Load(vecGlob, 0, val2); - vecGlob += THREAD_DIM; - - dist.reduceIter(val1, val2); - - UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob, dist); - } - }; - template struct UnrollVecDiffCached - { - template - static __device__ __forceinline__ void calcCheck(const T1*, const T2*, int, Dist&, int) - { - } - - template - static __device__ __forceinline__ void calcWithoutCheck(const T1*, const T2*, Dist&) - { - } - }; - - template struct VecDiffCachedCalculator; - template struct VecDiffCachedCalculator - { - template - static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) - { - UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, tid); - } - }; - template struct VecDiffCachedCalculator - { - template - static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) - { - UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob + tid, dist); - } - }; - } // namespace vec_distance_detail -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP +#define OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP + +#include "../datamov_utils.hpp" + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + namespace vec_distance_detail + { + template struct UnrollVecDiffCached + { + template + static __device__ void calcCheck(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int ind) + { + if (ind < len) + { + T1 val1 = *vecCached++; + + T2 val2; + ForceGlob::Load(vecGlob, ind, val2); + + dist.reduceIter(val1, val2); + + UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, ind + THREAD_DIM); + } + } + + template + static __device__ void calcWithoutCheck(const T1* vecCached, const T2* vecGlob, Dist& dist) + { + T1 val1 = *vecCached++; + + T2 val2; + ForceGlob::Load(vecGlob, 0, val2); + vecGlob += THREAD_DIM; + + dist.reduceIter(val1, val2); + + UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob, dist); + } + }; + template struct UnrollVecDiffCached + { + template + static __device__ __forceinline__ void calcCheck(const T1*, const T2*, int, Dist&, int) + { + } + + template + static __device__ __forceinline__ void calcWithoutCheck(const T1*, const T2*, Dist&) + { + } + }; + + template struct VecDiffCachedCalculator; + template struct VecDiffCachedCalculator + { + template + static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) + { + UnrollVecDiffCached::calcCheck(vecCached, vecGlob, len, dist, tid); + } + }; + template struct VecDiffCachedCalculator + { + template + static __device__ __forceinline__ void calc(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, int tid) + { + UnrollVecDiffCached::calcWithoutCheck(vecCached, vecGlob + tid, dist); + } + }; + } // namespace vec_distance_detail +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_VEC_DISTANCE_DETAIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp index 61e88cfff0..42570c6830 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/dynamic_smem.hpp @@ -1,88 +1,88 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_DYNAMIC_SMEM_HPP -#define OPENCV_CUDA_DYNAMIC_SMEM_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct DynamicSharedMem - { - __device__ __forceinline__ operator T*() - { - extern __shared__ int __smem[]; - return (T*)__smem; - } - - __device__ __forceinline__ operator const T*() const - { - extern __shared__ int __smem[]; - return (T*)__smem; - } - }; - - // specialize for double to avoid unaligned memory access compile errors - template<> struct DynamicSharedMem - { - __device__ __forceinline__ operator double*() - { - extern __shared__ double __smem_d[]; - return (double*)__smem_d; - } - - __device__ __forceinline__ operator const double*() const - { - extern __shared__ double __smem_d[]; - return (double*)__smem_d; - } - }; -}}} - -//! @endcond - -#endif // OPENCV_CUDA_DYNAMIC_SMEM_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_DYNAMIC_SMEM_HPP +#define OPENCV_CUDA_DYNAMIC_SMEM_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct DynamicSharedMem + { + __device__ __forceinline__ operator T*() + { + extern __shared__ int __smem[]; + return (T*)__smem; + } + + __device__ __forceinline__ operator const T*() const + { + extern __shared__ int __smem[]; + return (T*)__smem; + } + }; + + // specialize for double to avoid unaligned memory access compile errors + template<> struct DynamicSharedMem + { + __device__ __forceinline__ operator double*() + { + extern __shared__ double __smem_d[]; + return (double*)__smem_d; + } + + __device__ __forceinline__ operator const double*() const + { + extern __shared__ double __smem_d[]; + return (double*)__smem_d; + } + }; +}}} + +//! @endcond + +#endif // OPENCV_CUDA_DYNAMIC_SMEM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp index 7697a876b3..17dc1171a2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/emulation.hpp @@ -1,269 +1,269 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_EMULATION_HPP_ -#define OPENCV_CUDA_EMULATION_HPP_ - -#include "common.hpp" -#include "warp_reduce.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct Emulation - { - - static __device__ __forceinline__ int syncthreadsOr(int pred) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) - // just campilation stab - return 0; -#else - return __syncthreads_or(pred); -#endif - } - - template - static __forceinline__ __device__ int Ballot(int predicate) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ >= 200) - return __ballot(predicate); -#else - __shared__ volatile int cta_buffer[CTA_SIZE]; - - int tid = threadIdx.x; - cta_buffer[tid] = predicate ? (1 << (tid & 31)) : 0; - return warp_reduce(cta_buffer); -#endif - } - - struct smem - { - enum { TAG_MASK = (1U << ( (sizeof(unsigned int) << 3) - 5U)) - 1U }; - - template - static __device__ __forceinline__ T atomicInc(T* address, T val) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) - T count; - unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); - do - { - count = *address & TAG_MASK; - count = tag | (count + 1); - *address = count; - } while (*address != count); - - return (count & TAG_MASK) - 1; -#else - return ::atomicInc(address, val); -#endif - } - - template - static __device__ __forceinline__ T atomicAdd(T* address, T val) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) - T count; - unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); - do - { - count = *address & TAG_MASK; - count = tag | (count + val); - *address = count; - } while (*address != count); - - return (count & TAG_MASK) - val; -#else - return ::atomicAdd(address, val); -#endif - } - - template - static __device__ __forceinline__ T atomicMin(T* address, T val) - { -#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) - T count = ::min(*address, val); - do - { - *address = count; - } while (*address > count); - - return count; -#else - return ::atomicMin(address, val); -#endif - } - }; // struct cmem - - struct glob - { - static __device__ __forceinline__ int atomicAdd(int* address, int val) - { - return ::atomicAdd(address, val); - } - static __device__ __forceinline__ unsigned int atomicAdd(unsigned int* address, unsigned int val) - { - return ::atomicAdd(address, val); - } - static __device__ __forceinline__ float atomicAdd(float* address, float val) - { - #if __CUDA_ARCH__ >= 200 - return ::atomicAdd(address, val); - #else - int* address_as_i = (int*) address; - int old = *address_as_i, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_i, assumed, - __float_as_int(val + __int_as_float(assumed))); - } while (assumed != old); - return __int_as_float(old); - #endif - } - static __device__ __forceinline__ double atomicAdd(double* address, double val) - { - #if __CUDA_ARCH__ >= 130 - unsigned long long int* address_as_ull = (unsigned long long int*) address; - unsigned long long int old = *address_as_ull, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_ull, assumed, - __double_as_longlong(val + __longlong_as_double(assumed))); - } while (assumed != old); - return __longlong_as_double(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0; - #endif - } - - static __device__ __forceinline__ int atomicMin(int* address, int val) - { - return ::atomicMin(address, val); - } - static __device__ __forceinline__ float atomicMin(float* address, float val) - { - #if __CUDA_ARCH__ >= 120 - int* address_as_i = (int*) address; - int old = *address_as_i, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_i, assumed, - __float_as_int(::fminf(val, __int_as_float(assumed)))); - } while (assumed != old); - return __int_as_float(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0f; - #endif - } - static __device__ __forceinline__ double atomicMin(double* address, double val) - { - #if __CUDA_ARCH__ >= 130 - unsigned long long int* address_as_ull = (unsigned long long int*) address; - unsigned long long int old = *address_as_ull, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_ull, assumed, - __double_as_longlong(::fmin(val, __longlong_as_double(assumed)))); - } while (assumed != old); - return __longlong_as_double(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0; - #endif - } - - static __device__ __forceinline__ int atomicMax(int* address, int val) - { - return ::atomicMax(address, val); - } - static __device__ __forceinline__ float atomicMax(float* address, float val) - { - #if __CUDA_ARCH__ >= 120 - int* address_as_i = (int*) address; - int old = *address_as_i, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_i, assumed, - __float_as_int(::fmaxf(val, __int_as_float(assumed)))); - } while (assumed != old); - return __int_as_float(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0f; - #endif - } - static __device__ __forceinline__ double atomicMax(double* address, double val) - { - #if __CUDA_ARCH__ >= 130 - unsigned long long int* address_as_ull = (unsigned long long int*) address; - unsigned long long int old = *address_as_ull, assumed; - do { - assumed = old; - old = ::atomicCAS(address_as_ull, assumed, - __double_as_longlong(::fmax(val, __longlong_as_double(assumed)))); - } while (assumed != old); - return __longlong_as_double(old); - #else - CV_UNUSED(address); - CV_UNUSED(val); - return 0.0; - #endif - } - }; - }; //struct Emulation -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif /* OPENCV_CUDA_EMULATION_HPP_ */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_EMULATION_HPP_ +#define OPENCV_CUDA_EMULATION_HPP_ + +#include "common.hpp" +#include "warp_reduce.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct Emulation + { + + static __device__ __forceinline__ int syncthreadsOr(int pred) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 200) + // just campilation stab + return 0; +#else + return __syncthreads_or(pred); +#endif + } + + template + static __forceinline__ __device__ int Ballot(int predicate) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ >= 200) + return __ballot(predicate); +#else + __shared__ volatile int cta_buffer[CTA_SIZE]; + + int tid = threadIdx.x; + cta_buffer[tid] = predicate ? (1 << (tid & 31)) : 0; + return warp_reduce(cta_buffer); +#endif + } + + struct smem + { + enum { TAG_MASK = (1U << ( (sizeof(unsigned int) << 3) - 5U)) - 1U }; + + template + static __device__ __forceinline__ T atomicInc(T* address, T val) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) + T count; + unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); + do + { + count = *address & TAG_MASK; + count = tag | (count + 1); + *address = count; + } while (*address != count); + + return (count & TAG_MASK) - 1; +#else + return ::atomicInc(address, val); +#endif + } + + template + static __device__ __forceinline__ T atomicAdd(T* address, T val) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) + T count; + unsigned int tag = threadIdx.x << ( (sizeof(unsigned int) << 3) - 5U); + do + { + count = *address & TAG_MASK; + count = tag | (count + val); + *address = count; + } while (*address != count); + + return (count & TAG_MASK) - val; +#else + return ::atomicAdd(address, val); +#endif + } + + template + static __device__ __forceinline__ T atomicMin(T* address, T val) + { +#if defined (__CUDA_ARCH__) && (__CUDA_ARCH__ < 120) + T count = ::min(*address, val); + do + { + *address = count; + } while (*address > count); + + return count; +#else + return ::atomicMin(address, val); +#endif + } + }; // struct cmem + + struct glob + { + static __device__ __forceinline__ int atomicAdd(int* address, int val) + { + return ::atomicAdd(address, val); + } + static __device__ __forceinline__ unsigned int atomicAdd(unsigned int* address, unsigned int val) + { + return ::atomicAdd(address, val); + } + static __device__ __forceinline__ float atomicAdd(float* address, float val) + { + #if __CUDA_ARCH__ >= 200 + return ::atomicAdd(address, val); + #else + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_i, assumed, + __float_as_int(val + __int_as_float(assumed))); + } while (assumed != old); + return __int_as_float(old); + #endif + } + static __device__ __forceinline__ double atomicAdd(double* address, double val) + { + #if __CUDA_ARCH__ >= 130 + unsigned long long int* address_as_ull = (unsigned long long int*) address; + unsigned long long int old = *address_as_ull, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_ull, assumed, + __double_as_longlong(val + __longlong_as_double(assumed))); + } while (assumed != old); + return __longlong_as_double(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0; + #endif + } + + static __device__ __forceinline__ int atomicMin(int* address, int val) + { + return ::atomicMin(address, val); + } + static __device__ __forceinline__ float atomicMin(float* address, float val) + { + #if __CUDA_ARCH__ >= 120 + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_i, assumed, + __float_as_int(::fminf(val, __int_as_float(assumed)))); + } while (assumed != old); + return __int_as_float(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0f; + #endif + } + static __device__ __forceinline__ double atomicMin(double* address, double val) + { + #if __CUDA_ARCH__ >= 130 + unsigned long long int* address_as_ull = (unsigned long long int*) address; + unsigned long long int old = *address_as_ull, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_ull, assumed, + __double_as_longlong(::fmin(val, __longlong_as_double(assumed)))); + } while (assumed != old); + return __longlong_as_double(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0; + #endif + } + + static __device__ __forceinline__ int atomicMax(int* address, int val) + { + return ::atomicMax(address, val); + } + static __device__ __forceinline__ float atomicMax(float* address, float val) + { + #if __CUDA_ARCH__ >= 120 + int* address_as_i = (int*) address; + int old = *address_as_i, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_i, assumed, + __float_as_int(::fmaxf(val, __int_as_float(assumed)))); + } while (assumed != old); + return __int_as_float(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0f; + #endif + } + static __device__ __forceinline__ double atomicMax(double* address, double val) + { + #if __CUDA_ARCH__ >= 130 + unsigned long long int* address_as_ull = (unsigned long long int*) address; + unsigned long long int old = *address_as_ull, assumed; + do { + assumed = old; + old = ::atomicCAS(address_as_ull, assumed, + __double_as_longlong(::fmax(val, __longlong_as_double(assumed)))); + } while (assumed != old); + return __longlong_as_double(old); + #else + CV_UNUSED(address); + CV_UNUSED(val); + return 0.0; + #endif + } + }; + }; //struct Emulation +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif /* OPENCV_CUDA_EMULATION_HPP_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp index bba354036a..bf3147edb9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/filters.hpp @@ -1,293 +1,293 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_FILTERS_HPP -#define OPENCV_CUDA_FILTERS_HPP - -#include "saturate_cast.hpp" -#include "vec_traits.hpp" -#include "vec_math.hpp" -#include "type_traits.hpp" -#include "nppdefs.h" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct PointFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) - : src(src_) - { - CV_UNUSED(fx); - CV_UNUSED(fy); - } - - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - return src(__float2int_rz(y), __float2int_rz(x)); - } - - Ptr2D src; - }; - - template struct LinearFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) - : src(src_) - { - CV_UNUSED(fx); - CV_UNUSED(fy); - } - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - typedef typename TypeVec::cn>::vec_type work_type; - - work_type out = VecTraits::all(0); - - const int x1 = __float2int_rd(x); - const int y1 = __float2int_rd(y); - if (x1 <= NPP_MIN_32S || x1 >= NPP_MAX_32S || y1 <= NPP_MIN_32S || y1 >= NPP_MAX_32S) - { - elem_type src_reg = src(y1, x1); - out = out + src_reg * 1.0f; - return saturate_cast(out); - } - const int x2 = x1 + 1; - const int y2 = y1 + 1; - - elem_type src_reg = src(y1, x1); - out = out + src_reg * ((x2 - x) * (y2 - y)); - - src_reg = src(y1, x2); - out = out + src_reg * ((x - x1) * (y2 - y)); - - src_reg = src(y2, x1); - out = out + src_reg * ((x2 - x) * (y - y1)); - - src_reg = src(y2, x2); - out = out + src_reg * ((x - x1) * (y - y1)); - - return saturate_cast(out); - } - - Ptr2D src; - }; - - template struct CubicFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - typedef typename TypeVec::cn>::vec_type work_type; - - explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) - : src(src_) - { - CV_UNUSED(fx); - CV_UNUSED(fy); - } - - static __device__ __forceinline__ float bicubicCoeff(float x_) - { - float x = fabsf(x_); - if (x <= 1.0f) - { - return x * x * (1.5f * x - 2.5f) + 1.0f; - } - else if (x < 2.0f) - { - return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f; - } - else - { - return 0.0f; - } - } - - __device__ elem_type operator ()(float y, float x) const - { - const float xmin = ::ceilf(x - 2.0f); - const float xmax = ::floorf(x + 2.0f); - - const float ymin = ::ceilf(y - 2.0f); - const float ymax = ::floorf(y + 2.0f); - - work_type sum = VecTraits::all(0); - float wsum = 0.0f; - - for (float cy = ymin; cy <= ymax; cy += 1.0f) - { - for (float cx = xmin; cx <= xmax; cx += 1.0f) - { - const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy); - sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx)); - wsum += w; - } - } - - work_type res = (!wsum)? VecTraits::all(0) : sum / wsum; - - return saturate_cast(res); - } - - Ptr2D src; - }; - // for integer scaling - template struct IntegerAreaFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) - : src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {} - - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - float fsx1 = x * scale_x; - float fsx2 = fsx1 + scale_x; - - int sx1 = __float2int_ru(fsx1); - int sx2 = __float2int_rd(fsx2); - - float fsy1 = y * scale_y; - float fsy2 = fsy1 + scale_y; - - int sy1 = __float2int_ru(fsy1); - int sy2 = __float2int_rd(fsy2); - - typedef typename TypeVec::cn>::vec_type work_type; - work_type out = VecTraits::all(0.f); - - for(int dy = sy1; dy < sy2; ++dy) - for(int dx = sx1; dx < sx2; ++dx) - { - out = out + src(dy, dx) * scale; - } - - return saturate_cast(out); - } - - Ptr2D src; - float scale_x, scale_y ,scale; - }; - - template struct AreaFilter - { - typedef typename Ptr2D::elem_type elem_type; - typedef float index_type; - - explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) - : src(src_), scale_x(scale_x_), scale_y(scale_y_){} - - __device__ __forceinline__ elem_type operator ()(float y, float x) const - { - float fsx1 = x * scale_x; - float fsx2 = fsx1 + scale_x; - - int sx1 = __float2int_ru(fsx1); - int sx2 = __float2int_rd(fsx2); - - float fsy1 = y * scale_y; - float fsy2 = fsy1 + scale_y; - - int sy1 = __float2int_ru(fsy1); - int sy2 = __float2int_rd(fsy2); - - float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1)); - - typedef typename TypeVec::cn>::vec_type work_type; - work_type out = VecTraits::all(0.f); - - for (int dy = sy1; dy < sy2; ++dy) - { - for (int dx = sx1; dx < sx2; ++dx) - out = out + src(dy, dx) * scale; - - if (sx1 > fsx1) - out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale); - - if (sx2 < fsx2) - out = out + src(dy, sx2) * ((fsx2 -sx2) * scale); - } - - if (sy1 > fsy1) - for (int dx = sx1; dx < sx2; ++dx) - out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale); - - if (sy2 < fsy2) - for (int dx = sx1; dx < sx2; ++dx) - out = out + src(sy2, dx) * ((fsy2 -sy2) * scale); - - if ((sy1 > fsy1) && (sx1 > fsx1)) - out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale); - - if ((sy1 > fsy1) && (sx2 < fsx2)) - out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale); - - if ((sy2 < fsy2) && (sx2 < fsx2)) - out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale); - - if ((sy2 < fsy2) && (sx1 > fsx1)) - out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale); - - return saturate_cast(out); - } - - Ptr2D src; - float scale_x, scale_y; - int width, haight; - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_FILTERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_FILTERS_HPP +#define OPENCV_CUDA_FILTERS_HPP + +#include "saturate_cast.hpp" +#include "vec_traits.hpp" +#include "vec_math.hpp" +#include "type_traits.hpp" +#include "nppdefs.h" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct PointFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ PointFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) + : src(src_) + { + CV_UNUSED(fx); + CV_UNUSED(fy); + } + + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + return src(__float2int_rz(y), __float2int_rz(x)); + } + + Ptr2D src; + }; + + template struct LinearFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ LinearFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) + : src(src_) + { + CV_UNUSED(fx); + CV_UNUSED(fy); + } + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + typedef typename TypeVec::cn>::vec_type work_type; + + work_type out = VecTraits::all(0); + + const int x1 = __float2int_rd(x); + const int y1 = __float2int_rd(y); + if (x1 <= NPP_MIN_32S || x1 >= NPP_MAX_32S || y1 <= NPP_MIN_32S || y1 >= NPP_MAX_32S) + { + elem_type src_reg = src(y1, x1); + out = out + src_reg * 1.0f; + return saturate_cast(out); + } + const int x2 = x1 + 1; + const int y2 = y1 + 1; + + elem_type src_reg = src(y1, x1); + out = out + src_reg * ((x2 - x) * (y2 - y)); + + src_reg = src(y1, x2); + out = out + src_reg * ((x - x1) * (y2 - y)); + + src_reg = src(y2, x1); + out = out + src_reg * ((x2 - x) * (y - y1)); + + src_reg = src(y2, x2); + out = out + src_reg * ((x - x1) * (y - y1)); + + return saturate_cast(out); + } + + Ptr2D src; + }; + + template struct CubicFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + typedef typename TypeVec::cn>::vec_type work_type; + + explicit __host__ __device__ __forceinline__ CubicFilter(const Ptr2D& src_, float fx = 0.f, float fy = 0.f) + : src(src_) + { + CV_UNUSED(fx); + CV_UNUSED(fy); + } + + static __device__ __forceinline__ float bicubicCoeff(float x_) + { + float x = fabsf(x_); + if (x <= 1.0f) + { + return x * x * (1.5f * x - 2.5f) + 1.0f; + } + else if (x < 2.0f) + { + return x * (x * (-0.5f * x + 2.5f) - 4.0f) + 2.0f; + } + else + { + return 0.0f; + } + } + + __device__ elem_type operator ()(float y, float x) const + { + const float xmin = ::ceilf(x - 2.0f); + const float xmax = ::floorf(x + 2.0f); + + const float ymin = ::ceilf(y - 2.0f); + const float ymax = ::floorf(y + 2.0f); + + work_type sum = VecTraits::all(0); + float wsum = 0.0f; + + for (float cy = ymin; cy <= ymax; cy += 1.0f) + { + for (float cx = xmin; cx <= xmax; cx += 1.0f) + { + const float w = bicubicCoeff(x - cx) * bicubicCoeff(y - cy); + sum = sum + w * src(__float2int_rd(cy), __float2int_rd(cx)); + wsum += w; + } + } + + work_type res = (!wsum)? VecTraits::all(0) : sum / wsum; + + return saturate_cast(res); + } + + Ptr2D src; + }; + // for integer scaling + template struct IntegerAreaFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ IntegerAreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) + : src(src_), scale_x(scale_x_), scale_y(scale_y_), scale(1.f / (scale_x * scale_y)) {} + + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + float fsx1 = x * scale_x; + float fsx2 = fsx1 + scale_x; + + int sx1 = __float2int_ru(fsx1); + int sx2 = __float2int_rd(fsx2); + + float fsy1 = y * scale_y; + float fsy2 = fsy1 + scale_y; + + int sy1 = __float2int_ru(fsy1); + int sy2 = __float2int_rd(fsy2); + + typedef typename TypeVec::cn>::vec_type work_type; + work_type out = VecTraits::all(0.f); + + for(int dy = sy1; dy < sy2; ++dy) + for(int dx = sx1; dx < sx2; ++dx) + { + out = out + src(dy, dx) * scale; + } + + return saturate_cast(out); + } + + Ptr2D src; + float scale_x, scale_y ,scale; + }; + + template struct AreaFilter + { + typedef typename Ptr2D::elem_type elem_type; + typedef float index_type; + + explicit __host__ __device__ __forceinline__ AreaFilter(const Ptr2D& src_, float scale_x_, float scale_y_) + : src(src_), scale_x(scale_x_), scale_y(scale_y_){} + + __device__ __forceinline__ elem_type operator ()(float y, float x) const + { + float fsx1 = x * scale_x; + float fsx2 = fsx1 + scale_x; + + int sx1 = __float2int_ru(fsx1); + int sx2 = __float2int_rd(fsx2); + + float fsy1 = y * scale_y; + float fsy2 = fsy1 + scale_y; + + int sy1 = __float2int_ru(fsy1); + int sy2 = __float2int_rd(fsy2); + + float scale = 1.f / (fminf(scale_x, src.width - fsx1) * fminf(scale_y, src.height - fsy1)); + + typedef typename TypeVec::cn>::vec_type work_type; + work_type out = VecTraits::all(0.f); + + for (int dy = sy1; dy < sy2; ++dy) + { + for (int dx = sx1; dx < sx2; ++dx) + out = out + src(dy, dx) * scale; + + if (sx1 > fsx1) + out = out + src(dy, (sx1 -1) ) * ((sx1 - fsx1) * scale); + + if (sx2 < fsx2) + out = out + src(dy, sx2) * ((fsx2 -sx2) * scale); + } + + if (sy1 > fsy1) + for (int dx = sx1; dx < sx2; ++dx) + out = out + src( (sy1 - 1) , dx) * ((sy1 -fsy1) * scale); + + if (sy2 < fsy2) + for (int dx = sx1; dx < sx2; ++dx) + out = out + src(sy2, dx) * ((fsy2 -sy2) * scale); + + if ((sy1 > fsy1) && (sx1 > fsx1)) + out = out + src( (sy1 - 1) , (sx1 - 1)) * ((sy1 -fsy1) * (sx1 -fsx1) * scale); + + if ((sy1 > fsy1) && (sx2 < fsx2)) + out = out + src( (sy1 - 1) , sx2) * ((sy1 -fsy1) * (fsx2 -sx2) * scale); + + if ((sy2 < fsy2) && (sx2 < fsx2)) + out = out + src(sy2, sx2) * ((fsy2 -sy2) * (fsx2 -sx2) * scale); + + if ((sy2 < fsy2) && (sx1 > fsx1)) + out = out + src(sy2, (sx1 - 1)) * ((fsy2 -sy2) * (sx1 -fsx1) * scale); + + return saturate_cast(out); + } + + Ptr2D src; + float scale_x, scale_y; + int width, haight; + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_FILTERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp index 6a01132d1e..f582080488 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/funcattrib.hpp @@ -1,79 +1,79 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP -#define OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP - -#include - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - void printFuncAttrib(Func& func) - { - - cudaFuncAttributes attrs; - cudaFuncGetAttributes(&attrs, func); - - printf("=== Function stats ===\n"); - printf("Name: \n"); - printf("sharedSizeBytes = %d\n", attrs.sharedSizeBytes); - printf("constSizeBytes = %d\n", attrs.constSizeBytes); - printf("localSizeBytes = %d\n", attrs.localSizeBytes); - printf("maxThreadsPerBlock = %d\n", attrs.maxThreadsPerBlock); - printf("numRegs = %d\n", attrs.numRegs); - printf("ptxVersion = %d\n", attrs.ptxVersion); - printf("binaryVersion = %d\n", attrs.binaryVersion); - printf("\n"); - fflush(stdout); - } -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif /* OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP +#define OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP + +#include + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + void printFuncAttrib(Func& func) + { + + cudaFuncAttributes attrs; + cudaFuncGetAttributes(&attrs, func); + + printf("=== Function stats ===\n"); + printf("Name: \n"); + printf("sharedSizeBytes = %d\n", attrs.sharedSizeBytes); + printf("constSizeBytes = %d\n", attrs.constSizeBytes); + printf("localSizeBytes = %d\n", attrs.localSizeBytes); + printf("maxThreadsPerBlock = %d\n", attrs.maxThreadsPerBlock); + printf("numRegs = %d\n", attrs.numRegs); + printf("ptxVersion = %d\n", attrs.ptxVersion); + printf("binaryVersion = %d\n", attrs.binaryVersion); + printf("\n"); + fflush(stdout); + } +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif /* OPENCV_CUDA_DEVICE_FUNCATTRIB_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp index 213f10c1bd..9f53d87527 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/functional.hpp @@ -1,805 +1,805 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_FUNCTIONAL_HPP -#define OPENCV_CUDA_FUNCTIONAL_HPP - -#include -#include "saturate_cast.hpp" -#include "vec_traits.hpp" -#include "type_traits.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - // Function Objects - template struct unary_function - { - typedef Argument argument_type; - typedef Result result_type; - }; - template struct binary_function - { - typedef Argument1 first_argument_type; - typedef Argument2 second_argument_type; - typedef Result result_type; - }; - - // Arithmetic Operations - template struct plus : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a + b; - } - __host__ __device__ __forceinline__ plus() {} - __host__ __device__ __forceinline__ plus(const plus&) {} - }; - - template struct minus : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a - b; - } - __host__ __device__ __forceinline__ minus() {} - __host__ __device__ __forceinline__ minus(const minus&) {} - }; - - template struct multiplies : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a * b; - } - __host__ __device__ __forceinline__ multiplies() {} - __host__ __device__ __forceinline__ multiplies(const multiplies&) {} - }; - - template struct divides : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a / b; - } - __host__ __device__ __forceinline__ divides() {} - __host__ __device__ __forceinline__ divides(const divides&) {} - }; - - template struct modulus : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a % b; - } - __host__ __device__ __forceinline__ modulus() {} - __host__ __device__ __forceinline__ modulus(const modulus&) {} - }; - - template struct negate : unary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a) const - { - return -a; - } - __host__ __device__ __forceinline__ negate() {} - __host__ __device__ __forceinline__ negate(const negate&) {} - }; - - // Comparison Operations - template struct equal_to : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a == b; - } - __host__ __device__ __forceinline__ equal_to() {} - __host__ __device__ __forceinline__ equal_to(const equal_to&) {} - }; - - template struct not_equal_to : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a != b; - } - __host__ __device__ __forceinline__ not_equal_to() {} - __host__ __device__ __forceinline__ not_equal_to(const not_equal_to&) {} - }; - - template struct greater : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a > b; - } - __host__ __device__ __forceinline__ greater() {} - __host__ __device__ __forceinline__ greater(const greater&) {} - }; - - template struct less : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a < b; - } - __host__ __device__ __forceinline__ less() {} - __host__ __device__ __forceinline__ less(const less&) {} - }; - - template struct greater_equal : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a >= b; - } - __host__ __device__ __forceinline__ greater_equal() {} - __host__ __device__ __forceinline__ greater_equal(const greater_equal&) {} - }; - - template struct less_equal : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a <= b; - } - __host__ __device__ __forceinline__ less_equal() {} - __host__ __device__ __forceinline__ less_equal(const less_equal&) {} - }; - - // Logical Operations - template struct logical_and : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a && b; - } - __host__ __device__ __forceinline__ logical_and() {} - __host__ __device__ __forceinline__ logical_and(const logical_and&) {} - }; - - template struct logical_or : binary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a || b; - } - __host__ __device__ __forceinline__ logical_or() {} - __host__ __device__ __forceinline__ logical_or(const logical_or&) {} - }; - - template struct logical_not : unary_function - { - __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a) const - { - return !a; - } - __host__ __device__ __forceinline__ logical_not() {} - __host__ __device__ __forceinline__ logical_not(const logical_not&) {} - }; - - // Bitwise Operations - template struct bit_and : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a & b; - } - __host__ __device__ __forceinline__ bit_and() {} - __host__ __device__ __forceinline__ bit_and(const bit_and&) {} - }; - - template struct bit_or : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a | b; - } - __host__ __device__ __forceinline__ bit_or() {} - __host__ __device__ __forceinline__ bit_or(const bit_or&) {} - }; - - template struct bit_xor : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, - typename TypeTraits::ParameterType b) const - { - return a ^ b; - } - __host__ __device__ __forceinline__ bit_xor() {} - __host__ __device__ __forceinline__ bit_xor(const bit_xor&) {} - }; - - template struct bit_not : unary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType v) const - { - return ~v; - } - __host__ __device__ __forceinline__ bit_not() {} - __host__ __device__ __forceinline__ bit_not(const bit_not&) {} - }; - - // Generalized Identity Operations - template struct identity : unary_function - { - __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType x) const - { - return x; - } - __host__ __device__ __forceinline__ identity() {} - __host__ __device__ __forceinline__ identity(const identity&) {} - }; - - template struct project1st : binary_function - { - __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return lhs; - } - __host__ __device__ __forceinline__ project1st() {} - __host__ __device__ __forceinline__ project1st(const project1st&) {} - }; - - template struct project2nd : binary_function - { - __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return rhs; - } - __host__ __device__ __forceinline__ project2nd() {} - __host__ __device__ __forceinline__ project2nd(const project2nd&) {} - }; - - // Min/Max Operations - -#define OPENCV_CUDA_IMPLEMENT_MINMAX(name, type, op) \ - template <> struct name : binary_function \ - { \ - __device__ __forceinline__ type operator()(type lhs, type rhs) const {return op(lhs, rhs);} \ - __host__ __device__ __forceinline__ name() {}\ - __host__ __device__ __forceinline__ name(const name&) {}\ - }; - - template struct maximum : binary_function - { - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return max(lhs, rhs); - } - __host__ __device__ __forceinline__ maximum() {} - __host__ __device__ __forceinline__ maximum(const maximum&) {} - }; - - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uchar, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, schar, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, char, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, ushort, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, short, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, int, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uint, ::max) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, float, ::fmax) - OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, double, ::fmax) - - template struct minimum : binary_function - { - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const - { - return min(lhs, rhs); - } - __host__ __device__ __forceinline__ minimum() {} - __host__ __device__ __forceinline__ minimum(const minimum&) {} - }; - - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uchar, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, schar, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, char, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, ushort, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, short, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, int, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uint, ::min) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, float, ::fmin) - OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, double, ::fmin) - -#undef OPENCV_CUDA_IMPLEMENT_MINMAX - - // Math functions - - template struct abs_func : unary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType x) const - { - return abs(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ unsigned char operator ()(unsigned char x) const - { - return x; - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ signed char operator ()(signed char x) const - { - return ::abs((int)x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ char operator ()(char x) const - { - return ::abs((int)x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ unsigned short operator ()(unsigned short x) const - { - return x; - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ short operator ()(short x) const - { - return ::abs((int)x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ unsigned int operator ()(unsigned int x) const - { - return x; - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ int operator ()(int x) const - { - return ::abs(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ float operator ()(float x) const - { - return ::fabsf(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - template <> struct abs_func : unary_function - { - __device__ __forceinline__ double operator ()(double x) const - { - return ::fabs(x); - } - - __host__ __device__ __forceinline__ abs_func() {} - __host__ __device__ __forceinline__ abs_func(const abs_func&) {} - }; - -#define OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(name, func) \ - template struct name ## _func : unary_function \ - { \ - __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v) const \ - { \ - return func ## f(v); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; \ - template <> struct name ## _func : unary_function \ - { \ - __device__ __forceinline__ double operator ()(double v) const \ - { \ - return func(v); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; - -#define OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(name, func) \ - template struct name ## _func : binary_function \ - { \ - __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v1, typename TypeTraits::ParameterType v2) const \ - { \ - return func ## f(v1, v2); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; \ - template <> struct name ## _func : binary_function \ - { \ - __device__ __forceinline__ double operator ()(double v1, double v2) const \ - { \ - return func(v1, v2); \ - } \ - __host__ __device__ __forceinline__ name ## _func() {} \ - __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ - }; - - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sqrt, ::sqrt) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp, ::exp) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp2, ::exp2) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp10, ::exp10) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log, ::log) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log2, ::log2) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log10, ::log10) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sin, ::sin) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cos, ::cos) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tan, ::tan) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asin, ::asin) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acos, ::acos) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atan, ::atan) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sinh, ::sinh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cosh, ::cosh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tanh, ::tanh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asinh, ::asinh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acosh, ::acosh) - OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atanh, ::atanh) - - OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(hypot, ::hypot) - OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(atan2, ::atan2) - OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(pow, ::pow) - - #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR - #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR_NO_DOUBLE - #undef OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR - - template struct hypot_sqr_func : binary_function - { - __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType src1, typename TypeTraits::ParameterType src2) const - { - return src1 * src1 + src2 * src2; - } - __host__ __device__ __forceinline__ hypot_sqr_func() {} - __host__ __device__ __forceinline__ hypot_sqr_func(const hypot_sqr_func&) {} - }; - - // Saturate Cast Functor - template struct saturate_cast_func : unary_function - { - __device__ __forceinline__ D operator ()(typename TypeTraits::ParameterType v) const - { - return saturate_cast(v); - } - __host__ __device__ __forceinline__ saturate_cast_func() {} - __host__ __device__ __forceinline__ saturate_cast_func(const saturate_cast_func&) {} - }; - - // Threshold Functors - template struct thresh_binary_func : unary_function - { - __host__ __device__ __forceinline__ thresh_binary_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src > thresh) * maxVal; - } - - __host__ __device__ __forceinline__ thresh_binary_func() {} - __host__ __device__ __forceinline__ thresh_binary_func(const thresh_binary_func& other) - : thresh(other.thresh), maxVal(other.maxVal) {} - - T thresh; - T maxVal; - }; - - template struct thresh_binary_inv_func : unary_function - { - __host__ __device__ __forceinline__ thresh_binary_inv_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src <= thresh) * maxVal; - } - - __host__ __device__ __forceinline__ thresh_binary_inv_func() {} - __host__ __device__ __forceinline__ thresh_binary_inv_func(const thresh_binary_inv_func& other) - : thresh(other.thresh), maxVal(other.maxVal) {} - - T thresh; - T maxVal; - }; - - template struct thresh_trunc_func : unary_function - { - explicit __host__ __device__ __forceinline__ thresh_trunc_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return minimum()(src, thresh); - } - - __host__ __device__ __forceinline__ thresh_trunc_func() {} - __host__ __device__ __forceinline__ thresh_trunc_func(const thresh_trunc_func& other) - : thresh(other.thresh) {} - - T thresh; - }; - - template struct thresh_to_zero_func : unary_function - { - explicit __host__ __device__ __forceinline__ thresh_to_zero_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src > thresh) * src; - } - - __host__ __device__ __forceinline__ thresh_to_zero_func() {} - __host__ __device__ __forceinline__ thresh_to_zero_func(const thresh_to_zero_func& other) - : thresh(other.thresh) {} - - T thresh; - }; - - template struct thresh_to_zero_inv_func : unary_function - { - explicit __host__ __device__ __forceinline__ thresh_to_zero_inv_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} - - __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const - { - return (src <= thresh) * src; - } - - __host__ __device__ __forceinline__ thresh_to_zero_inv_func() {} - __host__ __device__ __forceinline__ thresh_to_zero_inv_func(const thresh_to_zero_inv_func& other) - : thresh(other.thresh) {} - - T thresh; - }; - - // Function Object Adaptors - template struct unary_negate : unary_function - { - explicit __host__ __device__ __forceinline__ unary_negate(const Predicate& p) : pred(p) {} - - __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x) const - { - return !pred(x); - } - - __host__ __device__ __forceinline__ unary_negate() {} - __host__ __device__ __forceinline__ unary_negate(const unary_negate& other) : pred(other.pred) {} - - Predicate pred; - }; - - template __host__ __device__ __forceinline__ unary_negate not1(const Predicate& pred) - { - return unary_negate(pred); - } - - template struct binary_negate : binary_function - { - explicit __host__ __device__ __forceinline__ binary_negate(const Predicate& p) : pred(p) {} - - __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x, - typename TypeTraits::ParameterType y) const - { - return !pred(x,y); - } - - __host__ __device__ __forceinline__ binary_negate() {} - __host__ __device__ __forceinline__ binary_negate(const binary_negate& other) : pred(other.pred) {} - - Predicate pred; - }; - - template __host__ __device__ __forceinline__ binary_negate not2(const BinaryPredicate& pred) - { - return binary_negate(pred); - } - - template struct binder1st : unary_function - { - __host__ __device__ __forceinline__ binder1st(const Op& op_, const typename Op::first_argument_type& arg1_) : op(op_), arg1(arg1_) {} - - __device__ __forceinline__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const - { - return op(arg1, a); - } - - __host__ __device__ __forceinline__ binder1st() {} - __host__ __device__ __forceinline__ binder1st(const binder1st& other) : op(other.op), arg1(other.arg1) {} - - Op op; - typename Op::first_argument_type arg1; - }; - - template __host__ __device__ __forceinline__ binder1st bind1st(const Op& op, const T& x) - { - return binder1st(op, typename Op::first_argument_type(x)); - } - - template struct binder2nd : unary_function - { - __host__ __device__ __forceinline__ binder2nd(const Op& op_, const typename Op::second_argument_type& arg2_) : op(op_), arg2(arg2_) {} - - __forceinline__ __device__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const - { - return op(a, arg2); - } - - __host__ __device__ __forceinline__ binder2nd() {} - __host__ __device__ __forceinline__ binder2nd(const binder2nd& other) : op(other.op), arg2(other.arg2) {} - - Op op; - typename Op::second_argument_type arg2; - }; - - template __host__ __device__ __forceinline__ binder2nd bind2nd(const Op& op, const T& x) - { - return binder2nd(op, typename Op::second_argument_type(x)); - } - - // Functor Traits - template struct IsUnaryFunction - { - typedef char Yes; - struct No {Yes a[2];}; - - template static Yes check(unary_function); - static No check(...); - - static F makeF(); - - enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; - }; - - template struct IsBinaryFunction - { - typedef char Yes; - struct No {Yes a[2];}; - - template static Yes check(binary_function); - static No check(...); - - static F makeF(); - - enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; - }; - - namespace functional_detail - { - template struct UnOpShift { enum { shift = 1 }; }; - template struct UnOpShift { enum { shift = 4 }; }; - template struct UnOpShift { enum { shift = 2 }; }; - - template struct DefaultUnaryShift - { - enum { shift = UnOpShift::shift }; - }; - - template struct BinOpShift { enum { shift = 1 }; }; - template struct BinOpShift { enum { shift = 4 }; }; - template struct BinOpShift { enum { shift = 2 }; }; - - template struct DefaultBinaryShift - { - enum { shift = BinOpShift::shift }; - }; - - template ::value> struct ShiftDispatcher; - template struct ShiftDispatcher - { - enum { shift = DefaultUnaryShift::shift }; - }; - template struct ShiftDispatcher - { - enum { shift = DefaultBinaryShift::shift }; - }; - } - - template struct DefaultTransformShift - { - enum { shift = functional_detail::ShiftDispatcher::shift }; - }; - - template struct DefaultTransformFunctorTraits - { - enum { simple_block_dim_x = 16 }; - enum { simple_block_dim_y = 16 }; - - enum { smart_block_dim_x = 16 }; - enum { smart_block_dim_y = 16 }; - enum { smart_shift = DefaultTransformShift::shift }; - }; - - template struct TransformFunctorTraits : DefaultTransformFunctorTraits {}; - -#define OPENCV_CUDA_TRANSFORM_FUNCTOR_TRAITS(type) \ - template <> struct TransformFunctorTraits< type > : DefaultTransformFunctorTraits< type > -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_FUNCTIONAL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_FUNCTIONAL_HPP +#define OPENCV_CUDA_FUNCTIONAL_HPP + +#include +#include "saturate_cast.hpp" +#include "vec_traits.hpp" +#include "type_traits.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + // Function Objects + template struct unary_function + { + typedef Argument argument_type; + typedef Result result_type; + }; + template struct binary_function + { + typedef Argument1 first_argument_type; + typedef Argument2 second_argument_type; + typedef Result result_type; + }; + + // Arithmetic Operations + template struct plus : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a + b; + } + __host__ __device__ __forceinline__ plus() {} + __host__ __device__ __forceinline__ plus(const plus&) {} + }; + + template struct minus : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a - b; + } + __host__ __device__ __forceinline__ minus() {} + __host__ __device__ __forceinline__ minus(const minus&) {} + }; + + template struct multiplies : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a * b; + } + __host__ __device__ __forceinline__ multiplies() {} + __host__ __device__ __forceinline__ multiplies(const multiplies&) {} + }; + + template struct divides : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a / b; + } + __host__ __device__ __forceinline__ divides() {} + __host__ __device__ __forceinline__ divides(const divides&) {} + }; + + template struct modulus : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a % b; + } + __host__ __device__ __forceinline__ modulus() {} + __host__ __device__ __forceinline__ modulus(const modulus&) {} + }; + + template struct negate : unary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a) const + { + return -a; + } + __host__ __device__ __forceinline__ negate() {} + __host__ __device__ __forceinline__ negate(const negate&) {} + }; + + // Comparison Operations + template struct equal_to : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a == b; + } + __host__ __device__ __forceinline__ equal_to() {} + __host__ __device__ __forceinline__ equal_to(const equal_to&) {} + }; + + template struct not_equal_to : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a != b; + } + __host__ __device__ __forceinline__ not_equal_to() {} + __host__ __device__ __forceinline__ not_equal_to(const not_equal_to&) {} + }; + + template struct greater : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a > b; + } + __host__ __device__ __forceinline__ greater() {} + __host__ __device__ __forceinline__ greater(const greater&) {} + }; + + template struct less : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a < b; + } + __host__ __device__ __forceinline__ less() {} + __host__ __device__ __forceinline__ less(const less&) {} + }; + + template struct greater_equal : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a >= b; + } + __host__ __device__ __forceinline__ greater_equal() {} + __host__ __device__ __forceinline__ greater_equal(const greater_equal&) {} + }; + + template struct less_equal : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a <= b; + } + __host__ __device__ __forceinline__ less_equal() {} + __host__ __device__ __forceinline__ less_equal(const less_equal&) {} + }; + + // Logical Operations + template struct logical_and : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a && b; + } + __host__ __device__ __forceinline__ logical_and() {} + __host__ __device__ __forceinline__ logical_and(const logical_and&) {} + }; + + template struct logical_or : binary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a || b; + } + __host__ __device__ __forceinline__ logical_or() {} + __host__ __device__ __forceinline__ logical_or(const logical_or&) {} + }; + + template struct logical_not : unary_function + { + __device__ __forceinline__ bool operator ()(typename TypeTraits::ParameterType a) const + { + return !a; + } + __host__ __device__ __forceinline__ logical_not() {} + __host__ __device__ __forceinline__ logical_not(const logical_not&) {} + }; + + // Bitwise Operations + template struct bit_and : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a & b; + } + __host__ __device__ __forceinline__ bit_and() {} + __host__ __device__ __forceinline__ bit_and(const bit_and&) {} + }; + + template struct bit_or : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a | b; + } + __host__ __device__ __forceinline__ bit_or() {} + __host__ __device__ __forceinline__ bit_or(const bit_or&) {} + }; + + template struct bit_xor : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType a, + typename TypeTraits::ParameterType b) const + { + return a ^ b; + } + __host__ __device__ __forceinline__ bit_xor() {} + __host__ __device__ __forceinline__ bit_xor(const bit_xor&) {} + }; + + template struct bit_not : unary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType v) const + { + return ~v; + } + __host__ __device__ __forceinline__ bit_not() {} + __host__ __device__ __forceinline__ bit_not(const bit_not&) {} + }; + + // Generalized Identity Operations + template struct identity : unary_function + { + __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType x) const + { + return x; + } + __host__ __device__ __forceinline__ identity() {} + __host__ __device__ __forceinline__ identity(const identity&) {} + }; + + template struct project1st : binary_function + { + __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return lhs; + } + __host__ __device__ __forceinline__ project1st() {} + __host__ __device__ __forceinline__ project1st(const project1st&) {} + }; + + template struct project2nd : binary_function + { + __device__ __forceinline__ typename TypeTraits::ParameterType operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return rhs; + } + __host__ __device__ __forceinline__ project2nd() {} + __host__ __device__ __forceinline__ project2nd(const project2nd&) {} + }; + + // Min/Max Operations + +#define OPENCV_CUDA_IMPLEMENT_MINMAX(name, type, op) \ + template <> struct name : binary_function \ + { \ + __device__ __forceinline__ type operator()(type lhs, type rhs) const {return op(lhs, rhs);} \ + __host__ __device__ __forceinline__ name() {}\ + __host__ __device__ __forceinline__ name(const name&) {}\ + }; + + template struct maximum : binary_function + { + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return max(lhs, rhs); + } + __host__ __device__ __forceinline__ maximum() {} + __host__ __device__ __forceinline__ maximum(const maximum&) {} + }; + + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uchar, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, schar, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, char, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, ushort, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, short, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, int, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, uint, ::max) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, float, ::fmax) + OPENCV_CUDA_IMPLEMENT_MINMAX(maximum, double, ::fmax) + + template struct minimum : binary_function + { + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType lhs, typename TypeTraits::ParameterType rhs) const + { + return min(lhs, rhs); + } + __host__ __device__ __forceinline__ minimum() {} + __host__ __device__ __forceinline__ minimum(const minimum&) {} + }; + + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uchar, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, schar, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, char, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, ushort, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, short, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, int, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, uint, ::min) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, float, ::fmin) + OPENCV_CUDA_IMPLEMENT_MINMAX(minimum, double, ::fmin) + +#undef OPENCV_CUDA_IMPLEMENT_MINMAX + + // Math functions + + template struct abs_func : unary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType x) const + { + return abs(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ unsigned char operator ()(unsigned char x) const + { + return x; + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ signed char operator ()(signed char x) const + { + return ::abs((int)x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ char operator ()(char x) const + { + return ::abs((int)x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ unsigned short operator ()(unsigned short x) const + { + return x; + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ short operator ()(short x) const + { + return ::abs((int)x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ unsigned int operator ()(unsigned int x) const + { + return x; + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ int operator ()(int x) const + { + return ::abs(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ float operator ()(float x) const + { + return ::fabsf(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + template <> struct abs_func : unary_function + { + __device__ __forceinline__ double operator ()(double x) const + { + return ::fabs(x); + } + + __host__ __device__ __forceinline__ abs_func() {} + __host__ __device__ __forceinline__ abs_func(const abs_func&) {} + }; + +#define OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(name, func) \ + template struct name ## _func : unary_function \ + { \ + __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v) const \ + { \ + return func ## f(v); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; \ + template <> struct name ## _func : unary_function \ + { \ + __device__ __forceinline__ double operator ()(double v) const \ + { \ + return func(v); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; + +#define OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(name, func) \ + template struct name ## _func : binary_function \ + { \ + __device__ __forceinline__ float operator ()(typename TypeTraits::ParameterType v1, typename TypeTraits::ParameterType v2) const \ + { \ + return func ## f(v1, v2); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; \ + template <> struct name ## _func : binary_function \ + { \ + __device__ __forceinline__ double operator ()(double v1, double v2) const \ + { \ + return func(v1, v2); \ + } \ + __host__ __device__ __forceinline__ name ## _func() {} \ + __host__ __device__ __forceinline__ name ## _func(const name ## _func&) {} \ + }; + + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sqrt, ::sqrt) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp, ::exp) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp2, ::exp2) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(exp10, ::exp10) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log, ::log) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log2, ::log2) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(log10, ::log10) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sin, ::sin) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cos, ::cos) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tan, ::tan) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asin, ::asin) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acos, ::acos) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atan, ::atan) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(sinh, ::sinh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(cosh, ::cosh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(tanh, ::tanh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(asinh, ::asinh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(acosh, ::acosh) + OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR(atanh, ::atanh) + + OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(hypot, ::hypot) + OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(atan2, ::atan2) + OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR(pow, ::pow) + + #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR + #undef OPENCV_CUDA_IMPLEMENT_UN_FUNCTOR_NO_DOUBLE + #undef OPENCV_CUDA_IMPLEMENT_BIN_FUNCTOR + + template struct hypot_sqr_func : binary_function + { + __device__ __forceinline__ T operator ()(typename TypeTraits::ParameterType src1, typename TypeTraits::ParameterType src2) const + { + return src1 * src1 + src2 * src2; + } + __host__ __device__ __forceinline__ hypot_sqr_func() {} + __host__ __device__ __forceinline__ hypot_sqr_func(const hypot_sqr_func&) {} + }; + + // Saturate Cast Functor + template struct saturate_cast_func : unary_function + { + __device__ __forceinline__ D operator ()(typename TypeTraits::ParameterType v) const + { + return saturate_cast(v); + } + __host__ __device__ __forceinline__ saturate_cast_func() {} + __host__ __device__ __forceinline__ saturate_cast_func(const saturate_cast_func&) {} + }; + + // Threshold Functors + template struct thresh_binary_func : unary_function + { + __host__ __device__ __forceinline__ thresh_binary_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src > thresh) * maxVal; + } + + __host__ __device__ __forceinline__ thresh_binary_func() {} + __host__ __device__ __forceinline__ thresh_binary_func(const thresh_binary_func& other) + : thresh(other.thresh), maxVal(other.maxVal) {} + + T thresh; + T maxVal; + }; + + template struct thresh_binary_inv_func : unary_function + { + __host__ __device__ __forceinline__ thresh_binary_inv_func(T thresh_, T maxVal_) : thresh(thresh_), maxVal(maxVal_) {} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src <= thresh) * maxVal; + } + + __host__ __device__ __forceinline__ thresh_binary_inv_func() {} + __host__ __device__ __forceinline__ thresh_binary_inv_func(const thresh_binary_inv_func& other) + : thresh(other.thresh), maxVal(other.maxVal) {} + + T thresh; + T maxVal; + }; + + template struct thresh_trunc_func : unary_function + { + explicit __host__ __device__ __forceinline__ thresh_trunc_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return minimum()(src, thresh); + } + + __host__ __device__ __forceinline__ thresh_trunc_func() {} + __host__ __device__ __forceinline__ thresh_trunc_func(const thresh_trunc_func& other) + : thresh(other.thresh) {} + + T thresh; + }; + + template struct thresh_to_zero_func : unary_function + { + explicit __host__ __device__ __forceinline__ thresh_to_zero_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src > thresh) * src; + } + + __host__ __device__ __forceinline__ thresh_to_zero_func() {} + __host__ __device__ __forceinline__ thresh_to_zero_func(const thresh_to_zero_func& other) + : thresh(other.thresh) {} + + T thresh; + }; + + template struct thresh_to_zero_inv_func : unary_function + { + explicit __host__ __device__ __forceinline__ thresh_to_zero_inv_func(T thresh_, T maxVal_ = 0) : thresh(thresh_) {CV_UNUSED(maxVal_);} + + __device__ __forceinline__ T operator()(typename TypeTraits::ParameterType src) const + { + return (src <= thresh) * src; + } + + __host__ __device__ __forceinline__ thresh_to_zero_inv_func() {} + __host__ __device__ __forceinline__ thresh_to_zero_inv_func(const thresh_to_zero_inv_func& other) + : thresh(other.thresh) {} + + T thresh; + }; + + // Function Object Adaptors + template struct unary_negate : unary_function + { + explicit __host__ __device__ __forceinline__ unary_negate(const Predicate& p) : pred(p) {} + + __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x) const + { + return !pred(x); + } + + __host__ __device__ __forceinline__ unary_negate() {} + __host__ __device__ __forceinline__ unary_negate(const unary_negate& other) : pred(other.pred) {} + + Predicate pred; + }; + + template __host__ __device__ __forceinline__ unary_negate not1(const Predicate& pred) + { + return unary_negate(pred); + } + + template struct binary_negate : binary_function + { + explicit __host__ __device__ __forceinline__ binary_negate(const Predicate& p) : pred(p) {} + + __device__ __forceinline__ bool operator()(typename TypeTraits::ParameterType x, + typename TypeTraits::ParameterType y) const + { + return !pred(x,y); + } + + __host__ __device__ __forceinline__ binary_negate() {} + __host__ __device__ __forceinline__ binary_negate(const binary_negate& other) : pred(other.pred) {} + + Predicate pred; + }; + + template __host__ __device__ __forceinline__ binary_negate not2(const BinaryPredicate& pred) + { + return binary_negate(pred); + } + + template struct binder1st : unary_function + { + __host__ __device__ __forceinline__ binder1st(const Op& op_, const typename Op::first_argument_type& arg1_) : op(op_), arg1(arg1_) {} + + __device__ __forceinline__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const + { + return op(arg1, a); + } + + __host__ __device__ __forceinline__ binder1st() {} + __host__ __device__ __forceinline__ binder1st(const binder1st& other) : op(other.op), arg1(other.arg1) {} + + Op op; + typename Op::first_argument_type arg1; + }; + + template __host__ __device__ __forceinline__ binder1st bind1st(const Op& op, const T& x) + { + return binder1st(op, typename Op::first_argument_type(x)); + } + + template struct binder2nd : unary_function + { + __host__ __device__ __forceinline__ binder2nd(const Op& op_, const typename Op::second_argument_type& arg2_) : op(op_), arg2(arg2_) {} + + __forceinline__ __device__ typename Op::result_type operator ()(typename TypeTraits::ParameterType a) const + { + return op(a, arg2); + } + + __host__ __device__ __forceinline__ binder2nd() {} + __host__ __device__ __forceinline__ binder2nd(const binder2nd& other) : op(other.op), arg2(other.arg2) {} + + Op op; + typename Op::second_argument_type arg2; + }; + + template __host__ __device__ __forceinline__ binder2nd bind2nd(const Op& op, const T& x) + { + return binder2nd(op, typename Op::second_argument_type(x)); + } + + // Functor Traits + template struct IsUnaryFunction + { + typedef char Yes; + struct No {Yes a[2];}; + + template static Yes check(unary_function); + static No check(...); + + static F makeF(); + + enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; + }; + + template struct IsBinaryFunction + { + typedef char Yes; + struct No {Yes a[2];}; + + template static Yes check(binary_function); + static No check(...); + + static F makeF(); + + enum { value = (sizeof(check(makeF())) == sizeof(Yes)) }; + }; + + namespace functional_detail + { + template struct UnOpShift { enum { shift = 1 }; }; + template struct UnOpShift { enum { shift = 4 }; }; + template struct UnOpShift { enum { shift = 2 }; }; + + template struct DefaultUnaryShift + { + enum { shift = UnOpShift::shift }; + }; + + template struct BinOpShift { enum { shift = 1 }; }; + template struct BinOpShift { enum { shift = 4 }; }; + template struct BinOpShift { enum { shift = 2 }; }; + + template struct DefaultBinaryShift + { + enum { shift = BinOpShift::shift }; + }; + + template ::value> struct ShiftDispatcher; + template struct ShiftDispatcher + { + enum { shift = DefaultUnaryShift::shift }; + }; + template struct ShiftDispatcher + { + enum { shift = DefaultBinaryShift::shift }; + }; + } + + template struct DefaultTransformShift + { + enum { shift = functional_detail::ShiftDispatcher::shift }; + }; + + template struct DefaultTransformFunctorTraits + { + enum { simple_block_dim_x = 16 }; + enum { simple_block_dim_y = 16 }; + + enum { smart_block_dim_x = 16 }; + enum { smart_block_dim_y = 16 }; + enum { smart_shift = DefaultTransformShift::shift }; + }; + + template struct TransformFunctorTraits : DefaultTransformFunctorTraits {}; + +#define OPENCV_CUDA_TRANSFORM_FUNCTOR_TRAITS(type) \ + template <> struct TransformFunctorTraits< type > : DefaultTransformFunctorTraits< type > +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_FUNCTIONAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp index 5f830b3365..7e15ed629a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/limits.hpp @@ -1,128 +1,128 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_LIMITS_HPP -#define OPENCV_CUDA_LIMITS_HPP - -#include -#include -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ -template struct numeric_limits; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static bool min() { return false; } - __device__ __forceinline__ static bool max() { return true; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static signed char min() { return SCHAR_MIN; } - __device__ __forceinline__ static signed char max() { return SCHAR_MAX; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static unsigned char min() { return 0; } - __device__ __forceinline__ static unsigned char max() { return UCHAR_MAX; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static short min() { return SHRT_MIN; } - __device__ __forceinline__ static short max() { return SHRT_MAX; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static unsigned short min() { return 0; } - __device__ __forceinline__ static unsigned short max() { return USHRT_MAX; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static int min() { return INT_MIN; } - __device__ __forceinline__ static int max() { return INT_MAX; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static unsigned int min() { return 0; } - __device__ __forceinline__ static unsigned int max() { return UINT_MAX; } - static const bool is_signed = false; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static float min() { return FLT_MIN; } - __device__ __forceinline__ static float max() { return FLT_MAX; } - __device__ __forceinline__ static float epsilon() { return FLT_EPSILON; } - static const bool is_signed = true; -}; - -template <> struct numeric_limits -{ - __device__ __forceinline__ static double min() { return DBL_MIN; } - __device__ __forceinline__ static double max() { return DBL_MAX; } - __device__ __forceinline__ static double epsilon() { return DBL_EPSILON; } - static const bool is_signed = true; -}; -}}} // namespace cv { namespace cuda { namespace cudev { - -//! @endcond - -#endif // OPENCV_CUDA_LIMITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_LIMITS_HPP +#define OPENCV_CUDA_LIMITS_HPP + +#include +#include +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ +template struct numeric_limits; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static bool min() { return false; } + __device__ __forceinline__ static bool max() { return true; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static signed char min() { return SCHAR_MIN; } + __device__ __forceinline__ static signed char max() { return SCHAR_MAX; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static unsigned char min() { return 0; } + __device__ __forceinline__ static unsigned char max() { return UCHAR_MAX; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static short min() { return SHRT_MIN; } + __device__ __forceinline__ static short max() { return SHRT_MAX; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static unsigned short min() { return 0; } + __device__ __forceinline__ static unsigned short max() { return USHRT_MAX; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static int min() { return INT_MIN; } + __device__ __forceinline__ static int max() { return INT_MAX; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static unsigned int min() { return 0; } + __device__ __forceinline__ static unsigned int max() { return UINT_MAX; } + static const bool is_signed = false; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static float min() { return FLT_MIN; } + __device__ __forceinline__ static float max() { return FLT_MAX; } + __device__ __forceinline__ static float epsilon() { return FLT_EPSILON; } + static const bool is_signed = true; +}; + +template <> struct numeric_limits +{ + __device__ __forceinline__ static double min() { return DBL_MIN; } + __device__ __forceinline__ static double max() { return DBL_MAX; } + __device__ __forceinline__ static double epsilon() { return DBL_EPSILON; } + static const bool is_signed = true; +}; +}}} // namespace cv { namespace cuda { namespace cudev { + +//! @endcond + +#endif // OPENCV_CUDA_LIMITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp index f422b0d58d..fb74de95a8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/reduce.hpp @@ -1,230 +1,230 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_REDUCE_HPP -#define OPENCV_CUDA_REDUCE_HPP - -#ifndef THRUST_DEBUG // eliminate -Wundef warning -#define THRUST_DEBUG 0 -#endif - -#include -#include "detail/reduce.hpp" -#include "detail/reduce_key_val.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - __device__ __forceinline__ void reduce(volatile T* smem, T& val, unsigned int tid, const Op& op) - { - reduce_detail::Dispatcher::reductor::template reduce(smem, val, tid, op); - } - template - __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, volatile V* svals, V& val, unsigned int tid, const Cmp& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce(skeys, key, svals, val, tid, cmp); - } -#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 - template - __device__ __forceinline__ void reduce(const thrust::tuple& smem, - const thrust::tuple& val, - unsigned int tid, - const thrust::tuple& op) - { - reduce_detail::Dispatcher::reductor::template reduce< - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple&>(smem, val, tid, op); - } - - template - __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, - const thrust::tuple& svals, - const thrust::tuple& val, - unsigned int tid, const Cmp& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce&, - const thrust::tuple&, - const Cmp&>(skeys, key, svals, val, tid, cmp); - } - - template - __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, - const thrust::tuple& key, - const thrust::tuple& svals, - const thrust::tuple& val, - unsigned int tid, - const thrust::tuple& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce< - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple&, - const thrust::tuple& - >(skeys, key, svals, val, tid, cmp); - } -#else - template - __device__ __forceinline__ void reduce(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, const thrust::tuple& op) - { - reduce_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&>(smem, val, tid, op); - } - - template - __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const Cmp& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const Cmp&>(skeys, key, svals, val, tid, cmp); - } - - template - __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, const thrust::tuple& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const thrust::tuple& cmp) - { - reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&>(skeys, key, svals, val, tid, cmp); - } -#endif - - // smem_tuple - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0) - { - return thrust::make_tuple((volatile T0*) t0); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8); - } - - template - __device__ __forceinline__ - thrust::tuple - smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8, T9* t9) - { - return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8, (volatile T9*) t9); - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_REDUCE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_REDUCE_HPP +#define OPENCV_CUDA_REDUCE_HPP + +#ifndef THRUST_DEBUG // eliminate -Wundef warning +#define THRUST_DEBUG 0 +#endif + +#include +#include "detail/reduce.hpp" +#include "detail/reduce_key_val.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + __device__ __forceinline__ void reduce(volatile T* smem, T& val, unsigned int tid, const Op& op) + { + reduce_detail::Dispatcher::reductor::template reduce(smem, val, tid, op); + } + template + __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, volatile V* svals, V& val, unsigned int tid, const Cmp& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce(skeys, key, svals, val, tid, cmp); + } +#if (CUDART_VERSION < 12040) // details: https://github.com/opencv/opencv_contrib/issues/3690 + template + __device__ __forceinline__ void reduce(const thrust::tuple& smem, + const thrust::tuple& val, + unsigned int tid, + const thrust::tuple& op) + { + reduce_detail::Dispatcher::reductor::template reduce< + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple&>(smem, val, tid, op); + } + + template + __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, + const thrust::tuple& svals, + const thrust::tuple& val, + unsigned int tid, const Cmp& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce&, + const thrust::tuple&, + const Cmp&>(skeys, key, svals, val, tid, cmp); + } + + template + __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, + const thrust::tuple& key, + const thrust::tuple& svals, + const thrust::tuple& val, + unsigned int tid, + const thrust::tuple& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce< + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple&, + const thrust::tuple& + >(skeys, key, svals, val, tid, cmp); + } +#else + template + __device__ __forceinline__ void reduce(const thrust::tuple& smem, const thrust::tuple& val, unsigned int tid, const thrust::tuple& op) + { + reduce_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&>(smem, val, tid, op); + } + + template + __device__ __forceinline__ void reduceKeyVal(volatile K* skeys, K& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const Cmp& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const Cmp&>(skeys, key, svals, val, tid, cmp); + } + + template + __device__ __forceinline__ void reduceKeyVal(const thrust::tuple& skeys, const thrust::tuple& key, const thrust::tuple& svals, const thrust::tuple& val, unsigned int tid, const thrust::tuple& cmp) + { + reduce_key_val_detail::Dispatcher::reductor::template reduce&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&, const thrust::tuple&>(skeys, key, svals, val, tid, cmp); + } +#endif + + // smem_tuple + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0) + { + return thrust::make_tuple((volatile T0*) t0); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8); + } + + template + __device__ __forceinline__ + thrust::tuple + smem_tuple(T0* t0, T1* t1, T2* t2, T3* t3, T4* t4, T5* t5, T6* t6, T7* t7, T8* t8, T9* t9) + { + return thrust::make_tuple((volatile T0*) t0, (volatile T1*) t1, (volatile T2*) t2, (volatile T3*) t3, (volatile T4*) t4, (volatile T5*) t5, (volatile T6*) t6, (volatile T7*) t7, (volatile T8*) t8, (volatile T9*) t9); + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_REDUCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp index 865d883683..c3a3d1cb83 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/saturate_cast.hpp @@ -1,292 +1,292 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_SATURATE_CAST_HPP -#define OPENCV_CUDA_SATURATE_CAST_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template __device__ __forceinline__ _Tp saturate_cast(uchar v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(schar v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(ushort v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(short v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(uint v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(int v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(float v) { return _Tp(v); } - template __device__ __forceinline__ _Tp saturate_cast(double v) { return _Tp(v); } - - template<> __device__ __forceinline__ uchar saturate_cast(schar v) - { - uint res = 0; - int vi = v; - asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(short v) - { - uint res = 0; - asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(ushort v) - { - uint res = 0; - asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(int v) - { - uint res = 0; - asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(uint v) - { - uint res = 0; - asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(float v) - { - uint res = 0; - asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ uchar saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - uint res = 0; - asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ schar saturate_cast(uchar v) - { - uint res = 0; - uint vi = v; - asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(short v) - { - uint res = 0; - asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(ushort v) - { - uint res = 0; - asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(int v) - { - uint res = 0; - asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(uint v) - { - uint res = 0; - asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(float v) - { - uint res = 0; - asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ schar saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - uint res = 0; - asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ ushort saturate_cast(schar v) - { - ushort res = 0; - int vi = v; - asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(short v) - { - ushort res = 0; - asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(int v) - { - ushort res = 0; - asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(uint v) - { - ushort res = 0; - asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(float v) - { - ushort res = 0; - asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ ushort saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - ushort res = 0; - asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ short saturate_cast(ushort v) - { - short res = 0; - asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(int v) - { - short res = 0; - asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(uint v) - { - short res = 0; - asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(float v) - { - short res = 0; - asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v)); - return res; - } - template<> __device__ __forceinline__ short saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - short res = 0; - asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v)); - return res; - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ int saturate_cast(uint v) - { - int res = 0; - asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ int saturate_cast(float v) - { - return __float2int_rn(v); - } - template<> __device__ __forceinline__ int saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - return __double2int_rn(v); - #else - return saturate_cast((float)v); - #endif - } - - template<> __device__ __forceinline__ uint saturate_cast(schar v) - { - uint res = 0; - int vi = v; - asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi)); - return res; - } - template<> __device__ __forceinline__ uint saturate_cast(short v) - { - uint res = 0; - asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v)); - return res; - } - template<> __device__ __forceinline__ uint saturate_cast(int v) - { - uint res = 0; - asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v)); - return res; - } - template<> __device__ __forceinline__ uint saturate_cast(float v) - { - return __float2uint_rn(v); - } - template<> __device__ __forceinline__ uint saturate_cast(double v) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 - return __double2uint_rn(v); - #else - return saturate_cast((float)v); - #endif - } -}}} - -//! @endcond - -#endif /* OPENCV_CUDA_SATURATE_CAST_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_SATURATE_CAST_HPP +#define OPENCV_CUDA_SATURATE_CAST_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template __device__ __forceinline__ _Tp saturate_cast(uchar v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(schar v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(ushort v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(short v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(uint v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(int v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(float v) { return _Tp(v); } + template __device__ __forceinline__ _Tp saturate_cast(double v) { return _Tp(v); } + + template<> __device__ __forceinline__ uchar saturate_cast(schar v) + { + uint res = 0; + int vi = v; + asm("cvt.sat.u8.s8 %0, %1;" : "=r"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(short v) + { + uint res = 0; + asm("cvt.sat.u8.s16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(ushort v) + { + uint res = 0; + asm("cvt.sat.u8.u16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(int v) + { + uint res = 0; + asm("cvt.sat.u8.s32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(uint v) + { + uint res = 0; + asm("cvt.sat.u8.u32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(float v) + { + uint res = 0; + asm("cvt.rni.sat.u8.f32 %0, %1;" : "=r"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ uchar saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + uint res = 0; + asm("cvt.rni.sat.u8.f64 %0, %1;" : "=r"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ schar saturate_cast(uchar v) + { + uint res = 0; + uint vi = v; + asm("cvt.sat.s8.u8 %0, %1;" : "=r"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(short v) + { + uint res = 0; + asm("cvt.sat.s8.s16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(ushort v) + { + uint res = 0; + asm("cvt.sat.s8.u16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(int v) + { + uint res = 0; + asm("cvt.sat.s8.s32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(uint v) + { + uint res = 0; + asm("cvt.sat.s8.u32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(float v) + { + uint res = 0; + asm("cvt.rni.sat.s8.f32 %0, %1;" : "=r"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ schar saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + uint res = 0; + asm("cvt.rni.sat.s8.f64 %0, %1;" : "=r"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ ushort saturate_cast(schar v) + { + ushort res = 0; + int vi = v; + asm("cvt.sat.u16.s8 %0, %1;" : "=h"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(short v) + { + ushort res = 0; + asm("cvt.sat.u16.s16 %0, %1;" : "=h"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(int v) + { + ushort res = 0; + asm("cvt.sat.u16.s32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(uint v) + { + ushort res = 0; + asm("cvt.sat.u16.u32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(float v) + { + ushort res = 0; + asm("cvt.rni.sat.u16.f32 %0, %1;" : "=h"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ ushort saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + ushort res = 0; + asm("cvt.rni.sat.u16.f64 %0, %1;" : "=h"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ short saturate_cast(ushort v) + { + short res = 0; + asm("cvt.sat.s16.u16 %0, %1;" : "=h"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(int v) + { + short res = 0; + asm("cvt.sat.s16.s32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(uint v) + { + short res = 0; + asm("cvt.sat.s16.u32 %0, %1;" : "=h"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(float v) + { + short res = 0; + asm("cvt.rni.sat.s16.f32 %0, %1;" : "=h"(res) : "f"(v)); + return res; + } + template<> __device__ __forceinline__ short saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + short res = 0; + asm("cvt.rni.sat.s16.f64 %0, %1;" : "=h"(res) : "d"(v)); + return res; + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ int saturate_cast(uint v) + { + int res = 0; + asm("cvt.sat.s32.u32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ int saturate_cast(float v) + { + return __float2int_rn(v); + } + template<> __device__ __forceinline__ int saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + return __double2int_rn(v); + #else + return saturate_cast((float)v); + #endif + } + + template<> __device__ __forceinline__ uint saturate_cast(schar v) + { + uint res = 0; + int vi = v; + asm("cvt.sat.u32.s8 %0, %1;" : "=r"(res) : "r"(vi)); + return res; + } + template<> __device__ __forceinline__ uint saturate_cast(short v) + { + uint res = 0; + asm("cvt.sat.u32.s16 %0, %1;" : "=r"(res) : "h"(v)); + return res; + } + template<> __device__ __forceinline__ uint saturate_cast(int v) + { + uint res = 0; + asm("cvt.sat.u32.s32 %0, %1;" : "=r"(res) : "r"(v)); + return res; + } + template<> __device__ __forceinline__ uint saturate_cast(float v) + { + return __float2uint_rn(v); + } + template<> __device__ __forceinline__ uint saturate_cast(double v) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 130 + return __double2uint_rn(v); + #else + return saturate_cast((float)v); + #endif + } +}}} + +//! @endcond + +#endif /* OPENCV_CUDA_SATURATE_CAST_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp index e7b0e2ae89..e128fb0962 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/scan.hpp @@ -1,258 +1,258 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_SCAN_HPP -#define OPENCV_CUDA_SCAN_HPP - -#include "opencv2/core/cuda/common.hpp" -#include "opencv2/core/cuda/utility.hpp" -#include "opencv2/core/cuda/warp.hpp" -#include "opencv2/core/cuda/warp_shuffle.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - enum ScanKind { EXCLUSIVE = 0, INCLUSIVE = 1 }; - - template struct WarpScan - { - __device__ __forceinline__ WarpScan() {} - __device__ __forceinline__ WarpScan(const WarpScan& other) { CV_UNUSED(other); } - - __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) - { - const unsigned int lane = idx & 31; - F op; - - if ( lane >= 1) ptr [idx ] = op(ptr [idx - 1], ptr [idx]); - if ( lane >= 2) ptr [idx ] = op(ptr [idx - 2], ptr [idx]); - if ( lane >= 4) ptr [idx ] = op(ptr [idx - 4], ptr [idx]); - if ( lane >= 8) ptr [idx ] = op(ptr [idx - 8], ptr [idx]); - if ( lane >= 16) ptr [idx ] = op(ptr [idx - 16], ptr [idx]); - - if( Kind == INCLUSIVE ) - return ptr [idx]; - else - return (lane > 0) ? ptr [idx - 1] : 0; - } - - __device__ __forceinline__ unsigned int index(const unsigned int tid) - { - return tid; - } - - __device__ __forceinline__ void init(volatile T *ptr){} - - static const int warp_offset = 0; - - typedef WarpScan merge; - }; - - template struct WarpScanNoComp - { - __device__ __forceinline__ WarpScanNoComp() {} - __device__ __forceinline__ WarpScanNoComp(const WarpScanNoComp& other) { CV_UNUSED(other); } - - __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) - { - const unsigned int lane = threadIdx.x & 31; - F op; - - ptr [idx ] = op(ptr [idx - 1], ptr [idx]); - ptr [idx ] = op(ptr [idx - 2], ptr [idx]); - ptr [idx ] = op(ptr [idx - 4], ptr [idx]); - ptr [idx ] = op(ptr [idx - 8], ptr [idx]); - ptr [idx ] = op(ptr [idx - 16], ptr [idx]); - - if( Kind == INCLUSIVE ) - return ptr [idx]; - else - return (lane > 0) ? ptr [idx - 1] : 0; - } - - __device__ __forceinline__ unsigned int index(const unsigned int tid) - { - return (tid >> warp_log) * warp_smem_stride + 16 + (tid & warp_mask); - } - - __device__ __forceinline__ void init(volatile T *ptr) - { - ptr[threadIdx.x] = 0; - } - - static const int warp_smem_stride = 32 + 16 + 1; - static const int warp_offset = 16; - static const int warp_log = 5; - static const int warp_mask = 31; - - typedef WarpScanNoComp merge; - }; - - template struct BlockScan - { - __device__ __forceinline__ BlockScan() {} - __device__ __forceinline__ BlockScan(const BlockScan& other) { CV_UNUSED(other); } - - __device__ __forceinline__ T operator()(volatile T *ptr) - { - const unsigned int tid = threadIdx.x; - const unsigned int lane = tid & warp_mask; - const unsigned int warp = tid >> warp_log; - - Sc scan; - typename Sc::merge merge_scan; - const unsigned int idx = scan.index(tid); - - T val = scan(ptr, idx); - __syncthreads (); - - if( warp == 0) - scan.init(ptr); - __syncthreads (); - - if( lane == 31 ) - ptr [scan.warp_offset + warp ] = (Kind == INCLUSIVE) ? val : ptr [idx]; - __syncthreads (); - - if( warp == 0 ) - merge_scan(ptr, idx); - __syncthreads(); - - if ( warp > 0) - val = ptr [scan.warp_offset + warp - 1] + val; - __syncthreads (); - - ptr[idx] = val; - __syncthreads (); - - return val ; - } - - static const int warp_log = 5; - static const int warp_mask = 31; - }; - - template - __device__ T warpScanInclusive(T idata, volatile T* s_Data, unsigned int tid) - { - #if __CUDA_ARCH__ >= 300 - const unsigned int laneId = cv::cuda::device::Warp::laneId(); - - // scan on shuffl functions - #pragma unroll - for (int i = 1; i <= (OPENCV_CUDA_WARP_SIZE / 2); i *= 2) - { - const T n = cv::cuda::device::shfl_up(idata, i); - if (laneId >= i) - idata += n; - } - - return idata; - #else - unsigned int pos = 2 * tid - (tid & (OPENCV_CUDA_WARP_SIZE - 1)); - s_Data[pos] = 0; - pos += OPENCV_CUDA_WARP_SIZE; - s_Data[pos] = idata; - - s_Data[pos] += s_Data[pos - 1]; - s_Data[pos] += s_Data[pos - 2]; - s_Data[pos] += s_Data[pos - 4]; - s_Data[pos] += s_Data[pos - 8]; - s_Data[pos] += s_Data[pos - 16]; - - return s_Data[pos]; - #endif - } - - template - __device__ __forceinline__ T warpScanExclusive(T idata, volatile T* s_Data, unsigned int tid) - { - return warpScanInclusive(idata, s_Data, tid) - idata; - } - - template - __device__ T blockScanInclusive(T idata, volatile T* s_Data, unsigned int tid) - { - if (tiNumScanThreads > OPENCV_CUDA_WARP_SIZE) - { - //Bottom-level inclusive warp scan - T warpResult = warpScanInclusive(idata, s_Data, tid); - - //Save top elements of each warp for exclusive warp scan - //sync to wait for warp scans to complete (because s_Data is being overwritten) - __syncthreads(); - if ((tid & (OPENCV_CUDA_WARP_SIZE - 1)) == (OPENCV_CUDA_WARP_SIZE - 1)) - { - s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE] = warpResult; - } - - //wait for warp scans to complete - __syncthreads(); - - if (tid < (tiNumScanThreads / OPENCV_CUDA_WARP_SIZE) ) - { - //grab top warp elements - T val = s_Data[tid]; - //calculate exclusive scan and write back to shared memory - s_Data[tid] = warpScanExclusive(val, s_Data, tid); - } - - //return updated warp scans with exclusive scan results - __syncthreads(); - - return warpResult + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE]; - } - else - { - return warpScanInclusive(idata, s_Data, tid); - } - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_SCAN_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_SCAN_HPP +#define OPENCV_CUDA_SCAN_HPP + +#include "opencv2/core/cuda/common.hpp" +#include "opencv2/core/cuda/utility.hpp" +#include "opencv2/core/cuda/warp.hpp" +#include "opencv2/core/cuda/warp_shuffle.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + enum ScanKind { EXCLUSIVE = 0, INCLUSIVE = 1 }; + + template struct WarpScan + { + __device__ __forceinline__ WarpScan() {} + __device__ __forceinline__ WarpScan(const WarpScan& other) { CV_UNUSED(other); } + + __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) + { + const unsigned int lane = idx & 31; + F op; + + if ( lane >= 1) ptr [idx ] = op(ptr [idx - 1], ptr [idx]); + if ( lane >= 2) ptr [idx ] = op(ptr [idx - 2], ptr [idx]); + if ( lane >= 4) ptr [idx ] = op(ptr [idx - 4], ptr [idx]); + if ( lane >= 8) ptr [idx ] = op(ptr [idx - 8], ptr [idx]); + if ( lane >= 16) ptr [idx ] = op(ptr [idx - 16], ptr [idx]); + + if( Kind == INCLUSIVE ) + return ptr [idx]; + else + return (lane > 0) ? ptr [idx - 1] : 0; + } + + __device__ __forceinline__ unsigned int index(const unsigned int tid) + { + return tid; + } + + __device__ __forceinline__ void init(volatile T *ptr){} + + static const int warp_offset = 0; + + typedef WarpScan merge; + }; + + template struct WarpScanNoComp + { + __device__ __forceinline__ WarpScanNoComp() {} + __device__ __forceinline__ WarpScanNoComp(const WarpScanNoComp& other) { CV_UNUSED(other); } + + __device__ __forceinline__ T operator()( volatile T *ptr , const unsigned int idx) + { + const unsigned int lane = threadIdx.x & 31; + F op; + + ptr [idx ] = op(ptr [idx - 1], ptr [idx]); + ptr [idx ] = op(ptr [idx - 2], ptr [idx]); + ptr [idx ] = op(ptr [idx - 4], ptr [idx]); + ptr [idx ] = op(ptr [idx - 8], ptr [idx]); + ptr [idx ] = op(ptr [idx - 16], ptr [idx]); + + if( Kind == INCLUSIVE ) + return ptr [idx]; + else + return (lane > 0) ? ptr [idx - 1] : 0; + } + + __device__ __forceinline__ unsigned int index(const unsigned int tid) + { + return (tid >> warp_log) * warp_smem_stride + 16 + (tid & warp_mask); + } + + __device__ __forceinline__ void init(volatile T *ptr) + { + ptr[threadIdx.x] = 0; + } + + static const int warp_smem_stride = 32 + 16 + 1; + static const int warp_offset = 16; + static const int warp_log = 5; + static const int warp_mask = 31; + + typedef WarpScanNoComp merge; + }; + + template struct BlockScan + { + __device__ __forceinline__ BlockScan() {} + __device__ __forceinline__ BlockScan(const BlockScan& other) { CV_UNUSED(other); } + + __device__ __forceinline__ T operator()(volatile T *ptr) + { + const unsigned int tid = threadIdx.x; + const unsigned int lane = tid & warp_mask; + const unsigned int warp = tid >> warp_log; + + Sc scan; + typename Sc::merge merge_scan; + const unsigned int idx = scan.index(tid); + + T val = scan(ptr, idx); + __syncthreads (); + + if( warp == 0) + scan.init(ptr); + __syncthreads (); + + if( lane == 31 ) + ptr [scan.warp_offset + warp ] = (Kind == INCLUSIVE) ? val : ptr [idx]; + __syncthreads (); + + if( warp == 0 ) + merge_scan(ptr, idx); + __syncthreads(); + + if ( warp > 0) + val = ptr [scan.warp_offset + warp - 1] + val; + __syncthreads (); + + ptr[idx] = val; + __syncthreads (); + + return val ; + } + + static const int warp_log = 5; + static const int warp_mask = 31; + }; + + template + __device__ T warpScanInclusive(T idata, volatile T* s_Data, unsigned int tid) + { + #if __CUDA_ARCH__ >= 300 + const unsigned int laneId = cv::cuda::device::Warp::laneId(); + + // scan on shuffl functions + #pragma unroll + for (int i = 1; i <= (OPENCV_CUDA_WARP_SIZE / 2); i *= 2) + { + const T n = cv::cuda::device::shfl_up(idata, i); + if (laneId >= i) + idata += n; + } + + return idata; + #else + unsigned int pos = 2 * tid - (tid & (OPENCV_CUDA_WARP_SIZE - 1)); + s_Data[pos] = 0; + pos += OPENCV_CUDA_WARP_SIZE; + s_Data[pos] = idata; + + s_Data[pos] += s_Data[pos - 1]; + s_Data[pos] += s_Data[pos - 2]; + s_Data[pos] += s_Data[pos - 4]; + s_Data[pos] += s_Data[pos - 8]; + s_Data[pos] += s_Data[pos - 16]; + + return s_Data[pos]; + #endif + } + + template + __device__ __forceinline__ T warpScanExclusive(T idata, volatile T* s_Data, unsigned int tid) + { + return warpScanInclusive(idata, s_Data, tid) - idata; + } + + template + __device__ T blockScanInclusive(T idata, volatile T* s_Data, unsigned int tid) + { + if (tiNumScanThreads > OPENCV_CUDA_WARP_SIZE) + { + //Bottom-level inclusive warp scan + T warpResult = warpScanInclusive(idata, s_Data, tid); + + //Save top elements of each warp for exclusive warp scan + //sync to wait for warp scans to complete (because s_Data is being overwritten) + __syncthreads(); + if ((tid & (OPENCV_CUDA_WARP_SIZE - 1)) == (OPENCV_CUDA_WARP_SIZE - 1)) + { + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE] = warpResult; + } + + //wait for warp scans to complete + __syncthreads(); + + if (tid < (tiNumScanThreads / OPENCV_CUDA_WARP_SIZE) ) + { + //grab top warp elements + T val = s_Data[tid]; + //calculate exclusive scan and write back to shared memory + s_Data[tid] = warpScanExclusive(val, s_Data, tid); + } + + //return updated warp scans with exclusive scan results + __syncthreads(); + + return warpResult + s_Data[tid >> OPENCV_CUDA_LOG_WARP_SIZE]; + } + else + { + return warpScanInclusive(idata, s_Data, tid); + } + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_SCAN_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp index 406fed748a..3d8c2e0d8e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/simd_functions.hpp @@ -1,869 +1,869 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -/* - * Copyright (c) 2013 NVIDIA Corporation. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * - * Neither the name of NVIDIA Corporation nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef OPENCV_CUDA_SIMD_FUNCTIONS_HPP -#define OPENCV_CUDA_SIMD_FUNCTIONS_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - // 2 - - static __device__ __forceinline__ unsigned int vadd2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vadd2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vadd.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = a ^ b; // sum bits - r = a + b; // actual sum - s = s ^ r; // determine carry-ins for each bit position - s = s & 0x00010000; // carry-in to high word (= carry-out from low word) - r = r - s; // subtract out carry-out from low word - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsub2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vsub2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vsub.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = a ^ b; // sum bits - r = a - b; // actual sum - s = s ^ r; // determine carry-ins for each bit position - s = s & 0x00010000; // borrow to high word - r = r + s; // compensate for borrow from low word - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vabsdiff2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vabsdiff2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vabsdiff.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t, u, v; - s = a & 0x0000ffff; // extract low halfword - r = b & 0x0000ffff; // extract low halfword - u = ::max(r, s); // maximum of low halfwords - v = ::min(r, s); // minimum of low halfwords - s = a & 0xffff0000; // extract high halfword - r = b & 0xffff0000; // extract high halfword - t = ::max(r, s); // maximum of high halfwords - s = ::min(r, s); // minimum of high halfwords - r = u | t; // maximum of both halfwords - s = v | s; // minimum of both halfwords - r = r - s; // |a - b| = max(a,b) - min(a,b); - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vavg2(unsigned int a, unsigned int b) - { - unsigned int r, s; - - // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> - // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) - s = a ^ b; - r = a & b; - s = s & 0xfffefffe; // ensure shift doesn't cross halfword boundaries - s = s >> 1; - s = r + s; - - return s; - } - - static __device__ __forceinline__ unsigned int vavrg2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vavrg2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> - // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) - unsigned int s; - s = a ^ b; - r = a | b; - s = s & 0xfffefffe; // ensure shift doesn't cross half-word boundaries - s = s >> 1; - r = r - s; - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vseteq2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r & ~c; // msb = 1, if r was 0x0000 - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpeq2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vseteq2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r & ~c; // msb = 1, if r was 0x0000 - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetge2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpge2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetge2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetgt2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80008000; // msbs = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpgt2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetgt2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80008000; // msbs = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetle2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmple2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetle2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetlt2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset2.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmplt2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetlt2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80008000; // msb = carry-outs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetne2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm ("vset2.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r | c; // msb = 1, if r was not 0x0000 - c = c & 0x80008000; // extract msbs - r = c >> 15; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpne2(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetne2(a, b); - c = r << 16; // convert bool - r = c - r; // into mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - r = a ^ b; // 0x0000 if a == b - c = r | 0x80008000; // set msbs, to catch carry out - c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 - c = r | c; // msb = 1, if r was not 0x0000 - c = c & 0x80008000; // extract msbs - r = c >> 15; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vmax2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmax2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmax.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t, u; - r = a & 0x0000ffff; // extract low halfword - s = b & 0x0000ffff; // extract low halfword - t = ::max(r, s); // maximum of low halfwords - r = a & 0xffff0000; // extract high halfword - s = b & 0xffff0000; // extract high halfword - u = ::max(r, s); // maximum of high halfwords - r = t | u; // combine halfword maximums - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vmin2(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmin2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmin.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t, u; - r = a & 0x0000ffff; // extract low halfword - s = b & 0x0000ffff; // extract low halfword - t = ::min(r, s); // minimum of low halfwords - r = a & 0xffff0000; // extract high halfword - s = b & 0xffff0000; // extract high halfword - u = ::min(r, s); // minimum of high halfwords - r = t | u; // combine halfword minimums - #endif - - return r; - } - - // 4 - - static __device__ __forceinline__ unsigned int vadd4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vadd4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vadd.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vadd.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t; - s = a ^ b; // sum bits - r = a & 0x7f7f7f7f; // clear msbs - t = b & 0x7f7f7f7f; // clear msbs - s = s & 0x80808080; // msb sum bits - r = r + t; // add without msbs, record carry-out in msbs - r = r ^ s; // sum of msb sum and carry-in bits, w/o carry-out - #endif /* __CUDA_ARCH__ >= 300 */ - - return r; - } - - static __device__ __forceinline__ unsigned int vsub4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vsub4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vsub.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vsub.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s, t; - s = a ^ ~b; // inverted sum bits - r = a | 0x80808080; // set msbs - t = b & 0x7f7f7f7f; // clear msbs - s = s & 0x80808080; // inverted msb sum bits - r = r - t; // subtract w/o msbs, record inverted borrows in msb - r = r ^ s; // combine inverted msb sum bits and borrows - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vavg4(unsigned int a, unsigned int b) - { - unsigned int r, s; - - // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> - // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) - s = a ^ b; - r = a & b; - s = s & 0xfefefefe; // ensure following shift doesn't cross byte boundaries - s = s >> 1; - s = r + s; - - return s; - } - - static __device__ __forceinline__ unsigned int vavrg4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vavrg4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> - // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) - unsigned int c; - c = a ^ b; - r = a | b; - c = c & 0xfefefefe; // ensure following shift doesn't cross byte boundaries - c = c >> 1; - r = r - c; - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vseteq4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x00 if a == b - c = r | 0x80808080; // set msbs, to catch carry out - r = r ^ c; // extract msbs, msb = 1 if r < 0x80 - c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 - c = r & ~c; // msb = 1, if r was 0x00 - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpeq4(unsigned int a, unsigned int b) - { - unsigned int r, t; - - #if __CUDA_ARCH__ >= 300 - r = vseteq4(a, b); - t = r << 8; // convert bool - r = t - r; // to mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - t = a ^ b; // 0x00 if a == b - r = t | 0x80808080; // set msbs, to catch carry out - t = t ^ r; // extract msbs, msb = 1 if t < 0x80 - r = r - 0x01010101; // msb = 0, if t was 0x00 or 0x80 - r = t & ~r; // msb = 1, if t was 0x00 - t = r >> 7; // build mask - t = r - t; // from - r = t | r; // msbs - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetle4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmple4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetle4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 - c = c & 0x80808080; // msbs = carry-outs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetlt4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmplt4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetlt4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - asm("not.b32 %0, %0;" : "+r"(a)); - c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] - c = c & 0x80808080; // msbs = carry-outs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetge4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavrg4(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpge4(unsigned int a, unsigned int b) - { - unsigned int r, s; - - #if __CUDA_ARCH__ >= 300 - r = vsetge4(a, b); - s = r << 8; // convert bool - r = s - r; // to mask - #else - asm ("not.b32 %0,%0;" : "+r"(b)); - r = vavrg4 (a, b); // (a + ~b + 1) / 2 = (a - b) / 2 - r = r & 0x80808080; // msb = carry-outs - s = r >> 7; // build mask - s = r - s; // from - r = s | r; // msbs - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetgt4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int c; - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpgt4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetgt4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - asm("not.b32 %0, %0;" : "+r"(b)); - c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] - c = c & 0x80808080; // msb = carry-outs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vsetne4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vset4.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - unsigned int c; - r = a ^ b; // 0x00 if a == b - c = r | 0x80808080; // set msbs, to catch carry out - c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 - c = r | c; // msb = 1, if r was not 0x00 - c = c & 0x80808080; // extract msbs - r = c >> 7; // convert to bool - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vcmpne4(unsigned int a, unsigned int b) - { - unsigned int r, c; - - #if __CUDA_ARCH__ >= 300 - r = vsetne4(a, b); - c = r << 8; // convert bool - r = c - r; // to mask - #else - // inspired by Alan Mycroft's null-byte detection algorithm: - // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) - r = a ^ b; // 0x00 if a == b - c = r | 0x80808080; // set msbs, to catch carry out - c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 - c = r | c; // msb = 1, if r was not 0x00 - c = c & 0x80808080; // extract msbs - r = c >> 7; // convert - r = c - r; // msbs to - r = c | r; // mask - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vabsdiff4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vabsdiff4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vabsdiff.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vabsdiff.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = vcmpge4(a, b); // mask = 0xff if a >= b - r = a ^ b; // - s = (r & s) ^ b; // select a when a >= b, else select b => max(a,b) - r = s ^ r; // select a when b >= a, else select b => min(a,b) - r = s - r; // |a - b| = max(a,b) - min(a,b); - #endif - - return r; - } - - static __device__ __forceinline__ unsigned int vmax4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmax4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmax.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmax.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = vcmpge4(a, b); // mask = 0xff if a >= b - r = a & s; // select a when b >= a - s = b & ~s; // select b when b < a - r = r | s; // combine byte selections - #endif - - return r; // byte-wise unsigned maximum - } - - static __device__ __forceinline__ unsigned int vmin4(unsigned int a, unsigned int b) - { - unsigned int r = 0; - - #if __CUDA_ARCH__ >= 300 - asm("vmin4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #elif __CUDA_ARCH__ >= 200 - asm("vmin.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - asm("vmin.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); - #else - unsigned int s; - s = vcmpge4(b, a); // mask = 0xff if a >= b - r = a & s; // select a when b >= a - s = b & ~s; // select b when b < a - r = r | s; // combine byte selections - #endif - - return r; - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_SIMD_FUNCTIONS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +/* + * Copyright (c) 2013 NVIDIA Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * Neither the name of NVIDIA Corporation nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef OPENCV_CUDA_SIMD_FUNCTIONS_HPP +#define OPENCV_CUDA_SIMD_FUNCTIONS_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + // 2 + + static __device__ __forceinline__ unsigned int vadd2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vadd2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vadd.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = a ^ b; // sum bits + r = a + b; // actual sum + s = s ^ r; // determine carry-ins for each bit position + s = s & 0x00010000; // carry-in to high word (= carry-out from low word) + r = r - s; // subtract out carry-out from low word + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsub2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vsub2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vsub.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = a ^ b; // sum bits + r = a - b; // actual sum + s = s ^ r; // determine carry-ins for each bit position + s = s & 0x00010000; // borrow to high word + r = r + s; // compensate for borrow from low word + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vabsdiff2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vabsdiff2.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vabsdiff.u32.u32.u32.sat %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t, u, v; + s = a & 0x0000ffff; // extract low halfword + r = b & 0x0000ffff; // extract low halfword + u = ::max(r, s); // maximum of low halfwords + v = ::min(r, s); // minimum of low halfwords + s = a & 0xffff0000; // extract high halfword + r = b & 0xffff0000; // extract high halfword + t = ::max(r, s); // maximum of high halfwords + s = ::min(r, s); // minimum of high halfwords + r = u | t; // maximum of both halfwords + s = v | s; // minimum of both halfwords + r = r - s; // |a - b| = max(a,b) - min(a,b); + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vavg2(unsigned int a, unsigned int b) + { + unsigned int r, s; + + // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> + // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) + s = a ^ b; + r = a & b; + s = s & 0xfffefffe; // ensure shift doesn't cross halfword boundaries + s = s >> 1; + s = r + s; + + return s; + } + + static __device__ __forceinline__ unsigned int vavrg2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vavrg2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> + // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) + unsigned int s; + s = a ^ b; + r = a | b; + s = s & 0xfffefffe; // ensure shift doesn't cross half-word boundaries + s = s >> 1; + r = r - s; + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vseteq2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r & ~c; // msb = 1, if r was 0x0000 + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpeq2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vseteq2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + r = r ^ c; // extract msbs, msb = 1 if r < 0x8000 + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r & ~c; // msb = 1, if r was 0x0000 + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetge2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpge2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetge2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavrg2(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetgt2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80008000; // msbs = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpgt2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetgt2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg2(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80008000; // msbs = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetle2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmple2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetle2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg2(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetlt2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset2.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmplt2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetlt2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg2(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80008000; // msb = carry-outs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetne2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm ("vset2.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r | c; // msb = 1, if r was not 0x0000 + c = c & 0x80008000; // extract msbs + r = c >> 15; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpne2(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetne2(a, b); + c = r << 16; // convert bool + r = c - r; // into mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + r = a ^ b; // 0x0000 if a == b + c = r | 0x80008000; // set msbs, to catch carry out + c = c - 0x00010001; // msb = 0, if r was 0x0000 or 0x8000 + c = r | c; // msb = 1, if r was not 0x0000 + c = c & 0x80008000; // extract msbs + r = c >> 15; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vmax2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmax2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmax.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t, u; + r = a & 0x0000ffff; // extract low halfword + s = b & 0x0000ffff; // extract low halfword + t = ::max(r, s); // maximum of low halfwords + r = a & 0xffff0000; // extract high halfword + s = b & 0xffff0000; // extract high halfword + u = ::max(r, s); // maximum of high halfwords + r = t | u; // combine halfword maximums + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vmin2(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmin2.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmin.u32.u32.u32 %0.h0, %1.h0, %2.h0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.h1, %1.h1, %2.h1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t, u; + r = a & 0x0000ffff; // extract low halfword + s = b & 0x0000ffff; // extract low halfword + t = ::min(r, s); // minimum of low halfwords + r = a & 0xffff0000; // extract high halfword + s = b & 0xffff0000; // extract high halfword + u = ::min(r, s); // minimum of high halfwords + r = t | u; // combine halfword minimums + #endif + + return r; + } + + // 4 + + static __device__ __forceinline__ unsigned int vadd4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vadd4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vadd.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vadd.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t; + s = a ^ b; // sum bits + r = a & 0x7f7f7f7f; // clear msbs + t = b & 0x7f7f7f7f; // clear msbs + s = s & 0x80808080; // msb sum bits + r = r + t; // add without msbs, record carry-out in msbs + r = r ^ s; // sum of msb sum and carry-in bits, w/o carry-out + #endif /* __CUDA_ARCH__ >= 300 */ + + return r; + } + + static __device__ __forceinline__ unsigned int vsub4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vsub4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vsub.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vsub.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s, t; + s = a ^ ~b; // inverted sum bits + r = a | 0x80808080; // set msbs + t = b & 0x7f7f7f7f; // clear msbs + s = s & 0x80808080; // inverted msb sum bits + r = r - t; // subtract w/o msbs, record inverted borrows in msb + r = r ^ s; // combine inverted msb sum bits and borrows + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vavg4(unsigned int a, unsigned int b) + { + unsigned int r, s; + + // HAKMEM #23: a + b = 2 * (a & b) + (a ^ b) ==> + // (a + b) / 2 = (a & b) + ((a ^ b) >> 1) + s = a ^ b; + r = a & b; + s = s & 0xfefefefe; // ensure following shift doesn't cross byte boundaries + s = s >> 1; + s = r + s; + + return s; + } + + static __device__ __forceinline__ unsigned int vavrg4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vavrg4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // HAKMEM #23: a + b = 2 * (a | b) - (a ^ b) ==> + // (a + b + 1) / 2 = (a | b) - ((a ^ b) >> 1) + unsigned int c; + c = a ^ b; + r = a | b; + c = c & 0xfefefefe; // ensure following shift doesn't cross byte boundaries + c = c >> 1; + r = r - c; + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vseteq4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.eq %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x00 if a == b + c = r | 0x80808080; // set msbs, to catch carry out + r = r ^ c; // extract msbs, msb = 1 if r < 0x80 + c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 + c = r & ~c; // msb = 1, if r was 0x00 + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpeq4(unsigned int a, unsigned int b) + { + unsigned int r, t; + + #if __CUDA_ARCH__ >= 300 + r = vseteq4(a, b); + t = r << 8; // convert bool + r = t - r; // to mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + t = a ^ b; // 0x00 if a == b + r = t | 0x80808080; // set msbs, to catch carry out + t = t ^ r; // extract msbs, msb = 1 if t < 0x80 + r = r - 0x01010101; // msb = 0, if t was 0x00 or 0x80 + r = t & ~r; // msb = 1, if t was 0x00 + t = r >> 7; // build mask + t = r - t; // from + r = t | r; // msbs + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetle4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.le %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmple4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetle4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavrg4(a, b); // (b + ~a + 1) / 2 = (b - a) / 2 + c = c & 0x80808080; // msbs = carry-outs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetlt4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.lt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmplt4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetlt4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + asm("not.b32 %0, %0;" : "+r"(a)); + c = vavg4(a, b); // (b + ~a) / 2 = (b - a) / 2 [rounded down] + c = c & 0x80808080; // msbs = carry-outs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetge4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.ge %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavrg4(a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpge4(unsigned int a, unsigned int b) + { + unsigned int r, s; + + #if __CUDA_ARCH__ >= 300 + r = vsetge4(a, b); + s = r << 8; // convert bool + r = s - r; // to mask + #else + asm ("not.b32 %0,%0;" : "+r"(b)); + r = vavrg4 (a, b); // (a + ~b + 1) / 2 = (a - b) / 2 + r = r & 0x80808080; // msb = carry-outs + s = r >> 7; // build mask + s = r - s; // from + r = s | r; // msbs + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetgt4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.gt %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int c; + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpgt4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetgt4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + asm("not.b32 %0, %0;" : "+r"(b)); + c = vavg4(a, b); // (a + ~b) / 2 = (a - b) / 2 [rounded down] + c = c & 0x80808080; // msb = carry-outs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vsetne4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vset4.u32.u32.ne %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + unsigned int c; + r = a ^ b; // 0x00 if a == b + c = r | 0x80808080; // set msbs, to catch carry out + c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 + c = r | c; // msb = 1, if r was not 0x00 + c = c & 0x80808080; // extract msbs + r = c >> 7; // convert to bool + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vcmpne4(unsigned int a, unsigned int b) + { + unsigned int r, c; + + #if __CUDA_ARCH__ >= 300 + r = vsetne4(a, b); + c = r << 8; // convert bool + r = c - r; // to mask + #else + // inspired by Alan Mycroft's null-byte detection algorithm: + // null_byte(x) = ((x - 0x01010101) & (~x & 0x80808080)) + r = a ^ b; // 0x00 if a == b + c = r | 0x80808080; // set msbs, to catch carry out + c = c - 0x01010101; // msb = 0, if r was 0x00 or 0x80 + c = r | c; // msb = 1, if r was not 0x00 + c = c & 0x80808080; // extract msbs + r = c >> 7; // convert + r = c - r; // msbs to + r = c | r; // mask + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vabsdiff4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vabsdiff4.u32.u32.u32.sat %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vabsdiff.u32.u32.u32.sat %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vabsdiff.u32.u32.u32.sat %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = vcmpge4(a, b); // mask = 0xff if a >= b + r = a ^ b; // + s = (r & s) ^ b; // select a when a >= b, else select b => max(a,b) + r = s ^ r; // select a when b >= a, else select b => min(a,b) + r = s - r; // |a - b| = max(a,b) - min(a,b); + #endif + + return r; + } + + static __device__ __forceinline__ unsigned int vmax4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmax4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmax.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmax.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = vcmpge4(a, b); // mask = 0xff if a >= b + r = a & s; // select a when b >= a + s = b & ~s; // select b when b < a + r = r | s; // combine byte selections + #endif + + return r; // byte-wise unsigned maximum + } + + static __device__ __forceinline__ unsigned int vmin4(unsigned int a, unsigned int b) + { + unsigned int r = 0; + + #if __CUDA_ARCH__ >= 300 + asm("vmin4.u32.u32.u32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #elif __CUDA_ARCH__ >= 200 + asm("vmin.u32.u32.u32 %0.b0, %1.b0, %2.b0, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.b1, %1.b1, %2.b1, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.b2, %1.b2, %2.b2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + asm("vmin.u32.u32.u32 %0.b3, %1.b3, %2.b3, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(r)); + #else + unsigned int s; + s = vcmpge4(b, a); // mask = 0xff if a >= b + r = a & s; // select a when b >= a + s = b & ~s; // select b when b < a + r = r | s; // combine byte selections + #endif + + return r; + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_SIMD_FUNCTIONS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp index fd4fb6f0c6..42aa6ea170 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/transform.hpp @@ -1,75 +1,75 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_TRANSFORM_HPP -#define OPENCV_CUDA_TRANSFORM_HPP - -#include "common.hpp" -#include "utility.hpp" -#include "detail/transform_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - static inline void transform(PtrStepSz src, PtrStepSz dst, UnOp op, const Mask& mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src, dst, op, mask, stream); - } - - template - static inline void transform(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, const Mask& mask, cudaStream_t stream) - { - typedef TransformFunctorTraits ft; - transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src1, src2, dst, op, mask, stream); - } -}}} - -//! @endcond - -#endif // OPENCV_CUDA_TRANSFORM_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_TRANSFORM_HPP +#define OPENCV_CUDA_TRANSFORM_HPP + +#include "common.hpp" +#include "utility.hpp" +#include "detail/transform_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + static inline void transform(PtrStepSz src, PtrStepSz dst, UnOp op, const Mask& mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src, dst, op, mask, stream); + } + + template + static inline void transform(PtrStepSz src1, PtrStepSz src2, PtrStepSz dst, BinOp op, const Mask& mask, cudaStream_t stream) + { + typedef TransformFunctorTraits ft; + transform_detail::TransformDispatcher::cn == 1 && VecTraits::cn == 1 && VecTraits::cn == 1 && ft::smart_shift != 1>::call(src1, src2, dst, op, mask, stream); + } +}}} + +//! @endcond + +#endif // OPENCV_CUDA_TRANSFORM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp index e7faa905a0..8b7a3fd168 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/type_traits.hpp @@ -1,90 +1,90 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_TYPE_TRAITS_HPP -#define OPENCV_CUDA_TYPE_TRAITS_HPP - -#include "detail/type_traits_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct IsSimpleParameter - { - enum {value = type_traits_detail::IsIntegral::value || type_traits_detail::IsFloat::value || - type_traits_detail::PointerTraits::type>::value}; - }; - - template struct TypeTraits - { - typedef typename type_traits_detail::UnConst::type NonConstType; - typedef typename type_traits_detail::UnVolatile::type NonVolatileType; - typedef typename type_traits_detail::UnVolatile::type>::type UnqualifiedType; - typedef typename type_traits_detail::PointerTraits::type PointeeType; - typedef typename type_traits_detail::ReferenceTraits::type ReferredType; - - enum { isConst = type_traits_detail::UnConst::value }; - enum { isVolatile = type_traits_detail::UnVolatile::value }; - - enum { isReference = type_traits_detail::ReferenceTraits::value }; - enum { isPointer = type_traits_detail::PointerTraits::type>::value }; - - enum { isUnsignedInt = type_traits_detail::IsUnsignedIntegral::value }; - enum { isSignedInt = type_traits_detail::IsSignedIntergral::value }; - enum { isIntegral = type_traits_detail::IsIntegral::value }; - enum { isFloat = type_traits_detail::IsFloat::value }; - enum { isArith = isIntegral || isFloat }; - enum { isVec = type_traits_detail::IsVec::value }; - - typedef typename type_traits_detail::Select::value, - T, typename type_traits_detail::AddParameterType::type>::type ParameterType; - }; -}}} - -//! @endcond - -#endif // OPENCV_CUDA_TYPE_TRAITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_TYPE_TRAITS_HPP +#define OPENCV_CUDA_TYPE_TRAITS_HPP + +#include "detail/type_traits_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct IsSimpleParameter + { + enum {value = type_traits_detail::IsIntegral::value || type_traits_detail::IsFloat::value || + type_traits_detail::PointerTraits::type>::value}; + }; + + template struct TypeTraits + { + typedef typename type_traits_detail::UnConst::type NonConstType; + typedef typename type_traits_detail::UnVolatile::type NonVolatileType; + typedef typename type_traits_detail::UnVolatile::type>::type UnqualifiedType; + typedef typename type_traits_detail::PointerTraits::type PointeeType; + typedef typename type_traits_detail::ReferenceTraits::type ReferredType; + + enum { isConst = type_traits_detail::UnConst::value }; + enum { isVolatile = type_traits_detail::UnVolatile::value }; + + enum { isReference = type_traits_detail::ReferenceTraits::value }; + enum { isPointer = type_traits_detail::PointerTraits::type>::value }; + + enum { isUnsignedInt = type_traits_detail::IsUnsignedIntegral::value }; + enum { isSignedInt = type_traits_detail::IsSignedIntergral::value }; + enum { isIntegral = type_traits_detail::IsIntegral::value }; + enum { isFloat = type_traits_detail::IsFloat::value }; + enum { isArith = isIntegral || isFloat }; + enum { isVec = type_traits_detail::IsVec::value }; + + typedef typename type_traits_detail::Select::value, + T, typename type_traits_detail::AddParameterType::type>::type ParameterType; + }; +}}} + +//! @endcond + +#endif // OPENCV_CUDA_TYPE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp index 525419265c..7f5db48a50 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/utility.hpp @@ -1,230 +1,230 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_UTILITY_HPP -#define OPENCV_CUDA_UTILITY_HPP - -#include "saturate_cast.hpp" -#include "datamov_utils.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct CV_EXPORTS ThrustAllocator - { - typedef uchar value_type; - virtual ~ThrustAllocator(); - virtual __device__ __host__ uchar* allocate(size_t numBytes) = 0; - virtual __device__ __host__ void deallocate(uchar* ptr, size_t numBytes) = 0; - static ThrustAllocator& getAllocator(); - static void setAllocator(ThrustAllocator* allocator); - }; - #define OPENCV_CUDA_LOG_WARP_SIZE (5) - #define OPENCV_CUDA_WARP_SIZE (1 << OPENCV_CUDA_LOG_WARP_SIZE) - #define OPENCV_CUDA_LOG_MEM_BANKS ((__CUDA_ARCH__ >= 200) ? 5 : 4) // 32 banks on fermi, 16 on tesla - #define OPENCV_CUDA_MEM_BANKS (1 << OPENCV_CUDA_LOG_MEM_BANKS) - - /////////////////////////////////////////////////////////////////////////////// - // swap - - template void __device__ __host__ __forceinline__ swap(T& a, T& b) - { - const T temp = a; - a = b; - b = temp; - } - - /////////////////////////////////////////////////////////////////////////////// - // Mask Reader - - struct SingleMask - { - explicit __host__ __device__ __forceinline__ SingleMask(PtrStepb mask_) : mask(mask_) {} - __host__ __device__ __forceinline__ SingleMask(const SingleMask& mask_): mask(mask_.mask){} - - __device__ __forceinline__ bool operator()(int y, int x) const - { - return mask.ptr(y)[x] != 0; - } - - PtrStepb mask; - }; - - struct SingleMaskChannels - { - __host__ __device__ __forceinline__ SingleMaskChannels(PtrStepb mask_, int channels_) - : mask(mask_), channels(channels_) {} - __host__ __device__ __forceinline__ SingleMaskChannels(const SingleMaskChannels& mask_) - :mask(mask_.mask), channels(mask_.channels){} - - __device__ __forceinline__ bool operator()(int y, int x) const - { - return mask.ptr(y)[x / channels] != 0; - } - - PtrStepb mask; - int channels; - }; - - struct MaskCollection - { - explicit __host__ __device__ __forceinline__ MaskCollection(PtrStepb* maskCollection_) - : maskCollection(maskCollection_) {} - - __device__ __forceinline__ MaskCollection(const MaskCollection& masks_) - : maskCollection(masks_.maskCollection), curMask(masks_.curMask){} - - __device__ __forceinline__ void next() - { - curMask = *maskCollection++; - } - __device__ __forceinline__ void setMask(int z) - { - curMask = maskCollection[z]; - } - - __device__ __forceinline__ bool operator()(int y, int x) const - { - uchar val; - return curMask.data == 0 || (ForceGlob::Load(curMask.ptr(y), x, val), (val != 0)); - } - - const PtrStepb* maskCollection; - PtrStepb curMask; - }; - - struct WithOutMask - { - __host__ __device__ __forceinline__ WithOutMask(){} - __host__ __device__ __forceinline__ WithOutMask(const WithOutMask&){} - - __device__ __forceinline__ void next() const - { - } - __device__ __forceinline__ void setMask(int) const - { - } - - __device__ __forceinline__ bool operator()(int, int) const - { - return true; - } - - __device__ __forceinline__ bool operator()(int, int, int) const - { - return true; - } - - static __device__ __forceinline__ bool check(int, int) - { - return true; - } - - static __device__ __forceinline__ bool check(int, int, int) - { - return true; - } - }; - - /////////////////////////////////////////////////////////////////////////////// - // Solve linear system - - // solve 2x2 linear system Ax=b - template __device__ __forceinline__ bool solve2x2(const T A[2][2], const T b[2], T x[2]) - { - T det = A[0][0] * A[1][1] - A[1][0] * A[0][1]; - - if (det != 0) - { - double invdet = 1.0 / det; - - x[0] = saturate_cast(invdet * (b[0] * A[1][1] - b[1] * A[0][1])); - - x[1] = saturate_cast(invdet * (A[0][0] * b[1] - A[1][0] * b[0])); - - return true; - } - - return false; - } - - // solve 3x3 linear system Ax=b - template __device__ __forceinline__ bool solve3x3(const T A[3][3], const T b[3], T x[3]) - { - T det = A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) - + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]); - - if (det != 0) - { - double invdet = 1.0 / det; - - x[0] = saturate_cast(invdet * - (b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - - A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2] ) + - A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2] ))); - - x[1] = saturate_cast(invdet * - (A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2] ) - - b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + - A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0]))); - - x[2] = saturate_cast(invdet * - (A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) - - A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) + - b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))); - - return true; - } - - return false; - } -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_UTILITY_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_UTILITY_HPP +#define OPENCV_CUDA_UTILITY_HPP + +#include "saturate_cast.hpp" +#include "datamov_utils.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct CV_EXPORTS ThrustAllocator + { + typedef uchar value_type; + virtual ~ThrustAllocator(); + virtual __device__ __host__ uchar* allocate(size_t numBytes) = 0; + virtual __device__ __host__ void deallocate(uchar* ptr, size_t numBytes) = 0; + static ThrustAllocator& getAllocator(); + static void setAllocator(ThrustAllocator* allocator); + }; + #define OPENCV_CUDA_LOG_WARP_SIZE (5) + #define OPENCV_CUDA_WARP_SIZE (1 << OPENCV_CUDA_LOG_WARP_SIZE) + #define OPENCV_CUDA_LOG_MEM_BANKS ((__CUDA_ARCH__ >= 200) ? 5 : 4) // 32 banks on fermi, 16 on tesla + #define OPENCV_CUDA_MEM_BANKS (1 << OPENCV_CUDA_LOG_MEM_BANKS) + + /////////////////////////////////////////////////////////////////////////////// + // swap + + template void __device__ __host__ __forceinline__ swap(T& a, T& b) + { + const T temp = a; + a = b; + b = temp; + } + + /////////////////////////////////////////////////////////////////////////////// + // Mask Reader + + struct SingleMask + { + explicit __host__ __device__ __forceinline__ SingleMask(PtrStepb mask_) : mask(mask_) {} + __host__ __device__ __forceinline__ SingleMask(const SingleMask& mask_): mask(mask_.mask){} + + __device__ __forceinline__ bool operator()(int y, int x) const + { + return mask.ptr(y)[x] != 0; + } + + PtrStepb mask; + }; + + struct SingleMaskChannels + { + __host__ __device__ __forceinline__ SingleMaskChannels(PtrStepb mask_, int channels_) + : mask(mask_), channels(channels_) {} + __host__ __device__ __forceinline__ SingleMaskChannels(const SingleMaskChannels& mask_) + :mask(mask_.mask), channels(mask_.channels){} + + __device__ __forceinline__ bool operator()(int y, int x) const + { + return mask.ptr(y)[x / channels] != 0; + } + + PtrStepb mask; + int channels; + }; + + struct MaskCollection + { + explicit __host__ __device__ __forceinline__ MaskCollection(PtrStepb* maskCollection_) + : maskCollection(maskCollection_) {} + + __device__ __forceinline__ MaskCollection(const MaskCollection& masks_) + : maskCollection(masks_.maskCollection), curMask(masks_.curMask){} + + __device__ __forceinline__ void next() + { + curMask = *maskCollection++; + } + __device__ __forceinline__ void setMask(int z) + { + curMask = maskCollection[z]; + } + + __device__ __forceinline__ bool operator()(int y, int x) const + { + uchar val; + return curMask.data == 0 || (ForceGlob::Load(curMask.ptr(y), x, val), (val != 0)); + } + + const PtrStepb* maskCollection; + PtrStepb curMask; + }; + + struct WithOutMask + { + __host__ __device__ __forceinline__ WithOutMask(){} + __host__ __device__ __forceinline__ WithOutMask(const WithOutMask&){} + + __device__ __forceinline__ void next() const + { + } + __device__ __forceinline__ void setMask(int) const + { + } + + __device__ __forceinline__ bool operator()(int, int) const + { + return true; + } + + __device__ __forceinline__ bool operator()(int, int, int) const + { + return true; + } + + static __device__ __forceinline__ bool check(int, int) + { + return true; + } + + static __device__ __forceinline__ bool check(int, int, int) + { + return true; + } + }; + + /////////////////////////////////////////////////////////////////////////////// + // Solve linear system + + // solve 2x2 linear system Ax=b + template __device__ __forceinline__ bool solve2x2(const T A[2][2], const T b[2], T x[2]) + { + T det = A[0][0] * A[1][1] - A[1][0] * A[0][1]; + + if (det != 0) + { + double invdet = 1.0 / det; + + x[0] = saturate_cast(invdet * (b[0] * A[1][1] - b[1] * A[0][1])); + + x[1] = saturate_cast(invdet * (A[0][0] * b[1] - A[1][0] * b[0])); + + return true; + } + + return false; + } + + // solve 3x3 linear system Ax=b + template __device__ __forceinline__ bool solve3x3(const T A[3][3], const T b[3], T x[3]) + { + T det = A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) + - A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + + A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]); + + if (det != 0) + { + double invdet = 1.0 / det; + + x[0] = saturate_cast(invdet * + (b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) - + A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2] ) + + A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2] ))); + + x[1] = saturate_cast(invdet * + (A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2] ) - + b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) + + A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0]))); + + x[2] = saturate_cast(invdet * + (A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) - + A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) + + b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0]))); + + return true; + } + + return false; + } +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_UTILITY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp index 64a372bb09..ef6e51087d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_distance.hpp @@ -1,232 +1,232 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_VEC_DISTANCE_HPP -#define OPENCV_CUDA_VEC_DISTANCE_HPP - -#include "reduce.hpp" -#include "functional.hpp" -#include "detail/vec_distance_detail.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct L1Dist - { - typedef int value_type; - typedef int result_type; - - __device__ __forceinline__ L1Dist() : mySum(0) {} - - __device__ __forceinline__ void reduceIter(int val1, int val2) - { - mySum = __sad(val1, val2, mySum); - } - - template __device__ __forceinline__ void reduceAll(int* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator int() const - { - return mySum; - } - - int mySum; - }; - template <> struct L1Dist - { - typedef float value_type; - typedef float result_type; - - __device__ __forceinline__ L1Dist() : mySum(0.0f) {} - - __device__ __forceinline__ void reduceIter(float val1, float val2) - { - mySum += ::fabs(val1 - val2); - } - - template __device__ __forceinline__ void reduceAll(float* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator float() const - { - return mySum; - } - - float mySum; - }; - - struct L2Dist - { - typedef float value_type; - typedef float result_type; - - __device__ __forceinline__ L2Dist() : mySum(0.0f) {} - - __device__ __forceinline__ void reduceIter(float val1, float val2) - { - float reg = val1 - val2; - mySum += reg * reg; - } - - template __device__ __forceinline__ void reduceAll(float* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator float() const - { - return sqrtf(mySum); - } - - float mySum; - }; - - struct HammingDist - { - typedef int value_type; - typedef int result_type; - - __device__ __forceinline__ HammingDist() : mySum(0) {} - - __device__ __forceinline__ void reduceIter(int val1, int val2) - { - mySum += __popc(val1 ^ val2); - } - - template __device__ __forceinline__ void reduceAll(int* smem, int tid) - { - reduce(smem, mySum, tid, plus()); - } - - __device__ __forceinline__ operator int() const - { - return mySum; - } - - int mySum; - }; - - // calc distance between two vectors in global memory - template - __device__ void calcVecDiffGlobal(const T1* vec1, const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) - { - for (int i = tid; i < len; i += THREAD_DIM) - { - T1 val1; - ForceGlob::Load(vec1, i, val1); - - T2 val2; - ForceGlob::Load(vec2, i, val2); - - dist.reduceIter(val1, val2); - } - - dist.reduceAll(smem, tid); - } - - // calc distance between two vectors, first vector is cached in register or shared memory, second vector is in global memory - template - __device__ __forceinline__ void calcVecDiffCached(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, typename Dist::result_type* smem, int tid) - { - vec_distance_detail::VecDiffCachedCalculator::calc(vecCached, vecGlob, len, dist, tid); - - dist.reduceAll(smem, tid); - } - - // calc distance between two vectors in global memory - template struct VecDiffGlobal - { - explicit __device__ __forceinline__ VecDiffGlobal(const T1* vec1_, int = 0, void* = 0, int = 0, int = 0) - { - vec1 = vec1_; - } - - template - __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const - { - calcVecDiffGlobal(vec1, vec2, len, dist, smem, tid); - } - - const T1* vec1; - }; - - // calc distance between two vectors, first vector is cached in register memory, second vector is in global memory - template struct VecDiffCachedRegister - { - template __device__ __forceinline__ VecDiffCachedRegister(const T1* vec1, int len, U* smem, int glob_tid, int tid) - { - if (glob_tid < len) - smem[glob_tid] = vec1[glob_tid]; - __syncthreads(); - - U* vec1ValsPtr = vec1Vals; - - #pragma unroll - for (int i = tid; i < MAX_LEN; i += THREAD_DIM) - *vec1ValsPtr++ = smem[i]; - - __syncthreads(); - } - - template - __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const - { - calcVecDiffCached(vec1Vals, vec2, len, dist, smem, tid); - } - - U vec1Vals[MAX_LEN / THREAD_DIM]; - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_VEC_DISTANCE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_VEC_DISTANCE_HPP +#define OPENCV_CUDA_VEC_DISTANCE_HPP + +#include "reduce.hpp" +#include "functional.hpp" +#include "detail/vec_distance_detail.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct L1Dist + { + typedef int value_type; + typedef int result_type; + + __device__ __forceinline__ L1Dist() : mySum(0) {} + + __device__ __forceinline__ void reduceIter(int val1, int val2) + { + mySum = __sad(val1, val2, mySum); + } + + template __device__ __forceinline__ void reduceAll(int* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator int() const + { + return mySum; + } + + int mySum; + }; + template <> struct L1Dist + { + typedef float value_type; + typedef float result_type; + + __device__ __forceinline__ L1Dist() : mySum(0.0f) {} + + __device__ __forceinline__ void reduceIter(float val1, float val2) + { + mySum += ::fabs(val1 - val2); + } + + template __device__ __forceinline__ void reduceAll(float* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator float() const + { + return mySum; + } + + float mySum; + }; + + struct L2Dist + { + typedef float value_type; + typedef float result_type; + + __device__ __forceinline__ L2Dist() : mySum(0.0f) {} + + __device__ __forceinline__ void reduceIter(float val1, float val2) + { + float reg = val1 - val2; + mySum += reg * reg; + } + + template __device__ __forceinline__ void reduceAll(float* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator float() const + { + return sqrtf(mySum); + } + + float mySum; + }; + + struct HammingDist + { + typedef int value_type; + typedef int result_type; + + __device__ __forceinline__ HammingDist() : mySum(0) {} + + __device__ __forceinline__ void reduceIter(int val1, int val2) + { + mySum += __popc(val1 ^ val2); + } + + template __device__ __forceinline__ void reduceAll(int* smem, int tid) + { + reduce(smem, mySum, tid, plus()); + } + + __device__ __forceinline__ operator int() const + { + return mySum; + } + + int mySum; + }; + + // calc distance between two vectors in global memory + template + __device__ void calcVecDiffGlobal(const T1* vec1, const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) + { + for (int i = tid; i < len; i += THREAD_DIM) + { + T1 val1; + ForceGlob::Load(vec1, i, val1); + + T2 val2; + ForceGlob::Load(vec2, i, val2); + + dist.reduceIter(val1, val2); + } + + dist.reduceAll(smem, tid); + } + + // calc distance between two vectors, first vector is cached in register or shared memory, second vector is in global memory + template + __device__ __forceinline__ void calcVecDiffCached(const T1* vecCached, const T2* vecGlob, int len, Dist& dist, typename Dist::result_type* smem, int tid) + { + vec_distance_detail::VecDiffCachedCalculator::calc(vecCached, vecGlob, len, dist, tid); + + dist.reduceAll(smem, tid); + } + + // calc distance between two vectors in global memory + template struct VecDiffGlobal + { + explicit __device__ __forceinline__ VecDiffGlobal(const T1* vec1_, int = 0, void* = 0, int = 0, int = 0) + { + vec1 = vec1_; + } + + template + __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const + { + calcVecDiffGlobal(vec1, vec2, len, dist, smem, tid); + } + + const T1* vec1; + }; + + // calc distance between two vectors, first vector is cached in register memory, second vector is in global memory + template struct VecDiffCachedRegister + { + template __device__ __forceinline__ VecDiffCachedRegister(const T1* vec1, int len, U* smem, int glob_tid, int tid) + { + if (glob_tid < len) + smem[glob_tid] = vec1[glob_tid]; + __syncthreads(); + + U* vec1ValsPtr = vec1Vals; + + #pragma unroll + for (int i = tid; i < MAX_LEN; i += THREAD_DIM) + *vec1ValsPtr++ = smem[i]; + + __syncthreads(); + } + + template + __device__ __forceinline__ void calc(const T2* vec2, int len, Dist& dist, typename Dist::result_type* smem, int tid) const + { + calcVecDiffCached(vec1Vals, vec2, len, dist, smem, tid); + } + + U vec1Vals[MAX_LEN / THREAD_DIM]; + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_VEC_DISTANCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp index cc22ddbbe4..80b1303681 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_math.hpp @@ -1,923 +1,923 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_VECMATH_HPP -#define OPENCV_CUDA_VECMATH_HPP - -#include "vec_traits.hpp" -#include "saturate_cast.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - -// saturate_cast - -namespace vec_math_detail -{ - template struct SatCastHelper; - template struct SatCastHelper<1, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x)); - } - }; - template struct SatCastHelper<2, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y)); - } - }; - template struct SatCastHelper<3, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z)); - } - }; - template struct SatCastHelper<4, VecD> - { - template static __device__ __forceinline__ VecD cast(const VecS& v) - { - typedef typename VecTraits::elem_type D; - return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z), saturate_cast(v.w)); - } - }; - - template static __device__ __forceinline__ VecD saturate_cast_helper(const VecS& v) - { - return SatCastHelper::cn, VecD>::cast(v); - } -} - -template static __device__ __forceinline__ T saturate_cast(const uchar1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float1& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double1& v) {return vec_math_detail::saturate_cast_helper(v);} - -template static __device__ __forceinline__ T saturate_cast(const uchar2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float2& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double2& v) {return vec_math_detail::saturate_cast_helper(v);} - -template static __device__ __forceinline__ T saturate_cast(const uchar3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float3& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double3& v) {return vec_math_detail::saturate_cast_helper(v);} - -template static __device__ __forceinline__ T saturate_cast(const uchar4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const char4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const ushort4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const short4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const uint4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const int4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const float4& v) {return vec_math_detail::saturate_cast_helper(v);} -template static __device__ __forceinline__ T saturate_cast(const double4& v) {return vec_math_detail::saturate_cast_helper(v);} - -// unary operators - -#define CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(op, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a) \ - { \ - return VecTraits::make(op (a.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a) \ - { \ - return VecTraits::make(op (a.x), op (a.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a) \ - { \ - return VecTraits::make(op (a.x), op (a.y), op (a.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a) \ - { \ - return VecTraits::make(op (a.x), op (a.y), op (a.z), op (a.w)); \ - } - -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, char, char) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, short, short) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, int, int) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, char, char) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, short, short) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, int, int) -CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uint, uint) - -#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_OP - -// unary functions - -#define CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(func_name, func, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a) \ - { \ - return VecTraits::make(func (a.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a) \ - { \ - return VecTraits::make(func (a.x), func (a.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a) \ - { \ - return VecTraits::make(func (a.x), func (a.y), func (a.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a) \ - { \ - return VecTraits::make(func (a.x), func (a.y), func (a.z), func (a.w)); \ - } - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabsf, float, float) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrt, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::exp, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::log, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sin, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cos, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tan, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asin, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acos, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atan, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::cosh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acosh, double, double) - -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, char, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, short, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, int, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, float, float) -CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanh, double, double) - -#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC - -// binary operators (vec & vec) - -#define CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(op, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, const input_type ## 1 & b) \ - { \ - return VecTraits::make(a.x op b.x); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, const input_type ## 2 & b) \ - { \ - return VecTraits::make(a.x op b.x, a.y op b.y); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, const input_type ## 3 & b) \ - { \ - return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, const input_type ## 4 & b) \ - { \ - return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z, a.w op b.w); \ - } - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uchar, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, char, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, ushort, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, short, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, char, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, ushort, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, short, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, int, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uint, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, float, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, double, uchar) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uint, uint) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uint, uint) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uint, uint) - -#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_OP - -// binary operators (vec & scalar) - -#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(op, input_type, scalar_type, output_type) \ - __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s); \ - } \ - __device__ __forceinline__ output_type ## 1 operator op(scalar_type s, const input_type ## 1 & b) \ - { \ - return VecTraits::make(s op b.x); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s, a.y op s); \ - } \ - __device__ __forceinline__ output_type ## 2 operator op(scalar_type s, const input_type ## 2 & b) \ - { \ - return VecTraits::make(s op b.x, s op b.y); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s, a.y op s, a.z op s); \ - } \ - __device__ __forceinline__ output_type ## 3 operator op(scalar_type s, const input_type ## 3 & b) \ - { \ - return VecTraits::make(s op b.x, s op b.y, s op b.z); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, scalar_type s) \ - { \ - return VecTraits::make(a.x op s, a.y op s, a.z op s, a.w op s); \ - } \ - __device__ __forceinline__ output_type ## 4 operator op(scalar_type s, const input_type ## 4 & b) \ - { \ - return VecTraits::make(s op b.x, s op b.y, s op b.z, s op b.w); \ - } - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, char, char, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, ushort, ushort, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, short, short, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, int, int, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uint, uint, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, float, float, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, double, double, uchar) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uint, uint, uint) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uint, uint, uint) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uint, uint, uint) - -#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP - -// binary function (vec & vec) - -#define CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(func_name, func, input_type, output_type) \ - __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, const input_type ## 1 & b) \ - { \ - return VecTraits::make(func (a.x, b.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, const input_type ## 2 & b) \ - { \ - return VecTraits::make(func (a.x, b.x), func (a.y, b.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, const input_type ## 3 & b) \ - { \ - return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, const input_type ## 4 & b) \ - { \ - return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z), func (a.w, b.w)); \ - } - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmaxf, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmax, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uchar, uchar) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, char, char) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, ushort, ushort) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, short, short) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uint, uint) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, int, int) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fminf, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fmin, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, char, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, short, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uint, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, int, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypot, double, double) - -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uchar, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, char, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, ushort, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, short, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uint, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, int, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, float, float) -CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2, double, double) - -#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC - -// binary function (vec & scalar) - -#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(func_name, func, input_type, scalar_type, output_type) \ - __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 1 func_name(scalar_type s, const input_type ## 1 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 2 func_name(scalar_type s, const input_type ## 2 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 3 func_name(scalar_type s, const input_type ## 3 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, scalar_type s) \ - { \ - return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s), func ((output_type) a.w, (output_type) s)); \ - } \ - __device__ __forceinline__ output_type ## 4 func_name(scalar_type s, const input_type ## 4 & b) \ - { \ - return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z), func ((output_type) s, (output_type) b.w)); \ - } - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uchar, uchar, uchar) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, char, char, char) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, ushort, ushort, ushort) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, short, short, short) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uint, uint, uint) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, int, int, int) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, double, double, double) - -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uchar, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uchar, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, char, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, char, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, ushort, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, ushort, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, short, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, short, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uint, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uint, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, int, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, int, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, float, float, float) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, float, double, double) -CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, double, double, double) - -#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC - -}}} // namespace cv { namespace cuda { namespace device - -//! @endcond - -#endif // OPENCV_CUDA_VECMATH_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_VECMATH_HPP +#define OPENCV_CUDA_VECMATH_HPP + +#include "vec_traits.hpp" +#include "saturate_cast.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + +// saturate_cast + +namespace vec_math_detail +{ + template struct SatCastHelper; + template struct SatCastHelper<1, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x)); + } + }; + template struct SatCastHelper<2, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y)); + } + }; + template struct SatCastHelper<3, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z)); + } + }; + template struct SatCastHelper<4, VecD> + { + template static __device__ __forceinline__ VecD cast(const VecS& v) + { + typedef typename VecTraits::elem_type D; + return VecTraits::make(saturate_cast(v.x), saturate_cast(v.y), saturate_cast(v.z), saturate_cast(v.w)); + } + }; + + template static __device__ __forceinline__ VecD saturate_cast_helper(const VecS& v) + { + return SatCastHelper::cn, VecD>::cast(v); + } +} + +template static __device__ __forceinline__ T saturate_cast(const uchar1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float1& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double1& v) {return vec_math_detail::saturate_cast_helper(v);} + +template static __device__ __forceinline__ T saturate_cast(const uchar2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float2& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double2& v) {return vec_math_detail::saturate_cast_helper(v);} + +template static __device__ __forceinline__ T saturate_cast(const uchar3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float3& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double3& v) {return vec_math_detail::saturate_cast_helper(v);} + +template static __device__ __forceinline__ T saturate_cast(const uchar4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const char4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const ushort4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const short4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const uint4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const int4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const float4& v) {return vec_math_detail::saturate_cast_helper(v);} +template static __device__ __forceinline__ T saturate_cast(const double4& v) {return vec_math_detail::saturate_cast_helper(v);} + +// unary operators + +#define CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(op, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a) \ + { \ + return VecTraits::make(op (a.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a) \ + { \ + return VecTraits::make(op (a.x), op (a.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a) \ + { \ + return VecTraits::make(op (a.x), op (a.y), op (a.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a) \ + { \ + return VecTraits::make(op (a.x), op (a.y), op (a.z), op (a.w)); \ + } + +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, char, char) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, short, short) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, int, int) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(-, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(!, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, char, char) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, short, short) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, int, int) +CV_CUDEV_IMPLEMENT_VEC_UNARY_OP(~, uint, uint) + +#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_OP + +// unary functions + +#define CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(func_name, func, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a) \ + { \ + return VecTraits::make(func (a.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a) \ + { \ + return VecTraits::make(func (a.x), func (a.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a) \ + { \ + return VecTraits::make(func (a.x), func (a.y), func (a.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a) \ + { \ + return VecTraits::make(func (a.x), func (a.y), func (a.z), func (a.w)); \ + } + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(abs, ::fabsf, float, float) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrtf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sqrt, ::sqrt, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::expf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp, ::exp, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp2, ::exp2, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(exp10, ::exp10, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::logf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log, ::log, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log2, ::log2, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10f, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(log10, ::log10, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sinf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sin, ::sin, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cosf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cos, ::cos, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tanf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tan, ::tan, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asinf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asin, ::asin, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acosf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acos, ::acos, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atanf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atan, ::atan, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(sinh, ::sinh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::coshf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(cosh, ::cosh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(tanh, ::tanh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(asinh, ::asinh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acoshf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(acosh, ::acosh, double, double) + +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, char, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, short, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, int, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanhf, float, float) +CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC(atanh, ::atanh, double, double) + +#undef CV_CUDEV_IMPLEMENT_VEC_UNARY_FUNC + +// binary operators (vec & vec) + +#define CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(op, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, const input_type ## 1 & b) \ + { \ + return VecTraits::make(a.x op b.x); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, const input_type ## 2 & b) \ + { \ + return VecTraits::make(a.x op b.x, a.y op b.y); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, const input_type ## 3 & b) \ + { \ + return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, const input_type ## 4 & b) \ + { \ + return VecTraits::make(a.x op b.x, a.y op b.y, a.z op b.z, a.w op b.w); \ + } + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(+, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(-, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(*, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uchar, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, char, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, ushort, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, short, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(/, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(==, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(!=, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(>=, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(<=, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&&, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, char, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, ushort, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, short, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, int, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, uint, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, float, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(||, double, uchar) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(&, uint, uint) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(|, uint, uint) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_OP(^, uint, uint) + +#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_OP + +// binary operators (vec & scalar) + +#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(op, input_type, scalar_type, output_type) \ + __device__ __forceinline__ output_type ## 1 operator op(const input_type ## 1 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s); \ + } \ + __device__ __forceinline__ output_type ## 1 operator op(scalar_type s, const input_type ## 1 & b) \ + { \ + return VecTraits::make(s op b.x); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(const input_type ## 2 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s, a.y op s); \ + } \ + __device__ __forceinline__ output_type ## 2 operator op(scalar_type s, const input_type ## 2 & b) \ + { \ + return VecTraits::make(s op b.x, s op b.y); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(const input_type ## 3 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s, a.y op s, a.z op s); \ + } \ + __device__ __forceinline__ output_type ## 3 operator op(scalar_type s, const input_type ## 3 & b) \ + { \ + return VecTraits::make(s op b.x, s op b.y, s op b.z); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(const input_type ## 4 & a, scalar_type s) \ + { \ + return VecTraits::make(a.x op s, a.y op s, a.z op s, a.w op s); \ + } \ + __device__ __forceinline__ output_type ## 4 operator op(scalar_type s, const input_type ## 4 & b) \ + { \ + return VecTraits::make(s op b.x, s op b.y, s op b.z, s op b.w); \ + } + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(+, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(-, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(*, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(/, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(==, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(!=, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(>=, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(<=, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&&, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, char, char, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, ushort, ushort, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, short, short, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, int, int, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, uint, uint, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, float, float, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(||, double, double, uchar) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(&, uint, uint, uint) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(|, uint, uint, uint) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP(^, uint, uint, uint) + +#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_OP + +// binary function (vec & vec) + +#define CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(func_name, func, input_type, output_type) \ + __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, const input_type ## 1 & b) \ + { \ + return VecTraits::make(func (a.x, b.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, const input_type ## 2 & b) \ + { \ + return VecTraits::make(func (a.x, b.x), func (a.y, b.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, const input_type ## 3 & b) \ + { \ + return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, const input_type ## 4 & b) \ + { \ + return VecTraits::make(func (a.x, b.x), func (a.y, b.y), func (a.z, b.z), func (a.w, b.w)); \ + } + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::max, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmaxf, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(max, ::fmax, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uchar, uchar) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, char, char) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, ushort, ushort) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, short, short) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, uint, uint) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::min, int, int) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fminf, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(min, ::fmin, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, char, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, short, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, uint, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, int, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypotf, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(hypot, ::hypot, double, double) + +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uchar, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, char, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, ushort, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, short, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, uint, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, int, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2f, float, float) +CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC(atan2, ::atan2, double, double) + +#undef CV_CUDEV_IMPLEMENT_VEC_BINARY_FUNC + +// binary function (vec & scalar) + +#define CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(func_name, func, input_type, scalar_type, output_type) \ + __device__ __forceinline__ output_type ## 1 func_name(const input_type ## 1 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 1 func_name(scalar_type s, const input_type ## 1 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(const input_type ## 2 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 2 func_name(scalar_type s, const input_type ## 2 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(const input_type ## 3 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 3 func_name(scalar_type s, const input_type ## 3 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(const input_type ## 4 & a, scalar_type s) \ + { \ + return VecTraits::make(func ((output_type) a.x, (output_type) s), func ((output_type) a.y, (output_type) s), func ((output_type) a.z, (output_type) s), func ((output_type) a.w, (output_type) s)); \ + } \ + __device__ __forceinline__ output_type ## 4 func_name(scalar_type s, const input_type ## 4 & b) \ + { \ + return VecTraits::make(func ((output_type) s, (output_type) b.x), func ((output_type) s, (output_type) b.y), func ((output_type) s, (output_type) b.z), func ((output_type) s, (output_type) b.w)); \ + } + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::max, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmaxf, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(max, ::fmax, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uchar, uchar, uchar) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, char, char, char) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, ushort, ushort, ushort) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, short, short, short) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, uint, uint, uint) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::min, int, int, int) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fminf, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(min, ::fmin, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypotf, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(hypot, ::hypot, double, double, double) + +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uchar, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uchar, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, char, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, char, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, ushort, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, ushort, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, short, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, short, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, uint, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, uint, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, int, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, int, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2f, float, float, float) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, float, double, double) +CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC(atan2, ::atan2, double, double, double) + +#undef CV_CUDEV_IMPLEMENT_SCALAR_BINARY_FUNC + +}}} // namespace cv { namespace cuda { namespace device + +//! @endcond + +#endif // OPENCV_CUDA_VECMATH_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp index 582187210d..b5ff281a0b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/vec_traits.hpp @@ -1,288 +1,288 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_VEC_TRAITS_HPP -#define OPENCV_CUDA_VEC_TRAITS_HPP - -#include "common.hpp" - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template struct TypeVec; - - struct __align__(8) uchar8 - { - uchar a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ uchar8 make_uchar8(uchar a0, uchar a1, uchar a2, uchar a3, uchar a4, uchar a5, uchar a6, uchar a7) - { - uchar8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(8) char8 - { - schar a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ char8 make_char8(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) - { - char8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(16) ushort8 - { - ushort a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ ushort8 make_ushort8(ushort a0, ushort a1, ushort a2, ushort a3, ushort a4, ushort a5, ushort a6, ushort a7) - { - ushort8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(16) short8 - { - short a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ short8 make_short8(short a0, short a1, short a2, short a3, short a4, short a5, short a6, short a7) - { - short8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(32) uint8 - { - uint a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ uint8 make_uint8(uint a0, uint a1, uint a2, uint a3, uint a4, uint a5, uint a6, uint a7) - { - uint8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(32) int8 - { - int a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ int8 make_int8(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7) - { - int8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct __align__(32) float8 - { - float a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ float8 make_float8(float a0, float a1, float a2, float a3, float a4, float a5, float a6, float a7) - { - float8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - struct double8 - { - double a0, a1, a2, a3, a4, a5, a6, a7; - }; - static __host__ __device__ __forceinline__ double8 make_double8(double a0, double a1, double a2, double a3, double a4, double a5, double a6, double a7) - { - double8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; - return val; - } - -#define OPENCV_CUDA_IMPLEMENT_TYPE_VEC(type) \ - template<> struct TypeVec { typedef type vec_type; }; \ - template<> struct TypeVec { typedef type ## 1 vec_type; }; \ - template<> struct TypeVec { typedef type ## 2 vec_type; }; \ - template<> struct TypeVec { typedef type ## 2 vec_type; }; \ - template<> struct TypeVec { typedef type ## 3 vec_type; }; \ - template<> struct TypeVec { typedef type ## 3 vec_type; }; \ - template<> struct TypeVec { typedef type ## 4 vec_type; }; \ - template<> struct TypeVec { typedef type ## 4 vec_type; }; \ - template<> struct TypeVec { typedef type ## 8 vec_type; }; \ - template<> struct TypeVec { typedef type ## 8 vec_type; }; - - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uchar) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(char) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(ushort) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(short) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(int) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uint) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(float) - OPENCV_CUDA_IMPLEMENT_TYPE_VEC(double) - - #undef OPENCV_CUDA_IMPLEMENT_TYPE_VEC - - template<> struct TypeVec { typedef schar vec_type; }; - template<> struct TypeVec { typedef char2 vec_type; }; - template<> struct TypeVec { typedef char3 vec_type; }; - template<> struct TypeVec { typedef char4 vec_type; }; - template<> struct TypeVec { typedef char8 vec_type; }; - - template<> struct TypeVec { typedef uchar vec_type; }; - template<> struct TypeVec { typedef uchar2 vec_type; }; - template<> struct TypeVec { typedef uchar3 vec_type; }; - template<> struct TypeVec { typedef uchar4 vec_type; }; - template<> struct TypeVec { typedef uchar8 vec_type; }; - - template struct VecTraits; - -#define OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(type) \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=1}; \ - static __device__ __host__ __forceinline__ type all(type v) {return v;} \ - static __device__ __host__ __forceinline__ type make(type x) {return x;} \ - static __device__ __host__ __forceinline__ type make(const type* v) {return *v;} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=1}; \ - static __device__ __host__ __forceinline__ type ## 1 all(type v) {return make_ ## type ## 1(v);} \ - static __device__ __host__ __forceinline__ type ## 1 make(type x) {return make_ ## type ## 1(x);} \ - static __device__ __host__ __forceinline__ type ## 1 make(const type* v) {return make_ ## type ## 1(*v);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=2}; \ - static __device__ __host__ __forceinline__ type ## 2 all(type v) {return make_ ## type ## 2(v, v);} \ - static __device__ __host__ __forceinline__ type ## 2 make(type x, type y) {return make_ ## type ## 2(x, y);} \ - static __device__ __host__ __forceinline__ type ## 2 make(const type* v) {return make_ ## type ## 2(v[0], v[1]);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=3}; \ - static __device__ __host__ __forceinline__ type ## 3 all(type v) {return make_ ## type ## 3(v, v, v);} \ - static __device__ __host__ __forceinline__ type ## 3 make(type x, type y, type z) {return make_ ## type ## 3(x, y, z);} \ - static __device__ __host__ __forceinline__ type ## 3 make(const type* v) {return make_ ## type ## 3(v[0], v[1], v[2]);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=4}; \ - static __device__ __host__ __forceinline__ type ## 4 all(type v) {return make_ ## type ## 4(v, v, v, v);} \ - static __device__ __host__ __forceinline__ type ## 4 make(type x, type y, type z, type w) {return make_ ## type ## 4(x, y, z, w);} \ - static __device__ __host__ __forceinline__ type ## 4 make(const type* v) {return make_ ## type ## 4(v[0], v[1], v[2], v[3]);} \ - }; \ - template<> struct VecTraits \ - { \ - typedef type elem_type; \ - enum {cn=8}; \ - static __device__ __host__ __forceinline__ type ## 8 all(type v) {return make_ ## type ## 8(v, v, v, v, v, v, v, v);} \ - static __device__ __host__ __forceinline__ type ## 8 make(type a0, type a1, type a2, type a3, type a4, type a5, type a6, type a7) {return make_ ## type ## 8(a0, a1, a2, a3, a4, a5, a6, a7);} \ - static __device__ __host__ __forceinline__ type ## 8 make(const type* v) {return make_ ## type ## 8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} \ - }; - - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uchar) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(ushort) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(short) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(int) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uint) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(float) - OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(double) - - #undef OPENCV_CUDA_IMPLEMENT_VEC_TRAITS - - template<> struct VecTraits - { - typedef char elem_type; - enum {cn=1}; - static __device__ __host__ __forceinline__ char all(char v) {return v;} - static __device__ __host__ __forceinline__ char make(char x) {return x;} - static __device__ __host__ __forceinline__ char make(const char* x) {return *x;} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=1}; - static __device__ __host__ __forceinline__ schar all(schar v) {return v;} - static __device__ __host__ __forceinline__ schar make(schar x) {return x;} - static __device__ __host__ __forceinline__ schar make(const schar* x) {return *x;} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=1}; - static __device__ __host__ __forceinline__ char1 all(schar v) {return make_char1(v);} - static __device__ __host__ __forceinline__ char1 make(schar x) {return make_char1(x);} - static __device__ __host__ __forceinline__ char1 make(const schar* v) {return make_char1(v[0]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=2}; - static __device__ __host__ __forceinline__ char2 all(schar v) {return make_char2(v, v);} - static __device__ __host__ __forceinline__ char2 make(schar x, schar y) {return make_char2(x, y);} - static __device__ __host__ __forceinline__ char2 make(const schar* v) {return make_char2(v[0], v[1]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=3}; - static __device__ __host__ __forceinline__ char3 all(schar v) {return make_char3(v, v, v);} - static __device__ __host__ __forceinline__ char3 make(schar x, schar y, schar z) {return make_char3(x, y, z);} - static __device__ __host__ __forceinline__ char3 make(const schar* v) {return make_char3(v[0], v[1], v[2]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=4}; - static __device__ __host__ __forceinline__ char4 all(schar v) {return make_char4(v, v, v, v);} - static __device__ __host__ __forceinline__ char4 make(schar x, schar y, schar z, schar w) {return make_char4(x, y, z, w);} - static __device__ __host__ __forceinline__ char4 make(const schar* v) {return make_char4(v[0], v[1], v[2], v[3]);} - }; - template<> struct VecTraits - { - typedef schar elem_type; - enum {cn=8}; - static __device__ __host__ __forceinline__ char8 all(schar v) {return make_char8(v, v, v, v, v, v, v, v);} - static __device__ __host__ __forceinline__ char8 make(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) {return make_char8(a0, a1, a2, a3, a4, a5, a6, a7);} - static __device__ __host__ __forceinline__ char8 make(const schar* v) {return make_char8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif // OPENCV_CUDA_VEC_TRAITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_VEC_TRAITS_HPP +#define OPENCV_CUDA_VEC_TRAITS_HPP + +#include "common.hpp" + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template struct TypeVec; + + struct __align__(8) uchar8 + { + uchar a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ uchar8 make_uchar8(uchar a0, uchar a1, uchar a2, uchar a3, uchar a4, uchar a5, uchar a6, uchar a7) + { + uchar8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(8) char8 + { + schar a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ char8 make_char8(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) + { + char8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(16) ushort8 + { + ushort a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ ushort8 make_ushort8(ushort a0, ushort a1, ushort a2, ushort a3, ushort a4, ushort a5, ushort a6, ushort a7) + { + ushort8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(16) short8 + { + short a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ short8 make_short8(short a0, short a1, short a2, short a3, short a4, short a5, short a6, short a7) + { + short8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(32) uint8 + { + uint a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ uint8 make_uint8(uint a0, uint a1, uint a2, uint a3, uint a4, uint a5, uint a6, uint a7) + { + uint8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(32) int8 + { + int a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ int8 make_int8(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7) + { + int8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct __align__(32) float8 + { + float a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ float8 make_float8(float a0, float a1, float a2, float a3, float a4, float a5, float a6, float a7) + { + float8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + struct double8 + { + double a0, a1, a2, a3, a4, a5, a6, a7; + }; + static __host__ __device__ __forceinline__ double8 make_double8(double a0, double a1, double a2, double a3, double a4, double a5, double a6, double a7) + { + double8 val = {a0, a1, a2, a3, a4, a5, a6, a7}; + return val; + } + +#define OPENCV_CUDA_IMPLEMENT_TYPE_VEC(type) \ + template<> struct TypeVec { typedef type vec_type; }; \ + template<> struct TypeVec { typedef type ## 1 vec_type; }; \ + template<> struct TypeVec { typedef type ## 2 vec_type; }; \ + template<> struct TypeVec { typedef type ## 2 vec_type; }; \ + template<> struct TypeVec { typedef type ## 3 vec_type; }; \ + template<> struct TypeVec { typedef type ## 3 vec_type; }; \ + template<> struct TypeVec { typedef type ## 4 vec_type; }; \ + template<> struct TypeVec { typedef type ## 4 vec_type; }; \ + template<> struct TypeVec { typedef type ## 8 vec_type; }; \ + template<> struct TypeVec { typedef type ## 8 vec_type; }; + + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uchar) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(char) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(ushort) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(short) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(int) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(uint) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(float) + OPENCV_CUDA_IMPLEMENT_TYPE_VEC(double) + + #undef OPENCV_CUDA_IMPLEMENT_TYPE_VEC + + template<> struct TypeVec { typedef schar vec_type; }; + template<> struct TypeVec { typedef char2 vec_type; }; + template<> struct TypeVec { typedef char3 vec_type; }; + template<> struct TypeVec { typedef char4 vec_type; }; + template<> struct TypeVec { typedef char8 vec_type; }; + + template<> struct TypeVec { typedef uchar vec_type; }; + template<> struct TypeVec { typedef uchar2 vec_type; }; + template<> struct TypeVec { typedef uchar3 vec_type; }; + template<> struct TypeVec { typedef uchar4 vec_type; }; + template<> struct TypeVec { typedef uchar8 vec_type; }; + + template struct VecTraits; + +#define OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(type) \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=1}; \ + static __device__ __host__ __forceinline__ type all(type v) {return v;} \ + static __device__ __host__ __forceinline__ type make(type x) {return x;} \ + static __device__ __host__ __forceinline__ type make(const type* v) {return *v;} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=1}; \ + static __device__ __host__ __forceinline__ type ## 1 all(type v) {return make_ ## type ## 1(v);} \ + static __device__ __host__ __forceinline__ type ## 1 make(type x) {return make_ ## type ## 1(x);} \ + static __device__ __host__ __forceinline__ type ## 1 make(const type* v) {return make_ ## type ## 1(*v);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=2}; \ + static __device__ __host__ __forceinline__ type ## 2 all(type v) {return make_ ## type ## 2(v, v);} \ + static __device__ __host__ __forceinline__ type ## 2 make(type x, type y) {return make_ ## type ## 2(x, y);} \ + static __device__ __host__ __forceinline__ type ## 2 make(const type* v) {return make_ ## type ## 2(v[0], v[1]);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=3}; \ + static __device__ __host__ __forceinline__ type ## 3 all(type v) {return make_ ## type ## 3(v, v, v);} \ + static __device__ __host__ __forceinline__ type ## 3 make(type x, type y, type z) {return make_ ## type ## 3(x, y, z);} \ + static __device__ __host__ __forceinline__ type ## 3 make(const type* v) {return make_ ## type ## 3(v[0], v[1], v[2]);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=4}; \ + static __device__ __host__ __forceinline__ type ## 4 all(type v) {return make_ ## type ## 4(v, v, v, v);} \ + static __device__ __host__ __forceinline__ type ## 4 make(type x, type y, type z, type w) {return make_ ## type ## 4(x, y, z, w);} \ + static __device__ __host__ __forceinline__ type ## 4 make(const type* v) {return make_ ## type ## 4(v[0], v[1], v[2], v[3]);} \ + }; \ + template<> struct VecTraits \ + { \ + typedef type elem_type; \ + enum {cn=8}; \ + static __device__ __host__ __forceinline__ type ## 8 all(type v) {return make_ ## type ## 8(v, v, v, v, v, v, v, v);} \ + static __device__ __host__ __forceinline__ type ## 8 make(type a0, type a1, type a2, type a3, type a4, type a5, type a6, type a7) {return make_ ## type ## 8(a0, a1, a2, a3, a4, a5, a6, a7);} \ + static __device__ __host__ __forceinline__ type ## 8 make(const type* v) {return make_ ## type ## 8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} \ + }; + + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uchar) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(ushort) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(short) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(int) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(uint) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(float) + OPENCV_CUDA_IMPLEMENT_VEC_TRAITS(double) + + #undef OPENCV_CUDA_IMPLEMENT_VEC_TRAITS + + template<> struct VecTraits + { + typedef char elem_type; + enum {cn=1}; + static __device__ __host__ __forceinline__ char all(char v) {return v;} + static __device__ __host__ __forceinline__ char make(char x) {return x;} + static __device__ __host__ __forceinline__ char make(const char* x) {return *x;} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=1}; + static __device__ __host__ __forceinline__ schar all(schar v) {return v;} + static __device__ __host__ __forceinline__ schar make(schar x) {return x;} + static __device__ __host__ __forceinline__ schar make(const schar* x) {return *x;} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=1}; + static __device__ __host__ __forceinline__ char1 all(schar v) {return make_char1(v);} + static __device__ __host__ __forceinline__ char1 make(schar x) {return make_char1(x);} + static __device__ __host__ __forceinline__ char1 make(const schar* v) {return make_char1(v[0]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=2}; + static __device__ __host__ __forceinline__ char2 all(schar v) {return make_char2(v, v);} + static __device__ __host__ __forceinline__ char2 make(schar x, schar y) {return make_char2(x, y);} + static __device__ __host__ __forceinline__ char2 make(const schar* v) {return make_char2(v[0], v[1]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=3}; + static __device__ __host__ __forceinline__ char3 all(schar v) {return make_char3(v, v, v);} + static __device__ __host__ __forceinline__ char3 make(schar x, schar y, schar z) {return make_char3(x, y, z);} + static __device__ __host__ __forceinline__ char3 make(const schar* v) {return make_char3(v[0], v[1], v[2]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=4}; + static __device__ __host__ __forceinline__ char4 all(schar v) {return make_char4(v, v, v, v);} + static __device__ __host__ __forceinline__ char4 make(schar x, schar y, schar z, schar w) {return make_char4(x, y, z, w);} + static __device__ __host__ __forceinline__ char4 make(const schar* v) {return make_char4(v[0], v[1], v[2], v[3]);} + }; + template<> struct VecTraits + { + typedef schar elem_type; + enum {cn=8}; + static __device__ __host__ __forceinline__ char8 all(schar v) {return make_char8(v, v, v, v, v, v, v, v);} + static __device__ __host__ __forceinline__ char8 make(schar a0, schar a1, schar a2, schar a3, schar a4, schar a5, schar a6, schar a7) {return make_char8(a0, a1, a2, a3, a4, a5, a6, a7);} + static __device__ __host__ __forceinline__ char8 make(const schar* v) {return make_char8(v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]);} + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif // OPENCV_CUDA_VEC_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp index 58e2c324c8..8af7e6a212 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp.hpp @@ -1,139 +1,139 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_DEVICE_WARP_HPP -#define OPENCV_CUDA_DEVICE_WARP_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - struct Warp - { - enum - { - LOG_WARP_SIZE = 5, - WARP_SIZE = 1 << LOG_WARP_SIZE, - STRIDE = WARP_SIZE - }; - - /** \brief Returns the warp lane ID of the calling thread. */ - static __device__ __forceinline__ unsigned int laneId() - { - unsigned int ret; - asm("mov.u32 %0, %%laneid;" : "=r"(ret) ); - return ret; - } - - template - static __device__ __forceinline__ void fill(It beg, It end, const T& value) - { - for(It t = beg + laneId(); t < end; t += STRIDE) - *t = value; - } - - template - static __device__ __forceinline__ OutIt copy(InIt beg, InIt end, OutIt out) - { - for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) - *out = *t; - return out; - } - - template - static __device__ __forceinline__ OutIt transform(InIt beg, InIt end, OutIt out, UnOp op) - { - for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) - *out = op(*t); - return out; - } - - template - static __device__ __forceinline__ OutIt transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) - { - unsigned int lane = laneId(); - - InIt1 t1 = beg1 + lane; - InIt2 t2 = beg2 + lane; - for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, out += STRIDE) - *out = op(*t1, *t2); - return out; - } - - template - static __device__ __forceinline__ T reduce(volatile T *ptr, BinOp op) - { - const unsigned int lane = laneId(); - - if (lane < 16) - { - T partial = ptr[lane]; - - ptr[lane] = partial = op(partial, ptr[lane + 16]); - ptr[lane] = partial = op(partial, ptr[lane + 8]); - ptr[lane] = partial = op(partial, ptr[lane + 4]); - ptr[lane] = partial = op(partial, ptr[lane + 2]); - ptr[lane] = partial = op(partial, ptr[lane + 1]); - } - - return *ptr; - } - - template - static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) - { - unsigned int lane = laneId(); - value += lane; - - for(OutIt t = beg + lane; t < end; t += STRIDE, value += STRIDE) - *t = value; - } - }; -}}} // namespace cv { namespace cuda { namespace cudev - -//! @endcond - -#endif /* OPENCV_CUDA_DEVICE_WARP_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_DEVICE_WARP_HPP +#define OPENCV_CUDA_DEVICE_WARP_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + struct Warp + { + enum + { + LOG_WARP_SIZE = 5, + WARP_SIZE = 1 << LOG_WARP_SIZE, + STRIDE = WARP_SIZE + }; + + /** \brief Returns the warp lane ID of the calling thread. */ + static __device__ __forceinline__ unsigned int laneId() + { + unsigned int ret; + asm("mov.u32 %0, %%laneid;" : "=r"(ret) ); + return ret; + } + + template + static __device__ __forceinline__ void fill(It beg, It end, const T& value) + { + for(It t = beg + laneId(); t < end; t += STRIDE) + *t = value; + } + + template + static __device__ __forceinline__ OutIt copy(InIt beg, InIt end, OutIt out) + { + for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) + *out = *t; + return out; + } + + template + static __device__ __forceinline__ OutIt transform(InIt beg, InIt end, OutIt out, UnOp op) + { + for(InIt t = beg + laneId(); t < end; t += STRIDE, out += STRIDE) + *out = op(*t); + return out; + } + + template + static __device__ __forceinline__ OutIt transform(InIt1 beg1, InIt1 end1, InIt2 beg2, OutIt out, BinOp op) + { + unsigned int lane = laneId(); + + InIt1 t1 = beg1 + lane; + InIt2 t2 = beg2 + lane; + for(; t1 < end1; t1 += STRIDE, t2 += STRIDE, out += STRIDE) + *out = op(*t1, *t2); + return out; + } + + template + static __device__ __forceinline__ T reduce(volatile T *ptr, BinOp op) + { + const unsigned int lane = laneId(); + + if (lane < 16) + { + T partial = ptr[lane]; + + ptr[lane] = partial = op(partial, ptr[lane + 16]); + ptr[lane] = partial = op(partial, ptr[lane + 8]); + ptr[lane] = partial = op(partial, ptr[lane + 4]); + ptr[lane] = partial = op(partial, ptr[lane + 2]); + ptr[lane] = partial = op(partial, ptr[lane + 1]); + } + + return *ptr; + } + + template + static __device__ __forceinline__ void yota(OutIt beg, OutIt end, T value) + { + unsigned int lane = laneId(); + value += lane; + + for(OutIt t = beg + lane; t < end; t += STRIDE, value += STRIDE) + *t = value; + } + }; +}}} // namespace cv { namespace cuda { namespace cudev + +//! @endcond + +#endif /* OPENCV_CUDA_DEVICE_WARP_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp index ee5c7ab645..530303d249 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_reduce.hpp @@ -1,76 +1,76 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_WARP_REDUCE_HPP__ -#define OPENCV_CUDA_WARP_REDUCE_HPP__ - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ - template - __device__ __forceinline__ T warp_reduce(volatile T *ptr , const unsigned int tid = threadIdx.x) - { - const unsigned int lane = tid & 31; // index of thread in warp (0..31) - - if (lane < 16) - { - T partial = ptr[tid]; - - ptr[tid] = partial = partial + ptr[tid + 16]; - ptr[tid] = partial = partial + ptr[tid + 8]; - ptr[tid] = partial = partial + ptr[tid + 4]; - ptr[tid] = partial = partial + ptr[tid + 2]; - ptr[tid] = partial = partial + ptr[tid + 1]; - } - - return ptr[tid - lane]; - } -}}} // namespace cv { namespace cuda { namespace cudev { - -//! @endcond - -#endif /* OPENCV_CUDA_WARP_REDUCE_HPP__ */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_WARP_REDUCE_HPP__ +#define OPENCV_CUDA_WARP_REDUCE_HPP__ + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ + template + __device__ __forceinline__ T warp_reduce(volatile T *ptr , const unsigned int tid = threadIdx.x) + { + const unsigned int lane = tid & 31; // index of thread in warp (0..31) + + if (lane < 16) + { + T partial = ptr[tid]; + + ptr[tid] = partial = partial + ptr[tid + 16]; + ptr[tid] = partial = partial + ptr[tid + 8]; + ptr[tid] = partial = partial + ptr[tid + 4]; + ptr[tid] = partial = partial + ptr[tid + 2]; + ptr[tid] = partial = partial + ptr[tid + 1]; + } + + return ptr[tid - lane]; + } +}}} // namespace cv { namespace cuda { namespace cudev { + +//! @endcond + +#endif /* OPENCV_CUDA_WARP_REDUCE_HPP__ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp index e61df5fdc6..0da54aee99 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda/warp_shuffle.hpp @@ -1,162 +1,162 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CUDA_WARP_SHUFFLE_HPP -#define OPENCV_CUDA_WARP_SHUFFLE_HPP - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -namespace cv { namespace cuda { namespace device -{ -#if __CUDACC_VER_MAJOR__ >= 9 -# define __shfl(x, y, z) __shfl_sync(0xFFFFFFFFU, x, y, z) -# define __shfl_up(x, y, z) __shfl_up_sync(0xFFFFFFFFU, x, y, z) -# define __shfl_down(x, y, z) __shfl_down_sync(0xFFFFFFFFU, x, y, z) -#endif - template - __device__ __forceinline__ T shfl(T val, int srcLane, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return __shfl(val, srcLane, width); - #else - return T(); - #endif - } - __device__ __forceinline__ unsigned int shfl(unsigned int val, int srcLane, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return (unsigned int) __shfl((int) val, srcLane, width); - #else - return 0; - #endif - } - __device__ __forceinline__ double shfl(double val, int srcLane, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - int lo = __double2loint(val); - int hi = __double2hiint(val); - - lo = __shfl(lo, srcLane, width); - hi = __shfl(hi, srcLane, width); - - return __hiloint2double(hi, lo); - #else - return 0.0; - #endif - } - - template - __device__ __forceinline__ T shfl_down(T val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return __shfl_down(val, delta, width); - #else - return T(); - #endif - } - __device__ __forceinline__ unsigned int shfl_down(unsigned int val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return (unsigned int) __shfl_down((int) val, delta, width); - #else - return 0; - #endif - } - __device__ __forceinline__ double shfl_down(double val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - int lo = __double2loint(val); - int hi = __double2hiint(val); - - lo = __shfl_down(lo, delta, width); - hi = __shfl_down(hi, delta, width); - - return __hiloint2double(hi, lo); - #else - return 0.0; - #endif - } - - template - __device__ __forceinline__ T shfl_up(T val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return __shfl_up(val, delta, width); - #else - return T(); - #endif - } - __device__ __forceinline__ unsigned int shfl_up(unsigned int val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - return (unsigned int) __shfl_up((int) val, delta, width); - #else - return 0; - #endif - } - __device__ __forceinline__ double shfl_up(double val, unsigned int delta, int width = warpSize) - { - #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 - int lo = __double2loint(val); - int hi = __double2hiint(val); - - lo = __shfl_up(lo, delta, width); - hi = __shfl_up(hi, delta, width); - - return __hiloint2double(hi, lo); - #else - return 0.0; - #endif - } -}}} - -# undef __shfl -# undef __shfl_up -# undef __shfl_down - -//! @endcond - -#endif // OPENCV_CUDA_WARP_SHUFFLE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CUDA_WARP_SHUFFLE_HPP +#define OPENCV_CUDA_WARP_SHUFFLE_HPP + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +namespace cv { namespace cuda { namespace device +{ +#if __CUDACC_VER_MAJOR__ >= 9 +# define __shfl(x, y, z) __shfl_sync(0xFFFFFFFFU, x, y, z) +# define __shfl_up(x, y, z) __shfl_up_sync(0xFFFFFFFFU, x, y, z) +# define __shfl_down(x, y, z) __shfl_down_sync(0xFFFFFFFFU, x, y, z) +#endif + template + __device__ __forceinline__ T shfl(T val, int srcLane, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return __shfl(val, srcLane, width); + #else + return T(); + #endif + } + __device__ __forceinline__ unsigned int shfl(unsigned int val, int srcLane, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return (unsigned int) __shfl((int) val, srcLane, width); + #else + return 0; + #endif + } + __device__ __forceinline__ double shfl(double val, int srcLane, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + int lo = __double2loint(val); + int hi = __double2hiint(val); + + lo = __shfl(lo, srcLane, width); + hi = __shfl(hi, srcLane, width); + + return __hiloint2double(hi, lo); + #else + return 0.0; + #endif + } + + template + __device__ __forceinline__ T shfl_down(T val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return __shfl_down(val, delta, width); + #else + return T(); + #endif + } + __device__ __forceinline__ unsigned int shfl_down(unsigned int val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return (unsigned int) __shfl_down((int) val, delta, width); + #else + return 0; + #endif + } + __device__ __forceinline__ double shfl_down(double val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + int lo = __double2loint(val); + int hi = __double2hiint(val); + + lo = __shfl_down(lo, delta, width); + hi = __shfl_down(hi, delta, width); + + return __hiloint2double(hi, lo); + #else + return 0.0; + #endif + } + + template + __device__ __forceinline__ T shfl_up(T val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return __shfl_up(val, delta, width); + #else + return T(); + #endif + } + __device__ __forceinline__ unsigned int shfl_up(unsigned int val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + return (unsigned int) __shfl_up((int) val, delta, width); + #else + return 0; + #endif + } + __device__ __forceinline__ double shfl_up(double val, unsigned int delta, int width = warpSize) + { + #if defined __CUDA_ARCH__ && __CUDA_ARCH__ >= 300 + int lo = __double2loint(val); + int hi = __double2hiint(val); + + lo = __shfl_up(lo, delta, width); + hi = __shfl_up(hi, delta, width); + + return __hiloint2double(hi, lo); + #else + return 0.0; + #endif + } +}}} + +# undef __shfl +# undef __shfl_up +# undef __shfl_down + +//! @endcond + +#endif // OPENCV_CUDA_WARP_SHUFFLE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp index 507194286e..deaf356fff 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda_stream_accessor.hpp @@ -1,86 +1,86 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP -#define OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP - -#ifndef __cplusplus -# error cuda_stream_accessor.hpp header must be compiled as C++ -#endif - -/** @file cuda_stream_accessor.hpp - * This is only header file that depends on CUDA Runtime API. All other headers are independent. - */ - -#include -#include "opencv2/core/cuda.hpp" - -namespace cv -{ - namespace cuda - { - -//! @addtogroup cudacore_struct -//! @{ - - /** @brief Class that enables getting cudaStream_t from cuda::Stream - */ - struct StreamAccessor - { - CV_EXPORTS static cudaStream_t getStream(const Stream& stream); - CV_EXPORTS static Stream wrapStream(cudaStream_t stream); - }; - - /** @brief Class that enables getting cudaEvent_t from cuda::Event - */ - struct EventAccessor - { - CV_EXPORTS static cudaEvent_t getEvent(const Event& event); - CV_EXPORTS static Event wrapEvent(cudaEvent_t event); - }; - -//! @} - - } -} - -#endif /* OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP +#define OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP + +#ifndef __cplusplus +# error cuda_stream_accessor.hpp header must be compiled as C++ +#endif + +/** @file cuda_stream_accessor.hpp + * This is only header file that depends on CUDA Runtime API. All other headers are independent. + */ + +#include +#include "opencv2/core/cuda.hpp" + +namespace cv +{ + namespace cuda + { + +//! @addtogroup cudacore_struct +//! @{ + + /** @brief Class that enables getting cudaStream_t from cuda::Stream + */ + struct StreamAccessor + { + CV_EXPORTS static cudaStream_t getStream(const Stream& stream); + CV_EXPORTS static Stream wrapStream(cudaStream_t stream); + }; + + /** @brief Class that enables getting cudaEvent_t from cuda::Event + */ + struct EventAccessor + { + CV_EXPORTS static cudaEvent_t getEvent(const Event& event); + CV_EXPORTS static Event wrapEvent(cudaEvent_t event); + }; + +//! @} + + } +} + +#endif /* OPENCV_CORE_CUDA_STREAM_ACCESSOR_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp index 73131b1d32..ddee2f3d59 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cuda_types.hpp @@ -1,152 +1,152 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CUDA_TYPES_HPP -#define OPENCV_CORE_CUDA_TYPES_HPP - -#ifndef __cplusplus -# error cuda_types.hpp header must be compiled as C++ -#endif - -#if defined(__OPENCV_BUILD) && defined(__clang__) -#pragma clang diagnostic ignored "-Winconsistent-missing-override" -#endif -#if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5 -#pragma GCC diagnostic ignored "-Wsuggest-override" -#endif - -/** @file - * @deprecated Use @ref cudev instead. - */ - -//! @cond IGNORED - -#ifdef __CUDACC__ - #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ -#else - #define __CV_CUDA_HOST_DEVICE__ -#endif - -#include "opencv2/core/cvdef.h" -#include "opencv2/core.hpp" - -namespace cv -{ - namespace cuda - { - - // Simple lightweight structures that encapsulates information about an image on device. - // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile - - template struct DevPtr - { - typedef T elem_type; - typedef int index_type; - - enum { elem_size = sizeof(elem_type) }; - - T* data; - - __CV_CUDA_HOST_DEVICE__ DevPtr() : data(0) {} - __CV_CUDA_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} - - __CV_CUDA_HOST_DEVICE__ size_t elemSize() const { return elem_size; } - __CV_CUDA_HOST_DEVICE__ operator T*() { return data; } - __CV_CUDA_HOST_DEVICE__ operator const T*() const { return data; } - }; - - template struct PtrSz : public DevPtr - { - __CV_CUDA_HOST_DEVICE__ PtrSz() : size(0) {} - __CV_CUDA_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} - - size_t size; - }; - - template struct PtrStep : public DevPtr - { - __CV_CUDA_HOST_DEVICE__ PtrStep() : step(0) {} - __CV_CUDA_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} - - size_t step; - - __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)(((DevPtr*)this)->data) + y * step); } - __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)(((DevPtr*)this)->data) + y * step); } - - __CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } - __CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } - }; - - template struct PtrStepSz : public PtrStep - { - __CV_CUDA_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} - __CV_CUDA_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) - : PtrStep(data_, step_), cols(cols_), rows(rows_) {} - - template - explicit PtrStepSz(const PtrStepSz& d) : PtrStep((T*)d.data, d.step), cols(d.cols), rows(d.rows){} - - int cols; - int rows; - - CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ Size size() const { return {cols, rows}; } - CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ T& operator ()(const Point &pos) { return (*this)(pos.y, pos.x); } - CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ const T& operator ()(const Point &pos) const { return (*this)(pos.y, pos.x); } - using PtrStep::operator(); - }; - - typedef PtrStepSz PtrStepSzb; - typedef PtrStepSz PtrStepSzus; - typedef PtrStepSz PtrStepSzf; - typedef PtrStepSz PtrStepSzi; - - typedef PtrStep PtrStepb; - typedef PtrStep PtrStepus; - typedef PtrStep PtrStepf; - typedef PtrStep PtrStepi; - - } -} - -//! @endcond - -#endif /* OPENCV_CORE_CUDA_TYPES_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CUDA_TYPES_HPP +#define OPENCV_CORE_CUDA_TYPES_HPP + +#ifndef __cplusplus +# error cuda_types.hpp header must be compiled as C++ +#endif + +#if defined(__OPENCV_BUILD) && defined(__clang__) +#pragma clang diagnostic ignored "-Winconsistent-missing-override" +#endif +#if defined(__OPENCV_BUILD) && defined(__GNUC__) && __GNUC__ >= 5 +#pragma GCC diagnostic ignored "-Wsuggest-override" +#endif + +/** @file + * @deprecated Use @ref cudev instead. + */ + +//! @cond IGNORED + +#ifdef __CUDACC__ + #define __CV_CUDA_HOST_DEVICE__ __host__ __device__ __forceinline__ +#else + #define __CV_CUDA_HOST_DEVICE__ +#endif + +#include "opencv2/core/cvdef.h" +#include "opencv2/core.hpp" + +namespace cv +{ + namespace cuda + { + + // Simple lightweight structures that encapsulates information about an image on device. + // It is intended to pass to nvcc-compiled code. GpuMat depends on headers that nvcc can't compile + + template struct DevPtr + { + typedef T elem_type; + typedef int index_type; + + enum { elem_size = sizeof(elem_type) }; + + T* data; + + __CV_CUDA_HOST_DEVICE__ DevPtr() : data(0) {} + __CV_CUDA_HOST_DEVICE__ DevPtr(T* data_) : data(data_) {} + + __CV_CUDA_HOST_DEVICE__ size_t elemSize() const { return elem_size; } + __CV_CUDA_HOST_DEVICE__ operator T*() { return data; } + __CV_CUDA_HOST_DEVICE__ operator const T*() const { return data; } + }; + + template struct PtrSz : public DevPtr + { + __CV_CUDA_HOST_DEVICE__ PtrSz() : size(0) {} + __CV_CUDA_HOST_DEVICE__ PtrSz(T* data_, size_t size_) : DevPtr(data_), size(size_) {} + + size_t size; + }; + + template struct PtrStep : public DevPtr + { + __CV_CUDA_HOST_DEVICE__ PtrStep() : step(0) {} + __CV_CUDA_HOST_DEVICE__ PtrStep(T* data_, size_t step_) : DevPtr(data_), step(step_) {} + + size_t step; + + __CV_CUDA_HOST_DEVICE__ T* ptr(int y = 0) { return ( T*)( ( char*)(((DevPtr*)this)->data) + y * step); } + __CV_CUDA_HOST_DEVICE__ const T* ptr(int y = 0) const { return (const T*)( (const char*)(((DevPtr*)this)->data) + y * step); } + + __CV_CUDA_HOST_DEVICE__ T& operator ()(int y, int x) { return ptr(y)[x]; } + __CV_CUDA_HOST_DEVICE__ const T& operator ()(int y, int x) const { return ptr(y)[x]; } + }; + + template struct PtrStepSz : public PtrStep + { + __CV_CUDA_HOST_DEVICE__ PtrStepSz() : cols(0), rows(0) {} + __CV_CUDA_HOST_DEVICE__ PtrStepSz(int rows_, int cols_, T* data_, size_t step_) + : PtrStep(data_, step_), cols(cols_), rows(rows_) {} + + template + explicit PtrStepSz(const PtrStepSz& d) : PtrStep((T*)d.data, d.step), cols(d.cols), rows(d.rows){} + + int cols; + int rows; + + CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ Size size() const { return {cols, rows}; } + CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ T& operator ()(const Point &pos) { return (*this)(pos.y, pos.x); } + CV_NODISCARD_STD __CV_CUDA_HOST_DEVICE__ const T& operator ()(const Point &pos) const { return (*this)(pos.y, pos.x); } + using PtrStep::operator(); + }; + + typedef PtrStepSz PtrStepSzb; + typedef PtrStepSz PtrStepSzus; + typedef PtrStepSz PtrStepSzf; + typedef PtrStepSz PtrStepSzi; + + typedef PtrStep PtrStepb; + typedef PtrStep PtrStepus; + typedef PtrStep PtrStepf; + typedef PtrStep PtrStepi; + + } +} + +//! @endcond + +#endif /* OPENCV_CORE_CUDA_TYPES_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h index fb4f4a133b..607f286615 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_dispatch.h @@ -1,395 +1,395 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#if defined __OPENCV_BUILD \ - -#include "cv_cpu_config.h" -#include "cv_cpu_helper.h" - -#ifdef CV_CPU_DISPATCH_MODE -#define CV_CPU_OPTIMIZATION_NAMESPACE __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) -#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) { -#define CV_CPU_OPTIMIZATION_NAMESPACE_END } -#else -#define CV_CPU_OPTIMIZATION_NAMESPACE cpu_baseline -#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace cpu_baseline { -#define CV_CPU_OPTIMIZATION_NAMESPACE_END } -#define CV_CPU_BASELINE_MODE 1 -#endif - - -#define __CV_CPU_DISPATCH_CHAIN_END(fn, args, mode, ...) /* done */ -#define __CV_CPU_DISPATCH(fn, args, mode, ...) __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) -#define __CV_CPU_DISPATCH_EXPAND(fn, args, ...) __CV_EXPAND(__CV_CPU_DISPATCH(fn, args, __VA_ARGS__)) -#define CV_CPU_DISPATCH(fn, args, ...) __CV_CPU_DISPATCH_EXPAND(fn, args, __VA_ARGS__, END) // expand macros - - -#if defined CV_ENABLE_INTRINSICS \ - && !defined CV_DISABLE_OPTIMIZATION \ - && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ \ - -#ifdef CV_CPU_COMPILE_SSE2 -# include -# define CV_MMX 1 -# define CV_SSE 1 -# define CV_SSE2 1 -#endif -#ifdef CV_CPU_COMPILE_SSE3 -# include -# define CV_SSE3 1 -#endif -#ifdef CV_CPU_COMPILE_SSSE3 -# include -# define CV_SSSE3 1 -#endif -#ifdef CV_CPU_COMPILE_SSE4_1 -# include -# define CV_SSE4_1 1 -#endif -#ifdef CV_CPU_COMPILE_SSE4_2 -# include -# define CV_SSE4_2 1 -#endif -#ifdef CV_CPU_COMPILE_POPCNT -# ifdef _MSC_VER -# include -# if defined(_M_X64) -# define CV_POPCNT_U64 (int)_mm_popcnt_u64 -# endif -# define CV_POPCNT_U32 _mm_popcnt_u32 -# else -# include -# if defined(__x86_64__) -# define CV_POPCNT_U64 __builtin_popcountll -# endif -# define CV_POPCNT_U32 __builtin_popcount -# endif -# define CV_POPCNT 1 -#endif -#ifdef CV_CPU_COMPILE_AVX -# include -# define CV_AVX 1 -#endif -#ifdef CV_CPU_COMPILE_FP16 -# if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64) -# include -# else -# include -# endif -# define CV_FP16 1 -#endif -#ifdef CV_CPU_COMPILE_NEON_DOTPROD -# include -# define CV_NEON_DOT 1 -#endif -#ifdef CV_CPU_COMPILE_AVX2 -# include -# define CV_AVX2 1 -#endif -#ifdef CV_CPU_COMPILE_AVX_512F -# include -# define CV_AVX_512F 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_COMMON -# define CV_AVX512_COMMON 1 -# define CV_AVX_512CD 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_KNL -# define CV_AVX512_KNL 1 -# define CV_AVX_512ER 1 -# define CV_AVX_512PF 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_KNM -# define CV_AVX512_KNM 1 -# define CV_AVX_5124FMAPS 1 -# define CV_AVX_5124VNNIW 1 -# define CV_AVX_512VPOPCNTDQ 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_SKX -# define CV_AVX512_SKX 1 -# define CV_AVX_512VL 1 -# define CV_AVX_512BW 1 -# define CV_AVX_512DQ 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_CNL -# define CV_AVX512_CNL 1 -# define CV_AVX_512IFMA 1 -# define CV_AVX_512VBMI 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_CLX -# define CV_AVX512_CLX 1 -# define CV_AVX_512VNNI 1 -#endif -#ifdef CV_CPU_COMPILE_AVX512_ICL -# define CV_AVX512_ICL 1 -# undef CV_AVX_512IFMA -# define CV_AVX_512IFMA 1 -# undef CV_AVX_512VBMI -# define CV_AVX_512VBMI 1 -# undef CV_AVX_512VNNI -# define CV_AVX_512VNNI 1 -# define CV_AVX_512VBMI2 1 -# define CV_AVX_512BITALG 1 -# define CV_AVX_512VPOPCNTDQ 1 -#endif -#ifdef CV_CPU_COMPILE_FMA3 -# define CV_FMA3 1 -#endif - -#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) -# include -# include -# define CV_NEON 1 -#elif defined(__ARM_NEON) -# include -# define CV_NEON 1 -#endif - -/* RVV-related macro states with different compiler -// +--------------------+----------+----------+ -// | Macro | Upstream | XuanTie | -// +--------------------+----------+----------+ -// | CV_CPU_COMPILE_RVV | defined | defined | -// | CV_RVV | 1 | 0 | -// | CV_RVV071 | 0 | 1 | -// | CV_TRY_RVV | 1 | 1 | -// +--------------------+----------+----------+ -*/ -#ifdef CV_CPU_COMPILE_RVV -# ifdef __riscv_vector_071 -# define CV_RVV071 1 -# else -# define CV_RVV 1 -# endif -#include -#endif - -#ifdef CV_CPU_COMPILE_VSX -# include -# undef vector -# undef pixel -# undef bool -# define CV_VSX 1 -#endif - -#ifdef CV_CPU_COMPILE_VSX3 -# define CV_VSX3 1 -#endif - -#ifdef CV_CPU_COMPILE_MSA -# include "hal/msa_macros.h" -# define CV_MSA 1 -#endif - -#ifdef CV_CPU_COMPILE_LSX -# include -# define CV_LSX 1 -#endif - -#ifdef CV_CPU_COMPILE_LASX -# include -# define CV_LASX 1 -#endif - -#ifdef __EMSCRIPTEN__ -# define CV_WASM_SIMD 1 -# include -#endif - -#endif // CV_ENABLE_INTRINSICS && !CV_DISABLE_OPTIMIZATION && !__CUDACC__ - -#if defined CV_CPU_COMPILE_AVX && !defined CV_CPU_BASELINE_COMPILE_AVX -struct VZeroUpperGuard { -#ifdef __GNUC__ - __attribute__((always_inline)) -#endif - inline VZeroUpperGuard() { _mm256_zeroupper(); } -#ifdef __GNUC__ - __attribute__((always_inline)) -#endif - inline ~VZeroUpperGuard() { _mm256_zeroupper(); } -}; -#define __CV_AVX_GUARD VZeroUpperGuard __vzeroupper_guard; CV_UNUSED(__vzeroupper_guard); -#endif - -#ifdef __CV_AVX_GUARD -#define CV_AVX_GUARD __CV_AVX_GUARD -#else -#define CV_AVX_GUARD -#endif - -#endif // __OPENCV_BUILD - - - -#if !defined __OPENCV_BUILD /* Compatibility code */ \ - && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ -#if defined __SSE2__ || defined _M_X64 || (defined _M_IX86_FP && _M_IX86_FP >= 2) -# include -# define CV_MMX 1 -# define CV_SSE 1 -# define CV_SSE2 1 -#elif defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) -# include -# include -# define CV_NEON 1 -#elif defined(__ARM_NEON) -# include -# define CV_NEON 1 -#elif defined(__VSX__) && defined(__PPC64__) && defined(__LITTLE_ENDIAN__) -# include -# undef vector -# undef pixel -# undef bool -# define CV_VSX 1 -#endif - -#ifdef __F16C__ -# include -# define CV_FP16 1 -#endif - -#endif // !__OPENCV_BUILD && !__CUDACC (Compatibility code) - - - -#ifndef CV_MMX -# define CV_MMX 0 -#endif -#ifndef CV_SSE -# define CV_SSE 0 -#endif -#ifndef CV_SSE2 -# define CV_SSE2 0 -#endif -#ifndef CV_SSE3 -# define CV_SSE3 0 -#endif -#ifndef CV_SSSE3 -# define CV_SSSE3 0 -#endif -#ifndef CV_SSE4_1 -# define CV_SSE4_1 0 -#endif -#ifndef CV_SSE4_2 -# define CV_SSE4_2 0 -#endif -#ifndef CV_POPCNT -# define CV_POPCNT 0 -#endif -#ifndef CV_AVX -# define CV_AVX 0 -#endif -#ifndef CV_FP16 -# define CV_FP16 0 -#endif -#ifndef CV_AVX2 -# define CV_AVX2 0 -#endif -#ifndef CV_FMA3 -# define CV_FMA3 0 -#endif -#ifndef CV_AVX_512F -# define CV_AVX_512F 0 -#endif -#ifndef CV_AVX_512BW -# define CV_AVX_512BW 0 -#endif -#ifndef CV_AVX_512CD -# define CV_AVX_512CD 0 -#endif -#ifndef CV_AVX_512DQ -# define CV_AVX_512DQ 0 -#endif -#ifndef CV_AVX_512ER -# define CV_AVX_512ER 0 -#endif -#ifndef CV_AVX_512IFMA -# define CV_AVX_512IFMA 0 -#endif -#define CV_AVX_512IFMA512 CV_AVX_512IFMA // deprecated -#ifndef CV_AVX_512PF -# define CV_AVX_512PF 0 -#endif -#ifndef CV_AVX_512VBMI -# define CV_AVX_512VBMI 0 -#endif -#ifndef CV_AVX_512VL -# define CV_AVX_512VL 0 -#endif -#ifndef CV_AVX_5124FMAPS -# define CV_AVX_5124FMAPS 0 -#endif -#ifndef CV_AVX_5124VNNIW -# define CV_AVX_5124VNNIW 0 -#endif -#ifndef CV_AVX_512VPOPCNTDQ -# define CV_AVX_512VPOPCNTDQ 0 -#endif -#ifndef CV_AVX_512VNNI -# define CV_AVX_512VNNI 0 -#endif -#ifndef CV_AVX_512VBMI2 -# define CV_AVX_512VBMI2 0 -#endif -#ifndef CV_AVX_512BITALG -# define CV_AVX_512BITALG 0 -#endif -#ifndef CV_AVX512_COMMON -# define CV_AVX512_COMMON 0 -#endif -#ifndef CV_AVX512_KNL -# define CV_AVX512_KNL 0 -#endif -#ifndef CV_AVX512_KNM -# define CV_AVX512_KNM 0 -#endif -#ifndef CV_AVX512_SKX -# define CV_AVX512_SKX 0 -#endif -#ifndef CV_AVX512_CNL -# define CV_AVX512_CNL 0 -#endif -#ifndef CV_AVX512_CLX -# define CV_AVX512_CLX 0 -#endif -#ifndef CV_AVX512_ICL -# define CV_AVX512_ICL 0 -#endif - -#ifndef CV_NEON -# define CV_NEON 0 -#endif - -#ifndef CV_RVV071 -# define CV_RVV071 0 -#endif - -#ifndef CV_VSX -# define CV_VSX 0 -#endif - -#ifndef CV_VSX3 -# define CV_VSX3 0 -#endif - -#ifndef CV_MSA -# define CV_MSA 0 -#endif - -#ifndef CV_WASM_SIMD -# define CV_WASM_SIMD 0 -#endif - -#ifndef CV_RVV -# define CV_RVV 0 -#endif - -#ifndef CV_LSX -# define CV_LSX 0 -#endif - -#ifndef CV_LASX -# define CV_LASX 0 -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#if defined __OPENCV_BUILD \ + +#include "cv_cpu_config.h" +#include "cv_cpu_helper.h" + +#ifdef CV_CPU_DISPATCH_MODE +#define CV_CPU_OPTIMIZATION_NAMESPACE __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) +#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace __CV_CAT(opt_, CV_CPU_DISPATCH_MODE) { +#define CV_CPU_OPTIMIZATION_NAMESPACE_END } +#else +#define CV_CPU_OPTIMIZATION_NAMESPACE cpu_baseline +#define CV_CPU_OPTIMIZATION_NAMESPACE_BEGIN namespace cpu_baseline { +#define CV_CPU_OPTIMIZATION_NAMESPACE_END } +#define CV_CPU_BASELINE_MODE 1 +#endif + + +#define __CV_CPU_DISPATCH_CHAIN_END(fn, args, mode, ...) /* done */ +#define __CV_CPU_DISPATCH(fn, args, mode, ...) __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) +#define __CV_CPU_DISPATCH_EXPAND(fn, args, ...) __CV_EXPAND(__CV_CPU_DISPATCH(fn, args, __VA_ARGS__)) +#define CV_CPU_DISPATCH(fn, args, ...) __CV_CPU_DISPATCH_EXPAND(fn, args, __VA_ARGS__, END) // expand macros + + +#if defined CV_ENABLE_INTRINSICS \ + && !defined CV_DISABLE_OPTIMIZATION \ + && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ \ + +#ifdef CV_CPU_COMPILE_SSE2 +# include +# define CV_MMX 1 +# define CV_SSE 1 +# define CV_SSE2 1 +#endif +#ifdef CV_CPU_COMPILE_SSE3 +# include +# define CV_SSE3 1 +#endif +#ifdef CV_CPU_COMPILE_SSSE3 +# include +# define CV_SSSE3 1 +#endif +#ifdef CV_CPU_COMPILE_SSE4_1 +# include +# define CV_SSE4_1 1 +#endif +#ifdef CV_CPU_COMPILE_SSE4_2 +# include +# define CV_SSE4_2 1 +#endif +#ifdef CV_CPU_COMPILE_POPCNT +# ifdef _MSC_VER +# include +# if defined(_M_X64) +# define CV_POPCNT_U64 (int)_mm_popcnt_u64 +# endif +# define CV_POPCNT_U32 _mm_popcnt_u32 +# else +# include +# if defined(__x86_64__) +# define CV_POPCNT_U64 __builtin_popcountll +# endif +# define CV_POPCNT_U32 __builtin_popcount +# endif +# define CV_POPCNT 1 +#endif +#ifdef CV_CPU_COMPILE_AVX +# include +# define CV_AVX 1 +#endif +#ifdef CV_CPU_COMPILE_FP16 +# if defined(__arm__) || defined(__aarch64__) || defined(_M_ARM) || defined(_M_ARM64) +# include +# else +# include +# endif +# define CV_FP16 1 +#endif +#ifdef CV_CPU_COMPILE_NEON_DOTPROD +# include +# define CV_NEON_DOT 1 +#endif +#ifdef CV_CPU_COMPILE_AVX2 +# include +# define CV_AVX2 1 +#endif +#ifdef CV_CPU_COMPILE_AVX_512F +# include +# define CV_AVX_512F 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_COMMON +# define CV_AVX512_COMMON 1 +# define CV_AVX_512CD 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_KNL +# define CV_AVX512_KNL 1 +# define CV_AVX_512ER 1 +# define CV_AVX_512PF 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_KNM +# define CV_AVX512_KNM 1 +# define CV_AVX_5124FMAPS 1 +# define CV_AVX_5124VNNIW 1 +# define CV_AVX_512VPOPCNTDQ 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_SKX +# define CV_AVX512_SKX 1 +# define CV_AVX_512VL 1 +# define CV_AVX_512BW 1 +# define CV_AVX_512DQ 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_CNL +# define CV_AVX512_CNL 1 +# define CV_AVX_512IFMA 1 +# define CV_AVX_512VBMI 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_CLX +# define CV_AVX512_CLX 1 +# define CV_AVX_512VNNI 1 +#endif +#ifdef CV_CPU_COMPILE_AVX512_ICL +# define CV_AVX512_ICL 1 +# undef CV_AVX_512IFMA +# define CV_AVX_512IFMA 1 +# undef CV_AVX_512VBMI +# define CV_AVX_512VBMI 1 +# undef CV_AVX_512VNNI +# define CV_AVX_512VNNI 1 +# define CV_AVX_512VBMI2 1 +# define CV_AVX_512BITALG 1 +# define CV_AVX_512VPOPCNTDQ 1 +#endif +#ifdef CV_CPU_COMPILE_FMA3 +# define CV_FMA3 1 +#endif + +#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) +# include +# include +# define CV_NEON 1 +#elif defined(__ARM_NEON) +# include +# define CV_NEON 1 +#endif + +/* RVV-related macro states with different compiler +// +--------------------+----------+----------+ +// | Macro | Upstream | XuanTie | +// +--------------------+----------+----------+ +// | CV_CPU_COMPILE_RVV | defined | defined | +// | CV_RVV | 1 | 0 | +// | CV_RVV071 | 0 | 1 | +// | CV_TRY_RVV | 1 | 1 | +// +--------------------+----------+----------+ +*/ +#ifdef CV_CPU_COMPILE_RVV +# ifdef __riscv_vector_071 +# define CV_RVV071 1 +# else +# define CV_RVV 1 +# endif +#include +#endif + +#ifdef CV_CPU_COMPILE_VSX +# include +# undef vector +# undef pixel +# undef bool +# define CV_VSX 1 +#endif + +#ifdef CV_CPU_COMPILE_VSX3 +# define CV_VSX3 1 +#endif + +#ifdef CV_CPU_COMPILE_MSA +# include "hal/msa_macros.h" +# define CV_MSA 1 +#endif + +#ifdef CV_CPU_COMPILE_LSX +# include +# define CV_LSX 1 +#endif + +#ifdef CV_CPU_COMPILE_LASX +# include +# define CV_LASX 1 +#endif + +#ifdef __EMSCRIPTEN__ +# define CV_WASM_SIMD 1 +# include +#endif + +#endif // CV_ENABLE_INTRINSICS && !CV_DISABLE_OPTIMIZATION && !__CUDACC__ + +#if defined CV_CPU_COMPILE_AVX && !defined CV_CPU_BASELINE_COMPILE_AVX +struct VZeroUpperGuard { +#ifdef __GNUC__ + __attribute__((always_inline)) +#endif + inline VZeroUpperGuard() { _mm256_zeroupper(); } +#ifdef __GNUC__ + __attribute__((always_inline)) +#endif + inline ~VZeroUpperGuard() { _mm256_zeroupper(); } +}; +#define __CV_AVX_GUARD VZeroUpperGuard __vzeroupper_guard; CV_UNUSED(__vzeroupper_guard); +#endif + +#ifdef __CV_AVX_GUARD +#define CV_AVX_GUARD __CV_AVX_GUARD +#else +#define CV_AVX_GUARD +#endif + +#endif // __OPENCV_BUILD + + + +#if !defined __OPENCV_BUILD /* Compatibility code */ \ + && !defined __CUDACC__ /* do not include SSE/AVX/NEON headers for NVCC compiler */ +#if defined __SSE2__ || defined _M_X64 || (defined _M_IX86_FP && _M_IX86_FP >= 2) +# include +# define CV_MMX 1 +# define CV_SSE 1 +# define CV_SSE2 1 +#elif defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) && (defined(CV_CPU_COMPILE_NEON) || !defined(_MSC_VER)) +# include +# include +# define CV_NEON 1 +#elif defined(__ARM_NEON) +# include +# define CV_NEON 1 +#elif defined(__VSX__) && defined(__PPC64__) && defined(__LITTLE_ENDIAN__) +# include +# undef vector +# undef pixel +# undef bool +# define CV_VSX 1 +#endif + +#ifdef __F16C__ +# include +# define CV_FP16 1 +#endif + +#endif // !__OPENCV_BUILD && !__CUDACC (Compatibility code) + + + +#ifndef CV_MMX +# define CV_MMX 0 +#endif +#ifndef CV_SSE +# define CV_SSE 0 +#endif +#ifndef CV_SSE2 +# define CV_SSE2 0 +#endif +#ifndef CV_SSE3 +# define CV_SSE3 0 +#endif +#ifndef CV_SSSE3 +# define CV_SSSE3 0 +#endif +#ifndef CV_SSE4_1 +# define CV_SSE4_1 0 +#endif +#ifndef CV_SSE4_2 +# define CV_SSE4_2 0 +#endif +#ifndef CV_POPCNT +# define CV_POPCNT 0 +#endif +#ifndef CV_AVX +# define CV_AVX 0 +#endif +#ifndef CV_FP16 +# define CV_FP16 0 +#endif +#ifndef CV_AVX2 +# define CV_AVX2 0 +#endif +#ifndef CV_FMA3 +# define CV_FMA3 0 +#endif +#ifndef CV_AVX_512F +# define CV_AVX_512F 0 +#endif +#ifndef CV_AVX_512BW +# define CV_AVX_512BW 0 +#endif +#ifndef CV_AVX_512CD +# define CV_AVX_512CD 0 +#endif +#ifndef CV_AVX_512DQ +# define CV_AVX_512DQ 0 +#endif +#ifndef CV_AVX_512ER +# define CV_AVX_512ER 0 +#endif +#ifndef CV_AVX_512IFMA +# define CV_AVX_512IFMA 0 +#endif +#define CV_AVX_512IFMA512 CV_AVX_512IFMA // deprecated +#ifndef CV_AVX_512PF +# define CV_AVX_512PF 0 +#endif +#ifndef CV_AVX_512VBMI +# define CV_AVX_512VBMI 0 +#endif +#ifndef CV_AVX_512VL +# define CV_AVX_512VL 0 +#endif +#ifndef CV_AVX_5124FMAPS +# define CV_AVX_5124FMAPS 0 +#endif +#ifndef CV_AVX_5124VNNIW +# define CV_AVX_5124VNNIW 0 +#endif +#ifndef CV_AVX_512VPOPCNTDQ +# define CV_AVX_512VPOPCNTDQ 0 +#endif +#ifndef CV_AVX_512VNNI +# define CV_AVX_512VNNI 0 +#endif +#ifndef CV_AVX_512VBMI2 +# define CV_AVX_512VBMI2 0 +#endif +#ifndef CV_AVX_512BITALG +# define CV_AVX_512BITALG 0 +#endif +#ifndef CV_AVX512_COMMON +# define CV_AVX512_COMMON 0 +#endif +#ifndef CV_AVX512_KNL +# define CV_AVX512_KNL 0 +#endif +#ifndef CV_AVX512_KNM +# define CV_AVX512_KNM 0 +#endif +#ifndef CV_AVX512_SKX +# define CV_AVX512_SKX 0 +#endif +#ifndef CV_AVX512_CNL +# define CV_AVX512_CNL 0 +#endif +#ifndef CV_AVX512_CLX +# define CV_AVX512_CLX 0 +#endif +#ifndef CV_AVX512_ICL +# define CV_AVX512_ICL 0 +#endif + +#ifndef CV_NEON +# define CV_NEON 0 +#endif + +#ifndef CV_RVV071 +# define CV_RVV071 0 +#endif + +#ifndef CV_VSX +# define CV_VSX 0 +#endif + +#ifndef CV_VSX3 +# define CV_VSX3 0 +#endif + +#ifndef CV_MSA +# define CV_MSA 0 +#endif + +#ifndef CV_WASM_SIMD +# define CV_WASM_SIMD 0 +#endif + +#ifndef CV_RVV +# define CV_RVV 0 +#endif + +#ifndef CV_LSX +# define CV_LSX 0 +#endif + +#ifndef CV_LASX +# define CV_LASX 0 +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h index 29952aec36..04b00d2024 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/cv_cpu_helper.h @@ -1,613 +1,613 @@ -// AUTOGENERATED, DO NOT EDIT - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE -# define CV_TRY_SSE 1 -# define CV_CPU_FORCE_SSE 1 -# define CV_CPU_HAS_SUPPORT_SSE 1 -# define CV_CPU_CALL_SSE(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE_(fn, args) return (opt_SSE::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE -# define CV_TRY_SSE 1 -# define CV_CPU_FORCE_SSE 0 -# define CV_CPU_HAS_SUPPORT_SSE (cv::checkHardwareSupport(CV_CPU_SSE)) -# define CV_CPU_CALL_SSE(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) -# define CV_CPU_CALL_SSE_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) -#else -# define CV_TRY_SSE 0 -# define CV_CPU_FORCE_SSE 0 -# define CV_CPU_HAS_SUPPORT_SSE 0 -# define CV_CPU_CALL_SSE(fn, args) -# define CV_CPU_CALL_SSE_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE(fn, args, mode, ...) CV_CPU_CALL_SSE(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE2 -# define CV_TRY_SSE2 1 -# define CV_CPU_FORCE_SSE2 1 -# define CV_CPU_HAS_SUPPORT_SSE2 1 -# define CV_CPU_CALL_SSE2(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE2_(fn, args) return (opt_SSE2::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE2 -# define CV_TRY_SSE2 1 -# define CV_CPU_FORCE_SSE2 0 -# define CV_CPU_HAS_SUPPORT_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2)) -# define CV_CPU_CALL_SSE2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) -# define CV_CPU_CALL_SSE2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) -#else -# define CV_TRY_SSE2 0 -# define CV_CPU_FORCE_SSE2 0 -# define CV_CPU_HAS_SUPPORT_SSE2 0 -# define CV_CPU_CALL_SSE2(fn, args) -# define CV_CPU_CALL_SSE2_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE2(fn, args, mode, ...) CV_CPU_CALL_SSE2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE3 -# define CV_TRY_SSE3 1 -# define CV_CPU_FORCE_SSE3 1 -# define CV_CPU_HAS_SUPPORT_SSE3 1 -# define CV_CPU_CALL_SSE3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE3_(fn, args) return (opt_SSE3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE3 -# define CV_TRY_SSE3 1 -# define CV_CPU_FORCE_SSE3 0 -# define CV_CPU_HAS_SUPPORT_SSE3 (cv::checkHardwareSupport(CV_CPU_SSE3)) -# define CV_CPU_CALL_SSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) -# define CV_CPU_CALL_SSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) -#else -# define CV_TRY_SSE3 0 -# define CV_CPU_FORCE_SSE3 0 -# define CV_CPU_HAS_SUPPORT_SSE3 0 -# define CV_CPU_CALL_SSE3(fn, args) -# define CV_CPU_CALL_SSE3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE3(fn, args, mode, ...) CV_CPU_CALL_SSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSSE3 -# define CV_TRY_SSSE3 1 -# define CV_CPU_FORCE_SSSE3 1 -# define CV_CPU_HAS_SUPPORT_SSSE3 1 -# define CV_CPU_CALL_SSSE3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSSE3_(fn, args) return (opt_SSSE3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSSE3 -# define CV_TRY_SSSE3 1 -# define CV_CPU_FORCE_SSSE3 0 -# define CV_CPU_HAS_SUPPORT_SSSE3 (cv::checkHardwareSupport(CV_CPU_SSSE3)) -# define CV_CPU_CALL_SSSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) -# define CV_CPU_CALL_SSSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) -#else -# define CV_TRY_SSSE3 0 -# define CV_CPU_FORCE_SSSE3 0 -# define CV_CPU_HAS_SUPPORT_SSSE3 0 -# define CV_CPU_CALL_SSSE3(fn, args) -# define CV_CPU_CALL_SSSE3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSSE3(fn, args, mode, ...) CV_CPU_CALL_SSSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_1 -# define CV_TRY_SSE4_1 1 -# define CV_CPU_FORCE_SSE4_1 1 -# define CV_CPU_HAS_SUPPORT_SSE4_1 1 -# define CV_CPU_CALL_SSE4_1(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE4_1_(fn, args) return (opt_SSE4_1::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_1 -# define CV_TRY_SSE4_1 1 -# define CV_CPU_FORCE_SSE4_1 0 -# define CV_CPU_HAS_SUPPORT_SSE4_1 (cv::checkHardwareSupport(CV_CPU_SSE4_1)) -# define CV_CPU_CALL_SSE4_1(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) -# define CV_CPU_CALL_SSE4_1_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) -#else -# define CV_TRY_SSE4_1 0 -# define CV_CPU_FORCE_SSE4_1 0 -# define CV_CPU_HAS_SUPPORT_SSE4_1 0 -# define CV_CPU_CALL_SSE4_1(fn, args) -# define CV_CPU_CALL_SSE4_1_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE4_1(fn, args, mode, ...) CV_CPU_CALL_SSE4_1(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_2 -# define CV_TRY_SSE4_2 1 -# define CV_CPU_FORCE_SSE4_2 1 -# define CV_CPU_HAS_SUPPORT_SSE4_2 1 -# define CV_CPU_CALL_SSE4_2(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_SSE4_2_(fn, args) return (opt_SSE4_2::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_2 -# define CV_TRY_SSE4_2 1 -# define CV_CPU_FORCE_SSE4_2 0 -# define CV_CPU_HAS_SUPPORT_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2)) -# define CV_CPU_CALL_SSE4_2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) -# define CV_CPU_CALL_SSE4_2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) -#else -# define CV_TRY_SSE4_2 0 -# define CV_CPU_FORCE_SSE4_2 0 -# define CV_CPU_HAS_SUPPORT_SSE4_2 0 -# define CV_CPU_CALL_SSE4_2(fn, args) -# define CV_CPU_CALL_SSE4_2_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_SSE4_2(fn, args, mode, ...) CV_CPU_CALL_SSE4_2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_POPCNT -# define CV_TRY_POPCNT 1 -# define CV_CPU_FORCE_POPCNT 1 -# define CV_CPU_HAS_SUPPORT_POPCNT 1 -# define CV_CPU_CALL_POPCNT(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_POPCNT_(fn, args) return (opt_POPCNT::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_POPCNT -# define CV_TRY_POPCNT 1 -# define CV_CPU_FORCE_POPCNT 0 -# define CV_CPU_HAS_SUPPORT_POPCNT (cv::checkHardwareSupport(CV_CPU_POPCNT)) -# define CV_CPU_CALL_POPCNT(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) -# define CV_CPU_CALL_POPCNT_(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) -#else -# define CV_TRY_POPCNT 0 -# define CV_CPU_FORCE_POPCNT 0 -# define CV_CPU_HAS_SUPPORT_POPCNT 0 -# define CV_CPU_CALL_POPCNT(fn, args) -# define CV_CPU_CALL_POPCNT_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_POPCNT(fn, args, mode, ...) CV_CPU_CALL_POPCNT(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX -# define CV_TRY_AVX 1 -# define CV_CPU_FORCE_AVX 1 -# define CV_CPU_HAS_SUPPORT_AVX 1 -# define CV_CPU_CALL_AVX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX_(fn, args) return (opt_AVX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX -# define CV_TRY_AVX 1 -# define CV_CPU_FORCE_AVX 0 -# define CV_CPU_HAS_SUPPORT_AVX (cv::checkHardwareSupport(CV_CPU_AVX)) -# define CV_CPU_CALL_AVX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) -# define CV_CPU_CALL_AVX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) -#else -# define CV_TRY_AVX 0 -# define CV_CPU_FORCE_AVX 0 -# define CV_CPU_HAS_SUPPORT_AVX 0 -# define CV_CPU_CALL_AVX(fn, args) -# define CV_CPU_CALL_AVX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX(fn, args, mode, ...) CV_CPU_CALL_AVX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FP16 -# define CV_TRY_FP16 1 -# define CV_CPU_FORCE_FP16 1 -# define CV_CPU_HAS_SUPPORT_FP16 1 -# define CV_CPU_CALL_FP16(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_FP16_(fn, args) return (opt_FP16::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FP16 -# define CV_TRY_FP16 1 -# define CV_CPU_FORCE_FP16 0 -# define CV_CPU_HAS_SUPPORT_FP16 (cv::checkHardwareSupport(CV_CPU_FP16)) -# define CV_CPU_CALL_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) -# define CV_CPU_CALL_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) -#else -# define CV_TRY_FP16 0 -# define CV_CPU_FORCE_FP16 0 -# define CV_CPU_HAS_SUPPORT_FP16 0 -# define CV_CPU_CALL_FP16(fn, args) -# define CV_CPU_CALL_FP16_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_FP16(fn, args, mode, ...) CV_CPU_CALL_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX2 -# define CV_TRY_AVX2 1 -# define CV_CPU_FORCE_AVX2 1 -# define CV_CPU_HAS_SUPPORT_AVX2 1 -# define CV_CPU_CALL_AVX2(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX2_(fn, args) return (opt_AVX2::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX2 -# define CV_TRY_AVX2 1 -# define CV_CPU_FORCE_AVX2 0 -# define CV_CPU_HAS_SUPPORT_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2)) -# define CV_CPU_CALL_AVX2(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) -# define CV_CPU_CALL_AVX2_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) -#else -# define CV_TRY_AVX2 0 -# define CV_CPU_FORCE_AVX2 0 -# define CV_CPU_HAS_SUPPORT_AVX2 0 -# define CV_CPU_CALL_AVX2(fn, args) -# define CV_CPU_CALL_AVX2_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX2(fn, args, mode, ...) CV_CPU_CALL_AVX2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FMA3 -# define CV_TRY_FMA3 1 -# define CV_CPU_FORCE_FMA3 1 -# define CV_CPU_HAS_SUPPORT_FMA3 1 -# define CV_CPU_CALL_FMA3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_FMA3_(fn, args) return (opt_FMA3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FMA3 -# define CV_TRY_FMA3 1 -# define CV_CPU_FORCE_FMA3 0 -# define CV_CPU_HAS_SUPPORT_FMA3 (cv::checkHardwareSupport(CV_CPU_FMA3)) -# define CV_CPU_CALL_FMA3(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) -# define CV_CPU_CALL_FMA3_(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) -#else -# define CV_TRY_FMA3 0 -# define CV_CPU_FORCE_FMA3 0 -# define CV_CPU_HAS_SUPPORT_FMA3 0 -# define CV_CPU_CALL_FMA3(fn, args) -# define CV_CPU_CALL_FMA3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_FMA3(fn, args, mode, ...) CV_CPU_CALL_FMA3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX_512F -# define CV_TRY_AVX_512F 1 -# define CV_CPU_FORCE_AVX_512F 1 -# define CV_CPU_HAS_SUPPORT_AVX_512F 1 -# define CV_CPU_CALL_AVX_512F(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX_512F_(fn, args) return (opt_AVX_512F::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX_512F -# define CV_TRY_AVX_512F 1 -# define CV_CPU_FORCE_AVX_512F 0 -# define CV_CPU_HAS_SUPPORT_AVX_512F (cv::checkHardwareSupport(CV_CPU_AVX_512F)) -# define CV_CPU_CALL_AVX_512F(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) -# define CV_CPU_CALL_AVX_512F_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) -#else -# define CV_TRY_AVX_512F 0 -# define CV_CPU_FORCE_AVX_512F 0 -# define CV_CPU_HAS_SUPPORT_AVX_512F 0 -# define CV_CPU_CALL_AVX_512F(fn, args) -# define CV_CPU_CALL_AVX_512F_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX_512F(fn, args, mode, ...) CV_CPU_CALL_AVX_512F(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_COMMON -# define CV_TRY_AVX512_COMMON 1 -# define CV_CPU_FORCE_AVX512_COMMON 1 -# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 1 -# define CV_CPU_CALL_AVX512_COMMON(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_COMMON_(fn, args) return (opt_AVX512_COMMON::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_COMMON -# define CV_TRY_AVX512_COMMON 1 -# define CV_CPU_FORCE_AVX512_COMMON 0 -# define CV_CPU_HAS_SUPPORT_AVX512_COMMON (cv::checkHardwareSupport(CV_CPU_AVX512_COMMON)) -# define CV_CPU_CALL_AVX512_COMMON(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) -# define CV_CPU_CALL_AVX512_COMMON_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) -#else -# define CV_TRY_AVX512_COMMON 0 -# define CV_CPU_FORCE_AVX512_COMMON 0 -# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 0 -# define CV_CPU_CALL_AVX512_COMMON(fn, args) -# define CV_CPU_CALL_AVX512_COMMON_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_COMMON(fn, args, mode, ...) CV_CPU_CALL_AVX512_COMMON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNL -# define CV_TRY_AVX512_KNL 1 -# define CV_CPU_FORCE_AVX512_KNL 1 -# define CV_CPU_HAS_SUPPORT_AVX512_KNL 1 -# define CV_CPU_CALL_AVX512_KNL(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_KNL_(fn, args) return (opt_AVX512_KNL::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNL -# define CV_TRY_AVX512_KNL 1 -# define CV_CPU_FORCE_AVX512_KNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNL (cv::checkHardwareSupport(CV_CPU_AVX512_KNL)) -# define CV_CPU_CALL_AVX512_KNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) -# define CV_CPU_CALL_AVX512_KNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) -#else -# define CV_TRY_AVX512_KNL 0 -# define CV_CPU_FORCE_AVX512_KNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNL 0 -# define CV_CPU_CALL_AVX512_KNL(fn, args) -# define CV_CPU_CALL_AVX512_KNL_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNM -# define CV_TRY_AVX512_KNM 1 -# define CV_CPU_FORCE_AVX512_KNM 1 -# define CV_CPU_HAS_SUPPORT_AVX512_KNM 1 -# define CV_CPU_CALL_AVX512_KNM(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_KNM_(fn, args) return (opt_AVX512_KNM::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNM -# define CV_TRY_AVX512_KNM 1 -# define CV_CPU_FORCE_AVX512_KNM 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNM (cv::checkHardwareSupport(CV_CPU_AVX512_KNM)) -# define CV_CPU_CALL_AVX512_KNM(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) -# define CV_CPU_CALL_AVX512_KNM_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) -#else -# define CV_TRY_AVX512_KNM 0 -# define CV_CPU_FORCE_AVX512_KNM 0 -# define CV_CPU_HAS_SUPPORT_AVX512_KNM 0 -# define CV_CPU_CALL_AVX512_KNM(fn, args) -# define CV_CPU_CALL_AVX512_KNM_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNM(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNM(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_SKX -# define CV_TRY_AVX512_SKX 1 -# define CV_CPU_FORCE_AVX512_SKX 1 -# define CV_CPU_HAS_SUPPORT_AVX512_SKX 1 -# define CV_CPU_CALL_AVX512_SKX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_SKX_(fn, args) return (opt_AVX512_SKX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_SKX -# define CV_TRY_AVX512_SKX 1 -# define CV_CPU_FORCE_AVX512_SKX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_SKX (cv::checkHardwareSupport(CV_CPU_AVX512_SKX)) -# define CV_CPU_CALL_AVX512_SKX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) -# define CV_CPU_CALL_AVX512_SKX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) -#else -# define CV_TRY_AVX512_SKX 0 -# define CV_CPU_FORCE_AVX512_SKX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_SKX 0 -# define CV_CPU_CALL_AVX512_SKX(fn, args) -# define CV_CPU_CALL_AVX512_SKX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_SKX(fn, args, mode, ...) CV_CPU_CALL_AVX512_SKX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CNL -# define CV_TRY_AVX512_CNL 1 -# define CV_CPU_FORCE_AVX512_CNL 1 -# define CV_CPU_HAS_SUPPORT_AVX512_CNL 1 -# define CV_CPU_CALL_AVX512_CNL(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_CNL_(fn, args) return (opt_AVX512_CNL::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CNL -# define CV_TRY_AVX512_CNL 1 -# define CV_CPU_FORCE_AVX512_CNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CNL (cv::checkHardwareSupport(CV_CPU_AVX512_CNL)) -# define CV_CPU_CALL_AVX512_CNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) -# define CV_CPU_CALL_AVX512_CNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) -#else -# define CV_TRY_AVX512_CNL 0 -# define CV_CPU_FORCE_AVX512_CNL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CNL 0 -# define CV_CPU_CALL_AVX512_CNL(fn, args) -# define CV_CPU_CALL_AVX512_CNL_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_CNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_CNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CLX -# define CV_TRY_AVX512_CLX 1 -# define CV_CPU_FORCE_AVX512_CLX 1 -# define CV_CPU_HAS_SUPPORT_AVX512_CLX 1 -# define CV_CPU_CALL_AVX512_CLX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_CLX_(fn, args) return (opt_AVX512_CLX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CLX -# define CV_TRY_AVX512_CLX 1 -# define CV_CPU_FORCE_AVX512_CLX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CLX (cv::checkHardwareSupport(CV_CPU_AVX512_CLX)) -# define CV_CPU_CALL_AVX512_CLX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) -# define CV_CPU_CALL_AVX512_CLX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) -#else -# define CV_TRY_AVX512_CLX 0 -# define CV_CPU_FORCE_AVX512_CLX 0 -# define CV_CPU_HAS_SUPPORT_AVX512_CLX 0 -# define CV_CPU_CALL_AVX512_CLX(fn, args) -# define CV_CPU_CALL_AVX512_CLX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_CLX(fn, args, mode, ...) CV_CPU_CALL_AVX512_CLX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_ICL -# define CV_TRY_AVX512_ICL 1 -# define CV_CPU_FORCE_AVX512_ICL 1 -# define CV_CPU_HAS_SUPPORT_AVX512_ICL 1 -# define CV_CPU_CALL_AVX512_ICL(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_AVX512_ICL_(fn, args) return (opt_AVX512_ICL::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_ICL -# define CV_TRY_AVX512_ICL 1 -# define CV_CPU_FORCE_AVX512_ICL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_ICL (cv::checkHardwareSupport(CV_CPU_AVX512_ICL)) -# define CV_CPU_CALL_AVX512_ICL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) -# define CV_CPU_CALL_AVX512_ICL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) -#else -# define CV_TRY_AVX512_ICL 0 -# define CV_CPU_FORCE_AVX512_ICL 0 -# define CV_CPU_HAS_SUPPORT_AVX512_ICL 0 -# define CV_CPU_CALL_AVX512_ICL(fn, args) -# define CV_CPU_CALL_AVX512_ICL_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_AVX512_ICL(fn, args, mode, ...) CV_CPU_CALL_AVX512_ICL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON -# define CV_TRY_NEON 1 -# define CV_CPU_FORCE_NEON 1 -# define CV_CPU_HAS_SUPPORT_NEON 1 -# define CV_CPU_CALL_NEON(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_(fn, args) return (opt_NEON::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON -# define CV_TRY_NEON 1 -# define CV_CPU_FORCE_NEON 0 -# define CV_CPU_HAS_SUPPORT_NEON (cv::checkHardwareSupport(CV_CPU_NEON)) -# define CV_CPU_CALL_NEON(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) -# define CV_CPU_CALL_NEON_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) -#else -# define CV_TRY_NEON 0 -# define CV_CPU_FORCE_NEON 0 -# define CV_CPU_HAS_SUPPORT_NEON 0 -# define CV_CPU_CALL_NEON(fn, args) -# define CV_CPU_CALL_NEON_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON(fn, args, mode, ...) CV_CPU_CALL_NEON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_DOTPROD -# define CV_TRY_NEON_DOTPROD 1 -# define CV_CPU_FORCE_NEON_DOTPROD 1 -# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 1 -# define CV_CPU_CALL_NEON_DOTPROD(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) return (opt_NEON_DOTPROD::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_DOTPROD -# define CV_TRY_NEON_DOTPROD 1 -# define CV_CPU_FORCE_NEON_DOTPROD 0 -# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD (cv::checkHardwareSupport(CV_CPU_NEON_DOTPROD)) -# define CV_CPU_CALL_NEON_DOTPROD(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) -# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) -#else -# define CV_TRY_NEON_DOTPROD 0 -# define CV_CPU_FORCE_NEON_DOTPROD 0 -# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 0 -# define CV_CPU_CALL_NEON_DOTPROD(fn, args) -# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON_DOTPROD(fn, args, mode, ...) CV_CPU_CALL_NEON_DOTPROD(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_FP16 -# define CV_TRY_NEON_FP16 1 -# define CV_CPU_FORCE_NEON_FP16 1 -# define CV_CPU_HAS_SUPPORT_NEON_FP16 1 -# define CV_CPU_CALL_NEON_FP16(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_FP16_(fn, args) return (opt_NEON_FP16::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_FP16 -# define CV_TRY_NEON_FP16 1 -# define CV_CPU_FORCE_NEON_FP16 0 -# define CV_CPU_HAS_SUPPORT_NEON_FP16 (cv::checkHardwareSupport(CV_CPU_NEON_FP16)) -# define CV_CPU_CALL_NEON_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) -# define CV_CPU_CALL_NEON_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) -#else -# define CV_TRY_NEON_FP16 0 -# define CV_CPU_FORCE_NEON_FP16 0 -# define CV_CPU_HAS_SUPPORT_NEON_FP16 0 -# define CV_CPU_CALL_NEON_FP16(fn, args) -# define CV_CPU_CALL_NEON_FP16_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON_FP16(fn, args, mode, ...) CV_CPU_CALL_NEON_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_BF16 -# define CV_TRY_NEON_BF16 1 -# define CV_CPU_FORCE_NEON_BF16 1 -# define CV_CPU_HAS_SUPPORT_NEON_BF16 1 -# define CV_CPU_CALL_NEON_BF16(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_NEON_BF16_(fn, args) return (opt_NEON_BF16::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_BF16 -# define CV_TRY_NEON_BF16 1 -# define CV_CPU_FORCE_NEON_BF16 0 -# define CV_CPU_HAS_SUPPORT_NEON_BF16 (cv::checkHardwareSupport(CV_CPU_NEON_BF16)) -# define CV_CPU_CALL_NEON_BF16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) -# define CV_CPU_CALL_NEON_BF16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) -#else -# define CV_TRY_NEON_BF16 0 -# define CV_CPU_FORCE_NEON_BF16 0 -# define CV_CPU_HAS_SUPPORT_NEON_BF16 0 -# define CV_CPU_CALL_NEON_BF16(fn, args) -# define CV_CPU_CALL_NEON_BF16_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_NEON_BF16(fn, args, mode, ...) CV_CPU_CALL_NEON_BF16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_MSA -# define CV_TRY_MSA 1 -# define CV_CPU_FORCE_MSA 1 -# define CV_CPU_HAS_SUPPORT_MSA 1 -# define CV_CPU_CALL_MSA(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_MSA_(fn, args) return (opt_MSA::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_MSA -# define CV_TRY_MSA 1 -# define CV_CPU_FORCE_MSA 0 -# define CV_CPU_HAS_SUPPORT_MSA (cv::checkHardwareSupport(CV_CPU_MSA)) -# define CV_CPU_CALL_MSA(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) -# define CV_CPU_CALL_MSA_(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) -#else -# define CV_TRY_MSA 0 -# define CV_CPU_FORCE_MSA 0 -# define CV_CPU_HAS_SUPPORT_MSA 0 -# define CV_CPU_CALL_MSA(fn, args) -# define CV_CPU_CALL_MSA_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_MSA(fn, args, mode, ...) CV_CPU_CALL_MSA(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX -# define CV_TRY_VSX 1 -# define CV_CPU_FORCE_VSX 1 -# define CV_CPU_HAS_SUPPORT_VSX 1 -# define CV_CPU_CALL_VSX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_VSX_(fn, args) return (opt_VSX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX -# define CV_TRY_VSX 1 -# define CV_CPU_FORCE_VSX 0 -# define CV_CPU_HAS_SUPPORT_VSX (cv::checkHardwareSupport(CV_CPU_VSX)) -# define CV_CPU_CALL_VSX(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) -# define CV_CPU_CALL_VSX_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) -#else -# define CV_TRY_VSX 0 -# define CV_CPU_FORCE_VSX 0 -# define CV_CPU_HAS_SUPPORT_VSX 0 -# define CV_CPU_CALL_VSX(fn, args) -# define CV_CPU_CALL_VSX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_VSX(fn, args, mode, ...) CV_CPU_CALL_VSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX3 -# define CV_TRY_VSX3 1 -# define CV_CPU_FORCE_VSX3 1 -# define CV_CPU_HAS_SUPPORT_VSX3 1 -# define CV_CPU_CALL_VSX3(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_VSX3_(fn, args) return (opt_VSX3::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX3 -# define CV_TRY_VSX3 1 -# define CV_CPU_FORCE_VSX3 0 -# define CV_CPU_HAS_SUPPORT_VSX3 (cv::checkHardwareSupport(CV_CPU_VSX3)) -# define CV_CPU_CALL_VSX3(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) -# define CV_CPU_CALL_VSX3_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) -#else -# define CV_TRY_VSX3 0 -# define CV_CPU_FORCE_VSX3 0 -# define CV_CPU_HAS_SUPPORT_VSX3 0 -# define CV_CPU_CALL_VSX3(fn, args) -# define CV_CPU_CALL_VSX3_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_VSX3(fn, args, mode, ...) CV_CPU_CALL_VSX3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_RVV -# define CV_TRY_RVV 1 -# define CV_CPU_FORCE_RVV 1 -# define CV_CPU_HAS_SUPPORT_RVV 1 -# define CV_CPU_CALL_RVV(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_RVV_(fn, args) return (opt_RVV::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_RVV -# define CV_TRY_RVV 1 -# define CV_CPU_FORCE_RVV 0 -# define CV_CPU_HAS_SUPPORT_RVV (cv::checkHardwareSupport(CV_CPU_RVV)) -# define CV_CPU_CALL_RVV(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) -# define CV_CPU_CALL_RVV_(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) -#else -# define CV_TRY_RVV 0 -# define CV_CPU_FORCE_RVV 0 -# define CV_CPU_HAS_SUPPORT_RVV 0 -# define CV_CPU_CALL_RVV(fn, args) -# define CV_CPU_CALL_RVV_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_RVV(fn, args, mode, ...) CV_CPU_CALL_RVV(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LSX -# define CV_TRY_LSX 1 -# define CV_CPU_FORCE_LSX 1 -# define CV_CPU_HAS_SUPPORT_LSX 1 -# define CV_CPU_CALL_LSX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_LSX_(fn, args) return (opt_LSX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LSX -# define CV_TRY_LSX 1 -# define CV_CPU_FORCE_LSX 0 -# define CV_CPU_HAS_SUPPORT_LSX (cv::checkHardwareSupport(CV_CPU_LSX)) -# define CV_CPU_CALL_LSX(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) -# define CV_CPU_CALL_LSX_(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) -#else -# define CV_TRY_LSX 0 -# define CV_CPU_FORCE_LSX 0 -# define CV_CPU_HAS_SUPPORT_LSX 0 -# define CV_CPU_CALL_LSX(fn, args) -# define CV_CPU_CALL_LSX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_LSX(fn, args, mode, ...) CV_CPU_CALL_LSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LASX -# define CV_TRY_LASX 1 -# define CV_CPU_FORCE_LASX 1 -# define CV_CPU_HAS_SUPPORT_LASX 1 -# define CV_CPU_CALL_LASX(fn, args) return (cpu_baseline::fn args) -# define CV_CPU_CALL_LASX_(fn, args) return (opt_LASX::fn args) -#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LASX -# define CV_TRY_LASX 1 -# define CV_CPU_FORCE_LASX 0 -# define CV_CPU_HAS_SUPPORT_LASX (cv::checkHardwareSupport(CV_CPU_LASX)) -# define CV_CPU_CALL_LASX(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) -# define CV_CPU_CALL_LASX_(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) -#else -# define CV_TRY_LASX 0 -# define CV_CPU_FORCE_LASX 0 -# define CV_CPU_HAS_SUPPORT_LASX 0 -# define CV_CPU_CALL_LASX(fn, args) -# define CV_CPU_CALL_LASX_(fn, args) -#endif -#define __CV_CPU_DISPATCH_CHAIN_LASX(fn, args, mode, ...) CV_CPU_CALL_LASX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) - -#define CV_CPU_CALL_BASELINE(fn, args) return (cpu_baseline::fn args) -#define __CV_CPU_DISPATCH_CHAIN_BASELINE(fn, args, mode, ...) CV_CPU_CALL_BASELINE(fn, args) /* last in sequence */ +// AUTOGENERATED, DO NOT EDIT + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE +# define CV_TRY_SSE 1 +# define CV_CPU_FORCE_SSE 1 +# define CV_CPU_HAS_SUPPORT_SSE 1 +# define CV_CPU_CALL_SSE(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE_(fn, args) return (opt_SSE::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE +# define CV_TRY_SSE 1 +# define CV_CPU_FORCE_SSE 0 +# define CV_CPU_HAS_SUPPORT_SSE (cv::checkHardwareSupport(CV_CPU_SSE)) +# define CV_CPU_CALL_SSE(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) +# define CV_CPU_CALL_SSE_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE) return (opt_SSE::fn args) +#else +# define CV_TRY_SSE 0 +# define CV_CPU_FORCE_SSE 0 +# define CV_CPU_HAS_SUPPORT_SSE 0 +# define CV_CPU_CALL_SSE(fn, args) +# define CV_CPU_CALL_SSE_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE(fn, args, mode, ...) CV_CPU_CALL_SSE(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE2 +# define CV_TRY_SSE2 1 +# define CV_CPU_FORCE_SSE2 1 +# define CV_CPU_HAS_SUPPORT_SSE2 1 +# define CV_CPU_CALL_SSE2(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE2_(fn, args) return (opt_SSE2::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE2 +# define CV_TRY_SSE2 1 +# define CV_CPU_FORCE_SSE2 0 +# define CV_CPU_HAS_SUPPORT_SSE2 (cv::checkHardwareSupport(CV_CPU_SSE2)) +# define CV_CPU_CALL_SSE2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) +# define CV_CPU_CALL_SSE2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE2) return (opt_SSE2::fn args) +#else +# define CV_TRY_SSE2 0 +# define CV_CPU_FORCE_SSE2 0 +# define CV_CPU_HAS_SUPPORT_SSE2 0 +# define CV_CPU_CALL_SSE2(fn, args) +# define CV_CPU_CALL_SSE2_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE2(fn, args, mode, ...) CV_CPU_CALL_SSE2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE3 +# define CV_TRY_SSE3 1 +# define CV_CPU_FORCE_SSE3 1 +# define CV_CPU_HAS_SUPPORT_SSE3 1 +# define CV_CPU_CALL_SSE3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE3_(fn, args) return (opt_SSE3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE3 +# define CV_TRY_SSE3 1 +# define CV_CPU_FORCE_SSE3 0 +# define CV_CPU_HAS_SUPPORT_SSE3 (cv::checkHardwareSupport(CV_CPU_SSE3)) +# define CV_CPU_CALL_SSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) +# define CV_CPU_CALL_SSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE3) return (opt_SSE3::fn args) +#else +# define CV_TRY_SSE3 0 +# define CV_CPU_FORCE_SSE3 0 +# define CV_CPU_HAS_SUPPORT_SSE3 0 +# define CV_CPU_CALL_SSE3(fn, args) +# define CV_CPU_CALL_SSE3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE3(fn, args, mode, ...) CV_CPU_CALL_SSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSSE3 +# define CV_TRY_SSSE3 1 +# define CV_CPU_FORCE_SSSE3 1 +# define CV_CPU_HAS_SUPPORT_SSSE3 1 +# define CV_CPU_CALL_SSSE3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSSE3_(fn, args) return (opt_SSSE3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSSE3 +# define CV_TRY_SSSE3 1 +# define CV_CPU_FORCE_SSSE3 0 +# define CV_CPU_HAS_SUPPORT_SSSE3 (cv::checkHardwareSupport(CV_CPU_SSSE3)) +# define CV_CPU_CALL_SSSE3(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) +# define CV_CPU_CALL_SSSE3_(fn, args) if (CV_CPU_HAS_SUPPORT_SSSE3) return (opt_SSSE3::fn args) +#else +# define CV_TRY_SSSE3 0 +# define CV_CPU_FORCE_SSSE3 0 +# define CV_CPU_HAS_SUPPORT_SSSE3 0 +# define CV_CPU_CALL_SSSE3(fn, args) +# define CV_CPU_CALL_SSSE3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSSE3(fn, args, mode, ...) CV_CPU_CALL_SSSE3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_1 +# define CV_TRY_SSE4_1 1 +# define CV_CPU_FORCE_SSE4_1 1 +# define CV_CPU_HAS_SUPPORT_SSE4_1 1 +# define CV_CPU_CALL_SSE4_1(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE4_1_(fn, args) return (opt_SSE4_1::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_1 +# define CV_TRY_SSE4_1 1 +# define CV_CPU_FORCE_SSE4_1 0 +# define CV_CPU_HAS_SUPPORT_SSE4_1 (cv::checkHardwareSupport(CV_CPU_SSE4_1)) +# define CV_CPU_CALL_SSE4_1(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) +# define CV_CPU_CALL_SSE4_1_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_1) return (opt_SSE4_1::fn args) +#else +# define CV_TRY_SSE4_1 0 +# define CV_CPU_FORCE_SSE4_1 0 +# define CV_CPU_HAS_SUPPORT_SSE4_1 0 +# define CV_CPU_CALL_SSE4_1(fn, args) +# define CV_CPU_CALL_SSE4_1_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE4_1(fn, args, mode, ...) CV_CPU_CALL_SSE4_1(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_SSE4_2 +# define CV_TRY_SSE4_2 1 +# define CV_CPU_FORCE_SSE4_2 1 +# define CV_CPU_HAS_SUPPORT_SSE4_2 1 +# define CV_CPU_CALL_SSE4_2(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_SSE4_2_(fn, args) return (opt_SSE4_2::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_SSE4_2 +# define CV_TRY_SSE4_2 1 +# define CV_CPU_FORCE_SSE4_2 0 +# define CV_CPU_HAS_SUPPORT_SSE4_2 (cv::checkHardwareSupport(CV_CPU_SSE4_2)) +# define CV_CPU_CALL_SSE4_2(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) +# define CV_CPU_CALL_SSE4_2_(fn, args) if (CV_CPU_HAS_SUPPORT_SSE4_2) return (opt_SSE4_2::fn args) +#else +# define CV_TRY_SSE4_2 0 +# define CV_CPU_FORCE_SSE4_2 0 +# define CV_CPU_HAS_SUPPORT_SSE4_2 0 +# define CV_CPU_CALL_SSE4_2(fn, args) +# define CV_CPU_CALL_SSE4_2_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_SSE4_2(fn, args, mode, ...) CV_CPU_CALL_SSE4_2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_POPCNT +# define CV_TRY_POPCNT 1 +# define CV_CPU_FORCE_POPCNT 1 +# define CV_CPU_HAS_SUPPORT_POPCNT 1 +# define CV_CPU_CALL_POPCNT(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_POPCNT_(fn, args) return (opt_POPCNT::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_POPCNT +# define CV_TRY_POPCNT 1 +# define CV_CPU_FORCE_POPCNT 0 +# define CV_CPU_HAS_SUPPORT_POPCNT (cv::checkHardwareSupport(CV_CPU_POPCNT)) +# define CV_CPU_CALL_POPCNT(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) +# define CV_CPU_CALL_POPCNT_(fn, args) if (CV_CPU_HAS_SUPPORT_POPCNT) return (opt_POPCNT::fn args) +#else +# define CV_TRY_POPCNT 0 +# define CV_CPU_FORCE_POPCNT 0 +# define CV_CPU_HAS_SUPPORT_POPCNT 0 +# define CV_CPU_CALL_POPCNT(fn, args) +# define CV_CPU_CALL_POPCNT_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_POPCNT(fn, args, mode, ...) CV_CPU_CALL_POPCNT(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX +# define CV_TRY_AVX 1 +# define CV_CPU_FORCE_AVX 1 +# define CV_CPU_HAS_SUPPORT_AVX 1 +# define CV_CPU_CALL_AVX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX_(fn, args) return (opt_AVX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX +# define CV_TRY_AVX 1 +# define CV_CPU_FORCE_AVX 0 +# define CV_CPU_HAS_SUPPORT_AVX (cv::checkHardwareSupport(CV_CPU_AVX)) +# define CV_CPU_CALL_AVX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) +# define CV_CPU_CALL_AVX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX) return (opt_AVX::fn args) +#else +# define CV_TRY_AVX 0 +# define CV_CPU_FORCE_AVX 0 +# define CV_CPU_HAS_SUPPORT_AVX 0 +# define CV_CPU_CALL_AVX(fn, args) +# define CV_CPU_CALL_AVX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX(fn, args, mode, ...) CV_CPU_CALL_AVX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FP16 +# define CV_TRY_FP16 1 +# define CV_CPU_FORCE_FP16 1 +# define CV_CPU_HAS_SUPPORT_FP16 1 +# define CV_CPU_CALL_FP16(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_FP16_(fn, args) return (opt_FP16::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FP16 +# define CV_TRY_FP16 1 +# define CV_CPU_FORCE_FP16 0 +# define CV_CPU_HAS_SUPPORT_FP16 (cv::checkHardwareSupport(CV_CPU_FP16)) +# define CV_CPU_CALL_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) +# define CV_CPU_CALL_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_FP16) return (opt_FP16::fn args) +#else +# define CV_TRY_FP16 0 +# define CV_CPU_FORCE_FP16 0 +# define CV_CPU_HAS_SUPPORT_FP16 0 +# define CV_CPU_CALL_FP16(fn, args) +# define CV_CPU_CALL_FP16_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_FP16(fn, args, mode, ...) CV_CPU_CALL_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX2 +# define CV_TRY_AVX2 1 +# define CV_CPU_FORCE_AVX2 1 +# define CV_CPU_HAS_SUPPORT_AVX2 1 +# define CV_CPU_CALL_AVX2(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX2_(fn, args) return (opt_AVX2::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX2 +# define CV_TRY_AVX2 1 +# define CV_CPU_FORCE_AVX2 0 +# define CV_CPU_HAS_SUPPORT_AVX2 (cv::checkHardwareSupport(CV_CPU_AVX2)) +# define CV_CPU_CALL_AVX2(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) +# define CV_CPU_CALL_AVX2_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX2) return (opt_AVX2::fn args) +#else +# define CV_TRY_AVX2 0 +# define CV_CPU_FORCE_AVX2 0 +# define CV_CPU_HAS_SUPPORT_AVX2 0 +# define CV_CPU_CALL_AVX2(fn, args) +# define CV_CPU_CALL_AVX2_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX2(fn, args, mode, ...) CV_CPU_CALL_AVX2(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_FMA3 +# define CV_TRY_FMA3 1 +# define CV_CPU_FORCE_FMA3 1 +# define CV_CPU_HAS_SUPPORT_FMA3 1 +# define CV_CPU_CALL_FMA3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_FMA3_(fn, args) return (opt_FMA3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_FMA3 +# define CV_TRY_FMA3 1 +# define CV_CPU_FORCE_FMA3 0 +# define CV_CPU_HAS_SUPPORT_FMA3 (cv::checkHardwareSupport(CV_CPU_FMA3)) +# define CV_CPU_CALL_FMA3(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) +# define CV_CPU_CALL_FMA3_(fn, args) if (CV_CPU_HAS_SUPPORT_FMA3) return (opt_FMA3::fn args) +#else +# define CV_TRY_FMA3 0 +# define CV_CPU_FORCE_FMA3 0 +# define CV_CPU_HAS_SUPPORT_FMA3 0 +# define CV_CPU_CALL_FMA3(fn, args) +# define CV_CPU_CALL_FMA3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_FMA3(fn, args, mode, ...) CV_CPU_CALL_FMA3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX_512F +# define CV_TRY_AVX_512F 1 +# define CV_CPU_FORCE_AVX_512F 1 +# define CV_CPU_HAS_SUPPORT_AVX_512F 1 +# define CV_CPU_CALL_AVX_512F(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX_512F_(fn, args) return (opt_AVX_512F::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX_512F +# define CV_TRY_AVX_512F 1 +# define CV_CPU_FORCE_AVX_512F 0 +# define CV_CPU_HAS_SUPPORT_AVX_512F (cv::checkHardwareSupport(CV_CPU_AVX_512F)) +# define CV_CPU_CALL_AVX_512F(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) +# define CV_CPU_CALL_AVX_512F_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX_512F) return (opt_AVX_512F::fn args) +#else +# define CV_TRY_AVX_512F 0 +# define CV_CPU_FORCE_AVX_512F 0 +# define CV_CPU_HAS_SUPPORT_AVX_512F 0 +# define CV_CPU_CALL_AVX_512F(fn, args) +# define CV_CPU_CALL_AVX_512F_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX_512F(fn, args, mode, ...) CV_CPU_CALL_AVX_512F(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_COMMON +# define CV_TRY_AVX512_COMMON 1 +# define CV_CPU_FORCE_AVX512_COMMON 1 +# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 1 +# define CV_CPU_CALL_AVX512_COMMON(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_COMMON_(fn, args) return (opt_AVX512_COMMON::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_COMMON +# define CV_TRY_AVX512_COMMON 1 +# define CV_CPU_FORCE_AVX512_COMMON 0 +# define CV_CPU_HAS_SUPPORT_AVX512_COMMON (cv::checkHardwareSupport(CV_CPU_AVX512_COMMON)) +# define CV_CPU_CALL_AVX512_COMMON(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) +# define CV_CPU_CALL_AVX512_COMMON_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_COMMON) return (opt_AVX512_COMMON::fn args) +#else +# define CV_TRY_AVX512_COMMON 0 +# define CV_CPU_FORCE_AVX512_COMMON 0 +# define CV_CPU_HAS_SUPPORT_AVX512_COMMON 0 +# define CV_CPU_CALL_AVX512_COMMON(fn, args) +# define CV_CPU_CALL_AVX512_COMMON_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_COMMON(fn, args, mode, ...) CV_CPU_CALL_AVX512_COMMON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNL +# define CV_TRY_AVX512_KNL 1 +# define CV_CPU_FORCE_AVX512_KNL 1 +# define CV_CPU_HAS_SUPPORT_AVX512_KNL 1 +# define CV_CPU_CALL_AVX512_KNL(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_KNL_(fn, args) return (opt_AVX512_KNL::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNL +# define CV_TRY_AVX512_KNL 1 +# define CV_CPU_FORCE_AVX512_KNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNL (cv::checkHardwareSupport(CV_CPU_AVX512_KNL)) +# define CV_CPU_CALL_AVX512_KNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) +# define CV_CPU_CALL_AVX512_KNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNL) return (opt_AVX512_KNL::fn args) +#else +# define CV_TRY_AVX512_KNL 0 +# define CV_CPU_FORCE_AVX512_KNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNL 0 +# define CV_CPU_CALL_AVX512_KNL(fn, args) +# define CV_CPU_CALL_AVX512_KNL_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_KNM +# define CV_TRY_AVX512_KNM 1 +# define CV_CPU_FORCE_AVX512_KNM 1 +# define CV_CPU_HAS_SUPPORT_AVX512_KNM 1 +# define CV_CPU_CALL_AVX512_KNM(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_KNM_(fn, args) return (opt_AVX512_KNM::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_KNM +# define CV_TRY_AVX512_KNM 1 +# define CV_CPU_FORCE_AVX512_KNM 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNM (cv::checkHardwareSupport(CV_CPU_AVX512_KNM)) +# define CV_CPU_CALL_AVX512_KNM(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) +# define CV_CPU_CALL_AVX512_KNM_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_KNM) return (opt_AVX512_KNM::fn args) +#else +# define CV_TRY_AVX512_KNM 0 +# define CV_CPU_FORCE_AVX512_KNM 0 +# define CV_CPU_HAS_SUPPORT_AVX512_KNM 0 +# define CV_CPU_CALL_AVX512_KNM(fn, args) +# define CV_CPU_CALL_AVX512_KNM_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_KNM(fn, args, mode, ...) CV_CPU_CALL_AVX512_KNM(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_SKX +# define CV_TRY_AVX512_SKX 1 +# define CV_CPU_FORCE_AVX512_SKX 1 +# define CV_CPU_HAS_SUPPORT_AVX512_SKX 1 +# define CV_CPU_CALL_AVX512_SKX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_SKX_(fn, args) return (opt_AVX512_SKX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_SKX +# define CV_TRY_AVX512_SKX 1 +# define CV_CPU_FORCE_AVX512_SKX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_SKX (cv::checkHardwareSupport(CV_CPU_AVX512_SKX)) +# define CV_CPU_CALL_AVX512_SKX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) +# define CV_CPU_CALL_AVX512_SKX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_SKX) return (opt_AVX512_SKX::fn args) +#else +# define CV_TRY_AVX512_SKX 0 +# define CV_CPU_FORCE_AVX512_SKX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_SKX 0 +# define CV_CPU_CALL_AVX512_SKX(fn, args) +# define CV_CPU_CALL_AVX512_SKX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_SKX(fn, args, mode, ...) CV_CPU_CALL_AVX512_SKX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CNL +# define CV_TRY_AVX512_CNL 1 +# define CV_CPU_FORCE_AVX512_CNL 1 +# define CV_CPU_HAS_SUPPORT_AVX512_CNL 1 +# define CV_CPU_CALL_AVX512_CNL(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_CNL_(fn, args) return (opt_AVX512_CNL::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CNL +# define CV_TRY_AVX512_CNL 1 +# define CV_CPU_FORCE_AVX512_CNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CNL (cv::checkHardwareSupport(CV_CPU_AVX512_CNL)) +# define CV_CPU_CALL_AVX512_CNL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) +# define CV_CPU_CALL_AVX512_CNL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CNL) return (opt_AVX512_CNL::fn args) +#else +# define CV_TRY_AVX512_CNL 0 +# define CV_CPU_FORCE_AVX512_CNL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CNL 0 +# define CV_CPU_CALL_AVX512_CNL(fn, args) +# define CV_CPU_CALL_AVX512_CNL_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_CNL(fn, args, mode, ...) CV_CPU_CALL_AVX512_CNL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_CLX +# define CV_TRY_AVX512_CLX 1 +# define CV_CPU_FORCE_AVX512_CLX 1 +# define CV_CPU_HAS_SUPPORT_AVX512_CLX 1 +# define CV_CPU_CALL_AVX512_CLX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_CLX_(fn, args) return (opt_AVX512_CLX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_CLX +# define CV_TRY_AVX512_CLX 1 +# define CV_CPU_FORCE_AVX512_CLX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CLX (cv::checkHardwareSupport(CV_CPU_AVX512_CLX)) +# define CV_CPU_CALL_AVX512_CLX(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) +# define CV_CPU_CALL_AVX512_CLX_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_CLX) return (opt_AVX512_CLX::fn args) +#else +# define CV_TRY_AVX512_CLX 0 +# define CV_CPU_FORCE_AVX512_CLX 0 +# define CV_CPU_HAS_SUPPORT_AVX512_CLX 0 +# define CV_CPU_CALL_AVX512_CLX(fn, args) +# define CV_CPU_CALL_AVX512_CLX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_CLX(fn, args, mode, ...) CV_CPU_CALL_AVX512_CLX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_AVX512_ICL +# define CV_TRY_AVX512_ICL 1 +# define CV_CPU_FORCE_AVX512_ICL 1 +# define CV_CPU_HAS_SUPPORT_AVX512_ICL 1 +# define CV_CPU_CALL_AVX512_ICL(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_AVX512_ICL_(fn, args) return (opt_AVX512_ICL::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_AVX512_ICL +# define CV_TRY_AVX512_ICL 1 +# define CV_CPU_FORCE_AVX512_ICL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_ICL (cv::checkHardwareSupport(CV_CPU_AVX512_ICL)) +# define CV_CPU_CALL_AVX512_ICL(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) +# define CV_CPU_CALL_AVX512_ICL_(fn, args) if (CV_CPU_HAS_SUPPORT_AVX512_ICL) return (opt_AVX512_ICL::fn args) +#else +# define CV_TRY_AVX512_ICL 0 +# define CV_CPU_FORCE_AVX512_ICL 0 +# define CV_CPU_HAS_SUPPORT_AVX512_ICL 0 +# define CV_CPU_CALL_AVX512_ICL(fn, args) +# define CV_CPU_CALL_AVX512_ICL_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_AVX512_ICL(fn, args, mode, ...) CV_CPU_CALL_AVX512_ICL(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON +# define CV_TRY_NEON 1 +# define CV_CPU_FORCE_NEON 1 +# define CV_CPU_HAS_SUPPORT_NEON 1 +# define CV_CPU_CALL_NEON(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_(fn, args) return (opt_NEON::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON +# define CV_TRY_NEON 1 +# define CV_CPU_FORCE_NEON 0 +# define CV_CPU_HAS_SUPPORT_NEON (cv::checkHardwareSupport(CV_CPU_NEON)) +# define CV_CPU_CALL_NEON(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) +# define CV_CPU_CALL_NEON_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON) return (opt_NEON::fn args) +#else +# define CV_TRY_NEON 0 +# define CV_CPU_FORCE_NEON 0 +# define CV_CPU_HAS_SUPPORT_NEON 0 +# define CV_CPU_CALL_NEON(fn, args) +# define CV_CPU_CALL_NEON_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON(fn, args, mode, ...) CV_CPU_CALL_NEON(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_DOTPROD +# define CV_TRY_NEON_DOTPROD 1 +# define CV_CPU_FORCE_NEON_DOTPROD 1 +# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 1 +# define CV_CPU_CALL_NEON_DOTPROD(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) return (opt_NEON_DOTPROD::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_DOTPROD +# define CV_TRY_NEON_DOTPROD 1 +# define CV_CPU_FORCE_NEON_DOTPROD 0 +# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD (cv::checkHardwareSupport(CV_CPU_NEON_DOTPROD)) +# define CV_CPU_CALL_NEON_DOTPROD(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) +# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_DOTPROD) return (opt_NEON_DOTPROD::fn args) +#else +# define CV_TRY_NEON_DOTPROD 0 +# define CV_CPU_FORCE_NEON_DOTPROD 0 +# define CV_CPU_HAS_SUPPORT_NEON_DOTPROD 0 +# define CV_CPU_CALL_NEON_DOTPROD(fn, args) +# define CV_CPU_CALL_NEON_DOTPROD_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON_DOTPROD(fn, args, mode, ...) CV_CPU_CALL_NEON_DOTPROD(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_FP16 +# define CV_TRY_NEON_FP16 1 +# define CV_CPU_FORCE_NEON_FP16 1 +# define CV_CPU_HAS_SUPPORT_NEON_FP16 1 +# define CV_CPU_CALL_NEON_FP16(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_FP16_(fn, args) return (opt_NEON_FP16::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_FP16 +# define CV_TRY_NEON_FP16 1 +# define CV_CPU_FORCE_NEON_FP16 0 +# define CV_CPU_HAS_SUPPORT_NEON_FP16 (cv::checkHardwareSupport(CV_CPU_NEON_FP16)) +# define CV_CPU_CALL_NEON_FP16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) +# define CV_CPU_CALL_NEON_FP16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_FP16) return (opt_NEON_FP16::fn args) +#else +# define CV_TRY_NEON_FP16 0 +# define CV_CPU_FORCE_NEON_FP16 0 +# define CV_CPU_HAS_SUPPORT_NEON_FP16 0 +# define CV_CPU_CALL_NEON_FP16(fn, args) +# define CV_CPU_CALL_NEON_FP16_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON_FP16(fn, args, mode, ...) CV_CPU_CALL_NEON_FP16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_NEON_BF16 +# define CV_TRY_NEON_BF16 1 +# define CV_CPU_FORCE_NEON_BF16 1 +# define CV_CPU_HAS_SUPPORT_NEON_BF16 1 +# define CV_CPU_CALL_NEON_BF16(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_NEON_BF16_(fn, args) return (opt_NEON_BF16::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_NEON_BF16 +# define CV_TRY_NEON_BF16 1 +# define CV_CPU_FORCE_NEON_BF16 0 +# define CV_CPU_HAS_SUPPORT_NEON_BF16 (cv::checkHardwareSupport(CV_CPU_NEON_BF16)) +# define CV_CPU_CALL_NEON_BF16(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) +# define CV_CPU_CALL_NEON_BF16_(fn, args) if (CV_CPU_HAS_SUPPORT_NEON_BF16) return (opt_NEON_BF16::fn args) +#else +# define CV_TRY_NEON_BF16 0 +# define CV_CPU_FORCE_NEON_BF16 0 +# define CV_CPU_HAS_SUPPORT_NEON_BF16 0 +# define CV_CPU_CALL_NEON_BF16(fn, args) +# define CV_CPU_CALL_NEON_BF16_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_NEON_BF16(fn, args, mode, ...) CV_CPU_CALL_NEON_BF16(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_MSA +# define CV_TRY_MSA 1 +# define CV_CPU_FORCE_MSA 1 +# define CV_CPU_HAS_SUPPORT_MSA 1 +# define CV_CPU_CALL_MSA(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_MSA_(fn, args) return (opt_MSA::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_MSA +# define CV_TRY_MSA 1 +# define CV_CPU_FORCE_MSA 0 +# define CV_CPU_HAS_SUPPORT_MSA (cv::checkHardwareSupport(CV_CPU_MSA)) +# define CV_CPU_CALL_MSA(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) +# define CV_CPU_CALL_MSA_(fn, args) if (CV_CPU_HAS_SUPPORT_MSA) return (opt_MSA::fn args) +#else +# define CV_TRY_MSA 0 +# define CV_CPU_FORCE_MSA 0 +# define CV_CPU_HAS_SUPPORT_MSA 0 +# define CV_CPU_CALL_MSA(fn, args) +# define CV_CPU_CALL_MSA_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_MSA(fn, args, mode, ...) CV_CPU_CALL_MSA(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX +# define CV_TRY_VSX 1 +# define CV_CPU_FORCE_VSX 1 +# define CV_CPU_HAS_SUPPORT_VSX 1 +# define CV_CPU_CALL_VSX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_VSX_(fn, args) return (opt_VSX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX +# define CV_TRY_VSX 1 +# define CV_CPU_FORCE_VSX 0 +# define CV_CPU_HAS_SUPPORT_VSX (cv::checkHardwareSupport(CV_CPU_VSX)) +# define CV_CPU_CALL_VSX(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) +# define CV_CPU_CALL_VSX_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX) return (opt_VSX::fn args) +#else +# define CV_TRY_VSX 0 +# define CV_CPU_FORCE_VSX 0 +# define CV_CPU_HAS_SUPPORT_VSX 0 +# define CV_CPU_CALL_VSX(fn, args) +# define CV_CPU_CALL_VSX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_VSX(fn, args, mode, ...) CV_CPU_CALL_VSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_VSX3 +# define CV_TRY_VSX3 1 +# define CV_CPU_FORCE_VSX3 1 +# define CV_CPU_HAS_SUPPORT_VSX3 1 +# define CV_CPU_CALL_VSX3(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_VSX3_(fn, args) return (opt_VSX3::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_VSX3 +# define CV_TRY_VSX3 1 +# define CV_CPU_FORCE_VSX3 0 +# define CV_CPU_HAS_SUPPORT_VSX3 (cv::checkHardwareSupport(CV_CPU_VSX3)) +# define CV_CPU_CALL_VSX3(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) +# define CV_CPU_CALL_VSX3_(fn, args) if (CV_CPU_HAS_SUPPORT_VSX3) return (opt_VSX3::fn args) +#else +# define CV_TRY_VSX3 0 +# define CV_CPU_FORCE_VSX3 0 +# define CV_CPU_HAS_SUPPORT_VSX3 0 +# define CV_CPU_CALL_VSX3(fn, args) +# define CV_CPU_CALL_VSX3_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_VSX3(fn, args, mode, ...) CV_CPU_CALL_VSX3(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_RVV +# define CV_TRY_RVV 1 +# define CV_CPU_FORCE_RVV 1 +# define CV_CPU_HAS_SUPPORT_RVV 1 +# define CV_CPU_CALL_RVV(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_RVV_(fn, args) return (opt_RVV::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_RVV +# define CV_TRY_RVV 1 +# define CV_CPU_FORCE_RVV 0 +# define CV_CPU_HAS_SUPPORT_RVV (cv::checkHardwareSupport(CV_CPU_RVV)) +# define CV_CPU_CALL_RVV(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) +# define CV_CPU_CALL_RVV_(fn, args) if (CV_CPU_HAS_SUPPORT_RVV) return (opt_RVV::fn args) +#else +# define CV_TRY_RVV 0 +# define CV_CPU_FORCE_RVV 0 +# define CV_CPU_HAS_SUPPORT_RVV 0 +# define CV_CPU_CALL_RVV(fn, args) +# define CV_CPU_CALL_RVV_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_RVV(fn, args, mode, ...) CV_CPU_CALL_RVV(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LSX +# define CV_TRY_LSX 1 +# define CV_CPU_FORCE_LSX 1 +# define CV_CPU_HAS_SUPPORT_LSX 1 +# define CV_CPU_CALL_LSX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_LSX_(fn, args) return (opt_LSX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LSX +# define CV_TRY_LSX 1 +# define CV_CPU_FORCE_LSX 0 +# define CV_CPU_HAS_SUPPORT_LSX (cv::checkHardwareSupport(CV_CPU_LSX)) +# define CV_CPU_CALL_LSX(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) +# define CV_CPU_CALL_LSX_(fn, args) if (CV_CPU_HAS_SUPPORT_LSX) return (opt_LSX::fn args) +#else +# define CV_TRY_LSX 0 +# define CV_CPU_FORCE_LSX 0 +# define CV_CPU_HAS_SUPPORT_LSX 0 +# define CV_CPU_CALL_LSX(fn, args) +# define CV_CPU_CALL_LSX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_LSX(fn, args, mode, ...) CV_CPU_CALL_LSX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#if !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_COMPILE_LASX +# define CV_TRY_LASX 1 +# define CV_CPU_FORCE_LASX 1 +# define CV_CPU_HAS_SUPPORT_LASX 1 +# define CV_CPU_CALL_LASX(fn, args) return (cpu_baseline::fn args) +# define CV_CPU_CALL_LASX_(fn, args) return (opt_LASX::fn args) +#elif !defined CV_DISABLE_OPTIMIZATION && defined CV_ENABLE_INTRINSICS && defined CV_CPU_DISPATCH_COMPILE_LASX +# define CV_TRY_LASX 1 +# define CV_CPU_FORCE_LASX 0 +# define CV_CPU_HAS_SUPPORT_LASX (cv::checkHardwareSupport(CV_CPU_LASX)) +# define CV_CPU_CALL_LASX(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) +# define CV_CPU_CALL_LASX_(fn, args) if (CV_CPU_HAS_SUPPORT_LASX) return (opt_LASX::fn args) +#else +# define CV_TRY_LASX 0 +# define CV_CPU_FORCE_LASX 0 +# define CV_CPU_HAS_SUPPORT_LASX 0 +# define CV_CPU_CALL_LASX(fn, args) +# define CV_CPU_CALL_LASX_(fn, args) +#endif +#define __CV_CPU_DISPATCH_CHAIN_LASX(fn, args, mode, ...) CV_CPU_CALL_LASX(fn, args); __CV_EXPAND(__CV_CPU_DISPATCH_CHAIN_ ## mode(fn, args, __VA_ARGS__)) + +#define CV_CPU_CALL_BASELINE(fn, args) return (cpu_baseline::fn args) +#define __CV_CPU_DISPATCH_CHAIN_BASELINE(fn, args, mode, ...) CV_CPU_CALL_BASELINE(fn, args) /* last in sequence */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h b/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h index 002a60f4d2..0e6d6ff49b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvdef.h @@ -1,948 +1,948 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CVDEF_H -#define OPENCV_CORE_CVDEF_H - -#include "opencv2/core/version.hpp" - -//! @addtogroup core_utils -//! @{ - -#ifdef OPENCV_INCLUDE_PORT_FILE // User-provided header file with custom platform configuration -#include OPENCV_INCLUDE_PORT_FILE -#endif - -#if !defined CV_DOXYGEN && !defined CV_IGNORE_DEBUG_BUILD_GUARD -#if (defined(_MSC_VER) && (defined(DEBUG) || defined(_DEBUG))) || \ - (defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_DEBUG_PEDANTIC)) -// Guard to prevent using of binary incompatible binaries / runtimes -// https://github.com/opencv/opencv/pull/9161 -#define CV__DEBUG_NS_BEGIN namespace debug_build_guard { -#define CV__DEBUG_NS_END } -namespace cv { namespace debug_build_guard { } using namespace debug_build_guard; } -#endif -#endif - -#ifndef CV__DEBUG_NS_BEGIN -#define CV__DEBUG_NS_BEGIN -#define CV__DEBUG_NS_END -#endif - - -#ifdef __OPENCV_BUILD -#include "cvconfig.h" -#endif - -#ifndef __CV_EXPAND -#define __CV_EXPAND(x) x -#endif - -#ifndef __CV_CAT -#define __CV_CAT__(x, y) x ## y -#define __CV_CAT_(x, y) __CV_CAT__(x, y) -#define __CV_CAT(x, y) __CV_CAT_(x, y) -#endif - -#define __CV_VA_NUM_ARGS_HELPER(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N -#define __CV_VA_NUM_ARGS(...) __CV_EXPAND(__CV_VA_NUM_ARGS_HELPER(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) - -#ifdef CV_Func -// keep current value (through OpenCV port file) -#elif defined __GNUC__ || (defined (__cpluscplus) && (__cpluscplus >= 201103)) -#define CV_Func __func__ -#elif defined __clang__ && (__clang_minor__ * 100 + __clang_major__ >= 305) -#define CV_Func __func__ -#elif defined(__STDC_VERSION__) && (__STDC_VERSION >= 199901) -#define CV_Func __func__ -#elif defined _MSC_VER -#define CV_Func __FUNCTION__ -#elif defined(__INTEL_COMPILER) && (_INTEL_COMPILER >= 600) -#define CV_Func __FUNCTION__ -#elif defined __IBMCPP__ && __IBMCPP__ >=500 -#define CV_Func __FUNCTION__ -#elif defined __BORLAND__ && (__BORLANDC__ >= 0x550) -#define CV_Func __FUNC__ -#else -#define CV_Func "" -#endif - -//! @cond IGNORED - -//////////////// static assert ///////////////// -#define CVAUX_CONCAT_EXP(a, b) a##b -#define CVAUX_CONCAT(a, b) CVAUX_CONCAT_EXP(a,b) - -#if defined(__clang__) -# ifndef __has_extension -# define __has_extension __has_feature /* compatibility, for older versions of clang */ -# endif -# if __has_extension(cxx_static_assert) -# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) -# elif __has_extension(c_static_assert) -# define CV_StaticAssert(condition, reason) _Static_assert((condition), reason " " #condition) -# endif -#elif defined(__GNUC__) -# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) -# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) -# endif -#elif defined(_MSC_VER) -# if _MSC_VER >= 1600 /* MSVC 10 */ -# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) -# endif -#endif -#ifndef CV_StaticAssert -# if !defined(__clang__) && defined(__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 302) -# define CV_StaticAssert(condition, reason) ({ extern int __attribute__((error("CV_StaticAssert: " reason " " #condition))) CV_StaticAssert(); ((condition) ? 0 : CV_StaticAssert()); }) -# else -namespace cv { - template struct CV_StaticAssert_failed; - template <> struct CV_StaticAssert_failed { enum { val = 1 }; }; - template struct CV_StaticAssert_test {}; -} -# define CV_StaticAssert(condition, reason)\ - typedef cv::CV_StaticAssert_test< sizeof(cv::CV_StaticAssert_failed< static_cast(condition) >) > CVAUX_CONCAT(CV_StaticAssert_failed_at_, __LINE__) -# endif -#endif - -// Suppress warning "-Wdeprecated-declarations" / C4996 -#if defined(_MSC_VER) - #define CV_DO_PRAGMA(x) __pragma(x) -#elif defined(__GNUC__) - #define CV_DO_PRAGMA(x) _Pragma (#x) -#else - #define CV_DO_PRAGMA(x) -#endif - -#ifdef _MSC_VER -#define CV_SUPPRESS_DEPRECATED_START \ - CV_DO_PRAGMA(warning(push)) \ - CV_DO_PRAGMA(warning(disable: 4996)) -#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(warning(pop)) -#elif defined (__clang__) || ((__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 405)) -#define CV_SUPPRESS_DEPRECATED_START \ - CV_DO_PRAGMA(GCC diagnostic push) \ - CV_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations") -#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(GCC diagnostic pop) -#else -#define CV_SUPPRESS_DEPRECATED_START -#define CV_SUPPRESS_DEPRECATED_END -#endif - -#define CV_UNUSED(name) (void)name - -//! @endcond - -// undef problematic defines sometimes defined by system headers (windows.h in particular) -#undef small -#undef min -#undef max -#undef abs -#undef Complex - -#if defined __cplusplus -#include -#else -#include -#endif - -#include "opencv2/core/hal/interface.h" - -#if defined __ICL -# define CV_ICC __ICL -#elif defined __ICC -# define CV_ICC __ICC -#elif defined __ECL -# define CV_ICC __ECL -#elif defined __ECC -# define CV_ICC __ECC -#elif defined __INTEL_COMPILER -# define CV_ICC __INTEL_COMPILER -#endif - -#if defined _WIN32 -# define CV_CDECL __cdecl -# define CV_STDCALL __stdcall -#else -# define CV_CDECL -# define CV_STDCALL -#endif - -#ifndef CV_INLINE -# if defined __cplusplus -# define CV_INLINE static inline -# elif defined _MSC_VER -# define CV_INLINE __inline -# else -# define CV_INLINE static -# endif -#endif - -#ifndef CV_ALWAYS_INLINE -#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -#define CV_ALWAYS_INLINE inline __attribute__((always_inline)) -#elif defined(_MSC_VER) -#define CV_ALWAYS_INLINE __forceinline -#else -#define CV_ALWAYS_INLINE inline -#endif -#endif - -#if defined CV_DISABLE_OPTIMIZATION || (defined CV_ICC && !defined CV_ENABLE_UNROLLED) -# define CV_ENABLE_UNROLLED 0 -#else -# define CV_ENABLE_UNROLLED 1 -#endif - -#ifdef __GNUC__ -# define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) -#elif defined _MSC_VER -# define CV_DECL_ALIGNED(x) __declspec(align(x)) -#else -# define CV_DECL_ALIGNED(x) -#endif - -/* CPU features and intrinsics support */ -#define CV_CPU_NONE 0 -#define CV_CPU_MMX 1 -#define CV_CPU_SSE 2 -#define CV_CPU_SSE2 3 -#define CV_CPU_SSE3 4 -#define CV_CPU_SSSE3 5 -#define CV_CPU_SSE4_1 6 -#define CV_CPU_SSE4_2 7 -#define CV_CPU_POPCNT 8 -#define CV_CPU_FP16 9 -#define CV_CPU_AVX 10 -#define CV_CPU_AVX2 11 -#define CV_CPU_FMA3 12 - -#define CV_CPU_AVX_512F 13 -#define CV_CPU_AVX_512BW 14 -#define CV_CPU_AVX_512CD 15 -#define CV_CPU_AVX_512DQ 16 -#define CV_CPU_AVX_512ER 17 -#define CV_CPU_AVX_512IFMA512 18 // deprecated -#define CV_CPU_AVX_512IFMA 18 -#define CV_CPU_AVX_512PF 19 -#define CV_CPU_AVX_512VBMI 20 -#define CV_CPU_AVX_512VL 21 -#define CV_CPU_AVX_512VBMI2 22 -#define CV_CPU_AVX_512VNNI 23 -#define CV_CPU_AVX_512BITALG 24 -#define CV_CPU_AVX_512VPOPCNTDQ 25 -#define CV_CPU_AVX_5124VNNIW 26 -#define CV_CPU_AVX_5124FMAPS 27 - -#define CV_CPU_NEON 100 -#define CV_CPU_NEON_DOTPROD 101 -#define CV_CPU_NEON_FP16 102 -#define CV_CPU_NEON_BF16 103 - -#define CV_CPU_MSA 150 - -#define CV_CPU_RISCVV 170 - -#define CV_CPU_VSX 200 -#define CV_CPU_VSX3 201 - -#define CV_CPU_RVV 210 - -#define CV_CPU_LSX 230 -#define CV_CPU_LASX 231 - -// CPU features groups -#define CV_CPU_AVX512_SKX 256 -#define CV_CPU_AVX512_COMMON 257 -#define CV_CPU_AVX512_KNL 258 -#define CV_CPU_AVX512_KNM 259 -#define CV_CPU_AVX512_CNL 260 -#define CV_CPU_AVX512_CLX 261 -#define CV_CPU_AVX512_ICL 262 - -// when adding to this list remember to update the following enum -#define CV_HARDWARE_MAX_FEATURE 512 - -/** @brief Available CPU features. -*/ -enum CpuFeatures { - CPU_MMX = 1, - CPU_SSE = 2, - CPU_SSE2 = 3, - CPU_SSE3 = 4, - CPU_SSSE3 = 5, - CPU_SSE4_1 = 6, - CPU_SSE4_2 = 7, - CPU_POPCNT = 8, - CPU_FP16 = 9, - CPU_AVX = 10, - CPU_AVX2 = 11, - CPU_FMA3 = 12, - - CPU_AVX_512F = 13, - CPU_AVX_512BW = 14, - CPU_AVX_512CD = 15, - CPU_AVX_512DQ = 16, - CPU_AVX_512ER = 17, - CPU_AVX_512IFMA512 = 18, // deprecated - CPU_AVX_512IFMA = 18, - CPU_AVX_512PF = 19, - CPU_AVX_512VBMI = 20, - CPU_AVX_512VL = 21, - CPU_AVX_512VBMI2 = 22, - CPU_AVX_512VNNI = 23, - CPU_AVX_512BITALG = 24, - CPU_AVX_512VPOPCNTDQ= 25, - CPU_AVX_5124VNNIW = 26, - CPU_AVX_5124FMAPS = 27, - - CPU_NEON = 100, - CPU_NEON_DOTPROD = 101, - CPU_NEON_FP16 = 102, - CPU_NEON_BF16 = 103, - - CPU_MSA = 150, - - CPU_RISCVV = 170, - - CPU_VSX = 200, - CPU_VSX3 = 201, - - CPU_RVV = 210, - - CPU_LSX = 230, - CPU_LASX = 231, - - CPU_AVX512_SKX = 256, //!< Skylake-X with AVX-512F/CD/BW/DQ/VL - CPU_AVX512_COMMON = 257, //!< Common instructions AVX-512F/CD for all CPUs that support AVX-512 - CPU_AVX512_KNL = 258, //!< Knights Landing with AVX-512F/CD/ER/PF - CPU_AVX512_KNM = 259, //!< Knights Mill with AVX-512F/CD/ER/PF/4FMAPS/4VNNIW/VPOPCNTDQ - CPU_AVX512_CNL = 260, //!< Cannon Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI - CPU_AVX512_CLX = 261, //!< Cascade Lake with AVX-512F/CD/BW/DQ/VL/VNNI - CPU_AVX512_ICL = 262, //!< Ice Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI/VNNI/VBMI2/BITALG/VPOPCNTDQ - - CPU_MAX_FEATURE = 512 // see CV_HARDWARE_MAX_FEATURE -}; - - -#include "cv_cpu_dispatch.h" - -#if !defined(CV_STRONG_ALIGNMENT) && defined(__arm__) && !(defined(__aarch64__) || defined(_M_ARM64)) -// int*, int64* should be propertly aligned pointers on ARMv7 -#define CV_STRONG_ALIGNMENT 1 -#endif -#if !defined(CV_STRONG_ALIGNMENT) -#define CV_STRONG_ALIGNMENT 0 -#endif - -/* fundamental constants */ -#define CV_PI 3.1415926535897932384626433832795 -#define CV_2PI 6.283185307179586476925286766559 -#define CV_LOG2 0.69314718055994530941723212145818 - -#if defined __ARM_FP16_FORMAT_IEEE \ - && !defined __CUDACC__ -# define CV_FP16_TYPE 1 -#else -# define CV_FP16_TYPE 0 -#endif - -typedef union Cv16suf -{ - short i; - ushort u; -#if CV_FP16_TYPE - __fp16 h; -#endif -} -Cv16suf; - -typedef union Cv32suf -{ - int i; - unsigned u; - float f; -} -Cv32suf; - -typedef union Cv64suf -{ - int64 i; - uint64 u; - double f; -} -Cv64suf; - -#ifndef OPENCV_ABI_COMPATIBILITY -#define OPENCV_ABI_COMPATIBILITY 400 -#endif - -#ifdef __OPENCV_BUILD -# define DISABLE_OPENCV_3_COMPATIBILITY -# define OPENCV_DISABLE_DEPRECATED_COMPATIBILITY -#endif - -#ifndef CV_EXPORTS -# if (defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined(CVAPI_EXPORTS) -# define CV_EXPORTS __declspec(dllexport) -# elif defined __GNUC__ && __GNUC__ >= 4 && (defined(CVAPI_EXPORTS) || defined(__APPLE__)) -# define CV_EXPORTS __attribute__ ((visibility ("default"))) -# endif -#endif - -#ifndef CV_EXPORTS -# define CV_EXPORTS -#endif - -#ifdef _MSC_VER -# define CV_EXPORTS_TEMPLATE -#else -# define CV_EXPORTS_TEMPLATE CV_EXPORTS -#endif - -#ifndef CV_DEPRECATED -# if defined(__GNUC__) -# define CV_DEPRECATED __attribute__ ((deprecated)) -# elif defined(_MSC_VER) -# define CV_DEPRECATED __declspec(deprecated) -# else -# define CV_DEPRECATED -# endif -#endif - -#ifndef CV_DEPRECATED_EXTERNAL -# if defined(__OPENCV_BUILD) -# define CV_DEPRECATED_EXTERNAL /* nothing */ -# else -# define CV_DEPRECATED_EXTERNAL CV_DEPRECATED -# endif -#endif - - -#ifndef CV_EXTERN_C -# ifdef __cplusplus -# define CV_EXTERN_C extern "C" -# else -# define CV_EXTERN_C -# endif -#endif - -/* special informative macros for wrapper generators */ -#define CV_EXPORTS_W CV_EXPORTS -#define CV_EXPORTS_W_SIMPLE CV_EXPORTS -#define CV_EXPORTS_AS(synonym) CV_EXPORTS -#define CV_EXPORTS_W_MAP CV_EXPORTS -#define CV_EXPORTS_W_PARAMS CV_EXPORTS -#define CV_IN_OUT -#define CV_OUT -#define CV_PROP -#define CV_PROP_RW -#define CV_ND // Indicates that input data should be parsed into Mat without channels -#define CV_WRAP -#define CV_WRAP_AS(synonym) -#define CV_WRAP_MAPPABLE(mappable) -#define CV_WRAP_PHANTOM(phantom_header) -#define CV_WRAP_DEFAULT(val) -/* Indicates that the function parameter has filesystem path semantic */ -#define CV_WRAP_FILE_PATH - -/****************************************************************************************\ -* Matrix type (Mat) * -\****************************************************************************************/ - -#define CV_MAX_DIM 32 -#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) -#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) -#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) -#define CV_MAT_CONT_FLAG_SHIFT 14 -#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) -#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) -#define CV_IS_CONT_MAT CV_IS_MAT_CONT -#define CV_SUBMAT_FLAG_SHIFT 15 -#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) -#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) - -/** Size of each channel item, - 0x28442211 = 0010 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ -#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15) - -#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type)) - -#ifndef MIN -# define MIN(a,b) ((a) > (b) ? (b) : (a)) -#endif - -#ifndef MAX -# define MAX(a,b) ((a) < (b) ? (b) : (a)) -#endif - -/** min & max without jumps */ -#define CV_IMIN(a, b) ((a) ^ (((a)^(b)) & (((a) < (b)) - 1))) -#define CV_IMAX(a, b) ((a) ^ (((a)^(b)) & (((a) > (b)) - 1))) -#define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) -#define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) -#define CV_SIGN(a) CV_CMP((a),0) - -///////////////////////////////////////// Enum operators /////////////////////////////////////// - -/** - -Provides compatibility operators for both classical and C++11 enum classes, -as well as exposing the C++11 enum class members for backwards compatibility - -@code - // Provides operators required for flag enums - CV_ENUM_FLAGS(AccessFlag) - - // Exposes the listed members of the enum class AccessFlag to the current namespace - CV_ENUM_CLASS_EXPOSE(AccessFlag, ACCESS_READ [, ACCESS_WRITE [, ...] ]); -@endcode -*/ - -#define __CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST) \ -static const EnumType MEMBER_CONST = EnumType::MEMBER_CONST; \ - -#define __CV_ENUM_CLASS_EXPOSE_2(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_1(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_3(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_2(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_4(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_3(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_5(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_4(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_6(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_5(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_7(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_6(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_8(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_7(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_CLASS_EXPOSE_9(EnumType, MEMBER_CONST, ...) \ -__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ -__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_8(EnumType, __VA_ARGS__)); \ - -#define __CV_ENUM_FLAGS_LOGICAL_NOT(EnumType) \ -static inline bool operator!(const EnumType& val) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return !static_cast(val); \ -} \ - -#define __CV_ENUM_FLAGS_LOGICAL_NOT_EQ(Arg1Type, Arg2Type) \ -static inline bool operator!=(const Arg1Type& a, const Arg2Type& b) \ -{ \ - return static_cast(a) != static_cast(b); \ -} \ - -#define __CV_ENUM_FLAGS_LOGICAL_EQ(Arg1Type, Arg2Type) \ -static inline bool operator==(const Arg1Type& a, const Arg2Type& b) \ -{ \ - return static_cast(a) == static_cast(b); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_NOT(EnumType) \ -static inline EnumType operator~(const EnumType& val) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(~static_cast(val)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_OR(EnumType, Arg1Type, Arg2Type) \ -static inline EnumType operator|(const Arg1Type& a, const Arg2Type& b) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(static_cast(a) | static_cast(b)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) \ -static inline EnumType operator&(const Arg1Type& a, const Arg2Type& b) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(static_cast(a) & static_cast(b)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_XOR(EnumType, Arg1Type, Arg2Type) \ -static inline EnumType operator^(const Arg1Type& a, const Arg2Type& b) \ -{ \ - typedef std::underlying_type::type UnderlyingType; \ - return static_cast(static_cast(a) ^ static_cast(b)); \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_OR_EQ(EnumType, Arg1Type) \ -static inline EnumType& operator|=(EnumType& _this, const Arg1Type& val) \ -{ \ - _this = static_cast(static_cast(_this) | static_cast(val)); \ - return _this; \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_AND_EQ(EnumType, Arg1Type) \ -static inline EnumType& operator&=(EnumType& _this, const Arg1Type& val) \ -{ \ - _this = static_cast(static_cast(_this) & static_cast(val)); \ - return _this; \ -} \ - -#define __CV_ENUM_FLAGS_BITWISE_XOR_EQ(EnumType, Arg1Type) \ -static inline EnumType& operator^=(EnumType& _this, const Arg1Type& val) \ -{ \ - _this = static_cast(static_cast(_this) ^ static_cast(val)); \ - return _this; \ -} \ - -#define CV_ENUM_CLASS_EXPOSE(EnumType, ...) \ -__CV_EXPAND(__CV_CAT(__CV_ENUM_CLASS_EXPOSE_, __CV_VA_NUM_ARGS(__VA_ARGS__))(EnumType, __VA_ARGS__)); \ - -#define CV_ENUM_FLAGS(EnumType) \ -__CV_ENUM_FLAGS_LOGICAL_NOT (EnumType) \ -__CV_ENUM_FLAGS_LOGICAL_EQ (EnumType, int) \ -__CV_ENUM_FLAGS_LOGICAL_NOT_EQ (EnumType, int) \ - \ -__CV_ENUM_FLAGS_BITWISE_NOT (EnumType) \ -__CV_ENUM_FLAGS_BITWISE_OR (EnumType, EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_AND (EnumType, EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_XOR (EnumType, EnumType, EnumType) \ - \ -__CV_ENUM_FLAGS_BITWISE_OR_EQ (EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_AND_EQ (EnumType, EnumType) \ -__CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType) \ - -/****************************************************************************************\ -* static analysys * -\****************************************************************************************/ - -// In practice, some macro are not processed correctly (noreturn is not detected). -// We need to use simplified definition for them. -#ifndef CV_STATIC_ANALYSIS -# if defined(__KLOCWORK__) || defined(__clang_analyzer__) || defined(__COVERITY__) -# define CV_STATIC_ANALYSIS 1 -# endif -#else -# if defined(CV_STATIC_ANALYSIS) && !(__CV_CAT(1, CV_STATIC_ANALYSIS) == 1) // defined and not empty -# if 0 == CV_STATIC_ANALYSIS -# undef CV_STATIC_ANALYSIS -# endif -# endif -#endif - -/****************************************************************************************\ -* Thread sanitizer * -\****************************************************************************************/ -#ifndef CV_THREAD_SANITIZER -# if defined(__has_feature) -# if __has_feature(thread_sanitizer) -# define CV_THREAD_SANITIZER -# endif -# endif -#endif - -/****************************************************************************************\ -* exchange-add operation for atomic operations on reference counters * -\****************************************************************************************/ - -#ifdef CV_XADD - // allow to use user-defined macro -#elif defined __GNUC__ || defined __clang__ -# if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined(__CUDACC__) && !defined __INTEL_COMPILER -# ifdef __ATOMIC_ACQ_REL -# define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), delta, __ATOMIC_ACQ_REL) -# else -# define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), delta, 4) -# endif -# else -# if defined __ATOMIC_ACQ_REL && !defined __clang__ - // version for gcc >= 4.7 -# define CV_XADD(addr, delta) (int)__atomic_fetch_add((unsigned*)(addr), (unsigned)(delta), __ATOMIC_ACQ_REL) -# else -# define CV_XADD(addr, delta) (int)__sync_fetch_and_add((unsigned*)(addr), (unsigned)(delta)) -# endif -# endif -#elif defined _MSC_VER && !defined RC_INVOKED -# include -# define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd((long volatile*)addr, delta) -#else - #ifdef OPENCV_FORCE_UNSAFE_XADD - CV_INLINE int CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; } - #else - #error "OpenCV: can't define safe CV_XADD macro for current platform (unsupported). Define CV_XADD macro through custom port header (see OPENCV_INCLUDE_PORT_FILE)" - #endif -#endif - - -/****************************************************************************************\ -* CV_NORETURN attribute * -\****************************************************************************************/ - -#ifndef CV_NORETURN -# if defined(__GNUC__) -# define CV_NORETURN __attribute__((__noreturn__)) -# elif defined(_MSC_VER) && (_MSC_VER >= 1300) -# define CV_NORETURN __declspec(noreturn) -# else -# define CV_NORETURN /* nothing by default */ -# endif -#endif - -/****************************************************************************************\ -* CV_NODISCARD_STD attribute (C++17) * -* encourages the compiler to issue a warning if the return value is discarded * -\****************************************************************************************/ -#ifndef CV_NODISCARD_STD -# ifndef __has_cpp_attribute -// workaround preprocessor non-compliance https://reviews.llvm.org/D57851 -# define __has_cpp_attribute(__x) 0 -# endif -# if __has_cpp_attribute(nodiscard) -# if defined(__NVCC__) && __CUDACC_VER_MAJOR__ < 12 -# define CV_NODISCARD_STD -# else -# define CV_NODISCARD_STD [[nodiscard]] -# endif -# elif __cplusplus >= 201703L -// available when compiler is C++17 compliant -# define CV_NODISCARD_STD [[nodiscard]] -# elif defined(__INTEL_COMPILER) - // see above, available when C++17 is enabled -# elif defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L -// available with VS2017 v15.3+ with /std:c++17 or higher; works on functions and classes -# define CV_NODISCARD_STD [[nodiscard]] -# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 700) && (__cplusplus >= 201103L) -// available with GCC 7.0+; works on functions, works or silently fails on classes -# define CV_NODISCARD_STD [[nodiscard]] -# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) && (__cplusplus >= 201103L) -// available with GCC 4.8+ but it usually does nothing and can fail noisily -- therefore not used -// define CV_NODISCARD_STD [[gnu::warn_unused_result]] -# endif -#endif -#ifndef CV_NODISCARD_STD -# define CV_NODISCARD_STD /* nothing by default */ -#endif - - -/****************************************************************************************\ -* C++ 11 * -\****************************************************************************************/ -#ifdef __cplusplus -// MSVC was stuck at __cplusplus == 199711L for a long time, even where it supports C++11, -// so check _MSC_VER instead. See: -// -# if defined(_MSC_VER) -# if _MSC_VER < 1800 -# error "OpenCV 4.x+ requires enabled C++11 support" -# endif -# elif __cplusplus < 201103L -# error "OpenCV 4.x+ requires enabled C++11 support" -# endif -#endif - -#ifndef CV_CXX11 -# define CV_CXX11 1 -#endif - -#ifndef CV_OVERRIDE -# define CV_OVERRIDE override -#endif - -#ifndef CV_FINAL -# define CV_FINAL final -#endif - -#ifndef CV_NOEXCEPT -# define CV_NOEXCEPT noexcept -#endif - -#ifndef CV_CONSTEXPR -# define CV_CONSTEXPR constexpr -#endif - -// Integer types portability -#ifdef __cplusplus -#include -namespace cv { -using std::int8_t; -using std::uint8_t; -using std::int16_t; -using std::uint16_t; -using std::int32_t; -using std::uint32_t; -using std::int64_t; -using std::uint64_t; -} -#else // pure C -#include -#endif - -#ifdef __cplusplus -namespace cv -{ - -class hfloat -{ -public: -#if CV_FP16_TYPE - - hfloat() : h(0) {} - explicit hfloat(float x) { h = (__fp16)x; } - operator float() const { return (float)h; } -protected: - __fp16 h; - -#else - hfloat() : w(0) {} - explicit hfloat(float x) - { - #if CV_FP16 && CV_AVX2 - __m128 v = _mm_load_ss(&x); - w = (ushort)_mm_cvtsi128_si32(_mm_cvtps_ph(v, 0)); - #else - Cv32suf in; - in.f = x; - unsigned sign = in.u & 0x80000000; - in.u ^= sign; - - if( in.u >= 0x47800000 ) - w = (ushort)(in.u > 0x7f800000 ? 0x7e00 : 0x7c00); - else - { - if (in.u < 0x38800000) - { - in.f += 0.5f; - w = (ushort)(in.u - 0x3f000000); - } - else - { - unsigned t = in.u + 0xc8000fff; - w = (ushort)((t + ((in.u >> 13) & 1)) >> 13); - } - } - - w = (ushort)(w | (sign >> 16)); - #endif - } - - operator float() const - { - #if CV_FP16 && CV_AVX2 - float f; - _mm_store_ss(&f, _mm_cvtph_ps(_mm_cvtsi32_si128(w))); - return f; - #else - Cv32suf out; - - unsigned t = ((w & 0x7fff) << 13) + 0x38000000; - unsigned sign = (w & 0x8000) << 16; - unsigned e = w & 0x7c00; - - out.u = t + (1 << 23); - out.u = (e >= 0x7c00 ? t + 0x38000000 : - e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; - return out.f; - #endif - } - -protected: - ushort w; - -#endif -}; - -inline hfloat hfloatFromBits(ushort w) { -#if CV_FP16_TYPE - Cv16suf u; - u.u = w; - hfloat res(float(u.h)); - return res; -#else - Cv32suf out; - - unsigned t = ((w & 0x7fff) << 13) + 0x38000000; - unsigned sign = (w & 0x8000) << 16; - unsigned e = w & 0x7c00; - - out.u = t + (1 << 23); - out.u = (e >= 0x7c00 ? t + 0x38000000 : - e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; - hfloat res(out.f); - return res; -#endif -} - -#if !defined(__OPENCV_BUILD) && !(defined __STDCPP_FLOAT16_T__) && !(defined __ARM_NEON) -typedef hfloat float16_t; -#endif - -} -#endif - -/** @brief Constructs the 'fourcc' code, used in video codecs and many other places. - Simply call it with 4 chars like `CV_FOURCC('I', 'Y', 'U', 'V')` -*/ -CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4) -{ - return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24); -} - -//! Macro to construct the fourcc code of the codec. Same as CV_FOURCC() -#define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) - -//! @} - -#ifndef __cplusplus -#include "opencv2/core/fast_math.hpp" // define cvRound(double) -#endif - -#endif // OPENCV_CORE_CVDEF_H +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CVDEF_H +#define OPENCV_CORE_CVDEF_H + +#include "opencv2/core/version.hpp" + +//! @addtogroup core_utils +//! @{ + +#ifdef OPENCV_INCLUDE_PORT_FILE // User-provided header file with custom platform configuration +#include OPENCV_INCLUDE_PORT_FILE +#endif + +#if !defined CV_DOXYGEN && !defined CV_IGNORE_DEBUG_BUILD_GUARD +#if (defined(_MSC_VER) && (defined(DEBUG) || defined(_DEBUG))) || \ + (defined(_GLIBCXX_DEBUG) || defined(_GLIBCXX_DEBUG_PEDANTIC)) +// Guard to prevent using of binary incompatible binaries / runtimes +// https://github.com/opencv/opencv/pull/9161 +#define CV__DEBUG_NS_BEGIN namespace debug_build_guard { +#define CV__DEBUG_NS_END } +namespace cv { namespace debug_build_guard { } using namespace debug_build_guard; } +#endif +#endif + +#ifndef CV__DEBUG_NS_BEGIN +#define CV__DEBUG_NS_BEGIN +#define CV__DEBUG_NS_END +#endif + + +#ifdef __OPENCV_BUILD +#include "cvconfig.h" +#endif + +#ifndef __CV_EXPAND +#define __CV_EXPAND(x) x +#endif + +#ifndef __CV_CAT +#define __CV_CAT__(x, y) x ## y +#define __CV_CAT_(x, y) __CV_CAT__(x, y) +#define __CV_CAT(x, y) __CV_CAT_(x, y) +#endif + +#define __CV_VA_NUM_ARGS_HELPER(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, N, ...) N +#define __CV_VA_NUM_ARGS(...) __CV_EXPAND(__CV_VA_NUM_ARGS_HELPER(__VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)) + +#ifdef CV_Func +// keep current value (through OpenCV port file) +#elif defined __GNUC__ || (defined (__cpluscplus) && (__cpluscplus >= 201103)) +#define CV_Func __func__ +#elif defined __clang__ && (__clang_minor__ * 100 + __clang_major__ >= 305) +#define CV_Func __func__ +#elif defined(__STDC_VERSION__) && (__STDC_VERSION >= 199901) +#define CV_Func __func__ +#elif defined _MSC_VER +#define CV_Func __FUNCTION__ +#elif defined(__INTEL_COMPILER) && (_INTEL_COMPILER >= 600) +#define CV_Func __FUNCTION__ +#elif defined __IBMCPP__ && __IBMCPP__ >=500 +#define CV_Func __FUNCTION__ +#elif defined __BORLAND__ && (__BORLANDC__ >= 0x550) +#define CV_Func __FUNC__ +#else +#define CV_Func "" +#endif + +//! @cond IGNORED + +//////////////// static assert ///////////////// +#define CVAUX_CONCAT_EXP(a, b) a##b +#define CVAUX_CONCAT(a, b) CVAUX_CONCAT_EXP(a,b) + +#if defined(__clang__) +# ifndef __has_extension +# define __has_extension __has_feature /* compatibility, for older versions of clang */ +# endif +# if __has_extension(cxx_static_assert) +# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) +# elif __has_extension(c_static_assert) +# define CV_StaticAssert(condition, reason) _Static_assert((condition), reason " " #condition) +# endif +#elif defined(__GNUC__) +# if (defined(__GXX_EXPERIMENTAL_CXX0X__) || __cplusplus >= 201103L) +# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) +# endif +#elif defined(_MSC_VER) +# if _MSC_VER >= 1600 /* MSVC 10 */ +# define CV_StaticAssert(condition, reason) static_assert((condition), reason " " #condition) +# endif +#endif +#ifndef CV_StaticAssert +# if !defined(__clang__) && defined(__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 302) +# define CV_StaticAssert(condition, reason) ({ extern int __attribute__((error("CV_StaticAssert: " reason " " #condition))) CV_StaticAssert(); ((condition) ? 0 : CV_StaticAssert()); }) +# else +namespace cv { + template struct CV_StaticAssert_failed; + template <> struct CV_StaticAssert_failed { enum { val = 1 }; }; + template struct CV_StaticAssert_test {}; +} +# define CV_StaticAssert(condition, reason)\ + typedef cv::CV_StaticAssert_test< sizeof(cv::CV_StaticAssert_failed< static_cast(condition) >) > CVAUX_CONCAT(CV_StaticAssert_failed_at_, __LINE__) +# endif +#endif + +// Suppress warning "-Wdeprecated-declarations" / C4996 +#if defined(_MSC_VER) + #define CV_DO_PRAGMA(x) __pragma(x) +#elif defined(__GNUC__) + #define CV_DO_PRAGMA(x) _Pragma (#x) +#else + #define CV_DO_PRAGMA(x) +#endif + +#ifdef _MSC_VER +#define CV_SUPPRESS_DEPRECATED_START \ + CV_DO_PRAGMA(warning(push)) \ + CV_DO_PRAGMA(warning(disable: 4996)) +#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(warning(pop)) +#elif defined (__clang__) || ((__GNUC__) && (__GNUC__*100 + __GNUC_MINOR__ > 405)) +#define CV_SUPPRESS_DEPRECATED_START \ + CV_DO_PRAGMA(GCC diagnostic push) \ + CV_DO_PRAGMA(GCC diagnostic ignored "-Wdeprecated-declarations") +#define CV_SUPPRESS_DEPRECATED_END CV_DO_PRAGMA(GCC diagnostic pop) +#else +#define CV_SUPPRESS_DEPRECATED_START +#define CV_SUPPRESS_DEPRECATED_END +#endif + +#define CV_UNUSED(name) (void)name + +//! @endcond + +// undef problematic defines sometimes defined by system headers (windows.h in particular) +#undef small +#undef min +#undef max +#undef abs +#undef Complex + +#if defined __cplusplus +#include +#else +#include +#endif + +#include "opencv2/core/hal/interface.h" + +#if defined __ICL +# define CV_ICC __ICL +#elif defined __ICC +# define CV_ICC __ICC +#elif defined __ECL +# define CV_ICC __ECL +#elif defined __ECC +# define CV_ICC __ECC +#elif defined __INTEL_COMPILER +# define CV_ICC __INTEL_COMPILER +#endif + +#if defined _WIN32 +# define CV_CDECL __cdecl +# define CV_STDCALL __stdcall +#else +# define CV_CDECL +# define CV_STDCALL +#endif + +#ifndef CV_INLINE +# if defined __cplusplus +# define CV_INLINE static inline +# elif defined _MSC_VER +# define CV_INLINE __inline +# else +# define CV_INLINE static +# endif +#endif + +#ifndef CV_ALWAYS_INLINE +#if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +#define CV_ALWAYS_INLINE inline __attribute__((always_inline)) +#elif defined(_MSC_VER) +#define CV_ALWAYS_INLINE __forceinline +#else +#define CV_ALWAYS_INLINE inline +#endif +#endif + +#if defined CV_DISABLE_OPTIMIZATION || (defined CV_ICC && !defined CV_ENABLE_UNROLLED) +# define CV_ENABLE_UNROLLED 0 +#else +# define CV_ENABLE_UNROLLED 1 +#endif + +#ifdef __GNUC__ +# define CV_DECL_ALIGNED(x) __attribute__ ((aligned (x))) +#elif defined _MSC_VER +# define CV_DECL_ALIGNED(x) __declspec(align(x)) +#else +# define CV_DECL_ALIGNED(x) +#endif + +/* CPU features and intrinsics support */ +#define CV_CPU_NONE 0 +#define CV_CPU_MMX 1 +#define CV_CPU_SSE 2 +#define CV_CPU_SSE2 3 +#define CV_CPU_SSE3 4 +#define CV_CPU_SSSE3 5 +#define CV_CPU_SSE4_1 6 +#define CV_CPU_SSE4_2 7 +#define CV_CPU_POPCNT 8 +#define CV_CPU_FP16 9 +#define CV_CPU_AVX 10 +#define CV_CPU_AVX2 11 +#define CV_CPU_FMA3 12 + +#define CV_CPU_AVX_512F 13 +#define CV_CPU_AVX_512BW 14 +#define CV_CPU_AVX_512CD 15 +#define CV_CPU_AVX_512DQ 16 +#define CV_CPU_AVX_512ER 17 +#define CV_CPU_AVX_512IFMA512 18 // deprecated +#define CV_CPU_AVX_512IFMA 18 +#define CV_CPU_AVX_512PF 19 +#define CV_CPU_AVX_512VBMI 20 +#define CV_CPU_AVX_512VL 21 +#define CV_CPU_AVX_512VBMI2 22 +#define CV_CPU_AVX_512VNNI 23 +#define CV_CPU_AVX_512BITALG 24 +#define CV_CPU_AVX_512VPOPCNTDQ 25 +#define CV_CPU_AVX_5124VNNIW 26 +#define CV_CPU_AVX_5124FMAPS 27 + +#define CV_CPU_NEON 100 +#define CV_CPU_NEON_DOTPROD 101 +#define CV_CPU_NEON_FP16 102 +#define CV_CPU_NEON_BF16 103 + +#define CV_CPU_MSA 150 + +#define CV_CPU_RISCVV 170 + +#define CV_CPU_VSX 200 +#define CV_CPU_VSX3 201 + +#define CV_CPU_RVV 210 + +#define CV_CPU_LSX 230 +#define CV_CPU_LASX 231 + +// CPU features groups +#define CV_CPU_AVX512_SKX 256 +#define CV_CPU_AVX512_COMMON 257 +#define CV_CPU_AVX512_KNL 258 +#define CV_CPU_AVX512_KNM 259 +#define CV_CPU_AVX512_CNL 260 +#define CV_CPU_AVX512_CLX 261 +#define CV_CPU_AVX512_ICL 262 + +// when adding to this list remember to update the following enum +#define CV_HARDWARE_MAX_FEATURE 512 + +/** @brief Available CPU features. +*/ +enum CpuFeatures { + CPU_MMX = 1, + CPU_SSE = 2, + CPU_SSE2 = 3, + CPU_SSE3 = 4, + CPU_SSSE3 = 5, + CPU_SSE4_1 = 6, + CPU_SSE4_2 = 7, + CPU_POPCNT = 8, + CPU_FP16 = 9, + CPU_AVX = 10, + CPU_AVX2 = 11, + CPU_FMA3 = 12, + + CPU_AVX_512F = 13, + CPU_AVX_512BW = 14, + CPU_AVX_512CD = 15, + CPU_AVX_512DQ = 16, + CPU_AVX_512ER = 17, + CPU_AVX_512IFMA512 = 18, // deprecated + CPU_AVX_512IFMA = 18, + CPU_AVX_512PF = 19, + CPU_AVX_512VBMI = 20, + CPU_AVX_512VL = 21, + CPU_AVX_512VBMI2 = 22, + CPU_AVX_512VNNI = 23, + CPU_AVX_512BITALG = 24, + CPU_AVX_512VPOPCNTDQ= 25, + CPU_AVX_5124VNNIW = 26, + CPU_AVX_5124FMAPS = 27, + + CPU_NEON = 100, + CPU_NEON_DOTPROD = 101, + CPU_NEON_FP16 = 102, + CPU_NEON_BF16 = 103, + + CPU_MSA = 150, + + CPU_RISCVV = 170, + + CPU_VSX = 200, + CPU_VSX3 = 201, + + CPU_RVV = 210, + + CPU_LSX = 230, + CPU_LASX = 231, + + CPU_AVX512_SKX = 256, //!< Skylake-X with AVX-512F/CD/BW/DQ/VL + CPU_AVX512_COMMON = 257, //!< Common instructions AVX-512F/CD for all CPUs that support AVX-512 + CPU_AVX512_KNL = 258, //!< Knights Landing with AVX-512F/CD/ER/PF + CPU_AVX512_KNM = 259, //!< Knights Mill with AVX-512F/CD/ER/PF/4FMAPS/4VNNIW/VPOPCNTDQ + CPU_AVX512_CNL = 260, //!< Cannon Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI + CPU_AVX512_CLX = 261, //!< Cascade Lake with AVX-512F/CD/BW/DQ/VL/VNNI + CPU_AVX512_ICL = 262, //!< Ice Lake with AVX-512F/CD/BW/DQ/VL/IFMA/VBMI/VNNI/VBMI2/BITALG/VPOPCNTDQ + + CPU_MAX_FEATURE = 512 // see CV_HARDWARE_MAX_FEATURE +}; + + +#include "cv_cpu_dispatch.h" + +#if !defined(CV_STRONG_ALIGNMENT) && defined(__arm__) && !(defined(__aarch64__) || defined(_M_ARM64)) +// int*, int64* should be propertly aligned pointers on ARMv7 +#define CV_STRONG_ALIGNMENT 1 +#endif +#if !defined(CV_STRONG_ALIGNMENT) +#define CV_STRONG_ALIGNMENT 0 +#endif + +/* fundamental constants */ +#define CV_PI 3.1415926535897932384626433832795 +#define CV_2PI 6.283185307179586476925286766559 +#define CV_LOG2 0.69314718055994530941723212145818 + +#if defined __ARM_FP16_FORMAT_IEEE \ + && !defined __CUDACC__ +# define CV_FP16_TYPE 1 +#else +# define CV_FP16_TYPE 0 +#endif + +typedef union Cv16suf +{ + short i; + ushort u; +#if CV_FP16_TYPE + __fp16 h; +#endif +} +Cv16suf; + +typedef union Cv32suf +{ + int i; + unsigned u; + float f; +} +Cv32suf; + +typedef union Cv64suf +{ + int64 i; + uint64 u; + double f; +} +Cv64suf; + +#ifndef OPENCV_ABI_COMPATIBILITY +#define OPENCV_ABI_COMPATIBILITY 400 +#endif + +#ifdef __OPENCV_BUILD +# define DISABLE_OPENCV_3_COMPATIBILITY +# define OPENCV_DISABLE_DEPRECATED_COMPATIBILITY +#endif + +#ifndef CV_EXPORTS +# if (defined _WIN32 || defined WINCE || defined __CYGWIN__) && defined(CVAPI_EXPORTS) +# define CV_EXPORTS __declspec(dllexport) +# elif defined __GNUC__ && __GNUC__ >= 4 && (defined(CVAPI_EXPORTS) || defined(__APPLE__)) +# define CV_EXPORTS __attribute__ ((visibility ("default"))) +# endif +#endif + +#ifndef CV_EXPORTS +# define CV_EXPORTS +#endif + +#ifdef _MSC_VER +# define CV_EXPORTS_TEMPLATE +#else +# define CV_EXPORTS_TEMPLATE CV_EXPORTS +#endif + +#ifndef CV_DEPRECATED +# if defined(__GNUC__) +# define CV_DEPRECATED __attribute__ ((deprecated)) +# elif defined(_MSC_VER) +# define CV_DEPRECATED __declspec(deprecated) +# else +# define CV_DEPRECATED +# endif +#endif + +#ifndef CV_DEPRECATED_EXTERNAL +# if defined(__OPENCV_BUILD) +# define CV_DEPRECATED_EXTERNAL /* nothing */ +# else +# define CV_DEPRECATED_EXTERNAL CV_DEPRECATED +# endif +#endif + + +#ifndef CV_EXTERN_C +# ifdef __cplusplus +# define CV_EXTERN_C extern "C" +# else +# define CV_EXTERN_C +# endif +#endif + +/* special informative macros for wrapper generators */ +#define CV_EXPORTS_W CV_EXPORTS +#define CV_EXPORTS_W_SIMPLE CV_EXPORTS +#define CV_EXPORTS_AS(synonym) CV_EXPORTS +#define CV_EXPORTS_W_MAP CV_EXPORTS +#define CV_EXPORTS_W_PARAMS CV_EXPORTS +#define CV_IN_OUT +#define CV_OUT +#define CV_PROP +#define CV_PROP_RW +#define CV_ND // Indicates that input data should be parsed into Mat without channels +#define CV_WRAP +#define CV_WRAP_AS(synonym) +#define CV_WRAP_MAPPABLE(mappable) +#define CV_WRAP_PHANTOM(phantom_header) +#define CV_WRAP_DEFAULT(val) +/* Indicates that the function parameter has filesystem path semantic */ +#define CV_WRAP_FILE_PATH + +/****************************************************************************************\ +* Matrix type (Mat) * +\****************************************************************************************/ + +#define CV_MAX_DIM 32 +#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) +#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) +#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) +#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) +#define CV_MAT_CONT_FLAG_SHIFT 14 +#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) +#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) +#define CV_IS_CONT_MAT CV_IS_MAT_CONT +#define CV_SUBMAT_FLAG_SHIFT 15 +#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) +#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) + +/** Size of each channel item, + 0x28442211 = 0010 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ +#define CV_ELEM_SIZE1(type) ((0x28442211 >> CV_MAT_DEPTH(type)*4) & 15) + +#define CV_ELEM_SIZE(type) (CV_MAT_CN(type)*CV_ELEM_SIZE1(type)) + +#ifndef MIN +# define MIN(a,b) ((a) > (b) ? (b) : (a)) +#endif + +#ifndef MAX +# define MAX(a,b) ((a) < (b) ? (b) : (a)) +#endif + +/** min & max without jumps */ +#define CV_IMIN(a, b) ((a) ^ (((a)^(b)) & (((a) < (b)) - 1))) +#define CV_IMAX(a, b) ((a) ^ (((a)^(b)) & (((a) > (b)) - 1))) +#define CV_SWAP(a,b,t) ((t) = (a), (a) = (b), (b) = (t)) +#define CV_CMP(a,b) (((a) > (b)) - ((a) < (b))) +#define CV_SIGN(a) CV_CMP((a),0) + +///////////////////////////////////////// Enum operators /////////////////////////////////////// + +/** + +Provides compatibility operators for both classical and C++11 enum classes, +as well as exposing the C++11 enum class members for backwards compatibility + +@code + // Provides operators required for flag enums + CV_ENUM_FLAGS(AccessFlag) + + // Exposes the listed members of the enum class AccessFlag to the current namespace + CV_ENUM_CLASS_EXPOSE(AccessFlag, ACCESS_READ [, ACCESS_WRITE [, ...] ]); +@endcode +*/ + +#define __CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST) \ +static const EnumType MEMBER_CONST = EnumType::MEMBER_CONST; \ + +#define __CV_ENUM_CLASS_EXPOSE_2(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_1(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_3(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_2(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_4(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_3(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_5(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_4(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_6(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_5(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_7(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_6(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_8(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_7(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_CLASS_EXPOSE_9(EnumType, MEMBER_CONST, ...) \ +__CV_ENUM_CLASS_EXPOSE_1(EnumType, MEMBER_CONST); \ +__CV_EXPAND(__CV_ENUM_CLASS_EXPOSE_8(EnumType, __VA_ARGS__)); \ + +#define __CV_ENUM_FLAGS_LOGICAL_NOT(EnumType) \ +static inline bool operator!(const EnumType& val) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return !static_cast(val); \ +} \ + +#define __CV_ENUM_FLAGS_LOGICAL_NOT_EQ(Arg1Type, Arg2Type) \ +static inline bool operator!=(const Arg1Type& a, const Arg2Type& b) \ +{ \ + return static_cast(a) != static_cast(b); \ +} \ + +#define __CV_ENUM_FLAGS_LOGICAL_EQ(Arg1Type, Arg2Type) \ +static inline bool operator==(const Arg1Type& a, const Arg2Type& b) \ +{ \ + return static_cast(a) == static_cast(b); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_NOT(EnumType) \ +static inline EnumType operator~(const EnumType& val) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(~static_cast(val)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_OR(EnumType, Arg1Type, Arg2Type) \ +static inline EnumType operator|(const Arg1Type& a, const Arg2Type& b) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(static_cast(a) | static_cast(b)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_AND(EnumType, Arg1Type, Arg2Type) \ +static inline EnumType operator&(const Arg1Type& a, const Arg2Type& b) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(static_cast(a) & static_cast(b)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_XOR(EnumType, Arg1Type, Arg2Type) \ +static inline EnumType operator^(const Arg1Type& a, const Arg2Type& b) \ +{ \ + typedef std::underlying_type::type UnderlyingType; \ + return static_cast(static_cast(a) ^ static_cast(b)); \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_OR_EQ(EnumType, Arg1Type) \ +static inline EnumType& operator|=(EnumType& _this, const Arg1Type& val) \ +{ \ + _this = static_cast(static_cast(_this) | static_cast(val)); \ + return _this; \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_AND_EQ(EnumType, Arg1Type) \ +static inline EnumType& operator&=(EnumType& _this, const Arg1Type& val) \ +{ \ + _this = static_cast(static_cast(_this) & static_cast(val)); \ + return _this; \ +} \ + +#define __CV_ENUM_FLAGS_BITWISE_XOR_EQ(EnumType, Arg1Type) \ +static inline EnumType& operator^=(EnumType& _this, const Arg1Type& val) \ +{ \ + _this = static_cast(static_cast(_this) ^ static_cast(val)); \ + return _this; \ +} \ + +#define CV_ENUM_CLASS_EXPOSE(EnumType, ...) \ +__CV_EXPAND(__CV_CAT(__CV_ENUM_CLASS_EXPOSE_, __CV_VA_NUM_ARGS(__VA_ARGS__))(EnumType, __VA_ARGS__)); \ + +#define CV_ENUM_FLAGS(EnumType) \ +__CV_ENUM_FLAGS_LOGICAL_NOT (EnumType) \ +__CV_ENUM_FLAGS_LOGICAL_EQ (EnumType, int) \ +__CV_ENUM_FLAGS_LOGICAL_NOT_EQ (EnumType, int) \ + \ +__CV_ENUM_FLAGS_BITWISE_NOT (EnumType) \ +__CV_ENUM_FLAGS_BITWISE_OR (EnumType, EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_AND (EnumType, EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_XOR (EnumType, EnumType, EnumType) \ + \ +__CV_ENUM_FLAGS_BITWISE_OR_EQ (EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_AND_EQ (EnumType, EnumType) \ +__CV_ENUM_FLAGS_BITWISE_XOR_EQ (EnumType, EnumType) \ + +/****************************************************************************************\ +* static analysys * +\****************************************************************************************/ + +// In practice, some macro are not processed correctly (noreturn is not detected). +// We need to use simplified definition for them. +#ifndef CV_STATIC_ANALYSIS +# if defined(__KLOCWORK__) || defined(__clang_analyzer__) || defined(__COVERITY__) +# define CV_STATIC_ANALYSIS 1 +# endif +#else +# if defined(CV_STATIC_ANALYSIS) && !(__CV_CAT(1, CV_STATIC_ANALYSIS) == 1) // defined and not empty +# if 0 == CV_STATIC_ANALYSIS +# undef CV_STATIC_ANALYSIS +# endif +# endif +#endif + +/****************************************************************************************\ +* Thread sanitizer * +\****************************************************************************************/ +#ifndef CV_THREAD_SANITIZER +# if defined(__has_feature) +# if __has_feature(thread_sanitizer) +# define CV_THREAD_SANITIZER +# endif +# endif +#endif + +/****************************************************************************************\ +* exchange-add operation for atomic operations on reference counters * +\****************************************************************************************/ + +#ifdef CV_XADD + // allow to use user-defined macro +#elif defined __GNUC__ || defined __clang__ +# if defined __clang__ && __clang_major__ >= 3 && !defined __ANDROID__ && !defined __EMSCRIPTEN__ && !defined(__CUDACC__) && !defined __INTEL_COMPILER +# ifdef __ATOMIC_ACQ_REL +# define CV_XADD(addr, delta) __c11_atomic_fetch_add((_Atomic(int)*)(addr), delta, __ATOMIC_ACQ_REL) +# else +# define CV_XADD(addr, delta) __atomic_fetch_add((_Atomic(int)*)(addr), delta, 4) +# endif +# else +# if defined __ATOMIC_ACQ_REL && !defined __clang__ + // version for gcc >= 4.7 +# define CV_XADD(addr, delta) (int)__atomic_fetch_add((unsigned*)(addr), (unsigned)(delta), __ATOMIC_ACQ_REL) +# else +# define CV_XADD(addr, delta) (int)__sync_fetch_and_add((unsigned*)(addr), (unsigned)(delta)) +# endif +# endif +#elif defined _MSC_VER && !defined RC_INVOKED +# include +# define CV_XADD(addr, delta) (int)_InterlockedExchangeAdd((long volatile*)addr, delta) +#else + #ifdef OPENCV_FORCE_UNSAFE_XADD + CV_INLINE int CV_XADD(int* addr, int delta) { int tmp = *addr; *addr += delta; return tmp; } + #else + #error "OpenCV: can't define safe CV_XADD macro for current platform (unsupported). Define CV_XADD macro through custom port header (see OPENCV_INCLUDE_PORT_FILE)" + #endif +#endif + + +/****************************************************************************************\ +* CV_NORETURN attribute * +\****************************************************************************************/ + +#ifndef CV_NORETURN +# if defined(__GNUC__) +# define CV_NORETURN __attribute__((__noreturn__)) +# elif defined(_MSC_VER) && (_MSC_VER >= 1300) +# define CV_NORETURN __declspec(noreturn) +# else +# define CV_NORETURN /* nothing by default */ +# endif +#endif + +/****************************************************************************************\ +* CV_NODISCARD_STD attribute (C++17) * +* encourages the compiler to issue a warning if the return value is discarded * +\****************************************************************************************/ +#ifndef CV_NODISCARD_STD +# ifndef __has_cpp_attribute +// workaround preprocessor non-compliance https://reviews.llvm.org/D57851 +# define __has_cpp_attribute(__x) 0 +# endif +# if __has_cpp_attribute(nodiscard) +# if defined(__NVCC__) && __CUDACC_VER_MAJOR__ < 12 +# define CV_NODISCARD_STD +# else +# define CV_NODISCARD_STD [[nodiscard]] +# endif +# elif __cplusplus >= 201703L +// available when compiler is C++17 compliant +# define CV_NODISCARD_STD [[nodiscard]] +# elif defined(__INTEL_COMPILER) + // see above, available when C++17 is enabled +# elif defined(_MSC_VER) && _MSC_VER >= 1911 && _MSVC_LANG >= 201703L +// available with VS2017 v15.3+ with /std:c++17 or higher; works on functions and classes +# define CV_NODISCARD_STD [[nodiscard]] +# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 700) && (__cplusplus >= 201103L) +// available with GCC 7.0+; works on functions, works or silently fails on classes +# define CV_NODISCARD_STD [[nodiscard]] +# elif defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 408) && (__cplusplus >= 201103L) +// available with GCC 4.8+ but it usually does nothing and can fail noisily -- therefore not used +// define CV_NODISCARD_STD [[gnu::warn_unused_result]] +# endif +#endif +#ifndef CV_NODISCARD_STD +# define CV_NODISCARD_STD /* nothing by default */ +#endif + + +/****************************************************************************************\ +* C++ 11 * +\****************************************************************************************/ +#ifdef __cplusplus +// MSVC was stuck at __cplusplus == 199711L for a long time, even where it supports C++11, +// so check _MSC_VER instead. See: +// +# if defined(_MSC_VER) +# if _MSC_VER < 1800 +# error "OpenCV 4.x+ requires enabled C++11 support" +# endif +# elif __cplusplus < 201103L +# error "OpenCV 4.x+ requires enabled C++11 support" +# endif +#endif + +#ifndef CV_CXX11 +# define CV_CXX11 1 +#endif + +#ifndef CV_OVERRIDE +# define CV_OVERRIDE override +#endif + +#ifndef CV_FINAL +# define CV_FINAL final +#endif + +#ifndef CV_NOEXCEPT +# define CV_NOEXCEPT noexcept +#endif + +#ifndef CV_CONSTEXPR +# define CV_CONSTEXPR constexpr +#endif + +// Integer types portability +#ifdef __cplusplus +#include +namespace cv { +using std::int8_t; +using std::uint8_t; +using std::int16_t; +using std::uint16_t; +using std::int32_t; +using std::uint32_t; +using std::int64_t; +using std::uint64_t; +} +#else // pure C +#include +#endif + +#ifdef __cplusplus +namespace cv +{ + +class hfloat +{ +public: +#if CV_FP16_TYPE + + hfloat() : h(0) {} + explicit hfloat(float x) { h = (__fp16)x; } + operator float() const { return (float)h; } +protected: + __fp16 h; + +#else + hfloat() : w(0) {} + explicit hfloat(float x) + { + #if CV_FP16 && CV_AVX2 + __m128 v = _mm_load_ss(&x); + w = (ushort)_mm_cvtsi128_si32(_mm_cvtps_ph(v, 0)); + #else + Cv32suf in; + in.f = x; + unsigned sign = in.u & 0x80000000; + in.u ^= sign; + + if( in.u >= 0x47800000 ) + w = (ushort)(in.u > 0x7f800000 ? 0x7e00 : 0x7c00); + else + { + if (in.u < 0x38800000) + { + in.f += 0.5f; + w = (ushort)(in.u - 0x3f000000); + } + else + { + unsigned t = in.u + 0xc8000fff; + w = (ushort)((t + ((in.u >> 13) & 1)) >> 13); + } + } + + w = (ushort)(w | (sign >> 16)); + #endif + } + + operator float() const + { + #if CV_FP16 && CV_AVX2 + float f; + _mm_store_ss(&f, _mm_cvtph_ps(_mm_cvtsi32_si128(w))); + return f; + #else + Cv32suf out; + + unsigned t = ((w & 0x7fff) << 13) + 0x38000000; + unsigned sign = (w & 0x8000) << 16; + unsigned e = w & 0x7c00; + + out.u = t + (1 << 23); + out.u = (e >= 0x7c00 ? t + 0x38000000 : + e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; + return out.f; + #endif + } + +protected: + ushort w; + +#endif +}; + +inline hfloat hfloatFromBits(ushort w) { +#if CV_FP16_TYPE + Cv16suf u; + u.u = w; + hfloat res(float(u.h)); + return res; +#else + Cv32suf out; + + unsigned t = ((w & 0x7fff) << 13) + 0x38000000; + unsigned sign = (w & 0x8000) << 16; + unsigned e = w & 0x7c00; + + out.u = t + (1 << 23); + out.u = (e >= 0x7c00 ? t + 0x38000000 : + e == 0 ? (static_cast(out.f -= 6.103515625e-05f), out.u) : t) | sign; + hfloat res(out.f); + return res; +#endif +} + +#if !defined(__OPENCV_BUILD) && !(defined __STDCPP_FLOAT16_T__) && !(defined __ARM_NEON) +typedef hfloat float16_t; +#endif + +} +#endif + +/** @brief Constructs the 'fourcc' code, used in video codecs and many other places. + Simply call it with 4 chars like `CV_FOURCC('I', 'Y', 'U', 'V')` +*/ +CV_INLINE int CV_FOURCC(char c1, char c2, char c3, char c4) +{ + return (c1 & 255) + ((c2 & 255) << 8) + ((c3 & 255) << 16) + ((c4 & 255) << 24); +} + +//! Macro to construct the fourcc code of the codec. Same as CV_FOURCC() +#define CV_FOURCC_MACRO(c1, c2, c3, c4) (((c1) & 255) + (((c2) & 255) << 8) + (((c3) & 255) << 16) + (((c4) & 255) << 24)) + +//! @} + +#ifndef __cplusplus +#include "opencv2/core/fast_math.hpp" // define cvRound(double) +#endif + +#endif // OPENCV_CORE_CVDEF_H diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp index 1946f2521f..d216d267ef 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.hpp @@ -1,189 +1,189 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CVSTD_HPP -#define OPENCV_CORE_CVSTD_HPP - -#ifndef __cplusplus -# error cvstd.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" -#include -#include -#include - -#include - -// import useful primitives from stl -# include -# include -# include //for abs(int) -# include - -namespace cv -{ - static inline uchar abs(uchar a) { return a; } - static inline ushort abs(ushort a) { return a; } - static inline unsigned abs(unsigned a) { return a; } - static inline uint64 abs(uint64 a) { return a; } - - using std::min; - using std::max; - using std::abs; - using std::swap; - using std::sqrt; - using std::exp; - using std::pow; - using std::log; -} - -#include "cvstd_wrapper.hpp" - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -//////////////////////////// memory management functions //////////////////////////// - -/** @brief Allocates an aligned memory buffer. - -The function allocates the buffer of the specified size and returns it. When the buffer size is 16 -bytes or more, the returned buffer is aligned to 16 bytes. -@param bufSize Allocated buffer size. - */ -CV_EXPORTS void* fastMalloc(size_t bufSize); - -/** @brief Deallocates a memory buffer. - -The function deallocates the buffer allocated with fastMalloc . If NULL pointer is passed, the -function does nothing. C version of the function clears the pointer *pptr* to avoid problems with -double memory deallocation. -@param ptr Pointer to the allocated buffer. - */ -CV_EXPORTS void fastFree(void* ptr); - -/*! - The STL-compliant memory Allocator based on cv::fastMalloc() and cv::fastFree() -*/ -template class Allocator -{ -public: - typedef _Tp value_type; - typedef value_type* pointer; - typedef const value_type* const_pointer; - typedef value_type& reference; - typedef const value_type& const_reference; - typedef size_t size_type; - typedef ptrdiff_t difference_type; - template class rebind { typedef Allocator other; }; - - explicit Allocator() {} - ~Allocator() {} - explicit Allocator(Allocator const&) {} - template - explicit Allocator(Allocator const&) {} - - // address - pointer address(reference r) { return &r; } - const_pointer address(const_reference r) { return &r; } - - pointer allocate(size_type count, const void* =0) { return reinterpret_cast(fastMalloc(count * sizeof (_Tp))); } - void deallocate(pointer p, size_type) { fastFree(p); } - - void construct(pointer p, const _Tp& v) { new(static_cast(p)) _Tp(v); } - void destroy(pointer p) { p->~_Tp(); } - - size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } -}; - -//! @} core_utils - - -//! @addtogroup core_basic -//! @{ - -//////////////////////////////// string class //////////////////////////////// - -class CV_EXPORTS FileNode; //for string constructor from FileNode - -typedef std::string String; - -#ifndef OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS - -//! @cond IGNORED -namespace details { -// std::tolower is int->int -static inline char char_tolower(char ch) -{ - return (char)std::tolower((int)ch); -} -// std::toupper is int->int -static inline char char_toupper(char ch) -{ - return (char)std::toupper((int)ch); -} -} // namespace details -//! @endcond - -static inline std::string toLowerCase(const std::string& str) -{ - std::string result(str); - std::transform(result.begin(), result.end(), result.begin(), details::char_tolower); - return result; -} - -static inline std::string toUpperCase(const std::string& str) -{ - std::string result(str); - std::transform(result.begin(), result.end(), result.begin(), details::char_toupper); - return result; -} - -#endif // OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS - -//! @} core_basic -} // cv - -#endif //OPENCV_CORE_CVSTD_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CVSTD_HPP +#define OPENCV_CORE_CVSTD_HPP + +#ifndef __cplusplus +# error cvstd.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" +#include +#include +#include + +#include + +// import useful primitives from stl +# include +# include +# include //for abs(int) +# include + +namespace cv +{ + static inline uchar abs(uchar a) { return a; } + static inline ushort abs(ushort a) { return a; } + static inline unsigned abs(unsigned a) { return a; } + static inline uint64 abs(uint64 a) { return a; } + + using std::min; + using std::max; + using std::abs; + using std::swap; + using std::sqrt; + using std::exp; + using std::pow; + using std::log; +} + +#include "cvstd_wrapper.hpp" + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +//////////////////////////// memory management functions //////////////////////////// + +/** @brief Allocates an aligned memory buffer. + +The function allocates the buffer of the specified size and returns it. When the buffer size is 16 +bytes or more, the returned buffer is aligned to 16 bytes. +@param bufSize Allocated buffer size. + */ +CV_EXPORTS void* fastMalloc(size_t bufSize); + +/** @brief Deallocates a memory buffer. + +The function deallocates the buffer allocated with fastMalloc . If NULL pointer is passed, the +function does nothing. C version of the function clears the pointer *pptr* to avoid problems with +double memory deallocation. +@param ptr Pointer to the allocated buffer. + */ +CV_EXPORTS void fastFree(void* ptr); + +/*! + The STL-compliant memory Allocator based on cv::fastMalloc() and cv::fastFree() +*/ +template class Allocator +{ +public: + typedef _Tp value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type& reference; + typedef const value_type& const_reference; + typedef size_t size_type; + typedef ptrdiff_t difference_type; + template class rebind { typedef Allocator other; }; + + explicit Allocator() {} + ~Allocator() {} + explicit Allocator(Allocator const&) {} + template + explicit Allocator(Allocator const&) {} + + // address + pointer address(reference r) { return &r; } + const_pointer address(const_reference r) { return &r; } + + pointer allocate(size_type count, const void* =0) { return reinterpret_cast(fastMalloc(count * sizeof (_Tp))); } + void deallocate(pointer p, size_type) { fastFree(p); } + + void construct(pointer p, const _Tp& v) { new(static_cast(p)) _Tp(v); } + void destroy(pointer p) { p->~_Tp(); } + + size_type max_size() const { return cv::max(static_cast<_Tp>(-1)/sizeof(_Tp), 1); } +}; + +//! @} core_utils + + +//! @addtogroup core_basic +//! @{ + +//////////////////////////////// string class //////////////////////////////// + +class CV_EXPORTS FileNode; //for string constructor from FileNode + +typedef std::string String; + +#ifndef OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS + +//! @cond IGNORED +namespace details { +// std::tolower is int->int +static inline char char_tolower(char ch) +{ + return (char)std::tolower((int)ch); +} +// std::toupper is int->int +static inline char char_toupper(char ch) +{ + return (char)std::toupper((int)ch); +} +} // namespace details +//! @endcond + +static inline std::string toLowerCase(const std::string& str) +{ + std::string result(str); + std::transform(result.begin(), result.end(), result.begin(), details::char_tolower); + return result; +} + +static inline std::string toUpperCase(const std::string& str) +{ + std::string result(str); + std::transform(result.begin(), result.end(), result.begin(), details::char_toupper); + return result; +} + +#endif // OPENCV_DISABLE_STRING_LOWER_UPPER_CONVERSIONS + +//! @} core_basic +} // cv + +#endif //OPENCV_CORE_CVSTD_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp index 42acfe09c7..37ad1e6906 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvstd.inl.hpp @@ -1,197 +1,197 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_CVSTDINL_HPP -#define OPENCV_CORE_CVSTDINL_HPP - -#include -#include -#include - -//! @cond IGNORED - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4127 ) -#endif - -namespace cv -{ - -template class DataType< std::complex<_Tp> > -{ -public: - typedef std::complex<_Tp> value_type; - typedef value_type work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - depth = DataType::depth, - channels = 2, - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) }; - - typedef Vec vec_type; -}; - -static inline -std::ostream& operator << (std::ostream& out, Ptr fmtd) -{ - fmtd->reset(); - for(const char* str = fmtd->next(); str; str = fmtd->next()) - out << str; - return out; -} - -static inline -std::ostream& operator << (std::ostream& out, const Mat& mtx) -{ - return out << Formatter::get()->format(mtx); -} - -static inline -std::ostream& operator << (std::ostream& out, const UMat& m) -{ - return out << m.getMat(ACCESS_READ); -} - -template static inline -std::ostream& operator << (std::ostream& out, const Complex<_Tp>& c) -{ - return out << "(" << c.re << "," << c.im << ")"; -} - -template static inline -std::ostream& operator << (std::ostream& out, const std::vector >& vec) -{ - return out << Formatter::get()->format(Mat(vec)); -} - - -template static inline -std::ostream& operator << (std::ostream& out, const std::vector >& vec) -{ - return out << Formatter::get()->format(Mat(vec)); -} - - -template static inline -std::ostream& operator << (std::ostream& out, const Matx<_Tp, m, n>& matx) -{ - return out << Formatter::get()->format(Mat(matx)); -} - -template static inline -std::ostream& operator << (std::ostream& out, const Point_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << "]"; - return out; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Point3_<_Tp>& p) -{ - out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; - return out; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Vec<_Tp, n>& vec) -{ - out << "["; - if (cv::traits::Depth<_Tp>::value <= CV_32S) - { - for (int i = 0; i < n - 1; ++i) { - out << (int)vec[i] << ", "; - } - out << (int)vec[n-1] << "]"; - } - else - { - for (int i = 0; i < n - 1; ++i) { - out << vec[i] << ", "; - } - out << vec[n-1] << "]"; - } - - return out; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Size_<_Tp>& size) -{ - return out << "[" << size.width << " x " << size.height << "]"; -} - -template static inline -std::ostream& operator << (std::ostream& out, const Rect_<_Tp>& rect) -{ - return out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; -} - -static inline std::ostream& operator << (std::ostream& out, const MatSize& msize) -{ - int i, dims = msize.dims(); - for( i = 0; i < dims; i++ ) - { - out << msize[i]; - if( i < dims-1 ) - out << " x "; - } - return out; -} - -static inline std::ostream &operator<< (std::ostream &s, cv::Range &r) -{ - return s << "[" << r.start << " : " << r.end << ")"; -} - -} // cv - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -//! @endcond - -#endif // OPENCV_CORE_CVSTDINL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_CVSTDINL_HPP +#define OPENCV_CORE_CVSTDINL_HPP + +#include +#include +#include + +//! @cond IGNORED + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable: 4127 ) +#endif + +namespace cv +{ + +template class DataType< std::complex<_Tp> > +{ +public: + typedef std::complex<_Tp> value_type; + typedef value_type work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + depth = DataType::depth, + channels = 2, + fmt = DataType::fmt + ((channels - 1) << 8), + type = CV_MAKETYPE(depth, channels) }; + + typedef Vec vec_type; +}; + +static inline +std::ostream& operator << (std::ostream& out, Ptr fmtd) +{ + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + out << str; + return out; +} + +static inline +std::ostream& operator << (std::ostream& out, const Mat& mtx) +{ + return out << Formatter::get()->format(mtx); +} + +static inline +std::ostream& operator << (std::ostream& out, const UMat& m) +{ + return out << m.getMat(ACCESS_READ); +} + +template static inline +std::ostream& operator << (std::ostream& out, const Complex<_Tp>& c) +{ + return out << "(" << c.re << "," << c.im << ")"; +} + +template static inline +std::ostream& operator << (std::ostream& out, const std::vector >& vec) +{ + return out << Formatter::get()->format(Mat(vec)); +} + + +template static inline +std::ostream& operator << (std::ostream& out, const std::vector >& vec) +{ + return out << Formatter::get()->format(Mat(vec)); +} + + +template static inline +std::ostream& operator << (std::ostream& out, const Matx<_Tp, m, n>& matx) +{ + return out << Formatter::get()->format(Mat(matx)); +} + +template static inline +std::ostream& operator << (std::ostream& out, const Point_<_Tp>& p) +{ + out << "[" << p.x << ", " << p.y << "]"; + return out; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Point3_<_Tp>& p) +{ + out << "[" << p.x << ", " << p.y << ", " << p.z << "]"; + return out; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Vec<_Tp, n>& vec) +{ + out << "["; + if (cv::traits::Depth<_Tp>::value <= CV_32S) + { + for (int i = 0; i < n - 1; ++i) { + out << (int)vec[i] << ", "; + } + out << (int)vec[n-1] << "]"; + } + else + { + for (int i = 0; i < n - 1; ++i) { + out << vec[i] << ", "; + } + out << vec[n-1] << "]"; + } + + return out; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Size_<_Tp>& size) +{ + return out << "[" << size.width << " x " << size.height << "]"; +} + +template static inline +std::ostream& operator << (std::ostream& out, const Rect_<_Tp>& rect) +{ + return out << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; +} + +static inline std::ostream& operator << (std::ostream& out, const MatSize& msize) +{ + int i, dims = msize.dims(); + for( i = 0; i < dims; i++ ) + { + out << msize[i]; + if( i < dims-1 ) + out << " x "; + } + return out; +} + +static inline std::ostream &operator<< (std::ostream &s, cv::Range &r) +{ + return s << "[" << r.start << " : " << r.end << ")"; +} + +} // cv + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +//! @endcond + +#endif // OPENCV_CORE_CVSTDINL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp b/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp index 7770d54a83..25e0041f28 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/cvstd_wrapper.hpp @@ -1,154 +1,154 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_CVSTD_WRAPPER_HPP -#define OPENCV_CORE_CVSTD_WRAPPER_HPP - -#include "opencv2/core/cvdef.h" - -#include -#include // std::shared_ptr -#include // std::enable_if - -namespace cv { - -using std::nullptr_t; - -//! @addtogroup core_basic -//! @{ - -#ifdef CV_DOXYGEN - -template using Ptr = std::shared_ptr<_Tp>; // In ideal world it should look like this, but we need some compatibility workarounds below - -template static inline -Ptr<_Tp> makePtr(const A1&... a1) { return std::make_shared<_Tp>(a1...); } - -#else // cv::Ptr with compatibility workarounds - -// It should be defined for C-API types only. -// C++ types should use regular "delete" operator. -template struct DefaultDeleter; -#if 0 -{ - void operator()(Y* p) const; -}; -#endif - -namespace sfinae { -template -struct has_parenthesis_operator -{ -private: - template - static CV_CONSTEXPR std::true_type has_parenthesis_operator_check(typename std::is_same().operator()(std::declval()...))>::type, Ret>::type*); - - template static CV_CONSTEXPR std::false_type has_parenthesis_operator_check(...); - - typedef decltype(has_parenthesis_operator_check(0)) type; - -public: -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) - static CV_CONSTEXPR bool value = type::value; -#else - // support MSVS 2013 - static const int value = type::value; -#endif -}; -} // namespace sfinae - -template -struct has_custom_delete - : public std::false_type {}; - -// Force has_custom_delete to std::false_type when NVCC is compiling CUDA source files -#ifndef __CUDACC__ -template -struct has_custom_delete, void, T*>::value >::type > - : public std::true_type {}; -#endif - -template -struct Ptr : public std::shared_ptr -{ -#if 0 - using std::shared_ptr::shared_ptr; // GCC 5.x can't handle this -#else - inline Ptr() CV_NOEXCEPT : std::shared_ptr() {} - inline Ptr(nullptr_t) CV_NOEXCEPT : std::shared_ptr(nullptr) {} - template inline Ptr(Y* p, D d) : std::shared_ptr(p, d) {} - template inline Ptr(nullptr_t, D d) : std::shared_ptr(nullptr, d) {} - - template inline Ptr(const Ptr& r, T* ptr) CV_NOEXCEPT : std::shared_ptr(r, ptr) {} - - inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} - inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} - - template inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} - template inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} -#endif - inline Ptr(const std::shared_ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} - inline Ptr(std::shared_ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} - - // Overload with custom DefaultDeleter: Ptr(...) - template - inline Ptr(const std::true_type&, Y* ptr) : std::shared_ptr(ptr, DefaultDeleter()) {} - - // Overload without custom deleter: Ptr(...); - template - inline Ptr(const std::false_type&, Y* ptr) : std::shared_ptr(ptr) {} - - template - inline Ptr(Y* ptr) : Ptr(has_custom_delete(), ptr) {} - - // Overload with custom DefaultDeleter: Ptr(...) - template - inline void reset(const std::true_type&, Y* ptr) { std::shared_ptr::reset(ptr, DefaultDeleter()); } - - // Overload without custom deleter: Ptr(...); - template - inline void reset(const std::false_type&, Y* ptr) { std::shared_ptr::reset(ptr); } - - template - inline void reset(Y* ptr) { Ptr::reset(has_custom_delete(), ptr); } - - template - void reset(Y* ptr, Deleter d) { std::shared_ptr::reset(ptr, d); } - - void reset() CV_NOEXCEPT { std::shared_ptr::reset(); } - - Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } - template inline Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } - - T* operator->() const CV_NOEXCEPT { return std::shared_ptr::get();} - typename std::add_lvalue_reference::type operator*() const CV_NOEXCEPT { return *std::shared_ptr::get(); } - - // OpenCV 3.x methods (not a part of standard C++ library) - inline void release() { std::shared_ptr::reset(); } - inline operator T* () const { return std::shared_ptr::get(); } - inline bool empty() const { return std::shared_ptr::get() == nullptr; } - - template inline - Ptr staticCast() const CV_NOEXCEPT { return std::static_pointer_cast(*this); } - - template inline - Ptr constCast() const CV_NOEXCEPT { return std::const_pointer_cast(*this); } - - template inline - Ptr dynamicCast() const CV_NOEXCEPT { return std::dynamic_pointer_cast(*this); } -}; - -template static inline -Ptr<_Tp> makePtr(const A1&... a1) -{ - static_assert( !has_custom_delete<_Tp>::value, "Can't use this makePtr with custom DefaultDeleter"); - return (Ptr<_Tp>)std::make_shared<_Tp>(a1...); -} - -#endif // CV_DOXYGEN - -//! @} core_basic -} // cv - -#endif //OPENCV_CORE_CVSTD_WRAPPER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_CVSTD_WRAPPER_HPP +#define OPENCV_CORE_CVSTD_WRAPPER_HPP + +#include "opencv2/core/cvdef.h" + +#include +#include // std::shared_ptr +#include // std::enable_if + +namespace cv { + +using std::nullptr_t; + +//! @addtogroup core_basic +//! @{ + +#ifdef CV_DOXYGEN + +template using Ptr = std::shared_ptr<_Tp>; // In ideal world it should look like this, but we need some compatibility workarounds below + +template static inline +Ptr<_Tp> makePtr(const A1&... a1) { return std::make_shared<_Tp>(a1...); } + +#else // cv::Ptr with compatibility workarounds + +// It should be defined for C-API types only. +// C++ types should use regular "delete" operator. +template struct DefaultDeleter; +#if 0 +{ + void operator()(Y* p) const; +}; +#endif + +namespace sfinae { +template +struct has_parenthesis_operator +{ +private: + template + static CV_CONSTEXPR std::true_type has_parenthesis_operator_check(typename std::is_same().operator()(std::declval()...))>::type, Ret>::type*); + + template static CV_CONSTEXPR std::false_type has_parenthesis_operator_check(...); + + typedef decltype(has_parenthesis_operator_check(0)) type; + +public: +#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) + static CV_CONSTEXPR bool value = type::value; +#else + // support MSVS 2013 + static const int value = type::value; +#endif +}; +} // namespace sfinae + +template +struct has_custom_delete + : public std::false_type {}; + +// Force has_custom_delete to std::false_type when NVCC is compiling CUDA source files +#ifndef __CUDACC__ +template +struct has_custom_delete, void, T*>::value >::type > + : public std::true_type {}; +#endif + +template +struct Ptr : public std::shared_ptr +{ +#if 0 + using std::shared_ptr::shared_ptr; // GCC 5.x can't handle this +#else + inline Ptr() CV_NOEXCEPT : std::shared_ptr() {} + inline Ptr(nullptr_t) CV_NOEXCEPT : std::shared_ptr(nullptr) {} + template inline Ptr(Y* p, D d) : std::shared_ptr(p, d) {} + template inline Ptr(nullptr_t, D d) : std::shared_ptr(nullptr, d) {} + + template inline Ptr(const Ptr& r, T* ptr) CV_NOEXCEPT : std::shared_ptr(r, ptr) {} + + inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} + inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} + + template inline Ptr(const Ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} + template inline Ptr(Ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} +#endif + inline Ptr(const std::shared_ptr& o) CV_NOEXCEPT : std::shared_ptr(o) {} + inline Ptr(std::shared_ptr&& o) CV_NOEXCEPT : std::shared_ptr(std::move(o)) {} + + // Overload with custom DefaultDeleter: Ptr(...) + template + inline Ptr(const std::true_type&, Y* ptr) : std::shared_ptr(ptr, DefaultDeleter()) {} + + // Overload without custom deleter: Ptr(...); + template + inline Ptr(const std::false_type&, Y* ptr) : std::shared_ptr(ptr) {} + + template + inline Ptr(Y* ptr) : Ptr(has_custom_delete(), ptr) {} + + // Overload with custom DefaultDeleter: Ptr(...) + template + inline void reset(const std::true_type&, Y* ptr) { std::shared_ptr::reset(ptr, DefaultDeleter()); } + + // Overload without custom deleter: Ptr(...); + template + inline void reset(const std::false_type&, Y* ptr) { std::shared_ptr::reset(ptr); } + + template + inline void reset(Y* ptr) { Ptr::reset(has_custom_delete(), ptr); } + + template + void reset(Y* ptr, Deleter d) { std::shared_ptr::reset(ptr, d); } + + void reset() CV_NOEXCEPT { std::shared_ptr::reset(); } + + Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } + template inline Ptr& operator=(const Ptr& o) { std::shared_ptr::operator =(o); return *this; } + + T* operator->() const CV_NOEXCEPT { return std::shared_ptr::get();} + typename std::add_lvalue_reference::type operator*() const CV_NOEXCEPT { return *std::shared_ptr::get(); } + + // OpenCV 3.x methods (not a part of standard C++ library) + inline void release() { std::shared_ptr::reset(); } + inline operator T* () const { return std::shared_ptr::get(); } + inline bool empty() const { return std::shared_ptr::get() == nullptr; } + + template inline + Ptr staticCast() const CV_NOEXCEPT { return std::static_pointer_cast(*this); } + + template inline + Ptr constCast() const CV_NOEXCEPT { return std::const_pointer_cast(*this); } + + template inline + Ptr dynamicCast() const CV_NOEXCEPT { return std::dynamic_pointer_cast(*this); } +}; + +template static inline +Ptr<_Tp> makePtr(const A1&... a1) +{ + static_assert( !has_custom_delete<_Tp>::value, "Can't use this makePtr with custom DefaultDeleter"); + return (Ptr<_Tp>)std::make_shared<_Tp>(a1...); +} + +#endif // CV_DOXYGEN + +//! @} core_basic +} // cv + +#endif //OPENCV_CORE_CVSTD_WRAPPER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp b/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp index 811a24324f..c039ec046a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/detail/async_promise.hpp @@ -1,69 +1,69 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ASYNC_PROMISE_HPP -#define OPENCV_CORE_ASYNC_PROMISE_HPP - -#include "../async.hpp" - -#include "exception_ptr.hpp" - -namespace cv { - -/** @addtogroup core_async -@{ -*/ - - -/** @brief Provides result of asynchronous operations - -*/ -class CV_EXPORTS AsyncPromise -{ -public: - ~AsyncPromise() CV_NOEXCEPT; - AsyncPromise() CV_NOEXCEPT; - explicit AsyncPromise(const AsyncPromise& o) CV_NOEXCEPT; - AsyncPromise& operator=(const AsyncPromise& o) CV_NOEXCEPT; - void release() CV_NOEXCEPT; - - /** Returns associated AsyncArray - @note Can be called once - */ - AsyncArray getArrayResult(); - - /** Stores asynchronous result. - @param[in] value result - */ - void setValue(InputArray value); - - // TODO "move" setters - -#if CV__EXCEPTION_PTR - /** Stores exception. - @param[in] exception exception to be raised in AsyncArray - */ - void setException(std::exception_ptr exception); -#endif - - /** Stores exception. - @param[in] exception exception to be raised in AsyncArray - */ - void setException(const cv::Exception& exception); - - explicit AsyncPromise(AsyncPromise&& o) { p = o.p; o.p = NULL; } - AsyncPromise& operator=(AsyncPromise&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } - - - // PImpl - typedef struct AsyncArray::Impl Impl; friend struct AsyncArray::Impl; - inline void* _getImpl() const CV_NOEXCEPT { return p; } -protected: - Impl* p; -}; - - -//! @} -} // namespace -#endif // OPENCV_CORE_ASYNC_PROMISE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ASYNC_PROMISE_HPP +#define OPENCV_CORE_ASYNC_PROMISE_HPP + +#include "../async.hpp" + +#include "exception_ptr.hpp" + +namespace cv { + +/** @addtogroup core_async +@{ +*/ + + +/** @brief Provides result of asynchronous operations + +*/ +class CV_EXPORTS AsyncPromise +{ +public: + ~AsyncPromise() CV_NOEXCEPT; + AsyncPromise() CV_NOEXCEPT; + explicit AsyncPromise(const AsyncPromise& o) CV_NOEXCEPT; + AsyncPromise& operator=(const AsyncPromise& o) CV_NOEXCEPT; + void release() CV_NOEXCEPT; + + /** Returns associated AsyncArray + @note Can be called once + */ + AsyncArray getArrayResult(); + + /** Stores asynchronous result. + @param[in] value result + */ + void setValue(InputArray value); + + // TODO "move" setters + +#if CV__EXCEPTION_PTR + /** Stores exception. + @param[in] exception exception to be raised in AsyncArray + */ + void setException(std::exception_ptr exception); +#endif + + /** Stores exception. + @param[in] exception exception to be raised in AsyncArray + */ + void setException(const cv::Exception& exception); + + explicit AsyncPromise(AsyncPromise&& o) { p = o.p; o.p = NULL; } + AsyncPromise& operator=(AsyncPromise&& o) CV_NOEXCEPT { std::swap(p, o.p); return *this; } + + + // PImpl + typedef struct AsyncArray::Impl Impl; friend struct AsyncArray::Impl; + inline void* _getImpl() const CV_NOEXCEPT { return p; } +protected: + Impl* p; +}; + + +//! @} +} // namespace +#endif // OPENCV_CORE_ASYNC_PROMISE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp index 230306f914..d6ec676922 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/detail/dispatch_helper.impl.hpp @@ -1,49 +1,49 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP -#define OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP - -//! @cond IGNORED - -namespace cv { -namespace detail { - -template class Functor, typename... Args> -static inline void depthDispatch(const int depth, Args&&... args) -{ - switch (depth) - { - case CV_8U: - Functor{}(std::forward(args)...); - break; - case CV_8S: - Functor{}(std::forward(args)...); - break; - case CV_16U: - Functor{}(std::forward(args)...); - break; - case CV_16S: - Functor{}(std::forward(args)...); - break; - case CV_32S: - Functor{}(std::forward(args)...); - break; - case CV_32F: - Functor{}(std::forward(args)...); - break; - case CV_64F: - Functor{}(std::forward(args)...); - break; - case CV_16F: - default: - CV_Error(cv::Error::BadDepth, "Unsupported matrix type."); - }; -} - -}} - -//! @endcond - -#endif //OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP +#define OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP + +//! @cond IGNORED + +namespace cv { +namespace detail { + +template class Functor, typename... Args> +static inline void depthDispatch(const int depth, Args&&... args) +{ + switch (depth) + { + case CV_8U: + Functor{}(std::forward(args)...); + break; + case CV_8S: + Functor{}(std::forward(args)...); + break; + case CV_16U: + Functor{}(std::forward(args)...); + break; + case CV_16S: + Functor{}(std::forward(args)...); + break; + case CV_32S: + Functor{}(std::forward(args)...); + break; + case CV_32F: + Functor{}(std::forward(args)...); + break; + case CV_64F: + Functor{}(std::forward(args)...); + break; + case CV_16F: + default: + CV_Error(cv::Error::BadDepth, "Unsupported matrix type."); + }; +} + +}} + +//! @endcond + +#endif //OPENCV_CORE_DETAIL_DISPATCH_HELPER_IMPL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp b/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp index ed5c40f24f..a1a591e455 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/detail/exception_ptr.hpp @@ -1,21 +1,21 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_DETAILS_EXCEPTION_PTR_H -#define OPENCV_CORE_DETAILS_EXCEPTION_PTR_H - -#ifndef CV__EXCEPTION_PTR -# if defined(__ANDROID__) && defined(ATOMIC_INT_LOCK_FREE) && ATOMIC_INT_LOCK_FREE < 2 -# define CV__EXCEPTION_PTR 0 // Not supported, details: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58938 -# else -# define CV__EXCEPTION_PTR 1 -# endif -#endif -#ifndef CV__EXCEPTION_PTR -# define CV__EXCEPTION_PTR 0 -#elif CV__EXCEPTION_PTR -# include // std::exception_ptr -#endif - -#endif // OPENCV_CORE_DETAILS_EXCEPTION_PTR_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_DETAILS_EXCEPTION_PTR_H +#define OPENCV_CORE_DETAILS_EXCEPTION_PTR_H + +#ifndef CV__EXCEPTION_PTR +# if defined(__ANDROID__) && defined(ATOMIC_INT_LOCK_FREE) && ATOMIC_INT_LOCK_FREE < 2 +# define CV__EXCEPTION_PTR 0 // Not supported, details: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58938 +# else +# define CV__EXCEPTION_PTR 1 +# endif +#endif +#ifndef CV__EXCEPTION_PTR +# define CV__EXCEPTION_PTR 0 +#elif CV__EXCEPTION_PTR +# include // std::exception_ptr +#endif + +#endif // OPENCV_CORE_DETAILS_EXCEPTION_PTR_H diff --git a/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp index 431eb6e71f..056a85a1bc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/directx.hpp @@ -1,184 +1,184 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors as is and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the copyright holders or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_DIRECTX_HPP -#define OPENCV_CORE_DIRECTX_HPP - -#include "mat.hpp" -#include "ocl.hpp" - -#if !defined(__d3d11_h__) -struct ID3D11Device; -struct ID3D11Texture2D; -#endif - -#if !defined(__d3d10_h__) -struct ID3D10Device; -struct ID3D10Texture2D; -#endif - -#if !defined(_D3D9_H_) -struct IDirect3DDevice9; -struct IDirect3DDevice9Ex; -struct IDirect3DSurface9; -#endif - - -namespace cv { namespace directx { - -namespace ocl { -using namespace cv::ocl; - -//! @addtogroup core_directx -// This section describes OpenCL and DirectX interoperability. -// -// To enable DirectX support, configure OpenCV using CMake with WITH_DIRECTX=ON . Note, DirectX is -// supported only on Windows. -// -// To use OpenCL functionality you should first initialize OpenCL context from DirectX resource. -// -//! @{ - -// TODO static functions in the Context class -//! @brief Creates OpenCL context from D3D11 device -// -//! @param pD3D11Device - pointer to D3D11 device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromD3D11Device(ID3D11Device* pD3D11Device); - -//! @brief Creates OpenCL context from D3D10 device -// -//! @param pD3D10Device - pointer to D3D10 device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromD3D10Device(ID3D10Device* pD3D10Device); - -//! @brief Creates OpenCL context from Direct3DDevice9Ex device -// -//! @param pDirect3DDevice9Ex - pointer to Direct3DDevice9Ex device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromDirect3DDevice9Ex(IDirect3DDevice9Ex* pDirect3DDevice9Ex); - -//! @brief Creates OpenCL context from Direct3DDevice9 device -// -//! @param pDirect3DDevice9 - pointer to Direct3Device9 device -//! @return Returns reference to OpenCL Context -CV_EXPORTS Context& initializeContextFromDirect3DDevice9(IDirect3DDevice9* pDirect3DDevice9); - -//! @} - -} // namespace cv::directx::ocl - -//! @addtogroup core_directx -//! @{ - -//! @brief Converts InputArray to ID3D11Texture2D. If destination texture format is DXGI_FORMAT_NV12 then -//! input UMat expected to be in BGR format and data will be downsampled and color-converted to NV12. -// -//! @note Note: Destination texture must be allocated by application. Function does memory copy from src to -//! pD3D11Texture2D -// -//! @param src - source InputArray -//! @param pD3D11Texture2D - destination D3D11 texture -CV_EXPORTS void convertToD3D11Texture2D(InputArray src, ID3D11Texture2D* pD3D11Texture2D); - -//! @brief Converts ID3D11Texture2D to OutputArray. If input texture format is DXGI_FORMAT_NV12 then -//! data will be upsampled and color-converted to BGR format. -// -//! @note Note: Destination matrix will be re-allocated if it has not enough memory to match texture size. -//! function does memory copy from pD3D11Texture2D to dst -// -//! @param pD3D11Texture2D - source D3D11 texture -//! @param dst - destination OutputArray -CV_EXPORTS void convertFromD3D11Texture2D(ID3D11Texture2D* pD3D11Texture2D, OutputArray dst); - -//! @brief Converts InputArray to ID3D10Texture2D -// -//! @note Note: function does memory copy from src to -//! pD3D10Texture2D -// -//! @param src - source InputArray -//! @param pD3D10Texture2D - destination D3D10 texture -CV_EXPORTS void convertToD3D10Texture2D(InputArray src, ID3D10Texture2D* pD3D10Texture2D); - -//! @brief Converts ID3D10Texture2D to OutputArray -// -//! @note Note: function does memory copy from pD3D10Texture2D -//! to dst -// -//! @param pD3D10Texture2D - source D3D10 texture -//! @param dst - destination OutputArray -CV_EXPORTS void convertFromD3D10Texture2D(ID3D10Texture2D* pD3D10Texture2D, OutputArray dst); - -//! @brief Converts InputArray to IDirect3DSurface9 -// -//! @note Note: function does memory copy from src to -//! pDirect3DSurface9 -// -//! @param src - source InputArray -//! @param pDirect3DSurface9 - destination D3D10 texture -//! @param surfaceSharedHandle - shared handle -CV_EXPORTS void convertToDirect3DSurface9(InputArray src, IDirect3DSurface9* pDirect3DSurface9, void* surfaceSharedHandle = NULL); - -//! @brief Converts IDirect3DSurface9 to OutputArray -// -//! @note Note: function does memory copy from pDirect3DSurface9 -//! to dst -// -//! @param pDirect3DSurface9 - source D3D10 texture -//! @param dst - destination OutputArray -//! @param surfaceSharedHandle - shared handle -CV_EXPORTS void convertFromDirect3DSurface9(IDirect3DSurface9* pDirect3DSurface9, OutputArray dst, void* surfaceSharedHandle = NULL); - -//! @brief Get OpenCV type from DirectX type -//! @param iDXGI_FORMAT - enum DXGI_FORMAT for D3D10/D3D11 -//! @return OpenCV type or -1 if there is no equivalent -CV_EXPORTS int getTypeFromDXGI_FORMAT(const int iDXGI_FORMAT); // enum DXGI_FORMAT for D3D10/D3D11 - -//! @brief Get OpenCV type from DirectX type -//! @param iD3DFORMAT - enum D3DTYPE for D3D9 -//! @return OpenCV type or -1 if there is no equivalent -CV_EXPORTS int getTypeFromD3DFORMAT(const int iD3DFORMAT); // enum D3DTYPE for D3D9 - -//! @} - -} } // namespace cv::directx - -#endif // OPENCV_CORE_DIRECTX_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors as is and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the copyright holders or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_DIRECTX_HPP +#define OPENCV_CORE_DIRECTX_HPP + +#include "mat.hpp" +#include "ocl.hpp" + +#if !defined(__d3d11_h__) +struct ID3D11Device; +struct ID3D11Texture2D; +#endif + +#if !defined(__d3d10_h__) +struct ID3D10Device; +struct ID3D10Texture2D; +#endif + +#if !defined(_D3D9_H_) +struct IDirect3DDevice9; +struct IDirect3DDevice9Ex; +struct IDirect3DSurface9; +#endif + + +namespace cv { namespace directx { + +namespace ocl { +using namespace cv::ocl; + +//! @addtogroup core_directx +// This section describes OpenCL and DirectX interoperability. +// +// To enable DirectX support, configure OpenCV using CMake with WITH_DIRECTX=ON . Note, DirectX is +// supported only on Windows. +// +// To use OpenCL functionality you should first initialize OpenCL context from DirectX resource. +// +//! @{ + +// TODO static functions in the Context class +//! @brief Creates OpenCL context from D3D11 device +// +//! @param pD3D11Device - pointer to D3D11 device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromD3D11Device(ID3D11Device* pD3D11Device); + +//! @brief Creates OpenCL context from D3D10 device +// +//! @param pD3D10Device - pointer to D3D10 device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromD3D10Device(ID3D10Device* pD3D10Device); + +//! @brief Creates OpenCL context from Direct3DDevice9Ex device +// +//! @param pDirect3DDevice9Ex - pointer to Direct3DDevice9Ex device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromDirect3DDevice9Ex(IDirect3DDevice9Ex* pDirect3DDevice9Ex); + +//! @brief Creates OpenCL context from Direct3DDevice9 device +// +//! @param pDirect3DDevice9 - pointer to Direct3Device9 device +//! @return Returns reference to OpenCL Context +CV_EXPORTS Context& initializeContextFromDirect3DDevice9(IDirect3DDevice9* pDirect3DDevice9); + +//! @} + +} // namespace cv::directx::ocl + +//! @addtogroup core_directx +//! @{ + +//! @brief Converts InputArray to ID3D11Texture2D. If destination texture format is DXGI_FORMAT_NV12 then +//! input UMat expected to be in BGR format and data will be downsampled and color-converted to NV12. +// +//! @note Note: Destination texture must be allocated by application. Function does memory copy from src to +//! pD3D11Texture2D +// +//! @param src - source InputArray +//! @param pD3D11Texture2D - destination D3D11 texture +CV_EXPORTS void convertToD3D11Texture2D(InputArray src, ID3D11Texture2D* pD3D11Texture2D); + +//! @brief Converts ID3D11Texture2D to OutputArray. If input texture format is DXGI_FORMAT_NV12 then +//! data will be upsampled and color-converted to BGR format. +// +//! @note Note: Destination matrix will be re-allocated if it has not enough memory to match texture size. +//! function does memory copy from pD3D11Texture2D to dst +// +//! @param pD3D11Texture2D - source D3D11 texture +//! @param dst - destination OutputArray +CV_EXPORTS void convertFromD3D11Texture2D(ID3D11Texture2D* pD3D11Texture2D, OutputArray dst); + +//! @brief Converts InputArray to ID3D10Texture2D +// +//! @note Note: function does memory copy from src to +//! pD3D10Texture2D +// +//! @param src - source InputArray +//! @param pD3D10Texture2D - destination D3D10 texture +CV_EXPORTS void convertToD3D10Texture2D(InputArray src, ID3D10Texture2D* pD3D10Texture2D); + +//! @brief Converts ID3D10Texture2D to OutputArray +// +//! @note Note: function does memory copy from pD3D10Texture2D +//! to dst +// +//! @param pD3D10Texture2D - source D3D10 texture +//! @param dst - destination OutputArray +CV_EXPORTS void convertFromD3D10Texture2D(ID3D10Texture2D* pD3D10Texture2D, OutputArray dst); + +//! @brief Converts InputArray to IDirect3DSurface9 +// +//! @note Note: function does memory copy from src to +//! pDirect3DSurface9 +// +//! @param src - source InputArray +//! @param pDirect3DSurface9 - destination D3D10 texture +//! @param surfaceSharedHandle - shared handle +CV_EXPORTS void convertToDirect3DSurface9(InputArray src, IDirect3DSurface9* pDirect3DSurface9, void* surfaceSharedHandle = NULL); + +//! @brief Converts IDirect3DSurface9 to OutputArray +// +//! @note Note: function does memory copy from pDirect3DSurface9 +//! to dst +// +//! @param pDirect3DSurface9 - source D3D10 texture +//! @param dst - destination OutputArray +//! @param surfaceSharedHandle - shared handle +CV_EXPORTS void convertFromDirect3DSurface9(IDirect3DSurface9* pDirect3DSurface9, OutputArray dst, void* surfaceSharedHandle = NULL); + +//! @brief Get OpenCV type from DirectX type +//! @param iDXGI_FORMAT - enum DXGI_FORMAT for D3D10/D3D11 +//! @return OpenCV type or -1 if there is no equivalent +CV_EXPORTS int getTypeFromDXGI_FORMAT(const int iDXGI_FORMAT); // enum DXGI_FORMAT for D3D10/D3D11 + +//! @brief Get OpenCV type from DirectX type +//! @param iD3DFORMAT - enum D3DTYPE for D3D9 +//! @return OpenCV type or -1 if there is no equivalent +CV_EXPORTS int getTypeFromD3DFORMAT(const int iD3DFORMAT); // enum D3DTYPE for D3D9 + +//! @} + +} } // namespace cv::directx + +#endif // OPENCV_CORE_DIRECTX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp index 990ca101c6..4fec990461 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.hpp @@ -1,979 +1,979 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang -#ifndef OPENCV_CORE_DUALQUATERNION_HPP -#define OPENCV_CORE_DUALQUATERNION_HPP - -#include -#include - -namespace cv{ -//! @addtogroup core_quaternion -//! @{ - -template class DualQuat; -template std::ostream& operator<<(std::ostream&, const DualQuat<_Tp>&); - -/** - * Dual quaternions were introduced to describe rotation together with translation while ordinary - * quaternions can only describe rotation. It can be used for shortest path pose interpolation, - * local pose optimization or volumetric deformation. More details can be found - * - https://en.wikipedia.org/wiki/Dual_quaternion - * - ["A beginners guide to dual-quaternions: what they are, how they work, and how to use them for 3D character hierarchies", Ben Kenwright, 2012](https://borodust.org/public/shared/beginner_dual_quats.pdf) - * - ["Dual Quaternions", Yan-Bin Jia, 2013](http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf) - * - ["Geometric Skinning with Approximate Dual Quaternion Blending", Kavan, 2008](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric) - * - http://rodolphe-vaillant.fr/?e=29 - * - * A unit dual quaternion can be classically represented as: - * \f[ - * \begin{equation} - * \begin{split} - * \sigma &= \left(r+\frac{\epsilon}{2}tr\right)\\ - * &= [w, x, y, z, w\_, x\_, y\_, z\_] - * \end{split} - * \end{equation} - * \f] - * where \f$r, t\f$ represents the rotation (ordinary unit quaternion) and translation (pure ordinary quaternion) respectively. - * - * A general dual quaternions which consist of two quaternions is usually represented in form of: - * \f[ - * \sigma = p + \epsilon q - * \f] - * where the introduced dual unit \f$\epsilon\f$ satisfies \f$\epsilon^2 = \epsilon^3 =...=0\f$, and \f$p, q\f$ are quaternions. - * - * Alternatively, dual quaternions can also be interpreted as four components which are all [dual numbers](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric): - * \f[ - * \sigma = \hat{q}_w + \hat{q}_xi + \hat{q}_yj + \hat{q}_zk - * \f] - * If we set \f$\hat{q}_x, \hat{q}_y\f$ and \f$\hat{q}_z\f$ equal to 0, a dual quaternion is transformed to a dual number. see normalize(). - * - * If you want to create a dual quaternion, you can use: - * - * ``` - * using namespace cv; - * double angle = CV_PI; - * - * // create from eight number - * DualQuatd dq1(1, 2, 3, 4, 5, 6, 7, 8); //p = [1,2,3,4]. q=[5,6,7,8] - * - * // create from Vec - * Vec v{1,2,3,4,5,6,7,8}; - * DualQuatd dq_v{v}; - * - * // create from two quaternion - * Quatd p(1, 2, 3, 4); - * Quatd q(5, 6, 7, 8); - * DualQuatd dq2 = DualQuatd::createFromQuat(p, q); - * - * // create from an angle, an axis and a translation - * Vec3d axis{0, 0, 1}; - * Vec3d trans{3, 4, 5}; - * DualQuatd dq3 = DualQuatd::createFromAngleAxisTrans(angle, axis, trans); - * - * // If you already have an instance of class Affine3, then you can use - * Affine3d R = dq3.toAffine3(); - * DualQuatd dq4 = DualQuatd::createFromAffine3(R); - * - * // or create directly by affine transformation matrix Rt - * // see createFromMat() in detail for the form of Rt - * Matx44d Rt = dq3.toMat(); - * DualQuatd dq5 = DualQuatd::createFromMat(Rt); - * - * // Any rotation + translation movement can - * // be expressed as a rotation + translation around the same line in space (expressed by Plucker - * // coords), and here's a way to represent it this way. - * Vec3d axis{1, 1, 1}; // axis will be normalized in createFromPitch - * Vec3d trans{3, 4 ,5}; - * axis = axis / std::sqrt(axis.dot(axis));// The formula for computing moment that I use below requires a normalized axis - * Vec3d moment = 1.0 / 2 * (trans.cross(axis) + axis.cross(trans.cross(axis)) * - * std::cos(rotation_angle / 2) / std::sin(rotation_angle / 2)); - * double d = trans.dot(qaxis); - * DualQuatd dq6 = DualQuatd::createFromPitch(angle, d, axis, moment); - * ``` - * - * A point \f$v=(x, y, z)\f$ in form of dual quaternion is \f$[1+\epsilon v]=[1,0,0,0,0,x,y,z]\f$. - * The transformation of a point \f$v_1\f$ to another point \f$v_2\f$ under the dual quaternion \f$\sigma\f$ is - * \f[ - * 1 + \epsilon v_2 = \sigma * (1 + \epsilon v_1) * \sigma^{\star} - * \f] - * where \f$\sigma^{\star}=p^*-\epsilon q^*.\f$ - * - * A line in the \f$Pl\ddot{u}cker\f$ coordinates \f$(\hat{l}, m)\f$ defined by the dual quaternion \f$l=\hat{l}+\epsilon m\f$. - * To transform a line, \f[l_2 = \sigma * l_1 * \sigma^*,\f] where \f$\sigma=r+\frac{\epsilon}{2}rt\f$ and - * \f$\sigma^*=p^*+\epsilon q^*\f$. - * - * To extract the Vec or Vec, see toVec(); - * - * To extract the affine transformation matrix, see toMat(); - * - * To extract the instance of Affine3, see toAffine3(); - * - * If two quaternions \f$q_0, q_1\f$ are needed to be interpolated, you can use sclerp() - * ``` - * DualQuatd::sclerp(q0, q1, t) - * ``` - * or dqblend(). - * ``` - * DualQuatd::dqblend(q0, q1, t) - * ``` - * With more than two dual quaternions to be blended, you can use generalize linear dual quaternion blending - * with the corresponding weights, i.e. gdqblend(). - * - */ -template -class CV_EXPORTS DualQuat{ - static_assert(std::is_floating_point<_Tp>::value, "Dual quaternion only make sense with type of float or double"); - using value_type = _Tp; - -public: - static constexpr _Tp CV_DUAL_QUAT_EPS = (_Tp)1.e-6; - - DualQuat(); - - /** - * @brief create from eight same type numbers. - */ - DualQuat(const _Tp w, const _Tp x, const _Tp y, const _Tp z, const _Tp w_, const _Tp x_, const _Tp y_, const _Tp z_); - - /** - * @brief create from a double or float vector. - */ - DualQuat(const Vec<_Tp, 8> &q); - - _Tp w, x, y, z, w_, x_, y_, z_; - - /** - * @brief create Dual Quaternion from two same type quaternions p and q. - * A Dual Quaternion \f$\sigma\f$ has the form: - * \f[\sigma = p + \epsilon q\f] - * where p and q are defined as follows: - * \f[\begin{equation} - * \begin{split} - * p &= w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\\ - * q &= w\_ + x\_\boldsymbol{i} + y\_\boldsymbol{j} + z\_\boldsymbol{k}. - * \end{split} - * \end{equation} - * \f] - * The p and q are the real part and dual part respectively. - * @param realPart a quaternion, real part of dual quaternion. - * @param dualPart a quaternion, dual part of dual quaternion. - * @sa Quat - */ - static DualQuat<_Tp> createFromQuat(const Quat<_Tp> &realPart, const Quat<_Tp> &dualPart); - - /** - * @brief create a dual quaternion from a rotation angle \f$\theta\f$, a rotation axis - * \f$\boldsymbol{u}\f$ and a translation \f$\boldsymbol{t}\f$. - * It generates a dual quaternion \f$\sigma\f$ in the form of - * \f[\begin{equation} - * \begin{split} - * \sigma &= r + \frac{\epsilon}{2}\boldsymbol{t}r \\ - * &= [\cos(\frac{\theta}{2}), \boldsymbol{u}\sin(\frac{\theta}{2})] - * + \frac{\epsilon}{2}[0, \boldsymbol{t}][[\cos(\frac{\theta}{2}), - * \boldsymbol{u}\sin(\frac{\theta}{2})]]\\ - * &= \cos(\frac{\theta}{2}) + \boldsymbol{u}\sin(\frac{\theta}{2}) - * + \frac{\epsilon}{2}(-(\boldsymbol{t} \cdot \boldsymbol{u})\sin(\frac{\theta}{2}) - * + \boldsymbol{t}\cos(\frac{\theta}{2}) + \boldsymbol{u} \times \boldsymbol{t} \sin(\frac{\theta}{2})). - * \end{split} - * \end{equation}\f] - * @param angle rotation angle. - * @param axis rotation axis. - * @param translation a vector of length 3. - * @note Axis will be normalized in this function. And translation is applied - * after the rotation. Use @ref createFromQuat(r, r * t / 2) to create a dual quaternion - * which translation is applied before rotation. - * @sa Quat - */ - static DualQuat<_Tp> createFromAngleAxisTrans(const _Tp angle, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &translation); - - /** - * @brief Transform this dual quaternion to an affine transformation matrix \f$M\f$. - * Dual quaternion consists of a rotation \f$r=[a,b,c,d]\f$ and a translation \f$t=[\Delta x,\Delta y,\Delta z]\f$. The - * affine transformation matrix \f$M\f$ has the form - * \f[ - * \begin{bmatrix} - * 1-2(e_2^2 +e_3^2) &2(e_1e_2-e_0e_3) &2(e_0e_2+e_1e_3) &\Delta x\\ - * 2(e_0e_3+e_1e_2) &1-2(e_1^2+e_3^2) &2(e_2e_3-e_0e_1) &\Delta y\\ - * 2(e_1e_3-e_0e_2) &2(e_0e_1+e_2e_3) &1-2(e_1^2-e_2^2) &\Delta z\\ - * 0&0&0&1 - * \end{bmatrix} - * \f] - * if A is a matrix consisting of n points to be transformed, this could be achieved by - * \f[ - * new\_A = M * A - * \f] - * where A has the form - * \f[ - * \begin{bmatrix} - * x_0& x_1& x_2&...&x_n\\ - * y_0& y_1& y_2&...&y_n\\ - * z_0& z_1& z_2&...&z_n\\ - * 1&1&1&...&1 - * \end{bmatrix} - * \f] - * where the same subscript represent the same point. The size of A should be \f$[4,n]\f$. - * and the same size for matrix new_A. - * @param _R 4x4 matrix that represents rotations and translation. - * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create - * a dual quaternion which translation is applied before rotation. - */ - static DualQuat<_Tp> createFromMat(InputArray _R); - - /** - * @brief create dual quaternion from an affine matrix. The definition of affine matrix can refer to createFromMat() - */ - static DualQuat<_Tp> createFromAffine3(const Affine3<_Tp> &R); - - /** - * @brief A dual quaternion is a vector in form of - * \f[ - * \begin{equation} - * \begin{split} - * \sigma &=\boldsymbol{p} + \epsilon \boldsymbol{q}\\ - * &= \cos\hat{\frac{\theta}{2}}+\overline{\hat{l}}\sin\frac{\hat{\theta}}{2} - * \end{split} - * \end{equation} - * \f] - * where \f$\hat{\theta}\f$ is dual angle and \f$\overline{\hat{l}}\f$ is dual axis: - * \f[ - * \hat{\theta}=\theta + \epsilon d,\\ - * \overline{\hat{l}}= \hat{l} +\epsilon m. - * \f] - * In this representation, \f$\theta\f$ is rotation angle and \f$(\hat{l},m)\f$ is the screw axis, d is the translation distance along the axis. - * - * @param angle rotation angle. - * @param d translation along the rotation axis. - * @param axis rotation axis represented by quaternion with w = 0. - * @param moment the moment of line, and it should be orthogonal to axis. - * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create - * a dual quaternion which translation is applied before rotation. - */ - static DualQuat<_Tp> createFromPitch(const _Tp angle, const _Tp d, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &moment); - - /** - * @brief return a quaternion which represent the real part of dual quaternion. - * The definition of real part is in createFromQuat(). - * @sa createFromQuat, getDualPart - */ - Quat<_Tp> getRealPart() const; - - /** - * @brief return a quaternion which represent the dual part of dual quaternion. - * The definition of dual part is in createFromQuat(). - * @sa createFromQuat, getRealPart - */ - Quat<_Tp> getDualPart() const; - - /** - * @brief return the conjugate of a dual quaternion. - * \f[ - * \begin{equation} - * \begin{split} - * \sigma^* &= (p + \epsilon q)^* - * &= (p^* + \epsilon q^*) - * \end{split} - * \end{equation} - * \f] - * @param dq a dual quaternion. - */ - template - friend DualQuat conjugate(const DualQuat &dq); - - /** - * @brief return the conjugate of a dual quaternion. - * \f[ - * \begin{equation} - * \begin{split} - * \sigma^* &= (p + \epsilon q)^* - * &= (p^* + \epsilon q^*) - * \end{split} - * \end{equation} - * \f] - */ - DualQuat<_Tp> conjugate() const; - - /** - * @brief return the rotation in quaternion form. - */ - Quat<_Tp> getRotation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the translation vector. - * The rotation \f$r\f$ in this dual quaternion \f$\sigma\f$ is applied before translation \f$t\f$. - * The dual quaternion \f$\sigma\f$ is defined as - * \f[\begin{equation} - * \begin{split} - * \sigma &= p + \epsilon q \\ - * &= r + \frac{\epsilon}{2}{t}r. - * \end{split} - * \end{equation}\f] - * Thus, the translation can be obtained as follows - * \f[t = 2qp^*.\f] - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - * @note This dual quaternion's translation is applied after the rotation. - */ - Vec<_Tp, 3> getTranslation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the norm \f$||\sigma||\f$ of dual quaternion \f$\sigma = p + \epsilon q\f$. - * \f[ - * \begin{equation} - * \begin{split} - * ||\sigma|| &= \sqrt{\sigma * \sigma^*} \\ - * &= ||p|| + \epsilon \frac{p \cdot q}{||p||}. - * \end{split} - * \end{equation} - * \f] - * Generally speaking, the norm of a not unit dual - * quaternion is a dual number. For convenience, we return it in the form of a dual quaternion - * , i.e. - * \f[ ||\sigma|| = [||p||, 0, 0, 0, \frac{p \cdot q}{||p||}, 0, 0, 0].\f] - * - * @note The data type of dual number is dual quaternion. - */ - DualQuat<_Tp> norm() const; - - /** - * @brief return a normalized dual quaternion. - * A dual quaternion can be expressed as - * \f[ - * \begin{equation} - * \begin{split} - * \sigma &= p + \epsilon q\\ - * &=||\sigma||\left(r+\frac{1}{2}tr\right) - * \end{split} - * \end{equation} - * \f] - * where \f$r, t\f$ represents the rotation (ordinary quaternion) and translation (pure ordinary quaternion) respectively, - * and \f$||\sigma||\f$ is the norm of dual quaternion(a dual number). - * A dual quaternion is unit if and only if - * \f[ - * ||p||=1, p \cdot q=0 - * \f] - * where \f$\cdot\f$ means dot product. - * The process of normalization is - * \f[ - * \sigma_{u}=\frac{\sigma}{||\sigma||} - * \f] - * Next, we simply proof \f$\sigma_u\f$ is a unit dual quaternion: - * \f[ - * \renewcommand{\Im}{\operatorname{Im}} - * \begin{equation} - * \begin{split} - * \sigma_{u}=\frac{\sigma}{||\sigma||}&=\frac{p + \epsilon q}{||p||+\epsilon\frac{p\cdot q}{||p||}}\\ - * &=\frac{p}{||p||}+\epsilon\left(\frac{q}{||p||}-p\frac{p\cdot q}{||p||^3}\right)\\ - * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\left(qp^{*}-p\cdot q\right)\frac{p}{||p||}\\ - * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\Im(qp^*)\frac{p}{||p||}.\\ - * \end{split} - * \end{equation} - * \f] - * As expected, the real part is a rotation and dual part is a pure quaternion. - */ - DualQuat<_Tp> normalize() const; - - /** - * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, - * the inverse dual quaternion is - * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] - * or equivalentlly, - * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] - * @param dq a dual quaternion. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion - * and this function will save some computations. - */ - template - friend DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit); - - /** - * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, - * the inverse dual quaternion is - * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] - * or equivalentlly, - * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the dot product of two dual quaternion. - * @param p other dual quaternion. - */ - _Tp dot(DualQuat<_Tp> p) const; - - /** - ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. - * This could be calculated as: - * \f[ - * p^t = \exp(t\ln p) - * \f] - * @param dq a dual quaternion. - * @param t index of power function. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion - * and this function will save some computations. - */ - template - friend DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit); - - /** - ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. - * This could be calculated as: - * \f[ - * p^t = \exp(t\ln p) - * \f] - * - * @param t index of power function. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> power(const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. - * This could be calculated as: - * \f[ - * p^q = \exp(q\ln p) - * \f] - * @param p a dual quaternion. - * @param q a dual quaternion. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion p assume to be a dual unit quaternion - * and this function will save some computations. - */ - template - friend DualQuat power(const DualQuat& p, const DualQuat& q, QuatAssumeType assumeUnit); - - /** - * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. - * This could be calculated as: - * \f[ - * p^q = \exp(q\ln p) - * \f] - * - * @param q a dual quaternion - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a dual unit quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> power(const DualQuat<_Tp>& q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of exponential function value - * @param dq a dual quaternion. - */ - template - friend DualQuat exp(const DualQuat &dq); - - /** - * @brief return the value of exponential function value - */ - DualQuat<_Tp> exp() const; - - /** - * @brief return the value of logarithm function value - * - * @param dq a dual quaternion. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion - * and this function will save some computations. - */ - template - friend DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit); - - /** - * @brief return the value of logarithm function value - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - */ - DualQuat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief Transform this dual quaternion to a vector. - */ - Vec<_Tp, 8> toVec() const; - - /** - * @brief Transform this dual quaternion to a affine transformation matrix - * the form of matrix, see createFromMat(). - */ - Matx<_Tp, 4, 4> toMat(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief Transform this dual quaternion to a instance of Affine3. - */ - Affine3<_Tp> toAffine3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief The screw linear interpolation(ScLERP) is an extension of spherical linear interpolation of dual quaternion. - * If \f$\sigma_1\f$ and \f$\sigma_2\f$ are two dual quaternions representing the initial and final pose. - * The interpolation of ScLERP function can be defined as: - * \f[ - * ScLERP(t;\sigma_1,\sigma_2) = \sigma_1 * (\sigma_1^{-1} * \sigma_2)^t, t\in[0,1] - * \f] - * - * @param q1 a dual quaternion represents a initial pose. - * @param q2 a dual quaternion represents a final pose. - * @param t interpolation parameter - * @param directChange if true, it always return the shortest path. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - * - * For example - * ``` - * double angle1 = CV_PI / 2; - * Vec3d axis{0, 0, 1}; - * Vec3d t(0, 0, 3); - * DualQuatd initial = DualQuatd::createFromAngleAxisTrans(angle1, axis, t); - * double angle2 = CV_PI; - * DualQuatd final = DualQuatd::createFromAngleAxisTrans(angle2, axis, t); - * DualQuatd inter = DualQuatd::sclerp(initial, final, 0.5); - * ``` - */ - static DualQuat<_Tp> sclerp(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, - bool directChange=true, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - /** - * @brief The method of Dual Quaternion linear Blending(DQB) is to compute a transformation between dual quaternion - * \f$q_1\f$ and \f$q_2\f$ and can be defined as: - * \f[ - * DQB(t;{\boldsymbol{q}}_1,{\boldsymbol{q}}_2)= - * \frac{(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2}{||(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2||}. - * \f] - * where \f$q_1\f$ and \f$q_2\f$ are unit dual quaternions representing the input transformations. - * If you want to use DQB that works for more than two rigid transformations, see @ref gdqblend - * - * @param q1 a unit dual quaternion representing the input transformations. - * @param q2 a unit dual quaternion representing the input transformations. - * @param t parameter \f$t\in[0,1]\f$. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion - * and this function will save some computations. - * - * @sa gdqblend - */ - static DualQuat<_Tp> dqblend(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, - QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. - * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights - * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply - * \f[ - * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} - * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. - * \f] - * @param dualquat vector of dual quaternions - * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should - * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions - * and this function will save some computations. - * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. - */ - template - static DualQuat<_Tp> gdqblend(const Vec, cn> &dualquat, InputArray weights, - QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. - * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights - * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply - * \f[ - * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} - * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. - * \f] - * @param dualquat The dual quaternions which have 8 channels and 1 row or 1 col. - * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should - * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. - * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions - * and this function will save some computations. - * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. - */ - static DualQuat<_Tp> gdqblend(InputArray dualquat, InputArray weights, - QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief Return opposite dual quaternion \f$-p\f$ - * which satisfies \f$p + (-p) = 0.\f$ - * - * For example - * ``` - * DualQuatd q{1, 2, 3, 4, 5, 6, 7, 8}; - * std::cout << -q << std::endl; // [-1, -2, -3, -4, -5, -6, -7, -8] - * ``` - */ - DualQuat<_Tp> operator-() const; - - /** - * @brief return true if two dual quaternions p and q are nearly equal, i.e. when the absolute - * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_DUAL_QUAT_EPS. - */ - bool operator==(const DualQuat<_Tp>&) const; - - /** - * @brief Subtraction operator of two dual quaternions p and q. - * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p - q << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] - * ``` - */ - DualQuat<_Tp> operator-(const DualQuat<_Tp>&) const; - - /** - * @brief Subtraction assignment operator of two dual quaternions p and q. - * It subtracts right operand from the left operand and assign the result to left operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p -= q; // equivalent to p = p - q - * std::cout << p << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] - * - * ``` - */ - DualQuat<_Tp>& operator-=(const DualQuat<_Tp>&); - - /** - * @brief Addition operator of two dual quaternions p and q. - * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p + q << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] - * ``` - */ - DualQuat<_Tp> operator+(const DualQuat<_Tp>&) const; - - /** - * @brief Addition assignment operator of two dual quaternions p and q. - * It adds right operand to the left operand and assign the result to left operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p += q; // equivalent to p = p + q - * std::cout << p << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] - * - * ``` - */ - DualQuat<_Tp>& operator+=(const DualQuat<_Tp>&); - - /** - * @brief Multiplication assignment operator of two quaternions. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication: - * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [A, B][C, D]\\ - * &=[AC, AD + BC] - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p *= q; - * std::cout << p << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] - * ``` - */ - DualQuat<_Tp>& operator*=(const DualQuat<_Tp>&); - - /** - * @brief Multiplication assignment operator of a quaternions and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ - * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * p *= s; - * std::cout << p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - DualQuat<_Tp> operator*=(const _Tp s); - - - /** - * @brief Multiplication operator of two dual quaternions q and p. - * Multiplies values on either side of the operator. - * - * Rule of dual quaternion multiplication: - * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [A, B][C, D]\\ - * &=[AC, AD + BC] - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p * q << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] - * ``` - */ - DualQuat<_Tp> operator*(const DualQuat<_Tp>&) const; - - /** - * @brief Division operator of a dual quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of dual quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z, w\_, x\_, y\_, z\_] / s\\ - * &=[w/s, x/s, y/s, z/s, w\_/s, x\_/s, y\_/s, z\_/s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4] - * ``` - * @note the type of scalar should be equal to this dual quaternion. - */ - DualQuat<_Tp> operator/(const _Tp s) const; - - /** - * @brief Division operator of two dual quaternions p and q. - * Divides left hand operand by right hand operand. - * - * Rule of dual quaternion division with a dual quaternion: - * \f[ - * \begin{equation} - * \begin{split} - * p / q &= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * std::cout << p / q << std::endl; // equivalent to p * q.inv() - * ``` - */ - DualQuat<_Tp> operator/(const DualQuat<_Tp>&) const; - - /** - * @brief Division assignment operator of two dual quaternions p and q; - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of dual quaternion division with a quaternion: - * \f[ - * \begin{equation} - * \begin{split} - * p / q&= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; - * p /= q; // equivalent to p = p * q.inv() - * std::cout << p << std::endl; - * ``` - */ - DualQuat<_Tp>& operator/=(const DualQuat<_Tp>&); - - /** - * @brief Division assignment operator of a dual quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of dual quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z, w\_, x\_, y\_ ,z\_] / s\\ - * &=[w / s, x / s, y / s, z / s, w\_ / \space s, x\_ / \space s, y\_ / \space s, z\_ / \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0;; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - Quat<_Tp>& operator/=(const _Tp s); - - /** - * @brief Addition operator of a scalar and a dual quaternions. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator+(const T s, const DualQuat&); - - /** - * @brief Addition operator of a dual quaternions and a scalar. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator+(const DualQuat&, const T s); - - /** - * @brief Multiplication operator of a scalar and a dual quaternions. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ - * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * std::cout << s * p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator*(const T s, const DualQuat&); - - /** - * @brief Subtraction operator of a dual quaternion and a scalar. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << p - scalar << std::endl; //[-1, 2, 3, 4, 5, 6, 7, 8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator-(const DualQuat&, const T s); - - /** - * @brief Subtraction operator of a scalar and a dual quaternions. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double scalar = 2.0; - * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4, -5, -6, -7, -8] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator-(const T s, const DualQuat&); - - /** - * @brief Multiplication operator of a dual quaternions and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of dual quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ - * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; - * double s = 2.0; - * std::cout << p * s << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] - * ``` - * @note the type of scalar should be equal to the dual quaternion. - */ - template - friend DualQuat cv::operator*(const DualQuat&, const T s); - - template - friend std::ostream& cv::operator<<(std::ostream&, const DualQuat&); - -}; - -using DualQuatd = DualQuat; -using DualQuatf = DualQuat; - -//! @} core -}//namespace - -#include "dualquaternion.inl.hpp" - -#endif /* OPENCV_CORE_QUATERNION_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang +#ifndef OPENCV_CORE_DUALQUATERNION_HPP +#define OPENCV_CORE_DUALQUATERNION_HPP + +#include +#include + +namespace cv{ +//! @addtogroup core_quaternion +//! @{ + +template class DualQuat; +template std::ostream& operator<<(std::ostream&, const DualQuat<_Tp>&); + +/** + * Dual quaternions were introduced to describe rotation together with translation while ordinary + * quaternions can only describe rotation. It can be used for shortest path pose interpolation, + * local pose optimization or volumetric deformation. More details can be found + * - https://en.wikipedia.org/wiki/Dual_quaternion + * - ["A beginners guide to dual-quaternions: what they are, how they work, and how to use them for 3D character hierarchies", Ben Kenwright, 2012](https://borodust.org/public/shared/beginner_dual_quats.pdf) + * - ["Dual Quaternions", Yan-Bin Jia, 2013](http://web.cs.iastate.edu/~cs577/handouts/dual-quaternion.pdf) + * - ["Geometric Skinning with Approximate Dual Quaternion Blending", Kavan, 2008](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric) + * - http://rodolphe-vaillant.fr/?e=29 + * + * A unit dual quaternion can be classically represented as: + * \f[ + * \begin{equation} + * \begin{split} + * \sigma &= \left(r+\frac{\epsilon}{2}tr\right)\\ + * &= [w, x, y, z, w\_, x\_, y\_, z\_] + * \end{split} + * \end{equation} + * \f] + * where \f$r, t\f$ represents the rotation (ordinary unit quaternion) and translation (pure ordinary quaternion) respectively. + * + * A general dual quaternions which consist of two quaternions is usually represented in form of: + * \f[ + * \sigma = p + \epsilon q + * \f] + * where the introduced dual unit \f$\epsilon\f$ satisfies \f$\epsilon^2 = \epsilon^3 =...=0\f$, and \f$p, q\f$ are quaternions. + * + * Alternatively, dual quaternions can also be interpreted as four components which are all [dual numbers](https://www.cs.utah.edu/~ladislav/kavan08geometric/kavan08geometric): + * \f[ + * \sigma = \hat{q}_w + \hat{q}_xi + \hat{q}_yj + \hat{q}_zk + * \f] + * If we set \f$\hat{q}_x, \hat{q}_y\f$ and \f$\hat{q}_z\f$ equal to 0, a dual quaternion is transformed to a dual number. see normalize(). + * + * If you want to create a dual quaternion, you can use: + * + * ``` + * using namespace cv; + * double angle = CV_PI; + * + * // create from eight number + * DualQuatd dq1(1, 2, 3, 4, 5, 6, 7, 8); //p = [1,2,3,4]. q=[5,6,7,8] + * + * // create from Vec + * Vec v{1,2,3,4,5,6,7,8}; + * DualQuatd dq_v{v}; + * + * // create from two quaternion + * Quatd p(1, 2, 3, 4); + * Quatd q(5, 6, 7, 8); + * DualQuatd dq2 = DualQuatd::createFromQuat(p, q); + * + * // create from an angle, an axis and a translation + * Vec3d axis{0, 0, 1}; + * Vec3d trans{3, 4, 5}; + * DualQuatd dq3 = DualQuatd::createFromAngleAxisTrans(angle, axis, trans); + * + * // If you already have an instance of class Affine3, then you can use + * Affine3d R = dq3.toAffine3(); + * DualQuatd dq4 = DualQuatd::createFromAffine3(R); + * + * // or create directly by affine transformation matrix Rt + * // see createFromMat() in detail for the form of Rt + * Matx44d Rt = dq3.toMat(); + * DualQuatd dq5 = DualQuatd::createFromMat(Rt); + * + * // Any rotation + translation movement can + * // be expressed as a rotation + translation around the same line in space (expressed by Plucker + * // coords), and here's a way to represent it this way. + * Vec3d axis{1, 1, 1}; // axis will be normalized in createFromPitch + * Vec3d trans{3, 4 ,5}; + * axis = axis / std::sqrt(axis.dot(axis));// The formula for computing moment that I use below requires a normalized axis + * Vec3d moment = 1.0 / 2 * (trans.cross(axis) + axis.cross(trans.cross(axis)) * + * std::cos(rotation_angle / 2) / std::sin(rotation_angle / 2)); + * double d = trans.dot(qaxis); + * DualQuatd dq6 = DualQuatd::createFromPitch(angle, d, axis, moment); + * ``` + * + * A point \f$v=(x, y, z)\f$ in form of dual quaternion is \f$[1+\epsilon v]=[1,0,0,0,0,x,y,z]\f$. + * The transformation of a point \f$v_1\f$ to another point \f$v_2\f$ under the dual quaternion \f$\sigma\f$ is + * \f[ + * 1 + \epsilon v_2 = \sigma * (1 + \epsilon v_1) * \sigma^{\star} + * \f] + * where \f$\sigma^{\star}=p^*-\epsilon q^*.\f$ + * + * A line in the \f$Pl\ddot{u}cker\f$ coordinates \f$(\hat{l}, m)\f$ defined by the dual quaternion \f$l=\hat{l}+\epsilon m\f$. + * To transform a line, \f[l_2 = \sigma * l_1 * \sigma^*,\f] where \f$\sigma=r+\frac{\epsilon}{2}rt\f$ and + * \f$\sigma^*=p^*+\epsilon q^*\f$. + * + * To extract the Vec or Vec, see toVec(); + * + * To extract the affine transformation matrix, see toMat(); + * + * To extract the instance of Affine3, see toAffine3(); + * + * If two quaternions \f$q_0, q_1\f$ are needed to be interpolated, you can use sclerp() + * ``` + * DualQuatd::sclerp(q0, q1, t) + * ``` + * or dqblend(). + * ``` + * DualQuatd::dqblend(q0, q1, t) + * ``` + * With more than two dual quaternions to be blended, you can use generalize linear dual quaternion blending + * with the corresponding weights, i.e. gdqblend(). + * + */ +template +class CV_EXPORTS DualQuat{ + static_assert(std::is_floating_point<_Tp>::value, "Dual quaternion only make sense with type of float or double"); + using value_type = _Tp; + +public: + static constexpr _Tp CV_DUAL_QUAT_EPS = (_Tp)1.e-6; + + DualQuat(); + + /** + * @brief create from eight same type numbers. + */ + DualQuat(const _Tp w, const _Tp x, const _Tp y, const _Tp z, const _Tp w_, const _Tp x_, const _Tp y_, const _Tp z_); + + /** + * @brief create from a double or float vector. + */ + DualQuat(const Vec<_Tp, 8> &q); + + _Tp w, x, y, z, w_, x_, y_, z_; + + /** + * @brief create Dual Quaternion from two same type quaternions p and q. + * A Dual Quaternion \f$\sigma\f$ has the form: + * \f[\sigma = p + \epsilon q\f] + * where p and q are defined as follows: + * \f[\begin{equation} + * \begin{split} + * p &= w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\\ + * q &= w\_ + x\_\boldsymbol{i} + y\_\boldsymbol{j} + z\_\boldsymbol{k}. + * \end{split} + * \end{equation} + * \f] + * The p and q are the real part and dual part respectively. + * @param realPart a quaternion, real part of dual quaternion. + * @param dualPart a quaternion, dual part of dual quaternion. + * @sa Quat + */ + static DualQuat<_Tp> createFromQuat(const Quat<_Tp> &realPart, const Quat<_Tp> &dualPart); + + /** + * @brief create a dual quaternion from a rotation angle \f$\theta\f$, a rotation axis + * \f$\boldsymbol{u}\f$ and a translation \f$\boldsymbol{t}\f$. + * It generates a dual quaternion \f$\sigma\f$ in the form of + * \f[\begin{equation} + * \begin{split} + * \sigma &= r + \frac{\epsilon}{2}\boldsymbol{t}r \\ + * &= [\cos(\frac{\theta}{2}), \boldsymbol{u}\sin(\frac{\theta}{2})] + * + \frac{\epsilon}{2}[0, \boldsymbol{t}][[\cos(\frac{\theta}{2}), + * \boldsymbol{u}\sin(\frac{\theta}{2})]]\\ + * &= \cos(\frac{\theta}{2}) + \boldsymbol{u}\sin(\frac{\theta}{2}) + * + \frac{\epsilon}{2}(-(\boldsymbol{t} \cdot \boldsymbol{u})\sin(\frac{\theta}{2}) + * + \boldsymbol{t}\cos(\frac{\theta}{2}) + \boldsymbol{u} \times \boldsymbol{t} \sin(\frac{\theta}{2})). + * \end{split} + * \end{equation}\f] + * @param angle rotation angle. + * @param axis rotation axis. + * @param translation a vector of length 3. + * @note Axis will be normalized in this function. And translation is applied + * after the rotation. Use @ref createFromQuat(r, r * t / 2) to create a dual quaternion + * which translation is applied before rotation. + * @sa Quat + */ + static DualQuat<_Tp> createFromAngleAxisTrans(const _Tp angle, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &translation); + + /** + * @brief Transform this dual quaternion to an affine transformation matrix \f$M\f$. + * Dual quaternion consists of a rotation \f$r=[a,b,c,d]\f$ and a translation \f$t=[\Delta x,\Delta y,\Delta z]\f$. The + * affine transformation matrix \f$M\f$ has the form + * \f[ + * \begin{bmatrix} + * 1-2(e_2^2 +e_3^2) &2(e_1e_2-e_0e_3) &2(e_0e_2+e_1e_3) &\Delta x\\ + * 2(e_0e_3+e_1e_2) &1-2(e_1^2+e_3^2) &2(e_2e_3-e_0e_1) &\Delta y\\ + * 2(e_1e_3-e_0e_2) &2(e_0e_1+e_2e_3) &1-2(e_1^2-e_2^2) &\Delta z\\ + * 0&0&0&1 + * \end{bmatrix} + * \f] + * if A is a matrix consisting of n points to be transformed, this could be achieved by + * \f[ + * new\_A = M * A + * \f] + * where A has the form + * \f[ + * \begin{bmatrix} + * x_0& x_1& x_2&...&x_n\\ + * y_0& y_1& y_2&...&y_n\\ + * z_0& z_1& z_2&...&z_n\\ + * 1&1&1&...&1 + * \end{bmatrix} + * \f] + * where the same subscript represent the same point. The size of A should be \f$[4,n]\f$. + * and the same size for matrix new_A. + * @param _R 4x4 matrix that represents rotations and translation. + * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create + * a dual quaternion which translation is applied before rotation. + */ + static DualQuat<_Tp> createFromMat(InputArray _R); + + /** + * @brief create dual quaternion from an affine matrix. The definition of affine matrix can refer to createFromMat() + */ + static DualQuat<_Tp> createFromAffine3(const Affine3<_Tp> &R); + + /** + * @brief A dual quaternion is a vector in form of + * \f[ + * \begin{equation} + * \begin{split} + * \sigma &=\boldsymbol{p} + \epsilon \boldsymbol{q}\\ + * &= \cos\hat{\frac{\theta}{2}}+\overline{\hat{l}}\sin\frac{\hat{\theta}}{2} + * \end{split} + * \end{equation} + * \f] + * where \f$\hat{\theta}\f$ is dual angle and \f$\overline{\hat{l}}\f$ is dual axis: + * \f[ + * \hat{\theta}=\theta + \epsilon d,\\ + * \overline{\hat{l}}= \hat{l} +\epsilon m. + * \f] + * In this representation, \f$\theta\f$ is rotation angle and \f$(\hat{l},m)\f$ is the screw axis, d is the translation distance along the axis. + * + * @param angle rotation angle. + * @param d translation along the rotation axis. + * @param axis rotation axis represented by quaternion with w = 0. + * @param moment the moment of line, and it should be orthogonal to axis. + * @note Translation is applied after the rotation. Use createFromQuat(r, r * t / 2) to create + * a dual quaternion which translation is applied before rotation. + */ + static DualQuat<_Tp> createFromPitch(const _Tp angle, const _Tp d, const Vec<_Tp, 3> &axis, const Vec<_Tp, 3> &moment); + + /** + * @brief return a quaternion which represent the real part of dual quaternion. + * The definition of real part is in createFromQuat(). + * @sa createFromQuat, getDualPart + */ + Quat<_Tp> getRealPart() const; + + /** + * @brief return a quaternion which represent the dual part of dual quaternion. + * The definition of dual part is in createFromQuat(). + * @sa createFromQuat, getRealPart + */ + Quat<_Tp> getDualPart() const; + + /** + * @brief return the conjugate of a dual quaternion. + * \f[ + * \begin{equation} + * \begin{split} + * \sigma^* &= (p + \epsilon q)^* + * &= (p^* + \epsilon q^*) + * \end{split} + * \end{equation} + * \f] + * @param dq a dual quaternion. + */ + template + friend DualQuat conjugate(const DualQuat &dq); + + /** + * @brief return the conjugate of a dual quaternion. + * \f[ + * \begin{equation} + * \begin{split} + * \sigma^* &= (p + \epsilon q)^* + * &= (p^* + \epsilon q^*) + * \end{split} + * \end{equation} + * \f] + */ + DualQuat<_Tp> conjugate() const; + + /** + * @brief return the rotation in quaternion form. + */ + Quat<_Tp> getRotation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the translation vector. + * The rotation \f$r\f$ in this dual quaternion \f$\sigma\f$ is applied before translation \f$t\f$. + * The dual quaternion \f$\sigma\f$ is defined as + * \f[\begin{equation} + * \begin{split} + * \sigma &= p + \epsilon q \\ + * &= r + \frac{\epsilon}{2}{t}r. + * \end{split} + * \end{equation}\f] + * Thus, the translation can be obtained as follows + * \f[t = 2qp^*.\f] + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + * @note This dual quaternion's translation is applied after the rotation. + */ + Vec<_Tp, 3> getTranslation(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the norm \f$||\sigma||\f$ of dual quaternion \f$\sigma = p + \epsilon q\f$. + * \f[ + * \begin{equation} + * \begin{split} + * ||\sigma|| &= \sqrt{\sigma * \sigma^*} \\ + * &= ||p|| + \epsilon \frac{p \cdot q}{||p||}. + * \end{split} + * \end{equation} + * \f] + * Generally speaking, the norm of a not unit dual + * quaternion is a dual number. For convenience, we return it in the form of a dual quaternion + * , i.e. + * \f[ ||\sigma|| = [||p||, 0, 0, 0, \frac{p \cdot q}{||p||}, 0, 0, 0].\f] + * + * @note The data type of dual number is dual quaternion. + */ + DualQuat<_Tp> norm() const; + + /** + * @brief return a normalized dual quaternion. + * A dual quaternion can be expressed as + * \f[ + * \begin{equation} + * \begin{split} + * \sigma &= p + \epsilon q\\ + * &=||\sigma||\left(r+\frac{1}{2}tr\right) + * \end{split} + * \end{equation} + * \f] + * where \f$r, t\f$ represents the rotation (ordinary quaternion) and translation (pure ordinary quaternion) respectively, + * and \f$||\sigma||\f$ is the norm of dual quaternion(a dual number). + * A dual quaternion is unit if and only if + * \f[ + * ||p||=1, p \cdot q=0 + * \f] + * where \f$\cdot\f$ means dot product. + * The process of normalization is + * \f[ + * \sigma_{u}=\frac{\sigma}{||\sigma||} + * \f] + * Next, we simply proof \f$\sigma_u\f$ is a unit dual quaternion: + * \f[ + * \renewcommand{\Im}{\operatorname{Im}} + * \begin{equation} + * \begin{split} + * \sigma_{u}=\frac{\sigma}{||\sigma||}&=\frac{p + \epsilon q}{||p||+\epsilon\frac{p\cdot q}{||p||}}\\ + * &=\frac{p}{||p||}+\epsilon\left(\frac{q}{||p||}-p\frac{p\cdot q}{||p||^3}\right)\\ + * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\left(qp^{*}-p\cdot q\right)\frac{p}{||p||}\\ + * &=\frac{p}{||p||}+\epsilon\frac{1}{||p||^2}\Im(qp^*)\frac{p}{||p||}.\\ + * \end{split} + * \end{equation} + * \f] + * As expected, the real part is a rotation and dual part is a pure quaternion. + */ + DualQuat<_Tp> normalize() const; + + /** + * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, + * the inverse dual quaternion is + * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] + * or equivalentlly, + * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] + * @param dq a dual quaternion. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion + * and this function will save some computations. + */ + template + friend DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit); + + /** + * @brief if \f$\sigma = p + \epsilon q\f$ is a dual quaternion, p is not zero, + * the inverse dual quaternion is + * \f[\sigma^{-1} = \frac{\sigma^*}{||\sigma||^2}, \f] + * or equivalentlly, + * \f[\sigma^{-1} = p^{-1} - \epsilon p^{-1}qp^{-1}.\f] + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the dot product of two dual quaternion. + * @param p other dual quaternion. + */ + _Tp dot(DualQuat<_Tp> p) const; + + /** + ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. + * This could be calculated as: + * \f[ + * p^t = \exp(t\ln p) + * \f] + * @param dq a dual quaternion. + * @param t index of power function. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion + * and this function will save some computations. + */ + template + friend DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit); + + /** + ** @brief return the value of \f$p^t\f$ where p is a dual quaternion. + * This could be calculated as: + * \f[ + * p^t = \exp(t\ln p) + * \f] + * + * @param t index of power function. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> power(const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. + * This could be calculated as: + * \f[ + * p^q = \exp(q\ln p) + * \f] + * @param p a dual quaternion. + * @param q a dual quaternion. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion p assume to be a dual unit quaternion + * and this function will save some computations. + */ + template + friend DualQuat power(const DualQuat& p, const DualQuat& q, QuatAssumeType assumeUnit); + + /** + * @brief return the value of \f$p^q\f$ where p and q are dual quaternions. + * This could be calculated as: + * \f[ + * p^q = \exp(q\ln p) + * \f] + * + * @param q a dual quaternion + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a dual unit quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> power(const DualQuat<_Tp>& q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of exponential function value + * @param dq a dual quaternion. + */ + template + friend DualQuat exp(const DualQuat &dq); + + /** + * @brief return the value of exponential function value + */ + DualQuat<_Tp> exp() const; + + /** + * @brief return the value of logarithm function value + * + * @param dq a dual quaternion. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, dual quaternion dq assume to be a unit dual quaternion + * and this function will save some computations. + */ + template + friend DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit); + + /** + * @brief return the value of logarithm function value + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + */ + DualQuat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief Transform this dual quaternion to a vector. + */ + Vec<_Tp, 8> toVec() const; + + /** + * @brief Transform this dual quaternion to a affine transformation matrix + * the form of matrix, see createFromMat(). + */ + Matx<_Tp, 4, 4> toMat(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief Transform this dual quaternion to a instance of Affine3. + */ + Affine3<_Tp> toAffine3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief The screw linear interpolation(ScLERP) is an extension of spherical linear interpolation of dual quaternion. + * If \f$\sigma_1\f$ and \f$\sigma_2\f$ are two dual quaternions representing the initial and final pose. + * The interpolation of ScLERP function can be defined as: + * \f[ + * ScLERP(t;\sigma_1,\sigma_2) = \sigma_1 * (\sigma_1^{-1} * \sigma_2)^t, t\in[0,1] + * \f] + * + * @param q1 a dual quaternion represents a initial pose. + * @param q2 a dual quaternion represents a final pose. + * @param t interpolation parameter + * @param directChange if true, it always return the shortest path. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + * + * For example + * ``` + * double angle1 = CV_PI / 2; + * Vec3d axis{0, 0, 1}; + * Vec3d t(0, 0, 3); + * DualQuatd initial = DualQuatd::createFromAngleAxisTrans(angle1, axis, t); + * double angle2 = CV_PI; + * DualQuatd final = DualQuatd::createFromAngleAxisTrans(angle2, axis, t); + * DualQuatd inter = DualQuatd::sclerp(initial, final, 0.5); + * ``` + */ + static DualQuat<_Tp> sclerp(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, + bool directChange=true, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + /** + * @brief The method of Dual Quaternion linear Blending(DQB) is to compute a transformation between dual quaternion + * \f$q_1\f$ and \f$q_2\f$ and can be defined as: + * \f[ + * DQB(t;{\boldsymbol{q}}_1,{\boldsymbol{q}}_2)= + * \frac{(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2}{||(1-t){\boldsymbol{q}}_1+t{\boldsymbol{q}}_2||}. + * \f] + * where \f$q_1\f$ and \f$q_2\f$ are unit dual quaternions representing the input transformations. + * If you want to use DQB that works for more than two rigid transformations, see @ref gdqblend + * + * @param q1 a unit dual quaternion representing the input transformations. + * @param q2 a unit dual quaternion representing the input transformations. + * @param t parameter \f$t\in[0,1]\f$. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, this dual quaternion assume to be a unit dual quaternion + * and this function will save some computations. + * + * @sa gdqblend + */ + static DualQuat<_Tp> dqblend(const DualQuat<_Tp> &q1, const DualQuat<_Tp> &q2, const _Tp t, + QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. + * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights + * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply + * \f[ + * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} + * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. + * \f] + * @param dualquat vector of dual quaternions + * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should + * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions + * and this function will save some computations. + * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. + */ + template + static DualQuat<_Tp> gdqblend(const Vec, cn> &dualquat, InputArray weights, + QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief The generalized Dual Quaternion linear Blending works for more than two rigid transformations. + * If these transformations are expressed as unit dual quaternions \f$q_1,...,q_n\f$ with convex weights + * \f$w = (w_1,...,w_n)\f$, the generalized DQB is simply + * \f[ + * gDQB(\boldsymbol{w};{\boldsymbol{q}}_1,...,{\boldsymbol{q}}_n)=\frac{w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n} + * {||w_1{\boldsymbol{q}}_1+...+w_n{\boldsymbol{q}}_n||}. + * \f] + * @param dualquat The dual quaternions which have 8 channels and 1 row or 1 col. + * @param weights vector of weights, the size of weights should be the same as dualquat, and the weights should + * satisfy \f$\sum_0^n w_{i} = 1\f$ and \f$w_i>0\f$. + * @param assumeUnit if @ref QUAT_ASSUME_UNIT, these dual quaternions assume to be unit quaternions + * and this function will save some computations. + * @note the type of weights' element should be the same as the date type of dual quaternion inside the dualquat. + */ + static DualQuat<_Tp> gdqblend(InputArray dualquat, InputArray weights, + QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief Return opposite dual quaternion \f$-p\f$ + * which satisfies \f$p + (-p) = 0.\f$ + * + * For example + * ``` + * DualQuatd q{1, 2, 3, 4, 5, 6, 7, 8}; + * std::cout << -q << std::endl; // [-1, -2, -3, -4, -5, -6, -7, -8] + * ``` + */ + DualQuat<_Tp> operator-() const; + + /** + * @brief return true if two dual quaternions p and q are nearly equal, i.e. when the absolute + * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_DUAL_QUAT_EPS. + */ + bool operator==(const DualQuat<_Tp>&) const; + + /** + * @brief Subtraction operator of two dual quaternions p and q. + * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p - q << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] + * ``` + */ + DualQuat<_Tp> operator-(const DualQuat<_Tp>&) const; + + /** + * @brief Subtraction assignment operator of two dual quaternions p and q. + * It subtracts right operand from the left operand and assign the result to left operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p -= q; // equivalent to p = p - q + * std::cout << p << std::endl; //[-4, -4, -4, -4, 4, -4, -4, -4] + * + * ``` + */ + DualQuat<_Tp>& operator-=(const DualQuat<_Tp>&); + + /** + * @brief Addition operator of two dual quaternions p and q. + * It returns a new dual quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p + q << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] + * ``` + */ + DualQuat<_Tp> operator+(const DualQuat<_Tp>&) const; + + /** + * @brief Addition assignment operator of two dual quaternions p and q. + * It adds right operand to the left operand and assign the result to left operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p += q; // equivalent to p = p + q + * std::cout << p << std::endl; //[6, 8, 10, 12, 14, 16, 18, 20] + * + * ``` + */ + DualQuat<_Tp>& operator+=(const DualQuat<_Tp>&); + + /** + * @brief Multiplication assignment operator of two quaternions. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication: + * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [A, B][C, D]\\ + * &=[AC, AD + BC] + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p *= q; + * std::cout << p << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] + * ``` + */ + DualQuat<_Tp>& operator*=(const DualQuat<_Tp>&); + + /** + * @brief Multiplication assignment operator of a quaternions and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ + * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * p *= s; + * std::cout << p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + DualQuat<_Tp> operator*=(const _Tp s); + + + /** + * @brief Multiplication operator of two dual quaternions q and p. + * Multiplies values on either side of the operator. + * + * Rule of dual quaternion multiplication: + * The dual quaternion can be written as an ordered pair of quaternions [A, B]. Thus + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [A, B][C, D]\\ + * &=[AC, AD + BC] + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p * q << std::endl; //[-60, 12, 30, 24, -216, 80, 124, 120] + * ``` + */ + DualQuat<_Tp> operator*(const DualQuat<_Tp>&) const; + + /** + * @brief Division operator of a dual quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of dual quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z, w\_, x\_, y\_, z\_] / s\\ + * &=[w/s, x/s, y/s, z/s, w\_/s, x\_/s, y\_/s, z\_/s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4] + * ``` + * @note the type of scalar should be equal to this dual quaternion. + */ + DualQuat<_Tp> operator/(const _Tp s) const; + + /** + * @brief Division operator of two dual quaternions p and q. + * Divides left hand operand by right hand operand. + * + * Rule of dual quaternion division with a dual quaternion: + * \f[ + * \begin{equation} + * \begin{split} + * p / q &= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * std::cout << p / q << std::endl; // equivalent to p * q.inv() + * ``` + */ + DualQuat<_Tp> operator/(const DualQuat<_Tp>&) const; + + /** + * @brief Division assignment operator of two dual quaternions p and q; + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of dual quaternion division with a quaternion: + * \f[ + * \begin{equation} + * \begin{split} + * p / q&= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * DualQuatd q{5, 6, 7, 8, 9, 10, 11, 12}; + * p /= q; // equivalent to p = p * q.inv() + * std::cout << p << std::endl; + * ``` + */ + DualQuat<_Tp>& operator/=(const DualQuat<_Tp>&); + + /** + * @brief Division assignment operator of a dual quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of dual quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z, w\_, x\_, y\_ ,z\_] / s\\ + * &=[w / s, x / s, y / s, z / s, w\_ / \space s, x\_ / \space s, y\_ / \space s, z\_ / \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0;; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + Quat<_Tp>& operator/=(const _Tp s); + + /** + * @brief Addition operator of a scalar and a dual quaternions. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator+(const T s, const DualQuat&); + + /** + * @brief Addition operator of a dual quaternions and a scalar. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4, 5, 6, 7, 8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator+(const DualQuat&, const T s); + + /** + * @brief Multiplication operator of a scalar and a dual quaternions. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ + * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * std::cout << s * p << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator*(const T s, const DualQuat&); + + /** + * @brief Subtraction operator of a dual quaternion and a scalar. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << p - scalar << std::endl; //[-1, 2, 3, 4, 5, 6, 7, 8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator-(const DualQuat&, const T s); + + /** + * @brief Subtraction operator of a scalar and a dual quaternions. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double scalar = 2.0; + * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4, -5, -6, -7, -8] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator-(const T s, const DualQuat&); + + /** + * @brief Multiplication operator of a dual quaternions and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of dual quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z, w\_, x\_, y\_, z\_] * s\\ + * &=[w s, x s, y s, z s, w\_ \space s, x\_ \space s, y\_ \space s, z\_ \space s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * DualQuatd p{1, 2, 3, 4, 5, 6, 7, 8}; + * double s = 2.0; + * std::cout << p * s << std::endl; //[2, 4, 6, 8, 10, 12, 14, 16] + * ``` + * @note the type of scalar should be equal to the dual quaternion. + */ + template + friend DualQuat cv::operator*(const DualQuat&, const T s); + + template + friend std::ostream& cv::operator<<(std::ostream&, const DualQuat&); + +}; + +using DualQuatd = DualQuat; +using DualQuatf = DualQuat; + +//! @} core +}//namespace + +#include "dualquaternion.inl.hpp" + +#endif /* OPENCV_CORE_QUATERNION_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp index 6d3d1f0f2e..1a68f12d30 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/dualquaternion.inl.hpp @@ -1,487 +1,487 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang - -#ifndef OPENCV_CORE_DUALQUATERNION_INL_HPP -#define OPENCV_CORE_DUALQUATERNION_INL_HPP - -#ifndef OPENCV_CORE_DUALQUATERNION_HPP -#error This is not a standalone header. Include dualquaternion.hpp instead. -#endif - -/////////////////////////////////////////////////////////////////////////////////////// -//Implementation -namespace cv { - -template -DualQuat::DualQuat():w(0), x(0), y(0), z(0), w_(0), x_(0), y_(0), z_(0){} - -template -DualQuat::DualQuat(const T vw, const T vx, const T vy, const T vz, const T _w, const T _x, const T _y, const T _z): - w(vw), x(vx), y(vy), z(vz), w_(_w), x_(_x), y_(_y), z_(_z){} - -template -DualQuat::DualQuat(const Vec &q):w(q[0]), x(q[1]), y(q[2]), z(q[3]), - w_(q[4]), x_(q[5]), y_(q[6]), z_(q[7]){} - -template -DualQuat DualQuat::createFromQuat(const Quat &realPart, const Quat &dualPart) -{ - T w = realPart.w; - T x = realPart.x; - T y = realPart.y; - T z = realPart.z; - T w_ = dualPart.w; - T x_ = dualPart.x; - T y_ = dualPart.y; - T z_ = dualPart.z; - return DualQuat(w, x, y, z, w_, x_, y_, z_); -} - -template -DualQuat DualQuat::createFromAngleAxisTrans(const T angle, const Vec &axis, const Vec &trans) -{ - Quat r = Quat::createFromAngleAxis(angle, axis); - Quat t{0, trans[0], trans[1], trans[2]}; - return createFromQuat(r, t * r * T(0.5)); -} - -template -DualQuat DualQuat::createFromMat(InputArray _R) -{ - CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); - if (_R.size() != Size(4, 4)) - { - CV_Error(Error::StsBadArg, "The input matrix must have 4 columns and 4 rows"); - } - Mat R = _R.getMat(); - Quat r = Quat::createFromRotMat(R.colRange(0, 3).rowRange(0, 3)); - Quat trans(0, R.at(0, 3), R.at(1, 3), R.at(2, 3)); - return createFromQuat(r, trans * r * T(0.5)); -} - -template -DualQuat DualQuat::createFromAffine3(const Affine3 &R) -{ - return createFromMat(R.matrix); -} - -template -DualQuat DualQuat::createFromPitch(const T angle, const T d, const Vec &axis, const Vec &moment) -{ - T half_angle = angle * T(0.5), half_d = d * T(0.5); - Quat qaxis = Quat(0, axis[0], axis[1], axis[2]).normalize(); - Quat qmoment = Quat(0, moment[0], moment[1], moment[2]); - qmoment -= qaxis * axis.dot(moment); - Quat dual = -half_d * std::sin(half_angle) + std::sin(half_angle) * qmoment + - half_d * std::cos(half_angle) * qaxis; - return createFromQuat(Quat::createFromAngleAxis(angle, axis), dual); -} - -template -inline bool DualQuat::operator==(const DualQuat &q) const -{ - return (abs(w - q.w) < CV_DUAL_QUAT_EPS && abs(x - q.x) < CV_DUAL_QUAT_EPS && - abs(y - q.y) < CV_DUAL_QUAT_EPS && abs(z - q.z) < CV_DUAL_QUAT_EPS && - abs(w_ - q.w_) < CV_DUAL_QUAT_EPS && abs(x_ - q.x_) < CV_DUAL_QUAT_EPS && - abs(y_ - q.y_) < CV_DUAL_QUAT_EPS && abs(z_ - q.z_) < CV_DUAL_QUAT_EPS); -} - -template -inline Quat DualQuat::getRealPart() const -{ - return Quat(w, x, y, z); -} - -template -inline Quat DualQuat::getDualPart() const -{ - return Quat(w_, x_, y_, z_); -} - -template -inline DualQuat conjugate(const DualQuat &dq) -{ - return dq.conjugate(); -} - -template -inline DualQuat DualQuat::conjugate() const -{ - return DualQuat(w, -x, -y, -z, w_, -x_, -y_, -z_); -} - -template -DualQuat DualQuat::norm() const -{ - Quat real = getRealPart(); - T realNorm = real.norm(); - Quat dual = getDualPart(); - if (realNorm < CV_DUAL_QUAT_EPS){ - return DualQuat(0, 0, 0, 0, 0, 0, 0, 0); - } - return DualQuat(realNorm, 0, 0, 0, real.dot(dual) / realNorm, 0, 0, 0); -} - -template -inline Quat DualQuat::getRotation(QuatAssumeType assumeUnit) const -{ - if (assumeUnit) - { - return getRealPart(); - } - return getRealPart().normalize(); -} - -template -inline Vec DualQuat::getTranslation(QuatAssumeType assumeUnit) const -{ - Quat trans = T(2.0) * (getDualPart() * getRealPart().inv(assumeUnit)); - return Vec{trans[1], trans[2], trans[3]}; -} - -template -DualQuat DualQuat::normalize() const -{ - Quat p = getRealPart(); - Quat q = getDualPart(); - T p_norm = p.norm(); - if (p_norm < CV_DUAL_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "Cannot normalize this dual quaternion: the norm is too small."); - } - Quat p_nr = p / p_norm; - Quat q_nr = q / p_norm; - return createFromQuat(p_nr, q_nr - p_nr * p_nr.dot(q_nr)); -} - -template -inline T DualQuat::dot(DualQuat q) const -{ - return q.w * w + q.x * x + q.y * y + q.z * z + q.w_ * w_ + q.x_ * x_ + q.y_ * y_ + q.z_ * z_; -} - -template -inline DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return dq.inv(assumeUnit); -} - -template -inline DualQuat DualQuat::inv(QuatAssumeType assumeUnit) const -{ - Quat real = getRealPart(); - Quat dual = getDualPart(); - return createFromQuat(real.inv(assumeUnit), -real.inv(assumeUnit) * dual * real.inv(assumeUnit)); -} - -template -inline DualQuat DualQuat::operator-(const DualQuat &q) const -{ - return DualQuat(w - q.w, x - q.x, y - q.y, z - q.z, w_ - q.w_, x_ - q.x_, y_ - q.y_, z_ - q.z_); -} - -template -inline DualQuat DualQuat::operator-() const -{ - return DualQuat(-w, -x, -y, -z, -w_, -x_, -y_, -z_); -} - -template -inline DualQuat DualQuat::operator+(const DualQuat &q) const -{ - return DualQuat(w + q.w, x + q.x, y + q.y, z + q.z, w_ + q.w_, x_ + q.x_, y_ + q.y_, z_ + q.z_); -} - -template -inline DualQuat& DualQuat::operator+=(const DualQuat &q) -{ - *this = *this + q; - return *this; -} - -template -inline DualQuat DualQuat::operator*(const DualQuat &q) const -{ - Quat A = getRealPart(); - Quat B = getDualPart(); - Quat C = q.getRealPart(); - Quat D = q.getDualPart(); - return DualQuat::createFromQuat(A * C, A * D + B * C); -} - -template -inline DualQuat& DualQuat::operator*=(const DualQuat &q) -{ - *this = *this * q; - return *this; -} - -template -inline DualQuat operator+(const T a, const DualQuat &q) -{ - return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); -} - -template -inline DualQuat operator+(const DualQuat &q, const T a) -{ - return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); -} - -template -inline DualQuat operator-(const DualQuat &q, const T a) -{ - return DualQuat(q.w - a, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); -} - -template -inline DualQuat& DualQuat::operator-=(const DualQuat &q) -{ - *this = *this - q; - return *this; -} - -template -inline DualQuat operator-(const T a, const DualQuat &q) -{ - return DualQuat(a - q.w, -q.x, -q.y, -q.z, -q.w_, -q.x_, -q.y_, -q.z_); -} - -template -inline DualQuat operator*(const T a, const DualQuat &q) -{ - return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); -} - -template -inline DualQuat operator*(const DualQuat &q, const T a) -{ - return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); -} - -template -inline DualQuat DualQuat::operator/(const T a) const -{ - return DualQuat(w / a, x / a, y / a, z / a, w_ / a, x_ / a, y_ / a, z_ / a); -} - -template -inline DualQuat DualQuat::operator/(const DualQuat &q) const -{ - return *this * q.inv(); -} - -template -inline DualQuat& DualQuat::operator/=(const DualQuat &q) -{ - *this = *this / q; - return *this; -} - -template -std::ostream & operator<<(std::ostream &os, const DualQuat &q) -{ - os << "DualQuat " << Vec{q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_}; - return os; -} - -template -inline DualQuat exp(const DualQuat &dq) -{ - return dq.exp(); -} - -namespace detail { - -template -Matx<_Tp, 4, 4> jacob_exp(const Quat<_Tp> &q) -{ - _Tp nv = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z); - _Tp sinc_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? _Tp(1.0) - nv * nv * _Tp(1.0/6.0) : std::sin(nv) / nv; - _Tp csiii_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? -_Tp(1.0/3.0) : (std::cos(nv) - sinc_nv) / nv / nv; - Matx<_Tp, 4, 4> J_exp_quat { - std::cos(nv), -sinc_nv * q.x, -sinc_nv * q.y, -sinc_nv * q.z, - sinc_nv * q.x, csiii_nv * q.x * q.x + sinc_nv, csiii_nv * q.x * q.y, csiii_nv * q.x * q.z, - sinc_nv * q.y, csiii_nv * q.y * q.x, csiii_nv * q.y * q.y + sinc_nv, csiii_nv * q.y * q.z, - sinc_nv * q.z, csiii_nv * q.z * q.x, csiii_nv * q.z * q.y, csiii_nv * q.z * q.z + sinc_nv - }; - return std::exp(q.w) * J_exp_quat; -} - -} // namespace detail - -template -DualQuat DualQuat::exp() const -{ - Quat real = getRealPart(); - return createFromQuat(real.exp(), Quat(detail::jacob_exp(real) * getDualPart().toVec())); -} - -template -DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return dq.log(assumeUnit); -} - -template -DualQuat DualQuat::log(QuatAssumeType assumeUnit) const -{ - Quat plog = getRealPart().log(assumeUnit); - Matx jacob = detail::jacob_exp(plog); - return createFromQuat(plog, Quat(jacob.inv() * getDualPart().toVec())); -} - -template -inline DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return dq.power(t, assumeUnit); -} - -template -inline DualQuat DualQuat::power(const T t, QuatAssumeType assumeUnit) const -{ - return (t * log(assumeUnit)).exp(); -} - -template -inline DualQuat power(const DualQuat &p, const DualQuat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) -{ - return p.power(q, assumeUnit); -} - -template -inline DualQuat DualQuat::power(const DualQuat &q, QuatAssumeType assumeUnit) const -{ - return (q * log(assumeUnit)).exp(); -} - -template -inline Vec DualQuat::toVec() const -{ - return Vec(w, x, y, z, w_, x_, y_, z_); -} - -template -Affine3 DualQuat::toAffine3(QuatAssumeType assumeUnit) const -{ - return Affine3(toMat(assumeUnit)); -} - -template -Matx DualQuat::toMat(QuatAssumeType assumeUnit) const -{ - Matx rot44 = getRotation(assumeUnit).toRotMat4x4(); - Vec translation = getTranslation(assumeUnit); - rot44(0, 3) = translation[0]; - rot44(1, 3) = translation[1]; - rot44(2, 3) = translation[2]; - return rot44; -} - -template -DualQuat DualQuat::sclerp(const DualQuat &q0, const DualQuat &q1, const T t, bool directChange, QuatAssumeType assumeUnit) -{ - DualQuat v0(q0), v1(q1); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - } - Quat v0Real = v0.getRealPart(); - Quat v1Real = v1.getRealPart(); - if (directChange && v1Real.dot(v0Real) < 0) - { - v0 = -v0; - } - DualQuat v0inv1 = v0.inv() * v1; - return v0 * v0inv1.power(t, QUAT_ASSUME_UNIT); -} - -template -DualQuat DualQuat::dqblend(const DualQuat &q1, const DualQuat &q2, const T t, QuatAssumeType assumeUnit) -{ - DualQuat v1(q1), v2(q2); - if (!assumeUnit) - { - v1 = v1.normalize(); - v2 = v2.normalize(); - } - if (v1.getRotation(assumeUnit).dot(v2.getRotation(assumeUnit)) < 0) - { - return ((1 - t) * v1 - t * v2).normalize(); - } - return ((1 - t) * v1 + t * v2).normalize(); -} - -template -DualQuat DualQuat::gdqblend(InputArray _dualquat, InputArray _weight, QuatAssumeType assumeUnit) -{ - CV_CheckTypeEQ(_weight.type(), cv::traits::Type::value, ""); - CV_CheckTypeEQ(_dualquat.type(), CV_MAKETYPE(CV_MAT_DEPTH(cv::traits::Type::value), 8), ""); - Size dq_s = _dualquat.size(); - if (dq_s != _weight.size() || (dq_s.height != 1 && dq_s.width != 1)) - { - CV_Error(Error::StsBadArg, "The size of weight must be the same as dualquat, both of them should be (1, n) or (n, 1)"); - } - Mat dualquat = _dualquat.getMat(), weight = _weight.getMat(); - const int cn = std::max(dq_s.width, dq_s.height); - if (!assumeUnit) - { - for (int i = 0; i < cn; ++i) - { - dualquat.at>(i) = DualQuat{dualquat.at>(i)}.normalize().toVec(); - } - } - Vec dq_blend = dualquat.at>(0) * weight.at(0); - Quat q0 = DualQuat {dualquat.at>(0)}.getRotation(assumeUnit); - for (int i = 1; i < cn; ++i) - { - T k = q0.dot(DualQuat{dualquat.at>(i)}.getRotation(assumeUnit)) < 0 ? -1: 1; - dq_blend = dq_blend + dualquat.at>(i) * k * weight.at(i); - } - return DualQuat{dq_blend}.normalize(); -} - -template -template -DualQuat DualQuat::gdqblend(const Vec, cn> &_dualquat, InputArray _weight, QuatAssumeType assumeUnit) -{ - Vec, cn> dualquat(_dualquat); - if (cn == 0) - { - return DualQuat(1, 0, 0, 0, 0, 0, 0, 0); - } - Mat dualquat_mat(cn, 1, CV_64FC(8)); - for (int i = 0; i < cn ; ++i) - { - dualquat_mat.at>(i) = dualquat[i].toVec(); - } - return gdqblend(dualquat_mat, _weight, assumeUnit); -} - -} //namespace cv - -#endif /*OPENCV_CORE_DUALQUATERNION_INL_HPP*/ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang + +#ifndef OPENCV_CORE_DUALQUATERNION_INL_HPP +#define OPENCV_CORE_DUALQUATERNION_INL_HPP + +#ifndef OPENCV_CORE_DUALQUATERNION_HPP +#error This is not a standalone header. Include dualquaternion.hpp instead. +#endif + +/////////////////////////////////////////////////////////////////////////////////////// +//Implementation +namespace cv { + +template +DualQuat::DualQuat():w(0), x(0), y(0), z(0), w_(0), x_(0), y_(0), z_(0){} + +template +DualQuat::DualQuat(const T vw, const T vx, const T vy, const T vz, const T _w, const T _x, const T _y, const T _z): + w(vw), x(vx), y(vy), z(vz), w_(_w), x_(_x), y_(_y), z_(_z){} + +template +DualQuat::DualQuat(const Vec &q):w(q[0]), x(q[1]), y(q[2]), z(q[3]), + w_(q[4]), x_(q[5]), y_(q[6]), z_(q[7]){} + +template +DualQuat DualQuat::createFromQuat(const Quat &realPart, const Quat &dualPart) +{ + T w = realPart.w; + T x = realPart.x; + T y = realPart.y; + T z = realPart.z; + T w_ = dualPart.w; + T x_ = dualPart.x; + T y_ = dualPart.y; + T z_ = dualPart.z; + return DualQuat(w, x, y, z, w_, x_, y_, z_); +} + +template +DualQuat DualQuat::createFromAngleAxisTrans(const T angle, const Vec &axis, const Vec &trans) +{ + Quat r = Quat::createFromAngleAxis(angle, axis); + Quat t{0, trans[0], trans[1], trans[2]}; + return createFromQuat(r, t * r * T(0.5)); +} + +template +DualQuat DualQuat::createFromMat(InputArray _R) +{ + CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); + if (_R.size() != Size(4, 4)) + { + CV_Error(Error::StsBadArg, "The input matrix must have 4 columns and 4 rows"); + } + Mat R = _R.getMat(); + Quat r = Quat::createFromRotMat(R.colRange(0, 3).rowRange(0, 3)); + Quat trans(0, R.at(0, 3), R.at(1, 3), R.at(2, 3)); + return createFromQuat(r, trans * r * T(0.5)); +} + +template +DualQuat DualQuat::createFromAffine3(const Affine3 &R) +{ + return createFromMat(R.matrix); +} + +template +DualQuat DualQuat::createFromPitch(const T angle, const T d, const Vec &axis, const Vec &moment) +{ + T half_angle = angle * T(0.5), half_d = d * T(0.5); + Quat qaxis = Quat(0, axis[0], axis[1], axis[2]).normalize(); + Quat qmoment = Quat(0, moment[0], moment[1], moment[2]); + qmoment -= qaxis * axis.dot(moment); + Quat dual = -half_d * std::sin(half_angle) + std::sin(half_angle) * qmoment + + half_d * std::cos(half_angle) * qaxis; + return createFromQuat(Quat::createFromAngleAxis(angle, axis), dual); +} + +template +inline bool DualQuat::operator==(const DualQuat &q) const +{ + return (abs(w - q.w) < CV_DUAL_QUAT_EPS && abs(x - q.x) < CV_DUAL_QUAT_EPS && + abs(y - q.y) < CV_DUAL_QUAT_EPS && abs(z - q.z) < CV_DUAL_QUAT_EPS && + abs(w_ - q.w_) < CV_DUAL_QUAT_EPS && abs(x_ - q.x_) < CV_DUAL_QUAT_EPS && + abs(y_ - q.y_) < CV_DUAL_QUAT_EPS && abs(z_ - q.z_) < CV_DUAL_QUAT_EPS); +} + +template +inline Quat DualQuat::getRealPart() const +{ + return Quat(w, x, y, z); +} + +template +inline Quat DualQuat::getDualPart() const +{ + return Quat(w_, x_, y_, z_); +} + +template +inline DualQuat conjugate(const DualQuat &dq) +{ + return dq.conjugate(); +} + +template +inline DualQuat DualQuat::conjugate() const +{ + return DualQuat(w, -x, -y, -z, w_, -x_, -y_, -z_); +} + +template +DualQuat DualQuat::norm() const +{ + Quat real = getRealPart(); + T realNorm = real.norm(); + Quat dual = getDualPart(); + if (realNorm < CV_DUAL_QUAT_EPS){ + return DualQuat(0, 0, 0, 0, 0, 0, 0, 0); + } + return DualQuat(realNorm, 0, 0, 0, real.dot(dual) / realNorm, 0, 0, 0); +} + +template +inline Quat DualQuat::getRotation(QuatAssumeType assumeUnit) const +{ + if (assumeUnit) + { + return getRealPart(); + } + return getRealPart().normalize(); +} + +template +inline Vec DualQuat::getTranslation(QuatAssumeType assumeUnit) const +{ + Quat trans = T(2.0) * (getDualPart() * getRealPart().inv(assumeUnit)); + return Vec{trans[1], trans[2], trans[3]}; +} + +template +DualQuat DualQuat::normalize() const +{ + Quat p = getRealPart(); + Quat q = getDualPart(); + T p_norm = p.norm(); + if (p_norm < CV_DUAL_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "Cannot normalize this dual quaternion: the norm is too small."); + } + Quat p_nr = p / p_norm; + Quat q_nr = q / p_norm; + return createFromQuat(p_nr, q_nr - p_nr * p_nr.dot(q_nr)); +} + +template +inline T DualQuat::dot(DualQuat q) const +{ + return q.w * w + q.x * x + q.y * y + q.z * z + q.w_ * w_ + q.x_ * x_ + q.y_ * y_ + q.z_ * z_; +} + +template +inline DualQuat inv(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return dq.inv(assumeUnit); +} + +template +inline DualQuat DualQuat::inv(QuatAssumeType assumeUnit) const +{ + Quat real = getRealPart(); + Quat dual = getDualPart(); + return createFromQuat(real.inv(assumeUnit), -real.inv(assumeUnit) * dual * real.inv(assumeUnit)); +} + +template +inline DualQuat DualQuat::operator-(const DualQuat &q) const +{ + return DualQuat(w - q.w, x - q.x, y - q.y, z - q.z, w_ - q.w_, x_ - q.x_, y_ - q.y_, z_ - q.z_); +} + +template +inline DualQuat DualQuat::operator-() const +{ + return DualQuat(-w, -x, -y, -z, -w_, -x_, -y_, -z_); +} + +template +inline DualQuat DualQuat::operator+(const DualQuat &q) const +{ + return DualQuat(w + q.w, x + q.x, y + q.y, z + q.z, w_ + q.w_, x_ + q.x_, y_ + q.y_, z_ + q.z_); +} + +template +inline DualQuat& DualQuat::operator+=(const DualQuat &q) +{ + *this = *this + q; + return *this; +} + +template +inline DualQuat DualQuat::operator*(const DualQuat &q) const +{ + Quat A = getRealPart(); + Quat B = getDualPart(); + Quat C = q.getRealPart(); + Quat D = q.getDualPart(); + return DualQuat::createFromQuat(A * C, A * D + B * C); +} + +template +inline DualQuat& DualQuat::operator*=(const DualQuat &q) +{ + *this = *this * q; + return *this; +} + +template +inline DualQuat operator+(const T a, const DualQuat &q) +{ + return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); +} + +template +inline DualQuat operator+(const DualQuat &q, const T a) +{ + return DualQuat(a + q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); +} + +template +inline DualQuat operator-(const DualQuat &q, const T a) +{ + return DualQuat(q.w - a, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_); +} + +template +inline DualQuat& DualQuat::operator-=(const DualQuat &q) +{ + *this = *this - q; + return *this; +} + +template +inline DualQuat operator-(const T a, const DualQuat &q) +{ + return DualQuat(a - q.w, -q.x, -q.y, -q.z, -q.w_, -q.x_, -q.y_, -q.z_); +} + +template +inline DualQuat operator*(const T a, const DualQuat &q) +{ + return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); +} + +template +inline DualQuat operator*(const DualQuat &q, const T a) +{ + return DualQuat(q.w * a, q.x * a, q.y * a, q.z * a, q.w_ * a, q.x_ * a, q.y_ * a, q.z_ * a); +} + +template +inline DualQuat DualQuat::operator/(const T a) const +{ + return DualQuat(w / a, x / a, y / a, z / a, w_ / a, x_ / a, y_ / a, z_ / a); +} + +template +inline DualQuat DualQuat::operator/(const DualQuat &q) const +{ + return *this * q.inv(); +} + +template +inline DualQuat& DualQuat::operator/=(const DualQuat &q) +{ + *this = *this / q; + return *this; +} + +template +std::ostream & operator<<(std::ostream &os, const DualQuat &q) +{ + os << "DualQuat " << Vec{q.w, q.x, q.y, q.z, q.w_, q.x_, q.y_, q.z_}; + return os; +} + +template +inline DualQuat exp(const DualQuat &dq) +{ + return dq.exp(); +} + +namespace detail { + +template +Matx<_Tp, 4, 4> jacob_exp(const Quat<_Tp> &q) +{ + _Tp nv = std::sqrt(q.x * q.x + q.y * q.y + q.z * q.z); + _Tp sinc_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? _Tp(1.0) - nv * nv * _Tp(1.0/6.0) : std::sin(nv) / nv; + _Tp csiii_nv = abs(nv) < cv::DualQuat<_Tp>::CV_DUAL_QUAT_EPS ? -_Tp(1.0/3.0) : (std::cos(nv) - sinc_nv) / nv / nv; + Matx<_Tp, 4, 4> J_exp_quat { + std::cos(nv), -sinc_nv * q.x, -sinc_nv * q.y, -sinc_nv * q.z, + sinc_nv * q.x, csiii_nv * q.x * q.x + sinc_nv, csiii_nv * q.x * q.y, csiii_nv * q.x * q.z, + sinc_nv * q.y, csiii_nv * q.y * q.x, csiii_nv * q.y * q.y + sinc_nv, csiii_nv * q.y * q.z, + sinc_nv * q.z, csiii_nv * q.z * q.x, csiii_nv * q.z * q.y, csiii_nv * q.z * q.z + sinc_nv + }; + return std::exp(q.w) * J_exp_quat; +} + +} // namespace detail + +template +DualQuat DualQuat::exp() const +{ + Quat real = getRealPart(); + return createFromQuat(real.exp(), Quat(detail::jacob_exp(real) * getDualPart().toVec())); +} + +template +DualQuat log(const DualQuat &dq, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return dq.log(assumeUnit); +} + +template +DualQuat DualQuat::log(QuatAssumeType assumeUnit) const +{ + Quat plog = getRealPart().log(assumeUnit); + Matx jacob = detail::jacob_exp(plog); + return createFromQuat(plog, Quat(jacob.inv() * getDualPart().toVec())); +} + +template +inline DualQuat power(const DualQuat &dq, const T t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return dq.power(t, assumeUnit); +} + +template +inline DualQuat DualQuat::power(const T t, QuatAssumeType assumeUnit) const +{ + return (t * log(assumeUnit)).exp(); +} + +template +inline DualQuat power(const DualQuat &p, const DualQuat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) +{ + return p.power(q, assumeUnit); +} + +template +inline DualQuat DualQuat::power(const DualQuat &q, QuatAssumeType assumeUnit) const +{ + return (q * log(assumeUnit)).exp(); +} + +template +inline Vec DualQuat::toVec() const +{ + return Vec(w, x, y, z, w_, x_, y_, z_); +} + +template +Affine3 DualQuat::toAffine3(QuatAssumeType assumeUnit) const +{ + return Affine3(toMat(assumeUnit)); +} + +template +Matx DualQuat::toMat(QuatAssumeType assumeUnit) const +{ + Matx rot44 = getRotation(assumeUnit).toRotMat4x4(); + Vec translation = getTranslation(assumeUnit); + rot44(0, 3) = translation[0]; + rot44(1, 3) = translation[1]; + rot44(2, 3) = translation[2]; + return rot44; +} + +template +DualQuat DualQuat::sclerp(const DualQuat &q0, const DualQuat &q1, const T t, bool directChange, QuatAssumeType assumeUnit) +{ + DualQuat v0(q0), v1(q1); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + } + Quat v0Real = v0.getRealPart(); + Quat v1Real = v1.getRealPart(); + if (directChange && v1Real.dot(v0Real) < 0) + { + v0 = -v0; + } + DualQuat v0inv1 = v0.inv() * v1; + return v0 * v0inv1.power(t, QUAT_ASSUME_UNIT); +} + +template +DualQuat DualQuat::dqblend(const DualQuat &q1, const DualQuat &q2, const T t, QuatAssumeType assumeUnit) +{ + DualQuat v1(q1), v2(q2); + if (!assumeUnit) + { + v1 = v1.normalize(); + v2 = v2.normalize(); + } + if (v1.getRotation(assumeUnit).dot(v2.getRotation(assumeUnit)) < 0) + { + return ((1 - t) * v1 - t * v2).normalize(); + } + return ((1 - t) * v1 + t * v2).normalize(); +} + +template +DualQuat DualQuat::gdqblend(InputArray _dualquat, InputArray _weight, QuatAssumeType assumeUnit) +{ + CV_CheckTypeEQ(_weight.type(), cv::traits::Type::value, ""); + CV_CheckTypeEQ(_dualquat.type(), CV_MAKETYPE(CV_MAT_DEPTH(cv::traits::Type::value), 8), ""); + Size dq_s = _dualquat.size(); + if (dq_s != _weight.size() || (dq_s.height != 1 && dq_s.width != 1)) + { + CV_Error(Error::StsBadArg, "The size of weight must be the same as dualquat, both of them should be (1, n) or (n, 1)"); + } + Mat dualquat = _dualquat.getMat(), weight = _weight.getMat(); + const int cn = std::max(dq_s.width, dq_s.height); + if (!assumeUnit) + { + for (int i = 0; i < cn; ++i) + { + dualquat.at>(i) = DualQuat{dualquat.at>(i)}.normalize().toVec(); + } + } + Vec dq_blend = dualquat.at>(0) * weight.at(0); + Quat q0 = DualQuat {dualquat.at>(0)}.getRotation(assumeUnit); + for (int i = 1; i < cn; ++i) + { + T k = q0.dot(DualQuat{dualquat.at>(i)}.getRotation(assumeUnit)) < 0 ? -1: 1; + dq_blend = dq_blend + dualquat.at>(i) * k * weight.at(i); + } + return DualQuat{dq_blend}.normalize(); +} + +template +template +DualQuat DualQuat::gdqblend(const Vec, cn> &_dualquat, InputArray _weight, QuatAssumeType assumeUnit) +{ + Vec, cn> dualquat(_dualquat); + if (cn == 0) + { + return DualQuat(1, 0, 0, 0, 0, 0, 0, 0); + } + Mat dualquat_mat(cn, 1, CV_64FC(8)); + for (int i = 0; i < cn ; ++i) + { + dualquat_mat.at>(i) = dualquat[i].toVec(); + } + return gdqblend(dualquat_mat, _weight, assumeUnit); +} + +} //namespace cv + +#endif /*OPENCV_CORE_DUALQUATERNION_INL_HPP*/ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp b/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp index ad3c84225f..d4b1774cf9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/eigen.hpp @@ -1,425 +1,425 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - - -#ifndef OPENCV_CORE_EIGEN_HPP -#define OPENCV_CORE_EIGEN_HPP - -#ifndef EIGEN_WORLD_VERSION -#error "Wrong usage of OpenCV's Eigen utility header. Include Eigen's headers first. See https://github.com/opencv/opencv/issues/17366" -#endif - -#include "opencv2/core.hpp" - -#if defined _MSC_VER && _MSC_VER >= 1200 -#ifndef NOMINMAX -#define NOMINMAX // fix https://github.com/opencv/opencv/issues/17548 -#endif -#pragma warning( disable: 4714 ) //__forceinline is not inlined -#pragma warning( disable: 4127 ) //conditional expression is constant -#pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data -#endif - -#if !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) -#if EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 -#include -#define OPENCV_EIGEN_TENSOR_SUPPORT 1 -#endif // EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 -#endif // !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) - -namespace cv -{ - -/** @addtogroup core_eigen -These functions are provided for OpenCV-Eigen interoperability. They convert `Mat` -objects to corresponding `Eigen::Matrix` objects and vice-versa. Consult the [Eigen -documentation](https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html) for -information about the `Matrix` template type. - -@note Using these functions requires the `Eigen/Dense` or similar header to be -included before this header. -*/ -//! @{ - -#if defined(OPENCV_EIGEN_TENSOR_SUPPORT) || defined(CV_DOXYGEN) -/** @brief Converts an Eigen::Tensor to a cv::Mat. - -The method converts an Eigen::Tensor with shape (H x W x C) to a cv::Mat where: - H = number of rows - W = number of columns - C = number of channels - -Usage: -\code -Eigen::Tensor a_tensor(...); -// populate tensor with values -Mat a_mat; -eigen2cv(a_tensor, a_mat); -\endcode -*/ -template static inline -void eigen2cv( const Eigen::Tensor<_Tp, 3, _layout> &src, OutputArray dst ) -{ - if( !(_layout & Eigen::RowMajorBit) ) - { - const std::array shuffle{2, 1, 0}; - Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor = src.swap_layout().shuffle(shuffle); - Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), row_major_tensor.data()); - _src.copyTo(dst); - } - else - { - Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), (void *)src.data()); - _src.copyTo(dst); - } -} - -/** @brief Converts a cv::Mat to an Eigen::Tensor. - -The method converts a cv::Mat to an Eigen Tensor with shape (H x W x C) where: - H = number of rows - W = number of columns - C = number of channels - -Usage: -\code -Mat a_mat(...); -// populate Mat with values -Eigen::Tensor a_tensor(...); -cv2eigen(a_mat, a_tensor); -\endcode -*/ -template static inline -void cv2eigen( const Mat &src, Eigen::Tensor<_Tp, 3, _layout> &dst ) -{ - if( !(_layout & Eigen::RowMajorBit) ) - { - Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor(src.rows, src.cols, src.channels()); - Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), row_major_tensor.data()); - if (src.type() == _dst.type()) - src.copyTo(_dst); - else - src.convertTo(_dst, _dst.type()); - const std::array shuffle{2, 1, 0}; - dst = row_major_tensor.swap_layout().shuffle(shuffle); - } - else - { - dst.resize(src.rows, src.cols, src.channels()); - Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), dst.data()); - if (src.type() == _dst.type()) - src.copyTo(_dst); - else - src.convertTo(_dst, _dst.type()); - } -} - -/** @brief Maps cv::Mat data to an Eigen::TensorMap. - -The method wraps an existing Mat data array with an Eigen TensorMap of shape (H x W x C) where: - H = number of rows - W = number of columns - C = number of channels - -Explicit instantiation of the return type is required. - -@note Caller should be aware of the lifetime of the cv::Mat instance and take appropriate safety measures. -The cv::Mat instance will retain ownership of the data and the Eigen::TensorMap will lose access when the cv::Mat data is deallocated. - -The example below initializes a cv::Mat and produces an Eigen::TensorMap: -\code -float arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; -Mat a_mat(2, 2, CV_32FC3, arr); -Eigen::TensorMap> a_tensormap = cv2eigen_tensormap(a_mat); -\endcode -*/ -template static inline -Eigen::TensorMap> cv2eigen_tensormap(InputArray src) -{ - Mat mat = src.getMat(); - CV_CheckTypeEQ(mat.type(), CV_MAKETYPE(traits::Type<_Tp>::value, mat.channels()), ""); - return Eigen::TensorMap>((_Tp *)mat.data, mat.rows, mat.cols, mat.channels()); -} -#endif // OPENCV_EIGEN_TENSOR_SUPPORT - -template static inline -void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) -{ - if( !(src.Flags & Eigen::RowMajorBit) ) - { - Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value, - (void*)src.data(), src.outerStride()*sizeof(_Tp)); - transpose(_src, dst); - } - else - { - Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value, - (void*)src.data(), src.outerStride()*sizeof(_Tp)); - _src.copyTo(dst); - } -} - -// Matx case -template static inline -void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, - Matx<_Tp, _rows, _cols>& dst ) -{ - if( !(src.Flags & Eigen::RowMajorBit) ) - { - dst = Matx<_Tp, _cols, _rows>(static_cast(src.data())).t(); - } - else - { - dst = Matx<_Tp, _rows, _cols>(static_cast(src.data())); - } -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) -{ - CV_DbgAssert(src.rows == _rows && src.cols == _cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else if( src.cols == src.rows ) - { - src.convertTo(_dst, _dst.type()); - transpose(_dst, _dst); - } - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -// Matx case -template static inline -void cv2eigen( const Matx<_Tp, _rows, _cols>& src, - Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) -{ - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); - } -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) -{ - dst.resize(src.rows, src.cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else if( src.cols == src.rows ) - { - src.convertTo(_dst, _dst.type()); - transpose(_dst, _dst); - } - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) -{ - CV_CheckEQ(src.dims, 2, ""); - dst.resize(src.rows, src.cols); - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); -} - -// Matx case -template static inline -void cv2eigen( const Matx<_Tp, _rows, _cols>& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) -{ - dst.resize(_rows, _cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); - } -} - -template static inline -void cv2eigen( const Matx<_Tp, _rows, _cols>& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) -{ - CV_CheckEQ(src.dims, 2, ""); - dst.resize(_rows, _cols); - const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); -} - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) -{ - CV_Assert(src.cols == 1); - dst.resize(src.rows); - - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -// Matx case -template static inline -void cv2eigen( const Matx<_Tp, _rows, 1>& src, - Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) -{ - dst.resize(_rows); - - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(1, _rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(_rows, 1, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.copyTo(_dst); - } -} - - -template static inline -void cv2eigen( const Mat& src, - Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) -{ - CV_Assert(src.rows == 1); - dst.resize(src.cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - if( src.type() == _dst.type() ) - transpose(src, _dst); - else - Mat(src.t()).convertTo(_dst, _dst.type()); - } - else - { - const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - src.convertTo(_dst, _dst.type()); - } -} - -//Matx -template static inline -void cv2eigen( const Matx<_Tp, 1, _cols>& src, - Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) -{ - dst.resize(_cols); - if( !(dst.Flags & Eigen::RowMajorBit) ) - { - const Mat _dst(_cols, 1, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - transpose(src, _dst); - } - else - { - const Mat _dst(1, _cols, traits::Type<_Tp>::value, - dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); - Mat(src).copyTo(_dst); - } -} - -//! @} - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + + +#ifndef OPENCV_CORE_EIGEN_HPP +#define OPENCV_CORE_EIGEN_HPP + +#ifndef EIGEN_WORLD_VERSION +#error "Wrong usage of OpenCV's Eigen utility header. Include Eigen's headers first. See https://github.com/opencv/opencv/issues/17366" +#endif + +#include "opencv2/core.hpp" + +#if defined _MSC_VER && _MSC_VER >= 1200 +#ifndef NOMINMAX +#define NOMINMAX // fix https://github.com/opencv/opencv/issues/17548 +#endif +#pragma warning( disable: 4714 ) //__forceinline is not inlined +#pragma warning( disable: 4127 ) //conditional expression is constant +#pragma warning( disable: 4244 ) //conversion from '__int64' to 'int', possible loss of data +#endif + +#if !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) +#if EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 +#include +#define OPENCV_EIGEN_TENSOR_SUPPORT 1 +#endif // EIGEN_WORLD_VERSION == 3 && EIGEN_MAJOR_VERSION >= 3 +#endif // !defined(OPENCV_DISABLE_EIGEN_TENSOR_SUPPORT) + +namespace cv +{ + +/** @addtogroup core_eigen +These functions are provided for OpenCV-Eigen interoperability. They convert `Mat` +objects to corresponding `Eigen::Matrix` objects and vice-versa. Consult the [Eigen +documentation](https://eigen.tuxfamily.org/dox/group__TutorialMatrixClass.html) for +information about the `Matrix` template type. + +@note Using these functions requires the `Eigen/Dense` or similar header to be +included before this header. +*/ +//! @{ + +#if defined(OPENCV_EIGEN_TENSOR_SUPPORT) || defined(CV_DOXYGEN) +/** @brief Converts an Eigen::Tensor to a cv::Mat. + +The method converts an Eigen::Tensor with shape (H x W x C) to a cv::Mat where: + H = number of rows + W = number of columns + C = number of channels + +Usage: +\code +Eigen::Tensor a_tensor(...); +// populate tensor with values +Mat a_mat; +eigen2cv(a_tensor, a_mat); +\endcode +*/ +template static inline +void eigen2cv( const Eigen::Tensor<_Tp, 3, _layout> &src, OutputArray dst ) +{ + if( !(_layout & Eigen::RowMajorBit) ) + { + const std::array shuffle{2, 1, 0}; + Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor = src.swap_layout().shuffle(shuffle); + Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), row_major_tensor.data()); + _src.copyTo(dst); + } + else + { + Mat _src(src.dimension(0), src.dimension(1), CV_MAKETYPE(DataType<_Tp>::type, src.dimension(2)), (void *)src.data()); + _src.copyTo(dst); + } +} + +/** @brief Converts a cv::Mat to an Eigen::Tensor. + +The method converts a cv::Mat to an Eigen Tensor with shape (H x W x C) where: + H = number of rows + W = number of columns + C = number of channels + +Usage: +\code +Mat a_mat(...); +// populate Mat with values +Eigen::Tensor a_tensor(...); +cv2eigen(a_mat, a_tensor); +\endcode +*/ +template static inline +void cv2eigen( const Mat &src, Eigen::Tensor<_Tp, 3, _layout> &dst ) +{ + if( !(_layout & Eigen::RowMajorBit) ) + { + Eigen::Tensor<_Tp, 3, !_layout> row_major_tensor(src.rows, src.cols, src.channels()); + Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), row_major_tensor.data()); + if (src.type() == _dst.type()) + src.copyTo(_dst); + else + src.convertTo(_dst, _dst.type()); + const std::array shuffle{2, 1, 0}; + dst = row_major_tensor.swap_layout().shuffle(shuffle); + } + else + { + dst.resize(src.rows, src.cols, src.channels()); + Mat _dst(src.rows, src.cols, CV_MAKETYPE(DataType<_Tp>::type, src.channels()), dst.data()); + if (src.type() == _dst.type()) + src.copyTo(_dst); + else + src.convertTo(_dst, _dst.type()); + } +} + +/** @brief Maps cv::Mat data to an Eigen::TensorMap. + +The method wraps an existing Mat data array with an Eigen TensorMap of shape (H x W x C) where: + H = number of rows + W = number of columns + C = number of channels + +Explicit instantiation of the return type is required. + +@note Caller should be aware of the lifetime of the cv::Mat instance and take appropriate safety measures. +The cv::Mat instance will retain ownership of the data and the Eigen::TensorMap will lose access when the cv::Mat data is deallocated. + +The example below initializes a cv::Mat and produces an Eigen::TensorMap: +\code +float arr[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; +Mat a_mat(2, 2, CV_32FC3, arr); +Eigen::TensorMap> a_tensormap = cv2eigen_tensormap(a_mat); +\endcode +*/ +template static inline +Eigen::TensorMap> cv2eigen_tensormap(InputArray src) +{ + Mat mat = src.getMat(); + CV_CheckTypeEQ(mat.type(), CV_MAKETYPE(traits::Type<_Tp>::value, mat.channels()), ""); + return Eigen::TensorMap>((_Tp *)mat.data, mat.rows, mat.cols, mat.channels()); +} +#endif // OPENCV_EIGEN_TENSOR_SUPPORT + +template static inline +void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, OutputArray dst ) +{ + if( !(src.Flags & Eigen::RowMajorBit) ) + { + Mat _src(src.cols(), src.rows(), traits::Type<_Tp>::value, + (void*)src.data(), src.outerStride()*sizeof(_Tp)); + transpose(_src, dst); + } + else + { + Mat _src(src.rows(), src.cols(), traits::Type<_Tp>::value, + (void*)src.data(), src.outerStride()*sizeof(_Tp)); + _src.copyTo(dst); + } +} + +// Matx case +template static inline +void eigen2cv( const Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& src, + Matx<_Tp, _rows, _cols>& dst ) +{ + if( !(src.Flags & Eigen::RowMajorBit) ) + { + dst = Matx<_Tp, _cols, _rows>(static_cast(src.data())).t(); + } + else + { + dst = Matx<_Tp, _rows, _cols>(static_cast(src.data())); + } +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) +{ + CV_DbgAssert(src.rows == _rows && src.cols == _cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else if( src.cols == src.rows ) + { + src.convertTo(_dst, _dst.type()); + transpose(_dst, _dst); + } + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +// Matx case +template static inline +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, _rows, _cols, _options, _maxRows, _maxCols>& dst ) +{ + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + } +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) +{ + dst.resize(src.rows, src.cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else if( src.cols == src.rows ) + { + src.convertTo(_dst, _dst.type()); + transpose(_dst, _dst); + } + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) +{ + CV_CheckEQ(src.dims, 2, ""); + dst.resize(src.rows, src.cols); + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); +} + +// Matx case +template static inline +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic>& dst ) +{ + dst.resize(_rows, _cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(_cols, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + } +} + +template static inline +void cv2eigen( const Matx<_Tp, _rows, _cols>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& dst ) +{ + CV_CheckEQ(src.dims, 2, ""); + dst.resize(_rows, _cols); + const Mat _dst(_rows, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); +} + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) +{ + CV_Assert(src.cols == 1); + dst.resize(src.rows); + + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +// Matx case +template static inline +void cv2eigen( const Matx<_Tp, _rows, 1>& src, + Eigen::Matrix<_Tp, Eigen::Dynamic, 1>& dst ) +{ + dst.resize(_rows); + + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(1, _rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(_rows, 1, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.copyTo(_dst); + } +} + + +template static inline +void cv2eigen( const Mat& src, + Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) +{ + CV_Assert(src.rows == 1); + dst.resize(src.cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(src.cols, src.rows, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + if( src.type() == _dst.type() ) + transpose(src, _dst); + else + Mat(src.t()).convertTo(_dst, _dst.type()); + } + else + { + const Mat _dst(src.rows, src.cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + src.convertTo(_dst, _dst.type()); + } +} + +//Matx +template static inline +void cv2eigen( const Matx<_Tp, 1, _cols>& src, + Eigen::Matrix<_Tp, 1, Eigen::Dynamic>& dst ) +{ + dst.resize(_cols); + if( !(dst.Flags & Eigen::RowMajorBit) ) + { + const Mat _dst(_cols, 1, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + transpose(src, _dst); + } + else + { + const Mat _dst(1, _cols, traits::Type<_Tp>::value, + dst.data(), (size_t)(dst.outerStride()*sizeof(_Tp))); + Mat(src).copyTo(_dst); + } +} + +//! @} + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp b/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp index 3a6f8163fe..a28c3fbedf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/fast_math.hpp @@ -1,433 +1,433 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_FAST_MATH_HPP -#define OPENCV_CORE_FAST_MATH_HPP - -#include "opencv2/core/cvdef.h" - -//! @addtogroup core_utils -//! @{ - -/****************************************************************************************\ -* fast math * -\****************************************************************************************/ - -#ifdef __cplusplus -# include -#else -# ifdef __BORLANDC__ -# include -# else -# include -# endif -#endif - -#if defined(__CUDACC__) - // nothing, intrinsics/asm code is not supported -#else - #if ((defined _MSC_VER && defined _M_X64) \ - || (defined __GNUC__ && defined __SSE2__)) \ - && !defined(OPENCV_SKIP_INCLUDE_EMMINTRIN_H) - #include - #endif - - #if defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 \ - && !defined(OPENCV_SKIP_INCLUDE_ALTIVEC_H) - #include - #undef vector - #undef bool - #undef pixel - #endif - - #if defined(CV_INLINE_ROUND_FLT) - // user-specified version - // CV_INLINE_ROUND_DBL should be defined too - #elif defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON) && !defined __SOFTFP__ - // 1. general scheme - #define ARM_ROUND(_value, _asm_string) \ - int res; \ - float temp; \ - CV_UNUSED(temp); \ - __asm__(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \ - return res - // 2. version for double - #ifdef __clang__ - #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]") - #else - #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]") - #endif - // 3. version for float - #define CV_INLINE_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]") - #elif defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 - // P8 and newer machines can convert fp32/64 to int quickly. - #define CV_INLINE_ROUND_DBL(value) \ - int out; \ - double temp; \ - __asm__( "fctiw %[temp],%[in]\n\tmfvsrwz %[out],%[temp]\n\t" : [out] "=r" (out), [temp] "=d" (temp) : [in] "d" ((double)(value)) : ); \ - return out; - - // FP32 also works with FP64 routine above - #define CV_INLINE_ROUND_FLT(value) CV_INLINE_ROUND_DBL(value) - #endif - - #ifdef CV_INLINE_ISINF_FLT - // user-specified version - // CV_INLINE_ISINF_DBL should be defined too - #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) - #define CV_INLINE_ISINF_DBL(value) return scalar_test_data_class(value, 0x30); - #define CV_INLINE_ISINF_FLT(value) CV_INLINE_ISINF_DBL(value) - #endif - - #ifdef CV_INLINE_ISNAN_FLT - // user-specified version - // CV_INLINE_ISNAN_DBL should be defined too - #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) - #define CV_INLINE_ISNAN_DBL(value) return scalar_test_data_class(value, 0x40); - #define CV_INLINE_ISNAN_FLT(value) CV_INLINE_ISNAN_DBL(value) - #endif - - #if !defined(OPENCV_USE_FASTMATH_BUILTINS) \ - && ( \ - defined(__x86_64__) || defined(__i686__) \ - || defined(__arm__) \ - || defined(__PPC64__) \ - ) - /* Let builtin C math functions when available. Dedicated hardware is available to - round and convert FP values. */ - #define OPENCV_USE_FASTMATH_BUILTINS 1 - #endif - - /* Enable builtin math functions if possible, desired, and available. - Note, not all math functions inline equally. E.g lrint will not inline - without the -fno-math-errno option. */ - #if defined(CV_ICC) - // nothing - #elif defined(OPENCV_USE_FASTMATH_BUILTINS) && OPENCV_USE_FASTMATH_BUILTINS - #if defined(__clang__) - #define CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - #if !defined(CV_INLINE_ISNAN_DBL) && __has_builtin(__builtin_isnan) - #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); - #endif - #if !defined(CV_INLINE_ISNAN_FLT) && __has_builtin(__builtin_isnan) - #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnan(value); - #endif - #if !defined(CV_INLINE_ISINF_DBL) && __has_builtin(__builtin_isinf) - #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); - #endif - #if !defined(CV_INLINE_ISINF_FLT) && __has_builtin(__builtin_isinf) - #define CV_INLINE_ISINF_FLT(value) return __builtin_isinf(value); - #endif - #elif defined(__GNUC__) - #define CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS - #if !defined(CV_INLINE_ISNAN_DBL) - #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); - #endif - #if !defined(CV_INLINE_ISNAN_FLT) - #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnanf(value); - #endif - #if !defined(CV_INLINE_ISINF_DBL) - #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); - #endif - #if !defined(CV_INLINE_ISINF_FLT) - #define CV_INLINE_ISINF_FLT(value) return __builtin_isinff(value); - #endif - #elif defined(_MSC_VER) - #if !defined(CV_INLINE_ISNAN_DBL) - #define CV_INLINE_ISNAN_DBL(value) return isnan(value); - #endif - #if !defined(CV_INLINE_ISNAN_FLT) - #define CV_INLINE_ISNAN_FLT(value) return isnan(value); - #endif - #if !defined(CV_INLINE_ISINF_DBL) - #define CV_INLINE_ISINF_DBL(value) return isinf(value); - #endif - #if !defined(CV_INLINE_ISINF_FLT) - #define CV_INLINE_ISINF_FLT(value) return isinf(value); - #endif - #endif - #endif - -#endif // defined(__CUDACC__) - -/** @brief Rounds floating-point number to the nearest integer - - @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the - result is not defined. - */ -CV_INLINE int -cvRound( double value ) -{ -#if defined CV_INLINE_ROUND_DBL - CV_INLINE_ROUND_DBL(value); -#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) - __m128d t = _mm_set_sd( value ); - return _mm_cvtsd_si32(t); -#elif defined _MSC_VER && defined _M_IX86 - int t; - __asm - { - fld value; - fistp t; - } - return t; -#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_lrint(value); -#else - return (int)lrint(value); -#endif -} - - -/** @brief Rounds floating-point number to the nearest integer not larger than the original. - - The function computes an integer i such that: - \f[i \le \texttt{value} < i+1\f] - @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the - result is not defined. - */ -CV_INLINE int cvFloor( double value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_floor(value); -#elif defined __loongarch64 - int i; - double tmp; - __asm__ ("ftintrm.l.d %[tmp], %[in] \n\t" - "movfr2gr.d %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i - (i > value); -#endif -} - -/** @brief Rounds floating-point number to the nearest integer not smaller than the original. - - The function computes an integer i such that: - \f[i \le \texttt{value} < i+1\f] - @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the - result is not defined. - */ -CV_INLINE int cvCeil( double value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_ceil(value); -#elif defined __loongarch64 - int i; - double tmp; - __asm__ ("ftintrp.l.d %[tmp], %[in] \n\t" - "movfr2gr.d %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i + (i < value); -#endif -} - -/** @brief Determines if the argument is Not A Number. - - @param value The input floating-point value - - The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 - otherwise. */ -CV_INLINE int cvIsNaN( double value ) -{ -#if defined CV_INLINE_ISNAN_DBL - CV_INLINE_ISNAN_DBL(value); -#else - Cv64suf ieee754; - ieee754.f = value; - return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) + - ((unsigned)ieee754.u != 0) > 0x7ff00000; -#endif -} - -/** @brief Determines if the argument is Infinity. - - @param value The input floating-point value - - The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) - and 0 otherwise. */ -CV_INLINE int cvIsInf( double value ) -{ -#if defined CV_INLINE_ISINF_DBL - CV_INLINE_ISINF_DBL(value); -#elif defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__PPC64__) || defined(__loongarch64) - Cv64suf ieee754; - ieee754.f = value; - return (ieee754.u & 0x7fffffffffffffff) == - 0x7ff0000000000000; -#else - Cv64suf ieee754; - ieee754.f = value; - return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 && - (unsigned)ieee754.u == 0; -#endif -} - -#ifdef __cplusplus - -/** @overload */ -CV_INLINE int cvRound(float value) -{ -#if defined CV_INLINE_ROUND_FLT - CV_INLINE_ROUND_FLT(value); -#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) - __m128 t = _mm_set_ss( value ); - return _mm_cvtss_si32(t); -#elif defined _MSC_VER && defined _M_IX86 - int t; - __asm - { - fld value; - fistp t; - } - return t; -#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_lrintf(value); -#else - return (int)lrintf(value); -#endif -} - -/** @overload */ -CV_INLINE int cvRound( int value ) -{ - return value; -} - -/** @overload */ -CV_INLINE int cvFloor( float value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_floorf(value); -#elif defined __loongarch__ - int i; - float tmp; - __asm__ ("ftintrm.w.s %[tmp], %[in] \n\t" - "movfr2gr.s %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i - (i > value); -#endif -} - -/** @overload */ -CV_INLINE int cvFloor( int value ) -{ - return value; -} - -/** @overload */ -CV_INLINE int cvCeil( float value ) -{ -#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ - defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS - return (int)__builtin_ceilf(value); -#elif defined __loongarch__ - int i; - float tmp; - __asm__ ("ftintrp.w.s %[tmp], %[in] \n\t" - "movfr2gr.s %[i], %[tmp] \n\t" - : [i] "=r" (i), [tmp] "=f" (tmp) - : [in] "f" (value) - :); - return i; -#else - int i = (int)value; - return i + (i < value); -#endif -} - -/** @overload */ -CV_INLINE int cvCeil( int value ) -{ - return value; -} - -/** @overload */ -CV_INLINE int cvIsNaN( float value ) -{ -#if defined CV_INLINE_ISNAN_FLT - CV_INLINE_ISNAN_FLT(value); -#else - Cv32suf ieee754; - ieee754.f = value; - return (ieee754.u & 0x7fffffff) > 0x7f800000; -#endif -} - -/** @overload */ -CV_INLINE int cvIsInf( float value ) -{ -#if defined CV_INLINE_ISINF_FLT - CV_INLINE_ISINF_FLT(value); -#else - Cv32suf ieee754; - ieee754.f = value; - return (ieee754.u & 0x7fffffff) == 0x7f800000; -#endif -} - -#endif // __cplusplus - -//! @} core_utils - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_FAST_MATH_HPP +#define OPENCV_CORE_FAST_MATH_HPP + +#include "opencv2/core/cvdef.h" + +//! @addtogroup core_utils +//! @{ + +/****************************************************************************************\ +* fast math * +\****************************************************************************************/ + +#ifdef __cplusplus +# include +#else +# ifdef __BORLANDC__ +# include +# else +# include +# endif +#endif + +#if defined(__CUDACC__) + // nothing, intrinsics/asm code is not supported +#else + #if ((defined _MSC_VER && defined _M_X64) \ + || (defined __GNUC__ && defined __SSE2__)) \ + && !defined(OPENCV_SKIP_INCLUDE_EMMINTRIN_H) + #include + #endif + + #if defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 \ + && !defined(OPENCV_SKIP_INCLUDE_ALTIVEC_H) + #include + #undef vector + #undef bool + #undef pixel + #endif + + #if defined(CV_INLINE_ROUND_FLT) + // user-specified version + // CV_INLINE_ROUND_DBL should be defined too + #elif defined __GNUC__ && defined __arm__ && (defined __ARM_PCS_VFP || defined __ARM_VFPV3__ || defined __ARM_NEON) && !defined __SOFTFP__ + // 1. general scheme + #define ARM_ROUND(_value, _asm_string) \ + int res; \ + float temp; \ + CV_UNUSED(temp); \ + __asm__(_asm_string : [res] "=r" (res), [temp] "=w" (temp) : [value] "w" (_value)); \ + return res + // 2. version for double + #ifdef __clang__ + #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %[value] \n vmov %[res], %[temp]") + #else + #define CV_INLINE_ROUND_DBL(value) ARM_ROUND(value, "vcvtr.s32.f64 %[temp], %P[value] \n vmov %[res], %[temp]") + #endif + // 3. version for float + #define CV_INLINE_ROUND_FLT(value) ARM_ROUND(value, "vcvtr.s32.f32 %[temp], %[value]\n vmov %[res], %[temp]") + #elif defined __PPC64__ && defined __GNUC__ && defined _ARCH_PWR8 + // P8 and newer machines can convert fp32/64 to int quickly. + #define CV_INLINE_ROUND_DBL(value) \ + int out; \ + double temp; \ + __asm__( "fctiw %[temp],%[in]\n\tmfvsrwz %[out],%[temp]\n\t" : [out] "=r" (out), [temp] "=d" (temp) : [in] "d" ((double)(value)) : ); \ + return out; + + // FP32 also works with FP64 routine above + #define CV_INLINE_ROUND_FLT(value) CV_INLINE_ROUND_DBL(value) + #endif + + #ifdef CV_INLINE_ISINF_FLT + // user-specified version + // CV_INLINE_ISINF_DBL should be defined too + #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) + #define CV_INLINE_ISINF_DBL(value) return scalar_test_data_class(value, 0x30); + #define CV_INLINE_ISINF_FLT(value) CV_INLINE_ISINF_DBL(value) + #endif + + #ifdef CV_INLINE_ISNAN_FLT + // user-specified version + // CV_INLINE_ISNAN_DBL should be defined too + #elif defined __PPC64__ && defined _ARCH_PWR9 && defined(scalar_test_data_class) + #define CV_INLINE_ISNAN_DBL(value) return scalar_test_data_class(value, 0x40); + #define CV_INLINE_ISNAN_FLT(value) CV_INLINE_ISNAN_DBL(value) + #endif + + #if !defined(OPENCV_USE_FASTMATH_BUILTINS) \ + && ( \ + defined(__x86_64__) || defined(__i686__) \ + || defined(__arm__) \ + || defined(__PPC64__) \ + ) + /* Let builtin C math functions when available. Dedicated hardware is available to + round and convert FP values. */ + #define OPENCV_USE_FASTMATH_BUILTINS 1 + #endif + + /* Enable builtin math functions if possible, desired, and available. + Note, not all math functions inline equally. E.g lrint will not inline + without the -fno-math-errno option. */ + #if defined(CV_ICC) + // nothing + #elif defined(OPENCV_USE_FASTMATH_BUILTINS) && OPENCV_USE_FASTMATH_BUILTINS + #if defined(__clang__) + #define CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + #if !defined(CV_INLINE_ISNAN_DBL) && __has_builtin(__builtin_isnan) + #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); + #endif + #if !defined(CV_INLINE_ISNAN_FLT) && __has_builtin(__builtin_isnan) + #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnan(value); + #endif + #if !defined(CV_INLINE_ISINF_DBL) && __has_builtin(__builtin_isinf) + #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); + #endif + #if !defined(CV_INLINE_ISINF_FLT) && __has_builtin(__builtin_isinf) + #define CV_INLINE_ISINF_FLT(value) return __builtin_isinf(value); + #endif + #elif defined(__GNUC__) + #define CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS + #if !defined(CV_INLINE_ISNAN_DBL) + #define CV_INLINE_ISNAN_DBL(value) return __builtin_isnan(value); + #endif + #if !defined(CV_INLINE_ISNAN_FLT) + #define CV_INLINE_ISNAN_FLT(value) return __builtin_isnanf(value); + #endif + #if !defined(CV_INLINE_ISINF_DBL) + #define CV_INLINE_ISINF_DBL(value) return __builtin_isinf(value); + #endif + #if !defined(CV_INLINE_ISINF_FLT) + #define CV_INLINE_ISINF_FLT(value) return __builtin_isinff(value); + #endif + #elif defined(_MSC_VER) + #if !defined(CV_INLINE_ISNAN_DBL) + #define CV_INLINE_ISNAN_DBL(value) return isnan(value); + #endif + #if !defined(CV_INLINE_ISNAN_FLT) + #define CV_INLINE_ISNAN_FLT(value) return isnan(value); + #endif + #if !defined(CV_INLINE_ISINF_DBL) + #define CV_INLINE_ISINF_DBL(value) return isinf(value); + #endif + #if !defined(CV_INLINE_ISINF_FLT) + #define CV_INLINE_ISINF_FLT(value) return isinf(value); + #endif + #endif + #endif + +#endif // defined(__CUDACC__) + +/** @brief Rounds floating-point number to the nearest integer + + @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the + result is not defined. + */ +CV_INLINE int +cvRound( double value ) +{ +#if defined CV_INLINE_ROUND_DBL + CV_INLINE_ROUND_DBL(value); +#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) + __m128d t = _mm_set_sd( value ); + return _mm_cvtsd_si32(t); +#elif defined _MSC_VER && defined _M_IX86 + int t; + __asm + { + fld value; + fistp t; + } + return t; +#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_lrint(value); +#else + return (int)lrint(value); +#endif +} + + +/** @brief Rounds floating-point number to the nearest integer not larger than the original. + + The function computes an integer i such that: + \f[i \le \texttt{value} < i+1\f] + @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the + result is not defined. + */ +CV_INLINE int cvFloor( double value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_floor(value); +#elif defined __loongarch64 + int i; + double tmp; + __asm__ ("ftintrm.l.d %[tmp], %[in] \n\t" + "movfr2gr.d %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i - (i > value); +#endif +} + +/** @brief Rounds floating-point number to the nearest integer not smaller than the original. + + The function computes an integer i such that: + \f[i \le \texttt{value} < i+1\f] + @param value floating-point number. If the value is outside of INT_MIN ... INT_MAX range, the + result is not defined. + */ +CV_INLINE int cvCeil( double value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_ceil(value); +#elif defined __loongarch64 + int i; + double tmp; + __asm__ ("ftintrp.l.d %[tmp], %[in] \n\t" + "movfr2gr.d %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i + (i < value); +#endif +} + +/** @brief Determines if the argument is Not A Number. + + @param value The input floating-point value + + The function returns 1 if the argument is Not A Number (as defined by IEEE754 standard), 0 + otherwise. */ +CV_INLINE int cvIsNaN( double value ) +{ +#if defined CV_INLINE_ISNAN_DBL + CV_INLINE_ISNAN_DBL(value); +#else + Cv64suf ieee754; + ieee754.f = value; + return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) + + ((unsigned)ieee754.u != 0) > 0x7ff00000; +#endif +} + +/** @brief Determines if the argument is Infinity. + + @param value The input floating-point value + + The function returns 1 if the argument is a plus or minus infinity (as defined by IEEE754 standard) + and 0 otherwise. */ +CV_INLINE int cvIsInf( double value ) +{ +#if defined CV_INLINE_ISINF_DBL + CV_INLINE_ISINF_DBL(value); +#elif defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__PPC64__) || defined(__loongarch64) + Cv64suf ieee754; + ieee754.f = value; + return (ieee754.u & 0x7fffffffffffffff) == + 0x7ff0000000000000; +#else + Cv64suf ieee754; + ieee754.f = value; + return ((unsigned)(ieee754.u >> 32) & 0x7fffffff) == 0x7ff00000 && + (unsigned)ieee754.u == 0; +#endif +} + +#ifdef __cplusplus + +/** @overload */ +CV_INLINE int cvRound(float value) +{ +#if defined CV_INLINE_ROUND_FLT + CV_INLINE_ROUND_FLT(value); +#elif ((defined _MSC_VER && defined _M_X64) || (defined __GNUC__ && defined __SSE2__)) && !defined(__CUDACC__) + __m128 t = _mm_set_ss( value ); + return _mm_cvtss_si32(t); +#elif defined _MSC_VER && defined _M_IX86 + int t; + __asm + { + fld value; + fistp t; + } + return t; +#elif defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_lrintf(value); +#else + return (int)lrintf(value); +#endif +} + +/** @overload */ +CV_INLINE int cvRound( int value ) +{ + return value; +} + +/** @overload */ +CV_INLINE int cvFloor( float value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_floorf(value); +#elif defined __loongarch__ + int i; + float tmp; + __asm__ ("ftintrm.w.s %[tmp], %[in] \n\t" + "movfr2gr.s %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i - (i > value); +#endif +} + +/** @overload */ +CV_INLINE int cvFloor( int value ) +{ + return value; +} + +/** @overload */ +CV_INLINE int cvCeil( float value ) +{ +#if defined CV__FASTMATH_ENABLE_GCC_MATH_BUILTINS || \ + defined CV__FASTMATH_ENABLE_CLANG_MATH_BUILTINS + return (int)__builtin_ceilf(value); +#elif defined __loongarch__ + int i; + float tmp; + __asm__ ("ftintrp.w.s %[tmp], %[in] \n\t" + "movfr2gr.s %[i], %[tmp] \n\t" + : [i] "=r" (i), [tmp] "=f" (tmp) + : [in] "f" (value) + :); + return i; +#else + int i = (int)value; + return i + (i < value); +#endif +} + +/** @overload */ +CV_INLINE int cvCeil( int value ) +{ + return value; +} + +/** @overload */ +CV_INLINE int cvIsNaN( float value ) +{ +#if defined CV_INLINE_ISNAN_FLT + CV_INLINE_ISNAN_FLT(value); +#else + Cv32suf ieee754; + ieee754.f = value; + return (ieee754.u & 0x7fffffff) > 0x7f800000; +#endif +} + +/** @overload */ +CV_INLINE int cvIsInf( float value ) +{ +#if defined CV_INLINE_ISINF_FLT + CV_INLINE_ISINF_FLT(value); +#else + Cv32suf ieee754; + ieee754.f = value; + return (ieee754.u & 0x7fffffff) == 0x7f800000; +#endif +} + +#endif // __cplusplus + +//! @} core_utils + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp index 34505515c0..deca4e9539 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/hal.hpp @@ -1,260 +1,260 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HAL_HPP -#define OPENCV_HAL_HPP - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/hal/interface.h" - -namespace cv { namespace hal { - -//! @addtogroup core_hal_functions -//! @{ - -CV_EXPORTS int normHamming(const uchar* a, int n); -CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); - -CV_EXPORTS int normHamming(const uchar* a, int n, int cellSize); -CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); - -CV_EXPORTS int LU32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS int LU64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS void SVD32f(float* At, size_t astep, float* W, float* U, size_t ustep, float* Vt, size_t vstep, int m, int n, int flags); -CV_EXPORTS void SVD64f(double* At, size_t astep, double* W, double* U, size_t ustep, double* Vt, size_t vstep, int m, int n, int flags); -CV_EXPORTS int QR32f(float* A, size_t astep, int m, int n, int k, float* b, size_t bstep, float* hFactors); -CV_EXPORTS int QR64f(double* A, size_t astep, int m, int n, int k, double* b, size_t bstep, double* hFactors); - -CV_EXPORTS void gemm32f(const float* src1, size_t src1_step, const float* src2, size_t src2_step, - float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); -CV_EXPORTS void gemm64f(const double* src1, size_t src1_step, const double* src2, size_t src2_step, - double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); -CV_EXPORTS void gemm32fc(const float* src1, size_t src1_step, const float* src2, size_t src2_step, - float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); -CV_EXPORTS void gemm64fc(const double* src1, size_t src1_step, const double* src2, size_t src2_step, - double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, - int m_a, int n_a, int n_d, int flags); - -CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); -CV_EXPORTS float normL1_(const float* a, const float* b, int n); -CV_EXPORTS float normL2Sqr_(const float* a, const float* b, int n); - -CV_EXPORTS void exp32f(const float* src, float* dst, int n); -CV_EXPORTS void exp64f(const double* src, double* dst, int n); -CV_EXPORTS void log32f(const float* src, float* dst, int n); -CV_EXPORTS void log64f(const double* src, double* dst, int n); - -CV_EXPORTS void cartToPolar32f(const float* x, const float* y, float* mag, float* angle, int n, bool angleInDegrees); -CV_EXPORTS void cartToPolar64f(const double* x, const double* y, double* mag, double* angle, int n, bool angleInDegrees); -CV_EXPORTS void fastAtan32f(const float* y, const float* x, float* dst, int n, bool angleInDegrees); -CV_EXPORTS void fastAtan64f(const double* y, const double* x, double* dst, int n, bool angleInDegrees); -CV_EXPORTS void magnitude32f(const float* x, const float* y, float* dst, int n); -CV_EXPORTS void magnitude64f(const double* x, const double* y, double* dst, int n); -CV_EXPORTS void polarToCart32f(const float* mag, const float* angle, float* x, float* y, int n, bool angleInDegrees); -CV_EXPORTS void polarToCart64f(const double* mag, const double* angle, double* x, double* y, int n, bool angleInDegrees); -CV_EXPORTS void sqrt32f(const float* src, float* dst, int len); -CV_EXPORTS void sqrt64f(const double* src, double* dst, int len); -CV_EXPORTS void invSqrt32f(const float* src, float* dst, int len); -CV_EXPORTS void invSqrt64f(const double* src, double* dst, int len); - -CV_EXPORTS void split8u(const uchar* src, uchar** dst, int len, int cn ); -CV_EXPORTS void split16u(const ushort* src, ushort** dst, int len, int cn ); -CV_EXPORTS void split32s(const int* src, int** dst, int len, int cn ); -CV_EXPORTS void split64s(const int64* src, int64** dst, int len, int cn ); - -CV_EXPORTS void merge8u(const uchar** src, uchar* dst, int len, int cn ); -CV_EXPORTS void merge16u(const ushort** src, ushort* dst, int len, int cn ); -CV_EXPORTS void merge32s(const int** src, int* dst, int len, int cn ); -CV_EXPORTS void merge64s(const int64** src, int64* dst, int len, int cn ); - -CV_EXPORTS void add8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void add64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void sub8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void sub64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void max8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void max64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void min8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void min64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void absdiff8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void absdiff64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void and8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void or8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void xor8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); -CV_EXPORTS void not8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); - -CV_EXPORTS void cmp8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp8s(const schar* src1, size_t step1, const schar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp16s(const short* src1, size_t step1, const short* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp32s(const int* src1, size_t step1, const int* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp32f(const float* src1, size_t step1, const float* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); -CV_EXPORTS void cmp64f(const double* src1, size_t step1, const double* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); - -CV_EXPORTS void mul8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void mul64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); - -CV_EXPORTS void div8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void div64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); - -CV_EXPORTS void recip8u( const uchar *, size_t, const uchar * src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip8s( const schar *, size_t, const schar * src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip16u( const ushort *, size_t, const ushort * src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip16s( const short *, size_t, const short * src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip32s( const int *, size_t, const int * src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip32f( const float *, size_t, const float * src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); -CV_EXPORTS void recip64f( const double *, size_t, const double * src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); - -CV_EXPORTS void addWeighted8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _scalars ); -CV_EXPORTS void addWeighted8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scalars ); -CV_EXPORTS void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scalars ); - -CV_EXPORTS void cvt16f32f( const hfloat* src, float* dst, int len ); -CV_EXPORTS void cvt32f16f( const float* src, hfloat* dst, int len ); - -CV_EXPORTS void addRNGBias32f( float* arr, const float* scaleBiasPairs, int len ); -CV_EXPORTS void addRNGBias64f( double* arr, const double* scaleBiasPairs, int len ); - -struct CV_EXPORTS DFT1D -{ - static Ptr create(int len, int count, int depth, int flags, bool * useBuffer = 0); - virtual void apply(const uchar *src, uchar *dst) = 0; - virtual ~DFT1D() {} -}; - -struct CV_EXPORTS DFT2D -{ - static Ptr create(int width, int height, int depth, - int src_channels, int dst_channels, - int flags, int nonzero_rows = 0); - virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; - virtual ~DFT2D() {} -}; - -struct CV_EXPORTS DCT2D -{ - static Ptr create(int width, int height, int depth, int flags); - virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; - virtual ~DCT2D() {} -}; - -//! @} core_hal - -//============================================================================= -// for binary compatibility with 3.0 - -//! @cond IGNORED - -CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); -CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); - -CV_EXPORTS void exp(const float* src, float* dst, int n); -CV_EXPORTS void exp(const double* src, double* dst, int n); -CV_EXPORTS void log(const float* src, float* dst, int n); -CV_EXPORTS void log(const double* src, double* dst, int n); - -CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); -CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); -CV_EXPORTS void magnitude(const double* x, const double* y, double* dst, int n); -CV_EXPORTS void sqrt(const float* src, float* dst, int len); -CV_EXPORTS void sqrt(const double* src, double* dst, int len); -CV_EXPORTS void invSqrt(const float* src, float* dst, int len); -CV_EXPORTS void invSqrt(const double* src, double* dst, int len); - -//! @endcond - -}} //cv::hal - -#endif //OPENCV_HAL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HAL_HPP +#define OPENCV_HAL_HPP + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/hal/interface.h" + +namespace cv { namespace hal { + +//! @addtogroup core_hal_functions +//! @{ + +CV_EXPORTS int normHamming(const uchar* a, int n); +CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n); + +CV_EXPORTS int normHamming(const uchar* a, int n, int cellSize); +CV_EXPORTS int normHamming(const uchar* a, const uchar* b, int n, int cellSize); + +CV_EXPORTS int LU32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS int LU64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky32f(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky64f(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS void SVD32f(float* At, size_t astep, float* W, float* U, size_t ustep, float* Vt, size_t vstep, int m, int n, int flags); +CV_EXPORTS void SVD64f(double* At, size_t astep, double* W, double* U, size_t ustep, double* Vt, size_t vstep, int m, int n, int flags); +CV_EXPORTS int QR32f(float* A, size_t astep, int m, int n, int k, float* b, size_t bstep, float* hFactors); +CV_EXPORTS int QR64f(double* A, size_t astep, int m, int n, int k, double* b, size_t bstep, double* hFactors); + +CV_EXPORTS void gemm32f(const float* src1, size_t src1_step, const float* src2, size_t src2_step, + float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); +CV_EXPORTS void gemm64f(const double* src1, size_t src1_step, const double* src2, size_t src2_step, + double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); +CV_EXPORTS void gemm32fc(const float* src1, size_t src1_step, const float* src2, size_t src2_step, + float alpha, const float* src3, size_t src3_step, float beta, float* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); +CV_EXPORTS void gemm64fc(const double* src1, size_t src1_step, const double* src2, size_t src2_step, + double alpha, const double* src3, size_t src3_step, double beta, double* dst, size_t dst_step, + int m_a, int n_a, int n_d, int flags); + +CV_EXPORTS int normL1_(const uchar* a, const uchar* b, int n); +CV_EXPORTS float normL1_(const float* a, const float* b, int n); +CV_EXPORTS float normL2Sqr_(const float* a, const float* b, int n); + +CV_EXPORTS void exp32f(const float* src, float* dst, int n); +CV_EXPORTS void exp64f(const double* src, double* dst, int n); +CV_EXPORTS void log32f(const float* src, float* dst, int n); +CV_EXPORTS void log64f(const double* src, double* dst, int n); + +CV_EXPORTS void cartToPolar32f(const float* x, const float* y, float* mag, float* angle, int n, bool angleInDegrees); +CV_EXPORTS void cartToPolar64f(const double* x, const double* y, double* mag, double* angle, int n, bool angleInDegrees); +CV_EXPORTS void fastAtan32f(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void fastAtan64f(const double* y, const double* x, double* dst, int n, bool angleInDegrees); +CV_EXPORTS void magnitude32f(const float* x, const float* y, float* dst, int n); +CV_EXPORTS void magnitude64f(const double* x, const double* y, double* dst, int n); +CV_EXPORTS void polarToCart32f(const float* mag, const float* angle, float* x, float* y, int n, bool angleInDegrees); +CV_EXPORTS void polarToCart64f(const double* mag, const double* angle, double* x, double* y, int n, bool angleInDegrees); +CV_EXPORTS void sqrt32f(const float* src, float* dst, int len); +CV_EXPORTS void sqrt64f(const double* src, double* dst, int len); +CV_EXPORTS void invSqrt32f(const float* src, float* dst, int len); +CV_EXPORTS void invSqrt64f(const double* src, double* dst, int len); + +CV_EXPORTS void split8u(const uchar* src, uchar** dst, int len, int cn ); +CV_EXPORTS void split16u(const ushort* src, ushort** dst, int len, int cn ); +CV_EXPORTS void split32s(const int* src, int** dst, int len, int cn ); +CV_EXPORTS void split64s(const int64* src, int64** dst, int len, int cn ); + +CV_EXPORTS void merge8u(const uchar** src, uchar* dst, int len, int cn ); +CV_EXPORTS void merge16u(const ushort** src, ushort* dst, int len, int cn ); +CV_EXPORTS void merge32s(const int** src, int* dst, int len, int cn ); +CV_EXPORTS void merge64s(const int64** src, int64* dst, int len, int cn ); + +CV_EXPORTS void add8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void add64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void sub8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void sub64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void max8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void max64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void min8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void min64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void absdiff8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void absdiff64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void and8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void or8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void xor8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); +CV_EXPORTS void not8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* ); + +CV_EXPORTS void cmp8u(const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp8s(const schar* src1, size_t step1, const schar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp16u(const ushort* src1, size_t step1, const ushort* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp16s(const short* src1, size_t step1, const short* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp32s(const int* src1, size_t step1, const int* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp32f(const float* src1, size_t step1, const float* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); +CV_EXPORTS void cmp64f(const double* src1, size_t step1, const double* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _cmpop); + +CV_EXPORTS void mul8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void mul64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); + +CV_EXPORTS void div8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void div64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); + +CV_EXPORTS void recip8u( const uchar *, size_t, const uchar * src2, size_t step2, uchar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip8s( const schar *, size_t, const schar * src2, size_t step2, schar* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip16u( const ushort *, size_t, const ushort * src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip16s( const short *, size_t, const short * src2, size_t step2, short* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip32s( const int *, size_t, const int * src2, size_t step2, int* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip32f( const float *, size_t, const float * src2, size_t step2, float* dst, size_t step, int width, int height, void* scale); +CV_EXPORTS void recip64f( const double *, size_t, const double * src2, size_t step2, double* dst, size_t step, int width, int height, void* scale); + +CV_EXPORTS void addWeighted8u( const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, int width, int height, void* _scalars ); +CV_EXPORTS void addWeighted8s( const schar* src1, size_t step1, const schar* src2, size_t step2, schar* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted16u( const ushort* src1, size_t step1, const ushort* src2, size_t step2, ushort* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted16s( const short* src1, size_t step1, const short* src2, size_t step2, short* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted32s( const int* src1, size_t step1, const int* src2, size_t step2, int* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted32f( const float* src1, size_t step1, const float* src2, size_t step2, float* dst, size_t step, int width, int height, void* scalars ); +CV_EXPORTS void addWeighted64f( const double* src1, size_t step1, const double* src2, size_t step2, double* dst, size_t step, int width, int height, void* scalars ); + +CV_EXPORTS void cvt16f32f( const hfloat* src, float* dst, int len ); +CV_EXPORTS void cvt32f16f( const float* src, hfloat* dst, int len ); + +CV_EXPORTS void addRNGBias32f( float* arr, const float* scaleBiasPairs, int len ); +CV_EXPORTS void addRNGBias64f( double* arr, const double* scaleBiasPairs, int len ); + +struct CV_EXPORTS DFT1D +{ + static Ptr create(int len, int count, int depth, int flags, bool * useBuffer = 0); + virtual void apply(const uchar *src, uchar *dst) = 0; + virtual ~DFT1D() {} +}; + +struct CV_EXPORTS DFT2D +{ + static Ptr create(int width, int height, int depth, + int src_channels, int dst_channels, + int flags, int nonzero_rows = 0); + virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; + virtual ~DFT2D() {} +}; + +struct CV_EXPORTS DCT2D +{ + static Ptr create(int width, int height, int depth, int flags); + virtual void apply(const uchar *src_data, size_t src_step, uchar *dst_data, size_t dst_step) = 0; + virtual ~DCT2D() {} +}; + +//! @} core_hal + +//============================================================================= +// for binary compatibility with 3.0 + +//! @cond IGNORED + +CV_EXPORTS int LU(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS int LU(double* A, size_t astep, int m, double* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky(float* A, size_t astep, int m, float* b, size_t bstep, int n); +CV_EXPORTS bool Cholesky(double* A, size_t astep, int m, double* b, size_t bstep, int n); + +CV_EXPORTS void exp(const float* src, float* dst, int n); +CV_EXPORTS void exp(const double* src, double* dst, int n); +CV_EXPORTS void log(const float* src, float* dst, int n); +CV_EXPORTS void log(const double* src, double* dst, int n); + +CV_EXPORTS void fastAtan2(const float* y, const float* x, float* dst, int n, bool angleInDegrees); +CV_EXPORTS void magnitude(const float* x, const float* y, float* dst, int n); +CV_EXPORTS void magnitude(const double* x, const double* y, double* dst, int n); +CV_EXPORTS void sqrt(const float* src, float* dst, int len); +CV_EXPORTS void sqrt(const double* src, double* dst, int len); +CV_EXPORTS void invSqrt(const float* src, float* dst, int len); +CV_EXPORTS void invSqrt(const double* src, double* dst, int len); + +//! @endcond + +}} //cv::hal + +#endif //OPENCV_HAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h b/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h index 2fbb13f4ad..6f0a83d359 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/interface.h @@ -1,190 +1,190 @@ -#ifndef OPENCV_CORE_HAL_INTERFACE_H -#define OPENCV_CORE_HAL_INTERFACE_H - -//! @addtogroup core_hal_interface -//! @{ - -//! @name Return codes -//! @{ -#define CV_HAL_ERROR_OK 0 -#define CV_HAL_ERROR_NOT_IMPLEMENTED 1 -#define CV_HAL_ERROR_UNKNOWN -1 -//! @} - -#ifdef __cplusplus -#include -#else -#include -#include -#endif - -//! @name Data types -//! primitive types -//! - schar - signed 1 byte integer -//! - uchar - unsigned 1 byte integer -//! - short - signed 2 byte integer -//! - ushort - unsigned 2 byte integer -//! - int - signed 4 byte integer -//! - uint - unsigned 4 byte integer -//! - int64 - signed 8 byte integer -//! - uint64 - unsigned 8 byte integer -//! @{ -#if !defined _MSC_VER && !defined __BORLANDC__ -# if defined __cplusplus && __cplusplus >= 201103L && !defined __APPLE__ -# include -# ifdef __NEWLIB__ - typedef unsigned int uint; -# else - typedef std::uint32_t uint; -# endif -# else -# include - typedef uint32_t uint; -# endif -#else - typedef unsigned uint; -#endif - -typedef signed char schar; - -#ifndef __IPL_H__ - typedef unsigned char uchar; - typedef unsigned short ushort; -#endif - -#if defined _MSC_VER || defined __BORLANDC__ - typedef __int64 int64; - typedef unsigned __int64 uint64; -# define CV_BIG_INT(n) n##I64 -# define CV_BIG_UINT(n) n##UI64 -#else - typedef int64_t int64; - typedef uint64_t uint64; -# define CV_BIG_INT(n) n##LL -# define CV_BIG_UINT(n) n##ULL -#endif - -#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" - -#define CV_CN_MAX 512 -#define CV_CN_SHIFT 3 -#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) - -#define CV_8U 0 -#define CV_8S 1 -#define CV_16U 2 -#define CV_16S 3 -#define CV_32S 4 -#define CV_32F 5 -#define CV_64F 6 -#define CV_16F 7 - -#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) -#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) - -#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) -#define CV_MAKE_TYPE CV_MAKETYPE - -#define CV_8UC1 CV_MAKETYPE(CV_8U,1) -#define CV_8UC2 CV_MAKETYPE(CV_8U,2) -#define CV_8UC3 CV_MAKETYPE(CV_8U,3) -#define CV_8UC4 CV_MAKETYPE(CV_8U,4) -#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) - -#define CV_8SC1 CV_MAKETYPE(CV_8S,1) -#define CV_8SC2 CV_MAKETYPE(CV_8S,2) -#define CV_8SC3 CV_MAKETYPE(CV_8S,3) -#define CV_8SC4 CV_MAKETYPE(CV_8S,4) -#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) - -#define CV_16UC1 CV_MAKETYPE(CV_16U,1) -#define CV_16UC2 CV_MAKETYPE(CV_16U,2) -#define CV_16UC3 CV_MAKETYPE(CV_16U,3) -#define CV_16UC4 CV_MAKETYPE(CV_16U,4) -#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) - -#define CV_16SC1 CV_MAKETYPE(CV_16S,1) -#define CV_16SC2 CV_MAKETYPE(CV_16S,2) -#define CV_16SC3 CV_MAKETYPE(CV_16S,3) -#define CV_16SC4 CV_MAKETYPE(CV_16S,4) -#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) - -#define CV_32SC1 CV_MAKETYPE(CV_32S,1) -#define CV_32SC2 CV_MAKETYPE(CV_32S,2) -#define CV_32SC3 CV_MAKETYPE(CV_32S,3) -#define CV_32SC4 CV_MAKETYPE(CV_32S,4) -#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) - -#define CV_32FC1 CV_MAKETYPE(CV_32F,1) -#define CV_32FC2 CV_MAKETYPE(CV_32F,2) -#define CV_32FC3 CV_MAKETYPE(CV_32F,3) -#define CV_32FC4 CV_MAKETYPE(CV_32F,4) -#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) - -#define CV_64FC1 CV_MAKETYPE(CV_64F,1) -#define CV_64FC2 CV_MAKETYPE(CV_64F,2) -#define CV_64FC3 CV_MAKETYPE(CV_64F,3) -#define CV_64FC4 CV_MAKETYPE(CV_64F,4) -#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) - -#define CV_16FC1 CV_MAKETYPE(CV_16F,1) -#define CV_16FC2 CV_MAKETYPE(CV_16F,2) -#define CV_16FC3 CV_MAKETYPE(CV_16F,3) -#define CV_16FC4 CV_MAKETYPE(CV_16F,4) -#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) -//! @} - -//! @name Comparison operation -//! @sa cv::CmpTypes -//! @{ -#define CV_HAL_CMP_EQ 0 -#define CV_HAL_CMP_GT 1 -#define CV_HAL_CMP_GE 2 -#define CV_HAL_CMP_LT 3 -#define CV_HAL_CMP_LE 4 -#define CV_HAL_CMP_NE 5 -//! @} - -//! @name Border processing modes -//! @sa cv::BorderTypes -//! @{ -#define CV_HAL_BORDER_CONSTANT 0 -#define CV_HAL_BORDER_REPLICATE 1 -#define CV_HAL_BORDER_REFLECT 2 -#define CV_HAL_BORDER_WRAP 3 -#define CV_HAL_BORDER_REFLECT_101 4 -#define CV_HAL_BORDER_TRANSPARENT 5 -#define CV_HAL_BORDER_ISOLATED 16 -//! @} - -//! @name DFT flags -//! @{ -#define CV_HAL_DFT_INVERSE 1 -#define CV_HAL_DFT_SCALE 2 -#define CV_HAL_DFT_ROWS 4 -#define CV_HAL_DFT_COMPLEX_OUTPUT 16 -#define CV_HAL_DFT_REAL_OUTPUT 32 -#define CV_HAL_DFT_TWO_STAGE 64 -#define CV_HAL_DFT_STAGE_COLS 128 -#define CV_HAL_DFT_IS_CONTINUOUS 512 -#define CV_HAL_DFT_IS_INPLACE 1024 -//! @} - -//! @name SVD flags -//! @{ -#define CV_HAL_SVD_NO_UV 1 -#define CV_HAL_SVD_SHORT_UV 2 -#define CV_HAL_SVD_MODIFY_A 4 -#define CV_HAL_SVD_FULL_UV 8 -//! @} - -//! @name Gemm flags -//! @{ -#define CV_HAL_GEMM_1_T 1 -#define CV_HAL_GEMM_2_T 2 -#define CV_HAL_GEMM_3_T 4 -//! @} - -//! @} - -#endif +#ifndef OPENCV_CORE_HAL_INTERFACE_H +#define OPENCV_CORE_HAL_INTERFACE_H + +//! @addtogroup core_hal_interface +//! @{ + +//! @name Return codes +//! @{ +#define CV_HAL_ERROR_OK 0 +#define CV_HAL_ERROR_NOT_IMPLEMENTED 1 +#define CV_HAL_ERROR_UNKNOWN -1 +//! @} + +#ifdef __cplusplus +#include +#else +#include +#include +#endif + +//! @name Data types +//! primitive types +//! - schar - signed 1 byte integer +//! - uchar - unsigned 1 byte integer +//! - short - signed 2 byte integer +//! - ushort - unsigned 2 byte integer +//! - int - signed 4 byte integer +//! - uint - unsigned 4 byte integer +//! - int64 - signed 8 byte integer +//! - uint64 - unsigned 8 byte integer +//! @{ +#if !defined _MSC_VER && !defined __BORLANDC__ +# if defined __cplusplus && __cplusplus >= 201103L && !defined __APPLE__ +# include +# ifdef __NEWLIB__ + typedef unsigned int uint; +# else + typedef std::uint32_t uint; +# endif +# else +# include + typedef uint32_t uint; +# endif +#else + typedef unsigned uint; +#endif + +typedef signed char schar; + +#ifndef __IPL_H__ + typedef unsigned char uchar; + typedef unsigned short ushort; +#endif + +#if defined _MSC_VER || defined __BORLANDC__ + typedef __int64 int64; + typedef unsigned __int64 uint64; +# define CV_BIG_INT(n) n##I64 +# define CV_BIG_UINT(n) n##UI64 +#else + typedef int64_t int64; + typedef uint64_t uint64; +# define CV_BIG_INT(n) n##LL +# define CV_BIG_UINT(n) n##ULL +#endif + +#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" + +#define CV_CN_MAX 512 +#define CV_CN_SHIFT 3 +#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) + +#define CV_8U 0 +#define CV_8S 1 +#define CV_16U 2 +#define CV_16S 3 +#define CV_32S 4 +#define CV_32F 5 +#define CV_64F 6 +#define CV_16F 7 + +#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) +#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) + +#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) +#define CV_MAKE_TYPE CV_MAKETYPE + +#define CV_8UC1 CV_MAKETYPE(CV_8U,1) +#define CV_8UC2 CV_MAKETYPE(CV_8U,2) +#define CV_8UC3 CV_MAKETYPE(CV_8U,3) +#define CV_8UC4 CV_MAKETYPE(CV_8U,4) +#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) + +#define CV_8SC1 CV_MAKETYPE(CV_8S,1) +#define CV_8SC2 CV_MAKETYPE(CV_8S,2) +#define CV_8SC3 CV_MAKETYPE(CV_8S,3) +#define CV_8SC4 CV_MAKETYPE(CV_8S,4) +#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) + +#define CV_16UC1 CV_MAKETYPE(CV_16U,1) +#define CV_16UC2 CV_MAKETYPE(CV_16U,2) +#define CV_16UC3 CV_MAKETYPE(CV_16U,3) +#define CV_16UC4 CV_MAKETYPE(CV_16U,4) +#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) + +#define CV_16SC1 CV_MAKETYPE(CV_16S,1) +#define CV_16SC2 CV_MAKETYPE(CV_16S,2) +#define CV_16SC3 CV_MAKETYPE(CV_16S,3) +#define CV_16SC4 CV_MAKETYPE(CV_16S,4) +#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) + +#define CV_32SC1 CV_MAKETYPE(CV_32S,1) +#define CV_32SC2 CV_MAKETYPE(CV_32S,2) +#define CV_32SC3 CV_MAKETYPE(CV_32S,3) +#define CV_32SC4 CV_MAKETYPE(CV_32S,4) +#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) + +#define CV_32FC1 CV_MAKETYPE(CV_32F,1) +#define CV_32FC2 CV_MAKETYPE(CV_32F,2) +#define CV_32FC3 CV_MAKETYPE(CV_32F,3) +#define CV_32FC4 CV_MAKETYPE(CV_32F,4) +#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) + +#define CV_64FC1 CV_MAKETYPE(CV_64F,1) +#define CV_64FC2 CV_MAKETYPE(CV_64F,2) +#define CV_64FC3 CV_MAKETYPE(CV_64F,3) +#define CV_64FC4 CV_MAKETYPE(CV_64F,4) +#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) + +#define CV_16FC1 CV_MAKETYPE(CV_16F,1) +#define CV_16FC2 CV_MAKETYPE(CV_16F,2) +#define CV_16FC3 CV_MAKETYPE(CV_16F,3) +#define CV_16FC4 CV_MAKETYPE(CV_16F,4) +#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) +//! @} + +//! @name Comparison operation +//! @sa cv::CmpTypes +//! @{ +#define CV_HAL_CMP_EQ 0 +#define CV_HAL_CMP_GT 1 +#define CV_HAL_CMP_GE 2 +#define CV_HAL_CMP_LT 3 +#define CV_HAL_CMP_LE 4 +#define CV_HAL_CMP_NE 5 +//! @} + +//! @name Border processing modes +//! @sa cv::BorderTypes +//! @{ +#define CV_HAL_BORDER_CONSTANT 0 +#define CV_HAL_BORDER_REPLICATE 1 +#define CV_HAL_BORDER_REFLECT 2 +#define CV_HAL_BORDER_WRAP 3 +#define CV_HAL_BORDER_REFLECT_101 4 +#define CV_HAL_BORDER_TRANSPARENT 5 +#define CV_HAL_BORDER_ISOLATED 16 +//! @} + +//! @name DFT flags +//! @{ +#define CV_HAL_DFT_INVERSE 1 +#define CV_HAL_DFT_SCALE 2 +#define CV_HAL_DFT_ROWS 4 +#define CV_HAL_DFT_COMPLEX_OUTPUT 16 +#define CV_HAL_DFT_REAL_OUTPUT 32 +#define CV_HAL_DFT_TWO_STAGE 64 +#define CV_HAL_DFT_STAGE_COLS 128 +#define CV_HAL_DFT_IS_CONTINUOUS 512 +#define CV_HAL_DFT_IS_INPLACE 1024 +//! @} + +//! @name SVD flags +//! @{ +#define CV_HAL_SVD_NO_UV 1 +#define CV_HAL_SVD_SHORT_UV 2 +#define CV_HAL_SVD_MODIFY_A 4 +#define CV_HAL_SVD_FULL_UV 8 +//! @} + +//! @name Gemm flags +//! @{ +#define CV_HAL_GEMM_1_T 1 +#define CV_HAL_GEMM_2_T 2 +#define CV_HAL_GEMM_3_T 4 +//! @} + +//! @} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp index afb74dc953..781bd045a5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin.hpp @@ -1,988 +1,988 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HAL_INTRIN_HPP -#define OPENCV_HAL_INTRIN_HPP - -#include -#include -#include -#include "opencv2/core/cvdef.h" - -#if defined(__GNUC__) && __GNUC__ == 12 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wuninitialized" -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif - -#define OPENCV_HAL_ADD(a, b) ((a) + (b)) -#define OPENCV_HAL_AND(a, b) ((a) & (b)) -#define OPENCV_HAL_NOP(a) (a) -#define OPENCV_HAL_1ST(a, b) (a) - -namespace { -inline unsigned int trailingZeros32(unsigned int value) { -#if defined(_MSC_VER) -#if (_MSC_VER < 1700) || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) - unsigned long index = 0; - _BitScanForward(&index, value); - return (unsigned int)index; -#elif defined(__clang__) - // clang-cl doesn't export _tzcnt_u32 for non BMI systems - return value ? __builtin_ctz(value) : 32; -#else - return _tzcnt_u32(value); -#endif -#elif defined(__GNUC__) || defined(__GNUG__) - return __builtin_ctz(value); -#elif defined(__ICC) || defined(__INTEL_COMPILER) - return _bit_scan_forward(value); -#elif defined(__clang__) - return llvm.cttz.i32(value, true); -#else - static const int MultiplyDeBruijnBitPosition[32] = { - 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, - 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; - return MultiplyDeBruijnBitPosition[((uint32_t)((value & -value) * 0x077CB531U)) >> 27]; -#endif -} -} - -// unlike HAL API, which is in cv::hal, -// we put intrinsics into cv namespace to make its -// access from within opencv code more accessible -namespace cv { - -namespace hal { - -enum StoreMode -{ - STORE_UNALIGNED = 0, - STORE_ALIGNED = 1, - STORE_ALIGNED_NOCACHE = 2 -}; - -} - -// TODO FIXIT: Don't use "God" traits. Split on separate cases. -template struct V_TypeTraits -{ -}; - -#define CV_INTRIN_DEF_TYPE_TRAITS(type, int_type_, uint_type_, abs_type_, w_type_, q_type_, sum_type_) \ - template<> struct V_TypeTraits \ - { \ - typedef type value_type; \ - typedef int_type_ int_type; \ - typedef abs_type_ abs_type; \ - typedef uint_type_ uint_type; \ - typedef w_type_ w_type; \ - typedef q_type_ q_type; \ - typedef sum_type_ sum_type; \ - \ - static inline int_type reinterpret_int(type x) \ - { \ - union { type l; int_type i; } v; \ - v.l = x; \ - return v.i; \ - } \ - \ - static inline type reinterpret_from_int(int_type x) \ - { \ - union { type l; int_type i; } v; \ - v.i = x; \ - return v.l; \ - } \ - } - -#define CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(type, int_type_, uint_type_, abs_type_, w_type_, sum_type_) \ - template<> struct V_TypeTraits \ - { \ - typedef type value_type; \ - typedef int_type_ int_type; \ - typedef abs_type_ abs_type; \ - typedef uint_type_ uint_type; \ - typedef w_type_ w_type; \ - typedef sum_type_ sum_type; \ - \ - static inline int_type reinterpret_int(type x) \ - { \ - union { type l; int_type i; } v; \ - v.l = x; \ - return v.i; \ - } \ - \ - static inline type reinterpret_from_int(int_type x) \ - { \ - union { type l; int_type i; } v; \ - v.i = x; \ - return v.l; \ - } \ - } - -CV_INTRIN_DEF_TYPE_TRAITS(uchar, schar, uchar, uchar, ushort, unsigned, unsigned); -CV_INTRIN_DEF_TYPE_TRAITS(schar, schar, uchar, uchar, short, int, int); -CV_INTRIN_DEF_TYPE_TRAITS(ushort, short, ushort, ushort, unsigned, uint64, unsigned); -CV_INTRIN_DEF_TYPE_TRAITS(short, short, ushort, ushort, int, int64, int); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(unsigned, int, unsigned, unsigned, uint64, unsigned); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int, int, unsigned, unsigned, int64, int); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(float, int, unsigned, float, double, float); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(uint64, int64, uint64, uint64, void, uint64); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int64, int64, uint64, uint64, void, int64); -CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(double, int64, uint64, double, void, double); - -#ifndef CV_DOXYGEN - -#ifndef CV_CPU_OPTIMIZATION_HAL_NAMESPACE -#ifdef CV_FORCE_SIMD128_CPP - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_EMULATOR_CPP - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_EMULATOR_CPP { - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } -#elif defined(CV_CPU_DISPATCH_MODE) - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) { - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } -#else - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_baseline - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_baseline { - #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } -#endif -#endif // CV_CPU_OPTIMIZATION_HAL_NAMESPACE - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -template inline _VecTp v_setzero_(); -template inline _VecTp v_setall_(uchar); -template inline _VecTp v_setall_(schar); -template inline _VecTp v_setall_(ushort); -template inline _VecTp v_setall_(short); -template inline _VecTp v_setall_(unsigned); -template inline _VecTp v_setall_(int); -template inline _VecTp v_setall_(uint64); -template inline _VecTp v_setall_(int64); -template inline _VecTp v_setall_(float); -template inline _VecTp v_setall_(double); - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END -using namespace CV_CPU_OPTIMIZATION_HAL_NAMESPACE; -#endif -} - -#ifdef CV_DOXYGEN -# undef CV_AVX2 -# undef CV_SSE2 -# undef CV_NEON -# undef CV_VSX -# undef CV_FP16 -# undef CV_MSA -# undef CV_RVV -#endif - -#if (CV_SSE2 || CV_NEON || CV_VSX || CV_MSA || CV_WASM_SIMD || CV_RVV071 || CV_LSX) && !defined(CV_FORCE_SIMD128_CPP) -#define CV__SIMD_FORWARD 128 -#include "opencv2/core/hal/intrin_forward.hpp" -#endif - -#if CV_SSE2 && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_sse_em.hpp" -#include "opencv2/core/hal/intrin_sse.hpp" - -#elif CV_NEON && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_neon.hpp" - -#elif CV_RVV071 && !defined(CV_FORCE_SIMD128_CPP) -#define CV_SIMD128_CPP 0 -#include "opencv2/core/hal/intrin_rvv071.hpp" - -#elif CV_VSX && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_vsx.hpp" - -#elif CV_MSA && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_msa.hpp" - -#elif CV_WASM_SIMD && !defined(CV_FORCE_SIMD128_CPP) -#include "opencv2/core/hal/intrin_wasm.hpp" - -#elif CV_RVV && !defined(CV_FORCE_SIMD128_CPP) -#include "opencv2/core/hal/intrin_rvv_scalable.hpp" - -#elif CV_LSX && !defined(CV_FORCE_SIMD128_CPP) - -#include "opencv2/core/hal/intrin_lsx.hpp" - -#else - -#include "opencv2/core/hal/intrin_cpp.hpp" - -#endif - -// AVX2 can be used together with SSE2, so -// we define those two sets of intrinsics at once. -// Most of the intrinsics do not conflict (the proper overloaded variant is -// resolved by the argument types, e.g. v_float32x4 ~ SSE2, v_float32x8 ~ AVX2), -// but some of AVX2 intrinsics get v256_ prefix instead of v_, e.g. v256_load() vs v_load(). -// Correspondingly, the wide intrinsics (which are mapped to the "widest" -// available instruction set) will get vx_ prefix -// (and will be mapped to v256_ counterparts) (e.g. vx_load() => v256_load()) -#if CV_AVX2 - -#define CV__SIMD_FORWARD 256 -#include "opencv2/core/hal/intrin_forward.hpp" -#include "opencv2/core/hal/intrin_avx.hpp" - -#endif - -// AVX512 can be used together with SSE2 and AVX2, so -// we define those sets of intrinsics at once. -// For some of AVX512 intrinsics get v512_ prefix instead of v_, e.g. v512_load() vs v_load(). -// Wide intrinsics will be mapped to v512_ counterparts in this case(e.g. vx_load() => v512_load()) -#if CV_AVX512_SKX - -#define CV__SIMD_FORWARD 512 -#include "opencv2/core/hal/intrin_forward.hpp" -#include "opencv2/core/hal/intrin_avx512.hpp" - -#endif - -#if CV_LASX - -#define CV__SIMD_FORWARD 256 -#include "opencv2/core/hal/intrin_forward.hpp" -#include "opencv2/core/hal/intrin_lasx.hpp" - -#endif - -//! @cond IGNORED - -namespace cv { - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN -#endif - -#ifndef CV_SIMD128 -#define CV_SIMD128 0 -#endif - -#ifndef CV_SIMD128_CPP -#define CV_SIMD128_CPP 0 -#endif - -#ifndef CV_SIMD128_64F -#define CV_SIMD128_64F 0 -#endif - -#ifndef CV_SIMD256 -#define CV_SIMD256 0 -#endif - -#ifndef CV_SIMD256_64F -#define CV_SIMD256_64F 0 -#endif - -#ifndef CV_SIMD512 -#define CV_SIMD512 0 -#endif - -#ifndef CV_SIMD512_64F -#define CV_SIMD512_64F 0 -#endif - -#ifndef CV_SIMD128_FP16 -#define CV_SIMD128_FP16 0 -#endif - -#ifndef CV_SIMD256_FP16 -#define CV_SIMD256_FP16 0 -#endif - -#ifndef CV_SIMD512_FP16 -#define CV_SIMD512_FP16 0 -#endif - -#ifndef CV_SIMD_SCALABLE -#define CV_SIMD_SCALABLE 0 -#endif - -#ifndef CV_SIMD_SCALABLE_64F -#define CV_SIMD_SCALABLE_64F 0 -#endif - -//================================================================================================== - -template struct V_RegTraits -{ -}; - -#define CV_DEF_REG_TRAITS(prefix, _reg, lane_type, suffix, _u_reg, _w_reg, _q_reg, _int_reg, _round_reg) \ - template<> struct V_RegTraits<_reg> \ - { \ - typedef _reg reg; \ - typedef _u_reg u_reg; \ - typedef _w_reg w_reg; \ - typedef _q_reg q_reg; \ - typedef _int_reg int_reg; \ - typedef _round_reg round_reg; \ - } - -#if CV_SIMD128 || CV_SIMD128_CPP - CV_DEF_REG_TRAITS(v, v_uint8x16, uchar, u8, v_uint8x16, v_uint16x8, v_uint32x4, v_int8x16, void); - CV_DEF_REG_TRAITS(v, v_int8x16, schar, s8, v_uint8x16, v_int16x8, v_int32x4, v_int8x16, void); - CV_DEF_REG_TRAITS(v, v_uint16x8, ushort, u16, v_uint16x8, v_uint32x4, v_uint64x2, v_int16x8, void); - CV_DEF_REG_TRAITS(v, v_int16x8, short, s16, v_uint16x8, v_int32x4, v_int64x2, v_int16x8, void); - CV_DEF_REG_TRAITS(v, v_uint32x4, unsigned, u32, v_uint32x4, v_uint64x2, void, v_int32x4, void); - CV_DEF_REG_TRAITS(v, v_int32x4, int, s32, v_uint32x4, v_int64x2, void, v_int32x4, void); -#if CV_SIMD128_64F || CV_SIMD128_CPP - CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, v_float64x2, void, v_int32x4, v_int32x4); -#else - CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, void, void, v_int32x4, v_int32x4); -#endif - CV_DEF_REG_TRAITS(v, v_uint64x2, uint64, u64, v_uint64x2, void, void, v_int64x2, void); - CV_DEF_REG_TRAITS(v, v_int64x2, int64, s64, v_uint64x2, void, void, v_int64x2, void); -#if CV_SIMD128_64F - CV_DEF_REG_TRAITS(v, v_float64x2, double, f64, v_float64x2, void, void, v_int64x2, v_int32x4); -#endif -#endif - -#if CV_SIMD256 - CV_DEF_REG_TRAITS(v256, v_uint8x32, uchar, u8, v_uint8x32, v_uint16x16, v_uint32x8, v_int8x32, void); - CV_DEF_REG_TRAITS(v256, v_int8x32, schar, s8, v_uint8x32, v_int16x16, v_int32x8, v_int8x32, void); - CV_DEF_REG_TRAITS(v256, v_uint16x16, ushort, u16, v_uint16x16, v_uint32x8, v_uint64x4, v_int16x16, void); - CV_DEF_REG_TRAITS(v256, v_int16x16, short, s16, v_uint16x16, v_int32x8, v_int64x4, v_int16x16, void); - CV_DEF_REG_TRAITS(v256, v_uint32x8, unsigned, u32, v_uint32x8, v_uint64x4, void, v_int32x8, void); - CV_DEF_REG_TRAITS(v256, v_int32x8, int, s32, v_uint32x8, v_int64x4, void, v_int32x8, void); - CV_DEF_REG_TRAITS(v256, v_float32x8, float, f32, v_float32x8, v_float64x4, void, v_int32x8, v_int32x8); - CV_DEF_REG_TRAITS(v256, v_uint64x4, uint64, u64, v_uint64x4, void, void, v_int64x4, void); - CV_DEF_REG_TRAITS(v256, v_int64x4, int64, s64, v_uint64x4, void, void, v_int64x4, void); - CV_DEF_REG_TRAITS(v256, v_float64x4, double, f64, v_float64x4, void, void, v_int64x4, v_int32x8); -#endif - -#if CV_SIMD512 - CV_DEF_REG_TRAITS(v512, v_uint8x64, uchar, u8, v_uint8x64, v_uint16x32, v_uint32x16, v_int8x64, void); - CV_DEF_REG_TRAITS(v512, v_int8x64, schar, s8, v_uint8x64, v_int16x32, v_int32x16, v_int8x64, void); - CV_DEF_REG_TRAITS(v512, v_uint16x32, ushort, u16, v_uint16x32, v_uint32x16, v_uint64x8, v_int16x32, void); - CV_DEF_REG_TRAITS(v512, v_int16x32, short, s16, v_uint16x32, v_int32x16, v_int64x8, v_int16x32, void); - CV_DEF_REG_TRAITS(v512, v_uint32x16, unsigned, u32, v_uint32x16, v_uint64x8, void, v_int32x16, void); - CV_DEF_REG_TRAITS(v512, v_int32x16, int, s32, v_uint32x16, v_int64x8, void, v_int32x16, void); - CV_DEF_REG_TRAITS(v512, v_float32x16, float, f32, v_float32x16, v_float64x8, void, v_int32x16, v_int32x16); - CV_DEF_REG_TRAITS(v512, v_uint64x8, uint64, u64, v_uint64x8, void, void, v_int64x8, void); - CV_DEF_REG_TRAITS(v512, v_int64x8, int64, s64, v_uint64x8, void, void, v_int64x8, void); - CV_DEF_REG_TRAITS(v512, v_float64x8, double, f64, v_float64x8, void, void, v_int64x8, v_int32x16); -#endif -#if CV_SIMD_SCALABLE - CV_DEF_REG_TRAITS(v, v_uint8, uchar, u8, v_uint8, v_uint16, v_uint32, v_int8, void); - CV_DEF_REG_TRAITS(v, v_int8, schar, s8, v_uint8, v_int16, v_int32, v_int8, void); - CV_DEF_REG_TRAITS(v, v_uint16, ushort, u16, v_uint16, v_uint32, v_uint64, v_int16, void); - CV_DEF_REG_TRAITS(v, v_int16, short, s16, v_uint16, v_int32, v_int64, v_int16, void); - CV_DEF_REG_TRAITS(v, v_uint32, unsigned, u32, v_uint32, v_uint64, void, v_int32, void); - CV_DEF_REG_TRAITS(v, v_int32, int, s32, v_uint32, v_int64, void, v_int32, void); - CV_DEF_REG_TRAITS(v, v_float32, float, f32, v_float32, v_float64, void, v_int32, v_int32); - CV_DEF_REG_TRAITS(v, v_uint64, uint64, u64, v_uint64, void, void, v_int64, void); - CV_DEF_REG_TRAITS(v, v_int64, int64, s64, v_uint64, void, void, v_int64, void); - CV_DEF_REG_TRAITS(v, v_float64, double, f64, v_float64, void, void, v_int64, v_int32); -#endif -//! @endcond - -#if CV_SIMD512 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 512) -#define CV__SIMD_NAMESPACE simd512 -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD 1 - #define CV_SIMD_64F CV_SIMD512_64F - #define CV_SIMD_FP16 CV_SIMD512_FP16 - #define CV_SIMD_WIDTH 64 -//! @addtogroup core_hal_intrin -//! @{ - //! @brief Maximum available vector register capacity 8-bit unsigned integer values - typedef v_uint8x64 v_uint8; - //! @brief Maximum available vector register capacity 8-bit signed integer values - typedef v_int8x64 v_int8; - //! @brief Maximum available vector register capacity 16-bit unsigned integer values - typedef v_uint16x32 v_uint16; - //! @brief Maximum available vector register capacity 16-bit signed integer values - typedef v_int16x32 v_int16; - //! @brief Maximum available vector register capacity 32-bit unsigned integer values - typedef v_uint32x16 v_uint32; - //! @brief Maximum available vector register capacity 32-bit signed integer values - typedef v_int32x16 v_int32; - //! @brief Maximum available vector register capacity 64-bit unsigned integer values - typedef v_uint64x8 v_uint64; - //! @brief Maximum available vector register capacity 64-bit signed integer values - typedef v_int64x8 v_int64; - //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) - typedef v_float32x16 v_float32; - #if CV_SIMD512_64F - //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) - typedef v_float64x8 v_float64; - #endif -//! @} - - #define VXPREFIX(func) v512##func -} // namespace -using namespace CV__SIMD_NAMESPACE; -#elif CV_SIMD256 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 256) -#define CV__SIMD_NAMESPACE simd256 -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD 1 - #define CV_SIMD_64F CV_SIMD256_64F - #define CV_SIMD_FP16 CV_SIMD256_FP16 - #define CV_SIMD_WIDTH 32 -//! @addtogroup core_hal_intrin -//! @{ - //! @brief Maximum available vector register capacity 8-bit unsigned integer values - typedef v_uint8x32 v_uint8; - //! @brief Maximum available vector register capacity 8-bit signed integer values - typedef v_int8x32 v_int8; - //! @brief Maximum available vector register capacity 16-bit unsigned integer values - typedef v_uint16x16 v_uint16; - //! @brief Maximum available vector register capacity 16-bit signed integer values - typedef v_int16x16 v_int16; - //! @brief Maximum available vector register capacity 32-bit unsigned integer values - typedef v_uint32x8 v_uint32; - //! @brief Maximum available vector register capacity 32-bit signed integer values - typedef v_int32x8 v_int32; - //! @brief Maximum available vector register capacity 64-bit unsigned integer values - typedef v_uint64x4 v_uint64; - //! @brief Maximum available vector register capacity 64-bit signed integer values - typedef v_int64x4 v_int64; - //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) - typedef v_float32x8 v_float32; - #if CV_SIMD256_64F - //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) - typedef v_float64x4 v_float64; - #endif -//! @} - - #define VXPREFIX(func) v256##func -} // namespace -using namespace CV__SIMD_NAMESPACE; -#elif (CV_SIMD128 || CV_SIMD128_CPP) && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 128) -#if defined CV_SIMD128_CPP -#define CV__SIMD_NAMESPACE simd128_cpp -#else -#define CV__SIMD_NAMESPACE simd128 -#endif -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD CV_SIMD128 - #define CV_SIMD_64F CV_SIMD128_64F - #define CV_SIMD_WIDTH 16 -//! @addtogroup core_hal_intrin -//! @{ - //! @brief Maximum available vector register capacity 8-bit unsigned integer values - typedef v_uint8x16 v_uint8; - //! @brief Maximum available vector register capacity 8-bit signed integer values - typedef v_int8x16 v_int8; - //! @brief Maximum available vector register capacity 16-bit unsigned integer values - typedef v_uint16x8 v_uint16; - //! @brief Maximum available vector register capacity 16-bit signed integer values - typedef v_int16x8 v_int16; - //! @brief Maximum available vector register capacity 32-bit unsigned integer values - typedef v_uint32x4 v_uint32; - //! @brief Maximum available vector register capacity 32-bit signed integer values - typedef v_int32x4 v_int32; - //! @brief Maximum available vector register capacity 64-bit unsigned integer values - typedef v_uint64x2 v_uint64; - //! @brief Maximum available vector register capacity 64-bit signed integer values - typedef v_int64x2 v_int64; - //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) - typedef v_float32x4 v_float32; - #if CV_SIMD128_64F - //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) - typedef v_float64x2 v_float64; - #endif -//! @} - - #define VXPREFIX(func) v##func -} // namespace -using namespace CV__SIMD_NAMESPACE; - -#elif CV_SIMD_SCALABLE -#define CV__SIMD_NAMESPACE simd -namespace CV__SIMD_NAMESPACE { - #define CV_SIMD 0 - #define CV_SIMD_WIDTH 128 /* 1024/8 */ - - #define VXPREFIX(func) v##func -} // namespace -using namespace CV__SIMD_NAMESPACE; - -#endif - -//! @cond IGNORED -#ifndef CV_SIMD_64F -#define CV_SIMD_64F 0 -#endif - -namespace CV__SIMD_NAMESPACE { -//! @addtogroup core_hal_intrin -//! @{ - //! @name Wide init with value - //! @{ - //! @brief Create maximum available capacity vector with elements set to a specific value - inline v_uint8 vx_setall_u8(uchar v) { return VXPREFIX(_setall_u8)(v); } - inline v_int8 vx_setall_s8(schar v) { return VXPREFIX(_setall_s8)(v); } - inline v_uint16 vx_setall_u16(ushort v) { return VXPREFIX(_setall_u16)(v); } - inline v_int16 vx_setall_s16(short v) { return VXPREFIX(_setall_s16)(v); } - inline v_int32 vx_setall_s32(int v) { return VXPREFIX(_setall_s32)(v); } - inline v_uint32 vx_setall_u32(unsigned v) { return VXPREFIX(_setall_u32)(v); } - inline v_float32 vx_setall_f32(float v) { return VXPREFIX(_setall_f32)(v); } - inline v_int64 vx_setall_s64(int64 v) { return VXPREFIX(_setall_s64)(v); } - inline v_uint64 vx_setall_u64(uint64 v) { return VXPREFIX(_setall_u64)(v); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_setall_f64(double v) { return VXPREFIX(_setall_f64)(v); } -#endif - //! @} - - //! @name Wide init with zero - //! @{ - //! @brief Create maximum available capacity vector with elements set to zero - inline v_uint8 vx_setzero_u8() { return VXPREFIX(_setzero_u8)(); } - inline v_int8 vx_setzero_s8() { return VXPREFIX(_setzero_s8)(); } - inline v_uint16 vx_setzero_u16() { return VXPREFIX(_setzero_u16)(); } - inline v_int16 vx_setzero_s16() { return VXPREFIX(_setzero_s16)(); } - inline v_int32 vx_setzero_s32() { return VXPREFIX(_setzero_s32)(); } - inline v_uint32 vx_setzero_u32() { return VXPREFIX(_setzero_u32)(); } - inline v_float32 vx_setzero_f32() { return VXPREFIX(_setzero_f32)(); } - inline v_int64 vx_setzero_s64() { return VXPREFIX(_setzero_s64)(); } - inline v_uint64 vx_setzero_u64() { return VXPREFIX(_setzero_u64)(); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_setzero_f64() { return VXPREFIX(_setzero_f64)(); } -#endif - //! @} - - //! @name Wide load from memory - //! @{ - //! @brief Load maximum available capacity register contents from memory - inline v_uint8 vx_load(const uchar * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int8 vx_load(const schar * ptr) { return VXPREFIX(_load)(ptr); } - inline v_uint16 vx_load(const ushort * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int16 vx_load(const short * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int32 vx_load(const int * ptr) { return VXPREFIX(_load)(ptr); } - inline v_uint32 vx_load(const unsigned * ptr) { return VXPREFIX(_load)(ptr); } - inline v_float32 vx_load(const float * ptr) { return VXPREFIX(_load)(ptr); } - inline v_int64 vx_load(const int64 * ptr) { return VXPREFIX(_load)(ptr); } - inline v_uint64 vx_load(const uint64 * ptr) { return VXPREFIX(_load)(ptr); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load(const double * ptr) { return VXPREFIX(_load)(ptr); } -#endif - //! @} - - //! @name Wide load from memory(aligned) - //! @{ - //! @brief Load maximum available capacity register contents from memory(aligned) - inline v_uint8 vx_load_aligned(const uchar * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int8 vx_load_aligned(const schar * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_uint16 vx_load_aligned(const ushort * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int16 vx_load_aligned(const short * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int32 vx_load_aligned(const int * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_uint32 vx_load_aligned(const unsigned * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_float32 vx_load_aligned(const float * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_int64 vx_load_aligned(const int64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } - inline v_uint64 vx_load_aligned(const uint64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load_aligned(const double * ptr) { return VXPREFIX(_load_aligned)(ptr); } -#endif - //! @} - - //! @name Wide load lower half from memory - //! @{ - //! @brief Load lower half of maximum available capacity register from memory - inline v_uint8 vx_load_low(const uchar * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int8 vx_load_low(const schar * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_uint16 vx_load_low(const ushort * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int16 vx_load_low(const short * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int32 vx_load_low(const int * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_uint32 vx_load_low(const unsigned * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_float32 vx_load_low(const float * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_int64 vx_load_low(const int64 * ptr) { return VXPREFIX(_load_low)(ptr); } - inline v_uint64 vx_load_low(const uint64 * ptr) { return VXPREFIX(_load_low)(ptr); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load_low(const double * ptr) { return VXPREFIX(_load_low)(ptr); } -#endif - //! @} - - //! @name Wide load halfs from memory - //! @{ - //! @brief Load maximum available capacity register contents from two memory blocks - inline v_uint8 vx_load_halves(const uchar * ptr0, const uchar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int8 vx_load_halves(const schar * ptr0, const schar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_uint16 vx_load_halves(const ushort * ptr0, const ushort * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int16 vx_load_halves(const short * ptr0, const short * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int32 vx_load_halves(const int * ptr0, const int * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_uint32 vx_load_halves(const unsigned * ptr0, const unsigned * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_float32 vx_load_halves(const float * ptr0, const float * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_int64 vx_load_halves(const int64 * ptr0, const int64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } - inline v_uint64 vx_load_halves(const uint64 * ptr0, const uint64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_load_halves(const double * ptr0, const double * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } -#endif - //! @} - - //! @name Wide LUT of elements - //! @{ - //! @brief Load maximum available capacity register contents with array elements by provided indexes - inline v_uint8 vx_lut(const uchar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int8 vx_lut(const schar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_uint16 vx_lut(const ushort * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int16 vx_lut(const short* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int32 vx_lut(const int* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_uint32 vx_lut(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_float32 vx_lut(const float* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_int64 vx_lut(const int64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } - inline v_uint64 vx_lut(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_lut(const double* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } -#endif - //! @} - - //! @name Wide LUT of element pairs - //! @{ - //! @brief Load maximum available capacity register contents with array element pairs by provided indexes - inline v_uint8 vx_lut_pairs(const uchar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int8 vx_lut_pairs(const schar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_uint16 vx_lut_pairs(const ushort * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int16 vx_lut_pairs(const short* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int32 vx_lut_pairs(const int* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_uint32 vx_lut_pairs(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_float32 vx_lut_pairs(const float* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_int64 vx_lut_pairs(const int64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } - inline v_uint64 vx_lut_pairs(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } -#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F - inline v_float64 vx_lut_pairs(const double* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } -#endif - //! @} - - //! @name Wide LUT of element quads - //! @{ - //! @brief Load maximum available capacity register contents with array element quads by provided indexes - inline v_uint8 vx_lut_quads(const uchar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_int8 vx_lut_quads(const schar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_uint16 vx_lut_quads(const ushort* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_int16 vx_lut_quads(const short* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_int32 vx_lut_quads(const int* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_uint32 vx_lut_quads(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - inline v_float32 vx_lut_quads(const float* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } - //! @} - - //! @name Wide load with double expansion - //! @{ - //! @brief Load maximum available capacity register contents from memory with double expand - inline v_uint16 vx_load_expand(const uchar * ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_int16 vx_load_expand(const schar * ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_uint32 vx_load_expand(const ushort * ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_int32 vx_load_expand(const short* ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_int64 vx_load_expand(const int* ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_uint64 vx_load_expand(const unsigned* ptr) { return VXPREFIX(_load_expand)(ptr); } - inline v_float32 vx_load_expand(const hfloat * ptr) { return VXPREFIX(_load_expand)(ptr); } - //! @} - - //! @name Wide load with quad expansion - //! @{ - //! @brief Load maximum available capacity register contents from memory with quad expand - inline v_uint32 vx_load_expand_q(const uchar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } - inline v_int32 vx_load_expand_q(const schar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } - //! @} - - /** @brief SIMD processing state cleanup call */ - inline void vx_cleanup() { VXPREFIX(_cleanup)(); } - -#if !CV_SIMD_SCALABLE - // Compatibility layer -#if !(CV_NEON && !defined(CV_FORCE_SIMD128_CPP)) - template struct VTraits { - static inline int vlanes() { return T::nlanes; } - enum { nlanes = T::nlanes, max_nlanes = T::nlanes }; - using lane_type = typename T::lane_type; - }; - - //////////// get0 //////////// - #define OPENCV_HAL_WRAP_GRT0(_Tpvec) \ - inline typename VTraits<_Tpvec>::lane_type v_get0(const _Tpvec& v) \ - { \ - return v.get0(); \ - } - - OPENCV_HAL_WRAP_GRT0(v_uint8) - OPENCV_HAL_WRAP_GRT0(v_int8) - OPENCV_HAL_WRAP_GRT0(v_uint16) - OPENCV_HAL_WRAP_GRT0(v_int16) - OPENCV_HAL_WRAP_GRT0(v_uint32) - OPENCV_HAL_WRAP_GRT0(v_int32) - OPENCV_HAL_WRAP_GRT0(v_uint64) - OPENCV_HAL_WRAP_GRT0(v_int64) - OPENCV_HAL_WRAP_GRT0(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_GRT0(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_GRT0(v_uint8x16) - OPENCV_HAL_WRAP_GRT0(v_uint16x8) - OPENCV_HAL_WRAP_GRT0(v_uint32x4) - OPENCV_HAL_WRAP_GRT0(v_uint64x2) - OPENCV_HAL_WRAP_GRT0(v_int8x16) - OPENCV_HAL_WRAP_GRT0(v_int16x8) - OPENCV_HAL_WRAP_GRT0(v_int32x4) - OPENCV_HAL_WRAP_GRT0(v_int64x2) - OPENCV_HAL_WRAP_GRT0(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_GRT0(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_GRT0(v_uint8x32) - OPENCV_HAL_WRAP_GRT0(v_uint16x16) - OPENCV_HAL_WRAP_GRT0(v_uint32x8) - OPENCV_HAL_WRAP_GRT0(v_uint64x4) - OPENCV_HAL_WRAP_GRT0(v_int8x32) - OPENCV_HAL_WRAP_GRT0(v_int16x16) - OPENCV_HAL_WRAP_GRT0(v_int32x8) - OPENCV_HAL_WRAP_GRT0(v_int64x4) - OPENCV_HAL_WRAP_GRT0(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_GRT0(v_float64x4) - #endif - #endif -#endif - - #define OPENCV_HAL_WRAP_BIN_OP_ADDSUB(_Tpvec) \ - template \ - inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ - return v_add(v_add(f1, f2), f3, vf...); \ - } - - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - // when we use CV_SIMD128 with 256/512 bit SIMD (e.g. AVX2 or AVX512) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x2) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x2) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - // when we use CV_SIMD256 with 512 bit SIMD (e.g. AVX512) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x32) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x16) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x8) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x4) - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x4) - #endif - #endif - - #define OPENCV_HAL_WRAP_BIN_OP_MUL(_Tpvec) \ - template \ - inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ - return v_mul(v_mul(f1, f2), f3, vf...); \ - } - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x4) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x4) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x32) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x16) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x8) - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x4) - #endif - #endif - - #define OPENCV_HAL_WRAP_EXTRACT(_Tpvec) \ - inline typename VTraits<_Tpvec>::lane_type v_extract_highest(const _Tpvec& v) \ - { \ - return v_extract_n::nlanes-1>(v); \ - } - - OPENCV_HAL_WRAP_EXTRACT(v_uint8) - OPENCV_HAL_WRAP_EXTRACT(v_int8) - OPENCV_HAL_WRAP_EXTRACT(v_uint16) - OPENCV_HAL_WRAP_EXTRACT(v_int16) - OPENCV_HAL_WRAP_EXTRACT(v_uint32) - OPENCV_HAL_WRAP_EXTRACT(v_int32) - OPENCV_HAL_WRAP_EXTRACT(v_uint64) - OPENCV_HAL_WRAP_EXTRACT(v_int64) - OPENCV_HAL_WRAP_EXTRACT(v_float32) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_EXTRACT(v_float64) - #endif - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_EXTRACT(v_uint8x16) - OPENCV_HAL_WRAP_EXTRACT(v_uint16x8) - OPENCV_HAL_WRAP_EXTRACT(v_uint32x4) - OPENCV_HAL_WRAP_EXTRACT(v_uint64x2) - OPENCV_HAL_WRAP_EXTRACT(v_int8x16) - OPENCV_HAL_WRAP_EXTRACT(v_int16x8) - OPENCV_HAL_WRAP_EXTRACT(v_int32x4) - OPENCV_HAL_WRAP_EXTRACT(v_int64x2) - OPENCV_HAL_WRAP_EXTRACT(v_float32x4) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_EXTRACT(v_float64x2) - #endif - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_EXTRACT(v_uint8x32) - OPENCV_HAL_WRAP_EXTRACT(v_uint16x16) - OPENCV_HAL_WRAP_EXTRACT(v_uint32x8) - OPENCV_HAL_WRAP_EXTRACT(v_uint64x4) - OPENCV_HAL_WRAP_EXTRACT(v_int8x32) - OPENCV_HAL_WRAP_EXTRACT(v_int16x16) - OPENCV_HAL_WRAP_EXTRACT(v_int32x8) - OPENCV_HAL_WRAP_EXTRACT(v_int64x4) - OPENCV_HAL_WRAP_EXTRACT(v_float32x8) - #if CV_SIMD_64F - OPENCV_HAL_WRAP_EXTRACT(v_float64x4) - #endif - #endif - - #define OPENCV_HAL_WRAP_BROADCAST(_Tpvec) \ - inline _Tpvec v_broadcast_highest(const _Tpvec& v) \ - { \ - return v_broadcast_element::nlanes-1>(v); \ - } - - OPENCV_HAL_WRAP_BROADCAST(v_uint32) - OPENCV_HAL_WRAP_BROADCAST(v_int32) - OPENCV_HAL_WRAP_BROADCAST(v_float32) - #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 - OPENCV_HAL_WRAP_BROADCAST(v_uint32x4) - OPENCV_HAL_WRAP_BROADCAST(v_int32x4) - OPENCV_HAL_WRAP_BROADCAST(v_float32x4) - #endif - #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 - OPENCV_HAL_WRAP_BROADCAST(v_uint32x8) - OPENCV_HAL_WRAP_BROADCAST(v_int32x8) - OPENCV_HAL_WRAP_BROADCAST(v_float32x8) - #endif - -#endif //!CV_SIMD_SCALABLE - -//! @cond IGNORED - - // backward compatibility - template static inline - void vx_store(_Tp* dst, const _Tvec& v) { return v_store(dst, v); } - // backward compatibility - template static inline - void vx_store_aligned(_Tp* dst, const _Tvec& v) { return v_store_aligned(dst, v); } - -//! @endcond - - -//! @} - #undef VXPREFIX -} // namespace - - -#ifndef CV_SIMD_FP16 -#define CV_SIMD_FP16 0 //!< Defined to 1 on native support of operations with float16x8_t / float16x16_t (SIMD256) types -#endif - -#ifndef CV_SIMD -#define CV_SIMD 0 -#endif - -#include "simd_utils.impl.hpp" - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END -#endif - -} // cv:: - -//! @endcond - -#if defined(__GNUC__) && __GNUC__ == 12 -#pragma GCC diagnostic pop -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HAL_INTRIN_HPP +#define OPENCV_HAL_INTRIN_HPP + +#include +#include +#include +#include "opencv2/core/cvdef.h" + +#if defined(__GNUC__) && __GNUC__ == 12 +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wuninitialized" +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif + +#define OPENCV_HAL_ADD(a, b) ((a) + (b)) +#define OPENCV_HAL_AND(a, b) ((a) & (b)) +#define OPENCV_HAL_NOP(a) (a) +#define OPENCV_HAL_1ST(a, b) (a) + +namespace { +inline unsigned int trailingZeros32(unsigned int value) { +#if defined(_MSC_VER) +#if (_MSC_VER < 1700) || defined(_M_ARM) || defined(_M_ARM64) || defined(_M_ARM64EC) + unsigned long index = 0; + _BitScanForward(&index, value); + return (unsigned int)index; +#elif defined(__clang__) + // clang-cl doesn't export _tzcnt_u32 for non BMI systems + return value ? __builtin_ctz(value) : 32; +#else + return _tzcnt_u32(value); +#endif +#elif defined(__GNUC__) || defined(__GNUG__) + return __builtin_ctz(value); +#elif defined(__ICC) || defined(__INTEL_COMPILER) + return _bit_scan_forward(value); +#elif defined(__clang__) + return llvm.cttz.i32(value, true); +#else + static const int MultiplyDeBruijnBitPosition[32] = { + 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, + 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; + return MultiplyDeBruijnBitPosition[((uint32_t)((value & -value) * 0x077CB531U)) >> 27]; +#endif +} +} + +// unlike HAL API, which is in cv::hal, +// we put intrinsics into cv namespace to make its +// access from within opencv code more accessible +namespace cv { + +namespace hal { + +enum StoreMode +{ + STORE_UNALIGNED = 0, + STORE_ALIGNED = 1, + STORE_ALIGNED_NOCACHE = 2 +}; + +} + +// TODO FIXIT: Don't use "God" traits. Split on separate cases. +template struct V_TypeTraits +{ +}; + +#define CV_INTRIN_DEF_TYPE_TRAITS(type, int_type_, uint_type_, abs_type_, w_type_, q_type_, sum_type_) \ + template<> struct V_TypeTraits \ + { \ + typedef type value_type; \ + typedef int_type_ int_type; \ + typedef abs_type_ abs_type; \ + typedef uint_type_ uint_type; \ + typedef w_type_ w_type; \ + typedef q_type_ q_type; \ + typedef sum_type_ sum_type; \ + \ + static inline int_type reinterpret_int(type x) \ + { \ + union { type l; int_type i; } v; \ + v.l = x; \ + return v.i; \ + } \ + \ + static inline type reinterpret_from_int(int_type x) \ + { \ + union { type l; int_type i; } v; \ + v.i = x; \ + return v.l; \ + } \ + } + +#define CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(type, int_type_, uint_type_, abs_type_, w_type_, sum_type_) \ + template<> struct V_TypeTraits \ + { \ + typedef type value_type; \ + typedef int_type_ int_type; \ + typedef abs_type_ abs_type; \ + typedef uint_type_ uint_type; \ + typedef w_type_ w_type; \ + typedef sum_type_ sum_type; \ + \ + static inline int_type reinterpret_int(type x) \ + { \ + union { type l; int_type i; } v; \ + v.l = x; \ + return v.i; \ + } \ + \ + static inline type reinterpret_from_int(int_type x) \ + { \ + union { type l; int_type i; } v; \ + v.i = x; \ + return v.l; \ + } \ + } + +CV_INTRIN_DEF_TYPE_TRAITS(uchar, schar, uchar, uchar, ushort, unsigned, unsigned); +CV_INTRIN_DEF_TYPE_TRAITS(schar, schar, uchar, uchar, short, int, int); +CV_INTRIN_DEF_TYPE_TRAITS(ushort, short, ushort, ushort, unsigned, uint64, unsigned); +CV_INTRIN_DEF_TYPE_TRAITS(short, short, ushort, ushort, int, int64, int); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(unsigned, int, unsigned, unsigned, uint64, unsigned); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int, int, unsigned, unsigned, int64, int); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(float, int, unsigned, float, double, float); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(uint64, int64, uint64, uint64, void, uint64); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(int64, int64, uint64, uint64, void, int64); +CV_INTRIN_DEF_TYPE_TRAITS_NO_Q_TYPE(double, int64, uint64, double, void, double); + +#ifndef CV_DOXYGEN + +#ifndef CV_CPU_OPTIMIZATION_HAL_NAMESPACE +#ifdef CV_FORCE_SIMD128_CPP + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_EMULATOR_CPP + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_EMULATOR_CPP { + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } +#elif defined(CV_CPU_DISPATCH_MODE) + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace __CV_CAT(hal_, CV_CPU_DISPATCH_MODE) { + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } +#else + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE hal_baseline + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN namespace hal_baseline { + #define CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END } +#endif +#endif // CV_CPU_OPTIMIZATION_HAL_NAMESPACE + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +template inline _VecTp v_setzero_(); +template inline _VecTp v_setall_(uchar); +template inline _VecTp v_setall_(schar); +template inline _VecTp v_setall_(ushort); +template inline _VecTp v_setall_(short); +template inline _VecTp v_setall_(unsigned); +template inline _VecTp v_setall_(int); +template inline _VecTp v_setall_(uint64); +template inline _VecTp v_setall_(int64); +template inline _VecTp v_setall_(float); +template inline _VecTp v_setall_(double); + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END +using namespace CV_CPU_OPTIMIZATION_HAL_NAMESPACE; +#endif +} + +#ifdef CV_DOXYGEN +# undef CV_AVX2 +# undef CV_SSE2 +# undef CV_NEON +# undef CV_VSX +# undef CV_FP16 +# undef CV_MSA +# undef CV_RVV +#endif + +#if (CV_SSE2 || CV_NEON || CV_VSX || CV_MSA || CV_WASM_SIMD || CV_RVV071 || CV_LSX) && !defined(CV_FORCE_SIMD128_CPP) +#define CV__SIMD_FORWARD 128 +#include "opencv2/core/hal/intrin_forward.hpp" +#endif + +#if CV_SSE2 && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_sse_em.hpp" +#include "opencv2/core/hal/intrin_sse.hpp" + +#elif CV_NEON && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_neon.hpp" + +#elif CV_RVV071 && !defined(CV_FORCE_SIMD128_CPP) +#define CV_SIMD128_CPP 0 +#include "opencv2/core/hal/intrin_rvv071.hpp" + +#elif CV_VSX && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_vsx.hpp" + +#elif CV_MSA && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_msa.hpp" + +#elif CV_WASM_SIMD && !defined(CV_FORCE_SIMD128_CPP) +#include "opencv2/core/hal/intrin_wasm.hpp" + +#elif CV_RVV && !defined(CV_FORCE_SIMD128_CPP) +#include "opencv2/core/hal/intrin_rvv_scalable.hpp" + +#elif CV_LSX && !defined(CV_FORCE_SIMD128_CPP) + +#include "opencv2/core/hal/intrin_lsx.hpp" + +#else + +#include "opencv2/core/hal/intrin_cpp.hpp" + +#endif + +// AVX2 can be used together with SSE2, so +// we define those two sets of intrinsics at once. +// Most of the intrinsics do not conflict (the proper overloaded variant is +// resolved by the argument types, e.g. v_float32x4 ~ SSE2, v_float32x8 ~ AVX2), +// but some of AVX2 intrinsics get v256_ prefix instead of v_, e.g. v256_load() vs v_load(). +// Correspondingly, the wide intrinsics (which are mapped to the "widest" +// available instruction set) will get vx_ prefix +// (and will be mapped to v256_ counterparts) (e.g. vx_load() => v256_load()) +#if CV_AVX2 + +#define CV__SIMD_FORWARD 256 +#include "opencv2/core/hal/intrin_forward.hpp" +#include "opencv2/core/hal/intrin_avx.hpp" + +#endif + +// AVX512 can be used together with SSE2 and AVX2, so +// we define those sets of intrinsics at once. +// For some of AVX512 intrinsics get v512_ prefix instead of v_, e.g. v512_load() vs v_load(). +// Wide intrinsics will be mapped to v512_ counterparts in this case(e.g. vx_load() => v512_load()) +#if CV_AVX512_SKX + +#define CV__SIMD_FORWARD 512 +#include "opencv2/core/hal/intrin_forward.hpp" +#include "opencv2/core/hal/intrin_avx512.hpp" + +#endif + +#if CV_LASX + +#define CV__SIMD_FORWARD 256 +#include "opencv2/core/hal/intrin_forward.hpp" +#include "opencv2/core/hal/intrin_lasx.hpp" + +#endif + +//! @cond IGNORED + +namespace cv { + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN +#endif + +#ifndef CV_SIMD128 +#define CV_SIMD128 0 +#endif + +#ifndef CV_SIMD128_CPP +#define CV_SIMD128_CPP 0 +#endif + +#ifndef CV_SIMD128_64F +#define CV_SIMD128_64F 0 +#endif + +#ifndef CV_SIMD256 +#define CV_SIMD256 0 +#endif + +#ifndef CV_SIMD256_64F +#define CV_SIMD256_64F 0 +#endif + +#ifndef CV_SIMD512 +#define CV_SIMD512 0 +#endif + +#ifndef CV_SIMD512_64F +#define CV_SIMD512_64F 0 +#endif + +#ifndef CV_SIMD128_FP16 +#define CV_SIMD128_FP16 0 +#endif + +#ifndef CV_SIMD256_FP16 +#define CV_SIMD256_FP16 0 +#endif + +#ifndef CV_SIMD512_FP16 +#define CV_SIMD512_FP16 0 +#endif + +#ifndef CV_SIMD_SCALABLE +#define CV_SIMD_SCALABLE 0 +#endif + +#ifndef CV_SIMD_SCALABLE_64F +#define CV_SIMD_SCALABLE_64F 0 +#endif + +//================================================================================================== + +template struct V_RegTraits +{ +}; + +#define CV_DEF_REG_TRAITS(prefix, _reg, lane_type, suffix, _u_reg, _w_reg, _q_reg, _int_reg, _round_reg) \ + template<> struct V_RegTraits<_reg> \ + { \ + typedef _reg reg; \ + typedef _u_reg u_reg; \ + typedef _w_reg w_reg; \ + typedef _q_reg q_reg; \ + typedef _int_reg int_reg; \ + typedef _round_reg round_reg; \ + } + +#if CV_SIMD128 || CV_SIMD128_CPP + CV_DEF_REG_TRAITS(v, v_uint8x16, uchar, u8, v_uint8x16, v_uint16x8, v_uint32x4, v_int8x16, void); + CV_DEF_REG_TRAITS(v, v_int8x16, schar, s8, v_uint8x16, v_int16x8, v_int32x4, v_int8x16, void); + CV_DEF_REG_TRAITS(v, v_uint16x8, ushort, u16, v_uint16x8, v_uint32x4, v_uint64x2, v_int16x8, void); + CV_DEF_REG_TRAITS(v, v_int16x8, short, s16, v_uint16x8, v_int32x4, v_int64x2, v_int16x8, void); + CV_DEF_REG_TRAITS(v, v_uint32x4, unsigned, u32, v_uint32x4, v_uint64x2, void, v_int32x4, void); + CV_DEF_REG_TRAITS(v, v_int32x4, int, s32, v_uint32x4, v_int64x2, void, v_int32x4, void); +#if CV_SIMD128_64F || CV_SIMD128_CPP + CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, v_float64x2, void, v_int32x4, v_int32x4); +#else + CV_DEF_REG_TRAITS(v, v_float32x4, float, f32, v_float32x4, void, void, v_int32x4, v_int32x4); +#endif + CV_DEF_REG_TRAITS(v, v_uint64x2, uint64, u64, v_uint64x2, void, void, v_int64x2, void); + CV_DEF_REG_TRAITS(v, v_int64x2, int64, s64, v_uint64x2, void, void, v_int64x2, void); +#if CV_SIMD128_64F + CV_DEF_REG_TRAITS(v, v_float64x2, double, f64, v_float64x2, void, void, v_int64x2, v_int32x4); +#endif +#endif + +#if CV_SIMD256 + CV_DEF_REG_TRAITS(v256, v_uint8x32, uchar, u8, v_uint8x32, v_uint16x16, v_uint32x8, v_int8x32, void); + CV_DEF_REG_TRAITS(v256, v_int8x32, schar, s8, v_uint8x32, v_int16x16, v_int32x8, v_int8x32, void); + CV_DEF_REG_TRAITS(v256, v_uint16x16, ushort, u16, v_uint16x16, v_uint32x8, v_uint64x4, v_int16x16, void); + CV_DEF_REG_TRAITS(v256, v_int16x16, short, s16, v_uint16x16, v_int32x8, v_int64x4, v_int16x16, void); + CV_DEF_REG_TRAITS(v256, v_uint32x8, unsigned, u32, v_uint32x8, v_uint64x4, void, v_int32x8, void); + CV_DEF_REG_TRAITS(v256, v_int32x8, int, s32, v_uint32x8, v_int64x4, void, v_int32x8, void); + CV_DEF_REG_TRAITS(v256, v_float32x8, float, f32, v_float32x8, v_float64x4, void, v_int32x8, v_int32x8); + CV_DEF_REG_TRAITS(v256, v_uint64x4, uint64, u64, v_uint64x4, void, void, v_int64x4, void); + CV_DEF_REG_TRAITS(v256, v_int64x4, int64, s64, v_uint64x4, void, void, v_int64x4, void); + CV_DEF_REG_TRAITS(v256, v_float64x4, double, f64, v_float64x4, void, void, v_int64x4, v_int32x8); +#endif + +#if CV_SIMD512 + CV_DEF_REG_TRAITS(v512, v_uint8x64, uchar, u8, v_uint8x64, v_uint16x32, v_uint32x16, v_int8x64, void); + CV_DEF_REG_TRAITS(v512, v_int8x64, schar, s8, v_uint8x64, v_int16x32, v_int32x16, v_int8x64, void); + CV_DEF_REG_TRAITS(v512, v_uint16x32, ushort, u16, v_uint16x32, v_uint32x16, v_uint64x8, v_int16x32, void); + CV_DEF_REG_TRAITS(v512, v_int16x32, short, s16, v_uint16x32, v_int32x16, v_int64x8, v_int16x32, void); + CV_DEF_REG_TRAITS(v512, v_uint32x16, unsigned, u32, v_uint32x16, v_uint64x8, void, v_int32x16, void); + CV_DEF_REG_TRAITS(v512, v_int32x16, int, s32, v_uint32x16, v_int64x8, void, v_int32x16, void); + CV_DEF_REG_TRAITS(v512, v_float32x16, float, f32, v_float32x16, v_float64x8, void, v_int32x16, v_int32x16); + CV_DEF_REG_TRAITS(v512, v_uint64x8, uint64, u64, v_uint64x8, void, void, v_int64x8, void); + CV_DEF_REG_TRAITS(v512, v_int64x8, int64, s64, v_uint64x8, void, void, v_int64x8, void); + CV_DEF_REG_TRAITS(v512, v_float64x8, double, f64, v_float64x8, void, void, v_int64x8, v_int32x16); +#endif +#if CV_SIMD_SCALABLE + CV_DEF_REG_TRAITS(v, v_uint8, uchar, u8, v_uint8, v_uint16, v_uint32, v_int8, void); + CV_DEF_REG_TRAITS(v, v_int8, schar, s8, v_uint8, v_int16, v_int32, v_int8, void); + CV_DEF_REG_TRAITS(v, v_uint16, ushort, u16, v_uint16, v_uint32, v_uint64, v_int16, void); + CV_DEF_REG_TRAITS(v, v_int16, short, s16, v_uint16, v_int32, v_int64, v_int16, void); + CV_DEF_REG_TRAITS(v, v_uint32, unsigned, u32, v_uint32, v_uint64, void, v_int32, void); + CV_DEF_REG_TRAITS(v, v_int32, int, s32, v_uint32, v_int64, void, v_int32, void); + CV_DEF_REG_TRAITS(v, v_float32, float, f32, v_float32, v_float64, void, v_int32, v_int32); + CV_DEF_REG_TRAITS(v, v_uint64, uint64, u64, v_uint64, void, void, v_int64, void); + CV_DEF_REG_TRAITS(v, v_int64, int64, s64, v_uint64, void, void, v_int64, void); + CV_DEF_REG_TRAITS(v, v_float64, double, f64, v_float64, void, void, v_int64, v_int32); +#endif +//! @endcond + +#if CV_SIMD512 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 512) +#define CV__SIMD_NAMESPACE simd512 +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD 1 + #define CV_SIMD_64F CV_SIMD512_64F + #define CV_SIMD_FP16 CV_SIMD512_FP16 + #define CV_SIMD_WIDTH 64 +//! @addtogroup core_hal_intrin +//! @{ + //! @brief Maximum available vector register capacity 8-bit unsigned integer values + typedef v_uint8x64 v_uint8; + //! @brief Maximum available vector register capacity 8-bit signed integer values + typedef v_int8x64 v_int8; + //! @brief Maximum available vector register capacity 16-bit unsigned integer values + typedef v_uint16x32 v_uint16; + //! @brief Maximum available vector register capacity 16-bit signed integer values + typedef v_int16x32 v_int16; + //! @brief Maximum available vector register capacity 32-bit unsigned integer values + typedef v_uint32x16 v_uint32; + //! @brief Maximum available vector register capacity 32-bit signed integer values + typedef v_int32x16 v_int32; + //! @brief Maximum available vector register capacity 64-bit unsigned integer values + typedef v_uint64x8 v_uint64; + //! @brief Maximum available vector register capacity 64-bit signed integer values + typedef v_int64x8 v_int64; + //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) + typedef v_float32x16 v_float32; + #if CV_SIMD512_64F + //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) + typedef v_float64x8 v_float64; + #endif +//! @} + + #define VXPREFIX(func) v512##func +} // namespace +using namespace CV__SIMD_NAMESPACE; +#elif CV_SIMD256 && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 256) +#define CV__SIMD_NAMESPACE simd256 +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD 1 + #define CV_SIMD_64F CV_SIMD256_64F + #define CV_SIMD_FP16 CV_SIMD256_FP16 + #define CV_SIMD_WIDTH 32 +//! @addtogroup core_hal_intrin +//! @{ + //! @brief Maximum available vector register capacity 8-bit unsigned integer values + typedef v_uint8x32 v_uint8; + //! @brief Maximum available vector register capacity 8-bit signed integer values + typedef v_int8x32 v_int8; + //! @brief Maximum available vector register capacity 16-bit unsigned integer values + typedef v_uint16x16 v_uint16; + //! @brief Maximum available vector register capacity 16-bit signed integer values + typedef v_int16x16 v_int16; + //! @brief Maximum available vector register capacity 32-bit unsigned integer values + typedef v_uint32x8 v_uint32; + //! @brief Maximum available vector register capacity 32-bit signed integer values + typedef v_int32x8 v_int32; + //! @brief Maximum available vector register capacity 64-bit unsigned integer values + typedef v_uint64x4 v_uint64; + //! @brief Maximum available vector register capacity 64-bit signed integer values + typedef v_int64x4 v_int64; + //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) + typedef v_float32x8 v_float32; + #if CV_SIMD256_64F + //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) + typedef v_float64x4 v_float64; + #endif +//! @} + + #define VXPREFIX(func) v256##func +} // namespace +using namespace CV__SIMD_NAMESPACE; +#elif (CV_SIMD128 || CV_SIMD128_CPP) && (!defined(CV__SIMD_FORCE_WIDTH) || CV__SIMD_FORCE_WIDTH == 128) +#if defined CV_SIMD128_CPP +#define CV__SIMD_NAMESPACE simd128_cpp +#else +#define CV__SIMD_NAMESPACE simd128 +#endif +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD CV_SIMD128 + #define CV_SIMD_64F CV_SIMD128_64F + #define CV_SIMD_WIDTH 16 +//! @addtogroup core_hal_intrin +//! @{ + //! @brief Maximum available vector register capacity 8-bit unsigned integer values + typedef v_uint8x16 v_uint8; + //! @brief Maximum available vector register capacity 8-bit signed integer values + typedef v_int8x16 v_int8; + //! @brief Maximum available vector register capacity 16-bit unsigned integer values + typedef v_uint16x8 v_uint16; + //! @brief Maximum available vector register capacity 16-bit signed integer values + typedef v_int16x8 v_int16; + //! @brief Maximum available vector register capacity 32-bit unsigned integer values + typedef v_uint32x4 v_uint32; + //! @brief Maximum available vector register capacity 32-bit signed integer values + typedef v_int32x4 v_int32; + //! @brief Maximum available vector register capacity 64-bit unsigned integer values + typedef v_uint64x2 v_uint64; + //! @brief Maximum available vector register capacity 64-bit signed integer values + typedef v_int64x2 v_int64; + //! @brief Maximum available vector register capacity 32-bit floating point values (single precision) + typedef v_float32x4 v_float32; + #if CV_SIMD128_64F + //! @brief Maximum available vector register capacity 64-bit floating point values (double precision) + typedef v_float64x2 v_float64; + #endif +//! @} + + #define VXPREFIX(func) v##func +} // namespace +using namespace CV__SIMD_NAMESPACE; + +#elif CV_SIMD_SCALABLE +#define CV__SIMD_NAMESPACE simd +namespace CV__SIMD_NAMESPACE { + #define CV_SIMD 0 + #define CV_SIMD_WIDTH 128 /* 1024/8 */ + + #define VXPREFIX(func) v##func +} // namespace +using namespace CV__SIMD_NAMESPACE; + +#endif + +//! @cond IGNORED +#ifndef CV_SIMD_64F +#define CV_SIMD_64F 0 +#endif + +namespace CV__SIMD_NAMESPACE { +//! @addtogroup core_hal_intrin +//! @{ + //! @name Wide init with value + //! @{ + //! @brief Create maximum available capacity vector with elements set to a specific value + inline v_uint8 vx_setall_u8(uchar v) { return VXPREFIX(_setall_u8)(v); } + inline v_int8 vx_setall_s8(schar v) { return VXPREFIX(_setall_s8)(v); } + inline v_uint16 vx_setall_u16(ushort v) { return VXPREFIX(_setall_u16)(v); } + inline v_int16 vx_setall_s16(short v) { return VXPREFIX(_setall_s16)(v); } + inline v_int32 vx_setall_s32(int v) { return VXPREFIX(_setall_s32)(v); } + inline v_uint32 vx_setall_u32(unsigned v) { return VXPREFIX(_setall_u32)(v); } + inline v_float32 vx_setall_f32(float v) { return VXPREFIX(_setall_f32)(v); } + inline v_int64 vx_setall_s64(int64 v) { return VXPREFIX(_setall_s64)(v); } + inline v_uint64 vx_setall_u64(uint64 v) { return VXPREFIX(_setall_u64)(v); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_setall_f64(double v) { return VXPREFIX(_setall_f64)(v); } +#endif + //! @} + + //! @name Wide init with zero + //! @{ + //! @brief Create maximum available capacity vector with elements set to zero + inline v_uint8 vx_setzero_u8() { return VXPREFIX(_setzero_u8)(); } + inline v_int8 vx_setzero_s8() { return VXPREFIX(_setzero_s8)(); } + inline v_uint16 vx_setzero_u16() { return VXPREFIX(_setzero_u16)(); } + inline v_int16 vx_setzero_s16() { return VXPREFIX(_setzero_s16)(); } + inline v_int32 vx_setzero_s32() { return VXPREFIX(_setzero_s32)(); } + inline v_uint32 vx_setzero_u32() { return VXPREFIX(_setzero_u32)(); } + inline v_float32 vx_setzero_f32() { return VXPREFIX(_setzero_f32)(); } + inline v_int64 vx_setzero_s64() { return VXPREFIX(_setzero_s64)(); } + inline v_uint64 vx_setzero_u64() { return VXPREFIX(_setzero_u64)(); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_setzero_f64() { return VXPREFIX(_setzero_f64)(); } +#endif + //! @} + + //! @name Wide load from memory + //! @{ + //! @brief Load maximum available capacity register contents from memory + inline v_uint8 vx_load(const uchar * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int8 vx_load(const schar * ptr) { return VXPREFIX(_load)(ptr); } + inline v_uint16 vx_load(const ushort * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int16 vx_load(const short * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int32 vx_load(const int * ptr) { return VXPREFIX(_load)(ptr); } + inline v_uint32 vx_load(const unsigned * ptr) { return VXPREFIX(_load)(ptr); } + inline v_float32 vx_load(const float * ptr) { return VXPREFIX(_load)(ptr); } + inline v_int64 vx_load(const int64 * ptr) { return VXPREFIX(_load)(ptr); } + inline v_uint64 vx_load(const uint64 * ptr) { return VXPREFIX(_load)(ptr); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load(const double * ptr) { return VXPREFIX(_load)(ptr); } +#endif + //! @} + + //! @name Wide load from memory(aligned) + //! @{ + //! @brief Load maximum available capacity register contents from memory(aligned) + inline v_uint8 vx_load_aligned(const uchar * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int8 vx_load_aligned(const schar * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_uint16 vx_load_aligned(const ushort * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int16 vx_load_aligned(const short * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int32 vx_load_aligned(const int * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_uint32 vx_load_aligned(const unsigned * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_float32 vx_load_aligned(const float * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_int64 vx_load_aligned(const int64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } + inline v_uint64 vx_load_aligned(const uint64 * ptr) { return VXPREFIX(_load_aligned)(ptr); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load_aligned(const double * ptr) { return VXPREFIX(_load_aligned)(ptr); } +#endif + //! @} + + //! @name Wide load lower half from memory + //! @{ + //! @brief Load lower half of maximum available capacity register from memory + inline v_uint8 vx_load_low(const uchar * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int8 vx_load_low(const schar * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_uint16 vx_load_low(const ushort * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int16 vx_load_low(const short * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int32 vx_load_low(const int * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_uint32 vx_load_low(const unsigned * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_float32 vx_load_low(const float * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_int64 vx_load_low(const int64 * ptr) { return VXPREFIX(_load_low)(ptr); } + inline v_uint64 vx_load_low(const uint64 * ptr) { return VXPREFIX(_load_low)(ptr); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load_low(const double * ptr) { return VXPREFIX(_load_low)(ptr); } +#endif + //! @} + + //! @name Wide load halfs from memory + //! @{ + //! @brief Load maximum available capacity register contents from two memory blocks + inline v_uint8 vx_load_halves(const uchar * ptr0, const uchar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int8 vx_load_halves(const schar * ptr0, const schar * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_uint16 vx_load_halves(const ushort * ptr0, const ushort * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int16 vx_load_halves(const short * ptr0, const short * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int32 vx_load_halves(const int * ptr0, const int * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_uint32 vx_load_halves(const unsigned * ptr0, const unsigned * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_float32 vx_load_halves(const float * ptr0, const float * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_int64 vx_load_halves(const int64 * ptr0, const int64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } + inline v_uint64 vx_load_halves(const uint64 * ptr0, const uint64 * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_load_halves(const double * ptr0, const double * ptr1) { return VXPREFIX(_load_halves)(ptr0, ptr1); } +#endif + //! @} + + //! @name Wide LUT of elements + //! @{ + //! @brief Load maximum available capacity register contents with array elements by provided indexes + inline v_uint8 vx_lut(const uchar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int8 vx_lut(const schar * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_uint16 vx_lut(const ushort * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int16 vx_lut(const short* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int32 vx_lut(const int* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_uint32 vx_lut(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_float32 vx_lut(const float* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_int64 vx_lut(const int64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } + inline v_uint64 vx_lut(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_lut(const double* ptr, const int* idx) { return VXPREFIX(_lut)(ptr, idx); } +#endif + //! @} + + //! @name Wide LUT of element pairs + //! @{ + //! @brief Load maximum available capacity register contents with array element pairs by provided indexes + inline v_uint8 vx_lut_pairs(const uchar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int8 vx_lut_pairs(const schar * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_uint16 vx_lut_pairs(const ushort * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int16 vx_lut_pairs(const short* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int32 vx_lut_pairs(const int* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_uint32 vx_lut_pairs(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_float32 vx_lut_pairs(const float* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_int64 vx_lut_pairs(const int64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } + inline v_uint64 vx_lut_pairs(const uint64 * ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } +#if CV_SIMD_64F || CV_SIMD_SCALABLE_64F + inline v_float64 vx_lut_pairs(const double* ptr, const int* idx) { return VXPREFIX(_lut_pairs)(ptr, idx); } +#endif + //! @} + + //! @name Wide LUT of element quads + //! @{ + //! @brief Load maximum available capacity register contents with array element quads by provided indexes + inline v_uint8 vx_lut_quads(const uchar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_int8 vx_lut_quads(const schar* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_uint16 vx_lut_quads(const ushort* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_int16 vx_lut_quads(const short* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_int32 vx_lut_quads(const int* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_uint32 vx_lut_quads(const unsigned* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + inline v_float32 vx_lut_quads(const float* ptr, const int* idx) { return VXPREFIX(_lut_quads)(ptr, idx); } + //! @} + + //! @name Wide load with double expansion + //! @{ + //! @brief Load maximum available capacity register contents from memory with double expand + inline v_uint16 vx_load_expand(const uchar * ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_int16 vx_load_expand(const schar * ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_uint32 vx_load_expand(const ushort * ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_int32 vx_load_expand(const short* ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_int64 vx_load_expand(const int* ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_uint64 vx_load_expand(const unsigned* ptr) { return VXPREFIX(_load_expand)(ptr); } + inline v_float32 vx_load_expand(const hfloat * ptr) { return VXPREFIX(_load_expand)(ptr); } + //! @} + + //! @name Wide load with quad expansion + //! @{ + //! @brief Load maximum available capacity register contents from memory with quad expand + inline v_uint32 vx_load_expand_q(const uchar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } + inline v_int32 vx_load_expand_q(const schar * ptr) { return VXPREFIX(_load_expand_q)(ptr); } + //! @} + + /** @brief SIMD processing state cleanup call */ + inline void vx_cleanup() { VXPREFIX(_cleanup)(); } + +#if !CV_SIMD_SCALABLE + // Compatibility layer +#if !(CV_NEON && !defined(CV_FORCE_SIMD128_CPP)) + template struct VTraits { + static inline int vlanes() { return T::nlanes; } + enum { nlanes = T::nlanes, max_nlanes = T::nlanes }; + using lane_type = typename T::lane_type; + }; + + //////////// get0 //////////// + #define OPENCV_HAL_WRAP_GRT0(_Tpvec) \ + inline typename VTraits<_Tpvec>::lane_type v_get0(const _Tpvec& v) \ + { \ + return v.get0(); \ + } + + OPENCV_HAL_WRAP_GRT0(v_uint8) + OPENCV_HAL_WRAP_GRT0(v_int8) + OPENCV_HAL_WRAP_GRT0(v_uint16) + OPENCV_HAL_WRAP_GRT0(v_int16) + OPENCV_HAL_WRAP_GRT0(v_uint32) + OPENCV_HAL_WRAP_GRT0(v_int32) + OPENCV_HAL_WRAP_GRT0(v_uint64) + OPENCV_HAL_WRAP_GRT0(v_int64) + OPENCV_HAL_WRAP_GRT0(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_GRT0(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_GRT0(v_uint8x16) + OPENCV_HAL_WRAP_GRT0(v_uint16x8) + OPENCV_HAL_WRAP_GRT0(v_uint32x4) + OPENCV_HAL_WRAP_GRT0(v_uint64x2) + OPENCV_HAL_WRAP_GRT0(v_int8x16) + OPENCV_HAL_WRAP_GRT0(v_int16x8) + OPENCV_HAL_WRAP_GRT0(v_int32x4) + OPENCV_HAL_WRAP_GRT0(v_int64x2) + OPENCV_HAL_WRAP_GRT0(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_GRT0(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_GRT0(v_uint8x32) + OPENCV_HAL_WRAP_GRT0(v_uint16x16) + OPENCV_HAL_WRAP_GRT0(v_uint32x8) + OPENCV_HAL_WRAP_GRT0(v_uint64x4) + OPENCV_HAL_WRAP_GRT0(v_int8x32) + OPENCV_HAL_WRAP_GRT0(v_int16x16) + OPENCV_HAL_WRAP_GRT0(v_int32x8) + OPENCV_HAL_WRAP_GRT0(v_int64x4) + OPENCV_HAL_WRAP_GRT0(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_GRT0(v_float64x4) + #endif + #endif +#endif + + #define OPENCV_HAL_WRAP_BIN_OP_ADDSUB(_Tpvec) \ + template \ + inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ + return v_add(v_add(f1, f2), f3, vf...); \ + } + + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + // when we use CV_SIMD128 with 256/512 bit SIMD (e.g. AVX2 or AVX512) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x2) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x2) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + // when we use CV_SIMD256 with 512 bit SIMD (e.g. AVX512) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint8x32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint16x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint32x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_uint64x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int8x32) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int16x16) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int32x8) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_int64x4) + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_ADDSUB(v_float64x4) + #endif + #endif + + #define OPENCV_HAL_WRAP_BIN_OP_MUL(_Tpvec) \ + template \ + inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const _Tpvec& f3, const Args&... vf) { \ + return v_mul(v_mul(f1, f2), f3, vf...); \ + } + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x4) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x4) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint8x32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint16x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_uint32x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int8x32) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int16x16) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_int32x8) + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_BIN_OP_MUL(v_float64x4) + #endif + #endif + + #define OPENCV_HAL_WRAP_EXTRACT(_Tpvec) \ + inline typename VTraits<_Tpvec>::lane_type v_extract_highest(const _Tpvec& v) \ + { \ + return v_extract_n::nlanes-1>(v); \ + } + + OPENCV_HAL_WRAP_EXTRACT(v_uint8) + OPENCV_HAL_WRAP_EXTRACT(v_int8) + OPENCV_HAL_WRAP_EXTRACT(v_uint16) + OPENCV_HAL_WRAP_EXTRACT(v_int16) + OPENCV_HAL_WRAP_EXTRACT(v_uint32) + OPENCV_HAL_WRAP_EXTRACT(v_int32) + OPENCV_HAL_WRAP_EXTRACT(v_uint64) + OPENCV_HAL_WRAP_EXTRACT(v_int64) + OPENCV_HAL_WRAP_EXTRACT(v_float32) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_EXTRACT(v_float64) + #endif + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_EXTRACT(v_uint8x16) + OPENCV_HAL_WRAP_EXTRACT(v_uint16x8) + OPENCV_HAL_WRAP_EXTRACT(v_uint32x4) + OPENCV_HAL_WRAP_EXTRACT(v_uint64x2) + OPENCV_HAL_WRAP_EXTRACT(v_int8x16) + OPENCV_HAL_WRAP_EXTRACT(v_int16x8) + OPENCV_HAL_WRAP_EXTRACT(v_int32x4) + OPENCV_HAL_WRAP_EXTRACT(v_int64x2) + OPENCV_HAL_WRAP_EXTRACT(v_float32x4) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_EXTRACT(v_float64x2) + #endif + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_EXTRACT(v_uint8x32) + OPENCV_HAL_WRAP_EXTRACT(v_uint16x16) + OPENCV_HAL_WRAP_EXTRACT(v_uint32x8) + OPENCV_HAL_WRAP_EXTRACT(v_uint64x4) + OPENCV_HAL_WRAP_EXTRACT(v_int8x32) + OPENCV_HAL_WRAP_EXTRACT(v_int16x16) + OPENCV_HAL_WRAP_EXTRACT(v_int32x8) + OPENCV_HAL_WRAP_EXTRACT(v_int64x4) + OPENCV_HAL_WRAP_EXTRACT(v_float32x8) + #if CV_SIMD_64F + OPENCV_HAL_WRAP_EXTRACT(v_float64x4) + #endif + #endif + + #define OPENCV_HAL_WRAP_BROADCAST(_Tpvec) \ + inline _Tpvec v_broadcast_highest(const _Tpvec& v) \ + { \ + return v_broadcast_element::nlanes-1>(v); \ + } + + OPENCV_HAL_WRAP_BROADCAST(v_uint32) + OPENCV_HAL_WRAP_BROADCAST(v_int32) + OPENCV_HAL_WRAP_BROADCAST(v_float32) + #if CV_SIMD_WIDTH != 16/*128*/ && CV_SIMD128 + OPENCV_HAL_WRAP_BROADCAST(v_uint32x4) + OPENCV_HAL_WRAP_BROADCAST(v_int32x4) + OPENCV_HAL_WRAP_BROADCAST(v_float32x4) + #endif + #if CV_SIMD_WIDTH != 32/*256*/ && CV_SIMD256 + OPENCV_HAL_WRAP_BROADCAST(v_uint32x8) + OPENCV_HAL_WRAP_BROADCAST(v_int32x8) + OPENCV_HAL_WRAP_BROADCAST(v_float32x8) + #endif + +#endif //!CV_SIMD_SCALABLE + +//! @cond IGNORED + + // backward compatibility + template static inline + void vx_store(_Tp* dst, const _Tvec& v) { return v_store(dst, v); } + // backward compatibility + template static inline + void vx_store_aligned(_Tp* dst, const _Tvec& v) { return v_store_aligned(dst, v); } + +//! @endcond + + +//! @} + #undef VXPREFIX +} // namespace + + +#ifndef CV_SIMD_FP16 +#define CV_SIMD_FP16 0 //!< Defined to 1 on native support of operations with float16x8_t / float16x16_t (SIMD256) types +#endif + +#ifndef CV_SIMD +#define CV_SIMD 0 +#endif + +#include "simd_utils.impl.hpp" + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END +#endif + +} // cv:: + +//! @endcond + +#if defined(__GNUC__) && __GNUC__ == 12 +#pragma GCC diagnostic pop +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp index f9a58ccd77..c7ce1e3d33 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx.hpp @@ -1,3189 +1,3189 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_AVX_HPP -#define OPENCV_HAL_INTRIN_AVX_HPP - -#define CV_SIMD256 1 -#define CV_SIMD256_64F 1 -#define CV_SIMD256_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Utils //////////// - -inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) -{ return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); } - -inline __m256 _v256_combine(const __m128& lo, const __m128& hi) -{ return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); } - -inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) -{ return _mm256_insertf128_pd(_mm256_castpd128_pd256(lo), hi, 1); } - -inline int _v_cvtsi256_si32(const __m256i& a) -{ return _mm_cvtsi128_si32(_mm256_castsi256_si128(a)); } - -inline __m256i _v256_shuffle_odd_64(const __m256i& v) -{ return _mm256_permute4x64_epi64(v, _MM_SHUFFLE(3, 1, 2, 0)); } - -inline __m256d _v256_shuffle_odd_64(const __m256d& v) -{ return _mm256_permute4x64_pd(v, _MM_SHUFFLE(3, 1, 2, 0)); } - -template -inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) -{ return _mm256_permute2x128_si256(a, b, imm); } - -template -inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) -{ return _mm256_permute2f128_ps(a, b, imm); } - -template -inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) -{ return _mm256_permute2f128_pd(a, b, imm); } - -template -inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } - -template -inline __m256i _v256_permute4x64(const __m256i& a) -{ return _mm256_permute4x64_epi64(a, imm); } - -template -inline __m256d _v256_permute4x64(const __m256d& a) -{ return _mm256_permute4x64_pd(a, imm); } - -template -inline _Tpvec v256_permute4x64(const _Tpvec& a) -{ return _Tpvec(_v256_permute4x64(a.val)); } - -inline __m128i _v256_extract_high(const __m256i& v) -{ return _mm256_extracti128_si256(v, 1); } - -inline __m128 _v256_extract_high(const __m256& v) -{ return _mm256_extractf128_ps(v, 1); } - -inline __m128d _v256_extract_high(const __m256d& v) -{ return _mm256_extractf128_pd(v, 1); } - -inline __m128i _v256_extract_low(const __m256i& v) -{ return _mm256_castsi256_si128(v); } - -inline __m128 _v256_extract_low(const __m256& v) -{ return _mm256_castps256_ps128(v); } - -inline __m128d _v256_extract_low(const __m256d& v) -{ return _mm256_castpd256_pd128(v); } - -inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) -{ - const __m256i m = _mm256_set1_epi32(65535); - __m256i am = _mm256_min_epu32(a, m); - __m256i bm = _mm256_min_epu32(b, m); - return _mm256_packus_epi32(am, bm); -} - -template -inline int _v256_extract_epi8(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi8(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 4)); - return _mm_extract_epi8(b, i & 15); // SSE4.1 -#endif -} - -template -inline int _v256_extract_epi16(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi16(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 3)); - return _mm_extract_epi16(b, i & 7); // SSE2 -#endif -} - -template -inline int _v256_extract_epi32(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi32(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 2)); - return _mm_extract_epi32(b, i & 3); // SSE4.1 -#endif -} - -template -inline int64 _v256_extract_epi64(const __m256i& a) -{ -#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) - return _mm256_extract_epi64(a, i); -#else - __m128i b = _mm256_extractf128_si256(a, ((i) >> 1)); - return _mm_extract_epi64(b, i & 1); // SSE4.1 -#endif -} - -///////// Types //////////// - -struct v_uint8x32 -{ - typedef uchar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_uint8x32(__m256i v) : val(v) {} - v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, - uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, - uchar v12, uchar v13, uchar v14, uchar v15, - uchar v16, uchar v17, uchar v18, uchar v19, - uchar v20, uchar v21, uchar v22, uchar v23, - uchar v24, uchar v25, uchar v26, uchar v27, - uchar v28, uchar v29, uchar v30, uchar v31) - { - val = _mm256_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, - (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, - (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, - (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, - (char)v28, (char)v29, (char)v30, (char)v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint8x32() {} - - uchar get0() const { return (uchar)_v_cvtsi256_si32(val); } -}; - -struct v_int8x32 -{ - typedef schar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_int8x32(__m256i v) : val(v) {} - v_int8x32(schar v0, schar v1, schar v2, schar v3, - schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, - schar v12, schar v13, schar v14, schar v15, - schar v16, schar v17, schar v18, schar v19, - schar v20, schar v21, schar v22, schar v23, - schar v24, schar v25, schar v26, schar v27, - schar v28, schar v29, schar v30, schar v31) - { - val = _mm256_setr_epi8(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, - v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int8x32() {} - - schar get0() const { return (schar)_v_cvtsi256_si32(val); } -}; - -struct v_uint16x16 -{ - typedef ushort lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_uint16x16(__m256i v) : val(v) {} - v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, - ushort v4, ushort v5, ushort v6, ushort v7, - ushort v8, ushort v9, ushort v10, ushort v11, - ushort v12, ushort v13, ushort v14, ushort v15) - { - val = _mm256_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, - (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint16x16() {} - - ushort get0() const { return (ushort)_v_cvtsi256_si32(val); } -}; - -struct v_int16x16 -{ - typedef short lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_int16x16(__m256i v) : val(v) {} - v_int16x16(short v0, short v1, short v2, short v3, - short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, - short v12, short v13, short v14, short v15) - { - val = _mm256_setr_epi16(v0, v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int16x16() {} - - short get0() const { return (short)_v_cvtsi256_si32(val); } -}; - -struct v_uint32x8 -{ - typedef unsigned lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_uint32x8(__m256i v) : val(v) {} - v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, - unsigned v4, unsigned v5, unsigned v6, unsigned v7) - { - val = _mm256_setr_epi32((unsigned)v0, (unsigned)v1, (unsigned)v2, - (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint32x8() {} - - unsigned get0() const { return (unsigned)_v_cvtsi256_si32(val); } -}; - -struct v_int32x8 -{ - typedef int lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_int32x8(__m256i v) : val(v) {} - v_int32x8(int v0, int v1, int v2, int v3, - int v4, int v5, int v6, int v7) - { - val = _mm256_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int32x8() {} - - int get0() const { return _v_cvtsi256_si32(val); } -}; - -struct v_float32x8 -{ - typedef float lane_type; - enum { nlanes = 8 }; - __m256 val; - - explicit v_float32x8(__m256 v) : val(v) {} - v_float32x8(float v0, float v1, float v2, float v3, - float v4, float v5, float v6, float v7) - { - val = _mm256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_float32x8() {} - - float get0() const { return _mm_cvtss_f32(_mm256_castps256_ps128(val)); } -}; - -struct v_uint64x4 -{ - typedef uint64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_uint64x4(__m256i v) : val(v) {} - v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) - { val = _mm256_setr_epi64x((int64)v0, (int64)v1, (int64)v2, (int64)v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_uint64x4() {} - - uint64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (uint64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); - int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); - return (unsigned)a | ((uint64)(unsigned)b << 32); - #endif - } -}; - -struct v_int64x4 -{ - typedef int64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_int64x4(__m256i v) : val(v) {} - v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) - { val = _mm256_setr_epi64x(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_int64x4() {} - - int64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (int64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); - int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); - return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); - #endif - } -}; - -struct v_float64x4 -{ - typedef double lane_type; - enum { nlanes = 4 }; - __m256d val; - - explicit v_float64x4(__m256d v) : val(v) {} - v_float64x4(double v0, double v1, double v2, double v3) - { val = _mm256_setr_pd(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_float64x4() {} - - double get0() const { return _mm_cvtsd_f64(_mm256_castpd256_pd128(val)); } -}; - -//////////////// Load and store operations /////////////// - -#define OPENCV_HAL_IMPL_AVX_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(_mm256_loadu_si256((const __m256i*)ptr)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm256_load_si256((const __m256i*)ptr)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - __m128i v128 = _mm_loadu_si128((const __m128i*)ptr); \ - return _Tpvec(_mm256_castsi128_si256(v128)); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vlo = _mm_loadu_si128((const __m128i*)ptr0); \ - __m128i vhi = _mm_loadu_si128((const __m128i*)ptr1); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_si256((__m256i*)ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm256_store_si256((__m256i*)ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm256_stream_si256((__m256i*)ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm256_storeu_si256((__m256i*)ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm256_stream_si256((__m256i*)ptr, a.val); \ - else \ - _mm256_store_si256((__m256i*)ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_si128((__m128i*)ptr, _v256_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_si128((__m128i*)ptr, _v256_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint8x32, uchar) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int8x32, schar) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint16x16, ushort) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int16x16, short) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint32x8, unsigned) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int32x8, int) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint64x4, uint64) -OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int64x4, int64) - -#define OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(_mm256_loadu_##suffix(ptr)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm256_load_##suffix(ptr)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - return _Tpvec(_mm256_cast##suffix##128_##suffix##256 \ - (_mm_loadu_##suffix(ptr))); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - halfreg vlo = _mm_loadu_##suffix(ptr0); \ - halfreg vhi = _mm_loadu_##suffix(ptr1); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_##suffix(ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm256_store_##suffix(ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm256_stream_##suffix(ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm256_storeu_##suffix(ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm256_stream_##suffix(ptr, a.val); \ - else \ - _mm256_store_##suffix(ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_##suffix(ptr, _v256_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm_storeu_##suffix(ptr, _v256_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float32x8, float, ps, __m128) -OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float64x4, double, pd, __m128d) - -#define OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_AVX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(_mm256_setzero_si256()); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm256_set1_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float32x8, suffix, _mm256_castps_si256) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float64x4, suffix, _mm256_castpd_si256) - -OPENCV_HAL_IMPL_AVX_INIT(v_uint8x32, uchar, u8, epi8, char) -OPENCV_HAL_IMPL_AVX_INIT(v_int8x32, schar, s8, epi8, char) -OPENCV_HAL_IMPL_AVX_INIT(v_uint16x16, ushort, u16, epi16, short) -OPENCV_HAL_IMPL_AVX_INIT(v_int16x16, short, s16, epi16, short) -OPENCV_HAL_IMPL_AVX_INIT(v_uint32x8, unsigned, u32, epi32, int) -OPENCV_HAL_IMPL_AVX_INIT(v_int32x8, int, s32, epi32, int) -OPENCV_HAL_IMPL_AVX_INIT(v_uint64x4, uint64, u64, epi64x, int64) -OPENCV_HAL_IMPL_AVX_INIT(v_int64x4, int64, s64, epi64x, int64) - -#define OPENCV_HAL_IMPL_AVX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(_mm256_setzero_##zsuffix()); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm256_set1_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ - OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, cast) - -OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float32x8, float, f32, ps, _mm256_castsi256_ps) -OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float64x4, double, f64, pd, _mm256_castsi256_pd) - -inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) -{ return a; } -inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) -{ return v_float32x8(_mm256_castpd_ps(a.val)); } - -inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) -{ return a; } -inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) -{ return v_float64x4(_mm256_castps_pd(a.val)); } - -/* Recombine */ -/*#define OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, perm) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(perm(a.val, b.val, 0x20)); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(perm(a.val, b.val, 0x31)); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { c = v_combine_low(a, b); d = v_combine_high(a, b); } - -#define OPENCV_HAL_IMPL_AVX_UNPACKS(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, _mm256_permute2x128_si256) \ - inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, \ - _Tpvec& b0, _Tpvec& b1) \ - { \ - __m256i v0 = _v256_shuffle_odd_64(a0.val); \ - __m256i v1 = _v256_shuffle_odd_64(a1.val); \ - b0.val = _mm256_unpacklo_##suffix(v0, v1); \ - b1.val = _mm256_unpackhi_##suffix(v0, v1); \ - } - -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint64x4, epi64) -OPENCV_HAL_IMPL_AVX_UNPACKS(v_int64x4, epi64) -OPENCV_HAL_IMPL_AVX_COMBINE(v_float32x8, _mm256_permute2f128_ps) -OPENCV_HAL_IMPL_AVX_COMBINE(v_float64x4, _mm256_permute2f128_pd) - -inline void v_zip(const v_float32x8& a0, const v_float32x8& a1, v_float32x8& b0, v_float32x8& b1) -{ - __m256 v0 = _mm256_unpacklo_ps(a0.val, a1.val); - __m256 v1 = _mm256_unpackhi_ps(a0.val, a1.val); - v_recombine(v_float32x8(v0), v_float32x8(v1), b0, b1); -} - -inline void v_zip(const v_float64x4& a0, const v_float64x4& a1, v_float64x4& b0, v_float64x4& b1) -{ - __m256d v0 = _v_shuffle_odd_64(a0.val); - __m256d v1 = _v_shuffle_odd_64(a1.val); - b0.val = _mm256_unpacklo_pd(v0, v1); - b1.val = _mm256_unpackhi_pd(v0, v1); -}*/ - -//////////////// Variant Value reordering /////////////// - -// unpacks -#define OPENCV_HAL_IMPL_AVX_UNPACK(_Tpvec, suffix) \ - inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_unpacklo_##suffix(a.val, b.val)); } \ - inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_unpackhi_##suffix(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int8x32, epi8) -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int16x16, epi16) -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int32x8, epi32) -OPENCV_HAL_IMPL_AVX_UNPACK(v_uint64x4, epi64) -OPENCV_HAL_IMPL_AVX_UNPACK(v_int64x4, epi64) -OPENCV_HAL_IMPL_AVX_UNPACK(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_UNPACK(v_float64x4, pd) - -// blend -#define OPENCV_HAL_IMPL_AVX_BLEND(_Tpvec, suffix) \ - template \ - inline _Tpvec v256_blend(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_blend_##suffix(a.val, b.val, m)); } - -OPENCV_HAL_IMPL_AVX_BLEND(v_uint16x16, epi16) -OPENCV_HAL_IMPL_AVX_BLEND(v_int16x16, epi16) -OPENCV_HAL_IMPL_AVX_BLEND(v_uint32x8, epi32) -OPENCV_HAL_IMPL_AVX_BLEND(v_int32x8, epi32) -OPENCV_HAL_IMPL_AVX_BLEND(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_BLEND(v_float64x4, pd) - -template -inline v_uint64x4 v256_blend(const v_uint64x4& a, const v_uint64x4& b) -{ - enum {M0 = m}; - enum {M1 = (M0 | (M0 << 2)) & 0x33}; - enum {M2 = (M1 | (M1 << 1)) & 0x55}; - enum {MM = M2 | (M2 << 1)}; - return v_uint64x4(_mm256_blend_epi32(a.val, b.val, MM)); -} -template -inline v_int64x4 v256_blend(const v_int64x4& a, const v_int64x4& b) -{ return v_int64x4(v256_blend(v_uint64x4(a.val), v_uint64x4(b.val)).val); } - -// shuffle -// todo: emulate 64bit -#define OPENCV_HAL_IMPL_AVX_SHUFFLE(_Tpvec, intrin) \ - template \ - inline _Tpvec v256_shuffle(const _Tpvec& a) \ - { return _Tpvec(_mm256_##intrin(a.val, m)); } - -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_uint32x8, shuffle_epi32) -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_int32x8, shuffle_epi32) -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float32x8, permute_ps) -OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float64x4, permute_pd) - -template -inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) -{ - ab0 = v256_unpacklo(a, b); - ab1 = v256_unpackhi(a, b); -} - -template -inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_mm256_blend_epi32(a.val, b.val, 0xf0)); } - -inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) -{ return v256_blend<0xf0>(a, b); } - -inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) -{ return v256_blend<0xc>(a, b); } - -template -inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) -{ return v256_permute2x128<0x21>(a, b); } - -template -inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_mm256_alignr_epi8(a.val, b.val, 8)); } -inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) -{ return v_float64x4(_mm256_shuffle_pd(b.val, a.val, _MM_SHUFFLE(0, 0, 1, 1))); } -// todo: emulate float32 - -template -inline _Tpvec v256_swap_halves(const _Tpvec& a) -{ return v256_permute2x128<1>(a, a); } - -template -inline _Tpvec v256_reverse_64(const _Tpvec& a) -{ return v256_permute4x64<_MM_SHUFFLE(0, 1, 2, 3)>(a); } - -// ZIP -#define OPENCV_HAL_IMPL_AVX_ZIP(_Tpvec) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x20>(a, b); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x31>(a, b); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - _Tpvec a1b0 = v256_alignr_128(a, b); \ - c = v256_combine_diagonal(a, a1b0); \ - d = v256_combine_diagonal(a1b0, b); \ - } \ - inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& ab0, _Tpvec& ab1) \ - { \ - _Tpvec ab0ab2, ab1ab3; \ - v256_zip(a, b, ab0ab2, ab1ab3); \ - v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ - } - -OPENCV_HAL_IMPL_AVX_ZIP(v_uint8x32) -OPENCV_HAL_IMPL_AVX_ZIP(v_int8x32) -OPENCV_HAL_IMPL_AVX_ZIP(v_uint16x16) -OPENCV_HAL_IMPL_AVX_ZIP(v_int16x16) -OPENCV_HAL_IMPL_AVX_ZIP(v_uint32x8) -OPENCV_HAL_IMPL_AVX_ZIP(v_int32x8) -OPENCV_HAL_IMPL_AVX_ZIP(v_uint64x4) -OPENCV_HAL_IMPL_AVX_ZIP(v_int64x4) -OPENCV_HAL_IMPL_AVX_ZIP(v_float32x8) -OPENCV_HAL_IMPL_AVX_ZIP(v_float64x4) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/* Element-wise binary and unary operations */ - -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_AVX_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint8x32, _mm256_adds_epu8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint8x32, _mm256_subs_epu8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int8x32, _mm256_adds_epi8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int8x32, _mm256_subs_epi8) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint16x16, _mm256_adds_epu16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint16x16, _mm256_subs_epu16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int16x16, _mm256_adds_epi16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int16x16, _mm256_subs_epi16) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint32x8, _mm256_add_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint32x8, _mm256_sub_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_uint32x8, _mm256_mullo_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int32x8, _mm256_add_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int32x8, _mm256_sub_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_int32x8, _mm256_mullo_epi32) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint64x4, _mm256_add_epi64) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint64x4, _mm256_sub_epi64) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int64x4, _mm256_add_epi64) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int64x4, _mm256_sub_epi64) - -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float32x8, _mm256_add_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float32x8, _mm256_sub_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float32x8, _mm256_mul_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float32x8, _mm256_div_ps) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float64x4, _mm256_add_pd) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float64x4, _mm256_sub_pd) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float64x4, _mm256_mul_pd) -OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float64x4, _mm256_div_pd) - -// saturating multiply 8-bit, 16-bit -inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) -{ - v_uint16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) -{ - v_int16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i pl = _mm256_mullo_epi16(a.val, b.val); - __m256i ph = _mm256_mulhi_epu16(a.val, b.val); - __m256i p0 = _mm256_unpacklo_epi16(pl, ph); - __m256i p1 = _mm256_unpackhi_epi16(pl, ph); - return v_uint16x16(_v256_packs_epu32(p0, p1)); -} -inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) -{ - __m256i pl = _mm256_mullo_epi16(a.val, b.val); - __m256i ph = _mm256_mulhi_epi16(a.val, b.val); - __m256i p0 = _mm256_unpacklo_epi16(pl, ph); - __m256i p1 = _mm256_unpackhi_epi16(pl, ph); - return v_int16x16(_mm256_packs_epi32(p0, p1)); -} - -/** Non-saturating arithmetics **/ -#define OPENCV_HAL_IMPL_AVX_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint8x32, _mm256_add_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int8x32, _mm256_add_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint16x16, _mm256_add_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int16x16, _mm256_add_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint8x32, _mm256_sub_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int8x32, _mm256_sub_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint16x16, _mm256_sub_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int16x16, _mm256_sub_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_uint16x16, _mm256_mullo_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_int16x16, _mm256_mullo_epi16) - -inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i ad = _mm256_srai_epi16(a.val, 8); - __m256i bd = _mm256_srai_epi16(b.val, 8); - __m256i p0 = _mm256_mullo_epi16(a.val, b.val); // even - __m256i p1 = _mm256_slli_epi16(_mm256_mullo_epi16(ad, bd), 8); // odd - - const __m256i b01 = _mm256_set1_epi32(0xFF00FF00); - return v_uint8x32(_mm256_blendv_epi8(p0, p1, b01)); -} -inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -// Multiply and expand -inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, - v_uint16x16& c, v_uint16x16& d) -{ - v_uint16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, - v_int16x16& c, v_int16x16& d) -{ - v_int16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, - v_int32x8& c, v_int32x8& d) -{ - v_int16x16 vhi = v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); - - v_int16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_s32(v0); - d = v_reinterpret_as_s32(v1); -} - -inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, - v_uint32x8& c, v_uint32x8& d) -{ - v_uint16x16 vhi = v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); - - v_uint16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_u32(v0); - d = v_reinterpret_as_u32(v1); -} - -inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, - v_uint64x4& c, v_uint64x4& d) -{ - __m256i v0 = _mm256_mul_epu32(a.val, b.val); - __m256i v1 = _mm256_mul_epu32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); - v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); -} - -inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); } -inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); } - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_AVX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(srai(a.val, imm)); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(srai(a.val, imm)); } - -OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint16x16, v_int16x16, epi16, _mm256_srai_epi16) -OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint32x8, v_int32x8, epi32, _mm256_srai_epi32) - -inline __m256i _mm256_srai_epi64xx(const __m256i a, int imm) -{ - __m256i d = _mm256_set1_epi64x((int64)1 << 63); - __m256i r = _mm256_srli_epi64(_mm256_add_epi64(a, d), imm); - return _mm256_sub_epi64(r, _mm256_srli_epi64(d, imm)); -} -OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint64x4, v_int64x4, epi64, _mm256_srai_epi64xx) - - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_AVX_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_AVX_BIN_OP(v_and, _Tpvec, _mm256_and_##suffix) \ - OPENCV_HAL_IMPL_AVX_BIN_OP(v_or, _Tpvec, _mm256_or_##suffix) \ - OPENCV_HAL_IMPL_AVX_BIN_OP(v_xor, _Tpvec, _mm256_xor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(_mm256_xor_##suffix(a.val, not_const)); } - -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint8x32, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int8x32, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint16x16, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int16x16, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint32x8, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int32x8, si256, _mm256_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint64x4, si256, _mm256_set1_epi64x(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int64x4, si256, _mm256_set1_epi64x(-1)) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float32x8, ps, _mm256_castsi256_ps(_mm256_set1_epi32(-1))) -OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float64x4, pd, _mm256_castsi256_pd(_mm256_set1_epi32(-1))) - -/** Select **/ -#define OPENCV_HAL_IMPL_AVX_SELECT(_Tpvec, suffix) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_blendv_##suffix(b.val, a.val, mask.val)); } - -OPENCV_HAL_IMPL_AVX_SELECT(v_uint8x32, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_int8x32, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_uint16x16, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_int16x16, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_uint32x8, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_int32x8, epi8) -OPENCV_HAL_IMPL_AVX_SELECT(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_SELECT(v_float64x4, pd) - -/** Comparison **/ -#define OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpvec) \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } \ - inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ - { return v_gt(b, a); } \ - inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_lt(a, b)); } \ - inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ - { return v_ge(b, a); } - -#define OPENCV_HAL_IMPL_AVX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, sbit) \ - inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ - inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ - { \ - __m256i smask = _mm256_set1_##suffix(sbit); \ - return _Tpuvec(_mm256_cmpgt_##suffix( \ - _mm256_xor_si256(a.val, smask), \ - _mm256_xor_si256(b.val, smask))); \ - } \ - inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ - inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(_mm256_cmpgt_##suffix(a.val, b.val)); } \ - OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpuvec) \ - OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpsvec) - -OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint8x32, v_int8x32, epi8, (char)-128) -OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint16x16, v_int16x16, epi16, (short)-32768) -OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint32x8, v_int32x8, epi32, (int)0x80000000) - -#define OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(_Tpvec) \ - inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_cmpeq_epi64(a.val, b.val)); } \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } - -OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_uint64x4) -OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_int64x4) - -#define OPENCV_HAL_IMPL_AVX_CMP_FLT(bin_op, imm8, _Tpvec, suffix) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm256_cmp_##suffix(a.val, b.val, imm8)); } - -#define OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, suffix) \ - OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, suffix) - -OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float64x4, pd) - -inline v_float32x8 v_not_nan(const v_float32x8& a) -{ return v_float32x8(_mm256_cmp_ps(a.val, a.val, _CMP_ORD_Q)); } -inline v_float64x4 v_not_nan(const v_float64x4& a) -{ return v_float64x4(_mm256_cmp_pd(a.val, a.val, _CMP_ORD_Q)); } - -/** min/max **/ -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint8x32, _mm256_min_epu8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint8x32, _mm256_max_epu8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int8x32, _mm256_min_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int8x32, _mm256_max_epi8) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint16x16, _mm256_min_epu16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint16x16, _mm256_max_epu16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int16x16, _mm256_min_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int16x16, _mm256_max_epi16) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint32x8, _mm256_min_epu32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint32x8, _mm256_max_epu32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int32x8, _mm256_min_epi32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int32x8, _mm256_max_epi32) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float32x8, _mm256_min_ps) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float32x8, _mm256_max_ps) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float64x4, _mm256_min_pd) -OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float64x4, _mm256_max_pd) - -/** Rotate **/ -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_R = (16 - imm) & 0xFF}; - enum {IMM_R2 = (32 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x03); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swap, IMM_R)); - return v_uint8x32(_mm256_alignr_epi8(swap, b.val, IMM_R2)); // imm < 32 -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x21); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swap, a.val, imm)); - return v_uint8x32(_mm256_alignr_epi8(b.val, swap, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - enum {IMM_R = (16 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(0, 0, 2, 0)); - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swapz, IMM_R)); - return v_uint8x32(_mm256_slli_si256(swapz, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(2, 0, 0, 1)); - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swapz, a.val, imm)); - return v_uint8x32(_mm256_srli_si256(swapz, IMM_L)); -} - -#define OPENCV_HAL_IMPL_AVX_ROTATE_CAST(intrin, _Tpvec, cast) \ - template \ - inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ - v_reinterpret_as_u8(b)); \ - return _Tpvec(cast(ret.val)); \ - } \ - template \ - inline _Tpvec intrin(const _Tpvec& a) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ - return _Tpvec(cast(ret.val)); \ - } - -#define OPENCV_HAL_IMPL_AVX_ROTATE(_Tpvec) \ - OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) - -OPENCV_HAL_IMPL_AVX_ROTATE(v_int8x32) -OPENCV_HAL_IMPL_AVX_ROTATE(v_uint16x16) -OPENCV_HAL_IMPL_AVX_ROTATE(v_int16x16) -OPENCV_HAL_IMPL_AVX_ROTATE(v_uint32x8) -OPENCV_HAL_IMPL_AVX_ROTATE(v_int32x8) -OPENCV_HAL_IMPL_AVX_ROTATE(v_uint64x4) -OPENCV_HAL_IMPL_AVX_ROTATE(v_int64x4) - -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float32x8, _mm256_castsi256_ps) -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float32x8, _mm256_castsi256_ps) -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float64x4, _mm256_castsi256_pd) -OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float64x4, _mm256_castsi256_pd) - -/** Reverse **/ -inline v_uint8x32 v_reverse(const v_uint8x32 &a) -{ - static const __m256i perm = _mm256_setr_epi8( - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - __m256i vec = _mm256_shuffle_epi8(a.val, perm); - return v_uint8x32(_mm256_permute2x128_si256(vec, vec, 1)); -} - -inline v_int8x32 v_reverse(const v_int8x32 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x16 v_reverse(const v_uint16x16 &a) -{ - static const __m256i perm = _mm256_setr_epi8( - 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1, - 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); - __m256i vec = _mm256_shuffle_epi8(a.val, perm); - return v_uint16x16(_mm256_permute2x128_si256(vec, vec, 1)); -} - -inline v_int16x16 v_reverse(const v_int16x16 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x8 v_reverse(const v_uint32x8 &a) -{ - static const __m256i perm = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); - return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); -} - -inline v_int32x8 v_reverse(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x8 v_reverse(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x4 v_reverse(const v_uint64x4 &a) -{ - return v_uint64x4(_mm256_permute4x64_epi64(a.val, _MM_SHUFFLE(0, 1, 2, 3))); -} - -inline v_int64x4 v_reverse(const v_int64x4 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x4 v_reverse(const v_float64x4 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////// Reduce and mask ///////// - -/** Reduce **/ -inline unsigned v_reduce_sum(const v_uint8x32& a) -{ - __m256i half = _mm256_sad_epu8(a.val, _mm256_setzero_si256()); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline int v_reduce_sum(const v_int8x32& a) -{ - __m256i half = _mm256_sad_epu8(_mm256_xor_si256(a.val, _mm256_set1_epi8((schar)-128)), _mm256_setzero_si256()); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))) - 4096; -} -#define OPENCV_HAL_IMPL_AVX_REDUCE_32(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ - val = intrin(val, _mm_srli_si128(val,8)); \ - val = intrin(val, _mm_srli_si128(val,4)); \ - val = intrin(val, _mm_srli_si128(val,2)); \ - val = intrin(val, _mm_srli_si128(val,1)); \ - return (sctype)_mm_cvtsi128_si32(val); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, min, _mm_min_epu8) -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, min, _mm_min_epi8) -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, max, _mm_max_epu8) -OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, max, _mm_max_epi8) - -#define OPENCV_HAL_IMPL_AVX_REDUCE_16(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ - v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ - v0 = intrin(v0, _mm_srli_si128(v0, 2)); \ - return (sctype) _mm_cvtsi128_si32(v0); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, min, _mm_min_epu16) -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, min, _mm_min_epi16) -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, max, _mm_max_epu16) -OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, max, _mm_max_epi16) - -#define OPENCV_HAL_IMPL_AVX_REDUCE_8(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ - v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ - return (sctype) _mm_cvtsi128_si32(v0); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, min, _mm_min_epu32) -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, min, _mm_min_epi32) -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, max, _mm_max_epu32) -OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, max, _mm_max_epi32) - -#define OPENCV_HAL_IMPL_AVX_REDUCE_FLT(func, intrin) \ - inline float v_reduce_##func(const v_float32x8& a) \ - { \ - __m128 v0 = _v256_extract_low(a.val); \ - __m128 v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 3, 2))); \ - v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 0, 1))); \ - return _mm_cvtss_f32(v0); \ - } - -OPENCV_HAL_IMPL_AVX_REDUCE_FLT(min, _mm_min_ps) -OPENCV_HAL_IMPL_AVX_REDUCE_FLT(max, _mm_max_ps) - -inline int v_reduce_sum(const v_int32x8& a) -{ - __m256i s0 = _mm256_hadd_epi32(a.val, a.val); - s0 = _mm256_hadd_epi32(s0, s0); - - __m128i s1 = _v256_extract_high(s0); - s1 = _mm_add_epi32(_v256_extract_low(s0), s1); - - return _mm_cvtsi128_si32(s1); -} - -inline unsigned v_reduce_sum(const v_uint32x8& a) -{ return v_reduce_sum(v_reinterpret_as_s32(a)); } - -inline int v_reduce_sum(const v_int16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline unsigned v_reduce_sum(const v_uint16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -inline float v_reduce_sum(const v_float32x8& a) -{ - __m256 s0 = _mm256_hadd_ps(a.val, a.val); - s0 = _mm256_hadd_ps(s0, s0); - - __m128 s1 = _v256_extract_high(s0); - s1 = _mm_add_ps(_v256_extract_low(s0), s1); - - return _mm_cvtss_f32(s1); -} - -inline uint64 v_reduce_sum(const v_uint64x4& a) -{ - uint64 CV_DECL_ALIGNED(32) idx[2]; - _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); - return idx[0] + idx[1]; -} -inline int64 v_reduce_sum(const v_int64x4& a) -{ - int64 CV_DECL_ALIGNED(32) idx[2]; - _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); - return idx[0] + idx[1]; -} -inline double v_reduce_sum(const v_float64x4& a) -{ - __m256d s0 = _mm256_hadd_pd(a.val, a.val); - return _mm_cvtsd_f64(_mm_add_pd(_v256_extract_low(s0), _v256_extract_high(s0))); -} - -inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, - const v_float32x8& c, const v_float32x8& d) -{ - __m256 ab = _mm256_hadd_ps(a.val, b.val); - __m256 cd = _mm256_hadd_ps(c.val, d.val); - return v_float32x8(_mm256_hadd_ps(ab, cd)); -} - -inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i half = _mm256_sad_epu8(a.val, b.val); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) -{ - __m256i half = _mm256_set1_epi8(0x7f); - half = _mm256_sad_epu8(_mm256_add_epi8(a.val, half), _mm256_add_epi8(b.val, half)); - __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) -{ - return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); -} -inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 m = v_lt(a, b); - return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); -} -inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) -{ - return v_reduce_sum(v_and(v_sub(a, b), v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff))))); -} - -/** Popcount **/ -inline v_uint8x32 v_popcount(const v_uint8x32& a) -{ - __m256i _popcnt_table = _mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); - __m256i _popcnt_mask = _mm256_set1_epi8(0x0F); - return v_uint8x32(_mm256_add_epi8(_mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256( a.val , _popcnt_mask)), - _mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256(_mm256_srli_epi16(a.val, 4), _popcnt_mask)))); -} -inline v_uint16x16 v_popcount(const v_uint16x16& a) -{ - v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v256_setall_u16(0x00ff)); -} -inline v_uint32x8 v_popcount(const v_uint32x8& a) -{ - v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v256_setall_u32(0x000000ff)); -} -inline v_uint64x4 v_popcount(const v_uint64x4& a) -{ - return v_uint64x4(_mm256_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm256_setzero_si256())); -} -inline v_uint8x32 v_popcount(const v_int8x32& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x16 v_popcount(const v_int16x16& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x8 v_popcount(const v_int32x8& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x4 v_popcount(const v_int64x4& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -/** Mask **/ -inline int v_signmask(const v_int8x32& a) -{ return _mm256_movemask_epi8(a.val); } -inline int v_signmask(const v_uint8x32& a) -{ return v_signmask(v_reinterpret_as_s8(a)); } - -inline int v_signmask(const v_int16x16& a) -{ return v_signmask(v_pack(a, a)) & 0xFFFF; } -inline int v_signmask(const v_uint16x16& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_float32x8& a) -{ return _mm256_movemask_ps(a.val); } -inline int v_signmask(const v_float64x4& a) -{ return _mm256_movemask_pd(a.val); } - -inline int v_signmask(const v_int32x8& a) -{ return v_signmask(v_reinterpret_as_f32(a)); } -inline int v_signmask(const v_uint32x8& a) -{ return v_signmask(v_reinterpret_as_f32(a)); } - -inline int v_signmask(const v_int64x4& a) -{ return v_signmask(v_reinterpret_as_f64(a)); } -inline int v_signmask(const v_uint64x4& a) -{ return v_signmask(v_reinterpret_as_f64(a)); } - -inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -/** Checks **/ -#define OPENCV_HAL_IMPL_AVX_CHECK(_Tpvec, allmask) \ - inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ - inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } -OPENCV_HAL_IMPL_AVX_CHECK(v_uint8x32, -1) -OPENCV_HAL_IMPL_AVX_CHECK(v_int8x32, -1) -OPENCV_HAL_IMPL_AVX_CHECK(v_uint32x8, 255) -OPENCV_HAL_IMPL_AVX_CHECK(v_int32x8, 255) -OPENCV_HAL_IMPL_AVX_CHECK(v_uint64x4, 15) -OPENCV_HAL_IMPL_AVX_CHECK(v_int64x4, 15) -OPENCV_HAL_IMPL_AVX_CHECK(v_float32x8, 255) -OPENCV_HAL_IMPL_AVX_CHECK(v_float64x4, 15) - -#define OPENCV_HAL_IMPL_AVX_CHECK_SHORT(_Tpvec) \ - inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ - inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } -OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_uint16x16) -OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_int16x16) - -////////// Other math ///////// - -/** Some frequent operations **/ -#if CV_FMA3 -#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } -#else -#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } -#endif - -#define OPENCV_HAL_IMPL_AVX_MISC(_Tpvec, suffix) \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(_mm256_sqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_AVX_MULADD(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_MULADD(v_float64x4, pd) -OPENCV_HAL_IMPL_AVX_MISC(v_float32x8, ps) -OPENCV_HAL_IMPL_AVX_MISC(v_float64x4, pd) - -inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x8 v_invsqrt(const v_float32x8& x) -{ - v_float32x8 half = v_mul(x, v256_setall_f32(0.5)); - v_float32x8 t = v_float32x8(_mm256_rsqrt_ps(x.val)); - // todo: _mm256_fnmsub_ps - t = v_mul(t, v_sub(v256_setall_f32(1.5), v_mul(v_mul(t, t), half))); - return t; -} - -inline v_float64x4 v_invsqrt(const v_float64x4& x) -{ - return v_div(v256_setall_f64(1.), v_sqrt(x)); -} - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_AVX_ABS(_Tpvec, suffix) \ - inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ - { return v_u##_Tpvec(_mm256_abs_##suffix(x.val)); } - -OPENCV_HAL_IMPL_AVX_ABS(int8x32, epi8) -OPENCV_HAL_IMPL_AVX_ABS(int16x16, epi16) -OPENCV_HAL_IMPL_AVX_ABS(int32x8, epi32) - -inline v_float32x8 v_abs(const v_float32x8& x) -{ return v_and(x, v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)))); } -inline v_float64x4 v_abs(const v_float64x4& x) -{ return v_and(x, v_float64x4(_mm256_castsi256_pd(_mm256_srli_epi64(_mm256_set1_epi64x(-1), 1)))); } - -/** Absolute difference **/ -inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) -{ - v_int8x32 d = v_sub_wrap(a, b); - v_int8x32 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} - -inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) -{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } - -inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 d = v_sub(a, b); - v_int32x8 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) -{ - v_int8x32 d = v_sub(a, b); - v_int8x32 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x8 v_round(const v_float32x8& a) -{ return v_int32x8(_mm256_cvtps_epi32(a.val)); } - -inline v_int32x8 v_round(const v_float64x4& a) -{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvtpd_epi32(a.val))); } - -inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) -{ - __m128i ai = _mm256_cvtpd_epi32(a.val), bi = _mm256_cvtpd_epi32(b.val); - return v_int32x8(_v256_combine(ai, bi)); -} - -inline v_int32x8 v_trunc(const v_float32x8& a) -{ return v_int32x8(_mm256_cvttps_epi32(a.val)); } - -inline v_int32x8 v_trunc(const v_float64x4& a) -{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvttpd_epi32(a.val))); } - -inline v_int32x8 v_floor(const v_float32x8& a) -{ return v_int32x8(_mm256_cvttps_epi32(_mm256_floor_ps(a.val))); } - -inline v_int32x8 v_floor(const v_float64x4& a) -{ return v_trunc(v_float64x4(_mm256_floor_pd(a.val))); } - -inline v_int32x8 v_ceil(const v_float32x8& a) -{ return v_int32x8(_mm256_cvttps_epi32(_mm256_ceil_ps(a.val))); } - -inline v_int32x8 v_ceil(const v_float64x4& a) -{ return v_trunc(v_float64x4(_mm256_ceil_pd(a.val))); } - -/** To float **/ -inline v_float32x8 v_cvt_f32(const v_int32x8& a) -{ return v_float32x8(_mm256_cvtepi32_ps(a.val)); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a) -{ return v_float32x8(_mm256_castps128_ps256(_mm256_cvtpd_ps(a.val))); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) -{ - __m128 af = _mm256_cvtpd_ps(a.val), bf = _mm256_cvtpd_ps(b.val); - return v_float32x8(_v256_combine(af, bf)); -} - -inline v_float64x4 v_cvt_f64(const v_int32x8& a) -{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_low(a.val))); } - -inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) -{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_high(a.val))); } - -inline v_float64x4 v_cvt_f64(const v_float32x8& a) -{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_low(a.val))); } - -inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) -{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_high(a.val))); } - -// from (Mysticial and wim) https://stackoverflow.com/q/41144668 -inline v_float64x4 v_cvt_f64(const v_int64x4& v) -{ - // constants encoded as floating-point - __m256i magic_i_lo = _mm256_set1_epi64x(0x4330000000000000); // 2^52 - __m256i magic_i_hi32 = _mm256_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 - __m256i magic_i_all = _mm256_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 - __m256d magic_d_all = _mm256_castsi256_pd(magic_i_all); - - // Blend the 32 lowest significant bits of v with magic_int_lo - __m256i v_lo = _mm256_blend_epi32(magic_i_lo, v.val, 0x55); - // Extract the 32 most significant bits of v - __m256i v_hi = _mm256_srli_epi64(v.val, 32); - // Flip the msb of v_hi and blend with 0x45300000 - v_hi = _mm256_xor_si256(v_hi, magic_i_hi32); - // Compute in double precision - __m256d v_hi_dbl = _mm256_sub_pd(_mm256_castsi256_pd(v_hi), magic_d_all); - // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition - __m256d result = _mm256_add_pd(v_hi_dbl, _mm256_castsi256_pd(v_lo)); - return v_float64x4(result); -} - -////////////// Lookup table access //////////////////// - -inline v_int8x32 v256_lut(const schar* tab, const int* idx) -{ - return v_int8x32(_mm256_setr_epi8(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], - tab[idx[16]], tab[idx[17]], tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], - tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], tab[idx[30]], tab[idx[31]])); -} -inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x32(_mm256_setr_epi16(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), *(const short*)(tab + idx[ 3]), - *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), - *(const short*)(tab + idx[ 8]), *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), - *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), *(const short*)(tab + idx[15]))); -} -inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x32(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 1)); -} -inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } - -inline v_int16x16 v256_lut(const short* tab, const int* idx) -{ - return v_int16x16(_mm256_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); -} -inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x16(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 2)); -} -inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int16x16(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 2));//Looks like intrinsic has wrong definition -#else - return v_int16x16(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 2)); -#endif -} -inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } - -inline v_int32x8 v256_lut(const int* tab, const int* idx) -{ - return v_int32x8(_mm256_i32gather_epi32(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); -} -inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int32x8(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); -#else - return v_int32x8(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); -#endif -} -inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) -{ - return v_int32x8(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); -} -inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } - -inline v_int64x4 v256_lut(const int64* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int64x4(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 8)); -#else - return v_int64x4(_mm256_i32gather_epi64(tab, _mm_loadu_si128((const __m128i*)idx), 8)); -#endif -} -inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) -{ - return v_int64x4(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); -} -inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } -inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } - -inline v_float32x8 v256_lut(const float* tab, const int* idx) -{ - return v_float32x8(_mm256_i32gather_ps(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); -} -inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } -inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } - -inline v_float64x4 v256_lut(const double* tab, const int* idx) -{ - return v_float64x4(_mm256_i32gather_pd(tab, _mm_loadu_si128((const __m128i*)idx), 8)); -} -inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) { return v_float64x4(_v256_combine(_mm_loadu_pd(tab + idx[0]), _mm_loadu_pd(tab + idx[1]))); } - -inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) -{ - return v_int32x8(_mm256_i32gather_epi32(tab, idxvec.val, 4)); -} - -inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) -{ - return v_float32x8(_mm256_i32gather_ps(tab, idxvec.val, 4)); -} - -inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) -{ - return v_float64x4(_mm256_i32gather_pd(tab, _mm256_castsi256_si128(idxvec.val), 8)); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) -{ - int CV_DECL_ALIGNED(32) idx[8]; - v_store_aligned(idx, idxvec); - __m128 z = _mm_setzero_ps(); - __m128 xy01, xy45, xy23, xy67; - xy01 = _mm_loadl_pi(z, (const __m64*)(tab + idx[0])); - xy01 = _mm_loadh_pi(xy01, (const __m64*)(tab + idx[1])); - xy45 = _mm_loadl_pi(z, (const __m64*)(tab + idx[4])); - xy45 = _mm_loadh_pi(xy45, (const __m64*)(tab + idx[5])); - __m256 xy0145 = _v256_combine(xy01, xy45); - xy23 = _mm_loadl_pi(z, (const __m64*)(tab + idx[2])); - xy23 = _mm_loadh_pi(xy23, (const __m64*)(tab + idx[3])); - xy67 = _mm_loadl_pi(z, (const __m64*)(tab + idx[6])); - xy67 = _mm_loadh_pi(xy67, (const __m64*)(tab + idx[7])); - __m256 xy2367 = _v256_combine(xy23, xy67); - - __m256 xxyy0145 = _mm256_unpacklo_ps(xy0145, xy2367); - __m256 xxyy2367 = _mm256_unpackhi_ps(xy0145, xy2367); - - x = v_float32x8(_mm256_unpacklo_ps(xxyy0145, xxyy2367)); - y = v_float32x8(_mm256_unpackhi_ps(xxyy0145, xxyy2367)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_low(idx, idxvec); - __m128d xy0 = _mm_loadu_pd(tab + idx[0]); - __m128d xy2 = _mm_loadu_pd(tab + idx[2]); - __m128d xy1 = _mm_loadu_pd(tab + idx[1]); - __m128d xy3 = _mm_loadu_pd(tab + idx[3]); - __m256d xy02 = _v256_combine(xy0, xy2); - __m256d xy13 = _v256_combine(xy1, xy3); - - x = v_float64x4(_mm256_unpacklo_pd(xy02, xy13)); - y = v_float64x4(_mm256_unpackhi_pd(xy02, xy13)); -} - -inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) -{ - return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); -} -inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x32 v_interleave_quads(const v_int8x32& vec) -{ - return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); -} -inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) -{ - return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); -} -inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x16 v_interleave_quads(const v_int16x16& vec) -{ - return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); -} -inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) -{ - return v_int32x8(_mm256_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); -} -inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x32 v_pack_triplets(const v_int8x32& vec) -{ - return v_int8x32(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))), - _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_pack_triplets(const v_int16x16& vec) -{ - return v_int16x16(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))), - _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_pack_triplets(const v_int32x8& vec) -{ - return v_int32x8(_mm256_permutevar8x32_epi32(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_pack_triplets(const v_float32x8& vec) -{ - return v_float32x8(_mm256_permutevar8x32_ps(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} - -////////// Matrix operations ///////// - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) -{ return v_int32x8(_mm256_madd_epi16(a.val, b.val)); } -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) -{ - __m256i even = _mm256_mul_epi32(a.val, b.val); - __m256i odd = _mm256_mul_epi32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); - return v_int64x4(_mm256_add_epi64(even, odd)); -} -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i even_m = _mm256_set1_epi32(0xFF00FF00); - __m256i even_a = _mm256_blendv_epi8(a.val, _mm256_setzero_si256(), even_m); - __m256i odd_a = _mm256_srli_epi16(a.val, 8); - - __m256i even_b = _mm256_blendv_epi8(b.val, _mm256_setzero_si256(), even_m); - __m256i odd_b = _mm256_srli_epi16(b.val, 8); - - __m256i prod0 = _mm256_madd_epi16(even_a, even_b); - __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); - return v_uint32x8(_mm256_add_epi32(prod0, prod1)); -} -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) -{ - __m256i even_a = _mm256_srai_epi16(_mm256_bslli_epi128(a.val, 1), 8); - __m256i odd_a = _mm256_srai_epi16(a.val, 8); - - __m256i even_b = _mm256_srai_epi16(_mm256_bslli_epi128(b.val, 1), 8); - __m256i odd_b = _mm256_srai_epi16(b.val, 8); - - __m256i prod0 = _mm256_madd_epi16(even_a, even_b); - __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); - return v_int32x8(_mm256_add_epi32(prod0, prod1)); -} -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i mullo = _mm256_mullo_epi16(a.val, b.val); - __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); - __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); - __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); - - __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); - __m256i p13 = _mm256_srli_epi64(mul0, 32); - __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); - __m256i p57 = _mm256_srli_epi64(mul1, 32); - - __m256i p15_ = _mm256_add_epi64(p02, p13); - __m256i p9d_ = _mm256_add_epi64(p46, p57); - - return v_uint64x4(_mm256_add_epi64( - _mm256_unpacklo_epi64(p15_, p9d_), - _mm256_unpackhi_epi64(p15_, p9d_) - )); -} -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) -{ - __m256i prod = _mm256_madd_epi16(a.val, b.val); - __m256i sign = _mm256_srai_epi32(prod, 31); - - __m256i lo = _mm256_unpacklo_epi32(prod, sign); - __m256i hi = _mm256_unpackhi_epi32(prod, sign); - - return v_int64x4(_mm256_add_epi64( - _mm256_unpacklo_epi64(lo, hi), - _mm256_unpackhi_epi64(lo, hi) - )); -} -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) -{ return v_dotprod(a, b); } -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod(a, b); } -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i mullo = _mm256_mullo_epi16(a.val, b.val); - __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); - __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); - __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); - - __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); - __m256i p13 = _mm256_srli_epi64(mul0, 32); - __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); - __m256i p57 = _mm256_srli_epi64(mul1, 32); - - __m256i p15_ = _mm256_add_epi64(p02, p13); - __m256i p9d_ = _mm256_add_epi64(p46, p57); - - return v_uint64x4(_mm256_add_epi64(p15_, p9d_)); -} -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) -{ - __m256i prod = _mm256_madd_epi16(a.val, b.val); - __m256i sign = _mm256_srai_epi32(prod, 31); - __m256i lo = _mm256_unpacklo_epi32(prod, sign); - __m256i hi = _mm256_unpackhi_epi32(prod, sign); - return v_int64x4(_mm256_add_epi64(lo, hi)); -} -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_dotprod_expand(a, b, c); } - -#define OPENCV_HAL_AVX_SPLAT2_PS(a, im) \ - v_float32x8(_mm256_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) - -inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& m3) -{ - v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); - v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); - v_float32x8 v37 = OPENCV_HAL_AVX_SPLAT2_PS(v, 3); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); -} - -inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& a) -{ - v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); - v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); -} - -#define OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m256i t0 = cast_from(_mm256_unpacklo_##suffix(a0.val, a1.val)); \ - __m256i t1 = cast_from(_mm256_unpacklo_##suffix(a2.val, a3.val)); \ - __m256i t2 = cast_from(_mm256_unpackhi_##suffix(a0.val, a1.val)); \ - __m256i t3 = cast_from(_mm256_unpackhi_##suffix(a2.val, a3.val)); \ - b0.val = cast_to(_mm256_unpacklo_epi64(t0, t1)); \ - b1.val = cast_to(_mm256_unpackhi_epi64(t0, t1)); \ - b2.val = cast_to(_mm256_unpacklo_epi64(t2, t3)); \ - b3.val = cast_to(_mm256_unpackhi_epi64(t2, t3)); \ - } - -OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_uint32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_int32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_float32x8, ps, _mm256_castps_si256, _mm256_castsi256_ps) - -//////////////// Value reordering /////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_AVX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(_v256_extract_low(a.val)); \ - b1.val = intrin(_v256_extract_high(a.val)); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v256_extract_low(a.val))); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v256_extract_high(a.val))); } \ - inline _Tpwvec v256_load_expand(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ - return _Tpwvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX_EXPAND(v_uint8x32, v_uint16x16, uchar, _mm256_cvtepu8_epi16) -OPENCV_HAL_IMPL_AVX_EXPAND(v_int8x32, v_int16x16, schar, _mm256_cvtepi8_epi16) -OPENCV_HAL_IMPL_AVX_EXPAND(v_uint16x16, v_uint32x8, ushort, _mm256_cvtepu16_epi32) -OPENCV_HAL_IMPL_AVX_EXPAND(v_int16x16, v_int32x8, short, _mm256_cvtepi16_epi32) -OPENCV_HAL_IMPL_AVX_EXPAND(v_uint32x8, v_uint64x4, unsigned, _mm256_cvtepu32_epi64) -OPENCV_HAL_IMPL_AVX_EXPAND(v_int32x8, v_int64x4, int, _mm256_cvtepi32_epi64) - -#define OPENCV_HAL_IMPL_AVX_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ - return _Tpvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_uint32x8, uchar, _mm256_cvtepu8_epi32) -OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_int32x8, schar, _mm256_cvtepi8_epi32) - -/* pack */ -// 16 -inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) -{ return v_int8x32(_v256_shuffle_odd_64(_mm256_packs_epi16(a.val, b.val))); } - -inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i t = _mm256_set1_epi16(255); - __m256i a1 = _mm256_min_epu16(a.val, t); - __m256i b1 = _mm256_min_epu16(b.val, t); - return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a1, b1))); -} - -inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a.val, b.val))); -} - -inline void v_pack_store(schar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar* ptr, const v_uint16x16& a) -{ - const __m256i m = _mm256_set1_epi16(255); - __m256i am = _mm256_min_epu16(a.val, m); - am = _v256_shuffle_odd_64(_mm256_packus_epi16(am, am)); - v_store_low(ptr, v_uint8x32(am)); -} - -inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); - return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) -{ - v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x16& a) -{ - v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 32 -inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) -{ return v_int16x16(_v256_shuffle_odd_64(_mm256_packs_epi32(a.val, b.val))); } - -inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } - -inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_mm256_packus_epi32(a.val, b.val))); } - -inline void v_pack_store(short* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x8& a) -{ - const __m256i m = _mm256_set1_epi32(65535); - __m256i am = _mm256_min_epu32(a.val, m); - am = _v256_shuffle_odd_64(_mm256_packus_epi32(am, am)); - v_store_low(ptr, v_uint16x16(am)); -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - - -template inline -v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) -{ - // we assume that n > 0, and so the shifted 32-bit values can be treated as signed numbers. - v_uint32x8 delta = v256_setall_u32(1 << (n-1)); - return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) -{ - v_uint32x8 delta = v256_setall_u32(1 << (n-1)); - v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x8& a) -{ - v_int32x8 delta = v256_setall_s32(1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 64 -// Non-saturating pack -inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) -{ - __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); - __m256i b0 = _mm256_shuffle_epi32(b.val, _MM_SHUFFLE(0, 0, 2, 0)); - __m256i ab = _mm256_unpacklo_epi64(a0, b0); // a0, a1, b0, b1, a2, a3, b2, b3 - return v_uint32x8(_v256_shuffle_odd_64(ab)); -} - -inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); - v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); -} - -inline void v_pack_store(int* ptr, const v_int64x4& b) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } - -template inline -v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) -{ - v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) -{ - v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x4& a) -{ - v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// pack boolean -inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i ab = _mm256_packs_epi16(a.val, b.val); - return v_uint8x32(_v256_shuffle_odd_64(ab)); -} - -inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d) -{ - __m256i ab = _mm256_packs_epi32(a.val, b.val); - __m256i cd = _mm256_packs_epi32(c.val, d.val); - - __m256i abcd = _v256_shuffle_odd_64(_mm256_packs_epi16(ab, cd)); - return v_uint8x32(_mm256_shuffle_epi32(abcd, _MM_SHUFFLE(3, 1, 2, 0))); -} - -inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, - const v_uint64x4& g, const v_uint64x4& h) -{ - __m256i ab = _mm256_packs_epi32(a.val, b.val); - __m256i cd = _mm256_packs_epi32(c.val, d.val); - __m256i ef = _mm256_packs_epi32(e.val, f.val); - __m256i gh = _mm256_packs_epi32(g.val, h.val); - - __m256i abcd = _mm256_packs_epi32(ab, cd); - __m256i efgh = _mm256_packs_epi32(ef, gh); - __m256i pkall = _v256_shuffle_odd_64(_mm256_packs_epi16(abcd, efgh)); - - __m256i rev = _mm256_alignr_epi8(pkall, pkall, 8); - return v_uint8x32(_mm256_unpacklo_epi16(pkall, rev)); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_AVX_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint8x32) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int8x32) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint16x16) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int16x16) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint32x8) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int32x8) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint64x4) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_int64x4) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_float32x8) -OPENCV_HAL_IMPL_AVX_EXTRACT(v_float64x4) - -template -inline uchar v_extract_n(v_uint8x32 a) -{ - return (uchar)_v256_extract_epi8(a.val); -} - -template -inline schar v_extract_n(v_int8x32 a) -{ - return (schar)v_extract_n(v_reinterpret_as_u8(a)); -} - -template -inline ushort v_extract_n(v_uint16x16 a) -{ - return (ushort)_v256_extract_epi16(a.val); -} - -template -inline short v_extract_n(v_int16x16 a) -{ - return (short)v_extract_n(v_reinterpret_as_u16(a)); -} - -template -inline uint v_extract_n(v_uint32x8 a) -{ - return (uint)_v256_extract_epi32(a.val); -} - -template -inline int v_extract_n(v_int32x8 a) -{ - return (int)v_extract_n(v_reinterpret_as_u32(a)); -} - -template -inline uint64 v_extract_n(v_uint64x4 a) -{ - return (uint64)_v256_extract_epi64(a.val); -} - -template -inline int64 v_extract_n(v_int64x4 v) -{ - return (int64)v_extract_n(v_reinterpret_as_u64(v)); -} - -template -inline float v_extract_n(v_float32x8 v) -{ - union { uint iv; float fv; } d; - d.iv = v_extract_n(v_reinterpret_as_u32(v)); - return d.fv; -} - -template -inline double v_extract_n(v_float64x4 v) -{ - union { uint64 iv; double dv; } d; - d.iv = v_extract_n(v_reinterpret_as_u64(v)); - return d.dv; -} - -template -inline v_uint32x8 v_broadcast_element(v_uint32x8 a) -{ - static const __m256i perm = _mm256_set1_epi32((char)i); - return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); -} - -template -inline v_int32x8 v_broadcast_element(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -template -inline v_float32x8 v_broadcast_element(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } - - -///////////////////// load deinterleave ///////////////////////////// - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - - const __m256i sh = _mm256_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, - 0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15); - __m256i p0 = _mm256_shuffle_epi8(ab0, sh); - __m256i p1 = _mm256_shuffle_epi8(ab1, sh); - __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint8x32(a0); - b = v_uint8x32(b0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - - const __m256i sh = _mm256_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, - 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15); - __m256i p0 = _mm256_shuffle_epi8(ab0, sh); - __m256i p1 = _mm256_shuffle_epi8(ab1, sh); - __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint16x16(a0); - b = v_uint16x16(b0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - - enum { sh = 0+2*4+1*16+3*64 }; - __m256i p0 = _mm256_shuffle_epi32(ab0, sh); - __m256i p1 = _mm256_shuffle_epi32(ab1, sh); - __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint32x8(a0); - b = v_uint32x8(b0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) -{ - __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); - - __m256i pl = _mm256_permute2x128_si256(ab0, ab1, 0 + 2*16); - __m256i ph = _mm256_permute2x128_si256(ab0, ab1, 1 + 3*16); - __m256i a0 = _mm256_unpacklo_epi64(pl, ph); - __m256i b0 = _mm256_unpackhi_epi64(pl, ph); - a = v_uint64x4(a0); - b = v_uint64x4(b0); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); - - __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); - __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); - - const __m256i m0 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - - __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); - __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); - - const __m256i - sh_b = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, - 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), - sh_g = _mm256_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, - 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), - sh_r = _mm256_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, - 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); - b0 = _mm256_shuffle_epi8(b0, sh_b); - g0 = _mm256_shuffle_epi8(g0, sh_g); - r0 = _mm256_shuffle_epi8(r0, sh_r); - - a = v_uint8x32(b0); - b = v_uint8x32(g0); - c = v_uint8x32(r0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - - __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); - __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); - - const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); - __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); - const __m256i sh_b = _mm256_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _mm256_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, - 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); - const __m256i sh_r = _mm256_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - b0 = _mm256_shuffle_epi8(b0, sh_b); - g0 = _mm256_shuffle_epi8(g0, sh_g); - r0 = _mm256_shuffle_epi8(r0, sh_r); - - a = v_uint16x16(b0); - b = v_uint16x16(g0); - c = v_uint16x16(r0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - - __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); - __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); - - __m256i b0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_low, s02_high, 0x24), bgr1, 0x92); - __m256i g0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_high, s02_low, 0x92), bgr1, 0x24); - __m256i r0 = _mm256_blend_epi32(_mm256_blend_epi32(bgr1, s02_low, 0x24), s02_high, 0x92); - - b0 = _mm256_shuffle_epi32(b0, 0x6c); - g0 = _mm256_shuffle_epi32(g0, 0xb1); - r0 = _mm256_shuffle_epi32(r0, 0xc6); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - - __m256i s01 = _mm256_blend_epi32(bgr0, bgr1, 0xf0); - __m256i s12 = _mm256_blend_epi32(bgr1, bgr2, 0xf0); - __m256i s20r = _mm256_permute4x64_epi64(_mm256_blend_epi32(bgr2, bgr0, 0xf0), 0x1b); - __m256i b0 = _mm256_unpacklo_epi64(s01, s20r); - __m256i g0 = _mm256_alignr_epi8(s12, s01, 8); - __m256i r0 = _mm256_unpackhi_epi64(s20r, s12); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); - __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 96)); - const __m256i sh = _mm256_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, - 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); - - __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); - __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); - __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); - __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); - - __m256i p01l = _mm256_unpacklo_epi32(p0, p1); - __m256i p01h = _mm256_unpackhi_epi32(p0, p1); - __m256i p23l = _mm256_unpacklo_epi32(p2, p3); - __m256i p23h = _mm256_unpackhi_epi32(p2, p3); - - __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); - __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); - __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); - __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi32(pll, plh); - __m256i g0 = _mm256_unpackhi_epi32(pll, plh); - __m256i r0 = _mm256_unpacklo_epi32(phl, phh); - __m256i a0 = _mm256_unpackhi_epi32(phl, phh); - - a = v_uint8x32(b0); - b = v_uint8x32(g0); - c = v_uint8x32(r0); - d = v_uint8x32(a0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d ) -{ - __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); - __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 48)); - const __m256i sh = _mm256_setr_epi8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15, - 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15); - __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); - __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); - __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); - __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); - - __m256i p01l = _mm256_unpacklo_epi32(p0, p1); - __m256i p01h = _mm256_unpackhi_epi32(p0, p1); - __m256i p23l = _mm256_unpacklo_epi32(p2, p3); - __m256i p23h = _mm256_unpackhi_epi32(p2, p3); - - __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); - __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); - __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); - __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi32(pll, plh); - __m256i g0 = _mm256_unpackhi_epi32(pll, plh); - __m256i r0 = _mm256_unpacklo_epi32(phl, phh); - __m256i a0 = _mm256_unpackhi_epi32(phl, phh); - - a = v_uint16x16(b0); - b = v_uint16x16(g0); - c = v_uint16x16(r0); - d = v_uint16x16(a0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) -{ - __m256i p0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i p1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - __m256i p2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); - __m256i p3 = _mm256_loadu_si256((const __m256i*)(ptr + 24)); - - __m256i p01l = _mm256_unpacklo_epi32(p0, p1); - __m256i p01h = _mm256_unpackhi_epi32(p0, p1); - __m256i p23l = _mm256_unpacklo_epi32(p2, p3); - __m256i p23h = _mm256_unpackhi_epi32(p2, p3); - - __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); - __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); - __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); - __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi32(pll, plh); - __m256i g0 = _mm256_unpackhi_epi32(pll, plh); - __m256i r0 = _mm256_unpacklo_epi32(phl, phh); - __m256i a0 = _mm256_unpackhi_epi32(phl, phh); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); - d = v_uint32x8(a0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) -{ - __m256i bgra0 = _mm256_loadu_si256((const __m256i*)ptr); - __m256i bgra1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); - __m256i bgra2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); - __m256i bgra3 = _mm256_loadu_si256((const __m256i*)(ptr + 12)); - - __m256i l02 = _mm256_permute2x128_si256(bgra0, bgra2, 0 + 2*16); - __m256i h02 = _mm256_permute2x128_si256(bgra0, bgra2, 1 + 3*16); - __m256i l13 = _mm256_permute2x128_si256(bgra1, bgra3, 0 + 2*16); - __m256i h13 = _mm256_permute2x128_si256(bgra1, bgra3, 1 + 3*16); - - __m256i b0 = _mm256_unpacklo_epi64(l02, l13); - __m256i g0 = _mm256_unpackhi_epi64(l02, l13); - __m256i r0 = _mm256_unpacklo_epi64(h02, h13); - __m256i a0 = _mm256_unpackhi_epi64(h02, h13); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); - d = v_uint64x4(a0); -} - -///////////////////////////// store interleave ///////////////////////////////////// - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi8(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi8(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 32), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 32), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 32), xy1); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi16(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi16(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 16), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 16), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 16), xy1); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi32(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi32(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 8), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 8), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 8), xy1); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = _mm256_unpacklo_epi64(x.val, y.val); - __m256i xy_h = _mm256_unpackhi_epi64(x.val, y.val); - - __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); - __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, xy0); - _mm256_stream_si256((__m256i*)(ptr + 4), xy1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, xy0); - _mm256_store_si256((__m256i*)(ptr + 4), xy1); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, xy0); - _mm256_storeu_si256((__m256i*)(ptr + 4), xy1); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _mm256_setr_epi8( - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); - const __m256i sh_g = _mm256_setr_epi8( - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); - const __m256i sh_r = _mm256_setr_epi8( - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); - - __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); - __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); - __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); - - const __m256i m0 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - - __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); - __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); - __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); - - __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - __m256i bgr1 = _mm256_permute2x128_si256(p2, p0, 0 + 3*16); - __m256i bgr2 = _mm256_permute2x128_si256(p1, p2, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 32), bgr1); - _mm256_stream_si256((__m256i*)(ptr + 64), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 32), bgr1); - _mm256_store_si256((__m256i*)(ptr + 64), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgr1); - _mm256_storeu_si256((__m256i*)(ptr + 64), bgr2); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _mm256_setr_epi8( - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _mm256_setr_epi8( - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); - const __m256i sh_r = _mm256_setr_epi8( - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - - __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); - __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); - __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); - - const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - - __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); - __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); - __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); - - __m256i bgr0 = _mm256_permute2x128_si256(p0, p2, 0 + 2*16); - //__m256i bgr1 = p1; - __m256i bgr2 = _mm256_permute2x128_si256(p0, p2, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 16), p1); - _mm256_stream_si256((__m256i*)(ptr + 32), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 16), p1); - _mm256_store_si256((__m256i*)(ptr + 32), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 16), p1); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgr2); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i b0 = _mm256_shuffle_epi32(a.val, 0x6c); - __m256i g0 = _mm256_shuffle_epi32(b.val, 0xb1); - __m256i r0 = _mm256_shuffle_epi32(c.val, 0xc6); - - __m256i p0 = _mm256_blend_epi32(_mm256_blend_epi32(b0, g0, 0x92), r0, 0x24); - __m256i p1 = _mm256_blend_epi32(_mm256_blend_epi32(g0, r0, 0x92), b0, 0x24); - __m256i p2 = _mm256_blend_epi32(_mm256_blend_epi32(r0, b0, 0x92), g0, 0x24); - - __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); - //__m256i bgr1 = p2; - __m256i bgr2 = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 8), p2); - _mm256_stream_si256((__m256i*)(ptr + 16), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 8), p2); - _mm256_store_si256((__m256i*)(ptr + 16), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 8), p2); - _mm256_storeu_si256((__m256i*)(ptr + 16), bgr2); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i s01 = _mm256_unpacklo_epi64(a.val, b.val); - __m256i s12 = _mm256_unpackhi_epi64(b.val, c.val); - __m256i s20 = _mm256_blend_epi32(c.val, a.val, 0xcc); - - __m256i bgr0 = _mm256_permute2x128_si256(s01, s20, 0 + 2*16); - __m256i bgr1 = _mm256_blend_epi32(s01, s12, 0x0f); - __m256i bgr2 = _mm256_permute2x128_si256(s20, s12, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgr0); - _mm256_stream_si256((__m256i*)(ptr + 4), bgr1); - _mm256_stream_si256((__m256i*)(ptr + 8), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgr0); - _mm256_store_si256((__m256i*)(ptr + 4), bgr1); - _mm256_store_si256((__m256i*)(ptr + 8), bgr2); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgr0); - _mm256_storeu_si256((__m256i*)(ptr + 4), bgr1); - _mm256_storeu_si256((__m256i*)(ptr + 8), bgr2); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, - const v_uint8x32& c, const v_uint8x32& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi8(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi8(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi8(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi8(c.val, d.val); - - __m256i bgra0_ = _mm256_unpacklo_epi16(bg0, ra0); - __m256i bgra1_ = _mm256_unpackhi_epi16(bg0, ra0); - __m256i bgra2_ = _mm256_unpacklo_epi16(bg1, ra1); - __m256i bgra3_ = _mm256_unpackhi_epi16(bg1, ra1); - - __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); - __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); - __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 32), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 64), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 96), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 32), bgra1); - _mm256_store_si256((__m256i*)(ptr + 64), bgra2); - _mm256_store_si256((__m256i*)(ptr + 96), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 64), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 96), bgra3); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, - const v_uint16x16& c, const v_uint16x16& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi16(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi16(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi16(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi16(c.val, d.val); - - __m256i bgra0_ = _mm256_unpacklo_epi32(bg0, ra0); - __m256i bgra1_ = _mm256_unpackhi_epi32(bg0, ra0); - __m256i bgra2_ = _mm256_unpacklo_epi32(bg1, ra1); - __m256i bgra3_ = _mm256_unpackhi_epi32(bg1, ra1); - - __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); - __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); - __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 16), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 32), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 48), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 16), bgra1); - _mm256_store_si256((__m256i*)(ptr + 32), bgra2); - _mm256_store_si256((__m256i*)(ptr + 48), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 16), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 32), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 48), bgra3); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi32(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi32(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi32(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi32(c.val, d.val); - - __m256i bgra0_ = _mm256_unpacklo_epi64(bg0, ra0); - __m256i bgra1_ = _mm256_unpackhi_epi64(bg0, ra0); - __m256i bgra2_ = _mm256_unpacklo_epi64(bg1, ra1); - __m256i bgra3_ = _mm256_unpackhi_epi64(bg1, ra1); - - __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); - __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); - __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 8), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 16), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 24), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 8), bgra1); - _mm256_store_si256((__m256i*)(ptr + 16), bgra2); - _mm256_store_si256((__m256i*)(ptr + 24), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 8), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 16), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 24), bgra3); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, - const v_uint64x4& c, const v_uint64x4& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = _mm256_unpacklo_epi64(a.val, b.val); - __m256i bg1 = _mm256_unpackhi_epi64(a.val, b.val); - __m256i ra0 = _mm256_unpacklo_epi64(c.val, d.val); - __m256i ra1 = _mm256_unpackhi_epi64(c.val, d.val); - - __m256i bgra0 = _mm256_permute2x128_si256(bg0, ra0, 0 + 2*16); - __m256i bgra1 = _mm256_permute2x128_si256(bg1, ra1, 0 + 2*16); - __m256i bgra2 = _mm256_permute2x128_si256(bg0, ra0, 1 + 3*16); - __m256i bgra3 = _mm256_permute2x128_si256(bg1, ra1, 1 + 3*16); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm256_stream_si256((__m256i*)ptr, bgra0); - _mm256_stream_si256((__m256i*)(ptr + 4), bgra1); - _mm256_stream_si256((__m256i*)(ptr + 8), bgra2); - _mm256_stream_si256((__m256i*)(ptr + 12), bgra3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm256_store_si256((__m256i*)ptr, bgra0); - _mm256_store_si256((__m256i*)(ptr + 4), bgra1); - _mm256_store_si256((__m256i*)(ptr + 8), bgra2); - _mm256_store_si256((__m256i*)(ptr + 12), bgra3); - } - else - { - _mm256_storeu_si256((__m256i*)ptr, bgra0); - _mm256_storeu_si256((__m256i*)(ptr + 4), bgra1); - _mm256_storeu_si256((__m256i*)(ptr + 8), bgra2); - _mm256_storeu_si256((__m256i*)(ptr + 12), bgra3); - } -} - -#define OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) -OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) - -// -// FP16 -// - -inline v_float32x8 v256_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - return v_float32x8(_mm256_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); -#else - float CV_DECL_ALIGNED(32) buf[8]; - for (int i = 0; i < 8; i++) - buf[i] = (float)ptr[i]; - return v256_load_aligned(buf); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x8& a) -{ -#if CV_FP16 - __m128i ah = _mm256_cvtps_ph(a.val, 0); - _mm_storeu_si128((__m128i*)ptr, ah); -#else - float CV_DECL_ALIGNED(32) buf[8]; - v_store_aligned(buf, a); - for (int i = 0; i < 8; i++) - ptr[i] = hfloat(buf[i]); -#endif -} - -// -// end of FP16 -// - -inline void v256_cleanup() { _mm256_zeroall(); } - -#include "intrin_math.hpp" -inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } -inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } -inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } -inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } - -inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } -inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } -inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_AVX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_AVX_HPP +#define OPENCV_HAL_INTRIN_AVX_HPP + +#define CV_SIMD256 1 +#define CV_SIMD256_64F 1 +#define CV_SIMD256_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Utils //////////// + +inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) +{ return _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1); } + +inline __m256 _v256_combine(const __m128& lo, const __m128& hi) +{ return _mm256_insertf128_ps(_mm256_castps128_ps256(lo), hi, 1); } + +inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) +{ return _mm256_insertf128_pd(_mm256_castpd128_pd256(lo), hi, 1); } + +inline int _v_cvtsi256_si32(const __m256i& a) +{ return _mm_cvtsi128_si32(_mm256_castsi256_si128(a)); } + +inline __m256i _v256_shuffle_odd_64(const __m256i& v) +{ return _mm256_permute4x64_epi64(v, _MM_SHUFFLE(3, 1, 2, 0)); } + +inline __m256d _v256_shuffle_odd_64(const __m256d& v) +{ return _mm256_permute4x64_pd(v, _MM_SHUFFLE(3, 1, 2, 0)); } + +template +inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) +{ return _mm256_permute2x128_si256(a, b, imm); } + +template +inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) +{ return _mm256_permute2f128_ps(a, b, imm); } + +template +inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) +{ return _mm256_permute2f128_pd(a, b, imm); } + +template +inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } + +template +inline __m256i _v256_permute4x64(const __m256i& a) +{ return _mm256_permute4x64_epi64(a, imm); } + +template +inline __m256d _v256_permute4x64(const __m256d& a) +{ return _mm256_permute4x64_pd(a, imm); } + +template +inline _Tpvec v256_permute4x64(const _Tpvec& a) +{ return _Tpvec(_v256_permute4x64(a.val)); } + +inline __m128i _v256_extract_high(const __m256i& v) +{ return _mm256_extracti128_si256(v, 1); } + +inline __m128 _v256_extract_high(const __m256& v) +{ return _mm256_extractf128_ps(v, 1); } + +inline __m128d _v256_extract_high(const __m256d& v) +{ return _mm256_extractf128_pd(v, 1); } + +inline __m128i _v256_extract_low(const __m256i& v) +{ return _mm256_castsi256_si128(v); } + +inline __m128 _v256_extract_low(const __m256& v) +{ return _mm256_castps256_ps128(v); } + +inline __m128d _v256_extract_low(const __m256d& v) +{ return _mm256_castpd256_pd128(v); } + +inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) +{ + const __m256i m = _mm256_set1_epi32(65535); + __m256i am = _mm256_min_epu32(a, m); + __m256i bm = _mm256_min_epu32(b, m); + return _mm256_packus_epi32(am, bm); +} + +template +inline int _v256_extract_epi8(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi8(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 4)); + return _mm_extract_epi8(b, i & 15); // SSE4.1 +#endif +} + +template +inline int _v256_extract_epi16(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi16(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 3)); + return _mm_extract_epi16(b, i & 7); // SSE2 +#endif +} + +template +inline int _v256_extract_epi32(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi32(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 2)); + return _mm_extract_epi32(b, i & 3); // SSE4.1 +#endif +} + +template +inline int64 _v256_extract_epi64(const __m256i& a) +{ +#if defined(CV__SIMD_HAVE_mm256_extract_epi8) || (CV_AVX2 && (!defined(_MSC_VER) || _MSC_VER >= 1910/*MSVS 2017*/)) + return _mm256_extract_epi64(a, i); +#else + __m128i b = _mm256_extractf128_si256(a, ((i) >> 1)); + return _mm_extract_epi64(b, i & 1); // SSE4.1 +#endif +} + +///////// Types //////////// + +struct v_uint8x32 +{ + typedef uchar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_uint8x32(__m256i v) : val(v) {} + v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, + uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, + uchar v12, uchar v13, uchar v14, uchar v15, + uchar v16, uchar v17, uchar v18, uchar v19, + uchar v20, uchar v21, uchar v22, uchar v23, + uchar v24, uchar v25, uchar v26, uchar v27, + uchar v28, uchar v29, uchar v30, uchar v31) + { + val = _mm256_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, + (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, + (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, + (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, + (char)v28, (char)v29, (char)v30, (char)v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint8x32() {} + + uchar get0() const { return (uchar)_v_cvtsi256_si32(val); } +}; + +struct v_int8x32 +{ + typedef schar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_int8x32(__m256i v) : val(v) {} + v_int8x32(schar v0, schar v1, schar v2, schar v3, + schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, + schar v12, schar v13, schar v14, schar v15, + schar v16, schar v17, schar v18, schar v19, + schar v20, schar v21, schar v22, schar v23, + schar v24, schar v25, schar v26, schar v27, + schar v28, schar v29, schar v30, schar v31) + { + val = _mm256_setr_epi8(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, + v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int8x32() {} + + schar get0() const { return (schar)_v_cvtsi256_si32(val); } +}; + +struct v_uint16x16 +{ + typedef ushort lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_uint16x16(__m256i v) : val(v) {} + v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, + ushort v4, ushort v5, ushort v6, ushort v7, + ushort v8, ushort v9, ushort v10, ushort v11, + ushort v12, ushort v13, ushort v14, ushort v15) + { + val = _mm256_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, + (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint16x16() {} + + ushort get0() const { return (ushort)_v_cvtsi256_si32(val); } +}; + +struct v_int16x16 +{ + typedef short lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_int16x16(__m256i v) : val(v) {} + v_int16x16(short v0, short v1, short v2, short v3, + short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, + short v12, short v13, short v14, short v15) + { + val = _mm256_setr_epi16(v0, v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int16x16() {} + + short get0() const { return (short)_v_cvtsi256_si32(val); } +}; + +struct v_uint32x8 +{ + typedef unsigned lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_uint32x8(__m256i v) : val(v) {} + v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, + unsigned v4, unsigned v5, unsigned v6, unsigned v7) + { + val = _mm256_setr_epi32((unsigned)v0, (unsigned)v1, (unsigned)v2, + (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint32x8() {} + + unsigned get0() const { return (unsigned)_v_cvtsi256_si32(val); } +}; + +struct v_int32x8 +{ + typedef int lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_int32x8(__m256i v) : val(v) {} + v_int32x8(int v0, int v1, int v2, int v3, + int v4, int v5, int v6, int v7) + { + val = _mm256_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int32x8() {} + + int get0() const { return _v_cvtsi256_si32(val); } +}; + +struct v_float32x8 +{ + typedef float lane_type; + enum { nlanes = 8 }; + __m256 val; + + explicit v_float32x8(__m256 v) : val(v) {} + v_float32x8(float v0, float v1, float v2, float v3, + float v4, float v5, float v6, float v7) + { + val = _mm256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_float32x8() {} + + float get0() const { return _mm_cvtss_f32(_mm256_castps256_ps128(val)); } +}; + +struct v_uint64x4 +{ + typedef uint64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_uint64x4(__m256i v) : val(v) {} + v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) + { val = _mm256_setr_epi64x((int64)v0, (int64)v1, (int64)v2, (int64)v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_uint64x4() {} + + uint64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (uint64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); + int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); + return (unsigned)a | ((uint64)(unsigned)b << 32); + #endif + } +}; + +struct v_int64x4 +{ + typedef int64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_int64x4(__m256i v) : val(v) {} + v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) + { val = _mm256_setr_epi64x(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_int64x4() {} + + int64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (int64)_mm_cvtsi128_si64(_mm256_castsi256_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm256_castsi256_si128(val)); + int b = _mm_cvtsi128_si32(_mm256_castsi256_si128(_mm256_srli_epi64(val, 32))); + return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); + #endif + } +}; + +struct v_float64x4 +{ + typedef double lane_type; + enum { nlanes = 4 }; + __m256d val; + + explicit v_float64x4(__m256d v) : val(v) {} + v_float64x4(double v0, double v1, double v2, double v3) + { val = _mm256_setr_pd(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_float64x4() {} + + double get0() const { return _mm_cvtsd_f64(_mm256_castpd256_pd128(val)); } +}; + +//////////////// Load and store operations /////////////// + +#define OPENCV_HAL_IMPL_AVX_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(_mm256_loadu_si256((const __m256i*)ptr)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm256_load_si256((const __m256i*)ptr)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + __m128i v128 = _mm_loadu_si128((const __m128i*)ptr); \ + return _Tpvec(_mm256_castsi128_si256(v128)); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vlo = _mm_loadu_si128((const __m128i*)ptr0); \ + __m128i vhi = _mm_loadu_si128((const __m128i*)ptr1); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_si256((__m256i*)ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm256_store_si256((__m256i*)ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm256_stream_si256((__m256i*)ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm256_storeu_si256((__m256i*)ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm256_stream_si256((__m256i*)ptr, a.val); \ + else \ + _mm256_store_si256((__m256i*)ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_si128((__m128i*)ptr, _v256_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_si128((__m128i*)ptr, _v256_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint8x32, uchar) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int8x32, schar) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint16x16, ushort) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int16x16, short) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint32x8, unsigned) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int32x8, int) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_uint64x4, uint64) +OPENCV_HAL_IMPL_AVX_LOADSTORE(v_int64x4, int64) + +#define OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(_mm256_loadu_##suffix(ptr)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm256_load_##suffix(ptr)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + return _Tpvec(_mm256_cast##suffix##128_##suffix##256 \ + (_mm_loadu_##suffix(ptr))); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + halfreg vlo = _mm_loadu_##suffix(ptr0); \ + halfreg vhi = _mm_loadu_##suffix(ptr1); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_##suffix(ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm256_store_##suffix(ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm256_stream_##suffix(ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm256_storeu_##suffix(ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm256_stream_##suffix(ptr, a.val); \ + else \ + _mm256_store_##suffix(ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_##suffix(ptr, _v256_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm_storeu_##suffix(ptr, _v256_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float32x8, float, ps, __m128) +OPENCV_HAL_IMPL_AVX_LOADSTORE_FLT(v_float64x4, double, pd, __m128d) + +#define OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_AVX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(_mm256_setzero_si256()); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm256_set1_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float32x8, suffix, _mm256_castps_si256) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_float64x4, suffix, _mm256_castpd_si256) + +OPENCV_HAL_IMPL_AVX_INIT(v_uint8x32, uchar, u8, epi8, char) +OPENCV_HAL_IMPL_AVX_INIT(v_int8x32, schar, s8, epi8, char) +OPENCV_HAL_IMPL_AVX_INIT(v_uint16x16, ushort, u16, epi16, short) +OPENCV_HAL_IMPL_AVX_INIT(v_int16x16, short, s16, epi16, short) +OPENCV_HAL_IMPL_AVX_INIT(v_uint32x8, unsigned, u32, epi32, int) +OPENCV_HAL_IMPL_AVX_INIT(v_int32x8, int, s32, epi32, int) +OPENCV_HAL_IMPL_AVX_INIT(v_uint64x4, uint64, u64, epi64x, int64) +OPENCV_HAL_IMPL_AVX_INIT(v_int64x4, int64, s64, epi64x, int64) + +#define OPENCV_HAL_IMPL_AVX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(_mm256_setzero_##zsuffix()); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm256_set1_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int8x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int16x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int32x8, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ + OPENCV_HAL_IMPL_AVX_CAST(_Tpvec, v_int64x4, suffix, cast) + +OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float32x8, float, f32, ps, _mm256_castsi256_ps) +OPENCV_HAL_IMPL_AVX_INIT_FLT(v_float64x4, double, f64, pd, _mm256_castsi256_pd) + +inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) +{ return a; } +inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) +{ return v_float32x8(_mm256_castpd_ps(a.val)); } + +inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) +{ return a; } +inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) +{ return v_float64x4(_mm256_castps_pd(a.val)); } + +/* Recombine */ +/*#define OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, perm) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(perm(a.val, b.val, 0x20)); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(perm(a.val, b.val, 0x31)); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { c = v_combine_low(a, b); d = v_combine_high(a, b); } + +#define OPENCV_HAL_IMPL_AVX_UNPACKS(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_COMBINE(_Tpvec, _mm256_permute2x128_si256) \ + inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, \ + _Tpvec& b0, _Tpvec& b1) \ + { \ + __m256i v0 = _v256_shuffle_odd_64(a0.val); \ + __m256i v1 = _v256_shuffle_odd_64(a1.val); \ + b0.val = _mm256_unpacklo_##suffix(v0, v1); \ + b1.val = _mm256_unpackhi_##suffix(v0, v1); \ + } + +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_uint64x4, epi64) +OPENCV_HAL_IMPL_AVX_UNPACKS(v_int64x4, epi64) +OPENCV_HAL_IMPL_AVX_COMBINE(v_float32x8, _mm256_permute2f128_ps) +OPENCV_HAL_IMPL_AVX_COMBINE(v_float64x4, _mm256_permute2f128_pd) + +inline void v_zip(const v_float32x8& a0, const v_float32x8& a1, v_float32x8& b0, v_float32x8& b1) +{ + __m256 v0 = _mm256_unpacklo_ps(a0.val, a1.val); + __m256 v1 = _mm256_unpackhi_ps(a0.val, a1.val); + v_recombine(v_float32x8(v0), v_float32x8(v1), b0, b1); +} + +inline void v_zip(const v_float64x4& a0, const v_float64x4& a1, v_float64x4& b0, v_float64x4& b1) +{ + __m256d v0 = _v_shuffle_odd_64(a0.val); + __m256d v1 = _v_shuffle_odd_64(a1.val); + b0.val = _mm256_unpacklo_pd(v0, v1); + b1.val = _mm256_unpackhi_pd(v0, v1); +}*/ + +//////////////// Variant Value reordering /////////////// + +// unpacks +#define OPENCV_HAL_IMPL_AVX_UNPACK(_Tpvec, suffix) \ + inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_unpacklo_##suffix(a.val, b.val)); } \ + inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_unpackhi_##suffix(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int8x32, epi8) +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int16x16, epi16) +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int32x8, epi32) +OPENCV_HAL_IMPL_AVX_UNPACK(v_uint64x4, epi64) +OPENCV_HAL_IMPL_AVX_UNPACK(v_int64x4, epi64) +OPENCV_HAL_IMPL_AVX_UNPACK(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_UNPACK(v_float64x4, pd) + +// blend +#define OPENCV_HAL_IMPL_AVX_BLEND(_Tpvec, suffix) \ + template \ + inline _Tpvec v256_blend(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_blend_##suffix(a.val, b.val, m)); } + +OPENCV_HAL_IMPL_AVX_BLEND(v_uint16x16, epi16) +OPENCV_HAL_IMPL_AVX_BLEND(v_int16x16, epi16) +OPENCV_HAL_IMPL_AVX_BLEND(v_uint32x8, epi32) +OPENCV_HAL_IMPL_AVX_BLEND(v_int32x8, epi32) +OPENCV_HAL_IMPL_AVX_BLEND(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_BLEND(v_float64x4, pd) + +template +inline v_uint64x4 v256_blend(const v_uint64x4& a, const v_uint64x4& b) +{ + enum {M0 = m}; + enum {M1 = (M0 | (M0 << 2)) & 0x33}; + enum {M2 = (M1 | (M1 << 1)) & 0x55}; + enum {MM = M2 | (M2 << 1)}; + return v_uint64x4(_mm256_blend_epi32(a.val, b.val, MM)); +} +template +inline v_int64x4 v256_blend(const v_int64x4& a, const v_int64x4& b) +{ return v_int64x4(v256_blend(v_uint64x4(a.val), v_uint64x4(b.val)).val); } + +// shuffle +// todo: emulate 64bit +#define OPENCV_HAL_IMPL_AVX_SHUFFLE(_Tpvec, intrin) \ + template \ + inline _Tpvec v256_shuffle(const _Tpvec& a) \ + { return _Tpvec(_mm256_##intrin(a.val, m)); } + +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_uint32x8, shuffle_epi32) +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_int32x8, shuffle_epi32) +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float32x8, permute_ps) +OPENCV_HAL_IMPL_AVX_SHUFFLE(v_float64x4, permute_pd) + +template +inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) +{ + ab0 = v256_unpacklo(a, b); + ab1 = v256_unpackhi(a, b); +} + +template +inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_mm256_blend_epi32(a.val, b.val, 0xf0)); } + +inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) +{ return v256_blend<0xf0>(a, b); } + +inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) +{ return v256_blend<0xc>(a, b); } + +template +inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) +{ return v256_permute2x128<0x21>(a, b); } + +template +inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_mm256_alignr_epi8(a.val, b.val, 8)); } +inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) +{ return v_float64x4(_mm256_shuffle_pd(b.val, a.val, _MM_SHUFFLE(0, 0, 1, 1))); } +// todo: emulate float32 + +template +inline _Tpvec v256_swap_halves(const _Tpvec& a) +{ return v256_permute2x128<1>(a, a); } + +template +inline _Tpvec v256_reverse_64(const _Tpvec& a) +{ return v256_permute4x64<_MM_SHUFFLE(0, 1, 2, 3)>(a); } + +// ZIP +#define OPENCV_HAL_IMPL_AVX_ZIP(_Tpvec) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x20>(a, b); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x31>(a, b); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + _Tpvec a1b0 = v256_alignr_128(a, b); \ + c = v256_combine_diagonal(a, a1b0); \ + d = v256_combine_diagonal(a1b0, b); \ + } \ + inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& ab0, _Tpvec& ab1) \ + { \ + _Tpvec ab0ab2, ab1ab3; \ + v256_zip(a, b, ab0ab2, ab1ab3); \ + v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ + } + +OPENCV_HAL_IMPL_AVX_ZIP(v_uint8x32) +OPENCV_HAL_IMPL_AVX_ZIP(v_int8x32) +OPENCV_HAL_IMPL_AVX_ZIP(v_uint16x16) +OPENCV_HAL_IMPL_AVX_ZIP(v_int16x16) +OPENCV_HAL_IMPL_AVX_ZIP(v_uint32x8) +OPENCV_HAL_IMPL_AVX_ZIP(v_int32x8) +OPENCV_HAL_IMPL_AVX_ZIP(v_uint64x4) +OPENCV_HAL_IMPL_AVX_ZIP(v_int64x4) +OPENCV_HAL_IMPL_AVX_ZIP(v_float32x8) +OPENCV_HAL_IMPL_AVX_ZIP(v_float64x4) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/* Element-wise binary and unary operations */ + +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_AVX_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint8x32, _mm256_adds_epu8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint8x32, _mm256_subs_epu8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int8x32, _mm256_adds_epi8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int8x32, _mm256_subs_epi8) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint16x16, _mm256_adds_epu16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint16x16, _mm256_subs_epu16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int16x16, _mm256_adds_epi16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int16x16, _mm256_subs_epi16) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint32x8, _mm256_add_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint32x8, _mm256_sub_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_uint32x8, _mm256_mullo_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int32x8, _mm256_add_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int32x8, _mm256_sub_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_int32x8, _mm256_mullo_epi32) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_uint64x4, _mm256_add_epi64) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_uint64x4, _mm256_sub_epi64) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_int64x4, _mm256_add_epi64) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_int64x4, _mm256_sub_epi64) + +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float32x8, _mm256_add_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float32x8, _mm256_sub_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float32x8, _mm256_mul_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float32x8, _mm256_div_ps) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_add, v_float64x4, _mm256_add_pd) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_sub, v_float64x4, _mm256_sub_pd) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_mul, v_float64x4, _mm256_mul_pd) +OPENCV_HAL_IMPL_AVX_BIN_OP(v_div, v_float64x4, _mm256_div_pd) + +// saturating multiply 8-bit, 16-bit +inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) +{ + v_uint16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) +{ + v_int16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i pl = _mm256_mullo_epi16(a.val, b.val); + __m256i ph = _mm256_mulhi_epu16(a.val, b.val); + __m256i p0 = _mm256_unpacklo_epi16(pl, ph); + __m256i p1 = _mm256_unpackhi_epi16(pl, ph); + return v_uint16x16(_v256_packs_epu32(p0, p1)); +} +inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) +{ + __m256i pl = _mm256_mullo_epi16(a.val, b.val); + __m256i ph = _mm256_mulhi_epi16(a.val, b.val); + __m256i p0 = _mm256_unpacklo_epi16(pl, ph); + __m256i p1 = _mm256_unpackhi_epi16(pl, ph); + return v_int16x16(_mm256_packs_epi32(p0, p1)); +} + +/** Non-saturating arithmetics **/ +#define OPENCV_HAL_IMPL_AVX_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint8x32, _mm256_add_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int8x32, _mm256_add_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_uint16x16, _mm256_add_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_add_wrap, v_int16x16, _mm256_add_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint8x32, _mm256_sub_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int8x32, _mm256_sub_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_uint16x16, _mm256_sub_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_sub_wrap, v_int16x16, _mm256_sub_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_uint16x16, _mm256_mullo_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_mul_wrap, v_int16x16, _mm256_mullo_epi16) + +inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i ad = _mm256_srai_epi16(a.val, 8); + __m256i bd = _mm256_srai_epi16(b.val, 8); + __m256i p0 = _mm256_mullo_epi16(a.val, b.val); // even + __m256i p1 = _mm256_slli_epi16(_mm256_mullo_epi16(ad, bd), 8); // odd + + const __m256i b01 = _mm256_set1_epi32(0xFF00FF00); + return v_uint8x32(_mm256_blendv_epi8(p0, p1, b01)); +} +inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +// Multiply and expand +inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, + v_uint16x16& c, v_uint16x16& d) +{ + v_uint16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, + v_int16x16& c, v_int16x16& d) +{ + v_int16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, + v_int32x8& c, v_int32x8& d) +{ + v_int16x16 vhi = v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); + + v_int16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_s32(v0); + d = v_reinterpret_as_s32(v1); +} + +inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, + v_uint32x8& c, v_uint32x8& d) +{ + v_uint16x16 vhi = v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); + + v_uint16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_u32(v0); + d = v_reinterpret_as_u32(v1); +} + +inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, + v_uint64x4& c, v_uint64x4& d) +{ + __m256i v0 = _mm256_mul_epu32(a.val, b.val); + __m256i v1 = _mm256_mul_epu32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); + v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); +} + +inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(_mm256_mulhi_epi16(a.val, b.val)); } +inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(_mm256_mulhi_epu16(a.val, b.val)); } + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_AVX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(srai(a.val, imm)); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(_mm256_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(_mm256_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(_mm256_srli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(srai(a.val, imm)); } + +OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint16x16, v_int16x16, epi16, _mm256_srai_epi16) +OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint32x8, v_int32x8, epi32, _mm256_srai_epi32) + +inline __m256i _mm256_srai_epi64xx(const __m256i a, int imm) +{ + __m256i d = _mm256_set1_epi64x((int64)1 << 63); + __m256i r = _mm256_srli_epi64(_mm256_add_epi64(a, d), imm); + return _mm256_sub_epi64(r, _mm256_srli_epi64(d, imm)); +} +OPENCV_HAL_IMPL_AVX_SHIFT_OP(v_uint64x4, v_int64x4, epi64, _mm256_srai_epi64xx) + + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_AVX_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_AVX_BIN_OP(v_and, _Tpvec, _mm256_and_##suffix) \ + OPENCV_HAL_IMPL_AVX_BIN_OP(v_or, _Tpvec, _mm256_or_##suffix) \ + OPENCV_HAL_IMPL_AVX_BIN_OP(v_xor, _Tpvec, _mm256_xor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(_mm256_xor_##suffix(a.val, not_const)); } + +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint8x32, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int8x32, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint16x16, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int16x16, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint32x8, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int32x8, si256, _mm256_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_uint64x4, si256, _mm256_set1_epi64x(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_int64x4, si256, _mm256_set1_epi64x(-1)) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float32x8, ps, _mm256_castsi256_ps(_mm256_set1_epi32(-1))) +OPENCV_HAL_IMPL_AVX_LOGIC_OP(v_float64x4, pd, _mm256_castsi256_pd(_mm256_set1_epi32(-1))) + +/** Select **/ +#define OPENCV_HAL_IMPL_AVX_SELECT(_Tpvec, suffix) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_blendv_##suffix(b.val, a.val, mask.val)); } + +OPENCV_HAL_IMPL_AVX_SELECT(v_uint8x32, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_int8x32, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_uint16x16, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_int16x16, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_uint32x8, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_int32x8, epi8) +OPENCV_HAL_IMPL_AVX_SELECT(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_SELECT(v_float64x4, pd) + +/** Comparison **/ +#define OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpvec) \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } \ + inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ + { return v_gt(b, a); } \ + inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_lt(a, b)); } \ + inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ + { return v_ge(b, a); } + +#define OPENCV_HAL_IMPL_AVX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, sbit) \ + inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ + inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ + { \ + __m256i smask = _mm256_set1_##suffix(sbit); \ + return _Tpuvec(_mm256_cmpgt_##suffix( \ + _mm256_xor_si256(a.val, smask), \ + _mm256_xor_si256(b.val, smask))); \ + } \ + inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(_mm256_cmpeq_##suffix(a.val, b.val)); } \ + inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(_mm256_cmpgt_##suffix(a.val, b.val)); } \ + OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpuvec) \ + OPENCV_HAL_IMPL_AVX_CMP_OP_OV(_Tpsvec) + +OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint8x32, v_int8x32, epi8, (char)-128) +OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint16x16, v_int16x16, epi16, (short)-32768) +OPENCV_HAL_IMPL_AVX_CMP_OP_INT(v_uint32x8, v_int32x8, epi32, (int)0x80000000) + +#define OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(_Tpvec) \ + inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_cmpeq_epi64(a.val, b.val)); } \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } + +OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_uint64x4) +OPENCV_HAL_IMPL_AVX_CMP_OP_64BIT(v_int64x4) + +#define OPENCV_HAL_IMPL_AVX_CMP_FLT(bin_op, imm8, _Tpvec, suffix) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm256_cmp_##suffix(a.val, b.val, imm8)); } + +#define OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, suffix) \ + OPENCV_HAL_IMPL_AVX_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, suffix) + +OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_CMP_OP_FLT(v_float64x4, pd) + +inline v_float32x8 v_not_nan(const v_float32x8& a) +{ return v_float32x8(_mm256_cmp_ps(a.val, a.val, _CMP_ORD_Q)); } +inline v_float64x4 v_not_nan(const v_float64x4& a) +{ return v_float64x4(_mm256_cmp_pd(a.val, a.val, _CMP_ORD_Q)); } + +/** min/max **/ +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint8x32, _mm256_min_epu8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint8x32, _mm256_max_epu8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int8x32, _mm256_min_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int8x32, _mm256_max_epi8) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint16x16, _mm256_min_epu16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint16x16, _mm256_max_epu16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int16x16, _mm256_min_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int16x16, _mm256_max_epi16) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_uint32x8, _mm256_min_epu32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_uint32x8, _mm256_max_epu32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_int32x8, _mm256_min_epi32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_int32x8, _mm256_max_epi32) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float32x8, _mm256_min_ps) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float32x8, _mm256_max_ps) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_min, v_float64x4, _mm256_min_pd) +OPENCV_HAL_IMPL_AVX_BIN_FUNC(v_max, v_float64x4, _mm256_max_pd) + +/** Rotate **/ +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_R = (16 - imm) & 0xFF}; + enum {IMM_R2 = (32 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x03); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swap, IMM_R)); + return v_uint8x32(_mm256_alignr_epi8(swap, b.val, IMM_R2)); // imm < 32 +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _mm256_permute2x128_si256(a.val, b.val, 0x21); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swap, a.val, imm)); + return v_uint8x32(_mm256_alignr_epi8(b.val, swap, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + enum {IMM_R = (16 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(0, 0, 2, 0)); + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(a.val, swapz, IMM_R)); + return v_uint8x32(_mm256_slli_si256(swapz, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i swapz = _mm256_permute2x128_si256(a.val, a.val, _MM_SHUFFLE(2, 0, 0, 1)); + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_mm256_alignr_epi8(swapz, a.val, imm)); + return v_uint8x32(_mm256_srli_si256(swapz, IMM_L)); +} + +#define OPENCV_HAL_IMPL_AVX_ROTATE_CAST(intrin, _Tpvec, cast) \ + template \ + inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ + v_reinterpret_as_u8(b)); \ + return _Tpvec(cast(ret.val)); \ + } \ + template \ + inline _Tpvec intrin(const _Tpvec& a) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ + return _Tpvec(cast(ret.val)); \ + } + +#define OPENCV_HAL_IMPL_AVX_ROTATE(_Tpvec) \ + OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) + +OPENCV_HAL_IMPL_AVX_ROTATE(v_int8x32) +OPENCV_HAL_IMPL_AVX_ROTATE(v_uint16x16) +OPENCV_HAL_IMPL_AVX_ROTATE(v_int16x16) +OPENCV_HAL_IMPL_AVX_ROTATE(v_uint32x8) +OPENCV_HAL_IMPL_AVX_ROTATE(v_int32x8) +OPENCV_HAL_IMPL_AVX_ROTATE(v_uint64x4) +OPENCV_HAL_IMPL_AVX_ROTATE(v_int64x4) + +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float32x8, _mm256_castsi256_ps) +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float32x8, _mm256_castsi256_ps) +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_left, v_float64x4, _mm256_castsi256_pd) +OPENCV_HAL_IMPL_AVX_ROTATE_CAST(v_rotate_right, v_float64x4, _mm256_castsi256_pd) + +/** Reverse **/ +inline v_uint8x32 v_reverse(const v_uint8x32 &a) +{ + static const __m256i perm = _mm256_setr_epi8( + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + __m256i vec = _mm256_shuffle_epi8(a.val, perm); + return v_uint8x32(_mm256_permute2x128_si256(vec, vec, 1)); +} + +inline v_int8x32 v_reverse(const v_int8x32 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x16 v_reverse(const v_uint16x16 &a) +{ + static const __m256i perm = _mm256_setr_epi8( + 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1, + 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); + __m256i vec = _mm256_shuffle_epi8(a.val, perm); + return v_uint16x16(_mm256_permute2x128_si256(vec, vec, 1)); +} + +inline v_int16x16 v_reverse(const v_int16x16 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x8 v_reverse(const v_uint32x8 &a) +{ + static const __m256i perm = _mm256_setr_epi32(7, 6, 5, 4, 3, 2, 1, 0); + return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); +} + +inline v_int32x8 v_reverse(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x8 v_reverse(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x4 v_reverse(const v_uint64x4 &a) +{ + return v_uint64x4(_mm256_permute4x64_epi64(a.val, _MM_SHUFFLE(0, 1, 2, 3))); +} + +inline v_int64x4 v_reverse(const v_int64x4 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x4 v_reverse(const v_float64x4 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////// Reduce and mask ///////// + +/** Reduce **/ +inline unsigned v_reduce_sum(const v_uint8x32& a) +{ + __m256i half = _mm256_sad_epu8(a.val, _mm256_setzero_si256()); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline int v_reduce_sum(const v_int8x32& a) +{ + __m256i half = _mm256_sad_epu8(_mm256_xor_si256(a.val, _mm256_set1_epi8((schar)-128)), _mm256_setzero_si256()); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))) - 4096; +} +#define OPENCV_HAL_IMPL_AVX_REDUCE_32(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ + val = intrin(val, _mm_srli_si128(val,8)); \ + val = intrin(val, _mm_srli_si128(val,4)); \ + val = intrin(val, _mm_srli_si128(val,2)); \ + val = intrin(val, _mm_srli_si128(val,1)); \ + return (sctype)_mm_cvtsi128_si32(val); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, min, _mm_min_epu8) +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, min, _mm_min_epi8) +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_uint8x32, uchar, max, _mm_max_epu8) +OPENCV_HAL_IMPL_AVX_REDUCE_32(v_int8x32, schar, max, _mm_max_epi8) + +#define OPENCV_HAL_IMPL_AVX_REDUCE_16(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ + v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ + v0 = intrin(v0, _mm_srli_si128(v0, 2)); \ + return (sctype) _mm_cvtsi128_si32(v0); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, min, _mm_min_epu16) +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, min, _mm_min_epi16) +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_uint16x16, ushort, max, _mm_max_epu16) +OPENCV_HAL_IMPL_AVX_REDUCE_16(v_int16x16, short, max, _mm_max_epi16) + +#define OPENCV_HAL_IMPL_AVX_REDUCE_8(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, _mm_srli_si128(v0, 8)); \ + v0 = intrin(v0, _mm_srli_si128(v0, 4)); \ + return (sctype) _mm_cvtsi128_si32(v0); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, min, _mm_min_epu32) +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, min, _mm_min_epi32) +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_uint32x8, unsigned, max, _mm_max_epu32) +OPENCV_HAL_IMPL_AVX_REDUCE_8(v_int32x8, int, max, _mm_max_epi32) + +#define OPENCV_HAL_IMPL_AVX_REDUCE_FLT(func, intrin) \ + inline float v_reduce_##func(const v_float32x8& a) \ + { \ + __m128 v0 = _v256_extract_low(a.val); \ + __m128 v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 3, 2))); \ + v0 = intrin(v0, _mm_permute_ps(v0, _MM_SHUFFLE(0, 0, 0, 1))); \ + return _mm_cvtss_f32(v0); \ + } + +OPENCV_HAL_IMPL_AVX_REDUCE_FLT(min, _mm_min_ps) +OPENCV_HAL_IMPL_AVX_REDUCE_FLT(max, _mm_max_ps) + +inline int v_reduce_sum(const v_int32x8& a) +{ + __m256i s0 = _mm256_hadd_epi32(a.val, a.val); + s0 = _mm256_hadd_epi32(s0, s0); + + __m128i s1 = _v256_extract_high(s0); + s1 = _mm_add_epi32(_v256_extract_low(s0), s1); + + return _mm_cvtsi128_si32(s1); +} + +inline unsigned v_reduce_sum(const v_uint32x8& a) +{ return v_reduce_sum(v_reinterpret_as_s32(a)); } + +inline int v_reduce_sum(const v_int16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline unsigned v_reduce_sum(const v_uint16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +inline float v_reduce_sum(const v_float32x8& a) +{ + __m256 s0 = _mm256_hadd_ps(a.val, a.val); + s0 = _mm256_hadd_ps(s0, s0); + + __m128 s1 = _v256_extract_high(s0); + s1 = _mm_add_ps(_v256_extract_low(s0), s1); + + return _mm_cvtss_f32(s1); +} + +inline uint64 v_reduce_sum(const v_uint64x4& a) +{ + uint64 CV_DECL_ALIGNED(32) idx[2]; + _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); + return idx[0] + idx[1]; +} +inline int64 v_reduce_sum(const v_int64x4& a) +{ + int64 CV_DECL_ALIGNED(32) idx[2]; + _mm_store_si128((__m128i*)idx, _mm_add_epi64(_v256_extract_low(a.val), _v256_extract_high(a.val))); + return idx[0] + idx[1]; +} +inline double v_reduce_sum(const v_float64x4& a) +{ + __m256d s0 = _mm256_hadd_pd(a.val, a.val); + return _mm_cvtsd_f64(_mm_add_pd(_v256_extract_low(s0), _v256_extract_high(s0))); +} + +inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, + const v_float32x8& c, const v_float32x8& d) +{ + __m256 ab = _mm256_hadd_ps(a.val, b.val); + __m256 cd = _mm256_hadd_ps(c.val, d.val); + return v_float32x8(_mm256_hadd_ps(ab, cd)); +} + +inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i half = _mm256_sad_epu8(a.val, b.val); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) +{ + __m256i half = _mm256_set1_epi8(0x7f); + half = _mm256_sad_epu8(_mm256_add_epi8(a.val, half), _mm256_add_epi8(b.val, half)); + __m128i quarter = _mm_add_epi32(_v256_extract_low(half), _v256_extract_high(half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) +{ + return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); +} +inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 m = v_lt(a, b); + return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); +} +inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) +{ + return v_reduce_sum(v_and(v_sub(a, b), v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff))))); +} + +/** Popcount **/ +inline v_uint8x32 v_popcount(const v_uint8x32& a) +{ + __m256i _popcnt_table = _mm256_setr_epi8(0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4); + __m256i _popcnt_mask = _mm256_set1_epi8(0x0F); + return v_uint8x32(_mm256_add_epi8(_mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256( a.val , _popcnt_mask)), + _mm256_shuffle_epi8(_popcnt_table, _mm256_and_si256(_mm256_srli_epi16(a.val, 4), _popcnt_mask)))); +} +inline v_uint16x16 v_popcount(const v_uint16x16& a) +{ + v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v256_setall_u16(0x00ff)); +} +inline v_uint32x8 v_popcount(const v_uint32x8& a) +{ + v_uint8x32 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v256_setall_u32(0x000000ff)); +} +inline v_uint64x4 v_popcount(const v_uint64x4& a) +{ + return v_uint64x4(_mm256_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm256_setzero_si256())); +} +inline v_uint8x32 v_popcount(const v_int8x32& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x16 v_popcount(const v_int16x16& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x8 v_popcount(const v_int32x8& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x4 v_popcount(const v_int64x4& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +/** Mask **/ +inline int v_signmask(const v_int8x32& a) +{ return _mm256_movemask_epi8(a.val); } +inline int v_signmask(const v_uint8x32& a) +{ return v_signmask(v_reinterpret_as_s8(a)); } + +inline int v_signmask(const v_int16x16& a) +{ return v_signmask(v_pack(a, a)) & 0xFFFF; } +inline int v_signmask(const v_uint16x16& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_float32x8& a) +{ return _mm256_movemask_ps(a.val); } +inline int v_signmask(const v_float64x4& a) +{ return _mm256_movemask_pd(a.val); } + +inline int v_signmask(const v_int32x8& a) +{ return v_signmask(v_reinterpret_as_f32(a)); } +inline int v_signmask(const v_uint32x8& a) +{ return v_signmask(v_reinterpret_as_f32(a)); } + +inline int v_signmask(const v_int64x4& a) +{ return v_signmask(v_reinterpret_as_f64(a)); } +inline int v_signmask(const v_uint64x4& a) +{ return v_signmask(v_reinterpret_as_f64(a)); } + +inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +/** Checks **/ +#define OPENCV_HAL_IMPL_AVX_CHECK(_Tpvec, allmask) \ + inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ + inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } +OPENCV_HAL_IMPL_AVX_CHECK(v_uint8x32, -1) +OPENCV_HAL_IMPL_AVX_CHECK(v_int8x32, -1) +OPENCV_HAL_IMPL_AVX_CHECK(v_uint32x8, 255) +OPENCV_HAL_IMPL_AVX_CHECK(v_int32x8, 255) +OPENCV_HAL_IMPL_AVX_CHECK(v_uint64x4, 15) +OPENCV_HAL_IMPL_AVX_CHECK(v_int64x4, 15) +OPENCV_HAL_IMPL_AVX_CHECK(v_float32x8, 255) +OPENCV_HAL_IMPL_AVX_CHECK(v_float64x4, 15) + +#define OPENCV_HAL_IMPL_AVX_CHECK_SHORT(_Tpvec) \ + inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ + inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } +OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_uint16x16) +OPENCV_HAL_IMPL_AVX_CHECK_SHORT(v_int16x16) + +////////// Other math ///////// + +/** Some frequent operations **/ +#if CV_FMA3 +#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_fmadd_##suffix(a.val, b.val, c.val)); } +#else +#define OPENCV_HAL_IMPL_AVX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm256_add_##suffix(_mm256_mul_##suffix(a.val, b.val), c.val)); } +#endif + +#define OPENCV_HAL_IMPL_AVX_MISC(_Tpvec, suffix) \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(_mm256_sqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_AVX_MULADD(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_MULADD(v_float64x4, pd) +OPENCV_HAL_IMPL_AVX_MISC(v_float32x8, ps) +OPENCV_HAL_IMPL_AVX_MISC(v_float64x4, pd) + +inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x8 v_invsqrt(const v_float32x8& x) +{ + v_float32x8 half = v_mul(x, v256_setall_f32(0.5)); + v_float32x8 t = v_float32x8(_mm256_rsqrt_ps(x.val)); + // todo: _mm256_fnmsub_ps + t = v_mul(t, v_sub(v256_setall_f32(1.5), v_mul(v_mul(t, t), half))); + return t; +} + +inline v_float64x4 v_invsqrt(const v_float64x4& x) +{ + return v_div(v256_setall_f64(1.), v_sqrt(x)); +} + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_AVX_ABS(_Tpvec, suffix) \ + inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ + { return v_u##_Tpvec(_mm256_abs_##suffix(x.val)); } + +OPENCV_HAL_IMPL_AVX_ABS(int8x32, epi8) +OPENCV_HAL_IMPL_AVX_ABS(int16x16, epi16) +OPENCV_HAL_IMPL_AVX_ABS(int32x8, epi32) + +inline v_float32x8 v_abs(const v_float32x8& x) +{ return v_and(x, v_float32x8(_mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff)))); } +inline v_float64x4 v_abs(const v_float64x4& x) +{ return v_and(x, v_float64x4(_mm256_castsi256_pd(_mm256_srli_epi64(_mm256_set1_epi64x(-1), 1)))); } + +/** Absolute difference **/ +inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) +{ + v_int8x32 d = v_sub_wrap(a, b); + v_int8x32 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} + +inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) +{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } + +inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 d = v_sub(a, b); + v_int32x8 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) +{ + v_int8x32 d = v_sub(a, b); + v_int8x32 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x8 v_round(const v_float32x8& a) +{ return v_int32x8(_mm256_cvtps_epi32(a.val)); } + +inline v_int32x8 v_round(const v_float64x4& a) +{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvtpd_epi32(a.val))); } + +inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) +{ + __m128i ai = _mm256_cvtpd_epi32(a.val), bi = _mm256_cvtpd_epi32(b.val); + return v_int32x8(_v256_combine(ai, bi)); +} + +inline v_int32x8 v_trunc(const v_float32x8& a) +{ return v_int32x8(_mm256_cvttps_epi32(a.val)); } + +inline v_int32x8 v_trunc(const v_float64x4& a) +{ return v_int32x8(_mm256_castsi128_si256(_mm256_cvttpd_epi32(a.val))); } + +inline v_int32x8 v_floor(const v_float32x8& a) +{ return v_int32x8(_mm256_cvttps_epi32(_mm256_floor_ps(a.val))); } + +inline v_int32x8 v_floor(const v_float64x4& a) +{ return v_trunc(v_float64x4(_mm256_floor_pd(a.val))); } + +inline v_int32x8 v_ceil(const v_float32x8& a) +{ return v_int32x8(_mm256_cvttps_epi32(_mm256_ceil_ps(a.val))); } + +inline v_int32x8 v_ceil(const v_float64x4& a) +{ return v_trunc(v_float64x4(_mm256_ceil_pd(a.val))); } + +/** To float **/ +inline v_float32x8 v_cvt_f32(const v_int32x8& a) +{ return v_float32x8(_mm256_cvtepi32_ps(a.val)); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a) +{ return v_float32x8(_mm256_castps128_ps256(_mm256_cvtpd_ps(a.val))); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) +{ + __m128 af = _mm256_cvtpd_ps(a.val), bf = _mm256_cvtpd_ps(b.val); + return v_float32x8(_v256_combine(af, bf)); +} + +inline v_float64x4 v_cvt_f64(const v_int32x8& a) +{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_low(a.val))); } + +inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) +{ return v_float64x4(_mm256_cvtepi32_pd(_v256_extract_high(a.val))); } + +inline v_float64x4 v_cvt_f64(const v_float32x8& a) +{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_low(a.val))); } + +inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) +{ return v_float64x4(_mm256_cvtps_pd(_v256_extract_high(a.val))); } + +// from (Mysticial and wim) https://stackoverflow.com/q/41144668 +inline v_float64x4 v_cvt_f64(const v_int64x4& v) +{ + // constants encoded as floating-point + __m256i magic_i_lo = _mm256_set1_epi64x(0x4330000000000000); // 2^52 + __m256i magic_i_hi32 = _mm256_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 + __m256i magic_i_all = _mm256_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 + __m256d magic_d_all = _mm256_castsi256_pd(magic_i_all); + + // Blend the 32 lowest significant bits of v with magic_int_lo + __m256i v_lo = _mm256_blend_epi32(magic_i_lo, v.val, 0x55); + // Extract the 32 most significant bits of v + __m256i v_hi = _mm256_srli_epi64(v.val, 32); + // Flip the msb of v_hi and blend with 0x45300000 + v_hi = _mm256_xor_si256(v_hi, magic_i_hi32); + // Compute in double precision + __m256d v_hi_dbl = _mm256_sub_pd(_mm256_castsi256_pd(v_hi), magic_d_all); + // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition + __m256d result = _mm256_add_pd(v_hi_dbl, _mm256_castsi256_pd(v_lo)); + return v_float64x4(result); +} + +////////////// Lookup table access //////////////////// + +inline v_int8x32 v256_lut(const schar* tab, const int* idx) +{ + return v_int8x32(_mm256_setr_epi8(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], + tab[idx[16]], tab[idx[17]], tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], + tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], tab[idx[30]], tab[idx[31]])); +} +inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x32(_mm256_setr_epi16(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), *(const short*)(tab + idx[ 3]), + *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), + *(const short*)(tab + idx[ 8]), *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), + *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), *(const short*)(tab + idx[15]))); +} +inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x32(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 1)); +} +inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } + +inline v_int16x16 v256_lut(const short* tab, const int* idx) +{ + return v_int16x16(_mm256_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); +} +inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x16(_mm256_i32gather_epi32((const int*)tab, _mm256_loadu_si256((const __m256i*)idx), 2)); +} +inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int16x16(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 2));//Looks like intrinsic has wrong definition +#else + return v_int16x16(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 2)); +#endif +} +inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } + +inline v_int32x8 v256_lut(const int* tab, const int* idx) +{ + return v_int32x8(_mm256_i32gather_epi32(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); +} +inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int32x8(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); +#else + return v_int32x8(_mm256_i32gather_epi64((const int64*)tab, _mm_loadu_si128((const __m128i*)idx), 4)); +#endif +} +inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) +{ + return v_int32x8(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); +} +inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } + +inline v_int64x4 v256_lut(const int64* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int64x4(_mm256_i32gather_epi64((const long long int*)tab, _mm_loadu_si128((const __m128i*)idx), 8)); +#else + return v_int64x4(_mm256_i32gather_epi64(tab, _mm_loadu_si128((const __m128i*)idx), 8)); +#endif +} +inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) +{ + return v_int64x4(_v256_combine(_mm_loadu_si128((const __m128i*)(tab + idx[0])), _mm_loadu_si128((const __m128i*)(tab + idx[1])))); +} +inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } +inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } + +inline v_float32x8 v256_lut(const float* tab, const int* idx) +{ + return v_float32x8(_mm256_i32gather_ps(tab, _mm256_loadu_si256((const __m256i*)idx), 4)); +} +inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } +inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } + +inline v_float64x4 v256_lut(const double* tab, const int* idx) +{ + return v_float64x4(_mm256_i32gather_pd(tab, _mm_loadu_si128((const __m128i*)idx), 8)); +} +inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) { return v_float64x4(_v256_combine(_mm_loadu_pd(tab + idx[0]), _mm_loadu_pd(tab + idx[1]))); } + +inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) +{ + return v_int32x8(_mm256_i32gather_epi32(tab, idxvec.val, 4)); +} + +inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) +{ + return v_float32x8(_mm256_i32gather_ps(tab, idxvec.val, 4)); +} + +inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) +{ + return v_float64x4(_mm256_i32gather_pd(tab, _mm256_castsi256_si128(idxvec.val), 8)); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) +{ + int CV_DECL_ALIGNED(32) idx[8]; + v_store_aligned(idx, idxvec); + __m128 z = _mm_setzero_ps(); + __m128 xy01, xy45, xy23, xy67; + xy01 = _mm_loadl_pi(z, (const __m64*)(tab + idx[0])); + xy01 = _mm_loadh_pi(xy01, (const __m64*)(tab + idx[1])); + xy45 = _mm_loadl_pi(z, (const __m64*)(tab + idx[4])); + xy45 = _mm_loadh_pi(xy45, (const __m64*)(tab + idx[5])); + __m256 xy0145 = _v256_combine(xy01, xy45); + xy23 = _mm_loadl_pi(z, (const __m64*)(tab + idx[2])); + xy23 = _mm_loadh_pi(xy23, (const __m64*)(tab + idx[3])); + xy67 = _mm_loadl_pi(z, (const __m64*)(tab + idx[6])); + xy67 = _mm_loadh_pi(xy67, (const __m64*)(tab + idx[7])); + __m256 xy2367 = _v256_combine(xy23, xy67); + + __m256 xxyy0145 = _mm256_unpacklo_ps(xy0145, xy2367); + __m256 xxyy2367 = _mm256_unpackhi_ps(xy0145, xy2367); + + x = v_float32x8(_mm256_unpacklo_ps(xxyy0145, xxyy2367)); + y = v_float32x8(_mm256_unpackhi_ps(xxyy0145, xxyy2367)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_low(idx, idxvec); + __m128d xy0 = _mm_loadu_pd(tab + idx[0]); + __m128d xy2 = _mm_loadu_pd(tab + idx[2]); + __m128d xy1 = _mm_loadu_pd(tab + idx[1]); + __m128d xy3 = _mm_loadu_pd(tab + idx[3]); + __m256d xy02 = _v256_combine(xy0, xy2); + __m256d xy13 = _v256_combine(xy1, xy3); + + x = v_float64x4(_mm256_unpacklo_pd(xy02, xy13)); + y = v_float64x4(_mm256_unpackhi_pd(xy02, xy13)); +} + +inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) +{ + return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); +} +inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x32 v_interleave_quads(const v_int8x32& vec) +{ + return v_int8x32(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); +} +inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) +{ + return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); +} +inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x16 v_interleave_quads(const v_int16x16& vec) +{ + return v_int16x16(_mm256_shuffle_epi8(vec.val, _mm256_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); +} +inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) +{ + return v_int32x8(_mm256_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); +} +inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x32 v_pack_triplets(const v_int8x32& vec) +{ + return v_int8x32(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))), + _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_pack_triplets(const v_int16x16& vec) +{ + return v_int16x16(_mm256_permutevar8x32_epi32(_mm256_shuffle_epi8(vec.val, _mm256_broadcastsi128_si256(_mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))), + _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_pack_triplets(const v_int32x8& vec) +{ + return v_int32x8(_mm256_permutevar8x32_epi32(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_pack_triplets(const v_float32x8& vec) +{ + return v_float32x8(_mm256_permutevar8x32_ps(vec.val, _mm256_set_epi64x(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} + +////////// Matrix operations ///////// + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) +{ return v_int32x8(_mm256_madd_epi16(a.val, b.val)); } +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) +{ + __m256i even = _mm256_mul_epi32(a.val, b.val); + __m256i odd = _mm256_mul_epi32(_mm256_srli_epi64(a.val, 32), _mm256_srli_epi64(b.val, 32)); + return v_int64x4(_mm256_add_epi64(even, odd)); +} +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i even_m = _mm256_set1_epi32(0xFF00FF00); + __m256i even_a = _mm256_blendv_epi8(a.val, _mm256_setzero_si256(), even_m); + __m256i odd_a = _mm256_srli_epi16(a.val, 8); + + __m256i even_b = _mm256_blendv_epi8(b.val, _mm256_setzero_si256(), even_m); + __m256i odd_b = _mm256_srli_epi16(b.val, 8); + + __m256i prod0 = _mm256_madd_epi16(even_a, even_b); + __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); + return v_uint32x8(_mm256_add_epi32(prod0, prod1)); +} +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) +{ + __m256i even_a = _mm256_srai_epi16(_mm256_bslli_epi128(a.val, 1), 8); + __m256i odd_a = _mm256_srai_epi16(a.val, 8); + + __m256i even_b = _mm256_srai_epi16(_mm256_bslli_epi128(b.val, 1), 8); + __m256i odd_b = _mm256_srai_epi16(b.val, 8); + + __m256i prod0 = _mm256_madd_epi16(even_a, even_b); + __m256i prod1 = _mm256_madd_epi16(odd_a, odd_b); + return v_int32x8(_mm256_add_epi32(prod0, prod1)); +} +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i mullo = _mm256_mullo_epi16(a.val, b.val); + __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); + __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); + __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); + + __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); + __m256i p13 = _mm256_srli_epi64(mul0, 32); + __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); + __m256i p57 = _mm256_srli_epi64(mul1, 32); + + __m256i p15_ = _mm256_add_epi64(p02, p13); + __m256i p9d_ = _mm256_add_epi64(p46, p57); + + return v_uint64x4(_mm256_add_epi64( + _mm256_unpacklo_epi64(p15_, p9d_), + _mm256_unpackhi_epi64(p15_, p9d_) + )); +} +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) +{ + __m256i prod = _mm256_madd_epi16(a.val, b.val); + __m256i sign = _mm256_srai_epi32(prod, 31); + + __m256i lo = _mm256_unpacklo_epi32(prod, sign); + __m256i hi = _mm256_unpackhi_epi32(prod, sign); + + return v_int64x4(_mm256_add_epi64( + _mm256_unpacklo_epi64(lo, hi), + _mm256_unpackhi_epi64(lo, hi) + )); +} +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) +{ return v_dotprod(a, b); } +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod(a, b); } +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i mullo = _mm256_mullo_epi16(a.val, b.val); + __m256i mulhi = _mm256_mulhi_epu16(a.val, b.val); + __m256i mul0 = _mm256_unpacklo_epi16(mullo, mulhi); + __m256i mul1 = _mm256_unpackhi_epi16(mullo, mulhi); + + __m256i p02 = _mm256_blend_epi32(mul0, _mm256_setzero_si256(), 0xAA); + __m256i p13 = _mm256_srli_epi64(mul0, 32); + __m256i p46 = _mm256_blend_epi32(mul1, _mm256_setzero_si256(), 0xAA); + __m256i p57 = _mm256_srli_epi64(mul1, 32); + + __m256i p15_ = _mm256_add_epi64(p02, p13); + __m256i p9d_ = _mm256_add_epi64(p46, p57); + + return v_uint64x4(_mm256_add_epi64(p15_, p9d_)); +} +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) +{ + __m256i prod = _mm256_madd_epi16(a.val, b.val); + __m256i sign = _mm256_srai_epi32(prod, 31); + __m256i lo = _mm256_unpacklo_epi32(prod, sign); + __m256i hi = _mm256_unpackhi_epi32(prod, sign); + return v_int64x4(_mm256_add_epi64(lo, hi)); +} +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_dotprod_expand(a, b, c); } + +#define OPENCV_HAL_AVX_SPLAT2_PS(a, im) \ + v_float32x8(_mm256_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) + +inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& m3) +{ + v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); + v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); + v_float32x8 v37 = OPENCV_HAL_AVX_SPLAT2_PS(v, 3); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); +} + +inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& a) +{ + v_float32x8 v04 = OPENCV_HAL_AVX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_AVX_SPLAT2_PS(v, 1); + v_float32x8 v26 = OPENCV_HAL_AVX_SPLAT2_PS(v, 2); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); +} + +#define OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m256i t0 = cast_from(_mm256_unpacklo_##suffix(a0.val, a1.val)); \ + __m256i t1 = cast_from(_mm256_unpacklo_##suffix(a2.val, a3.val)); \ + __m256i t2 = cast_from(_mm256_unpackhi_##suffix(a0.val, a1.val)); \ + __m256i t3 = cast_from(_mm256_unpackhi_##suffix(a2.val, a3.val)); \ + b0.val = cast_to(_mm256_unpacklo_epi64(t0, t1)); \ + b1.val = cast_to(_mm256_unpackhi_epi64(t0, t1)); \ + b2.val = cast_to(_mm256_unpacklo_epi64(t2, t3)); \ + b3.val = cast_to(_mm256_unpackhi_epi64(t2, t3)); \ + } + +OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_uint32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_int32x8, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX_TRANSPOSE4x4(v_float32x8, ps, _mm256_castps_si256, _mm256_castsi256_ps) + +//////////////// Value reordering /////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_AVX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(_v256_extract_low(a.val)); \ + b1.val = intrin(_v256_extract_high(a.val)); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v256_extract_low(a.val))); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v256_extract_high(a.val))); } \ + inline _Tpwvec v256_load_expand(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ + return _Tpwvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX_EXPAND(v_uint8x32, v_uint16x16, uchar, _mm256_cvtepu8_epi16) +OPENCV_HAL_IMPL_AVX_EXPAND(v_int8x32, v_int16x16, schar, _mm256_cvtepi8_epi16) +OPENCV_HAL_IMPL_AVX_EXPAND(v_uint16x16, v_uint32x8, ushort, _mm256_cvtepu16_epi32) +OPENCV_HAL_IMPL_AVX_EXPAND(v_int16x16, v_int32x8, short, _mm256_cvtepi16_epi32) +OPENCV_HAL_IMPL_AVX_EXPAND(v_uint32x8, v_uint64x4, unsigned, _mm256_cvtepu32_epi64) +OPENCV_HAL_IMPL_AVX_EXPAND(v_int32x8, v_int64x4, int, _mm256_cvtepi32_epi64) + +#define OPENCV_HAL_IMPL_AVX_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ + return _Tpvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_uint32x8, uchar, _mm256_cvtepu8_epi32) +OPENCV_HAL_IMPL_AVX_EXPAND_Q(v_int32x8, schar, _mm256_cvtepi8_epi32) + +/* pack */ +// 16 +inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) +{ return v_int8x32(_v256_shuffle_odd_64(_mm256_packs_epi16(a.val, b.val))); } + +inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i t = _mm256_set1_epi16(255); + __m256i a1 = _mm256_min_epu16(a.val, t); + __m256i b1 = _mm256_min_epu16(b.val, t); + return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a1, b1))); +} + +inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + return v_uint8x32(_v256_shuffle_odd_64(_mm256_packus_epi16(a.val, b.val))); +} + +inline void v_pack_store(schar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar* ptr, const v_uint16x16& a) +{ + const __m256i m = _mm256_set1_epi16(255); + __m256i am = _mm256_min_epu16(a.val, m); + am = _v256_shuffle_odd_64(_mm256_packus_epi16(am, am)); + v_store_low(ptr, v_uint8x32(am)); +} + +inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); + return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) +{ + v_uint16x16 delta = v256_setall_u16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x16& a) +{ + v_int16x16 delta = v256_setall_s16((short)(1 << (n-1))); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 32 +inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) +{ return v_int16x16(_v256_shuffle_odd_64(_mm256_packs_epi32(a.val, b.val))); } + +inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } + +inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_mm256_packus_epi32(a.val, b.val))); } + +inline void v_pack_store(short* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x8& a) +{ + const __m256i m = _mm256_set1_epi32(65535); + __m256i am = _mm256_min_epu32(a.val, m); + am = _v256_shuffle_odd_64(_mm256_packus_epi32(am, am)); + v_store_low(ptr, v_uint16x16(am)); +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + + +template inline +v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) +{ + // we assume that n > 0, and so the shifted 32-bit values can be treated as signed numbers. + v_uint32x8 delta = v256_setall_u32(1 << (n-1)); + return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) +{ + v_uint32x8 delta = v256_setall_u32(1 << (n-1)); + v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x8& a) +{ + v_int32x8 delta = v256_setall_s32(1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 64 +// Non-saturating pack +inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) +{ + __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); + __m256i b0 = _mm256_shuffle_epi32(b.val, _MM_SHUFFLE(0, 0, 2, 0)); + __m256i ab = _mm256_unpacklo_epi64(a0, b0); // a0, a1, b0, b1, a2, a3, b2, b3 + return v_uint32x8(_v256_shuffle_odd_64(ab)); +} + +inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + __m256i a0 = _mm256_shuffle_epi32(a.val, _MM_SHUFFLE(0, 0, 2, 0)); + v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); +} + +inline void v_pack_store(int* ptr, const v_int64x4& b) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } + +template inline +v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) +{ + v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + v_uint64x4 delta = v256_setall_u64((uint64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) +{ + v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x4& a) +{ + v_int64x4 delta = v256_setall_s64((int64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// pack boolean +inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i ab = _mm256_packs_epi16(a.val, b.val); + return v_uint8x32(_v256_shuffle_odd_64(ab)); +} + +inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d) +{ + __m256i ab = _mm256_packs_epi32(a.val, b.val); + __m256i cd = _mm256_packs_epi32(c.val, d.val); + + __m256i abcd = _v256_shuffle_odd_64(_mm256_packs_epi16(ab, cd)); + return v_uint8x32(_mm256_shuffle_epi32(abcd, _MM_SHUFFLE(3, 1, 2, 0))); +} + +inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, + const v_uint64x4& g, const v_uint64x4& h) +{ + __m256i ab = _mm256_packs_epi32(a.val, b.val); + __m256i cd = _mm256_packs_epi32(c.val, d.val); + __m256i ef = _mm256_packs_epi32(e.val, f.val); + __m256i gh = _mm256_packs_epi32(g.val, h.val); + + __m256i abcd = _mm256_packs_epi32(ab, cd); + __m256i efgh = _mm256_packs_epi32(ef, gh); + __m256i pkall = _v256_shuffle_odd_64(_mm256_packs_epi16(abcd, efgh)); + + __m256i rev = _mm256_alignr_epi8(pkall, pkall, 8); + return v_uint8x32(_mm256_unpacklo_epi16(pkall, rev)); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_AVX_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint8x32) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int8x32) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint16x16) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int16x16) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint32x8) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int32x8) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_uint64x4) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_int64x4) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_float32x8) +OPENCV_HAL_IMPL_AVX_EXTRACT(v_float64x4) + +template +inline uchar v_extract_n(v_uint8x32 a) +{ + return (uchar)_v256_extract_epi8(a.val); +} + +template +inline schar v_extract_n(v_int8x32 a) +{ + return (schar)v_extract_n(v_reinterpret_as_u8(a)); +} + +template +inline ushort v_extract_n(v_uint16x16 a) +{ + return (ushort)_v256_extract_epi16(a.val); +} + +template +inline short v_extract_n(v_int16x16 a) +{ + return (short)v_extract_n(v_reinterpret_as_u16(a)); +} + +template +inline uint v_extract_n(v_uint32x8 a) +{ + return (uint)_v256_extract_epi32(a.val); +} + +template +inline int v_extract_n(v_int32x8 a) +{ + return (int)v_extract_n(v_reinterpret_as_u32(a)); +} + +template +inline uint64 v_extract_n(v_uint64x4 a) +{ + return (uint64)_v256_extract_epi64(a.val); +} + +template +inline int64 v_extract_n(v_int64x4 v) +{ + return (int64)v_extract_n(v_reinterpret_as_u64(v)); +} + +template +inline float v_extract_n(v_float32x8 v) +{ + union { uint iv; float fv; } d; + d.iv = v_extract_n(v_reinterpret_as_u32(v)); + return d.fv; +} + +template +inline double v_extract_n(v_float64x4 v) +{ + union { uint64 iv; double dv; } d; + d.iv = v_extract_n(v_reinterpret_as_u64(v)); + return d.dv; +} + +template +inline v_uint32x8 v_broadcast_element(v_uint32x8 a) +{ + static const __m256i perm = _mm256_set1_epi32((char)i); + return v_uint32x8(_mm256_permutevar8x32_epi32(a.val, perm)); +} + +template +inline v_int32x8 v_broadcast_element(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +template +inline v_float32x8 v_broadcast_element(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } + + +///////////////////// load deinterleave ///////////////////////////// + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + + const __m256i sh = _mm256_setr_epi8(0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15, + 0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15); + __m256i p0 = _mm256_shuffle_epi8(ab0, sh); + __m256i p1 = _mm256_shuffle_epi8(ab1, sh); + __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint8x32(a0); + b = v_uint8x32(b0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + + const __m256i sh = _mm256_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15, + 0, 1, 4, 5, 8, 9, 12, 13, 2, 3, 6, 7, 10, 11, 14, 15); + __m256i p0 = _mm256_shuffle_epi8(ab0, sh); + __m256i p1 = _mm256_shuffle_epi8(ab1, sh); + __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint16x16(a0); + b = v_uint16x16(b0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + + enum { sh = 0+2*4+1*16+3*64 }; + __m256i p0 = _mm256_shuffle_epi32(ab0, sh); + __m256i p1 = _mm256_shuffle_epi32(ab1, sh); + __m256i pl = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint32x8(a0); + b = v_uint32x8(b0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) +{ + __m256i ab0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i ab1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); + + __m256i pl = _mm256_permute2x128_si256(ab0, ab1, 0 + 2*16); + __m256i ph = _mm256_permute2x128_si256(ab0, ab1, 1 + 3*16); + __m256i a0 = _mm256_unpacklo_epi64(pl, ph); + __m256i b0 = _mm256_unpackhi_epi64(pl, ph); + a = v_uint64x4(a0); + b = v_uint64x4(b0); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); + + __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); + __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); + + const __m256i m0 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + + __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); + __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); + + const __m256i + sh_b = _mm256_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, + 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), + sh_g = _mm256_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, + 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), + sh_r = _mm256_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, + 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); + b0 = _mm256_shuffle_epi8(b0, sh_b); + g0 = _mm256_shuffle_epi8(g0, sh_g); + r0 = _mm256_shuffle_epi8(r0, sh_r); + + a = v_uint8x32(b0); + b = v_uint8x32(g0); + c = v_uint8x32(r0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + + __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); + __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); + + const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + __m256i b0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = _mm256_blendv_epi8(_mm256_blendv_epi8(bgr1, s02_low, m0), s02_high, m1); + __m256i r0 = _mm256_blendv_epi8(_mm256_blendv_epi8(s02_high, s02_low, m1), bgr1, m0); + const __m256i sh_b = _mm256_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _mm256_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, + 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); + const __m256i sh_r = _mm256_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + b0 = _mm256_shuffle_epi8(b0, sh_b); + g0 = _mm256_shuffle_epi8(g0, sh_g); + r0 = _mm256_shuffle_epi8(r0, sh_r); + + a = v_uint16x16(b0); + b = v_uint16x16(g0); + c = v_uint16x16(r0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + + __m256i s02_low = _mm256_permute2x128_si256(bgr0, bgr2, 0 + 2*16); + __m256i s02_high = _mm256_permute2x128_si256(bgr0, bgr2, 1 + 3*16); + + __m256i b0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_low, s02_high, 0x24), bgr1, 0x92); + __m256i g0 = _mm256_blend_epi32(_mm256_blend_epi32(s02_high, s02_low, 0x92), bgr1, 0x24); + __m256i r0 = _mm256_blend_epi32(_mm256_blend_epi32(bgr1, s02_low, 0x24), s02_high, 0x92); + + b0 = _mm256_shuffle_epi32(b0, 0x6c); + g0 = _mm256_shuffle_epi32(g0, 0xb1); + r0 = _mm256_shuffle_epi32(r0, 0xc6); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + + __m256i s01 = _mm256_blend_epi32(bgr0, bgr1, 0xf0); + __m256i s12 = _mm256_blend_epi32(bgr1, bgr2, 0xf0); + __m256i s20r = _mm256_permute4x64_epi64(_mm256_blend_epi32(bgr2, bgr0, 0xf0), 0x1b); + __m256i b0 = _mm256_unpacklo_epi64(s01, s20r); + __m256i g0 = _mm256_alignr_epi8(s12, s01, 8); + __m256i r0 = _mm256_unpackhi_epi64(s20r, s12); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 64)); + __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 96)); + const __m256i sh = _mm256_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, + 0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15); + + __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); + __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); + __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); + __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); + + __m256i p01l = _mm256_unpacklo_epi32(p0, p1); + __m256i p01h = _mm256_unpackhi_epi32(p0, p1); + __m256i p23l = _mm256_unpacklo_epi32(p2, p3); + __m256i p23h = _mm256_unpackhi_epi32(p2, p3); + + __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); + __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); + __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); + __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi32(pll, plh); + __m256i g0 = _mm256_unpackhi_epi32(pll, plh); + __m256i r0 = _mm256_unpacklo_epi32(phl, phh); + __m256i a0 = _mm256_unpackhi_epi32(phl, phh); + + a = v_uint8x32(b0); + b = v_uint8x32(g0); + c = v_uint8x32(r0); + d = v_uint8x32(a0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d ) +{ + __m256i bgr0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgr1 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + __m256i bgr2 = _mm256_loadu_si256((const __m256i*)(ptr + 32)); + __m256i bgr3 = _mm256_loadu_si256((const __m256i*)(ptr + 48)); + const __m256i sh = _mm256_setr_epi8(0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15, + 0, 1, 8, 9, 2, 3, 10, 11, 4, 5, 12, 13, 6, 7, 14, 15); + __m256i p0 = _mm256_shuffle_epi8(bgr0, sh); + __m256i p1 = _mm256_shuffle_epi8(bgr1, sh); + __m256i p2 = _mm256_shuffle_epi8(bgr2, sh); + __m256i p3 = _mm256_shuffle_epi8(bgr3, sh); + + __m256i p01l = _mm256_unpacklo_epi32(p0, p1); + __m256i p01h = _mm256_unpackhi_epi32(p0, p1); + __m256i p23l = _mm256_unpacklo_epi32(p2, p3); + __m256i p23h = _mm256_unpackhi_epi32(p2, p3); + + __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); + __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); + __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); + __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi32(pll, plh); + __m256i g0 = _mm256_unpackhi_epi32(pll, plh); + __m256i r0 = _mm256_unpacklo_epi32(phl, phh); + __m256i a0 = _mm256_unpackhi_epi32(phl, phh); + + a = v_uint16x16(b0); + b = v_uint16x16(g0); + c = v_uint16x16(r0); + d = v_uint16x16(a0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) +{ + __m256i p0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i p1 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + __m256i p2 = _mm256_loadu_si256((const __m256i*)(ptr + 16)); + __m256i p3 = _mm256_loadu_si256((const __m256i*)(ptr + 24)); + + __m256i p01l = _mm256_unpacklo_epi32(p0, p1); + __m256i p01h = _mm256_unpackhi_epi32(p0, p1); + __m256i p23l = _mm256_unpacklo_epi32(p2, p3); + __m256i p23h = _mm256_unpackhi_epi32(p2, p3); + + __m256i pll = _mm256_permute2x128_si256(p01l, p23l, 0 + 2*16); + __m256i plh = _mm256_permute2x128_si256(p01l, p23l, 1 + 3*16); + __m256i phl = _mm256_permute2x128_si256(p01h, p23h, 0 + 2*16); + __m256i phh = _mm256_permute2x128_si256(p01h, p23h, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi32(pll, plh); + __m256i g0 = _mm256_unpackhi_epi32(pll, plh); + __m256i r0 = _mm256_unpacklo_epi32(phl, phh); + __m256i a0 = _mm256_unpackhi_epi32(phl, phh); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); + d = v_uint32x8(a0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) +{ + __m256i bgra0 = _mm256_loadu_si256((const __m256i*)ptr); + __m256i bgra1 = _mm256_loadu_si256((const __m256i*)(ptr + 4)); + __m256i bgra2 = _mm256_loadu_si256((const __m256i*)(ptr + 8)); + __m256i bgra3 = _mm256_loadu_si256((const __m256i*)(ptr + 12)); + + __m256i l02 = _mm256_permute2x128_si256(bgra0, bgra2, 0 + 2*16); + __m256i h02 = _mm256_permute2x128_si256(bgra0, bgra2, 1 + 3*16); + __m256i l13 = _mm256_permute2x128_si256(bgra1, bgra3, 0 + 2*16); + __m256i h13 = _mm256_permute2x128_si256(bgra1, bgra3, 1 + 3*16); + + __m256i b0 = _mm256_unpacklo_epi64(l02, l13); + __m256i g0 = _mm256_unpackhi_epi64(l02, l13); + __m256i r0 = _mm256_unpacklo_epi64(h02, h13); + __m256i a0 = _mm256_unpackhi_epi64(h02, h13); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); + d = v_uint64x4(a0); +} + +///////////////////////////// store interleave ///////////////////////////////////// + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi8(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi8(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 32), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 32), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 32), xy1); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi16(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi16(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 16), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 16), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 16), xy1); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi32(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi32(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 8), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 8), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 8), xy1); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = _mm256_unpacklo_epi64(x.val, y.val); + __m256i xy_h = _mm256_unpackhi_epi64(x.val, y.val); + + __m256i xy0 = _mm256_permute2x128_si256(xy_l, xy_h, 0 + 2*16); + __m256i xy1 = _mm256_permute2x128_si256(xy_l, xy_h, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, xy0); + _mm256_stream_si256((__m256i*)(ptr + 4), xy1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, xy0); + _mm256_store_si256((__m256i*)(ptr + 4), xy1); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, xy0); + _mm256_storeu_si256((__m256i*)(ptr + 4), xy1); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _mm256_setr_epi8( + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); + const __m256i sh_g = _mm256_setr_epi8( + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); + const __m256i sh_r = _mm256_setr_epi8( + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); + + __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); + __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); + __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); + + const __m256i m0 = _mm256_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + + __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); + __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); + __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); + + __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + __m256i bgr1 = _mm256_permute2x128_si256(p2, p0, 0 + 3*16); + __m256i bgr2 = _mm256_permute2x128_si256(p1, p2, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 32), bgr1); + _mm256_stream_si256((__m256i*)(ptr + 64), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 32), bgr1); + _mm256_store_si256((__m256i*)(ptr + 64), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgr1); + _mm256_storeu_si256((__m256i*)(ptr + 64), bgr2); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _mm256_setr_epi8( + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _mm256_setr_epi8( + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); + const __m256i sh_r = _mm256_setr_epi8( + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + + __m256i b0 = _mm256_shuffle_epi8(a.val, sh_b); + __m256i g0 = _mm256_shuffle_epi8(b.val, sh_g); + __m256i r0 = _mm256_shuffle_epi8(c.val, sh_r); + + const __m256i m0 = _mm256_setr_epi8(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _mm256_setr_epi8(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + + __m256i p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, g0, m0), r0, m1); + __m256i p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, r0, m0), b0, m1); + __m256i p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, b0, m0), g0, m1); + + __m256i bgr0 = _mm256_permute2x128_si256(p0, p2, 0 + 2*16); + //__m256i bgr1 = p1; + __m256i bgr2 = _mm256_permute2x128_si256(p0, p2, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 16), p1); + _mm256_stream_si256((__m256i*)(ptr + 32), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 16), p1); + _mm256_store_si256((__m256i*)(ptr + 32), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 16), p1); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgr2); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i b0 = _mm256_shuffle_epi32(a.val, 0x6c); + __m256i g0 = _mm256_shuffle_epi32(b.val, 0xb1); + __m256i r0 = _mm256_shuffle_epi32(c.val, 0xc6); + + __m256i p0 = _mm256_blend_epi32(_mm256_blend_epi32(b0, g0, 0x92), r0, 0x24); + __m256i p1 = _mm256_blend_epi32(_mm256_blend_epi32(g0, r0, 0x92), b0, 0x24); + __m256i p2 = _mm256_blend_epi32(_mm256_blend_epi32(r0, b0, 0x92), g0, 0x24); + + __m256i bgr0 = _mm256_permute2x128_si256(p0, p1, 0 + 2*16); + //__m256i bgr1 = p2; + __m256i bgr2 = _mm256_permute2x128_si256(p0, p1, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 8), p2); + _mm256_stream_si256((__m256i*)(ptr + 16), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 8), p2); + _mm256_store_si256((__m256i*)(ptr + 16), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 8), p2); + _mm256_storeu_si256((__m256i*)(ptr + 16), bgr2); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i s01 = _mm256_unpacklo_epi64(a.val, b.val); + __m256i s12 = _mm256_unpackhi_epi64(b.val, c.val); + __m256i s20 = _mm256_blend_epi32(c.val, a.val, 0xcc); + + __m256i bgr0 = _mm256_permute2x128_si256(s01, s20, 0 + 2*16); + __m256i bgr1 = _mm256_blend_epi32(s01, s12, 0x0f); + __m256i bgr2 = _mm256_permute2x128_si256(s20, s12, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgr0); + _mm256_stream_si256((__m256i*)(ptr + 4), bgr1); + _mm256_stream_si256((__m256i*)(ptr + 8), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgr0); + _mm256_store_si256((__m256i*)(ptr + 4), bgr1); + _mm256_store_si256((__m256i*)(ptr + 8), bgr2); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgr0); + _mm256_storeu_si256((__m256i*)(ptr + 4), bgr1); + _mm256_storeu_si256((__m256i*)(ptr + 8), bgr2); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, + const v_uint8x32& c, const v_uint8x32& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi8(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi8(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi8(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi8(c.val, d.val); + + __m256i bgra0_ = _mm256_unpacklo_epi16(bg0, ra0); + __m256i bgra1_ = _mm256_unpackhi_epi16(bg0, ra0); + __m256i bgra2_ = _mm256_unpacklo_epi16(bg1, ra1); + __m256i bgra3_ = _mm256_unpackhi_epi16(bg1, ra1); + + __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); + __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); + __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 32), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 64), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 96), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 32), bgra1); + _mm256_store_si256((__m256i*)(ptr + 64), bgra2); + _mm256_store_si256((__m256i*)(ptr + 96), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 64), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 96), bgra3); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, + const v_uint16x16& c, const v_uint16x16& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi16(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi16(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi16(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi16(c.val, d.val); + + __m256i bgra0_ = _mm256_unpacklo_epi32(bg0, ra0); + __m256i bgra1_ = _mm256_unpackhi_epi32(bg0, ra0); + __m256i bgra2_ = _mm256_unpacklo_epi32(bg1, ra1); + __m256i bgra3_ = _mm256_unpackhi_epi32(bg1, ra1); + + __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); + __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); + __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 16), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 32), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 48), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 16), bgra1); + _mm256_store_si256((__m256i*)(ptr + 32), bgra2); + _mm256_store_si256((__m256i*)(ptr + 48), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 16), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 32), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 48), bgra3); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi32(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi32(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi32(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi32(c.val, d.val); + + __m256i bgra0_ = _mm256_unpacklo_epi64(bg0, ra0); + __m256i bgra1_ = _mm256_unpackhi_epi64(bg0, ra0); + __m256i bgra2_ = _mm256_unpacklo_epi64(bg1, ra1); + __m256i bgra3_ = _mm256_unpackhi_epi64(bg1, ra1); + + __m256i bgra0 = _mm256_permute2x128_si256(bgra0_, bgra1_, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bgra0_, bgra1_, 1 + 3*16); + __m256i bgra1 = _mm256_permute2x128_si256(bgra2_, bgra3_, 0 + 2*16); + __m256i bgra3 = _mm256_permute2x128_si256(bgra2_, bgra3_, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 8), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 16), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 24), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 8), bgra1); + _mm256_store_si256((__m256i*)(ptr + 16), bgra2); + _mm256_store_si256((__m256i*)(ptr + 24), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 8), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 16), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 24), bgra3); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, + const v_uint64x4& c, const v_uint64x4& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = _mm256_unpacklo_epi64(a.val, b.val); + __m256i bg1 = _mm256_unpackhi_epi64(a.val, b.val); + __m256i ra0 = _mm256_unpacklo_epi64(c.val, d.val); + __m256i ra1 = _mm256_unpackhi_epi64(c.val, d.val); + + __m256i bgra0 = _mm256_permute2x128_si256(bg0, ra0, 0 + 2*16); + __m256i bgra1 = _mm256_permute2x128_si256(bg1, ra1, 0 + 2*16); + __m256i bgra2 = _mm256_permute2x128_si256(bg0, ra0, 1 + 3*16); + __m256i bgra3 = _mm256_permute2x128_si256(bg1, ra1, 1 + 3*16); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm256_stream_si256((__m256i*)ptr, bgra0); + _mm256_stream_si256((__m256i*)(ptr + 4), bgra1); + _mm256_stream_si256((__m256i*)(ptr + 8), bgra2); + _mm256_stream_si256((__m256i*)(ptr + 12), bgra3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm256_store_si256((__m256i*)ptr, bgra0); + _mm256_store_si256((__m256i*)(ptr + 4), bgra1); + _mm256_store_si256((__m256i*)(ptr + 8), bgra2); + _mm256_store_si256((__m256i*)(ptr + 12), bgra3); + } + else + { + _mm256_storeu_si256((__m256i*)ptr, bgra0); + _mm256_storeu_si256((__m256i*)(ptr + 4), bgra1); + _mm256_storeu_si256((__m256i*)(ptr + 8), bgra2); + _mm256_storeu_si256((__m256i*)(ptr + 12), bgra3); + } +} + +#define OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) +OPENCV_HAL_IMPL_AVX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) + +// +// FP16 +// + +inline v_float32x8 v256_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + return v_float32x8(_mm256_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); +#else + float CV_DECL_ALIGNED(32) buf[8]; + for (int i = 0; i < 8; i++) + buf[i] = (float)ptr[i]; + return v256_load_aligned(buf); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x8& a) +{ +#if CV_FP16 + __m128i ah = _mm256_cvtps_ph(a.val, 0); + _mm_storeu_si128((__m128i*)ptr, ah); +#else + float CV_DECL_ALIGNED(32) buf[8]; + v_store_aligned(buf, a); + for (int i = 0; i < 8; i++) + ptr[i] = hfloat(buf[i]); +#endif +} + +// +// end of FP16 +// + +inline void v256_cleanup() { _mm256_zeroall(); } + +#include "intrin_math.hpp" +inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } +inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } +inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } +inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } + +inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } +inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } +inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_AVX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp index 9d6eee2dde..077b4d17a7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_avx512.hpp @@ -1,3101 +1,3101 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_AVX512_HPP -#define OPENCV_HAL_INTRIN_AVX512_HPP - -#if defined(_MSC_VER) && (_MSC_VER < 1920/*MSVS2019*/) -# pragma warning(disable:4146) // unary minus operator applied to unsigned type, result still unsigned -# pragma warning(disable:4309) // 'argument': truncation of constant value -# pragma warning(disable:4310) // cast truncates constant value -#endif - -#define CVT_ROUND_MODES_IMPLEMENTED 0 - -#define CV_SIMD512 1 -#define CV_SIMD512_64F 1 -#define CV_SIMD512_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) - -#define _v512_set_epu64(a7, a6, a5, a4, a3, a2, a1, a0) _mm512_set_epi64((int64)(a7),(int64)(a6),(int64)(a5),(int64)(a4),(int64)(a3),(int64)(a2),(int64)(a1),(int64)(a0)) -#define _v512_set_epu32(a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _mm512_set_epi64(((int64)(a15)<<32)|(int64)(a14), ((int64)(a13)<<32)|(int64)(a12), ((int64)(a11)<<32)|(int64)(a10), ((int64)( a9)<<32)|(int64)( a8), \ - ((int64)( a7)<<32)|(int64)( a6), ((int64)( a5)<<32)|(int64)( a4), ((int64)( a3)<<32)|(int64)( a2), ((int64)( a1)<<32)|(int64)( a0)) -#define _v512_set_epu16(a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ - a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _v512_set_epu32(((unsigned)(a31)<<16)|(unsigned)(a30), ((unsigned)(a29)<<16)|(unsigned)(a28), ((unsigned)(a27)<<16)|(unsigned)(a26), ((unsigned)(a25)<<16)|(unsigned)(a24), \ - ((unsigned)(a23)<<16)|(unsigned)(a22), ((unsigned)(a21)<<16)|(unsigned)(a20), ((unsigned)(a19)<<16)|(unsigned)(a18), ((unsigned)(a17)<<16)|(unsigned)(a16), \ - ((unsigned)(a15)<<16)|(unsigned)(a14), ((unsigned)(a13)<<16)|(unsigned)(a12), ((unsigned)(a11)<<16)|(unsigned)(a10), ((unsigned)( a9)<<16)|(unsigned)( a8), \ - ((unsigned)( a7)<<16)|(unsigned)( a6), ((unsigned)( a5)<<16)|(unsigned)( a4), ((unsigned)( a3)<<16)|(unsigned)( a2), ((unsigned)( a1)<<16)|(unsigned)( a0)) -#define _v512_set_epu8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ - a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ - a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ - a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _v512_set_epu32(((unsigned)(a63)<<24)|((unsigned)(a62)<<16)|((unsigned)(a61)<<8)|(unsigned)(a60),((unsigned)(a59)<<24)|((unsigned)(a58)<<16)|((unsigned)(a57)<<8)|(unsigned)(a56), \ - ((unsigned)(a55)<<24)|((unsigned)(a54)<<16)|((unsigned)(a53)<<8)|(unsigned)(a52),((unsigned)(a51)<<24)|((unsigned)(a50)<<16)|((unsigned)(a49)<<8)|(unsigned)(a48), \ - ((unsigned)(a47)<<24)|((unsigned)(a46)<<16)|((unsigned)(a45)<<8)|(unsigned)(a44),((unsigned)(a43)<<24)|((unsigned)(a42)<<16)|((unsigned)(a41)<<8)|(unsigned)(a40), \ - ((unsigned)(a39)<<24)|((unsigned)(a38)<<16)|((unsigned)(a37)<<8)|(unsigned)(a36),((unsigned)(a35)<<24)|((unsigned)(a34)<<16)|((unsigned)(a33)<<8)|(unsigned)(a32), \ - ((unsigned)(a31)<<24)|((unsigned)(a30)<<16)|((unsigned)(a29)<<8)|(unsigned)(a28),((unsigned)(a27)<<24)|((unsigned)(a26)<<16)|((unsigned)(a25)<<8)|(unsigned)(a24), \ - ((unsigned)(a23)<<24)|((unsigned)(a22)<<16)|((unsigned)(a21)<<8)|(unsigned)(a20),((unsigned)(a19)<<24)|((unsigned)(a18)<<16)|((unsigned)(a17)<<8)|(unsigned)(a16), \ - ((unsigned)(a15)<<24)|((unsigned)(a14)<<16)|((unsigned)(a13)<<8)|(unsigned)(a12),((unsigned)(a11)<<24)|((unsigned)(a10)<<16)|((unsigned)( a9)<<8)|(unsigned)( a8), \ - ((unsigned)( a7)<<24)|((unsigned)( a6)<<16)|((unsigned)( a5)<<8)|(unsigned)( a4),((unsigned)( a3)<<24)|((unsigned)( a2)<<16)|((unsigned)( a1)<<8)|(unsigned)( a0)) -#define _v512_set_epi8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ - a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ - a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ - a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ - _v512_set_epu8((uchar)(a63), (uchar)(a62), (uchar)(a61), (uchar)(a60), (uchar)(a59), (uchar)(a58), (uchar)(a57), (uchar)(a56), \ - (uchar)(a55), (uchar)(a54), (uchar)(a53), (uchar)(a52), (uchar)(a51), (uchar)(a50), (uchar)(a49), (uchar)(a48), \ - (uchar)(a47), (uchar)(a46), (uchar)(a45), (uchar)(a44), (uchar)(a43), (uchar)(a42), (uchar)(a41), (uchar)(a40), \ - (uchar)(a39), (uchar)(a38), (uchar)(a37), (uchar)(a36), (uchar)(a35), (uchar)(a34), (uchar)(a33), (uchar)(a32), \ - (uchar)(a31), (uchar)(a30), (uchar)(a29), (uchar)(a28), (uchar)(a27), (uchar)(a26), (uchar)(a25), (uchar)(a24), \ - (uchar)(a23), (uchar)(a22), (uchar)(a21), (uchar)(a20), (uchar)(a19), (uchar)(a18), (uchar)(a17), (uchar)(a16), \ - (uchar)(a15), (uchar)(a14), (uchar)(a13), (uchar)(a12), (uchar)(a11), (uchar)(a10), (uchar)( a9), (uchar)( a8), \ - (uchar)( a7), (uchar)( a6), (uchar)( a5), (uchar)( a4), (uchar)( a3), (uchar)( a2), (uchar)( a1), (uchar)( a0)) - -#ifndef _mm512_cvtpd_pslo -#ifdef _mm512_zextsi256_si512 -#define _mm512_cvtpd_pslo(a) _mm512_zextps256_ps512(_mm512_cvtpd_ps(a)) -#else -//if preferred way to extend with zeros is unavailable -#define _mm512_cvtpd_pslo(a) _mm512_castps256_ps512(_mm512_cvtpd_ps(a)) -#endif -#endif -///////// Utils //////////// - -namespace -{ - -inline __m512i _v512_combine(const __m256i& lo, const __m256i& hi) -{ return _mm512_inserti32x8(_mm512_castsi256_si512(lo), hi, 1); } - -inline __m512 _v512_combine(const __m256& lo, const __m256& hi) -{ return _mm512_insertf32x8(_mm512_castps256_ps512(lo), hi, 1); } - -inline __m512d _v512_combine(const __m256d& lo, const __m256d& hi) -{ return _mm512_insertf64x4(_mm512_castpd256_pd512(lo), hi, 1); } - -inline int _v_cvtsi512_si32(const __m512i& a) -{ return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); } - -inline __m256i _v512_extract_high(const __m512i& v) -{ return _mm512_extracti32x8_epi32(v, 1); } - -inline __m256 _v512_extract_high(const __m512& v) -{ return _mm512_extractf32x8_ps(v, 1); } - -inline __m256d _v512_extract_high(const __m512d& v) -{ return _mm512_extractf64x4_pd(v, 1); } - -inline __m256i _v512_extract_low(const __m512i& v) -{ return _mm512_castsi512_si256(v); } - -inline __m256 _v512_extract_low(const __m512& v) -{ return _mm512_castps512_ps256(v); } - -inline __m256d _v512_extract_low(const __m512d& v) -{ return _mm512_castpd512_pd256(v); } - -inline __m512i _v512_insert(const __m512i& a, const __m256i& b) -{ return _mm512_inserti32x8(a, b, 0); } - -inline __m512 _v512_insert(const __m512& a, const __m256& b) -{ return _mm512_insertf32x8(a, b, 0); } - -inline __m512d _v512_insert(const __m512d& a, const __m256d& b) -{ return _mm512_insertf64x4(a, b, 0); } - -} - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Types //////////// - -struct v_uint8x64 -{ - typedef uchar lane_type; - enum { nlanes = 64 }; - __m512i val; - - explicit v_uint8x64(__m512i v) : val(v) {} - v_uint8x64(uchar v0, uchar v1, uchar v2, uchar v3, - uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, - uchar v12, uchar v13, uchar v14, uchar v15, - uchar v16, uchar v17, uchar v18, uchar v19, - uchar v20, uchar v21, uchar v22, uchar v23, - uchar v24, uchar v25, uchar v26, uchar v27, - uchar v28, uchar v29, uchar v30, uchar v31, - uchar v32, uchar v33, uchar v34, uchar v35, - uchar v36, uchar v37, uchar v38, uchar v39, - uchar v40, uchar v41, uchar v42, uchar v43, - uchar v44, uchar v45, uchar v46, uchar v47, - uchar v48, uchar v49, uchar v50, uchar v51, - uchar v52, uchar v53, uchar v54, uchar v55, - uchar v56, uchar v57, uchar v58, uchar v59, - uchar v60, uchar v61, uchar v62, uchar v63) - { - val = _v512_set_epu8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, - v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, - v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, - v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); - } - v_uint8x64() {} - - static inline v_uint8x64 zero() { return v_uint8x64(_mm512_setzero_si512()); } - - uchar get0() const { return (uchar)_v_cvtsi512_si32(val); } -}; - -struct v_int8x64 -{ - typedef schar lane_type; - enum { nlanes = 64 }; - __m512i val; - - explicit v_int8x64(__m512i v) : val(v) {} - v_int8x64(schar v0, schar v1, schar v2, schar v3, - schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, - schar v12, schar v13, schar v14, schar v15, - schar v16, schar v17, schar v18, schar v19, - schar v20, schar v21, schar v22, schar v23, - schar v24, schar v25, schar v26, schar v27, - schar v28, schar v29, schar v30, schar v31, - schar v32, schar v33, schar v34, schar v35, - schar v36, schar v37, schar v38, schar v39, - schar v40, schar v41, schar v42, schar v43, - schar v44, schar v45, schar v46, schar v47, - schar v48, schar v49, schar v50, schar v51, - schar v52, schar v53, schar v54, schar v55, - schar v56, schar v57, schar v58, schar v59, - schar v60, schar v61, schar v62, schar v63) - { - val = _v512_set_epi8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, - v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, - v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, - v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); - } - v_int8x64() {} - - static inline v_int8x64 zero() { return v_int8x64(_mm512_setzero_si512()); } - - schar get0() const { return (schar)_v_cvtsi512_si32(val); } -}; - -struct v_uint16x32 -{ - typedef ushort lane_type; - enum { nlanes = 32 }; - __m512i val; - - explicit v_uint16x32(__m512i v) : val(v) {} - v_uint16x32(ushort v0, ushort v1, ushort v2, ushort v3, - ushort v4, ushort v5, ushort v6, ushort v7, - ushort v8, ushort v9, ushort v10, ushort v11, - ushort v12, ushort v13, ushort v14, ushort v15, - ushort v16, ushort v17, ushort v18, ushort v19, - ushort v20, ushort v21, ushort v22, ushort v23, - ushort v24, ushort v25, ushort v26, ushort v27, - ushort v28, ushort v29, ushort v30, ushort v31) - { - val = _v512_set_epu16(v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, - v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); - } - v_uint16x32() {} - - static inline v_uint16x32 zero() { return v_uint16x32(_mm512_setzero_si512()); } - - ushort get0() const { return (ushort)_v_cvtsi512_si32(val); } -}; - -struct v_int16x32 -{ - typedef short lane_type; - enum { nlanes = 32 }; - __m512i val; - - explicit v_int16x32(__m512i v) : val(v) {} - v_int16x32(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15, - short v16, short v17, short v18, short v19, short v20, short v21, short v22, short v23, - short v24, short v25, short v26, short v27, short v28, short v29, short v30, short v31) - { - val = _v512_set_epu16((ushort)v31, (ushort)v30, (ushort)v29, (ushort)v28, (ushort)v27, (ushort)v26, (ushort)v25, (ushort)v24, - (ushort)v23, (ushort)v22, (ushort)v21, (ushort)v20, (ushort)v19, (ushort)v18, (ushort)v17, (ushort)v16, - (ushort)v15, (ushort)v14, (ushort)v13, (ushort)v12, (ushort)v11, (ushort)v10, (ushort)v9 , (ushort)v8, - (ushort)v7 , (ushort)v6 , (ushort)v5 , (ushort)v4 , (ushort)v3 , (ushort)v2 , (ushort)v1 , (ushort)v0); - } - v_int16x32() {} - - static inline v_int16x32 zero() { return v_int16x32(_mm512_setzero_si512()); } - - short get0() const { return (short)_v_cvtsi512_si32(val); } -}; - -struct v_uint32x16 -{ - typedef unsigned lane_type; - enum { nlanes = 16 }; - __m512i val; - - explicit v_uint32x16(__m512i v) : val(v) {} - v_uint32x16(unsigned v0, unsigned v1, unsigned v2, unsigned v3, - unsigned v4, unsigned v5, unsigned v6, unsigned v7, - unsigned v8, unsigned v9, unsigned v10, unsigned v11, - unsigned v12, unsigned v13, unsigned v14, unsigned v15) - { - val = _mm512_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3, (int)v4, (int)v5, (int)v6, (int)v7, - (int)v8, (int)v9, (int)v10, (int)v11, (int)v12, (int)v13, (int)v14, (int)v15); - } - v_uint32x16() {} - - static inline v_uint32x16 zero() { return v_uint32x16(_mm512_setzero_si512()); } - - unsigned get0() const { return (unsigned)_v_cvtsi512_si32(val); } -}; - -struct v_int32x16 -{ - typedef int lane_type; - enum { nlanes = 16 }; - __m512i val; - - explicit v_int32x16(__m512i v) : val(v) {} - v_int32x16(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7, - int v8, int v9, int v10, int v11, int v12, int v13, int v14, int v15) - { - val = _mm512_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - v_int32x16() {} - - static inline v_int32x16 zero() { return v_int32x16(_mm512_setzero_si512()); } - - int get0() const { return _v_cvtsi512_si32(val); } -}; - -struct v_float32x16 -{ - typedef float lane_type; - enum { nlanes = 16 }; - __m512 val; - - explicit v_float32x16(__m512 v) : val(v) {} - v_float32x16(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, - float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15) - { - val = _mm512_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - v_float32x16() {} - - static inline v_float32x16 zero() { return v_float32x16(_mm512_setzero_ps()); } - - float get0() const { return _mm_cvtss_f32(_mm512_castps512_ps128(val)); } -}; - -struct v_uint64x8 -{ - typedef uint64 lane_type; - enum { nlanes = 8 }; - __m512i val; - - explicit v_uint64x8(__m512i v) : val(v) {} - v_uint64x8(uint64 v0, uint64 v1, uint64 v2, uint64 v3, uint64 v4, uint64 v5, uint64 v6, uint64 v7) - { val = _mm512_setr_epi64((int64)v0, (int64)v1, (int64)v2, (int64)v3, (int64)v4, (int64)v5, (int64)v6, (int64)v7); } - v_uint64x8() {} - - static inline v_uint64x8 zero() { return v_uint64x8(_mm512_setzero_si512()); } - - uint64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (uint64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); - int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); - return (unsigned)a | ((uint64)(unsigned)b << 32); - #endif - } -}; - -struct v_int64x8 -{ - typedef int64 lane_type; - enum { nlanes = 8 }; - __m512i val; - - explicit v_int64x8(__m512i v) : val(v) {} - v_int64x8(int64 v0, int64 v1, int64 v2, int64 v3, int64 v4, int64 v5, int64 v6, int64 v7) - { val = _mm512_setr_epi64(v0, v1, v2, v3, v4, v5, v6, v7); } - v_int64x8() {} - - static inline v_int64x8 zero() { return v_int64x8(_mm512_setzero_si512()); } - - int64 get0() const - { - #if defined __x86_64__ || defined _M_X64 - return (int64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); - #else - int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); - int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); - return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); - #endif - } -}; - -struct v_float64x8 -{ - typedef double lane_type; - enum { nlanes = 8 }; - __m512d val; - - explicit v_float64x8(__m512d v) : val(v) {} - v_float64x8(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7) - { val = _mm512_setr_pd(v0, v1, v2, v3, v4, v5, v6, v7); } - v_float64x8() {} - - static inline v_float64x8 zero() { return v_float64x8(_mm512_setzero_pd()); } - - double get0() const { return _mm_cvtsd_f64(_mm512_castpd512_pd128(val)); } -}; - -//////////////// Load and store operations /////////////// - -#define OPENCV_HAL_IMPL_AVX512_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v512_load(const _Tp* ptr) \ - { return _Tpvec(_mm512_loadu_si512((const __m512i*)ptr)); } \ - inline _Tpvec v512_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm512_load_si512((const __m512i*)ptr)); } \ - inline _Tpvec v512_load_low(const _Tp* ptr) \ - { \ - __m256i v256 = _mm256_loadu_si256((const __m256i*)ptr); \ - return _Tpvec(_mm512_castsi256_si512(v256)); \ - } \ - inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m256i vlo = _mm256_loadu_si256((const __m256i*)ptr0); \ - __m256i vhi = _mm256_loadu_si256((const __m256i*)ptr1); \ - return _Tpvec(_v512_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm512_storeu_si512((__m512i*)ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm512_store_si512((__m512i*)ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm512_stream_si512((__m512i*)ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm512_storeu_si512((__m512i*)ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm512_stream_si512((__m512i*)ptr, a.val); \ - else \ - _mm512_store_si512((__m512i*)ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint8x64, uchar) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int8x64, schar) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint16x32, ushort) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int16x32, short) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint32x16, unsigned) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int32x16, int) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint64x8, uint64) -OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int64x8, int64) - -#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ - inline _Tpvec v512_load(const _Tp* ptr) \ - { return _Tpvec(_mm512_loadu_##suffix(ptr)); } \ - inline _Tpvec v512_load_aligned(const _Tp* ptr) \ - { return _Tpvec(_mm512_load_##suffix(ptr)); } \ - inline _Tpvec v512_load_low(const _Tp* ptr) \ - { \ - return _Tpvec(_mm512_cast##suffix##256_##suffix##512 \ - (_mm256_loadu_##suffix(ptr))); \ - } \ - inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - halfreg vlo = _mm256_loadu_##suffix(ptr0); \ - halfreg vhi = _mm256_loadu_##suffix(ptr1); \ - return _Tpvec(_v512_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { _mm512_storeu_##suffix(ptr, a.val); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { _mm512_store_##suffix(ptr, a.val); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { _mm512_stream_##suffix(ptr, a.val); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm512_storeu_##suffix(ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm512_stream_##suffix(ptr, a.val); \ - else \ - _mm512_store_##suffix(ptr, a.val); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_##suffix(ptr, _v512_extract_low(a.val)); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { _mm256_storeu_##suffix(ptr, _v512_extract_high(a.val)); } - -OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float32x16, float, ps, __m256) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float64x8, double, pd, __m256d) - -#define OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_AVX512_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v512_setzero_##suffix() \ - { return _Tpvec(_mm512_setzero_si512()); } \ - inline _Tpvec v512_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm512_set1_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v512_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v512_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float32x16, suffix, _mm512_castps_si512) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float64x8, suffix, _mm512_castpd_si512) - -OPENCV_HAL_IMPL_AVX512_INIT(v_uint8x64, uchar, u8, epi8, char) -OPENCV_HAL_IMPL_AVX512_INIT(v_int8x64, schar, s8, epi8, char) -OPENCV_HAL_IMPL_AVX512_INIT(v_uint16x32, ushort, u16, epi16, short) -OPENCV_HAL_IMPL_AVX512_INIT(v_int16x32, short, s16, epi16, short) -OPENCV_HAL_IMPL_AVX512_INIT(v_uint32x16, unsigned, u32, epi32, int) -OPENCV_HAL_IMPL_AVX512_INIT(v_int32x16, int, s32, epi32, int) -OPENCV_HAL_IMPL_AVX512_INIT(v_uint64x8, uint64, u64, epi64, int64) -OPENCV_HAL_IMPL_AVX512_INIT(v_int64x8, int64, s64, epi64, int64) - -#define OPENCV_HAL_IMPL_AVX512_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v512_setzero_##suffix() \ - { return _Tpvec(_mm512_setzero_##zsuffix()); } \ - inline _Tpvec v512_setall_##suffix(_Tp v) \ - { return _Tpvec(_mm512_set1_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v512_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v512_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, cast) \ - OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, cast) - -OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float32x16, float, f32, ps, _mm512_castsi512_ps) -OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float64x8, double, f64, pd, _mm512_castsi512_pd) - -inline v_float32x16 v_reinterpret_as_f32(const v_float32x16& a) -{ return a; } -inline v_float32x16 v_reinterpret_as_f32(const v_float64x8& a) -{ return v_float32x16(_mm512_castpd_ps(a.val)); } - -inline v_float64x8 v_reinterpret_as_f64(const v_float64x8& a) -{ return a; } -inline v_float64x8 v_reinterpret_as_f64(const v_float32x16& a) -{ return v_float64x8(_mm512_castps_pd(a.val)); } - -// FP16 -inline v_float32x16 v512_load_expand(const hfloat* ptr) -{ - return v_float32x16(_mm512_cvtph_ps(_mm256_loadu_si256((const __m256i*)ptr))); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x16& a) -{ - __m256i ah = _mm512_cvtps_ph(a.val, 0); - _mm256_storeu_si256((__m256i*)ptr, ah); -} - -/* Recombine & ZIP */ -inline void v_zip(const v_int8x64& a, const v_int8x64& b, v_int8x64& ab0, v_int8x64& ab1) -{ -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8( 95, 31, 94, 30, 93, 29, 92, 28, 91, 27, 90, 26, 89, 25, 88, 24, - 87, 23, 86, 22, 85, 21, 84, 20, 83, 19, 82, 18, 81, 17, 80, 16, - 79, 15, 78, 14, 77, 13, 76, 12, 75, 11, 74, 10, 73, 9, 72, 8, - 71, 7, 70, 6, 69, 5, 68, 4, 67, 3, 66, 2, 65, 1, 64, 0); - ab0 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu8(127, 63, 126, 62, 125, 61, 124, 60, 123, 59, 122, 58, 121, 57, 120, 56, - 119, 55, 118, 54, 117, 53, 116, 52, 115, 51, 114, 50, 113, 49, 112, 48, - 111, 47, 110, 46, 109, 45, 108, 44, 107, 43, 106, 42, 105, 41, 104, 40, - 103, 39, 102, 38, 101, 37, 100, 36, 99, 35, 98, 34, 97, 33, 96, 32); - ab1 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask1, b.val)); -#else - __m512i low = _mm512_unpacklo_epi8(a.val, b.val); - __m512i high = _mm512_unpackhi_epi8(a.val, b.val); - ab0 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(11, 10, 3, 2, 9, 8, 1, 0), high)); - ab1 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(15, 14, 7, 6, 13, 12, 5, 4), high)); -#endif -} -inline void v_zip(const v_int16x32& a, const v_int16x32& b, v_int16x32& ab0, v_int16x32& ab1) -{ - __m512i mask0 = _v512_set_epu16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10, 41, 9, 40, 8, - 39, 7, 38, 6, 37, 5, 36, 4, 35, 3, 34, 2, 33, 1, 32, 0); - ab0 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26, 57, 25, 56, 24, - 55, 23, 54, 22, 53, 21, 52, 20, 51, 19, 50, 18, 49, 17, 48, 16); - ab1 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask1, b.val)); -} -inline void v_zip(const v_int32x16& a, const v_int32x16& b, v_int32x16& ab0, v_int32x16& ab1) -{ - __m512i mask0 = _v512_set_epu32(23, 7, 22, 6, 21, 5, 20, 4, 19, 3, 18, 2, 17, 1, 16, 0); - ab0 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu32(31, 15, 30, 14, 29, 13, 28, 12, 27, 11, 26, 10, 25, 9, 24, 8); - ab1 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask1, b.val)); -} -inline void v_zip(const v_int64x8& a, const v_int64x8& b, v_int64x8& ab0, v_int64x8& ab1) -{ - __m512i mask0 = _v512_set_epu64(11, 3, 10, 2, 9, 1, 8, 0); - ab0 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask0, b.val)); - __m512i mask1 = _v512_set_epu64(15, 7, 14, 6, 13, 5, 12, 4); - ab1 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask1, b.val)); -} - -inline void v_zip(const v_uint8x64& a, const v_uint8x64& b, v_uint8x64& ab0, v_uint8x64& ab1) -{ - v_int8x64 i0, i1; - v_zip(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b), i0, i1); - ab0 = v_reinterpret_as_u8(i0); - ab1 = v_reinterpret_as_u8(i1); -} -inline void v_zip(const v_uint16x32& a, const v_uint16x32& b, v_uint16x32& ab0, v_uint16x32& ab1) -{ - v_int16x32 i0, i1; - v_zip(v_reinterpret_as_s16(a), v_reinterpret_as_s16(b), i0, i1); - ab0 = v_reinterpret_as_u16(i0); - ab1 = v_reinterpret_as_u16(i1); -} -inline void v_zip(const v_uint32x16& a, const v_uint32x16& b, v_uint32x16& ab0, v_uint32x16& ab1) -{ - v_int32x16 i0, i1; - v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); - ab0 = v_reinterpret_as_u32(i0); - ab1 = v_reinterpret_as_u32(i1); -} -inline void v_zip(const v_uint64x8& a, const v_uint64x8& b, v_uint64x8& ab0, v_uint64x8& ab1) -{ - v_int64x8 i0, i1; - v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); - ab0 = v_reinterpret_as_u64(i0); - ab1 = v_reinterpret_as_u64(i1); -} -inline void v_zip(const v_float32x16& a, const v_float32x16& b, v_float32x16& ab0, v_float32x16& ab1) -{ - v_int32x16 i0, i1; - v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); - ab0 = v_reinterpret_as_f32(i0); - ab1 = v_reinterpret_as_f32(i1); -} -inline void v_zip(const v_float64x8& a, const v_float64x8& b, v_float64x8& ab0, v_float64x8& ab1) -{ - v_int64x8 i0, i1; - v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); - ab0 = v_reinterpret_as_f64(i0); - ab1 = v_reinterpret_as_f64(i1); -} - -#define OPENCV_HAL_IMPL_AVX512_COMBINE(_Tpvec, suffix) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_v512_combine(_v512_extract_low(a.val), _v512_extract_low(b.val))); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_v512_insert(b.val, _v512_extract_high(a.val))); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - c.val = _v512_combine(_v512_extract_low(a.val),_v512_extract_low(b.val)); \ - d.val = _v512_insert(b.val,_v512_extract_high(a.val)); \ - } - - -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint8x64, epi8) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int8x64, epi8) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint16x32, epi16) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int16x32, epi16) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint32x16, epi32) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int32x16, epi32) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint64x8, epi64) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_int64x8, epi64) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_COMBINE(v_float64x8, pd) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/* Element-wise binary and unary operations */ - -/** Non-saturating arithmetics **/ -#define OPENCV_HAL_IMPL_AVX512_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint8x64, _mm512_add_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int8x64, _mm512_add_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint16x32, _mm512_add_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int16x32, _mm512_add_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint8x64, _mm512_sub_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int8x64, _mm512_sub_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint16x32, _mm512_sub_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int16x32, _mm512_sub_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_uint16x32, _mm512_mullo_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_int16x32, _mm512_mullo_epi16) - -inline v_uint8x64 v_mul_wrap(const v_uint8x64& a, const v_uint8x64& b) -{ - __m512i ad = _mm512_srai_epi16(a.val, 8); - __m512i bd = _mm512_srai_epi16(b.val, 8); - __m512i p0 = _mm512_mullo_epi16(a.val, b.val); // even - __m512i p1 = _mm512_slli_epi16(_mm512_mullo_epi16(ad, bd), 8); // odd - return v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, p0, p1)); -} -inline v_int8x64 v_mul_wrap(const v_int8x64& a, const v_int8x64& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -#define OPENCV_HAL_IMPL_AVX512_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint32x16, _mm512_add_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint32x16, _mm512_sub_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int32x16, _mm512_add_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int32x16, _mm512_sub_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint64x8, _mm512_add_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint64x8, _mm512_sub_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int64x8, _mm512_add_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int64x8, _mm512_sub_epi64) - -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint32x16, _mm512_mullo_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int32x16, _mm512_mullo_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint64x8, _mm512_mullo_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int64x8, _mm512_mullo_epi64) - -/** Saturating arithmetics **/ -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint8x64, _mm512_adds_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint8x64, _mm512_subs_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int8x64, _mm512_adds_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int8x64, _mm512_subs_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint16x32, _mm512_adds_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint16x32, _mm512_subs_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int16x32, _mm512_adds_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int16x32, _mm512_subs_epi16) - -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float32x16, _mm512_add_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float32x16, _mm512_sub_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float32x16, _mm512_mul_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float32x16, _mm512_div_ps) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float64x8, _mm512_add_pd) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float64x8, _mm512_sub_pd) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float64x8, _mm512_mul_pd) -OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float64x8, _mm512_div_pd) - -// saturating multiply -inline v_uint8x64 v_mul(const v_uint8x64& a, const v_uint8x64& b) -{ - v_uint16x32 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x64 v_mul(const v_int8x64& a, const v_int8x64& b) -{ - v_int16x32 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x32 v_mul(const v_uint16x32& a, const v_uint16x32& b) -{ - __m512i pl = _mm512_mullo_epi16(a.val, b.val); - __m512i ph = _mm512_mulhi_epu16(a.val, b.val); - __m512i p0 = _mm512_unpacklo_epi16(pl, ph); - __m512i p1 = _mm512_unpackhi_epi16(pl, ph); - - const __m512i m = _mm512_set1_epi32(65535); - return v_uint16x32(_mm512_packus_epi32(_mm512_min_epu32(p0, m), _mm512_min_epu32(p1, m))); -} -inline v_int16x32 v_mul(const v_int16x32& a, const v_int16x32& b) -{ - __m512i pl = _mm512_mullo_epi16(a.val, b.val); - __m512i ph = _mm512_mulhi_epi16(a.val, b.val); - __m512i p0 = _mm512_unpacklo_epi16(pl, ph); - __m512i p1 = _mm512_unpackhi_epi16(pl, ph); - return v_int16x32(_mm512_packs_epi32(p0, p1)); -} - -inline v_int16x32 v_mul_hi(const v_int16x32& a, const v_int16x32& b) { return v_int16x32(_mm512_mulhi_epi16(a.val, b.val)); } -inline v_uint16x32 v_mul_hi(const v_uint16x32& a, const v_uint16x32& b) { return v_uint16x32(_mm512_mulhi_epu16(a.val, b.val)); } - -// Multiply and expand -inline void v_mul_expand(const v_uint8x64& a, const v_uint8x64& b, - v_uint16x32& c, v_uint16x32& d) -{ - v_uint16x32 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x64& a, const v_int8x64& b, - v_int16x32& c, v_int16x32& d) -{ - v_int16x32 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x32& a, const v_int16x32& b, - v_int32x16& c, v_int32x16& d) -{ - v_int16x32 v0, v1; - v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); - - c = v_reinterpret_as_s32(v0); - d = v_reinterpret_as_s32(v1); -} - -inline void v_mul_expand(const v_uint16x32& a, const v_uint16x32& b, - v_uint32x16& c, v_uint32x16& d) -{ - v_uint16x32 v0, v1; - v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); - - c = v_reinterpret_as_u32(v0); - d = v_reinterpret_as_u32(v1); -} - -inline void v_mul_expand(const v_uint32x16& a, const v_uint32x16& b, - v_uint64x8& c, v_uint64x8& d) -{ - v_zip(v_uint64x8(_mm512_mul_epu32(a.val, b.val)), - v_uint64x8(_mm512_mul_epu32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); -} - -inline void v_mul_expand(const v_int32x16& a, const v_int32x16& b, - v_int64x8& c, v_int64x8& d) -{ - v_zip(v_int64x8(_mm512_mul_epi32(a.val, b.val)), - v_int64x8(_mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); -} - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_AVX512_SHIFT_OP(_Tpuvec, _Tpsvec, suffix) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } - -OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint16x32, v_int16x32, epi16) -OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint32x16, v_int32x16, epi32) -OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint64x8, v_int64x8, epi64) - - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_AVX512_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_AVX512_BIN_OP(v_and, _Tpvec, _mm512_and_##suffix) \ - OPENCV_HAL_IMPL_AVX512_BIN_OP(v_or, _Tpvec, _mm512_or_##suffix) \ - OPENCV_HAL_IMPL_AVX512_BIN_OP(v_xor, _Tpvec, _mm512_xor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(_mm512_xor_##suffix(a.val, not_const)); } - -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint8x64, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int8x64, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint16x32, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int16x32, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint32x16, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int32x16, si512, _mm512_set1_epi32(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint64x8, si512, _mm512_set1_epi64(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int64x8, si512, _mm512_set1_epi64(-1)) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float32x16, ps, _mm512_castsi512_ps(_mm512_set1_epi32(-1))) -OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float64x8, pd, _mm512_castsi512_pd(_mm512_set1_epi32(-1))) - -/** Select **/ -#define OPENCV_HAL_IMPL_AVX512_SELECT(_Tpvec, suffix, zsuf) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm512_mask_blend_##suffix(_mm512_cmp_##suffix##_mask(mask.val, _mm512_setzero_##zsuf(), _MM_CMPINT_EQ), a.val, b.val)); } - -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint8x64, epi8, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int8x64, epi8, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint16x32, epi16, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int16x32, epi16, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint32x16, epi32, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int32x16, epi32, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_uint64x8, epi64, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_int64x8, epi64, si512) -OPENCV_HAL_IMPL_AVX512_SELECT(v_float32x16, ps, ps) -OPENCV_HAL_IMPL_AVX512_SELECT(v_float64x8, pd, pd) - -/** Comparison **/ -#define OPENCV_HAL_IMPL_AVX512_CMP_INT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval)); } - -#define OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(_Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_eq, _MM_CMPINT_EQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ne, _MM_CMPINT_NE, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_lt, _MM_CMPINT_LT, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_gt, _MM_CMPINT_NLE, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_le, _MM_CMPINT_LE, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ge, _MM_CMPINT_NLT, _Tpvec, sufcmp, sufset, tval) - -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint8x64, epu8, epi8, (char)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int8x64, epi8, epi8, (char)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint16x32, epu16, epi16, (short)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int16x32, epi16, epi16, (short)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint32x16, epu32, epi32, (int)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int32x16, epi32, epi32, (int)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint64x8, epu64, epi64, (int64)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int64x8, epi64, epi64, (int64)-1) - -#define OPENCV_HAL_IMPL_AVX512_CMP_FLT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(_mm512_castsi512_##sufcmp(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval))); } - -#define OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(_Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, sufcmp, sufset, tval) \ - OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, sufcmp, sufset, tval) - -OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float32x16, ps, epi32, (int)-1) -OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float64x8, pd, epi64, (int64)-1) - -inline v_float32x16 v_not_nan(const v_float32x16& a) -{ return v_float32x16(_mm512_castsi512_ps(_mm512_maskz_set1_epi32(_mm512_cmp_ps_mask(a.val, a.val, _CMP_ORD_Q), (int)-1))); } -inline v_float64x8 v_not_nan(const v_float64x8& a) -{ return v_float64x8(_mm512_castsi512_pd(_mm512_maskz_set1_epi64(_mm512_cmp_pd_mask(a.val, a.val, _CMP_ORD_Q), (int64)-1))); } - -/** min/max **/ -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint8x64, _mm512_min_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint8x64, _mm512_max_epu8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int8x64, _mm512_min_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int8x64, _mm512_max_epi8) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint16x32, _mm512_min_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint16x32, _mm512_max_epu16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int16x32, _mm512_min_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int16x32, _mm512_max_epi16) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint32x16, _mm512_min_epu32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint32x16, _mm512_max_epu32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int32x16, _mm512_min_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int32x16, _mm512_max_epi32) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint64x8, _mm512_min_epu64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint64x8, _mm512_max_epu64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int64x8, _mm512_min_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int64x8, _mm512_max_epi64) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float32x16, _mm512_min_ps) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float32x16, _mm512_max_ps) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float64x8, _mm512_min_pd) -OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float64x8, _mm512_max_pd) - -/** Rotate **/ -namespace { - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) - { - return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 ), imm4 *8), - _mm512_slli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 + 1), (4-imm4)*8))); - }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) - { - return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, 15), imm4 *8), - _mm512_slli_epi32( b.val, (4-imm4)*8))); - }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) - { - return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16), imm4 *8), - _mm512_slli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 15), (4-imm4)*8))); - }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) - { return v_int8x64(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, 15), imm4*8)); }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) - { return v_int8x64(_mm512_alignr_epi32(b.val, a.val, imm32)); }}; - template<> - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64&) { return a; }}; - template - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) - { return v_int8x64(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16)); }}; - template<> - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) { return b; }}; - template<> - struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; -} -template inline v_int8x64 v_rotate_right(const v_int8x64& a, const v_int8x64& b) -{ - return imm >= 128 ? v_int8x64() : -#if CV_AVX_512VBMI - v_int8x64(_mm512_permutex2var_epi8(a.val, - _v512_set_epu8(0x3f + imm, 0x3e + imm, 0x3d + imm, 0x3c + imm, 0x3b + imm, 0x3a + imm, 0x39 + imm, 0x38 + imm, - 0x37 + imm, 0x36 + imm, 0x35 + imm, 0x34 + imm, 0x33 + imm, 0x32 + imm, 0x31 + imm, 0x30 + imm, - 0x2f + imm, 0x2e + imm, 0x2d + imm, 0x2c + imm, 0x2b + imm, 0x2a + imm, 0x29 + imm, 0x28 + imm, - 0x27 + imm, 0x26 + imm, 0x25 + imm, 0x24 + imm, 0x23 + imm, 0x22 + imm, 0x21 + imm, 0x20 + imm, - 0x1f + imm, 0x1e + imm, 0x1d + imm, 0x1c + imm, 0x1b + imm, 0x1a + imm, 0x19 + imm, 0x18 + imm, - 0x17 + imm, 0x16 + imm, 0x15 + imm, 0x14 + imm, 0x13 + imm, 0x12 + imm, 0x11 + imm, 0x10 + imm, - 0x0f + imm, 0x0e + imm, 0x0d + imm, 0x0c + imm, 0x0b + imm, 0x0a + imm, 0x09 + imm, 0x08 + imm, - 0x07 + imm, 0x06 + imm, 0x05 + imm, 0x04 + imm, 0x03 + imm, 0x02 + imm, 0x01 + imm, 0x00 + imm), b.val)); -#else - _v_rotate_right 15), imm/4>::eval(a, b); -#endif -} -template -inline v_int8x64 v_rotate_left(const v_int8x64& a, const v_int8x64& b) -{ - if (imm == 0) return a; - if (imm == 64) return b; - if (imm >= 128) return v_int8x64(); -#if CV_AVX_512VBMI - return v_int8x64(_mm512_permutex2var_epi8(b.val, - _v512_set_epi8(0x7f - imm,0x7e - imm,0x7d - imm,0x7c - imm,0x7b - imm,0x7a - imm,0x79 - imm,0x78 - imm, - 0x77 - imm,0x76 - imm,0x75 - imm,0x74 - imm,0x73 - imm,0x72 - imm,0x71 - imm,0x70 - imm, - 0x6f - imm,0x6e - imm,0x6d - imm,0x6c - imm,0x6b - imm,0x6a - imm,0x69 - imm,0x68 - imm, - 0x67 - imm,0x66 - imm,0x65 - imm,0x64 - imm,0x63 - imm,0x62 - imm,0x61 - imm,0x60 - imm, - 0x5f - imm,0x5e - imm,0x5d - imm,0x5c - imm,0x5b - imm,0x5a - imm,0x59 - imm,0x58 - imm, - 0x57 - imm,0x56 - imm,0x55 - imm,0x54 - imm,0x53 - imm,0x52 - imm,0x51 - imm,0x50 - imm, - 0x4f - imm,0x4e - imm,0x4d - imm,0x4c - imm,0x4b - imm,0x4a - imm,0x49 - imm,0x48 - imm, - 0x47 - imm,0x46 - imm,0x45 - imm,0x44 - imm,0x43 - imm,0x42 - imm,0x41 - imm,0x40 - imm), a.val)); -#else - return imm < 64 ? v_rotate_right<64 - imm>(b, a) : v_rotate_right<128 - imm>(v512_setzero_s8(), b); -#endif -} -template -inline v_int8x64 v_rotate_right(const v_int8x64& a) -{ - if (imm == 0) return a; - if (imm >= 64) return v_int8x64(); -#if CV_AVX_512VBMI - return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF >> imm, - _v512_set_epu8(0x3f + imm,0x3e + imm,0x3d + imm,0x3c + imm,0x3b + imm,0x3a + imm,0x39 + imm,0x38 + imm, - 0x37 + imm,0x36 + imm,0x35 + imm,0x34 + imm,0x33 + imm,0x32 + imm,0x31 + imm,0x30 + imm, - 0x2f + imm,0x2e + imm,0x2d + imm,0x2c + imm,0x2b + imm,0x2a + imm,0x29 + imm,0x28 + imm, - 0x27 + imm,0x26 + imm,0x25 + imm,0x24 + imm,0x23 + imm,0x22 + imm,0x21 + imm,0x20 + imm, - 0x1f + imm,0x1e + imm,0x1d + imm,0x1c + imm,0x1b + imm,0x1a + imm,0x19 + imm,0x18 + imm, - 0x17 + imm,0x16 + imm,0x15 + imm,0x14 + imm,0x13 + imm,0x12 + imm,0x11 + imm,0x10 + imm, - 0x0f + imm,0x0e + imm,0x0d + imm,0x0c + imm,0x0b + imm,0x0a + imm,0x09 + imm,0x08 + imm, - 0x07 + imm,0x06 + imm,0x05 + imm,0x04 + imm,0x03 + imm,0x02 + imm,0x01 + imm,0x00 + imm), a.val)); -#else - return v_rotate_right(a, v512_setzero_s8()); -#endif -} -template -inline v_int8x64 v_rotate_left(const v_int8x64& a) -{ - if (imm == 0) return a; - if (imm >= 64) return v_int8x64(); -#if CV_AVX_512VBMI - return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF << imm, - _v512_set_epi8(0x3f - imm,0x3e - imm,0x3d - imm,0x3c - imm,0x3b - imm,0x3a - imm,0x39 - imm,0x38 - imm, - 0x37 - imm,0x36 - imm,0x35 - imm,0x34 - imm,0x33 - imm,0x32 - imm,0x31 - imm,0x30 - imm, - 0x2f - imm,0x2e - imm,0x2d - imm,0x2c - imm,0x2b - imm,0x2a - imm,0x29 - imm,0x28 - imm, - 0x27 - imm,0x26 - imm,0x25 - imm,0x24 - imm,0x23 - imm,0x22 - imm,0x21 - imm,0x20 - imm, - 0x1f - imm,0x1e - imm,0x1d - imm,0x1c - imm,0x1b - imm,0x1a - imm,0x19 - imm,0x18 - imm, - 0x17 - imm,0x16 - imm,0x15 - imm,0x14 - imm,0x13 - imm,0x12 - imm,0x11 - imm,0x10 - imm, - 0x0f - imm,0x0e - imm,0x0d - imm,0x0c - imm,0x0b - imm,0x0a - imm,0x09 - imm,0x08 - imm, - 0x07 - imm,0x06 - imm,0x05 - imm,0x04 - imm,0x03 - imm,0x02 - imm,0x01 - imm,0x00 - imm), a.val)); -#else - return v_rotate_right<64 - imm>(v512_setzero_s8(), a); -#endif -} - -#define OPENCV_HAL_IMPL_AVX512_ROTATE_PM(_Tpvec, suffix) \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a))); } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a))); } - -#define OPENCV_HAL_IMPL_AVX512_ROTATE_EC(_Tpvec, suffix) \ -template \ -inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ - enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ - if (imm == 0) return a; \ - if (imm == _Tpvec::nlanes) return b; \ - if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << SHIFT2)&MASK, b.val), (MASK << (imm))&MASK, a.val)); \ -} \ -template \ -inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ - enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ - if (imm == 0) return a; \ - if (imm == _Tpvec::nlanes) return b; \ - if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << (imm))&MASK, a.val), (MASK << SHIFT2)&MASK, b.val)); \ -} \ -template \ -inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - if (imm == 0) return a; \ - if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_maskz_expand_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ -} \ -template \ -inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - if (imm == 0) return a; \ - if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ - return _Tpvec(_mm512_maskz_compress_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ -} - -OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint8x64, u8) -OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint16x32, u16) -OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_int16x32, s16) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint32x16, epi32) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int32x16, epi32) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint64x8, epi64) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int64x8, epi64) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float64x8, pd) - -/** Reverse **/ -inline v_uint8x64 v_reverse(const v_uint8x64 &a) -{ -#if CV_AVX_512VBMI - static const __m512i perm = _mm512_set_epi32( - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f, - 0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f, - 0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f); - return v_uint8x64(_mm512_permutexvar_epi8(perm, a.val)); -#else - static const __m512i shuf = _mm512_set_epi32( - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, - 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f); - static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); - __m512i vec = _mm512_shuffle_epi8(a.val, shuf); - return v_uint8x64(_mm512_permutexvar_epi64(perm, vec)); -#endif -} - -inline v_int8x64 v_reverse(const v_int8x64 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x32 v_reverse(const v_uint16x32 &a) -{ -#if CV_AVX_512VBMI - static const __m512i perm = _mm512_set_epi32( - 0x00000001, 0x00020003, 0x00040005, 0x00060007, - 0x00080009, 0x000a000b, 0x000c000d, 0x000e000f, - 0x00100011, 0x00120013, 0x00140015, 0x00160017, - 0x00180019, 0x001a001b, 0x001c001d, 0x001e001f); - return v_uint16x32(_mm512_permutexvar_epi16(perm, a.val)); -#else - static const __m512i shuf = _mm512_set_epi32( - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, - 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e); - static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); - __m512i vec = _mm512_shuffle_epi8(a.val, shuf); - return v_uint16x32(_mm512_permutexvar_epi64(perm, vec)); -#endif -} - -inline v_int16x32 v_reverse(const v_int16x32 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x16 v_reverse(const v_uint32x16 &a) -{ - static const __m512i perm = _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14, 15); - return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); -} - -inline v_int32x16 v_reverse(const v_int32x16 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x16 v_reverse(const v_float32x16 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x8 v_reverse(const v_uint64x8 &a) -{ - static const __m512i perm = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); - return v_uint64x8(_mm512_permutexvar_epi64(perm, a.val)); -} - -inline v_int64x8 v_reverse(const v_int64x8 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x8 v_reverse(const v_float64x8 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////// Reduce ///////// - -/** Reduce **/ -#define OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64(a, b) a + b -#define OPENCV_HAL_IMPL_AVX512_REDUCE_8(sctype, func, _Tpvec, ifunc, scop) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - sctype CV_DECL_ALIGNED(64) idx[2]; \ - _mm_store_si128((__m128i*)idx, _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1))); \ - return scop(idx[0], idx[1]); } -OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, min, v_uint64x8, min_epu64, min) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, max, v_uint64x8, max_epu64, max) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, sum, v_uint64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, min, v_int64x8, min_epi64, min) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, max, v_int64x8, max_epi64, max) -OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, sum, v_int64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_8F(func, ifunc, scop) \ - inline double v_reduce_##func(const v_float64x8& a) \ - { __m256d half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - double CV_DECL_ALIGNED(64) idx[2]; \ - _mm_store_pd(idx, _mm_##ifunc(_mm256_castpd256_pd128(half), _mm256_extractf128_pd(half, 1))); \ - return scop(idx[0], idx[1]); } -OPENCV_HAL_IMPL_AVX512_REDUCE_8F(min, min_pd, min) -OPENCV_HAL_IMPL_AVX512_REDUCE_8F(max, max_pd, max) -OPENCV_HAL_IMPL_AVX512_REDUCE_8F(sum, add_pd, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_16(sctype, func, _Tpvec, ifunc) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ - return (sctype)_mm_cvtsi128_si32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, min, v_uint32x16, min_epu32) -OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, max, v_uint32x16, max_epu32) -OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, min, v_int32x16, min_epi32) -OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, max, v_int32x16, max_epi32) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_16F(func, ifunc) \ - inline float v_reduce_##func(const v_float32x16& a) \ - { __m256 half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128 quarter = _mm_##ifunc(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 3, 2))); \ - quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 0, 1))); \ - return _mm_cvtss_f32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_16F(min, min_ps) -OPENCV_HAL_IMPL_AVX512_REDUCE_16F(max, max_ps) - -inline float v_reduce_sum(const v_float32x16& a) -{ - __m256 half = _mm256_add_ps(_v512_extract_low(a.val), _v512_extract_high(a.val)); - __m128 quarter = _mm_add_ps(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); - quarter = _mm_hadd_ps(quarter, quarter); - return _mm_cvtss_f32(_mm_hadd_ps(quarter, quarter)); -} -inline int v_reduce_sum(const v_int32x16& a) -{ - __m256i half = _mm256_add_epi32(_v512_extract_low(a.val), _v512_extract_high(a.val)); - __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); - quarter = _mm_hadd_epi32(quarter, quarter); - return _mm_cvtsi128_si32(_mm_hadd_epi32(quarter, quarter)); -} -inline uint v_reduce_sum(const v_uint32x16& a) -{ return (uint)v_reduce_sum(v_reinterpret_as_s32(a)); } - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_32(sctype, func, _Tpvec, ifunc) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ - return (sctype)_mm_cvtsi128_si32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, min, v_uint16x32, min_epu16) -OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, max, v_uint16x32, max_epu16) -OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, min, v_int16x32, min_epi16) -OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, max, v_int16x32, max_epi16) - -inline int v_reduce_sum(const v_int16x32& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline uint v_reduce_sum(const v_uint16x32& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_64(sctype, func, _Tpvec, ifunc) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ - __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ - quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 1)); \ - return (sctype)_mm_cvtsi128_si32(quarter); } -OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, min, v_uint8x64, min_epu8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, max, v_uint8x64, max_epu8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, min, v_int8x64, min_epi8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, max, v_int8x64, max_epi8) - -#define OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(sctype, _Tpvec, suffix) \ - inline sctype v_reduce_sum(const _Tpvec& a) \ - { __m512i a16 = _mm512_add_epi16(_mm512_cvt##suffix##_epi16(_v512_extract_low(a.val)), \ - _mm512_cvt##suffix##_epi16(_v512_extract_high(a.val))); \ - a16 = _mm512_cvtepi16_epi32(_mm256_add_epi16(_v512_extract_low(a16), _v512_extract_high(a16))); \ - __m256i a8 = _mm256_add_epi32(_v512_extract_low(a16), _v512_extract_high(a16)); \ - __m128i a4 = _mm_add_epi32(_mm256_castsi256_si128(a8), _mm256_extracti128_si256(a8, 1)); \ - a4 = _mm_hadd_epi32(a4, a4); \ - return (sctype)_mm_cvtsi128_si32(_mm_hadd_epi32(a4, a4)); } -OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(uint, v_uint8x64, epu8) -OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(int, v_int8x64, epi8) - -inline v_float32x16 v_reduce_sum4(const v_float32x16& a, const v_float32x16& b, - const v_float32x16& c, const v_float32x16& d) -{ - __m256 abl = _mm256_hadd_ps(_v512_extract_low(a.val), _v512_extract_low(b.val)); - __m256 abh = _mm256_hadd_ps(_v512_extract_high(a.val), _v512_extract_high(b.val)); - __m256 cdl = _mm256_hadd_ps(_v512_extract_low(c.val), _v512_extract_low(d.val)); - __m256 cdh = _mm256_hadd_ps(_v512_extract_high(c.val), _v512_extract_high(d.val)); - return v_float32x16(_v512_combine(_mm256_hadd_ps(abl, cdl), _mm256_hadd_ps(abh, cdh))); -} - -inline unsigned v_reduce_sad(const v_uint8x64& a, const v_uint8x64& b) -{ - __m512i val = _mm512_sad_epu8(a.val, b.val); - __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); - __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_int8x64& a, const v_int8x64& b) -{ - __m512i val = _mm512_set1_epi8(-128); - val = _mm512_sad_epu8(_mm512_add_epi8(a.val, val), _mm512_add_epi8(b.val, val)); - __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); - __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); -} -inline unsigned v_reduce_sad(const v_uint16x32& a, const v_uint16x32& b) -{ return v_reduce_sum(v_add_wrap(v_sub(a, b), v_sub(b, a))); } -inline unsigned v_reduce_sad(const v_int16x32& a, const v_int16x32& b) -{ return v_reduce_sum(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b)))); } -inline unsigned v_reduce_sad(const v_uint32x16& a, const v_uint32x16& b) -{ return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); } -inline unsigned v_reduce_sad(const v_int32x16& a, const v_int32x16& b) -{ return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b)))); } -inline float v_reduce_sad(const v_float32x16& a, const v_float32x16& b) -{ return v_reduce_sum(v_and(v_sub(a, b), v_float32x16(_mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff))))); } -inline double v_reduce_sad(const v_float64x8& a, const v_float64x8& b) -{ return v_reduce_sum(v_and(v_sub(a, b), v_float64x8(_mm512_castsi512_pd(_mm512_set1_epi64(0x7fffffffffffffff))))); } - -/** Popcount **/ -inline v_uint8x64 v_popcount(const v_int8x64& a) -{ -#if CV_AVX_512BITALG - return v_uint8x64(_mm512_popcnt_epi8(a.val)); -#elif CV_AVX_512VBMI - __m512i _popcnt_table0 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, - 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0); - __m512i _popcnt_table1 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, - 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1); - return v_uint8x64(_mm512_sub_epi8(_mm512_permutex2var_epi8(_popcnt_table0, a.val, _popcnt_table1), _mm512_movm_epi8(_mm512_movepi8_mask(a.val)))); -#else - __m512i _popcnt_table = _mm512_set4_epi32(0x04030302, 0x03020201, 0x03020201, 0x02010100); - __m512i _popcnt_mask = _mm512_set1_epi8(0x0F); - - return v_uint8x64(_mm512_add_epi8(_mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512( a.val, _popcnt_mask)), - _mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512(_mm512_srli_epi16(a.val, 4), _popcnt_mask)))); -#endif -} -inline v_uint16x32 v_popcount(const v_int16x32& a) -{ -#if CV_AVX_512BITALG - return v_uint16x32(_mm512_popcnt_epi16(a.val)); -#elif CV_AVX_512VPOPCNTDQ - __m512i zero = _mm512_setzero_si512(); - return v_uint16x32(_mm512_packs_epi32(_mm512_popcnt_epi32(_mm512_unpacklo_epi16(a.val, zero)), - _mm512_popcnt_epi32(_mm512_unpackhi_epi16(a.val, zero)))); -#else - v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v512_setall_u16(0x00ff)); -#endif -} -inline v_uint32x16 v_popcount(const v_int32x16& a) -{ -#if CV_AVX_512VPOPCNTDQ - return v_uint32x16(_mm512_popcnt_epi32(a.val)); -#else - v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v512_setall_u32(0x000000ff)); -#endif -} -inline v_uint64x8 v_popcount(const v_int64x8& a) -{ -#if CV_AVX_512VPOPCNTDQ - return v_uint64x8(_mm512_popcnt_epi64(a.val)); -#else - return v_uint64x8(_mm512_sad_epu8(v_popcount(v_reinterpret_as_s8(a)).val, _mm512_setzero_si512())); -#endif -} - - -inline v_uint8x64 v_popcount(const v_uint8x64& a) { return v_popcount(v_reinterpret_as_s8 (a)); } -inline v_uint16x32 v_popcount(const v_uint16x32& a) { return v_popcount(v_reinterpret_as_s16(a)); } -inline v_uint32x16 v_popcount(const v_uint32x16& a) { return v_popcount(v_reinterpret_as_s32(a)); } -inline v_uint64x8 v_popcount(const v_uint64x8& a) { return v_popcount(v_reinterpret_as_s64(a)); } - - -////////// Other math ///////// - -/** Some frequent operations **/ -#if CV_FMA3 -#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } -#else -#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } -#endif - -#define OPENCV_HAL_IMPL_AVX512_MISC(_Tpvec, suffix) \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(_mm512_sqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_AVX512_MULADD(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_MULADD(v_float64x8, pd) -OPENCV_HAL_IMPL_AVX512_MISC(v_float32x16, ps) -OPENCV_HAL_IMPL_AVX512_MISC(v_float64x8, pd) - -inline v_int32x16 v_fma(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) -{ return v_add(v_mul(a, b), c); } -inline v_int32x16 v_muladd(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) -{ return v_fma(a, b, c); } - -inline v_float32x16 v_invsqrt(const v_float32x16& x) -{ -#if CV_AVX_512ER - return v_float32x16(_mm512_rsqrt28_ps(x.val)); -#else - v_float32x16 half = v_mul(x, v512_setall_f32(0.5)); - v_float32x16 t = v_float32x16(_mm512_rsqrt14_ps(x.val)); - t = v_mul(t, v_sub(v512_setall_f32(1.5), v_mul(v_mul(t, t), half))); - return t; -#endif -} - -inline v_float64x8 v_invsqrt(const v_float64x8& x) -{ -#if CV_AVX_512ER - return v_float64x8(_mm512_rsqrt28_pd(x.val)); -#else - return v_div(v512_setall_f64(1.), v_sqrt(x)); -// v_float64x8 half = x * v512_setall_f64(0.5); -// v_float64x8 t = v_float64x8(_mm512_rsqrt14_pd(x.val)); -// t *= v512_setall_f64(1.5) - ((t * t) * half); -// t *= v512_setall_f64(1.5) - ((t * t) * half); -// return t; -#endif -} - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_AVX512_ABS(_Tpvec, _Tpuvec, suffix) \ - inline _Tpuvec v_abs(const _Tpvec& x) \ - { return _Tpuvec(_mm512_abs_##suffix(x.val)); } - -OPENCV_HAL_IMPL_AVX512_ABS(v_int8x64, v_uint8x64, epi8) -OPENCV_HAL_IMPL_AVX512_ABS(v_int16x32, v_uint16x32, epi16) -OPENCV_HAL_IMPL_AVX512_ABS(v_int32x16, v_uint32x16, epi32) -OPENCV_HAL_IMPL_AVX512_ABS(v_int64x8, v_uint64x8, epi64) - -inline v_float32x16 v_abs(const v_float32x16& x) -{ -#ifdef _mm512_abs_pd - return v_float32x16(_mm512_abs_ps(x.val)); -#else - return v_float32x16(_mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(x.val), - _v512_set_epu64(0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, - 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF)))); -#endif -} - -inline v_float64x8 v_abs(const v_float64x8& x) -{ -#ifdef _mm512_abs_pd - #if defined __GNUC__ && (__GNUC__ < 7 || (__GNUC__ == 7 && __GNUC_MINOR__ <= 3) || (__GNUC__ == 8 && __GNUC_MINOR__ <= 2)) - // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87476 - return v_float64x8(_mm512_abs_pd(_mm512_castpd_ps(x.val))); - #else - return v_float64x8(_mm512_abs_pd(x.val)); - #endif -#else - return v_float64x8(_mm512_castsi512_pd(_mm512_and_si512(_mm512_castpd_si512(x.val), - _v512_set_epu64(0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, - 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF)))); -#endif -} - -/** Absolute difference **/ -inline v_uint8x64 v_absdiff(const v_uint8x64& a, const v_uint8x64& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x32 v_absdiff(const v_uint16x32& a, const v_uint16x32& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x16 v_absdiff(const v_uint32x16& a, const v_uint32x16& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x64 v_absdiff(const v_int8x64& a, const v_int8x64& b) -{ - v_int8x64 d = v_sub_wrap(a, b); - v_int8x64 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} - -inline v_uint16x32 v_absdiff(const v_int16x32& a, const v_int16x32& b) -{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } - -inline v_uint32x16 v_absdiff(const v_int32x16& a, const v_int32x16& b) -{ - v_int32x16 d = v_sub(a, b); - v_int32x16 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -inline v_float32x16 v_absdiff(const v_float32x16& a, const v_float32x16& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x8 v_absdiff(const v_float64x8& a, const v_float64x8& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x64 v_absdiffs(const v_int8x64& a, const v_int8x64& b) -{ - v_int8x64 d = v_sub(a, b); - v_int8x64 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x32 v_absdiffs(const v_int16x32& a, const v_int16x32& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x16 v_round(const v_float32x16& a) -{ return v_int32x16(_mm512_cvtps_epi32(a.val)); } - -inline v_int32x16 v_round(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(a.val))); } - -inline v_int32x16 v_round(const v_float64x8& a, const v_float64x8& b) -{ return v_int32x16(_v512_combine(_mm512_cvtpd_epi32(a.val), _mm512_cvtpd_epi32(b.val))); } - -inline v_int32x16 v_trunc(const v_float32x16& a) -{ return v_int32x16(_mm512_cvttps_epi32(a.val)); } - -inline v_int32x16 v_trunc(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvttpd_epi32(a.val))); } - -#if CVT_ROUND_MODES_IMPLEMENTED -inline v_int32x16 v_floor(const v_float32x16& a) -{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)); } - -inline v_int32x16 v_floor(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC))); } - -inline v_int32x16 v_ceil(const v_float32x16& a) -{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)); } - -inline v_int32x16 v_ceil(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC))); } -#else -inline v_int32x16 v_floor(const v_float32x16& a) -{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 1))); } - -inline v_int32x16 v_floor(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 1)))); } - -inline v_int32x16 v_ceil(const v_float32x16& a) -{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 2))); } - -inline v_int32x16 v_ceil(const v_float64x8& a) -{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 2)))); } -#endif - -/** To float **/ -inline v_float32x16 v_cvt_f32(const v_int32x16& a) -{ return v_float32x16(_mm512_cvtepi32_ps(a.val)); } - -inline v_float32x16 v_cvt_f32(const v_float64x8& a) -{ return v_float32x16(_mm512_cvtpd_pslo(a.val)); } - -inline v_float32x16 v_cvt_f32(const v_float64x8& a, const v_float64x8& b) -{ return v_float32x16(_v512_combine(_mm512_cvtpd_ps(a.val), _mm512_cvtpd_ps(b.val))); } - -inline v_float64x8 v_cvt_f64(const v_int32x16& a) -{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_low(a.val))); } - -inline v_float64x8 v_cvt_f64_high(const v_int32x16& a) -{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_high(a.val))); } - -inline v_float64x8 v_cvt_f64(const v_float32x16& a) -{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_low(a.val))); } - -inline v_float64x8 v_cvt_f64_high(const v_float32x16& a) -{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_high(a.val))); } - -// from (Mysticial and wim) https://stackoverflow.com/q/41144668 -inline v_float64x8 v_cvt_f64(const v_int64x8& v) -{ -#if CV_AVX_512DQ - return v_float64x8(_mm512_cvtepi64_pd(v.val)); -#else - // constants encoded as floating-point - __m512i magic_i_lo = _mm512_set1_epi64(0x4330000000000000); // 2^52 - __m512i magic_i_hi32 = _mm512_set1_epi64(0x4530000080000000); // 2^84 + 2^63 - __m512i magic_i_all = _mm512_set1_epi64(0x4530000080100000); // 2^84 + 2^63 + 2^52 - __m512d magic_d_all = _mm512_castsi512_pd(magic_i_all); - - // Blend the 32 lowest significant bits of v with magic_int_lo - __m512i v_lo = _mm512_mask_blend_epi32(0x5555, magic_i_lo, v.val); - // Extract the 32 most significant bits of v - __m512i v_hi = _mm512_srli_epi64(v.val, 32); - // Flip the msb of v_hi and blend with 0x45300000 - v_hi = _mm512_xor_si512(v_hi, magic_i_hi32); - // Compute in double precision - __m512d v_hi_dbl = _mm512_sub_pd(_mm512_castsi512_pd(v_hi), magic_d_all); - // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition - __m512d result = _mm512_add_pd(v_hi_dbl, _mm512_castsi512_pd(v_lo)); - return v_float64x8(result); -#endif -} - -////////////// Lookup table access //////////////////// - -inline v_int8x64 v512_lut(const schar* tab, const int* idx) -{ - __m128i p0 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); - __m128i p1 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); - __m128i p2 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 2), (const int *)tab, 1)); - __m128i p3 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 3), (const int *)tab, 1)); - return v_int8x64(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512(p0), p1, 1), p2, 2), p3, 3)); -} -inline v_int8x64 v512_lut_pairs(const schar* tab, const int* idx) -{ - __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); - __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); - return v_int8x64(_v512_combine(p0, p1)); -} -inline v_int8x64 v512_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x64(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 1)); -} -inline v_uint8x64 v512_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut((const schar *)tab, idx)); } -inline v_uint8x64 v512_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x64 v512_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_quads((const schar *)tab, idx)); } - -inline v_int16x32 v512_lut(const short* tab, const int* idx) -{ - __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 2)); - __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 2)); - return v_int16x32(_v512_combine(p0, p1)); -} -inline v_int16x32 v512_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x32(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 2)); -} -inline v_int16x32 v512_lut_quads(const short* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 2)); -#else - return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 2)); -#endif -} -inline v_uint16x32 v512_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut((const short *)tab, idx)); } -inline v_uint16x32 v512_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_pairs((const short *)tab, idx)); } -inline v_uint16x32 v512_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_quads((const short *)tab, idx)); } - -inline v_int32x16 v512_lut(const int* tab, const int* idx) -{ - return v_int32x16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); -} -inline v_int32x16 v512_lut_pairs(const int* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 4)); -#else - return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 4)); -#endif -} -inline v_int32x16 v512_lut_quads(const int* tab, const int* idx) -{ - return v_int32x16(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( - _mm_loadu_si128((const __m128i*)(tab + idx[0]))), - _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), - _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), - _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); -} -inline v_uint32x16 v512_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut((const int *)tab, idx)); } -inline v_uint32x16 v512_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_pairs((const int *)tab, idx)); } -inline v_uint32x16 v512_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_quads((const int *)tab, idx)); } - -inline v_int64x8 v512_lut(const int64* tab, const int* idx) -{ -#if defined(__GNUC__) - return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 8)); -#else - return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), tab , 8)); -#endif -} -inline v_int64x8 v512_lut_pairs(const int64* tab, const int* idx) -{ - return v_int64x8(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( - _mm_loadu_si128((const __m128i*)(tab + idx[0]))), - _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), - _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), - _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); -} -inline v_uint64x8 v512_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut((const int64 *)tab, idx)); } -inline v_uint64x8 v512_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut_pairs((const int64 *)tab, idx)); } - -inline v_float32x16 v512_lut(const float* tab, const int* idx) -{ - return v_float32x16(_mm512_i32gather_ps(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); -} -inline v_float32x16 v512_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_pairs((const int *)tab, idx)); } -inline v_float32x16 v512_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_quads((const int *)tab, idx)); } - -inline v_float64x8 v512_lut(const double* tab, const int* idx) -{ - return v_float64x8(_mm512_i32gather_pd(_mm256_loadu_si256((const __m256i*)idx), tab, 8)); -} -inline v_float64x8 v512_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x8(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_castpd128_pd512( - _mm_loadu_pd(tab + idx[0])), - _mm_loadu_pd(tab + idx[1]), 1), - _mm_loadu_pd(tab + idx[2]), 2), - _mm_loadu_pd(tab + idx[3]), 3)); -} - -inline v_int32x16 v_lut(const int* tab, const v_int32x16& idxvec) -{ - return v_int32x16(_mm512_i32gather_epi32(idxvec.val, tab, 4)); -} - -inline v_uint32x16 v_lut(const unsigned* tab, const v_int32x16& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x16 v_lut(const float* tab, const v_int32x16& idxvec) -{ - return v_float32x16(_mm512_i32gather_ps(idxvec.val, tab, 4)); -} - -inline v_float64x8 v_lut(const double* tab, const v_int32x16& idxvec) -{ - return v_float64x8(_mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8)); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x16& idxvec, v_float32x16& x, v_float32x16& y) -{ - x.val = _mm512_i32gather_ps(idxvec.val, tab, 4); - y.val = _mm512_i32gather_ps(idxvec.val, &tab[1], 4); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x16& idxvec, v_float64x8& x, v_float64x8& y) -{ - x.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8); - y.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), &tab[1], 8); -} - -inline v_int8x64 v_interleave_pairs(const v_int8x64& vec) -{ - return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0d0e0c, 0x0b090a08, 0x07050604, 0x03010200))); -} -inline v_uint8x64 v_interleave_pairs(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x64 v_interleave_quads(const v_int8x64& vec) -{ - return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0b0e0a, 0x0d090c08, 0x07030602, 0x05010400))); -} -inline v_uint8x64 v_interleave_quads(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x32 v_interleave_pairs(const v_int16x32& vec) -{ - return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0b0a, 0x0d0c0908, 0x07060302, 0x05040100))); -} -inline v_uint16x32 v_interleave_pairs(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x32 v_interleave_quads(const v_int16x32& vec) -{ - return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0706, 0x0d0c0504, 0x0b0a0302, 0x09080100))); -} -inline v_uint16x32 v_interleave_quads(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x16 v_interleave_pairs(const v_int32x16& vec) -{ - return v_int32x16(_mm512_shuffle_epi32(vec.val, _MM_PERM_ACBD)); -} -inline v_uint32x16 v_interleave_pairs(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x16 v_interleave_pairs(const v_float32x16& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x64 v_pack_triplets(const v_int8x64& vec) -{ - return v_int8x64(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, - 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), - _mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0xffffff0f, 0x0e0d0c0a, 0x09080605, 0x04020100)))); -} -inline v_uint8x64 v_pack_triplets(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x32 v_pack_triplets(const v_int16x32& vec) -{ - return v_int16x32(_mm512_permutexvar_epi16(_v512_set_epu64(0x001f001f001f001f, 0x001f001f001f001f, 0x001e001d001c001a, 0x0019001800160015, - 0x0014001200110010, 0x000e000d000c000a, 0x0009000800060005, 0x0004000200010000), vec.val)); -} -inline v_uint16x32 v_pack_triplets(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x16 v_pack_triplets(const v_int32x16& vec) -{ - return v_int32x16(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, - 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); -} -inline v_uint32x16 v_pack_triplets(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } -inline v_float32x16 v_pack_triplets(const v_float32x16& vec) -{ - return v_float32x16(_mm512_permutexvar_ps(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, - 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); -} - -////////// Matrix operations ///////// - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b) -{ return v_int32x16(_mm512_madd_epi16(a.val, b.val)); } -inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b) -{ - __m512i even = _mm512_mul_epi32(a.val, b.val); - __m512i odd = _mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32)); - return v_int64x8(_mm512_add_epi64(even, odd)); -} -inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b) -{ - __m512i even_a = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, _mm512_setzero_si512()); - __m512i odd_a = _mm512_srli_epi16(a.val, 8); - - __m512i even_b = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b.val, _mm512_setzero_si512()); - __m512i odd_b = _mm512_srli_epi16(b.val, 8); - - __m512i prod0 = _mm512_madd_epi16(even_a, even_b); - __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); - return v_uint32x16(_mm512_add_epi32(prod0, prod1)); -} -inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b) -{ - __m512i even_a = _mm512_srai_epi16(_mm512_bslli_epi128(a.val, 1), 8); - __m512i odd_a = _mm512_srai_epi16(a.val, 8); - - __m512i even_b = _mm512_srai_epi16(_mm512_bslli_epi128(b.val, 1), 8); - __m512i odd_b = _mm512_srai_epi16(b.val, 8); - - __m512i prod0 = _mm512_madd_epi16(even_a, even_b); - __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); - return v_int32x16(_mm512_add_epi32(prod0, prod1)); -} -inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b) -{ - __m512i mullo = _mm512_mullo_epi16(a.val, b.val); - __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); - __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); - __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); - - __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); - __m512i p13 = _mm512_srli_epi64(mul0, 32); - __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); - __m512i p57 = _mm512_srli_epi64(mul1, 32); - - __m512i p15_ = _mm512_add_epi64(p02, p13); - __m512i p9d_ = _mm512_add_epi64(p46, p57); - - return v_uint64x8(_mm512_add_epi64( - _mm512_unpacklo_epi64(p15_, p9d_), - _mm512_unpackhi_epi64(p15_, p9d_) - )); -} -inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b) -{ - __m512i prod = _mm512_madd_epi16(a.val, b.val); - __m512i even = _mm512_srai_epi64(_mm512_bslli_epi128(prod, 4), 32); - __m512i odd = _mm512_srai_epi64(prod, 32); - return v_int64x8(_mm512_add_epi64(even, odd)); -} -inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b) -{ return v_dotprod(a, b); } -inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b) -{ return v_dotprod(a, b); } -inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b) -{ - __m512i mullo = _mm512_mullo_epi16(a.val, b.val); - __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); - __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); - __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); - - __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); - __m512i p13 = _mm512_srli_epi64(mul0, 32); - __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); - __m512i p57 = _mm512_srli_epi64(mul1, 32); - - __m512i p15_ = _mm512_add_epi64(p02, p13); - __m512i p9d_ = _mm512_add_epi64(p46, p57); - return v_uint64x8(_mm512_add_epi64(p15_, p9d_)); -} -inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b) -{ return v_dotprod_expand(a, b); } -inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) -{ return v_dotprod_expand(a, b, c); } - -// 32 >> 64f -inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - - -#define OPENCV_HAL_AVX512_SPLAT2_PS(a, im) \ - v_float32x16(_mm512_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) - -inline v_float32x16 v_matmul(const v_float32x16& v, - const v_float32x16& m0, const v_float32x16& m1, - const v_float32x16& m2, const v_float32x16& m3) -{ - v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); - v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); - v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); - v_float32x16 v37 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 3); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); -} - -inline v_float32x16 v_matmuladd(const v_float32x16& v, - const v_float32x16& m0, const v_float32x16& m1, - const v_float32x16& m2, const v_float32x16& a) -{ - v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); - v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); - v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); -} - -#define OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m512i t0 = cast_from(_mm512_unpacklo_##suffix(a0.val, a1.val)); \ - __m512i t1 = cast_from(_mm512_unpacklo_##suffix(a2.val, a3.val)); \ - __m512i t2 = cast_from(_mm512_unpackhi_##suffix(a0.val, a1.val)); \ - __m512i t3 = cast_from(_mm512_unpackhi_##suffix(a2.val, a3.val)); \ - b0.val = cast_to(_mm512_unpacklo_epi64(t0, t1)); \ - b1.val = cast_to(_mm512_unpackhi_epi64(t0, t1)); \ - b2.val = cast_to(_mm512_unpacklo_epi64(t2, t3)); \ - b3.val = cast_to(_mm512_unpackhi_epi64(t2, t3)); \ - } - -OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_uint32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_int32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_float32x16, ps, _mm512_castps_si512, _mm512_castsi512_ps) - -//////////////// Value reordering /////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_AVX512_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(_v512_extract_low(a.val)); \ - b1.val = intrin(_v512_extract_high(a.val)); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v512_extract_low(a.val))); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin(_v512_extract_high(a.val))); } \ - inline _Tpwvec v512_load_expand(const _Tp* ptr) \ - { \ - __m256i a = _mm256_loadu_si256((const __m256i*)ptr); \ - return _Tpwvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint8x64, v_uint16x32, uchar, _mm512_cvtepu8_epi16) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_int8x64, v_int16x32, schar, _mm512_cvtepi8_epi16) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint16x32, v_uint32x16, ushort, _mm512_cvtepu16_epi32) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_int16x32, v_int32x16, short, _mm512_cvtepi16_epi32) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint32x16, v_uint64x8, unsigned, _mm512_cvtepu32_epi64) -OPENCV_HAL_IMPL_AVX512_EXPAND(v_int32x16, v_int64x8, int, _mm512_cvtepi32_epi64) - -#define OPENCV_HAL_IMPL_AVX512_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v512_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ - return _Tpvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_uint32x16, uchar, _mm512_cvtepu8_epi32) -OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_int32x16, schar, _mm512_cvtepi8_epi32) - -/* pack */ -// 16 -inline v_int8x64 v_pack(const v_int16x32& a, const v_int16x32& b) -{ return v_int8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } - -inline v_uint8x64 v_pack(const v_uint16x32& a, const v_uint16x32& b) -{ - const __m512i t = _mm512_set1_epi16(255); - return v_uint8x64(_v512_combine(_mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, t)), _mm512_cvtepi16_epi8(_mm512_min_epu16(b.val, t)))); -} - -inline v_uint8x64 v_pack_u(const v_int16x32& a, const v_int16x32& b) -{ - return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi16(a.val, b.val))); -} - -inline void v_pack_store(schar* ptr, const v_int16x32& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar* ptr, const v_uint16x32& a) -{ - const __m512i m = _mm512_set1_epi16(255); - _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, m))); -} - -inline void v_pack_u_store(uchar* ptr, const v_int16x32& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x64 v_rshr_pack(const v_uint16x32& a, const v_uint16x32& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); - return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x32& a) -{ - v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint8x64 v_rshr_pack_u(const v_int16x32& a, const v_int16x32& b) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x32& a) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int8x64 v_rshr_pack(const v_int16x32& a, const v_int16x32& b) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x32& a) -{ - v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 32 -inline v_int16x32 v_pack(const v_int32x16& a, const v_int32x16& b) -{ return v_int16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi32(a.val, b.val))); } - -inline v_uint16x32 v_pack(const v_uint32x16& a, const v_uint32x16& b) -{ - const __m512i m = _mm512_set1_epi32(65535); - return v_uint16x32(_v512_combine(_mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m)), _mm512_cvtepi32_epi16(_mm512_min_epu32(b.val, m)))); -} - -inline v_uint16x32 v_pack_u(const v_int32x16& a, const v_int32x16& b) -{ return v_uint16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi32(a.val, b.val))); } - -inline void v_pack_store(short* ptr, const v_int32x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x16& a) -{ - const __m512i m = _mm512_set1_epi32(65535); - _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m))); -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x16& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - - -template inline -v_uint16x32 v_rshr_pack(const v_uint32x16& a, const v_uint32x16& b) -{ - v_uint32x16 delta = v512_setall_u32(1 << (n-1)); - return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), - v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); -} - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x16& a) -{ - v_uint32x16 delta = v512_setall_u32(1 << (n-1)); - v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); -} - -template inline -v_uint16x32 v_rshr_pack_u(const v_int32x16& a, const v_int32x16& b) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x16& a) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int16x32 v_rshr_pack(const v_int32x16& a, const v_int32x16& b) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x16& a) -{ - v_int32x16 delta = v512_setall_s32(1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// 64 -// Non-saturating pack -inline v_uint32x16 v_pack(const v_uint64x8& a, const v_uint64x8& b) -{ return v_uint32x16(_v512_combine(_mm512_cvtepi64_epi32(a.val), _mm512_cvtepi64_epi32(b.val))); } - -inline v_int32x16 v_pack(const v_int64x8& a, const v_int64x8& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x8& a) -{ _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi64_epi32(a.val)); } - -inline void v_pack_store(int* ptr, const v_int64x8& b) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } - -template inline -v_uint32x16 v_rshr_pack(const v_uint64x8& a, const v_uint64x8& b) -{ - v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x8& a) -{ - v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -template inline -v_int32x16 v_rshr_pack(const v_int64x8& a, const v_int64x8& b) -{ - v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); - return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); -} - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x8& a) -{ - v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); - v_pack_store(ptr, v_shr(v_add(a, delta), n)); -} - -// pack boolean -inline v_uint8x64 v_pack_b(const v_uint16x32& a, const v_uint16x32& b) -{ return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } - -inline v_uint8x64 v_pack_b(const v_uint32x16& a, const v_uint32x16& b, - const v_uint32x16& c, const v_uint32x16& d) -{ - __m512i ab = _mm512_packs_epi32(a.val, b.val); - __m512i cd = _mm512_packs_epi32(c.val, d.val); - - return v_uint8x64(_mm512_permutexvar_epi32(_v512_set_epu32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0), _mm512_packs_epi16(ab, cd))); -} - -inline v_uint8x64 v_pack_b(const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, - const v_uint64x8& d, const v_uint64x8& e, const v_uint64x8& f, - const v_uint64x8& g, const v_uint64x8& h) -{ - __m512i ab = _mm512_packs_epi32(a.val, b.val); - __m512i cd = _mm512_packs_epi32(c.val, d.val); - __m512i ef = _mm512_packs_epi32(e.val, f.val); - __m512i gh = _mm512_packs_epi32(g.val, h.val); - - __m512i abcd = _mm512_packs_epi32(ab, cd); - __m512i efgh = _mm512_packs_epi32(ef, gh); - - return v_uint8x64(_mm512_permutexvar_epi16(_v512_set_epu16(31, 23, 15, 7, 30, 22, 14, 6, 29, 21, 13, 5, 28, 20, 12, 4, - 27, 19, 11, 3, 26, 18, 10, 2, 25, 17, 9, 1, 24, 16, 8, 0), _mm512_packs_epi16(abcd, efgh))); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_AVX512_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint8x64) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int8x64) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint16x32) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int16x32) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint32x16) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int32x16) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint64x8) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int64x8) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float32x16) -OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float64x8) - -#define OPENCV_HAL_IMPL_AVX512_EXTRACT_N(_Tpvec, _Tp) \ -template inline _Tp v_extract_n(_Tpvec v) { return v_rotate_right(v).get0(); } - -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint8x64, uchar) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int8x64, schar) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint16x32, ushort) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int16x32, short) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint32x16, uint) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int32x16, int) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint64x8, uint64) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int64x8, int64) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float32x16, float) -OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float64x8, double) - -template -inline v_uint32x16 v_broadcast_element(v_uint32x16 a) -{ - static const __m512i perm = _mm512_set1_epi32((char)i); - return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); -} - -template -inline v_int32x16 v_broadcast_element(const v_int32x16 &a) -{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -template -inline v_float32x16 v_broadcast_element(const v_float32x16 &a) -{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } - - -///////////////////// load deinterleave ///////////////////////////// - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, - 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, - 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, - 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, - 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask0, ab1)); - b = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask1, ab1)); -#else - __m512i mask0 = _mm512_set4_epi32(0x0f0d0b09, 0x07050301, 0x0e0c0a08, 0x06040200); - __m512i a0b0 = _mm512_shuffle_epi8(ab0, mask0); - __m512i a1b1 = _mm512_shuffle_epi8(ab1, mask0); - __m512i mask1 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask2 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask1, a1b1)); - b = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask2, a1b1)); -#endif -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask0, ab1)); - b = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask1, ab1)); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask0, ab1)); - b = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask1, ab1)); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b ) -{ - __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); - __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); - a = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask0, ab1)); - b = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask1, ab1)); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); - -#if CV_AVX_512VBMI2 - __m512i mask0 = _v512_set_epu8(126, 123, 120, 117, 114, 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, - 78, 75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, - 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, 62, 59, 56, 53, 50, - 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2); - __m512i r0b01 = _mm512_permutex2var_epi8(bgr0, mask0, bgr1); - __m512i b1g12 = _mm512_permutex2var_epi8(bgr1, mask0, bgr2); - __m512i r12b2 = _mm512_permutex2var_epi8(bgr1, - _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, - 77, 74, 71, 68, 65, 127, 124, 121, 118, 115, 112, 109, 106, 103, 100, 97, - 94, 91, 88, 85, 82, 79, 76, 73, 70, 67, 64, 61, 58, 55, 52, 49, - 46, 43, 40, 37, 34, 31, 28, 25, 22, 19, 16, 13, 10, 7, 4, 1), bgr2); - a = v_uint8x64(_mm512_mask_compress_epi8(r12b2, 0xffffffffffe00000, r0b01)); - b = v_uint8x64(_mm512_mask_compress_epi8(b1g12, 0x2492492492492492, bgr0)); - c = v_uint8x64(_mm512_mask_expand_epi8(r0b01, 0xffffffffffe00000, r12b2)); -#elif CV_AVX_512VBMI - __m512i b0g0b1 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr1, bgr0); - __m512i g1r1g2 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr2, bgr1); - __m512i r2b2r0 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr0, bgr2); - a = v_uint8x64(_mm512_permutex2var_epi8(b0g0b1, _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, - 77, 74, 71, 68, 65, 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, - 46, 45, 43, 42, 40, 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, - 23, 21, 20, 18, 17, 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0), bgr2)); - b = v_uint8x64(_mm512_permutex2var_epi8(g1r1g2, _v512_set_epu8( 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, 46, 45, 43, 42, 40, - 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, 23, 21, 20, 18, 17, - 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0, 126, 123, 120, 117, 114, - 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, 78, 75, 72, 69, 66), bgr0)); - c = v_uint8x64(_mm512_permutex2var_epi8(r2b2r0, _v512_set_epu8( 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, - 15, 12, 9, 6, 3, 0, 125, 122, 119, 116, 113, 110, 107, 104, 101, 98, - 95, 92, 89, 86, 83, 80, 77, 74, 71, 68, 65, 62, 59, 56, 53, 50, - 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2), bgr1)); -#else - __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, - 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); - __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); - __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); - __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); - - __m512i b0g0 = _mm512_mask_blend_epi32(0xf800, b01g1, r12b2); - __m512i r0b1 = _mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, - 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0); - __m512i g1r1 = _mm512_alignr_epi32(r12b2, g20r0, 11); - a = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b0g0, r0b1)); - c = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, r0b1, g1r1)); - b = v_uint8x64(_mm512_shuffle_epi8(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1r1, b0g0), _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001))); -#endif -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - - __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, - 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); - __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); - __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); - __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); - - a = v_uint16x32(_mm512_mask_blend_epi32(0xf800, b01g1, r12b2)); - b = v_uint16x32(_mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, - 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0)); - c = v_uint16x32(_mm512_alignr_epi32(r12b2, g20r0, 11)); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - - __m512i mask0 = _v512_set_epu32(29, 26, 23, 20, 17, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); - __m512i b01r1 = _mm512_permutex2var_epi32(bgr0, mask0, bgr1); - __m512i g12b2 = _mm512_permutex2var_epi32(bgr1, mask0, bgr2); - __m512i r20g0 = _mm512_permutex2var_epi32(bgr2, mask0, bgr0); - - a = v_uint32x16(_mm512_mask_blend_epi32(0xf800, b01r1, g12b2)); - b = v_uint32x16(_mm512_alignr_epi32(g12b2, r20g0, 11)); - c = v_uint32x16(_mm512_permutex2var_epi32(bgr1, _v512_set_epu32(21, 20, 19, 18, 17, 16, 13, 10, 7, 4, 1, 26, 25, 24, 23, 22), r20g0)); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c ) -{ - __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); - __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - - __m512i mask0 = _v512_set_epu64(13, 10, 15, 12, 9, 6, 3, 0); - __m512i b01g1 = _mm512_permutex2var_epi64(bgr0, mask0, bgr1); - __m512i r12b2 = _mm512_permutex2var_epi64(bgr1, mask0, bgr2); - __m512i g20r0 = _mm512_permutex2var_epi64(bgr2, mask0, bgr0); - - a = v_uint64x8(_mm512_mask_blend_epi64(0xc0, b01g1, r12b2)); - c = v_uint64x8(_mm512_alignr_epi64(r12b2, g20r0, 6)); - b = v_uint64x8(_mm512_permutex2var_epi64(bgr1, _v512_set_epu64(10, 9, 8, 5, 2, 13, 12, 11), g20r0)); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c, v_uint8x64& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 192)); - -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, - 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, - 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, - 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, - 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi8(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi8(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi8(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi8(bgra2, mask1, bgra3); - - a = v_uint8x64(_mm512_permutex2var_epi8(br01, mask0, br23)); - c = v_uint8x64(_mm512_permutex2var_epi8(br01, mask1, br23)); - b = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask0, ga23)); - d = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask1, ga23)); -#else - __m512i mask = _mm512_set4_epi32(0x0f0b0703, 0x0e0a0602, 0x0d090501, 0x0c080400); - __m512i b0g0r0a0 = _mm512_shuffle_epi8(bgra0, mask); - __m512i b1g1r1a1 = _mm512_shuffle_epi8(bgra1, mask); - __m512i b2g2r2a2 = _mm512_shuffle_epi8(bgra2, mask); - __m512i b3g3r3a3 = _mm512_shuffle_epi8(bgra3, mask); - - __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi32(b0g0r0a0, mask0, b1g1r1a1); - __m512i ga01 = _mm512_permutex2var_epi32(b0g0r0a0, mask1, b1g1r1a1); - __m512i br23 = _mm512_permutex2var_epi32(b2g2r2a2, mask0, b3g3r3a3); - __m512i ga23 = _mm512_permutex2var_epi32(b2g2r2a2, mask1, b3g3r3a3); - - a = v_uint8x64(_mm512_permutex2var_epi32(br01, mask0, br23)); - c = v_uint8x64(_mm512_permutex2var_epi32(br01, mask1, br23)); - b = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask0, ga23)); - d = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask1, ga23)); -#endif -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c, v_uint16x32& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 96)); - - __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, - 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, - 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi16(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi16(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi16(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi16(bgra2, mask1, bgra3); - - a = v_uint16x32(_mm512_permutex2var_epi16(br01, mask0, br23)); - c = v_uint16x32(_mm512_permutex2var_epi16(br01, mask1, br23)); - b = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask0, ga23)); - d = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask1, ga23)); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c, v_uint32x16& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 48)); - - __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi32(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi32(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi32(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi32(bgra2, mask1, bgra3); - - a = v_uint32x16(_mm512_permutex2var_epi32(br01, mask0, br23)); - c = v_uint32x16(_mm512_permutex2var_epi32(br01, mask1, br23)); - b = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask0, ga23)); - d = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask1, ga23)); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c, v_uint64x8& d ) -{ - __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); - __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); - __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); - __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 24)); - - __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); - __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); - - __m512i br01 = _mm512_permutex2var_epi64(bgra0, mask0, bgra1); - __m512i ga01 = _mm512_permutex2var_epi64(bgra0, mask1, bgra1); - __m512i br23 = _mm512_permutex2var_epi64(bgra2, mask0, bgra3); - __m512i ga23 = _mm512_permutex2var_epi64(bgra2, mask1, bgra3); - - a = v_uint64x8(_mm512_permutex2var_epi64(br01, mask0, br23)); - c = v_uint64x8(_mm512_permutex2var_epi64(br01, mask1, br23)); - b = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask0, ga23)); - d = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask1, ga23)); -} - -///////////////////////////// store interleave ///////////////////////////////////// - -inline void v_store_interleave( uchar* ptr, const v_uint8x64& x, const v_uint8x64& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint8x64 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 64), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 64), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 64), high.val); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x32& x, const v_uint16x32& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint16x32 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 32), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 32), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 32), high.val); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x16& x, const v_uint32x16& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint32x16 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 16), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 16), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 16), high.val); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x8& x, const v_uint64x8& y, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint64x8 low, high; - v_zip(x, y, low, high); - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, low.val); - _mm512_stream_si512((__m512i*)(ptr + 8), high.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, low.val); - _mm512_store_si512((__m512i*)(ptr + 8), high.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, low.val); - _mm512_storeu_si512((__m512i*)(ptr + 8), high.val); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, const v_uint8x64& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ -#if CV_AVX_512VBMI - __m512i mask0 = _v512_set_epu8(127, 84, 20, 126, 83, 19, 125, 82, 18, 124, 81, 17, 123, 80, 16, 122, - 79, 15, 121, 78, 14, 120, 77, 13, 119, 76, 12, 118, 75, 11, 117, 74, - 10, 116, 73, 9, 115, 72, 8, 114, 71, 7, 113, 70, 6, 112, 69, 5, - 111, 68, 4, 110, 67, 3, 109, 66, 2, 108, 65, 1, 107, 64, 0, 106); - __m512i mask1 = _v512_set_epu8( 21, 42, 105, 20, 41, 104, 19, 40, 103, 18, 39, 102, 17, 38, 101, 16, - 37, 100, 15, 36, 99, 14, 35, 98, 13, 34, 97, 12, 33, 96, 11, 32, - 95, 10, 31, 94, 9, 30, 93, 8, 29, 92, 7, 28, 91, 6, 27, 90, - 5, 26, 89, 4, 25, 88, 3, 24, 87, 2, 23, 86, 1, 22, 85, 0); - __m512i mask2 = _v512_set_epu8(106, 127, 63, 105, 126, 62, 104, 125, 61, 103, 124, 60, 102, 123, 59, 101, - 122, 58, 100, 121, 57, 99, 120, 56, 98, 119, 55, 97, 118, 54, 96, 117, - 53, 95, 116, 52, 94, 115, 51, 93, 114, 50, 92, 113, 49, 91, 112, 48, - 90, 111, 47, 89, 110, 46, 88, 109, 45, 87, 108, 44, 86, 107, 43, 85); - __m512i r2g0r0 = _mm512_permutex2var_epi8(b.val, mask0, c.val); - __m512i b0r1b1 = _mm512_permutex2var_epi8(a.val, mask1, c.val); - __m512i g1b2g2 = _mm512_permutex2var_epi8(a.val, mask2, b.val); - - __m512i bgr0 = _mm512_mask_blend_epi8(0x9249249249249249, r2g0r0, b0r1b1); - __m512i bgr1 = _mm512_mask_blend_epi8(0x9249249249249249, b0r1b1, g1b2g2); - __m512i bgr2 = _mm512_mask_blend_epi8(0x9249249249249249, g1b2g2, r2g0r0); -#else - __m512i g1g0 = _mm512_shuffle_epi8(b.val, _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001)); - __m512i b0g0 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, g1g0); - __m512i r0b1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, c.val, a.val); - __m512i g1r1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1g0, c.val); - - __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, - 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); - __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, - 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); - __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, - 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); - __m512i b0g0b2 = _mm512_permutex2var_epi16(b0g0, mask0, r0b1); - __m512i r1b1r0 = _mm512_permutex2var_epi16(b0g0, mask1, g1r1); - __m512i g2r2g1 = _mm512_permutex2var_epi16(r0b1, mask2, g1r1); - - __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); - __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); - __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); -#endif - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 64), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 128), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 64), bgr1); - _mm512_store_si512((__m512i*)(ptr + 128), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 128), bgr2); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, const v_uint16x32& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, - 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); - __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, - 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); - __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, - 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); - __m512i b0g0b2 = _mm512_permutex2var_epi16(a.val, mask0, b.val); - __m512i r1b1r0 = _mm512_permutex2var_epi16(a.val, mask1, c.val); - __m512i g2r2g1 = _mm512_permutex2var_epi16(b.val, mask2, c.val); - - __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); - __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); - __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 32), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 64), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 32), bgr1); - _mm512_store_si512((__m512i*)(ptr + 64), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgr2); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, const v_uint32x16& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m512i mask0 = _v512_set_epu32(26, 31, 15, 25, 30, 14, 24, 29, 13, 23, 28, 12, 22, 27, 11, 21); - __m512i mask1 = _v512_set_epu32(31, 10, 25, 30, 9, 24, 29, 8, 23, 28, 7, 22, 27, 6, 21, 26); - __m512i g1b2g2 = _mm512_permutex2var_epi32(a.val, mask0, b.val); - __m512i r2r1b1 = _mm512_permutex2var_epi32(a.val, mask1, c.val); - - __m512i bgr0 = _mm512_mask_expand_epi32(_mm512_mask_expand_epi32(_mm512_maskz_expand_epi32(0x9249, a.val), 0x2492, b.val), 0x4924, c.val); - __m512i bgr1 = _mm512_mask_blend_epi32(0x9249, r2r1b1, g1b2g2); - __m512i bgr2 = _mm512_mask_blend_epi32(0x9249, g1b2g2, r2r1b1); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 16), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 32), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 16), bgr1); - _mm512_store_si512((__m512i*)(ptr + 32), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgr2); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - __m512i mask0 = _v512_set_epu64( 5, 12, 7, 4, 11, 6, 3, 10); - __m512i mask1 = _v512_set_epu64(15, 7, 4, 14, 6, 3, 13, 5); - __m512i r1b1b2 = _mm512_permutex2var_epi64(a.val, mask0, c.val); - __m512i g2r2g1 = _mm512_permutex2var_epi64(b.val, mask1, c.val); - - __m512i bgr0 = _mm512_mask_expand_epi64(_mm512_mask_expand_epi64(_mm512_maskz_expand_epi64(0x49, a.val), 0x92, b.val), 0x24, c.val); - __m512i bgr1 = _mm512_mask_blend_epi64(0xdb, g2r2g1, r1b1b2); - __m512i bgr2 = _mm512_mask_blend_epi64(0xdb, r1b1b2, g2r2g1); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgr0); - _mm512_stream_si512((__m512i*)(ptr + 8), bgr1); - _mm512_stream_si512((__m512i*)(ptr + 16), bgr2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgr0); - _mm512_store_si512((__m512i*)(ptr + 8), bgr1); - _mm512_store_si512((__m512i*)(ptr + 16), bgr2); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgr0); - _mm512_storeu_si512((__m512i*)(ptr + 8), bgr1); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgr2); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, - const v_uint8x64& c, const v_uint8x64& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint8x64 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint8x64 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 64), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 128), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 192), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 64), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 128), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 192), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 128), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 192), bgra3.val); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, - const v_uint16x32& c, const v_uint16x32& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint16x32 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint16x32 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 32), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 64), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 96), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 32), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 64), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 96), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 64), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 96), bgra3.val); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, - const v_uint32x16& c, const v_uint32x16& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint32x16 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint32x16 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 16), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 32), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 48), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 16), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 32), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 48), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 32), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 48), bgra3.val); - } -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, - const v_uint64x8& c, const v_uint64x8& d, - hal::StoreMode mode=hal::STORE_UNALIGNED ) -{ - v_uint64x8 br01, br23, ga01, ga23; - v_zip(a, c, br01, br23); - v_zip(b, d, ga01, ga23); - v_uint64x8 bgra0, bgra1, bgra2, bgra3; - v_zip(br01, ga01, bgra0, bgra1); - v_zip(br23, ga23, bgra2, bgra3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm512_stream_si512((__m512i*)ptr, bgra0.val); - _mm512_stream_si512((__m512i*)(ptr + 8), bgra1.val); - _mm512_stream_si512((__m512i*)(ptr + 16), bgra2.val); - _mm512_stream_si512((__m512i*)(ptr + 24), bgra3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm512_store_si512((__m512i*)ptr, bgra0.val); - _mm512_store_si512((__m512i*)(ptr + 8), bgra1.val); - _mm512_store_si512((__m512i*)(ptr + 16), bgra2.val); - _mm512_store_si512((__m512i*)(ptr + 24), bgra3.val); - } - else - { - _mm512_storeu_si512((__m512i*)ptr, bgra0.val); - _mm512_storeu_si512((__m512i*)(ptr + 8), bgra1.val); - _mm512_storeu_si512((__m512i*)(ptr + 16), bgra2.val); - _mm512_storeu_si512((__m512i*)(ptr + 24), bgra3.val); - } -} - -#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int8x64, schar, s8, v_uint8x64, uchar, u8) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int16x32, short, s16, v_uint16x32, ushort, u16) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int32x16, int, s32, v_uint32x16, unsigned, u32) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float32x16, float, f32, v_uint32x16, unsigned, u32) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int64x8, int64, s64, v_uint64x8, uint64, u64) -OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float64x8, double, f64, v_uint64x8, uint64, u64) - -////////// Mask and checks ///////// - -/** Mask **/ -inline int64 v_signmask(const v_int8x64& a) { return (int64)_mm512_movepi8_mask(a.val); } -inline int v_signmask(const v_int16x32& a) { return (int)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline int v_signmask(const v_int32x16& a) { return (int)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline int v_signmask(const v_int64x8& a) { return (int)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } - -inline int64 v_signmask(const v_uint8x64& a) { return v_signmask(v_reinterpret_as_s8(a)); } -inline int v_signmask(const v_uint16x32& a) { return v_signmask(v_reinterpret_as_s16(a)); } -inline int v_signmask(const v_uint32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_uint64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } -inline int v_signmask(const v_float32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_float64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } - -/** Checks **/ -inline bool v_check_all(const v_int8x64& a) { return !(bool)_mm512_cmp_epi8_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int8x64& a) { return (bool)_mm512_movepi8_mask(a.val); } -inline bool v_check_all(const v_int16x32& a) { return !(bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int16x32& a) { return (bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline bool v_check_all(const v_int32x16& a) { return !(bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int32x16& a) { return (bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } -inline bool v_check_all(const v_int64x8& a) { return !(bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } -inline bool v_check_any(const v_int64x8& a) { return (bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } - -inline bool v_check_all(const v_float32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_float32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_float64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_float64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } -inline bool v_check_all(const v_uint8x64& a) { return v_check_all(v_reinterpret_as_s8(a)); } -inline bool v_check_all(const v_uint16x32& a) { return v_check_all(v_reinterpret_as_s16(a)); } -inline bool v_check_all(const v_uint32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_uint64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_uint8x64& a) { return v_check_any(v_reinterpret_as_s8(a)); } -inline bool v_check_any(const v_uint16x32& a) { return v_check_any(v_reinterpret_as_s16(a)); } -inline bool v_check_any(const v_uint32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_uint64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } - -inline int v_scan_forward(const v_int8x64& a) -{ - int64 mask = _mm512_movepi8_mask(a.val); - int mask32 = (int)mask; - return mask != 0 ? mask32 != 0 ? trailingZeros32(mask32) : 32 + trailingZeros32((int)(mask >> 32)) : 0; -} -inline int v_scan_forward(const v_uint8x64& a) { return v_scan_forward(v_reinterpret_as_s8(a)); } -inline int v_scan_forward(const v_int16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } -inline int v_scan_forward(const v_uint16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } -inline int v_scan_forward(const v_int32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } -inline int v_scan_forward(const v_uint32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } -inline int v_scan_forward(const v_float32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } -inline int v_scan_forward(const v_int64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } -inline int v_scan_forward(const v_uint64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } -inline int v_scan_forward(const v_float64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } - -inline void v512_cleanup() { _mm256_zeroall(); } - -#include "intrin_math.hpp" -inline v_float32x16 v_exp(const v_float32x16& x) { return v_exp_default_32f(x); } -inline v_float32x16 v_log(const v_float32x16& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x16& x, v_float32x16& s, v_float32x16& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x16 v_sin(const v_float32x16& x) { return v_sin_default_32f(x); } -inline v_float32x16 v_cos(const v_float32x16& x) { return v_cos_default_32f(x); } -inline v_float32x16 v_erf(const v_float32x16& x) { return v_erf_default_32f(x); } - -inline v_float64x8 v_exp(const v_float64x8& x) { return v_exp_default_64f(x); } -inline v_float64x8 v_log(const v_float64x8& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x8& x, v_float64x8& s, v_float64x8& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x8 v_sin(const v_float64x8& x) { return v_sin_default_64f(x); } -inline v_float64x8 v_cos(const v_float64x8& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_AVX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_AVX512_HPP +#define OPENCV_HAL_INTRIN_AVX512_HPP + +#if defined(_MSC_VER) && (_MSC_VER < 1920/*MSVS2019*/) +# pragma warning(disable:4146) // unary minus operator applied to unsigned type, result still unsigned +# pragma warning(disable:4309) // 'argument': truncation of constant value +# pragma warning(disable:4310) // cast truncates constant value +#endif + +#define CVT_ROUND_MODES_IMPLEMENTED 0 + +#define CV_SIMD512 1 +#define CV_SIMD512_64F 1 +#define CV_SIMD512_FP16 0 // no native operations with FP16 type. Only load/store from float32x8 are available (if CV_FP16 == 1) + +#define _v512_set_epu64(a7, a6, a5, a4, a3, a2, a1, a0) _mm512_set_epi64((int64)(a7),(int64)(a6),(int64)(a5),(int64)(a4),(int64)(a3),(int64)(a2),(int64)(a1),(int64)(a0)) +#define _v512_set_epu32(a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _mm512_set_epi64(((int64)(a15)<<32)|(int64)(a14), ((int64)(a13)<<32)|(int64)(a12), ((int64)(a11)<<32)|(int64)(a10), ((int64)( a9)<<32)|(int64)( a8), \ + ((int64)( a7)<<32)|(int64)( a6), ((int64)( a5)<<32)|(int64)( a4), ((int64)( a3)<<32)|(int64)( a2), ((int64)( a1)<<32)|(int64)( a0)) +#define _v512_set_epu16(a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ + a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _v512_set_epu32(((unsigned)(a31)<<16)|(unsigned)(a30), ((unsigned)(a29)<<16)|(unsigned)(a28), ((unsigned)(a27)<<16)|(unsigned)(a26), ((unsigned)(a25)<<16)|(unsigned)(a24), \ + ((unsigned)(a23)<<16)|(unsigned)(a22), ((unsigned)(a21)<<16)|(unsigned)(a20), ((unsigned)(a19)<<16)|(unsigned)(a18), ((unsigned)(a17)<<16)|(unsigned)(a16), \ + ((unsigned)(a15)<<16)|(unsigned)(a14), ((unsigned)(a13)<<16)|(unsigned)(a12), ((unsigned)(a11)<<16)|(unsigned)(a10), ((unsigned)( a9)<<16)|(unsigned)( a8), \ + ((unsigned)( a7)<<16)|(unsigned)( a6), ((unsigned)( a5)<<16)|(unsigned)( a4), ((unsigned)( a3)<<16)|(unsigned)( a2), ((unsigned)( a1)<<16)|(unsigned)( a0)) +#define _v512_set_epu8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ + a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ + a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ + a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _v512_set_epu32(((unsigned)(a63)<<24)|((unsigned)(a62)<<16)|((unsigned)(a61)<<8)|(unsigned)(a60),((unsigned)(a59)<<24)|((unsigned)(a58)<<16)|((unsigned)(a57)<<8)|(unsigned)(a56), \ + ((unsigned)(a55)<<24)|((unsigned)(a54)<<16)|((unsigned)(a53)<<8)|(unsigned)(a52),((unsigned)(a51)<<24)|((unsigned)(a50)<<16)|((unsigned)(a49)<<8)|(unsigned)(a48), \ + ((unsigned)(a47)<<24)|((unsigned)(a46)<<16)|((unsigned)(a45)<<8)|(unsigned)(a44),((unsigned)(a43)<<24)|((unsigned)(a42)<<16)|((unsigned)(a41)<<8)|(unsigned)(a40), \ + ((unsigned)(a39)<<24)|((unsigned)(a38)<<16)|((unsigned)(a37)<<8)|(unsigned)(a36),((unsigned)(a35)<<24)|((unsigned)(a34)<<16)|((unsigned)(a33)<<8)|(unsigned)(a32), \ + ((unsigned)(a31)<<24)|((unsigned)(a30)<<16)|((unsigned)(a29)<<8)|(unsigned)(a28),((unsigned)(a27)<<24)|((unsigned)(a26)<<16)|((unsigned)(a25)<<8)|(unsigned)(a24), \ + ((unsigned)(a23)<<24)|((unsigned)(a22)<<16)|((unsigned)(a21)<<8)|(unsigned)(a20),((unsigned)(a19)<<24)|((unsigned)(a18)<<16)|((unsigned)(a17)<<8)|(unsigned)(a16), \ + ((unsigned)(a15)<<24)|((unsigned)(a14)<<16)|((unsigned)(a13)<<8)|(unsigned)(a12),((unsigned)(a11)<<24)|((unsigned)(a10)<<16)|((unsigned)( a9)<<8)|(unsigned)( a8), \ + ((unsigned)( a7)<<24)|((unsigned)( a6)<<16)|((unsigned)( a5)<<8)|(unsigned)( a4),((unsigned)( a3)<<24)|((unsigned)( a2)<<16)|((unsigned)( a1)<<8)|(unsigned)( a0)) +#define _v512_set_epi8(a63, a62, a61, a60, a59, a58, a57, a56, a55, a54, a53, a52, a51, a50, a49, a48, \ + a47, a46, a45, a44, a43, a42, a41, a40, a39, a38, a37, a36, a35, a34, a33, a32, \ + a31, a30, a29, a28, a27, a26, a25, a24, a23, a22, a21, a20, a19, a18, a17, a16, \ + a15, a14, a13, a12, a11, a10, a9, a8, a7, a6, a5, a4, a3, a2, a1, a0) \ + _v512_set_epu8((uchar)(a63), (uchar)(a62), (uchar)(a61), (uchar)(a60), (uchar)(a59), (uchar)(a58), (uchar)(a57), (uchar)(a56), \ + (uchar)(a55), (uchar)(a54), (uchar)(a53), (uchar)(a52), (uchar)(a51), (uchar)(a50), (uchar)(a49), (uchar)(a48), \ + (uchar)(a47), (uchar)(a46), (uchar)(a45), (uchar)(a44), (uchar)(a43), (uchar)(a42), (uchar)(a41), (uchar)(a40), \ + (uchar)(a39), (uchar)(a38), (uchar)(a37), (uchar)(a36), (uchar)(a35), (uchar)(a34), (uchar)(a33), (uchar)(a32), \ + (uchar)(a31), (uchar)(a30), (uchar)(a29), (uchar)(a28), (uchar)(a27), (uchar)(a26), (uchar)(a25), (uchar)(a24), \ + (uchar)(a23), (uchar)(a22), (uchar)(a21), (uchar)(a20), (uchar)(a19), (uchar)(a18), (uchar)(a17), (uchar)(a16), \ + (uchar)(a15), (uchar)(a14), (uchar)(a13), (uchar)(a12), (uchar)(a11), (uchar)(a10), (uchar)( a9), (uchar)( a8), \ + (uchar)( a7), (uchar)( a6), (uchar)( a5), (uchar)( a4), (uchar)( a3), (uchar)( a2), (uchar)( a1), (uchar)( a0)) + +#ifndef _mm512_cvtpd_pslo +#ifdef _mm512_zextsi256_si512 +#define _mm512_cvtpd_pslo(a) _mm512_zextps256_ps512(_mm512_cvtpd_ps(a)) +#else +//if preferred way to extend with zeros is unavailable +#define _mm512_cvtpd_pslo(a) _mm512_castps256_ps512(_mm512_cvtpd_ps(a)) +#endif +#endif +///////// Utils //////////// + +namespace +{ + +inline __m512i _v512_combine(const __m256i& lo, const __m256i& hi) +{ return _mm512_inserti32x8(_mm512_castsi256_si512(lo), hi, 1); } + +inline __m512 _v512_combine(const __m256& lo, const __m256& hi) +{ return _mm512_insertf32x8(_mm512_castps256_ps512(lo), hi, 1); } + +inline __m512d _v512_combine(const __m256d& lo, const __m256d& hi) +{ return _mm512_insertf64x4(_mm512_castpd256_pd512(lo), hi, 1); } + +inline int _v_cvtsi512_si32(const __m512i& a) +{ return _mm_cvtsi128_si32(_mm512_castsi512_si128(a)); } + +inline __m256i _v512_extract_high(const __m512i& v) +{ return _mm512_extracti32x8_epi32(v, 1); } + +inline __m256 _v512_extract_high(const __m512& v) +{ return _mm512_extractf32x8_ps(v, 1); } + +inline __m256d _v512_extract_high(const __m512d& v) +{ return _mm512_extractf64x4_pd(v, 1); } + +inline __m256i _v512_extract_low(const __m512i& v) +{ return _mm512_castsi512_si256(v); } + +inline __m256 _v512_extract_low(const __m512& v) +{ return _mm512_castps512_ps256(v); } + +inline __m256d _v512_extract_low(const __m512d& v) +{ return _mm512_castpd512_pd256(v); } + +inline __m512i _v512_insert(const __m512i& a, const __m256i& b) +{ return _mm512_inserti32x8(a, b, 0); } + +inline __m512 _v512_insert(const __m512& a, const __m256& b) +{ return _mm512_insertf32x8(a, b, 0); } + +inline __m512d _v512_insert(const __m512d& a, const __m256d& b) +{ return _mm512_insertf64x4(a, b, 0); } + +} + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Types //////////// + +struct v_uint8x64 +{ + typedef uchar lane_type; + enum { nlanes = 64 }; + __m512i val; + + explicit v_uint8x64(__m512i v) : val(v) {} + v_uint8x64(uchar v0, uchar v1, uchar v2, uchar v3, + uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, + uchar v12, uchar v13, uchar v14, uchar v15, + uchar v16, uchar v17, uchar v18, uchar v19, + uchar v20, uchar v21, uchar v22, uchar v23, + uchar v24, uchar v25, uchar v26, uchar v27, + uchar v28, uchar v29, uchar v30, uchar v31, + uchar v32, uchar v33, uchar v34, uchar v35, + uchar v36, uchar v37, uchar v38, uchar v39, + uchar v40, uchar v41, uchar v42, uchar v43, + uchar v44, uchar v45, uchar v46, uchar v47, + uchar v48, uchar v49, uchar v50, uchar v51, + uchar v52, uchar v53, uchar v54, uchar v55, + uchar v56, uchar v57, uchar v58, uchar v59, + uchar v60, uchar v61, uchar v62, uchar v63) + { + val = _v512_set_epu8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, + v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, + v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, + v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); + } + v_uint8x64() {} + + static inline v_uint8x64 zero() { return v_uint8x64(_mm512_setzero_si512()); } + + uchar get0() const { return (uchar)_v_cvtsi512_si32(val); } +}; + +struct v_int8x64 +{ + typedef schar lane_type; + enum { nlanes = 64 }; + __m512i val; + + explicit v_int8x64(__m512i v) : val(v) {} + v_int8x64(schar v0, schar v1, schar v2, schar v3, + schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, + schar v12, schar v13, schar v14, schar v15, + schar v16, schar v17, schar v18, schar v19, + schar v20, schar v21, schar v22, schar v23, + schar v24, schar v25, schar v26, schar v27, + schar v28, schar v29, schar v30, schar v31, + schar v32, schar v33, schar v34, schar v35, + schar v36, schar v37, schar v38, schar v39, + schar v40, schar v41, schar v42, schar v43, + schar v44, schar v45, schar v46, schar v47, + schar v48, schar v49, schar v50, schar v51, + schar v52, schar v53, schar v54, schar v55, + schar v56, schar v57, schar v58, schar v59, + schar v60, schar v61, schar v62, schar v63) + { + val = _v512_set_epi8(v63, v62, v61, v60, v59, v58, v57, v56, v55, v54, v53, v52, v51, v50, v49, v48, + v47, v46, v45, v44, v43, v42, v41, v40, v39, v38, v37, v36, v35, v34, v33, v32, + v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, + v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); + } + v_int8x64() {} + + static inline v_int8x64 zero() { return v_int8x64(_mm512_setzero_si512()); } + + schar get0() const { return (schar)_v_cvtsi512_si32(val); } +}; + +struct v_uint16x32 +{ + typedef ushort lane_type; + enum { nlanes = 32 }; + __m512i val; + + explicit v_uint16x32(__m512i v) : val(v) {} + v_uint16x32(ushort v0, ushort v1, ushort v2, ushort v3, + ushort v4, ushort v5, ushort v6, ushort v7, + ushort v8, ushort v9, ushort v10, ushort v11, + ushort v12, ushort v13, ushort v14, ushort v15, + ushort v16, ushort v17, ushort v18, ushort v19, + ushort v20, ushort v21, ushort v22, ushort v23, + ushort v24, ushort v25, ushort v26, ushort v27, + ushort v28, ushort v29, ushort v30, ushort v31) + { + val = _v512_set_epu16(v31, v30, v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, v19, v18, v17, v16, + v15, v14, v13, v12, v11, v10, v9, v8, v7, v6, v5, v4, v3, v2, v1, v0); + } + v_uint16x32() {} + + static inline v_uint16x32 zero() { return v_uint16x32(_mm512_setzero_si512()); } + + ushort get0() const { return (ushort)_v_cvtsi512_si32(val); } +}; + +struct v_int16x32 +{ + typedef short lane_type; + enum { nlanes = 32 }; + __m512i val; + + explicit v_int16x32(__m512i v) : val(v) {} + v_int16x32(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15, + short v16, short v17, short v18, short v19, short v20, short v21, short v22, short v23, + short v24, short v25, short v26, short v27, short v28, short v29, short v30, short v31) + { + val = _v512_set_epu16((ushort)v31, (ushort)v30, (ushort)v29, (ushort)v28, (ushort)v27, (ushort)v26, (ushort)v25, (ushort)v24, + (ushort)v23, (ushort)v22, (ushort)v21, (ushort)v20, (ushort)v19, (ushort)v18, (ushort)v17, (ushort)v16, + (ushort)v15, (ushort)v14, (ushort)v13, (ushort)v12, (ushort)v11, (ushort)v10, (ushort)v9 , (ushort)v8, + (ushort)v7 , (ushort)v6 , (ushort)v5 , (ushort)v4 , (ushort)v3 , (ushort)v2 , (ushort)v1 , (ushort)v0); + } + v_int16x32() {} + + static inline v_int16x32 zero() { return v_int16x32(_mm512_setzero_si512()); } + + short get0() const { return (short)_v_cvtsi512_si32(val); } +}; + +struct v_uint32x16 +{ + typedef unsigned lane_type; + enum { nlanes = 16 }; + __m512i val; + + explicit v_uint32x16(__m512i v) : val(v) {} + v_uint32x16(unsigned v0, unsigned v1, unsigned v2, unsigned v3, + unsigned v4, unsigned v5, unsigned v6, unsigned v7, + unsigned v8, unsigned v9, unsigned v10, unsigned v11, + unsigned v12, unsigned v13, unsigned v14, unsigned v15) + { + val = _mm512_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3, (int)v4, (int)v5, (int)v6, (int)v7, + (int)v8, (int)v9, (int)v10, (int)v11, (int)v12, (int)v13, (int)v14, (int)v15); + } + v_uint32x16() {} + + static inline v_uint32x16 zero() { return v_uint32x16(_mm512_setzero_si512()); } + + unsigned get0() const { return (unsigned)_v_cvtsi512_si32(val); } +}; + +struct v_int32x16 +{ + typedef int lane_type; + enum { nlanes = 16 }; + __m512i val; + + explicit v_int32x16(__m512i v) : val(v) {} + v_int32x16(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7, + int v8, int v9, int v10, int v11, int v12, int v13, int v14, int v15) + { + val = _mm512_setr_epi32(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + v_int32x16() {} + + static inline v_int32x16 zero() { return v_int32x16(_mm512_setzero_si512()); } + + int get0() const { return _v_cvtsi512_si32(val); } +}; + +struct v_float32x16 +{ + typedef float lane_type; + enum { nlanes = 16 }; + __m512 val; + + explicit v_float32x16(__m512 v) : val(v) {} + v_float32x16(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, + float v8, float v9, float v10, float v11, float v12, float v13, float v14, float v15) + { + val = _mm512_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + v_float32x16() {} + + static inline v_float32x16 zero() { return v_float32x16(_mm512_setzero_ps()); } + + float get0() const { return _mm_cvtss_f32(_mm512_castps512_ps128(val)); } +}; + +struct v_uint64x8 +{ + typedef uint64 lane_type; + enum { nlanes = 8 }; + __m512i val; + + explicit v_uint64x8(__m512i v) : val(v) {} + v_uint64x8(uint64 v0, uint64 v1, uint64 v2, uint64 v3, uint64 v4, uint64 v5, uint64 v6, uint64 v7) + { val = _mm512_setr_epi64((int64)v0, (int64)v1, (int64)v2, (int64)v3, (int64)v4, (int64)v5, (int64)v6, (int64)v7); } + v_uint64x8() {} + + static inline v_uint64x8 zero() { return v_uint64x8(_mm512_setzero_si512()); } + + uint64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (uint64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); + int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); + return (unsigned)a | ((uint64)(unsigned)b << 32); + #endif + } +}; + +struct v_int64x8 +{ + typedef int64 lane_type; + enum { nlanes = 8 }; + __m512i val; + + explicit v_int64x8(__m512i v) : val(v) {} + v_int64x8(int64 v0, int64 v1, int64 v2, int64 v3, int64 v4, int64 v5, int64 v6, int64 v7) + { val = _mm512_setr_epi64(v0, v1, v2, v3, v4, v5, v6, v7); } + v_int64x8() {} + + static inline v_int64x8 zero() { return v_int64x8(_mm512_setzero_si512()); } + + int64 get0() const + { + #if defined __x86_64__ || defined _M_X64 + return (int64)_mm_cvtsi128_si64(_mm512_castsi512_si128(val)); + #else + int a = _mm_cvtsi128_si32(_mm512_castsi512_si128(val)); + int b = _mm_cvtsi128_si32(_mm512_castsi512_si128(_mm512_srli_epi64(val, 32))); + return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); + #endif + } +}; + +struct v_float64x8 +{ + typedef double lane_type; + enum { nlanes = 8 }; + __m512d val; + + explicit v_float64x8(__m512d v) : val(v) {} + v_float64x8(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7) + { val = _mm512_setr_pd(v0, v1, v2, v3, v4, v5, v6, v7); } + v_float64x8() {} + + static inline v_float64x8 zero() { return v_float64x8(_mm512_setzero_pd()); } + + double get0() const { return _mm_cvtsd_f64(_mm512_castpd512_pd128(val)); } +}; + +//////////////// Load and store operations /////////////// + +#define OPENCV_HAL_IMPL_AVX512_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v512_load(const _Tp* ptr) \ + { return _Tpvec(_mm512_loadu_si512((const __m512i*)ptr)); } \ + inline _Tpvec v512_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm512_load_si512((const __m512i*)ptr)); } \ + inline _Tpvec v512_load_low(const _Tp* ptr) \ + { \ + __m256i v256 = _mm256_loadu_si256((const __m256i*)ptr); \ + return _Tpvec(_mm512_castsi256_si512(v256)); \ + } \ + inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m256i vlo = _mm256_loadu_si256((const __m256i*)ptr0); \ + __m256i vhi = _mm256_loadu_si256((const __m256i*)ptr1); \ + return _Tpvec(_v512_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm512_storeu_si512((__m512i*)ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm512_store_si512((__m512i*)ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm512_stream_si512((__m512i*)ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm512_storeu_si512((__m512i*)ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm512_stream_si512((__m512i*)ptr, a.val); \ + else \ + _mm512_store_si512((__m512i*)ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_si256((__m256i*)ptr, _v512_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint8x64, uchar) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int8x64, schar) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint16x32, ushort) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int16x32, short) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint32x16, unsigned) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int32x16, int) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_uint64x8, uint64) +OPENCV_HAL_IMPL_AVX512_LOADSTORE(v_int64x8, int64) + +#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(_Tpvec, _Tp, suffix, halfreg) \ + inline _Tpvec v512_load(const _Tp* ptr) \ + { return _Tpvec(_mm512_loadu_##suffix(ptr)); } \ + inline _Tpvec v512_load_aligned(const _Tp* ptr) \ + { return _Tpvec(_mm512_load_##suffix(ptr)); } \ + inline _Tpvec v512_load_low(const _Tp* ptr) \ + { \ + return _Tpvec(_mm512_cast##suffix##256_##suffix##512 \ + (_mm256_loadu_##suffix(ptr))); \ + } \ + inline _Tpvec v512_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + halfreg vlo = _mm256_loadu_##suffix(ptr0); \ + halfreg vhi = _mm256_loadu_##suffix(ptr1); \ + return _Tpvec(_v512_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { _mm512_storeu_##suffix(ptr, a.val); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { _mm512_store_##suffix(ptr, a.val); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { _mm512_stream_##suffix(ptr, a.val); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm512_storeu_##suffix(ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm512_stream_##suffix(ptr, a.val); \ + else \ + _mm512_store_##suffix(ptr, a.val); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_##suffix(ptr, _v512_extract_low(a.val)); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { _mm256_storeu_##suffix(ptr, _v512_extract_high(a.val)); } + +OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float32x16, float, ps, __m256) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_FLT(v_float64x8, double, pd, __m256d) + +#define OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_AVX512_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v512_setzero_##suffix() \ + { return _Tpvec(_mm512_setzero_si512()); } \ + inline _Tpvec v512_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm512_set1_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v512_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v512_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float32x16, suffix, _mm512_castps_si512) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_float64x8, suffix, _mm512_castpd_si512) + +OPENCV_HAL_IMPL_AVX512_INIT(v_uint8x64, uchar, u8, epi8, char) +OPENCV_HAL_IMPL_AVX512_INIT(v_int8x64, schar, s8, epi8, char) +OPENCV_HAL_IMPL_AVX512_INIT(v_uint16x32, ushort, u16, epi16, short) +OPENCV_HAL_IMPL_AVX512_INIT(v_int16x32, short, s16, epi16, short) +OPENCV_HAL_IMPL_AVX512_INIT(v_uint32x16, unsigned, u32, epi32, int) +OPENCV_HAL_IMPL_AVX512_INIT(v_int32x16, int, s32, epi32, int) +OPENCV_HAL_IMPL_AVX512_INIT(v_uint64x8, uint64, u64, epi64, int64) +OPENCV_HAL_IMPL_AVX512_INIT(v_int64x8, int64, s64, epi64, int64) + +#define OPENCV_HAL_IMPL_AVX512_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v512_setzero_##suffix() \ + { return _Tpvec(_mm512_setzero_##zsuffix()); } \ + inline _Tpvec v512_setall_##suffix(_Tp v) \ + { return _Tpvec(_mm512_set1_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v512_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v512_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint8x64, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int8x64, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint16x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int16x32, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint32x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int32x16, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_uint64x8, suffix, cast) \ + OPENCV_HAL_IMPL_AVX512_CAST(_Tpvec, v_int64x8, suffix, cast) + +OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float32x16, float, f32, ps, _mm512_castsi512_ps) +OPENCV_HAL_IMPL_AVX512_INIT_FLT(v_float64x8, double, f64, pd, _mm512_castsi512_pd) + +inline v_float32x16 v_reinterpret_as_f32(const v_float32x16& a) +{ return a; } +inline v_float32x16 v_reinterpret_as_f32(const v_float64x8& a) +{ return v_float32x16(_mm512_castpd_ps(a.val)); } + +inline v_float64x8 v_reinterpret_as_f64(const v_float64x8& a) +{ return a; } +inline v_float64x8 v_reinterpret_as_f64(const v_float32x16& a) +{ return v_float64x8(_mm512_castps_pd(a.val)); } + +// FP16 +inline v_float32x16 v512_load_expand(const hfloat* ptr) +{ + return v_float32x16(_mm512_cvtph_ps(_mm256_loadu_si256((const __m256i*)ptr))); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x16& a) +{ + __m256i ah = _mm512_cvtps_ph(a.val, 0); + _mm256_storeu_si256((__m256i*)ptr, ah); +} + +/* Recombine & ZIP */ +inline void v_zip(const v_int8x64& a, const v_int8x64& b, v_int8x64& ab0, v_int8x64& ab1) +{ +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8( 95, 31, 94, 30, 93, 29, 92, 28, 91, 27, 90, 26, 89, 25, 88, 24, + 87, 23, 86, 22, 85, 21, 84, 20, 83, 19, 82, 18, 81, 17, 80, 16, + 79, 15, 78, 14, 77, 13, 76, 12, 75, 11, 74, 10, 73, 9, 72, 8, + 71, 7, 70, 6, 69, 5, 68, 4, 67, 3, 66, 2, 65, 1, 64, 0); + ab0 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu8(127, 63, 126, 62, 125, 61, 124, 60, 123, 59, 122, 58, 121, 57, 120, 56, + 119, 55, 118, 54, 117, 53, 116, 52, 115, 51, 114, 50, 113, 49, 112, 48, + 111, 47, 110, 46, 109, 45, 108, 44, 107, 43, 106, 42, 105, 41, 104, 40, + 103, 39, 102, 38, 101, 37, 100, 36, 99, 35, 98, 34, 97, 33, 96, 32); + ab1 = v_int8x64(_mm512_permutex2var_epi8(a.val, mask1, b.val)); +#else + __m512i low = _mm512_unpacklo_epi8(a.val, b.val); + __m512i high = _mm512_unpackhi_epi8(a.val, b.val); + ab0 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(11, 10, 3, 2, 9, 8, 1, 0), high)); + ab1 = v_int8x64(_mm512_permutex2var_epi64(low, _v512_set_epu64(15, 14, 7, 6, 13, 12, 5, 4), high)); +#endif +} +inline void v_zip(const v_int16x32& a, const v_int16x32& b, v_int16x32& ab0, v_int16x32& ab1) +{ + __m512i mask0 = _v512_set_epu16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10, 41, 9, 40, 8, + 39, 7, 38, 6, 37, 5, 36, 4, 35, 3, 34, 2, 33, 1, 32, 0); + ab0 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26, 57, 25, 56, 24, + 55, 23, 54, 22, 53, 21, 52, 20, 51, 19, 50, 18, 49, 17, 48, 16); + ab1 = v_int16x32(_mm512_permutex2var_epi16(a.val, mask1, b.val)); +} +inline void v_zip(const v_int32x16& a, const v_int32x16& b, v_int32x16& ab0, v_int32x16& ab1) +{ + __m512i mask0 = _v512_set_epu32(23, 7, 22, 6, 21, 5, 20, 4, 19, 3, 18, 2, 17, 1, 16, 0); + ab0 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu32(31, 15, 30, 14, 29, 13, 28, 12, 27, 11, 26, 10, 25, 9, 24, 8); + ab1 = v_int32x16(_mm512_permutex2var_epi32(a.val, mask1, b.val)); +} +inline void v_zip(const v_int64x8& a, const v_int64x8& b, v_int64x8& ab0, v_int64x8& ab1) +{ + __m512i mask0 = _v512_set_epu64(11, 3, 10, 2, 9, 1, 8, 0); + ab0 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask0, b.val)); + __m512i mask1 = _v512_set_epu64(15, 7, 14, 6, 13, 5, 12, 4); + ab1 = v_int64x8(_mm512_permutex2var_epi64(a.val, mask1, b.val)); +} + +inline void v_zip(const v_uint8x64& a, const v_uint8x64& b, v_uint8x64& ab0, v_uint8x64& ab1) +{ + v_int8x64 i0, i1; + v_zip(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b), i0, i1); + ab0 = v_reinterpret_as_u8(i0); + ab1 = v_reinterpret_as_u8(i1); +} +inline void v_zip(const v_uint16x32& a, const v_uint16x32& b, v_uint16x32& ab0, v_uint16x32& ab1) +{ + v_int16x32 i0, i1; + v_zip(v_reinterpret_as_s16(a), v_reinterpret_as_s16(b), i0, i1); + ab0 = v_reinterpret_as_u16(i0); + ab1 = v_reinterpret_as_u16(i1); +} +inline void v_zip(const v_uint32x16& a, const v_uint32x16& b, v_uint32x16& ab0, v_uint32x16& ab1) +{ + v_int32x16 i0, i1; + v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); + ab0 = v_reinterpret_as_u32(i0); + ab1 = v_reinterpret_as_u32(i1); +} +inline void v_zip(const v_uint64x8& a, const v_uint64x8& b, v_uint64x8& ab0, v_uint64x8& ab1) +{ + v_int64x8 i0, i1; + v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); + ab0 = v_reinterpret_as_u64(i0); + ab1 = v_reinterpret_as_u64(i1); +} +inline void v_zip(const v_float32x16& a, const v_float32x16& b, v_float32x16& ab0, v_float32x16& ab1) +{ + v_int32x16 i0, i1; + v_zip(v_reinterpret_as_s32(a), v_reinterpret_as_s32(b), i0, i1); + ab0 = v_reinterpret_as_f32(i0); + ab1 = v_reinterpret_as_f32(i1); +} +inline void v_zip(const v_float64x8& a, const v_float64x8& b, v_float64x8& ab0, v_float64x8& ab1) +{ + v_int64x8 i0, i1; + v_zip(v_reinterpret_as_s64(a), v_reinterpret_as_s64(b), i0, i1); + ab0 = v_reinterpret_as_f64(i0); + ab1 = v_reinterpret_as_f64(i1); +} + +#define OPENCV_HAL_IMPL_AVX512_COMBINE(_Tpvec, suffix) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_v512_combine(_v512_extract_low(a.val), _v512_extract_low(b.val))); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_v512_insert(b.val, _v512_extract_high(a.val))); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + c.val = _v512_combine(_v512_extract_low(a.val),_v512_extract_low(b.val)); \ + d.val = _v512_insert(b.val,_v512_extract_high(a.val)); \ + } + + +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint8x64, epi8) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int8x64, epi8) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint16x32, epi16) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int16x32, epi16) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint32x16, epi32) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int32x16, epi32) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_uint64x8, epi64) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_int64x8, epi64) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_COMBINE(v_float64x8, pd) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/* Element-wise binary and unary operations */ + +/** Non-saturating arithmetics **/ +#define OPENCV_HAL_IMPL_AVX512_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint8x64, _mm512_add_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int8x64, _mm512_add_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_uint16x32, _mm512_add_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_add_wrap, v_int16x32, _mm512_add_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint8x64, _mm512_sub_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int8x64, _mm512_sub_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_uint16x32, _mm512_sub_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_sub_wrap, v_int16x32, _mm512_sub_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_uint16x32, _mm512_mullo_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_mul_wrap, v_int16x32, _mm512_mullo_epi16) + +inline v_uint8x64 v_mul_wrap(const v_uint8x64& a, const v_uint8x64& b) +{ + __m512i ad = _mm512_srai_epi16(a.val, 8); + __m512i bd = _mm512_srai_epi16(b.val, 8); + __m512i p0 = _mm512_mullo_epi16(a.val, b.val); // even + __m512i p1 = _mm512_slli_epi16(_mm512_mullo_epi16(ad, bd), 8); // odd + return v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, p0, p1)); +} +inline v_int8x64 v_mul_wrap(const v_int8x64& a, const v_int8x64& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +#define OPENCV_HAL_IMPL_AVX512_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint32x16, _mm512_add_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint32x16, _mm512_sub_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int32x16, _mm512_add_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int32x16, _mm512_sub_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint64x8, _mm512_add_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint64x8, _mm512_sub_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int64x8, _mm512_add_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int64x8, _mm512_sub_epi64) + +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint32x16, _mm512_mullo_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int32x16, _mm512_mullo_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_uint64x8, _mm512_mullo_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_int64x8, _mm512_mullo_epi64) + +/** Saturating arithmetics **/ +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint8x64, _mm512_adds_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint8x64, _mm512_subs_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int8x64, _mm512_adds_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int8x64, _mm512_subs_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_uint16x32, _mm512_adds_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_uint16x32, _mm512_subs_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_int16x32, _mm512_adds_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_int16x32, _mm512_subs_epi16) + +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float32x16, _mm512_add_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float32x16, _mm512_sub_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float32x16, _mm512_mul_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float32x16, _mm512_div_ps) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_add, v_float64x8, _mm512_add_pd) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_sub, v_float64x8, _mm512_sub_pd) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_mul, v_float64x8, _mm512_mul_pd) +OPENCV_HAL_IMPL_AVX512_BIN_OP(v_div, v_float64x8, _mm512_div_pd) + +// saturating multiply +inline v_uint8x64 v_mul(const v_uint8x64& a, const v_uint8x64& b) +{ + v_uint16x32 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x64 v_mul(const v_int8x64& a, const v_int8x64& b) +{ + v_int16x32 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x32 v_mul(const v_uint16x32& a, const v_uint16x32& b) +{ + __m512i pl = _mm512_mullo_epi16(a.val, b.val); + __m512i ph = _mm512_mulhi_epu16(a.val, b.val); + __m512i p0 = _mm512_unpacklo_epi16(pl, ph); + __m512i p1 = _mm512_unpackhi_epi16(pl, ph); + + const __m512i m = _mm512_set1_epi32(65535); + return v_uint16x32(_mm512_packus_epi32(_mm512_min_epu32(p0, m), _mm512_min_epu32(p1, m))); +} +inline v_int16x32 v_mul(const v_int16x32& a, const v_int16x32& b) +{ + __m512i pl = _mm512_mullo_epi16(a.val, b.val); + __m512i ph = _mm512_mulhi_epi16(a.val, b.val); + __m512i p0 = _mm512_unpacklo_epi16(pl, ph); + __m512i p1 = _mm512_unpackhi_epi16(pl, ph); + return v_int16x32(_mm512_packs_epi32(p0, p1)); +} + +inline v_int16x32 v_mul_hi(const v_int16x32& a, const v_int16x32& b) { return v_int16x32(_mm512_mulhi_epi16(a.val, b.val)); } +inline v_uint16x32 v_mul_hi(const v_uint16x32& a, const v_uint16x32& b) { return v_uint16x32(_mm512_mulhi_epu16(a.val, b.val)); } + +// Multiply and expand +inline void v_mul_expand(const v_uint8x64& a, const v_uint8x64& b, + v_uint16x32& c, v_uint16x32& d) +{ + v_uint16x32 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x64& a, const v_int8x64& b, + v_int16x32& c, v_int16x32& d) +{ + v_int16x32 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x32& a, const v_int16x32& b, + v_int32x16& c, v_int32x16& d) +{ + v_int16x32 v0, v1; + v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); + + c = v_reinterpret_as_s32(v0); + d = v_reinterpret_as_s32(v1); +} + +inline void v_mul_expand(const v_uint16x32& a, const v_uint16x32& b, + v_uint32x16& c, v_uint32x16& d) +{ + v_uint16x32 v0, v1; + v_zip(v_mul_wrap(a, b), v_mul_hi(a, b), v0, v1); + + c = v_reinterpret_as_u32(v0); + d = v_reinterpret_as_u32(v1); +} + +inline void v_mul_expand(const v_uint32x16& a, const v_uint32x16& b, + v_uint64x8& c, v_uint64x8& d) +{ + v_zip(v_uint64x8(_mm512_mul_epu32(a.val, b.val)), + v_uint64x8(_mm512_mul_epu32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); +} + +inline void v_mul_expand(const v_int32x16& a, const v_int32x16& b, + v_int64x8& c, v_int64x8& d) +{ + v_zip(v_int64x8(_mm512_mul_epi32(a.val, b.val)), + v_int64x8(_mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32))), c, d); +} + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_AVX512_SHIFT_OP(_Tpuvec, _Tpsvec, suffix) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(_mm512_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(_mm512_slli_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(_mm512_srli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(_mm512_srai_##suffix(a.val, imm)); } + +OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint16x32, v_int16x32, epi16) +OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint32x16, v_int32x16, epi32) +OPENCV_HAL_IMPL_AVX512_SHIFT_OP(v_uint64x8, v_int64x8, epi64) + + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_AVX512_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_AVX512_BIN_OP(v_and, _Tpvec, _mm512_and_##suffix) \ + OPENCV_HAL_IMPL_AVX512_BIN_OP(v_or, _Tpvec, _mm512_or_##suffix) \ + OPENCV_HAL_IMPL_AVX512_BIN_OP(v_xor, _Tpvec, _mm512_xor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(_mm512_xor_##suffix(a.val, not_const)); } + +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint8x64, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int8x64, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint16x32, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int16x32, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint32x16, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int32x16, si512, _mm512_set1_epi32(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_uint64x8, si512, _mm512_set1_epi64(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_int64x8, si512, _mm512_set1_epi64(-1)) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float32x16, ps, _mm512_castsi512_ps(_mm512_set1_epi32(-1))) +OPENCV_HAL_IMPL_AVX512_LOGIC_OP(v_float64x8, pd, _mm512_castsi512_pd(_mm512_set1_epi32(-1))) + +/** Select **/ +#define OPENCV_HAL_IMPL_AVX512_SELECT(_Tpvec, suffix, zsuf) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm512_mask_blend_##suffix(_mm512_cmp_##suffix##_mask(mask.val, _mm512_setzero_##zsuf(), _MM_CMPINT_EQ), a.val, b.val)); } + +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint8x64, epi8, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int8x64, epi8, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint16x32, epi16, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int16x32, epi16, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint32x16, epi32, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int32x16, epi32, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_uint64x8, epi64, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_int64x8, epi64, si512) +OPENCV_HAL_IMPL_AVX512_SELECT(v_float32x16, ps, ps) +OPENCV_HAL_IMPL_AVX512_SELECT(v_float64x8, pd, pd) + +/** Comparison **/ +#define OPENCV_HAL_IMPL_AVX512_CMP_INT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval)); } + +#define OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(_Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_eq, _MM_CMPINT_EQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ne, _MM_CMPINT_NE, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_lt, _MM_CMPINT_LT, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_gt, _MM_CMPINT_NLE, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_le, _MM_CMPINT_LE, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_INT(v_ge, _MM_CMPINT_NLT, _Tpvec, sufcmp, sufset, tval) + +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint8x64, epu8, epi8, (char)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int8x64, epi8, epi8, (char)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint16x32, epu16, epi16, (short)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int16x32, epi16, epi16, (short)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint32x16, epu32, epi32, (int)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int32x16, epi32, epi32, (int)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_uint64x8, epu64, epi64, (int64)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_INT(v_int64x8, epi64, epi64, (int64)-1) + +#define OPENCV_HAL_IMPL_AVX512_CMP_FLT(bin_op, imm8, _Tpvec, sufcmp, sufset, tval) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(_mm512_castsi512_##sufcmp(_mm512_maskz_set1_##sufset(_mm512_cmp_##sufcmp##_mask(a.val, b.val, imm8), tval))); } + +#define OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(_Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_eq, _CMP_EQ_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ne, _CMP_NEQ_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_lt, _CMP_LT_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_gt, _CMP_GT_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_le, _CMP_LE_OQ, _Tpvec, sufcmp, sufset, tval) \ + OPENCV_HAL_IMPL_AVX512_CMP_FLT(v_ge, _CMP_GE_OQ, _Tpvec, sufcmp, sufset, tval) + +OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float32x16, ps, epi32, (int)-1) +OPENCV_HAL_IMPL_AVX512_CMP_OP_FLT(v_float64x8, pd, epi64, (int64)-1) + +inline v_float32x16 v_not_nan(const v_float32x16& a) +{ return v_float32x16(_mm512_castsi512_ps(_mm512_maskz_set1_epi32(_mm512_cmp_ps_mask(a.val, a.val, _CMP_ORD_Q), (int)-1))); } +inline v_float64x8 v_not_nan(const v_float64x8& a) +{ return v_float64x8(_mm512_castsi512_pd(_mm512_maskz_set1_epi64(_mm512_cmp_pd_mask(a.val, a.val, _CMP_ORD_Q), (int64)-1))); } + +/** min/max **/ +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint8x64, _mm512_min_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint8x64, _mm512_max_epu8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int8x64, _mm512_min_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int8x64, _mm512_max_epi8) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint16x32, _mm512_min_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint16x32, _mm512_max_epu16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int16x32, _mm512_min_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int16x32, _mm512_max_epi16) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint32x16, _mm512_min_epu32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint32x16, _mm512_max_epu32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int32x16, _mm512_min_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int32x16, _mm512_max_epi32) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_uint64x8, _mm512_min_epu64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_uint64x8, _mm512_max_epu64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_int64x8, _mm512_min_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_int64x8, _mm512_max_epi64) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float32x16, _mm512_min_ps) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float32x16, _mm512_max_ps) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_min, v_float64x8, _mm512_min_pd) +OPENCV_HAL_IMPL_AVX512_BIN_FUNC(v_max, v_float64x8, _mm512_max_pd) + +/** Rotate **/ +namespace { + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) + { + return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 ), imm4 *8), + _mm512_slli_epi32(_mm512_alignr_epi32(b.val, a.val, imm32 + 1), (4-imm4)*8))); + }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) + { + return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(b.val, a.val, 15), imm4 *8), + _mm512_slli_epi32( b.val, (4-imm4)*8))); + }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) + { + return v_int8x64(_mm512_or_si512(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16), imm4 *8), + _mm512_slli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 15), (4-imm4)*8))); + }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) + { return v_int8x64(_mm512_srli_epi32(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, 15), imm4*8)); }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64& b) + { return v_int8x64(_mm512_alignr_epi32(b.val, a.val, imm32)); }}; + template<> + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64& a, const v_int8x64&) { return a; }}; + template + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) + { return v_int8x64(_mm512_alignr_epi32(_mm512_setzero_si512(), b.val, imm32 - 16)); }}; + template<> + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64& b) { return b; }}; + template<> + struct _v_rotate_right { static inline v_int8x64 eval(const v_int8x64&, const v_int8x64&) { return v_int8x64(); }}; +} +template inline v_int8x64 v_rotate_right(const v_int8x64& a, const v_int8x64& b) +{ + return imm >= 128 ? v_int8x64() : +#if CV_AVX_512VBMI + v_int8x64(_mm512_permutex2var_epi8(a.val, + _v512_set_epu8(0x3f + imm, 0x3e + imm, 0x3d + imm, 0x3c + imm, 0x3b + imm, 0x3a + imm, 0x39 + imm, 0x38 + imm, + 0x37 + imm, 0x36 + imm, 0x35 + imm, 0x34 + imm, 0x33 + imm, 0x32 + imm, 0x31 + imm, 0x30 + imm, + 0x2f + imm, 0x2e + imm, 0x2d + imm, 0x2c + imm, 0x2b + imm, 0x2a + imm, 0x29 + imm, 0x28 + imm, + 0x27 + imm, 0x26 + imm, 0x25 + imm, 0x24 + imm, 0x23 + imm, 0x22 + imm, 0x21 + imm, 0x20 + imm, + 0x1f + imm, 0x1e + imm, 0x1d + imm, 0x1c + imm, 0x1b + imm, 0x1a + imm, 0x19 + imm, 0x18 + imm, + 0x17 + imm, 0x16 + imm, 0x15 + imm, 0x14 + imm, 0x13 + imm, 0x12 + imm, 0x11 + imm, 0x10 + imm, + 0x0f + imm, 0x0e + imm, 0x0d + imm, 0x0c + imm, 0x0b + imm, 0x0a + imm, 0x09 + imm, 0x08 + imm, + 0x07 + imm, 0x06 + imm, 0x05 + imm, 0x04 + imm, 0x03 + imm, 0x02 + imm, 0x01 + imm, 0x00 + imm), b.val)); +#else + _v_rotate_right 15), imm/4>::eval(a, b); +#endif +} +template +inline v_int8x64 v_rotate_left(const v_int8x64& a, const v_int8x64& b) +{ + if (imm == 0) return a; + if (imm == 64) return b; + if (imm >= 128) return v_int8x64(); +#if CV_AVX_512VBMI + return v_int8x64(_mm512_permutex2var_epi8(b.val, + _v512_set_epi8(0x7f - imm,0x7e - imm,0x7d - imm,0x7c - imm,0x7b - imm,0x7a - imm,0x79 - imm,0x78 - imm, + 0x77 - imm,0x76 - imm,0x75 - imm,0x74 - imm,0x73 - imm,0x72 - imm,0x71 - imm,0x70 - imm, + 0x6f - imm,0x6e - imm,0x6d - imm,0x6c - imm,0x6b - imm,0x6a - imm,0x69 - imm,0x68 - imm, + 0x67 - imm,0x66 - imm,0x65 - imm,0x64 - imm,0x63 - imm,0x62 - imm,0x61 - imm,0x60 - imm, + 0x5f - imm,0x5e - imm,0x5d - imm,0x5c - imm,0x5b - imm,0x5a - imm,0x59 - imm,0x58 - imm, + 0x57 - imm,0x56 - imm,0x55 - imm,0x54 - imm,0x53 - imm,0x52 - imm,0x51 - imm,0x50 - imm, + 0x4f - imm,0x4e - imm,0x4d - imm,0x4c - imm,0x4b - imm,0x4a - imm,0x49 - imm,0x48 - imm, + 0x47 - imm,0x46 - imm,0x45 - imm,0x44 - imm,0x43 - imm,0x42 - imm,0x41 - imm,0x40 - imm), a.val)); +#else + return imm < 64 ? v_rotate_right<64 - imm>(b, a) : v_rotate_right<128 - imm>(v512_setzero_s8(), b); +#endif +} +template +inline v_int8x64 v_rotate_right(const v_int8x64& a) +{ + if (imm == 0) return a; + if (imm >= 64) return v_int8x64(); +#if CV_AVX_512VBMI + return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF >> imm, + _v512_set_epu8(0x3f + imm,0x3e + imm,0x3d + imm,0x3c + imm,0x3b + imm,0x3a + imm,0x39 + imm,0x38 + imm, + 0x37 + imm,0x36 + imm,0x35 + imm,0x34 + imm,0x33 + imm,0x32 + imm,0x31 + imm,0x30 + imm, + 0x2f + imm,0x2e + imm,0x2d + imm,0x2c + imm,0x2b + imm,0x2a + imm,0x29 + imm,0x28 + imm, + 0x27 + imm,0x26 + imm,0x25 + imm,0x24 + imm,0x23 + imm,0x22 + imm,0x21 + imm,0x20 + imm, + 0x1f + imm,0x1e + imm,0x1d + imm,0x1c + imm,0x1b + imm,0x1a + imm,0x19 + imm,0x18 + imm, + 0x17 + imm,0x16 + imm,0x15 + imm,0x14 + imm,0x13 + imm,0x12 + imm,0x11 + imm,0x10 + imm, + 0x0f + imm,0x0e + imm,0x0d + imm,0x0c + imm,0x0b + imm,0x0a + imm,0x09 + imm,0x08 + imm, + 0x07 + imm,0x06 + imm,0x05 + imm,0x04 + imm,0x03 + imm,0x02 + imm,0x01 + imm,0x00 + imm), a.val)); +#else + return v_rotate_right(a, v512_setzero_s8()); +#endif +} +template +inline v_int8x64 v_rotate_left(const v_int8x64& a) +{ + if (imm == 0) return a; + if (imm >= 64) return v_int8x64(); +#if CV_AVX_512VBMI + return v_int8x64(_mm512_maskz_permutexvar_epi8(0xFFFFFFFFFFFFFFFF << imm, + _v512_set_epi8(0x3f - imm,0x3e - imm,0x3d - imm,0x3c - imm,0x3b - imm,0x3a - imm,0x39 - imm,0x38 - imm, + 0x37 - imm,0x36 - imm,0x35 - imm,0x34 - imm,0x33 - imm,0x32 - imm,0x31 - imm,0x30 - imm, + 0x2f - imm,0x2e - imm,0x2d - imm,0x2c - imm,0x2b - imm,0x2a - imm,0x29 - imm,0x28 - imm, + 0x27 - imm,0x26 - imm,0x25 - imm,0x24 - imm,0x23 - imm,0x22 - imm,0x21 - imm,0x20 - imm, + 0x1f - imm,0x1e - imm,0x1d - imm,0x1c - imm,0x1b - imm,0x1a - imm,0x19 - imm,0x18 - imm, + 0x17 - imm,0x16 - imm,0x15 - imm,0x14 - imm,0x13 - imm,0x12 - imm,0x11 - imm,0x10 - imm, + 0x0f - imm,0x0e - imm,0x0d - imm,0x0c - imm,0x0b - imm,0x0a - imm,0x09 - imm,0x08 - imm, + 0x07 - imm,0x06 - imm,0x05 - imm,0x04 - imm,0x03 - imm,0x02 - imm,0x01 - imm,0x00 - imm), a.val)); +#else + return v_rotate_right<64 - imm>(v512_setzero_s8(), a); +#endif +} + +#define OPENCV_HAL_IMPL_AVX512_ROTATE_PM(_Tpvec, suffix) \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a), v_reinterpret_as_s8(b))); } \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ return v_reinterpret_as_##suffix(v_rotate_left(v_reinterpret_as_s8(a))); } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ return v_reinterpret_as_##suffix(v_rotate_right(v_reinterpret_as_s8(a))); } + +#define OPENCV_HAL_IMPL_AVX512_ROTATE_EC(_Tpvec, suffix) \ +template \ +inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ + enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ + if (imm == 0) return a; \ + if (imm == _Tpvec::nlanes) return b; \ + if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << SHIFT2)&MASK, b.val), (MASK << (imm))&MASK, a.val)); \ +} \ +template \ +inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + enum { SHIFT2 = (_Tpvec::nlanes - imm) }; \ + enum { MASK = ((1 << _Tpvec::nlanes) - 1) }; \ + if (imm == 0) return a; \ + if (imm == _Tpvec::nlanes) return b; \ + if (imm >= 2*_Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_mask_expand_##suffix(_mm512_maskz_compress_##suffix((MASK << (imm))&MASK, a.val), (MASK << SHIFT2)&MASK, b.val)); \ +} \ +template \ +inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + if (imm == 0) return a; \ + if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_maskz_expand_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ +} \ +template \ +inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + if (imm == 0) return a; \ + if (imm >= _Tpvec::nlanes) return _Tpvec::zero(); \ + return _Tpvec(_mm512_maskz_compress_##suffix((1 << _Tpvec::nlanes) - (1 << (imm)), a.val)); \ +} + +OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint8x64, u8) +OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_uint16x32, u16) +OPENCV_HAL_IMPL_AVX512_ROTATE_PM(v_int16x32, s16) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint32x16, epi32) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int32x16, epi32) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_uint64x8, epi64) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_int64x8, epi64) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_ROTATE_EC(v_float64x8, pd) + +/** Reverse **/ +inline v_uint8x64 v_reverse(const v_uint8x64 &a) +{ +#if CV_AVX_512VBMI + static const __m512i perm = _mm512_set_epi32( + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x10111213, 0x14151617, 0x18191a1b, 0x1c1d1e1f, + 0x20212223, 0x24252627, 0x28292a2b, 0x2c2d2e2f, + 0x30313233, 0x34353637, 0x38393a3b, 0x3c3d3e3f); + return v_uint8x64(_mm512_permutexvar_epi8(perm, a.val)); +#else + static const __m512i shuf = _mm512_set_epi32( + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f, + 0x00010203, 0x04050607, 0x08090a0b, 0x0c0d0e0f); + static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); + __m512i vec = _mm512_shuffle_epi8(a.val, shuf); + return v_uint8x64(_mm512_permutexvar_epi64(perm, vec)); +#endif +} + +inline v_int8x64 v_reverse(const v_int8x64 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x32 v_reverse(const v_uint16x32 &a) +{ +#if CV_AVX_512VBMI + static const __m512i perm = _mm512_set_epi32( + 0x00000001, 0x00020003, 0x00040005, 0x00060007, + 0x00080009, 0x000a000b, 0x000c000d, 0x000e000f, + 0x00100011, 0x00120013, 0x00140015, 0x00160017, + 0x00180019, 0x001a001b, 0x001c001d, 0x001e001f); + return v_uint16x32(_mm512_permutexvar_epi16(perm, a.val)); +#else + static const __m512i shuf = _mm512_set_epi32( + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e, + 0x01000302, 0x05040706, 0x09080b0a, 0x0d0c0f0e); + static const __m512i perm = _mm512_set_epi64(1, 0, 3, 2, 5, 4, 7, 6); + __m512i vec = _mm512_shuffle_epi8(a.val, shuf); + return v_uint16x32(_mm512_permutexvar_epi64(perm, vec)); +#endif +} + +inline v_int16x32 v_reverse(const v_int16x32 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x16 v_reverse(const v_uint32x16 &a) +{ + static const __m512i perm = _mm512_set_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14, 15); + return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); +} + +inline v_int32x16 v_reverse(const v_int32x16 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x16 v_reverse(const v_float32x16 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x8 v_reverse(const v_uint64x8 &a) +{ + static const __m512i perm = _mm512_set_epi64(0, 1, 2, 3, 4, 5, 6, 7); + return v_uint64x8(_mm512_permutexvar_epi64(perm, a.val)); +} + +inline v_int64x8 v_reverse(const v_int64x8 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x8 v_reverse(const v_float64x8 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////// Reduce ///////// + +/** Reduce **/ +#define OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64(a, b) a + b +#define OPENCV_HAL_IMPL_AVX512_REDUCE_8(sctype, func, _Tpvec, ifunc, scop) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + sctype CV_DECL_ALIGNED(64) idx[2]; \ + _mm_store_si128((__m128i*)idx, _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1))); \ + return scop(idx[0], idx[1]); } +OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, min, v_uint64x8, min_epu64, min) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, max, v_uint64x8, max_epu64, max) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(uint64, sum, v_uint64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, min, v_int64x8, min_epi64, min) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, max, v_int64x8, max_epi64, max) +OPENCV_HAL_IMPL_AVX512_REDUCE_8(int64, sum, v_int64x8, add_epi64, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_8F(func, ifunc, scop) \ + inline double v_reduce_##func(const v_float64x8& a) \ + { __m256d half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + double CV_DECL_ALIGNED(64) idx[2]; \ + _mm_store_pd(idx, _mm_##ifunc(_mm256_castpd256_pd128(half), _mm256_extractf128_pd(half, 1))); \ + return scop(idx[0], idx[1]); } +OPENCV_HAL_IMPL_AVX512_REDUCE_8F(min, min_pd, min) +OPENCV_HAL_IMPL_AVX512_REDUCE_8F(max, max_pd, max) +OPENCV_HAL_IMPL_AVX512_REDUCE_8F(sum, add_pd, OPENCV_HAL_IMPL_AVX512_REDUCE_ADD64) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_16(sctype, func, _Tpvec, ifunc) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ + return (sctype)_mm_cvtsi128_si32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, min, v_uint32x16, min_epu32) +OPENCV_HAL_IMPL_AVX512_REDUCE_16(uint, max, v_uint32x16, max_epu32) +OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, min, v_int32x16, min_epi32) +OPENCV_HAL_IMPL_AVX512_REDUCE_16(int, max, v_int32x16, max_epi32) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_16F(func, ifunc) \ + inline float v_reduce_##func(const v_float32x16& a) \ + { __m256 half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128 quarter = _mm_##ifunc(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 3, 2))); \ + quarter = _mm_##ifunc(quarter, _mm_permute_ps(quarter, _MM_SHUFFLE(0, 0, 0, 1))); \ + return _mm_cvtss_f32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_16F(min, min_ps) +OPENCV_HAL_IMPL_AVX512_REDUCE_16F(max, max_ps) + +inline float v_reduce_sum(const v_float32x16& a) +{ + __m256 half = _mm256_add_ps(_v512_extract_low(a.val), _v512_extract_high(a.val)); + __m128 quarter = _mm_add_ps(_mm256_castps256_ps128(half), _mm256_extractf128_ps(half, 1)); + quarter = _mm_hadd_ps(quarter, quarter); + return _mm_cvtss_f32(_mm_hadd_ps(quarter, quarter)); +} +inline int v_reduce_sum(const v_int32x16& a) +{ + __m256i half = _mm256_add_epi32(_v512_extract_low(a.val), _v512_extract_high(a.val)); + __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); + quarter = _mm_hadd_epi32(quarter, quarter); + return _mm_cvtsi128_si32(_mm_hadd_epi32(quarter, quarter)); +} +inline uint v_reduce_sum(const v_uint32x16& a) +{ return (uint)v_reduce_sum(v_reinterpret_as_s32(a)); } + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_32(sctype, func, _Tpvec, ifunc) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ + return (sctype)_mm_cvtsi128_si32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, min, v_uint16x32, min_epu16) +OPENCV_HAL_IMPL_AVX512_REDUCE_32(ushort, max, v_uint16x32, max_epu16) +OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, min, v_int16x32, min_epi16) +OPENCV_HAL_IMPL_AVX512_REDUCE_32(short, max, v_int16x32, max_epi16) + +inline int v_reduce_sum(const v_int16x32& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline uint v_reduce_sum(const v_uint16x32& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_64(sctype, func, _Tpvec, ifunc) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { __m256i half = _mm256_##ifunc(_v512_extract_low(a.val), _v512_extract_high(a.val)); \ + __m128i quarter = _mm_##ifunc(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 8)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 4)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 2)); \ + quarter = _mm_##ifunc(quarter, _mm_srli_si128(quarter, 1)); \ + return (sctype)_mm_cvtsi128_si32(quarter); } +OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, min, v_uint8x64, min_epu8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64(uchar, max, v_uint8x64, max_epu8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, min, v_int8x64, min_epi8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64(schar, max, v_int8x64, max_epi8) + +#define OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(sctype, _Tpvec, suffix) \ + inline sctype v_reduce_sum(const _Tpvec& a) \ + { __m512i a16 = _mm512_add_epi16(_mm512_cvt##suffix##_epi16(_v512_extract_low(a.val)), \ + _mm512_cvt##suffix##_epi16(_v512_extract_high(a.val))); \ + a16 = _mm512_cvtepi16_epi32(_mm256_add_epi16(_v512_extract_low(a16), _v512_extract_high(a16))); \ + __m256i a8 = _mm256_add_epi32(_v512_extract_low(a16), _v512_extract_high(a16)); \ + __m128i a4 = _mm_add_epi32(_mm256_castsi256_si128(a8), _mm256_extracti128_si256(a8, 1)); \ + a4 = _mm_hadd_epi32(a4, a4); \ + return (sctype)_mm_cvtsi128_si32(_mm_hadd_epi32(a4, a4)); } +OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(uint, v_uint8x64, epu8) +OPENCV_HAL_IMPL_AVX512_REDUCE_64_SUM(int, v_int8x64, epi8) + +inline v_float32x16 v_reduce_sum4(const v_float32x16& a, const v_float32x16& b, + const v_float32x16& c, const v_float32x16& d) +{ + __m256 abl = _mm256_hadd_ps(_v512_extract_low(a.val), _v512_extract_low(b.val)); + __m256 abh = _mm256_hadd_ps(_v512_extract_high(a.val), _v512_extract_high(b.val)); + __m256 cdl = _mm256_hadd_ps(_v512_extract_low(c.val), _v512_extract_low(d.val)); + __m256 cdh = _mm256_hadd_ps(_v512_extract_high(c.val), _v512_extract_high(d.val)); + return v_float32x16(_v512_combine(_mm256_hadd_ps(abl, cdl), _mm256_hadd_ps(abh, cdh))); +} + +inline unsigned v_reduce_sad(const v_uint8x64& a, const v_uint8x64& b) +{ + __m512i val = _mm512_sad_epu8(a.val, b.val); + __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); + __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_int8x64& a, const v_int8x64& b) +{ + __m512i val = _mm512_set1_epi8(-128); + val = _mm512_sad_epu8(_mm512_add_epi8(a.val, val), _mm512_add_epi8(b.val, val)); + __m256i half = _mm256_add_epi32(_v512_extract_low(val), _v512_extract_high(val)); + __m128i quarter = _mm_add_epi32(_mm256_castsi256_si128(half), _mm256_extracti128_si256(half, 1)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(quarter, _mm_unpackhi_epi64(quarter, quarter))); +} +inline unsigned v_reduce_sad(const v_uint16x32& a, const v_uint16x32& b) +{ return v_reduce_sum(v_add_wrap(v_sub(a, b), v_sub(b, a))); } +inline unsigned v_reduce_sad(const v_int16x32& a, const v_int16x32& b) +{ return v_reduce_sum(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b)))); } +inline unsigned v_reduce_sad(const v_uint32x16& a, const v_uint32x16& b) +{ return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); } +inline unsigned v_reduce_sad(const v_int32x16& a, const v_int32x16& b) +{ return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b)))); } +inline float v_reduce_sad(const v_float32x16& a, const v_float32x16& b) +{ return v_reduce_sum(v_and(v_sub(a, b), v_float32x16(_mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff))))); } +inline double v_reduce_sad(const v_float64x8& a, const v_float64x8& b) +{ return v_reduce_sum(v_and(v_sub(a, b), v_float64x8(_mm512_castsi512_pd(_mm512_set1_epi64(0x7fffffffffffffff))))); } + +/** Popcount **/ +inline v_uint8x64 v_popcount(const v_int8x64& a) +{ +#if CV_AVX_512BITALG + return v_uint8x64(_mm512_popcnt_epi8(a.val)); +#elif CV_AVX_512VBMI + __m512i _popcnt_table0 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1, + 4, 3, 3, 2, 3, 2, 2, 1, 3, 2, 2, 1, 2, 1, 1, 0); + __m512i _popcnt_table1 = _v512_set_epu8(7, 6, 6, 5, 6, 5, 5, 4, 6, 5, 5, 4, 5, 4, 4, 3, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 6, 5, 5, 4, 5, 4, 4, 3, 5, 4, 4, 3, 4, 3, 3, 2, + 5, 4, 4, 3, 4, 3, 3, 2, 4, 3, 3, 2, 3, 2, 2, 1); + return v_uint8x64(_mm512_sub_epi8(_mm512_permutex2var_epi8(_popcnt_table0, a.val, _popcnt_table1), _mm512_movm_epi8(_mm512_movepi8_mask(a.val)))); +#else + __m512i _popcnt_table = _mm512_set4_epi32(0x04030302, 0x03020201, 0x03020201, 0x02010100); + __m512i _popcnt_mask = _mm512_set1_epi8(0x0F); + + return v_uint8x64(_mm512_add_epi8(_mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512( a.val, _popcnt_mask)), + _mm512_shuffle_epi8(_popcnt_table, _mm512_and_si512(_mm512_srli_epi16(a.val, 4), _popcnt_mask)))); +#endif +} +inline v_uint16x32 v_popcount(const v_int16x32& a) +{ +#if CV_AVX_512BITALG + return v_uint16x32(_mm512_popcnt_epi16(a.val)); +#elif CV_AVX_512VPOPCNTDQ + __m512i zero = _mm512_setzero_si512(); + return v_uint16x32(_mm512_packs_epi32(_mm512_popcnt_epi32(_mm512_unpacklo_epi16(a.val, zero)), + _mm512_popcnt_epi32(_mm512_unpackhi_epi16(a.val, zero)))); +#else + v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v512_setall_u16(0x00ff)); +#endif +} +inline v_uint32x16 v_popcount(const v_int32x16& a) +{ +#if CV_AVX_512VPOPCNTDQ + return v_uint32x16(_mm512_popcnt_epi32(a.val)); +#else + v_uint8x64 p = v_popcount(v_reinterpret_as_s8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v512_setall_u32(0x000000ff)); +#endif +} +inline v_uint64x8 v_popcount(const v_int64x8& a) +{ +#if CV_AVX_512VPOPCNTDQ + return v_uint64x8(_mm512_popcnt_epi64(a.val)); +#else + return v_uint64x8(_mm512_sad_epu8(v_popcount(v_reinterpret_as_s8(a)).val, _mm512_setzero_si512())); +#endif +} + + +inline v_uint8x64 v_popcount(const v_uint8x64& a) { return v_popcount(v_reinterpret_as_s8 (a)); } +inline v_uint16x32 v_popcount(const v_uint16x32& a) { return v_popcount(v_reinterpret_as_s16(a)); } +inline v_uint32x16 v_popcount(const v_uint32x16& a) { return v_popcount(v_reinterpret_as_s32(a)); } +inline v_uint64x8 v_popcount(const v_uint64x8& a) { return v_popcount(v_reinterpret_as_s64(a)); } + + +////////// Other math ///////// + +/** Some frequent operations **/ +#if CV_FMA3 +#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_fmadd_##suffix(a.val, b.val, c.val)); } +#else +#define OPENCV_HAL_IMPL_AVX512_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(_mm512_add_##suffix(_mm512_mul_##suffix(a.val, b.val), c.val)); } +#endif + +#define OPENCV_HAL_IMPL_AVX512_MISC(_Tpvec, suffix) \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(_mm512_sqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_AVX512_MULADD(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_MULADD(v_float64x8, pd) +OPENCV_HAL_IMPL_AVX512_MISC(v_float32x16, ps) +OPENCV_HAL_IMPL_AVX512_MISC(v_float64x8, pd) + +inline v_int32x16 v_fma(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) +{ return v_add(v_mul(a, b), c); } +inline v_int32x16 v_muladd(const v_int32x16& a, const v_int32x16& b, const v_int32x16& c) +{ return v_fma(a, b, c); } + +inline v_float32x16 v_invsqrt(const v_float32x16& x) +{ +#if CV_AVX_512ER + return v_float32x16(_mm512_rsqrt28_ps(x.val)); +#else + v_float32x16 half = v_mul(x, v512_setall_f32(0.5)); + v_float32x16 t = v_float32x16(_mm512_rsqrt14_ps(x.val)); + t = v_mul(t, v_sub(v512_setall_f32(1.5), v_mul(v_mul(t, t), half))); + return t; +#endif +} + +inline v_float64x8 v_invsqrt(const v_float64x8& x) +{ +#if CV_AVX_512ER + return v_float64x8(_mm512_rsqrt28_pd(x.val)); +#else + return v_div(v512_setall_f64(1.), v_sqrt(x)); +// v_float64x8 half = x * v512_setall_f64(0.5); +// v_float64x8 t = v_float64x8(_mm512_rsqrt14_pd(x.val)); +// t *= v512_setall_f64(1.5) - ((t * t) * half); +// t *= v512_setall_f64(1.5) - ((t * t) * half); +// return t; +#endif +} + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_AVX512_ABS(_Tpvec, _Tpuvec, suffix) \ + inline _Tpuvec v_abs(const _Tpvec& x) \ + { return _Tpuvec(_mm512_abs_##suffix(x.val)); } + +OPENCV_HAL_IMPL_AVX512_ABS(v_int8x64, v_uint8x64, epi8) +OPENCV_HAL_IMPL_AVX512_ABS(v_int16x32, v_uint16x32, epi16) +OPENCV_HAL_IMPL_AVX512_ABS(v_int32x16, v_uint32x16, epi32) +OPENCV_HAL_IMPL_AVX512_ABS(v_int64x8, v_uint64x8, epi64) + +inline v_float32x16 v_abs(const v_float32x16& x) +{ +#ifdef _mm512_abs_pd + return v_float32x16(_mm512_abs_ps(x.val)); +#else + return v_float32x16(_mm512_castsi512_ps(_mm512_and_si512(_mm512_castps_si512(x.val), + _v512_set_epu64(0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, + 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF, 0x7FFFFFFF7FFFFFFF)))); +#endif +} + +inline v_float64x8 v_abs(const v_float64x8& x) +{ +#ifdef _mm512_abs_pd + #if defined __GNUC__ && (__GNUC__ < 7 || (__GNUC__ == 7 && __GNUC_MINOR__ <= 3) || (__GNUC__ == 8 && __GNUC_MINOR__ <= 2)) + // Workaround for https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87476 + return v_float64x8(_mm512_abs_pd(_mm512_castpd_ps(x.val))); + #else + return v_float64x8(_mm512_abs_pd(x.val)); + #endif +#else + return v_float64x8(_mm512_castsi512_pd(_mm512_and_si512(_mm512_castpd_si512(x.val), + _v512_set_epu64(0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, + 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF)))); +#endif +} + +/** Absolute difference **/ +inline v_uint8x64 v_absdiff(const v_uint8x64& a, const v_uint8x64& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x32 v_absdiff(const v_uint16x32& a, const v_uint16x32& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x16 v_absdiff(const v_uint32x16& a, const v_uint32x16& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x64 v_absdiff(const v_int8x64& a, const v_int8x64& b) +{ + v_int8x64 d = v_sub_wrap(a, b); + v_int8x64 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} + +inline v_uint16x32 v_absdiff(const v_int16x32& a, const v_int16x32& b) +{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } + +inline v_uint32x16 v_absdiff(const v_int32x16& a, const v_int32x16& b) +{ + v_int32x16 d = v_sub(a, b); + v_int32x16 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +inline v_float32x16 v_absdiff(const v_float32x16& a, const v_float32x16& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x8 v_absdiff(const v_float64x8& a, const v_float64x8& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x64 v_absdiffs(const v_int8x64& a, const v_int8x64& b) +{ + v_int8x64 d = v_sub(a, b); + v_int8x64 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x32 v_absdiffs(const v_int16x32& a, const v_int16x32& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x16 v_round(const v_float32x16& a) +{ return v_int32x16(_mm512_cvtps_epi32(a.val)); } + +inline v_int32x16 v_round(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(a.val))); } + +inline v_int32x16 v_round(const v_float64x8& a, const v_float64x8& b) +{ return v_int32x16(_v512_combine(_mm512_cvtpd_epi32(a.val), _mm512_cvtpd_epi32(b.val))); } + +inline v_int32x16 v_trunc(const v_float32x16& a) +{ return v_int32x16(_mm512_cvttps_epi32(a.val)); } + +inline v_int32x16 v_trunc(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvttpd_epi32(a.val))); } + +#if CVT_ROUND_MODES_IMPLEMENTED +inline v_int32x16 v_floor(const v_float32x16& a) +{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC)); } + +inline v_int32x16 v_floor(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC))); } + +inline v_int32x16 v_ceil(const v_float32x16& a) +{ return v_int32x16(_mm512_cvt_roundps_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC)); } + +inline v_int32x16 v_ceil(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvt_roundpd_epi32(a.val, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC))); } +#else +inline v_int32x16 v_floor(const v_float32x16& a) +{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 1))); } + +inline v_int32x16 v_floor(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 1)))); } + +inline v_int32x16 v_ceil(const v_float32x16& a) +{ return v_int32x16(_mm512_cvtps_epi32(_mm512_roundscale_ps(a.val, 2))); } + +inline v_int32x16 v_ceil(const v_float64x8& a) +{ return v_int32x16(_mm512_castsi256_si512(_mm512_cvtpd_epi32(_mm512_roundscale_pd(a.val, 2)))); } +#endif + +/** To float **/ +inline v_float32x16 v_cvt_f32(const v_int32x16& a) +{ return v_float32x16(_mm512_cvtepi32_ps(a.val)); } + +inline v_float32x16 v_cvt_f32(const v_float64x8& a) +{ return v_float32x16(_mm512_cvtpd_pslo(a.val)); } + +inline v_float32x16 v_cvt_f32(const v_float64x8& a, const v_float64x8& b) +{ return v_float32x16(_v512_combine(_mm512_cvtpd_ps(a.val), _mm512_cvtpd_ps(b.val))); } + +inline v_float64x8 v_cvt_f64(const v_int32x16& a) +{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_low(a.val))); } + +inline v_float64x8 v_cvt_f64_high(const v_int32x16& a) +{ return v_float64x8(_mm512_cvtepi32_pd(_v512_extract_high(a.val))); } + +inline v_float64x8 v_cvt_f64(const v_float32x16& a) +{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_low(a.val))); } + +inline v_float64x8 v_cvt_f64_high(const v_float32x16& a) +{ return v_float64x8(_mm512_cvtps_pd(_v512_extract_high(a.val))); } + +// from (Mysticial and wim) https://stackoverflow.com/q/41144668 +inline v_float64x8 v_cvt_f64(const v_int64x8& v) +{ +#if CV_AVX_512DQ + return v_float64x8(_mm512_cvtepi64_pd(v.val)); +#else + // constants encoded as floating-point + __m512i magic_i_lo = _mm512_set1_epi64(0x4330000000000000); // 2^52 + __m512i magic_i_hi32 = _mm512_set1_epi64(0x4530000080000000); // 2^84 + 2^63 + __m512i magic_i_all = _mm512_set1_epi64(0x4530000080100000); // 2^84 + 2^63 + 2^52 + __m512d magic_d_all = _mm512_castsi512_pd(magic_i_all); + + // Blend the 32 lowest significant bits of v with magic_int_lo + __m512i v_lo = _mm512_mask_blend_epi32(0x5555, magic_i_lo, v.val); + // Extract the 32 most significant bits of v + __m512i v_hi = _mm512_srli_epi64(v.val, 32); + // Flip the msb of v_hi and blend with 0x45300000 + v_hi = _mm512_xor_si512(v_hi, magic_i_hi32); + // Compute in double precision + __m512d v_hi_dbl = _mm512_sub_pd(_mm512_castsi512_pd(v_hi), magic_d_all); + // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition + __m512d result = _mm512_add_pd(v_hi_dbl, _mm512_castsi512_pd(v_lo)); + return v_float64x8(result); +#endif +} + +////////////// Lookup table access //////////////////// + +inline v_int8x64 v512_lut(const schar* tab, const int* idx) +{ + __m128i p0 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); + __m128i p1 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); + __m128i p2 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 2), (const int *)tab, 1)); + __m128i p3 = _mm512_cvtepi32_epi8(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 3), (const int *)tab, 1)); + return v_int8x64(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512(p0), p1, 1), p2, 2), p3, 3)); +} +inline v_int8x64 v512_lut_pairs(const schar* tab, const int* idx) +{ + __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 1)); + __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 1)); + return v_int8x64(_v512_combine(p0, p1)); +} +inline v_int8x64 v512_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x64(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 1)); +} +inline v_uint8x64 v512_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut((const schar *)tab, idx)); } +inline v_uint8x64 v512_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x64 v512_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v512_lut_quads((const schar *)tab, idx)); } + +inline v_int16x32 v512_lut(const short* tab, const int* idx) +{ + __m256i p0 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx ), (const int *)tab, 2)); + __m256i p1 = _mm512_cvtepi32_epi16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx + 1), (const int *)tab, 2)); + return v_int16x32(_v512_combine(p0, p1)); +} +inline v_int16x32 v512_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x32(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), (const int *)tab, 2)); +} +inline v_int16x32 v512_lut_quads(const short* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 2)); +#else + return v_int16x32(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 2)); +#endif +} +inline v_uint16x32 v512_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut((const short *)tab, idx)); } +inline v_uint16x32 v512_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_pairs((const short *)tab, idx)); } +inline v_uint16x32 v512_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v512_lut_quads((const short *)tab, idx)); } + +inline v_int32x16 v512_lut(const int* tab, const int* idx) +{ + return v_int32x16(_mm512_i32gather_epi32(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); +} +inline v_int32x16 v512_lut_pairs(const int* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 4)); +#else + return v_int32x16(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const int64*)tab, 4)); +#endif +} +inline v_int32x16 v512_lut_quads(const int* tab, const int* idx) +{ + return v_int32x16(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( + _mm_loadu_si128((const __m128i*)(tab + idx[0]))), + _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), + _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), + _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); +} +inline v_uint32x16 v512_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut((const int *)tab, idx)); } +inline v_uint32x16 v512_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_pairs((const int *)tab, idx)); } +inline v_uint32x16 v512_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v512_lut_quads((const int *)tab, idx)); } + +inline v_int64x8 v512_lut(const int64* tab, const int* idx) +{ +#if defined(__GNUC__) + return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), (const long long int*)tab, 8)); +#else + return v_int64x8(_mm512_i32gather_epi64(_mm256_loadu_si256((const __m256i*)idx), tab , 8)); +#endif +} +inline v_int64x8 v512_lut_pairs(const int64* tab, const int* idx) +{ + return v_int64x8(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_castsi128_si512( + _mm_loadu_si128((const __m128i*)(tab + idx[0]))), + _mm_loadu_si128((const __m128i*)(tab + idx[1])), 1), + _mm_loadu_si128((const __m128i*)(tab + idx[2])), 2), + _mm_loadu_si128((const __m128i*)(tab + idx[3])), 3)); +} +inline v_uint64x8 v512_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut((const int64 *)tab, idx)); } +inline v_uint64x8 v512_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v512_lut_pairs((const int64 *)tab, idx)); } + +inline v_float32x16 v512_lut(const float* tab, const int* idx) +{ + return v_float32x16(_mm512_i32gather_ps(_mm512_loadu_si512((const __m512i*)idx), tab, 4)); +} +inline v_float32x16 v512_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_pairs((const int *)tab, idx)); } +inline v_float32x16 v512_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v512_lut_quads((const int *)tab, idx)); } + +inline v_float64x8 v512_lut(const double* tab, const int* idx) +{ + return v_float64x8(_mm512_i32gather_pd(_mm256_loadu_si256((const __m256i*)idx), tab, 8)); +} +inline v_float64x8 v512_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x8(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_insertf64x2(_mm512_castpd128_pd512( + _mm_loadu_pd(tab + idx[0])), + _mm_loadu_pd(tab + idx[1]), 1), + _mm_loadu_pd(tab + idx[2]), 2), + _mm_loadu_pd(tab + idx[3]), 3)); +} + +inline v_int32x16 v_lut(const int* tab, const v_int32x16& idxvec) +{ + return v_int32x16(_mm512_i32gather_epi32(idxvec.val, tab, 4)); +} + +inline v_uint32x16 v_lut(const unsigned* tab, const v_int32x16& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x16 v_lut(const float* tab, const v_int32x16& idxvec) +{ + return v_float32x16(_mm512_i32gather_ps(idxvec.val, tab, 4)); +} + +inline v_float64x8 v_lut(const double* tab, const v_int32x16& idxvec) +{ + return v_float64x8(_mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8)); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x16& idxvec, v_float32x16& x, v_float32x16& y) +{ + x.val = _mm512_i32gather_ps(idxvec.val, tab, 4); + y.val = _mm512_i32gather_ps(idxvec.val, &tab[1], 4); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x16& idxvec, v_float64x8& x, v_float64x8& y) +{ + x.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), tab, 8); + y.val = _mm512_i32gather_pd(_v512_extract_low(idxvec.val), &tab[1], 8); +} + +inline v_int8x64 v_interleave_pairs(const v_int8x64& vec) +{ + return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0d0e0c, 0x0b090a08, 0x07050604, 0x03010200))); +} +inline v_uint8x64 v_interleave_pairs(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x64 v_interleave_quads(const v_int8x64& vec) +{ + return v_int8x64(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0b0e0a, 0x0d090c08, 0x07030602, 0x05010400))); +} +inline v_uint8x64 v_interleave_quads(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x32 v_interleave_pairs(const v_int16x32& vec) +{ + return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0b0a, 0x0d0c0908, 0x07060302, 0x05040100))); +} +inline v_uint16x32 v_interleave_pairs(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x32 v_interleave_quads(const v_int16x32& vec) +{ + return v_int16x32(_mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0x0f0e0706, 0x0d0c0504, 0x0b0a0302, 0x09080100))); +} +inline v_uint16x32 v_interleave_quads(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x16 v_interleave_pairs(const v_int32x16& vec) +{ + return v_int32x16(_mm512_shuffle_epi32(vec.val, _MM_PERM_ACBD)); +} +inline v_uint32x16 v_interleave_pairs(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x16 v_interleave_pairs(const v_float32x16& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x64 v_pack_triplets(const v_int8x64& vec) +{ + return v_int8x64(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, + 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), + _mm512_shuffle_epi8(vec.val, _mm512_set4_epi32(0xffffff0f, 0x0e0d0c0a, 0x09080605, 0x04020100)))); +} +inline v_uint8x64 v_pack_triplets(const v_uint8x64& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x32 v_pack_triplets(const v_int16x32& vec) +{ + return v_int16x32(_mm512_permutexvar_epi16(_v512_set_epu64(0x001f001f001f001f, 0x001f001f001f001f, 0x001e001d001c001a, 0x0019001800160015, + 0x0014001200110010, 0x000e000d000c000a, 0x0009000800060005, 0x0004000200010000), vec.val)); +} +inline v_uint16x32 v_pack_triplets(const v_uint16x32& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x16 v_pack_triplets(const v_int32x16& vec) +{ + return v_int32x16(_mm512_permutexvar_epi32(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, + 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); +} +inline v_uint32x16 v_pack_triplets(const v_uint32x16& vec) { return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } +inline v_float32x16 v_pack_triplets(const v_float32x16& vec) +{ + return v_float32x16(_mm512_permutexvar_ps(_v512_set_epu64(0x0000000f0000000f, 0x0000000f0000000f, 0x0000000e0000000d, 0x0000000c0000000a, + 0x0000000900000008, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000), vec.val)); +} + +////////// Matrix operations ///////// + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b) +{ return v_int32x16(_mm512_madd_epi16(a.val, b.val)); } +inline v_int32x16 v_dotprod(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b) +{ + __m512i even = _mm512_mul_epi32(a.val, b.val); + __m512i odd = _mm512_mul_epi32(_mm512_srli_epi64(a.val, 32), _mm512_srli_epi64(b.val, 32)); + return v_int64x8(_mm512_add_epi64(even, odd)); +} +inline v_int64x8 v_dotprod(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b) +{ + __m512i even_a = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, _mm512_setzero_si512()); + __m512i odd_a = _mm512_srli_epi16(a.val, 8); + + __m512i even_b = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b.val, _mm512_setzero_si512()); + __m512i odd_b = _mm512_srli_epi16(b.val, 8); + + __m512i prod0 = _mm512_madd_epi16(even_a, even_b); + __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); + return v_uint32x16(_mm512_add_epi32(prod0, prod1)); +} +inline v_uint32x16 v_dotprod_expand(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b) +{ + __m512i even_a = _mm512_srai_epi16(_mm512_bslli_epi128(a.val, 1), 8); + __m512i odd_a = _mm512_srai_epi16(a.val, 8); + + __m512i even_b = _mm512_srai_epi16(_mm512_bslli_epi128(b.val, 1), 8); + __m512i odd_b = _mm512_srai_epi16(b.val, 8); + + __m512i prod0 = _mm512_madd_epi16(even_a, even_b); + __m512i prod1 = _mm512_madd_epi16(odd_a, odd_b); + return v_int32x16(_mm512_add_epi32(prod0, prod1)); +} +inline v_int32x16 v_dotprod_expand(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b) +{ + __m512i mullo = _mm512_mullo_epi16(a.val, b.val); + __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); + __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); + __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); + + __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); + __m512i p13 = _mm512_srli_epi64(mul0, 32); + __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); + __m512i p57 = _mm512_srli_epi64(mul1, 32); + + __m512i p15_ = _mm512_add_epi64(p02, p13); + __m512i p9d_ = _mm512_add_epi64(p46, p57); + + return v_uint64x8(_mm512_add_epi64( + _mm512_unpacklo_epi64(p15_, p9d_), + _mm512_unpackhi_epi64(p15_, p9d_) + )); +} +inline v_uint64x8 v_dotprod_expand(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b) +{ + __m512i prod = _mm512_madd_epi16(a.val, b.val); + __m512i even = _mm512_srai_epi64(_mm512_bslli_epi128(prod, 4), 32); + __m512i odd = _mm512_srai_epi64(prod, 32); + return v_int64x8(_mm512_add_epi64(even, odd)); +} +inline v_int64x8 v_dotprod_expand(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x8 v_dotprod_expand(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b) +{ return v_dotprod(a, b); } +inline v_int32x16 v_dotprod_fast(const v_int16x32& a, const v_int16x32& b, const v_int32x16& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b) +{ return v_dotprod(a, b); } +inline v_int64x8 v_dotprod_fast(const v_int32x16& a, const v_int32x16& b, const v_int64x8& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x16 v_dotprod_expand_fast(const v_uint8x64& a, const v_uint8x64& b, const v_uint32x16& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x16 v_dotprod_expand_fast(const v_int8x64& a, const v_int8x64& b, const v_int32x16& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b) +{ + __m512i mullo = _mm512_mullo_epi16(a.val, b.val); + __m512i mulhi = _mm512_mulhi_epu16(a.val, b.val); + __m512i mul0 = _mm512_unpacklo_epi16(mullo, mulhi); + __m512i mul1 = _mm512_unpackhi_epi16(mullo, mulhi); + + __m512i p02 = _mm512_mask_blend_epi32(0xAAAA, mul0, _mm512_setzero_si512()); + __m512i p13 = _mm512_srli_epi64(mul0, 32); + __m512i p46 = _mm512_mask_blend_epi32(0xAAAA, mul1, _mm512_setzero_si512()); + __m512i p57 = _mm512_srli_epi64(mul1, 32); + + __m512i p15_ = _mm512_add_epi64(p02, p13); + __m512i p9d_ = _mm512_add_epi64(p46, p57); + return v_uint64x8(_mm512_add_epi64(p15_, p9d_)); +} +inline v_uint64x8 v_dotprod_expand_fast(const v_uint16x32& a, const v_uint16x32& b, const v_uint64x8& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b) +{ return v_dotprod_expand(a, b); } +inline v_int64x8 v_dotprod_expand_fast(const v_int16x32& a, const v_int16x32& b, const v_int64x8& c) +{ return v_dotprod_expand(a, b, c); } + +// 32 >> 64f +inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x8 v_dotprod_expand_fast(const v_int32x16& a, const v_int32x16& b, const v_float64x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + + +#define OPENCV_HAL_AVX512_SPLAT2_PS(a, im) \ + v_float32x16(_mm512_permute_ps(a.val, _MM_SHUFFLE(im, im, im, im))) + +inline v_float32x16 v_matmul(const v_float32x16& v, + const v_float32x16& m0, const v_float32x16& m1, + const v_float32x16& m2, const v_float32x16& m3) +{ + v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); + v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); + v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); + v_float32x16 v37 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 3); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); +} + +inline v_float32x16 v_matmuladd(const v_float32x16& v, + const v_float32x16& m0, const v_float32x16& m1, + const v_float32x16& m2, const v_float32x16& a) +{ + v_float32x16 v04 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 0); + v_float32x16 v15 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 1); + v_float32x16 v26 = OPENCV_HAL_AVX512_SPLAT2_PS(v, 2); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); +} + +#define OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m512i t0 = cast_from(_mm512_unpacklo_##suffix(a0.val, a1.val)); \ + __m512i t1 = cast_from(_mm512_unpacklo_##suffix(a2.val, a3.val)); \ + __m512i t2 = cast_from(_mm512_unpackhi_##suffix(a0.val, a1.val)); \ + __m512i t3 = cast_from(_mm512_unpackhi_##suffix(a2.val, a3.val)); \ + b0.val = cast_to(_mm512_unpacklo_epi64(t0, t1)); \ + b1.val = cast_to(_mm512_unpackhi_epi64(t0, t1)); \ + b2.val = cast_to(_mm512_unpacklo_epi64(t2, t3)); \ + b3.val = cast_to(_mm512_unpackhi_epi64(t2, t3)); \ + } + +OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_uint32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_int32x16, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_AVX512_TRANSPOSE4x4(v_float32x16, ps, _mm512_castps_si512, _mm512_castsi512_ps) + +//////////////// Value reordering /////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_AVX512_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(_v512_extract_low(a.val)); \ + b1.val = intrin(_v512_extract_high(a.val)); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v512_extract_low(a.val))); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin(_v512_extract_high(a.val))); } \ + inline _Tpwvec v512_load_expand(const _Tp* ptr) \ + { \ + __m256i a = _mm256_loadu_si256((const __m256i*)ptr); \ + return _Tpwvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint8x64, v_uint16x32, uchar, _mm512_cvtepu8_epi16) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_int8x64, v_int16x32, schar, _mm512_cvtepi8_epi16) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint16x32, v_uint32x16, ushort, _mm512_cvtepu16_epi32) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_int16x32, v_int32x16, short, _mm512_cvtepi16_epi32) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_uint32x16, v_uint64x8, unsigned, _mm512_cvtepu32_epi64) +OPENCV_HAL_IMPL_AVX512_EXPAND(v_int32x16, v_int64x8, int, _mm512_cvtepi32_epi64) + +#define OPENCV_HAL_IMPL_AVX512_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v512_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadu_si128((const __m128i*)ptr); \ + return _Tpvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_uint32x16, uchar, _mm512_cvtepu8_epi32) +OPENCV_HAL_IMPL_AVX512_EXPAND_Q(v_int32x16, schar, _mm512_cvtepi8_epi32) + +/* pack */ +// 16 +inline v_int8x64 v_pack(const v_int16x32& a, const v_int16x32& b) +{ return v_int8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } + +inline v_uint8x64 v_pack(const v_uint16x32& a, const v_uint16x32& b) +{ + const __m512i t = _mm512_set1_epi16(255); + return v_uint8x64(_v512_combine(_mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, t)), _mm512_cvtepi16_epi8(_mm512_min_epu16(b.val, t)))); +} + +inline v_uint8x64 v_pack_u(const v_int16x32& a, const v_int16x32& b) +{ + return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi16(a.val, b.val))); +} + +inline void v_pack_store(schar* ptr, const v_int16x32& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar* ptr, const v_uint16x32& a) +{ + const __m512i m = _mm512_set1_epi16(255); + _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi16_epi8(_mm512_min_epu16(a.val, m))); +} + +inline void v_pack_u_store(uchar* ptr, const v_int16x32& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x64 v_rshr_pack(const v_uint16x32& a, const v_uint16x32& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); + return v_pack_u(v_reinterpret_as_s16(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s16(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x32& a) +{ + v_uint16x32 delta = v512_setall_u16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_reinterpret_as_s16(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint8x64 v_rshr_pack_u(const v_int16x32& a, const v_int16x32& b) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x32& a) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int8x64 v_rshr_pack(const v_int16x32& a, const v_int16x32& b) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x32& a) +{ + v_int16x32 delta = v512_setall_s16((short)(1 << (n-1))); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 32 +inline v_int16x32 v_pack(const v_int32x16& a, const v_int32x16& b) +{ return v_int16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi32(a.val, b.val))); } + +inline v_uint16x32 v_pack(const v_uint32x16& a, const v_uint32x16& b) +{ + const __m512i m = _mm512_set1_epi32(65535); + return v_uint16x32(_v512_combine(_mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m)), _mm512_cvtepi32_epi16(_mm512_min_epu32(b.val, m)))); +} + +inline v_uint16x32 v_pack_u(const v_int32x16& a, const v_int32x16& b) +{ return v_uint16x32(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packus_epi32(a.val, b.val))); } + +inline void v_pack_store(short* ptr, const v_int32x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x16& a) +{ + const __m512i m = _mm512_set1_epi32(65535); + _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi32_epi16(_mm512_min_epu32(a.val, m))); +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x16& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + + +template inline +v_uint16x32 v_rshr_pack(const v_uint32x16& a, const v_uint32x16& b) +{ + v_uint32x16 delta = v512_setall_u32(1 << (n-1)); + return v_pack_u(v_reinterpret_as_s32(v_shr(v_add(a, delta), n)), + v_reinterpret_as_s32(v_shr(v_add(b, delta), n))); +} + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x16& a) +{ + v_uint32x16 delta = v512_setall_u32(1 << (n-1)); + v_pack_u_store(ptr, v_reinterpret_as_s32(v_shr(v_add(a, delta), n))); +} + +template inline +v_uint16x32 v_rshr_pack_u(const v_int32x16& a, const v_int32x16& b) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + return v_pack_u(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x16& a) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + v_pack_u_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int16x32 v_rshr_pack(const v_int32x16& a, const v_int32x16& b) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x16& a) +{ + v_int32x16 delta = v512_setall_s32(1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// 64 +// Non-saturating pack +inline v_uint32x16 v_pack(const v_uint64x8& a, const v_uint64x8& b) +{ return v_uint32x16(_v512_combine(_mm512_cvtepi64_epi32(a.val), _mm512_cvtepi64_epi32(b.val))); } + +inline v_int32x16 v_pack(const v_int64x8& a, const v_int64x8& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x8& a) +{ _mm256_storeu_si256((__m256i*)ptr, _mm512_cvtepi64_epi32(a.val)); } + +inline void v_pack_store(int* ptr, const v_int64x8& b) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } + +template inline +v_uint32x16 v_rshr_pack(const v_uint64x8& a, const v_uint64x8& b) +{ + v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x8& a) +{ + v_uint64x8 delta = v512_setall_u64((uint64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +template inline +v_int32x16 v_rshr_pack(const v_int64x8& a, const v_int64x8& b) +{ + v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); + return v_pack(v_shr(v_add(a, delta), n), v_shr(v_add(b, delta), n)); +} + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x8& a) +{ + v_int64x8 delta = v512_setall_s64((int64)1 << (n-1)); + v_pack_store(ptr, v_shr(v_add(a, delta), n)); +} + +// pack boolean +inline v_uint8x64 v_pack_b(const v_uint16x32& a, const v_uint16x32& b) +{ return v_uint8x64(_mm512_permutexvar_epi64(_v512_set_epu64(7, 5, 3, 1, 6, 4, 2, 0), _mm512_packs_epi16(a.val, b.val))); } + +inline v_uint8x64 v_pack_b(const v_uint32x16& a, const v_uint32x16& b, + const v_uint32x16& c, const v_uint32x16& d) +{ + __m512i ab = _mm512_packs_epi32(a.val, b.val); + __m512i cd = _mm512_packs_epi32(c.val, d.val); + + return v_uint8x64(_mm512_permutexvar_epi32(_v512_set_epu32(15, 11, 7, 3, 14, 10, 6, 2, 13, 9, 5, 1, 12, 8, 4, 0), _mm512_packs_epi16(ab, cd))); +} + +inline v_uint8x64 v_pack_b(const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, + const v_uint64x8& d, const v_uint64x8& e, const v_uint64x8& f, + const v_uint64x8& g, const v_uint64x8& h) +{ + __m512i ab = _mm512_packs_epi32(a.val, b.val); + __m512i cd = _mm512_packs_epi32(c.val, d.val); + __m512i ef = _mm512_packs_epi32(e.val, f.val); + __m512i gh = _mm512_packs_epi32(g.val, h.val); + + __m512i abcd = _mm512_packs_epi32(ab, cd); + __m512i efgh = _mm512_packs_epi32(ef, gh); + + return v_uint8x64(_mm512_permutexvar_epi16(_v512_set_epu16(31, 23, 15, 7, 30, 22, 14, 6, 29, 21, 13, 5, 28, 20, 12, 4, + 27, 19, 11, 3, 26, 18, 10, 2, 25, 17, 9, 1, 24, 16, 8, 0), _mm512_packs_epi16(abcd, efgh))); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_AVX512_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint8x64) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int8x64) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint16x32) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int16x32) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint32x16) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int32x16) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_uint64x8) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_int64x8) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float32x16) +OPENCV_HAL_IMPL_AVX512_EXTRACT(v_float64x8) + +#define OPENCV_HAL_IMPL_AVX512_EXTRACT_N(_Tpvec, _Tp) \ +template inline _Tp v_extract_n(_Tpvec v) { return v_rotate_right(v).get0(); } + +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint8x64, uchar) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int8x64, schar) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint16x32, ushort) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int16x32, short) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint32x16, uint) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int32x16, int) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_uint64x8, uint64) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_int64x8, int64) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float32x16, float) +OPENCV_HAL_IMPL_AVX512_EXTRACT_N(v_float64x8, double) + +template +inline v_uint32x16 v_broadcast_element(v_uint32x16 a) +{ + static const __m512i perm = _mm512_set1_epi32((char)i); + return v_uint32x16(_mm512_permutexvar_epi32(perm, a.val)); +} + +template +inline v_int32x16 v_broadcast_element(const v_int32x16 &a) +{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +template +inline v_float32x16 v_broadcast_element(const v_float32x16 &a) +{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } + + +///////////////////// load deinterleave ///////////////////////////// + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, + 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, + 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, + 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, + 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask0, ab1)); + b = v_uint8x64(_mm512_permutex2var_epi8(ab0, mask1, ab1)); +#else + __m512i mask0 = _mm512_set4_epi32(0x0f0d0b09, 0x07050301, 0x0e0c0a08, 0x06040200); + __m512i a0b0 = _mm512_shuffle_epi8(ab0, mask0); + __m512i a1b1 = _mm512_shuffle_epi8(ab1, mask0); + __m512i mask1 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask2 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask1, a1b1)); + b = v_uint8x64(_mm512_permutex2var_epi64(a0b0, mask2, a1b1)); +#endif +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask0, ab1)); + b = v_uint16x32(_mm512_permutex2var_epi16(ab0, mask1, ab1)); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask0, ab1)); + b = v_uint32x16(_mm512_permutex2var_epi32(ab0, mask1, ab1)); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b ) +{ + __m512i ab0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i ab1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); + __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); + a = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask0, ab1)); + b = v_uint64x8(_mm512_permutex2var_epi64(ab0, mask1, ab1)); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); + +#if CV_AVX_512VBMI2 + __m512i mask0 = _v512_set_epu8(126, 123, 120, 117, 114, 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, + 78, 75, 72, 69, 66, 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, + 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, 62, 59, 56, 53, 50, + 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2); + __m512i r0b01 = _mm512_permutex2var_epi8(bgr0, mask0, bgr1); + __m512i b1g12 = _mm512_permutex2var_epi8(bgr1, mask0, bgr2); + __m512i r12b2 = _mm512_permutex2var_epi8(bgr1, + _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, + 77, 74, 71, 68, 65, 127, 124, 121, 118, 115, 112, 109, 106, 103, 100, 97, + 94, 91, 88, 85, 82, 79, 76, 73, 70, 67, 64, 61, 58, 55, 52, 49, + 46, 43, 40, 37, 34, 31, 28, 25, 22, 19, 16, 13, 10, 7, 4, 1), bgr2); + a = v_uint8x64(_mm512_mask_compress_epi8(r12b2, 0xffffffffffe00000, r0b01)); + b = v_uint8x64(_mm512_mask_compress_epi8(b1g12, 0x2492492492492492, bgr0)); + c = v_uint8x64(_mm512_mask_expand_epi8(r0b01, 0xffffffffffe00000, r12b2)); +#elif CV_AVX_512VBMI + __m512i b0g0b1 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr1, bgr0); + __m512i g1r1g2 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr2, bgr1); + __m512i r2b2r0 = _mm512_mask_blend_epi8(0xb6db6db6db6db6db, bgr0, bgr2); + a = v_uint8x64(_mm512_permutex2var_epi8(b0g0b1, _v512_set_epu8(125, 122, 119, 116, 113, 110, 107, 104, 101, 98, 95, 92, 89, 86, 83, 80, + 77, 74, 71, 68, 65, 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, + 46, 45, 43, 42, 40, 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, + 23, 21, 20, 18, 17, 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0), bgr2)); + b = v_uint8x64(_mm512_permutex2var_epi8(g1r1g2, _v512_set_epu8( 63, 61, 60, 58, 57, 55, 54, 52, 51, 49, 48, 46, 45, 43, 42, 40, + 39, 37, 36, 34, 33, 31, 30, 28, 27, 25, 24, 23, 21, 20, 18, 17, + 15, 14, 12, 11, 9, 8, 6, 5, 3, 2, 0, 126, 123, 120, 117, 114, + 111, 108, 105, 102, 99, 96, 93, 90, 87, 84, 81, 78, 75, 72, 69, 66), bgr0)); + c = v_uint8x64(_mm512_permutex2var_epi8(r2b2r0, _v512_set_epu8( 63, 60, 57, 54, 51, 48, 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, + 15, 12, 9, 6, 3, 0, 125, 122, 119, 116, 113, 110, 107, 104, 101, 98, + 95, 92, 89, 86, 83, 80, 77, 74, 71, 68, 65, 62, 59, 56, 53, 50, + 47, 44, 41, 38, 35, 32, 29, 26, 23, 20, 17, 14, 11, 8, 5, 2), bgr1)); +#else + __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, + 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); + __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); + __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); + __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); + + __m512i b0g0 = _mm512_mask_blend_epi32(0xf800, b01g1, r12b2); + __m512i r0b1 = _mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, + 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0); + __m512i g1r1 = _mm512_alignr_epi32(r12b2, g20r0, 11); + a = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, b0g0, r0b1)); + c = v_uint8x64(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, r0b1, g1r1)); + b = v_uint8x64(_mm512_shuffle_epi8(_mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1r1, b0g0), _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001))); +#endif +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + + __m512i mask0 = _v512_set_epu16(61, 58, 55, 52, 49, 46, 43, 40, 37, 34, 63, 60, 57, 54, 51, 48, + 45, 42, 39, 36, 33, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); + __m512i b01g1 = _mm512_permutex2var_epi16(bgr0, mask0, bgr1); + __m512i r12b2 = _mm512_permutex2var_epi16(bgr1, mask0, bgr2); + __m512i g20r0 = _mm512_permutex2var_epi16(bgr2, mask0, bgr0); + + a = v_uint16x32(_mm512_mask_blend_epi32(0xf800, b01g1, r12b2)); + b = v_uint16x32(_mm512_permutex2var_epi16(bgr1, _v512_set_epu16(42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 29, 26, 23, 20, 17, + 14, 11, 8, 5, 2, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43), g20r0)); + c = v_uint16x32(_mm512_alignr_epi32(r12b2, g20r0, 11)); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + + __m512i mask0 = _v512_set_epu32(29, 26, 23, 20, 17, 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0); + __m512i b01r1 = _mm512_permutex2var_epi32(bgr0, mask0, bgr1); + __m512i g12b2 = _mm512_permutex2var_epi32(bgr1, mask0, bgr2); + __m512i r20g0 = _mm512_permutex2var_epi32(bgr2, mask0, bgr0); + + a = v_uint32x16(_mm512_mask_blend_epi32(0xf800, b01r1, g12b2)); + b = v_uint32x16(_mm512_alignr_epi32(g12b2, r20g0, 11)); + c = v_uint32x16(_mm512_permutex2var_epi32(bgr1, _v512_set_epu32(21, 20, 19, 18, 17, 16, 13, 10, 7, 4, 1, 26, 25, 24, 23, 22), r20g0)); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c ) +{ + __m512i bgr0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgr1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); + __m512i bgr2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + + __m512i mask0 = _v512_set_epu64(13, 10, 15, 12, 9, 6, 3, 0); + __m512i b01g1 = _mm512_permutex2var_epi64(bgr0, mask0, bgr1); + __m512i r12b2 = _mm512_permutex2var_epi64(bgr1, mask0, bgr2); + __m512i g20r0 = _mm512_permutex2var_epi64(bgr2, mask0, bgr0); + + a = v_uint64x8(_mm512_mask_blend_epi64(0xc0, b01g1, r12b2)); + c = v_uint64x8(_mm512_alignr_epi64(r12b2, g20r0, 6)); + b = v_uint64x8(_mm512_permutex2var_epi64(bgr1, _v512_set_epu64(10, 9, 8, 5, 2, 13, 12, 11), g20r0)); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x64& a, v_uint8x64& b, v_uint8x64& c, v_uint8x64& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 128)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 192)); + +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8(126, 124, 122, 120, 118, 116, 114, 112, 110, 108, 106, 104, 102, 100, 98, 96, + 94, 92, 90, 88, 86, 84, 82, 80, 78, 76, 74, 72, 70, 68, 66, 64, + 62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu8(127, 125, 123, 121, 119, 117, 115, 113, 111, 109, 107, 105, 103, 101, 99, 97, + 95, 93, 91, 89, 87, 85, 83, 81, 79, 77, 75, 73, 71, 69, 67, 65, + 63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi8(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi8(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi8(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi8(bgra2, mask1, bgra3); + + a = v_uint8x64(_mm512_permutex2var_epi8(br01, mask0, br23)); + c = v_uint8x64(_mm512_permutex2var_epi8(br01, mask1, br23)); + b = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask0, ga23)); + d = v_uint8x64(_mm512_permutex2var_epi8(ga01, mask1, ga23)); +#else + __m512i mask = _mm512_set4_epi32(0x0f0b0703, 0x0e0a0602, 0x0d090501, 0x0c080400); + __m512i b0g0r0a0 = _mm512_shuffle_epi8(bgra0, mask); + __m512i b1g1r1a1 = _mm512_shuffle_epi8(bgra1, mask); + __m512i b2g2r2a2 = _mm512_shuffle_epi8(bgra2, mask); + __m512i b3g3r3a3 = _mm512_shuffle_epi8(bgra3, mask); + + __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi32(b0g0r0a0, mask0, b1g1r1a1); + __m512i ga01 = _mm512_permutex2var_epi32(b0g0r0a0, mask1, b1g1r1a1); + __m512i br23 = _mm512_permutex2var_epi32(b2g2r2a2, mask0, b3g3r3a3); + __m512i ga23 = _mm512_permutex2var_epi32(b2g2r2a2, mask1, b3g3r3a3); + + a = v_uint8x64(_mm512_permutex2var_epi32(br01, mask0, br23)); + c = v_uint8x64(_mm512_permutex2var_epi32(br01, mask1, br23)); + b = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask0, ga23)); + d = v_uint8x64(_mm512_permutex2var_epi32(ga01, mask1, ga23)); +#endif +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x32& a, v_uint16x32& b, v_uint16x32& c, v_uint16x32& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 64)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 96)); + + __m512i mask0 = _v512_set_epu16(62, 60, 58, 56, 54, 52, 50, 48, 46, 44, 42, 40, 38, 36, 34, 32, + 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu16(63, 61, 59, 57, 55, 53, 51, 49, 47, 45, 43, 41, 39, 37, 35, 33, + 31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi16(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi16(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi16(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi16(bgra2, mask1, bgra3); + + a = v_uint16x32(_mm512_permutex2var_epi16(br01, mask0, br23)); + c = v_uint16x32(_mm512_permutex2var_epi16(br01, mask1, br23)); + b = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask0, ga23)); + d = v_uint16x32(_mm512_permutex2var_epi16(ga01, mask1, ga23)); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x16& a, v_uint32x16& b, v_uint32x16& c, v_uint32x16& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 32)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 48)); + + __m512i mask0 = _v512_set_epu32(30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu32(31, 29, 27, 25, 23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi32(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi32(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi32(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi32(bgra2, mask1, bgra3); + + a = v_uint32x16(_mm512_permutex2var_epi32(br01, mask0, br23)); + c = v_uint32x16(_mm512_permutex2var_epi32(br01, mask1, br23)); + b = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask0, ga23)); + d = v_uint32x16(_mm512_permutex2var_epi32(ga01, mask1, ga23)); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x8& a, v_uint64x8& b, v_uint64x8& c, v_uint64x8& d ) +{ + __m512i bgra0 = _mm512_loadu_si512((const __m512i*)ptr); + __m512i bgra1 = _mm512_loadu_si512((const __m512i*)(ptr + 8)); + __m512i bgra2 = _mm512_loadu_si512((const __m512i*)(ptr + 16)); + __m512i bgra3 = _mm512_loadu_si512((const __m512i*)(ptr + 24)); + + __m512i mask0 = _v512_set_epu64(14, 12, 10, 8, 6, 4, 2, 0); + __m512i mask1 = _v512_set_epu64(15, 13, 11, 9, 7, 5, 3, 1); + + __m512i br01 = _mm512_permutex2var_epi64(bgra0, mask0, bgra1); + __m512i ga01 = _mm512_permutex2var_epi64(bgra0, mask1, bgra1); + __m512i br23 = _mm512_permutex2var_epi64(bgra2, mask0, bgra3); + __m512i ga23 = _mm512_permutex2var_epi64(bgra2, mask1, bgra3); + + a = v_uint64x8(_mm512_permutex2var_epi64(br01, mask0, br23)); + c = v_uint64x8(_mm512_permutex2var_epi64(br01, mask1, br23)); + b = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask0, ga23)); + d = v_uint64x8(_mm512_permutex2var_epi64(ga01, mask1, ga23)); +} + +///////////////////////////// store interleave ///////////////////////////////////// + +inline void v_store_interleave( uchar* ptr, const v_uint8x64& x, const v_uint8x64& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint8x64 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 64), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 64), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 64), high.val); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x32& x, const v_uint16x32& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint16x32 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 32), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 32), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 32), high.val); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x16& x, const v_uint32x16& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint32x16 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 16), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 16), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 16), high.val); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x8& x, const v_uint64x8& y, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint64x8 low, high; + v_zip(x, y, low, high); + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, low.val); + _mm512_stream_si512((__m512i*)(ptr + 8), high.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, low.val); + _mm512_store_si512((__m512i*)(ptr + 8), high.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, low.val); + _mm512_storeu_si512((__m512i*)(ptr + 8), high.val); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, const v_uint8x64& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ +#if CV_AVX_512VBMI + __m512i mask0 = _v512_set_epu8(127, 84, 20, 126, 83, 19, 125, 82, 18, 124, 81, 17, 123, 80, 16, 122, + 79, 15, 121, 78, 14, 120, 77, 13, 119, 76, 12, 118, 75, 11, 117, 74, + 10, 116, 73, 9, 115, 72, 8, 114, 71, 7, 113, 70, 6, 112, 69, 5, + 111, 68, 4, 110, 67, 3, 109, 66, 2, 108, 65, 1, 107, 64, 0, 106); + __m512i mask1 = _v512_set_epu8( 21, 42, 105, 20, 41, 104, 19, 40, 103, 18, 39, 102, 17, 38, 101, 16, + 37, 100, 15, 36, 99, 14, 35, 98, 13, 34, 97, 12, 33, 96, 11, 32, + 95, 10, 31, 94, 9, 30, 93, 8, 29, 92, 7, 28, 91, 6, 27, 90, + 5, 26, 89, 4, 25, 88, 3, 24, 87, 2, 23, 86, 1, 22, 85, 0); + __m512i mask2 = _v512_set_epu8(106, 127, 63, 105, 126, 62, 104, 125, 61, 103, 124, 60, 102, 123, 59, 101, + 122, 58, 100, 121, 57, 99, 120, 56, 98, 119, 55, 97, 118, 54, 96, 117, + 53, 95, 116, 52, 94, 115, 51, 93, 114, 50, 92, 113, 49, 91, 112, 48, + 90, 111, 47, 89, 110, 46, 88, 109, 45, 87, 108, 44, 86, 107, 43, 85); + __m512i r2g0r0 = _mm512_permutex2var_epi8(b.val, mask0, c.val); + __m512i b0r1b1 = _mm512_permutex2var_epi8(a.val, mask1, c.val); + __m512i g1b2g2 = _mm512_permutex2var_epi8(a.val, mask2, b.val); + + __m512i bgr0 = _mm512_mask_blend_epi8(0x9249249249249249, r2g0r0, b0r1b1); + __m512i bgr1 = _mm512_mask_blend_epi8(0x9249249249249249, b0r1b1, g1b2g2); + __m512i bgr2 = _mm512_mask_blend_epi8(0x9249249249249249, g1b2g2, r2g0r0); +#else + __m512i g1g0 = _mm512_shuffle_epi8(b.val, _mm512_set4_epi32(0x0e0f0c0d, 0x0a0b0809, 0x06070405, 0x02030001)); + __m512i b0g0 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, a.val, g1g0); + __m512i r0b1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, c.val, a.val); + __m512i g1r1 = _mm512_mask_blend_epi8(0xAAAAAAAAAAAAAAAA, g1g0, c.val); + + __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, + 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); + __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, + 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); + __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, + 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); + __m512i b0g0b2 = _mm512_permutex2var_epi16(b0g0, mask0, r0b1); + __m512i r1b1r0 = _mm512_permutex2var_epi16(b0g0, mask1, g1r1); + __m512i g2r2g1 = _mm512_permutex2var_epi16(r0b1, mask2, g1r1); + + __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); + __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); + __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); +#endif + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 64), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 128), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 64), bgr1); + _mm512_store_si512((__m512i*)(ptr + 128), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 128), bgr2); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, const v_uint16x32& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m512i mask0 = _v512_set_epu16(42, 10, 31, 41, 9, 30, 40, 8, 29, 39, 7, 28, 38, 6, 27, 37, + 5, 26, 36, 4, 25, 35, 3, 24, 34, 2, 23, 33, 1, 22, 32, 0); + __m512i mask1 = _v512_set_epu16(21, 52, 41, 20, 51, 40, 19, 50, 39, 18, 49, 38, 17, 48, 37, 16, + 47, 36, 15, 46, 35, 14, 45, 34, 13, 44, 33, 12, 43, 32, 11, 42); + __m512i mask2 = _v512_set_epu16(63, 31, 20, 62, 30, 19, 61, 29, 18, 60, 28, 17, 59, 27, 16, 58, + 26, 15, 57, 25, 14, 56, 24, 13, 55, 23, 12, 54, 22, 11, 53, 21); + __m512i b0g0b2 = _mm512_permutex2var_epi16(a.val, mask0, b.val); + __m512i r1b1r0 = _mm512_permutex2var_epi16(a.val, mask1, c.val); + __m512i g2r2g1 = _mm512_permutex2var_epi16(b.val, mask2, c.val); + + __m512i bgr0 = _mm512_mask_blend_epi16(0x24924924, b0g0b2, r1b1r0); + __m512i bgr1 = _mm512_mask_blend_epi16(0x24924924, r1b1r0, g2r2g1); + __m512i bgr2 = _mm512_mask_blend_epi16(0x24924924, g2r2g1, b0g0b2); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 32), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 64), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 32), bgr1); + _mm512_store_si512((__m512i*)(ptr + 64), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgr2); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, const v_uint32x16& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m512i mask0 = _v512_set_epu32(26, 31, 15, 25, 30, 14, 24, 29, 13, 23, 28, 12, 22, 27, 11, 21); + __m512i mask1 = _v512_set_epu32(31, 10, 25, 30, 9, 24, 29, 8, 23, 28, 7, 22, 27, 6, 21, 26); + __m512i g1b2g2 = _mm512_permutex2var_epi32(a.val, mask0, b.val); + __m512i r2r1b1 = _mm512_permutex2var_epi32(a.val, mask1, c.val); + + __m512i bgr0 = _mm512_mask_expand_epi32(_mm512_mask_expand_epi32(_mm512_maskz_expand_epi32(0x9249, a.val), 0x2492, b.val), 0x4924, c.val); + __m512i bgr1 = _mm512_mask_blend_epi32(0x9249, r2r1b1, g1b2g2); + __m512i bgr2 = _mm512_mask_blend_epi32(0x9249, g1b2g2, r2r1b1); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 16), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 32), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 16), bgr1); + _mm512_store_si512((__m512i*)(ptr + 32), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgr2); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, const v_uint64x8& c, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + __m512i mask0 = _v512_set_epu64( 5, 12, 7, 4, 11, 6, 3, 10); + __m512i mask1 = _v512_set_epu64(15, 7, 4, 14, 6, 3, 13, 5); + __m512i r1b1b2 = _mm512_permutex2var_epi64(a.val, mask0, c.val); + __m512i g2r2g1 = _mm512_permutex2var_epi64(b.val, mask1, c.val); + + __m512i bgr0 = _mm512_mask_expand_epi64(_mm512_mask_expand_epi64(_mm512_maskz_expand_epi64(0x49, a.val), 0x92, b.val), 0x24, c.val); + __m512i bgr1 = _mm512_mask_blend_epi64(0xdb, g2r2g1, r1b1b2); + __m512i bgr2 = _mm512_mask_blend_epi64(0xdb, r1b1b2, g2r2g1); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgr0); + _mm512_stream_si512((__m512i*)(ptr + 8), bgr1); + _mm512_stream_si512((__m512i*)(ptr + 16), bgr2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgr0); + _mm512_store_si512((__m512i*)(ptr + 8), bgr1); + _mm512_store_si512((__m512i*)(ptr + 16), bgr2); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgr0); + _mm512_storeu_si512((__m512i*)(ptr + 8), bgr1); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgr2); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x64& a, const v_uint8x64& b, + const v_uint8x64& c, const v_uint8x64& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint8x64 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint8x64 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 64), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 128), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 192), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 64), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 128), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 192), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 128), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 192), bgra3.val); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x32& a, const v_uint16x32& b, + const v_uint16x32& c, const v_uint16x32& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint16x32 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint16x32 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 32), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 64), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 96), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 32), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 64), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 96), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 64), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 96), bgra3.val); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x16& a, const v_uint32x16& b, + const v_uint32x16& c, const v_uint32x16& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint32x16 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint32x16 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 16), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 32), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 48), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 16), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 32), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 48), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 32), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 48), bgra3.val); + } +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x8& a, const v_uint64x8& b, + const v_uint64x8& c, const v_uint64x8& d, + hal::StoreMode mode=hal::STORE_UNALIGNED ) +{ + v_uint64x8 br01, br23, ga01, ga23; + v_zip(a, c, br01, br23); + v_zip(b, d, ga01, ga23); + v_uint64x8 bgra0, bgra1, bgra2, bgra3; + v_zip(br01, ga01, bgra0, bgra1); + v_zip(br23, ga23, bgra2, bgra3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm512_stream_si512((__m512i*)ptr, bgra0.val); + _mm512_stream_si512((__m512i*)(ptr + 8), bgra1.val); + _mm512_stream_si512((__m512i*)(ptr + 16), bgra2.val); + _mm512_stream_si512((__m512i*)(ptr + 24), bgra3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm512_store_si512((__m512i*)ptr, bgra0.val); + _mm512_store_si512((__m512i*)(ptr + 8), bgra1.val); + _mm512_store_si512((__m512i*)(ptr + 16), bgra2.val); + _mm512_store_si512((__m512i*)(ptr + 24), bgra3.val); + } + else + { + _mm512_storeu_si512((__m512i*)ptr, bgra0.val); + _mm512_storeu_si512((__m512i*)(ptr + 8), bgra1.val); + _mm512_storeu_si512((__m512i*)(ptr + 16), bgra2.val); + _mm512_storeu_si512((__m512i*)(ptr + 24), bgra3.val); + } +} + +#define OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int8x64, schar, s8, v_uint8x64, uchar, u8) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int16x32, short, s16, v_uint16x32, ushort, u16) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int32x16, int, s32, v_uint32x16, unsigned, u32) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float32x16, float, f32, v_uint32x16, unsigned, u32) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_int64x8, int64, s64, v_uint64x8, uint64, u64) +OPENCV_HAL_IMPL_AVX512_LOADSTORE_INTERLEAVE(v_float64x8, double, f64, v_uint64x8, uint64, u64) + +////////// Mask and checks ///////// + +/** Mask **/ +inline int64 v_signmask(const v_int8x64& a) { return (int64)_mm512_movepi8_mask(a.val); } +inline int v_signmask(const v_int16x32& a) { return (int)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline int v_signmask(const v_int32x16& a) { return (int)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline int v_signmask(const v_int64x8& a) { return (int)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } + +inline int64 v_signmask(const v_uint8x64& a) { return v_signmask(v_reinterpret_as_s8(a)); } +inline int v_signmask(const v_uint16x32& a) { return v_signmask(v_reinterpret_as_s16(a)); } +inline int v_signmask(const v_uint32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_uint64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } +inline int v_signmask(const v_float32x16& a) { return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_float64x8& a) { return v_signmask(v_reinterpret_as_s64(a)); } + +/** Checks **/ +inline bool v_check_all(const v_int8x64& a) { return !(bool)_mm512_cmp_epi8_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int8x64& a) { return (bool)_mm512_movepi8_mask(a.val); } +inline bool v_check_all(const v_int16x32& a) { return !(bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int16x32& a) { return (bool)_mm512_cmp_epi16_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline bool v_check_all(const v_int32x16& a) { return !(bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int32x16& a) { return (bool)_mm512_cmp_epi32_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } +inline bool v_check_all(const v_int64x8& a) { return !(bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_NLT); } +inline bool v_check_any(const v_int64x8& a) { return (bool)_mm512_cmp_epi64_mask(a.val, _mm512_setzero_si512(), _MM_CMPINT_LT); } + +inline bool v_check_all(const v_float32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_float32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_float64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_float64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } +inline bool v_check_all(const v_uint8x64& a) { return v_check_all(v_reinterpret_as_s8(a)); } +inline bool v_check_all(const v_uint16x32& a) { return v_check_all(v_reinterpret_as_s16(a)); } +inline bool v_check_all(const v_uint32x16& a) { return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_uint64x8& a) { return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_uint8x64& a) { return v_check_any(v_reinterpret_as_s8(a)); } +inline bool v_check_any(const v_uint16x32& a) { return v_check_any(v_reinterpret_as_s16(a)); } +inline bool v_check_any(const v_uint32x16& a) { return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_uint64x8& a) { return v_check_any(v_reinterpret_as_s64(a)); } + +inline int v_scan_forward(const v_int8x64& a) +{ + int64 mask = _mm512_movepi8_mask(a.val); + int mask32 = (int)mask; + return mask != 0 ? mask32 != 0 ? trailingZeros32(mask32) : 32 + trailingZeros32((int)(mask >> 32)) : 0; +} +inline int v_scan_forward(const v_uint8x64& a) { return v_scan_forward(v_reinterpret_as_s8(a)); } +inline int v_scan_forward(const v_int16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } +inline int v_scan_forward(const v_uint16x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))); } +inline int v_scan_forward(const v_int32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } +inline int v_scan_forward(const v_uint32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } +inline int v_scan_forward(const v_float32x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 2; } +inline int v_scan_forward(const v_int64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } +inline int v_scan_forward(const v_uint64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } +inline int v_scan_forward(const v_float64x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s16(a))) / 4; } + +inline void v512_cleanup() { _mm256_zeroall(); } + +#include "intrin_math.hpp" +inline v_float32x16 v_exp(const v_float32x16& x) { return v_exp_default_32f(x); } +inline v_float32x16 v_log(const v_float32x16& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x16& x, v_float32x16& s, v_float32x16& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x16 v_sin(const v_float32x16& x) { return v_sin_default_32f(x); } +inline v_float32x16 v_cos(const v_float32x16& x) { return v_cos_default_32f(x); } +inline v_float32x16 v_erf(const v_float32x16& x) { return v_erf_default_32f(x); } + +inline v_float64x8 v_exp(const v_float64x8& x) { return v_exp_default_64f(x); } +inline v_float64x8 v_log(const v_float64x8& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x8& x, v_float64x8& s, v_float64x8& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x8 v_sin(const v_float64x8& x) { return v_sin_default_64f(x); } +inline v_float64x8 v_cos(const v_float64x8& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_AVX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp index 1b2462c642..3e5d484145 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_cpp.hpp @@ -1,3373 +1,3373 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HAL_INTRIN_CPP_HPP -#define OPENCV_HAL_INTRIN_CPP_HPP - -#include -#include -#include -#include "opencv2/core/utility.hpp" -#include "opencv2/core/saturate.hpp" - -//! @cond IGNORED -#define CV_SIMD128_CPP 1 -#if defined(CV_FORCE_SIMD128_CPP) -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#endif -#if defined(CV_DOXYGEN) -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#define CV_SIMD256 1 -#define CV_SIMD256_64F 1 -#define CV_SIMD512 1 -#define CV_SIMD512_64F 1 -#else -#define CV_SIMD256 0 // Explicitly disable SIMD256 and SIMD512 support for scalar intrinsic implementation -#define CV_SIMD512 0 // to avoid warnings during compilation -#endif -//! @endcond - -namespace cv -{ - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN -#endif - -/** @addtogroup core_hal_intrin - -"Universal intrinsics" is a types and functions set intended to simplify vectorization of code on -different platforms. Currently a few different SIMD extensions on different architectures are supported. -128 bit registers of various types support is implemented for a wide range of architectures -including x86(__SSE/SSE2/SSE4.2__), ARM(__NEON__), PowerPC(__VSX__), MIPS(__MSA__). -256 bit long registers are supported on x86(__AVX2__) and 512 bit long registers are supported on x86(__AVX512__). -In case when there is no SIMD extension available during compilation, fallback C++ implementation of intrinsics -will be chosen and code will work as expected although it could be slower. - -### Types - -There are several types representing packed values vector registers, each type is -implemented as a structure based on a one SIMD register. - -- cv::v_uint8 and cv::v_int8: 8-bit integer values (unsigned/signed) - char -- cv::v_uint16 and cv::v_int16: 16-bit integer values (unsigned/signed) - short -- cv::v_uint32 and cv::v_int32: 32-bit integer values (unsigned/signed) - int -- cv::v_uint64 and cv::v_int64: 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32: 32-bit floating point values (signed) - float -- cv::v_float64: 64-bit floating point values (signed) - double - -Exact bit length(and value quantity) of listed types is compile time deduced and depends on architecture SIMD -capabilities chosen as available during compilation of the library. All the types contains __nlanes__ enumeration -to check for exact value quantity of the type. - -In case the exact bit length of the type is important it is possible to use specific fixed length register types. - -There are several types representing 128-bit registers. - -- cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char -- cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short -- cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsigned/signed) - int -- cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32x4: four 32-bit floating point values (signed) - float -- cv::v_float64x2: two 64-bit floating point values (signed) - double - -There are several types representing 256-bit registers. - -- cv::v_uint8x32 and cv::v_int8x32: thirty two 8-bit integer values (unsigned/signed) - char -- cv::v_uint16x16 and cv::v_int16x16: sixteen 16-bit integer values (unsigned/signed) - short -- cv::v_uint32x8 and cv::v_int32x8: eight 32-bit integer values (unsigned/signed) - int -- cv::v_uint64x4 and cv::v_int64x4: four 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32x8: eight 32-bit floating point values (signed) - float -- cv::v_float64x4: four 64-bit floating point values (signed) - double - -@note -256 bit registers at the moment implemented for AVX2 SIMD extension only, if you want to use this type directly, -don't forget to check the CV_SIMD256 preprocessor definition: -@code -#if CV_SIMD256 -//... -#endif -@endcode - -There are several types representing 512-bit registers. - -- cv::v_uint8x64 and cv::v_int8x64: sixty four 8-bit integer values (unsigned/signed) - char -- cv::v_uint16x32 and cv::v_int16x32: thirty two 16-bit integer values (unsigned/signed) - short -- cv::v_uint32x16 and cv::v_int32x16: sixteen 32-bit integer values (unsigned/signed) - int -- cv::v_uint64x8 and cv::v_int64x8: eight 64-bit integer values (unsigned/signed) - int64 -- cv::v_float32x16: sixteen 32-bit floating point values (signed) - float -- cv::v_float64x8: eight 64-bit floating point values (signed) - double -@note -512 bit registers at the moment implemented for AVX512 SIMD extension only, if you want to use this type directly, -don't forget to check the CV_SIMD512 preprocessor definition. - -@note -cv::v_float64x2 is not implemented in NEON variant, if you want to use this type, don't forget to -check the CV_SIMD128_64F preprocessor definition. - -### Load and store operations - -These operations allow to set contents of the register explicitly or by loading it from some memory -block and to save contents of the register to memory block. - -There are variable size register load operations that provide result of maximum available size -depending on chosen platform capabilities. -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -- Other create methods: -vx_setall_s8, vx_setall_u8, ..., -vx_setzero_u8, vx_setzero_s8, ... -- Memory load operations: -vx_load, vx_load_aligned, vx_load_low, vx_load_halves, -- Memory operations with expansion of values: -vx_load_expand, vx_load_expand_q - -Also there are fixed size register load/store operations. - -For 128 bit registers -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -@ref v_reg::v_reg(_Tp s0, _Tp s1) "from two values", ... -- Other create methods: -@ref v_setall_s8, @ref v_setall_u8, ..., -@ref v_setzero_u8, @ref v_setzero_s8, ... -- Memory load operations: -@ref v_load, @ref v_load_aligned, @ref v_load_low, @ref v_load_halves, -- Memory operations with expansion of values: -@ref v_load_expand, @ref v_load_expand_q - -For 256 bit registers(check CV_SIMD256 preprocessor definition) -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) "from four values", ... -- Other create methods: -@ref v256_setall_s8, @ref v256_setall_u8, ..., -@ref v256_setzero_u8, @ref v256_setzero_s8, ... -- Memory load operations: -@ref v256_load, @ref v256_load_aligned, @ref v256_load_low, @ref v256_load_halves, -- Memory operations with expansion of values: -@ref v256_load_expand, @ref v256_load_expand_q - -For 512 bit registers(check CV_SIMD512 preprocessor definition) -- Constructors: -@ref v_reg::v_reg(const _Tp *ptr) "from memory", -@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7) "from eight values", ... -- Other create methods: -@ref v512_setall_s8, @ref v512_setall_u8, ..., -@ref v512_setzero_u8, @ref v512_setzero_s8, ... -- Memory load operations: -@ref v512_load, @ref v512_load_aligned, @ref v512_load_low, @ref v512_load_halves, -- Memory operations with expansion of values: -@ref v512_load_expand, @ref v512_load_expand_q - -Store to memory operations are similar across different platform capabilities: -@ref v_store, @ref v_store_aligned, -@ref v_store_high, @ref v_store_low - -### Value reordering - -These operations allow to reorder or recombine elements in one or multiple vectors. - -- Interleave, deinterleave (2, 3 and 4 channels): @ref v_load_deinterleave, @ref v_store_interleave -- Expand: @ref v_expand, @ref v_expand_low, @ref v_expand_high -- Pack: @ref v_pack, @ref v_pack_u, @ref v_pack_b, @ref v_rshr_pack, @ref v_rshr_pack_u, -@ref v_pack_store, @ref v_pack_u_store, @ref v_rshr_pack_store, @ref v_rshr_pack_u_store -- Recombine: @ref v_zip, @ref v_recombine, @ref v_combine_low, @ref v_combine_high -- Reverse: @ref v_reverse -- Extract: @ref v_extract - - -### Arithmetic, bitwise and comparison operations - -Element-wise binary and unary operations. - -- Arithmetics: -@ref v_add(const v_reg &a, const v_reg &b) "+", -@ref v_sub(const v_reg &a, const v_reg &b) "-", -@ref v_mul(const v_reg &a, const v_reg &b) "*", -@ref v_div(const v_reg &a, const v_reg &b) "/", -@ref v_mul_expand - -- Non-saturating arithmetics: @ref v_add_wrap, @ref v_sub_wrap - -- Bitwise shifts: -@ref v_shl(const v_reg &a, int s) "<<", -@ref v_shr(const v_reg &a, int s) ">>", -@ref v_shl, @ref v_shr - -- Bitwise logic: -@ref v_and(const v_reg &a, const v_reg &b) "&", -@ref v_or(const v_reg &a, const v_reg &b) "|", -@ref v_xor(const v_reg &a, const v_reg &b) "^", -@ref v_not(const v_reg &a) "~" - -- Comparison: -@ref v_gt(const v_reg &a, const v_reg &b) ">", -@ref v_ge(const v_reg &a, const v_reg &b) ">=", -@ref v_lt(const v_reg &a, const v_reg &b) "<", -@ref v_le(const v_reg &a, const v_reg &b) "<=", -@ref v_eq(const v_reg &a, const v_reg &b) "==", -@ref v_ne(const v_reg &a, const v_reg &b) "!=" - -- min/max: @ref v_min, @ref v_max - -### Reduce and mask - -Most of these operations return only one value. - -- Reduce: @ref v_reduce_min, @ref v_reduce_max, @ref v_reduce_sum, @ref v_popcount -- Mask: @ref v_signmask, @ref v_check_all, @ref v_check_any, @ref v_select - -### Other math - -- Some frequent operations: @ref v_sqrt, @ref v_invsqrt, @ref v_magnitude, @ref v_sqr_magnitude, @ref v_exp, @ref v_log, - @ref v_erf, @ref v_sin, @ref v_cos -- Absolute values: @ref v_abs, @ref v_absdiff, @ref v_absdiffs - -### Conversions - -Different type conversions and casts: - -- Rounding: @ref v_round, @ref v_floor, @ref v_ceil, @ref v_trunc, -- To float: @ref v_cvt_f32, @ref v_cvt_f64 -- Reinterpret: @ref v_reinterpret_as_u8, @ref v_reinterpret_as_s8, ... - -### Matrix operations - -In these operations vectors represent matrix rows/columns: @ref v_dotprod, @ref v_dotprod_fast, -@ref v_dotprod_expand, @ref v_dotprod_expand_fast, @ref v_matmul, @ref v_transpose4x4 - -### Usability - -Most operations are implemented only for some subset of the available types, following matrices -shows the applicability of different operations to the types. - -Regular integers: - -| Operations\\Types | uint 8 | int 8 | uint 16 | int 16 | uint 32 | int 32 | -|-------------------|:-:|:-:|:-:|:-:|:-:|:-:| -|load, store | x | x | x | x | x | x | -|interleave | x | x | x | x | x | x | -|expand | x | x | x | x | x | x | -|expand_low | x | x | x | x | x | x | -|expand_high | x | x | x | x | x | x | -|expand_q | x | x | | | | | -|add, sub | x | x | x | x | x | x | -|add_wrap, sub_wrap | x | x | x | x | | | -|mul_wrap | x | x | x | x | | | -|mul | x | x | x | x | x | x | -|mul_expand | x | x | x | x | x | | -|compare | x | x | x | x | x | x | -|shift | | | x | x | x | x | -|dotprod | | | | x | | x | -|dotprod_fast | | | | x | | x | -|dotprod_expand | x | x | x | x | | x | -|dotprod_expand_fast| x | x | x | x | | x | -|logical | x | x | x | x | x | x | -|min, max | x | x | x | x | x | x | -|absdiff | x | x | x | x | x | x | -|absdiffs | | x | | x | | | -|reduce | x | x | x | x | x | x | -|mask | x | x | x | x | x | x | -|pack | x | x | x | x | x | x | -|pack_u | x | | x | | | | -|pack_b | x | | | | | | -|unpack | x | x | x | x | x | x | -|extract | x | x | x | x | x | x | -|rotate (lanes) | x | x | x | x | x | x | -|cvt_flt32 | | | | | | x | -|cvt_flt64 | | | | | | x | -|transpose4x4 | | | | | x | x | -|reverse | x | x | x | x | x | x | -|extract_n | x | x | x | x | x | x | -|broadcast_element | | | | | x | x | - -Big integers: - -| Operations\\Types | uint 64 | int 64 | -|-------------------|:-:|:-:| -|load, store | x | x | -|add, sub | x | x | -|shift | x | x | -|logical | x | x | -|reverse | x | x | -|extract | x | x | -|rotate (lanes) | x | x | -|cvt_flt64 | | x | -|extract_n | x | x | - -Floating point: - -| Operations\\Types | float 32 | float 64 | -|-------------------|:-:|:-:| -|load, store | x | x | -|interleave | x | | -|add, sub | x | x | -|mul | x | x | -|div | x | x | -|compare | x | x | -|min, max | x | x | -|absdiff | x | x | -|reduce | x | | -|mask | x | x | -|unpack | x | x | -|cvt_flt32 | | x | -|cvt_flt64 | x | | -|sqrt, abs | x | x | -|float math | x | x | -|transpose4x4 | x | | -|extract | x | x | -|rotate (lanes) | x | x | -|reverse | x | x | -|extract_n | x | x | -|broadcast_element | x | | -|exp | x | x | -|log | x | x | -|sin, cos | x | x | - - @{ */ - -template struct v_reg -{ -//! @cond IGNORED - typedef _Tp lane_type; - enum { nlanes = n }; -// !@endcond - - /** @brief Constructor - - Initializes register with data from memory - @param ptr pointer to memory block with data for register */ - explicit v_reg(const _Tp* ptr) { for( int i = 0; i < n; i++ ) s[i] = ptr[i]; } - - /** @brief Constructor - - Initializes register with two 64-bit values */ - v_reg(_Tp s0, _Tp s1) { s[0] = s0; s[1] = s1; } - - /** @brief Constructor - - Initializes register with four 32-bit values */ - v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; } - - /** @brief Constructor - - Initializes register with eight 16-bit values */ - v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, - _Tp s4, _Tp s5, _Tp s6, _Tp s7) - { - s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; - s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; - } - - /** @brief Constructor - - Initializes register with sixteen 8-bit values */ - v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, - _Tp s4, _Tp s5, _Tp s6, _Tp s7, - _Tp s8, _Tp s9, _Tp s10, _Tp s11, - _Tp s12, _Tp s13, _Tp s14, _Tp s15) - { - s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; - s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; - s[8] = s8; s[9] = s9; s[10] = s10; s[11] = s11; - s[12] = s12; s[13] = s13; s[14] = s14; s[15] = s15; - } - - /** @brief Default constructor - - Does not initialize anything*/ - v_reg() {} - - /** @brief Copy constructor */ - v_reg(const v_reg<_Tp, n> & r) - { - for( int i = 0; i < n; i++ ) - s[i] = r.s[i]; - } - /** @brief Access first value - - Returns value of the first lane according to register type, for example: - @code{.cpp} - v_int32x4 r(1, 2, 3, 4); - int v = r.get0(); // returns 1 - v_uint64x2 r(1, 2); - uint64_t v = r.get0(); // returns 1 - @endcode - */ - _Tp get0() const { return s[0]; } - -//! @cond IGNORED - _Tp get(const int i) const { return s[i]; } - v_reg<_Tp, n> high() const - { - v_reg<_Tp, n> c; - int i; - for( i = 0; i < n/2; i++ ) - { - c.s[i] = s[i+(n/2)]; - c.s[i+(n/2)] = 0; - } - return c; - } - - static v_reg<_Tp, n> zero() - { - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = (_Tp)0; - return c; - } - - static v_reg<_Tp, n> all(_Tp s) - { - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = s; - return c; - } - - template v_reg<_Tp2, n2> reinterpret_as() const - { - size_t bytes = std::min(sizeof(_Tp2)*n2, sizeof(_Tp)*n); - v_reg<_Tp2, n2> c; - std::memcpy(&c.s[0], &s[0], bytes); - return c; - } - - v_reg& operator=(const v_reg<_Tp, n> & r) - { - for( int i = 0; i < n; i++ ) - s[i] = r.s[i]; - return *this; - } - - _Tp s[n]; -//! @endcond -}; - -/** @brief Sixteen 8-bit unsigned integer values */ -typedef v_reg v_uint8x16; -/** @brief Sixteen 8-bit signed integer values */ -typedef v_reg v_int8x16; -/** @brief Eight 16-bit unsigned integer values */ -typedef v_reg v_uint16x8; -/** @brief Eight 16-bit signed integer values */ -typedef v_reg v_int16x8; -/** @brief Four 32-bit unsigned integer values */ -typedef v_reg v_uint32x4; -/** @brief Four 32-bit signed integer values */ -typedef v_reg v_int32x4; -/** @brief Four 32-bit floating point values (single precision) */ -typedef v_reg v_float32x4; -/** @brief Two 64-bit floating point values (double precision) */ -typedef v_reg v_float64x2; -/** @brief Two 64-bit unsigned integer values */ -typedef v_reg v_uint64x2; -/** @brief Two 64-bit signed integer values */ -typedef v_reg v_int64x2; - -#if CV_SIMD256 -/** @brief Thirty two 8-bit unsigned integer values */ -typedef v_reg v_uint8x32; -/** @brief Thirty two 8-bit signed integer values */ -typedef v_reg v_int8x32; -/** @brief Sixteen 16-bit unsigned integer values */ -typedef v_reg v_uint16x16; -/** @brief Sixteen 16-bit signed integer values */ -typedef v_reg v_int16x16; -/** @brief Eight 32-bit unsigned integer values */ -typedef v_reg v_uint32x8; -/** @brief Eight 32-bit signed integer values */ -typedef v_reg v_int32x8; -/** @brief Eight 32-bit floating point values (single precision) */ -typedef v_reg v_float32x8; -/** @brief Four 64-bit floating point values (double precision) */ -typedef v_reg v_float64x4; -/** @brief Four 64-bit unsigned integer values */ -typedef v_reg v_uint64x4; -/** @brief Four 64-bit signed integer values */ -typedef v_reg v_int64x4; -#endif - -#if CV_SIMD512 -/** @brief Sixty four 8-bit unsigned integer values */ -typedef v_reg v_uint8x64; -/** @brief Sixty four 8-bit signed integer values */ -typedef v_reg v_int8x64; -/** @brief Thirty two 16-bit unsigned integer values */ -typedef v_reg v_uint16x32; -/** @brief Thirty two 16-bit signed integer values */ -typedef v_reg v_int16x32; -/** @brief Sixteen 32-bit unsigned integer values */ -typedef v_reg v_uint32x16; -/** @brief Sixteen 32-bit signed integer values */ -typedef v_reg v_int32x16; -/** @brief Sixteen 32-bit floating point values (single precision) */ -typedef v_reg v_float32x16; -/** @brief Eight 64-bit floating point values (double precision) */ -typedef v_reg v_float64x8; -/** @brief Eight 64-bit unsigned integer values */ -typedef v_reg v_uint64x8; -/** @brief Eight 64-bit signed integer values */ -typedef v_reg v_int64x8; -#endif - -enum { - simd128_width = 16, -#if CV_SIMD256 - simd256_width = 32, -#endif -#if CV_SIMD512 - simd512_width = 64, - simdmax_width = simd512_width -#elif CV_SIMD256 - simdmax_width = simd256_width -#else - simdmax_width = simd128_width -#endif -}; - -/** @brief Add values - -For all types. */ -template CV_INLINE v_reg<_Tp, n> v_add(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Subtract values - -For all types. */ -template CV_INLINE v_reg<_Tp, n> v_sub(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Multiply values - -For 16- and 32-bit integer types and floating types. */ -template CV_INLINE v_reg<_Tp, n> v_mul(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Divide values - -For floating types only. */ -template CV_INLINE v_reg<_Tp, n> v_div(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - - -/** @brief Bitwise AND - -Only for integer types. */ -template CV_INLINE v_reg<_Tp, n> v_and(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Bitwise OR - -Only for integer types. */ -template CV_INLINE v_reg<_Tp, n> v_or(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Bitwise XOR - -Only for integer types.*/ -template CV_INLINE v_reg<_Tp, n> v_xor(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); - -/** @brief Bitwise NOT - -Only for integer types.*/ -template CV_INLINE v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a); - - -#ifndef CV_DOXYGEN - -#define CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, ...) \ -__CV_EXPAND(macro_name(uchar, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(schar, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(ushort, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(short, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(unsigned, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(int, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(uint64, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(int64, __VA_ARGS__)) \ - -#define CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, ...) \ -__CV_EXPAND(macro_name(float, __VA_ARGS__)) \ -__CV_EXPAND(macro_name(double, __VA_ARGS__)) \ - -#define CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(macro_name, ...) \ -CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, __VA_ARGS__) \ -CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, __VA_ARGS__) \ - -#define CV__HAL_INTRIN_IMPL_BIN_OP_(_Tp, bin_op, func) \ -template inline \ -v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ - return c; \ -} - -#define CV__HAL_INTRIN_IMPL_BIN_OP(bin_op, func) CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, bin_op, func) - -CV__HAL_INTRIN_IMPL_BIN_OP(+, v_add) -CV__HAL_INTRIN_IMPL_BIN_OP(-, v_sub) -CV__HAL_INTRIN_IMPL_BIN_OP(*, v_mul) -CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, /, v_div) - -#define CV__HAL_INTRIN_IMPL_BIT_OP_(_Tp, bit_op, func) \ -template CV_INLINE \ -v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - typedef typename V_TypeTraits<_Tp>::int_type itype; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ - V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ - return c; \ -} - -#define CV__HAL_INTRIN_IMPL_BIT_OP(bit_op, func) \ -CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) \ -CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) /* TODO: FIXIT remove this after masks refactoring */ - - -CV__HAL_INTRIN_IMPL_BIT_OP(&, v_and) -CV__HAL_INTRIN_IMPL_BIT_OP(|, v_or) -CV__HAL_INTRIN_IMPL_BIT_OP(^, v_xor) - -#define CV__HAL_INTRIN_IMPL_BITWISE_NOT_(_Tp, dummy, dummy2) \ -template CV_INLINE \ -v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); \ - return c; \ -} \ - -CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BITWISE_NOT_, ~, v_not) - -#endif // !CV_DOXYGEN - - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_MATH_FUNC(func, cfunc, _Tp2) \ -template inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp2, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = cfunc(a.s[i]); \ - return c; \ -} - -/** @brief Square root of elements - -Only for floating point types.*/ -OPENCV_HAL_IMPL_MATH_FUNC(v_sqrt, std::sqrt, _Tp) - -/** - * @brief Exponential \f$ e^x \f$ of elements - * - * Only for floating point types. Core implementation steps: - * 1. Decompose Input: Convert the input to \f$ 2^{x \cdot \log_2e} \f$ and split its exponential into integer and fractional parts: - * \f$ x \cdot \log_2e = n + f \f$, where \f$ n \f$ is the integer part and \f$ f \f$ is the fractional part. - * 2. Compute \f$ 2^n \f$: Calculated by shifting the bits. - * 3. Adjust Fractional Part: Compute \f$ f \cdot \ln2 \f$ to convert the fractional part to base \f$ e \f$. - * \f$ C1 \f$ and \f$ C2 \f$ are used to adjust the fractional part. - * 4. Polynomial Approximation for \f$ e^{f \cdot \ln2} \f$: The closer the fractional part is to 0, the more accurate the result. - * - For float16 and float32, use a Taylor Series with 6 terms. - * - For float64, use Pade Polynomials Approximation with 4 terms. - * 5. Combine Results: Multiply the two parts together to get the final result: - * \f$ e^x = 2^n \cdot e^{f \cdot \ln2} \f$. - * - * @note The precision of the calculation depends on the implementation and the data type of the input vector. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_exp, std::exp, _Tp) -#define OPENCV_HAL_MATH_HAVE_EXP 1 - -/** - * @brief Natural logarithm \f$ \log(x) \f$ of elements - * - * Only for floating point types. Core implementation steps: - * 1. Decompose Input: Use binary representation to decompose the input into mantissa part \f$ m \f$ and exponent part \f$ e \f$. Such that \f$ \log(x) = \log(m \cdot 2^e) = \log(m) + e \cdot \ln(2) \f$. - * 2. Adjust Mantissa and Exponent Parts: If the mantissa is less than \f$ \sqrt{0.5} \f$, adjust the exponent and mantissa to ensure the mantissa is in the range \f$ (\sqrt{0.5}, \sqrt{2}) \f$ for better approximation. - * 3. Polynomial Approximation for \f$ \log(m) \f$: The closer the \f$ m \f$ is to 1, the more accurate the result. - * - For float16 and float32, use a Taylor Series with 9 terms. - * - For float64, use Pade Polynomials Approximation with 6 terms. - * 4. Combine Results: Add the two parts together to get the final result. - * - * @note The precision of the calculation depends on the implementation and the data type of the input. - * - * @note Similar to the behavior of std::log(), \f$ \ln(0) = -\infty \f$. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_log, std::log, _Tp) - -/** - * @brief Error function. - * - * @note Support FP32 precision for now. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_erf, std::erf, _Tp) - -/** - * @brief Compute sine \f$ sin(x) \f$ and cosine \f$ cos(x) \f$ of elements at the same time - * - * Only for floating point types. Core implementation steps: - * 1. Input Normalization: Scale the periodicity from 2π to 4 and reduce the angle to the range \f$ [0, \frac{\pi}{4}] \f$ using periodicity and trigonometric identities. - * 2. Polynomial Approximation for \f$ sin(x) \f$ and \f$ cos(x) \f$: - * - For float16 and float32, use a Taylor series with 4 terms for sine and 5 terms for cosine. - * - For float64, use a Taylor series with 7 terms for sine and 8 terms for cosine. - * 3. Select Results: select and convert the final sine and cosine values for the original input angle. - * - * @note The precision of the calculation depends on the implementation and the data type of the input vector. - */ -template -inline void v_sincos(const v_reg<_Tp, n>& x, v_reg<_Tp, n>& s, v_reg<_Tp, n>& c) -{ - for( int i = 0; i < n; i++ ) - { - s.s[i] = std::sin(x.s[i]); - c.s[i] = std::cos(x.s[i]); - } -} - -/** - * @brief Sine \f$ sin(x) \f$ of elements - * - * Only for floating point types. Core implementation the same as @ref v_sincos. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_sin, std::sin, _Tp) - -/** - * @brief Cosine \f$ cos(x) \f$ of elements - * - * Only for floating point types. Core implementation the same as @ref v_sincos. - */ -OPENCV_HAL_IMPL_MATH_FUNC(v_cos, std::cos, _Tp) - -/** @brief Absolute value of elements - -Only for floating point types.*/ -OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs, - typename V_TypeTraits<_Tp>::abs_type) - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_MINMAX_FUNC(func, cfunc) \ -template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = cfunc(a.s[i], b.s[i]); \ - return c; \ -} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(func, cfunc) \ -template inline _Tp func(const v_reg<_Tp, n>& a) \ -{ \ - _Tp c = a.s[0]; \ - for( int i = 1; i < n; i++ ) \ - c = cfunc(c, a.s[i]); \ - return c; \ -} - -/** @brief Choose min values for each pair - -Scheme: -@code -{A1 A2 ...} -{B1 B2 ...} --------------- -{min(A1,B1) min(A2,B2) ...} -@endcode -For all types except 64-bit integer. */ -OPENCV_HAL_IMPL_MINMAX_FUNC(v_min, std::min) - -/** @brief Choose max values for each pair - -Scheme: -@code -{A1 A2 ...} -{B1 B2 ...} --------------- -{max(A1,B1) max(A2,B2) ...} -@endcode -For all types except 64-bit integer. */ -OPENCV_HAL_IMPL_MINMAX_FUNC(v_max, std::max) - -/** @brief Find one min value - -Scheme: -@code -{A1 A2 A3 ...} => min(A1,A2,A3,...) -@endcode -For all types except 64-bit integer and 64-bit floating point types. */ -OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min) - -/** @brief Find one max value - -Scheme: -@code -{A1 A2 A3 ...} => max(A1,A2,A3,...) -@endcode -For all types except 64-bit integer and 64-bit floating point types. */ -OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max) - -static const unsigned char popCountTable[] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; -/** @brief Count the 1 bits in the vector lanes and return result as corresponding unsigned type - -Scheme: -@code -{A1 A2 A3 ...} => {popcount(A1), popcount(A2), popcount(A3), ...} -@endcode -For all integer types. */ -template -inline v_reg::abs_type, n> v_popcount(const v_reg<_Tp, n>& a) -{ - v_reg::abs_type, n> b = v_reg::abs_type, n>::zero(); - for (int i = 0; i < n*(int)sizeof(_Tp); i++) - b.s[i/sizeof(_Tp)] += popCountTable[v_reinterpret_as_u8(a).s[i]]; - return b; -} - - -//! @cond IGNORED -template -inline void v_minmax( const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - v_reg<_Tp, n>& minval, v_reg<_Tp, n>& maxval ) -{ - for( int i = 0; i < n; i++ ) - { - minval.s[i] = std::min(a.s[i], b.s[i]); - maxval.s[i] = std::max(a.s[i], b.s[i]); - } -} -//! @endcond - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_CMP_OP(cmp_op, func) \ -template \ -inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - typedef typename V_TypeTraits<_Tp>::int_type itype; \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)-(int)(a.s[i] cmp_op b.s[i])); \ - return c; \ -} - -/** @brief Less-than comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(<, v_lt) - -/** @brief Greater-than comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(>, v_gt) - -/** @brief Less-than or equal comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(<=, v_le) - -/** @brief Greater-than or equal comparison - -For all types except 64-bit integer values. */ -OPENCV_HAL_IMPL_CMP_OP(>=, v_ge) - -/** @brief Equal comparison */ -OPENCV_HAL_IMPL_CMP_OP(==, v_eq) - -/** @brief Not equal comparison */ -OPENCV_HAL_IMPL_CMP_OP(!=, v_ne) - -template -inline v_reg v_not_nan(const v_reg& a) -{ - typedef typename V_TypeTraits::int_type itype; - v_reg c; - for (int i = 0; i < n; i++) - c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); - return c; -} -template -inline v_reg v_not_nan(const v_reg& a) -{ - typedef typename V_TypeTraits::int_type itype; - v_reg c; - for (int i = 0; i < n; i++) - c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); - return c; -} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_ARITHM_OP(func, bin_op, cast_op, _Tp2) \ -template \ -inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - typedef _Tp2 rtype; \ - v_reg c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = cast_op(a.s[i] bin_op b.s[i]); \ - return c; \ -} - -/** @brief Add values without saturation - -For 8- and 16-bit integer values. */ -OPENCV_HAL_IMPL_ARITHM_OP(v_add_wrap, +, (_Tp), _Tp) - -/** @brief Subtract values without saturation - -For 8- and 16-bit integer values. */ -OPENCV_HAL_IMPL_ARITHM_OP(v_sub_wrap, -, (_Tp), _Tp) - -/** @brief Multiply values without saturation - -For 8- and 16-bit integer values. */ -OPENCV_HAL_IMPL_ARITHM_OP(v_mul_wrap, *, (_Tp), _Tp) - -//! @cond IGNORED -template inline T _absdiff(T a, T b) -{ - return a > b ? a - b : b - a; -} -//! @endcond - -/** @brief Absolute difference - -Returns \f$ |a - b| \f$ converted to corresponding unsigned type. -Example: -@code{.cpp} -v_int32x4 a, b; // {1, 2, 3, 4} and {4, 3, 2, 1} -v_uint32x4 c = v_absdiff(a, b); // result is {3, 1, 1, 3} -@endcode -For 8-, 16-, 32-bit integer source types. */ -template -inline v_reg::abs_type, n> v_absdiff(const v_reg<_Tp, n>& a, const v_reg<_Tp, n> & b) -{ - typedef typename V_TypeTraits<_Tp>::abs_type rtype; - v_reg c; - const rtype mask = (rtype)(std::numeric_limits<_Tp>::is_signed ? (1 << (sizeof(rtype)*8 - 1)) : 0); - for( int i = 0; i < n; i++ ) - { - rtype ua = a.s[i] ^ mask; - rtype ub = b.s[i] ^ mask; - c.s[i] = _absdiff(ua, ub); - } - return c; -} - -/** @overload - -For 32-bit floating point values */ -template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - c.s[i] = _absdiff(a.s[i], b.s[i]); - return c; -} - -/** @overload - -For 64-bit floating point values */ -template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - c.s[i] = _absdiff(a.s[i], b.s[i]); - return c; -} - -/** @brief Saturating absolute difference - -Returns \f$ saturate(|a - b|) \f$ . -For 8-, 16-bit signed integer source types. */ -template -inline v_reg<_Tp, n> v_absdiffs(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++) - c.s[i] = saturate_cast<_Tp>(std::abs(a.s[i] - b.s[i])); - return c; -} - -/** @brief Inversed square root - -Returns \f$ 1/sqrt(a) \f$ -For floating point types only. */ -template -inline v_reg<_Tp, n> v_invsqrt(const v_reg<_Tp, n>& a) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = 1.f/std::sqrt(a.s[i]); - return c; -} - -/** @brief Magnitude - -Returns \f$ sqrt(a^2 + b^2) \f$ -For floating point types only. */ -template -inline v_reg<_Tp, n> v_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = std::sqrt(a.s[i]*a.s[i] + b.s[i]*b.s[i]); - return c; -} - -/** @brief Square of the magnitude - -Returns \f$ a^2 + b^2 \f$ -For floating point types only. */ -template -inline v_reg<_Tp, n> v_sqr_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = a.s[i]*a.s[i] + b.s[i]*b.s[i]; - return c; -} - -/** @brief Multiply and add - - Returns \f$ a*b + c \f$ - For floating point types and signed 32bit int only. */ -template -inline v_reg<_Tp, n> v_fma(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg<_Tp, n>& c) -{ - v_reg<_Tp, n> d; - for( int i = 0; i < n; i++ ) - d.s[i] = a.s[i]*b.s[i] + c.s[i]; - return d; -} - -/** @brief A synonym for v_fma */ -template -inline v_reg<_Tp, n> v_muladd(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg<_Tp, n>& c) -{ - return v_fma(a, b, c); -} - -/** @brief Dot product of elements - -Multiply values in two registers and sum adjacent result pairs. - -Scheme: -@code - {A1 A2 ...} // 16-bit -x {B1 B2 ...} // 16-bit -------------- -{A1B1+A2B2 ...} // 32-bit - -@endcode -*/ -template inline v_reg::w_type, n/2> -v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1]; - return c; -} - -/** @brief Dot product of elements - -Same as cv::v_dotprod, but add a third element to the sum of adjacent pairs. -Scheme: -@code - {A1 A2 ...} // 16-bit -x {B1 B2 ...} // 16-bit -------------- - {A1B1+A2B2+C1 ...} // 32-bit -@endcode -*/ -template inline v_reg::w_type, n/2> -v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::w_type, n / 2>& c) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg s; - for( int i = 0; i < (n/2); i++ ) - s.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1] + c.s[i]; - return s; -} - -/** @brief Fast Dot product of elements - -Same as cv::v_dotprod, but it may perform unorder sum between result pairs in some platforms, -this intrinsic can be used if the sum among all lanes is only matters -and also it should be yielding better performance on the affected platforms. - -*/ -template inline v_reg::w_type, n/2> -v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ return v_dotprod(a, b); } - -/** @brief Fast Dot product of elements - -Same as cv::v_dotprod_fast, but add a third element to the sum of adjacent pairs. -*/ -template inline v_reg::w_type, n/2> -v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::w_type, n / 2>& c) -{ return v_dotprod(a, b, c); } - -/** @brief Dot product of elements and expand - -Multiply values in two registers and expand the sum of adjacent result pairs. - -Scheme: -@code - {A1 A2 A3 A4 ...} // 8-bit -x {B1 B2 B3 B4 ...} // 8-bit -------------- - {A1B1+A2B2+A3B3+A4B4 ...} // 32-bit - -@endcode -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg s; - for( int i = 0; i < (n/4); i++ ) - s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + - (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3]; - return s; -} - -/** @brief Dot product of elements - -Same as cv::v_dotprod_expand, but add a third element to the sum of adjacent pairs. -Scheme: -@code - {A1 A2 A3 A4 ...} // 8-bit -x {B1 B2 B3 B4 ...} // 8-bit -------------- - {A1B1+A2B2+A3B3+A4B4+C1 ...} // 32-bit -@endcode -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::q_type, n / 4>& c) -{ - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg s; - for( int i = 0; i < (n/4); i++ ) - s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + - (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3] + c.s[i]; - return s; -} - -/** @brief Fast Dot product of elements and expand - -Multiply values in two registers and expand the sum of adjacent result pairs. - -Same as cv::v_dotprod_expand, but it may perform unorder sum between result pairs in some platforms, -this intrinsic can be used if the sum among all lanes is only matters -and also it should be yielding better performance on the affected platforms. - -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ return v_dotprod_expand(a, b); } - -/** @brief Fast Dot product of elements - -Same as cv::v_dotprod_expand_fast, but add a third element to the sum of adjacent pairs. -*/ -template inline v_reg::q_type, n/4> -v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - const v_reg::q_type, n / 4>& c) -{ return v_dotprod_expand(a, b, c); } - -/** @brief Multiply and expand - -Multiply values two registers and store results in two registers with wider pack type. -Scheme: -@code - {A B C D} // 32-bit -x {E F G H} // 32-bit ---------------- -{AE BF} // 64-bit - {CG DH} // 64-bit -@endcode -Example: -@code{.cpp} -v_uint32x4 a, b; // {1,2,3,4} and {2,2,2,2} -v_uint64x2 c, d; // results -v_mul_expand(a, b, c, d); // c, d = {2,4}, {6, 8} -@endcode -Implemented only for 16- and unsigned 32-bit source types (v_int16x8, v_uint16x8, v_uint32x4). -*/ -template inline void v_mul_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - v_reg::w_type, n/2>& c, - v_reg::w_type, n/2>& d) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = (w_type)a.s[i]*b.s[i]; - d.s[i] = (w_type)a.s[i+(n/2)]*b.s[i+(n/2)]; - } -} - -/** @brief Multiply and extract high part - -Multiply values two registers and store high part of the results. -Implemented only for 16-bit source types (v_int16x8, v_uint16x8). Returns \f$ a*b >> 16 \f$ -*/ -template inline v_reg<_Tp, n> v_mul_hi(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg<_Tp, n> c; - for (int i = 0; i < n; i++) - c.s[i] = (_Tp)(((w_type)a.s[i] * b.s[i]) >> sizeof(_Tp)*8); - return c; -} - -//! @cond IGNORED -template inline void v_hsum(const v_reg<_Tp, n>& a, - v_reg::w_type, n/2>& c) -{ - typedef typename V_TypeTraits<_Tp>::w_type w_type; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = (w_type)a.s[i*2] + a.s[i*2+1]; - } -} -//! @endcond - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_SHIFT_OP(shift_op, func) \ -template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, int imm) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = (_Tp)(a.s[i] shift_op imm); \ - return c; \ -} - -/** @brief Bitwise shift left - -For 16-, 32- and 64-bit integer values. */ -OPENCV_HAL_IMPL_SHIFT_OP(<<, v_shl) - -/** @brief Bitwise shift right - -For 16-, 32- and 64-bit integer values. */ -OPENCV_HAL_IMPL_SHIFT_OP(>>, v_shr) - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(suffix,opA,opB) \ -template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp, n> b; \ - for (int i = 0; i < n; i++) \ - { \ - int sIndex = i opA imm; \ - if (0 <= sIndex && sIndex < n) \ - { \ - b.s[i] = a.s[sIndex]; \ - } \ - else \ - { \ - b.s[i] = 0; \ - } \ - } \ - return b; \ -} \ -template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tp, n> c; \ - for (int i = 0; i < n; i++) \ - { \ - int aIndex = i opA imm; \ - int bIndex = i opA imm opB n; \ - if (0 <= bIndex && bIndex < n) \ - { \ - c.s[i] = b.s[bIndex]; \ - } \ - else if (0 <= aIndex && aIndex < n) \ - { \ - c.s[i] = a.s[aIndex]; \ - } \ - else \ - { \ - c.s[i] = 0; \ - } \ - } \ - return c; \ -} - -/** @brief Element shift left among vector - -For all type */ -OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(left, -, +) - -/** @brief Element shift right among vector - -For all type */ -OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(right, +, -) - -/** @brief Sum packed values - -Scheme: -@code -{A1 A2 A3 ...} => sum{A1,A2,A3,...} -@endcode -*/ -template inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a) -{ - typename V_TypeTraits<_Tp>::sum_type c = a.s[0]; - for( int i = 1; i < n; i++ ) - c += a.s[i]; - return c; -} - -/** @brief Sums all elements of each input vector, returns the vector of sums - - Scheme: - @code - result[0] = a[0] + a[1] + a[2] + a[3] - result[1] = b[0] + b[1] + b[2] + b[3] - result[2] = c[0] + c[1] + c[2] + c[3] - result[3] = d[0] + d[1] + d[2] + d[3] - @endcode -*/ -template inline v_reg v_reduce_sum4(const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg r; - for(int i = 0; i < (n/4); i++) - { - r.s[i*4 + 0] = a.s[i*4 + 0] + a.s[i*4 + 1] + a.s[i*4 + 2] + a.s[i*4 + 3]; - r.s[i*4 + 1] = b.s[i*4 + 0] + b.s[i*4 + 1] + b.s[i*4 + 2] + b.s[i*4 + 3]; - r.s[i*4 + 2] = c.s[i*4 + 0] + c.s[i*4 + 1] + c.s[i*4 + 2] + c.s[i*4 + 3]; - r.s[i*4 + 3] = d.s[i*4 + 0] + d.s[i*4 + 1] + d.s[i*4 + 2] + d.s[i*4 + 3]; - } - return r; -} - -/** @brief Sum absolute differences of values - -Scheme: -@code -{A1 A2 A3 ...} {B1 B2 B3 ...} => sum{ABS(A1-B1),abs(A2-B2),abs(A3-B3),...} -@endcode -For all types except 64-bit types.*/ -template inline typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type v_reduce_sad(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type c = _absdiff(a.s[0], b.s[0]); - for (int i = 1; i < n; i++) - c += _absdiff(a.s[i], b.s[i]); - return c; -} - -/** @brief Get negative values mask -@deprecated v_signmask depends on a lane count heavily and therefore isn't universal enough - -Returned value is a bit mask with bits set to 1 on places corresponding to negative packed values indexes. -Example: -@code{.cpp} -v_int32x4 r; // set to {-1, -1, 1, 1} -int mask = v_signmask(r); // mask = 3 <== 00000000 00000000 00000000 00000011 -@endcode -*/ -template inline int v_signmask(const v_reg<_Tp, n>& a) -{ - int mask = 0; - for( int i = 0; i < n; i++ ) - mask |= (V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) << i; - return mask; -} - -/** @brief Get first negative lane index - -Returned value is an index of first negative lane (undefined for input of all positive values) -Example: -@code{.cpp} -v_int32x4 r; // set to {0, 0, -1, -1} -int idx = v_heading_zeros(r); // idx = 2 -@endcode -*/ -template inline int v_scan_forward(const v_reg<_Tp, n>& a) -{ - for (int i = 0; i < n; i++) - if(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) - return i; - return 0; -} - -/** @brief Check if all packed values are less than zero - -Unsigned values will be casted to signed: `uchar 254 => char -2`. -*/ -template inline bool v_check_all(const v_reg<_Tp, n>& a) -{ - for( int i = 0; i < n; i++ ) - if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) >= 0 ) - return false; - return true; -} - -/** @brief Check if any of packed values is less than zero - -Unsigned values will be casted to signed: `uchar 254 => char -2`. -*/ -template inline bool v_check_any(const v_reg<_Tp, n>& a) -{ - for( int i = 0; i < n; i++ ) - if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0 ) - return true; - return false; -} - -/** @brief Per-element select (blend operation) - -Return value will be built by combining values _a_ and _b_ using the following scheme: - result[i] = mask[i] ? a[i] : b[i]; - -@note: _mask_ element values are restricted to these values: -- 0: select element from _b_ -- 0xff/0xffff/etc: select element from _a_ -(fully compatible with bitwise-based operator) -*/ -template inline v_reg<_Tp, n> v_select(const v_reg<_Tp, n>& mask, - const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - typedef V_TypeTraits<_Tp> Traits; - typedef typename Traits::int_type int_type; - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - { - int_type m = Traits::reinterpret_int(mask.s[i]); - CV_DbgAssert(m == 0 || m == (~(int_type)0)); // restrict mask values: 0 or 0xff/0xffff/etc - c.s[i] = m ? a.s[i] : b.s[i]; - } - return c; -} - -/** @brief Expand values to the wider pack type - -Copy contents of register to two registers with 2x wider pack type. -Scheme: -@code - int32x4 int64x2 int64x2 -{A B C D} ==> {A B} , {C D} -@endcode */ -template inline void v_expand(const v_reg<_Tp, n>& a, - v_reg::w_type, n/2>& b0, - v_reg::w_type, n/2>& b1) -{ - for( int i = 0; i < (n/2); i++ ) - { - b0.s[i] = a.s[i]; - b1.s[i] = a.s[i+(n/2)]; - } -} - -/** @brief Expand lower values to the wider pack type - -Same as cv::v_expand, but return lower half of the vector. - -Scheme: -@code - int32x4 int64x2 -{A B C D} ==> {A B} -@endcode */ -template -inline v_reg::w_type, n/2> -v_expand_low(const v_reg<_Tp, n>& a) -{ - v_reg::w_type, n/2> b; - for( int i = 0; i < (n/2); i++ ) - b.s[i] = a.s[i]; - return b; -} - -/** @brief Expand higher values to the wider pack type - -Same as cv::v_expand_low, but expand higher half of the vector instead. - -Scheme: -@code - int32x4 int64x2 -{A B C D} ==> {C D} -@endcode */ -template -inline v_reg::w_type, n/2> -v_expand_high(const v_reg<_Tp, n>& a) -{ - v_reg::w_type, n/2> b; - for( int i = 0; i < (n/2); i++ ) - b.s[i] = a.s[i+(n/2)]; - return b; -} - -//! @cond IGNORED -template inline v_reg::int_type, n> - v_reinterpret_as_int(const v_reg<_Tp, n>& a) -{ - v_reg::int_type, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = V_TypeTraits<_Tp>::reinterpret_int(a.s[i]); - return c; -} - -template inline v_reg::uint_type, n> - v_reinterpret_as_uint(const v_reg<_Tp, n>& a) -{ - v_reg::uint_type, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = V_TypeTraits<_Tp>::reinterpret_uint(a.s[i]); - return c; -} -//! @endcond - -/** @brief Interleave two vectors - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} ---------------- - {A1 B1 A2 B2} and {A3 B3 A4 B4} -@endcode -For all types except 64-bit. -*/ -template inline void v_zip( const v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, - v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1 ) -{ - int i; - for( i = 0; i < n/2; i++ ) - { - b0.s[i*2] = a0.s[i]; - b0.s[i*2+1] = a1.s[i]; - } - for( ; i < n; i++ ) - { - b1.s[i*2-n] = a0.s[i]; - b1.s[i*2-n+1] = a1.s[i]; - } -} - -/** @brief Load register contents from memory - -@param ptr pointer to memory block with data -@return register object - -@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc. - -@note Use vx_load version to get maximum available register length result - -@note Alignment requirement: -if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). -Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). - */ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); -} - -#if CV_SIMD256 -/** @brief Load 256-bit length register contents from memory - -@param ptr pointer to memory block with data -@return register object - -@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x32, int ==> cv::v_int32x8, etc. - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load version to get maximum available register length result - -@note Alignment requirement: -if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). -Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). - */ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); -} -#endif - -#if CV_SIMD512 -/** @brief Load 512-bit length register contents from memory - -@param ptr pointer to memory block with data -@return register object - -@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x64, int ==> cv::v_int32x16, etc. - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load version to get maximum available register length result - -@note Alignment requirement: -if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). -Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). - */ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); -} -#endif - -/** @brief Load register contents from memory (aligned) - -similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary in case of SIMD128, 32-byte - SIMD256, etc) - -@note Use vx_load_aligned version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_aligned(const _Tp* ptr) -{ - CV_Assert(isAligned)>(ptr)); - return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); -} - -#if CV_SIMD256 -/** @brief Load register contents from memory (aligned) - -similar to cv::v256_load, but source memory block should be aligned (to 32-byte boundary in case of SIMD256, 64-byte - SIMD512, etc) - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_aligned version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_aligned(const _Tp* ptr) -{ - CV_Assert(isAligned)>(ptr)); - return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from memory (aligned) - -similar to cv::v512_load, but source memory block should be aligned (to 64-byte boundary in case of SIMD512, etc) - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_aligned version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_aligned(const _Tp* ptr) -{ - CV_Assert(isAligned)>(ptr)); - return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); -} -#endif - -/** @brief Load 64-bits of data to lower part (high part is undefined). - -@param ptr memory block containing data for first half (0..n/2) - -@code{.cpp} -int lo[2] = { 1, 2 }; -v_int32x4 r = v_load_low(lo); -@endcode - -@note Use vx_load_low version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_low(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for( int i = 0; i < c.nlanes/2; i++ ) - { - c.s[i] = ptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load 128-bits of data to lower part (high part is undefined). - -@param ptr memory block containing data for first half (0..n/2) - -@code{.cpp} -int lo[4] = { 1, 2, 3, 4 }; -v_int32x8 r = v256_load_low(lo); -@endcode - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_low version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_low(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_reg<_Tp, simd256_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load 256-bits of data to lower part (high part is undefined). - -@param ptr memory block containing data for first half (0..n/2) - -@code{.cpp} -int lo[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; -v_int32x16 r = v512_load_low(lo); -@endcode - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_low version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_low(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_reg<_Tp, simd512_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -/** @brief Load register contents from two memory blocks - -@param loptr memory block containing data for first half (0..n/2) -@param hiptr memory block containing data for second half (n/2..n) - -@code{.cpp} -int lo[2] = { 1, 2 }, hi[2] = { 3, 4 }; -v_int32x4 r = v_load_halves(lo, hi); -@endcode - -@note Use vx_load_halves version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_halves(const _Tp* loptr, const _Tp* hiptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(loptr)); - CV_Assert(isAligned(hiptr)); -#endif - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for( int i = 0; i < c.nlanes/2; i++ ) - { - c.s[i] = loptr[i]; - c.s[i+c.nlanes/2] = hiptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load register contents from two memory blocks - -@param loptr memory block containing data for first half (0..n/2) -@param hiptr memory block containing data for second half (n/2..n) - -@code{.cpp} -int lo[4] = { 1, 2, 3, 4 }, hi[4] = { 5, 6, 7, 8 }; -v_int32x8 r = v256_load_halves(lo, hi); -@endcode - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_halves version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_halves(const _Tp* loptr, const _Tp* hiptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(loptr)); - CV_Assert(isAligned(hiptr)); -#endif - v_reg<_Tp, simd256_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = loptr[i]; - c.s[i + c.nlanes / 2] = hiptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from two memory blocks - -@param loptr memory block containing data for first half (0..n/2) -@param hiptr memory block containing data for second half (n/2..n) - -@code{.cpp} -int lo[4] = { 1, 2, 3, 4, 5, 6, 7, 8 }, hi[4] = { 9, 10, 11, 12, 13, 14, 15, 16 }; -v_int32x16 r = v512_load_halves(lo, hi); -@endcode - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_halves version to get maximum available register length result -*/ -template -inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_halves(const _Tp* loptr, const _Tp* hiptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(loptr)); - CV_Assert(isAligned(hiptr)); -#endif - v_reg<_Tp, simd512_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes / 2; i++) - { - c.s[i] = loptr[i]; - c.s[i + c.nlanes / 2] = hiptr[i]; - } - return c; -} -#endif - -/** @brief Load register contents from memory with double expand - -Same as cv::v_load, but result pack type will be 2x wider than memory type. - -@code{.cpp} -short buf[4] = {1, 2, 3, 4}; // type is int16 -v_int32x4 r = v_load_expand(buf); // r = {1, 2, 3, 4} - type is int32 -@endcode -For 8-, 16-, 32-bit integer source types. - -@note Use vx_load_expand version to get maximum available register length result -*/ -template -inline v_reg::w_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> -v_load_expand(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - { - c.s[i] = ptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load register contents from memory with double expand - -Same as cv::v256_load, but result pack type will be 2x wider than memory type. - -@code{.cpp} -short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int16 -v_int32x8 r = v256_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 -@endcode -For 8-, 16-, 32-bit integer source types. - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_expand version to get maximum available register length result -*/ -template -inline v_reg::w_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> -v256_load_expand(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from memory with double expand - -Same as cv::v512_load, but result pack type will be 2x wider than memory type. - -@code{.cpp} -short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int16 -v_int32x16 r = v512_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 -@endcode -For 8-, 16-, 32-bit integer source types. - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_expand version to get maximum available register length result -*/ -template -inline v_reg::w_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> -v512_load_expand(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::w_type w_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -/** @brief Load register contents from memory with quad expand - -Same as cv::v_load_expand, but result type is 4 times wider than source. -@code{.cpp} -char buf[4] = {1, 2, 3, 4}; // type is int8 -v_int32x4 r = v_load_expand_q(buf); // r = {1, 2, 3, 4} - type is int32 -@endcode -For 8-bit integer source types. - -@note Use vx_load_expand_q version to get maximum available register length result -*/ -template -inline v_reg::q_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> -v_load_expand_q(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg c; - for( int i = 0; i < c.nlanes; i++ ) - { - c.s[i] = ptr[i]; - } - return c; -} - -#if CV_SIMD256 -/** @brief Load register contents from memory with quad expand - -Same as cv::v256_load_expand, but result type is 4 times wider than source. -@code{.cpp} -char buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int8 -v_int32x8 r = v256_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 -@endcode -For 8-bit integer source types. - -@note Check CV_SIMD256 preprocessor definition prior to use. -Use vx_load_expand_q version to get maximum available register length result -*/ -template -inline v_reg::q_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> -v256_load_expand_q(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -#if CV_SIMD512 -/** @brief Load register contents from memory with quad expand - -Same as cv::v512_load_expand, but result type is 4 times wider than source. -@code{.cpp} -char buf[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int8 -v_int32x16 r = v512_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 -@endcode -For 8-bit integer source types. - -@note Check CV_SIMD512 preprocessor definition prior to use. -Use vx_load_expand_q version to get maximum available register length result -*/ -template -inline v_reg::q_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> -v512_load_expand_q(const _Tp* ptr) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - typedef typename V_TypeTraits<_Tp>::q_type q_type; - v_reg c; - for (int i = 0; i < c.nlanes; i++) - { - c.s[i] = ptr[i]; - } - return c; -} -#endif - -/** @brief Load and deinterleave (2 channels) - -Load data from memory deinterleave and store to 2 registers. -Scheme: -@code -{A1 B1 A2 B2 ...} ==> {A1 A2 ...}, {B1 B2 ...} -@endcode -For all types except 64-bit. */ -template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, - v_reg<_Tp, n>& b) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i2; - for( i = i2 = 0; i < n; i++, i2 += 2 ) - { - a.s[i] = ptr[i2]; - b.s[i] = ptr[i2+1]; - } -} - -/** @brief Load and deinterleave (3 channels) - -Load data from memory deinterleave and store to 3 registers. -Scheme: -@code -{A1 B1 C1 A2 B2 C2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} -@endcode -For all types except 64-bit. */ -template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, - v_reg<_Tp, n>& b, v_reg<_Tp, n>& c) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i3; - for( i = i3 = 0; i < n; i++, i3 += 3 ) - { - a.s[i] = ptr[i3]; - b.s[i] = ptr[i3+1]; - c.s[i] = ptr[i3+2]; - } -} - -/** @brief Load and deinterleave (4 channels) - -Load data from memory deinterleave and store to 4 registers. -Scheme: -@code -{A1 B1 C1 D1 A2 B2 C2 D2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} -@endcode -For all types except 64-bit. */ -template -inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, - v_reg<_Tp, n>& b, v_reg<_Tp, n>& c, - v_reg<_Tp, n>& d) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i4; - for( i = i4 = 0; i < n; i++, i4 += 4 ) - { - a.s[i] = ptr[i4]; - b.s[i] = ptr[i4+1]; - c.s[i] = ptr[i4+2]; - d.s[i] = ptr[i4+3]; - } -} - -/** @brief Interleave and store (2 channels) - -Interleave and store data from 2 registers to memory. -Scheme: -@code -{A1 A2 ...}, {B1 B2 ...} ==> {A1 B1 A2 B2 ...} -@endcode -For all types except 64-bit. */ -template -inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, - const v_reg<_Tp, n>& b, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i2; - for( i = i2 = 0; i < n; i++, i2 += 2 ) - { - ptr[i2] = a.s[i]; - ptr[i2+1] = b.s[i]; - } -} - -/** @brief Interleave and store (3 channels) - -Interleave and store data from 3 registers to memory. -Scheme: -@code -{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} ==> {A1 B1 C1 A2 B2 C2 ...} -@endcode -For all types except 64-bit. */ -template -inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, - const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i3; - for( i = i3 = 0; i < n; i++, i3 += 3 ) - { - ptr[i3] = a.s[i]; - ptr[i3+1] = b.s[i]; - ptr[i3+2] = c.s[i]; - } -} - -/** @brief Interleave and store (4 channels) - -Interleave and store data from 4 registers to memory. -Scheme: -@code -{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} -@endcode -For all types except 64-bit. */ -template inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, - const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, - const v_reg<_Tp, n>& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - int i, i4; - for( i = i4 = 0; i < n; i++, i4 += 4 ) - { - ptr[i4] = a.s[i]; - ptr[i4+1] = b.s[i]; - ptr[i4+2] = c.s[i]; - ptr[i4+3] = d.s[i]; - } -} - -/** @brief Store data to memory - -Store register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {A B C D} -@endcode -Pointer can be unaligned. */ -template -inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - for( int i = 0; i < n; i++ ) - ptr[i] = a.s[i]; -} - -template -inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - v_store(ptr, a); -} - -/** @brief Store data to memory (lower half) - -Store lower half of register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {A B} -@endcode */ -template -inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - for( int i = 0; i < (n/2); i++ ) - ptr[i] = a.s[i]; -} - -/** @brief Store data to memory (higher half) - -Store higher half of register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {C D} -@endcode */ -template -inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a) -{ -#if CV_STRONG_ALIGNMENT - CV_Assert(isAligned(ptr)); -#endif - for( int i = 0; i < (n/2); i++ ) - ptr[i] = a.s[i+(n/2)]; -} - -/** @brief Store data to memory (aligned) - -Store register contents to memory. -Scheme: -@code - REG {A B C D} ==> MEM {A B C D} -@endcode -Pointer __should__ be aligned by 16-byte boundary. */ -template -inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a) -{ - CV_Assert(isAligned)>(ptr)); - v_store(ptr, a); -} - -template -inline void v_store_aligned_nocache(_Tp* ptr, const v_reg<_Tp, n>& a) -{ - CV_Assert(isAligned)>(ptr)); - v_store(ptr, a); -} - -template -inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) -{ - CV_Assert(isAligned)>(ptr)); - v_store(ptr, a); -} - -/** @brief Combine vector from first elements of two vectors - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} ---------------- - {A1 A2 B1 B2} -@endcode -For all types except 64-bit. */ -template -inline v_reg<_Tp, n> v_combine_low(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = a.s[i]; - c.s[i+(n/2)] = b.s[i]; - } - return c; -} - -/** @brief Combine vector from last elements of two vectors - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} ---------------- - {A3 A4 B3 B4} -@endcode -For all types except 64-bit. */ -template -inline v_reg<_Tp, n> v_combine_high(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < (n/2); i++ ) - { - c.s[i] = a.s[i+(n/2)]; - c.s[i+(n/2)] = b.s[i+(n/2)]; - } - return c; -} - -/** @brief Combine two vectors from lower and higher parts of two other vectors - -@code{.cpp} -low = cv::v_combine_low(a, b); -high = cv::v_combine_high(a, b); -@endcode */ -template -inline void v_recombine(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, - v_reg<_Tp, n>& low, v_reg<_Tp, n>& high) -{ - for( int i = 0; i < (n/2); i++ ) - { - low.s[i] = a.s[i]; - low.s[i+(n/2)] = b.s[i]; - high.s[i] = a.s[i+(n/2)]; - high.s[i+(n/2)] = b.s[i+(n/2)]; - } -} - -/** @brief Vector reverse order - -Reverse the order of the vector -Scheme: -@code - REG {A1 ... An} ==> REG {An ... A1} -@endcode -For all types. */ -template -inline v_reg<_Tp, n> v_reverse(const v_reg<_Tp, n>& a) -{ - v_reg<_Tp, n> c; - for( int i = 0; i < n; i++ ) - c.s[i] = a.s[n-i-1]; - return c; -} - -/** @brief Vector extract - -Scheme: -@code - {A1 A2 A3 A4} - {B1 B2 B3 B4} -======================== -shift = 1 {A2 A3 A4 B1} -shift = 2 {A3 A4 B1 B2} -shift = 3 {A4 B1 B2 B3} -@endcode -Restriction: 0 <= shift < nlanes - -Usage: -@code -v_int32x4 a, b, c; -c = v_extract<2>(a, b); -@endcode -For all types. */ -template -inline v_reg<_Tp, n> v_extract(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - v_reg<_Tp, n> r; - const int shift = n - s; - int i = 0; - for (; i < shift; ++i) - r.s[i] = a.s[i+s]; - for (; i < n; ++i) - r.s[i] = b.s[i-shift]; - return r; -} - -/** @brief Vector extract - -Scheme: -Return the s-th element of v. -Restriction: 0 <= s < nlanes - -Usage: -@code -v_int32x4 a; -int r; -r = v_extract_n<2>(a); -@endcode -For all types. */ -template -inline _Tp v_extract_n(const v_reg<_Tp, n>& v) -{ - CV_DbgAssert(s >= 0 && s < n); - return v.s[s]; -} - -/** @brief Broadcast i-th element of vector - -Scheme: -@code -{ v[0] v[1] v[2] ... v[SZ] } => { v[i], v[i], v[i] ... v[i] } -@endcode -Restriction: 0 <= i < nlanes -Supported types: 32-bit integers and floats (s32/u32/f32) - */ -template -inline v_reg<_Tp, n> v_broadcast_element(const v_reg<_Tp, n>& a) -{ - CV_DbgAssert(i >= 0 && i < n); - return v_reg<_Tp, n>::all(a.s[i]); -} - -/** @brief Round elements - -Rounds each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_round(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = cvRound(a.s[i]); - return c; -} - -/** @overload */ -template inline v_reg v_round(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvRound(a.s[i]); - c.s[i+n] = cvRound(b.s[i]); - } - return c; -} - -/** @brief Floor elements - -Floor each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_floor(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = cvFloor(a.s[i]); - return c; -} - -/** @brief Ceil elements - -Ceil each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_ceil(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = cvCeil(a.s[i]); - return c; -} - -/** @brief Truncate elements - -Truncate each value. Input type is float vector ==> output type is int vector. -@note Only for floating point types. -*/ -template inline v_reg v_trunc(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = (int)(a.s[i]); - return c; -} - -/** @overload */ -template inline v_reg v_round(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvRound(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @overload */ -template inline v_reg v_floor(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvFloor(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @overload */ -template inline v_reg v_ceil(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = cvCeil(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @overload */ -template inline v_reg v_trunc(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = (int)(a.s[i]); - c.s[i+n] = 0; - } - return c; -} - -/** @brief Convert to float - -Supported input type is cv::v_int32. */ -template inline v_reg v_cvt_f32(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = (float)a.s[i]; - return c; -} - -/** @brief Convert lower half to float - -Supported input type is cv::v_float64. */ -template inline v_reg v_cvt_f32(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = (float)a.s[i]; - c.s[i+n] = 0; - } - return c; -} - -/** @brief Convert to float - -Supported input type is cv::v_float64. */ -template inline v_reg v_cvt_f32(const v_reg& a, const v_reg& b) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - { - c.s[i] = (float)a.s[i]; - c.s[i+n] = (float)b.s[i]; - } - return c; -} - -/** @brief Convert lower half to double - -Supported input type is cv::v_int32. */ -template CV_INLINE v_reg v_cvt_f64(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i]; - return c; -} - -/** @brief Convert to double high part of vector - -Supported input type is cv::v_int32. */ -template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i + (n/2)]; - return c; -} - -/** @brief Convert lower half to double - -Supported input type is cv::v_float32. */ -template CV_INLINE v_reg v_cvt_f64(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i]; - return c; -} - -/** @brief Convert to double high part of vector - -Supported input type is cv::v_float32. */ -template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < (n/2); i++ ) - c.s[i] = (double)a.s[i + (n/2)]; - return c; -} - -/** @brief Convert to double - -Supported input type is cv::v_int64. */ -template CV_INLINE v_reg v_cvt_f64(const v_reg& a) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = (double)a.s[i]; - return c; -} - - -template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut(const _Tp* tab, const int* idx) -{ - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes; i++) - c.s[i] = tab[idx[i]]; - return c; -} -template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_pairs(const _Tp* tab, const int* idx) -{ - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes; i++) - c.s[i] = tab[idx[i / 2] + i % 2]; - return c; -} -template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_quads(const _Tp* tab, const int* idx) -{ - v_reg<_Tp, simd128_width / sizeof(_Tp)> c; - for (int i = 0; i < c.nlanes; i++) - c.s[i] = tab[idx[i / 4] + i % 4]; - return c; -} - -template inline v_reg v_lut(const int* tab, const v_reg& idx) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = tab[idx.s[i]]; - return c; -} - -template inline v_reg v_lut(const unsigned* tab, const v_reg& idx) -{ - v_reg c; - for (int i = 0; i < n; i++) - c.s[i] = tab[idx.s[i]]; - return c; -} - -template inline v_reg v_lut(const float* tab, const v_reg& idx) -{ - v_reg c; - for( int i = 0; i < n; i++ ) - c.s[i] = tab[idx.s[i]]; - return c; -} - -template inline v_reg v_lut(const double* tab, const v_reg& idx) -{ - v_reg c; - for( int i = 0; i < n/2; i++ ) - c.s[i] = tab[idx.s[i]]; - return c; -} - - -template inline void v_lut_deinterleave(const float* tab, const v_reg& idx, - v_reg& x, v_reg& y) -{ - for( int i = 0; i < n; i++ ) - { - int j = idx.s[i]; - x.s[i] = tab[j]; - y.s[i] = tab[j+1]; - } -} - -template inline void v_lut_deinterleave(const double* tab, const v_reg& idx, - v_reg& x, v_reg& y) -{ - for( int i = 0; i < n; i++ ) - { - int j = idx.s[i]; - x.s[i] = tab[j]; - y.s[i] = tab[j+1]; - } -} - -template inline v_reg<_Tp, n> v_interleave_pairs(const v_reg<_Tp, n>& vec) -{ - v_reg<_Tp, n> c; - for (int i = 0; i < n/4; i++) - { - c.s[4*i ] = vec.s[4*i ]; - c.s[4*i+1] = vec.s[4*i+2]; - c.s[4*i+2] = vec.s[4*i+1]; - c.s[4*i+3] = vec.s[4*i+3]; - } - return c; -} - -template inline v_reg<_Tp, n> v_interleave_quads(const v_reg<_Tp, n>& vec) -{ - v_reg<_Tp, n> c; - for (int i = 0; i < n/8; i++) - { - c.s[8*i ] = vec.s[8*i ]; - c.s[8*i+1] = vec.s[8*i+4]; - c.s[8*i+2] = vec.s[8*i+1]; - c.s[8*i+3] = vec.s[8*i+5]; - c.s[8*i+4] = vec.s[8*i+2]; - c.s[8*i+5] = vec.s[8*i+6]; - c.s[8*i+6] = vec.s[8*i+3]; - c.s[8*i+7] = vec.s[8*i+7]; - } - return c; -} - -template inline v_reg<_Tp, n> v_pack_triplets(const v_reg<_Tp, n>& vec) -{ - v_reg<_Tp, n> c; - for (int i = 0; i < n/4; i++) - { - c.s[3*i ] = vec.s[4*i ]; - c.s[3*i+1] = vec.s[4*i+1]; - c.s[3*i+2] = vec.s[4*i+2]; - } - return c; -} - -/** @brief Transpose 4x4 matrix - -Scheme: -@code -a0 {A1 A2 A3 A4} -a1 {B1 B2 B3 B4} -a2 {C1 C2 C3 C4} -a3 {D1 D2 D3 D4} -=============== -b0 {A1 B1 C1 D1} -b1 {A2 B2 C2 D2} -b2 {A3 B3 C3 D3} -b3 {A4 B4 C4 D4} -@endcode -*/ -template -inline void v_transpose4x4( v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, - const v_reg<_Tp, n>& a2, const v_reg<_Tp, n>& a3, - v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1, - v_reg<_Tp, n>& b2, v_reg<_Tp, n>& b3 ) -{ - for (int i = 0; i < n / 4; i++) - { - b0.s[0 + i*4] = a0.s[0 + i*4]; b0.s[1 + i*4] = a1.s[0 + i*4]; - b0.s[2 + i*4] = a2.s[0 + i*4]; b0.s[3 + i*4] = a3.s[0 + i*4]; - b1.s[0 + i*4] = a0.s[1 + i*4]; b1.s[1 + i*4] = a1.s[1 + i*4]; - b1.s[2 + i*4] = a2.s[1 + i*4]; b1.s[3 + i*4] = a3.s[1 + i*4]; - b2.s[0 + i*4] = a0.s[2 + i*4]; b2.s[1 + i*4] = a1.s[2 + i*4]; - b2.s[2 + i*4] = a2.s[2 + i*4]; b2.s[3 + i*4] = a3.s[2 + i*4]; - b3.s[0 + i*4] = a0.s[3 + i*4]; b3.s[1 + i*4] = a1.s[3 + i*4]; - b3.s[2 + i*4] = a2.s[3 + i*4]; b3.s[3 + i*4] = a3.s[3 + i*4]; - } -} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_INIT_ZERO(_Tpvec, prefix, suffix) \ -inline _Tpvec prefix##_setzero_##suffix() { return _Tpvec::zero(); } \ -template <> inline _Tpvec v_setzero_() { return _Tpvec::zero(); } - -//! @name Init with zero -//! @{ -//! @brief Create new vector with zero elements -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x16, v, u8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x16, v, s8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x8, v, u16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x8, v, s16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x4, v, u32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x4, v, s32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x4, v, f32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x2, v, f64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x2, v, u64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x2, v, s64) - -#if CV_SIMD256 -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x32, v256, u8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x32, v256, s8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x16, v256, u16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x16, v256, s16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x8, v256, u32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x8, v256, s32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x8, v256, f32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x4, v256, f64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x4, v256, u64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x4, v256, s64) -#endif - -#if CV_SIMD512 -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x64, v512, u8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x64, v512, s8) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x32, v512, u16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x32, v512, s16) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x16, v512, u32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x16, v512, s32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x16, v512, f32) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x8, v512, f64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x8, v512, u64) -OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x8, v512, s64) -#endif -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_INIT_VAL(_Tpvec, _Tp, prefix, suffix) \ -inline _Tpvec prefix##_setall_##suffix(_Tp val) { return _Tpvec::all(val); } \ -template <> inline _Tpvec v_setall_(_Tp val) { return _Tpvec::all(val); } - -//! @name Init with value -//! @{ -//! @brief Create new vector with elements set to a specific value -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x16, uchar, v, u8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x16, schar, v, s8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x8, ushort, v, u16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x8, short, v, s16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x4, unsigned, v, u32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x4, int, v, s32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x4, float, v, f32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x2, double, v, f64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x2, uint64, v, u64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x2, int64, v, s64) - -#if CV_SIMD256 -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x32, uchar, v256, u8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x32, schar, v256, s8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x16, ushort, v256, u16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x16, short, v256, s16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x8, unsigned, v256, u32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x8, int, v256, s32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x8, float, v256, f32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x4, double, v256, f64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x4, uint64, v256, u64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x4, int64, v256, s64) -#endif - -#if CV_SIMD512 -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x64, uchar, v512, u8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x64, schar, v512, s8) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x32, ushort, v512, u16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x32, short, v512, s16) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x16, unsigned, v512, u32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x16, int, v512, s32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x16, float, v512, f32) -OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x8, double, v512, f64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x8, uint64, v512, u64) -OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x8, int64, v512, s64) -#endif -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_REINTERPRET(_Tp, suffix) \ -template inline v_reg<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)> \ - v_reinterpret_as_##suffix(const v_reg<_Tp0, n0>& a) \ -{ return a.template reinterpret_as<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)>(); } - -//! @name Reinterpret -//! @{ -//! @brief Convert vector to different type without modifying underlying data. -OPENCV_HAL_IMPL_C_REINTERPRET(uchar, u8) -OPENCV_HAL_IMPL_C_REINTERPRET(schar, s8) -OPENCV_HAL_IMPL_C_REINTERPRET(ushort, u16) -OPENCV_HAL_IMPL_C_REINTERPRET(short, s16) -OPENCV_HAL_IMPL_C_REINTERPRET(unsigned, u32) -OPENCV_HAL_IMPL_C_REINTERPRET(int, s32) -OPENCV_HAL_IMPL_C_REINTERPRET(float, f32) -OPENCV_HAL_IMPL_C_REINTERPRET(double, f64) -OPENCV_HAL_IMPL_C_REINTERPRET(uint64, u64) -OPENCV_HAL_IMPL_C_REINTERPRET(int64, s64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_SHIFTL(_Tp) \ -template inline v_reg<_Tp, n> v_shl(const v_reg<_Tp, n>& a) \ -{ return v_shl(a, shift); } - -//! @name Left shift -//! @{ -//! @brief Shift left -OPENCV_HAL_IMPL_C_SHIFTL(ushort) -OPENCV_HAL_IMPL_C_SHIFTL(short) -OPENCV_HAL_IMPL_C_SHIFTL(unsigned) -OPENCV_HAL_IMPL_C_SHIFTL(int) -OPENCV_HAL_IMPL_C_SHIFTL(uint64) -OPENCV_HAL_IMPL_C_SHIFTL(int64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_SHIFTR(_Tp) \ -template inline v_reg<_Tp, n> v_shr(const v_reg<_Tp, n>& a) \ -{ return v_shr(a, shift); } - -//! @name Right shift -//! @{ -//! @brief Shift right -OPENCV_HAL_IMPL_C_SHIFTR(ushort) -OPENCV_HAL_IMPL_C_SHIFTR(short) -OPENCV_HAL_IMPL_C_SHIFTR(unsigned) -OPENCV_HAL_IMPL_C_SHIFTR(int) -OPENCV_HAL_IMPL_C_SHIFTR(uint64) -OPENCV_HAL_IMPL_C_SHIFTR(int64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_RSHIFTR(_Tp) \ -template inline v_reg<_Tp, n> v_rshr(const v_reg<_Tp, n>& a) \ -{ \ - v_reg<_Tp, n> c; \ - for( int i = 0; i < n; i++ ) \ - c.s[i] = (_Tp)((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ - return c; \ -} - -//! @name Rounding shift -//! @{ -//! @brief Rounding shift right -OPENCV_HAL_IMPL_C_RSHIFTR(ushort) -OPENCV_HAL_IMPL_C_RSHIFTR(short) -OPENCV_HAL_IMPL_C_RSHIFTR(unsigned) -OPENCV_HAL_IMPL_C_RSHIFTR(int) -OPENCV_HAL_IMPL_C_RSHIFTR(uint64) -OPENCV_HAL_IMPL_C_RSHIFTR(int64) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_PACK(_Tp, _Tpn, pack_suffix, cast) \ -template inline v_reg<_Tpn, 2*n> v_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tpn, 2*n> c; \ - for( int i = 0; i < n; i++ ) \ - { \ - c.s[i] = cast<_Tpn>(a.s[i]); \ - c.s[i+n] = cast<_Tpn>(b.s[i]); \ - } \ - return c; \ -} - -//! @name Pack -//! @{ -//! @brief Pack values from two vectors to one -//! -//! Return vector type have twice more elements than input vector types. Variant with _u_ suffix also -//! converts to corresponding unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_PACK(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_PACK(int, ushort, pack_u, saturate_cast) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_RSHR_PACK(_Tp, _Tpn, pack_suffix, cast) \ -template inline v_reg<_Tpn, 2*n> v_rshr_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ -{ \ - v_reg<_Tpn, 2*n> c; \ - for( int i = 0; i < n; i++ ) \ - { \ - c.s[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ - c.s[i+n] = cast<_Tpn>((b.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ - } \ - return c; \ -} - -//! @name Pack with rounding shift -//! @{ -//! @brief Pack values from two vectors to one with rounding shift -//! -//! Values from the input vectors will be shifted right by _n_ bits with rounding, converted to narrower -//! type and returned in the result vector. Variant with _u_ suffix converts to unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_RSHR_PACK(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK(int, ushort, pack_u, saturate_cast) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ -template inline void v_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ -{ \ - for( int i = 0; i < n; i++ ) \ - ptr[i] = cast<_Tpn>(a.s[i]); \ -} - -//! @name Pack and store -//! @{ -//! @brief Store values from the input vector into memory with pack -//! -//! Values will be stored into memory with conversion to narrower type. -//! Variant with _u_ suffix converts to corresponding unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_PACK_STORE(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_PACK_STORE(int, ushort, pack_u, saturate_cast) -//! @} - -//! @brief Helper macro -//! @ingroup core_hal_intrin_impl -#define OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ -template inline void v_rshr_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ -{ \ - for( int i = 0; i < n; i++ ) \ - ptr[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ -} - -//! @name Pack and store with rounding shift -//! @{ -//! @brief Store values from the input vector into memory with pack -//! -//! Values will be shifted _n_ bits right with rounding, converted to narrower type and stored into -//! memory. Variant with _u_ suffix converts to unsigned type. -//! -//! - pack: for 16-, 32- and 64-bit integer input types -//! - pack_u: for 16- and 32-bit signed integer input types -//! -//! @note All variants except 64-bit use saturation. -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(ushort, uchar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, schar, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(unsigned, ushort, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, short, pack, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(uint64, unsigned, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int64, int, pack, static_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, uchar, pack_u, saturate_cast) -OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, ushort, pack_u, saturate_cast) -//! @} - -//! @cond IGNORED -template -inline void _pack_b(_Tpm* mptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) -{ - for (int i = 0; i < n; ++i) - { - mptr[i] = (_Tpm)a.s[i]; - mptr[i + n] = (_Tpm)b.s[i]; - } -} -//! @endcond - -//! @name Pack boolean values -//! @{ -//! @brief Pack boolean values from multiple vectors to one unsigned 8-bit integer vector -//! -//! @note Must provide valid boolean values to guarantee same result for all architectures. - -/** @brief -//! For 16-bit boolean values - -Scheme: -@code -a {0xFFFF 0 0 0xFFFF 0 0xFFFF 0xFFFF 0} -b {0xFFFF 0 0xFFFF 0 0 0xFFFF 0 0xFFFF} -=============== -{ - 0xFF 0 0 0xFF 0 0xFF 0xFF 0 - 0xFF 0 0xFF 0 0 0xFF 0 0xFF -} -@endcode */ - -template inline v_reg v_pack_b(const v_reg& a, const v_reg& b) -{ - v_reg mask; - _pack_b(mask.s, a, b); - return mask; -} - -/** @overload -For 32-bit boolean values - -Scheme: -@code -a {0xFFFF.. 0 0 0xFFFF..} -b {0 0xFFFF.. 0xFFFF.. 0} -c {0xFFFF.. 0 0xFFFF.. 0} -d {0 0xFFFF.. 0 0xFFFF..} -=============== -{ - 0xFF 0 0 0xFF 0 0xFF 0xFF 0 - 0xFF 0 0xFF 0 0 0xFF 0 0xFF -} -@endcode */ - -template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg mask; - _pack_b(mask.s, a, b); - _pack_b(mask.s + 2*n, c, d); - return mask; -} - -/** @overload -For 64-bit boolean values - -Scheme: -@code -a {0xFFFF.. 0} -b {0 0xFFFF..} -c {0xFFFF.. 0} -d {0 0xFFFF..} - -e {0xFFFF.. 0} -f {0xFFFF.. 0} -g {0 0xFFFF..} -h {0 0xFFFF..} -=============== -{ - 0xFF 0 0 0xFF 0xFF 0 0 0xFF - 0xFF 0 0xFF 0 0 0xFF 0 0xFF -} -@endcode */ -template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d, - const v_reg& e, const v_reg& f, - const v_reg& g, const v_reg& h) -{ - v_reg mask; - _pack_b(mask.s, a, b); - _pack_b(mask.s + 2*n, c, d); - _pack_b(mask.s + 4*n, e, f); - _pack_b(mask.s + 6*n, g, h); - return mask; -} -//! @} - -/** @brief Matrix multiplication - -Scheme: -@code -{A0 A1 A2 A3} |V0| -{B0 B1 B2 B3} |V1| -{C0 C1 C2 C3} |V2| -{D0 D1 D2 D3} x |V3| -==================== -{R0 R1 R2 R3}, where: -R0 = A0V0 + B0V1 + C0V2 + D0V3, -R1 = A1V0 + B1V1 + C1V2 + D1V3 -... -@endcode -*/ -template -inline v_reg v_matmul(const v_reg& v, - const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg res; - for (int i = 0; i < n / 4; i++) - { - res.s[0 + i*4] = v.s[0 + i*4] * a.s[0 + i*4] + v.s[1 + i*4] * b.s[0 + i*4] + v.s[2 + i*4] * c.s[0 + i*4] + v.s[3 + i*4] * d.s[0 + i*4]; - res.s[1 + i*4] = v.s[0 + i*4] * a.s[1 + i*4] + v.s[1 + i*4] * b.s[1 + i*4] + v.s[2 + i*4] * c.s[1 + i*4] + v.s[3 + i*4] * d.s[1 + i*4]; - res.s[2 + i*4] = v.s[0 + i*4] * a.s[2 + i*4] + v.s[1 + i*4] * b.s[2 + i*4] + v.s[2 + i*4] * c.s[2 + i*4] + v.s[3 + i*4] * d.s[2 + i*4]; - res.s[3 + i*4] = v.s[0 + i*4] * a.s[3 + i*4] + v.s[1 + i*4] * b.s[3 + i*4] + v.s[2 + i*4] * c.s[3 + i*4] + v.s[3 + i*4] * d.s[3 + i*4]; - } - return res; -} - -/** @brief Matrix multiplication and add - -Scheme: -@code -{A0 A1 A2 A3} |V0| |D0| -{B0 B1 B2 B3} |V1| |D1| -{C0 C1 C2 C3} x |V2| + |D2| -==================== |D3| -{R0 R1 R2 R3}, where: -R0 = A0V0 + B0V1 + C0V2 + D0, -R1 = A1V0 + B1V1 + C1V2 + D1 -... -@endcode -*/ -template -inline v_reg v_matmuladd(const v_reg& v, - const v_reg& a, const v_reg& b, - const v_reg& c, const v_reg& d) -{ - v_reg res; - for (int i = 0; i < n / 4; i++) - { - res.s[0 + i * 4] = v.s[0 + i * 4] * a.s[0 + i * 4] + v.s[1 + i * 4] * b.s[0 + i * 4] + v.s[2 + i * 4] * c.s[0 + i * 4] + d.s[0 + i * 4]; - res.s[1 + i * 4] = v.s[0 + i * 4] * a.s[1 + i * 4] + v.s[1 + i * 4] * b.s[1 + i * 4] + v.s[2 + i * 4] * c.s[1 + i * 4] + d.s[1 + i * 4]; - res.s[2 + i * 4] = v.s[0 + i * 4] * a.s[2 + i * 4] + v.s[1 + i * 4] * b.s[2 + i * 4] + v.s[2 + i * 4] * c.s[2 + i * 4] + d.s[2 + i * 4]; - res.s[3 + i * 4] = v.s[0 + i * 4] * a.s[3 + i * 4] + v.s[1 + i * 4] * b.s[3 + i * 4] + v.s[2 + i * 4] * c.s[3 + i * 4] + d.s[3 + i * 4]; - } - return res; -} - - -template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } -template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b, - const v_reg& c) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } - -template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b) -{ return v_dotprod_expand(a, b); } -template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b, - const v_reg& c) -{ return v_dotprod_expand(a, b, c); } - -////// FP16 support /////// - -inline v_reg -v_load_expand(const hfloat* ptr) -{ - v_reg v; - for( int i = 0; i < v.nlanes; i++ ) - { - v.s[i] = ptr[i]; - } - return v; -} -#if CV_SIMD256 -inline v_reg -v256_load_expand(const hfloat* ptr) -{ - v_reg v; - for (int i = 0; i < v.nlanes; i++) - { - v.s[i] = ptr[i]; - } - return v; -} -#endif -#if CV_SIMD512 -inline v_reg -v512_load_expand(const hfloat* ptr) -{ - v_reg v; - for (int i = 0; i < v.nlanes; i++) - { - v.s[i] = ptr[i]; - } - return v; -} -#endif - -template inline void -v_pack_store(hfloat* ptr, const v_reg& v) -{ - for( int i = 0; i < v.nlanes; i++ ) - { - ptr[i] = hfloat(v.s[i]); - } -} - -inline void v_cleanup() {} -#if CV_SIMD256 -inline void v256_cleanup() {} -#endif -#if CV_SIMD512 -inline void v512_cleanup() {} -#endif - -//! @} - -#ifndef CV_DOXYGEN -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END -#endif -} - -#if !defined(CV_DOXYGEN) -#undef CV_SIMD256 -#undef CV_SIMD512 -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HAL_INTRIN_CPP_HPP +#define OPENCV_HAL_INTRIN_CPP_HPP + +#include +#include +#include +#include "opencv2/core/utility.hpp" +#include "opencv2/core/saturate.hpp" + +//! @cond IGNORED +#define CV_SIMD128_CPP 1 +#if defined(CV_FORCE_SIMD128_CPP) +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#endif +#if defined(CV_DOXYGEN) +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#define CV_SIMD256 1 +#define CV_SIMD256_64F 1 +#define CV_SIMD512 1 +#define CV_SIMD512_64F 1 +#else +#define CV_SIMD256 0 // Explicitly disable SIMD256 and SIMD512 support for scalar intrinsic implementation +#define CV_SIMD512 0 // to avoid warnings during compilation +#endif +//! @endcond + +namespace cv +{ + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN +#endif + +/** @addtogroup core_hal_intrin + +"Universal intrinsics" is a types and functions set intended to simplify vectorization of code on +different platforms. Currently a few different SIMD extensions on different architectures are supported. +128 bit registers of various types support is implemented for a wide range of architectures +including x86(__SSE/SSE2/SSE4.2__), ARM(__NEON__), PowerPC(__VSX__), MIPS(__MSA__). +256 bit long registers are supported on x86(__AVX2__) and 512 bit long registers are supported on x86(__AVX512__). +In case when there is no SIMD extension available during compilation, fallback C++ implementation of intrinsics +will be chosen and code will work as expected although it could be slower. + +### Types + +There are several types representing packed values vector registers, each type is +implemented as a structure based on a one SIMD register. + +- cv::v_uint8 and cv::v_int8: 8-bit integer values (unsigned/signed) - char +- cv::v_uint16 and cv::v_int16: 16-bit integer values (unsigned/signed) - short +- cv::v_uint32 and cv::v_int32: 32-bit integer values (unsigned/signed) - int +- cv::v_uint64 and cv::v_int64: 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32: 32-bit floating point values (signed) - float +- cv::v_float64: 64-bit floating point values (signed) - double + +Exact bit length(and value quantity) of listed types is compile time deduced and depends on architecture SIMD +capabilities chosen as available during compilation of the library. All the types contains __nlanes__ enumeration +to check for exact value quantity of the type. + +In case the exact bit length of the type is important it is possible to use specific fixed length register types. + +There are several types representing 128-bit registers. + +- cv::v_uint8x16 and cv::v_int8x16: sixteen 8-bit integer values (unsigned/signed) - char +- cv::v_uint16x8 and cv::v_int16x8: eight 16-bit integer values (unsigned/signed) - short +- cv::v_uint32x4 and cv::v_int32x4: four 32-bit integer values (unsigned/signed) - int +- cv::v_uint64x2 and cv::v_int64x2: two 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32x4: four 32-bit floating point values (signed) - float +- cv::v_float64x2: two 64-bit floating point values (signed) - double + +There are several types representing 256-bit registers. + +- cv::v_uint8x32 and cv::v_int8x32: thirty two 8-bit integer values (unsigned/signed) - char +- cv::v_uint16x16 and cv::v_int16x16: sixteen 16-bit integer values (unsigned/signed) - short +- cv::v_uint32x8 and cv::v_int32x8: eight 32-bit integer values (unsigned/signed) - int +- cv::v_uint64x4 and cv::v_int64x4: four 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32x8: eight 32-bit floating point values (signed) - float +- cv::v_float64x4: four 64-bit floating point values (signed) - double + +@note +256 bit registers at the moment implemented for AVX2 SIMD extension only, if you want to use this type directly, +don't forget to check the CV_SIMD256 preprocessor definition: +@code +#if CV_SIMD256 +//... +#endif +@endcode + +There are several types representing 512-bit registers. + +- cv::v_uint8x64 and cv::v_int8x64: sixty four 8-bit integer values (unsigned/signed) - char +- cv::v_uint16x32 and cv::v_int16x32: thirty two 16-bit integer values (unsigned/signed) - short +- cv::v_uint32x16 and cv::v_int32x16: sixteen 32-bit integer values (unsigned/signed) - int +- cv::v_uint64x8 and cv::v_int64x8: eight 64-bit integer values (unsigned/signed) - int64 +- cv::v_float32x16: sixteen 32-bit floating point values (signed) - float +- cv::v_float64x8: eight 64-bit floating point values (signed) - double +@note +512 bit registers at the moment implemented for AVX512 SIMD extension only, if you want to use this type directly, +don't forget to check the CV_SIMD512 preprocessor definition. + +@note +cv::v_float64x2 is not implemented in NEON variant, if you want to use this type, don't forget to +check the CV_SIMD128_64F preprocessor definition. + +### Load and store operations + +These operations allow to set contents of the register explicitly or by loading it from some memory +block and to save contents of the register to memory block. + +There are variable size register load operations that provide result of maximum available size +depending on chosen platform capabilities. +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +- Other create methods: +vx_setall_s8, vx_setall_u8, ..., +vx_setzero_u8, vx_setzero_s8, ... +- Memory load operations: +vx_load, vx_load_aligned, vx_load_low, vx_load_halves, +- Memory operations with expansion of values: +vx_load_expand, vx_load_expand_q + +Also there are fixed size register load/store operations. + +For 128 bit registers +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +@ref v_reg::v_reg(_Tp s0, _Tp s1) "from two values", ... +- Other create methods: +@ref v_setall_s8, @ref v_setall_u8, ..., +@ref v_setzero_u8, @ref v_setzero_s8, ... +- Memory load operations: +@ref v_load, @ref v_load_aligned, @ref v_load_low, @ref v_load_halves, +- Memory operations with expansion of values: +@ref v_load_expand, @ref v_load_expand_q + +For 256 bit registers(check CV_SIMD256 preprocessor definition) +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) "from four values", ... +- Other create methods: +@ref v256_setall_s8, @ref v256_setall_u8, ..., +@ref v256_setzero_u8, @ref v256_setzero_s8, ... +- Memory load operations: +@ref v256_load, @ref v256_load_aligned, @ref v256_load_low, @ref v256_load_halves, +- Memory operations with expansion of values: +@ref v256_load_expand, @ref v256_load_expand_q + +For 512 bit registers(check CV_SIMD512 preprocessor definition) +- Constructors: +@ref v_reg::v_reg(const _Tp *ptr) "from memory", +@ref v_reg::v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, _Tp s4, _Tp s5, _Tp s6, _Tp s7) "from eight values", ... +- Other create methods: +@ref v512_setall_s8, @ref v512_setall_u8, ..., +@ref v512_setzero_u8, @ref v512_setzero_s8, ... +- Memory load operations: +@ref v512_load, @ref v512_load_aligned, @ref v512_load_low, @ref v512_load_halves, +- Memory operations with expansion of values: +@ref v512_load_expand, @ref v512_load_expand_q + +Store to memory operations are similar across different platform capabilities: +@ref v_store, @ref v_store_aligned, +@ref v_store_high, @ref v_store_low + +### Value reordering + +These operations allow to reorder or recombine elements in one or multiple vectors. + +- Interleave, deinterleave (2, 3 and 4 channels): @ref v_load_deinterleave, @ref v_store_interleave +- Expand: @ref v_expand, @ref v_expand_low, @ref v_expand_high +- Pack: @ref v_pack, @ref v_pack_u, @ref v_pack_b, @ref v_rshr_pack, @ref v_rshr_pack_u, +@ref v_pack_store, @ref v_pack_u_store, @ref v_rshr_pack_store, @ref v_rshr_pack_u_store +- Recombine: @ref v_zip, @ref v_recombine, @ref v_combine_low, @ref v_combine_high +- Reverse: @ref v_reverse +- Extract: @ref v_extract + + +### Arithmetic, bitwise and comparison operations + +Element-wise binary and unary operations. + +- Arithmetics: +@ref v_add(const v_reg &a, const v_reg &b) "+", +@ref v_sub(const v_reg &a, const v_reg &b) "-", +@ref v_mul(const v_reg &a, const v_reg &b) "*", +@ref v_div(const v_reg &a, const v_reg &b) "/", +@ref v_mul_expand + +- Non-saturating arithmetics: @ref v_add_wrap, @ref v_sub_wrap + +- Bitwise shifts: +@ref v_shl(const v_reg &a, int s) "<<", +@ref v_shr(const v_reg &a, int s) ">>", +@ref v_shl, @ref v_shr + +- Bitwise logic: +@ref v_and(const v_reg &a, const v_reg &b) "&", +@ref v_or(const v_reg &a, const v_reg &b) "|", +@ref v_xor(const v_reg &a, const v_reg &b) "^", +@ref v_not(const v_reg &a) "~" + +- Comparison: +@ref v_gt(const v_reg &a, const v_reg &b) ">", +@ref v_ge(const v_reg &a, const v_reg &b) ">=", +@ref v_lt(const v_reg &a, const v_reg &b) "<", +@ref v_le(const v_reg &a, const v_reg &b) "<=", +@ref v_eq(const v_reg &a, const v_reg &b) "==", +@ref v_ne(const v_reg &a, const v_reg &b) "!=" + +- min/max: @ref v_min, @ref v_max + +### Reduce and mask + +Most of these operations return only one value. + +- Reduce: @ref v_reduce_min, @ref v_reduce_max, @ref v_reduce_sum, @ref v_popcount +- Mask: @ref v_signmask, @ref v_check_all, @ref v_check_any, @ref v_select + +### Other math + +- Some frequent operations: @ref v_sqrt, @ref v_invsqrt, @ref v_magnitude, @ref v_sqr_magnitude, @ref v_exp, @ref v_log, + @ref v_erf, @ref v_sin, @ref v_cos +- Absolute values: @ref v_abs, @ref v_absdiff, @ref v_absdiffs + +### Conversions + +Different type conversions and casts: + +- Rounding: @ref v_round, @ref v_floor, @ref v_ceil, @ref v_trunc, +- To float: @ref v_cvt_f32, @ref v_cvt_f64 +- Reinterpret: @ref v_reinterpret_as_u8, @ref v_reinterpret_as_s8, ... + +### Matrix operations + +In these operations vectors represent matrix rows/columns: @ref v_dotprod, @ref v_dotprod_fast, +@ref v_dotprod_expand, @ref v_dotprod_expand_fast, @ref v_matmul, @ref v_transpose4x4 + +### Usability + +Most operations are implemented only for some subset of the available types, following matrices +shows the applicability of different operations to the types. + +Regular integers: + +| Operations\\Types | uint 8 | int 8 | uint 16 | int 16 | uint 32 | int 32 | +|-------------------|:-:|:-:|:-:|:-:|:-:|:-:| +|load, store | x | x | x | x | x | x | +|interleave | x | x | x | x | x | x | +|expand | x | x | x | x | x | x | +|expand_low | x | x | x | x | x | x | +|expand_high | x | x | x | x | x | x | +|expand_q | x | x | | | | | +|add, sub | x | x | x | x | x | x | +|add_wrap, sub_wrap | x | x | x | x | | | +|mul_wrap | x | x | x | x | | | +|mul | x | x | x | x | x | x | +|mul_expand | x | x | x | x | x | | +|compare | x | x | x | x | x | x | +|shift | | | x | x | x | x | +|dotprod | | | | x | | x | +|dotprod_fast | | | | x | | x | +|dotprod_expand | x | x | x | x | | x | +|dotprod_expand_fast| x | x | x | x | | x | +|logical | x | x | x | x | x | x | +|min, max | x | x | x | x | x | x | +|absdiff | x | x | x | x | x | x | +|absdiffs | | x | | x | | | +|reduce | x | x | x | x | x | x | +|mask | x | x | x | x | x | x | +|pack | x | x | x | x | x | x | +|pack_u | x | | x | | | | +|pack_b | x | | | | | | +|unpack | x | x | x | x | x | x | +|extract | x | x | x | x | x | x | +|rotate (lanes) | x | x | x | x | x | x | +|cvt_flt32 | | | | | | x | +|cvt_flt64 | | | | | | x | +|transpose4x4 | | | | | x | x | +|reverse | x | x | x | x | x | x | +|extract_n | x | x | x | x | x | x | +|broadcast_element | | | | | x | x | + +Big integers: + +| Operations\\Types | uint 64 | int 64 | +|-------------------|:-:|:-:| +|load, store | x | x | +|add, sub | x | x | +|shift | x | x | +|logical | x | x | +|reverse | x | x | +|extract | x | x | +|rotate (lanes) | x | x | +|cvt_flt64 | | x | +|extract_n | x | x | + +Floating point: + +| Operations\\Types | float 32 | float 64 | +|-------------------|:-:|:-:| +|load, store | x | x | +|interleave | x | | +|add, sub | x | x | +|mul | x | x | +|div | x | x | +|compare | x | x | +|min, max | x | x | +|absdiff | x | x | +|reduce | x | | +|mask | x | x | +|unpack | x | x | +|cvt_flt32 | | x | +|cvt_flt64 | x | | +|sqrt, abs | x | x | +|float math | x | x | +|transpose4x4 | x | | +|extract | x | x | +|rotate (lanes) | x | x | +|reverse | x | x | +|extract_n | x | x | +|broadcast_element | x | | +|exp | x | x | +|log | x | x | +|sin, cos | x | x | + + @{ */ + +template struct v_reg +{ +//! @cond IGNORED + typedef _Tp lane_type; + enum { nlanes = n }; +// !@endcond + + /** @brief Constructor + + Initializes register with data from memory + @param ptr pointer to memory block with data for register */ + explicit v_reg(const _Tp* ptr) { for( int i = 0; i < n; i++ ) s[i] = ptr[i]; } + + /** @brief Constructor + + Initializes register with two 64-bit values */ + v_reg(_Tp s0, _Tp s1) { s[0] = s0; s[1] = s1; } + + /** @brief Constructor + + Initializes register with four 32-bit values */ + v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3) { s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; } + + /** @brief Constructor + + Initializes register with eight 16-bit values */ + v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, + _Tp s4, _Tp s5, _Tp s6, _Tp s7) + { + s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; + s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; + } + + /** @brief Constructor + + Initializes register with sixteen 8-bit values */ + v_reg(_Tp s0, _Tp s1, _Tp s2, _Tp s3, + _Tp s4, _Tp s5, _Tp s6, _Tp s7, + _Tp s8, _Tp s9, _Tp s10, _Tp s11, + _Tp s12, _Tp s13, _Tp s14, _Tp s15) + { + s[0] = s0; s[1] = s1; s[2] = s2; s[3] = s3; + s[4] = s4; s[5] = s5; s[6] = s6; s[7] = s7; + s[8] = s8; s[9] = s9; s[10] = s10; s[11] = s11; + s[12] = s12; s[13] = s13; s[14] = s14; s[15] = s15; + } + + /** @brief Default constructor + + Does not initialize anything*/ + v_reg() {} + + /** @brief Copy constructor */ + v_reg(const v_reg<_Tp, n> & r) + { + for( int i = 0; i < n; i++ ) + s[i] = r.s[i]; + } + /** @brief Access first value + + Returns value of the first lane according to register type, for example: + @code{.cpp} + v_int32x4 r(1, 2, 3, 4); + int v = r.get0(); // returns 1 + v_uint64x2 r(1, 2); + uint64_t v = r.get0(); // returns 1 + @endcode + */ + _Tp get0() const { return s[0]; } + +//! @cond IGNORED + _Tp get(const int i) const { return s[i]; } + v_reg<_Tp, n> high() const + { + v_reg<_Tp, n> c; + int i; + for( i = 0; i < n/2; i++ ) + { + c.s[i] = s[i+(n/2)]; + c.s[i+(n/2)] = 0; + } + return c; + } + + static v_reg<_Tp, n> zero() + { + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = (_Tp)0; + return c; + } + + static v_reg<_Tp, n> all(_Tp s) + { + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = s; + return c; + } + + template v_reg<_Tp2, n2> reinterpret_as() const + { + size_t bytes = std::min(sizeof(_Tp2)*n2, sizeof(_Tp)*n); + v_reg<_Tp2, n2> c; + std::memcpy(&c.s[0], &s[0], bytes); + return c; + } + + v_reg& operator=(const v_reg<_Tp, n> & r) + { + for( int i = 0; i < n; i++ ) + s[i] = r.s[i]; + return *this; + } + + _Tp s[n]; +//! @endcond +}; + +/** @brief Sixteen 8-bit unsigned integer values */ +typedef v_reg v_uint8x16; +/** @brief Sixteen 8-bit signed integer values */ +typedef v_reg v_int8x16; +/** @brief Eight 16-bit unsigned integer values */ +typedef v_reg v_uint16x8; +/** @brief Eight 16-bit signed integer values */ +typedef v_reg v_int16x8; +/** @brief Four 32-bit unsigned integer values */ +typedef v_reg v_uint32x4; +/** @brief Four 32-bit signed integer values */ +typedef v_reg v_int32x4; +/** @brief Four 32-bit floating point values (single precision) */ +typedef v_reg v_float32x4; +/** @brief Two 64-bit floating point values (double precision) */ +typedef v_reg v_float64x2; +/** @brief Two 64-bit unsigned integer values */ +typedef v_reg v_uint64x2; +/** @brief Two 64-bit signed integer values */ +typedef v_reg v_int64x2; + +#if CV_SIMD256 +/** @brief Thirty two 8-bit unsigned integer values */ +typedef v_reg v_uint8x32; +/** @brief Thirty two 8-bit signed integer values */ +typedef v_reg v_int8x32; +/** @brief Sixteen 16-bit unsigned integer values */ +typedef v_reg v_uint16x16; +/** @brief Sixteen 16-bit signed integer values */ +typedef v_reg v_int16x16; +/** @brief Eight 32-bit unsigned integer values */ +typedef v_reg v_uint32x8; +/** @brief Eight 32-bit signed integer values */ +typedef v_reg v_int32x8; +/** @brief Eight 32-bit floating point values (single precision) */ +typedef v_reg v_float32x8; +/** @brief Four 64-bit floating point values (double precision) */ +typedef v_reg v_float64x4; +/** @brief Four 64-bit unsigned integer values */ +typedef v_reg v_uint64x4; +/** @brief Four 64-bit signed integer values */ +typedef v_reg v_int64x4; +#endif + +#if CV_SIMD512 +/** @brief Sixty four 8-bit unsigned integer values */ +typedef v_reg v_uint8x64; +/** @brief Sixty four 8-bit signed integer values */ +typedef v_reg v_int8x64; +/** @brief Thirty two 16-bit unsigned integer values */ +typedef v_reg v_uint16x32; +/** @brief Thirty two 16-bit signed integer values */ +typedef v_reg v_int16x32; +/** @brief Sixteen 32-bit unsigned integer values */ +typedef v_reg v_uint32x16; +/** @brief Sixteen 32-bit signed integer values */ +typedef v_reg v_int32x16; +/** @brief Sixteen 32-bit floating point values (single precision) */ +typedef v_reg v_float32x16; +/** @brief Eight 64-bit floating point values (double precision) */ +typedef v_reg v_float64x8; +/** @brief Eight 64-bit unsigned integer values */ +typedef v_reg v_uint64x8; +/** @brief Eight 64-bit signed integer values */ +typedef v_reg v_int64x8; +#endif + +enum { + simd128_width = 16, +#if CV_SIMD256 + simd256_width = 32, +#endif +#if CV_SIMD512 + simd512_width = 64, + simdmax_width = simd512_width +#elif CV_SIMD256 + simdmax_width = simd256_width +#else + simdmax_width = simd128_width +#endif +}; + +/** @brief Add values + +For all types. */ +template CV_INLINE v_reg<_Tp, n> v_add(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Subtract values + +For all types. */ +template CV_INLINE v_reg<_Tp, n> v_sub(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Multiply values + +For 16- and 32-bit integer types and floating types. */ +template CV_INLINE v_reg<_Tp, n> v_mul(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Divide values + +For floating types only. */ +template CV_INLINE v_reg<_Tp, n> v_div(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + + +/** @brief Bitwise AND + +Only for integer types. */ +template CV_INLINE v_reg<_Tp, n> v_and(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Bitwise OR + +Only for integer types. */ +template CV_INLINE v_reg<_Tp, n> v_or(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Bitwise XOR + +Only for integer types.*/ +template CV_INLINE v_reg<_Tp, n> v_xor(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b); + +/** @brief Bitwise NOT + +Only for integer types.*/ +template CV_INLINE v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a); + + +#ifndef CV_DOXYGEN + +#define CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, ...) \ +__CV_EXPAND(macro_name(uchar, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(schar, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(ushort, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(short, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(unsigned, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(int, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(uint64, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(int64, __VA_ARGS__)) \ + +#define CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, ...) \ +__CV_EXPAND(macro_name(float, __VA_ARGS__)) \ +__CV_EXPAND(macro_name(double, __VA_ARGS__)) \ + +#define CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(macro_name, ...) \ +CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(macro_name, __VA_ARGS__) \ +CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(macro_name, __VA_ARGS__) \ + +#define CV__HAL_INTRIN_IMPL_BIN_OP_(_Tp, bin_op, func) \ +template inline \ +v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = saturate_cast<_Tp>(a.s[i] bin_op b.s[i]); \ + return c; \ +} + +#define CV__HAL_INTRIN_IMPL_BIN_OP(bin_op, func) CV__HAL_INTRIN_EXPAND_WITH_ALL_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, bin_op, func) + +CV__HAL_INTRIN_IMPL_BIN_OP(+, v_add) +CV__HAL_INTRIN_IMPL_BIN_OP(-, v_sub) +CV__HAL_INTRIN_IMPL_BIN_OP(*, v_mul) +CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIN_OP_, /, v_div) + +#define CV__HAL_INTRIN_IMPL_BIT_OP_(_Tp, bit_op, func) \ +template CV_INLINE \ +v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + typedef typename V_TypeTraits<_Tp>::int_type itype; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) bit_op \ + V_TypeTraits<_Tp>::reinterpret_int(b.s[i]))); \ + return c; \ +} + +#define CV__HAL_INTRIN_IMPL_BIT_OP(bit_op, func) \ +CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) \ +CV__HAL_INTRIN_EXPAND_WITH_FP_TYPES(CV__HAL_INTRIN_IMPL_BIT_OP_, bit_op, func) /* TODO: FIXIT remove this after masks refactoring */ + + +CV__HAL_INTRIN_IMPL_BIT_OP(&, v_and) +CV__HAL_INTRIN_IMPL_BIT_OP(|, v_or) +CV__HAL_INTRIN_IMPL_BIT_OP(^, v_xor) + +#define CV__HAL_INTRIN_IMPL_BITWISE_NOT_(_Tp, dummy, dummy2) \ +template CV_INLINE \ +v_reg<_Tp, n> v_not(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int(~V_TypeTraits<_Tp>::reinterpret_int(a.s[i])); \ + return c; \ +} \ + +CV__HAL_INTRIN_EXPAND_WITH_INTEGER_TYPES(CV__HAL_INTRIN_IMPL_BITWISE_NOT_, ~, v_not) + +#endif // !CV_DOXYGEN + + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_MATH_FUNC(func, cfunc, _Tp2) \ +template inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp2, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = cfunc(a.s[i]); \ + return c; \ +} + +/** @brief Square root of elements + +Only for floating point types.*/ +OPENCV_HAL_IMPL_MATH_FUNC(v_sqrt, std::sqrt, _Tp) + +/** + * @brief Exponential \f$ e^x \f$ of elements + * + * Only for floating point types. Core implementation steps: + * 1. Decompose Input: Convert the input to \f$ 2^{x \cdot \log_2e} \f$ and split its exponential into integer and fractional parts: + * \f$ x \cdot \log_2e = n + f \f$, where \f$ n \f$ is the integer part and \f$ f \f$ is the fractional part. + * 2. Compute \f$ 2^n \f$: Calculated by shifting the bits. + * 3. Adjust Fractional Part: Compute \f$ f \cdot \ln2 \f$ to convert the fractional part to base \f$ e \f$. + * \f$ C1 \f$ and \f$ C2 \f$ are used to adjust the fractional part. + * 4. Polynomial Approximation for \f$ e^{f \cdot \ln2} \f$: The closer the fractional part is to 0, the more accurate the result. + * - For float16 and float32, use a Taylor Series with 6 terms. + * - For float64, use Pade Polynomials Approximation with 4 terms. + * 5. Combine Results: Multiply the two parts together to get the final result: + * \f$ e^x = 2^n \cdot e^{f \cdot \ln2} \f$. + * + * @note The precision of the calculation depends on the implementation and the data type of the input vector. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_exp, std::exp, _Tp) +#define OPENCV_HAL_MATH_HAVE_EXP 1 + +/** + * @brief Natural logarithm \f$ \log(x) \f$ of elements + * + * Only for floating point types. Core implementation steps: + * 1. Decompose Input: Use binary representation to decompose the input into mantissa part \f$ m \f$ and exponent part \f$ e \f$. Such that \f$ \log(x) = \log(m \cdot 2^e) = \log(m) + e \cdot \ln(2) \f$. + * 2. Adjust Mantissa and Exponent Parts: If the mantissa is less than \f$ \sqrt{0.5} \f$, adjust the exponent and mantissa to ensure the mantissa is in the range \f$ (\sqrt{0.5}, \sqrt{2}) \f$ for better approximation. + * 3. Polynomial Approximation for \f$ \log(m) \f$: The closer the \f$ m \f$ is to 1, the more accurate the result. + * - For float16 and float32, use a Taylor Series with 9 terms. + * - For float64, use Pade Polynomials Approximation with 6 terms. + * 4. Combine Results: Add the two parts together to get the final result. + * + * @note The precision of the calculation depends on the implementation and the data type of the input. + * + * @note Similar to the behavior of std::log(), \f$ \ln(0) = -\infty \f$. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_log, std::log, _Tp) + +/** + * @brief Error function. + * + * @note Support FP32 precision for now. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_erf, std::erf, _Tp) + +/** + * @brief Compute sine \f$ sin(x) \f$ and cosine \f$ cos(x) \f$ of elements at the same time + * + * Only for floating point types. Core implementation steps: + * 1. Input Normalization: Scale the periodicity from 2π to 4 and reduce the angle to the range \f$ [0, \frac{\pi}{4}] \f$ using periodicity and trigonometric identities. + * 2. Polynomial Approximation for \f$ sin(x) \f$ and \f$ cos(x) \f$: + * - For float16 and float32, use a Taylor series with 4 terms for sine and 5 terms for cosine. + * - For float64, use a Taylor series with 7 terms for sine and 8 terms for cosine. + * 3. Select Results: select and convert the final sine and cosine values for the original input angle. + * + * @note The precision of the calculation depends on the implementation and the data type of the input vector. + */ +template +inline void v_sincos(const v_reg<_Tp, n>& x, v_reg<_Tp, n>& s, v_reg<_Tp, n>& c) +{ + for( int i = 0; i < n; i++ ) + { + s.s[i] = std::sin(x.s[i]); + c.s[i] = std::cos(x.s[i]); + } +} + +/** + * @brief Sine \f$ sin(x) \f$ of elements + * + * Only for floating point types. Core implementation the same as @ref v_sincos. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_sin, std::sin, _Tp) + +/** + * @brief Cosine \f$ cos(x) \f$ of elements + * + * Only for floating point types. Core implementation the same as @ref v_sincos. + */ +OPENCV_HAL_IMPL_MATH_FUNC(v_cos, std::cos, _Tp) + +/** @brief Absolute value of elements + +Only for floating point types.*/ +OPENCV_HAL_IMPL_MATH_FUNC(v_abs, (typename V_TypeTraits<_Tp>::abs_type)std::abs, + typename V_TypeTraits<_Tp>::abs_type) + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_MINMAX_FUNC(func, cfunc) \ +template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = cfunc(a.s[i], b.s[i]); \ + return c; \ +} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(func, cfunc) \ +template inline _Tp func(const v_reg<_Tp, n>& a) \ +{ \ + _Tp c = a.s[0]; \ + for( int i = 1; i < n; i++ ) \ + c = cfunc(c, a.s[i]); \ + return c; \ +} + +/** @brief Choose min values for each pair + +Scheme: +@code +{A1 A2 ...} +{B1 B2 ...} +-------------- +{min(A1,B1) min(A2,B2) ...} +@endcode +For all types except 64-bit integer. */ +OPENCV_HAL_IMPL_MINMAX_FUNC(v_min, std::min) + +/** @brief Choose max values for each pair + +Scheme: +@code +{A1 A2 ...} +{B1 B2 ...} +-------------- +{max(A1,B1) max(A2,B2) ...} +@endcode +For all types except 64-bit integer. */ +OPENCV_HAL_IMPL_MINMAX_FUNC(v_max, std::max) + +/** @brief Find one min value + +Scheme: +@code +{A1 A2 A3 ...} => min(A1,A2,A3,...) +@endcode +For all types except 64-bit integer and 64-bit floating point types. */ +OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_min, std::min) + +/** @brief Find one max value + +Scheme: +@code +{A1 A2 A3 ...} => max(A1,A2,A3,...) +@endcode +For all types except 64-bit integer and 64-bit floating point types. */ +OPENCV_HAL_IMPL_REDUCE_MINMAX_FUNC(v_reduce_max, std::max) + +static const unsigned char popCountTable[] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; +/** @brief Count the 1 bits in the vector lanes and return result as corresponding unsigned type + +Scheme: +@code +{A1 A2 A3 ...} => {popcount(A1), popcount(A2), popcount(A3), ...} +@endcode +For all integer types. */ +template +inline v_reg::abs_type, n> v_popcount(const v_reg<_Tp, n>& a) +{ + v_reg::abs_type, n> b = v_reg::abs_type, n>::zero(); + for (int i = 0; i < n*(int)sizeof(_Tp); i++) + b.s[i/sizeof(_Tp)] += popCountTable[v_reinterpret_as_u8(a).s[i]]; + return b; +} + + +//! @cond IGNORED +template +inline void v_minmax( const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + v_reg<_Tp, n>& minval, v_reg<_Tp, n>& maxval ) +{ + for( int i = 0; i < n; i++ ) + { + minval.s[i] = std::min(a.s[i], b.s[i]); + maxval.s[i] = std::max(a.s[i], b.s[i]); + } +} +//! @endcond + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_CMP_OP(cmp_op, func) \ +template \ +inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + typedef typename V_TypeTraits<_Tp>::int_type itype; \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = V_TypeTraits<_Tp>::reinterpret_from_int((itype)-(int)(a.s[i] cmp_op b.s[i])); \ + return c; \ +} + +/** @brief Less-than comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(<, v_lt) + +/** @brief Greater-than comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(>, v_gt) + +/** @brief Less-than or equal comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(<=, v_le) + +/** @brief Greater-than or equal comparison + +For all types except 64-bit integer values. */ +OPENCV_HAL_IMPL_CMP_OP(>=, v_ge) + +/** @brief Equal comparison */ +OPENCV_HAL_IMPL_CMP_OP(==, v_eq) + +/** @brief Not equal comparison */ +OPENCV_HAL_IMPL_CMP_OP(!=, v_ne) + +template +inline v_reg v_not_nan(const v_reg& a) +{ + typedef typename V_TypeTraits::int_type itype; + v_reg c; + for (int i = 0; i < n; i++) + c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); + return c; +} +template +inline v_reg v_not_nan(const v_reg& a) +{ + typedef typename V_TypeTraits::int_type itype; + v_reg c; + for (int i = 0; i < n; i++) + c.s[i] = V_TypeTraits::reinterpret_from_int((itype)-(int)(a.s[i] == a.s[i])); + return c; +} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_ARITHM_OP(func, bin_op, cast_op, _Tp2) \ +template \ +inline v_reg<_Tp2, n> func(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + typedef _Tp2 rtype; \ + v_reg c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = cast_op(a.s[i] bin_op b.s[i]); \ + return c; \ +} + +/** @brief Add values without saturation + +For 8- and 16-bit integer values. */ +OPENCV_HAL_IMPL_ARITHM_OP(v_add_wrap, +, (_Tp), _Tp) + +/** @brief Subtract values without saturation + +For 8- and 16-bit integer values. */ +OPENCV_HAL_IMPL_ARITHM_OP(v_sub_wrap, -, (_Tp), _Tp) + +/** @brief Multiply values without saturation + +For 8- and 16-bit integer values. */ +OPENCV_HAL_IMPL_ARITHM_OP(v_mul_wrap, *, (_Tp), _Tp) + +//! @cond IGNORED +template inline T _absdiff(T a, T b) +{ + return a > b ? a - b : b - a; +} +//! @endcond + +/** @brief Absolute difference + +Returns \f$ |a - b| \f$ converted to corresponding unsigned type. +Example: +@code{.cpp} +v_int32x4 a, b; // {1, 2, 3, 4} and {4, 3, 2, 1} +v_uint32x4 c = v_absdiff(a, b); // result is {3, 1, 1, 3} +@endcode +For 8-, 16-, 32-bit integer source types. */ +template +inline v_reg::abs_type, n> v_absdiff(const v_reg<_Tp, n>& a, const v_reg<_Tp, n> & b) +{ + typedef typename V_TypeTraits<_Tp>::abs_type rtype; + v_reg c; + const rtype mask = (rtype)(std::numeric_limits<_Tp>::is_signed ? (1 << (sizeof(rtype)*8 - 1)) : 0); + for( int i = 0; i < n; i++ ) + { + rtype ua = a.s[i] ^ mask; + rtype ub = b.s[i] ^ mask; + c.s[i] = _absdiff(ua, ub); + } + return c; +} + +/** @overload + +For 32-bit floating point values */ +template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + c.s[i] = _absdiff(a.s[i], b.s[i]); + return c; +} + +/** @overload + +For 64-bit floating point values */ +template inline v_reg v_absdiff(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + c.s[i] = _absdiff(a.s[i], b.s[i]); + return c; +} + +/** @brief Saturating absolute difference + +Returns \f$ saturate(|a - b|) \f$ . +For 8-, 16-bit signed integer source types. */ +template +inline v_reg<_Tp, n> v_absdiffs(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++) + c.s[i] = saturate_cast<_Tp>(std::abs(a.s[i] - b.s[i])); + return c; +} + +/** @brief Inversed square root + +Returns \f$ 1/sqrt(a) \f$ +For floating point types only. */ +template +inline v_reg<_Tp, n> v_invsqrt(const v_reg<_Tp, n>& a) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = 1.f/std::sqrt(a.s[i]); + return c; +} + +/** @brief Magnitude + +Returns \f$ sqrt(a^2 + b^2) \f$ +For floating point types only. */ +template +inline v_reg<_Tp, n> v_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = std::sqrt(a.s[i]*a.s[i] + b.s[i]*b.s[i]); + return c; +} + +/** @brief Square of the magnitude + +Returns \f$ a^2 + b^2 \f$ +For floating point types only. */ +template +inline v_reg<_Tp, n> v_sqr_magnitude(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = a.s[i]*a.s[i] + b.s[i]*b.s[i]; + return c; +} + +/** @brief Multiply and add + + Returns \f$ a*b + c \f$ + For floating point types and signed 32bit int only. */ +template +inline v_reg<_Tp, n> v_fma(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg<_Tp, n>& c) +{ + v_reg<_Tp, n> d; + for( int i = 0; i < n; i++ ) + d.s[i] = a.s[i]*b.s[i] + c.s[i]; + return d; +} + +/** @brief A synonym for v_fma */ +template +inline v_reg<_Tp, n> v_muladd(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg<_Tp, n>& c) +{ + return v_fma(a, b, c); +} + +/** @brief Dot product of elements + +Multiply values in two registers and sum adjacent result pairs. + +Scheme: +@code + {A1 A2 ...} // 16-bit +x {B1 B2 ...} // 16-bit +------------- +{A1B1+A2B2 ...} // 32-bit + +@endcode +*/ +template inline v_reg::w_type, n/2> +v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1]; + return c; +} + +/** @brief Dot product of elements + +Same as cv::v_dotprod, but add a third element to the sum of adjacent pairs. +Scheme: +@code + {A1 A2 ...} // 16-bit +x {B1 B2 ...} // 16-bit +------------- + {A1B1+A2B2+C1 ...} // 32-bit +@endcode +*/ +template inline v_reg::w_type, n/2> +v_dotprod(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::w_type, n / 2>& c) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg s; + for( int i = 0; i < (n/2); i++ ) + s.s[i] = (w_type)a.s[i*2]*b.s[i*2] + (w_type)a.s[i*2+1]*b.s[i*2+1] + c.s[i]; + return s; +} + +/** @brief Fast Dot product of elements + +Same as cv::v_dotprod, but it may perform unorder sum between result pairs in some platforms, +this intrinsic can be used if the sum among all lanes is only matters +and also it should be yielding better performance on the affected platforms. + +*/ +template inline v_reg::w_type, n/2> +v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ return v_dotprod(a, b); } + +/** @brief Fast Dot product of elements + +Same as cv::v_dotprod_fast, but add a third element to the sum of adjacent pairs. +*/ +template inline v_reg::w_type, n/2> +v_dotprod_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::w_type, n / 2>& c) +{ return v_dotprod(a, b, c); } + +/** @brief Dot product of elements and expand + +Multiply values in two registers and expand the sum of adjacent result pairs. + +Scheme: +@code + {A1 A2 A3 A4 ...} // 8-bit +x {B1 B2 B3 B4 ...} // 8-bit +------------- + {A1B1+A2B2+A3B3+A4B4 ...} // 32-bit + +@endcode +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg s; + for( int i = 0; i < (n/4); i++ ) + s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + + (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3]; + return s; +} + +/** @brief Dot product of elements + +Same as cv::v_dotprod_expand, but add a third element to the sum of adjacent pairs. +Scheme: +@code + {A1 A2 A3 A4 ...} // 8-bit +x {B1 B2 B3 B4 ...} // 8-bit +------------- + {A1B1+A2B2+A3B3+A4B4+C1 ...} // 32-bit +@endcode +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::q_type, n / 4>& c) +{ + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg s; + for( int i = 0; i < (n/4); i++ ) + s.s[i] = (q_type)a.s[i*4 ]*b.s[i*4 ] + (q_type)a.s[i*4 + 1]*b.s[i*4 + 1] + + (q_type)a.s[i*4 + 2]*b.s[i*4 + 2] + (q_type)a.s[i*4 + 3]*b.s[i*4 + 3] + c.s[i]; + return s; +} + +/** @brief Fast Dot product of elements and expand + +Multiply values in two registers and expand the sum of adjacent result pairs. + +Same as cv::v_dotprod_expand, but it may perform unorder sum between result pairs in some platforms, +this intrinsic can be used if the sum among all lanes is only matters +and also it should be yielding better performance on the affected platforms. + +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ return v_dotprod_expand(a, b); } + +/** @brief Fast Dot product of elements + +Same as cv::v_dotprod_expand_fast, but add a third element to the sum of adjacent pairs. +*/ +template inline v_reg::q_type, n/4> +v_dotprod_expand_fast(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + const v_reg::q_type, n / 4>& c) +{ return v_dotprod_expand(a, b, c); } + +/** @brief Multiply and expand + +Multiply values two registers and store results in two registers with wider pack type. +Scheme: +@code + {A B C D} // 32-bit +x {E F G H} // 32-bit +--------------- +{AE BF} // 64-bit + {CG DH} // 64-bit +@endcode +Example: +@code{.cpp} +v_uint32x4 a, b; // {1,2,3,4} and {2,2,2,2} +v_uint64x2 c, d; // results +v_mul_expand(a, b, c, d); // c, d = {2,4}, {6, 8} +@endcode +Implemented only for 16- and unsigned 32-bit source types (v_int16x8, v_uint16x8, v_uint32x4). +*/ +template inline void v_mul_expand(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + v_reg::w_type, n/2>& c, + v_reg::w_type, n/2>& d) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = (w_type)a.s[i]*b.s[i]; + d.s[i] = (w_type)a.s[i+(n/2)]*b.s[i+(n/2)]; + } +} + +/** @brief Multiply and extract high part + +Multiply values two registers and store high part of the results. +Implemented only for 16-bit source types (v_int16x8, v_uint16x8). Returns \f$ a*b >> 16 \f$ +*/ +template inline v_reg<_Tp, n> v_mul_hi(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg<_Tp, n> c; + for (int i = 0; i < n; i++) + c.s[i] = (_Tp)(((w_type)a.s[i] * b.s[i]) >> sizeof(_Tp)*8); + return c; +} + +//! @cond IGNORED +template inline void v_hsum(const v_reg<_Tp, n>& a, + v_reg::w_type, n/2>& c) +{ + typedef typename V_TypeTraits<_Tp>::w_type w_type; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = (w_type)a.s[i*2] + a.s[i*2+1]; + } +} +//! @endcond + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_SHIFT_OP(shift_op, func) \ +template inline v_reg<_Tp, n> func(const v_reg<_Tp, n>& a, int imm) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = (_Tp)(a.s[i] shift_op imm); \ + return c; \ +} + +/** @brief Bitwise shift left + +For 16-, 32- and 64-bit integer values. */ +OPENCV_HAL_IMPL_SHIFT_OP(<<, v_shl) + +/** @brief Bitwise shift right + +For 16-, 32- and 64-bit integer values. */ +OPENCV_HAL_IMPL_SHIFT_OP(>>, v_shr) + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(suffix,opA,opB) \ +template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp, n> b; \ + for (int i = 0; i < n; i++) \ + { \ + int sIndex = i opA imm; \ + if (0 <= sIndex && sIndex < n) \ + { \ + b.s[i] = a.s[sIndex]; \ + } \ + else \ + { \ + b.s[i] = 0; \ + } \ + } \ + return b; \ +} \ +template inline v_reg<_Tp, n> v_rotate_##suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tp, n> c; \ + for (int i = 0; i < n; i++) \ + { \ + int aIndex = i opA imm; \ + int bIndex = i opA imm opB n; \ + if (0 <= bIndex && bIndex < n) \ + { \ + c.s[i] = b.s[bIndex]; \ + } \ + else if (0 <= aIndex && aIndex < n) \ + { \ + c.s[i] = a.s[aIndex]; \ + } \ + else \ + { \ + c.s[i] = 0; \ + } \ + } \ + return c; \ +} + +/** @brief Element shift left among vector + +For all type */ +OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(left, -, +) + +/** @brief Element shift right among vector + +For all type */ +OPENCV_HAL_IMPL_ROTATE_SHIFT_OP(right, +, -) + +/** @brief Sum packed values + +Scheme: +@code +{A1 A2 A3 ...} => sum{A1,A2,A3,...} +@endcode +*/ +template inline typename V_TypeTraits<_Tp>::sum_type v_reduce_sum(const v_reg<_Tp, n>& a) +{ + typename V_TypeTraits<_Tp>::sum_type c = a.s[0]; + for( int i = 1; i < n; i++ ) + c += a.s[i]; + return c; +} + +/** @brief Sums all elements of each input vector, returns the vector of sums + + Scheme: + @code + result[0] = a[0] + a[1] + a[2] + a[3] + result[1] = b[0] + b[1] + b[2] + b[3] + result[2] = c[0] + c[1] + c[2] + c[3] + result[3] = d[0] + d[1] + d[2] + d[3] + @endcode +*/ +template inline v_reg v_reduce_sum4(const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg r; + for(int i = 0; i < (n/4); i++) + { + r.s[i*4 + 0] = a.s[i*4 + 0] + a.s[i*4 + 1] + a.s[i*4 + 2] + a.s[i*4 + 3]; + r.s[i*4 + 1] = b.s[i*4 + 0] + b.s[i*4 + 1] + b.s[i*4 + 2] + b.s[i*4 + 3]; + r.s[i*4 + 2] = c.s[i*4 + 0] + c.s[i*4 + 1] + c.s[i*4 + 2] + c.s[i*4 + 3]; + r.s[i*4 + 3] = d.s[i*4 + 0] + d.s[i*4 + 1] + d.s[i*4 + 2] + d.s[i*4 + 3]; + } + return r; +} + +/** @brief Sum absolute differences of values + +Scheme: +@code +{A1 A2 A3 ...} {B1 B2 B3 ...} => sum{ABS(A1-B1),abs(A2-B2),abs(A3-B3),...} +@endcode +For all types except 64-bit types.*/ +template inline typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type v_reduce_sad(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typename V_TypeTraits< typename V_TypeTraits<_Tp>::abs_type >::sum_type c = _absdiff(a.s[0], b.s[0]); + for (int i = 1; i < n; i++) + c += _absdiff(a.s[i], b.s[i]); + return c; +} + +/** @brief Get negative values mask +@deprecated v_signmask depends on a lane count heavily and therefore isn't universal enough + +Returned value is a bit mask with bits set to 1 on places corresponding to negative packed values indexes. +Example: +@code{.cpp} +v_int32x4 r; // set to {-1, -1, 1, 1} +int mask = v_signmask(r); // mask = 3 <== 00000000 00000000 00000000 00000011 +@endcode +*/ +template inline int v_signmask(const v_reg<_Tp, n>& a) +{ + int mask = 0; + for( int i = 0; i < n; i++ ) + mask |= (V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) << i; + return mask; +} + +/** @brief Get first negative lane index + +Returned value is an index of first negative lane (undefined for input of all positive values) +Example: +@code{.cpp} +v_int32x4 r; // set to {0, 0, -1, -1} +int idx = v_heading_zeros(r); // idx = 2 +@endcode +*/ +template inline int v_scan_forward(const v_reg<_Tp, n>& a) +{ + for (int i = 0; i < n; i++) + if(V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0) + return i; + return 0; +} + +/** @brief Check if all packed values are less than zero + +Unsigned values will be casted to signed: `uchar 254 => char -2`. +*/ +template inline bool v_check_all(const v_reg<_Tp, n>& a) +{ + for( int i = 0; i < n; i++ ) + if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) >= 0 ) + return false; + return true; +} + +/** @brief Check if any of packed values is less than zero + +Unsigned values will be casted to signed: `uchar 254 => char -2`. +*/ +template inline bool v_check_any(const v_reg<_Tp, n>& a) +{ + for( int i = 0; i < n; i++ ) + if( V_TypeTraits<_Tp>::reinterpret_int(a.s[i]) < 0 ) + return true; + return false; +} + +/** @brief Per-element select (blend operation) + +Return value will be built by combining values _a_ and _b_ using the following scheme: + result[i] = mask[i] ? a[i] : b[i]; + +@note: _mask_ element values are restricted to these values: +- 0: select element from _b_ +- 0xff/0xffff/etc: select element from _a_ +(fully compatible with bitwise-based operator) +*/ +template inline v_reg<_Tp, n> v_select(const v_reg<_Tp, n>& mask, + const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + typedef V_TypeTraits<_Tp> Traits; + typedef typename Traits::int_type int_type; + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + { + int_type m = Traits::reinterpret_int(mask.s[i]); + CV_DbgAssert(m == 0 || m == (~(int_type)0)); // restrict mask values: 0 or 0xff/0xffff/etc + c.s[i] = m ? a.s[i] : b.s[i]; + } + return c; +} + +/** @brief Expand values to the wider pack type + +Copy contents of register to two registers with 2x wider pack type. +Scheme: +@code + int32x4 int64x2 int64x2 +{A B C D} ==> {A B} , {C D} +@endcode */ +template inline void v_expand(const v_reg<_Tp, n>& a, + v_reg::w_type, n/2>& b0, + v_reg::w_type, n/2>& b1) +{ + for( int i = 0; i < (n/2); i++ ) + { + b0.s[i] = a.s[i]; + b1.s[i] = a.s[i+(n/2)]; + } +} + +/** @brief Expand lower values to the wider pack type + +Same as cv::v_expand, but return lower half of the vector. + +Scheme: +@code + int32x4 int64x2 +{A B C D} ==> {A B} +@endcode */ +template +inline v_reg::w_type, n/2> +v_expand_low(const v_reg<_Tp, n>& a) +{ + v_reg::w_type, n/2> b; + for( int i = 0; i < (n/2); i++ ) + b.s[i] = a.s[i]; + return b; +} + +/** @brief Expand higher values to the wider pack type + +Same as cv::v_expand_low, but expand higher half of the vector instead. + +Scheme: +@code + int32x4 int64x2 +{A B C D} ==> {C D} +@endcode */ +template +inline v_reg::w_type, n/2> +v_expand_high(const v_reg<_Tp, n>& a) +{ + v_reg::w_type, n/2> b; + for( int i = 0; i < (n/2); i++ ) + b.s[i] = a.s[i+(n/2)]; + return b; +} + +//! @cond IGNORED +template inline v_reg::int_type, n> + v_reinterpret_as_int(const v_reg<_Tp, n>& a) +{ + v_reg::int_type, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = V_TypeTraits<_Tp>::reinterpret_int(a.s[i]); + return c; +} + +template inline v_reg::uint_type, n> + v_reinterpret_as_uint(const v_reg<_Tp, n>& a) +{ + v_reg::uint_type, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = V_TypeTraits<_Tp>::reinterpret_uint(a.s[i]); + return c; +} +//! @endcond + +/** @brief Interleave two vectors + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +--------------- + {A1 B1 A2 B2} and {A3 B3 A4 B4} +@endcode +For all types except 64-bit. +*/ +template inline void v_zip( const v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, + v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1 ) +{ + int i; + for( i = 0; i < n/2; i++ ) + { + b0.s[i*2] = a0.s[i]; + b0.s[i*2+1] = a1.s[i]; + } + for( ; i < n; i++ ) + { + b1.s[i*2-n] = a0.s[i]; + b1.s[i*2-n+1] = a1.s[i]; + } +} + +/** @brief Load register contents from memory + +@param ptr pointer to memory block with data +@return register object + +@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x16, int ==> cv::v_int32x4, etc. + +@note Use vx_load version to get maximum available register length result + +@note Alignment requirement: +if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). +Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). + */ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); +} + +#if CV_SIMD256 +/** @brief Load 256-bit length register contents from memory + +@param ptr pointer to memory block with data +@return register object + +@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x32, int ==> cv::v_int32x8, etc. + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load version to get maximum available register length result + +@note Alignment requirement: +if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). +Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). + */ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); +} +#endif + +#if CV_SIMD512 +/** @brief Load 512-bit length register contents from memory + +@param ptr pointer to memory block with data +@return register object + +@note Returned type will be detected from passed pointer type, for example uchar ==> cv::v_uint8x64, int ==> cv::v_int32x16, etc. + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load version to get maximum available register length result + +@note Alignment requirement: +if CV_STRONG_ALIGNMENT=1 then passed pointer must be aligned (`sizeof(lane type)` should be enough). +Do not cast pointer types without runtime check for pointer alignment (like `uchar*` => `int*`). + */ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); +} +#endif + +/** @brief Load register contents from memory (aligned) + +similar to cv::v_load, but source memory block should be aligned (to 16-byte boundary in case of SIMD128, 32-byte - SIMD256, etc) + +@note Use vx_load_aligned version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_aligned(const _Tp* ptr) +{ + CV_Assert(isAligned)>(ptr)); + return v_reg<_Tp, simd128_width / sizeof(_Tp)>(ptr); +} + +#if CV_SIMD256 +/** @brief Load register contents from memory (aligned) + +similar to cv::v256_load, but source memory block should be aligned (to 32-byte boundary in case of SIMD256, 64-byte - SIMD512, etc) + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_aligned version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_aligned(const _Tp* ptr) +{ + CV_Assert(isAligned)>(ptr)); + return v_reg<_Tp, simd256_width / sizeof(_Tp)>(ptr); +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from memory (aligned) + +similar to cv::v512_load, but source memory block should be aligned (to 64-byte boundary in case of SIMD512, etc) + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_aligned version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_aligned(const _Tp* ptr) +{ + CV_Assert(isAligned)>(ptr)); + return v_reg<_Tp, simd512_width / sizeof(_Tp)>(ptr); +} +#endif + +/** @brief Load 64-bits of data to lower part (high part is undefined). + +@param ptr memory block containing data for first half (0..n/2) + +@code{.cpp} +int lo[2] = { 1, 2 }; +v_int32x4 r = v_load_low(lo); +@endcode + +@note Use vx_load_low version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_low(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for( int i = 0; i < c.nlanes/2; i++ ) + { + c.s[i] = ptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load 128-bits of data to lower part (high part is undefined). + +@param ptr memory block containing data for first half (0..n/2) + +@code{.cpp} +int lo[4] = { 1, 2, 3, 4 }; +v_int32x8 r = v256_load_low(lo); +@endcode + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_low version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_low(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_reg<_Tp, simd256_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load 256-bits of data to lower part (high part is undefined). + +@param ptr memory block containing data for first half (0..n/2) + +@code{.cpp} +int lo[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; +v_int32x16 r = v512_load_low(lo); +@endcode + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_low version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_low(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_reg<_Tp, simd512_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +/** @brief Load register contents from two memory blocks + +@param loptr memory block containing data for first half (0..n/2) +@param hiptr memory block containing data for second half (n/2..n) + +@code{.cpp} +int lo[2] = { 1, 2 }, hi[2] = { 3, 4 }; +v_int32x4 r = v_load_halves(lo, hi); +@endcode + +@note Use vx_load_halves version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_load_halves(const _Tp* loptr, const _Tp* hiptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(loptr)); + CV_Assert(isAligned(hiptr)); +#endif + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for( int i = 0; i < c.nlanes/2; i++ ) + { + c.s[i] = loptr[i]; + c.s[i+c.nlanes/2] = hiptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load register contents from two memory blocks + +@param loptr memory block containing data for first half (0..n/2) +@param hiptr memory block containing data for second half (n/2..n) + +@code{.cpp} +int lo[4] = { 1, 2, 3, 4 }, hi[4] = { 5, 6, 7, 8 }; +v_int32x8 r = v256_load_halves(lo, hi); +@endcode + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_halves version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd256_width / sizeof(_Tp)> v256_load_halves(const _Tp* loptr, const _Tp* hiptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(loptr)); + CV_Assert(isAligned(hiptr)); +#endif + v_reg<_Tp, simd256_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = loptr[i]; + c.s[i + c.nlanes / 2] = hiptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from two memory blocks + +@param loptr memory block containing data for first half (0..n/2) +@param hiptr memory block containing data for second half (n/2..n) + +@code{.cpp} +int lo[4] = { 1, 2, 3, 4, 5, 6, 7, 8 }, hi[4] = { 9, 10, 11, 12, 13, 14, 15, 16 }; +v_int32x16 r = v512_load_halves(lo, hi); +@endcode + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_halves version to get maximum available register length result +*/ +template +inline v_reg<_Tp, simd512_width / sizeof(_Tp)> v512_load_halves(const _Tp* loptr, const _Tp* hiptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(loptr)); + CV_Assert(isAligned(hiptr)); +#endif + v_reg<_Tp, simd512_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes / 2; i++) + { + c.s[i] = loptr[i]; + c.s[i + c.nlanes / 2] = hiptr[i]; + } + return c; +} +#endif + +/** @brief Load register contents from memory with double expand + +Same as cv::v_load, but result pack type will be 2x wider than memory type. + +@code{.cpp} +short buf[4] = {1, 2, 3, 4}; // type is int16 +v_int32x4 r = v_load_expand(buf); // r = {1, 2, 3, 4} - type is int32 +@endcode +For 8-, 16-, 32-bit integer source types. + +@note Use vx_load_expand version to get maximum available register length result +*/ +template +inline v_reg::w_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> +v_load_expand(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + { + c.s[i] = ptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load register contents from memory with double expand + +Same as cv::v256_load, but result pack type will be 2x wider than memory type. + +@code{.cpp} +short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int16 +v_int32x8 r = v256_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 +@endcode +For 8-, 16-, 32-bit integer source types. + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_expand version to get maximum available register length result +*/ +template +inline v_reg::w_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> +v256_load_expand(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from memory with double expand + +Same as cv::v512_load, but result pack type will be 2x wider than memory type. + +@code{.cpp} +short buf[8] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int16 +v_int32x16 r = v512_load_expand(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 +@endcode +For 8-, 16-, 32-bit integer source types. + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_expand version to get maximum available register length result +*/ +template +inline v_reg::w_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::w_type)> +v512_load_expand(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::w_type w_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +/** @brief Load register contents from memory with quad expand + +Same as cv::v_load_expand, but result type is 4 times wider than source. +@code{.cpp} +char buf[4] = {1, 2, 3, 4}; // type is int8 +v_int32x4 r = v_load_expand_q(buf); // r = {1, 2, 3, 4} - type is int32 +@endcode +For 8-bit integer source types. + +@note Use vx_load_expand_q version to get maximum available register length result +*/ +template +inline v_reg::q_type, simd128_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> +v_load_expand_q(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg c; + for( int i = 0; i < c.nlanes; i++ ) + { + c.s[i] = ptr[i]; + } + return c; +} + +#if CV_SIMD256 +/** @brief Load register contents from memory with quad expand + +Same as cv::v256_load_expand, but result type is 4 times wider than source. +@code{.cpp} +char buf[8] = {1, 2, 3, 4, 5, 6, 7, 8}; // type is int8 +v_int32x8 r = v256_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8} - type is int32 +@endcode +For 8-bit integer source types. + +@note Check CV_SIMD256 preprocessor definition prior to use. +Use vx_load_expand_q version to get maximum available register length result +*/ +template +inline v_reg::q_type, simd256_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> +v256_load_expand_q(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +#if CV_SIMD512 +/** @brief Load register contents from memory with quad expand + +Same as cv::v512_load_expand, but result type is 4 times wider than source. +@code{.cpp} +char buf[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; // type is int8 +v_int32x16 r = v512_load_expand_q(buf); // r = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} - type is int32 +@endcode +For 8-bit integer source types. + +@note Check CV_SIMD512 preprocessor definition prior to use. +Use vx_load_expand_q version to get maximum available register length result +*/ +template +inline v_reg::q_type, simd512_width / sizeof(typename V_TypeTraits<_Tp>::q_type)> +v512_load_expand_q(const _Tp* ptr) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + typedef typename V_TypeTraits<_Tp>::q_type q_type; + v_reg c; + for (int i = 0; i < c.nlanes; i++) + { + c.s[i] = ptr[i]; + } + return c; +} +#endif + +/** @brief Load and deinterleave (2 channels) + +Load data from memory deinterleave and store to 2 registers. +Scheme: +@code +{A1 B1 A2 B2 ...} ==> {A1 A2 ...}, {B1 B2 ...} +@endcode +For all types except 64-bit. */ +template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, + v_reg<_Tp, n>& b) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i2; + for( i = i2 = 0; i < n; i++, i2 += 2 ) + { + a.s[i] = ptr[i2]; + b.s[i] = ptr[i2+1]; + } +} + +/** @brief Load and deinterleave (3 channels) + +Load data from memory deinterleave and store to 3 registers. +Scheme: +@code +{A1 B1 C1 A2 B2 C2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} +@endcode +For all types except 64-bit. */ +template inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, + v_reg<_Tp, n>& b, v_reg<_Tp, n>& c) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i3; + for( i = i3 = 0; i < n; i++, i3 += 3 ) + { + a.s[i] = ptr[i3]; + b.s[i] = ptr[i3+1]; + c.s[i] = ptr[i3+2]; + } +} + +/** @brief Load and deinterleave (4 channels) + +Load data from memory deinterleave and store to 4 registers. +Scheme: +@code +{A1 B1 C1 D1 A2 B2 C2 D2 ...} ==> {A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} +@endcode +For all types except 64-bit. */ +template +inline void v_load_deinterleave(const _Tp* ptr, v_reg<_Tp, n>& a, + v_reg<_Tp, n>& b, v_reg<_Tp, n>& c, + v_reg<_Tp, n>& d) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i4; + for( i = i4 = 0; i < n; i++, i4 += 4 ) + { + a.s[i] = ptr[i4]; + b.s[i] = ptr[i4+1]; + c.s[i] = ptr[i4+2]; + d.s[i] = ptr[i4+3]; + } +} + +/** @brief Interleave and store (2 channels) + +Interleave and store data from 2 registers to memory. +Scheme: +@code +{A1 A2 ...}, {B1 B2 ...} ==> {A1 B1 A2 B2 ...} +@endcode +For all types except 64-bit. */ +template +inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, + const v_reg<_Tp, n>& b, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i2; + for( i = i2 = 0; i < n; i++, i2 += 2 ) + { + ptr[i2] = a.s[i]; + ptr[i2+1] = b.s[i]; + } +} + +/** @brief Interleave and store (3 channels) + +Interleave and store data from 3 registers to memory. +Scheme: +@code +{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...} ==> {A1 B1 C1 A2 B2 C2 ...} +@endcode +For all types except 64-bit. */ +template +inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, + const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i3; + for( i = i3 = 0; i < n; i++, i3 += 3 ) + { + ptr[i3] = a.s[i]; + ptr[i3+1] = b.s[i]; + ptr[i3+2] = c.s[i]; + } +} + +/** @brief Interleave and store (4 channels) + +Interleave and store data from 4 registers to memory. +Scheme: +@code +{A1 A2 ...}, {B1 B2 ...}, {C1 C2 ...}, {D1 D2 ...} ==> {A1 B1 C1 D1 A2 B2 C2 D2 ...} +@endcode +For all types except 64-bit. */ +template inline void v_store_interleave( _Tp* ptr, const v_reg<_Tp, n>& a, + const v_reg<_Tp, n>& b, const v_reg<_Tp, n>& c, + const v_reg<_Tp, n>& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + int i, i4; + for( i = i4 = 0; i < n; i++, i4 += 4 ) + { + ptr[i4] = a.s[i]; + ptr[i4+1] = b.s[i]; + ptr[i4+2] = c.s[i]; + ptr[i4+3] = d.s[i]; + } +} + +/** @brief Store data to memory + +Store register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {A B C D} +@endcode +Pointer can be unaligned. */ +template +inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + for( int i = 0; i < n; i++ ) + ptr[i] = a.s[i]; +} + +template +inline void v_store(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + v_store(ptr, a); +} + +/** @brief Store data to memory (lower half) + +Store lower half of register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {A B} +@endcode */ +template +inline void v_store_low(_Tp* ptr, const v_reg<_Tp, n>& a) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + for( int i = 0; i < (n/2); i++ ) + ptr[i] = a.s[i]; +} + +/** @brief Store data to memory (higher half) + +Store higher half of register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {C D} +@endcode */ +template +inline void v_store_high(_Tp* ptr, const v_reg<_Tp, n>& a) +{ +#if CV_STRONG_ALIGNMENT + CV_Assert(isAligned(ptr)); +#endif + for( int i = 0; i < (n/2); i++ ) + ptr[i] = a.s[i+(n/2)]; +} + +/** @brief Store data to memory (aligned) + +Store register contents to memory. +Scheme: +@code + REG {A B C D} ==> MEM {A B C D} +@endcode +Pointer __should__ be aligned by 16-byte boundary. */ +template +inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a) +{ + CV_Assert(isAligned)>(ptr)); + v_store(ptr, a); +} + +template +inline void v_store_aligned_nocache(_Tp* ptr, const v_reg<_Tp, n>& a) +{ + CV_Assert(isAligned)>(ptr)); + v_store(ptr, a); +} + +template +inline void v_store_aligned(_Tp* ptr, const v_reg<_Tp, n>& a, hal::StoreMode /*mode*/) +{ + CV_Assert(isAligned)>(ptr)); + v_store(ptr, a); +} + +/** @brief Combine vector from first elements of two vectors + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +--------------- + {A1 A2 B1 B2} +@endcode +For all types except 64-bit. */ +template +inline v_reg<_Tp, n> v_combine_low(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = a.s[i]; + c.s[i+(n/2)] = b.s[i]; + } + return c; +} + +/** @brief Combine vector from last elements of two vectors + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +--------------- + {A3 A4 B3 B4} +@endcode +For all types except 64-bit. */ +template +inline v_reg<_Tp, n> v_combine_high(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < (n/2); i++ ) + { + c.s[i] = a.s[i+(n/2)]; + c.s[i+(n/2)] = b.s[i+(n/2)]; + } + return c; +} + +/** @brief Combine two vectors from lower and higher parts of two other vectors + +@code{.cpp} +low = cv::v_combine_low(a, b); +high = cv::v_combine_high(a, b); +@endcode */ +template +inline void v_recombine(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b, + v_reg<_Tp, n>& low, v_reg<_Tp, n>& high) +{ + for( int i = 0; i < (n/2); i++ ) + { + low.s[i] = a.s[i]; + low.s[i+(n/2)] = b.s[i]; + high.s[i] = a.s[i+(n/2)]; + high.s[i+(n/2)] = b.s[i+(n/2)]; + } +} + +/** @brief Vector reverse order + +Reverse the order of the vector +Scheme: +@code + REG {A1 ... An} ==> REG {An ... A1} +@endcode +For all types. */ +template +inline v_reg<_Tp, n> v_reverse(const v_reg<_Tp, n>& a) +{ + v_reg<_Tp, n> c; + for( int i = 0; i < n; i++ ) + c.s[i] = a.s[n-i-1]; + return c; +} + +/** @brief Vector extract + +Scheme: +@code + {A1 A2 A3 A4} + {B1 B2 B3 B4} +======================== +shift = 1 {A2 A3 A4 B1} +shift = 2 {A3 A4 B1 B2} +shift = 3 {A4 B1 B2 B3} +@endcode +Restriction: 0 <= shift < nlanes + +Usage: +@code +v_int32x4 a, b, c; +c = v_extract<2>(a, b); +@endcode +For all types. */ +template +inline v_reg<_Tp, n> v_extract(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + v_reg<_Tp, n> r; + const int shift = n - s; + int i = 0; + for (; i < shift; ++i) + r.s[i] = a.s[i+s]; + for (; i < n; ++i) + r.s[i] = b.s[i-shift]; + return r; +} + +/** @brief Vector extract + +Scheme: +Return the s-th element of v. +Restriction: 0 <= s < nlanes + +Usage: +@code +v_int32x4 a; +int r; +r = v_extract_n<2>(a); +@endcode +For all types. */ +template +inline _Tp v_extract_n(const v_reg<_Tp, n>& v) +{ + CV_DbgAssert(s >= 0 && s < n); + return v.s[s]; +} + +/** @brief Broadcast i-th element of vector + +Scheme: +@code +{ v[0] v[1] v[2] ... v[SZ] } => { v[i], v[i], v[i] ... v[i] } +@endcode +Restriction: 0 <= i < nlanes +Supported types: 32-bit integers and floats (s32/u32/f32) + */ +template +inline v_reg<_Tp, n> v_broadcast_element(const v_reg<_Tp, n>& a) +{ + CV_DbgAssert(i >= 0 && i < n); + return v_reg<_Tp, n>::all(a.s[i]); +} + +/** @brief Round elements + +Rounds each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_round(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = cvRound(a.s[i]); + return c; +} + +/** @overload */ +template inline v_reg v_round(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvRound(a.s[i]); + c.s[i+n] = cvRound(b.s[i]); + } + return c; +} + +/** @brief Floor elements + +Floor each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_floor(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = cvFloor(a.s[i]); + return c; +} + +/** @brief Ceil elements + +Ceil each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_ceil(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = cvCeil(a.s[i]); + return c; +} + +/** @brief Truncate elements + +Truncate each value. Input type is float vector ==> output type is int vector. +@note Only for floating point types. +*/ +template inline v_reg v_trunc(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = (int)(a.s[i]); + return c; +} + +/** @overload */ +template inline v_reg v_round(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvRound(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @overload */ +template inline v_reg v_floor(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvFloor(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @overload */ +template inline v_reg v_ceil(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = cvCeil(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @overload */ +template inline v_reg v_trunc(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = (int)(a.s[i]); + c.s[i+n] = 0; + } + return c; +} + +/** @brief Convert to float + +Supported input type is cv::v_int32. */ +template inline v_reg v_cvt_f32(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = (float)a.s[i]; + return c; +} + +/** @brief Convert lower half to float + +Supported input type is cv::v_float64. */ +template inline v_reg v_cvt_f32(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = (float)a.s[i]; + c.s[i+n] = 0; + } + return c; +} + +/** @brief Convert to float + +Supported input type is cv::v_float64. */ +template inline v_reg v_cvt_f32(const v_reg& a, const v_reg& b) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + { + c.s[i] = (float)a.s[i]; + c.s[i+n] = (float)b.s[i]; + } + return c; +} + +/** @brief Convert lower half to double + +Supported input type is cv::v_int32. */ +template CV_INLINE v_reg v_cvt_f64(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i]; + return c; +} + +/** @brief Convert to double high part of vector + +Supported input type is cv::v_int32. */ +template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i + (n/2)]; + return c; +} + +/** @brief Convert lower half to double + +Supported input type is cv::v_float32. */ +template CV_INLINE v_reg v_cvt_f64(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i]; + return c; +} + +/** @brief Convert to double high part of vector + +Supported input type is cv::v_float32. */ +template CV_INLINE v_reg v_cvt_f64_high(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < (n/2); i++ ) + c.s[i] = (double)a.s[i + (n/2)]; + return c; +} + +/** @brief Convert to double + +Supported input type is cv::v_int64. */ +template CV_INLINE v_reg v_cvt_f64(const v_reg& a) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = (double)a.s[i]; + return c; +} + + +template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut(const _Tp* tab, const int* idx) +{ + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes; i++) + c.s[i] = tab[idx[i]]; + return c; +} +template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_pairs(const _Tp* tab, const int* idx) +{ + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes; i++) + c.s[i] = tab[idx[i / 2] + i % 2]; + return c; +} +template inline v_reg<_Tp, simd128_width / sizeof(_Tp)> v_lut_quads(const _Tp* tab, const int* idx) +{ + v_reg<_Tp, simd128_width / sizeof(_Tp)> c; + for (int i = 0; i < c.nlanes; i++) + c.s[i] = tab[idx[i / 4] + i % 4]; + return c; +} + +template inline v_reg v_lut(const int* tab, const v_reg& idx) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = tab[idx.s[i]]; + return c; +} + +template inline v_reg v_lut(const unsigned* tab, const v_reg& idx) +{ + v_reg c; + for (int i = 0; i < n; i++) + c.s[i] = tab[idx.s[i]]; + return c; +} + +template inline v_reg v_lut(const float* tab, const v_reg& idx) +{ + v_reg c; + for( int i = 0; i < n; i++ ) + c.s[i] = tab[idx.s[i]]; + return c; +} + +template inline v_reg v_lut(const double* tab, const v_reg& idx) +{ + v_reg c; + for( int i = 0; i < n/2; i++ ) + c.s[i] = tab[idx.s[i]]; + return c; +} + + +template inline void v_lut_deinterleave(const float* tab, const v_reg& idx, + v_reg& x, v_reg& y) +{ + for( int i = 0; i < n; i++ ) + { + int j = idx.s[i]; + x.s[i] = tab[j]; + y.s[i] = tab[j+1]; + } +} + +template inline void v_lut_deinterleave(const double* tab, const v_reg& idx, + v_reg& x, v_reg& y) +{ + for( int i = 0; i < n; i++ ) + { + int j = idx.s[i]; + x.s[i] = tab[j]; + y.s[i] = tab[j+1]; + } +} + +template inline v_reg<_Tp, n> v_interleave_pairs(const v_reg<_Tp, n>& vec) +{ + v_reg<_Tp, n> c; + for (int i = 0; i < n/4; i++) + { + c.s[4*i ] = vec.s[4*i ]; + c.s[4*i+1] = vec.s[4*i+2]; + c.s[4*i+2] = vec.s[4*i+1]; + c.s[4*i+3] = vec.s[4*i+3]; + } + return c; +} + +template inline v_reg<_Tp, n> v_interleave_quads(const v_reg<_Tp, n>& vec) +{ + v_reg<_Tp, n> c; + for (int i = 0; i < n/8; i++) + { + c.s[8*i ] = vec.s[8*i ]; + c.s[8*i+1] = vec.s[8*i+4]; + c.s[8*i+2] = vec.s[8*i+1]; + c.s[8*i+3] = vec.s[8*i+5]; + c.s[8*i+4] = vec.s[8*i+2]; + c.s[8*i+5] = vec.s[8*i+6]; + c.s[8*i+6] = vec.s[8*i+3]; + c.s[8*i+7] = vec.s[8*i+7]; + } + return c; +} + +template inline v_reg<_Tp, n> v_pack_triplets(const v_reg<_Tp, n>& vec) +{ + v_reg<_Tp, n> c; + for (int i = 0; i < n/4; i++) + { + c.s[3*i ] = vec.s[4*i ]; + c.s[3*i+1] = vec.s[4*i+1]; + c.s[3*i+2] = vec.s[4*i+2]; + } + return c; +} + +/** @brief Transpose 4x4 matrix + +Scheme: +@code +a0 {A1 A2 A3 A4} +a1 {B1 B2 B3 B4} +a2 {C1 C2 C3 C4} +a3 {D1 D2 D3 D4} +=============== +b0 {A1 B1 C1 D1} +b1 {A2 B2 C2 D2} +b2 {A3 B3 C3 D3} +b3 {A4 B4 C4 D4} +@endcode +*/ +template +inline void v_transpose4x4( v_reg<_Tp, n>& a0, const v_reg<_Tp, n>& a1, + const v_reg<_Tp, n>& a2, const v_reg<_Tp, n>& a3, + v_reg<_Tp, n>& b0, v_reg<_Tp, n>& b1, + v_reg<_Tp, n>& b2, v_reg<_Tp, n>& b3 ) +{ + for (int i = 0; i < n / 4; i++) + { + b0.s[0 + i*4] = a0.s[0 + i*4]; b0.s[1 + i*4] = a1.s[0 + i*4]; + b0.s[2 + i*4] = a2.s[0 + i*4]; b0.s[3 + i*4] = a3.s[0 + i*4]; + b1.s[0 + i*4] = a0.s[1 + i*4]; b1.s[1 + i*4] = a1.s[1 + i*4]; + b1.s[2 + i*4] = a2.s[1 + i*4]; b1.s[3 + i*4] = a3.s[1 + i*4]; + b2.s[0 + i*4] = a0.s[2 + i*4]; b2.s[1 + i*4] = a1.s[2 + i*4]; + b2.s[2 + i*4] = a2.s[2 + i*4]; b2.s[3 + i*4] = a3.s[2 + i*4]; + b3.s[0 + i*4] = a0.s[3 + i*4]; b3.s[1 + i*4] = a1.s[3 + i*4]; + b3.s[2 + i*4] = a2.s[3 + i*4]; b3.s[3 + i*4] = a3.s[3 + i*4]; + } +} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_INIT_ZERO(_Tpvec, prefix, suffix) \ +inline _Tpvec prefix##_setzero_##suffix() { return _Tpvec::zero(); } \ +template <> inline _Tpvec v_setzero_() { return _Tpvec::zero(); } + +//! @name Init with zero +//! @{ +//! @brief Create new vector with zero elements +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x16, v, u8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x16, v, s8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x8, v, u16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x8, v, s16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x4, v, u32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x4, v, s32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x4, v, f32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x2, v, f64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x2, v, u64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x2, v, s64) + +#if CV_SIMD256 +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x32, v256, u8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x32, v256, s8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x16, v256, u16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x16, v256, s16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x8, v256, u32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x8, v256, s32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x8, v256, f32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x4, v256, f64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x4, v256, u64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x4, v256, s64) +#endif + +#if CV_SIMD512 +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint8x64, v512, u8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int8x64, v512, s8) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint16x32, v512, u16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int16x32, v512, s16) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint32x16, v512, u32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int32x16, v512, s32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float32x16, v512, f32) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_float64x8, v512, f64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_uint64x8, v512, u64) +OPENCV_HAL_IMPL_C_INIT_ZERO(v_int64x8, v512, s64) +#endif +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_INIT_VAL(_Tpvec, _Tp, prefix, suffix) \ +inline _Tpvec prefix##_setall_##suffix(_Tp val) { return _Tpvec::all(val); } \ +template <> inline _Tpvec v_setall_(_Tp val) { return _Tpvec::all(val); } + +//! @name Init with value +//! @{ +//! @brief Create new vector with elements set to a specific value +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x16, uchar, v, u8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x16, schar, v, s8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x8, ushort, v, u16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x8, short, v, s16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x4, unsigned, v, u32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x4, int, v, s32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x4, float, v, f32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x2, double, v, f64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x2, uint64, v, u64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x2, int64, v, s64) + +#if CV_SIMD256 +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x32, uchar, v256, u8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x32, schar, v256, s8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x16, ushort, v256, u16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x16, short, v256, s16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x8, unsigned, v256, u32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x8, int, v256, s32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x8, float, v256, f32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x4, double, v256, f64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x4, uint64, v256, u64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x4, int64, v256, s64) +#endif + +#if CV_SIMD512 +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint8x64, uchar, v512, u8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int8x64, schar, v512, s8) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint16x32, ushort, v512, u16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int16x32, short, v512, s16) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint32x16, unsigned, v512, u32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int32x16, int, v512, s32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float32x16, float, v512, f32) +OPENCV_HAL_IMPL_C_INIT_VAL(v_float64x8, double, v512, f64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_uint64x8, uint64, v512, u64) +OPENCV_HAL_IMPL_C_INIT_VAL(v_int64x8, int64, v512, s64) +#endif +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_REINTERPRET(_Tp, suffix) \ +template inline v_reg<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)> \ + v_reinterpret_as_##suffix(const v_reg<_Tp0, n0>& a) \ +{ return a.template reinterpret_as<_Tp, n0*sizeof(_Tp0)/sizeof(_Tp)>(); } + +//! @name Reinterpret +//! @{ +//! @brief Convert vector to different type without modifying underlying data. +OPENCV_HAL_IMPL_C_REINTERPRET(uchar, u8) +OPENCV_HAL_IMPL_C_REINTERPRET(schar, s8) +OPENCV_HAL_IMPL_C_REINTERPRET(ushort, u16) +OPENCV_HAL_IMPL_C_REINTERPRET(short, s16) +OPENCV_HAL_IMPL_C_REINTERPRET(unsigned, u32) +OPENCV_HAL_IMPL_C_REINTERPRET(int, s32) +OPENCV_HAL_IMPL_C_REINTERPRET(float, f32) +OPENCV_HAL_IMPL_C_REINTERPRET(double, f64) +OPENCV_HAL_IMPL_C_REINTERPRET(uint64, u64) +OPENCV_HAL_IMPL_C_REINTERPRET(int64, s64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_SHIFTL(_Tp) \ +template inline v_reg<_Tp, n> v_shl(const v_reg<_Tp, n>& a) \ +{ return v_shl(a, shift); } + +//! @name Left shift +//! @{ +//! @brief Shift left +OPENCV_HAL_IMPL_C_SHIFTL(ushort) +OPENCV_HAL_IMPL_C_SHIFTL(short) +OPENCV_HAL_IMPL_C_SHIFTL(unsigned) +OPENCV_HAL_IMPL_C_SHIFTL(int) +OPENCV_HAL_IMPL_C_SHIFTL(uint64) +OPENCV_HAL_IMPL_C_SHIFTL(int64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_SHIFTR(_Tp) \ +template inline v_reg<_Tp, n> v_shr(const v_reg<_Tp, n>& a) \ +{ return v_shr(a, shift); } + +//! @name Right shift +//! @{ +//! @brief Shift right +OPENCV_HAL_IMPL_C_SHIFTR(ushort) +OPENCV_HAL_IMPL_C_SHIFTR(short) +OPENCV_HAL_IMPL_C_SHIFTR(unsigned) +OPENCV_HAL_IMPL_C_SHIFTR(int) +OPENCV_HAL_IMPL_C_SHIFTR(uint64) +OPENCV_HAL_IMPL_C_SHIFTR(int64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_RSHIFTR(_Tp) \ +template inline v_reg<_Tp, n> v_rshr(const v_reg<_Tp, n>& a) \ +{ \ + v_reg<_Tp, n> c; \ + for( int i = 0; i < n; i++ ) \ + c.s[i] = (_Tp)((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ + return c; \ +} + +//! @name Rounding shift +//! @{ +//! @brief Rounding shift right +OPENCV_HAL_IMPL_C_RSHIFTR(ushort) +OPENCV_HAL_IMPL_C_RSHIFTR(short) +OPENCV_HAL_IMPL_C_RSHIFTR(unsigned) +OPENCV_HAL_IMPL_C_RSHIFTR(int) +OPENCV_HAL_IMPL_C_RSHIFTR(uint64) +OPENCV_HAL_IMPL_C_RSHIFTR(int64) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_PACK(_Tp, _Tpn, pack_suffix, cast) \ +template inline v_reg<_Tpn, 2*n> v_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tpn, 2*n> c; \ + for( int i = 0; i < n; i++ ) \ + { \ + c.s[i] = cast<_Tpn>(a.s[i]); \ + c.s[i+n] = cast<_Tpn>(b.s[i]); \ + } \ + return c; \ +} + +//! @name Pack +//! @{ +//! @brief Pack values from two vectors to one +//! +//! Return vector type have twice more elements than input vector types. Variant with _u_ suffix also +//! converts to corresponding unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_PACK(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_PACK(int, ushort, pack_u, saturate_cast) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_RSHR_PACK(_Tp, _Tpn, pack_suffix, cast) \ +template inline v_reg<_Tpn, 2*n> v_rshr_##pack_suffix(const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) \ +{ \ + v_reg<_Tpn, 2*n> c; \ + for( int i = 0; i < n; i++ ) \ + { \ + c.s[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ + c.s[i+n] = cast<_Tpn>((b.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ + } \ + return c; \ +} + +//! @name Pack with rounding shift +//! @{ +//! @brief Pack values from two vectors to one with rounding shift +//! +//! Values from the input vectors will be shifted right by _n_ bits with rounding, converted to narrower +//! type and returned in the result vector. Variant with _u_ suffix converts to unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_RSHR_PACK(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK(int, ushort, pack_u, saturate_cast) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ +template inline void v_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ +{ \ + for( int i = 0; i < n; i++ ) \ + ptr[i] = cast<_Tpn>(a.s[i]); \ +} + +//! @name Pack and store +//! @{ +//! @brief Store values from the input vector into memory with pack +//! +//! Values will be stored into memory with conversion to narrower type. +//! Variant with _u_ suffix converts to corresponding unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_PACK_STORE(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_PACK_STORE(int, ushort, pack_u, saturate_cast) +//! @} + +//! @brief Helper macro +//! @ingroup core_hal_intrin_impl +#define OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(_Tp, _Tpn, pack_suffix, cast) \ +template inline void v_rshr_##pack_suffix##_store(_Tpn* ptr, const v_reg<_Tp, n>& a) \ +{ \ + for( int i = 0; i < n; i++ ) \ + ptr[i] = cast<_Tpn>((a.s[i] + ((_Tp)1 << (shift - 1))) >> shift); \ +} + +//! @name Pack and store with rounding shift +//! @{ +//! @brief Store values from the input vector into memory with pack +//! +//! Values will be shifted _n_ bits right with rounding, converted to narrower type and stored into +//! memory. Variant with _u_ suffix converts to unsigned type. +//! +//! - pack: for 16-, 32- and 64-bit integer input types +//! - pack_u: for 16- and 32-bit signed integer input types +//! +//! @note All variants except 64-bit use saturation. +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(ushort, uchar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, schar, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(unsigned, ushort, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, short, pack, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(uint64, unsigned, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int64, int, pack, static_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(short, uchar, pack_u, saturate_cast) +OPENCV_HAL_IMPL_C_RSHR_PACK_STORE(int, ushort, pack_u, saturate_cast) +//! @} + +//! @cond IGNORED +template +inline void _pack_b(_Tpm* mptr, const v_reg<_Tp, n>& a, const v_reg<_Tp, n>& b) +{ + for (int i = 0; i < n; ++i) + { + mptr[i] = (_Tpm)a.s[i]; + mptr[i + n] = (_Tpm)b.s[i]; + } +} +//! @endcond + +//! @name Pack boolean values +//! @{ +//! @brief Pack boolean values from multiple vectors to one unsigned 8-bit integer vector +//! +//! @note Must provide valid boolean values to guarantee same result for all architectures. + +/** @brief +//! For 16-bit boolean values + +Scheme: +@code +a {0xFFFF 0 0 0xFFFF 0 0xFFFF 0xFFFF 0} +b {0xFFFF 0 0xFFFF 0 0 0xFFFF 0 0xFFFF} +=============== +{ + 0xFF 0 0 0xFF 0 0xFF 0xFF 0 + 0xFF 0 0xFF 0 0 0xFF 0 0xFF +} +@endcode */ + +template inline v_reg v_pack_b(const v_reg& a, const v_reg& b) +{ + v_reg mask; + _pack_b(mask.s, a, b); + return mask; +} + +/** @overload +For 32-bit boolean values + +Scheme: +@code +a {0xFFFF.. 0 0 0xFFFF..} +b {0 0xFFFF.. 0xFFFF.. 0} +c {0xFFFF.. 0 0xFFFF.. 0} +d {0 0xFFFF.. 0 0xFFFF..} +=============== +{ + 0xFF 0 0 0xFF 0 0xFF 0xFF 0 + 0xFF 0 0xFF 0 0 0xFF 0 0xFF +} +@endcode */ + +template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg mask; + _pack_b(mask.s, a, b); + _pack_b(mask.s + 2*n, c, d); + return mask; +} + +/** @overload +For 64-bit boolean values + +Scheme: +@code +a {0xFFFF.. 0} +b {0 0xFFFF..} +c {0xFFFF.. 0} +d {0 0xFFFF..} + +e {0xFFFF.. 0} +f {0xFFFF.. 0} +g {0 0xFFFF..} +h {0 0xFFFF..} +=============== +{ + 0xFF 0 0 0xFF 0xFF 0 0 0xFF + 0xFF 0 0xFF 0 0 0xFF 0 0xFF +} +@endcode */ +template inline v_reg v_pack_b(const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d, + const v_reg& e, const v_reg& f, + const v_reg& g, const v_reg& h) +{ + v_reg mask; + _pack_b(mask.s, a, b); + _pack_b(mask.s + 2*n, c, d); + _pack_b(mask.s + 4*n, e, f); + _pack_b(mask.s + 6*n, g, h); + return mask; +} +//! @} + +/** @brief Matrix multiplication + +Scheme: +@code +{A0 A1 A2 A3} |V0| +{B0 B1 B2 B3} |V1| +{C0 C1 C2 C3} |V2| +{D0 D1 D2 D3} x |V3| +==================== +{R0 R1 R2 R3}, where: +R0 = A0V0 + B0V1 + C0V2 + D0V3, +R1 = A1V0 + B1V1 + C1V2 + D1V3 +... +@endcode +*/ +template +inline v_reg v_matmul(const v_reg& v, + const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg res; + for (int i = 0; i < n / 4; i++) + { + res.s[0 + i*4] = v.s[0 + i*4] * a.s[0 + i*4] + v.s[1 + i*4] * b.s[0 + i*4] + v.s[2 + i*4] * c.s[0 + i*4] + v.s[3 + i*4] * d.s[0 + i*4]; + res.s[1 + i*4] = v.s[0 + i*4] * a.s[1 + i*4] + v.s[1 + i*4] * b.s[1 + i*4] + v.s[2 + i*4] * c.s[1 + i*4] + v.s[3 + i*4] * d.s[1 + i*4]; + res.s[2 + i*4] = v.s[0 + i*4] * a.s[2 + i*4] + v.s[1 + i*4] * b.s[2 + i*4] + v.s[2 + i*4] * c.s[2 + i*4] + v.s[3 + i*4] * d.s[2 + i*4]; + res.s[3 + i*4] = v.s[0 + i*4] * a.s[3 + i*4] + v.s[1 + i*4] * b.s[3 + i*4] + v.s[2 + i*4] * c.s[3 + i*4] + v.s[3 + i*4] * d.s[3 + i*4]; + } + return res; +} + +/** @brief Matrix multiplication and add + +Scheme: +@code +{A0 A1 A2 A3} |V0| |D0| +{B0 B1 B2 B3} |V1| |D1| +{C0 C1 C2 C3} x |V2| + |D2| +==================== |D3| +{R0 R1 R2 R3}, where: +R0 = A0V0 + B0V1 + C0V2 + D0, +R1 = A1V0 + B1V1 + C1V2 + D1 +... +@endcode +*/ +template +inline v_reg v_matmuladd(const v_reg& v, + const v_reg& a, const v_reg& b, + const v_reg& c, const v_reg& d) +{ + v_reg res; + for (int i = 0; i < n / 4; i++) + { + res.s[0 + i * 4] = v.s[0 + i * 4] * a.s[0 + i * 4] + v.s[1 + i * 4] * b.s[0 + i * 4] + v.s[2 + i * 4] * c.s[0 + i * 4] + d.s[0 + i * 4]; + res.s[1 + i * 4] = v.s[0 + i * 4] * a.s[1 + i * 4] + v.s[1 + i * 4] * b.s[1 + i * 4] + v.s[2 + i * 4] * c.s[1 + i * 4] + d.s[1 + i * 4]; + res.s[2 + i * 4] = v.s[0 + i * 4] * a.s[2 + i * 4] + v.s[1 + i * 4] * b.s[2 + i * 4] + v.s[2 + i * 4] * c.s[2 + i * 4] + d.s[2 + i * 4]; + res.s[3 + i * 4] = v.s[0 + i * 4] * a.s[3 + i * 4] + v.s[1 + i * 4] * b.s[3 + i * 4] + v.s[2 + i * 4] * c.s[3 + i * 4] + d.s[3 + i * 4]; + } + return res; +} + + +template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } +template inline v_reg v_dotprod_expand(const v_reg& a, const v_reg& b, + const v_reg& c) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } + +template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b) +{ return v_dotprod_expand(a, b); } +template inline v_reg v_dotprod_expand_fast(const v_reg& a, const v_reg& b, + const v_reg& c) +{ return v_dotprod_expand(a, b, c); } + +////// FP16 support /////// + +inline v_reg +v_load_expand(const hfloat* ptr) +{ + v_reg v; + for( int i = 0; i < v.nlanes; i++ ) + { + v.s[i] = ptr[i]; + } + return v; +} +#if CV_SIMD256 +inline v_reg +v256_load_expand(const hfloat* ptr) +{ + v_reg v; + for (int i = 0; i < v.nlanes; i++) + { + v.s[i] = ptr[i]; + } + return v; +} +#endif +#if CV_SIMD512 +inline v_reg +v512_load_expand(const hfloat* ptr) +{ + v_reg v; + for (int i = 0; i < v.nlanes; i++) + { + v.s[i] = ptr[i]; + } + return v; +} +#endif + +template inline void +v_pack_store(hfloat* ptr, const v_reg& v) +{ + for( int i = 0; i < v.nlanes; i++ ) + { + ptr[i] = hfloat(v.s[i]); + } +} + +inline void v_cleanup() {} +#if CV_SIMD256 +inline void v256_cleanup() {} +#endif +#if CV_SIMD512 +inline void v512_cleanup() {} +#endif + +//! @} + +#ifndef CV_DOXYGEN +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END +#endif +} + +#if !defined(CV_DOXYGEN) +#undef CV_SIMD256 +#undef CV_SIMD512 +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp index 524574c6d8..28f67cc9ef 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_forward.hpp @@ -1,191 +1,191 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef CV__SIMD_FORWARD -#error "Need to pre-define forward width" -#endif - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -/** Types **/ -#if CV__SIMD_FORWARD == 1024 -// [todo] 1024 -#error "1024-long ops not implemented yet" -#elif CV__SIMD_FORWARD == 512 -// 512 -#define __CV_VX(fun) v512_##fun -#define __CV_V_UINT8 v_uint8x64 -#define __CV_V_INT8 v_int8x64 -#define __CV_V_UINT16 v_uint16x32 -#define __CV_V_INT16 v_int16x32 -#define __CV_V_UINT32 v_uint32x16 -#define __CV_V_INT32 v_int32x16 -#define __CV_V_UINT64 v_uint64x8 -#define __CV_V_INT64 v_int64x8 -#define __CV_V_FLOAT32 v_float32x16 -#define __CV_V_FLOAT64 v_float64x8 -struct v_uint8x64; -struct v_int8x64; -struct v_uint16x32; -struct v_int16x32; -struct v_uint32x16; -struct v_int32x16; -struct v_uint64x8; -struct v_int64x8; -struct v_float32x16; -struct v_float64x8; -#elif CV__SIMD_FORWARD == 256 -// 256 -#define __CV_VX(fun) v256_##fun -#define __CV_V_UINT8 v_uint8x32 -#define __CV_V_INT8 v_int8x32 -#define __CV_V_UINT16 v_uint16x16 -#define __CV_V_INT16 v_int16x16 -#define __CV_V_UINT32 v_uint32x8 -#define __CV_V_INT32 v_int32x8 -#define __CV_V_UINT64 v_uint64x4 -#define __CV_V_INT64 v_int64x4 -#define __CV_V_FLOAT32 v_float32x8 -#define __CV_V_FLOAT64 v_float64x4 -struct v_uint8x32; -struct v_int8x32; -struct v_uint16x16; -struct v_int16x16; -struct v_uint32x8; -struct v_int32x8; -struct v_uint64x4; -struct v_int64x4; -struct v_float32x8; -struct v_float64x4; -#else -// 128 -#define __CV_VX(fun) v_##fun -#define __CV_V_UINT8 v_uint8x16 -#define __CV_V_INT8 v_int8x16 -#define __CV_V_UINT16 v_uint16x8 -#define __CV_V_INT16 v_int16x8 -#define __CV_V_UINT32 v_uint32x4 -#define __CV_V_INT32 v_int32x4 -#define __CV_V_UINT64 v_uint64x2 -#define __CV_V_INT64 v_int64x2 -#define __CV_V_FLOAT32 v_float32x4 -#define __CV_V_FLOAT64 v_float64x2 -struct v_uint8x16; -struct v_int8x16; -struct v_uint16x8; -struct v_int16x8; -struct v_uint32x4; -struct v_int32x4; -struct v_uint64x2; -struct v_int64x2; -struct v_float32x4; -struct v_float64x2; -#endif - -/** Value reordering **/ - -// Expansion -void v_expand(const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); -void v_expand(const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); -void v_expand(const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); -void v_expand(const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); -void v_expand(const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); -void v_expand(const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); -// Low Expansion -__CV_V_UINT16 v_expand_low(const __CV_V_UINT8&); -__CV_V_INT16 v_expand_low(const __CV_V_INT8&); -__CV_V_UINT32 v_expand_low(const __CV_V_UINT16&); -__CV_V_INT32 v_expand_low(const __CV_V_INT16&); -__CV_V_UINT64 v_expand_low(const __CV_V_UINT32&); -__CV_V_INT64 v_expand_low(const __CV_V_INT32&); -// High Expansion -__CV_V_UINT16 v_expand_high(const __CV_V_UINT8&); -__CV_V_INT16 v_expand_high(const __CV_V_INT8&); -__CV_V_UINT32 v_expand_high(const __CV_V_UINT16&); -__CV_V_INT32 v_expand_high(const __CV_V_INT16&); -__CV_V_UINT64 v_expand_high(const __CV_V_UINT32&); -__CV_V_INT64 v_expand_high(const __CV_V_INT32&); -// Load & Low Expansion -__CV_V_UINT16 __CV_VX(load_expand)(const uchar*); -__CV_V_INT16 __CV_VX(load_expand)(const schar*); -__CV_V_UINT32 __CV_VX(load_expand)(const ushort*); -__CV_V_INT32 __CV_VX(load_expand)(const short*); -__CV_V_UINT64 __CV_VX(load_expand)(const uint*); -__CV_V_INT64 __CV_VX(load_expand)(const int*); -// Load lower 8-bit and expand into 32-bit -__CV_V_UINT32 __CV_VX(load_expand_q)(const uchar*); -__CV_V_INT32 __CV_VX(load_expand_q)(const schar*); - -// Saturating Pack -__CV_V_UINT8 v_pack(const __CV_V_UINT16&, const __CV_V_UINT16&); -__CV_V_INT8 v_pack(const __CV_V_INT16&, const __CV_V_INT16&); -__CV_V_UINT16 v_pack(const __CV_V_UINT32&, const __CV_V_UINT32&); -__CV_V_INT16 v_pack(const __CV_V_INT32&, const __CV_V_INT32&); -// Non-saturating Pack -__CV_V_UINT32 v_pack(const __CV_V_UINT64&, const __CV_V_UINT64&); -__CV_V_INT32 v_pack(const __CV_V_INT64&, const __CV_V_INT64&); -// Pack signed integers with unsigned saturation -__CV_V_UINT8 v_pack_u(const __CV_V_INT16&, const __CV_V_INT16&); -__CV_V_UINT16 v_pack_u(const __CV_V_INT32&, const __CV_V_INT32&); - -/** Arithmetic, bitwise and comparison operations **/ - -// Non-saturating multiply -#if CV_VSX -template -Tvec v_mul_wrap(const Tvec& a, const Tvec& b); -#else -__CV_V_UINT8 v_mul_wrap(const __CV_V_UINT8&, const __CV_V_UINT8&); -__CV_V_INT8 v_mul_wrap(const __CV_V_INT8&, const __CV_V_INT8&); -__CV_V_UINT16 v_mul_wrap(const __CV_V_UINT16&, const __CV_V_UINT16&); -__CV_V_INT16 v_mul_wrap(const __CV_V_INT16&, const __CV_V_INT16&); -#endif - -// Multiply and expand -#if CV_VSX -template -void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d); -#else -void v_mul_expand(const __CV_V_UINT8&, const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); -void v_mul_expand(const __CV_V_INT8&, const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); -void v_mul_expand(const __CV_V_UINT16&, const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); -void v_mul_expand(const __CV_V_INT16&, const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); -void v_mul_expand(const __CV_V_UINT32&, const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); -void v_mul_expand(const __CV_V_INT32&, const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); -#endif - -// Conversions -__CV_V_FLOAT32 v_cvt_f32(const __CV_V_INT32& a); -__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a); -__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a, const __CV_V_FLOAT64& b); -__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT32& a); -__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_INT32& a); -__CV_V_FLOAT64 v_cvt_f64(const __CV_V_FLOAT32& a); -__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_FLOAT32& a); -__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT64& a); - -/** Cleanup **/ -#undef CV__SIMD_FORWARD -#undef __CV_VX -#undef __CV_V_UINT8 -#undef __CV_V_INT8 -#undef __CV_V_UINT16 -#undef __CV_V_INT16 -#undef __CV_V_UINT32 -#undef __CV_V_INT32 -#undef __CV_V_UINT64 -#undef __CV_V_INT64 -#undef __CV_V_FLOAT32 -#undef __CV_V_FLOAT64 - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef CV__SIMD_FORWARD +#error "Need to pre-define forward width" +#endif + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +/** Types **/ +#if CV__SIMD_FORWARD == 1024 +// [todo] 1024 +#error "1024-long ops not implemented yet" +#elif CV__SIMD_FORWARD == 512 +// 512 +#define __CV_VX(fun) v512_##fun +#define __CV_V_UINT8 v_uint8x64 +#define __CV_V_INT8 v_int8x64 +#define __CV_V_UINT16 v_uint16x32 +#define __CV_V_INT16 v_int16x32 +#define __CV_V_UINT32 v_uint32x16 +#define __CV_V_INT32 v_int32x16 +#define __CV_V_UINT64 v_uint64x8 +#define __CV_V_INT64 v_int64x8 +#define __CV_V_FLOAT32 v_float32x16 +#define __CV_V_FLOAT64 v_float64x8 +struct v_uint8x64; +struct v_int8x64; +struct v_uint16x32; +struct v_int16x32; +struct v_uint32x16; +struct v_int32x16; +struct v_uint64x8; +struct v_int64x8; +struct v_float32x16; +struct v_float64x8; +#elif CV__SIMD_FORWARD == 256 +// 256 +#define __CV_VX(fun) v256_##fun +#define __CV_V_UINT8 v_uint8x32 +#define __CV_V_INT8 v_int8x32 +#define __CV_V_UINT16 v_uint16x16 +#define __CV_V_INT16 v_int16x16 +#define __CV_V_UINT32 v_uint32x8 +#define __CV_V_INT32 v_int32x8 +#define __CV_V_UINT64 v_uint64x4 +#define __CV_V_INT64 v_int64x4 +#define __CV_V_FLOAT32 v_float32x8 +#define __CV_V_FLOAT64 v_float64x4 +struct v_uint8x32; +struct v_int8x32; +struct v_uint16x16; +struct v_int16x16; +struct v_uint32x8; +struct v_int32x8; +struct v_uint64x4; +struct v_int64x4; +struct v_float32x8; +struct v_float64x4; +#else +// 128 +#define __CV_VX(fun) v_##fun +#define __CV_V_UINT8 v_uint8x16 +#define __CV_V_INT8 v_int8x16 +#define __CV_V_UINT16 v_uint16x8 +#define __CV_V_INT16 v_int16x8 +#define __CV_V_UINT32 v_uint32x4 +#define __CV_V_INT32 v_int32x4 +#define __CV_V_UINT64 v_uint64x2 +#define __CV_V_INT64 v_int64x2 +#define __CV_V_FLOAT32 v_float32x4 +#define __CV_V_FLOAT64 v_float64x2 +struct v_uint8x16; +struct v_int8x16; +struct v_uint16x8; +struct v_int16x8; +struct v_uint32x4; +struct v_int32x4; +struct v_uint64x2; +struct v_int64x2; +struct v_float32x4; +struct v_float64x2; +#endif + +/** Value reordering **/ + +// Expansion +void v_expand(const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); +void v_expand(const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); +void v_expand(const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); +void v_expand(const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); +void v_expand(const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); +void v_expand(const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); +// Low Expansion +__CV_V_UINT16 v_expand_low(const __CV_V_UINT8&); +__CV_V_INT16 v_expand_low(const __CV_V_INT8&); +__CV_V_UINT32 v_expand_low(const __CV_V_UINT16&); +__CV_V_INT32 v_expand_low(const __CV_V_INT16&); +__CV_V_UINT64 v_expand_low(const __CV_V_UINT32&); +__CV_V_INT64 v_expand_low(const __CV_V_INT32&); +// High Expansion +__CV_V_UINT16 v_expand_high(const __CV_V_UINT8&); +__CV_V_INT16 v_expand_high(const __CV_V_INT8&); +__CV_V_UINT32 v_expand_high(const __CV_V_UINT16&); +__CV_V_INT32 v_expand_high(const __CV_V_INT16&); +__CV_V_UINT64 v_expand_high(const __CV_V_UINT32&); +__CV_V_INT64 v_expand_high(const __CV_V_INT32&); +// Load & Low Expansion +__CV_V_UINT16 __CV_VX(load_expand)(const uchar*); +__CV_V_INT16 __CV_VX(load_expand)(const schar*); +__CV_V_UINT32 __CV_VX(load_expand)(const ushort*); +__CV_V_INT32 __CV_VX(load_expand)(const short*); +__CV_V_UINT64 __CV_VX(load_expand)(const uint*); +__CV_V_INT64 __CV_VX(load_expand)(const int*); +// Load lower 8-bit and expand into 32-bit +__CV_V_UINT32 __CV_VX(load_expand_q)(const uchar*); +__CV_V_INT32 __CV_VX(load_expand_q)(const schar*); + +// Saturating Pack +__CV_V_UINT8 v_pack(const __CV_V_UINT16&, const __CV_V_UINT16&); +__CV_V_INT8 v_pack(const __CV_V_INT16&, const __CV_V_INT16&); +__CV_V_UINT16 v_pack(const __CV_V_UINT32&, const __CV_V_UINT32&); +__CV_V_INT16 v_pack(const __CV_V_INT32&, const __CV_V_INT32&); +// Non-saturating Pack +__CV_V_UINT32 v_pack(const __CV_V_UINT64&, const __CV_V_UINT64&); +__CV_V_INT32 v_pack(const __CV_V_INT64&, const __CV_V_INT64&); +// Pack signed integers with unsigned saturation +__CV_V_UINT8 v_pack_u(const __CV_V_INT16&, const __CV_V_INT16&); +__CV_V_UINT16 v_pack_u(const __CV_V_INT32&, const __CV_V_INT32&); + +/** Arithmetic, bitwise and comparison operations **/ + +// Non-saturating multiply +#if CV_VSX +template +Tvec v_mul_wrap(const Tvec& a, const Tvec& b); +#else +__CV_V_UINT8 v_mul_wrap(const __CV_V_UINT8&, const __CV_V_UINT8&); +__CV_V_INT8 v_mul_wrap(const __CV_V_INT8&, const __CV_V_INT8&); +__CV_V_UINT16 v_mul_wrap(const __CV_V_UINT16&, const __CV_V_UINT16&); +__CV_V_INT16 v_mul_wrap(const __CV_V_INT16&, const __CV_V_INT16&); +#endif + +// Multiply and expand +#if CV_VSX +template +void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d); +#else +void v_mul_expand(const __CV_V_UINT8&, const __CV_V_UINT8&, __CV_V_UINT16&, __CV_V_UINT16&); +void v_mul_expand(const __CV_V_INT8&, const __CV_V_INT8&, __CV_V_INT16&, __CV_V_INT16&); +void v_mul_expand(const __CV_V_UINT16&, const __CV_V_UINT16&, __CV_V_UINT32&, __CV_V_UINT32&); +void v_mul_expand(const __CV_V_INT16&, const __CV_V_INT16&, __CV_V_INT32&, __CV_V_INT32&); +void v_mul_expand(const __CV_V_UINT32&, const __CV_V_UINT32&, __CV_V_UINT64&, __CV_V_UINT64&); +void v_mul_expand(const __CV_V_INT32&, const __CV_V_INT32&, __CV_V_INT64&, __CV_V_INT64&); +#endif + +// Conversions +__CV_V_FLOAT32 v_cvt_f32(const __CV_V_INT32& a); +__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a); +__CV_V_FLOAT32 v_cvt_f32(const __CV_V_FLOAT64& a, const __CV_V_FLOAT64& b); +__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT32& a); +__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_INT32& a); +__CV_V_FLOAT64 v_cvt_f64(const __CV_V_FLOAT32& a); +__CV_V_FLOAT64 v_cvt_f64_high(const __CV_V_FLOAT32& a); +__CV_V_FLOAT64 v_cvt_f64(const __CV_V_INT64& a); + +/** Cleanup **/ +#undef CV__SIMD_FORWARD +#undef __CV_VX +#undef __CV_V_UINT8 +#undef __CV_V_INT8 +#undef __CV_V_UINT16 +#undef __CV_V_INT16 +#undef __CV_V_UINT32 +#undef __CV_V_INT32 +#undef __CV_V_UINT64 +#undef __CV_V_INT64 +#undef __CV_V_FLOAT32 +#undef __CV_V_FLOAT64 + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp index 6f53a5f9bf..3661b7ef32 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lasx.hpp @@ -1,3036 +1,3036 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_LASX_HPP -#define OPENCV_HAL_INTRIN_LASX_HPP - -#include -#include - -#define CV_SIMD256 1 -#define CV_SIMD256_64F 1 -#define CV_SIMD256_FP16 0 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Utils //////////// - -inline __m256i _v256_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, - char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, - char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, - char v30, char v31) -{ - return (__m256i)v32i8{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, - v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, - v30, v31 }; -} - -inline __m256i _v256_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, - char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, - char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, - char v30, char v31) -{ - return (__m256i)v32i8{ v31, v30, - v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, - v19, v18, v17, v16, v15, v14, v13, v12, v11, v10, - v9, v8, v7, v6, v5, v4, v3, v2, v1, v0 }; -} - -inline __m256i _v256_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15) -{ - return (__m256i)v16i16{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; -} - -inline __m256i _v256_setr_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) -{ - return (__m256i)v8i32{ v0, v1, v2, v3, v4, v5, v6, v7 }; -} - -inline __m256i _v256_set_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) -{ - return (__m256i)v8i32{ v7, v6, v5, v4, v3, v2, v1, v0 }; -} - -inline __m256i _v256_setall_w(int v0) -{ - return (__m256i)v8i32{ v0, v0, v0, v0, v0, v0, v0, v0 }; -} - -inline __m256i _v256_setr_d(int64 v0, int64 v1, int64 v2, int64 v3) -{ - return (__m256i)v4i64{ v0, v1, v2, v3 }; -} - -inline __m256i _v256_set_d(int64 v0, int64 v1, int64 v2, int64 v3) -{ - return (__m256i)v4i64{ v3, v2, v1, v0 }; -} - -inline __m256 _v256_setr_ps(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7) -{ - return (__m256)v8f32{ v0, v1, v2, v3, v4, v5, v6, v7 }; -} - -inline __m256 _v256_setall_ps(float f32) -{ - return (__m256)v8f32{ f32, f32, f32, f32, f32, f32, f32, f32 }; -} - -inline __m256d _v256_setr_pd(double v0, double v1, double v2, double v3) -{ - return (__m256d)v4f64{ v0, v1, v2, v3 }; -} - -inline __m256d _v256_setall_pd(double f64) -{ - return (__m256d)v4f64{ f64, f64, f64, f64 }; -} - -inline __m256i _lasx_packus_h(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_bu_h(b, a, 0); -} - -inline __m256i _lasx_packs_h(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_b_h(b, a, 0); -} - -inline __m256i _lasx_packus_w(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_hu_w(b, a, 0); -} - -inline __m256i _lasx_packs_w(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrarni_h_w(b, a, 0); -} - -inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) -{ return __lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02); } - -inline __m256 _v256_combine(const __m128& lo, const __m128& hi) -{ return __m256(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } - -inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) -{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } - -inline __m256i _v256_shuffle_odd_64(const __m256i& v) -{ return __lasx_xvpermi_d(v, 0xd8); } - -inline __m256d _v256_shuffle_odd_64(const __m256d& v) -{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&v), 0xd8)); } - -//LASX: only use for permute WITHOUT zero clearing -template -inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) -{ return __lasx_xvpermi_q(a, b, imm); } - -template -inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) -{ return __m256(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } - -template -inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) -{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } - -template -inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } - -template -inline __m256i _v256_permute4x64(const __m256i& a) -{ return __lasx_xvpermi_d(a, imm); } - -template -inline __m256d _v256_permute4x64(const __m256d& a) -{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&a), imm)); } - -template -inline _Tpvec v256_permute4x64(const _Tpvec& a) -{ return _Tpvec(_v256_permute4x64(a.val)); } - -inline __m128i _v256_extract_high(const __m256i& v) -{ __m256i temp256i = __lasx_xvpermi_d(v, 0x4E); - return *((__m128i*)&temp256i); } - -inline __m128 _v256_extract_high(const __m256& v) -{ return __m128(_v256_extract_high(*((__m256i*)&v))); } - -inline __m128d _v256_extract_high(const __m256d& v) -{ return __m128d(_v256_extract_high(*((__m256i*)&v))); } - -inline __m128i _v256_extract_low(const __m256i& v) -{ return *((__m128i*)&v); } - -inline __m128 _v256_extract_low(const __m256& v) -{ return __m128(_v256_extract_low(*((__m256i*)&v))); } - -inline __m128d _v256_extract_low(const __m256d& v) -{ return __m128d(_v256_extract_low(*((__m256i*)&v))); } - -inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) -{ - return __lasx_xvssrlrni_hu_w(b, a, 0); -} - -template -inline int _v256_extract_b(const __m256i& a) -{ - int des[1] = {0}; - __lasx_xvstelm_b(a, des, 0, i); - return des[0]; -} - -template -inline int _v256_extract_h(const __m256i& a) -{ - int des[1] = {0}; - __lasx_xvstelm_h(a, des, 0, i); - return des[0]; -} - -template -inline int _v256_extract_w(const __m256i& a) -{ - return __lasx_xvpickve2gr_w(a, i); -} - -template -inline int64 _v256_extract_d(const __m256i& a) -{ - return __lasx_xvpickve2gr_d(a, i); -} - -///////// Types //////////// - -struct v_uint8x32 -{ - typedef uchar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_uint8x32(__m256i v) : val(v) {} - v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, - uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, - uchar v12, uchar v13, uchar v14, uchar v15, - uchar v16, uchar v17, uchar v18, uchar v19, - uchar v20, uchar v21, uchar v22, uchar v23, - uchar v24, uchar v25, uchar v26, uchar v27, - uchar v28, uchar v29, uchar v30, uchar v31) - { - val = _v256_setr_b((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, - (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, - (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, - (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, - (char)v28, (char)v29, (char)v30, (char)v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint8x32() {} - - uchar get0() const { - uchar des[1] = {0}; - __lasx_xvstelm_b(val, des, 0, 0); - return des[0]; - } -}; - -struct v_int8x32 -{ - typedef schar lane_type; - enum { nlanes = 32 }; - __m256i val; - - explicit v_int8x32(__m256i v) : val(v) {} - v_int8x32(schar v0, schar v1, schar v2, schar v3, - schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, - schar v12, schar v13, schar v14, schar v15, - schar v16, schar v17, schar v18, schar v19, - schar v20, schar v21, schar v22, schar v23, - schar v24, schar v25, schar v26, schar v27, - schar v28, schar v29, schar v30, schar v31) - { - val = _v256_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, - v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, - v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int8x32() {} - - schar get0() const { - schar des[1] = {0}; - __lasx_xvstelm_b(val, des, 0, 0); - return des[0]; - } -}; - -struct v_uint16x16 -{ - typedef ushort lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_uint16x16(__m256i v) : val(v) {} - v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, - ushort v4, ushort v5, ushort v6, ushort v7, - ushort v8, ushort v9, ushort v10, ushort v11, - ushort v12, ushort v13, ushort v14, ushort v15) - { - val = _v256_setr_h((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, - (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint16x16() {} - - ushort get0() const { - ushort des[1] = {0}; - __lasx_xvstelm_h(val, des, 0, 0); - return des[0]; - } -}; - -struct v_int16x16 -{ - typedef short lane_type; - enum { nlanes = 16 }; - __m256i val; - - explicit v_int16x16(__m256i v) : val(v) {} - v_int16x16(short v0, short v1, short v2, short v3, - short v4, short v5, short v6, short v7, - short v8, short v9, short v10, short v11, - short v12, short v13, short v14, short v15) - { - val = _v256_setr_h(v0, v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int16x16() {} - - short get0() const { - short des[1] = {0}; - __lasx_xvstelm_h(val, des, 0, 0); - return des[0]; - } -}; - -struct v_uint32x8 -{ - typedef unsigned lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_uint32x8(__m256i v) : val(v) {} - v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, - unsigned v4, unsigned v5, unsigned v6, unsigned v7) - { - val = _v256_setr_w((unsigned)v0, (unsigned)v1, (unsigned)v2, - (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_uint32x8() {} - - unsigned get0() const { return __lasx_xvpickve2gr_wu(val, 0); } -}; - -struct v_int32x8 -{ - typedef int lane_type; - enum { nlanes = 8 }; - __m256i val; - - explicit v_int32x8(__m256i v) : val(v) {} - v_int32x8(int v0, int v1, int v2, int v3, - int v4, int v5, int v6, int v7) - { - val = _v256_setr_w(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_int32x8() {} - - int get0() const { return __lasx_xvpickve2gr_w(val, 0); } -}; - -struct v_float32x8 -{ - typedef float lane_type; - enum { nlanes = 8 }; - __m256 val; - - explicit v_float32x8(__m256 v) : val(v) {} - explicit v_float32x8(__m256i v) { val = *((__m256*)&v); } - v_float32x8(float v0, float v1, float v2, float v3, - float v4, float v5, float v6, float v7) - { - val = _v256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); - } - /* coverity[uninit_ctor]: suppress warning */ - v_float32x8() {} - - float get0() const { - float des[1] = {0}; - __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); - return des[0]; - } - - int get0toint() const { - int des[1] = {0}; - __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); - return des[0]; - } -}; - -struct v_uint64x4 -{ - typedef uint64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_uint64x4(__m256i v) : val(v) {} - v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) - { val = _v256_setr_d((int64)v0, (int64)v1, (int64)v2, (int64)v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_uint64x4() {} - - uint64 get0() const - { - return __lasx_xvpickve2gr_du(val, 0); - } -}; - -struct v_int64x4 -{ - typedef int64 lane_type; - enum { nlanes = 4 }; - __m256i val; - - explicit v_int64x4(__m256i v) : val(v) {} - v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) - { val = _v256_setr_d(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_int64x4() {} - - int64 get0() const - { - return __lasx_xvpickve2gr_d(val, 0); - } -}; - -struct v_float64x4 -{ - typedef double lane_type; - enum { nlanes = 4 }; - __m256d val; - - explicit v_float64x4(__m256d v) : val(v) {} - explicit v_float64x4(__m256i v) { val = *((__m256d*)&v); } - v_float64x4(double v0, double v1, double v2, double v3) - { val = _v256_setr_pd(v0, v1, v2, v3); } - /* coverity[uninit_ctor]: suppress warning */ - v_float64x4() {} - - double get0() const { - double des[1] = {0}; - __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); - return des[0]; - } - - int64 get0toint64() const { - int64 des[1] = {0}; - __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); - return des[0]; - } -}; - -//////////////// Load and store operations /////////////// - -#define OPENCV_HAL_IMPL_LASX_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - __m128i v128 = __lsx_vld(ptr, 0); \ - return _Tpvec(*((__m256i*)&v128)); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vlo = __lsx_vld(ptr0, 0); \ - __m128i vhi = __lsx_vld(ptr1, 0); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - __lasx_xvst(a.val, ptr, 0); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - __lasx_xvst(a.val, ptr, 0); \ - else \ - __lasx_xvst(a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } - -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint8x32, uchar) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int8x32, schar) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint16x16, ushort) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int16x16, short) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint32x8, unsigned) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int32x8, int) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint64x4, uint64) -OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int64x4, int64) - - -#define OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ - inline _Tpvec v256_load(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_aligned(const _Tp* ptr) \ - { return _Tpvec(__lasx_xvld(ptr, 0)); } \ - inline _Tpvec v256_load_low(const _Tp* ptr) \ - { \ - __m128i v128 = __lsx_vld(ptr, 0); \ - return _Tpvec(*((__m256i*)&v128)); \ - } \ - inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - halfreg vlo = __lsx_vld(ptr0, 0); \ - halfreg vhi = __lsx_vld(ptr1, 0); \ - return _Tpvec(_v256_combine(vlo, vhi)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lasx_xvst(a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ - { \ - if( mode == hal::STORE_UNALIGNED ) \ - __lasx_xvst(a.val, ptr, 0); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - __lasx_xvst(a.val, ptr, 0); \ - else \ - __lasx_xvst(a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } - -OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float32x8, float, __m128i) -OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float64x4, double, __m128i) - - -inline __m256i _lasx_256_castps_si256(const __m256& v) -{ return __m256i(v); } - -inline __m256i _lasx_256_castpd_si256(const __m256d& v) -{ return __m256i(v); } - -#define OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_LASX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(__lasx_xvreplgr2vr_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float32x8, suffix, _lasx_256_castps_si256) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float64x4, suffix, _lasx_256_castpd_si256) - -OPENCV_HAL_IMPL_LASX_INIT(v_uint8x32, uchar, u8, b, int) -OPENCV_HAL_IMPL_LASX_INIT(v_int8x32, schar, s8, b, int) -OPENCV_HAL_IMPL_LASX_INIT(v_uint16x16, ushort, u16, h, int) -OPENCV_HAL_IMPL_LASX_INIT(v_int16x16, short, s16, h, int) -OPENCV_HAL_IMPL_LASX_INIT(v_uint32x8, unsigned, u32, w, int) -OPENCV_HAL_IMPL_LASX_INIT(v_int32x8, int, s32, w, int) -OPENCV_HAL_IMPL_LASX_INIT(v_uint64x4, uint64, u64, d, long int) -OPENCV_HAL_IMPL_LASX_INIT(v_int64x4, int64, s64, d, long int) - - -inline __m256 _lasx_256_castsi256_ps(const __m256i &v) -{ return __m256(v); } - -inline __m256d _lasx_256_castsi256_pd(const __m256i &v) -{ return __m256d(v); } - -#define OPENCV_HAL_IMPL_LASX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v256_setzero_##suffix() \ - { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ - inline _Tpvec v256_setall_##suffix(_Tp v) \ - { return _Tpvec(_v256_setall_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v256_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v256_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ - OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, cast) - -OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float32x8, float, f32, ps, _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float64x4, double, f64, pd, _lasx_256_castsi256_pd) - -inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) -{ return a; } -inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) -{ return v_float32x8(_lasx_256_castps_si256(__m256(a.val))); } - -inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) -{ return a; } -inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) -{ return v_float64x4(_lasx_256_castpd_si256(__m256d(a.val))); } - - -//////////////// Variant Value reordering /////////////// - -// unpacks -#define OPENCV_HAL_IMPL_LASX_UNPACK(_Tpvec, suffix) \ - inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvilvl_##suffix(__m256i(b.val), __m256i(a.val))); } \ - inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvilvh_##suffix(__m256i(b.val), __m256i(a.val))); } - -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint8x32, b) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int8x32, b) -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint16x16, h) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int16x16, h) -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint32x8, w) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int32x8, w) -OPENCV_HAL_IMPL_LASX_UNPACK(v_uint64x4, d) -OPENCV_HAL_IMPL_LASX_UNPACK(v_int64x4, d) -OPENCV_HAL_IMPL_LASX_UNPACK(v_float32x8, w) -OPENCV_HAL_IMPL_LASX_UNPACK(v_float64x4, d) - - -// shuffle -// todo: emulate 64bit -#define OPENCV_HAL_IMPL_LASX_SHUFFLE(_Tpvec, intrin) \ - template \ - inline _Tpvec v256_shuffle(const _Tpvec& a) \ - { return _Tpvec(__lasx_xvshuf4i_##intrin(a.val, m)); } - -OPENCV_HAL_IMPL_LASX_SHUFFLE(v_uint32x8, w) -OPENCV_HAL_IMPL_LASX_SHUFFLE(v_int32x8, w) - -template -inline v_float32x8 v256_shuffle(const v_float32x8 &a) -{ return v_float32x8(__lasx_xvshuf4i_w(*((__m256i*)&a.val), m)); } - -template -inline v_float64x4 v256_shuffle(const v_float64x4 &a) -{ - const int m1 = m & 0b1; - const int m2 = m & 0b10; - const int m3 = m & 0b100; - const int m4 = m & 0b1000; - const int m5 = m2 << 1; - const int m6 = m3 << 2; - const int m7 = m4 << 3; - const int m8 = m1 & m5 & m6 & m7; - - return v_float64x4(__lasx_xvshuf4i_d(*((__m256i*)&a.val), *((__m256i*)&a.val), m8)); -} - -template -inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) -{ - ab0 = v256_unpacklo(a, b); - ab1 = v256_unpackhi(a, b); -} - -template -inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(__lasx_xvpermi_q(a.val, b.val, 0x12)); } - -inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) -{ return v_float32x8(__lasx_xvpermi_q(a.val, b.val, 0x12)); } - -inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) -{ return v_float64x4(__lasx_xvpermi_q(a.val, b.val, 0x12)); } - -template -inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) -{ return v256_permute2x128<0x03>(a, b); } - -inline __m256i _v256_alignr_b(const __m256i &a, const __m256i &b, const int imm) -{ - if (imm == 8) { - return __lasx_xvshuf4i_d(b, a, 0x9); // b.d1 a.d0 b.d3 a.d2 - } else { - __m256i byteIndex = _v256_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); - return __lasx_xvshuf_b(a, b, __lasx_xvadd_b(__lasx_xvreplgr2vr_b(imm), byteIndex)); - } -} - -template -inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(_v256_alignr_b(a.val, b.val, 8)); } -inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) -{ return v_float64x4(__lasx_xvshuf4i_d(b.val, a.val, 0x9)); } // b.d1 a.d0 b.d3 a.d2 -// todo: emulate float32 - -template -inline _Tpvec v256_swap_halves(const _Tpvec& a) -{ return v256_permute2x128<1>(a, a); } - -template -inline _Tpvec v256_reverse_64(const _Tpvec& a) -{ return v256_permute4x64<0x1b>(a); } - - -// ZIP -#define OPENCV_HAL_IMPL_LASX_ZIP(_Tpvec) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x02>(a, b); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return v256_permute2x128<0x13>(a, b); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - _Tpvec a1b0 = v256_alignr_128(a, b); \ - c = v256_combine_diagonal(a, a1b0); \ - d = v256_combine_diagonal(a1b0, b); \ - } \ - inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& ab0, _Tpvec& ab1) \ - { \ - _Tpvec ab0ab2, ab1ab3; \ - v256_zip(a, b, ab0ab2, ab1ab3); \ - v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ - } - -OPENCV_HAL_IMPL_LASX_ZIP(v_uint8x32) -OPENCV_HAL_IMPL_LASX_ZIP(v_int8x32) -OPENCV_HAL_IMPL_LASX_ZIP(v_uint16x16) -OPENCV_HAL_IMPL_LASX_ZIP(v_int16x16) -OPENCV_HAL_IMPL_LASX_ZIP(v_uint32x8) -OPENCV_HAL_IMPL_LASX_ZIP(v_int32x8) -OPENCV_HAL_IMPL_LASX_ZIP(v_uint64x4) -OPENCV_HAL_IMPL_LASX_ZIP(v_int64x4) -OPENCV_HAL_IMPL_LASX_ZIP(v_float32x8) -OPENCV_HAL_IMPL_LASX_ZIP(v_float64x4) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_LASX_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint8x32, __lasx_xvsadd_bu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint8x32, __lasx_xvssub_bu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int8x32, __lasx_xvsadd_b) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int8x32, __lasx_xvssub_b) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint16x16, __lasx_xvsadd_hu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint16x16, __lasx_xvssub_hu) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int16x16, __lasx_xvsadd_h) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int16x16, __lasx_xvssub_h) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint32x8, __lasx_xvadd_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint32x8, __lasx_xvsub_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_uint32x8, __lasx_xvmul_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int32x8, __lasx_xvadd_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int32x8, __lasx_xvsub_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_int32x8, __lasx_xvmul_w) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint64x4, __lasx_xvadd_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint64x4, __lasx_xvsub_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int64x4, __lasx_xvadd_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int64x4, __lasx_xvsub_d) - -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float32x8, __lasx_xvfadd_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float32x8, __lasx_xvfsub_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float32x8, __lasx_xvfmul_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float32x8, __lasx_xvfdiv_s) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float64x4, __lasx_xvfadd_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float64x4, __lasx_xvfsub_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float64x4, __lasx_xvfmul_d) -OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float64x4, __lasx_xvfdiv_d) - -// saturating multiply 8-bit, 16-bit -inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) -{ - v_uint16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) -{ - v_int16x16 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i pl = __lasx_xvmul_h(a.val, b.val); - __m256i ph = __lasx_xvmuh_hu(a.val, b.val); - __m256i p0 = __lasx_xvilvl_h(ph, pl); - __m256i p1 = __lasx_xvilvh_h(ph, pl); - return v_uint16x16(_v256_packs_epu32(p0, p1)); -} -inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) -{ - __m256i pl = __lasx_xvmul_h(a.val, b.val); - __m256i ph = __lasx_xvmuh_h(a.val, b.val); - __m256i p0 = __lasx_xvilvl_h(ph, pl); - __m256i p1 = __lasx_xvilvh_h(ph, pl); - return v_int16x16(_lasx_packs_w(p0, p1)); -} - -/** Non-saturating arithmetics **/ - -#define OPENCV_HAL_IMPL_LASX_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint8x32, __lasx_xvadd_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int8x32, __lasx_xvadd_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint16x16, __lasx_xvadd_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int16x16, __lasx_xvadd_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint8x32, __lasx_xvsub_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int8x32, __lasx_xvsub_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint16x16, __lasx_xvsub_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int16x16, __lasx_xvsub_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_uint16x16, __lasx_xvmul_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_int16x16, __lasx_xvmul_h) - -inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i p0 = __lasx_xvmulwev_h_bu(a.val, b.val); - __m256i p1 = __lasx_xvmulwod_h_bu(a.val, b.val); - return v_uint8x32(__lasx_xvpackev_b(p1, p0)); -} - -inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -// Multiply and expand -inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, - v_uint16x16& c, v_uint16x16& d) -{ - v_uint16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, - v_int16x16& c, v_int16x16& d) -{ - v_int16x16 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, - v_int32x8& c, v_int32x8& d) -{ - v_int16x16 vhi = v_int16x16(__lasx_xvmuh_h(a.val, b.val)); - - v_int16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_s32(v0); - d = v_reinterpret_as_s32(v1); -} - -inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, - v_uint32x8& c, v_uint32x8& d) -{ - v_uint16x16 vhi = v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); - - v_uint16x16 v0, v1; - v_zip(v_mul_wrap(a, b), vhi, v0, v1); - - c = v_reinterpret_as_u32(v0); - d = v_reinterpret_as_u32(v1); -} - -inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, - v_uint64x4& c, v_uint64x4& d) -{ - __m256i v0 = __lasx_xvmulwev_d_wu(a.val, b.val); - __m256i v1 = __lasx_xvmulwod_d_wu(a.val, b.val); - v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); -} - -inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(__lasx_xvmuh_h(a.val, b.val)); } -inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); } - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_LASX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } - -OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint16x16, v_int16x16, h, __lasx_xvsra_h) -OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint32x8, v_int32x8, w, __lasx_xvsra_w) -OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint64x4, v_int64x4, d, __lasx_xvsra_d) - - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_LASX_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_LASX_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix) \ - OPENCV_HAL_IMPL_LASX_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix) \ - OPENCV_HAL_IMPL_LASX_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lasx_xvnori_b(a.val, 0)); } - -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint8x32, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int8x32, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint16x16, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int16x16, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint32x8, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int32x8, v, __lasx_xvreplgr2vr_w(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint64x4, v, __lasx_xvreplgr2vr_d(-1)) -OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int64x4, v, __lasx_xvreplgr2vr_d(-1)) - -#define OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(*((__m256i*)(&a.val)), *((__m256i*)(&b.val)))); } - -#define OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(_Tpvec, suffix, not_const, cast) \ - OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix, cast) \ - OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix, cast) \ - OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix, cast) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lasx_xvxor_##suffix(*((__m256i*)(&a.val)), not_const)); } - -OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float32x8, v, __lasx_xvreplgr2vr_w(-1), _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float64x4, v, __lasx_xvreplgr2vr_d(-1), _lasx_256_castsi256_pd) - -/** Select **/ -#define OPENCV_HAL_IMPL_LASX_SELECT(_Tpvec) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvbitsel_v(b.val, a.val, mask.val)); } - -OPENCV_HAL_IMPL_LASX_SELECT(v_uint8x32) -OPENCV_HAL_IMPL_LASX_SELECT(v_int8x32) -OPENCV_HAL_IMPL_LASX_SELECT(v_uint16x16) -OPENCV_HAL_IMPL_LASX_SELECT(v_int16x16) -OPENCV_HAL_IMPL_LASX_SELECT(v_uint32x8) -OPENCV_HAL_IMPL_LASX_SELECT(v_int32x8) - -inline v_float32x8 v_select(const v_float32x8 &mask, const v_float32x8 &a, const v_float32x8 &b) -{ return v_float32x8(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } - -inline v_float64x4 v_select(const v_float64x4 &mask, const v_float64x4 &a, const v_float64x4 &b) -{ return v_float64x4(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } - -/** Comparison **/ -#define OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpvec) \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } \ - inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ - { return v_gt(b, a); } \ - inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_lt(a, b)); } \ - inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ - { return v_ge(b, a); } - -#define OPENCV_HAL_IMPL_LASX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ - inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ - inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ - { \ - return _Tpuvec(__lasx_xvslt_##usuffix(b.val, a.val)); \ - } \ - inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ - inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lasx_xvslt_##suffix(b.val, a.val)); } \ - OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpuvec) \ - OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpsvec) - -OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint8x32, v_int8x32, b, bu) -OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint16x16, v_int16x16, h, hu) -OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint32x8, v_int32x8, w, wu) - -#define OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(_Tpvec, suffix) \ - inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } - -OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_uint64x4, d) -OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_int64x4, d) - -#define OPENCV_HAL_IMPL_LASX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lasx_##suffix##_##ssuffix(a.val, b.val)); } - -#define OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(_Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_eq, xvfcmp_ceq, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_ne, xvfcmp_cne, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_lt, xvfcmp_clt, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LASX_CMP_FLT(v_le, xvfcmp_cle, _Tpvec, ssuffix) - -OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float32x8, s) -OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float64x4, d) - -inline v_float32x8 v_gt(const v_float32x8 &a, const v_float32x8 &b) -{ return v_float32x8(__lasx_xvfcmp_clt_s(b.val, a.val)); } - -inline v_float32x8 v_ge(const v_float32x8 &a, const v_float32x8 &b) -{ return v_float32x8(__lasx_xvfcmp_cle_s(b.val, a.val)); } - -inline v_float64x4 v_gt(const v_float64x4 &a, const v_float64x4 &b) -{ return v_float64x4(__lasx_xvfcmp_clt_d(b.val, a.val)); } - -inline v_float64x4 v_ge(const v_float64x4 &a, const v_float64x4 &b) -{ return v_float64x4(__lasx_xvfcmp_cle_d(b.val, a.val)); } - -inline v_float32x8 v_not_nan(const v_float32x8& a) -{ return v_float32x8(__lasx_xvfcmp_cor_s(a.val, a.val)); } -inline v_float64x4 v_not_nan(const v_float64x4& a) -{ return v_float64x4(__lasx_xvfcmp_cor_d(a.val, a.val)); } - -/** min/max **/ -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint8x32, __lasx_xvmin_bu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint8x32, __lasx_xvmax_bu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int8x32, __lasx_xvmin_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int8x32, __lasx_xvmax_b) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint16x16, __lasx_xvmin_hu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint16x16, __lasx_xvmax_hu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int16x16, __lasx_xvmin_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int16x16, __lasx_xvmax_h) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint32x8, __lasx_xvmin_wu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint32x8, __lasx_xvmax_wu) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int32x8, __lasx_xvmin_w) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int32x8, __lasx_xvmax_w) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float32x8, __lasx_xvfmin_s) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float32x8, __lasx_xvfmax_s) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float64x4, __lasx_xvfmin_d) -OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float64x4, __lasx_xvfmax_d) - -/** Rotate **/ -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_R = (16 - imm) & 0xFF}; - enum {IMM_R2 = (32 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _v256_permute2x128<0x21>(a.val, b.val); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swap, IMM_R)); - return v_uint8x32(_v256_alignr_b(swap, b.val, IMM_R2)); // imm < 32 -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) -{ - enum {IMM_L = (imm - 16) & 0xFF}; - - if (imm == 0) return a; - if (imm == 32) return b; - if (imm > 32) return v_uint8x32(); - - __m256i swap = _v256_permute2x128<0x03>(a.val, b.val); - if (imm == 16) return v_uint8x32(swap); - if (imm < 16) return v_uint8x32(_v256_alignr_b(swap, a.val, imm)); - return v_uint8x32(_v256_alignr_b(b.val, swap, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_left(const v_uint8x32& a) -{ - enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; - enum {IMM_R = (16 - imm) & 0xFF}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i swapz = __lasx_xvpermi_q(a.val, vzero, 0x20);; - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swapz, IMM_R)); - return v_uint8x32(__lasx_xvbsll_v(swapz, IMM_L)); -} - -template -inline v_uint8x32 v_rotate_right(const v_uint8x32& a) -{ - enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; - - if (imm == 0) return a; - if (imm > 32) return v_uint8x32(); - - // ESAC control[3] ? [127:0] = 0 - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i swapz = __lasx_xvpermi_q(vzero, a.val, 0x21);; - if (imm == 16) return v_uint8x32(swapz); - if (imm < 16) return v_uint8x32(_v256_alignr_b(swapz, a.val, imm)); - return v_uint8x32(__lasx_xvbsrl_v(swapz, IMM_L)); -} - -#define OPENCV_HAL_IMPL_LASX_ROTATE_CAST(intrin, _Tpvec, cast) \ - template \ - inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ - v_reinterpret_as_u8(b)); \ - return _Tpvec(cast(ret.val)); \ - } \ - template \ - inline _Tpvec intrin(const _Tpvec& a) \ - { \ - enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ - v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ - return _Tpvec(cast(ret.val)); \ - } - -#define OPENCV_HAL_IMPL_LASX_ROTATE(_Tpvec) \ - OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) - -OPENCV_HAL_IMPL_LASX_ROTATE(v_int8x32) -OPENCV_HAL_IMPL_LASX_ROTATE(v_uint16x16) -OPENCV_HAL_IMPL_LASX_ROTATE(v_int16x16) -OPENCV_HAL_IMPL_LASX_ROTATE(v_uint32x8) -OPENCV_HAL_IMPL_LASX_ROTATE(v_int32x8) -OPENCV_HAL_IMPL_LASX_ROTATE(v_uint64x4) -OPENCV_HAL_IMPL_LASX_ROTATE(v_int64x4) - -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float32x8, _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float32x8, _lasx_256_castsi256_ps) -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float64x4, _lasx_256_castsi256_pd) -OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float64x4, _lasx_256_castsi256_pd) - -/** Reverse **/ -inline v_uint8x32 v_reverse(const v_uint8x32 &a) -{ - static const __m256i perm = _v256_setr_b( - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, - 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - __m256i vec = __lasx_xvshuf_b(a.val, a.val, perm); - return v_uint8x32(__lasx_xvpermi_q(vec, vec, 1)); -} - -inline v_int8x32 v_reverse(const v_int8x32 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x16 v_reverse(const v_uint16x16 &a) -{ - __m256i vec = __lasx_xvshuf4i_h(a.val, 0x1B); - vec = __lasx_xvshuf4i_w(vec, 0x4E); - return v_uint16x16(__lasx_xvpermi_d(vec, 0x4E)); -} - -inline v_int16x16 v_reverse(const v_int16x16 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x8 v_reverse(const v_uint32x8 &a) -{ - __m256i vec = __lasx_xvshuf4i_w(a.val, 0x1B); - return v_uint32x8(__lasx_xvpermi_d(vec, 0x4E)); -} - -inline v_int32x8 v_reverse(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x8 v_reverse(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x4 v_reverse(const v_uint64x4 &a) -{ - return v_uint64x4(__lasx_xvpermi_d(a.val, 0x1b)); -} - -inline v_int64x4 v_reverse(const v_int64x4 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x4 v_reverse(const v_float64x4 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////// Reduce and mask ///////// - -/** Reduce **/ -// this function is return a[0]+a[1]+...+a[31] -inline unsigned v_reduce_sum(const v_uint8x32& a) -{ - __m256i t1 = __lasx_xvhaddw_hu_bu(a.val, a.val); - __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); - __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); - __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); - return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); -} - -inline int v_reduce_sum(const v_int8x32& a) -{ - __m256i t1 = __lasx_xvhaddw_h_b(a.val, a.val); - __m256i t2 = __lasx_xvhaddw_w_h(t1, t1); - __m256i t3 = __lasx_xvhaddw_d_w(t2, t2); - __m256i t4 = __lasx_xvhaddw_q_d(t3, t3); - return (int)(((v8i32)t4)[0]+((v8i32)t4)[4]); -} - -#define OPENCV_HAL_IMPL_LASX_REDUCE_32(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ - val = intrin(val, __lsx_vbsrl_v(val,8)); \ - val = intrin(val, __lsx_vbsrl_v(val,4)); \ - val = intrin(val, __lsx_vbsrl_v(val,2)); \ - val = intrin(val, __lsx_vbsrl_v(val,1)); \ - return (sctype)__lsx_vpickve2gr_w(val, 0); \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, min, __lsx_vmin_bu) -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, min, __lsx_vmin_b) -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, max, __lsx_vmax_bu) -OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, max, __lsx_vmax_b) - -#define OPENCV_HAL_IMPL_LASX_REDUCE_16(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 2)); \ - return (sctype) __lsx_vpickve2gr_w(v0, 0); \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, min, __lsx_vmin_hu) -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, min, __lsx_vmin_h) -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, max, __lsx_vmax_hu) -OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, max, __lsx_vmax_h) - -#define OPENCV_HAL_IMPL_LASX_REDUCE_8(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i v0 = _v256_extract_low(a.val); \ - __m128i v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ - v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ - return (sctype) __lsx_vpickve2gr_w(v0, 0); \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, min, __lsx_vmin_wu) -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, min, __lsx_vmin_w) -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, max, __lsx_vmax_wu) -OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, max, __lsx_vmax_w) - -#define OPENCV_HAL_IMPL_LASX_REDUCE_FLT(func, intrin) \ - inline float v_reduce_##func(const v_float32x8& a) \ - { \ - __m128 v0 = _v256_extract_low(a.val); \ - __m128 v1 = _v256_extract_high(a.val); \ - v0 = intrin(v0, v1); \ - v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x0e))); \ - v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x01))); \ - float *fvalue = (float*)&v0; \ - return fvalue[0]; \ - } - -OPENCV_HAL_IMPL_LASX_REDUCE_FLT(min, __lsx_vfmin_s) -OPENCV_HAL_IMPL_LASX_REDUCE_FLT(max, __lsx_vfmax_s) - -inline int v_reduce_sum(const v_int32x8& a) -{ - __m256i t1 = __lasx_xvhaddw_d_w(a.val, a.val); - __m256i t2 = __lasx_xvhaddw_q_d(t1, t1); - return (int)(((v8i32)t2)[0]+((v8i32)t2)[4]); -} - -inline unsigned v_reduce_sum(const v_uint32x8& a) -{ return v_reduce_sum(v_reinterpret_as_s32(a)); } - -inline int v_reduce_sum(const v_int16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline unsigned v_reduce_sum(const v_uint16x16& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -inline float v_reduce_sum(const v_float32x8& a) -{ - float result = 0; - float *pa = (float*)&a; - for (int i = 0; i < 2; ++i) { - result += pa[i*4] + pa[i*4+1] + pa[i*4+2] + pa[i*4+3]; - } - return result; -} - -inline uint64 v_reduce_sum(const v_uint64x4& a) -{ - __m256i t0 = __lasx_xvhaddw_qu_du(a.val, a.val); - return (uint64)(((v4u64)t0)[0] + ((v4u64)t0)[2]); -} -inline int64 v_reduce_sum(const v_int64x4& a) -{ - __m256i t0 = __lasx_xvhaddw_q_d(a.val, a.val); - return (int64)(((v4i64)t0)[0] + ((v4i64)t0)[2]); -} -inline double v_reduce_sum(const v_float64x4& a) -{ - double *pa = (double*)&a; - return pa[0] + pa[1] + pa[2] + pa[3]; -} - -inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, - const v_float32x8& c, const v_float32x8& d) -{ - float *pa = (float*)&a; - float *pb = (float*)&b; - float *pc = (float*)&c; - float *pd = (float*)&d; - - float v0 = pa[0] + pa[1] + pa[2] + pa[3]; - float v1 = pb[0] + pb[1] + pb[2] + pb[3]; - float v2 = pc[0] + pc[1] + pc[2] + pc[3]; - float v3 = pd[0] + pd[1] + pd[2] + pd[3]; - float v4 = pa[4] + pa[5] + pa[6] + pa[7]; - float v5 = pb[4] + pb[5] + pb[6] + pb[7]; - float v6 = pc[4] + pc[5] + pc[6] + pc[7]; - float v7 = pd[4] + pd[5] + pd[6] + pd[7]; - return v_float32x8(v0, v1, v2, v3, v4, v5, v6, v7); -} - -inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i t0 = __lasx_xvabsd_bu(a.val, b.val); - __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); - __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); - __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); - __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); - return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); -} -inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) -{ - __m256i t0 = __lasx_xvabsd_b(a.val, b.val); - __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); - __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); - __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); - __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); - return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); -} -inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) -{ - v_uint32x8 l, h; - v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) -{ - return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); -} -inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) -{ - v_int32x8 m = v_lt(a, b); - return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); -} -inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) -{ - v_float32x8 a_b = v_sub(a, b); - return v_reduce_sum(v_float32x8(*((__m256i*)&a_b.val) & __lasx_xvreplgr2vr_w(0x7fffffff))); -} - -/** Popcount **/ -inline v_uint8x32 v_popcount(const v_uint8x32& a) -{ return v_uint8x32(__lasx_xvpcnt_b(a.val)); } -inline v_uint16x16 v_popcount(const v_uint16x16& a) -{ return v_uint16x16(__lasx_xvpcnt_h(a.val)); } -inline v_uint32x8 v_popcount(const v_uint32x8& a) -{ return v_uint32x8(__lasx_xvpcnt_w(a.val)); } -inline v_uint64x4 v_popcount(const v_uint64x4& a) -{ return v_uint64x4(__lasx_xvpcnt_d(a.val)); } -inline v_uint8x32 v_popcount(const v_int8x32& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x16 v_popcount(const v_int16x16& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x8 v_popcount(const v_int32x8& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x4 v_popcount(const v_int64x4& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -inline int v_signmask(const v_int8x32& a) -{ - __m256i result = __lasx_xvmskltz_b(a.val); - int mask = __lasx_xvpickve2gr_w(result, 0); - mask |= (__lasx_xvpickve2gr_w(result, 4) << 16); - return mask; -} -inline int v_signmask(const v_uint8x32& a) -{ return v_signmask(v_reinterpret_as_s8(a)); } - -inline int v_signmask(const v_int16x16& a) -{ return v_signmask(v_pack(a, a)) & 0xFFFF; } -inline int v_signmask(const v_uint16x16& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_int32x8& a) -{ - __m256i result = __lasx_xvmskltz_w(a.val); - int mask = __lasx_xvpickve2gr_w(result, 0); - mask |= (__lasx_xvpickve2gr_w(result, 4) << 4); - return mask; -} -inline int v_signmask(const v_uint32x8& a) -{ return v_signmask(*(v_int32x8*)(&a)); } - -inline int v_signmask(const v_int64x4& a) -{ - __m256i result = __lasx_xvmskltz_d(a.val); - int mask = __lasx_xvpickve2gr_d(result, 0); - mask |= (__lasx_xvpickve2gr_w(result, 4) << 2); - return mask; -} -inline int v_signmask(const v_uint64x4& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } - -inline int v_signmask(const v_float32x8& a) -{ return v_signmask(*(v_int32x8*)(&a)); } - -inline int v_signmask(const v_float64x4& a) -{ return v_signmask(*(v_int64x4*)(&a)); } - -inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -/** Checks **/ -#define OPENCV_HAL_IMPL_LASX_CHECK(_Tpvec, allmask) \ - inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ - inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } -OPENCV_HAL_IMPL_LASX_CHECK(v_uint8x32, -1) -OPENCV_HAL_IMPL_LASX_CHECK(v_int8x32, -1) -OPENCV_HAL_IMPL_LASX_CHECK(v_uint32x8, 255) -OPENCV_HAL_IMPL_LASX_CHECK(v_int32x8, 255) -OPENCV_HAL_IMPL_LASX_CHECK(v_uint64x4, 15) -OPENCV_HAL_IMPL_LASX_CHECK(v_int64x4, 15) -OPENCV_HAL_IMPL_LASX_CHECK(v_float32x8, 255) -OPENCV_HAL_IMPL_LASX_CHECK(v_float64x4, 15) - -#define OPENCV_HAL_IMPL_LASX_CHECK_SHORT(_Tpvec) \ - inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ - inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } -OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_uint16x16) -OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_int16x16) - -////////// Other math ///////// - -/** Some frequent operations **/ -#define OPENCV_HAL_IMPL_LASX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(__lasx_xvfsqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_LASX_MULADD(v_float32x8, s) -OPENCV_HAL_IMPL_LASX_MULADD(v_float64x4, d) - -inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_int32x8(__lasx_xvmadd_w(c.val, a.val, b.val)); -} - -inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x8 v_invsqrt(const v_float32x8& x) -{ return v_float32x8(__lasx_xvfrsqrt_s(x.val)); } - -inline v_float64x4 v_invsqrt(const v_float64x4& x) -{ return v_float64x4(__lasx_xvfrsqrt_d(x.val)); } - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_LASX_ABS(_Tpvec, suffix) \ - inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ - { return v_u##_Tpvec(__lasx_xvabsd_##suffix(x.val, __lasx_xvreplgr2vr_w(0))); } - -OPENCV_HAL_IMPL_LASX_ABS(int8x32, b) -OPENCV_HAL_IMPL_LASX_ABS(int16x16, h) -OPENCV_HAL_IMPL_LASX_ABS(int32x8, w) - -inline v_float32x8 v_abs(const v_float32x8& x) -{ return v_float32x8(*((__m256i*)&x) & __lasx_xvreplgr2vr_w(0x7fffffff)); } -inline v_float64x4 v_abs(const v_float64x4& x) -{ return v_float64x4(*((__m256i*)&x) & __lasx_xvreplgr2vr_d(0x7fffffffffffffff)); } - -/** Absolute difference **/ -inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) -{ return (v_uint8x32)__lasx_xvabsd_bu(a.val, b.val); } -inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) -{ return (v_uint16x16)__lasx_xvabsd_hu(a.val, b.val); } -inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) -{ return (v_uint32x8)__lasx_xvabsd_wu(a.val, b.val); } - -inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) -{ return (v_uint8x32)__lasx_xvabsd_b(a.val, b.val); } -inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) -{ return (v_uint16x16)__lasx_xvabsd_h(a.val, b.val); } -inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) -{ return (v_uint32x8)__lasx_xvabsd_w(a.val, b.val); } - -inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) -{ - v_int8x32 d = v_sub(a, b); - v_int8x32 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x8 v_round(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftint_w_s(a.val)); } - -inline v_int32x8 v_round(const v_float64x4& a) -{ __m256i t = __lasx_xvftint_w_d(a.val, a.val); - return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } - -inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) -{ - __m256i abi = __lasx_xvftint_w_d(b.val, a.val); - return v_int32x8(__lasx_xvpermi_d(abi, 0b11011000)); //3120 -} - -inline v_int32x8 v_trunc(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftintrz_w_s(a.val)); } - -inline v_int32x8 v_trunc(const v_float64x4& a) -{ __m256i t = __lasx_xvftintrz_w_d(a.val, a.val); - return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } - -inline v_int32x8 v_floor(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrm_s(a.val)))); } - -inline v_int32x8 v_floor(const v_float64x4& a) -{ return v_trunc(v_float64x4(__lasx_xvfrintrm_d(a.val))); } - -inline v_int32x8 v_ceil(const v_float32x8& a) -{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrp_s(a.val)))); } - -inline v_int32x8 v_ceil(const v_float64x4& a) -{ return v_trunc(v_float64x4(__lasx_xvfrintrp_d(a.val))); } - -/** To float **/ -inline v_float32x8 v_cvt_f32(const v_int32x8& a) -{ return v_float32x8(__lasx_xvffint_s_w(a.val)); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a) -{ return v_float32x8(__lasx_xvpermi_d(__lasx_xvfcvt_s_d(a.val, a.val), 0x88)); } - -inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) -{ - __m256 abf = __lasx_xvfcvt_s_d(a.val, b.val); //warnning: order of a,b is diff from instruction xvfcvt.s.d - return v_float32x8(__lasx_xvpermi_d(abf, 0x8D)); -} - -inline v_float64x4 v_cvt_f64(const v_int32x8& a) -{ - __m256i alow = __lasx_xvpermi_d(a.val, 0x10); - return v_float64x4(__lasx_xvffintl_d_w(alow)); -} - -inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) -{ - __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); - return v_float64x4(__lasx_xvffintl_d_w(ahigh)); -} - -inline v_float64x4 v_cvt_f64(const v_float32x8& a) -{ - __m256i alow = __lasx_xvpermi_d(a.val, 0x10); - return v_float64x4(__lasx_xvfcvtl_d_s((__m256)alow)); -} - -inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) -{ - __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); - return v_float64x4(__lasx_xvfcvtl_d_s((__m256)ahigh)); -} - -inline v_float64x4 v_cvt_f64(const v_int64x4& v) -{ return v_float64x4(__lasx_xvffint_d_l(v.val)); } - -////////////// Lookup table access //////////////////// - -inline v_int8x32 v256_lut(const schar* tab, const int* idx) -{ - return v_int8x32(_v256_setr_b(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], - tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], - tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], tab[idx[16]], tab[idx[17]], - tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], - tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], - tab[idx[30]], tab[idx[31]])); -} -inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x32(_v256_setr_h(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), - *(const short*)(tab + idx[ 3]), *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), - *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), *(const short*)(tab + idx[ 8]), - *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), - *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), - *(const short*)(tab + idx[15]))); -} -inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x32(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), - *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), - *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]))); -} -inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } - -inline v_int16x16 v256_lut(const short* tab, const int* idx) -{ - return v_int16x16(_v256_setr_h(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], - tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], - tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], - tab[idx[15]])); -} -inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x16(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), - *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), - *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); -} -inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) -{ - return v_int16x16(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), - *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); - -} -inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } -inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } - -inline v_int32x8 v256_lut(const int* tab, const int* idx) -{ - return v_int32x8(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), - *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), - *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); -} -inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x8(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), - *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); -} -inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) -{ - return v_int32x8(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); -} -inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } -inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } - -inline v_int64x4 v256_lut(const int64* tab, const int* idx) -{ - return v_int64x4(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), - *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); -} -inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) -{ - return v_int64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); -} -inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } -inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } - -inline v_float32x8 v256_lut(const float* tab, const int* idx) -{ - return v_float32x8(_v256_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); -} -inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } -inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } - -inline v_float64x4 v256_lut(const double* tab, const int* idx) -{ - return v_float64x4(_v256_setr_pd(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) -{ return v_float64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); } - -inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) -{ - int *idx = (int*)&idxvec.val; - return v256_lut(tab, idx); -} - -inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v256_lut(tab, idx); -} - -inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v256_lut(tab, idx); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) -{ - const int *idx = (const int*)&idxvec.val; - __m128i xy01, xy45, xy23, xy67; - xy01 = __lsx_vld(tab + idx[0], 0); - xy01 = __lsx_vextrins_d(xy01, __lsx_vld(tab + idx[1], 0), 0x10); - xy45 = __lsx_vld(tab + idx[4], 0); - xy45 = __lsx_vextrins_d(xy45, __lsx_vld(tab + idx[5], 0), 0x10); - __m256i xy0145 = _v256_combine(xy01, xy45); - xy23 = __lsx_vld(tab + idx[2], 0); - xy23 = __lsx_vextrins_d(xy23, __lsx_vld(tab + idx[3], 0), 0x10); - xy67 = __lsx_vld(tab + idx[6], 0); - xy67 = __lsx_vextrins_d(xy67, __lsx_vld(tab + idx[7], 0), 0x10); - __m256i xy2367 = _v256_combine(xy23, xy67); - - __m256i xxyy0145 = __lasx_xvilvl_w(xy2367, xy0145); - __m256i xxyy2367 = __lasx_xvilvh_w(xy2367, xy0145); - - x = v_float32x8(__lasx_xvilvl_w(xxyy2367, xxyy0145)); - y = v_float32x8(__lasx_xvilvh_w(xxyy2367, xxyy0145)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) -{ - //int CV_DECL_ALIGNED(32) idx[4]; - const int *idx = (const int*)&idxvec.val; - __m128i xy0 = __lsx_vld(tab + idx[0], 0); - __m128i xy2 = __lsx_vld(tab + idx[2], 0); - __m128i xy1 = __lsx_vld(tab + idx[1], 0); - __m128i xy3 = __lsx_vld(tab + idx[3], 0); - __m256i xy02 = _v256_combine(xy0, xy2); - __m256i xy13 = _v256_combine(xy1, xy3); - - x = v_float64x4(__lasx_xvilvl_d(xy13, xy02)); - y = v_float64x4(__lasx_xvilvh_d(xy13, xy02)); -} - -inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) -{ - return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); -} -inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x32 v_interleave_quads(const v_int8x32& vec) -{ - return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); -} -inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) -{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) -{ - return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); -} -inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) -{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x16 v_interleave_quads(const v_int16x16& vec) -{ - return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, - _v256_set_d(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); -} -inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) -{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) -{ - return v_int32x8(__lasx_xvshuf4i_w(vec.val, 0xd8)); -} -inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) -{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) -{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x32 v_pack_triplets(const v_int8x32& vec) -{ - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, - _v256_set_d(0x1211100f0e0d0c0a, 0x0908060504020100, 0x1211100f0e0d0c0a, 0x0908060504020100)); - return v_int8x32(__lasx_xvperm_w(t1, - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) -{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x16 v_pack_triplets(const v_int16x16& vec) -{ - __m256i vzero = __lasx_xvreplgr2vr_w(0); - __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, - _v256_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100, 0x11100f0e0d0c0b0a, 0x0908050403020100)); - return v_int16x16(__lasx_xvperm_w(t1, - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) -{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x8 v_pack_triplets(const v_int32x8& vec) -{ - return v_int32x8(__lasx_xvperm_w(vec.val, - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} -inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) -{ return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } -inline v_float32x8 v_pack_triplets(const v_float32x8& vec) -{ - return v_float32x8(__lasx_xvperm_w(*(__m256i*)(&vec.val), - _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); -} - -////////// Matrix operations ///////// - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) -{ return v_int32x8(__lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val))); } - -inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) -{ - __m256i even = __lasx_xvmulwev_d_w(a.val, b.val); - return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); -} -inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ - __m256i even = __lasx_xvmaddwev_d_w(c.val, a.val, b.val); - return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); -} - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) -{ - __m256i even = __lasx_xvmulwev_h_bu(a.val, b.val); - __m256i odd = __lasx_xvmulwod_h_bu(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_wu_hu(even, even); - __m256i prod1 = __lasx_xvhaddw_wu_hu(odd, odd); - return v_uint32x8(__lasx_xvadd_w(prod0, prod1)); -} -inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) -{ - __m256i even = __lasx_xvmulwev_h_b(a.val, b.val); - __m256i odd = __lasx_xvmulwod_h_b(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_w_h(even, even); - __m256i prod1 = __lasx_xvhaddw_w_h(odd, odd); - return v_int32x8(__lasx_xvadd_w(prod0, prod1)); -} -inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); - __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); - __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); - return v_uint64x4(__lasx_xvadd_d(prod0, prod1)); -} -inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) -{ - __m256i even = __lasx_xvmulwev_w_h(a.val, b.val); - __m256i odd = __lasx_xvmulwod_w_h(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_d_w(even, even); - __m256i prod1 = __lasx_xvhaddw_d_w(odd, odd); - return v_int64x4(__lasx_xvadd_d(prod0, prod1)); -} - -inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) -{ return v_dotprod(a, b); } -inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod(a, b); } -inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); - __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); - __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); - __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); - return v_uint64x4(__lasx_xvadd_d(__lasx_xvilvl_d(prod1, prod0), __lasx_xvilvh_d(prod1, prod0))); -} -inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) -{ - __m256i prod = __lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val)); - __m256i sign = __lasx_xvsrai_w(prod, 31); - __m256i lo = __lasx_xvilvl_w(sign, prod); - __m256i hi = __lasx_xvilvh_w(sign, prod); - return v_int64x4(__lasx_xvadd_d(lo, hi)); -} -inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) -{ return v_dotprod_expand(a, b, c); } - - -#define OPENCV_HAL_LASX_SPLAT2_PS(a, im) \ - v_float32x8(__lasx_xvpermi_w(a.val, a.val, im)) - -inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& m3) -{ - v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); - v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); - v_float32x8 v37 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xFF); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); -} - -inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, - const v_float32x8& m1, const v_float32x8& m2, - const v_float32x8& a) -{ - v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); - v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); - v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); - return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); -} - - -#define OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(_Tpvec, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m256i t0 = cast_from(__lasx_xvilvl_w(a1.val, a0.val)); \ - __m256i t1 = cast_from(__lasx_xvilvl_w(a3.val, a2.val)); \ - __m256i t2 = cast_from(__lasx_xvilvh_w(a1.val, a0.val)); \ - __m256i t3 = cast_from(__lasx_xvilvh_w(a3.val, a2.val)); \ - b0.val = cast_to(__lasx_xvilvl_d(t1, t0)); \ - b1.val = cast_to(__lasx_xvilvh_d(t1, t0)); \ - b2.val = cast_to(__lasx_xvilvl_d(t3, t2)); \ - b3.val = cast_to(__lasx_xvilvh_d(t3, t2)); \ - } - -OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_uint32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_int32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) - -inline void v_transpose4x4(const v_float32x8 &a0, const v_float32x8 &a1, - const v_float32x8 &a2, const v_float32x8 &a3, - v_float32x8 &b0, v_float32x8 &b1, v_float32x8 &b2, v_float32x8 &b3) -{ - __m256i t0 = __lasx_xvilvl_w(__m256i(a1.val), __m256i(a0.val)); - __m256i t1 = __lasx_xvilvl_w(__m256i(a3.val), __m256i(a2.val)); - __m256i t2 = __lasx_xvilvh_w(__m256i(a1.val), __m256i(a0.val)); - __m256i t3 = __lasx_xvilvh_w(__m256i(a3.val), __m256i(a2.val)); - b0.val = __m256(__lasx_xvilvl_d(t1, t0)); - b1.val = __m256(__lasx_xvilvh_d(t1, t0)); - b2.val = __m256(__lasx_xvilvl_d(t3, t2)); - b3.val = __m256(__lasx_xvilvh_d(t3, t2)); -} - -//////////////// Value reordering /////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_LASX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(a.val); \ - b1.val = intrin(__lasx_xvpermi_q(a.val, a.val, 0x11)); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(a.val)); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin(__lasx_xvpermi_q(a.val, a.val, 0x11))); } \ - inline _Tpwvec v256_load_expand(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - return _Tpwvec(intrin(*((__m256i*)&a))); \ - } - -OPENCV_HAL_IMPL_LASX_EXPAND(v_uint8x32, v_uint16x16, uchar, __lasx_vext2xv_hu_bu) -OPENCV_HAL_IMPL_LASX_EXPAND(v_int8x32, v_int16x16, schar, __lasx_vext2xv_h_b) -OPENCV_HAL_IMPL_LASX_EXPAND(v_uint16x16, v_uint32x8, ushort, __lasx_vext2xv_wu_hu) -OPENCV_HAL_IMPL_LASX_EXPAND(v_int16x16, v_int32x8, short, __lasx_vext2xv_w_h) -OPENCV_HAL_IMPL_LASX_EXPAND(v_uint32x8, v_uint64x4, unsigned, __lasx_vext2xv_du_wu) -OPENCV_HAL_IMPL_LASX_EXPAND(v_int32x8, v_int64x4, int, __lasx_vext2xv_d_w) - -#define OPENCV_HAL_IMPL_LASX_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - return _Tpvec(intrin(*((__m256i*)&a))); \ - } - -OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_uint32x8, uchar, __lasx_vext2xv_wu_bu) -OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_int32x8, schar, __lasx_vext2xv_w_b) - -/* pack */ -// 16 -inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) -{ return v_int8x32(_v256_shuffle_odd_64(_lasx_packs_h(a.val, b.val))); } - -inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) -{ return v_uint8x32(_v256_shuffle_odd_64(__lasx_xvssrlrni_bu_h(b.val, a.val, 0))); } - -inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - return v_uint8x32(_v256_shuffle_odd_64(_lasx_packus_h(a.val, b.val))); -} - -inline void v_pack_store(schar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar *ptr, const v_uint16x16& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i res = __lasx_xvssrlrni_bu_h(b.val, a.val, n); - return v_uint8x32(_v256_shuffle_odd_64(res)); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) -{ - __m256i res = __lasx_xvssrlrni_bu_h(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) -{ - __m256i res = __lasx_xvssrarni_bu_h(b.val, a.val, n); - return v_uint8x32(_v256_shuffle_odd_64(res)); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) -{ - __m256i res = __lasx_xvssrarni_bu_h(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) -{ - __m256i res = __lasx_xvssrarni_b_h(b.val, a.val, n); - return v_int8x32(_v256_shuffle_odd_64(res)); -} - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x16& a) -{ - __m256i res = __lasx_xvssrarni_b_h(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -// 32 -inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) -{ return v_int16x16(_v256_shuffle_odd_64(_lasx_packs_w(a.val, b.val))); } - -inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } - -inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(_lasx_packus_w(a.val, b.val))); } - -inline void v_pack_store(short* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x8& a) -{ - __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, 0); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrlrni_hu_w(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) -{ - __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) -{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_hu_w(b.val, a.val, n))); } - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) -{ - __m256i res = __lasx_xvssrarni_hu_w(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) -{ return v_int16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_h_w(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x8& a) -{ - __m256i res = __lasx_xvssrarni_h_w(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -// 64 -// Non-saturating pack -inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) -{ - __m256i ab = __lasx_xvpickev_w(b.val, a.val); - return v_uint32x8(_v256_shuffle_odd_64(ab)); -} - -inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - __m256i a0 = __lasx_xvshuf4i_w(a.val, 0x08); - v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); -} - -inline void v_pack_store(int* ptr, const v_int64x4& b) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } - -template inline -v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) -{ return v_uint32x8(_v256_shuffle_odd_64(__lasx_xvsrlrni_w_d(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) -{ - __m256i res = __lasx_xvsrlrni_w_d(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -template inline -v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) -{ return v_int32x8(_v256_shuffle_odd_64(__lasx_xvsrarni_w_d(b.val, a.val, n))); } - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x4& a) -{ - __m256i res = __lasx_xvsrarni_w_d(a.val, a.val, n); - __lasx_xvstelm_d(res, ptr, 0, 0); - __lasx_xvstelm_d(res, ptr, 8, 2); -} - -// pack boolean -inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) -{ - __m256i ab = _lasx_packs_h(a.val, b.val); - return v_uint8x32(_v256_shuffle_odd_64(ab)); -} - -inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d) -{ - __m256i ab = _lasx_packs_w(a.val, b.val); - __m256i cd = _lasx_packs_w(c.val, d.val); - - __m256i abcd = _v256_shuffle_odd_64(_lasx_packs_h(ab, cd)); - return v_uint8x32(__lasx_xvshuf4i_w(abcd, 0xd8)); -} - -inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, - const v_uint64x4& g, const v_uint64x4& h) -{ - __m256i ab = _lasx_packs_w(a.val, b.val); - __m256i cd = _lasx_packs_w(c.val, d.val); - __m256i ef = _lasx_packs_w(e.val, f.val); - __m256i gh = _lasx_packs_w(g.val, h.val); - - __m256i abcd = _lasx_packs_w(ab, cd); - __m256i efgh = _lasx_packs_w(ef, gh); - __m256i pkall = _v256_shuffle_odd_64(_lasx_packs_h(abcd, efgh)); - - __m256i rev = _v256_alignr_b(pkall, pkall, 8); - return v_uint8x32(__lasx_xvilvl_h(rev, pkall)); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_LASX_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint8x32) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int8x32) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint16x16) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int16x16) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint32x8) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int32x8) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint64x4) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_int64x4) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_float32x8) -OPENCV_HAL_IMPL_LASX_EXTRACT(v_float64x4) - -template -inline uchar v_extract_n(v_uint8x32 a) -{ - return (uchar)_v256_extract_b(a.val); -} - -template -inline schar v_extract_n(v_int8x32 a) -{ - return (schar)v_extract_n(v_reinterpret_as_u8(a)); -} - -template -inline ushort v_extract_n(v_uint16x16 a) -{ - return (ushort)_v256_extract_h(a.val); -} - -template -inline short v_extract_n(v_int16x16 a) -{ - return (short)v_extract_n(v_reinterpret_as_u16(a)); -} - -template -inline uint v_extract_n(v_uint32x8 a) -{ - return (uint)_v256_extract_w(a.val); -} - -template -inline int v_extract_n(v_int32x8 a) -{ - return (int)v_extract_n(v_reinterpret_as_u32(a)); -} - -template -inline uint64 v_extract_n(v_uint64x4 a) -{ - return (uint64)_v256_extract_d(a.val); -} - -template -inline int64 v_extract_n(v_int64x4 v) -{ - return (int64)v_extract_n(v_reinterpret_as_u64(v)); -} - -template -inline float v_extract_n(v_float32x8 v) -{ - union { uint iv; float fv; } d; - d.iv = v_extract_n(v_reinterpret_as_u32(v)); - return d.fv; -} - -template -inline double v_extract_n(v_float64x4 v) -{ - union { uint64 iv; double dv; } d; - d.iv = v_extract_n(v_reinterpret_as_u64(v)); - return d.dv; -} - -template -inline v_uint32x8 v_broadcast_element(v_uint32x8 a) -{ - static const __m256i perm = __lasx_xvreplgr2vr_w((char)i); - return v_uint32x8(__lasx_xvperm_w(a.val, perm)); -} - -template -inline v_int32x8 v_broadcast_element(const v_int32x8 &a) -{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -template -inline v_float32x8 v_broadcast_element(const v_float32x8 &a) -{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } - -///////////////////// load deinterleave ///////////////////////////// - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - - __m256i p0 = __lasx_xvpickev_b(t1, t0); - __m256i p1 = __lasx_xvpickod_b(t1, t0); - - a.val = __lasx_xvpermi_d(p0, 0xd8); - b.val = __lasx_xvpermi_d(p1, 0xd8); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - - __m256i p0 = __lasx_xvpickev_h(t1, t0); - __m256i p1 = __lasx_xvpickod_h(t1, t0); - - a.val = __lasx_xvpermi_d(p0, 0xd8); - b.val = __lasx_xvpermi_d(p1, 0xd8); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - - __m256i p0 = __lasx_xvpickev_w(t1, t0); - __m256i p1 = __lasx_xvpickod_w(t1, t0); - - a.val = __lasx_xvpermi_d(p0, 0xd8); - b.val = __lasx_xvpermi_d(p1, 0xd8); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) -{ - __m256i ab0 = __lasx_xvld(ptr, 0); - __m256i ab1 = __lasx_xvld(ptr, 32); - - __m256i pl = __lasx_xvpermi_q(ab0, ab1, 0x02); - __m256i ph = __lasx_xvpermi_q(ab0, ab1, 0x13); - __m256i a0 = __lasx_xvilvl_d(ph, pl); - __m256i b0 = __lasx_xvilvh_d(ph, pl); - a = v_uint64x4(a0); - b = v_uint64x4(b0); -} - -inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); - __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); - - const __m256i m0 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); - - __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); - __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); - - const __m256i - sh_b = _v256_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, - 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), - sh_g = _v256_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, - 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), - sh_r = _v256_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, - 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); - b0 = __lasx_xvshuf_b(b0, b0, sh_b); - g0 = __lasx_xvshuf_b(g0, g0, sh_g); - r0 = __lasx_xvshuf_b(r0, r0, sh_r); - - a = v_uint8x32(b0); - b = v_uint8x32(g0); - c = v_uint8x32(r0); -} - -inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); - __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); - - const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); - __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); - __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); - const __m256i sh_b = _v256_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _v256_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, - 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); - const __m256i sh_r = _v256_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - b0 = __lasx_xvshuf_b(b0, b0, sh_b); - g0 = __lasx_xvshuf_b(g0, g0, sh_g); - r0 = __lasx_xvshuf_b(r0, r0, sh_r); - - a = v_uint16x16(b0); - b = v_uint16x16(g0); - c = v_uint16x16(r0); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); - __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); - - __m256i m24 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); - __m256i m92 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); - __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m24), bgr1, m92); - __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m92), bgr1, m24); - __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m24), s02_high, m92); - - b0 = __lasx_xvshuf4i_w(b0, 0x6c); - g0 = __lasx_xvshuf4i_w(g0, 0xb1); - r0 = __lasx_xvshuf4i_w(r0, 0xc6); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) -{ - __m256i bgr0 = __lasx_xvld(ptr, 0); - __m256i bgr1 = __lasx_xvld(ptr, 32); - __m256i bgr2 = __lasx_xvld(ptr, 64); - - __m256i s01 = __lasx_xvpermi_q(bgr0, bgr1, 0x12); // get bgr0 low 128 and bgr1 high 128 - __m256i s12 = __lasx_xvpermi_q(bgr1, bgr2, 0x12); - __m256i s20r = __lasx_xvpermi_d(__lasx_xvpermi_q(bgr2, bgr0, 0x12), 0x1b); - __m256i b0 = __lasx_xvilvl_d(s20r, s01); - __m256i g0 = _v256_alignr_b(s12, s01, 8); - __m256i r0 = __lasx_xvilvh_d(s12, s20r); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - __m256i t2 = __lasx_xvld(ptr, 64); - __m256i t3 = __lasx_xvld(ptr, 96); - - const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); - __m256i ac_lo = __lasx_xvpickev_b(t1, t0); - __m256i bd_lo = __lasx_xvpickod_b(t1, t0); - __m256i ac_hi = __lasx_xvpickev_b(t3, t2); - __m256i bd_hi = __lasx_xvpickod_b(t3, t2); - - __m256i a_pre = __lasx_xvpickev_b(ac_hi, ac_lo); - __m256i c_pre = __lasx_xvpickod_b(ac_hi, ac_lo); - __m256i b_pre = __lasx_xvpickev_b(bd_hi, bd_lo); - __m256i d_pre = __lasx_xvpickod_b(bd_hi, bd_lo); - - a.val = __lasx_xvperm_w(a_pre, sh); - b.val = __lasx_xvperm_w(b_pre, sh); - c.val = __lasx_xvperm_w(c_pre, sh); - d.val = __lasx_xvperm_w(d_pre, sh); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d) -{ - __m256i t0 = __lasx_xvld(ptr, 0); - __m256i t1 = __lasx_xvld(ptr, 32); - __m256i t2 = __lasx_xvld(ptr, 64); - __m256i t3 = __lasx_xvld(ptr, 96); - - const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); - __m256i ac_lo = __lasx_xvpickev_h(t1, t0); - __m256i bd_lo = __lasx_xvpickod_h(t1, t0); - __m256i ac_hi = __lasx_xvpickev_h(t3, t2); - __m256i bd_hi = __lasx_xvpickod_h(t3, t2); - - __m256i a_pre = __lasx_xvpickev_h(ac_hi, ac_lo); - __m256i c_pre = __lasx_xvpickod_h(ac_hi, ac_lo); - __m256i b_pre = __lasx_xvpickev_h(bd_hi, bd_lo); - __m256i d_pre = __lasx_xvpickod_h(bd_hi, bd_lo); - - a.val = __lasx_xvperm_w(a_pre, sh); - b.val = __lasx_xvperm_w(b_pre, sh); - c.val = __lasx_xvperm_w(c_pre, sh); - d.val = __lasx_xvperm_w(d_pre, sh); -} - -inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) -{ - __m256i p0 = __lasx_xvld(ptr, 0); - __m256i p1 = __lasx_xvld(ptr, 32); - __m256i p2 = __lasx_xvld(ptr, 64); - __m256i p3 = __lasx_xvld(ptr, 96); - - __m256i p01l = __lasx_xvilvl_w(p1, p0); - __m256i p01h = __lasx_xvilvh_w(p1, p0); - __m256i p23l = __lasx_xvilvl_w(p3, p2); - __m256i p23h = __lasx_xvilvh_w(p3, p2); - - __m256i pll = __lasx_xvpermi_q(p01l, p23l, 0x02); - __m256i plh = __lasx_xvpermi_q(p01l, p23l, 0x13); - __m256i phl = __lasx_xvpermi_q(p01h, p23h, 0x02); - __m256i phh = __lasx_xvpermi_q(p01h, p23h, 0x13); - - __m256i b0 = __lasx_xvilvl_w(plh, pll); - __m256i g0 = __lasx_xvilvh_w(plh, pll); - __m256i r0 = __lasx_xvilvl_w(phh, phl); - __m256i a0 = __lasx_xvilvh_w(phh, phl); - - a = v_uint32x8(b0); - b = v_uint32x8(g0); - c = v_uint32x8(r0); - d = v_uint32x8(a0); -} - -inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) -{ - __m256i bgra0 = __lasx_xvld(ptr, 0); - __m256i bgra1 = __lasx_xvld(ptr, 32); - __m256i bgra2 = __lasx_xvld(ptr, 64); - __m256i bgra3 = __lasx_xvld(ptr, 96); - - __m256i l02 = __lasx_xvpermi_q(bgra0, bgra2, 0x02); - __m256i h02 = __lasx_xvpermi_q(bgra0, bgra2, 0x13); - __m256i l13 = __lasx_xvpermi_q(bgra1, bgra3, 0x02); - __m256i h13 = __lasx_xvpermi_q(bgra1, bgra3, 0x13); - - __m256i b0 = __lasx_xvilvl_d(l13, l02); - __m256i g0 = __lasx_xvilvh_d(l13, l02); - __m256i r0 = __lasx_xvilvl_d(h13, h02); - __m256i a0 = __lasx_xvilvh_d(h13, h02); - - a = v_uint64x4(b0); - b = v_uint64x4(g0); - c = v_uint64x4(r0); - d = v_uint64x4(a0); -} - -///////////////////////////// store interleave ///////////////////////////////////// - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_b(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_b(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 32*1); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_h(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_h(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 16*2); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_w(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_w(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 8*4); -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i xy_l = __lasx_xvilvl_d(y.val, x.val); - __m256i xy_h = __lasx_xvilvh_d(y.val, x.val); - - __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); - __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); - - __lasx_xvst(xy0, (__m256i*)ptr, 0); - __lasx_xvst(xy1, (__m256i*)ptr, 4*8); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _v256_setr_b( - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, - 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); - const __m256i sh_g = _v256_setr_b( - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, - 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); - const __m256i sh_r = _v256_setr_b( - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, - 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); - - __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); - __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); - __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); - - const __m256i m0 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, - 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - const __m256i m1 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, - 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - - __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); - __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); - __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); - - __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); - __m256i bgr1 = __lasx_xvpermi_q(p0, p2, 0 + 3*16); - __m256i bgr2 = __lasx_xvpermi_q(p2, p1, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(bgr1, (__m256i*)ptr, 32); - __lasx_xvst(bgr2, (__m256i*)ptr, 64); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - const __m256i sh_b = _v256_setr_b( - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, - 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m256i sh_g = _v256_setr_b( - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, - 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); - const __m256i sh_r = _v256_setr_b( - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, - 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - - __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); - __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); - __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); - - const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, - 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); - const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, - -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); - - __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); - __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); - __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); - - __m256i bgr0 = __lasx_xvpermi_q(p2, p0, 0 + 2*16); - __m256i bgr2 = __lasx_xvpermi_q(p2, p0, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(p1, (__m256i*)ptr, 16*2); - __lasx_xvst(bgr2, (__m256i*)ptr, 32*2); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i b0 = __lasx_xvshuf4i_w(a.val, 0x6c); - __m256i g0 = __lasx_xvshuf4i_w(b.val, 0xb1); - __m256i r0 = __lasx_xvshuf4i_w(c.val, 0xc6); - - __m256i bitmask_1 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); - __m256i bitmask_2 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); - - __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, bitmask_1), r0, bitmask_2); - __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, bitmask_1), b0, bitmask_2); - __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, bitmask_1), g0, bitmask_2); - - __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); - __m256i bgr2 = __lasx_xvpermi_q(p1, p0, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(p2, (__m256i*)ptr, 8*4); - __lasx_xvst(bgr2, (__m256i*)ptr, 16*4); -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i s01 = __lasx_xvilvl_d(b.val, a.val); - __m256i s12 = __lasx_xvilvh_d(c.val, b.val); - __m256i s20 = __lasx_xvpermi_w(a.val, c.val, 0xe4); - - __m256i bgr0 = __lasx_xvpermi_q(s20, s01, 0 + 2*16); - __m256i bgr1 = __lasx_xvpermi_q(s01, s12, 0x30); - __m256i bgr2 = __lasx_xvpermi_q(s12, s20, 1 + 3*16); - - __lasx_xvst(bgr0, (__m256i*)ptr, 0); - __lasx_xvst(bgr1, (__m256i*)ptr, 4*8); - __lasx_xvst(bgr2, (__m256i*)ptr, 8*8); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, - const v_uint8x32& c, const v_uint8x32& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_b(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_b(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_b(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_b(d.val, c.val); - - __m256i bgra0_ = __lasx_xvilvl_h(ra0, bg0); - __m256i bgra1_ = __lasx_xvilvh_h(ra0, bg0); - __m256i bgra2_ = __lasx_xvilvl_h(ra1, bg1); - __m256i bgra3_ = __lasx_xvilvh_h(ra1, bg1); - - __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); - __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); - __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)ptr, 32); - __lasx_xvst(bgra2, (__m256i*)ptr, 64); - __lasx_xvst(bgra3, (__m256i*)ptr, 96); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, - const v_uint16x16& c, const v_uint16x16& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_h(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_h(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_h(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_h(d.val, c.val); - - __m256i bgra0_ = __lasx_xvilvl_w(ra0, bg0); - __m256i bgra1_ = __lasx_xvilvh_w(ra0, bg0); - __m256i bgra2_ = __lasx_xvilvl_w(ra1, bg1); - __m256i bgra3_ = __lasx_xvilvh_w(ra1, bg1); - - __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); - __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); - __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)ptr, 16*2); - __lasx_xvst(bgra2, (__m256i*)ptr, 32*2); - __lasx_xvst(bgra3, (__m256i*)ptr, 48*2); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, - const v_uint32x8& c, const v_uint32x8& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_w(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_w(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_w(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_w(d.val, c.val); - - __m256i bgra0_ = __lasx_xvilvl_d(ra0, bg0); - __m256i bgra1_ = __lasx_xvilvh_d(ra0, bg0); - __m256i bgra2_ = __lasx_xvilvl_d(ra1, bg1); - __m256i bgra3_ = __lasx_xvilvh_d(ra1, bg1); - - __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); - __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); - __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)ptr, 8*4); - __lasx_xvst(bgra2, (__m256i*)ptr, 16*4); - __lasx_xvst(bgra3, (__m256i*)ptr, 24*4); -} - -inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, - const v_uint64x4& c, const v_uint64x4& d, - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) -{ - __m256i bg0 = __lasx_xvilvl_d(b.val, a.val); - __m256i bg1 = __lasx_xvilvh_d(b.val, a.val); - __m256i ra0 = __lasx_xvilvl_d(d.val, c.val); - __m256i ra1 = __lasx_xvilvh_d(d.val, c.val); - - __m256i bgra0 = __lasx_xvpermi_q(ra0, bg0, 0 + 2*16); - __m256i bgra1 = __lasx_xvpermi_q(ra1, bg1, 0 + 2*16); - __m256i bgra2 = __lasx_xvpermi_q(ra0, bg0, 1 + 3*16); - __m256i bgra3 = __lasx_xvpermi_q(ra1, bg1, 1 + 3*16); - - __lasx_xvst(bgra0, (__m256i*)ptr, 0); - __lasx_xvst(bgra1, (__m256i*)(ptr), 4*8); - __lasx_xvst(bgra2, (__m256i*)(ptr), 8*8); - __lasx_xvst(bgra3, (__m256i*)(ptr), 12*8); -} - - -#define OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1/*, mode*/); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1/*, mode*/); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1/*, mode*/); \ -} - -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) -OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) - -// -// FP16 -// - -inline v_float32x8 v256_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - //1-load128, 2-permi, 3-cvt - return v_float32x8(__lasx_xvfcvtl_s_h(__lasx_xvpermi_d(__lsx_vld((const __m128i*)ptr, 0), 0x10))); -#else - float CV_DECL_ALIGNED(32) buf[8]; - for (int i = 0; i < 8; i++) - buf[i] = (float)ptr[i]; - return v256_load_aligned(buf); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x8& a) -{ -#if CV_FP16 - __m256i ah = __lasx_xvfcvt_h_s(a.val, a.val); - __lsx_vst((_m128i)ah, ptr, 0); -#else - float CV_DECL_ALIGNED(32) buf[8]; - v_store_aligned(buf, a); - for (int i = 0; i < 8; i++) - ptr[i] = hfloat(buf[i]); -#endif -} - -// -// end of FP16 -// - -inline void v256_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } -inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } -inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } -inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } - -inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } -inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } -inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_LASX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_LASX_HPP +#define OPENCV_HAL_INTRIN_LASX_HPP + +#include +#include + +#define CV_SIMD256 1 +#define CV_SIMD256_64F 1 +#define CV_SIMD256_FP16 0 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Utils //////////// + +inline __m256i _v256_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, + char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, + char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, + char v30, char v31) +{ + return (__m256i)v32i8{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, + v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, + v30, v31 }; +} + +inline __m256i _v256_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, char v7, char v8, char v9, + char v10, char v11, char v12, char v13, char v14, char v15, char v16, char v17, char v18, char v19, + char v20, char v21, char v22, char v23, char v24, char v25, char v26, char v27, char v28, char v29, + char v30, char v31) +{ + return (__m256i)v32i8{ v31, v30, + v29, v28, v27, v26, v25, v24, v23, v22, v21, v20, + v19, v18, v17, v16, v15, v14, v13, v12, v11, v10, + v9, v8, v7, v6, v5, v4, v3, v2, v1, v0 }; +} + +inline __m256i _v256_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, short v12, short v13, short v14, short v15) +{ + return (__m256i)v16i16{ v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +inline __m256i _v256_setr_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) +{ + return (__m256i)v8i32{ v0, v1, v2, v3, v4, v5, v6, v7 }; +} + +inline __m256i _v256_set_w(int v0, int v1, int v2, int v3, int v4, int v5, int v6, int v7) +{ + return (__m256i)v8i32{ v7, v6, v5, v4, v3, v2, v1, v0 }; +} + +inline __m256i _v256_setall_w(int v0) +{ + return (__m256i)v8i32{ v0, v0, v0, v0, v0, v0, v0, v0 }; +} + +inline __m256i _v256_setr_d(int64 v0, int64 v1, int64 v2, int64 v3) +{ + return (__m256i)v4i64{ v0, v1, v2, v3 }; +} + +inline __m256i _v256_set_d(int64 v0, int64 v1, int64 v2, int64 v3) +{ + return (__m256i)v4i64{ v3, v2, v1, v0 }; +} + +inline __m256 _v256_setr_ps(float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7) +{ + return (__m256)v8f32{ v0, v1, v2, v3, v4, v5, v6, v7 }; +} + +inline __m256 _v256_setall_ps(float f32) +{ + return (__m256)v8f32{ f32, f32, f32, f32, f32, f32, f32, f32 }; +} + +inline __m256d _v256_setr_pd(double v0, double v1, double v2, double v3) +{ + return (__m256d)v4f64{ v0, v1, v2, v3 }; +} + +inline __m256d _v256_setall_pd(double f64) +{ + return (__m256d)v4f64{ f64, f64, f64, f64 }; +} + +inline __m256i _lasx_packus_h(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_bu_h(b, a, 0); +} + +inline __m256i _lasx_packs_h(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_b_h(b, a, 0); +} + +inline __m256i _lasx_packus_w(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_hu_w(b, a, 0); +} + +inline __m256i _lasx_packs_w(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrarni_h_w(b, a, 0); +} + +inline __m256i _v256_combine(const __m128i& lo, const __m128i& hi) +{ return __lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02); } + +inline __m256 _v256_combine(const __m128& lo, const __m128& hi) +{ return __m256(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } + +inline __m256d _v256_combine(const __m128d& lo, const __m128d& hi) +{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&lo), *((__m256i*)&hi), 0x02)); } + +inline __m256i _v256_shuffle_odd_64(const __m256i& v) +{ return __lasx_xvpermi_d(v, 0xd8); } + +inline __m256d _v256_shuffle_odd_64(const __m256d& v) +{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&v), 0xd8)); } + +//LASX: only use for permute WITHOUT zero clearing +template +inline __m256i _v256_permute2x128(const __m256i& a, const __m256i& b) +{ return __lasx_xvpermi_q(a, b, imm); } + +template +inline __m256 _v256_permute2x128(const __m256& a, const __m256& b) +{ return __m256(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } + +template +inline __m256d _v256_permute2x128(const __m256d& a, const __m256d& b) +{ return __m256d(__lasx_xvpermi_q(*((__m256i*)&a), *((__m256i*)&b), imm)); } + +template +inline _Tpvec v256_permute2x128(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_v256_permute2x128(a.val, b.val)); } + +template +inline __m256i _v256_permute4x64(const __m256i& a) +{ return __lasx_xvpermi_d(a, imm); } + +template +inline __m256d _v256_permute4x64(const __m256d& a) +{ return __m256d(__lasx_xvpermi_d(*((__m256i*)&a), imm)); } + +template +inline _Tpvec v256_permute4x64(const _Tpvec& a) +{ return _Tpvec(_v256_permute4x64(a.val)); } + +inline __m128i _v256_extract_high(const __m256i& v) +{ __m256i temp256i = __lasx_xvpermi_d(v, 0x4E); + return *((__m128i*)&temp256i); } + +inline __m128 _v256_extract_high(const __m256& v) +{ return __m128(_v256_extract_high(*((__m256i*)&v))); } + +inline __m128d _v256_extract_high(const __m256d& v) +{ return __m128d(_v256_extract_high(*((__m256i*)&v))); } + +inline __m128i _v256_extract_low(const __m256i& v) +{ return *((__m128i*)&v); } + +inline __m128 _v256_extract_low(const __m256& v) +{ return __m128(_v256_extract_low(*((__m256i*)&v))); } + +inline __m128d _v256_extract_low(const __m256d& v) +{ return __m128d(_v256_extract_low(*((__m256i*)&v))); } + +inline __m256i _v256_packs_epu32(const __m256i& a, const __m256i& b) +{ + return __lasx_xvssrlrni_hu_w(b, a, 0); +} + +template +inline int _v256_extract_b(const __m256i& a) +{ + int des[1] = {0}; + __lasx_xvstelm_b(a, des, 0, i); + return des[0]; +} + +template +inline int _v256_extract_h(const __m256i& a) +{ + int des[1] = {0}; + __lasx_xvstelm_h(a, des, 0, i); + return des[0]; +} + +template +inline int _v256_extract_w(const __m256i& a) +{ + return __lasx_xvpickve2gr_w(a, i); +} + +template +inline int64 _v256_extract_d(const __m256i& a) +{ + return __lasx_xvpickve2gr_d(a, i); +} + +///////// Types //////////// + +struct v_uint8x32 +{ + typedef uchar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_uint8x32(__m256i v) : val(v) {} + v_uint8x32(uchar v0, uchar v1, uchar v2, uchar v3, + uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, + uchar v12, uchar v13, uchar v14, uchar v15, + uchar v16, uchar v17, uchar v18, uchar v19, + uchar v20, uchar v21, uchar v22, uchar v23, + uchar v24, uchar v25, uchar v26, uchar v27, + uchar v28, uchar v29, uchar v30, uchar v31) + { + val = _v256_setr_b((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6 , (char)v7, (char)v8, (char)v9, + (char)v10, (char)v11, (char)v12, (char)v13, (char)v14, (char)v15, + (char)v16, (char)v17, (char)v18, (char)v19, (char)v20, (char)v21, + (char)v22, (char)v23, (char)v24, (char)v25, (char)v26, (char)v27, + (char)v28, (char)v29, (char)v30, (char)v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint8x32() {} + + uchar get0() const { + uchar des[1] = {0}; + __lasx_xvstelm_b(val, des, 0, 0); + return des[0]; + } +}; + +struct v_int8x32 +{ + typedef schar lane_type; + enum { nlanes = 32 }; + __m256i val; + + explicit v_int8x32(__m256i v) : val(v) {} + v_int8x32(schar v0, schar v1, schar v2, schar v3, + schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, + schar v12, schar v13, schar v14, schar v15, + schar v16, schar v17, schar v18, schar v19, + schar v20, schar v21, schar v22, schar v23, + schar v24, schar v25, schar v26, schar v27, + schar v28, schar v29, schar v30, schar v31) + { + val = _v256_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, + v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, + v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int8x32() {} + + schar get0() const { + schar des[1] = {0}; + __lasx_xvstelm_b(val, des, 0, 0); + return des[0]; + } +}; + +struct v_uint16x16 +{ + typedef ushort lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_uint16x16(__m256i v) : val(v) {} + v_uint16x16(ushort v0, ushort v1, ushort v2, ushort v3, + ushort v4, ushort v5, ushort v6, ushort v7, + ushort v8, ushort v9, ushort v10, ushort v11, + ushort v12, ushort v13, ushort v14, ushort v15) + { + val = _v256_setr_h((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7, (short)v8, (short)v9, + (short)v10, (short)v11, (short)v12, (short)v13, (short)v14, (short)v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint16x16() {} + + ushort get0() const { + ushort des[1] = {0}; + __lasx_xvstelm_h(val, des, 0, 0); + return des[0]; + } +}; + +struct v_int16x16 +{ + typedef short lane_type; + enum { nlanes = 16 }; + __m256i val; + + explicit v_int16x16(__m256i v) : val(v) {} + v_int16x16(short v0, short v1, short v2, short v3, + short v4, short v5, short v6, short v7, + short v8, short v9, short v10, short v11, + short v12, short v13, short v14, short v15) + { + val = _v256_setr_h(v0, v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int16x16() {} + + short get0() const { + short des[1] = {0}; + __lasx_xvstelm_h(val, des, 0, 0); + return des[0]; + } +}; + +struct v_uint32x8 +{ + typedef unsigned lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_uint32x8(__m256i v) : val(v) {} + v_uint32x8(unsigned v0, unsigned v1, unsigned v2, unsigned v3, + unsigned v4, unsigned v5, unsigned v6, unsigned v7) + { + val = _v256_setr_w((unsigned)v0, (unsigned)v1, (unsigned)v2, + (unsigned)v3, (unsigned)v4, (unsigned)v5, (unsigned)v6, (unsigned)v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_uint32x8() {} + + unsigned get0() const { return __lasx_xvpickve2gr_wu(val, 0); } +}; + +struct v_int32x8 +{ + typedef int lane_type; + enum { nlanes = 8 }; + __m256i val; + + explicit v_int32x8(__m256i v) : val(v) {} + v_int32x8(int v0, int v1, int v2, int v3, + int v4, int v5, int v6, int v7) + { + val = _v256_setr_w(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_int32x8() {} + + int get0() const { return __lasx_xvpickve2gr_w(val, 0); } +}; + +struct v_float32x8 +{ + typedef float lane_type; + enum { nlanes = 8 }; + __m256 val; + + explicit v_float32x8(__m256 v) : val(v) {} + explicit v_float32x8(__m256i v) { val = *((__m256*)&v); } + v_float32x8(float v0, float v1, float v2, float v3, + float v4, float v5, float v6, float v7) + { + val = _v256_setr_ps(v0, v1, v2, v3, v4, v5, v6, v7); + } + /* coverity[uninit_ctor]: suppress warning */ + v_float32x8() {} + + float get0() const { + float des[1] = {0}; + __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); + return des[0]; + } + + int get0toint() const { + int des[1] = {0}; + __lasx_xvstelm_w(*((__m256i*)&val), des, 0, 0); + return des[0]; + } +}; + +struct v_uint64x4 +{ + typedef uint64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_uint64x4(__m256i v) : val(v) {} + v_uint64x4(uint64 v0, uint64 v1, uint64 v2, uint64 v3) + { val = _v256_setr_d((int64)v0, (int64)v1, (int64)v2, (int64)v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_uint64x4() {} + + uint64 get0() const + { + return __lasx_xvpickve2gr_du(val, 0); + } +}; + +struct v_int64x4 +{ + typedef int64 lane_type; + enum { nlanes = 4 }; + __m256i val; + + explicit v_int64x4(__m256i v) : val(v) {} + v_int64x4(int64 v0, int64 v1, int64 v2, int64 v3) + { val = _v256_setr_d(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_int64x4() {} + + int64 get0() const + { + return __lasx_xvpickve2gr_d(val, 0); + } +}; + +struct v_float64x4 +{ + typedef double lane_type; + enum { nlanes = 4 }; + __m256d val; + + explicit v_float64x4(__m256d v) : val(v) {} + explicit v_float64x4(__m256i v) { val = *((__m256d*)&v); } + v_float64x4(double v0, double v1, double v2, double v3) + { val = _v256_setr_pd(v0, v1, v2, v3); } + /* coverity[uninit_ctor]: suppress warning */ + v_float64x4() {} + + double get0() const { + double des[1] = {0}; + __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); + return des[0]; + } + + int64 get0toint64() const { + int64 des[1] = {0}; + __lasx_xvstelm_d(*((__m256i*)&val), des, 0, 0); + return des[0]; + } +}; + +//////////////// Load and store operations /////////////// + +#define OPENCV_HAL_IMPL_LASX_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + __m128i v128 = __lsx_vld(ptr, 0); \ + return _Tpvec(*((__m256i*)&v128)); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vlo = __lsx_vld(ptr0, 0); \ + __m128i vhi = __lsx_vld(ptr1, 0); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + __lasx_xvst(a.val, ptr, 0); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + __lasx_xvst(a.val, ptr, 0); \ + else \ + __lasx_xvst(a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } + +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint8x32, uchar) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int8x32, schar) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint16x16, ushort) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int16x16, short) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint32x8, unsigned) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int32x8, int) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_uint64x4, uint64) +OPENCV_HAL_IMPL_LASX_LOADSTORE(v_int64x4, int64) + + +#define OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ + inline _Tpvec v256_load(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_aligned(const _Tp* ptr) \ + { return _Tpvec(__lasx_xvld(ptr, 0)); } \ + inline _Tpvec v256_load_low(const _Tp* ptr) \ + { \ + __m128i v128 = __lsx_vld(ptr, 0); \ + return _Tpvec(*((__m256i*)&v128)); \ + } \ + inline _Tpvec v256_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + halfreg vlo = __lsx_vld(ptr0, 0); \ + halfreg vhi = __lsx_vld(ptr1, 0); \ + return _Tpvec(_v256_combine(vlo, vhi)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lasx_xvst(a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ + { \ + if( mode == hal::STORE_UNALIGNED ) \ + __lasx_xvst(a.val, ptr, 0); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + __lasx_xvst(a.val, ptr, 0); \ + else \ + __lasx_xvst(a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_low(a.val), ptr, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(_v256_extract_high(a.val), ptr, 0); } + +OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float32x8, float, __m128i) +OPENCV_HAL_IMPL_LASX_LOADSTORE_FLT(v_float64x4, double, __m128i) + + +inline __m256i _lasx_256_castps_si256(const __m256& v) +{ return __m256i(v); } + +inline __m256i _lasx_256_castpd_si256(const __m256d& v) +{ return __m256i(v); } + +#define OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_LASX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(__lasx_xvreplgr2vr_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float32x8, suffix, _lasx_256_castps_si256) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_float64x4, suffix, _lasx_256_castpd_si256) + +OPENCV_HAL_IMPL_LASX_INIT(v_uint8x32, uchar, u8, b, int) +OPENCV_HAL_IMPL_LASX_INIT(v_int8x32, schar, s8, b, int) +OPENCV_HAL_IMPL_LASX_INIT(v_uint16x16, ushort, u16, h, int) +OPENCV_HAL_IMPL_LASX_INIT(v_int16x16, short, s16, h, int) +OPENCV_HAL_IMPL_LASX_INIT(v_uint32x8, unsigned, u32, w, int) +OPENCV_HAL_IMPL_LASX_INIT(v_int32x8, int, s32, w, int) +OPENCV_HAL_IMPL_LASX_INIT(v_uint64x4, uint64, u64, d, long int) +OPENCV_HAL_IMPL_LASX_INIT(v_int64x4, int64, s64, d, long int) + + +inline __m256 _lasx_256_castsi256_ps(const __m256i &v) +{ return __m256(v); } + +inline __m256d _lasx_256_castsi256_pd(const __m256i &v) +{ return __m256d(v); } + +#define OPENCV_HAL_IMPL_LASX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v256_setzero_##suffix() \ + { return _Tpvec(__lasx_xvreplgr2vr_d(0)); } \ + inline _Tpvec v256_setall_##suffix(_Tp v) \ + { return _Tpvec(_v256_setall_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v256_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v256_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint8x32, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int8x32, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint16x16, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int16x16, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint32x8, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int32x8, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_uint64x4, suffix, cast) \ + OPENCV_HAL_IMPL_LASX_CAST(_Tpvec, v_int64x4, suffix, cast) + +OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float32x8, float, f32, ps, _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_INIT_FLT(v_float64x4, double, f64, pd, _lasx_256_castsi256_pd) + +inline v_float32x8 v_reinterpret_as_f32(const v_float32x8& a) +{ return a; } +inline v_float32x8 v_reinterpret_as_f32(const v_float64x4& a) +{ return v_float32x8(_lasx_256_castps_si256(__m256(a.val))); } + +inline v_float64x4 v_reinterpret_as_f64(const v_float64x4& a) +{ return a; } +inline v_float64x4 v_reinterpret_as_f64(const v_float32x8& a) +{ return v_float64x4(_lasx_256_castpd_si256(__m256d(a.val))); } + + +//////////////// Variant Value reordering /////////////// + +// unpacks +#define OPENCV_HAL_IMPL_LASX_UNPACK(_Tpvec, suffix) \ + inline _Tpvec v256_unpacklo(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvilvl_##suffix(__m256i(b.val), __m256i(a.val))); } \ + inline _Tpvec v256_unpackhi(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvilvh_##suffix(__m256i(b.val), __m256i(a.val))); } + +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint8x32, b) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int8x32, b) +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint16x16, h) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int16x16, h) +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint32x8, w) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int32x8, w) +OPENCV_HAL_IMPL_LASX_UNPACK(v_uint64x4, d) +OPENCV_HAL_IMPL_LASX_UNPACK(v_int64x4, d) +OPENCV_HAL_IMPL_LASX_UNPACK(v_float32x8, w) +OPENCV_HAL_IMPL_LASX_UNPACK(v_float64x4, d) + + +// shuffle +// todo: emulate 64bit +#define OPENCV_HAL_IMPL_LASX_SHUFFLE(_Tpvec, intrin) \ + template \ + inline _Tpvec v256_shuffle(const _Tpvec& a) \ + { return _Tpvec(__lasx_xvshuf4i_##intrin(a.val, m)); } + +OPENCV_HAL_IMPL_LASX_SHUFFLE(v_uint32x8, w) +OPENCV_HAL_IMPL_LASX_SHUFFLE(v_int32x8, w) + +template +inline v_float32x8 v256_shuffle(const v_float32x8 &a) +{ return v_float32x8(__lasx_xvshuf4i_w(*((__m256i*)&a.val), m)); } + +template +inline v_float64x4 v256_shuffle(const v_float64x4 &a) +{ + const int m1 = m & 0b1; + const int m2 = m & 0b10; + const int m3 = m & 0b100; + const int m4 = m & 0b1000; + const int m5 = m2 << 1; + const int m6 = m3 << 2; + const int m7 = m4 << 3; + const int m8 = m1 & m5 & m6 & m7; + + return v_float64x4(__lasx_xvshuf4i_d(*((__m256i*)&a.val), *((__m256i*)&a.val), m8)); +} + +template +inline void v256_zip(const _Tpvec& a, const _Tpvec& b, _Tpvec& ab0, _Tpvec& ab1) +{ + ab0 = v256_unpacklo(a, b); + ab1 = v256_unpackhi(a, b); +} + +template +inline _Tpvec v256_combine_diagonal(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(__lasx_xvpermi_q(a.val, b.val, 0x12)); } + +inline v_float32x8 v256_combine_diagonal(const v_float32x8& a, const v_float32x8& b) +{ return v_float32x8(__lasx_xvpermi_q(a.val, b.val, 0x12)); } + +inline v_float64x4 v256_combine_diagonal(const v_float64x4& a, const v_float64x4& b) +{ return v_float64x4(__lasx_xvpermi_q(a.val, b.val, 0x12)); } + +template +inline _Tpvec v256_alignr_128(const _Tpvec& a, const _Tpvec& b) +{ return v256_permute2x128<0x03>(a, b); } + +inline __m256i _v256_alignr_b(const __m256i &a, const __m256i &b, const int imm) +{ + if (imm == 8) { + return __lasx_xvshuf4i_d(b, a, 0x9); // b.d1 a.d0 b.d3 a.d2 + } else { + __m256i byteIndex = _v256_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + return __lasx_xvshuf_b(a, b, __lasx_xvadd_b(__lasx_xvreplgr2vr_b(imm), byteIndex)); + } +} + +template +inline _Tpvec v256_alignr_64(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(_v256_alignr_b(a.val, b.val, 8)); } +inline v_float64x4 v256_alignr_64(const v_float64x4& a, const v_float64x4& b) +{ return v_float64x4(__lasx_xvshuf4i_d(b.val, a.val, 0x9)); } // b.d1 a.d0 b.d3 a.d2 +// todo: emulate float32 + +template +inline _Tpvec v256_swap_halves(const _Tpvec& a) +{ return v256_permute2x128<1>(a, a); } + +template +inline _Tpvec v256_reverse_64(const _Tpvec& a) +{ return v256_permute4x64<0x1b>(a); } + + +// ZIP +#define OPENCV_HAL_IMPL_LASX_ZIP(_Tpvec) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x02>(a, b); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return v256_permute2x128<0x13>(a, b); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + _Tpvec a1b0 = v256_alignr_128(a, b); \ + c = v256_combine_diagonal(a, a1b0); \ + d = v256_combine_diagonal(a1b0, b); \ + } \ + inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& ab0, _Tpvec& ab1) \ + { \ + _Tpvec ab0ab2, ab1ab3; \ + v256_zip(a, b, ab0ab2, ab1ab3); \ + v_recombine(ab0ab2, ab1ab3, ab0, ab1); \ + } + +OPENCV_HAL_IMPL_LASX_ZIP(v_uint8x32) +OPENCV_HAL_IMPL_LASX_ZIP(v_int8x32) +OPENCV_HAL_IMPL_LASX_ZIP(v_uint16x16) +OPENCV_HAL_IMPL_LASX_ZIP(v_int16x16) +OPENCV_HAL_IMPL_LASX_ZIP(v_uint32x8) +OPENCV_HAL_IMPL_LASX_ZIP(v_int32x8) +OPENCV_HAL_IMPL_LASX_ZIP(v_uint64x4) +OPENCV_HAL_IMPL_LASX_ZIP(v_int64x4) +OPENCV_HAL_IMPL_LASX_ZIP(v_float32x8) +OPENCV_HAL_IMPL_LASX_ZIP(v_float64x4) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_LASX_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint8x32, __lasx_xvsadd_bu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint8x32, __lasx_xvssub_bu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int8x32, __lasx_xvsadd_b) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int8x32, __lasx_xvssub_b) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint16x16, __lasx_xvsadd_hu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint16x16, __lasx_xvssub_hu) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int16x16, __lasx_xvsadd_h) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int16x16, __lasx_xvssub_h) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint32x8, __lasx_xvadd_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint32x8, __lasx_xvsub_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_uint32x8, __lasx_xvmul_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int32x8, __lasx_xvadd_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int32x8, __lasx_xvsub_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_int32x8, __lasx_xvmul_w) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_uint64x4, __lasx_xvadd_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_uint64x4, __lasx_xvsub_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_int64x4, __lasx_xvadd_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_int64x4, __lasx_xvsub_d) + +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float32x8, __lasx_xvfadd_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float32x8, __lasx_xvfsub_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float32x8, __lasx_xvfmul_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float32x8, __lasx_xvfdiv_s) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_add, v_float64x4, __lasx_xvfadd_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_sub, v_float64x4, __lasx_xvfsub_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_mul, v_float64x4, __lasx_xvfmul_d) +OPENCV_HAL_IMPL_LASX_BIN_OP(v_div, v_float64x4, __lasx_xvfdiv_d) + +// saturating multiply 8-bit, 16-bit +inline v_uint8x32 v_mul(const v_uint8x32& a, const v_uint8x32& b) +{ + v_uint16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x32 v_mul(const v_int8x32& a, const v_int8x32& b) +{ + v_int16x16 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x16 v_mul(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i pl = __lasx_xvmul_h(a.val, b.val); + __m256i ph = __lasx_xvmuh_hu(a.val, b.val); + __m256i p0 = __lasx_xvilvl_h(ph, pl); + __m256i p1 = __lasx_xvilvh_h(ph, pl); + return v_uint16x16(_v256_packs_epu32(p0, p1)); +} +inline v_int16x16 v_mul(const v_int16x16& a, const v_int16x16& b) +{ + __m256i pl = __lasx_xvmul_h(a.val, b.val); + __m256i ph = __lasx_xvmuh_h(a.val, b.val); + __m256i p0 = __lasx_xvilvl_h(ph, pl); + __m256i p1 = __lasx_xvilvh_h(ph, pl); + return v_int16x16(_lasx_packs_w(p0, p1)); +} + +/** Non-saturating arithmetics **/ + +#define OPENCV_HAL_IMPL_LASX_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint8x32, __lasx_xvadd_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int8x32, __lasx_xvadd_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_uint16x16, __lasx_xvadd_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_add_wrap, v_int16x16, __lasx_xvadd_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint8x32, __lasx_xvsub_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int8x32, __lasx_xvsub_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_uint16x16, __lasx_xvsub_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_sub_wrap, v_int16x16, __lasx_xvsub_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_uint16x16, __lasx_xvmul_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_mul_wrap, v_int16x16, __lasx_xvmul_h) + +inline v_uint8x32 v_mul_wrap(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i p0 = __lasx_xvmulwev_h_bu(a.val, b.val); + __m256i p1 = __lasx_xvmulwod_h_bu(a.val, b.val); + return v_uint8x32(__lasx_xvpackev_b(p1, p0)); +} + +inline v_int8x32 v_mul_wrap(const v_int8x32& a, const v_int8x32& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +// Multiply and expand +inline void v_mul_expand(const v_uint8x32& a, const v_uint8x32& b, + v_uint16x16& c, v_uint16x16& d) +{ + v_uint16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x32& a, const v_int8x32& b, + v_int16x16& c, v_int16x16& d) +{ + v_int16x16 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x16& a, const v_int16x16& b, + v_int32x8& c, v_int32x8& d) +{ + v_int16x16 vhi = v_int16x16(__lasx_xvmuh_h(a.val, b.val)); + + v_int16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_s32(v0); + d = v_reinterpret_as_s32(v1); +} + +inline void v_mul_expand(const v_uint16x16& a, const v_uint16x16& b, + v_uint32x8& c, v_uint32x8& d) +{ + v_uint16x16 vhi = v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); + + v_uint16x16 v0, v1; + v_zip(v_mul_wrap(a, b), vhi, v0, v1); + + c = v_reinterpret_as_u32(v0); + d = v_reinterpret_as_u32(v1); +} + +inline void v_mul_expand(const v_uint32x8& a, const v_uint32x8& b, + v_uint64x4& c, v_uint64x4& d) +{ + __m256i v0 = __lasx_xvmulwev_d_wu(a.val, b.val); + __m256i v1 = __lasx_xvmulwod_d_wu(a.val, b.val); + v_zip(v_uint64x4(v0), v_uint64x4(v1), c, d); +} + +inline v_int16x16 v_mul_hi(const v_int16x16& a, const v_int16x16& b) { return v_int16x16(__lasx_xvmuh_h(a.val, b.val)); } +inline v_uint16x16 v_mul_hi(const v_uint16x16& a, const v_uint16x16& b) { return v_uint16x16(__lasx_xvmuh_hu(a.val, b.val)); } + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_LASX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(__lasx_xvsll_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(__lasx_xvsrl_##suffix(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(srai(a.val, __lasx_xvreplgr2vr_##suffix(imm))); } + +OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint16x16, v_int16x16, h, __lasx_xvsra_h) +OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint32x8, v_int32x8, w, __lasx_xvsra_w) +OPENCV_HAL_IMPL_LASX_SHIFT_OP(v_uint64x4, v_int64x4, d, __lasx_xvsra_d) + + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_LASX_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_LASX_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix) \ + OPENCV_HAL_IMPL_LASX_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix) \ + OPENCV_HAL_IMPL_LASX_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lasx_xvnori_b(a.val, 0)); } + +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint8x32, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int8x32, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint16x16, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int16x16, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint32x8, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int32x8, v, __lasx_xvreplgr2vr_w(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_uint64x4, v, __lasx_xvreplgr2vr_d(-1)) +OPENCV_HAL_IMPL_LASX_LOGIC_OP(v_int64x4, v, __lasx_xvreplgr2vr_d(-1)) + +#define OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(*((__m256i*)(&a.val)), *((__m256i*)(&b.val)))); } + +#define OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(_Tpvec, suffix, not_const, cast) \ + OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_and, _Tpvec, __lasx_xvand_##suffix, cast) \ + OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_or, _Tpvec, __lasx_xvor_##suffix, cast) \ + OPENCV_HAL_IMPL_LASX_FLOAT_BIN_OP(v_xor, _Tpvec, __lasx_xvxor_##suffix, cast) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lasx_xvxor_##suffix(*((__m256i*)(&a.val)), not_const)); } + +OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float32x8, v, __lasx_xvreplgr2vr_w(-1), _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_FLOAT_LOGIC_OP(v_float64x4, v, __lasx_xvreplgr2vr_d(-1), _lasx_256_castsi256_pd) + +/** Select **/ +#define OPENCV_HAL_IMPL_LASX_SELECT(_Tpvec) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvbitsel_v(b.val, a.val, mask.val)); } + +OPENCV_HAL_IMPL_LASX_SELECT(v_uint8x32) +OPENCV_HAL_IMPL_LASX_SELECT(v_int8x32) +OPENCV_HAL_IMPL_LASX_SELECT(v_uint16x16) +OPENCV_HAL_IMPL_LASX_SELECT(v_int16x16) +OPENCV_HAL_IMPL_LASX_SELECT(v_uint32x8) +OPENCV_HAL_IMPL_LASX_SELECT(v_int32x8) + +inline v_float32x8 v_select(const v_float32x8 &mask, const v_float32x8 &a, const v_float32x8 &b) +{ return v_float32x8(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } + +inline v_float64x4 v_select(const v_float64x4 &mask, const v_float64x4 &a, const v_float64x4 &b) +{ return v_float64x4(__lasx_xvbitsel_v(*((__m256i*)&b.val), *((__m256i*)&a.val), *((__m256i*)&mask.val))); } + +/** Comparison **/ +#define OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpvec) \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } \ + inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ + { return v_gt(b, a); } \ + inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_lt(a, b)); } \ + inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ + { return v_ge(b, a); } + +#define OPENCV_HAL_IMPL_LASX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ + inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ + inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ + { \ + return _Tpuvec(__lasx_xvslt_##usuffix(b.val, a.val)); \ + } \ + inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ + inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lasx_xvslt_##suffix(b.val, a.val)); } \ + OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpuvec) \ + OPENCV_HAL_IMPL_LASX_CMP_OP_OV(_Tpsvec) + +OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint8x32, v_int8x32, b, bu) +OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint16x16, v_int16x16, h, hu) +OPENCV_HAL_IMPL_LASX_CMP_OP_INT(v_uint32x8, v_int32x8, w, wu) + +#define OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(_Tpvec, suffix) \ + inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_xvseq_##suffix(a.val, b.val)); } \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } + +OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_uint64x4, d) +OPENCV_HAL_IMPL_LASX_CMP_OP_64BIT(v_int64x4, d) + +#define OPENCV_HAL_IMPL_LASX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lasx_##suffix##_##ssuffix(a.val, b.val)); } + +#define OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(_Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_eq, xvfcmp_ceq, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_ne, xvfcmp_cne, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_lt, xvfcmp_clt, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LASX_CMP_FLT(v_le, xvfcmp_cle, _Tpvec, ssuffix) + +OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float32x8, s) +OPENCV_HAL_IMPL_LASX_CMP_OP_FLT(v_float64x4, d) + +inline v_float32x8 v_gt(const v_float32x8 &a, const v_float32x8 &b) +{ return v_float32x8(__lasx_xvfcmp_clt_s(b.val, a.val)); } + +inline v_float32x8 v_ge(const v_float32x8 &a, const v_float32x8 &b) +{ return v_float32x8(__lasx_xvfcmp_cle_s(b.val, a.val)); } + +inline v_float64x4 v_gt(const v_float64x4 &a, const v_float64x4 &b) +{ return v_float64x4(__lasx_xvfcmp_clt_d(b.val, a.val)); } + +inline v_float64x4 v_ge(const v_float64x4 &a, const v_float64x4 &b) +{ return v_float64x4(__lasx_xvfcmp_cle_d(b.val, a.val)); } + +inline v_float32x8 v_not_nan(const v_float32x8& a) +{ return v_float32x8(__lasx_xvfcmp_cor_s(a.val, a.val)); } +inline v_float64x4 v_not_nan(const v_float64x4& a) +{ return v_float64x4(__lasx_xvfcmp_cor_d(a.val, a.val)); } + +/** min/max **/ +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint8x32, __lasx_xvmin_bu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint8x32, __lasx_xvmax_bu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int8x32, __lasx_xvmin_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int8x32, __lasx_xvmax_b) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint16x16, __lasx_xvmin_hu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint16x16, __lasx_xvmax_hu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int16x16, __lasx_xvmin_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int16x16, __lasx_xvmax_h) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_uint32x8, __lasx_xvmin_wu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_uint32x8, __lasx_xvmax_wu) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_int32x8, __lasx_xvmin_w) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_int32x8, __lasx_xvmax_w) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float32x8, __lasx_xvfmin_s) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float32x8, __lasx_xvfmax_s) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_min, v_float64x4, __lasx_xvfmin_d) +OPENCV_HAL_IMPL_LASX_BIN_FUNC(v_max, v_float64x4, __lasx_xvfmax_d) + +/** Rotate **/ +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_R = (16 - imm) & 0xFF}; + enum {IMM_R2 = (32 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _v256_permute2x128<0x21>(a.val, b.val); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swap, IMM_R)); + return v_uint8x32(_v256_alignr_b(swap, b.val, IMM_R2)); // imm < 32 +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a, const v_uint8x32& b) +{ + enum {IMM_L = (imm - 16) & 0xFF}; + + if (imm == 0) return a; + if (imm == 32) return b; + if (imm > 32) return v_uint8x32(); + + __m256i swap = _v256_permute2x128<0x03>(a.val, b.val); + if (imm == 16) return v_uint8x32(swap); + if (imm < 16) return v_uint8x32(_v256_alignr_b(swap, a.val, imm)); + return v_uint8x32(_v256_alignr_b(b.val, swap, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_left(const v_uint8x32& a) +{ + enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; + enum {IMM_R = (16 - imm) & 0xFF}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i swapz = __lasx_xvpermi_q(a.val, vzero, 0x20);; + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_v256_alignr_b(a.val, swapz, IMM_R)); + return v_uint8x32(__lasx_xvbsll_v(swapz, IMM_L)); +} + +template +inline v_uint8x32 v_rotate_right(const v_uint8x32& a) +{ + enum {IMM_L = ((imm - 16) & 0xFF) > 31 ? 31 : ((imm - 16) & 0xFF)}; + + if (imm == 0) return a; + if (imm > 32) return v_uint8x32(); + + // ESAC control[3] ? [127:0] = 0 + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i swapz = __lasx_xvpermi_q(vzero, a.val, 0x21);; + if (imm == 16) return v_uint8x32(swapz); + if (imm < 16) return v_uint8x32(_v256_alignr_b(swapz, a.val, imm)); + return v_uint8x32(__lasx_xvbsrl_v(swapz, IMM_L)); +} + +#define OPENCV_HAL_IMPL_LASX_ROTATE_CAST(intrin, _Tpvec, cast) \ + template \ + inline _Tpvec intrin(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a), \ + v_reinterpret_as_u8(b)); \ + return _Tpvec(cast(ret.val)); \ + } \ + template \ + inline _Tpvec intrin(const _Tpvec& a) \ + { \ + enum {IMMxW = imm * sizeof(typename _Tpvec::lane_type)}; \ + v_uint8x32 ret = intrin(v_reinterpret_as_u8(a)); \ + return _Tpvec(cast(ret.val)); \ + } + +#define OPENCV_HAL_IMPL_LASX_ROTATE(_Tpvec) \ + OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, _Tpvec, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, _Tpvec, OPENCV_HAL_NOP) + +OPENCV_HAL_IMPL_LASX_ROTATE(v_int8x32) +OPENCV_HAL_IMPL_LASX_ROTATE(v_uint16x16) +OPENCV_HAL_IMPL_LASX_ROTATE(v_int16x16) +OPENCV_HAL_IMPL_LASX_ROTATE(v_uint32x8) +OPENCV_HAL_IMPL_LASX_ROTATE(v_int32x8) +OPENCV_HAL_IMPL_LASX_ROTATE(v_uint64x4) +OPENCV_HAL_IMPL_LASX_ROTATE(v_int64x4) + +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float32x8, _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float32x8, _lasx_256_castsi256_ps) +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_left, v_float64x4, _lasx_256_castsi256_pd) +OPENCV_HAL_IMPL_LASX_ROTATE_CAST(v_rotate_right, v_float64x4, _lasx_256_castsi256_pd) + +/** Reverse **/ +inline v_uint8x32 v_reverse(const v_uint8x32 &a) +{ + static const __m256i perm = _v256_setr_b( + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, + 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + __m256i vec = __lasx_xvshuf_b(a.val, a.val, perm); + return v_uint8x32(__lasx_xvpermi_q(vec, vec, 1)); +} + +inline v_int8x32 v_reverse(const v_int8x32 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x16 v_reverse(const v_uint16x16 &a) +{ + __m256i vec = __lasx_xvshuf4i_h(a.val, 0x1B); + vec = __lasx_xvshuf4i_w(vec, 0x4E); + return v_uint16x16(__lasx_xvpermi_d(vec, 0x4E)); +} + +inline v_int16x16 v_reverse(const v_int16x16 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x8 v_reverse(const v_uint32x8 &a) +{ + __m256i vec = __lasx_xvshuf4i_w(a.val, 0x1B); + return v_uint32x8(__lasx_xvpermi_d(vec, 0x4E)); +} + +inline v_int32x8 v_reverse(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x8 v_reverse(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x4 v_reverse(const v_uint64x4 &a) +{ + return v_uint64x4(__lasx_xvpermi_d(a.val, 0x1b)); +} + +inline v_int64x4 v_reverse(const v_int64x4 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x4 v_reverse(const v_float64x4 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////// Reduce and mask ///////// + +/** Reduce **/ +// this function is return a[0]+a[1]+...+a[31] +inline unsigned v_reduce_sum(const v_uint8x32& a) +{ + __m256i t1 = __lasx_xvhaddw_hu_bu(a.val, a.val); + __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); + __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); + __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); + return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); +} + +inline int v_reduce_sum(const v_int8x32& a) +{ + __m256i t1 = __lasx_xvhaddw_h_b(a.val, a.val); + __m256i t2 = __lasx_xvhaddw_w_h(t1, t1); + __m256i t3 = __lasx_xvhaddw_d_w(t2, t2); + __m256i t4 = __lasx_xvhaddw_q_d(t3, t3); + return (int)(((v8i32)t4)[0]+((v8i32)t4)[4]); +} + +#define OPENCV_HAL_IMPL_LASX_REDUCE_32(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i val = intrin(_v256_extract_low(a.val), _v256_extract_high(a.val)); \ + val = intrin(val, __lsx_vbsrl_v(val,8)); \ + val = intrin(val, __lsx_vbsrl_v(val,4)); \ + val = intrin(val, __lsx_vbsrl_v(val,2)); \ + val = intrin(val, __lsx_vbsrl_v(val,1)); \ + return (sctype)__lsx_vpickve2gr_w(val, 0); \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, min, __lsx_vmin_bu) +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, min, __lsx_vmin_b) +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_uint8x32, uchar, max, __lsx_vmax_bu) +OPENCV_HAL_IMPL_LASX_REDUCE_32(v_int8x32, schar, max, __lsx_vmax_b) + +#define OPENCV_HAL_IMPL_LASX_REDUCE_16(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 2)); \ + return (sctype) __lsx_vpickve2gr_w(v0, 0); \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, min, __lsx_vmin_hu) +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, min, __lsx_vmin_h) +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_uint16x16, ushort, max, __lsx_vmax_hu) +OPENCV_HAL_IMPL_LASX_REDUCE_16(v_int16x16, short, max, __lsx_vmax_h) + +#define OPENCV_HAL_IMPL_LASX_REDUCE_8(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i v0 = _v256_extract_low(a.val); \ + __m128i v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 8)); \ + v0 = intrin(v0, __lsx_vbsrl_v(v0, 4)); \ + return (sctype) __lsx_vpickve2gr_w(v0, 0); \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, min, __lsx_vmin_wu) +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, min, __lsx_vmin_w) +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_uint32x8, unsigned, max, __lsx_vmax_wu) +OPENCV_HAL_IMPL_LASX_REDUCE_8(v_int32x8, int, max, __lsx_vmax_w) + +#define OPENCV_HAL_IMPL_LASX_REDUCE_FLT(func, intrin) \ + inline float v_reduce_##func(const v_float32x8& a) \ + { \ + __m128 v0 = _v256_extract_low(a.val); \ + __m128 v1 = _v256_extract_high(a.val); \ + v0 = intrin(v0, v1); \ + v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x0e))); \ + v0 = intrin(v0, __m128(__lsx_vpermi_w(*((__m128i*)&v0), *((__m128i*)&v0), 0x01))); \ + float *fvalue = (float*)&v0; \ + return fvalue[0]; \ + } + +OPENCV_HAL_IMPL_LASX_REDUCE_FLT(min, __lsx_vfmin_s) +OPENCV_HAL_IMPL_LASX_REDUCE_FLT(max, __lsx_vfmax_s) + +inline int v_reduce_sum(const v_int32x8& a) +{ + __m256i t1 = __lasx_xvhaddw_d_w(a.val, a.val); + __m256i t2 = __lasx_xvhaddw_q_d(t1, t1); + return (int)(((v8i32)t2)[0]+((v8i32)t2)[4]); +} + +inline unsigned v_reduce_sum(const v_uint32x8& a) +{ return v_reduce_sum(v_reinterpret_as_s32(a)); } + +inline int v_reduce_sum(const v_int16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline unsigned v_reduce_sum(const v_uint16x16& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +inline float v_reduce_sum(const v_float32x8& a) +{ + float result = 0; + float *pa = (float*)&a; + for (int i = 0; i < 2; ++i) { + result += pa[i*4] + pa[i*4+1] + pa[i*4+2] + pa[i*4+3]; + } + return result; +} + +inline uint64 v_reduce_sum(const v_uint64x4& a) +{ + __m256i t0 = __lasx_xvhaddw_qu_du(a.val, a.val); + return (uint64)(((v4u64)t0)[0] + ((v4u64)t0)[2]); +} +inline int64 v_reduce_sum(const v_int64x4& a) +{ + __m256i t0 = __lasx_xvhaddw_q_d(a.val, a.val); + return (int64)(((v4i64)t0)[0] + ((v4i64)t0)[2]); +} +inline double v_reduce_sum(const v_float64x4& a) +{ + double *pa = (double*)&a; + return pa[0] + pa[1] + pa[2] + pa[3]; +} + +inline v_float32x8 v_reduce_sum4(const v_float32x8& a, const v_float32x8& b, + const v_float32x8& c, const v_float32x8& d) +{ + float *pa = (float*)&a; + float *pb = (float*)&b; + float *pc = (float*)&c; + float *pd = (float*)&d; + + float v0 = pa[0] + pa[1] + pa[2] + pa[3]; + float v1 = pb[0] + pb[1] + pb[2] + pb[3]; + float v2 = pc[0] + pc[1] + pc[2] + pc[3]; + float v3 = pd[0] + pd[1] + pd[2] + pd[3]; + float v4 = pa[4] + pa[5] + pa[6] + pa[7]; + float v5 = pb[4] + pb[5] + pb[6] + pb[7]; + float v6 = pc[4] + pc[5] + pc[6] + pc[7]; + float v7 = pd[4] + pd[5] + pd[6] + pd[7]; + return v_float32x8(v0, v1, v2, v3, v4, v5, v6, v7); +} + +inline unsigned v_reduce_sad(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i t0 = __lasx_xvabsd_bu(a.val, b.val); + __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); + __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); + __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); + __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); + return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); +} +inline unsigned v_reduce_sad(const v_int8x32& a, const v_int8x32& b) +{ + __m256i t0 = __lasx_xvabsd_b(a.val, b.val); + __m256i t1 = __lasx_xvhaddw_hu_bu(t0, t0); + __m256i t2 = __lasx_xvhaddw_wu_hu(t1, t1); + __m256i t3 = __lasx_xvhaddw_du_wu(t2, t2); + __m256i t4 = __lasx_xvhaddw_qu_du(t3, t3); + return (unsigned)(((v8u32)t4)[0]+((v8u32)t4)[4]); +} +inline unsigned v_reduce_sad(const v_uint16x16& a, const v_uint16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_add_wrap(v_sub(a, b), v_sub(b, a)), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x16& a, const v_int16x16& b) +{ + v_uint32x8 l, h; + v_expand(v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x8& a, const v_uint32x8& b) +{ + return v_reduce_sum(v_sub(v_max(a, b), v_min(a, b))); +} +inline unsigned v_reduce_sad(const v_int32x8& a, const v_int32x8& b) +{ + v_int32x8 m = v_lt(a, b); + return v_reduce_sum(v_reinterpret_as_u32(v_sub(v_xor(v_sub(a, b), m), m))); +} +inline float v_reduce_sad(const v_float32x8& a, const v_float32x8& b) +{ + v_float32x8 a_b = v_sub(a, b); + return v_reduce_sum(v_float32x8(*((__m256i*)&a_b.val) & __lasx_xvreplgr2vr_w(0x7fffffff))); +} + +/** Popcount **/ +inline v_uint8x32 v_popcount(const v_uint8x32& a) +{ return v_uint8x32(__lasx_xvpcnt_b(a.val)); } +inline v_uint16x16 v_popcount(const v_uint16x16& a) +{ return v_uint16x16(__lasx_xvpcnt_h(a.val)); } +inline v_uint32x8 v_popcount(const v_uint32x8& a) +{ return v_uint32x8(__lasx_xvpcnt_w(a.val)); } +inline v_uint64x4 v_popcount(const v_uint64x4& a) +{ return v_uint64x4(__lasx_xvpcnt_d(a.val)); } +inline v_uint8x32 v_popcount(const v_int8x32& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x16 v_popcount(const v_int16x16& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x8 v_popcount(const v_int32x8& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x4 v_popcount(const v_int64x4& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +inline int v_signmask(const v_int8x32& a) +{ + __m256i result = __lasx_xvmskltz_b(a.val); + int mask = __lasx_xvpickve2gr_w(result, 0); + mask |= (__lasx_xvpickve2gr_w(result, 4) << 16); + return mask; +} +inline int v_signmask(const v_uint8x32& a) +{ return v_signmask(v_reinterpret_as_s8(a)); } + +inline int v_signmask(const v_int16x16& a) +{ return v_signmask(v_pack(a, a)) & 0xFFFF; } +inline int v_signmask(const v_uint16x16& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_int32x8& a) +{ + __m256i result = __lasx_xvmskltz_w(a.val); + int mask = __lasx_xvpickve2gr_w(result, 0); + mask |= (__lasx_xvpickve2gr_w(result, 4) << 4); + return mask; +} +inline int v_signmask(const v_uint32x8& a) +{ return v_signmask(*(v_int32x8*)(&a)); } + +inline int v_signmask(const v_int64x4& a) +{ + __m256i result = __lasx_xvmskltz_d(a.val); + int mask = __lasx_xvpickve2gr_d(result, 0); + mask |= (__lasx_xvpickve2gr_w(result, 4) << 2); + return mask; +} +inline int v_signmask(const v_uint64x4& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } + +inline int v_signmask(const v_float32x8& a) +{ return v_signmask(*(v_int32x8*)(&a)); } + +inline int v_signmask(const v_float64x4& a) +{ return v_signmask(*(v_int64x4*)(&a)); } + +inline int v_scan_forward(const v_int8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x32& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +/** Checks **/ +#define OPENCV_HAL_IMPL_LASX_CHECK(_Tpvec, allmask) \ + inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ + inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } +OPENCV_HAL_IMPL_LASX_CHECK(v_uint8x32, -1) +OPENCV_HAL_IMPL_LASX_CHECK(v_int8x32, -1) +OPENCV_HAL_IMPL_LASX_CHECK(v_uint32x8, 255) +OPENCV_HAL_IMPL_LASX_CHECK(v_int32x8, 255) +OPENCV_HAL_IMPL_LASX_CHECK(v_uint64x4, 15) +OPENCV_HAL_IMPL_LASX_CHECK(v_int64x4, 15) +OPENCV_HAL_IMPL_LASX_CHECK(v_float32x8, 255) +OPENCV_HAL_IMPL_LASX_CHECK(v_float64x4, 15) + +#define OPENCV_HAL_IMPL_LASX_CHECK_SHORT(_Tpvec) \ + inline bool v_check_all(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) == 0xaaaaaaaa; } \ + inline bool v_check_any(const _Tpvec& a) { return (v_signmask(v_reinterpret_as_s8(a)) & 0xaaaaaaaa) != 0; } +OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_uint16x16) +OPENCV_HAL_IMPL_LASX_CHECK_SHORT(v_int16x16) + +////////// Other math ///////// + +/** Some frequent operations **/ +#define OPENCV_HAL_IMPL_LASX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(__lasx_xvfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(__lasx_xvfsqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_LASX_MULADD(v_float32x8, s) +OPENCV_HAL_IMPL_LASX_MULADD(v_float64x4, d) + +inline v_int32x8 v_fma(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_int32x8(__lasx_xvmadd_w(c.val, a.val, b.val)); +} + +inline v_int32x8 v_muladd(const v_int32x8& a, const v_int32x8& b, const v_int32x8& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x8 v_invsqrt(const v_float32x8& x) +{ return v_float32x8(__lasx_xvfrsqrt_s(x.val)); } + +inline v_float64x4 v_invsqrt(const v_float64x4& x) +{ return v_float64x4(__lasx_xvfrsqrt_d(x.val)); } + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_LASX_ABS(_Tpvec, suffix) \ + inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ + { return v_u##_Tpvec(__lasx_xvabsd_##suffix(x.val, __lasx_xvreplgr2vr_w(0))); } + +OPENCV_HAL_IMPL_LASX_ABS(int8x32, b) +OPENCV_HAL_IMPL_LASX_ABS(int16x16, h) +OPENCV_HAL_IMPL_LASX_ABS(int32x8, w) + +inline v_float32x8 v_abs(const v_float32x8& x) +{ return v_float32x8(*((__m256i*)&x) & __lasx_xvreplgr2vr_w(0x7fffffff)); } +inline v_float64x4 v_abs(const v_float64x4& x) +{ return v_float64x4(*((__m256i*)&x) & __lasx_xvreplgr2vr_d(0x7fffffffffffffff)); } + +/** Absolute difference **/ +inline v_uint8x32 v_absdiff(const v_uint8x32& a, const v_uint8x32& b) +{ return (v_uint8x32)__lasx_xvabsd_bu(a.val, b.val); } +inline v_uint16x16 v_absdiff(const v_uint16x16& a, const v_uint16x16& b) +{ return (v_uint16x16)__lasx_xvabsd_hu(a.val, b.val); } +inline v_uint32x8 v_absdiff(const v_uint32x8& a, const v_uint32x8& b) +{ return (v_uint32x8)__lasx_xvabsd_wu(a.val, b.val); } + +inline v_uint8x32 v_absdiff(const v_int8x32& a, const v_int8x32& b) +{ return (v_uint8x32)__lasx_xvabsd_b(a.val, b.val); } +inline v_uint16x16 v_absdiff(const v_int16x16& a, const v_int16x16& b) +{ return (v_uint16x16)__lasx_xvabsd_h(a.val, b.val); } +inline v_uint32x8 v_absdiff(const v_int32x8& a, const v_int32x8& b) +{ return (v_uint32x8)__lasx_xvabsd_w(a.val, b.val); } + +inline v_float32x8 v_absdiff(const v_float32x8& a, const v_float32x8& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x4 v_absdiff(const v_float64x4& a, const v_float64x4& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x32 v_absdiffs(const v_int8x32& a, const v_int8x32& b) +{ + v_int8x32 d = v_sub(a, b); + v_int8x32 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x16 v_absdiffs(const v_int16x16& a, const v_int16x16& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x8 v_round(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftint_w_s(a.val)); } + +inline v_int32x8 v_round(const v_float64x4& a) +{ __m256i t = __lasx_xvftint_w_d(a.val, a.val); + return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } + +inline v_int32x8 v_round(const v_float64x4& a, const v_float64x4& b) +{ + __m256i abi = __lasx_xvftint_w_d(b.val, a.val); + return v_int32x8(__lasx_xvpermi_d(abi, 0b11011000)); //3120 +} + +inline v_int32x8 v_trunc(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftintrz_w_s(a.val)); } + +inline v_int32x8 v_trunc(const v_float64x4& a) +{ __m256i t = __lasx_xvftintrz_w_d(a.val, a.val); + return v_int32x8(__lasx_xvpermi_d(t, 0x88)); } + +inline v_int32x8 v_floor(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrm_s(a.val)))); } + +inline v_int32x8 v_floor(const v_float64x4& a) +{ return v_trunc(v_float64x4(__lasx_xvfrintrm_d(a.val))); } + +inline v_int32x8 v_ceil(const v_float32x8& a) +{ return v_int32x8(__lasx_xvftintrz_w_s(__m256(__lasx_xvfrintrp_s(a.val)))); } + +inline v_int32x8 v_ceil(const v_float64x4& a) +{ return v_trunc(v_float64x4(__lasx_xvfrintrp_d(a.val))); } + +/** To float **/ +inline v_float32x8 v_cvt_f32(const v_int32x8& a) +{ return v_float32x8(__lasx_xvffint_s_w(a.val)); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a) +{ return v_float32x8(__lasx_xvpermi_d(__lasx_xvfcvt_s_d(a.val, a.val), 0x88)); } + +inline v_float32x8 v_cvt_f32(const v_float64x4& a, const v_float64x4& b) +{ + __m256 abf = __lasx_xvfcvt_s_d(a.val, b.val); //warnning: order of a,b is diff from instruction xvfcvt.s.d + return v_float32x8(__lasx_xvpermi_d(abf, 0x8D)); +} + +inline v_float64x4 v_cvt_f64(const v_int32x8& a) +{ + __m256i alow = __lasx_xvpermi_d(a.val, 0x10); + return v_float64x4(__lasx_xvffintl_d_w(alow)); +} + +inline v_float64x4 v_cvt_f64_high(const v_int32x8& a) +{ + __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); + return v_float64x4(__lasx_xvffintl_d_w(ahigh)); +} + +inline v_float64x4 v_cvt_f64(const v_float32x8& a) +{ + __m256i alow = __lasx_xvpermi_d(a.val, 0x10); + return v_float64x4(__lasx_xvfcvtl_d_s((__m256)alow)); +} + +inline v_float64x4 v_cvt_f64_high(const v_float32x8& a) +{ + __m256i ahigh = __lasx_xvpermi_d(a.val, 0x32); + return v_float64x4(__lasx_xvfcvtl_d_s((__m256)ahigh)); +} + +inline v_float64x4 v_cvt_f64(const v_int64x4& v) +{ return v_float64x4(__lasx_xvffint_d_l(v.val)); } + +////////////// Lookup table access //////////////////// + +inline v_int8x32 v256_lut(const schar* tab, const int* idx) +{ + return v_int8x32(_v256_setr_b(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], + tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], tab[idx[10]], tab[idx[11]], + tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]], tab[idx[16]], tab[idx[17]], + tab[idx[18]], tab[idx[19]], tab[idx[20]], tab[idx[21]], tab[idx[22]], tab[idx[23]], + tab[idx[24]], tab[idx[25]], tab[idx[26]], tab[idx[27]], tab[idx[28]], tab[idx[29]], + tab[idx[30]], tab[idx[31]])); +} +inline v_int8x32 v256_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x32(_v256_setr_h(*(const short*)(tab + idx[ 0]), *(const short*)(tab + idx[ 1]), *(const short*)(tab + idx[ 2]), + *(const short*)(tab + idx[ 3]), *(const short*)(tab + idx[ 4]), *(const short*)(tab + idx[ 5]), + *(const short*)(tab + idx[ 6]), *(const short*)(tab + idx[ 7]), *(const short*)(tab + idx[ 8]), + *(const short*)(tab + idx[ 9]), *(const short*)(tab + idx[10]), *(const short*)(tab + idx[11]), + *(const short*)(tab + idx[12]), *(const short*)(tab + idx[13]), *(const short*)(tab + idx[14]), + *(const short*)(tab + idx[15]))); +} +inline v_int8x32 v256_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x32(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), + *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), + *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]))); +} +inline v_uint8x32 v256_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x32 v256_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v256_lut_quads((const schar *)tab, idx)); } + +inline v_int16x16 v256_lut(const short* tab, const int* idx) +{ + return v_int16x16(_v256_setr_h(tab[idx[ 0]], tab[idx[ 1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], + tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], tab[idx[ 8]], tab[idx[ 9]], + tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], + tab[idx[15]])); +} +inline v_int16x16 v256_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x16(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), + *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), + *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); +} +inline v_int16x16 v256_lut_quads(const short* tab, const int* idx) +{ + return v_int16x16(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), + *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); + +} +inline v_uint16x16 v256_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_pairs((const short *)tab, idx)); } +inline v_uint16x16 v256_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v256_lut_quads((const short *)tab, idx)); } + +inline v_int32x8 v256_lut(const int* tab, const int* idx) +{ + return v_int32x8(_v256_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]), + *(const int*)(tab + idx[4]), *(const int*)(tab + idx[5]), + *(const int*)(tab + idx[6]), *(const int*)(tab + idx[7]) )); +} +inline v_int32x8 v256_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x8(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), + *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); +} +inline v_int32x8 v256_lut_quads(const int* tab, const int* idx) +{ + return v_int32x8(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); +} +inline v_uint32x8 v256_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_pairs((const int *)tab, idx)); } +inline v_uint32x8 v256_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v256_lut_quads((const int *)tab, idx)); } + +inline v_int64x4 v256_lut(const int64* tab, const int* idx) +{ + return v_int64x4(_v256_setr_d(*(const long long int*)(tab + idx[0]), *(const long long int*)(tab + idx[1]), + *(const long long int*)(tab + idx[2]), *(const long long int*)(tab + idx[3]) )); +} +inline v_int64x4 v256_lut_pairs(const int64* tab, const int* idx) +{ + return v_int64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); +} +inline v_uint64x4 v256_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut((const int64 *)tab, idx)); } +inline v_uint64x4 v256_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v256_lut_pairs((const int64 *)tab, idx)); } + +inline v_float32x8 v256_lut(const float* tab, const int* idx) +{ + return v_float32x8(_v256_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); +} +inline v_float32x8 v256_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_pairs((const int *)tab, idx)); } +inline v_float32x8 v256_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v256_lut_quads((const int *)tab, idx)); } + +inline v_float64x4 v256_lut(const double* tab, const int* idx) +{ + return v_float64x4(_v256_setr_pd(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_float64x4 v256_lut_pairs(const double* tab, const int* idx) +{ return v_float64x4(_v256_combine(__lsx_vld(tab + idx[0], 0), __lsx_vld(tab + idx[1], 0))); } + +inline v_int32x8 v_lut(const int* tab, const v_int32x8& idxvec) +{ + int *idx = (int*)&idxvec.val; + return v256_lut(tab, idx); +} + +inline v_uint32x8 v_lut(const unsigned* tab, const v_int32x8& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x8 v_lut(const float* tab, const v_int32x8& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v256_lut(tab, idx); +} + +inline v_float64x4 v_lut(const double* tab, const v_int32x8& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v256_lut(tab, idx); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x8& idxvec, v_float32x8& x, v_float32x8& y) +{ + const int *idx = (const int*)&idxvec.val; + __m128i xy01, xy45, xy23, xy67; + xy01 = __lsx_vld(tab + idx[0], 0); + xy01 = __lsx_vextrins_d(xy01, __lsx_vld(tab + idx[1], 0), 0x10); + xy45 = __lsx_vld(tab + idx[4], 0); + xy45 = __lsx_vextrins_d(xy45, __lsx_vld(tab + idx[5], 0), 0x10); + __m256i xy0145 = _v256_combine(xy01, xy45); + xy23 = __lsx_vld(tab + idx[2], 0); + xy23 = __lsx_vextrins_d(xy23, __lsx_vld(tab + idx[3], 0), 0x10); + xy67 = __lsx_vld(tab + idx[6], 0); + xy67 = __lsx_vextrins_d(xy67, __lsx_vld(tab + idx[7], 0), 0x10); + __m256i xy2367 = _v256_combine(xy23, xy67); + + __m256i xxyy0145 = __lasx_xvilvl_w(xy2367, xy0145); + __m256i xxyy2367 = __lasx_xvilvh_w(xy2367, xy0145); + + x = v_float32x8(__lasx_xvilvl_w(xxyy2367, xxyy0145)); + y = v_float32x8(__lasx_xvilvh_w(xxyy2367, xxyy0145)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x8& idxvec, v_float64x4& x, v_float64x4& y) +{ + //int CV_DECL_ALIGNED(32) idx[4]; + const int *idx = (const int*)&idxvec.val; + __m128i xy0 = __lsx_vld(tab + idx[0], 0); + __m128i xy2 = __lsx_vld(tab + idx[2], 0); + __m128i xy1 = __lsx_vld(tab + idx[1], 0); + __m128i xy3 = __lsx_vld(tab + idx[3], 0); + __m256i xy02 = _v256_combine(xy0, xy2); + __m256i xy13 = _v256_combine(xy1, xy3); + + x = v_float64x4(__lasx_xvilvl_d(xy13, xy02)); + y = v_float64x4(__lasx_xvilvh_d(xy13, xy02)); +} + +inline v_int8x32 v_interleave_pairs(const v_int8x32& vec) +{ + return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0d0e0c0b090a08, 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x0705060403010200))); +} +inline v_uint8x32 v_interleave_pairs(const v_uint8x32& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x32 v_interleave_quads(const v_int8x32& vec) +{ + return v_int8x32(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0b0e0a0d090c08, 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x0703060205010400))); +} +inline v_uint8x32 v_interleave_quads(const v_uint8x32& vec) +{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_interleave_pairs(const v_int16x16& vec) +{ + return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0e0b0a0d0c0908, 0x0706030205040100, 0x0f0e0b0a0d0c0908, 0x0706030205040100))); +} +inline v_uint16x16 v_interleave_pairs(const v_uint16x16& vec) +{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x16 v_interleave_quads(const v_int16x16& vec) +{ + return v_int16x16(__lasx_xvshuf_b(vec.val, vec.val, + _v256_set_d(0x0f0e07060d0c0504, 0x0b0a030209080100, 0x0f0e07060d0c0504, 0x0b0a030209080100))); +} +inline v_uint16x16 v_interleave_quads(const v_uint16x16& vec) +{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_interleave_pairs(const v_int32x8& vec) +{ + return v_int32x8(__lasx_xvshuf4i_w(vec.val, 0xd8)); +} +inline v_uint32x8 v_interleave_pairs(const v_uint32x8& vec) +{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_interleave_pairs(const v_float32x8& vec) +{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x32 v_pack_triplets(const v_int8x32& vec) +{ + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, + _v256_set_d(0x1211100f0e0d0c0a, 0x0908060504020100, 0x1211100f0e0d0c0a, 0x0908060504020100)); + return v_int8x32(__lasx_xvperm_w(t1, + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint8x32 v_pack_triplets(const v_uint8x32& vec) +{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x16 v_pack_triplets(const v_int16x16& vec) +{ + __m256i vzero = __lasx_xvreplgr2vr_w(0); + __m256i t1 = __lasx_xvshuf_b(vzero, vec.val, + _v256_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100, 0x11100f0e0d0c0b0a, 0x0908050403020100)); + return v_int16x16(__lasx_xvperm_w(t1, + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint16x16 v_pack_triplets(const v_uint16x16& vec) +{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x8 v_pack_triplets(const v_int32x8& vec) +{ + return v_int32x8(__lasx_xvperm_w(vec.val, + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} +inline v_uint32x8 v_pack_triplets(const v_uint32x8& vec) +{ return v_reinterpret_as_u32(v_pack_triplets(v_reinterpret_as_s32(vec))); } +inline v_float32x8 v_pack_triplets(const v_float32x8& vec) +{ + return v_float32x8(__lasx_xvperm_w(*(__m256i*)(&vec.val), + _v256_set_d(0x0000000700000007, 0x0000000600000005, 0x0000000400000002, 0x0000000100000000))); +} + +////////// Matrix operations ///////// + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b) +{ return v_int32x8(__lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val))); } + +inline v_int32x8 v_dotprod(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b) +{ + __m256i even = __lasx_xvmulwev_d_w(a.val, b.val); + return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); +} +inline v_int64x4 v_dotprod(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ + __m256i even = __lasx_xvmaddwev_d_w(c.val, a.val, b.val); + return v_int64x4(__lasx_xvmaddwod_d_w(even, a.val, b.val)); +} + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b) +{ + __m256i even = __lasx_xvmulwev_h_bu(a.val, b.val); + __m256i odd = __lasx_xvmulwod_h_bu(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_wu_hu(even, even); + __m256i prod1 = __lasx_xvhaddw_wu_hu(odd, odd); + return v_uint32x8(__lasx_xvadd_w(prod0, prod1)); +} +inline v_uint32x8 v_dotprod_expand(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b) +{ + __m256i even = __lasx_xvmulwev_h_b(a.val, b.val); + __m256i odd = __lasx_xvmulwod_h_b(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_w_h(even, even); + __m256i prod1 = __lasx_xvhaddw_w_h(odd, odd); + return v_int32x8(__lasx_xvadd_w(prod0, prod1)); +} +inline v_int32x8 v_dotprod_expand(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); + __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); + __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); + return v_uint64x4(__lasx_xvadd_d(prod0, prod1)); +} +inline v_uint64x4 v_dotprod_expand(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b) +{ + __m256i even = __lasx_xvmulwev_w_h(a.val, b.val); + __m256i odd = __lasx_xvmulwod_w_h(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_d_w(even, even); + __m256i prod1 = __lasx_xvhaddw_d_w(odd, odd); + return v_int64x4(__lasx_xvadd_d(prod0, prod1)); +} + +inline v_int64x4 v_dotprod_expand(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x4 v_dotprod_expand(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b) +{ return v_dotprod(a, b); } +inline v_int32x8 v_dotprod_fast(const v_int16x16& a, const v_int16x16& b, const v_int32x8& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod(a, b); } +inline v_int64x4 v_dotprod_fast(const v_int32x8& a, const v_int32x8& b, const v_int64x4& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x8 v_dotprod_expand_fast(const v_uint8x32& a, const v_uint8x32& b, const v_uint32x8& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x8 v_dotprod_expand_fast(const v_int8x32& a, const v_int8x32& b, const v_int32x8& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i even = __lasx_xvmulwev_w_hu(a.val, b.val); + __m256i odd = __lasx_xvmulwod_w_hu(a.val, b.val); + __m256i prod0 = __lasx_xvhaddw_du_wu(even, even); + __m256i prod1 = __lasx_xvhaddw_du_wu(odd, odd); + return v_uint64x4(__lasx_xvadd_d(__lasx_xvilvl_d(prod1, prod0), __lasx_xvilvh_d(prod1, prod0))); +} +inline v_uint64x4 v_dotprod_expand_fast(const v_uint16x16& a, const v_uint16x16& b, const v_uint64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b) +{ + __m256i prod = __lasx_xvadd_w(__lasx_xvmulwev_w_h(a.val, b.val), __lasx_xvmulwod_w_h(a.val, b.val)); + __m256i sign = __lasx_xvsrai_w(prod, 31); + __m256i lo = __lasx_xvilvl_w(sign, prod); + __m256i hi = __lasx_xvilvh_w(sign, prod); + return v_int64x4(__lasx_xvadd_d(lo, hi)); +} +inline v_int64x4 v_dotprod_expand_fast(const v_int16x16& a, const v_int16x16& b, const v_int64x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x4 v_dotprod_expand_fast(const v_int32x8& a, const v_int32x8& b, const v_float64x4& c) +{ return v_dotprod_expand(a, b, c); } + + +#define OPENCV_HAL_LASX_SPLAT2_PS(a, im) \ + v_float32x8(__lasx_xvpermi_w(a.val, a.val, im)) + +inline v_float32x8 v_matmul(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& m3) +{ + v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); + v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); + v_float32x8 v37 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xFF); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, v_mul(v37, m3)))); +} + +inline v_float32x8 v_matmuladd(const v_float32x8& v, const v_float32x8& m0, + const v_float32x8& m1, const v_float32x8& m2, + const v_float32x8& a) +{ + v_float32x8 v04 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0); + v_float32x8 v15 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0x55); + v_float32x8 v26 = OPENCV_HAL_LASX_SPLAT2_PS(v, 0xAA); + return v_fma(v04, m0, v_fma(v15, m1, v_fma(v26, m2, a))); +} + + +#define OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(_Tpvec, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m256i t0 = cast_from(__lasx_xvilvl_w(a1.val, a0.val)); \ + __m256i t1 = cast_from(__lasx_xvilvl_w(a3.val, a2.val)); \ + __m256i t2 = cast_from(__lasx_xvilvh_w(a1.val, a0.val)); \ + __m256i t3 = cast_from(__lasx_xvilvh_w(a3.val, a2.val)); \ + b0.val = cast_to(__lasx_xvilvl_d(t1, t0)); \ + b1.val = cast_to(__lasx_xvilvh_d(t1, t0)); \ + b2.val = cast_to(__lasx_xvilvl_d(t3, t2)); \ + b3.val = cast_to(__lasx_xvilvh_d(t3, t2)); \ + } + +OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_uint32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_LASX_TRANSPOSE4x4(v_int32x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) + +inline void v_transpose4x4(const v_float32x8 &a0, const v_float32x8 &a1, + const v_float32x8 &a2, const v_float32x8 &a3, + v_float32x8 &b0, v_float32x8 &b1, v_float32x8 &b2, v_float32x8 &b3) +{ + __m256i t0 = __lasx_xvilvl_w(__m256i(a1.val), __m256i(a0.val)); + __m256i t1 = __lasx_xvilvl_w(__m256i(a3.val), __m256i(a2.val)); + __m256i t2 = __lasx_xvilvh_w(__m256i(a1.val), __m256i(a0.val)); + __m256i t3 = __lasx_xvilvh_w(__m256i(a3.val), __m256i(a2.val)); + b0.val = __m256(__lasx_xvilvl_d(t1, t0)); + b1.val = __m256(__lasx_xvilvh_d(t1, t0)); + b2.val = __m256(__lasx_xvilvl_d(t3, t2)); + b3.val = __m256(__lasx_xvilvh_d(t3, t2)); +} + +//////////////// Value reordering /////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_LASX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(a.val); \ + b1.val = intrin(__lasx_xvpermi_q(a.val, a.val, 0x11)); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(a.val)); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin(__lasx_xvpermi_q(a.val, a.val, 0x11))); } \ + inline _Tpwvec v256_load_expand(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + return _Tpwvec(intrin(*((__m256i*)&a))); \ + } + +OPENCV_HAL_IMPL_LASX_EXPAND(v_uint8x32, v_uint16x16, uchar, __lasx_vext2xv_hu_bu) +OPENCV_HAL_IMPL_LASX_EXPAND(v_int8x32, v_int16x16, schar, __lasx_vext2xv_h_b) +OPENCV_HAL_IMPL_LASX_EXPAND(v_uint16x16, v_uint32x8, ushort, __lasx_vext2xv_wu_hu) +OPENCV_HAL_IMPL_LASX_EXPAND(v_int16x16, v_int32x8, short, __lasx_vext2xv_w_h) +OPENCV_HAL_IMPL_LASX_EXPAND(v_uint32x8, v_uint64x4, unsigned, __lasx_vext2xv_du_wu) +OPENCV_HAL_IMPL_LASX_EXPAND(v_int32x8, v_int64x4, int, __lasx_vext2xv_d_w) + +#define OPENCV_HAL_IMPL_LASX_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v256_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + return _Tpvec(intrin(*((__m256i*)&a))); \ + } + +OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_uint32x8, uchar, __lasx_vext2xv_wu_bu) +OPENCV_HAL_IMPL_LASX_EXPAND_Q(v_int32x8, schar, __lasx_vext2xv_w_b) + +/* pack */ +// 16 +inline v_int8x32 v_pack(const v_int16x16& a, const v_int16x16& b) +{ return v_int8x32(_v256_shuffle_odd_64(_lasx_packs_h(a.val, b.val))); } + +inline v_uint8x32 v_pack(const v_uint16x16& a, const v_uint16x16& b) +{ return v_uint8x32(_v256_shuffle_odd_64(__lasx_xvssrlrni_bu_h(b.val, a.val, 0))); } + +inline v_uint8x32 v_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + return v_uint8x32(_v256_shuffle_odd_64(_lasx_packus_h(a.val, b.val))); +} + +inline void v_pack_store(schar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar *ptr, const v_uint16x16& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_u_store(uchar* ptr, const v_int16x16& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x32 v_rshr_pack(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i res = __lasx_xvssrlrni_bu_h(b.val, a.val, n); + return v_uint8x32(_v256_shuffle_odd_64(res)); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x16& a) +{ + __m256i res = __lasx_xvssrlrni_bu_h(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_uint8x32 v_rshr_pack_u(const v_int16x16& a, const v_int16x16& b) +{ + __m256i res = __lasx_xvssrarni_bu_h(b.val, a.val, n); + return v_uint8x32(_v256_shuffle_odd_64(res)); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x16& a) +{ + __m256i res = __lasx_xvssrarni_bu_h(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_int8x32 v_rshr_pack(const v_int16x16& a, const v_int16x16& b) +{ + __m256i res = __lasx_xvssrarni_b_h(b.val, a.val, n); + return v_int8x32(_v256_shuffle_odd_64(res)); +} + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x16& a) +{ + __m256i res = __lasx_xvssrarni_b_h(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +// 32 +inline v_int16x16 v_pack(const v_int32x8& a, const v_int32x8& b) +{ return v_int16x16(_v256_shuffle_odd_64(_lasx_packs_w(a.val, b.val))); } + +inline v_uint16x16 v_pack(const v_uint32x8& a, const v_uint32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_v256_packs_epu32(a.val, b.val))); } + +inline v_uint16x16 v_pack_u(const v_int32x8& a, const v_int32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(_lasx_packus_w(a.val, b.val))); } + +inline void v_pack_store(short* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x8& a) +{ + __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, 0); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x8& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint16x16 v_rshr_pack(const v_uint32x8& a, const v_uint32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrlrni_hu_w(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x8& a) +{ + __m256i res = __lasx_xvssrlrni_hu_w(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_uint16x16 v_rshr_pack_u(const v_int32x8& a, const v_int32x8& b) +{ return v_uint16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_hu_w(b.val, a.val, n))); } + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x8& a) +{ + __m256i res = __lasx_xvssrarni_hu_w(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_int16x16 v_rshr_pack(const v_int32x8& a, const v_int32x8& b) +{ return v_int16x16(_v256_shuffle_odd_64(__lasx_xvssrarni_h_w(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x8& a) +{ + __m256i res = __lasx_xvssrarni_h_w(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +// 64 +// Non-saturating pack +inline v_uint32x8 v_pack(const v_uint64x4& a, const v_uint64x4& b) +{ + __m256i ab = __lasx_xvpickev_w(b.val, a.val); + return v_uint32x8(_v256_shuffle_odd_64(ab)); +} + +inline v_int32x8 v_pack(const v_int64x4& a, const v_int64x4& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + __m256i a0 = __lasx_xvshuf4i_w(a.val, 0x08); + v_store_low(ptr, v_uint32x8(_v256_shuffle_odd_64(a0))); +} + +inline void v_pack_store(int* ptr, const v_int64x4& b) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(b)); } + +template inline +v_uint32x8 v_rshr_pack(const v_uint64x4& a, const v_uint64x4& b) +{ return v_uint32x8(_v256_shuffle_odd_64(__lasx_xvsrlrni_w_d(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x4& a) +{ + __m256i res = __lasx_xvsrlrni_w_d(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +template inline +v_int32x8 v_rshr_pack(const v_int64x4& a, const v_int64x4& b) +{ return v_int32x8(_v256_shuffle_odd_64(__lasx_xvsrarni_w_d(b.val, a.val, n))); } + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x4& a) +{ + __m256i res = __lasx_xvsrarni_w_d(a.val, a.val, n); + __lasx_xvstelm_d(res, ptr, 0, 0); + __lasx_xvstelm_d(res, ptr, 8, 2); +} + +// pack boolean +inline v_uint8x32 v_pack_b(const v_uint16x16& a, const v_uint16x16& b) +{ + __m256i ab = _lasx_packs_h(a.val, b.val); + return v_uint8x32(_v256_shuffle_odd_64(ab)); +} + +inline v_uint8x32 v_pack_b(const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d) +{ + __m256i ab = _lasx_packs_w(a.val, b.val); + __m256i cd = _lasx_packs_w(c.val, d.val); + + __m256i abcd = _v256_shuffle_odd_64(_lasx_packs_h(ab, cd)); + return v_uint8x32(__lasx_xvshuf4i_w(abcd, 0xd8)); +} + +inline v_uint8x32 v_pack_b(const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + const v_uint64x4& d, const v_uint64x4& e, const v_uint64x4& f, + const v_uint64x4& g, const v_uint64x4& h) +{ + __m256i ab = _lasx_packs_w(a.val, b.val); + __m256i cd = _lasx_packs_w(c.val, d.val); + __m256i ef = _lasx_packs_w(e.val, f.val); + __m256i gh = _lasx_packs_w(g.val, h.val); + + __m256i abcd = _lasx_packs_w(ab, cd); + __m256i efgh = _lasx_packs_w(ef, gh); + __m256i pkall = _v256_shuffle_odd_64(_lasx_packs_h(abcd, efgh)); + + __m256i rev = _v256_alignr_b(pkall, pkall, 8); + return v_uint8x32(__lasx_xvilvl_h(rev, pkall)); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_LASX_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint8x32) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int8x32) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint16x16) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int16x16) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint32x8) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int32x8) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_uint64x4) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_int64x4) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_float32x8) +OPENCV_HAL_IMPL_LASX_EXTRACT(v_float64x4) + +template +inline uchar v_extract_n(v_uint8x32 a) +{ + return (uchar)_v256_extract_b(a.val); +} + +template +inline schar v_extract_n(v_int8x32 a) +{ + return (schar)v_extract_n(v_reinterpret_as_u8(a)); +} + +template +inline ushort v_extract_n(v_uint16x16 a) +{ + return (ushort)_v256_extract_h(a.val); +} + +template +inline short v_extract_n(v_int16x16 a) +{ + return (short)v_extract_n(v_reinterpret_as_u16(a)); +} + +template +inline uint v_extract_n(v_uint32x8 a) +{ + return (uint)_v256_extract_w(a.val); +} + +template +inline int v_extract_n(v_int32x8 a) +{ + return (int)v_extract_n(v_reinterpret_as_u32(a)); +} + +template +inline uint64 v_extract_n(v_uint64x4 a) +{ + return (uint64)_v256_extract_d(a.val); +} + +template +inline int64 v_extract_n(v_int64x4 v) +{ + return (int64)v_extract_n(v_reinterpret_as_u64(v)); +} + +template +inline float v_extract_n(v_float32x8 v) +{ + union { uint iv; float fv; } d; + d.iv = v_extract_n(v_reinterpret_as_u32(v)); + return d.fv; +} + +template +inline double v_extract_n(v_float64x4 v) +{ + union { uint64 iv; double dv; } d; + d.iv = v_extract_n(v_reinterpret_as_u64(v)); + return d.dv; +} + +template +inline v_uint32x8 v_broadcast_element(v_uint32x8 a) +{ + static const __m256i perm = __lasx_xvreplgr2vr_w((char)i); + return v_uint32x8(__lasx_xvperm_w(a.val, perm)); +} + +template +inline v_int32x8 v_broadcast_element(const v_int32x8 &a) +{ return v_reinterpret_as_s32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +template +inline v_float32x8 v_broadcast_element(const v_float32x8 &a) +{ return v_reinterpret_as_f32(v_broadcast_element(v_reinterpret_as_u32(a))); } + +///////////////////// load deinterleave ///////////////////////////// + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + + __m256i p0 = __lasx_xvpickev_b(t1, t0); + __m256i p1 = __lasx_xvpickod_b(t1, t0); + + a.val = __lasx_xvpermi_d(p0, 0xd8); + b.val = __lasx_xvpermi_d(p1, 0xd8); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b ) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + + __m256i p0 = __lasx_xvpickev_h(t1, t0); + __m256i p1 = __lasx_xvpickod_h(t1, t0); + + a.val = __lasx_xvpermi_d(p0, 0xd8); + b.val = __lasx_xvpermi_d(p1, 0xd8); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b ) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + + __m256i p0 = __lasx_xvpickev_w(t1, t0); + __m256i p1 = __lasx_xvpickod_w(t1, t0); + + a.val = __lasx_xvpermi_d(p0, 0xd8); + b.val = __lasx_xvpermi_d(p1, 0xd8); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b ) +{ + __m256i ab0 = __lasx_xvld(ptr, 0); + __m256i ab1 = __lasx_xvld(ptr, 32); + + __m256i pl = __lasx_xvpermi_q(ab0, ab1, 0x02); + __m256i ph = __lasx_xvpermi_q(ab0, ab1, 0x13); + __m256i a0 = __lasx_xvilvl_d(ph, pl); + __m256i b0 = __lasx_xvilvh_d(ph, pl); + a = v_uint64x4(a0); + b = v_uint64x4(b0); +} + +inline void v_load_deinterleave( const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); + __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); + + const __m256i m0 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1); + + __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); + __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); + + const __m256i + sh_b = _v256_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, + 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13), + sh_g = _v256_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, + 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14), + sh_r = _v256_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, + 2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); + b0 = __lasx_xvshuf_b(b0, b0, sh_b); + g0 = __lasx_xvshuf_b(g0, g0, sh_g); + r0 = __lasx_xvshuf_b(r0, r0, sh_r); + + a = v_uint8x32(b0); + b = v_uint8x32(g0); + c = v_uint8x32(r0); +} + +inline void v_load_deinterleave( const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); + __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); + + const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m0), bgr1, m1); + __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m0), s02_high, m1); + __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m1), bgr1, m0); + const __m256i sh_b = _v256_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _v256_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, + 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); + const __m256i sh_r = _v256_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + b0 = __lasx_xvshuf_b(b0, b0, sh_b); + g0 = __lasx_xvshuf_b(g0, g0, sh_g); + r0 = __lasx_xvshuf_b(r0, r0, sh_r); + + a = v_uint16x16(b0); + b = v_uint16x16(g0); + c = v_uint16x16(r0); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s02_low = __lasx_xvpermi_q(bgr0, bgr2, 0x02); + __m256i s02_high = __lasx_xvpermi_q(bgr0, bgr2, 0x13); + + __m256i m24 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); + __m256i m92 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); + __m256i b0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_low, s02_high, m24), bgr1, m92); + __m256i g0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(s02_high, s02_low, m92), bgr1, m24); + __m256i r0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(bgr1, s02_low, m24), s02_high, m92); + + b0 = __lasx_xvshuf4i_w(b0, 0x6c); + g0 = __lasx_xvshuf4i_w(g0, 0xb1); + r0 = __lasx_xvshuf4i_w(r0, 0xc6); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c ) +{ + __m256i bgr0 = __lasx_xvld(ptr, 0); + __m256i bgr1 = __lasx_xvld(ptr, 32); + __m256i bgr2 = __lasx_xvld(ptr, 64); + + __m256i s01 = __lasx_xvpermi_q(bgr0, bgr1, 0x12); // get bgr0 low 128 and bgr1 high 128 + __m256i s12 = __lasx_xvpermi_q(bgr1, bgr2, 0x12); + __m256i s20r = __lasx_xvpermi_d(__lasx_xvpermi_q(bgr2, bgr0, 0x12), 0x1b); + __m256i b0 = __lasx_xvilvl_d(s20r, s01); + __m256i g0 = _v256_alignr_b(s12, s01, 8); + __m256i r0 = __lasx_xvilvh_d(s12, s20r); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x32& a, v_uint8x32& b, v_uint8x32& c, v_uint8x32& d) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + __m256i t2 = __lasx_xvld(ptr, 64); + __m256i t3 = __lasx_xvld(ptr, 96); + + const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); + __m256i ac_lo = __lasx_xvpickev_b(t1, t0); + __m256i bd_lo = __lasx_xvpickod_b(t1, t0); + __m256i ac_hi = __lasx_xvpickev_b(t3, t2); + __m256i bd_hi = __lasx_xvpickod_b(t3, t2); + + __m256i a_pre = __lasx_xvpickev_b(ac_hi, ac_lo); + __m256i c_pre = __lasx_xvpickod_b(ac_hi, ac_lo); + __m256i b_pre = __lasx_xvpickev_b(bd_hi, bd_lo); + __m256i d_pre = __lasx_xvpickod_b(bd_hi, bd_lo); + + a.val = __lasx_xvperm_w(a_pre, sh); + b.val = __lasx_xvperm_w(b_pre, sh); + c.val = __lasx_xvperm_w(c_pre, sh); + d.val = __lasx_xvperm_w(d_pre, sh); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x16& a, v_uint16x16& b, v_uint16x16& c, v_uint16x16& d) +{ + __m256i t0 = __lasx_xvld(ptr, 0); + __m256i t1 = __lasx_xvld(ptr, 32); + __m256i t2 = __lasx_xvld(ptr, 64); + __m256i t3 = __lasx_xvld(ptr, 96); + + const __m256i sh = _v256_setr_w(0, 4, 1, 5, 2, 6, 3, 7); + __m256i ac_lo = __lasx_xvpickev_h(t1, t0); + __m256i bd_lo = __lasx_xvpickod_h(t1, t0); + __m256i ac_hi = __lasx_xvpickev_h(t3, t2); + __m256i bd_hi = __lasx_xvpickod_h(t3, t2); + + __m256i a_pre = __lasx_xvpickev_h(ac_hi, ac_lo); + __m256i c_pre = __lasx_xvpickod_h(ac_hi, ac_lo); + __m256i b_pre = __lasx_xvpickev_h(bd_hi, bd_lo); + __m256i d_pre = __lasx_xvpickod_h(bd_hi, bd_lo); + + a.val = __lasx_xvperm_w(a_pre, sh); + b.val = __lasx_xvperm_w(b_pre, sh); + c.val = __lasx_xvperm_w(c_pre, sh); + d.val = __lasx_xvperm_w(d_pre, sh); +} + +inline void v_load_deinterleave( const unsigned* ptr, v_uint32x8& a, v_uint32x8& b, v_uint32x8& c, v_uint32x8& d ) +{ + __m256i p0 = __lasx_xvld(ptr, 0); + __m256i p1 = __lasx_xvld(ptr, 32); + __m256i p2 = __lasx_xvld(ptr, 64); + __m256i p3 = __lasx_xvld(ptr, 96); + + __m256i p01l = __lasx_xvilvl_w(p1, p0); + __m256i p01h = __lasx_xvilvh_w(p1, p0); + __m256i p23l = __lasx_xvilvl_w(p3, p2); + __m256i p23h = __lasx_xvilvh_w(p3, p2); + + __m256i pll = __lasx_xvpermi_q(p01l, p23l, 0x02); + __m256i plh = __lasx_xvpermi_q(p01l, p23l, 0x13); + __m256i phl = __lasx_xvpermi_q(p01h, p23h, 0x02); + __m256i phh = __lasx_xvpermi_q(p01h, p23h, 0x13); + + __m256i b0 = __lasx_xvilvl_w(plh, pll); + __m256i g0 = __lasx_xvilvh_w(plh, pll); + __m256i r0 = __lasx_xvilvl_w(phh, phl); + __m256i a0 = __lasx_xvilvh_w(phh, phl); + + a = v_uint32x8(b0); + b = v_uint32x8(g0); + c = v_uint32x8(r0); + d = v_uint32x8(a0); +} + +inline void v_load_deinterleave( const uint64* ptr, v_uint64x4& a, v_uint64x4& b, v_uint64x4& c, v_uint64x4& d ) +{ + __m256i bgra0 = __lasx_xvld(ptr, 0); + __m256i bgra1 = __lasx_xvld(ptr, 32); + __m256i bgra2 = __lasx_xvld(ptr, 64); + __m256i bgra3 = __lasx_xvld(ptr, 96); + + __m256i l02 = __lasx_xvpermi_q(bgra0, bgra2, 0x02); + __m256i h02 = __lasx_xvpermi_q(bgra0, bgra2, 0x13); + __m256i l13 = __lasx_xvpermi_q(bgra1, bgra3, 0x02); + __m256i h13 = __lasx_xvpermi_q(bgra1, bgra3, 0x13); + + __m256i b0 = __lasx_xvilvl_d(l13, l02); + __m256i g0 = __lasx_xvilvh_d(l13, l02); + __m256i r0 = __lasx_xvilvl_d(h13, h02); + __m256i a0 = __lasx_xvilvh_d(h13, h02); + + a = v_uint64x4(b0); + b = v_uint64x4(g0); + c = v_uint64x4(r0); + d = v_uint64x4(a0); +} + +///////////////////////////// store interleave ///////////////////////////////////// + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& x, const v_uint8x32& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_b(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_b(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 32*1); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& x, const v_uint16x16& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_h(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_h(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 16*2); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& x, const v_uint32x8& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_w(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_w(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 8*4); +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& x, const v_uint64x4& y, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i xy_l = __lasx_xvilvl_d(y.val, x.val); + __m256i xy_h = __lasx_xvilvh_d(y.val, x.val); + + __m256i xy0 = __lasx_xvpermi_q(xy_h, xy_l, 0 + 2*16); + __m256i xy1 = __lasx_xvpermi_q(xy_h, xy_l, 1 + 3*16); + + __lasx_xvst(xy0, (__m256i*)ptr, 0); + __lasx_xvst(xy1, (__m256i*)ptr, 4*8); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, const v_uint8x32& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _v256_setr_b( + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, + 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); + const __m256i sh_g = _v256_setr_b( + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, + 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); + const __m256i sh_r = _v256_setr_b( + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, + 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); + + __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); + __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); + __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); + + const __m256i m0 = _v256_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, + 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + const __m256i m1 = _v256_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, + 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + + __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); + __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); + __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); + + __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); + __m256i bgr1 = __lasx_xvpermi_q(p0, p2, 0 + 3*16); + __m256i bgr2 = __lasx_xvpermi_q(p2, p1, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(bgr1, (__m256i*)ptr, 32); + __lasx_xvst(bgr2, (__m256i*)ptr, 64); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, const v_uint16x16& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + const __m256i sh_b = _v256_setr_b( + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11, + 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m256i sh_g = _v256_setr_b( + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, + 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); + const __m256i sh_r = _v256_setr_b( + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, + 4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + + __m256i b0 = __lasx_xvshuf_b(a.val, a.val, sh_b); + __m256i g0 = __lasx_xvshuf_b(b.val, b.val, sh_g); + __m256i r0 = __lasx_xvshuf_b(c.val, c.val, sh_r); + + const __m256i m0 = _v256_setr_b(0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, + 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0); + const __m256i m1 = _v256_setr_b(0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, + -1, -1, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, -1, -1, 0, 0); + + __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, m0), r0, m1); + __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, m0), b0, m1); + __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, m0), g0, m1); + + __m256i bgr0 = __lasx_xvpermi_q(p2, p0, 0 + 2*16); + __m256i bgr2 = __lasx_xvpermi_q(p2, p0, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(p1, (__m256i*)ptr, 16*2); + __lasx_xvst(bgr2, (__m256i*)ptr, 32*2); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, const v_uint32x8& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i b0 = __lasx_xvshuf4i_w(a.val, 0x6c); + __m256i g0 = __lasx_xvshuf4i_w(b.val, 0xb1); + __m256i r0 = __lasx_xvshuf4i_w(c.val, 0xc6); + + __m256i bitmask_1 = _v256_set_w(-1, 0, 0, -1, 0, 0, -1, 0); + __m256i bitmask_2 = _v256_set_w(0, 0, -1, 0, 0, -1, 0, 0); + + __m256i p0 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(b0, g0, bitmask_1), r0, bitmask_2); + __m256i p1 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(g0, r0, bitmask_1), b0, bitmask_2); + __m256i p2 = __lasx_xvbitsel_v(__lasx_xvbitsel_v(r0, b0, bitmask_1), g0, bitmask_2); + + __m256i bgr0 = __lasx_xvpermi_q(p1, p0, 0 + 2*16); + __m256i bgr2 = __lasx_xvpermi_q(p1, p0, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(p2, (__m256i*)ptr, 8*4); + __lasx_xvst(bgr2, (__m256i*)ptr, 16*4); +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, const v_uint64x4& c, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i s01 = __lasx_xvilvl_d(b.val, a.val); + __m256i s12 = __lasx_xvilvh_d(c.val, b.val); + __m256i s20 = __lasx_xvpermi_w(a.val, c.val, 0xe4); + + __m256i bgr0 = __lasx_xvpermi_q(s20, s01, 0 + 2*16); + __m256i bgr1 = __lasx_xvpermi_q(s01, s12, 0x30); + __m256i bgr2 = __lasx_xvpermi_q(s12, s20, 1 + 3*16); + + __lasx_xvst(bgr0, (__m256i*)ptr, 0); + __lasx_xvst(bgr1, (__m256i*)ptr, 4*8); + __lasx_xvst(bgr2, (__m256i*)ptr, 8*8); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x32& a, const v_uint8x32& b, + const v_uint8x32& c, const v_uint8x32& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_b(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_b(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_b(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_b(d.val, c.val); + + __m256i bgra0_ = __lasx_xvilvl_h(ra0, bg0); + __m256i bgra1_ = __lasx_xvilvh_h(ra0, bg0); + __m256i bgra2_ = __lasx_xvilvl_h(ra1, bg1); + __m256i bgra3_ = __lasx_xvilvh_h(ra1, bg1); + + __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); + __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); + __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)ptr, 32); + __lasx_xvst(bgra2, (__m256i*)ptr, 64); + __lasx_xvst(bgra3, (__m256i*)ptr, 96); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x16& a, const v_uint16x16& b, + const v_uint16x16& c, const v_uint16x16& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_h(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_h(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_h(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_h(d.val, c.val); + + __m256i bgra0_ = __lasx_xvilvl_w(ra0, bg0); + __m256i bgra1_ = __lasx_xvilvh_w(ra0, bg0); + __m256i bgra2_ = __lasx_xvilvl_w(ra1, bg1); + __m256i bgra3_ = __lasx_xvilvh_w(ra1, bg1); + + __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); + __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); + __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)ptr, 16*2); + __lasx_xvst(bgra2, (__m256i*)ptr, 32*2); + __lasx_xvst(bgra3, (__m256i*)ptr, 48*2); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x8& a, const v_uint32x8& b, + const v_uint32x8& c, const v_uint32x8& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_w(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_w(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_w(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_w(d.val, c.val); + + __m256i bgra0_ = __lasx_xvilvl_d(ra0, bg0); + __m256i bgra1_ = __lasx_xvilvh_d(ra0, bg0); + __m256i bgra2_ = __lasx_xvilvl_d(ra1, bg1); + __m256i bgra3_ = __lasx_xvilvh_d(ra1, bg1); + + __m256i bgra0 = __lasx_xvpermi_q(bgra1_, bgra0_, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(bgra1_, bgra0_, 1 + 3*16); + __m256i bgra1 = __lasx_xvpermi_q(bgra3_, bgra2_, 0 + 2*16); + __m256i bgra3 = __lasx_xvpermi_q(bgra3_, bgra2_, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)ptr, 8*4); + __lasx_xvst(bgra2, (__m256i*)ptr, 16*4); + __lasx_xvst(bgra3, (__m256i*)ptr, 24*4); +} + +inline void v_store_interleave( uint64* ptr, const v_uint64x4& a, const v_uint64x4& b, + const v_uint64x4& c, const v_uint64x4& d, + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) +{ + __m256i bg0 = __lasx_xvilvl_d(b.val, a.val); + __m256i bg1 = __lasx_xvilvh_d(b.val, a.val); + __m256i ra0 = __lasx_xvilvl_d(d.val, c.val); + __m256i ra1 = __lasx_xvilvh_d(d.val, c.val); + + __m256i bgra0 = __lasx_xvpermi_q(ra0, bg0, 0 + 2*16); + __m256i bgra1 = __lasx_xvpermi_q(ra1, bg1, 0 + 2*16); + __m256i bgra2 = __lasx_xvpermi_q(ra0, bg0, 1 + 3*16); + __m256i bgra3 = __lasx_xvpermi_q(ra1, bg1, 1 + 3*16); + + __lasx_xvst(bgra0, (__m256i*)ptr, 0); + __lasx_xvst(bgra1, (__m256i*)(ptr), 4*8); + __lasx_xvst(bgra2, (__m256i*)(ptr), 8*8); + __lasx_xvst(bgra3, (__m256i*)(ptr), 12*8); +} + + +#define OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1/*, mode*/); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1/*, mode*/); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1/*, mode*/); \ +} + +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int8x32, schar, s8, v_uint8x32, uchar, u8) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int16x16, short, s16, v_uint16x16, ushort, u16) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int32x8, int, s32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float32x8, float, f32, v_uint32x8, unsigned, u32) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_int64x4, int64, s64, v_uint64x4, uint64, u64) +OPENCV_HAL_IMPL_LASX_LOADSTORE_INTERLEAVE(v_float64x4, double, f64, v_uint64x4, uint64, u64) + +// +// FP16 +// + +inline v_float32x8 v256_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + //1-load128, 2-permi, 3-cvt + return v_float32x8(__lasx_xvfcvtl_s_h(__lasx_xvpermi_d(__lsx_vld((const __m128i*)ptr, 0), 0x10))); +#else + float CV_DECL_ALIGNED(32) buf[8]; + for (int i = 0; i < 8; i++) + buf[i] = (float)ptr[i]; + return v256_load_aligned(buf); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x8& a) +{ +#if CV_FP16 + __m256i ah = __lasx_xvfcvt_h_s(a.val, a.val); + __lsx_vst((_m128i)ah, ptr, 0); +#else + float CV_DECL_ALIGNED(32) buf[8]; + v_store_aligned(buf, a); + for (int i = 0; i < 8; i++) + ptr[i] = hfloat(buf[i]); +#endif +} + +// +// end of FP16 +// + +inline void v256_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x8 v_exp(const v_float32x8& x) { return v_exp_default_32f(x); } +inline v_float32x8 v_log(const v_float32x8& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x8& x, v_float32x8& s, v_float32x8& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x8 v_sin(const v_float32x8& x) { return v_sin_default_32f(x); } +inline v_float32x8 v_cos(const v_float32x8& x) { return v_cos_default_32f(x); } +inline v_float32x8 v_erf(const v_float32x8& x) { return v_erf_default_32f(x); } + +inline v_float64x4 v_exp(const v_float64x4& x) { return v_exp_default_64f(x); } +inline v_float64x4 v_log(const v_float64x4& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x4& x, v_float64x4& s, v_float64x4& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x4 v_sin(const v_float64x4& x) { return v_sin_default_64f(x); } +inline v_float64x4 v_cos(const v_float64x4& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_LASX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp index e89c9e5a47..a2f23d6abe 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_lsx.hpp @@ -1,2546 +1,2546 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_LSX_HPP -#define OPENCV_HAL_INTRIN_LSX_HPP - -#include - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#define CV_SIMD128_FP16 0 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -/////////// Utils //////// - -inline __m128i _v128_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, - char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) -{ - return (__m128i)v16i8{ v0, v1, v2, v3, v4, v5, v6, v7, - v8, v9, v10, v11, v12, v13, v14, v15 }; -} - -inline __m128i _v128_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, - char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) -{ - return (__m128i)v16i8{ v15, v14, v13, v12, v11, v10, v9, v8, - v7, v6, v5, v4, v3, v2, v1, v0 }; -} - -inline __m128i _v128_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, - short v6, short v7) -{ - return (__m128i)v8i16{ v0, v1, v2, v3, v4, v5, v6, v7 }; -} - -inline __m128i _v128_setr_w(int v0, int v1, int v2, int v3) -{ - return (__m128i)v4i32{ v0, v1, v2, v3 }; -} - -inline __m128i _v128_set_w(int v0, int v1, int v2, int v3) -{ - return (__m128i)v4i32{ v3, v2, v1, v0 }; -} - -inline __m128i _v128_setall_w(int v0) -{ - return __lsx_vreplgr2vr_w(v0); -} - -inline __m128i _v128_setr_d(int64 v0, int64 v1) -{ - return (__m128i)v2i64{ v0, v1 }; -} - -inline __m128i _v128_set_d(int64 v0, int64 v1) -{ - return (__m128i)v2i64{ v1, v0 }; -} - -inline __m128 _v128_setr_ps(float v0, float v1, float v2, float v3) -{ - return (__m128)v4f32{ v0, v1, v2, v3 }; -} - -inline __m128 _v128_setall_ps(float v0) -{ - return (__m128)v4f32{ v0, v0, v0, v0 }; -} - -inline __m128d _v128_setr_pd(double v0, double v1) -{ - return (__m128d)v2f64{ v0, v1 }; -} - -inline __m128d _v128_setall_pd(double v0) -{ - return (__m128d)v2f64{ v0, v0 }; -} - -inline __m128i _lsx_packus_h(const __m128i& a, const __m128i& b) -{ - return __lsx_vssrarni_bu_h(b, a, 0); -} - -inline __m128i _lsx_packs_h(const __m128i& a, const __m128i& b) -{ - return __lsx_vssrarni_b_h(b, a, 0); -} - -inline __m128i _lsx_packus_w(const __m128i& a, const __m128i& b) -{ - return __lsx_vssrarni_hu_w(b, a, 0); -} - -/////// Types /////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16}; - - v_uint8x16() {} - explicit v_uint8x16(__m128i v): val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - - uchar get0() const - { - return (uchar)__lsx_vpickve2gr_bu(val, 0); - } - - __m128i val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(__m128i v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); - } - - schar get0() const - { - return (schar)__lsx_vpickve2gr_b(val, 0); - } - - __m128i val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(__m128i v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); - } - - ushort get0() const - { - return (ushort)__lsx_vpickve2gr_hu(val, 0); - } - - __m128i val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(__m128i v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); - } - - short get0() const - { - return (short)__lsx_vpickve2gr_h(val, 0); - } - - __m128i val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(__m128i v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - val = _v128_setr_w(v0, v1, v2, v3); - } - - unsigned get0() const - { - return (unsigned)__lsx_vpickve2gr_wu(val, 0); - } - - __m128i val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(__m128i v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - val = _v128_setr_w(v0, v1, v2, v3); - } - - int get0() const - { - return (int)__lsx_vpickve2gr_w(val, 0); - } - - __m128i val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4}; - - v_float32x4() {} - explicit v_float32x4(__m128 v) : val(v) {} - explicit v_float32x4(__m128i v) { val = *((__m128*)&v); } - v_float32x4(float v0, float v1, float v2, float v3) - { - val = _v128_setr_ps(v0, v1, v2, v3); - } - - float get0() const - { - union { int iv; float fv; } d; - d.iv = __lsx_vpickve2gr_w(val, 0); - return d.fv; - } - - int get0toint() const - { - __m128i result = __lsx_vftintrz_w_s(val); - return (int)__lsx_vpickve2gr_w(result, 0); - } - - __m128 val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2}; - - v_uint64x2() {} - explicit v_uint64x2(__m128i v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - val = _v128_setr_d(v0, v1); - } - - uint64 get0() const - { - return __lsx_vpickve2gr_du(val, 0); - } - - __m128i val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2}; - - v_int64x2() {} - explicit v_int64x2(__m128i v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - val = _v128_setr_d(v0, v1); - } - - uint64 get0() const - { - return __lsx_vpickve2gr_d(val, 0); - } - - __m128i val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2}; - - v_float64x2() {} - explicit v_float64x2(__m128d v) : val(v) {} - explicit v_float64x2(__m128i v) { val = *((__m128d*)&v); } - v_float64x2(double v0, double v1) - { - val = _v128_setr_pd(v0, v1); - } - - double get0() const - { - union { int64 iv; double fv; } d; - d.iv = __lsx_vpickve2gr_d(val, 0); - return d.fv; - } - - int64 get0toint64() const - { - __m128i result = __lsx_vftintrz_l_d(val); - return (int64)__lsx_vpickve2gr_d(result, 0); - } - - __m128d val; -}; - -////////////// Load and store operations ///////// - -#define OPENCV_HAL_IMPL_LSX_LOADSTORE(_Tpvec, _Tp) \ - inline _Tpvec v_load(const _Tp* ptr) \ - { return _Tpvec(__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_aligned(const _Tp* ptr) \ - { return _Tpvec(__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_low(const _Tp* ptr) \ - { return _Tpvec(__lsx_vldrepl_d(ptr, 0)); } \ - inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ - __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ - return _Tpvec(__lsx_vilvl_d(vh, vl)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst(a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ - { \ - if ( mode == hal::STORE_UNALIGNED) \ - __lsx_vst(a.val, ptr, 0); \ - else if ( mode == hal::STORE_ALIGNED_NOCACHE) \ - __lsx_vst(a.val, ptr, 0); \ - else \ - __lsx_vst(a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d(a.val, ptr, 0, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d(a.val, ptr, 0, 1); } \ - -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint8x16, uchar) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int8x16, schar) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint16x8, ushort) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int16x8, short) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint32x4, unsigned) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int32x4, int) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint64x2, uint64) -OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int64x2, int64) - -#define OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ - inline _Tpvec v_load(const _Tp* ptr) \ - { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_aligned(const _Tp* ptr) \ - { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ - inline _Tpvec v_load_low(const _Tp* ptr) \ - { return _Tpvec((halfreg)__lsx_vldrepl_d(ptr, 0)); } \ - inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ - { \ - __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ - __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ - return _Tpvec((halfreg)__lsx_vilvl_d(vh, vl)); \ - } \ - inline void v_store(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst((__m128i)a.val, ptr, 0); } \ - inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst((__m128i)a.val, ptr, 0); } \ - inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vst((__m128i)a.val, ptr, 0); } \ - inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ - { \ - if( mode == hal::STORE_UNALIGNED) \ - __lsx_vst((__m128i)a.val, ptr, 0); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE) \ - __lsx_vst((__m128i)a.val, ptr, 0); \ - else \ - __lsx_vst((__m128i)a.val, ptr, 0); \ - } \ - inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 0); } \ - inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ - { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 1); } \ - -OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float32x4, float, __m128) -OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float64x2, double, __m128d) - -inline __m128i _lsx_128_castps_si128(const __m128& v) -{ return __m128i(v); } - -inline __m128i _lsx_128_castpd_si128(const __m128d& v) -{ return __m128i(v); } - -#define OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ - inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ - { return _Tpvec(cast(a.val)); } - -#define OPENCV_HAL_IMPL_LSX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ - inline _Tpvec v_setzero_##suffix() \ - { return _Tpvec(__lsx_vldi(0)); } \ - inline _Tpvec v_setall_##suffix(_Tp v) \ - { return _Tpvec(__lsx_vreplgr2vr_##ssuffix((ctype_s)v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, OPENCV_HAL_NOP) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float32x4, suffix, _lsx_128_castps_si128) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float64x2, suffix, _lsx_128_castpd_si128) \ - -OPENCV_HAL_IMPL_LSX_INIT(v_uint8x16, uchar, u8, b, int) -OPENCV_HAL_IMPL_LSX_INIT(v_int8x16, schar, s8, b, int) -OPENCV_HAL_IMPL_LSX_INIT(v_uint16x8, ushort, u16, h, int) -OPENCV_HAL_IMPL_LSX_INIT(v_int16x8, short, s16, h, int) -OPENCV_HAL_IMPL_LSX_INIT(v_uint32x4, unsigned, u32, w, int) -OPENCV_HAL_IMPL_LSX_INIT(v_int32x4, int, s32, w, int) -OPENCV_HAL_IMPL_LSX_INIT(v_uint64x2, uint64, u64, d, long int) -OPENCV_HAL_IMPL_LSX_INIT(v_int64x2, int64, s64, d, long int) - -inline __m128 _lsx_128_castsi128_ps(const __m128i &v) -{ return __m128(v); } - -inline __m128d _lsx_128_castsi128_pd(const __m128i &v) -{ return __m128d(v); } - -#define OPENCV_HAL_IMPL_LSX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ - inline _Tpvec v_setzero_##suffix() \ - { return _Tpvec(__lsx_vldi(0)); } \ - inline _Tpvec v_setall_##suffix(_Tp v) \ - { return _Tpvec(_v128_setall_##zsuffix(v)); } \ - template <> inline _Tpvec v_setzero_() \ - { return v_setzero_##suffix(); } \ - template <> inline _Tpvec v_setall_(_Tp v) \ - { return v_setall_##suffix(v); } \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, cast) \ - OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, cast) \ - -OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float32x4, float, f32, ps, _lsx_128_castsi128_ps) -OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float64x2, double, f64, pd, _lsx_128_castsi128_pd) - -inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) -{ return a; } -inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) -{ return v_float32x4(_lsx_128_castps_si128(__m128(a.val))); } - -inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) -{ return a; } -inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) -{ return v_float64x2(_lsx_128_castpd_si128(__m128d(a.val))); } - -//////////////// Variant Value reordering /////////////// - -// unpacks -#define OPENCV_HAL_IMPL_LSX_UNPACK(_Tpvec, suffix) \ - inline _Tpvec v128_unpacklo(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vilvl_##suffix(__m128i(b.val), __m128i(a.val))); } \ - inline _Tpvec v128_unpackhi(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vilvh_##suffix(__m128i(b.val), __m128i(a.val))); } \ - -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint8x16, b) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int8x16, b) -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint16x8, h) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int16x8, h) -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint32x4, w) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int32x4, w) -OPENCV_HAL_IMPL_LSX_UNPACK(v_uint64x2, d) -OPENCV_HAL_IMPL_LSX_UNPACK(v_int64x2, d) -OPENCV_HAL_IMPL_LSX_UNPACK(v_float32x4, w) -OPENCV_HAL_IMPL_LSX_UNPACK(v_float64x2, d) - -//ZIP -#define OPENCV_HAL_IMPL_LSX_ZIP(_Tpvec) \ - inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ - { return (_Tpvec)__lsx_vilvl_d((__m128i)b.val, (__m128i)a.val); } \ - inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ - { return (_Tpvec)__lsx_vilvh_d((__m128i)b.val, (__m128i)a.val); } \ - inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ - { \ - __m128i a1 = (__m128i)a.val, b1 = (__m128i)b.val; \ - c = _Tpvec(__lsx_vilvl_d(b1, a1)); \ - d = _Tpvec(__lsx_vilvh_d(b1, a1)); \ - } \ - inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ - _Tpvec& ab0, _Tpvec& ab1) \ - { \ - ab0 = v128_unpacklo(a, b); \ - ab1 = v128_unpackhi(a, b); \ - } - -OPENCV_HAL_IMPL_LSX_ZIP(v_uint8x16) -OPENCV_HAL_IMPL_LSX_ZIP(v_int8x16) -OPENCV_HAL_IMPL_LSX_ZIP(v_uint16x8) -OPENCV_HAL_IMPL_LSX_ZIP(v_int16x8) -OPENCV_HAL_IMPL_LSX_ZIP(v_uint32x4) -OPENCV_HAL_IMPL_LSX_ZIP(v_int32x4) -OPENCV_HAL_IMPL_LSX_ZIP(v_uint64x2) -OPENCV_HAL_IMPL_LSX_ZIP(v_int64x2) -OPENCV_HAL_IMPL_LSX_ZIP(v_float32x4) -OPENCV_HAL_IMPL_LSX_ZIP(v_float64x2) - -////////// Arithmetic, bitwise and comparison operations ///////// - -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_LSX_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint8x16, __lsx_vsadd_bu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint8x16, __lsx_vssub_bu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int8x16, __lsx_vsadd_b) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int8x16, __lsx_vssub_b) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint16x8, __lsx_vsadd_hu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint16x8, __lsx_vssub_hu) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int16x8, __lsx_vsadd_h) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int16x8, __lsx_vssub_h) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint32x4, __lsx_vadd_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint32x4, __lsx_vsub_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_uint32x4, __lsx_vmul_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int32x4, __lsx_vadd_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int32x4, __lsx_vsub_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_int32x4, __lsx_vmul_w) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint64x2, __lsx_vadd_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint64x2, __lsx_vsub_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int64x2, __lsx_vadd_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int64x2, __lsx_vsub_d) - -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float32x4, __lsx_vfadd_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float32x4, __lsx_vfsub_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float32x4, __lsx_vfmul_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float32x4, __lsx_vfdiv_s) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float64x2, __lsx_vfadd_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float64x2, __lsx_vfsub_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float64x2, __lsx_vfmul_d) -OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float64x2, __lsx_vfdiv_d) - -// saturating multiply 8-bit, 16-bit -inline v_uint8x16 v_mul(const v_uint8x16& a, const v_uint8x16& b) -{ - v_uint16x8 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_int8x16 v_mul(const v_int8x16& a, const v_int8x16& b) -{ - v_int16x8 c, d; - v_mul_expand(a, b, c, d); - return v_pack(c, d); -} -inline v_uint16x8 v_mul(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i pev = __lsx_vmulwev_w_hu(a0, b0); - __m128i pod = __lsx_vmulwod_w_hu(a0, b0); - __m128i pl = __lsx_vilvl_w(pod, pev); - __m128i ph = __lsx_vilvh_w(pod, pev); - return (v_uint16x8)__lsx_vssrlrni_hu_w(ph, pl, 0); -} -inline v_int16x8 v_mul(const v_int16x8& a, const v_int16x8& b) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i pev = __lsx_vmulwev_w_h(a0, b0); - __m128i pod = __lsx_vmulwod_w_h(a0, b0); - __m128i pl = __lsx_vilvl_w(pod, pev); - __m128i ph = __lsx_vilvh_w(pod, pev); - return (v_int16x8)__lsx_vssrarni_h_w(ph, pl, 0); -} - -/** Non-saturating arithmetics **/ - -#define OPENCV_HAL_IMPL_LSX_BIN_FUNC(func, _Tpvec, intrin) \ - inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin(a.val, b.val)); } \ - -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint8x16, __lsx_vadd_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int8x16, __lsx_vadd_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint16x8, __lsx_vadd_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int16x8, __lsx_vadd_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint8x16, __lsx_vsub_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int8x16, __lsx_vsub_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint16x8, __lsx_vsub_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int16x8, __lsx_vsub_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_uint16x8, __lsx_vmul_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_int16x8, __lsx_vmul_h) - -inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); - __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); - return v_uint8x16(__lsx_vpackev_b(p1, p0)); -} - -inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -// Multiply and expand -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); - __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); - c.val = __lsx_vilvl_h(p1, p0); - d.val = __lsx_vilvh_h(p1, p0); -} -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_h_b(a0, b0); - __m128i p1 = __lsx_vmulwod_h_b(a0, b0); - c.val = __lsx_vilvl_h(p1, p0); - d.val = __lsx_vilvh_h(p1, p0); -} -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_w_h(a0, b0); - __m128i p1 = __lsx_vmulwod_w_h(a0, b0); - c.val = __lsx_vilvl_w(p1, p0); - d.val = __lsx_vilvh_w(p1, p0); -} -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_w_hu(a0, b0); - __m128i p1 = __lsx_vmulwod_w_hu(a0, b0); - c.val = __lsx_vilvl_w(p1, p0); - d.val = __lsx_vilvh_w(p1, p0); -} -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - __m128i a0 = a.val, b0 = b.val; - __m128i p0 = __lsx_vmulwev_d_wu(a0, b0); - __m128i p1 = __lsx_vmulwod_d_wu(a0, b0); - c.val = __lsx_vilvl_d(p1, p0); - d.val = __lsx_vilvh_d(p1, p0); -} -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ return v_int16x8(__lsx_vmuh_h(a.val, b.val)); } -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint16x8(__lsx_vmuh_hu(a.val, b.val)); } - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_LSX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ - inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ - { return _Tpsvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ - { return _Tpuvec(__lsx_vsrl_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ - { return _Tpsvec(srai(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ - template \ - inline _Tpuvec v_shl(const _Tpuvec& a) \ - { return _Tpuvec(__lsx_vslli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shl(const _Tpsvec& a) \ - { return _Tpsvec(__lsx_vslli_##suffix(a.val, imm)); } \ - template \ - inline _Tpuvec v_shr(const _Tpuvec& a) \ - { return _Tpuvec(__lsx_vsrli_##suffix(a.val, imm)); } \ - template \ - inline _Tpsvec v_shr(const _Tpsvec& a) \ - { return _Tpsvec(__lsx_vsrai_##suffix(a.val, imm)); } \ - -OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint16x8, v_int16x8, h, __lsx_vsra_h) -OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint32x4, v_int32x4, w, __lsx_vsra_w) -OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint64x2, v_int64x2, d, __lsx_vsra_d) - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_LSX_LOGIC_OP(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_LSX_BIN_OP(v_and, _Tpvec, __lsx_vand_##suffix) \ - OPENCV_HAL_IMPL_LSX_BIN_OP(v_or, _Tpvec, __lsx_vor_##suffix) \ - OPENCV_HAL_IMPL_LSX_BIN_OP(v_xor, _Tpvec, __lsx_vxor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lsx_vnori_b(a.val, 0)); } \ - -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint8x16, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int8x16, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint16x8, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int16x8, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint32x4, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int32x4, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint64x2, v) -OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int64x2, v) - -#define OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(intrin((__m128i)(a.val), (__m128i)(b.val))); } - -#define OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(_Tpvec, cast) \ - OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_and, _Tpvec, __lsx_vand_v, cast) \ - OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_or, _Tpvec, __lsx_vor_v, cast) \ - OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_xor, _Tpvec, __lsx_vxor_v, cast) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { return _Tpvec(__lsx_vnori_b((__m128i)(a.val), 0)); } \ - -OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float32x4, _lsx_128_castsi128_ps) -OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float64x2, _lsx_128_castsi128_pd) - -/** Select **/ -#define OPENCV_HAL_IMPL_LSX_SELECT(_Tpvec) \ - inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vbitsel_v(b.val, a.val, mask.val)); } \ - -OPENCV_HAL_IMPL_LSX_SELECT(v_uint8x16) -OPENCV_HAL_IMPL_LSX_SELECT(v_int8x16) -OPENCV_HAL_IMPL_LSX_SELECT(v_uint16x8) -OPENCV_HAL_IMPL_LSX_SELECT(v_int16x8) -OPENCV_HAL_IMPL_LSX_SELECT(v_uint32x4) -OPENCV_HAL_IMPL_LSX_SELECT(v_int32x4) - -inline v_float32x4 v_select(const v_float32x4 &mask, const v_float32x4 &a, const v_float32x4 &b) -{ return v_float32x4(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } -inline v_float64x2 v_select(const v_float64x2 &mask, const v_float64x2 &a, const v_float64x2 &b) -{ return v_float64x2(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } - -/** Comparison **/ -#define OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpvec) \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } \ - inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ - { return v_gt(b, a); } \ - inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_lt(a, b)); } \ - inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ - { return v_ge(b, a); } \ - -#define OPENCV_HAL_IMPL_LSX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ - inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(__lsx_vseq_##suffix(a.val, b.val)); } \ - inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ - { return _Tpuvec(__lsx_vslt_##usuffix(b.val, a.val)); } \ - inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lsx_vseq_##suffix(a.val, b.val)); } \ - inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ - { return _Tpsvec(__lsx_vslt_##suffix(b.val, a.val)); } \ - OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpuvec) \ - OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpsvec) - -OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint8x16, v_int8x16, b, bu) -OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint16x8, v_int16x8, h, hu) -OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint32x4, v_int32x4, w, wu) - -#define OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(_Tpvec, suffix) \ - inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_vseq_##suffix(a.val, b.val)); } \ - inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ - { return v_not(v_eq(a, b)); } - -OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_uint64x2, d) -OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_int64x2, d) - -#define OPENCV_HAL_IMPL_LSX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { return _Tpvec(__lsx_##suffix##_##ssuffix(a.val, b.val)); } \ - -#define OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(_Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_eq, vfcmp_ceq, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_ne, vfcmp_cne, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_lt, vfcmp_clt, _Tpvec, ssuffix) \ - OPENCV_HAL_IMPL_LSX_CMP_FLT(v_le, vfcmp_cle, _Tpvec, ssuffix) \ - -OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float32x4, s) -OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float64x2, d) - -inline v_float32x4 v_gt(const v_float32x4 &a, const v_float32x4 &b) -{ return v_float32x4(__lsx_vfcmp_clt_s(b.val, a.val)); } - -inline v_float32x4 v_ge(const v_float32x4 &a, const v_float32x4 &b) -{ return v_float32x4(__lsx_vfcmp_cle_s(b.val, a.val)); } - -inline v_float64x2 v_gt(const v_float64x2 &a, const v_float64x2 &b) -{ return v_float64x2(__lsx_vfcmp_clt_d(b.val, a.val)); } - -inline v_float64x2 v_ge(const v_float64x2 &a, const v_float64x2 &b) -{ return v_float64x2(__lsx_vfcmp_cle_d(b.val, a.val)); } - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(__lsx_vfcmp_cor_s(a.val, a.val)); } - -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(__lsx_vfcmp_cor_d(a.val, a.val)); } - -/** min/max **/ -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint8x16, __lsx_vmin_bu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint8x16, __lsx_vmax_bu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int8x16, __lsx_vmin_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int8x16, __lsx_vmax_b) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint16x8, __lsx_vmin_hu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint16x8, __lsx_vmax_hu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int16x8, __lsx_vmin_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int16x8, __lsx_vmax_h) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint32x4, __lsx_vmin_wu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint32x4, __lsx_vmax_wu) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int32x4, __lsx_vmin_w) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int32x4, __lsx_vmax_w) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float32x4, __lsx_vfmin_s) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float32x4, __lsx_vfmax_s) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float64x2, __lsx_vfmin_d) -OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float64x2, __lsx_vfmax_d) - -template 16)), - bool is_first = (imm == 0), - bool is_half = (imm == 8), - bool is_second = (imm == 16), - bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> -class v_lsx_palignr_u8_class; - -template -class v_lsx_palignr_u8_class; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - CV_UNUSED(b); - return a; - } -}; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - return __lsx_vshuf4i_d(a, b, 0x9); - } -}; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - CV_UNUSED(a); - return b; - } -}; - -template -class v_lsx_palignr_u8_class -{ -public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - enum { imm2 = (sizeof(__m128i) - imm) }; - return __lsx_vor_v(__lsx_vbsrl_v(a, imm), __lsx_vbsll_v(b, imm2)); - } -}; - -template -inline __m128i v_lsx_palignr_u8(const __m128i& a, const __m128i& b) -{ - CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_lsx_palignr_u8"); - return v_lsx_palignr_u8_class()(a, b); -} -/** Rotate **/ -#define OPENCV_HAL_IMPL_LSX_ROTATE_CAST(_Tpvec, cast) \ - template \ - inline _Tpvec v_rotate_right(const _Tpvec &a) \ - { \ - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ - __m128i ret = __lsx_vbsrl_v((__m128i)a.val, imm2); \ - return _Tpvec(cast(ret)); \ - } \ - template \ - inline _Tpvec v_rotate_left(const _Tpvec &a) \ - { \ - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ - __m128i ret = __lsx_vbsll_v((__m128i)a.val, imm2); \ - return _Tpvec(cast(ret)); \ - } \ - template \ - inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ - return _Tpvec(cast(v_lsx_palignr_u8((__m128i)a.val, (__m128i)b.val))); \ - } \ - template \ - inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ - { \ - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type))}; \ - return _Tpvec(cast(v_lsx_palignr_u8((__m128i)b.val, (__m128i)a.val))); \ - } - -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint8x16, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int8x16, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint16x8, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int16x8, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint32x4, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int32x4, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint64x2, OPENCV_HAL_NOP) \ -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int64x2, OPENCV_HAL_NOP) \ - -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float32x4, _lsx_128_castsi128_ps) -OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float64x2, _lsx_128_castsi128_pd) - -/** Rverse **/ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - __m128i vec = __lsx_vshuf4i_b(a.val, 0x1B); - return v_uint8x16(__lsx_vshuf4i_w(vec, 0x1B)); -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - __m128i vec = __lsx_vshuf4i_h(a.val, 0x1B); - return v_uint16x8(__lsx_vshuf4i_w(vec, 0x4E)); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ return v_uint32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_int32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ return v_uint64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_int64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -////////////// Reduce and mask //////////// - -/** Reduce **/ -// this function is return a[0]+a[1]+...+a[31] -inline unsigned v_reduce_sum(const v_uint8x16& a) -{ - __m128i t1 = __lsx_vhaddw_hu_bu(a.val, a.val); - __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); - __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); - __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); - return (unsigned)__lsx_vpickve2gr_w(t4, 0); -} - -inline int v_reduce_sum(const v_int8x16 &a) -{ - __m128i t1 = __lsx_vhaddw_h_b(a.val, a.val); - __m128i t2 = __lsx_vhaddw_w_h(t1, t1); - __m128i t3 = __lsx_vhaddw_d_w(t2, t2); - __m128i t4 = __lsx_vhaddw_q_d(t3, t3); - return (int)__lsx_vpickve2gr_w(t4, 0); -} - -#define OPENCV_HAL_IMPL_LSX_REDUCE_16(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec& a) \ - { \ - __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ - val = intrin(val, __lsx_vbsrl_v(val, 4)); \ - val = intrin(val, __lsx_vbsrl_v(val, 2)); \ - val = intrin(val, __lsx_vbsrl_v(val, 1)); \ - return (sctype)__lsx_vpickve2gr_b(val, 0); \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, min, __lsx_vmin_bu) -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, max, __lsx_vmax_bu) -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, min, __lsx_vmin_b) -OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, max, __lsx_vmax_b) - -#define OPENCV_HAL_IMPL_LSX_REDUCE_8(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec &a) \ - { \ - __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ - val = intrin(val, __lsx_vbsrl_v(val, 4)); \ - val = intrin(val, __lsx_vbsrl_v(val, 2)); \ - return (sctype)__lsx_vpickve2gr_h(val, 0); \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, min, __lsx_vmin_hu) -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, max, __lsx_vmax_hu) -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, min, __lsx_vmin_h) -OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, max, __lsx_vmax_h) - -#define OPENCV_HAL_IMPL_LSX_REDUCE_4(_Tpvec, sctype, func, intrin) \ - inline sctype v_reduce_##func(const _Tpvec &a) \ - { \ - __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ - val = intrin(val, __lsx_vbsrl_v(val, 4)); \ - return (sctype)__lsx_vpickve2gr_w(val, 0); \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, min, __lsx_vmin_wu) -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, max, __lsx_vmax_wu) -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, min, __lsx_vmin_w) -OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, max, __lsx_vmax_w) - -#define OPENCV_HAL_IMPL_LSX_REDUCE_FLT(func, intrin) \ - inline float v_reduce_##func(const v_float32x4 &a) \ - { \ - __m128 val = a.val; \ - val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 8)); \ - val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 4)); \ - float *fval = (float*)&val; \ - return fval[0]; \ - } - -OPENCV_HAL_IMPL_LSX_REDUCE_FLT(min, __lsx_vfmin_s) -OPENCV_HAL_IMPL_LSX_REDUCE_FLT(max, __lsx_vfmax_s) - -inline int v_reduce_sum(const v_int32x4 &a) -{ - __m128i t1 = __lsx_vhaddw_d_w(a.val, a.val); - __m128i t2 = __lsx_vhaddw_q_d(t1, t1); - return (int)__lsx_vpickve2gr_w(t2, 0); -} - -inline unsigned v_reduce_sum(const v_uint32x4 &a) -{ - __m128i t1 = __lsx_vhaddw_du_wu(a.val, a.val); - __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); - return (int)__lsx_vpickve2gr_w(t2, 0); -} - -inline int v_reduce_sum(const v_int16x8 &a) -{ - __m128i t1 = __lsx_vhaddw_w_h(a.val, a.val); - __m128i t2 = __lsx_vhaddw_d_w(t1, t1); - __m128i t3 = __lsx_vhaddw_q_d(t2, t2); - return (int)__lsx_vpickve2gr_w(t3, 0); -} - -inline unsigned v_reduce_sum(const v_uint16x8 &a) -{ - __m128i t1 = __lsx_vhaddw_wu_hu(a.val, a.val); - __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); - __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); - return (int)__lsx_vpickve2gr_w(t3, 0); -} - -inline float v_reduce_sum(const v_float32x4 &a) -{ - __m128i val = (__m128i)a.val; - val = __lsx_vbsrl_v(val, 8); - __m128 result = __lsx_vfadd_s(a.val, (__m128)val); - float *pa = (float*)&result; - return (float)(pa[0] + pa[1]); -} - -inline uint64 v_reduce_sum(const v_uint64x2 &a) -{ - __m128i t0 = __lsx_vhaddw_qu_du(a.val, a.val); - return (uint64)__lsx_vpickve2gr_du(t0, 0); -} - -inline int64 v_reduce_sum(const v_int64x2 &a) -{ - __m128i t0 = __lsx_vhaddw_q_d(a.val, a.val); - return (int64)__lsx_vpickve2gr_d(t0, 0); -} - -inline double v_reduce_sum(const v_float64x2 &a) -{ - double *pa = (double*)&a; - return pa[0] + pa[1]; -} - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - __m128i a0 = (__m128i)a.val; - __m128i b0 = (__m128i)b.val; - __m128i c0 = (__m128i)c.val; - __m128i d0 = (__m128i)d.val; - __m128i ac_l = __lsx_vilvl_w(c0, a0); - __m128i ac_h = __lsx_vilvh_w(c0, a0); - __m128i bd_l = __lsx_vilvl_w(d0, b0); - __m128i bd_h = __lsx_vilvh_w(d0, b0); - __m128 ac = __lsx_vfadd_s((__m128)ac_l, (__m128)ac_h); - __m128 bd = __lsx_vfadd_s((__m128)bd_l, (__m128)bd_h); - return v_float32x4(__lsx_vfadd_s((__m128)__lsx_vilvl_w((__m128i)bd, (__m128i)ac), - (__m128)__lsx_vilvh_w((__m128i)bd, (__m128i)ac))); -} - -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - __m128i t0 = __lsx_vabsd_b(a.val, b.val); - __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); - __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); - __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); - __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); - return (unsigned)__lsx_vpickve2gr_w(t4, 0); -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i t0 = __lsx_vabsd_bu(a.val, b.val); - __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); - __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); - __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); - __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); - return (unsigned)__lsx_vpickve2gr_w(t4, 0); -} - -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i t0 = __lsx_vabsd_hu(a.val, b.val); - __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); - __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); - __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); - return (unsigned)__lsx_vpickve2gr_w(t3, 0); -} - -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - __m128i t0 = __lsx_vabsd_h(a.val, b.val); - __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); - __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); - __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); - return (unsigned)__lsx_vpickve2gr_w(t3, 0); -} - -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - __m128i t0 = __lsx_vabsd_wu(a.val, b.val); - __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); - __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); - return (unsigned)__lsx_vpickve2gr_w(t2, 0); -} - -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - __m128i t0 = __lsx_vabsd_w(a.val, b.val); - __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); - __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); - return (unsigned)__lsx_vpickve2gr_w(t2, 0); -} - -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 a_b = v_sub(a, b); - return v_reduce_sum(v_float32x4((__m128i)a_b.val & __lsx_vreplgr2vr_w(0x7fffffff))); -} - -/** Popcount **/ -#define OPENCV_HAL_IMPL_LSX_POPCOUNT(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_popcount(const _Tp& a) \ -{ return _Tpvec(__lsx_vpcnt_##suffix(a.val)); } - -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_uint8x16, b); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_int8x16, b); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_uint16x8, h); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_int16x8, h); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_uint32x4, w); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_int32x4, w); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_uint64x2, d); -OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_int64x2, d); - -/** Mask **/ -#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ -inline tt reinterpret_int(ft x) { union {ft l; tt i;} v; v.l = x; return v.i; } -OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) - -inline int v_signmask(const v_int8x16& a) -{ - __m128i result = __lsx_vmskltz_b(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_uint8x16& a) -{ return v_signmask(v_reinterpret_as_s8(a)) ;} - -inline int v_signmask(const v_int16x8 &a) -{ - __m128i result = __lsx_vmskltz_h(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_uint16x8 &a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_uint32x4& a) -{ - __m128i result = __lsx_vmskltz_w(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_int32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } - -inline int v_signmask(const v_uint64x2& a) -{ - __m128i result = __lsx_vmskltz_d(a.val); - return __lsx_vpickve2gr_w(result, 0); -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } - -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(*(v_int32x4*)(&a)); } - -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(*(v_int64x2*)(&a)); } - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -/** Checks **/ -#define OPENCV_HAL_IMPL_LSX_CHECK(_Tpvec, allmask) \ - inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ - inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } -OPENCV_HAL_IMPL_LSX_CHECK(v_uint8x16, 65535) -OPENCV_HAL_IMPL_LSX_CHECK(v_int8x16, 65535) -OPENCV_HAL_IMPL_LSX_CHECK(v_uint16x8, 255); -OPENCV_HAL_IMPL_LSX_CHECK(v_int16x8, 255); -OPENCV_HAL_IMPL_LSX_CHECK(v_uint32x4, 15) -OPENCV_HAL_IMPL_LSX_CHECK(v_int32x4, 15) -OPENCV_HAL_IMPL_LSX_CHECK(v_uint64x2, 3) -OPENCV_HAL_IMPL_LSX_CHECK(v_int64x2, 3) -OPENCV_HAL_IMPL_LSX_CHECK(v_float32x4, 15) -OPENCV_HAL_IMPL_LSX_CHECK(v_float64x2, 3) - -///////////// Other math ///////////// - -/** Some frequent operations **/ -#define OPENCV_HAL_IMPL_LSX_MULADD(_Tpvec, suffix) \ - inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ - { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec &b, const _Tpvec& c) \ - { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ - inline _Tpvec v_sqrt(const _Tpvec& x) \ - { return _Tpvec(__lsx_vfsqrt_##suffix(x.val)); } \ - inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_fma(a, a, v_mul(b, b)); } \ - inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ - { return v_sqrt(v_fma(a, a, v_mul(b, b))); } - -OPENCV_HAL_IMPL_LSX_MULADD(v_float32x4, s) -OPENCV_HAL_IMPL_LSX_MULADD(v_float64x2, d) - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ return v_int32x4(__lsx_vmadd_w(c.val, a.val, b.val)); } - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ return v_fma(a, b, c); } - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - return v_float32x4(__lsx_vfrsqrt_s(x.val)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - return v_float64x2(__lsx_vfrsqrt_d(x.val)); -} - -/** Absolute values **/ -#define OPENCV_HAL_IMPL_LSX_ABS(_Tpvec, suffix) \ - inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ - { return v_u##_Tpvec(__lsx_vabsd_##suffix(x.val, __lsx_vldi(0))); } - -OPENCV_HAL_IMPL_LSX_ABS(int8x16, b) -OPENCV_HAL_IMPL_LSX_ABS(int16x8, h) -OPENCV_HAL_IMPL_LSX_ABS(int32x4, w) - -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(*((__m128i*)&x) & __lsx_vreplgr2vr_w(0x7fffffff)); } -inline v_float64x2 v_abs(const v_float64x2& x) -{ return v_float64x2(*((__m128i*)&x) & __lsx_vreplgr2vr_d(0x7fffffffffffffff)); } - -/** Absolute difference **/ - -inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) -{ return (v_uint8x16)__lsx_vabsd_bu(a.val, b.val); } -inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) -{ return (v_uint16x8)__lsx_vabsd_hu(a.val, b.val); } -inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) -{ return (v_uint32x4)__lsx_vabsd_wu(a.val, b.val); } - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ return (v_uint8x16)__lsx_vabsd_b(a.val, b.val); } -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ return (v_uint16x8)__lsx_vabsd_h(a.val, b.val); } -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ return (v_uint32x4)__lsx_vabsd_w(a.val, b.val); } - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ return v_abs(v_sub(a, b)); } - -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ return v_abs(v_sub(a, b)); } - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub(a, b); - v_int8x16 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); -} -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -///////// Conversions ///////// - -/** Rounding **/ -inline v_int32x4 v_round(const v_float32x4& a) -{ return v_int32x4(__lsx_vftint_w_s(a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a) -{ return v_int32x4(__lsx_vftint_w_d(a.val, a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ return v_int32x4(__lsx_vftint_w_d(b.val, a.val)); } - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(__lsx_vftintrz_w_s(a.val)); } - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ return v_int32x4(__lsx_vftintrz_w_d(a.val, a.val)); } - -inline v_int32x4 v_floor(const v_float32x4& a) -{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrm_s(a.val)))); } - -inline v_int32x4 v_floor(const v_float64x2& a) -{ return v_trunc(v_float64x2(__lsx_vfrintrm_d(a.val))); } - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrp_s(a.val)))); } - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ return v_trunc(v_float64x2(__lsx_vfrintrp_d(a.val))); } - -/** To float **/ -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ return v_float32x4(__lsx_vffint_s_w(a.val)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ return v_float32x4(__lsx_vfcvt_s_d(a.val, a.val)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ return v_float32x4(__lsx_vfcvt_s_d(b.val, a.val)); } - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ return v_float64x2(__lsx_vffintl_d_w(a.val)); } - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ return v_float64x2(__lsx_vffinth_d_w(a.val)); } - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ return v_float64x2(__lsx_vfcvtl_d_s(a.val)); } - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ return v_float64x2(__lsx_vfcvth_d_s(a.val)); } - -inline v_float64x2 v_cvt_f64(const v_int64x2& v) -{ return v_float64x2(__lsx_vffint_d_l(v.val)); } - - -//////////////// Lookup table access //////////////// -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - return v_int8x16(_v128_setr_b(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], tab[idx[8]], - tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], - tab[idx[14]], tab[idx[15]])); -} - -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x16(_v128_setr_h(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), - *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), *(const short*)(tab + idx[4]), - *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); -} - -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x16(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -} - -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) -{ return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) -{ return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) -{ return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - return v_int16x8(_v128_setr_h(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x8(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); -} - -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) -{ return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) -{ return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) -{ return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - return v_int32x4(_v128_setr_w(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_int32x4 v_lut_pairs(const int *tab, const int* idx) -{ - return v_int32x4(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(__lsx_vld(tab + idx[0], 0)); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int *idx) -{ - return v_int64x2(_v128_setr_d(tab[idx[0]], tab[idx[1]])); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(__lsx_vld(tab + idx[0], 0)); -} - -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(_v128_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ - return v_float32x4((__m128)_v128_setr_pd(*(const double*)(tab + idx[0]), *(const double*)(tab + idx[1]))); -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4((__m128)__lsx_vld(tab + idx[0], 0)); -} - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(_v128_setr_pd(tab[idx[0]], tab[idx[1]])); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2((__m128d)__lsx_vld(tab + idx[0], 0)); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int *idx = (int*)&idxvec.val; - return v_lut(tab, idx); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v_lut(tab, idx); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - const int *idx = (const int*)&idxvec.val; - return v_lut(tab, idx); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - const int *idx = (const int*)&idxvec.val; - __m128i xy0 = __lsx_vld(tab + idx[0], 0); - __m128i xy1 = __lsx_vld(tab + idx[1], 0); - __m128i xy2 = __lsx_vld(tab + idx[2], 0); - __m128i xy3 = __lsx_vld(tab + idx[3], 0); - __m128i xy01 = __lsx_vilvl_d(xy1, xy0); - __m128i xy23 = __lsx_vilvl_d(xy3, xy2); - __m128i xxyy02 = __lsx_vilvl_w(xy23, xy01); - __m128i xxyy13 = __lsx_vilvh_w(xy23, xy01); - x = v_float32x4((__m128)__lsx_vilvl_w(xxyy13, xxyy02)); - y = v_float32x4((__m128)__lsx_vilvh_w(xxyy13, xxyy02)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - const int* idx = (const int*)&idxvec.val; - __m128i xy0 = __lsx_vld(tab + idx[0], 0); - __m128i xy1 = __lsx_vld(tab + idx[1], 0); - x = v_float64x2((__m128d)__lsx_vilvl_d(xy1, xy0)); - y = v_float64x2((__m128d)__lsx_vilvh_d(xy1, xy0)); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0705060403010200, 0x0f0d0e0c0b090a08))); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0703060205010400, 0x0f0b0e0a0d090c08))); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0706030205040100, 0x0f0e0b0a0d0c0908))); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, - _v128_setr_d(0x0b0a030209080100, 0x0f0e07060d0c0504))); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - return v_int32x4(__lsx_vshuf4i_w(vec.val, 0xd8)); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) -{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) -{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - __m128i zero = __lsx_vldi(0); - return v_int8x16(__lsx_vshuf_b(zero, vec.val, - _v128_set_d(0x1211100f0e0d0c0a, 0x0908060504020100))); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - __m128i zero = __lsx_vldi(0); - return v_int16x8(__lsx_vshuf_b(zero, vec.val, - _v128_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100))); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -//////////// Matrix operations ///////// - -/////////// Dot Product ///////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - __m128i x = a.val, y = b.val; - return v_int32x4(__lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y)); -} -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - __m128i x = a.val, y = b.val, z = c.val; - __m128i t = __lsx_vmaddwev_w_h(z, x, y); - return v_int32x4(__lsx_vmaddwod_w_h(t, x, y)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - __m128i x = a.val, y = b.val; - return v_int64x2(__lsx_vmaddwod_d_w(__lsx_vmulwev_d_w(x, y), x, y)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - __m128i x = a.val, y = b.val, z = c.val; - __m128i t = __lsx_vmaddwev_d_w(z, x, y); - return v_int64x2(__lsx_vmaddwod_d_w(t, x, y)); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_h_bu(x, y); - __m128i odd = __lsx_vmulwod_h_bu(x, y); - __m128i prod0 = __lsx_vhaddw_wu_hu(even, even); - __m128i prod1 = __lsx_vhaddw_wu_hu(odd, odd); - return v_uint32x4(__lsx_vadd_w(prod0, prod1)); -} - -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand(a, b), c) ;} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_h_b(x, y); - __m128i odd = __lsx_vmulwod_h_b(x, y); - __m128i prod0 = __lsx_vhaddw_w_h(even, even); - __m128i prod1 = __lsx_vhaddw_w_h(odd, odd); - return v_int32x4(__lsx_vadd_w(prod0, prod1)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_w_hu(x, y); - __m128i odd = __lsx_vmulwod_w_hu(x, y); - __m128i prod0 = __lsx_vhaddw_du_wu(even, even); - __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); - return v_uint64x2(__lsx_vadd_d(prod0, prod1)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_w_h(x, y); - __m128i odd = __lsx_vmulwod_w_h(x, y); - __m128i prod0 = __lsx_vhaddw_d_w(even, even); - __m128i prod1 = __lsx_vhaddw_d_w(odd, odd); - return v_int64x2(__lsx_vadd_d(prod0, prod1)); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - - -///////// Fast Dot Product ////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i even = __lsx_vmulwev_w_hu(x, y); - __m128i odd = __lsx_vmulwod_w_hu(x, y); - __m128i prod0 = __lsx_vhaddw_du_wu(even, even); - __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); - return v_uint64x2(__lsx_vilvl_d(__lsx_vhaddw_qu_du(prod0, prod0), __lsx_vhaddw_qu_du(prod1, prod1))); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - __m128i x = a.val, y = b.val; - __m128i prod = __lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y); - __m128i sign = __lsx_vsrai_w(prod, 31); - __m128i lo = __lsx_vilvl_w(sign, prod); - __m128i hi = __lsx_vilvh_w(sign, prod); - return v_int64x2(__lsx_vadd_d(lo, hi)); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) -{ - __m128i x = (__m128i)v.val; - __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); - __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); - __m128 v2 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val); - __m128 v3 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xFF), m3.val); - - return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), __lsx_vfadd_s(v2, v3))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& a) -{ - __m128i x = (__m128i)v.val; - __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); - __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); - __m128 v2 = __lsx_vfmadd_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val, a.val); - - return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), v2)); -} - -#define OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(_Tpvec, cast_from, cast_to) \ - inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ - { \ - __m128i t0 = cast_from(__lsx_vilvl_w(a1.val, a0.val)); \ - __m128i t1 = cast_from(__lsx_vilvl_w(a3.val, a2.val)); \ - __m128i t2 = cast_from(__lsx_vilvh_w(a1.val, a0.val)); \ - __m128i t3 = cast_from(__lsx_vilvh_w(a3.val, a2.val)); \ - b0.val = cast_to(__lsx_vilvl_d(t1, t0)); \ - b1.val = cast_to(__lsx_vilvh_d(t1, t0)); \ - b2.val = cast_to(__lsx_vilvl_d(t3, t2)); \ - b3.val = cast_to(__lsx_vilvh_d(t3, t2)); \ - } - -OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_uint32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_int32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) - -inline void v_transpose4x4(const v_float32x4& a0, const v_float32x4& a1, - const v_float32x4& a2, const v_float32x4& a3, - v_float32x4& b0, v_float32x4& b1, v_float32x4& b2, v_float32x4& b3) -{ - __m128i vec0 = (__m128i)a0.val, vec1 = (__m128i)a1.val; - __m128i vec2 = (__m128i)a2.val, vec3 = (__m128i)a3.val; - __m128i t0 = __lsx_vilvl_w(vec1, vec0); - __m128i t1 = __lsx_vilvl_w(vec3, vec2); - __m128i t2 = __lsx_vilvh_w(vec1, vec0); - __m128i t3 = __lsx_vilvh_w(vec3, vec2); - b0.val = __m128(__lsx_vilvl_d(t1, t0)); - b1.val = __m128(__lsx_vilvh_d(t1, t0)); - b2.val = __m128(__lsx_vilvl_d(t3, t2)); - b3.val = __m128(__lsx_vilvh_d(t3, t2)); -} - -////////////////// Value reordering //////////////// - -/* Expand */ -#define OPENCV_HAL_IMPL_LSX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin_lo, intrin_hi) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin_lo(a.val, 0); \ - b1.val = intrin_hi(a.val); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin_lo(a.val, 0)); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(intrin_hi(a.val)); } \ - inline _Tpwvec v_load_expand(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - return _Tpwvec(intrin_lo(a, 0)); \ - } - -OPENCV_HAL_IMPL_LSX_EXPAND(v_uint8x16, v_uint16x8, uchar, __lsx_vsllwil_hu_bu, __lsx_vexth_hu_bu) -OPENCV_HAL_IMPL_LSX_EXPAND(v_int8x16, v_int16x8, schar, __lsx_vsllwil_h_b, __lsx_vexth_h_b) -OPENCV_HAL_IMPL_LSX_EXPAND(v_uint16x8, v_uint32x4, ushort, __lsx_vsllwil_wu_hu, __lsx_vexth_wu_hu) -OPENCV_HAL_IMPL_LSX_EXPAND(v_int16x8, v_int32x4, short, __lsx_vsllwil_w_h, __lsx_vexth_w_h) -OPENCV_HAL_IMPL_LSX_EXPAND(v_uint32x4, v_uint64x2, unsigned, __lsx_vsllwil_du_wu, __lsx_vexth_du_wu) -OPENCV_HAL_IMPL_LSX_EXPAND(v_int32x4, v_int64x2, int, __lsx_vsllwil_d_w, __lsx_vexth_d_w) - -#define OPENCV_HAL_IMPL_LSX_EXPAND_Q(_Tpvec, _Tp, intrin_lo, intrin_hi) \ - inline _Tpvec v_load_expand_q(const _Tp* ptr) \ - { \ - __m128i a = __lsx_vld(ptr, 0); \ - __m128i b = intrin_lo(a, 0); \ - return _Tpvec(intrin_hi(b, 0)); \ - } - -OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_uint32x4, uchar, __lsx_vsllwil_hu_bu, __lsx_vsllwil_wu_hu) -OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_int32x4, schar, __lsx_vsllwil_h_b, __lsx_vsllwil_w_h) - -/* pack */ -// 16 -inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) -{ return v_int8x16(_lsx_packs_h(a.val, b.val)); } - -inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, 0)); } - -inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) -{ return v_uint8x16(_lsx_packus_h(a.val, b.val)); } - -inline void v_pack_store(schar* ptr, const v_int16x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(uchar* ptr, const v_uint16x8& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) -{ v_store_low(ptr, v_pack_u(a, a)); } - -template inline -v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) -{ __lsx_vstelm_d(__lsx_vssrlrni_bu_h(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) -{ return v_uint8x16(__lsx_vssrarni_bu_h(b.val, a.val, n)); } - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) -{ __lsx_vstelm_d(__lsx_vssrarni_bu_h(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) -{ return v_int8x16(__lsx_vssrarni_b_h(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x8& a) -{ __lsx_vstelm_d(__lsx_vssrarni_b_h(a.val, a.val, n), ptr, 0, 0); } - -//32 -inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) -{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, 0)); } - -inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) -{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, 0)); } - -inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) -{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, 0)); } - -inline void v_pack_store(short* ptr, const v_int32x4& a) -{ v_store_low(ptr, v_pack(a, a)); } - -inline void v_pack_store(ushort *ptr, const v_uint32x4& a) -{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, 0), ptr, 0, 0); } - -inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) -{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, 0), ptr, 0, 0); } - -template inline -v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) -{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) -{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) -{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, n)); } - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) -{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) -{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x4& a) -{ __lsx_vstelm_d(__lsx_vssrarni_h_w(a.val, a.val, n), ptr, 0, 0); } - -// 64 -// Non-saturaing pack -inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint32x4(__lsx_vpickev_w(b.val, a.val)); } - -inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) -{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } - -inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) -{ __lsx_vstelm_d(__lsx_vshuf4i_w(a.val, 0x08), ptr, 0, 0); } - -inline void v_pack_store(int *ptr, const v_int64x2& a) -{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(a)); } - -template inline -v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint32x4(__lsx_vsrlrni_w_d(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) -{ __lsx_vstelm_d(__lsx_vsrlrni_w_d(a.val, a.val, n), ptr, 0, 0); } - -template inline -v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) -{ return v_int32x4(__lsx_vsrarni_w_d(b.val, a.val, n)); } - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x2& a) -{ __lsx_vstelm_d(__lsx_vsrarni_w_d(a.val, a.val, n), ptr, 0, 0); } - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ return v_uint8x16(__lsx_vssrarni_b_h(b.val, a.val, 0)); } - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - __m128i ab = __lsx_vssrarni_h_w(b.val, a.val, 0); - __m128i cd = __lsx_vssrarni_h_w(d.val, c.val, 0); - return v_uint8x16(__lsx_vssrarni_b_h(cd, ab, 0)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - __m128i ab = __lsx_vssrarni_w_d(b.val, a.val, 0); - __m128i cd = __lsx_vssrarni_w_d(d.val, c.val, 0); - __m128i ef = __lsx_vssrarni_w_d(f.val, e.val, 0); - __m128i gh = __lsx_vssrarni_w_d(h.val, g.val, 0); - - __m128i abcd = __lsx_vssrarni_h_w(cd, ab, 0); - __m128i efgh = __lsx_vssrarni_h_w(gh, ef, 0); - return v_uint8x16(__lsx_vssrarni_b_h(efgh, abcd, 0)); -} - -/* Recombine */ -// its up there with load and store operations - -/* Extract */ -#define OPENCV_HAL_IMPL_LSX_EXTRACT(_Tpvec) \ - template \ - inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ - { return v_rotate_right(a, b); } - -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint8x16) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int8x16) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint16x8) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int16x8) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint32x4) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int32x4) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint64x2) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_int64x2) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_float32x4) -OPENCV_HAL_IMPL_LSX_EXTRACT(v_float64x2) - -#define OPENCV_HAL_IMPL_LSX_EXTRACT_N(_Tpvec, _Twvec, intrin) \ -template \ -inline _Twvec v_extract_n(const _Tpvec& a) \ -{ return (_Twvec)intrin(a.val, i); } - -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint8x16, uchar, __lsx_vpickve2gr_b) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int8x16, schar, __lsx_vpickve2gr_b) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint16x8, ushort, __lsx_vpickve2gr_h) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int16x8, short, __lsx_vpickve2gr_h) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint32x4, uint, __lsx_vpickve2gr_w) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int32x4, int, __lsx_vpickve2gr_w) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint64x2, uint64, __lsx_vpickve2gr_d) -OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int64x2, int64, __lsx_vpickve2gr_d) - -template -inline float v_extract_n(const v_float32x4& v) -{ - union { uint iv; float fv; } d; - d.iv = __lsx_vpickve2gr_w(v.val, i); - return d.fv; -} - -template -inline double v_extract_n(const v_float64x2& v) -{ - union { uint64 iv; double dv; } d; - d.iv = __lsx_vpickve2gr_d(v.val, i); - return d.dv; -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) -{ return v_uint32x4(__lsx_vreplvei_w(a.val, i)); } - -template -inline v_int32x4 v_broadcast_element(const v_int32x4& a) -{ return v_int32x4(__lsx_vreplvei_w(a.val, i)); } - -template -inline v_float32x4 v_broadcast_element(const v_float32x4& a) -{ return v_float32x4((__m128)__lsx_vreplvei_w((__m128i)a.val, i)); } - -/////////////////// load deinterleave ////////////////////////////// - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - - a.val = __lsx_vpickev_b(t1, t0); - b.val = __lsx_vpickod_b(t1, t0); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - a.val = __lsx_vpickev_h(t1, t0); - b.val = __lsx_vpickod_h(t1, t0); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - a.val = __lsx_vpickev_w(t1, t0); - b.val = __lsx_vpickod_w(t1, t0); -} - -inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - a.val = __lsx_vilvl_d(t1, t0); - b.val = __lsx_vilvh_d(t1, t0); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - const __m128i shuff0 = _v128_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - const __m128i shuff1 = _v128_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff0); - __m128i b0 = __lsx_vbitsel_v(t1, t0, shuff1); - __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); - const __m128i shuff_a = _v128_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29); - const __m128i shuff_b = _v128_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30); - const __m128i shuff_c = _v128_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31); - - a.val = __lsx_vshuf_b(t2, a0, shuff_a); - b.val = __lsx_vshuf_b(t2, b0, shuff_b); - c.val = __lsx_vshuf_b(t2, c0, shuff_c); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - const __m128i shuff0 = _v128_setr_h(0, 0, -1, 0, 0, -1, 0, 0); - const __m128i shuff1 = _v128_setr_h(0, -1, 0, 0, -1, 0, 0, -1); - - __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff1); - __m128i b0 = __lsx_vbitsel_v(t0, t1, shuff0); - __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); - - const __m128i shuff_a = _v128_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 20, 21, 26, 27); - const __m128i shuff_b = _v128_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 16, 17, 22, 23, 28, 29); - const __m128i shuff_c = _v128_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31); - - a.val = __lsx_vshuf_b(t2, a0, shuff_a); - b.val = __lsx_vshuf_b(t2, b0, shuff_b); - c.val = __lsx_vshuf_b(t2, c0, shuff_c); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - - __m128i a0 = __lsx_vpermi_w(t1, t0, 0xAC); - __m128i b0 = __lsx_vpermi_w(t1, t0, 0xC5); - __m128i c0 = __lsx_vpermi_w(t1, t0, 0x5A); - - a.val = __lsx_vextrins_w(a0, t2, 0x31); - b0 = __lsx_vshuf4i_w(b0, 0x38); - c0 = __lsx_vshuf4i_w(c0, 0x8); - b.val = __lsx_vextrins_w(b0, t2, 0x32); - c.val = __lsx_vpermi_w(t2, c0, 0xC4); -} - -inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - - a.val = __lsx_vshuf4i_d(t0, t1, 0xC); - b.val = __lsx_vshuf4i_d(t0, t2, 0x9); - c.val = __lsx_vshuf4i_d(t1, t2, 0xC); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - __m128i t3 = __lsx_vld(ptr, 48); - - __m128i ac_lo = __lsx_vpickev_b(t1, t0); - __m128i bd_lo = __lsx_vpickod_b(t1, t0); - __m128i ac_hi = __lsx_vpickev_b(t3, t2); - __m128i bd_hi = __lsx_vpickod_b(t3, t2); - - a.val = __lsx_vpickev_b(ac_hi, ac_lo); - c.val = __lsx_vpickod_b(ac_hi, ac_lo); - b.val = __lsx_vpickev_b(bd_hi, bd_lo); - d.val = __lsx_vpickod_b(bd_hi, bd_lo); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - __m128i t3 = __lsx_vld(ptr, 48); - - __m128i ac_lo = __lsx_vpickev_h(t1, t0); - __m128i bd_lo = __lsx_vpickod_h(t1, t0); - __m128i ac_hi = __lsx_vpickev_h(t3, t2); - __m128i bd_hi = __lsx_vpickod_h(t3, t2); - - a.val = __lsx_vpickev_h(ac_hi, ac_lo); - c.val = __lsx_vpickod_h(ac_hi, ac_lo); - b.val = __lsx_vpickev_h(bd_hi, bd_lo); - d.val = __lsx_vpickod_h(bd_hi, bd_lo); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) -{ - __m128i p0 = __lsx_vld(ptr, 0); - __m128i p1 = __lsx_vld(ptr, 16); - __m128i p2 = __lsx_vld(ptr, 32); - __m128i p3 = __lsx_vld(ptr, 48); - - __m128i t0 = __lsx_vilvl_w(p1, p0); - __m128i t1 = __lsx_vilvl_w(p3, p2); - __m128i t2 = __lsx_vilvh_w(p1, p0); - __m128i t3 = __lsx_vilvh_w(p3, p2); - a.val = __lsx_vilvl_d(t1, t0); - b.val = __lsx_vilvh_d(t1, t0); - c.val = __lsx_vilvl_d(t3, t2); - d.val = __lsx_vilvh_d(t3, t2); -} - -inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) -{ - __m128i t0 = __lsx_vld(ptr, 0); - __m128i t1 = __lsx_vld(ptr, 16); - __m128i t2 = __lsx_vld(ptr, 32); - __m128i t3 = __lsx_vld(ptr, 48); - - a.val = __lsx_vilvl_d(t2, t0); - b.val = __lsx_vilvh_d(t2, t0); - c.val = __lsx_vilvl_d(t3, t1); - d.val = __lsx_vilvh_d(t3, t1); -} - -////////////////////////// store interleave //////////////////////////////// - -inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_b(b.val, a.val); - __m128i v1 = __lsx_vilvh_b(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_h(b.val, a.val); - __m128i v1 = __lsx_vilvh_h(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_w(b.val, a.val); - __m128i v1 = __lsx_vilvh_w(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v0 = __lsx_vilvl_d(b.val, a.val); - __m128i v1 = __lsx_vilvh_d(b.val, a.val); - - __lsx_vst(v0, ptr, 0); - __lsx_vst(v1, ptr, 16); -} - -inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, const v_uint8x16& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); - __m128i v_c = c.val; - const __m128i shuff0 = _v128_setr_b(0, 1, 16, 2, 3, 17, 4, 5, 18, 6, 7, 19, 8, 9, 20, 10); - const __m128i shuff1 = _v128_setr_b(11, 21, 12, 13, 22, 14, 15, 23, 0, 0, 0, 0, 0, 0, 0, 0); - const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 24, 18, 19, 25, 20, 21); - const __m128i shuff3 = _v128_setr_b(26, 6, 7, 27, 8, 9, 28, 10, 11, 29, 12, 13, 30, 14, 15, 31); - __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); - - __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); - __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); - __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); - dst1 = __lsx_vshuf_b(abc, dst1, shuff2); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); -} - -inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, const v_uint16x8& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); - __m128i v_c = c.val; - const __m128i shuff0 = _v128_setr_b(0, 1, 2, 3, 16, 17, 4, 5, 6, 7, 18, 19, 8, 9, 10, 11); - const __m128i shuff1 = _v128_setr_b(20, 21, 12, 13, 14, 15, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0); - const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 24, 25, 20, 21); - const __m128i shuff3 = _v128_setr_b(6, 7, 26, 27, 8, 9, 10, 11, 28, 29, 12, 13, 14, 15, 30, 31); - __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); - - __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); - __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); - __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); - dst1 = __lsx_vshuf_b(abc, dst1, shuff2); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, const v_uint32x4& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i v_c = c.val; - __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); //a0 b0 a1 b1 - __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); //a2 b2 a3 b3 - __m128i bc_od = __lsx_vpackod_w(v_c, b.val); // b1 c1 b3 c3 - - __m128i dst0 = __lsx_vshuf4i_w(ab_lo, 0xB4); //a0 b0 b1 a1 - __m128i dst1 = __lsx_vilvl_d(ab_hi, bc_od); //b1 c1 a2 b2 - __m128i dst2 = __lsx_vpermi_w(bc_od, ab_hi, 0xE8); //a2, a3, b3, c3 - - dst0 = __lsx_vextrins_w(dst0, v_c, 0x20); - dst2 = __lsx_vextrins_w(dst2, v_c, 0x2); - __lsx_vst(dst0, ptr, 0); //a0 b0 c0 a1 - __lsx_vst(dst1, ptr, 16); //b1 c1 a2 b2 - __lsx_vst(dst2, ptr, 32); //c2 a3 b3 c3 -} - -inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i dst0 = __lsx_vilvl_d(b.val, a.val); - __m128i dst1 = __lsx_vpermi_w(a.val, c.val, 0xE4); - __m128i dst2 = __lsx_vilvh_d(c.val, b.val); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); -} - -inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, const v_uint8x16& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); - __m128i cd_lo = __lsx_vilvl_b(d.val, c.val); - __m128i cd_hi = __lsx_vilvh_b(d.val, c.val); - - __m128i dst0 = __lsx_vilvl_h(cd_lo, ab_lo); - __m128i dst1 = __lsx_vilvh_h(cd_lo, ab_lo); - __m128i dst2 = __lsx_vilvl_h(cd_hi, ab_hi); - __m128i dst3 = __lsx_vilvh_h(cd_hi, ab_hi); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - const v_uint16x8& c, const v_uint16x8& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); - __m128i cd_lo = __lsx_vilvl_h(d.val, c.val); - __m128i cd_hi = __lsx_vilvh_h(d.val, c.val); - - __m128i dst0 = __lsx_vilvl_w(cd_lo, ab_lo); - __m128i dst1 = __lsx_vilvh_w(cd_lo, ab_lo); - __m128i dst2 = __lsx_vilvl_w(cd_hi, ab_hi); - __m128i dst3 = __lsx_vilvh_w(cd_hi, ab_hi); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); - __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); - __m128i cd_lo = __lsx_vilvl_w(d.val, c.val); - __m128i cd_hi = __lsx_vilvh_w(d.val, c.val); - - __m128i dst0 = __lsx_vilvl_d(cd_lo, ab_lo); - __m128i dst1 = __lsx_vilvh_d(cd_lo, ab_lo); - __m128i dst2 = __lsx_vilvl_d(cd_hi, ab_hi); - __m128i dst3 = __lsx_vilvh_d(cd_hi, ab_hi); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, const v_uint64x2& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - __m128i dst0 = __lsx_vilvl_d(b.val, a.val); - __m128i dst2 = __lsx_vilvh_d(b.val, a.val); - __m128i dst1 = __lsx_vilvl_d(d.val, c.val); - __m128i dst3 = __lsx_vilvh_d(d.val, c.val); - - __lsx_vst(dst0, ptr, 0); - __lsx_vst(dst1, ptr, 16); - __lsx_vst(dst2, ptr, 32); - __lsx_vst(dst3, ptr, 48); -} - -#define OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, \ - _Tpvec0& c0, _Tpvec0& d0) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1); \ -} \ -inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0,\ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1); \ -} \ -inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1); \ -} - -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float32x4, float, f32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) - -// -// FP16 -// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - return v_float32x4(__lsx_vfcvtl_s_h((__m128)__lsx_vld(ptr, 0))); -#else - float CV_DECL_ALIGNED(32) buf[4]; - for (int i = 0; i < 4; i++) - buf[i] = (float)ptr[i]; - return v_float32x4((__m128)__lsx_vld(buf, 0)); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& a) -{ -#if CV_FP16 - __m128i res = (__m218i)__lsx_vfcvt_h_s(a.val, a.val); - __lsx_vstelm_d(res, ptr, 0, 0); -#else - float CV_DECL_ALIGNED(32) buf[4]; - v_store_aligned(buf, a); - for (int i = 0; i < 4; i++) - ptr[i] = hfloat(buf[i]); -#endif -} - -// -// end of FP16 -// - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_LSX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_LSX_HPP +#define OPENCV_HAL_INTRIN_LSX_HPP + +#include + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#define CV_SIMD128_FP16 0 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +/////////// Utils //////// + +inline __m128i _v128_setr_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, + char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) +{ + return (__m128i)v16i8{ v0, v1, v2, v3, v4, v5, v6, v7, + v8, v9, v10, v11, v12, v13, v14, v15 }; +} + +inline __m128i _v128_set_b(char v0, char v1, char v2, char v3, char v4, char v5, char v6, + char v7, char v8, char v9, char v10, char v11, char v12, char v13, char v14, char v15) +{ + return (__m128i)v16i8{ v15, v14, v13, v12, v11, v10, v9, v8, + v7, v6, v5, v4, v3, v2, v1, v0 }; +} + +inline __m128i _v128_setr_h(short v0, short v1, short v2, short v3, short v4, short v5, + short v6, short v7) +{ + return (__m128i)v8i16{ v0, v1, v2, v3, v4, v5, v6, v7 }; +} + +inline __m128i _v128_setr_w(int v0, int v1, int v2, int v3) +{ + return (__m128i)v4i32{ v0, v1, v2, v3 }; +} + +inline __m128i _v128_set_w(int v0, int v1, int v2, int v3) +{ + return (__m128i)v4i32{ v3, v2, v1, v0 }; +} + +inline __m128i _v128_setall_w(int v0) +{ + return __lsx_vreplgr2vr_w(v0); +} + +inline __m128i _v128_setr_d(int64 v0, int64 v1) +{ + return (__m128i)v2i64{ v0, v1 }; +} + +inline __m128i _v128_set_d(int64 v0, int64 v1) +{ + return (__m128i)v2i64{ v1, v0 }; +} + +inline __m128 _v128_setr_ps(float v0, float v1, float v2, float v3) +{ + return (__m128)v4f32{ v0, v1, v2, v3 }; +} + +inline __m128 _v128_setall_ps(float v0) +{ + return (__m128)v4f32{ v0, v0, v0, v0 }; +} + +inline __m128d _v128_setr_pd(double v0, double v1) +{ + return (__m128d)v2f64{ v0, v1 }; +} + +inline __m128d _v128_setall_pd(double v0) +{ + return (__m128d)v2f64{ v0, v0 }; +} + +inline __m128i _lsx_packus_h(const __m128i& a, const __m128i& b) +{ + return __lsx_vssrarni_bu_h(b, a, 0); +} + +inline __m128i _lsx_packs_h(const __m128i& a, const __m128i& b) +{ + return __lsx_vssrarni_b_h(b, a, 0); +} + +inline __m128i _lsx_packus_w(const __m128i& a, const __m128i& b) +{ + return __lsx_vssrarni_hu_w(b, a, 0); +} + +/////// Types /////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16}; + + v_uint8x16() {} + explicit v_uint8x16(__m128i v): val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + + uchar get0() const + { + return (uchar)__lsx_vpickve2gr_bu(val, 0); + } + + __m128i val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(__m128i v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + val = _v128_setr_b(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15); + } + + schar get0() const + { + return (schar)__lsx_vpickve2gr_b(val, 0); + } + + __m128i val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(__m128i v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); + } + + ushort get0() const + { + return (ushort)__lsx_vpickve2gr_hu(val, 0); + } + + __m128i val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(__m128i v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + val = _v128_setr_h(v0, v1, v2, v3, v4, v5, v6, v7); + } + + short get0() const + { + return (short)__lsx_vpickve2gr_h(val, 0); + } + + __m128i val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(__m128i v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + val = _v128_setr_w(v0, v1, v2, v3); + } + + unsigned get0() const + { + return (unsigned)__lsx_vpickve2gr_wu(val, 0); + } + + __m128i val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(__m128i v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + val = _v128_setr_w(v0, v1, v2, v3); + } + + int get0() const + { + return (int)__lsx_vpickve2gr_w(val, 0); + } + + __m128i val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4}; + + v_float32x4() {} + explicit v_float32x4(__m128 v) : val(v) {} + explicit v_float32x4(__m128i v) { val = *((__m128*)&v); } + v_float32x4(float v0, float v1, float v2, float v3) + { + val = _v128_setr_ps(v0, v1, v2, v3); + } + + float get0() const + { + union { int iv; float fv; } d; + d.iv = __lsx_vpickve2gr_w(val, 0); + return d.fv; + } + + int get0toint() const + { + __m128i result = __lsx_vftintrz_w_s(val); + return (int)__lsx_vpickve2gr_w(result, 0); + } + + __m128 val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2}; + + v_uint64x2() {} + explicit v_uint64x2(__m128i v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + val = _v128_setr_d(v0, v1); + } + + uint64 get0() const + { + return __lsx_vpickve2gr_du(val, 0); + } + + __m128i val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2}; + + v_int64x2() {} + explicit v_int64x2(__m128i v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + val = _v128_setr_d(v0, v1); + } + + uint64 get0() const + { + return __lsx_vpickve2gr_d(val, 0); + } + + __m128i val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2}; + + v_float64x2() {} + explicit v_float64x2(__m128d v) : val(v) {} + explicit v_float64x2(__m128i v) { val = *((__m128d*)&v); } + v_float64x2(double v0, double v1) + { + val = _v128_setr_pd(v0, v1); + } + + double get0() const + { + union { int64 iv; double fv; } d; + d.iv = __lsx_vpickve2gr_d(val, 0); + return d.fv; + } + + int64 get0toint64() const + { + __m128i result = __lsx_vftintrz_l_d(val); + return (int64)__lsx_vpickve2gr_d(result, 0); + } + + __m128d val; +}; + +////////////// Load and store operations ///////// + +#define OPENCV_HAL_IMPL_LSX_LOADSTORE(_Tpvec, _Tp) \ + inline _Tpvec v_load(const _Tp* ptr) \ + { return _Tpvec(__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_aligned(const _Tp* ptr) \ + { return _Tpvec(__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_low(const _Tp* ptr) \ + { return _Tpvec(__lsx_vldrepl_d(ptr, 0)); } \ + inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ + __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ + return _Tpvec(__lsx_vilvl_d(vh, vl)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst(a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ + { \ + if ( mode == hal::STORE_UNALIGNED) \ + __lsx_vst(a.val, ptr, 0); \ + else if ( mode == hal::STORE_ALIGNED_NOCACHE) \ + __lsx_vst(a.val, ptr, 0); \ + else \ + __lsx_vst(a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d(a.val, ptr, 0, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d(a.val, ptr, 0, 1); } \ + +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint8x16, uchar) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int8x16, schar) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint16x8, ushort) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int16x8, short) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint32x4, unsigned) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int32x4, int) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_uint64x2, uint64) +OPENCV_HAL_IMPL_LSX_LOADSTORE(v_int64x2, int64) + +#define OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(_Tpvec, _Tp, halfreg) \ + inline _Tpvec v_load(const _Tp* ptr) \ + { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_aligned(const _Tp* ptr) \ + { return _Tpvec((halfreg)__lsx_vld(ptr, 0)); } \ + inline _Tpvec v_load_low(const _Tp* ptr) \ + { return _Tpvec((halfreg)__lsx_vldrepl_d(ptr, 0)); } \ + inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ + { \ + __m128i vl = __lsx_vldrepl_d(ptr0, 0); \ + __m128i vh = __lsx_vldrepl_d(ptr1, 0); \ + return _Tpvec((halfreg)__lsx_vilvl_d(vh, vl)); \ + } \ + inline void v_store(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst((__m128i)a.val, ptr, 0); } \ + inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst((__m128i)a.val, ptr, 0); } \ + inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vst((__m128i)a.val, ptr, 0); } \ + inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode)\ + { \ + if( mode == hal::STORE_UNALIGNED) \ + __lsx_vst((__m128i)a.val, ptr, 0); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE) \ + __lsx_vst((__m128i)a.val, ptr, 0); \ + else \ + __lsx_vst((__m128i)a.val, ptr, 0); \ + } \ + inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 0); } \ + inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ + { __lsx_vstelm_d((__m128i)a.val, ptr, 0, 1); } \ + +OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float32x4, float, __m128) +OPENCV_HAL_IMPL_LSX_LOADSTORE_FLT(v_float64x2, double, __m128d) + +inline __m128i _lsx_128_castps_si128(const __m128& v) +{ return __m128i(v); } + +inline __m128i _lsx_128_castpd_si128(const __m128d& v) +{ return __m128i(v); } + +#define OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, _Tpvecf, suffix, cast) \ + inline _Tpvec v_reinterpret_as_##suffix(const _Tpvecf& a) \ + { return _Tpvec(cast(a.val)); } + +#define OPENCV_HAL_IMPL_LSX_INIT(_Tpvec, _Tp, suffix, ssuffix, ctype_s) \ + inline _Tpvec v_setzero_##suffix() \ + { return _Tpvec(__lsx_vldi(0)); } \ + inline _Tpvec v_setall_##suffix(_Tp v) \ + { return _Tpvec(__lsx_vreplgr2vr_##ssuffix((ctype_s)v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, OPENCV_HAL_NOP) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float32x4, suffix, _lsx_128_castps_si128) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_float64x2, suffix, _lsx_128_castpd_si128) \ + +OPENCV_HAL_IMPL_LSX_INIT(v_uint8x16, uchar, u8, b, int) +OPENCV_HAL_IMPL_LSX_INIT(v_int8x16, schar, s8, b, int) +OPENCV_HAL_IMPL_LSX_INIT(v_uint16x8, ushort, u16, h, int) +OPENCV_HAL_IMPL_LSX_INIT(v_int16x8, short, s16, h, int) +OPENCV_HAL_IMPL_LSX_INIT(v_uint32x4, unsigned, u32, w, int) +OPENCV_HAL_IMPL_LSX_INIT(v_int32x4, int, s32, w, int) +OPENCV_HAL_IMPL_LSX_INIT(v_uint64x2, uint64, u64, d, long int) +OPENCV_HAL_IMPL_LSX_INIT(v_int64x2, int64, s64, d, long int) + +inline __m128 _lsx_128_castsi128_ps(const __m128i &v) +{ return __m128(v); } + +inline __m128d _lsx_128_castsi128_pd(const __m128i &v) +{ return __m128d(v); } + +#define OPENCV_HAL_IMPL_LSX_INIT_FLT(_Tpvec, _Tp, suffix, zsuffix, cast) \ + inline _Tpvec v_setzero_##suffix() \ + { return _Tpvec(__lsx_vldi(0)); } \ + inline _Tpvec v_setall_##suffix(_Tp v) \ + { return _Tpvec(_v128_setall_##zsuffix(v)); } \ + template <> inline _Tpvec v_setzero_() \ + { return v_setzero_##suffix(); } \ + template <> inline _Tpvec v_setall_(_Tp v) \ + { return v_setall_##suffix(v); } \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint8x16, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int8x16, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint16x8, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int16x8, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint32x4, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int32x4, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_uint64x2, suffix, cast) \ + OPENCV_HAL_IMPL_LSX_CAST(_Tpvec, v_int64x2, suffix, cast) \ + +OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float32x4, float, f32, ps, _lsx_128_castsi128_ps) +OPENCV_HAL_IMPL_LSX_INIT_FLT(v_float64x2, double, f64, pd, _lsx_128_castsi128_pd) + +inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) +{ return a; } +inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) +{ return v_float32x4(_lsx_128_castps_si128(__m128(a.val))); } + +inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) +{ return a; } +inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) +{ return v_float64x2(_lsx_128_castpd_si128(__m128d(a.val))); } + +//////////////// Variant Value reordering /////////////// + +// unpacks +#define OPENCV_HAL_IMPL_LSX_UNPACK(_Tpvec, suffix) \ + inline _Tpvec v128_unpacklo(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vilvl_##suffix(__m128i(b.val), __m128i(a.val))); } \ + inline _Tpvec v128_unpackhi(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vilvh_##suffix(__m128i(b.val), __m128i(a.val))); } \ + +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint8x16, b) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int8x16, b) +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint16x8, h) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int16x8, h) +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint32x4, w) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int32x4, w) +OPENCV_HAL_IMPL_LSX_UNPACK(v_uint64x2, d) +OPENCV_HAL_IMPL_LSX_UNPACK(v_int64x2, d) +OPENCV_HAL_IMPL_LSX_UNPACK(v_float32x4, w) +OPENCV_HAL_IMPL_LSX_UNPACK(v_float64x2, d) + +//ZIP +#define OPENCV_HAL_IMPL_LSX_ZIP(_Tpvec) \ + inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ + { return (_Tpvec)__lsx_vilvl_d((__m128i)b.val, (__m128i)a.val); } \ + inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ + { return (_Tpvec)__lsx_vilvh_d((__m128i)b.val, (__m128i)a.val); } \ + inline void v_recombine(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ + { \ + __m128i a1 = (__m128i)a.val, b1 = (__m128i)b.val; \ + c = _Tpvec(__lsx_vilvl_d(b1, a1)); \ + d = _Tpvec(__lsx_vilvh_d(b1, a1)); \ + } \ + inline void v_zip(const _Tpvec& a, const _Tpvec& b, \ + _Tpvec& ab0, _Tpvec& ab1) \ + { \ + ab0 = v128_unpacklo(a, b); \ + ab1 = v128_unpackhi(a, b); \ + } + +OPENCV_HAL_IMPL_LSX_ZIP(v_uint8x16) +OPENCV_HAL_IMPL_LSX_ZIP(v_int8x16) +OPENCV_HAL_IMPL_LSX_ZIP(v_uint16x8) +OPENCV_HAL_IMPL_LSX_ZIP(v_int16x8) +OPENCV_HAL_IMPL_LSX_ZIP(v_uint32x4) +OPENCV_HAL_IMPL_LSX_ZIP(v_int32x4) +OPENCV_HAL_IMPL_LSX_ZIP(v_uint64x2) +OPENCV_HAL_IMPL_LSX_ZIP(v_int64x2) +OPENCV_HAL_IMPL_LSX_ZIP(v_float32x4) +OPENCV_HAL_IMPL_LSX_ZIP(v_float64x2) + +////////// Arithmetic, bitwise and comparison operations ///////// + +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_LSX_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint8x16, __lsx_vsadd_bu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint8x16, __lsx_vssub_bu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int8x16, __lsx_vsadd_b) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int8x16, __lsx_vssub_b) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint16x8, __lsx_vsadd_hu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint16x8, __lsx_vssub_hu) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int16x8, __lsx_vsadd_h) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int16x8, __lsx_vssub_h) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint32x4, __lsx_vadd_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint32x4, __lsx_vsub_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_uint32x4, __lsx_vmul_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int32x4, __lsx_vadd_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int32x4, __lsx_vsub_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_int32x4, __lsx_vmul_w) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_uint64x2, __lsx_vadd_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_uint64x2, __lsx_vsub_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_int64x2, __lsx_vadd_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_int64x2, __lsx_vsub_d) + +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float32x4, __lsx_vfadd_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float32x4, __lsx_vfsub_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float32x4, __lsx_vfmul_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float32x4, __lsx_vfdiv_s) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_add, v_float64x2, __lsx_vfadd_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_sub, v_float64x2, __lsx_vfsub_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_mul, v_float64x2, __lsx_vfmul_d) +OPENCV_HAL_IMPL_LSX_BIN_OP(v_div, v_float64x2, __lsx_vfdiv_d) + +// saturating multiply 8-bit, 16-bit +inline v_uint8x16 v_mul(const v_uint8x16& a, const v_uint8x16& b) +{ + v_uint16x8 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_int8x16 v_mul(const v_int8x16& a, const v_int8x16& b) +{ + v_int16x8 c, d; + v_mul_expand(a, b, c, d); + return v_pack(c, d); +} +inline v_uint16x8 v_mul(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i pev = __lsx_vmulwev_w_hu(a0, b0); + __m128i pod = __lsx_vmulwod_w_hu(a0, b0); + __m128i pl = __lsx_vilvl_w(pod, pev); + __m128i ph = __lsx_vilvh_w(pod, pev); + return (v_uint16x8)__lsx_vssrlrni_hu_w(ph, pl, 0); +} +inline v_int16x8 v_mul(const v_int16x8& a, const v_int16x8& b) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i pev = __lsx_vmulwev_w_h(a0, b0); + __m128i pod = __lsx_vmulwod_w_h(a0, b0); + __m128i pl = __lsx_vilvl_w(pod, pev); + __m128i ph = __lsx_vilvh_w(pod, pev); + return (v_int16x8)__lsx_vssrarni_h_w(ph, pl, 0); +} + +/** Non-saturating arithmetics **/ + +#define OPENCV_HAL_IMPL_LSX_BIN_FUNC(func, _Tpvec, intrin) \ + inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin(a.val, b.val)); } \ + +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint8x16, __lsx_vadd_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int8x16, __lsx_vadd_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_uint16x8, __lsx_vadd_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_add_wrap, v_int16x8, __lsx_vadd_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint8x16, __lsx_vsub_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int8x16, __lsx_vsub_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_uint16x8, __lsx_vsub_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_sub_wrap, v_int16x8, __lsx_vsub_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_uint16x8, __lsx_vmul_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_mul_wrap, v_int16x8, __lsx_vmul_h) + +inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); + __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); + return v_uint8x16(__lsx_vpackev_b(p1, p0)); +} + +inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +// Multiply and expand +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_h_bu(a0, b0); + __m128i p1 = __lsx_vmulwod_h_bu(a0, b0); + c.val = __lsx_vilvl_h(p1, p0); + d.val = __lsx_vilvh_h(p1, p0); +} +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_h_b(a0, b0); + __m128i p1 = __lsx_vmulwod_h_b(a0, b0); + c.val = __lsx_vilvl_h(p1, p0); + d.val = __lsx_vilvh_h(p1, p0); +} +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_w_h(a0, b0); + __m128i p1 = __lsx_vmulwod_w_h(a0, b0); + c.val = __lsx_vilvl_w(p1, p0); + d.val = __lsx_vilvh_w(p1, p0); +} +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_w_hu(a0, b0); + __m128i p1 = __lsx_vmulwod_w_hu(a0, b0); + c.val = __lsx_vilvl_w(p1, p0); + d.val = __lsx_vilvh_w(p1, p0); +} +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + __m128i a0 = a.val, b0 = b.val; + __m128i p0 = __lsx_vmulwev_d_wu(a0, b0); + __m128i p1 = __lsx_vmulwod_d_wu(a0, b0); + c.val = __lsx_vilvl_d(p1, p0); + d.val = __lsx_vilvh_d(p1, p0); +} +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ return v_int16x8(__lsx_vmuh_h(a.val, b.val)); } +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint16x8(__lsx_vmuh_hu(a.val, b.val)); } + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_LSX_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ + inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ + { return _Tpsvec(__lsx_vsll_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ + { return _Tpuvec(__lsx_vsrl_##suffix(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ + { return _Tpsvec(srai(a.val, __lsx_vreplgr2vr_##suffix(imm))); } \ + template \ + inline _Tpuvec v_shl(const _Tpuvec& a) \ + { return _Tpuvec(__lsx_vslli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shl(const _Tpsvec& a) \ + { return _Tpsvec(__lsx_vslli_##suffix(a.val, imm)); } \ + template \ + inline _Tpuvec v_shr(const _Tpuvec& a) \ + { return _Tpuvec(__lsx_vsrli_##suffix(a.val, imm)); } \ + template \ + inline _Tpsvec v_shr(const _Tpsvec& a) \ + { return _Tpsvec(__lsx_vsrai_##suffix(a.val, imm)); } \ + +OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint16x8, v_int16x8, h, __lsx_vsra_h) +OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint32x4, v_int32x4, w, __lsx_vsra_w) +OPENCV_HAL_IMPL_LSX_SHIFT_OP(v_uint64x2, v_int64x2, d, __lsx_vsra_d) + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_LSX_LOGIC_OP(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_LSX_BIN_OP(v_and, _Tpvec, __lsx_vand_##suffix) \ + OPENCV_HAL_IMPL_LSX_BIN_OP(v_or, _Tpvec, __lsx_vor_##suffix) \ + OPENCV_HAL_IMPL_LSX_BIN_OP(v_xor, _Tpvec, __lsx_vxor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lsx_vnori_b(a.val, 0)); } \ + +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint8x16, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int8x16, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint16x8, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int16x8, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint32x4, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int32x4, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_uint64x2, v) +OPENCV_HAL_IMPL_LSX_LOGIC_OP(v_int64x2, v) + +#define OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(bin_op, _Tpvec, intrin, cast) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(intrin((__m128i)(a.val), (__m128i)(b.val))); } + +#define OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(_Tpvec, cast) \ + OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_and, _Tpvec, __lsx_vand_v, cast) \ + OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_or, _Tpvec, __lsx_vor_v, cast) \ + OPENCV_HAL_IMPL_LSX_FLOAT_BIN_OP(v_xor, _Tpvec, __lsx_vxor_v, cast) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { return _Tpvec(__lsx_vnori_b((__m128i)(a.val), 0)); } \ + +OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float32x4, _lsx_128_castsi128_ps) +OPENCV_HAL_IMPL_LSX_FLOAT_LOGIC_OP(v_float64x2, _lsx_128_castsi128_pd) + +/** Select **/ +#define OPENCV_HAL_IMPL_LSX_SELECT(_Tpvec) \ + inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vbitsel_v(b.val, a.val, mask.val)); } \ + +OPENCV_HAL_IMPL_LSX_SELECT(v_uint8x16) +OPENCV_HAL_IMPL_LSX_SELECT(v_int8x16) +OPENCV_HAL_IMPL_LSX_SELECT(v_uint16x8) +OPENCV_HAL_IMPL_LSX_SELECT(v_int16x8) +OPENCV_HAL_IMPL_LSX_SELECT(v_uint32x4) +OPENCV_HAL_IMPL_LSX_SELECT(v_int32x4) + +inline v_float32x4 v_select(const v_float32x4 &mask, const v_float32x4 &a, const v_float32x4 &b) +{ return v_float32x4(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } +inline v_float64x2 v_select(const v_float64x2 &mask, const v_float64x2 &a, const v_float64x2 &b) +{ return v_float64x2(__lsx_vbitsel_v((__m128i)b.val, (__m128i)a.val, (__m128i)mask.val)); } + +/** Comparison **/ +#define OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpvec) \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } \ + inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ + { return v_gt(b, a); } \ + inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_lt(a, b)); } \ + inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ + { return v_ge(b, a); } \ + +#define OPENCV_HAL_IMPL_LSX_CMP_OP_INT(_Tpuvec, _Tpsvec, suffix, usuffix) \ + inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(__lsx_vseq_##suffix(a.val, b.val)); } \ + inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ + { return _Tpuvec(__lsx_vslt_##usuffix(b.val, a.val)); } \ + inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lsx_vseq_##suffix(a.val, b.val)); } \ + inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ + { return _Tpsvec(__lsx_vslt_##suffix(b.val, a.val)); } \ + OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpuvec) \ + OPENCV_HAL_IMPL_LSX_CMP_OP_OV(_Tpsvec) + +OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint8x16, v_int8x16, b, bu) +OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint16x8, v_int16x8, h, hu) +OPENCV_HAL_IMPL_LSX_CMP_OP_INT(v_uint32x4, v_int32x4, w, wu) + +#define OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(_Tpvec, suffix) \ + inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_vseq_##suffix(a.val, b.val)); } \ + inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ + { return v_not(v_eq(a, b)); } + +OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_uint64x2, d) +OPENCV_HAL_IMPL_LSX_CMP_OP_64BIT(v_int64x2, d) + +#define OPENCV_HAL_IMPL_LSX_CMP_FLT(bin_op, suffix, _Tpvec, ssuffix) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { return _Tpvec(__lsx_##suffix##_##ssuffix(a.val, b.val)); } \ + +#define OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(_Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_eq, vfcmp_ceq, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_ne, vfcmp_cne, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_lt, vfcmp_clt, _Tpvec, ssuffix) \ + OPENCV_HAL_IMPL_LSX_CMP_FLT(v_le, vfcmp_cle, _Tpvec, ssuffix) \ + +OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float32x4, s) +OPENCV_HAL_IMPL_LSX_CMP_OP_FLT(v_float64x2, d) + +inline v_float32x4 v_gt(const v_float32x4 &a, const v_float32x4 &b) +{ return v_float32x4(__lsx_vfcmp_clt_s(b.val, a.val)); } + +inline v_float32x4 v_ge(const v_float32x4 &a, const v_float32x4 &b) +{ return v_float32x4(__lsx_vfcmp_cle_s(b.val, a.val)); } + +inline v_float64x2 v_gt(const v_float64x2 &a, const v_float64x2 &b) +{ return v_float64x2(__lsx_vfcmp_clt_d(b.val, a.val)); } + +inline v_float64x2 v_ge(const v_float64x2 &a, const v_float64x2 &b) +{ return v_float64x2(__lsx_vfcmp_cle_d(b.val, a.val)); } + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(__lsx_vfcmp_cor_s(a.val, a.val)); } + +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(__lsx_vfcmp_cor_d(a.val, a.val)); } + +/** min/max **/ +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint8x16, __lsx_vmin_bu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint8x16, __lsx_vmax_bu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int8x16, __lsx_vmin_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int8x16, __lsx_vmax_b) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint16x8, __lsx_vmin_hu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint16x8, __lsx_vmax_hu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int16x8, __lsx_vmin_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int16x8, __lsx_vmax_h) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_uint32x4, __lsx_vmin_wu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_uint32x4, __lsx_vmax_wu) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_int32x4, __lsx_vmin_w) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_int32x4, __lsx_vmax_w) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float32x4, __lsx_vfmin_s) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float32x4, __lsx_vfmax_s) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_min, v_float64x2, __lsx_vfmin_d) +OPENCV_HAL_IMPL_LSX_BIN_FUNC(v_max, v_float64x2, __lsx_vfmax_d) + +template 16)), + bool is_first = (imm == 0), + bool is_half = (imm == 8), + bool is_second = (imm == 16), + bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> +class v_lsx_palignr_u8_class; + +template +class v_lsx_palignr_u8_class; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + CV_UNUSED(b); + return a; + } +}; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + return __lsx_vshuf4i_d(a, b, 0x9); + } +}; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + CV_UNUSED(a); + return b; + } +}; + +template +class v_lsx_palignr_u8_class +{ +public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + enum { imm2 = (sizeof(__m128i) - imm) }; + return __lsx_vor_v(__lsx_vbsrl_v(a, imm), __lsx_vbsll_v(b, imm2)); + } +}; + +template +inline __m128i v_lsx_palignr_u8(const __m128i& a, const __m128i& b) +{ + CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_lsx_palignr_u8"); + return v_lsx_palignr_u8_class()(a, b); +} +/** Rotate **/ +#define OPENCV_HAL_IMPL_LSX_ROTATE_CAST(_Tpvec, cast) \ + template \ + inline _Tpvec v_rotate_right(const _Tpvec &a) \ + { \ + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ + __m128i ret = __lsx_vbsrl_v((__m128i)a.val, imm2); \ + return _Tpvec(cast(ret)); \ + } \ + template \ + inline _Tpvec v_rotate_left(const _Tpvec &a) \ + { \ + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ + __m128i ret = __lsx_vbsll_v((__m128i)a.val, imm2); \ + return _Tpvec(cast(ret)); \ + } \ + template \ + inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type))}; \ + return _Tpvec(cast(v_lsx_palignr_u8((__m128i)a.val, (__m128i)b.val))); \ + } \ + template \ + inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ + { \ + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type))}; \ + return _Tpvec(cast(v_lsx_palignr_u8((__m128i)b.val, (__m128i)a.val))); \ + } + +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint8x16, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int8x16, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint16x8, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int16x8, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint32x4, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int32x4, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_uint64x2, OPENCV_HAL_NOP) \ +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_int64x2, OPENCV_HAL_NOP) \ + +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float32x4, _lsx_128_castsi128_ps) +OPENCV_HAL_IMPL_LSX_ROTATE_CAST(v_float64x2, _lsx_128_castsi128_pd) + +/** Rverse **/ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + __m128i vec = __lsx_vshuf4i_b(a.val, 0x1B); + return v_uint8x16(__lsx_vshuf4i_w(vec, 0x1B)); +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + __m128i vec = __lsx_vshuf4i_h(a.val, 0x1B); + return v_uint16x8(__lsx_vshuf4i_w(vec, 0x4E)); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ return v_uint32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_int32x4(__lsx_vshuf4i_w(a.val, 0x1B)); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ return v_uint64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_int64x2(__lsx_vshuf4i_w(a.val, 0x4E)); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +////////////// Reduce and mask //////////// + +/** Reduce **/ +// this function is return a[0]+a[1]+...+a[31] +inline unsigned v_reduce_sum(const v_uint8x16& a) +{ + __m128i t1 = __lsx_vhaddw_hu_bu(a.val, a.val); + __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); + __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); + __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); + return (unsigned)__lsx_vpickve2gr_w(t4, 0); +} + +inline int v_reduce_sum(const v_int8x16 &a) +{ + __m128i t1 = __lsx_vhaddw_h_b(a.val, a.val); + __m128i t2 = __lsx_vhaddw_w_h(t1, t1); + __m128i t3 = __lsx_vhaddw_d_w(t2, t2); + __m128i t4 = __lsx_vhaddw_q_d(t3, t3); + return (int)__lsx_vpickve2gr_w(t4, 0); +} + +#define OPENCV_HAL_IMPL_LSX_REDUCE_16(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec& a) \ + { \ + __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ + val = intrin(val, __lsx_vbsrl_v(val, 4)); \ + val = intrin(val, __lsx_vbsrl_v(val, 2)); \ + val = intrin(val, __lsx_vbsrl_v(val, 1)); \ + return (sctype)__lsx_vpickve2gr_b(val, 0); \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, min, __lsx_vmin_bu) +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_uint8x16, uchar, max, __lsx_vmax_bu) +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, min, __lsx_vmin_b) +OPENCV_HAL_IMPL_LSX_REDUCE_16(v_int8x16, schar, max, __lsx_vmax_b) + +#define OPENCV_HAL_IMPL_LSX_REDUCE_8(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec &a) \ + { \ + __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ + val = intrin(val, __lsx_vbsrl_v(val, 4)); \ + val = intrin(val, __lsx_vbsrl_v(val, 2)); \ + return (sctype)__lsx_vpickve2gr_h(val, 0); \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, min, __lsx_vmin_hu) +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_uint16x8, ushort, max, __lsx_vmax_hu) +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, min, __lsx_vmin_h) +OPENCV_HAL_IMPL_LSX_REDUCE_8(v_int16x8, short, max, __lsx_vmax_h) + +#define OPENCV_HAL_IMPL_LSX_REDUCE_4(_Tpvec, sctype, func, intrin) \ + inline sctype v_reduce_##func(const _Tpvec &a) \ + { \ + __m128i val = intrin(a.val, __lsx_vbsrl_v(a.val, 8)); \ + val = intrin(val, __lsx_vbsrl_v(val, 4)); \ + return (sctype)__lsx_vpickve2gr_w(val, 0); \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, min, __lsx_vmin_wu) +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_uint32x4, unsigned, max, __lsx_vmax_wu) +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, min, __lsx_vmin_w) +OPENCV_HAL_IMPL_LSX_REDUCE_4(v_int32x4, int, max, __lsx_vmax_w) + +#define OPENCV_HAL_IMPL_LSX_REDUCE_FLT(func, intrin) \ + inline float v_reduce_##func(const v_float32x4 &a) \ + { \ + __m128 val = a.val; \ + val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 8)); \ + val = intrin(val, (__m128)__lsx_vbsrl_v((__m128i)val, 4)); \ + float *fval = (float*)&val; \ + return fval[0]; \ + } + +OPENCV_HAL_IMPL_LSX_REDUCE_FLT(min, __lsx_vfmin_s) +OPENCV_HAL_IMPL_LSX_REDUCE_FLT(max, __lsx_vfmax_s) + +inline int v_reduce_sum(const v_int32x4 &a) +{ + __m128i t1 = __lsx_vhaddw_d_w(a.val, a.val); + __m128i t2 = __lsx_vhaddw_q_d(t1, t1); + return (int)__lsx_vpickve2gr_w(t2, 0); +} + +inline unsigned v_reduce_sum(const v_uint32x4 &a) +{ + __m128i t1 = __lsx_vhaddw_du_wu(a.val, a.val); + __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); + return (int)__lsx_vpickve2gr_w(t2, 0); +} + +inline int v_reduce_sum(const v_int16x8 &a) +{ + __m128i t1 = __lsx_vhaddw_w_h(a.val, a.val); + __m128i t2 = __lsx_vhaddw_d_w(t1, t1); + __m128i t3 = __lsx_vhaddw_q_d(t2, t2); + return (int)__lsx_vpickve2gr_w(t3, 0); +} + +inline unsigned v_reduce_sum(const v_uint16x8 &a) +{ + __m128i t1 = __lsx_vhaddw_wu_hu(a.val, a.val); + __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); + __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); + return (int)__lsx_vpickve2gr_w(t3, 0); +} + +inline float v_reduce_sum(const v_float32x4 &a) +{ + __m128i val = (__m128i)a.val; + val = __lsx_vbsrl_v(val, 8); + __m128 result = __lsx_vfadd_s(a.val, (__m128)val); + float *pa = (float*)&result; + return (float)(pa[0] + pa[1]); +} + +inline uint64 v_reduce_sum(const v_uint64x2 &a) +{ + __m128i t0 = __lsx_vhaddw_qu_du(a.val, a.val); + return (uint64)__lsx_vpickve2gr_du(t0, 0); +} + +inline int64 v_reduce_sum(const v_int64x2 &a) +{ + __m128i t0 = __lsx_vhaddw_q_d(a.val, a.val); + return (int64)__lsx_vpickve2gr_d(t0, 0); +} + +inline double v_reduce_sum(const v_float64x2 &a) +{ + double *pa = (double*)&a; + return pa[0] + pa[1]; +} + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + __m128i a0 = (__m128i)a.val; + __m128i b0 = (__m128i)b.val; + __m128i c0 = (__m128i)c.val; + __m128i d0 = (__m128i)d.val; + __m128i ac_l = __lsx_vilvl_w(c0, a0); + __m128i ac_h = __lsx_vilvh_w(c0, a0); + __m128i bd_l = __lsx_vilvl_w(d0, b0); + __m128i bd_h = __lsx_vilvh_w(d0, b0); + __m128 ac = __lsx_vfadd_s((__m128)ac_l, (__m128)ac_h); + __m128 bd = __lsx_vfadd_s((__m128)bd_l, (__m128)bd_h); + return v_float32x4(__lsx_vfadd_s((__m128)__lsx_vilvl_w((__m128i)bd, (__m128i)ac), + (__m128)__lsx_vilvh_w((__m128i)bd, (__m128i)ac))); +} + +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + __m128i t0 = __lsx_vabsd_b(a.val, b.val); + __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); + __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); + __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); + __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); + return (unsigned)__lsx_vpickve2gr_w(t4, 0); +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i t0 = __lsx_vabsd_bu(a.val, b.val); + __m128i t1 = __lsx_vhaddw_hu_bu(t0, t0); + __m128i t2 = __lsx_vhaddw_wu_hu(t1, t1); + __m128i t3 = __lsx_vhaddw_du_wu(t2, t2); + __m128i t4 = __lsx_vhaddw_qu_du(t3, t3); + return (unsigned)__lsx_vpickve2gr_w(t4, 0); +} + +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i t0 = __lsx_vabsd_hu(a.val, b.val); + __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); + __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); + __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); + return (unsigned)__lsx_vpickve2gr_w(t3, 0); +} + +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + __m128i t0 = __lsx_vabsd_h(a.val, b.val); + __m128i t1 = __lsx_vhaddw_wu_hu(t0, t0); + __m128i t2 = __lsx_vhaddw_du_wu(t1, t1); + __m128i t3 = __lsx_vhaddw_qu_du(t2, t2); + return (unsigned)__lsx_vpickve2gr_w(t3, 0); +} + +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + __m128i t0 = __lsx_vabsd_wu(a.val, b.val); + __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); + __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); + return (unsigned)__lsx_vpickve2gr_w(t2, 0); +} + +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + __m128i t0 = __lsx_vabsd_w(a.val, b.val); + __m128i t1 = __lsx_vhaddw_du_wu(t0, t0); + __m128i t2 = __lsx_vhaddw_qu_du(t1, t1); + return (unsigned)__lsx_vpickve2gr_w(t2, 0); +} + +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 a_b = v_sub(a, b); + return v_reduce_sum(v_float32x4((__m128i)a_b.val & __lsx_vreplgr2vr_w(0x7fffffff))); +} + +/** Popcount **/ +#define OPENCV_HAL_IMPL_LSX_POPCOUNT(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_popcount(const _Tp& a) \ +{ return _Tpvec(__lsx_vpcnt_##suffix(a.val)); } + +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_uint8x16, b); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint8x16, v_int8x16, b); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_uint16x8, h); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint16x8, v_int16x8, h); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_uint32x4, w); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint32x4, v_int32x4, w); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_uint64x2, d); +OPENCV_HAL_IMPL_LSX_POPCOUNT(v_uint64x2, v_int64x2, d); + +/** Mask **/ +#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ +inline tt reinterpret_int(ft x) { union {ft l; tt i;} v; v.l = x; return v.i; } +OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) + +inline int v_signmask(const v_int8x16& a) +{ + __m128i result = __lsx_vmskltz_b(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_uint8x16& a) +{ return v_signmask(v_reinterpret_as_s8(a)) ;} + +inline int v_signmask(const v_int16x8 &a) +{ + __m128i result = __lsx_vmskltz_h(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_uint16x8 &a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_uint32x4& a) +{ + __m128i result = __lsx_vmskltz_w(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_int32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } + +inline int v_signmask(const v_uint64x2& a) +{ + __m128i result = __lsx_vmskltz_d(a.val); + return __lsx_vpickve2gr_w(result, 0); +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } + +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(*(v_int32x4*)(&a)); } + +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(*(v_int64x2*)(&a)); } + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +/** Checks **/ +#define OPENCV_HAL_IMPL_LSX_CHECK(_Tpvec, allmask) \ + inline bool v_check_all(const _Tpvec& a) { return v_signmask(a) == allmask; } \ + inline bool v_check_any(const _Tpvec& a) { return v_signmask(a) != 0; } +OPENCV_HAL_IMPL_LSX_CHECK(v_uint8x16, 65535) +OPENCV_HAL_IMPL_LSX_CHECK(v_int8x16, 65535) +OPENCV_HAL_IMPL_LSX_CHECK(v_uint16x8, 255); +OPENCV_HAL_IMPL_LSX_CHECK(v_int16x8, 255); +OPENCV_HAL_IMPL_LSX_CHECK(v_uint32x4, 15) +OPENCV_HAL_IMPL_LSX_CHECK(v_int32x4, 15) +OPENCV_HAL_IMPL_LSX_CHECK(v_uint64x2, 3) +OPENCV_HAL_IMPL_LSX_CHECK(v_int64x2, 3) +OPENCV_HAL_IMPL_LSX_CHECK(v_float32x4, 15) +OPENCV_HAL_IMPL_LSX_CHECK(v_float64x2, 3) + +///////////// Other math ///////////// + +/** Some frequent operations **/ +#define OPENCV_HAL_IMPL_LSX_MULADD(_Tpvec, suffix) \ + inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ + { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec &b, const _Tpvec& c) \ + { return _Tpvec(__lsx_vfmadd_##suffix(a.val, b.val, c.val)); } \ + inline _Tpvec v_sqrt(const _Tpvec& x) \ + { return _Tpvec(__lsx_vfsqrt_##suffix(x.val)); } \ + inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_fma(a, a, v_mul(b, b)); } \ + inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ + { return v_sqrt(v_fma(a, a, v_mul(b, b))); } + +OPENCV_HAL_IMPL_LSX_MULADD(v_float32x4, s) +OPENCV_HAL_IMPL_LSX_MULADD(v_float64x2, d) + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ return v_int32x4(__lsx_vmadd_w(c.val, a.val, b.val)); } + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ return v_fma(a, b, c); } + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + return v_float32x4(__lsx_vfrsqrt_s(x.val)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + return v_float64x2(__lsx_vfrsqrt_d(x.val)); +} + +/** Absolute values **/ +#define OPENCV_HAL_IMPL_LSX_ABS(_Tpvec, suffix) \ + inline v_u##_Tpvec v_abs(const v_##_Tpvec& x) \ + { return v_u##_Tpvec(__lsx_vabsd_##suffix(x.val, __lsx_vldi(0))); } + +OPENCV_HAL_IMPL_LSX_ABS(int8x16, b) +OPENCV_HAL_IMPL_LSX_ABS(int16x8, h) +OPENCV_HAL_IMPL_LSX_ABS(int32x4, w) + +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(*((__m128i*)&x) & __lsx_vreplgr2vr_w(0x7fffffff)); } +inline v_float64x2 v_abs(const v_float64x2& x) +{ return v_float64x2(*((__m128i*)&x) & __lsx_vreplgr2vr_d(0x7fffffffffffffff)); } + +/** Absolute difference **/ + +inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) +{ return (v_uint8x16)__lsx_vabsd_bu(a.val, b.val); } +inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) +{ return (v_uint16x8)__lsx_vabsd_hu(a.val, b.val); } +inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) +{ return (v_uint32x4)__lsx_vabsd_wu(a.val, b.val); } + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ return (v_uint8x16)__lsx_vabsd_b(a.val, b.val); } +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ return (v_uint16x8)__lsx_vabsd_h(a.val, b.val); } +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ return (v_uint32x4)__lsx_vabsd_w(a.val, b.val); } + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ return v_abs(v_sub(a, b)); } + +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ return v_abs(v_sub(a, b)); } + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub(a, b); + v_int8x16 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); +} +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +///////// Conversions ///////// + +/** Rounding **/ +inline v_int32x4 v_round(const v_float32x4& a) +{ return v_int32x4(__lsx_vftint_w_s(a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a) +{ return v_int32x4(__lsx_vftint_w_d(a.val, a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ return v_int32x4(__lsx_vftint_w_d(b.val, a.val)); } + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(__lsx_vftintrz_w_s(a.val)); } + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ return v_int32x4(__lsx_vftintrz_w_d(a.val, a.val)); } + +inline v_int32x4 v_floor(const v_float32x4& a) +{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrm_s(a.val)))); } + +inline v_int32x4 v_floor(const v_float64x2& a) +{ return v_trunc(v_float64x2(__lsx_vfrintrm_d(a.val))); } + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ return v_int32x4(__lsx_vftintrz_w_s(__m128(__lsx_vfrintrp_s(a.val)))); } + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ return v_trunc(v_float64x2(__lsx_vfrintrp_d(a.val))); } + +/** To float **/ +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ return v_float32x4(__lsx_vffint_s_w(a.val)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ return v_float32x4(__lsx_vfcvt_s_d(a.val, a.val)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ return v_float32x4(__lsx_vfcvt_s_d(b.val, a.val)); } + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ return v_float64x2(__lsx_vffintl_d_w(a.val)); } + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ return v_float64x2(__lsx_vffinth_d_w(a.val)); } + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ return v_float64x2(__lsx_vfcvtl_d_s(a.val)); } + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ return v_float64x2(__lsx_vfcvth_d_s(a.val)); } + +inline v_float64x2 v_cvt_f64(const v_int64x2& v) +{ return v_float64x2(__lsx_vffint_d_l(v.val)); } + + +//////////////// Lookup table access //////////////// +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + return v_int8x16(_v128_setr_b(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], tab[idx[8]], + tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], + tab[idx[14]], tab[idx[15]])); +} + +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x16(_v128_setr_h(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), + *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), *(const short*)(tab + idx[4]), + *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); +} + +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x16(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +} + +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) +{ return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) +{ return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) +{ return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + return v_int16x8(_v128_setr_h(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x8(_v128_setr_w(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); +} + +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) +{ return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) +{ return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) +{ return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + return v_int32x4(_v128_setr_w(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_int32x4 v_lut_pairs(const int *tab, const int* idx) +{ + return v_int32x4(_v128_setr_d(*(const int64_t*)(tab + idx[0]), *(const int64_t*)(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(__lsx_vld(tab + idx[0], 0)); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int *idx) +{ + return v_int64x2(_v128_setr_d(tab[idx[0]], tab[idx[1]])); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(__lsx_vld(tab + idx[0], 0)); +} + +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(_v128_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ + return v_float32x4((__m128)_v128_setr_pd(*(const double*)(tab + idx[0]), *(const double*)(tab + idx[1]))); +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4((__m128)__lsx_vld(tab + idx[0], 0)); +} + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(_v128_setr_pd(tab[idx[0]], tab[idx[1]])); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2((__m128d)__lsx_vld(tab + idx[0], 0)); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int *idx = (int*)&idxvec.val; + return v_lut(tab, idx); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v_lut(tab, idx); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + const int *idx = (const int*)&idxvec.val; + return v_lut(tab, idx); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + const int *idx = (const int*)&idxvec.val; + __m128i xy0 = __lsx_vld(tab + idx[0], 0); + __m128i xy1 = __lsx_vld(tab + idx[1], 0); + __m128i xy2 = __lsx_vld(tab + idx[2], 0); + __m128i xy3 = __lsx_vld(tab + idx[3], 0); + __m128i xy01 = __lsx_vilvl_d(xy1, xy0); + __m128i xy23 = __lsx_vilvl_d(xy3, xy2); + __m128i xxyy02 = __lsx_vilvl_w(xy23, xy01); + __m128i xxyy13 = __lsx_vilvh_w(xy23, xy01); + x = v_float32x4((__m128)__lsx_vilvl_w(xxyy13, xxyy02)); + y = v_float32x4((__m128)__lsx_vilvh_w(xxyy13, xxyy02)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + const int* idx = (const int*)&idxvec.val; + __m128i xy0 = __lsx_vld(tab + idx[0], 0); + __m128i xy1 = __lsx_vld(tab + idx[1], 0); + x = v_float64x2((__m128d)__lsx_vilvl_d(xy1, xy0)); + y = v_float64x2((__m128d)__lsx_vilvh_d(xy1, xy0)); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0705060403010200, 0x0f0d0e0c0b090a08))); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + return v_int8x16(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0703060205010400, 0x0f0b0e0a0d090c08))); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0706030205040100, 0x0f0e0b0a0d0c0908))); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + return v_int16x8(__lsx_vshuf_b(vec.val, vec.val, + _v128_setr_d(0x0b0a030209080100, 0x0f0e07060d0c0504))); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + return v_int32x4(__lsx_vshuf4i_w(vec.val, 0xd8)); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) +{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) +{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + __m128i zero = __lsx_vldi(0); + return v_int8x16(__lsx_vshuf_b(zero, vec.val, + _v128_set_d(0x1211100f0e0d0c0a, 0x0908060504020100))); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + __m128i zero = __lsx_vldi(0); + return v_int16x8(__lsx_vshuf_b(zero, vec.val, + _v128_set_d(0x11100f0e0d0c0b0a, 0x0908050403020100))); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +//////////// Matrix operations ///////// + +/////////// Dot Product ///////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + __m128i x = a.val, y = b.val; + return v_int32x4(__lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y)); +} +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + __m128i x = a.val, y = b.val, z = c.val; + __m128i t = __lsx_vmaddwev_w_h(z, x, y); + return v_int32x4(__lsx_vmaddwod_w_h(t, x, y)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + __m128i x = a.val, y = b.val; + return v_int64x2(__lsx_vmaddwod_d_w(__lsx_vmulwev_d_w(x, y), x, y)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + __m128i x = a.val, y = b.val, z = c.val; + __m128i t = __lsx_vmaddwev_d_w(z, x, y); + return v_int64x2(__lsx_vmaddwod_d_w(t, x, y)); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_h_bu(x, y); + __m128i odd = __lsx_vmulwod_h_bu(x, y); + __m128i prod0 = __lsx_vhaddw_wu_hu(even, even); + __m128i prod1 = __lsx_vhaddw_wu_hu(odd, odd); + return v_uint32x4(__lsx_vadd_w(prod0, prod1)); +} + +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand(a, b), c) ;} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_h_b(x, y); + __m128i odd = __lsx_vmulwod_h_b(x, y); + __m128i prod0 = __lsx_vhaddw_w_h(even, even); + __m128i prod1 = __lsx_vhaddw_w_h(odd, odd); + return v_int32x4(__lsx_vadd_w(prod0, prod1)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_w_hu(x, y); + __m128i odd = __lsx_vmulwod_w_hu(x, y); + __m128i prod0 = __lsx_vhaddw_du_wu(even, even); + __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); + return v_uint64x2(__lsx_vadd_d(prod0, prod1)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_w_h(x, y); + __m128i odd = __lsx_vmulwod_w_h(x, y); + __m128i prod0 = __lsx_vhaddw_d_w(even, even); + __m128i prod1 = __lsx_vhaddw_d_w(odd, odd); + return v_int64x2(__lsx_vadd_d(prod0, prod1)); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + + +///////// Fast Dot Product ////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i even = __lsx_vmulwev_w_hu(x, y); + __m128i odd = __lsx_vmulwod_w_hu(x, y); + __m128i prod0 = __lsx_vhaddw_du_wu(even, even); + __m128i prod1 = __lsx_vhaddw_du_wu(odd, odd); + return v_uint64x2(__lsx_vilvl_d(__lsx_vhaddw_qu_du(prod0, prod0), __lsx_vhaddw_qu_du(prod1, prod1))); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + __m128i x = a.val, y = b.val; + __m128i prod = __lsx_vmaddwod_w_h(__lsx_vmulwev_w_h(x, y), x, y); + __m128i sign = __lsx_vsrai_w(prod, 31); + __m128i lo = __lsx_vilvl_w(sign, prod); + __m128i hi = __lsx_vilvh_w(sign, prod); + return v_int64x2(__lsx_vadd_d(lo, hi)); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& m3) +{ + __m128i x = (__m128i)v.val; + __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); + __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); + __m128 v2 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val); + __m128 v3 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0xFF), m3.val); + + return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), __lsx_vfadd_s(v2, v3))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, const v_float32x4& a) +{ + __m128i x = (__m128i)v.val; + __m128 v0 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x0), m0.val); + __m128 v1 = __lsx_vfmul_s((__m128)__lsx_vshuf4i_w(x, 0x55), m1.val); + __m128 v2 = __lsx_vfmadd_s((__m128)__lsx_vshuf4i_w(x, 0xAA), m2.val, a.val); + + return v_float32x4(__lsx_vfadd_s(__lsx_vfadd_s(v0, v1), v2)); +} + +#define OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(_Tpvec, cast_from, cast_to) \ + inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ + { \ + __m128i t0 = cast_from(__lsx_vilvl_w(a1.val, a0.val)); \ + __m128i t1 = cast_from(__lsx_vilvl_w(a3.val, a2.val)); \ + __m128i t2 = cast_from(__lsx_vilvh_w(a1.val, a0.val)); \ + __m128i t3 = cast_from(__lsx_vilvh_w(a3.val, a2.val)); \ + b0.val = cast_to(__lsx_vilvl_d(t1, t0)); \ + b1.val = cast_to(__lsx_vilvh_d(t1, t0)); \ + b2.val = cast_to(__lsx_vilvl_d(t3, t2)); \ + b3.val = cast_to(__lsx_vilvh_d(t3, t2)); \ + } + +OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_uint32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_LSX_TRANSPOSE4X4(v_int32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP) + +inline void v_transpose4x4(const v_float32x4& a0, const v_float32x4& a1, + const v_float32x4& a2, const v_float32x4& a3, + v_float32x4& b0, v_float32x4& b1, v_float32x4& b2, v_float32x4& b3) +{ + __m128i vec0 = (__m128i)a0.val, vec1 = (__m128i)a1.val; + __m128i vec2 = (__m128i)a2.val, vec3 = (__m128i)a3.val; + __m128i t0 = __lsx_vilvl_w(vec1, vec0); + __m128i t1 = __lsx_vilvl_w(vec3, vec2); + __m128i t2 = __lsx_vilvh_w(vec1, vec0); + __m128i t3 = __lsx_vilvh_w(vec3, vec2); + b0.val = __m128(__lsx_vilvl_d(t1, t0)); + b1.val = __m128(__lsx_vilvh_d(t1, t0)); + b2.val = __m128(__lsx_vilvl_d(t3, t2)); + b3.val = __m128(__lsx_vilvh_d(t3, t2)); +} + +////////////////// Value reordering //////////////// + +/* Expand */ +#define OPENCV_HAL_IMPL_LSX_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin_lo, intrin_hi) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin_lo(a.val, 0); \ + b1.val = intrin_hi(a.val); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin_lo(a.val, 0)); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(intrin_hi(a.val)); } \ + inline _Tpwvec v_load_expand(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + return _Tpwvec(intrin_lo(a, 0)); \ + } + +OPENCV_HAL_IMPL_LSX_EXPAND(v_uint8x16, v_uint16x8, uchar, __lsx_vsllwil_hu_bu, __lsx_vexth_hu_bu) +OPENCV_HAL_IMPL_LSX_EXPAND(v_int8x16, v_int16x8, schar, __lsx_vsllwil_h_b, __lsx_vexth_h_b) +OPENCV_HAL_IMPL_LSX_EXPAND(v_uint16x8, v_uint32x4, ushort, __lsx_vsllwil_wu_hu, __lsx_vexth_wu_hu) +OPENCV_HAL_IMPL_LSX_EXPAND(v_int16x8, v_int32x4, short, __lsx_vsllwil_w_h, __lsx_vexth_w_h) +OPENCV_HAL_IMPL_LSX_EXPAND(v_uint32x4, v_uint64x2, unsigned, __lsx_vsllwil_du_wu, __lsx_vexth_du_wu) +OPENCV_HAL_IMPL_LSX_EXPAND(v_int32x4, v_int64x2, int, __lsx_vsllwil_d_w, __lsx_vexth_d_w) + +#define OPENCV_HAL_IMPL_LSX_EXPAND_Q(_Tpvec, _Tp, intrin_lo, intrin_hi) \ + inline _Tpvec v_load_expand_q(const _Tp* ptr) \ + { \ + __m128i a = __lsx_vld(ptr, 0); \ + __m128i b = intrin_lo(a, 0); \ + return _Tpvec(intrin_hi(b, 0)); \ + } + +OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_uint32x4, uchar, __lsx_vsllwil_hu_bu, __lsx_vsllwil_wu_hu) +OPENCV_HAL_IMPL_LSX_EXPAND_Q(v_int32x4, schar, __lsx_vsllwil_h_b, __lsx_vsllwil_w_h) + +/* pack */ +// 16 +inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) +{ return v_int8x16(_lsx_packs_h(a.val, b.val)); } + +inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, 0)); } + +inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) +{ return v_uint8x16(_lsx_packus_h(a.val, b.val)); } + +inline void v_pack_store(schar* ptr, const v_int16x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(uchar* ptr, const v_uint16x8& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) +{ v_store_low(ptr, v_pack_u(a, a)); } + +template inline +v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint8x16(__lsx_vssrlrni_bu_h(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) +{ __lsx_vstelm_d(__lsx_vssrlrni_bu_h(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) +{ return v_uint8x16(__lsx_vssrarni_bu_h(b.val, a.val, n)); } + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) +{ __lsx_vstelm_d(__lsx_vssrarni_bu_h(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) +{ return v_int8x16(__lsx_vssrarni_b_h(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x8& a) +{ __lsx_vstelm_d(__lsx_vssrarni_b_h(a.val, a.val, n), ptr, 0, 0); } + +//32 +inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) +{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, 0)); } + +inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) +{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, 0)); } + +inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) +{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, 0)); } + +inline void v_pack_store(short* ptr, const v_int32x4& a) +{ v_store_low(ptr, v_pack(a, a)); } + +inline void v_pack_store(ushort *ptr, const v_uint32x4& a) +{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, 0), ptr, 0, 0); } + +inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) +{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, 0), ptr, 0, 0); } + +template inline +v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) +{ return v_uint16x8(__lsx_vssrlrni_hu_w(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) +{ __lsx_vstelm_d(__lsx_vssrlrni_hu_w(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) +{ return v_uint16x8(__lsx_vssrarni_hu_w(b.val, a.val, n)); } + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) +{ __lsx_vstelm_d(__lsx_vssrarni_hu_w(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) +{ return v_int16x8(__lsx_vssrarni_h_w(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x4& a) +{ __lsx_vstelm_d(__lsx_vssrarni_h_w(a.val, a.val, n), ptr, 0, 0); } + +// 64 +// Non-saturaing pack +inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint32x4(__lsx_vpickev_w(b.val, a.val)); } + +inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) +{ return v_reinterpret_as_s32(v_pack(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); } + +inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) +{ __lsx_vstelm_d(__lsx_vshuf4i_w(a.val, 0x08), ptr, 0, 0); } + +inline void v_pack_store(int *ptr, const v_int64x2& a) +{ v_pack_store((unsigned*)ptr, v_reinterpret_as_u64(a)); } + +template inline +v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint32x4(__lsx_vsrlrni_w_d(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) +{ __lsx_vstelm_d(__lsx_vsrlrni_w_d(a.val, a.val, n), ptr, 0, 0); } + +template inline +v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) +{ return v_int32x4(__lsx_vsrarni_w_d(b.val, a.val, n)); } + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x2& a) +{ __lsx_vstelm_d(__lsx_vsrarni_w_d(a.val, a.val, n), ptr, 0, 0); } + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ return v_uint8x16(__lsx_vssrarni_b_h(b.val, a.val, 0)); } + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + __m128i ab = __lsx_vssrarni_h_w(b.val, a.val, 0); + __m128i cd = __lsx_vssrarni_h_w(d.val, c.val, 0); + return v_uint8x16(__lsx_vssrarni_b_h(cd, ab, 0)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + __m128i ab = __lsx_vssrarni_w_d(b.val, a.val, 0); + __m128i cd = __lsx_vssrarni_w_d(d.val, c.val, 0); + __m128i ef = __lsx_vssrarni_w_d(f.val, e.val, 0); + __m128i gh = __lsx_vssrarni_w_d(h.val, g.val, 0); + + __m128i abcd = __lsx_vssrarni_h_w(cd, ab, 0); + __m128i efgh = __lsx_vssrarni_h_w(gh, ef, 0); + return v_uint8x16(__lsx_vssrarni_b_h(efgh, abcd, 0)); +} + +/* Recombine */ +// its up there with load and store operations + +/* Extract */ +#define OPENCV_HAL_IMPL_LSX_EXTRACT(_Tpvec) \ + template \ + inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ + { return v_rotate_right(a, b); } + +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint8x16) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int8x16) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint16x8) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int16x8) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint32x4) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int32x4) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_uint64x2) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_int64x2) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_float32x4) +OPENCV_HAL_IMPL_LSX_EXTRACT(v_float64x2) + +#define OPENCV_HAL_IMPL_LSX_EXTRACT_N(_Tpvec, _Twvec, intrin) \ +template \ +inline _Twvec v_extract_n(const _Tpvec& a) \ +{ return (_Twvec)intrin(a.val, i); } + +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint8x16, uchar, __lsx_vpickve2gr_b) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int8x16, schar, __lsx_vpickve2gr_b) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint16x8, ushort, __lsx_vpickve2gr_h) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int16x8, short, __lsx_vpickve2gr_h) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint32x4, uint, __lsx_vpickve2gr_w) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int32x4, int, __lsx_vpickve2gr_w) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_uint64x2, uint64, __lsx_vpickve2gr_d) +OPENCV_HAL_IMPL_LSX_EXTRACT_N(v_int64x2, int64, __lsx_vpickve2gr_d) + +template +inline float v_extract_n(const v_float32x4& v) +{ + union { uint iv; float fv; } d; + d.iv = __lsx_vpickve2gr_w(v.val, i); + return d.fv; +} + +template +inline double v_extract_n(const v_float64x2& v) +{ + union { uint64 iv; double dv; } d; + d.iv = __lsx_vpickve2gr_d(v.val, i); + return d.dv; +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) +{ return v_uint32x4(__lsx_vreplvei_w(a.val, i)); } + +template +inline v_int32x4 v_broadcast_element(const v_int32x4& a) +{ return v_int32x4(__lsx_vreplvei_w(a.val, i)); } + +template +inline v_float32x4 v_broadcast_element(const v_float32x4& a) +{ return v_float32x4((__m128)__lsx_vreplvei_w((__m128i)a.val, i)); } + +/////////////////// load deinterleave ////////////////////////////// + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + + a.val = __lsx_vpickev_b(t1, t0); + b.val = __lsx_vpickod_b(t1, t0); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + a.val = __lsx_vpickev_h(t1, t0); + b.val = __lsx_vpickod_h(t1, t0); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + a.val = __lsx_vpickev_w(t1, t0); + b.val = __lsx_vpickod_w(t1, t0); +} + +inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + a.val = __lsx_vilvl_d(t1, t0); + b.val = __lsx_vilvh_d(t1, t0); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + const __m128i shuff0 = _v128_setr_b(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + const __m128i shuff1 = _v128_setr_b(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff0); + __m128i b0 = __lsx_vbitsel_v(t1, t0, shuff1); + __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); + const __m128i shuff_a = _v128_setr_b(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29); + const __m128i shuff_b = _v128_setr_b(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30); + const __m128i shuff_c = _v128_setr_b(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31); + + a.val = __lsx_vshuf_b(t2, a0, shuff_a); + b.val = __lsx_vshuf_b(t2, b0, shuff_b); + c.val = __lsx_vshuf_b(t2, c0, shuff_c); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + const __m128i shuff0 = _v128_setr_h(0, 0, -1, 0, 0, -1, 0, 0); + const __m128i shuff1 = _v128_setr_h(0, -1, 0, 0, -1, 0, 0, -1); + + __m128i a0 = __lsx_vbitsel_v(t0, t1, shuff1); + __m128i b0 = __lsx_vbitsel_v(t0, t1, shuff0); + __m128i c0 = __lsx_vbitsel_v(t1, t0, shuff0); + + const __m128i shuff_a = _v128_setr_b(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 20, 21, 26, 27); + const __m128i shuff_b = _v128_setr_b(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 16, 17, 22, 23, 28, 29); + const __m128i shuff_c = _v128_setr_b(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31); + + a.val = __lsx_vshuf_b(t2, a0, shuff_a); + b.val = __lsx_vshuf_b(t2, b0, shuff_b); + c.val = __lsx_vshuf_b(t2, c0, shuff_c); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + + __m128i a0 = __lsx_vpermi_w(t1, t0, 0xAC); + __m128i b0 = __lsx_vpermi_w(t1, t0, 0xC5); + __m128i c0 = __lsx_vpermi_w(t1, t0, 0x5A); + + a.val = __lsx_vextrins_w(a0, t2, 0x31); + b0 = __lsx_vshuf4i_w(b0, 0x38); + c0 = __lsx_vshuf4i_w(c0, 0x8); + b.val = __lsx_vextrins_w(b0, t2, 0x32); + c.val = __lsx_vpermi_w(t2, c0, 0xC4); +} + +inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + + a.val = __lsx_vshuf4i_d(t0, t1, 0xC); + b.val = __lsx_vshuf4i_d(t0, t2, 0x9); + c.val = __lsx_vshuf4i_d(t1, t2, 0xC); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + __m128i t3 = __lsx_vld(ptr, 48); + + __m128i ac_lo = __lsx_vpickev_b(t1, t0); + __m128i bd_lo = __lsx_vpickod_b(t1, t0); + __m128i ac_hi = __lsx_vpickev_b(t3, t2); + __m128i bd_hi = __lsx_vpickod_b(t3, t2); + + a.val = __lsx_vpickev_b(ac_hi, ac_lo); + c.val = __lsx_vpickod_b(ac_hi, ac_lo); + b.val = __lsx_vpickev_b(bd_hi, bd_lo); + d.val = __lsx_vpickod_b(bd_hi, bd_lo); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + __m128i t3 = __lsx_vld(ptr, 48); + + __m128i ac_lo = __lsx_vpickev_h(t1, t0); + __m128i bd_lo = __lsx_vpickod_h(t1, t0); + __m128i ac_hi = __lsx_vpickev_h(t3, t2); + __m128i bd_hi = __lsx_vpickod_h(t3, t2); + + a.val = __lsx_vpickev_h(ac_hi, ac_lo); + c.val = __lsx_vpickod_h(ac_hi, ac_lo); + b.val = __lsx_vpickev_h(bd_hi, bd_lo); + d.val = __lsx_vpickod_h(bd_hi, bd_lo); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) +{ + __m128i p0 = __lsx_vld(ptr, 0); + __m128i p1 = __lsx_vld(ptr, 16); + __m128i p2 = __lsx_vld(ptr, 32); + __m128i p3 = __lsx_vld(ptr, 48); + + __m128i t0 = __lsx_vilvl_w(p1, p0); + __m128i t1 = __lsx_vilvl_w(p3, p2); + __m128i t2 = __lsx_vilvh_w(p1, p0); + __m128i t3 = __lsx_vilvh_w(p3, p2); + a.val = __lsx_vilvl_d(t1, t0); + b.val = __lsx_vilvh_d(t1, t0); + c.val = __lsx_vilvl_d(t3, t2); + d.val = __lsx_vilvh_d(t3, t2); +} + +inline void v_load_deinterleave(const uint64* ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) +{ + __m128i t0 = __lsx_vld(ptr, 0); + __m128i t1 = __lsx_vld(ptr, 16); + __m128i t2 = __lsx_vld(ptr, 32); + __m128i t3 = __lsx_vld(ptr, 48); + + a.val = __lsx_vilvl_d(t2, t0); + b.val = __lsx_vilvh_d(t2, t0); + c.val = __lsx_vilvl_d(t3, t1); + d.val = __lsx_vilvh_d(t3, t1); +} + +////////////////////////// store interleave //////////////////////////////// + +inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_b(b.val, a.val); + __m128i v1 = __lsx_vilvh_b(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_h(b.val, a.val); + __m128i v1 = __lsx_vilvh_h(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_w(b.val, a.val); + __m128i v1 = __lsx_vilvh_w(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v0 = __lsx_vilvl_d(b.val, a.val); + __m128i v1 = __lsx_vilvh_d(b.val, a.val); + + __lsx_vst(v0, ptr, 0); + __lsx_vst(v1, ptr, 16); +} + +inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, const v_uint8x16& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); + __m128i v_c = c.val; + const __m128i shuff0 = _v128_setr_b(0, 1, 16, 2, 3, 17, 4, 5, 18, 6, 7, 19, 8, 9, 20, 10); + const __m128i shuff1 = _v128_setr_b(11, 21, 12, 13, 22, 14, 15, 23, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 24, 18, 19, 25, 20, 21); + const __m128i shuff3 = _v128_setr_b(26, 6, 7, 27, 8, 9, 28, 10, 11, 29, 12, 13, 30, 14, 15, 31); + __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); + + __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); + __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); + __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); + dst1 = __lsx_vshuf_b(abc, dst1, shuff2); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); +} + +inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, const v_uint16x8& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); + __m128i v_c = c.val; + const __m128i shuff0 = _v128_setr_b(0, 1, 2, 3, 16, 17, 4, 5, 6, 7, 18, 19, 8, 9, 10, 11); + const __m128i shuff1 = _v128_setr_b(20, 21, 12, 13, 14, 15, 22, 23, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i shuff2 = _v128_setr_b(0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 24, 25, 20, 21); + const __m128i shuff3 = _v128_setr_b(6, 7, 26, 27, 8, 9, 10, 11, 28, 29, 12, 13, 14, 15, 30, 31); + __m128i abc = __lsx_vpermi_w(v_c, ab_hi, 0xE4); + + __m128i dst0 = __lsx_vshuf_b(v_c, ab_lo, shuff0); + __m128i dst1 = __lsx_vshuf_b(v_c, ab_lo, shuff1); + __m128i dst2 = __lsx_vshuf_b(v_c, ab_hi, shuff3); + dst1 = __lsx_vshuf_b(abc, dst1, shuff2); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, const v_uint32x4& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i v_c = c.val; + __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); //a0 b0 a1 b1 + __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); //a2 b2 a3 b3 + __m128i bc_od = __lsx_vpackod_w(v_c, b.val); // b1 c1 b3 c3 + + __m128i dst0 = __lsx_vshuf4i_w(ab_lo, 0xB4); //a0 b0 b1 a1 + __m128i dst1 = __lsx_vilvl_d(ab_hi, bc_od); //b1 c1 a2 b2 + __m128i dst2 = __lsx_vpermi_w(bc_od, ab_hi, 0xE8); //a2, a3, b3, c3 + + dst0 = __lsx_vextrins_w(dst0, v_c, 0x20); + dst2 = __lsx_vextrins_w(dst2, v_c, 0x2); + __lsx_vst(dst0, ptr, 0); //a0 b0 c0 a1 + __lsx_vst(dst1, ptr, 16); //b1 c1 a2 b2 + __lsx_vst(dst2, ptr, 32); //c2 a3 b3 c3 +} + +inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i dst0 = __lsx_vilvl_d(b.val, a.val); + __m128i dst1 = __lsx_vpermi_w(a.val, c.val, 0xE4); + __m128i dst2 = __lsx_vilvh_d(c.val, b.val); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); +} + +inline void v_store_interleave(uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, const v_uint8x16& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_b(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_b(b.val, a.val); + __m128i cd_lo = __lsx_vilvl_b(d.val, c.val); + __m128i cd_hi = __lsx_vilvh_b(d.val, c.val); + + __m128i dst0 = __lsx_vilvl_h(cd_lo, ab_lo); + __m128i dst1 = __lsx_vilvh_h(cd_lo, ab_lo); + __m128i dst2 = __lsx_vilvl_h(cd_hi, ab_hi); + __m128i dst3 = __lsx_vilvh_h(cd_hi, ab_hi); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +inline void v_store_interleave(ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + const v_uint16x8& c, const v_uint16x8& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_h(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_h(b.val, a.val); + __m128i cd_lo = __lsx_vilvl_h(d.val, c.val); + __m128i cd_hi = __lsx_vilvh_h(d.val, c.val); + + __m128i dst0 = __lsx_vilvl_w(cd_lo, ab_lo); + __m128i dst1 = __lsx_vilvh_w(cd_lo, ab_lo); + __m128i dst2 = __lsx_vilvl_w(cd_hi, ab_hi); + __m128i dst3 = __lsx_vilvh_w(cd_hi, ab_hi); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i ab_lo = __lsx_vilvl_w(b.val, a.val); + __m128i ab_hi = __lsx_vilvh_w(b.val, a.val); + __m128i cd_lo = __lsx_vilvl_w(d.val, c.val); + __m128i cd_hi = __lsx_vilvh_w(d.val, c.val); + + __m128i dst0 = __lsx_vilvl_d(cd_lo, ab_lo); + __m128i dst1 = __lsx_vilvh_d(cd_lo, ab_lo); + __m128i dst2 = __lsx_vilvl_d(cd_hi, ab_hi); + __m128i dst3 = __lsx_vilvh_d(cd_hi, ab_hi); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +inline void v_store_interleave(uint64* ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, const v_uint64x2& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + __m128i dst0 = __lsx_vilvl_d(b.val, a.val); + __m128i dst2 = __lsx_vilvh_d(b.val, a.val); + __m128i dst1 = __lsx_vilvl_d(d.val, c.val); + __m128i dst3 = __lsx_vilvh_d(d.val, c.val); + + __lsx_vst(dst0, ptr, 0); + __lsx_vst(dst1, ptr, 16); + __lsx_vst(dst2, ptr, 32); + __lsx_vst(dst3, ptr, 48); +} + +#define OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave(const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, \ + _Tpvec0& c0, _Tpvec0& d0) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1); \ +} \ +inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, const _Tpvec0& c0,\ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1); \ +} \ +inline void v_store_interleave(_Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1); \ +} + +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float32x4, float, f32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_LSX_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) + +// +// FP16 +// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + return v_float32x4(__lsx_vfcvtl_s_h((__m128)__lsx_vld(ptr, 0))); +#else + float CV_DECL_ALIGNED(32) buf[4]; + for (int i = 0; i < 4; i++) + buf[i] = (float)ptr[i]; + return v_float32x4((__m128)__lsx_vld(buf, 0)); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& a) +{ +#if CV_FP16 + __m128i res = (__m218i)__lsx_vfcvt_h_s(a.val, a.val); + __lsx_vstelm_d(res, ptr, 0, 0); +#else + float CV_DECL_ALIGNED(32) buf[4]; + v_store_aligned(buf, a); + for (int i = 0; i < 4; i++) + ptr[i] = hfloat(buf[i]); +#endif +} + +// +// end of FP16 +// + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_LSX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp index b6912a7a8a..b7e649e744 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_math.hpp @@ -1,687 +1,687 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - - -/* Universal Intrinsics implementation of sin, cos, exp and log - - Inspired by Intel Approximate Math library, and based on the - corresponding algorithms of the cephes math library -*/ - -/* Copyright (C) 2010,2011 RJVB - extensions */ -/* Copyright (C) 2011 Julien Pommier - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - (this is the zlib license) -*/ -#ifndef OPENCV_HAL_INTRIN_MATH_HPP -#define OPENCV_HAL_INTRIN_MATH_HPP - -//! @name Exponential -//! @{ -// Implementation is the same as float32 vector. -template -inline _TpVec16F v_exp_default_16f(const _TpVec16F &x) { - const _TpVec16F _vexp_lo_f16 = v_setall_<_TpVec16F>(-10.7421875f); - const _TpVec16F _vexp_hi_f16 = v_setall_<_TpVec16F>(11.f); - const _TpVec16F _vexp_half_fp16 = v_setall_<_TpVec16F>(0.5f); - const _TpVec16F _vexp_one_fp16 = v_setall_<_TpVec16F>(1.f); - const _TpVec16F _vexp_LOG2EF_f16 = v_setall_<_TpVec16F>(1.44269504088896341f); - const _TpVec16F _vexp_C1_f16 = v_setall_<_TpVec16F>(-6.93359375E-1f); - const _TpVec16F _vexp_C2_f16 = v_setall_<_TpVec16F>(2.12194440E-4f); - const _TpVec16F _vexp_p0_f16 = v_setall_<_TpVec16F>(1.9875691500E-4f); - const _TpVec16F _vexp_p1_f16 = v_setall_<_TpVec16F>(1.3981999507E-3f); - const _TpVec16F _vexp_p2_f16 = v_setall_<_TpVec16F>(8.3334519073E-3f); - const _TpVec16F _vexp_p3_f16 = v_setall_<_TpVec16F>(4.1665795894E-2f); - const _TpVec16F _vexp_p4_f16 = v_setall_<_TpVec16F>(1.6666665459E-1f); - const _TpVec16F _vexp_p5_f16 = v_setall_<_TpVec16F>(5.0000001201E-1f); - - _TpVec16F _vexp_, _vexp_x, _vexp_y, _vexp_xx; - _TpVec16S _vexp_mm; - const _TpVec16S _vexp_bias_s16 = v_setall_<_TpVec16S>((short)0xf); - - // compute exponential of x - _vexp_x = v_max(x, _vexp_lo_f16); - _vexp_x = v_min(_vexp_x, _vexp_hi_f16); - - _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f16, _vexp_half_fp16); - _vexp_mm = v_floor(_vexp_); - _vexp_ = v_cvt_f16(_vexp_mm); - _vexp_mm = v_add(_vexp_mm, _vexp_bias_s16); - _vexp_mm = v_shl(_vexp_mm, 10); - - _vexp_x = v_fma(_vexp_, _vexp_C1_f16, _vexp_x); - _vexp_x = v_fma(_vexp_, _vexp_C2_f16, _vexp_x); - _vexp_xx = v_mul(_vexp_x, _vexp_x); - - _vexp_y = v_fma(_vexp_x, _vexp_p0_f16, _vexp_p1_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f16); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f16); - - _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); - _vexp_y = v_add(_vexp_y, _vexp_one_fp16); - _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f16(_vexp_mm)); - - // exp(NAN) -> NAN - _TpVec16F mask_not_nan = v_not_nan(x); - return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); -} - -template -inline _TpVec32F v_exp_default_32f(const _TpVec32F &x) { - const _TpVec32F _vexp_lo_f32 = v_setall_<_TpVec32F>(-88.3762626647949f); - const _TpVec32F _vexp_hi_f32 = v_setall_<_TpVec32F>(89.f); - const _TpVec32F _vexp_half_fp32 = v_setall_<_TpVec32F>(0.5f); - const _TpVec32F _vexp_one_fp32 = v_setall_<_TpVec32F>(1.f); - const _TpVec32F _vexp_LOG2EF_f32 = v_setall_<_TpVec32F>(1.44269504088896341f); - const _TpVec32F _vexp_C1_f32 = v_setall_<_TpVec32F>(-6.93359375E-1f); - const _TpVec32F _vexp_C2_f32 = v_setall_<_TpVec32F>(2.12194440E-4f); - const _TpVec32F _vexp_p0_f32 = v_setall_<_TpVec32F>(1.9875691500E-4f); - const _TpVec32F _vexp_p1_f32 = v_setall_<_TpVec32F>(1.3981999507E-3f); - const _TpVec32F _vexp_p2_f32 = v_setall_<_TpVec32F>(8.3334519073E-3f); - const _TpVec32F _vexp_p3_f32 = v_setall_<_TpVec32F>(4.1665795894E-2f); - const _TpVec32F _vexp_p4_f32 = v_setall_<_TpVec32F>(1.6666665459E-1f); - const _TpVec32F _vexp_p5_f32 = v_setall_<_TpVec32F>(5.0000001201E-1f); - - _TpVec32F _vexp_, _vexp_x, _vexp_y, _vexp_xx; - _TpVec32S _vexp_mm; - const _TpVec32S _vexp_bias_s32 = v_setall_<_TpVec32S>((int)0x7f); - - // compute exponential of x - _vexp_x = v_max(x, _vexp_lo_f32); - _vexp_x = v_min(_vexp_x, _vexp_hi_f32); - - _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f32, _vexp_half_fp32); - _vexp_mm = v_floor(_vexp_); - _vexp_ = v_cvt_f32(_vexp_mm); - _vexp_mm = v_add(_vexp_mm, _vexp_bias_s32); - _vexp_mm = v_shl(_vexp_mm, 23); - - _vexp_x = v_fma(_vexp_, _vexp_C1_f32, _vexp_x); - _vexp_x = v_fma(_vexp_, _vexp_C2_f32, _vexp_x); - _vexp_xx = v_mul(_vexp_x, _vexp_x); - - _vexp_y = v_fma(_vexp_x, _vexp_p0_f32, _vexp_p1_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f32); - _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f32); - - _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); - _vexp_y = v_add(_vexp_y, _vexp_one_fp32); - _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f32(_vexp_mm)); - - // exp(NAN) -> NAN - _TpVec32F mask_not_nan = v_not_nan(x); - return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); -} - -template -inline _TpVec64F v_exp_default_64f(const _TpVec64F &x) { - const _TpVec64F _vexp_lo_f64 = v_setall_<_TpVec64F>(-709.43613930310391424428); - const _TpVec64F _vexp_hi_f64 = v_setall_<_TpVec64F>(710.); - const _TpVec64F _vexp_half_f64 = v_setall_<_TpVec64F>(0.5); - const _TpVec64F _vexp_one_f64 = v_setall_<_TpVec64F>(1.0); - const _TpVec64F _vexp_two_f64 = v_setall_<_TpVec64F>(2.0); - const _TpVec64F _vexp_LOG2EF_f64 = v_setall_<_TpVec64F>(1.44269504088896340736); - const _TpVec64F _vexp_C1_f64 = v_setall_<_TpVec64F>(-6.93145751953125E-1); - const _TpVec64F _vexp_C2_f64 = v_setall_<_TpVec64F>(-1.42860682030941723212E-6); - const _TpVec64F _vexp_p0_f64 = v_setall_<_TpVec64F>(1.26177193074810590878E-4); - const _TpVec64F _vexp_p1_f64 = v_setall_<_TpVec64F>(3.02994407707441961300E-2); - const _TpVec64F _vexp_p2_f64 = v_setall_<_TpVec64F>(9.99999999999999999910E-1); - const _TpVec64F _vexp_q0_f64 = v_setall_<_TpVec64F>(3.00198505138664455042E-6); - const _TpVec64F _vexp_q1_f64 = v_setall_<_TpVec64F>(2.52448340349684104192E-3); - const _TpVec64F _vexp_q2_f64 = v_setall_<_TpVec64F>(2.27265548208155028766E-1); - const _TpVec64F _vexp_q3_f64 = v_setall_<_TpVec64F>(2.00000000000000000009E0); - - _TpVec64F _vexp_, _vexp_x, _vexp_y, _vexp_z, _vexp_xx; - _TpVec64S _vexp_mm; - const _TpVec64S _vexp_bias_s64 = v_setall_<_TpVec64S>((int64)0x3ff); - - // compute exponential of x - _vexp_x = v_max(x, _vexp_lo_f64); - _vexp_x = v_min(_vexp_x, _vexp_hi_f64); - - _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f64, _vexp_half_f64); - _vexp_mm = v_expand_low(v_floor(_vexp_)); - _vexp_ = v_cvt_f64(_vexp_mm); - _vexp_mm = v_add(_vexp_mm, _vexp_bias_s64); - _vexp_mm = v_shl(_vexp_mm, 52); - - _vexp_x = v_fma(_vexp_, _vexp_C1_f64, _vexp_x); - _vexp_x = v_fma(_vexp_, _vexp_C2_f64, _vexp_x); - _vexp_xx = v_mul(_vexp_x, _vexp_x); - - _vexp_y = v_fma(_vexp_xx, _vexp_p0_f64, _vexp_p1_f64); - _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_p2_f64); - _vexp_y = v_mul(_vexp_y, _vexp_x); - - _vexp_z = v_fma(_vexp_xx, _vexp_q0_f64, _vexp_q1_f64); - _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q2_f64); - _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q3_f64); - - _vexp_z = v_div(_vexp_y, v_sub(_vexp_z, _vexp_y)); - _vexp_z = v_fma(_vexp_two_f64, _vexp_z, _vexp_one_f64); - _vexp_z = v_mul(_vexp_z, v_reinterpret_as_f64(_vexp_mm)); - - // exp(NAN) -> NAN - _TpVec64F mask_not_nan = v_not_nan(x); - return v_select(mask_not_nan, _vexp_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7FF8000000000000))); -} -//! @} - -//! @name Natural Logarithm -//! @{ -template -inline _TpVec16F v_log_default_16f(const _TpVec16F &x) { - const _TpVec16F _vlog_one_fp16 = v_setall_<_TpVec16F>(1.0f); - const _TpVec16F _vlog_SQRTHF_fp16 = v_setall_<_TpVec16F>(0.707106781186547524f); - const _TpVec16F _vlog_q1_fp16 = v_setall_<_TpVec16F>(-2.12194440E-4f); - const _TpVec16F _vlog_q2_fp16 = v_setall_<_TpVec16F>(0.693359375f); - const _TpVec16F _vlog_p0_fp16 = v_setall_<_TpVec16F>(7.0376836292E-2f); - const _TpVec16F _vlog_p1_fp16 = v_setall_<_TpVec16F>(-1.1514610310E-1f); - const _TpVec16F _vlog_p2_fp16 = v_setall_<_TpVec16F>(1.1676998740E-1f); - const _TpVec16F _vlog_p3_fp16 = v_setall_<_TpVec16F>(-1.2420140846E-1f); - const _TpVec16F _vlog_p4_fp16 = v_setall_<_TpVec16F>(1.4249322787E-1f); - const _TpVec16F _vlog_p5_fp16 = v_setall_<_TpVec16F>(-1.6668057665E-1f); - const _TpVec16F _vlog_p6_fp16 = v_setall_<_TpVec16F>(2.0000714765E-1f); - const _TpVec16F _vlog_p7_fp16 = v_setall_<_TpVec16F>(-2.4999993993E-1f); - const _TpVec16F _vlog_p8_fp16 = v_setall_<_TpVec16F>(3.3333331174E-1f); - - _TpVec16F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; - _TpVec16S _vlog_ux, _vlog_emm0; - const _TpVec16S _vlog_inv_mant_mask_s16 = v_setall_<_TpVec16S>((short)~0x7c00); - - _vlog_ux = v_reinterpret_as_s16(x); - _vlog_emm0 = v_shr(_vlog_ux, 10); - - _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s16); - _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s16(v_setall_<_TpVec16F>(0.5f))); - _vlog_x = v_reinterpret_as_f16(_vlog_ux); - - _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec16S>((short)0xf)); - _vlog_e = v_cvt_f16(_vlog_emm0); - - _vlog_e = v_add(_vlog_e, _vlog_one_fp16); - - _TpVec16F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp16); - _vlog_tmp = v_and(_vlog_x, _vlog_mask); - _vlog_x = v_sub(_vlog_x, _vlog_one_fp16); - _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp16, _vlog_mask)); - _vlog_x = v_add(_vlog_x, _vlog_tmp); - - _vlog_z = v_mul(_vlog_x, _vlog_x); - - _vlog_y = v_fma(_vlog_p0_fp16, _vlog_x, _vlog_p1_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp16); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp16); - _vlog_y = v_mul(_vlog_y, _vlog_x); - _vlog_y = v_mul(_vlog_y, _vlog_z); - - _vlog_y = v_fma(_vlog_e, _vlog_q1_fp16, _vlog_y); - - _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec16F>(0.5f))); - - _vlog_x = v_add(_vlog_x, _vlog_y); - _vlog_x = v_fma(_vlog_e, _vlog_q2_fp16, _vlog_x); - // log(0) -> -INF - _TpVec16F mask_zero = v_eq(x, v_setzero_<_TpVec16F>()); - _vlog_x = v_select(mask_zero, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0xfc00)), _vlog_x); - // log(NEG), log(NAN) -> NAN - _TpVec16F mask_not_nan = v_ge(x, v_setzero_<_TpVec16F>()); - _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); - // log(INF) -> INF - _TpVec16F mask_inf = v_eq(x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); - _vlog_x = v_select(mask_inf, x, _vlog_x); - return _vlog_x; -} - -template -inline _TpVec32F v_log_default_32f(const _TpVec32F &x) { - const _TpVec32F _vlog_one_fp32 = v_setall_<_TpVec32F>(1.0f); - const _TpVec32F _vlog_SQRTHF_fp32 = v_setall_<_TpVec32F>(0.707106781186547524f); - const _TpVec32F _vlog_q1_fp32 = v_setall_<_TpVec32F>(-2.12194440E-4f); - const _TpVec32F _vlog_q2_fp32 = v_setall_<_TpVec32F>(0.693359375f); - const _TpVec32F _vlog_p0_fp32 = v_setall_<_TpVec32F>(7.0376836292E-2f); - const _TpVec32F _vlog_p1_fp32 = v_setall_<_TpVec32F>(-1.1514610310E-1f); - const _TpVec32F _vlog_p2_fp32 = v_setall_<_TpVec32F>(1.1676998740E-1f); - const _TpVec32F _vlog_p3_fp32 = v_setall_<_TpVec32F>(-1.2420140846E-1f); - const _TpVec32F _vlog_p4_fp32 = v_setall_<_TpVec32F>(1.4249322787E-1f); - const _TpVec32F _vlog_p5_fp32 = v_setall_<_TpVec32F>(-1.6668057665E-1f); - const _TpVec32F _vlog_p6_fp32 = v_setall_<_TpVec32F>(2.0000714765E-1f); - const _TpVec32F _vlog_p7_fp32 = v_setall_<_TpVec32F>(-2.4999993993E-1f); - const _TpVec32F _vlog_p8_fp32 = v_setall_<_TpVec32F>(3.3333331174E-1f); - - _TpVec32F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; - _TpVec32S _vlog_ux, _vlog_emm0; - const _TpVec32S _vlog_inv_mant_mask_s32 = v_setall_<_TpVec32S>((int)~0x7f800000); - - _vlog_ux = v_reinterpret_as_s32(x); - _vlog_emm0 = v_shr(_vlog_ux, 23); - - _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s32); - _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s32(v_setall_<_TpVec32F>(0.5f))); - _vlog_x = v_reinterpret_as_f32(_vlog_ux); - - _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec32S>((int)0x7f)); - _vlog_e = v_cvt_f32(_vlog_emm0); - - _vlog_e = v_add(_vlog_e, _vlog_one_fp32); - - _TpVec32F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp32); - _vlog_tmp = v_and(_vlog_x, _vlog_mask); - _vlog_x = v_sub(_vlog_x, _vlog_one_fp32); - _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp32, _vlog_mask)); - _vlog_x = v_add(_vlog_x, _vlog_tmp); - - _vlog_z = v_mul(_vlog_x, _vlog_x); - - _vlog_y = v_fma(_vlog_p0_fp32, _vlog_x, _vlog_p1_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp32); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp32); - _vlog_y = v_mul(_vlog_y, _vlog_x); - _vlog_y = v_mul(_vlog_y, _vlog_z); - - _vlog_y = v_fma(_vlog_e, _vlog_q1_fp32, _vlog_y); - - _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec32F>(0.5f))); - - _vlog_x = v_add(_vlog_x, _vlog_y); - _vlog_x = v_fma(_vlog_e, _vlog_q2_fp32, _vlog_x); - // log(0) -> -INF - _TpVec32F mask_zero = v_eq(x, v_setzero_<_TpVec32F>()); - _vlog_x = v_select(mask_zero, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0xff800000)), _vlog_x); - // log(NEG), log(NAN) -> NAN - _TpVec32F mask_not_nan = v_ge(x, v_setzero_<_TpVec32F>()); - _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); - // log(INF) -> INF - _TpVec32F mask_inf = v_eq(x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); - _vlog_x = v_select(mask_inf, x, _vlog_x); - return _vlog_x; -} - -template -inline _TpVec64F v_log_default_64f(const _TpVec64F &x) { - const _TpVec64F _vlog_one_fp64 = v_setall_<_TpVec64F>(1.0); - const _TpVec64F _vlog_SQRTHF_fp64 = v_setall_<_TpVec64F>(0.7071067811865475244); - const _TpVec64F _vlog_p0_fp64 = v_setall_<_TpVec64F>(1.01875663804580931796E-4); - const _TpVec64F _vlog_p1_fp64 = v_setall_<_TpVec64F>(4.97494994976747001425E-1); - const _TpVec64F _vlog_p2_fp64 = v_setall_<_TpVec64F>(4.70579119878881725854); - const _TpVec64F _vlog_p3_fp64 = v_setall_<_TpVec64F>(1.44989225341610930846E1); - const _TpVec64F _vlog_p4_fp64 = v_setall_<_TpVec64F>(1.79368678507819816313E1); - const _TpVec64F _vlog_p5_fp64 = v_setall_<_TpVec64F>(7.70838733755885391666); - const _TpVec64F _vlog_q0_fp64 = v_setall_<_TpVec64F>(1.12873587189167450590E1); - const _TpVec64F _vlog_q1_fp64 = v_setall_<_TpVec64F>(4.52279145837532221105E1); - const _TpVec64F _vlog_q2_fp64 = v_setall_<_TpVec64F>(8.29875266912776603211E1); - const _TpVec64F _vlog_q3_fp64 = v_setall_<_TpVec64F>(7.11544750618563894466E1); - const _TpVec64F _vlog_q4_fp64 = v_setall_<_TpVec64F>(2.31251620126765340583E1); - - const _TpVec64F _vlog_C0_fp64 = v_setall_<_TpVec64F>(2.121944400546905827679e-4); - const _TpVec64F _vlog_C1_fp64 = v_setall_<_TpVec64F>(0.693359375); - - _TpVec64F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp, _vlog_xx; - _TpVec64S _vlog_ux, _vlog_emm0; - const _TpVec64S _vlog_inv_mant_mask_s64 = v_setall_<_TpVec64S>((int64)~0x7ff0000000000000); - - _vlog_ux = v_reinterpret_as_s64(x); - _vlog_emm0 = v_shr(_vlog_ux, 52); - - _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s64); - _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s64(v_setall_<_TpVec64F>(0.5))); - _vlog_x = v_reinterpret_as_f64(_vlog_ux); - - _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec64S>((int64)0x3ff)); - _vlog_e = v_cvt_f64(_vlog_emm0); - - _vlog_e = v_add(_vlog_e, _vlog_one_fp64); - - _TpVec64F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp64); - _vlog_tmp = v_and(_vlog_x, _vlog_mask); - _vlog_x = v_sub(_vlog_x, _vlog_one_fp64); - _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp64, _vlog_mask)); - _vlog_x = v_add(_vlog_x, _vlog_tmp); - - _vlog_xx = v_mul(_vlog_x, _vlog_x); - - _vlog_y = v_fma(_vlog_p0_fp64, _vlog_x, _vlog_p1_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp64); - _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp64); - _vlog_y = v_mul(_vlog_y, _vlog_x); - _vlog_y = v_mul(_vlog_y, _vlog_xx); - - _vlog_z = v_add(_vlog_x, _vlog_q0_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q1_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q2_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q3_fp64); - _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q4_fp64); - - _vlog_z = v_div(_vlog_y, _vlog_z); - _vlog_z = v_sub(_vlog_z, v_mul(_vlog_e, _vlog_C0_fp64)); - _vlog_z = v_sub(_vlog_z, v_mul(_vlog_xx, v_setall_<_TpVec64F>(0.5))); - - _vlog_z = v_add(_vlog_z, _vlog_x); - _vlog_z = v_fma(_vlog_e, _vlog_C1_fp64, _vlog_z); - - // log(0) -> -INF - _TpVec64F mask_zero = v_eq(x, v_setzero_<_TpVec64F>()); - _vlog_z = v_select(mask_zero, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0xfff0000000000000)), _vlog_z); - // log(NEG), log(NAN) -> NAN - _TpVec64F mask_not_nan = v_ge(x, v_setzero_<_TpVec64F>()); - _vlog_z = v_select(mask_not_nan, _vlog_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000))); - // log(INF) -> INF - _TpVec64F mask_inf = v_eq(x, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); - _vlog_z = v_select(mask_inf, x, _vlog_z); - return _vlog_z; -} -//! @} - -//! @name Sine and Cosine -//! @{ -template -inline void v_sincos_default_16f(const _TpVec16F &x, _TpVec16F &ysin, _TpVec16F &ycos) { - const _TpVec16F v_cephes_FOPI = v_setall_<_TpVec16F>(hfloat(1.27323954473516f)); // 4 / M_PI - const _TpVec16F v_minus_DP1 = v_setall_<_TpVec16F>(hfloat(-0.78515625f)); - const _TpVec16F v_minus_DP2 = v_setall_<_TpVec16F>(hfloat(-2.4187564849853515625E-4f)); - const _TpVec16F v_minus_DP3 = v_setall_<_TpVec16F>(hfloat(-3.77489497744594108E-8f)); - const _TpVec16F v_sincof_p0 = v_setall_<_TpVec16F>(hfloat(-1.9515295891E-4f)); - const _TpVec16F v_sincof_p1 = v_setall_<_TpVec16F>(hfloat(8.3321608736E-3f)); - const _TpVec16F v_sincof_p2 = v_setall_<_TpVec16F>(hfloat(-1.6666654611E-1f)); - const _TpVec16F v_coscof_p0 = v_setall_<_TpVec16F>(hfloat(2.443315711809948E-5f)); - const _TpVec16F v_coscof_p1 = v_setall_<_TpVec16F>(hfloat(-1.388731625493765E-3f)); - const _TpVec16F v_coscof_p2 = v_setall_<_TpVec16F>(hfloat(4.166664568298827E-2f)); - const _TpVec16F v_nan = v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00)); - const _TpVec16F v_neg_zero = v_setall_<_TpVec16F>(hfloat(-0.f)); - - _TpVec16F _vx, _vy, sign_mask_sin, sign_mask_cos; - _TpVec16S emm2; - - sign_mask_sin = v_lt(x, v_setzero_<_TpVec16F>()); - _vx = v_abs(x); - _vy = v_mul(_vx, v_cephes_FOPI); - - emm2 = v_trunc(_vy); - emm2 = v_add(emm2, v_setall_<_TpVec16S>((short)1)); - emm2 = v_and(emm2, v_setall_<_TpVec16S>((short)~1)); - _vy = v_cvt_f16(emm2); - - _TpVec16F poly_mask = v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)0))); - - _vx = v_fma(_vy, v_minus_DP1, _vx); - _vx = v_fma(_vy, v_minus_DP2, _vx); - _vx = v_fma(_vy, v_minus_DP3, _vx); - - sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0)))); - sign_mask_cos = v_reinterpret_as_f16(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0))); - - _TpVec16F _vxx = v_mul(_vx, _vx); - _TpVec16F y1, y2; - - y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); - y1 = v_fma(y1, _vxx, v_coscof_p2); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(-0.5f))); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(1.f))); - - y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); - y2 = v_fma(y2, _vxx, v_sincof_p2); - y2 = v_mul(y2, _vxx); - y2 = v_fma(y2, _vx, _vx); - - ysin = v_select(poly_mask, y2, y1); - ycos = v_select(poly_mask, y1, y2); - ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); - ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); - - // sincos(NAN) -> NAN, sincos(±INF) -> NAN - _TpVec16F mask_inf = v_eq(_vx, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); - _TpVec16F mask_nan = v_or(mask_inf, v_ne(x, x)); - ysin = v_select(mask_nan, v_nan, ysin); - ycos = v_select(mask_nan, v_nan, ycos); -} - -template -inline _TpVec16F v_sin_default_16f(const _TpVec16F &x) { - _TpVec16F ysin, ycos; - v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); - return ysin; -} - -template -inline _TpVec16F v_cos_default_16f(const _TpVec16F &x) { - _TpVec16F ysin, ycos; - v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); - return ycos; -} - - -template -inline void v_sincos_default_32f(const _TpVec32F &x, _TpVec32F &ysin, _TpVec32F &ycos) { - const _TpVec32F v_cephes_FOPI = v_setall_<_TpVec32F>(1.27323954473516f); // 4 / M_PI - const _TpVec32F v_minus_DP1 = v_setall_<_TpVec32F>(-0.78515625f); - const _TpVec32F v_minus_DP2 = v_setall_<_TpVec32F>(-2.4187564849853515625E-4f); - const _TpVec32F v_minus_DP3 = v_setall_<_TpVec32F>(-3.77489497744594108E-8f); - const _TpVec32F v_sincof_p0 = v_setall_<_TpVec32F>(-1.9515295891E-4f); - const _TpVec32F v_sincof_p1 = v_setall_<_TpVec32F>(8.3321608736E-3f); - const _TpVec32F v_sincof_p2 = v_setall_<_TpVec32F>(-1.6666654611E-1f); - const _TpVec32F v_coscof_p0 = v_setall_<_TpVec32F>(2.443315711809948E-5f); - const _TpVec32F v_coscof_p1 = v_setall_<_TpVec32F>(-1.388731625493765E-3f); - const _TpVec32F v_coscof_p2 = v_setall_<_TpVec32F>(4.166664568298827E-2f); - const _TpVec32F v_nan = v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000)); - const _TpVec32F v_neg_zero = v_setall_<_TpVec32F>(-0.f); - - _TpVec32F _vx, _vy, sign_mask_sin, sign_mask_cos; - _TpVec32S emm2; - - sign_mask_sin = v_lt(x, v_setzero_<_TpVec32F>()); - _vx = v_abs(x); - _vy = v_mul(_vx, v_cephes_FOPI); - - emm2 = v_trunc(_vy); - emm2 = v_add(emm2, v_setall_<_TpVec32S>(1)); - emm2 = v_and(emm2, v_setall_<_TpVec32S>(~1)); - _vy = v_cvt_f32(emm2); - - _TpVec32F poly_mask = v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(0))); - - _vx = v_fma(_vy, v_minus_DP1, _vx); - _vx = v_fma(_vy, v_minus_DP2, _vx); - _vx = v_fma(_vy, v_minus_DP3, _vx); - - sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0)))); - sign_mask_cos = v_reinterpret_as_f32(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0))); - - _TpVec32F _vxx = v_mul(_vx, _vx); - _TpVec32F y1, y2; - - y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); - y1 = v_fma(y1, _vxx, v_coscof_p2); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(-0.5f)); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(1.f)); - - y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); - y2 = v_fma(y2, _vxx, v_sincof_p2); - y2 = v_mul(y2, _vxx); - y2 = v_fma(y2, _vx, _vx); - - ysin = v_select(poly_mask, y2, y1); - ycos = v_select(poly_mask, y1, y2); - ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); - ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); - - // sincos(NAN) -> NAN, sincos(±INF) -> NAN - _TpVec32F mask_inf = v_eq(_vx, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); - _TpVec32F mask_nan = v_or(mask_inf, v_ne(x, x)); - ysin = v_select(mask_nan, v_nan, ysin); - ycos = v_select(mask_nan, v_nan, ycos); -} - -template -inline _TpVec32F v_sin_default_32f(const _TpVec32F &x) { - _TpVec32F ysin, ycos; - v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); - return ysin; -} - -template -inline _TpVec32F v_cos_default_32f(const _TpVec32F &x) { - _TpVec32F ysin, ycos; - v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); - return ycos; -} - -template -inline void v_sincos_default_64f(const _TpVec64F &x, _TpVec64F &ysin, _TpVec64F &ycos) { - const _TpVec64F v_cephes_FOPI = v_setall_<_TpVec64F>(1.2732395447351626861510701069801148); // 4 / M_PI - const _TpVec64F v_minus_DP1 = v_setall_<_TpVec64F>(-7.853981554508209228515625E-1); - const _TpVec64F v_minus_DP2 = v_setall_<_TpVec64F>(-7.94662735614792836714E-9); - const _TpVec64F v_minus_DP3 = v_setall_<_TpVec64F>(-3.06161699786838294307E-17); - const _TpVec64F v_sin_C1 = v_setall_<_TpVec64F>(1.58962301576546568060E-10); - const _TpVec64F v_sin_C2 = v_setall_<_TpVec64F>(-2.50507477628578072866E-8); - const _TpVec64F v_sin_C3 = v_setall_<_TpVec64F>(2.75573136213857245213E-6); - const _TpVec64F v_sin_C4 = v_setall_<_TpVec64F>(-1.98412698295895385996E-4); - const _TpVec64F v_sin_C5 = v_setall_<_TpVec64F>(8.33333333332211858878E-3); - const _TpVec64F v_sin_C6 = v_setall_<_TpVec64F>(-1.66666666666666307295E-1); - const _TpVec64F v_cos_C1 = v_setall_<_TpVec64F>(-1.13585365213876817300E-11); - const _TpVec64F v_cos_C2 = v_setall_<_TpVec64F>(2.08757008419747316778E-9); - const _TpVec64F v_cos_C3 = v_setall_<_TpVec64F>(-2.75573141792967388112E-7); - const _TpVec64F v_cos_C4 = v_setall_<_TpVec64F>(2.48015872888517045348E-5); - const _TpVec64F v_cos_C5 = v_setall_<_TpVec64F>(-1.38888888888730564116E-3); - const _TpVec64F v_cos_C6 = v_setall_<_TpVec64F>(4.16666666666665929218E-2); - const _TpVec64F v_nan = v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000)); - const _TpVec64F v_neg_zero = v_setall_<_TpVec64F>(-0.0); - - _TpVec64F _vx, _vy, sign_mask_sin, sign_mask_cos; - _TpVec64S emm2; - - sign_mask_sin = v_lt(x, v_setzero_<_TpVec64F>()); - _vx = v_abs(x); - _vy = v_mul(_vx, v_cephes_FOPI); - - emm2 = v_expand_low(v_trunc(_vy)); - emm2 = v_add(emm2, v_setall_<_TpVec64S>((int64)1)); - emm2 = v_and(emm2, v_setall_<_TpVec64S>((int64)~1)); - _vy = v_cvt_f64(emm2); - - _TpVec64F poly_mask = v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)0))); - - _vx = v_fma(_vy, v_minus_DP1, _vx); - _vx = v_fma(_vy, v_minus_DP2, _vx); - _vx = v_fma(_vy, v_minus_DP3, _vx); - - sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0)))); - sign_mask_cos = v_reinterpret_as_f64(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0))); - - _TpVec64F _vxx = v_mul(_vx, _vx); - _TpVec64F y1, y2; - - y1 = v_fma(v_cos_C1, _vxx, v_cos_C2); - y1 = v_fma(y1, _vxx, v_cos_C3); - y1 = v_fma(y1, _vxx, v_cos_C4); - y1 = v_fma(y1, _vxx, v_cos_C5); - y1 = v_fma(y1, _vxx, v_cos_C6); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(-0.5)); - y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(1.0)); - - y2 = v_fma(v_sin_C1, _vxx, v_sin_C2); - y2 = v_fma(y2, _vxx, v_sin_C3); - y2 = v_fma(y2, _vxx, v_sin_C4); - y2 = v_fma(y2, _vxx, v_sin_C5); - y2 = v_fma(y2, _vxx, v_sin_C6); - y2 = v_mul(y2, _vxx); - y2 = v_fma(y2, _vx, _vx); - - ysin = v_select(poly_mask, y2, y1); - ycos = v_select(poly_mask, y1, y2); - ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); - ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); - - // sincos(NAN) -> NAN, sincos(±INF) -> NAN - _TpVec64F mask_inf = v_eq(_vx, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); - _TpVec64F mask_nan = v_or(mask_inf, v_ne(x, x)); - ysin = v_select(mask_nan, v_nan, ysin); - ycos = v_select(mask_nan, v_nan, ycos); -} - -template -inline _TpVec64F v_sin_default_64f(const _TpVec64F &x) { - _TpVec64F ysin, ycos; - v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); - return ysin; -} - -template -inline _TpVec64F v_cos_default_64f(const _TpVec64F &x) { - _TpVec64F ysin, ycos; - v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); - return ycos; -} -//! @} - - -/* This implementation is derived from the approximation approach of Error Function (Erf) from PyTorch - https://github.com/pytorch/pytorch/blob/9c50ecc84b9a6e699a7f058891b889aafbf976c7/aten/src/ATen/cpu/vec/vec512/vec512_float.h#L189-L220 -*/ - -//! @name Error Function -//! @{ -template -inline _TpVec32F v_erf_default_32f(const _TpVec32F &v) { - const _TpVec32F coef0 = v_setall_<_TpVec32F>(0.3275911f), - coef1 = v_setall_<_TpVec32F>(1.061405429f), - coef2 = v_setall_<_TpVec32F>(-1.453152027f), - coef3 = v_setall_<_TpVec32F>(1.421413741f), - coef4 = v_setall_<_TpVec32F>(-0.284496736f), - coef5 = v_setall_<_TpVec32F>(0.254829592f), - ones = v_setall_<_TpVec32F>(1.0f), - neg_zeros = v_setall_<_TpVec32F>(-0.f); - _TpVec32F t = v_abs(v); - // sign(v) - _TpVec32F sign_mask = v_and(neg_zeros, v); - - t = v_div(ones, v_fma(coef0, t, ones)); - _TpVec32F r = v_fma(coef1, t, coef2); - r = v_fma(r, t, coef3); - r = v_fma(r, t, coef4); - r = v_fma(r, t, coef5); - // - v * v - _TpVec32F v2 = v_mul(v, v); - _TpVec32F mv2 = v_xor(neg_zeros, v2); - // - exp(- v * v) - _TpVec32F exp = v_exp_default_32f<_TpVec32F, _TpVec32S>(mv2); - _TpVec32F neg_exp = v_xor(neg_zeros, exp); - _TpVec32F res = v_mul(t, neg_exp); - res = v_fma(r, res, ones); - return v_xor(sign_mask, res); -} -//! @} - -#endif // OPENCV_HAL_INTRIN_MATH_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + + +/* Universal Intrinsics implementation of sin, cos, exp and log + + Inspired by Intel Approximate Math library, and based on the + corresponding algorithms of the cephes math library +*/ + +/* Copyright (C) 2010,2011 RJVB - extensions */ +/* Copyright (C) 2011 Julien Pommier + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + (this is the zlib license) +*/ +#ifndef OPENCV_HAL_INTRIN_MATH_HPP +#define OPENCV_HAL_INTRIN_MATH_HPP + +//! @name Exponential +//! @{ +// Implementation is the same as float32 vector. +template +inline _TpVec16F v_exp_default_16f(const _TpVec16F &x) { + const _TpVec16F _vexp_lo_f16 = v_setall_<_TpVec16F>(-10.7421875f); + const _TpVec16F _vexp_hi_f16 = v_setall_<_TpVec16F>(11.f); + const _TpVec16F _vexp_half_fp16 = v_setall_<_TpVec16F>(0.5f); + const _TpVec16F _vexp_one_fp16 = v_setall_<_TpVec16F>(1.f); + const _TpVec16F _vexp_LOG2EF_f16 = v_setall_<_TpVec16F>(1.44269504088896341f); + const _TpVec16F _vexp_C1_f16 = v_setall_<_TpVec16F>(-6.93359375E-1f); + const _TpVec16F _vexp_C2_f16 = v_setall_<_TpVec16F>(2.12194440E-4f); + const _TpVec16F _vexp_p0_f16 = v_setall_<_TpVec16F>(1.9875691500E-4f); + const _TpVec16F _vexp_p1_f16 = v_setall_<_TpVec16F>(1.3981999507E-3f); + const _TpVec16F _vexp_p2_f16 = v_setall_<_TpVec16F>(8.3334519073E-3f); + const _TpVec16F _vexp_p3_f16 = v_setall_<_TpVec16F>(4.1665795894E-2f); + const _TpVec16F _vexp_p4_f16 = v_setall_<_TpVec16F>(1.6666665459E-1f); + const _TpVec16F _vexp_p5_f16 = v_setall_<_TpVec16F>(5.0000001201E-1f); + + _TpVec16F _vexp_, _vexp_x, _vexp_y, _vexp_xx; + _TpVec16S _vexp_mm; + const _TpVec16S _vexp_bias_s16 = v_setall_<_TpVec16S>((short)0xf); + + // compute exponential of x + _vexp_x = v_max(x, _vexp_lo_f16); + _vexp_x = v_min(_vexp_x, _vexp_hi_f16); + + _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f16, _vexp_half_fp16); + _vexp_mm = v_floor(_vexp_); + _vexp_ = v_cvt_f16(_vexp_mm); + _vexp_mm = v_add(_vexp_mm, _vexp_bias_s16); + _vexp_mm = v_shl(_vexp_mm, 10); + + _vexp_x = v_fma(_vexp_, _vexp_C1_f16, _vexp_x); + _vexp_x = v_fma(_vexp_, _vexp_C2_f16, _vexp_x); + _vexp_xx = v_mul(_vexp_x, _vexp_x); + + _vexp_y = v_fma(_vexp_x, _vexp_p0_f16, _vexp_p1_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f16); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f16); + + _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); + _vexp_y = v_add(_vexp_y, _vexp_one_fp16); + _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f16(_vexp_mm)); + + // exp(NAN) -> NAN + _TpVec16F mask_not_nan = v_not_nan(x); + return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); +} + +template +inline _TpVec32F v_exp_default_32f(const _TpVec32F &x) { + const _TpVec32F _vexp_lo_f32 = v_setall_<_TpVec32F>(-88.3762626647949f); + const _TpVec32F _vexp_hi_f32 = v_setall_<_TpVec32F>(89.f); + const _TpVec32F _vexp_half_fp32 = v_setall_<_TpVec32F>(0.5f); + const _TpVec32F _vexp_one_fp32 = v_setall_<_TpVec32F>(1.f); + const _TpVec32F _vexp_LOG2EF_f32 = v_setall_<_TpVec32F>(1.44269504088896341f); + const _TpVec32F _vexp_C1_f32 = v_setall_<_TpVec32F>(-6.93359375E-1f); + const _TpVec32F _vexp_C2_f32 = v_setall_<_TpVec32F>(2.12194440E-4f); + const _TpVec32F _vexp_p0_f32 = v_setall_<_TpVec32F>(1.9875691500E-4f); + const _TpVec32F _vexp_p1_f32 = v_setall_<_TpVec32F>(1.3981999507E-3f); + const _TpVec32F _vexp_p2_f32 = v_setall_<_TpVec32F>(8.3334519073E-3f); + const _TpVec32F _vexp_p3_f32 = v_setall_<_TpVec32F>(4.1665795894E-2f); + const _TpVec32F _vexp_p4_f32 = v_setall_<_TpVec32F>(1.6666665459E-1f); + const _TpVec32F _vexp_p5_f32 = v_setall_<_TpVec32F>(5.0000001201E-1f); + + _TpVec32F _vexp_, _vexp_x, _vexp_y, _vexp_xx; + _TpVec32S _vexp_mm; + const _TpVec32S _vexp_bias_s32 = v_setall_<_TpVec32S>((int)0x7f); + + // compute exponential of x + _vexp_x = v_max(x, _vexp_lo_f32); + _vexp_x = v_min(_vexp_x, _vexp_hi_f32); + + _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f32, _vexp_half_fp32); + _vexp_mm = v_floor(_vexp_); + _vexp_ = v_cvt_f32(_vexp_mm); + _vexp_mm = v_add(_vexp_mm, _vexp_bias_s32); + _vexp_mm = v_shl(_vexp_mm, 23); + + _vexp_x = v_fma(_vexp_, _vexp_C1_f32, _vexp_x); + _vexp_x = v_fma(_vexp_, _vexp_C2_f32, _vexp_x); + _vexp_xx = v_mul(_vexp_x, _vexp_x); + + _vexp_y = v_fma(_vexp_x, _vexp_p0_f32, _vexp_p1_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p2_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p3_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p4_f32); + _vexp_y = v_fma(_vexp_y, _vexp_x, _vexp_p5_f32); + + _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_x); + _vexp_y = v_add(_vexp_y, _vexp_one_fp32); + _vexp_y = v_mul(_vexp_y, v_reinterpret_as_f32(_vexp_mm)); + + // exp(NAN) -> NAN + _TpVec32F mask_not_nan = v_not_nan(x); + return v_select(mask_not_nan, _vexp_y, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); +} + +template +inline _TpVec64F v_exp_default_64f(const _TpVec64F &x) { + const _TpVec64F _vexp_lo_f64 = v_setall_<_TpVec64F>(-709.43613930310391424428); + const _TpVec64F _vexp_hi_f64 = v_setall_<_TpVec64F>(710.); + const _TpVec64F _vexp_half_f64 = v_setall_<_TpVec64F>(0.5); + const _TpVec64F _vexp_one_f64 = v_setall_<_TpVec64F>(1.0); + const _TpVec64F _vexp_two_f64 = v_setall_<_TpVec64F>(2.0); + const _TpVec64F _vexp_LOG2EF_f64 = v_setall_<_TpVec64F>(1.44269504088896340736); + const _TpVec64F _vexp_C1_f64 = v_setall_<_TpVec64F>(-6.93145751953125E-1); + const _TpVec64F _vexp_C2_f64 = v_setall_<_TpVec64F>(-1.42860682030941723212E-6); + const _TpVec64F _vexp_p0_f64 = v_setall_<_TpVec64F>(1.26177193074810590878E-4); + const _TpVec64F _vexp_p1_f64 = v_setall_<_TpVec64F>(3.02994407707441961300E-2); + const _TpVec64F _vexp_p2_f64 = v_setall_<_TpVec64F>(9.99999999999999999910E-1); + const _TpVec64F _vexp_q0_f64 = v_setall_<_TpVec64F>(3.00198505138664455042E-6); + const _TpVec64F _vexp_q1_f64 = v_setall_<_TpVec64F>(2.52448340349684104192E-3); + const _TpVec64F _vexp_q2_f64 = v_setall_<_TpVec64F>(2.27265548208155028766E-1); + const _TpVec64F _vexp_q3_f64 = v_setall_<_TpVec64F>(2.00000000000000000009E0); + + _TpVec64F _vexp_, _vexp_x, _vexp_y, _vexp_z, _vexp_xx; + _TpVec64S _vexp_mm; + const _TpVec64S _vexp_bias_s64 = v_setall_<_TpVec64S>((int64)0x3ff); + + // compute exponential of x + _vexp_x = v_max(x, _vexp_lo_f64); + _vexp_x = v_min(_vexp_x, _vexp_hi_f64); + + _vexp_ = v_fma(_vexp_x, _vexp_LOG2EF_f64, _vexp_half_f64); + _vexp_mm = v_expand_low(v_floor(_vexp_)); + _vexp_ = v_cvt_f64(_vexp_mm); + _vexp_mm = v_add(_vexp_mm, _vexp_bias_s64); + _vexp_mm = v_shl(_vexp_mm, 52); + + _vexp_x = v_fma(_vexp_, _vexp_C1_f64, _vexp_x); + _vexp_x = v_fma(_vexp_, _vexp_C2_f64, _vexp_x); + _vexp_xx = v_mul(_vexp_x, _vexp_x); + + _vexp_y = v_fma(_vexp_xx, _vexp_p0_f64, _vexp_p1_f64); + _vexp_y = v_fma(_vexp_y, _vexp_xx, _vexp_p2_f64); + _vexp_y = v_mul(_vexp_y, _vexp_x); + + _vexp_z = v_fma(_vexp_xx, _vexp_q0_f64, _vexp_q1_f64); + _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q2_f64); + _vexp_z = v_fma(_vexp_xx, _vexp_z, _vexp_q3_f64); + + _vexp_z = v_div(_vexp_y, v_sub(_vexp_z, _vexp_y)); + _vexp_z = v_fma(_vexp_two_f64, _vexp_z, _vexp_one_f64); + _vexp_z = v_mul(_vexp_z, v_reinterpret_as_f64(_vexp_mm)); + + // exp(NAN) -> NAN + _TpVec64F mask_not_nan = v_not_nan(x); + return v_select(mask_not_nan, _vexp_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7FF8000000000000))); +} +//! @} + +//! @name Natural Logarithm +//! @{ +template +inline _TpVec16F v_log_default_16f(const _TpVec16F &x) { + const _TpVec16F _vlog_one_fp16 = v_setall_<_TpVec16F>(1.0f); + const _TpVec16F _vlog_SQRTHF_fp16 = v_setall_<_TpVec16F>(0.707106781186547524f); + const _TpVec16F _vlog_q1_fp16 = v_setall_<_TpVec16F>(-2.12194440E-4f); + const _TpVec16F _vlog_q2_fp16 = v_setall_<_TpVec16F>(0.693359375f); + const _TpVec16F _vlog_p0_fp16 = v_setall_<_TpVec16F>(7.0376836292E-2f); + const _TpVec16F _vlog_p1_fp16 = v_setall_<_TpVec16F>(-1.1514610310E-1f); + const _TpVec16F _vlog_p2_fp16 = v_setall_<_TpVec16F>(1.1676998740E-1f); + const _TpVec16F _vlog_p3_fp16 = v_setall_<_TpVec16F>(-1.2420140846E-1f); + const _TpVec16F _vlog_p4_fp16 = v_setall_<_TpVec16F>(1.4249322787E-1f); + const _TpVec16F _vlog_p5_fp16 = v_setall_<_TpVec16F>(-1.6668057665E-1f); + const _TpVec16F _vlog_p6_fp16 = v_setall_<_TpVec16F>(2.0000714765E-1f); + const _TpVec16F _vlog_p7_fp16 = v_setall_<_TpVec16F>(-2.4999993993E-1f); + const _TpVec16F _vlog_p8_fp16 = v_setall_<_TpVec16F>(3.3333331174E-1f); + + _TpVec16F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; + _TpVec16S _vlog_ux, _vlog_emm0; + const _TpVec16S _vlog_inv_mant_mask_s16 = v_setall_<_TpVec16S>((short)~0x7c00); + + _vlog_ux = v_reinterpret_as_s16(x); + _vlog_emm0 = v_shr(_vlog_ux, 10); + + _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s16); + _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s16(v_setall_<_TpVec16F>(0.5f))); + _vlog_x = v_reinterpret_as_f16(_vlog_ux); + + _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec16S>((short)0xf)); + _vlog_e = v_cvt_f16(_vlog_emm0); + + _vlog_e = v_add(_vlog_e, _vlog_one_fp16); + + _TpVec16F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp16); + _vlog_tmp = v_and(_vlog_x, _vlog_mask); + _vlog_x = v_sub(_vlog_x, _vlog_one_fp16); + _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp16, _vlog_mask)); + _vlog_x = v_add(_vlog_x, _vlog_tmp); + + _vlog_z = v_mul(_vlog_x, _vlog_x); + + _vlog_y = v_fma(_vlog_p0_fp16, _vlog_x, _vlog_p1_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp16); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp16); + _vlog_y = v_mul(_vlog_y, _vlog_x); + _vlog_y = v_mul(_vlog_y, _vlog_z); + + _vlog_y = v_fma(_vlog_e, _vlog_q1_fp16, _vlog_y); + + _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec16F>(0.5f))); + + _vlog_x = v_add(_vlog_x, _vlog_y); + _vlog_x = v_fma(_vlog_e, _vlog_q2_fp16, _vlog_x); + // log(0) -> -INF + _TpVec16F mask_zero = v_eq(x, v_setzero_<_TpVec16F>()); + _vlog_x = v_select(mask_zero, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0xfc00)), _vlog_x); + // log(NEG), log(NAN) -> NAN + _TpVec16F mask_not_nan = v_ge(x, v_setzero_<_TpVec16F>()); + _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00))); + // log(INF) -> INF + _TpVec16F mask_inf = v_eq(x, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); + _vlog_x = v_select(mask_inf, x, _vlog_x); + return _vlog_x; +} + +template +inline _TpVec32F v_log_default_32f(const _TpVec32F &x) { + const _TpVec32F _vlog_one_fp32 = v_setall_<_TpVec32F>(1.0f); + const _TpVec32F _vlog_SQRTHF_fp32 = v_setall_<_TpVec32F>(0.707106781186547524f); + const _TpVec32F _vlog_q1_fp32 = v_setall_<_TpVec32F>(-2.12194440E-4f); + const _TpVec32F _vlog_q2_fp32 = v_setall_<_TpVec32F>(0.693359375f); + const _TpVec32F _vlog_p0_fp32 = v_setall_<_TpVec32F>(7.0376836292E-2f); + const _TpVec32F _vlog_p1_fp32 = v_setall_<_TpVec32F>(-1.1514610310E-1f); + const _TpVec32F _vlog_p2_fp32 = v_setall_<_TpVec32F>(1.1676998740E-1f); + const _TpVec32F _vlog_p3_fp32 = v_setall_<_TpVec32F>(-1.2420140846E-1f); + const _TpVec32F _vlog_p4_fp32 = v_setall_<_TpVec32F>(1.4249322787E-1f); + const _TpVec32F _vlog_p5_fp32 = v_setall_<_TpVec32F>(-1.6668057665E-1f); + const _TpVec32F _vlog_p6_fp32 = v_setall_<_TpVec32F>(2.0000714765E-1f); + const _TpVec32F _vlog_p7_fp32 = v_setall_<_TpVec32F>(-2.4999993993E-1f); + const _TpVec32F _vlog_p8_fp32 = v_setall_<_TpVec32F>(3.3333331174E-1f); + + _TpVec32F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp; + _TpVec32S _vlog_ux, _vlog_emm0; + const _TpVec32S _vlog_inv_mant_mask_s32 = v_setall_<_TpVec32S>((int)~0x7f800000); + + _vlog_ux = v_reinterpret_as_s32(x); + _vlog_emm0 = v_shr(_vlog_ux, 23); + + _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s32); + _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s32(v_setall_<_TpVec32F>(0.5f))); + _vlog_x = v_reinterpret_as_f32(_vlog_ux); + + _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec32S>((int)0x7f)); + _vlog_e = v_cvt_f32(_vlog_emm0); + + _vlog_e = v_add(_vlog_e, _vlog_one_fp32); + + _TpVec32F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp32); + _vlog_tmp = v_and(_vlog_x, _vlog_mask); + _vlog_x = v_sub(_vlog_x, _vlog_one_fp32); + _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp32, _vlog_mask)); + _vlog_x = v_add(_vlog_x, _vlog_tmp); + + _vlog_z = v_mul(_vlog_x, _vlog_x); + + _vlog_y = v_fma(_vlog_p0_fp32, _vlog_x, _vlog_p1_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p6_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p7_fp32); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p8_fp32); + _vlog_y = v_mul(_vlog_y, _vlog_x); + _vlog_y = v_mul(_vlog_y, _vlog_z); + + _vlog_y = v_fma(_vlog_e, _vlog_q1_fp32, _vlog_y); + + _vlog_y = v_sub(_vlog_y, v_mul(_vlog_z, v_setall_<_TpVec32F>(0.5f))); + + _vlog_x = v_add(_vlog_x, _vlog_y); + _vlog_x = v_fma(_vlog_e, _vlog_q2_fp32, _vlog_x); + // log(0) -> -INF + _TpVec32F mask_zero = v_eq(x, v_setzero_<_TpVec32F>()); + _vlog_x = v_select(mask_zero, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0xff800000)), _vlog_x); + // log(NEG), log(NAN) -> NAN + _TpVec32F mask_not_nan = v_ge(x, v_setzero_<_TpVec32F>()); + _vlog_x = v_select(mask_not_nan, _vlog_x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000))); + // log(INF) -> INF + _TpVec32F mask_inf = v_eq(x, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); + _vlog_x = v_select(mask_inf, x, _vlog_x); + return _vlog_x; +} + +template +inline _TpVec64F v_log_default_64f(const _TpVec64F &x) { + const _TpVec64F _vlog_one_fp64 = v_setall_<_TpVec64F>(1.0); + const _TpVec64F _vlog_SQRTHF_fp64 = v_setall_<_TpVec64F>(0.7071067811865475244); + const _TpVec64F _vlog_p0_fp64 = v_setall_<_TpVec64F>(1.01875663804580931796E-4); + const _TpVec64F _vlog_p1_fp64 = v_setall_<_TpVec64F>(4.97494994976747001425E-1); + const _TpVec64F _vlog_p2_fp64 = v_setall_<_TpVec64F>(4.70579119878881725854); + const _TpVec64F _vlog_p3_fp64 = v_setall_<_TpVec64F>(1.44989225341610930846E1); + const _TpVec64F _vlog_p4_fp64 = v_setall_<_TpVec64F>(1.79368678507819816313E1); + const _TpVec64F _vlog_p5_fp64 = v_setall_<_TpVec64F>(7.70838733755885391666); + const _TpVec64F _vlog_q0_fp64 = v_setall_<_TpVec64F>(1.12873587189167450590E1); + const _TpVec64F _vlog_q1_fp64 = v_setall_<_TpVec64F>(4.52279145837532221105E1); + const _TpVec64F _vlog_q2_fp64 = v_setall_<_TpVec64F>(8.29875266912776603211E1); + const _TpVec64F _vlog_q3_fp64 = v_setall_<_TpVec64F>(7.11544750618563894466E1); + const _TpVec64F _vlog_q4_fp64 = v_setall_<_TpVec64F>(2.31251620126765340583E1); + + const _TpVec64F _vlog_C0_fp64 = v_setall_<_TpVec64F>(2.121944400546905827679e-4); + const _TpVec64F _vlog_C1_fp64 = v_setall_<_TpVec64F>(0.693359375); + + _TpVec64F _vlog_x, _vlog_e, _vlog_y, _vlog_z, _vlog_tmp, _vlog_xx; + _TpVec64S _vlog_ux, _vlog_emm0; + const _TpVec64S _vlog_inv_mant_mask_s64 = v_setall_<_TpVec64S>((int64)~0x7ff0000000000000); + + _vlog_ux = v_reinterpret_as_s64(x); + _vlog_emm0 = v_shr(_vlog_ux, 52); + + _vlog_ux = v_and(_vlog_ux, _vlog_inv_mant_mask_s64); + _vlog_ux = v_or(_vlog_ux, v_reinterpret_as_s64(v_setall_<_TpVec64F>(0.5))); + _vlog_x = v_reinterpret_as_f64(_vlog_ux); + + _vlog_emm0 = v_sub(_vlog_emm0, v_setall_<_TpVec64S>((int64)0x3ff)); + _vlog_e = v_cvt_f64(_vlog_emm0); + + _vlog_e = v_add(_vlog_e, _vlog_one_fp64); + + _TpVec64F _vlog_mask = v_lt(_vlog_x, _vlog_SQRTHF_fp64); + _vlog_tmp = v_and(_vlog_x, _vlog_mask); + _vlog_x = v_sub(_vlog_x, _vlog_one_fp64); + _vlog_e = v_sub(_vlog_e, v_and(_vlog_one_fp64, _vlog_mask)); + _vlog_x = v_add(_vlog_x, _vlog_tmp); + + _vlog_xx = v_mul(_vlog_x, _vlog_x); + + _vlog_y = v_fma(_vlog_p0_fp64, _vlog_x, _vlog_p1_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p2_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p3_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p4_fp64); + _vlog_y = v_fma(_vlog_y, _vlog_x, _vlog_p5_fp64); + _vlog_y = v_mul(_vlog_y, _vlog_x); + _vlog_y = v_mul(_vlog_y, _vlog_xx); + + _vlog_z = v_add(_vlog_x, _vlog_q0_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q1_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q2_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q3_fp64); + _vlog_z = v_fma(_vlog_z, _vlog_x, _vlog_q4_fp64); + + _vlog_z = v_div(_vlog_y, _vlog_z); + _vlog_z = v_sub(_vlog_z, v_mul(_vlog_e, _vlog_C0_fp64)); + _vlog_z = v_sub(_vlog_z, v_mul(_vlog_xx, v_setall_<_TpVec64F>(0.5))); + + _vlog_z = v_add(_vlog_z, _vlog_x); + _vlog_z = v_fma(_vlog_e, _vlog_C1_fp64, _vlog_z); + + // log(0) -> -INF + _TpVec64F mask_zero = v_eq(x, v_setzero_<_TpVec64F>()); + _vlog_z = v_select(mask_zero, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0xfff0000000000000)), _vlog_z); + // log(NEG), log(NAN) -> NAN + _TpVec64F mask_not_nan = v_ge(x, v_setzero_<_TpVec64F>()); + _vlog_z = v_select(mask_not_nan, _vlog_z, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000))); + // log(INF) -> INF + _TpVec64F mask_inf = v_eq(x, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); + _vlog_z = v_select(mask_inf, x, _vlog_z); + return _vlog_z; +} +//! @} + +//! @name Sine and Cosine +//! @{ +template +inline void v_sincos_default_16f(const _TpVec16F &x, _TpVec16F &ysin, _TpVec16F &ycos) { + const _TpVec16F v_cephes_FOPI = v_setall_<_TpVec16F>(hfloat(1.27323954473516f)); // 4 / M_PI + const _TpVec16F v_minus_DP1 = v_setall_<_TpVec16F>(hfloat(-0.78515625f)); + const _TpVec16F v_minus_DP2 = v_setall_<_TpVec16F>(hfloat(-2.4187564849853515625E-4f)); + const _TpVec16F v_minus_DP3 = v_setall_<_TpVec16F>(hfloat(-3.77489497744594108E-8f)); + const _TpVec16F v_sincof_p0 = v_setall_<_TpVec16F>(hfloat(-1.9515295891E-4f)); + const _TpVec16F v_sincof_p1 = v_setall_<_TpVec16F>(hfloat(8.3321608736E-3f)); + const _TpVec16F v_sincof_p2 = v_setall_<_TpVec16F>(hfloat(-1.6666654611E-1f)); + const _TpVec16F v_coscof_p0 = v_setall_<_TpVec16F>(hfloat(2.443315711809948E-5f)); + const _TpVec16F v_coscof_p1 = v_setall_<_TpVec16F>(hfloat(-1.388731625493765E-3f)); + const _TpVec16F v_coscof_p2 = v_setall_<_TpVec16F>(hfloat(4.166664568298827E-2f)); + const _TpVec16F v_nan = v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7e00)); + const _TpVec16F v_neg_zero = v_setall_<_TpVec16F>(hfloat(-0.f)); + + _TpVec16F _vx, _vy, sign_mask_sin, sign_mask_cos; + _TpVec16S emm2; + + sign_mask_sin = v_lt(x, v_setzero_<_TpVec16F>()); + _vx = v_abs(x); + _vy = v_mul(_vx, v_cephes_FOPI); + + emm2 = v_trunc(_vy); + emm2 = v_add(emm2, v_setall_<_TpVec16S>((short)1)); + emm2 = v_and(emm2, v_setall_<_TpVec16S>((short)~1)); + _vy = v_cvt_f16(emm2); + + _TpVec16F poly_mask = v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)0))); + + _vx = v_fma(_vy, v_minus_DP1, _vx); + _vx = v_fma(_vy, v_minus_DP2, _vx); + _vx = v_fma(_vy, v_minus_DP3, _vx); + + sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f16(v_eq(v_and(emm2, v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0)))); + sign_mask_cos = v_reinterpret_as_f16(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec16S>((short)2)), v_setall_<_TpVec16S>((short)4)), v_setall_<_TpVec16S>((short)0))); + + _TpVec16F _vxx = v_mul(_vx, _vx); + _TpVec16F y1, y2; + + y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); + y1 = v_fma(y1, _vxx, v_coscof_p2); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(-0.5f))); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec16F>(hfloat(1.f))); + + y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); + y2 = v_fma(y2, _vxx, v_sincof_p2); + y2 = v_mul(y2, _vxx); + y2 = v_fma(y2, _vx, _vx); + + ysin = v_select(poly_mask, y2, y1); + ycos = v_select(poly_mask, y1, y2); + ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); + ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); + + // sincos(NAN) -> NAN, sincos(±INF) -> NAN + _TpVec16F mask_inf = v_eq(_vx, v_reinterpret_as_f16(v_setall_<_TpVec16S>((short)0x7c00))); + _TpVec16F mask_nan = v_or(mask_inf, v_ne(x, x)); + ysin = v_select(mask_nan, v_nan, ysin); + ycos = v_select(mask_nan, v_nan, ycos); +} + +template +inline _TpVec16F v_sin_default_16f(const _TpVec16F &x) { + _TpVec16F ysin, ycos; + v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); + return ysin; +} + +template +inline _TpVec16F v_cos_default_16f(const _TpVec16F &x) { + _TpVec16F ysin, ycos; + v_sincos_default_16f<_TpVec16F, _TpVec16S>(x, ysin, ycos); + return ycos; +} + + +template +inline void v_sincos_default_32f(const _TpVec32F &x, _TpVec32F &ysin, _TpVec32F &ycos) { + const _TpVec32F v_cephes_FOPI = v_setall_<_TpVec32F>(1.27323954473516f); // 4 / M_PI + const _TpVec32F v_minus_DP1 = v_setall_<_TpVec32F>(-0.78515625f); + const _TpVec32F v_minus_DP2 = v_setall_<_TpVec32F>(-2.4187564849853515625E-4f); + const _TpVec32F v_minus_DP3 = v_setall_<_TpVec32F>(-3.77489497744594108E-8f); + const _TpVec32F v_sincof_p0 = v_setall_<_TpVec32F>(-1.9515295891E-4f); + const _TpVec32F v_sincof_p1 = v_setall_<_TpVec32F>(8.3321608736E-3f); + const _TpVec32F v_sincof_p2 = v_setall_<_TpVec32F>(-1.6666654611E-1f); + const _TpVec32F v_coscof_p0 = v_setall_<_TpVec32F>(2.443315711809948E-5f); + const _TpVec32F v_coscof_p1 = v_setall_<_TpVec32F>(-1.388731625493765E-3f); + const _TpVec32F v_coscof_p2 = v_setall_<_TpVec32F>(4.166664568298827E-2f); + const _TpVec32F v_nan = v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7fc00000)); + const _TpVec32F v_neg_zero = v_setall_<_TpVec32F>(-0.f); + + _TpVec32F _vx, _vy, sign_mask_sin, sign_mask_cos; + _TpVec32S emm2; + + sign_mask_sin = v_lt(x, v_setzero_<_TpVec32F>()); + _vx = v_abs(x); + _vy = v_mul(_vx, v_cephes_FOPI); + + emm2 = v_trunc(_vy); + emm2 = v_add(emm2, v_setall_<_TpVec32S>(1)); + emm2 = v_and(emm2, v_setall_<_TpVec32S>(~1)); + _vy = v_cvt_f32(emm2); + + _TpVec32F poly_mask = v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(0))); + + _vx = v_fma(_vy, v_minus_DP1, _vx); + _vx = v_fma(_vy, v_minus_DP2, _vx); + _vx = v_fma(_vy, v_minus_DP3, _vx); + + sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f32(v_eq(v_and(emm2, v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0)))); + sign_mask_cos = v_reinterpret_as_f32(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec32S>(2)), v_setall_<_TpVec32S>(4)), v_setall_<_TpVec32S>(0))); + + _TpVec32F _vxx = v_mul(_vx, _vx); + _TpVec32F y1, y2; + + y1 = v_fma(v_coscof_p0, _vxx, v_coscof_p1); + y1 = v_fma(y1, _vxx, v_coscof_p2); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(-0.5f)); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec32F>(1.f)); + + y2 = v_fma(v_sincof_p0, _vxx, v_sincof_p1); + y2 = v_fma(y2, _vxx, v_sincof_p2); + y2 = v_mul(y2, _vxx); + y2 = v_fma(y2, _vx, _vx); + + ysin = v_select(poly_mask, y2, y1); + ycos = v_select(poly_mask, y1, y2); + ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); + ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); + + // sincos(NAN) -> NAN, sincos(±INF) -> NAN + _TpVec32F mask_inf = v_eq(_vx, v_reinterpret_as_f32(v_setall_<_TpVec32S>((int)0x7f800000))); + _TpVec32F mask_nan = v_or(mask_inf, v_ne(x, x)); + ysin = v_select(mask_nan, v_nan, ysin); + ycos = v_select(mask_nan, v_nan, ycos); +} + +template +inline _TpVec32F v_sin_default_32f(const _TpVec32F &x) { + _TpVec32F ysin, ycos; + v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); + return ysin; +} + +template +inline _TpVec32F v_cos_default_32f(const _TpVec32F &x) { + _TpVec32F ysin, ycos; + v_sincos_default_32f<_TpVec32F, _TpVec32S>(x, ysin, ycos); + return ycos; +} + +template +inline void v_sincos_default_64f(const _TpVec64F &x, _TpVec64F &ysin, _TpVec64F &ycos) { + const _TpVec64F v_cephes_FOPI = v_setall_<_TpVec64F>(1.2732395447351626861510701069801148); // 4 / M_PI + const _TpVec64F v_minus_DP1 = v_setall_<_TpVec64F>(-7.853981554508209228515625E-1); + const _TpVec64F v_minus_DP2 = v_setall_<_TpVec64F>(-7.94662735614792836714E-9); + const _TpVec64F v_minus_DP3 = v_setall_<_TpVec64F>(-3.06161699786838294307E-17); + const _TpVec64F v_sin_C1 = v_setall_<_TpVec64F>(1.58962301576546568060E-10); + const _TpVec64F v_sin_C2 = v_setall_<_TpVec64F>(-2.50507477628578072866E-8); + const _TpVec64F v_sin_C3 = v_setall_<_TpVec64F>(2.75573136213857245213E-6); + const _TpVec64F v_sin_C4 = v_setall_<_TpVec64F>(-1.98412698295895385996E-4); + const _TpVec64F v_sin_C5 = v_setall_<_TpVec64F>(8.33333333332211858878E-3); + const _TpVec64F v_sin_C6 = v_setall_<_TpVec64F>(-1.66666666666666307295E-1); + const _TpVec64F v_cos_C1 = v_setall_<_TpVec64F>(-1.13585365213876817300E-11); + const _TpVec64F v_cos_C2 = v_setall_<_TpVec64F>(2.08757008419747316778E-9); + const _TpVec64F v_cos_C3 = v_setall_<_TpVec64F>(-2.75573141792967388112E-7); + const _TpVec64F v_cos_C4 = v_setall_<_TpVec64F>(2.48015872888517045348E-5); + const _TpVec64F v_cos_C5 = v_setall_<_TpVec64F>(-1.38888888888730564116E-3); + const _TpVec64F v_cos_C6 = v_setall_<_TpVec64F>(4.16666666666665929218E-2); + const _TpVec64F v_nan = v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff8000000000000)); + const _TpVec64F v_neg_zero = v_setall_<_TpVec64F>(-0.0); + + _TpVec64F _vx, _vy, sign_mask_sin, sign_mask_cos; + _TpVec64S emm2; + + sign_mask_sin = v_lt(x, v_setzero_<_TpVec64F>()); + _vx = v_abs(x); + _vy = v_mul(_vx, v_cephes_FOPI); + + emm2 = v_expand_low(v_trunc(_vy)); + emm2 = v_add(emm2, v_setall_<_TpVec64S>((int64)1)); + emm2 = v_and(emm2, v_setall_<_TpVec64S>((int64)~1)); + _vy = v_cvt_f64(emm2); + + _TpVec64F poly_mask = v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)0))); + + _vx = v_fma(_vy, v_minus_DP1, _vx); + _vx = v_fma(_vy, v_minus_DP2, _vx); + _vx = v_fma(_vy, v_minus_DP3, _vx); + + sign_mask_sin = v_xor(sign_mask_sin, v_reinterpret_as_f64(v_eq(v_and(emm2, v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0)))); + sign_mask_cos = v_reinterpret_as_f64(v_eq(v_and(v_sub(emm2, v_setall_<_TpVec64S>((int64)2)), v_setall_<_TpVec64S>((int64)4)), v_setall_<_TpVec64S>((int64)0))); + + _TpVec64F _vxx = v_mul(_vx, _vx); + _TpVec64F y1, y2; + + y1 = v_fma(v_cos_C1, _vxx, v_cos_C2); + y1 = v_fma(y1, _vxx, v_cos_C3); + y1 = v_fma(y1, _vxx, v_cos_C4); + y1 = v_fma(y1, _vxx, v_cos_C5); + y1 = v_fma(y1, _vxx, v_cos_C6); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(-0.5)); + y1 = v_fma(y1, _vxx, v_setall_<_TpVec64F>(1.0)); + + y2 = v_fma(v_sin_C1, _vxx, v_sin_C2); + y2 = v_fma(y2, _vxx, v_sin_C3); + y2 = v_fma(y2, _vxx, v_sin_C4); + y2 = v_fma(y2, _vxx, v_sin_C5); + y2 = v_fma(y2, _vxx, v_sin_C6); + y2 = v_mul(y2, _vxx); + y2 = v_fma(y2, _vx, _vx); + + ysin = v_select(poly_mask, y2, y1); + ycos = v_select(poly_mask, y1, y2); + ysin = v_select(sign_mask_sin, ysin, v_xor(v_neg_zero, ysin)); + ycos = v_select(sign_mask_cos, v_xor(v_neg_zero, ycos), ycos); + + // sincos(NAN) -> NAN, sincos(±INF) -> NAN + _TpVec64F mask_inf = v_eq(_vx, v_reinterpret_as_f64(v_setall_<_TpVec64S>((int64)0x7ff0000000000000))); + _TpVec64F mask_nan = v_or(mask_inf, v_ne(x, x)); + ysin = v_select(mask_nan, v_nan, ysin); + ycos = v_select(mask_nan, v_nan, ycos); +} + +template +inline _TpVec64F v_sin_default_64f(const _TpVec64F &x) { + _TpVec64F ysin, ycos; + v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); + return ysin; +} + +template +inline _TpVec64F v_cos_default_64f(const _TpVec64F &x) { + _TpVec64F ysin, ycos; + v_sincos_default_64f<_TpVec64F, _TpVec64S>(x, ysin, ycos); + return ycos; +} +//! @} + + +/* This implementation is derived from the approximation approach of Error Function (Erf) from PyTorch + https://github.com/pytorch/pytorch/blob/9c50ecc84b9a6e699a7f058891b889aafbf976c7/aten/src/ATen/cpu/vec/vec512/vec512_float.h#L189-L220 +*/ + +//! @name Error Function +//! @{ +template +inline _TpVec32F v_erf_default_32f(const _TpVec32F &v) { + const _TpVec32F coef0 = v_setall_<_TpVec32F>(0.3275911f), + coef1 = v_setall_<_TpVec32F>(1.061405429f), + coef2 = v_setall_<_TpVec32F>(-1.453152027f), + coef3 = v_setall_<_TpVec32F>(1.421413741f), + coef4 = v_setall_<_TpVec32F>(-0.284496736f), + coef5 = v_setall_<_TpVec32F>(0.254829592f), + ones = v_setall_<_TpVec32F>(1.0f), + neg_zeros = v_setall_<_TpVec32F>(-0.f); + _TpVec32F t = v_abs(v); + // sign(v) + _TpVec32F sign_mask = v_and(neg_zeros, v); + + t = v_div(ones, v_fma(coef0, t, ones)); + _TpVec32F r = v_fma(coef1, t, coef2); + r = v_fma(r, t, coef3); + r = v_fma(r, t, coef4); + r = v_fma(r, t, coef5); + // - v * v + _TpVec32F v2 = v_mul(v, v); + _TpVec32F mv2 = v_xor(neg_zeros, v2); + // - exp(- v * v) + _TpVec32F exp = v_exp_default_32f<_TpVec32F, _TpVec32S>(mv2); + _TpVec32F neg_exp = v_xor(neg_zeros, exp); + _TpVec32F res = v_mul(t, neg_exp); + res = v_fma(r, res, ones); + return v_xor(sign_mask, res); +} +//! @} + +#endif // OPENCV_HAL_INTRIN_MATH_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp index 98b753c42e..3917faa292 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_msa.hpp @@ -1,1886 +1,1886 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_HAL_INTRIN_MSA_HPP -#define OPENCV_HAL_INTRIN_MSA_HPP - -#include -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @cond IGNORED -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD128 1 - -//MSA implements 128-bit wide vector registers shared with the 64-bit wide floating-point unit registers. -//MSA and FPU can not be both present, unless the FPU has 64-bit floating-point registers. -#define CV_SIMD128_64F 1 - -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16 }; - - v_uint8x16() {} - explicit v_uint8x16(v16u8 v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = msa_ld1q_u8(v); - } - - uchar get0() const - { - return msa_getq_lane_u8(val, 0); - } - - v16u8 val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(v16i8 v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = msa_ld1q_s8(v); - } - - schar get0() const - { - return msa_getq_lane_s8(val, 0); - } - - v16i8 val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(v8u16 v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = msa_ld1q_u16(v); - } - - ushort get0() const - { - return msa_getq_lane_u16(val, 0); - } - - v8u16 val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(v8i16 v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = msa_ld1q_s16(v); - } - - short get0() const - { - return msa_getq_lane_s16(val, 0); - } - - v8i16 val; -}; - -struct v_uint32x4 -{ - typedef unsigned int lane_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(v4u32 v) : val(v) {} - v_uint32x4(unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3) - { - unsigned int v[] = {v0, v1, v2, v3}; - val = msa_ld1q_u32(v); - } - - unsigned int get0() const - { - return msa_getq_lane_u32(val, 0); - } - - v4u32 val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(v4i32 v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = msa_ld1q_s32(v); - } - - int get0() const - { - return msa_getq_lane_s32(val, 0); - } - - v4i32 val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4 }; - - v_float32x4() {} - explicit v_float32x4(v4f32 v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = msa_ld1q_f32(v); - } - - float get0() const - { - return msa_getq_lane_f32(val, 0); - } - - v4f32 val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2 }; - - v_uint64x2() {} - explicit v_uint64x2(v2u64 v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = msa_ld1q_u64(v); - } - - uint64 get0() const - { - return msa_getq_lane_u64(val, 0); - } - - v2u64 val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2 }; - - v_int64x2() {} - explicit v_int64x2(v2i64 v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = msa_ld1q_s64(v); - } - - int64 get0() const - { - return msa_getq_lane_s64(val, 0); - } - - v2i64 val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2 }; - - v_float64x2() {} - explicit v_float64x2(v2f64 v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = msa_ld1q_f64(v); - } - - double get0() const - { - return msa_getq_lane_f64(val, 0); - } - - v2f64 val; -}; - -#define OPENCV_HAL_IMPL_MSA_INIT(_Tpv, _Tp, suffix) \ -inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(msa_dupq_n_##suffix((_Tp)0)); } \ -inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(msa_dupq_n_##suffix(v)); } \ -template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(MSA_TPV_REINTERPRET(v16u8, v.val)); } \ -inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(MSA_TPV_REINTERPRET(v16i8, v.val)); } \ -inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(MSA_TPV_REINTERPRET(v8u16, v.val)); } \ -inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(MSA_TPV_REINTERPRET(v8i16, v.val)); } \ -inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(MSA_TPV_REINTERPRET(v4u32, v.val)); } \ -inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(MSA_TPV_REINTERPRET(v4i32, v.val)); } \ -inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(MSA_TPV_REINTERPRET(v2u64, v.val)); } \ -inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(MSA_TPV_REINTERPRET(v2i64, v.val)); } \ -inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(MSA_TPV_REINTERPRET(v4f32, v.val)); } \ -inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(MSA_TPV_REINTERPRET(v2f64, v.val)); } - -OPENCV_HAL_IMPL_MSA_INIT(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_MSA_INIT(int8x16, schar, s8) -OPENCV_HAL_IMPL_MSA_INIT(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_MSA_INIT(int16x8, short, s16) -OPENCV_HAL_IMPL_MSA_INIT(uint32x4, unsigned int, u32) -OPENCV_HAL_IMPL_MSA_INIT(int32x4, int, s32) -OPENCV_HAL_IMPL_MSA_INIT(uint64x2, uint64, u64) -OPENCV_HAL_IMPL_MSA_INIT(int64x2, int64, s64) -OPENCV_HAL_IMPL_MSA_INIT(float32x4, float, f32) -OPENCV_HAL_IMPL_MSA_INIT(float64x2, double, f64) - -#define OPENCV_HAL_IMPL_MSA_PACK(_Tpvec, _Tpwvec, pack, mov, rshr) \ -inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - return _Tpvec(mov(a.val, b.val)); \ -} \ -template inline \ -_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - return _Tpvec(rshr(a.val, b.val, n)); \ -} - -OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_uint16x8, pack, msa_qpack_u16, msa_qrpackr_u16) -OPENCV_HAL_IMPL_MSA_PACK(v_int8x16, v_int16x8, pack, msa_qpack_s16, msa_qrpackr_s16) -OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_uint32x4, pack, msa_qpack_u32, msa_qrpackr_u32) -OPENCV_HAL_IMPL_MSA_PACK(v_int16x8, v_int32x4, pack, msa_qpack_s32, msa_qrpackr_s32) -OPENCV_HAL_IMPL_MSA_PACK(v_uint32x4, v_uint64x2, pack, msa_pack_u64, msa_rpackr_u64) -OPENCV_HAL_IMPL_MSA_PACK(v_int32x4, v_int64x2, pack, msa_pack_s64, msa_rpackr_s64) -OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_int16x8, pack_u, msa_qpacku_s16, msa_qrpackru_s16) -OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_int32x4, pack_u, msa_qpacku_s32, msa_qrpackru_s32) - -#define OPENCV_HAL_IMPL_MSA_PACK_STORE(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ -inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = mov(a.val); \ - msa_st1_##suffix(ptr, a1); \ -} \ -template inline \ -void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = rshr(a.val, n); \ - msa_st1_##suffix(ptr, a1); \ -} - -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_uint16x8, pack, msa_qmovn_u16, msa_qrshrn_n_u16) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int8x16, schar, v8i8, s8, v_int16x8, pack, msa_qmovn_s16, msa_qrshrn_n_s16) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_uint32x4, pack, msa_qmovn_u32, msa_qrshrn_n_u32) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int16x8, short, v4i16, s16, v_int32x4, pack, msa_qmovn_s32, msa_qrshrn_n_s32) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint32x4, unsigned, v2u32, u32, v_uint64x2, pack, msa_movn_u64, msa_rshrn_n_u64) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int32x4, int, v2i32, s32, v_int64x2, pack, msa_movn_s64, msa_rshrn_n_s64) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_int16x8, pack_u, msa_qmovun_s16, msa_qrshrun_n_s16) -OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_int32x4, pack_u, msa_qmovun_s32, msa_qrshrun_n_s32) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - return v_uint8x16(msa_pack_u16(a.val, b.val)); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - return v_uint8x16(msa_pack_u16(msa_pack_u32(a.val, b.val), msa_pack_u32(c.val, d.val))); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - v8u16 abcd = msa_pack_u32(msa_pack_u64(a.val, b.val), msa_pack_u64(c.val, d.val)); - v8u16 efgh = msa_pack_u32(msa_pack_u64(e.val, f.val), msa_pack_u64(g.val, h.val)); - return v_uint8x16(msa_pack_u16(abcd, efgh)); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - v4f32 v0 = v.val; - v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); - res = msa_mlaq_lane_f32(res, m1.val, v0, 1); - res = msa_mlaq_lane_f32(res, m2.val, v0, 2); - res = msa_mlaq_lane_f32(res, m3.val, v0, 3); - return v_float32x4(res); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - v4f32 v0 = v.val; - v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); - res = msa_mlaq_lane_f32(res, m1.val, v0, 1); - res = msa_mlaq_lane_f32(res, m2.val, v0, 2); - res = msa_addq_f32(res, a.val); - return v_float32x4(res); -} - -#define OPENCV_HAL_IMPL_MSA_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint8x16, msa_qaddq_u8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint8x16, msa_qsubq_u8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int8x16, msa_qaddq_s8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int8x16, msa_qsubq_s8) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint16x8, msa_qaddq_u16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint16x8, msa_qsubq_u16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int16x8, msa_qaddq_s16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int16x8, msa_qsubq_s16) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int32x4, msa_addq_s32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int32x4, msa_subq_s32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_int32x4, msa_mulq_s32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint32x4, msa_addq_u32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint32x4, msa_subq_u32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_uint32x4, msa_mulq_u32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float32x4, msa_addq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float32x4, msa_subq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float32x4, msa_mulq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int64x2, msa_addq_s64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int64x2, msa_subq_s64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint64x2, msa_addq_u64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint64x2, msa_subq_u64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float32x4, msa_divq_f32) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float64x2, msa_addq_f64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float64x2, msa_subq_f64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float64x2, msa_mulq_f64) -OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float64x2, msa_divq_f64) - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_MSA_MUL_SAT(_Tpvec, _Tpwvec) \ -inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ -} - -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int16x8, v_int32x4) -OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint16x8, v_uint32x4) - -// Multiply and expand -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - v16i8 a_lo, a_hi, b_lo, b_hi; - - ILVRL_B2_SB(a.val, msa_dupq_n_s8(0), a_lo, a_hi); - ILVRL_B2_SB(b.val, msa_dupq_n_s8(0), b_lo, b_hi); - c.val = msa_mulq_s16(msa_paddlq_s8(a_lo), msa_paddlq_s8(b_lo)); - d.val = msa_mulq_s16(msa_paddlq_s8(a_hi), msa_paddlq_s8(b_hi)); -} - -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - v16u8 a_lo, a_hi, b_lo, b_hi; - - ILVRL_B2_UB(a.val, msa_dupq_n_u8(0), a_lo, a_hi); - ILVRL_B2_UB(b.val, msa_dupq_n_u8(0), b_lo, b_hi); - c.val = msa_mulq_u16(msa_paddlq_u8(a_lo), msa_paddlq_u8(b_lo)); - d.val = msa_mulq_u16(msa_paddlq_u8(a_hi), msa_paddlq_u8(b_hi)); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - v8i16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); - ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); - c.val = msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)); - d.val = msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - v8u16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); - ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); - c.val = msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)); - d.val = msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - v4u32 a_lo, a_hi, b_lo, b_hi; - - ILVRL_W2_UW(a.val, msa_dupq_n_u32(0), a_lo, a_hi); - ILVRL_W2_UW(b.val, msa_dupq_n_u32(0), b_lo, b_hi); - c.val = msa_mulq_u64(msa_paddlq_u32(a_lo), msa_paddlq_u32(b_lo)); - d.val = msa_mulq_u64(msa_paddlq_u32(a_hi), msa_paddlq_u32(b_hi)); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - v8i16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); - ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); - - return v_int16x8(msa_packr_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)), - msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)), 16)); -} - -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - v8u16 a_lo, a_hi, b_lo, b_hi; - - ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); - ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); - - return v_uint16x8(msa_packr_u32(msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)), - msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)), 16)); -} - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ return v_int32x4(msa_dotp_s_w(a.val, b.val)); } -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_int32x4(msa_dpadd_s_w(c.val , a.val, b.val)); } - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ return v_int64x2(msa_dotp_s_d(a.val, b.val)); } -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_int64x2(msa_dpadd_s_d(c.val , a.val, b.val)); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); - v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); - v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); - v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); - v4u32 prod = msa_dotp_u_w(even_a, even_b); - return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ - v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); - v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); - v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); - v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); - v4u32 prod = msa_dpadd_u_w(c.val, even_a, even_b); - return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - v8i16 prod = msa_dotp_s_h(a.val, b.val); - return v_int32x4(msa_hadd_s32(prod, prod)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, - const v_int32x4& c) -{ return v_dotprod_expand(a, b) + c; } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); - v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); - v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); - v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); - v2u64 prod = msa_dotp_u_d(even_a, even_b); - return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, - const v_uint64x2& c) -{ - v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); - v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); - v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); - v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); - v2u64 prod = msa_dpadd_u_d(c.val, even_a, even_b); - return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v4i32 prod = msa_dotp_s_w(a.val, b.val); - return v_int64x2(msa_hadd_s64(prod, prod)); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_dotprod_expand(a, b, c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -#define OPENCV_HAL_IMPL_MSA_LOGIC_OP(_Tpvec, _Tpv, suffix) \ -OPENCV_HAL_IMPL_MSA_BIN_OP(v_and, _Tpvec, msa_andq_##suffix) \ -OPENCV_HAL_IMPL_MSA_BIN_OP(v_or, _Tpvec, msa_orrq_##suffix) \ -OPENCV_HAL_IMPL_MSA_BIN_OP(v_xor, _Tpvec, msa_eorq_##suffix) \ -inline _Tpvec v_not(const _Tpvec& a) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_u8(MSA_TPV_REINTERPRET(v16u8, a.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint8x16, v16u8, u8) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int8x16, v16i8, s8) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint16x8, v8u16, u16) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int16x8, v8i16, s16) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint32x4, v4u32, u32) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int32x4, v4i32, s32) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint64x2, v2u64, u64) -OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int64x2, v2i64, s64) - -#define OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(bin_op, intrin) \ -inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ -{ \ - return v_float32x4(MSA_TPV_REINTERPRET(v4f32, intrin(MSA_TPV_REINTERPRET(v4i32, a.val), MSA_TPV_REINTERPRET(v4i32, b.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_and, msa_andq_s32) -OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_or, msa_orrq_s32) -OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_xor, msa_eorq_s32) - -inline v_float32x4 v_not(const v_float32x4& a) -{ - return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); -} - -/* v_abs */ -#define OPENCV_HAL_IMPL_MSA_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ -inline _Tpuvec v_abs(const _Tpsvec& a) \ -{ \ - return v_reinterpret_as_##usuffix(_Tpsvec(msa_absq_##ssuffix(a.val))); \ -} - -OPENCV_HAL_IMPL_MSA_ABS(v_uint8x16, v_int8x16, u8, s8) -OPENCV_HAL_IMPL_MSA_ABS(v_uint16x8, v_int16x8, u16, s16) -OPENCV_HAL_IMPL_MSA_ABS(v_uint32x4, v_int32x4, u32, s32) - -/* v_abs(float), v_sqrt, v_invsqrt */ -#define OPENCV_HAL_IMPL_MSA_BASIC_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a) \ -{ \ - return _Tpvec(intrin(a.val)); \ -} - -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_abs, msa_absq_f32) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_abs, msa_absq_f64) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_sqrt, msa_sqrtq_f32) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_invsqrt, msa_rsqrtq_f32) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_sqrt, msa_sqrtq_f64) -OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_invsqrt, msa_rsqrtq_f64) - -#define OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(bin_op, intrin) \ -inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ -{ \ - return v_float64x2(MSA_TPV_REINTERPRET(v2f64, intrin(MSA_TPV_REINTERPRET(v2i64, a.val), MSA_TPV_REINTERPRET(v2i64, b.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_and, msa_andq_s64) -OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_or, msa_orrq_s64) -OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_xor, msa_eorq_s64) - -inline v_float64x2 v_not(const v_float64x2& a) -{ - return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); -} - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_MSA_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_min, msa_minq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_max, msa_maxq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_min, msa_minq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_max, msa_maxq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_min, msa_minq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_max, msa_maxq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_min, msa_minq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_max, msa_maxq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_min, msa_minq_u32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_max, msa_maxq_u32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_min, msa_minq_s32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_max, msa_maxq_s32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_min, msa_minq_f32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_max, msa_maxq_f32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_min, msa_minq_f64) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_max, msa_maxq_f64) - -#define OPENCV_HAL_IMPL_MSA_INT_CMP_OP(_Tpvec, _Tpv, suffix, not_suffix) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ceqq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_##not_suffix(msa_ceqq_##suffix(a.val, b.val)))); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cltq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgtq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cleq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgeq_##suffix(a.val, b.val))); } - -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint8x16, v16u8, u8, u8) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int8x16, v16i8, s8, u8) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint16x8, v8u16, u16, u16) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int16x8, v8i16, s16, u16) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint32x4, v4u32, u32, u32) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int32x4, v4i32, s32, u32) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float32x4, v4f32, f32, u32) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint64x2, v2u64, u64, u64) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int64x2, v2i64, s64, u64) -OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float64x2, v2f64, f64, u64) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ceqq_f32(a.val, a.val))); } -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ceqq_f64(a.val, a.val))); } - -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_add_wrap, msa_addq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_add_wrap, msa_addq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_add_wrap, msa_addq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_add_wrap, msa_addq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_sub_wrap, msa_subq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_sub_wrap, msa_subq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_sub_wrap, msa_subq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_sub_wrap, msa_subq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_mul_wrap, msa_mulq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_mul_wrap, msa_mulq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_mul_wrap, msa_mulq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_mul_wrap, msa_mulq_s16) - -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_absdiff, msa_abdq_u8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_absdiff, msa_abdq_u16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_absdiff, msa_abdq_u32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_absdiff, msa_abdq_f32) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_absdiff, msa_abdq_f64) - -/** Saturating absolute difference **/ -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_absdiffs, msa_qabdq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_absdiffs, msa_qabdq_s16) - -#define OPENCV_HAL_IMPL_MSA_BIN_FUNC2(_Tpvec, _Tpvec2, _Tpv, func, intrin) \ -inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec2(MSA_TPV_REINTERPRET(_Tpv, intrin(a.val, b.val))); \ -} - -OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int8x16, v_uint8x16, v16u8, v_absdiff, msa_abdq_s8) -OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int16x8, v_uint16x8, v8u16, v_absdiff, msa_abdq_s16) -OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int32x4, v_uint32x4, v4u32, v_absdiff, msa_abdq_s32) - -/* v_magnitude, v_sqr_magnitude, v_fma, v_muladd */ -inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 x(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); - return v_sqrt(x); -} - -inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_float32x4(msa_mlaq_f32(c.val, a.val, b.val)); -} - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_int32x4(msa_mlaq_s32(c.val, a.val, b.val)); -} - -inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - v_float64x2 x(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); - return v_sqrt(x); -} - -inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_float64x2(msa_mlaq_f64(c.val, a.val, b.val)); -} - -inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_fma(a, b, c); -} - -// trade efficiency for convenience -#define OPENCV_HAL_IMPL_MSA_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ -inline _Tpvec v_shl(const _Tpvec& a, int n) \ -{ return _Tpvec(msa_shlq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ -inline _Tpvec v_shr(const _Tpvec& a, int n) \ -{ return _Tpvec(msa_shrq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec(msa_shlq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec(msa_shrq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_rshr(const _Tpvec& a) \ -{ return _Tpvec(msa_rshrq_n_##suffix(a.val, n)); } - -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint8x16, u8, schar, s8) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int8x16, s8, schar, s8) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint16x8, u16, short, s16) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int16x8, s16, short, s16) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint32x4, u32, int, s32) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int32x4, s32, int, s32) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint64x2, u64, int64, s64) -OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int64x2, s64, int64, s64) - -/* v_rotate_right, v_rotate_left */ -#define OPENCV_HAL_IMPL_MSA_ROTATE_OP(_Tpvec, _Tpv, _Tpvs, suffix) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##suffix(0), n))); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(msa_dupq_n_##suffix(0), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ \ - return a; \ -} \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), n))); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, b.val), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ \ - CV_UNUSED(b); \ - return a; \ -} - -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint8x16, v16u8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int8x16, v16i8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint16x8, v8u16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int16x8, v8i16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float32x4, v4f32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint64x2, v2u64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int64x2, v2i64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float64x2, v2f64, v2i64, s64) - -#define OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr), msa_dup_n_##suffix((_Tp)0))); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr0), msa_ld1_##suffix(ptr1))); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ msa_st1q_##suffix(ptr, a.val); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ \ - int n = _Tpvec::nlanes; \ - for( int i = 0; i < (n/2); i++ ) \ - ptr[i] = a.val[i]; \ -} \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - int n = _Tpvec::nlanes; \ - for( int i = 0; i < (n/2); i++ ) \ - ptr[i] = a.val[i+(n/2)]; \ -} - -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int16x8, short, s16) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int32x4, int, s32) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float32x4, float, f32) -OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float64x2, double, f64) - - -/** Reverse **/ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - v_uint8x16 c = v_uint8x16((v16u8)__builtin_msa_vshf_b((v16i8)((v2i64){0x08090A0B0C0D0E0F, 0x0001020304050607}), msa_dupq_n_s8(0), (v16i8)a.val)); - return c; -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - v_uint16x8 c = v_uint16x8((v8u16)__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000500060007, 0x0000000100020003}), msa_dupq_n_s16(0), (v8i16)a.val)); - return c; -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - v_uint32x4 c; - c.val[0] = a.val[3]; - c.val[1] = a.val[2]; - c.val[2] = a.val[1]; - c.val[3] = a.val[0]; - return c; -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - v_uint64x2 c; - c.val[0] = a.val[1]; - c.val[1] = a.val[0]; - return c; -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(func, cfunc) \ -inline unsigned short v_reduce_##func(const v_uint16x8& a) \ -{ \ - v8u16 a_lo, a_hi; \ - ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); \ - v4u32 b = msa_##func##q_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(a_hi)); \ - v4u32 b_lo, b_hi; \ - ILVRL_W2_UW(b, msa_dupq_n_u32(0), b_lo, b_hi); \ - v2u64 c = msa_##func##q_u64(msa_paddlq_u32(b_lo), msa_paddlq_u32(b_hi)); \ - return (unsigned short)cfunc(c[0], c[1]); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(min, std::min) - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(func, cfunc) \ -inline short v_reduce_##func(const v_int16x8& a) \ -{ \ - v8i16 a_lo, a_hi; \ - ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); \ - v4i32 b = msa_##func##q_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(a_hi)); \ - v4i32 b_lo, b_hi; \ - ILVRL_W2_SW(b, msa_dupq_n_s32(0), b_lo, b_hi); \ - v2i64 c = msa_##func##q_s64(msa_paddlq_s32(b_lo), msa_paddlq_s32(b_hi)); \ - return (short)cfunc(c[0], c[1]); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(min, std::min) - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(_Tpvec, scalartype, func, cfunc) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return (scalartype)cfunc(cfunc(a.val[0], a.val[1]), cfunc(a.val[2], a.val[3])); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, min, std::min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, max, std::max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, min, std::min) - - -#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(_Tpvec, scalartype, _Tpvec2, func) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpvec2 a1, a2; \ - v_expand(a, a1, a2); \ - return (scalartype)v_reduce_##func(v_##func(a1, a2)); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, max) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, min) -OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, max) - - - -#define OPENCV_HAL_IMPL_MSA_REDUCE_SUM(_Tpvec, scalartype, suffix) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - return (scalartype)msa_sum_##suffix(a.val); \ -} - -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint8x16, unsigned short, u8) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int8x16, short, s8) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint16x8, unsigned, u16) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int16x8, int, s16) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint32x4, uint64_t, u32) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int32x4, int64_t, s32) -OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_float32x4, float, f32) - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ return (uint64)(msa_getq_lane_u64(a.val, 0) + msa_getq_lane_u64(a.val, 1)); } -inline int64 v_reduce_sum(const v_int64x2& a) -{ return (int64)(msa_getq_lane_s64(a.val, 0) + msa_getq_lane_s64(a.val, 1)); } -inline double v_reduce_sum(const v_float64x2& a) -{ - return msa_getq_lane_f64(a.val, 0) + msa_getq_lane_f64(a.val, 1); -} - -/* v_reduce_sum4, v_reduce_sad */ -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - v4f32 u0 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val))), - MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val)))); // a0+a1 b0+b1 a2+a3 b2+b3 - v4f32 u1 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val))), - MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val)))); // c0+c1 d0+d1 c2+c3 d2+d3 - - return v_float32x4(msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))), - MSA_TPV_REINTERPRET(v4f32, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))))); -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - v16u8 t0 = msa_abdq_u8(a.val, b.val); - v8u16 t1 = msa_paddlq_u8(t0); - v4u32 t2 = msa_paddlq_u16(t1); - return msa_sum_u32(t2); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - v16u8 t0 = MSA_TPV_REINTERPRET(v16u8, msa_abdq_s8(a.val, b.val)); - v8u16 t1 = msa_paddlq_u8(t0); - v4u32 t2 = msa_paddlq_u16(t1); - return msa_sum_u32(t2); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - v8u16 t0 = msa_abdq_u16(a.val, b.val); - v4u32 t1 = msa_paddlq_u16(t0); - return msa_sum_u32(t1); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - v8u16 t0 = MSA_TPV_REINTERPRET(v8u16, msa_abdq_s16(a.val, b.val)); - v4u32 t1 = msa_paddlq_u16(t0); - return msa_sum_u32(t1); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - v4u32 t0 = msa_abdq_u32(a.val, b.val); - return msa_sum_u32(t0); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - v4u32 t0 = MSA_TPV_REINTERPRET(v4u32, msa_abdq_s32(a.val, b.val)); - return msa_sum_u32(t0); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - v4f32 t0 = msa_abdq_f32(a.val, b.val); - return msa_sum_f32(t0); -} - -/* v_popcount */ -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(_Tpvec) \ -inline v_uint8x16 v_popcount(const _Tpvec& a) \ -{ \ - v16u8 t = MSA_TPV_REINTERPRET(v16u8, msa_cntq_s8(MSA_TPV_REINTERPRET(v16i8, a.val))); \ - return v_uint8x16(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_uint8x16) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_int8x16) - -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(_Tpvec) \ -inline v_uint16x8 v_popcount(const _Tpvec& a) \ -{ \ - v8u16 t = MSA_TPV_REINTERPRET(v8u16, msa_cntq_s16(MSA_TPV_REINTERPRET(v8i16, a.val))); \ - return v_uint16x8(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_uint16x8) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_int16x8) - -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(_Tpvec) \ -inline v_uint32x4 v_popcount(const _Tpvec& a) \ -{ \ - v4u32 t = MSA_TPV_REINTERPRET(v4u32, msa_cntq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))); \ - return v_uint32x4(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_uint32x4) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_int32x4) - -#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(_Tpvec) \ -inline v_uint64x2 v_popcount(const _Tpvec& a) \ -{ \ - v2u64 t = MSA_TPV_REINTERPRET(v2u64, msa_cntq_s64(MSA_TPV_REINTERPRET(v2i64, a.val))); \ - return v_uint64x2(t); \ -} -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_uint64x2) -OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_int64x2) - -inline int v_signmask(const v_uint8x16& a) -{ - v8i8 m0 = msa_create_s8(CV_BIG_UINT(0x0706050403020100)); - v16u8 v0 = msa_shlq_u8(msa_shrq_n_u8(a.val, 7), msa_combine_s8(m0, m0)); - v8u16 v1 = msa_paddlq_u8(v0); - v4u32 v2 = msa_paddlq_u16(v1); - v2u64 v3 = msa_paddlq_u32(v2); - return (int)msa_getq_lane_u64(v3, 0) + ((int)msa_getq_lane_u64(v3, 1) << 8); -} -inline int v_signmask(const v_int8x16& a) -{ return v_signmask(v_reinterpret_as_u8(a)); } - -inline int v_signmask(const v_uint16x8& a) -{ - v4i16 m0 = msa_create_s16(CV_BIG_UINT(0x0003000200010000)); - v8u16 v0 = msa_shlq_u16(msa_shrq_n_u16(a.val, 15), msa_combine_s16(m0, m0)); - v4u32 v1 = msa_paddlq_u16(v0); - v2u64 v2 = msa_paddlq_u32(v1); - return (int)msa_getq_lane_u64(v2, 0) + ((int)msa_getq_lane_u64(v2, 1) << 4); -} -inline int v_signmask(const v_int16x8& a) -{ return v_signmask(v_reinterpret_as_u16(a)); } - -inline int v_signmask(const v_uint32x4& a) -{ - v2i32 m0 = msa_create_s32(CV_BIG_UINT(0x0000000100000000)); - v4u32 v0 = msa_shlq_u32(msa_shrq_n_u32(a.val, 31), msa_combine_s32(m0, m0)); - v2u64 v1 = msa_paddlq_u32(v0); - return (int)msa_getq_lane_u64(v1, 0) + ((int)msa_getq_lane_u64(v1, 1) << 2); -} -inline int v_signmask(const v_int32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } - -inline int v_signmask(const v_uint64x2& a) -{ - v2u64 v0 = msa_shrq_n_u64(a.val, 63); - return (int)msa_getq_lane_u64(v0, 0) + ((int)msa_getq_lane_u64(v0, 1) << 1); -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } - -#define OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(_Tpvec, _Tpvec2, suffix, shift) \ -inline bool v_check_all(const v_##_Tpvec& a) \ -{ \ - _Tpvec2 v0 = msa_shrq_n_##suffix(msa_mvnq_##suffix(a.val), shift); \ - v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ - return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) == 0; \ -} \ -inline bool v_check_any(const v_##_Tpvec& a) \ -{ \ - _Tpvec2 v0 = msa_shrq_n_##suffix(a.val, shift); \ - v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ - return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) != 0; \ -} - -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint8x16, v16u8, u8, 7) -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint16x8, v8u16, u16, 15) -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint32x4, v4u32, u32, 31) -OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint64x2, v2u64, u64, 63) - -inline bool v_check_all(const v_int8x16& a) -{ return v_check_all(v_reinterpret_as_u8(a)); } -inline bool v_check_all(const v_int16x8& a) -{ return v_check_all(v_reinterpret_as_u16(a)); } -inline bool v_check_all(const v_int32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } - -inline bool v_check_any(const v_int8x16& a) -{ return v_check_any(v_reinterpret_as_u8(a)); } -inline bool v_check_any(const v_int16x8& a) -{ return v_check_any(v_reinterpret_as_u16(a)); } -inline bool v_check_any(const v_int32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } - -inline bool v_check_all(const v_int64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_int64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } - -/* v_select */ -#define OPENCV_HAL_IMPL_MSA_SELECT(_Tpvec, _Tpv, _Tpvu) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_bslq_u8(MSA_TPV_REINTERPRET(_Tpvu, mask.val), \ - MSA_TPV_REINTERPRET(_Tpvu, b.val), MSA_TPV_REINTERPRET(_Tpvu, a.val)))); \ -} - -OPENCV_HAL_IMPL_MSA_SELECT(v_uint8x16, v16u8, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_int8x16, v16i8, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_uint16x8, v8u16, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_int16x8, v8i16, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_uint32x4, v4u32, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_int32x4, v4i32, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_float32x4, v4f32, v16u8) -OPENCV_HAL_IMPL_MSA_SELECT(v_float64x2, v2f64, v16u8) - -#define OPENCV_HAL_IMPL_MSA_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix, ssuffix, _Tpv, _Tpvs) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - b0.val = msa_paddlq_##suffix(a_lo); \ - b1.val = msa_paddlq_##suffix(a_hi); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - return _Tpwvec(msa_paddlq_##suffix(a_lo)); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ - return _Tpwvec(msa_paddlq_##suffix(a_hi)); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return _Tpwvec(msa_movl_##suffix(msa_ld1_##suffix(ptr))); \ -} - -OPENCV_HAL_IMPL_MSA_EXPAND(v_uint8x16, v_uint16x8, uchar, u8, s8, v16u8, v16i8) -OPENCV_HAL_IMPL_MSA_EXPAND(v_int8x16, v_int16x8, schar, s8, s8, v16i8, v16i8) -OPENCV_HAL_IMPL_MSA_EXPAND(v_uint16x8, v_uint32x4, ushort, u16, s16, v8u16, v8i16) -OPENCV_HAL_IMPL_MSA_EXPAND(v_int16x8, v_int32x4, short, s16, s16, v8i16, v8i16) -OPENCV_HAL_IMPL_MSA_EXPAND(v_uint32x4, v_uint64x2, uint, u32, s32, v4u32, v4i32) -OPENCV_HAL_IMPL_MSA_EXPAND(v_int32x4, v_int64x2, int, s32, s32, v4i32, v4i32) - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - return v_uint32x4((v4u32){ptr[0], ptr[1], ptr[2], ptr[3]}); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - return v_int32x4((v4i32){ptr[0], ptr[1], ptr[2], ptr[3]}); -} - -/* v_zip, v_combine_low, v_combine_high, v_recombine */ -#define OPENCV_HAL_IMPL_MSA_UNPACKS(_Tpvec, _Tpv, _Tpvs, ssuffix) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ -{ \ - b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ - b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ -} \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - c.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ - d.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ -} - -OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint8x16, v16u8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_int8x16, v16i8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint16x8, v8u16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_int16x8, v8i16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_float32x4, v4f32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_UNPACKS(v_float64x2, v2f64, v2i64, s64) - -/* v_extract */ -#define OPENCV_HAL_IMPL_MSA_EXTRACT(_Tpvec, _Tpv, _Tpvs, suffix) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), s))); \ -} - -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint8x16, v16u8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int8x16, v16i8, v16i8, s8) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint16x8, v8u16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int16x8, v8i16, v8i16, s16) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint64x2, v2u64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_int64x2, v2i64, v2i64, s64) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_float32x4, v4f32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_EXTRACT(v_float64x2, v2f64, v2i64, s64) - -/* v_round, v_floor, v_ceil, v_trunc */ -inline v_int32x4 v_round(const v_float32x4& a) -{ - return v_int32x4(msa_cvttintq_s32_f32(a.val)); -} - -inline v_int32x4 v_floor(const v_float32x4& a) -{ - v4i32 a1 = msa_cvttintq_s32_f32(a.val); - return v_int32x4(msa_addq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(msa_cvtfintq_f32_s32(a1), a.val)))); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - v4i32 a1 = msa_cvttintq_s32_f32(a.val); - return v_int32x4(msa_subq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(a.val, msa_cvtfintq_f32_s32(a1))))); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ - return v_int32x4(msa_cvttruncq_s32_f32(a.val)); -} - -inline v_int32x4 v_round(const v_float64x2& a) -{ - return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_dupq_n_s64(0))); -} - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_cvttintq_s64_f64(b.val))); -} - -inline v_int32x4 v_floor(const v_float64x2& a) -{ - v2f64 a1 = msa_cvtrintq_f64(a.val); - return v_int32x4(msa_pack_s64(msa_addq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a1, a.val))), msa_dupq_n_s64(0))); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - v2f64 a1 = msa_cvtrintq_f64(a.val); - return v_int32x4(msa_pack_s64(msa_subq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a.val, a1))), msa_dupq_n_s64(0))); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ - return v_int32x4(msa_pack_s64(msa_cvttruncq_s64_f64(a.val), msa_dupq_n_s64(0))); -} - -#define OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(_Tpvec, _Tpv, _Tpvs, ssuffix) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, \ - _Tpvec& b2, _Tpvec& b3) \ -{ \ - _Tpv t00 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ - _Tpv t01 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ - _Tpv t10 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ - _Tpv t11 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ - b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ - b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ - b2.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ - b3.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ -} - -OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_uint32x4, v4u32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_int32x4, v4i32, v4i32, s32) -OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_float32x4, v4f32, v4i32, s32) - -#define OPENCV_HAL_IMPL_MSA_INTERLEAVED(_Tpvec, _Tp, suffix) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ -{ \ - msa_ld2q_##suffix(ptr, &a.val, &b.val); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ -{ \ - msa_ld3q_##suffix(ptr, &a.val, &b.val, &c.val); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ - v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - msa_ld4q_##suffix(ptr, &a.val, &b.val, &c.val, &d.val); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - msa_st2q_##suffix(ptr, a.val, b.val); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - msa_st3q_##suffix(ptr, a.val, b.val, c.val); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, const v_##_Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - msa_st4q_##suffix(ptr, a.val, b.val, c.val, d.val); \ -} - -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int8x16, schar, s8) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int16x8, short, s16) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int32x4, int, s32) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(float32x4, float, f32) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint64x2, uint64, u64) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(int64x2, int64, s64) -OPENCV_HAL_IMPL_MSA_INTERLEAVED(float64x2, double, f64) - -/* v_cvt_f32, v_cvt_f64, v_cvt_f64_high */ -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(msa_cvtfintq_f32_s32(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - return v_float32x4(msa_cvtfq_f32_f64(a.val, msa_dupq_n_f64(0.0f))); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - return v_float32x4(msa_cvtfq_f32_f64(a.val, b.val)); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - return v_float64x2(msa_cvtflq_f64_f32(msa_cvtfintq_f32_s32(a.val))); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - return v_float64x2(msa_cvtfhq_f64_f32(msa_cvtfintq_f32_s32(a.val))); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - return v_float64x2(msa_cvtflq_f64_f32(a.val)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - return v_float64x2(msa_cvtfhq_f64_f32(a.val)); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ - return v_float64x2(msa_cvtfintq_f64_s64(a.val)); -} - -////////////// Lookup table access //////////////////// -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[ 0]], - tab[idx[ 1]], - tab[idx[ 2]], - tab[idx[ 3]], - tab[idx[ 4]], - tab[idx[ 5]], - tab[idx[ 6]], - tab[idx[ 7]], - tab[idx[ 8]], - tab[idx[ 9]], - tab[idx[10]], - tab[idx[11]], - tab[idx[12]], - tab[idx[13]], - tab[idx[14]], - tab[idx[15]] - }; - return v_int8x16(msa_ld1q_s8(elems)); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[4]], - tab[idx[4] + 1], - tab[idx[5]], - tab[idx[5] + 1], - tab[idx[6]], - tab[idx[6] + 1], - tab[idx[7]], - tab[idx[7] + 1] - }; - return v_int8x16(msa_ld1q_s8(elems)); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[2] + 2], - tab[idx[2] + 3], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[3] + 2], - tab[idx[3] + 3] - }; - return v_int8x16(msa_ld1q_s8(elems)); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } - - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]], - tab[idx[4]], - tab[idx[5]], - tab[idx[6]], - tab[idx[7]] - }; - return v_int16x8(msa_ld1q_s16(elems)); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1] - }; - return v_int16x8(msa_ld1q_s16(elems)); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(msa_combine_s16(msa_ld1_s16(tab + idx[0]), msa_ld1_s16(tab + idx[1]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_int32x4(msa_ld1q_s32(elems)); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(msa_combine_s32(msa_ld1_s32(tab + idx[0]), msa_ld1_s32(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(msa_ld1q_s32(tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(msa_combine_s64(msa_create_s64(tab[idx[0]]), msa_create_s64(tab[idx[1]]))); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(msa_ld1q_s64(tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_float32x4(msa_ld1q_f32(elems)); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ - uint64 CV_DECL_ALIGNED(32) elems[2] = - { - *(uint64*)(tab + idx[0]), - *(uint64*)(tab + idx[1]) - }; - return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ld1q_u64(elems))); -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4(msa_ld1q_f32(tab + idx[0])); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - unsigned CV_DECL_ALIGNED(32) elems[4] = - { - tab[msa_getq_lane_s32(idxvec.val, 0)], - tab[msa_getq_lane_s32(idxvec.val, 1)], - tab[msa_getq_lane_s32(idxvec.val, 2)], - tab[msa_getq_lane_s32(idxvec.val, 3)] - }; - return v_uint32x4(msa_ld1q_u32(elems)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - v4f32 xy02 = msa_combine_f32(msa_ld1_f32(tab + idx[0]), msa_ld1_f32(tab + idx[2])); - v4f32 xy13 = msa_combine_f32(msa_ld1_f32(tab + idx[1]), msa_ld1_f32(tab + idx[3])); - x = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); - y = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0705060403010200, 0x0F0D0E0C0B090A08}), msa_dupq_n_s8(0), vec.val)); - return c; -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0703060205010400, 0x0F0B0E0A0D090C08}), msa_dupq_n_s8(0), vec.val)); - return c; -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0003000100020000, 0x0007000500060004}), msa_dupq_n_s16(0), vec.val)); - return c; -} - -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } - -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0005000100040000, 0x0007000300060002}), msa_dupq_n_s16(0), vec.val)); - return c; -} - -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - v_int32x4 c; - c.val[0] = vec.val[0]; - c.val[1] = vec.val[2]; - c.val[2] = vec.val[1]; - c.val[3] = vec.val[3]; - return c; -} - -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0908060504020100, 0x131211100E0D0C0A}), msa_dupq_n_s8(0), vec.val)); - return c; -} - -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000200010000, 0x0009000800060005}), msa_dupq_n_s16(0), vec.val)); - return c; -} - -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - double CV_DECL_ALIGNED(32) elems[2] = - { - tab[idx[0]], - tab[idx[1]] - }; - return v_float64x2(msa_ld1q_f64(elems)); -} - -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(msa_ld1q_f64(tab + idx[0])); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - v2f64 xy0 = msa_ld1q_f64(tab + idx[0]); - v2f64 xy1 = msa_ld1q_f64(tab + idx[1]); - x = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvevq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); - y = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvodq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); -} - -template -inline typename _Tp::lane_type v_extract_n(const _Tp& a) -{ - return v_rotate_right(a).get0(); -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) -{ - return v_setall_u32(v_extract_n(a)); -} -template -inline v_int32x4 v_broadcast_element(const v_int32x4& a) -{ - return v_setall_s32(v_extract_n(a)); -} -template -inline v_float32x4 v_broadcast_element(const v_float32x4& a) -{ - return v_setall_f32(v_extract_n(a)); -} - -////// FP16 support /////// -#if CV_FP16 -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ -#ifndef msa_ld1_f16 - v4f16 v = (v4f16)msa_ld1_s16((const short*)ptr); -#else - v4f16 v = msa_ld1_f16((const __fp16*)ptr); -#endif - return v_float32x4(msa_cvt_f32_f16(v)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - v4f16 hv = msa_cvt_f16_f32(v.val); - -#ifndef msa_st1_f16 - msa_st1_s16((short*)ptr, (int16x4_t)hv); -#else - msa_st1_f16((__fp16*)ptr, hv); -#endif -} -#else -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - float buf[4]; - for( int i = 0; i < 4; i++ ) - buf[i] = (float)ptr[i]; - return v_load(buf); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - float buf[4]; - v_store(buf, v); - for( int i = 0; i < 4; i++ ) - ptr[i] = (hfloat)buf[i]; -} -#endif - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_HAL_INTRIN_MSA_HPP +#define OPENCV_HAL_INTRIN_MSA_HPP + +#include +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @cond IGNORED +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD128 1 + +//MSA implements 128-bit wide vector registers shared with the 64-bit wide floating-point unit registers. +//MSA and FPU can not be both present, unless the FPU has 64-bit floating-point registers. +#define CV_SIMD128_64F 1 + +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16 }; + + v_uint8x16() {} + explicit v_uint8x16(v16u8 v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = msa_ld1q_u8(v); + } + + uchar get0() const + { + return msa_getq_lane_u8(val, 0); + } + + v16u8 val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(v16i8 v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = msa_ld1q_s8(v); + } + + schar get0() const + { + return msa_getq_lane_s8(val, 0); + } + + v16i8 val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(v8u16 v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = msa_ld1q_u16(v); + } + + ushort get0() const + { + return msa_getq_lane_u16(val, 0); + } + + v8u16 val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(v8i16 v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = msa_ld1q_s16(v); + } + + short get0() const + { + return msa_getq_lane_s16(val, 0); + } + + v8i16 val; +}; + +struct v_uint32x4 +{ + typedef unsigned int lane_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(v4u32 v) : val(v) {} + v_uint32x4(unsigned int v0, unsigned int v1, unsigned int v2, unsigned int v3) + { + unsigned int v[] = {v0, v1, v2, v3}; + val = msa_ld1q_u32(v); + } + + unsigned int get0() const + { + return msa_getq_lane_u32(val, 0); + } + + v4u32 val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(v4i32 v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = msa_ld1q_s32(v); + } + + int get0() const + { + return msa_getq_lane_s32(val, 0); + } + + v4i32 val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4 }; + + v_float32x4() {} + explicit v_float32x4(v4f32 v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = msa_ld1q_f32(v); + } + + float get0() const + { + return msa_getq_lane_f32(val, 0); + } + + v4f32 val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2 }; + + v_uint64x2() {} + explicit v_uint64x2(v2u64 v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = msa_ld1q_u64(v); + } + + uint64 get0() const + { + return msa_getq_lane_u64(val, 0); + } + + v2u64 val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2 }; + + v_int64x2() {} + explicit v_int64x2(v2i64 v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = msa_ld1q_s64(v); + } + + int64 get0() const + { + return msa_getq_lane_s64(val, 0); + } + + v2i64 val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2 }; + + v_float64x2() {} + explicit v_float64x2(v2f64 v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = msa_ld1q_f64(v); + } + + double get0() const + { + return msa_getq_lane_f64(val, 0); + } + + v2f64 val; +}; + +#define OPENCV_HAL_IMPL_MSA_INIT(_Tpv, _Tp, suffix) \ +inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(msa_dupq_n_##suffix((_Tp)0)); } \ +inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(msa_dupq_n_##suffix(v)); } \ +template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(MSA_TPV_REINTERPRET(v16u8, v.val)); } \ +inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(MSA_TPV_REINTERPRET(v16i8, v.val)); } \ +inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(MSA_TPV_REINTERPRET(v8u16, v.val)); } \ +inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(MSA_TPV_REINTERPRET(v8i16, v.val)); } \ +inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(MSA_TPV_REINTERPRET(v4u32, v.val)); } \ +inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(MSA_TPV_REINTERPRET(v4i32, v.val)); } \ +inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(MSA_TPV_REINTERPRET(v2u64, v.val)); } \ +inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(MSA_TPV_REINTERPRET(v2i64, v.val)); } \ +inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(MSA_TPV_REINTERPRET(v4f32, v.val)); } \ +inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(MSA_TPV_REINTERPRET(v2f64, v.val)); } + +OPENCV_HAL_IMPL_MSA_INIT(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_MSA_INIT(int8x16, schar, s8) +OPENCV_HAL_IMPL_MSA_INIT(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_MSA_INIT(int16x8, short, s16) +OPENCV_HAL_IMPL_MSA_INIT(uint32x4, unsigned int, u32) +OPENCV_HAL_IMPL_MSA_INIT(int32x4, int, s32) +OPENCV_HAL_IMPL_MSA_INIT(uint64x2, uint64, u64) +OPENCV_HAL_IMPL_MSA_INIT(int64x2, int64, s64) +OPENCV_HAL_IMPL_MSA_INIT(float32x4, float, f32) +OPENCV_HAL_IMPL_MSA_INIT(float64x2, double, f64) + +#define OPENCV_HAL_IMPL_MSA_PACK(_Tpvec, _Tpwvec, pack, mov, rshr) \ +inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + return _Tpvec(mov(a.val, b.val)); \ +} \ +template inline \ +_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + return _Tpvec(rshr(a.val, b.val, n)); \ +} + +OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_uint16x8, pack, msa_qpack_u16, msa_qrpackr_u16) +OPENCV_HAL_IMPL_MSA_PACK(v_int8x16, v_int16x8, pack, msa_qpack_s16, msa_qrpackr_s16) +OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_uint32x4, pack, msa_qpack_u32, msa_qrpackr_u32) +OPENCV_HAL_IMPL_MSA_PACK(v_int16x8, v_int32x4, pack, msa_qpack_s32, msa_qrpackr_s32) +OPENCV_HAL_IMPL_MSA_PACK(v_uint32x4, v_uint64x2, pack, msa_pack_u64, msa_rpackr_u64) +OPENCV_HAL_IMPL_MSA_PACK(v_int32x4, v_int64x2, pack, msa_pack_s64, msa_rpackr_s64) +OPENCV_HAL_IMPL_MSA_PACK(v_uint8x16, v_int16x8, pack_u, msa_qpacku_s16, msa_qrpackru_s16) +OPENCV_HAL_IMPL_MSA_PACK(v_uint16x8, v_int32x4, pack_u, msa_qpacku_s32, msa_qrpackru_s32) + +#define OPENCV_HAL_IMPL_MSA_PACK_STORE(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ +inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = mov(a.val); \ + msa_st1_##suffix(ptr, a1); \ +} \ +template inline \ +void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = rshr(a.val, n); \ + msa_st1_##suffix(ptr, a1); \ +} + +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_uint16x8, pack, msa_qmovn_u16, msa_qrshrn_n_u16) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int8x16, schar, v8i8, s8, v_int16x8, pack, msa_qmovn_s16, msa_qrshrn_n_s16) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_uint32x4, pack, msa_qmovn_u32, msa_qrshrn_n_u32) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int16x8, short, v4i16, s16, v_int32x4, pack, msa_qmovn_s32, msa_qrshrn_n_s32) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint32x4, unsigned, v2u32, u32, v_uint64x2, pack, msa_movn_u64, msa_rshrn_n_u64) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_int32x4, int, v2i32, s32, v_int64x2, pack, msa_movn_s64, msa_rshrn_n_s64) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint8x16, uchar, v8u8, u8, v_int16x8, pack_u, msa_qmovun_s16, msa_qrshrun_n_s16) +OPENCV_HAL_IMPL_MSA_PACK_STORE(v_uint16x8, ushort, v4u16, u16, v_int32x4, pack_u, msa_qmovun_s32, msa_qrshrun_n_s32) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + return v_uint8x16(msa_pack_u16(a.val, b.val)); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + return v_uint8x16(msa_pack_u16(msa_pack_u32(a.val, b.val), msa_pack_u32(c.val, d.val))); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + v8u16 abcd = msa_pack_u32(msa_pack_u64(a.val, b.val), msa_pack_u64(c.val, d.val)); + v8u16 efgh = msa_pack_u32(msa_pack_u64(e.val, f.val), msa_pack_u64(g.val, h.val)); + return v_uint8x16(msa_pack_u16(abcd, efgh)); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + v4f32 v0 = v.val; + v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); + res = msa_mlaq_lane_f32(res, m1.val, v0, 1); + res = msa_mlaq_lane_f32(res, m2.val, v0, 2); + res = msa_mlaq_lane_f32(res, m3.val, v0, 3); + return v_float32x4(res); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + v4f32 v0 = v.val; + v4f32 res = msa_mulq_lane_f32(m0.val, v0, 0); + res = msa_mlaq_lane_f32(res, m1.val, v0, 1); + res = msa_mlaq_lane_f32(res, m2.val, v0, 2); + res = msa_addq_f32(res, a.val); + return v_float32x4(res); +} + +#define OPENCV_HAL_IMPL_MSA_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint8x16, msa_qaddq_u8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint8x16, msa_qsubq_u8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int8x16, msa_qaddq_s8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int8x16, msa_qsubq_s8) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint16x8, msa_qaddq_u16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint16x8, msa_qsubq_u16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int16x8, msa_qaddq_s16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int16x8, msa_qsubq_s16) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int32x4, msa_addq_s32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int32x4, msa_subq_s32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_int32x4, msa_mulq_s32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint32x4, msa_addq_u32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint32x4, msa_subq_u32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_uint32x4, msa_mulq_u32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float32x4, msa_addq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float32x4, msa_subq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float32x4, msa_mulq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_int64x2, msa_addq_s64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_int64x2, msa_subq_s64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_uint64x2, msa_addq_u64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_uint64x2, msa_subq_u64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float32x4, msa_divq_f32) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_add, v_float64x2, msa_addq_f64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_sub, v_float64x2, msa_subq_f64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_mul, v_float64x2, msa_mulq_f64) +OPENCV_HAL_IMPL_MSA_BIN_OP(v_div, v_float64x2, msa_divq_f64) + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_MSA_MUL_SAT(_Tpvec, _Tpwvec) \ +inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ +} + +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_int16x8, v_int32x4) +OPENCV_HAL_IMPL_MSA_MUL_SAT(v_uint16x8, v_uint32x4) + +// Multiply and expand +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + v16i8 a_lo, a_hi, b_lo, b_hi; + + ILVRL_B2_SB(a.val, msa_dupq_n_s8(0), a_lo, a_hi); + ILVRL_B2_SB(b.val, msa_dupq_n_s8(0), b_lo, b_hi); + c.val = msa_mulq_s16(msa_paddlq_s8(a_lo), msa_paddlq_s8(b_lo)); + d.val = msa_mulq_s16(msa_paddlq_s8(a_hi), msa_paddlq_s8(b_hi)); +} + +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + v16u8 a_lo, a_hi, b_lo, b_hi; + + ILVRL_B2_UB(a.val, msa_dupq_n_u8(0), a_lo, a_hi); + ILVRL_B2_UB(b.val, msa_dupq_n_u8(0), b_lo, b_hi); + c.val = msa_mulq_u16(msa_paddlq_u8(a_lo), msa_paddlq_u8(b_lo)); + d.val = msa_mulq_u16(msa_paddlq_u8(a_hi), msa_paddlq_u8(b_hi)); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + v8i16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); + ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); + c.val = msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)); + d.val = msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + v8u16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); + ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); + c.val = msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)); + d.val = msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + v4u32 a_lo, a_hi, b_lo, b_hi; + + ILVRL_W2_UW(a.val, msa_dupq_n_u32(0), a_lo, a_hi); + ILVRL_W2_UW(b.val, msa_dupq_n_u32(0), b_lo, b_hi); + c.val = msa_mulq_u64(msa_paddlq_u32(a_lo), msa_paddlq_u32(b_lo)); + d.val = msa_mulq_u64(msa_paddlq_u32(a_hi), msa_paddlq_u32(b_hi)); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + v8i16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); + ILVRL_H2_SH(b.val, msa_dupq_n_s16(0), b_lo, b_hi); + + return v_int16x8(msa_packr_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(b_lo)), + msa_mulq_s32(msa_paddlq_s16(a_hi), msa_paddlq_s16(b_hi)), 16)); +} + +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + v8u16 a_lo, a_hi, b_lo, b_hi; + + ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); + ILVRL_H2_UH(b.val, msa_dupq_n_u16(0), b_lo, b_hi); + + return v_uint16x8(msa_packr_u32(msa_mulq_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(b_lo)), + msa_mulq_u32(msa_paddlq_u16(a_hi), msa_paddlq_u16(b_hi)), 16)); +} + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ return v_int32x4(msa_dotp_s_w(a.val, b.val)); } +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_int32x4(msa_dpadd_s_w(c.val , a.val, b.val)); } + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ return v_int64x2(msa_dotp_s_d(a.val, b.val)); } +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_int64x2(msa_dpadd_s_d(c.val , a.val, b.val)); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); + v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); + v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); + v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); + v4u32 prod = msa_dotp_u_w(even_a, even_b); + return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ + v8u16 even_a = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8), 8); + v8u16 odd_a = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, a.val), 8); + v8u16 even_b = msa_shrq_n_u16(msa_shlq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8), 8); + v8u16 odd_b = msa_shrq_n_u16(MSA_TPV_REINTERPRET(v8u16, b.val), 8); + v4u32 prod = msa_dpadd_u_w(c.val, even_a, even_b); + return v_uint32x4(msa_dpadd_u_w(prod, odd_a, odd_b)); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + v8i16 prod = msa_dotp_s_h(a.val, b.val); + return v_int32x4(msa_hadd_s32(prod, prod)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, + const v_int32x4& c) +{ return v_dotprod_expand(a, b) + c; } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); + v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); + v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); + v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); + v2u64 prod = msa_dotp_u_d(even_a, even_b); + return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, + const v_uint64x2& c) +{ + v4u32 even_a = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16), 16); + v4u32 odd_a = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, a.val), 16); + v4u32 even_b = msa_shrq_n_u32(msa_shlq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16), 16); + v4u32 odd_b = msa_shrq_n_u32(MSA_TPV_REINTERPRET(v4u32, b.val), 16); + v2u64 prod = msa_dpadd_u_d(c.val, even_a, even_b); + return v_uint64x2(msa_dpadd_u_d(prod, odd_a, odd_b)); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v4i32 prod = msa_dotp_s_w(a.val, b.val); + return v_int64x2(msa_hadd_s64(prod, prod)); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_dotprod_expand(a, b, c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +#define OPENCV_HAL_IMPL_MSA_LOGIC_OP(_Tpvec, _Tpv, suffix) \ +OPENCV_HAL_IMPL_MSA_BIN_OP(v_and, _Tpvec, msa_andq_##suffix) \ +OPENCV_HAL_IMPL_MSA_BIN_OP(v_or, _Tpvec, msa_orrq_##suffix) \ +OPENCV_HAL_IMPL_MSA_BIN_OP(v_xor, _Tpvec, msa_eorq_##suffix) \ +inline _Tpvec v_not(const _Tpvec& a) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_u8(MSA_TPV_REINTERPRET(v16u8, a.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint8x16, v16u8, u8) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int8x16, v16i8, s8) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint16x8, v8u16, u16) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int16x8, v8i16, s16) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint32x4, v4u32, u32) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int32x4, v4i32, s32) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_uint64x2, v2u64, u64) +OPENCV_HAL_IMPL_MSA_LOGIC_OP(v_int64x2, v2i64, s64) + +#define OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(bin_op, intrin) \ +inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ +{ \ + return v_float32x4(MSA_TPV_REINTERPRET(v4f32, intrin(MSA_TPV_REINTERPRET(v4i32, a.val), MSA_TPV_REINTERPRET(v4i32, b.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_and, msa_andq_s32) +OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_or, msa_orrq_s32) +OPENCV_HAL_IMPL_MSA_FLT_BIT_OP(v_xor, msa_eorq_s32) + +inline v_float32x4 v_not(const v_float32x4& a) +{ + return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); +} + +/* v_abs */ +#define OPENCV_HAL_IMPL_MSA_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ +inline _Tpuvec v_abs(const _Tpsvec& a) \ +{ \ + return v_reinterpret_as_##usuffix(_Tpsvec(msa_absq_##ssuffix(a.val))); \ +} + +OPENCV_HAL_IMPL_MSA_ABS(v_uint8x16, v_int8x16, u8, s8) +OPENCV_HAL_IMPL_MSA_ABS(v_uint16x8, v_int16x8, u16, s16) +OPENCV_HAL_IMPL_MSA_ABS(v_uint32x4, v_int32x4, u32, s32) + +/* v_abs(float), v_sqrt, v_invsqrt */ +#define OPENCV_HAL_IMPL_MSA_BASIC_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a) \ +{ \ + return _Tpvec(intrin(a.val)); \ +} + +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_abs, msa_absq_f32) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_abs, msa_absq_f64) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_sqrt, msa_sqrtq_f32) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float32x4, v_invsqrt, msa_rsqrtq_f32) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_sqrt, msa_sqrtq_f64) +OPENCV_HAL_IMPL_MSA_BASIC_FUNC(v_float64x2, v_invsqrt, msa_rsqrtq_f64) + +#define OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(bin_op, intrin) \ +inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ +{ \ + return v_float64x2(MSA_TPV_REINTERPRET(v2f64, intrin(MSA_TPV_REINTERPRET(v2i64, a.val), MSA_TPV_REINTERPRET(v2i64, b.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_and, msa_andq_s64) +OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_or, msa_orrq_s64) +OPENCV_HAL_IMPL_MSA_DBL_BIT_OP(v_xor, msa_eorq_s64) + +inline v_float64x2 v_not(const v_float64x2& a) +{ + return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_mvnq_s32(MSA_TPV_REINTERPRET(v4i32, a.val)))); +} + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_MSA_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_min, msa_minq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_max, msa_maxq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_min, msa_minq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_max, msa_maxq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_min, msa_minq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_max, msa_maxq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_min, msa_minq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_max, msa_maxq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_min, msa_minq_u32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_max, msa_maxq_u32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_min, msa_minq_s32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int32x4, v_max, msa_maxq_s32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_min, msa_minq_f32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_max, msa_maxq_f32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_min, msa_minq_f64) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_max, msa_maxq_f64) + +#define OPENCV_HAL_IMPL_MSA_INT_CMP_OP(_Tpvec, _Tpv, suffix, not_suffix) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ceqq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_mvnq_##not_suffix(msa_ceqq_##suffix(a.val, b.val)))); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cltq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgtq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cleq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_cgeq_##suffix(a.val, b.val))); } + +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint8x16, v16u8, u8, u8) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int8x16, v16i8, s8, u8) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint16x8, v8u16, u16, u16) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int16x8, v8i16, s16, u16) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint32x4, v4u32, u32, u32) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int32x4, v4i32, s32, u32) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float32x4, v4f32, f32, u32) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_uint64x2, v2u64, u64, u64) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_int64x2, v2i64, s64, u64) +OPENCV_HAL_IMPL_MSA_INT_CMP_OP(v_float64x2, v2f64, f64, u64) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ceqq_f32(a.val, a.val))); } +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ceqq_f64(a.val, a.val))); } + +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_add_wrap, msa_addq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_add_wrap, msa_addq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_add_wrap, msa_addq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_add_wrap, msa_addq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_sub_wrap, msa_subq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_sub_wrap, msa_subq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_sub_wrap, msa_subq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_sub_wrap, msa_subq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_mul_wrap, msa_mulq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_mul_wrap, msa_mulq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_mul_wrap, msa_mulq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_mul_wrap, msa_mulq_s16) + +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint8x16, v_absdiff, msa_abdq_u8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint16x8, v_absdiff, msa_abdq_u16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_uint32x4, v_absdiff, msa_abdq_u32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float32x4, v_absdiff, msa_abdq_f32) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_float64x2, v_absdiff, msa_abdq_f64) + +/** Saturating absolute difference **/ +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int8x16, v_absdiffs, msa_qabdq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC(v_int16x8, v_absdiffs, msa_qabdq_s16) + +#define OPENCV_HAL_IMPL_MSA_BIN_FUNC2(_Tpvec, _Tpvec2, _Tpv, func, intrin) \ +inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec2(MSA_TPV_REINTERPRET(_Tpv, intrin(a.val, b.val))); \ +} + +OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int8x16, v_uint8x16, v16u8, v_absdiff, msa_abdq_s8) +OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int16x8, v_uint16x8, v8u16, v_absdiff, msa_abdq_s16) +OPENCV_HAL_IMPL_MSA_BIN_FUNC2(v_int32x4, v_uint32x4, v4u32, v_absdiff, msa_abdq_s32) + +/* v_magnitude, v_sqr_magnitude, v_fma, v_muladd */ +inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 x(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); + return v_sqrt(x); +} + +inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(msa_mlaq_f32(msa_mulq_f32(a.val, a.val), b.val, b.val)); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_float32x4(msa_mlaq_f32(c.val, a.val, b.val)); +} + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_int32x4(msa_mlaq_s32(c.val, a.val, b.val)); +} + +inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + v_float64x2 x(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); + return v_sqrt(x); +} + +inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(msa_mlaq_f64(msa_mulq_f64(a.val, a.val), b.val, b.val)); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_float64x2(msa_mlaq_f64(c.val, a.val, b.val)); +} + +inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_fma(a, b, c); +} + +// trade efficiency for convenience +#define OPENCV_HAL_IMPL_MSA_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ +inline _Tpvec v_shl(const _Tpvec& a, int n) \ +{ return _Tpvec(msa_shlq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ +inline _Tpvec v_shr(const _Tpvec& a, int n) \ +{ return _Tpvec(msa_shrq_##suffix(a.val, msa_dupq_n_##ssuffix((_Tps)n))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec(msa_shlq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec(msa_shrq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_rshr(const _Tpvec& a) \ +{ return _Tpvec(msa_rshrq_n_##suffix(a.val, n)); } + +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint8x16, u8, schar, s8) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int8x16, s8, schar, s8) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint16x8, u16, short, s16) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int16x8, s16, short, s16) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint32x4, u32, int, s32) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int32x4, s32, int, s32) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_uint64x2, u64, int64, s64) +OPENCV_HAL_IMPL_MSA_SHIFT_OP(v_int64x2, s64, int64, s64) + +/* v_rotate_right, v_rotate_left */ +#define OPENCV_HAL_IMPL_MSA_ROTATE_OP(_Tpvec, _Tpv, _Tpvs, suffix) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##suffix(0), n))); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(msa_dupq_n_##suffix(0), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ \ + return a; \ +} \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), n))); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, b.val), MSA_TPV_REINTERPRET(_Tpvs, a.val), _Tpvec::nlanes - n))); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ \ + CV_UNUSED(b); \ + return a; \ +} + +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint8x16, v16u8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int8x16, v16i8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint16x8, v8u16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int16x8, v8i16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float32x4, v4f32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_uint64x2, v2u64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_int64x2, v2i64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_ROTATE_OP(v_float64x2, v2f64, v2i64, s64) + +#define OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(msa_ld1q_##suffix(ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr), msa_dup_n_##suffix((_Tp)0))); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ return _Tpvec(msa_combine_##suffix(msa_ld1_##suffix(ptr0), msa_ld1_##suffix(ptr1))); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ msa_st1q_##suffix(ptr, a.val); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ \ + int n = _Tpvec::nlanes; \ + for( int i = 0; i < (n/2); i++ ) \ + ptr[i] = a.val[i]; \ +} \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + int n = _Tpvec::nlanes; \ + for( int i = 0; i < (n/2); i++ ) \ + ptr[i] = a.val[i+(n/2)]; \ +} + +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int16x8, short, s16) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int32x4, int, s32) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float32x4, float, f32) +OPENCV_HAL_IMPL_MSA_LOADSTORE_OP(v_float64x2, double, f64) + + +/** Reverse **/ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + v_uint8x16 c = v_uint8x16((v16u8)__builtin_msa_vshf_b((v16i8)((v2i64){0x08090A0B0C0D0E0F, 0x0001020304050607}), msa_dupq_n_s8(0), (v16i8)a.val)); + return c; +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + v_uint16x8 c = v_uint16x8((v8u16)__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000500060007, 0x0000000100020003}), msa_dupq_n_s16(0), (v8i16)a.val)); + return c; +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + v_uint32x4 c; + c.val[0] = a.val[3]; + c.val[1] = a.val[2]; + c.val[2] = a.val[1]; + c.val[3] = a.val[0]; + return c; +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + v_uint64x2 c; + c.val[0] = a.val[1]; + c.val[1] = a.val[0]; + return c; +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(func, cfunc) \ +inline unsigned short v_reduce_##func(const v_uint16x8& a) \ +{ \ + v8u16 a_lo, a_hi; \ + ILVRL_H2_UH(a.val, msa_dupq_n_u16(0), a_lo, a_hi); \ + v4u32 b = msa_##func##q_u32(msa_paddlq_u16(a_lo), msa_paddlq_u16(a_hi)); \ + v4u32 b_lo, b_hi; \ + ILVRL_W2_UW(b, msa_dupq_n_u32(0), b_lo, b_hi); \ + v2u64 c = msa_##func##q_u64(msa_paddlq_u32(b_lo), msa_paddlq_u32(b_hi)); \ + return (unsigned short)cfunc(c[0], c[1]); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8U(min, std::min) + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(func, cfunc) \ +inline short v_reduce_##func(const v_int16x8& a) \ +{ \ + v8i16 a_lo, a_hi; \ + ILVRL_H2_SH(a.val, msa_dupq_n_s16(0), a_lo, a_hi); \ + v4i32 b = msa_##func##q_s32(msa_paddlq_s16(a_lo), msa_paddlq_s16(a_hi)); \ + v4i32 b_lo, b_hi; \ + ILVRL_W2_SW(b, msa_dupq_n_s32(0), b_lo, b_hi); \ + v2i64 c = msa_##func##q_s64(msa_paddlq_s32(b_lo), msa_paddlq_s32(b_hi)); \ + return (short)cfunc(c[0], c[1]); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_8S(min, std::min) + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(_Tpvec, scalartype, func, cfunc) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return (scalartype)cfunc(cfunc(a.val[0], a.val[1]), cfunc(a.val[2], a.val[3])); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_int32x4, int, min, std::min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, max, std::max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_4(v_float32x4, float, min, std::min) + + +#define OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(_Tpvec, scalartype, _Tpvec2, func) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpvec2 a1, a2; \ + v_expand(a, a1, a2); \ + return (scalartype)v_reduce_##func(v_##func(a1, a2)); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_uint8x16, uchar, v_uint16x8, max) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, min) +OPENCV_HAL_IMPL_MSA_REDUCE_OP_16(v_int8x16, char, v_int16x8, max) + + + +#define OPENCV_HAL_IMPL_MSA_REDUCE_SUM(_Tpvec, scalartype, suffix) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + return (scalartype)msa_sum_##suffix(a.val); \ +} + +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint8x16, unsigned short, u8) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int8x16, short, s8) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint16x8, unsigned, u16) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int16x8, int, s16) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_uint32x4, uint64_t, u32) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_int32x4, int64_t, s32) +OPENCV_HAL_IMPL_MSA_REDUCE_SUM(v_float32x4, float, f32) + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ return (uint64)(msa_getq_lane_u64(a.val, 0) + msa_getq_lane_u64(a.val, 1)); } +inline int64 v_reduce_sum(const v_int64x2& a) +{ return (int64)(msa_getq_lane_s64(a.val, 0) + msa_getq_lane_s64(a.val, 1)); } +inline double v_reduce_sum(const v_float64x2& a) +{ + return msa_getq_lane_f64(a.val, 0) + msa_getq_lane_f64(a.val, 1); +} + +/* v_reduce_sum4, v_reduce_sad */ +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + v4f32 u0 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val))), + MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, b.val), MSA_TPV_REINTERPRET(v4i32, a.val)))); // a0+a1 b0+b1 a2+a3 b2+b3 + v4f32 u1 = msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val))), + MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, d.val), MSA_TPV_REINTERPRET(v4i32, c.val)))); // c0+c1 d0+d1 c2+c3 d2+d3 + + return v_float32x4(msa_addq_f32(MSA_TPV_REINTERPRET(v4f32, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))), + MSA_TPV_REINTERPRET(v4f32, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, u1), MSA_TPV_REINTERPRET(v2i64, u0))))); +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + v16u8 t0 = msa_abdq_u8(a.val, b.val); + v8u16 t1 = msa_paddlq_u8(t0); + v4u32 t2 = msa_paddlq_u16(t1); + return msa_sum_u32(t2); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + v16u8 t0 = MSA_TPV_REINTERPRET(v16u8, msa_abdq_s8(a.val, b.val)); + v8u16 t1 = msa_paddlq_u8(t0); + v4u32 t2 = msa_paddlq_u16(t1); + return msa_sum_u32(t2); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + v8u16 t0 = msa_abdq_u16(a.val, b.val); + v4u32 t1 = msa_paddlq_u16(t0); + return msa_sum_u32(t1); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + v8u16 t0 = MSA_TPV_REINTERPRET(v8u16, msa_abdq_s16(a.val, b.val)); + v4u32 t1 = msa_paddlq_u16(t0); + return msa_sum_u32(t1); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + v4u32 t0 = msa_abdq_u32(a.val, b.val); + return msa_sum_u32(t0); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + v4u32 t0 = MSA_TPV_REINTERPRET(v4u32, msa_abdq_s32(a.val, b.val)); + return msa_sum_u32(t0); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + v4f32 t0 = msa_abdq_f32(a.val, b.val); + return msa_sum_f32(t0); +} + +/* v_popcount */ +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(_Tpvec) \ +inline v_uint8x16 v_popcount(const _Tpvec& a) \ +{ \ + v16u8 t = MSA_TPV_REINTERPRET(v16u8, msa_cntq_s8(MSA_TPV_REINTERPRET(v16i8, a.val))); \ + return v_uint8x16(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_uint8x16) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE8(v_int8x16) + +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(_Tpvec) \ +inline v_uint16x8 v_popcount(const _Tpvec& a) \ +{ \ + v8u16 t = MSA_TPV_REINTERPRET(v8u16, msa_cntq_s16(MSA_TPV_REINTERPRET(v8i16, a.val))); \ + return v_uint16x8(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_uint16x8) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE16(v_int16x8) + +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(_Tpvec) \ +inline v_uint32x4 v_popcount(const _Tpvec& a) \ +{ \ + v4u32 t = MSA_TPV_REINTERPRET(v4u32, msa_cntq_s32(MSA_TPV_REINTERPRET(v4i32, a.val))); \ + return v_uint32x4(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_uint32x4) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE32(v_int32x4) + +#define OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(_Tpvec) \ +inline v_uint64x2 v_popcount(const _Tpvec& a) \ +{ \ + v2u64 t = MSA_TPV_REINTERPRET(v2u64, msa_cntq_s64(MSA_TPV_REINTERPRET(v2i64, a.val))); \ + return v_uint64x2(t); \ +} +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_uint64x2) +OPENCV_HAL_IMPL_MSA_POPCOUNT_SIZE64(v_int64x2) + +inline int v_signmask(const v_uint8x16& a) +{ + v8i8 m0 = msa_create_s8(CV_BIG_UINT(0x0706050403020100)); + v16u8 v0 = msa_shlq_u8(msa_shrq_n_u8(a.val, 7), msa_combine_s8(m0, m0)); + v8u16 v1 = msa_paddlq_u8(v0); + v4u32 v2 = msa_paddlq_u16(v1); + v2u64 v3 = msa_paddlq_u32(v2); + return (int)msa_getq_lane_u64(v3, 0) + ((int)msa_getq_lane_u64(v3, 1) << 8); +} +inline int v_signmask(const v_int8x16& a) +{ return v_signmask(v_reinterpret_as_u8(a)); } + +inline int v_signmask(const v_uint16x8& a) +{ + v4i16 m0 = msa_create_s16(CV_BIG_UINT(0x0003000200010000)); + v8u16 v0 = msa_shlq_u16(msa_shrq_n_u16(a.val, 15), msa_combine_s16(m0, m0)); + v4u32 v1 = msa_paddlq_u16(v0); + v2u64 v2 = msa_paddlq_u32(v1); + return (int)msa_getq_lane_u64(v2, 0) + ((int)msa_getq_lane_u64(v2, 1) << 4); +} +inline int v_signmask(const v_int16x8& a) +{ return v_signmask(v_reinterpret_as_u16(a)); } + +inline int v_signmask(const v_uint32x4& a) +{ + v2i32 m0 = msa_create_s32(CV_BIG_UINT(0x0000000100000000)); + v4u32 v0 = msa_shlq_u32(msa_shrq_n_u32(a.val, 31), msa_combine_s32(m0, m0)); + v2u64 v1 = msa_paddlq_u32(v0); + return (int)msa_getq_lane_u64(v1, 0) + ((int)msa_getq_lane_u64(v1, 1) << 2); +} +inline int v_signmask(const v_int32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } + +inline int v_signmask(const v_uint64x2& a) +{ + v2u64 v0 = msa_shrq_n_u64(a.val, 63); + return (int)msa_getq_lane_u64(v0, 0) + ((int)msa_getq_lane_u64(v0, 1) << 1); +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } + +#define OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(_Tpvec, _Tpvec2, suffix, shift) \ +inline bool v_check_all(const v_##_Tpvec& a) \ +{ \ + _Tpvec2 v0 = msa_shrq_n_##suffix(msa_mvnq_##suffix(a.val), shift); \ + v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ + return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) == 0; \ +} \ +inline bool v_check_any(const v_##_Tpvec& a) \ +{ \ + _Tpvec2 v0 = msa_shrq_n_##suffix(a.val, shift); \ + v2u64 v1 = MSA_TPV_REINTERPRET(v2u64, v0); \ + return (msa_getq_lane_u64(v1, 0) | msa_getq_lane_u64(v1, 1)) != 0; \ +} + +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint8x16, v16u8, u8, 7) +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint16x8, v8u16, u16, 15) +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint32x4, v4u32, u32, 31) +OPENCV_HAL_IMPL_MSA_CHECK_ALLANY(uint64x2, v2u64, u64, 63) + +inline bool v_check_all(const v_int8x16& a) +{ return v_check_all(v_reinterpret_as_u8(a)); } +inline bool v_check_all(const v_int16x8& a) +{ return v_check_all(v_reinterpret_as_u16(a)); } +inline bool v_check_all(const v_int32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } + +inline bool v_check_any(const v_int8x16& a) +{ return v_check_any(v_reinterpret_as_u8(a)); } +inline bool v_check_any(const v_int16x8& a) +{ return v_check_any(v_reinterpret_as_u16(a)); } +inline bool v_check_any(const v_int32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } + +inline bool v_check_all(const v_int64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_int64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } + +/* v_select */ +#define OPENCV_HAL_IMPL_MSA_SELECT(_Tpvec, _Tpv, _Tpvu) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_bslq_u8(MSA_TPV_REINTERPRET(_Tpvu, mask.val), \ + MSA_TPV_REINTERPRET(_Tpvu, b.val), MSA_TPV_REINTERPRET(_Tpvu, a.val)))); \ +} + +OPENCV_HAL_IMPL_MSA_SELECT(v_uint8x16, v16u8, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_int8x16, v16i8, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_uint16x8, v8u16, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_int16x8, v8i16, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_uint32x4, v4u32, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_int32x4, v4i32, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_float32x4, v4f32, v16u8) +OPENCV_HAL_IMPL_MSA_SELECT(v_float64x2, v2f64, v16u8) + +#define OPENCV_HAL_IMPL_MSA_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix, ssuffix, _Tpv, _Tpvs) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + b0.val = msa_paddlq_##suffix(a_lo); \ + b1.val = msa_paddlq_##suffix(a_hi); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + _Tpv a_lo = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + return _Tpwvec(msa_paddlq_##suffix(a_lo)); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + _Tpv a_hi = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), msa_dupq_n_##ssuffix(0))); \ + return _Tpwvec(msa_paddlq_##suffix(a_hi)); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return _Tpwvec(msa_movl_##suffix(msa_ld1_##suffix(ptr))); \ +} + +OPENCV_HAL_IMPL_MSA_EXPAND(v_uint8x16, v_uint16x8, uchar, u8, s8, v16u8, v16i8) +OPENCV_HAL_IMPL_MSA_EXPAND(v_int8x16, v_int16x8, schar, s8, s8, v16i8, v16i8) +OPENCV_HAL_IMPL_MSA_EXPAND(v_uint16x8, v_uint32x4, ushort, u16, s16, v8u16, v8i16) +OPENCV_HAL_IMPL_MSA_EXPAND(v_int16x8, v_int32x4, short, s16, s16, v8i16, v8i16) +OPENCV_HAL_IMPL_MSA_EXPAND(v_uint32x4, v_uint64x2, uint, u32, s32, v4u32, v4i32) +OPENCV_HAL_IMPL_MSA_EXPAND(v_int32x4, v_int64x2, int, s32, s32, v4i32, v4i32) + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + return v_uint32x4((v4u32){ptr[0], ptr[1], ptr[2], ptr[3]}); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + return v_int32x4((v4i32){ptr[0], ptr[1], ptr[2], ptr[3]}); +} + +/* v_zip, v_combine_low, v_combine_high, v_recombine */ +#define OPENCV_HAL_IMPL_MSA_UNPACKS(_Tpvec, _Tpv, _Tpvs, ssuffix) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ +{ \ + b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ + b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ +} \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val)))); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + c.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ + d.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, b.val), MSA_TPV_REINTERPRET(v2i64, a.val))); \ +} + +OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint8x16, v16u8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_int8x16, v16i8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint16x8, v8u16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_int16x8, v8i16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_float32x4, v4f32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_UNPACKS(v_float64x2, v2f64, v2i64, s64) + +/* v_extract */ +#define OPENCV_HAL_IMPL_MSA_EXTRACT(_Tpvec, _Tpv, _Tpvs, suffix) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(MSA_TPV_REINTERPRET(_Tpv, msa_extq_##suffix(MSA_TPV_REINTERPRET(_Tpvs, a.val), MSA_TPV_REINTERPRET(_Tpvs, b.val), s))); \ +} + +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint8x16, v16u8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int8x16, v16i8, v16i8, s8) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint16x8, v8u16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int16x8, v8i16, v8i16, s16) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_uint64x2, v2u64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_int64x2, v2i64, v2i64, s64) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_float32x4, v4f32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_EXTRACT(v_float64x2, v2f64, v2i64, s64) + +/* v_round, v_floor, v_ceil, v_trunc */ +inline v_int32x4 v_round(const v_float32x4& a) +{ + return v_int32x4(msa_cvttintq_s32_f32(a.val)); +} + +inline v_int32x4 v_floor(const v_float32x4& a) +{ + v4i32 a1 = msa_cvttintq_s32_f32(a.val); + return v_int32x4(msa_addq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(msa_cvtfintq_f32_s32(a1), a.val)))); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + v4i32 a1 = msa_cvttintq_s32_f32(a.val); + return v_int32x4(msa_subq_s32(a1, MSA_TPV_REINTERPRET(v4i32, msa_cgtq_f32(a.val, msa_cvtfintq_f32_s32(a1))))); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ + return v_int32x4(msa_cvttruncq_s32_f32(a.val)); +} + +inline v_int32x4 v_round(const v_float64x2& a) +{ + return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_dupq_n_s64(0))); +} + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + return v_int32x4(msa_pack_s64(msa_cvttintq_s64_f64(a.val), msa_cvttintq_s64_f64(b.val))); +} + +inline v_int32x4 v_floor(const v_float64x2& a) +{ + v2f64 a1 = msa_cvtrintq_f64(a.val); + return v_int32x4(msa_pack_s64(msa_addq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a1, a.val))), msa_dupq_n_s64(0))); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + v2f64 a1 = msa_cvtrintq_f64(a.val); + return v_int32x4(msa_pack_s64(msa_subq_s64(msa_cvttruncq_s64_f64(a1), MSA_TPV_REINTERPRET(v2i64, msa_cgtq_f64(a.val, a1))), msa_dupq_n_s64(0))); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ + return v_int32x4(msa_pack_s64(msa_cvttruncq_s64_f64(a.val), msa_dupq_n_s64(0))); +} + +#define OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(_Tpvec, _Tpv, _Tpvs, ssuffix) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, \ + _Tpvec& b2, _Tpvec& b3) \ +{ \ + _Tpv t00 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ + _Tpv t01 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a1.val), MSA_TPV_REINTERPRET(_Tpvs, a0.val))); \ + _Tpv t10 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ + _Tpv t11 = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_##ssuffix(MSA_TPV_REINTERPRET(_Tpvs, a3.val), MSA_TPV_REINTERPRET(_Tpvs, a2.val))); \ + b0.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ + b1.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t10), MSA_TPV_REINTERPRET(v2i64, t00))); \ + b2.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvrq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ + b3.val = MSA_TPV_REINTERPRET(_Tpv, msa_ilvlq_s64(MSA_TPV_REINTERPRET(v2i64, t11), MSA_TPV_REINTERPRET(v2i64, t01))); \ +} + +OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_uint32x4, v4u32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_int32x4, v4i32, v4i32, s32) +OPENCV_HAL_IMPL_MSA_TRANSPOSE4x4(v_float32x4, v4f32, v4i32, s32) + +#define OPENCV_HAL_IMPL_MSA_INTERLEAVED(_Tpvec, _Tp, suffix) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ +{ \ + msa_ld2q_##suffix(ptr, &a.val, &b.val); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ +{ \ + msa_ld3q_##suffix(ptr, &a.val, &b.val, &c.val); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ + v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + msa_ld4q_##suffix(ptr, &a.val, &b.val, &c.val, &d.val); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + msa_st2q_##suffix(ptr, a.val, b.val); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + msa_st3q_##suffix(ptr, a.val, b.val, c.val); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, const v_##_Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + msa_st4q_##suffix(ptr, a.val, b.val, c.val, d.val); \ +} + +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int8x16, schar, s8) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int16x8, short, s16) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int32x4, int, s32) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(float32x4, float, f32) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(uint64x2, uint64, u64) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(int64x2, int64, s64) +OPENCV_HAL_IMPL_MSA_INTERLEAVED(float64x2, double, f64) + +/* v_cvt_f32, v_cvt_f64, v_cvt_f64_high */ +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(msa_cvtfintq_f32_s32(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + return v_float32x4(msa_cvtfq_f32_f64(a.val, msa_dupq_n_f64(0.0f))); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + return v_float32x4(msa_cvtfq_f32_f64(a.val, b.val)); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + return v_float64x2(msa_cvtflq_f64_f32(msa_cvtfintq_f32_s32(a.val))); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + return v_float64x2(msa_cvtfhq_f64_f32(msa_cvtfintq_f32_s32(a.val))); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + return v_float64x2(msa_cvtflq_f64_f32(a.val)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + return v_float64x2(msa_cvtfhq_f64_f32(a.val)); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ + return v_float64x2(msa_cvtfintq_f64_s64(a.val)); +} + +////////////// Lookup table access //////////////////// +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[ 0]], + tab[idx[ 1]], + tab[idx[ 2]], + tab[idx[ 3]], + tab[idx[ 4]], + tab[idx[ 5]], + tab[idx[ 6]], + tab[idx[ 7]], + tab[idx[ 8]], + tab[idx[ 9]], + tab[idx[10]], + tab[idx[11]], + tab[idx[12]], + tab[idx[13]], + tab[idx[14]], + tab[idx[15]] + }; + return v_int8x16(msa_ld1q_s8(elems)); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[4]], + tab[idx[4] + 1], + tab[idx[5]], + tab[idx[5] + 1], + tab[idx[6]], + tab[idx[6] + 1], + tab[idx[7]], + tab[idx[7] + 1] + }; + return v_int8x16(msa_ld1q_s8(elems)); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[2] + 2], + tab[idx[2] + 3], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[3] + 2], + tab[idx[3] + 3] + }; + return v_int8x16(msa_ld1q_s8(elems)); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } + + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]], + tab[idx[4]], + tab[idx[5]], + tab[idx[6]], + tab[idx[7]] + }; + return v_int16x8(msa_ld1q_s16(elems)); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1] + }; + return v_int16x8(msa_ld1q_s16(elems)); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(msa_combine_s16(msa_ld1_s16(tab + idx[0]), msa_ld1_s16(tab + idx[1]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_int32x4(msa_ld1q_s32(elems)); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(msa_combine_s32(msa_ld1_s32(tab + idx[0]), msa_ld1_s32(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(msa_ld1q_s32(tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(msa_combine_s64(msa_create_s64(tab[idx[0]]), msa_create_s64(tab[idx[1]]))); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(msa_ld1q_s64(tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_float32x4(msa_ld1q_f32(elems)); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ + uint64 CV_DECL_ALIGNED(32) elems[2] = + { + *(uint64*)(tab + idx[0]), + *(uint64*)(tab + idx[1]) + }; + return v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ld1q_u64(elems))); +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4(msa_ld1q_f32(tab + idx[0])); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + unsigned CV_DECL_ALIGNED(32) elems[4] = + { + tab[msa_getq_lane_s32(idxvec.val, 0)], + tab[msa_getq_lane_s32(idxvec.val, 1)], + tab[msa_getq_lane_s32(idxvec.val, 2)], + tab[msa_getq_lane_s32(idxvec.val, 3)] + }; + return v_uint32x4(msa_ld1q_u32(elems)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + v4f32 xy02 = msa_combine_f32(msa_ld1_f32(tab + idx[0]), msa_ld1_f32(tab + idx[2])); + v4f32 xy13 = msa_combine_f32(msa_ld1_f32(tab + idx[1]), msa_ld1_f32(tab + idx[3])); + x = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvevq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); + y = v_float32x4(MSA_TPV_REINTERPRET(v4f32, msa_ilvodq_s32(MSA_TPV_REINTERPRET(v4i32, xy13), MSA_TPV_REINTERPRET(v4i32, xy02)))); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0705060403010200, 0x0F0D0E0C0B090A08}), msa_dupq_n_s8(0), vec.val)); + return c; +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0703060205010400, 0x0F0B0E0A0D090C08}), msa_dupq_n_s8(0), vec.val)); + return c; +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0003000100020000, 0x0007000500060004}), msa_dupq_n_s16(0), vec.val)); + return c; +} + +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } + +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0005000100040000, 0x0007000300060002}), msa_dupq_n_s16(0), vec.val)); + return c; +} + +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + v_int32x4 c; + c.val[0] = vec.val[0]; + c.val[1] = vec.val[2]; + c.val[2] = vec.val[1]; + c.val[3] = vec.val[3]; + return c; +} + +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + v_int8x16 c = v_int8x16(__builtin_msa_vshf_b((v16i8)((v2i64){0x0908060504020100, 0x131211100E0D0C0A}), msa_dupq_n_s8(0), vec.val)); + return c; +} + +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + v_int16x8 c = v_int16x8(__builtin_msa_vshf_h((v8i16)((v2i64){0x0004000200010000, 0x0009000800060005}), msa_dupq_n_s16(0), vec.val)); + return c; +} + +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + double CV_DECL_ALIGNED(32) elems[2] = + { + tab[idx[0]], + tab[idx[1]] + }; + return v_float64x2(msa_ld1q_f64(elems)); +} + +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(msa_ld1q_f64(tab + idx[0])); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + v2f64 xy0 = msa_ld1q_f64(tab + idx[0]); + v2f64 xy1 = msa_ld1q_f64(tab + idx[1]); + x = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvevq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); + y = v_float64x2(MSA_TPV_REINTERPRET(v2f64, msa_ilvodq_s64(MSA_TPV_REINTERPRET(v2i64, xy1), MSA_TPV_REINTERPRET(v2i64, xy0)))); +} + +template +inline typename _Tp::lane_type v_extract_n(const _Tp& a) +{ + return v_rotate_right(a).get0(); +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) +{ + return v_setall_u32(v_extract_n(a)); +} +template +inline v_int32x4 v_broadcast_element(const v_int32x4& a) +{ + return v_setall_s32(v_extract_n(a)); +} +template +inline v_float32x4 v_broadcast_element(const v_float32x4& a) +{ + return v_setall_f32(v_extract_n(a)); +} + +////// FP16 support /////// +#if CV_FP16 +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ +#ifndef msa_ld1_f16 + v4f16 v = (v4f16)msa_ld1_s16((const short*)ptr); +#else + v4f16 v = msa_ld1_f16((const __fp16*)ptr); +#endif + return v_float32x4(msa_cvt_f32_f16(v)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + v4f16 hv = msa_cvt_f16_f32(v.val); + +#ifndef msa_st1_f16 + msa_st1_s16((short*)ptr, (int16x4_t)hv); +#else + msa_st1_f16((__fp16*)ptr, hv); +#endif +} +#else +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + float buf[4]; + for( int i = 0; i < 4; i++ ) + buf[i] = (float)ptr[i]; + return v_load(buf); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + float buf[4]; + v_store(buf, v); + for( int i = 0; i < 4; i++ ) + ptr[i] = (hfloat)buf[i]; +} +#endif + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp index eb10edfc44..64fb7d73bc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_neon.hpp @@ -1,2679 +1,2679 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HAL_INTRIN_NEON_HPP -#define OPENCV_HAL_INTRIN_NEON_HPP - -#include -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD128 1 -#if defined(__aarch64__) || defined(_M_ARM64) -#define CV_SIMD128_64F 1 -#else -#define CV_SIMD128_64F 0 -#endif - -// The following macro checks if the code is being compiled for the -// AArch64 execution state of Armv8, to enable the 128-bit -// intrinsics. The macro `__ARM_64BIT_STATE` is the one recommended by -// the Arm C Language Extension (ACLE) specifications [1] to check the -// availability of 128-bit intrinsics, and it is supporrted by clang -// and gcc. The macro `_M_ARM64` is the equivalent one for Microsoft -// Visual Studio [2] . -// -// [1] https://developer.arm.com/documentation/101028/0012/13--Advanced-SIMD--Neon--intrinsics -// [2] https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros -#if defined(__ARM_64BIT_STATE) || defined(_M_ARM64) -#define CV_NEON_AARCH64 1 -#else -#define CV_NEON_AARCH64 0 -#endif - - -//////////// Utils //////////// - -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ - { c = vuzp1q_##suffix(a, b); d = vuzp2q_##suffix(a, b); } -#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv&a, const _Tpv&b, _Tpv& c, _Tpv& d) \ - { c = vuzp1_##suffix(a, b); d = vuzp2_##suffix(a, b); } -#else -#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ - { _Tpvx2 ab = vuzpq_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } -#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ - inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ - { _Tpvx2 ab = vuzp_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } -#endif - -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) \ - template static inline \ - _Tpv vreinterpretq_##suffix##_f64(T a) { return (_Tpv) a; } \ - template static inline \ - float64x2_t vreinterpretq_f64_##suffix(T a) { return (float64x2_t) a; } -#else -#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) -#endif - -#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(_Tpv, _Tpvl, suffix) \ - OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) \ - OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpvl##_t, _Tpvl##x2_t, suffix) \ - OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) - -#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(_Tpv, _Tpvl, suffix) \ - OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) - -#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(_Tpv, _Tpvl, suffix) \ - OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) - -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint8x16, uint8x8, u8) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int8x16, int8x8, s8) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint16x8, uint16x4, u16) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int16x8, int16x4, s16) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint32x4, uint32x2, u32) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int32x4, int32x2, s32) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(float32x4, float32x2, f32) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(uint64x2, uint64x1, u64) -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(int64x2, int64x1, s64) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(float64x2, float64x1,f64) -#endif - -//////////// Compatibility layer //////////// -template struct VTraits { - static inline int vlanes() { return T::nlanes; } - enum { max_nlanes = T::nlanes, nlanes = T::nlanes }; - using lane_type = typename T::lane_type; -}; - -template -inline typename VTraits::lane_type v_get0(const T& v) \ -{ \ - return v.get0(); \ -} -//////////// Types //////////// - -struct v_uint8x16 -{ - v_uint8x16() {} - explicit v_uint8x16(uint8x16_t v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = vld1q_u8(v); - } - uint8x16_t val; - -private: - friend struct VTraits; - enum { nlanes = 16 }; - typedef uchar lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint8x16& v); - uchar get0() const - { - return vgetq_lane_u8(val, 0); - } -}; - -struct v_int8x16 -{ - v_int8x16() {} - explicit v_int8x16(int8x16_t v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = vld1q_s8(v); - } - int8x16_t val; - -private: - friend struct VTraits; - enum { nlanes = 16 }; - typedef schar lane_type; - - friend typename VTraits::lane_type v_get0(const v_int8x16& v); - schar get0() const - { - return vgetq_lane_s8(val, 0); - } -}; - -struct v_uint16x8 -{ - v_uint16x8() {} - explicit v_uint16x8(uint16x8_t v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = vld1q_u16(v); - } - uint16x8_t val; - -private: - friend struct VTraits; - enum { nlanes = 8 }; - typedef ushort lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint16x8& v); - ushort get0() const - { - return vgetq_lane_u16(val, 0); - } -}; - -struct v_int16x8 -{ - v_int16x8() {} - explicit v_int16x8(int16x8_t v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = vld1q_s16(v); - } - int16x8_t val; - -private: - friend struct VTraits; - enum { nlanes = 8 }; - typedef short lane_type; - - friend typename VTraits::lane_type v_get0(const v_int16x8& v); - short get0() const - { - return vgetq_lane_s16(val, 0); - } -}; - -struct v_uint32x4 -{ - v_uint32x4() {} - explicit v_uint32x4(uint32x4_t v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - unsigned v[] = {v0, v1, v2, v3}; - val = vld1q_u32(v); - } - uint32x4_t val; - -private: - friend struct VTraits; - enum { nlanes = 4 }; - typedef unsigned lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint32x4& v); - unsigned get0() const - { - return vgetq_lane_u32(val, 0); - } -}; - -struct v_int32x4 -{ - v_int32x4() {} - explicit v_int32x4(int32x4_t v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = vld1q_s32(v); - } - int32x4_t val; - -private: - friend struct VTraits; - enum { nlanes = 4 }; - typedef int lane_type; - - friend typename VTraits::lane_type v_get0(const v_int32x4& v); - int get0() const - { - return vgetq_lane_s32(val, 0); - } -}; - -struct v_float32x4 -{ - v_float32x4() {} - explicit v_float32x4(float32x4_t v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = vld1q_f32(v); - } - float32x4_t val; - -private: - friend struct VTraits; - enum { nlanes = 4 }; - typedef float lane_type; - - friend typename VTraits::lane_type v_get0(const v_float32x4& v); - float get0() const - { - return vgetq_lane_f32(val, 0); - } -}; - -struct v_uint64x2 -{ - v_uint64x2() {} - explicit v_uint64x2(uint64x2_t v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = vld1q_u64(v); - } - uint64x2_t val; -private: - friend struct VTraits; - enum { nlanes = 2 }; - typedef uint64 lane_type; - - friend typename VTraits::lane_type v_get0(const v_uint64x2& v); - uint64 get0() const - { - return vgetq_lane_u64(val, 0); - } -}; - -struct v_int64x2 -{ - v_int64x2() {} - explicit v_int64x2(int64x2_t v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = vld1q_s64(v); - } - int64x2_t val; - -private: - friend struct VTraits; - enum { nlanes = 2 }; - typedef int64 lane_type; - - friend typename VTraits::lane_type v_get0(const v_int64x2& v); - int64 get0() const - { - return vgetq_lane_s64(val, 0); - } -}; - -#if CV_SIMD128_64F -struct v_float64x2 -{ - v_float64x2() {} - explicit v_float64x2(float64x2_t v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = vld1q_f64(v); - } - - float64x2_t val; -private: - friend struct VTraits; - enum { nlanes = 2 }; - typedef double lane_type; - - friend typename VTraits::lane_type v_get0(const v_float64x2& v); - double get0() const - { - return vgetq_lane_f64(val, 0); - } -}; -#endif - -#define OPENCV_HAL_IMPL_NEON_INIT(_Tpv, _Tp, suffix) \ -inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(vdupq_n_##suffix((_Tp)0)); } \ -inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(vdupq_n_##suffix(v)); } \ -template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -inline _Tpv##_t vreinterpretq_##suffix##_##suffix(_Tpv##_t v) { return v; } \ -inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(vreinterpretq_u8_##suffix(v.val)); } \ -inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(vreinterpretq_s8_##suffix(v.val)); } \ -inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(vreinterpretq_u16_##suffix(v.val)); } \ -inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpretq_s16_##suffix(v.val)); } \ -inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(vreinterpretq_u32_##suffix(v.val)); } \ -inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(vreinterpretq_s32_##suffix(v.val)); } \ -inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(vreinterpretq_u64_##suffix(v.val)); } \ -inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(vreinterpretq_s64_##suffix(v.val)); } \ -inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(vreinterpretq_f32_##suffix(v.val)); } - -OPENCV_HAL_IMPL_NEON_INIT(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_INIT(int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_INIT(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_INIT(int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_INIT(uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_NEON_INIT(int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_INIT(uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_INIT(int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_INIT(float32x4, float, f32) -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_INIT_64(_Tpv, suffix) \ -inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(vreinterpretq_f64_##suffix(v.val)); } -OPENCV_HAL_IMPL_NEON_INIT(float64x2, double, f64) -OPENCV_HAL_IMPL_NEON_INIT_64(uint8x16, u8) -OPENCV_HAL_IMPL_NEON_INIT_64(int8x16, s8) -OPENCV_HAL_IMPL_NEON_INIT_64(uint16x8, u16) -OPENCV_HAL_IMPL_NEON_INIT_64(int16x8, s16) -OPENCV_HAL_IMPL_NEON_INIT_64(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_INIT_64(int32x4, s32) -OPENCV_HAL_IMPL_NEON_INIT_64(uint64x2, u64) -OPENCV_HAL_IMPL_NEON_INIT_64(int64x2, s64) -OPENCV_HAL_IMPL_NEON_INIT_64(float32x4, f32) -OPENCV_HAL_IMPL_NEON_INIT_64(float64x2, f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_PACK(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ -inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - hreg a1 = mov(a.val), b1 = mov(b.val); \ - return _Tpvec(vcombine_##suffix(a1, b1)); \ -} \ -inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = mov(a.val); \ - vst1_##suffix(ptr, a1); \ -} \ -template inline \ -_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - hreg a1 = rshr(a.val, n); \ - hreg b1 = rshr(b.val, n); \ - return _Tpvec(vcombine_##suffix(a1, b1)); \ -} \ -template inline \ -void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - hreg a1 = rshr(a.val, n); \ - vst1_##suffix(ptr, a1); \ -} - -OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_uint16x8, pack, vqmovn_u16, vqrshrn_n_u16) -OPENCV_HAL_IMPL_NEON_PACK(v_int8x16, schar, int8x8_t, s8, v_int16x8, pack, vqmovn_s16, vqrshrn_n_s16) -OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_uint32x4, pack, vqmovn_u32, vqrshrn_n_u32) -OPENCV_HAL_IMPL_NEON_PACK(v_int16x8, short, int16x4_t, s16, v_int32x4, pack, vqmovn_s32, vqrshrn_n_s32) -OPENCV_HAL_IMPL_NEON_PACK(v_uint32x4, unsigned, uint32x2_t, u32, v_uint64x2, pack, vmovn_u64, vrshrn_n_u64) -OPENCV_HAL_IMPL_NEON_PACK(v_int32x4, int, int32x2_t, s32, v_int64x2, pack, vmovn_s64, vrshrn_n_s64) - -OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_int16x8, pack_u, vqmovun_s16, vqrshrun_n_s16) -OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_int32x4, pack_u, vqmovun_s32, vqrshrun_n_s32) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - uint8x16_t ab = vcombine_u8(vmovn_u16(a.val), vmovn_u16(b.val)); - return v_uint8x16(ab); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - uint16x8_t nab = vcombine_u16(vmovn_u32(a.val), vmovn_u32(b.val)); - uint16x8_t ncd = vcombine_u16(vmovn_u32(c.val), vmovn_u32(d.val)); - return v_uint8x16(vcombine_u8(vmovn_u16(nab), vmovn_u16(ncd))); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - uint32x4_t ab = vcombine_u32(vmovn_u64(a.val), vmovn_u64(b.val)); - uint32x4_t cd = vcombine_u32(vmovn_u64(c.val), vmovn_u64(d.val)); - uint32x4_t ef = vcombine_u32(vmovn_u64(e.val), vmovn_u64(f.val)); - uint32x4_t gh = vcombine_u32(vmovn_u64(g.val), vmovn_u64(h.val)); - - uint16x8_t abcd = vcombine_u16(vmovn_u32(ab), vmovn_u32(cd)); - uint16x8_t efgh = vcombine_u16(vmovn_u32(ef), vmovn_u32(gh)); - return v_uint8x16(vcombine_u8(vmovn_u16(abcd), vmovn_u16(efgh))); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); - float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); - res = vmlaq_lane_f32(res, m1.val, vl, 1); - res = vmlaq_lane_f32(res, m2.val, vh, 0); - res = vmlaq_lane_f32(res, m3.val, vh, 1); - return v_float32x4(res); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); - float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); - res = vmlaq_lane_f32(res, m1.val, vl, 1); - res = vmlaq_lane_f32(res, m2.val, vh, 0); - res = vaddq_f32(res, a.val); - return v_float32x4(res); -} - -#define OPENCV_HAL_IMPL_NEON_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op (const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint8x16, vqaddq_u8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint8x16, vqsubq_u8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int8x16, vqaddq_s8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int8x16, vqsubq_s8) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint16x8, vqaddq_u16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint16x8, vqsubq_u16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int16x8, vqaddq_s16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int16x8, vqsubq_s16) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int32x4, vaddq_s32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int32x4, vsubq_s32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_int32x4, vmulq_s32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint32x4, vaddq_u32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint32x4, vsubq_u32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_uint32x4, vmulq_u32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float32x4, vaddq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float32x4, vsubq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float32x4, vmulq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int64x2, vaddq_s64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int64x2, vsubq_s64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint64x2, vaddq_u64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint64x2, vsubq_u64) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float32x4, vdivq_f32) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float64x2, vaddq_f64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float64x2, vsubq_f64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float64x2, vmulq_f64) -OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float64x2, vdivq_f64) -#else -inline v_float32x4 v_div (const v_float32x4& a, const v_float32x4& b) -{ - float32x4_t reciprocal = vrecpeq_f32(b.val); - reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); - reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); - return v_float32x4(vmulq_f32(a.val, reciprocal)); -} -#endif - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_NEON_MUL_SAT(_Tpvec, _Tpwvec) \ - inline _Tpvec v_mul (const _Tpvec& a, const _Tpvec& b) \ - { \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ - } - -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int16x8, v_int32x4) -OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint16x8, v_uint32x4) - -// Multiply and expand -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - c.val = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_s8(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - c.val = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_u8(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - c.val = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_s16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - c.val = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_u16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - c.val = vmull_u32(vget_low_u32(a.val), vget_low_u32(b.val)); -#if CV_NEON_AARCH64 - d.val = vmull_high_u32(a.val, b.val); -#else // #if CV_NEON_AARCH64 - d.val = vmull_u32(vget_high_u32(a.val), vget_high_u32(b.val)); -#endif // #if CV_NEON_AARCH64 -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ -#if CV_NEON_AARCH64 - int32x4_t c = vmull_high_s16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - int32x4_t c = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); -#endif // #if CV_NEON_AARCH64 - return v_int16x8(vcombine_s16( - vshrn_n_s32(vmull_s16( vget_low_s16(a.val), vget_low_s16(b.val)), 16), - vshrn_n_s32(c, 16) - )); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_NEON_AARCH64 - uint32x4_t c = vmull_high_u16(a.val, b.val); -#else // #if CV_NEON_AARCH64 - uint32x4_t c = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); -#endif // #if CV_NEON_AARCH64 - return v_uint16x8(vcombine_u16( - vshrn_n_u32(vmull_u16( vget_low_u16(a.val), vget_low_u16(b.val)), 16), - vshrn_n_u32(c, 16) - )); -} - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - int16x8_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int16x4_t a0 = vget_low_s16(uzp1); - int16x4_t b0 = vget_high_s16(uzp1); - int16x4_t a1 = vget_low_s16(uzp2); - int16x4_t b1 = vget_high_s16(uzp2); - int32x4_t p = vmull_s16(a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -} -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - int16x8_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int16x4_t a0 = vget_low_s16(uzp1); - int16x4_t b0 = vget_high_s16(uzp1); - int16x4_t a1 = vget_low_s16(uzp2); - int16x4_t b1 = vget_high_s16(uzp2); - int32x4_t p = vmlal_s16(c.val, a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - int32x4_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int32x2_t a0 = vget_low_s32(uzp1); - int32x2_t b0 = vget_high_s32(uzp1); - int32x2_t a1 = vget_low_s32(uzp2); - int32x2_t b1 = vget_high_s32(uzp2); - int64x2_t p = vmull_s32(a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - int32x4_t uzp1, uzp2; - _v128_unzip(a.val, b.val, uzp1, uzp2); - int32x2_t a0 = vget_low_s32(uzp1); - int32x2_t b0 = vget_high_s32(uzp1); - int32x2_t a1 = vget_low_s32(uzp2); - int32x2_t b1 = vget_high_s32(uzp2); - int64x2_t p = vmlal_s32(c.val, a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -} - -// 8 >> 32 -#ifdef CV_NEON_DOT -#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(_Tpvec1, _Tpvec2, suffix) \ -inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b) \ -{ \ - return _Tpvec1(vdotq_##suffix(vdupq_n_##suffix(0), a.val, b.val));\ -} \ -inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ -{ \ - return _Tpvec1(vdotq_##suffix(c.val, a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_uint32x4, v_uint8x16, u32) -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_int32x4, v_int8x16, s32) -#else -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - const uint8x16_t zero = vreinterpretq_u8_u32(vdupq_n_u32(0)); - const uint8x16_t mask = vreinterpretq_u8_u32(vdupq_n_u32(0x00FF00FF)); - const uint16x8_t zero32 = vreinterpretq_u16_u32(vdupq_n_u32(0)); - const uint16x8_t mask32 = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); - - uint16x8_t even = vmulq_u16(vreinterpretq_u16_u8(vbslq_u8(mask, a.val, zero)), - vreinterpretq_u16_u8(vbslq_u8(mask, b.val, zero))); - uint16x8_t odd = vmulq_u16(vshrq_n_u16(vreinterpretq_u16_u8(a.val), 8), - vshrq_n_u16(vreinterpretq_u16_u8(b.val), 8)); - - uint32x4_t s0 = vaddq_u32(vreinterpretq_u32_u16(vbslq_u16(mask32, even, zero32)), - vreinterpretq_u32_u16(vbslq_u16(mask32, odd, zero32))); - uint32x4_t s1 = vaddq_u32(vshrq_n_u32(vreinterpretq_u32_u16(even), 16), - vshrq_n_u32(vreinterpretq_u32_u16(odd), 16)); - return v_uint32x4(vaddq_u32(s0, s1)); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, - const v_uint32x4& c) -{ - return v_add(v_dotprod_expand(a, b), c); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - int16x8_t p0 = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); - int16x8_t p1 = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); - int16x8_t uzp1, uzp2; - _v128_unzip(p0, p1, uzp1, uzp2); - int16x8_t sum = vaddq_s16(uzp1, uzp2); - int16x4_t uzpl1, uzpl2; - _v128_unzip(vget_low_s16(sum), vget_high_s16(sum), uzpl1, uzpl2); - return v_int32x4(vaddl_s16(uzpl1, uzpl2)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, - const v_int32x4& c) -{ - return v_add(v_dotprod_expand(a, b), c); -} -#endif -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - const uint16x8_t zero = vreinterpretq_u16_u32(vdupq_n_u32(0)); - const uint16x8_t mask = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); - - uint32x4_t even = vmulq_u32(vreinterpretq_u32_u16(vbslq_u16(mask, a.val, zero)), - vreinterpretq_u32_u16(vbslq_u16(mask, b.val, zero))); - uint32x4_t odd = vmulq_u32(vshrq_n_u32(vreinterpretq_u32_u16(a.val), 16), - vshrq_n_u32(vreinterpretq_u32_u16(b.val), 16)); - uint32x4_t uzp1, uzp2; - _v128_unzip(even, odd, uzp1, uzp2); - uint64x2_t s0 = vaddl_u32(vget_low_u32(uzp1), vget_high_u32(uzp1)); - uint64x2_t s1 = vaddl_u32(vget_low_u32(uzp2), vget_high_u32(uzp2)); - return v_uint64x2(vaddq_u64(s0, s1)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - int32x4_t p0 = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); - int32x4_t p1 = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); - - int32x4_t uzp1, uzp2; - _v128_unzip(p0, p1, uzp1, uzp2); - int32x4_t sum = vaddq_s32(uzp1, uzp2); - - int32x2_t uzpl1, uzpl2; - _v128_unzip(vget_low_s32(sum), vget_high_s32(sum), uzpl1, uzpl2); - return v_int64x2(vaddl_s32(uzpl1, uzpl2)); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, - const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -#if CV_SIMD128_64F -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, - const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } -#endif - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ -#if CV_NEON_AARCH64 - int32x4_t p = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); - return v_int32x4(vmlal_high_s16(p, a.val, b.val)); -#else - int16x4_t a0 = vget_low_s16(a.val); - int16x4_t a1 = vget_high_s16(a.val); - int16x4_t b0 = vget_low_s16(b.val); - int16x4_t b1 = vget_high_s16(b.val); - int32x4_t p = vmull_s16(a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -#endif -} -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ -#if CV_NEON_AARCH64 - int32x4_t p = vmlal_s16(c.val, vget_low_s16(a.val), vget_low_s16(b.val)); - return v_int32x4(vmlal_high_s16(p, a.val, b.val)); -#else - int16x4_t a0 = vget_low_s16(a.val); - int16x4_t a1 = vget_high_s16(a.val); - int16x4_t b0 = vget_low_s16(b.val); - int16x4_t b1 = vget_high_s16(b.val); - int32x4_t p = vmlal_s16(c.val, a0, b0); - return v_int32x4(vmlal_s16(p, a1, b1)); -#endif -} - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_NEON_AARCH64 - int64x2_t p = vmull_s32(vget_low_s32(a.val), vget_low_s32(b.val)); - return v_int64x2(vmlal_high_s32(p, a.val, b.val)); -#else - int32x2_t a0 = vget_low_s32(a.val); - int32x2_t a1 = vget_high_s32(a.val); - int32x2_t b0 = vget_low_s32(b.val); - int32x2_t b1 = vget_high_s32(b.val); - int64x2_t p = vmull_s32(a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -#endif -} -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ -#if CV_NEON_AARCH64 - int64x2_t p = vmlal_s32(c.val, vget_low_s32(a.val), vget_low_s32(b.val)); - return v_int64x2(vmlal_high_s32(p, a.val, b.val)); -#else - int32x2_t a0 = vget_low_s32(a.val); - int32x2_t a1 = vget_high_s32(a.val); - int32x2_t b0 = vget_low_s32(b.val); - int32x2_t b1 = vget_high_s32(b.val); - int64x2_t p = vmlal_s32(c.val, a0, b0); - return v_int64x2(vmlal_s32(p, a1, b1)); -#endif -} - -// 8 >> 32 -#ifdef CV_NEON_DOT -#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(_Tpvec1, _Tpvec2, suffix) \ -inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b) \ -{ \ - return v_dotprod_expand(a, b); \ -} \ -inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ -{ \ - return v_dotprod_expand(a, b, c); \ -} - -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_uint32x4, v_uint8x16, u32) -OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_int32x4, v_int8x16, s32) -#else -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ - uint16x8_t p0 = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); - uint16x8_t p1 = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); - uint32x4_t s0 = vaddl_u16(vget_low_u16(p0), vget_low_u16(p1)); - uint32x4_t s1 = vaddl_u16(vget_high_u16(p0), vget_high_u16(p1)); - return v_uint32x4(vaddq_u32(s0, s1)); -} -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ - return v_add(v_dotprod_expand_fast(a, b), c); -} - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ - int16x8_t prod = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); - prod = vmlal_s8(prod, vget_high_s8(a.val), vget_high_s8(b.val)); - return v_int32x4(vaddl_s16(vget_low_s16(prod), vget_high_s16(prod))); -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ - return v_add(v_dotprod_expand_fast(a, b), c); -} -#endif - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - uint32x4_t p0 = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); - uint32x4_t p1 = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); - uint64x2_t s0 = vaddl_u32(vget_low_u32(p0), vget_high_u32(p0)); - uint64x2_t s1 = vaddl_u32(vget_low_u32(p1), vget_high_u32(p1)); - return v_uint64x2(vaddq_u64(s0, s1)); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - int32x4_t prod = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); - prod = vmlal_s16(prod, vget_high_s16(a.val), vget_high_s16(b.val)); - return v_int64x2(vaddl_s32(vget_low_s32(prod), vget_high_s32(prod))); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -#if CV_SIMD128_64F -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod_fast(a, b)); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } -#endif - - -#define OPENCV_HAL_IMPL_NEON_LOGIC_OP(_Tpvec, suffix) \ - OPENCV_HAL_IMPL_NEON_BIN_OP(v_and, _Tpvec, vandq_##suffix) \ - OPENCV_HAL_IMPL_NEON_BIN_OP(v_or, _Tpvec, vorrq_##suffix) \ - OPENCV_HAL_IMPL_NEON_BIN_OP(v_xor, _Tpvec, veorq_##suffix) \ - inline _Tpvec v_not (const _Tpvec& a) \ - { \ - return _Tpvec(vreinterpretq_##suffix##_u8(vmvnq_u8(vreinterpretq_u8_##suffix(a.val)))); \ - } - -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint8x16, u8) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int8x16, s8) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint16x8, u16) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int16x8, s16) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint32x4, u32) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int32x4, s32) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint64x2, u64) -OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int64x2, s64) - -#define OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(bin_op, intrin) \ -inline v_float32x4 bin_op (const v_float32x4& a, const v_float32x4& b) \ -{ \ - return v_float32x4(vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val)))); \ -} - -OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_and, vandq_s32) -OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_or, vorrq_s32) -OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_xor, veorq_s32) - -inline v_float32x4 v_not (const v_float32x4& a) -{ - return v_float32x4(vreinterpretq_f32_s32(vmvnq_s32(vreinterpretq_s32_f32(a.val)))); -} - -#if CV_SIMD128_64F -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - return v_float32x4(vsqrtq_f32(x.val)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - v_float32x4 one = v_setall_f32(1.0f); - return v_div(one, v_sqrt(x)); -} -#else -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - float32x4_t x1 = vmaxq_f32(x.val, vdupq_n_f32(FLT_MIN)); - float32x4_t e = vrsqrteq_f32(x1); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); - return v_float32x4(vmulq_f32(x.val, e)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - float32x4_t e = vrsqrteq_f32(x.val); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); - return v_float32x4(e); -} -#endif - -#define OPENCV_HAL_IMPL_NEON_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ -inline _Tpuvec v_abs(const _Tpsvec& a) { return v_reinterpret_as_##usuffix(_Tpsvec(vabsq_##ssuffix(a.val))); } - -OPENCV_HAL_IMPL_NEON_ABS(v_uint8x16, v_int8x16, u8, s8) -OPENCV_HAL_IMPL_NEON_ABS(v_uint16x8, v_int16x8, u16, s16) -OPENCV_HAL_IMPL_NEON_ABS(v_uint32x4, v_int32x4, u32, s32) - -inline v_float32x4 v_abs(v_float32x4 x) -{ return v_float32x4(vabsq_f32(x.val)); } - -#if CV_SIMD128_64F -#define OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(bin_op, intrin) \ -inline v_float64x2 bin_op (const v_float64x2& a, const v_float64x2& b) \ -{ \ - return v_float64x2(vreinterpretq_f64_s64(intrin(vreinterpretq_s64_f64(a.val), vreinterpretq_s64_f64(b.val)))); \ -} - -OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_and, vandq_s64) -OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_or, vorrq_s64) -OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_xor, veorq_s64) - -inline v_float64x2 v_not (const v_float64x2& a) -{ - return v_float64x2(vreinterpretq_f64_s32(vmvnq_s32(vreinterpretq_s32_f64(a.val)))); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ - return v_float64x2(vsqrtq_f64(x.val)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - v_float64x2 one = v_setall_f64(1.0f); - return v_div(one, v_sqrt(x)); -} - -inline v_float64x2 v_abs(v_float64x2 x) -{ return v_float64x2(vabsq_f64(x.val)); } -#endif - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_NEON_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_min, vminq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_max, vmaxq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_min, vminq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_max, vmaxq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_min, vminq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_max, vmaxq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_min, vminq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_max, vmaxq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_min, vminq_u32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_max, vmaxq_u32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_min, vminq_s32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_max, vmaxq_s32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_min, vminq_f32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_max, vmaxq_f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_min, vminq_f64) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_max, vmaxq_f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_INT_CMP_OP(_Tpvec, cast, suffix, not_suffix) \ -inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vceqq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vmvnq_##not_suffix(vceqq_##suffix(a.val, b.val)))); } \ -inline _Tpvec v_lt (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcltq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_gt (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcgtq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_le (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcleq_##suffix(a.val, b.val))); } \ -inline _Tpvec v_ge (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(cast(vcgeq_##suffix(a.val, b.val))); } - -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint8x16, OPENCV_HAL_NOP, u8, u8) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int8x16, vreinterpretq_s8_u8, s8, u8) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint16x8, OPENCV_HAL_NOP, u16, u16) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int16x8, vreinterpretq_s16_u16, s16, u16) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint32x4, OPENCV_HAL_NOP, u32, u32) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int32x4, vreinterpretq_s32_u32, s32, u32) -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float32x4, vreinterpretq_f32_u32, f32, u32) -#if defined(__aarch64__) || defined(_M_ARM64) -static inline uint64x2_t vmvnq_u64(uint64x2_t a) -{ - uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); - return veorq_u64(a, vx); -} -//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint64x2, OPENCV_HAL_NOP, u64, u64) -//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int64x2, vreinterpretq_s64_u64, s64, u64) -static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint64x2(vceqq_u64(a.val, b.val)); } -static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) -{ return v_uint64x2(vmvnq_u64(vceqq_u64(a.val, b.val))); } -static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) -{ return v_int64x2(vreinterpretq_s64_u64(vceqq_s64(a.val, b.val))); } -static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) -{ return v_int64x2(vreinterpretq_s64_u64(vmvnq_u64(vceqq_s64(a.val, b.val)))); } -#else -static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) -{ - uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); - uint32x4_t swapped = vrev64q_u32(cmp); - return v_uint64x2(vreinterpretq_u64_u32(vandq_u32(cmp, swapped))); -} -static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) -{ - uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); - uint32x4_t swapped = vrev64q_u32(cmp); - uint64x2_t v_eq = vreinterpretq_u64_u32(vandq_u32(cmp, swapped)); - uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); - return v_uint64x2(veorq_u64(v_eq, vx)); -} -static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) -{ - return v_reinterpret_as_s64(v_eq(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); -} -static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) -{ - return v_reinterpret_as_s64(v_ne(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); -} -#endif -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float64x2, vreinterpretq_f64_u64, f64, u64) -#endif - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(vreinterpretq_f32_u32(vceqq_f32(a.val, a.val))); } -#if CV_SIMD128_64F -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(vreinterpretq_f64_u64(vceqq_f64(a.val, a.val))); } -#endif - -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_add_wrap, vaddq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_add_wrap, vaddq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_add_wrap, vaddq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_add_wrap, vaddq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_sub_wrap, vsubq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_sub_wrap, vsubq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_sub_wrap, vsubq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_sub_wrap, vsubq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_mul_wrap, vmulq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_mul_wrap, vmulq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_mul_wrap, vmulq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_mul_wrap, vmulq_s16) - -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_absdiff, vabdq_u8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_absdiff, vabdq_u16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_absdiff, vabdq_u32) -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_absdiff, vabdq_f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_absdiff, vabdq_f64) -#endif - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ return v_int8x16(vqabsq_s8(vqsubq_s8(a.val, b.val))); } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_int16x8(vqabsq_s16(vqsubq_s16(a.val, b.val))); } - -#define OPENCV_HAL_IMPL_NEON_BIN_FUNC2(_Tpvec, _Tpvec2, cast, func, intrin) \ -inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec2(cast(intrin(a.val, b.val))); \ -} - -OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int8x16, v_uint8x16, vreinterpretq_u8_s8, v_absdiff, vabdq_s8) -OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int16x8, v_uint16x8, vreinterpretq_u16_s16, v_absdiff, vabdq_s16) -OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int32x4, v_uint32x4, vreinterpretq_u32_s32, v_absdiff, vabdq_s32) - -inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 x(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); - return v_sqrt(x); -} - -inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ -#if CV_SIMD128_64F - // ARMv8, which adds support for 64-bit floating-point (so CV_SIMD128_64F is defined), - // also adds FMA support both for single- and double-precision floating-point vectors - return v_float32x4(vfmaq_f32(c.val, a.val, b.val)); -#else - return v_float32x4(vmlaq_f32(c.val, a.val, b.val)); -#endif -} - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_int32x4(vmlaq_s32(c.val, a.val, b.val)); -} - -inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -#if CV_SIMD128_64F -inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - v_float64x2 x(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); - return v_sqrt(x); -} - -inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_float64x2(vfmaq_f64(c.val, a.val, b.val)); -} - -inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_fma(a, b, c); -} -#endif - -// trade efficiency for convenience -#define OPENCV_HAL_IMPL_NEON_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ -inline _Tpvec v_shl (const _Tpvec& a, int n) \ -{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)n))); } \ -inline _Tpvec v_shr (const _Tpvec& a, int n) \ -{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)-n))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec(vshlq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec(vshrq_n_##suffix(a.val, n)); } \ -template inline _Tpvec v_rshr(const _Tpvec& a) \ -{ return _Tpvec(vrshrq_n_##suffix(a.val, n)); } - -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint8x16, u8, schar, s8) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int8x16, s8, schar, s8) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint16x8, u16, short, s16) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int16x8, s16, short, s16) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint32x4, u32, int, s32) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int32x4, s32, int, s32) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint64x2, u64, int64, s64) -OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int64x2, s64, int64, s64) - -#define OPENCV_HAL_IMPL_NEON_ROTATE_OP(_Tpvec, suffix) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ return _Tpvec(vextq_##suffix(a.val, vdupq_n_##suffix(0), n)); } \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ return _Tpvec(vextq_##suffix(vdupq_n_##suffix(0), a.val, VTraits<_Tpvec>::nlanes - n)); } \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vextq_##suffix(a.val, b.val, n)); } \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vextq_##suffix(b.val, a.val, VTraits<_Tpvec>::nlanes - n)); } \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ CV_UNUSED(b); return a; } - -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint8x16, u8) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int8x16, s8) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint16x8, u16) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int16x8, s16) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint32x4, u32) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int32x4, s32) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float32x4, f32) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint64x2, u64) -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int64x2, s64) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float64x2, f64) -#endif - -#if defined(__clang__) && defined(__aarch64__) -// avoid LD2 instruction. details: https://github.com/opencv/opencv/issues/14863 -#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ \ -typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; \ -uint64 v = *(unaligned_uint64*)ptr; \ -return _Tpvec(v_reinterpret_as_##suffix(v_uint64x2(v, (uint64)123456))); \ -} -#else -#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr), vdup_n_##suffix((_Tp)0))); } -#endif - -#define OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(vld1q_##suffix(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vld1q_##suffix(ptr)); } \ -OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr0), vld1_##suffix(ptr1))); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vst1q_##suffix(ptr, a.val); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vst1_##suffix(ptr, vget_low_##suffix(a.val)); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ vst1_##suffix(ptr, vget_high_##suffix(a.val)); } - -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float64x2, double, f64) -#endif - -inline unsigned v_reduce_sum(const v_uint8x16& a) -{ -#if CV_NEON_AARCH64 - uint16_t t0 = vaddlvq_u8(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(a.val)); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline int v_reduce_sum(const v_int8x16& a) -{ -#if CV_NEON_AARCH64 - int16_t t0 = vaddlvq_s8(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - int32x4_t t0 = vpaddlq_s16(vpaddlq_s8(a.val)); - int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); - return vget_lane_s32(vpadd_s32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sum(const v_uint16x8& a) -{ -#if CV_NEON_AARCH64 - uint32_t t0 = vaddlvq_u16(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(a.val); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline int v_reduce_sum(const v_int16x8& a) -{ -#if CV_NEON_AARCH64 - int32_t t0 = vaddlvq_s16(a.val); - return t0; -#else // #if CV_NEON_AARCH64 - int32x4_t t0 = vpaddlq_s16(a.val); - int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); - return vget_lane_s32(vpadd_s32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return v##vectorfunc##vq_##suffix(a.val); \ -} -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ - a0 = vp##vectorfunc##_##suffix(a0, a0); \ - a0 = vp##vectorfunc##_##suffix(a0, a0); \ - return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ -} -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, max, max, u8) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, min, min, u8) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, max, max, s8) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, min, min, s8) - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return v##vectorfunc##vq_##suffix(a.val); \ -} -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ - a0 = vp##vectorfunc##_##suffix(a0, a0); \ - return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ -} -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, max, max, u16) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, min, min, u16) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, max, max, s16) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, min, min, s16) - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - return v##vectorfunc##vq_##suffix(a.val); \ -} -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ - return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, vget_high_##suffix(a.val)),0); \ -} -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, sum, add, u32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, max, max, u32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, min, min, u32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, sum, add, s32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, max, max, s32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, min, min, s32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, sum, add, f32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, max, max, f32) -OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, min, min, f32) - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ -#if CV_NEON_AARCH64 - return vaddvq_u64(a.val); -#else // #if CV_NEON_AARCH64 - return vget_lane_u64(vadd_u64(vget_low_u64(a.val), vget_high_u64(a.val)),0); -#endif // #if CV_NEON_AARCH64 -} -inline int64 v_reduce_sum(const v_int64x2& a) -{ -#if CV_NEON_AARCH64 - return vaddvq_s64(a.val); -#else // #if CV_NEON_AARCH64 - return vget_lane_s64(vadd_s64(vget_low_s64(a.val), vget_high_s64(a.val)),0); -#endif // #if CV_NEON_AARCH64 -} -#if CV_SIMD128_64F -inline double v_reduce_sum(const v_float64x2& a) -{ - return vaddvq_f64(a.val); -} -#endif - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ -#if CV_NEON_AARCH64 - float32x4_t ab = vpaddq_f32(a.val, b.val); // a0+a1 a2+a3 b0+b1 b2+b3 - float32x4_t cd = vpaddq_f32(c.val, d.val); // c0+c1 d0+d1 c2+c3 d2+d3 - return v_float32x4(vpaddq_f32(ab, cd)); // sumA sumB sumC sumD -#else // #if CV_NEON_AARCH64 - float32x4x2_t ab = vtrnq_f32(a.val, b.val); - float32x4x2_t cd = vtrnq_f32(c.val, d.val); - - float32x4_t u0 = vaddq_f32(ab.val[0], ab.val[1]); // a0+a1 b0+b1 a2+a3 b2+b3 - float32x4_t u1 = vaddq_f32(cd.val[0], cd.val[1]); // c0+c1 d0+d1 c2+c3 d2+d3 - - float32x4_t v0 = vcombine_f32(vget_low_f32(u0), vget_low_f32(u1)); - float32x4_t v1 = vcombine_f32(vget_high_f32(u0), vget_high_f32(u1)); - - return v_float32x4(vaddq_f32(v0, v1)); -#endif // #if CV_NEON_AARCH64 -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ -#if CV_NEON_AARCH64 - uint8x16_t t0 = vabdq_u8(a.val, b.val); - uint16_t t1 = vaddlvq_u8(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vabdq_u8(a.val, b.val))); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_NEON_AARCH64 - uint8x16_t t0 = vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)); - uint16_t t1 = vaddlvq_u8(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)))); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_NEON_AARCH64 - uint16x8_t t0 = vabdq_u16(a.val, b.val); - uint32_t t1 = vaddlvq_u16(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vabdq_u16(a.val, b.val)); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ -#if CV_NEON_AARCH64 - uint16x8_t t0 = vreinterpretq_u16_s16(vabdq_s16(a.val, b.val)); - uint32_t t1 = vaddlvq_u16(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vpaddlq_u16(vreinterpretq_u16_s16(vabdq_s16(a.val, b.val))); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ -#if CV_NEON_AARCH64 - uint32x4_t t0 = vabdq_u32(a.val, b.val); - uint32_t t1 = vaddvq_u32(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vabdq_u32(a.val, b.val); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_NEON_AARCH64 - uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); - uint32_t t1 = vaddvq_u32(t0); - return t1; -#else // #if CV_NEON_AARCH64 - uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); - uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); - return vget_lane_u32(vpadd_u32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ -#if CV_NEON_AARCH64 - float32x4_t t0 = vabdq_f32(a.val, b.val); - return vaddvq_f32(t0); -#else // #if CV_NEON_AARCH64 - float32x4_t t0 = vabdq_f32(a.val, b.val); - float32x2_t t1 = vpadd_f32(vget_low_f32(t0), vget_high_f32(t0)); - return vget_lane_f32(vpadd_f32(t1, t1), 0); -#endif // #if CV_NEON_AARCH64 -} - -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ return v_uint8x16(vcntq_u8(a.val)); } -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_uint8x16(vcntq_u8(vreinterpretq_u8_s8(a.val))); } -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u16(a.val)))); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s16(a.val)))); } -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u32(a.val))))); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s32(a.val))))); } -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u64(a.val)))))); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s64(a.val)))))); } - -inline int v_signmask(const v_uint8x16& a) -{ -#if CV_NEON_AARCH64 - const int8x16_t signPosition = {0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7}; - const uint8x16_t byteOrder = {0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15}; - uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), signPosition); - uint8x16_t v1 = vqtbl1q_u8(v0, byteOrder); - uint32_t t0 = vaddlvq_u16(vreinterpretq_u16_u8(v1)); - return t0; -#else // #if CV_NEON_AARCH64 - int8x8_t m0 = vcreate_s8(CV_BIG_UINT(0x0706050403020100)); - uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), vcombine_s8(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0))); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8); -#endif // #if CV_NEON_AARCH64 -} - -inline int v_signmask(const v_int8x16& a) -{ return v_signmask(v_reinterpret_as_u8(a)); } - -inline int v_signmask(const v_uint16x8& a) -{ -#if CV_NEON_AARCH64 - const int16x8_t signPosition = {0,1,2,3,4,5,6,7}; - uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), signPosition); - uint32_t t0 = vaddlvq_u16(v0); - return t0; -#else // #if CV_NEON_AARCH64 - int16x4_t m0 = vcreate_s16(CV_BIG_UINT(0x0003000200010000)); - uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), vcombine_s16(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(v0)); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 4); -#endif // #if CV_NEON_AARCH64 -} -inline int v_signmask(const v_int16x8& a) -{ return v_signmask(v_reinterpret_as_u16(a)); } - -inline int v_signmask(const v_uint32x4& a) -{ -#if CV_NEON_AARCH64 - const int32x4_t signPosition = {0,1,2,3}; - uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), signPosition); - uint32_t t0 = vaddvq_u32(v0); - return t0; -#else // #if CV_NEON_AARCH64 - int32x2_t m0 = vcreate_s32(CV_BIG_UINT(0x0000000100000000)); - uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), vcombine_s32(m0, m0)); - uint64x2_t v1 = vpaddlq_u32(v0); - return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 2); -#endif // #if CV_NEON_AARCH64 -} -inline int v_signmask(const v_int32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(v_reinterpret_as_u32(a)); } -inline int v_signmask(const v_uint64x2& a) -{ -#if CV_NEON_AARCH64 - const int64x2_t signPosition = {0,1}; - uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), signPosition); - int t0 = (int)vaddvq_u64(v0); - return t0; -#else // #if CV_NEON_AARCH64 - int64x1_t m0 = vdup_n_s64(0); - uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), vcombine_s64(m0, m0)); - return (int)vgetq_lane_u64(v0, 0) + ((int)vgetq_lane_u64(v0, 1) << 1); -#endif // #if CV_NEON_AARCH64 -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -#if CV_SIMD128_64F -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -#endif - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } -#if CV_SIMD128_64F -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } -#endif - -#if CV_NEON_AARCH64 - #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ - inline bool v_check_all(const v_##_Tpvec& a) \ - { \ - return (vminvq_##suffix(a.val) >> shift) != 0; \ - } \ - inline bool v_check_any(const v_##_Tpvec& a) \ - { \ - return (vmaxvq_##suffix(a.val) >> shift) != 0; \ - } -#else // #if CV_NEON_AARCH64 - #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ - inline bool v_check_all(const v_##_Tpvec& a) \ - { \ - _Tpvec##_t v0 = vshrq_n_##suffix(vmvnq_##suffix(a.val), shift); \ - uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ - return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) == 0; \ - } \ - inline bool v_check_any(const v_##_Tpvec& a) \ - { \ - _Tpvec##_t v0 = vshrq_n_##suffix(a.val, shift); \ - uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ - return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) != 0; \ - } -#endif // #if CV_NEON_AARCH64 - -OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint8x16, u8, 7) -OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint16x8, u16, 15) -OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint32x4, u32, 31) - -inline bool v_check_all(const v_uint64x2& a) -{ - uint64x2_t v0 = vshrq_n_u64(a.val, 63); - return (vgetq_lane_u64(v0, 0) & vgetq_lane_u64(v0, 1)) == 1; -} -inline bool v_check_any(const v_uint64x2& a) -{ - uint64x2_t v0 = vshrq_n_u64(a.val, 63); - return (vgetq_lane_u64(v0, 0) | vgetq_lane_u64(v0, 1)) != 0; -} - -inline bool v_check_all(const v_int8x16& a) -{ return v_check_all(v_reinterpret_as_u8(a)); } -inline bool v_check_all(const v_int16x8& a) -{ return v_check_all(v_reinterpret_as_u16(a)); } -inline bool v_check_all(const v_int32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } - -inline bool v_check_any(const v_int8x16& a) -{ return v_check_any(v_reinterpret_as_u8(a)); } -inline bool v_check_any(const v_int16x8& a) -{ return v_check_any(v_reinterpret_as_u16(a)); } -inline bool v_check_any(const v_int32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } - -inline bool v_check_all(const v_int64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_int64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -#if CV_SIMD128_64F -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -#endif - -#define OPENCV_HAL_IMPL_NEON_SELECT(_Tpvec, suffix, usuffix) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(vbslq_##suffix(vreinterpretq_##usuffix##_##suffix(mask.val), a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_NEON_SELECT(v_uint8x16, u8, u8) -OPENCV_HAL_IMPL_NEON_SELECT(v_int8x16, s8, u8) -OPENCV_HAL_IMPL_NEON_SELECT(v_uint16x8, u16, u16) -OPENCV_HAL_IMPL_NEON_SELECT(v_int16x8, s16, u16) -OPENCV_HAL_IMPL_NEON_SELECT(v_uint32x4, u32, u32) -OPENCV_HAL_IMPL_NEON_SELECT(v_int32x4, s32, u32) -OPENCV_HAL_IMPL_NEON_SELECT(v_float32x4, f32, u32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_SELECT(v_float64x2, f64, u64) -#endif - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ - b1.val = vmovl_high_##suffix(a.val); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_high_##suffix(a.val)); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ -} -#else -#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ - b1.val = vmovl_##suffix(vget_high_##suffix(a.val)); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - return _Tpwvec(vmovl_##suffix(vget_high_##suffix(a.val))); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ -} -#endif - -OPENCV_HAL_IMPL_NEON_EXPAND(v_uint8x16, v_uint16x8, uchar, u8) -OPENCV_HAL_IMPL_NEON_EXPAND(v_int8x16, v_int16x8, schar, s8) -OPENCV_HAL_IMPL_NEON_EXPAND(v_uint16x8, v_uint32x4, ushort, u16) -OPENCV_HAL_IMPL_NEON_EXPAND(v_int16x8, v_int32x4, short, s16) -OPENCV_HAL_IMPL_NEON_EXPAND(v_uint32x4, v_uint64x2, uint, u32) -OPENCV_HAL_IMPL_NEON_EXPAND(v_int32x4, v_int64x2, int, s32) - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; - uint8x8_t v0 = vcreate_u8(*(unaligned_uint*)ptr); - uint16x4_t v1 = vget_low_u16(vmovl_u8(v0)); - return v_uint32x4(vmovl_u16(v1)); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; - int8x8_t v0 = vcreate_s8(*(unaligned_uint*)ptr); - int16x4_t v1 = vget_low_s16(vmovl_s8(v0)); - return v_int32x4(vmovl_s16(v1)); -} - -#if defined(__aarch64__) || defined(_M_ARM64) -#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ -inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ -{ \ - b0.val = vzip1q_##suffix(a0.val, a1.val); \ - b1.val = vzip2q_##suffix(a0.val, a1.val); \ -} \ -inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ -} \ -inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ -} \ -inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ - d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ -} -#else -#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ -inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ -{ \ - _Tpvec##x2_t p = vzipq_##suffix(a0.val, a1.val); \ - b0.val = p.val[0]; \ - b1.val = p.val[1]; \ -} \ -inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ -} \ -inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ -} \ -inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ - d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ -} -#endif - -OPENCV_HAL_IMPL_NEON_UNPACKS(uint8x16, u8) -OPENCV_HAL_IMPL_NEON_UNPACKS(int8x16, s8) -OPENCV_HAL_IMPL_NEON_UNPACKS(uint16x8, u16) -OPENCV_HAL_IMPL_NEON_UNPACKS(int16x8, s16) -OPENCV_HAL_IMPL_NEON_UNPACKS(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_UNPACKS(int32x4, s32) -OPENCV_HAL_IMPL_NEON_UNPACKS(float32x4, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_UNPACKS(float64x2, f64) -#endif - -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - uint8x16_t vec = vrev64q_u8(a.val); - return v_uint8x16(vextq_u8(vec, vec, 8)); -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - uint16x8_t vec = vrev64q_u16(a.val); - return v_uint16x8(vextq_u16(vec, vec, 4)); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - uint32x4_t vec = vrev64q_u32(a.val); - return v_uint32x4(vextq_u32(vec, vec, 2)); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - uint64x2_t vec = a.val; - uint64x1_t vec_lo = vget_low_u64(vec); - uint64x1_t vec_hi = vget_high_u64(vec); - return v_uint64x2(vcombine_u64(vec_hi, vec_lo)); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -#if CV_SIMD128_64F -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } -#endif - -#define OPENCV_HAL_IMPL_NEON_EXTRACT(_Tpvec, suffix) \ -template \ -inline v_##_Tpvec v_extract(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - return v_##_Tpvec(vextq_##suffix(a.val, b.val, s)); \ -} - -OPENCV_HAL_IMPL_NEON_EXTRACT(uint8x16, u8) -OPENCV_HAL_IMPL_NEON_EXTRACT(int8x16, s8) -OPENCV_HAL_IMPL_NEON_EXTRACT(uint16x8, u16) -OPENCV_HAL_IMPL_NEON_EXTRACT(int16x8, s16) -OPENCV_HAL_IMPL_NEON_EXTRACT(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_EXTRACT(int32x4, s32) -OPENCV_HAL_IMPL_NEON_EXTRACT(uint64x2, u64) -OPENCV_HAL_IMPL_NEON_EXTRACT(int64x2, s64) -OPENCV_HAL_IMPL_NEON_EXTRACT(float32x4, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_EXTRACT(float64x2, f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_EXTRACT_N(_Tpvec, _Tp, suffix) \ -template inline _Tp v_extract_n(_Tpvec v) { return vgetq_lane_##suffix(v.val, i); } - -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint32x4, uint, u32) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float64x2, double, f64) -#endif - -#define OPENCV_HAL_IMPL_NEON_BROADCAST(_Tpvec, _Tp, suffix) \ -template inline _Tpvec v_broadcast_element(_Tpvec v) { _Tp t = v_extract_n(v); return v_setall_##suffix(t); } - -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint32x4, uint, u32) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_int64x2, int64, s64) -OPENCV_HAL_IMPL_NEON_BROADCAST(v_float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_BROADCAST(v_float64x2, double, f64) -#endif - -#if CV_SIMD128_64F -inline v_int32x4 v_round(const v_float32x4& a) -{ - float32x4_t a_ = a.val; - int32x4_t result; -#if defined _MSC_VER - result = vcvtnq_s32_f32(a_); -#else - __asm__ ("fcvtns %0.4s, %1.4s" - : "=w"(result) - : "w"(a_) - : /* No clobbers */); -#endif - return v_int32x4(result); -} -#else -inline v_int32x4 v_round(const v_float32x4& a) -{ - // See https://github.com/opencv/opencv/pull/24271#issuecomment-1867318007 - float32x4_t delta = vdupq_n_f32(12582912.0f); - return v_int32x4(vcvtq_s32_f32(vsubq_f32(vaddq_f32(a.val, delta), delta))); -} -#endif -inline v_int32x4 v_floor(const v_float32x4& a) -{ - int32x4_t a1 = vcvtq_s32_f32(a.val); - uint32x4_t mask = vcgtq_f32(vcvtq_f32_s32(a1), a.val); - return v_int32x4(vaddq_s32(a1, vreinterpretq_s32_u32(mask))); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - int32x4_t a1 = vcvtq_s32_f32(a.val); - uint32x4_t mask = vcgtq_f32(a.val, vcvtq_f32_s32(a1)); - return v_int32x4(vsubq_s32(a1, vreinterpretq_s32_u32(mask))); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(vcvtq_s32_f32(a.val)); } - -#if CV_SIMD128_64F -inline v_int32x4 v_round(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), zero)); -} - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), vmovn_s64(vcvtnq_s64_f64(b.val)))); -} - -inline v_int32x4 v_floor(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - int64x2_t a1 = vcvtq_s64_f64(a.val); - uint64x2_t mask = vcgtq_f64(vcvtq_f64_s64(a1), a.val); - a1 = vaddq_s64(a1, vreinterpretq_s64_u64(mask)); - return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - int64x2_t a1 = vcvtq_s64_f64(a.val); - uint64x2_t mask = vcgtq_f64(a.val, vcvtq_f64_s64(a1)); - a1 = vsubq_s64(a1, vreinterpretq_s64_u64(mask)); - return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ - static const int32x2_t zero = vdup_n_s32(0); - return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), zero)); -} -#endif - -#if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ - const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ - v_##_Tpvec& b0, v_##_Tpvec& b1, \ - v_##_Tpvec& b2, v_##_Tpvec& b3) \ -{ \ - /* -- Pass 1: 64b transpose */ \ - _Tpvec##_t t0 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ - vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ - _Tpvec##_t t1 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ - vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ - _Tpvec##_t t2 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ - vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ - _Tpvec##_t t3 = vreinterpretq_##suffix##32_##suffix##64( \ - vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ - vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ - /* -- Pass 2: 32b transpose */ \ - b0.val = vtrn1q_##suffix##32(t0, t1); \ - b1.val = vtrn2q_##suffix##32(t0, t1); \ - b2.val = vtrn1q_##suffix##32(t2, t3); \ - b3.val = vtrn2q_##suffix##32(t2, t3); \ -} - -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f) -#else // #if CV_NEON_AARCH64 -#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ - const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ - v_##_Tpvec& b0, v_##_Tpvec& b1, \ - v_##_Tpvec& b2, v_##_Tpvec& b3) \ -{ \ - /* m00 m01 m02 m03 */ \ - /* m10 m11 m12 m13 */ \ - /* m20 m21 m22 m23 */ \ - /* m30 m31 m32 m33 */ \ - _Tpvec##x2_t t0 = vtrnq_##suffix(a0.val, a1.val); \ - _Tpvec##x2_t t1 = vtrnq_##suffix(a2.val, a3.val); \ - /* m00 m10 m02 m12 */ \ - /* m01 m11 m03 m13 */ \ - /* m20 m30 m22 m32 */ \ - /* m21 m31 m23 m33 */ \ - b0.val = vcombine_##suffix(vget_low_##suffix(t0.val[0]), vget_low_##suffix(t1.val[0])); \ - b1.val = vcombine_##suffix(vget_low_##suffix(t0.val[1]), vget_low_##suffix(t1.val[1])); \ - b2.val = vcombine_##suffix(vget_high_##suffix(t0.val[0]), vget_high_##suffix(t1.val[0])); \ - b3.val = vcombine_##suffix(vget_high_##suffix(t0.val[1]), vget_high_##suffix(t1.val[1])); \ -} - -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u32) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s32) -OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f32) -#endif // #if CV_NEON_AARCH64 - -#define OPENCV_HAL_IMPL_NEON_INTERLEAVED(_Tpvec, _Tp, suffix) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ -{ \ - _Tpvec##x2_t v = vld2q_##suffix(ptr); \ - a.val = v.val[0]; \ - b.val = v.val[1]; \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ -{ \ - _Tpvec##x3_t v = vld3q_##suffix(ptr); \ - a.val = v.val[0]; \ - b.val = v.val[1]; \ - c.val = v.val[2]; \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ - v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - _Tpvec##x4_t v = vld4q_##suffix(ptr); \ - a.val = v.val[0]; \ - b.val = v.val[1]; \ - c.val = v.val[2]; \ - d.val = v.val[3]; \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec##x2_t v; \ - v.val[0] = a.val; \ - v.val[1] = b.val; \ - vst2q_##suffix(ptr, v); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - _Tpvec##x3_t v; \ - v.val[0] = a.val; \ - v.val[1] = b.val; \ - v.val[2] = c.val; \ - vst3q_##suffix(ptr, v); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, const v_##_Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec##x4_t v; \ - v.val[0] = a.val; \ - v.val[1] = b.val; \ - v.val[2] = c.val; \ - v.val[3] = d.val; \ - vst4q_##suffix(ptr, v); \ -} - -#define OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(tp, suffix) \ -inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b ) \ -{ \ - tp##x1_t a0 = vld1_##suffix(ptr); \ - tp##x1_t b0 = vld1_##suffix(ptr + 1); \ - tp##x1_t a1 = vld1_##suffix(ptr + 2); \ - tp##x1_t b1 = vld1_##suffix(ptr + 3); \ - a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ - b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ -} \ - \ -inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, \ - v_##tp##x2& b, v_##tp##x2& c ) \ -{ \ - tp##x1_t a0 = vld1_##suffix(ptr); \ - tp##x1_t b0 = vld1_##suffix(ptr + 1); \ - tp##x1_t c0 = vld1_##suffix(ptr + 2); \ - tp##x1_t a1 = vld1_##suffix(ptr + 3); \ - tp##x1_t b1 = vld1_##suffix(ptr + 4); \ - tp##x1_t c1 = vld1_##suffix(ptr + 5); \ - a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ - b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ - c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ -} \ - \ -inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b, \ - v_##tp##x2& c, v_##tp##x2& d ) \ -{ \ - tp##x1_t a0 = vld1_##suffix(ptr); \ - tp##x1_t b0 = vld1_##suffix(ptr + 1); \ - tp##x1_t c0 = vld1_##suffix(ptr + 2); \ - tp##x1_t d0 = vld1_##suffix(ptr + 3); \ - tp##x1_t a1 = vld1_##suffix(ptr + 4); \ - tp##x1_t b1 = vld1_##suffix(ptr + 5); \ - tp##x1_t c1 = vld1_##suffix(ptr + 6); \ - tp##x1_t d1 = vld1_##suffix(ptr + 7); \ - a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ - b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ - c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ - d = v_##tp##x2(vcombine_##suffix(d0, d1)); \ -} \ - \ -inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ - vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ - vst1_##suffix(ptr + 2, vget_high_##suffix(a.val)); \ - vst1_##suffix(ptr + 3, vget_high_##suffix(b.val)); \ -} \ - \ -inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, \ - const v_##tp##x2& b, const v_##tp##x2& c, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ - vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ - vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ - vst1_##suffix(ptr + 3, vget_high_##suffix(a.val)); \ - vst1_##suffix(ptr + 4, vget_high_##suffix(b.val)); \ - vst1_##suffix(ptr + 5, vget_high_##suffix(c.val)); \ -} \ - \ -inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ - const v_##tp##x2& c, const v_##tp##x2& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ - vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ - vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ - vst1_##suffix(ptr + 3, vget_low_##suffix(d.val)); \ - vst1_##suffix(ptr + 4, vget_high_##suffix(a.val)); \ - vst1_##suffix(ptr + 5, vget_high_##suffix(b.val)); \ - vst1_##suffix(ptr + 6, vget_high_##suffix(c.val)); \ - vst1_##suffix(ptr + 7, vget_high_##suffix(d.val)); \ -} - -OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint8x16, uchar, u8) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(int8x16, schar, s8) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint16x8, ushort, u16) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(int16x8, short, s16) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(int32x4, int, s32) -OPENCV_HAL_IMPL_NEON_INTERLEAVED(float32x4, float, f32) -#if CV_SIMD128_64F -OPENCV_HAL_IMPL_NEON_INTERLEAVED(float64x2, double, f64) -#endif - -OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(int64, s64) -OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(uint64, u64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(vcvtq_f32_s32(a.val)); -} - -#if CV_SIMD128_64F -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - float32x2_t zero = vdup_n_f32(0.0f); - return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), zero)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), vcvt_f32_f64(b.val))); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_low_s32(a.val)))); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_high_s32(a.val)))); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vget_low_f32(a.val))); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - return v_float64x2(vcvt_f64_f32(vget_high_f32(a.val))); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ return v_float64x2(vcvtq_f64_s64(a.val)); } - -#endif - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[ 0]], - tab[idx[ 1]], - tab[idx[ 2]], - tab[idx[ 3]], - tab[idx[ 4]], - tab[idx[ 5]], - tab[idx[ 6]], - tab[idx[ 7]], - tab[idx[ 8]], - tab[idx[ 9]], - tab[idx[10]], - tab[idx[11]], - tab[idx[12]], - tab[idx[13]], - tab[idx[14]], - tab[idx[15]] - }; - return v_int8x16(vld1q_s8(elems)); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[4]], - tab[idx[4] + 1], - tab[idx[5]], - tab[idx[5] + 1], - tab[idx[6]], - tab[idx[6] + 1], - tab[idx[7]], - tab[idx[7] + 1] - }; - return v_int8x16(vld1q_s8(elems)); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[2] + 2], - tab[idx[2] + 3], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[3] + 2], - tab[idx[3] + 3] - }; - return v_int8x16(vld1q_s8(elems)); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]], - tab[idx[4]], - tab[idx[5]], - tab[idx[6]], - tab[idx[7]] - }; - return v_int16x8(vld1q_s16(elems)); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1] - }; - return v_int16x8(vld1q_s16(elems)); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(vcombine_s16(vld1_s16(tab + idx[0]), vld1_s16(tab + idx[1]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_int32x4(vld1q_s32(elems)); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(vcombine_s32(vld1_s32(tab + idx[0]), vld1_s32(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(vld1q_s32(tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(vcombine_s64(vcreate_s64(tab[idx[0]]), vcreate_s64(tab[idx[1]]))); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(vld1q_s64(tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_float32x4(vld1q_f32(elems)); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ - typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; - - uint64 CV_DECL_ALIGNED(32) elems[2] = - { - *(unaligned_uint64*)(tab + idx[0]), - *(unaligned_uint64*)(tab + idx[1]) - }; - return v_float32x4(vreinterpretq_f32_u64(vld1q_u64(elems))); -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4(vld1q_f32(tab + idx[0])); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - tab[vgetq_lane_s32(idxvec.val, 2)], - tab[vgetq_lane_s32(idxvec.val, 3)] - }; - return v_int32x4(vld1q_s32(elems)); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - unsigned CV_DECL_ALIGNED(32) elems[4] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - tab[vgetq_lane_s32(idxvec.val, 2)], - tab[vgetq_lane_s32(idxvec.val, 3)] - }; - return v_uint32x4(vld1q_u32(elems)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - tab[vgetq_lane_s32(idxvec.val, 2)], - tab[vgetq_lane_s32(idxvec.val, 3)] - }; - return v_float32x4(vld1q_f32(elems)); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - /*int CV_DECL_ALIGNED(32) idx[4]; - v_store(idx, idxvec); - - float32x4_t xy02 = vcombine_f32(vld1_f32(tab + idx[0]), vld1_f32(tab + idx[2])); - float32x4_t xy13 = vcombine_f32(vld1_f32(tab + idx[1]), vld1_f32(tab + idx[3])); - - float32x4x2_t xxyy = vuzpq_f32(xy02, xy13); - x = v_float32x4(xxyy.val[0]); - y = v_float32x4(xxyy.val[1]);*/ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - x = v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); - y = v_float32x4(tab[idx[0]+1], tab[idx[1]+1], tab[idx[2]+1], tab[idx[3]+1]); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0705060403010200)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0705060403010200)))); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0703060205010400)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0703060205010400)))); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - return v_int16x8(vreinterpretq_s16_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100)), vtbl1_s8(vget_high_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100))))); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - int16x4x2_t res = vzip_s16(vget_low_s16(vec.val), vget_high_s16(vec.val)); - return v_int16x8(vcombine_s16(res.val[0], res.val[1])); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - int32x2x2_t res = vzip_s32(vget_low_s32(vec.val), vget_high_s32(vec.val)); - return v_int32x4(vcombine_s32(res.val[0], res.val[1])); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - return v_int8x16(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0605040201000000)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0807060504020100))), vdupq_n_s8(0), 2)); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - return v_int16x8(vreinterpretq_s16_s8(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0504030201000000)), vget_high_s8(vreinterpretq_s8_s16(vec.val))), vdupq_n_s8(0), 2))); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -#if CV_SIMD128_64F -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - double CV_DECL_ALIGNED(32) elems[2] = - { - tab[idx[0]], - tab[idx[1]] - }; - return v_float64x2(vld1q_f64(elems)); -} - -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(vld1q_f64(tab + idx[0])); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - double CV_DECL_ALIGNED(32) elems[2] = - { - tab[vgetq_lane_s32(idxvec.val, 0)], - tab[vgetq_lane_s32(idxvec.val, 1)], - }; - return v_float64x2(vld1q_f64(elems)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - x = v_float64x2(tab[idx[0]], tab[idx[1]]); - y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); -} -#endif - -////// FP16 support /////// -#if CV_FP16 -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - float16x4_t v = - #ifndef vld1_f16 // APPLE compiler defines vld1_f16 as macro - (float16x4_t)vld1_s16((const short*)ptr); - #else - vld1_f16((const __fp16*)ptr); - #endif - return v_float32x4(vcvt_f32_f16(v)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - float16x4_t hv = vcvt_f16_f32(v.val); - - #ifndef vst1_f16 // APPLE compiler defines vst1_f16 as macro - vst1_s16((short*)ptr, (int16x4_t)hv); - #else - vst1_f16((__fp16*)ptr, hv); - #endif -} -#else -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - const int N = 4; - float buf[N]; - for( int i = 0; i < N; i++ ) buf[i] = (float)ptr[i]; - return v_load(buf); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - const int N = 4; - float buf[N]; - v_store(buf, v); - for( int i = 0; i < N; i++ ) ptr[i] = hfloat(buf[i]); -} -#endif - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -#if defined(CV_SIMD_FP16) && CV_SIMD_FP16 -inline v_float16x8 v_exp(const v_float16x8& x) { return v_exp_default_16f(x); } -inline v_float16x8 v_log(const v_float16x8& x) { return v_log_default_16f(x); } -inline void v_sincos(const v_float16x8& x, v_float16x8& s, v_float16x8& c) { v_sincos_default_16f(x, s, c); } -inline v_float16x8 v_sin(const v_float16x8& x) { return v_sin_default_16f(x); } -inline v_float16x8 v_cos(const v_float16x8& x) { return v_cos_default_16f(x); } -#endif -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } -#if CV_SIMD128_64F -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } -#endif - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HAL_INTRIN_NEON_HPP +#define OPENCV_HAL_INTRIN_NEON_HPP + +#include +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD128 1 +#if defined(__aarch64__) || defined(_M_ARM64) +#define CV_SIMD128_64F 1 +#else +#define CV_SIMD128_64F 0 +#endif + +// The following macro checks if the code is being compiled for the +// AArch64 execution state of Armv8, to enable the 128-bit +// intrinsics. The macro `__ARM_64BIT_STATE` is the one recommended by +// the Arm C Language Extension (ACLE) specifications [1] to check the +// availability of 128-bit intrinsics, and it is supporrted by clang +// and gcc. The macro `_M_ARM64` is the equivalent one for Microsoft +// Visual Studio [2] . +// +// [1] https://developer.arm.com/documentation/101028/0012/13--Advanced-SIMD--Neon--intrinsics +// [2] https://docs.microsoft.com/en-us/cpp/preprocessor/predefined-macros +#if defined(__ARM_64BIT_STATE) || defined(_M_ARM64) +#define CV_NEON_AARCH64 1 +#else +#define CV_NEON_AARCH64 0 +#endif + + +//////////// Utils //////////// + +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ + { c = vuzp1q_##suffix(a, b); d = vuzp2q_##suffix(a, b); } +#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv&a, const _Tpv&b, _Tpv& c, _Tpv& d) \ + { c = vuzp1_##suffix(a, b); d = vuzp2_##suffix(a, b); } +#else +#define OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ + { _Tpvx2 ab = vuzpq_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } +#define OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpv, _Tpvx2, suffix) \ + inline void _v128_unzip(const _Tpv& a, const _Tpv& b, _Tpv& c, _Tpv& d) \ + { _Tpvx2 ab = vuzp_##suffix(a, b); c = ab.val[0]; d = ab.val[1]; } +#endif + +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) \ + template static inline \ + _Tpv vreinterpretq_##suffix##_f64(T a) { return (_Tpv) a; } \ + template static inline \ + float64x2_t vreinterpretq_f64_##suffix(T a) { return (float64x2_t) a; } +#else +#define OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv, suffix) +#endif + +#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(_Tpv, _Tpvl, suffix) \ + OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) \ + OPENCV_HAL_IMPL_NEON_UNZIP_L(_Tpvl##_t, _Tpvl##x2_t, suffix) \ + OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) + +#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(_Tpv, _Tpvl, suffix) \ + OPENCV_HAL_IMPL_NEON_REINTERPRET(_Tpv##_t, suffix) + +#define OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(_Tpv, _Tpvl, suffix) \ + OPENCV_HAL_IMPL_NEON_UNZIP(_Tpv##_t, _Tpv##x2_t, suffix) + +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint8x16, uint8x8, u8) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int8x16, int8x8, s8) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint16x8, uint16x4, u16) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int16x8, int16x4, s16) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(uint32x4, uint32x2, u32) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(int32x4, int32x2, s32) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX(float32x4, float32x2, f32) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(uint64x2, uint64x1, u64) +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_I64(int64x2, int64x1, s64) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_UTILS_SUFFIX_F64(float64x2, float64x1,f64) +#endif + +//////////// Compatibility layer //////////// +template struct VTraits { + static inline int vlanes() { return T::nlanes; } + enum { max_nlanes = T::nlanes, nlanes = T::nlanes }; + using lane_type = typename T::lane_type; +}; + +template +inline typename VTraits::lane_type v_get0(const T& v) \ +{ \ + return v.get0(); \ +} +//////////// Types //////////// + +struct v_uint8x16 +{ + v_uint8x16() {} + explicit v_uint8x16(uint8x16_t v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = vld1q_u8(v); + } + uint8x16_t val; + +private: + friend struct VTraits; + enum { nlanes = 16 }; + typedef uchar lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint8x16& v); + uchar get0() const + { + return vgetq_lane_u8(val, 0); + } +}; + +struct v_int8x16 +{ + v_int8x16() {} + explicit v_int8x16(int8x16_t v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = vld1q_s8(v); + } + int8x16_t val; + +private: + friend struct VTraits; + enum { nlanes = 16 }; + typedef schar lane_type; + + friend typename VTraits::lane_type v_get0(const v_int8x16& v); + schar get0() const + { + return vgetq_lane_s8(val, 0); + } +}; + +struct v_uint16x8 +{ + v_uint16x8() {} + explicit v_uint16x8(uint16x8_t v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = vld1q_u16(v); + } + uint16x8_t val; + +private: + friend struct VTraits; + enum { nlanes = 8 }; + typedef ushort lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint16x8& v); + ushort get0() const + { + return vgetq_lane_u16(val, 0); + } +}; + +struct v_int16x8 +{ + v_int16x8() {} + explicit v_int16x8(int16x8_t v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = vld1q_s16(v); + } + int16x8_t val; + +private: + friend struct VTraits; + enum { nlanes = 8 }; + typedef short lane_type; + + friend typename VTraits::lane_type v_get0(const v_int16x8& v); + short get0() const + { + return vgetq_lane_s16(val, 0); + } +}; + +struct v_uint32x4 +{ + v_uint32x4() {} + explicit v_uint32x4(uint32x4_t v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + unsigned v[] = {v0, v1, v2, v3}; + val = vld1q_u32(v); + } + uint32x4_t val; + +private: + friend struct VTraits; + enum { nlanes = 4 }; + typedef unsigned lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint32x4& v); + unsigned get0() const + { + return vgetq_lane_u32(val, 0); + } +}; + +struct v_int32x4 +{ + v_int32x4() {} + explicit v_int32x4(int32x4_t v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = vld1q_s32(v); + } + int32x4_t val; + +private: + friend struct VTraits; + enum { nlanes = 4 }; + typedef int lane_type; + + friend typename VTraits::lane_type v_get0(const v_int32x4& v); + int get0() const + { + return vgetq_lane_s32(val, 0); + } +}; + +struct v_float32x4 +{ + v_float32x4() {} + explicit v_float32x4(float32x4_t v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = vld1q_f32(v); + } + float32x4_t val; + +private: + friend struct VTraits; + enum { nlanes = 4 }; + typedef float lane_type; + + friend typename VTraits::lane_type v_get0(const v_float32x4& v); + float get0() const + { + return vgetq_lane_f32(val, 0); + } +}; + +struct v_uint64x2 +{ + v_uint64x2() {} + explicit v_uint64x2(uint64x2_t v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = vld1q_u64(v); + } + uint64x2_t val; +private: + friend struct VTraits; + enum { nlanes = 2 }; + typedef uint64 lane_type; + + friend typename VTraits::lane_type v_get0(const v_uint64x2& v); + uint64 get0() const + { + return vgetq_lane_u64(val, 0); + } +}; + +struct v_int64x2 +{ + v_int64x2() {} + explicit v_int64x2(int64x2_t v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = vld1q_s64(v); + } + int64x2_t val; + +private: + friend struct VTraits; + enum { nlanes = 2 }; + typedef int64 lane_type; + + friend typename VTraits::lane_type v_get0(const v_int64x2& v); + int64 get0() const + { + return vgetq_lane_s64(val, 0); + } +}; + +#if CV_SIMD128_64F +struct v_float64x2 +{ + v_float64x2() {} + explicit v_float64x2(float64x2_t v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = vld1q_f64(v); + } + + float64x2_t val; +private: + friend struct VTraits; + enum { nlanes = 2 }; + typedef double lane_type; + + friend typename VTraits::lane_type v_get0(const v_float64x2& v); + double get0() const + { + return vgetq_lane_f64(val, 0); + } +}; +#endif + +#define OPENCV_HAL_IMPL_NEON_INIT(_Tpv, _Tp, suffix) \ +inline v_##_Tpv v_setzero_##suffix() { return v_##_Tpv(vdupq_n_##suffix((_Tp)0)); } \ +inline v_##_Tpv v_setall_##suffix(_Tp v) { return v_##_Tpv(vdupq_n_##suffix(v)); } \ +template <> inline v_##_Tpv v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline v_##_Tpv v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +inline _Tpv##_t vreinterpretq_##suffix##_##suffix(_Tpv##_t v) { return v; } \ +inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16(vreinterpretq_u8_##suffix(v.val)); } \ +inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16(vreinterpretq_s8_##suffix(v.val)); } \ +inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8(vreinterpretq_u16_##suffix(v.val)); } \ +inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpretq_s16_##suffix(v.val)); } \ +inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4(vreinterpretq_u32_##suffix(v.val)); } \ +inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4(vreinterpretq_s32_##suffix(v.val)); } \ +inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2(vreinterpretq_u64_##suffix(v.val)); } \ +inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2(vreinterpretq_s64_##suffix(v.val)); } \ +inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4(vreinterpretq_f32_##suffix(v.val)); } + +OPENCV_HAL_IMPL_NEON_INIT(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_INIT(int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_INIT(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_INIT(int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_INIT(uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_NEON_INIT(int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_INIT(uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_INIT(int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_INIT(float32x4, float, f32) +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_INIT_64(_Tpv, suffix) \ +inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2(vreinterpretq_f64_##suffix(v.val)); } +OPENCV_HAL_IMPL_NEON_INIT(float64x2, double, f64) +OPENCV_HAL_IMPL_NEON_INIT_64(uint8x16, u8) +OPENCV_HAL_IMPL_NEON_INIT_64(int8x16, s8) +OPENCV_HAL_IMPL_NEON_INIT_64(uint16x8, u16) +OPENCV_HAL_IMPL_NEON_INIT_64(int16x8, s16) +OPENCV_HAL_IMPL_NEON_INIT_64(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_INIT_64(int32x4, s32) +OPENCV_HAL_IMPL_NEON_INIT_64(uint64x2, u64) +OPENCV_HAL_IMPL_NEON_INIT_64(int64x2, s64) +OPENCV_HAL_IMPL_NEON_INIT_64(float32x4, f32) +OPENCV_HAL_IMPL_NEON_INIT_64(float64x2, f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_PACK(_Tpvec, _Tp, hreg, suffix, _Tpwvec, pack, mov, rshr) \ +inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + hreg a1 = mov(a.val), b1 = mov(b.val); \ + return _Tpvec(vcombine_##suffix(a1, b1)); \ +} \ +inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = mov(a.val); \ + vst1_##suffix(ptr, a1); \ +} \ +template inline \ +_Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + hreg a1 = rshr(a.val, n); \ + hreg b1 = rshr(b.val, n); \ + return _Tpvec(vcombine_##suffix(a1, b1)); \ +} \ +template inline \ +void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + hreg a1 = rshr(a.val, n); \ + vst1_##suffix(ptr, a1); \ +} + +OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_uint16x8, pack, vqmovn_u16, vqrshrn_n_u16) +OPENCV_HAL_IMPL_NEON_PACK(v_int8x16, schar, int8x8_t, s8, v_int16x8, pack, vqmovn_s16, vqrshrn_n_s16) +OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_uint32x4, pack, vqmovn_u32, vqrshrn_n_u32) +OPENCV_HAL_IMPL_NEON_PACK(v_int16x8, short, int16x4_t, s16, v_int32x4, pack, vqmovn_s32, vqrshrn_n_s32) +OPENCV_HAL_IMPL_NEON_PACK(v_uint32x4, unsigned, uint32x2_t, u32, v_uint64x2, pack, vmovn_u64, vrshrn_n_u64) +OPENCV_HAL_IMPL_NEON_PACK(v_int32x4, int, int32x2_t, s32, v_int64x2, pack, vmovn_s64, vrshrn_n_s64) + +OPENCV_HAL_IMPL_NEON_PACK(v_uint8x16, uchar, uint8x8_t, u8, v_int16x8, pack_u, vqmovun_s16, vqrshrun_n_s16) +OPENCV_HAL_IMPL_NEON_PACK(v_uint16x8, ushort, uint16x4_t, u16, v_int32x4, pack_u, vqmovun_s32, vqrshrun_n_s32) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + uint8x16_t ab = vcombine_u8(vmovn_u16(a.val), vmovn_u16(b.val)); + return v_uint8x16(ab); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + uint16x8_t nab = vcombine_u16(vmovn_u32(a.val), vmovn_u32(b.val)); + uint16x8_t ncd = vcombine_u16(vmovn_u32(c.val), vmovn_u32(d.val)); + return v_uint8x16(vcombine_u8(vmovn_u16(nab), vmovn_u16(ncd))); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + uint32x4_t ab = vcombine_u32(vmovn_u64(a.val), vmovn_u64(b.val)); + uint32x4_t cd = vcombine_u32(vmovn_u64(c.val), vmovn_u64(d.val)); + uint32x4_t ef = vcombine_u32(vmovn_u64(e.val), vmovn_u64(f.val)); + uint32x4_t gh = vcombine_u32(vmovn_u64(g.val), vmovn_u64(h.val)); + + uint16x8_t abcd = vcombine_u16(vmovn_u32(ab), vmovn_u32(cd)); + uint16x8_t efgh = vcombine_u16(vmovn_u32(ef), vmovn_u32(gh)); + return v_uint8x16(vcombine_u8(vmovn_u16(abcd), vmovn_u16(efgh))); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); + float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); + res = vmlaq_lane_f32(res, m1.val, vl, 1); + res = vmlaq_lane_f32(res, m2.val, vh, 0); + res = vmlaq_lane_f32(res, m3.val, vh, 1); + return v_float32x4(res); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + float32x2_t vl = vget_low_f32(v.val), vh = vget_high_f32(v.val); + float32x4_t res = vmulq_lane_f32(m0.val, vl, 0); + res = vmlaq_lane_f32(res, m1.val, vl, 1); + res = vmlaq_lane_f32(res, m2.val, vh, 0); + res = vaddq_f32(res, a.val); + return v_float32x4(res); +} + +#define OPENCV_HAL_IMPL_NEON_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op (const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint8x16, vqaddq_u8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint8x16, vqsubq_u8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int8x16, vqaddq_s8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int8x16, vqsubq_s8) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint16x8, vqaddq_u16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint16x8, vqsubq_u16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int16x8, vqaddq_s16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int16x8, vqsubq_s16) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int32x4, vaddq_s32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int32x4, vsubq_s32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_int32x4, vmulq_s32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint32x4, vaddq_u32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint32x4, vsubq_u32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_uint32x4, vmulq_u32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float32x4, vaddq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float32x4, vsubq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float32x4, vmulq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_int64x2, vaddq_s64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_int64x2, vsubq_s64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_uint64x2, vaddq_u64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_uint64x2, vsubq_u64) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float32x4, vdivq_f32) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_add, v_float64x2, vaddq_f64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_sub, v_float64x2, vsubq_f64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_mul, v_float64x2, vmulq_f64) +OPENCV_HAL_IMPL_NEON_BIN_OP(v_div, v_float64x2, vdivq_f64) +#else +inline v_float32x4 v_div (const v_float32x4& a, const v_float32x4& b) +{ + float32x4_t reciprocal = vrecpeq_f32(b.val); + reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); + reciprocal = vmulq_f32(vrecpsq_f32(b.val, reciprocal), reciprocal); + return v_float32x4(vmulq_f32(a.val, reciprocal)); +} +#endif + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_NEON_MUL_SAT(_Tpvec, _Tpwvec) \ + inline _Tpvec v_mul (const _Tpvec& a, const _Tpvec& b) \ + { \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ + } + +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_int16x8, v_int32x4) +OPENCV_HAL_IMPL_NEON_MUL_SAT(v_uint16x8, v_uint32x4) + +// Multiply and expand +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + c.val = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_s8(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + c.val = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_u8(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + c.val = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_s16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + c.val = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_u16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + c.val = vmull_u32(vget_low_u32(a.val), vget_low_u32(b.val)); +#if CV_NEON_AARCH64 + d.val = vmull_high_u32(a.val, b.val); +#else // #if CV_NEON_AARCH64 + d.val = vmull_u32(vget_high_u32(a.val), vget_high_u32(b.val)); +#endif // #if CV_NEON_AARCH64 +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ +#if CV_NEON_AARCH64 + int32x4_t c = vmull_high_s16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + int32x4_t c = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); +#endif // #if CV_NEON_AARCH64 + return v_int16x8(vcombine_s16( + vshrn_n_s32(vmull_s16( vget_low_s16(a.val), vget_low_s16(b.val)), 16), + vshrn_n_s32(c, 16) + )); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_NEON_AARCH64 + uint32x4_t c = vmull_high_u16(a.val, b.val); +#else // #if CV_NEON_AARCH64 + uint32x4_t c = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); +#endif // #if CV_NEON_AARCH64 + return v_uint16x8(vcombine_u16( + vshrn_n_u32(vmull_u16( vget_low_u16(a.val), vget_low_u16(b.val)), 16), + vshrn_n_u32(c, 16) + )); +} + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + int16x8_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int16x4_t a0 = vget_low_s16(uzp1); + int16x4_t b0 = vget_high_s16(uzp1); + int16x4_t a1 = vget_low_s16(uzp2); + int16x4_t b1 = vget_high_s16(uzp2); + int32x4_t p = vmull_s16(a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +} +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + int16x8_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int16x4_t a0 = vget_low_s16(uzp1); + int16x4_t b0 = vget_high_s16(uzp1); + int16x4_t a1 = vget_low_s16(uzp2); + int16x4_t b1 = vget_high_s16(uzp2); + int32x4_t p = vmlal_s16(c.val, a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + int32x4_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int32x2_t a0 = vget_low_s32(uzp1); + int32x2_t b0 = vget_high_s32(uzp1); + int32x2_t a1 = vget_low_s32(uzp2); + int32x2_t b1 = vget_high_s32(uzp2); + int64x2_t p = vmull_s32(a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + int32x4_t uzp1, uzp2; + _v128_unzip(a.val, b.val, uzp1, uzp2); + int32x2_t a0 = vget_low_s32(uzp1); + int32x2_t b0 = vget_high_s32(uzp1); + int32x2_t a1 = vget_low_s32(uzp2); + int32x2_t b1 = vget_high_s32(uzp2); + int64x2_t p = vmlal_s32(c.val, a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +} + +// 8 >> 32 +#ifdef CV_NEON_DOT +#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(_Tpvec1, _Tpvec2, suffix) \ +inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b) \ +{ \ + return _Tpvec1(vdotq_##suffix(vdupq_n_##suffix(0), a.val, b.val));\ +} \ +inline _Tpvec1 v_dotprod_expand(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ +{ \ + return _Tpvec1(vdotq_##suffix(c.val, a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_uint32x4, v_uint8x16, u32) +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_OP(v_int32x4, v_int8x16, s32) +#else +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + const uint8x16_t zero = vreinterpretq_u8_u32(vdupq_n_u32(0)); + const uint8x16_t mask = vreinterpretq_u8_u32(vdupq_n_u32(0x00FF00FF)); + const uint16x8_t zero32 = vreinterpretq_u16_u32(vdupq_n_u32(0)); + const uint16x8_t mask32 = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); + + uint16x8_t even = vmulq_u16(vreinterpretq_u16_u8(vbslq_u8(mask, a.val, zero)), + vreinterpretq_u16_u8(vbslq_u8(mask, b.val, zero))); + uint16x8_t odd = vmulq_u16(vshrq_n_u16(vreinterpretq_u16_u8(a.val), 8), + vshrq_n_u16(vreinterpretq_u16_u8(b.val), 8)); + + uint32x4_t s0 = vaddq_u32(vreinterpretq_u32_u16(vbslq_u16(mask32, even, zero32)), + vreinterpretq_u32_u16(vbslq_u16(mask32, odd, zero32))); + uint32x4_t s1 = vaddq_u32(vshrq_n_u32(vreinterpretq_u32_u16(even), 16), + vshrq_n_u32(vreinterpretq_u32_u16(odd), 16)); + return v_uint32x4(vaddq_u32(s0, s1)); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, + const v_uint32x4& c) +{ + return v_add(v_dotprod_expand(a, b), c); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + int16x8_t p0 = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); + int16x8_t p1 = vmull_s8(vget_high_s8(a.val), vget_high_s8(b.val)); + int16x8_t uzp1, uzp2; + _v128_unzip(p0, p1, uzp1, uzp2); + int16x8_t sum = vaddq_s16(uzp1, uzp2); + int16x4_t uzpl1, uzpl2; + _v128_unzip(vget_low_s16(sum), vget_high_s16(sum), uzpl1, uzpl2); + return v_int32x4(vaddl_s16(uzpl1, uzpl2)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, + const v_int32x4& c) +{ + return v_add(v_dotprod_expand(a, b), c); +} +#endif +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + const uint16x8_t zero = vreinterpretq_u16_u32(vdupq_n_u32(0)); + const uint16x8_t mask = vreinterpretq_u16_u32(vdupq_n_u32(0x0000FFFF)); + + uint32x4_t even = vmulq_u32(vreinterpretq_u32_u16(vbslq_u16(mask, a.val, zero)), + vreinterpretq_u32_u16(vbslq_u16(mask, b.val, zero))); + uint32x4_t odd = vmulq_u32(vshrq_n_u32(vreinterpretq_u32_u16(a.val), 16), + vshrq_n_u32(vreinterpretq_u32_u16(b.val), 16)); + uint32x4_t uzp1, uzp2; + _v128_unzip(even, odd, uzp1, uzp2); + uint64x2_t s0 = vaddl_u32(vget_low_u32(uzp1), vget_high_u32(uzp1)); + uint64x2_t s1 = vaddl_u32(vget_low_u32(uzp2), vget_high_u32(uzp2)); + return v_uint64x2(vaddq_u64(s0, s1)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + int32x4_t p0 = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); + int32x4_t p1 = vmull_s16(vget_high_s16(a.val), vget_high_s16(b.val)); + + int32x4_t uzp1, uzp2; + _v128_unzip(p0, p1, uzp1, uzp2); + int32x4_t sum = vaddq_s32(uzp1, uzp2); + + int32x2_t uzpl1, uzpl2; + _v128_unzip(vget_low_s32(sum), vget_high_s32(sum), uzpl1, uzpl2); + return v_int64x2(vaddl_s32(uzpl1, uzpl2)); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, + const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +#if CV_SIMD128_64F +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, + const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } +#endif + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ +#if CV_NEON_AARCH64 + int32x4_t p = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); + return v_int32x4(vmlal_high_s16(p, a.val, b.val)); +#else + int16x4_t a0 = vget_low_s16(a.val); + int16x4_t a1 = vget_high_s16(a.val); + int16x4_t b0 = vget_low_s16(b.val); + int16x4_t b1 = vget_high_s16(b.val); + int32x4_t p = vmull_s16(a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +#endif +} +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ +#if CV_NEON_AARCH64 + int32x4_t p = vmlal_s16(c.val, vget_low_s16(a.val), vget_low_s16(b.val)); + return v_int32x4(vmlal_high_s16(p, a.val, b.val)); +#else + int16x4_t a0 = vget_low_s16(a.val); + int16x4_t a1 = vget_high_s16(a.val); + int16x4_t b0 = vget_low_s16(b.val); + int16x4_t b1 = vget_high_s16(b.val); + int32x4_t p = vmlal_s16(c.val, a0, b0); + return v_int32x4(vmlal_s16(p, a1, b1)); +#endif +} + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_NEON_AARCH64 + int64x2_t p = vmull_s32(vget_low_s32(a.val), vget_low_s32(b.val)); + return v_int64x2(vmlal_high_s32(p, a.val, b.val)); +#else + int32x2_t a0 = vget_low_s32(a.val); + int32x2_t a1 = vget_high_s32(a.val); + int32x2_t b0 = vget_low_s32(b.val); + int32x2_t b1 = vget_high_s32(b.val); + int64x2_t p = vmull_s32(a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +#endif +} +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ +#if CV_NEON_AARCH64 + int64x2_t p = vmlal_s32(c.val, vget_low_s32(a.val), vget_low_s32(b.val)); + return v_int64x2(vmlal_high_s32(p, a.val, b.val)); +#else + int32x2_t a0 = vget_low_s32(a.val); + int32x2_t a1 = vget_high_s32(a.val); + int32x2_t b0 = vget_low_s32(b.val); + int32x2_t b1 = vget_high_s32(b.val); + int64x2_t p = vmlal_s32(c.val, a0, b0); + return v_int64x2(vmlal_s32(p, a1, b1)); +#endif +} + +// 8 >> 32 +#ifdef CV_NEON_DOT +#define OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(_Tpvec1, _Tpvec2, suffix) \ +inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b) \ +{ \ + return v_dotprod_expand(a, b); \ +} \ +inline _Tpvec1 v_dotprod_expand_fast(const _Tpvec2& a, const _Tpvec2& b, const _Tpvec1& c) \ +{ \ + return v_dotprod_expand(a, b, c); \ +} + +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_uint32x4, v_uint8x16, u32) +OPENCV_HAL_IMPL_NEON_DOT_PRODUCT_FAST_OP(v_int32x4, v_int8x16, s32) +#else +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ + uint16x8_t p0 = vmull_u8(vget_low_u8(a.val), vget_low_u8(b.val)); + uint16x8_t p1 = vmull_u8(vget_high_u8(a.val), vget_high_u8(b.val)); + uint32x4_t s0 = vaddl_u16(vget_low_u16(p0), vget_low_u16(p1)); + uint32x4_t s1 = vaddl_u16(vget_high_u16(p0), vget_high_u16(p1)); + return v_uint32x4(vaddq_u32(s0, s1)); +} +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ + return v_add(v_dotprod_expand_fast(a, b), c); +} + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ + int16x8_t prod = vmull_s8(vget_low_s8(a.val), vget_low_s8(b.val)); + prod = vmlal_s8(prod, vget_high_s8(a.val), vget_high_s8(b.val)); + return v_int32x4(vaddl_s16(vget_low_s16(prod), vget_high_s16(prod))); +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ + return v_add(v_dotprod_expand_fast(a, b), c); +} +#endif + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + uint32x4_t p0 = vmull_u16(vget_low_u16(a.val), vget_low_u16(b.val)); + uint32x4_t p1 = vmull_u16(vget_high_u16(a.val), vget_high_u16(b.val)); + uint64x2_t s0 = vaddl_u32(vget_low_u32(p0), vget_high_u32(p0)); + uint64x2_t s1 = vaddl_u32(vget_low_u32(p1), vget_high_u32(p1)); + return v_uint64x2(vaddq_u64(s0, s1)); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + int32x4_t prod = vmull_s16(vget_low_s16(a.val), vget_low_s16(b.val)); + prod = vmlal_s16(prod, vget_high_s16(a.val), vget_high_s16(b.val)); + return v_int64x2(vaddl_s32(vget_low_s32(prod), vget_high_s32(prod))); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +#if CV_SIMD128_64F +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod_fast(a, b)); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } +#endif + + +#define OPENCV_HAL_IMPL_NEON_LOGIC_OP(_Tpvec, suffix) \ + OPENCV_HAL_IMPL_NEON_BIN_OP(v_and, _Tpvec, vandq_##suffix) \ + OPENCV_HAL_IMPL_NEON_BIN_OP(v_or, _Tpvec, vorrq_##suffix) \ + OPENCV_HAL_IMPL_NEON_BIN_OP(v_xor, _Tpvec, veorq_##suffix) \ + inline _Tpvec v_not (const _Tpvec& a) \ + { \ + return _Tpvec(vreinterpretq_##suffix##_u8(vmvnq_u8(vreinterpretq_u8_##suffix(a.val)))); \ + } + +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint8x16, u8) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int8x16, s8) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint16x8, u16) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int16x8, s16) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint32x4, u32) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int32x4, s32) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_uint64x2, u64) +OPENCV_HAL_IMPL_NEON_LOGIC_OP(v_int64x2, s64) + +#define OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(bin_op, intrin) \ +inline v_float32x4 bin_op (const v_float32x4& a, const v_float32x4& b) \ +{ \ + return v_float32x4(vreinterpretq_f32_s32(intrin(vreinterpretq_s32_f32(a.val), vreinterpretq_s32_f32(b.val)))); \ +} + +OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_and, vandq_s32) +OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_or, vorrq_s32) +OPENCV_HAL_IMPL_NEON_FLT_BIT_OP(v_xor, veorq_s32) + +inline v_float32x4 v_not (const v_float32x4& a) +{ + return v_float32x4(vreinterpretq_f32_s32(vmvnq_s32(vreinterpretq_s32_f32(a.val)))); +} + +#if CV_SIMD128_64F +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + return v_float32x4(vsqrtq_f32(x.val)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + v_float32x4 one = v_setall_f32(1.0f); + return v_div(one, v_sqrt(x)); +} +#else +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + float32x4_t x1 = vmaxq_f32(x.val, vdupq_n_f32(FLT_MIN)); + float32x4_t e = vrsqrteq_f32(x1); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x1, e), e), e); + return v_float32x4(vmulq_f32(x.val, e)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + float32x4_t e = vrsqrteq_f32(x.val); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(x.val, e), e), e); + return v_float32x4(e); +} +#endif + +#define OPENCV_HAL_IMPL_NEON_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ +inline _Tpuvec v_abs(const _Tpsvec& a) { return v_reinterpret_as_##usuffix(_Tpsvec(vabsq_##ssuffix(a.val))); } + +OPENCV_HAL_IMPL_NEON_ABS(v_uint8x16, v_int8x16, u8, s8) +OPENCV_HAL_IMPL_NEON_ABS(v_uint16x8, v_int16x8, u16, s16) +OPENCV_HAL_IMPL_NEON_ABS(v_uint32x4, v_int32x4, u32, s32) + +inline v_float32x4 v_abs(v_float32x4 x) +{ return v_float32x4(vabsq_f32(x.val)); } + +#if CV_SIMD128_64F +#define OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(bin_op, intrin) \ +inline v_float64x2 bin_op (const v_float64x2& a, const v_float64x2& b) \ +{ \ + return v_float64x2(vreinterpretq_f64_s64(intrin(vreinterpretq_s64_f64(a.val), vreinterpretq_s64_f64(b.val)))); \ +} + +OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_and, vandq_s64) +OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_or, vorrq_s64) +OPENCV_HAL_IMPL_NEON_DBL_BIT_OP(v_xor, veorq_s64) + +inline v_float64x2 v_not (const v_float64x2& a) +{ + return v_float64x2(vreinterpretq_f64_s32(vmvnq_s32(vreinterpretq_s32_f64(a.val)))); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ + return v_float64x2(vsqrtq_f64(x.val)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + v_float64x2 one = v_setall_f64(1.0f); + return v_div(one, v_sqrt(x)); +} + +inline v_float64x2 v_abs(v_float64x2 x) +{ return v_float64x2(vabsq_f64(x.val)); } +#endif + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_NEON_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_min, vminq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_max, vmaxq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_min, vminq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_max, vmaxq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_min, vminq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_max, vmaxq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_min, vminq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_max, vmaxq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_min, vminq_u32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_max, vmaxq_u32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_min, vminq_s32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int32x4, v_max, vmaxq_s32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_min, vminq_f32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_max, vmaxq_f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_min, vminq_f64) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_max, vmaxq_f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_INT_CMP_OP(_Tpvec, cast, suffix, not_suffix) \ +inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vceqq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vmvnq_##not_suffix(vceqq_##suffix(a.val, b.val)))); } \ +inline _Tpvec v_lt (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcltq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_gt (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcgtq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_le (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcleq_##suffix(a.val, b.val))); } \ +inline _Tpvec v_ge (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(cast(vcgeq_##suffix(a.val, b.val))); } + +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint8x16, OPENCV_HAL_NOP, u8, u8) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int8x16, vreinterpretq_s8_u8, s8, u8) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint16x8, OPENCV_HAL_NOP, u16, u16) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int16x8, vreinterpretq_s16_u16, s16, u16) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint32x4, OPENCV_HAL_NOP, u32, u32) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int32x4, vreinterpretq_s32_u32, s32, u32) +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float32x4, vreinterpretq_f32_u32, f32, u32) +#if defined(__aarch64__) || defined(_M_ARM64) +static inline uint64x2_t vmvnq_u64(uint64x2_t a) +{ + uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); + return veorq_u64(a, vx); +} +//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_uint64x2, OPENCV_HAL_NOP, u64, u64) +//OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_int64x2, vreinterpretq_s64_u64, s64, u64) +static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint64x2(vceqq_u64(a.val, b.val)); } +static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) +{ return v_uint64x2(vmvnq_u64(vceqq_u64(a.val, b.val))); } +static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) +{ return v_int64x2(vreinterpretq_s64_u64(vceqq_s64(a.val, b.val))); } +static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) +{ return v_int64x2(vreinterpretq_s64_u64(vmvnq_u64(vceqq_s64(a.val, b.val)))); } +#else +static inline v_uint64x2 v_eq (const v_uint64x2& a, const v_uint64x2& b) +{ + uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); + uint32x4_t swapped = vrev64q_u32(cmp); + return v_uint64x2(vreinterpretq_u64_u32(vandq_u32(cmp, swapped))); +} +static inline v_uint64x2 v_ne (const v_uint64x2& a, const v_uint64x2& b) +{ + uint32x4_t cmp = vceqq_u32(vreinterpretq_u32_u64(a.val), vreinterpretq_u32_u64(b.val)); + uint32x4_t swapped = vrev64q_u32(cmp); + uint64x2_t v_eq = vreinterpretq_u64_u32(vandq_u32(cmp, swapped)); + uint64x2_t vx = vreinterpretq_u64_u32(vdupq_n_u32(0xFFFFFFFF)); + return v_uint64x2(veorq_u64(v_eq, vx)); +} +static inline v_int64x2 v_eq (const v_int64x2& a, const v_int64x2& b) +{ + return v_reinterpret_as_s64(v_eq(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); +} +static inline v_int64x2 v_ne (const v_int64x2& a, const v_int64x2& b) +{ + return v_reinterpret_as_s64(v_ne(v_reinterpret_as_u64(a), v_reinterpret_as_u64(b))); +} +#endif +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_INT_CMP_OP(v_float64x2, vreinterpretq_f64_u64, f64, u64) +#endif + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(vreinterpretq_f32_u32(vceqq_f32(a.val, a.val))); } +#if CV_SIMD128_64F +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(vreinterpretq_f64_u64(vceqq_f64(a.val, a.val))); } +#endif + +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_add_wrap, vaddq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_add_wrap, vaddq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_add_wrap, vaddq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_add_wrap, vaddq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_sub_wrap, vsubq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_sub_wrap, vsubq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_sub_wrap, vsubq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_sub_wrap, vsubq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_mul_wrap, vmulq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int8x16, v_mul_wrap, vmulq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_mul_wrap, vmulq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_int16x8, v_mul_wrap, vmulq_s16) + +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint8x16, v_absdiff, vabdq_u8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint16x8, v_absdiff, vabdq_u16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_uint32x4, v_absdiff, vabdq_u32) +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float32x4, v_absdiff, vabdq_f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BIN_FUNC(v_float64x2, v_absdiff, vabdq_f64) +#endif + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ return v_int8x16(vqabsq_s8(vqsubq_s8(a.val, b.val))); } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_int16x8(vqabsq_s16(vqsubq_s16(a.val, b.val))); } + +#define OPENCV_HAL_IMPL_NEON_BIN_FUNC2(_Tpvec, _Tpvec2, cast, func, intrin) \ +inline _Tpvec2 func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec2(cast(intrin(a.val, b.val))); \ +} + +OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int8x16, v_uint8x16, vreinterpretq_u8_s8, v_absdiff, vabdq_s8) +OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int16x8, v_uint16x8, vreinterpretq_u16_s16, v_absdiff, vabdq_s16) +OPENCV_HAL_IMPL_NEON_BIN_FUNC2(v_int32x4, v_uint32x4, vreinterpretq_u32_s32, v_absdiff, vabdq_s32) + +inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 x(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); + return v_sqrt(x); +} + +inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vmlaq_f32(vmulq_f32(a.val, a.val), b.val, b.val)); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ +#if CV_SIMD128_64F + // ARMv8, which adds support for 64-bit floating-point (so CV_SIMD128_64F is defined), + // also adds FMA support both for single- and double-precision floating-point vectors + return v_float32x4(vfmaq_f32(c.val, a.val, b.val)); +#else + return v_float32x4(vmlaq_f32(c.val, a.val, b.val)); +#endif +} + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_int32x4(vmlaq_s32(c.val, a.val, b.val)); +} + +inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +#if CV_SIMD128_64F +inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + v_float64x2 x(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); + return v_sqrt(x); +} + +inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vaddq_f64(vmulq_f64(a.val, a.val), vmulq_f64(b.val, b.val))); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_float64x2(vfmaq_f64(c.val, a.val, b.val)); +} + +inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_fma(a, b, c); +} +#endif + +// trade efficiency for convenience +#define OPENCV_HAL_IMPL_NEON_SHIFT_OP(_Tpvec, suffix, _Tps, ssuffix) \ +inline _Tpvec v_shl (const _Tpvec& a, int n) \ +{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)n))); } \ +inline _Tpvec v_shr (const _Tpvec& a, int n) \ +{ return _Tpvec(vshlq_##suffix(a.val, vdupq_n_##ssuffix((_Tps)-n))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec(vshlq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec(vshrq_n_##suffix(a.val, n)); } \ +template inline _Tpvec v_rshr(const _Tpvec& a) \ +{ return _Tpvec(vrshrq_n_##suffix(a.val, n)); } + +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint8x16, u8, schar, s8) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int8x16, s8, schar, s8) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint16x8, u16, short, s16) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int16x8, s16, short, s16) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint32x4, u32, int, s32) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int32x4, s32, int, s32) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_uint64x2, u64, int64, s64) +OPENCV_HAL_IMPL_NEON_SHIFT_OP(v_int64x2, s64, int64, s64) + +#define OPENCV_HAL_IMPL_NEON_ROTATE_OP(_Tpvec, suffix) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ return _Tpvec(vextq_##suffix(a.val, vdupq_n_##suffix(0), n)); } \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ return _Tpvec(vextq_##suffix(vdupq_n_##suffix(0), a.val, VTraits<_Tpvec>::nlanes - n)); } \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vextq_##suffix(a.val, b.val, n)); } \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vextq_##suffix(b.val, a.val, VTraits<_Tpvec>::nlanes - n)); } \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ CV_UNUSED(b); return a; } + +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint8x16, u8) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int8x16, s8) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint16x8, u16) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int16x8, s16) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint32x4, u32) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int32x4, s32) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float32x4, f32) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_uint64x2, u64) +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_int64x2, s64) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_ROTATE_OP(v_float64x2, f64) +#endif + +#if defined(__clang__) && defined(__aarch64__) +// avoid LD2 instruction. details: https://github.com/opencv/opencv/issues/14863 +#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ \ +typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; \ +uint64 v = *(unaligned_uint64*)ptr; \ +return _Tpvec(v_reinterpret_as_##suffix(v_uint64x2(v, (uint64)123456))); \ +} +#else +#define OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr), vdup_n_##suffix((_Tp)0))); } +#endif + +#define OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(vld1q_##suffix(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vld1q_##suffix(ptr)); } \ +OPENCV_HAL_IMPL_NEON_LOAD_LOW_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ return _Tpvec(vcombine_##suffix(vld1_##suffix(ptr0), vld1_##suffix(ptr1))); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vst1q_##suffix(ptr, a.val); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vst1_##suffix(ptr, vget_low_##suffix(a.val)); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ vst1_##suffix(ptr, vget_high_##suffix(a.val)); } + +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_LOADSTORE_OP(v_float64x2, double, f64) +#endif + +inline unsigned v_reduce_sum(const v_uint8x16& a) +{ +#if CV_NEON_AARCH64 + uint16_t t0 = vaddlvq_u8(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(a.val)); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline int v_reduce_sum(const v_int8x16& a) +{ +#if CV_NEON_AARCH64 + int16_t t0 = vaddlvq_s8(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + int32x4_t t0 = vpaddlq_s16(vpaddlq_s8(a.val)); + int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); + return vget_lane_s32(vpadd_s32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sum(const v_uint16x8& a) +{ +#if CV_NEON_AARCH64 + uint32_t t0 = vaddlvq_u16(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(a.val); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline int v_reduce_sum(const v_int16x8& a) +{ +#if CV_NEON_AARCH64 + int32_t t0 = vaddlvq_s16(a.val); + return t0; +#else // #if CV_NEON_AARCH64 + int32x4_t t0 = vpaddlq_s16(a.val); + int32x2_t t1 = vpadd_s32(vget_low_s32(t0), vget_high_s32(t0)); + return vget_lane_s32(vpadd_s32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return v##vectorfunc##vq_##suffix(a.val); \ +} +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ + a0 = vp##vectorfunc##_##suffix(a0, a0); \ + a0 = vp##vectorfunc##_##suffix(a0, a0); \ + return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ +} +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, max, max, u8) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_uint8x16, uint8x8, uchar, min, min, u8) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, max, max, s8) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_16(v_int8x16, int8x8, schar, min, min, s8) + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return v##vectorfunc##vq_##suffix(a.val); \ +} +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ + a0 = vp##vectorfunc##_##suffix(a0, a0); \ + return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, a0),0); \ +} +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, max, max, u16) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_uint16x8, uint16x4, ushort, min, min, u16) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, max, max, s16) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_8(v_int16x8, int16x4, short, min, min, s16) + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + return v##vectorfunc##vq_##suffix(a.val); \ +} +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(_Tpvec, _Tpnvec, scalartype, func, vectorfunc, suffix) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _Tpnvec##_t a0 = vp##vectorfunc##_##suffix(vget_low_##suffix(a.val), vget_high_##suffix(a.val)); \ + return (scalartype)vget_lane_##suffix(vp##vectorfunc##_##suffix(a0, vget_high_##suffix(a.val)),0); \ +} +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, sum, add, u32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, max, max, u32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_uint32x4, uint32x2, unsigned, min, min, u32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, sum, add, s32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, max, max, s32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_int32x4, int32x2, int, min, min, s32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, sum, add, f32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, max, max, f32) +OPENCV_HAL_IMPL_NEON_REDUCE_OP_4(v_float32x4, float32x2, float, min, min, f32) + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ +#if CV_NEON_AARCH64 + return vaddvq_u64(a.val); +#else // #if CV_NEON_AARCH64 + return vget_lane_u64(vadd_u64(vget_low_u64(a.val), vget_high_u64(a.val)),0); +#endif // #if CV_NEON_AARCH64 +} +inline int64 v_reduce_sum(const v_int64x2& a) +{ +#if CV_NEON_AARCH64 + return vaddvq_s64(a.val); +#else // #if CV_NEON_AARCH64 + return vget_lane_s64(vadd_s64(vget_low_s64(a.val), vget_high_s64(a.val)),0); +#endif // #if CV_NEON_AARCH64 +} +#if CV_SIMD128_64F +inline double v_reduce_sum(const v_float64x2& a) +{ + return vaddvq_f64(a.val); +} +#endif + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ +#if CV_NEON_AARCH64 + float32x4_t ab = vpaddq_f32(a.val, b.val); // a0+a1 a2+a3 b0+b1 b2+b3 + float32x4_t cd = vpaddq_f32(c.val, d.val); // c0+c1 d0+d1 c2+c3 d2+d3 + return v_float32x4(vpaddq_f32(ab, cd)); // sumA sumB sumC sumD +#else // #if CV_NEON_AARCH64 + float32x4x2_t ab = vtrnq_f32(a.val, b.val); + float32x4x2_t cd = vtrnq_f32(c.val, d.val); + + float32x4_t u0 = vaddq_f32(ab.val[0], ab.val[1]); // a0+a1 b0+b1 a2+a3 b2+b3 + float32x4_t u1 = vaddq_f32(cd.val[0], cd.val[1]); // c0+c1 d0+d1 c2+c3 d2+d3 + + float32x4_t v0 = vcombine_f32(vget_low_f32(u0), vget_low_f32(u1)); + float32x4_t v1 = vcombine_f32(vget_high_f32(u0), vget_high_f32(u1)); + + return v_float32x4(vaddq_f32(v0, v1)); +#endif // #if CV_NEON_AARCH64 +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ +#if CV_NEON_AARCH64 + uint8x16_t t0 = vabdq_u8(a.val, b.val); + uint16_t t1 = vaddlvq_u8(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vabdq_u8(a.val, b.val))); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_NEON_AARCH64 + uint8x16_t t0 = vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)); + uint16_t t1 = vaddlvq_u8(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vpaddlq_u8(vreinterpretq_u8_s8(vabdq_s8(a.val, b.val)))); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_NEON_AARCH64 + uint16x8_t t0 = vabdq_u16(a.val, b.val); + uint32_t t1 = vaddlvq_u16(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vabdq_u16(a.val, b.val)); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ +#if CV_NEON_AARCH64 + uint16x8_t t0 = vreinterpretq_u16_s16(vabdq_s16(a.val, b.val)); + uint32_t t1 = vaddlvq_u16(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vpaddlq_u16(vreinterpretq_u16_s16(vabdq_s16(a.val, b.val))); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ +#if CV_NEON_AARCH64 + uint32x4_t t0 = vabdq_u32(a.val, b.val); + uint32_t t1 = vaddvq_u32(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vabdq_u32(a.val, b.val); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_NEON_AARCH64 + uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); + uint32_t t1 = vaddvq_u32(t0); + return t1; +#else // #if CV_NEON_AARCH64 + uint32x4_t t0 = vreinterpretq_u32_s32(vabdq_s32(a.val, b.val)); + uint32x2_t t1 = vpadd_u32(vget_low_u32(t0), vget_high_u32(t0)); + return vget_lane_u32(vpadd_u32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ +#if CV_NEON_AARCH64 + float32x4_t t0 = vabdq_f32(a.val, b.val); + return vaddvq_f32(t0); +#else // #if CV_NEON_AARCH64 + float32x4_t t0 = vabdq_f32(a.val, b.val); + float32x2_t t1 = vpadd_f32(vget_low_f32(t0), vget_high_f32(t0)); + return vget_lane_f32(vpadd_f32(t1, t1), 0); +#endif // #if CV_NEON_AARCH64 +} + +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ return v_uint8x16(vcntq_u8(a.val)); } +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_uint8x16(vcntq_u8(vreinterpretq_u8_s8(a.val))); } +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u16(a.val)))); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_uint16x8(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s16(a.val)))); } +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u32(a.val))))); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_uint32x4(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s32(a.val))))); } +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_u64(a.val)))))); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_uint64x2(vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(vcntq_u8(vreinterpretq_u8_s64(a.val)))))); } + +inline int v_signmask(const v_uint8x16& a) +{ +#if CV_NEON_AARCH64 + const int8x16_t signPosition = {0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7}; + const uint8x16_t byteOrder = {0,8,1,9,2,10,3,11,4,12,5,13,6,14,7,15}; + uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), signPosition); + uint8x16_t v1 = vqtbl1q_u8(v0, byteOrder); + uint32_t t0 = vaddlvq_u16(vreinterpretq_u16_u8(v1)); + return t0; +#else // #if CV_NEON_AARCH64 + int8x8_t m0 = vcreate_s8(CV_BIG_UINT(0x0706050403020100)); + uint8x16_t v0 = vshlq_u8(vshrq_n_u8(a.val, 7), vcombine_s8(m0, m0)); + uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(vpaddlq_u8(v0))); + return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 8); +#endif // #if CV_NEON_AARCH64 +} + +inline int v_signmask(const v_int8x16& a) +{ return v_signmask(v_reinterpret_as_u8(a)); } + +inline int v_signmask(const v_uint16x8& a) +{ +#if CV_NEON_AARCH64 + const int16x8_t signPosition = {0,1,2,3,4,5,6,7}; + uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), signPosition); + uint32_t t0 = vaddlvq_u16(v0); + return t0; +#else // #if CV_NEON_AARCH64 + int16x4_t m0 = vcreate_s16(CV_BIG_UINT(0x0003000200010000)); + uint16x8_t v0 = vshlq_u16(vshrq_n_u16(a.val, 15), vcombine_s16(m0, m0)); + uint64x2_t v1 = vpaddlq_u32(vpaddlq_u16(v0)); + return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 4); +#endif // #if CV_NEON_AARCH64 +} +inline int v_signmask(const v_int16x8& a) +{ return v_signmask(v_reinterpret_as_u16(a)); } + +inline int v_signmask(const v_uint32x4& a) +{ +#if CV_NEON_AARCH64 + const int32x4_t signPosition = {0,1,2,3}; + uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), signPosition); + uint32_t t0 = vaddvq_u32(v0); + return t0; +#else // #if CV_NEON_AARCH64 + int32x2_t m0 = vcreate_s32(CV_BIG_UINT(0x0000000100000000)); + uint32x4_t v0 = vshlq_u32(vshrq_n_u32(a.val, 31), vcombine_s32(m0, m0)); + uint64x2_t v1 = vpaddlq_u32(v0); + return (int)vgetq_lane_u64(v1, 0) + ((int)vgetq_lane_u64(v1, 1) << 2); +#endif // #if CV_NEON_AARCH64 +} +inline int v_signmask(const v_int32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(v_reinterpret_as_u32(a)); } +inline int v_signmask(const v_uint64x2& a) +{ +#if CV_NEON_AARCH64 + const int64x2_t signPosition = {0,1}; + uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), signPosition); + int t0 = (int)vaddvq_u64(v0); + return t0; +#else // #if CV_NEON_AARCH64 + int64x1_t m0 = vdup_n_s64(0); + uint64x2_t v0 = vshlq_u64(vshrq_n_u64(a.val, 63), vcombine_s64(m0, m0)); + return (int)vgetq_lane_u64(v0, 0) + ((int)vgetq_lane_u64(v0, 1) << 1); +#endif // #if CV_NEON_AARCH64 +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +#if CV_SIMD128_64F +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +#endif + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } +#if CV_SIMD128_64F +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } +#endif + +#if CV_NEON_AARCH64 + #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ + inline bool v_check_all(const v_##_Tpvec& a) \ + { \ + return (vminvq_##suffix(a.val) >> shift) != 0; \ + } \ + inline bool v_check_any(const v_##_Tpvec& a) \ + { \ + return (vmaxvq_##suffix(a.val) >> shift) != 0; \ + } +#else // #if CV_NEON_AARCH64 + #define OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(_Tpvec, suffix, shift) \ + inline bool v_check_all(const v_##_Tpvec& a) \ + { \ + _Tpvec##_t v0 = vshrq_n_##suffix(vmvnq_##suffix(a.val), shift); \ + uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ + return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) == 0; \ + } \ + inline bool v_check_any(const v_##_Tpvec& a) \ + { \ + _Tpvec##_t v0 = vshrq_n_##suffix(a.val, shift); \ + uint64x2_t v1 = vreinterpretq_u64_##suffix(v0); \ + return (vgetq_lane_u64(v1, 0) | vgetq_lane_u64(v1, 1)) != 0; \ + } +#endif // #if CV_NEON_AARCH64 + +OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint8x16, u8, 7) +OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint16x8, u16, 15) +OPENCV_HAL_IMPL_NEON_CHECK_ALLANY(uint32x4, u32, 31) + +inline bool v_check_all(const v_uint64x2& a) +{ + uint64x2_t v0 = vshrq_n_u64(a.val, 63); + return (vgetq_lane_u64(v0, 0) & vgetq_lane_u64(v0, 1)) == 1; +} +inline bool v_check_any(const v_uint64x2& a) +{ + uint64x2_t v0 = vshrq_n_u64(a.val, 63); + return (vgetq_lane_u64(v0, 0) | vgetq_lane_u64(v0, 1)) != 0; +} + +inline bool v_check_all(const v_int8x16& a) +{ return v_check_all(v_reinterpret_as_u8(a)); } +inline bool v_check_all(const v_int16x8& a) +{ return v_check_all(v_reinterpret_as_u16(a)); } +inline bool v_check_all(const v_int32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } + +inline bool v_check_any(const v_int8x16& a) +{ return v_check_any(v_reinterpret_as_u8(a)); } +inline bool v_check_any(const v_int16x8& a) +{ return v_check_any(v_reinterpret_as_u16(a)); } +inline bool v_check_any(const v_int32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } + +inline bool v_check_all(const v_int64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_int64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +#if CV_SIMD128_64F +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +#endif + +#define OPENCV_HAL_IMPL_NEON_SELECT(_Tpvec, suffix, usuffix) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(vbslq_##suffix(vreinterpretq_##usuffix##_##suffix(mask.val), a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_NEON_SELECT(v_uint8x16, u8, u8) +OPENCV_HAL_IMPL_NEON_SELECT(v_int8x16, s8, u8) +OPENCV_HAL_IMPL_NEON_SELECT(v_uint16x8, u16, u16) +OPENCV_HAL_IMPL_NEON_SELECT(v_int16x8, s16, u16) +OPENCV_HAL_IMPL_NEON_SELECT(v_uint32x4, u32, u32) +OPENCV_HAL_IMPL_NEON_SELECT(v_int32x4, s32, u32) +OPENCV_HAL_IMPL_NEON_SELECT(v_float32x4, f32, u32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_SELECT(v_float64x2, f64, u64) +#endif + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ + b1.val = vmovl_high_##suffix(a.val); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_high_##suffix(a.val)); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ +} +#else +#define OPENCV_HAL_IMPL_NEON_EXPAND(_Tpvec, _Tpwvec, _Tp, suffix) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = vmovl_##suffix(vget_low_##suffix(a.val)); \ + b1.val = vmovl_##suffix(vget_high_##suffix(a.val)); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_##suffix(vget_low_##suffix(a.val))); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + return _Tpwvec(vmovl_##suffix(vget_high_##suffix(a.val))); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return _Tpwvec(vmovl_##suffix(vld1_##suffix(ptr))); \ +} +#endif + +OPENCV_HAL_IMPL_NEON_EXPAND(v_uint8x16, v_uint16x8, uchar, u8) +OPENCV_HAL_IMPL_NEON_EXPAND(v_int8x16, v_int16x8, schar, s8) +OPENCV_HAL_IMPL_NEON_EXPAND(v_uint16x8, v_uint32x4, ushort, u16) +OPENCV_HAL_IMPL_NEON_EXPAND(v_int16x8, v_int32x4, short, s16) +OPENCV_HAL_IMPL_NEON_EXPAND(v_uint32x4, v_uint64x2, uint, u32) +OPENCV_HAL_IMPL_NEON_EXPAND(v_int32x4, v_int64x2, int, s32) + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; + uint8x8_t v0 = vcreate_u8(*(unaligned_uint*)ptr); + uint16x4_t v1 = vget_low_u16(vmovl_u8(v0)); + return v_uint32x4(vmovl_u16(v1)); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + typedef unsigned int CV_DECL_ALIGNED(1) unaligned_uint; + int8x8_t v0 = vcreate_s8(*(unaligned_uint*)ptr); + int16x4_t v1 = vget_low_s16(vmovl_s8(v0)); + return v_int32x4(vmovl_s16(v1)); +} + +#if defined(__aarch64__) || defined(_M_ARM64) +#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ +inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ +{ \ + b0.val = vzip1q_##suffix(a0.val, a1.val); \ + b1.val = vzip2q_##suffix(a0.val, a1.val); \ +} \ +inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ +} \ +inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ +} \ +inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ + d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ +} +#else +#define OPENCV_HAL_IMPL_NEON_UNPACKS(_Tpvec, suffix) \ +inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ +{ \ + _Tpvec##x2_t p = vzipq_##suffix(a0.val, a1.val); \ + b0.val = p.val[0]; \ + b1.val = p.val[1]; \ +} \ +inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val))); \ +} \ +inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val))); \ +} \ +inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + c.val = vcombine_##suffix(vget_low_##suffix(a.val), vget_low_##suffix(b.val)); \ + d.val = vcombine_##suffix(vget_high_##suffix(a.val), vget_high_##suffix(b.val)); \ +} +#endif + +OPENCV_HAL_IMPL_NEON_UNPACKS(uint8x16, u8) +OPENCV_HAL_IMPL_NEON_UNPACKS(int8x16, s8) +OPENCV_HAL_IMPL_NEON_UNPACKS(uint16x8, u16) +OPENCV_HAL_IMPL_NEON_UNPACKS(int16x8, s16) +OPENCV_HAL_IMPL_NEON_UNPACKS(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_UNPACKS(int32x4, s32) +OPENCV_HAL_IMPL_NEON_UNPACKS(float32x4, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_UNPACKS(float64x2, f64) +#endif + +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + uint8x16_t vec = vrev64q_u8(a.val); + return v_uint8x16(vextq_u8(vec, vec, 8)); +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + uint16x8_t vec = vrev64q_u16(a.val); + return v_uint16x8(vextq_u16(vec, vec, 4)); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + uint32x4_t vec = vrev64q_u32(a.val); + return v_uint32x4(vextq_u32(vec, vec, 2)); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + uint64x2_t vec = a.val; + uint64x1_t vec_lo = vget_low_u64(vec); + uint64x1_t vec_hi = vget_high_u64(vec); + return v_uint64x2(vcombine_u64(vec_hi, vec_lo)); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +#if CV_SIMD128_64F +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } +#endif + +#define OPENCV_HAL_IMPL_NEON_EXTRACT(_Tpvec, suffix) \ +template \ +inline v_##_Tpvec v_extract(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + return v_##_Tpvec(vextq_##suffix(a.val, b.val, s)); \ +} + +OPENCV_HAL_IMPL_NEON_EXTRACT(uint8x16, u8) +OPENCV_HAL_IMPL_NEON_EXTRACT(int8x16, s8) +OPENCV_HAL_IMPL_NEON_EXTRACT(uint16x8, u16) +OPENCV_HAL_IMPL_NEON_EXTRACT(int16x8, s16) +OPENCV_HAL_IMPL_NEON_EXTRACT(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_EXTRACT(int32x4, s32) +OPENCV_HAL_IMPL_NEON_EXTRACT(uint64x2, u64) +OPENCV_HAL_IMPL_NEON_EXTRACT(int64x2, s64) +OPENCV_HAL_IMPL_NEON_EXTRACT(float32x4, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_EXTRACT(float64x2, f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_EXTRACT_N(_Tpvec, _Tp, suffix) \ +template inline _Tp v_extract_n(_Tpvec v) { return vgetq_lane_##suffix(v.val, i); } + +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint32x4, uint, u32) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_EXTRACT_N(v_float64x2, double, f64) +#endif + +#define OPENCV_HAL_IMPL_NEON_BROADCAST(_Tpvec, _Tp, suffix) \ +template inline _Tpvec v_broadcast_element(_Tpvec v) { _Tp t = v_extract_n(v); return v_setall_##suffix(t); } + +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint32x4, uint, u32) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_int64x2, int64, s64) +OPENCV_HAL_IMPL_NEON_BROADCAST(v_float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_BROADCAST(v_float64x2, double, f64) +#endif + +#if CV_SIMD128_64F +inline v_int32x4 v_round(const v_float32x4& a) +{ + float32x4_t a_ = a.val; + int32x4_t result; +#if defined _MSC_VER + result = vcvtnq_s32_f32(a_); +#else + __asm__ ("fcvtns %0.4s, %1.4s" + : "=w"(result) + : "w"(a_) + : /* No clobbers */); +#endif + return v_int32x4(result); +} +#else +inline v_int32x4 v_round(const v_float32x4& a) +{ + // See https://github.com/opencv/opencv/pull/24271#issuecomment-1867318007 + float32x4_t delta = vdupq_n_f32(12582912.0f); + return v_int32x4(vcvtq_s32_f32(vsubq_f32(vaddq_f32(a.val, delta), delta))); +} +#endif +inline v_int32x4 v_floor(const v_float32x4& a) +{ + int32x4_t a1 = vcvtq_s32_f32(a.val); + uint32x4_t mask = vcgtq_f32(vcvtq_f32_s32(a1), a.val); + return v_int32x4(vaddq_s32(a1, vreinterpretq_s32_u32(mask))); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + int32x4_t a1 = vcvtq_s32_f32(a.val); + uint32x4_t mask = vcgtq_f32(a.val, vcvtq_f32_s32(a1)); + return v_int32x4(vsubq_s32(a1, vreinterpretq_s32_u32(mask))); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(vcvtq_s32_f32(a.val)); } + +#if CV_SIMD128_64F +inline v_int32x4 v_round(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), zero)); +} + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + return v_int32x4(vcombine_s32(vmovn_s64(vcvtnq_s64_f64(a.val)), vmovn_s64(vcvtnq_s64_f64(b.val)))); +} + +inline v_int32x4 v_floor(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + int64x2_t a1 = vcvtq_s64_f64(a.val); + uint64x2_t mask = vcgtq_f64(vcvtq_f64_s64(a1), a.val); + a1 = vaddq_s64(a1, vreinterpretq_s64_u64(mask)); + return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + int64x2_t a1 = vcvtq_s64_f64(a.val); + uint64x2_t mask = vcgtq_f64(a.val, vcvtq_f64_s64(a1)); + a1 = vsubq_s64(a1, vreinterpretq_s64_u64(mask)); + return v_int32x4(vcombine_s32(vmovn_s64(a1), zero)); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ + static const int32x2_t zero = vdup_n_s32(0); + return v_int32x4(vcombine_s32(vmovn_s64(vcvtaq_s64_f64(a.val)), zero)); +} +#endif + +#if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ + const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ + v_##_Tpvec& b0, v_##_Tpvec& b1, \ + v_##_Tpvec& b2, v_##_Tpvec& b3) \ +{ \ + /* -- Pass 1: 64b transpose */ \ + _Tpvec##_t t0 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ + vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ + _Tpvec##_t t1 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn1q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ + vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ + _Tpvec##_t t2 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a0.val), \ + vreinterpretq_##suffix##64_##suffix##32(a2.val))); \ + _Tpvec##_t t3 = vreinterpretq_##suffix##32_##suffix##64( \ + vtrn2q_##suffix##64(vreinterpretq_##suffix##64_##suffix##32(a1.val), \ + vreinterpretq_##suffix##64_##suffix##32(a3.val))); \ + /* -- Pass 2: 32b transpose */ \ + b0.val = vtrn1q_##suffix##32(t0, t1); \ + b1.val = vtrn2q_##suffix##32(t0, t1); \ + b2.val = vtrn1q_##suffix##32(t2, t3); \ + b3.val = vtrn2q_##suffix##32(t2, t3); \ +} + +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f) +#else // #if CV_NEON_AARCH64 +#define OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const v_##_Tpvec& a0, const v_##_Tpvec& a1, \ + const v_##_Tpvec& a2, const v_##_Tpvec& a3, \ + v_##_Tpvec& b0, v_##_Tpvec& b1, \ + v_##_Tpvec& b2, v_##_Tpvec& b3) \ +{ \ + /* m00 m01 m02 m03 */ \ + /* m10 m11 m12 m13 */ \ + /* m20 m21 m22 m23 */ \ + /* m30 m31 m32 m33 */ \ + _Tpvec##x2_t t0 = vtrnq_##suffix(a0.val, a1.val); \ + _Tpvec##x2_t t1 = vtrnq_##suffix(a2.val, a3.val); \ + /* m00 m10 m02 m12 */ \ + /* m01 m11 m03 m13 */ \ + /* m20 m30 m22 m32 */ \ + /* m21 m31 m23 m33 */ \ + b0.val = vcombine_##suffix(vget_low_##suffix(t0.val[0]), vget_low_##suffix(t1.val[0])); \ + b1.val = vcombine_##suffix(vget_low_##suffix(t0.val[1]), vget_low_##suffix(t1.val[1])); \ + b2.val = vcombine_##suffix(vget_high_##suffix(t0.val[0]), vget_high_##suffix(t1.val[0])); \ + b3.val = vcombine_##suffix(vget_high_##suffix(t0.val[1]), vget_high_##suffix(t1.val[1])); \ +} + +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(uint32x4, u32) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(int32x4, s32) +OPENCV_HAL_IMPL_NEON_TRANSPOSE4x4(float32x4, f32) +#endif // #if CV_NEON_AARCH64 + +#define OPENCV_HAL_IMPL_NEON_INTERLEAVED(_Tpvec, _Tp, suffix) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ +{ \ + _Tpvec##x2_t v = vld2q_##suffix(ptr); \ + a.val = v.val[0]; \ + b.val = v.val[1]; \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ +{ \ + _Tpvec##x3_t v = vld3q_##suffix(ptr); \ + a.val = v.val[0]; \ + b.val = v.val[1]; \ + c.val = v.val[2]; \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ + v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + _Tpvec##x4_t v = vld4q_##suffix(ptr); \ + a.val = v.val[0]; \ + b.val = v.val[1]; \ + c.val = v.val[2]; \ + d.val = v.val[3]; \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec##x2_t v; \ + v.val[0] = a.val; \ + v.val[1] = b.val; \ + vst2q_##suffix(ptr, v); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + _Tpvec##x3_t v; \ + v.val[0] = a.val; \ + v.val[1] = b.val; \ + v.val[2] = c.val; \ + vst3q_##suffix(ptr, v); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, const v_##_Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec##x4_t v; \ + v.val[0] = a.val; \ + v.val[1] = b.val; \ + v.val[2] = c.val; \ + v.val[3] = d.val; \ + vst4q_##suffix(ptr, v); \ +} + +#define OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(tp, suffix) \ +inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b ) \ +{ \ + tp##x1_t a0 = vld1_##suffix(ptr); \ + tp##x1_t b0 = vld1_##suffix(ptr + 1); \ + tp##x1_t a1 = vld1_##suffix(ptr + 2); \ + tp##x1_t b1 = vld1_##suffix(ptr + 3); \ + a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ + b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ +} \ + \ +inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, \ + v_##tp##x2& b, v_##tp##x2& c ) \ +{ \ + tp##x1_t a0 = vld1_##suffix(ptr); \ + tp##x1_t b0 = vld1_##suffix(ptr + 1); \ + tp##x1_t c0 = vld1_##suffix(ptr + 2); \ + tp##x1_t a1 = vld1_##suffix(ptr + 3); \ + tp##x1_t b1 = vld1_##suffix(ptr + 4); \ + tp##x1_t c1 = vld1_##suffix(ptr + 5); \ + a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ + b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ + c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ +} \ + \ +inline void v_load_deinterleave( const tp* ptr, v_##tp##x2& a, v_##tp##x2& b, \ + v_##tp##x2& c, v_##tp##x2& d ) \ +{ \ + tp##x1_t a0 = vld1_##suffix(ptr); \ + tp##x1_t b0 = vld1_##suffix(ptr + 1); \ + tp##x1_t c0 = vld1_##suffix(ptr + 2); \ + tp##x1_t d0 = vld1_##suffix(ptr + 3); \ + tp##x1_t a1 = vld1_##suffix(ptr + 4); \ + tp##x1_t b1 = vld1_##suffix(ptr + 5); \ + tp##x1_t c1 = vld1_##suffix(ptr + 6); \ + tp##x1_t d1 = vld1_##suffix(ptr + 7); \ + a = v_##tp##x2(vcombine_##suffix(a0, a1)); \ + b = v_##tp##x2(vcombine_##suffix(b0, b1)); \ + c = v_##tp##x2(vcombine_##suffix(c0, c1)); \ + d = v_##tp##x2(vcombine_##suffix(d0, d1)); \ +} \ + \ +inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ + vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ + vst1_##suffix(ptr + 2, vget_high_##suffix(a.val)); \ + vst1_##suffix(ptr + 3, vget_high_##suffix(b.val)); \ +} \ + \ +inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, \ + const v_##tp##x2& b, const v_##tp##x2& c, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ + vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ + vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ + vst1_##suffix(ptr + 3, vget_high_##suffix(a.val)); \ + vst1_##suffix(ptr + 4, vget_high_##suffix(b.val)); \ + vst1_##suffix(ptr + 5, vget_high_##suffix(c.val)); \ +} \ + \ +inline void v_store_interleave( tp* ptr, const v_##tp##x2& a, const v_##tp##x2& b, \ + const v_##tp##x2& c, const v_##tp##x2& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + vst1_##suffix(ptr, vget_low_##suffix(a.val)); \ + vst1_##suffix(ptr + 1, vget_low_##suffix(b.val)); \ + vst1_##suffix(ptr + 2, vget_low_##suffix(c.val)); \ + vst1_##suffix(ptr + 3, vget_low_##suffix(d.val)); \ + vst1_##suffix(ptr + 4, vget_high_##suffix(a.val)); \ + vst1_##suffix(ptr + 5, vget_high_##suffix(b.val)); \ + vst1_##suffix(ptr + 6, vget_high_##suffix(c.val)); \ + vst1_##suffix(ptr + 7, vget_high_##suffix(d.val)); \ +} + +OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint8x16, uchar, u8) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(int8x16, schar, s8) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint16x8, ushort, u16) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(int16x8, short, s16) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(int32x4, int, s32) +OPENCV_HAL_IMPL_NEON_INTERLEAVED(float32x4, float, f32) +#if CV_SIMD128_64F +OPENCV_HAL_IMPL_NEON_INTERLEAVED(float64x2, double, f64) +#endif + +OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(int64, s64) +OPENCV_HAL_IMPL_NEON_INTERLEAVED_INT64(uint64, u64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(vcvtq_f32_s32(a.val)); +} + +#if CV_SIMD128_64F +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + float32x2_t zero = vdup_n_f32(0.0f); + return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), zero)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + return v_float32x4(vcombine_f32(vcvt_f32_f64(a.val), vcvt_f32_f64(b.val))); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_low_s32(a.val)))); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vcvt_f32_s32(vget_high_s32(a.val)))); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vget_low_f32(a.val))); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + return v_float64x2(vcvt_f64_f32(vget_high_f32(a.val))); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ return v_float64x2(vcvtq_f64_s64(a.val)); } + +#endif + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[ 0]], + tab[idx[ 1]], + tab[idx[ 2]], + tab[idx[ 3]], + tab[idx[ 4]], + tab[idx[ 5]], + tab[idx[ 6]], + tab[idx[ 7]], + tab[idx[ 8]], + tab[idx[ 9]], + tab[idx[10]], + tab[idx[11]], + tab[idx[12]], + tab[idx[13]], + tab[idx[14]], + tab[idx[15]] + }; + return v_int8x16(vld1q_s8(elems)); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[4]], + tab[idx[4] + 1], + tab[idx[5]], + tab[idx[5] + 1], + tab[idx[6]], + tab[idx[6] + 1], + tab[idx[7]], + tab[idx[7] + 1] + }; + return v_int8x16(vld1q_s8(elems)); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[2] + 2], + tab[idx[2] + 3], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[3] + 2], + tab[idx[3] + 3] + }; + return v_int8x16(vld1q_s8(elems)); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]], + tab[idx[4]], + tab[idx[5]], + tab[idx[6]], + tab[idx[7]] + }; + return v_int16x8(vld1q_s16(elems)); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1] + }; + return v_int16x8(vld1q_s16(elems)); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(vcombine_s16(vld1_s16(tab + idx[0]), vld1_s16(tab + idx[1]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_int32x4(vld1q_s32(elems)); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(vcombine_s32(vld1_s32(tab + idx[0]), vld1_s32(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(vld1q_s32(tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(vcombine_s64(vcreate_s64(tab[idx[0]]), vcreate_s64(tab[idx[1]]))); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(vld1q_s64(tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_float32x4(vld1q_f32(elems)); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ + typedef uint64 CV_DECL_ALIGNED(1) unaligned_uint64; + + uint64 CV_DECL_ALIGNED(32) elems[2] = + { + *(unaligned_uint64*)(tab + idx[0]), + *(unaligned_uint64*)(tab + idx[1]) + }; + return v_float32x4(vreinterpretq_f32_u64(vld1q_u64(elems))); +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4(vld1q_f32(tab + idx[0])); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + tab[vgetq_lane_s32(idxvec.val, 2)], + tab[vgetq_lane_s32(idxvec.val, 3)] + }; + return v_int32x4(vld1q_s32(elems)); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + unsigned CV_DECL_ALIGNED(32) elems[4] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + tab[vgetq_lane_s32(idxvec.val, 2)], + tab[vgetq_lane_s32(idxvec.val, 3)] + }; + return v_uint32x4(vld1q_u32(elems)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + tab[vgetq_lane_s32(idxvec.val, 2)], + tab[vgetq_lane_s32(idxvec.val, 3)] + }; + return v_float32x4(vld1q_f32(elems)); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + /*int CV_DECL_ALIGNED(32) idx[4]; + v_store(idx, idxvec); + + float32x4_t xy02 = vcombine_f32(vld1_f32(tab + idx[0]), vld1_f32(tab + idx[2])); + float32x4_t xy13 = vcombine_f32(vld1_f32(tab + idx[1]), vld1_f32(tab + idx[3])); + + float32x4x2_t xxyy = vuzpq_f32(xy02, xy13); + x = v_float32x4(xxyy.val[0]); + y = v_float32x4(xxyy.val[1]);*/ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + x = v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); + y = v_float32x4(tab[idx[0]+1], tab[idx[1]+1], tab[idx[2]+1], tab[idx[3]+1]); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0705060403010200)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0705060403010200)))); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + return v_int8x16(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0703060205010400)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0703060205010400)))); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + return v_int16x8(vreinterpretq_s16_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100)), vtbl1_s8(vget_high_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0706030205040100))))); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + int16x4x2_t res = vzip_s16(vget_low_s16(vec.val), vget_high_s16(vec.val)); + return v_int16x8(vcombine_s16(res.val[0], res.val[1])); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + int32x2x2_t res = vzip_s32(vget_low_s32(vec.val), vget_high_s32(vec.val)); + return v_int32x4(vcombine_s32(res.val[0], res.val[1])); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + return v_int8x16(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vec.val), vcreate_s8(0x0605040201000000)), vtbl1_s8(vget_high_s8(vec.val), vcreate_s8(0x0807060504020100))), vdupq_n_s8(0), 2)); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + return v_int16x8(vreinterpretq_s16_s8(vextq_s8(vcombine_s8(vtbl1_s8(vget_low_s8(vreinterpretq_s8_s16(vec.val)), vcreate_s8(0x0504030201000000)), vget_high_s8(vreinterpretq_s8_s16(vec.val))), vdupq_n_s8(0), 2))); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +#if CV_SIMD128_64F +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + double CV_DECL_ALIGNED(32) elems[2] = + { + tab[idx[0]], + tab[idx[1]] + }; + return v_float64x2(vld1q_f64(elems)); +} + +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(vld1q_f64(tab + idx[0])); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + double CV_DECL_ALIGNED(32) elems[2] = + { + tab[vgetq_lane_s32(idxvec.val, 0)], + tab[vgetq_lane_s32(idxvec.val, 1)], + }; + return v_float64x2(vld1q_f64(elems)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + x = v_float64x2(tab[idx[0]], tab[idx[1]]); + y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); +} +#endif + +////// FP16 support /////// +#if CV_FP16 +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + float16x4_t v = + #ifndef vld1_f16 // APPLE compiler defines vld1_f16 as macro + (float16x4_t)vld1_s16((const short*)ptr); + #else + vld1_f16((const __fp16*)ptr); + #endif + return v_float32x4(vcvt_f32_f16(v)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + float16x4_t hv = vcvt_f16_f32(v.val); + + #ifndef vst1_f16 // APPLE compiler defines vst1_f16 as macro + vst1_s16((short*)ptr, (int16x4_t)hv); + #else + vst1_f16((__fp16*)ptr, hv); + #endif +} +#else +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + const int N = 4; + float buf[N]; + for( int i = 0; i < N; i++ ) buf[i] = (float)ptr[i]; + return v_load(buf); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + const int N = 4; + float buf[N]; + v_store(buf, v); + for( int i = 0; i < N; i++ ) ptr[i] = hfloat(buf[i]); +} +#endif + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +#if defined(CV_SIMD_FP16) && CV_SIMD_FP16 +inline v_float16x8 v_exp(const v_float16x8& x) { return v_exp_default_16f(x); } +inline v_float16x8 v_log(const v_float16x8& x) { return v_log_default_16f(x); } +inline void v_sincos(const v_float16x8& x, v_float16x8& s, v_float16x8& c) { v_sincos_default_16f(x, s, c); } +inline v_float16x8 v_sin(const v_float16x8& x) { return v_sin_default_16f(x); } +inline v_float16x8 v_cos(const v_float16x8& x) { return v_cos_default_16f(x); } +#endif +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } +#if CV_SIMD128_64F +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } +#endif + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp index bcd2662082..146335dc01 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv071.hpp @@ -1,2888 +1,2888 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -// Copyright (C) 2015, PingTouGe Semiconductor Co., Ltd., all rights reserved. - -#ifndef OPENCV_HAL_INTRIN_RISCVV_HPP -#define OPENCV_HAL_INTRIN_RISCVV_HPP - -#include -#include -#include "opencv2/core/utility.hpp" - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -//////////// Types //////////// -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16 }; - - v_uint8x16() {} - explicit v_uint8x16(vuint8m1_t v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = (vuint8m1_t)vle8_v_u8m1((unsigned char*)v, 16); - } - uchar get0() const - { - return vmv_x_s_u8m1_u8(val); - } - - vuint8m1_t val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(vint8m1_t v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = (vint8m1_t)vle8_v_i8m1((schar*)v, 16); - } - schar get0() const - { - return vmv_x_s_i8m1_i8(val); - } - - vint8m1_t val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(vuint16m1_t v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = (vuint16m1_t)vle16_v_u16m1((unsigned short*)v, 8); - } - ushort get0() const - { - return vmv_x_s_u16m1_u16(val); - } - - vuint16m1_t val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(vint16m1_t v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = (vint16m1_t)vle16_v_i16m1((signed short*)v, 8); - } - short get0() const - { - return vmv_x_s_i16m1_i16(val); - } - - vint16m1_t val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(vuint32m1_t v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - unsigned v[] = {v0, v1, v2, v3}; - val = (vuint32m1_t)vle32_v_u32m1((unsigned int*)v, 4); - } - unsigned get0() const - { - return vmv_x_s_u32m1_u32(val); - } - - vuint32m1_t val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(vint32m1_t v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = (vint32m1_t)vle32_v_i32m1((signed int*)v, 4); - } - int get0() const - { - return vmv_x_s_i32m1_i32(val); - } - vint32m1_t val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4 }; - - v_float32x4() {} - explicit v_float32x4(vfloat32m1_t v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = (vfloat32m1_t)vle32_v_f32m1((float*)v, 4); - } - float get0() const - { - return vfmv_f_s_f32m1_f32(val); - } - vfloat32m1_t val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2 }; - - v_uint64x2() {} - explicit v_uint64x2(vuint64m1_t v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = (vuint64m1_t)vle64_v_u64m1((unsigned long*)v, 2); - } - uint64 get0() const - { - return vmv_x_s_u64m1_u64(val); - } - vuint64m1_t val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2 }; - - v_int64x2() {} - explicit v_int64x2(vint64m1_t v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = (vint64m1_t)vle64_v_i64m1((long*)v, 2); - } - int64 get0() const - { - return vmv_x_s_i64m1_i64(val); - } - vint64m1_t val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2 }; - - v_float64x2() {} - explicit v_float64x2(vfloat64m1_t v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = (vfloat64m1_t)vle64_v_f64m1((double*)v, 2); - } - double get0() const - { - return vfmv_f_s_f64m1_f64(val); - } - vfloat64m1_t val; -}; -/* -#define OPENCV_HAL_IMPL_RISCVV_INIT(_Tpv, _Tp, suffix) \ -inline _Tp##m1_t vreinterpret_v_##suffix##m1_##suffix##m1(_Tp##m1_t v) { return v; } \ -inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16((vuint8m1_t)(v.val)); } \ -inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16((vint8m1_t)(v.val)); } \ -inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8((vuint16m1_t)(v.val)); } \ -inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } \ -inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4((vuint32m1_t)(v.val)); } \ -inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4((vint32m1_t)(v.val)); } \ -inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2((vuint64m1_t)(v.val)); } \ -inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2((vint64m1_t)(v.val)); } \ -inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4((vfloat32m1_t)(v.val)); }\ -inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2((vfloat64m1_t)(v.val)); } - - -OPENCV_HAL_IMPL_RISCVV_INIT(uint8x16, vuint8, u8) -OPENCV_HAL_IMPL_RISCVV_INIT(int8x16, vint8, i8) -OPENCV_HAL_IMPL_RISCVV_INIT(uint16x8, vuint16, u16) -OPENCV_HAL_IMPL_RISCVV_INIT(int16x8, vint16, i16) -OPENCV_HAL_IMPL_RISCVV_INIT(uint32x4, vuint32, u32) -OPENCV_HAL_IMPL_RISCVV_INIT(int32x4, vint32, i32) -OPENCV_HAL_IMPL_RISCVV_INIT(uint64x2, vuint64, u64) -OPENCV_HAL_IMPL_RISCVV_INIT(int64x2, vint64, i64) -OPENCV_HAL_IMPL_RISCVV_INIT(float64x2, vfloat64, f64) -OPENCV_HAL_IMPL_RISCVV_INIT(float32x4, vfloat32, f32) -*/ -inline v_uint8x16 v_reinterpret_as_u8(const v_uint8x16& v) { return v_uint8x16(v.val); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint8x16& v) { return v_int8x16(vreinterpret_v_u8m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint8x16& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(vreinterpret_v_u8m1_u16m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint8x16& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u8m1_u32m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint8x16& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u8m1_u64m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint8x16& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u8m1_u32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint8x16& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u8m1_u64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int8x16& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_int8x16& v) { return v_int8x16(v.val); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(vreinterpret_v_i8m1_u8m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_int8x16& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(vreinterpret_v_i8m1_u8m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_int8x16& v) { return v_int32x4(vreinterpret_v_i8m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(vreinterpret_v_i8m1_u8m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_int8x16& v) { return v_int64x2(vreinterpret_v_i8m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int8x16& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i8m1_i32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_int8x16& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i8m1_i64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_uint16x8& v) { return v_uint8x16(vreinterpret_v_u16m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(vreinterpret_v_u16m1_i16m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint16x8& v) { return v_uint16x8(v.val); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint16x8& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint16x8& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u16m1_u32m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint16x8& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u16m1_u64m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint16x8& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u16m1_u32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint16x8& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u16m1_u64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int16x8& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_int16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int16x8& v) { return v_uint16x8(vreinterpret_v_i16m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_int16x8& v) { return v_int16x8(v.val); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(vreinterpret_v_i16m1_u16m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_int16x8& v) { return v_int32x4(vreinterpret_v_i16m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(vreinterpret_v_i16m1_u16m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_int16x8& v) { return v_int64x2(vreinterpret_v_i16m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int16x8& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i16m1_i32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_int16x8& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i16m1_i64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_uint32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_u32m1_i32m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_u32m1_i32m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint32x4& v) { return v_uint32x4(v.val); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint32x4& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint32x4& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u32m1_u64m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint32x4& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(v.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint32x4& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u32m1_u64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int32x4& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_int32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_i32m1_u32m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_int32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int32x4& v) { return v_uint32x4(vreinterpret_v_i32m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_int32x4& v) { return v_int32x4(v.val); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_i32m1_u32m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_int32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int32x4& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(v.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_int32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(v.val))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_uint64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(v.val)); } -inline v_int8x16 v_reinterpret_as_s8(const v_uint64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_u64m1_i64m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_uint64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(v.val)); } -inline v_int16x8 v_reinterpret_as_s16(const v_uint64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_u64m1_i64m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_uint64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_uint64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_u64m1_i64m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_uint64x2& v) { return v_uint64x2(v.val); } -inline v_int64x2 v_reinterpret_as_s64(const v_uint64x2& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u64m1_u32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(v.val)); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_int64x2& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_int64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(v.val)); } -inline v_uint16x8 v_reinterpret_as_u16(const v_int64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_i64m1_u64m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_int64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(v.val)); } -inline v_uint32x4 v_reinterpret_as_u32(const v_int64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_i64m1_u64m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_int64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_int64x2& v) { return v_uint64x2(vreinterpret_v_i64m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_int64x2& v) { return v_int64x2(v.val); } -inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(v.val))); } -inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(v.val)); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_float32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(vreinterpret_v_f32m1_u32m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_float32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_f32m1_i32m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_float32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_f32m1_u32m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_float32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_f32m1_i32m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_float32x4& v) { return v_uint32x4(vreinterpret_v_f32m1_u32m1(v.val)); } -inline v_int32x4 v_reinterpret_as_s32(const v_float32x4& v) { return v_int32x4(vreinterpret_v_f32m1_i32m1(v.val)); } -inline v_uint64x2 v_reinterpret_as_u64(const v_float32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_f32m1_u32m1(v.val))); } -inline v_int64x2 v_reinterpret_as_s64(const v_float32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val))); } -inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& v) { return v_float32x4(v.val); } -inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val)))); } - -inline v_uint8x16 v_reinterpret_as_u8(const v_float64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(vreinterpret_v_f64m1_u64m1(v.val))); } -inline v_int8x16 v_reinterpret_as_s8(const v_float64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_f64m1_i64m1(v.val))); } -inline v_uint16x8 v_reinterpret_as_u16(const v_float64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_f64m1_u64m1(v.val))); } -inline v_int16x8 v_reinterpret_as_s16(const v_float64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_f64m1_i64m1(v.val))); } -inline v_uint32x4 v_reinterpret_as_u32(const v_float64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_f64m1_u64m1(v.val))); } -inline v_int32x4 v_reinterpret_as_s32(const v_float64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val))); } -inline v_uint64x2 v_reinterpret_as_u64(const v_float64x2& v) { return v_uint64x2(vreinterpret_v_f64m1_u64m1(v.val)); } -inline v_int64x2 v_reinterpret_as_s64(const v_float64x2& v) { return v_int64x2(vreinterpret_v_f64m1_i64m1(v.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val)))); } -inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& v) { return v_float64x2(v.val); } - -#define OPENCV_HAL_IMPL_RISCVV_INIT_SET(__Tp, _Tp, suffix, len, num) \ -inline v_##_Tp##x##num v_setzero_##suffix() { return v_##_Tp##x##num(vmv_v_x_##len##m1(0, num)); } \ -inline v_##_Tp##x##num v_setall_##suffix(__Tp v) { return v_##_Tp##x##num(vmv_v_x_##len##m1(v, num)); } \ -template <> inline v_##_Tp##x##num v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline v_##_Tp##x##num v_setall_(__Tp v) { return v_setall_##suffix(v); } - -OPENCV_HAL_IMPL_RISCVV_INIT_SET(uchar, uint8, u8, u8, 16) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(schar, int8, s8, i8, 16) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(ushort, uint16, u16, u16, 8) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(short, int16, s16, i16, 8) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned int, uint32, u32, u32, 4) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(int, int32, s32, i32, 4) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned long, uint64, u64, u64, 2) -OPENCV_HAL_IMPL_RISCVV_INIT_SET(long, int64, s64, i64, 2) -inline v_float32x4 v_setzero_f32() { return v_float32x4(vfmv_v_f_f32m1(0, 4)); } -inline v_float32x4 v_setall_f32(float v) { return v_float32x4(vfmv_v_f_f32m1(v, 4)); } - -inline v_float64x2 v_setzero_f64() { return v_float64x2(vfmv_v_f_f64m1(0, 2)); } -inline v_float64x2 v_setall_f64(double v) { return v_float64x2(vfmv_v_f_f64m1(v, 2)); } - -template <> inline v_float32x4 v_setzero_() { return v_setzero_f32(); } -template <> inline v_float32x4 v_setall_(float v) { return v_setall_f32(v); } - -template <> inline v_float64x2 v_setzero_() { return v_setzero_f64(); } -template <> inline v_float64x2 v_setall_(double v) { return v_setall_f64(v); } - -#define OPENCV_HAL_IMPL_RISCVV_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -#define OPENCV_HAL_IMPL_RISCVV_BIN_OPN(bin_op, _Tpvec, intrin, num) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val, num)); \ -} - -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint8x16, vsaddu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint8x16, vssubu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int8x16, vsadd_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int8x16, vssub_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint16x8, vsaddu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint16x8, vssubu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int16x8, vsadd_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int16x8, vssub_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int32x4, vadd_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int32x4, vsub_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_int32x4, vmul_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint32x4, vadd_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint32x4, vsub_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_uint32x4, vmul_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int64x2, vadd_vv_i64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int64x2, vsub_vv_i64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint64x2, vadd_vv_u64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint64x2, vsub_vv_u64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float32x4, vfadd_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float32x4, vfsub_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float32x4, vfmul_vv_f32m1, 4) -inline v_float32x4 v_div(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vfdiv_vv_f32m1(a.val, b.val, 4)); -} - -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float64x2, vfadd_vv_f64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float64x2, vfsub_vv_f64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float64x2, vfmul_vv_f64m1, 2) -inline v_float64x2 v_div(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vfdiv_vv_f64m1(a.val, b.val, 2)); -} -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_RISCVV_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -#define OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(_Tpvec, func, intrin, num) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val, num)); \ -} -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_min, vminu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_max, vmaxu_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_min, vmin_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_max, vmax_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_min, vminu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_max, vmaxu_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_min, vmin_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_max, vmax_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_min, vminu_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_max, vmaxu_vv_u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_min, vmin_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_max, vmax_vv_i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_min, vfmin_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_max, vfmax_vv_f32m1, 4) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_min, vfmin_vv_f64m1, 2) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_max, vfmax_vv_f64m1, 2) - -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - return v_float32x4(vfsqrt_v_f32m1(x.val, 4)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - return v_float32x4(vfrdiv_vf_f32m1(vfsqrt_v_f32m1(x.val, 4), 1, 4)); -} - -inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - v_float32x4 x(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); - return v_sqrt(x); -} - -inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_float32x4(vfmadd_vv_f32m1(a.val, b.val, c.val, 4)); -} - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_int32x4(vmadd_vv_i32m1(a.val, b.val, c.val, 4)); -} - -inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 3, 4), m3.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - return v_float32x4(res); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - res = vfadd_vv_f32m1(res, a.val, 4);//vmulai_f32(res, m1.val, v.val, 1); - return v_float32x4(res); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ - return v_float64x2(vfsqrt_v_f64m1(x.val, 2)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - return v_float64x2(vfrdiv_vf_f64m1(vfsqrt_v_f64m1(x.val, 2), 1, 2)); -} - -inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - v_float64x2 x(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); - return v_sqrt(x); -} - -inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_float64x2(vfmadd_vv_f64m1(a.val, b.val, c.val, 2)); -} - -inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_fma(a, b, c); -} - -#define OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(_Tpvec, suffix, num) \ - OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_and, _Tpvec, vand_vv_##suffix, num) \ - OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_or, _Tpvec, vor_vv_##suffix, num) \ - OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_xor, _Tpvec, vxor_vv_##suffix, num) \ - inline _Tpvec v_not(const _Tpvec & a) \ - { \ - return _Tpvec(vnot_v_##suffix(a.val, num)); \ - } - -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint8x16, u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint16x8, u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint32x4, u32m1, 4) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint64x2, u64m1, 2) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int8x16, i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int16x8, i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int32x4, i32m1, 4) -OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int64x2, i64m1, 2) - -#define OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(bin_op, intrin) \ -inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ -{ \ - return v_float32x4(vreinterpret_v_i32m1_f32m1(intrin(vreinterpret_v_f32m1_i32m1(a.val), vreinterpret_v_f32m1_i32m1(b.val), 4))); \ -} - -OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_and, vand_vv_i32m1) -OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_or, vor_vv_i32m1) -OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_xor, vxor_vv_i32m1) - -inline v_float32x4 v_not(const v_float32x4& a) -{ - return v_float32x4(vreinterpret_v_i32m1_f32m1(vnot_v_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 4))); -} - -#define OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(bin_op, intrin) \ -inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ -{ \ - return v_float64x2(vreinterpret_v_i64m1_f64m1(intrin(vreinterpret_v_f64m1_i64m1(a.val), vreinterpret_v_f64m1_i64m1(b.val), 2))); \ -} - -OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_and, vand_vv_i64m1) -OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_or, vor_vv_i64m1) -OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_xor, vxor_vv_i64m1) - -inline v_float64x2 v_not(const v_float64x2& a) -{ - return v_float64x2(vreinterpret_v_i64m1_f64m1(vnot_v_i64m1(vreinterpret_v_f64m1_i64m1(a.val), 2))); -} -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - return v_int16x8(vmulh_vv_i16m1(a.val, b.val, 8)); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - return v_uint16x8(vmulhu_vv_u16m1(a.val, b.val, 8)); -} - -//#define OPENCV_HAL_IMPL_RISCVV_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ -//inline _Tpuvec v_abs(const _Tpsvec& a) { \ -// E##xm1_t mask=vmflt_vf_e32xm1_f32m1(x.val, 0.0, 4); - -//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint8x16, v_int8x16, u8, s8) -//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint16x8, v_int16x8, u16, s16) -//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint32x4, v_int32x4, u32, s32) - -inline v_uint32x4 v_abs(v_int32x4 x) -{ - vbool32_t mask=vmslt_vx_i32m1_b32(x.val, 0, 4); - return v_uint32x4(vreinterpret_v_i32m1_u32m1(vrsub_vx_i32m1_m(mask, x.val, x.val, 0, 4))); -} - -inline v_uint16x8 v_abs(v_int16x8 x) -{ - vbool16_t mask=vmslt_vx_i16m1_b16(x.val, 0, 8); - return v_uint16x8(vreinterpret_v_i16m1_u16m1(vrsub_vx_i16m1_m(mask, x.val, x.val, 0, 8))); -} - -inline v_uint8x16 v_abs(v_int8x16 x) -{ - vbool8_t mask=vmslt_vx_i8m1_b8(x.val, 0, 16); - return v_uint8x16(vreinterpret_v_i8m1_u8m1(vrsub_vx_i8m1_m(mask, x.val, x.val, 0, 16))); -} - -inline v_float32x4 v_abs(v_float32x4 x) -{ - return (v_float32x4)vfsgnjx_vv_f32m1(x.val, x.val, 4); -} - -inline v_float64x2 v_abs(v_float64x2 x) -{ - return (v_float64x2)vfsgnjx_vv_f64m1(x.val, x.val, 2); -} - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ - vfloat32m1_t ret = vfsub_vv_f32m1(a.val, b.val, 4); - return (v_float32x4)vfsgnjx_vv_f32m1(ret, ret, 4); -} - -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ - vfloat64m1_t ret = vfsub_vv_f64m1(a.val, b.val, 2); - return (v_float64x2)vfsgnjx_vv_f64m1(ret, ret, 2); -} - -#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(bit, num) \ -inline v_uint##bit##x##num v_absdiff(v_uint##bit##x##num a, v_uint##bit##x##num b){ \ - vuint##bit##m1_t vmax = vmaxu_vv_u##bit##m1(a.val, b.val, num); \ - vuint##bit##m1_t vmin = vminu_vv_u##bit##m1(a.val, b.val, num); \ - return v_uint##bit##x##num(vsub_vv_u##bit##m1(vmax, vmin, num));\ -} - -OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(8, 16) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(16, 8) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(32, 4) - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(v_int8x16 a, v_int8x16 b){ - vint8m1_t vmax = vmax_vv_i8m1(a.val, b.val, 16); - vint8m1_t vmin = vmin_vv_i8m1(a.val, b.val, 16); - return v_int8x16(vssub_vv_i8m1(vmax, vmin, 16)); -} -inline v_int16x8 v_absdiffs(v_int16x8 a, v_int16x8 b){ - vint16m1_t vmax = vmax_vv_i16m1(a.val, b.val, 8); - vint16m1_t vmin = vmin_vv_i16m1(a.val, b.val, 8); - return v_int16x8(vssub_vv_i16m1(vmax, vmin, 8)); -} - -#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF(_Tpvec, _Tpv, num) \ -inline v_uint##_Tpvec v_absdiff(v_int##_Tpvec a, v_int##_Tpvec b){ \ - vint##_Tpv##_t max = vmax_vv_i##_Tpv(a.val, b.val, num);\ - vint##_Tpv##_t min = vmin_vv_i##_Tpv(a.val, b.val, num);\ - return v_uint##_Tpvec(vreinterpret_v_i##_Tpv##_u##_Tpv(vsub_vv_i##_Tpv(max, min, num))); \ -} - -OPENCV_HAL_IMPL_RISCVV_ABSDIFF(8x16, 8m1, 16) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF(16x8, 16m1, 8) -OPENCV_HAL_IMPL_RISCVV_ABSDIFF(32x4, 32m1, 4) - -// Multiply and expand -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - vint16m2_t res = vundefined_i16m2(); - res = vwmul_vv_i16m2(a.val, b.val, 16); - c.val = vget_v_i16m2_i16m1(res, 0); - d.val = vget_v_i16m2_i16m1(res, 1); -} - -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - vuint16m2_t res = vundefined_u16m2(); - res = vwmulu_vv_u16m2(a.val, b.val, 16); - c.val = vget_v_u16m2_u16m1(res, 0); - d.val = vget_v_u16m2_u16m1(res, 1); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - vint32m2_t res = vundefined_i32m2(); - res = vwmul_vv_i32m2(a.val, b.val, 8); - c.val = vget_v_i32m2_i32m1(res, 0); - d.val = vget_v_i32m2_i32m1(res, 1); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - vuint32m2_t res = vundefined_u32m2(); - res = vwmulu_vv_u32m2(a.val, b.val, 8); - c.val = vget_v_u32m2_u32m1(res, 0); - d.val = vget_v_u32m2_u32m1(res, 1); -} - -inline void v_mul_expand(const v_int32x4& a, const v_int32x4& b, - v_int64x2& c, v_int64x2& d) -{ - vint64m2_t res = vundefined_i64m2(); - res = vwmul_vv_i64m2(a.val, b.val, 4); - c.val = vget_v_i64m2_i64m1(res, 0); - d.val = vget_v_i64m2_i64m1(res, 1); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - vuint64m2_t res = vundefined_u64m2(); - res = vwmulu_vv_u64m2(a.val, b.val, 4); - c.val = vget_v_u64m2_u64m1(res, 0); - d.val = vget_v_u64m2_u64m1(res, 1); -} - -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_add_wrap, vadd_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_add_wrap, vadd_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_add_wrap, vadd_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_add_wrap, vadd_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_sub_wrap, vsub_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_sub_wrap, vsub_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_sub_wrap, vsub_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_sub_wrap, vsub_vv_i16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_mul_wrap, vmul_vv_u8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_mul_wrap, vmul_vv_i8m1, 16) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_mul_wrap, vmul_vv_u16m1, 8) -OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_mul_wrap, vmul_vv_i16m1, 8) -//////// Dot Product //////// -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - vuint32m2_t vindex = vundefined_u32m2(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 1, 4); - vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); - vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vint32m2_t res = vundefined_i32m2(); - res = vwmul_vv_i32m2(a.val, b.val, 8); - res = vrgather_vv_i32m2(res, vindex, 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0), vget_v_i32m2_i32m1(res, 1), 4)); -} -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - vuint32m2_t vindex = vundefined_u32m2(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 1, 4); - vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); - vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vint32m2_t res = vundefined_i32m2(); - res = vwmul_vv_i32m2(a.val, b.val, 8); - res = vrgather_vv_i32m2(res, vindex, 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0),vget_v_i32m2_i32m1(res, 1), 4), c.val, 4)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - vuint64m2_t vindex = vundefined_u64m2(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 1, 2); - vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); - vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vint64m2_t res = vundefined_i64m2(); - res = vwmul_vv_i64m2(a.val, b.val, 4); - res = vrgather_vv_i64m2(res, vindex, 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - vuint64m2_t vindex = vundefined_u64m2(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 1, 2); - vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); - vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vint64m2_t res = vundefined_i64m2(); - res = vwmul_vv_i64m2(a.val, b.val, 4); - res = vrgather_vv_i64m2(res, vindex, 4); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2), c.val, 2)); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v1 = vrgather_vv_u16m2(v1, vindex, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); -} - -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, - const v_uint32x4& c) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v1 = vrgather_vv_u16m2(v1, vindex, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v1 = vrgather_vv_i16m2(v1, vindex, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, - const v_int32x4& c) -{ - vuint32m4_t vindex32 = vundefined_u32m4(); - vuint32m1_t vindex0 = vid_v_u32m1(4); - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); - vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); - vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); - vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); - vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v1 = vrgather_vv_i16m2(v1, vindex, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); -} - -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v1 = vrgather_vv_u32m2(v1, vindex, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); -} - -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, - const v_uint64x2& c) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v1 = vrgather_vv_u32m2(v1, vindex, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v1 = vrgather_vv_i32m2(v1, vindex, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, - const v_int64x2& c) -{ - vuint64m4_t vindex64 = vundefined_u64m4(); - vuint64m1_t vindex0 = vid_v_u64m1(2); - vindex0 = vsll_vx_u64m1(vindex0, 2, 2); - vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); - vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); - vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); - vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v1 = vrgather_vv_i32m2(v1, vindex, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); -} - -//////// Fast Dot Product //////// -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ - vint32m2_t v1 = vundefined_i32m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4)); -} - -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ - vint32m2_t v1 = vundefined_i32m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4), c.val, 4)); -} - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ - vint64m2_t v1 = vundefined_i64m2(); - v1 = vwmul_vv_i64m2(a.val, b.val, 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2)); -} -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - vint64m2_t v1 = vundefined_i64m2(); - v1 = vwmul_vv_i64m2(a.val, b.val, 8); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 4), c.val, 4)); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); -} - -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ - vuint16m2_t v1 = vundefined_u16m2(); - vuint32m2_t v2 = vundefined_u32m2(); - v1 = vwmulu_vv_u16m2(a.val, b.val, 16); - v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); - return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); -} - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ - vint16m2_t v1 = vundefined_i16m2(); - vint32m2_t v2 = vundefined_i32m2(); - v1 = vwmul_vv_i16m2(a.val, b.val, 16); - v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); - return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); -} - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ - vuint32m2_t v1 = vundefined_u32m2(); - vuint64m2_t v2 = vundefined_u64m2(); - v1 = vwmulu_vv_u32m2(a.val, b.val, 8); - v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); - return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); -} - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ - vint32m2_t v1 = vundefined_i32m2(); - vint64m2_t v2 = vundefined_i64m2(); - v1 = vwmul_vv_i32m2(a.val, b.val, 8); - v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); - return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); -} - - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(_Tpvec, _Tpvec2, len, scalartype, func, intrin, num) \ -inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ -{\ - v##_Tpvec2##m1_t val = vmv_v_x_##len##m1(0, num); \ - val = intrin(val, a.val, val, num); \ - return vmv_x_s_##len##m1_##len(val); \ -} - - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(_Tpvec, _Tpvec2, scalartype, func, funcu, num, scalerfunc) \ -inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ -{\ - v##_Tpvec##m1_t val = vundefined_##_Tpvec2##m1(); \ - val = v##funcu##_vs_##_Tpvec2##m1_##_Tpvec2##m1(val, a.val, a.val, num); \ - return scalerfunc(val); \ -} -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int8, int16, i16, int, sum, vwredsum_vs_i8m1_i16m1, 16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int16, int32, i32, int, sum, vwredsum_vs_i16m1_i32m1, 8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int32, int64, i64, int, sum, vwredsum_vs_i32m1_i64m1, 4) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint8, uint16, u16, unsigned, sum, vwredsumu_vs_u8m1_u16m1, 16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint16, uint32, u32, unsigned, sum, vwredsumu_vs_u16m1_u32m1, 8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint32, uint64, u64, unsigned, sum, vwredsumu_vs_u32m1_u64m1, 4) -inline float v_reduce_sum(const v_float32x4& a) \ -{\ - vfloat32m1_t val = vfmv_v_f_f32m1(0.0, 4); \ - val = vfredosum_vs_f32m1_f32m1(val, a.val, val, 4); \ - return vfmv_f_s_f32m1_f32(val); \ -} -inline double v_reduce_sum(const v_float64x2& a) \ -{\ - vfloat64m1_t val = vfmv_v_f_f64m1(0.0, 2); \ - val = vfredosum_vs_f64m1_f64m1(val, a.val, val, 2); \ - return vfmv_f_s_f64m1_f64(val); \ -} -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ vuint64m1_t res = vundefined_u64m1(); return vmv_x_s_u64m1_u64(vredsum_vs_u64m1_u64m1(res, a.val, vmv_v_x_u64m1(0, 2), 2)); } - -inline int64 v_reduce_sum(const v_int64x2& a) -{ vint64m1_t res = vundefined_i64m1(); return vmv_x_s_i64m1_i64(vredsum_vs_i64m1_i64m1(res, a.val, vmv_v_x_i64m1(0, 2), 2)); } - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(func) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int8, i8, int, func, red##func, 16, vmv_x_s_i8m1_i8) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int16, i16, int, func, red##func, 8, vmv_x_s_i16m1_i16) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int32, i32, int, func, red##func, 4, vmv_x_s_i32m1_i32) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int64, i64, int, func, red##func, 2, vmv_x_s_i64m1_i64) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint8, u8, unsigned, func, red##func##u, 16, vmv_x_s_u8m1_u8) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint16, u16, unsigned, func, red##func##u, 8, vmv_x_s_u16m1_u16) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint32, u32, unsigned, func, red##func##u, 4, vmv_x_s_u32m1_u32) \ -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(float32, f32, float, func, fred##func, 4, vfmv_f_s_f32m1_f32) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(max) -OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(min) - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t b0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t c0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t d0 = vfmv_v_f_f32m1(0.0, 4); - a0 = vfredosum_vs_f32m1_f32m1(a0, a.val, a0, 4); - b0 = vfredosum_vs_f32m1_f32m1(b0, b.val, b0, 4); - c0 = vfredosum_vs_f32m1_f32m1(c0, c.val, c0, 4); - d0 = vfredosum_vs_f32m1_f32m1(d0, d.val, d0, 4); - vfloat32m1_t res; - res = vslideup_vx_f32m1(a0, b0, 1, 4); - res = vslideup_vx_f32m1(res, c0, 2, 4); - res = vslideup_vx_f32m1(res, d0, 3, 4); - return v_float32x4(res); -} - -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); - vfloat32m1_t x = vfsub_vv_f32m1(a.val, b.val, 4); - vbool32_t mask=vmflt_vf_f32m1_b32(x, 0, 4); - vfloat32m1_t val = vfrsub_vf_f32m1_m(mask, x, x, 0, 4); - a0 = vfredosum_vs_f32m1_f32m1(a0, val, a0, 4); - return vfmv_f_s_f32m1_f32(a0); -} - -#define OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(_Tpvec, _Tpvec2) \ -inline unsigned v_reduce_sad(const _Tpvec& a, const _Tpvec&b){ \ - _Tpvec2 x = v_absdiff(a, b); \ - return v_reduce_sum(x); \ -} - -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int8x16, v_uint8x16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint8x16, v_uint8x16) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int16x8, v_uint16x8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint16x8, v_uint16x8) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int32x4, v_uint32x4) -OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint32x4, v_uint32x4) - -#define OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(_Tpvec, _Tp, _T, num, uv) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmseq_vv_##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmsne_vv_##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(b.val, a.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(a.val, b.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ \ - vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(b.val, a.val, num); \ - return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ -} \ - -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int8x16, i8m1, 8, 16, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int16x8, i16m1, 16, 8, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int32x4, i32m1, 32, 4, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int64x2, i64m1, 64, 2, _vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint8x16, u8m1, 8, 16, u_vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint16x8, u16m1, 16, 8, u_vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint32x4, u32m1, 32, 4, u_vv_) -OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint64x2, u64m1, 64, 2, u_vv_) - -//TODO: == -inline v_float32x4 v_eq(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_ne(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfne_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_lt(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmflt_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_le(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfle_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_gt(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfgt_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} -inline v_float32x4 v_ge(const v_float32x4& a, const v_float32x4& b) -{ - vbool32_t mask = vmfge_vv_f32m1_b32(a.val, b.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -}/**/ -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ - vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, a.val, 4); - vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); - return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); -} - -//TODO: == -inline v_float64x2 v_eq(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_ne(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfne_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_lt(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmflt_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_le(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfle_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_gt(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfgt_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -inline v_float64x2 v_ge(const v_float64x2& a, const v_float64x2& b) -{ - vbool64_t mask = vmfge_vv_f64m1_b64(a.val, b.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -}/**/ -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ - vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, a.val, 2); - vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); - return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); -} -#define OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(_Tp, _T) \ -inline void v_transpose4x4(const v_##_Tp##32x4& a0, const v_##_Tp##32x4& a1, \ - const v_##_Tp##32x4& a2, const v_##_Tp##32x4& a3, \ - v_##_Tp##32x4& b0, v_##_Tp##32x4& b1, \ - v_##_Tp##32x4& b2, v_##_Tp##32x4& b3) \ -{ \ - vuint32m4_t vindex = vundefined_u32m4(); \ - vuint32m1_t vindex0 = vid_v_u32m1(4); \ - vindex0 = vsll_vx_u32m1(vindex0, 2, 4); \ - vindex = vset_v_u32m1_u32m4(vindex, 0, vindex0); \ - vindex = vset_v_u32m1_u32m4(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); \ - vindex = vset_v_u32m1_u32m4(vindex, 2, vadd_vx_u32m1(vindex0, 2, 4)); \ - vindex = vset_v_u32m1_u32m4(vindex, 3, vadd_vx_u32m1(vindex0, 3, 4)); \ - v##_Tp##32m4_t val = vundefined_##_T##m4(); \ - val = vset_v_##_T##m1_##_T##m4(val, 0, a0.val); \ - val = vset_v_##_T##m1_##_T##m4(val, 1, a1.val); \ - val = vset_v_##_T##m1_##_T##m4(val, 2, a2.val); \ - val = vset_v_##_T##m1_##_T##m4(val, 3, a3.val); \ - val = vrgather_vv_##_T##m4(val, vindex, 16); \ - b0.val = vget_v_##_T##m4_##_T##m1(val, 0); \ - b1.val = vget_v_##_T##m4_##_T##m1(val, 1); \ - b2.val = vget_v_##_T##m4_##_T##m1(val, 2); \ - b3.val = vget_v_##_T##m4_##_T##m1(val, 3); \ -} -OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(uint, u32) -OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(int, i32) -OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(float, f32) - - -#define OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(_Tpvec, suffix, _T, num) \ -inline _Tpvec v_shl(const _Tpvec& a, int n) \ -{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } - -#define OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(_Tpvec, suffix, _T, num, intric) \ -inline _Tpvec v_shr(const _Tpvec& a, int n) \ -{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); }\ -template inline _Tpvec v_rshr(const _Tpvec& a) \ -{ return _Tpvec((v##intric##_vx_##_T##m1(vadd_vx_##_T##m1(a.val, 1<<(n-1), num), n, num))); } - -// trade efficiency for convenience -#define OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(suffix, _T, num, intrin) \ -OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(v_##suffix##x##num, suffix, _T, num) \ -OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(v_##suffix##x##num, suffix, _T, num, intrin) - -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint8, u8, 16, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint16, u16, 8, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint32, u32, 4, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint64, u64, 2, srl) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int8, i8, 16, sra) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int16, i16, 8, sra) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int32, i32, 4, sra) -OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int64, i64, 2, sra) - -#if 0 -#define VUP4(n) {0, 1, 2, 3} -#define VUP8(n) {0, 1, 2, 3, 4, 5, 6, 7} -#define VUP16(n) {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} -#define VUP2(n) {0, 1} -#endif -#define OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(_Tpvec, suffix, _T, num, num2, vmv, len) \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - suffix##m1_t tmp = vmv##_##_T##m1(0, num);\ - tmp = vslideup_vx_##_T##m1_m(vmset_m_##len(num), tmp, a.val, n, num);\ - return _Tpvec(tmp);\ -} \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - suffix##m1_t res = vundefined_##_T##m1(); \ - return _Tpvec(vslidedown_vx_##_T##m1(res, a.val, n, num));\ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - suffix##m2_t tmp = vundefined_##_T##m2(); \ - suffix##m2_t res = vundefined_##_T##m2(); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, b.val); \ - res = vslidedown_vx_##_T##m2(res, tmp, n, num2);\ - return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 0));\ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - suffix##m2_t tmp = vundefined_##_T##m2(); \ - suffix##m2_t res = vundefined_##_T##m2(); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, b.val); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a.val); \ - res = vslideup_vx_##_T##m2(res, tmp, n, num2);\ - return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 1));\ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ \ - CV_UNUSED(b); return a; \ -} - -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint8x16, vuint8, u8, 16, 32, vmv_v_x, b8) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int8x16, vint8, i8, 16, 32, vmv_v_x, b8) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint16x8, vuint16, u16, 8, 16, vmv_v_x, b16) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int16x8, vint16, i16, 8, 16, vmv_v_x, b16) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint32x4, vuint32, u32, 4, 8, vmv_v_x, b32) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int32x4, vint32, i32, 4, 8, vmv_v_x, b32) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint64x2, vuint64, u64, 2, 4, vmv_v_x, b64) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int64x2, vint64, i64, 2, 4, vmv_v_x, b64) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float32x4, vfloat32, f32, 4, 8, vfmv_v_f, b32) -OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float64x2, vfloat64, f64, 2, 4, vfmv_v_f, b64) - -#if 1 -#define vreinterpret_v_i8m1_i8m1 -#define vreinterpret_v_u8m1_u8m1 -#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize, ldst_len, ldst_type) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp2##_t res = vundefined_##len(); \ - _Tp2##_t res1 = vundefined_##len(); \ - res = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr0, 8)); \ - res1 = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr1, 8)); \ - res = vslideup_vx_##len(res, res1, hnum, num); \ - return _Tpvec(res); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 8))); }\ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 16))); } \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 8);}\ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tp2##_t a0 = vundefined_##len(); \ - a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ - vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a0), 8);}\ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } - -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8, i8m1, schar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16, i8m1, schar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32, i8m1, schar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64, u8m1, uchar) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64, i8m1, schar) - -#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp2##_t res = vundefined_##len(); \ - _Tp2##_t res1 = vundefined_##len(); \ - res = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr0, 8))); \ - res1 = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr1, 8))); \ - res = vslideup_vx_##len(res, res1, hnum, num); \ - return _Tpvec(res); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 8)))); }\ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 16)))); } \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 8);}\ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tp2##_t a0 = vundefined_##len(); \ - a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ - vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a0)), 8);}\ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) - -#else - -#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp2##_t res, res1; \ - res = vle##elemsize##_v_##len(ptr0, hnum); \ - res1 = vle##elemsize##_v_##len(ptr1, hnum); \ - res = vslideup_vx_##len(res, res1, hnum, num); \ - return _Tpvec(res); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, hnum)); }\ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec((_Tp2##_t)vle##elemsize##_v_##len((const _Tp *)ptr, num)); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, hnum);}\ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tp2##_t a0; \ - a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ - vse##elemsize##_v_##len(ptr, a0, hnum);}\ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ vse##elemsize##_v_##len(ptr, a.val, num); } - -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) -OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) - -#endif - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ -#if 0 - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[ 0]], - tab[idx[ 1]], - tab[idx[ 2]], - tab[idx[ 3]], - tab[idx[ 4]], - tab[idx[ 5]], - tab[idx[ 6]], - tab[idx[ 7]], - tab[idx[ 8]], - tab[idx[ 9]], - tab[idx[10]], - tab[idx[11]], - tab[idx[12]], - tab[idx[13]], - tab[idx[14]], - tab[idx[15]] - }; - return v_int8x16(vle8_v_i8m1(elems, 16)); -#else -#if __riscv_v == 7000 - return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, vle32_v_u32m4((unsigned int *)idx, 16), 16), 0, 16), 0, 16)); -#else - return v_int8x16(vloxei32_v_i8m1(tab, vle32_v_u32m4((unsigned int *)idx, 16), 16)); -#endif -#endif -} - -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx){ -#if 0 - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[4]], - tab[idx[4] + 1], - tab[idx[5]], - tab[idx[5] + 1], - tab[idx[6]], - tab[idx[6] + 1], - tab[idx[7]], - tab[idx[7] + 1] - }; - return v_int8x16(vle8_v_i8m1(elems, 16)); -#else - vuint32m4_t seq, index; - vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 8); - seq = vid_v_u32m4(16); - index = vsrl_vx_u32m4(seq, 1, 16); - vidx = vrgather_vv_u32m4(vidx, index, 16); - index = vadd_vv_u32m4(vand_vx_u32m4(seq, 1, 16), vidx, 16); -#if __riscv_v == 7000 - return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); -#else - return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); -#endif -#endif -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ -#if 0 - schar CV_DECL_ALIGNED(32) elems[16] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[2] + 2], - tab[idx[2] + 3], - tab[idx[3]], - tab[idx[3] + 1], - tab[idx[3] + 2], - tab[idx[3] + 3] - }; - return v_int8x16(vle8_v_i8m1(elems, 16)); -#else - vuint32m4_t seq, index; - vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 4); - seq = vid_v_u32m4(16); - index = vsrl_vx_u32m4(seq, 2, 16); - vidx = vrgather_vv_u32m4(vidx, index, 16); - seq = vset_v_u32m1_u32m4(seq, 1, vget_v_u32m4_u32m1(seq, 0)); - seq = vset_v_u32m1_u32m4(seq, 2, vget_v_u32m4_u32m1(seq, 0)); - seq = vset_v_u32m1_u32m4(seq, 3, vget_v_u32m4_u32m1(seq, 0)); - index = vadd_vv_u32m4(seq, vidx, 16); -#if __riscv_v == 7000 - return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); -#else - return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); -#endif -#endif -} - -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ -#if 0 - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]], - tab[idx[4]], - tab[idx[5]], - tab[idx[6]], - tab[idx[7]] - }; - return v_int16x8(vle16_v_i16m1(elems, 8)); -#else -#if __riscv_v == 7000 - return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8), 0, 8)); -#else - return v_int16x8(vloxei32_v_i16m1(tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8)); -#endif -#endif -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ -#if 0 - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[2]], - tab[idx[2] + 1], - tab[idx[3]], - tab[idx[3] + 1] - }; - return v_int16x8(vle16_v_i16m1(elems, 8)); -#else - vuint32m2_t seq, index; - vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 4); - seq = vid_v_u32m2(8); - index = vsrl_vx_u32m2(seq, 1, 8); - vidx = vrgather_vv_u32m2(vidx, index, 8); - index = vsll_vx_u32m2(vadd_vv_u32m2(vand_vx_u32m2(seq, 1, 8), vidx, 8), 1, 8); -#if __riscv_v == 7000 - return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); -#else - return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); -#endif -#endif -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ -#if 0 - short CV_DECL_ALIGNED(32) elems[8] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[0] + 2], - tab[idx[0] + 3], - tab[idx[1]], - tab[idx[1] + 1], - tab[idx[1] + 2], - tab[idx[1] + 3] - }; - return v_int16x8(vle16_v_i16m1(elems, 8)); -#else - vuint32m2_t seq, index; - vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 2); - seq = vid_v_u32m2(8); - index = vsrl_vx_u32m2(seq, 2, 8); - vidx = vrgather_vv_u32m2(vidx, index, 8); - seq = vset_v_u32m1_u32m2(seq, 1, vget_v_u32m2_u32m1(seq, 0)); - index = vsll_vx_u32m2(vadd_vv_u32m2(seq, vidx, 8), 1, 8); -#if __riscv_v == 7000 - return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); -#else - return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); -#endif -#endif -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ -#if 0 - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_int32x4(vle32_v_i32m1(elems, 4)); -#else - return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); -#endif -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ -#if 0 - int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[0] + 1], - tab[idx[1]], - tab[idx[1] + 1] - }; - return v_int32x4(vle32_v_i32m1(elems, 4)); -#else - vuint32m1_t seq, index; - vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); - seq = vid_v_u32m1(4); - index = vsrl_vx_u32m1(seq, 1, 4); - vidx = vrgather_vv_u32m1(vidx, index, 4); - index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); - return v_int32x4(vloxei32_v_i32m1(tab, index, 4)); -#endif -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(vle32_v_i32m1(tab+idx[0], 4)); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - //vint64m1_t res = {tab[idx[0]], tab[idx[1]]}; - return v_int64x2(vloxei64_v_i64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(vle64_v_i64m1(tab+idx[0], 2)); -} - -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) -{ - //vuint64m1_t res = {tab[idx[0]], tab[idx[1]]}; - return v_uint64x2(vloxei64_v_u64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); -} -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) -{ - return v_uint64x2(vle64_v_u64m1(tab+idx[0], 2)); -} - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ -#if 0 - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[1]], - tab[idx[2]], - tab[idx[3]] - }; - return v_float32x4(vle32_v_f32m1(elems, 4)); -#else - return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); -#endif -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) -{ -#if 0 - float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idx[0]], - tab[idx[0]+1], - tab[idx[1]], - tab[idx[1]+1] - }; - return v_float32x4(vle32_v_f32m1(elems, 4)); -#else - vuint32m1_t seq, index; - vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); - seq = vid_v_u32m1(4); - index = vsrl_vx_u32m1(seq, 1, 4); - vidx = vrgather_vv_u32m1(vidx, index, 4); - index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); - return v_float32x4(vloxei32_v_f32m1(tab, index, 4)); -#endif -} -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) -{ - return v_float32x4(vle32_v_f32m1(tab + idx[0], 4)); -} -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - //vfloat64m1_t res = {tab[idx[0]], tab[idx[1]]}; - return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(vle64_v_f64m1(tab+idx[0], 2)); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - /*int CV_DECL_ALIGNED(32) elems[4] = - { - tab[idxvec.val[0]], - tab[idxvec.val[1]], - tab[idxvec.val[2]], - tab[idxvec.val[3]] - };*/ - return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - /*unsigned CV_DECL_ALIGNED(32) elems[4] = - { - tab[idxvec.val[0]], - tab[idxvec.val[1]], - tab[idxvec.val[2]], - tab[idxvec.val[3]] - };*/ - return v_uint32x4(vloxei32_v_u32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - /*float CV_DECL_ALIGNED(32) elems[4] = - { - tab[idxvec.val[0]], - tab[idxvec.val[1]], - tab[idxvec.val[2]], - tab[idxvec.val[3]] - };*/ - return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); -} -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - //vfloat64m1_t res = {tab[idxvec.val[0]], tab[idxvec.val[1]]}; - return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vreinterpret_v_i64m1_u64m1(vget_v_i64m2_i64m1(vwadd_vx_i64m2(idxvec.val, 0, 2), 0)), 3, 2), 2)); -} -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - vint32m1_t index = vmul_vx_i32m1(idxvec.val, 4, 4); - //vint32m1_t index_y = vadd_vx_i32m1(index_x, 4, 4); - - //x.val = vlxe_v_f32m1(tab, index_x, 4); - //y.val = vlxe_v_f32m1(tab, index_y, 4); - vloxseg2ei32_v_f32m1(&x.val, &y.val, tab, vreinterpret_v_i32m1_u32m1(index), 4); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - - x = v_float64x2(tab[idx[0]], tab[idx[1]]); - y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); -} - -#define OPENCV_HAL_IMPL_RISCVV_PACKS(_Tp, _Tp2, _T2, num2, _T1, num, intrin, shr, _Type, elemsize) \ -inline v_##_Tp##x##num v_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ - return v_##_Tp##x##num(shr##_##_T1##m1(tmp, 0, num)); \ -}\ -template inline \ -v_##_Tp##x##num v_rshr_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ - return v_##_Tp##x##num(intrin##_##_T1##m1(tmp, n, num)); \ -}\ -inline void v_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ - asm("" ::: "memory"); \ - vse##elemsize##_v_##_T1##m1(ptr, shr##_##_T1##m1(tmp, 0, num), num2); \ -}\ -template inline \ -void v_rshr_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ -{ \ - v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ - tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ - vse##elemsize##_v_##_T1##m1(ptr, intrin##_##_T1##m1(tmp, n, num), num2); \ -} -OPENCV_HAL_IMPL_RISCVV_PACKS(int8, int16, i16, 8, i8, 16, vnclip_wx, vnclip_wx, signed char, 8) -OPENCV_HAL_IMPL_RISCVV_PACKS(int16, int32, i32, 4, i16, 8, vnclip_wx, vnclip_wx, signed short, 16) -OPENCV_HAL_IMPL_RISCVV_PACKS(int32, int64, i64, 2, i32, 4, vnclip_wx, vnsra_wx, int, 32) -OPENCV_HAL_IMPL_RISCVV_PACKS(uint8, uint16, u16, 8, u8, 16, vnclipu_wx, vnclipu_wx, unsigned char, 8) -OPENCV_HAL_IMPL_RISCVV_PACKS(uint16, uint32, u32, 4, u16, 8, vnclipu_wx, vnclipu_wx, unsigned short, 16) -OPENCV_HAL_IMPL_RISCVV_PACKS(uint32, uint64, u64, 2, u32, 4, vnclipu_wx, vnsrl_wx, unsigned int, 32) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - vuint16m2_t tmp = vundefined_u16m2(); \ - tmp = vset_v_u16m1_u16m2(tmp, 0, a.val); \ - tmp = vset_v_u16m1_u16m2(tmp, 1, b.val); \ - return v_uint8x16(vnsrl_wx_u8m1(tmp, 0, 16)); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - vuint32m4_t vabcd = vundefined_u32m4(); \ - vuint16m2_t v16 = vundefined_u16m2(); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 0, a.val); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 1, b.val); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 2, c.val); \ - vabcd = vset_v_u32m1_u32m4(vabcd, 3, d.val); \ - v16 = vnsrl_wx_u16m2(vabcd, 0, 16); - return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - vuint64m8_t v64 = vundefined_u64m8(); \ - vuint32m4_t v32 = vundefined_u32m4(); \ - vuint16m2_t v16 = vundefined_u16m2(); \ - v64 = vset_v_u64m1_u64m8(v64, 0, a.val); \ - v64 = vset_v_u64m1_u64m8(v64, 1, b.val); \ - v64 = vset_v_u64m1_u64m8(v64, 2, c.val); \ - v64 = vset_v_u64m1_u64m8(v64, 3, d.val); \ - v64 = vset_v_u64m1_u64m8(v64, 4, e.val); \ - v64 = vset_v_u64m1_u64m8(v64, 5, f.val); \ - v64 = vset_v_u64m1_u64m8(v64, 6, g.val); \ - v64 = vset_v_u64m1_u64m8(v64, 7, h.val); \ - v32 = vnsrl_wx_u32m4(v64, 0, 16); - v16 = vnsrl_wx_u16m2(v32, 0, 16); - return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); -} - -//inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) \ -//{ \ -// int16xm2_u tmp; \ -// tmp.m1[0] = (vint16m1_t)a.val; \ -// tmp.m1[1] = (vint16m1_t)b.val; \ -// e8xm1_t mask = (e8xm1_t)vmsge_vx_e16xm2_i16m2(tmp.v, 0, 16);\ -// return v_uint8x16(vnclipuvi_mask_u8m1_u16m2(vmv_v_x_u8m1(0, 16), (vuint16m2_t)tmp.v, 0, mask, 16)); -//} - -#define OPENCV_HAL_IMPL_RISCVV_PACK_U(tp1, num1, tp2, num2, _Tp) \ -inline v_uint##tp1##x##num1 v_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ - vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1)); \ -} \ -inline void v_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - return vse##tp1##_v_u##tp1##m1(ptr, vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1), num2); \ -} \ -template inline \ -v_uint##tp1##x##num1 v_rshr_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ - vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), n, num1)); \ -} \ -template inline \ -void v_rshr_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ -{ \ - vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ - tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ - vint##tp2##m2_t val_ = vmax_vx_i##tp2##m2(tmp, 0, num1);\ - vuint##tp1##m1_t val = vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val_), n, num1); \ - return vse##tp1##_v_u##tp1##m1(ptr, val, num2);\ -} -OPENCV_HAL_IMPL_RISCVV_PACK_U(8, 16, 16, 8, unsigned char ) -OPENCV_HAL_IMPL_RISCVV_PACK_U(16, 8, 32, 4, unsigned short) - - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_RISCVV_MUL_SAT(_Tpvec, num, mul, cvt) \ - inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ - { \ - auto res = mul(a.val, b.val, num); \ - return _Tpvec(cvt(res, 0, num)); \ - } - -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int8x16, 16, vwmul_vv_i16m2, vnclip_wx_i8m1) -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint8x16, 16, vwmulu_vv_u16m2, vnclipu_wx_u8m1) -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int16x8, 32, vwmul_vv_i32m2, vnclip_wx_i16m1) -OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint16x8, 32, vwmulu_vv_u32m2, vnclipu_wx_u16m1) - - -static const signed char popCountTable[256] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; - -inline vuint8m1_t vcnt_u8(vuint8m1_t val){ -#if __riscv_v == 7000 - vuint8m1_t v0 = vand_vx_u8m1(val, 1, 16); - return vadd_vv_u8m1(vloxei8_v_u8m1((unsigned char*)popCountTable, vsrl_vx_u8m1(val, 1, 16), 16), v0, 16); -#else - return vloxei8_v_u8m1((unsigned char*)popCountTable, val, 16); -#endif -} - -inline v_uint8x16 -v_popcount(const v_uint8x16& a) -{ - return v_uint8x16(vcnt_u8(a.val)); -} - -inline v_uint8x16 -v_popcount(const v_int8x16& a) -{ - return v_uint8x16(vcnt_u8(vreinterpret_v_i8m1_u8m1(a.val))); -} - -inline v_uint16x8 -v_popcount(const v_uint16x8& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u16m1_u8m1(a.val)); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); -} - -inline v_uint16x8 -v_popcount(const v_int16x8& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(a.val))); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); -} - -inline v_uint32x4 -v_popcount(const v_uint32x4& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u32m1_u8m1(a.val)); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); - return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); -} - -inline v_uint32x4 -v_popcount(const v_int32x4& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(a.val))); - vuint8m1_t seq = vid_v_u8m1(8); - vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); - vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); - return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); -} - -inline v_uint64x2 -v_popcount(const v_uint64x2& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u64m1_u8m1(a.val)); - vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); - vuint16m1_t res1 = vundefined_u16m1(); - vuint16m1_t res2 = vundefined_u16m1(); - res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); - res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); - return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); -} - -inline v_uint64x2 -v_popcount(const v_int64x2& a) -{ - vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(a.val))); - vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); - vuint16m1_t res1 = vundefined_u16m1(), res2 = vundefined_u16m1(); - res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); - res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); - return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); -} - -#define SMASK 1, 2, 4, 8, 16, 32, 64, 128 -inline int v_signmask(const v_uint8x16& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint8m1_t id = vid_v_u8m1(16); - vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); - vuint8m1_t t0 = vsrl_vx_u8m1(a.val, 7, 16); - vbool8_t mask = vmseq_vx_u8m1_b8(t0, 1, 16); - res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); - return vmv_x_s_u16m1_u16(res); -} -inline int v_signmask(const v_int8x16& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint8m1_t id = vid_v_u8m1(16); - vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); - vbool8_t mask = vmslt_vx_i8m1_b8(a.val, 0, 16); - res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); - return vmv_x_s_u16m1_u16(res); -} - -inline int v_signmask(const v_int16x8& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint16m1_t id = vid_v_u16m1(8); - vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); - vbool16_t mask = vmslt_vx_i16m1_b16(a.val, 0, 8); - res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); - return vmv_x_s_u16m1_u16(res); -} -inline int v_signmask(const v_uint16x8& a) -{ - vuint16m1_t res = vundefined_u16m1(); - vuint16m1_t id = vid_v_u16m1(8); - vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); - vuint16m1_t t0 = vsrl_vx_u16m1(a.val, 15, 8); - vbool16_t mask = vmseq_vx_u16m1_b16(t0, 1, 8); - res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 8); - return vmv_x_s_u16m1_u16(res); -} -inline int v_signmask(const v_int32x4& a) -{ - vuint32m1_t res = vundefined_u32m1(); - vuint32m1_t id = vid_v_u32m1(4); - vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); - vbool32_t mask = vmslt_vx_i32m1_b32(a.val, 0, 4); - res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); - return vmv_x_s_u32m1_u32(res); -} -inline int v_signmask(const v_uint32x4& a) -{ - vuint32m1_t res = vundefined_u32m1(); - vuint32m1_t id = vid_v_u32m1(4); - vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); - vuint32m1_t t0 = vsrl_vx_u32m1(a.val, 31, 4); - vbool32_t mask = vmseq_vx_u32m1_b32(t0, 1, 4); - res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); - return vmv_x_s_u32m1_u32(res); -} -inline int v_signmask(const v_uint64x2& a) -{ - vuint64m1_t res = vundefined_u64m1(); - vuint64m1_t id = vid_v_u64m1(2); - vuint64m1_t num = vsll_vv_u64m1(vmv_v_x_u64m1(1, 2), id, 2); - vuint64m1_t t0 = vsrl_vx_u64m1(a.val, 63, 2); - vbool64_t mask = vmseq_vx_u64m1_b64(t0, 1, 2); - res = vredsum_vs_u64m1_u64m1_m(mask, res, num, vmv_v_x_u64m1(0, 2), 2); - return vmv_x_s_u64m1_u64(res); -} -inline int v_signmask(const v_int64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_u64(a)); } -inline int v_signmask(const v_float32x4& a) -{ - return v_signmask(v_reinterpret_as_u32(a)); - /* - vuint32m1_t res; - vuint32m1_t id = vid_v_u32m1(4); - vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); - vbool32_t mask = vmflt_vf_f32m1_b32(a.val, 0, 4); - res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); - return vmv_x_s_u32m1_u32(res);*/ -} - -inline int v_scan_forward(const v_int8x16& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint8x16& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_int16x8& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint16x8& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_int32x4& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint32x4& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_float32x4& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_int64x2& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } -inline int v_scan_forward(const v_uint64x2& a) { -int val = v_signmask(a); -if(val==0) return 0; -else return trailingZeros32(val); } - -#define OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(_Tpvec, suffix, _T, shift, num, mask_b) \ -inline bool v_check_all(const v_##_Tpvec& a) \ -{ \ - suffix##m1_t v0 = vsrl_vx_##_T(vnot_v_##_T(a.val, num), shift, num); \ - return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) == 0; \ -} \ -inline bool v_check_any(const v_##_Tpvec& a) \ -{ \ - suffix##m1_t v0 = vsrl_vx_##_T(a.val, shift, num); \ - return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) != 0; \ -} - -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint8x16, vuint8, u8m1, 7, 16, b8) -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint16x8, vuint16, u16m1, 15, 8, b16) -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint32x4, vuint32, u32m1, 31, 4, b32) -OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint64x2, vuint64, u64m1, 63, 2, b64) - -inline bool v_check_all(const v_int8x16& a) -{ return v_check_all(v_reinterpret_as_u8(a)); } -inline bool v_check_all(const v_int16x8& a) -{ return v_check_all(v_reinterpret_as_u16(a)); } -inline bool v_check_all(const v_int32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_u32(a)); } -inline bool v_check_all(const v_int64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_u64(a)); } - -inline bool v_check_any(const v_int8x16& a) -{ return v_check_any(v_reinterpret_as_u8(a)); } -inline bool v_check_any(const v_int16x8& a) -{ return v_check_any(v_reinterpret_as_u16(a)); } -inline bool v_check_any(const v_int32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_u32(a)); } -inline bool v_check_any(const v_int64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_u64(a)); } - -#define OPENCV_HAL_IMPL_RISCVV_SELECT(_Tpvec, suffix, _Tpvec2, num, mask_func) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(vmerge_vvm_##suffix(mask_func(mask.val, 0, num), b.val, a.val, num)); \ -} - -OPENCV_HAL_IMPL_RISCVV_SELECT(v_int8x16, i8m1, vbool8_t, 16, vmsne_vx_i8m1_b8) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_int16x8, i16m1, vbool16_t, 8, vmsne_vx_i16m1_b16) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_int32x4, i32m1, vbool32_t, 4, vmsne_vx_i32m1_b32) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint8x16, u8m1, vbool8_t, 16, vmsne_vx_u8m1_b8) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint16x8, u16m1, vbool16_t, 8, vmsne_vx_u16m1_b16) -OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint32x4, u32m1, vbool32_t, 4, vmsne_vx_u32m1_b32) -inline v_float32x4 v_select(const v_float32x4& mask, const v_float32x4& a, const v_float32x4& b) -{ - return v_float32x4(vmerge_vvm_f32m1(vmfne_vf_f32m1_b32(mask.val, 0, 4), b.val, a.val, 4)); -} -inline v_float64x2 v_select(const v_float64x2& mask, const v_float64x2& a, const v_float64x2& b) -{ - return v_float64x2(vmerge_vvm_f64m1(vmfne_vf_f64m1_b64(mask.val, 0, 2), b.val, a.val, 2)); -} - -#define OPENCV_HAL_IMPL_RISCVV_EXPAND(add, _Tpvec, _Tpwvec, _Tp, _Tp1, num1, _Tp2, num2, _T1, _T2, num3) \ -inline void v_expand(const _Tpvec& a, v_##_Tpwvec& b0, v_##_Tpwvec& b1) \ -{ \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ - b0.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 0); \ - b1.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 1); \ -} \ -inline v_##_Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num2); \ - return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ -} \ -inline v_##_Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ - return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 1)); \ -} \ -inline v_##_Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - _T2##_t val = vle##num3##_v_##_Tp1(ptr, num2); \ - _T1##_t b = vw##add##_vx_##_Tp2##m2(val, 0, num2); \ - return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ -} - -OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint8x16, uint16x8, uchar, u8m1, 16, u16, 8, vuint16m2, vuint8m1, 8) -OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint16x8, uint32x4, ushort, u16m1, 8, u32, 4, vuint32m2, vuint16m1, 16) -OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint32x4, uint64x2, uint, u32m1, 4, u64, 2, vuint64m2, vuint32m1, 32) -OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int8x16, int16x8, schar, i8m1, 16, i16, 8, vint16m2, vint8m1, 8) -OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int16x8, int32x4, short, i16m1, 8, i32, 4, vint32m2, vint16m1, 16) -OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int32x4, int64x2, int, i32m1, 4, i64, 2, vint64m2, vint32m1, 32) - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - vuint16m2_t b = vundefined_u16m2(); - vuint32m2_t c = vundefined_u32m2(); - vuint8m1_t val = vle8_v_u8m1(ptr, 4); \ - b = vwaddu_vv_u16m2(val, vmv_v_x_u8m1(0, 4), 4); \ - c = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(b, 0), vmv_v_x_u16m1(0, 4), 4); \ - return v_uint32x4(vget_v_u32m2_u32m1(c, 0)); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - vint16m2_t b = vundefined_i16m2(); - vint32m2_t c = vundefined_i32m2(); - vint8m1_t val = vle8_v_i8m1(ptr, 4); \ - b = vwadd_vv_i16m2(val, vmv_v_x_i8m1(0, 4), 4); \ - c = vwadd_vv_i32m2(vget_v_i16m2_i16m1(b, 0), vmv_v_x_i16m1(0, 4), 4); \ - return v_int32x4(vget_v_i32m2_i32m1(c, 0)); -} -#define VITL_16 {0x11011000, 0x13031202, 0x15051404, 0x17071606, 0x19091808, 0x1B0B1A0A, 0x1D0D1C0C, 0x1F0F1E0E} -#define VITL_8 {0x00080000, 0x00090001, 0x000A0002, 0x000B0003, 0x000C0004, 0x000D0005, 0x000E0006, 0x000F0007} -#define VITL_4 {0x00000000, 0x00000004, 0x00000001, 0x00000005, 0x00000002, 0x00000006, 0x00000003, 0x00000007} -#define VITL_2 {0, 0, 2, 0, 1, 0, 3, 0} - -#define OPENCV_HAL_IMPL_RISCVV_UNPACKS(_Tpvec, _Tp, _T, _UTp, _UT, num, num2, len, numh, refunc) \ -inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ -{ \ - v##_Tp##m2_t tmp = vundefined_##_T##m2();\ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a0.val); \ - tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a1.val); \ - unsigned mdata[] = VITL_##num; \ - vuint32m2_t mask = vle32_v_u32m2(mdata, 8); \ - tmp = (v##_Tp##m2_t)vrgather_vv_##_T##m2((v##_Tp##m2_t)tmp, refunc(mask), num2); \ - b0.val = vget_v_##_T##m2_##_T##m1(tmp, 0); \ - b1.val = vget_v_##_T##m2_##_T##m1(tmp, 1); \ -} \ -inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - v##_Tp##m1_t b0 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ - return v_##_Tpvec(b0);\ -} \ -inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ -{ \ - v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ - v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ - v##_Tp##m1_t b1 = vundefined_##_T##m1(); \ - b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ - a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ - b1 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ - return v_##_Tpvec(b1);\ -} \ -inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ - v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ - c.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ - b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ - a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ - d.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ -} - -OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint8x16, uint8, u8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(int8x16, int8, i8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint16x8, uint16, u16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(int16x8, int16, i16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint32x4, uint32, u32, uint32, u32, 4, 8, b32, 2,) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(int32x4, int32, i32, uint32, u32, 4, 8, b32, 2,) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(float32x4, float32, f32, uint32, u32, 4, 8, b32, 2,) -OPENCV_HAL_IMPL_RISCVV_UNPACKS(float64x2, float64, f64, uint64, u64, 2, 4, b64, 1, vreinterpret_v_u32m2_u64m2) - -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - return v_uint8x16(vrgather_vv_u8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); -} -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ - return v_int8x16(vrgather_vv_i8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); -} - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - return v_uint16x8(vrgather_vv_u16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ - return v_int16x8(vrgather_vv_i16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); -} -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - return v_uint32x4(vrgather_vv_u32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ - return v_int32x4(vrgather_vv_i32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); -} - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - return v_uint64x2(vrgather_vv_u64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ - return v_int64x2(vrgather_vv_i64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); -} - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ - return v_float64x2(vrgather_vv_f64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); -} - -#define OPENCV_HAL_IMPL_RISCVV_EXTRACT(_Tpvec, suffix, size) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ -{ return v_rotate_right(a, b);} -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint8x16, u8, 0) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int8x16, s8, 0) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint16x8, u16, 1) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int16x8, s16, 1) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint32x4, u32, 2) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int32x4, s32, 2) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint64x2, u64, 3) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int64x2, s64, 3) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float32x4, f32, 2) -OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float64x2, f64, 3) - - -#define OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(_Tpvec, _Tp, suffix, vtype, _vtype, num, mvfunc) \ -template inline _Tp v_extract_n(_Tpvec v) { vtype tmp = vundefined_##_vtype(); return mvfunc(vslidedown_vx_##_vtype(tmp, v.val, i, num)); } - -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint8x16, uchar, u8, vuint8m1_t, u8m1, 16, vmv_x_s_u8m1_u8) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int8x16, schar, s8, vint8m1_t, i8m1, 16, vmv_x_s_i8m1_i8) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint16x8, ushort, u16, vuint16m1_t, u16m1, 8, vmv_x_s_u16m1_u16) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int16x8, short, s16, vint16m1_t, i16m1, 8, vmv_x_s_i16m1_i16) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint32x4, uint, u32, vuint32m1_t, u32m1, 4, vmv_x_s_u32m1_u32) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int32x4, int, s32, vint32m1_t, i32m1, 4, vmv_x_s_i32m1_i32) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint64x2, uint64, u64, vuint64m1_t, u64m1, 2, vmv_x_s_u64m1_u64) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int64x2, int64, s64, vint64m1_t, i64m1, 2, vmv_x_s_i64m1_i64) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float32x4, float, f32, vfloat32m1_t, f32m1, 4, vfmv_f_s_f32m1_f32) -OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float64x2, double, f64, vfloat64m1_t, f64m1, 2, vfmv_f_s_f64m1_f64) - -#define OPENCV_HAL_IMPL_RISCVV_BROADCAST(_Tpvec, _Tp, num) \ -template inline _Tpvec v_broadcast_element(_Tpvec v) { return _Tpvec(vrgather_vx_##_Tp##m1(v.val, i, num)); } - -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint8x16, u8, 16) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int8x16, i8, 16) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint16x8, u16, 8) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int16x8, i16, 8) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint32x4, u32, 4) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int32x4, i32, 4) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint64x2, u64, 2) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int64x2, i64, 2) -OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_float32x4, f32, 4) - -inline void __builtin_riscv_fsrm(int val) -{ - asm("csrw frm, %0\n\t" - : - :"r"(val)); - return; -} - -inline void barrier1(void *arg) { - __asm__ __volatile__("" : : "r" (arg) : "memory"); -} - -inline v_int32x4 v_round(const v_float32x4& a) -{ - __builtin_riscv_fsrm(0); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} -inline v_int32x4 v_floor(const v_float32x4& a) -{ - __builtin_riscv_fsrm(2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - __builtin_riscv_fsrm(3); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ - __builtin_riscv_fsrm(1); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_round(const v_float64x2& a) -{ - __builtin_riscv_fsrm(0); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - //_val = vset_f64m2(_val, 1, a.val); - _val = vset_v_f64m1_f64m2(_val, 1, vfmv_v_f_f64m1(0, 2)); - barrier1(&_val); - vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - __builtin_riscv_fsrm(0); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - _val = vset_v_f64m1_f64m2(_val, 1, b.val); - barrier1(&_val); - vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} -inline v_int32x4 v_floor(const v_float64x2& a) -{ - __builtin_riscv_fsrm(2); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - __builtin_riscv_fsrm(3); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ - __builtin_riscv_fsrm(1); - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); - barrier1(&nan); - vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); - vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); - __builtin_riscv_fsrm(0); - return v_int32x4(val); -} - -#define OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ -{ \ - intrin##2e##elemsize##_v_##_T##m1(&a.val, &b.val, ptr, num); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ -{ \ - intrin##3e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num); \ -}\ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ - v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ -{ \ - intrin##4e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num); \ -} \ - -#define OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - intrin##2e##elemsize##_v_##_T##m1(ptr, a.val, b.val, num); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - intrin##3e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, num); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - intrin##4e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num); \ -} - -#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(_Tpvec, _Tp, num, ld, st, _T, elemsize) \ -OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(ld, _Tpvec, num, _Tp, _T, elemsize) \ -OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(st, _Tpvec, num, _Tp, _T, elemsize) - -//OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, uchar, ) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int8, schar, 16, vlseg, vsseg, i8, 8) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int16, short, 8, vlseg, vsseg, i16, 16) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int32, int, 4, vlseg, vsseg, i32, 32) - -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, unsigned char, 16, vlseg, vsseg, u8, 8) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint16, unsigned short, 8, vlseg, vsseg, u16, 16) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint32, unsigned int, 4, vlseg, vsseg, u32, 32) - -#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(_Tpvec, _Tp, num, _T, _esize) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ -{ vlseg2e##_esize##_v_##_T##m1(&a.val, &b.val, ptr, num);} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ -{ vlseg3e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num);}\ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ - v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ -{ vlseg4e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num);} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vsseg2e##_esize##_v_##_T##m1(ptr, a.val, b.val, num);} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vsseg3e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, num);} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ - const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ vsseg4e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num);} - -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float32, float, 4, f32, 32) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float64, double, 2, f64, 64) - -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(uint64, unsigned long, 2, u64, 64) -OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(int64, long, 2, i64, 64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(vfcvt_f_x_v_f32m1(a.val, 4)); -} - -#if CV_SIMD128_64F -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); - return v_float32x4(aval); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - vfloat64m2_t _val = vundefined_f64m2(); - _val = vset_v_f64m1_f64m2(_val, 0, a.val); - _val = vset_v_f64m1_f64m2(_val, 1, b.val); - vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 4); - return v_float32x4(aval); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); - return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ - return v_float64x2(vfcvt_f_x_v_f64m1(a.val, 2)); -} - -#endif -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - uint64 mdata[2] = {0x0705060403010200, 0x0F0D0E0C0B090A08}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ - return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); -} - -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - uint64 mdata[2] = {0x0703060205010400, 0x0F0B0E0A0D090C08}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) -{ - return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); -} - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - uint64 mdata[2] = {0x0706030205040100, 0x0F0E0B0A0D0C0908}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - uint64 mdata[2] = {0x0B0A030209080100, 0x0F0E07060D0C0504}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - uint64 mdata[2] = {0x0B0A090803020100, 0x0F0E0D0C07060504}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int32x4(vreinterpret_v_i8m1_i32m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - uint64 mdata[2] = {0x0908060504020100, 0xFFFFFFFF0E0D0C0A}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int8x16(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vec.val), vreinterpret_v_u64m1_u8m1(m0), 16))); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - uint64 mdata[2] = {0x0908050403020100, 0xFFFFFFFF0D0C0B0A}; - vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); - return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -#if CV_SIMD128_64F -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, - const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ - vint64m2_t v1 = vwmul_vv_i64m2(a.val, b.val, 4); - vfloat64m1_t res = vfcvt_f_x_v_f64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2), 2); - return v_float64x2(res); -} -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ v_float64x2 res = v_dotprod_expand_fast(a, b); - return v_add(res, c); } -#endif -////// FP16 support /////// -#if __riscv_v == 7000 -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - vfloat16m1_t v = vle16_v_f16m1((__fp16*)ptr, 4); - vfloat32m2_t v32 = vfwcvt_f_f_v_f32m2(v, 4); - return v_float32x4(vget_v_f32m2_f32m1(v32, 0)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - vfloat32m2_t v32 = vundefined_f32m2(); - v32 = vset_v_f32m1_f32m2(v32, 0, v.val); - vfloat16m1_t hv = vfncvt_f_f_w_f16m1(v32, 4); - vse16_v_f16m1((__fp16*)ptr, hv, 4); -} -#else -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - vfloat16mf2_t v = vle16_v_f16mf2((__fp16*)ptr, 4); - vfloat32m1_t v32 = vfwcvt_f_f_v_f32m1(v, 4); - return v_float32x4(v32); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - //vfloat32m2_t v32 = vundefined_f32m2(); - //v32 = vset_f32m2(v32, 0, v.val); - vfloat16mf2_t hv = vfncvt_f_f_w_f16mf2(v.val, 4); - vse16_v_f16mf2((__fp16*)ptr, hv, 4); -} -#endif - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +// Copyright (C) 2015, PingTouGe Semiconductor Co., Ltd., all rights reserved. + +#ifndef OPENCV_HAL_INTRIN_RISCVV_HPP +#define OPENCV_HAL_INTRIN_RISCVV_HPP + +#include +#include +#include "opencv2/core/utility.hpp" + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +//////////// Types //////////// +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16 }; + + v_uint8x16() {} + explicit v_uint8x16(vuint8m1_t v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = (vuint8m1_t)vle8_v_u8m1((unsigned char*)v, 16); + } + uchar get0() const + { + return vmv_x_s_u8m1_u8(val); + } + + vuint8m1_t val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(vint8m1_t v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = (vint8m1_t)vle8_v_i8m1((schar*)v, 16); + } + schar get0() const + { + return vmv_x_s_i8m1_i8(val); + } + + vint8m1_t val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(vuint16m1_t v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = (vuint16m1_t)vle16_v_u16m1((unsigned short*)v, 8); + } + ushort get0() const + { + return vmv_x_s_u16m1_u16(val); + } + + vuint16m1_t val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(vint16m1_t v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = (vint16m1_t)vle16_v_i16m1((signed short*)v, 8); + } + short get0() const + { + return vmv_x_s_i16m1_i16(val); + } + + vint16m1_t val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(vuint32m1_t v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + unsigned v[] = {v0, v1, v2, v3}; + val = (vuint32m1_t)vle32_v_u32m1((unsigned int*)v, 4); + } + unsigned get0() const + { + return vmv_x_s_u32m1_u32(val); + } + + vuint32m1_t val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(vint32m1_t v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = (vint32m1_t)vle32_v_i32m1((signed int*)v, 4); + } + int get0() const + { + return vmv_x_s_i32m1_i32(val); + } + vint32m1_t val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4 }; + + v_float32x4() {} + explicit v_float32x4(vfloat32m1_t v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = (vfloat32m1_t)vle32_v_f32m1((float*)v, 4); + } + float get0() const + { + return vfmv_f_s_f32m1_f32(val); + } + vfloat32m1_t val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2 }; + + v_uint64x2() {} + explicit v_uint64x2(vuint64m1_t v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = (vuint64m1_t)vle64_v_u64m1((unsigned long*)v, 2); + } + uint64 get0() const + { + return vmv_x_s_u64m1_u64(val); + } + vuint64m1_t val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2 }; + + v_int64x2() {} + explicit v_int64x2(vint64m1_t v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = (vint64m1_t)vle64_v_i64m1((long*)v, 2); + } + int64 get0() const + { + return vmv_x_s_i64m1_i64(val); + } + vint64m1_t val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2 }; + + v_float64x2() {} + explicit v_float64x2(vfloat64m1_t v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = (vfloat64m1_t)vle64_v_f64m1((double*)v, 2); + } + double get0() const + { + return vfmv_f_s_f64m1_f64(val); + } + vfloat64m1_t val; +}; +/* +#define OPENCV_HAL_IMPL_RISCVV_INIT(_Tpv, _Tp, suffix) \ +inline _Tp##m1_t vreinterpret_v_##suffix##m1_##suffix##m1(_Tp##m1_t v) { return v; } \ +inline v_uint8x16 v_reinterpret_as_u8(const v_##_Tpv& v) { return v_uint8x16((vuint8m1_t)(v.val)); } \ +inline v_int8x16 v_reinterpret_as_s8(const v_##_Tpv& v) { return v_int8x16((vint8m1_t)(v.val)); } \ +inline v_uint16x8 v_reinterpret_as_u16(const v_##_Tpv& v) { return v_uint16x8((vuint16m1_t)(v.val)); } \ +inline v_int16x8 v_reinterpret_as_s16(const v_##_Tpv& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } \ +inline v_uint32x4 v_reinterpret_as_u32(const v_##_Tpv& v) { return v_uint32x4((vuint32m1_t)(v.val)); } \ +inline v_int32x4 v_reinterpret_as_s32(const v_##_Tpv& v) { return v_int32x4((vint32m1_t)(v.val)); } \ +inline v_uint64x2 v_reinterpret_as_u64(const v_##_Tpv& v) { return v_uint64x2((vuint64m1_t)(v.val)); } \ +inline v_int64x2 v_reinterpret_as_s64(const v_##_Tpv& v) { return v_int64x2((vint64m1_t)(v.val)); } \ +inline v_float32x4 v_reinterpret_as_f32(const v_##_Tpv& v) { return v_float32x4((vfloat32m1_t)(v.val)); }\ +inline v_float64x2 v_reinterpret_as_f64(const v_##_Tpv& v) { return v_float64x2((vfloat64m1_t)(v.val)); } + + +OPENCV_HAL_IMPL_RISCVV_INIT(uint8x16, vuint8, u8) +OPENCV_HAL_IMPL_RISCVV_INIT(int8x16, vint8, i8) +OPENCV_HAL_IMPL_RISCVV_INIT(uint16x8, vuint16, u16) +OPENCV_HAL_IMPL_RISCVV_INIT(int16x8, vint16, i16) +OPENCV_HAL_IMPL_RISCVV_INIT(uint32x4, vuint32, u32) +OPENCV_HAL_IMPL_RISCVV_INIT(int32x4, vint32, i32) +OPENCV_HAL_IMPL_RISCVV_INIT(uint64x2, vuint64, u64) +OPENCV_HAL_IMPL_RISCVV_INIT(int64x2, vint64, i64) +OPENCV_HAL_IMPL_RISCVV_INIT(float64x2, vfloat64, f64) +OPENCV_HAL_IMPL_RISCVV_INIT(float32x4, vfloat32, f32) +*/ +inline v_uint8x16 v_reinterpret_as_u8(const v_uint8x16& v) { return v_uint8x16(v.val); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint8x16& v) { return v_int8x16(vreinterpret_v_u8m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint8x16& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(vreinterpret_v_u8m1_u16m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint8x16& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u8m1_u32m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint8x16& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u8m1_u64m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint8x16& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u8m1_u32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint8x16& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u8m1_u64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int8x16& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_int8x16& v) { return v_int8x16(v.val); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int8x16& v) { return v_uint16x8(vreinterpret_v_u8m1_u16m1(vreinterpret_v_i8m1_u8m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_int8x16& v) { return v_int16x8(vreinterpret_v_i8m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int8x16& v) { return v_uint32x4(vreinterpret_v_u8m1_u32m1(vreinterpret_v_i8m1_u8m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_int8x16& v) { return v_int32x4(vreinterpret_v_i8m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int8x16& v) { return v_uint64x2(vreinterpret_v_u8m1_u64m1(vreinterpret_v_i8m1_u8m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_int8x16& v) { return v_int64x2(vreinterpret_v_i8m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int8x16& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i8m1_i32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_int8x16& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i8m1_i64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_uint16x8& v) { return v_uint8x16(vreinterpret_v_u16m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(vreinterpret_v_u16m1_i16m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint16x8& v) { return v_uint16x8(v.val); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint16x8& v) { return v_int16x8(vreinterpret_v_u16m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint16x8& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(vreinterpret_v_u16m1_u32m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint16x8& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u16m1_u64m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint16x8& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u16m1_u32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint16x8& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u16m1_u64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int16x8& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_int16x8& v) { return v_int8x16(vreinterpret_v_i16m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int16x8& v) { return v_uint16x8(vreinterpret_v_i16m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_int16x8& v) { return v_int16x8(v.val); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int16x8& v) { return v_uint32x4(vreinterpret_v_u16m1_u32m1(vreinterpret_v_i16m1_u16m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_int16x8& v) { return v_int32x4(vreinterpret_v_i16m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int16x8& v) { return v_uint64x2(vreinterpret_v_u16m1_u64m1(vreinterpret_v_i16m1_u16m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_int16x8& v) { return v_int64x2(vreinterpret_v_i16m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int16x8& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i16m1_i32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_int16x8& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i16m1_i64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_uint32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_u32m1_i32m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_u32m1_i32m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint32x4& v) { return v_uint32x4(v.val); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint32x4& v) { return v_int32x4(vreinterpret_v_u32m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint32x4& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(vreinterpret_v_u32m1_u64m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint32x4& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(v.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint32x4& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(vreinterpret_v_u32m1_u64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int32x4& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_int32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_i32m1_u32m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_int32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int32x4& v) { return v_uint32x4(vreinterpret_v_i32m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_int32x4& v) { return v_int32x4(v.val); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_i32m1_u32m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_int32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int32x4& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(v.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_int32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(v.val))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_uint64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(v.val)); } +inline v_int8x16 v_reinterpret_as_s8(const v_uint64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_u64m1_i64m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_uint64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(v.val)); } +inline v_int16x8 v_reinterpret_as_s16(const v_uint64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_u64m1_i64m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_uint64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_uint64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_u64m1_i64m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_uint64x2& v) { return v_uint64x2(v.val); } +inline v_int64x2 v_reinterpret_as_s64(const v_uint64x2& v) { return v_int64x2(vreinterpret_v_u64m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& v) { return v_float32x4(vreinterpret_v_u32m1_f32m1(vreinterpret_v_u64m1_u32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& v) { return v_float64x2(vreinterpret_v_u64m1_f64m1(v.val)); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_int64x2& v) { return v_uint8x16(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_int64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(v.val)); } +inline v_uint16x8 v_reinterpret_as_u16(const v_int64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_i64m1_u64m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_int64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(v.val)); } +inline v_uint32x4 v_reinterpret_as_u32(const v_int64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_i64m1_u64m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_int64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_int64x2& v) { return v_uint64x2(vreinterpret_v_i64m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_int64x2& v) { return v_int64x2(v.val); } +inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(v.val))); } +inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(v.val)); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_float32x4& v) { return v_uint8x16(vreinterpret_v_u32m1_u8m1(vreinterpret_v_f32m1_u32m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_float32x4& v) { return v_int8x16(vreinterpret_v_i32m1_i8m1(vreinterpret_v_f32m1_i32m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_float32x4& v) { return v_uint16x8(vreinterpret_v_u32m1_u16m1(vreinterpret_v_f32m1_u32m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_float32x4& v) { return v_int16x8(vreinterpret_v_i32m1_i16m1(vreinterpret_v_f32m1_i32m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_float32x4& v) { return v_uint32x4(vreinterpret_v_f32m1_u32m1(v.val)); } +inline v_int32x4 v_reinterpret_as_s32(const v_float32x4& v) { return v_int32x4(vreinterpret_v_f32m1_i32m1(v.val)); } +inline v_uint64x2 v_reinterpret_as_u64(const v_float32x4& v) { return v_uint64x2(vreinterpret_v_u32m1_u64m1(vreinterpret_v_f32m1_u32m1(v.val))); } +inline v_int64x2 v_reinterpret_as_s64(const v_float32x4& v) { return v_int64x2(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val))); } +inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& v) { return v_float32x4(v.val); } +inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& v) { return v_float64x2(vreinterpret_v_i64m1_f64m1(vreinterpret_v_i32m1_i64m1(vreinterpret_v_f32m1_i32m1(v.val)))); } + +inline v_uint8x16 v_reinterpret_as_u8(const v_float64x2& v) { return v_uint8x16(vreinterpret_v_u64m1_u8m1(vreinterpret_v_f64m1_u64m1(v.val))); } +inline v_int8x16 v_reinterpret_as_s8(const v_float64x2& v) { return v_int8x16(vreinterpret_v_i64m1_i8m1(vreinterpret_v_f64m1_i64m1(v.val))); } +inline v_uint16x8 v_reinterpret_as_u16(const v_float64x2& v) { return v_uint16x8(vreinterpret_v_u64m1_u16m1(vreinterpret_v_f64m1_u64m1(v.val))); } +inline v_int16x8 v_reinterpret_as_s16(const v_float64x2& v) { return v_int16x8(vreinterpret_v_i64m1_i16m1(vreinterpret_v_f64m1_i64m1(v.val))); } +inline v_uint32x4 v_reinterpret_as_u32(const v_float64x2& v) { return v_uint32x4(vreinterpret_v_u64m1_u32m1(vreinterpret_v_f64m1_u64m1(v.val))); } +inline v_int32x4 v_reinterpret_as_s32(const v_float64x2& v) { return v_int32x4(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val))); } +inline v_uint64x2 v_reinterpret_as_u64(const v_float64x2& v) { return v_uint64x2(vreinterpret_v_f64m1_u64m1(v.val)); } +inline v_int64x2 v_reinterpret_as_s64(const v_float64x2& v) { return v_int64x2(vreinterpret_v_f64m1_i64m1(v.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& v) { return v_float32x4(vreinterpret_v_i32m1_f32m1(vreinterpret_v_i64m1_i32m1(vreinterpret_v_f64m1_i64m1(v.val)))); } +inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& v) { return v_float64x2(v.val); } + +#define OPENCV_HAL_IMPL_RISCVV_INIT_SET(__Tp, _Tp, suffix, len, num) \ +inline v_##_Tp##x##num v_setzero_##suffix() { return v_##_Tp##x##num(vmv_v_x_##len##m1(0, num)); } \ +inline v_##_Tp##x##num v_setall_##suffix(__Tp v) { return v_##_Tp##x##num(vmv_v_x_##len##m1(v, num)); } \ +template <> inline v_##_Tp##x##num v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline v_##_Tp##x##num v_setall_(__Tp v) { return v_setall_##suffix(v); } + +OPENCV_HAL_IMPL_RISCVV_INIT_SET(uchar, uint8, u8, u8, 16) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(schar, int8, s8, i8, 16) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(ushort, uint16, u16, u16, 8) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(short, int16, s16, i16, 8) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned int, uint32, u32, u32, 4) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(int, int32, s32, i32, 4) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(unsigned long, uint64, u64, u64, 2) +OPENCV_HAL_IMPL_RISCVV_INIT_SET(long, int64, s64, i64, 2) +inline v_float32x4 v_setzero_f32() { return v_float32x4(vfmv_v_f_f32m1(0, 4)); } +inline v_float32x4 v_setall_f32(float v) { return v_float32x4(vfmv_v_f_f32m1(v, 4)); } + +inline v_float64x2 v_setzero_f64() { return v_float64x2(vfmv_v_f_f64m1(0, 2)); } +inline v_float64x2 v_setall_f64(double v) { return v_float64x2(vfmv_v_f_f64m1(v, 2)); } + +template <> inline v_float32x4 v_setzero_() { return v_setzero_f32(); } +template <> inline v_float32x4 v_setall_(float v) { return v_setall_f32(v); } + +template <> inline v_float64x2 v_setzero_() { return v_setzero_f64(); } +template <> inline v_float64x2 v_setall_(double v) { return v_setall_f64(v); } + +#define OPENCV_HAL_IMPL_RISCVV_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +#define OPENCV_HAL_IMPL_RISCVV_BIN_OPN(bin_op, _Tpvec, intrin, num) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val, num)); \ +} + +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint8x16, vsaddu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint8x16, vssubu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int8x16, vsadd_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int8x16, vssub_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint16x8, vsaddu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint16x8, vssubu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int16x8, vsadd_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int16x8, vssub_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int32x4, vadd_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int32x4, vsub_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_int32x4, vmul_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint32x4, vadd_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint32x4, vsub_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_uint32x4, vmul_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_int64x2, vadd_vv_i64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_int64x2, vsub_vv_i64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_uint64x2, vadd_vv_u64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_uint64x2, vsub_vv_u64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float32x4, vfadd_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float32x4, vfsub_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float32x4, vfmul_vv_f32m1, 4) +inline v_float32x4 v_div(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vfdiv_vv_f32m1(a.val, b.val, 4)); +} + +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_add, v_float64x2, vfadd_vv_f64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_sub, v_float64x2, vfsub_vv_f64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_mul, v_float64x2, vfmul_vv_f64m1, 2) +inline v_float64x2 v_div(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vfdiv_vv_f64m1(a.val, b.val, 2)); +} +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_RISCVV_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +#define OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(_Tpvec, func, intrin, num) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val, num)); \ +} +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_min, vminu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_max, vmaxu_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_min, vmin_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_max, vmax_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_min, vminu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_max, vmaxu_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_min, vmin_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_max, vmax_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_min, vminu_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint32x4, v_max, vmaxu_vv_u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_min, vmin_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int32x4, v_max, vmax_vv_i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_min, vfmin_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float32x4, v_max, vfmax_vv_f32m1, 4) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_min, vfmin_vv_f64m1, 2) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_float64x2, v_max, vfmax_vv_f64m1, 2) + +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + return v_float32x4(vfsqrt_v_f32m1(x.val, 4)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + return v_float32x4(vfrdiv_vf_f32m1(vfsqrt_v_f32m1(x.val, 4), 1, 4)); +} + +inline v_float32x4 v_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + v_float32x4 x(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); + return v_sqrt(x); +} + +inline v_float32x4 v_sqr_magnitude(const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vfmacc_vv_f32m1(vfmul_vv_f32m1(a.val, a.val, 4), b.val, b.val, 4)); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_float32x4(vfmadd_vv_f32m1(a.val, b.val, c.val, 4)); +} + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_int32x4(vmadd_vv_i32m1(a.val, b.val, c.val, 4)); +} + +inline v_float32x4 v_muladd(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 3, 4), m3.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + return v_float32x4(res); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + vfloat32m1_t res = vfmul_vv_f32m1(m0.val, vrgather_vx_f32m1(v.val, 0, 4), 4);//vmuli_f32(m0.val, v.val, 0); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 1, 4), m1.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfmacc_vv_f32m1(res, vrgather_vx_f32m1(v.val, 2, 4), m2.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + res = vfadd_vv_f32m1(res, a.val, 4);//vmulai_f32(res, m1.val, v.val, 1); + return v_float32x4(res); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ + return v_float64x2(vfsqrt_v_f64m1(x.val, 2)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + return v_float64x2(vfrdiv_vf_f64m1(vfsqrt_v_f64m1(x.val, 2), 1, 2)); +} + +inline v_float64x2 v_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + v_float64x2 x(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); + return v_sqrt(x); +} + +inline v_float64x2 v_sqr_magnitude(const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vfmacc_vv_f64m1(vfmul_vv_f64m1(a.val, a.val, 2), b.val, b.val, 2)); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_float64x2(vfmadd_vv_f64m1(a.val, b.val, c.val, 2)); +} + +inline v_float64x2 v_muladd(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_fma(a, b, c); +} + +#define OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(_Tpvec, suffix, num) \ + OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_and, _Tpvec, vand_vv_##suffix, num) \ + OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_or, _Tpvec, vor_vv_##suffix, num) \ + OPENCV_HAL_IMPL_RISCVV_BIN_OPN(v_xor, _Tpvec, vxor_vv_##suffix, num) \ + inline _Tpvec v_not(const _Tpvec & a) \ + { \ + return _Tpvec(vnot_v_##suffix(a.val, num)); \ + } + +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint8x16, u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint16x8, u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint32x4, u32m1, 4) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_uint64x2, u64m1, 2) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int8x16, i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int16x8, i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int32x4, i32m1, 4) +OPENCV_HAL_IMPL_RISCVV_LOGIC_OPN(v_int64x2, i64m1, 2) + +#define OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(bin_op, intrin) \ +inline v_float32x4 bin_op(const v_float32x4& a, const v_float32x4& b) \ +{ \ + return v_float32x4(vreinterpret_v_i32m1_f32m1(intrin(vreinterpret_v_f32m1_i32m1(a.val), vreinterpret_v_f32m1_i32m1(b.val), 4))); \ +} + +OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_and, vand_vv_i32m1) +OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_or, vor_vv_i32m1) +OPENCV_HAL_IMPL_RISCVV_FLT_BIT_OP(v_xor, vxor_vv_i32m1) + +inline v_float32x4 v_not(const v_float32x4& a) +{ + return v_float32x4(vreinterpret_v_i32m1_f32m1(vnot_v_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 4))); +} + +#define OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(bin_op, intrin) \ +inline v_float64x2 bin_op(const v_float64x2& a, const v_float64x2& b) \ +{ \ + return v_float64x2(vreinterpret_v_i64m1_f64m1(intrin(vreinterpret_v_f64m1_i64m1(a.val), vreinterpret_v_f64m1_i64m1(b.val), 2))); \ +} + +OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_and, vand_vv_i64m1) +OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_or, vor_vv_i64m1) +OPENCV_HAL_IMPL_RISCVV_FLT_64BIT_OP(v_xor, vxor_vv_i64m1) + +inline v_float64x2 v_not(const v_float64x2& a) +{ + return v_float64x2(vreinterpret_v_i64m1_f64m1(vnot_v_i64m1(vreinterpret_v_f64m1_i64m1(a.val), 2))); +} +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + return v_int16x8(vmulh_vv_i16m1(a.val, b.val, 8)); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + return v_uint16x8(vmulhu_vv_u16m1(a.val, b.val, 8)); +} + +//#define OPENCV_HAL_IMPL_RISCVV_ABS(_Tpuvec, _Tpsvec, usuffix, ssuffix) \ +//inline _Tpuvec v_abs(const _Tpsvec& a) { \ +// E##xm1_t mask=vmflt_vf_e32xm1_f32m1(x.val, 0.0, 4); + +//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint8x16, v_int8x16, u8, s8) +//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint16x8, v_int16x8, u16, s16) +//OPENCV_HAL_IMPL_RISCVV_ABS(v_uint32x4, v_int32x4, u32, s32) + +inline v_uint32x4 v_abs(v_int32x4 x) +{ + vbool32_t mask=vmslt_vx_i32m1_b32(x.val, 0, 4); + return v_uint32x4(vreinterpret_v_i32m1_u32m1(vrsub_vx_i32m1_m(mask, x.val, x.val, 0, 4))); +} + +inline v_uint16x8 v_abs(v_int16x8 x) +{ + vbool16_t mask=vmslt_vx_i16m1_b16(x.val, 0, 8); + return v_uint16x8(vreinterpret_v_i16m1_u16m1(vrsub_vx_i16m1_m(mask, x.val, x.val, 0, 8))); +} + +inline v_uint8x16 v_abs(v_int8x16 x) +{ + vbool8_t mask=vmslt_vx_i8m1_b8(x.val, 0, 16); + return v_uint8x16(vreinterpret_v_i8m1_u8m1(vrsub_vx_i8m1_m(mask, x.val, x.val, 0, 16))); +} + +inline v_float32x4 v_abs(v_float32x4 x) +{ + return (v_float32x4)vfsgnjx_vv_f32m1(x.val, x.val, 4); +} + +inline v_float64x2 v_abs(v_float64x2 x) +{ + return (v_float64x2)vfsgnjx_vv_f64m1(x.val, x.val, 2); +} + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ + vfloat32m1_t ret = vfsub_vv_f32m1(a.val, b.val, 4); + return (v_float32x4)vfsgnjx_vv_f32m1(ret, ret, 4); +} + +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ + vfloat64m1_t ret = vfsub_vv_f64m1(a.val, b.val, 2); + return (v_float64x2)vfsgnjx_vv_f64m1(ret, ret, 2); +} + +#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(bit, num) \ +inline v_uint##bit##x##num v_absdiff(v_uint##bit##x##num a, v_uint##bit##x##num b){ \ + vuint##bit##m1_t vmax = vmaxu_vv_u##bit##m1(a.val, b.val, num); \ + vuint##bit##m1_t vmin = vminu_vv_u##bit##m1(a.val, b.val, num); \ + return v_uint##bit##x##num(vsub_vv_u##bit##m1(vmax, vmin, num));\ +} + +OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(8, 16) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(16, 8) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF_U(32, 4) + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(v_int8x16 a, v_int8x16 b){ + vint8m1_t vmax = vmax_vv_i8m1(a.val, b.val, 16); + vint8m1_t vmin = vmin_vv_i8m1(a.val, b.val, 16); + return v_int8x16(vssub_vv_i8m1(vmax, vmin, 16)); +} +inline v_int16x8 v_absdiffs(v_int16x8 a, v_int16x8 b){ + vint16m1_t vmax = vmax_vv_i16m1(a.val, b.val, 8); + vint16m1_t vmin = vmin_vv_i16m1(a.val, b.val, 8); + return v_int16x8(vssub_vv_i16m1(vmax, vmin, 8)); +} + +#define OPENCV_HAL_IMPL_RISCVV_ABSDIFF(_Tpvec, _Tpv, num) \ +inline v_uint##_Tpvec v_absdiff(v_int##_Tpvec a, v_int##_Tpvec b){ \ + vint##_Tpv##_t max = vmax_vv_i##_Tpv(a.val, b.val, num);\ + vint##_Tpv##_t min = vmin_vv_i##_Tpv(a.val, b.val, num);\ + return v_uint##_Tpvec(vreinterpret_v_i##_Tpv##_u##_Tpv(vsub_vv_i##_Tpv(max, min, num))); \ +} + +OPENCV_HAL_IMPL_RISCVV_ABSDIFF(8x16, 8m1, 16) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF(16x8, 16m1, 8) +OPENCV_HAL_IMPL_RISCVV_ABSDIFF(32x4, 32m1, 4) + +// Multiply and expand +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + vint16m2_t res = vundefined_i16m2(); + res = vwmul_vv_i16m2(a.val, b.val, 16); + c.val = vget_v_i16m2_i16m1(res, 0); + d.val = vget_v_i16m2_i16m1(res, 1); +} + +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + vuint16m2_t res = vundefined_u16m2(); + res = vwmulu_vv_u16m2(a.val, b.val, 16); + c.val = vget_v_u16m2_u16m1(res, 0); + d.val = vget_v_u16m2_u16m1(res, 1); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + vint32m2_t res = vundefined_i32m2(); + res = vwmul_vv_i32m2(a.val, b.val, 8); + c.val = vget_v_i32m2_i32m1(res, 0); + d.val = vget_v_i32m2_i32m1(res, 1); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + vuint32m2_t res = vundefined_u32m2(); + res = vwmulu_vv_u32m2(a.val, b.val, 8); + c.val = vget_v_u32m2_u32m1(res, 0); + d.val = vget_v_u32m2_u32m1(res, 1); +} + +inline void v_mul_expand(const v_int32x4& a, const v_int32x4& b, + v_int64x2& c, v_int64x2& d) +{ + vint64m2_t res = vundefined_i64m2(); + res = vwmul_vv_i64m2(a.val, b.val, 4); + c.val = vget_v_i64m2_i64m1(res, 0); + d.val = vget_v_i64m2_i64m1(res, 1); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + vuint64m2_t res = vundefined_u64m2(); + res = vwmulu_vv_u64m2(a.val, b.val, 4); + c.val = vget_v_u64m2_u64m1(res, 0); + d.val = vget_v_u64m2_u64m1(res, 1); +} + +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_add_wrap, vadd_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_add_wrap, vadd_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_add_wrap, vadd_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_add_wrap, vadd_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_sub_wrap, vsub_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_sub_wrap, vsub_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_sub_wrap, vsub_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_sub_wrap, vsub_vv_i16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint8x16, v_mul_wrap, vmul_vv_u8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int8x16, v_mul_wrap, vmul_vv_i8m1, 16) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_uint16x8, v_mul_wrap, vmul_vv_u16m1, 8) +OPENCV_HAL_IMPL_RISCVV_BINN_FUNC(v_int16x8, v_mul_wrap, vmul_vv_i16m1, 8) +//////// Dot Product //////// +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + vuint32m2_t vindex = vundefined_u32m2(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 1, 4); + vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); + vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vint32m2_t res = vundefined_i32m2(); + res = vwmul_vv_i32m2(a.val, b.val, 8); + res = vrgather_vv_i32m2(res, vindex, 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0), vget_v_i32m2_i32m1(res, 1), 4)); +} +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + vuint32m2_t vindex = vundefined_u32m2(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 1, 4); + vindex = vset_v_u32m1_u32m2(vindex, 0, vindex0); + vindex = vset_v_u32m1_u32m2(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vint32m2_t res = vundefined_i32m2(); + res = vwmul_vv_i32m2(a.val, b.val, 8); + res = vrgather_vv_i32m2(res, vindex, 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(res, 0),vget_v_i32m2_i32m1(res, 1), 4), c.val, 4)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + vuint64m2_t vindex = vundefined_u64m2(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 1, 2); + vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); + vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vint64m2_t res = vundefined_i64m2(); + res = vwmul_vv_i64m2(a.val, b.val, 4); + res = vrgather_vv_i64m2(res, vindex, 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + vuint64m2_t vindex = vundefined_u64m2(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 1, 2); + vindex = vset_v_u64m1_u64m2(vindex, 0, vindex0); + vindex = vset_v_u64m1_u64m2(vindex, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vint64m2_t res = vundefined_i64m2(); + res = vwmul_vv_i64m2(a.val, b.val, 4); + res = vrgather_vv_i64m2(res, vindex, 4); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(res, 0), vget_v_i64m2_i64m1(res, 1), 2), c.val, 2)); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v1 = vrgather_vv_u16m2(v1, vindex, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); +} + +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, + const v_uint32x4& c) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v1 = vrgather_vv_u16m2(v1, vindex, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v1 = vrgather_vv_i16m2(v1, vindex, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, + const v_int32x4& c) +{ + vuint32m4_t vindex32 = vundefined_u32m4(); + vuint32m1_t vindex0 = vid_v_u32m1(4); + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); + vindex32 = vset_v_u32m1_u32m4(vindex32, 0, vindex0); + vindex32 = vset_v_u32m1_u32m4(vindex32, 1, vadd_vx_u32m1(vindex0, 1, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 2, vadd_vx_u32m1(vindex0, 2, 4)); + vindex32 = vset_v_u32m1_u32m4(vindex32, 3, vadd_vx_u32m1(vindex0, 3, 4)); + vuint16m2_t vindex = vnsrl_wx_u16m2(vindex32, 0, 16); + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v1 = vrgather_vv_i16m2(v1, vindex, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); +} + +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v1 = vrgather_vv_u32m2(v1, vindex, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); +} + +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, + const v_uint64x2& c) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v1 = vrgather_vv_u32m2(v1, vindex, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v1 = vrgather_vv_i32m2(v1, vindex, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, + const v_int64x2& c) +{ + vuint64m4_t vindex64 = vundefined_u64m4(); + vuint64m1_t vindex0 = vid_v_u64m1(2); + vindex0 = vsll_vx_u64m1(vindex0, 2, 2); + vindex64 = vset_v_u64m1_u64m4(vindex64, 0, vindex0); + vindex64 = vset_v_u64m1_u64m4(vindex64, 1, vadd_vx_u64m1(vindex0, 1, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 2, vadd_vx_u64m1(vindex0, 2, 2)); + vindex64 = vset_v_u64m1_u64m4(vindex64, 3, vadd_vx_u64m1(vindex0, 3, 2)); + vuint32m2_t vindex = vnsrl_wx_u32m2(vindex64, 0, 8); + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v1 = vrgather_vv_i32m2(v1, vindex, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); +} + +//////// Fast Dot Product //////// +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ + vint32m2_t v1 = vundefined_i32m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4)); +} + +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ + vint32m2_t v1 = vundefined_i32m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4), c.val, 4)); +} + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ + vint64m2_t v1 = vundefined_i64m2(); + v1 = vwmul_vv_i64m2(a.val, b.val, 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2)); +} +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + vint64m2_t v1 = vundefined_i64m2(); + v1 = vwmul_vv_i64m2(a.val, b.val, 8); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 4), c.val, 4)); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4)); +} + +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ + vuint16m2_t v1 = vundefined_u16m2(); + vuint32m2_t v2 = vundefined_u32m2(); + v1 = vwmulu_vv_u16m2(a.val, b.val, 16); + v2 = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(v1, 0), vget_v_u16m2_u16m1(v1, 1), 8); + return v_uint32x4(vadd_vv_u32m1(vadd_vv_u32m1(vget_v_u32m2_u32m1(v2, 0), vget_v_u32m2_u32m1(v2, 1), 4), c.val, 4)); +} + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4)); +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ + vint16m2_t v1 = vundefined_i16m2(); + vint32m2_t v2 = vundefined_i32m2(); + v1 = vwmul_vv_i16m2(a.val, b.val, 16); + v2 = vwadd_vv_i32m2(vget_v_i16m2_i16m1(v1, 0), vget_v_i16m2_i16m1(v1, 1), 8); + return v_int32x4(vadd_vv_i32m1(vadd_vv_i32m1(vget_v_i32m2_i32m1(v2, 0), vget_v_i32m2_i32m1(v2, 1), 4), c.val, 4)); +} + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2)); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ + vuint32m2_t v1 = vundefined_u32m2(); + vuint64m2_t v2 = vundefined_u64m2(); + v1 = vwmulu_vv_u32m2(a.val, b.val, 8); + v2 = vwaddu_vv_u64m2(vget_v_u32m2_u32m1(v1, 0), vget_v_u32m2_u32m1(v1, 1), 4); + return v_uint64x2(vadd_vv_u64m1(vadd_vv_u64m1(vget_v_u64m2_u64m1(v2, 0), vget_v_u64m2_u64m1(v2, 1), 2), c.val, 2)); +} + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2)); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ + vint32m2_t v1 = vundefined_i32m2(); + vint64m2_t v2 = vundefined_i64m2(); + v1 = vwmul_vv_i32m2(a.val, b.val, 8); + v2 = vwadd_vv_i64m2(vget_v_i32m2_i32m1(v1, 0), vget_v_i32m2_i32m1(v1, 1), 4); + return v_int64x2(vadd_vv_i64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v2, 0), vget_v_i64m2_i64m1(v2, 1), 2), c.val, 2)); +} + + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(_Tpvec, _Tpvec2, len, scalartype, func, intrin, num) \ +inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ +{\ + v##_Tpvec2##m1_t val = vmv_v_x_##len##m1(0, num); \ + val = intrin(val, a.val, val, num); \ + return vmv_x_s_##len##m1_##len(val); \ +} + + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(_Tpvec, _Tpvec2, scalartype, func, funcu, num, scalerfunc) \ +inline scalartype v_reduce_##func(const v_##_Tpvec##x##num& a) \ +{\ + v##_Tpvec##m1_t val = vundefined_##_Tpvec2##m1(); \ + val = v##funcu##_vs_##_Tpvec2##m1_##_Tpvec2##m1(val, a.val, a.val, num); \ + return scalerfunc(val); \ +} +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int8, int16, i16, int, sum, vwredsum_vs_i8m1_i16m1, 16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int16, int32, i32, int, sum, vwredsum_vs_i16m1_i32m1, 8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(int32, int64, i64, int, sum, vwredsum_vs_i32m1_i64m1, 4) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint8, uint16, u16, unsigned, sum, vwredsumu_vs_u8m1_u16m1, 16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint16, uint32, u32, unsigned, sum, vwredsumu_vs_u16m1_u32m1, 8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_W(uint32, uint64, u64, unsigned, sum, vwredsumu_vs_u32m1_u64m1, 4) +inline float v_reduce_sum(const v_float32x4& a) \ +{\ + vfloat32m1_t val = vfmv_v_f_f32m1(0.0, 4); \ + val = vfredosum_vs_f32m1_f32m1(val, a.val, val, 4); \ + return vfmv_f_s_f32m1_f32(val); \ +} +inline double v_reduce_sum(const v_float64x2& a) \ +{\ + vfloat64m1_t val = vfmv_v_f_f64m1(0.0, 2); \ + val = vfredosum_vs_f64m1_f64m1(val, a.val, val, 2); \ + return vfmv_f_s_f64m1_f64(val); \ +} +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ vuint64m1_t res = vundefined_u64m1(); return vmv_x_s_u64m1_u64(vredsum_vs_u64m1_u64m1(res, a.val, vmv_v_x_u64m1(0, 2), 2)); } + +inline int64 v_reduce_sum(const v_int64x2& a) +{ vint64m1_t res = vundefined_i64m1(); return vmv_x_s_i64m1_i64(vredsum_vs_i64m1_i64m1(res, a.val, vmv_v_x_i64m1(0, 2), 2)); } + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(func) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int8, i8, int, func, red##func, 16, vmv_x_s_i8m1_i8) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int16, i16, int, func, red##func, 8, vmv_x_s_i16m1_i16) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int32, i32, int, func, red##func, 4, vmv_x_s_i32m1_i32) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(int64, i64, int, func, red##func, 2, vmv_x_s_i64m1_i64) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint8, u8, unsigned, func, red##func##u, 16, vmv_x_s_u8m1_u8) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint16, u16, unsigned, func, red##func##u, 8, vmv_x_s_u16m1_u16) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(uint32, u32, unsigned, func, red##func##u, 4, vmv_x_s_u32m1_u32) \ +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP_(float32, f32, float, func, fred##func, 4, vfmv_f_s_f32m1_f32) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(max) +OPENCV_HAL_IMPL_RISCVV_REDUCE_OP(min) + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t b0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t c0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t d0 = vfmv_v_f_f32m1(0.0, 4); + a0 = vfredosum_vs_f32m1_f32m1(a0, a.val, a0, 4); + b0 = vfredosum_vs_f32m1_f32m1(b0, b.val, b0, 4); + c0 = vfredosum_vs_f32m1_f32m1(c0, c.val, c0, 4); + d0 = vfredosum_vs_f32m1_f32m1(d0, d.val, d0, 4); + vfloat32m1_t res; + res = vslideup_vx_f32m1(a0, b0, 1, 4); + res = vslideup_vx_f32m1(res, c0, 2, 4); + res = vslideup_vx_f32m1(res, d0, 3, 4); + return v_float32x4(res); +} + +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + vfloat32m1_t a0 = vfmv_v_f_f32m1(0.0, 4); + vfloat32m1_t x = vfsub_vv_f32m1(a.val, b.val, 4); + vbool32_t mask=vmflt_vf_f32m1_b32(x, 0, 4); + vfloat32m1_t val = vfrsub_vf_f32m1_m(mask, x, x, 0, 4); + a0 = vfredosum_vs_f32m1_f32m1(a0, val, a0, 4); + return vfmv_f_s_f32m1_f32(a0); +} + +#define OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(_Tpvec, _Tpvec2) \ +inline unsigned v_reduce_sad(const _Tpvec& a, const _Tpvec&b){ \ + _Tpvec2 x = v_absdiff(a, b); \ + return v_reduce_sum(x); \ +} + +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int8x16, v_uint8x16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint8x16, v_uint8x16) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int16x8, v_uint16x8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint16x8, v_uint16x8) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_int32x4, v_uint32x4) +OPENCV_HAL_IMPL_RISCVV_REDUCE_SAD(v_uint32x4, v_uint32x4) + +#define OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(_Tpvec, _Tp, _T, num, uv) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmseq_vv_##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmsne_vv_##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmslt##uv##_Tp##_b##_T(b.val, a.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(a.val, b.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ \ + vbool##_T##_t mask = vmsle##uv##_Tp##_b##_T(b.val, a.val, num); \ + return _Tpvec(vmerge_vxm_##_Tp(mask, vmv_v_x_##_Tp(0, num), -1, num)); \ +} \ + +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int8x16, i8m1, 8, 16, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int16x8, i16m1, 16, 8, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int32x4, i32m1, 32, 4, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_int64x2, i64m1, 64, 2, _vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint8x16, u8m1, 8, 16, u_vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint16x8, u16m1, 16, 8, u_vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint32x4, u32m1, 32, 4, u_vv_) +OPENCV_HAL_IMPL_RISCVV_INT_CMP_OP(v_uint64x2, u64m1, 64, 2, u_vv_) + +//TODO: == +inline v_float32x4 v_eq(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_ne(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfne_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_lt(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmflt_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_le(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfle_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_gt(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfgt_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} +inline v_float32x4 v_ge(const v_float32x4& a, const v_float32x4& b) +{ + vbool32_t mask = vmfge_vv_f32m1_b32(a.val, b.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +}/**/ +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ + vbool32_t mask = vmfeq_vv_f32m1_b32(a.val, a.val, 4); + vint32m1_t res = vmerge_vxm_i32m1(mask, vmv_v_x_i32m1(0.0, 4), -1, 4); + return v_float32x4(vreinterpret_v_i32m1_f32m1(res)); +} + +//TODO: == +inline v_float64x2 v_eq(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_ne(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfne_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_lt(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmflt_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_le(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfle_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_gt(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfgt_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +inline v_float64x2 v_ge(const v_float64x2& a, const v_float64x2& b) +{ + vbool64_t mask = vmfge_vv_f64m1_b64(a.val, b.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +}/**/ +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ + vbool64_t mask = vmfeq_vv_f64m1_b64(a.val, a.val, 2); + vint64m1_t res = vmerge_vxm_i64m1(mask, vmv_v_x_i64m1(0.0, 2), -1, 2); + return v_float64x2(vreinterpret_v_i64m1_f64m1(res)); +} +#define OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(_Tp, _T) \ +inline void v_transpose4x4(const v_##_Tp##32x4& a0, const v_##_Tp##32x4& a1, \ + const v_##_Tp##32x4& a2, const v_##_Tp##32x4& a3, \ + v_##_Tp##32x4& b0, v_##_Tp##32x4& b1, \ + v_##_Tp##32x4& b2, v_##_Tp##32x4& b3) \ +{ \ + vuint32m4_t vindex = vundefined_u32m4(); \ + vuint32m1_t vindex0 = vid_v_u32m1(4); \ + vindex0 = vsll_vx_u32m1(vindex0, 2, 4); \ + vindex = vset_v_u32m1_u32m4(vindex, 0, vindex0); \ + vindex = vset_v_u32m1_u32m4(vindex, 1, vadd_vx_u32m1(vindex0, 1, 4)); \ + vindex = vset_v_u32m1_u32m4(vindex, 2, vadd_vx_u32m1(vindex0, 2, 4)); \ + vindex = vset_v_u32m1_u32m4(vindex, 3, vadd_vx_u32m1(vindex0, 3, 4)); \ + v##_Tp##32m4_t val = vundefined_##_T##m4(); \ + val = vset_v_##_T##m1_##_T##m4(val, 0, a0.val); \ + val = vset_v_##_T##m1_##_T##m4(val, 1, a1.val); \ + val = vset_v_##_T##m1_##_T##m4(val, 2, a2.val); \ + val = vset_v_##_T##m1_##_T##m4(val, 3, a3.val); \ + val = vrgather_vv_##_T##m4(val, vindex, 16); \ + b0.val = vget_v_##_T##m4_##_T##m1(val, 0); \ + b1.val = vget_v_##_T##m4_##_T##m1(val, 1); \ + b2.val = vget_v_##_T##m4_##_T##m1(val, 2); \ + b3.val = vget_v_##_T##m4_##_T##m1(val, 3); \ +} +OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(uint, u32) +OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(int, i32) +OPENCV_HAL_IMPL_RISCVV_TRANSPOSE4x4(float, f32) + + +#define OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(_Tpvec, suffix, _T, num) \ +inline _Tpvec v_shl(const _Tpvec& a, int n) \ +{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec((vsll_vx_##_T##m1(a.val, n, num))); } + +#define OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(_Tpvec, suffix, _T, num, intric) \ +inline _Tpvec v_shr(const _Tpvec& a, int n) \ +{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec((v##intric##_vx_##_T##m1(a.val, n, num))); }\ +template inline _Tpvec v_rshr(const _Tpvec& a) \ +{ return _Tpvec((v##intric##_vx_##_T##m1(vadd_vx_##_T##m1(a.val, 1<<(n-1), num), n, num))); } + +// trade efficiency for convenience +#define OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(suffix, _T, num, intrin) \ +OPENCV_HAL_IMPL_RISCVV_SHIFT_LEFT(v_##suffix##x##num, suffix, _T, num) \ +OPENCV_HAL_IMPL_RISCVV_SHIFT_RIGHT(v_##suffix##x##num, suffix, _T, num, intrin) + +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint8, u8, 16, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint16, u16, 8, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint32, u32, 4, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(uint64, u64, 2, srl) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int8, i8, 16, sra) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int16, i16, 8, sra) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int32, i32, 4, sra) +OPENCV_HAL_IMPL_RISCVV_SHIFT_OP(int64, i64, 2, sra) + +#if 0 +#define VUP4(n) {0, 1, 2, 3} +#define VUP8(n) {0, 1, 2, 3, 4, 5, 6, 7} +#define VUP16(n) {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15} +#define VUP2(n) {0, 1} +#endif +#define OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(_Tpvec, suffix, _T, num, num2, vmv, len) \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + suffix##m1_t tmp = vmv##_##_T##m1(0, num);\ + tmp = vslideup_vx_##_T##m1_m(vmset_m_##len(num), tmp, a.val, n, num);\ + return _Tpvec(tmp);\ +} \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + suffix##m1_t res = vundefined_##_T##m1(); \ + return _Tpvec(vslidedown_vx_##_T##m1(res, a.val, n, num));\ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + suffix##m2_t tmp = vundefined_##_T##m2(); \ + suffix##m2_t res = vundefined_##_T##m2(); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, b.val); \ + res = vslidedown_vx_##_T##m2(res, tmp, n, num2);\ + return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 0));\ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + suffix##m2_t tmp = vundefined_##_T##m2(); \ + suffix##m2_t res = vundefined_##_T##m2(); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, b.val); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a.val); \ + res = vslideup_vx_##_T##m2(res, tmp, n, num2);\ + return _Tpvec(vget_v_##_T##m2_##_T##m1(res, 1));\ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ \ + CV_UNUSED(b); return a; \ +} + +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint8x16, vuint8, u8, 16, 32, vmv_v_x, b8) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int8x16, vint8, i8, 16, 32, vmv_v_x, b8) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint16x8, vuint16, u16, 8, 16, vmv_v_x, b16) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int16x8, vint16, i16, 8, 16, vmv_v_x, b16) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint32x4, vuint32, u32, 4, 8, vmv_v_x, b32) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int32x4, vint32, i32, 4, 8, vmv_v_x, b32) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_uint64x2, vuint64, u64, 2, 4, vmv_v_x, b64) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_int64x2, vint64, i64, 2, 4, vmv_v_x, b64) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float32x4, vfloat32, f32, 4, 8, vfmv_v_f, b32) +OPENCV_HAL_IMPL_RISCVV_ROTATE_OP(v_float64x2, vfloat64, f64, 2, 4, vfmv_v_f, b64) + +#if 1 +#define vreinterpret_v_i8m1_i8m1 +#define vreinterpret_v_u8m1_u8m1 +#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize, ldst_len, ldst_type) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp2##_t res = vundefined_##len(); \ + _Tp2##_t res1 = vundefined_##len(); \ + res = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr0, 8)); \ + res1 = vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr1, 8)); \ + res = vslideup_vx_##len(res, res1, hnum, num); \ + return _Tpvec(res); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 8))); }\ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_##ldst_len##_##len(vle8_v_##ldst_len((ldst_type *)ptr, 16))); } \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 8);}\ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tp2##_t a0 = vundefined_##len(); \ + a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ + vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a0), 8);}\ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vse8_v_##ldst_len((ldst_type *)ptr, vreinterpret_v_##len##_##ldst_len(a.val), 16); } + +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8, i8m1, schar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16, i8m1, schar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32, i8m1, schar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64, u8m1, uchar) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64, i8m1, schar) + +#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp2##_t res = vundefined_##len(); \ + _Tp2##_t res1 = vundefined_##len(); \ + res = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr0, 8))); \ + res1 = vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr1, 8))); \ + res = vslideup_vx_##len(res, res1, hnum, num); \ + return _Tpvec(res); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 8)))); }\ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vreinterpret_v_u##elemsize##m1_##len(vreinterpret_v_u8m1_u##elemsize##m1(vle8_v_u8m1((uchar *)ptr, 16)))); } \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 8);}\ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tp2##_t a0 = vundefined_##len(); \ + a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ + vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a0)), 8);}\ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vse8_v_u8m1((uchar *)ptr, vreinterpret_v_u##elemsize##m1_u8m1(vreinterpret_v_##len##_u##elemsize##m1(a.val)), 16); } +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_FLOAT_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) + +#else + +#define OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(_Tpvec, _Tp, _Tp2, len, hnum, num, elemsize) \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp2##_t res, res1; \ + res = vle##elemsize##_v_##len(ptr0, hnum); \ + res1 = vle##elemsize##_v_##len(ptr1, hnum); \ + res = vslideup_vx_##len(res, res1, hnum, num); \ + return _Tpvec(res); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, hnum)); }\ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(vle##elemsize##_v_##len(ptr, num)); } \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec((_Tp2##_t)vle##elemsize##_v_##len((const _Tp *)ptr, num)); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, hnum);}\ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tp2##_t a0; \ + a0 = vslidedown_vx_##len(a0, a.val, hnum, num); \ + vse##elemsize##_v_##len(ptr, a0, hnum);}\ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ vse##elemsize##_v_##len(ptr, a.val, num); } + +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint8x16, uchar, vuint8m1, u8m1, 8, 16, 8) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int8x16, schar, vint8m1, i8m1, 8, 16, 8) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint16x8, ushort, vuint16m1, u16m1, 4, 8, 16) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int16x8, short, vint16m1, i16m1, 4, 8, 16) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint32x4, unsigned, vuint32m1, u32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int32x4, int, vint32m1, i32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_uint64x2, unsigned long, vuint64m1, u64m1, 1, 2, 64) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_int64x2, long, vint64m1, i64m1, 1, 2, 64) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float32x4, float, vfloat32m1, f32m1, 2, 4, 32) +OPENCV_HAL_IMPL_RISCVV_LOADSTORE_OP(v_float64x2, double, vfloat64m1, f64m1, 1, 2, 64) + +#endif + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ +#if 0 + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[ 0]], + tab[idx[ 1]], + tab[idx[ 2]], + tab[idx[ 3]], + tab[idx[ 4]], + tab[idx[ 5]], + tab[idx[ 6]], + tab[idx[ 7]], + tab[idx[ 8]], + tab[idx[ 9]], + tab[idx[10]], + tab[idx[11]], + tab[idx[12]], + tab[idx[13]], + tab[idx[14]], + tab[idx[15]] + }; + return v_int8x16(vle8_v_i8m1(elems, 16)); +#else +#if __riscv_v == 7000 + return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, vle32_v_u32m4((unsigned int *)idx, 16), 16), 0, 16), 0, 16)); +#else + return v_int8x16(vloxei32_v_i8m1(tab, vle32_v_u32m4((unsigned int *)idx, 16), 16)); +#endif +#endif +} + +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx){ +#if 0 + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[4]], + tab[idx[4] + 1], + tab[idx[5]], + tab[idx[5] + 1], + tab[idx[6]], + tab[idx[6] + 1], + tab[idx[7]], + tab[idx[7] + 1] + }; + return v_int8x16(vle8_v_i8m1(elems, 16)); +#else + vuint32m4_t seq, index; + vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 8); + seq = vid_v_u32m4(16); + index = vsrl_vx_u32m4(seq, 1, 16); + vidx = vrgather_vv_u32m4(vidx, index, 16); + index = vadd_vv_u32m4(vand_vx_u32m4(seq, 1, 16), vidx, 16); +#if __riscv_v == 7000 + return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); +#else + return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); +#endif +#endif +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ +#if 0 + schar CV_DECL_ALIGNED(32) elems[16] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[2] + 2], + tab[idx[2] + 3], + tab[idx[3]], + tab[idx[3] + 1], + tab[idx[3] + 2], + tab[idx[3] + 3] + }; + return v_int8x16(vle8_v_i8m1(elems, 16)); +#else + vuint32m4_t seq, index; + vuint32m4_t vidx = vle32_v_u32m4((unsigned int *)idx, 4); + seq = vid_v_u32m4(16); + index = vsrl_vx_u32m4(seq, 2, 16); + vidx = vrgather_vv_u32m4(vidx, index, 16); + seq = vset_v_u32m1_u32m4(seq, 1, vget_v_u32m4_u32m1(seq, 0)); + seq = vset_v_u32m1_u32m4(seq, 2, vget_v_u32m4_u32m1(seq, 0)); + seq = vset_v_u32m1_u32m4(seq, 3, vget_v_u32m4_u32m1(seq, 0)); + index = vadd_vv_u32m4(seq, vidx, 16); +#if __riscv_v == 7000 + return v_int8x16(vnclip_wx_i8m1(vnclip_wx_i16m2(vlxb_v_i32m4((const int *)tab, index, 16), 0, 16), 0, 16)); +#else + return v_int8x16(vloxei32_v_i8m1(tab, index, 16)); +#endif +#endif +} + +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ +#if 0 + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]], + tab[idx[4]], + tab[idx[5]], + tab[idx[6]], + tab[idx[7]] + }; + return v_int16x8(vle16_v_i16m1(elems, 8)); +#else +#if __riscv_v == 7000 + return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8), 0, 8)); +#else + return v_int16x8(vloxei32_v_i16m1(tab, vsll_vx_u32m2(vle32_v_u32m2((unsigned int *)idx, 8), 1, 8), 8)); +#endif +#endif +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ +#if 0 + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[2]], + tab[idx[2] + 1], + tab[idx[3]], + tab[idx[3] + 1] + }; + return v_int16x8(vle16_v_i16m1(elems, 8)); +#else + vuint32m2_t seq, index; + vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 4); + seq = vid_v_u32m2(8); + index = vsrl_vx_u32m2(seq, 1, 8); + vidx = vrgather_vv_u32m2(vidx, index, 8); + index = vsll_vx_u32m2(vadd_vv_u32m2(vand_vx_u32m2(seq, 1, 8), vidx, 8), 1, 8); +#if __riscv_v == 7000 + return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); +#else + return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); +#endif +#endif +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ +#if 0 + short CV_DECL_ALIGNED(32) elems[8] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[0] + 2], + tab[idx[0] + 3], + tab[idx[1]], + tab[idx[1] + 1], + tab[idx[1] + 2], + tab[idx[1] + 3] + }; + return v_int16x8(vle16_v_i16m1(elems, 8)); +#else + vuint32m2_t seq, index; + vuint32m2_t vidx = vle32_v_u32m2((unsigned int *)idx, 2); + seq = vid_v_u32m2(8); + index = vsrl_vx_u32m2(seq, 2, 8); + vidx = vrgather_vv_u32m2(vidx, index, 8); + seq = vset_v_u32m1_u32m2(seq, 1, vget_v_u32m2_u32m1(seq, 0)); + index = vsll_vx_u32m2(vadd_vv_u32m2(seq, vidx, 8), 1, 8); +#if __riscv_v == 7000 + return v_int16x8(vnclip_wx_i16m1(vlxh_v_i32m2((const int *)tab, index, 8), 0, 8)); +#else + return v_int16x8(vloxei32_v_i16m1(tab, index, 8)); +#endif +#endif +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ +#if 0 + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_int32x4(vle32_v_i32m1(elems, 4)); +#else + return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); +#endif +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ +#if 0 + int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[0] + 1], + tab[idx[1]], + tab[idx[1] + 1] + }; + return v_int32x4(vle32_v_i32m1(elems, 4)); +#else + vuint32m1_t seq, index; + vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); + seq = vid_v_u32m1(4); + index = vsrl_vx_u32m1(seq, 1, 4); + vidx = vrgather_vv_u32m1(vidx, index, 4); + index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); + return v_int32x4(vloxei32_v_i32m1(tab, index, 4)); +#endif +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(vle32_v_i32m1(tab+idx[0], 4)); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + //vint64m1_t res = {tab[idx[0]], tab[idx[1]]}; + return v_int64x2(vloxei64_v_i64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(vle64_v_i64m1(tab+idx[0], 2)); +} + +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) +{ + //vuint64m1_t res = {tab[idx[0]], tab[idx[1]]}; + return v_uint64x2(vloxei64_v_u64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); +} +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) +{ + return v_uint64x2(vle64_v_u64m1(tab+idx[0], 2)); +} + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ +#if 0 + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[1]], + tab[idx[2]], + tab[idx[3]] + }; + return v_float32x4(vle32_v_f32m1(elems, 4)); +#else + return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vle32_v_u32m1((unsigned int *)idx, 4), 2, 4), 4)); +#endif +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) +{ +#if 0 + float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idx[0]], + tab[idx[0]+1], + tab[idx[1]], + tab[idx[1]+1] + }; + return v_float32x4(vle32_v_f32m1(elems, 4)); +#else + vuint32m1_t seq, index; + vuint32m1_t vidx = vle32_v_u32m1((unsigned int *)idx, 2); + seq = vid_v_u32m1(4); + index = vsrl_vx_u32m1(seq, 1, 4); + vidx = vrgather_vv_u32m1(vidx, index, 4); + index = vsll_vx_u32m1(vadd_vv_u32m1(vand_vx_u32m1(seq, 1, 4), vidx, 4), 2, 4); + return v_float32x4(vloxei32_v_f32m1(tab, index, 4)); +#endif +} +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) +{ + return v_float32x4(vle32_v_f32m1(tab + idx[0], 4)); +} +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + //vfloat64m1_t res = {tab[idx[0]], tab[idx[1]]}; + return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vget_v_u64m2_u64m1(vwaddu_vx_u64m2(vle32_v_u32m1((uint32_t*)idx, 2), 0, 2), 0), 3, 2), 2)); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(vle64_v_f64m1(tab+idx[0], 2)); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + /*int CV_DECL_ALIGNED(32) elems[4] = + { + tab[idxvec.val[0]], + tab[idxvec.val[1]], + tab[idxvec.val[2]], + tab[idxvec.val[3]] + };*/ + return v_int32x4(vloxei32_v_i32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + /*unsigned CV_DECL_ALIGNED(32) elems[4] = + { + tab[idxvec.val[0]], + tab[idxvec.val[1]], + tab[idxvec.val[2]], + tab[idxvec.val[3]] + };*/ + return v_uint32x4(vloxei32_v_u32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + /*float CV_DECL_ALIGNED(32) elems[4] = + { + tab[idxvec.val[0]], + tab[idxvec.val[1]], + tab[idxvec.val[2]], + tab[idxvec.val[3]] + };*/ + return v_float32x4(vloxei32_v_f32m1(tab, vsll_vx_u32m1(vreinterpret_v_i32m1_u32m1(idxvec.val), 2, 4), 4)); +} +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + //vfloat64m1_t res = {tab[idxvec.val[0]], tab[idxvec.val[1]]}; + return v_float64x2(vloxei64_v_f64m1(tab, vsll_vx_u64m1(vreinterpret_v_i64m1_u64m1(vget_v_i64m2_i64m1(vwadd_vx_i64m2(idxvec.val, 0, 2), 0)), 3, 2), 2)); +} +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + vint32m1_t index = vmul_vx_i32m1(idxvec.val, 4, 4); + //vint32m1_t index_y = vadd_vx_i32m1(index_x, 4, 4); + + //x.val = vlxe_v_f32m1(tab, index_x, 4); + //y.val = vlxe_v_f32m1(tab, index_y, 4); + vloxseg2ei32_v_f32m1(&x.val, &y.val, tab, vreinterpret_v_i32m1_u32m1(index), 4); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + + x = v_float64x2(tab[idx[0]], tab[idx[1]]); + y = v_float64x2(tab[idx[0]+1], tab[idx[1]+1]); +} + +#define OPENCV_HAL_IMPL_RISCVV_PACKS(_Tp, _Tp2, _T2, num2, _T1, num, intrin, shr, _Type, elemsize) \ +inline v_##_Tp##x##num v_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ + return v_##_Tp##x##num(shr##_##_T1##m1(tmp, 0, num)); \ +}\ +template inline \ +v_##_Tp##x##num v_rshr_pack(const v_##_Tp2##x##num2& a, const v_##_Tp2##x##num2& b) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, b.val); \ + return v_##_Tp##x##num(intrin##_##_T1##m1(tmp, n, num)); \ +}\ +inline void v_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ + asm("" ::: "memory"); \ + vse##elemsize##_v_##_T1##m1(ptr, shr##_##_T1##m1(tmp, 0, num), num2); \ +}\ +template inline \ +void v_rshr_pack_store(_Type* ptr, const v_##_Tp2##x##num2& a) \ +{ \ + v##_Tp2##m2_t tmp = vundefined_##_T2##m2(); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 0, a.val); \ + tmp = vset_v_##_T2##m1_##_T2##m2(tmp, 1, vmv_v_x_##_T2##m1(0, num2)); \ + vse##elemsize##_v_##_T1##m1(ptr, intrin##_##_T1##m1(tmp, n, num), num2); \ +} +OPENCV_HAL_IMPL_RISCVV_PACKS(int8, int16, i16, 8, i8, 16, vnclip_wx, vnclip_wx, signed char, 8) +OPENCV_HAL_IMPL_RISCVV_PACKS(int16, int32, i32, 4, i16, 8, vnclip_wx, vnclip_wx, signed short, 16) +OPENCV_HAL_IMPL_RISCVV_PACKS(int32, int64, i64, 2, i32, 4, vnclip_wx, vnsra_wx, int, 32) +OPENCV_HAL_IMPL_RISCVV_PACKS(uint8, uint16, u16, 8, u8, 16, vnclipu_wx, vnclipu_wx, unsigned char, 8) +OPENCV_HAL_IMPL_RISCVV_PACKS(uint16, uint32, u32, 4, u16, 8, vnclipu_wx, vnclipu_wx, unsigned short, 16) +OPENCV_HAL_IMPL_RISCVV_PACKS(uint32, uint64, u64, 2, u32, 4, vnclipu_wx, vnsrl_wx, unsigned int, 32) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + vuint16m2_t tmp = vundefined_u16m2(); \ + tmp = vset_v_u16m1_u16m2(tmp, 0, a.val); \ + tmp = vset_v_u16m1_u16m2(tmp, 1, b.val); \ + return v_uint8x16(vnsrl_wx_u8m1(tmp, 0, 16)); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + vuint32m4_t vabcd = vundefined_u32m4(); \ + vuint16m2_t v16 = vundefined_u16m2(); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 0, a.val); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 1, b.val); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 2, c.val); \ + vabcd = vset_v_u32m1_u32m4(vabcd, 3, d.val); \ + v16 = vnsrl_wx_u16m2(vabcd, 0, 16); + return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + vuint64m8_t v64 = vundefined_u64m8(); \ + vuint32m4_t v32 = vundefined_u32m4(); \ + vuint16m2_t v16 = vundefined_u16m2(); \ + v64 = vset_v_u64m1_u64m8(v64, 0, a.val); \ + v64 = vset_v_u64m1_u64m8(v64, 1, b.val); \ + v64 = vset_v_u64m1_u64m8(v64, 2, c.val); \ + v64 = vset_v_u64m1_u64m8(v64, 3, d.val); \ + v64 = vset_v_u64m1_u64m8(v64, 4, e.val); \ + v64 = vset_v_u64m1_u64m8(v64, 5, f.val); \ + v64 = vset_v_u64m1_u64m8(v64, 6, g.val); \ + v64 = vset_v_u64m1_u64m8(v64, 7, h.val); \ + v32 = vnsrl_wx_u32m4(v64, 0, 16); + v16 = vnsrl_wx_u16m2(v32, 0, 16); + return v_uint8x16(vnsrl_wx_u8m1(v16, 0, 16)); +} + +//inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) \ +//{ \ +// int16xm2_u tmp; \ +// tmp.m1[0] = (vint16m1_t)a.val; \ +// tmp.m1[1] = (vint16m1_t)b.val; \ +// e8xm1_t mask = (e8xm1_t)vmsge_vx_e16xm2_i16m2(tmp.v, 0, 16);\ +// return v_uint8x16(vnclipuvi_mask_u8m1_u16m2(vmv_v_x_u8m1(0, 16), (vuint16m2_t)tmp.v, 0, mask, 16)); +//} + +#define OPENCV_HAL_IMPL_RISCVV_PACK_U(tp1, num1, tp2, num2, _Tp) \ +inline v_uint##tp1##x##num1 v_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ + vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1)); \ +} \ +inline void v_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + return vse##tp1##_v_u##tp1##m1(ptr, vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), 0, num1), num2); \ +} \ +template inline \ +v_uint##tp1##x##num1 v_rshr_pack_u(const v_int##tp2##x##num2& a, const v_int##tp2##x##num2& b) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 1, b.val); \ + vint##tp2##m2_t val = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + return v_uint##tp1##x##num1(vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val), n, num1)); \ +} \ +template inline \ +void v_rshr_pack_u_store(_Tp* ptr, const v_int##tp2##x##num2& a) \ +{ \ + vint##tp2##m2_t tmp = vundefined_##i##tp2##m2(); \ + tmp = vset_v_##i##tp2##m1_##i##tp2##m2(tmp, 0, a.val); \ + vint##tp2##m2_t val_ = vmax_vx_i##tp2##m2(tmp, 0, num1);\ + vuint##tp1##m1_t val = vnclipu_wx_u##tp1##m1(vreinterpret_v_i##tp2##m2_u##tp2##m2(val_), n, num1); \ + return vse##tp1##_v_u##tp1##m1(ptr, val, num2);\ +} +OPENCV_HAL_IMPL_RISCVV_PACK_U(8, 16, 16, 8, unsigned char ) +OPENCV_HAL_IMPL_RISCVV_PACK_U(16, 8, 32, 4, unsigned short) + + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_RISCVV_MUL_SAT(_Tpvec, num, mul, cvt) \ + inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ + { \ + auto res = mul(a.val, b.val, num); \ + return _Tpvec(cvt(res, 0, num)); \ + } + +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int8x16, 16, vwmul_vv_i16m2, vnclip_wx_i8m1) +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint8x16, 16, vwmulu_vv_u16m2, vnclipu_wx_u8m1) +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_int16x8, 32, vwmul_vv_i32m2, vnclip_wx_i16m1) +OPENCV_HAL_IMPL_RISCVV_MUL_SAT(v_uint16x8, 32, vwmulu_vv_u32m2, vnclipu_wx_u16m1) + + +static const signed char popCountTable[256] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; + +inline vuint8m1_t vcnt_u8(vuint8m1_t val){ +#if __riscv_v == 7000 + vuint8m1_t v0 = vand_vx_u8m1(val, 1, 16); + return vadd_vv_u8m1(vloxei8_v_u8m1((unsigned char*)popCountTable, vsrl_vx_u8m1(val, 1, 16), 16), v0, 16); +#else + return vloxei8_v_u8m1((unsigned char*)popCountTable, val, 16); +#endif +} + +inline v_uint8x16 +v_popcount(const v_uint8x16& a) +{ + return v_uint8x16(vcnt_u8(a.val)); +} + +inline v_uint8x16 +v_popcount(const v_int8x16& a) +{ + return v_uint8x16(vcnt_u8(vreinterpret_v_i8m1_u8m1(a.val))); +} + +inline v_uint16x8 +v_popcount(const v_uint16x8& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u16m1_u8m1(a.val)); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); +} + +inline v_uint16x8 +v_popcount(const v_int16x8& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(a.val))); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + return v_uint16x8(vget_v_u16m2_u16m1(vwaddu_vv_u16m2(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8), 0)); +} + +inline v_uint32x4 +v_popcount(const v_uint32x4& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u32m1_u8m1(a.val)); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); + return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); +} + +inline v_uint32x4 +v_popcount(const v_int32x4& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(a.val))); + vuint8m1_t seq = vid_v_u8m1(8); + vuint8m1_t index = vsll_vx_u8m1(seq, 1, 8); + vuint8m1_t sum = vadd_vv_u8m1(vrgather_vv_u8m1(tmp, index, 8), vrgather_vv_u8m1(tmp, vadd_vx_u8m1(index, 1, 8), 8), 8); + return v_uint32x4(vget_v_u32m4_u32m1(vwaddu_vx_u32m4(vwaddu_vv_u16m2(vrgather_vv_u8m1(sum, index, 4), vrgather_vv_u8m1(sum, vadd_vx_u8m1(index, 1, 4), 4), 4), 0, 4), 0)); +} + +inline v_uint64x2 +v_popcount(const v_uint64x2& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_u64m1_u8m1(a.val)); + vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); + vuint16m1_t res1 = vundefined_u16m1(); + vuint16m1_t res2 = vundefined_u16m1(); + res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); + res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); + return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); +} + +inline v_uint64x2 +v_popcount(const v_int64x2& a) +{ + vuint8m1_t tmp = vcnt_u8(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i64m1_i8m1(a.val))); + vuint16m2_t tmp16 = vwaddu_vx_u16m2(tmp, 0, 16); + vuint16m1_t res1 = vundefined_u16m1(), res2 = vundefined_u16m1(); + res1 = vredsum_vs_u16m1_u16m1(res1, vget_v_u16m2_u16m1(tmp16, 0), vmv_v_x_u16m1(0, 8), 8); + res2 = vredsum_vs_u16m1_u16m1(res2, vget_v_u16m2_u16m1(tmp16, 1), vmv_v_x_u16m1(0, 8), 8); + return v_uint64x2((unsigned long)vmv_x_s_u16m1_u16(res1), (unsigned long)vmv_x_s_u16m1_u16(res2)); +} + +#define SMASK 1, 2, 4, 8, 16, 32, 64, 128 +inline int v_signmask(const v_uint8x16& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint8m1_t id = vid_v_u8m1(16); + vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); + vuint8m1_t t0 = vsrl_vx_u8m1(a.val, 7, 16); + vbool8_t mask = vmseq_vx_u8m1_b8(t0, 1, 16); + res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); + return vmv_x_s_u16m1_u16(res); +} +inline int v_signmask(const v_int8x16& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint8m1_t id = vid_v_u8m1(16); + vuint16m2_t num = vsll_vv_u16m2(vmv_v_x_u16m2(1, 16), vwaddu_vx_u16m2(id, 0, 16), 16); + vbool8_t mask = vmslt_vx_i8m1_b8(a.val, 0, 16); + res = vredsum_vs_u16m2_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); + return vmv_x_s_u16m1_u16(res); +} + +inline int v_signmask(const v_int16x8& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint16m1_t id = vid_v_u16m1(8); + vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); + vbool16_t mask = vmslt_vx_i16m1_b16(a.val, 0, 8); + res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 16); + return vmv_x_s_u16m1_u16(res); +} +inline int v_signmask(const v_uint16x8& a) +{ + vuint16m1_t res = vundefined_u16m1(); + vuint16m1_t id = vid_v_u16m1(8); + vuint16m1_t num = vsll_vv_u16m1(vmv_v_x_u16m1(1, 8), id, 8); + vuint16m1_t t0 = vsrl_vx_u16m1(a.val, 15, 8); + vbool16_t mask = vmseq_vx_u16m1_b16(t0, 1, 8); + res = vredsum_vs_u16m1_u16m1_m(mask, res, num, vmv_v_x_u16m1(0, 8), 8); + return vmv_x_s_u16m1_u16(res); +} +inline int v_signmask(const v_int32x4& a) +{ + vuint32m1_t res = vundefined_u32m1(); + vuint32m1_t id = vid_v_u32m1(4); + vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); + vbool32_t mask = vmslt_vx_i32m1_b32(a.val, 0, 4); + res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); + return vmv_x_s_u32m1_u32(res); +} +inline int v_signmask(const v_uint32x4& a) +{ + vuint32m1_t res = vundefined_u32m1(); + vuint32m1_t id = vid_v_u32m1(4); + vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); + vuint32m1_t t0 = vsrl_vx_u32m1(a.val, 31, 4); + vbool32_t mask = vmseq_vx_u32m1_b32(t0, 1, 4); + res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); + return vmv_x_s_u32m1_u32(res); +} +inline int v_signmask(const v_uint64x2& a) +{ + vuint64m1_t res = vundefined_u64m1(); + vuint64m1_t id = vid_v_u64m1(2); + vuint64m1_t num = vsll_vv_u64m1(vmv_v_x_u64m1(1, 2), id, 2); + vuint64m1_t t0 = vsrl_vx_u64m1(a.val, 63, 2); + vbool64_t mask = vmseq_vx_u64m1_b64(t0, 1, 2); + res = vredsum_vs_u64m1_u64m1_m(mask, res, num, vmv_v_x_u64m1(0, 2), 2); + return vmv_x_s_u64m1_u64(res); +} +inline int v_signmask(const v_int64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_u64(a)); } +inline int v_signmask(const v_float32x4& a) +{ + return v_signmask(v_reinterpret_as_u32(a)); + /* + vuint32m1_t res; + vuint32m1_t id = vid_v_u32m1(4); + vuint32m1_t num = vsll_vv_u32m1(vmv_v_x_u32m1(1, 4), id, 4); + vbool32_t mask = vmflt_vf_f32m1_b32(a.val, 0, 4); + res = vredsum_vs_u32m1_u32m1_m(mask, res, num, vmv_v_x_u32m1(0, 4), 4); + return vmv_x_s_u32m1_u32(res);*/ +} + +inline int v_scan_forward(const v_int8x16& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint8x16& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_int16x8& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint16x8& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_int32x4& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint32x4& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_float32x4& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_int64x2& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } +inline int v_scan_forward(const v_uint64x2& a) { +int val = v_signmask(a); +if(val==0) return 0; +else return trailingZeros32(val); } + +#define OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(_Tpvec, suffix, _T, shift, num, mask_b) \ +inline bool v_check_all(const v_##_Tpvec& a) \ +{ \ + suffix##m1_t v0 = vsrl_vx_##_T(vnot_v_##_T(a.val, num), shift, num); \ + return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) == 0; \ +} \ +inline bool v_check_any(const v_##_Tpvec& a) \ +{ \ + suffix##m1_t v0 = vsrl_vx_##_T(a.val, shift, num); \ + return (vcpop_m_##mask_b(vmseq_vx_##_T##_##mask_b(v0, 1, num), num)) != 0; \ +} + +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint8x16, vuint8, u8m1, 7, 16, b8) +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint16x8, vuint16, u16m1, 15, 8, b16) +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint32x4, vuint32, u32m1, 31, 4, b32) +OPENCV_HAL_IMPL_RISCVV_CHECK_ALLANY(uint64x2, vuint64, u64m1, 63, 2, b64) + +inline bool v_check_all(const v_int8x16& a) +{ return v_check_all(v_reinterpret_as_u8(a)); } +inline bool v_check_all(const v_int16x8& a) +{ return v_check_all(v_reinterpret_as_u16(a)); } +inline bool v_check_all(const v_int32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_u32(a)); } +inline bool v_check_all(const v_int64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_u64(a)); } + +inline bool v_check_any(const v_int8x16& a) +{ return v_check_any(v_reinterpret_as_u8(a)); } +inline bool v_check_any(const v_int16x8& a) +{ return v_check_any(v_reinterpret_as_u16(a)); } +inline bool v_check_any(const v_int32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_u32(a)); } +inline bool v_check_any(const v_int64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_u64(a)); } + +#define OPENCV_HAL_IMPL_RISCVV_SELECT(_Tpvec, suffix, _Tpvec2, num, mask_func) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(vmerge_vvm_##suffix(mask_func(mask.val, 0, num), b.val, a.val, num)); \ +} + +OPENCV_HAL_IMPL_RISCVV_SELECT(v_int8x16, i8m1, vbool8_t, 16, vmsne_vx_i8m1_b8) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_int16x8, i16m1, vbool16_t, 8, vmsne_vx_i16m1_b16) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_int32x4, i32m1, vbool32_t, 4, vmsne_vx_i32m1_b32) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint8x16, u8m1, vbool8_t, 16, vmsne_vx_u8m1_b8) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint16x8, u16m1, vbool16_t, 8, vmsne_vx_u16m1_b16) +OPENCV_HAL_IMPL_RISCVV_SELECT(v_uint32x4, u32m1, vbool32_t, 4, vmsne_vx_u32m1_b32) +inline v_float32x4 v_select(const v_float32x4& mask, const v_float32x4& a, const v_float32x4& b) +{ + return v_float32x4(vmerge_vvm_f32m1(vmfne_vf_f32m1_b32(mask.val, 0, 4), b.val, a.val, 4)); +} +inline v_float64x2 v_select(const v_float64x2& mask, const v_float64x2& a, const v_float64x2& b) +{ + return v_float64x2(vmerge_vvm_f64m1(vmfne_vf_f64m1_b64(mask.val, 0, 2), b.val, a.val, 2)); +} + +#define OPENCV_HAL_IMPL_RISCVV_EXPAND(add, _Tpvec, _Tpwvec, _Tp, _Tp1, num1, _Tp2, num2, _T1, _T2, num3) \ +inline void v_expand(const _Tpvec& a, v_##_Tpwvec& b0, v_##_Tpwvec& b1) \ +{ \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ + b0.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 0); \ + b1.val = vget_v_##_Tp2##m2_##_Tp2##m1(b, 1); \ +} \ +inline v_##_Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num2); \ + return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ +} \ +inline v_##_Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(a.val, 0, num1); \ + return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 1)); \ +} \ +inline v_##_Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + _T2##_t val = vle##num3##_v_##_Tp1(ptr, num2); \ + _T1##_t b = vw##add##_vx_##_Tp2##m2(val, 0, num2); \ + return v_##_Tpwvec(vget_v_##_Tp2##m2_##_Tp2##m1(b, 0)); \ +} + +OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint8x16, uint16x8, uchar, u8m1, 16, u16, 8, vuint16m2, vuint8m1, 8) +OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint16x8, uint32x4, ushort, u16m1, 8, u32, 4, vuint32m2, vuint16m1, 16) +OPENCV_HAL_IMPL_RISCVV_EXPAND(addu, v_uint32x4, uint64x2, uint, u32m1, 4, u64, 2, vuint64m2, vuint32m1, 32) +OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int8x16, int16x8, schar, i8m1, 16, i16, 8, vint16m2, vint8m1, 8) +OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int16x8, int32x4, short, i16m1, 8, i32, 4, vint32m2, vint16m1, 16) +OPENCV_HAL_IMPL_RISCVV_EXPAND(add, v_int32x4, int64x2, int, i32m1, 4, i64, 2, vint64m2, vint32m1, 32) + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + vuint16m2_t b = vundefined_u16m2(); + vuint32m2_t c = vundefined_u32m2(); + vuint8m1_t val = vle8_v_u8m1(ptr, 4); \ + b = vwaddu_vv_u16m2(val, vmv_v_x_u8m1(0, 4), 4); \ + c = vwaddu_vv_u32m2(vget_v_u16m2_u16m1(b, 0), vmv_v_x_u16m1(0, 4), 4); \ + return v_uint32x4(vget_v_u32m2_u32m1(c, 0)); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + vint16m2_t b = vundefined_i16m2(); + vint32m2_t c = vundefined_i32m2(); + vint8m1_t val = vle8_v_i8m1(ptr, 4); \ + b = vwadd_vv_i16m2(val, vmv_v_x_i8m1(0, 4), 4); \ + c = vwadd_vv_i32m2(vget_v_i16m2_i16m1(b, 0), vmv_v_x_i16m1(0, 4), 4); \ + return v_int32x4(vget_v_i32m2_i32m1(c, 0)); +} +#define VITL_16 {0x11011000, 0x13031202, 0x15051404, 0x17071606, 0x19091808, 0x1B0B1A0A, 0x1D0D1C0C, 0x1F0F1E0E} +#define VITL_8 {0x00080000, 0x00090001, 0x000A0002, 0x000B0003, 0x000C0004, 0x000D0005, 0x000E0006, 0x000F0007} +#define VITL_4 {0x00000000, 0x00000004, 0x00000001, 0x00000005, 0x00000002, 0x00000006, 0x00000003, 0x00000007} +#define VITL_2 {0, 0, 2, 0, 1, 0, 3, 0} + +#define OPENCV_HAL_IMPL_RISCVV_UNPACKS(_Tpvec, _Tp, _T, _UTp, _UT, num, num2, len, numh, refunc) \ +inline void v_zip(const v_##_Tpvec& a0, const v_##_Tpvec& a1, v_##_Tpvec& b0, v_##_Tpvec& b1) \ +{ \ + v##_Tp##m2_t tmp = vundefined_##_T##m2();\ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 0, a0.val); \ + tmp = vset_v_##_T##m1_##_T##m2(tmp, 1, a1.val); \ + unsigned mdata[] = VITL_##num; \ + vuint32m2_t mask = vle32_v_u32m2(mdata, 8); \ + tmp = (v##_Tp##m2_t)vrgather_vv_##_T##m2((v##_Tp##m2_t)tmp, refunc(mask), num2); \ + b0.val = vget_v_##_T##m2_##_T##m1(tmp, 0); \ + b1.val = vget_v_##_T##m2_##_T##m1(tmp, 1); \ +} \ +inline v_##_Tpvec v_combine_low(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + v##_Tp##m1_t b0 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ + return v_##_Tpvec(b0);\ +} \ +inline v_##_Tpvec v_combine_high(const v_##_Tpvec& a, const v_##_Tpvec& b) \ +{ \ + v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ + v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ + v##_Tp##m1_t b1 = vundefined_##_T##m1(); \ + b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ + a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ + b1 = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ + return v_##_Tpvec(b1);\ +} \ +inline void v_recombine(const v_##_Tpvec& a, const v_##_Tpvec& b, v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + v##_Tp##m1_t b0 = vundefined_##_T##m1(); \ + v##_Tp##m1_t a0 = vundefined_##_T##m1(); \ + c.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a.val, b.val, numh, num); \ + b0 = vslidedown_vx_##_T##m1(b0, b.val, numh, num); \ + a0 = vslidedown_vx_##_T##m1(a0, a.val, numh, num); \ + d.val = vslideup_vx_##_T##m1_m(vmset_m_##len(num), a0, b0, numh, num); \ +} + +OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint8x16, uint8, u8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(int8x16, int8, i8, uint8, u8, 16, 32, b8, 8, vreinterpret_v_u32m2_u8m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint16x8, uint16, u16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(int16x8, int16, i16, uint16, u16, 8, 16, b16, 4, vreinterpret_v_u32m2_u16m2) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(uint32x4, uint32, u32, uint32, u32, 4, 8, b32, 2,) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(int32x4, int32, i32, uint32, u32, 4, 8, b32, 2,) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(float32x4, float32, f32, uint32, u32, 4, 8, b32, 2,) +OPENCV_HAL_IMPL_RISCVV_UNPACKS(float64x2, float64, f64, uint64, u64, 2, 4, b64, 1, vreinterpret_v_u32m2_u64m2) + +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + return v_uint8x16(vrgather_vv_u8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); +} +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ + return v_int8x16(vrgather_vv_i8m1(a.val, vrsub_vx_u8m1(vid_v_u8m1(16), 15, 16), 16)); +} + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + return v_uint16x8(vrgather_vv_u16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ + return v_int16x8(vrgather_vv_i16m1(a.val, vrsub_vx_u16m1(vid_v_u16m1(8), 7, 8), 8)); +} +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + return v_uint32x4(vrgather_vv_u32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ + return v_int32x4(vrgather_vv_i32m1(a.val, vrsub_vx_u32m1(vid_v_u32m1(4), 3, 4), 4)); +} + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + return v_uint64x2(vrgather_vv_u64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ + return v_int64x2(vrgather_vv_i64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); +} + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ + return v_float64x2(vrgather_vv_f64m1(a.val, vrsub_vx_u64m1(vid_v_u64m1(2), 1, 2), 2)); +} + +#define OPENCV_HAL_IMPL_RISCVV_EXTRACT(_Tpvec, suffix, size) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) \ +{ return v_rotate_right(a, b);} +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint8x16, u8, 0) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int8x16, s8, 0) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint16x8, u16, 1) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int16x8, s16, 1) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint32x4, u32, 2) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int32x4, s32, 2) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_uint64x2, u64, 3) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_int64x2, s64, 3) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float32x4, f32, 2) +OPENCV_HAL_IMPL_RISCVV_EXTRACT(v_float64x2, f64, 3) + + +#define OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(_Tpvec, _Tp, suffix, vtype, _vtype, num, mvfunc) \ +template inline _Tp v_extract_n(_Tpvec v) { vtype tmp = vundefined_##_vtype(); return mvfunc(vslidedown_vx_##_vtype(tmp, v.val, i, num)); } + +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint8x16, uchar, u8, vuint8m1_t, u8m1, 16, vmv_x_s_u8m1_u8) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int8x16, schar, s8, vint8m1_t, i8m1, 16, vmv_x_s_i8m1_i8) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint16x8, ushort, u16, vuint16m1_t, u16m1, 8, vmv_x_s_u16m1_u16) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int16x8, short, s16, vint16m1_t, i16m1, 8, vmv_x_s_i16m1_i16) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint32x4, uint, u32, vuint32m1_t, u32m1, 4, vmv_x_s_u32m1_u32) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int32x4, int, s32, vint32m1_t, i32m1, 4, vmv_x_s_i32m1_i32) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_uint64x2, uint64, u64, vuint64m1_t, u64m1, 2, vmv_x_s_u64m1_u64) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_int64x2, int64, s64, vint64m1_t, i64m1, 2, vmv_x_s_i64m1_i64) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float32x4, float, f32, vfloat32m1_t, f32m1, 4, vfmv_f_s_f32m1_f32) +OPENCV_HAL_IMPL_RISCVV_EXTRACT_N(v_float64x2, double, f64, vfloat64m1_t, f64m1, 2, vfmv_f_s_f64m1_f64) + +#define OPENCV_HAL_IMPL_RISCVV_BROADCAST(_Tpvec, _Tp, num) \ +template inline _Tpvec v_broadcast_element(_Tpvec v) { return _Tpvec(vrgather_vx_##_Tp##m1(v.val, i, num)); } + +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint8x16, u8, 16) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int8x16, i8, 16) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint16x8, u16, 8) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int16x8, i16, 8) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint32x4, u32, 4) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int32x4, i32, 4) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_uint64x2, u64, 2) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_int64x2, i64, 2) +OPENCV_HAL_IMPL_RISCVV_BROADCAST(v_float32x4, f32, 4) + +inline void __builtin_riscv_fsrm(int val) +{ + asm("csrw frm, %0\n\t" + : + :"r"(val)); + return; +} + +inline void barrier1(void *arg) { + __asm__ __volatile__("" : : "r" (arg) : "memory"); +} + +inline v_int32x4 v_round(const v_float32x4& a) +{ + __builtin_riscv_fsrm(0); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} +inline v_int32x4 v_floor(const v_float32x4& a) +{ + __builtin_riscv_fsrm(2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + __builtin_riscv_fsrm(3); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ + __builtin_riscv_fsrm(1); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(a.val), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), a.val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_round(const v_float64x2& a) +{ + __builtin_riscv_fsrm(0); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + //_val = vset_f64m2(_val, 1, a.val); + _val = vset_v_f64m1_f64m2(_val, 1, vfmv_v_f_f64m1(0, 2)); + barrier1(&_val); + vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + __builtin_riscv_fsrm(0); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + _val = vset_v_f64m1_f64m2(_val, 1, b.val); + barrier1(&_val); + vint32m1_t val = vfncvt_x_f_w_i32m1(_val, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} +inline v_int32x4 v_floor(const v_float64x2& a) +{ + __builtin_riscv_fsrm(2); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + __builtin_riscv_fsrm(3); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ + __builtin_riscv_fsrm(1); + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + vint32m1_t nan = vand_vx_i32m1(vreinterpret_v_f32m1_i32m1(aval), 0x7f800000, 4); + barrier1(&nan); + vbool32_t mask = vmsne_vx_i32m1_b32(nan, 0x7f800000, 4); + vint32m1_t val = vfcvt_x_f_v_i32m1_m(mask, vmv_v_x_i32m1(0, 4), aval, 4); + __builtin_riscv_fsrm(0); + return v_int32x4(val); +} + +#define OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ +{ \ + intrin##2e##elemsize##_v_##_T##m1(&a.val, &b.val, ptr, num); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ +{ \ + intrin##3e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num); \ +}\ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ + v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ +{ \ + intrin##4e##elemsize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num); \ +} \ + +#define OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(intrin, _Tpvec, num, _Tp, _T, elemsize) \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + intrin##2e##elemsize##_v_##_T##m1(ptr, a.val, b.val, num); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + intrin##3e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, num); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + intrin##4e##elemsize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num); \ +} + +#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(_Tpvec, _Tp, num, ld, st, _T, elemsize) \ +OPENCV_HAL_IMPL_RISCVV_LOAD_DEINTERLEAVED(ld, _Tpvec, num, _Tp, _T, elemsize) \ +OPENCV_HAL_IMPL_RISCVV_STORE_INTERLEAVED(st, _Tpvec, num, _Tp, _T, elemsize) + +//OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, uchar, ) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int8, schar, 16, vlseg, vsseg, i8, 8) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int16, short, 8, vlseg, vsseg, i16, 16) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(int32, int, 4, vlseg, vsseg, i32, 32) + +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint8, unsigned char, 16, vlseg, vsseg, u8, 8) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint16, unsigned short, 8, vlseg, vsseg, u16, 16) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED(uint32, unsigned int, 4, vlseg, vsseg, u32, 32) + +#define OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(_Tpvec, _Tp, num, _T, _esize) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b) \ +{ vlseg2e##_esize##_v_##_T##m1(&a.val, &b.val, ptr, num);} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, v_##_Tpvec##x##num& c) \ +{ vlseg3e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, ptr, num);}\ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec##x##num& a, v_##_Tpvec##x##num& b, \ + v_##_Tpvec##x##num& c, v_##_Tpvec##x##num& d) \ +{ vlseg4e##_esize##_v_##_T##m1(&a.val, &b.val, &c.val, &d.val, ptr, num);} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vsseg2e##_esize##_v_##_T##m1(ptr, a.val, b.val, num);} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vsseg3e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, num);} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec##x##num& a, const v_##_Tpvec##x##num& b, \ + const v_##_Tpvec##x##num& c, const v_##_Tpvec##x##num& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ vsseg4e##_esize##_v_##_T##m1(ptr, a.val, b.val, c.val, d.val, num);} + +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float32, float, 4, f32, 32) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(float64, double, 2, f64, 64) + +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(uint64, unsigned long, 2, u64, 64) +OPENCV_HAL_IMPL_RISCVV_INTERLEAVED_(int64, long, 2, i64, 64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(vfcvt_f_x_v_f32m1(a.val, 4)); +} + +#if CV_SIMD128_64F +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 2); + return v_float32x4(aval); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + vfloat64m2_t _val = vundefined_f64m2(); + _val = vset_v_f64m1_f64m2(_val, 0, a.val); + _val = vset_v_f64m1_f64m2(_val, 1, b.val); + vfloat32m1_t aval = vfncvt_f_f_w_f32m1(_val, 4); + return v_float32x4(aval); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + vfloat32m1_t val = vfcvt_f_x_v_f32m1(a.val, 4); + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 0)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + vfloat64m2_t _val = vfwcvt_f_f_v_f64m2(a.val, 4); + return v_float64x2(vget_v_f64m2_f64m1(_val, 1)); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ + return v_float64x2(vfcvt_f_x_v_f64m1(a.val, 2)); +} + +#endif +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + uint64 mdata[2] = {0x0705060403010200, 0x0F0D0E0C0B090A08}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ + return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); +} + +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + uint64 mdata[2] = {0x0703060205010400, 0x0F0B0E0A0D090C08}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int8x16(vrgather_vv_i8m1(vec.val, vreinterpret_v_u64m1_u8m1(m0), 16)); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) +{ + return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); +} + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + uint64 mdata[2] = {0x0706030205040100, 0x0F0E0B0A0D0C0908}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + uint64 mdata[2] = {0x0B0A030209080100, 0x0F0E07060D0C0504}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + uint64 mdata[2] = {0x0B0A090803020100, 0x0F0E0D0C07060504}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int32x4(vreinterpret_v_i8m1_i32m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i32m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + uint64 mdata[2] = {0x0908060504020100, 0xFFFFFFFF0E0D0C0A}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int8x16(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vec.val), vreinterpret_v_u64m1_u8m1(m0), 16))); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + uint64 mdata[2] = {0x0908050403020100, 0xFFFFFFFF0D0C0B0A}; + vuint64m1_t m0 = vle64_v_u64m1(mdata, 2); + return v_int16x8(vreinterpret_v_i8m1_i16m1(vreinterpret_v_u8m1_i8m1(vrgather_vv_u8m1(vreinterpret_v_i8m1_u8m1(vreinterpret_v_i16m1_i8m1(vec.val)), vreinterpret_v_u64m1_u8m1(m0), 16)))); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +#if CV_SIMD128_64F +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, + const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ + vint64m2_t v1 = vwmul_vv_i64m2(a.val, b.val, 4); + vfloat64m1_t res = vfcvt_f_x_v_f64m1(vadd_vv_i64m1(vget_v_i64m2_i64m1(v1, 0), vget_v_i64m2_i64m1(v1, 1), 2), 2); + return v_float64x2(res); +} +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ v_float64x2 res = v_dotprod_expand_fast(a, b); + return v_add(res, c); } +#endif +////// FP16 support /////// +#if __riscv_v == 7000 +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + vfloat16m1_t v = vle16_v_f16m1((__fp16*)ptr, 4); + vfloat32m2_t v32 = vfwcvt_f_f_v_f32m2(v, 4); + return v_float32x4(vget_v_f32m2_f32m1(v32, 0)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + vfloat32m2_t v32 = vundefined_f32m2(); + v32 = vset_v_f32m1_f32m2(v32, 0, v.val); + vfloat16m1_t hv = vfncvt_f_f_w_f16m1(v32, 4); + vse16_v_f16m1((__fp16*)ptr, hv, 4); +} +#else +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + vfloat16mf2_t v = vle16_v_f16mf2((__fp16*)ptr, 4); + vfloat32m1_t v32 = vfwcvt_f_f_v_f32m1(v, 4); + return v_float32x4(v32); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + //vfloat32m2_t v32 = vundefined_f32m2(); + //v32 = vset_f32m2(v32, 0, v.val); + vfloat16mf2_t hv = vfncvt_f_f_w_f16mf2(v.val, 4); + vse16_v_f16mf2((__fp16*)ptr, hv, 4); +} +#endif + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp index b97b041d44..b6ce2d7f47 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_rvv_scalable.hpp @@ -1,2153 +1,2153 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// The original implementation is contributed by HAN Liutong. -// Copyright (C) 2022, Institute of Software, Chinese Academy of Sciences. - -#ifndef OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP -#define OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP - -#include - -#if defined(__GNUC__) && !defined(__clang__) -// FIXIT: eliminate massive warnigs from templates -// GCC from 'rvv-next': riscv64-unknown-linux-gnu-g++ (g42df3464463) 12.0.1 20220505 (prerelease) -// doesn't work: #pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wignored-attributes" -#endif - -#ifndef CV_RVV_MAX_VLEN -#define CV_RVV_MAX_VLEN 1024 -#endif - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define CV_SIMD_SCALABLE 1 -#define CV_SIMD_SCALABLE_64F 1 - -using v_uint8 = vuint8m2_t; -using v_int8 = vint8m2_t; -using v_uint16 = vuint16m2_t; -using v_int16 = vint16m2_t; -using v_uint32 = vuint32m2_t; -using v_int32 = vint32m2_t; -using v_uint64 = vuint64m2_t; -using v_int64 = vint64m2_t; - -using v_float32 = vfloat32m2_t; -#if CV_SIMD_SCALABLE_64F -using v_float64 = vfloat64m2_t; -#endif - -using uchar = unsigned char; -using schar = signed char; -using ushort = unsigned short; -using uint = unsigned int; -using uint64 = unsigned long int; -using int64 = long int; - - -template -struct VTraits; - -#define OPENCV_HAL_IMPL_RVV_TRAITS(REG, TYP, SUF, SZ) \ -template <> \ -struct VTraits \ -{ \ - static inline int vlanes() { return __riscv_vsetvlmax_##SUF(); } \ - using lane_type = TYP; \ - static const int max_nlanes = CV_RVV_MAX_VLEN/SZ; \ -}; - -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m1_t, int8_t, e8m1, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m2_t, int8_t, e8m2, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m4_t, int8_t, e8m4, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vint8m8_t, int8_t, e8m8, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m1_t, uint8_t, e8m1, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m2_t, uint8_t, e8m2, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m4_t, uint8_t, e8m4, 8) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m8_t, uint8_t, e8m8, 8) - -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m1_t, int16_t, e16m1, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m2_t, int16_t, e16m2, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m4_t, int16_t, e16m4, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vint16m8_t, int16_t, e16m8, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m1_t, uint16_t, e16m1, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m2_t, uint16_t, e16m2, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m4_t, uint16_t, e16m4, 16) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m8_t, uint16_t, e16m8, 16) - -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m1_t, int32_t, e32m1, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m2_t, int32_t, e32m2, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m4_t, int32_t, e32m4, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vint32m8_t, int32_t, e32m8, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m1_t, uint32_t, e32m1, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m2_t, uint32_t, e32m2, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m4_t, uint32_t, e32m4, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m8_t, uint32_t, e32m8, 32) - -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m1_t, int64_t, e64m1, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m2_t, int64_t, e64m2, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m4_t, int64_t, e64m4, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vint64m8_t, int64_t, e64m8, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m1_t, uint64_t, e64m1, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m2_t, uint64_t, e64m2, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m4_t, uint64_t, e64m4, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m8_t, uint64_t, e64m8, 64) - -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m1_t, float, e32m1, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m2_t, float, e32m2, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m4_t, float, e32m4, 32) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m8_t, float, e32m8, 32) - -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m1_t, double, e64m1, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m2_t, double, e64m2, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m4_t, double, e64m4, 64) -OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m8_t, double, e64m8, 64) -#endif - - -// LLVM/Clang defines "overloaded intrinsics" e.g. 'vand(op1, op2)' -// GCC does not have these functions, so we need to implement them manually -// We implement only selected subset required to build current state of the code -// Included inside namespace cv:: -// #ifndef __riscv_v_intrinsic_overloading -// #include "intrin_rvv_compat_overloaded.hpp" -// #endif // __riscv_v_intrinsic_overloading - - -//////////// get0 //////////// -#define OPENCV_HAL_IMPL_RVV_GRT0_INT(_Tpvec, _Tp) \ -inline _Tp v_get0(const v_##_Tpvec& v) \ -{ \ - return __riscv_vmv_x(v); \ -} - -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint8, uchar) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int8, schar) -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint16, ushort) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int16, short) -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint32, unsigned) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int32, int) -OPENCV_HAL_IMPL_RVV_GRT0_INT(uint64, uint64) -OPENCV_HAL_IMPL_RVV_GRT0_INT(int64, int64) - -inline float v_get0(const v_float32& v) \ -{ \ - return __riscv_vfmv_f(v); \ -} -#if CV_SIMD_SCALABLE_64F -inline double v_get0(const v_float64& v) \ -{ \ - return __riscv_vfmv_f(v); \ -} -#endif - -//////////// Initial //////////// - -#define OPENCV_HAL_IMPL_RVV_INIT_INTEGER(_Tpvec, _Tp, suffix1, suffix2, vl) \ -inline v_##_Tpvec v_setzero_##suffix1() \ -{ \ - return __riscv_vmv_v_x_##suffix2##m2(0, vl); \ -} \ -inline v_##_Tpvec v_setall_##suffix1(_Tp v) \ -{ \ - return __riscv_vmv_v_x_##suffix2##m2(v, vl); \ -} \ -template <> inline v_##_Tpvec v_setzero_() \ -{ \ - return v_setzero_##suffix1(); \ -} \ -template <> inline v_##_Tpvec v_setall_(_Tp v) \ -{ \ - return v_setall_##suffix1(v); \ -} - -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint8, uchar, u8, u8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int8, schar, s8, i8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint16, ushort, u16, u16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int16, short, s16, i16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint32, uint, u32, u32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int32, int, s32, i32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint64, uint64, u64, u64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int64, int64, s64, i64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_INIT_FP(_Tpv, _Tp, suffix, vl) \ -inline v_##_Tpv v_setzero_##suffix() \ -{ \ - return __riscv_vfmv_v_f_##suffix##m2(0, vl); \ -} \ -inline v_##_Tpv v_setall_##suffix(_Tp v) \ -{ \ - return __riscv_vfmv_v_f_##suffix##m2(v, vl); \ -} \ -template <> inline v_##_Tpv v_setzero_() \ -{ \ - return v_setzero_##suffix(); \ -} \ -template <> inline v_##_Tpv v_setall_(_Tp v) \ -{ \ - return v_setall_##suffix(v); \ -} - -OPENCV_HAL_IMPL_RVV_INIT_FP(float32, float, f32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_INIT_FP(float64, double, f64, VTraits::vlanes()) -#endif - -//////////// Reinterpret //////////// -#define OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(_Tpvec1, suffix1) \ -inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec1& v) \ -{ \ - return v;\ -} -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint8, u8) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint16, u16) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint32, u32) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint64, u64) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int8, s8) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int16, s16) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int32, s32) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int64, s64) -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float32, f32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float64, f64) -#endif -// TODO: can be simplified by using overloaded RV intrinsic -#define OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2) \ -inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ -{ \ - return v_##_Tpvec1(__riscv_vreinterpret_v_##nsuffix2##m2_##nsuffix1##m2(v));\ -} \ -inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ -{ \ - return v_##_Tpvec2(__riscv_vreinterpret_v_##nsuffix1##m2_##nsuffix2##m2(v));\ -} - -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, int8, u8, s8, u8, i8) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, int16, u16, s16, u16, i16) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, int32, u32, s32, u32, i32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, float32, u32, f32, u32, f32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, float32, s32, f32, i32, f32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, int64, u64, s64, u64, i64) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, float64, u64, f64, u64, f64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int64, float64, s64, f64, i64, f64) -#endif -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint16, u8, u16, u8, u16) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint32, u8, u32, u8, u32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint64, u8, u64, u8, u64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint32, u16, u32, u16, u32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint64, u16, u64, u16, u64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, uint64, u32, u64, u32, u64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int16, s8, s16, i8, i16) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int32, s8, s32, i8, i32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int64, s8, s64, i8, i64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int32, s16, s32, i16, i32) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int64, s16, s64, i16, i64) -OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, int64, s32, s64, i32, i64) - - -#define OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2, width1, width2) \ -inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ -{ \ - return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix1##width1##m2(__riscv_vreinterpret_v_##nsuffix2##width2##m2_##nsuffix1##width2##m2(v));\ -} \ -inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ -{ \ - return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix2##width2##m2(__riscv_vreinterpret_v_##nsuffix1##width1##m2_##nsuffix1##width2##m2(v));\ -} - -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int16, u8, s16, u, i, 8, 16) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int32, u8, s32, u, i, 8, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int64, u8, s64, u, i, 8, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int8, u16, s8, u, i, 16, 8) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int32, u16, s32, u, i, 16, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int64, u16, s64, u, i, 16, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int8, u32, s8, u, i, 32, 8) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int16, u32, s16, u, i, 32, 16) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int64, u32, s64, u, i, 32, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int8, u64, s8, u, i, 64, 8) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int16, u64, s16, u, i, 64, 16) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int32, u64, s32, u, i, 64, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float32, u8, f32, u, f, 8, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float32, u16, f32, u, f, 16, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, float32, u64, f32, u, f, 64, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float32, s8, f32, i, f, 8, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float32, s16, f32, i, f, 16, 32) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int64, float32, s64, f32, i, f, 64, 32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float64, u8, f64, u, f, 8, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float64, u16, f64, u, f, 16, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, float64, u32, f64, u, f, 32, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float64, s8, f64, i, f, 8, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float64, s16, f64, i, f, 16, 64) -OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int32, float64, s32, f64, i, f, 32, 64) -// Three times reinterpret -inline v_float32 v_reinterpret_as_f32(const v_float64& v) \ -{ \ - return __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vreinterpret_v_u64m2_u32m2(__riscv_vreinterpret_v_f64m2_u64m2(v)));\ -} - -inline v_float64 v_reinterpret_as_f64(const v_float32& v) \ -{ \ - return __riscv_vreinterpret_v_u64m2_f64m2(__riscv_vreinterpret_v_u32m2_u64m2(__riscv_vreinterpret_v_f32m2_u32m2(v)));\ -} -#endif - -//////////// Extract ////////////// - -#define OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(_Tpvec, _Tp, vl) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ -} \ -template inline _Tp v_extract_n(_Tpvec v, int i = s) \ -{ \ - return __riscv_vmv_x(__riscv_vslidedown(v, i, vl)); \ -} - -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint8, uchar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int8, schar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint16, ushort, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int16, short, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint32, unsigned int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int32, int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint64, uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int64, int64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_EXTRACT_FP(_Tpvec, _Tp, vl) \ -template \ -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ -} \ -template inline _Tp v_extract_n(_Tpvec v, int i = s) \ -{ \ - return __riscv_vfmv_f(__riscv_vslidedown(v, i, vl)); \ -} - -OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float32, float, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float64, double, VTraits::vlanes()) -#endif - -#define OPENCV_HAL_IMPL_RVV_EXTRACT(_Tpvec, _Tp, vl) \ -inline _Tp v_extract_highest(_Tpvec v) \ -{ \ - return v_extract_n(v, vl-1); \ -} - -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint8, uchar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int8, schar, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint16, ushort, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int16, short, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint32, unsigned int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int32, int, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint64, uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_int64, int64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_EXTRACT(v_float32, float, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_EXTRACT(v_float64, double, VTraits::vlanes()) -#endif - - -////////////// Load/Store ////////////// -#define OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(_Tpvec, _nTpvec, _Tp, hvl, vl, width, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ \ - return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ -} \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ \ - return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ \ - __riscv_vse##width##_v_##suffix##m2(ptr, a, vl); \ -} \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ \ - return __riscv_vle##width##_v_##suffix##m2(ptr, hvl); \ -} \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - return __riscv_vslideup(__riscv_vle##width##_v_##suffix##m2(ptr0, hvl), __riscv_vle##width##_v_##suffix##m2(ptr1, hvl), hvl, vl); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, vl); \ -} \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, vl); \ -} \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, vl); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, a, hvl); \ -} \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - __riscv_vse##width(ptr, __riscv_vslidedown_vx_##suffix##m2(a, hvl, vl), hvl); \ -} \ -template \ -_Tpvec v_load_##suffix(Targs... nScalars) \ -{ \ - return v_load({nScalars...}); \ -} - - -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint8, vuint8m2_t, uchar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, u8) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int8, vint8m2_t, schar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, i8) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint16, vuint16m2_t, ushort, VTraits::vlanes() / 2, VTraits::vlanes(), 16, u16) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int16, vint16m2_t, short, VTraits::vlanes() / 2, VTraits::vlanes(), 16, i16) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint32, vuint32m2_t, unsigned int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, u32) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int32, vint32m2_t, int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, i32) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint64, vuint64m2_t, uint64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, u64) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int64, vint64m2_t, int64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, i64) -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float32, vfloat32m2_t, float, VTraits::vlanes() /2 , VTraits::vlanes(), 32, f32) - -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float64, vfloat64m2_t, double, VTraits::vlanes() / 2, VTraits::vlanes(), 64, f64) -#endif - -////////////// Lookup table access //////////////////// -#define OPENCV_HAL_IMPL_RVV_LUT(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_lut(const _Tp* tab, const int* idx) \ -{ \ - auto vidx = __riscv_vmul(__riscv_vreinterpret_u32##suffix(__riscv_vle32_v_i32##suffix(idx, VTraits<_Tpvec>::vlanes())), sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ - return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT(v_int8, schar, m8) -OPENCV_HAL_IMPL_RVV_LUT(v_int16, short, m4) -OPENCV_HAL_IMPL_RVV_LUT(v_int32, int, m2) -OPENCV_HAL_IMPL_RVV_LUT(v_int64, int64_t, m1) -OPENCV_HAL_IMPL_RVV_LUT(v_float32, float, m2) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_LUT(v_float64, double, m1) -#endif - -#define OPENCV_HAL_IMPL_RVV_LUT_PAIRS(_Tpvec, _Tp, suffix1, suffix2, v_trunc) \ -inline _Tpvec v_lut_pairs(const _Tp* tab, const int* idx) \ -{ \ - auto v0 = __riscv_vle32_v_u32##suffix1((unsigned*)idx, VTraits<_Tpvec>::vlanes()/2); \ - auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/2); \ - auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/2); \ - auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/2); \ - auto sh1 = __riscv_vslide1up(v_trunc(__riscv_vreinterpret_u32##suffix2(w1)),0, VTraits<_Tpvec>::vlanes()); \ - auto vid = __riscv_vor(sh1, v_trunc(__riscv_vreinterpret_u32##suffix2(w0)), VTraits<_Tpvec>::vlanes()); \ - auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ - return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int8, schar, m4, m8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int16, short, m2, m4, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int32, int, m1, m2, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float32, float, m1, m2, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int64, int64_t, m1, m2, __riscv_vlmul_trunc_u32m1) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float64, double, m1, m2, __riscv_vlmul_trunc_u32m1) -#endif - - -#define OPENCV_HAL_IMPL_RVV_LUT_QUADS(_Tpvec, _Tp, suffix0, suffix1, suffix2, v_trunc) \ -inline _Tpvec v_lut_quads(const _Tp* tab, const int* idx) \ -{ \ - auto v0 = __riscv_vle32_v_u32##suffix0((unsigned*)idx, VTraits<_Tpvec>::vlanes()/4); \ - auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/4); \ - auto v2 = __riscv_vadd(v0, 2, VTraits<_Tpvec>::vlanes()/4); \ - auto v3 = __riscv_vadd(v0, 3, VTraits<_Tpvec>::vlanes()/4); \ - auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/4); \ - auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/4); \ - auto w2 = __riscv_vwcvtu_x(v2, VTraits<_Tpvec>::vlanes()/4); \ - auto w3 = __riscv_vwcvtu_x(v3, VTraits<_Tpvec>::vlanes()/4); \ - auto sh2 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w2),0, VTraits<_Tpvec>::vlanes()/2); \ - auto sh3 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w3),0, VTraits<_Tpvec>::vlanes()/2); \ - auto vid0 = __riscv_vor(sh2, __riscv_vreinterpret_u32##suffix1(w0), VTraits<_Tpvec>::vlanes()/2); \ - auto vid1 = __riscv_vor(sh3, __riscv_vreinterpret_u32##suffix1(w1), VTraits<_Tpvec>::vlanes()/2); \ - auto wid0 = __riscv_vwcvtu_x(v_trunc(vid0), VTraits<_Tpvec>::vlanes()/2); \ - auto wid1 = __riscv_vwcvtu_x(v_trunc(vid1), VTraits<_Tpvec>::vlanes()/2); \ - auto shwid1 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix2(wid1),0, VTraits<_Tpvec>::vlanes()); \ - auto vid = __riscv_vor(shwid1, __riscv_vreinterpret_u32##suffix2(wid0), VTraits<_Tpvec>::vlanes()); \ - auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ - return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int8, schar, m2, m4, m8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int16, short, m1 , m2, m4, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int32, int, m1, m2, m2, __riscv_vlmul_trunc_u32m1) -OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_float32, float, m1, m2, m2, __riscv_vlmul_trunc_u32m1) - -#define OPENCV_HAL_IMPL_RVV_LUT_VEC(_Tpvec, _Tp) \ -inline _Tpvec v_lut(const _Tp* tab, const v_int32& vidx) \ -{ \ - v_uint32 vidx_ = __riscv_vmul(__riscv_vreinterpret_u32m2(vidx), sizeof(_Tp), VTraits::vlanes()); \ - return __riscv_vloxei32(tab, vidx_, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_LUT_VEC(v_float32, float) -OPENCV_HAL_IMPL_RVV_LUT_VEC(v_int32, int) -OPENCV_HAL_IMPL_RVV_LUT_VEC(v_uint32, unsigned) - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_lut(const double* tab, const v_int32& vidx) \ -{ \ - vuint32m1_t vidx_ = __riscv_vmul(__riscv_vlmul_trunc_u32m1(__riscv_vreinterpret_u32m2(vidx)), sizeof(double), VTraits::vlanes()); \ - return __riscv_vloxei32(tab, vidx_, VTraits::vlanes()); \ -} -#endif - - -inline v_uint8 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } -inline v_uint8 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } -inline v_uint8 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } -inline v_uint16 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } -inline v_uint16 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } -inline v_uint16 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } -inline v_uint32 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } -inline v_uint32 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } -inline v_uint32 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } -inline v_uint64 v_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64 v_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -////////////// Pack boolean //////////////////// -inline v_uint8 v_pack_b(const v_uint16& a, const v_uint16& b) -{ - return __riscv_vnsrl(__riscv_vset(__riscv_vlmul_ext_v_u16m2_u16m4(a),1,b), 0, VTraits::vlanes()); -} - -inline v_uint8 v_pack_b(const v_uint32& a, const v_uint32& b, - const v_uint32& c, const v_uint32& d) -{ - - return __riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u32m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()); -} - -inline v_uint8 v_pack_b(const v_uint64& a, const v_uint64& b, const v_uint64& c, - const v_uint64& d, const v_uint64& e, const v_uint64& f, - const v_uint64& g, const v_uint64& h) -{ - vuint8m1_t t0 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); - vuint8m1_t t1 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(e),1,f),2,g),3,h), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); - - return __riscv_vset(__riscv_vlmul_ext_u8m2(t0), 1, t1); -} - -////////////// Arithmetics ////////////// -#define OPENCV_HAL_IMPL_RVV_BIN_OP(_Tpvec, ocv_intrin, rvv_intrin) \ -inline _Tpvec v_##ocv_intrin(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return rvv_intrin(a, b, VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub, __riscv_vssubu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub, __riscv_vssub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub, __riscv_vssubu) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub, __riscv_vssub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, sub, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, mul, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, sub, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, mul, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, add, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, sub, __riscv_vfsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, mul, __riscv_vfmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, div, __riscv_vfdiv) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, sub, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, add, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, sub, __riscv_vsub) - -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, add, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, sub, __riscv_vfsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, mul, __riscv_vfmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, div, __riscv_vfdiv) -#endif - -#define OPENCV_HAL_IMPL_RVV_BIN_MADD(_Tpvec, rvv_add) \ -template \ -inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ - return v_add(rvv_add(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ -} -#define OPENCV_HAL_IMPL_RVV_BIN_MMUL(_Tpvec, rvv_mul) \ -template \ -inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ - return v_mul(rvv_mul(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ -} -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint8, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int8, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint16, __riscv_vsaddu) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int16, __riscv_vsadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint32, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int32, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float32, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint64, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int64, __riscv_vadd) - -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_uint32, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_int32, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float32, __riscv_vfmul) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float64, __riscv_vfadd) -OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float64, __riscv_vfmul) -#endif - -#define OPENCV_HAL_IMPL_RVV_MUL_EXPAND(_Tpvec, _Tpwvec, _TpwvecM2, suffix, wmul) \ -inline void v_mul_expand(const _Tpvec& a, const _Tpvec& b, _Tpwvec& c, _Tpwvec& d) \ -{ \ - _TpwvecM2 temp = wmul(a, b, VTraits<_Tpvec>::vlanes()); \ - c = __riscv_vget_##suffix##m2(temp, 0); \ - d = __riscv_vget_##suffix##m2(temp, 1); \ -} - -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint8, v_uint16, vuint16m4_t, u16, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int8, v_int16, vint16m4_t, i16, __riscv_vwmul) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint16, v_uint32, vuint32m4_t, u32, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int16, v_int32, vint32m4_t, i32, __riscv_vwmul) -OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint32, v_uint64, vuint64m4_t, u64, __riscv_vwmulu) - -inline v_int16 v_mul_hi(const v_int16& a, const v_int16& b) -{ - return __riscv_vmulh(a, b, VTraits::vlanes()); -} -inline v_uint16 v_mul_hi(const v_uint16& a, const v_uint16& b) -{ - return __riscv_vmulhu(a, b, VTraits::vlanes()); -} - -////////////// Arithmetics (wrap)////////////// -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add_wrap, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub_wrap, __riscv_vsub) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, mul_wrap, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, mul_wrap, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, mul_wrap, __riscv_vmul) -OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, mul_wrap, __riscv_vmul) - -//////// Saturating Multiply //////// -#define OPENCV_HAL_IMPL_RVV_MUL_SAT(_Tpvec, _clip, _wmul) \ -inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _clip(_wmul(a, b, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -template \ -inline _Tpvec v_mul(const _Tpvec& a1, const _Tpvec& a2, const Args&... va) { \ - return v_mul(_clip(_wmul(a1, a2, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()), va...); \ -} - -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint8, __riscv_vnclipu, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int8, __riscv_vnclip, __riscv_vwmul) -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint16, __riscv_vnclipu, __riscv_vwmulu) -OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int16, __riscv_vnclip, __riscv_vwmul) - -////////////// Bitwise logic ////////////// - -#define OPENCV_HAL_IMPL_RVV_LOGIC_OP(_Tpvec, vl) \ -inline _Tpvec v_and(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vand(a, b, vl); \ -} \ -inline _Tpvec v_or(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vor(a, b, vl); \ -} \ -inline _Tpvec v_xor(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vxor(a, b, vl); \ -} \ -inline _Tpvec v_not (const _Tpvec& a) \ -{ \ - return __riscv_vnot(a, vl); \ -} - -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(intrin) \ -inline v_float32 intrin (const v_float32& a, const v_float32& b) \ -{ \ - return __riscv_vreinterpret_f32m2(intrin(__riscv_vreinterpret_i32m2(a), __riscv_vreinterpret_i32m2(b))); \ -} -OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_and) -OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_or) -OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_xor) - -inline v_float32 v_not (const v_float32& a) \ -{ \ - return __riscv_vreinterpret_f32m2(v_not(__riscv_vreinterpret_i32m2(a))); \ -} - -#if CV_SIMD_SCALABLE_64F -#define OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(intrin) \ -inline v_float64 intrin (const v_float64& a, const v_float64& b) \ -{ \ - return __riscv_vreinterpret_f64m2(intrin(__riscv_vreinterpret_i64m2(a), __riscv_vreinterpret_i64m2(b))); \ -} -OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_and) -OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_or) -OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_xor) - -inline v_float64 v_not (const v_float64& a) \ -{ \ - return __riscv_vreinterpret_f64m2(v_not(__riscv_vreinterpret_i64m2(a))); \ -} -#endif - - -////////////// Bitwise shifts ////////////// -/* Usage -1. v_shl(vec); -2. v_shl(vec, N); // instead of vec << N, when N is non-constant. -*/ - -#define OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(_Tpvec, vl) \ -template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ -} \ -template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsrl(a, uint8_t(n), vl)); \ -} - -#define OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(_Tpvec, vl) \ -template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ -} \ -template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ -{ \ - return _Tpvec(__riscv_vsra(a, uint8_t(n), vl)); \ -} - -OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int64, VTraits::vlanes()) - -////////////// Comparison ////////////// -#define OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, op, intrin, suffix) \ -inline _Tpvec v_##op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - size_t VLEN = VTraits<_Tpvec>::vlanes(); \ - uint64_t ones = -1; \ - return __riscv_vmerge(__riscv_vmv_v_x_##suffix##m2(0, VLEN), ones, intrin(a, b, VLEN), VLEN); \ -} - -#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, op, intrin, suffix) \ -inline _Tpvec v_##op (const _Tpvec& a, const _Tpvec& b) \ -{ \ - size_t VLEN = VTraits<_Tpvec>::vlanes(); \ - union { uint64_t u; VTraits<_Tpvec>::lane_type d; } ones; \ - ones.u = -1; \ - auto diff = intrin(a, b, VLEN); \ - auto z = __riscv_vfmv_v_f_##suffix##m2(0, VLEN); \ - auto res = __riscv_vfmerge(z, ones.d, diff, VLEN); \ - return _Tpvec(res); \ -} //TODO - -#define OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(_Tpvec, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmsltu, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgtu, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsleu, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsgeu, suffix) - -#define OPENCV_HAL_IMPL_RVV_SIGNED_CMP(_Tpvec, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmslt, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgt, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsle, suffix) \ -OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsge, suffix) - -#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP(_Tpvec, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, eq, __riscv_vmfeq, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ne, __riscv_vmfne, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, lt, __riscv_vmflt, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, gt, __riscv_vmfgt, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, le, __riscv_vmfle, suffix) \ -OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ge, __riscv_vmfge, suffix) - - -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint8, u8) -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint16, u16) -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint32, u32) -OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint64, u64) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int8, i8) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int16, i16) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int32, i32) -OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int64, i64) -OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float32, f32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float64, f64) -#endif - -inline v_float32 v_not_nan(const v_float32& a) -{ return v_eq(a, a); } - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_not_nan(const v_float64& a) -{ return v_eq(a, a); } -#endif - -////////////// Min/Max ////////////// - -#define OPENCV_HAL_IMPL_RVV_BIN_FUNC(_Tpvec, func, intrin, vl) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return intrin(a, b, vl); \ -} - -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_min, __riscv_vminu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_max, __riscv_vmaxu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_min, __riscv_vmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_max, __riscv_vmax, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_min, __riscv_vminu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_max, __riscv_vmaxu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_min, __riscv_vmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_max, __riscv_vmax, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_min, __riscv_vminu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_max, __riscv_vmaxu, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_min, __riscv_vmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_max, __riscv_vmax, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_min, __riscv_vfmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_max, __riscv_vfmax, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_min, __riscv_vfmin, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_max, __riscv_vfmax, VTraits::vlanes()) -#endif - -////////////// Transpose4x4 ////////////// -#define OPENCV_HAL_IMPL_RVV_ZIP4(_Tpvec, _wTpvec, suffix, convert2u, convert) \ -inline void v_zip4(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ - int vl = 4; \ - _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2u( \ - __riscv_vor(__riscv_vzext_vf2(convert(a0), vl), \ - __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(convert(a1), vl)), 0, vl*2)), \ - vl))); \ - b0 = __riscv_vget_##suffix##m2(temp, 0); \ - b1 = __riscv_vget_##suffix##m2(__riscv_vrgather(temp, __riscv_vadd(__riscv_vid_v_u32m4(vl), 4, vl)/*{4,5,6,7} */, vl) ,0); \ -} - -OPENCV_HAL_IMPL_RVV_ZIP4(v_uint32, vuint32m4_t, u32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP4(v_int32, vint32m4_t, i32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) -OPENCV_HAL_IMPL_RVV_ZIP4(v_float32, vfloat32m4_t, f32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) - - -#define OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, const _Tpvec& a2, const _Tpvec& a3, _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) { \ - _Tpvec t0,t1,t2,t3; \ - v_zip4(a0, a2, t0, t2); \ - v_zip4(a1, a3, t1, t3); \ - v_zip4(t0, t1, b0, b1); \ - v_zip4(t2, t3, b2, b3); \ -} - -OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_uint32, u32) -OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_int32, i32) -OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_float32, f32) - -////////////// Reduce ////////////// - -#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl, red) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - _nwTpvec zero = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ - _nwTpvec res = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ - res = __riscv_v##red(a, zero, vl); \ - return (scalartype)__riscv_vmv_x(res); \ -} -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint8, v_uint16, vuint16m1_t, unsigned, u16, VTraits::vlanes(), wredsumu) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int8, v_int16, vint16m1_t, int, i16, VTraits::vlanes(), wredsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint16, v_uint32, vuint32m1_t, unsigned, u32, VTraits::vlanes(), wredsumu) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int16, v_int32, vint32m1_t, int, i32, VTraits::vlanes(), wredsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint32, v_uint64, vuint64m1_t, unsigned, u64, VTraits::vlanes(), wredsumu) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int32, v_int64, vint64m1_t, int, i64, VTraits::vlanes(), wredsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint64, v_uint64, vuint64m1_t, uint64, u64, VTraits::vlanes(), redsum) -OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int64, v_int64, vint64m1_t, int64, i64, VTraits::vlanes(), redsum) - - -#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - _nwTpvec zero = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ - _nwTpvec res = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ - res = __riscv_vfredusum(a, zero, vl); \ - return (scalartype)__riscv_vfmv_f(res); \ -} -OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float32, v_float32, vfloat32m1_t, float, f32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float64, v_float64, vfloat64m1_t, float, f64, VTraits::vlanes()) -#endif - -#define OPENCV_HAL_IMPL_RVV_REDUCE(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ - return (scalartype)__riscv_vmv_x(__riscv_v##red(a, narrowM1, vl)); \ -} - -#define OPENCV_HAL_IMPL_RVV_REDUCE_FP(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ - return (scalartype)__riscv_vfmv_f(__riscv_v##red(a, narrowM1, vl)); \ -} - -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, min, uchar, u8, VTraits::vlanes(), redminu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, min, schar, i8, VTraits::vlanes(), redmin) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, min, ushort, u16, VTraits::vlanes(), redminu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, min, short, i16, VTraits::vlanes(), redmin) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, min, unsigned, u32, VTraits::vlanes(), redminu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, min, int, i32, VTraits::vlanes(), redmin) -OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, min, float, f32, VTraits::vlanes(), fredmin) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, max, uchar, u8, VTraits::vlanes(), redmaxu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, max, schar, i8, VTraits::vlanes(), redmax) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, max, ushort, u16, VTraits::vlanes(), redmaxu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, max, short, i16, VTraits::vlanes(), redmax) -OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, max, unsigned, u32, VTraits::vlanes(), redmaxu) -OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, max, int, i32, VTraits::vlanes(), redmax) -OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, max, float, f32, VTraits::vlanes(), fredmax) - -inline v_float32 v_reduce_sum4(const v_float32& a, const v_float32& b, - const v_float32& c, const v_float32& d) -{ - // 0000 1111 2222 3333 .... - vuint64m4_t vid1 = __riscv_vid_v_u64m4(VTraits::vlanes()); - vuint16m4_t t1 = __riscv_vreinterpret_u16m4(vid1); - vuint16m4_t t2 = __riscv_vslide1up(t1, 0, VTraits::vlanes()); - vuint16m4_t t3 = __riscv_vslide1up(t2, 0, VTraits::vlanes()); - vuint16m4_t t4 = __riscv_vslide1up(t3, 0, VTraits::vlanes()); - t1 = __riscv_vor( - __riscv_vor(t1, t2, VTraits::vlanes()), - __riscv_vor(t3, t4, VTraits::vlanes()), - VTraits::vlanes() - ); - - // index for transpose4X4 - vuint16m4_t vidx0 = __riscv_vmul(t1, 12, VTraits::vlanes()); - vidx0 = __riscv_vadd(vidx0, __riscv_vid_v_u16m4(VTraits::vlanes()), VTraits::vlanes()); - vuint16m4_t vidx1 = __riscv_vadd(vidx0, 4, VTraits::vlanes()); - vuint16m4_t vidx2 = __riscv_vadd(vidx0, 8, VTraits::vlanes()); - vuint16m4_t vidx3 = __riscv_vadd(vidx0, 12, VTraits::vlanes()); - - // zip - vuint32m4_t tempA = __riscv_vreinterpret_u32m4( \ - __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(a), VTraits::vlanes()), \ - __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(c), VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes())); \ - vuint32m4_t tempB = __riscv_vreinterpret_u32m4( \ - __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(b), VTraits::vlanes()), \ - __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(d), VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes())); \ - vfloat32m8_t temp = __riscv_vreinterpret_f32m8(__riscv_vreinterpret_u32m8( \ - __riscv_vor(__riscv_vzext_vf2(tempA, VTraits::vlanes()), \ - __riscv_vreinterpret_u64m8(__riscv_vslide1up(__riscv_vreinterpret_u32m8(__riscv_vzext_vf2(tempB, VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes()))); - - // transpose - vfloat32m2_t b0 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx0, VTraits::vlanes())); - vfloat32m2_t b1 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx1, VTraits::vlanes())); - vfloat32m2_t b2 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx2, VTraits::vlanes())); - vfloat32m2_t b3 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx3, VTraits::vlanes())); - - // vector add - v_float32 res = __riscv_vfadd( - __riscv_vfadd(b0, b1, VTraits::vlanes()), - __riscv_vfadd(b2, b3, VTraits::vlanes()), - VTraits::vlanes() - ); - return res; -} - -////////////// Square-Root ////////////// - -inline v_float32 v_sqrt(const v_float32& x) -{ - return __riscv_vfsqrt(x, VTraits::vlanes()); -} - -inline v_float32 v_invsqrt(const v_float32& x) -{ - v_float32 one = v_setall_f32(1.0f); - return v_div(one, v_sqrt(x)); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_sqrt(const v_float64& x) -{ - return __riscv_vfsqrt(x, VTraits::vlanes()); -} - -inline v_float64 v_invsqrt(const v_float64& x) -{ - v_float64 one = v_setall_f64(1.0f); - return v_div(one, v_sqrt(x)); -} -#endif - -inline v_float32 v_magnitude(const v_float32& a, const v_float32& b) -{ - v_float32 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); - return v_sqrt(x); -} - -inline v_float32 v_sqr_magnitude(const v_float32& a, const v_float32& b) -{ - return v_float32(__riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes())); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_magnitude(const v_float64& a, const v_float64& b) -{ - v_float64 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); - return v_sqrt(x); -} - -inline v_float64 v_sqr_magnitude(const v_float64& a, const v_float64& b) -{ - return __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); -} -#endif - -////////////// Multiply-Add ////////////// - -inline v_float32 v_fma(const v_float32& a, const v_float32& b, const v_float32& c) -{ - return __riscv_vfmacc(c, a, b, VTraits::vlanes()); -} -inline v_int32 v_fma(const v_int32& a, const v_int32& b, const v_int32& c) -{ - return __riscv_vmacc(c, a, b, VTraits::vlanes()); -} - -inline v_float32 v_muladd(const v_float32& a, const v_float32& b, const v_float32& c) -{ - return v_fma(a, b, c); -} - -inline v_int32 v_muladd(const v_int32& a, const v_int32& b, const v_int32& c) -{ - return v_fma(a, b, c); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_fma(const v_float64& a, const v_float64& b, const v_float64& c) -{ - return __riscv_vfmacc_vv_f64m2(c, a, b, VTraits::vlanes()); -} - -inline v_float64 v_muladd(const v_float64& a, const v_float64& b, const v_float64& c) -{ - return v_fma(a, b, c); -} -#endif - -////////////// Check all/any ////////////// - -#define OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(_Tpvec, vl) \ -inline bool v_check_all(const _Tpvec& a) \ -{ \ - return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) == vl; \ -} \ -inline bool v_check_any(const _Tpvec& a) \ -{ \ - return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) != 0; \ -} - -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int64, VTraits::vlanes()) - - -inline bool v_check_all(const v_uint8& a) -{ return v_check_all(v_reinterpret_as_s8(a)); } -inline bool v_check_any(const v_uint8& a) -{ return v_check_any(v_reinterpret_as_s8(a)); } - -inline bool v_check_all(const v_uint16& a) -{ return v_check_all(v_reinterpret_as_s16(a)); } -inline bool v_check_any(const v_uint16& a) -{ return v_check_any(v_reinterpret_as_s16(a)); } - -inline bool v_check_all(const v_uint32& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_uint32& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } - -inline bool v_check_all(const v_float32& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_float32& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } - -inline bool v_check_all(const v_uint64& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_uint64& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } - -#if CV_SIMD_SCALABLE_64F -inline bool v_check_all(const v_float64& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_float64& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } -#endif - -////////////// abs ////////////// - -#define OPENCV_HAL_IMPL_RVV_ABSDIFF(_Tpvec, abs) \ -inline _Tpvec v_##abs(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return v_sub(v_max(a, b), v_min(a, b)); \ -} - -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint8, absdiff) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint16, absdiff) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint32, absdiff) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float32, absdiff) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float64, absdiff) -#endif -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int8, absdiffs) -OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int16, absdiffs) - -#define OPENCV_HAL_IMPL_RVV_ABSDIFF_S(_Tpvec, _rTpvec, width) \ -inline _rTpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vnclipu(__riscv_vreinterpret_u##width##m4(__riscv_vwsub_vv(v_max(a, b), v_min(a, b), VTraits<_Tpvec>::vlanes())), 0, 0, VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int8, v_uint8, 16) -OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int16, v_uint16, 32) -OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int32, v_uint32, 64) - -#define OPENCV_HAL_IMPL_RVV_ABS(_Tprvec, _Tpvec, suffix) \ -inline _Tprvec v_abs(const _Tpvec& a) \ -{ \ - return v_absdiff(a, v_setzero_##suffix()); \ -} - -OPENCV_HAL_IMPL_RVV_ABS(v_uint8, v_int8, s8) -OPENCV_HAL_IMPL_RVV_ABS(v_uint16, v_int16, s16) -OPENCV_HAL_IMPL_RVV_ABS(v_uint32, v_int32, s32) -OPENCV_HAL_IMPL_RVV_ABS(v_float32, v_float32, f32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_ABS(v_float64, v_float64, f64) -#endif - - -#define OPENCV_HAL_IMPL_RVV_REDUCE_SAD(_Tpvec, scalartype) \ -inline scalartype v_reduce_sad(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return v_reduce_sum(v_absdiff(a, b)); \ -} - -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint8, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int8, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint16, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int16, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint32, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int32, unsigned) -OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_float32, float) - -////////////// Select ////////////// - -#define OPENCV_HAL_IMPL_RVV_SELECT(_Tpvec, vl) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vmerge(b, a, __riscv_vmsne(mask, 0, vl), vl); \ -} - -OPENCV_HAL_IMPL_RVV_SELECT(v_uint8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_uint16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_uint32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_int8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_int16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_SELECT(v_int32, VTraits::vlanes()) - -inline v_float32 v_select(const v_float32& mask, const v_float32& a, const v_float32& b) \ -{ \ - return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ -} - -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_select(const v_float64& mask, const v_float64& a, const v_float64& b) \ -{ \ - return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ -} -#endif - -////////////// Rotate shift ////////////// - -#define OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(_Tpvec, suffix, vl) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - return __riscv_vslidedown(a, n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - return __riscv_vslideup(__riscv_vmv_v_x_##suffix##m2(0, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ CV_UNUSED(b); return a; } - -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint8, u8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int8, i8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint16, u16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int16, i16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint32, u32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int32, i32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint64, u64, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int64, i64, VTraits::vlanes()) - -#define OPENCV_HAL_IMPL_RVV_ROTATE_FP(_Tpvec, suffix, vl) \ -template inline _Tpvec v_rotate_right(const _Tpvec& a) \ -{ \ - return __riscv_vslidedown(a, n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a) \ -{ \ - return __riscv_vslideup(__riscv_vfmv_v_f_##suffix##m2(0, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ -{ return a; } \ -template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ -} \ -template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ -} \ -template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ -{ CV_UNUSED(b); return a; } - -OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float32, f32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float64, f64, VTraits::vlanes()) -#endif - -////////////// Convert to float ////////////// -inline v_float32 v_cvt_f32(const v_int32& a) -{ - return __riscv_vfcvt_f_x_v_f32m2(a, VTraits::vlanes()); -} - -#if CV_SIMD_SCALABLE_64F -inline v_float32 v_cvt_f32(const v_float64& a) -{ - return __riscv_vfncvt_f(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); -} - -inline v_float32 v_cvt_f32(const v_float64& a, const v_float64& b) -{ - return __riscv_vfncvt_f(__riscv_vset(__riscv_vlmul_ext_f64m4(a),1,b), VTraits::vlanes()); -} - -inline v_float64 v_cvt_f64(const v_int32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); -} - -inline v_float64 v_cvt_f64_high(const v_int32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); -} - -inline v_float64 v_cvt_f64(const v_float32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); -} - -inline v_float64 v_cvt_f64_high(const v_float32& a) -{ - return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); -} - -inline v_float64 v_cvt_f64(const v_int64& a) -{ - return __riscv_vfcvt_f(a, VTraits::vlanes()); -} -#endif - -//////////// Broadcast ////////////// - -#define OPENCV_HAL_IMPL_RVV_BROADCAST(_Tpvec, suffix) \ -template inline _Tpvec v_broadcast_element(_Tpvec v, int i = s) \ -{ \ - return v_setall_##suffix(v_extract_n(v, i)); \ -} \ -inline _Tpvec v_broadcast_highest(_Tpvec v) \ -{ \ - return v_setall_##suffix(v_extract_n(v, VTraits<_Tpvec>::vlanes()-1)); \ -} - -OPENCV_HAL_IMPL_RVV_BROADCAST(v_uint32, u32) -OPENCV_HAL_IMPL_RVV_BROADCAST(v_int32, s32) -OPENCV_HAL_IMPL_RVV_BROADCAST(v_float32, f32) - - -////////////// Reverse ////////////// -#define OPENCV_HAL_IMPL_RVV_REVERSE(_Tpvec, width) \ -inline _Tpvec v_reverse(const _Tpvec& a) \ -{ \ - vuint##width##m2_t vidx = __riscv_vrsub(__riscv_vid_v_u##width##m2(VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()-1, VTraits<_Tpvec>::vlanes()); \ - return __riscv_vrgather(a, vidx, VTraits<_Tpvec>::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint8, 8) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int8, 8) -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint16, 16) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int16, 16) -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint32, 32) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int32, 32) -OPENCV_HAL_IMPL_RVV_REVERSE(v_float32, 32) -OPENCV_HAL_IMPL_RVV_REVERSE(v_uint64, 64) -OPENCV_HAL_IMPL_RVV_REVERSE(v_int64, 64) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_REVERSE(v_float64, 64) -#endif - -//////////// Value reordering //////////// - -#define OPENCV_HAL_IMPL_RVV_EXPAND(_Tp, _Tpwvec, _Tpwvec_m2, _Tpvec, width, suffix, suffix2, cvt) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ - b0 = __riscv_vget_##suffix##m2(temp, 0); \ - b1 = __riscv_vget_##suffix##m2(temp, 1); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ \ - _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ - return __riscv_vget_##suffix##m2(temp, 0); \ -} \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ \ - _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ - return __riscv_vget_##suffix##m2(temp, 1); \ -} \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - return cvt(__riscv_vle##width##_v_##suffix2##m1(ptr, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_EXPAND(uchar, v_uint16, vuint16m4_t, v_uint8, 8, u16, u8, __riscv_vwcvtu_x) -OPENCV_HAL_IMPL_RVV_EXPAND(schar, v_int16, vint16m4_t, v_int8, 8, i16, i8, __riscv_vwcvt_x) -OPENCV_HAL_IMPL_RVV_EXPAND(ushort, v_uint32, vuint32m4_t, v_uint16, 16, u32, u16, __riscv_vwcvtu_x) -OPENCV_HAL_IMPL_RVV_EXPAND(short, v_int32, vint32m4_t, v_int16, 16, i32, i16, __riscv_vwcvt_x) -OPENCV_HAL_IMPL_RVV_EXPAND(uint, v_uint64, vuint64m4_t, v_uint32, 32, u64, u32, __riscv_vwcvtu_x) -OPENCV_HAL_IMPL_RVV_EXPAND(int, v_int64, vint64m4_t, v_int32, 32, i64, i32, __riscv_vwcvt_x) - -inline v_uint32 v_load_expand_q(const uchar* ptr) -{ - return __riscv_vwcvtu_x(__riscv_vwcvtu_x(__riscv_vle8_v_u8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); -} - -inline v_int32 v_load_expand_q(const schar* ptr) -{ - return __riscv_vwcvt_x(__riscv_vwcvt_x(__riscv_vle8_v_i8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); -} - -#define OPENCV_HAL_IMPL_RVV_PACK(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ -inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ -{ \ - return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} \ -template inline \ -_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ -{ \ - return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -template inline \ -void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} - -#define OPENCV_HAL_IMPL_RVV_PACK_32(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ -inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ -{ \ - return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, VTraits<_Tpvec>::vlanes()); \ -} \ -inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} \ -template inline \ -_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ -{ \ - return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ -} \ -template inline \ -void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_PACK(v_uint8, uchar, v_uint16, 8, u8, u16, __riscv_vnclipu, __riscv_vnclipu) -OPENCV_HAL_IMPL_RVV_PACK(v_int8, schar, v_int16, 8, i8, i16, __riscv_vnclip, __riscv_vnclip) -OPENCV_HAL_IMPL_RVV_PACK(v_uint16, ushort, v_uint32, 16, u16, u32, __riscv_vnclipu, __riscv_vnclipu) -OPENCV_HAL_IMPL_RVV_PACK(v_int16, short, v_int32, 16, i16, i32, __riscv_vnclip, __riscv_vnclip) -OPENCV_HAL_IMPL_RVV_PACK_32(v_uint32, unsigned, v_uint64, 32, u32, u64, __riscv_vnclipu, __riscv_vnsrl) -OPENCV_HAL_IMPL_RVV_PACK_32(v_int32, int, v_int64, 32, i32, i64, __riscv_vnclip, __riscv_vnsra) - -#define OPENCV_HAL_IMPL_RVV_PACK_U(_Tpvec, _Tp, _wTpvec, _wTp, hwidth, width, hsuffix, suffix, cast, hvl, vl) \ -inline _Tpvec v_pack_u(const _wTpvec& a, const _wTpvec& b) \ -{ \ - return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), 0, 0, vl); \ -} \ -inline void v_pack_u_store(_Tp* ptr, const _wTpvec& a) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), 0, 0, vl), hvl); \ -} \ -template inline \ -_Tpvec v_rshr_pack_u(const _wTpvec& a, const _wTpvec& b, int n = N) \ -{ \ - return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), n, 0, vl); \ -} \ -template inline \ -void v_rshr_pack_u_store(_Tp* ptr, const _wTpvec& a, int n = N) \ -{ \ - __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), n, 0, vl), hvl); \ -} - -OPENCV_HAL_IMPL_RVV_PACK_U(v_uint8, uchar, v_int16, short, 8, 16, u8, i16, __riscv_vreinterpret_v_i16m4_u16m4, VTraits::vlanes(), VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_PACK_U(v_uint16, ushort, v_int32, int, 16, 32, u16, i32, __riscv_vreinterpret_v_i32m4_u32m4, VTraits::vlanes(), VTraits::vlanes()) - - -/* void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) - a0 = {A1 A2 A3 A4} - a1 = {B1 B2 B3 B4} ---------------- - {A1 B1 A2 B2} and {A3 B3 A4 B4} -*/ - -#define OPENCV_HAL_IMPL_RVV_ZIP(_Tpvec, _wTpvec, suffix, width, width2, convert2um2, convert2um1) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ - _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2um2( \ - __riscv_vor(__riscv_vzext_vf2(convert2um1(a0), VTraits<_Tpvec>::vlanes()*2), \ - __riscv_vreinterpret_u##width2##m4(__riscv_vslide1up(__riscv_vreinterpret_u##width##m4(__riscv_vzext_vf2(convert2um1(a1), VTraits<_Tpvec>::vlanes()*2)), 0, VTraits<_Tpvec>::vlanes()*2)), \ - VTraits<_Tpvec>::vlanes()))); \ - b0 = __riscv_vget_##suffix##m2(temp, 0); \ - b1 = __riscv_vget_##suffix##m2(temp, 1); \ -} -OPENCV_HAL_IMPL_RVV_ZIP(v_uint8, vuint8m4_t, u8, 8, 16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP(v_int8, vint8m4_t, i8, 8, 16, __riscv_vreinterpret_u8m4, __riscv_vreinterpret_u8m2) -OPENCV_HAL_IMPL_RVV_ZIP(v_uint16, vuint16m4_t, u16, 16, 32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP(v_int16, vint16m4_t, i16, 16, 32, __riscv_vreinterpret_u16m4, __riscv_vreinterpret_u16m2) -OPENCV_HAL_IMPL_RVV_ZIP(v_uint32, vuint32m4_t, u32, 32, 64, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_ZIP(v_int32, vint32m4_t, i32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) -OPENCV_HAL_IMPL_RVV_ZIP(v_float32, vfloat32m4_t, f32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) - -#if CV_SIMD_SCALABLE_64F -inline void v_zip(const v_float64& a0, const v_float64& a1, v_float64& b0, v_float64& b1) { \ - vuint16mf2_t idx0 = __riscv_vid_v_u16mf2(VTraits::vlanes()); - vuint16mf2_t idx1 = __riscv_vadd(idx0, VTraits::vlanes(), VTraits::vlanes()); - vuint16m1_t idx = __riscv_vreinterpret_u16m1(( \ - __riscv_vor(__riscv_vzext_vf2(idx0, VTraits::vlanes()), \ - __riscv_vreinterpret_u32m1(__riscv_vslide1up(__riscv_vreinterpret_u16m1(__riscv_vzext_vf2(idx1, VTraits::vlanes())), 0, VTraits::vlanes())), \ - VTraits::vlanes()))); -#if 0 - vfloat64m4_t temp = __riscv_vcreate_v_f64m2_f64m4(a0, a1); -#else // TODO: clean up when RVV Intrinsic is frozen. - vfloat64m4_t temp = __riscv_vlmul_ext_f64m4(a0); - temp = __riscv_vset(temp, 1, a1); -#endif - temp = __riscv_vrgatherei16(temp, idx, VTraits::vlanes()*2); - b0 = __riscv_vget_f64m2(temp, 0); \ - b1 = __riscv_vget_f64m2(temp, 1); \ -} -#endif - -#define OPENCV_HAL_IMPL_RVV_UNPACKS(_Tpvec, width) \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup(a, b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes());\ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return __riscv_vslideup( \ - __riscv_vslidedown(a, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ - __riscv_vslidedown(b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ - VTraits<_Tpvec>::vlanes()/2, \ - VTraits<_Tpvec>::vlanes()); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - c = v_combine_low(a, b); \ - d = v_combine_high(a, b); \ -} - -OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint8, 8) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_int8, 8) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint16, 16) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_int16, 16) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint32, 32) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_int32, 32) -OPENCV_HAL_IMPL_RVV_UNPACKS(v_float32, 32) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_UNPACKS(v_float64, 64) -#endif - -#define OPENCV_HAL_IMPL_RVV_INTERLEAVED(_Tpvec, _Tp, suffix, width, hwidth, vl) \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ -{ \ - a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*2, VTraits::vlanes()); \ - b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*2, VTraits::vlanes()); \ -}\ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ -{ \ - a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*3, VTraits::vlanes()); \ - b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*3, VTraits::vlanes()); \ - c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*3, VTraits::vlanes()); \ -} \ -inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ - v_##_Tpvec& c, v_##_Tpvec& d) \ -{ \ - \ - a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*4, VTraits::vlanes()); \ - b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*4, VTraits::vlanes()); \ - c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*4, VTraits::vlanes()); \ - d = __riscv_vlse##width##_v_##suffix##m2(ptr+3, sizeof(_Tp)*4, VTraits::vlanes()); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - __riscv_vsse##width(ptr, sizeof(_Tp)*2, a, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+1, sizeof(_Tp)*2, b, VTraits::vlanes()); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ \ - __riscv_vsse##width(ptr, sizeof(_Tp)*3, a, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+1, sizeof(_Tp)*3, b, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+2, sizeof(_Tp)*3, c, VTraits::vlanes()); \ -} \ -inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ - const v_##_Tpvec& c, const v_##_Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ -{ \ - __riscv_vsse##width(ptr, sizeof(_Tp)*4, a, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+1, sizeof(_Tp)*4, b, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+2, sizeof(_Tp)*4, c, VTraits::vlanes()); \ - __riscv_vsse##width(ptr+3, sizeof(_Tp)*4, d, VTraits::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint8, uchar, u8, 8, 4, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int8, schar, i8, 8, 4, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint16, ushort, u16, 16, 8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int16, short, i16, 16, 8, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint32, unsigned, u32, 32, 16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int32, int, i32, 32, 16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(float32, float, f32, 32, 16, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint64, uint64, u64, 64, 32, VTraits::vlanes()) -OPENCV_HAL_IMPL_RVV_INTERLEAVED(int64, int64, i64, 64, 32, VTraits::vlanes()) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_INTERLEAVED(float64, double, f64, 64, 32, VTraits::vlanes()) -#endif - -static uint64_t idx_interleave_pairs[] = { \ - 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x1715161413111210, 0x1f1d1e1c1b191a18, \ - 0x2725262423212220, 0x2f2d2e2c2b292a28, 0x3735363433313230, 0x3f3d3e3c3b393a38, \ - 0x4745464443414240, 0x4f4d4e4c4b494a48, 0x5755565453515250, 0x5f5d5e5c5b595a58, \ - 0x6765666463616260, 0x6f6d6e6c6b696a68, 0x7775767473717270, 0x7f7d7e7c7b797a78}; - -static uint64_t idx_interleave_quads[] = { \ - 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x1713161215111410, 0x1f1b1e1a1d191c18, \ - 0x2723262225212420, 0x2f2b2e2a2d292c28, 0x3733363235313430, 0x3f3b3e3a3d393c38, \ - 0x4743464245414440, 0x4f4b4e4a4d494c48, 0x5753565255515450, 0x5f5b5e5a5d595c58, \ - 0x6763666265616460, 0x6f6b6e6a6d696c68, 0x7773767275717470, 0x7f7b7e7a7d797c78}; - -#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(_Tpvec, func) \ -inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ - CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ - vuint8m2_t vidx = __riscv_vundefined_u8m2();\ - vidx = __riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)); \ - return __riscv_vrgather(vec, vidx, VTraits::vlanes()); \ -} -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, quads) - -#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(_Tpvec, width, vzext_vfx, func) \ -inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ - CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ - vuint##width##m2_t vidx = __riscv_vundefined_u##width##m2();\ - vidx = __riscv_vget_u##width##m2(vzext_vfx(__riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)), VTraits::vlanes()), 0); \ - return __riscv_vrgather(vec, vidx, VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, pairs) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, pairs) - -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, quads) -OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, quads) - -//////////// PopCount ////////// -static const unsigned char popCountTable[256] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; -#define OPENCV_HAL_IMPL_RVV_HADD(_Tpvec, _Tpvec2, _Tm2, width, width2, suffix, add) \ -static inline _Tpvec2 v_hadd(_Tpvec a) { \ - vuint##width2##m2_t oneX2 = __riscv_vmv_v_x_u##width2##m2(1, VTraits::vlanes()); \ - vuint##width##m2_t one = __riscv_vreinterpret_u##width##m2(oneX2); \ - _Tm2 res = add(a, __riscv_vslide1down(a, 0, VTraits::vlanes()), VTraits::vlanes()); \ - return __riscv_vget_##suffix##m2(__riscv_vcompress(res, __riscv_vmseq(one, 1, VTraits::vlanes()), VTraits::vlanes()), 0); \ -} -OPENCV_HAL_IMPL_RVV_HADD(v_uint8, v_uint16, vuint16m4_t, 8, 16, u16, __riscv_vwaddu_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_uint16, v_uint32, vuint32m4_t, 16, 32, u32, __riscv_vwaddu_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_uint32, v_uint64, vuint64m4_t, 32, 64, u64, __riscv_vwaddu_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_int8, v_int16, vint16m4_t, 8, 16, i16, __riscv_vwadd_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_int16, v_int32, vint32m4_t, 16, 32, i32, __riscv_vwadd_vv) -OPENCV_HAL_IMPL_RVV_HADD(v_int32, v_int64, vint64m4_t, 32, 64, i64, __riscv_vwadd_vv) - -OPENCV_HAL_IMPL_RVV_HADD(vint32m4_t, v_int32, vint32m4_t, 16, 32, i32, __riscv_vadd) -OPENCV_HAL_IMPL_RVV_HADD(vint64m4_t, v_int64, vint64m4_t, 32, 64, i64, __riscv_vadd) - -inline v_uint8 v_popcount(const v_uint8& a) -{ - return __riscv_vloxei8(popCountTable, a, VTraits::vlanes()); -} -inline v_uint16 v_popcount(const v_uint16& a) -{ - return v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))); -} -inline v_uint32 v_popcount(const v_uint32& a) -{ - return v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a)))); -} -inline v_uint64 v_popcount(const v_uint64& a) -{ - return v_hadd(v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))))); -} - -inline v_uint8 v_popcount(const v_int8& a) -{ - return v_popcount(v_abs(a));\ -} -inline v_uint16 v_popcount(const v_int16& a) -{ - return v_popcount(v_abs(a));\ -} -inline v_uint32 v_popcount(const v_int32& a) -{ - return v_popcount(v_abs(a));\ -} -inline v_uint64 v_popcount(const v_int64& a) -{ - // max(0 - a) is used, since v_abs does not support 64-bit integers. - return v_popcount(v_reinterpret_as_u64(__riscv_vmax(a, v_sub(v_setzero_s64(), a), VTraits::vlanes()))); -} - - -//////////// SignMask //////////// -#define OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(_Tpvec) \ -inline int v_signmask(const _Tpvec& a) \ -{ \ - uint8_t ans[4] = {0}; \ - __riscv_vsm(ans, __riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ - return *(reinterpret_cast(ans)) & (((__int128_t)1 << VTraits<_Tpvec>::vlanes()) - 1); \ -} \ -inline int v_scan_forward(const _Tpvec& a) \ -{ \ - return (int)__riscv_vfirst(__riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int8) -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int16) -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int32) -OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int64) - -inline int64 v_signmask(const v_uint8& a) -{ return v_signmask(v_reinterpret_as_s8(a)); } -inline int64 v_signmask(const v_uint16& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } -inline int v_signmask(const v_uint32& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_float32& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_uint64& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } -#if CV_SIMD_SCALABLE_64F -inline int v_signmask(const v_float64& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } -#endif - -//////////// Scan forward //////////// -inline int v_scan_forward(const v_uint8& a) -{ return v_scan_forward(v_reinterpret_as_s8(a)); } -inline int v_scan_forward(const v_uint16& a) -{ return v_scan_forward(v_reinterpret_as_s16(a)); } -inline int v_scan_forward(const v_uint32& a) -{ return v_scan_forward(v_reinterpret_as_s32(a)); } -inline int v_scan_forward(const v_float32& a) -{ return v_scan_forward(v_reinterpret_as_s32(a)); } -inline int v_scan_forward(const v_uint64& a) -{ return v_scan_forward(v_reinterpret_as_s64(a)); } -#if CV_SIMD_SCALABLE_64F -inline int v_scan_forward(const v_float64& a) -{ return v_scan_forward(v_reinterpret_as_s64(a)); } -#endif - -//////////// Pack triplets //////////// -// {A0, A1, A2, A3, B0, B1, B2, B3, C0 ...} --> {A0, A1, A2, B0, B1, B2, C0 ...} -// mask: {0,0,0,1, ...} -> {T,T,T,F, ...} -#define OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(_Tpvec, v_trunc) \ -inline _Tpvec v_pack_triplets(const _Tpvec& vec) { \ - size_t vl = VTraits::vlanes(); \ - vuint32m2_t one = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t zero = __riscv_vmv_v_x_u8m2(0, vl); \ - vuint8m2_t mask = __riscv_vreinterpret_u8m2(one); \ - return __riscv_vcompress(vec, __riscv_vmseq(v_trunc(__riscv_vslideup(zero, mask, 3, vl)), 0, vl), VTraits<_Tpvec>::vlanes()); \ -} - -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int8, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint16, __riscv_vlmul_trunc_u8m1) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int16, __riscv_vlmul_trunc_u8m1) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint32, __riscv_vlmul_trunc_u8mf2) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int32, __riscv_vlmul_trunc_u8mf2) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float32, __riscv_vlmul_trunc_u8mf2) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint64, __riscv_vlmul_trunc_u8mf4) -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int64, __riscv_vlmul_trunc_u8mf4) -#if CV_SIMD_SCALABLE_64F -OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float64, __riscv_vlmul_trunc_u8mf4) -#endif - - -////// FP16 support /////// - -#if defined(__riscv_zfh) && __riscv_zfh -inline v_float32 v_load_expand(const hfloat* ptr) -{ - return __riscv_vfwcvt_f(__riscv_vle16_v_f16m1((_Float16*)ptr, VTraits::vlanes()) ,VTraits::vlanes());; -} - -inline void v_pack_store(hfloat* ptr, const v_float32& v) -{ - __riscv_vse16_v_f16m1((_Float16*)ptr, __riscv_vfncvt_f_f_w_f16m1(v, VTraits::vlanes()), VTraits::vlanes()); -} -#else -inline v_float32 v_load_expand(const hfloat* ptr) -{ - float buf[32]; - for( int i = 0; i < VTraits::vlanes(); i++ ) buf[i] = (float)ptr[i]; - return v_load(buf); -} - -inline void v_pack_store(hfloat* ptr, const v_float32& v) -{ - float buf[32]; - v_store(buf, v); - for( int i = 0; i < VTraits::vlanes(); i++ ) ptr[i] = hfloat(buf[i]); -} -#endif -////////////// Rounding ////////////// -inline v_int32 v_round(const v_float32& a) -{ - // return vfcvt_x(vfadd(a, 1e-6, VTraits::vlanes()), VTraits::vlanes()); - return __riscv_vfcvt_x(a, VTraits::vlanes()); -} - -inline v_int32 v_floor(const v_float32& a) -{ - return __riscv_vfcvt_x(__riscv_vfsub(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); - // return vfcvt_x(a, VTraits::vlanes()); -} - -inline v_int32 v_ceil(const v_float32& a) -{ - return __riscv_vfcvt_x(__riscv_vfadd(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); -} - -inline v_int32 v_trunc(const v_float32& a) -{ - return __riscv_vfcvt_rtz_x(a, VTraits::vlanes()); -} -#if CV_SIMD_SCALABLE_64F -inline v_int32 v_round(const v_float64& a) -{ - return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); -} - -inline v_int32 v_round(const v_float64& a, const v_float64& b) -{ - // return vfncvt_x(vset(vlmul_ext_f64m2(vfadd(a, 1e-6, VTraits::vlanes())), 1, b), VTraits::vlanes()); - // Fix https://github.com/opencv/opencv/issues/24746 - return __riscv_vfncvt_x(__riscv_vset(__riscv_vlmul_ext_f64m4(a), 1, b), VTraits::vlanes()); -} - -inline v_int32 v_floor(const v_float64& a) -{ - return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfsub(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); -} - -inline v_int32 v_ceil(const v_float64& a) -{ - return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfadd(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); -} - -inline v_int32 v_trunc(const v_float64& a) -{ - return __riscv_vfncvt_rtz_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); -} -#endif - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32 v_dotprod(const v_int16& a, const v_int16& b) -{ - vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); - return v_hadd(temp1); -} - -inline v_int32 v_dotprod(const v_int16& a, const v_int16& b, const v_int32& c) -{ - vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); - return __riscv_vadd(v_hadd(temp1), c, VTraits::vlanes()); -} - -// 32 >> 64 -inline v_int64 v_dotprod(const v_int32& a, const v_int32& b) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ - vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ - vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); - vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_i64m2(res); \ -} -inline v_int64 v_dotprod(const v_int32& a, const v_int32& b, const v_int64& c) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ - vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ - vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); - vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); \ -} - -// 8 >> 32 -inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_u32m2(res); -} - -inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b, - const v_uint32& c) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_u32m2(res), c, VTraits::vlanes()); -} - -inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_i32m2(res); -} - -inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b, - const v_int32& c) -{ - vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ - vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ - vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ - vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_i32m2(res), c, VTraits::vlanes()); -} - - -// // 16 >> 64 -inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_u64m2(res); -} -inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b, const v_uint64& c) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ - vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_u64m2(res), c, VTraits::vlanes()); -} - -inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vlmul_trunc_i64m2(res); -} -inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b, - const v_int64& c) -{ - vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ - vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ - vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ - vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ - vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); - vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); - vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); - vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); - res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ - return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); -} - -// // 32 >> 64f -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b, - const v_float64& c) -{ return v_add(v_dotprod_expand(a, b) , c); } -#endif - -//////// Fast Dot Product //////// -// 16 >> 32 -inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b, const v_int32& c) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - -// 32 >> 64 -inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b, const v_int64& c) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - - -// 8 >> 32 -inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b) -{ - vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); - auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res); -} -inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b, const v_uint32& c) -{ - vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); - auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res), VTraits::vlanes()); -} -inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b, const v_int32& c) -{ - vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - -// 16 >> 64 -inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b) -{ - vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b, const v_uint64& c) -{ - vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} -inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); -} -inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b, const v_int64& c) -{ - vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); - return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); -} - -// 32 >> 64f -#if CV_SIMD_SCALABLE_64F -inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b) -{ return v_cvt_f64(v_dotprod_fast(a, b)); } -inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b, const v_float64& c) -{ return v_add(v_dotprod_expand_fast(a, b) , c); } -#endif - -// TODO: only 128 bit now. -inline v_float32 v_matmul(const v_float32& v, const v_float32& mat0, - const v_float32& mat1, const v_float32& mat2, - const v_float32& mat3) -{ - vfloat32m2_t res; - res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v, 0), VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 1), mat1, VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 2), mat2, VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 3), mat3, VTraits::vlanes()); - return res; -} - -// TODO: only 128 bit now. -inline v_float32 v_matmuladd(const v_float32& v, const v_float32& mat0, - const v_float32& mat1, const v_float32& mat2, - const v_float32& a) -{ - vfloat32m2_t res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v,0), VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,1), mat1, VTraits::vlanes()); - res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,2), mat2, VTraits::vlanes()); - return __riscv_vfadd(res, a, VTraits::vlanes()); -} - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32 v_exp(const v_float32& x) { return v_exp_default_32f(x); } -inline v_float32 v_log(const v_float32& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32& x, v_float32& s, v_float32& c) { v_sincos_default_32f(x, s, c); } -inline v_float32 v_sin(const v_float32& x) { return v_sin_default_32f(x); } -inline v_float32 v_cos(const v_float32& x) { return v_cos_default_32f(x); } -inline v_float32 v_erf(const v_float32& x) { return v_erf_default_32f(x); } - -inline v_float64 v_exp(const v_float64& x) { return v_exp_default_64f(x); } -inline v_float64 v_log(const v_float64& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64& x, v_float64& s, v_float64& c) { v_sincos_default_64f(x, s, c); } -inline v_float64 v_sin(const v_float64& x) { return v_sin_default_64f(x); } -inline v_float64 v_cos(const v_float64& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} //namespace cv - -#endif //OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// The original implementation is contributed by HAN Liutong. +// Copyright (C) 2022, Institute of Software, Chinese Academy of Sciences. + +#ifndef OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP +#define OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP + +#include + +#if defined(__GNUC__) && !defined(__clang__) +// FIXIT: eliminate massive warnigs from templates +// GCC from 'rvv-next': riscv64-unknown-linux-gnu-g++ (g42df3464463) 12.0.1 20220505 (prerelease) +// doesn't work: #pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wignored-attributes" +#endif + +#ifndef CV_RVV_MAX_VLEN +#define CV_RVV_MAX_VLEN 1024 +#endif + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define CV_SIMD_SCALABLE 1 +#define CV_SIMD_SCALABLE_64F 1 + +using v_uint8 = vuint8m2_t; +using v_int8 = vint8m2_t; +using v_uint16 = vuint16m2_t; +using v_int16 = vint16m2_t; +using v_uint32 = vuint32m2_t; +using v_int32 = vint32m2_t; +using v_uint64 = vuint64m2_t; +using v_int64 = vint64m2_t; + +using v_float32 = vfloat32m2_t; +#if CV_SIMD_SCALABLE_64F +using v_float64 = vfloat64m2_t; +#endif + +using uchar = unsigned char; +using schar = signed char; +using ushort = unsigned short; +using uint = unsigned int; +using uint64 = unsigned long int; +using int64 = long int; + + +template +struct VTraits; + +#define OPENCV_HAL_IMPL_RVV_TRAITS(REG, TYP, SUF, SZ) \ +template <> \ +struct VTraits \ +{ \ + static inline int vlanes() { return __riscv_vsetvlmax_##SUF(); } \ + using lane_type = TYP; \ + static const int max_nlanes = CV_RVV_MAX_VLEN/SZ; \ +}; + +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m1_t, int8_t, e8m1, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m2_t, int8_t, e8m2, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m4_t, int8_t, e8m4, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vint8m8_t, int8_t, e8m8, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m1_t, uint8_t, e8m1, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m2_t, uint8_t, e8m2, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m4_t, uint8_t, e8m4, 8) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint8m8_t, uint8_t, e8m8, 8) + +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m1_t, int16_t, e16m1, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m2_t, int16_t, e16m2, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m4_t, int16_t, e16m4, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vint16m8_t, int16_t, e16m8, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m1_t, uint16_t, e16m1, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m2_t, uint16_t, e16m2, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m4_t, uint16_t, e16m4, 16) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint16m8_t, uint16_t, e16m8, 16) + +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m1_t, int32_t, e32m1, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m2_t, int32_t, e32m2, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m4_t, int32_t, e32m4, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vint32m8_t, int32_t, e32m8, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m1_t, uint32_t, e32m1, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m2_t, uint32_t, e32m2, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m4_t, uint32_t, e32m4, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint32m8_t, uint32_t, e32m8, 32) + +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m1_t, int64_t, e64m1, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m2_t, int64_t, e64m2, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m4_t, int64_t, e64m4, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vint64m8_t, int64_t, e64m8, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m1_t, uint64_t, e64m1, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m2_t, uint64_t, e64m2, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m4_t, uint64_t, e64m4, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vuint64m8_t, uint64_t, e64m8, 64) + +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m1_t, float, e32m1, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m2_t, float, e32m2, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m4_t, float, e32m4, 32) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat32m8_t, float, e32m8, 32) + +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m1_t, double, e64m1, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m2_t, double, e64m2, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m4_t, double, e64m4, 64) +OPENCV_HAL_IMPL_RVV_TRAITS(vfloat64m8_t, double, e64m8, 64) +#endif + + +// LLVM/Clang defines "overloaded intrinsics" e.g. 'vand(op1, op2)' +// GCC does not have these functions, so we need to implement them manually +// We implement only selected subset required to build current state of the code +// Included inside namespace cv:: +// #ifndef __riscv_v_intrinsic_overloading +// #include "intrin_rvv_compat_overloaded.hpp" +// #endif // __riscv_v_intrinsic_overloading + + +//////////// get0 //////////// +#define OPENCV_HAL_IMPL_RVV_GRT0_INT(_Tpvec, _Tp) \ +inline _Tp v_get0(const v_##_Tpvec& v) \ +{ \ + return __riscv_vmv_x(v); \ +} + +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint8, uchar) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int8, schar) +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint16, ushort) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int16, short) +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint32, unsigned) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int32, int) +OPENCV_HAL_IMPL_RVV_GRT0_INT(uint64, uint64) +OPENCV_HAL_IMPL_RVV_GRT0_INT(int64, int64) + +inline float v_get0(const v_float32& v) \ +{ \ + return __riscv_vfmv_f(v); \ +} +#if CV_SIMD_SCALABLE_64F +inline double v_get0(const v_float64& v) \ +{ \ + return __riscv_vfmv_f(v); \ +} +#endif + +//////////// Initial //////////// + +#define OPENCV_HAL_IMPL_RVV_INIT_INTEGER(_Tpvec, _Tp, suffix1, suffix2, vl) \ +inline v_##_Tpvec v_setzero_##suffix1() \ +{ \ + return __riscv_vmv_v_x_##suffix2##m2(0, vl); \ +} \ +inline v_##_Tpvec v_setall_##suffix1(_Tp v) \ +{ \ + return __riscv_vmv_v_x_##suffix2##m2(v, vl); \ +} \ +template <> inline v_##_Tpvec v_setzero_() \ +{ \ + return v_setzero_##suffix1(); \ +} \ +template <> inline v_##_Tpvec v_setall_(_Tp v) \ +{ \ + return v_setall_##suffix1(v); \ +} + +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint8, uchar, u8, u8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int8, schar, s8, i8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint16, ushort, u16, u16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int16, short, s16, i16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint32, uint, u32, u32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int32, int, s32, i32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(uint64, uint64, u64, u64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INIT_INTEGER(int64, int64, s64, i64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_INIT_FP(_Tpv, _Tp, suffix, vl) \ +inline v_##_Tpv v_setzero_##suffix() \ +{ \ + return __riscv_vfmv_v_f_##suffix##m2(0, vl); \ +} \ +inline v_##_Tpv v_setall_##suffix(_Tp v) \ +{ \ + return __riscv_vfmv_v_f_##suffix##m2(v, vl); \ +} \ +template <> inline v_##_Tpv v_setzero_() \ +{ \ + return v_setzero_##suffix(); \ +} \ +template <> inline v_##_Tpv v_setall_(_Tp v) \ +{ \ + return v_setall_##suffix(v); \ +} + +OPENCV_HAL_IMPL_RVV_INIT_FP(float32, float, f32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_INIT_FP(float64, double, f64, VTraits::vlanes()) +#endif + +//////////// Reinterpret //////////// +#define OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(_Tpvec1, suffix1) \ +inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec1& v) \ +{ \ + return v;\ +} +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint8, u8) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint16, u16) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint32, u32) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(uint64, u64) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int8, s8) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int16, s16) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int32, s32) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(int64, s64) +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float32, f32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_NOTHING_REINTERPRET(float64, f64) +#endif +// TODO: can be simplified by using overloaded RV intrinsic +#define OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2) \ +inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ +{ \ + return v_##_Tpvec1(__riscv_vreinterpret_v_##nsuffix2##m2_##nsuffix1##m2(v));\ +} \ +inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ +{ \ + return v_##_Tpvec2(__riscv_vreinterpret_v_##nsuffix1##m2_##nsuffix2##m2(v));\ +} + +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, int8, u8, s8, u8, i8) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, int16, u16, s16, u16, i16) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, int32, u32, s32, u32, i32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, float32, u32, f32, u32, f32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, float32, s32, f32, i32, f32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, int64, u64, s64, u64, i64) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint64, float64, u64, f64, u64, f64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int64, float64, s64, f64, i64, f64) +#endif +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint16, u8, u16, u8, u16) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint32, u8, u32, u8, u32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint8, uint64, u8, u64, u8, u64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint32, u16, u32, u16, u32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint16, uint64, u16, u64, u16, u64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(uint32, uint64, u32, u64, u32, u64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int16, s8, s16, i8, i16) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int32, s8, s32, i8, i32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int8, int64, s8, s64, i8, i64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int32, s16, s32, i16, i32) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int16, int64, s16, s64, i16, i64) +OPENCV_HAL_IMPL_RVV_NATIVE_REINTERPRET(int32, int64, s32, s64, i32, i64) + + +#define OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(_Tpvec1, _Tpvec2, suffix1, suffix2, nsuffix1, nsuffix2, width1, width2) \ +inline v_##_Tpvec1 v_reinterpret_as_##suffix1(const v_##_Tpvec2& v) \ +{ \ + return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix1##width1##m2(__riscv_vreinterpret_v_##nsuffix2##width2##m2_##nsuffix1##width2##m2(v));\ +} \ +inline v_##_Tpvec2 v_reinterpret_as_##suffix2(const v_##_Tpvec1& v) \ +{ \ + return __riscv_vreinterpret_v_##nsuffix1##width2##m2_##nsuffix2##width2##m2(__riscv_vreinterpret_v_##nsuffix1##width1##m2_##nsuffix1##width2##m2(v));\ +} + +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int16, u8, s16, u, i, 8, 16) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int32, u8, s32, u, i, 8, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, int64, u8, s64, u, i, 8, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int8, u16, s8, u, i, 16, 8) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int32, u16, s32, u, i, 16, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, int64, u16, s64, u, i, 16, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int8, u32, s8, u, i, 32, 8) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int16, u32, s16, u, i, 32, 16) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, int64, u32, s64, u, i, 32, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int8, u64, s8, u, i, 64, 8) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int16, u64, s16, u, i, 64, 16) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, int32, u64, s32, u, i, 64, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float32, u8, f32, u, f, 8, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float32, u16, f32, u, f, 16, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint64, float32, u64, f32, u, f, 64, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float32, s8, f32, i, f, 8, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float32, s16, f32, i, f, 16, 32) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int64, float32, s64, f32, i, f, 64, 32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint8, float64, u8, f64, u, f, 8, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint16, float64, u16, f64, u, f, 16, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(uint32, float64, u32, f64, u, f, 32, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int8, float64, s8, f64, i, f, 8, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int16, float64, s16, f64, i, f, 16, 64) +OPENCV_HAL_IMPL_RVV_TWO_TIMES_REINTERPRET(int32, float64, s32, f64, i, f, 32, 64) +// Three times reinterpret +inline v_float32 v_reinterpret_as_f32(const v_float64& v) \ +{ \ + return __riscv_vreinterpret_v_u32m2_f32m2(__riscv_vreinterpret_v_u64m2_u32m2(__riscv_vreinterpret_v_f64m2_u64m2(v)));\ +} + +inline v_float64 v_reinterpret_as_f64(const v_float32& v) \ +{ \ + return __riscv_vreinterpret_v_u64m2_f64m2(__riscv_vreinterpret_v_u32m2_u64m2(__riscv_vreinterpret_v_f32m2_u32m2(v)));\ +} +#endif + +//////////// Extract ////////////// + +#define OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(_Tpvec, _Tp, vl) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ +} \ +template inline _Tp v_extract_n(_Tpvec v, int i = s) \ +{ \ + return __riscv_vmv_x(__riscv_vslidedown(v, i, vl)); \ +} + +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint8, uchar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int8, schar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint16, ushort, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int16, short, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint32, unsigned int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int32, int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_uint64, uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT_INTEGER(v_int64, int64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_EXTRACT_FP(_Tpvec, _Tp, vl) \ +template \ +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b, int i = s) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, i, vl), b, VTraits<_Tpvec>::vlanes() - i, vl); \ +} \ +template inline _Tp v_extract_n(_Tpvec v, int i = s) \ +{ \ + return __riscv_vfmv_f(__riscv_vslidedown(v, i, vl)); \ +} + +OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float32, float, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_EXTRACT_FP(v_float64, double, VTraits::vlanes()) +#endif + +#define OPENCV_HAL_IMPL_RVV_EXTRACT(_Tpvec, _Tp, vl) \ +inline _Tp v_extract_highest(_Tpvec v) \ +{ \ + return v_extract_n(v, vl-1); \ +} + +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint8, uchar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int8, schar, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint16, ushort, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int16, short, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint32, unsigned int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int32, int, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_uint64, uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_int64, int64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_EXTRACT(v_float32, float, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_EXTRACT(v_float64, double, VTraits::vlanes()) +#endif + + +////////////// Load/Store ////////////// +#define OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(_Tpvec, _nTpvec, _Tp, hvl, vl, width, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ \ + return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ +} \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ \ + return __riscv_vle##width##_v_##suffix##m2(ptr, vl); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ \ + __riscv_vse##width##_v_##suffix##m2(ptr, a, vl); \ +} \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ \ + return __riscv_vle##width##_v_##suffix##m2(ptr, hvl); \ +} \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + return __riscv_vslideup(__riscv_vle##width##_v_##suffix##m2(ptr0, hvl), __riscv_vle##width##_v_##suffix##m2(ptr1, hvl), hvl, vl); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, vl); \ +} \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, vl); \ +} \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, vl); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, a, hvl); \ +} \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + __riscv_vse##width(ptr, __riscv_vslidedown_vx_##suffix##m2(a, hvl, vl), hvl); \ +} \ +template \ +_Tpvec v_load_##suffix(Targs... nScalars) \ +{ \ + return v_load({nScalars...}); \ +} + + +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint8, vuint8m2_t, uchar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, u8) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int8, vint8m2_t, schar, VTraits::vlanes() / 2, VTraits::vlanes(), 8, i8) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint16, vuint16m2_t, ushort, VTraits::vlanes() / 2, VTraits::vlanes(), 16, u16) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int16, vint16m2_t, short, VTraits::vlanes() / 2, VTraits::vlanes(), 16, i16) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint32, vuint32m2_t, unsigned int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, u32) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int32, vint32m2_t, int, VTraits::vlanes() / 2, VTraits::vlanes(), 32, i32) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_uint64, vuint64m2_t, uint64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, u64) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_int64, vint64m2_t, int64, VTraits::vlanes() / 2, VTraits::vlanes(), 64, i64) +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float32, vfloat32m2_t, float, VTraits::vlanes() /2 , VTraits::vlanes(), 32, f32) + +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_LOADSTORE_OP(v_float64, vfloat64m2_t, double, VTraits::vlanes() / 2, VTraits::vlanes(), 64, f64) +#endif + +////////////// Lookup table access //////////////////// +#define OPENCV_HAL_IMPL_RVV_LUT(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_lut(const _Tp* tab, const int* idx) \ +{ \ + auto vidx = __riscv_vmul(__riscv_vreinterpret_u32##suffix(__riscv_vle32_v_i32##suffix(idx, VTraits<_Tpvec>::vlanes())), sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ + return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT(v_int8, schar, m8) +OPENCV_HAL_IMPL_RVV_LUT(v_int16, short, m4) +OPENCV_HAL_IMPL_RVV_LUT(v_int32, int, m2) +OPENCV_HAL_IMPL_RVV_LUT(v_int64, int64_t, m1) +OPENCV_HAL_IMPL_RVV_LUT(v_float32, float, m2) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_LUT(v_float64, double, m1) +#endif + +#define OPENCV_HAL_IMPL_RVV_LUT_PAIRS(_Tpvec, _Tp, suffix1, suffix2, v_trunc) \ +inline _Tpvec v_lut_pairs(const _Tp* tab, const int* idx) \ +{ \ + auto v0 = __riscv_vle32_v_u32##suffix1((unsigned*)idx, VTraits<_Tpvec>::vlanes()/2); \ + auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/2); \ + auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/2); \ + auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/2); \ + auto sh1 = __riscv_vslide1up(v_trunc(__riscv_vreinterpret_u32##suffix2(w1)),0, VTraits<_Tpvec>::vlanes()); \ + auto vid = __riscv_vor(sh1, v_trunc(__riscv_vreinterpret_u32##suffix2(w0)), VTraits<_Tpvec>::vlanes()); \ + auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ + return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int8, schar, m4, m8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int16, short, m2, m4, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int32, int, m1, m2, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float32, float, m1, m2, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_int64, int64_t, m1, m2, __riscv_vlmul_trunc_u32m1) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_LUT_PAIRS(v_float64, double, m1, m2, __riscv_vlmul_trunc_u32m1) +#endif + + +#define OPENCV_HAL_IMPL_RVV_LUT_QUADS(_Tpvec, _Tp, suffix0, suffix1, suffix2, v_trunc) \ +inline _Tpvec v_lut_quads(const _Tp* tab, const int* idx) \ +{ \ + auto v0 = __riscv_vle32_v_u32##suffix0((unsigned*)idx, VTraits<_Tpvec>::vlanes()/4); \ + auto v1 = __riscv_vadd(v0, 1, VTraits<_Tpvec>::vlanes()/4); \ + auto v2 = __riscv_vadd(v0, 2, VTraits<_Tpvec>::vlanes()/4); \ + auto v3 = __riscv_vadd(v0, 3, VTraits<_Tpvec>::vlanes()/4); \ + auto w0 = __riscv_vwcvtu_x(v0, VTraits<_Tpvec>::vlanes()/4); \ + auto w1 = __riscv_vwcvtu_x(v1, VTraits<_Tpvec>::vlanes()/4); \ + auto w2 = __riscv_vwcvtu_x(v2, VTraits<_Tpvec>::vlanes()/4); \ + auto w3 = __riscv_vwcvtu_x(v3, VTraits<_Tpvec>::vlanes()/4); \ + auto sh2 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w2),0, VTraits<_Tpvec>::vlanes()/2); \ + auto sh3 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix1(w3),0, VTraits<_Tpvec>::vlanes()/2); \ + auto vid0 = __riscv_vor(sh2, __riscv_vreinterpret_u32##suffix1(w0), VTraits<_Tpvec>::vlanes()/2); \ + auto vid1 = __riscv_vor(sh3, __riscv_vreinterpret_u32##suffix1(w1), VTraits<_Tpvec>::vlanes()/2); \ + auto wid0 = __riscv_vwcvtu_x(v_trunc(vid0), VTraits<_Tpvec>::vlanes()/2); \ + auto wid1 = __riscv_vwcvtu_x(v_trunc(vid1), VTraits<_Tpvec>::vlanes()/2); \ + auto shwid1 = __riscv_vslide1up(__riscv_vreinterpret_u32##suffix2(wid1),0, VTraits<_Tpvec>::vlanes()); \ + auto vid = __riscv_vor(shwid1, __riscv_vreinterpret_u32##suffix2(wid0), VTraits<_Tpvec>::vlanes()); \ + auto vidx = __riscv_vmul(vid, sizeof(_Tp), VTraits<_Tpvec>::vlanes()); \ + return __riscv_vloxei32(tab, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int8, schar, m2, m4, m8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int16, short, m1 , m2, m4, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_int32, int, m1, m2, m2, __riscv_vlmul_trunc_u32m1) +OPENCV_HAL_IMPL_RVV_LUT_QUADS(v_float32, float, m1, m2, m2, __riscv_vlmul_trunc_u32m1) + +#define OPENCV_HAL_IMPL_RVV_LUT_VEC(_Tpvec, _Tp) \ +inline _Tpvec v_lut(const _Tp* tab, const v_int32& vidx) \ +{ \ + v_uint32 vidx_ = __riscv_vmul(__riscv_vreinterpret_u32m2(vidx), sizeof(_Tp), VTraits::vlanes()); \ + return __riscv_vloxei32(tab, vidx_, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_LUT_VEC(v_float32, float) +OPENCV_HAL_IMPL_RVV_LUT_VEC(v_int32, int) +OPENCV_HAL_IMPL_RVV_LUT_VEC(v_uint32, unsigned) + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_lut(const double* tab, const v_int32& vidx) \ +{ \ + vuint32m1_t vidx_ = __riscv_vmul(__riscv_vlmul_trunc_u32m1(__riscv_vreinterpret_u32m2(vidx)), sizeof(double), VTraits::vlanes()); \ + return __riscv_vloxei32(tab, vidx_, VTraits::vlanes()); \ +} +#endif + + +inline v_uint8 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((schar*)tab, idx)); } +inline v_uint8 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((schar*)tab, idx)); } +inline v_uint8 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((schar*)tab, idx)); } +inline v_uint16 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((short*)tab, idx)); } +inline v_uint16 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((short*)tab, idx)); } +inline v_uint16 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((short*)tab, idx)); } +inline v_uint32 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((int*)tab, idx)); } +inline v_uint32 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((int*)tab, idx)); } +inline v_uint32 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((int*)tab, idx)); } +inline v_uint64 v_lut(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64 v_lut_pairs(const uint64* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +////////////// Pack boolean //////////////////// +inline v_uint8 v_pack_b(const v_uint16& a, const v_uint16& b) +{ + return __riscv_vnsrl(__riscv_vset(__riscv_vlmul_ext_v_u16m2_u16m4(a),1,b), 0, VTraits::vlanes()); +} + +inline v_uint8 v_pack_b(const v_uint32& a, const v_uint32& b, + const v_uint32& c, const v_uint32& d) +{ + + return __riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u32m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()); +} + +inline v_uint8 v_pack_b(const v_uint64& a, const v_uint64& b, const v_uint64& c, + const v_uint64& d, const v_uint64& e, const v_uint64& f, + const v_uint64& g, const v_uint64& h) +{ + vuint8m1_t t0 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(a),1,b),2,c),3,d), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); + vuint8m1_t t1 = __riscv_vnsrl(__riscv_vnsrl(__riscv_vnsrl(__riscv_vset(__riscv_vset(__riscv_vset(__riscv_vlmul_ext_u64m8(e),1,f),2,g),3,h), 0, VTraits::vlanes()), 0, VTraits::vlanes()), 0, VTraits::vlanes()); + + return __riscv_vset(__riscv_vlmul_ext_u8m2(t0), 1, t1); +} + +////////////// Arithmetics ////////////// +#define OPENCV_HAL_IMPL_RVV_BIN_OP(_Tpvec, ocv_intrin, rvv_intrin) \ +inline _Tpvec v_##ocv_intrin(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return rvv_intrin(a, b, VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub, __riscv_vssubu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub, __riscv_vssub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub, __riscv_vssubu) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub, __riscv_vssub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, sub, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint32, mul, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, sub, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int32, mul, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, add, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, sub, __riscv_vfsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, mul, __riscv_vfmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float32, div, __riscv_vfdiv) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint64, sub, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, add, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int64, sub, __riscv_vsub) + +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, add, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, sub, __riscv_vfsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, mul, __riscv_vfmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_float64, div, __riscv_vfdiv) +#endif + +#define OPENCV_HAL_IMPL_RVV_BIN_MADD(_Tpvec, rvv_add) \ +template \ +inline _Tpvec v_add(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ + return v_add(rvv_add(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ +} +#define OPENCV_HAL_IMPL_RVV_BIN_MMUL(_Tpvec, rvv_mul) \ +template \ +inline _Tpvec v_mul(const _Tpvec& f1, const _Tpvec& f2, const Args&... vf) { \ + return v_mul(rvv_mul(f1, f2, VTraits<_Tpvec>::vlanes()), vf...); \ +} +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint8, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int8, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint16, __riscv_vsaddu) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int16, __riscv_vsadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint32, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int32, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float32, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_uint64, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_int64, __riscv_vadd) + +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_uint32, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_int32, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float32, __riscv_vfmul) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_BIN_MADD(v_float64, __riscv_vfadd) +OPENCV_HAL_IMPL_RVV_BIN_MMUL(v_float64, __riscv_vfmul) +#endif + +#define OPENCV_HAL_IMPL_RVV_MUL_EXPAND(_Tpvec, _Tpwvec, _TpwvecM2, suffix, wmul) \ +inline void v_mul_expand(const _Tpvec& a, const _Tpvec& b, _Tpwvec& c, _Tpwvec& d) \ +{ \ + _TpwvecM2 temp = wmul(a, b, VTraits<_Tpvec>::vlanes()); \ + c = __riscv_vget_##suffix##m2(temp, 0); \ + d = __riscv_vget_##suffix##m2(temp, 1); \ +} + +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint8, v_uint16, vuint16m4_t, u16, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int8, v_int16, vint16m4_t, i16, __riscv_vwmul) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint16, v_uint32, vuint32m4_t, u32, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_int16, v_int32, vint32m4_t, i32, __riscv_vwmul) +OPENCV_HAL_IMPL_RVV_MUL_EXPAND(v_uint32, v_uint64, vuint64m4_t, u64, __riscv_vwmulu) + +inline v_int16 v_mul_hi(const v_int16& a, const v_int16& b) +{ + return __riscv_vmulh(a, b, VTraits::vlanes()); +} +inline v_uint16 v_mul_hi(const v_uint16& a, const v_uint16& b) +{ + return __riscv_vmulhu(a, b, VTraits::vlanes()); +} + +////////////// Arithmetics (wrap)////////////// +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, add_wrap, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, sub_wrap, __riscv_vsub) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint8, mul_wrap, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int8, mul_wrap, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_uint16, mul_wrap, __riscv_vmul) +OPENCV_HAL_IMPL_RVV_BIN_OP(v_int16, mul_wrap, __riscv_vmul) + +//////// Saturating Multiply //////// +#define OPENCV_HAL_IMPL_RVV_MUL_SAT(_Tpvec, _clip, _wmul) \ +inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _clip(_wmul(a, b, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +template \ +inline _Tpvec v_mul(const _Tpvec& a1, const _Tpvec& a2, const Args&... va) { \ + return v_mul(_clip(_wmul(a1, a2, VTraits<_Tpvec>::vlanes()), 0, 0, VTraits<_Tpvec>::vlanes()), va...); \ +} + +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint8, __riscv_vnclipu, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int8, __riscv_vnclip, __riscv_vwmul) +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_uint16, __riscv_vnclipu, __riscv_vwmulu) +OPENCV_HAL_IMPL_RVV_MUL_SAT(v_int16, __riscv_vnclip, __riscv_vwmul) + +////////////// Bitwise logic ////////////// + +#define OPENCV_HAL_IMPL_RVV_LOGIC_OP(_Tpvec, vl) \ +inline _Tpvec v_and(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vand(a, b, vl); \ +} \ +inline _Tpvec v_or(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vor(a, b, vl); \ +} \ +inline _Tpvec v_xor(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vxor(a, b, vl); \ +} \ +inline _Tpvec v_not (const _Tpvec& a) \ +{ \ + return __riscv_vnot(a, vl); \ +} + +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_LOGIC_OP(v_int64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(intrin) \ +inline v_float32 intrin (const v_float32& a, const v_float32& b) \ +{ \ + return __riscv_vreinterpret_f32m2(intrin(__riscv_vreinterpret_i32m2(a), __riscv_vreinterpret_i32m2(b))); \ +} +OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_and) +OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_or) +OPENCV_HAL_IMPL_RVV_FLT_BIT_OP(v_xor) + +inline v_float32 v_not (const v_float32& a) \ +{ \ + return __riscv_vreinterpret_f32m2(v_not(__riscv_vreinterpret_i32m2(a))); \ +} + +#if CV_SIMD_SCALABLE_64F +#define OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(intrin) \ +inline v_float64 intrin (const v_float64& a, const v_float64& b) \ +{ \ + return __riscv_vreinterpret_f64m2(intrin(__riscv_vreinterpret_i64m2(a), __riscv_vreinterpret_i64m2(b))); \ +} +OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_and) +OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_or) +OPENCV_HAL_IMPL_RVV_FLT64_BIT_OP(v_xor) + +inline v_float64 v_not (const v_float64& a) \ +{ \ + return __riscv_vreinterpret_f64m2(v_not(__riscv_vreinterpret_i64m2(a))); \ +} +#endif + + +////////////// Bitwise shifts ////////////// +/* Usage +1. v_shl(vec); +2. v_shl(vec, N); // instead of vec << N, when N is non-constant. +*/ + +#define OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(_Tpvec, vl) \ +template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ +} \ +template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsrl(a, uint8_t(n), vl)); \ +} + +#define OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(_Tpvec, vl) \ +template inline _Tpvec v_shl(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsll(a, uint8_t(n), vl)); \ +} \ +template inline _Tpvec v_shr(const _Tpvec& a, int n = s) \ +{ \ + return _Tpvec(__riscv_vsra(a, uint8_t(n), vl)); \ +} + +OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_UNSIGNED_SHIFT_OP(v_uint64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SIGNED_SHIFT_OP(v_int64, VTraits::vlanes()) + +////////////// Comparison ////////////// +#define OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, op, intrin, suffix) \ +inline _Tpvec v_##op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + size_t VLEN = VTraits<_Tpvec>::vlanes(); \ + uint64_t ones = -1; \ + return __riscv_vmerge(__riscv_vmv_v_x_##suffix##m2(0, VLEN), ones, intrin(a, b, VLEN), VLEN); \ +} + +#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, op, intrin, suffix) \ +inline _Tpvec v_##op (const _Tpvec& a, const _Tpvec& b) \ +{ \ + size_t VLEN = VTraits<_Tpvec>::vlanes(); \ + union { uint64_t u; VTraits<_Tpvec>::lane_type d; } ones; \ + ones.u = -1; \ + auto diff = intrin(a, b, VLEN); \ + auto z = __riscv_vfmv_v_f_##suffix##m2(0, VLEN); \ + auto res = __riscv_vfmerge(z, ones.d, diff, VLEN); \ + return _Tpvec(res); \ +} //TODO + +#define OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(_Tpvec, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmsltu, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgtu, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsleu, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsgeu, suffix) + +#define OPENCV_HAL_IMPL_RVV_SIGNED_CMP(_Tpvec, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, eq, __riscv_vmseq, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ne, __riscv_vmsne, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, lt, __riscv_vmslt, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, gt, __riscv_vmsgt, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, le, __riscv_vmsle, suffix) \ +OPENCV_HAL_IMPL_RVV_INT_CMP_OP(_Tpvec, ge, __riscv_vmsge, suffix) + +#define OPENCV_HAL_IMPL_RVV_FLOAT_CMP(_Tpvec, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, eq, __riscv_vmfeq, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ne, __riscv_vmfne, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, lt, __riscv_vmflt, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, gt, __riscv_vmfgt, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, le, __riscv_vmfle, suffix) \ +OPENCV_HAL_IMPL_RVV_FLOAT_CMP_OP(_Tpvec, ge, __riscv_vmfge, suffix) + + +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint8, u8) +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint16, u16) +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint32, u32) +OPENCV_HAL_IMPL_RVV_UNSIGNED_CMP(v_uint64, u64) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int8, i8) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int16, i16) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int32, i32) +OPENCV_HAL_IMPL_RVV_SIGNED_CMP(v_int64, i64) +OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float32, f32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_FLOAT_CMP(v_float64, f64) +#endif + +inline v_float32 v_not_nan(const v_float32& a) +{ return v_eq(a, a); } + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_not_nan(const v_float64& a) +{ return v_eq(a, a); } +#endif + +////////////// Min/Max ////////////// + +#define OPENCV_HAL_IMPL_RVV_BIN_FUNC(_Tpvec, func, intrin, vl) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return intrin(a, b, vl); \ +} + +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_min, __riscv_vminu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint8, v_max, __riscv_vmaxu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_min, __riscv_vmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int8, v_max, __riscv_vmax, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_min, __riscv_vminu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint16, v_max, __riscv_vmaxu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_min, __riscv_vmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int16, v_max, __riscv_vmax, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_min, __riscv_vminu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_uint32, v_max, __riscv_vmaxu, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_min, __riscv_vmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_int32, v_max, __riscv_vmax, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_min, __riscv_vfmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float32, v_max, __riscv_vfmax, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_min, __riscv_vfmin, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_BIN_FUNC(v_float64, v_max, __riscv_vfmax, VTraits::vlanes()) +#endif + +////////////// Transpose4x4 ////////////// +#define OPENCV_HAL_IMPL_RVV_ZIP4(_Tpvec, _wTpvec, suffix, convert2u, convert) \ +inline void v_zip4(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ + int vl = 4; \ + _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2u( \ + __riscv_vor(__riscv_vzext_vf2(convert(a0), vl), \ + __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(convert(a1), vl)), 0, vl*2)), \ + vl))); \ + b0 = __riscv_vget_##suffix##m2(temp, 0); \ + b1 = __riscv_vget_##suffix##m2(__riscv_vrgather(temp, __riscv_vadd(__riscv_vid_v_u32m4(vl), 4, vl)/*{4,5,6,7} */, vl) ,0); \ +} + +OPENCV_HAL_IMPL_RVV_ZIP4(v_uint32, vuint32m4_t, u32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP4(v_int32, vint32m4_t, i32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) +OPENCV_HAL_IMPL_RVV_ZIP4(v_float32, vfloat32m4_t, f32, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) + + +#define OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, const _Tpvec& a2, const _Tpvec& a3, _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) { \ + _Tpvec t0,t1,t2,t3; \ + v_zip4(a0, a2, t0, t2); \ + v_zip4(a1, a3, t1, t3); \ + v_zip4(t0, t1, b0, b1); \ + v_zip4(t2, t3, b2, b3); \ +} + +OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_uint32, u32) +OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_int32, i32) +OPENCV_HAL_IMPL_RVV_TRANSPOSE4x4(v_float32, f32) + +////////////// Reduce ////////////// + +#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl, red) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + _nwTpvec zero = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ + _nwTpvec res = __riscv_vmv_v_x_##wsuffix##m1(0, vl); \ + res = __riscv_v##red(a, zero, vl); \ + return (scalartype)__riscv_vmv_x(res); \ +} +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint8, v_uint16, vuint16m1_t, unsigned, u16, VTraits::vlanes(), wredsumu) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int8, v_int16, vint16m1_t, int, i16, VTraits::vlanes(), wredsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint16, v_uint32, vuint32m1_t, unsigned, u32, VTraits::vlanes(), wredsumu) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int16, v_int32, vint32m1_t, int, i32, VTraits::vlanes(), wredsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint32, v_uint64, vuint64m1_t, unsigned, u64, VTraits::vlanes(), wredsumu) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int32, v_int64, vint64m1_t, int, i64, VTraits::vlanes(), wredsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_uint64, v_uint64, vuint64m1_t, uint64, u64, VTraits::vlanes(), redsum) +OPENCV_HAL_IMPL_RVV_REDUCE_SUM(v_int64, v_int64, vint64m1_t, int64, i64, VTraits::vlanes(), redsum) + + +#define OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(_Tpvec, _wTpvec, _nwTpvec, scalartype, wsuffix, vl) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + _nwTpvec zero = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ + _nwTpvec res = __riscv_vfmv_v_f_##wsuffix##m1(0, vl); \ + res = __riscv_vfredusum(a, zero, vl); \ + return (scalartype)__riscv_vfmv_f(res); \ +} +OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float32, v_float32, vfloat32m1_t, float, f32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_REDUCE_SUM_FP(v_float64, v_float64, vfloat64m1_t, float, f64, VTraits::vlanes()) +#endif + +#define OPENCV_HAL_IMPL_RVV_REDUCE(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ + return (scalartype)__riscv_vmv_x(__riscv_v##red(a, narrowM1, vl)); \ +} + +#define OPENCV_HAL_IMPL_RVV_REDUCE_FP(_Tpvec, _nTpvec, func, scalartype, suffix, vl, red) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + _nTpvec narrowM1 = __riscv_vlmul_trunc_##suffix##m1(a); \ + return (scalartype)__riscv_vfmv_f(__riscv_v##red(a, narrowM1, vl)); \ +} + +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, min, uchar, u8, VTraits::vlanes(), redminu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, min, schar, i8, VTraits::vlanes(), redmin) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, min, ushort, u16, VTraits::vlanes(), redminu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, min, short, i16, VTraits::vlanes(), redmin) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, min, unsigned, u32, VTraits::vlanes(), redminu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, min, int, i32, VTraits::vlanes(), redmin) +OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, min, float, f32, VTraits::vlanes(), fredmin) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint8, vuint8m1_t, max, uchar, u8, VTraits::vlanes(), redmaxu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int8, vint8m1_t, max, schar, i8, VTraits::vlanes(), redmax) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint16, vuint16m1_t, max, ushort, u16, VTraits::vlanes(), redmaxu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int16, vint16m1_t, max, short, i16, VTraits::vlanes(), redmax) +OPENCV_HAL_IMPL_RVV_REDUCE(v_uint32, vuint32m1_t, max, unsigned, u32, VTraits::vlanes(), redmaxu) +OPENCV_HAL_IMPL_RVV_REDUCE(v_int32, vint32m1_t, max, int, i32, VTraits::vlanes(), redmax) +OPENCV_HAL_IMPL_RVV_REDUCE_FP(v_float32, vfloat32m1_t, max, float, f32, VTraits::vlanes(), fredmax) + +inline v_float32 v_reduce_sum4(const v_float32& a, const v_float32& b, + const v_float32& c, const v_float32& d) +{ + // 0000 1111 2222 3333 .... + vuint64m4_t vid1 = __riscv_vid_v_u64m4(VTraits::vlanes()); + vuint16m4_t t1 = __riscv_vreinterpret_u16m4(vid1); + vuint16m4_t t2 = __riscv_vslide1up(t1, 0, VTraits::vlanes()); + vuint16m4_t t3 = __riscv_vslide1up(t2, 0, VTraits::vlanes()); + vuint16m4_t t4 = __riscv_vslide1up(t3, 0, VTraits::vlanes()); + t1 = __riscv_vor( + __riscv_vor(t1, t2, VTraits::vlanes()), + __riscv_vor(t3, t4, VTraits::vlanes()), + VTraits::vlanes() + ); + + // index for transpose4X4 + vuint16m4_t vidx0 = __riscv_vmul(t1, 12, VTraits::vlanes()); + vidx0 = __riscv_vadd(vidx0, __riscv_vid_v_u16m4(VTraits::vlanes()), VTraits::vlanes()); + vuint16m4_t vidx1 = __riscv_vadd(vidx0, 4, VTraits::vlanes()); + vuint16m4_t vidx2 = __riscv_vadd(vidx0, 8, VTraits::vlanes()); + vuint16m4_t vidx3 = __riscv_vadd(vidx0, 12, VTraits::vlanes()); + + // zip + vuint32m4_t tempA = __riscv_vreinterpret_u32m4( \ + __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(a), VTraits::vlanes()), \ + __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(c), VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes())); \ + vuint32m4_t tempB = __riscv_vreinterpret_u32m4( \ + __riscv_vor(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(b), VTraits::vlanes()), \ + __riscv_vreinterpret_u64m4(__riscv_vslide1up(__riscv_vreinterpret_u32m4(__riscv_vzext_vf2(__riscv_vreinterpret_u32m2(d), VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes())); \ + vfloat32m8_t temp = __riscv_vreinterpret_f32m8(__riscv_vreinterpret_u32m8( \ + __riscv_vor(__riscv_vzext_vf2(tempA, VTraits::vlanes()), \ + __riscv_vreinterpret_u64m8(__riscv_vslide1up(__riscv_vreinterpret_u32m8(__riscv_vzext_vf2(tempB, VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes()))); + + // transpose + vfloat32m2_t b0 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx0, VTraits::vlanes())); + vfloat32m2_t b1 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx1, VTraits::vlanes())); + vfloat32m2_t b2 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx2, VTraits::vlanes())); + vfloat32m2_t b3 = __riscv_vlmul_trunc_f32m2(__riscv_vrgatherei16(temp, vidx3, VTraits::vlanes())); + + // vector add + v_float32 res = __riscv_vfadd( + __riscv_vfadd(b0, b1, VTraits::vlanes()), + __riscv_vfadd(b2, b3, VTraits::vlanes()), + VTraits::vlanes() + ); + return res; +} + +////////////// Square-Root ////////////// + +inline v_float32 v_sqrt(const v_float32& x) +{ + return __riscv_vfsqrt(x, VTraits::vlanes()); +} + +inline v_float32 v_invsqrt(const v_float32& x) +{ + v_float32 one = v_setall_f32(1.0f); + return v_div(one, v_sqrt(x)); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_sqrt(const v_float64& x) +{ + return __riscv_vfsqrt(x, VTraits::vlanes()); +} + +inline v_float64 v_invsqrt(const v_float64& x) +{ + v_float64 one = v_setall_f64(1.0f); + return v_div(one, v_sqrt(x)); +} +#endif + +inline v_float32 v_magnitude(const v_float32& a, const v_float32& b) +{ + v_float32 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); + return v_sqrt(x); +} + +inline v_float32 v_sqr_magnitude(const v_float32& a, const v_float32& b) +{ + return v_float32(__riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes())); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_magnitude(const v_float64& a, const v_float64& b) +{ + v_float64 x = __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); + return v_sqrt(x); +} + +inline v_float64 v_sqr_magnitude(const v_float64& a, const v_float64& b) +{ + return __riscv_vfmacc(__riscv_vfmul(a, a, VTraits::vlanes()), b, b, VTraits::vlanes()); +} +#endif + +////////////// Multiply-Add ////////////// + +inline v_float32 v_fma(const v_float32& a, const v_float32& b, const v_float32& c) +{ + return __riscv_vfmacc(c, a, b, VTraits::vlanes()); +} +inline v_int32 v_fma(const v_int32& a, const v_int32& b, const v_int32& c) +{ + return __riscv_vmacc(c, a, b, VTraits::vlanes()); +} + +inline v_float32 v_muladd(const v_float32& a, const v_float32& b, const v_float32& c) +{ + return v_fma(a, b, c); +} + +inline v_int32 v_muladd(const v_int32& a, const v_int32& b, const v_int32& c) +{ + return v_fma(a, b, c); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_fma(const v_float64& a, const v_float64& b, const v_float64& c) +{ + return __riscv_vfmacc_vv_f64m2(c, a, b, VTraits::vlanes()); +} + +inline v_float64 v_muladd(const v_float64& a, const v_float64& b, const v_float64& c) +{ + return v_fma(a, b, c); +} +#endif + +////////////// Check all/any ////////////// + +#define OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(_Tpvec, vl) \ +inline bool v_check_all(const _Tpvec& a) \ +{ \ + return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) == vl; \ +} \ +inline bool v_check_any(const _Tpvec& a) \ +{ \ + return (int)__riscv_vcpop(__riscv_vmslt(a, 0, vl), vl) != 0; \ +} + +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_CHECK_ALLANY(v_int64, VTraits::vlanes()) + + +inline bool v_check_all(const v_uint8& a) +{ return v_check_all(v_reinterpret_as_s8(a)); } +inline bool v_check_any(const v_uint8& a) +{ return v_check_any(v_reinterpret_as_s8(a)); } + +inline bool v_check_all(const v_uint16& a) +{ return v_check_all(v_reinterpret_as_s16(a)); } +inline bool v_check_any(const v_uint16& a) +{ return v_check_any(v_reinterpret_as_s16(a)); } + +inline bool v_check_all(const v_uint32& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_uint32& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } + +inline bool v_check_all(const v_float32& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_float32& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } + +inline bool v_check_all(const v_uint64& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_uint64& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } + +#if CV_SIMD_SCALABLE_64F +inline bool v_check_all(const v_float64& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_float64& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } +#endif + +////////////// abs ////////////// + +#define OPENCV_HAL_IMPL_RVV_ABSDIFF(_Tpvec, abs) \ +inline _Tpvec v_##abs(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return v_sub(v_max(a, b), v_min(a, b)); \ +} + +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint8, absdiff) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint16, absdiff) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_uint32, absdiff) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float32, absdiff) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_float64, absdiff) +#endif +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int8, absdiffs) +OPENCV_HAL_IMPL_RVV_ABSDIFF(v_int16, absdiffs) + +#define OPENCV_HAL_IMPL_RVV_ABSDIFF_S(_Tpvec, _rTpvec, width) \ +inline _rTpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vnclipu(__riscv_vreinterpret_u##width##m4(__riscv_vwsub_vv(v_max(a, b), v_min(a, b), VTraits<_Tpvec>::vlanes())), 0, 0, VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int8, v_uint8, 16) +OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int16, v_uint16, 32) +OPENCV_HAL_IMPL_RVV_ABSDIFF_S(v_int32, v_uint32, 64) + +#define OPENCV_HAL_IMPL_RVV_ABS(_Tprvec, _Tpvec, suffix) \ +inline _Tprvec v_abs(const _Tpvec& a) \ +{ \ + return v_absdiff(a, v_setzero_##suffix()); \ +} + +OPENCV_HAL_IMPL_RVV_ABS(v_uint8, v_int8, s8) +OPENCV_HAL_IMPL_RVV_ABS(v_uint16, v_int16, s16) +OPENCV_HAL_IMPL_RVV_ABS(v_uint32, v_int32, s32) +OPENCV_HAL_IMPL_RVV_ABS(v_float32, v_float32, f32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_ABS(v_float64, v_float64, f64) +#endif + + +#define OPENCV_HAL_IMPL_RVV_REDUCE_SAD(_Tpvec, scalartype) \ +inline scalartype v_reduce_sad(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return v_reduce_sum(v_absdiff(a, b)); \ +} + +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint8, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int8, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint16, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int16, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_uint32, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_int32, unsigned) +OPENCV_HAL_IMPL_RVV_REDUCE_SAD(v_float32, float) + +////////////// Select ////////////// + +#define OPENCV_HAL_IMPL_RVV_SELECT(_Tpvec, vl) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vmerge(b, a, __riscv_vmsne(mask, 0, vl), vl); \ +} + +OPENCV_HAL_IMPL_RVV_SELECT(v_uint8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_uint16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_uint32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_int8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_int16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_SELECT(v_int32, VTraits::vlanes()) + +inline v_float32 v_select(const v_float32& mask, const v_float32& a, const v_float32& b) \ +{ \ + return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ +} + +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_select(const v_float64& mask, const v_float64& a, const v_float64& b) \ +{ \ + return __riscv_vmerge(b, a, __riscv_vmfne(mask, 0, VTraits::vlanes()), VTraits::vlanes()); \ +} +#endif + +////////////// Rotate shift ////////////// + +#define OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(_Tpvec, suffix, vl) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + return __riscv_vslidedown(a, n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + return __riscv_vslideup(__riscv_vmv_v_x_##suffix##m2(0, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ CV_UNUSED(b); return a; } + +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint8, u8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int8, i8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint16, u16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int16, i16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint32, u32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int32, i32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_uint64, u64, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_ROTATE_INTEGER(v_int64, i64, VTraits::vlanes()) + +#define OPENCV_HAL_IMPL_RVV_ROTATE_FP(_Tpvec, suffix, vl) \ +template inline _Tpvec v_rotate_right(const _Tpvec& a) \ +{ \ + return __riscv_vslidedown(a, n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a) \ +{ \ + return __riscv_vslideup(__riscv_vfmv_v_f_##suffix##m2(0, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a) \ +{ return a; } \ +template inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(a, n, vl), b, VTraits<_Tpvec>::vlanes() - n, vl); \ +} \ +template inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(__riscv_vslidedown(b, VTraits<_Tpvec>::vlanes() - n, vl), a, n, vl); \ +} \ +template<> inline _Tpvec v_rotate_left<0>(const _Tpvec& a, const _Tpvec& b) \ +{ CV_UNUSED(b); return a; } + +OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float32, f32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_ROTATE_FP(v_float64, f64, VTraits::vlanes()) +#endif + +////////////// Convert to float ////////////// +inline v_float32 v_cvt_f32(const v_int32& a) +{ + return __riscv_vfcvt_f_x_v_f32m2(a, VTraits::vlanes()); +} + +#if CV_SIMD_SCALABLE_64F +inline v_float32 v_cvt_f32(const v_float64& a) +{ + return __riscv_vfncvt_f(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); +} + +inline v_float32 v_cvt_f32(const v_float64& a, const v_float64& b) +{ + return __riscv_vfncvt_f(__riscv_vset(__riscv_vlmul_ext_f64m4(a),1,b), VTraits::vlanes()); +} + +inline v_float64 v_cvt_f64(const v_int32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); +} + +inline v_float64 v_cvt_f64_high(const v_int32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); +} + +inline v_float64 v_cvt_f64(const v_float32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 0); +} + +inline v_float64 v_cvt_f64_high(const v_float32& a) +{ + return __riscv_vget_f64m2(__riscv_vfwcvt_f(a, VTraits::vlanes()), 1); +} + +inline v_float64 v_cvt_f64(const v_int64& a) +{ + return __riscv_vfcvt_f(a, VTraits::vlanes()); +} +#endif + +//////////// Broadcast ////////////// + +#define OPENCV_HAL_IMPL_RVV_BROADCAST(_Tpvec, suffix) \ +template inline _Tpvec v_broadcast_element(_Tpvec v, int i = s) \ +{ \ + return v_setall_##suffix(v_extract_n(v, i)); \ +} \ +inline _Tpvec v_broadcast_highest(_Tpvec v) \ +{ \ + return v_setall_##suffix(v_extract_n(v, VTraits<_Tpvec>::vlanes()-1)); \ +} + +OPENCV_HAL_IMPL_RVV_BROADCAST(v_uint32, u32) +OPENCV_HAL_IMPL_RVV_BROADCAST(v_int32, s32) +OPENCV_HAL_IMPL_RVV_BROADCAST(v_float32, f32) + + +////////////// Reverse ////////////// +#define OPENCV_HAL_IMPL_RVV_REVERSE(_Tpvec, width) \ +inline _Tpvec v_reverse(const _Tpvec& a) \ +{ \ + vuint##width##m2_t vidx = __riscv_vrsub(__riscv_vid_v_u##width##m2(VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()-1, VTraits<_Tpvec>::vlanes()); \ + return __riscv_vrgather(a, vidx, VTraits<_Tpvec>::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint8, 8) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int8, 8) +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint16, 16) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int16, 16) +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint32, 32) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int32, 32) +OPENCV_HAL_IMPL_RVV_REVERSE(v_float32, 32) +OPENCV_HAL_IMPL_RVV_REVERSE(v_uint64, 64) +OPENCV_HAL_IMPL_RVV_REVERSE(v_int64, 64) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_REVERSE(v_float64, 64) +#endif + +//////////// Value reordering //////////// + +#define OPENCV_HAL_IMPL_RVV_EXPAND(_Tp, _Tpwvec, _Tpwvec_m2, _Tpvec, width, suffix, suffix2, cvt) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ + b0 = __riscv_vget_##suffix##m2(temp, 0); \ + b1 = __riscv_vget_##suffix##m2(temp, 1); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ \ + _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ + return __riscv_vget_##suffix##m2(temp, 0); \ +} \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ \ + _Tpwvec_m2 temp = cvt(a, VTraits<_Tpvec>::vlanes()); \ + return __riscv_vget_##suffix##m2(temp, 1); \ +} \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + return cvt(__riscv_vle##width##_v_##suffix2##m1(ptr, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_EXPAND(uchar, v_uint16, vuint16m4_t, v_uint8, 8, u16, u8, __riscv_vwcvtu_x) +OPENCV_HAL_IMPL_RVV_EXPAND(schar, v_int16, vint16m4_t, v_int8, 8, i16, i8, __riscv_vwcvt_x) +OPENCV_HAL_IMPL_RVV_EXPAND(ushort, v_uint32, vuint32m4_t, v_uint16, 16, u32, u16, __riscv_vwcvtu_x) +OPENCV_HAL_IMPL_RVV_EXPAND(short, v_int32, vint32m4_t, v_int16, 16, i32, i16, __riscv_vwcvt_x) +OPENCV_HAL_IMPL_RVV_EXPAND(uint, v_uint64, vuint64m4_t, v_uint32, 32, u64, u32, __riscv_vwcvtu_x) +OPENCV_HAL_IMPL_RVV_EXPAND(int, v_int64, vint64m4_t, v_int32, 32, i64, i32, __riscv_vwcvt_x) + +inline v_uint32 v_load_expand_q(const uchar* ptr) +{ + return __riscv_vwcvtu_x(__riscv_vwcvtu_x(__riscv_vle8_v_u8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); +} + +inline v_int32 v_load_expand_q(const schar* ptr) +{ + return __riscv_vwcvt_x(__riscv_vwcvt_x(__riscv_vle8_v_i8mf2(ptr, VTraits::vlanes()), VTraits::vlanes()), VTraits::vlanes()); +} + +#define OPENCV_HAL_IMPL_RVV_PACK(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ +inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ +{ \ + return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} \ +template inline \ +_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ +{ \ + return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +template inline \ +void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} + +#define OPENCV_HAL_IMPL_RVV_PACK_32(_Tpvec, _Tp, _wTpvec, hwidth, hsuffix, suffix, rshr, shr) \ +inline _Tpvec v_pack(const _wTpvec& a, const _wTpvec& b) \ +{ \ + return shr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, VTraits<_Tpvec>::vlanes()); \ +} \ +inline void v_pack_store(_Tp* ptr, const _wTpvec& a) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, shr(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} \ +template inline \ +_Tpvec v_rshr_pack(const _wTpvec& a, const _wTpvec& b, int N = n) \ +{ \ + return rshr(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), N, 0, VTraits<_Tpvec>::vlanes()); \ +} \ +template inline \ +void v_rshr_pack_store(_Tp* ptr, const _wTpvec& a, int N = n) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, rshr(a, N, 0, VTraits<_Tpvec>::vlanes()), VTraits<_wTpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_PACK(v_uint8, uchar, v_uint16, 8, u8, u16, __riscv_vnclipu, __riscv_vnclipu) +OPENCV_HAL_IMPL_RVV_PACK(v_int8, schar, v_int16, 8, i8, i16, __riscv_vnclip, __riscv_vnclip) +OPENCV_HAL_IMPL_RVV_PACK(v_uint16, ushort, v_uint32, 16, u16, u32, __riscv_vnclipu, __riscv_vnclipu) +OPENCV_HAL_IMPL_RVV_PACK(v_int16, short, v_int32, 16, i16, i32, __riscv_vnclip, __riscv_vnclip) +OPENCV_HAL_IMPL_RVV_PACK_32(v_uint32, unsigned, v_uint64, 32, u32, u64, __riscv_vnclipu, __riscv_vnsrl) +OPENCV_HAL_IMPL_RVV_PACK_32(v_int32, int, v_int64, 32, i32, i64, __riscv_vnclip, __riscv_vnsra) + +#define OPENCV_HAL_IMPL_RVV_PACK_U(_Tpvec, _Tp, _wTpvec, _wTp, hwidth, width, hsuffix, suffix, cast, hvl, vl) \ +inline _Tpvec v_pack_u(const _wTpvec& a, const _wTpvec& b) \ +{ \ + return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), 0, 0, vl); \ +} \ +inline void v_pack_u_store(_Tp* ptr, const _wTpvec& a) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), 0, 0, vl), hvl); \ +} \ +template inline \ +_Tpvec v_rshr_pack_u(const _wTpvec& a, const _wTpvec& b, int n = N) \ +{ \ + return __riscv_vnclipu(cast(__riscv_vmax(__riscv_vset(__riscv_vlmul_ext_##suffix##m4(a), 1, b), 0, vl)), n, 0, vl); \ +} \ +template inline \ +void v_rshr_pack_u_store(_Tp* ptr, const _wTpvec& a, int n = N) \ +{ \ + __riscv_vse##hwidth##_v_##hsuffix##m1(ptr, __riscv_vnclipu(__riscv_vreinterpret_u##width##m2(__riscv_vmax(a, 0, vl)), n, 0, vl), hvl); \ +} + +OPENCV_HAL_IMPL_RVV_PACK_U(v_uint8, uchar, v_int16, short, 8, 16, u8, i16, __riscv_vreinterpret_v_i16m4_u16m4, VTraits::vlanes(), VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_PACK_U(v_uint16, ushort, v_int32, int, 16, 32, u16, i32, __riscv_vreinterpret_v_i32m4_u32m4, VTraits::vlanes(), VTraits::vlanes()) + + +/* void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) + a0 = {A1 A2 A3 A4} + a1 = {B1 B2 B3 B4} +--------------- + {A1 B1 A2 B2} and {A3 B3 A4 B4} +*/ + +#define OPENCV_HAL_IMPL_RVV_ZIP(_Tpvec, _wTpvec, suffix, width, width2, convert2um2, convert2um1) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) { \ + _wTpvec temp = __riscv_vreinterpret_##suffix##m4(convert2um2( \ + __riscv_vor(__riscv_vzext_vf2(convert2um1(a0), VTraits<_Tpvec>::vlanes()*2), \ + __riscv_vreinterpret_u##width2##m4(__riscv_vslide1up(__riscv_vreinterpret_u##width##m4(__riscv_vzext_vf2(convert2um1(a1), VTraits<_Tpvec>::vlanes()*2)), 0, VTraits<_Tpvec>::vlanes()*2)), \ + VTraits<_Tpvec>::vlanes()))); \ + b0 = __riscv_vget_##suffix##m2(temp, 0); \ + b1 = __riscv_vget_##suffix##m2(temp, 1); \ +} +OPENCV_HAL_IMPL_RVV_ZIP(v_uint8, vuint8m4_t, u8, 8, 16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP(v_int8, vint8m4_t, i8, 8, 16, __riscv_vreinterpret_u8m4, __riscv_vreinterpret_u8m2) +OPENCV_HAL_IMPL_RVV_ZIP(v_uint16, vuint16m4_t, u16, 16, 32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP(v_int16, vint16m4_t, i16, 16, 32, __riscv_vreinterpret_u16m4, __riscv_vreinterpret_u16m2) +OPENCV_HAL_IMPL_RVV_ZIP(v_uint32, vuint32m4_t, u32, 32, 64, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_ZIP(v_int32, vint32m4_t, i32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) +OPENCV_HAL_IMPL_RVV_ZIP(v_float32, vfloat32m4_t, f32, 32, 64, __riscv_vreinterpret_u32m4, __riscv_vreinterpret_u32m2) + +#if CV_SIMD_SCALABLE_64F +inline void v_zip(const v_float64& a0, const v_float64& a1, v_float64& b0, v_float64& b1) { \ + vuint16mf2_t idx0 = __riscv_vid_v_u16mf2(VTraits::vlanes()); + vuint16mf2_t idx1 = __riscv_vadd(idx0, VTraits::vlanes(), VTraits::vlanes()); + vuint16m1_t idx = __riscv_vreinterpret_u16m1(( \ + __riscv_vor(__riscv_vzext_vf2(idx0, VTraits::vlanes()), \ + __riscv_vreinterpret_u32m1(__riscv_vslide1up(__riscv_vreinterpret_u16m1(__riscv_vzext_vf2(idx1, VTraits::vlanes())), 0, VTraits::vlanes())), \ + VTraits::vlanes()))); +#if 0 + vfloat64m4_t temp = __riscv_vcreate_v_f64m2_f64m4(a0, a1); +#else // TODO: clean up when RVV Intrinsic is frozen. + vfloat64m4_t temp = __riscv_vlmul_ext_f64m4(a0); + temp = __riscv_vset(temp, 1, a1); +#endif + temp = __riscv_vrgatherei16(temp, idx, VTraits::vlanes()*2); + b0 = __riscv_vget_f64m2(temp, 0); \ + b1 = __riscv_vget_f64m2(temp, 1); \ +} +#endif + +#define OPENCV_HAL_IMPL_RVV_UNPACKS(_Tpvec, width) \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup(a, b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes());\ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return __riscv_vslideup( \ + __riscv_vslidedown(a, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ + __riscv_vslidedown(b, VTraits<_Tpvec>::vlanes()/2, VTraits<_Tpvec>::vlanes()), \ + VTraits<_Tpvec>::vlanes()/2, \ + VTraits<_Tpvec>::vlanes()); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + c = v_combine_low(a, b); \ + d = v_combine_high(a, b); \ +} + +OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint8, 8) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_int8, 8) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint16, 16) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_int16, 16) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_uint32, 32) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_int32, 32) +OPENCV_HAL_IMPL_RVV_UNPACKS(v_float32, 32) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_UNPACKS(v_float64, 64) +#endif + +#define OPENCV_HAL_IMPL_RVV_INTERLEAVED(_Tpvec, _Tp, suffix, width, hwidth, vl) \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b) \ +{ \ + a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*2, VTraits::vlanes()); \ + b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*2, VTraits::vlanes()); \ +}\ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, v_##_Tpvec& c) \ +{ \ + a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*3, VTraits::vlanes()); \ + b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*3, VTraits::vlanes()); \ + c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*3, VTraits::vlanes()); \ +} \ +inline void v_load_deinterleave(const _Tp* ptr, v_##_Tpvec& a, v_##_Tpvec& b, \ + v_##_Tpvec& c, v_##_Tpvec& d) \ +{ \ + \ + a = __riscv_vlse##width##_v_##suffix##m2(ptr , sizeof(_Tp)*4, VTraits::vlanes()); \ + b = __riscv_vlse##width##_v_##suffix##m2(ptr+1, sizeof(_Tp)*4, VTraits::vlanes()); \ + c = __riscv_vlse##width##_v_##suffix##m2(ptr+2, sizeof(_Tp)*4, VTraits::vlanes()); \ + d = __riscv_vlse##width##_v_##suffix##m2(ptr+3, sizeof(_Tp)*4, VTraits::vlanes()); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + __riscv_vsse##width(ptr, sizeof(_Tp)*2, a, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+1, sizeof(_Tp)*2, b, VTraits::vlanes()); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ \ + __riscv_vsse##width(ptr, sizeof(_Tp)*3, a, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+1, sizeof(_Tp)*3, b, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+2, sizeof(_Tp)*3, c, VTraits::vlanes()); \ +} \ +inline void v_store_interleave( _Tp* ptr, const v_##_Tpvec& a, const v_##_Tpvec& b, \ + const v_##_Tpvec& c, const v_##_Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED ) \ +{ \ + __riscv_vsse##width(ptr, sizeof(_Tp)*4, a, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+1, sizeof(_Tp)*4, b, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+2, sizeof(_Tp)*4, c, VTraits::vlanes()); \ + __riscv_vsse##width(ptr+3, sizeof(_Tp)*4, d, VTraits::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint8, uchar, u8, 8, 4, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int8, schar, i8, 8, 4, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint16, ushort, u16, 16, 8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int16, short, i16, 16, 8, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint32, unsigned, u32, 32, 16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int32, int, i32, 32, 16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(float32, float, f32, 32, 16, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(uint64, uint64, u64, 64, 32, VTraits::vlanes()) +OPENCV_HAL_IMPL_RVV_INTERLEAVED(int64, int64, i64, 64, 32, VTraits::vlanes()) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_INTERLEAVED(float64, double, f64, 64, 32, VTraits::vlanes()) +#endif + +static uint64_t idx_interleave_pairs[] = { \ + 0x0705060403010200, 0x0f0d0e0c0b090a08, 0x1715161413111210, 0x1f1d1e1c1b191a18, \ + 0x2725262423212220, 0x2f2d2e2c2b292a28, 0x3735363433313230, 0x3f3d3e3c3b393a38, \ + 0x4745464443414240, 0x4f4d4e4c4b494a48, 0x5755565453515250, 0x5f5d5e5c5b595a58, \ + 0x6765666463616260, 0x6f6d6e6c6b696a68, 0x7775767473717270, 0x7f7d7e7c7b797a78}; + +static uint64_t idx_interleave_quads[] = { \ + 0x0703060205010400, 0x0f0b0e0a0d090c08, 0x1713161215111410, 0x1f1b1e1a1d191c18, \ + 0x2723262225212420, 0x2f2b2e2a2d292c28, 0x3733363235313430, 0x3f3b3e3a3d393c38, \ + 0x4743464245414440, 0x4f4b4e4a4d494c48, 0x5753565255515450, 0x5f5b5e5a5d595c58, \ + 0x6763666265616460, 0x6f6b6e6a6d696c68, 0x7773767275717470, 0x7f7b7e7a7d797c78}; + +#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(_Tpvec, func) \ +inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ + CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ + vuint8m2_t vidx = __riscv_vundefined_u8m2();\ + vidx = __riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)); \ + return __riscv_vrgather(vec, vidx, VTraits::vlanes()); \ +} +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_uint8, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ_NOEXPEND(v_int8, quads) + +#define OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(_Tpvec, width, vzext_vfx, func) \ +inline _Tpvec v_interleave_##func(const _Tpvec& vec) { \ + CV_CheckLE(VTraits<_Tpvec>::vlanes(), VTraits<_Tpvec>::max_nlanes, "RVV implementation only supports VLEN in the range [128, 1024]"); \ + vuint##width##m2_t vidx = __riscv_vundefined_u##width##m2();\ + vidx = __riscv_vget_u##width##m2(vzext_vfx(__riscv_vreinterpret_u8m2(__riscv_vle64_v_u64m2(idx_interleave_##func, 16)), VTraits::vlanes()), 0); \ + return __riscv_vrgather(vec, vidx, VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, pairs) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, pairs) + +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint16, 16, __riscv_vzext_vf2, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int16, 16, __riscv_vzext_vf2, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_uint32, 32, __riscv_vzext_vf4, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_int32, 32, __riscv_vzext_vf4, quads) +OPENCV_HAL_IMPL_RVV_INTERLEAVED_PQ(v_float32, 32, __riscv_vzext_vf4, quads) + +//////////// PopCount ////////// +static const unsigned char popCountTable[256] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; +#define OPENCV_HAL_IMPL_RVV_HADD(_Tpvec, _Tpvec2, _Tm2, width, width2, suffix, add) \ +static inline _Tpvec2 v_hadd(_Tpvec a) { \ + vuint##width2##m2_t oneX2 = __riscv_vmv_v_x_u##width2##m2(1, VTraits::vlanes()); \ + vuint##width##m2_t one = __riscv_vreinterpret_u##width##m2(oneX2); \ + _Tm2 res = add(a, __riscv_vslide1down(a, 0, VTraits::vlanes()), VTraits::vlanes()); \ + return __riscv_vget_##suffix##m2(__riscv_vcompress(res, __riscv_vmseq(one, 1, VTraits::vlanes()), VTraits::vlanes()), 0); \ +} +OPENCV_HAL_IMPL_RVV_HADD(v_uint8, v_uint16, vuint16m4_t, 8, 16, u16, __riscv_vwaddu_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_uint16, v_uint32, vuint32m4_t, 16, 32, u32, __riscv_vwaddu_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_uint32, v_uint64, vuint64m4_t, 32, 64, u64, __riscv_vwaddu_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_int8, v_int16, vint16m4_t, 8, 16, i16, __riscv_vwadd_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_int16, v_int32, vint32m4_t, 16, 32, i32, __riscv_vwadd_vv) +OPENCV_HAL_IMPL_RVV_HADD(v_int32, v_int64, vint64m4_t, 32, 64, i64, __riscv_vwadd_vv) + +OPENCV_HAL_IMPL_RVV_HADD(vint32m4_t, v_int32, vint32m4_t, 16, 32, i32, __riscv_vadd) +OPENCV_HAL_IMPL_RVV_HADD(vint64m4_t, v_int64, vint64m4_t, 32, 64, i64, __riscv_vadd) + +inline v_uint8 v_popcount(const v_uint8& a) +{ + return __riscv_vloxei8(popCountTable, a, VTraits::vlanes()); +} +inline v_uint16 v_popcount(const v_uint16& a) +{ + return v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))); +} +inline v_uint32 v_popcount(const v_uint32& a) +{ + return v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a)))); +} +inline v_uint64 v_popcount(const v_uint64& a) +{ + return v_hadd(v_hadd(v_hadd(v_popcount(__riscv_vreinterpret_u8m2(a))))); +} + +inline v_uint8 v_popcount(const v_int8& a) +{ + return v_popcount(v_abs(a));\ +} +inline v_uint16 v_popcount(const v_int16& a) +{ + return v_popcount(v_abs(a));\ +} +inline v_uint32 v_popcount(const v_int32& a) +{ + return v_popcount(v_abs(a));\ +} +inline v_uint64 v_popcount(const v_int64& a) +{ + // max(0 - a) is used, since v_abs does not support 64-bit integers. + return v_popcount(v_reinterpret_as_u64(__riscv_vmax(a, v_sub(v_setzero_s64(), a), VTraits::vlanes()))); +} + + +//////////// SignMask //////////// +#define OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(_Tpvec) \ +inline int v_signmask(const _Tpvec& a) \ +{ \ + uint8_t ans[4] = {0}; \ + __riscv_vsm(ans, __riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ + return *(reinterpret_cast(ans)) & (((__int128_t)1 << VTraits<_Tpvec>::vlanes()) - 1); \ +} \ +inline int v_scan_forward(const _Tpvec& a) \ +{ \ + return (int)__riscv_vfirst(__riscv_vmslt(a, 0, VTraits<_Tpvec>::vlanes()), VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int8) +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int16) +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int32) +OPENCV_HAL_IMPL_RVV_SIGNMASK_OP(v_int64) + +inline int64 v_signmask(const v_uint8& a) +{ return v_signmask(v_reinterpret_as_s8(a)); } +inline int64 v_signmask(const v_uint16& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } +inline int v_signmask(const v_uint32& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_float32& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_uint64& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } +#if CV_SIMD_SCALABLE_64F +inline int v_signmask(const v_float64& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } +#endif + +//////////// Scan forward //////////// +inline int v_scan_forward(const v_uint8& a) +{ return v_scan_forward(v_reinterpret_as_s8(a)); } +inline int v_scan_forward(const v_uint16& a) +{ return v_scan_forward(v_reinterpret_as_s16(a)); } +inline int v_scan_forward(const v_uint32& a) +{ return v_scan_forward(v_reinterpret_as_s32(a)); } +inline int v_scan_forward(const v_float32& a) +{ return v_scan_forward(v_reinterpret_as_s32(a)); } +inline int v_scan_forward(const v_uint64& a) +{ return v_scan_forward(v_reinterpret_as_s64(a)); } +#if CV_SIMD_SCALABLE_64F +inline int v_scan_forward(const v_float64& a) +{ return v_scan_forward(v_reinterpret_as_s64(a)); } +#endif + +//////////// Pack triplets //////////// +// {A0, A1, A2, A3, B0, B1, B2, B3, C0 ...} --> {A0, A1, A2, B0, B1, B2, C0 ...} +// mask: {0,0,0,1, ...} -> {T,T,T,F, ...} +#define OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(_Tpvec, v_trunc) \ +inline _Tpvec v_pack_triplets(const _Tpvec& vec) { \ + size_t vl = VTraits::vlanes(); \ + vuint32m2_t one = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t zero = __riscv_vmv_v_x_u8m2(0, vl); \ + vuint8m2_t mask = __riscv_vreinterpret_u8m2(one); \ + return __riscv_vcompress(vec, __riscv_vmseq(v_trunc(__riscv_vslideup(zero, mask, 3, vl)), 0, vl), VTraits<_Tpvec>::vlanes()); \ +} + +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int8, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint16, __riscv_vlmul_trunc_u8m1) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int16, __riscv_vlmul_trunc_u8m1) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint32, __riscv_vlmul_trunc_u8mf2) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int32, __riscv_vlmul_trunc_u8mf2) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float32, __riscv_vlmul_trunc_u8mf2) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_uint64, __riscv_vlmul_trunc_u8mf4) +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_int64, __riscv_vlmul_trunc_u8mf4) +#if CV_SIMD_SCALABLE_64F +OPENCV_HAL_IMPL_RVV_PACK_TRIPLETS(v_float64, __riscv_vlmul_trunc_u8mf4) +#endif + + +////// FP16 support /////// + +#if defined(__riscv_zfh) && __riscv_zfh +inline v_float32 v_load_expand(const hfloat* ptr) +{ + return __riscv_vfwcvt_f(__riscv_vle16_v_f16m1((_Float16*)ptr, VTraits::vlanes()) ,VTraits::vlanes());; +} + +inline void v_pack_store(hfloat* ptr, const v_float32& v) +{ + __riscv_vse16_v_f16m1((_Float16*)ptr, __riscv_vfncvt_f_f_w_f16m1(v, VTraits::vlanes()), VTraits::vlanes()); +} +#else +inline v_float32 v_load_expand(const hfloat* ptr) +{ + float buf[32]; + for( int i = 0; i < VTraits::vlanes(); i++ ) buf[i] = (float)ptr[i]; + return v_load(buf); +} + +inline void v_pack_store(hfloat* ptr, const v_float32& v) +{ + float buf[32]; + v_store(buf, v); + for( int i = 0; i < VTraits::vlanes(); i++ ) ptr[i] = hfloat(buf[i]); +} +#endif +////////////// Rounding ////////////// +inline v_int32 v_round(const v_float32& a) +{ + // return vfcvt_x(vfadd(a, 1e-6, VTraits::vlanes()), VTraits::vlanes()); + return __riscv_vfcvt_x(a, VTraits::vlanes()); +} + +inline v_int32 v_floor(const v_float32& a) +{ + return __riscv_vfcvt_x(__riscv_vfsub(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); + // return vfcvt_x(a, VTraits::vlanes()); +} + +inline v_int32 v_ceil(const v_float32& a) +{ + return __riscv_vfcvt_x(__riscv_vfadd(a, 0.5f - 1e-5, VTraits::vlanes()), VTraits::vlanes()); +} + +inline v_int32 v_trunc(const v_float32& a) +{ + return __riscv_vfcvt_rtz_x(a, VTraits::vlanes()); +} +#if CV_SIMD_SCALABLE_64F +inline v_int32 v_round(const v_float64& a) +{ + return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); +} + +inline v_int32 v_round(const v_float64& a, const v_float64& b) +{ + // return vfncvt_x(vset(vlmul_ext_f64m2(vfadd(a, 1e-6, VTraits::vlanes())), 1, b), VTraits::vlanes()); + // Fix https://github.com/opencv/opencv/issues/24746 + return __riscv_vfncvt_x(__riscv_vset(__riscv_vlmul_ext_f64m4(a), 1, b), VTraits::vlanes()); +} + +inline v_int32 v_floor(const v_float64& a) +{ + return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfsub(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); +} + +inline v_int32 v_ceil(const v_float64& a) +{ + return __riscv_vfncvt_x(__riscv_vlmul_ext_f64m4(__riscv_vfadd(a, 0.5f - 1e-6, VTraits::vlanes())), VTraits::vlanes()); +} + +inline v_int32 v_trunc(const v_float64& a) +{ + return __riscv_vfncvt_rtz_x(__riscv_vlmul_ext_f64m4(a), VTraits::vlanes()); +} +#endif + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32 v_dotprod(const v_int16& a, const v_int16& b) +{ + vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); + return v_hadd(temp1); +} + +inline v_int32 v_dotprod(const v_int16& a, const v_int16& b, const v_int32& c) +{ + vint32m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); + return __riscv_vadd(v_hadd(temp1), c, VTraits::vlanes()); +} + +// 32 >> 64 +inline v_int64 v_dotprod(const v_int32& a, const v_int32& b) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ + vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ + vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); + vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_i64m2(res); \ +} +inline v_int64 v_dotprod(const v_int32& a, const v_int32& b, const v_int64& c) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint32m2_t one32 = __riscv_vreinterpret_u32m2(one64); \ + vbool16_t mask = __riscv_vmseq(one32, 1, VTraits::vlanes()); \ + vint64m4_t temp1 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint64m4_t temp2 = __riscv_vslide1down(temp1, 0, VTraits::vlanes()); + vint64m4_t res = __riscv_vadd(temp1, temp2, VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); \ +} + +// 8 >> 32 +inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_u32m2(res); +} + +inline v_uint32 v_dotprod_expand(const v_uint8& a, const v_uint8& b, + const v_uint32& c) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vuint16m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint32m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_u32m2(res), c, VTraits::vlanes()); +} + +inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_i32m2(res); +} + +inline v_int32 v_dotprod_expand(const v_int8& a, const v_int8& b, + const v_int32& c) +{ + vuint32m2_t one32 = __riscv_vmv_v_x_u32m2(1, VTraits::vlanes()); \ + vuint8m2_t one8 = __riscv_vreinterpret_u8m2(one32); \ + vbool4_t mask = __riscv_vmseq(one8, 1, VTraits::vlanes()); \ + vint16m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint16m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint16m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint16m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint32m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_i32m2(res), c, VTraits::vlanes()); +} + + +// // 16 >> 64 +inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_u64m2(res); +} +inline v_uint64 v_dotprod_expand(const v_uint16& a, const v_uint16& b, const v_uint64& c) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vuint32m4_t t0 = __riscv_vwmulu(a, b, VTraits::vlanes()); \ + vuint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vuint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vuint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vuint64m8_t res = __riscv_vadd(__riscv_vwaddu_vv(t2, t3, VTraits::vlanes()), __riscv_vwaddu_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_u64m2(res), c, VTraits::vlanes()); +} + +inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vlmul_trunc_i64m2(res); +} +inline v_int64 v_dotprod_expand(const v_int16& a, const v_int16& b, + const v_int64& c) +{ + vuint64m2_t one64 = __riscv_vmv_v_x_u64m2(1, VTraits::vlanes()); \ + vuint16m2_t one16 = __riscv_vreinterpret_u16m2(one64); \ + vbool8_t mask = __riscv_vmseq(one16, 1, VTraits::vlanes()); \ + vint32m4_t t0 = __riscv_vwmul(a, b, VTraits::vlanes()); \ + vint32m4_t t1= __riscv_vslide1down(t0, 0, VTraits::vlanes()); + vint32m4_t t2= __riscv_vslide1down(t1, 0, VTraits::vlanes()); + vint32m4_t t3= __riscv_vslide1down(t2, 0, VTraits::vlanes()); + vint64m8_t res = __riscv_vadd(__riscv_vwadd_vv(t2, t3, VTraits::vlanes()), __riscv_vwadd_vv(t0, t1, VTraits::vlanes()), VTraits::vlanes()); + res = __riscv_vcompress(res, mask, VTraits::vlanes()); \ + return __riscv_vadd(__riscv_vlmul_trunc_i64m2(res), c, VTraits::vlanes()); +} + +// // 32 >> 64f +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64 v_dotprod_expand(const v_int32& a, const v_int32& b, + const v_float64& c) +{ return v_add(v_dotprod_expand(a, b) , c); } +#endif + +//////// Fast Dot Product //////// +// 16 >> 32 +inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int32 v_dotprod_fast(const v_int16& a, const v_int16& b, const v_int32& c) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + +// 32 >> 64 +inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int64 v_dotprod_fast(const v_int32& a, const v_int32& b, const v_int64& c) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + + +// 8 >> 32 +inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b) +{ + vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); + auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res); +} +inline v_uint32 v_dotprod_expand_fast(const v_uint8& a, const v_uint8& b, const v_uint32& c) +{ + vuint32m1_t zero = __riscv_vmv_v_x_u32m1(0, VTraits::vlanes()); + auto res = __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u32m2(0, VTraits::vlanes()), 0, res), VTraits::vlanes()); +} +inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int32 v_dotprod_expand_fast(const v_int8& a, const v_int8& b, const v_int32& c) +{ + vint32m1_t zero = __riscv_vmv_v_x_i32m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i32m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + +// 16 >> 64 +inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b) +{ + vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_uint64 v_dotprod_expand_fast(const v_uint16& a, const v_uint16& b, const v_uint64& c) +{ + vuint64m1_t zero = __riscv_vmv_v_x_u64m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_u64m2(0, VTraits::vlanes()), 0, __riscv_vwredsumu_tu(zero, __riscv_vwmulu(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} +inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())); +} +inline v_int64 v_dotprod_expand_fast(const v_int16& a, const v_int16& b, const v_int64& c) +{ + vint64m1_t zero = __riscv_vmv_v_x_i64m1(0, VTraits::vlanes()); + return __riscv_vadd(c, __riscv_vset(__riscv_vmv_v_x_i64m2(0, VTraits::vlanes()), 0, __riscv_vwredsum_tu(zero, __riscv_vwmul(a, b, VTraits::vlanes()), zero, VTraits::vlanes())), VTraits::vlanes()); +} + +// 32 >> 64f +#if CV_SIMD_SCALABLE_64F +inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b) +{ return v_cvt_f64(v_dotprod_fast(a, b)); } +inline v_float64 v_dotprod_expand_fast(const v_int32& a, const v_int32& b, const v_float64& c) +{ return v_add(v_dotprod_expand_fast(a, b) , c); } +#endif + +// TODO: only 128 bit now. +inline v_float32 v_matmul(const v_float32& v, const v_float32& mat0, + const v_float32& mat1, const v_float32& mat2, + const v_float32& mat3) +{ + vfloat32m2_t res; + res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v, 0), VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 1), mat1, VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 2), mat2, VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v, 3), mat3, VTraits::vlanes()); + return res; +} + +// TODO: only 128 bit now. +inline v_float32 v_matmuladd(const v_float32& v, const v_float32& mat0, + const v_float32& mat1, const v_float32& mat2, + const v_float32& a) +{ + vfloat32m2_t res = __riscv_vfmul_vf_f32m2(mat0, v_extract_n(v,0), VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,1), mat1, VTraits::vlanes()); + res = __riscv_vfmacc_vf_f32m2(res, v_extract_n(v,2), mat2, VTraits::vlanes()); + return __riscv_vfadd(res, a, VTraits::vlanes()); +} + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32 v_exp(const v_float32& x) { return v_exp_default_32f(x); } +inline v_float32 v_log(const v_float32& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32& x, v_float32& s, v_float32& c) { v_sincos_default_32f(x, s, c); } +inline v_float32 v_sin(const v_float32& x) { return v_sin_default_32f(x); } +inline v_float32 v_cos(const v_float32& x) { return v_cos_default_32f(x); } +inline v_float32 v_erf(const v_float32& x) { return v_erf_default_32f(x); } + +inline v_float64 v_exp(const v_float64& x) { return v_exp_default_64f(x); } +inline v_float64 v_log(const v_float64& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64& x, v_float64& s, v_float64& c) { v_sincos_default_64f(x, s, c); } +inline v_float64 v_sin(const v_float64& x) { return v_sin_default_64f(x); } +inline v_float64 v_cos(const v_float64& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} //namespace cv + +#endif //OPENCV_HAL_INTRIN_RVV_SCALABLE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp index 88ce25737b..369cd2fbc6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse.hpp @@ -1,3483 +1,3483 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HAL_SSE_HPP -#define OPENCV_HAL_SSE_HPP - -#include -#include "opencv2/core/utility.hpp" - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 -#define CV_SIMD128_FP16 0 // no native operations with FP16 type. - -namespace cv -{ - -//! @cond IGNORED - -// -// Compilation troubleshooting: -// - MSVC: error C2719: 'a': formal parameter with requested alignment of 16 won't be aligned -// Replace parameter declaration to const reference: -// -v_int32x4 a -// +const v_int32x4& a -// - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Types //////////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - typedef __m128i vector_type; - enum { nlanes = 16 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint8x16() {} - explicit v_uint8x16(__m128i v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6, (char)v7, - (char)v8, (char)v9, (char)v10, (char)v11, - (char)v12, (char)v13, (char)v14, (char)v15); - } - - uchar get0() const - { - return (uchar)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - typedef __m128i vector_type; - enum { nlanes = 16 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int8x16() {} - explicit v_int8x16(__m128i v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, - (char)v4, (char)v5, (char)v6, (char)v7, - (char)v8, (char)v9, (char)v10, (char)v11, - (char)v12, (char)v13, (char)v14, (char)v15); - } - - schar get0() const - { - return (schar)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - typedef __m128i vector_type; - enum { nlanes = 8 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint16x8() {} - explicit v_uint16x8(__m128i v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7); - } - - ushort get0() const - { - return (ushort)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - typedef __m128i vector_type; - enum { nlanes = 8 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int16x8() {} - explicit v_int16x8(__m128i v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, - (short)v4, (short)v5, (short)v6, (short)v7); - } - - short get0() const - { - return (short)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - typedef __m128i vector_type; - enum { nlanes = 4 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint32x4() {} - explicit v_uint32x4(__m128i v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - val = _mm_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3); - } - - unsigned get0() const - { - return (unsigned)_mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - typedef __m128i vector_type; - enum { nlanes = 4 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int32x4() {} - explicit v_int32x4(__m128i v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - val = _mm_setr_epi32(v0, v1, v2, v3); - } - - int get0() const - { - return _mm_cvtsi128_si32(val); - } - - __m128i val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - typedef __m128 vector_type; - enum { nlanes = 4 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_float32x4() {} - explicit v_float32x4(__m128 v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - val = _mm_setr_ps(v0, v1, v2, v3); - } - - float get0() const - { - return _mm_cvtss_f32(val); - } - - __m128 val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - typedef __m128i vector_type; - enum { nlanes = 2 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_uint64x2() {} - explicit v_uint64x2(__m128i v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { -#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) - val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); -#elif defined(__GNUC__) - val = _mm_setr_epi64((__m64)v0, (__m64)v1); -#else - val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); -#endif - } - - uint64 get0() const - { - #if !defined(__x86_64__) && !defined(_M_X64) - int a = _mm_cvtsi128_si32(val); - int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); - return (unsigned)a | ((uint64)(unsigned)b << 32); - #else - return (uint64)_mm_cvtsi128_si64(val); - #endif - } - - __m128i val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - typedef __m128i vector_type; - enum { nlanes = 2 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_int64x2() {} - explicit v_int64x2(__m128i v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { -#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) - val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); -#elif defined(__GNUC__) - val = _mm_setr_epi64((__m64)v0, (__m64)v1); -#else - val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); -#endif - } - - int64 get0() const - { - #if !defined(__x86_64__) && !defined(_M_X64) - int a = _mm_cvtsi128_si32(val); - int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); - return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); - #else - return _mm_cvtsi128_si64(val); - #endif - } - - __m128i val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - typedef __m128d vector_type; - enum { nlanes = 2 }; - - /* coverity[uninit_ctor]: suppress warning */ - v_float64x2() {} - explicit v_float64x2(__m128d v) : val(v) {} - v_float64x2(double v0, double v1) - { - val = _mm_setr_pd(v0, v1); - } - - double get0() const - { - return _mm_cvtsd_f64(val); - } - - __m128d val; -}; - -namespace hal_sse_internal -{ - template - to_sse_type v_sse_reinterpret_as(const from_sse_type& val); - -#define OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(to_sse_type, from_sse_type, sse_cast_intrin) \ - template<> inline \ - to_sse_type v_sse_reinterpret_as(const from_sse_type& a) \ - { return sse_cast_intrin(a); } - - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128i, OPENCV_HAL_NOP) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128, _mm_castps_si128) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128d, _mm_castpd_si128) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128i, _mm_castsi128_ps) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128, OPENCV_HAL_NOP) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128d, _mm_castpd_ps) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128i, _mm_castsi128_pd) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128, _mm_castps_pd) - OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128d, OPENCV_HAL_NOP) -} - -#define OPENCV_HAL_IMPL_SSE_INITVEC(_Tpvec, _Tp, suffix, zsuffix, ssuffix, _Tps, cast) \ -inline _Tpvec v_setzero_##suffix() { return _Tpvec(_mm_setzero_##zsuffix()); } \ -inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(_mm_set1_##ssuffix((_Tps)v)); } \ -template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ -{ return _Tpvec(cast(a.val)); } - -OPENCV_HAL_IMPL_SSE_INITVEC(v_uint8x16, uchar, u8, si128, epi8, schar, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_int8x16, schar, s8, si128, epi8, schar, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_uint16x8, ushort, u16, si128, epi16, short, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_int16x8, short, s16, si128, epi16, short, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_uint32x4, unsigned, u32, si128, epi32, int, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_int32x4, int, s32, si128, epi32, int, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_INITVEC(v_float32x4, float, f32, ps, ps, float, _mm_castsi128_ps) -OPENCV_HAL_IMPL_SSE_INITVEC(v_float64x2, double, f64, pd, pd, double, _mm_castsi128_pd) - -inline v_uint64x2 v_setzero_u64() { return v_uint64x2(_mm_setzero_si128()); } -inline v_int64x2 v_setzero_s64() { return v_int64x2(_mm_setzero_si128()); } -inline v_uint64x2 v_setall_u64(uint64 val) { return v_uint64x2(val, val); } -inline v_int64x2 v_setall_s64(int64 val) { return v_int64x2(val, val); } - -template <> inline v_uint64x2 v_setzero_() { return v_setzero_u64(); } -template <> inline v_int64x2 v_setzero_() { return v_setzero_s64(); } -template <> inline v_uint64x2 v_setall_(uint64 val) { return v_setall_u64(val); } -template <> inline v_int64x2 v_setall_(int64 val) { return v_setall_s64(val); } - -template inline -v_uint64x2 v_reinterpret_as_u64(const _Tpvec& a) { return v_uint64x2(a.val); } -template inline -v_int64x2 v_reinterpret_as_s64(const _Tpvec& a) { return v_int64x2(a.val); } -inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& a) -{ return v_float32x4(_mm_castsi128_ps(a.val)); } -inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& a) -{ return v_float32x4(_mm_castsi128_ps(a.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& a) -{ return v_float64x2(_mm_castsi128_pd(a.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& a) -{ return v_float64x2(_mm_castsi128_pd(a.val)); } - -#define OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(_Tpvec, suffix) \ -inline _Tpvec v_reinterpret_as_##suffix(const v_float32x4& a) \ -{ return _Tpvec(_mm_castps_si128(a.val)); } \ -inline _Tpvec v_reinterpret_as_##suffix(const v_float64x2& a) \ -{ return _Tpvec(_mm_castpd_si128(a.val)); } - -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint8x16, u8) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int8x16, s8) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint16x8, u16) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int16x8, s16) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint32x4, u32) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int32x4, s32) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint64x2, u64) -OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int64x2, s64) - -inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) {return a; } -inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) {return a; } -inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) {return v_float32x4(_mm_castpd_ps(a.val)); } -inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) {return v_float64x2(_mm_castps_pd(a.val)); } - -//////////////// PACK /////////////// -inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i delta = _mm_set1_epi16(255); - return v_uint8x16(_mm_packus_epi16(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)), - _mm_subs_epu16(b.val, _mm_subs_epu16(b.val, delta)))); -} - -inline void v_pack_store(uchar* ptr, const v_uint16x8& a) -{ - __m128i delta = _mm_set1_epi16(255); - __m128i a1 = _mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); -} - -inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) -{ return v_uint8x16(_mm_packus_epi16(a.val, b.val)); } - -inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) -{ _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a.val, a.val)); } - -template inline -v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - return v_uint8x16(_mm_packus_epi16(_mm_srli_epi16(_mm_adds_epu16(a.val, delta), n), - _mm_srli_epi16(_mm_adds_epu16(b.val, delta), n))); -} - -template inline -void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) -{ - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - __m128i a1 = _mm_srli_epi16(_mm_adds_epu16(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); -} - -template inline -v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) -{ - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - return v_uint8x16(_mm_packus_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), - _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); -} - -template inline -void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) -{ - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); -} - -inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) -{ return v_int8x16(_mm_packs_epi16(a.val, b.val)); } - -inline void v_pack_store(schar* ptr, const v_int16x8& a) -{ _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a.val, a.val)); } - -template inline -v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - return v_int8x16(_mm_packs_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), - _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); -} -template inline -void v_rshr_pack_store(schar* ptr, const v_int16x8& a) -{ - // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. - __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); - __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a1, a1)); -} - - -// byte-wise "mask ? a : b" -inline __m128i v_select_si128(__m128i mask, __m128i a, __m128i b) -{ -#if CV_SSE4_1 - return _mm_blendv_epi8(b, a, mask); -#else - return _mm_xor_si128(b, _mm_and_si128(_mm_xor_si128(a, b), mask)); -#endif -} - -inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) -{ return v_uint16x8(_v128_packs_epu32(a.val, b.val)); } - -inline void v_pack_store(ushort* ptr, const v_uint32x4& a) -{ - __m128i z = _mm_setzero_si128(), maxval32 = _mm_set1_epi32(65535), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, a.val), maxval32, a.val), delta32); - __m128i r = _mm_packs_epi32(a1, a1); - _mm_storel_epi64((__m128i*)ptr, _mm_sub_epi16(r, _mm_set1_epi16(-32768))); -} - -template inline -v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i b1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(b.val, delta), n), delta32); - return v_uint16x8(_mm_sub_epi16(_mm_packs_epi32(a1, b1), _mm_set1_epi16(-32768))); -} - -template inline -void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - _mm_storel_epi64((__m128i*)ptr, a2); -} - -inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_uint16x8(_mm_packus_epi32(a.val, b.val)); -#else - __m128i delta32 = _mm_set1_epi32(32768); - - // preliminary saturate negative values to zero - __m128i a1 = _mm_and_si128(a.val, _mm_cmpgt_epi32(a.val, _mm_set1_epi32(0))); - __m128i b1 = _mm_and_si128(b.val, _mm_cmpgt_epi32(b.val, _mm_set1_epi32(0))); - - __m128i r = _mm_packs_epi32(_mm_sub_epi32(a1, delta32), _mm_sub_epi32(b1, delta32)); - return v_uint16x8(_mm_sub_epi16(r, _mm_set1_epi16(-32768))); -#endif -} - -inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) -{ -#if CV_SSE4_1 - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a.val, a.val)); -#else - __m128i delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(a.val, delta32); - __m128i r = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - _mm_storel_epi64((__m128i*)ptr, r); -#endif -} - -template inline -v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - __m128i delta = _mm_set1_epi32(1 << (n - 1)); - return v_uint16x8(_mm_packus_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), - _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); -#else - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - __m128i b1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(b.val, delta), n), delta32); - __m128i b2 = _mm_sub_epi16(_mm_packs_epi32(b1, b1), _mm_set1_epi16(-32768)); - return v_uint16x8(_mm_unpacklo_epi64(a2, b2)); -#endif -} - -template inline -void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) -{ -#if CV_SSE4_1 - __m128i delta = _mm_set1_epi32(1 << (n - 1)); - __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a1, a1)); -#else - __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); - __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); - __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); - _mm_storel_epi64((__m128i*)ptr, a2); -#endif -} - -inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) -{ return v_int16x8(_mm_packs_epi32(a.val, b.val)); } - -inline void v_pack_store(short* ptr, const v_int32x4& a) -{ - _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a.val, a.val)); -} - -template inline -v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)); - return v_int16x8(_mm_packs_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), - _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); -} - -template inline -void v_rshr_pack_store(short* ptr, const v_int32x4& a) -{ - __m128i delta = _mm_set1_epi32(1 << (n-1)); - __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); - _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a1, a1)); -} - - -// [a0 0 | b0 0] [a1 0 | b1 0] -inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 - return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); -} - -inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a1); -} - -// [a0 0 | b0 0] [a1 0 | b1 0] -inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) -{ - __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 - return v_int32x4(_mm_unpacklo_epi32(v0, v1)); -} - -inline void v_pack_store(int* ptr, const v_int64x2& a) -{ - __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a1); -} - -template inline -v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - uint64 delta = (uint64)1 << (n-1); - v_uint64x2 delta2(delta, delta); - __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i b1 = _mm_srli_epi64(_mm_add_epi64(b.val, delta2.val), n); - __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 - return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); -} - -template inline -void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - uint64 delta = (uint64)1 << (n-1); - v_uint64x2 delta2(delta, delta); - __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a2); -} - -inline __m128i v_sign_epi64(__m128i a) -{ - return _mm_shuffle_epi32(_mm_srai_epi32(a, 31), _MM_SHUFFLE(3, 3, 1, 1)); // x m0 | x m1 -} - -inline __m128i v_srai_epi64(__m128i a, int imm) -{ - __m128i smask = v_sign_epi64(a); - return _mm_xor_si128(_mm_srli_epi64(_mm_xor_si128(a, smask), imm), smask); -} - -template inline -v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) -{ - int64 delta = (int64)1 << (n-1); - v_int64x2 delta2(delta, delta); - __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i b1 = v_srai_epi64(_mm_add_epi64(b.val, delta2.val), n); - __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 - __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 - return v_int32x4(_mm_unpacklo_epi32(v0, v1)); -} - -template inline -void v_rshr_pack_store(int* ptr, const v_int64x2& a) -{ - int64 delta = (int64)1 << (n-1); - v_int64x2 delta2(delta, delta); - __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); - __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); - _mm_storel_epi64((__m128i*)ptr, a2); -} - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - __m128i ab = _mm_packs_epi16(a.val, b.val); - return v_uint8x16(ab); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - __m128i ab = _mm_packs_epi32(a.val, b.val); - __m128i cd = _mm_packs_epi32(c.val, d.val); - return v_uint8x16(_mm_packs_epi16(ab, cd)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - __m128i ab = _mm_packs_epi32(a.val, b.val); - __m128i cd = _mm_packs_epi32(c.val, d.val); - __m128i ef = _mm_packs_epi32(e.val, f.val); - __m128i gh = _mm_packs_epi32(g.val, h.val); - - __m128i abcd = _mm_packs_epi32(ab, cd); - __m128i efgh = _mm_packs_epi32(ef, gh); - return v_uint8x16(_mm_packs_epi16(abcd, efgh)); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); - __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); - __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); - __m128 v3 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(3, 3, 3, 3)), m3.val); - - return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, v3))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); - __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); - __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); - - return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, a.val))); -} - -#define OPENCV_HAL_IMPL_SSE_BIN_OP(bin_op, _Tpvec, intrin) \ - inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ - { \ - return _Tpvec(intrin(a.val, b.val)); \ - } - -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint8x16, _mm_adds_epu8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint8x16, _mm_subs_epu8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int8x16, _mm_adds_epi8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int8x16, _mm_subs_epi8) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint16x8, _mm_adds_epu16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint16x8, _mm_subs_epu16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int16x8, _mm_adds_epi16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int16x8, _mm_subs_epi16) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint32x4, _mm_add_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint32x4, _mm_sub_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_uint32x4, _v128_mullo_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int32x4, _mm_add_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int32x4, _mm_sub_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_int32x4, _v128_mullo_epi32) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float32x4, _mm_add_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float32x4, _mm_sub_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float32x4, _mm_mul_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float32x4, _mm_div_ps) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float64x2, _mm_add_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float64x2, _mm_sub_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float64x2, _mm_mul_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float64x2, _mm_div_pd) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint64x2, _mm_add_epi64) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint64x2, _mm_sub_epi64) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int64x2, _mm_add_epi64) -OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int64x2, _mm_sub_epi64) - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_SSE_MUL_SAT(_Tpvec, _Tpwvec) \ - inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ - { \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ - } - -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint16x8, v_uint32x4) -OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int16x8, v_int32x4) - -// Multiply and expand -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - v_uint16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - v_int16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - __m128i v0 = _mm_mullo_epi16(a.val, b.val); - __m128i v1 = _mm_mulhi_epi16(a.val, b.val); - c.val = _mm_unpacklo_epi16(v0, v1); - d.val = _mm_unpackhi_epi16(v0, v1); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - __m128i v0 = _mm_mullo_epi16(a.val, b.val); - __m128i v1 = _mm_mulhi_epu16(a.val, b.val); - c.val = _mm_unpacklo_epi16(v0, v1); - d.val = _mm_unpackhi_epi16(v0, v1); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - __m128i c0 = _mm_mul_epu32(a.val, b.val); - __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); - c.val = _mm_unpacklo_epi64(c0, c1); - d.val = _mm_unpackhi_epi64(c0, c1); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) { return v_int16x8(_mm_mulhi_epi16(a.val, b.val)); } -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) { return v_uint16x8(_mm_mulhi_epu16(a.val, b.val)); } - -//////// Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ return v_int32x4(_mm_madd_epi16(a.val, b.val)); } -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - __m128i even = _mm_mul_epi32(a.val, b.val); - __m128i odd = _mm_mul_epi32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); - return v_int64x2(_mm_add_epi64(even, odd)); -#else - __m128i even_u = _mm_mul_epu32(a.val, b.val); - __m128i odd_u = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); - // convert unsigned to signed high multiplication (from: Agner Fog(veclib) and H S Warren: Hacker's delight, 2003, p. 132) - __m128i a_sign = _mm_srai_epi32(a.val, 31); - __m128i b_sign = _mm_srai_epi32(b.val, 31); - // |x * sign of x - __m128i axb = _mm_and_si128(a.val, b_sign); - __m128i bxa = _mm_and_si128(b.val, a_sign); - // sum of sign corrections - __m128i ssum = _mm_add_epi32(bxa, axb); - __m128i even_ssum = _mm_slli_epi64(ssum, 32); - __m128i odd_ssum = _mm_and_si128(ssum, _mm_set_epi32(-1, 0, -1, 0)); - // convert to signed and prod - return v_int64x2(_mm_add_epi64(_mm_sub_epi64(even_u, even_ssum), _mm_sub_epi64(odd_u, odd_ssum))); -#endif -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i a0 = _mm_srli_epi16(_mm_slli_si128(a.val, 1), 8); // even - __m128i a1 = _mm_srli_epi16(a.val, 8); // odd - __m128i b0 = _mm_srli_epi16(_mm_slli_si128(b.val, 1), 8); - __m128i b1 = _mm_srli_epi16(b.val, 8); - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_uint32x4(_mm_add_epi32(p0, p1)); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - __m128i a0 = _mm_srai_epi16(_mm_slli_si128(a.val, 1), 8); // even - __m128i a1 = _mm_srai_epi16(a.val, 8); // odd - __m128i b0 = _mm_srai_epi16(_mm_slli_si128(b.val, 1), 8); - __m128i b1 = _mm_srai_epi16(b.val, 8); - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_int32x4(_mm_add_epi32(p0, p1)); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 c, d; - v_mul_expand(a, b, c, d); - - v_uint64x2 c0, c1, d0, d1; - v_expand(c, c0, c1); - v_expand(d, d0, d1); - - c0 = v_add(c0, c1); d0 = v_add(d0, d1); - return v_uint64x2(_mm_add_epi64( - _mm_unpacklo_epi64(c0.val, d0.val), - _mm_unpackhi_epi64(c0.val, d0.val) - )); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_int64x2(_mm_add_epi64( - _mm_unpacklo_epi64(c.val, d.val), - _mm_unpackhi_epi64(c.val, d.val) - )); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_cvt_f64(v_dotprod(a, b)); -#else - v_float64x2 c = v_mul(v_cvt_f64(a), v_cvt_f64(b)); - v_float64x2 d = v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b)); - - return v_float64x2(_mm_add_pd( - _mm_unpacklo_pd(c.val, d.val), - _mm_unpackhi_pd(c.val, d.val) - )); -#endif -} -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_add(v_dotprod(a, b), c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_add(v_dotprod_fast(a, b), c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i a0 = v_expand_low(a).val; - __m128i a1 = v_expand_high(a).val; - __m128i b0 = v_expand_low(b).val; - __m128i b1 = v_expand_high(b).val; - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_uint32x4(_mm_add_epi32(p0, p1)); -} -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_SSE4_1 - __m128i a0 = _mm_cvtepi8_epi16(a.val); - __m128i a1 = v_expand_high(a).val; - __m128i b0 = _mm_cvtepi8_epi16(b.val); - __m128i b1 = v_expand_high(b).val; - __m128i p0 = _mm_madd_epi16(a0, b0); - __m128i p1 = _mm_madd_epi16(a1, b1); - return v_int32x4(_mm_add_epi32(p0, p1)); -#else - return v_dotprod_expand(a, b); -#endif -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 c, d; - v_mul_expand(a, b, c, d); - - v_uint64x2 c0, c1, d0, d1; - v_expand(c, c0, c1); - v_expand(d, d0, d1); - - c0 = v_add(c0, c1); d0 = v_add(d0, d1); - return v_add(c0, d0); -} -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_add(c, d); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c); -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } - -#define OPENCV_HAL_IMPL_SSE_LOGIC_OP(_Tpvec, suffix, not_const) \ - OPENCV_HAL_IMPL_SSE_BIN_OP(v_and, _Tpvec, _mm_and_##suffix) \ - OPENCV_HAL_IMPL_SSE_BIN_OP(v_or, _Tpvec, _mm_or_##suffix) \ - OPENCV_HAL_IMPL_SSE_BIN_OP(v_xor, _Tpvec, _mm_xor_##suffix) \ - inline _Tpvec v_not(const _Tpvec& a) \ - { \ - return _Tpvec(_mm_xor_##suffix(a.val, not_const)); \ - } - -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint8x16, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int8x16, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint16x8, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int16x8, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint32x4, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int32x4, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint64x2, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int64x2, si128, _mm_set1_epi32(-1)) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float32x4, ps, _mm_castsi128_ps(_mm_set1_epi32(-1))) -OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float64x2, pd, _mm_castsi128_pd(_mm_set1_epi32(-1))) - -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ return v_float32x4(_mm_sqrt_ps(x.val)); } - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - const __m128 _0_5 = _mm_set1_ps(0.5f), _1_5 = _mm_set1_ps(1.5f); - __m128 t = x.val; - __m128 h = _mm_mul_ps(t, _0_5); - t = _mm_rsqrt_ps(t); - t = _mm_mul_ps(t, _mm_sub_ps(_1_5, _mm_mul_ps(_mm_mul_ps(t, t), h))); - return v_float32x4(t); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ return v_float64x2(_mm_sqrt_pd(x.val)); } - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - const __m128d v_1 = _mm_set1_pd(1.); - return v_float64x2(_mm_div_pd(v_1, _mm_sqrt_pd(x.val))); -} - -#define OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(_Tpuvec, _Tpsvec, func, suffix, subWidth) \ -inline _Tpuvec v_abs(const _Tpsvec& x) \ -{ return _Tpuvec(_mm_##func##_ep##suffix(x.val, _mm_sub_ep##subWidth(_mm_setzero_si128(), x.val))); } - -OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint8x16, v_int8x16, min, u8, i8) -OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint16x8, v_int16x8, max, i16, i16) -inline v_uint32x4 v_abs(const v_int32x4& x) -{ - __m128i s = _mm_srli_epi32(x.val, 31); - __m128i f = _mm_srai_epi32(x.val, 31); - return v_uint32x4(_mm_add_epi32(_mm_xor_si128(x.val, f), s)); -} -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(_mm_and_ps(x.val, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)))); } -inline v_float64x2 v_abs(const v_float64x2& x) -{ - return v_float64x2(_mm_and_pd(x.val, - _mm_castsi128_pd(_mm_srli_epi64(_mm_set1_epi32(-1), 1)))); -} - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_SSE_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_min, _mm_min_epu8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_max, _mm_max_epu8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_min, _mm_min_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_max, _mm_max_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_min, _mm_min_ps) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_max, _mm_max_ps) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_min, _mm_min_pd) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_max, _mm_max_pd) - -inline v_int8x16 v_min(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_SSE4_1 - return v_int8x16(_mm_min_epi8(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi8((char)-128); - return v_int8x16(_mm_xor_si128(delta, _mm_min_epu8(_mm_xor_si128(a.val, delta), - _mm_xor_si128(b.val, delta)))); -#endif -} -inline v_int8x16 v_max(const v_int8x16& a, const v_int8x16& b) -{ -#if CV_SSE4_1 - return v_int8x16(_mm_max_epi8(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi8((char)-128); - return v_int8x16(_mm_xor_si128(delta, _mm_max_epu8(_mm_xor_si128(a.val, delta), - _mm_xor_si128(b.val, delta)))); -#endif -} -inline v_uint16x8 v_min(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_SSE4_1 - return v_uint16x8(_mm_min_epu16(a.val, b.val)); -#else - return v_uint16x8(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, b.val))); -#endif -} -inline v_uint16x8 v_max(const v_uint16x8& a, const v_uint16x8& b) -{ -#if CV_SSE4_1 - return v_uint16x8(_mm_max_epu16(a.val, b.val)); -#else - return v_uint16x8(_mm_adds_epu16(_mm_subs_epu16(a.val, b.val), b.val)); -#endif -} -inline v_uint32x4 v_min(const v_uint32x4& a, const v_uint32x4& b) -{ -#if CV_SSE4_1 - return v_uint32x4(_mm_min_epu32(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi32((int)0x80000000); - __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); - return v_uint32x4(v_select_si128(mask, b.val, a.val)); -#endif -} -inline v_uint32x4 v_max(const v_uint32x4& a, const v_uint32x4& b) -{ -#if CV_SSE4_1 - return v_uint32x4(_mm_max_epu32(a.val, b.val)); -#else - __m128i delta = _mm_set1_epi32((int)0x80000000); - __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); - return v_uint32x4(v_select_si128(mask, a.val, b.val)); -#endif -} -inline v_int32x4 v_min(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_int32x4(_mm_min_epi32(a.val, b.val)); -#else - return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), b.val, a.val)); -#endif -} -inline v_int32x4 v_max(const v_int32x4& a, const v_int32x4& b) -{ -#if CV_SSE4_1 - return v_int32x4(_mm_max_epi32(a.val, b.val)); -#else - return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), a.val, b.val)); -#endif -} - -#define OPENCV_HAL_IMPL_SSE_INT_CMP_OP(_Tpuvec, _Tpsvec, suffix, sbit) \ -inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ -{ return _Tpuvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ -inline _Tpuvec v_ne(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpuvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ -} \ -inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ -{ return _Tpsvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ -inline _Tpsvec v_ne(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpsvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ -} \ -inline _Tpuvec v_lt(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask))); \ -} \ -inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask))); \ -} \ -inline _Tpuvec v_le(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - __m128i not_mask = _mm_set1_epi32(-1); \ - __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask)); \ - return _Tpuvec(_mm_xor_si128(res, not_mask)); \ -} \ -inline _Tpuvec v_ge(const _Tpuvec& a, const _Tpuvec& b) \ -{ \ - __m128i smask = _mm_set1_##suffix(sbit); \ - __m128i not_mask = _mm_set1_epi32(-1); \ - __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask)); \ - return _Tpuvec(_mm_xor_si128(res, not_mask)); \ -} \ -inline _Tpsvec v_lt(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - return _Tpsvec(_mm_cmpgt_##suffix(b.val, a.val)); \ -} \ -inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - return _Tpsvec(_mm_cmpgt_##suffix(a.val, b.val)); \ -} \ -inline _Tpsvec v_le(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(a.val, b.val), not_mask)); \ -} \ -inline _Tpsvec v_ge(const _Tpsvec& a, const _Tpsvec& b) \ -{ \ - __m128i not_mask = _mm_set1_epi32(-1); \ - return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(b.val, a.val), not_mask)); \ -} - -OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint8x16, v_int8x16, epi8, (char)-128) -OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint16x8, v_int16x8, epi16, (short)-32768) -OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint32x4, v_int32x4, epi32, (int)0x80000000) - -#define OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(_Tpvec, suffix) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpneq_##suffix(a.val, b.val)); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmplt_##suffix(a.val, b.val)); } \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpgt_##suffix(a.val, b.val)); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmple_##suffix(a.val, b.val)); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpge_##suffix(a.val, b.val)); } - -OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float32x4, ps) -OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float64x2, pd) - -#if CV_SSE4_1 -#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ -inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(_mm_cmpeq_epi64(a.val, b.val)); } \ -inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ -{ return v_not(v_eq(a, b)); } -#else -#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ __m128i cmp = _mm_cmpeq_epi32(a.val, b.val); \ - return _Tpvec(_mm_and_si128(cmp, _mm_shuffle_epi32(cmp, _MM_SHUFFLE(2, 3, 0, 1)))); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return v_not(v_eq(a, b)); } -#endif - -OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_uint64x2) -OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_int64x2) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(_mm_cmpord_ps(a.val, a.val)); } -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(_mm_cmpord_pd(a.val, a.val)); } - -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_add_wrap, _mm_add_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_add_wrap, _mm_add_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_add_wrap, _mm_add_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_add_wrap, _mm_add_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_sub_wrap, _mm_sub_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_sub_wrap, _mm_sub_epi8) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_sub_wrap, _mm_sub_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_sub_wrap, _mm_sub_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_mul_wrap, _mm_mullo_epi16) -OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_mul_wrap, _mm_mullo_epi16) - -inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i ad = _mm_srai_epi16(a.val, 8); - __m128i bd = _mm_srai_epi16(b.val, 8); - __m128i p0 = _mm_mullo_epi16(a.val, b.val); // even - __m128i p1 = _mm_slli_epi16(_mm_mullo_epi16(ad, bd), 8); // odd - const __m128i b01 = _mm_set1_epi32(0xFF00FF00); - return v_uint8x16(_v128_blendv_epi8(p0, p1, b01)); -} -inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) -{ - return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); -} - -/** Absolute difference **/ - -inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub_wrap(a, b); - v_int8x16 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ - return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); -} -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ - v_int32x4 d = v_sub(a, b); - v_int32x4 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub(a, b); - v_int8x16 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); - } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ -#if CV_FMA3 - return v_float32x4(_mm_fmadd_ps(a.val, b.val, c.val)); -#else - return v_float32x4(_mm_add_ps(_mm_mul_ps(a.val, b.val), c.val)); -#endif -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ -#if CV_FMA3 - return v_float64x2(_mm_fmadd_pd(a.val, b.val, c.val)); -#else - return v_float64x2(_mm_add_pd(_mm_mul_pd(a.val, b.val), c.val)); -#endif -} - -#define OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(_Tpvec, _Tp, _Tpreg, suffix, absmask_vec) \ -inline _Tpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpreg absmask = _mm_castsi128_##suffix(absmask_vec); \ - return _Tpvec(_mm_and_##suffix(_mm_sub_##suffix(a.val, b.val), absmask)); \ -} \ -inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpvec res = v_fma(a, a, v_mul(b, b)); \ - return _Tpvec(_mm_sqrt_##suffix(res.val)); \ -} \ -inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return v_fma(a, a, v_mul(b, b)); \ -} \ -inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ \ - return v_fma(a, b, c); \ -} - -OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float32x4, float, __m128, ps, _mm_set1_epi32((int)0x7fffffff)) -OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float64x2, double, __m128d, pd, _mm_srli_epi64(_mm_set1_epi32(-1), 1)) - -#define OPENCV_HAL_IMPL_SSE_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ -inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ -} \ -inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(srai(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shl(const _Tpuvec& a) \ -{ \ - return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shl(const _Tpsvec& a) \ -{ \ - return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shr(const _Tpuvec& a) \ -{ \ - return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shr(const _Tpsvec& a) \ -{ \ - return _Tpsvec(srai(a.val, imm)); \ -} - -OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint16x8, v_int16x8, epi16, _mm_srai_epi16) -OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint32x4, v_int32x4, epi32, _mm_srai_epi32) -OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint64x2, v_int64x2, epi64, v_srai_epi64) - -namespace hal_sse_internal -{ - template 16)), - bool is_first = (imm == 0), - bool is_half = (imm == 8), - bool is_second = (imm == 16), - bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> - class v_sse_palignr_u8_class; - - template - class v_sse_palignr_u8_class; - - template - class v_sse_palignr_u8_class - { - public: - inline __m128i operator()(const __m128i& a, const __m128i&) const - { - return a; - } - }; - - template - class v_sse_palignr_u8_class - { - public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - return _mm_unpacklo_epi64(_mm_unpackhi_epi64(a, a), b); - } - }; - - template - class v_sse_palignr_u8_class - { - public: - inline __m128i operator()(const __m128i&, const __m128i& b) const - { - return b; - } - }; - - template - class v_sse_palignr_u8_class - { -#if CV_SSSE3 - public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - return _mm_alignr_epi8(b, a, imm); - } -#else - public: - inline __m128i operator()(const __m128i& a, const __m128i& b) const - { - enum { imm2 = (sizeof(__m128i) - imm) }; - return _mm_or_si128(_mm_srli_si128(a, imm), _mm_slli_si128(b, imm2)); - } -#endif - }; - - template - inline __m128i v_sse_palignr_u8(const __m128i& a, const __m128i& b) - { - CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_sse_palignr_u8."); - return v_sse_palignr_u8_class()(a, b); - } -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a) -{ - using namespace hal_sse_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - _mm_srli_si128( - v_sse_reinterpret_as<__m128i>(a.val), imm2))); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a) -{ - using namespace hal_sse_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - _mm_slli_si128( - v_sse_reinterpret_as<__m128i>(a.val), imm2))); -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_sse_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - v_sse_palignr_u8( - v_sse_reinterpret_as<__m128i>(a.val), - v_sse_reinterpret_as<__m128i>(b.val)))); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_sse_internal; - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_sse_reinterpret_as( - v_sse_palignr_u8( - v_sse_reinterpret_as<__m128i>(b.val), - v_sse_reinterpret_as<__m128i>(a.val)))); -} - -#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(_Tpvec, _Tp) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(_mm_loadu_si128((const __m128i*)ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(_mm_load_si128((const __m128i*)ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(_mm_loadl_epi64((const __m128i*)ptr)); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - return _Tpvec(_mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ - _mm_loadl_epi64((const __m128i*)ptr1))); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storeu_si128((__m128i*)ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ _mm_store_si128((__m128i*)ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ _mm_stream_si128((__m128i*)ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ -{ \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm_storeu_si128((__m128i*)ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm_stream_si128((__m128i*)ptr, a.val); \ - else \ - _mm_store_si128((__m128i*)ptr, a.val); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storel_epi64((__m128i*)ptr, a.val); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a.val, a.val)); } - -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint8x16, uchar) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int8x16, schar) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint16x8, ushort) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int16x8, short) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint32x4, unsigned) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int32x4, int) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint64x2, uint64) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int64x2, int64) - -#define OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(_Tpvec, _Tp, suffix) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(_mm_loadu_##suffix(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(_mm_load_##suffix(ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(_mm_castsi128_##suffix(_mm_loadl_epi64((const __m128i*)ptr))); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - return _Tpvec(_mm_castsi128_##suffix( \ - _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ - _mm_loadl_epi64((const __m128i*)ptr1)))); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storeu_##suffix(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ _mm_store_##suffix(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ _mm_stream_##suffix(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ -{ \ - if( mode == hal::STORE_UNALIGNED ) \ - _mm_storeu_##suffix(ptr, a.val); \ - else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ - _mm_stream_##suffix(ptr, a.val); \ - else \ - _mm_store_##suffix(ptr, a.val); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ _mm_storel_epi64((__m128i*)ptr, _mm_cast##suffix##_si128(a.val)); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - __m128i a1 = _mm_cast##suffix##_si128(a.val); \ - _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a1, a1)); \ -} - -OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float32x4, float, ps) -OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float64x2, double, pd) - -inline unsigned v_reduce_sum(const v_uint8x16& a) -{ - __m128i half = _mm_sad_epu8(a.val, _mm_setzero_si128()); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); -} -inline int v_reduce_sum(const v_int8x16& a) -{ - __m128i half = _mm_set1_epi8((schar)-128); - half = _mm_sad_epu8(_mm_xor_si128(a.val, half), _mm_setzero_si128()); - return _mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))) - 2048; -} -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(func) \ -inline schar v_reduce_##func(const v_int8x16& a) \ -{ \ - __m128i val = a.val; \ - __m128i smask = _mm_set1_epi8((schar)-128); \ - val = _mm_xor_si128(val, smask); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ - return (schar)_mm_cvtsi128_si32(val) ^ (schar)-128; \ -} \ -inline uchar v_reduce_##func(const v_uint8x16& a) \ -{ \ - __m128i val = a.val; \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ - val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ - return (uchar)_mm_cvtsi128_si32(val); \ -} -OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(min) - -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(_Tpvec, scalartype, func, suffix, sbit) \ -inline scalartype v_reduce_##func(const v_##_Tpvec& a) \ -{ \ - __m128i val = a.val; \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ - return (scalartype)_mm_cvtsi128_si32(val); \ -} \ -inline unsigned scalartype v_reduce_##func(const v_u##_Tpvec& a) \ -{ \ - __m128i val = a.val; \ - __m128i smask = _mm_set1_epi16(sbit); \ - val = _mm_xor_si128(val, smask); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ - val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ - return (unsigned scalartype)(_mm_cvtsi128_si32(val) ^ sbit); \ -} -OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, max, epi16, (short)-32768) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, min, epi16, (short)-32768) - -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, cast_from, cast_to, extract) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - regtype val = a.val; \ - val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 8))); \ - val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 4))); \ - return (scalartype)_mm_cvt##extract(val); \ -} - -#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(_Tpvec, scalartype, func, scalar_func) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - scalartype CV_DECL_ALIGNED(16) buf[4]; \ - v_store_aligned(buf, a); \ - scalartype s0 = scalar_func(buf[0], buf[1]); \ - scalartype s1 = scalar_func(buf[2], buf[3]); \ - return scalar_func(s0, s1); \ -} - -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_uint32x4, unsigned, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_int32x4, int, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_float32x4, float, __m128, ps, _mm_castps_si128, _mm_castsi128_ps, ss_f32) - -inline int v_reduce_sum(const v_int16x8& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } -inline unsigned v_reduce_sum(const v_uint16x8& a) -{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ - uint64 CV_DECL_ALIGNED(32) idx[2]; - v_store_aligned(idx, a); - return idx[0] + idx[1]; -} -inline int64 v_reduce_sum(const v_int64x2& a) -{ - int64 CV_DECL_ALIGNED(32) idx[2]; - v_store_aligned(idx, a); - return idx[0] + idx[1]; -} -inline double v_reduce_sum(const v_float64x2& a) -{ - double CV_DECL_ALIGNED(32) idx[2]; - v_store_aligned(idx, a); - return idx[0] + idx[1]; -} - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ -#if CV_SSE3 - __m128 ab = _mm_hadd_ps(a.val, b.val); - __m128 cd = _mm_hadd_ps(c.val, d.val); - return v_float32x4(_mm_hadd_ps(ab, cd)); -#else - __m128 ac = _mm_add_ps(_mm_unpacklo_ps(a.val, c.val), _mm_unpackhi_ps(a.val, c.val)); - __m128 bd = _mm_add_ps(_mm_unpacklo_ps(b.val, d.val), _mm_unpackhi_ps(b.val, d.val)); - return v_float32x4(_mm_add_ps(_mm_unpacklo_ps(ac, bd), _mm_unpackhi_ps(ac, bd))); -#endif -} - -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, max, std::max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, min, std::min) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, max, std::max) -OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, min, std::min) - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - __m128i half = _mm_sad_epu8(a.val, b.val); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - __m128i half = _mm_set1_epi8(0x7f); - half = _mm_sad_epu8(_mm_add_epi8(a.val, half), _mm_add_epi8(b.val, half)); - return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} - -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ - __m128i m1 = _mm_set1_epi32(0x55555555); - __m128i m2 = _mm_set1_epi32(0x33333333); - __m128i m4 = _mm_set1_epi32(0x0f0f0f0f); - __m128i p = a.val; - p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 1), m1), _mm_and_si128(p, m1)); - p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 2), m2), _mm_and_si128(p, m2)); - p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 4), m4), _mm_and_si128(p, m4)); - return v_uint8x16(p); -} -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); -} -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); -} -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ - return v_uint64x2(_mm_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm_setzero_si128())); -} -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(_Tpvec, suffix, cast_op, allmask) \ -inline int v_signmask(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)); } \ -inline bool v_check_all(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) == allmask; } \ -inline bool v_check_any(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) != 0; } -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint8x16, epi8, OPENCV_HAL_NOP, 65535) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int8x16, epi8, OPENCV_HAL_NOP, 65535) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint32x4, ps, _mm_castsi128_ps, 15) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int32x4, ps, _mm_castsi128_ps, 15) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint64x2, pd, _mm_castsi128_pd, 3) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int64x2, pd, _mm_castsi128_pd, 3) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float32x4, ps, OPENCV_HAL_NOP, 15) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float64x2, pd, OPENCV_HAL_NOP, 3) - -#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(_Tpvec) \ -inline int v_signmask(const _Tpvec& a) { return _mm_movemask_epi8(_mm_packs_epi16(a.val, a.val)) & 255; } \ -inline bool v_check_all(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) == 0xaaaa; } \ -inline bool v_check_any(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) != 0; } -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_uint16x8) -OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_int16x8) - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -#if CV_SSE4_1 -#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, cast_ret, cast, suffix) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(cast_ret(_mm_blendv_##suffix(cast(b.val), cast(a.val), cast(mask.val)))); \ -} - -OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, _mm_castps_si128, _mm_castsi128_ps, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, _mm_castps_si128, _mm_castsi128_ps, ps) -// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, TBD, TBD, pd) -// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, TBD, TBD, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, OPENCV_HAL_NOP, OPENCV_HAL_NOP, pd) - -#else // CV_SSE4_1 - -#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, suffix) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(_mm_xor_##suffix(b.val, _mm_and_##suffix(_mm_xor_##suffix(b.val, a.val), mask.val))); \ -} - -OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, si128) -// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, si128) -// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, si128) -OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, ps) -OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, pd) -#endif - -/* Expand */ -#define OPENCV_HAL_IMPL_SSE_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ - inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ - { \ - b0.val = intrin(a.val); \ - b1.val = __CV_CAT(intrin, _high)(a.val); \ - } \ - inline _Tpwvec v_expand_low(const _Tpvec& a) \ - { return _Tpwvec(intrin(a.val)); } \ - inline _Tpwvec v_expand_high(const _Tpvec& a) \ - { return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ - inline _Tpwvec v_load_expand(const _Tp* ptr) \ - { \ - __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ - return _Tpwvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_SSE_EXPAND(v_uint8x16, v_uint16x8, uchar, _v128_cvtepu8_epi16) -OPENCV_HAL_IMPL_SSE_EXPAND(v_int8x16, v_int16x8, schar, _v128_cvtepi8_epi16) -OPENCV_HAL_IMPL_SSE_EXPAND(v_uint16x8, v_uint32x4, ushort, _v128_cvtepu16_epi32) -OPENCV_HAL_IMPL_SSE_EXPAND(v_int16x8, v_int32x4, short, _v128_cvtepi16_epi32) -OPENCV_HAL_IMPL_SSE_EXPAND(v_uint32x4, v_uint64x2, unsigned, _v128_cvtepu32_epi64) -OPENCV_HAL_IMPL_SSE_EXPAND(v_int32x4, v_int64x2, int, _v128_cvtepi32_epi64) - -#define OPENCV_HAL_IMPL_SSE_EXPAND_Q(_Tpvec, _Tp, intrin) \ - inline _Tpvec v_load_expand_q(const _Tp* ptr) \ - { \ - typedef int CV_DECL_ALIGNED(1) unaligned_int; \ - __m128i a = _mm_cvtsi32_si128(*(const unaligned_int*)ptr); \ - return _Tpvec(intrin(a)); \ - } - -OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_uint32x4, uchar, _v128_cvtepu8_epi32) -OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_int32x4, schar, _v128_cvtepi8_epi32) - -#define OPENCV_HAL_IMPL_SSE_UNPACKS(_Tpvec, suffix, cast_from, cast_to) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ -{ \ - b0.val = _mm_unpacklo_##suffix(a0.val, a1.val); \ - b1.val = _mm_unpackhi_##suffix(a0.val, a1.val); \ -} \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ - return _Tpvec(cast_to(_mm_unpacklo_epi64(a1, b1))); \ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ - return _Tpvec(cast_to(_mm_unpackhi_epi64(a1, b1))); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ - c.val = cast_to(_mm_unpacklo_epi64(a1, b1)); \ - d.val = cast_to(_mm_unpackhi_epi64(a1, b1)); \ -} - -OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_int8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_int16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) -OPENCV_HAL_IMPL_SSE_UNPACKS(v_float64x2, pd, _mm_castpd_si128, _mm_castsi128_pd) - -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ -#if CV_SSSE3 - static const __m128i perm = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); - return v_uint8x16(_mm_shuffle_epi8(a.val, perm)); -#else - uchar CV_DECL_ALIGNED(32) d[16]; - v_store_aligned(d, a); - return v_uint8x16(d[15], d[14], d[13], d[12], d[11], d[10], d[9], d[8], d[7], d[6], d[5], d[4], d[3], d[2], d[1], d[0]); -#endif -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ -#if CV_SSSE3 - static const __m128i perm = _mm_setr_epi8(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); - return v_uint16x8(_mm_shuffle_epi8(a.val, perm)); -#else - __m128i r = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3)); - r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); - r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); - return v_uint16x8(r); -#endif -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - return v_uint32x4(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3))); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - return v_uint64x2(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(1, 0, 3, 2))); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -template -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) -{ - return v_rotate_right(a, b); -} - -inline v_int32x4 v_round(const v_float32x4& a) -{ return v_int32x4(_mm_cvtps_epi32(a.val)); } - -inline v_int32x4 v_floor(const v_float32x4& a) -{ - __m128i a1 = _mm_cvtps_epi32(a.val); - __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(_mm_cvtepi32_ps(a1), a.val)); - return v_int32x4(_mm_add_epi32(a1, mask)); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - __m128i a1 = _mm_cvtps_epi32(a.val); - __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(a.val, _mm_cvtepi32_ps(a1))); - return v_int32x4(_mm_sub_epi32(a1, mask)); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(_mm_cvttps_epi32(a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a) -{ return v_int32x4(_mm_cvtpd_epi32(a.val)); } - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - __m128i ai = _mm_cvtpd_epi32(a.val), bi = _mm_cvtpd_epi32(b.val); - return v_int32x4(_mm_unpacklo_epi64(ai, bi)); -} - -inline v_int32x4 v_floor(const v_float64x2& a) -{ - __m128i a1 = _mm_cvtpd_epi32(a.val); - __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(_mm_cvtepi32_pd(a1), a.val)); - mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 - return v_int32x4(_mm_add_epi32(a1, mask)); -} - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ - __m128i a1 = _mm_cvtpd_epi32(a.val); - __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(a.val, _mm_cvtepi32_pd(a1))); - mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 - return v_int32x4(_mm_sub_epi32(a1, mask)); -} - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ return v_int32x4(_mm_cvttpd_epi32(a.val)); } - -#define OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, \ - _Tpvec& b2, _Tpvec& b3) \ -{ \ - __m128i t0 = cast_from(_mm_unpacklo_##suffix(a0.val, a1.val)); \ - __m128i t1 = cast_from(_mm_unpacklo_##suffix(a2.val, a3.val)); \ - __m128i t2 = cast_from(_mm_unpackhi_##suffix(a0.val, a1.val)); \ - __m128i t3 = cast_from(_mm_unpackhi_##suffix(a2.val, a3.val)); \ -\ - b0.val = cast_to(_mm_unpacklo_epi64(t0, t1)); \ - b1.val = cast_to(_mm_unpackhi_epi64(t0, t1)); \ - b2.val = cast_to(_mm_unpacklo_epi64(t2, t3)); \ - b3.val = cast_to(_mm_unpackhi_epi64(t2, t3)); \ -} - -OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) -OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) - -// load deinterleave -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) -{ - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - - __m128i t10 = _mm_unpacklo_epi8(t00, t01); - __m128i t11 = _mm_unpackhi_epi8(t00, t01); - - __m128i t20 = _mm_unpacklo_epi8(t10, t11); - __m128i t21 = _mm_unpackhi_epi8(t10, t11); - - __m128i t30 = _mm_unpacklo_epi8(t20, t21); - __m128i t31 = _mm_unpackhi_epi8(t20, t21); - - a.val = _mm_unpacklo_epi8(t30, t31); - b.val = _mm_unpackhi_epi8(t30, t31); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) -{ -#if CV_SSE4_1 - const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - __m128i s0 = _mm_loadu_si128((const __m128i*)ptr); - __m128i s1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - __m128i s2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); - __m128i a0 = _mm_blendv_epi8(_mm_blendv_epi8(s0, s1, m0), s2, m1); - __m128i b0 = _mm_blendv_epi8(_mm_blendv_epi8(s1, s2, m0), s0, m1); - __m128i c0 = _mm_blendv_epi8(_mm_blendv_epi8(s2, s0, m0), s1, m1); - const __m128i sh_b = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); - const __m128i sh_g = _mm_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14); - const __m128i sh_r = _mm_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); - a0 = _mm_shuffle_epi8(a0, sh_b); - b0 = _mm_shuffle_epi8(b0, sh_g); - c0 = _mm_shuffle_epi8(c0, sh_r); - a.val = a0; - b.val = b0; - c.val = c0; -#elif CV_SSSE3 - const __m128i m0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); - const __m128i m1 = _mm_alignr_epi8(m0, m0, 11); - const __m128i m2 = _mm_alignr_epi8(m0, m0, 6); - - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); - - __m128i s0 = _mm_shuffle_epi8(t0, m0); - __m128i s1 = _mm_shuffle_epi8(t1, m1); - __m128i s2 = _mm_shuffle_epi8(t2, m2); - - t0 = _mm_alignr_epi8(s1, _mm_slli_si128(s0, 10), 5); - a.val = _mm_alignr_epi8(s2, t0, 5); - - t1 = _mm_alignr_epi8(_mm_srli_si128(s1, 5), _mm_slli_si128(s0, 5), 6); - b.val = _mm_alignr_epi8(_mm_srli_si128(s2, 5), t1, 5); - - t2 = _mm_alignr_epi8(_mm_srli_si128(s2, 10), s1, 11); - c.val = _mm_alignr_epi8(t2, s0, 11); -#else - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 32)); - - __m128i t10 = _mm_unpacklo_epi8(t00, _mm_unpackhi_epi64(t01, t01)); - __m128i t11 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t00, t00), t02); - __m128i t12 = _mm_unpacklo_epi8(t01, _mm_unpackhi_epi64(t02, t02)); - - __m128i t20 = _mm_unpacklo_epi8(t10, _mm_unpackhi_epi64(t11, t11)); - __m128i t21 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t10, t10), t12); - __m128i t22 = _mm_unpacklo_epi8(t11, _mm_unpackhi_epi64(t12, t12)); - - __m128i t30 = _mm_unpacklo_epi8(t20, _mm_unpackhi_epi64(t21, t21)); - __m128i t31 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t20, t20), t22); - __m128i t32 = _mm_unpacklo_epi8(t21, _mm_unpackhi_epi64(t22, t22)); - - a.val = _mm_unpacklo_epi8(t30, _mm_unpackhi_epi64(t31, t31)); - b.val = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t30, t30), t32); - c.val = _mm_unpacklo_epi8(t31, _mm_unpackhi_epi64(t32, t32)); -#endif -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) -{ - __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... - __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... - __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); // a8 b8 c8 d8 ... - __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 48)); // a12 b12 c12 d12 ... - - __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 a8 b0 b8 ... - __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a2 a10 b2 b10 ... - __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a4 a12 b4 b12 ... - __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a6 a14 b6 b14 ... - - u0 = _mm_unpacklo_epi8(v0, v2); // a0 a4 a8 a12 ... - u1 = _mm_unpacklo_epi8(v1, v3); // a2 a6 a10 a14 ... - u2 = _mm_unpackhi_epi8(v0, v2); // a1 a5 a9 a13 ... - u3 = _mm_unpackhi_epi8(v1, v3); // a3 a7 a11 a15 ... - - v0 = _mm_unpacklo_epi8(u0, u1); // a0 a2 a4 a6 ... - v1 = _mm_unpacklo_epi8(u2, u3); // a1 a3 a5 a7 ... - v2 = _mm_unpackhi_epi8(u0, u1); // c0 c2 c4 c6 ... - v3 = _mm_unpackhi_epi8(u2, u3); // c1 c3 c5 c7 ... - - a.val = _mm_unpacklo_epi8(v0, v1); - b.val = _mm_unpackhi_epi8(v0, v1); - c.val = _mm_unpacklo_epi8(v2, v3); - d.val = _mm_unpackhi_epi8(v2, v3); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) -{ - __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 a2 b2 a3 b3 - __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); // a4 b4 a5 b5 a6 b6 a7 b7 - - __m128i v2 = _mm_unpacklo_epi16(v0, v1); // a0 a4 b0 b4 a1 a5 b1 b5 - __m128i v3 = _mm_unpackhi_epi16(v0, v1); // a2 a6 b2 b6 a3 a7 b3 b7 - __m128i v4 = _mm_unpacklo_epi16(v2, v3); // a0 a2 a4 a6 b0 b2 b4 b6 - __m128i v5 = _mm_unpackhi_epi16(v2, v3); // a1 a3 a5 a7 b1 b3 b5 b7 - - a.val = _mm_unpacklo_epi16(v4, v5); // a0 a1 a2 a3 a4 a5 a6 a7 - b.val = _mm_unpackhi_epi16(v4, v5); // b0 b1 ab b3 b4 b5 b6 b7 -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) -{ -#if CV_SSE4_1 - __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); - __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); - __m128i v2 = _mm_loadu_si128((__m128i*)(ptr + 16)); - __m128i a0 = _mm_blend_epi16(_mm_blend_epi16(v0, v1, 0x92), v2, 0x24); - __m128i b0 = _mm_blend_epi16(_mm_blend_epi16(v2, v0, 0x92), v1, 0x24); - __m128i c0 = _mm_blend_epi16(_mm_blend_epi16(v1, v2, 0x92), v0, 0x24); - - const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m128i sh_b = _mm_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); - const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - a0 = _mm_shuffle_epi8(a0, sh_a); - b0 = _mm_shuffle_epi8(b0, sh_b); - c0 = _mm_shuffle_epi8(c0, sh_c); - - a.val = a0; - b.val = b0; - c.val = c0; -#else - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 8)); - __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 16)); - - __m128i t10 = _mm_unpacklo_epi16(t00, _mm_unpackhi_epi64(t01, t01)); - __m128i t11 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t00, t00), t02); - __m128i t12 = _mm_unpacklo_epi16(t01, _mm_unpackhi_epi64(t02, t02)); - - __m128i t20 = _mm_unpacklo_epi16(t10, _mm_unpackhi_epi64(t11, t11)); - __m128i t21 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t10, t10), t12); - __m128i t22 = _mm_unpacklo_epi16(t11, _mm_unpackhi_epi64(t12, t12)); - - a.val = _mm_unpacklo_epi16(t20, _mm_unpackhi_epi64(t21, t21)); - b.val = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t20, t20), t22); - c.val = _mm_unpacklo_epi16(t21, _mm_unpackhi_epi64(t22, t22)); -#endif -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) -{ - __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 - __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 8)); // a2 b2 c2 d2 ... - __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... - __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 24)); // a6 b6 c6 d6 ... - - __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 a4 b0 b4 ... - __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a1 a5 b1 b5 ... - __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a2 a6 b2 b6 ... - __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a3 a7 b3 b7 ... - - u0 = _mm_unpacklo_epi16(v0, v2); // a0 a2 a4 a6 ... - u1 = _mm_unpacklo_epi16(v1, v3); // a1 a3 a5 a7 ... - u2 = _mm_unpackhi_epi16(v0, v2); // c0 c2 c4 c6 ... - u3 = _mm_unpackhi_epi16(v1, v3); // c1 c3 c5 c7 ... - - a.val = _mm_unpacklo_epi16(u0, u1); - b.val = _mm_unpackhi_epi16(u0, u1); - c.val = _mm_unpacklo_epi16(u2, u3); - d.val = _mm_unpackhi_epi16(u2, u3); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) -{ - __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 - __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 4)); // a2 b2 a3 b3 - - __m128i v2 = _mm_unpacklo_epi32(v0, v1); // a0 a2 b0 b2 - __m128i v3 = _mm_unpackhi_epi32(v0, v1); // a1 a3 b1 b3 - - a.val = _mm_unpacklo_epi32(v2, v3); // a0 a1 a2 a3 - b.val = _mm_unpackhi_epi32(v2, v3); // b0 b1 ab b3 -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) -{ - __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 4)); - __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 8)); - - __m128i t10 = _mm_unpacklo_epi32(t00, _mm_unpackhi_epi64(t01, t01)); - __m128i t11 = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t00, t00), t02); - __m128i t12 = _mm_unpacklo_epi32(t01, _mm_unpackhi_epi64(t02, t02)); - - a.val = _mm_unpacklo_epi32(t10, _mm_unpackhi_epi64(t11, t11)); - b.val = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t10, t10), t12); - c.val = _mm_unpacklo_epi32(t11, _mm_unpackhi_epi64(t12, t12)); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) -{ - v_uint32x4 s0(_mm_loadu_si128((const __m128i*)ptr)); // a0 b0 c0 d0 - v_uint32x4 s1(_mm_loadu_si128((const __m128i*)(ptr + 4))); // a1 b1 c1 d1 - v_uint32x4 s2(_mm_loadu_si128((const __m128i*)(ptr + 8))); // a2 b2 c2 d2 - v_uint32x4 s3(_mm_loadu_si128((const __m128i*)(ptr + 12))); // a3 b3 c3 d3 - - v_transpose4x4(s0, s1, s2, s3, a, b, c, d); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) -{ - __m128 u0 = _mm_loadu_ps(ptr); // a0 b0 a1 b1 - __m128 u1 = _mm_loadu_ps((ptr + 4)); // a2 b2 a3 b3 - - a.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); // a0 a1 a2 a3 - b.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(3, 1, 3, 1)); // b0 b1 ab b3 -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) -{ - __m128 t0 = _mm_loadu_ps(ptr + 0); - __m128 t1 = _mm_loadu_ps(ptr + 4); - __m128 t2 = _mm_loadu_ps(ptr + 8); - - __m128 at12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 1, 0, 2)); - a.val = _mm_shuffle_ps(t0, at12, _MM_SHUFFLE(2, 0, 3, 0)); - - __m128 bt01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 0, 0, 1)); - __m128 bt12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 2, 0, 3)); - b.val = _mm_shuffle_ps(bt01, bt12, _MM_SHUFFLE(2, 0, 2, 0)); - - __m128 ct01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 1, 0, 2)); - c.val = _mm_shuffle_ps(ct01, t2, _MM_SHUFFLE(3, 0, 2, 0)); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) -{ - __m128 t0 = _mm_loadu_ps(ptr + 0); - __m128 t1 = _mm_loadu_ps(ptr + 4); - __m128 t2 = _mm_loadu_ps(ptr + 8); - __m128 t3 = _mm_loadu_ps(ptr + 12); - __m128 t02lo = _mm_unpacklo_ps(t0, t2); - __m128 t13lo = _mm_unpacklo_ps(t1, t3); - __m128 t02hi = _mm_unpackhi_ps(t0, t2); - __m128 t13hi = _mm_unpackhi_ps(t1, t3); - a.val = _mm_unpacklo_ps(t02lo, t13lo); - b.val = _mm_unpackhi_ps(t02lo, t13lo); - c.val = _mm_unpacklo_ps(t02hi, t13hi); - d.val = _mm_unpackhi_ps(t02hi, t13hi); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) -{ - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); - - a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); - b = v_uint64x2(_mm_unpackhi_epi64(t0, t1)); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) -{ - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0, b0 - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0, a1 - __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // b1, c1 - - t1 = _mm_shuffle_epi32(t1, 0x4e); // a1, c0 - - a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); - b = v_uint64x2(_mm_unpacklo_epi64(_mm_unpackhi_epi64(t0, t0), t2)); - c = v_uint64x2(_mm_unpackhi_epi64(t1, t2)); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, - v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) -{ - __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 - __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0 d0 - __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // a1 b1 - __m128i t3 = _mm_loadu_si128((const __m128i*)(ptr + 6)); // c1 d1 - - a = v_uint64x2(_mm_unpacklo_epi64(t0, t2)); - b = v_uint64x2(_mm_unpackhi_epi64(t0, t2)); - c = v_uint64x2(_mm_unpacklo_epi64(t1, t3)); - d = v_uint64x2(_mm_unpackhi_epi64(t1, t3)); -} - -// store interleave - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi8(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi8(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 16), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 16), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 16), v1); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ -#if CV_SSE4_1 - const __m128i sh_a = _mm_setr_epi8(0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); - const __m128i sh_b = _mm_setr_epi8(5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); - const __m128i sh_c = _mm_setr_epi8(10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); - __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); - __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); - __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); - - const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); - const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); - __m128i v0 = _mm_blendv_epi8(_mm_blendv_epi8(a0, b0, m1), c0, m0); - __m128i v1 = _mm_blendv_epi8(_mm_blendv_epi8(b0, c0, m1), a0, m0); - __m128i v2 = _mm_blendv_epi8(_mm_blendv_epi8(c0, a0, m1), b0, m0); -#elif CV_SSSE3 - const __m128i m0 = _mm_setr_epi8(0, 6, 11, 1, 7, 12, 2, 8, 13, 3, 9, 14, 4, 10, 15, 5); - const __m128i m1 = _mm_setr_epi8(5, 11, 0, 6, 12, 1, 7, 13, 2, 8, 14, 3, 9, 15, 4, 10); - const __m128i m2 = _mm_setr_epi8(10, 0, 5, 11, 1, 6, 12, 2, 7, 13, 3, 8, 14, 4, 9, 15); - - __m128i t0 = _mm_alignr_epi8(b.val, _mm_slli_si128(a.val, 10), 5); - t0 = _mm_alignr_epi8(c.val, t0, 5); - __m128i v0 = _mm_shuffle_epi8(t0, m0); - - __m128i t1 = _mm_alignr_epi8(_mm_srli_si128(b.val, 5), _mm_slli_si128(a.val, 5), 6); - t1 = _mm_alignr_epi8(_mm_srli_si128(c.val, 5), t1, 5); - __m128i v1 = _mm_shuffle_epi8(t1, m1); - - __m128i t2 = _mm_alignr_epi8(_mm_srli_si128(c.val, 10), b.val, 11); - t2 = _mm_alignr_epi8(t2, a.val, 11); - __m128i v2 = _mm_shuffle_epi8(t2, m2); -#else - __m128i z = _mm_setzero_si128(); - __m128i ab0 = _mm_unpacklo_epi8(a.val, b.val); - __m128i ab1 = _mm_unpackhi_epi8(a.val, b.val); - __m128i c0 = _mm_unpacklo_epi8(c.val, z); - __m128i c1 = _mm_unpackhi_epi8(c.val, z); - - __m128i p00 = _mm_unpacklo_epi16(ab0, c0); - __m128i p01 = _mm_unpackhi_epi16(ab0, c0); - __m128i p02 = _mm_unpacklo_epi16(ab1, c1); - __m128i p03 = _mm_unpackhi_epi16(ab1, c1); - - __m128i p10 = _mm_unpacklo_epi32(p00, p01); - __m128i p11 = _mm_unpackhi_epi32(p00, p01); - __m128i p12 = _mm_unpacklo_epi32(p02, p03); - __m128i p13 = _mm_unpackhi_epi32(p02, p03); - - __m128i p20 = _mm_unpacklo_epi64(p10, p11); - __m128i p21 = _mm_unpackhi_epi64(p10, p11); - __m128i p22 = _mm_unpacklo_epi64(p12, p13); - __m128i p23 = _mm_unpackhi_epi64(p12, p13); - - p20 = _mm_slli_si128(p20, 1); - p22 = _mm_slli_si128(p22, 1); - - __m128i p30 = _mm_slli_epi64(_mm_unpacklo_epi32(p20, p21), 8); - __m128i p31 = _mm_srli_epi64(_mm_unpackhi_epi32(p20, p21), 8); - __m128i p32 = _mm_slli_epi64(_mm_unpacklo_epi32(p22, p23), 8); - __m128i p33 = _mm_srli_epi64(_mm_unpackhi_epi32(p22, p23), 8); - - __m128i p40 = _mm_unpacklo_epi64(p30, p31); - __m128i p41 = _mm_unpackhi_epi64(p30, p31); - __m128i p42 = _mm_unpacklo_epi64(p32, p33); - __m128i p43 = _mm_unpackhi_epi64(p32, p33); - - __m128i v0 = _mm_or_si128(_mm_srli_si128(p40, 2), _mm_slli_si128(p41, 10)); - __m128i v1 = _mm_or_si128(_mm_srli_si128(p41, 6), _mm_slli_si128(p42, 6)); - __m128i v2 = _mm_or_si128(_mm_srli_si128(p42, 10), _mm_slli_si128(p43, 2)); -#endif - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 16), v1); - _mm_stream_si128((__m128i*)(ptr + 32), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 16), v1); - _mm_store_si128((__m128i*)(ptr + 32), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 16), v1); - _mm_storeu_si128((__m128i*)(ptr + 32), v2); - } -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, const v_uint8x16& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - __m128i u0 = _mm_unpacklo_epi8(a.val, c.val); // a0 c0 a1 c1 ... - __m128i u1 = _mm_unpackhi_epi8(a.val, c.val); // a8 c8 a9 c9 ... - __m128i u2 = _mm_unpacklo_epi8(b.val, d.val); // b0 d0 b1 d1 ... - __m128i u3 = _mm_unpackhi_epi8(b.val, d.val); // b8 d8 b9 d9 ... - - __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 b0 c0 d0 ... - __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a4 b4 c4 d4 ... - __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a8 b8 c8 d8 ... - __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a12 b12 c12 d12 ... - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 16), v1); - _mm_stream_si128((__m128i*)(ptr + 32), v2); - _mm_stream_si128((__m128i*)(ptr + 48), v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 16), v1); - _mm_store_si128((__m128i*)(ptr + 32), v2); - _mm_store_si128((__m128i*)(ptr + 48), v3); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 16), v1); - _mm_storeu_si128((__m128i*)(ptr + 32), v2); - _mm_storeu_si128((__m128i*)(ptr + 48), v3); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi16(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi16(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 8), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 8), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 8), v1); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, - const v_uint16x8& b, const v_uint16x8& c, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ -#if CV_SSE4_1 - const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); - const __m128i sh_b = _mm_setr_epi8(10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); - const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); - __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); - __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); - __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); - - __m128i v0 = _mm_blend_epi16(_mm_blend_epi16(a0, b0, 0x92), c0, 0x24); - __m128i v1 = _mm_blend_epi16(_mm_blend_epi16(c0, a0, 0x92), b0, 0x24); - __m128i v2 = _mm_blend_epi16(_mm_blend_epi16(b0, c0, 0x92), a0, 0x24); -#else - __m128i z = _mm_setzero_si128(); - __m128i ab0 = _mm_unpacklo_epi16(a.val, b.val); - __m128i ab1 = _mm_unpackhi_epi16(a.val, b.val); - __m128i c0 = _mm_unpacklo_epi16(c.val, z); - __m128i c1 = _mm_unpackhi_epi16(c.val, z); - - __m128i p10 = _mm_unpacklo_epi32(ab0, c0); - __m128i p11 = _mm_unpackhi_epi32(ab0, c0); - __m128i p12 = _mm_unpacklo_epi32(ab1, c1); - __m128i p13 = _mm_unpackhi_epi32(ab1, c1); - - __m128i p20 = _mm_unpacklo_epi64(p10, p11); - __m128i p21 = _mm_unpackhi_epi64(p10, p11); - __m128i p22 = _mm_unpacklo_epi64(p12, p13); - __m128i p23 = _mm_unpackhi_epi64(p12, p13); - - p20 = _mm_slli_si128(p20, 2); - p22 = _mm_slli_si128(p22, 2); - - __m128i p30 = _mm_unpacklo_epi64(p20, p21); - __m128i p31 = _mm_unpackhi_epi64(p20, p21); - __m128i p32 = _mm_unpacklo_epi64(p22, p23); - __m128i p33 = _mm_unpackhi_epi64(p22, p23); - - __m128i v0 = _mm_or_si128(_mm_srli_si128(p30, 2), _mm_slli_si128(p31, 10)); - __m128i v1 = _mm_or_si128(_mm_srli_si128(p31, 6), _mm_slli_si128(p32, 6)); - __m128i v2 = _mm_or_si128(_mm_srli_si128(p32, 10), _mm_slli_si128(p33, 2)); -#endif - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 8), v1); - _mm_stream_si128((__m128i*)(ptr + 16), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 8), v1); - _mm_store_si128((__m128i*)(ptr + 16), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 8), v1); - _mm_storeu_si128((__m128i*)(ptr + 16), v2); - } -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - const v_uint16x8& c, const v_uint16x8& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - __m128i u0 = _mm_unpacklo_epi16(a.val, c.val); // a0 c0 a1 c1 ... - __m128i u1 = _mm_unpackhi_epi16(a.val, c.val); // a4 c4 a5 c5 ... - __m128i u2 = _mm_unpacklo_epi16(b.val, d.val); // b0 d0 b1 d1 ... - __m128i u3 = _mm_unpackhi_epi16(b.val, d.val); // b4 d4 b5 d5 ... - - __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 b0 c0 d0 ... - __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a2 b2 c2 d2 ... - __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a4 b4 c4 d4 ... - __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a6 b6 c6 d6 ... - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 8), v1); - _mm_stream_si128((__m128i*)(ptr + 16), v2); - _mm_stream_si128((__m128i*)(ptr + 24), v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 8), v1); - _mm_store_si128((__m128i*)(ptr + 16), v2); - _mm_store_si128((__m128i*)(ptr + 24), v3); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 8), v1); - _mm_storeu_si128((__m128i*)(ptr + 16), v2); - _mm_storeu_si128((__m128i*)(ptr + 24), v3); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 4), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 4), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 4), v1); - } -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - v_uint32x4 z = v_setzero_u32(), u0, u1, u2, u3; - v_transpose4x4(a, b, c, z, u0, u1, u2, u3); - - __m128i v0 = _mm_or_si128(u0.val, _mm_slli_si128(u1.val, 12)); - __m128i v1 = _mm_or_si128(_mm_srli_si128(u1.val, 4), _mm_slli_si128(u2.val, 8)); - __m128i v2 = _mm_or_si128(_mm_srli_si128(u2.val, 8), _mm_slli_si128(u3.val, 4)); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 4), v1); - _mm_stream_si128((__m128i*)(ptr + 8), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 4), v1); - _mm_store_si128((__m128i*)(ptr + 8), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 4), v1); - _mm_storeu_si128((__m128i*)(ptr + 8), v2); - } -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - v_uint32x4 v0, v1, v2, v3; - v_transpose4x4(a, b, c, d, v0, v1, v2, v3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0.val); - _mm_stream_si128((__m128i*)(ptr + 4), v1.val); - _mm_stream_si128((__m128i*)(ptr + 8), v2.val); - _mm_stream_si128((__m128i*)(ptr + 12), v3.val); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0.val); - _mm_store_si128((__m128i*)(ptr + 4), v1.val); - _mm_store_si128((__m128i*)(ptr + 8), v2.val); - _mm_store_si128((__m128i*)(ptr + 12), v3.val); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0.val); - _mm_storeu_si128((__m128i*)(ptr + 4), v1.val); - _mm_storeu_si128((__m128i*)(ptr + 8), v2.val); - _mm_storeu_si128((__m128i*)(ptr + 12), v3.val); - } -} - -// 2-channel, float only -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128 v0 = _mm_unpacklo_ps(a.val, b.val); // a0 b0 a1 b1 - __m128 v1 = _mm_unpackhi_ps(a.val, b.val); // a2 b2 a3 b3 - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_ps(ptr, v0); - _mm_stream_ps(ptr + 4, v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_ps(ptr, v0); - _mm_store_ps(ptr + 4, v1); - } - else - { - _mm_storeu_ps(ptr, v0); - _mm_storeu_ps(ptr + 4, v1); - } -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128 u0 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(0, 0, 0, 0)); - __m128 u1 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(1, 1, 0, 0)); - __m128 v0 = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); - __m128 u2 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(1, 1, 1, 1)); - __m128 u3 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(2, 2, 2, 2)); - __m128 v1 = _mm_shuffle_ps(u2, u3, _MM_SHUFFLE(2, 0, 2, 0)); - __m128 u4 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(3, 3, 2, 2)); - __m128 u5 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(3, 3, 3, 3)); - __m128 v2 = _mm_shuffle_ps(u4, u5, _MM_SHUFFLE(2, 0, 2, 0)); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_ps(ptr, v0); - _mm_stream_ps(ptr + 4, v1); - _mm_stream_ps(ptr + 8, v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_ps(ptr, v0); - _mm_store_ps(ptr + 4, v1); - _mm_store_ps(ptr + 8, v2); - } - else - { - _mm_storeu_ps(ptr, v0); - _mm_storeu_ps(ptr + 4, v1); - _mm_storeu_ps(ptr + 8, v2); - } -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128 u0 = _mm_unpacklo_ps(a.val, c.val); - __m128 u1 = _mm_unpacklo_ps(b.val, d.val); - __m128 u2 = _mm_unpackhi_ps(a.val, c.val); - __m128 u3 = _mm_unpackhi_ps(b.val, d.val); - __m128 v0 = _mm_unpacklo_ps(u0, u1); - __m128 v2 = _mm_unpacklo_ps(u2, u3); - __m128 v1 = _mm_unpackhi_ps(u0, u1); - __m128 v3 = _mm_unpackhi_ps(u2, u3); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_ps(ptr, v0); - _mm_stream_ps(ptr + 4, v1); - _mm_stream_ps(ptr + 8, v2); - _mm_stream_ps(ptr + 12, v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_ps(ptr, v0); - _mm_store_ps(ptr + 4, v1); - _mm_store_ps(ptr + 8, v2); - _mm_store_ps(ptr + 12, v3); - } - else - { - _mm_storeu_ps(ptr, v0); - _mm_storeu_ps(ptr + 4, v1); - _mm_storeu_ps(ptr + 8, v2); - _mm_storeu_ps(ptr + 12, v3); - } -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); - __m128i v1 = _mm_unpackhi_epi64(a.val, b.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 2), v1); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 2), v1); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 2), v1); - } -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); - __m128i v1 = _mm_unpacklo_epi64(c.val, _mm_unpackhi_epi64(a.val, a.val)); - __m128i v2 = _mm_unpackhi_epi64(b.val, c.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 2), v1); - _mm_stream_si128((__m128i*)(ptr + 4), v2); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 2), v1); - _mm_store_si128((__m128i*)(ptr + 4), v2); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 2), v1); - _mm_storeu_si128((__m128i*)(ptr + 4), v2); - } -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, const v_uint64x2& d, - hal::StoreMode mode = hal::STORE_UNALIGNED) -{ - __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); - __m128i v1 = _mm_unpacklo_epi64(c.val, d.val); - __m128i v2 = _mm_unpackhi_epi64(a.val, b.val); - __m128i v3 = _mm_unpackhi_epi64(c.val, d.val); - - if( mode == hal::STORE_ALIGNED_NOCACHE ) - { - _mm_stream_si128((__m128i*)(ptr), v0); - _mm_stream_si128((__m128i*)(ptr + 2), v1); - _mm_stream_si128((__m128i*)(ptr + 4), v2); - _mm_stream_si128((__m128i*)(ptr + 6), v3); - } - else if( mode == hal::STORE_ALIGNED ) - { - _mm_store_si128((__m128i*)(ptr), v0); - _mm_store_si128((__m128i*)(ptr + 2), v1); - _mm_store_si128((__m128i*)(ptr + 4), v2); - _mm_store_si128((__m128i*)(ptr + 6), v3); - } - else - { - _mm_storeu_si128((__m128i*)(ptr), v0); - _mm_storeu_si128((__m128i*)(ptr + 2), v1); - _mm_storeu_si128((__m128i*)(ptr + 4), v2); - _mm_storeu_si128((__m128i*)(ptr + 6), v3); - } -} - -#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(_mm_cvtepi32_ps(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - return v_float32x4(_mm_cvtpd_ps(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - return v_float32x4(_mm_movelh_ps(_mm_cvtpd_ps(a.val), _mm_cvtpd_ps(b.val))); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ - return v_float64x2(_mm_cvtepi32_pd(a.val)); -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ - return v_float64x2(_mm_cvtepi32_pd(_mm_srli_si128(a.val,8))); -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - return v_float64x2(_mm_cvtps_pd(a.val)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - return v_float64x2(_mm_cvtps_pd(_mm_movehl_ps(a.val, a.val))); -} - -// from (Mysticial and wim) https://stackoverflow.com/q/41144668 -inline v_float64x2 v_cvt_f64(const v_int64x2& v) -{ - // constants encoded as floating-point - __m128i magic_i_hi32 = _mm_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 - __m128i magic_i_all = _mm_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 - __m128d magic_d_all = _mm_castsi128_pd(magic_i_all); - // Blend the 32 lowest significant bits of v with magic_int_lo -#if CV_SSE4_1 - __m128i magic_i_lo = _mm_set1_epi64x(0x4330000000000000); // 2^52 - __m128i v_lo = _mm_blend_epi16(v.val, magic_i_lo, 0xcc); -#else - __m128i magic_i_lo = _mm_set1_epi32(0x43300000); // 2^52 - __m128i v_lo = _mm_unpacklo_epi32(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(0, 0, 2, 0)), magic_i_lo); -#endif - // Extract the 32 most significant bits of v - __m128i v_hi = _mm_srli_epi64(v.val, 32); - // Flip the msb of v_hi and blend with 0x45300000 - v_hi = _mm_xor_si128(v_hi, magic_i_hi32); - // Compute in double precision - __m128d v_hi_dbl = _mm_sub_pd(_mm_castsi128_pd(v_hi), magic_d_all); - // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition - __m128d result = _mm_add_pd(v_hi_dbl, _mm_castsi128_pd(v_lo)); - return v_float64x2(result); -} - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int8x16(_mm_setr_epi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); -#else - return v_int8x16(_mm_setr_epi64( - _mm_setr_pi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]]), - _mm_setr_pi8(tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]) - )); -#endif -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int8x16(_mm_setr_epi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), - *(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); -#else - return v_int8x16(_mm_setr_epi64( - _mm_setr_pi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3])), - _mm_setr_pi16(*(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7])) - )); -#endif -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int8x16(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -#else - return v_int8x16(_mm_setr_epi64( - _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), - _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) - )); -#endif -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int16x8(_mm_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); -#else - return v_int16x8(_mm_setr_epi64( - _mm_setr_pi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]), - _mm_setr_pi16(tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]) - )); -#endif -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int16x8(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), - *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -#else - return v_int16x8(_mm_setr_epi64( - _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), - _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) - )); -#endif -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ -#if defined(_MSC_VER) - return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], - tab[idx[2]], tab[idx[3]])); -#else - return v_int32x4(_mm_setr_epi64( - _mm_setr_pi32(tab[idx[0]], tab[idx[1]]), - _mm_setr_pi32(tab[idx[2]], tab[idx[3]]) - )); -#endif -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(_mm_set_epi64x(tab[idx[1]], tab[idx[0]])); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_float64x2(_mm_castsi128_pd(_mm_loadu_si128((const __m128i*)(tab + idx[0])))); } - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - int idx[2]; - v_store_low(idx, idxvec); - return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); -} - -// loads pairs from the table and deinterleaves them, e.g. returns: -// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), -// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) -// note that the indices are float's indices, not the float-pair indices. -// in theory, this function can be used to implement bilinear interpolation, -// when idxvec are the offsets within the image. -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - int CV_DECL_ALIGNED(32) idx[4]; - v_store_aligned(idx, idxvec); - __m128 z = _mm_setzero_ps(); - __m128 xy01 = _mm_loadl_pi(z, (__m64*)(tab + idx[0])); - __m128 xy23 = _mm_loadl_pi(z, (__m64*)(tab + idx[2])); - xy01 = _mm_loadh_pi(xy01, (__m64*)(tab + idx[1])); - xy23 = _mm_loadh_pi(xy23, (__m64*)(tab + idx[3])); - __m128 xxyy02 = _mm_unpacklo_ps(xy01, xy23); - __m128 xxyy13 = _mm_unpackhi_ps(xy01, xy23); - x = v_float32x4(_mm_unpacklo_ps(xxyy02, xxyy13)); - y = v_float32x4(_mm_unpackhi_ps(xxyy02, xxyy13)); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - int idx[2]; - v_store_low(idx, idxvec); - __m128d xy0 = _mm_loadu_pd(tab + idx[0]); - __m128d xy1 = _mm_loadu_pd(tab + idx[1]); - x = v_float64x2(_mm_unpacklo_pd(xy0, xy1)); - y = v_float64x2(_mm_unpackhi_pd(xy0, xy1)); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ -#if CV_SSSE3 - return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200))); -#else - __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); - a = _mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0)); - a = _mm_shuffle_epi32(a, _MM_SHUFFLE(3, 1, 2, 0)); - return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); -#endif -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ -#if CV_SSSE3 - return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400))); -#else - __m128i a = _mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); - return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); -#endif -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ -#if CV_SSSE3 - return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100))); -#else - __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); - return v_int16x8(_mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0))); -#endif -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ -#if CV_SSSE3 - return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100))); -#else - return v_int16x8(_mm_unpacklo_epi16(vec.val, _mm_unpackhi_epi64(vec.val, vec.val))); -#endif -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - return v_int32x4(_mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ -#if CV_SSSE3 - return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))); -#else - __m128i mask = _mm_set1_epi64x(0x00000000FFFFFFFF); - __m128i a = _mm_srli_si128(_mm_or_si128(_mm_andnot_si128(mask, vec.val), _mm_and_si128(mask, _mm_sll_epi32(vec.val, _mm_set_epi64x(0, 8)))), 1); - return v_int8x16(_mm_srli_si128(_mm_shufflelo_epi16(a, _MM_SHUFFLE(2, 1, 0, 3)), 2)); -#endif -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ -#if CV_SSSE3 - return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))); -#else - return v_int16x8(_mm_srli_si128(_mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(2, 1, 0, 3)), 2)); -#endif -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -template -inline uchar v_extract_n(const v_uint8x16& v) -{ -#if CV_SSE4_1 - return (uchar)_mm_extract_epi8(v.val, i); -#else - return v_rotate_right(v).get0(); -#endif -} - -template -inline schar v_extract_n(const v_int8x16& v) -{ - return (schar)v_extract_n(v_reinterpret_as_u8(v)); -} - -template -inline ushort v_extract_n(const v_uint16x8& v) -{ - return (ushort)_mm_extract_epi16(v.val, i); -} - -template -inline short v_extract_n(const v_int16x8& v) -{ - return (short)v_extract_n(v_reinterpret_as_u16(v)); -} - -template -inline uint v_extract_n(const v_uint32x4& v) -{ -#if CV_SSE4_1 - return (uint)_mm_extract_epi32(v.val, i); -#else - return v_rotate_right(v).get0(); -#endif -} - -template -inline int v_extract_n(const v_int32x4& v) -{ - return (int)v_extract_n(v_reinterpret_as_u32(v)); -} - -template -inline uint64 v_extract_n(const v_uint64x2& v) -{ -#ifdef CV__SIMD_NATIVE_mm_extract_epi64 - return (uint64)_v128_extract_epi64(v.val); -#else - return v_rotate_right(v).get0(); -#endif -} - -template -inline int64 v_extract_n(const v_int64x2& v) -{ - return (int64)v_extract_n(v_reinterpret_as_u64(v)); -} - -template -inline float v_extract_n(const v_float32x4& v) -{ - union { uint iv; float fv; } d; - d.iv = v_extract_n(v_reinterpret_as_u32(v)); - return d.fv; -} - -template -inline double v_extract_n(const v_float64x2& v) -{ - union { uint64 iv; double dv; } d; - d.iv = v_extract_n(v_reinterpret_as_u64(v)); - return d.dv; -} - -template -inline v_int32x4 v_broadcast_element(const v_int32x4& v) -{ - return v_int32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& v) -{ - return v_uint32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); -} - -template -inline v_float32x4 v_broadcast_element(const v_float32x4& v) -{ - return v_float32x4(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE((char)i,(char)i,(char)i,(char)i))); -} - -////////////// FP16 support /////////////////////////// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ -#if CV_FP16 - return v_float32x4(_mm_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); -#else - const __m128i z = _mm_setzero_si128(), delta = _mm_set1_epi32(0x38000000); - const __m128i signmask = _mm_set1_epi32(0x80000000), maxexp = _mm_set1_epi32(0x7c000000); - const __m128 deltaf = _mm_castsi128_ps(_mm_set1_epi32(0x38800000)); - __m128i bits = _mm_unpacklo_epi16(z, _mm_loadl_epi64((const __m128i*)ptr)); // h << 16 - __m128i e = _mm_and_si128(bits, maxexp), sign = _mm_and_si128(bits, signmask); - __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_xor_si128(bits, sign), 3), delta); // ((h & 0x7fff) << 13) + delta - __m128i zt = _mm_castps_si128(_mm_sub_ps(_mm_castsi128_ps(_mm_add_epi32(t, _mm_set1_epi32(1 << 23))), deltaf)); - - t = _mm_add_epi32(t, _mm_and_si128(delta, _mm_cmpeq_epi32(maxexp, e))); - __m128i zmask = _mm_cmpeq_epi32(e, z); - __m128i ft = v_select_si128(zmask, zt, t); - return v_float32x4(_mm_castsi128_ps(_mm_or_si128(ft, sign))); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ -#if CV_FP16 - __m128i fp16_value = _mm_cvtps_ph(v.val, 0); - _mm_storel_epi64((__m128i*)ptr, fp16_value); -#else - const __m128i signmask = _mm_set1_epi32(0x80000000); - const __m128i rval = _mm_set1_epi32(0x3f000000); - - __m128i t = _mm_castps_si128(v.val); - __m128i sign = _mm_srai_epi32(_mm_and_si128(t, signmask), 16); - t = _mm_andnot_si128(signmask, t); - - __m128i finitemask = _mm_cmpgt_epi32(_mm_set1_epi32(0x47800000), t); - __m128i isnan = _mm_cmpgt_epi32(t, _mm_set1_epi32(0x7f800000)); - __m128i naninf = v_select_si128(isnan, _mm_set1_epi32(0x7e00), _mm_set1_epi32(0x7c00)); - __m128i tinymask = _mm_cmpgt_epi32(_mm_set1_epi32(0x38800000), t); - __m128i tt = _mm_castps_si128(_mm_add_ps(_mm_castsi128_ps(t), _mm_castsi128_ps(rval))); - tt = _mm_sub_epi32(tt, rval); - __m128i odd = _mm_and_si128(_mm_srli_epi32(t, 13), _mm_set1_epi32(1)); - __m128i nt = _mm_add_epi32(t, _mm_set1_epi32(0xc8000fff)); - nt = _mm_srli_epi32(_mm_add_epi32(nt, odd), 13); - t = v_select_si128(tinymask, tt, nt); - t = v_select_si128(finitemask, t, naninf); - t = _mm_or_si128(t, sign); - t = _mm_packs_epi32(t, t); - _mm_storel_epi64((__m128i*)ptr, t); -#endif -} - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HAL_SSE_HPP +#define OPENCV_HAL_SSE_HPP + +#include +#include "opencv2/core/utility.hpp" + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 +#define CV_SIMD128_FP16 0 // no native operations with FP16 type. + +namespace cv +{ + +//! @cond IGNORED + +// +// Compilation troubleshooting: +// - MSVC: error C2719: 'a': formal parameter with requested alignment of 16 won't be aligned +// Replace parameter declaration to const reference: +// -v_int32x4 a +// +const v_int32x4& a +// + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Types //////////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + typedef __m128i vector_type; + enum { nlanes = 16 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint8x16() {} + explicit v_uint8x16(__m128i v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6, (char)v7, + (char)v8, (char)v9, (char)v10, (char)v11, + (char)v12, (char)v13, (char)v14, (char)v15); + } + + uchar get0() const + { + return (uchar)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + typedef __m128i vector_type; + enum { nlanes = 16 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int8x16() {} + explicit v_int8x16(__m128i v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + val = _mm_setr_epi8((char)v0, (char)v1, (char)v2, (char)v3, + (char)v4, (char)v5, (char)v6, (char)v7, + (char)v8, (char)v9, (char)v10, (char)v11, + (char)v12, (char)v13, (char)v14, (char)v15); + } + + schar get0() const + { + return (schar)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + typedef __m128i vector_type; + enum { nlanes = 8 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint16x8() {} + explicit v_uint16x8(__m128i v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7); + } + + ushort get0() const + { + return (ushort)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + typedef __m128i vector_type; + enum { nlanes = 8 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int16x8() {} + explicit v_int16x8(__m128i v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + val = _mm_setr_epi16((short)v0, (short)v1, (short)v2, (short)v3, + (short)v4, (short)v5, (short)v6, (short)v7); + } + + short get0() const + { + return (short)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + typedef __m128i vector_type; + enum { nlanes = 4 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint32x4() {} + explicit v_uint32x4(__m128i v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + val = _mm_setr_epi32((int)v0, (int)v1, (int)v2, (int)v3); + } + + unsigned get0() const + { + return (unsigned)_mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + typedef __m128i vector_type; + enum { nlanes = 4 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int32x4() {} + explicit v_int32x4(__m128i v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + val = _mm_setr_epi32(v0, v1, v2, v3); + } + + int get0() const + { + return _mm_cvtsi128_si32(val); + } + + __m128i val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + typedef __m128 vector_type; + enum { nlanes = 4 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_float32x4() {} + explicit v_float32x4(__m128 v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + val = _mm_setr_ps(v0, v1, v2, v3); + } + + float get0() const + { + return _mm_cvtss_f32(val); + } + + __m128 val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + typedef __m128i vector_type; + enum { nlanes = 2 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_uint64x2() {} + explicit v_uint64x2(__m128i v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { +#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) + val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); +#elif defined(__GNUC__) + val = _mm_setr_epi64((__m64)v0, (__m64)v1); +#else + val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); +#endif + } + + uint64 get0() const + { + #if !defined(__x86_64__) && !defined(_M_X64) + int a = _mm_cvtsi128_si32(val); + int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); + return (unsigned)a | ((uint64)(unsigned)b << 32); + #else + return (uint64)_mm_cvtsi128_si64(val); + #endif + } + + __m128i val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + typedef __m128i vector_type; + enum { nlanes = 2 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_int64x2() {} + explicit v_int64x2(__m128i v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { +#if defined(_MSC_VER) && _MSC_VER >= 1920/*MSVS 2019*/ && defined(_M_X64) && !defined(__clang__) + val = _mm_setr_epi64x((int64_t)v0, (int64_t)v1); +#elif defined(__GNUC__) + val = _mm_setr_epi64((__m64)v0, (__m64)v1); +#else + val = _mm_setr_epi32((int)v0, (int)(v0 >> 32), (int)v1, (int)(v1 >> 32)); +#endif + } + + int64 get0() const + { + #if !defined(__x86_64__) && !defined(_M_X64) + int a = _mm_cvtsi128_si32(val); + int b = _mm_cvtsi128_si32(_mm_srli_epi64(val, 32)); + return (int64)((unsigned)a | ((uint64)(unsigned)b << 32)); + #else + return _mm_cvtsi128_si64(val); + #endif + } + + __m128i val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + typedef __m128d vector_type; + enum { nlanes = 2 }; + + /* coverity[uninit_ctor]: suppress warning */ + v_float64x2() {} + explicit v_float64x2(__m128d v) : val(v) {} + v_float64x2(double v0, double v1) + { + val = _mm_setr_pd(v0, v1); + } + + double get0() const + { + return _mm_cvtsd_f64(val); + } + + __m128d val; +}; + +namespace hal_sse_internal +{ + template + to_sse_type v_sse_reinterpret_as(const from_sse_type& val); + +#define OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(to_sse_type, from_sse_type, sse_cast_intrin) \ + template<> inline \ + to_sse_type v_sse_reinterpret_as(const from_sse_type& a) \ + { return sse_cast_intrin(a); } + + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128i, OPENCV_HAL_NOP) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128, _mm_castps_si128) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128i, __m128d, _mm_castpd_si128) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128i, _mm_castsi128_ps) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128, OPENCV_HAL_NOP) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128, __m128d, _mm_castpd_ps) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128i, _mm_castsi128_pd) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128, _mm_castps_pd) + OPENCV_HAL_IMPL_SSE_REINTERPRET_RAW(__m128d, __m128d, OPENCV_HAL_NOP) +} + +#define OPENCV_HAL_IMPL_SSE_INITVEC(_Tpvec, _Tp, suffix, zsuffix, ssuffix, _Tps, cast) \ +inline _Tpvec v_setzero_##suffix() { return _Tpvec(_mm_setzero_##zsuffix()); } \ +inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(_mm_set1_##ssuffix((_Tps)v)); } \ +template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ +{ return _Tpvec(cast(a.val)); } + +OPENCV_HAL_IMPL_SSE_INITVEC(v_uint8x16, uchar, u8, si128, epi8, schar, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_int8x16, schar, s8, si128, epi8, schar, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_uint16x8, ushort, u16, si128, epi16, short, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_int16x8, short, s16, si128, epi16, short, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_uint32x4, unsigned, u32, si128, epi32, int, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_int32x4, int, s32, si128, epi32, int, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_INITVEC(v_float32x4, float, f32, ps, ps, float, _mm_castsi128_ps) +OPENCV_HAL_IMPL_SSE_INITVEC(v_float64x2, double, f64, pd, pd, double, _mm_castsi128_pd) + +inline v_uint64x2 v_setzero_u64() { return v_uint64x2(_mm_setzero_si128()); } +inline v_int64x2 v_setzero_s64() { return v_int64x2(_mm_setzero_si128()); } +inline v_uint64x2 v_setall_u64(uint64 val) { return v_uint64x2(val, val); } +inline v_int64x2 v_setall_s64(int64 val) { return v_int64x2(val, val); } + +template <> inline v_uint64x2 v_setzero_() { return v_setzero_u64(); } +template <> inline v_int64x2 v_setzero_() { return v_setzero_s64(); } +template <> inline v_uint64x2 v_setall_(uint64 val) { return v_setall_u64(val); } +template <> inline v_int64x2 v_setall_(int64 val) { return v_setall_s64(val); } + +template inline +v_uint64x2 v_reinterpret_as_u64(const _Tpvec& a) { return v_uint64x2(a.val); } +template inline +v_int64x2 v_reinterpret_as_s64(const _Tpvec& a) { return v_int64x2(a.val); } +inline v_float32x4 v_reinterpret_as_f32(const v_uint64x2& a) +{ return v_float32x4(_mm_castsi128_ps(a.val)); } +inline v_float32x4 v_reinterpret_as_f32(const v_int64x2& a) +{ return v_float32x4(_mm_castsi128_ps(a.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_uint64x2& a) +{ return v_float64x2(_mm_castsi128_pd(a.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_int64x2& a) +{ return v_float64x2(_mm_castsi128_pd(a.val)); } + +#define OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(_Tpvec, suffix) \ +inline _Tpvec v_reinterpret_as_##suffix(const v_float32x4& a) \ +{ return _Tpvec(_mm_castps_si128(a.val)); } \ +inline _Tpvec v_reinterpret_as_##suffix(const v_float64x2& a) \ +{ return _Tpvec(_mm_castpd_si128(a.val)); } + +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint8x16, u8) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int8x16, s8) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint16x8, u16) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int16x8, s16) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint32x4, u32) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int32x4, s32) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_uint64x2, u64) +OPENCV_HAL_IMPL_SSE_INIT_FROM_FLT(v_int64x2, s64) + +inline v_float32x4 v_reinterpret_as_f32(const v_float32x4& a) {return a; } +inline v_float64x2 v_reinterpret_as_f64(const v_float64x2& a) {return a; } +inline v_float32x4 v_reinterpret_as_f32(const v_float64x2& a) {return v_float32x4(_mm_castpd_ps(a.val)); } +inline v_float64x2 v_reinterpret_as_f64(const v_float32x4& a) {return v_float64x2(_mm_castps_pd(a.val)); } + +//////////////// PACK /////////////// +inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i delta = _mm_set1_epi16(255); + return v_uint8x16(_mm_packus_epi16(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)), + _mm_subs_epu16(b.val, _mm_subs_epu16(b.val, delta)))); +} + +inline void v_pack_store(uchar* ptr, const v_uint16x8& a) +{ + __m128i delta = _mm_set1_epi16(255); + __m128i a1 = _mm_subs_epu16(a.val, _mm_subs_epu16(a.val, delta)); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); +} + +inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) +{ return v_uint8x16(_mm_packus_epi16(a.val, b.val)); } + +inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) +{ _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a.val, a.val)); } + +template inline +v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + return v_uint8x16(_mm_packus_epi16(_mm_srli_epi16(_mm_adds_epu16(a.val, delta), n), + _mm_srli_epi16(_mm_adds_epu16(b.val, delta), n))); +} + +template inline +void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) +{ + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + __m128i a1 = _mm_srli_epi16(_mm_adds_epu16(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); +} + +template inline +v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) +{ + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + return v_uint8x16(_mm_packus_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), + _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); +} + +template inline +void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) +{ + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi16(a1, a1)); +} + +inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) +{ return v_int8x16(_mm_packs_epi16(a.val, b.val)); } + +inline void v_pack_store(schar* ptr, const v_int16x8& a) +{ _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a.val, a.val)); } + +template inline +v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + return v_int8x16(_mm_packs_epi16(_mm_srai_epi16(_mm_adds_epi16(a.val, delta), n), + _mm_srai_epi16(_mm_adds_epi16(b.val, delta), n))); +} +template inline +void v_rshr_pack_store(schar* ptr, const v_int16x8& a) +{ + // we assume that n > 0, and so the shifted 16-bit values can be treated as signed numbers. + __m128i delta = _mm_set1_epi16((short)(1 << (n-1))); + __m128i a1 = _mm_srai_epi16(_mm_adds_epi16(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi16(a1, a1)); +} + + +// byte-wise "mask ? a : b" +inline __m128i v_select_si128(__m128i mask, __m128i a, __m128i b) +{ +#if CV_SSE4_1 + return _mm_blendv_epi8(b, a, mask); +#else + return _mm_xor_si128(b, _mm_and_si128(_mm_xor_si128(a, b), mask)); +#endif +} + +inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) +{ return v_uint16x8(_v128_packs_epu32(a.val, b.val)); } + +inline void v_pack_store(ushort* ptr, const v_uint32x4& a) +{ + __m128i z = _mm_setzero_si128(), maxval32 = _mm_set1_epi32(65535), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(v_select_si128(_mm_cmpgt_epi32(z, a.val), maxval32, a.val), delta32); + __m128i r = _mm_packs_epi32(a1, a1); + _mm_storel_epi64((__m128i*)ptr, _mm_sub_epi16(r, _mm_set1_epi16(-32768))); +} + +template inline +v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i b1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(b.val, delta), n), delta32); + return v_uint16x8(_mm_sub_epi16(_mm_packs_epi32(a1, b1), _mm_set1_epi16(-32768))); +} + +template inline +void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srli_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + _mm_storel_epi64((__m128i*)ptr, a2); +} + +inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_uint16x8(_mm_packus_epi32(a.val, b.val)); +#else + __m128i delta32 = _mm_set1_epi32(32768); + + // preliminary saturate negative values to zero + __m128i a1 = _mm_and_si128(a.val, _mm_cmpgt_epi32(a.val, _mm_set1_epi32(0))); + __m128i b1 = _mm_and_si128(b.val, _mm_cmpgt_epi32(b.val, _mm_set1_epi32(0))); + + __m128i r = _mm_packs_epi32(_mm_sub_epi32(a1, delta32), _mm_sub_epi32(b1, delta32)); + return v_uint16x8(_mm_sub_epi16(r, _mm_set1_epi16(-32768))); +#endif +} + +inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) +{ +#if CV_SSE4_1 + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a.val, a.val)); +#else + __m128i delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(a.val, delta32); + __m128i r = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + _mm_storel_epi64((__m128i*)ptr, r); +#endif +} + +template inline +v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + __m128i delta = _mm_set1_epi32(1 << (n - 1)); + return v_uint16x8(_mm_packus_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), + _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); +#else + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + __m128i b1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(b.val, delta), n), delta32); + __m128i b2 = _mm_sub_epi16(_mm_packs_epi32(b1, b1), _mm_set1_epi16(-32768)); + return v_uint16x8(_mm_unpacklo_epi64(a2, b2)); +#endif +} + +template inline +void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) +{ +#if CV_SSE4_1 + __m128i delta = _mm_set1_epi32(1 << (n - 1)); + __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packus_epi32(a1, a1)); +#else + __m128i delta = _mm_set1_epi32(1 << (n-1)), delta32 = _mm_set1_epi32(32768); + __m128i a1 = _mm_sub_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), delta32); + __m128i a2 = _mm_sub_epi16(_mm_packs_epi32(a1, a1), _mm_set1_epi16(-32768)); + _mm_storel_epi64((__m128i*)ptr, a2); +#endif +} + +inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) +{ return v_int16x8(_mm_packs_epi32(a.val, b.val)); } + +inline void v_pack_store(short* ptr, const v_int32x4& a) +{ + _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a.val, a.val)); +} + +template inline +v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)); + return v_int16x8(_mm_packs_epi32(_mm_srai_epi32(_mm_add_epi32(a.val, delta), n), + _mm_srai_epi32(_mm_add_epi32(b.val, delta), n))); +} + +template inline +void v_rshr_pack_store(short* ptr, const v_int32x4& a) +{ + __m128i delta = _mm_set1_epi32(1 << (n-1)); + __m128i a1 = _mm_srai_epi32(_mm_add_epi32(a.val, delta), n); + _mm_storel_epi64((__m128i*)ptr, _mm_packs_epi32(a1, a1)); +} + + +// [a0 0 | b0 0] [a1 0 | b1 0] +inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 + return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); +} + +inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a1); +} + +// [a0 0 | b0 0] [a1 0 | b1 0] +inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) +{ + __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); // b0 b1 0 0 + return v_int32x4(_mm_unpacklo_epi32(v0, v1)); +} + +inline void v_pack_store(int* ptr, const v_int64x2& a) +{ + __m128i a1 = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a1); +} + +template inline +v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + uint64 delta = (uint64)1 << (n-1); + v_uint64x2 delta2(delta, delta); + __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i b1 = _mm_srli_epi64(_mm_add_epi64(b.val, delta2.val), n); + __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 + return v_uint32x4(_mm_unpacklo_epi32(v0, v1)); +} + +template inline +void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + uint64 delta = (uint64)1 << (n-1); + v_uint64x2 delta2(delta, delta); + __m128i a1 = _mm_srli_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a2); +} + +inline __m128i v_sign_epi64(__m128i a) +{ + return _mm_shuffle_epi32(_mm_srai_epi32(a, 31), _MM_SHUFFLE(3, 3, 1, 1)); // x m0 | x m1 +} + +inline __m128i v_srai_epi64(__m128i a, int imm) +{ + __m128i smask = v_sign_epi64(a); + return _mm_xor_si128(_mm_srli_epi64(_mm_xor_si128(a, smask), imm), smask); +} + +template inline +v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) +{ + int64 delta = (int64)1 << (n-1); + v_int64x2 delta2(delta, delta); + __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i b1 = v_srai_epi64(_mm_add_epi64(b.val, delta2.val), n); + __m128i v0 = _mm_unpacklo_epi32(a1, b1); // a0 a1 0 0 + __m128i v1 = _mm_unpackhi_epi32(a1, b1); // b0 b1 0 0 + return v_int32x4(_mm_unpacklo_epi32(v0, v1)); +} + +template inline +void v_rshr_pack_store(int* ptr, const v_int64x2& a) +{ + int64 delta = (int64)1 << (n-1); + v_int64x2 delta2(delta, delta); + __m128i a1 = v_srai_epi64(_mm_add_epi64(a.val, delta2.val), n); + __m128i a2 = _mm_shuffle_epi32(a1, _MM_SHUFFLE(0, 2, 2, 0)); + _mm_storel_epi64((__m128i*)ptr, a2); +} + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + __m128i ab = _mm_packs_epi16(a.val, b.val); + return v_uint8x16(ab); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + __m128i ab = _mm_packs_epi32(a.val, b.val); + __m128i cd = _mm_packs_epi32(c.val, d.val); + return v_uint8x16(_mm_packs_epi16(ab, cd)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + __m128i ab = _mm_packs_epi32(a.val, b.val); + __m128i cd = _mm_packs_epi32(c.val, d.val); + __m128i ef = _mm_packs_epi32(e.val, f.val); + __m128i gh = _mm_packs_epi32(g.val, h.val); + + __m128i abcd = _mm_packs_epi32(ab, cd); + __m128i efgh = _mm_packs_epi32(ef, gh); + return v_uint8x16(_mm_packs_epi16(abcd, efgh)); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); + __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); + __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); + __m128 v3 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(3, 3, 3, 3)), m3.val); + + return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, v3))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + __m128 v0 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(0, 0, 0, 0)), m0.val); + __m128 v1 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(1, 1, 1, 1)), m1.val); + __m128 v2 = _mm_mul_ps(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE(2, 2, 2, 2)), m2.val); + + return v_float32x4(_mm_add_ps(_mm_add_ps(v0, v1), _mm_add_ps(v2, a.val))); +} + +#define OPENCV_HAL_IMPL_SSE_BIN_OP(bin_op, _Tpvec, intrin) \ + inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ + { \ + return _Tpvec(intrin(a.val, b.val)); \ + } + +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint8x16, _mm_adds_epu8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint8x16, _mm_subs_epu8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int8x16, _mm_adds_epi8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int8x16, _mm_subs_epi8) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint16x8, _mm_adds_epu16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint16x8, _mm_subs_epu16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int16x8, _mm_adds_epi16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int16x8, _mm_subs_epi16) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint32x4, _mm_add_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint32x4, _mm_sub_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_uint32x4, _v128_mullo_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int32x4, _mm_add_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int32x4, _mm_sub_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_int32x4, _v128_mullo_epi32) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float32x4, _mm_add_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float32x4, _mm_sub_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float32x4, _mm_mul_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float32x4, _mm_div_ps) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_float64x2, _mm_add_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_float64x2, _mm_sub_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_mul, v_float64x2, _mm_mul_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_div, v_float64x2, _mm_div_pd) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_uint64x2, _mm_add_epi64) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_uint64x2, _mm_sub_epi64) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_add, v_int64x2, _mm_add_epi64) +OPENCV_HAL_IMPL_SSE_BIN_OP(v_sub, v_int64x2, _mm_sub_epi64) + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_SSE_MUL_SAT(_Tpvec, _Tpwvec) \ + inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ + { \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ + } + +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_uint16x8, v_uint32x4) +OPENCV_HAL_IMPL_SSE_MUL_SAT(v_int16x8, v_int32x4) + +// Multiply and expand +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + v_uint16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + v_int16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + __m128i v0 = _mm_mullo_epi16(a.val, b.val); + __m128i v1 = _mm_mulhi_epi16(a.val, b.val); + c.val = _mm_unpacklo_epi16(v0, v1); + d.val = _mm_unpackhi_epi16(v0, v1); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + __m128i v0 = _mm_mullo_epi16(a.val, b.val); + __m128i v1 = _mm_mulhi_epu16(a.val, b.val); + c.val = _mm_unpacklo_epi16(v0, v1); + d.val = _mm_unpackhi_epi16(v0, v1); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + __m128i c0 = _mm_mul_epu32(a.val, b.val); + __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); + c.val = _mm_unpacklo_epi64(c0, c1); + d.val = _mm_unpackhi_epi64(c0, c1); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) { return v_int16x8(_mm_mulhi_epi16(a.val, b.val)); } +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) { return v_uint16x8(_mm_mulhi_epu16(a.val, b.val)); } + +//////// Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ return v_int32x4(_mm_madd_epi16(a.val, b.val)); } +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + __m128i even = _mm_mul_epi32(a.val, b.val); + __m128i odd = _mm_mul_epi32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); + return v_int64x2(_mm_add_epi64(even, odd)); +#else + __m128i even_u = _mm_mul_epu32(a.val, b.val); + __m128i odd_u = _mm_mul_epu32(_mm_srli_epi64(a.val, 32), _mm_srli_epi64(b.val, 32)); + // convert unsigned to signed high multiplication (from: Agner Fog(veclib) and H S Warren: Hacker's delight, 2003, p. 132) + __m128i a_sign = _mm_srai_epi32(a.val, 31); + __m128i b_sign = _mm_srai_epi32(b.val, 31); + // |x * sign of x + __m128i axb = _mm_and_si128(a.val, b_sign); + __m128i bxa = _mm_and_si128(b.val, a_sign); + // sum of sign corrections + __m128i ssum = _mm_add_epi32(bxa, axb); + __m128i even_ssum = _mm_slli_epi64(ssum, 32); + __m128i odd_ssum = _mm_and_si128(ssum, _mm_set_epi32(-1, 0, -1, 0)); + // convert to signed and prod + return v_int64x2(_mm_add_epi64(_mm_sub_epi64(even_u, even_ssum), _mm_sub_epi64(odd_u, odd_ssum))); +#endif +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i a0 = _mm_srli_epi16(_mm_slli_si128(a.val, 1), 8); // even + __m128i a1 = _mm_srli_epi16(a.val, 8); // odd + __m128i b0 = _mm_srli_epi16(_mm_slli_si128(b.val, 1), 8); + __m128i b1 = _mm_srli_epi16(b.val, 8); + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_uint32x4(_mm_add_epi32(p0, p1)); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + __m128i a0 = _mm_srai_epi16(_mm_slli_si128(a.val, 1), 8); // even + __m128i a1 = _mm_srai_epi16(a.val, 8); // odd + __m128i b0 = _mm_srai_epi16(_mm_slli_si128(b.val, 1), 8); + __m128i b1 = _mm_srai_epi16(b.val, 8); + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_int32x4(_mm_add_epi32(p0, p1)); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 c, d; + v_mul_expand(a, b, c, d); + + v_uint64x2 c0, c1, d0, d1; + v_expand(c, c0, c1); + v_expand(d, d0, d1); + + c0 = v_add(c0, c1); d0 = v_add(d0, d1); + return v_uint64x2(_mm_add_epi64( + _mm_unpacklo_epi64(c0.val, d0.val), + _mm_unpackhi_epi64(c0.val, d0.val) + )); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_int64x2(_mm_add_epi64( + _mm_unpacklo_epi64(c.val, d.val), + _mm_unpackhi_epi64(c.val, d.val) + )); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_cvt_f64(v_dotprod(a, b)); +#else + v_float64x2 c = v_mul(v_cvt_f64(a), v_cvt_f64(b)); + v_float64x2 d = v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b)); + + return v_float64x2(_mm_add_pd( + _mm_unpacklo_pd(c.val, d.val), + _mm_unpackhi_pd(c.val, d.val) + )); +#endif +} +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_add(v_dotprod(a, b), c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_add(v_dotprod_fast(a, b), c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i a0 = v_expand_low(a).val; + __m128i a1 = v_expand_high(a).val; + __m128i b0 = v_expand_low(b).val; + __m128i b1 = v_expand_high(b).val; + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_uint32x4(_mm_add_epi32(p0, p1)); +} +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_SSE4_1 + __m128i a0 = _mm_cvtepi8_epi16(a.val); + __m128i a1 = v_expand_high(a).val; + __m128i b0 = _mm_cvtepi8_epi16(b.val); + __m128i b1 = v_expand_high(b).val; + __m128i p0 = _mm_madd_epi16(a0, b0); + __m128i p1 = _mm_madd_epi16(a1, b1); + return v_int32x4(_mm_add_epi32(p0, p1)); +#else + return v_dotprod_expand(a, b); +#endif +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 c, d; + v_mul_expand(a, b, c, d); + + v_uint64x2 c0, c1, d0, d1; + v_expand(c, c0, c1); + v_expand(d, d0, d1); + + c0 = v_add(c0, c1); d0 = v_add(d0, d1); + return v_add(c0, d0); +} +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_add(c, d); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c); +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_mul(v_cvt_f64_high(a), v_cvt_f64_high(b))); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_fma(v_cvt_f64(a), v_cvt_f64(b), v_fma(v_cvt_f64_high(a), v_cvt_f64_high(b), c)); } + +#define OPENCV_HAL_IMPL_SSE_LOGIC_OP(_Tpvec, suffix, not_const) \ + OPENCV_HAL_IMPL_SSE_BIN_OP(v_and, _Tpvec, _mm_and_##suffix) \ + OPENCV_HAL_IMPL_SSE_BIN_OP(v_or, _Tpvec, _mm_or_##suffix) \ + OPENCV_HAL_IMPL_SSE_BIN_OP(v_xor, _Tpvec, _mm_xor_##suffix) \ + inline _Tpvec v_not(const _Tpvec& a) \ + { \ + return _Tpvec(_mm_xor_##suffix(a.val, not_const)); \ + } + +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint8x16, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int8x16, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint16x8, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int16x8, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint32x4, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int32x4, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_uint64x2, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_int64x2, si128, _mm_set1_epi32(-1)) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float32x4, ps, _mm_castsi128_ps(_mm_set1_epi32(-1))) +OPENCV_HAL_IMPL_SSE_LOGIC_OP(v_float64x2, pd, _mm_castsi128_pd(_mm_set1_epi32(-1))) + +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ return v_float32x4(_mm_sqrt_ps(x.val)); } + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + const __m128 _0_5 = _mm_set1_ps(0.5f), _1_5 = _mm_set1_ps(1.5f); + __m128 t = x.val; + __m128 h = _mm_mul_ps(t, _0_5); + t = _mm_rsqrt_ps(t); + t = _mm_mul_ps(t, _mm_sub_ps(_1_5, _mm_mul_ps(_mm_mul_ps(t, t), h))); + return v_float32x4(t); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ return v_float64x2(_mm_sqrt_pd(x.val)); } + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + const __m128d v_1 = _mm_set1_pd(1.); + return v_float64x2(_mm_div_pd(v_1, _mm_sqrt_pd(x.val))); +} + +#define OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(_Tpuvec, _Tpsvec, func, suffix, subWidth) \ +inline _Tpuvec v_abs(const _Tpsvec& x) \ +{ return _Tpuvec(_mm_##func##_ep##suffix(x.val, _mm_sub_ep##subWidth(_mm_setzero_si128(), x.val))); } + +OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint8x16, v_int8x16, min, u8, i8) +OPENCV_HAL_IMPL_SSE_ABS_INT_FUNC(v_uint16x8, v_int16x8, max, i16, i16) +inline v_uint32x4 v_abs(const v_int32x4& x) +{ + __m128i s = _mm_srli_epi32(x.val, 31); + __m128i f = _mm_srai_epi32(x.val, 31); + return v_uint32x4(_mm_add_epi32(_mm_xor_si128(x.val, f), s)); +} +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(_mm_and_ps(x.val, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff)))); } +inline v_float64x2 v_abs(const v_float64x2& x) +{ + return v_float64x2(_mm_and_pd(x.val, + _mm_castsi128_pd(_mm_srli_epi64(_mm_set1_epi32(-1), 1)))); +} + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_SSE_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_min, _mm_min_epu8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_max, _mm_max_epu8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_min, _mm_min_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_max, _mm_max_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_min, _mm_min_ps) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float32x4, v_max, _mm_max_ps) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_min, _mm_min_pd) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_float64x2, v_max, _mm_max_pd) + +inline v_int8x16 v_min(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_SSE4_1 + return v_int8x16(_mm_min_epi8(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi8((char)-128); + return v_int8x16(_mm_xor_si128(delta, _mm_min_epu8(_mm_xor_si128(a.val, delta), + _mm_xor_si128(b.val, delta)))); +#endif +} +inline v_int8x16 v_max(const v_int8x16& a, const v_int8x16& b) +{ +#if CV_SSE4_1 + return v_int8x16(_mm_max_epi8(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi8((char)-128); + return v_int8x16(_mm_xor_si128(delta, _mm_max_epu8(_mm_xor_si128(a.val, delta), + _mm_xor_si128(b.val, delta)))); +#endif +} +inline v_uint16x8 v_min(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_SSE4_1 + return v_uint16x8(_mm_min_epu16(a.val, b.val)); +#else + return v_uint16x8(_mm_subs_epu16(a.val, _mm_subs_epu16(a.val, b.val))); +#endif +} +inline v_uint16x8 v_max(const v_uint16x8& a, const v_uint16x8& b) +{ +#if CV_SSE4_1 + return v_uint16x8(_mm_max_epu16(a.val, b.val)); +#else + return v_uint16x8(_mm_adds_epu16(_mm_subs_epu16(a.val, b.val), b.val)); +#endif +} +inline v_uint32x4 v_min(const v_uint32x4& a, const v_uint32x4& b) +{ +#if CV_SSE4_1 + return v_uint32x4(_mm_min_epu32(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi32((int)0x80000000); + __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); + return v_uint32x4(v_select_si128(mask, b.val, a.val)); +#endif +} +inline v_uint32x4 v_max(const v_uint32x4& a, const v_uint32x4& b) +{ +#if CV_SSE4_1 + return v_uint32x4(_mm_max_epu32(a.val, b.val)); +#else + __m128i delta = _mm_set1_epi32((int)0x80000000); + __m128i mask = _mm_cmpgt_epi32(_mm_xor_si128(a.val, delta), _mm_xor_si128(b.val, delta)); + return v_uint32x4(v_select_si128(mask, a.val, b.val)); +#endif +} +inline v_int32x4 v_min(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_int32x4(_mm_min_epi32(a.val, b.val)); +#else + return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), b.val, a.val)); +#endif +} +inline v_int32x4 v_max(const v_int32x4& a, const v_int32x4& b) +{ +#if CV_SSE4_1 + return v_int32x4(_mm_max_epi32(a.val, b.val)); +#else + return v_int32x4(v_select_si128(_mm_cmpgt_epi32(a.val, b.val), a.val, b.val)); +#endif +} + +#define OPENCV_HAL_IMPL_SSE_INT_CMP_OP(_Tpuvec, _Tpsvec, suffix, sbit) \ +inline _Tpuvec v_eq(const _Tpuvec& a, const _Tpuvec& b) \ +{ return _Tpuvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ +inline _Tpuvec v_ne(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpuvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ +} \ +inline _Tpsvec v_eq(const _Tpsvec& a, const _Tpsvec& b) \ +{ return _Tpsvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ +inline _Tpsvec v_ne(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpsvec(_mm_xor_si128(_mm_cmpeq_##suffix(a.val, b.val), not_mask)); \ +} \ +inline _Tpuvec v_lt(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask))); \ +} \ +inline _Tpuvec v_gt(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + return _Tpuvec(_mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask))); \ +} \ +inline _Tpuvec v_le(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + __m128i not_mask = _mm_set1_epi32(-1); \ + __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(a.val, smask), _mm_xor_si128(b.val, smask)); \ + return _Tpuvec(_mm_xor_si128(res, not_mask)); \ +} \ +inline _Tpuvec v_ge(const _Tpuvec& a, const _Tpuvec& b) \ +{ \ + __m128i smask = _mm_set1_##suffix(sbit); \ + __m128i not_mask = _mm_set1_epi32(-1); \ + __m128i res = _mm_cmpgt_##suffix(_mm_xor_si128(b.val, smask), _mm_xor_si128(a.val, smask)); \ + return _Tpuvec(_mm_xor_si128(res, not_mask)); \ +} \ +inline _Tpsvec v_lt(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + return _Tpsvec(_mm_cmpgt_##suffix(b.val, a.val)); \ +} \ +inline _Tpsvec v_gt(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + return _Tpsvec(_mm_cmpgt_##suffix(a.val, b.val)); \ +} \ +inline _Tpsvec v_le(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(a.val, b.val), not_mask)); \ +} \ +inline _Tpsvec v_ge(const _Tpsvec& a, const _Tpsvec& b) \ +{ \ + __m128i not_mask = _mm_set1_epi32(-1); \ + return _Tpsvec(_mm_xor_si128(_mm_cmpgt_##suffix(b.val, a.val), not_mask)); \ +} + +OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint8x16, v_int8x16, epi8, (char)-128) +OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint16x8, v_int16x8, epi16, (short)-32768) +OPENCV_HAL_IMPL_SSE_INT_CMP_OP(v_uint32x4, v_int32x4, epi32, (int)0x80000000) + +#define OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(_Tpvec, suffix) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpeq_##suffix(a.val, b.val)); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpneq_##suffix(a.val, b.val)); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmplt_##suffix(a.val, b.val)); } \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpgt_##suffix(a.val, b.val)); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmple_##suffix(a.val, b.val)); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpge_##suffix(a.val, b.val)); } + +OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float32x4, ps) +OPENCV_HAL_IMPL_SSE_FLT_CMP_OP(v_float64x2, pd) + +#if CV_SSE4_1 +#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ +inline _Tpvec v_eq (const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(_mm_cmpeq_epi64(a.val, b.val)); } \ +inline _Tpvec v_ne (const _Tpvec& a, const _Tpvec& b) \ +{ return v_not(v_eq(a, b)); } +#else +#define OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(_Tpvec) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ __m128i cmp = _mm_cmpeq_epi32(a.val, b.val); \ + return _Tpvec(_mm_and_si128(cmp, _mm_shuffle_epi32(cmp, _MM_SHUFFLE(2, 3, 0, 1)))); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return v_not(v_eq(a, b)); } +#endif + +OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_uint64x2) +OPENCV_HAL_IMPL_SSE_64BIT_CMP_OP(v_int64x2) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(_mm_cmpord_ps(a.val, a.val)); } +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(_mm_cmpord_pd(a.val, a.val)); } + +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_add_wrap, _mm_add_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_add_wrap, _mm_add_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_add_wrap, _mm_add_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_add_wrap, _mm_add_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint8x16, v_sub_wrap, _mm_sub_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int8x16, v_sub_wrap, _mm_sub_epi8) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_sub_wrap, _mm_sub_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_sub_wrap, _mm_sub_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_uint16x8, v_mul_wrap, _mm_mullo_epi16) +OPENCV_HAL_IMPL_SSE_BIN_FUNC(v_int16x8, v_mul_wrap, _mm_mullo_epi16) + +inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i ad = _mm_srai_epi16(a.val, 8); + __m128i bd = _mm_srai_epi16(b.val, 8); + __m128i p0 = _mm_mullo_epi16(a.val, b.val); // even + __m128i p1 = _mm_slli_epi16(_mm_mullo_epi16(ad, bd), 8); // odd + const __m128i b01 = _mm_set1_epi32(0xFF00FF00); + return v_uint8x16(_v128_blendv_epi8(p0, p1, b01)); +} +inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) +{ + return v_reinterpret_as_s8(v_mul_wrap(v_reinterpret_as_u8(a), v_reinterpret_as_u8(b))); +} + +/** Absolute difference **/ + +inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub_wrap(a, b); + v_int8x16 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ + return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); +} +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ + v_int32x4 d = v_sub(a, b); + v_int32x4 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub(a, b); + v_int8x16 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); + } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ +#if CV_FMA3 + return v_float32x4(_mm_fmadd_ps(a.val, b.val, c.val)); +#else + return v_float32x4(_mm_add_ps(_mm_mul_ps(a.val, b.val), c.val)); +#endif +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ +#if CV_FMA3 + return v_float64x2(_mm_fmadd_pd(a.val, b.val, c.val)); +#else + return v_float64x2(_mm_add_pd(_mm_mul_pd(a.val, b.val), c.val)); +#endif +} + +#define OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(_Tpvec, _Tp, _Tpreg, suffix, absmask_vec) \ +inline _Tpvec v_absdiff(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpreg absmask = _mm_castsi128_##suffix(absmask_vec); \ + return _Tpvec(_mm_and_##suffix(_mm_sub_##suffix(a.val, b.val), absmask)); \ +} \ +inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpvec res = v_fma(a, a, v_mul(b, b)); \ + return _Tpvec(_mm_sqrt_##suffix(res.val)); \ +} \ +inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return v_fma(a, a, v_mul(b, b)); \ +} \ +inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ \ + return v_fma(a, b, c); \ +} + +OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float32x4, float, __m128, ps, _mm_set1_epi32((int)0x7fffffff)) +OPENCV_HAL_IMPL_SSE_MISC_FLT_OP(v_float64x2, double, __m128d, pd, _mm_srli_epi64(_mm_set1_epi32(-1), 1)) + +#define OPENCV_HAL_IMPL_SSE_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, srai) \ +inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ +} \ +inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(srai(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shl(const _Tpuvec& a) \ +{ \ + return _Tpuvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shl(const _Tpsvec& a) \ +{ \ + return _Tpsvec(_mm_slli_##suffix(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shr(const _Tpuvec& a) \ +{ \ + return _Tpuvec(_mm_srli_##suffix(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shr(const _Tpsvec& a) \ +{ \ + return _Tpsvec(srai(a.val, imm)); \ +} + +OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint16x8, v_int16x8, epi16, _mm_srai_epi16) +OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint32x4, v_int32x4, epi32, _mm_srai_epi32) +OPENCV_HAL_IMPL_SSE_SHIFT_OP(v_uint64x2, v_int64x2, epi64, v_srai_epi64) + +namespace hal_sse_internal +{ + template 16)), + bool is_first = (imm == 0), + bool is_half = (imm == 8), + bool is_second = (imm == 16), + bool is_other = (((imm > 0) && (imm < 8)) || ((imm > 8) && (imm < 16)))> + class v_sse_palignr_u8_class; + + template + class v_sse_palignr_u8_class; + + template + class v_sse_palignr_u8_class + { + public: + inline __m128i operator()(const __m128i& a, const __m128i&) const + { + return a; + } + }; + + template + class v_sse_palignr_u8_class + { + public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + return _mm_unpacklo_epi64(_mm_unpackhi_epi64(a, a), b); + } + }; + + template + class v_sse_palignr_u8_class + { + public: + inline __m128i operator()(const __m128i&, const __m128i& b) const + { + return b; + } + }; + + template + class v_sse_palignr_u8_class + { +#if CV_SSSE3 + public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + return _mm_alignr_epi8(b, a, imm); + } +#else + public: + inline __m128i operator()(const __m128i& a, const __m128i& b) const + { + enum { imm2 = (sizeof(__m128i) - imm) }; + return _mm_or_si128(_mm_srli_si128(a, imm), _mm_slli_si128(b, imm2)); + } +#endif + }; + + template + inline __m128i v_sse_palignr_u8(const __m128i& a, const __m128i& b) + { + CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_sse_palignr_u8."); + return v_sse_palignr_u8_class()(a, b); + } +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a) +{ + using namespace hal_sse_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + _mm_srli_si128( + v_sse_reinterpret_as<__m128i>(a.val), imm2))); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a) +{ + using namespace hal_sse_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + _mm_slli_si128( + v_sse_reinterpret_as<__m128i>(a.val), imm2))); +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_sse_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + v_sse_palignr_u8( + v_sse_reinterpret_as<__m128i>(a.val), + v_sse_reinterpret_as<__m128i>(b.val)))); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_sse_internal; + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_sse_reinterpret_as( + v_sse_palignr_u8( + v_sse_reinterpret_as<__m128i>(b.val), + v_sse_reinterpret_as<__m128i>(a.val)))); +} + +#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(_Tpvec, _Tp) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(_mm_loadu_si128((const __m128i*)ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(_mm_load_si128((const __m128i*)ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(_mm_loadl_epi64((const __m128i*)ptr)); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + return _Tpvec(_mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ + _mm_loadl_epi64((const __m128i*)ptr1))); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storeu_si128((__m128i*)ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ _mm_store_si128((__m128i*)ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ _mm_stream_si128((__m128i*)ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ +{ \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm_storeu_si128((__m128i*)ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm_stream_si128((__m128i*)ptr, a.val); \ + else \ + _mm_store_si128((__m128i*)ptr, a.val); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storel_epi64((__m128i*)ptr, a.val); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a.val, a.val)); } + +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint8x16, uchar) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int8x16, schar) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint16x8, ushort) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int16x8, short) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint32x4, unsigned) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int32x4, int) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_uint64x2, uint64) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INT_OP(v_int64x2, int64) + +#define OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(_Tpvec, _Tp, suffix) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(_mm_loadu_##suffix(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(_mm_load_##suffix(ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(_mm_castsi128_##suffix(_mm_loadl_epi64((const __m128i*)ptr))); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + return _Tpvec(_mm_castsi128_##suffix( \ + _mm_unpacklo_epi64(_mm_loadl_epi64((const __m128i*)ptr0), \ + _mm_loadl_epi64((const __m128i*)ptr1)))); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storeu_##suffix(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ _mm_store_##suffix(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ _mm_stream_##suffix(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ +{ \ + if( mode == hal::STORE_UNALIGNED ) \ + _mm_storeu_##suffix(ptr, a.val); \ + else if( mode == hal::STORE_ALIGNED_NOCACHE ) \ + _mm_stream_##suffix(ptr, a.val); \ + else \ + _mm_store_##suffix(ptr, a.val); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ _mm_storel_epi64((__m128i*)ptr, _mm_cast##suffix##_si128(a.val)); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + __m128i a1 = _mm_cast##suffix##_si128(a.val); \ + _mm_storel_epi64((__m128i*)ptr, _mm_unpackhi_epi64(a1, a1)); \ +} + +OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float32x4, float, ps) +OPENCV_HAL_IMPL_SSE_LOADSTORE_FLT_OP(v_float64x2, double, pd) + +inline unsigned v_reduce_sum(const v_uint8x16& a) +{ + __m128i half = _mm_sad_epu8(a.val, _mm_setzero_si128()); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); +} +inline int v_reduce_sum(const v_int8x16& a) +{ + __m128i half = _mm_set1_epi8((schar)-128); + half = _mm_sad_epu8(_mm_xor_si128(a.val, half), _mm_setzero_si128()); + return _mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))) - 2048; +} +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(func) \ +inline schar v_reduce_##func(const v_int8x16& a) \ +{ \ + __m128i val = a.val; \ + __m128i smask = _mm_set1_epi8((schar)-128); \ + val = _mm_xor_si128(val, smask); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ + return (schar)_mm_cvtsi128_si32(val) ^ (schar)-128; \ +} \ +inline uchar v_reduce_##func(const v_uint8x16& a) \ +{ \ + __m128i val = a.val; \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,2)); \ + val = _mm_##func##_epu8(val, _mm_srli_si128(val,1)); \ + return (uchar)_mm_cvtsi128_si32(val); \ +} +OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_16(min) + +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(_Tpvec, scalartype, func, suffix, sbit) \ +inline scalartype v_reduce_##func(const v_##_Tpvec& a) \ +{ \ + __m128i val = a.val; \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ + return (scalartype)_mm_cvtsi128_si32(val); \ +} \ +inline unsigned scalartype v_reduce_##func(const v_u##_Tpvec& a) \ +{ \ + __m128i val = a.val; \ + __m128i smask = _mm_set1_epi16(sbit); \ + val = _mm_xor_si128(val, smask); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,8)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,4)); \ + val = _mm_##func##_##suffix(val, _mm_srli_si128(val,2)); \ + return (unsigned scalartype)(_mm_cvtsi128_si32(val) ^ sbit); \ +} +OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, max, epi16, (short)-32768) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_8(int16x8, short, min, epi16, (short)-32768) + +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, cast_from, cast_to, extract) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + regtype val = a.val; \ + val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 8))); \ + val = _mm_add_##suffix(val, cast_to(_mm_srli_si128(cast_from(val), 4))); \ + return (scalartype)_mm_cvt##extract(val); \ +} + +#define OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(_Tpvec, scalartype, func, scalar_func) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + scalartype CV_DECL_ALIGNED(16) buf[4]; \ + v_store_aligned(buf, a); \ + scalartype s0 = scalar_func(buf[0], buf[1]); \ + scalartype s1 = scalar_func(buf[2], buf[3]); \ + return scalar_func(s0, s1); \ +} + +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_uint32x4, unsigned, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_int32x4, int, __m128i, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP, si128_si32) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4_SUM(v_float32x4, float, __m128, ps, _mm_castps_si128, _mm_castsi128_ps, ss_f32) + +inline int v_reduce_sum(const v_int16x8& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } +inline unsigned v_reduce_sum(const v_uint16x8& a) +{ return v_reduce_sum(v_add(v_expand_low(a), v_expand_high(a))); } + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ + uint64 CV_DECL_ALIGNED(32) idx[2]; + v_store_aligned(idx, a); + return idx[0] + idx[1]; +} +inline int64 v_reduce_sum(const v_int64x2& a) +{ + int64 CV_DECL_ALIGNED(32) idx[2]; + v_store_aligned(idx, a); + return idx[0] + idx[1]; +} +inline double v_reduce_sum(const v_float64x2& a) +{ + double CV_DECL_ALIGNED(32) idx[2]; + v_store_aligned(idx, a); + return idx[0] + idx[1]; +} + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ +#if CV_SSE3 + __m128 ab = _mm_hadd_ps(a.val, b.val); + __m128 cd = _mm_hadd_ps(c.val, d.val); + return v_float32x4(_mm_hadd_ps(ab, cd)); +#else + __m128 ac = _mm_add_ps(_mm_unpacklo_ps(a.val, c.val), _mm_unpackhi_ps(a.val, c.val)); + __m128 bd = _mm_add_ps(_mm_unpacklo_ps(b.val, d.val), _mm_unpackhi_ps(b.val, d.val)); + return v_float32x4(_mm_add_ps(_mm_unpacklo_ps(ac, bd), _mm_unpackhi_ps(ac, bd))); +#endif +} + +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, max, std::max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_uint32x4, unsigned, min, std::min) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, max, std::max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_int32x4, int, min, std::min) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, max, std::max) +OPENCV_HAL_IMPL_SSE_REDUCE_OP_4(v_float32x4, float, min, std::min) + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + __m128i half = _mm_sad_epu8(a.val, b.val); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + __m128i half = _mm_set1_epi8(0x7f); + half = _mm_sad_epu8(_mm_add_epi8(a.val, half), _mm_add_epi8(b.val, half)); + return (unsigned)_mm_cvtsi128_si32(_mm_add_epi32(half, _mm_unpackhi_epi64(half, half))); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} + +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ + __m128i m1 = _mm_set1_epi32(0x55555555); + __m128i m2 = _mm_set1_epi32(0x33333333); + __m128i m4 = _mm_set1_epi32(0x0f0f0f0f); + __m128i p = a.val; + p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 1), m1), _mm_and_si128(p, m1)); + p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 2), m2), _mm_and_si128(p, m2)); + p = _mm_add_epi32(_mm_and_si128(_mm_srli_epi32(p, 4), m4), _mm_and_si128(p, m4)); + return v_uint8x16(p); +} +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); +} +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); +} +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ + return v_uint64x2(_mm_sad_epu8(v_popcount(v_reinterpret_as_u8(a)).val, _mm_setzero_si128())); +} +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(_Tpvec, suffix, cast_op, allmask) \ +inline int v_signmask(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)); } \ +inline bool v_check_all(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) == allmask; } \ +inline bool v_check_any(const _Tpvec& a) { return _mm_movemask_##suffix(cast_op(a.val)) != 0; } +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint8x16, epi8, OPENCV_HAL_NOP, 65535) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int8x16, epi8, OPENCV_HAL_NOP, 65535) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint32x4, ps, _mm_castsi128_ps, 15) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int32x4, ps, _mm_castsi128_ps, 15) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_uint64x2, pd, _mm_castsi128_pd, 3) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_int64x2, pd, _mm_castsi128_pd, 3) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float32x4, ps, OPENCV_HAL_NOP, 15) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS(v_float64x2, pd, OPENCV_HAL_NOP, 3) + +#define OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(_Tpvec) \ +inline int v_signmask(const _Tpvec& a) { return _mm_movemask_epi8(_mm_packs_epi16(a.val, a.val)) & 255; } \ +inline bool v_check_all(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) == 0xaaaa; } \ +inline bool v_check_any(const _Tpvec& a) { return (_mm_movemask_epi8(a.val) & 0xaaaa) != 0; } +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_uint16x8) +OPENCV_HAL_IMPL_SSE_CHECK_SIGNS_SHORT(v_int16x8) + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +#if CV_SSE4_1 +#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, cast_ret, cast, suffix) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(cast_ret(_mm_blendv_##suffix(cast(b.val), cast(a.val), cast(mask.val)))); \ +} + +OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, OPENCV_HAL_NOP, OPENCV_HAL_NOP, epi8) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, _mm_castps_si128, _mm_castsi128_ps, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, _mm_castps_si128, _mm_castsi128_ps, ps) +// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, TBD, TBD, pd) +// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, TBD, TBD, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, OPENCV_HAL_NOP, OPENCV_HAL_NOP, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, OPENCV_HAL_NOP, OPENCV_HAL_NOP, pd) + +#else // CV_SSE4_1 + +#define OPENCV_HAL_IMPL_SSE_SELECT(_Tpvec, suffix) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(_mm_xor_##suffix(b.val, _mm_and_##suffix(_mm_xor_##suffix(b.val, a.val), mask.val))); \ +} + +OPENCV_HAL_IMPL_SSE_SELECT(v_uint8x16, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_int8x16, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint16x8, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_int16x8, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_uint32x4, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_int32x4, si128) +// OPENCV_HAL_IMPL_SSE_SELECT(v_uint64x2, si128) +// OPENCV_HAL_IMPL_SSE_SELECT(v_int64x2, si128) +OPENCV_HAL_IMPL_SSE_SELECT(v_float32x4, ps) +OPENCV_HAL_IMPL_SSE_SELECT(v_float64x2, pd) +#endif + +/* Expand */ +#define OPENCV_HAL_IMPL_SSE_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ + inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ + { \ + b0.val = intrin(a.val); \ + b1.val = __CV_CAT(intrin, _high)(a.val); \ + } \ + inline _Tpwvec v_expand_low(const _Tpvec& a) \ + { return _Tpwvec(intrin(a.val)); } \ + inline _Tpwvec v_expand_high(const _Tpvec& a) \ + { return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ + inline _Tpwvec v_load_expand(const _Tp* ptr) \ + { \ + __m128i a = _mm_loadl_epi64((const __m128i*)ptr); \ + return _Tpwvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_SSE_EXPAND(v_uint8x16, v_uint16x8, uchar, _v128_cvtepu8_epi16) +OPENCV_HAL_IMPL_SSE_EXPAND(v_int8x16, v_int16x8, schar, _v128_cvtepi8_epi16) +OPENCV_HAL_IMPL_SSE_EXPAND(v_uint16x8, v_uint32x4, ushort, _v128_cvtepu16_epi32) +OPENCV_HAL_IMPL_SSE_EXPAND(v_int16x8, v_int32x4, short, _v128_cvtepi16_epi32) +OPENCV_HAL_IMPL_SSE_EXPAND(v_uint32x4, v_uint64x2, unsigned, _v128_cvtepu32_epi64) +OPENCV_HAL_IMPL_SSE_EXPAND(v_int32x4, v_int64x2, int, _v128_cvtepi32_epi64) + +#define OPENCV_HAL_IMPL_SSE_EXPAND_Q(_Tpvec, _Tp, intrin) \ + inline _Tpvec v_load_expand_q(const _Tp* ptr) \ + { \ + typedef int CV_DECL_ALIGNED(1) unaligned_int; \ + __m128i a = _mm_cvtsi32_si128(*(const unaligned_int*)ptr); \ + return _Tpvec(intrin(a)); \ + } + +OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_uint32x4, uchar, _v128_cvtepu8_epi32) +OPENCV_HAL_IMPL_SSE_EXPAND_Q(v_int32x4, schar, _v128_cvtepi8_epi32) + +#define OPENCV_HAL_IMPL_SSE_UNPACKS(_Tpvec, suffix, cast_from, cast_to) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ +{ \ + b0.val = _mm_unpacklo_##suffix(a0.val, a1.val); \ + b1.val = _mm_unpackhi_##suffix(a0.val, a1.val); \ +} \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ + return _Tpvec(cast_to(_mm_unpacklo_epi64(a1, b1))); \ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ + return _Tpvec(cast_to(_mm_unpackhi_epi64(a1, b1))); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + __m128i a1 = cast_from(a.val), b1 = cast_from(b.val); \ + c.val = cast_to(_mm_unpacklo_epi64(a1, b1)); \ + d.val = cast_to(_mm_unpackhi_epi64(a1, b1)); \ +} + +OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_int8x16, epi8, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_int16x8, epi16, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) +OPENCV_HAL_IMPL_SSE_UNPACKS(v_float64x2, pd, _mm_castpd_si128, _mm_castsi128_pd) + +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ +#if CV_SSSE3 + static const __m128i perm = _mm_setr_epi8(15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + return v_uint8x16(_mm_shuffle_epi8(a.val, perm)); +#else + uchar CV_DECL_ALIGNED(32) d[16]; + v_store_aligned(d, a); + return v_uint8x16(d[15], d[14], d[13], d[12], d[11], d[10], d[9], d[8], d[7], d[6], d[5], d[4], d[3], d[2], d[1], d[0]); +#endif +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ +#if CV_SSSE3 + static const __m128i perm = _mm_setr_epi8(14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1); + return v_uint16x8(_mm_shuffle_epi8(a.val, perm)); +#else + __m128i r = _mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3)); + r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); + r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(2, 3, 0, 1)); + return v_uint16x8(r); +#endif +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + return v_uint32x4(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(0, 1, 2, 3))); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + return v_uint64x2(_mm_shuffle_epi32(a.val, _MM_SHUFFLE(1, 0, 3, 2))); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +template +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) +{ + return v_rotate_right(a, b); +} + +inline v_int32x4 v_round(const v_float32x4& a) +{ return v_int32x4(_mm_cvtps_epi32(a.val)); } + +inline v_int32x4 v_floor(const v_float32x4& a) +{ + __m128i a1 = _mm_cvtps_epi32(a.val); + __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(_mm_cvtepi32_ps(a1), a.val)); + return v_int32x4(_mm_add_epi32(a1, mask)); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + __m128i a1 = _mm_cvtps_epi32(a.val); + __m128i mask = _mm_castps_si128(_mm_cmpgt_ps(a.val, _mm_cvtepi32_ps(a1))); + return v_int32x4(_mm_sub_epi32(a1, mask)); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(_mm_cvttps_epi32(a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a) +{ return v_int32x4(_mm_cvtpd_epi32(a.val)); } + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + __m128i ai = _mm_cvtpd_epi32(a.val), bi = _mm_cvtpd_epi32(b.val); + return v_int32x4(_mm_unpacklo_epi64(ai, bi)); +} + +inline v_int32x4 v_floor(const v_float64x2& a) +{ + __m128i a1 = _mm_cvtpd_epi32(a.val); + __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(_mm_cvtepi32_pd(a1), a.val)); + mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 + return v_int32x4(_mm_add_epi32(a1, mask)); +} + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ + __m128i a1 = _mm_cvtpd_epi32(a.val); + __m128i mask = _mm_castpd_si128(_mm_cmpgt_pd(a.val, _mm_cvtepi32_pd(a1))); + mask = _mm_srli_si128(_mm_slli_si128(mask, 4), 8); // m0 m0 m1 m1 => m0 m1 0 0 + return v_int32x4(_mm_sub_epi32(a1, mask)); +} + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ return v_int32x4(_mm_cvttpd_epi32(a.val)); } + +#define OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(_Tpvec, suffix, cast_from, cast_to) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, \ + _Tpvec& b2, _Tpvec& b3) \ +{ \ + __m128i t0 = cast_from(_mm_unpacklo_##suffix(a0.val, a1.val)); \ + __m128i t1 = cast_from(_mm_unpacklo_##suffix(a2.val, a3.val)); \ + __m128i t2 = cast_from(_mm_unpackhi_##suffix(a0.val, a1.val)); \ + __m128i t3 = cast_from(_mm_unpackhi_##suffix(a2.val, a3.val)); \ +\ + b0.val = cast_to(_mm_unpacklo_epi64(t0, t1)); \ + b1.val = cast_to(_mm_unpackhi_epi64(t0, t1)); \ + b2.val = cast_to(_mm_unpacklo_epi64(t2, t3)); \ + b3.val = cast_to(_mm_unpackhi_epi64(t2, t3)); \ +} + +OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_uint32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_int32x4, epi32, OPENCV_HAL_NOP, OPENCV_HAL_NOP) +OPENCV_HAL_IMPL_SSE_TRANSPOSE4x4(v_float32x4, ps, _mm_castps_si128, _mm_castsi128_ps) + +// load deinterleave +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) +{ + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + + __m128i t10 = _mm_unpacklo_epi8(t00, t01); + __m128i t11 = _mm_unpackhi_epi8(t00, t01); + + __m128i t20 = _mm_unpacklo_epi8(t10, t11); + __m128i t21 = _mm_unpackhi_epi8(t10, t11); + + __m128i t30 = _mm_unpacklo_epi8(t20, t21); + __m128i t31 = _mm_unpackhi_epi8(t20, t21); + + a.val = _mm_unpacklo_epi8(t30, t31); + b.val = _mm_unpackhi_epi8(t30, t31); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) +{ +#if CV_SSE4_1 + const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + __m128i s0 = _mm_loadu_si128((const __m128i*)ptr); + __m128i s1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + __m128i s2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); + __m128i a0 = _mm_blendv_epi8(_mm_blendv_epi8(s0, s1, m0), s2, m1); + __m128i b0 = _mm_blendv_epi8(_mm_blendv_epi8(s1, s2, m0), s0, m1); + __m128i c0 = _mm_blendv_epi8(_mm_blendv_epi8(s2, s0, m0), s1, m1); + const __m128i sh_b = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13); + const __m128i sh_g = _mm_setr_epi8(1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14); + const __m128i sh_r = _mm_setr_epi8(2, 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15); + a0 = _mm_shuffle_epi8(a0, sh_b); + b0 = _mm_shuffle_epi8(b0, sh_g); + c0 = _mm_shuffle_epi8(c0, sh_r); + a.val = a0; + b.val = b0; + c.val = c0; +#elif CV_SSSE3 + const __m128i m0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, 1, 4, 7, 10, 13, 2, 5, 8, 11, 14); + const __m128i m1 = _mm_alignr_epi8(m0, m0, 11); + const __m128i m2 = _mm_alignr_epi8(m0, m0, 6); + + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); + + __m128i s0 = _mm_shuffle_epi8(t0, m0); + __m128i s1 = _mm_shuffle_epi8(t1, m1); + __m128i s2 = _mm_shuffle_epi8(t2, m2); + + t0 = _mm_alignr_epi8(s1, _mm_slli_si128(s0, 10), 5); + a.val = _mm_alignr_epi8(s2, t0, 5); + + t1 = _mm_alignr_epi8(_mm_srli_si128(s1, 5), _mm_slli_si128(s0, 5), 6); + b.val = _mm_alignr_epi8(_mm_srli_si128(s2, 5), t1, 5); + + t2 = _mm_alignr_epi8(_mm_srli_si128(s2, 10), s1, 11); + c.val = _mm_alignr_epi8(t2, s0, 11); +#else + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 32)); + + __m128i t10 = _mm_unpacklo_epi8(t00, _mm_unpackhi_epi64(t01, t01)); + __m128i t11 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t00, t00), t02); + __m128i t12 = _mm_unpacklo_epi8(t01, _mm_unpackhi_epi64(t02, t02)); + + __m128i t20 = _mm_unpacklo_epi8(t10, _mm_unpackhi_epi64(t11, t11)); + __m128i t21 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t10, t10), t12); + __m128i t22 = _mm_unpacklo_epi8(t11, _mm_unpackhi_epi64(t12, t12)); + + __m128i t30 = _mm_unpacklo_epi8(t20, _mm_unpackhi_epi64(t21, t21)); + __m128i t31 = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t20, t20), t22); + __m128i t32 = _mm_unpacklo_epi8(t21, _mm_unpackhi_epi64(t22, t22)); + + a.val = _mm_unpacklo_epi8(t30, _mm_unpackhi_epi64(t31, t31)); + b.val = _mm_unpacklo_epi8(_mm_unpackhi_epi64(t30, t30), t32); + c.val = _mm_unpacklo_epi8(t31, _mm_unpackhi_epi64(t32, t32)); +#endif +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) +{ + __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... + __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... + __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 32)); // a8 b8 c8 d8 ... + __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 48)); // a12 b12 c12 d12 ... + + __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 a8 b0 b8 ... + __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a2 a10 b2 b10 ... + __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a4 a12 b4 b12 ... + __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a6 a14 b6 b14 ... + + u0 = _mm_unpacklo_epi8(v0, v2); // a0 a4 a8 a12 ... + u1 = _mm_unpacklo_epi8(v1, v3); // a2 a6 a10 a14 ... + u2 = _mm_unpackhi_epi8(v0, v2); // a1 a5 a9 a13 ... + u3 = _mm_unpackhi_epi8(v1, v3); // a3 a7 a11 a15 ... + + v0 = _mm_unpacklo_epi8(u0, u1); // a0 a2 a4 a6 ... + v1 = _mm_unpacklo_epi8(u2, u3); // a1 a3 a5 a7 ... + v2 = _mm_unpackhi_epi8(u0, u1); // c0 c2 c4 c6 ... + v3 = _mm_unpackhi_epi8(u2, u3); // c1 c3 c5 c7 ... + + a.val = _mm_unpacklo_epi8(v0, v1); + b.val = _mm_unpackhi_epi8(v0, v1); + c.val = _mm_unpacklo_epi8(v2, v3); + d.val = _mm_unpackhi_epi8(v2, v3); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) +{ + __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 a2 b2 a3 b3 + __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); // a4 b4 a5 b5 a6 b6 a7 b7 + + __m128i v2 = _mm_unpacklo_epi16(v0, v1); // a0 a4 b0 b4 a1 a5 b1 b5 + __m128i v3 = _mm_unpackhi_epi16(v0, v1); // a2 a6 b2 b6 a3 a7 b3 b7 + __m128i v4 = _mm_unpacklo_epi16(v2, v3); // a0 a2 a4 a6 b0 b2 b4 b6 + __m128i v5 = _mm_unpackhi_epi16(v2, v3); // a1 a3 a5 a7 b1 b3 b5 b7 + + a.val = _mm_unpacklo_epi16(v4, v5); // a0 a1 a2 a3 a4 a5 a6 a7 + b.val = _mm_unpackhi_epi16(v4, v5); // b0 b1 ab b3 b4 b5 b6 b7 +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) +{ +#if CV_SSE4_1 + __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); + __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 8)); + __m128i v2 = _mm_loadu_si128((__m128i*)(ptr + 16)); + __m128i a0 = _mm_blend_epi16(_mm_blend_epi16(v0, v1, 0x92), v2, 0x24); + __m128i b0 = _mm_blend_epi16(_mm_blend_epi16(v2, v0, 0x92), v1, 0x24); + __m128i c0 = _mm_blend_epi16(_mm_blend_epi16(v1, v2, 0x92), v0, 0x24); + + const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m128i sh_b = _mm_setr_epi8(2, 3, 8, 9, 14, 15, 4, 5, 10, 11, 0, 1, 6, 7, 12, 13); + const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + a0 = _mm_shuffle_epi8(a0, sh_a); + b0 = _mm_shuffle_epi8(b0, sh_b); + c0 = _mm_shuffle_epi8(c0, sh_c); + + a.val = a0; + b.val = b0; + c.val = c0; +#else + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 8)); + __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 16)); + + __m128i t10 = _mm_unpacklo_epi16(t00, _mm_unpackhi_epi64(t01, t01)); + __m128i t11 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t00, t00), t02); + __m128i t12 = _mm_unpacklo_epi16(t01, _mm_unpackhi_epi64(t02, t02)); + + __m128i t20 = _mm_unpacklo_epi16(t10, _mm_unpackhi_epi64(t11, t11)); + __m128i t21 = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t10, t10), t12); + __m128i t22 = _mm_unpacklo_epi16(t11, _mm_unpackhi_epi64(t12, t12)); + + a.val = _mm_unpacklo_epi16(t20, _mm_unpackhi_epi64(t21, t21)); + b.val = _mm_unpacklo_epi16(_mm_unpackhi_epi64(t20, t20), t22); + c.val = _mm_unpacklo_epi16(t21, _mm_unpackhi_epi64(t22, t22)); +#endif +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) +{ + __m128i u0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 c0 d0 a1 b1 c1 d1 + __m128i u1 = _mm_loadu_si128((const __m128i*)(ptr + 8)); // a2 b2 c2 d2 ... + __m128i u2 = _mm_loadu_si128((const __m128i*)(ptr + 16)); // a4 b4 c4 d4 ... + __m128i u3 = _mm_loadu_si128((const __m128i*)(ptr + 24)); // a6 b6 c6 d6 ... + + __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 a4 b0 b4 ... + __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a1 a5 b1 b5 ... + __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a2 a6 b2 b6 ... + __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a3 a7 b3 b7 ... + + u0 = _mm_unpacklo_epi16(v0, v2); // a0 a2 a4 a6 ... + u1 = _mm_unpacklo_epi16(v1, v3); // a1 a3 a5 a7 ... + u2 = _mm_unpackhi_epi16(v0, v2); // c0 c2 c4 c6 ... + u3 = _mm_unpackhi_epi16(v1, v3); // c1 c3 c5 c7 ... + + a.val = _mm_unpacklo_epi16(u0, u1); + b.val = _mm_unpackhi_epi16(u0, u1); + c.val = _mm_unpacklo_epi16(u2, u3); + d.val = _mm_unpackhi_epi16(u2, u3); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) +{ + __m128i v0 = _mm_loadu_si128((__m128i*)(ptr)); // a0 b0 a1 b1 + __m128i v1 = _mm_loadu_si128((__m128i*)(ptr + 4)); // a2 b2 a3 b3 + + __m128i v2 = _mm_unpacklo_epi32(v0, v1); // a0 a2 b0 b2 + __m128i v3 = _mm_unpackhi_epi32(v0, v1); // a1 a3 b1 b3 + + a.val = _mm_unpacklo_epi32(v2, v3); // a0 a1 a2 a3 + b.val = _mm_unpackhi_epi32(v2, v3); // b0 b1 ab b3 +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) +{ + __m128i t00 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t01 = _mm_loadu_si128((const __m128i*)(ptr + 4)); + __m128i t02 = _mm_loadu_si128((const __m128i*)(ptr + 8)); + + __m128i t10 = _mm_unpacklo_epi32(t00, _mm_unpackhi_epi64(t01, t01)); + __m128i t11 = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t00, t00), t02); + __m128i t12 = _mm_unpacklo_epi32(t01, _mm_unpackhi_epi64(t02, t02)); + + a.val = _mm_unpacklo_epi32(t10, _mm_unpackhi_epi64(t11, t11)); + b.val = _mm_unpacklo_epi32(_mm_unpackhi_epi64(t10, t10), t12); + c.val = _mm_unpacklo_epi32(t11, _mm_unpackhi_epi64(t12, t12)); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) +{ + v_uint32x4 s0(_mm_loadu_si128((const __m128i*)ptr)); // a0 b0 c0 d0 + v_uint32x4 s1(_mm_loadu_si128((const __m128i*)(ptr + 4))); // a1 b1 c1 d1 + v_uint32x4 s2(_mm_loadu_si128((const __m128i*)(ptr + 8))); // a2 b2 c2 d2 + v_uint32x4 s3(_mm_loadu_si128((const __m128i*)(ptr + 12))); // a3 b3 c3 d3 + + v_transpose4x4(s0, s1, s2, s3, a, b, c, d); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) +{ + __m128 u0 = _mm_loadu_ps(ptr); // a0 b0 a1 b1 + __m128 u1 = _mm_loadu_ps((ptr + 4)); // a2 b2 a3 b3 + + a.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); // a0 a1 a2 a3 + b.val = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(3, 1, 3, 1)); // b0 b1 ab b3 +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) +{ + __m128 t0 = _mm_loadu_ps(ptr + 0); + __m128 t1 = _mm_loadu_ps(ptr + 4); + __m128 t2 = _mm_loadu_ps(ptr + 8); + + __m128 at12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 1, 0, 2)); + a.val = _mm_shuffle_ps(t0, at12, _MM_SHUFFLE(2, 0, 3, 0)); + + __m128 bt01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 0, 0, 1)); + __m128 bt12 = _mm_shuffle_ps(t1, t2, _MM_SHUFFLE(0, 2, 0, 3)); + b.val = _mm_shuffle_ps(bt01, bt12, _MM_SHUFFLE(2, 0, 2, 0)); + + __m128 ct01 = _mm_shuffle_ps(t0, t1, _MM_SHUFFLE(0, 1, 0, 2)); + c.val = _mm_shuffle_ps(ct01, t2, _MM_SHUFFLE(3, 0, 2, 0)); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) +{ + __m128 t0 = _mm_loadu_ps(ptr + 0); + __m128 t1 = _mm_loadu_ps(ptr + 4); + __m128 t2 = _mm_loadu_ps(ptr + 8); + __m128 t3 = _mm_loadu_ps(ptr + 12); + __m128 t02lo = _mm_unpacklo_ps(t0, t2); + __m128 t13lo = _mm_unpacklo_ps(t1, t3); + __m128 t02hi = _mm_unpackhi_ps(t0, t2); + __m128 t13hi = _mm_unpackhi_ps(t1, t3); + a.val = _mm_unpacklo_ps(t02lo, t13lo); + b.val = _mm_unpackhi_ps(t02lo, t13lo); + c.val = _mm_unpacklo_ps(t02hi, t13hi); + d.val = _mm_unpackhi_ps(t02hi, t13hi); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) +{ + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); + + a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); + b = v_uint64x2(_mm_unpackhi_epi64(t0, t1)); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) +{ + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0, b0 + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0, a1 + __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // b1, c1 + + t1 = _mm_shuffle_epi32(t1, 0x4e); // a1, c0 + + a = v_uint64x2(_mm_unpacklo_epi64(t0, t1)); + b = v_uint64x2(_mm_unpacklo_epi64(_mm_unpackhi_epi64(t0, t0), t2)); + c = v_uint64x2(_mm_unpackhi_epi64(t1, t2)); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, + v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) +{ + __m128i t0 = _mm_loadu_si128((const __m128i*)ptr); // a0 b0 + __m128i t1 = _mm_loadu_si128((const __m128i*)(ptr + 2)); // c0 d0 + __m128i t2 = _mm_loadu_si128((const __m128i*)(ptr + 4)); // a1 b1 + __m128i t3 = _mm_loadu_si128((const __m128i*)(ptr + 6)); // c1 d1 + + a = v_uint64x2(_mm_unpacklo_epi64(t0, t2)); + b = v_uint64x2(_mm_unpackhi_epi64(t0, t2)); + c = v_uint64x2(_mm_unpacklo_epi64(t1, t3)); + d = v_uint64x2(_mm_unpackhi_epi64(t1, t3)); +} + +// store interleave + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi8(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi8(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 16), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 16), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 16), v1); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ +#if CV_SSE4_1 + const __m128i sh_a = _mm_setr_epi8(0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5); + const __m128i sh_b = _mm_setr_epi8(5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10); + const __m128i sh_c = _mm_setr_epi8(10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15); + __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); + __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); + __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); + + const __m128i m0 = _mm_setr_epi8(0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0); + const __m128i m1 = _mm_setr_epi8(0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0); + __m128i v0 = _mm_blendv_epi8(_mm_blendv_epi8(a0, b0, m1), c0, m0); + __m128i v1 = _mm_blendv_epi8(_mm_blendv_epi8(b0, c0, m1), a0, m0); + __m128i v2 = _mm_blendv_epi8(_mm_blendv_epi8(c0, a0, m1), b0, m0); +#elif CV_SSSE3 + const __m128i m0 = _mm_setr_epi8(0, 6, 11, 1, 7, 12, 2, 8, 13, 3, 9, 14, 4, 10, 15, 5); + const __m128i m1 = _mm_setr_epi8(5, 11, 0, 6, 12, 1, 7, 13, 2, 8, 14, 3, 9, 15, 4, 10); + const __m128i m2 = _mm_setr_epi8(10, 0, 5, 11, 1, 6, 12, 2, 7, 13, 3, 8, 14, 4, 9, 15); + + __m128i t0 = _mm_alignr_epi8(b.val, _mm_slli_si128(a.val, 10), 5); + t0 = _mm_alignr_epi8(c.val, t0, 5); + __m128i v0 = _mm_shuffle_epi8(t0, m0); + + __m128i t1 = _mm_alignr_epi8(_mm_srli_si128(b.val, 5), _mm_slli_si128(a.val, 5), 6); + t1 = _mm_alignr_epi8(_mm_srli_si128(c.val, 5), t1, 5); + __m128i v1 = _mm_shuffle_epi8(t1, m1); + + __m128i t2 = _mm_alignr_epi8(_mm_srli_si128(c.val, 10), b.val, 11); + t2 = _mm_alignr_epi8(t2, a.val, 11); + __m128i v2 = _mm_shuffle_epi8(t2, m2); +#else + __m128i z = _mm_setzero_si128(); + __m128i ab0 = _mm_unpacklo_epi8(a.val, b.val); + __m128i ab1 = _mm_unpackhi_epi8(a.val, b.val); + __m128i c0 = _mm_unpacklo_epi8(c.val, z); + __m128i c1 = _mm_unpackhi_epi8(c.val, z); + + __m128i p00 = _mm_unpacklo_epi16(ab0, c0); + __m128i p01 = _mm_unpackhi_epi16(ab0, c0); + __m128i p02 = _mm_unpacklo_epi16(ab1, c1); + __m128i p03 = _mm_unpackhi_epi16(ab1, c1); + + __m128i p10 = _mm_unpacklo_epi32(p00, p01); + __m128i p11 = _mm_unpackhi_epi32(p00, p01); + __m128i p12 = _mm_unpacklo_epi32(p02, p03); + __m128i p13 = _mm_unpackhi_epi32(p02, p03); + + __m128i p20 = _mm_unpacklo_epi64(p10, p11); + __m128i p21 = _mm_unpackhi_epi64(p10, p11); + __m128i p22 = _mm_unpacklo_epi64(p12, p13); + __m128i p23 = _mm_unpackhi_epi64(p12, p13); + + p20 = _mm_slli_si128(p20, 1); + p22 = _mm_slli_si128(p22, 1); + + __m128i p30 = _mm_slli_epi64(_mm_unpacklo_epi32(p20, p21), 8); + __m128i p31 = _mm_srli_epi64(_mm_unpackhi_epi32(p20, p21), 8); + __m128i p32 = _mm_slli_epi64(_mm_unpacklo_epi32(p22, p23), 8); + __m128i p33 = _mm_srli_epi64(_mm_unpackhi_epi32(p22, p23), 8); + + __m128i p40 = _mm_unpacklo_epi64(p30, p31); + __m128i p41 = _mm_unpackhi_epi64(p30, p31); + __m128i p42 = _mm_unpacklo_epi64(p32, p33); + __m128i p43 = _mm_unpackhi_epi64(p32, p33); + + __m128i v0 = _mm_or_si128(_mm_srli_si128(p40, 2), _mm_slli_si128(p41, 10)); + __m128i v1 = _mm_or_si128(_mm_srli_si128(p41, 6), _mm_slli_si128(p42, 6)); + __m128i v2 = _mm_or_si128(_mm_srli_si128(p42, 10), _mm_slli_si128(p43, 2)); +#endif + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 16), v1); + _mm_stream_si128((__m128i*)(ptr + 32), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 16), v1); + _mm_store_si128((__m128i*)(ptr + 32), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 16), v1); + _mm_storeu_si128((__m128i*)(ptr + 32), v2); + } +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, const v_uint8x16& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + __m128i u0 = _mm_unpacklo_epi8(a.val, c.val); // a0 c0 a1 c1 ... + __m128i u1 = _mm_unpackhi_epi8(a.val, c.val); // a8 c8 a9 c9 ... + __m128i u2 = _mm_unpacklo_epi8(b.val, d.val); // b0 d0 b1 d1 ... + __m128i u3 = _mm_unpackhi_epi8(b.val, d.val); // b8 d8 b9 d9 ... + + __m128i v0 = _mm_unpacklo_epi8(u0, u2); // a0 b0 c0 d0 ... + __m128i v1 = _mm_unpackhi_epi8(u0, u2); // a4 b4 c4 d4 ... + __m128i v2 = _mm_unpacklo_epi8(u1, u3); // a8 b8 c8 d8 ... + __m128i v3 = _mm_unpackhi_epi8(u1, u3); // a12 b12 c12 d12 ... + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 16), v1); + _mm_stream_si128((__m128i*)(ptr + 32), v2); + _mm_stream_si128((__m128i*)(ptr + 48), v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 16), v1); + _mm_store_si128((__m128i*)(ptr + 32), v2); + _mm_store_si128((__m128i*)(ptr + 48), v3); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 16), v1); + _mm_storeu_si128((__m128i*)(ptr + 32), v2); + _mm_storeu_si128((__m128i*)(ptr + 48), v3); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi16(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi16(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 8), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 8), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 8), v1); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, + const v_uint16x8& b, const v_uint16x8& c, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ +#if CV_SSE4_1 + const __m128i sh_a = _mm_setr_epi8(0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5, 10, 11); + const __m128i sh_b = _mm_setr_epi8(10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15, 4, 5); + const __m128i sh_c = _mm_setr_epi8(4, 5, 10, 11, 0, 1, 6, 7, 12, 13, 2, 3, 8, 9, 14, 15); + __m128i a0 = _mm_shuffle_epi8(a.val, sh_a); + __m128i b0 = _mm_shuffle_epi8(b.val, sh_b); + __m128i c0 = _mm_shuffle_epi8(c.val, sh_c); + + __m128i v0 = _mm_blend_epi16(_mm_blend_epi16(a0, b0, 0x92), c0, 0x24); + __m128i v1 = _mm_blend_epi16(_mm_blend_epi16(c0, a0, 0x92), b0, 0x24); + __m128i v2 = _mm_blend_epi16(_mm_blend_epi16(b0, c0, 0x92), a0, 0x24); +#else + __m128i z = _mm_setzero_si128(); + __m128i ab0 = _mm_unpacklo_epi16(a.val, b.val); + __m128i ab1 = _mm_unpackhi_epi16(a.val, b.val); + __m128i c0 = _mm_unpacklo_epi16(c.val, z); + __m128i c1 = _mm_unpackhi_epi16(c.val, z); + + __m128i p10 = _mm_unpacklo_epi32(ab0, c0); + __m128i p11 = _mm_unpackhi_epi32(ab0, c0); + __m128i p12 = _mm_unpacklo_epi32(ab1, c1); + __m128i p13 = _mm_unpackhi_epi32(ab1, c1); + + __m128i p20 = _mm_unpacklo_epi64(p10, p11); + __m128i p21 = _mm_unpackhi_epi64(p10, p11); + __m128i p22 = _mm_unpacklo_epi64(p12, p13); + __m128i p23 = _mm_unpackhi_epi64(p12, p13); + + p20 = _mm_slli_si128(p20, 2); + p22 = _mm_slli_si128(p22, 2); + + __m128i p30 = _mm_unpacklo_epi64(p20, p21); + __m128i p31 = _mm_unpackhi_epi64(p20, p21); + __m128i p32 = _mm_unpacklo_epi64(p22, p23); + __m128i p33 = _mm_unpackhi_epi64(p22, p23); + + __m128i v0 = _mm_or_si128(_mm_srli_si128(p30, 2), _mm_slli_si128(p31, 10)); + __m128i v1 = _mm_or_si128(_mm_srli_si128(p31, 6), _mm_slli_si128(p32, 6)); + __m128i v2 = _mm_or_si128(_mm_srli_si128(p32, 10), _mm_slli_si128(p33, 2)); +#endif + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 8), v1); + _mm_stream_si128((__m128i*)(ptr + 16), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 8), v1); + _mm_store_si128((__m128i*)(ptr + 16), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 8), v1); + _mm_storeu_si128((__m128i*)(ptr + 16), v2); + } +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + const v_uint16x8& c, const v_uint16x8& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + __m128i u0 = _mm_unpacklo_epi16(a.val, c.val); // a0 c0 a1 c1 ... + __m128i u1 = _mm_unpackhi_epi16(a.val, c.val); // a4 c4 a5 c5 ... + __m128i u2 = _mm_unpacklo_epi16(b.val, d.val); // b0 d0 b1 d1 ... + __m128i u3 = _mm_unpackhi_epi16(b.val, d.val); // b4 d4 b5 d5 ... + + __m128i v0 = _mm_unpacklo_epi16(u0, u2); // a0 b0 c0 d0 ... + __m128i v1 = _mm_unpackhi_epi16(u0, u2); // a2 b2 c2 d2 ... + __m128i v2 = _mm_unpacklo_epi16(u1, u3); // a4 b4 c4 d4 ... + __m128i v3 = _mm_unpackhi_epi16(u1, u3); // a6 b6 c6 d6 ... + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 8), v1); + _mm_stream_si128((__m128i*)(ptr + 16), v2); + _mm_stream_si128((__m128i*)(ptr + 24), v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 8), v1); + _mm_store_si128((__m128i*)(ptr + 16), v2); + _mm_store_si128((__m128i*)(ptr + 24), v3); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 8), v1); + _mm_storeu_si128((__m128i*)(ptr + 16), v2); + _mm_storeu_si128((__m128i*)(ptr + 24), v3); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi32(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi32(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 4), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 4), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 4), v1); + } +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + v_uint32x4 z = v_setzero_u32(), u0, u1, u2, u3; + v_transpose4x4(a, b, c, z, u0, u1, u2, u3); + + __m128i v0 = _mm_or_si128(u0.val, _mm_slli_si128(u1.val, 12)); + __m128i v1 = _mm_or_si128(_mm_srli_si128(u1.val, 4), _mm_slli_si128(u2.val, 8)); + __m128i v2 = _mm_or_si128(_mm_srli_si128(u2.val, 8), _mm_slli_si128(u3.val, 4)); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 4), v1); + _mm_stream_si128((__m128i*)(ptr + 8), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 4), v1); + _mm_store_si128((__m128i*)(ptr + 8), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 4), v1); + _mm_storeu_si128((__m128i*)(ptr + 8), v2); + } +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + v_uint32x4 v0, v1, v2, v3; + v_transpose4x4(a, b, c, d, v0, v1, v2, v3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0.val); + _mm_stream_si128((__m128i*)(ptr + 4), v1.val); + _mm_stream_si128((__m128i*)(ptr + 8), v2.val); + _mm_stream_si128((__m128i*)(ptr + 12), v3.val); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0.val); + _mm_store_si128((__m128i*)(ptr + 4), v1.val); + _mm_store_si128((__m128i*)(ptr + 8), v2.val); + _mm_store_si128((__m128i*)(ptr + 12), v3.val); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0.val); + _mm_storeu_si128((__m128i*)(ptr + 4), v1.val); + _mm_storeu_si128((__m128i*)(ptr + 8), v2.val); + _mm_storeu_si128((__m128i*)(ptr + 12), v3.val); + } +} + +// 2-channel, float only +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128 v0 = _mm_unpacklo_ps(a.val, b.val); // a0 b0 a1 b1 + __m128 v1 = _mm_unpackhi_ps(a.val, b.val); // a2 b2 a3 b3 + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_ps(ptr, v0); + _mm_stream_ps(ptr + 4, v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_ps(ptr, v0); + _mm_store_ps(ptr + 4, v1); + } + else + { + _mm_storeu_ps(ptr, v0); + _mm_storeu_ps(ptr + 4, v1); + } +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128 u0 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(0, 0, 0, 0)); + __m128 u1 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(1, 1, 0, 0)); + __m128 v0 = _mm_shuffle_ps(u0, u1, _MM_SHUFFLE(2, 0, 2, 0)); + __m128 u2 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(1, 1, 1, 1)); + __m128 u3 = _mm_shuffle_ps(a.val, b.val, _MM_SHUFFLE(2, 2, 2, 2)); + __m128 v1 = _mm_shuffle_ps(u2, u3, _MM_SHUFFLE(2, 0, 2, 0)); + __m128 u4 = _mm_shuffle_ps(c.val, a.val, _MM_SHUFFLE(3, 3, 2, 2)); + __m128 u5 = _mm_shuffle_ps(b.val, c.val, _MM_SHUFFLE(3, 3, 3, 3)); + __m128 v2 = _mm_shuffle_ps(u4, u5, _MM_SHUFFLE(2, 0, 2, 0)); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_ps(ptr, v0); + _mm_stream_ps(ptr + 4, v1); + _mm_stream_ps(ptr + 8, v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_ps(ptr, v0); + _mm_store_ps(ptr + 4, v1); + _mm_store_ps(ptr + 8, v2); + } + else + { + _mm_storeu_ps(ptr, v0); + _mm_storeu_ps(ptr + 4, v1); + _mm_storeu_ps(ptr + 8, v2); + } +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128 u0 = _mm_unpacklo_ps(a.val, c.val); + __m128 u1 = _mm_unpacklo_ps(b.val, d.val); + __m128 u2 = _mm_unpackhi_ps(a.val, c.val); + __m128 u3 = _mm_unpackhi_ps(b.val, d.val); + __m128 v0 = _mm_unpacklo_ps(u0, u1); + __m128 v2 = _mm_unpacklo_ps(u2, u3); + __m128 v1 = _mm_unpackhi_ps(u0, u1); + __m128 v3 = _mm_unpackhi_ps(u2, u3); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_ps(ptr, v0); + _mm_stream_ps(ptr + 4, v1); + _mm_stream_ps(ptr + 8, v2); + _mm_stream_ps(ptr + 12, v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_ps(ptr, v0); + _mm_store_ps(ptr + 4, v1); + _mm_store_ps(ptr + 8, v2); + _mm_store_ps(ptr + 12, v3); + } + else + { + _mm_storeu_ps(ptr, v0); + _mm_storeu_ps(ptr + 4, v1); + _mm_storeu_ps(ptr + 8, v2); + _mm_storeu_ps(ptr + 12, v3); + } +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); + __m128i v1 = _mm_unpackhi_epi64(a.val, b.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 2), v1); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 2), v1); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 2), v1); + } +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); + __m128i v1 = _mm_unpacklo_epi64(c.val, _mm_unpackhi_epi64(a.val, a.val)); + __m128i v2 = _mm_unpackhi_epi64(b.val, c.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 2), v1); + _mm_stream_si128((__m128i*)(ptr + 4), v2); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 2), v1); + _mm_store_si128((__m128i*)(ptr + 4), v2); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 2), v1); + _mm_storeu_si128((__m128i*)(ptr + 4), v2); + } +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, const v_uint64x2& d, + hal::StoreMode mode = hal::STORE_UNALIGNED) +{ + __m128i v0 = _mm_unpacklo_epi64(a.val, b.val); + __m128i v1 = _mm_unpacklo_epi64(c.val, d.val); + __m128i v2 = _mm_unpackhi_epi64(a.val, b.val); + __m128i v3 = _mm_unpackhi_epi64(c.val, d.val); + + if( mode == hal::STORE_ALIGNED_NOCACHE ) + { + _mm_stream_si128((__m128i*)(ptr), v0); + _mm_stream_si128((__m128i*)(ptr + 2), v1); + _mm_stream_si128((__m128i*)(ptr + 4), v2); + _mm_stream_si128((__m128i*)(ptr + 6), v3); + } + else if( mode == hal::STORE_ALIGNED ) + { + _mm_store_si128((__m128i*)(ptr), v0); + _mm_store_si128((__m128i*)(ptr + 2), v1); + _mm_store_si128((__m128i*)(ptr + 4), v2); + _mm_store_si128((__m128i*)(ptr + 6), v3); + } + else + { + _mm_storeu_si128((__m128i*)(ptr), v0); + _mm_storeu_si128((__m128i*)(ptr + 2), v1); + _mm_storeu_si128((__m128i*)(ptr + 4), v2); + _mm_storeu_si128((__m128i*)(ptr + 6), v3); + } +} + +#define OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_SSE_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(_mm_cvtepi32_ps(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + return v_float32x4(_mm_cvtpd_ps(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + return v_float32x4(_mm_movelh_ps(_mm_cvtpd_ps(a.val), _mm_cvtpd_ps(b.val))); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ + return v_float64x2(_mm_cvtepi32_pd(a.val)); +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ + return v_float64x2(_mm_cvtepi32_pd(_mm_srli_si128(a.val,8))); +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + return v_float64x2(_mm_cvtps_pd(a.val)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + return v_float64x2(_mm_cvtps_pd(_mm_movehl_ps(a.val, a.val))); +} + +// from (Mysticial and wim) https://stackoverflow.com/q/41144668 +inline v_float64x2 v_cvt_f64(const v_int64x2& v) +{ + // constants encoded as floating-point + __m128i magic_i_hi32 = _mm_set1_epi64x(0x4530000080000000); // 2^84 + 2^63 + __m128i magic_i_all = _mm_set1_epi64x(0x4530000080100000); // 2^84 + 2^63 + 2^52 + __m128d magic_d_all = _mm_castsi128_pd(magic_i_all); + // Blend the 32 lowest significant bits of v with magic_int_lo +#if CV_SSE4_1 + __m128i magic_i_lo = _mm_set1_epi64x(0x4330000000000000); // 2^52 + __m128i v_lo = _mm_blend_epi16(v.val, magic_i_lo, 0xcc); +#else + __m128i magic_i_lo = _mm_set1_epi32(0x43300000); // 2^52 + __m128i v_lo = _mm_unpacklo_epi32(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(0, 0, 2, 0)), magic_i_lo); +#endif + // Extract the 32 most significant bits of v + __m128i v_hi = _mm_srli_epi64(v.val, 32); + // Flip the msb of v_hi and blend with 0x45300000 + v_hi = _mm_xor_si128(v_hi, magic_i_hi32); + // Compute in double precision + __m128d v_hi_dbl = _mm_sub_pd(_mm_castsi128_pd(v_hi), magic_d_all); + // (v_hi - magic_d_all) + v_lo Do not assume associativity of floating point addition + __m128d result = _mm_add_pd(v_hi_dbl, _mm_castsi128_pd(v_lo)); + return v_float64x2(result); +} + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int8x16(_mm_setr_epi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]])); +#else + return v_int8x16(_mm_setr_epi64( + _mm_setr_pi8(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]]), + _mm_setr_pi8(tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]) + )); +#endif +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int8x16(_mm_setr_epi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3]), + *(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7]))); +#else + return v_int8x16(_mm_setr_epi64( + _mm_setr_pi16(*(const short*)(tab + idx[0]), *(const short*)(tab + idx[1]), *(const short*)(tab + idx[2]), *(const short*)(tab + idx[3])), + _mm_setr_pi16(*(const short*)(tab + idx[4]), *(const short*)(tab + idx[5]), *(const short*)(tab + idx[6]), *(const short*)(tab + idx[7])) + )); +#endif +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int8x16(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +#else + return v_int8x16(_mm_setr_epi64( + _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), + _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) + )); +#endif +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int16x8(_mm_setr_epi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]])); +#else + return v_int16x8(_mm_setr_epi64( + _mm_setr_pi16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]), + _mm_setr_pi16(tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]) + )); +#endif +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int16x8(_mm_setr_epi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), + *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +#else + return v_int16x8(_mm_setr_epi64( + _mm_setr_pi32(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1])), + _mm_setr_pi32(*(const int*)(tab + idx[2]), *(const int*)(tab + idx[3])) + )); +#endif +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ +#if defined(_MSC_VER) + return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], + tab[idx[2]], tab[idx[3]])); +#else + return v_int32x4(_mm_setr_epi64( + _mm_setr_pi32(tab[idx[0]], tab[idx[1]]), + _mm_setr_pi32(tab[idx[2]], tab[idx[3]]) + )); +#endif +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(_mm_set_epi64x(*(const int64_t*)(tab + idx[1]), *(const int64_t*)(tab + idx[0]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(_mm_set_epi64x(tab[idx[1]], tab[idx[0]])); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(_mm_loadu_si128((const __m128i*)(tab + idx[0]))); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_float64x2(_mm_castsi128_pd(_mm_loadu_si128((const __m128i*)(tab + idx[0])))); } + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + return v_int32x4(_mm_setr_epi32(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + return v_float32x4(_mm_setr_ps(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]])); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + int idx[2]; + v_store_low(idx, idxvec); + return v_float64x2(_mm_setr_pd(tab[idx[0]], tab[idx[1]])); +} + +// loads pairs from the table and deinterleaves them, e.g. returns: +// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), +// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) +// note that the indices are float's indices, not the float-pair indices. +// in theory, this function can be used to implement bilinear interpolation, +// when idxvec are the offsets within the image. +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + int CV_DECL_ALIGNED(32) idx[4]; + v_store_aligned(idx, idxvec); + __m128 z = _mm_setzero_ps(); + __m128 xy01 = _mm_loadl_pi(z, (__m64*)(tab + idx[0])); + __m128 xy23 = _mm_loadl_pi(z, (__m64*)(tab + idx[2])); + xy01 = _mm_loadh_pi(xy01, (__m64*)(tab + idx[1])); + xy23 = _mm_loadh_pi(xy23, (__m64*)(tab + idx[3])); + __m128 xxyy02 = _mm_unpacklo_ps(xy01, xy23); + __m128 xxyy13 = _mm_unpackhi_ps(xy01, xy23); + x = v_float32x4(_mm_unpacklo_ps(xxyy02, xxyy13)); + y = v_float32x4(_mm_unpackhi_ps(xxyy02, xxyy13)); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + int idx[2]; + v_store_low(idx, idxvec); + __m128d xy0 = _mm_loadu_pd(tab + idx[0]); + __m128d xy1 = _mm_loadu_pd(tab + idx[1]); + x = v_float64x2(_mm_unpacklo_pd(xy0, xy1)); + y = v_float64x2(_mm_unpackhi_pd(xy0, xy1)); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ +#if CV_SSSE3 + return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0d0e0c0b090a08, 0x0705060403010200))); +#else + __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); + a = _mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0)); + a = _mm_shuffle_epi32(a, _MM_SHUFFLE(3, 1, 2, 0)); + return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); +#endif +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ +#if CV_SSSE3 + return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0b0e0a0d090c08, 0x0703060205010400))); +#else + __m128i a = _mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); + return v_int8x16(_mm_unpacklo_epi8(a, _mm_unpackhi_epi64(a, a))); +#endif +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ +#if CV_SSSE3 + return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e0b0a0d0c0908, 0x0706030205040100))); +#else + __m128i a = _mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(3, 1, 2, 0)); + return v_int16x8(_mm_shufflehi_epi16(a, _MM_SHUFFLE(3, 1, 2, 0))); +#endif +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ +#if CV_SSSE3 + return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0x0f0e07060d0c0504, 0x0b0a030209080100))); +#else + return v_int16x8(_mm_unpacklo_epi16(vec.val, _mm_unpackhi_epi64(vec.val, vec.val))); +#endif +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + return v_int32x4(_mm_shuffle_epi32(vec.val, _MM_SHUFFLE(3, 1, 2, 0))); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) { return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ +#if CV_SSSE3 + return v_int8x16(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffffff0f0e0d0c0a, 0x0908060504020100))); +#else + __m128i mask = _mm_set1_epi64x(0x00000000FFFFFFFF); + __m128i a = _mm_srli_si128(_mm_or_si128(_mm_andnot_si128(mask, vec.val), _mm_and_si128(mask, _mm_sll_epi32(vec.val, _mm_set_epi64x(0, 8)))), 1); + return v_int8x16(_mm_srli_si128(_mm_shufflelo_epi16(a, _MM_SHUFFLE(2, 1, 0, 3)), 2)); +#endif +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ +#if CV_SSSE3 + return v_int16x8(_mm_shuffle_epi8(vec.val, _mm_set_epi64x(0xffff0f0e0d0c0b0a, 0x0908050403020100))); +#else + return v_int16x8(_mm_srli_si128(_mm_shufflelo_epi16(vec.val, _MM_SHUFFLE(2, 1, 0, 3)), 2)); +#endif +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +template +inline uchar v_extract_n(const v_uint8x16& v) +{ +#if CV_SSE4_1 + return (uchar)_mm_extract_epi8(v.val, i); +#else + return v_rotate_right(v).get0(); +#endif +} + +template +inline schar v_extract_n(const v_int8x16& v) +{ + return (schar)v_extract_n(v_reinterpret_as_u8(v)); +} + +template +inline ushort v_extract_n(const v_uint16x8& v) +{ + return (ushort)_mm_extract_epi16(v.val, i); +} + +template +inline short v_extract_n(const v_int16x8& v) +{ + return (short)v_extract_n(v_reinterpret_as_u16(v)); +} + +template +inline uint v_extract_n(const v_uint32x4& v) +{ +#if CV_SSE4_1 + return (uint)_mm_extract_epi32(v.val, i); +#else + return v_rotate_right(v).get0(); +#endif +} + +template +inline int v_extract_n(const v_int32x4& v) +{ + return (int)v_extract_n(v_reinterpret_as_u32(v)); +} + +template +inline uint64 v_extract_n(const v_uint64x2& v) +{ +#ifdef CV__SIMD_NATIVE_mm_extract_epi64 + return (uint64)_v128_extract_epi64(v.val); +#else + return v_rotate_right(v).get0(); +#endif +} + +template +inline int64 v_extract_n(const v_int64x2& v) +{ + return (int64)v_extract_n(v_reinterpret_as_u64(v)); +} + +template +inline float v_extract_n(const v_float32x4& v) +{ + union { uint iv; float fv; } d; + d.iv = v_extract_n(v_reinterpret_as_u32(v)); + return d.fv; +} + +template +inline double v_extract_n(const v_float64x2& v) +{ + union { uint64 iv; double dv; } d; + d.iv = v_extract_n(v_reinterpret_as_u64(v)); + return d.dv; +} + +template +inline v_int32x4 v_broadcast_element(const v_int32x4& v) +{ + return v_int32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& v) +{ + return v_uint32x4(_mm_shuffle_epi32(v.val, _MM_SHUFFLE(i,i,i,i))); +} + +template +inline v_float32x4 v_broadcast_element(const v_float32x4& v) +{ + return v_float32x4(_mm_shuffle_ps(v.val, v.val, _MM_SHUFFLE((char)i,(char)i,(char)i,(char)i))); +} + +////////////// FP16 support /////////////////////////// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ +#if CV_FP16 + return v_float32x4(_mm_cvtph_ps(_mm_loadu_si128((const __m128i*)ptr))); +#else + const __m128i z = _mm_setzero_si128(), delta = _mm_set1_epi32(0x38000000); + const __m128i signmask = _mm_set1_epi32(0x80000000), maxexp = _mm_set1_epi32(0x7c000000); + const __m128 deltaf = _mm_castsi128_ps(_mm_set1_epi32(0x38800000)); + __m128i bits = _mm_unpacklo_epi16(z, _mm_loadl_epi64((const __m128i*)ptr)); // h << 16 + __m128i e = _mm_and_si128(bits, maxexp), sign = _mm_and_si128(bits, signmask); + __m128i t = _mm_add_epi32(_mm_srli_epi32(_mm_xor_si128(bits, sign), 3), delta); // ((h & 0x7fff) << 13) + delta + __m128i zt = _mm_castps_si128(_mm_sub_ps(_mm_castsi128_ps(_mm_add_epi32(t, _mm_set1_epi32(1 << 23))), deltaf)); + + t = _mm_add_epi32(t, _mm_and_si128(delta, _mm_cmpeq_epi32(maxexp, e))); + __m128i zmask = _mm_cmpeq_epi32(e, z); + __m128i ft = v_select_si128(zmask, zt, t); + return v_float32x4(_mm_castsi128_ps(_mm_or_si128(ft, sign))); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ +#if CV_FP16 + __m128i fp16_value = _mm_cvtps_ph(v.val, 0); + _mm_storel_epi64((__m128i*)ptr, fp16_value); +#else + const __m128i signmask = _mm_set1_epi32(0x80000000); + const __m128i rval = _mm_set1_epi32(0x3f000000); + + __m128i t = _mm_castps_si128(v.val); + __m128i sign = _mm_srai_epi32(_mm_and_si128(t, signmask), 16); + t = _mm_andnot_si128(signmask, t); + + __m128i finitemask = _mm_cmpgt_epi32(_mm_set1_epi32(0x47800000), t); + __m128i isnan = _mm_cmpgt_epi32(t, _mm_set1_epi32(0x7f800000)); + __m128i naninf = v_select_si128(isnan, _mm_set1_epi32(0x7e00), _mm_set1_epi32(0x7c00)); + __m128i tinymask = _mm_cmpgt_epi32(_mm_set1_epi32(0x38800000), t); + __m128i tt = _mm_castps_si128(_mm_add_ps(_mm_castsi128_ps(t), _mm_castsi128_ps(rval))); + tt = _mm_sub_epi32(tt, rval); + __m128i odd = _mm_and_si128(_mm_srli_epi32(t, 13), _mm_set1_epi32(1)); + __m128i nt = _mm_add_epi32(t, _mm_set1_epi32(0xc8000fff)); + nt = _mm_srli_epi32(_mm_add_epi32(nt, odd), 13); + t = v_select_si128(tinymask, tt, nt); + t = v_select_si128(finitemask, t, naninf); + t = _mm_or_si128(t, sign); + t = _mm_packs_epi32(t, t); + _mm_storel_epi64((__m128i*)ptr, t); +#endif +} + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp index 654f9c7a34..6fb088161a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_sse_em.hpp @@ -1,180 +1,180 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_INTRIN_SSE_EM_HPP -#define OPENCV_HAL_INTRIN_SSE_EM_HPP - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#define OPENCV_HAL_SSE_WRAP_1(fun, tp) \ - inline tp _v128_##fun(const tp& a) \ - { return _mm_##fun(a); } - -#define OPENCV_HAL_SSE_WRAP_2(fun, tp) \ - inline tp _v128_##fun(const tp& a, const tp& b) \ - { return _mm_##fun(a, b); } - -#define OPENCV_HAL_SSE_WRAP_3(fun, tp) \ - inline tp _v128_##fun(const tp& a, const tp& b, const tp& c) \ - { return _mm_##fun(a, b, c); } - -///////////////////////////// XOP ///////////////////////////// - -// [todo] define CV_XOP -#if 1 // CV_XOP -inline __m128i _v128_comgt_epu32(const __m128i& a, const __m128i& b) -{ - const __m128i delta = _mm_set1_epi32((int)0x80000000); - return _mm_cmpgt_epi32(_mm_xor_si128(a, delta), _mm_xor_si128(b, delta)); -} -// wrapping XOP -#else -OPENCV_HAL_SSE_WRAP_2(_v128_comgt_epu32, __m128i) -#endif // !CV_XOP - -///////////////////////////// SSE4.1 ///////////////////////////// - -#if !CV_SSE4_1 - -/** Swizzle **/ -inline __m128i _v128_blendv_epi8(const __m128i& a, const __m128i& b, const __m128i& mask) -{ return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(b, a), mask)); } - -/** Convert **/ -// 8 >> 16 -inline __m128i _v128_cvtepu8_epi16(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi8(a, z); -} -inline __m128i _v128_cvtepi8_epi16(const __m128i& a) -{ return _mm_srai_epi16(_mm_unpacklo_epi8(a, a), 8); } -// 8 >> 32 -inline __m128i _v128_cvtepu8_epi32(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi16(_mm_unpacklo_epi8(a, z), z); -} -inline __m128i _v128_cvtepi8_epi32(const __m128i& a) -{ - __m128i r = _mm_unpacklo_epi8(a, a); - r = _mm_unpacklo_epi8(r, r); - return _mm_srai_epi32(r, 24); -} -// 16 >> 32 -inline __m128i _v128_cvtepu16_epi32(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi16(a, z); -} -inline __m128i _v128_cvtepi16_epi32(const __m128i& a) -{ return _mm_srai_epi32(_mm_unpacklo_epi16(a, a), 16); } -// 32 >> 64 -inline __m128i _v128_cvtepu32_epi64(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpacklo_epi32(a, z); -} -inline __m128i _v128_cvtepi32_epi64(const __m128i& a) -{ return _mm_unpacklo_epi32(a, _mm_srai_epi32(a, 31)); } - -/** Arithmetic **/ -inline __m128i _v128_mullo_epi32(const __m128i& a, const __m128i& b) -{ - __m128i c0 = _mm_mul_epu32(a, b); - __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a, 32), _mm_srli_epi64(b, 32)); - __m128i d0 = _mm_unpacklo_epi32(c0, c1); - __m128i d1 = _mm_unpackhi_epi32(c0, c1); - return _mm_unpacklo_epi64(d0, d1); -} - -/** Math **/ -inline __m128i _v128_min_epu32(const __m128i& a, const __m128i& b) -{ return _v128_blendv_epi8(a, b, _v128_comgt_epu32(a, b)); } - -// wrapping SSE4.1 -#else -OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi16, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi16, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepu16_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi16_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepu32_epi64, __m128i) -OPENCV_HAL_SSE_WRAP_1(cvtepi32_epi64, __m128i) -OPENCV_HAL_SSE_WRAP_2(min_epu32, __m128i) -OPENCV_HAL_SSE_WRAP_2(mullo_epi32, __m128i) -OPENCV_HAL_SSE_WRAP_3(blendv_epi8, __m128i) -#endif // !CV_SSE4_1 - -///////////////////////////// Revolutionary ///////////////////////////// - -/** Convert **/ -// 16 << 8 -inline __m128i _v128_cvtepu8_epi16_high(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpackhi_epi8(a, z); -} -inline __m128i _v128_cvtepi8_epi16_high(const __m128i& a) -{ return _mm_srai_epi16(_mm_unpackhi_epi8(a, a), 8); } -// 32 << 16 -inline __m128i _v128_cvtepu16_epi32_high(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpackhi_epi16(a, z); -} -inline __m128i _v128_cvtepi16_epi32_high(const __m128i& a) -{ return _mm_srai_epi32(_mm_unpackhi_epi16(a, a), 16); } -// 64 << 32 -inline __m128i _v128_cvtepu32_epi64_high(const __m128i& a) -{ - const __m128i z = _mm_setzero_si128(); - return _mm_unpackhi_epi32(a, z); -} -inline __m128i _v128_cvtepi32_epi64_high(const __m128i& a) -{ return _mm_unpackhi_epi32(a, _mm_srai_epi32(a, 31)); } - -/** Miscellaneous **/ -inline __m128i _v128_packs_epu32(const __m128i& a, const __m128i& b) -{ - const __m128i m = _mm_set1_epi32(65535); - __m128i am = _v128_min_epu32(a, m); - __m128i bm = _v128_min_epu32(b, m); -#if CV_SSE4_1 - return _mm_packus_epi32(am, bm); -#else - const __m128i d = _mm_set1_epi32(32768), nd = _mm_set1_epi16(-32768); - am = _mm_sub_epi32(am, d); - bm = _mm_sub_epi32(bm, d); - am = _mm_packs_epi32(am, bm); - return _mm_sub_epi16(am, nd); -#endif -} - -template -inline int64 _v128_extract_epi64(const __m128i& a) -{ -#if defined(CV__SIMD_HAVE_mm_extract_epi64) || (CV_SSE4_1 && (defined(__x86_64__)/*GCC*/ || defined(_M_X64)/*MSVC*/)) -#define CV__SIMD_NATIVE_mm_extract_epi64 1 - return _mm_extract_epi64(a, i); -#else - CV_DECL_ALIGNED(16) int64 tmp[2]; - _mm_store_si128((__m128i*)tmp, a); - return tmp[i]; -#endif -} - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} // cv:: - -#endif // OPENCV_HAL_INTRIN_SSE_EM_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_INTRIN_SSE_EM_HPP +#define OPENCV_HAL_INTRIN_SSE_EM_HPP + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#define OPENCV_HAL_SSE_WRAP_1(fun, tp) \ + inline tp _v128_##fun(const tp& a) \ + { return _mm_##fun(a); } + +#define OPENCV_HAL_SSE_WRAP_2(fun, tp) \ + inline tp _v128_##fun(const tp& a, const tp& b) \ + { return _mm_##fun(a, b); } + +#define OPENCV_HAL_SSE_WRAP_3(fun, tp) \ + inline tp _v128_##fun(const tp& a, const tp& b, const tp& c) \ + { return _mm_##fun(a, b, c); } + +///////////////////////////// XOP ///////////////////////////// + +// [todo] define CV_XOP +#if 1 // CV_XOP +inline __m128i _v128_comgt_epu32(const __m128i& a, const __m128i& b) +{ + const __m128i delta = _mm_set1_epi32((int)0x80000000); + return _mm_cmpgt_epi32(_mm_xor_si128(a, delta), _mm_xor_si128(b, delta)); +} +// wrapping XOP +#else +OPENCV_HAL_SSE_WRAP_2(_v128_comgt_epu32, __m128i) +#endif // !CV_XOP + +///////////////////////////// SSE4.1 ///////////////////////////// + +#if !CV_SSE4_1 + +/** Swizzle **/ +inline __m128i _v128_blendv_epi8(const __m128i& a, const __m128i& b, const __m128i& mask) +{ return _mm_xor_si128(a, _mm_and_si128(_mm_xor_si128(b, a), mask)); } + +/** Convert **/ +// 8 >> 16 +inline __m128i _v128_cvtepu8_epi16(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi8(a, z); +} +inline __m128i _v128_cvtepi8_epi16(const __m128i& a) +{ return _mm_srai_epi16(_mm_unpacklo_epi8(a, a), 8); } +// 8 >> 32 +inline __m128i _v128_cvtepu8_epi32(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi16(_mm_unpacklo_epi8(a, z), z); +} +inline __m128i _v128_cvtepi8_epi32(const __m128i& a) +{ + __m128i r = _mm_unpacklo_epi8(a, a); + r = _mm_unpacklo_epi8(r, r); + return _mm_srai_epi32(r, 24); +} +// 16 >> 32 +inline __m128i _v128_cvtepu16_epi32(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi16(a, z); +} +inline __m128i _v128_cvtepi16_epi32(const __m128i& a) +{ return _mm_srai_epi32(_mm_unpacklo_epi16(a, a), 16); } +// 32 >> 64 +inline __m128i _v128_cvtepu32_epi64(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpacklo_epi32(a, z); +} +inline __m128i _v128_cvtepi32_epi64(const __m128i& a) +{ return _mm_unpacklo_epi32(a, _mm_srai_epi32(a, 31)); } + +/** Arithmetic **/ +inline __m128i _v128_mullo_epi32(const __m128i& a, const __m128i& b) +{ + __m128i c0 = _mm_mul_epu32(a, b); + __m128i c1 = _mm_mul_epu32(_mm_srli_epi64(a, 32), _mm_srli_epi64(b, 32)); + __m128i d0 = _mm_unpacklo_epi32(c0, c1); + __m128i d1 = _mm_unpackhi_epi32(c0, c1); + return _mm_unpacklo_epi64(d0, d1); +} + +/** Math **/ +inline __m128i _v128_min_epu32(const __m128i& a, const __m128i& b) +{ return _v128_blendv_epi8(a, b, _v128_comgt_epu32(a, b)); } + +// wrapping SSE4.1 +#else +OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi16, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi16, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepu8_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi8_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepu16_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi16_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepu32_epi64, __m128i) +OPENCV_HAL_SSE_WRAP_1(cvtepi32_epi64, __m128i) +OPENCV_HAL_SSE_WRAP_2(min_epu32, __m128i) +OPENCV_HAL_SSE_WRAP_2(mullo_epi32, __m128i) +OPENCV_HAL_SSE_WRAP_3(blendv_epi8, __m128i) +#endif // !CV_SSE4_1 + +///////////////////////////// Revolutionary ///////////////////////////// + +/** Convert **/ +// 16 << 8 +inline __m128i _v128_cvtepu8_epi16_high(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpackhi_epi8(a, z); +} +inline __m128i _v128_cvtepi8_epi16_high(const __m128i& a) +{ return _mm_srai_epi16(_mm_unpackhi_epi8(a, a), 8); } +// 32 << 16 +inline __m128i _v128_cvtepu16_epi32_high(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpackhi_epi16(a, z); +} +inline __m128i _v128_cvtepi16_epi32_high(const __m128i& a) +{ return _mm_srai_epi32(_mm_unpackhi_epi16(a, a), 16); } +// 64 << 32 +inline __m128i _v128_cvtepu32_epi64_high(const __m128i& a) +{ + const __m128i z = _mm_setzero_si128(); + return _mm_unpackhi_epi32(a, z); +} +inline __m128i _v128_cvtepi32_epi64_high(const __m128i& a) +{ return _mm_unpackhi_epi32(a, _mm_srai_epi32(a, 31)); } + +/** Miscellaneous **/ +inline __m128i _v128_packs_epu32(const __m128i& a, const __m128i& b) +{ + const __m128i m = _mm_set1_epi32(65535); + __m128i am = _v128_min_epu32(a, m); + __m128i bm = _v128_min_epu32(b, m); +#if CV_SSE4_1 + return _mm_packus_epi32(am, bm); +#else + const __m128i d = _mm_set1_epi32(32768), nd = _mm_set1_epi16(-32768); + am = _mm_sub_epi32(am, d); + bm = _mm_sub_epi32(bm, d); + am = _mm_packs_epi32(am, bm); + return _mm_sub_epi16(am, nd); +#endif +} + +template +inline int64 _v128_extract_epi64(const __m128i& a) +{ +#if defined(CV__SIMD_HAVE_mm_extract_epi64) || (CV_SSE4_1 && (defined(__x86_64__)/*GCC*/ || defined(_M_X64)/*MSVC*/)) +#define CV__SIMD_NATIVE_mm_extract_epi64 1 + return _mm_extract_epi64(a, i); +#else + CV_DECL_ALIGNED(16) int64 tmp[2]; + _mm_store_si128((__m128i*)tmp, a); + return tmp[i]; +#endif +} + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} // cv:: + +#endif // OPENCV_HAL_INTRIN_SSE_EM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp index b0e2a3472b..2157e1e870 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_vsx.hpp @@ -1,1619 +1,1619 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_VSX_HPP -#define OPENCV_HAL_VSX_HPP - -#include -#include "opencv2/core/utility.hpp" - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 1 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -///////// Types //////////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - enum { nlanes = 16 }; - vec_uchar16 val; - - explicit v_uint8x16(const vec_uchar16& v) : val(v) - {} - v_uint8x16() - {} - v_uint8x16(vec_bchar16 v) : val(vec_uchar16_c(v)) - {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - : val(vec_uchar16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) - {} - - static inline v_uint8x16 zero() { return v_uint8x16(vec_uchar16_z); } - - uchar get0() const - { return vec_extract(val, 0); } -}; - -struct v_int8x16 -{ - typedef schar lane_type; - enum { nlanes = 16 }; - vec_char16 val; - - explicit v_int8x16(const vec_char16& v) : val(v) - {} - v_int8x16() - {} - v_int8x16(vec_bchar16 v) : val(vec_char16_c(v)) - {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - : val(vec_char16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) - {} - - static inline v_int8x16 zero() { return v_int8x16(vec_char16_z); } - - schar get0() const - { return vec_extract(val, 0); } -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - enum { nlanes = 8 }; - vec_ushort8 val; - - explicit v_uint16x8(const vec_ushort8& v) : val(v) - {} - v_uint16x8() - {} - v_uint16x8(vec_bshort8 v) : val(vec_ushort8_c(v)) - {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - : val(vec_ushort8_set(v0, v1, v2, v3, v4, v5, v6, v7)) - {} - - static inline v_uint16x8 zero() { return v_uint16x8(vec_ushort8_z); } - - ushort get0() const - { return vec_extract(val, 0); } -}; - -struct v_int16x8 -{ - typedef short lane_type; - enum { nlanes = 8 }; - vec_short8 val; - - explicit v_int16x8(const vec_short8& v) : val(v) - {} - v_int16x8() - {} - v_int16x8(vec_bshort8 v) : val(vec_short8_c(v)) - {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - : val(vec_short8_set(v0, v1, v2, v3, v4, v5, v6, v7)) - {} - - static inline v_int16x8 zero() { return v_int16x8(vec_short8_z); } - - short get0() const - { return vec_extract(val, 0); } -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - enum { nlanes = 4 }; - vec_uint4 val; - - explicit v_uint32x4(const vec_uint4& v) : val(v) - {} - v_uint32x4() - {} - v_uint32x4(vec_bint4 v) : val(vec_uint4_c(v)) - {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) : val(vec_uint4_set(v0, v1, v2, v3)) - {} - - static inline v_uint32x4 zero() { return v_uint32x4(vec_uint4_z); } - - uint get0() const - { return vec_extract(val, 0); } -}; - -struct v_int32x4 -{ - typedef int lane_type; - enum { nlanes = 4 }; - vec_int4 val; - - explicit v_int32x4(const vec_int4& v) : val(v) - {} - v_int32x4() - {} - v_int32x4(vec_bint4 v) : val(vec_int4_c(v)) - {} - v_int32x4(int v0, int v1, int v2, int v3) : val(vec_int4_set(v0, v1, v2, v3)) - {} - - static inline v_int32x4 zero() { return v_int32x4(vec_int4_z); } - - int get0() const - { return vec_extract(val, 0); } -}; - -struct v_float32x4 -{ - typedef float lane_type; - enum { nlanes = 4 }; - vec_float4 val; - - explicit v_float32x4(const vec_float4& v) : val(v) - {} - v_float32x4() - {} - v_float32x4(vec_bint4 v) : val(vec_float4_c(v)) - {} - v_float32x4(float v0, float v1, float v2, float v3) : val(vec_float4_set(v0, v1, v2, v3)) - {} - - static inline v_float32x4 zero() { return v_float32x4(vec_float4_z); } - - float get0() const - { return vec_extract(val, 0); } -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - enum { nlanes = 2 }; - vec_udword2 val; - - explicit v_uint64x2(const vec_udword2& v) : val(v) - {} - v_uint64x2() - {} - v_uint64x2(vec_bdword2 v) : val(vec_udword2_c(v)) - {} - v_uint64x2(uint64 v0, uint64 v1) : val(vec_udword2_set(v0, v1)) - {} - - static inline v_uint64x2 zero() { return v_uint64x2(vec_udword2_z); } - - uint64 get0() const - { return vec_extract(val, 0); } -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - enum { nlanes = 2 }; - vec_dword2 val; - - explicit v_int64x2(const vec_dword2& v) : val(v) - {} - v_int64x2() - {} - v_int64x2(vec_bdword2 v) : val(vec_dword2_c(v)) - {} - v_int64x2(int64 v0, int64 v1) : val(vec_dword2_set(v0, v1)) - {} - - static inline v_int64x2 zero() { return v_int64x2(vec_dword2_z); } - - int64 get0() const - { return vec_extract(val, 0); } -}; - -struct v_float64x2 -{ - typedef double lane_type; - enum { nlanes = 2 }; - vec_double2 val; - - explicit v_float64x2(const vec_double2& v) : val(v) - {} - v_float64x2() - {} - v_float64x2(vec_bdword2 v) : val(vec_double2_c(v)) - {} - v_float64x2(double v0, double v1) : val(vec_double2_set(v0, v1)) - {} - - static inline v_float64x2 zero() { return v_float64x2(vec_double2_z); } - - double get0() const - { return vec_extract(val, 0); } -}; - -#define OPENCV_HAL_IMPL_VSX_EXTRACT_N(_Tpvec, _Tp) \ -template inline _Tp v_extract_n(VSX_UNUSED(_Tpvec v)) { return vec_extract(v.val, i); } - -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint8x16, uchar) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int8x16, schar) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint16x8, ushort) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int16x8, short) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint32x4, uint) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int32x4, int) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint64x2, uint64) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int64x2, int64) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float32x4, float) -OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float64x2, double) - -//////////////// Load and store operations /////////////// - -/* - * clang-5 aborted during parse "vec_xxx_c" only if it's - * inside a function template which is defined by preprocessor macro. - * - * if vec_xxx_c defined as C++ cast, clang-5 will pass it -*/ -#define OPENCV_HAL_IMPL_VSX_INITVEC(_Tpvec, _Tp, suffix, cast) \ -inline _Tpvec v_setzero_##suffix() { return _Tpvec(vec_splats((_Tp)0)); } \ -inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(vec_splats((_Tp)v));} \ -template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(_Tp v); } \ -template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0 &a) \ -{ return _Tpvec((cast)a.val); } - -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint8x16, uchar, u8, vec_uchar16) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int8x16, schar, s8, vec_char16) -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint16x8, ushort, u16, vec_ushort8) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int16x8, short, s16, vec_short8) -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint32x4, uint, u32, vec_uint4) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int32x4, int, s32, vec_int4) -OPENCV_HAL_IMPL_VSX_INITVEC(v_uint64x2, uint64, u64, vec_udword2) -OPENCV_HAL_IMPL_VSX_INITVEC(v_int64x2, int64, s64, vec_dword2) -OPENCV_HAL_IMPL_VSX_INITVEC(v_float32x4, float, f32, vec_float4) -OPENCV_HAL_IMPL_VSX_INITVEC(v_float64x2, double, f64, vec_double2) - -#define OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, ld, ld_a, st, st_a) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(ld(0, ptr)); } \ -inline _Tpvec v_load_aligned(VSX_UNUSED(const _Tp* ptr)) \ -{ return _Tpvec(ld_a(0, ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ return _Tpvec(vec_ld_l8(ptr)); } \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ return _Tpvec(vec_mergesqh(vec_ld_l8(ptr0), vec_ld_l8(ptr1))); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ st(a.val, 0, ptr); } \ -inline void v_store_aligned(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ -{ st_a(a.val, 0, ptr); } \ -inline void v_store_aligned_nocache(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ -{ st_a(a.val, 0, ptr); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ -{ if(mode == hal::STORE_UNALIGNED) st(a.val, 0, ptr); else st_a(a.val, 0, ptr); } \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ vec_st_l8(a.val, ptr); } \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ vec_st_h8(a.val, ptr); } - -// working around gcc bug for aligned ld/st -// if runtime check for vec_ld/st fail we failback to unaligned ld/st -// https://github.com/opencv/opencv/issues/13211 -#ifdef CV_COMPILER_VSX_BROKEN_ALIGNED - #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ - OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vsx_ld, vsx_st, vsx_st) -#else - #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ - OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vec_ld, vsx_st, vec_st) -#endif - -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint8x16, uchar) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int8x16, schar) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint16x8, ushort) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int16x8, short) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint32x4, uint) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int32x4, int) -OPENCV_HAL_IMPL_VSX_LOADSTORE(v_float32x4, float) - -OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_float64x2, double, vsx_ld, vsx_ld, vsx_st, vsx_st) -OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_uint64x2, uint64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) -OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_int64x2, int64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) - -//////////////// Value reordering /////////////// - -/* de&interleave */ -#define OPENCV_HAL_IMPL_VSX_INTERLEAVE(_Tp, _Tpvec) \ -inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b) \ -{ vec_ld_deinterleave(ptr, a.val, b.val);} \ -inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, \ - _Tpvec& b, _Tpvec& c) \ -{ vec_ld_deinterleave(ptr, a.val, b.val, c.val); } \ -inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b, \ - _Tpvec& c, _Tpvec& d) \ -{ vec_ld_deinterleave(ptr, a.val, b.val, c.val, d.val); } \ -inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vec_st_interleave(a.val, b.val, ptr); } \ -inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, \ - const _Tpvec& b, const _Tpvec& c, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vec_st_interleave(a.val, b.val, c.val, ptr); } \ -inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ - const _Tpvec& c, const _Tpvec& d, \ - hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ -{ vec_st_interleave(a.val, b.val, c.val, d.val, ptr); } - -OPENCV_HAL_IMPL_VSX_INTERLEAVE(uchar, v_uint8x16) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(schar, v_int8x16) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(ushort, v_uint16x8) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(short, v_int16x8) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint, v_uint32x4) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(int, v_int32x4) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(float, v_float32x4) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(double, v_float64x2) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(int64, v_int64x2) -OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint64, v_uint64x2) - -/* Expand */ -#define OPENCV_HAL_IMPL_VSX_EXPAND(_Tpvec, _Tpwvec, _Tp, fl, fh) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = fh(a.val); \ - b1.val = fl(a.val); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ return _Tpwvec(fh(a.val)); } \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ return _Tpwvec(fl(a.val)); } \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ return _Tpwvec(fh(vec_ld_l8(ptr))); } - -OPENCV_HAL_IMPL_VSX_EXPAND(v_uint8x16, v_uint16x8, uchar, vec_unpacklu, vec_unpackhu) -OPENCV_HAL_IMPL_VSX_EXPAND(v_int8x16, v_int16x8, schar, vec_unpackl, vec_unpackh) -OPENCV_HAL_IMPL_VSX_EXPAND(v_uint16x8, v_uint32x4, ushort, vec_unpacklu, vec_unpackhu) -OPENCV_HAL_IMPL_VSX_EXPAND(v_int16x8, v_int32x4, short, vec_unpackl, vec_unpackh) -OPENCV_HAL_IMPL_VSX_EXPAND(v_uint32x4, v_uint64x2, uint, vec_unpacklu, vec_unpackhu) -OPENCV_HAL_IMPL_VSX_EXPAND(v_int32x4, v_int64x2, int, vec_unpackl, vec_unpackh) - -/* Load and zero expand a 4 byte value into the second dword, first is don't care. */ -#if !defined(CV_COMPILER_VSX_BROKEN_ASM) - #define _LXSIWZX(out, ptr, T) __asm__ ("lxsiwzx %x0, 0, %1\r\n" : "=wa"(out) : "r" (ptr) : "memory"); -#else - /* This is compiler-agnostic, but will introduce an unneeded splat on the critical path. */ - #define _LXSIWZX(out, ptr, T) out = (T)vec_udword2_sp(*(uint32_t*)(ptr)); -#endif - -inline v_uint32x4 v_load_expand_q(const uchar* ptr) -{ - // Zero-extend the extra 24B instead of unpacking. Usually faster in small kernel - // Likewise note, value is zero extended and upper 4 bytes are zero'ed. - vec_uchar16 pmu = {8, 12, 12, 12, 9, 12, 12, 12, 10, 12, 12, 12, 11, 12, 12, 12}; - vec_uchar16 out; - - _LXSIWZX(out, ptr, vec_uchar16); - out = vec_perm(out, out, pmu); - return v_uint32x4((vec_uint4)out); -} - -inline v_int32x4 v_load_expand_q(const schar* ptr) -{ - vec_char16 out; - vec_short8 outs; - vec_int4 outw; - - _LXSIWZX(out, ptr, vec_char16); - outs = vec_unpackl(out); - outw = vec_unpackh(outs); - return v_int32x4(outw); -} - -/* pack */ -#define OPENCV_HAL_IMPL_VSX_PACK(_Tpvec, _Tp, _Tpwvec, _Tpvn, _Tpdel, sfnc, pkfnc, addfnc, pack) \ -inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - return _Tpvec(pkfnc(a.val, b.val)); \ -} \ -inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - vec_st_l8(pkfnc(a.val, a.val), ptr); \ -} \ -template \ -inline _Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ -{ \ - const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ - const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ - return _Tpvec(pkfnc(sfnc(addfnc(a.val, delta), vn), sfnc(addfnc(b.val, delta), vn))); \ -} \ -template \ -inline void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ -{ \ - const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ - const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ - vec_st_l8(pkfnc(sfnc(addfnc(a.val, delta), vn), delta), ptr); \ -} - -OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_uint16x8, unsigned short, unsigned short, - vec_sr, vec_packs, vec_adds, pack) -OPENCV_HAL_IMPL_VSX_PACK(v_int8x16, schar, v_int16x8, unsigned short, short, - vec_sra, vec_packs, vec_adds, pack) - -OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_uint32x4, unsigned int, unsigned int, - vec_sr, vec_packs, vec_add, pack) -OPENCV_HAL_IMPL_VSX_PACK(v_int16x8, short, v_int32x4, unsigned int, int, - vec_sra, vec_packs, vec_add, pack) - -OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_uint64x2, unsigned long long, unsigned long long, - vec_sr, vec_pack, vec_add, pack) -OPENCV_HAL_IMPL_VSX_PACK(v_int32x4, int, v_int64x2, unsigned long long, long long, - vec_sra, vec_pack, vec_add, pack) - -OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_int16x8, unsigned short, short, - vec_sra, vec_packsu, vec_adds, pack_u) -OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_int32x4, unsigned int, int, - vec_sra, vec_packsu, vec_add, pack_u) -// Following variant is not implemented on other platforms: -//OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_int64x2, unsigned long long, long long, -// vec_sra, vec_packsu, vec_add, pack_u) - -// pack boolean -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - vec_uchar16 ab = vec_pack(a.val, b.val); - return v_uint8x16(ab); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - vec_ushort8 ab = vec_pack(a.val, b.val); - vec_ushort8 cd = vec_pack(c.val, d.val); - return v_uint8x16(vec_pack(ab, cd)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - vec_uint4 ab = vec_pack(a.val, b.val); - vec_uint4 cd = vec_pack(c.val, d.val); - vec_uint4 ef = vec_pack(e.val, f.val); - vec_uint4 gh = vec_pack(g.val, h.val); - - vec_ushort8 abcd = vec_pack(ab, cd); - vec_ushort8 efgh = vec_pack(ef, gh); - return v_uint8x16(vec_pack(abcd, efgh)); -} - -/* Recombine */ -template -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) -{ - b0.val = vec_mergeh(a0.val, a1.val); - b1.val = vec_mergel(a0.val, a1.val); -} - -template -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(vec_mergesql(a.val, b.val)); } - -template -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) -{ return _Tpvec(vec_mergesqh(a.val, b.val)); } - -template -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) -{ - c.val = vec_mergesqh(a.val, b.val); - d.val = vec_mergesql(a.val, b.val); -} - -////////// Arithmetic, bitwise and comparison operations ///////// - -/* Element-wise binary and unary operations */ -/** Arithmetics **/ -#define OPENCV_HAL_IMPL_VSX_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint8x16, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint8x16, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int8x16, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int8x16, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint16x8, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint16x8, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int16x8, vec_adds) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int16x8, vec_subs) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint32x4, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint32x4, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_uint32x4, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int32x4, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int32x4, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_int32x4, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float32x4, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float32x4, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float32x4, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float32x4, vec_div) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float64x2, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float64x2, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float64x2, vec_mul) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float64x2, vec_div) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint64x2, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint64x2, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int64x2, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int64x2, vec_sub) - -// saturating multiply -#define OPENCV_HAL_IMPL_VSX_MUL_SAT(_Tpvec, _Tpwvec) \ - inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ - { \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ - } - -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int16x8, v_int32x4) -OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint16x8, v_uint32x4) - -template -inline void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d) -{ - Twvec p0 = Twvec(vec_mule(a.val, b.val)); - Twvec p1 = Twvec(vec_mulo(a.val, b.val)); - v_zip(p0, p1, c, d); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - vec_int4 p0 = vec_mule(a.val, b.val); - vec_int4 p1 = vec_mulo(a.val, b.val); - static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; - return v_int16x8(vec_perm(vec_short8_c(p0), vec_short8_c(p1), perm)); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - vec_uint4 p0 = vec_mule(a.val, b.val); - vec_uint4 p1 = vec_mulo(a.val, b.val); - static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; - return v_uint16x8(vec_perm(vec_ushort8_c(p0), vec_ushort8_c(p1), perm)); -} - -/** Non-saturating arithmetics **/ -#define OPENCV_HAL_IMPL_VSX_BIN_FUNC(func, intrin) \ -template \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(intrin(a.val, b.val)); } - -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_add_wrap, vec_add) -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_sub_wrap, vec_sub) -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_mul_wrap, vec_mul) - -/** Bitwise shifts **/ -#define OPENCV_HAL_IMPL_VSX_SHIFT_OP(_Tpvec, shr, splfunc) \ -inline _Tpvec v_shl(const _Tpvec& a, int imm) \ -{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ -inline _Tpvec v_shr(const _Tpvec& a, int imm) \ -{ return _Tpvec(shr(a.val, splfunc(imm))); } \ -template inline _Tpvec v_shl(const _Tpvec& a) \ -{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ -template inline _Tpvec v_shr(const _Tpvec& a) \ -{ return _Tpvec(shr(a.val, splfunc(imm))); } - -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint8x16, vec_sr, vec_uchar16_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint16x8, vec_sr, vec_ushort8_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint32x4, vec_sr, vec_uint4_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint64x2, vec_sr, vec_udword2_sp) -// algebraic right shift -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int8x16, vec_sra, vec_uchar16_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int16x8, vec_sra, vec_ushort8_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int32x4, vec_sra, vec_uint4_sp) -OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int64x2, vec_sra, vec_udword2_sp) - -/** Bitwise logic **/ -#define OPENCV_HAL_IMPL_VSX_LOGIC_OP(_Tpvec) \ -OPENCV_HAL_IMPL_VSX_BIN_OP(v_and, _Tpvec, vec_and) \ -OPENCV_HAL_IMPL_VSX_BIN_OP(v_or, _Tpvec, vec_or) \ -OPENCV_HAL_IMPL_VSX_BIN_OP(v_xor, _Tpvec, vec_xor) \ -inline _Tpvec v_not(const _Tpvec& a) \ -{ return _Tpvec(vec_not(a.val)); } - -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint8x16) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int8x16) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint16x8) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int16x8) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint32x4) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int32x4) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint64x2) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int64x2) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float32x4) -OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float64x2) - -/** Bitwise select **/ -#define OPENCV_HAL_IMPL_VSX_SELECT(_Tpvec, cast) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_sel(b.val, a.val, cast(mask.val))); } - -OPENCV_HAL_IMPL_VSX_SELECT(v_uint8x16, vec_bchar16_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_int8x16, vec_bchar16_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_uint16x8, vec_bshort8_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_int16x8, vec_bshort8_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_uint32x4, vec_bint4_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_int32x4, vec_bint4_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_float32x4, vec_bint4_c) -OPENCV_HAL_IMPL_VSX_SELECT(v_float64x2, vec_bdword2_c) - -/** Comparison **/ -#define OPENCV_HAL_IMPL_VSX_INT_CMP_OP(_Tpvec) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpeq(a.val, b.val)); } \ -inline _Tpvec V_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpne(a.val, b.val)); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmplt(a.val, b.val)); } \ -inline _Tpvec V_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpgt(a.val, b.val)); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmple(a.val, b.val)); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_cmpge(a.val, b.val)); } - -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint8x16) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int8x16) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint16x8) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int16x8) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint32x4) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int32x4) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float32x4) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float64x2) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint64x2) -OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int64x2) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ return v_float32x4(vec_cmpeq(a.val, a.val)); } -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ return v_float64x2(vec_cmpeq(a.val, a.val)); } - -/** min/max **/ -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_min, vec_min) -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_max, vec_max) - -/** Rotate **/ -#define OPENCV_IMPL_VSX_ROTATE(_Tpvec, suffix, shf, cast) \ -template \ -inline _Tpvec v_rotate_##suffix(const _Tpvec& a) \ -{ \ - const int wd = imm * sizeof(typename _Tpvec::lane_type); \ - if (wd > 15) \ - return _Tpvec::zero(); \ - return _Tpvec((cast)shf(vec_uchar16_c(a.val), vec_uchar16_sp(wd << 3))); \ -} - -#define OPENCV_IMPL_VSX_ROTATE_LR(_Tpvec, cast) \ -OPENCV_IMPL_VSX_ROTATE(_Tpvec, left, vec_slo, cast) \ -OPENCV_IMPL_VSX_ROTATE(_Tpvec, right, vec_sro, cast) - -OPENCV_IMPL_VSX_ROTATE_LR(v_uint8x16, vec_uchar16) -OPENCV_IMPL_VSX_ROTATE_LR(v_int8x16, vec_char16) -OPENCV_IMPL_VSX_ROTATE_LR(v_uint16x8, vec_ushort8) -OPENCV_IMPL_VSX_ROTATE_LR(v_int16x8, vec_short8) -OPENCV_IMPL_VSX_ROTATE_LR(v_uint32x4, vec_uint4) -OPENCV_IMPL_VSX_ROTATE_LR(v_int32x4, vec_int4) -OPENCV_IMPL_VSX_ROTATE_LR(v_float32x4, vec_float4) -OPENCV_IMPL_VSX_ROTATE_LR(v_uint64x2, vec_udword2) -OPENCV_IMPL_VSX_ROTATE_LR(v_int64x2, vec_dword2) -OPENCV_IMPL_VSX_ROTATE_LR(v_float64x2, vec_double2) - -template -inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) -{ - enum { CV_SHIFT = 16 - imm * (sizeof(typename _Tpvec::lane_type)) }; - if (CV_SHIFT == 16) - return a; -#ifdef __IBMCPP__ - return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT & 15)); -#else - return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT)); -#endif -} - -template -inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) -{ - enum { CV_SHIFT = imm * (sizeof(typename _Tpvec::lane_type)) }; - if (CV_SHIFT == 16) - return b; - return _Tpvec(vec_sld(a.val, b.val, CV_SHIFT)); -} - -#define OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, suffix, rg1, rg2) \ -template \ -inline _Tpvec v_rotate_##suffix(const _Tpvec& a, const _Tpvec& b) \ -{ \ - if (imm == 1) \ - return _Tpvec(vec_permi(rg1.val, rg2.val, 2)); \ - return imm ? b : a; \ -} - -#define OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(_Tpvec) \ -OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, left, b, a) \ -OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, right, a, b) - -OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_float64x2) -OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_uint64x2) -OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_int64x2) - -/* Reverse */ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ - static const vec_uchar16 perm = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_uint8x16(vec_perm(vec, vec, perm)); -} - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ - static const vec_uchar16 perm = {14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_reinterpret_as_u16(v_uint8x16(vec_perm(vec, vec, perm))); -} - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ - static const vec_uchar16 perm = {12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_reinterpret_as_u32(v_uint8x16(vec_perm(vec, vec, perm))); -} - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ - static const vec_uchar16 perm = {8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7}; - vec_uchar16 vec = (vec_uchar16)a.val; - return v_reinterpret_as_u64(v_uint8x16(vec_perm(vec, vec, perm))); -} - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - -/* Extract */ -template -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) -{ return v_rotate_right(a, b); } - -////////// Reduce and mask ///////// - -/** Reduce **/ -inline uint v_reduce_sum(const v_uint8x16& a) -{ - const vec_uint4 zero4 = vec_uint4_z; - vec_uint4 sum4 = vec_sum4s(a.val, zero4); - return (uint)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); -} -inline int v_reduce_sum(const v_int8x16& a) -{ - const vec_int4 zero4 = vec_int4_z; - vec_int4 sum4 = vec_sum4s(a.val, zero4); - return (int)vec_extract(vec_sums(sum4, zero4), 3); -} -inline int v_reduce_sum(const v_int16x8& a) -{ - const vec_int4 zero = vec_int4_z; - return saturate_cast(vec_extract(vec_sums(vec_sum4s(a.val, zero), zero), 3)); -} -inline uint v_reduce_sum(const v_uint16x8& a) -{ - const vec_int4 v4 = vec_int4_c(vec_unpackhu(vec_adds(a.val, vec_sld(a.val, a.val, 8)))); - return saturate_cast(vec_extract(vec_sums(v4, vec_int4_z), 3)); -} - -#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(_Tpvec, _Tpvec2, scalartype, suffix, func) \ -inline scalartype v_reduce_##suffix(const _Tpvec& a) \ -{ \ - const _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ - return vec_extract(func(rs, vec_sld(rs, rs, 4)), 0); \ -} -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, sum, vec_add) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, sum, vec_add) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, sum, vec_add) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, min, vec_min) - -inline uint64 v_reduce_sum(const v_uint64x2& a) -{ - return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); -} -inline int64 v_reduce_sum(const v_int64x2& a) -{ - return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); -} -inline double v_reduce_sum(const v_float64x2& a) -{ - return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); -} - -#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(_Tpvec, _Tpvec2, scalartype, suffix, func) \ -inline scalartype v_reduce_##suffix(const _Tpvec& a) \ -{ \ - _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ - rs = func(rs, vec_sld(rs, rs, 4)); \ - return vec_extract(func(rs, vec_sld(rs, rs, 2)), 0); \ -} -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, min, vec_min) - -#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(_Tpvec, _Tpvec2, scalartype, suffix, func) \ -inline scalartype v_reduce_##suffix(const _Tpvec& a) \ -{ \ - _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ - rs = func(rs, vec_sld(rs, rs, 4)); \ - rs = func(rs, vec_sld(rs, rs, 2)); \ - return vec_extract(func(rs, vec_sld(rs, rs, 1)), 0); \ -} -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, min, vec_min) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, max, vec_max) -OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, min, vec_min) - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - vec_float4 ac = vec_add(vec_mergel(a.val, c.val), vec_mergeh(a.val, c.val)); - ac = vec_add(ac, vec_sld(ac, ac, 8)); - - vec_float4 bd = vec_add(vec_mergel(b.val, d.val), vec_mergeh(b.val, d.val)); - bd = vec_add(bd, vec_sld(bd, bd, 8)); - return v_float32x4(vec_mergeh(ac, bd)); -} - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - const vec_uint4 zero4 = vec_uint4_z; - vec_uint4 sum4 = vec_sum4s(vec_absd(a.val, b.val), zero4); - return (unsigned)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - const vec_int4 zero4 = vec_int4_z; - vec_char16 ad = vec_abss(vec_subs(a.val, b.val)); - vec_int4 sum4 = vec_sum4s(ad, zero4); - return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - vec_ushort8 ad = vec_absd(a.val, b.val); - VSX_UNUSED(vec_int4) sum = vec_sums(vec_int4_c(vec_unpackhu(ad)) + vec_int4_c(vec_unpacklu(ad)), vec_int4_z); - return (unsigned)vec_extract(sum, 3); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - const vec_int4 zero4 = vec_int4_z; - vec_short8 ad = vec_abss(vec_subs(a.val, b.val)); - vec_int4 sum4 = vec_sum4s(ad, zero4); - return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - const vec_uint4 ad = vec_absd(a.val, b.val); - const vec_uint4 rd = vec_add(ad, vec_sld(ad, ad, 8)); - return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - vec_int4 ad = vec_abss(vec_sub(a.val, b.val)); - return (unsigned)vec_extract(vec_sums(ad, vec_int4_z), 3); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - const vec_float4 ad = vec_abs(vec_sub(a.val, b.val)); - const vec_float4 rd = vec_add(ad, vec_sld(ad, ad, 8)); - return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); -} - -/** Popcount **/ -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ return v_uint8x16(vec_popcntu(a.val)); } -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_uint8x16(vec_popcntu(a.val)); } -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ return v_uint16x8(vec_popcntu(a.val)); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_uint16x8(vec_popcntu(a.val)); } -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ return v_uint32x4(vec_popcntu(a.val)); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_uint32x4(vec_popcntu(a.val)); } -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ return v_uint64x2(vec_popcntu(a.val)); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_uint64x2(vec_popcntu(a.val)); } - -/** Mask **/ -inline int v_signmask(const v_uint8x16& a) -{ - static const vec_uchar16 qperm = {120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0}; - return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); -} -inline int v_signmask(const v_int8x16& a) -{ return v_signmask(v_reinterpret_as_u8(a)); } - -inline int v_signmask(const v_int16x8& a) -{ - static const vec_uchar16 qperm = {112, 96, 80, 64, 48, 32, 16, 0, 128, 128, 128, 128, 128, 128, 128, 128}; - return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); -} -inline int v_signmask(const v_uint16x8& a) -{ return v_signmask(v_reinterpret_as_s16(a)); } - -inline int v_signmask(const v_int32x4& a) -{ - static const vec_uchar16 qperm = {96, 64, 32, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}; - return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); -} -inline int v_signmask(const v_uint32x4& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } -inline int v_signmask(const v_float32x4& a) -{ return v_signmask(v_reinterpret_as_s32(a)); } - -inline int v_signmask(const v_int64x2& a) -{ - VSX_UNUSED(const vec_dword2) sv = vec_sr(a.val, vec_udword2_sp(63)); - return (int)vec_extract(sv, 0) | (int)vec_extract(sv, 1) << 1; -} -inline int v_signmask(const v_uint64x2& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } -inline int v_signmask(const v_float64x2& a) -{ return v_signmask(v_reinterpret_as_s64(a)); } - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } - -template -inline bool v_check_all(const _Tpvec& a) -{ return vec_all_lt(a.val, _Tpvec::zero().val); } -inline bool v_check_all(const v_uint8x16& a) -{ return v_check_all(v_reinterpret_as_s8(a)); } -inline bool v_check_all(const v_uint16x8& a) -{ return v_check_all(v_reinterpret_as_s16(a)); } -inline bool v_check_all(const v_uint32x4& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_uint64x2& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } -inline bool v_check_all(const v_float32x4& a) -{ return v_check_all(v_reinterpret_as_s32(a)); } -inline bool v_check_all(const v_float64x2& a) -{ return v_check_all(v_reinterpret_as_s64(a)); } - -template -inline bool v_check_any(const _Tpvec& a) -{ return vec_any_lt(a.val, _Tpvec::zero().val); } -inline bool v_check_any(const v_uint8x16& a) -{ return v_check_any(v_reinterpret_as_s8(a)); } -inline bool v_check_any(const v_uint16x8& a) -{ return v_check_any(v_reinterpret_as_s16(a)); } -inline bool v_check_any(const v_uint32x4& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_uint64x2& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } -inline bool v_check_any(const v_float32x4& a) -{ return v_check_any(v_reinterpret_as_s32(a)); } -inline bool v_check_any(const v_float64x2& a) -{ return v_check_any(v_reinterpret_as_s64(a)); } - -////////// Other math ///////// - -/** Some frequent operations **/ -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ return v_float32x4(vec_sqrt(x.val)); } -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ return v_float64x2(vec_sqrt(x.val)); } - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ return v_float32x4(vec_rsqrt(x.val)); } -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ return v_float64x2(vec_rsqrt(x.val)); } - -#define OPENCV_HAL_IMPL_VSX_MULADD(_Tpvec) \ -inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_sqrt(vec_madd(a.val, a.val, vec_mul(b.val, b.val)))); } \ -inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(vec_madd(a.val, a.val, vec_mul(b.val, b.val))); } \ -inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } \ -inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } - -OPENCV_HAL_IMPL_VSX_MULADD(v_float32x4) -OPENCV_HAL_IMPL_VSX_MULADD(v_float64x2) - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ return v_add(v_mul(a, b), c); } - -// TODO: exp, log, sin, cos - -/** Absolute values **/ -inline v_uint8x16 v_abs(const v_int8x16& x) -{ return v_uint8x16(vec_uchar16_c(vec_abs(x.val))); } - -inline v_uint16x8 v_abs(const v_int16x8& x) -{ return v_uint16x8(vec_ushort8_c(vec_abs(x.val))); } - -inline v_uint32x4 v_abs(const v_int32x4& x) -{ return v_uint32x4(vec_uint4_c(vec_abs(x.val))); } - -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(vec_abs(x.val)); } - -inline v_float64x2 v_abs(const v_float64x2& x) -{ return v_float64x2(vec_abs(x.val)); } - -/** Absolute difference **/ -// unsigned -OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_absdiff, vec_absd) - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ return v_reinterpret_as_u8(v_sub_wrap(v_max(a, b), v_min(a, b))); } -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ return v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b))); } - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ return v_abs(v_sub(a, b)); } -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ return v_abs(v_sub(a, b)); } - -/** Absolute difference for signed integers **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ return v_int8x16(vec_abss(vec_subs(a.val, b.val))); } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_int16x8(vec_abss(vec_subs(a.val, b.val))); } - -////////// Conversions ///////// - -/** Rounding **/ -inline v_int32x4 v_round(const v_float32x4& a) -{ return v_int32x4(vec_cts(vec_rint(a.val))); } - -inline v_int32x4 v_round(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_int4_z)); } - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_ctso(vec_rint(b.val)))); } - -inline v_int32x4 v_floor(const v_float32x4& a) -{ return v_int32x4(vec_cts(vec_floor(a.val))); } - -inline v_int32x4 v_floor(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_floor(a.val)), vec_int4_z)); } - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ return v_int32x4(vec_cts(vec_ceil(a.val))); } - -inline v_int32x4 v_ceil(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(vec_ceil(a.val)), vec_int4_z)); } - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(vec_cts(a.val)); } - -inline v_int32x4 v_trunc(const v_float64x2& a) -{ return v_int32x4(vec_mergesqo(vec_ctso(a.val), vec_int4_z)); } - -/** To float **/ -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ return v_float32x4(vec_ctf(a.val)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_float4_z)); } - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_cvfo(b.val))); } - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ return v_float64x2(vec_ctdo(vec_mergeh(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ return v_float64x2(vec_ctdo(vec_mergel(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ return v_float64x2(vec_cvfo(vec_mergeh(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ return v_float64x2(vec_cvfo(vec_mergel(a.val, a.val))); } - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ return v_float64x2(vec_ctd(a.val)); } - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - return v_reinterpret_as_s8(v_int16x8(*(const short*)(tab+idx[0]), *(const short*)(tab+idx[1]), *(const short*)(tab+idx[2]), *(const short*)(tab+idx[3]), - *(const short*)(tab+idx[4]), *(const short*)(tab+idx[5]), *(const short*)(tab+idx[6]), *(const short*)(tab+idx[7]))); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - return v_reinterpret_as_s8(v_int32x4(*(const int*)(tab+idx[0]), *(const int*)(tab+idx[1]), *(const int*)(tab+idx[2]), *(const int*)(tab+idx[3]))); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - return v_reinterpret_as_s16(v_int32x4(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_reinterpret_as_s16(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short*)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short*)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short*)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_reinterpret_as_s32(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(vsx_ld(0, tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int*)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int*)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int*)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(vsx_ld2(0, tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int*)tab, idx)); } -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_load(tab + *idx); } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_load(tab + *idx); } - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - const int idx[4] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1), - vec_extract(idxvec.val, 2), - vec_extract(idxvec.val, 3) - }; - return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - const int idx[4] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1), - vec_extract(idxvec.val, 2), - vec_extract(idxvec.val, 3) - }; - return v_uint32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - const int idx[4] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1), - vec_extract(idxvec.val, 2), - vec_extract(idxvec.val, 3) - }; - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - const int idx[2] = { - vec_extract(idxvec.val, 0), - vec_extract(idxvec.val, 1) - }; - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} - -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - vec_float4 xy0 = vec_ld_l8(tab + vec_extract(idxvec.val, 0)); - vec_float4 xy1 = vec_ld_l8(tab + vec_extract(idxvec.val, 1)); - vec_float4 xy2 = vec_ld_l8(tab + vec_extract(idxvec.val, 2)); - vec_float4 xy3 = vec_ld_l8(tab + vec_extract(idxvec.val, 3)); - vec_float4 xy02 = vec_mergeh(xy0, xy2); // x0, x2, y0, y2 - vec_float4 xy13 = vec_mergeh(xy1, xy3); // x1, x3, y1, y3 - x.val = vec_mergeh(xy02, xy13); - y.val = vec_mergel(xy02, xy13); -} -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - vec_double2 xy0 = vsx_ld(vec_extract(idxvec.val, 0), tab); - vec_double2 xy1 = vsx_ld(vec_extract(idxvec.val, 1), tab); - x.val = vec_mergeh(xy0, xy1); - y.val = vec_mergel(xy0, xy1); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - static const vec_uchar16 perm = {0, 2, 1, 3, 4, 6, 5, 7, 8, 10, 9, 11, 12, 14, 13, 15}; - return v_int8x16(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } - -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - static const vec_uchar16 perm = {0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15}; - return v_int8x16(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - static const vec_uchar16 perm = {0,1, 4,5, 2,3, 6,7, 8,9, 12,13, 10,11, 14,15}; - return v_int16x8(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } - -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - static const vec_uchar16 perm = {0,1, 8,9, 2,3, 10,11, 4,5, 12,13, 6,7, 14,15}; - return v_int16x8(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - static const vec_uchar16 perm = {0,1,2,3, 8,9,10,11, 4,5,6,7, 12,13,14,15}; - return v_int32x4(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) -{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) -{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - static const vec_uchar16 perm = {0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 15, 15, 15}; - return v_int8x16(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) -{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - static const vec_uchar16 perm = {0,1, 2,3, 4,5, 8,9, 10,11, 12,13, 14,15, 14,15}; - return v_int16x8(vec_perm(vec.val, vec.val, perm)); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) -{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) -{ return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) -{ return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) -{ return vec; } - -/////// FP16 support //////// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - vec_ushort8 vf16 = vec_ld_l8((const ushort*)ptr); -#if CV_VSX3 && defined(vec_extract_fp_from_shorth) - return v_float32x4(vec_extract_fp_from_shorth(vf16)); -#elif CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) - vec_float4 vf32; - __asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wa" (vf32) : "wa" (vec_mergeh(vf16, vf16))); - return v_float32x4(vf32); -#else - const vec_int4 z = vec_int4_z, delta = vec_int4_sp(0x38000000); - const vec_int4 signmask = vec_int4_sp(0x80000000); - const vec_int4 maxexp = vec_int4_sp(0x7c000000); - const vec_float4 deltaf = vec_float4_c(vec_int4_sp(0x38800000)); - - vec_int4 bits = vec_int4_c(vec_mergeh(vec_short8_c(z), vec_short8_c(vf16))); - vec_int4 e = vec_and(bits, maxexp), sign = vec_and(bits, signmask); - vec_int4 t = vec_add(vec_sr(vec_xor(bits, sign), vec_uint4_sp(3)), delta); // ((h & 0x7fff) << 13) + delta - vec_int4 zt = vec_int4_c(vec_sub(vec_float4_c(vec_add(t, vec_int4_sp(1 << 23))), deltaf)); - - t = vec_add(t, vec_and(delta, vec_cmpeq(maxexp, e))); - vec_bint4 zmask = vec_cmpeq(e, z); - vec_int4 ft = vec_sel(t, zt, zmask); - return v_float32x4(vec_float4_c(vec_or(ft, sign))); -#endif -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ -// fixme: Is there any builtin op or intrinsic that cover "xvcvsphp"? -#if CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) - vec_ushort8 vf16; - __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wa" (v.val)); - vec_st_l8(vec_mergesqe(vf16, vf16), ptr); -#else - const vec_int4 signmask = vec_int4_sp(0x80000000); - const vec_int4 rval = vec_int4_sp(0x3f000000); - - vec_int4 t = vec_int4_c(v.val); - vec_int4 sign = vec_sra(vec_and(t, signmask), vec_uint4_sp(16)); - t = vec_and(vec_nor(signmask, signmask), t); - - vec_bint4 finitemask = vec_cmpgt(vec_int4_sp(0x47800000), t); - vec_bint4 isnan = vec_cmpgt(t, vec_int4_sp(0x7f800000)); - vec_int4 naninf = vec_sel(vec_int4_sp(0x7c00), vec_int4_sp(0x7e00), isnan); - vec_bint4 tinymask = vec_cmpgt(vec_int4_sp(0x38800000), t); - vec_int4 tt = vec_int4_c(vec_add(vec_float4_c(t), vec_float4_c(rval))); - tt = vec_sub(tt, rval); - vec_int4 odd = vec_and(vec_sr(t, vec_uint4_sp(13)), vec_int4_sp(1)); - vec_int4 nt = vec_add(t, vec_int4_sp(0xc8000fff)); - nt = vec_sr(vec_add(nt, odd), vec_uint4_sp(13)); - t = vec_sel(nt, tt, tinymask); - t = vec_sel(naninf, t, finitemask); - t = vec_or(t, sign); - vec_st_l8(vec_packs(t, t), ptr); -#endif -} - -inline void v_cleanup() {} - - -/** Reinterpret **/ -/** its up there with load and store operations **/ - -////////// Matrix operations ///////// - -//////// Dot Product //////// -// 16 >> 32 -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)); } -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_int32x4(vec_msum(a.val, b.val, c.val)); } - -// 32 >> 64 -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - vec_dword2 even = vec_mule(a.val, b.val); - vec_dword2 odd = vec_mulo(a.val, b.val); - return v_int64x2(vec_add(even, odd)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_add(v_dotprod(a, b), c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_uint32x4(vec_msum(a.val, b.val, c.val)); } -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)); } - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - const vec_ushort8 eight = vec_ushort8_sp(8); - vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even - vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd - vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); - vec_short8 b1 = vec_sra((vec_short8)b.val, eight); - return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); -} - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ - const vec_ushort8 eight = vec_ushort8_sp(8); - vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even - vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd - vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); - vec_short8 b1 = vec_sra((vec_short8)b.val, eight); - return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, c.val))); -} - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - const vec_uint4 zero = vec_uint4_z; - vec_uint4 even = vec_mule(a.val, b.val); - vec_uint4 odd = vec_mulo(a.val, b.val); - vec_udword2 e0 = (vec_udword2)vec_mergee(even, zero); - vec_udword2 e1 = (vec_udword2)vec_mergeo(even, zero); - vec_udword2 o0 = (vec_udword2)vec_mergee(odd, zero); - vec_udword2 o1 = (vec_udword2)vec_mergeo(odd, zero); - vec_udword2 s0 = vec_add(e0, o0); - vec_udword2 s1 = vec_add(e1, o1); - return v_uint64x2(vec_add(s0, s1)); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_int64x2(vec_add(vec_mergeh(c.val, d.val), vec_mergel(c.val, d.val))); -} -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)) + c; } -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)) + c; } - -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ - vec_short8 a0 = vec_unpackh(a.val); - vec_short8 a1 = vec_unpackl(a.val); - vec_short8 b0 = vec_unpackh(b.val); - vec_short8 b1 = vec_unpackl(b.val); - return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); -} -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 prod = v_dotprod(a, b); - v_int64x2 c, d; - v_expand(prod, c, d); - return v_add(c, d); -} -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand_fast(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - const vec_float4 v0 = vec_splat(v.val, 0); - const vec_float4 v1 = vec_splat(v.val, 1); - const vec_float4 v2 = vec_splat(v.val, 2); - VSX_UNUSED(const vec_float4) v3 = vec_splat(v.val, 3); - return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, vec_mul(v3, m3.val))))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - const vec_float4 v0 = vec_splat(v.val, 0); - const vec_float4 v1 = vec_splat(v.val, 1); - const vec_float4 v2 = vec_splat(v.val, 2); - return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, a.val)))); -} - -#define OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(_Tpvec, _Tpvec2) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ -{ \ - _Tpvec2 a02 = vec_mergeh(a0.val, a2.val); \ - _Tpvec2 a13 = vec_mergeh(a1.val, a3.val); \ - b0.val = vec_mergeh(a02, a13); \ - b1.val = vec_mergel(a02, a13); \ - a02 = vec_mergel(a0.val, a2.val); \ - a13 = vec_mergel(a1.val, a3.val); \ - b2.val = vec_mergeh(a02, a13); \ - b3.val = vec_mergel(a02, a13); \ -} -OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_uint32x4, vec_uint4) -OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_int32x4, vec_int4) -OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_float32x4, vec_float4) - -template -inline Tvec v_broadcast_element(const Tvec& v) -{ return Tvec(vec_splat(v.val, i)); } - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif // OPENCV_HAL_VSX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_VSX_HPP +#define OPENCV_HAL_VSX_HPP + +#include +#include "opencv2/core/utility.hpp" + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 1 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +///////// Types //////////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + enum { nlanes = 16 }; + vec_uchar16 val; + + explicit v_uint8x16(const vec_uchar16& v) : val(v) + {} + v_uint8x16() + {} + v_uint8x16(vec_bchar16 v) : val(vec_uchar16_c(v)) + {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + : val(vec_uchar16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) + {} + + static inline v_uint8x16 zero() { return v_uint8x16(vec_uchar16_z); } + + uchar get0() const + { return vec_extract(val, 0); } +}; + +struct v_int8x16 +{ + typedef schar lane_type; + enum { nlanes = 16 }; + vec_char16 val; + + explicit v_int8x16(const vec_char16& v) : val(v) + {} + v_int8x16() + {} + v_int8x16(vec_bchar16 v) : val(vec_char16_c(v)) + {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + : val(vec_char16_set(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15)) + {} + + static inline v_int8x16 zero() { return v_int8x16(vec_char16_z); } + + schar get0() const + { return vec_extract(val, 0); } +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + enum { nlanes = 8 }; + vec_ushort8 val; + + explicit v_uint16x8(const vec_ushort8& v) : val(v) + {} + v_uint16x8() + {} + v_uint16x8(vec_bshort8 v) : val(vec_ushort8_c(v)) + {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + : val(vec_ushort8_set(v0, v1, v2, v3, v4, v5, v6, v7)) + {} + + static inline v_uint16x8 zero() { return v_uint16x8(vec_ushort8_z); } + + ushort get0() const + { return vec_extract(val, 0); } +}; + +struct v_int16x8 +{ + typedef short lane_type; + enum { nlanes = 8 }; + vec_short8 val; + + explicit v_int16x8(const vec_short8& v) : val(v) + {} + v_int16x8() + {} + v_int16x8(vec_bshort8 v) : val(vec_short8_c(v)) + {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + : val(vec_short8_set(v0, v1, v2, v3, v4, v5, v6, v7)) + {} + + static inline v_int16x8 zero() { return v_int16x8(vec_short8_z); } + + short get0() const + { return vec_extract(val, 0); } +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + enum { nlanes = 4 }; + vec_uint4 val; + + explicit v_uint32x4(const vec_uint4& v) : val(v) + {} + v_uint32x4() + {} + v_uint32x4(vec_bint4 v) : val(vec_uint4_c(v)) + {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) : val(vec_uint4_set(v0, v1, v2, v3)) + {} + + static inline v_uint32x4 zero() { return v_uint32x4(vec_uint4_z); } + + uint get0() const + { return vec_extract(val, 0); } +}; + +struct v_int32x4 +{ + typedef int lane_type; + enum { nlanes = 4 }; + vec_int4 val; + + explicit v_int32x4(const vec_int4& v) : val(v) + {} + v_int32x4() + {} + v_int32x4(vec_bint4 v) : val(vec_int4_c(v)) + {} + v_int32x4(int v0, int v1, int v2, int v3) : val(vec_int4_set(v0, v1, v2, v3)) + {} + + static inline v_int32x4 zero() { return v_int32x4(vec_int4_z); } + + int get0() const + { return vec_extract(val, 0); } +}; + +struct v_float32x4 +{ + typedef float lane_type; + enum { nlanes = 4 }; + vec_float4 val; + + explicit v_float32x4(const vec_float4& v) : val(v) + {} + v_float32x4() + {} + v_float32x4(vec_bint4 v) : val(vec_float4_c(v)) + {} + v_float32x4(float v0, float v1, float v2, float v3) : val(vec_float4_set(v0, v1, v2, v3)) + {} + + static inline v_float32x4 zero() { return v_float32x4(vec_float4_z); } + + float get0() const + { return vec_extract(val, 0); } +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + enum { nlanes = 2 }; + vec_udword2 val; + + explicit v_uint64x2(const vec_udword2& v) : val(v) + {} + v_uint64x2() + {} + v_uint64x2(vec_bdword2 v) : val(vec_udword2_c(v)) + {} + v_uint64x2(uint64 v0, uint64 v1) : val(vec_udword2_set(v0, v1)) + {} + + static inline v_uint64x2 zero() { return v_uint64x2(vec_udword2_z); } + + uint64 get0() const + { return vec_extract(val, 0); } +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + enum { nlanes = 2 }; + vec_dword2 val; + + explicit v_int64x2(const vec_dword2& v) : val(v) + {} + v_int64x2() + {} + v_int64x2(vec_bdword2 v) : val(vec_dword2_c(v)) + {} + v_int64x2(int64 v0, int64 v1) : val(vec_dword2_set(v0, v1)) + {} + + static inline v_int64x2 zero() { return v_int64x2(vec_dword2_z); } + + int64 get0() const + { return vec_extract(val, 0); } +}; + +struct v_float64x2 +{ + typedef double lane_type; + enum { nlanes = 2 }; + vec_double2 val; + + explicit v_float64x2(const vec_double2& v) : val(v) + {} + v_float64x2() + {} + v_float64x2(vec_bdword2 v) : val(vec_double2_c(v)) + {} + v_float64x2(double v0, double v1) : val(vec_double2_set(v0, v1)) + {} + + static inline v_float64x2 zero() { return v_float64x2(vec_double2_z); } + + double get0() const + { return vec_extract(val, 0); } +}; + +#define OPENCV_HAL_IMPL_VSX_EXTRACT_N(_Tpvec, _Tp) \ +template inline _Tp v_extract_n(VSX_UNUSED(_Tpvec v)) { return vec_extract(v.val, i); } + +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint8x16, uchar) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int8x16, schar) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint16x8, ushort) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int16x8, short) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint32x4, uint) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int32x4, int) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_uint64x2, uint64) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_int64x2, int64) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float32x4, float) +OPENCV_HAL_IMPL_VSX_EXTRACT_N(v_float64x2, double) + +//////////////// Load and store operations /////////////// + +/* + * clang-5 aborted during parse "vec_xxx_c" only if it's + * inside a function template which is defined by preprocessor macro. + * + * if vec_xxx_c defined as C++ cast, clang-5 will pass it +*/ +#define OPENCV_HAL_IMPL_VSX_INITVEC(_Tpvec, _Tp, suffix, cast) \ +inline _Tpvec v_setzero_##suffix() { return _Tpvec(vec_splats((_Tp)0)); } \ +inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(vec_splats((_Tp)v));} \ +template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(_Tp v); } \ +template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0 &a) \ +{ return _Tpvec((cast)a.val); } + +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint8x16, uchar, u8, vec_uchar16) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int8x16, schar, s8, vec_char16) +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint16x8, ushort, u16, vec_ushort8) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int16x8, short, s16, vec_short8) +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint32x4, uint, u32, vec_uint4) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int32x4, int, s32, vec_int4) +OPENCV_HAL_IMPL_VSX_INITVEC(v_uint64x2, uint64, u64, vec_udword2) +OPENCV_HAL_IMPL_VSX_INITVEC(v_int64x2, int64, s64, vec_dword2) +OPENCV_HAL_IMPL_VSX_INITVEC(v_float32x4, float, f32, vec_float4) +OPENCV_HAL_IMPL_VSX_INITVEC(v_float64x2, double, f64, vec_double2) + +#define OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, ld, ld_a, st, st_a) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(ld(0, ptr)); } \ +inline _Tpvec v_load_aligned(VSX_UNUSED(const _Tp* ptr)) \ +{ return _Tpvec(ld_a(0, ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ return _Tpvec(vec_ld_l8(ptr)); } \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ return _Tpvec(vec_mergesqh(vec_ld_l8(ptr0), vec_ld_l8(ptr1))); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ st(a.val, 0, ptr); } \ +inline void v_store_aligned(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ +{ st_a(a.val, 0, ptr); } \ +inline void v_store_aligned_nocache(VSX_UNUSED(_Tp* ptr), const _Tpvec& a) \ +{ st_a(a.val, 0, ptr); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode mode) \ +{ if(mode == hal::STORE_UNALIGNED) st(a.val, 0, ptr); else st_a(a.val, 0, ptr); } \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ vec_st_l8(a.val, ptr); } \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ vec_st_h8(a.val, ptr); } + +// working around gcc bug for aligned ld/st +// if runtime check for vec_ld/st fail we failback to unaligned ld/st +// https://github.com/opencv/opencv/issues/13211 +#ifdef CV_COMPILER_VSX_BROKEN_ALIGNED + #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ + OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vsx_ld, vsx_st, vsx_st) +#else + #define OPENCV_HAL_IMPL_VSX_LOADSTORE(_Tpvec, _Tp) \ + OPENCV_HAL_IMPL_VSX_LOADSTORE_C(_Tpvec, _Tp, vsx_ld, vec_ld, vsx_st, vec_st) +#endif + +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint8x16, uchar) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int8x16, schar) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint16x8, ushort) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int16x8, short) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_uint32x4, uint) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_int32x4, int) +OPENCV_HAL_IMPL_VSX_LOADSTORE(v_float32x4, float) + +OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_float64x2, double, vsx_ld, vsx_ld, vsx_st, vsx_st) +OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_uint64x2, uint64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) +OPENCV_HAL_IMPL_VSX_LOADSTORE_C(v_int64x2, int64, vsx_ld2, vsx_ld2, vsx_st2, vsx_st2) + +//////////////// Value reordering /////////////// + +/* de&interleave */ +#define OPENCV_HAL_IMPL_VSX_INTERLEAVE(_Tp, _Tpvec) \ +inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b) \ +{ vec_ld_deinterleave(ptr, a.val, b.val);} \ +inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, \ + _Tpvec& b, _Tpvec& c) \ +{ vec_ld_deinterleave(ptr, a.val, b.val, c.val); } \ +inline void v_load_deinterleave(const _Tp* ptr, _Tpvec& a, _Tpvec& b, \ + _Tpvec& c, _Tpvec& d) \ +{ vec_ld_deinterleave(ptr, a.val, b.val, c.val, d.val); } \ +inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vec_st_interleave(a.val, b.val, ptr); } \ +inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, \ + const _Tpvec& b, const _Tpvec& c, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vec_st_interleave(a.val, b.val, c.val, ptr); } \ +inline void v_store_interleave(_Tp* ptr, const _Tpvec& a, const _Tpvec& b, \ + const _Tpvec& c, const _Tpvec& d, \ + hal::StoreMode /*mode*/=hal::STORE_UNALIGNED) \ +{ vec_st_interleave(a.val, b.val, c.val, d.val, ptr); } + +OPENCV_HAL_IMPL_VSX_INTERLEAVE(uchar, v_uint8x16) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(schar, v_int8x16) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(ushort, v_uint16x8) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(short, v_int16x8) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint, v_uint32x4) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(int, v_int32x4) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(float, v_float32x4) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(double, v_float64x2) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(int64, v_int64x2) +OPENCV_HAL_IMPL_VSX_INTERLEAVE(uint64, v_uint64x2) + +/* Expand */ +#define OPENCV_HAL_IMPL_VSX_EXPAND(_Tpvec, _Tpwvec, _Tp, fl, fh) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = fh(a.val); \ + b1.val = fl(a.val); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ return _Tpwvec(fh(a.val)); } \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ return _Tpwvec(fl(a.val)); } \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ return _Tpwvec(fh(vec_ld_l8(ptr))); } + +OPENCV_HAL_IMPL_VSX_EXPAND(v_uint8x16, v_uint16x8, uchar, vec_unpacklu, vec_unpackhu) +OPENCV_HAL_IMPL_VSX_EXPAND(v_int8x16, v_int16x8, schar, vec_unpackl, vec_unpackh) +OPENCV_HAL_IMPL_VSX_EXPAND(v_uint16x8, v_uint32x4, ushort, vec_unpacklu, vec_unpackhu) +OPENCV_HAL_IMPL_VSX_EXPAND(v_int16x8, v_int32x4, short, vec_unpackl, vec_unpackh) +OPENCV_HAL_IMPL_VSX_EXPAND(v_uint32x4, v_uint64x2, uint, vec_unpacklu, vec_unpackhu) +OPENCV_HAL_IMPL_VSX_EXPAND(v_int32x4, v_int64x2, int, vec_unpackl, vec_unpackh) + +/* Load and zero expand a 4 byte value into the second dword, first is don't care. */ +#if !defined(CV_COMPILER_VSX_BROKEN_ASM) + #define _LXSIWZX(out, ptr, T) __asm__ ("lxsiwzx %x0, 0, %1\r\n" : "=wa"(out) : "r" (ptr) : "memory"); +#else + /* This is compiler-agnostic, but will introduce an unneeded splat on the critical path. */ + #define _LXSIWZX(out, ptr, T) out = (T)vec_udword2_sp(*(uint32_t*)(ptr)); +#endif + +inline v_uint32x4 v_load_expand_q(const uchar* ptr) +{ + // Zero-extend the extra 24B instead of unpacking. Usually faster in small kernel + // Likewise note, value is zero extended and upper 4 bytes are zero'ed. + vec_uchar16 pmu = {8, 12, 12, 12, 9, 12, 12, 12, 10, 12, 12, 12, 11, 12, 12, 12}; + vec_uchar16 out; + + _LXSIWZX(out, ptr, vec_uchar16); + out = vec_perm(out, out, pmu); + return v_uint32x4((vec_uint4)out); +} + +inline v_int32x4 v_load_expand_q(const schar* ptr) +{ + vec_char16 out; + vec_short8 outs; + vec_int4 outw; + + _LXSIWZX(out, ptr, vec_char16); + outs = vec_unpackl(out); + outw = vec_unpackh(outs); + return v_int32x4(outw); +} + +/* pack */ +#define OPENCV_HAL_IMPL_VSX_PACK(_Tpvec, _Tp, _Tpwvec, _Tpvn, _Tpdel, sfnc, pkfnc, addfnc, pack) \ +inline _Tpvec v_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + return _Tpvec(pkfnc(a.val, b.val)); \ +} \ +inline void v_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + vec_st_l8(pkfnc(a.val, a.val), ptr); \ +} \ +template \ +inline _Tpvec v_rshr_##pack(const _Tpwvec& a, const _Tpwvec& b) \ +{ \ + const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ + const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ + return _Tpvec(pkfnc(sfnc(addfnc(a.val, delta), vn), sfnc(addfnc(b.val, delta), vn))); \ +} \ +template \ +inline void v_rshr_##pack##_store(_Tp* ptr, const _Tpwvec& a) \ +{ \ + const __vector _Tpvn vn = vec_splats((_Tpvn)n); \ + const __vector _Tpdel delta = vec_splats((_Tpdel)((_Tpdel)1 << (n-1))); \ + vec_st_l8(pkfnc(sfnc(addfnc(a.val, delta), vn), delta), ptr); \ +} + +OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_uint16x8, unsigned short, unsigned short, + vec_sr, vec_packs, vec_adds, pack) +OPENCV_HAL_IMPL_VSX_PACK(v_int8x16, schar, v_int16x8, unsigned short, short, + vec_sra, vec_packs, vec_adds, pack) + +OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_uint32x4, unsigned int, unsigned int, + vec_sr, vec_packs, vec_add, pack) +OPENCV_HAL_IMPL_VSX_PACK(v_int16x8, short, v_int32x4, unsigned int, int, + vec_sra, vec_packs, vec_add, pack) + +OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_uint64x2, unsigned long long, unsigned long long, + vec_sr, vec_pack, vec_add, pack) +OPENCV_HAL_IMPL_VSX_PACK(v_int32x4, int, v_int64x2, unsigned long long, long long, + vec_sra, vec_pack, vec_add, pack) + +OPENCV_HAL_IMPL_VSX_PACK(v_uint8x16, uchar, v_int16x8, unsigned short, short, + vec_sra, vec_packsu, vec_adds, pack_u) +OPENCV_HAL_IMPL_VSX_PACK(v_uint16x8, ushort, v_int32x4, unsigned int, int, + vec_sra, vec_packsu, vec_add, pack_u) +// Following variant is not implemented on other platforms: +//OPENCV_HAL_IMPL_VSX_PACK(v_uint32x4, uint, v_int64x2, unsigned long long, long long, +// vec_sra, vec_packsu, vec_add, pack_u) + +// pack boolean +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + vec_uchar16 ab = vec_pack(a.val, b.val); + return v_uint8x16(ab); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + vec_ushort8 ab = vec_pack(a.val, b.val); + vec_ushort8 cd = vec_pack(c.val, d.val); + return v_uint8x16(vec_pack(ab, cd)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + vec_uint4 ab = vec_pack(a.val, b.val); + vec_uint4 cd = vec_pack(c.val, d.val); + vec_uint4 ef = vec_pack(e.val, f.val); + vec_uint4 gh = vec_pack(g.val, h.val); + + vec_ushort8 abcd = vec_pack(ab, cd); + vec_ushort8 efgh = vec_pack(ef, gh); + return v_uint8x16(vec_pack(abcd, efgh)); +} + +/* Recombine */ +template +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) +{ + b0.val = vec_mergeh(a0.val, a1.val); + b1.val = vec_mergel(a0.val, a1.val); +} + +template +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(vec_mergesql(a.val, b.val)); } + +template +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) +{ return _Tpvec(vec_mergesqh(a.val, b.val)); } + +template +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) +{ + c.val = vec_mergesqh(a.val, b.val); + d.val = vec_mergesql(a.val, b.val); +} + +////////// Arithmetic, bitwise and comparison operations ///////// + +/* Element-wise binary and unary operations */ +/** Arithmetics **/ +#define OPENCV_HAL_IMPL_VSX_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint8x16, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint8x16, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int8x16, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int8x16, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint16x8, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint16x8, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int16x8, vec_adds) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int16x8, vec_subs) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint32x4, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint32x4, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_uint32x4, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int32x4, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int32x4, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_int32x4, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float32x4, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float32x4, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float32x4, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float32x4, vec_div) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_float64x2, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_float64x2, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_mul, v_float64x2, vec_mul) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_div, v_float64x2, vec_div) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_uint64x2, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_uint64x2, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_add, v_int64x2, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_OP(v_sub, v_int64x2, vec_sub) + +// saturating multiply +#define OPENCV_HAL_IMPL_VSX_MUL_SAT(_Tpvec, _Tpwvec) \ + inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ + { \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ + } + +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_int16x8, v_int32x4) +OPENCV_HAL_IMPL_VSX_MUL_SAT(v_uint16x8, v_uint32x4) + +template +inline void v_mul_expand(const Tvec& a, const Tvec& b, Twvec& c, Twvec& d) +{ + Twvec p0 = Twvec(vec_mule(a.val, b.val)); + Twvec p1 = Twvec(vec_mulo(a.val, b.val)); + v_zip(p0, p1, c, d); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + vec_int4 p0 = vec_mule(a.val, b.val); + vec_int4 p1 = vec_mulo(a.val, b.val); + static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; + return v_int16x8(vec_perm(vec_short8_c(p0), vec_short8_c(p1), perm)); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + vec_uint4 p0 = vec_mule(a.val, b.val); + vec_uint4 p1 = vec_mulo(a.val, b.val); + static const vec_uchar16 perm = {2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}; + return v_uint16x8(vec_perm(vec_ushort8_c(p0), vec_ushort8_c(p1), perm)); +} + +/** Non-saturating arithmetics **/ +#define OPENCV_HAL_IMPL_VSX_BIN_FUNC(func, intrin) \ +template \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(intrin(a.val, b.val)); } + +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_add_wrap, vec_add) +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_sub_wrap, vec_sub) +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_mul_wrap, vec_mul) + +/** Bitwise shifts **/ +#define OPENCV_HAL_IMPL_VSX_SHIFT_OP(_Tpvec, shr, splfunc) \ +inline _Tpvec v_shl(const _Tpvec& a, int imm) \ +{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ +inline _Tpvec v_shr(const _Tpvec& a, int imm) \ +{ return _Tpvec(shr(a.val, splfunc(imm))); } \ +template inline _Tpvec v_shl(const _Tpvec& a) \ +{ return _Tpvec(vec_sl(a.val, splfunc(imm))); } \ +template inline _Tpvec v_shr(const _Tpvec& a) \ +{ return _Tpvec(shr(a.val, splfunc(imm))); } + +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint8x16, vec_sr, vec_uchar16_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint16x8, vec_sr, vec_ushort8_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint32x4, vec_sr, vec_uint4_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_uint64x2, vec_sr, vec_udword2_sp) +// algebraic right shift +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int8x16, vec_sra, vec_uchar16_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int16x8, vec_sra, vec_ushort8_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int32x4, vec_sra, vec_uint4_sp) +OPENCV_HAL_IMPL_VSX_SHIFT_OP(v_int64x2, vec_sra, vec_udword2_sp) + +/** Bitwise logic **/ +#define OPENCV_HAL_IMPL_VSX_LOGIC_OP(_Tpvec) \ +OPENCV_HAL_IMPL_VSX_BIN_OP(v_and, _Tpvec, vec_and) \ +OPENCV_HAL_IMPL_VSX_BIN_OP(v_or, _Tpvec, vec_or) \ +OPENCV_HAL_IMPL_VSX_BIN_OP(v_xor, _Tpvec, vec_xor) \ +inline _Tpvec v_not(const _Tpvec& a) \ +{ return _Tpvec(vec_not(a.val)); } + +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint8x16) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int8x16) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint16x8) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int16x8) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint32x4) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int32x4) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_uint64x2) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_int64x2) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float32x4) +OPENCV_HAL_IMPL_VSX_LOGIC_OP(v_float64x2) + +/** Bitwise select **/ +#define OPENCV_HAL_IMPL_VSX_SELECT(_Tpvec, cast) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_sel(b.val, a.val, cast(mask.val))); } + +OPENCV_HAL_IMPL_VSX_SELECT(v_uint8x16, vec_bchar16_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_int8x16, vec_bchar16_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_uint16x8, vec_bshort8_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_int16x8, vec_bshort8_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_uint32x4, vec_bint4_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_int32x4, vec_bint4_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_float32x4, vec_bint4_c) +OPENCV_HAL_IMPL_VSX_SELECT(v_float64x2, vec_bdword2_c) + +/** Comparison **/ +#define OPENCV_HAL_IMPL_VSX_INT_CMP_OP(_Tpvec) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpeq(a.val, b.val)); } \ +inline _Tpvec V_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpne(a.val, b.val)); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmplt(a.val, b.val)); } \ +inline _Tpvec V_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpgt(a.val, b.val)); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmple(a.val, b.val)); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_cmpge(a.val, b.val)); } + +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint8x16) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int8x16) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint16x8) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int16x8) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint32x4) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int32x4) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float32x4) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_float64x2) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_uint64x2) +OPENCV_HAL_IMPL_VSX_INT_CMP_OP(v_int64x2) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ return v_float32x4(vec_cmpeq(a.val, a.val)); } +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ return v_float64x2(vec_cmpeq(a.val, a.val)); } + +/** min/max **/ +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_min, vec_min) +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_max, vec_max) + +/** Rotate **/ +#define OPENCV_IMPL_VSX_ROTATE(_Tpvec, suffix, shf, cast) \ +template \ +inline _Tpvec v_rotate_##suffix(const _Tpvec& a) \ +{ \ + const int wd = imm * sizeof(typename _Tpvec::lane_type); \ + if (wd > 15) \ + return _Tpvec::zero(); \ + return _Tpvec((cast)shf(vec_uchar16_c(a.val), vec_uchar16_sp(wd << 3))); \ +} + +#define OPENCV_IMPL_VSX_ROTATE_LR(_Tpvec, cast) \ +OPENCV_IMPL_VSX_ROTATE(_Tpvec, left, vec_slo, cast) \ +OPENCV_IMPL_VSX_ROTATE(_Tpvec, right, vec_sro, cast) + +OPENCV_IMPL_VSX_ROTATE_LR(v_uint8x16, vec_uchar16) +OPENCV_IMPL_VSX_ROTATE_LR(v_int8x16, vec_char16) +OPENCV_IMPL_VSX_ROTATE_LR(v_uint16x8, vec_ushort8) +OPENCV_IMPL_VSX_ROTATE_LR(v_int16x8, vec_short8) +OPENCV_IMPL_VSX_ROTATE_LR(v_uint32x4, vec_uint4) +OPENCV_IMPL_VSX_ROTATE_LR(v_int32x4, vec_int4) +OPENCV_IMPL_VSX_ROTATE_LR(v_float32x4, vec_float4) +OPENCV_IMPL_VSX_ROTATE_LR(v_uint64x2, vec_udword2) +OPENCV_IMPL_VSX_ROTATE_LR(v_int64x2, vec_dword2) +OPENCV_IMPL_VSX_ROTATE_LR(v_float64x2, vec_double2) + +template +inline _Tpvec v_rotate_right(const _Tpvec& a, const _Tpvec& b) +{ + enum { CV_SHIFT = 16 - imm * (sizeof(typename _Tpvec::lane_type)) }; + if (CV_SHIFT == 16) + return a; +#ifdef __IBMCPP__ + return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT & 15)); +#else + return _Tpvec(vec_sld(b.val, a.val, CV_SHIFT)); +#endif +} + +template +inline _Tpvec v_rotate_left(const _Tpvec& a, const _Tpvec& b) +{ + enum { CV_SHIFT = imm * (sizeof(typename _Tpvec::lane_type)) }; + if (CV_SHIFT == 16) + return b; + return _Tpvec(vec_sld(a.val, b.val, CV_SHIFT)); +} + +#define OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, suffix, rg1, rg2) \ +template \ +inline _Tpvec v_rotate_##suffix(const _Tpvec& a, const _Tpvec& b) \ +{ \ + if (imm == 1) \ + return _Tpvec(vec_permi(rg1.val, rg2.val, 2)); \ + return imm ? b : a; \ +} + +#define OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(_Tpvec) \ +OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, left, b, a) \ +OPENCV_IMPL_VSX_ROTATE_64_2RG(_Tpvec, right, a, b) + +OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_float64x2) +OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_uint64x2) +OPENCV_IMPL_VSX_ROTATE_64_2RG_LR(v_int64x2) + +/* Reverse */ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ + static const vec_uchar16 perm = {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_uint8x16(vec_perm(vec, vec, perm)); +} + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ + static const vec_uchar16 perm = {14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_reinterpret_as_u16(v_uint8x16(vec_perm(vec, vec, perm))); +} + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ + static const vec_uchar16 perm = {12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_reinterpret_as_u32(v_uint8x16(vec_perm(vec, vec, perm))); +} + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ + static const vec_uchar16 perm = {8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7}; + vec_uchar16 vec = (vec_uchar16)a.val; + return v_reinterpret_as_u64(v_uint8x16(vec_perm(vec, vec, perm))); +} + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + +/* Extract */ +template +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) +{ return v_rotate_right(a, b); } + +////////// Reduce and mask ///////// + +/** Reduce **/ +inline uint v_reduce_sum(const v_uint8x16& a) +{ + const vec_uint4 zero4 = vec_uint4_z; + vec_uint4 sum4 = vec_sum4s(a.val, zero4); + return (uint)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); +} +inline int v_reduce_sum(const v_int8x16& a) +{ + const vec_int4 zero4 = vec_int4_z; + vec_int4 sum4 = vec_sum4s(a.val, zero4); + return (int)vec_extract(vec_sums(sum4, zero4), 3); +} +inline int v_reduce_sum(const v_int16x8& a) +{ + const vec_int4 zero = vec_int4_z; + return saturate_cast(vec_extract(vec_sums(vec_sum4s(a.val, zero), zero), 3)); +} +inline uint v_reduce_sum(const v_uint16x8& a) +{ + const vec_int4 v4 = vec_int4_c(vec_unpackhu(vec_adds(a.val, vec_sld(a.val, a.val, 8)))); + return saturate_cast(vec_extract(vec_sums(v4, vec_int4_z), 3)); +} + +#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(_Tpvec, _Tpvec2, scalartype, suffix, func) \ +inline scalartype v_reduce_##suffix(const _Tpvec& a) \ +{ \ + const _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ + return vec_extract(func(rs, vec_sld(rs, rs, 4)), 0); \ +} +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, sum, vec_add) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_uint32x4, vec_uint4, uint, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, sum, vec_add) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_int32x4, vec_int4, int, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, sum, vec_add) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_4(v_float32x4, vec_float4, float, min, vec_min) + +inline uint64 v_reduce_sum(const v_uint64x2& a) +{ + return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); +} +inline int64 v_reduce_sum(const v_int64x2& a) +{ + return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); +} +inline double v_reduce_sum(const v_float64x2& a) +{ + return vec_extract(vec_add(a.val, vec_permi(a.val, a.val, 3)), 0); +} + +#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(_Tpvec, _Tpvec2, scalartype, suffix, func) \ +inline scalartype v_reduce_##suffix(const _Tpvec& a) \ +{ \ + _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ + rs = func(rs, vec_sld(rs, rs, 4)); \ + return vec_extract(func(rs, vec_sld(rs, rs, 2)), 0); \ +} +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_uint16x8, vec_ushort8, ushort, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_8(v_int16x8, vec_short8, short, min, vec_min) + +#define OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(_Tpvec, _Tpvec2, scalartype, suffix, func) \ +inline scalartype v_reduce_##suffix(const _Tpvec& a) \ +{ \ + _Tpvec2 rs = func(a.val, vec_sld(a.val, a.val, 8)); \ + rs = func(rs, vec_sld(rs, rs, 4)); \ + rs = func(rs, vec_sld(rs, rs, 2)); \ + return vec_extract(func(rs, vec_sld(rs, rs, 1)), 0); \ +} +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_uint8x16, vec_uchar16, uchar, min, vec_min) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, max, vec_max) +OPENCV_HAL_IMPL_VSX_REDUCE_OP_16(v_int8x16, vec_char16, schar, min, vec_min) + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + vec_float4 ac = vec_add(vec_mergel(a.val, c.val), vec_mergeh(a.val, c.val)); + ac = vec_add(ac, vec_sld(ac, ac, 8)); + + vec_float4 bd = vec_add(vec_mergel(b.val, d.val), vec_mergeh(b.val, d.val)); + bd = vec_add(bd, vec_sld(bd, bd, 8)); + return v_float32x4(vec_mergeh(ac, bd)); +} + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + const vec_uint4 zero4 = vec_uint4_z; + vec_uint4 sum4 = vec_sum4s(vec_absd(a.val, b.val), zero4); + return (unsigned)vec_extract(vec_sums(vec_int4_c(sum4), vec_int4_c(zero4)), 3); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + const vec_int4 zero4 = vec_int4_z; + vec_char16 ad = vec_abss(vec_subs(a.val, b.val)); + vec_int4 sum4 = vec_sum4s(ad, zero4); + return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + vec_ushort8 ad = vec_absd(a.val, b.val); + VSX_UNUSED(vec_int4) sum = vec_sums(vec_int4_c(vec_unpackhu(ad)) + vec_int4_c(vec_unpacklu(ad)), vec_int4_z); + return (unsigned)vec_extract(sum, 3); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + const vec_int4 zero4 = vec_int4_z; + vec_short8 ad = vec_abss(vec_subs(a.val, b.val)); + vec_int4 sum4 = vec_sum4s(ad, zero4); + return (unsigned)vec_extract(vec_sums(sum4, zero4), 3); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + const vec_uint4 ad = vec_absd(a.val, b.val); + const vec_uint4 rd = vec_add(ad, vec_sld(ad, ad, 8)); + return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + vec_int4 ad = vec_abss(vec_sub(a.val, b.val)); + return (unsigned)vec_extract(vec_sums(ad, vec_int4_z), 3); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + const vec_float4 ad = vec_abs(vec_sub(a.val, b.val)); + const vec_float4 rd = vec_add(ad, vec_sld(ad, ad, 8)); + return vec_extract(vec_add(rd, vec_sld(rd, rd, 4)), 0); +} + +/** Popcount **/ +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ return v_uint8x16(vec_popcntu(a.val)); } +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_uint8x16(vec_popcntu(a.val)); } +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ return v_uint16x8(vec_popcntu(a.val)); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_uint16x8(vec_popcntu(a.val)); } +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ return v_uint32x4(vec_popcntu(a.val)); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_uint32x4(vec_popcntu(a.val)); } +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ return v_uint64x2(vec_popcntu(a.val)); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_uint64x2(vec_popcntu(a.val)); } + +/** Mask **/ +inline int v_signmask(const v_uint8x16& a) +{ + static const vec_uchar16 qperm = {120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0}; + return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); +} +inline int v_signmask(const v_int8x16& a) +{ return v_signmask(v_reinterpret_as_u8(a)); } + +inline int v_signmask(const v_int16x8& a) +{ + static const vec_uchar16 qperm = {112, 96, 80, 64, 48, 32, 16, 0, 128, 128, 128, 128, 128, 128, 128, 128}; + return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); +} +inline int v_signmask(const v_uint16x8& a) +{ return v_signmask(v_reinterpret_as_s16(a)); } + +inline int v_signmask(const v_int32x4& a) +{ + static const vec_uchar16 qperm = {96, 64, 32, 0, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128}; + return vec_extract((vec_int4)vec_vbpermq(v_reinterpret_as_u8(a).val, qperm), 2); +} +inline int v_signmask(const v_uint32x4& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } +inline int v_signmask(const v_float32x4& a) +{ return v_signmask(v_reinterpret_as_s32(a)); } + +inline int v_signmask(const v_int64x2& a) +{ + VSX_UNUSED(const vec_dword2) sv = vec_sr(a.val, vec_udword2_sp(63)); + return (int)vec_extract(sv, 0) | (int)vec_extract(sv, 1) << 1; +} +inline int v_signmask(const v_uint64x2& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } +inline int v_signmask(const v_float64x2& a) +{ return v_signmask(v_reinterpret_as_s64(a)); } + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(a)); } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(a)); } + +template +inline bool v_check_all(const _Tpvec& a) +{ return vec_all_lt(a.val, _Tpvec::zero().val); } +inline bool v_check_all(const v_uint8x16& a) +{ return v_check_all(v_reinterpret_as_s8(a)); } +inline bool v_check_all(const v_uint16x8& a) +{ return v_check_all(v_reinterpret_as_s16(a)); } +inline bool v_check_all(const v_uint32x4& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_uint64x2& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } +inline bool v_check_all(const v_float32x4& a) +{ return v_check_all(v_reinterpret_as_s32(a)); } +inline bool v_check_all(const v_float64x2& a) +{ return v_check_all(v_reinterpret_as_s64(a)); } + +template +inline bool v_check_any(const _Tpvec& a) +{ return vec_any_lt(a.val, _Tpvec::zero().val); } +inline bool v_check_any(const v_uint8x16& a) +{ return v_check_any(v_reinterpret_as_s8(a)); } +inline bool v_check_any(const v_uint16x8& a) +{ return v_check_any(v_reinterpret_as_s16(a)); } +inline bool v_check_any(const v_uint32x4& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_uint64x2& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } +inline bool v_check_any(const v_float32x4& a) +{ return v_check_any(v_reinterpret_as_s32(a)); } +inline bool v_check_any(const v_float64x2& a) +{ return v_check_any(v_reinterpret_as_s64(a)); } + +////////// Other math ///////// + +/** Some frequent operations **/ +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ return v_float32x4(vec_sqrt(x.val)); } +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ return v_float64x2(vec_sqrt(x.val)); } + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ return v_float32x4(vec_rsqrt(x.val)); } +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ return v_float64x2(vec_rsqrt(x.val)); } + +#define OPENCV_HAL_IMPL_VSX_MULADD(_Tpvec) \ +inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_sqrt(vec_madd(a.val, a.val, vec_mul(b.val, b.val)))); } \ +inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(vec_madd(a.val, a.val, vec_mul(b.val, b.val))); } \ +inline _Tpvec v_fma(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } \ +inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ return _Tpvec(vec_madd(a.val, b.val, c.val)); } + +OPENCV_HAL_IMPL_VSX_MULADD(v_float32x4) +OPENCV_HAL_IMPL_VSX_MULADD(v_float64x2) + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ return v_add(v_mul(a, b), c); } + +// TODO: exp, log, sin, cos + +/** Absolute values **/ +inline v_uint8x16 v_abs(const v_int8x16& x) +{ return v_uint8x16(vec_uchar16_c(vec_abs(x.val))); } + +inline v_uint16x8 v_abs(const v_int16x8& x) +{ return v_uint16x8(vec_ushort8_c(vec_abs(x.val))); } + +inline v_uint32x4 v_abs(const v_int32x4& x) +{ return v_uint32x4(vec_uint4_c(vec_abs(x.val))); } + +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(vec_abs(x.val)); } + +inline v_float64x2 v_abs(const v_float64x2& x) +{ return v_float64x2(vec_abs(x.val)); } + +/** Absolute difference **/ +// unsigned +OPENCV_HAL_IMPL_VSX_BIN_FUNC(v_absdiff, vec_absd) + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ return v_reinterpret_as_u8(v_sub_wrap(v_max(a, b), v_min(a, b))); } +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); } +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ return v_reinterpret_as_u32(v_sub(v_max(a, b), v_min(a, b))); } + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ return v_abs(v_sub(a, b)); } +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ return v_abs(v_sub(a, b)); } + +/** Absolute difference for signed integers **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ return v_int8x16(vec_abss(vec_subs(a.val, b.val))); } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_int16x8(vec_abss(vec_subs(a.val, b.val))); } + +////////// Conversions ///////// + +/** Rounding **/ +inline v_int32x4 v_round(const v_float32x4& a) +{ return v_int32x4(vec_cts(vec_rint(a.val))); } + +inline v_int32x4 v_round(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_int4_z)); } + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_rint(a.val)), vec_ctso(vec_rint(b.val)))); } + +inline v_int32x4 v_floor(const v_float32x4& a) +{ return v_int32x4(vec_cts(vec_floor(a.val))); } + +inline v_int32x4 v_floor(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_floor(a.val)), vec_int4_z)); } + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ return v_int32x4(vec_cts(vec_ceil(a.val))); } + +inline v_int32x4 v_ceil(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(vec_ceil(a.val)), vec_int4_z)); } + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(vec_cts(a.val)); } + +inline v_int32x4 v_trunc(const v_float64x2& a) +{ return v_int32x4(vec_mergesqo(vec_ctso(a.val), vec_int4_z)); } + +/** To float **/ +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ return v_float32x4(vec_ctf(a.val)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_float4_z)); } + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ return v_float32x4(vec_mergesqo(vec_cvfo(a.val), vec_cvfo(b.val))); } + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ return v_float64x2(vec_ctdo(vec_mergeh(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ return v_float64x2(vec_ctdo(vec_mergel(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ return v_float64x2(vec_cvfo(vec_mergeh(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ return v_float64x2(vec_cvfo(vec_mergel(a.val, a.val))); } + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ return v_float64x2(vec_ctd(a.val)); } + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + return v_reinterpret_as_s8(v_int16x8(*(const short*)(tab+idx[0]), *(const short*)(tab+idx[1]), *(const short*)(tab+idx[2]), *(const short*)(tab+idx[3]), + *(const short*)(tab+idx[4]), *(const short*)(tab+idx[5]), *(const short*)(tab+idx[6]), *(const short*)(tab+idx[7]))); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + return v_reinterpret_as_s8(v_int32x4(*(const int*)(tab+idx[0]), *(const int*)(tab+idx[1]), *(const int*)(tab+idx[2]), *(const int*)(tab+idx[3]))); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar*)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar*)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + return v_reinterpret_as_s16(v_int32x4(*(const int*)(tab + idx[0]), *(const int*)(tab + idx[1]), *(const int*)(tab + idx[2]), *(const int*)(tab + idx[3]))); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_reinterpret_as_s16(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short*)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short*)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short*)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_reinterpret_as_s32(v_int64x2(*(const int64*)(tab + idx[0]), *(const int64*)(tab + idx[1]))); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(vsx_ld(0, tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int*)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int*)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int*)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(vsx_ld2(0, tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int*)tab, idx)); } +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_load(tab + *idx); } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) { return v_load(tab + *idx); } + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + const int idx[4] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1), + vec_extract(idxvec.val, 2), + vec_extract(idxvec.val, 3) + }; + return v_int32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + const int idx[4] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1), + vec_extract(idxvec.val, 2), + vec_extract(idxvec.val, 3) + }; + return v_uint32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + const int idx[4] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1), + vec_extract(idxvec.val, 2), + vec_extract(idxvec.val, 3) + }; + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + const int idx[2] = { + vec_extract(idxvec.val, 0), + vec_extract(idxvec.val, 1) + }; + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} + +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + vec_float4 xy0 = vec_ld_l8(tab + vec_extract(idxvec.val, 0)); + vec_float4 xy1 = vec_ld_l8(tab + vec_extract(idxvec.val, 1)); + vec_float4 xy2 = vec_ld_l8(tab + vec_extract(idxvec.val, 2)); + vec_float4 xy3 = vec_ld_l8(tab + vec_extract(idxvec.val, 3)); + vec_float4 xy02 = vec_mergeh(xy0, xy2); // x0, x2, y0, y2 + vec_float4 xy13 = vec_mergeh(xy1, xy3); // x1, x3, y1, y3 + x.val = vec_mergeh(xy02, xy13); + y.val = vec_mergel(xy02, xy13); +} +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + vec_double2 xy0 = vsx_ld(vec_extract(idxvec.val, 0), tab); + vec_double2 xy1 = vsx_ld(vec_extract(idxvec.val, 1), tab); + x.val = vec_mergeh(xy0, xy1); + y.val = vec_mergel(xy0, xy1); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + static const vec_uchar16 perm = {0, 2, 1, 3, 4, 6, 5, 7, 8, 10, 9, 11, 12, 14, 13, 15}; + return v_int8x16(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } + +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + static const vec_uchar16 perm = {0, 4, 1, 5, 2, 6, 3, 7, 8, 12, 9, 13, 10, 14, 11, 15}; + return v_int8x16(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + static const vec_uchar16 perm = {0,1, 4,5, 2,3, 6,7, 8,9, 12,13, 10,11, 14,15}; + return v_int16x8(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } + +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + static const vec_uchar16 perm = {0,1, 8,9, 2,3, 10,11, 4,5, 12,13, 6,7, 14,15}; + return v_int16x8(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + static const vec_uchar16 perm = {0,1,2,3, 8,9,10,11, 4,5,6,7, 12,13,14,15}; + return v_int32x4(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) +{ return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) +{ return v_reinterpret_as_f32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + static const vec_uchar16 perm = {0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14, 15, 15, 15, 15}; + return v_int8x16(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) +{ return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + static const vec_uchar16 perm = {0,1, 2,3, 4,5, 8,9, 10,11, 12,13, 14,15, 14,15}; + return v_int16x8(vec_perm(vec.val, vec.val, perm)); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) +{ return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) +{ return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) +{ return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) +{ return vec; } + +/////// FP16 support //////// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + vec_ushort8 vf16 = vec_ld_l8((const ushort*)ptr); +#if CV_VSX3 && defined(vec_extract_fp_from_shorth) + return v_float32x4(vec_extract_fp_from_shorth(vf16)); +#elif CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) + vec_float4 vf32; + __asm__ __volatile__ ("xvcvhpsp %x0,%x1" : "=wa" (vf32) : "wa" (vec_mergeh(vf16, vf16))); + return v_float32x4(vf32); +#else + const vec_int4 z = vec_int4_z, delta = vec_int4_sp(0x38000000); + const vec_int4 signmask = vec_int4_sp(0x80000000); + const vec_int4 maxexp = vec_int4_sp(0x7c000000); + const vec_float4 deltaf = vec_float4_c(vec_int4_sp(0x38800000)); + + vec_int4 bits = vec_int4_c(vec_mergeh(vec_short8_c(z), vec_short8_c(vf16))); + vec_int4 e = vec_and(bits, maxexp), sign = vec_and(bits, signmask); + vec_int4 t = vec_add(vec_sr(vec_xor(bits, sign), vec_uint4_sp(3)), delta); // ((h & 0x7fff) << 13) + delta + vec_int4 zt = vec_int4_c(vec_sub(vec_float4_c(vec_add(t, vec_int4_sp(1 << 23))), deltaf)); + + t = vec_add(t, vec_and(delta, vec_cmpeq(maxexp, e))); + vec_bint4 zmask = vec_cmpeq(e, z); + vec_int4 ft = vec_sel(t, zt, zmask); + return v_float32x4(vec_float4_c(vec_or(ft, sign))); +#endif +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ +// fixme: Is there any builtin op or intrinsic that cover "xvcvsphp"? +#if CV_VSX3 && !defined(CV_COMPILER_VSX_BROKEN_ASM) + vec_ushort8 vf16; + __asm__ __volatile__ ("xvcvsphp %x0,%x1" : "=wa" (vf16) : "wa" (v.val)); + vec_st_l8(vec_mergesqe(vf16, vf16), ptr); +#else + const vec_int4 signmask = vec_int4_sp(0x80000000); + const vec_int4 rval = vec_int4_sp(0x3f000000); + + vec_int4 t = vec_int4_c(v.val); + vec_int4 sign = vec_sra(vec_and(t, signmask), vec_uint4_sp(16)); + t = vec_and(vec_nor(signmask, signmask), t); + + vec_bint4 finitemask = vec_cmpgt(vec_int4_sp(0x47800000), t); + vec_bint4 isnan = vec_cmpgt(t, vec_int4_sp(0x7f800000)); + vec_int4 naninf = vec_sel(vec_int4_sp(0x7c00), vec_int4_sp(0x7e00), isnan); + vec_bint4 tinymask = vec_cmpgt(vec_int4_sp(0x38800000), t); + vec_int4 tt = vec_int4_c(vec_add(vec_float4_c(t), vec_float4_c(rval))); + tt = vec_sub(tt, rval); + vec_int4 odd = vec_and(vec_sr(t, vec_uint4_sp(13)), vec_int4_sp(1)); + vec_int4 nt = vec_add(t, vec_int4_sp(0xc8000fff)); + nt = vec_sr(vec_add(nt, odd), vec_uint4_sp(13)); + t = vec_sel(nt, tt, tinymask); + t = vec_sel(naninf, t, finitemask); + t = vec_or(t, sign); + vec_st_l8(vec_packs(t, t), ptr); +#endif +} + +inline void v_cleanup() {} + + +/** Reinterpret **/ +/** its up there with load and store operations **/ + +////////// Matrix operations ///////// + +//////// Dot Product //////// +// 16 >> 32 +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)); } +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_int32x4(vec_msum(a.val, b.val, c.val)); } + +// 32 >> 64 +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + vec_dword2 even = vec_mule(a.val, b.val); + vec_dword2 odd = vec_mulo(a.val, b.val); + return v_int64x2(vec_add(even, odd)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_add(v_dotprod(a, b), c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_uint32x4(vec_msum(a.val, b.val, c.val)); } +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)); } + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + const vec_ushort8 eight = vec_ushort8_sp(8); + vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even + vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd + vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); + vec_short8 b1 = vec_sra((vec_short8)b.val, eight); + return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); +} + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ + const vec_ushort8 eight = vec_ushort8_sp(8); + vec_short8 a0 = vec_sra((vec_short8)vec_sld(a.val, a.val, 1), eight); // even + vec_short8 a1 = vec_sra((vec_short8)a.val, eight); // odd + vec_short8 b0 = vec_sra((vec_short8)vec_sld(b.val, b.val, 1), eight); + vec_short8 b1 = vec_sra((vec_short8)b.val, eight); + return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, c.val))); +} + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + const vec_uint4 zero = vec_uint4_z; + vec_uint4 even = vec_mule(a.val, b.val); + vec_uint4 odd = vec_mulo(a.val, b.val); + vec_udword2 e0 = (vec_udword2)vec_mergee(even, zero); + vec_udword2 e1 = (vec_udword2)vec_mergeo(even, zero); + vec_udword2 o0 = (vec_udword2)vec_mergee(odd, zero); + vec_udword2 o1 = (vec_udword2)vec_mergeo(odd, zero); + vec_udword2 s0 = vec_add(e0, o0); + vec_udword2 s1 = vec_add(e1, o1); + return v_uint64x2(vec_add(s0, s1)); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_int64x2(vec_add(vec_mergeh(c.val, d.val), vec_mergel(c.val, d.val))); +} +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_int32x4(vec_msum(a.val, b.val, vec_int4_z)) + c; } +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_uint32x4(vec_msum(a.val, b.val, vec_uint4_z)) + c; } + +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ + vec_short8 a0 = vec_unpackh(a.val); + vec_short8 a1 = vec_unpackl(a.val); + vec_short8 b0 = vec_unpackh(b.val); + vec_short8 b1 = vec_unpackl(b.val); + return v_int32x4(vec_msum(a0, b0, vec_msum(a1, b1, vec_int4_z))); +} +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 prod = v_dotprod(a, b); + v_int64x2 c, d; + v_expand(prod, c, d); + return v_add(c, d); +} +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand_fast(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + const vec_float4 v0 = vec_splat(v.val, 0); + const vec_float4 v1 = vec_splat(v.val, 1); + const vec_float4 v2 = vec_splat(v.val, 2); + VSX_UNUSED(const vec_float4) v3 = vec_splat(v.val, 3); + return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, vec_mul(v3, m3.val))))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + const vec_float4 v0 = vec_splat(v.val, 0); + const vec_float4 v1 = vec_splat(v.val, 1); + const vec_float4 v2 = vec_splat(v.val, 2); + return v_float32x4(vec_madd(v0, m0.val, vec_madd(v1, m1.val, vec_madd(v2, m2.val, a.val)))); +} + +#define OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(_Tpvec, _Tpvec2) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, _Tpvec& b2, _Tpvec& b3) \ +{ \ + _Tpvec2 a02 = vec_mergeh(a0.val, a2.val); \ + _Tpvec2 a13 = vec_mergeh(a1.val, a3.val); \ + b0.val = vec_mergeh(a02, a13); \ + b1.val = vec_mergel(a02, a13); \ + a02 = vec_mergel(a0.val, a2.val); \ + a13 = vec_mergel(a1.val, a3.val); \ + b2.val = vec_mergeh(a02, a13); \ + b3.val = vec_mergel(a02, a13); \ +} +OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_uint32x4, vec_uint4) +OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_int32x4, vec_int4) +OPENCV_HAL_IMPL_VSX_TRANSPOSE4x4(v_float32x4, vec_float4) + +template +inline Tvec v_broadcast_element(const Tvec& v) +{ return Tvec(vec_splat(v.val, i)); } + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif // OPENCV_HAL_VSX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp index d8d27edb3a..7c4d8e05df 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/intrin_wasm.hpp @@ -1,2801 +1,2801 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_HAL_INTRIN_WASM_HPP -#define OPENCV_HAL_INTRIN_WASM_HPP - -#include -#include -#include -#include "opencv2/core/saturate.hpp" - - -// Emscripten v2.0.13 (latest officially supported, as of 07/30/2024): -// __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__ and __EMSCRIPTEN_tiny__ are defined via commandline in -// https://github.com/emscripten-core/emscripten/blob/1690a5802cd1241adc9714fb7fa2f633d38860dc/tools/shared.py#L506-L515 -// -// See https://github.com/opencv/opencv/pull/25909 -#ifndef __EMSCRIPTEN_major__ -#include -#endif - -#define CV_SIMD128 1 -#define CV_SIMD128_64F 0 // Now all implementation of f64 use fallback, so disable it. -#define CV_SIMD128_FP16 0 - -namespace cv -{ - -//! @cond IGNORED - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN - -#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) < (1038046) -// handle renames: https://github.com/emscripten-core/emscripten/pull/9440 (https://github.com/emscripten-core/emscripten/commit/755d5b46cb84d0aa120c10981b11d05646c29673) -#define wasm_i32x4_trunc_saturate_f32x4 wasm_trunc_saturate_i32x4_f32x4 -#define wasm_u32x4_trunc_saturate_f32x4 wasm_trunc_saturate_u32x4_f32x4 -#define wasm_i64x2_trunc_saturate_f64x2 wasm_trunc_saturate_i64x2_f64x2 -#define wasm_u64x2_trunc_saturate_f64x2 wasm_trunc_saturate_u64x2_f64x2 -#define wasm_f32x4_convert_i32x4 wasm_convert_f32x4_i32x4 -#define wasm_f32x4_convert_u32x4 wasm_convert_f32x4_u32x4 -#define wasm_f64x2_convert_i64x2 wasm_convert_f64x2_i64x2 -#define wasm_f64x2_convert_u64x2 wasm_convert_f64x2_u64x2 -#endif // COMPATIBILITY: <1.38.46 - -///////// Types /////////// - -struct v_uint8x16 -{ - typedef uchar lane_type; - typedef v128_t vector_type; - enum { nlanes = 16 }; - - v_uint8x16() {} - explicit v_uint8x16(v128_t v) : val(v) {} - v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, - uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) - { - uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = wasm_v128_load(v); - } - - uchar get0() const - { - return (uchar)wasm_i8x16_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_int8x16 -{ - typedef schar lane_type; - typedef v128_t vector_type; - enum { nlanes = 16 }; - - v_int8x16() {} - explicit v_int8x16(v128_t v) : val(v) {} - v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, - schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) - { - schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; - val = wasm_v128_load(v); - } - - schar get0() const - { - return wasm_i8x16_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_uint16x8 -{ - typedef ushort lane_type; - typedef v128_t vector_type; - enum { nlanes = 8 }; - - v_uint16x8() {} - explicit v_uint16x8(v128_t v) : val(v) {} - v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) - { - ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = wasm_v128_load(v); - } - - ushort get0() const - { - return (ushort)wasm_i16x8_extract_lane(val, 0); // wasm_u16x8_extract_lane() unimplemented yet - } - - v128_t val; -}; - -struct v_int16x8 -{ - typedef short lane_type; - typedef v128_t vector_type; - enum { nlanes = 8 }; - - v_int16x8() {} - explicit v_int16x8(v128_t v) : val(v) {} - v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) - { - short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; - val = wasm_v128_load(v); - } - - short get0() const - { - return wasm_i16x8_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_uint32x4 -{ - typedef unsigned lane_type; - typedef v128_t vector_type; - enum { nlanes = 4 }; - - v_uint32x4() {} - explicit v_uint32x4(v128_t v) : val(v) {} - v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) - { - unsigned v[] = {v0, v1, v2, v3}; - val = wasm_v128_load(v); - } - - unsigned get0() const - { - return (unsigned)wasm_i32x4_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_int32x4 -{ - typedef int lane_type; - typedef v128_t vector_type; - enum { nlanes = 4 }; - - v_int32x4() {} - explicit v_int32x4(v128_t v) : val(v) {} - v_int32x4(int v0, int v1, int v2, int v3) - { - int v[] = {v0, v1, v2, v3}; - val = wasm_v128_load(v); - } - - int get0() const - { - return wasm_i32x4_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_float32x4 -{ - typedef float lane_type; - typedef v128_t vector_type; - enum { nlanes = 4 }; - - v_float32x4() {} - explicit v_float32x4(v128_t v) : val(v) {} - v_float32x4(float v0, float v1, float v2, float v3) - { - float v[] = {v0, v1, v2, v3}; - val = wasm_v128_load(v); - } - - float get0() const - { - return wasm_f32x4_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_uint64x2 -{ - typedef uint64 lane_type; - typedef v128_t vector_type; - enum { nlanes = 2 }; - - v_uint64x2() {} - explicit v_uint64x2(v128_t v) : val(v) {} - v_uint64x2(uint64 v0, uint64 v1) - { - uint64 v[] = {v0, v1}; - val = wasm_v128_load(v); - } - - uint64 get0() const - { - return (uint64)wasm_i64x2_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_int64x2 -{ - typedef int64 lane_type; - typedef v128_t vector_type; - enum { nlanes = 2 }; - - v_int64x2() {} - explicit v_int64x2(v128_t v) : val(v) {} - v_int64x2(int64 v0, int64 v1) - { - int64 v[] = {v0, v1}; - val = wasm_v128_load(v); - } - - int64 get0() const - { - return wasm_i64x2_extract_lane(val, 0); - } - - v128_t val; -}; - -struct v_float64x2 -{ - typedef double lane_type; - typedef v128_t vector_type; - enum { nlanes = 2 }; - - v_float64x2() {} - explicit v_float64x2(v128_t v) : val(v) {} - v_float64x2(double v0, double v1) - { - double v[] = {v0, v1}; - val = wasm_v128_load(v); - } - - double get0() const - { - return wasm_f64x2_extract_lane(val, 0); - } - - v128_t val; -}; - -namespace -{ -#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ -inline tt reinterpret_int(ft x) { union { ft l; tt i; } v; v.l = x; return v.i; } -OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) -OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) -OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) -OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) -OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) - -static const unsigned char popCountTable[] = -{ - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, -}; -} // namespace - -static v128_t wasm_unpacklo_i8x16(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23); -} - -static v128_t wasm_unpacklo_i16x8(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,1,16,17,2,3,18,19,4,5,20,21,6,7,22,23); -} - -static v128_t wasm_unpacklo_i32x4(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,1,2,3,16,17,18,19,4,5,6,7,20,21,22,23); -} - -static v128_t wasm_unpacklo_i64x2(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); -} - -static v128_t wasm_unpackhi_i8x16(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,24,9,25,10,26,11,27,12,28,13,29,14,30,15,31); -} - -static v128_t wasm_unpackhi_i16x8(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,9,24,25,10,11,26,27,12,13,28,29,14,15,30,31); -} - -static v128_t wasm_unpackhi_i32x4(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,9,10,11,24,25,26,27,12,13,14,15,28,29,30,31); -} - -static v128_t wasm_unpackhi_i64x2(v128_t a, v128_t b) { - return wasm_i8x16_shuffle(a, b, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); -} - -/** Convert **/ -// 8 >> 16 -inline v128_t v128_cvtu8x16_i16x8(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i8x16(a, z); -} -inline v128_t v128_cvti8x16_i16x8(const v128_t& a) -{ return wasm_i16x8_shr(wasm_unpacklo_i8x16(a, a), 8); } -// 8 >> 32 -inline v128_t v128_cvtu8x16_i32x4(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i16x8(wasm_unpacklo_i8x16(a, z), z); -} -inline v128_t v128_cvti8x16_i32x4(const v128_t& a) -{ - v128_t r = wasm_unpacklo_i8x16(a, a); - r = wasm_unpacklo_i8x16(r, r); - return wasm_i32x4_shr(r, 24); -} -// 16 >> 32 -inline v128_t v128_cvtu16x8_i32x4(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i16x8(a, z); -} -inline v128_t v128_cvti16x8_i32x4(const v128_t& a) -{ return wasm_i32x4_shr(wasm_unpacklo_i16x8(a, a), 16); } -// 32 >> 64 -inline v128_t v128_cvtu32x4_i64x2(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpacklo_i32x4(a, z); -} -inline v128_t v128_cvti32x4_i64x2(const v128_t& a) -{ return wasm_unpacklo_i32x4(a, wasm_i32x4_shr(a, 31)); } - -// 16 << 8 -inline v128_t v128_cvtu8x16_i16x8_high(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpackhi_i8x16(a, z); -} -inline v128_t v128_cvti8x16_i16x8_high(const v128_t& a) -{ return wasm_i16x8_shr(wasm_unpackhi_i8x16(a, a), 8); } -// 32 << 16 -inline v128_t v128_cvtu16x8_i32x4_high(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpackhi_i16x8(a, z); -} -inline v128_t v128_cvti16x8_i32x4_high(const v128_t& a) -{ return wasm_i32x4_shr(wasm_unpackhi_i16x8(a, a), 16); } -// 64 << 32 -inline v128_t v128_cvtu32x4_i64x2_high(const v128_t& a) -{ - const v128_t z = wasm_i8x16_splat(0); - return wasm_unpackhi_i32x4(a, z); -} -inline v128_t v128_cvti32x4_i64x2_high(const v128_t& a) -{ return wasm_unpackhi_i32x4(a, wasm_i32x4_shr(a, 31)); } - -#define OPENCV_HAL_IMPL_WASM_INITVEC(_Tpvec, _Tp, suffix, zsuffix, _Tps) \ -inline _Tpvec v_setzero_##suffix() { return _Tpvec(wasm_##zsuffix##_splat((_Tps)0)); } \ -inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(wasm_##zsuffix##_splat((_Tps)v)); } \ -template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ -template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ -template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ -{ return _Tpvec(a.val); } - -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint8x16, uchar, u8, i8x16, schar) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int8x16, schar, s8, i8x16, schar) -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint16x8, ushort, u16, i16x8, short) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int16x8, short, s16, i16x8, short) -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint32x4, unsigned, u32, i32x4, int) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int32x4, int, s32, i32x4, int) -OPENCV_HAL_IMPL_WASM_INITVEC(v_float32x4, float, f32, f32x4, float) -OPENCV_HAL_IMPL_WASM_INITVEC(v_uint64x2, uint64, u64, i64x2, int64) -OPENCV_HAL_IMPL_WASM_INITVEC(v_int64x2, int64, s64, i64x2, int64) -OPENCV_HAL_IMPL_WASM_INITVEC(v_float64x2, double, f64, f64x2, double) - -//////////////// PACK /////////////// -inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); - return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); - return v_int8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); - return v_uint16x8(wasm_i8x16_shuffle(a1, b1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) -{ - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i32x4_splat(-32768); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); - return v_int16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - return v_uint32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) -{ - return v_int32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); - return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i32x4_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); - return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} - -template -inline v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t b1 = wasm_u16x8_shr(wasm_i16x8_add(b.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u16x8_gt(b1, maxval)); - return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -template -inline v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); - return v_int8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -template -inline v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t b1 = wasm_u32x4_shr(wasm_i32x4_add(b.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u32x4_gt(b1, maxval)); - return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -template -inline v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i16x8_splat(-32768); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); - return v_int16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} -template -inline v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t b1 = wasm_u64x2_shr(wasm_i64x2_add(b.val, delta), n); - return v_uint32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -template -inline v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t b1 = wasm_i64x2_shr(wasm_i64x2_add(b.val, delta), n); - return v_int32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); -} -template -inline v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); - return v_uint8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} -template -inline v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i16x8_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); - return v_uint16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); -} - -inline void v_pack_store(uchar* ptr, const v_uint16x8& a) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(schar* ptr, const v_int16x8& a) -{ - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - schar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(ushort* ptr, const v_uint32x4& a) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(short* ptr, const v_int32x4& a) -{ - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i32x4_splat(-32768); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - short t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - unsigned t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_store(int* ptr, const v_int64x2& a) -{ - v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - int t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) -{ - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i32x4_splat(0); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); - v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} - -template -inline void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) -{ - v128_t delta = wasm_i16x8_splat((short)(1 << (n-1))); - v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(schar* ptr, const v_int16x8& a) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t maxval = wasm_i16x8_splat(127); - v128_t minval = wasm_i16x8_splat(-128); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - schar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); - v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(short* ptr, const v_int32x4& a) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t maxval = wasm_i32x4_splat(32767); - v128_t minval = wasm_i32x4_splat(-32768); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - short t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - unsigned t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_store(int* ptr, const v_int64x2& a) -{ - v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); - v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); - v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); - int t_ptr[4]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<2; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) -{ - v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); - v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); - v128_t maxval = wasm_i16x8_splat(255); - v128_t minval = wasm_i16x8_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); - uchar t_ptr[16]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<8; ++i) { - ptr[i] = t_ptr[i]; - } -} -template -inline void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) -{ - v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); - v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); - v128_t maxval = wasm_i32x4_splat(65535); - v128_t minval = wasm_i32x4_splat(0); - v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); - v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); - v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); - ushort t_ptr[8]; - wasm_v128_store(t_ptr, r); - for (int i=0; i<4; ++i) { - ptr[i] = t_ptr[i]; - } -} - -inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t maxval = wasm_i16x8_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); - return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); -} - -inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d) -{ - v128_t maxval = wasm_i32x4_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); - v128_t c1 = wasm_v128_bitselect(maxval, c.val, wasm_u32x4_gt(c.val, maxval)); - v128_t d1 = wasm_v128_bitselect(maxval, d.val, wasm_u32x4_gt(d.val, maxval)); - v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); - v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); - return v_uint8x16(wasm_i8x16_shuffle(ab, cd, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); -} - -inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, - const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, - const v_uint64x2& g, const v_uint64x2& h) -{ - v128_t maxval = wasm_i32x4_splat(255); - v128_t a1 = wasm_v128_bitselect(maxval, a.val, ((__u64x2)(a.val) > (__u64x2)maxval)); - v128_t b1 = wasm_v128_bitselect(maxval, b.val, ((__u64x2)(b.val) > (__u64x2)maxval)); - v128_t c1 = wasm_v128_bitselect(maxval, c.val, ((__u64x2)(c.val) > (__u64x2)maxval)); - v128_t d1 = wasm_v128_bitselect(maxval, d.val, ((__u64x2)(d.val) > (__u64x2)maxval)); - v128_t e1 = wasm_v128_bitselect(maxval, e.val, ((__u64x2)(e.val) > (__u64x2)maxval)); - v128_t f1 = wasm_v128_bitselect(maxval, f.val, ((__u64x2)(f.val) > (__u64x2)maxval)); - v128_t g1 = wasm_v128_bitselect(maxval, g.val, ((__u64x2)(g.val) > (__u64x2)maxval)); - v128_t h1 = wasm_v128_bitselect(maxval, h.val, ((__u64x2)(h.val) > (__u64x2)maxval)); - v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t ef = wasm_i8x16_shuffle(e1, f1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t gh = wasm_i8x16_shuffle(g1, h1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); - v128_t abcd = wasm_i8x16_shuffle(ab, cd, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); - v128_t efgh = wasm_i8x16_shuffle(ef, gh, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); - return v_uint8x16(wasm_i8x16_shuffle(abcd, efgh, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); -} - -inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& m3) -{ - v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); - v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); - v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); - v128_t v3 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 3)); - v0 = wasm_f32x4_mul(v0, m0.val); - v1 = wasm_f32x4_mul(v1, m1.val); - v2 = wasm_f32x4_mul(v2, m2.val); - v3 = wasm_f32x4_mul(v3, m3.val); - - return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, v3))); -} - -inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, - const v_float32x4& m1, const v_float32x4& m2, - const v_float32x4& a) -{ - v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); - v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); - v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); - v0 = wasm_f32x4_mul(v0, m0.val); - v1 = wasm_f32x4_mul(v1, m1.val); - v2 = wasm_f32x4_mul(v2, m2.val); - - return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, a.val))); -} - -#define OPENCV_HAL_IMPL_WASM_BIN_OP(bin_op, _Tpvec, intrin) \ -inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint8x16, wasm_u8x16_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint8x16, wasm_u8x16_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int8x16, wasm_i8x16_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int8x16, wasm_i8x16_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint16x8, wasm_u16x8_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint16x8, wasm_u16x8_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int16x8, wasm_i16x8_add_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int16x8, wasm_i16x8_sub_saturate) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint32x4, wasm_i32x4_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint32x4, wasm_i32x4_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_uint32x4, wasm_i32x4_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int32x4, wasm_i32x4_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int32x4, wasm_i32x4_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_int32x4, wasm_i32x4_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float32x4, wasm_f32x4_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float32x4, wasm_f32x4_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float32x4, wasm_f32x4_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float32x4, wasm_f32x4_div) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint64x2, wasm_i64x2_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint64x2, wasm_i64x2_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int64x2, wasm_i64x2_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int64x2, wasm_i64x2_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float64x2, wasm_f64x2_add) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float64x2, wasm_f64x2_sub) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float64x2, wasm_f64x2_mul) -OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float64x2, wasm_f64x2_div) - -// saturating multiply 8-bit, 16-bit -#define OPENCV_HAL_IMPL_WASM_MUL_SAT(_Tpvec, _Tpwvec) \ -inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ -{ \ - _Tpwvec c, d; \ - v_mul_expand(a, b, c, d); \ - return v_pack(c, d); \ -} - -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint8x16, v_uint16x8) -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int8x16, v_int16x8) -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint16x8, v_uint32x4) -OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int16x8, v_int32x4) - -// Multiply and expand -inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, - v_uint16x8& c, v_uint16x8& d) -{ - v_uint16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, - v_int16x8& c, v_int16x8& d) -{ - v_int16x8 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c = v_mul_wrap(a0, b0); - d = v_mul_wrap(a1, b1); -} - -inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, - v_int32x4& c, v_int32x4& d) -{ - v_int32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c.val = wasm_i32x4_mul(a0.val, b0.val); - d.val = wasm_i32x4_mul(a1.val, b1.val); -} - -inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, - v_uint32x4& c, v_uint32x4& d) -{ - v_uint32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c.val = wasm_i32x4_mul(a0.val, b0.val); - d.val = wasm_i32x4_mul(a1.val, b1.val); -} - -inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, - v_uint64x2& c, v_uint64x2& d) -{ - v_uint64x2 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - c.val = ((__u64x2)(a0.val) * (__u64x2)(b0.val)); - d.val = ((__u64x2)(a1.val) * (__u64x2)(b1.val)); -} - -inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) -{ - v_int32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - v128_t c = wasm_i32x4_mul(a0.val, b0.val); - v128_t d = wasm_i32x4_mul(a1.val, b1.val); - return v_int16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); -} -inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 a0, a1, b0, b1; - v_expand(a, a0, a1); - v_expand(b, b0, b1); - v128_t c = wasm_i32x4_mul(a0.val, b0.val); - v128_t d = wasm_i32x4_mul(a1.val, b1.val); - return v_uint16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); -} - -//////// Dot Product //////// - -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) -{ - v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); - v128_t a1 = wasm_i32x4_shr(a.val, 16); - v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); - v128_t b1 = wasm_i32x4_shr(b.val, 16); - v128_t c = wasm_i32x4_mul(a0, b0); - v128_t d = wasm_i32x4_mul(a1, b1); - return v_int32x4(wasm_i32x4_add(c, d)); -} - -inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_add(v_dotprod(a, b), c); } - -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) -{ - v128_t a0 = wasm_i64x2_shr(wasm_i64x2_shl(a.val, 32), 32); - v128_t a1 = wasm_i64x2_shr(a.val, 32); - v128_t b0 = wasm_i64x2_shr(wasm_i64x2_shl(b.val, 32), 32); - v128_t b1 = wasm_i64x2_shr(b.val, 32); - v128_t c = (v128_t)((__i64x2)a0 * (__i64x2)b0); - v128_t d = (v128_t)((__i64x2)a1 * (__i64x2)b1); - return v_int64x2(wasm_i64x2_add(c, d)); -} -inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ - return v_add(v_dotprod(a, b), c); -} - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) -{ - v128_t a0 = wasm_u16x8_shr(wasm_i16x8_shl(a.val, 8), 8); - v128_t a1 = wasm_u16x8_shr(a.val, 8); - v128_t b0 = wasm_u16x8_shr(wasm_i16x8_shl(b.val, 8), 8); - v128_t b1 = wasm_u16x8_shr(b.val, 8); - return v_uint32x4((v_add( - v_dotprod(v_int16x8(a0), v_int16x8(b0)), - v_dotprod(v_int16x8(a1), v_int16x8(b1)))).val - ); -} -inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) -{ - v128_t a0 = wasm_i16x8_shr(wasm_i16x8_shl(a.val, 8), 8); - v128_t a1 = wasm_i16x8_shr(a.val, 8); - v128_t b0 = wasm_i16x8_shr(wasm_i16x8_shl(b.val, 8), 8); - v128_t b1 = wasm_i16x8_shr(b.val, 8); - return v_int32x4(v_add( - v_dotprod(v_int16x8(a0), v_int16x8(b0)), - v_dotprod(v_int16x8(a1), v_int16x8(b1)) - )); -} -inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) -{ - v128_t a0 = wasm_u32x4_shr(wasm_i32x4_shl(a.val, 16), 16); - v128_t a1 = wasm_u32x4_shr(a.val, 16); - v128_t b0 = wasm_u32x4_shr(wasm_i32x4_shl(b.val, 16), 16); - v128_t b1 = wasm_u32x4_shr(b.val, 16); - return v_uint64x2((v_add( - v_dotprod(v_int32x4(a0), v_int32x4(b0)), - v_dotprod(v_int32x4(a1), v_int32x4(b1))).val - )); -} -inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) -{ - v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); - v128_t a1 = wasm_i32x4_shr(a.val, 16); - v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); - v128_t b1 = wasm_i32x4_shr(b.val, 16); - return v_int64x2((v_add( - v_dotprod(v_int32x4(a0), v_int32x4(b0)), - v_dotprod(v_int32x4(a1), v_int32x4(b1))) - )); -} - -inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) -{ return v_cvt_f64(v_dotprod(a, b)); } -inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_add(v_dotprod_expand(a, b), c); } - -//////// Fast Dot Product //////// - -// 16 >> 32 -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod(a, b); } -inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) -{ return v_dotprod(a, b, c); } - -// 32 >> 64 -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod(a, b); } -inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) -{ return v_dotprod(a, b, c); } - -// 8 >> 32 -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) -{ return v_dotprod_expand(a, b); } -inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) -{ return v_dotprod_expand(a, b, c); } - -// 16 >> 64 -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) -{ return v_dotprod_expand(a, b, c); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) -{ return v_dotprod_expand(a, b); } -inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) -{ return v_dotprod_expand(a, b, c); } - -// 32 >> 64f -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) -{ return v_dotprod_expand(a, b); } -inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) -{ return v_dotprod_expand(a, b, c); } - -#define OPENCV_HAL_IMPL_WASM_LOGIC_OP(_Tpvec) \ -OPENCV_HAL_IMPL_WASM_BIN_OP(v_and, _Tpvec, wasm_v128_and) \ -OPENCV_HAL_IMPL_WASM_BIN_OP(v_or, _Tpvec, wasm_v128_or) \ -OPENCV_HAL_IMPL_WASM_BIN_OP(v_xor, _Tpvec, wasm_v128_xor) \ -inline _Tpvec v_not(const _Tpvec& a) \ -{ \ - return _Tpvec(wasm_v128_not(a.val)); \ -} - -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint8x16) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int8x16) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint16x8) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int16x8) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint32x4) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int32x4) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint64x2) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int64x2) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float32x4) -OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float64x2) - -inline v_float32x4 v_sqrt(const v_float32x4& x) -{ - return v_float32x4(wasm_f32x4_sqrt(x.val)); -} - -inline v_float32x4 v_invsqrt(const v_float32x4& x) -{ - const v128_t _1_0 = wasm_f32x4_splat(1.0); - return v_float32x4(wasm_f32x4_div(_1_0, wasm_f32x4_sqrt(x.val))); -} - -inline v_float64x2 v_sqrt(const v_float64x2& x) -{ - return v_float64x2(wasm_f64x2_sqrt(x.val)); -} - -inline v_float64x2 v_invsqrt(const v_float64x2& x) -{ - const v128_t _1_0 = wasm_f64x2_splat(1.0); - return v_float64x2(wasm_f64x2_div(_1_0, wasm_f64x2_sqrt(x.val))); -} - -#define OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(_Tpuvec, _Tpsvec, suffix, zsuffix, shiftWidth) \ -inline _Tpuvec v_abs(const _Tpsvec& x) \ -{ \ - v128_t s = wasm_##suffix##_shr(x.val, shiftWidth); \ - v128_t f = wasm_##zsuffix##_shr(x.val, shiftWidth); \ - return _Tpuvec(wasm_##zsuffix##_add(wasm_v128_xor(x.val, f), s)); \ -} - -OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint8x16, v_int8x16, u8x16, i8x16, 7) -OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint16x8, v_int16x8, u16x8, i16x8, 15) -OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint32x4, v_int32x4, u32x4, i32x4, 31) - -inline v_float32x4 v_abs(const v_float32x4& x) -{ return v_float32x4(wasm_f32x4_abs(x.val)); } -inline v_float64x2 v_abs(const v_float64x2& x) -{ - return v_float64x2(wasm_f64x2_abs(x.val)); -} - -// TODO: exp, log, sin, cos - -#define OPENCV_HAL_IMPL_WASM_BIN_FUNC(_Tpvec, func, intrin) \ -inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(intrin(a.val, b.val)); \ -} - -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_min, wasm_f32x4_min) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_max, wasm_f32x4_max) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_min, wasm_f64x2_min) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_max, wasm_f64x2_max) - -#define OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(_Tpvec, suffix) \ -inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_v128_bitselect(b.val, a.val, wasm_##suffix##_gt(a.val, b.val))); \ -} \ -inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_v128_bitselect(a.val, b.val, wasm_##suffix##_gt(a.val, b.val))); \ -} - -OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int8x16, i8x16) -OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int16x8, i16x8) -OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int32x4, i32x4) - -#define OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(_Tpvec, suffix, deltaNum) \ -inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t delta = wasm_##suffix##_splat(deltaNum); \ - v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ - return _Tpvec(wasm_v128_bitselect(b.val, a.val, mask)); \ -} \ -inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t delta = wasm_##suffix##_splat(deltaNum); \ - v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ - return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask)); \ -} - -OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint8x16, i8x16, (schar)0x80) -OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint16x8, i16x8, (short)0x8000) -OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint32x4, i32x4, (int)0x80000000) - -#define OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(_Tpvec, suffix, esuffix) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##esuffix##_eq(a.val, b.val)); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##esuffix##_ne(a.val, b.val)); } \ -inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_lt(a.val, b.val)); } \ -inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_gt(a.val, b.val)); } \ -inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_le(a.val, b.val)); } \ -inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ -{ return _Tpvec(wasm_##suffix##_ge(a.val, b.val)); } - -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint8x16, u8x16, i8x16) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int8x16, i8x16, i8x16) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint16x8, u16x8, i16x8) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int16x8, i16x8, i16x8) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint32x4, u32x4, i32x4) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int32x4, i32x4, i32x4) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float32x4, f32x4, f32x4) -OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float64x2, f64x2, f64x2) - -#define OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(_Tpvec, cast) \ -inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ -{ return cast(v_eq(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } \ -inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ -{ return cast(v_ne(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } - -OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_uint64x2, v_reinterpret_as_u64) -OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_int64x2, v_reinterpret_as_s64) - -inline v_float32x4 v_not_nan(const v_float32x4& a) -{ - v128_t z = wasm_i32x4_splat(0x7fffffff); - v128_t t = wasm_i32x4_splat(0x7f800000); - return v_float32x4(wasm_u32x4_lt(wasm_v128_and(a.val, z), t)); -} -inline v_float64x2 v_not_nan(const v_float64x2& a) -{ - v128_t z = wasm_i64x2_splat(0x7fffffffffffffff); - v128_t t = wasm_i64x2_splat(0x7ff0000000000000); - return v_float64x2((__u64x2)(wasm_v128_and(a.val, z)) < (__u64x2)t); -} - -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_add_wrap, wasm_i8x16_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_add_wrap, wasm_i8x16_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_add_wrap, wasm_i16x8_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_add_wrap, wasm_i16x8_add) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_sub_wrap, wasm_i8x16_sub) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_sub_wrap, wasm_i8x16_sub) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_sub_wrap, wasm_i16x8_sub) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_sub_wrap, wasm_i16x8_sub) -#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) >= (1039012) -// details: https://github.com/opencv/opencv/issues/18097 ( https://github.com/emscripten-core/emscripten/issues/12018 ) -// 1.39.12: https://github.com/emscripten-core/emscripten/commit/cd801d0f110facfd694212a3c8b2ed2ffcd630e2 -inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) -{ - uchar a_[16], b_[16]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - for (int i = 0; i < 16; i++) - a_[i] = (uchar)(a_[i] * b_[i]); - return v_uint8x16(wasm_v128_load(a_)); -} -inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) -{ - schar a_[16], b_[16]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - for (int i = 0; i < 16; i++) - a_[i] = (schar)(a_[i] * b_[i]); - return v_int8x16(wasm_v128_load(a_)); -} -#else -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_mul_wrap, wasm_i8x16_mul) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_mul_wrap, wasm_i8x16_mul) -#endif -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_mul_wrap, wasm_i16x8_mul) -OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_mul_wrap, wasm_i16x8_mul) - - -/** Absolute difference **/ - -inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) -{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } -inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - -inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub_wrap(a, b); - v_int8x16 m = v_lt(a, b); - return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); -} -inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) -{ - return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); -} -inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) -{ - v_int32x4 d = v_sub(a, b); - v_int32x4 m = v_lt(a, b); - return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); -} - -/** Saturating absolute difference **/ -inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) -{ - v_int8x16 d = v_sub(a, b); - v_int8x16 m = v_lt(a, b); - return v_sub(v_xor(d, m), m); - } -inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) -{ return v_sub(v_max(a, b), v_min(a, b)); } - - -inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) -{ - return v_fma(a, b, c); -} - -inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) -{ - return v_add(v_mul(a, b), c); -} - -inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) -{ - v128_t absmask_vec = wasm_i32x4_splat(0x7fffffff); - return v_float32x4(wasm_v128_and(wasm_f32x4_sub(a.val, b.val), absmask_vec)); -} -inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) -{ - v128_t absmask_vec = wasm_u64x2_shr(wasm_i32x4_splat(-1), 1); - return v_float64x2(wasm_v128_and(wasm_f64x2_sub(a.val, b.val), absmask_vec)); -} - -#define OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(_Tpvec, suffix) \ -inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ - v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ - return _Tpvec(wasm_##suffix##_sqrt(wasm_##suffix##_add(a_Square, b_Square))); \ -} \ -inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ -{ \ - v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ - v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ - return _Tpvec(wasm_##suffix##_add(a_Square, b_Square)); \ -} \ -inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ -{ \ - return _Tpvec(wasm_##suffix##_add(wasm_##suffix##_mul(a.val, b.val), c.val)); \ -} - -OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float32x4, f32x4) -OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float64x2, f64x2) - -#define OPENCV_HAL_IMPL_WASM_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, ssuffix) \ -inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ -{ \ - return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ -} \ -inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ -{ \ - return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shl(const _Tpuvec& a) \ -{ \ - return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shl(const _Tpsvec& a) \ -{ \ - return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ -} \ -template \ -inline _Tpuvec v_shr(const _Tpuvec& a) \ -{ \ - return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ -} \ -template \ -inline _Tpsvec v_shr(const _Tpsvec& a) \ -{ \ - return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ -} - -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint8x16, v_int8x16, i8x16, u8x16) -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint16x8, v_int16x8, i16x8, u16x8) -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint32x4, v_int32x4, i32x4, u32x4) -OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint64x2, v_int64x2, i64x2, u64x2) - -namespace hal_wasm_internal -{ - template 16)), - bool is_first = (imm == 0), - bool is_second = (imm == 16), - bool is_other = (((imm > 0) && (imm < 16)))> - class v_wasm_palignr_u8_class; - - template - class v_wasm_palignr_u8_class; - - template - class v_wasm_palignr_u8_class - { - public: - inline v128_t operator()(const v128_t& a, const v128_t&) const - { - return a; - } - }; - - template - class v_wasm_palignr_u8_class - { - public: - inline v128_t operator()(const v128_t&, const v128_t& b) const - { - return b; - } - }; - - template - class v_wasm_palignr_u8_class - { - public: - inline v128_t operator()(const v128_t& a, const v128_t& b) const - { - enum { imm2 = (sizeof(v128_t) - imm) }; - return wasm_i8x16_shuffle(a, b, - imm, imm+1, imm+2, imm+3, - imm+4, imm+5, imm+6, imm+7, - imm+8, imm+9, imm+10, imm+11, - imm+12, imm+13, imm+14, imm+15); - } - }; - - template - inline v128_t v_wasm_palignr_u8(const v128_t& a, const v128_t& b) - { - CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_wasm_palignr_u8."); - return v_wasm_palignr_u8_class()(a, b); - } -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a) -{ - using namespace hal_wasm_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - v128_t z = wasm_i8x16_splat(0); - return _Tpvec(v_wasm_palignr_u8(a.val, z)); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a) -{ - using namespace hal_wasm_internal; - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; - v128_t z = wasm_i8x16_splat(0); - return _Tpvec(v_wasm_palignr_u8(z, a.val)); -} - -template -inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_wasm_internal; - enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_wasm_palignr_u8(a.val, b.val)); -} - -template -inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) -{ - using namespace hal_wasm_internal; - enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; - return _Tpvec(v_wasm_palignr_u8(b.val, a.val)); -} - -#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(_Tpvec, _Tp) \ -inline _Tpvec v_load(const _Tp* ptr) \ -{ return _Tpvec(wasm_v128_load(ptr)); } \ -inline _Tpvec v_load_aligned(const _Tp* ptr) \ -{ return _Tpvec(wasm_v128_load(ptr)); } \ -inline _Tpvec v_load_low(const _Tp* ptr) \ -{ \ - _Tp tmp[_Tpvec::nlanes] = {0}; \ - for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ - tmp[i] = ptr[i]; \ - } \ - return _Tpvec(wasm_v128_load(tmp)); \ -} \ -inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ -{ \ - _Tp tmp[_Tpvec::nlanes]; \ - for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ - tmp[i] = ptr0[i]; \ - tmp[i+_Tpvec::nlanes/2] = ptr1[i]; \ - } \ - return _Tpvec(wasm_v128_load(tmp)); \ -} \ -inline void v_store(_Tp* ptr, const _Tpvec& a) \ -{ wasm_v128_store(ptr, a.val); } \ -inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ -{ wasm_v128_store(ptr, a.val); } \ -inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ -{ wasm_v128_store(ptr, a.val); } \ -inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ -{ \ - wasm_v128_store(ptr, a.val); \ -} \ -inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ - ptr[i] = a_[i]; \ -} \ -inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ - ptr[i] = a_[i + (_Tpvec::nlanes / 2)]; \ -} - -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint8x16, uchar) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int8x16, schar) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint16x8, ushort) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int16x8, short) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint32x4, unsigned) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int32x4, int) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint64x2, uint64) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int64x2, int64) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float32x4, float) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float64x2, double) - - -/** Reverse **/ -inline v_uint8x16 v_reverse(const v_uint8x16 &a) -{ return v_uint8x16(wasm_i8x16_shuffle(a.val, a.val, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)); } - -inline v_int8x16 v_reverse(const v_int8x16 &a) -{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } - -inline v_uint16x8 v_reverse(const v_uint16x8 &a) -{ return v_uint16x8(wasm_i8x16_shuffle(a.val, a.val, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1)); } - -inline v_int16x8 v_reverse(const v_int16x8 &a) -{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } - -inline v_uint32x4 v_reverse(const v_uint32x4 &a) -{ return v_uint32x4(wasm_i8x16_shuffle(a.val, a.val, 12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3)); } - -inline v_int32x4 v_reverse(const v_int32x4 &a) -{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_float32x4 v_reverse(const v_float32x4 &a) -{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } - -inline v_uint64x2 v_reverse(const v_uint64x2 &a) -{ return v_uint64x2(wasm_i8x16_shuffle(a.val, a.val, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7)); } - -inline v_int64x2 v_reverse(const v_int64x2 &a) -{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } - -inline v_float64x2 v_reverse(const v_float64x2 &a) -{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } - - -#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - regtype val = a.val; \ - val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ - val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3)); \ - return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ -} - -OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_uint32x4, unsigned, v128_t, i32x4, i32x4) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_int32x4, int, v128_t, i32x4, i32x4) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_float32x4, float, v128_t, f32x4, f32x4) - -// To do: Optimize v_reduce_sum with wasm intrin. -// Now use fallback implementation as there is no widening op in wasm intrin. - -#define OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(_Tpvec, scalartype) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - scalartype c = a_[0]; \ - for (int i = 1; i < _Tpvec::nlanes; i++) \ - c += a_[i]; \ - return c; \ -} - -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint8x16, unsigned) -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int8x16, int) -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint16x8, unsigned) -OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int16x8, int) - - -#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ -inline scalartype v_reduce_sum(const _Tpvec& a) \ -{ \ - regtype val = a.val; \ - val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ - return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ -} -OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_uint64x2, uint64, v128_t, i64x2, i64x2) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_int64x2, int64, v128_t, i64x2, i64x2) -OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_float64x2, double, v128_t, f64x2,f64x2) - -inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d) -{ - v128_t ac = wasm_f32x4_add(wasm_unpacklo_i32x4(a.val, c.val), wasm_unpackhi_i32x4(a.val, c.val)); - v128_t bd = wasm_f32x4_add(wasm_unpacklo_i32x4(b.val, d.val), wasm_unpackhi_i32x4(b.val, d.val)); - return v_float32x4(wasm_f32x4_add(wasm_unpacklo_i32x4(ac, bd), wasm_unpackhi_i32x4(ac, bd))); -} - -#define OPENCV_HAL_IMPL_WASM_REDUCE_OP(_Tpvec, scalartype, func, scalar_func) \ -inline scalartype v_reduce_##func(const _Tpvec& a) \ -{ \ - scalartype buf[_Tpvec::nlanes]; \ - v_store(buf, a); \ - scalartype tmp = buf[0]; \ - for (int i=1; i<_Tpvec::nlanes; ++i) { \ - tmp = scalar_func(tmp, buf[i]); \ - } \ - return tmp; \ -} - -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, min, std::min) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, max, std::max) -OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, min, std::min) - -inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) -{ - v_uint16x8 l16, h16; - v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; - v_expand(v_absdiff(a, b), l16, h16); - v_expand(l16, l16_l32, l16_h32); - v_expand(h16, h16_l32, h16_h32); - return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); -} -inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) -{ - v_uint16x8 l16, h16; - v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; - v_expand(v_absdiff(a, b), l16, h16); - v_expand(l16, l16_l32, l16_h32); - v_expand(h16, h16_l32, h16_h32); - return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); -} -inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) -{ - v_uint32x4 l, h; - v_expand(v_absdiff(a, b), l, h); - return v_reduce_sum(v_add(l, h)); -} -inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} -inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) -{ - return v_reduce_sum(v_absdiff(a, b)); -} - -inline v_uint8x16 v_popcount(const v_uint8x16& a) -{ - v128_t m1 = wasm_i32x4_splat(0x55555555); - v128_t m2 = wasm_i32x4_splat(0x33333333); - v128_t m4 = wasm_i32x4_splat(0x0f0f0f0f); - v128_t p = a.val; - p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 1), m1), wasm_v128_and(p, m1)); - p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 2), m2), wasm_v128_and(p, m2)); - p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 4), m4), wasm_v128_and(p, m4)); - return v_uint8x16(p); -} -inline v_uint16x8 v_popcount(const v_uint16x8& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); -} -inline v_uint32x4 v_popcount(const v_uint32x4& a) -{ - v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); - p = v_add(p, v_rotate_right<1>(p)); - p = v_add(p, v_rotate_right<2>(p)); - return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); -} -inline v_uint64x2 v_popcount(const v_uint64x2& a) -{ - uint64 a_[2], b_[2] = { 0 }; - wasm_v128_store(a_, a.val); - for (int i = 0; i < 16; i++) - b_[i / 8] += popCountTable[((uint8_t*)a_)[i]]; - return v_uint64x2(wasm_v128_load(b_)); -} -inline v_uint8x16 v_popcount(const v_int8x16& a) -{ return v_popcount(v_reinterpret_as_u8(a)); } -inline v_uint16x8 v_popcount(const v_int16x8& a) -{ return v_popcount(v_reinterpret_as_u16(a)); } -inline v_uint32x4 v_popcount(const v_int32x4& a) -{ return v_popcount(v_reinterpret_as_u32(a)); } -inline v_uint64x2 v_popcount(const v_int64x2& a) -{ return v_popcount(v_reinterpret_as_u64(a)); } - -#define OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(_Tpvec, suffix, scalarType) \ -inline int v_signmask(const _Tpvec& a) \ -{ \ - _Tpvec::lane_type a_[_Tpvec::nlanes]; \ - wasm_v128_store(a_, a.val); \ - int mask = 0; \ - for (int i = 0; i < _Tpvec::nlanes; i++) \ - mask |= (reinterpret_int(a_[i]) < 0) << i; \ - return mask; \ -} \ -inline bool v_check_all(const _Tpvec& a) \ -{ return wasm_i8x16_all_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0))); } \ -inline bool v_check_any(const _Tpvec& a) \ -{ return wasm_i8x16_any_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0)));; } - -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint8x16, i8x16, schar) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int8x16, i8x16, schar) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint16x8, i16x8, short) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int16x8, i16x8, short) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint32x4, i32x4, int) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int32x4, i32x4, int) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float32x4, i32x4, float) -OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float64x2, f64x2, double) - -#define OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(_Tpvec, suffix, esuffix) \ -inline bool v_check_all(const _Tpvec& a) \ -{ \ - v128_t masked = v_reinterpret_as_##esuffix(a).val; \ - masked = wasm_i32x4_replace_lane(masked, 0, 0xffffffff); \ - masked = wasm_i32x4_replace_lane(masked, 2, 0xffffffff); \ - return wasm_i8x16_all_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ -} \ -inline bool v_check_any(const _Tpvec& a) \ -{ \ - v128_t masked = v_reinterpret_as_##esuffix(a).val; \ - masked = wasm_i32x4_replace_lane(masked, 0, 0x0); \ - masked = wasm_i32x4_replace_lane(masked, 2, 0x0); \ - return wasm_i8x16_any_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ -} \ - -OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_int64x2, i32x4, s32) -OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_uint64x2, i32x4, u32) - - -inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } -inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } -inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } -inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } -inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } - -#define OPENCV_HAL_IMPL_WASM_SELECT(_Tpvec) \ -inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask.val)); \ -} - -OPENCV_HAL_IMPL_WASM_SELECT(v_uint8x16) -OPENCV_HAL_IMPL_WASM_SELECT(v_int8x16) -OPENCV_HAL_IMPL_WASM_SELECT(v_uint16x8) -OPENCV_HAL_IMPL_WASM_SELECT(v_int16x8) -OPENCV_HAL_IMPL_WASM_SELECT(v_uint32x4) -OPENCV_HAL_IMPL_WASM_SELECT(v_int32x4) -OPENCV_HAL_IMPL_WASM_SELECT(v_uint64x2) -OPENCV_HAL_IMPL_WASM_SELECT(v_int64x2) -OPENCV_HAL_IMPL_WASM_SELECT(v_float32x4) -OPENCV_HAL_IMPL_WASM_SELECT(v_float64x2) - -#define OPENCV_HAL_IMPL_WASM_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ -inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ -{ \ - b0.val = intrin(a.val); \ - b1.val = __CV_CAT(intrin, _high)(a.val); \ -} \ -inline _Tpwvec v_expand_low(const _Tpvec& a) \ -{ return _Tpwvec(intrin(a.val)); } \ -inline _Tpwvec v_expand_high(const _Tpvec& a) \ -{ return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ -inline _Tpwvec v_load_expand(const _Tp* ptr) \ -{ \ - v128_t a = wasm_v128_load(ptr); \ - return _Tpwvec(intrin(a)); \ -} - -OPENCV_HAL_IMPL_WASM_EXPAND(v_uint8x16, v_uint16x8, uchar, v128_cvtu8x16_i16x8) -OPENCV_HAL_IMPL_WASM_EXPAND(v_int8x16, v_int16x8, schar, v128_cvti8x16_i16x8) -OPENCV_HAL_IMPL_WASM_EXPAND(v_uint16x8, v_uint32x4, ushort, v128_cvtu16x8_i32x4) -OPENCV_HAL_IMPL_WASM_EXPAND(v_int16x8, v_int32x4, short, v128_cvti16x8_i32x4) -OPENCV_HAL_IMPL_WASM_EXPAND(v_uint32x4, v_uint64x2, unsigned, v128_cvtu32x4_i64x2) -OPENCV_HAL_IMPL_WASM_EXPAND(v_int32x4, v_int64x2, int, v128_cvti32x4_i64x2) - -#define OPENCV_HAL_IMPL_WASM_EXPAND_Q(_Tpvec, _Tp, intrin) \ -inline _Tpvec v_load_expand_q(const _Tp* ptr) \ -{ \ - v128_t a = wasm_v128_load(ptr); \ - return _Tpvec(intrin(a)); \ -} - -OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_uint32x4, uchar, v128_cvtu8x16_i32x4) -OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_int32x4, schar, v128_cvti8x16_i32x4) - -#define OPENCV_HAL_IMPL_WASM_UNPACKS(_Tpvec, suffix) \ -inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ -{ \ - b0.val = wasm_unpacklo_##suffix(a0.val, a1.val); \ - b1.val = wasm_unpackhi_##suffix(a0.val, a1.val); \ -} \ -inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_unpacklo_i64x2(a.val, b.val)); \ -} \ -inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ -{ \ - return _Tpvec(wasm_unpackhi_i64x2(a.val, b.val)); \ -} \ -inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ -{ \ - c.val = wasm_unpacklo_i64x2(a.val, b.val); \ - d.val = wasm_unpackhi_i64x2(a.val, b.val); \ -} - -OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint8x16, i8x16) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_int8x16, i8x16) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint16x8, i16x8) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_int16x8, i16x8) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint32x4, i32x4) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_int32x4, i32x4) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_float32x4, i32x4) -OPENCV_HAL_IMPL_WASM_UNPACKS(v_float64x2, i64x2) - -template -inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) -{ - return v_rotate_right(a, b); -} - -inline v_int32x4 v_round(const v_float32x4& a) -{ - v128_t h = wasm_f32x4_splat(0.5); - return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(wasm_f32x4_add(a.val, h))); -} - -inline v_int32x4 v_floor(const v_float32x4& a) -{ - v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); - v128_t mask = wasm_f32x4_lt(a.val, wasm_f32x4_convert_i32x4(a1)); - return v_int32x4(wasm_i32x4_add(a1, mask)); -} - -inline v_int32x4 v_ceil(const v_float32x4& a) -{ - v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); - v128_t mask = wasm_f32x4_gt(a.val, wasm_f32x4_convert_i32x4(a1)); - return v_int32x4(wasm_i32x4_sub(a1, mask)); -} - -inline v_int32x4 v_trunc(const v_float32x4& a) -{ return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(a.val)); } - -#define OPENCV_HAL_IMPL_WASM_MATH_FUNC(func, cfunc) \ -inline v_int32x4 func(const v_float64x2& a) \ -{ \ - double a_[2]; \ - wasm_v128_store(a_, a.val); \ - int c_[4]; \ - c_[0] = cfunc(a_[0]); \ - c_[1] = cfunc(a_[1]); \ - c_[2] = 0; \ - c_[3] = 0; \ - return v_int32x4(wasm_v128_load(c_)); \ -} - -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_round, cvRound) -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_floor, cvFloor) -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_ceil, cvCeil) -OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_trunc, int) - -inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) -{ - double a_[2], b_[2]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - int c_[4]; - c_[0] = cvRound(a_[0]); - c_[1] = cvRound(a_[1]); - c_[2] = cvRound(b_[0]); - c_[3] = cvRound(b_[1]); - return v_int32x4(wasm_v128_load(c_)); -} - -#define OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(_Tpvec, suffix) \ -inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ - const _Tpvec& a2, const _Tpvec& a3, \ - _Tpvec& b0, _Tpvec& b1, \ - _Tpvec& b2, _Tpvec& b3) \ -{ \ - v128_t t0 = wasm_unpacklo_##suffix(a0.val, a1.val); \ - v128_t t1 = wasm_unpacklo_##suffix(a2.val, a3.val); \ - v128_t t2 = wasm_unpackhi_##suffix(a0.val, a1.val); \ - v128_t t3 = wasm_unpackhi_##suffix(a2.val, a3.val); \ -\ - b0.val = wasm_unpacklo_i64x2(t0, t1); \ - b1.val = wasm_unpackhi_i64x2(t0, t1); \ - b2.val = wasm_unpacklo_i64x2(t2, t3); \ - b3.val = wasm_unpackhi_i64x2(t2, t3); \ -} - -OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_uint32x4, i32x4) -OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_int32x4, i32x4) -OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_float32x4, i32x4) - -// load deinterleave -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) -{ - v128_t t00 = wasm_v128_load(ptr); - v128_t t01 = wasm_v128_load(ptr + 16); - - a.val = wasm_i8x16_shuffle(t00, t01, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30); - b.val = wasm_i8x16_shuffle(t00, t01, 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) -{ - v128_t t00 = wasm_v128_load(ptr); - v128_t t01 = wasm_v128_load(ptr + 16); - v128_t t02 = wasm_v128_load(ptr + 32); - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,3,6,9,12,15,18,21,24,27,30,1,2,4,5,7); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 1,4,7,10,13,16,19,22,25,28,31,0,2,3,5,6); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 2,5,8,11,14,17,20,23,26,29,0,1,3,4,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,17,20,23,26,29); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,18,21,24,27,30); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,16,19,22,25,28,31); -} - -inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) -{ - v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... - v128_t u1 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... - v128_t u2 = wasm_v128_load(ptr + 32); // a8 b8 c8 d8 ... - v128_t u3 = wasm_v128_load(ptr + 48); // a12 b12 c12 d12 ... - - v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); - v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); - v128_t v2 = wasm_i8x16_shuffle(u0, u1, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); - v128_t v3 = wasm_i8x16_shuffle(u2, u3, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); - c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) -{ - v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 a2 b2 a3 b3 - v128_t v1 = wasm_v128_load(ptr + 8); // a4 b4 a5 b5 a6 b6 a7 b7 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29); // a0 a1 a2 a3 a4 a5 a6 a7 - b.val = wasm_i8x16_shuffle(v0, v1, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31); // b0 b1 ab b3 b4 b5 b6 b7 -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) -{ - v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 b1 c1 a2 b2 - v128_t t01 = wasm_v128_load(ptr + 8); // c2 a3 b3 c3 a4 b4 c4 a5 - v128_t t02 = wasm_v128_load(ptr + 16); // b5 c5 a6 b6 c6 a7 b7 c7 - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,6,7,12,13,18,19,24,25,30,31,2,3,4,5); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 2,3,8,9,14,15,20,21,26,27,0,1,4,5,6,7); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 4,5,10,11,16,17,22,23,28,29,0,1,2,3,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,26,27); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,16,17,22,23,28,29); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,18,19,24,25,30,31); -} - -inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) -{ - v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 - v128_t u1 = wasm_v128_load(ptr + 8); // a2 b2 c2 d2 ... - v128_t u2 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... - v128_t u3 = wasm_v128_load(ptr + 24); // a6 b6 c6 d6 ... - - v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a0 a1 a2 a3 b0 b1 b2 b3 - v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a4 a5 a6 a7 b4 b5 b6 b7 - v128_t v2 = wasm_i8x16_shuffle(u0, u1, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c0 c1 c2 c3 d0 d1 d2 d3 - v128_t v3 = wasm_i8x16_shuffle(u2, u3, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c4 c5 c6 c7 d4 d5 d6 d7 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); - c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) -{ - v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 - v128_t v1 = wasm_v128_load(ptr + 4); // a2 b2 a3 b3 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 - b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) -{ - v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 - v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 - v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); -} - -inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) -{ - v_uint32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 - v_uint32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 - v_uint32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 - v_uint32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 - - v_transpose4x4(s0, s1, s2, s3, a, b, c, d); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) -{ - v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 - v128_t v1 = wasm_v128_load((ptr + 4)); // a2 b2 a3 b3 - - a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 - b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) -{ - v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 - v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 - v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 - - v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); - v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); - v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); - - a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); - b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); - c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); -} - -inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) -{ - v_float32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 - v_float32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 - v_float32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 - v_float32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 - - v_transpose4x4(s0, s1, s2, s3, a, b, c, d); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) -{ - v128_t t0 = wasm_v128_load(ptr); // a0 b0 - v128_t t1 = wasm_v128_load(ptr + 2); // a1 b1 - - a.val = wasm_unpacklo_i64x2(t0, t1); - b.val = wasm_unpackhi_i64x2(t0, t1); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) -{ - v128_t t0 = wasm_v128_load(ptr); // a0, b0 - v128_t t1 = wasm_v128_load(ptr + 2); // c0, a1 - v128_t t2 = wasm_v128_load(ptr + 4); // b1, c1 - - a.val = wasm_i8x16_shuffle(t0, t1, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); - b.val = wasm_i8x16_shuffle(t0, t2, 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23); - c.val = wasm_i8x16_shuffle(t1, t2, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); -} - -inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, - v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) -{ - v128_t t0 = wasm_v128_load(ptr); // a0 b0 - v128_t t1 = wasm_v128_load(ptr + 2); // c0 d0 - v128_t t2 = wasm_v128_load(ptr + 4); // a1 b1 - v128_t t3 = wasm_v128_load(ptr + 6); // c1 d1 - - a.val = wasm_unpacklo_i64x2(t0, t2); - b.val = wasm_unpackhi_i64x2(t0, t2); - c.val = wasm_unpacklo_i64x2(t1, t3); - d.val = wasm_unpackhi_i64x2(t1, t3); -} - -// store interleave - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i8x16(a.val, b.val); - v128_t v1 = wasm_unpackhi_i8x16(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 16, v1); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,16,0,1,17,0,2,18,0,3,19,0,4,20,0,5); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 21,0,6,22,0,7,23,0,8,24,0,9,25,0,10,26); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,11,27,0,12,28,0,13,29,0,14,30,0,15,31,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,16,3,4,17,6,7,18,9,10,19,12,13,20,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,21,2,3,22,5,6,23,8,9,24,11,12,25,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 26,1,2,27,4,5,28,7,8,29,10,11,30,13,14,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 16, t11); - wasm_v128_store(ptr + 32, t12); -} - -inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, - const v_uint8x16& c, const v_uint8x16& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - v128_t u0 = wasm_unpacklo_i8x16(a.val, c.val); // a0 c0 a1 c1 ... - v128_t u1 = wasm_unpackhi_i8x16(a.val, c.val); // a8 c8 a9 c9 ... - v128_t u2 = wasm_unpacklo_i8x16(b.val, d.val); // b0 d0 b1 d1 ... - v128_t u3 = wasm_unpackhi_i8x16(b.val, d.val); // b8 d8 b9 d9 ... - - v128_t v0 = wasm_unpacklo_i8x16(u0, u2); // a0 b0 c0 d0 ... - v128_t v1 = wasm_unpackhi_i8x16(u0, u2); // a4 b4 c4 d4 ... - v128_t v2 = wasm_unpacklo_i8x16(u1, u3); // a8 b8 c8 d8 ... - v128_t v3 = wasm_unpackhi_i8x16(u1, u3); // a12 b12 c12 d12 ... - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 16, v1); - wasm_v128_store(ptr + 32, v2); - wasm_v128_store(ptr + 48, v3); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i16x8(a.val, b.val); - v128_t v1 = wasm_unpackhi_i16x8(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 8, v1); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, - const v_uint16x8& b, const v_uint16x8& c, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,16,17,0,0,2,3,18,19,0,0,4,5,20,21); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 0,0,6,7,22,23,0,0,8,9,24,25,0,0,10,11); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 26,27,0,0,12,13,28,29,0,0,14,15,30,31,0,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,16,17,6,7,8,9,18,19,12,13,14,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 20,21,2,3,4,5,22,23,8,9,10,11,24,25,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 0,1,26,27,4,5,6,7,28,29,10,11,12,13,30,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 8, t11); - wasm_v128_store(ptr + 16, t12); -} - -inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, - const v_uint16x8& c, const v_uint16x8& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - // a0 a1 a2 a3 .... - // b0 b1 b2 b3 .... - // c0 c1 c2 c3 .... - // d0 d1 d2 d3 .... - v128_t u0 = wasm_unpacklo_i16x8(a.val, c.val); // a0 c0 a1 c1 ... - v128_t u1 = wasm_unpackhi_i16x8(a.val, c.val); // a4 c4 a5 c5 ... - v128_t u2 = wasm_unpacklo_i16x8(b.val, d.val); // b0 d0 b1 d1 ... - v128_t u3 = wasm_unpackhi_i16x8(b.val, d.val); // b4 d4 b5 d5 ... - - v128_t v0 = wasm_unpacklo_i16x8(u0, u2); // a0 b0 c0 d0 ... - v128_t v1 = wasm_unpackhi_i16x8(u0, u2); // a2 b2 c2 d2 ... - v128_t v2 = wasm_unpacklo_i16x8(u1, u3); // a4 b4 c4 d4 ... - v128_t v3 = wasm_unpackhi_i16x8(u1, u3); // a6 b6 c6 d6 ... - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 8, v1); - wasm_v128_store(ptr + 16, v2); - wasm_v128_store(ptr + 24, v3); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); - v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 4, v1); -} - -inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 4, t11); - wasm_v128_store(ptr + 8, t12); -} - -inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, - const v_uint32x4& c, const v_uint32x4& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v_uint32x4 v0, v1, v2, v3; - v_transpose4x4(a, b, c, d, v0, v1, v2, v3); - - wasm_v128_store(ptr, v0.val); - wasm_v128_store(ptr + 4, v1.val); - wasm_v128_store(ptr + 8, v2.val); - wasm_v128_store(ptr + 12, v3.val); -} - -// 2-channel, float only -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); - v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 4, v1); -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); - v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); - v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); - - v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); - v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); - v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); - - wasm_v128_store(ptr, t10); - wasm_v128_store(ptr + 4, t11); - wasm_v128_store(ptr + 8, t12); -} - -inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, - const v_float32x4& c, const v_float32x4& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v_float32x4 v0, v1, v2, v3; - v_transpose4x4(a, b, c, d, v0, v1, v2, v3); - - wasm_v128_store(ptr, v0.val); - wasm_v128_store(ptr + 4, v1.val); - wasm_v128_store(ptr + 8, v2.val); - wasm_v128_store(ptr + 12, v3.val); -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); - v128_t v1 = wasm_unpackhi_i64x2(a.val, b.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 2, v1); -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); - v128_t v1 = wasm_i8x16_shuffle(a.val, c.val, 16,17,18,19,20,21,22,23,8,9,10,11,12,13,14,15); - v128_t v2 = wasm_i8x16_shuffle(b.val, c.val, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 2, v1); - wasm_v128_store(ptr + 4, v2); -} - -inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, - const v_uint64x2& c, const v_uint64x2& d, - hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) -{ - v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); - v128_t v1 = wasm_unpacklo_i64x2(c.val, d.val); - v128_t v2 = wasm_unpackhi_i64x2(a.val, b.val); - v128_t v3 = wasm_unpackhi_i64x2(c.val, d.val); - - wasm_v128_store(ptr, v0); - wasm_v128_store(ptr + 2, v1); - wasm_v128_store(ptr + 4, v2); - wasm_v128_store(ptr + 6, v3); -} - -#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ -{ \ - _Tpvec1 a1, b1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ -{ \ - _Tpvec1 a1, b1, c1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ -} \ -inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ -{ \ - _Tpvec1 a1, b1, c1, d1; \ - v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ - a0 = v_reinterpret_as_##suffix0(a1); \ - b0 = v_reinterpret_as_##suffix0(b1); \ - c0 = v_reinterpret_as_##suffix0(c1); \ - d0 = v_reinterpret_as_##suffix0(d1); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ -} \ -inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ - const _Tpvec0& c0, const _Tpvec0& d0, \ - hal::StoreMode mode = hal::STORE_UNALIGNED ) \ -{ \ - _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ - _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ - _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ - _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ - v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ -} - -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) -OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) - -inline v_float32x4 v_cvt_f32(const v_int32x4& a) -{ - return v_float32x4(wasm_f32x4_convert_i32x4(a.val)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a) -{ - double a_[2]; - wasm_v128_store(a_, a.val); - float c_[4]; - c_[0] = (float)(a_[0]); - c_[1] = (float)(a_[1]); - c_[2] = 0; - c_[3] = 0; - return v_float32x4(wasm_v128_load(c_)); -} - -inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) -{ - double a_[2], b_[2]; - wasm_v128_store(a_, a.val); - wasm_v128_store(b_, b.val); - float c_[4]; - c_[0] = (float)(a_[0]); - c_[1] = (float)(a_[1]); - c_[2] = (float)(b_[0]); - c_[3] = (float)(b_[1]); - return v_float32x4(wasm_v128_load(c_)); -} - -inline v_float64x2 v_cvt_f64(const v_int32x4& a) -{ -#ifdef __wasm_unimplemented_simd128__ - v128_t p = v128_cvti32x4_i64x2(a.val); - return v_float64x2(wasm_f64x2_convert_i64x2(p)); -#else - int a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[0]); - c_[1] = (double)(a_[1]); - return v_float64x2(wasm_v128_load(c_)); -#endif -} - -inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) -{ -#ifdef __wasm_unimplemented_simd128__ - v128_t p = v128_cvti32x4_i64x2_high(a.val); - return v_float64x2(wasm_f64x2_convert_i64x2(p)); -#else - int a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[2]); - c_[1] = (double)(a_[3]); - return v_float64x2(wasm_v128_load(c_)); -#endif -} - -inline v_float64x2 v_cvt_f64(const v_float32x4& a) -{ - float a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[0]); - c_[1] = (double)(a_[1]); - return v_float64x2(wasm_v128_load(c_)); -} - -inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) -{ - float a_[4]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[2]); - c_[1] = (double)(a_[3]); - return v_float64x2(wasm_v128_load(c_)); -} - -inline v_float64x2 v_cvt_f64(const v_int64x2& a) -{ -#ifdef __wasm_unimplemented_simd128__ - return v_float64x2(wasm_f64x2_convert_i64x2(a.val)); -#else - int64 a_[2]; - wasm_v128_store(a_, a.val); - double c_[2]; - c_[0] = (double)(a_[0]); - c_[1] = (double)(a_[1]); - return v_float64x2(wasm_v128_load(c_)); -#endif -} - -////////////// Lookup table access //////////////////// - -inline v_int8x16 v_lut(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], - tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); -} -inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1], - tab[idx[4]], tab[idx[4]+1], tab[idx[5]], tab[idx[5]+1], tab[idx[6]], tab[idx[6]+1], tab[idx[7]], tab[idx[7]+1]); -} -inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) -{ - return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3], - tab[idx[2]], tab[idx[2]+1], tab[idx[2]+2], tab[idx[2]+3], tab[idx[3]], tab[idx[3]+1], tab[idx[3]+2], tab[idx[3]+3]); -} -inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } -inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } - -inline v_int16x8 v_lut(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], - tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); -} -inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], - tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1]); -} -inline v_int16x8 v_lut_quads(const short* tab, const int* idx) -{ - return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], - tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3]); -} -inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } -inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } -inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } - -inline v_int32x4 v_lut(const int* tab, const int* idx) -{ - return v_int32x4(tab[idx[0]], tab[idx[1]], - tab[idx[2]], tab[idx[3]]); -} -inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) -{ - return v_int32x4(tab[idx[0]], tab[idx[0]+1], - tab[idx[1]], tab[idx[1]+1]); -} -inline v_int32x4 v_lut_quads(const int* tab, const int* idx) -{ - return v_int32x4(wasm_v128_load(tab + idx[0])); -} -inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } -inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } -inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } - -inline v_int64x2 v_lut(const int64_t* tab, const int* idx) -{ - return v_int64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) -{ - return v_int64x2(wasm_v128_load(tab + idx[0])); -} -inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } -inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } - -inline v_float32x4 v_lut(const float* tab, const int* idx) -{ - return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); -} -inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } -inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } - -inline v_float64x2 v_lut(const double* tab, const int* idx) -{ - return v_float64x2(tab[idx[0]], tab[idx[1]]); -} -inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) -{ - return v_float64x2(wasm_v128_load(tab + idx[0])); -} - -inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) -{ - return v_int32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); -} - -inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) -{ - return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); -} - -inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) -{ - return v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); -} - -inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) -{ - return v_float64x2(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)]); -} - -// loads pairs from the table and deinterleaves them, e.g. returns: -// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), -// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) -// note that the indices are float's indices, not the float-pair indices. -// in theory, this function can be used to implement bilinear interpolation, -// when idxvec are the offsets within the image. -inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) -{ - x = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); - y = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)+1], - tab[wasm_i32x4_extract_lane(idxvec.val, 1)+1], - tab[wasm_i32x4_extract_lane(idxvec.val, 2)+1], - tab[wasm_i32x4_extract_lane(idxvec.val, 3)+1]); -} - -inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) -{ - v128_t xy0 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 0)); - v128_t xy1 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 1)); - x.val = wasm_unpacklo_i64x2(xy0, xy1); - y.val = wasm_unpacklo_i64x2(xy0, xy1); -} - -inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) -{ - return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15)); -} -inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } -inline v_int8x16 v_interleave_quads(const v_int8x16& vec) -{ - return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,4,1,5,2,6,3,7,8,12,9,13,10,14,11,15)); -} -inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) -{ - return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,4,5,2,3,6,7,8,9,12,13,10,11,14,15)); -} -inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } -inline v_int16x8 v_interleave_quads(const v_int16x8& vec) -{ - return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,8,9,2,3,10,11,4,5,12,13,6,7,14,15)); -} -inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) -{ - return v_int32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); -} -inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } -inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) -{ - return v_float32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); -} - -inline v_int8x16 v_pack_triplets(const v_int8x16& vec) -{ - return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,4,5,6,8,9,10,12,13,14,16,16,16,16)); -} -inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } - -inline v_int16x8 v_pack_triplets(const v_int16x8& vec) -{ - return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,4,5,8,9,10,11,12,13,14,15,6,7)); -} -inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } - -inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } -inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } -inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } - -template -inline typename _Tp::lane_type v_extract_n(const _Tp& a) -{ - return v_rotate_right(a).get0(); -} - -template -inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) -{ - return v_setall_u32(v_extract_n(a)); -} -template -inline v_int32x4 v_broadcast_element(const v_int32x4& a) -{ - return v_setall_s32(v_extract_n(a)); -} -template -inline v_float32x4 v_broadcast_element(const v_float32x4& a) -{ - return v_setall_f32(v_extract_n(a)); -} - - -////////////// FP16 support /////////////////////////// - -inline v_float32x4 v_load_expand(const hfloat* ptr) -{ - float a[4]; - for (int i = 0; i < 4; i++) - a[i] = ptr[i]; - return v_float32x4(wasm_v128_load(a)); -} - -inline void v_pack_store(hfloat* ptr, const v_float32x4& v) -{ - double v_[4]; - wasm_v128_store(v_, v.val); - ptr[0] = hfloat(v_[0]); - ptr[1] = hfloat(v_[1]); - ptr[2] = hfloat(v_[2]); - ptr[3] = hfloat(v_[3]); -} - -inline void v_cleanup() {} - -#include "intrin_math.hpp" -inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } -inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } -inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } -inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } -inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } -inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } - -inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } -inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } -inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } -inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } -inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } - -CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END - -//! @endcond - -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_HAL_INTRIN_WASM_HPP +#define OPENCV_HAL_INTRIN_WASM_HPP + +#include +#include +#include +#include "opencv2/core/saturate.hpp" + + +// Emscripten v2.0.13 (latest officially supported, as of 07/30/2024): +// __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__ and __EMSCRIPTEN_tiny__ are defined via commandline in +// https://github.com/emscripten-core/emscripten/blob/1690a5802cd1241adc9714fb7fa2f633d38860dc/tools/shared.py#L506-L515 +// +// See https://github.com/opencv/opencv/pull/25909 +#ifndef __EMSCRIPTEN_major__ +#include +#endif + +#define CV_SIMD128 1 +#define CV_SIMD128_64F 0 // Now all implementation of f64 use fallback, so disable it. +#define CV_SIMD128_FP16 0 + +namespace cv +{ + +//! @cond IGNORED + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_BEGIN + +#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) < (1038046) +// handle renames: https://github.com/emscripten-core/emscripten/pull/9440 (https://github.com/emscripten-core/emscripten/commit/755d5b46cb84d0aa120c10981b11d05646c29673) +#define wasm_i32x4_trunc_saturate_f32x4 wasm_trunc_saturate_i32x4_f32x4 +#define wasm_u32x4_trunc_saturate_f32x4 wasm_trunc_saturate_u32x4_f32x4 +#define wasm_i64x2_trunc_saturate_f64x2 wasm_trunc_saturate_i64x2_f64x2 +#define wasm_u64x2_trunc_saturate_f64x2 wasm_trunc_saturate_u64x2_f64x2 +#define wasm_f32x4_convert_i32x4 wasm_convert_f32x4_i32x4 +#define wasm_f32x4_convert_u32x4 wasm_convert_f32x4_u32x4 +#define wasm_f64x2_convert_i64x2 wasm_convert_f64x2_i64x2 +#define wasm_f64x2_convert_u64x2 wasm_convert_f64x2_u64x2 +#endif // COMPATIBILITY: <1.38.46 + +///////// Types /////////// + +struct v_uint8x16 +{ + typedef uchar lane_type; + typedef v128_t vector_type; + enum { nlanes = 16 }; + + v_uint8x16() {} + explicit v_uint8x16(v128_t v) : val(v) {} + v_uint8x16(uchar v0, uchar v1, uchar v2, uchar v3, uchar v4, uchar v5, uchar v6, uchar v7, + uchar v8, uchar v9, uchar v10, uchar v11, uchar v12, uchar v13, uchar v14, uchar v15) + { + uchar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = wasm_v128_load(v); + } + + uchar get0() const + { + return (uchar)wasm_i8x16_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_int8x16 +{ + typedef schar lane_type; + typedef v128_t vector_type; + enum { nlanes = 16 }; + + v_int8x16() {} + explicit v_int8x16(v128_t v) : val(v) {} + v_int8x16(schar v0, schar v1, schar v2, schar v3, schar v4, schar v5, schar v6, schar v7, + schar v8, schar v9, schar v10, schar v11, schar v12, schar v13, schar v14, schar v15) + { + schar v[] = {v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15}; + val = wasm_v128_load(v); + } + + schar get0() const + { + return wasm_i8x16_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_uint16x8 +{ + typedef ushort lane_type; + typedef v128_t vector_type; + enum { nlanes = 8 }; + + v_uint16x8() {} + explicit v_uint16x8(v128_t v) : val(v) {} + v_uint16x8(ushort v0, ushort v1, ushort v2, ushort v3, ushort v4, ushort v5, ushort v6, ushort v7) + { + ushort v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = wasm_v128_load(v); + } + + ushort get0() const + { + return (ushort)wasm_i16x8_extract_lane(val, 0); // wasm_u16x8_extract_lane() unimplemented yet + } + + v128_t val; +}; + +struct v_int16x8 +{ + typedef short lane_type; + typedef v128_t vector_type; + enum { nlanes = 8 }; + + v_int16x8() {} + explicit v_int16x8(v128_t v) : val(v) {} + v_int16x8(short v0, short v1, short v2, short v3, short v4, short v5, short v6, short v7) + { + short v[] = {v0, v1, v2, v3, v4, v5, v6, v7}; + val = wasm_v128_load(v); + } + + short get0() const + { + return wasm_i16x8_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_uint32x4 +{ + typedef unsigned lane_type; + typedef v128_t vector_type; + enum { nlanes = 4 }; + + v_uint32x4() {} + explicit v_uint32x4(v128_t v) : val(v) {} + v_uint32x4(unsigned v0, unsigned v1, unsigned v2, unsigned v3) + { + unsigned v[] = {v0, v1, v2, v3}; + val = wasm_v128_load(v); + } + + unsigned get0() const + { + return (unsigned)wasm_i32x4_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_int32x4 +{ + typedef int lane_type; + typedef v128_t vector_type; + enum { nlanes = 4 }; + + v_int32x4() {} + explicit v_int32x4(v128_t v) : val(v) {} + v_int32x4(int v0, int v1, int v2, int v3) + { + int v[] = {v0, v1, v2, v3}; + val = wasm_v128_load(v); + } + + int get0() const + { + return wasm_i32x4_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_float32x4 +{ + typedef float lane_type; + typedef v128_t vector_type; + enum { nlanes = 4 }; + + v_float32x4() {} + explicit v_float32x4(v128_t v) : val(v) {} + v_float32x4(float v0, float v1, float v2, float v3) + { + float v[] = {v0, v1, v2, v3}; + val = wasm_v128_load(v); + } + + float get0() const + { + return wasm_f32x4_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_uint64x2 +{ + typedef uint64 lane_type; + typedef v128_t vector_type; + enum { nlanes = 2 }; + + v_uint64x2() {} + explicit v_uint64x2(v128_t v) : val(v) {} + v_uint64x2(uint64 v0, uint64 v1) + { + uint64 v[] = {v0, v1}; + val = wasm_v128_load(v); + } + + uint64 get0() const + { + return (uint64)wasm_i64x2_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_int64x2 +{ + typedef int64 lane_type; + typedef v128_t vector_type; + enum { nlanes = 2 }; + + v_int64x2() {} + explicit v_int64x2(v128_t v) : val(v) {} + v_int64x2(int64 v0, int64 v1) + { + int64 v[] = {v0, v1}; + val = wasm_v128_load(v); + } + + int64 get0() const + { + return wasm_i64x2_extract_lane(val, 0); + } + + v128_t val; +}; + +struct v_float64x2 +{ + typedef double lane_type; + typedef v128_t vector_type; + enum { nlanes = 2 }; + + v_float64x2() {} + explicit v_float64x2(v128_t v) : val(v) {} + v_float64x2(double v0, double v1) + { + double v[] = {v0, v1}; + val = wasm_v128_load(v); + } + + double get0() const + { + return wasm_f64x2_extract_lane(val, 0); + } + + v128_t val; +}; + +namespace +{ +#define OPENCV_HAL_IMPL_REINTERPRET_INT(ft, tt) \ +inline tt reinterpret_int(ft x) { union { ft l; tt i; } v; v.l = x; return v.i; } +OPENCV_HAL_IMPL_REINTERPRET_INT(uchar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(schar, schar) +OPENCV_HAL_IMPL_REINTERPRET_INT(ushort, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(short, short) +OPENCV_HAL_IMPL_REINTERPRET_INT(unsigned, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(int, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(float, int) +OPENCV_HAL_IMPL_REINTERPRET_INT(uint64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(int64, int64) +OPENCV_HAL_IMPL_REINTERPRET_INT(double, int64) + +static const unsigned char popCountTable[] = +{ + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8, +}; +} // namespace + +static v128_t wasm_unpacklo_i8x16(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,16,1,17,2,18,3,19,4,20,5,21,6,22,7,23); +} + +static v128_t wasm_unpacklo_i16x8(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,1,16,17,2,3,18,19,4,5,20,21,6,7,22,23); +} + +static v128_t wasm_unpacklo_i32x4(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,1,2,3,16,17,18,19,4,5,6,7,20,21,22,23); +} + +static v128_t wasm_unpacklo_i64x2(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); +} + +static v128_t wasm_unpackhi_i8x16(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,24,9,25,10,26,11,27,12,28,13,29,14,30,15,31); +} + +static v128_t wasm_unpackhi_i16x8(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,9,24,25,10,11,26,27,12,13,28,29,14,15,30,31); +} + +static v128_t wasm_unpackhi_i32x4(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,9,10,11,24,25,26,27,12,13,14,15,28,29,30,31); +} + +static v128_t wasm_unpackhi_i64x2(v128_t a, v128_t b) { + return wasm_i8x16_shuffle(a, b, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); +} + +/** Convert **/ +// 8 >> 16 +inline v128_t v128_cvtu8x16_i16x8(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i8x16(a, z); +} +inline v128_t v128_cvti8x16_i16x8(const v128_t& a) +{ return wasm_i16x8_shr(wasm_unpacklo_i8x16(a, a), 8); } +// 8 >> 32 +inline v128_t v128_cvtu8x16_i32x4(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i16x8(wasm_unpacklo_i8x16(a, z), z); +} +inline v128_t v128_cvti8x16_i32x4(const v128_t& a) +{ + v128_t r = wasm_unpacklo_i8x16(a, a); + r = wasm_unpacklo_i8x16(r, r); + return wasm_i32x4_shr(r, 24); +} +// 16 >> 32 +inline v128_t v128_cvtu16x8_i32x4(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i16x8(a, z); +} +inline v128_t v128_cvti16x8_i32x4(const v128_t& a) +{ return wasm_i32x4_shr(wasm_unpacklo_i16x8(a, a), 16); } +// 32 >> 64 +inline v128_t v128_cvtu32x4_i64x2(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpacklo_i32x4(a, z); +} +inline v128_t v128_cvti32x4_i64x2(const v128_t& a) +{ return wasm_unpacklo_i32x4(a, wasm_i32x4_shr(a, 31)); } + +// 16 << 8 +inline v128_t v128_cvtu8x16_i16x8_high(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpackhi_i8x16(a, z); +} +inline v128_t v128_cvti8x16_i16x8_high(const v128_t& a) +{ return wasm_i16x8_shr(wasm_unpackhi_i8x16(a, a), 8); } +// 32 << 16 +inline v128_t v128_cvtu16x8_i32x4_high(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpackhi_i16x8(a, z); +} +inline v128_t v128_cvti16x8_i32x4_high(const v128_t& a) +{ return wasm_i32x4_shr(wasm_unpackhi_i16x8(a, a), 16); } +// 64 << 32 +inline v128_t v128_cvtu32x4_i64x2_high(const v128_t& a) +{ + const v128_t z = wasm_i8x16_splat(0); + return wasm_unpackhi_i32x4(a, z); +} +inline v128_t v128_cvti32x4_i64x2_high(const v128_t& a) +{ return wasm_unpackhi_i32x4(a, wasm_i32x4_shr(a, 31)); } + +#define OPENCV_HAL_IMPL_WASM_INITVEC(_Tpvec, _Tp, suffix, zsuffix, _Tps) \ +inline _Tpvec v_setzero_##suffix() { return _Tpvec(wasm_##zsuffix##_splat((_Tps)0)); } \ +inline _Tpvec v_setall_##suffix(_Tp v) { return _Tpvec(wasm_##zsuffix##_splat((_Tps)v)); } \ +template <> inline _Tpvec v_setzero_() { return v_setzero_##suffix(); } \ +template <> inline _Tpvec v_setall_(_Tp v) { return v_setall_##suffix(v); } \ +template inline _Tpvec v_reinterpret_as_##suffix(const _Tpvec0& a) \ +{ return _Tpvec(a.val); } + +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint8x16, uchar, u8, i8x16, schar) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int8x16, schar, s8, i8x16, schar) +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint16x8, ushort, u16, i16x8, short) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int16x8, short, s16, i16x8, short) +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint32x4, unsigned, u32, i32x4, int) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int32x4, int, s32, i32x4, int) +OPENCV_HAL_IMPL_WASM_INITVEC(v_float32x4, float, f32, f32x4, float) +OPENCV_HAL_IMPL_WASM_INITVEC(v_uint64x2, uint64, u64, i64x2, int64) +OPENCV_HAL_IMPL_WASM_INITVEC(v_int64x2, int64, s64, i64x2, int64) +OPENCV_HAL_IMPL_WASM_INITVEC(v_float64x2, double, f64, f64x2, double) + +//////////////// PACK /////////////// +inline v_uint8x16 v_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); + return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +inline v_int8x16 v_pack(const v_int16x8& a, const v_int16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); + return v_int8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +inline v_uint16x8 v_pack(const v_uint32x4& a, const v_uint32x4& b) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); + return v_uint16x8(wasm_i8x16_shuffle(a1, b1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +inline v_int16x8 v_pack(const v_int32x4& a, const v_int32x4& b) +{ + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i32x4_splat(-32768); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); + return v_int16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +inline v_uint32x4 v_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + return v_uint32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +inline v_int32x4 v_pack(const v_int64x2& a, const v_int64x2& b) +{ + return v_int32x4(wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +inline v_uint8x16 v_pack_u(const v_int16x8& a, const v_int16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i16x8_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i16x8_lt(b1, minval)); + return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +inline v_uint16x8 v_pack_u(const v_int32x4& a, const v_int32x4& b) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i32x4_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_i32x4_gt(b.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t b2 = wasm_v128_bitselect(minval, b1, wasm_i32x4_lt(b1, minval)); + return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} + +template +inline v_uint8x16 v_rshr_pack(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t b1 = wasm_u16x8_shr(wasm_i16x8_add(b.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u16x8_gt(b1, maxval)); + return v_uint8x16(wasm_i8x16_shuffle(a2, b2, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +template +inline v_int8x16 v_rshr_pack(const v_int16x8& a, const v_int16x8& b) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); + return v_int8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +template +inline v_uint16x8 v_rshr_pack(const v_uint32x4& a, const v_uint32x4& b) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t b1 = wasm_u32x4_shr(wasm_i32x4_add(b.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_u32x4_gt(b1, maxval)); + return v_uint16x8(wasm_i8x16_shuffle(a2, b2, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +template +inline v_int16x8 v_rshr_pack(const v_int32x4& a, const v_int32x4& b) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i16x8_splat(-32768); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); + return v_int16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} +template +inline v_uint32x4 v_rshr_pack(const v_uint64x2& a, const v_uint64x2& b) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t b1 = wasm_u64x2_shr(wasm_i64x2_add(b.val, delta), n); + return v_uint32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +template +inline v_int32x4 v_rshr_pack(const v_int64x2& a, const v_int64x2& b) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t b1 = wasm_i64x2_shr(wasm_i64x2_add(b.val, delta), n); + return v_int32x4(wasm_i8x16_shuffle(a1, b1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27)); +} +template +inline v_uint8x16 v_rshr_pack_u(const v_int16x8& a, const v_int16x8& b) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t b1 = wasm_i16x8_shr(wasm_i16x8_add(b.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i16x8_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i16x8_lt(b1, minval)); + return v_uint8x16(wasm_i8x16_shuffle(a3, b3, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} +template +inline v_uint16x8 v_rshr_pack_u(const v_int32x4& a, const v_int32x4& b) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t b1 = wasm_i32x4_shr(wasm_i32x4_add(b.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i16x8_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t b2 = wasm_v128_bitselect(maxval, b1, wasm_i32x4_gt(b1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t b3 = wasm_v128_bitselect(minval, b2, wasm_i32x4_lt(b1, minval)); + return v_uint16x8(wasm_i8x16_shuffle(a3, b3, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29)); +} + +inline void v_pack_store(uchar* ptr, const v_uint16x8& a) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(schar* ptr, const v_int16x8& a) +{ + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + schar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(ushort* ptr, const v_uint32x4& a) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(short* ptr, const v_int32x4& a) +{ + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i32x4_splat(-32768); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + short t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + unsigned t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_store(int* ptr, const v_int64x2& a) +{ + v128_t r = wasm_i8x16_shuffle(a.val, a.val, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + int t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_u_store(uchar* ptr, const v_int16x8& a) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i16x8_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +inline void v_pack_u_store(ushort* ptr, const v_int32x4& a) +{ + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i32x4_splat(0); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_i32x4_gt(a.val, maxval)); + v128_t a2 = wasm_v128_bitselect(minval, a1, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} + +template +inline void v_rshr_pack_store(uchar* ptr, const v_uint16x8& a) +{ + v128_t delta = wasm_i16x8_splat((short)(1 << (n-1))); + v128_t a1 = wasm_u16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u16x8_gt(a1, maxval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(schar* ptr, const v_int16x8& a) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t maxval = wasm_i16x8_splat(127); + v128_t minval = wasm_i16x8_splat(-128); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + schar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(ushort* ptr, const v_uint32x4& a) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_u32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_u32x4_gt(a1, maxval)); + v128_t r = wasm_i8x16_shuffle(a2, a2, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(short* ptr, const v_int32x4& a) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t maxval = wasm_i32x4_splat(32767); + v128_t minval = wasm_i32x4_splat(-32768); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + short t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(unsigned* ptr, const v_uint64x2& a) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_u64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + unsigned t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_store(int* ptr, const v_int64x2& a) +{ + v128_t delta = wasm_i64x2_splat(((int64)1 << (n-1))); + v128_t a1 = wasm_i64x2_shr(wasm_i64x2_add(a.val, delta), n); + v128_t r = wasm_i8x16_shuffle(a1, a1, 0,1,2,3,8,9,10,11,0,1,2,3,8,9,10,11); + int t_ptr[4]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<2; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_u_store(uchar* ptr, const v_int16x8& a) +{ + v128_t delta = wasm_i16x8_splat(((short)1 << (n-1))); + v128_t a1 = wasm_i16x8_shr(wasm_i16x8_add(a.val, delta), n); + v128_t maxval = wasm_i16x8_splat(255); + v128_t minval = wasm_i16x8_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i16x8_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i16x8_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,2,4,6,8,10,12,14,0,2,4,6,8,10,12,14); + uchar t_ptr[16]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<8; ++i) { + ptr[i] = t_ptr[i]; + } +} +template +inline void v_rshr_pack_u_store(ushort* ptr, const v_int32x4& a) +{ + v128_t delta = wasm_i32x4_splat(((int)1 << (n-1))); + v128_t a1 = wasm_i32x4_shr(wasm_i32x4_add(a.val, delta), n); + v128_t maxval = wasm_i32x4_splat(65535); + v128_t minval = wasm_i32x4_splat(0); + v128_t a2 = wasm_v128_bitselect(maxval, a1, wasm_i32x4_gt(a1, maxval)); + v128_t a3 = wasm_v128_bitselect(minval, a2, wasm_i32x4_lt(a1, minval)); + v128_t r = wasm_i8x16_shuffle(a3, a3, 0,1,4,5,8,9,12,13,0,1,4,5,8,9,12,13); + ushort t_ptr[8]; + wasm_v128_store(t_ptr, r); + for (int i=0; i<4; ++i) { + ptr[i] = t_ptr[i]; + } +} + +inline v_uint8x16 v_pack_b(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t maxval = wasm_i16x8_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u16x8_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u16x8_gt(b.val, maxval)); + return v_uint8x16(wasm_i8x16_shuffle(a1, b1, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30)); +} + +inline v_uint8x16 v_pack_b(const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d) +{ + v128_t maxval = wasm_i32x4_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, wasm_u32x4_gt(a.val, maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, wasm_u32x4_gt(b.val, maxval)); + v128_t c1 = wasm_v128_bitselect(maxval, c.val, wasm_u32x4_gt(c.val, maxval)); + v128_t d1 = wasm_v128_bitselect(maxval, d.val, wasm_u32x4_gt(d.val, maxval)); + v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); + v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,4,8,12,16,20,24,28,0,4,8,12,16,20,24,28); + return v_uint8x16(wasm_i8x16_shuffle(ab, cd, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); +} + +inline v_uint8x16 v_pack_b(const v_uint64x2& a, const v_uint64x2& b, const v_uint64x2& c, + const v_uint64x2& d, const v_uint64x2& e, const v_uint64x2& f, + const v_uint64x2& g, const v_uint64x2& h) +{ + v128_t maxval = wasm_i32x4_splat(255); + v128_t a1 = wasm_v128_bitselect(maxval, a.val, ((__u64x2)(a.val) > (__u64x2)maxval)); + v128_t b1 = wasm_v128_bitselect(maxval, b.val, ((__u64x2)(b.val) > (__u64x2)maxval)); + v128_t c1 = wasm_v128_bitselect(maxval, c.val, ((__u64x2)(c.val) > (__u64x2)maxval)); + v128_t d1 = wasm_v128_bitselect(maxval, d.val, ((__u64x2)(d.val) > (__u64x2)maxval)); + v128_t e1 = wasm_v128_bitselect(maxval, e.val, ((__u64x2)(e.val) > (__u64x2)maxval)); + v128_t f1 = wasm_v128_bitselect(maxval, f.val, ((__u64x2)(f.val) > (__u64x2)maxval)); + v128_t g1 = wasm_v128_bitselect(maxval, g.val, ((__u64x2)(g.val) > (__u64x2)maxval)); + v128_t h1 = wasm_v128_bitselect(maxval, h.val, ((__u64x2)(h.val) > (__u64x2)maxval)); + v128_t ab = wasm_i8x16_shuffle(a1, b1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t cd = wasm_i8x16_shuffle(c1, d1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t ef = wasm_i8x16_shuffle(e1, f1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t gh = wasm_i8x16_shuffle(g1, h1, 0,8,16,24,0,8,16,24,0,8,16,24,0,8,16,24); + v128_t abcd = wasm_i8x16_shuffle(ab, cd, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); + v128_t efgh = wasm_i8x16_shuffle(ef, gh, 0,1,2,3,16,17,18,19,0,1,2,3,16,17,18,19); + return v_uint8x16(wasm_i8x16_shuffle(abcd, efgh, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23)); +} + +inline v_float32x4 v_matmul(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& m3) +{ + v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); + v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); + v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); + v128_t v3 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 3)); + v0 = wasm_f32x4_mul(v0, m0.val); + v1 = wasm_f32x4_mul(v1, m1.val); + v2 = wasm_f32x4_mul(v2, m2.val); + v3 = wasm_f32x4_mul(v3, m3.val); + + return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, v3))); +} + +inline v_float32x4 v_matmuladd(const v_float32x4& v, const v_float32x4& m0, + const v_float32x4& m1, const v_float32x4& m2, + const v_float32x4& a) +{ + v128_t v0 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 0)); + v128_t v1 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 1)); + v128_t v2 = wasm_f32x4_splat(wasm_f32x4_extract_lane(v.val, 2)); + v0 = wasm_f32x4_mul(v0, m0.val); + v1 = wasm_f32x4_mul(v1, m1.val); + v2 = wasm_f32x4_mul(v2, m2.val); + + return v_float32x4(wasm_f32x4_add(wasm_f32x4_add(v0, v1), wasm_f32x4_add(v2, a.val))); +} + +#define OPENCV_HAL_IMPL_WASM_BIN_OP(bin_op, _Tpvec, intrin) \ +inline _Tpvec bin_op(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint8x16, wasm_u8x16_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint8x16, wasm_u8x16_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int8x16, wasm_i8x16_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int8x16, wasm_i8x16_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint16x8, wasm_u16x8_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint16x8, wasm_u16x8_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int16x8, wasm_i16x8_add_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int16x8, wasm_i16x8_sub_saturate) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint32x4, wasm_i32x4_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint32x4, wasm_i32x4_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_uint32x4, wasm_i32x4_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int32x4, wasm_i32x4_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int32x4, wasm_i32x4_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_int32x4, wasm_i32x4_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float32x4, wasm_f32x4_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float32x4, wasm_f32x4_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float32x4, wasm_f32x4_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float32x4, wasm_f32x4_div) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_uint64x2, wasm_i64x2_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_uint64x2, wasm_i64x2_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_int64x2, wasm_i64x2_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_int64x2, wasm_i64x2_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_add, v_float64x2, wasm_f64x2_add) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_sub, v_float64x2, wasm_f64x2_sub) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_mul, v_float64x2, wasm_f64x2_mul) +OPENCV_HAL_IMPL_WASM_BIN_OP(v_div, v_float64x2, wasm_f64x2_div) + +// saturating multiply 8-bit, 16-bit +#define OPENCV_HAL_IMPL_WASM_MUL_SAT(_Tpvec, _Tpwvec) \ +inline _Tpvec v_mul(const _Tpvec& a, const _Tpvec& b) \ +{ \ + _Tpwvec c, d; \ + v_mul_expand(a, b, c, d); \ + return v_pack(c, d); \ +} + +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint8x16, v_uint16x8) +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int8x16, v_int16x8) +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_uint16x8, v_uint32x4) +OPENCV_HAL_IMPL_WASM_MUL_SAT(v_int16x8, v_int32x4) + +// Multiply and expand +inline void v_mul_expand(const v_uint8x16& a, const v_uint8x16& b, + v_uint16x8& c, v_uint16x8& d) +{ + v_uint16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int8x16& a, const v_int8x16& b, + v_int16x8& c, v_int16x8& d) +{ + v_int16x8 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c = v_mul_wrap(a0, b0); + d = v_mul_wrap(a1, b1); +} + +inline void v_mul_expand(const v_int16x8& a, const v_int16x8& b, + v_int32x4& c, v_int32x4& d) +{ + v_int32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c.val = wasm_i32x4_mul(a0.val, b0.val); + d.val = wasm_i32x4_mul(a1.val, b1.val); +} + +inline void v_mul_expand(const v_uint16x8& a, const v_uint16x8& b, + v_uint32x4& c, v_uint32x4& d) +{ + v_uint32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c.val = wasm_i32x4_mul(a0.val, b0.val); + d.val = wasm_i32x4_mul(a1.val, b1.val); +} + +inline void v_mul_expand(const v_uint32x4& a, const v_uint32x4& b, + v_uint64x2& c, v_uint64x2& d) +{ + v_uint64x2 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + c.val = ((__u64x2)(a0.val) * (__u64x2)(b0.val)); + d.val = ((__u64x2)(a1.val) * (__u64x2)(b1.val)); +} + +inline v_int16x8 v_mul_hi(const v_int16x8& a, const v_int16x8& b) +{ + v_int32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + v128_t c = wasm_i32x4_mul(a0.val, b0.val); + v128_t d = wasm_i32x4_mul(a1.val, b1.val); + return v_int16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); +} +inline v_uint16x8 v_mul_hi(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 a0, a1, b0, b1; + v_expand(a, a0, a1); + v_expand(b, b0, b1); + v128_t c = wasm_i32x4_mul(a0.val, b0.val); + v128_t d = wasm_i32x4_mul(a1.val, b1.val); + return v_uint16x8(wasm_i8x16_shuffle(c, d, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31)); +} + +//////// Dot Product //////// + +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b) +{ + v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); + v128_t a1 = wasm_i32x4_shr(a.val, 16); + v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); + v128_t b1 = wasm_i32x4_shr(b.val, 16); + v128_t c = wasm_i32x4_mul(a0, b0); + v128_t d = wasm_i32x4_mul(a1, b1); + return v_int32x4(wasm_i32x4_add(c, d)); +} + +inline v_int32x4 v_dotprod(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_add(v_dotprod(a, b), c); } + +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b) +{ + v128_t a0 = wasm_i64x2_shr(wasm_i64x2_shl(a.val, 32), 32); + v128_t a1 = wasm_i64x2_shr(a.val, 32); + v128_t b0 = wasm_i64x2_shr(wasm_i64x2_shl(b.val, 32), 32); + v128_t b1 = wasm_i64x2_shr(b.val, 32); + v128_t c = (v128_t)((__i64x2)a0 * (__i64x2)b0); + v128_t d = (v128_t)((__i64x2)a1 * (__i64x2)b1); + return v_int64x2(wasm_i64x2_add(c, d)); +} +inline v_int64x2 v_dotprod(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ + return v_add(v_dotprod(a, b), c); +} + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b) +{ + v128_t a0 = wasm_u16x8_shr(wasm_i16x8_shl(a.val, 8), 8); + v128_t a1 = wasm_u16x8_shr(a.val, 8); + v128_t b0 = wasm_u16x8_shr(wasm_i16x8_shl(b.val, 8), 8); + v128_t b1 = wasm_u16x8_shr(b.val, 8); + return v_uint32x4((v_add( + v_dotprod(v_int16x8(a0), v_int16x8(b0)), + v_dotprod(v_int16x8(a1), v_int16x8(b1)))).val + ); +} +inline v_uint32x4 v_dotprod_expand(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b) +{ + v128_t a0 = wasm_i16x8_shr(wasm_i16x8_shl(a.val, 8), 8); + v128_t a1 = wasm_i16x8_shr(a.val, 8); + v128_t b0 = wasm_i16x8_shr(wasm_i16x8_shl(b.val, 8), 8); + v128_t b1 = wasm_i16x8_shr(b.val, 8); + return v_int32x4(v_add( + v_dotprod(v_int16x8(a0), v_int16x8(b0)), + v_dotprod(v_int16x8(a1), v_int16x8(b1)) + )); +} +inline v_int32x4 v_dotprod_expand(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b) +{ + v128_t a0 = wasm_u32x4_shr(wasm_i32x4_shl(a.val, 16), 16); + v128_t a1 = wasm_u32x4_shr(a.val, 16); + v128_t b0 = wasm_u32x4_shr(wasm_i32x4_shl(b.val, 16), 16); + v128_t b1 = wasm_u32x4_shr(b.val, 16); + return v_uint64x2((v_add( + v_dotprod(v_int32x4(a0), v_int32x4(b0)), + v_dotprod(v_int32x4(a1), v_int32x4(b1))).val + )); +} +inline v_uint64x2 v_dotprod_expand(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b) +{ + v128_t a0 = wasm_i32x4_shr(wasm_i32x4_shl(a.val, 16), 16); + v128_t a1 = wasm_i32x4_shr(a.val, 16); + v128_t b0 = wasm_i32x4_shr(wasm_i32x4_shl(b.val, 16), 16); + v128_t b1 = wasm_i32x4_shr(b.val, 16); + return v_int64x2((v_add( + v_dotprod(v_int32x4(a0), v_int32x4(b0)), + v_dotprod(v_int32x4(a1), v_int32x4(b1))) + )); +} + +inline v_int64x2 v_dotprod_expand(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b) +{ return v_cvt_f64(v_dotprod(a, b)); } +inline v_float64x2 v_dotprod_expand(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_add(v_dotprod_expand(a, b), c); } + +//////// Fast Dot Product //////// + +// 16 >> 32 +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod(a, b); } +inline v_int32x4 v_dotprod_fast(const v_int16x8& a, const v_int16x8& b, const v_int32x4& c) +{ return v_dotprod(a, b, c); } + +// 32 >> 64 +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod(a, b); } +inline v_int64x2 v_dotprod_fast(const v_int32x4& a, const v_int32x4& b, const v_int64x2& c) +{ return v_dotprod(a, b, c); } + +// 8 >> 32 +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_uint32x4 v_dotprod_expand_fast(const v_uint8x16& a, const v_uint8x16& b, const v_uint32x4& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b) +{ return v_dotprod_expand(a, b); } +inline v_int32x4 v_dotprod_expand_fast(const v_int8x16& a, const v_int8x16& b, const v_int32x4& c) +{ return v_dotprod_expand(a, b, c); } + +// 16 >> 64 +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_uint64x2 v_dotprod_expand_fast(const v_uint16x8& a, const v_uint16x8& b, const v_uint64x2& c) +{ return v_dotprod_expand(a, b, c); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b) +{ return v_dotprod_expand(a, b); } +inline v_int64x2 v_dotprod_expand_fast(const v_int16x8& a, const v_int16x8& b, const v_int64x2& c) +{ return v_dotprod_expand(a, b, c); } + +// 32 >> 64f +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b) +{ return v_dotprod_expand(a, b); } +inline v_float64x2 v_dotprod_expand_fast(const v_int32x4& a, const v_int32x4& b, const v_float64x2& c) +{ return v_dotprod_expand(a, b, c); } + +#define OPENCV_HAL_IMPL_WASM_LOGIC_OP(_Tpvec) \ +OPENCV_HAL_IMPL_WASM_BIN_OP(v_and, _Tpvec, wasm_v128_and) \ +OPENCV_HAL_IMPL_WASM_BIN_OP(v_or, _Tpvec, wasm_v128_or) \ +OPENCV_HAL_IMPL_WASM_BIN_OP(v_xor, _Tpvec, wasm_v128_xor) \ +inline _Tpvec v_not(const _Tpvec& a) \ +{ \ + return _Tpvec(wasm_v128_not(a.val)); \ +} + +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint8x16) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int8x16) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint16x8) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int16x8) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint32x4) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int32x4) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_uint64x2) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_int64x2) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float32x4) +OPENCV_HAL_IMPL_WASM_LOGIC_OP(v_float64x2) + +inline v_float32x4 v_sqrt(const v_float32x4& x) +{ + return v_float32x4(wasm_f32x4_sqrt(x.val)); +} + +inline v_float32x4 v_invsqrt(const v_float32x4& x) +{ + const v128_t _1_0 = wasm_f32x4_splat(1.0); + return v_float32x4(wasm_f32x4_div(_1_0, wasm_f32x4_sqrt(x.val))); +} + +inline v_float64x2 v_sqrt(const v_float64x2& x) +{ + return v_float64x2(wasm_f64x2_sqrt(x.val)); +} + +inline v_float64x2 v_invsqrt(const v_float64x2& x) +{ + const v128_t _1_0 = wasm_f64x2_splat(1.0); + return v_float64x2(wasm_f64x2_div(_1_0, wasm_f64x2_sqrt(x.val))); +} + +#define OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(_Tpuvec, _Tpsvec, suffix, zsuffix, shiftWidth) \ +inline _Tpuvec v_abs(const _Tpsvec& x) \ +{ \ + v128_t s = wasm_##suffix##_shr(x.val, shiftWidth); \ + v128_t f = wasm_##zsuffix##_shr(x.val, shiftWidth); \ + return _Tpuvec(wasm_##zsuffix##_add(wasm_v128_xor(x.val, f), s)); \ +} + +OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint8x16, v_int8x16, u8x16, i8x16, 7) +OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint16x8, v_int16x8, u16x8, i16x8, 15) +OPENCV_HAL_IMPL_WASM_ABS_INT_FUNC(v_uint32x4, v_int32x4, u32x4, i32x4, 31) + +inline v_float32x4 v_abs(const v_float32x4& x) +{ return v_float32x4(wasm_f32x4_abs(x.val)); } +inline v_float64x2 v_abs(const v_float64x2& x) +{ + return v_float64x2(wasm_f64x2_abs(x.val)); +} + +// TODO: exp, log, sin, cos + +#define OPENCV_HAL_IMPL_WASM_BIN_FUNC(_Tpvec, func, intrin) \ +inline _Tpvec func(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(intrin(a.val, b.val)); \ +} + +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_min, wasm_f32x4_min) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float32x4, v_max, wasm_f32x4_max) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_min, wasm_f64x2_min) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_float64x2, v_max, wasm_f64x2_max) + +#define OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(_Tpvec, suffix) \ +inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_v128_bitselect(b.val, a.val, wasm_##suffix##_gt(a.val, b.val))); \ +} \ +inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_v128_bitselect(a.val, b.val, wasm_##suffix##_gt(a.val, b.val))); \ +} + +OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int8x16, i8x16) +OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int16x8, i16x8) +OPENCV_HAL_IMPL_WASM_MINMAX_S_INIT_FUNC(v_int32x4, i32x4) + +#define OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(_Tpvec, suffix, deltaNum) \ +inline _Tpvec v_min(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t delta = wasm_##suffix##_splat(deltaNum); \ + v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ + return _Tpvec(wasm_v128_bitselect(b.val, a.val, mask)); \ +} \ +inline _Tpvec v_max(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t delta = wasm_##suffix##_splat(deltaNum); \ + v128_t mask = wasm_##suffix##_gt(wasm_v128_xor(a.val, delta), wasm_v128_xor(b.val, delta)); \ + return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask)); \ +} + +OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint8x16, i8x16, (schar)0x80) +OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint16x8, i16x8, (short)0x8000) +OPENCV_HAL_IMPL_WASM_MINMAX_U_INIT_FUNC(v_uint32x4, i32x4, (int)0x80000000) + +#define OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(_Tpvec, suffix, esuffix) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##esuffix##_eq(a.val, b.val)); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##esuffix##_ne(a.val, b.val)); } \ +inline _Tpvec v_lt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_lt(a.val, b.val)); } \ +inline _Tpvec v_gt(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_gt(a.val, b.val)); } \ +inline _Tpvec v_le(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_le(a.val, b.val)); } \ +inline _Tpvec v_ge(const _Tpvec& a, const _Tpvec& b) \ +{ return _Tpvec(wasm_##suffix##_ge(a.val, b.val)); } + +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint8x16, u8x16, i8x16) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int8x16, i8x16, i8x16) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint16x8, u16x8, i16x8) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int16x8, i16x8, i16x8) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_uint32x4, u32x4, i32x4) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_int32x4, i32x4, i32x4) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float32x4, f32x4, f32x4) +OPENCV_HAL_IMPL_WASM_INIT_CMP_OP(v_float64x2, f64x2, f64x2) + +#define OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(_Tpvec, cast) \ +inline _Tpvec v_eq(const _Tpvec& a, const _Tpvec& b) \ +{ return cast(v_eq(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } \ +inline _Tpvec v_ne(const _Tpvec& a, const _Tpvec& b) \ +{ return cast(v_ne(v_reinterpret_as_f64(a), v_reinterpret_as_f64(b))); } + +OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_uint64x2, v_reinterpret_as_u64) +OPENCV_HAL_IMPL_WASM_64BIT_CMP_OP(v_int64x2, v_reinterpret_as_s64) + +inline v_float32x4 v_not_nan(const v_float32x4& a) +{ + v128_t z = wasm_i32x4_splat(0x7fffffff); + v128_t t = wasm_i32x4_splat(0x7f800000); + return v_float32x4(wasm_u32x4_lt(wasm_v128_and(a.val, z), t)); +} +inline v_float64x2 v_not_nan(const v_float64x2& a) +{ + v128_t z = wasm_i64x2_splat(0x7fffffffffffffff); + v128_t t = wasm_i64x2_splat(0x7ff0000000000000); + return v_float64x2((__u64x2)(wasm_v128_and(a.val, z)) < (__u64x2)t); +} + +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_add_wrap, wasm_i8x16_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_add_wrap, wasm_i8x16_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_add_wrap, wasm_i16x8_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_add_wrap, wasm_i16x8_add) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_sub_wrap, wasm_i8x16_sub) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_sub_wrap, wasm_i8x16_sub) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_sub_wrap, wasm_i16x8_sub) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_sub_wrap, wasm_i16x8_sub) +#if (__EMSCRIPTEN_major__ * 1000000 + __EMSCRIPTEN_minor__ * 1000 + __EMSCRIPTEN_tiny__) >= (1039012) +// details: https://github.com/opencv/opencv/issues/18097 ( https://github.com/emscripten-core/emscripten/issues/12018 ) +// 1.39.12: https://github.com/emscripten-core/emscripten/commit/cd801d0f110facfd694212a3c8b2ed2ffcd630e2 +inline v_uint8x16 v_mul_wrap(const v_uint8x16& a, const v_uint8x16& b) +{ + uchar a_[16], b_[16]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + for (int i = 0; i < 16; i++) + a_[i] = (uchar)(a_[i] * b_[i]); + return v_uint8x16(wasm_v128_load(a_)); +} +inline v_int8x16 v_mul_wrap(const v_int8x16& a, const v_int8x16& b) +{ + schar a_[16], b_[16]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + for (int i = 0; i < 16; i++) + a_[i] = (schar)(a_[i] * b_[i]); + return v_int8x16(wasm_v128_load(a_)); +} +#else +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint8x16, v_mul_wrap, wasm_i8x16_mul) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int8x16, v_mul_wrap, wasm_i8x16_mul) +#endif +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_uint16x8, v_mul_wrap, wasm_i16x8_mul) +OPENCV_HAL_IMPL_WASM_BIN_FUNC(v_int16x8, v_mul_wrap, wasm_i16x8_mul) + + +/** Absolute difference **/ + +inline v_uint8x16 v_absdiff(const v_uint8x16& a, const v_uint8x16& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint16x8 v_absdiff(const v_uint16x8& a, const v_uint16x8& b) +{ return v_add_wrap(v_sub(a, b), v_sub(b, a)); } +inline v_uint32x4 v_absdiff(const v_uint32x4& a, const v_uint32x4& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + +inline v_uint8x16 v_absdiff(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub_wrap(a, b); + v_int8x16 m = v_lt(a, b); + return v_reinterpret_as_u8(v_sub_wrap(v_xor(d, m), m)); +} +inline v_uint16x8 v_absdiff(const v_int16x8& a, const v_int16x8& b) +{ + return v_reinterpret_as_u16(v_sub_wrap(v_max(a, b), v_min(a, b))); +} +inline v_uint32x4 v_absdiff(const v_int32x4& a, const v_int32x4& b) +{ + v_int32x4 d = v_sub(a, b); + v_int32x4 m = v_lt(a, b); + return v_reinterpret_as_u32(v_sub(v_xor(d, m), m)); +} + +/** Saturating absolute difference **/ +inline v_int8x16 v_absdiffs(const v_int8x16& a, const v_int8x16& b) +{ + v_int8x16 d = v_sub(a, b); + v_int8x16 m = v_lt(a, b); + return v_sub(v_xor(d, m), m); + } +inline v_int16x8 v_absdiffs(const v_int16x8& a, const v_int16x8& b) +{ return v_sub(v_max(a, b), v_min(a, b)); } + + +inline v_int32x4 v_fma(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_int32x4 v_muladd(const v_int32x4& a, const v_int32x4& b, const v_int32x4& c) +{ + return v_fma(a, b, c); +} + +inline v_float32x4 v_fma(const v_float32x4& a, const v_float32x4& b, const v_float32x4& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_float64x2 v_fma(const v_float64x2& a, const v_float64x2& b, const v_float64x2& c) +{ + return v_add(v_mul(a, b), c); +} + +inline v_float32x4 v_absdiff(const v_float32x4& a, const v_float32x4& b) +{ + v128_t absmask_vec = wasm_i32x4_splat(0x7fffffff); + return v_float32x4(wasm_v128_and(wasm_f32x4_sub(a.val, b.val), absmask_vec)); +} +inline v_float64x2 v_absdiff(const v_float64x2& a, const v_float64x2& b) +{ + v128_t absmask_vec = wasm_u64x2_shr(wasm_i32x4_splat(-1), 1); + return v_float64x2(wasm_v128_and(wasm_f64x2_sub(a.val, b.val), absmask_vec)); +} + +#define OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(_Tpvec, suffix) \ +inline _Tpvec v_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ + v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ + return _Tpvec(wasm_##suffix##_sqrt(wasm_##suffix##_add(a_Square, b_Square))); \ +} \ +inline _Tpvec v_sqr_magnitude(const _Tpvec& a, const _Tpvec& b) \ +{ \ + v128_t a_Square = wasm_##suffix##_mul(a.val, a.val); \ + v128_t b_Square = wasm_##suffix##_mul(b.val, b.val); \ + return _Tpvec(wasm_##suffix##_add(a_Square, b_Square)); \ +} \ +inline _Tpvec v_muladd(const _Tpvec& a, const _Tpvec& b, const _Tpvec& c) \ +{ \ + return _Tpvec(wasm_##suffix##_add(wasm_##suffix##_mul(a.val, b.val), c.val)); \ +} + +OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float32x4, f32x4) +OPENCV_HAL_IMPL_WASM_MISC_FLT_OP(v_float64x2, f64x2) + +#define OPENCV_HAL_IMPL_WASM_SHIFT_OP(_Tpuvec, _Tpsvec, suffix, ssuffix) \ +inline _Tpuvec v_shl(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +inline _Tpsvec v_shl(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +inline _Tpuvec v_shr(const _Tpuvec& a, int imm) \ +{ \ + return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ +} \ +inline _Tpsvec v_shr(const _Tpsvec& a, int imm) \ +{ \ + return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shl(const _Tpuvec& a) \ +{ \ + return _Tpuvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shl(const _Tpsvec& a) \ +{ \ + return _Tpsvec(wasm_##suffix##_shl(a.val, imm)); \ +} \ +template \ +inline _Tpuvec v_shr(const _Tpuvec& a) \ +{ \ + return _Tpuvec(wasm_##ssuffix##_shr(a.val, imm)); \ +} \ +template \ +inline _Tpsvec v_shr(const _Tpsvec& a) \ +{ \ + return _Tpsvec(wasm_##suffix##_shr(a.val, imm)); \ +} + +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint8x16, v_int8x16, i8x16, u8x16) +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint16x8, v_int16x8, i16x8, u16x8) +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint32x4, v_int32x4, i32x4, u32x4) +OPENCV_HAL_IMPL_WASM_SHIFT_OP(v_uint64x2, v_int64x2, i64x2, u64x2) + +namespace hal_wasm_internal +{ + template 16)), + bool is_first = (imm == 0), + bool is_second = (imm == 16), + bool is_other = (((imm > 0) && (imm < 16)))> + class v_wasm_palignr_u8_class; + + template + class v_wasm_palignr_u8_class; + + template + class v_wasm_palignr_u8_class + { + public: + inline v128_t operator()(const v128_t& a, const v128_t&) const + { + return a; + } + }; + + template + class v_wasm_palignr_u8_class + { + public: + inline v128_t operator()(const v128_t&, const v128_t& b) const + { + return b; + } + }; + + template + class v_wasm_palignr_u8_class + { + public: + inline v128_t operator()(const v128_t& a, const v128_t& b) const + { + enum { imm2 = (sizeof(v128_t) - imm) }; + return wasm_i8x16_shuffle(a, b, + imm, imm+1, imm+2, imm+3, + imm+4, imm+5, imm+6, imm+7, + imm+8, imm+9, imm+10, imm+11, + imm+12, imm+13, imm+14, imm+15); + } + }; + + template + inline v128_t v_wasm_palignr_u8(const v128_t& a, const v128_t& b) + { + CV_StaticAssert((imm >= 0) && (imm <= 16), "Invalid imm for v_wasm_palignr_u8."); + return v_wasm_palignr_u8_class()(a, b); + } +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a) +{ + using namespace hal_wasm_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + v128_t z = wasm_i8x16_splat(0); + return _Tpvec(v_wasm_palignr_u8(a.val, z)); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a) +{ + using namespace hal_wasm_internal; + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; + v128_t z = wasm_i8x16_splat(0); + return _Tpvec(v_wasm_palignr_u8(z, a.val)); +} + +template +inline _Tpvec v_rotate_right(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_wasm_internal; + enum { imm2 = (imm * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_wasm_palignr_u8(a.val, b.val)); +} + +template +inline _Tpvec v_rotate_left(const _Tpvec &a, const _Tpvec &b) +{ + using namespace hal_wasm_internal; + enum { imm2 = ((_Tpvec::nlanes - imm) * sizeof(typename _Tpvec::lane_type)) }; + return _Tpvec(v_wasm_palignr_u8(b.val, a.val)); +} + +#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(_Tpvec, _Tp) \ +inline _Tpvec v_load(const _Tp* ptr) \ +{ return _Tpvec(wasm_v128_load(ptr)); } \ +inline _Tpvec v_load_aligned(const _Tp* ptr) \ +{ return _Tpvec(wasm_v128_load(ptr)); } \ +inline _Tpvec v_load_low(const _Tp* ptr) \ +{ \ + _Tp tmp[_Tpvec::nlanes] = {0}; \ + for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ + tmp[i] = ptr[i]; \ + } \ + return _Tpvec(wasm_v128_load(tmp)); \ +} \ +inline _Tpvec v_load_halves(const _Tp* ptr0, const _Tp* ptr1) \ +{ \ + _Tp tmp[_Tpvec::nlanes]; \ + for (int i=0; i<_Tpvec::nlanes/2; ++i) { \ + tmp[i] = ptr0[i]; \ + tmp[i+_Tpvec::nlanes/2] = ptr1[i]; \ + } \ + return _Tpvec(wasm_v128_load(tmp)); \ +} \ +inline void v_store(_Tp* ptr, const _Tpvec& a) \ +{ wasm_v128_store(ptr, a.val); } \ +inline void v_store_aligned(_Tp* ptr, const _Tpvec& a) \ +{ wasm_v128_store(ptr, a.val); } \ +inline void v_store_aligned_nocache(_Tp* ptr, const _Tpvec& a) \ +{ wasm_v128_store(ptr, a.val); } \ +inline void v_store(_Tp* ptr, const _Tpvec& a, hal::StoreMode /*mode*/) \ +{ \ + wasm_v128_store(ptr, a.val); \ +} \ +inline void v_store_low(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ + ptr[i] = a_[i]; \ +} \ +inline void v_store_high(_Tp* ptr, const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + for (int i = 0; i < (_Tpvec::nlanes / 2); i++) \ + ptr[i] = a_[i + (_Tpvec::nlanes / 2)]; \ +} + +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint8x16, uchar) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int8x16, schar) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint16x8, ushort) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int16x8, short) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint32x4, unsigned) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int32x4, int) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_uint64x2, uint64) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_int64x2, int64) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float32x4, float) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INT_OP(v_float64x2, double) + + +/** Reverse **/ +inline v_uint8x16 v_reverse(const v_uint8x16 &a) +{ return v_uint8x16(wasm_i8x16_shuffle(a.val, a.val, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)); } + +inline v_int8x16 v_reverse(const v_int8x16 &a) +{ return v_reinterpret_as_s8(v_reverse(v_reinterpret_as_u8(a))); } + +inline v_uint16x8 v_reverse(const v_uint16x8 &a) +{ return v_uint16x8(wasm_i8x16_shuffle(a.val, a.val, 14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1)); } + +inline v_int16x8 v_reverse(const v_int16x8 &a) +{ return v_reinterpret_as_s16(v_reverse(v_reinterpret_as_u16(a))); } + +inline v_uint32x4 v_reverse(const v_uint32x4 &a) +{ return v_uint32x4(wasm_i8x16_shuffle(a.val, a.val, 12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3)); } + +inline v_int32x4 v_reverse(const v_int32x4 &a) +{ return v_reinterpret_as_s32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_float32x4 v_reverse(const v_float32x4 &a) +{ return v_reinterpret_as_f32(v_reverse(v_reinterpret_as_u32(a))); } + +inline v_uint64x2 v_reverse(const v_uint64x2 &a) +{ return v_uint64x2(wasm_i8x16_shuffle(a.val, a.val, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7)); } + +inline v_int64x2 v_reverse(const v_int64x2 &a) +{ return v_reinterpret_as_s64(v_reverse(v_reinterpret_as_u64(a))); } + +inline v_float64x2 v_reverse(const v_float64x2 &a) +{ return v_reinterpret_as_f64(v_reverse(v_reinterpret_as_u64(a))); } + + +#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + regtype val = a.val; \ + val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ + val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 4,5,6,7,8,9,10,11,12,13,14,15,0,1,2,3)); \ + return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ +} + +OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_uint32x4, unsigned, v128_t, i32x4, i32x4) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_int32x4, int, v128_t, i32x4, i32x4) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_4_SUM(v_float32x4, float, v128_t, f32x4, f32x4) + +// To do: Optimize v_reduce_sum with wasm intrin. +// Now use fallback implementation as there is no widening op in wasm intrin. + +#define OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(_Tpvec, scalartype) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + scalartype c = a_[0]; \ + for (int i = 1; i < _Tpvec::nlanes; i++) \ + c += a_[i]; \ + return c; \ +} + +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint8x16, unsigned) +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int8x16, int) +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_uint16x8, unsigned) +OPENCV_HAL_IMPL_FALLBACK_REDUCE_OP_SUM(v_int16x8, int) + + +#define OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(_Tpvec, scalartype, regtype, suffix, esuffix) \ +inline scalartype v_reduce_sum(const _Tpvec& a) \ +{ \ + regtype val = a.val; \ + val = wasm_##suffix##_add(val, wasm_i8x16_shuffle(val, val, 8,9,10,11,12,13,14,15,0,1,2,3,4,5,6,7)); \ + return (scalartype)wasm_##esuffix##_extract_lane(val, 0); \ +} +OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_uint64x2, uint64, v128_t, i64x2, i64x2) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_int64x2, int64, v128_t, i64x2, i64x2) +OPENCV_HAL_IMPL_WASM_REDUCE_OP_2_SUM(v_float64x2, double, v128_t, f64x2,f64x2) + +inline v_float32x4 v_reduce_sum4(const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d) +{ + v128_t ac = wasm_f32x4_add(wasm_unpacklo_i32x4(a.val, c.val), wasm_unpackhi_i32x4(a.val, c.val)); + v128_t bd = wasm_f32x4_add(wasm_unpacklo_i32x4(b.val, d.val), wasm_unpackhi_i32x4(b.val, d.val)); + return v_float32x4(wasm_f32x4_add(wasm_unpacklo_i32x4(ac, bd), wasm_unpackhi_i32x4(ac, bd))); +} + +#define OPENCV_HAL_IMPL_WASM_REDUCE_OP(_Tpvec, scalartype, func, scalar_func) \ +inline scalartype v_reduce_##func(const _Tpvec& a) \ +{ \ + scalartype buf[_Tpvec::nlanes]; \ + v_store(buf, a); \ + scalartype tmp = buf[0]; \ + for (int i=1; i<_Tpvec::nlanes; ++i) { \ + tmp = scalar_func(tmp, buf[i]); \ + } \ + return tmp; \ +} + +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint8x16, uchar, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int8x16, schar, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint16x8, ushort, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int16x8, short, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_uint32x4, unsigned, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_int32x4, int, min, std::min) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, max, std::max) +OPENCV_HAL_IMPL_WASM_REDUCE_OP(v_float32x4, float, min, std::min) + +inline unsigned v_reduce_sad(const v_uint8x16& a, const v_uint8x16& b) +{ + v_uint16x8 l16, h16; + v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; + v_expand(v_absdiff(a, b), l16, h16); + v_expand(l16, l16_l32, l16_h32); + v_expand(h16, h16_l32, h16_h32); + return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); +} +inline unsigned v_reduce_sad(const v_int8x16& a, const v_int8x16& b) +{ + v_uint16x8 l16, h16; + v_uint32x4 l16_l32, l16_h32, h16_l32, h16_h32; + v_expand(v_absdiff(a, b), l16, h16); + v_expand(l16, l16_l32, l16_h32); + v_expand(h16, h16_l32, h16_h32); + return v_reduce_sum(v_add(v_add(l16_l32, l16_h32), v_add(h16_l32, h16_h32))); +} +inline unsigned v_reduce_sad(const v_uint16x8& a, const v_uint16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_int16x8& a, const v_int16x8& b) +{ + v_uint32x4 l, h; + v_expand(v_absdiff(a, b), l, h); + return v_reduce_sum(v_add(l, h)); +} +inline unsigned v_reduce_sad(const v_uint32x4& a, const v_uint32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline unsigned v_reduce_sad(const v_int32x4& a, const v_int32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} +inline float v_reduce_sad(const v_float32x4& a, const v_float32x4& b) +{ + return v_reduce_sum(v_absdiff(a, b)); +} + +inline v_uint8x16 v_popcount(const v_uint8x16& a) +{ + v128_t m1 = wasm_i32x4_splat(0x55555555); + v128_t m2 = wasm_i32x4_splat(0x33333333); + v128_t m4 = wasm_i32x4_splat(0x0f0f0f0f); + v128_t p = a.val; + p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 1), m1), wasm_v128_and(p, m1)); + p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 2), m2), wasm_v128_and(p, m2)); + p = wasm_i32x4_add(wasm_v128_and(wasm_u32x4_shr(p, 4), m4), wasm_v128_and(p, m4)); + return v_uint8x16(p); +} +inline v_uint16x8 v_popcount(const v_uint16x8& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + return v_and(v_reinterpret_as_u16(p), v_setall_u16(0x00ff)); +} +inline v_uint32x4 v_popcount(const v_uint32x4& a) +{ + v_uint8x16 p = v_popcount(v_reinterpret_as_u8(a)); + p = v_add(p, v_rotate_right<1>(p)); + p = v_add(p, v_rotate_right<2>(p)); + return v_and(v_reinterpret_as_u32(p), v_setall_u32(0x000000ff)); +} +inline v_uint64x2 v_popcount(const v_uint64x2& a) +{ + uint64 a_[2], b_[2] = { 0 }; + wasm_v128_store(a_, a.val); + for (int i = 0; i < 16; i++) + b_[i / 8] += popCountTable[((uint8_t*)a_)[i]]; + return v_uint64x2(wasm_v128_load(b_)); +} +inline v_uint8x16 v_popcount(const v_int8x16& a) +{ return v_popcount(v_reinterpret_as_u8(a)); } +inline v_uint16x8 v_popcount(const v_int16x8& a) +{ return v_popcount(v_reinterpret_as_u16(a)); } +inline v_uint32x4 v_popcount(const v_int32x4& a) +{ return v_popcount(v_reinterpret_as_u32(a)); } +inline v_uint64x2 v_popcount(const v_int64x2& a) +{ return v_popcount(v_reinterpret_as_u64(a)); } + +#define OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(_Tpvec, suffix, scalarType) \ +inline int v_signmask(const _Tpvec& a) \ +{ \ + _Tpvec::lane_type a_[_Tpvec::nlanes]; \ + wasm_v128_store(a_, a.val); \ + int mask = 0; \ + for (int i = 0; i < _Tpvec::nlanes; i++) \ + mask |= (reinterpret_int(a_[i]) < 0) << i; \ + return mask; \ +} \ +inline bool v_check_all(const _Tpvec& a) \ +{ return wasm_i8x16_all_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0))); } \ +inline bool v_check_any(const _Tpvec& a) \ +{ return wasm_i8x16_any_true(wasm_##suffix##_lt(a.val, wasm_##suffix##_splat(0)));; } + +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint8x16, i8x16, schar) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int8x16, i8x16, schar) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint16x8, i16x8, short) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int16x8, i16x8, short) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_uint32x4, i32x4, int) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_int32x4, i32x4, int) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float32x4, i32x4, float) +OPENCV_HAL_IMPL_WASM_CHECK_SIGNS(v_float64x2, f64x2, double) + +#define OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(_Tpvec, suffix, esuffix) \ +inline bool v_check_all(const _Tpvec& a) \ +{ \ + v128_t masked = v_reinterpret_as_##esuffix(a).val; \ + masked = wasm_i32x4_replace_lane(masked, 0, 0xffffffff); \ + masked = wasm_i32x4_replace_lane(masked, 2, 0xffffffff); \ + return wasm_i8x16_all_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ +} \ +inline bool v_check_any(const _Tpvec& a) \ +{ \ + v128_t masked = v_reinterpret_as_##esuffix(a).val; \ + masked = wasm_i32x4_replace_lane(masked, 0, 0x0); \ + masked = wasm_i32x4_replace_lane(masked, 2, 0x0); \ + return wasm_i8x16_any_true(wasm_##suffix##_lt(masked, wasm_##suffix##_splat(0))); \ +} \ + +OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_int64x2, i32x4, s32) +OPENCV_HAL_IMPL_WASM_CHECK_ALL_ANY(v_uint64x2, i32x4, u32) + + +inline int v_scan_forward(const v_int8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_uint8x16& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))); } +inline int v_scan_forward(const v_int16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_uint16x8& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 2; } +inline int v_scan_forward(const v_int32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_uint32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_float32x4& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 4; } +inline int v_scan_forward(const v_int64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_uint64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } +inline int v_scan_forward(const v_float64x2& a) { return trailingZeros32(v_signmask(v_reinterpret_as_s8(a))) / 8; } + +#define OPENCV_HAL_IMPL_WASM_SELECT(_Tpvec) \ +inline _Tpvec v_select(const _Tpvec& mask, const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_v128_bitselect(a.val, b.val, mask.val)); \ +} + +OPENCV_HAL_IMPL_WASM_SELECT(v_uint8x16) +OPENCV_HAL_IMPL_WASM_SELECT(v_int8x16) +OPENCV_HAL_IMPL_WASM_SELECT(v_uint16x8) +OPENCV_HAL_IMPL_WASM_SELECT(v_int16x8) +OPENCV_HAL_IMPL_WASM_SELECT(v_uint32x4) +OPENCV_HAL_IMPL_WASM_SELECT(v_int32x4) +OPENCV_HAL_IMPL_WASM_SELECT(v_uint64x2) +OPENCV_HAL_IMPL_WASM_SELECT(v_int64x2) +OPENCV_HAL_IMPL_WASM_SELECT(v_float32x4) +OPENCV_HAL_IMPL_WASM_SELECT(v_float64x2) + +#define OPENCV_HAL_IMPL_WASM_EXPAND(_Tpvec, _Tpwvec, _Tp, intrin) \ +inline void v_expand(const _Tpvec& a, _Tpwvec& b0, _Tpwvec& b1) \ +{ \ + b0.val = intrin(a.val); \ + b1.val = __CV_CAT(intrin, _high)(a.val); \ +} \ +inline _Tpwvec v_expand_low(const _Tpvec& a) \ +{ return _Tpwvec(intrin(a.val)); } \ +inline _Tpwvec v_expand_high(const _Tpvec& a) \ +{ return _Tpwvec(__CV_CAT(intrin, _high)(a.val)); } \ +inline _Tpwvec v_load_expand(const _Tp* ptr) \ +{ \ + v128_t a = wasm_v128_load(ptr); \ + return _Tpwvec(intrin(a)); \ +} + +OPENCV_HAL_IMPL_WASM_EXPAND(v_uint8x16, v_uint16x8, uchar, v128_cvtu8x16_i16x8) +OPENCV_HAL_IMPL_WASM_EXPAND(v_int8x16, v_int16x8, schar, v128_cvti8x16_i16x8) +OPENCV_HAL_IMPL_WASM_EXPAND(v_uint16x8, v_uint32x4, ushort, v128_cvtu16x8_i32x4) +OPENCV_HAL_IMPL_WASM_EXPAND(v_int16x8, v_int32x4, short, v128_cvti16x8_i32x4) +OPENCV_HAL_IMPL_WASM_EXPAND(v_uint32x4, v_uint64x2, unsigned, v128_cvtu32x4_i64x2) +OPENCV_HAL_IMPL_WASM_EXPAND(v_int32x4, v_int64x2, int, v128_cvti32x4_i64x2) + +#define OPENCV_HAL_IMPL_WASM_EXPAND_Q(_Tpvec, _Tp, intrin) \ +inline _Tpvec v_load_expand_q(const _Tp* ptr) \ +{ \ + v128_t a = wasm_v128_load(ptr); \ + return _Tpvec(intrin(a)); \ +} + +OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_uint32x4, uchar, v128_cvtu8x16_i32x4) +OPENCV_HAL_IMPL_WASM_EXPAND_Q(v_int32x4, schar, v128_cvti8x16_i32x4) + +#define OPENCV_HAL_IMPL_WASM_UNPACKS(_Tpvec, suffix) \ +inline void v_zip(const _Tpvec& a0, const _Tpvec& a1, _Tpvec& b0, _Tpvec& b1) \ +{ \ + b0.val = wasm_unpacklo_##suffix(a0.val, a1.val); \ + b1.val = wasm_unpackhi_##suffix(a0.val, a1.val); \ +} \ +inline _Tpvec v_combine_low(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_unpacklo_i64x2(a.val, b.val)); \ +} \ +inline _Tpvec v_combine_high(const _Tpvec& a, const _Tpvec& b) \ +{ \ + return _Tpvec(wasm_unpackhi_i64x2(a.val, b.val)); \ +} \ +inline void v_recombine(const _Tpvec& a, const _Tpvec& b, _Tpvec& c, _Tpvec& d) \ +{ \ + c.val = wasm_unpacklo_i64x2(a.val, b.val); \ + d.val = wasm_unpackhi_i64x2(a.val, b.val); \ +} + +OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint8x16, i8x16) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_int8x16, i8x16) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint16x8, i16x8) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_int16x8, i16x8) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_uint32x4, i32x4) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_int32x4, i32x4) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_float32x4, i32x4) +OPENCV_HAL_IMPL_WASM_UNPACKS(v_float64x2, i64x2) + +template +inline _Tpvec v_extract(const _Tpvec& a, const _Tpvec& b) +{ + return v_rotate_right(a, b); +} + +inline v_int32x4 v_round(const v_float32x4& a) +{ + v128_t h = wasm_f32x4_splat(0.5); + return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(wasm_f32x4_add(a.val, h))); +} + +inline v_int32x4 v_floor(const v_float32x4& a) +{ + v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); + v128_t mask = wasm_f32x4_lt(a.val, wasm_f32x4_convert_i32x4(a1)); + return v_int32x4(wasm_i32x4_add(a1, mask)); +} + +inline v_int32x4 v_ceil(const v_float32x4& a) +{ + v128_t a1 = wasm_i32x4_trunc_saturate_f32x4(a.val); + v128_t mask = wasm_f32x4_gt(a.val, wasm_f32x4_convert_i32x4(a1)); + return v_int32x4(wasm_i32x4_sub(a1, mask)); +} + +inline v_int32x4 v_trunc(const v_float32x4& a) +{ return v_int32x4(wasm_i32x4_trunc_saturate_f32x4(a.val)); } + +#define OPENCV_HAL_IMPL_WASM_MATH_FUNC(func, cfunc) \ +inline v_int32x4 func(const v_float64x2& a) \ +{ \ + double a_[2]; \ + wasm_v128_store(a_, a.val); \ + int c_[4]; \ + c_[0] = cfunc(a_[0]); \ + c_[1] = cfunc(a_[1]); \ + c_[2] = 0; \ + c_[3] = 0; \ + return v_int32x4(wasm_v128_load(c_)); \ +} + +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_round, cvRound) +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_floor, cvFloor) +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_ceil, cvCeil) +OPENCV_HAL_IMPL_WASM_MATH_FUNC(v_trunc, int) + +inline v_int32x4 v_round(const v_float64x2& a, const v_float64x2& b) +{ + double a_[2], b_[2]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + int c_[4]; + c_[0] = cvRound(a_[0]); + c_[1] = cvRound(a_[1]); + c_[2] = cvRound(b_[0]); + c_[3] = cvRound(b_[1]); + return v_int32x4(wasm_v128_load(c_)); +} + +#define OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(_Tpvec, suffix) \ +inline void v_transpose4x4(const _Tpvec& a0, const _Tpvec& a1, \ + const _Tpvec& a2, const _Tpvec& a3, \ + _Tpvec& b0, _Tpvec& b1, \ + _Tpvec& b2, _Tpvec& b3) \ +{ \ + v128_t t0 = wasm_unpacklo_##suffix(a0.val, a1.val); \ + v128_t t1 = wasm_unpacklo_##suffix(a2.val, a3.val); \ + v128_t t2 = wasm_unpackhi_##suffix(a0.val, a1.val); \ + v128_t t3 = wasm_unpackhi_##suffix(a2.val, a3.val); \ +\ + b0.val = wasm_unpacklo_i64x2(t0, t1); \ + b1.val = wasm_unpackhi_i64x2(t0, t1); \ + b2.val = wasm_unpacklo_i64x2(t2, t3); \ + b3.val = wasm_unpackhi_i64x2(t2, t3); \ +} + +OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_uint32x4, i32x4) +OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_int32x4, i32x4) +OPENCV_HAL_IMPL_WASM_TRANSPOSE4x4(v_float32x4, i32x4) + +// load deinterleave +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b) +{ + v128_t t00 = wasm_v128_load(ptr); + v128_t t01 = wasm_v128_load(ptr + 16); + + a.val = wasm_i8x16_shuffle(t00, t01, 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30); + b.val = wasm_i8x16_shuffle(t00, t01, 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c) +{ + v128_t t00 = wasm_v128_load(ptr); + v128_t t01 = wasm_v128_load(ptr + 16); + v128_t t02 = wasm_v128_load(ptr + 32); + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,3,6,9,12,15,18,21,24,27,30,1,2,4,5,7); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 1,4,7,10,13,16,19,22,25,28,31,0,2,3,5,6); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 2,5,8,11,14,17,20,23,26,29,0,1,3,4,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,17,20,23,26,29); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,18,21,24,27,30); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,16,19,22,25,28,31); +} + +inline void v_load_deinterleave(const uchar* ptr, v_uint8x16& a, v_uint8x16& b, v_uint8x16& c, v_uint8x16& d) +{ + v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 ... + v128_t u1 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... + v128_t u2 = wasm_v128_load(ptr + 32); // a8 b8 c8 d8 ... + v128_t u3 = wasm_v128_load(ptr + 48); // a12 b12 c12 d12 ... + + v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); + v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,4,8,12,16,20,24,28,1,5,9,13,17,21,25,29); + v128_t v2 = wasm_i8x16_shuffle(u0, u1, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); + v128_t v3 = wasm_i8x16_shuffle(u2, u3, 2,6,10,14,18,22,26,30,3,7,11,15,19,23,27,31); + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); + c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b) +{ + v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 a2 b2 a3 b3 + v128_t v1 = wasm_v128_load(ptr + 8); // a4 b4 a5 b5 a6 b6 a7 b7 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,4,5,8,9,12,13,16,17,20,21,24,25,28,29); // a0 a1 a2 a3 a4 a5 a6 a7 + b.val = wasm_i8x16_shuffle(v0, v1, 2,3,6,7,10,11,14,15,18,19,22,23,26,27,30,31); // b0 b1 ab b3 b4 b5 b6 b7 +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c) +{ + v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 b1 c1 a2 b2 + v128_t t01 = wasm_v128_load(ptr + 8); // c2 a3 b3 c3 a4 b4 c4 a5 + v128_t t02 = wasm_v128_load(ptr + 16); // b5 c5 a6 b6 c6 a7 b7 c7 + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,6,7,12,13,18,19,24,25,30,31,2,3,4,5); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 2,3,8,9,14,15,20,21,26,27,0,1,4,5,6,7); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 4,5,10,11,16,17,22,23,28,29,0,1,2,3,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,26,27); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,16,17,22,23,28,29); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,8,9,18,19,24,25,30,31); +} + +inline void v_load_deinterleave(const ushort* ptr, v_uint16x8& a, v_uint16x8& b, v_uint16x8& c, v_uint16x8& d) +{ + v128_t u0 = wasm_v128_load(ptr); // a0 b0 c0 d0 a1 b1 c1 d1 + v128_t u1 = wasm_v128_load(ptr + 8); // a2 b2 c2 d2 ... + v128_t u2 = wasm_v128_load(ptr + 16); // a4 b4 c4 d4 ... + v128_t u3 = wasm_v128_load(ptr + 24); // a6 b6 c6 d6 ... + + v128_t v0 = wasm_i8x16_shuffle(u0, u1, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a0 a1 a2 a3 b0 b1 b2 b3 + v128_t v1 = wasm_i8x16_shuffle(u2, u3, 0,1,8,9,16,17,24,25,2,3,10,11,18,19,26,27); // a4 a5 a6 a7 b4 b5 b6 b7 + v128_t v2 = wasm_i8x16_shuffle(u0, u1, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c0 c1 c2 c3 d0 d1 d2 d3 + v128_t v3 = wasm_i8x16_shuffle(u2, u3, 4,5,12,13,20,21,28,29,6,7,14,15,22,23,30,31); // c4 c5 c6 c7 d4 d5 d6 d7 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + b.val = wasm_i8x16_shuffle(v0, v1, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); + c.val = wasm_i8x16_shuffle(v2, v3, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + d.val = wasm_i8x16_shuffle(v2, v3, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b) +{ + v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 + v128_t v1 = wasm_v128_load(ptr + 4); // a2 b2 a3 b3 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 + b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c) +{ + v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 + v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 + v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); +} + +inline void v_load_deinterleave(const unsigned* ptr, v_uint32x4& a, v_uint32x4& b, v_uint32x4& c, v_uint32x4& d) +{ + v_uint32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 + v_uint32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 + v_uint32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 + v_uint32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 + + v_transpose4x4(s0, s1, s2, s3, a, b, c, d); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b) +{ + v128_t v0 = wasm_v128_load(ptr); // a0 b0 a1 b1 + v128_t v1 = wasm_v128_load((ptr + 4)); // a2 b2 a3 b3 + + a.val = wasm_i8x16_shuffle(v0, v1, 0,1,2,3,8,9,10,11,16,17,18,19,24,25,26,27); // a0 a1 a2 a3 + b.val = wasm_i8x16_shuffle(v0, v1, 4,5,6,7,12,13,14,15,20,21,22,23,28,29,30,31); // b0 b1 b2 b3 +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c) +{ + v128_t t00 = wasm_v128_load(ptr); // a0 b0 c0 a1 + v128_t t01 = wasm_v128_load(ptr + 4); // b2 c2 a3 b3 + v128_t t02 = wasm_v128_load(ptr + 8); // c3 a4 b4 c4 + + v128_t t10 = wasm_i8x16_shuffle(t00, t01, 0,1,2,3,12,13,14,15,24,25,26,27,4,5,6,7); + v128_t t11 = wasm_i8x16_shuffle(t00, t01, 4,5,6,7,16,17,18,19,28,29,30,31,0,1,2,3); + v128_t t12 = wasm_i8x16_shuffle(t00, t01, 8,9,10,11,20,21,22,23,0,1,2,3,4,5,6,7); + + a.val = wasm_i8x16_shuffle(t10, t02, 0,1,2,3,4,5,6,7,8,9,10,11,20,21,22,23); + b.val = wasm_i8x16_shuffle(t11, t02, 0,1,2,3,4,5,6,7,8,9,10,11,24,25,26,27); + c.val = wasm_i8x16_shuffle(t12, t02, 0,1,2,3,4,5,6,7,16,17,18,19,28,29,30,31); +} + +inline void v_load_deinterleave(const float* ptr, v_float32x4& a, v_float32x4& b, v_float32x4& c, v_float32x4& d) +{ + v_float32x4 s0(wasm_v128_load(ptr)); // a0 b0 c0 d0 + v_float32x4 s1(wasm_v128_load(ptr + 4)); // a1 b1 c1 d1 + v_float32x4 s2(wasm_v128_load(ptr + 8)); // a2 b2 c2 d2 + v_float32x4 s3(wasm_v128_load(ptr + 12)); // a3 b3 c3 d3 + + v_transpose4x4(s0, s1, s2, s3, a, b, c, d); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b) +{ + v128_t t0 = wasm_v128_load(ptr); // a0 b0 + v128_t t1 = wasm_v128_load(ptr + 2); // a1 b1 + + a.val = wasm_unpacklo_i64x2(t0, t1); + b.val = wasm_unpackhi_i64x2(t0, t1); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, v_uint64x2& b, v_uint64x2& c) +{ + v128_t t0 = wasm_v128_load(ptr); // a0, b0 + v128_t t1 = wasm_v128_load(ptr + 2); // c0, a1 + v128_t t2 = wasm_v128_load(ptr + 4); // b1, c1 + + a.val = wasm_i8x16_shuffle(t0, t1, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); + b.val = wasm_i8x16_shuffle(t0, t2, 8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23); + c.val = wasm_i8x16_shuffle(t1, t2, 0,1,2,3,4,5,6,7,24,25,26,27,28,29,30,31); +} + +inline void v_load_deinterleave(const uint64 *ptr, v_uint64x2& a, + v_uint64x2& b, v_uint64x2& c, v_uint64x2& d) +{ + v128_t t0 = wasm_v128_load(ptr); // a0 b0 + v128_t t1 = wasm_v128_load(ptr + 2); // c0 d0 + v128_t t2 = wasm_v128_load(ptr + 4); // a1 b1 + v128_t t3 = wasm_v128_load(ptr + 6); // c1 d1 + + a.val = wasm_unpacklo_i64x2(t0, t2); + b.val = wasm_unpackhi_i64x2(t0, t2); + c.val = wasm_unpacklo_i64x2(t1, t3); + d.val = wasm_unpackhi_i64x2(t1, t3); +} + +// store interleave + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i8x16(a.val, b.val); + v128_t v1 = wasm_unpackhi_i8x16(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 16, v1); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,16,0,1,17,0,2,18,0,3,19,0,4,20,0,5); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 21,0,6,22,0,7,23,0,8,24,0,9,25,0,10,26); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,11,27,0,12,28,0,13,29,0,14,30,0,15,31,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,16,3,4,17,6,7,18,9,10,19,12,13,20,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,21,2,3,22,5,6,23,8,9,24,11,12,25,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 26,1,2,27,4,5,28,7,8,29,10,11,30,13,14,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 16, t11); + wasm_v128_store(ptr + 32, t12); +} + +inline void v_store_interleave( uchar* ptr, const v_uint8x16& a, const v_uint8x16& b, + const v_uint8x16& c, const v_uint8x16& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + v128_t u0 = wasm_unpacklo_i8x16(a.val, c.val); // a0 c0 a1 c1 ... + v128_t u1 = wasm_unpackhi_i8x16(a.val, c.val); // a8 c8 a9 c9 ... + v128_t u2 = wasm_unpacklo_i8x16(b.val, d.val); // b0 d0 b1 d1 ... + v128_t u3 = wasm_unpackhi_i8x16(b.val, d.val); // b8 d8 b9 d9 ... + + v128_t v0 = wasm_unpacklo_i8x16(u0, u2); // a0 b0 c0 d0 ... + v128_t v1 = wasm_unpackhi_i8x16(u0, u2); // a4 b4 c4 d4 ... + v128_t v2 = wasm_unpacklo_i8x16(u1, u3); // a8 b8 c8 d8 ... + v128_t v3 = wasm_unpackhi_i8x16(u1, u3); // a12 b12 c12 d12 ... + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 16, v1); + wasm_v128_store(ptr + 32, v2); + wasm_v128_store(ptr + 48, v3); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i16x8(a.val, b.val); + v128_t v1 = wasm_unpackhi_i16x8(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 8, v1); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, + const v_uint16x8& b, const v_uint16x8& c, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,16,17,0,0,2,3,18,19,0,0,4,5,20,21); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 0,0,6,7,22,23,0,0,8,9,24,25,0,0,10,11); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 26,27,0,0,12,13,28,29,0,0,14,15,30,31,0,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,16,17,6,7,8,9,18,19,12,13,14,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 20,21,2,3,4,5,22,23,8,9,10,11,24,25,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 0,1,26,27,4,5,6,7,28,29,10,11,12,13,30,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 8, t11); + wasm_v128_store(ptr + 16, t12); +} + +inline void v_store_interleave( ushort* ptr, const v_uint16x8& a, const v_uint16x8& b, + const v_uint16x8& c, const v_uint16x8& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + // a0 a1 a2 a3 .... + // b0 b1 b2 b3 .... + // c0 c1 c2 c3 .... + // d0 d1 d2 d3 .... + v128_t u0 = wasm_unpacklo_i16x8(a.val, c.val); // a0 c0 a1 c1 ... + v128_t u1 = wasm_unpackhi_i16x8(a.val, c.val); // a4 c4 a5 c5 ... + v128_t u2 = wasm_unpacklo_i16x8(b.val, d.val); // b0 d0 b1 d1 ... + v128_t u3 = wasm_unpackhi_i16x8(b.val, d.val); // b4 d4 b5 d5 ... + + v128_t v0 = wasm_unpacklo_i16x8(u0, u2); // a0 b0 c0 d0 ... + v128_t v1 = wasm_unpackhi_i16x8(u0, u2); // a2 b2 c2 d2 ... + v128_t v2 = wasm_unpacklo_i16x8(u1, u3); // a4 b4 c4 d4 ... + v128_t v3 = wasm_unpackhi_i16x8(u1, u3); // a6 b6 c6 d6 ... + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 8, v1); + wasm_v128_store(ptr + 16, v2); + wasm_v128_store(ptr + 24, v3); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); + v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 4, v1); +} + +inline void v_store_interleave( unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 4, t11); + wasm_v128_store(ptr + 8, t12); +} + +inline void v_store_interleave(unsigned* ptr, const v_uint32x4& a, const v_uint32x4& b, + const v_uint32x4& c, const v_uint32x4& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v_uint32x4 v0, v1, v2, v3; + v_transpose4x4(a, b, c, d, v0, v1, v2, v3); + + wasm_v128_store(ptr, v0.val); + wasm_v128_store(ptr + 4, v1.val); + wasm_v128_store(ptr + 8, v2.val); + wasm_v128_store(ptr + 12, v3.val); +} + +// 2-channel, float only +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i32x4(a.val, b.val); + v128_t v1 = wasm_unpackhi_i32x4(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 4, v1); +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t t00 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,16,17,18,19,0,0,0,0,4,5,6,7); + v128_t t01 = wasm_i8x16_shuffle(a.val, b.val, 20,21,22,23,0,0,0,0,8,9,10,11,24,25,26,27); + v128_t t02 = wasm_i8x16_shuffle(a.val, b.val, 0,0,0,0,12,13,14,15,28,29,30,31,0,0,0,0); + + v128_t t10 = wasm_i8x16_shuffle(t00, c.val, 0,1,2,3,4,5,6,7,16,17,18,19,12,13,14,15); + v128_t t11 = wasm_i8x16_shuffle(t01, c.val, 0,1,2,3,20,21,22,23,8,9,10,11,12,13,14,15); + v128_t t12 = wasm_i8x16_shuffle(t02, c.val, 24,25,26,27,4,5,6,7,8,9,10,11,28,29,30,31); + + wasm_v128_store(ptr, t10); + wasm_v128_store(ptr + 4, t11); + wasm_v128_store(ptr + 8, t12); +} + +inline void v_store_interleave(float* ptr, const v_float32x4& a, const v_float32x4& b, + const v_float32x4& c, const v_float32x4& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v_float32x4 v0, v1, v2, v3; + v_transpose4x4(a, b, c, d, v0, v1, v2, v3); + + wasm_v128_store(ptr, v0.val); + wasm_v128_store(ptr + 4, v1.val); + wasm_v128_store(ptr + 8, v2.val); + wasm_v128_store(ptr + 12, v3.val); +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); + v128_t v1 = wasm_unpackhi_i64x2(a.val, b.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 2, v1); +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_i8x16_shuffle(a.val, b.val, 0,1,2,3,4,5,6,7,16,17,18,19,20,21,22,23); + v128_t v1 = wasm_i8x16_shuffle(a.val, c.val, 16,17,18,19,20,21,22,23,8,9,10,11,12,13,14,15); + v128_t v2 = wasm_i8x16_shuffle(b.val, c.val, 8,9,10,11,12,13,14,15,24,25,26,27,28,29,30,31); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 2, v1); + wasm_v128_store(ptr + 4, v2); +} + +inline void v_store_interleave(uint64 *ptr, const v_uint64x2& a, const v_uint64x2& b, + const v_uint64x2& c, const v_uint64x2& d, + hal::StoreMode /*mode*/ = hal::STORE_UNALIGNED) +{ + v128_t v0 = wasm_unpacklo_i64x2(a.val, b.val); + v128_t v1 = wasm_unpacklo_i64x2(c.val, d.val); + v128_t v2 = wasm_unpackhi_i64x2(a.val, b.val); + v128_t v3 = wasm_unpackhi_i64x2(c.val, d.val); + + wasm_v128_store(ptr, v0); + wasm_v128_store(ptr + 2, v1); + wasm_v128_store(ptr + 4, v2); + wasm_v128_store(ptr + 6, v3); +} + +#define OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(_Tpvec0, _Tp0, suffix0, _Tpvec1, _Tp1, suffix1) \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0 ) \ +{ \ + _Tpvec1 a1, b1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0 ) \ +{ \ + _Tpvec1 a1, b1, c1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ +} \ +inline void v_load_deinterleave( const _Tp0* ptr, _Tpvec0& a0, _Tpvec0& b0, _Tpvec0& c0, _Tpvec0& d0 ) \ +{ \ + _Tpvec1 a1, b1, c1, d1; \ + v_load_deinterleave((const _Tp1*)ptr, a1, b1, c1, d1); \ + a0 = v_reinterpret_as_##suffix0(a1); \ + b0 = v_reinterpret_as_##suffix0(b1); \ + c0 = v_reinterpret_as_##suffix0(c1); \ + d0 = v_reinterpret_as_##suffix0(d1); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, mode); \ +} \ +inline void v_store_interleave( _Tp0* ptr, const _Tpvec0& a0, const _Tpvec0& b0, \ + const _Tpvec0& c0, const _Tpvec0& d0, \ + hal::StoreMode mode = hal::STORE_UNALIGNED ) \ +{ \ + _Tpvec1 a1 = v_reinterpret_as_##suffix1(a0); \ + _Tpvec1 b1 = v_reinterpret_as_##suffix1(b0); \ + _Tpvec1 c1 = v_reinterpret_as_##suffix1(c0); \ + _Tpvec1 d1 = v_reinterpret_as_##suffix1(d0); \ + v_store_interleave((_Tp1*)ptr, a1, b1, c1, d1, mode); \ +} + +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int8x16, schar, s8, v_uint8x16, uchar, u8) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int16x8, short, s16, v_uint16x8, ushort, u16) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int32x4, int, s32, v_uint32x4, unsigned, u32) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_int64x2, int64, s64, v_uint64x2, uint64, u64) +OPENCV_HAL_IMPL_WASM_LOADSTORE_INTERLEAVE(v_float64x2, double, f64, v_uint64x2, uint64, u64) + +inline v_float32x4 v_cvt_f32(const v_int32x4& a) +{ + return v_float32x4(wasm_f32x4_convert_i32x4(a.val)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a) +{ + double a_[2]; + wasm_v128_store(a_, a.val); + float c_[4]; + c_[0] = (float)(a_[0]); + c_[1] = (float)(a_[1]); + c_[2] = 0; + c_[3] = 0; + return v_float32x4(wasm_v128_load(c_)); +} + +inline v_float32x4 v_cvt_f32(const v_float64x2& a, const v_float64x2& b) +{ + double a_[2], b_[2]; + wasm_v128_store(a_, a.val); + wasm_v128_store(b_, b.val); + float c_[4]; + c_[0] = (float)(a_[0]); + c_[1] = (float)(a_[1]); + c_[2] = (float)(b_[0]); + c_[3] = (float)(b_[1]); + return v_float32x4(wasm_v128_load(c_)); +} + +inline v_float64x2 v_cvt_f64(const v_int32x4& a) +{ +#ifdef __wasm_unimplemented_simd128__ + v128_t p = v128_cvti32x4_i64x2(a.val); + return v_float64x2(wasm_f64x2_convert_i64x2(p)); +#else + int a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[0]); + c_[1] = (double)(a_[1]); + return v_float64x2(wasm_v128_load(c_)); +#endif +} + +inline v_float64x2 v_cvt_f64_high(const v_int32x4& a) +{ +#ifdef __wasm_unimplemented_simd128__ + v128_t p = v128_cvti32x4_i64x2_high(a.val); + return v_float64x2(wasm_f64x2_convert_i64x2(p)); +#else + int a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[2]); + c_[1] = (double)(a_[3]); + return v_float64x2(wasm_v128_load(c_)); +#endif +} + +inline v_float64x2 v_cvt_f64(const v_float32x4& a) +{ + float a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[0]); + c_[1] = (double)(a_[1]); + return v_float64x2(wasm_v128_load(c_)); +} + +inline v_float64x2 v_cvt_f64_high(const v_float32x4& a) +{ + float a_[4]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[2]); + c_[1] = (double)(a_[3]); + return v_float64x2(wasm_v128_load(c_)); +} + +inline v_float64x2 v_cvt_f64(const v_int64x2& a) +{ +#ifdef __wasm_unimplemented_simd128__ + return v_float64x2(wasm_f64x2_convert_i64x2(a.val)); +#else + int64 a_[2]; + wasm_v128_store(a_, a.val); + double c_[2]; + c_[0] = (double)(a_[0]); + c_[1] = (double)(a_[1]); + return v_float64x2(wasm_v128_load(c_)); +#endif +} + +////////////// Lookup table access //////////////////// + +inline v_int8x16 v_lut(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[1]], tab[idx[ 2]], tab[idx[ 3]], tab[idx[ 4]], tab[idx[ 5]], tab[idx[ 6]], tab[idx[ 7]], + tab[idx[8]], tab[idx[9]], tab[idx[10]], tab[idx[11]], tab[idx[12]], tab[idx[13]], tab[idx[14]], tab[idx[15]]); +} +inline v_int8x16 v_lut_pairs(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1], + tab[idx[4]], tab[idx[4]+1], tab[idx[5]], tab[idx[5]+1], tab[idx[6]], tab[idx[6]+1], tab[idx[7]], tab[idx[7]+1]); +} +inline v_int8x16 v_lut_quads(const schar* tab, const int* idx) +{ + return v_int8x16(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3], + tab[idx[2]], tab[idx[2]+1], tab[idx[2]+2], tab[idx[2]+3], tab[idx[3]], tab[idx[3]+1], tab[idx[3]+2], tab[idx[3]+3]); +} +inline v_uint8x16 v_lut(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_pairs(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_pairs((const schar *)tab, idx)); } +inline v_uint8x16 v_lut_quads(const uchar* tab, const int* idx) { return v_reinterpret_as_u8(v_lut_quads((const schar *)tab, idx)); } + +inline v_int16x8 v_lut(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]], + tab[idx[4]], tab[idx[5]], tab[idx[6]], tab[idx[7]]); +} +inline v_int16x8 v_lut_pairs(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[1]], tab[idx[1]+1], + tab[idx[2]], tab[idx[2]+1], tab[idx[3]], tab[idx[3]+1]); +} +inline v_int16x8 v_lut_quads(const short* tab, const int* idx) +{ + return v_int16x8(tab[idx[0]], tab[idx[0]+1], tab[idx[0]+2], tab[idx[0]+3], + tab[idx[1]], tab[idx[1]+1], tab[idx[1]+2], tab[idx[1]+3]); +} +inline v_uint16x8 v_lut(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut((const short *)tab, idx)); } +inline v_uint16x8 v_lut_pairs(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_pairs((const short *)tab, idx)); } +inline v_uint16x8 v_lut_quads(const ushort* tab, const int* idx) { return v_reinterpret_as_u16(v_lut_quads((const short *)tab, idx)); } + +inline v_int32x4 v_lut(const int* tab, const int* idx) +{ + return v_int32x4(tab[idx[0]], tab[idx[1]], + tab[idx[2]], tab[idx[3]]); +} +inline v_int32x4 v_lut_pairs(const int* tab, const int* idx) +{ + return v_int32x4(tab[idx[0]], tab[idx[0]+1], + tab[idx[1]], tab[idx[1]+1]); +} +inline v_int32x4 v_lut_quads(const int* tab, const int* idx) +{ + return v_int32x4(wasm_v128_load(tab + idx[0])); +} +inline v_uint32x4 v_lut(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut((const int *)tab, idx)); } +inline v_uint32x4 v_lut_pairs(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_pairs((const int *)tab, idx)); } +inline v_uint32x4 v_lut_quads(const unsigned* tab, const int* idx) { return v_reinterpret_as_u32(v_lut_quads((const int *)tab, idx)); } + +inline v_int64x2 v_lut(const int64_t* tab, const int* idx) +{ + return v_int64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_int64x2 v_lut_pairs(const int64_t* tab, const int* idx) +{ + return v_int64x2(wasm_v128_load(tab + idx[0])); +} +inline v_uint64x2 v_lut(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut((const int64_t *)tab, idx)); } +inline v_uint64x2 v_lut_pairs(const uint64_t* tab, const int* idx) { return v_reinterpret_as_u64(v_lut_pairs((const int64_t *)tab, idx)); } + +inline v_float32x4 v_lut(const float* tab, const int* idx) +{ + return v_float32x4(tab[idx[0]], tab[idx[1]], tab[idx[2]], tab[idx[3]]); +} +inline v_float32x4 v_lut_pairs(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_pairs((const int *)tab, idx)); } +inline v_float32x4 v_lut_quads(const float* tab, const int* idx) { return v_reinterpret_as_f32(v_lut_quads((const int *)tab, idx)); } + +inline v_float64x2 v_lut(const double* tab, const int* idx) +{ + return v_float64x2(tab[idx[0]], tab[idx[1]]); +} +inline v_float64x2 v_lut_pairs(const double* tab, const int* idx) +{ + return v_float64x2(wasm_v128_load(tab + idx[0])); +} + +inline v_int32x4 v_lut(const int* tab, const v_int32x4& idxvec) +{ + return v_int32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); +} + +inline v_uint32x4 v_lut(const unsigned* tab, const v_int32x4& idxvec) +{ + return v_reinterpret_as_u32(v_lut((const int *)tab, idxvec)); +} + +inline v_float32x4 v_lut(const float* tab, const v_int32x4& idxvec) +{ + return v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); +} + +inline v_float64x2 v_lut(const double* tab, const v_int32x4& idxvec) +{ + return v_float64x2(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)]); +} + +// loads pairs from the table and deinterleaves them, e.g. returns: +// x = (tab[idxvec[0], tab[idxvec[1]], tab[idxvec[2]], tab[idxvec[3]]), +// y = (tab[idxvec[0]+1], tab[idxvec[1]+1], tab[idxvec[2]+1], tab[idxvec[3]+1]) +// note that the indices are float's indices, not the float-pair indices. +// in theory, this function can be used to implement bilinear interpolation, +// when idxvec are the offsets within the image. +inline void v_lut_deinterleave(const float* tab, const v_int32x4& idxvec, v_float32x4& x, v_float32x4& y) +{ + x = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)]); + y = v_float32x4(tab[wasm_i32x4_extract_lane(idxvec.val, 0)+1], + tab[wasm_i32x4_extract_lane(idxvec.val, 1)+1], + tab[wasm_i32x4_extract_lane(idxvec.val, 2)+1], + tab[wasm_i32x4_extract_lane(idxvec.val, 3)+1]); +} + +inline void v_lut_deinterleave(const double* tab, const v_int32x4& idxvec, v_float64x2& x, v_float64x2& y) +{ + v128_t xy0 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 0)); + v128_t xy1 = wasm_v128_load(tab + wasm_i32x4_extract_lane(idxvec.val, 1)); + x.val = wasm_unpacklo_i64x2(xy0, xy1); + y.val = wasm_unpacklo_i64x2(xy0, xy1); +} + +inline v_int8x16 v_interleave_pairs(const v_int8x16& vec) +{ + return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,2,1,3,4,6,5,7,8,10,9,11,12,14,13,15)); +} +inline v_uint8x16 v_interleave_pairs(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_pairs(v_reinterpret_as_s8(vec))); } +inline v_int8x16 v_interleave_quads(const v_int8x16& vec) +{ + return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,4,1,5,2,6,3,7,8,12,9,13,10,14,11,15)); +} +inline v_uint8x16 v_interleave_quads(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_interleave_quads(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_interleave_pairs(const v_int16x8& vec) +{ + return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,4,5,2,3,6,7,8,9,12,13,10,11,14,15)); +} +inline v_uint16x8 v_interleave_pairs(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_pairs(v_reinterpret_as_s16(vec))); } +inline v_int16x8 v_interleave_quads(const v_int16x8& vec) +{ + return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,8,9,2,3,10,11,4,5,12,13,6,7,14,15)); +} +inline v_uint16x8 v_interleave_quads(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_interleave_quads(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_interleave_pairs(const v_int32x4& vec) +{ + return v_int32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); +} +inline v_uint32x4 v_interleave_pairs(const v_uint32x4& vec) { return v_reinterpret_as_u32(v_interleave_pairs(v_reinterpret_as_s32(vec))); } +inline v_float32x4 v_interleave_pairs(const v_float32x4& vec) +{ + return v_float32x4(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,8,9,10,11,4,5,6,7,12,13,14,15)); +} + +inline v_int8x16 v_pack_triplets(const v_int8x16& vec) +{ + return v_int8x16(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,4,5,6,8,9,10,12,13,14,16,16,16,16)); +} +inline v_uint8x16 v_pack_triplets(const v_uint8x16& vec) { return v_reinterpret_as_u8(v_pack_triplets(v_reinterpret_as_s8(vec))); } + +inline v_int16x8 v_pack_triplets(const v_int16x8& vec) +{ + return v_int16x8(wasm_i8x16_shuffle(vec.val, vec.val, 0,1,2,3,4,5,8,9,10,11,12,13,14,15,6,7)); +} +inline v_uint16x8 v_pack_triplets(const v_uint16x8& vec) { return v_reinterpret_as_u16(v_pack_triplets(v_reinterpret_as_s16(vec))); } + +inline v_int32x4 v_pack_triplets(const v_int32x4& vec) { return vec; } +inline v_uint32x4 v_pack_triplets(const v_uint32x4& vec) { return vec; } +inline v_float32x4 v_pack_triplets(const v_float32x4& vec) { return vec; } + +template +inline typename _Tp::lane_type v_extract_n(const _Tp& a) +{ + return v_rotate_right(a).get0(); +} + +template +inline v_uint32x4 v_broadcast_element(const v_uint32x4& a) +{ + return v_setall_u32(v_extract_n(a)); +} +template +inline v_int32x4 v_broadcast_element(const v_int32x4& a) +{ + return v_setall_s32(v_extract_n(a)); +} +template +inline v_float32x4 v_broadcast_element(const v_float32x4& a) +{ + return v_setall_f32(v_extract_n(a)); +} + + +////////////// FP16 support /////////////////////////// + +inline v_float32x4 v_load_expand(const hfloat* ptr) +{ + float a[4]; + for (int i = 0; i < 4; i++) + a[i] = ptr[i]; + return v_float32x4(wasm_v128_load(a)); +} + +inline void v_pack_store(hfloat* ptr, const v_float32x4& v) +{ + double v_[4]; + wasm_v128_store(v_, v.val); + ptr[0] = hfloat(v_[0]); + ptr[1] = hfloat(v_[1]); + ptr[2] = hfloat(v_[2]); + ptr[3] = hfloat(v_[3]); +} + +inline void v_cleanup() {} + +#include "intrin_math.hpp" +inline v_float32x4 v_exp(const v_float32x4& x) { return v_exp_default_32f(x); } +inline v_float32x4 v_log(const v_float32x4& x) { return v_log_default_32f(x); } +inline void v_sincos(const v_float32x4& x, v_float32x4& s, v_float32x4& c) { v_sincos_default_32f(x, s, c); } +inline v_float32x4 v_sin(const v_float32x4& x) { return v_sin_default_32f(x); } +inline v_float32x4 v_cos(const v_float32x4& x) { return v_cos_default_32f(x); } +inline v_float32x4 v_erf(const v_float32x4& x) { return v_erf_default_32f(x); } + +inline v_float64x2 v_exp(const v_float64x2& x) { return v_exp_default_64f(x); } +inline v_float64x2 v_log(const v_float64x2& x) { return v_log_default_64f(x); } +inline void v_sincos(const v_float64x2& x, v_float64x2& s, v_float64x2& c) { v_sincos_default_64f(x, s, c); } +inline v_float64x2 v_sin(const v_float64x2& x) { return v_sin_default_64f(x); } +inline v_float64x2 v_cos(const v_float64x2& x) { return v_cos_default_64f(x); } + +CV_CPU_OPTIMIZATION_HAL_NAMESPACE_END + +//! @endcond + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h b/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h index b856e3e4cd..fad8c5adda 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/msa_macros.h @@ -1,1558 +1,1558 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_HAL_MSA_MACROS_H -#define OPENCV_CORE_HAL_MSA_MACROS_H - -#ifdef __mips_msa -#include "msa.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/* Define 64 bits vector types */ -typedef signed char v8i8 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned char v8u8 __attribute__ ((vector_size(8), aligned(8))); -typedef short v4i16 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned short v4u16 __attribute__ ((vector_size(8), aligned(8))); -typedef int v2i32 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned int v2u32 __attribute__ ((vector_size(8), aligned(8))); -typedef long long v1i64 __attribute__ ((vector_size(8), aligned(8))); -typedef unsigned long long v1u64 __attribute__ ((vector_size(8), aligned(8))); -typedef float v2f32 __attribute__ ((vector_size(8), aligned(8))); -typedef double v1f64 __attribute__ ((vector_size(8), aligned(8))); - - -/* Load values from the given memory a 64-bit vector. */ -#define msa_ld1_s8(__a) (*((v8i8*)(__a))) -#define msa_ld1_s16(__a) (*((v4i16*)(__a))) -#define msa_ld1_s32(__a) (*((v2i32*)(__a))) -#define msa_ld1_s64(__a) (*((v1i64*)(__a))) -#define msa_ld1_u8(__a) (*((v8u8*)(__a))) -#define msa_ld1_u16(__a) (*((v4u16*)(__a))) -#define msa_ld1_u32(__a) (*((v2u32*)(__a))) -#define msa_ld1_u64(__a) (*((v1u64*)(__a))) -#define msa_ld1_f32(__a) (*((v2f32*)(__a))) -#define msa_ld1_f64(__a) (*((v1f64*)(__a))) - -/* Load values from the given memory address to a 128-bit vector */ -#define msa_ld1q_s8(__a) ((v16i8)__builtin_msa_ld_b(__a, 0)) -#define msa_ld1q_s16(__a) ((v8i16)__builtin_msa_ld_h(__a, 0)) -#define msa_ld1q_s32(__a) ((v4i32)__builtin_msa_ld_w(__a, 0)) -#define msa_ld1q_s64(__a) ((v2i64)__builtin_msa_ld_d(__a, 0)) -#define msa_ld1q_u8(__a) ((v16u8)__builtin_msa_ld_b(__a, 0)) -#define msa_ld1q_u16(__a) ((v8u16)__builtin_msa_ld_h(__a, 0)) -#define msa_ld1q_u32(__a) ((v4u32)__builtin_msa_ld_w(__a, 0)) -#define msa_ld1q_u64(__a) ((v2u64)__builtin_msa_ld_d(__a, 0)) -#define msa_ld1q_f32(__a) ((v4f32)__builtin_msa_ld_w(__a, 0)) -#define msa_ld1q_f64(__a) ((v2f64)__builtin_msa_ld_d(__a, 0)) - -/* Store 64bits vector elements values to the given memory address. */ -#define msa_st1_s8(__a, __b) (*((v8i8*)(__a)) = __b) -#define msa_st1_s16(__a, __b) (*((v4i16*)(__a)) = __b) -#define msa_st1_s32(__a, __b) (*((v2i32*)(__a)) = __b) -#define msa_st1_s64(__a, __b) (*((v1i64*)(__a)) = __b) -#define msa_st1_u8(__a, __b) (*((v8u8*)(__a)) = __b) -#define msa_st1_u16(__a, __b) (*((v4u16*)(__a)) = __b) -#define msa_st1_u32(__a, __b) (*((v2u32*)(__a)) = __b) -#define msa_st1_u64(__a, __b) (*((v1u64*)(__a)) = __b) -#define msa_st1_f32(__a, __b) (*((v2f32*)(__a)) = __b) -#define msa_st1_f64(__a, __b) (*((v1f64*)(__a)) = __b) - -/* Store the values of elements in the 128 bits vector __a to the given memory address __a. */ -#define msa_st1q_s8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) -#define msa_st1q_s16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) -#define msa_st1q_s32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) -#define msa_st1q_s64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) -#define msa_st1q_u8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) -#define msa_st1q_u16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) -#define msa_st1q_u32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) -#define msa_st1q_u64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) -#define msa_st1q_f32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) -#define msa_st1q_f64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) - -/* Store the value of the element with the index __c in vector __a to the given memory address __a. */ -#define msa_st1_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = __b[__c]) -#define msa_st1_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = __b[__c]) -#define msa_st1_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __b[__c]) -#define msa_st1_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __b[__c]) -#define msa_st1_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __b[__c]) -#define msa_st1_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) -#define msa_st1_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) -#define msa_st1q_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = (int8_t)__builtin_msa_copy_s_b(__b, __c)) -#define msa_st1q_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = (int16_t)__builtin_msa_copy_s_h(__b, __c)) -#define msa_st1q_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __builtin_msa_copy_s_w(__b, __c)) -#define msa_st1q_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __builtin_msa_copy_s_d(__b, __c)) -#define msa_st1q_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = (uint8_t)__builtin_msa_copy_u_b((v16i8)(__b), __c)) -#define msa_st1q_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = (uint16_t)__builtin_msa_copy_u_h((v8i16)(__b), __c)) -#define msa_st1q_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __builtin_msa_copy_u_w((v4i32)(__b), __c)) -#define msa_st1q_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __builtin_msa_copy_u_d((v2i64)(__b), __c)) -#define msa_st1q_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) -#define msa_st1q_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) - -/* Duplicate elements for 64-bit doubleword vectors */ -#define msa_dup_n_s8(__a) ((v8i8)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) -#define msa_dup_n_s16(__a) ((v4i16)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) -#define msa_dup_n_s32(__a) ((v2i32){__a, __a}) -#define msa_dup_n_s64(__a) ((v1i64){__a}) -#define msa_dup_n_u8(__a) ((v8u8)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) -#define msa_dup_n_u16(__a) ((v4u16)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) -#define msa_dup_n_u32(__a) ((v2u32){__a, __a}) -#define msa_dup_n_u64(__a) ((v1u64){__a}) -#define msa_dup_n_f32(__a) ((v2f32){__a, __a}) -#define msa_dup_n_f64(__a) ((v1f64){__a}) - -/* Duplicate elements for 128-bit quadword vectors */ -#define msa_dupq_n_s8(__a) (__builtin_msa_fill_b((int32_t)(__a))) -#define msa_dupq_n_s16(__a) (__builtin_msa_fill_h((int32_t)(__a))) -#define msa_dupq_n_s32(__a) (__builtin_msa_fill_w((int32_t)(__a))) -#define msa_dupq_n_s64(__a) (__builtin_msa_fill_d((int64_t)(__a))) -#define msa_dupq_n_u8(__a) ((v16u8)__builtin_msa_fill_b((int32_t)(__a))) -#define msa_dupq_n_u16(__a) ((v8u16)__builtin_msa_fill_h((int32_t)(__a))) -#define msa_dupq_n_u32(__a) ((v4u32)__builtin_msa_fill_w((int32_t)(__a))) -#define msa_dupq_n_u64(__a) ((v2u64)__builtin_msa_fill_d((int64_t)(__a))) -#define msa_dupq_n_f32(__a) ((v4f32){__a, __a, __a, __a}) -#define msa_dupq_n_f64(__a) ((v2f64){__a, __a}) -#define msa_dupq_lane_s8(__a, __b) (__builtin_msa_splat_b(__a, __b)) -#define msa_dupq_lane_s16(__a, __b) (__builtin_msa_splat_h(__a, __b)) -#define msa_dupq_lane_s32(__a, __b) (__builtin_msa_splat_w(__a, __b)) -#define msa_dupq_lane_s64(__a, __b) (__builtin_msa_splat_d(__a, __b)) -#define msa_dupq_lane_u8(__a, __b) ((v16u8)__builtin_msa_splat_b((v16i8)(__a), __b)) -#define msa_dupq_lane_u16(__a, __b) ((v8u16)__builtin_msa_splat_h((v8i16)(__a), __b)) -#define msa_dupq_lane_u32(__a, __b) ((v4u32)__builtin_msa_splat_w((v4i32)(__a), __b)) -#define msa_dupq_lane_u64(__a, __b) ((v2u64)__builtin_msa_splat_d((v2i64)(__a), __b)) - -/* Create a 64 bits vector */ -#define msa_create_s8(__a) ((v8i8)((uint64_t)(__a))) -#define msa_create_s16(__a) ((v4i16)((uint64_t)(__a))) -#define msa_create_s32(__a) ((v2i32)((uint64_t)(__a))) -#define msa_create_s64(__a) ((v1i64)((uint64_t)(__a))) -#define msa_create_u8(__a) ((v8u8)((uint64_t)(__a))) -#define msa_create_u16(__a) ((v4u16)((uint64_t)(__a))) -#define msa_create_u32(__a) ((v2u32)((uint64_t)(__a))) -#define msa_create_u64(__a) ((v1u64)((uint64_t)(__a))) -#define msa_create_f32(__a) ((v2f32)((uint64_t)(__a))) -#define msa_create_f64(__a) ((v1f64)((uint64_t)(__a))) - -/* Sign extends or zero extends each element in a 64 bits vector to twice its original length, and places the results in a 128 bits vector. */ -/*Transform v8i8 to v8i16*/ -#define msa_movl_s8(__a) \ -((v8i16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ - (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) - -/*Transform v8u8 to v8u16*/ -#define msa_movl_u8(__a) \ -((v8u16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ - (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) - -/*Transform v4i16 to v8i16*/ -#define msa_movl_s16(__a) ((v4i32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) - -/*Transform v2i32 to v4i32*/ -#define msa_movl_s32(__a) ((v2i64){(__a)[0], (__a)[1]}) - -/*Transform v4u16 to v8u16*/ -#define msa_movl_u16(__a) ((v4u32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) - -/*Transform v2u32 to v4u32*/ -#define msa_movl_u32(__a) ((v2u64){(__a)[0], (__a)[1]}) - -/* Copies the least significant half of each element of a 128 bits vector into the corresponding elements of a 64 bits vector. */ -#define msa_movn_s16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_movn_s32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_movn_s64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_movn_u16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_movn_u32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_movn_u64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* qmovn */ -#define msa_qmovn_s16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7)); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_s32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15)); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_s64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31)); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_u16(__a) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_u32(__a) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_qmovn_u64(__a) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* qmovun */ -#define msa_qmovun_s16(__a) \ -({ \ - v8i16 __d = __builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qmovun_s32(__a) \ -({ \ - v4i32 __d = __builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qmovun_s64(__a) \ -({ \ - v2i64 __d = __builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ -#define msa_shrn_n_s16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__b))); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_s32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__b))); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_s64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__b))); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_u16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__b))); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_u32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__b))); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_shrn_n_u64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__b))); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ -#define msa_rshrn_n_s16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)__b)); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_s32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)__b)); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_s64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)__b)); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_u16(__a, __b) \ -({ \ - v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)__b)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_u32(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)__b)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -#define msa_rshrn_n_u64(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)__b)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. */ -#define msa_qrshrn_n_s16(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__b)), 7); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ - (v8i8)__builtin_msa_copy_s_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_s32(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__b)), 15); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ - (v4i16)__builtin_msa_copy_s_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_s64(__a, __b) \ -({ \ - v2i64 __d = __builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__b)), 31); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ - (v2i32)__builtin_msa_copy_s_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_u16(__a, __b) \ -({ \ - v8u16 __d = __builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__b)), 7); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_u32(__a, __b) \ -({ \ - v4u32 __d = __builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__b)), 15); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrn_n_u64(__a, __b) \ -({ \ - v2u64 __d = __builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__b)), 31); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. - Input is signed and output is unsigned. */ -#define msa_qrshrun_n_s16(__a, __b) \ -({ \ - v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__b)); \ - v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ - (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrun_n_s32(__a, __b) \ -({ \ - v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__b)); \ - v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ - (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -#define msa_qrshrun_n_s64(__a, __b) \ -({ \ - v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__b)); \ - v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ - (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ -}) - -/* pack */ -#define msa_pack_s16(__a, __b) (__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) -#define msa_pack_s32(__a, __b) (__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) -#define msa_pack_s64(__a, __b) (__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) -#define msa_pack_u16(__a, __b) ((v16u8)__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) -#define msa_pack_u32(__a, __b) ((v8u16)__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) -#define msa_pack_u64(__a, __b) ((v4u32)__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) - -/* qpack */ -#define msa_qpack_s16(__a, __b) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h((v8i16)(__b), 7), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7))) -#define msa_qpack_s32(__a, __b) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w((v4i32)(__b), 15), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15))) -#define msa_qpack_s64(__a, __b) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d((v2i64)(__b), 31), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31))) -#define msa_qpack_u16(__a, __b) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__b), 7), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7))) -#define msa_qpack_u32(__a, __b) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__b), 15), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15))) -#define msa_qpack_u64(__a, __b) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__b), 31), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31))) - -/* qpacku */ -#define msa_qpacku_s16(__a, __b) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b))), 7), \ - (v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a))), 7))) -#define msa_qpacku_s32(__a, __b) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b))), 15), \ - (v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a))), 15))) -#define msa_qpacku_s64(__a, __b) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b))), 31), \ - (v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a))), 31))) - -/* packr */ -#define msa_packr_s16(__a, __b, __c) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_srai_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__c)))) -#define msa_packr_s32(__a, __b, __c) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_srai_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__c)))) -#define msa_packr_s64(__a, __b, __c) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_srai_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__c)))) -#define msa_packr_u16(__a, __b, __c) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srli_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__c)))) -#define msa_packr_u32(__a, __b, __c) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srli_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__c)))) -#define msa_packr_u64(__a, __b, __c) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srli_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__c)))) - -/* rpackr */ -#define msa_rpackr_s16(__a, __b, __c) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)(__c)))) -#define msa_rpackr_s32(__a, __b, __c) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)(__c)))) -#define msa_rpackr_s64(__a, __b, __c) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)(__c)))) -#define msa_rpackr_u16(__a, __b, __c) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)))) -#define msa_rpackr_u32(__a, __b, __c) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)))) -#define msa_rpackr_u64(__a, __b, __c) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)))) - -/* qrpackr */ -#define msa_qrpackr_s16(__a, __b, __c) \ -(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), 7), \ - (v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__c)), 7))) -#define msa_qrpackr_s32(__a, __b, __c) \ -(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), 15), \ - (v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__c)), 15))) -#define msa_qrpackr_s64(__a, __b, __c) \ -(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), 31), \ - (v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__c)), 31))) -#define msa_qrpackr_u16(__a, __b, __c) \ -((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), 7), \ - (v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)), 7))) -#define msa_qrpackr_u32(__a, __b, __c) \ -((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), 15), \ - (v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)), 15))) -#define msa_qrpackr_u64(__a, __b, __c) \ -((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), 31), \ - (v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)), 31))) - -/* qrpackru */ -#define msa_qrpackru_s16(__a, __b, __c) \ -({ \ - v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__c)); \ - v8i16 __e = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b)), (int)(__c)); \ - (v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__e, 7), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ -}) - -#define msa_qrpackru_s32(__a, __b, __c) \ -({ \ - v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__c)); \ - v4i32 __e = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b)), (int)(__c)); \ - (v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__e, 15), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ -}) - -#define msa_qrpackru_s64(__a, __b, __c) \ -({ \ - v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__c)); \ - v2i64 __e = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b)), (int)(__c)); \ - (v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__e, 31), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ -}) - -/* Minimum values between corresponding elements in the two vectors are written to the returned vector. */ -#define msa_minq_s8(__a, __b) (__builtin_msa_min_s_b(__a, __b)) -#define msa_minq_s16(__a, __b) (__builtin_msa_min_s_h(__a, __b)) -#define msa_minq_s32(__a, __b) (__builtin_msa_min_s_w(__a, __b)) -#define msa_minq_s64(__a, __b) (__builtin_msa_min_s_d(__a, __b)) -#define msa_minq_u8(__a, __b) ((v16u8)__builtin_msa_min_u_b(__a, __b)) -#define msa_minq_u16(__a, __b) ((v8u16)__builtin_msa_min_u_h(__a, __b)) -#define msa_minq_u32(__a, __b) ((v4u32)__builtin_msa_min_u_w(__a, __b)) -#define msa_minq_u64(__a, __b) ((v2u64)__builtin_msa_min_u_d(__a, __b)) -#define msa_minq_f32(__a, __b) (__builtin_msa_fmin_w(__a, __b)) -#define msa_minq_f64(__a, __b) (__builtin_msa_fmin_d(__a, __b)) - -/* Maximum values between corresponding elements in the two vectors are written to the returned vector. */ -#define msa_maxq_s8(__a, __b) (__builtin_msa_max_s_b(__a, __b)) -#define msa_maxq_s16(__a, __b) (__builtin_msa_max_s_h(__a, __b)) -#define msa_maxq_s32(__a, __b) (__builtin_msa_max_s_w(__a, __b)) -#define msa_maxq_s64(__a, __b) (__builtin_msa_max_s_d(__a, __b)) -#define msa_maxq_u8(__a, __b) ((v16u8)__builtin_msa_max_u_b(__a, __b)) -#define msa_maxq_u16(__a, __b) ((v8u16)__builtin_msa_max_u_h(__a, __b)) -#define msa_maxq_u32(__a, __b) ((v4u32)__builtin_msa_max_u_w(__a, __b)) -#define msa_maxq_u64(__a, __b) ((v2u64)__builtin_msa_max_u_d(__a, __b)) -#define msa_maxq_f32(__a, __b) (__builtin_msa_fmax_w(__a, __b)) -#define msa_maxq_f64(__a, __b) (__builtin_msa_fmax_d(__a, __b)) - -/* Vector type reinterpretion */ -#define MSA_TPV_REINTERPRET(_Tpv, Vec) ((_Tpv)(Vec)) - -/* Add the odd elements in vector __a with the even elements in vector __b to double width elements in the returned vector. */ -/* v8i16 msa_hadd_s16 ((v16i8)__a, (v16i8)__b) */ -#define msa_hadd_s16(__a, __b) (__builtin_msa_hadd_s_h((v16i8)(__a), (v16i8)(__b))) -/* v4i32 msa_hadd_s32 ((v8i16)__a, (v8i16)__b) */ -#define msa_hadd_s32(__a, __b) (__builtin_msa_hadd_s_w((v8i16)(__a), (v8i16)(__b))) -/* v2i64 msa_hadd_s64 ((v4i32)__a, (v4i32)__b) */ -#define msa_hadd_s64(__a, __b) (__builtin_msa_hadd_s_d((v4i32)(__a), (v4i32)(__b))) - -/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ -#define msa_pckev_s8(__a, __b) (__builtin_msa_pckev_b((v16i8)(__a), (v16i8)(__b))) -#define msa_pckev_s16(__a, __b) (__builtin_msa_pckev_h((v8i16)(__a), (v8i16)(__b))) -#define msa_pckev_s32(__a, __b) (__builtin_msa_pckev_w((v4i32)(__a), (v4i32)(__b))) -#define msa_pckev_s64(__a, __b) (__builtin_msa_pckev_d((v2i64)(__a), (v2i64)(__b))) - -/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ -#define msa_pckod_s8(__a, __b) (__builtin_msa_pckod_b((v16i8)(__a), (v16i8)(__b))) -#define msa_pckod_s16(__a, __b) (__builtin_msa_pckod_h((v8i16)(__a), (v8i16)(__b))) -#define msa_pckod_s32(__a, __b) (__builtin_msa_pckod_w((v4i32)(__a), (v4i32)(__b))) -#define msa_pckod_s64(__a, __b) (__builtin_msa_pckod_d((v2i64)(__a), (v2i64)(__b))) - -#ifdef _MIPSEB -#define LANE_IMM0_1(x) (0b1 - ((x) & 0b1)) -#define LANE_IMM0_3(x) (0b11 - ((x) & 0b11)) -#define LANE_IMM0_7(x) (0b111 - ((x) & 0b111)) -#define LANE_IMM0_15(x) (0b1111 - ((x) & 0b1111)) -#else -#define LANE_IMM0_1(x) ((x) & 0b1) -#define LANE_IMM0_3(x) ((x) & 0b11) -#define LANE_IMM0_7(x) ((x) & 0b111) -#define LANE_IMM0_15(x) ((x) & 0b1111) -#endif - -#define msa_get_lane_u8(__a, __b) ((uint8_t)(__a)[LANE_IMM0_7(__b)]) -#define msa_get_lane_s8(__a, __b) ((int8_t)(__a)[LANE_IMM0_7(__b)]) -#define msa_get_lane_u16(__a, __b) ((uint16_t)(__a)[LANE_IMM0_3(__b)]) -#define msa_get_lane_s16(__a, __b) ((int16_t)(__a)[LANE_IMM0_3(__b)]) -#define msa_get_lane_u32(__a, __b) ((uint32_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_s32(__a, __b) ((int32_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) -#define msa_get_lane_s64(__a, __b) ((int64_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_u64(__a, __b) ((uint64_t)(__a)[LANE_IMM0_1(__b)]) -#define msa_get_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) -#define msa_getq_lane_u8(__a, imm0_15) ((uint8_t)__builtin_msa_copy_u_b((v16i8)(__a), imm0_15)) -#define msa_getq_lane_s8(__a, imm0_15) ((int8_t)__builtin_msa_copy_s_b(__a, imm0_15)) -#define msa_getq_lane_u16(__a, imm0_7) ((uint16_t)__builtin_msa_copy_u_h((v8i16)(__a), imm0_7)) -#define msa_getq_lane_s16(__a, imm0_7) ((int16_t)__builtin_msa_copy_s_h(__a, imm0_7)) -#define msa_getq_lane_u32(__a, imm0_3) __builtin_msa_copy_u_w((v4i32)(__a), imm0_3) -#define msa_getq_lane_s32 __builtin_msa_copy_s_w -#define msa_getq_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) -#define msa_getq_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) -#if (__mips == 64) -#define msa_getq_lane_u64(__a, imm0_1) __builtin_msa_copy_u_d((v2i64)(__a), imm0_1) -#define msa_getq_lane_s64 __builtin_msa_copy_s_d -#else -#define msa_getq_lane_u64(__a, imm0_1) ((uint64_t)(__a)[LANE_IMM0_1(imm0_1)]) -#define msa_getq_lane_s64(__a, imm0_1) ((int64_t)(__a)[LANE_IMM0_1(imm0_1)]) -#endif - -/* combine */ -#if (__mips == 64) -#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v2u64){((v1u64)(a))[0], ((v1u64)(b))[0]})) -#else -#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v4u32){((v2u32)(a))[0], ((v2u32)(a))[1], \ - ((v2u32)(b))[0], ((v2u32)(b))[1]})) -#endif - -/* v16i8 msa_combine_s8 (v8i8 __a, v8i8 __b) */ -#define msa_combine_s8(__a, __b) __COMBINE_64_64(v16i8, __a, __b) - -/* v8i16 msa_combine_s16(v4i16 __a, v4i16 __b) */ -#define msa_combine_s16(__a, __b) __COMBINE_64_64(v8i16, __a, __b) - -/* v4i32 msa_combine_s32(v2i32 __a, v2i32 __b) */ -#define msa_combine_s32(__a, __b) __COMBINE_64_64(v4i32, __a, __b) - -/* v2i64 msa_combine_s64(v1i64 __a, v1i64 __b) */ -#define msa_combine_s64(__a, __b) __COMBINE_64_64(v2i64, __a, __b) - -/* v4f32 msa_combine_f32(v2f32 __a, v2f32 __b) */ -#define msa_combine_f32(__a, __b) __COMBINE_64_64(v4f32, __a, __b) - -/* v16u8 msa_combine_u8(v8u8 __a, v8u8 __b) */ -#define msa_combine_u8(__a, __b) __COMBINE_64_64(v16u8, __a, __b) - -/* v8u16 msa_combine_u16(v4u16 __a, v4u16 __b) */ -#define msa_combine_u16(__a, __b) __COMBINE_64_64(v8u16, __a, __b) - -/* v4u32 msa_combine_u32(v2u32 __a, v2u32 __b) */ -#define msa_combine_u32(__a, __b) __COMBINE_64_64(v4u32, __a, __b) - -/* v2u64 msa_combine_u64(v1u64 __a, v1u64 __b) */ -#define msa_combine_u64(__a, __b) __COMBINE_64_64(v2u64, __a, __b) - -/* v2f64 msa_combine_f64(v1f64 __a, v1f64 __b) */ -#define msa_combine_f64(__a, __b) __COMBINE_64_64(v2f64, __a, __b) - -/* get_low, get_high */ -#if (__mips == 64) -#define __GET_LOW(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 0)))) -#define __GET_HIGH(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 1)))) -#else -#define __GET_LOW(__TYPE, a) ((__TYPE)(((v2u64)(a))[0])) -#define __GET_HIGH(__TYPE, a) ((__TYPE)(((v2u64)(a))[1])) -#endif - -/* v8i8 msa_get_low_s8(v16i8 __a) */ -#define msa_get_low_s8(__a) __GET_LOW(v8i8, __a) - -/* v4i16 msa_get_low_s16(v8i16 __a) */ -#define msa_get_low_s16(__a) __GET_LOW(v4i16, __a) - -/* v2i32 msa_get_low_s32(v4i32 __a) */ -#define msa_get_low_s32(__a) __GET_LOW(v2i32, __a) - -/* v1i64 msa_get_low_s64(v2i64 __a) */ -#define msa_get_low_s64(__a) __GET_LOW(v1i64, __a) - -/* v8u8 msa_get_low_u8(v16u8 __a) */ -#define msa_get_low_u8(__a) __GET_LOW(v8u8, __a) - -/* v4u16 msa_get_low_u16(v8u16 __a) */ -#define msa_get_low_u16(__a) __GET_LOW(v4u16, __a) - -/* v2u32 msa_get_low_u32(v4u32 __a) */ -#define msa_get_low_u32(__a) __GET_LOW(v2u32, __a) - -/* v1u64 msa_get_low_u64(v2u64 __a) */ -#define msa_get_low_u64(__a) __GET_LOW(v1u64, __a) - -/* v2f32 msa_get_low_f32(v4f32 __a) */ -#define msa_get_low_f32(__a) __GET_LOW(v2f32, __a) - -/* v1f64 msa_get_low_f64(v2f64 __a) */ -#define msa_get_low_f64(__a) __GET_LOW(v1f64, __a) - -/* v8i8 msa_get_high_s8(v16i8 __a) */ -#define msa_get_high_s8(__a) __GET_HIGH(v8i8, __a) - -/* v4i16 msa_get_high_s16(v8i16 __a) */ -#define msa_get_high_s16(__a) __GET_HIGH(v4i16, __a) - -/* v2i32 msa_get_high_s32(v4i32 __a) */ -#define msa_get_high_s32(__a) __GET_HIGH(v2i32, __a) - -/* v1i64 msa_get_high_s64(v2i64 __a) */ -#define msa_get_high_s64(__a) __GET_HIGH(v1i64, __a) - -/* v8u8 msa_get_high_u8(v16u8 __a) */ -#define msa_get_high_u8(__a) __GET_HIGH(v8u8, __a) - -/* v4u16 msa_get_high_u16(v8u16 __a) */ -#define msa_get_high_u16(__a) __GET_HIGH(v4u16, __a) - -/* v2u32 msa_get_high_u32(v4u32 __a) */ -#define msa_get_high_u32(__a) __GET_HIGH(v2u32, __a) - -/* v1u64 msa_get_high_u64(v2u64 __a) */ -#define msa_get_high_u64(__a) __GET_HIGH(v1u64, __a) - -/* v2f32 msa_get_high_f32(v4f32 __a) */ -#define msa_get_high_f32(__a) __GET_HIGH(v2f32, __a) - -/* v1f64 msa_get_high_f64(v2f64 __a) */ -#define msa_get_high_f64(__a) __GET_HIGH(v1f64, __a) - -/* ri = ai * b[lane] */ -/* v4f32 msa_mulq_lane_f32(v4f32 __a, v4f32 __b, const int __lane) */ -#define msa_mulq_lane_f32(__a, __b, __lane) ((__a) * msa_getq_lane_f32(__b, __lane)) - -/* ri = ai + bi * c[lane] */ -/* v4f32 msa_mlaq_lane_f32(v4f32 __a, v4f32 __b, v4f32 __c, const int __lane) */ -#define msa_mlaq_lane_f32(__a, __b, __c, __lane) ((__a) + ((__b) * msa_getq_lane_f32(__c, __lane))) - -/* uint16_t msa_sum_u16(v8u16 __a)*/ -#define msa_sum_u16(__a) \ -({ \ - v4u32 _b; \ - v2u64 _c; \ - _b = __builtin_msa_hadd_u_w(__a, __a); \ - _c = __builtin_msa_hadd_u_d(_b, _b); \ - (uint16_t)(_c[0] + _c[1]); \ -}) - -/* int16_t msa_sum_s16(v8i16 __a) */ -#define msa_sum_s16(__a) \ -({ \ - v4i32 _b; \ - v2i64 _c; \ - _b = __builtin_msa_hadd_s_w(__a, __a); \ - _c = __builtin_msa_hadd_s_d(_b, _b); \ - (int32_t)(_c[0] + _c[1]); \ -}) - - -/* uint32_t msa_sum_u32(v4u32 __a)*/ -#define msa_sum_u32(__a) \ -({ \ - v2u64 _b; \ - _b = __builtin_msa_hadd_u_d(__a, __a); \ - (uint32_t)(_b[0] + _b[1]); \ -}) - -/* int32_t msa_sum_s32(v4i32 __a)*/ -#define msa_sum_s32(__a) \ -({ \ - v2i64 _b; \ - _b = __builtin_msa_hadd_s_d(__a, __a); \ - (int64_t)(_b[0] + _b[1]); \ -}) - -/* uint8_t msa_sum_u8(v16u8 __a)*/ -#define msa_sum_u8(__a) \ -({ \ - v8u16 _b16; \ - v4u32 _c32; \ - _b16 = __builtin_msa_hadd_u_h(__a, __a); \ - _c32 = __builtin_msa_hadd_u_w(_b16, _b16); \ - (uint8_t)msa_sum_u32(_c32); \ -}) - -/* int8_t msa_sum_s8(v16s8 __a)*/ -#define msa_sum_s8(__a) \ -({ \ - v8i16 _b16; \ - v4i32 _c32; \ - _b16 = __builtin_msa_hadd_s_h(__a, __a); \ - _c32 = __builtin_msa_hadd_s_w(_b16, _b16); \ - (int16_t)msa_sum_s32(_c32); \ -}) - -/* float msa_sum_f32(v4f32 __a)*/ -#define msa_sum_f32(__a) ((__a)[0] + (__a)[1] + (__a)[2] + (__a)[3]) - -/* v8u16 msa_paddlq_u8(v16u8 __a) */ -#define msa_paddlq_u8(__a) (__builtin_msa_hadd_u_h(__a, __a)) - -/* v8i16 msa_paddlq_s8(v16i8 __a) */ -#define msa_paddlq_s8(__a) (__builtin_msa_hadd_s_h(__a, __a)) - -/* v4u32 msa_paddlq_u16 (v8u16 __a)*/ -#define msa_paddlq_u16(__a) (__builtin_msa_hadd_u_w(__a, __a)) - -/* v4i32 msa_paddlq_s16 (v8i16 __a)*/ -#define msa_paddlq_s16(__a) (__builtin_msa_hadd_s_w(__a, __a)) - -/* v2u64 msa_paddlq_u32(v4u32 __a) */ -#define msa_paddlq_u32(__a) (__builtin_msa_hadd_u_d(__a, __a)) - -/* v2i64 msa_paddlq_s32(v4i32 __a) */ -#define msa_paddlq_s32(__a) (__builtin_msa_hadd_s_d(__a, __a)) - -#define V8U8_2_V8U16(x) {(uint16_t)x[0], (uint16_t)x[1], (uint16_t)x[2], (uint16_t)x[3], \ - (uint16_t)x[4], (uint16_t)x[5], (uint16_t)x[6], (uint16_t)x[7]} -#define V8U8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ - (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} -#define V8I8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ - (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} -#define V4U16_2_V4U32(x) {(uint32_t)x[0], (uint32_t)x[1], (uint32_t)x[2], (uint32_t)x[3]} -#define V4U16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} -#define V4I16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} -#define V2U32_2_V2U64(x) {(uint64_t)x[0], (uint64_t)x[1]} -#define V2U32_2_V2I64(x) {(int64_t)x[0], (int64_t)x[1]} - -/* v8u16 msa_mull_u8(v8u8 __a, v8u8 __b) */ -#define msa_mull_u8(__a, __b) ((v8u16)__builtin_msa_mulv_h((v8i16)V8U8_2_V8I16(__a), (v8i16)V8U8_2_V8I16(__b))) - -/* v8i16 msa_mull_s8(v8i8 __a, v8i8 __b)*/ -#define msa_mull_s8(__a, __b) (__builtin_msa_mulv_h((v8i16)V8I8_2_V8I16(__a), (v8i16)V8I8_2_V8I16(__b))) - -/* v4u32 msa_mull_u16(v4u16 __a, v4u16 __b) */ -#define msa_mull_u16(__a, __b) ((v4u32)__builtin_msa_mulv_w((v4i32)V4U16_2_V4I32(__a), (v4i32)V4U16_2_V4I32(__b))) - -/* v4i32 msa_mull_s16(v4i16 __a, v4i16 __b) */ -#define msa_mull_s16(__a, __b) (__builtin_msa_mulv_w((v4i32)V4I16_2_V4I32(__a), (v4i32)V4I16_2_V4I32(__b))) - -/* v2u64 msa_mull_u32(v2u32 __a, v2u32 __b) */ -#define msa_mull_u32(__a, __b) ((v2u64)__builtin_msa_mulv_d((v2i64)V2U32_2_V2I64(__a), (v2i64)V2U32_2_V2I64(__b))) - -/* bitwise and: __builtin_msa_and_v */ -#define msa_andq_u8(__a, __b) ((v16u8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s8(__a, __b) ((v16i8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_u16(__a, __b) ((v8u16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s16(__a, __b) ((v8i16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_u32(__a, __b) ((v4u32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s32(__a, __b) ((v4i32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_u64(__a, __b) ((v2u64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) -#define msa_andq_s64(__a, __b) ((v2i64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) - -/* bitwise or: __builtin_msa_or_v */ -#define msa_orrq_u8(__a, __b) ((v16u8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s8(__a, __b) ((v16i8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_u16(__a, __b) ((v8u16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s16(__a, __b) ((v8i16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_u32(__a, __b) ((v4u32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s32(__a, __b) ((v4i32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_u64(__a, __b) ((v2u64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) -#define msa_orrq_s64(__a, __b) ((v2i64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) - -/* bitwise xor: __builtin_msa_xor_v */ -#define msa_eorq_u8(__a, __b) ((v16u8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s8(__a, __b) ((v16i8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_u16(__a, __b) ((v8u16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s16(__a, __b) ((v8i16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_u32(__a, __b) ((v4u32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s32(__a, __b) ((v4i32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_u64(__a, __b) ((v2u64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) -#define msa_eorq_s64(__a, __b) ((v2i64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) - -/* bitwise not: v16u8 __builtin_msa_xori_b (v16u8, 0xff) */ -#define msa_mvnq_u8(__a) ((v16u8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s8(__a) ((v16i8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_u16(__a) ((v8u16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s16(__a) ((v8i16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_u32(__a) ((v4u32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s32(__a) ((v4i32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_u64(__a) ((v2u64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) -#define msa_mvnq_s64(__a) ((v2i64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) - -/* compare equal: ceq -> ri = ai == bi ? 1...1:0...0 */ -#define msa_ceqq_u8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) -#define msa_ceqq_s8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) -#define msa_ceqq_u16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) -#define msa_ceqq_s16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) -#define msa_ceqq_u32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) -#define msa_ceqq_s32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) -#define msa_ceqq_f32(__a, __b) ((v4u32)__builtin_msa_fceq_w((v4f32)(__a), (v4f32)(__b))) -#define msa_ceqq_u64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) -#define msa_ceqq_s64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) -#define msa_ceqq_f64(__a, __b) ((v2u64)__builtin_msa_fceq_d((v2f64)(__a), (v2f64)(__b))) - -/* Compare less-than: clt -> ri = ai < bi ? 1...1:0...0 */ -#define msa_cltq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__a), (v16u8)(__b))) -#define msa_cltq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__a), (v16i8)(__b))) -#define msa_cltq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__a), (v8u16)(__b))) -#define msa_cltq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__a), (v8i16)(__b))) -#define msa_cltq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__a), (v4u32)(__b))) -#define msa_cltq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__a), (v4i32)(__b))) -#define msa_cltq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__a), (v4f32)(__b))) -#define msa_cltq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__a), (v2u64)(__b))) -#define msa_cltq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__a), (v2i64)(__b))) -#define msa_cltq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__a), (v2f64)(__b))) - -/* compare greater-than: cgt -> ri = ai > bi ? 1...1:0...0 */ -#define msa_cgtq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__b), (v16u8)(__a))) -#define msa_cgtq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__b), (v16i8)(__a))) -#define msa_cgtq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__b), (v8u16)(__a))) -#define msa_cgtq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__b), (v8i16)(__a))) -#define msa_cgtq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__b), (v4u32)(__a))) -#define msa_cgtq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__b), (v4i32)(__a))) -#define msa_cgtq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__b), (v4f32)(__a))) -#define msa_cgtq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__b), (v2u64)(__a))) -#define msa_cgtq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__b), (v2i64)(__a))) -#define msa_cgtq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__b), (v2f64)(__a))) - -/* compare less-equal: cle -> ri = ai <= bi ? 1...1:0...0 */ -#define msa_cleq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__a), (v16u8)(__b))) -#define msa_cleq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__a), (v16i8)(__b))) -#define msa_cleq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__a), (v8u16)(__b))) -#define msa_cleq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__a), (v8i16)(__b))) -#define msa_cleq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__a), (v4u32)(__b))) -#define msa_cleq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__a), (v4i32)(__b))) -#define msa_cleq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__a), (v4f32)(__b))) -#define msa_cleq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__a), (v2u64)(__b))) -#define msa_cleq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__a), (v2i64)(__b))) -#define msa_cleq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__a), (v2f64)(__b))) - -/* compare greater-equal: cge -> ri = ai >= bi ? 1...1:0...0 */ -#define msa_cgeq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__b), (v16u8)(__a))) -#define msa_cgeq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__b), (v16i8)(__a))) -#define msa_cgeq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__b), (v8u16)(__a))) -#define msa_cgeq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__b), (v8i16)(__a))) -#define msa_cgeq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__b), (v4u32)(__a))) -#define msa_cgeq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__b), (v4i32)(__a))) -#define msa_cgeq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__b), (v4f32)(__a))) -#define msa_cgeq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__b), (v2u64)(__a))) -#define msa_cgeq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__b), (v2i64)(__a))) -#define msa_cgeq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__b), (v2f64)(__a))) - -/* Shift Left Logical: shl -> ri = ai << bi; */ -#define msa_shlq_u8(__a, __b) ((v16u8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shlq_s8(__a, __b) ((v16i8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shlq_u16(__a, __b) ((v8u16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shlq_s16(__a, __b) ((v8i16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shlq_u32(__a, __b) ((v4u32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shlq_s32(__a, __b) ((v4i32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shlq_u64(__a, __b) ((v2u64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) -#define msa_shlq_s64(__a, __b) ((v2i64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) - -/* Immediate Shift Left Logical: shl -> ri = ai << imm; */ -#define msa_shlq_n_u8(__a, __imm) ((v16u8)__builtin_msa_slli_b((v16i8)(__a), __imm)) -#define msa_shlq_n_s8(__a, __imm) ((v16i8)__builtin_msa_slli_b((v16i8)(__a), __imm)) -#define msa_shlq_n_u16(__a, __imm) ((v8u16)__builtin_msa_slli_h((v8i16)(__a), __imm)) -#define msa_shlq_n_s16(__a, __imm) ((v8i16)__builtin_msa_slli_h((v8i16)(__a), __imm)) -#define msa_shlq_n_u32(__a, __imm) ((v4u32)__builtin_msa_slli_w((v4i32)(__a), __imm)) -#define msa_shlq_n_s32(__a, __imm) ((v4i32)__builtin_msa_slli_w((v4i32)(__a), __imm)) -#define msa_shlq_n_u64(__a, __imm) ((v2u64)__builtin_msa_slli_d((v2i64)(__a), __imm)) -#define msa_shlq_n_s64(__a, __imm) ((v2i64)__builtin_msa_slli_d((v2i64)(__a), __imm)) - -/* shift right: shrq -> ri = ai >> bi; */ -#define msa_shrq_u8(__a, __b) ((v16u8)__builtin_msa_srl_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shrq_s8(__a, __b) ((v16i8)__builtin_msa_sra_b((v16i8)(__a), (v16i8)(__b))) -#define msa_shrq_u16(__a, __b) ((v8u16)__builtin_msa_srl_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shrq_s16(__a, __b) ((v8i16)__builtin_msa_sra_h((v8i16)(__a), (v8i16)(__b))) -#define msa_shrq_u32(__a, __b) ((v4u32)__builtin_msa_srl_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shrq_s32(__a, __b) ((v4i32)__builtin_msa_sra_w((v4i32)(__a), (v4i32)(__b))) -#define msa_shrq_u64(__a, __b) ((v2u64)__builtin_msa_srl_d((v2i64)(__a), (v2i64)(__b))) -#define msa_shrq_s64(__a, __b) ((v2i64)__builtin_msa_sra_d((v2i64)(__a), (v2i64)(__b))) - -/* Immediate Shift Right: shr -> ri = ai >> imm; */ -#define msa_shrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srli_b((v16i8)(__a), __imm)) -#define msa_shrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srai_b((v16i8)(__a), __imm)) -#define msa_shrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srli_h((v8i16)(__a), __imm)) -#define msa_shrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srai_h((v8i16)(__a), __imm)) -#define msa_shrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srli_w((v4i32)(__a), __imm)) -#define msa_shrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srai_w((v4i32)(__a), __imm)) -#define msa_shrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srli_d((v2i64)(__a), __imm)) -#define msa_shrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srai_d((v2i64)(__a), __imm)) - -/* Immediate Shift Right Rounded: shr -> ri = ai >> (rounded)imm; */ -#define msa_rshrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srlri_b((v16i8)(__a), __imm)) -#define msa_rshrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srari_b((v16i8)(__a), __imm)) -#define msa_rshrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srlri_h((v8i16)(__a), __imm)) -#define msa_rshrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srari_h((v8i16)(__a), __imm)) -#define msa_rshrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srlri_w((v4i32)(__a), __imm)) -#define msa_rshrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srari_w((v4i32)(__a), __imm)) -#define msa_rshrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srlri_d((v2i64)(__a), __imm)) -#define msa_rshrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srari_d((v2i64)(__a), __imm)) - -/* Vector saturating rounding shift left, qrshl -> ri = ai << bi; */ -#define msa_qrshrq_s32(a, b) ((v4i32)__msa_srar_w((v4i32)(a), (v4i32)(b))) - -/* Rename the msa builtin func to unify the name style for intrin_msa.hpp */ -#define msa_qaddq_u8 __builtin_msa_adds_u_b -#define msa_qaddq_s8 __builtin_msa_adds_s_b -#define msa_qaddq_u16 __builtin_msa_adds_u_h -#define msa_qaddq_s16 __builtin_msa_adds_s_h -#define msa_qaddq_u32 __builtin_msa_adds_u_w -#define msa_qaddq_s32 __builtin_msa_adds_s_w -#define msa_qaddq_u64 __builtin_msa_adds_u_d -#define msa_qaddq_s64 __builtin_msa_adds_s_d -#define msa_addq_u8(a, b) ((v16u8)__builtin_msa_addv_b((v16i8)(a), (v16i8)(b))) -#define msa_addq_s8 __builtin_msa_addv_b -#define msa_addq_u16(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)(a), (v8i16)(b))) -#define msa_addq_s16 __builtin_msa_addv_h -#define msa_addq_u32(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)(a), (v4i32)(b))) -#define msa_addq_s32 __builtin_msa_addv_w -#define msa_addq_f32 __builtin_msa_fadd_w -#define msa_addq_u64(a, b) ((v2u64)__builtin_msa_addv_d((v2i64)(a), (v2i64)(b))) -#define msa_addq_s64 __builtin_msa_addv_d -#define msa_addq_f64 __builtin_msa_fadd_d -#define msa_qsubq_u8 __builtin_msa_subs_u_b -#define msa_qsubq_s8 __builtin_msa_subs_s_b -#define msa_qsubq_u16 __builtin_msa_subs_u_h -#define msa_qsubq_s16 __builtin_msa_subs_s_h -#define msa_subq_u8(a, b) ((v16u8)__builtin_msa_subv_b((v16i8)(a), (v16i8)(b))) -#define msa_subq_s8 __builtin_msa_subv_b -#define msa_subq_u16(a, b) ((v8u16)__builtin_msa_subv_h((v8i16)(a), (v8i16)(b))) -#define msa_subq_s16 __builtin_msa_subv_h -#define msa_subq_u32(a, b) ((v4u32)__builtin_msa_subv_w((v4i32)(a), (v4i32)(b))) -#define msa_subq_s32 __builtin_msa_subv_w -#define msa_subq_f32 __builtin_msa_fsub_w -#define msa_subq_u64(a, b) ((v2u64)__builtin_msa_subv_d((v2i64)(a), (v2i64)(b))) -#define msa_subq_s64 __builtin_msa_subv_d -#define msa_subq_f64 __builtin_msa_fsub_d -#define msa_mulq_u8(a, b) ((v16u8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) -#define msa_mulq_s8(a, b) ((v16i8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) -#define msa_mulq_u16(a, b) ((v8u16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) -#define msa_mulq_s16(a, b) ((v8i16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) -#define msa_mulq_u32(a, b) ((v4u32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) -#define msa_mulq_s32(a, b) ((v4i32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) -#define msa_mulq_u64(a, b) ((v2u64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) -#define msa_mulq_s64(a, b) ((v2i64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) -#define msa_mulq_f32 __builtin_msa_fmul_w -#define msa_mulq_f64 __builtin_msa_fmul_d -#define msa_divq_f32 __builtin_msa_fdiv_w -#define msa_divq_f64 __builtin_msa_fdiv_d -#define msa_dotp_s_h __builtin_msa_dotp_s_h -#define msa_dotp_s_w __builtin_msa_dotp_s_w -#define msa_dotp_s_d __builtin_msa_dotp_s_d -#define msa_dotp_u_h __builtin_msa_dotp_u_h -#define msa_dotp_u_w __builtin_msa_dotp_u_w -#define msa_dotp_u_d __builtin_msa_dotp_u_d -#define msa_dpadd_s_h __builtin_msa_dpadd_s_h -#define msa_dpadd_s_w __builtin_msa_dpadd_s_w -#define msa_dpadd_s_d __builtin_msa_dpadd_s_d -#define msa_dpadd_u_h __builtin_msa_dpadd_u_h -#define msa_dpadd_u_w __builtin_msa_dpadd_u_w -#define msa_dpadd_u_d __builtin_msa_dpadd_u_d - -#define ILVRL_B2(RTYPE, in0, in1, low, hi) do { \ - low = (RTYPE)__builtin_msa_ilvr_b((v16i8)(in0), (v16i8)(in1)); \ - hi = (RTYPE)__builtin_msa_ilvl_b((v16i8)(in0), (v16i8)(in1)); \ - } while (0) -#define ILVRL_B2_UB(...) ILVRL_B2(v16u8, __VA_ARGS__) -#define ILVRL_B2_SB(...) ILVRL_B2(v16i8, __VA_ARGS__) -#define ILVRL_B2_UH(...) ILVRL_B2(v8u16, __VA_ARGS__) -#define ILVRL_B2_SH(...) ILVRL_B2(v8i16, __VA_ARGS__) -#define ILVRL_B2_SW(...) ILVRL_B2(v4i32, __VA_ARGS__) - -#define ILVRL_H2(RTYPE, in0, in1, low, hi) do { \ - low = (RTYPE)__builtin_msa_ilvr_h((v8i16)(in0), (v8i16)(in1)); \ - hi = (RTYPE)__builtin_msa_ilvl_h((v8i16)(in0), (v8i16)(in1)); \ - } while (0) -#define ILVRL_H2_UB(...) ILVRL_H2(v16u8, __VA_ARGS__) -#define ILVRL_H2_SB(...) ILVRL_H2(v16i8, __VA_ARGS__) -#define ILVRL_H2_UH(...) ILVRL_H2(v8u16, __VA_ARGS__) -#define ILVRL_H2_SH(...) ILVRL_H2(v8i16, __VA_ARGS__) -#define ILVRL_H2_SW(...) ILVRL_H2(v4i32, __VA_ARGS__) -#define ILVRL_H2_UW(...) ILVRL_H2(v4u32, __VA_ARGS__) - -#define ILVRL_W2(RTYPE, in0, in1, low, hi) do { \ - low = (RTYPE)__builtin_msa_ilvr_w((v4i32)(in0), (v4i32)(in1)); \ - hi = (RTYPE)__builtin_msa_ilvl_w((v4i32)(in0), (v4i32)(in1)); \ - } while (0) -#define ILVRL_W2_UB(...) ILVRL_W2(v16u8, __VA_ARGS__) -#define ILVRL_W2_SH(...) ILVRL_W2(v8i16, __VA_ARGS__) -#define ILVRL_W2_SW(...) ILVRL_W2(v4i32, __VA_ARGS__) -#define ILVRL_W2_UW(...) ILVRL_W2(v4u32, __VA_ARGS__) - -/* absq, qabsq (r = |a|;) */ -#define msa_absq_s8(a) __builtin_msa_add_a_b(a, __builtin_msa_fill_b(0)) -#define msa_absq_s16(a) __builtin_msa_add_a_h(a, __builtin_msa_fill_h(0)) -#define msa_absq_s32(a) __builtin_msa_add_a_w(a, __builtin_msa_fill_w(0)) -#define msa_absq_s64(a) __builtin_msa_add_a_d(a, __builtin_msa_fill_d(0)) -#define msa_absq_f32(a) ((v4f32)__builtin_msa_bclri_w((v4u32)(a), 31)) -#define msa_absq_f64(a) ((v2f64)__builtin_msa_bclri_d((v2u64)(a), 63)) -#define msa_qabsq_s8(a) __builtin_msa_adds_a_b(a, __builtin_msa_fill_b(0)) -#define msa_qabsq_s16(a) __builtin_msa_adds_a_h(a, __builtin_msa_fill_h(0)) -#define msa_qabsq_s32(a) __builtin_msa_adds_a_w(a, __builtin_msa_fill_w(0)) -#define msa_qabsq_s64(a) __builtin_msa_adds_a_d(a, __builtin_msa_fill_d(0)) - -/* abdq, qabdq (r = |a - b|;) */ -#define msa_abdq_u8 __builtin_msa_asub_u_b -#define msa_abdq_s8 __builtin_msa_asub_s_b -#define msa_abdq_u16 __builtin_msa_asub_u_h -#define msa_abdq_s16 __builtin_msa_asub_s_h -#define msa_abdq_u32 __builtin_msa_asub_u_w -#define msa_abdq_s32 __builtin_msa_asub_s_w -#define msa_abdq_u64 __builtin_msa_asub_u_d -#define msa_abdq_s64 __builtin_msa_asub_s_d -#define msa_abdq_f32(a, b) msa_absq_f32(__builtin_msa_fsub_w(a, b)) -#define msa_abdq_f64(a, b) msa_absq_f64(__builtin_msa_fsub_d(a, b)) -#define msa_qabdq_s8(a, b) msa_qabsq_s8(__builtin_msa_subs_s_b(a, b)) -#define msa_qabdq_s16(a, b) msa_qabsq_s16(__builtin_msa_subs_s_h(a, b)) -#define msa_qabdq_s32(a, b) msa_qabsq_s32(__builtin_msa_subs_s_w(a, b)) -#define msa_qabdq_s64(a, b) msa_qabsq_s64(__builtin_msa_subs_s_d(a, b)) - -/* sqrtq, rsqrtq */ -#define msa_sqrtq_f32 __builtin_msa_fsqrt_w -#define msa_sqrtq_f64 __builtin_msa_fsqrt_d -#define msa_rsqrtq_f32 __builtin_msa_frsqrt_w -#define msa_rsqrtq_f64 __builtin_msa_frsqrt_d - - -/* mlaq: r = a + b * c; */ -__extension__ extern __inline v4i32 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_s32(v4i32 __a, v4i32 __b, v4i32 __c) -{ - __asm__ volatile("maddv.w %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -__extension__ extern __inline v2i64 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_s64(v2i64 __a, v2i64 __b, v2i64 __c) -{ - __asm__ volatile("maddv.d %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -__extension__ extern __inline v4f32 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_f32(v4f32 __a, v4f32 __b, v4f32 __c) -{ - __asm__ volatile("fmadd.w %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -__extension__ extern __inline v2f64 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_mlaq_f64(v2f64 __a, v2f64 __b, v2f64 __c) -{ - __asm__ volatile("fmadd.d %w[__a], %w[__b], %w[__c]\n" - // Outputs - : [__a] "+f"(__a) - // Inputs - : [__b] "f"(__b), [__c] "f"(__c)); - return __a; -} - -/* cntq */ -#define msa_cntq_s8 __builtin_msa_pcnt_b -#define msa_cntq_s16 __builtin_msa_pcnt_h -#define msa_cntq_s32 __builtin_msa_pcnt_w -#define msa_cntq_s64 __builtin_msa_pcnt_d - -/* bslq (a: mask; r = b(if a == 0); r = c(if a == 1);) */ -#define msa_bslq_u8 __builtin_msa_bsel_v - -/* ilvrq, ilvlq (For EL only, ilvrq: b0, a0, b1, a1; ilvlq: b2, a2, b3, a3;) */ -#define msa_ilvrq_s8 __builtin_msa_ilvr_b -#define msa_ilvrq_s16 __builtin_msa_ilvr_h -#define msa_ilvrq_s32 __builtin_msa_ilvr_w -#define msa_ilvrq_s64 __builtin_msa_ilvr_d -#define msa_ilvlq_s8 __builtin_msa_ilvl_b -#define msa_ilvlq_s16 __builtin_msa_ilvl_h -#define msa_ilvlq_s32 __builtin_msa_ilvl_w -#define msa_ilvlq_s64 __builtin_msa_ilvl_d - -/* ilvevq, ilvodq (ilvevq: b0, a0, b2, a2; ilvodq: b1, a1, b3, a3; ) */ -#define msa_ilvevq_s8 __builtin_msa_ilvev_b -#define msa_ilvevq_s16 __builtin_msa_ilvev_h -#define msa_ilvevq_s32 __builtin_msa_ilvev_w -#define msa_ilvevq_s64 __builtin_msa_ilvev_d -#define msa_ilvodq_s8 __builtin_msa_ilvod_b -#define msa_ilvodq_s16 __builtin_msa_ilvod_h -#define msa_ilvodq_s32 __builtin_msa_ilvod_w -#define msa_ilvodq_s64 __builtin_msa_ilvod_d - -/* extq (r = (a || b); a concatenation b and get elements from index c) */ -#ifdef _MIPSEB -#define msa_extq_s8(a, b, c) \ -(__builtin_msa_vshf_b(__builtin_msa_subv_b((v16i8)((v2i64){0x1716151413121110, 0x1F1E1D1C1B1A1918}), __builtin_msa_fill_b(c)), a, b)) -#define msa_extq_s16(a, b, c) \ -(__builtin_msa_vshf_h(__builtin_msa_subv_h((v8i16)((v2i64){0x000B000A00090008, 0x000F000E000D000C}), __builtin_msa_fill_h(c)), a, b)) -#define msa_extq_s32(a, b, c) \ -(__builtin_msa_vshf_w(__builtin_msa_subv_w((v4i32)((v2i64){0x0000000500000004, 0x0000000700000006}), __builtin_msa_fill_w(c)), a, b)) -#define msa_extq_s64(a, b, c) \ -(__builtin_msa_vshf_d(__builtin_msa_subv_d((v2i64){0x0000000000000002, 0x0000000000000003}, __builtin_msa_fill_d(c)), a, b)) -#else -#define msa_extq_s8(a, b, c) \ -(__builtin_msa_vshf_b(__builtin_msa_addv_b((v16i8)((v2i64){0x0706050403020100, 0x0F0E0D0C0B0A0908}), __builtin_msa_fill_b(c)), b, a)) -#define msa_extq_s16(a, b, c) \ -(__builtin_msa_vshf_h(__builtin_msa_addv_h((v8i16)((v2i64){0x0003000200010000, 0x0007000600050004}), __builtin_msa_fill_h(c)), b, a)) -#define msa_extq_s32(a, b, c) \ -(__builtin_msa_vshf_w(__builtin_msa_addv_w((v4i32)((v2i64){0x0000000100000000, 0x0000000300000002}), __builtin_msa_fill_w(c)), b, a)) -#define msa_extq_s64(a, b, c) \ -(__builtin_msa_vshf_d(__builtin_msa_addv_d((v2i64){0x0000000000000000, 0x0000000000000001}, __builtin_msa_fill_d(c)), b, a)) -#endif /* _MIPSEB */ - -/* cvttruncq, cvttintq, cvtrintq */ -#define msa_cvttruncq_u32_f32 __builtin_msa_ftrunc_u_w -#define msa_cvttruncq_s32_f32 __builtin_msa_ftrunc_s_w -#define msa_cvttruncq_u64_f64 __builtin_msa_ftrunc_u_d -#define msa_cvttruncq_s64_f64 __builtin_msa_ftrunc_s_d -#define msa_cvttintq_u32_f32 __builtin_msa_ftint_u_w -#define msa_cvttintq_s32_f32 __builtin_msa_ftint_s_w -#define msa_cvttintq_u64_f64 __builtin_msa_ftint_u_d -#define msa_cvttintq_s64_f64 __builtin_msa_ftint_s_d -#define msa_cvtrintq_f32 __builtin_msa_frint_w -#define msa_cvtrintq_f64 __builtin_msa_frint_d - -/* cvtfintq, cvtfq */ -#define msa_cvtfintq_f32_u32 __builtin_msa_ffint_u_w -#define msa_cvtfintq_f32_s32 __builtin_msa_ffint_s_w -#define msa_cvtfintq_f64_u64 __builtin_msa_ffint_u_d -#define msa_cvtfintq_f64_s64 __builtin_msa_ffint_s_d -#define msa_cvtfq_f32_f64 __builtin_msa_fexdo_w -#define msa_cvtflq_f64_f32 __builtin_msa_fexupr_d -#define msa_cvtfhq_f64_f32 __builtin_msa_fexupl_d - -#define msa_addl_u8(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)V8U8_2_V8I16(a), (v8i16)V8U8_2_V8I16(b))) -#define msa_addl_s8(a, b) (__builtin_msa_addv_h((v8i16)V8I8_2_V8I16(a), (v8i16)V8I8_2_V8I16(b))) -#define msa_addl_u16(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)V4U16_2_V4I32(a), (v4i32)V4U16_2_V4I32(b))) -#define msa_addl_s16(a, b) (__builtin_msa_addv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) -#define msa_subl_s16(a, b) (__builtin_msa_subv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) -#define msa_recpeq_f32 __builtin_msa_frcp_w -#define msa_recpsq_f32(a, b) (__builtin_msa_fsub_w(msa_dupq_n_f32(2.0f), __builtin_msa_fmul_w(a, b))) - -#define MSA_INTERLEAVED_IMPL_LOAD2_STORE2(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld2q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ - *a = (_Tpv)__builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ -} \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st2q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b) \ -{ \ - msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df((_Tpvs)b, (_Tpvs)a)); \ - msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df((_Tpvs)b, (_Tpvs)a)); \ -} - -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint8_t, v16u8, v16i8, u8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int8_t, v16i8, v16i8, s8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint16_t, v8u16, v8i16, u16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int16_t, v8i16, v8i16, s16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint32_t, v4u32, v4i32, u32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int32_t, v4i32, v4i32, s32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(float, v4f32, v4i32, f32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint64_t, v2u64, v2i64, u64, d, 2) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int64_t, v2i64, v2i64, s64, d, 2) -MSA_INTERLEAVED_IMPL_LOAD2_STORE2(double, v2f64, v2i64, f64, d, 2) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ - _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0704011F1F1F1F1F, 0x1F1C191613100D0A}), (_Tpvs)v0, (_Tpvs)v1); \ - *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150E0B080502, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0603001F1F1F1F1F, 0x1E1B1815120F0C09}), (_Tpvs)v0, (_Tpvs)v1); \ - *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150D0A070401, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x05021F1F1F1F1F1F, 0x1D1A1714110E0B08}), (_Tpvs)v0, (_Tpvs)v1); \ - *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x17160F0C09060300, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ -} -#else -#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ - _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15120F0C09060300, 0x00000000001E1B18}), (_Tpvs)v1, (_Tpvs)v0); \ - *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1D1A1714110A0908}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1613100D0A070401, 0x00000000001F1C19}), (_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1E1B1815120A0908}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1714110E0B080502, 0x0000000000001D1A}), (_Tpvs)v1, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1F1C191613100908}), (_Tpvs)v2, v3); \ -} -#endif - -MSA_INTERLEAVED_IMPL_LOAD3_8(uint8_t, v16u8, v16i8, u8) -MSA_INTERLEAVED_IMPL_LOAD3_8(int8_t, v16i8, v16i8, s8) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ - _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00030000000F000F, 0x000F000C00090006}), (_Tpvs)v1, (_Tpvs)v0); \ - *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000A00050002, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0002000F000F000F, 0x000E000B00080005}), (_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000700040001, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000F000F000F, 0x000D000A00070004}), (_Tpvs)v1, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000600030000, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ -} -#else -#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ - _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0009000600030000, 0x00000000000F000C}), (_Tpvs)v1, (_Tpvs)v0); \ - *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000D000A00050004}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A000700040001, 0x000000000000000D}), (_Tpvs)v1, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000E000B00080004}), (_Tpvs)v2, v3); \ - v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000800050002, 0x000000000000000E}), (_Tpvs)v1, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000F000C00090004}), (_Tpvs)v2, v3); \ -} -#endif - -MSA_INTERLEAVED_IMPL_LOAD3_16(uint16_t, v8u16, v8i16, u16) -MSA_INTERLEAVED_IMPL_LOAD3_16(int16_t, v8i16, v8i16, s16) - -#define MSA_INTERLEAVED_IMPL_LOAD3_32(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - _Tpv v00 = msa_ld1q_##suffix(ptr); \ - _Tpv v01 = msa_ld1q_##suffix(ptr + 4); \ - _Tpv v02 = msa_ld1q_##suffix(ptr + 8); \ - _Tpvs v10 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v01, (v2i64)v01), (_Tpvs)v00); \ - _Tpvs v11 = __builtin_msa_ilvr_w((_Tpvs)v02, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v00, (v2i64)v00)); \ - _Tpvs v12 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v02, (v2i64)v02), (_Tpvs)v01); \ - *a = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v11, (v2i64)v11), v10); \ - *b = (_Tpv)__builtin_msa_ilvr_w(v12, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v10, (v2i64)v10)); \ - *c = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v12, (v2i64)v12), v11); \ -} - -MSA_INTERLEAVED_IMPL_LOAD3_32(uint32_t, v4u32, v4i32, u32) -MSA_INTERLEAVED_IMPL_LOAD3_32(int32_t, v4i32, v4i32, s32) -MSA_INTERLEAVED_IMPL_LOAD3_32(float, v4f32, v4i32, f32) - -#define MSA_INTERLEAVED_IMPL_LOAD3_64(_Tp, _Tpv, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ -{ \ - *((_Tp*)a) = *ptr; *((_Tp*)b) = *(ptr + 1); *((_Tp*)c) = *(ptr + 2); \ - *((_Tp*)a + 1) = *(ptr + 3); *((_Tp*)b + 1) = *(ptr + 4); *((_Tp*)c + 1) = *(ptr + 5); \ -} - -MSA_INTERLEAVED_IMPL_LOAD3_64(uint64_t, v2u64, u64) -MSA_INTERLEAVED_IMPL_LOAD3_64(int64_t, v2i64, s64) -MSA_INTERLEAVED_IMPL_LOAD3_64(double, v2f64, f64) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0F0E0D0C0B1F1F1F, 0x1F1E1D1C1B1A1F1F}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0D1C140C1B130B1A, 0x1F170F1E160E1D15}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A09080706051F1F, 0x19181716151F1F1F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1D14071C13061B12, 0x170A1F16091E1508}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x04030201001F1F1F, 0x14131211101F1F1F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15021C14011B1300, 0x051F17041E16031D}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ -} -#else -#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000050403020100, 0x0000001413121110}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A02110901100800, 0x05140C04130B0312}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000A09080706, 0x00001A1918171615}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x170A011609001508, 0x0D04190C03180B02}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000F0E0D0C0B, 0x0000001F1E1D1C1B}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x021C09011B08001A, 0x1F0C041E0B031D0A}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ -} -#endif - -MSA_INTERLEAVED_IMPL_STORE3_8(uint8_t, v16u8, v16i8, u8) -MSA_INTERLEAVED_IMPL_STORE3_8(int8_t, v16i8, v16i8, s8) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000700060005000F, 0x000F000E000D000F}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A0006000D0009, 0x000F000B0007000E}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00040003000F000F, 0x000C000B000A000F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000E000A0003000D, 0x0005000F000B0004}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000200010000000F, 0x00090008000F000F}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000E00090000, 0x000B0002000F000A}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ -} -#else -#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000200010000, 0x0000000A00090008}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000800040000, 0x0006000200090005}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000500040003, 0x00000000000C000B}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B00040000000A, 0x0002000C00050001}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000000070006, 0x0000000F000E000D}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00050000000D0004, 0x000F00060001000E}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ -} -#endif - -MSA_INTERLEAVED_IMPL_STORE3_16(uint16_t, v8u16, v8i16, u16) -MSA_INTERLEAVED_IMPL_STORE3_16(int16_t, v8i16, v8i16, s16) - -#ifdef _MIPSEB -#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000007, 0x0000000700000006}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000006, 0x0000000700000005}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000001, 0x0000000500000007}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000700000004, 0x0000000500000002}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000007, 0x0000000400000007}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000000, 0x0000000100000007}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ -} -#else -#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000100000000, 0x0000000000000004}), (_Tpvs)b, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000000, 0x0000000100000004}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000002, 0x0000000600000005}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000002, 0x0000000300000000}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ - v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000003, 0x0000000000000007}), (_Tpvs)b, (_Tpvs)a); \ - v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000006, 0x0000000700000002}), (_Tpvs)c, (_Tpvs)v0); \ - msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ -} -#endif - -MSA_INTERLEAVED_IMPL_STORE3_32(uint32_t, v4u32, v4i32, u32) -MSA_INTERLEAVED_IMPL_STORE3_32(int32_t, v4i32, v4i32, s32) -MSA_INTERLEAVED_IMPL_STORE3_32(float, v4f32, v4i32, f32) - -#define MSA_INTERLEAVED_IMPL_STORE3_64(_Tp, _Tpv, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ -{ \ - *ptr = a[0]; *(ptr + 1) = b[0]; *(ptr + 2) = c[0]; \ - *(ptr + 3) = a[1]; *(ptr + 4) = b[1]; *(ptr + 5) = c[1]; \ -} - -MSA_INTERLEAVED_IMPL_STORE3_64(uint64_t, v2u64, u64) -MSA_INTERLEAVED_IMPL_STORE3_64(int64_t, v2i64, s64) -MSA_INTERLEAVED_IMPL_STORE3_64(double, v2f64, f64) - -#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + nlanes * 2); \ - _Tpv v3 = msa_ld1q_##suffix(ptr + nlanes * 3); \ - _Tpvs t0 = __builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ - _Tpvs t1 = __builtin_msa_pckev_##df((_Tpvs)v3, (_Tpvs)v2); \ - _Tpvs t2 = __builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ - _Tpvs t3 = __builtin_msa_pckod_##df((_Tpvs)v3, (_Tpvs)v2); \ - *a = (_Tpv)__builtin_msa_pckev_##df(t1, t0); \ - *b = (_Tpv)__builtin_msa_pckev_##df(t3, t2); \ - *c = (_Tpv)__builtin_msa_pckod_##df(t1, t0); \ - *d = (_Tpv)__builtin_msa_pckod_##df(t3, t2); \ -} \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ -{ \ - _Tpvs v0 = __builtin_msa_ilvr_##df((_Tpvs)c, (_Tpvs)a); \ - _Tpvs v1 = __builtin_msa_ilvr_##df((_Tpvs)d, (_Tpvs)b); \ - _Tpvs v2 = __builtin_msa_ilvl_##df((_Tpvs)c, (_Tpvs)a); \ - _Tpvs v3 = __builtin_msa_ilvl_##df((_Tpvs)d, (_Tpvs)b); \ - msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df(v1, v0)); \ - msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df(v1, v0)); \ - msa_st1q_##suffix(ptr + 2 * nlanes, (_Tpv)__builtin_msa_ilvr_##df(v3, v2)); \ - msa_st1q_##suffix(ptr + 3 * nlanes, (_Tpv)__builtin_msa_ilvl_##df(v3, v2)); \ -} - -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint8_t, v16u8, v16i8, u8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int8_t, v16i8, v16i8, s8, b, 16) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint16_t, v8u16, v8i16, u16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int16_t, v8i16, v8i16, s16, h, 8) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint32_t, v4u32, v4i32, u32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int32_t, v4i32, v4i32, s32, w, 4) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4(float, v4f32, v4i32, f32, w, 4) - -#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(_Tp, _Tpv, _Tpvs, suffix) \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ -{ \ - _Tpv v0 = msa_ld1q_##suffix(ptr); \ - _Tpv v1 = msa_ld1q_##suffix(ptr + 2); \ - _Tpv v2 = msa_ld1q_##suffix(ptr + 4); \ - _Tpv v3 = msa_ld1q_##suffix(ptr + 6); \ - *a = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v2, (_Tpvs)v0); \ - *b = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v2, (_Tpvs)v0); \ - *c = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v3, (_Tpvs)v1); \ - *d = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v3, (_Tpvs)v1); \ -} \ -__extension__ extern __inline void \ -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ -msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ -{ \ - msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)b, (_Tpvs)a)); \ - msa_st1q_##suffix(ptr + 2, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)d, (_Tpvs)c)); \ - msa_st1q_##suffix(ptr + 4, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)b, (_Tpvs)a)); \ - msa_st1q_##suffix(ptr + 6, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)d, (_Tpvs)c)); \ -} - -MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(uint64_t, v2u64, v2i64, u64) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(int64_t, v2i64, v2i64, s64) -MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(double, v2f64, v2i64, f64) - -__extension__ extern __inline v8i16 -__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) -msa_qdmulhq_n_s16(v8i16 a, int16_t b) -{ - v8i16 a_lo, a_hi; - ILVRL_H2_SH(a, msa_dupq_n_s16(0), a_lo, a_hi); - return msa_packr_s32(msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_dupq_n_s32(b)), 1), - msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_hi), msa_dupq_n_s32(b)), 1), 16); -} - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif /*__mips_msa*/ -#endif /* OPENCV_CORE_MSA_MACROS_H */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_HAL_MSA_MACROS_H +#define OPENCV_CORE_HAL_MSA_MACROS_H + +#ifdef __mips_msa +#include "msa.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/* Define 64 bits vector types */ +typedef signed char v8i8 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned char v8u8 __attribute__ ((vector_size(8), aligned(8))); +typedef short v4i16 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned short v4u16 __attribute__ ((vector_size(8), aligned(8))); +typedef int v2i32 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned int v2u32 __attribute__ ((vector_size(8), aligned(8))); +typedef long long v1i64 __attribute__ ((vector_size(8), aligned(8))); +typedef unsigned long long v1u64 __attribute__ ((vector_size(8), aligned(8))); +typedef float v2f32 __attribute__ ((vector_size(8), aligned(8))); +typedef double v1f64 __attribute__ ((vector_size(8), aligned(8))); + + +/* Load values from the given memory a 64-bit vector. */ +#define msa_ld1_s8(__a) (*((v8i8*)(__a))) +#define msa_ld1_s16(__a) (*((v4i16*)(__a))) +#define msa_ld1_s32(__a) (*((v2i32*)(__a))) +#define msa_ld1_s64(__a) (*((v1i64*)(__a))) +#define msa_ld1_u8(__a) (*((v8u8*)(__a))) +#define msa_ld1_u16(__a) (*((v4u16*)(__a))) +#define msa_ld1_u32(__a) (*((v2u32*)(__a))) +#define msa_ld1_u64(__a) (*((v1u64*)(__a))) +#define msa_ld1_f32(__a) (*((v2f32*)(__a))) +#define msa_ld1_f64(__a) (*((v1f64*)(__a))) + +/* Load values from the given memory address to a 128-bit vector */ +#define msa_ld1q_s8(__a) ((v16i8)__builtin_msa_ld_b(__a, 0)) +#define msa_ld1q_s16(__a) ((v8i16)__builtin_msa_ld_h(__a, 0)) +#define msa_ld1q_s32(__a) ((v4i32)__builtin_msa_ld_w(__a, 0)) +#define msa_ld1q_s64(__a) ((v2i64)__builtin_msa_ld_d(__a, 0)) +#define msa_ld1q_u8(__a) ((v16u8)__builtin_msa_ld_b(__a, 0)) +#define msa_ld1q_u16(__a) ((v8u16)__builtin_msa_ld_h(__a, 0)) +#define msa_ld1q_u32(__a) ((v4u32)__builtin_msa_ld_w(__a, 0)) +#define msa_ld1q_u64(__a) ((v2u64)__builtin_msa_ld_d(__a, 0)) +#define msa_ld1q_f32(__a) ((v4f32)__builtin_msa_ld_w(__a, 0)) +#define msa_ld1q_f64(__a) ((v2f64)__builtin_msa_ld_d(__a, 0)) + +/* Store 64bits vector elements values to the given memory address. */ +#define msa_st1_s8(__a, __b) (*((v8i8*)(__a)) = __b) +#define msa_st1_s16(__a, __b) (*((v4i16*)(__a)) = __b) +#define msa_st1_s32(__a, __b) (*((v2i32*)(__a)) = __b) +#define msa_st1_s64(__a, __b) (*((v1i64*)(__a)) = __b) +#define msa_st1_u8(__a, __b) (*((v8u8*)(__a)) = __b) +#define msa_st1_u16(__a, __b) (*((v4u16*)(__a)) = __b) +#define msa_st1_u32(__a, __b) (*((v2u32*)(__a)) = __b) +#define msa_st1_u64(__a, __b) (*((v1u64*)(__a)) = __b) +#define msa_st1_f32(__a, __b) (*((v2f32*)(__a)) = __b) +#define msa_st1_f64(__a, __b) (*((v1f64*)(__a)) = __b) + +/* Store the values of elements in the 128 bits vector __a to the given memory address __a. */ +#define msa_st1q_s8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) +#define msa_st1q_s16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) +#define msa_st1q_s32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) +#define msa_st1q_s64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) +#define msa_st1q_u8(__a, __b) (__builtin_msa_st_b((v16i8)(__b), __a, 0)) +#define msa_st1q_u16(__a, __b) (__builtin_msa_st_h((v8i16)(__b), __a, 0)) +#define msa_st1q_u32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) +#define msa_st1q_u64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) +#define msa_st1q_f32(__a, __b) (__builtin_msa_st_w((v4i32)(__b), __a, 0)) +#define msa_st1q_f64(__a, __b) (__builtin_msa_st_d((v2i64)(__b), __a, 0)) + +/* Store the value of the element with the index __c in vector __a to the given memory address __a. */ +#define msa_st1_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = __b[__c]) +#define msa_st1_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = __b[__c]) +#define msa_st1_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __b[__c]) +#define msa_st1_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __b[__c]) +#define msa_st1_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __b[__c]) +#define msa_st1_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) +#define msa_st1_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) +#define msa_st1q_lane_s8(__a, __b, __c) (*((int8_t*)(__a)) = (int8_t)__builtin_msa_copy_s_b(__b, __c)) +#define msa_st1q_lane_s16(__a, __b, __c) (*((int16_t*)(__a)) = (int16_t)__builtin_msa_copy_s_h(__b, __c)) +#define msa_st1q_lane_s32(__a, __b, __c) (*((int32_t*)(__a)) = __builtin_msa_copy_s_w(__b, __c)) +#define msa_st1q_lane_s64(__a, __b, __c) (*((int64_t*)(__a)) = __builtin_msa_copy_s_d(__b, __c)) +#define msa_st1q_lane_u8(__a, __b, __c) (*((uint8_t*)(__a)) = (uint8_t)__builtin_msa_copy_u_b((v16i8)(__b), __c)) +#define msa_st1q_lane_u16(__a, __b, __c) (*((uint16_t*)(__a)) = (uint16_t)__builtin_msa_copy_u_h((v8i16)(__b), __c)) +#define msa_st1q_lane_u32(__a, __b, __c) (*((uint32_t*)(__a)) = __builtin_msa_copy_u_w((v4i32)(__b), __c)) +#define msa_st1q_lane_u64(__a, __b, __c) (*((uint64_t*)(__a)) = __builtin_msa_copy_u_d((v2i64)(__b), __c)) +#define msa_st1q_lane_f32(__a, __b, __c) (*((float*)(__a)) = __b[__c]) +#define msa_st1q_lane_f64(__a, __b, __c) (*((double*)(__a)) = __b[__c]) + +/* Duplicate elements for 64-bit doubleword vectors */ +#define msa_dup_n_s8(__a) ((v8i8)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) +#define msa_dup_n_s16(__a) ((v4i16)__builtin_msa_copy_s_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) +#define msa_dup_n_s32(__a) ((v2i32){__a, __a}) +#define msa_dup_n_s64(__a) ((v1i64){__a}) +#define msa_dup_n_u8(__a) ((v8u8)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_b((int32_t)(__a)), 0)) +#define msa_dup_n_u16(__a) ((v4u16)__builtin_msa_copy_u_d((v2i64)__builtin_msa_fill_h((int32_t)(__a)), 0)) +#define msa_dup_n_u32(__a) ((v2u32){__a, __a}) +#define msa_dup_n_u64(__a) ((v1u64){__a}) +#define msa_dup_n_f32(__a) ((v2f32){__a, __a}) +#define msa_dup_n_f64(__a) ((v1f64){__a}) + +/* Duplicate elements for 128-bit quadword vectors */ +#define msa_dupq_n_s8(__a) (__builtin_msa_fill_b((int32_t)(__a))) +#define msa_dupq_n_s16(__a) (__builtin_msa_fill_h((int32_t)(__a))) +#define msa_dupq_n_s32(__a) (__builtin_msa_fill_w((int32_t)(__a))) +#define msa_dupq_n_s64(__a) (__builtin_msa_fill_d((int64_t)(__a))) +#define msa_dupq_n_u8(__a) ((v16u8)__builtin_msa_fill_b((int32_t)(__a))) +#define msa_dupq_n_u16(__a) ((v8u16)__builtin_msa_fill_h((int32_t)(__a))) +#define msa_dupq_n_u32(__a) ((v4u32)__builtin_msa_fill_w((int32_t)(__a))) +#define msa_dupq_n_u64(__a) ((v2u64)__builtin_msa_fill_d((int64_t)(__a))) +#define msa_dupq_n_f32(__a) ((v4f32){__a, __a, __a, __a}) +#define msa_dupq_n_f64(__a) ((v2f64){__a, __a}) +#define msa_dupq_lane_s8(__a, __b) (__builtin_msa_splat_b(__a, __b)) +#define msa_dupq_lane_s16(__a, __b) (__builtin_msa_splat_h(__a, __b)) +#define msa_dupq_lane_s32(__a, __b) (__builtin_msa_splat_w(__a, __b)) +#define msa_dupq_lane_s64(__a, __b) (__builtin_msa_splat_d(__a, __b)) +#define msa_dupq_lane_u8(__a, __b) ((v16u8)__builtin_msa_splat_b((v16i8)(__a), __b)) +#define msa_dupq_lane_u16(__a, __b) ((v8u16)__builtin_msa_splat_h((v8i16)(__a), __b)) +#define msa_dupq_lane_u32(__a, __b) ((v4u32)__builtin_msa_splat_w((v4i32)(__a), __b)) +#define msa_dupq_lane_u64(__a, __b) ((v2u64)__builtin_msa_splat_d((v2i64)(__a), __b)) + +/* Create a 64 bits vector */ +#define msa_create_s8(__a) ((v8i8)((uint64_t)(__a))) +#define msa_create_s16(__a) ((v4i16)((uint64_t)(__a))) +#define msa_create_s32(__a) ((v2i32)((uint64_t)(__a))) +#define msa_create_s64(__a) ((v1i64)((uint64_t)(__a))) +#define msa_create_u8(__a) ((v8u8)((uint64_t)(__a))) +#define msa_create_u16(__a) ((v4u16)((uint64_t)(__a))) +#define msa_create_u32(__a) ((v2u32)((uint64_t)(__a))) +#define msa_create_u64(__a) ((v1u64)((uint64_t)(__a))) +#define msa_create_f32(__a) ((v2f32)((uint64_t)(__a))) +#define msa_create_f64(__a) ((v1f64)((uint64_t)(__a))) + +/* Sign extends or zero extends each element in a 64 bits vector to twice its original length, and places the results in a 128 bits vector. */ +/*Transform v8i8 to v8i16*/ +#define msa_movl_s8(__a) \ +((v8i16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ + (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) + +/*Transform v8u8 to v8u16*/ +#define msa_movl_u8(__a) \ +((v8u16){(__a)[0], (__a)[1], (__a)[2], (__a)[3], \ + (__a)[4], (__a)[5], (__a)[6], (__a)[7]}) + +/*Transform v4i16 to v8i16*/ +#define msa_movl_s16(__a) ((v4i32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) + +/*Transform v2i32 to v4i32*/ +#define msa_movl_s32(__a) ((v2i64){(__a)[0], (__a)[1]}) + +/*Transform v4u16 to v8u16*/ +#define msa_movl_u16(__a) ((v4u32){(__a)[0], (__a)[1], (__a)[2], (__a)[3]}) + +/*Transform v2u32 to v4u32*/ +#define msa_movl_u32(__a) ((v2u64){(__a)[0], (__a)[1]}) + +/* Copies the least significant half of each element of a 128 bits vector into the corresponding elements of a 64 bits vector. */ +#define msa_movn_s16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_movn_s32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_movn_s64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_movn_u16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)(__a)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_movn_u32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_movn_u64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* qmovn */ +#define msa_qmovn_s16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7)); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_s32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15)); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_s64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31)); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_u16(__a) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_u32(__a) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_qmovn_u64(__a) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* qmovun */ +#define msa_qmovun_s16(__a) \ +({ \ + v8i16 __d = __builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qmovun_s32(__a) \ +({ \ + v4i32 __d = __builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qmovun_s64(__a) \ +({ \ + v2i64 __d = __builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ +#define msa_shrn_n_s16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__b))); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_s32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__b))); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_s64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__b))); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_u16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__b))); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_u32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__b))); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_shrn_n_u64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__b))); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, and places the results in a 64 bits vector. */ +#define msa_rshrn_n_s16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)__b)); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_s32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)__b)); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_s64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)__b)); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_u16(__a, __b) \ +({ \ + v16i8 __d = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)__b)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_u32(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)__b)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +#define msa_rshrn_n_u64(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)__b)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__d, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. */ +#define msa_qrshrn_n_s16(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__b)), 7); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ + (v8i8)__builtin_msa_copy_s_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_s32(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__b)), 15); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ + (v4i16)__builtin_msa_copy_s_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_s64(__a, __b) \ +({ \ + v2i64 __d = __builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__b)), 31); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ + (v2i32)__builtin_msa_copy_s_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_u16(__a, __b) \ +({ \ + v8u16 __d = __builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__b)), 7); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__d); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_u32(__a, __b) \ +({ \ + v4u32 __d = __builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__b)), 15); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__d); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrn_n_u64(__a, __b) \ +({ \ + v2u64 __d = __builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__b)), 31); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__d); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +/* Right shift elements in a 128 bits vector by an immediate value, saturate the results and them in a 64 bits vector. + Input is signed and output is unsigned. */ +#define msa_qrshrun_n_s16(__a, __b) \ +({ \ + v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__b)); \ + v16i8 __e = __builtin_msa_pckev_b(__builtin_msa_fill_b(0), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ + (v8u8)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrun_n_s32(__a, __b) \ +({ \ + v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__b)); \ + v8i16 __e = __builtin_msa_pckev_h(__builtin_msa_fill_h(0), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ + (v4u16)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +#define msa_qrshrun_n_s64(__a, __b) \ +({ \ + v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__b)); \ + v4i32 __e = __builtin_msa_pckev_w(__builtin_msa_fill_w(0), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ + (v2u32)__builtin_msa_copy_u_d((v2i64)__e, 0); \ +}) + +/* pack */ +#define msa_pack_s16(__a, __b) (__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) +#define msa_pack_s32(__a, __b) (__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) +#define msa_pack_s64(__a, __b) (__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) +#define msa_pack_u16(__a, __b) ((v16u8)__builtin_msa_pckev_b((v16i8)(__b), (v16i8)(__a))) +#define msa_pack_u32(__a, __b) ((v8u16)__builtin_msa_pckev_h((v8i16)(__b), (v8i16)(__a))) +#define msa_pack_u64(__a, __b) ((v4u32)__builtin_msa_pckev_w((v4i32)(__b), (v4i32)(__a))) + +/* qpack */ +#define msa_qpack_s16(__a, __b) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h((v8i16)(__b), 7), (v16i8)__builtin_msa_sat_s_h((v8i16)(__a), 7))) +#define msa_qpack_s32(__a, __b) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w((v4i32)(__b), 15), (v8i16)__builtin_msa_sat_s_w((v4i32)(__a), 15))) +#define msa_qpack_s64(__a, __b) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d((v2i64)(__b), 31), (v4i32)__builtin_msa_sat_s_d((v2i64)(__a), 31))) +#define msa_qpack_u16(__a, __b) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__b), 7), (v16i8)__builtin_msa_sat_u_h((v8u16)(__a), 7))) +#define msa_qpack_u32(__a, __b) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__b), 15), (v8i16)__builtin_msa_sat_u_w((v4u32)(__a), 15))) +#define msa_qpack_u64(__a, __b) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__b), 31), (v4i32)__builtin_msa_sat_u_d((v2u64)(__a), 31))) + +/* qpacku */ +#define msa_qpacku_s16(__a, __b) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b))), 7), \ + (v16i8)__builtin_msa_sat_u_h((v8u16)(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a))), 7))) +#define msa_qpacku_s32(__a, __b) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b))), 15), \ + (v8i16)__builtin_msa_sat_u_w((v4u32)(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a))), 15))) +#define msa_qpacku_s64(__a, __b) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b))), 31), \ + (v4i32)__builtin_msa_sat_u_d((v2u64)(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a))), 31))) + +/* packr */ +#define msa_packr_s16(__a, __b, __c) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_srai_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srai_h((v8i16)(__a), (int)(__c)))) +#define msa_packr_s32(__a, __b, __c) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_srai_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srai_w((v4i32)(__a), (int)(__c)))) +#define msa_packr_s64(__a, __b, __c) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_srai_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srai_d((v2i64)(__a), (int)(__c)))) +#define msa_packr_u16(__a, __b, __c) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srli_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srli_h((v8i16)(__a), (int)(__c)))) +#define msa_packr_u32(__a, __b, __c) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srli_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srli_w((v4i32)(__a), (int)(__c)))) +#define msa_packr_u64(__a, __b, __c) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srli_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srli_d((v2i64)(__a), (int)(__c)))) + +/* rpackr */ +#define msa_rpackr_s16(__a, __b, __c) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srari_h((v8i16)(__a), (int)(__c)))) +#define msa_rpackr_s32(__a, __b, __c) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srari_w((v4i32)(__a), (int)(__c)))) +#define msa_rpackr_s64(__a, __b, __c) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srari_d((v2i64)(__a), (int)(__c)))) +#define msa_rpackr_u16(__a, __b, __c) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), (v16i8)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)))) +#define msa_rpackr_u32(__a, __b, __c) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), (v8i16)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)))) +#define msa_rpackr_u64(__a, __b, __c) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), (v4i32)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)))) + +/* qrpackr */ +#define msa_qrpackr_s16(__a, __b, __c) \ +(__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__b), (int)(__c)), 7), \ + (v16i8)__builtin_msa_sat_s_h(__builtin_msa_srari_h((v8i16)(__a), (int)(__c)), 7))) +#define msa_qrpackr_s32(__a, __b, __c) \ +(__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__b), (int)(__c)), 15), \ + (v8i16)__builtin_msa_sat_s_w(__builtin_msa_srari_w((v4i32)(__a), (int)(__c)), 15))) +#define msa_qrpackr_s64(__a, __b, __c) \ +(__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__b), (int)(__c)), 31), \ + (v4i32)__builtin_msa_sat_s_d(__builtin_msa_srari_d((v2i64)(__a), (int)(__c)), 31))) +#define msa_qrpackr_u16(__a, __b, __c) \ +((v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__b), (int)(__c)), 7), \ + (v16i8)__builtin_msa_sat_u_h((v8u16)__builtin_msa_srlri_h((v8i16)(__a), (int)(__c)), 7))) +#define msa_qrpackr_u32(__a, __b, __c) \ +((v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__b), (int)(__c)), 15), \ + (v8i16)__builtin_msa_sat_u_w((v4u32)__builtin_msa_srlri_w((v4i32)(__a), (int)(__c)), 15))) +#define msa_qrpackr_u64(__a, __b, __c) \ +((v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__b), (int)(__c)), 31), \ + (v4i32)__builtin_msa_sat_u_d((v2u64)__builtin_msa_srlri_d((v2i64)(__a), (int)(__c)), 31))) + +/* qrpackru */ +#define msa_qrpackru_s16(__a, __b, __c) \ +({ \ + v8i16 __d = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__a)), (int)(__c)); \ + v8i16 __e = __builtin_msa_srlri_h(__builtin_msa_max_s_h(__builtin_msa_fill_h(0), (v8i16)(__b)), (int)(__c)); \ + (v16u8)__builtin_msa_pckev_b((v16i8)__builtin_msa_sat_u_h((v8u16)__e, 7), (v16i8)__builtin_msa_sat_u_h((v8u16)__d, 7)); \ +}) + +#define msa_qrpackru_s32(__a, __b, __c) \ +({ \ + v4i32 __d = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__a)), (int)(__c)); \ + v4i32 __e = __builtin_msa_srlri_w(__builtin_msa_max_s_w(__builtin_msa_fill_w(0), (v4i32)(__b)), (int)(__c)); \ + (v8u16)__builtin_msa_pckev_h((v8i16)__builtin_msa_sat_u_w((v4u32)__e, 15), (v8i16)__builtin_msa_sat_u_w((v4u32)__d, 15)); \ +}) + +#define msa_qrpackru_s64(__a, __b, __c) \ +({ \ + v2i64 __d = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__a)), (int)(__c)); \ + v2i64 __e = __builtin_msa_srlri_d(__builtin_msa_max_s_d(__builtin_msa_fill_d(0), (v2i64)(__b)), (int)(__c)); \ + (v4u32)__builtin_msa_pckev_w((v4i32)__builtin_msa_sat_u_d((v2u64)__e, 31), (v4i32)__builtin_msa_sat_u_d((v2u64)__d, 31)); \ +}) + +/* Minimum values between corresponding elements in the two vectors are written to the returned vector. */ +#define msa_minq_s8(__a, __b) (__builtin_msa_min_s_b(__a, __b)) +#define msa_minq_s16(__a, __b) (__builtin_msa_min_s_h(__a, __b)) +#define msa_minq_s32(__a, __b) (__builtin_msa_min_s_w(__a, __b)) +#define msa_minq_s64(__a, __b) (__builtin_msa_min_s_d(__a, __b)) +#define msa_minq_u8(__a, __b) ((v16u8)__builtin_msa_min_u_b(__a, __b)) +#define msa_minq_u16(__a, __b) ((v8u16)__builtin_msa_min_u_h(__a, __b)) +#define msa_minq_u32(__a, __b) ((v4u32)__builtin_msa_min_u_w(__a, __b)) +#define msa_minq_u64(__a, __b) ((v2u64)__builtin_msa_min_u_d(__a, __b)) +#define msa_minq_f32(__a, __b) (__builtin_msa_fmin_w(__a, __b)) +#define msa_minq_f64(__a, __b) (__builtin_msa_fmin_d(__a, __b)) + +/* Maximum values between corresponding elements in the two vectors are written to the returned vector. */ +#define msa_maxq_s8(__a, __b) (__builtin_msa_max_s_b(__a, __b)) +#define msa_maxq_s16(__a, __b) (__builtin_msa_max_s_h(__a, __b)) +#define msa_maxq_s32(__a, __b) (__builtin_msa_max_s_w(__a, __b)) +#define msa_maxq_s64(__a, __b) (__builtin_msa_max_s_d(__a, __b)) +#define msa_maxq_u8(__a, __b) ((v16u8)__builtin_msa_max_u_b(__a, __b)) +#define msa_maxq_u16(__a, __b) ((v8u16)__builtin_msa_max_u_h(__a, __b)) +#define msa_maxq_u32(__a, __b) ((v4u32)__builtin_msa_max_u_w(__a, __b)) +#define msa_maxq_u64(__a, __b) ((v2u64)__builtin_msa_max_u_d(__a, __b)) +#define msa_maxq_f32(__a, __b) (__builtin_msa_fmax_w(__a, __b)) +#define msa_maxq_f64(__a, __b) (__builtin_msa_fmax_d(__a, __b)) + +/* Vector type reinterpretion */ +#define MSA_TPV_REINTERPRET(_Tpv, Vec) ((_Tpv)(Vec)) + +/* Add the odd elements in vector __a with the even elements in vector __b to double width elements in the returned vector. */ +/* v8i16 msa_hadd_s16 ((v16i8)__a, (v16i8)__b) */ +#define msa_hadd_s16(__a, __b) (__builtin_msa_hadd_s_h((v16i8)(__a), (v16i8)(__b))) +/* v4i32 msa_hadd_s32 ((v8i16)__a, (v8i16)__b) */ +#define msa_hadd_s32(__a, __b) (__builtin_msa_hadd_s_w((v8i16)(__a), (v8i16)(__b))) +/* v2i64 msa_hadd_s64 ((v4i32)__a, (v4i32)__b) */ +#define msa_hadd_s64(__a, __b) (__builtin_msa_hadd_s_d((v4i32)(__a), (v4i32)(__b))) + +/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ +#define msa_pckev_s8(__a, __b) (__builtin_msa_pckev_b((v16i8)(__a), (v16i8)(__b))) +#define msa_pckev_s16(__a, __b) (__builtin_msa_pckev_h((v8i16)(__a), (v8i16)(__b))) +#define msa_pckev_s32(__a, __b) (__builtin_msa_pckev_w((v4i32)(__a), (v4i32)(__b))) +#define msa_pckev_s64(__a, __b) (__builtin_msa_pckev_d((v2i64)(__a), (v2i64)(__b))) + +/* Copy even elements in __a to the left half and even elements in __b to the right half and return the result vector. */ +#define msa_pckod_s8(__a, __b) (__builtin_msa_pckod_b((v16i8)(__a), (v16i8)(__b))) +#define msa_pckod_s16(__a, __b) (__builtin_msa_pckod_h((v8i16)(__a), (v8i16)(__b))) +#define msa_pckod_s32(__a, __b) (__builtin_msa_pckod_w((v4i32)(__a), (v4i32)(__b))) +#define msa_pckod_s64(__a, __b) (__builtin_msa_pckod_d((v2i64)(__a), (v2i64)(__b))) + +#ifdef _MIPSEB +#define LANE_IMM0_1(x) (0b1 - ((x) & 0b1)) +#define LANE_IMM0_3(x) (0b11 - ((x) & 0b11)) +#define LANE_IMM0_7(x) (0b111 - ((x) & 0b111)) +#define LANE_IMM0_15(x) (0b1111 - ((x) & 0b1111)) +#else +#define LANE_IMM0_1(x) ((x) & 0b1) +#define LANE_IMM0_3(x) ((x) & 0b11) +#define LANE_IMM0_7(x) ((x) & 0b111) +#define LANE_IMM0_15(x) ((x) & 0b1111) +#endif + +#define msa_get_lane_u8(__a, __b) ((uint8_t)(__a)[LANE_IMM0_7(__b)]) +#define msa_get_lane_s8(__a, __b) ((int8_t)(__a)[LANE_IMM0_7(__b)]) +#define msa_get_lane_u16(__a, __b) ((uint16_t)(__a)[LANE_IMM0_3(__b)]) +#define msa_get_lane_s16(__a, __b) ((int16_t)(__a)[LANE_IMM0_3(__b)]) +#define msa_get_lane_u32(__a, __b) ((uint32_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_s32(__a, __b) ((int32_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) +#define msa_get_lane_s64(__a, __b) ((int64_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_u64(__a, __b) ((uint64_t)(__a)[LANE_IMM0_1(__b)]) +#define msa_get_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) +#define msa_getq_lane_u8(__a, imm0_15) ((uint8_t)__builtin_msa_copy_u_b((v16i8)(__a), imm0_15)) +#define msa_getq_lane_s8(__a, imm0_15) ((int8_t)__builtin_msa_copy_s_b(__a, imm0_15)) +#define msa_getq_lane_u16(__a, imm0_7) ((uint16_t)__builtin_msa_copy_u_h((v8i16)(__a), imm0_7)) +#define msa_getq_lane_s16(__a, imm0_7) ((int16_t)__builtin_msa_copy_s_h(__a, imm0_7)) +#define msa_getq_lane_u32(__a, imm0_3) __builtin_msa_copy_u_w((v4i32)(__a), imm0_3) +#define msa_getq_lane_s32 __builtin_msa_copy_s_w +#define msa_getq_lane_f32(__a, __b) ((float)(__a)[LANE_IMM0_3(__b)]) +#define msa_getq_lane_f64(__a, __b) ((double)(__a)[LANE_IMM0_1(__b)]) +#if (__mips == 64) +#define msa_getq_lane_u64(__a, imm0_1) __builtin_msa_copy_u_d((v2i64)(__a), imm0_1) +#define msa_getq_lane_s64 __builtin_msa_copy_s_d +#else +#define msa_getq_lane_u64(__a, imm0_1) ((uint64_t)(__a)[LANE_IMM0_1(imm0_1)]) +#define msa_getq_lane_s64(__a, imm0_1) ((int64_t)(__a)[LANE_IMM0_1(imm0_1)]) +#endif + +/* combine */ +#if (__mips == 64) +#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v2u64){((v1u64)(a))[0], ((v1u64)(b))[0]})) +#else +#define __COMBINE_64_64(__TYPE, a, b) ((__TYPE)((v4u32){((v2u32)(a))[0], ((v2u32)(a))[1], \ + ((v2u32)(b))[0], ((v2u32)(b))[1]})) +#endif + +/* v16i8 msa_combine_s8 (v8i8 __a, v8i8 __b) */ +#define msa_combine_s8(__a, __b) __COMBINE_64_64(v16i8, __a, __b) + +/* v8i16 msa_combine_s16(v4i16 __a, v4i16 __b) */ +#define msa_combine_s16(__a, __b) __COMBINE_64_64(v8i16, __a, __b) + +/* v4i32 msa_combine_s32(v2i32 __a, v2i32 __b) */ +#define msa_combine_s32(__a, __b) __COMBINE_64_64(v4i32, __a, __b) + +/* v2i64 msa_combine_s64(v1i64 __a, v1i64 __b) */ +#define msa_combine_s64(__a, __b) __COMBINE_64_64(v2i64, __a, __b) + +/* v4f32 msa_combine_f32(v2f32 __a, v2f32 __b) */ +#define msa_combine_f32(__a, __b) __COMBINE_64_64(v4f32, __a, __b) + +/* v16u8 msa_combine_u8(v8u8 __a, v8u8 __b) */ +#define msa_combine_u8(__a, __b) __COMBINE_64_64(v16u8, __a, __b) + +/* v8u16 msa_combine_u16(v4u16 __a, v4u16 __b) */ +#define msa_combine_u16(__a, __b) __COMBINE_64_64(v8u16, __a, __b) + +/* v4u32 msa_combine_u32(v2u32 __a, v2u32 __b) */ +#define msa_combine_u32(__a, __b) __COMBINE_64_64(v4u32, __a, __b) + +/* v2u64 msa_combine_u64(v1u64 __a, v1u64 __b) */ +#define msa_combine_u64(__a, __b) __COMBINE_64_64(v2u64, __a, __b) + +/* v2f64 msa_combine_f64(v1f64 __a, v1f64 __b) */ +#define msa_combine_f64(__a, __b) __COMBINE_64_64(v2f64, __a, __b) + +/* get_low, get_high */ +#if (__mips == 64) +#define __GET_LOW(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 0)))) +#define __GET_HIGH(__TYPE, a) ((__TYPE)((v1u64)(__builtin_msa_copy_u_d((v2i64)(a), 1)))) +#else +#define __GET_LOW(__TYPE, a) ((__TYPE)(((v2u64)(a))[0])) +#define __GET_HIGH(__TYPE, a) ((__TYPE)(((v2u64)(a))[1])) +#endif + +/* v8i8 msa_get_low_s8(v16i8 __a) */ +#define msa_get_low_s8(__a) __GET_LOW(v8i8, __a) + +/* v4i16 msa_get_low_s16(v8i16 __a) */ +#define msa_get_low_s16(__a) __GET_LOW(v4i16, __a) + +/* v2i32 msa_get_low_s32(v4i32 __a) */ +#define msa_get_low_s32(__a) __GET_LOW(v2i32, __a) + +/* v1i64 msa_get_low_s64(v2i64 __a) */ +#define msa_get_low_s64(__a) __GET_LOW(v1i64, __a) + +/* v8u8 msa_get_low_u8(v16u8 __a) */ +#define msa_get_low_u8(__a) __GET_LOW(v8u8, __a) + +/* v4u16 msa_get_low_u16(v8u16 __a) */ +#define msa_get_low_u16(__a) __GET_LOW(v4u16, __a) + +/* v2u32 msa_get_low_u32(v4u32 __a) */ +#define msa_get_low_u32(__a) __GET_LOW(v2u32, __a) + +/* v1u64 msa_get_low_u64(v2u64 __a) */ +#define msa_get_low_u64(__a) __GET_LOW(v1u64, __a) + +/* v2f32 msa_get_low_f32(v4f32 __a) */ +#define msa_get_low_f32(__a) __GET_LOW(v2f32, __a) + +/* v1f64 msa_get_low_f64(v2f64 __a) */ +#define msa_get_low_f64(__a) __GET_LOW(v1f64, __a) + +/* v8i8 msa_get_high_s8(v16i8 __a) */ +#define msa_get_high_s8(__a) __GET_HIGH(v8i8, __a) + +/* v4i16 msa_get_high_s16(v8i16 __a) */ +#define msa_get_high_s16(__a) __GET_HIGH(v4i16, __a) + +/* v2i32 msa_get_high_s32(v4i32 __a) */ +#define msa_get_high_s32(__a) __GET_HIGH(v2i32, __a) + +/* v1i64 msa_get_high_s64(v2i64 __a) */ +#define msa_get_high_s64(__a) __GET_HIGH(v1i64, __a) + +/* v8u8 msa_get_high_u8(v16u8 __a) */ +#define msa_get_high_u8(__a) __GET_HIGH(v8u8, __a) + +/* v4u16 msa_get_high_u16(v8u16 __a) */ +#define msa_get_high_u16(__a) __GET_HIGH(v4u16, __a) + +/* v2u32 msa_get_high_u32(v4u32 __a) */ +#define msa_get_high_u32(__a) __GET_HIGH(v2u32, __a) + +/* v1u64 msa_get_high_u64(v2u64 __a) */ +#define msa_get_high_u64(__a) __GET_HIGH(v1u64, __a) + +/* v2f32 msa_get_high_f32(v4f32 __a) */ +#define msa_get_high_f32(__a) __GET_HIGH(v2f32, __a) + +/* v1f64 msa_get_high_f64(v2f64 __a) */ +#define msa_get_high_f64(__a) __GET_HIGH(v1f64, __a) + +/* ri = ai * b[lane] */ +/* v4f32 msa_mulq_lane_f32(v4f32 __a, v4f32 __b, const int __lane) */ +#define msa_mulq_lane_f32(__a, __b, __lane) ((__a) * msa_getq_lane_f32(__b, __lane)) + +/* ri = ai + bi * c[lane] */ +/* v4f32 msa_mlaq_lane_f32(v4f32 __a, v4f32 __b, v4f32 __c, const int __lane) */ +#define msa_mlaq_lane_f32(__a, __b, __c, __lane) ((__a) + ((__b) * msa_getq_lane_f32(__c, __lane))) + +/* uint16_t msa_sum_u16(v8u16 __a)*/ +#define msa_sum_u16(__a) \ +({ \ + v4u32 _b; \ + v2u64 _c; \ + _b = __builtin_msa_hadd_u_w(__a, __a); \ + _c = __builtin_msa_hadd_u_d(_b, _b); \ + (uint16_t)(_c[0] + _c[1]); \ +}) + +/* int16_t msa_sum_s16(v8i16 __a) */ +#define msa_sum_s16(__a) \ +({ \ + v4i32 _b; \ + v2i64 _c; \ + _b = __builtin_msa_hadd_s_w(__a, __a); \ + _c = __builtin_msa_hadd_s_d(_b, _b); \ + (int32_t)(_c[0] + _c[1]); \ +}) + + +/* uint32_t msa_sum_u32(v4u32 __a)*/ +#define msa_sum_u32(__a) \ +({ \ + v2u64 _b; \ + _b = __builtin_msa_hadd_u_d(__a, __a); \ + (uint32_t)(_b[0] + _b[1]); \ +}) + +/* int32_t msa_sum_s32(v4i32 __a)*/ +#define msa_sum_s32(__a) \ +({ \ + v2i64 _b; \ + _b = __builtin_msa_hadd_s_d(__a, __a); \ + (int64_t)(_b[0] + _b[1]); \ +}) + +/* uint8_t msa_sum_u8(v16u8 __a)*/ +#define msa_sum_u8(__a) \ +({ \ + v8u16 _b16; \ + v4u32 _c32; \ + _b16 = __builtin_msa_hadd_u_h(__a, __a); \ + _c32 = __builtin_msa_hadd_u_w(_b16, _b16); \ + (uint8_t)msa_sum_u32(_c32); \ +}) + +/* int8_t msa_sum_s8(v16s8 __a)*/ +#define msa_sum_s8(__a) \ +({ \ + v8i16 _b16; \ + v4i32 _c32; \ + _b16 = __builtin_msa_hadd_s_h(__a, __a); \ + _c32 = __builtin_msa_hadd_s_w(_b16, _b16); \ + (int16_t)msa_sum_s32(_c32); \ +}) + +/* float msa_sum_f32(v4f32 __a)*/ +#define msa_sum_f32(__a) ((__a)[0] + (__a)[1] + (__a)[2] + (__a)[3]) + +/* v8u16 msa_paddlq_u8(v16u8 __a) */ +#define msa_paddlq_u8(__a) (__builtin_msa_hadd_u_h(__a, __a)) + +/* v8i16 msa_paddlq_s8(v16i8 __a) */ +#define msa_paddlq_s8(__a) (__builtin_msa_hadd_s_h(__a, __a)) + +/* v4u32 msa_paddlq_u16 (v8u16 __a)*/ +#define msa_paddlq_u16(__a) (__builtin_msa_hadd_u_w(__a, __a)) + +/* v4i32 msa_paddlq_s16 (v8i16 __a)*/ +#define msa_paddlq_s16(__a) (__builtin_msa_hadd_s_w(__a, __a)) + +/* v2u64 msa_paddlq_u32(v4u32 __a) */ +#define msa_paddlq_u32(__a) (__builtin_msa_hadd_u_d(__a, __a)) + +/* v2i64 msa_paddlq_s32(v4i32 __a) */ +#define msa_paddlq_s32(__a) (__builtin_msa_hadd_s_d(__a, __a)) + +#define V8U8_2_V8U16(x) {(uint16_t)x[0], (uint16_t)x[1], (uint16_t)x[2], (uint16_t)x[3], \ + (uint16_t)x[4], (uint16_t)x[5], (uint16_t)x[6], (uint16_t)x[7]} +#define V8U8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ + (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} +#define V8I8_2_V8I16(x) {(int16_t)x[0], (int16_t)x[1], (int16_t)x[2], (int16_t)x[3], \ + (int16_t)x[4], (int16_t)x[5], (int16_t)x[6], (int16_t)x[7]} +#define V4U16_2_V4U32(x) {(uint32_t)x[0], (uint32_t)x[1], (uint32_t)x[2], (uint32_t)x[3]} +#define V4U16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} +#define V4I16_2_V4I32(x) {(int32_t)x[0], (int32_t)x[1], (int32_t)x[2], (int32_t)x[3]} +#define V2U32_2_V2U64(x) {(uint64_t)x[0], (uint64_t)x[1]} +#define V2U32_2_V2I64(x) {(int64_t)x[0], (int64_t)x[1]} + +/* v8u16 msa_mull_u8(v8u8 __a, v8u8 __b) */ +#define msa_mull_u8(__a, __b) ((v8u16)__builtin_msa_mulv_h((v8i16)V8U8_2_V8I16(__a), (v8i16)V8U8_2_V8I16(__b))) + +/* v8i16 msa_mull_s8(v8i8 __a, v8i8 __b)*/ +#define msa_mull_s8(__a, __b) (__builtin_msa_mulv_h((v8i16)V8I8_2_V8I16(__a), (v8i16)V8I8_2_V8I16(__b))) + +/* v4u32 msa_mull_u16(v4u16 __a, v4u16 __b) */ +#define msa_mull_u16(__a, __b) ((v4u32)__builtin_msa_mulv_w((v4i32)V4U16_2_V4I32(__a), (v4i32)V4U16_2_V4I32(__b))) + +/* v4i32 msa_mull_s16(v4i16 __a, v4i16 __b) */ +#define msa_mull_s16(__a, __b) (__builtin_msa_mulv_w((v4i32)V4I16_2_V4I32(__a), (v4i32)V4I16_2_V4I32(__b))) + +/* v2u64 msa_mull_u32(v2u32 __a, v2u32 __b) */ +#define msa_mull_u32(__a, __b) ((v2u64)__builtin_msa_mulv_d((v2i64)V2U32_2_V2I64(__a), (v2i64)V2U32_2_V2I64(__b))) + +/* bitwise and: __builtin_msa_and_v */ +#define msa_andq_u8(__a, __b) ((v16u8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s8(__a, __b) ((v16i8)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_u16(__a, __b) ((v8u16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s16(__a, __b) ((v8i16)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_u32(__a, __b) ((v4u32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s32(__a, __b) ((v4i32)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_u64(__a, __b) ((v2u64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) +#define msa_andq_s64(__a, __b) ((v2i64)__builtin_msa_and_v((v16u8)(__a), (v16u8)(__b))) + +/* bitwise or: __builtin_msa_or_v */ +#define msa_orrq_u8(__a, __b) ((v16u8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s8(__a, __b) ((v16i8)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_u16(__a, __b) ((v8u16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s16(__a, __b) ((v8i16)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_u32(__a, __b) ((v4u32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s32(__a, __b) ((v4i32)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_u64(__a, __b) ((v2u64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) +#define msa_orrq_s64(__a, __b) ((v2i64)__builtin_msa_or_v((v16u8)(__a), (v16u8)(__b))) + +/* bitwise xor: __builtin_msa_xor_v */ +#define msa_eorq_u8(__a, __b) ((v16u8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s8(__a, __b) ((v16i8)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_u16(__a, __b) ((v8u16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s16(__a, __b) ((v8i16)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_u32(__a, __b) ((v4u32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s32(__a, __b) ((v4i32)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_u64(__a, __b) ((v2u64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) +#define msa_eorq_s64(__a, __b) ((v2i64)__builtin_msa_xor_v((v16u8)(__a), (v16u8)(__b))) + +/* bitwise not: v16u8 __builtin_msa_xori_b (v16u8, 0xff) */ +#define msa_mvnq_u8(__a) ((v16u8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s8(__a) ((v16i8)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_u16(__a) ((v8u16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s16(__a) ((v8i16)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_u32(__a) ((v4u32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s32(__a) ((v4i32)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_u64(__a) ((v2u64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) +#define msa_mvnq_s64(__a) ((v2i64)__builtin_msa_xori_b((v16u8)(__a), 0xFF)) + +/* compare equal: ceq -> ri = ai == bi ? 1...1:0...0 */ +#define msa_ceqq_u8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) +#define msa_ceqq_s8(__a, __b) ((v16u8)__builtin_msa_ceq_b((v16i8)(__a), (v16i8)(__b))) +#define msa_ceqq_u16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) +#define msa_ceqq_s16(__a, __b) ((v8u16)__builtin_msa_ceq_h((v8i16)(__a), (v8i16)(__b))) +#define msa_ceqq_u32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) +#define msa_ceqq_s32(__a, __b) ((v4u32)__builtin_msa_ceq_w((v4i32)(__a), (v4i32)(__b))) +#define msa_ceqq_f32(__a, __b) ((v4u32)__builtin_msa_fceq_w((v4f32)(__a), (v4f32)(__b))) +#define msa_ceqq_u64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) +#define msa_ceqq_s64(__a, __b) ((v2u64)__builtin_msa_ceq_d((v2i64)(__a), (v2i64)(__b))) +#define msa_ceqq_f64(__a, __b) ((v2u64)__builtin_msa_fceq_d((v2f64)(__a), (v2f64)(__b))) + +/* Compare less-than: clt -> ri = ai < bi ? 1...1:0...0 */ +#define msa_cltq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__a), (v16u8)(__b))) +#define msa_cltq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__a), (v16i8)(__b))) +#define msa_cltq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__a), (v8u16)(__b))) +#define msa_cltq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__a), (v8i16)(__b))) +#define msa_cltq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__a), (v4u32)(__b))) +#define msa_cltq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__a), (v4i32)(__b))) +#define msa_cltq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__a), (v4f32)(__b))) +#define msa_cltq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__a), (v2u64)(__b))) +#define msa_cltq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__a), (v2i64)(__b))) +#define msa_cltq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__a), (v2f64)(__b))) + +/* compare greater-than: cgt -> ri = ai > bi ? 1...1:0...0 */ +#define msa_cgtq_u8(__a, __b) ((v16u8)__builtin_msa_clt_u_b((v16u8)(__b), (v16u8)(__a))) +#define msa_cgtq_s8(__a, __b) ((v16u8)__builtin_msa_clt_s_b((v16i8)(__b), (v16i8)(__a))) +#define msa_cgtq_u16(__a, __b) ((v8u16)__builtin_msa_clt_u_h((v8u16)(__b), (v8u16)(__a))) +#define msa_cgtq_s16(__a, __b) ((v8u16)__builtin_msa_clt_s_h((v8i16)(__b), (v8i16)(__a))) +#define msa_cgtq_u32(__a, __b) ((v4u32)__builtin_msa_clt_u_w((v4u32)(__b), (v4u32)(__a))) +#define msa_cgtq_s32(__a, __b) ((v4u32)__builtin_msa_clt_s_w((v4i32)(__b), (v4i32)(__a))) +#define msa_cgtq_f32(__a, __b) ((v4u32)__builtin_msa_fclt_w((v4f32)(__b), (v4f32)(__a))) +#define msa_cgtq_u64(__a, __b) ((v2u64)__builtin_msa_clt_u_d((v2u64)(__b), (v2u64)(__a))) +#define msa_cgtq_s64(__a, __b) ((v2u64)__builtin_msa_clt_s_d((v2i64)(__b), (v2i64)(__a))) +#define msa_cgtq_f64(__a, __b) ((v2u64)__builtin_msa_fclt_d((v2f64)(__b), (v2f64)(__a))) + +/* compare less-equal: cle -> ri = ai <= bi ? 1...1:0...0 */ +#define msa_cleq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__a), (v16u8)(__b))) +#define msa_cleq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__a), (v16i8)(__b))) +#define msa_cleq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__a), (v8u16)(__b))) +#define msa_cleq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__a), (v8i16)(__b))) +#define msa_cleq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__a), (v4u32)(__b))) +#define msa_cleq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__a), (v4i32)(__b))) +#define msa_cleq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__a), (v4f32)(__b))) +#define msa_cleq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__a), (v2u64)(__b))) +#define msa_cleq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__a), (v2i64)(__b))) +#define msa_cleq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__a), (v2f64)(__b))) + +/* compare greater-equal: cge -> ri = ai >= bi ? 1...1:0...0 */ +#define msa_cgeq_u8(__a, __b) ((v16u8)__builtin_msa_cle_u_b((v16u8)(__b), (v16u8)(__a))) +#define msa_cgeq_s8(__a, __b) ((v16u8)__builtin_msa_cle_s_b((v16i8)(__b), (v16i8)(__a))) +#define msa_cgeq_u16(__a, __b) ((v8u16)__builtin_msa_cle_u_h((v8u16)(__b), (v8u16)(__a))) +#define msa_cgeq_s16(__a, __b) ((v8u16)__builtin_msa_cle_s_h((v8i16)(__b), (v8i16)(__a))) +#define msa_cgeq_u32(__a, __b) ((v4u32)__builtin_msa_cle_u_w((v4u32)(__b), (v4u32)(__a))) +#define msa_cgeq_s32(__a, __b) ((v4u32)__builtin_msa_cle_s_w((v4i32)(__b), (v4i32)(__a))) +#define msa_cgeq_f32(__a, __b) ((v4u32)__builtin_msa_fcle_w((v4f32)(__b), (v4f32)(__a))) +#define msa_cgeq_u64(__a, __b) ((v2u64)__builtin_msa_cle_u_d((v2u64)(__b), (v2u64)(__a))) +#define msa_cgeq_s64(__a, __b) ((v2u64)__builtin_msa_cle_s_d((v2i64)(__b), (v2i64)(__a))) +#define msa_cgeq_f64(__a, __b) ((v2u64)__builtin_msa_fcle_d((v2f64)(__b), (v2f64)(__a))) + +/* Shift Left Logical: shl -> ri = ai << bi; */ +#define msa_shlq_u8(__a, __b) ((v16u8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shlq_s8(__a, __b) ((v16i8)__builtin_msa_sll_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shlq_u16(__a, __b) ((v8u16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shlq_s16(__a, __b) ((v8i16)__builtin_msa_sll_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shlq_u32(__a, __b) ((v4u32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shlq_s32(__a, __b) ((v4i32)__builtin_msa_sll_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shlq_u64(__a, __b) ((v2u64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) +#define msa_shlq_s64(__a, __b) ((v2i64)__builtin_msa_sll_d((v2i64)(__a), (v2i64)(__b))) + +/* Immediate Shift Left Logical: shl -> ri = ai << imm; */ +#define msa_shlq_n_u8(__a, __imm) ((v16u8)__builtin_msa_slli_b((v16i8)(__a), __imm)) +#define msa_shlq_n_s8(__a, __imm) ((v16i8)__builtin_msa_slli_b((v16i8)(__a), __imm)) +#define msa_shlq_n_u16(__a, __imm) ((v8u16)__builtin_msa_slli_h((v8i16)(__a), __imm)) +#define msa_shlq_n_s16(__a, __imm) ((v8i16)__builtin_msa_slli_h((v8i16)(__a), __imm)) +#define msa_shlq_n_u32(__a, __imm) ((v4u32)__builtin_msa_slli_w((v4i32)(__a), __imm)) +#define msa_shlq_n_s32(__a, __imm) ((v4i32)__builtin_msa_slli_w((v4i32)(__a), __imm)) +#define msa_shlq_n_u64(__a, __imm) ((v2u64)__builtin_msa_slli_d((v2i64)(__a), __imm)) +#define msa_shlq_n_s64(__a, __imm) ((v2i64)__builtin_msa_slli_d((v2i64)(__a), __imm)) + +/* shift right: shrq -> ri = ai >> bi; */ +#define msa_shrq_u8(__a, __b) ((v16u8)__builtin_msa_srl_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shrq_s8(__a, __b) ((v16i8)__builtin_msa_sra_b((v16i8)(__a), (v16i8)(__b))) +#define msa_shrq_u16(__a, __b) ((v8u16)__builtin_msa_srl_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shrq_s16(__a, __b) ((v8i16)__builtin_msa_sra_h((v8i16)(__a), (v8i16)(__b))) +#define msa_shrq_u32(__a, __b) ((v4u32)__builtin_msa_srl_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shrq_s32(__a, __b) ((v4i32)__builtin_msa_sra_w((v4i32)(__a), (v4i32)(__b))) +#define msa_shrq_u64(__a, __b) ((v2u64)__builtin_msa_srl_d((v2i64)(__a), (v2i64)(__b))) +#define msa_shrq_s64(__a, __b) ((v2i64)__builtin_msa_sra_d((v2i64)(__a), (v2i64)(__b))) + +/* Immediate Shift Right: shr -> ri = ai >> imm; */ +#define msa_shrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srli_b((v16i8)(__a), __imm)) +#define msa_shrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srai_b((v16i8)(__a), __imm)) +#define msa_shrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srli_h((v8i16)(__a), __imm)) +#define msa_shrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srai_h((v8i16)(__a), __imm)) +#define msa_shrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srli_w((v4i32)(__a), __imm)) +#define msa_shrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srai_w((v4i32)(__a), __imm)) +#define msa_shrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srli_d((v2i64)(__a), __imm)) +#define msa_shrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srai_d((v2i64)(__a), __imm)) + +/* Immediate Shift Right Rounded: shr -> ri = ai >> (rounded)imm; */ +#define msa_rshrq_n_u8(__a, __imm) ((v16u8)__builtin_msa_srlri_b((v16i8)(__a), __imm)) +#define msa_rshrq_n_s8(__a, __imm) ((v16i8)__builtin_msa_srari_b((v16i8)(__a), __imm)) +#define msa_rshrq_n_u16(__a, __imm) ((v8u16)__builtin_msa_srlri_h((v8i16)(__a), __imm)) +#define msa_rshrq_n_s16(__a, __imm) ((v8i16)__builtin_msa_srari_h((v8i16)(__a), __imm)) +#define msa_rshrq_n_u32(__a, __imm) ((v4u32)__builtin_msa_srlri_w((v4i32)(__a), __imm)) +#define msa_rshrq_n_s32(__a, __imm) ((v4i32)__builtin_msa_srari_w((v4i32)(__a), __imm)) +#define msa_rshrq_n_u64(__a, __imm) ((v2u64)__builtin_msa_srlri_d((v2i64)(__a), __imm)) +#define msa_rshrq_n_s64(__a, __imm) ((v2i64)__builtin_msa_srari_d((v2i64)(__a), __imm)) + +/* Vector saturating rounding shift left, qrshl -> ri = ai << bi; */ +#define msa_qrshrq_s32(a, b) ((v4i32)__msa_srar_w((v4i32)(a), (v4i32)(b))) + +/* Rename the msa builtin func to unify the name style for intrin_msa.hpp */ +#define msa_qaddq_u8 __builtin_msa_adds_u_b +#define msa_qaddq_s8 __builtin_msa_adds_s_b +#define msa_qaddq_u16 __builtin_msa_adds_u_h +#define msa_qaddq_s16 __builtin_msa_adds_s_h +#define msa_qaddq_u32 __builtin_msa_adds_u_w +#define msa_qaddq_s32 __builtin_msa_adds_s_w +#define msa_qaddq_u64 __builtin_msa_adds_u_d +#define msa_qaddq_s64 __builtin_msa_adds_s_d +#define msa_addq_u8(a, b) ((v16u8)__builtin_msa_addv_b((v16i8)(a), (v16i8)(b))) +#define msa_addq_s8 __builtin_msa_addv_b +#define msa_addq_u16(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)(a), (v8i16)(b))) +#define msa_addq_s16 __builtin_msa_addv_h +#define msa_addq_u32(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)(a), (v4i32)(b))) +#define msa_addq_s32 __builtin_msa_addv_w +#define msa_addq_f32 __builtin_msa_fadd_w +#define msa_addq_u64(a, b) ((v2u64)__builtin_msa_addv_d((v2i64)(a), (v2i64)(b))) +#define msa_addq_s64 __builtin_msa_addv_d +#define msa_addq_f64 __builtin_msa_fadd_d +#define msa_qsubq_u8 __builtin_msa_subs_u_b +#define msa_qsubq_s8 __builtin_msa_subs_s_b +#define msa_qsubq_u16 __builtin_msa_subs_u_h +#define msa_qsubq_s16 __builtin_msa_subs_s_h +#define msa_subq_u8(a, b) ((v16u8)__builtin_msa_subv_b((v16i8)(a), (v16i8)(b))) +#define msa_subq_s8 __builtin_msa_subv_b +#define msa_subq_u16(a, b) ((v8u16)__builtin_msa_subv_h((v8i16)(a), (v8i16)(b))) +#define msa_subq_s16 __builtin_msa_subv_h +#define msa_subq_u32(a, b) ((v4u32)__builtin_msa_subv_w((v4i32)(a), (v4i32)(b))) +#define msa_subq_s32 __builtin_msa_subv_w +#define msa_subq_f32 __builtin_msa_fsub_w +#define msa_subq_u64(a, b) ((v2u64)__builtin_msa_subv_d((v2i64)(a), (v2i64)(b))) +#define msa_subq_s64 __builtin_msa_subv_d +#define msa_subq_f64 __builtin_msa_fsub_d +#define msa_mulq_u8(a, b) ((v16u8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) +#define msa_mulq_s8(a, b) ((v16i8)__builtin_msa_mulv_b((v16i8)(a), (v16i8)(b))) +#define msa_mulq_u16(a, b) ((v8u16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) +#define msa_mulq_s16(a, b) ((v8i16)__builtin_msa_mulv_h((v8i16)(a), (v8i16)(b))) +#define msa_mulq_u32(a, b) ((v4u32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) +#define msa_mulq_s32(a, b) ((v4i32)__builtin_msa_mulv_w((v4i32)(a), (v4i32)(b))) +#define msa_mulq_u64(a, b) ((v2u64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) +#define msa_mulq_s64(a, b) ((v2i64)__builtin_msa_mulv_d((v2i64)(a), (v2i64)(b))) +#define msa_mulq_f32 __builtin_msa_fmul_w +#define msa_mulq_f64 __builtin_msa_fmul_d +#define msa_divq_f32 __builtin_msa_fdiv_w +#define msa_divq_f64 __builtin_msa_fdiv_d +#define msa_dotp_s_h __builtin_msa_dotp_s_h +#define msa_dotp_s_w __builtin_msa_dotp_s_w +#define msa_dotp_s_d __builtin_msa_dotp_s_d +#define msa_dotp_u_h __builtin_msa_dotp_u_h +#define msa_dotp_u_w __builtin_msa_dotp_u_w +#define msa_dotp_u_d __builtin_msa_dotp_u_d +#define msa_dpadd_s_h __builtin_msa_dpadd_s_h +#define msa_dpadd_s_w __builtin_msa_dpadd_s_w +#define msa_dpadd_s_d __builtin_msa_dpadd_s_d +#define msa_dpadd_u_h __builtin_msa_dpadd_u_h +#define msa_dpadd_u_w __builtin_msa_dpadd_u_w +#define msa_dpadd_u_d __builtin_msa_dpadd_u_d + +#define ILVRL_B2(RTYPE, in0, in1, low, hi) do { \ + low = (RTYPE)__builtin_msa_ilvr_b((v16i8)(in0), (v16i8)(in1)); \ + hi = (RTYPE)__builtin_msa_ilvl_b((v16i8)(in0), (v16i8)(in1)); \ + } while (0) +#define ILVRL_B2_UB(...) ILVRL_B2(v16u8, __VA_ARGS__) +#define ILVRL_B2_SB(...) ILVRL_B2(v16i8, __VA_ARGS__) +#define ILVRL_B2_UH(...) ILVRL_B2(v8u16, __VA_ARGS__) +#define ILVRL_B2_SH(...) ILVRL_B2(v8i16, __VA_ARGS__) +#define ILVRL_B2_SW(...) ILVRL_B2(v4i32, __VA_ARGS__) + +#define ILVRL_H2(RTYPE, in0, in1, low, hi) do { \ + low = (RTYPE)__builtin_msa_ilvr_h((v8i16)(in0), (v8i16)(in1)); \ + hi = (RTYPE)__builtin_msa_ilvl_h((v8i16)(in0), (v8i16)(in1)); \ + } while (0) +#define ILVRL_H2_UB(...) ILVRL_H2(v16u8, __VA_ARGS__) +#define ILVRL_H2_SB(...) ILVRL_H2(v16i8, __VA_ARGS__) +#define ILVRL_H2_UH(...) ILVRL_H2(v8u16, __VA_ARGS__) +#define ILVRL_H2_SH(...) ILVRL_H2(v8i16, __VA_ARGS__) +#define ILVRL_H2_SW(...) ILVRL_H2(v4i32, __VA_ARGS__) +#define ILVRL_H2_UW(...) ILVRL_H2(v4u32, __VA_ARGS__) + +#define ILVRL_W2(RTYPE, in0, in1, low, hi) do { \ + low = (RTYPE)__builtin_msa_ilvr_w((v4i32)(in0), (v4i32)(in1)); \ + hi = (RTYPE)__builtin_msa_ilvl_w((v4i32)(in0), (v4i32)(in1)); \ + } while (0) +#define ILVRL_W2_UB(...) ILVRL_W2(v16u8, __VA_ARGS__) +#define ILVRL_W2_SH(...) ILVRL_W2(v8i16, __VA_ARGS__) +#define ILVRL_W2_SW(...) ILVRL_W2(v4i32, __VA_ARGS__) +#define ILVRL_W2_UW(...) ILVRL_W2(v4u32, __VA_ARGS__) + +/* absq, qabsq (r = |a|;) */ +#define msa_absq_s8(a) __builtin_msa_add_a_b(a, __builtin_msa_fill_b(0)) +#define msa_absq_s16(a) __builtin_msa_add_a_h(a, __builtin_msa_fill_h(0)) +#define msa_absq_s32(a) __builtin_msa_add_a_w(a, __builtin_msa_fill_w(0)) +#define msa_absq_s64(a) __builtin_msa_add_a_d(a, __builtin_msa_fill_d(0)) +#define msa_absq_f32(a) ((v4f32)__builtin_msa_bclri_w((v4u32)(a), 31)) +#define msa_absq_f64(a) ((v2f64)__builtin_msa_bclri_d((v2u64)(a), 63)) +#define msa_qabsq_s8(a) __builtin_msa_adds_a_b(a, __builtin_msa_fill_b(0)) +#define msa_qabsq_s16(a) __builtin_msa_adds_a_h(a, __builtin_msa_fill_h(0)) +#define msa_qabsq_s32(a) __builtin_msa_adds_a_w(a, __builtin_msa_fill_w(0)) +#define msa_qabsq_s64(a) __builtin_msa_adds_a_d(a, __builtin_msa_fill_d(0)) + +/* abdq, qabdq (r = |a - b|;) */ +#define msa_abdq_u8 __builtin_msa_asub_u_b +#define msa_abdq_s8 __builtin_msa_asub_s_b +#define msa_abdq_u16 __builtin_msa_asub_u_h +#define msa_abdq_s16 __builtin_msa_asub_s_h +#define msa_abdq_u32 __builtin_msa_asub_u_w +#define msa_abdq_s32 __builtin_msa_asub_s_w +#define msa_abdq_u64 __builtin_msa_asub_u_d +#define msa_abdq_s64 __builtin_msa_asub_s_d +#define msa_abdq_f32(a, b) msa_absq_f32(__builtin_msa_fsub_w(a, b)) +#define msa_abdq_f64(a, b) msa_absq_f64(__builtin_msa_fsub_d(a, b)) +#define msa_qabdq_s8(a, b) msa_qabsq_s8(__builtin_msa_subs_s_b(a, b)) +#define msa_qabdq_s16(a, b) msa_qabsq_s16(__builtin_msa_subs_s_h(a, b)) +#define msa_qabdq_s32(a, b) msa_qabsq_s32(__builtin_msa_subs_s_w(a, b)) +#define msa_qabdq_s64(a, b) msa_qabsq_s64(__builtin_msa_subs_s_d(a, b)) + +/* sqrtq, rsqrtq */ +#define msa_sqrtq_f32 __builtin_msa_fsqrt_w +#define msa_sqrtq_f64 __builtin_msa_fsqrt_d +#define msa_rsqrtq_f32 __builtin_msa_frsqrt_w +#define msa_rsqrtq_f64 __builtin_msa_frsqrt_d + + +/* mlaq: r = a + b * c; */ +__extension__ extern __inline v4i32 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_s32(v4i32 __a, v4i32 __b, v4i32 __c) +{ + __asm__ volatile("maddv.w %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +__extension__ extern __inline v2i64 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_s64(v2i64 __a, v2i64 __b, v2i64 __c) +{ + __asm__ volatile("maddv.d %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +__extension__ extern __inline v4f32 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_f32(v4f32 __a, v4f32 __b, v4f32 __c) +{ + __asm__ volatile("fmadd.w %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +__extension__ extern __inline v2f64 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_mlaq_f64(v2f64 __a, v2f64 __b, v2f64 __c) +{ + __asm__ volatile("fmadd.d %w[__a], %w[__b], %w[__c]\n" + // Outputs + : [__a] "+f"(__a) + // Inputs + : [__b] "f"(__b), [__c] "f"(__c)); + return __a; +} + +/* cntq */ +#define msa_cntq_s8 __builtin_msa_pcnt_b +#define msa_cntq_s16 __builtin_msa_pcnt_h +#define msa_cntq_s32 __builtin_msa_pcnt_w +#define msa_cntq_s64 __builtin_msa_pcnt_d + +/* bslq (a: mask; r = b(if a == 0); r = c(if a == 1);) */ +#define msa_bslq_u8 __builtin_msa_bsel_v + +/* ilvrq, ilvlq (For EL only, ilvrq: b0, a0, b1, a1; ilvlq: b2, a2, b3, a3;) */ +#define msa_ilvrq_s8 __builtin_msa_ilvr_b +#define msa_ilvrq_s16 __builtin_msa_ilvr_h +#define msa_ilvrq_s32 __builtin_msa_ilvr_w +#define msa_ilvrq_s64 __builtin_msa_ilvr_d +#define msa_ilvlq_s8 __builtin_msa_ilvl_b +#define msa_ilvlq_s16 __builtin_msa_ilvl_h +#define msa_ilvlq_s32 __builtin_msa_ilvl_w +#define msa_ilvlq_s64 __builtin_msa_ilvl_d + +/* ilvevq, ilvodq (ilvevq: b0, a0, b2, a2; ilvodq: b1, a1, b3, a3; ) */ +#define msa_ilvevq_s8 __builtin_msa_ilvev_b +#define msa_ilvevq_s16 __builtin_msa_ilvev_h +#define msa_ilvevq_s32 __builtin_msa_ilvev_w +#define msa_ilvevq_s64 __builtin_msa_ilvev_d +#define msa_ilvodq_s8 __builtin_msa_ilvod_b +#define msa_ilvodq_s16 __builtin_msa_ilvod_h +#define msa_ilvodq_s32 __builtin_msa_ilvod_w +#define msa_ilvodq_s64 __builtin_msa_ilvod_d + +/* extq (r = (a || b); a concatenation b and get elements from index c) */ +#ifdef _MIPSEB +#define msa_extq_s8(a, b, c) \ +(__builtin_msa_vshf_b(__builtin_msa_subv_b((v16i8)((v2i64){0x1716151413121110, 0x1F1E1D1C1B1A1918}), __builtin_msa_fill_b(c)), a, b)) +#define msa_extq_s16(a, b, c) \ +(__builtin_msa_vshf_h(__builtin_msa_subv_h((v8i16)((v2i64){0x000B000A00090008, 0x000F000E000D000C}), __builtin_msa_fill_h(c)), a, b)) +#define msa_extq_s32(a, b, c) \ +(__builtin_msa_vshf_w(__builtin_msa_subv_w((v4i32)((v2i64){0x0000000500000004, 0x0000000700000006}), __builtin_msa_fill_w(c)), a, b)) +#define msa_extq_s64(a, b, c) \ +(__builtin_msa_vshf_d(__builtin_msa_subv_d((v2i64){0x0000000000000002, 0x0000000000000003}, __builtin_msa_fill_d(c)), a, b)) +#else +#define msa_extq_s8(a, b, c) \ +(__builtin_msa_vshf_b(__builtin_msa_addv_b((v16i8)((v2i64){0x0706050403020100, 0x0F0E0D0C0B0A0908}), __builtin_msa_fill_b(c)), b, a)) +#define msa_extq_s16(a, b, c) \ +(__builtin_msa_vshf_h(__builtin_msa_addv_h((v8i16)((v2i64){0x0003000200010000, 0x0007000600050004}), __builtin_msa_fill_h(c)), b, a)) +#define msa_extq_s32(a, b, c) \ +(__builtin_msa_vshf_w(__builtin_msa_addv_w((v4i32)((v2i64){0x0000000100000000, 0x0000000300000002}), __builtin_msa_fill_w(c)), b, a)) +#define msa_extq_s64(a, b, c) \ +(__builtin_msa_vshf_d(__builtin_msa_addv_d((v2i64){0x0000000000000000, 0x0000000000000001}, __builtin_msa_fill_d(c)), b, a)) +#endif /* _MIPSEB */ + +/* cvttruncq, cvttintq, cvtrintq */ +#define msa_cvttruncq_u32_f32 __builtin_msa_ftrunc_u_w +#define msa_cvttruncq_s32_f32 __builtin_msa_ftrunc_s_w +#define msa_cvttruncq_u64_f64 __builtin_msa_ftrunc_u_d +#define msa_cvttruncq_s64_f64 __builtin_msa_ftrunc_s_d +#define msa_cvttintq_u32_f32 __builtin_msa_ftint_u_w +#define msa_cvttintq_s32_f32 __builtin_msa_ftint_s_w +#define msa_cvttintq_u64_f64 __builtin_msa_ftint_u_d +#define msa_cvttintq_s64_f64 __builtin_msa_ftint_s_d +#define msa_cvtrintq_f32 __builtin_msa_frint_w +#define msa_cvtrintq_f64 __builtin_msa_frint_d + +/* cvtfintq, cvtfq */ +#define msa_cvtfintq_f32_u32 __builtin_msa_ffint_u_w +#define msa_cvtfintq_f32_s32 __builtin_msa_ffint_s_w +#define msa_cvtfintq_f64_u64 __builtin_msa_ffint_u_d +#define msa_cvtfintq_f64_s64 __builtin_msa_ffint_s_d +#define msa_cvtfq_f32_f64 __builtin_msa_fexdo_w +#define msa_cvtflq_f64_f32 __builtin_msa_fexupr_d +#define msa_cvtfhq_f64_f32 __builtin_msa_fexupl_d + +#define msa_addl_u8(a, b) ((v8u16)__builtin_msa_addv_h((v8i16)V8U8_2_V8I16(a), (v8i16)V8U8_2_V8I16(b))) +#define msa_addl_s8(a, b) (__builtin_msa_addv_h((v8i16)V8I8_2_V8I16(a), (v8i16)V8I8_2_V8I16(b))) +#define msa_addl_u16(a, b) ((v4u32)__builtin_msa_addv_w((v4i32)V4U16_2_V4I32(a), (v4i32)V4U16_2_V4I32(b))) +#define msa_addl_s16(a, b) (__builtin_msa_addv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) +#define msa_subl_s16(a, b) (__builtin_msa_subv_w((v4i32)V4I16_2_V4I32(a), (v4i32)V4I16_2_V4I32(b))) +#define msa_recpeq_f32 __builtin_msa_frcp_w +#define msa_recpsq_f32(a, b) (__builtin_msa_fsub_w(msa_dupq_n_f32(2.0f), __builtin_msa_fmul_w(a, b))) + +#define MSA_INTERLEAVED_IMPL_LOAD2_STORE2(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld2q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ + *a = (_Tpv)__builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ +} \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st2q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b) \ +{ \ + msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df((_Tpvs)b, (_Tpvs)a)); \ + msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df((_Tpvs)b, (_Tpvs)a)); \ +} + +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint8_t, v16u8, v16i8, u8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int8_t, v16i8, v16i8, s8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint16_t, v8u16, v8i16, u16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int16_t, v8i16, v8i16, s16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint32_t, v4u32, v4i32, u32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int32_t, v4i32, v4i32, s32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(float, v4f32, v4i32, f32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(uint64_t, v2u64, v2i64, u64, d, 2) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(int64_t, v2i64, v2i64, s64, d, 2) +MSA_INTERLEAVED_IMPL_LOAD2_STORE2(double, v2f64, v2i64, f64, d, 2) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ + _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0704011F1F1F1F1F, 0x1F1C191613100D0A}), (_Tpvs)v0, (_Tpvs)v1); \ + *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150E0B080502, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0603001F1F1F1F1F, 0x1E1B1815120F0C09}), (_Tpvs)v0, (_Tpvs)v1); \ + *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x1716150D0A070401, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x05021F1F1F1F1F1F, 0x1D1A1714110E0B08}), (_Tpvs)v0, (_Tpvs)v1); \ + *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x17160F0C09060300, 0x1F1E1D1C1B1A1918}), v3, (_Tpvs)v2); \ +} +#else +#define MSA_INTERLEAVED_IMPL_LOAD3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 16); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 32); \ + _Tpvs v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15120F0C09060300, 0x00000000001E1B18}), (_Tpvs)v1, (_Tpvs)v0); \ + *a = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1D1A1714110A0908}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1613100D0A070401, 0x00000000001F1C19}), (_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1E1B1815120A0908}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1714110E0B080502, 0x0000000000001D1A}), (_Tpvs)v1, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_vshf_b((_Tpvs)((v2i64){0x0706050403020100, 0x1F1C191613100908}), (_Tpvs)v2, v3); \ +} +#endif + +MSA_INTERLEAVED_IMPL_LOAD3_8(uint8_t, v16u8, v16i8, u8) +MSA_INTERLEAVED_IMPL_LOAD3_8(int8_t, v16i8, v16i8, s8) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ + _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00030000000F000F, 0x000F000C00090006}), (_Tpvs)v1, (_Tpvs)v0); \ + *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000A00050002, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0002000F000F000F, 0x000E000B00080005}), (_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000700040001, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000F000F000F, 0x000D000A00070004}), (_Tpvs)v1, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000600030000, 0x000F000E000D000C}), (_Tpvs)v2, v3); \ +} +#else +#define MSA_INTERLEAVED_IMPL_LOAD3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 8); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 16); \ + _Tpvs v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0009000600030000, 0x00000000000F000C}), (_Tpvs)v1, (_Tpvs)v0); \ + *a = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000D000A00050004}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A000700040001, 0x000000000000000D}), (_Tpvs)v1, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000E000B00080004}), (_Tpvs)v2, v3); \ + v3 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B000800050002, 0x000000000000000E}), (_Tpvs)v1, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_vshf_h((_Tpvs)((v2i64){0x0003000200010000, 0x000F000C00090004}), (_Tpvs)v2, v3); \ +} +#endif + +MSA_INTERLEAVED_IMPL_LOAD3_16(uint16_t, v8u16, v8i16, u16) +MSA_INTERLEAVED_IMPL_LOAD3_16(int16_t, v8i16, v8i16, s16) + +#define MSA_INTERLEAVED_IMPL_LOAD3_32(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + _Tpv v00 = msa_ld1q_##suffix(ptr); \ + _Tpv v01 = msa_ld1q_##suffix(ptr + 4); \ + _Tpv v02 = msa_ld1q_##suffix(ptr + 8); \ + _Tpvs v10 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v01, (v2i64)v01), (_Tpvs)v00); \ + _Tpvs v11 = __builtin_msa_ilvr_w((_Tpvs)v02, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v00, (v2i64)v00)); \ + _Tpvs v12 = __builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v02, (v2i64)v02), (_Tpvs)v01); \ + *a = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v11, (v2i64)v11), v10); \ + *b = (_Tpv)__builtin_msa_ilvr_w(v12, (_Tpvs)__builtin_msa_ilvl_d((v2i64)v10, (v2i64)v10)); \ + *c = (_Tpv)__builtin_msa_ilvr_w((_Tpvs)__builtin_msa_ilvl_d((v2i64)v12, (v2i64)v12), v11); \ +} + +MSA_INTERLEAVED_IMPL_LOAD3_32(uint32_t, v4u32, v4i32, u32) +MSA_INTERLEAVED_IMPL_LOAD3_32(int32_t, v4i32, v4i32, s32) +MSA_INTERLEAVED_IMPL_LOAD3_32(float, v4f32, v4i32, f32) + +#define MSA_INTERLEAVED_IMPL_LOAD3_64(_Tp, _Tpv, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld3q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c) \ +{ \ + *((_Tp*)a) = *ptr; *((_Tp*)b) = *(ptr + 1); *((_Tp*)c) = *(ptr + 2); \ + *((_Tp*)a + 1) = *(ptr + 3); *((_Tp*)b + 1) = *(ptr + 4); *((_Tp*)c + 1) = *(ptr + 5); \ +} + +MSA_INTERLEAVED_IMPL_LOAD3_64(uint64_t, v2u64, u64) +MSA_INTERLEAVED_IMPL_LOAD3_64(int64_t, v2i64, s64) +MSA_INTERLEAVED_IMPL_LOAD3_64(double, v2f64, f64) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0F0E0D0C0B1F1F1F, 0x1F1E1D1C1B1A1F1F}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0D1C140C1B130B1A, 0x1F170F1E160E1D15}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A09080706051F1F, 0x19181716151F1F1F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x1D14071C13061B12, 0x170A1F16091E1508}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x04030201001F1F1F, 0x14131211101F1F1F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x15021C14011B1300, 0x051F17041E16031D}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ +} +#else +#define MSA_INTERLEAVED_IMPL_STORE3_8(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000050403020100, 0x0000001413121110}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0A02110901100800, 0x05140C04130B0312}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000A09080706, 0x00001A1918171615}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x170A011609001508, 0x0D04190C03180B02}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x0000000F0E0D0C0B, 0x0000001F1E1D1C1B}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_b((_Tpvs)((v2i64){0x021C09011B08001A, 0x1F0C041E0B031D0A}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 32, (_Tpv)v1); \ +} +#endif + +MSA_INTERLEAVED_IMPL_STORE3_8(uint8_t, v16u8, v16i8, u8) +MSA_INTERLEAVED_IMPL_STORE3_8(int8_t, v16i8, v16i8, s8) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000700060005000F, 0x000F000E000D000F}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000A0006000D0009, 0x000F000B0007000E}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00040003000F000F, 0x000C000B000A000F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000E000A0003000D, 0x0005000F000B0004}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000200010000000F, 0x00090008000F000F}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000E00090000, 0x000B0002000F000A}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ +} +#else +#define MSA_INTERLEAVED_IMPL_STORE3_16(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000200010000, 0x0000000A00090008}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0001000800040000, 0x0006000200090005}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000500040003, 0x00000000000C000B}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x000B00040000000A, 0x0002000C00050001}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x0000000000070006, 0x0000000F000E000D}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_h((_Tpvs)((v2i64){0x00050000000D0004, 0x000F00060001000E}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 16, (_Tpv)v1); \ +} +#endif + +MSA_INTERLEAVED_IMPL_STORE3_16(uint16_t, v8u16, v8i16, u16) +MSA_INTERLEAVED_IMPL_STORE3_16(int16_t, v8i16, v8i16, s16) + +#ifdef _MIPSEB +#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000007, 0x0000000700000006}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000300000006, 0x0000000700000005}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000001, 0x0000000500000007}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000700000004, 0x0000000500000002}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000007, 0x0000000400000007}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000000, 0x0000000100000007}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ +} +#else +#define MSA_INTERLEAVED_IMPL_STORE3_32(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + _Tpvs v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000100000000, 0x0000000000000004}), (_Tpvs)b, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000200000000, 0x0000000100000004}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000002, 0x0000000600000005}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000500000002, 0x0000000300000000}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 4, (_Tpv)v1); \ + v0 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000003, 0x0000000000000007}), (_Tpvs)b, (_Tpvs)a); \ + v1 = __builtin_msa_vshf_w((_Tpvs)((v2i64){0x0000000000000006, 0x0000000700000002}), (_Tpvs)c, (_Tpvs)v0); \ + msa_st1q_##suffix(ptr + 8, (_Tpv)v1); \ +} +#endif + +MSA_INTERLEAVED_IMPL_STORE3_32(uint32_t, v4u32, v4i32, u32) +MSA_INTERLEAVED_IMPL_STORE3_32(int32_t, v4i32, v4i32, s32) +MSA_INTERLEAVED_IMPL_STORE3_32(float, v4f32, v4i32, f32) + +#define MSA_INTERLEAVED_IMPL_STORE3_64(_Tp, _Tpv, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st3q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c) \ +{ \ + *ptr = a[0]; *(ptr + 1) = b[0]; *(ptr + 2) = c[0]; \ + *(ptr + 3) = a[1]; *(ptr + 4) = b[1]; *(ptr + 5) = c[1]; \ +} + +MSA_INTERLEAVED_IMPL_STORE3_64(uint64_t, v2u64, u64) +MSA_INTERLEAVED_IMPL_STORE3_64(int64_t, v2i64, s64) +MSA_INTERLEAVED_IMPL_STORE3_64(double, v2f64, f64) + +#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4(_Tp, _Tpv, _Tpvs, suffix, df, nlanes) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + nlanes); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + nlanes * 2); \ + _Tpv v3 = msa_ld1q_##suffix(ptr + nlanes * 3); \ + _Tpvs t0 = __builtin_msa_pckev_##df((_Tpvs)v1, (_Tpvs)v0); \ + _Tpvs t1 = __builtin_msa_pckev_##df((_Tpvs)v3, (_Tpvs)v2); \ + _Tpvs t2 = __builtin_msa_pckod_##df((_Tpvs)v1, (_Tpvs)v0); \ + _Tpvs t3 = __builtin_msa_pckod_##df((_Tpvs)v3, (_Tpvs)v2); \ + *a = (_Tpv)__builtin_msa_pckev_##df(t1, t0); \ + *b = (_Tpv)__builtin_msa_pckev_##df(t3, t2); \ + *c = (_Tpv)__builtin_msa_pckod_##df(t1, t0); \ + *d = (_Tpv)__builtin_msa_pckod_##df(t3, t2); \ +} \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ +{ \ + _Tpvs v0 = __builtin_msa_ilvr_##df((_Tpvs)c, (_Tpvs)a); \ + _Tpvs v1 = __builtin_msa_ilvr_##df((_Tpvs)d, (_Tpvs)b); \ + _Tpvs v2 = __builtin_msa_ilvl_##df((_Tpvs)c, (_Tpvs)a); \ + _Tpvs v3 = __builtin_msa_ilvl_##df((_Tpvs)d, (_Tpvs)b); \ + msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_##df(v1, v0)); \ + msa_st1q_##suffix(ptr + nlanes, (_Tpv)__builtin_msa_ilvl_##df(v1, v0)); \ + msa_st1q_##suffix(ptr + 2 * nlanes, (_Tpv)__builtin_msa_ilvr_##df(v3, v2)); \ + msa_st1q_##suffix(ptr + 3 * nlanes, (_Tpv)__builtin_msa_ilvl_##df(v3, v2)); \ +} + +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint8_t, v16u8, v16i8, u8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int8_t, v16i8, v16i8, s8, b, 16) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint16_t, v8u16, v8i16, u16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int16_t, v8i16, v8i16, s16, h, 8) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(uint32_t, v4u32, v4i32, u32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(int32_t, v4i32, v4i32, s32, w, 4) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4(float, v4f32, v4i32, f32, w, 4) + +#define MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(_Tp, _Tpv, _Tpvs, suffix) \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_ld4q_##suffix(const _Tp* ptr, _Tpv* a, _Tpv* b, _Tpv* c, _Tpv* d) \ +{ \ + _Tpv v0 = msa_ld1q_##suffix(ptr); \ + _Tpv v1 = msa_ld1q_##suffix(ptr + 2); \ + _Tpv v2 = msa_ld1q_##suffix(ptr + 4); \ + _Tpv v3 = msa_ld1q_##suffix(ptr + 6); \ + *a = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v2, (_Tpvs)v0); \ + *b = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v2, (_Tpvs)v0); \ + *c = (_Tpv)__builtin_msa_ilvr_d((_Tpvs)v3, (_Tpvs)v1); \ + *d = (_Tpv)__builtin_msa_ilvl_d((_Tpvs)v3, (_Tpvs)v1); \ +} \ +__extension__ extern __inline void \ +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) \ +msa_st4q_##suffix(_Tp* ptr, const _Tpv a, const _Tpv b, const _Tpv c, const _Tpv d) \ +{ \ + msa_st1q_##suffix(ptr, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)b, (_Tpvs)a)); \ + msa_st1q_##suffix(ptr + 2, (_Tpv)__builtin_msa_ilvr_d((_Tpvs)d, (_Tpvs)c)); \ + msa_st1q_##suffix(ptr + 4, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)b, (_Tpvs)a)); \ + msa_st1q_##suffix(ptr + 6, (_Tpv)__builtin_msa_ilvl_d((_Tpvs)d, (_Tpvs)c)); \ +} + +MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(uint64_t, v2u64, v2i64, u64) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(int64_t, v2i64, v2i64, s64) +MSA_INTERLEAVED_IMPL_LOAD4_STORE4_64(double, v2f64, v2i64, f64) + +__extension__ extern __inline v8i16 +__attribute__ ((__always_inline__, __gnu_inline__, __artificial__)) +msa_qdmulhq_n_s16(v8i16 a, int16_t b) +{ + v8i16 a_lo, a_hi; + ILVRL_H2_SH(a, msa_dupq_n_s16(0), a_lo, a_hi); + return msa_packr_s32(msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_lo), msa_dupq_n_s32(b)), 1), + msa_shlq_n_s32(msa_mulq_s32(msa_paddlq_s16(a_hi), msa_dupq_n_s32(b)), 1), 16); +} + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif /*__mips_msa*/ +#endif /* OPENCV_CORE_MSA_MACROS_H */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp index 14e3dfd56f..0a1ab2c523 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/hal/simd_utils.impl.hpp @@ -1,186 +1,186 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -// This header is not standalone. Don't include directly, use "intrin.hpp" instead. -#ifdef OPENCV_HAL_INTRIN_HPP // defined in intrin.hpp - - -#if CV_SIMD128 || CV_SIMD128_CPP - -template struct Type2Vec128_Traits; -#define CV_INTRIN_DEF_TYPE2VEC128_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec128_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uchar, v_uint8x16); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(schar, v_int8x16); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(ushort, v_uint16x8); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(short, v_int16x8); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(unsigned, v_uint32x4); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int, v_int32x4); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(float, v_float32x4); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uint64, v_uint64x2); -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int64, v_int64x2); -#if CV_SIMD128_64F -CV_INTRIN_DEF_TYPE2VEC128_TRAITS(double, v_float64x2); -#endif - -template static inline -typename Type2Vec128_Traits<_T>::vec_type v_setall(const _T& a); - -template<> inline Type2Vec128_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } -template<> inline Type2Vec128_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } -template<> inline Type2Vec128_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } -template<> inline Type2Vec128_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } -template<> inline Type2Vec128_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } -template<> inline Type2Vec128_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } -template<> inline Type2Vec128_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } -template<> inline Type2Vec128_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } -template<> inline Type2Vec128_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } -#if CV_SIMD128_64F -template<> inline Type2Vec128_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } -#endif - -#endif // SIMD128 - - -#if CV_SIMD256 - -template struct Type2Vec256_Traits; -#define CV_INTRIN_DEF_TYPE2VEC256_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec256_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uchar, v_uint8x32); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(schar, v_int8x32); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(ushort, v_uint16x16); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(short, v_int16x16); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(unsigned, v_uint32x8); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int, v_int32x8); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(float, v_float32x8); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uint64, v_uint64x4); -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int64, v_int64x4); -#if CV_SIMD256_64F -CV_INTRIN_DEF_TYPE2VEC256_TRAITS(double, v_float64x4); -#endif - -template static inline -typename Type2Vec256_Traits<_T>::vec_type v256_setall(const _T& a); - -template<> inline Type2Vec256_Traits< uchar>::vec_type v256_setall< uchar>(const uchar& a) { return v256_setall_u8(a); } -template<> inline Type2Vec256_Traits< schar>::vec_type v256_setall< schar>(const schar& a) { return v256_setall_s8(a); } -template<> inline Type2Vec256_Traits::vec_type v256_setall(const ushort& a) { return v256_setall_u16(a); } -template<> inline Type2Vec256_Traits< short>::vec_type v256_setall< short>(const short& a) { return v256_setall_s16(a); } -template<> inline Type2Vec256_Traits< uint>::vec_type v256_setall< uint>(const uint& a) { return v256_setall_u32(a); } -template<> inline Type2Vec256_Traits< int>::vec_type v256_setall< int>(const int& a) { return v256_setall_s32(a); } -template<> inline Type2Vec256_Traits::vec_type v256_setall(const uint64& a) { return v256_setall_u64(a); } -template<> inline Type2Vec256_Traits< int64>::vec_type v256_setall< int64>(const int64& a) { return v256_setall_s64(a); } -template<> inline Type2Vec256_Traits< float>::vec_type v256_setall< float>(const float& a) { return v256_setall_f32(a); } -#if CV_SIMD256_64F -template<> inline Type2Vec256_Traits::vec_type v256_setall(const double& a) { return v256_setall_f64(a); } -#endif - -#endif // SIMD256 - - -#if CV_SIMD512 - -template struct Type2Vec512_Traits; -#define CV_INTRIN_DEF_TYPE2VEC512_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec512_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uchar, v_uint8x64); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(schar, v_int8x64); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(ushort, v_uint16x32); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(short, v_int16x32); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(unsigned, v_uint32x16); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int, v_int32x16); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(float, v_float32x16); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uint64, v_uint64x8); -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int64, v_int64x8); -#if CV_SIMD512_64F -CV_INTRIN_DEF_TYPE2VEC512_TRAITS(double, v_float64x8); -#endif - -template static inline -typename Type2Vec512_Traits<_T>::vec_type v512_setall(const _T& a); - -template<> inline Type2Vec512_Traits< uchar>::vec_type v512_setall< uchar>(const uchar& a) { return v512_setall_u8(a); } -template<> inline Type2Vec512_Traits< schar>::vec_type v512_setall< schar>(const schar& a) { return v512_setall_s8(a); } -template<> inline Type2Vec512_Traits::vec_type v512_setall(const ushort& a) { return v512_setall_u16(a); } -template<> inline Type2Vec512_Traits< short>::vec_type v512_setall< short>(const short& a) { return v512_setall_s16(a); } -template<> inline Type2Vec512_Traits< uint>::vec_type v512_setall< uint>(const uint& a) { return v512_setall_u32(a); } -template<> inline Type2Vec512_Traits< int>::vec_type v512_setall< int>(const int& a) { return v512_setall_s32(a); } -template<> inline Type2Vec512_Traits::vec_type v512_setall(const uint64& a) { return v512_setall_u64(a); } -template<> inline Type2Vec512_Traits< int64>::vec_type v512_setall< int64>(const int64& a) { return v512_setall_s64(a); } -template<> inline Type2Vec512_Traits< float>::vec_type v512_setall< float>(const float& a) { return v512_setall_f32(a); } -#if CV_SIMD512_64F -template<> inline Type2Vec512_Traits::vec_type v512_setall(const double& a) { return v512_setall_f64(a); } -#endif - -#endif // SIMD512 - -#if CV_SIMD_SCALABLE -template struct Type2Vec_Traits; -#define CV_INTRIN_DEF_TYPE2VEC_TRAITS(type_, vec_type_) \ - template<> struct Type2Vec_Traits \ - { \ - typedef vec_type_ vec_type; \ - } - -CV_INTRIN_DEF_TYPE2VEC_TRAITS(uchar, v_uint8); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(schar, v_int8); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(ushort, v_uint16); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(short, v_int16); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(unsigned, v_uint32); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(int, v_int32); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(float, v_float32); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(uint64, v_uint64); -CV_INTRIN_DEF_TYPE2VEC_TRAITS(int64, v_int64); -#if CV_SIMD_SCALABLE_64F -CV_INTRIN_DEF_TYPE2VEC_TRAITS(double, v_float64); -#endif -template static inline -typename Type2Vec_Traits<_T>::vec_type v_setall(const _T& a); - -template<> inline Type2Vec_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } -template<> inline Type2Vec_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } -template<> inline Type2Vec_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } -template<> inline Type2Vec_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } -template<> inline Type2Vec_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } -template<> inline Type2Vec_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } -template<> inline Type2Vec_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } -template<> inline Type2Vec_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } -template<> inline Type2Vec_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } -#if CV_SIMD_SCALABLE_64F -template<> inline Type2Vec_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } -#endif -#endif - - -#if CV_SIMD_SCALABLE -template static inline -typename Type2Vec_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } -#elif CV_SIMD_WIDTH == 16 -template static inline -typename Type2Vec128_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } -#elif CV_SIMD_WIDTH == 32 -template static inline -typename Type2Vec256_Traits<_T>::vec_type vx_setall(const _T& a) { return v256_setall(a); } -#elif CV_SIMD_WIDTH == 64 -template static inline -typename Type2Vec512_Traits<_T>::vec_type vx_setall(const _T& a) { return v512_setall(a); } -#else -#error "Build configuration error, unsupported CV_SIMD_WIDTH" -#endif - - -#endif // OPENCV_HAL_INTRIN_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +// This header is not standalone. Don't include directly, use "intrin.hpp" instead. +#ifdef OPENCV_HAL_INTRIN_HPP // defined in intrin.hpp + + +#if CV_SIMD128 || CV_SIMD128_CPP + +template struct Type2Vec128_Traits; +#define CV_INTRIN_DEF_TYPE2VEC128_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec128_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uchar, v_uint8x16); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(schar, v_int8x16); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(ushort, v_uint16x8); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(short, v_int16x8); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(unsigned, v_uint32x4); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int, v_int32x4); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(float, v_float32x4); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(uint64, v_uint64x2); +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(int64, v_int64x2); +#if CV_SIMD128_64F +CV_INTRIN_DEF_TYPE2VEC128_TRAITS(double, v_float64x2); +#endif + +template static inline +typename Type2Vec128_Traits<_T>::vec_type v_setall(const _T& a); + +template<> inline Type2Vec128_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } +template<> inline Type2Vec128_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } +template<> inline Type2Vec128_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } +template<> inline Type2Vec128_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } +template<> inline Type2Vec128_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } +template<> inline Type2Vec128_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } +template<> inline Type2Vec128_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } +template<> inline Type2Vec128_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } +template<> inline Type2Vec128_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } +#if CV_SIMD128_64F +template<> inline Type2Vec128_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } +#endif + +#endif // SIMD128 + + +#if CV_SIMD256 + +template struct Type2Vec256_Traits; +#define CV_INTRIN_DEF_TYPE2VEC256_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec256_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uchar, v_uint8x32); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(schar, v_int8x32); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(ushort, v_uint16x16); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(short, v_int16x16); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(unsigned, v_uint32x8); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int, v_int32x8); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(float, v_float32x8); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(uint64, v_uint64x4); +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(int64, v_int64x4); +#if CV_SIMD256_64F +CV_INTRIN_DEF_TYPE2VEC256_TRAITS(double, v_float64x4); +#endif + +template static inline +typename Type2Vec256_Traits<_T>::vec_type v256_setall(const _T& a); + +template<> inline Type2Vec256_Traits< uchar>::vec_type v256_setall< uchar>(const uchar& a) { return v256_setall_u8(a); } +template<> inline Type2Vec256_Traits< schar>::vec_type v256_setall< schar>(const schar& a) { return v256_setall_s8(a); } +template<> inline Type2Vec256_Traits::vec_type v256_setall(const ushort& a) { return v256_setall_u16(a); } +template<> inline Type2Vec256_Traits< short>::vec_type v256_setall< short>(const short& a) { return v256_setall_s16(a); } +template<> inline Type2Vec256_Traits< uint>::vec_type v256_setall< uint>(const uint& a) { return v256_setall_u32(a); } +template<> inline Type2Vec256_Traits< int>::vec_type v256_setall< int>(const int& a) { return v256_setall_s32(a); } +template<> inline Type2Vec256_Traits::vec_type v256_setall(const uint64& a) { return v256_setall_u64(a); } +template<> inline Type2Vec256_Traits< int64>::vec_type v256_setall< int64>(const int64& a) { return v256_setall_s64(a); } +template<> inline Type2Vec256_Traits< float>::vec_type v256_setall< float>(const float& a) { return v256_setall_f32(a); } +#if CV_SIMD256_64F +template<> inline Type2Vec256_Traits::vec_type v256_setall(const double& a) { return v256_setall_f64(a); } +#endif + +#endif // SIMD256 + + +#if CV_SIMD512 + +template struct Type2Vec512_Traits; +#define CV_INTRIN_DEF_TYPE2VEC512_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec512_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uchar, v_uint8x64); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(schar, v_int8x64); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(ushort, v_uint16x32); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(short, v_int16x32); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(unsigned, v_uint32x16); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int, v_int32x16); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(float, v_float32x16); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(uint64, v_uint64x8); +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(int64, v_int64x8); +#if CV_SIMD512_64F +CV_INTRIN_DEF_TYPE2VEC512_TRAITS(double, v_float64x8); +#endif + +template static inline +typename Type2Vec512_Traits<_T>::vec_type v512_setall(const _T& a); + +template<> inline Type2Vec512_Traits< uchar>::vec_type v512_setall< uchar>(const uchar& a) { return v512_setall_u8(a); } +template<> inline Type2Vec512_Traits< schar>::vec_type v512_setall< schar>(const schar& a) { return v512_setall_s8(a); } +template<> inline Type2Vec512_Traits::vec_type v512_setall(const ushort& a) { return v512_setall_u16(a); } +template<> inline Type2Vec512_Traits< short>::vec_type v512_setall< short>(const short& a) { return v512_setall_s16(a); } +template<> inline Type2Vec512_Traits< uint>::vec_type v512_setall< uint>(const uint& a) { return v512_setall_u32(a); } +template<> inline Type2Vec512_Traits< int>::vec_type v512_setall< int>(const int& a) { return v512_setall_s32(a); } +template<> inline Type2Vec512_Traits::vec_type v512_setall(const uint64& a) { return v512_setall_u64(a); } +template<> inline Type2Vec512_Traits< int64>::vec_type v512_setall< int64>(const int64& a) { return v512_setall_s64(a); } +template<> inline Type2Vec512_Traits< float>::vec_type v512_setall< float>(const float& a) { return v512_setall_f32(a); } +#if CV_SIMD512_64F +template<> inline Type2Vec512_Traits::vec_type v512_setall(const double& a) { return v512_setall_f64(a); } +#endif + +#endif // SIMD512 + +#if CV_SIMD_SCALABLE +template struct Type2Vec_Traits; +#define CV_INTRIN_DEF_TYPE2VEC_TRAITS(type_, vec_type_) \ + template<> struct Type2Vec_Traits \ + { \ + typedef vec_type_ vec_type; \ + } + +CV_INTRIN_DEF_TYPE2VEC_TRAITS(uchar, v_uint8); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(schar, v_int8); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(ushort, v_uint16); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(short, v_int16); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(unsigned, v_uint32); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(int, v_int32); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(float, v_float32); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(uint64, v_uint64); +CV_INTRIN_DEF_TYPE2VEC_TRAITS(int64, v_int64); +#if CV_SIMD_SCALABLE_64F +CV_INTRIN_DEF_TYPE2VEC_TRAITS(double, v_float64); +#endif +template static inline +typename Type2Vec_Traits<_T>::vec_type v_setall(const _T& a); + +template<> inline Type2Vec_Traits< uchar>::vec_type v_setall< uchar>(const uchar& a) { return v_setall_u8(a); } +template<> inline Type2Vec_Traits< schar>::vec_type v_setall< schar>(const schar& a) { return v_setall_s8(a); } +template<> inline Type2Vec_Traits::vec_type v_setall(const ushort& a) { return v_setall_u16(a); } +template<> inline Type2Vec_Traits< short>::vec_type v_setall< short>(const short& a) { return v_setall_s16(a); } +template<> inline Type2Vec_Traits< uint>::vec_type v_setall< uint>(const uint& a) { return v_setall_u32(a); } +template<> inline Type2Vec_Traits< int>::vec_type v_setall< int>(const int& a) { return v_setall_s32(a); } +template<> inline Type2Vec_Traits::vec_type v_setall(const uint64& a) { return v_setall_u64(a); } +template<> inline Type2Vec_Traits< int64>::vec_type v_setall< int64>(const int64& a) { return v_setall_s64(a); } +template<> inline Type2Vec_Traits< float>::vec_type v_setall< float>(const float& a) { return v_setall_f32(a); } +#if CV_SIMD_SCALABLE_64F +template<> inline Type2Vec_Traits::vec_type v_setall(const double& a) { return v_setall_f64(a); } +#endif +#endif + + +#if CV_SIMD_SCALABLE +template static inline +typename Type2Vec_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } +#elif CV_SIMD_WIDTH == 16 +template static inline +typename Type2Vec128_Traits<_T>::vec_type vx_setall(const _T& a) { return v_setall(a); } +#elif CV_SIMD_WIDTH == 32 +template static inline +typename Type2Vec256_Traits<_T>::vec_type vx_setall(const _T& a) { return v256_setall(a); } +#elif CV_SIMD_WIDTH == 64 +template static inline +typename Type2Vec512_Traits<_T>::vec_type vx_setall(const _T& a) { return v512_setall(a); } +#else +#error "Build configuration error, unsupported CV_SIMD_WIDTH" +#endif + + +#endif // OPENCV_HAL_INTRIN_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp b/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp index be1b8faecb..2282e12aee 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/mat.hpp @@ -1,3814 +1,3814 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_MAT_HPP -#define OPENCV_CORE_MAT_HPP - -#ifndef __cplusplus -# error mat.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/matx.hpp" -#include "opencv2/core/types.hpp" - -#include "opencv2/core/bufferpool.hpp" - -#include -#include - -namespace cv -{ - -//! @addtogroup core_basic -//! @{ - -enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, - ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; -CV_ENUM_FLAGS(AccessFlag) -__CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag) - -CV__DEBUG_NS_BEGIN - -class CV_EXPORTS _OutputArray; - -//////////////////////// Input/Output Array Arguments ///////////////////////////////// - -/** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. - -It is defined as: -@code - typedef const _InputArray& InputArray; -@endcode -where \ref cv::_InputArray is a class that can be constructed from \ref cv::Mat, \ref cv::Mat_, -\ref cv::Matx, std::vector, std::vector>, std::vector, -std::vector>, \ref cv::UMat, std::vector or `double`. It can also be constructed from -a matrix expression. - -Since this is mostly implementation-level class, and its interface may change in future versions, we -do not describe it in details. There are a few key things, though, that should be kept in mind: - -- When you see in the reference manual or in OpenCV source code a function that takes - InputArray, it means that you can actually pass `Mat`, `Matx`, `vector` etc. (see above the - complete list). -- Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or - simply cv::Mat() as you probably did before). -- The class is designed solely for passing parameters. That is, normally you *should not* - declare class members, local and global variables of this type. -- If you want to design your own function or a class method that can operate of arrays of - multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside - a function you should use _InputArray::getMat() method to construct a matrix header for the - array (without copying data). _InputArray::kind() can be used to distinguish Mat from - `vector<>` etc., but normally it is not needed. - -Here is how you can use a function that takes InputArray : -@code - std::vector vec; - // points or a circle - for( int i = 0; i < 30; i++ ) - vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), - (float)(100 - 30*sin(i*CV_PI*2/5)))); - cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); -@endcode -That is, we form an STL vector containing points, and apply in-place affine transformation to the -vector using the 2x3 matrix created inline as `Matx` instance. - -Here is how such a function can be implemented (for simplicity, we implement a very specific case of -it, according to the assertion statement inside) : -@code - void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) - { - // get Mat headers for input arrays. This is O(1) operation, - // unless _src and/or _m are matrix expressions. - Mat src = _src.getMat(), m = _m.getMat(); - CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); - - // [re]create the output array so that it has the proper size and type. - // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. - _dst.create(src.size(), src.type()); - Mat dst = _dst.getMat(); - - for( int i = 0; i < src.rows; i++ ) - for( int j = 0; j < src.cols; j++ ) - { - Point2f pt = src.at(i, j); - dst.at(i, j) = Point2f(m.at(0, 0)*pt.x + - m.at(0, 1)*pt.y + - m.at(0, 2), - m.at(1, 0)*pt.x + - m.at(1, 1)*pt.y + - m.at(1, 2)); - } - } -@endcode -There is another related type, InputArrayOfArrays, which is currently defined as a synonym for -InputArray: -@code - typedef InputArray InputArrayOfArrays; -@endcode -It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate -synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation -level their use is similar, but _InputArray::getMat(idx) should be used to get header for the -idx-th component of the outer vector and _InputArray::size().area() should be used to find the -number of components (vectors/matrices) of the outer vector. - -In general, type support is limited to cv::Mat types. Other types are forbidden. -But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc. -This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat. -To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers. -Custom type is wrapped as Mat-compatible `CV_8UC` values (N = sizeof(T), N <= CV_CN_MAX). - */ -class CV_EXPORTS _InputArray -{ -public: - enum KindFlag { - KIND_SHIFT = 16, - FIXED_TYPE = 0x8000 << KIND_SHIFT, - FIXED_SIZE = 0x4000 << KIND_SHIFT, - KIND_MASK = 31 << KIND_SHIFT, - - NONE = 0 << KIND_SHIFT, - MAT = 1 << KIND_SHIFT, - MATX = 2 << KIND_SHIFT, - STD_VECTOR = 3 << KIND_SHIFT, - STD_VECTOR_VECTOR = 4 << KIND_SHIFT, - STD_VECTOR_MAT = 5 << KIND_SHIFT, -#if OPENCV_ABI_COMPATIBILITY < 500 - EXPR = 6 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/pull/17046 -#endif - OPENGL_BUFFER = 7 << KIND_SHIFT, - CUDA_HOST_MEM = 8 << KIND_SHIFT, - CUDA_GPU_MAT = 9 << KIND_SHIFT, - UMAT =10 << KIND_SHIFT, - STD_VECTOR_UMAT =11 << KIND_SHIFT, - STD_BOOL_VECTOR =12 << KIND_SHIFT, - STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT, -#if OPENCV_ABI_COMPATIBILITY < 500 - STD_ARRAY =14 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/issues/18897 -#endif - STD_ARRAY_MAT =15 << KIND_SHIFT - }; - - _InputArray(); - _InputArray(int _flags, void* _obj); - _InputArray(const Mat& m); - _InputArray(const MatExpr& expr); - _InputArray(const std::vector& vec); - template _InputArray(const Mat_<_Tp>& m); - template _InputArray(const std::vector<_Tp>& vec); - _InputArray(const std::vector& vec); - template _InputArray(const std::vector >& vec); - _InputArray(const std::vector >&) = delete; // not supported - template _InputArray(const std::vector >& vec); - template _InputArray(const _Tp* vec, int n); - template _InputArray(const Matx<_Tp, m, n>& matx); - _InputArray(const double& val); - _InputArray(const cuda::GpuMat& d_mat); - _InputArray(const std::vector& d_mat_array); - _InputArray(const ogl::Buffer& buf); - _InputArray(const cuda::HostMem& cuda_mem); - template _InputArray(const cudev::GpuMat_<_Tp>& m); - _InputArray(const UMat& um); - _InputArray(const std::vector& umv); - - template _InputArray(const std::array<_Tp, _Nm>& arr); - template _InputArray(const std::array& arr); - - template static _InputArray rawIn(const std::vector<_Tp>& vec); - template static _InputArray rawIn(const std::array<_Tp, _Nm>& arr); - - Mat getMat(int idx=-1) const; - Mat getMat_(int idx=-1) const; - UMat getUMat(int idx=-1) const; - void getMatVector(std::vector& mv) const; - void getUMatVector(std::vector& umv) const; - void getGpuMatVector(std::vector& gpumv) const; - cuda::GpuMat getGpuMat() const; - ogl::Buffer getOGlBuffer() const; - - int getFlags() const; - void* getObj() const; - Size getSz() const; - - _InputArray::KindFlag kind() const; - int dims(int i=-1) const; - int cols(int i=-1) const; - int rows(int i=-1) const; - Size size(int i=-1) const; - int sizend(int* sz, int i=-1) const; - bool sameSize(const _InputArray& arr) const; - size_t total(int i=-1) const; - int type(int i=-1) const; - int depth(int i=-1) const; - int channels(int i=-1) const; - bool isContinuous(int i=-1) const; - bool isSubmatrix(int i=-1) const; - bool empty() const; - void copyTo(const _OutputArray& arr) const; - void copyTo(const _OutputArray& arr, const _InputArray & mask) const; - size_t offset(int i=-1) const; - size_t step(int i=-1) const; - bool isMat() const; - bool isUMat() const; - bool isMatVector() const; - bool isUMatVector() const; - bool isMatx() const; - bool isVector() const; - bool isGpuMat() const; - bool isGpuMatVector() const; - ~_InputArray(); - -protected: - int flags; - void* obj; - Size sz; - - void init(int _flags, const void* _obj); - void init(int _flags, const void* _obj, Size _sz); -}; -CV_ENUM_FLAGS(_InputArray::KindFlag) -__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag) - -/** @brief This type is very similar to InputArray except that it is used for input/output and output function -parameters. - -Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, -`vector` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly -create OutputArray instances* applies here too. - -If you want to make your function polymorphic (i.e. accept different arrays as output parameters), -it is also not very difficult. Take the sample above as the reference. Note that -_OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee -that the output array is properly allocated. - -Optional output parameters. If you do not need certain output array to be computed and returned to -you, pass cv::noArray(), just like you would in the case of optional input array. At the -implementation level, use _OutputArray::needed() to check if certain output array needs to be -computed or not. - -There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper -generators: -@code - typedef OutputArray OutputArrayOfArrays; - typedef OutputArray InputOutputArray; - typedef OutputArray InputOutputArrayOfArrays; -@endcode - */ -class CV_EXPORTS _OutputArray : public _InputArray -{ -public: - enum DepthMask - { - DEPTH_MASK_8U = 1 << CV_8U, - DEPTH_MASK_8S = 1 << CV_8S, - DEPTH_MASK_16U = 1 << CV_16U, - DEPTH_MASK_16S = 1 << CV_16S, - DEPTH_MASK_32S = 1 << CV_32S, - DEPTH_MASK_32F = 1 << CV_32F, - DEPTH_MASK_64F = 1 << CV_64F, - DEPTH_MASK_16F = 1 << CV_16F, - DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, - DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, - DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1, - DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F - }; - - _OutputArray(); - _OutputArray(int _flags, void* _obj); - _OutputArray(Mat& m); - _OutputArray(std::vector& vec); - _OutputArray(cuda::GpuMat& d_mat); - _OutputArray(std::vector& d_mat); - _OutputArray(ogl::Buffer& buf); - _OutputArray(cuda::HostMem& cuda_mem); - template _OutputArray(cudev::GpuMat_<_Tp>& m); - template _OutputArray(std::vector<_Tp>& vec); - _OutputArray(std::vector& vec) = delete; // not supported - template _OutputArray(std::vector >& vec); - _OutputArray(std::vector >&) = delete; // not supported - template _OutputArray(std::vector >& vec); - template _OutputArray(Mat_<_Tp>& m); - template _OutputArray(_Tp* vec, int n); - template _OutputArray(Matx<_Tp, m, n>& matx); - _OutputArray(UMat& m); - _OutputArray(std::vector& vec); - - _OutputArray(const Mat& m); - _OutputArray(const std::vector& vec); - _OutputArray(const cuda::GpuMat& d_mat); - _OutputArray(const std::vector& d_mat); - _OutputArray(const ogl::Buffer& buf); - _OutputArray(const cuda::HostMem& cuda_mem); - template _OutputArray(const cudev::GpuMat_<_Tp>& m); - template _OutputArray(const std::vector<_Tp>& vec); - template _OutputArray(const std::vector >& vec); - template _OutputArray(const std::vector >& vec); - template _OutputArray(const Mat_<_Tp>& m); - template _OutputArray(const _Tp* vec, int n); - template _OutputArray(const Matx<_Tp, m, n>& matx); - _OutputArray(const UMat& m); - _OutputArray(const std::vector& vec); - - template _OutputArray(std::array<_Tp, _Nm>& arr); - template _OutputArray(const std::array<_Tp, _Nm>& arr); - template _OutputArray(std::array& arr); - template _OutputArray(const std::array& arr); - - template static _OutputArray rawOut(std::vector<_Tp>& vec); - template static _OutputArray rawOut(std::array<_Tp, _Nm>& arr); - - bool fixedSize() const; - bool fixedType() const; - bool needed() const; - Mat& getMatRef(int i=-1) const; - UMat& getUMatRef(int i=-1) const; - cuda::GpuMat& getGpuMatRef() const; - std::vector& getGpuMatVecRef() const; - ogl::Buffer& getOGlBufferRef() const; - cuda::HostMem& getHostMemRef() const; - void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; - void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; - void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; - void createSameSize(const _InputArray& arr, int mtype) const; - void release() const; - void clear() const; - void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; - - void assign(const UMat& u) const; - void assign(const Mat& m) const; - - void assign(const std::vector& v) const; - void assign(const std::vector& v) const; - - void move(UMat& u) const; - void move(Mat& m) const; -}; - - -class CV_EXPORTS _InputOutputArray : public _OutputArray -{ -public: - _InputOutputArray(); - _InputOutputArray(int _flags, void* _obj); - _InputOutputArray(Mat& m); - _InputOutputArray(std::vector& vec); - _InputOutputArray(cuda::GpuMat& d_mat); - _InputOutputArray(ogl::Buffer& buf); - _InputOutputArray(cuda::HostMem& cuda_mem); - template _InputOutputArray(cudev::GpuMat_<_Tp>& m); - template _InputOutputArray(std::vector<_Tp>& vec); - _InputOutputArray(std::vector& vec) = delete; // not supported - template _InputOutputArray(std::vector >& vec); - template _InputOutputArray(std::vector >& vec); - template _InputOutputArray(Mat_<_Tp>& m); - template _InputOutputArray(_Tp* vec, int n); - template _InputOutputArray(Matx<_Tp, m, n>& matx); - _InputOutputArray(UMat& m); - _InputOutputArray(std::vector& vec); - - _InputOutputArray(const Mat& m); - _InputOutputArray(const std::vector& vec); - _InputOutputArray(const cuda::GpuMat& d_mat); - _InputOutputArray(const std::vector& d_mat); - _InputOutputArray(const ogl::Buffer& buf); - _InputOutputArray(const cuda::HostMem& cuda_mem); - template _InputOutputArray(const cudev::GpuMat_<_Tp>& m); - template _InputOutputArray(const std::vector<_Tp>& vec); - template _InputOutputArray(const std::vector >& vec); - template _InputOutputArray(const std::vector >& vec); - template _InputOutputArray(const Mat_<_Tp>& m); - template _InputOutputArray(const _Tp* vec, int n); - template _InputOutputArray(const Matx<_Tp, m, n>& matx); - _InputOutputArray(const UMat& m); - _InputOutputArray(const std::vector& vec); - - template _InputOutputArray(std::array<_Tp, _Nm>& arr); - template _InputOutputArray(const std::array<_Tp, _Nm>& arr); - template _InputOutputArray(std::array& arr); - template _InputOutputArray(const std::array& arr); - - template static _InputOutputArray rawInOut(std::vector<_Tp>& vec); - template _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr); - -}; - -/** Helper to wrap custom types. @see InputArray */ -template static inline _InputArray rawIn(_Tp& v); -/** Helper to wrap custom types. @see InputArray */ -template static inline _OutputArray rawOut(_Tp& v); -/** Helper to wrap custom types. @see InputArray */ -template static inline _InputOutputArray rawInOut(_Tp& v); - -CV__DEBUG_NS_END - -typedef const _InputArray& InputArray; -typedef InputArray InputArrayOfArrays; -typedef const _OutputArray& OutputArray; -typedef OutputArray OutputArrayOfArrays; -typedef const _InputOutputArray& InputOutputArray; -typedef InputOutputArray InputOutputArrayOfArrays; - -/** @brief Returns an empty InputArray or OutputArray. - - This function is used to provide an "empty" or "null" array when certain functions - take optional input or output arrays that you don't want to provide. - - Many OpenCV functions accept optional arguments as `cv::InputArray` or `cv::OutputArray`. - When you don't want to pass any data for these optional parameters, you can use `cv::noArray()` - to indicate that you are omitting them. - - @return An empty `cv::InputArray` or `cv::OutputArray` that can be used as a placeholder. - - @note This is often used when a function has optional arrays, and you do not want to - provide a specific input or output array. - - @see cv::InputArray, cv::OutputArray - */ -CV_EXPORTS InputOutputArray noArray(); - -/////////////////////////////////// MatAllocator ////////////////////////////////////// - -/** @brief Usage flags for allocator - - @warning All flags except `USAGE_DEFAULT` are experimental. - - @warning For the OpenCL allocator, `USAGE_ALLOCATE_SHARED_MEMORY` depends on - OpenCV's optional, experimental integration with OpenCL SVM. To enable this - integration, build OpenCV using the `WITH_OPENCL_SVM=ON` CMake option and, at - runtime, call `cv::ocl::Context::getDefault().setUseSVM(true);` or similar - code. Note that SVM is incompatible with OpenCL 1.x. -*/ -enum UMatUsageFlags -{ - USAGE_DEFAULT = 0, - - // buffer allocation policy is platform and usage specific - USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, - USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, - USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY - - __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint -}; - -struct CV_EXPORTS UMatData; - -/** @brief Custom array allocator -*/ -class CV_EXPORTS MatAllocator -{ -public: - MatAllocator() {} - virtual ~MatAllocator() {} - - // let's comment it off for now to detect and fix all the uses of allocator - //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, - // uchar*& datastart, uchar*& data, size_t* step) = 0; - //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; - virtual UMatData* allocate(int dims, const int* sizes, int type, - void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0; - virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0; - virtual void deallocate(UMatData* data) const = 0; - virtual void map(UMatData* data, AccessFlag accessflags) const; - virtual void unmap(UMatData* data) const; - virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], - const size_t srcofs[], const size_t srcstep[], - const size_t dststep[]) const; - virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], - const size_t dstofs[], const size_t dststep[], - const size_t srcstep[]) const; - virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], - const size_t srcofs[], const size_t srcstep[], - const size_t dstofs[], const size_t dststep[], bool sync) const; - - // default implementation returns DummyBufferPoolController - virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; -}; - - -//////////////////////////////// MatCommaInitializer ////////////////////////////////// - -/** @brief Comma-separated Matrix Initializer - - The class instances are usually not created explicitly. - Instead, they are created on "matrix << firstValue" operator. - - The sample below initializes 2x2 rotation matrix: - - \code - double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); - Mat R = (Mat_(2,2) << a, -b, b, a); - \endcode -*/ -template class MatCommaInitializer_ -{ -public: - //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat - MatCommaInitializer_(Mat_<_Tp>* _m); - //! the operator that takes the next value and put it to the matrix - template MatCommaInitializer_<_Tp>& operator , (T2 v); - //! another form of conversion operator - operator Mat_<_Tp>() const; -protected: - MatIterator_<_Tp> it; -}; - - -/////////////////////////////////////// Mat /////////////////////////////////////////// - -// note that umatdata might be allocated together -// with the matrix data, not as a separate object. -// therefore, it does not have constructor or destructor; -// it should be explicitly initialized using init(). -struct CV_EXPORTS UMatData -{ - enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, - DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, - USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64, - ASYNC_CLEANUP=128 - }; - UMatData(const MatAllocator* allocator); - ~UMatData(); - - // provide atomic access to the structure - void lock(); - void unlock(); - - bool hostCopyObsolete() const; - bool deviceCopyObsolete() const; - bool deviceMemMapped() const; - bool copyOnMap() const; - bool tempUMat() const; - bool tempCopiedUMat() const; - void markHostCopyObsolete(bool flag); - void markDeviceCopyObsolete(bool flag); - void markDeviceMemMapped(bool flag); - - const MatAllocator* prevAllocator; - const MatAllocator* currAllocator; - int urefcount; - int refcount; - uchar* data; - uchar* origdata; - size_t size; - - UMatData::MemoryFlag flags; - void* handle; - void* userdata; - int allocatorFlags_; - int mapcount; - UMatData* originalUMatData; - std::shared_ptr allocatorContext; -}; -CV_ENUM_FLAGS(UMatData::MemoryFlag) - - -struct CV_EXPORTS MatSize -{ - explicit MatSize(int* _p) CV_NOEXCEPT; - int dims() const CV_NOEXCEPT; - Size operator()() const; - const int& operator[](int i) const; - int& operator[](int i); - operator const int*() const CV_NOEXCEPT; // TODO OpenCV 4.0: drop this - bool operator == (const MatSize& sz) const CV_NOEXCEPT; - bool operator != (const MatSize& sz) const CV_NOEXCEPT; - - int* p; -}; - -struct CV_EXPORTS MatStep -{ - MatStep() CV_NOEXCEPT; - explicit MatStep(size_t s) CV_NOEXCEPT; - const size_t& operator[](int i) const CV_NOEXCEPT; - size_t& operator[](int i) CV_NOEXCEPT; - operator size_t() const; - MatStep& operator = (size_t s); - - size_t* p; - size_t buf[2]; -protected: - MatStep& operator = (const MatStep&); -}; - -/** @example samples/cpp/cout_mat.cpp -An example demonstrating the serial out capabilities of cv::Mat -*/ - - /** @brief n-dimensional dense array class \anchor CVMat_Details - -The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It -can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel -volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms -may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array -`M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means -that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, -and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . - -So, the data layout in Mat is compatible with the majority of dense array types from the standard -toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, -that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. -Due to this compatibility, it is possible to make a Mat header for user-allocated data and process -it in-place using OpenCV functions. - -There are many different ways to create a Mat object. The most popular options are listed below: - -- Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) -constructor. A new array of the specified size and type is allocated. type has the same meaning as -in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 -means a 2-channel (complex) floating-point array, and so on. -@code - // make a 7x7 complex matrix filled with 1+3j. - Mat M(7,7,CV_32FC2,Scalar(1,3)); - // and now turn M to a 100x60 15-channel 8-bit matrix. - // The old content will be deallocated - M.create(100,60,CV_8UC(15)); -@endcode -As noted in the introduction to this chapter, create() allocates only a new array when the shape -or type of the current array are different from the specified ones. - -- Create a multi-dimensional array: -@code - // create a 100x100x100 8-bit array - int sz[] = {100, 100, 100}; - Mat bigCube(3, sz, CV_8U, Scalar::all(0)); -@endcode -It passes the number of dimensions =1 to the Mat constructor but the created array will be -2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 -when the array is empty). - -- Use a copy constructor or assignment operator where there can be an array or expression on the -right side (see below). As noted in the introduction, the array assignment is an O(1) operation -because it only copies the header and increases the reference counter. The Mat::clone() method can -be used to get a full (deep) copy of the array when you need it. - -- Construct a header for a part of another array. It can be a single row, single column, several -rows, several columns, rectangular region in the array (called a *minor* in algebra) or a -diagonal. Such operations are also O(1) because the new header references the same data. You can -actually modify a part of the array using this feature, for example: -@code - // add the 5-th row, multiplied by 3 to the 3rd row - M.row(3) = M.row(3) + M.row(5)*3; - // now copy the 7-th column to the 1-st column - // M.col(1) = M.col(7); // this will not work - Mat M1 = M.col(1); - M.col(7).copyTo(M1); - // create a new 320x240 image - Mat img(Size(320,240),CV_8UC3); - // select a ROI - Mat roi(img, Rect(10,10,100,100)); - // fill the ROI with (0,255,0) (which is green in RGB space); - // the original 320x240 image will be modified - roi = Scalar(0,255,0); -@endcode -Due to the additional datastart and dataend members, it is possible to compute a relative -sub-array position in the main *container* array using locateROI(): -@code - Mat A = Mat::eye(10, 10, CV_32S); - // extracts A columns, 1 (inclusive) to 3 (exclusive). - Mat B = A(Range::all(), Range(1, 3)); - // extracts B rows, 5 (inclusive) to 9 (exclusive). - // that is, C \~ A(Range(5, 9), Range(1, 3)) - Mat C = B(Range(5, 9), Range::all()); - Size size; Point ofs; - C.locateROI(size, ofs); - // size will be (width=10,height=10) and the ofs will be (x=1, y=5) -@endcode -As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted -sub-matrices. - -- Make a header for user-allocated data. It can be useful to do the following: - -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or - a processing module for gstreamer, and so on). For example: - @code - Mat process_video_frame(const unsigned char* pixels, - int width, int height, int step) - { - // wrap input buffer - Mat img(height, width, CV_8UC3, (unsigned char*)pixels, step); - - Mat result; - GaussianBlur(img, result, Size(7, 7), 1.5, 1.5); - - return result; - } - @endcode - -# Quickly initialize small matrices and/or get a super-fast element access. - @code - double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; - Mat M = Mat(3, 3, CV_64F, m).inv(); - @endcode - . - -- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: -@code - // create a double-precision identity matrix and add it to M. - M += Mat::eye(M.rows, M.cols, CV_64F); -@endcode - -- Use a comma-separated initializer: -@code - // create a 3x3 double-precision identity matrix - Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); -@endcode -With this approach, you first call a constructor of the Mat class with the proper parameters, and -then you just put `<< operator` followed by comma-separated values that can be constants, -variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation -errors. - -Once the array is created, it is automatically managed via a reference-counting mechanism. If the -array header is built on top of user-allocated data, you should handle the data by yourself. The -array data is deallocated when no one points to it. If you want to release the data pointed by a -array header before the array destructor is called, use Mat::release(). - -The next important thing to learn about the array class is element access. This manual already -described how to compute an address of each array element. Normally, you are not required to use the -formula directly in the code. If you know the array element type (which can be retrieved using the -method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: -@code - M.at(i,j) += 1.f; -@endcode -assuming that `M` is a double-precision floating-point array. There are several variants of the method -at for a different number of dimensions. - -If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to -the row first, and then just use the plain C operator [] : -@code - // compute sum of positive matrix elements - // (assuming that M is a double-precision matrix) - double sum=0; - for(int i = 0; i < M.rows; i++) - { - const double* Mi = M.ptr(i); - for(int j = 0; j < M.cols; j++) - sum += std::max(Mi[j], 0.); - } -@endcode -Some operations, like the one above, do not actually depend on the array shape. They just process -elements of an array one by one (or elements from multiple arrays that have the same coordinates, -for example, array addition). Such operations are called *element-wise*. It makes sense to check -whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If -yes, process them as a long single row: -@code - // compute the sum of positive matrix elements, optimized variant - double sum=0; - int cols = M.cols, rows = M.rows; - if(M.isContinuous()) - { - cols *= rows; - rows = 1; - } - for(int i = 0; i < rows; i++) - { - const double* Mi = M.ptr(i); - for(int j = 0; j < cols; j++) - sum += std::max(Mi[j], 0.); - } -@endcode -In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is -smaller, which is especially noticeable in case of small matrices. - -Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: -@code - // compute sum of positive matrix elements, iterator-based variant - double sum=0; - MatConstIterator_ it = M.begin(), it_end = M.end(); - for(; it != it_end; ++it) - sum += std::max(*it, 0.); -@endcode -The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, -including std::sort(). - -@note Matrix Expressions and arithmetic see MatExpr -*/ -class CV_EXPORTS Mat -{ -public: - /** - These are various constructors that form a matrix. As noted in the AutomaticAllocation, often - the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. - The constructed matrix can further be assigned to another matrix or matrix expression or can be - allocated with Mat::create . In the former case, the old content is de-referenced. - */ - Mat() CV_NOEXCEPT; - - /** @overload - @param rows Number of rows in a 2D array. - @param cols Number of columns in a 2D array. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(int rows, int cols, int type); - - /** @overload - @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the - number of columns go in the reverse order. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(Size size, int type); - - /** @overload - @param rows Number of rows in a 2D array. - @param cols Number of columns in a 2D array. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(int rows, int cols, int type, const Scalar& s); - - /** @overload - @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the - number of columns go in the reverse order. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(Size size, int type, const Scalar& s); - - /** @overload - @param ndims Array dimensionality. - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(int ndims, const int* sizes, int type); - - /** @overload - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - */ - Mat(const std::vector& sizes, int type); - - /** @overload - @param ndims Array dimensionality. - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(int ndims, const int* sizes, int type, const Scalar& s); - - /** @overload - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param s An optional value to initialize each matrix element with. To set all the matrix elements to - the particular value after the construction, use the assignment operator - Mat::operator=(const Scalar& value) . - */ - Mat(const std::vector& sizes, int type, const Scalar& s); - - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - */ - Mat(const Mat& m); - - /** @overload - @param rows Number of rows in a 2D array. - @param cols Number of columns in a 2D array. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param step Number of bytes each matrix row occupies. The value should include the padding bytes at - the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed - and the actual step is calculated as cols*elemSize(). See Mat::elemSize. - */ - Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); - - /** @overload - @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the - number of columns go in the reverse order. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param step Number of bytes each matrix row occupies. The value should include the padding bytes at - the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed - and the actual step is calculated as cols*elemSize(). See Mat::elemSize. - */ - Mat(Size size, int type, void* data, size_t step=AUTO_STEP); - - /** @overload - @param ndims Array dimensionality. - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always - set to the element size). If not specified, the matrix is assumed to be continuous. - */ - Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); - - /** @overload - @param sizes Array of integers specifying an n-dimensional array shape. - @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always - set to the element size). If not specified, the matrix is assumed to be continuous. - */ - Mat(const std::vector& sizes, int type, void* data, const size_t* steps=0); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range - end is exclusive. Use Range::all() to take all the rows. - @param colRange Range of the m columns to take. Use Range::all() to take all the columns. - */ - Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param roi Region of interest. - */ - Mat(const Mat& m, const Rect& roi); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param ranges Array of selected ranges of m along each dimensionality. - */ - Mat(const Mat& m, const Range* ranges); - - /** @overload - @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied - by these constructors. Instead, the header pointing to m data or its sub-array is constructed and - associated with it. The reference counter, if any, is incremented. So, when you modify the matrix - formed using such a constructor, you also modify the corresponding elements of m . If you want to - have an independent copy of the sub-array, use Mat::clone() . - @param ranges Array of selected ranges of m along each dimensionality. - */ - Mat(const Mat& m, const std::vector& ranges); - - /** @overload - @param vec STL vector whose elements form the matrix. The matrix has a single column and the number - of rows equal to the number of vector elements. Type of the matrix matches the type of vector - elements. The constructor can handle arbitrary types, for which there is a properly declared - DataType . This means that the vector elements must be primitive numbers or uni-type numerical - tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is - explicit. Since STL vectors are not automatically converted to Mat instances, you should write - Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements - will be added to the vector because it can potentially yield vector data reallocation, and, thus, - the matrix data pointer will be invalid. - @param copyData Flag to specify whether the underlying data of the STL vector should be copied - to (true) or shared with (false) the newly constructed matrix. When the data is copied, the - allocated buffer is managed using Mat reference counting mechanism. While the data is shared, - the reference counter is NULL, and you should not deallocate the data until the matrix is - destructed. - */ - template explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); - - /** @overload - */ - template::value>::type> - explicit Mat(const std::initializer_list<_Tp> list); - - /** @overload - */ - template explicit Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list); - - /** @overload - */ - template explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false); - - /** @overload - */ - template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); - - /** @overload - */ - template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); - - /** @overload - */ - template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); - - /** @overload - */ - template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); - - /** @overload - */ - template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); - - //! download data from GpuMat - explicit Mat(const cuda::GpuMat& m); - - //! destructor - calls release() - ~Mat(); - - /** @brief assignment operators - - These are available assignment operators. Since they all are very different, make sure to read the - operator parameters description. - @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that - no data is copied but the data is shared and the reference counter, if any, is incremented. Before - assigning new data, the old data is de-referenced via Mat::release . - */ - Mat& operator = (const Mat& m); - - /** @overload - @param expr Assigned matrix expression object. As opposite to the first form of the assignment - operation, the second form can reuse already allocated matrix if it has the right size and type to - fit the matrix expression result. It is automatically handled by the real function that the matrix - expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of - automatic C reallocation. - */ - Mat& operator = (const MatExpr& expr); - - //! retrieve UMat from Mat - UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; - - /** @brief Creates a matrix header for the specified matrix row. - - The method makes a new header for the specified matrix row and returns it. This is an O(1) - operation, regardless of the matrix size. The underlying data of the new matrix is shared with the - original matrix. Here is the example of one of the classical basic matrix processing operations, - axpy, used by LU and many other algorithms: - @code - inline void matrix_axpy(Mat& A, int i, int j, double alpha) - { - A.row(i) += A.row(j)*alpha; - } - @endcode - @note In the current implementation, the following code does not work as expected: - @code - Mat A; - ... - A.row(i) = A.row(j); // will not work - @endcode - This happens because A.row(i) forms a temporary header that is further assigned to another header. - Remember that each of these operations is O(1), that is, no data is copied. Thus, the above - assignment is not true if you may have expected the j-th row to be copied to the i-th row. To - achieve that, you should either turn this simple assignment into an expression or use the - Mat::copyTo method: - @code - Mat A; - ... - // works, but looks a bit obscure. - A.row(i) = A.row(j) + 0; - // this is a bit longer, but the recommended method. - A.row(j).copyTo(A.row(i)); - @endcode - @param y A 0-based row index. - */ - Mat row(int y) const; - - /** @brief Creates a matrix header for the specified matrix column. - - The method makes a new header for the specified matrix column and returns it. This is an O(1) - operation, regardless of the matrix size. The underlying data of the new matrix is shared with the - original matrix. See also the Mat::row description. - @param x A 0-based column index. - */ - Mat col(int x) const; - - /** @brief Creates a matrix header for the specified row span. - - The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and - Mat::col , this is an O(1) operation. - @param startrow An inclusive 0-based start index of the row span. - @param endrow An exclusive 0-based ending index of the row span. - */ - Mat rowRange(int startrow, int endrow) const; - - /** @overload - @param r Range structure containing both the start and the end indices. - */ - Mat rowRange(const Range& r) const; - - /** @brief Creates a matrix header for the specified column span. - - The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and - Mat::col , this is an O(1) operation. - @param startcol An inclusive 0-based start index of the column span. - @param endcol An exclusive 0-based ending index of the column span. - */ - Mat colRange(int startcol, int endcol) const; - - /** @overload - @param r Range structure containing both the start and the end indices. - */ - Mat colRange(const Range& r) const; - - /** @brief Extracts a diagonal from a matrix - - The method makes a new header for the specified matrix diagonal. The new matrix is represented as a - single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. - @param d index of the diagonal, with the following values: - - `d=0` is the main diagonal. - - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set - immediately below the main one. - - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set - immediately above the main one. - For example: - @code - Mat m = (Mat_(3,3) << - 1,2,3, - 4,5,6, - 7,8,9); - Mat d0 = m.diag(0); - Mat d1 = m.diag(1); - Mat d_1 = m.diag(-1); - @endcode - The resulting matrices are - @code - d0 = - [1; - 5; - 9] - d1 = - [2; - 6] - d_1 = - [4; - 8] - @endcode - */ - Mat diag(int d=0) const; - - /** @brief creates a diagonal matrix - - The method creates a square diagonal matrix from specified main diagonal. - @param d One-dimensional matrix that represents the main diagonal. - */ - CV_NODISCARD_STD static Mat diag(const Mat& d); - - /** @brief Creates a full copy of the array and the underlying data. - - The method creates a full copy of the array. The original step[] is not taken into account. So, the - array copy is a continuous array occupying total()*elemSize() bytes. - */ - CV_NODISCARD_STD Mat clone() const; - - /** @brief Copies the matrix to another one. - - The method copies the matrix data to another matrix. Before copying the data, the method invokes : - @code - m.create(this->size(), this->type()); - @endcode - so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the - function does not handle the case of a partial overlap between the source and the destination - matrices. - - When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, - the newly allocated matrix is initialized with all zeros before copying the data. - @param m Destination matrix. If it does not have a proper size or type before the operation, it is - reallocated. - */ - void copyTo( OutputArray m ) const; - - /** @overload - @param m Destination matrix. If it does not have a proper size or type before the operation, it is - reallocated. - @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix - elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. - */ - void copyTo( OutputArray m, InputArray mask ) const; - - /** @brief Converts an array to another data type with optional scaling. - - The method converts source pixel values to the target data type. saturate_cast\<\> is applied at - the end to avoid possible overflows: - - \f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] - @param m output matrix; if it does not have a proper size or type before the operation, it is - reallocated. - @param rtype desired output matrix type or, rather, the depth since the number of channels are the - same as the input has; if rtype is negative, the output matrix will have the same type as the input. - @param alpha optional scale factor. - @param beta optional delta added to the scaled values. - */ - void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; - - /** @brief Provides a functional form of convertTo. - - This is an internally used method called by the @ref MatrixExpressions engine. - @param m Destination array. - @param type Desired destination array depth (or -1 if it should be the same as the source type). - */ - void assignTo( Mat& m, int type=-1 ) const; - - /** @brief Sets all or some of the array elements to the specified value. - @param s Assigned scalar converted to the actual array type. - */ - Mat& operator = (const Scalar& s); - - /** @brief Sets all or some of the array elements to the specified value. - - This is an advanced variant of the Mat::operator=(const Scalar& s) operator. - @param value Assigned scalar converted to the actual array type. - @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix - elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels - */ - Mat& setTo(InputArray value, InputArray mask=noArray()); - - /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. - - The method makes a new matrix header for \*this elements. The new matrix may have a different size - and/or different number of channels. Any combination is possible if: - - No extra elements are included into the new matrix and no elements are excluded. Consequently, - the product rows\*cols\*channels() must stay the same after the transformation. - - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of - rows, or the operation changes the indices of elements row in some other way, the matrix must be - continuous. See Mat::isContinuous . - - For example, if there is a set of 3D points stored as an STL vector, and you want to represent the - points as a 3xN matrix, do the following: - @code - std::vector vec; - ... - Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation - reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. - // Also, an O(1) operation - t(); // finally, transpose the Nx3 matrix. - // This involves copying all the elements - @endcode - 3-channel 2x2 matrix reshaped to 1-channel 4x3 matrix, each column has values from one of original channels: - @code - Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); - vector new_shape {4, 3}; - m = m.reshape(1, new_shape); - @endcode - or: - @code - Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); - const int new_shape[] = {4, 3}; - m = m.reshape(1, 2, new_shape); - @endcode - @param cn New number of channels. If the parameter is 0, the number of channels remains the same. - @param rows New number of rows. If the parameter is 0, the number of rows remains the same. - */ - Mat reshape(int cn, int rows=0) const; - - /** @overload - * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. - * @param newndims New number of dimentions. - * @param newsz Array with new matrix size by all dimentions. If some sizes are zero, - * the original sizes in those dimensions are presumed. - */ - Mat reshape(int cn, int newndims, const int* newsz) const; - - /** @overload - * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. - * @param newshape Vector with new matrix size by all dimentions. If some sizes are zero, - * the original sizes in those dimensions are presumed. - */ - Mat reshape(int cn, const std::vector& newshape) const; - - /** @brief Transposes a matrix. - - The method performs matrix transposition by means of matrix expressions. It does not perform the - actual transposition but returns a temporary matrix transposition object that can be further used as - a part of more complex matrix expressions or can be assigned to a matrix: - @code - Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; - Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) - @endcode - */ - MatExpr t() const; - - /** @brief Inverses a matrix. - - The method performs a matrix inversion by means of matrix expressions. This means that a temporary - matrix inversion object is returned by the method and can be used further as a part of more complex - matrix expressions or can be assigned to a matrix. - @param method Matrix inversion method. One of cv::DecompTypes - */ - MatExpr inv(int method=DECOMP_LU) const; - - /** @brief Performs an element-wise multiplication or division of the two matrices. - - The method returns a temporary object encoding per-element array multiplication, with optional - scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. - - Example: - @code - Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) - @endcode - @param m Another array of the same type and the same size as \*this, or a matrix expression. - @param scale Optional scale factor. - */ - MatExpr mul(InputArray m, double scale=1) const; - - /** @brief Computes a cross-product of two 3-element vectors. - - The method computes a cross-product of two 3-element vectors. The vectors must be 3-element - floating-point vectors of the same shape and size. The result is another 3-element vector of the - same shape and type as operands. - @param m Another cross-product operand. - */ - Mat cross(InputArray m) const; - - /** @brief Computes a dot-product of two vectors. - - The method computes a dot-product of two matrices. If the matrices are not single-column or - single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D - vectors. The vectors must have the same size and type. If the matrices have more than one channel, - the dot products from all the channels are summed together. - @param m another dot-product operand. - */ - double dot(InputArray m) const; - - /** @brief Returns a zero array of the specified size and type. - - The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant - array as a function parameter, part of a matrix expression, or as a matrix initializer: - @code - Mat A; - A = Mat::zeros(3, 3, CV_32F); - @endcode - In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. - Otherwise, the existing matrix A is filled with zeros. - @param rows Number of rows. - @param cols Number of columns. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr zeros(int rows, int cols, int type); - - /** @overload - @param size Alternative to the matrix size specification Size(cols, rows) . - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr zeros(Size size, int type); - - /** @overload - @param ndims Array dimensionality. - @param sz Array of integers specifying the array shape. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr zeros(int ndims, const int* sz, int type); - - /** @brief Returns an array of all 1's of the specified size and type. - - The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using - this method you can initialize an array with an arbitrary value, using the following Matlab idiom: - @code - Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. - @endcode - The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it - just remembers the scale factor (3 in this case) and use it when actually invoking the matrix - initializer. - @note In case of multi-channels type, only the first channel will be initialized with 1's, the - others will be set to 0's. - @param rows Number of rows. - @param cols Number of columns. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr ones(int rows, int cols, int type); - - /** @overload - @param size Alternative to the matrix size specification Size(cols, rows) . - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr ones(Size size, int type); - - /** @overload - @param ndims Array dimensionality. - @param sz Array of integers specifying the array shape. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr ones(int ndims, const int* sz, int type); - - /** @brief Returns an identity matrix of the specified size and type. - - The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to - Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: - @code - // make a 4x4 diagonal matrix with 0.1's on the diagonal. - Mat A = Mat::eye(4, 4, CV_32F)*0.1; - @endcode - @note In case of multi-channels type, identity matrix will be initialized only for the first channel, - the others will be set to 0's - @param rows Number of rows. - @param cols Number of columns. - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr eye(int rows, int cols, int type); - - /** @overload - @param size Alternative matrix size specification as Size(cols, rows) . - @param type Created matrix type. - */ - CV_NODISCARD_STD static MatExpr eye(Size size, int type); - - /** @brief Allocates new array data if needed. - - This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays - call this method for each output array. The method uses the following algorithm: - - -# If the current array shape and the type match the new ones, return immediately. Otherwise, - de-reference the previous data by calling Mat::release. - -# Initialize the new header. - -# Allocate the new data of total()\*elemSize() bytes. - -# Allocate the new, associated with the data, reference counter and set it to 1. - - Such a scheme makes the memory management robust and efficient at the same time and helps avoid - extra typing for you. This means that usually there is no need to explicitly allocate output arrays. - That is, instead of writing: - @code - Mat color; - ... - Mat gray(color.rows, color.cols, color.depth()); - cvtColor(color, gray, COLOR_BGR2GRAY); - @endcode - you can simply write: - @code - Mat color; - ... - Mat gray; - cvtColor(color, gray, COLOR_BGR2GRAY); - @endcode - because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array - internally. - @param rows New number of rows. - @param cols New number of columns. - @param type New matrix type. - */ - void create(int rows, int cols, int type); - - /** @overload - @param size Alternative new matrix size specification: Size(cols, rows) - @param type New matrix type. - */ - void create(Size size, int type); - - /** @overload - @param ndims New array dimensionality. - @param sizes Array of integers specifying a new array shape. - @param type New matrix type. - */ - void create(int ndims, const int* sizes, int type); - - /** @overload - @param sizes Array of integers specifying a new array shape. - @param type New matrix type. - */ - void create(const std::vector& sizes, int type); - - /** @brief Increments the reference counter. - - The method increments the reference counter associated with the matrix data. If the matrix header - points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no - effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It - is called implicitly by the matrix assignment operator. The reference counter increment is an atomic - operation on the platforms that support it. Thus, it is safe to operate on the same matrices - asynchronously in different threads. - */ - void addref(); - - /** @brief Decrements the reference counter and deallocates the matrix if needed. - - The method decrements the reference counter associated with the matrix data. When the reference - counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers - are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the - reference counter is NULL, and the method has no effect in this case. - - This method can be called manually to force the matrix data deallocation. But since this method is - automatically called in the destructor, or by any other method that changes the data pointer, it is - usually not needed. The reference counter decrement and check for 0 is an atomic operation on the - platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in - different threads. - */ - void release(); - - //! internal use function, consider to use 'release' method instead; deallocates the matrix data - void deallocate(); - //! internal use function; properly re-allocates _size, _step arrays - void copySize(const Mat& m); - - /** @brief Reserves space for the certain number of rows. - - The method reserves space for sz rows. If the matrix already has enough space to store sz rows, - nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method - emulates the corresponding method of the STL vector class. - @param sz Number of rows. - */ - void reserve(size_t sz); - - /** @brief Reserves space for the certain number of bytes. - - The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, - nothing happens. If matrix has to be reallocated its previous content could be lost. - @param sz Number of bytes. - */ - void reserveBuffer(size_t sz); - - /** @brief Changes the number of matrix rows. - - The methods change the number of matrix rows. If the matrix is reallocated, the first - min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL - vector class. - @param sz New number of rows. - */ - void resize(size_t sz); - - /** @overload - @param sz New number of rows. - @param s Value assigned to the newly added elements. - */ - void resize(size_t sz, const Scalar& s); - - //! internal function - void push_back_(const void* elem); - - /** @brief Adds elements to the bottom of the matrix. - - The methods add one or more elements to the bottom of the matrix. They emulate the corresponding - method of the STL vector class. When elem is Mat , its type and the number of columns must be the - same as in the container matrix. - @param elem Added element(s). - */ - template void push_back(const _Tp& elem); - - /** @overload - @param elem Added element(s). - */ - template void push_back(const Mat_<_Tp>& elem); - - /** @overload - @param elem Added element(s). - */ - template void push_back(const std::vector<_Tp>& elem); - - /** @overload - @param m Added line(s). - */ - void push_back(const Mat& m); - - /** @brief Removes elements from the bottom of the matrix. - - The method removes one or more rows from the bottom of the matrix. - @param nelems Number of removed rows. If it is greater than the total number of rows, an exception - is thrown. - */ - void pop_back(size_t nelems=1); - - /** @brief Locates the matrix header within a parent matrix. - - After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, - Mat::colRange, and others, the resultant submatrix points just to the part of the original big - matrix. However, each submatrix contains information (represented by datastart and dataend - fields) that helps reconstruct the original matrix size and the position of the extracted - submatrix within the original matrix. The method locateROI does exactly that. - @param wholeSize Output parameter that contains the size of the whole matrix containing *this* - as a part. - @param ofs Output parameter that contains an offset of *this* inside the whole matrix. - */ - void locateROI( Size& wholeSize, Point& ofs ) const; - - /** @brief Adjusts a submatrix size and position within the parent matrix. - - The method is complimentary to Mat::locateROI . The typical use of these functions is to determine - the submatrix position within the parent matrix and then shift the position somehow. Typically, it - can be required for filtering operations when pixels outside of the ROI should be taken into - account. When all the method parameters are positive, the ROI needs to grow in all directions by the - specified amount, for example: - @code - A.adjustROI(2, 2, 2, 2); - @endcode - In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted - by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the - filtering with the 5x5 kernel. - - adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the - adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is - located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not - be increased in the upward direction. - - The function is used internally by the OpenCV filtering functions, like filter2D , morphological - operations, and so on. - @param dtop Shift of the top submatrix boundary upwards. - @param dbottom Shift of the bottom submatrix boundary downwards. - @param dleft Shift of the left submatrix boundary to the left. - @param dright Shift of the right submatrix boundary to the right. - @sa copyMakeBorder - */ - Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - - /** @brief Extracts a rectangular submatrix. - - The operators make a new header for the specified sub-array of \*this . They are the most - generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, - `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, - the operators are O(1) operations, that is, no matrix data is copied. - @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To - select all the rows, use Range::all(). - @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. - To select all the columns, use Range::all(). - */ - Mat operator()( Range rowRange, Range colRange ) const; - - /** @overload - @param roi Extracted submatrix specified as a rectangle. - */ - Mat operator()( const Rect& roi ) const; - - /** @overload - @param ranges Array of selected ranges along each array dimension. - */ - Mat operator()( const Range* ranges ) const; - - /** @overload - @param ranges Array of selected ranges along each array dimension. - */ - Mat operator()(const std::vector& ranges) const; - - template operator std::vector<_Tp>() const; - template operator Vec<_Tp, n>() const; - template operator Matx<_Tp, m, n>() const; - - template operator std::array<_Tp, _Nm>() const; - - /** @brief Reports whether the matrix is continuous or not. - - The method returns true if the matrix elements are stored continuously without gaps at the end of - each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. - Matrices created with Mat::create are always continuous. But if you extract a part of the matrix - using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, - such matrices may no longer have this property. - - The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when - you construct a matrix header. Thus, the continuity check is a very fast operation, though - theoretically it could be done as follows: - @code - // alternative implementation of Mat::isContinuous() - bool myCheckMatContinuity(const Mat& m) - { - //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; - return m.rows == 1 || m.step == m.cols*m.elemSize(); - } - @endcode - The method is used in quite a few of OpenCV functions. The point is that element-wise operations - (such as arithmetic and logical operations, math functions, alpha blending, color space - transformations, and others) do not depend on the image geometry. Thus, if all the input and output - arrays are continuous, the functions can process them as very long single-row vectors. The example - below illustrates how an alpha-blending function can be implemented: - @code - template - void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) - { - const float alpha_scale = (float)std::numeric_limits::max(), - inv_scale = 1.f/alpha_scale; - - CV_Assert( src1.type() == src2.type() && - src1.type() == CV_MAKETYPE(traits::Depth::value, 4) && - src1.size() == src2.size()); - Size size = src1.size(); - dst.create(size, src1.type()); - - // here is the idiom: check the arrays for continuity and, - // if this is the case, - // treat the arrays as 1D vectors - if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) - { - size.width *= size.height; - size.height = 1; - } - size.width *= 4; - - for( int i = 0; i < size.height; i++ ) - { - // when the arrays are continuous, - // the outer loop is executed only once - const T* ptr1 = src1.ptr(i); - const T* ptr2 = src2.ptr(i); - T* dptr = dst.ptr(i); - - for( int j = 0; j < size.width; j += 4 ) - { - float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; - dptr[j] = saturate_cast(ptr1[j]*alpha + ptr2[j]*beta); - dptr[j+1] = saturate_cast(ptr1[j+1]*alpha + ptr2[j+1]*beta); - dptr[j+2] = saturate_cast(ptr1[j+2]*alpha + ptr2[j+2]*beta); - dptr[j+3] = saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale); - } - } - } - @endcode - This approach, while being very simple, can boost the performance of a simple element-operation by - 10-20 percents, especially if the image is rather small and the operation is quite simple. - - Another OpenCV idiom in this function, a call of Mat::create for the destination array, that - allocates the destination array unless it already has the proper size and type. And while the newly - allocated arrays are always continuous, you still need to check the destination array because - Mat::create does not always allocate a new matrix. - */ - bool isContinuous() const; - - //! returns true if the matrix is a submatrix of another matrix - bool isSubmatrix() const; - - /** @brief Returns the matrix element size in bytes. - - The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , - the method returns 3\*sizeof(short) or 6. - */ - size_t elemSize() const; - - /** @brief Returns the size of each matrix element channel in bytes. - - The method returns the matrix element channel size in bytes, that is, it ignores the number of - channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. - */ - size_t elemSize1() const; - - /** @brief Returns the type of a matrix element. - - The method returns a matrix element type. This is an identifier compatible with the CvMat type - system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. - */ - int type() const; - - /** @brief Returns the depth of a matrix element. - - The method returns the identifier of the matrix element depth (the type of each individual channel). - For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of - matrix types contains the following values: - - CV_8U - 8-bit unsigned integers ( 0..255 ) - - CV_8S - 8-bit signed integers ( -128..127 ) - - CV_16U - 16-bit unsigned integers ( 0..65535 ) - - CV_16S - 16-bit signed integers ( -32768..32767 ) - - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) - */ - int depth() const; - - /** @brief Returns the number of matrix channels. - - The method returns the number of matrix channels. - */ - int channels() const; - - /** @brief Returns a normalized step. - - The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an - arbitrary matrix element. - */ - size_t step1(int i=0) const; - - /** @brief Returns true if the array has no elements. - - The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and - resize() methods `M.total() == 0` does not imply that `M.data == NULL`. - */ - bool empty() const; - - /** @brief Returns the total number of array elements. - - The method returns the number of array elements (a number of pixels if the array represents an - image). - */ - size_t total() const; - - /** @brief Returns the total number of array elements. - - The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim - */ - size_t total(int startDim, int endDim=INT_MAX) const; - - /** - * @param elemChannels Number of channels or number of columns the matrix should have. - * For a 2-D matrix, when the matrix has only 1 column, then it should have - * elemChannels channels; When the matrix has only 1 channel, - * then it should have elemChannels columns. - * For a 3-D matrix, it should have only one channel. Furthermore, - * if the number of planes is not one, then the number of rows - * within every plane has to be 1; if the number of rows within - * every plane is not 1, then the number of planes has to be 1. - * @param depth The depth the matrix should have. Set it to -1 when any depth is fine. - * @param requireContinuous Set it to true to require the matrix to be continuous - * @return -1 if the requirement is not satisfied. - * Otherwise, it returns the number of elements in the matrix. Note - * that an element may have multiple channels. - * - * The following code demonstrates its usage for a 2-d matrix: - * @snippet snippets/core_mat_checkVector.cpp example-2d - * - * The following code demonstrates its usage for a 3-d matrix: - * @snippet snippets/core_mat_checkVector.cpp example-3d - */ - int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; - - /** @brief Returns a pointer to the specified matrix row. - - The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in - Mat::isContinuous to know how to use these methods. - @param i0 A 0-based row index. - */ - uchar* ptr(int i0=0); - /** @overload */ - const uchar* ptr(int i0=0) const; - - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - uchar* ptr(int row, int col); - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - const uchar* ptr(int row, int col) const; - - /** @overload */ - uchar* ptr(int i0, int i1, int i2); - /** @overload */ - const uchar* ptr(int i0, int i1, int i2) const; - - /** @overload */ - uchar* ptr(const int* idx); - /** @overload */ - const uchar* ptr(const int* idx) const; - /** @overload */ - template uchar* ptr(const Vec& idx); - /** @overload */ - template const uchar* ptr(const Vec& idx) const; - - /** @overload */ - template _Tp* ptr(int i0=0); - /** @overload */ - template const _Tp* ptr(int i0=0) const; - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template _Tp* ptr(int row, int col); - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template const _Tp* ptr(int row, int col) const; - /** @overload */ - template _Tp* ptr(int i0, int i1, int i2); - /** @overload */ - template const _Tp* ptr(int i0, int i1, int i2) const; - /** @overload */ - template _Tp* ptr(const int* idx); - /** @overload */ - template const _Tp* ptr(const int* idx) const; - /** @overload */ - template _Tp* ptr(const Vec& idx); - /** @overload */ - template const _Tp* ptr(const Vec& idx) const; - - /** @brief Returns a reference to the specified array element. - - The template methods return a reference to the specified array element. For the sake of higher - performance, the index range checks are only performed in the Debug configuration. - - Note that the variants with a single index (i) can be used to access elements of single-row or - single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and - B is an M x 1 integer matrix, you can simply write `A.at(k+4)` and `B.at(2*i+1)` - instead of `A.at(0,k+4)` and `B.at(2*i+1,0)`, respectively. - - The example below initializes a Hilbert matrix: - @code - Mat H(100, 100, CV_64F); - for(int i = 0; i < H.rows; i++) - for(int j = 0; j < H.cols; j++) - H.at(i,j)=1./(i+j+1); - @endcode - - Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends - on the image from which you are trying to retrieve the data. The table below gives a better insight in this: - - If matrix is of type `CV_8U` then use `Mat.at(y,x)`. - - If matrix is of type `CV_8S` then use `Mat.at(y,x)`. - - If matrix is of type `CV_16U` then use `Mat.at(y,x)`. - - If matrix is of type `CV_16S` then use `Mat.at(y,x)`. - - If matrix is of type `CV_32S` then use `Mat.at(y,x)`. - - If matrix is of type `CV_32F` then use `Mat.at(y,x)`. - - If matrix is of type `CV_64F` then use `Mat.at(y,x)`. - - @param i0 Index along the dimension 0 - */ - template _Tp& at(int i0=0); - /** @overload - @param i0 Index along the dimension 0 - */ - template const _Tp& at(int i0=0) const; - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template _Tp& at(int row, int col); - /** @overload - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - template const _Tp& at(int row, int col) const; - - /** @overload - @param i0 Index along the dimension 0 - @param i1 Index along the dimension 1 - @param i2 Index along the dimension 2 - */ - template _Tp& at(int i0, int i1, int i2); - /** @overload - @param i0 Index along the dimension 0 - @param i1 Index along the dimension 1 - @param i2 Index along the dimension 2 - */ - template const _Tp& at(int i0, int i1, int i2) const; - - /** @overload - @param idx Array of Mat::dims indices. - */ - template _Tp& at(const int* idx); - /** @overload - @param idx Array of Mat::dims indices. - */ - template const _Tp& at(const int* idx) const; - - /** @overload */ - template _Tp& at(const Vec& idx); - /** @overload */ - template const _Tp& at(const Vec& idx) const; - - /** @overload - special versions for 2D arrays (especially convenient for referencing image pixels) - @param pt Element position specified as Point(j,i) . - */ - template _Tp& at(Point pt); - /** @overload - special versions for 2D arrays (especially convenient for referencing image pixels) - @param pt Element position specified as Point(j,i) . - */ - template const _Tp& at(Point pt) const; - - /** @brief Returns the matrix iterator and sets it to the first matrix element. - - The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very - similar to the use of bi-directional STL iterators. In the example below, the alpha blending - function is rewritten using the matrix iterators: - @code - template - void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) - { - typedef Vec VT; - - const float alpha_scale = (float)std::numeric_limits::max(), - inv_scale = 1.f/alpha_scale; - - CV_Assert( src1.type() == src2.type() && - src1.type() == traits::Type::value && - src1.size() == src2.size()); - Size size = src1.size(); - dst.create(size, src1.type()); - - MatConstIterator_ it1 = src1.begin(), it1_end = src1.end(); - MatConstIterator_ it2 = src2.begin(); - MatIterator_ dst_it = dst.begin(); - - for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) - { - VT pix1 = *it1, pix2 = *it2; - float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; - *dst_it = VT(saturate_cast(pix1[0]*alpha + pix2[0]*beta), - saturate_cast(pix1[1]*alpha + pix2[1]*beta), - saturate_cast(pix1[2]*alpha + pix2[2]*beta), - saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale)); - } - } - @endcode - */ - template MatIterator_<_Tp> begin(); - template MatConstIterator_<_Tp> begin() const; - - /** @brief Same as begin() but for inverse traversal - */ - template std::reverse_iterator> rbegin(); - template std::reverse_iterator> rbegin() const; - - /** @brief Returns the matrix iterator and sets it to the after-last matrix element. - - The methods return the matrix read-only or read-write iterators, set to the point following the last - matrix element. - */ - template MatIterator_<_Tp> end(); - template MatConstIterator_<_Tp> end() const; - - /** @brief Same as end() but for inverse traversal - */ - template std::reverse_iterator< MatIterator_<_Tp>> rend(); - template std::reverse_iterator< MatConstIterator_<_Tp>> rend() const; - - - /** @brief Runs the given functor over all matrix elements in parallel. - - The operation passed as argument has to be a function pointer, a function object or a lambda(C++11). - - Example 1. All of the operations below put 0xFF the first channel of all matrix elements: - @code - Mat image(1920, 1080, CV_8UC3); - typedef cv::Point3_ Pixel; - - // first. raw pointer access. - for (int r = 0; r < image.rows; ++r) { - Pixel* ptr = image.ptr(r, 0); - const Pixel* ptr_end = ptr + image.cols; - for (; ptr != ptr_end; ++ptr) { - ptr->x = 255; - } - } - - // Using MatIterator. (Simple but there are a Iterator's overhead) - for (Pixel &p : cv::Mat_(image)) { - p.x = 255; - } - - // Parallel execution with function object. - struct Operator { - void operator ()(Pixel &pixel, const int * position) { - pixel.x = 255; - } - }; - image.forEach(Operator()); - - // Parallel execution using C++11 lambda. - image.forEach([](Pixel &p, const int * position) -> void { - p.x = 255; - }); - @endcode - Example 2. Using the pixel's position: - @code - // Creating 3D matrix (255 x 255 x 255) typed uint8_t - // and initialize all elements by the value which equals elements position. - // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). - - int sizes[] = { 255, 255, 255 }; - typedef cv::Point3_ Pixel; - - Mat_ image = Mat::zeros(3, sizes, CV_8UC3); - - image.forEach([](Pixel& pixel, const int position[]) -> void { - pixel.x = position[0]; - pixel.y = position[1]; - pixel.z = position[2]; - }); - @endcode - */ - template void forEach(const Functor& operation); - /** @overload */ - template void forEach(const Functor& operation) const; - - Mat(Mat&& m) CV_NOEXCEPT; - Mat& operator = (Mat&& m); - - enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; - enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - //! the matrix dimensionality, >= 2 - int dims; - //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions - int rows, cols; - //! pointer to the data - uchar* data; - - //! helper fields used in locateROI and adjustROI - const uchar* datastart; - const uchar* dataend; - const uchar* datalimit; - - //! custom allocator - MatAllocator* allocator; - //! and the standard allocator - static MatAllocator* getStdAllocator(); - static MatAllocator* getDefaultAllocator(); - static void setDefaultAllocator(MatAllocator* allocator); - - //! internal use method: updates the continuity flag - void updateContinuityFlag(); - - //! interaction with UMat - UMatData* u; - - MatSize size; - MatStep step; - -protected: - template void forEach_impl(const Functor& operation); -}; - - -///////////////////////////////// Mat_<_Tp> //////////////////////////////////// - -/** @brief Template matrix class derived from Mat - -@code{.cpp} - template class Mat_ : public Mat - { - public: - // ... some specific methods - // and - // no new extra fields - }; -@endcode -The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any -extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to -these two classes can be freely but carefully converted one to another. For example: -@code{.cpp} - // create a 100x100 8-bit matrix - Mat M(100,100,CV_8U); - // this will be compiled fine. no any data conversion will be done. - Mat_& M1 = (Mat_&)M; - // the program is likely to crash at the statement below - M1(99,99) = 1.f; -@endcode -While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element -access operations and if you know matrix type at the compilation time. Note that -`Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same -and run at the same speed, but the latter is certainly shorter: -@code{.cpp} - Mat_ M(20,20); - for(int i = 0; i < M.rows; i++) - for(int j = 0; j < M.cols; j++) - M(i,j) = 1./(i+j+1); - Mat E, V; - eigen(M,E,V); - cout << E.at(0,0)/E.at(M.rows-1,0); -@endcode -To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: -@code{.cpp} - // allocate a 320x240 color image and fill it with green (in RGB space) - Mat_ img(240, 320, Vec3b(0,255,0)); - // now draw a diagonal white line - for(int i = 0; i < 100; i++) - img(i,i)=Vec3b(255,255,255); - // and now scramble the 2nd (red) channel of each pixel - for(int i = 0; i < img.rows; i++) - for(int j = 0; j < img.cols; j++) - img(i,j)[2] ^= (uchar)(i ^ j); -@endcode -Mat_ is fully compatible with C++11 range-based for loop. For example such loop -can be used to safely apply look-up table: -@code{.cpp} -void applyTable(Mat_& I, const uchar* const table) -{ - for(auto& pixel : I) - { - pixel = table[pixel]; - } -} -@endcode - */ -template class Mat_ : public Mat -{ -public: - typedef _Tp value_type; - typedef typename DataType<_Tp>::channel_type channel_type; - typedef MatIterator_<_Tp> iterator; - typedef MatConstIterator_<_Tp> const_iterator; - - //! default constructor - Mat_() CV_NOEXCEPT; - //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) - Mat_(int _rows, int _cols); - //! constructor that sets each matrix element to specified value - Mat_(int _rows, int _cols, const _Tp& value); - //! equivalent to Mat(_size, DataType<_Tp>::type) - explicit Mat_(Size _size); - //! constructor that sets each matrix element to specified value - Mat_(Size _size, const _Tp& value); - //! n-dim array constructor - Mat_(int _ndims, const int* _sizes); - //! n-dim array constructor that sets each matrix element to specified value - Mat_(int _ndims, const int* _sizes, const _Tp& value); - //! copy/conversion constructor. If m is of different type, it's converted - Mat_(const Mat& m); - //! copy constructor - Mat_(const Mat_& m); - //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type - Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); - //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type - Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); - //! selects a submatrix - Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); - //! selects a submatrix - Mat_(const Mat_& m, const Rect& roi); - //! selects a submatrix, n-dim version - Mat_(const Mat_& m, const Range* ranges); - //! selects a submatrix, n-dim version - Mat_(const Mat_& m, const std::vector& ranges); - //! from a matrix expression - explicit Mat_(const MatExpr& e); - //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column - explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); - template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); - template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); - explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); - explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); - explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); - - Mat_(std::initializer_list<_Tp> values); - explicit Mat_(const std::initializer_list sizes, const std::initializer_list<_Tp> values); - - template explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false); - - Mat_& operator = (const Mat& m); - Mat_& operator = (const Mat_& m); - //! set all the elements to s. - Mat_& operator = (const _Tp& s); - //! assign a matrix expression - Mat_& operator = (const MatExpr& e); - - //! iterators; they are smart enough to skip gaps in the end of rows - iterator begin(); - iterator end(); - const_iterator begin() const; - const_iterator end() const; - - //reverse iterators - std::reverse_iterator rbegin(); - std::reverse_iterator rend(); - std::reverse_iterator rbegin() const; - std::reverse_iterator rend() const; - - //! template methods for operation over all matrix elements. - // the operations take care of skipping gaps in the end of rows (if any) - template void forEach(const Functor& operation); - template void forEach(const Functor& operation) const; - - //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) - void create(int _rows, int _cols); - //! equivalent to Mat::create(_size, DataType<_Tp>::type) - void create(Size _size); - //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) - void create(int _ndims, const int* _sizes); - //! equivalent to Mat::release() - void release(); - //! cross-product - Mat_ cross(const Mat_& m) const; - //! data type conversion - template operator Mat_() const; - //! overridden forms of Mat::row() etc. - Mat_ row(int y) const; - Mat_ col(int x) const; - Mat_ diag(int d=0) const; - CV_NODISCARD_STD Mat_ clone() const; - - //! overridden forms of Mat::elemSize() etc. - size_t elemSize() const; - size_t elemSize1() const; - int type() const; - int depth() const; - int channels() const; - size_t step1(int i=0) const; - //! returns step()/sizeof(_Tp) - size_t stepT(int i=0) const; - - //! overridden forms of Mat::zeros() etc. Data type is omitted, of course - CV_NODISCARD_STD static MatExpr zeros(int rows, int cols); - CV_NODISCARD_STD static MatExpr zeros(Size size); - CV_NODISCARD_STD static MatExpr zeros(int _ndims, const int* _sizes); - CV_NODISCARD_STD static MatExpr ones(int rows, int cols); - CV_NODISCARD_STD static MatExpr ones(Size size); - CV_NODISCARD_STD static MatExpr ones(int _ndims, const int* _sizes); - CV_NODISCARD_STD static MatExpr eye(int rows, int cols); - CV_NODISCARD_STD static MatExpr eye(Size size); - - //! some more overridden methods - Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); - Mat_ operator()( const Range& rowRange, const Range& colRange ) const; - Mat_ operator()( const Rect& roi ) const; - Mat_ operator()( const Range* ranges ) const; - Mat_ operator()(const std::vector& ranges) const; - - //! more convenient forms of row and element access operators - _Tp* operator [](int y); - const _Tp* operator [](int y) const; - - //! returns reference to the specified element - _Tp& operator ()(const int* idx); - //! returns read-only reference to the specified element - const _Tp& operator ()(const int* idx) const; - - //! returns reference to the specified element - template _Tp& operator ()(const Vec& idx); - //! returns read-only reference to the specified element - template const _Tp& operator ()(const Vec& idx) const; - - //! returns reference to the specified element (1D case) - _Tp& operator ()(int idx0); - //! returns read-only reference to the specified element (1D case) - const _Tp& operator ()(int idx0) const; - //! returns reference to the specified element (2D case) - _Tp& operator ()(int row, int col); - //! returns read-only reference to the specified element (2D case) - const _Tp& operator ()(int row, int col) const; - //! returns reference to the specified element (3D case) - _Tp& operator ()(int idx0, int idx1, int idx2); - //! returns read-only reference to the specified element (3D case) - const _Tp& operator ()(int idx0, int idx1, int idx2) const; - - _Tp& operator ()(Point pt); - const _Tp& operator ()(Point pt) const; - - //! conversion to vector. - operator std::vector<_Tp>() const; - - //! conversion to array. - template operator std::array<_Tp, _Nm>() const; - - //! conversion to Vec - template operator Vec::channel_type, n>() const; - //! conversion to Matx - template operator Matx::channel_type, m, n>() const; - - Mat_(Mat_&& m); - Mat_& operator = (Mat_&& m); - - Mat_(Mat&& m); - Mat_& operator = (Mat&& m); - - Mat_(MatExpr&& e); -}; - -typedef Mat_ Mat1b; -typedef Mat_ Mat2b; -typedef Mat_ Mat3b; -typedef Mat_ Mat4b; - -typedef Mat_ Mat1s; -typedef Mat_ Mat2s; -typedef Mat_ Mat3s; -typedef Mat_ Mat4s; - -typedef Mat_ Mat1w; -typedef Mat_ Mat2w; -typedef Mat_ Mat3w; -typedef Mat_ Mat4w; - -typedef Mat_ Mat1i; -typedef Mat_ Mat2i; -typedef Mat_ Mat3i; -typedef Mat_ Mat4i; - -typedef Mat_ Mat1f; -typedef Mat_ Mat2f; -typedef Mat_ Mat3f; -typedef Mat_ Mat4f; - -typedef Mat_ Mat1d; -typedef Mat_ Mat2d; -typedef Mat_ Mat3d; -typedef Mat_ Mat4d; - -/** @todo document */ -class CV_EXPORTS UMat -{ -public: - //! default constructor - UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT) CV_NOEXCEPT; - //! constructs 2D matrix of the specified size and type - // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) - UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - //! constructs 2D matrix and fills it with the specified value _s. - UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); - UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); - - //! constructs n-dimensional matrix - UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); - - //! copy constructor - UMat(const UMat& m); - - //! creates a matrix header for a part of the bigger matrix - UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); - UMat(const UMat& m, const Rect& roi); - UMat(const UMat& m, const Range* ranges); - UMat(const UMat& m, const std::vector& ranges); - - // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0) - //! builds matrix from std::vector with or without copying the data - template explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); - - //! destructor - calls release() - ~UMat(); - //! assignment operators - UMat& operator = (const UMat& m); - - Mat getMat(AccessFlag flags) const; - - //! returns a new matrix header for the specified row - UMat row(int y) const; - //! returns a new matrix header for the specified column - UMat col(int x) const; - //! ... for the specified row span - UMat rowRange(int startrow, int endrow) const; - UMat rowRange(const Range& r) const; - //! ... for the specified column span - UMat colRange(int startcol, int endcol) const; - UMat colRange(const Range& r) const; - //! ... for the specified diagonal - //! (d=0 - the main diagonal, - //! >0 - a diagonal from the upper half, - //! <0 - a diagonal from the lower half) - UMat diag(int d=0) const; - //! constructs a square diagonal matrix which main diagonal is vector "d" - CV_NODISCARD_STD static UMat diag(const UMat& d, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat diag(const UMat& d) { return diag(d, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - - //! returns deep copy of the matrix, i.e. the data is copied - CV_NODISCARD_STD UMat clone() const; - //! copies the matrix content to "m". - // It calls m.create(this->size(), this->type()). - void copyTo( OutputArray m ) const; - //! copies those matrix elements to "m" that are marked with non-zero mask elements. - void copyTo( OutputArray m, InputArray mask ) const; - //! converts matrix to another datatype with optional scaling. See cvConvertScale. - void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; - - void assignTo( UMat& m, int type=-1 ) const; - - //! sets every matrix element to s - UMat& operator = (const Scalar& s); - //! sets some of the matrix elements to s, according to the mask - UMat& setTo(InputArray value, InputArray mask=noArray()); - //! creates alternative matrix header for the same data, with different - // number of channels and/or different number of rows. see cvReshape. - UMat reshape(int cn, int rows=0) const; - UMat reshape(int cn, int newndims, const int* newsz) const; - - //! matrix transposition by means of matrix expressions - UMat t() const; - //! matrix inversion by means of matrix expressions - UMat inv(int method=DECOMP_LU) const; - //! per-element matrix multiplication by means of matrix expressions - UMat mul(InputArray m, double scale=1) const; - - //! computes dot-product - double dot(InputArray m) const; - - //! Matlab-style matrix initialization - CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat zeros(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type) { return zeros(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat zeros(Size size, int type) { return zeros(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type) { return zeros(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat ones(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat ones(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat ones(int rows, int cols, int type) { return ones(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat ones(Size size, int type) { return ones(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type) { return ones(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat eye(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat eye(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); - CV_NODISCARD_STD static UMat eye(int rows, int cols, int type) { return eye(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - CV_NODISCARD_STD static UMat eye(Size size, int type) { return eye(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload - - //! allocates new matrix data unless the matrix already has specified size and type. - // previous data is unreferenced if needed. - void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - void create(const std::vector& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); - - //! increases the reference counter; use with care to avoid memleaks - void addref(); - //! decreases reference counter; - // deallocates the data when reference counter reaches 0. - void release(); - - //! deallocates the matrix data - void deallocate(); - //! internal use function; properly re-allocates _size, _step arrays - void copySize(const UMat& m); - - //! locates matrix header within a parent matrix. See below - void locateROI( Size& wholeSize, Point& ofs ) const; - //! moves/resizes the current matrix ROI inside the parent matrix. - UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); - //! extracts a rectangular sub-matrix - // (this is a generalized form of row, rowRange etc.) - UMat operator()( Range rowRange, Range colRange ) const; - UMat operator()( const Rect& roi ) const; - UMat operator()( const Range* ranges ) const; - UMat operator()(const std::vector& ranges) const; - - //! returns true iff the matrix data is continuous - // (i.e. when there are no gaps between successive rows). - // similar to CV_IS_MAT_CONT(cvmat->type) - bool isContinuous() const; - - //! returns true if the matrix is a submatrix of another matrix - bool isSubmatrix() const; - - //! returns element size in bytes, - // similar to CV_ELEM_SIZE(cvmat->type) - size_t elemSize() const; - //! returns the size of element channel in bytes. - size_t elemSize1() const; - //! returns element type, similar to CV_MAT_TYPE(cvmat->type) - int type() const; - //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) - int depth() const; - //! returns element type, similar to CV_MAT_CN(cvmat->type) - int channels() const; - //! returns step/elemSize1() - size_t step1(int i=0) const; - //! returns true if matrix data is NULL - bool empty() const; - //! returns the total number of matrix elements - size_t total() const; - - //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise - int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; - - UMat(UMat&& m); - UMat& operator = (UMat&& m); - - /*! Returns the OpenCL buffer handle on which UMat operates on. - The UMat instance should be kept alive during the use of the handle to prevent the buffer to be - returned to the OpenCV buffer pool. - */ - void* handle(AccessFlag accessFlags) const; - void ndoffset(size_t* ofs) const; - - enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; - enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; - - /*! includes several bit-fields: - - the magic signature - - continuity flag - - depth - - number of channels - */ - int flags; - - //! the matrix dimensionality, >= 2 - int dims; - - //! number of rows in the matrix; -1 when the matrix has more than 2 dimensions - int rows; - - //! number of columns in the matrix; -1 when the matrix has more than 2 dimensions - int cols; - - //! custom allocator - MatAllocator* allocator; - - //! usage flags for allocator; recommend do not set directly, instead set during construct/create/getUMat - UMatUsageFlags usageFlags; - - //! and the standard allocator - static MatAllocator* getStdAllocator(); - - //! internal use method: updates the continuity flag - void updateContinuityFlag(); - - //! black-box container of UMat data - UMatData* u; - - //! offset of the submatrix (or 0) - size_t offset; - - //! dimensional size of the matrix; accessible in various formats - MatSize size; - - //! number of bytes each matrix element/row/plane/dimension occupies - MatStep step; - -protected: -}; - - -/////////////////////////// multi-dimensional sparse matrix ////////////////////////// - -/** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. - -Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only -non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its -stored elements can actually become 0. It is up to you to detect such elements and delete them -using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is -filled so that the search time is O(1) in average (regardless of whether element is there or not). -Elements can be accessed using the following methods: -- Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and - SparseMat::find), for example: - @code - const int dims = 5; - int size[5] = {10, 10, 10, 10, 10}; - SparseMat sparse_mat(dims, size, CV_32F); - for(int i = 0; i < 1000; i++) - { - int idx[dims]; - for(int k = 0; k < dims; k++) - idx[k] = rand() % size[k]; - sparse_mat.ref(idx) += 1.f; - } - cout << "nnz = " << sparse_mat.nzcount() << endl; - @endcode -- Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. - That is, the iteration loop is familiar to STL users: - @code - // prints elements of a sparse floating-point matrix - // and the sum of elements. - SparseMatConstIterator_ - it = sparse_mat.begin(), - it_end = sparse_mat.end(); - double s = 0; - int dims = sparse_mat.dims(); - for(; it != it_end; ++it) - { - // print element indices and the element value - const SparseMat::Node* n = it.node(); - printf("("); - for(int i = 0; i < dims; i++) - printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); - printf(": %g\n", it.value()); - s += *it; - } - printf("Element sum is %g\n", s); - @endcode - If you run this loop, you will notice that elements are not enumerated in a logical order - (lexicographical, and so on). They come in the same order as they are stored in the hash table - (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. - Note, however, that pointers to the nodes may become invalid when you add more elements to the - matrix. This may happen due to possible buffer reallocation. -- Combination of the above 2 methods when you need to process 2 or more sparse matrices - simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 - floating-point sparse matrices: - @code - double cross_corr(const SparseMat& a, const SparseMat& b) - { - const SparseMat *_a = &a, *_b = &b; - // if b contains less elements than a, - // it is faster to iterate through b - if(_a->nzcount() > _b->nzcount()) - std::swap(_a, _b); - SparseMatConstIterator_ it = _a->begin(), - it_end = _a->end(); - double ccorr = 0; - for(; it != it_end; ++it) - { - // take the next element from the first matrix - float avalue = *it; - const Node* anode = it.node(); - // and try to find an element with the same index in the second matrix. - // since the hash value depends only on the element index, - // reuse the hash value stored in the node - float bvalue = _b->value(anode->idx,&anode->hashval); - ccorr += avalue*bvalue; - } - return ccorr; - } - @endcode - */ -class CV_EXPORTS SparseMat -{ -public: - typedef SparseMatIterator iterator; - typedef SparseMatConstIterator const_iterator; - - enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; - - //! the sparse matrix header - struct CV_EXPORTS Hdr - { - Hdr(int _dims, const int* _sizes, int _type); - void clear(); - int refcount; - int dims; - int valueOffset; - size_t nodeSize; - size_t nodeCount; - size_t freeList; - std::vector pool; - std::vector hashtab; - int size[MAX_DIM]; - }; - - //! sparse matrix node - element of a hash table - struct CV_EXPORTS Node - { - //! hash value - size_t hashval; - //! index of the next node in the same hash table entry - size_t next; - //! index of the matrix element - int idx[MAX_DIM]; - }; - - /** @brief Various SparseMat constructors. - */ - SparseMat(); - - /** @overload - @param dims Array dimensionality. - @param _sizes Sparce matrix size on all dementions. - @param _type Sparse matrix data type. - */ - SparseMat(int dims, const int* _sizes, int _type); - - /** @overload - @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted - to sparse representation. - */ - SparseMat(const SparseMat& m); - - /** @overload - @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted - to sparse representation. - */ - explicit SparseMat(const Mat& m); - - //! the destructor - ~SparseMat(); - - //! assignment operator. This is O(1) operation, i.e. no data is copied - SparseMat& operator = (const SparseMat& m); - //! equivalent to the corresponding constructor - SparseMat& operator = (const Mat& m); - - //! creates full copy of the matrix - CV_NODISCARD_STD SparseMat clone() const; - - //! copies all the data to the destination matrix. All the previous content of m is erased - void copyTo( SparseMat& m ) const; - //! converts sparse matrix to dense matrix. - void copyTo( Mat& m ) const; - //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type - void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; - //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. - /*! - @param [out] m - output matrix; if it does not have a proper size or type before the operation, - it is reallocated - @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels - are the same as the input has; if rtype is negative, the output matrix will have the - same type as the input. - @param [in] alpha - optional scale factor - @param [in] beta - optional delta added to the scaled values - */ - void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; - - // not used now - void assignTo( SparseMat& m, int type=-1 ) const; - - //! reallocates sparse matrix. - /*! - If the matrix already had the proper size and type, - it is simply cleared with clear(), otherwise, - the old matrix is released (using release()) and the new one is allocated. - */ - void create(int dims, const int* _sizes, int _type); - //! sets all the sparse matrix elements to 0, which means clearing the hash table. - void clear(); - //! manually increments the reference counter to the header. - void addref(); - // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. - void release(); - - //! converts sparse matrix to the old-style representation; all the elements are copied. - //operator CvSparseMat*() const; - //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) - size_t elemSize() const; - //! returns elemSize()/channels() - size_t elemSize1() const; - - //! returns type of sparse matrix elements - int type() const; - //! returns the depth of sparse matrix elements - int depth() const; - //! returns the number of channels - int channels() const; - - //! returns the array of sizes, or NULL if the matrix is not allocated - const int* size() const; - //! returns the size of i-th matrix dimension (or 0) - int size(int i) const; - //! returns the matrix dimensionality - int dims() const; - //! returns the number of non-zero elements (=the number of hash table nodes) - size_t nzcount() const; - - //! computes the element hash value (1D case) - size_t hash(int i0) const; - //! computes the element hash value (2D case) - size_t hash(int i0, int i1) const; - //! computes the element hash value (3D case) - size_t hash(int i0, int i1, int i2) const; - //! computes the element hash value (nD case) - size_t hash(const int* idx) const; - - //!@{ - /*! - specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. - return pointer to the matrix element. - - if the element is there (it's non-zero), the pointer to it is returned - - if it's not there and createMissing=false, NULL pointer is returned - - if it's not there and createMissing=true, then the new element - is created and initialized with 0. Pointer to it is returned - - if the optional hashval pointer is not NULL, the element hash value is - not computed, but *hashval is taken instead. - */ - //! returns pointer to the specified element (1D case) - uchar* ptr(int i0, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (2D case) - uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (3D case) - uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); - //! returns pointer to the specified element (nD case) - uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); - //!@} - - //!@{ - /*! - return read-write reference to the specified sparse matrix element. - - `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. - The methods always return a valid reference. - If the element did not exist, it is created and initialized with 0. - */ - //! returns reference to the specified element (1D case) - template _Tp& ref(int i0, size_t* hashval=0); - //! returns reference to the specified element (2D case) - template _Tp& ref(int i0, int i1, size_t* hashval=0); - //! returns reference to the specified element (3D case) - template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); - //! returns reference to the specified element (nD case) - template _Tp& ref(const int* idx, size_t* hashval=0); - //!@} - - //!@{ - /*! - return value of the specified sparse matrix element. - - `value<_Tp>(i0,...[,hashval])` is equivalent to - @code - { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } - @endcode - - That is, if the element did not exist, the methods return 0. - */ - //! returns value of the specified element (1D case) - template _Tp value(int i0, size_t* hashval=0) const; - //! returns value of the specified element (2D case) - template _Tp value(int i0, int i1, size_t* hashval=0) const; - //! returns value of the specified element (3D case) - template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; - //! returns value of the specified element (nD case) - template _Tp value(const int* idx, size_t* hashval=0) const; - //!@} - - //!@{ - /*! - Return pointer to the specified sparse matrix element if it exists - - `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. - - If the specified element does not exist, the methods return NULL. - */ - //! returns pointer to the specified element (1D case) - template const _Tp* find(int i0, size_t* hashval=0) const; - //! returns pointer to the specified element (2D case) - template const _Tp* find(int i0, int i1, size_t* hashval=0) const; - //! returns pointer to the specified element (3D case) - template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; - //! returns pointer to the specified element (nD case) - template const _Tp* find(const int* idx, size_t* hashval=0) const; - //!@} - - //! erases the specified element (2D case) - void erase(int i0, int i1, size_t* hashval=0); - //! erases the specified element (3D case) - void erase(int i0, int i1, int i2, size_t* hashval=0); - //! erases the specified element (nD case) - void erase(const int* idx, size_t* hashval=0); - - //!@{ - /*! - return the sparse matrix iterator pointing to the first sparse matrix element - */ - //! returns the sparse matrix iterator at the matrix beginning - SparseMatIterator begin(); - //! returns the sparse matrix iterator at the matrix beginning - template SparseMatIterator_<_Tp> begin(); - //! returns the read-only sparse matrix iterator at the matrix beginning - SparseMatConstIterator begin() const; - //! returns the read-only sparse matrix iterator at the matrix beginning - template SparseMatConstIterator_<_Tp> begin() const; - //!@} - /*! - return the sparse matrix iterator pointing to the element following the last sparse matrix element - */ - //! returns the sparse matrix iterator at the matrix end - SparseMatIterator end(); - //! returns the read-only sparse matrix iterator at the matrix end - SparseMatConstIterator end() const; - //! returns the typed sparse matrix iterator at the matrix end - template SparseMatIterator_<_Tp> end(); - //! returns the typed read-only sparse matrix iterator at the matrix end - template SparseMatConstIterator_<_Tp> end() const; - - //! returns the value stored in the sparse martix node - template _Tp& value(Node* n); - //! returns the value stored in the sparse martix node - template const _Tp& value(const Node* n) const; - - ////////////// some internal-use methods /////////////// - Node* node(size_t nidx); - const Node* node(size_t nidx) const; - - uchar* newNode(const int* idx, size_t hashval); - void removeNode(size_t hidx, size_t nidx, size_t previdx); - void resizeHashTab(size_t newsize); - - int flags; - Hdr* hdr; -}; - - - -///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// - -/** @brief Template sparse n-dimensional array class derived from SparseMat - -SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies -notation of some operations: -@code - int sz[] = {10, 20, 30}; - SparseMat_ M(3, sz); - ... - M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); -@endcode - */ -template class SparseMat_ : public SparseMat -{ -public: - typedef SparseMatIterator_<_Tp> iterator; - typedef SparseMatConstIterator_<_Tp> const_iterator; - - //! the default constructor - SparseMat_(); - //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type) - SparseMat_(int dims, const int* _sizes); - //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted - SparseMat_(const SparseMat& m); - //! the copy constructor. This is O(1) operation - no data is copied - SparseMat_(const SparseMat_& m); - //! converts dense matrix to the sparse form - SparseMat_(const Mat& m); - //! converts the old-style sparse matrix to the C++ class. All the elements are copied - //SparseMat_(const CvSparseMat* m); - //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted - SparseMat_& operator = (const SparseMat& m); - //! the assignment operator. This is O(1) operation - no data is copied - SparseMat_& operator = (const SparseMat_& m); - //! converts dense matrix to the sparse form - SparseMat_& operator = (const Mat& m); - - //! makes full copy of the matrix. All the elements are duplicated - CV_NODISCARD_STD SparseMat_ clone() const; - //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) - void create(int dims, const int* _sizes); - //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied - //operator CvSparseMat*() const; - - //! returns type of the matrix elements - int type() const; - //! returns depth of the matrix elements - int depth() const; - //! returns the number of channels in each matrix element - int channels() const; - - //! equivalent to SparseMat::ref<_Tp>(i0, hashval) - _Tp& ref(int i0, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) - _Tp& ref(int i0, int i1, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) - _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); - //! equivalent to SparseMat::ref<_Tp>(idx, hashval) - _Tp& ref(const int* idx, size_t* hashval=0); - - //! equivalent to SparseMat::value<_Tp>(i0, hashval) - _Tp operator()(int i0, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) - _Tp operator()(int i0, int i1, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) - _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; - //! equivalent to SparseMat::value<_Tp>(idx, hashval) - _Tp operator()(const int* idx, size_t* hashval=0) const; - - //! returns sparse matrix iterator pointing to the first sparse matrix element - SparseMatIterator_<_Tp> begin(); - //! returns read-only sparse matrix iterator pointing to the first sparse matrix element - SparseMatConstIterator_<_Tp> begin() const; - //! returns sparse matrix iterator pointing to the element following the last sparse matrix element - SparseMatIterator_<_Tp> end(); - //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element - SparseMatConstIterator_<_Tp> end() const; -}; - - - -////////////////////////////////// MatConstIterator ////////////////////////////////// - -class CV_EXPORTS MatConstIterator -{ -public: - typedef uchar* value_type; - typedef ptrdiff_t difference_type; - typedef const uchar** pointer; - typedef uchar* reference; - - typedef std::random_access_iterator_tag iterator_category; - - //! default constructor - MatConstIterator(); - //! constructor that sets the iterator to the beginning of the matrix - MatConstIterator(const Mat* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator(const Mat* _m, const int* _idx); - //! copy constructor - MatConstIterator(const MatConstIterator& it); - - //! copy operator - MatConstIterator& operator = (const MatConstIterator& it); - //! returns the current matrix element - const uchar* operator *() const; - //! returns the i-th matrix element, relative to the current - const uchar* operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatConstIterator& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatConstIterator& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatConstIterator& operator --(); - //! decrements the iterator - MatConstIterator operator --(int); - //! increments the iterator - MatConstIterator& operator ++(); - //! increments the iterator - MatConstIterator operator ++(int); - //! returns the current iterator position - Point pos() const; - //! returns the current iterator position - void pos(int* _idx) const; - - ptrdiff_t lpos() const; - void seek(ptrdiff_t ofs, bool relative = false); - void seek(const int* _idx, bool relative = false); - - const Mat* m; - size_t elemSize; - const uchar* ptr; - const uchar* sliceStart; - const uchar* sliceEnd; -}; - - - -////////////////////////////////// MatConstIterator_ ///////////////////////////////// - -/** @brief Matrix read-only iterator - */ -template -class MatConstIterator_ : public MatConstIterator -{ -public: - typedef _Tp value_type; - typedef ptrdiff_t difference_type; - typedef const _Tp* pointer; - typedef const _Tp& reference; - - typedef std::random_access_iterator_tag iterator_category; - - //! default constructor - MatConstIterator_(); - //! constructor that sets the iterator to the beginning of the matrix - MatConstIterator_(const Mat_<_Tp>* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); - //! copy constructor - MatConstIterator_(const MatConstIterator_& it); - - //! copy operator - MatConstIterator_& operator = (const MatConstIterator_& it); - //! returns the current matrix element - const _Tp& operator *() const; - //! returns the i-th matrix element, relative to the current - const _Tp& operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatConstIterator_& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatConstIterator_& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatConstIterator_& operator --(); - //! decrements the iterator - MatConstIterator_ operator --(int); - //! increments the iterator - MatConstIterator_& operator ++(); - //! increments the iterator - MatConstIterator_ operator ++(int); - //! returns the current iterator position - Point pos() const; -}; - - - -//////////////////////////////////// MatIterator_ //////////////////////////////////// - -/** @brief Matrix read-write iterator -*/ -template -class MatIterator_ : public MatConstIterator_<_Tp> -{ -public: - typedef _Tp* pointer; - typedef _Tp& reference; - - typedef std::random_access_iterator_tag iterator_category; - - //! the default constructor - MatIterator_(); - //! constructor that sets the iterator to the beginning of the matrix - MatIterator_(Mat_<_Tp>* _m); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, Point _pt); - //! constructor that sets the iterator to the specified element of the matrix - MatIterator_(Mat_<_Tp>* _m, const int* _idx); - //! copy constructor - MatIterator_(const MatIterator_& it); - //! copy operator - MatIterator_& operator = (const MatIterator_<_Tp>& it ); - - //! returns the current matrix element - _Tp& operator *() const; - //! returns the i-th matrix element, relative to the current - _Tp& operator [](ptrdiff_t i) const; - - //! shifts the iterator forward by the specified number of elements - MatIterator_& operator += (ptrdiff_t ofs); - //! shifts the iterator backward by the specified number of elements - MatIterator_& operator -= (ptrdiff_t ofs); - //! decrements the iterator - MatIterator_& operator --(); - //! decrements the iterator - MatIterator_ operator --(int); - //! increments the iterator - MatIterator_& operator ++(); - //! increments the iterator - MatIterator_ operator ++(int); -}; - - - -/////////////////////////////// SparseMatConstIterator /////////////////////////////// - -/** @brief Read-Only Sparse Matrix Iterator. - - Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: - - \code - SparseMatConstIterator it = m.begin(), it_end = m.end(); - double s = 0; - CV_Assert( m.type() == CV_32F ); - for( ; it != it_end; ++it ) - s += it.value(); - \endcode -*/ -class CV_EXPORTS SparseMatConstIterator -{ -public: - //! the default constructor - SparseMatConstIterator(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatConstIterator(const SparseMat* _m); - //! the copy constructor - SparseMatConstIterator(const SparseMatConstIterator& it); - - //! the assignment operator - SparseMatConstIterator& operator = (const SparseMatConstIterator& it); - - //! template method returning the current matrix element - template const _Tp& value() const; - //! returns the current node of the sparse matrix. it.node->idx is the current element index - const SparseMat::Node* node() const; - - //! moves iterator to the previous element - SparseMatConstIterator& operator --(); - //! moves iterator to the previous element - SparseMatConstIterator operator --(int); - //! moves iterator to the next element - SparseMatConstIterator& operator ++(); - //! moves iterator to the next element - SparseMatConstIterator operator ++(int); - - //! moves iterator to the element after the last element - void seekEnd(); - - const SparseMat* m; - size_t hashidx; - uchar* ptr; -}; - - - -////////////////////////////////// SparseMatIterator ///////////////////////////////// - -/** @brief Read-write Sparse Matrix Iterator - - The class is similar to cv::SparseMatConstIterator, - but can be used for in-place modification of the matrix elements. -*/ -class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator -{ -public: - //! the default constructor - SparseMatIterator(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatIterator(SparseMat* _m); - //! the full constructor setting the iterator to the specified sparse matrix element - SparseMatIterator(SparseMat* _m, const int* idx); - //! the copy constructor - SparseMatIterator(const SparseMatIterator& it); - - //! the assignment operator - SparseMatIterator& operator = (const SparseMatIterator& it); - //! returns read-write reference to the current sparse matrix element - template _Tp& value() const; - //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) - SparseMat::Node* node() const; - - //! moves iterator to the next element - SparseMatIterator& operator ++(); - //! moves iterator to the next element - SparseMatIterator operator ++(int); -}; - - - -/////////////////////////////// SparseMatConstIterator_ ////////////////////////////// - -/** @brief Template Read-Only Sparse Matrix Iterator Class. - - This is the derived from SparseMatConstIterator class that - introduces more convenient operator *() for accessing the current element. -*/ -template class SparseMatConstIterator_ : public SparseMatConstIterator -{ -public: - - typedef std::forward_iterator_tag iterator_category; - - //! the default constructor - SparseMatConstIterator_(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatConstIterator_(const SparseMat_<_Tp>* _m); - SparseMatConstIterator_(const SparseMat* _m); - //! the copy constructor - SparseMatConstIterator_(const SparseMatConstIterator_& it); - - //! the assignment operator - SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); - //! the element access operator - const _Tp& operator *() const; - - //! moves iterator to the next element - SparseMatConstIterator_& operator ++(); - //! moves iterator to the next element - SparseMatConstIterator_ operator ++(int); -}; - - - -///////////////////////////////// SparseMatIterator_ ///////////////////////////////// - -/** @brief Template Read-Write Sparse Matrix Iterator Class. - - This is the derived from cv::SparseMatConstIterator_ class that - introduces more convenient operator *() for accessing the current element. -*/ -template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> -{ -public: - - typedef std::forward_iterator_tag iterator_category; - - //! the default constructor - SparseMatIterator_(); - //! the full constructor setting the iterator to the first sparse matrix element - SparseMatIterator_(SparseMat_<_Tp>* _m); - SparseMatIterator_(SparseMat* _m); - //! the copy constructor - SparseMatIterator_(const SparseMatIterator_& it); - - //! the assignment operator - SparseMatIterator_& operator = (const SparseMatIterator_& it); - //! returns the reference to the current element - _Tp& operator *() const; - - //! moves the iterator to the next element - SparseMatIterator_& operator ++(); - //! moves the iterator to the next element - SparseMatIterator_ operator ++(int); -}; - - - -/////////////////////////////////// NAryMatIterator ////////////////////////////////// - -/** @brief n-ary multi-dimensional array iterator. - -Use the class to implement unary, binary, and, generally, n-ary element-wise operations on -multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some -may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of -the iterators after each small operations may be a big overhead. In this case consider using -NAryMatIterator to iterate through several matrices simultaneously as long as they have the same -geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, -`it.planes[1]`,... will be the slices of the corresponding matrices. - -The example below illustrates how you can compute a normalized and threshold 3D color histogram: -@code - void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) - { - const int histSize[] = {N, N, N}; - - // make sure that the histogram has a proper size and type - hist.create(3, histSize, CV_32F); - - // and clear it - hist = Scalar(0); - - // the loop below assumes that the image - // is a 8-bit 3-channel. check it. - CV_Assert(image.type() == CV_8UC3); - MatConstIterator_ it = image.begin(), - it_end = image.end(); - for( ; it != it_end; ++it ) - { - const Vec3b& pix = *it; - hist.at(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; - } - - minProb *= image.rows*image.cols; - - // initialize iterator (the style is different from STL). - // after initialization the iterator will contain - // the number of slices or planes the iterator will go through. - // it simultaneously increments iterators for several matrices - // supplied as a null terminated list of pointers - const Mat* arrays[] = {&hist, 0}; - Mat planes[1]; - NAryMatIterator itNAry(arrays, planes, 1); - double s = 0; - // iterate through the matrix. on each iteration - // itNAry.planes[i] (of type Mat) will be set to the current plane - // of the i-th n-dim matrix passed to the iterator constructor. - for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) - { - threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO); - s += sum(itNAry.planes[0])[0]; - } - - s = 1./s; - itNAry = NAryMatIterator(arrays, planes, 1); - for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) - itNAry.planes[0] *= s; - } -@endcode - */ -class CV_EXPORTS NAryMatIterator -{ -public: - //! the default constructor - NAryMatIterator(); - //! the full constructor taking arbitrary number of n-dim matrices - NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); - //! the full constructor taking arbitrary number of n-dim matrices - NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); - //! the separate iterator initialization method - void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); - - //! proceeds to the next plane of every iterated matrix - NAryMatIterator& operator ++(); - //! proceeds to the next plane of every iterated matrix (postfix increment operator) - NAryMatIterator operator ++(int); - - //! the iterated arrays - const Mat** arrays; - //! the current planes - Mat* planes; - //! data pointers - uchar** ptrs; - //! the number of arrays - int narrays; - //! the number of hyper-planes that the iterator steps through - size_t nplanes; - //! the size of each segment (in elements) - size_t size; -protected: - int iterdepth; - size_t idx; -}; - - - -///////////////////////////////// Matrix Expressions ///////////////////////////////// - -class CV_EXPORTS MatOp -{ -public: - MatOp(); - virtual ~MatOp(); - - virtual bool elementWise(const MatExpr& expr) const; - virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; - virtual void roi(const MatExpr& expr, const Range& rowRange, - const Range& colRange, MatExpr& res) const; - virtual void diag(const MatExpr& expr, int d, MatExpr& res) const; - virtual void augAssignAdd(const MatExpr& expr, Mat& m) const; - virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const; - virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const; - virtual void augAssignDivide(const MatExpr& expr, Mat& m) const; - virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; - virtual void augAssignOr(const MatExpr& expr, Mat& m) const; - virtual void augAssignXor(const MatExpr& expr, Mat& m) const; - - virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; - virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; - - virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; - virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; - - virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; - virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; - - virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; - virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; - - virtual void abs(const MatExpr& expr, MatExpr& res) const; - - virtual void transpose(const MatExpr& expr, MatExpr& res) const; - virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; - virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; - - virtual Size size(const MatExpr& expr) const; - virtual int type(const MatExpr& expr) const; -}; - -/** @brief Matrix expression representation -@anchor MatrixExpressions -This is a list of implemented matrix operations that can be combined in arbitrary complex -expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a -real-valued scalar ( double )): -- Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` -- Scaling: `A*alpha` -- Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` -- Matrix multiplication: `A*B` -- Transposition: `A.t()` (means AT) -- Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: - `A.inv([method]) (~ A-1)`, `A.inv([method])*B (~ X: AX=B)` -- Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of - `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose - elements are set to 255 (if the particular element or pair of elements satisfy the condition) or - 0. -- Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of - `&`, `|`, `^`. -- Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` -- Element-wise absolute value: `abs(A)` -- Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` -- Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, - mean, sum, countNonZero, trace, determinant, repeat, and others. -- Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated - initializers, matrix constructors and operators that extract sub-matrices (see Mat description). -- Mat_() constructors to cast the result to the proper type. -@note Comma-separated initializers and probably some other operations may require additional -explicit Mat() or Mat_() constructor calls to resolve a possible ambiguity. - -Here are examples of matrix expressions: -@code - // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) - SVD svd(A); - Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); - - // compute the new vector of parameters in the Levenberg-Marquardt algorithm - x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); - - // sharpen image using "unsharp mask" algorithm - Mat blurred; double sigma = 1, threshold = 5, amount = 1; - GaussianBlur(img, blurred, Size(), sigma, sigma); - Mat lowContrastMask = abs(img - blurred) < threshold; - Mat sharpened = img*(1+amount) + blurred*(-amount); - img.copyTo(sharpened, lowContrastMask); -@endcode -*/ -class CV_EXPORTS MatExpr -{ -public: - MatExpr(); - explicit MatExpr(const Mat& m); - - MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), - const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); - - operator Mat() const; - template operator Mat_<_Tp>() const; - - Size size() const; - int type() const; - - MatExpr row(int y) const; - MatExpr col(int x) const; - MatExpr diag(int d = 0) const; - MatExpr operator()( const Range& rowRange, const Range& colRange ) const; - MatExpr operator()( const Rect& roi ) const; - - MatExpr t() const; - MatExpr inv(int method = DECOMP_LU) const; - MatExpr mul(const MatExpr& e, double scale=1) const; - MatExpr mul(const Mat& m, double scale=1) const; - - Mat cross(const Mat& m) const; - double dot(const Mat& m) const; - - void swap(MatExpr& b); - - const MatOp* op; - int flags; - - Mat a, b, c; - double alpha, beta; - Scalar s; -}; - -//! @} core_basic - -//! @relates cv::MatExpr -//! @{ -CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); -CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); -CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); -CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); } -template static inline -MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; } - -CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a); -CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); -CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); -CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); } -template static inline -MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; } - -CV_EXPORTS MatExpr operator - (const Mat& m); -CV_EXPORTS MatExpr operator - (const MatExpr& e); - -CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator * (const Mat& a, double s); -CV_EXPORTS MatExpr operator * (double s, const Mat& a); -CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); -CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); -CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); } -template static inline -MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; } - -CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator / (const Mat& a, double s); -CV_EXPORTS MatExpr operator / (double s, const Mat& a); -CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); -CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); -CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); -CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); -CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); -template static inline -MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); } -template static inline -MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; } - -CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator < (const Mat& a, double s); -CV_EXPORTS MatExpr operator < (double s, const Mat& a); -template static inline -MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); } -template static inline -MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; } - -CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator <= (const Mat& a, double s); -CV_EXPORTS MatExpr operator <= (double s, const Mat& a); -template static inline -MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); } -template static inline -MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; } - -CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator == (const Mat& a, double s); -CV_EXPORTS MatExpr operator == (double s, const Mat& a); -template static inline -MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); } -template static inline -MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; } - -CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator != (const Mat& a, double s); -CV_EXPORTS MatExpr operator != (double s, const Mat& a); -template static inline -MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); } -template static inline -MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; } - -CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator >= (const Mat& a, double s); -CV_EXPORTS MatExpr operator >= (double s, const Mat& a); -template static inline -MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); } -template static inline -MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; } - -CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator > (const Mat& a, double s); -CV_EXPORTS MatExpr operator > (double s, const Mat& a); -template static inline -MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); } -template static inline -MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; } - -CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); -template static inline -MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); } -template static inline -MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; } - -CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); -template static inline -MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); } -template static inline -MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; } - -CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); -CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); -CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); -template static inline -MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); } -template static inline -MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; } - -CV_EXPORTS MatExpr operator ~(const Mat& m); - -CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); -CV_EXPORTS MatExpr min(const Mat& a, double s); -CV_EXPORTS MatExpr min(double s, const Mat& a); -template static inline -MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); } -template static inline -MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); } - -CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); -CV_EXPORTS MatExpr max(const Mat& a, double s); -CV_EXPORTS MatExpr max(double s, const Mat& a); -template static inline -MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); } -template static inline -MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); } - -/** @brief Calculates an absolute value of each matrix element. - -abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: -- C = abs(A-B) is equivalent to `absdiff(A, B, C)` -- C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` -- C = `Mat_ >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, -beta)` - -The output matrix has the same size and the same type as the input one except for the last case, -where C is depth=CV_8U . -@param m matrix. -@sa @ref MatrixExpressions, absdiff, convertScaleAbs - */ -CV_EXPORTS MatExpr abs(const Mat& m); -/** @overload -@param e matrix expression. -*/ -CV_EXPORTS MatExpr abs(const MatExpr& e); -//! @} relates cv::MatExpr - -} // cv - -#include "opencv2/core/mat.inl.hpp" - -#endif // OPENCV_CORE_MAT_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_MAT_HPP +#define OPENCV_CORE_MAT_HPP + +#ifndef __cplusplus +# error mat.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/matx.hpp" +#include "opencv2/core/types.hpp" + +#include "opencv2/core/bufferpool.hpp" + +#include +#include + +namespace cv +{ + +//! @addtogroup core_basic +//! @{ + +enum AccessFlag { ACCESS_READ=1<<24, ACCESS_WRITE=1<<25, + ACCESS_RW=3<<24, ACCESS_MASK=ACCESS_RW, ACCESS_FAST=1<<26 }; +CV_ENUM_FLAGS(AccessFlag) +__CV_ENUM_FLAGS_BITWISE_AND(AccessFlag, int, AccessFlag) + +CV__DEBUG_NS_BEGIN + +class CV_EXPORTS _OutputArray; + +//////////////////////// Input/Output Array Arguments ///////////////////////////////// + +/** @brief This is the proxy class for passing read-only input arrays into OpenCV functions. + +It is defined as: +@code + typedef const _InputArray& InputArray; +@endcode +where \ref cv::_InputArray is a class that can be constructed from \ref cv::Mat, \ref cv::Mat_, +\ref cv::Matx, std::vector, std::vector>, std::vector, +std::vector>, \ref cv::UMat, std::vector or `double`. It can also be constructed from +a matrix expression. + +Since this is mostly implementation-level class, and its interface may change in future versions, we +do not describe it in details. There are a few key things, though, that should be kept in mind: + +- When you see in the reference manual or in OpenCV source code a function that takes + InputArray, it means that you can actually pass `Mat`, `Matx`, `vector` etc. (see above the + complete list). +- Optional input arguments: If some of the input arrays may be empty, pass cv::noArray() (or + simply cv::Mat() as you probably did before). +- The class is designed solely for passing parameters. That is, normally you *should not* + declare class members, local and global variables of this type. +- If you want to design your own function or a class method that can operate of arrays of + multiple types, you can use InputArray (or OutputArray) for the respective parameters. Inside + a function you should use _InputArray::getMat() method to construct a matrix header for the + array (without copying data). _InputArray::kind() can be used to distinguish Mat from + `vector<>` etc., but normally it is not needed. + +Here is how you can use a function that takes InputArray : +@code + std::vector vec; + // points or a circle + for( int i = 0; i < 30; i++ ) + vec.push_back(Point2f((float)(100 + 30*cos(i*CV_PI*2/5)), + (float)(100 - 30*sin(i*CV_PI*2/5)))); + cv::transform(vec, vec, cv::Matx23f(0.707, -0.707, 10, 0.707, 0.707, 20)); +@endcode +That is, we form an STL vector containing points, and apply in-place affine transformation to the +vector using the 2x3 matrix created inline as `Matx` instance. + +Here is how such a function can be implemented (for simplicity, we implement a very specific case of +it, according to the assertion statement inside) : +@code + void myAffineTransform(InputArray _src, OutputArray _dst, InputArray _m) + { + // get Mat headers for input arrays. This is O(1) operation, + // unless _src and/or _m are matrix expressions. + Mat src = _src.getMat(), m = _m.getMat(); + CV_Assert( src.type() == CV_32FC2 && m.type() == CV_32F && m.size() == Size(3, 2) ); + + // [re]create the output array so that it has the proper size and type. + // In case of Mat it calls Mat::create, in case of STL vector it calls vector::resize. + _dst.create(src.size(), src.type()); + Mat dst = _dst.getMat(); + + for( int i = 0; i < src.rows; i++ ) + for( int j = 0; j < src.cols; j++ ) + { + Point2f pt = src.at(i, j); + dst.at(i, j) = Point2f(m.at(0, 0)*pt.x + + m.at(0, 1)*pt.y + + m.at(0, 2), + m.at(1, 0)*pt.x + + m.at(1, 1)*pt.y + + m.at(1, 2)); + } + } +@endcode +There is another related type, InputArrayOfArrays, which is currently defined as a synonym for +InputArray: +@code + typedef InputArray InputArrayOfArrays; +@endcode +It denotes function arguments that are either vectors of vectors or vectors of matrices. A separate +synonym is needed to generate Python/Java etc. wrappers properly. At the function implementation +level their use is similar, but _InputArray::getMat(idx) should be used to get header for the +idx-th component of the outer vector and _InputArray::size().area() should be used to find the +number of components (vectors/matrices) of the outer vector. + +In general, type support is limited to cv::Mat types. Other types are forbidden. +But in some cases we need to support passing of custom non-general Mat types, like arrays of cv::KeyPoint, cv::DMatch, etc. +This data is not intended to be interpreted as an image data, or processed somehow like regular cv::Mat. +To pass such custom type use rawIn() / rawOut() / rawInOut() wrappers. +Custom type is wrapped as Mat-compatible `CV_8UC` values (N = sizeof(T), N <= CV_CN_MAX). + */ +class CV_EXPORTS _InputArray +{ +public: + enum KindFlag { + KIND_SHIFT = 16, + FIXED_TYPE = 0x8000 << KIND_SHIFT, + FIXED_SIZE = 0x4000 << KIND_SHIFT, + KIND_MASK = 31 << KIND_SHIFT, + + NONE = 0 << KIND_SHIFT, + MAT = 1 << KIND_SHIFT, + MATX = 2 << KIND_SHIFT, + STD_VECTOR = 3 << KIND_SHIFT, + STD_VECTOR_VECTOR = 4 << KIND_SHIFT, + STD_VECTOR_MAT = 5 << KIND_SHIFT, +#if OPENCV_ABI_COMPATIBILITY < 500 + EXPR = 6 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/pull/17046 +#endif + OPENGL_BUFFER = 7 << KIND_SHIFT, + CUDA_HOST_MEM = 8 << KIND_SHIFT, + CUDA_GPU_MAT = 9 << KIND_SHIFT, + UMAT =10 << KIND_SHIFT, + STD_VECTOR_UMAT =11 << KIND_SHIFT, + STD_BOOL_VECTOR =12 << KIND_SHIFT, + STD_VECTOR_CUDA_GPU_MAT = 13 << KIND_SHIFT, +#if OPENCV_ABI_COMPATIBILITY < 500 + STD_ARRAY =14 << KIND_SHIFT, //!< removed: https://github.com/opencv/opencv/issues/18897 +#endif + STD_ARRAY_MAT =15 << KIND_SHIFT + }; + + _InputArray(); + _InputArray(int _flags, void* _obj); + _InputArray(const Mat& m); + _InputArray(const MatExpr& expr); + _InputArray(const std::vector& vec); + template _InputArray(const Mat_<_Tp>& m); + template _InputArray(const std::vector<_Tp>& vec); + _InputArray(const std::vector& vec); + template _InputArray(const std::vector >& vec); + _InputArray(const std::vector >&) = delete; // not supported + template _InputArray(const std::vector >& vec); + template _InputArray(const _Tp* vec, int n); + template _InputArray(const Matx<_Tp, m, n>& matx); + _InputArray(const double& val); + _InputArray(const cuda::GpuMat& d_mat); + _InputArray(const std::vector& d_mat_array); + _InputArray(const ogl::Buffer& buf); + _InputArray(const cuda::HostMem& cuda_mem); + template _InputArray(const cudev::GpuMat_<_Tp>& m); + _InputArray(const UMat& um); + _InputArray(const std::vector& umv); + + template _InputArray(const std::array<_Tp, _Nm>& arr); + template _InputArray(const std::array& arr); + + template static _InputArray rawIn(const std::vector<_Tp>& vec); + template static _InputArray rawIn(const std::array<_Tp, _Nm>& arr); + + Mat getMat(int idx=-1) const; + Mat getMat_(int idx=-1) const; + UMat getUMat(int idx=-1) const; + void getMatVector(std::vector& mv) const; + void getUMatVector(std::vector& umv) const; + void getGpuMatVector(std::vector& gpumv) const; + cuda::GpuMat getGpuMat() const; + ogl::Buffer getOGlBuffer() const; + + int getFlags() const; + void* getObj() const; + Size getSz() const; + + _InputArray::KindFlag kind() const; + int dims(int i=-1) const; + int cols(int i=-1) const; + int rows(int i=-1) const; + Size size(int i=-1) const; + int sizend(int* sz, int i=-1) const; + bool sameSize(const _InputArray& arr) const; + size_t total(int i=-1) const; + int type(int i=-1) const; + int depth(int i=-1) const; + int channels(int i=-1) const; + bool isContinuous(int i=-1) const; + bool isSubmatrix(int i=-1) const; + bool empty() const; + void copyTo(const _OutputArray& arr) const; + void copyTo(const _OutputArray& arr, const _InputArray & mask) const; + size_t offset(int i=-1) const; + size_t step(int i=-1) const; + bool isMat() const; + bool isUMat() const; + bool isMatVector() const; + bool isUMatVector() const; + bool isMatx() const; + bool isVector() const; + bool isGpuMat() const; + bool isGpuMatVector() const; + ~_InputArray(); + +protected: + int flags; + void* obj; + Size sz; + + void init(int _flags, const void* _obj); + void init(int _flags, const void* _obj, Size _sz); +}; +CV_ENUM_FLAGS(_InputArray::KindFlag) +__CV_ENUM_FLAGS_BITWISE_AND(_InputArray::KindFlag, int, _InputArray::KindFlag) + +/** @brief This type is very similar to InputArray except that it is used for input/output and output function +parameters. + +Just like with InputArray, OpenCV users should not care about OutputArray, they just pass `Mat`, +`vector` etc. to the functions. The same limitation as for `InputArray`: *Do not explicitly +create OutputArray instances* applies here too. + +If you want to make your function polymorphic (i.e. accept different arrays as output parameters), +it is also not very difficult. Take the sample above as the reference. Note that +_OutputArray::create() needs to be called before _OutputArray::getMat(). This way you guarantee +that the output array is properly allocated. + +Optional output parameters. If you do not need certain output array to be computed and returned to +you, pass cv::noArray(), just like you would in the case of optional input array. At the +implementation level, use _OutputArray::needed() to check if certain output array needs to be +computed or not. + +There are several synonyms for OutputArray that are used to assist automatic Python/Java/... wrapper +generators: +@code + typedef OutputArray OutputArrayOfArrays; + typedef OutputArray InputOutputArray; + typedef OutputArray InputOutputArrayOfArrays; +@endcode + */ +class CV_EXPORTS _OutputArray : public _InputArray +{ +public: + enum DepthMask + { + DEPTH_MASK_8U = 1 << CV_8U, + DEPTH_MASK_8S = 1 << CV_8S, + DEPTH_MASK_16U = 1 << CV_16U, + DEPTH_MASK_16S = 1 << CV_16S, + DEPTH_MASK_32S = 1 << CV_32S, + DEPTH_MASK_32F = 1 << CV_32F, + DEPTH_MASK_64F = 1 << CV_64F, + DEPTH_MASK_16F = 1 << CV_16F, + DEPTH_MASK_ALL = (DEPTH_MASK_64F<<1)-1, + DEPTH_MASK_ALL_BUT_8S = DEPTH_MASK_ALL & ~DEPTH_MASK_8S, + DEPTH_MASK_ALL_16F = (DEPTH_MASK_16F<<1)-1, + DEPTH_MASK_FLT = DEPTH_MASK_32F + DEPTH_MASK_64F + }; + + _OutputArray(); + _OutputArray(int _flags, void* _obj); + _OutputArray(Mat& m); + _OutputArray(std::vector& vec); + _OutputArray(cuda::GpuMat& d_mat); + _OutputArray(std::vector& d_mat); + _OutputArray(ogl::Buffer& buf); + _OutputArray(cuda::HostMem& cuda_mem); + template _OutputArray(cudev::GpuMat_<_Tp>& m); + template _OutputArray(std::vector<_Tp>& vec); + _OutputArray(std::vector& vec) = delete; // not supported + template _OutputArray(std::vector >& vec); + _OutputArray(std::vector >&) = delete; // not supported + template _OutputArray(std::vector >& vec); + template _OutputArray(Mat_<_Tp>& m); + template _OutputArray(_Tp* vec, int n); + template _OutputArray(Matx<_Tp, m, n>& matx); + _OutputArray(UMat& m); + _OutputArray(std::vector& vec); + + _OutputArray(const Mat& m); + _OutputArray(const std::vector& vec); + _OutputArray(const cuda::GpuMat& d_mat); + _OutputArray(const std::vector& d_mat); + _OutputArray(const ogl::Buffer& buf); + _OutputArray(const cuda::HostMem& cuda_mem); + template _OutputArray(const cudev::GpuMat_<_Tp>& m); + template _OutputArray(const std::vector<_Tp>& vec); + template _OutputArray(const std::vector >& vec); + template _OutputArray(const std::vector >& vec); + template _OutputArray(const Mat_<_Tp>& m); + template _OutputArray(const _Tp* vec, int n); + template _OutputArray(const Matx<_Tp, m, n>& matx); + _OutputArray(const UMat& m); + _OutputArray(const std::vector& vec); + + template _OutputArray(std::array<_Tp, _Nm>& arr); + template _OutputArray(const std::array<_Tp, _Nm>& arr); + template _OutputArray(std::array& arr); + template _OutputArray(const std::array& arr); + + template static _OutputArray rawOut(std::vector<_Tp>& vec); + template static _OutputArray rawOut(std::array<_Tp, _Nm>& arr); + + bool fixedSize() const; + bool fixedType() const; + bool needed() const; + Mat& getMatRef(int i=-1) const; + UMat& getUMatRef(int i=-1) const; + cuda::GpuMat& getGpuMatRef() const; + std::vector& getGpuMatVecRef() const; + ogl::Buffer& getOGlBufferRef() const; + cuda::HostMem& getHostMemRef() const; + void create(Size sz, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; + void create(int rows, int cols, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; + void create(int dims, const int* size, int type, int i=-1, bool allowTransposed=false, _OutputArray::DepthMask fixedDepthMask=static_cast<_OutputArray::DepthMask>(0)) const; + void createSameSize(const _InputArray& arr, int mtype) const; + void release() const; + void clear() const; + void setTo(const _InputArray& value, const _InputArray & mask = _InputArray()) const; + + void assign(const UMat& u) const; + void assign(const Mat& m) const; + + void assign(const std::vector& v) const; + void assign(const std::vector& v) const; + + void move(UMat& u) const; + void move(Mat& m) const; +}; + + +class CV_EXPORTS _InputOutputArray : public _OutputArray +{ +public: + _InputOutputArray(); + _InputOutputArray(int _flags, void* _obj); + _InputOutputArray(Mat& m); + _InputOutputArray(std::vector& vec); + _InputOutputArray(cuda::GpuMat& d_mat); + _InputOutputArray(ogl::Buffer& buf); + _InputOutputArray(cuda::HostMem& cuda_mem); + template _InputOutputArray(cudev::GpuMat_<_Tp>& m); + template _InputOutputArray(std::vector<_Tp>& vec); + _InputOutputArray(std::vector& vec) = delete; // not supported + template _InputOutputArray(std::vector >& vec); + template _InputOutputArray(std::vector >& vec); + template _InputOutputArray(Mat_<_Tp>& m); + template _InputOutputArray(_Tp* vec, int n); + template _InputOutputArray(Matx<_Tp, m, n>& matx); + _InputOutputArray(UMat& m); + _InputOutputArray(std::vector& vec); + + _InputOutputArray(const Mat& m); + _InputOutputArray(const std::vector& vec); + _InputOutputArray(const cuda::GpuMat& d_mat); + _InputOutputArray(const std::vector& d_mat); + _InputOutputArray(const ogl::Buffer& buf); + _InputOutputArray(const cuda::HostMem& cuda_mem); + template _InputOutputArray(const cudev::GpuMat_<_Tp>& m); + template _InputOutputArray(const std::vector<_Tp>& vec); + template _InputOutputArray(const std::vector >& vec); + template _InputOutputArray(const std::vector >& vec); + template _InputOutputArray(const Mat_<_Tp>& m); + template _InputOutputArray(const _Tp* vec, int n); + template _InputOutputArray(const Matx<_Tp, m, n>& matx); + _InputOutputArray(const UMat& m); + _InputOutputArray(const std::vector& vec); + + template _InputOutputArray(std::array<_Tp, _Nm>& arr); + template _InputOutputArray(const std::array<_Tp, _Nm>& arr); + template _InputOutputArray(std::array& arr); + template _InputOutputArray(const std::array& arr); + + template static _InputOutputArray rawInOut(std::vector<_Tp>& vec); + template _InputOutputArray rawInOut(std::array<_Tp, _Nm>& arr); + +}; + +/** Helper to wrap custom types. @see InputArray */ +template static inline _InputArray rawIn(_Tp& v); +/** Helper to wrap custom types. @see InputArray */ +template static inline _OutputArray rawOut(_Tp& v); +/** Helper to wrap custom types. @see InputArray */ +template static inline _InputOutputArray rawInOut(_Tp& v); + +CV__DEBUG_NS_END + +typedef const _InputArray& InputArray; +typedef InputArray InputArrayOfArrays; +typedef const _OutputArray& OutputArray; +typedef OutputArray OutputArrayOfArrays; +typedef const _InputOutputArray& InputOutputArray; +typedef InputOutputArray InputOutputArrayOfArrays; + +/** @brief Returns an empty InputArray or OutputArray. + + This function is used to provide an "empty" or "null" array when certain functions + take optional input or output arrays that you don't want to provide. + + Many OpenCV functions accept optional arguments as `cv::InputArray` or `cv::OutputArray`. + When you don't want to pass any data for these optional parameters, you can use `cv::noArray()` + to indicate that you are omitting them. + + @return An empty `cv::InputArray` or `cv::OutputArray` that can be used as a placeholder. + + @note This is often used when a function has optional arrays, and you do not want to + provide a specific input or output array. + + @see cv::InputArray, cv::OutputArray + */ +CV_EXPORTS InputOutputArray noArray(); + +/////////////////////////////////// MatAllocator ////////////////////////////////////// + +/** @brief Usage flags for allocator + + @warning All flags except `USAGE_DEFAULT` are experimental. + + @warning For the OpenCL allocator, `USAGE_ALLOCATE_SHARED_MEMORY` depends on + OpenCV's optional, experimental integration with OpenCL SVM. To enable this + integration, build OpenCV using the `WITH_OPENCL_SVM=ON` CMake option and, at + runtime, call `cv::ocl::Context::getDefault().setUseSVM(true);` or similar + code. Note that SVM is incompatible with OpenCL 1.x. +*/ +enum UMatUsageFlags +{ + USAGE_DEFAULT = 0, + + // buffer allocation policy is platform and usage specific + USAGE_ALLOCATE_HOST_MEMORY = 1 << 0, + USAGE_ALLOCATE_DEVICE_MEMORY = 1 << 1, + USAGE_ALLOCATE_SHARED_MEMORY = 1 << 2, // It is not equal to: USAGE_ALLOCATE_HOST_MEMORY | USAGE_ALLOCATE_DEVICE_MEMORY + + __UMAT_USAGE_FLAGS_32BIT = 0x7fffffff // Binary compatibility hint +}; + +struct CV_EXPORTS UMatData; + +/** @brief Custom array allocator +*/ +class CV_EXPORTS MatAllocator +{ +public: + MatAllocator() {} + virtual ~MatAllocator() {} + + // let's comment it off for now to detect and fix all the uses of allocator + //virtual void allocate(int dims, const int* sizes, int type, int*& refcount, + // uchar*& datastart, uchar*& data, size_t* step) = 0; + //virtual void deallocate(int* refcount, uchar* datastart, uchar* data) = 0; + virtual UMatData* allocate(int dims, const int* sizes, int type, + void* data, size_t* step, AccessFlag flags, UMatUsageFlags usageFlags) const = 0; + virtual bool allocate(UMatData* data, AccessFlag accessflags, UMatUsageFlags usageFlags) const = 0; + virtual void deallocate(UMatData* data) const = 0; + virtual void map(UMatData* data, AccessFlag accessflags) const; + virtual void unmap(UMatData* data) const; + virtual void download(UMatData* data, void* dst, int dims, const size_t sz[], + const size_t srcofs[], const size_t srcstep[], + const size_t dststep[]) const; + virtual void upload(UMatData* data, const void* src, int dims, const size_t sz[], + const size_t dstofs[], const size_t dststep[], + const size_t srcstep[]) const; + virtual void copy(UMatData* srcdata, UMatData* dstdata, int dims, const size_t sz[], + const size_t srcofs[], const size_t srcstep[], + const size_t dstofs[], const size_t dststep[], bool sync) const; + + // default implementation returns DummyBufferPoolController + virtual BufferPoolController* getBufferPoolController(const char* id = NULL) const; +}; + + +//////////////////////////////// MatCommaInitializer ////////////////////////////////// + +/** @brief Comma-separated Matrix Initializer + + The class instances are usually not created explicitly. + Instead, they are created on "matrix << firstValue" operator. + + The sample below initializes 2x2 rotation matrix: + + \code + double angle = 30, a = cos(angle*CV_PI/180), b = sin(angle*CV_PI/180); + Mat R = (Mat_(2,2) << a, -b, b, a); + \endcode +*/ +template class MatCommaInitializer_ +{ +public: + //! the constructor, created by "matrix << firstValue" operator, where matrix is cv::Mat + MatCommaInitializer_(Mat_<_Tp>* _m); + //! the operator that takes the next value and put it to the matrix + template MatCommaInitializer_<_Tp>& operator , (T2 v); + //! another form of conversion operator + operator Mat_<_Tp>() const; +protected: + MatIterator_<_Tp> it; +}; + + +/////////////////////////////////////// Mat /////////////////////////////////////////// + +// note that umatdata might be allocated together +// with the matrix data, not as a separate object. +// therefore, it does not have constructor or destructor; +// it should be explicitly initialized using init(). +struct CV_EXPORTS UMatData +{ + enum MemoryFlag { COPY_ON_MAP=1, HOST_COPY_OBSOLETE=2, + DEVICE_COPY_OBSOLETE=4, TEMP_UMAT=8, TEMP_COPIED_UMAT=24, + USER_ALLOCATED=32, DEVICE_MEM_MAPPED=64, + ASYNC_CLEANUP=128 + }; + UMatData(const MatAllocator* allocator); + ~UMatData(); + + // provide atomic access to the structure + void lock(); + void unlock(); + + bool hostCopyObsolete() const; + bool deviceCopyObsolete() const; + bool deviceMemMapped() const; + bool copyOnMap() const; + bool tempUMat() const; + bool tempCopiedUMat() const; + void markHostCopyObsolete(bool flag); + void markDeviceCopyObsolete(bool flag); + void markDeviceMemMapped(bool flag); + + const MatAllocator* prevAllocator; + const MatAllocator* currAllocator; + int urefcount; + int refcount; + uchar* data; + uchar* origdata; + size_t size; + + UMatData::MemoryFlag flags; + void* handle; + void* userdata; + int allocatorFlags_; + int mapcount; + UMatData* originalUMatData; + std::shared_ptr allocatorContext; +}; +CV_ENUM_FLAGS(UMatData::MemoryFlag) + + +struct CV_EXPORTS MatSize +{ + explicit MatSize(int* _p) CV_NOEXCEPT; + int dims() const CV_NOEXCEPT; + Size operator()() const; + const int& operator[](int i) const; + int& operator[](int i); + operator const int*() const CV_NOEXCEPT; // TODO OpenCV 4.0: drop this + bool operator == (const MatSize& sz) const CV_NOEXCEPT; + bool operator != (const MatSize& sz) const CV_NOEXCEPT; + + int* p; +}; + +struct CV_EXPORTS MatStep +{ + MatStep() CV_NOEXCEPT; + explicit MatStep(size_t s) CV_NOEXCEPT; + const size_t& operator[](int i) const CV_NOEXCEPT; + size_t& operator[](int i) CV_NOEXCEPT; + operator size_t() const; + MatStep& operator = (size_t s); + + size_t* p; + size_t buf[2]; +protected: + MatStep& operator = (const MatStep&); +}; + +/** @example samples/cpp/cout_mat.cpp +An example demonstrating the serial out capabilities of cv::Mat +*/ + + /** @brief n-dimensional dense array class \anchor CVMat_Details + +The class Mat represents an n-dimensional dense numerical single-channel or multi-channel array. It +can be used to store real or complex-valued vectors and matrices, grayscale or color images, voxel +volumes, vector fields, point clouds, tensors, histograms (though, very high-dimensional histograms +may be better stored in a SparseMat ). The data layout of the array `M` is defined by the array +`M.step[]`, so that the address of element \f$(i_0,...,i_{M.dims-1})\f$, where \f$0\leq i_k= M.step[i+1]` (in fact, `M.step[i] >= M.step[i+1]*M.size[i+1]` ). This means +that 2-dimensional matrices are stored row-by-row, 3-dimensional matrices are stored plane-by-plane, +and so on. M.step[M.dims-1] is minimal and always equal to the element size M.elemSize() . + +So, the data layout in Mat is compatible with the majority of dense array types from the standard +toolkits and SDKs, such as Numpy (ndarray), Win32 (independent device bitmaps), and others, +that is, with any array that uses *steps* (or *strides*) to compute the position of a pixel. +Due to this compatibility, it is possible to make a Mat header for user-allocated data and process +it in-place using OpenCV functions. + +There are many different ways to create a Mat object. The most popular options are listed below: + +- Use the create(nrows, ncols, type) method or the similar Mat(nrows, ncols, type[, fillValue]) +constructor. A new array of the specified size and type is allocated. type has the same meaning as +in the cvCreateMat method. For example, CV_8UC1 means a 8-bit single-channel array, CV_32FC2 +means a 2-channel (complex) floating-point array, and so on. +@code + // make a 7x7 complex matrix filled with 1+3j. + Mat M(7,7,CV_32FC2,Scalar(1,3)); + // and now turn M to a 100x60 15-channel 8-bit matrix. + // The old content will be deallocated + M.create(100,60,CV_8UC(15)); +@endcode +As noted in the introduction to this chapter, create() allocates only a new array when the shape +or type of the current array are different from the specified ones. + +- Create a multi-dimensional array: +@code + // create a 100x100x100 8-bit array + int sz[] = {100, 100, 100}; + Mat bigCube(3, sz, CV_8U, Scalar::all(0)); +@endcode +It passes the number of dimensions =1 to the Mat constructor but the created array will be +2-dimensional with the number of columns set to 1. So, Mat::dims is always \>= 2 (can also be 0 +when the array is empty). + +- Use a copy constructor or assignment operator where there can be an array or expression on the +right side (see below). As noted in the introduction, the array assignment is an O(1) operation +because it only copies the header and increases the reference counter. The Mat::clone() method can +be used to get a full (deep) copy of the array when you need it. + +- Construct a header for a part of another array. It can be a single row, single column, several +rows, several columns, rectangular region in the array (called a *minor* in algebra) or a +diagonal. Such operations are also O(1) because the new header references the same data. You can +actually modify a part of the array using this feature, for example: +@code + // add the 5-th row, multiplied by 3 to the 3rd row + M.row(3) = M.row(3) + M.row(5)*3; + // now copy the 7-th column to the 1-st column + // M.col(1) = M.col(7); // this will not work + Mat M1 = M.col(1); + M.col(7).copyTo(M1); + // create a new 320x240 image + Mat img(Size(320,240),CV_8UC3); + // select a ROI + Mat roi(img, Rect(10,10,100,100)); + // fill the ROI with (0,255,0) (which is green in RGB space); + // the original 320x240 image will be modified + roi = Scalar(0,255,0); +@endcode +Due to the additional datastart and dataend members, it is possible to compute a relative +sub-array position in the main *container* array using locateROI(): +@code + Mat A = Mat::eye(10, 10, CV_32S); + // extracts A columns, 1 (inclusive) to 3 (exclusive). + Mat B = A(Range::all(), Range(1, 3)); + // extracts B rows, 5 (inclusive) to 9 (exclusive). + // that is, C \~ A(Range(5, 9), Range(1, 3)) + Mat C = B(Range(5, 9), Range::all()); + Size size; Point ofs; + C.locateROI(size, ofs); + // size will be (width=10,height=10) and the ofs will be (x=1, y=5) +@endcode +As in case of whole matrices, if you need a deep copy, use the `clone()` method of the extracted +sub-matrices. + +- Make a header for user-allocated data. It can be useful to do the following: + -# Process "foreign" data using OpenCV (for example, when you implement a DirectShow\* filter or + a processing module for gstreamer, and so on). For example: + @code + Mat process_video_frame(const unsigned char* pixels, + int width, int height, int step) + { + // wrap input buffer + Mat img(height, width, CV_8UC3, (unsigned char*)pixels, step); + + Mat result; + GaussianBlur(img, result, Size(7, 7), 1.5, 1.5); + + return result; + } + @endcode + -# Quickly initialize small matrices and/or get a super-fast element access. + @code + double m[3][3] = {{a, b, c}, {d, e, f}, {g, h, i}}; + Mat M = Mat(3, 3, CV_64F, m).inv(); + @endcode + . + +- Use MATLAB-style array initializers, zeros(), ones(), eye(), for example: +@code + // create a double-precision identity matrix and add it to M. + M += Mat::eye(M.rows, M.cols, CV_64F); +@endcode + +- Use a comma-separated initializer: +@code + // create a 3x3 double-precision identity matrix + Mat M = (Mat_(3,3) << 1, 0, 0, 0, 1, 0, 0, 0, 1); +@endcode +With this approach, you first call a constructor of the Mat class with the proper parameters, and +then you just put `<< operator` followed by comma-separated values that can be constants, +variables, expressions, and so on. Also, note the extra parentheses required to avoid compilation +errors. + +Once the array is created, it is automatically managed via a reference-counting mechanism. If the +array header is built on top of user-allocated data, you should handle the data by yourself. The +array data is deallocated when no one points to it. If you want to release the data pointed by a +array header before the array destructor is called, use Mat::release(). + +The next important thing to learn about the array class is element access. This manual already +described how to compute an address of each array element. Normally, you are not required to use the +formula directly in the code. If you know the array element type (which can be retrieved using the +method Mat::type() ), you can access the element \f$M_{ij}\f$ of a 2-dimensional array as: +@code + M.at(i,j) += 1.f; +@endcode +assuming that `M` is a double-precision floating-point array. There are several variants of the method +at for a different number of dimensions. + +If you need to process a whole row of a 2D array, the most efficient way is to get the pointer to +the row first, and then just use the plain C operator [] : +@code + // compute sum of positive matrix elements + // (assuming that M is a double-precision matrix) + double sum=0; + for(int i = 0; i < M.rows; i++) + { + const double* Mi = M.ptr(i); + for(int j = 0; j < M.cols; j++) + sum += std::max(Mi[j], 0.); + } +@endcode +Some operations, like the one above, do not actually depend on the array shape. They just process +elements of an array one by one (or elements from multiple arrays that have the same coordinates, +for example, array addition). Such operations are called *element-wise*. It makes sense to check +whether all the input/output arrays are continuous, namely, have no gaps at the end of each row. If +yes, process them as a long single row: +@code + // compute the sum of positive matrix elements, optimized variant + double sum=0; + int cols = M.cols, rows = M.rows; + if(M.isContinuous()) + { + cols *= rows; + rows = 1; + } + for(int i = 0; i < rows; i++) + { + const double* Mi = M.ptr(i); + for(int j = 0; j < cols; j++) + sum += std::max(Mi[j], 0.); + } +@endcode +In case of the continuous matrix, the outer loop body is executed just once. So, the overhead is +smaller, which is especially noticeable in case of small matrices. + +Finally, there are STL-style iterators that are smart enough to skip gaps between successive rows: +@code + // compute sum of positive matrix elements, iterator-based variant + double sum=0; + MatConstIterator_ it = M.begin(), it_end = M.end(); + for(; it != it_end; ++it) + sum += std::max(*it, 0.); +@endcode +The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, +including std::sort(). + +@note Matrix Expressions and arithmetic see MatExpr +*/ +class CV_EXPORTS Mat +{ +public: + /** + These are various constructors that form a matrix. As noted in the AutomaticAllocation, often + the default constructor is enough, and the proper matrix will be allocated by an OpenCV function. + The constructed matrix can further be assigned to another matrix or matrix expression or can be + allocated with Mat::create . In the former case, the old content is de-referenced. + */ + Mat() CV_NOEXCEPT; + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(int rows, int cols, int type); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(Size size, int type); + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(int rows, int cols, int type, const Scalar& s); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(Size size, int type, const Scalar& s); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(int ndims, const int* sizes, int type); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + */ + Mat(const std::vector& sizes, int type); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(int ndims, const int* sizes, int type, const Scalar& s); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param s An optional value to initialize each matrix element with. To set all the matrix elements to + the particular value after the construction, use the assignment operator + Mat::operator=(const Scalar& value) . + */ + Mat(const std::vector& sizes, int type, const Scalar& s); + + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + */ + Mat(const Mat& m); + + /** @overload + @param rows Number of rows in a 2D array. + @param cols Number of columns in a 2D array. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP); + + /** @overload + @param size 2D array size: Size(cols, rows) . In the Size() constructor, the number of rows and the + number of columns go in the reverse order. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(Size size, int type, void* data, size_t step=AUTO_STEP); + + /** @overload + @param ndims Array dimensionality. + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always + set to the element size). If not specified, the matrix is assumed to be continuous. + */ + Mat(int ndims, const int* sizes, int type, void* data, const size_t* steps=0); + + /** @overload + @param sizes Array of integers specifying an n-dimensional array shape. + @param type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param steps Array of ndims-1 steps in case of a multi-dimensional array (the last step is always + set to the element size). If not specified, the matrix is assumed to be continuous. + */ + Mat(const std::vector& sizes, int type, void* data, const size_t* steps=0); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param rowRange Range of the m rows to take. As usual, the range start is inclusive and the range + end is exclusive. Use Range::all() to take all the rows. + @param colRange Range of the m columns to take. Use Range::all() to take all the columns. + */ + Mat(const Mat& m, const Range& rowRange, const Range& colRange=Range::all()); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param roi Region of interest. + */ + Mat(const Mat& m, const Rect& roi); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param ranges Array of selected ranges of m along each dimensionality. + */ + Mat(const Mat& m, const Range* ranges); + + /** @overload + @param m Array that (as a whole or partly) is assigned to the constructed matrix. No data is copied + by these constructors. Instead, the header pointing to m data or its sub-array is constructed and + associated with it. The reference counter, if any, is incremented. So, when you modify the matrix + formed using such a constructor, you also modify the corresponding elements of m . If you want to + have an independent copy of the sub-array, use Mat::clone() . + @param ranges Array of selected ranges of m along each dimensionality. + */ + Mat(const Mat& m, const std::vector& ranges); + + /** @overload + @param vec STL vector whose elements form the matrix. The matrix has a single column and the number + of rows equal to the number of vector elements. Type of the matrix matches the type of vector + elements. The constructor can handle arbitrary types, for which there is a properly declared + DataType . This means that the vector elements must be primitive numbers or uni-type numerical + tuples of numbers. Mixed-type structures are not supported. The corresponding constructor is + explicit. Since STL vectors are not automatically converted to Mat instances, you should write + Mat(vec) explicitly. Unless you copy the data into the matrix ( copyData=true ), no new elements + will be added to the vector because it can potentially yield vector data reallocation, and, thus, + the matrix data pointer will be invalid. + @param copyData Flag to specify whether the underlying data of the STL vector should be copied + to (true) or shared with (false) the newly constructed matrix. When the data is copied, the + allocated buffer is managed using Mat reference counting mechanism. While the data is shared, + the reference counter is NULL, and you should not deallocate the data until the matrix is + destructed. + */ + template explicit Mat(const std::vector<_Tp>& vec, bool copyData=false); + + /** @overload + */ + template::value>::type> + explicit Mat(const std::initializer_list<_Tp> list); + + /** @overload + */ + template explicit Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list); + + /** @overload + */ + template explicit Mat(const std::array<_Tp, _Nm>& arr, bool copyData=false); + + /** @overload + */ + template explicit Mat(const Vec<_Tp, n>& vec, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Matx<_Tp, m, n>& mtx, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Point_<_Tp>& pt, bool copyData=true); + + /** @overload + */ + template explicit Mat(const Point3_<_Tp>& pt, bool copyData=true); + + /** @overload + */ + template explicit Mat(const MatCommaInitializer_<_Tp>& commaInitializer); + + //! download data from GpuMat + explicit Mat(const cuda::GpuMat& m); + + //! destructor - calls release() + ~Mat(); + + /** @brief assignment operators + + These are available assignment operators. Since they all are very different, make sure to read the + operator parameters description. + @param m Assigned, right-hand-side matrix. Matrix assignment is an O(1) operation. This means that + no data is copied but the data is shared and the reference counter, if any, is incremented. Before + assigning new data, the old data is de-referenced via Mat::release . + */ + Mat& operator = (const Mat& m); + + /** @overload + @param expr Assigned matrix expression object. As opposite to the first form of the assignment + operation, the second form can reuse already allocated matrix if it has the right size and type to + fit the matrix expression result. It is automatically handled by the real function that the matrix + expressions is expanded to. For example, C=A+B is expanded to add(A, B, C), and add takes care of + automatic C reallocation. + */ + Mat& operator = (const MatExpr& expr); + + //! retrieve UMat from Mat + UMat getUMat(AccessFlag accessFlags, UMatUsageFlags usageFlags = USAGE_DEFAULT) const; + + /** @brief Creates a matrix header for the specified matrix row. + + The method makes a new header for the specified matrix row and returns it. This is an O(1) + operation, regardless of the matrix size. The underlying data of the new matrix is shared with the + original matrix. Here is the example of one of the classical basic matrix processing operations, + axpy, used by LU and many other algorithms: + @code + inline void matrix_axpy(Mat& A, int i, int j, double alpha) + { + A.row(i) += A.row(j)*alpha; + } + @endcode + @note In the current implementation, the following code does not work as expected: + @code + Mat A; + ... + A.row(i) = A.row(j); // will not work + @endcode + This happens because A.row(i) forms a temporary header that is further assigned to another header. + Remember that each of these operations is O(1), that is, no data is copied. Thus, the above + assignment is not true if you may have expected the j-th row to be copied to the i-th row. To + achieve that, you should either turn this simple assignment into an expression or use the + Mat::copyTo method: + @code + Mat A; + ... + // works, but looks a bit obscure. + A.row(i) = A.row(j) + 0; + // this is a bit longer, but the recommended method. + A.row(j).copyTo(A.row(i)); + @endcode + @param y A 0-based row index. + */ + Mat row(int y) const; + + /** @brief Creates a matrix header for the specified matrix column. + + The method makes a new header for the specified matrix column and returns it. This is an O(1) + operation, regardless of the matrix size. The underlying data of the new matrix is shared with the + original matrix. See also the Mat::row description. + @param x A 0-based column index. + */ + Mat col(int x) const; + + /** @brief Creates a matrix header for the specified row span. + + The method makes a new header for the specified row span of the matrix. Similarly to Mat::row and + Mat::col , this is an O(1) operation. + @param startrow An inclusive 0-based start index of the row span. + @param endrow An exclusive 0-based ending index of the row span. + */ + Mat rowRange(int startrow, int endrow) const; + + /** @overload + @param r Range structure containing both the start and the end indices. + */ + Mat rowRange(const Range& r) const; + + /** @brief Creates a matrix header for the specified column span. + + The method makes a new header for the specified column span of the matrix. Similarly to Mat::row and + Mat::col , this is an O(1) operation. + @param startcol An inclusive 0-based start index of the column span. + @param endcol An exclusive 0-based ending index of the column span. + */ + Mat colRange(int startcol, int endcol) const; + + /** @overload + @param r Range structure containing both the start and the end indices. + */ + Mat colRange(const Range& r) const; + + /** @brief Extracts a diagonal from a matrix + + The method makes a new header for the specified matrix diagonal. The new matrix is represented as a + single-column matrix. Similarly to Mat::row and Mat::col, this is an O(1) operation. + @param d index of the diagonal, with the following values: + - `d=0` is the main diagonal. + - `d<0` is a diagonal from the lower half. For example, d=-1 means the diagonal is set + immediately below the main one. + - `d>0` is a diagonal from the upper half. For example, d=1 means the diagonal is set + immediately above the main one. + For example: + @code + Mat m = (Mat_(3,3) << + 1,2,3, + 4,5,6, + 7,8,9); + Mat d0 = m.diag(0); + Mat d1 = m.diag(1); + Mat d_1 = m.diag(-1); + @endcode + The resulting matrices are + @code + d0 = + [1; + 5; + 9] + d1 = + [2; + 6] + d_1 = + [4; + 8] + @endcode + */ + Mat diag(int d=0) const; + + /** @brief creates a diagonal matrix + + The method creates a square diagonal matrix from specified main diagonal. + @param d One-dimensional matrix that represents the main diagonal. + */ + CV_NODISCARD_STD static Mat diag(const Mat& d); + + /** @brief Creates a full copy of the array and the underlying data. + + The method creates a full copy of the array. The original step[] is not taken into account. So, the + array copy is a continuous array occupying total()*elemSize() bytes. + */ + CV_NODISCARD_STD Mat clone() const; + + /** @brief Copies the matrix to another one. + + The method copies the matrix data to another matrix. Before copying the data, the method invokes : + @code + m.create(this->size(), this->type()); + @endcode + so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the + function does not handle the case of a partial overlap between the source and the destination + matrices. + + When the operation mask is specified, if the Mat::create call shown above reallocates the matrix, + the newly allocated matrix is initialized with all zeros before copying the data. + @param m Destination matrix. If it does not have a proper size or type before the operation, it is + reallocated. + */ + void copyTo( OutputArray m ) const; + + /** @overload + @param m Destination matrix. If it does not have a proper size or type before the operation, it is + reallocated. + @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix + elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels. + */ + void copyTo( OutputArray m, InputArray mask ) const; + + /** @brief Converts an array to another data type with optional scaling. + + The method converts source pixel values to the target data type. saturate_cast\<\> is applied at + the end to avoid possible overflows: + + \f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] + @param m output matrix; if it does not have a proper size or type before the operation, it is + reallocated. + @param rtype desired output matrix type or, rather, the depth since the number of channels are the + same as the input has; if rtype is negative, the output matrix will have the same type as the input. + @param alpha optional scale factor. + @param beta optional delta added to the scaled values. + */ + void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; + + /** @brief Provides a functional form of convertTo. + + This is an internally used method called by the @ref MatrixExpressions engine. + @param m Destination array. + @param type Desired destination array depth (or -1 if it should be the same as the source type). + */ + void assignTo( Mat& m, int type=-1 ) const; + + /** @brief Sets all or some of the array elements to the specified value. + @param s Assigned scalar converted to the actual array type. + */ + Mat& operator = (const Scalar& s); + + /** @brief Sets all or some of the array elements to the specified value. + + This is an advanced variant of the Mat::operator=(const Scalar& s) operator. + @param value Assigned scalar converted to the actual array type. + @param mask Operation mask of the same size as \*this. Its non-zero elements indicate which matrix + elements need to be copied. The mask has to be of type CV_8U and can have 1 or multiple channels + */ + Mat& setTo(InputArray value, InputArray mask=noArray()); + + /** @brief Changes the shape and/or the number of channels of a 2D matrix without copying the data. + + The method makes a new matrix header for \*this elements. The new matrix may have a different size + and/or different number of channels. Any combination is possible if: + - No extra elements are included into the new matrix and no elements are excluded. Consequently, + the product rows\*cols\*channels() must stay the same after the transformation. + - No data is copied. That is, this is an O(1) operation. Consequently, if you change the number of + rows, or the operation changes the indices of elements row in some other way, the matrix must be + continuous. See Mat::isContinuous . + + For example, if there is a set of 3D points stored as an STL vector, and you want to represent the + points as a 3xN matrix, do the following: + @code + std::vector vec; + ... + Mat pointMat = Mat(vec). // convert vector to Mat, O(1) operation + reshape(1). // make Nx3 1-channel matrix out of Nx1 3-channel. + // Also, an O(1) operation + t(); // finally, transpose the Nx3 matrix. + // This involves copying all the elements + @endcode + 3-channel 2x2 matrix reshaped to 1-channel 4x3 matrix, each column has values from one of original channels: + @code + Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); + vector new_shape {4, 3}; + m = m.reshape(1, new_shape); + @endcode + or: + @code + Mat m(Size(2, 2), CV_8UC3, Scalar(1, 2, 3)); + const int new_shape[] = {4, 3}; + m = m.reshape(1, 2, new_shape); + @endcode + @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + @param rows New number of rows. If the parameter is 0, the number of rows remains the same. + */ + Mat reshape(int cn, int rows=0) const; + + /** @overload + * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + * @param newndims New number of dimentions. + * @param newsz Array with new matrix size by all dimentions. If some sizes are zero, + * the original sizes in those dimensions are presumed. + */ + Mat reshape(int cn, int newndims, const int* newsz) const; + + /** @overload + * @param cn New number of channels. If the parameter is 0, the number of channels remains the same. + * @param newshape Vector with new matrix size by all dimentions. If some sizes are zero, + * the original sizes in those dimensions are presumed. + */ + Mat reshape(int cn, const std::vector& newshape) const; + + /** @brief Transposes a matrix. + + The method performs matrix transposition by means of matrix expressions. It does not perform the + actual transposition but returns a temporary matrix transposition object that can be further used as + a part of more complex matrix expressions or can be assigned to a matrix: + @code + Mat A1 = A + Mat::eye(A.size(), A.type())*lambda; + Mat C = A1.t()*A1; // compute (A + lambda*I)^t * (A + lamda*I) + @endcode + */ + MatExpr t() const; + + /** @brief Inverses a matrix. + + The method performs a matrix inversion by means of matrix expressions. This means that a temporary + matrix inversion object is returned by the method and can be used further as a part of more complex + matrix expressions or can be assigned to a matrix. + @param method Matrix inversion method. One of cv::DecompTypes + */ + MatExpr inv(int method=DECOMP_LU) const; + + /** @brief Performs an element-wise multiplication or division of the two matrices. + + The method returns a temporary object encoding per-element array multiplication, with optional + scale. Note that this is not a matrix multiplication that corresponds to a simpler "\*" operator. + + Example: + @code + Mat C = A.mul(5/B); // equivalent to divide(A, B, C, 5) + @endcode + @param m Another array of the same type and the same size as \*this, or a matrix expression. + @param scale Optional scale factor. + */ + MatExpr mul(InputArray m, double scale=1) const; + + /** @brief Computes a cross-product of two 3-element vectors. + + The method computes a cross-product of two 3-element vectors. The vectors must be 3-element + floating-point vectors of the same shape and size. The result is another 3-element vector of the + same shape and type as operands. + @param m Another cross-product operand. + */ + Mat cross(InputArray m) const; + + /** @brief Computes a dot-product of two vectors. + + The method computes a dot-product of two matrices. If the matrices are not single-column or + single-row vectors, the top-to-bottom left-to-right scan ordering is used to treat them as 1D + vectors. The vectors must have the same size and type. If the matrices have more than one channel, + the dot products from all the channels are summed together. + @param m another dot-product operand. + */ + double dot(InputArray m) const; + + /** @brief Returns a zero array of the specified size and type. + + The method returns a Matlab-style zero array initializer. It can be used to quickly form a constant + array as a function parameter, part of a matrix expression, or as a matrix initializer: + @code + Mat A; + A = Mat::zeros(3, 3, CV_32F); + @endcode + In the example above, a new matrix is allocated only if A is not a 3x3 floating-point matrix. + Otherwise, the existing matrix A is filled with zeros. + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr zeros(int rows, int cols, int type); + + /** @overload + @param size Alternative to the matrix size specification Size(cols, rows) . + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr zeros(Size size, int type); + + /** @overload + @param ndims Array dimensionality. + @param sz Array of integers specifying the array shape. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr zeros(int ndims, const int* sz, int type); + + /** @brief Returns an array of all 1's of the specified size and type. + + The method returns a Matlab-style 1's array initializer, similarly to Mat::zeros. Note that using + this method you can initialize an array with an arbitrary value, using the following Matlab idiom: + @code + Mat A = Mat::ones(100, 100, CV_8U)*3; // make 100x100 matrix filled with 3. + @endcode + The above operation does not form a 100x100 matrix of 1's and then multiply it by 3. Instead, it + just remembers the scale factor (3 in this case) and use it when actually invoking the matrix + initializer. + @note In case of multi-channels type, only the first channel will be initialized with 1's, the + others will be set to 0's. + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr ones(int rows, int cols, int type); + + /** @overload + @param size Alternative to the matrix size specification Size(cols, rows) . + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr ones(Size size, int type); + + /** @overload + @param ndims Array dimensionality. + @param sz Array of integers specifying the array shape. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr ones(int ndims, const int* sz, int type); + + /** @brief Returns an identity matrix of the specified size and type. + + The method returns a Matlab-style identity matrix initializer, similarly to Mat::zeros. Similarly to + Mat::ones, you can use a scale operation to create a scaled identity matrix efficiently: + @code + // make a 4x4 diagonal matrix with 0.1's on the diagonal. + Mat A = Mat::eye(4, 4, CV_32F)*0.1; + @endcode + @note In case of multi-channels type, identity matrix will be initialized only for the first channel, + the others will be set to 0's + @param rows Number of rows. + @param cols Number of columns. + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr eye(int rows, int cols, int type); + + /** @overload + @param size Alternative matrix size specification as Size(cols, rows) . + @param type Created matrix type. + */ + CV_NODISCARD_STD static MatExpr eye(Size size, int type); + + /** @brief Allocates new array data if needed. + + This is one of the key Mat methods. Most new-style OpenCV functions and methods that produce arrays + call this method for each output array. The method uses the following algorithm: + + -# If the current array shape and the type match the new ones, return immediately. Otherwise, + de-reference the previous data by calling Mat::release. + -# Initialize the new header. + -# Allocate the new data of total()\*elemSize() bytes. + -# Allocate the new, associated with the data, reference counter and set it to 1. + + Such a scheme makes the memory management robust and efficient at the same time and helps avoid + extra typing for you. This means that usually there is no need to explicitly allocate output arrays. + That is, instead of writing: + @code + Mat color; + ... + Mat gray(color.rows, color.cols, color.depth()); + cvtColor(color, gray, COLOR_BGR2GRAY); + @endcode + you can simply write: + @code + Mat color; + ... + Mat gray; + cvtColor(color, gray, COLOR_BGR2GRAY); + @endcode + because cvtColor, as well as the most of OpenCV functions, calls Mat::create() for the output array + internally. + @param rows New number of rows. + @param cols New number of columns. + @param type New matrix type. + */ + void create(int rows, int cols, int type); + + /** @overload + @param size Alternative new matrix size specification: Size(cols, rows) + @param type New matrix type. + */ + void create(Size size, int type); + + /** @overload + @param ndims New array dimensionality. + @param sizes Array of integers specifying a new array shape. + @param type New matrix type. + */ + void create(int ndims, const int* sizes, int type); + + /** @overload + @param sizes Array of integers specifying a new array shape. + @param type New matrix type. + */ + void create(const std::vector& sizes, int type); + + /** @brief Increments the reference counter. + + The method increments the reference counter associated with the matrix data. If the matrix header + points to an external data set (see Mat::Mat ), the reference counter is NULL, and the method has no + effect in this case. Normally, to avoid memory leaks, the method should not be called explicitly. It + is called implicitly by the matrix assignment operator. The reference counter increment is an atomic + operation on the platforms that support it. Thus, it is safe to operate on the same matrices + asynchronously in different threads. + */ + void addref(); + + /** @brief Decrements the reference counter and deallocates the matrix if needed. + + The method decrements the reference counter associated with the matrix data. When the reference + counter reaches 0, the matrix data is deallocated and the data and the reference counter pointers + are set to NULL's. If the matrix header points to an external data set (see Mat::Mat ), the + reference counter is NULL, and the method has no effect in this case. + + This method can be called manually to force the matrix data deallocation. But since this method is + automatically called in the destructor, or by any other method that changes the data pointer, it is + usually not needed. The reference counter decrement and check for 0 is an atomic operation on the + platforms that support it. Thus, it is safe to operate on the same matrices asynchronously in + different threads. + */ + void release(); + + //! internal use function, consider to use 'release' method instead; deallocates the matrix data + void deallocate(); + //! internal use function; properly re-allocates _size, _step arrays + void copySize(const Mat& m); + + /** @brief Reserves space for the certain number of rows. + + The method reserves space for sz rows. If the matrix already has enough space to store sz rows, + nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method + emulates the corresponding method of the STL vector class. + @param sz Number of rows. + */ + void reserve(size_t sz); + + /** @brief Reserves space for the certain number of bytes. + + The method reserves space for sz bytes. If the matrix already has enough space to store sz bytes, + nothing happens. If matrix has to be reallocated its previous content could be lost. + @param sz Number of bytes. + */ + void reserveBuffer(size_t sz); + + /** @brief Changes the number of matrix rows. + + The methods change the number of matrix rows. If the matrix is reallocated, the first + min(Mat::rows, sz) rows are preserved. The methods emulate the corresponding methods of the STL + vector class. + @param sz New number of rows. + */ + void resize(size_t sz); + + /** @overload + @param sz New number of rows. + @param s Value assigned to the newly added elements. + */ + void resize(size_t sz, const Scalar& s); + + //! internal function + void push_back_(const void* elem); + + /** @brief Adds elements to the bottom of the matrix. + + The methods add one or more elements to the bottom of the matrix. They emulate the corresponding + method of the STL vector class. When elem is Mat , its type and the number of columns must be the + same as in the container matrix. + @param elem Added element(s). + */ + template void push_back(const _Tp& elem); + + /** @overload + @param elem Added element(s). + */ + template void push_back(const Mat_<_Tp>& elem); + + /** @overload + @param elem Added element(s). + */ + template void push_back(const std::vector<_Tp>& elem); + + /** @overload + @param m Added line(s). + */ + void push_back(const Mat& m); + + /** @brief Removes elements from the bottom of the matrix. + + The method removes one or more rows from the bottom of the matrix. + @param nelems Number of removed rows. If it is greater than the total number of rows, an exception + is thrown. + */ + void pop_back(size_t nelems=1); + + /** @brief Locates the matrix header within a parent matrix. + + After you extracted a submatrix from a matrix using Mat::row, Mat::col, Mat::rowRange, + Mat::colRange, and others, the resultant submatrix points just to the part of the original big + matrix. However, each submatrix contains information (represented by datastart and dataend + fields) that helps reconstruct the original matrix size and the position of the extracted + submatrix within the original matrix. The method locateROI does exactly that. + @param wholeSize Output parameter that contains the size of the whole matrix containing *this* + as a part. + @param ofs Output parameter that contains an offset of *this* inside the whole matrix. + */ + void locateROI( Size& wholeSize, Point& ofs ) const; + + /** @brief Adjusts a submatrix size and position within the parent matrix. + + The method is complimentary to Mat::locateROI . The typical use of these functions is to determine + the submatrix position within the parent matrix and then shift the position somehow. Typically, it + can be required for filtering operations when pixels outside of the ROI should be taken into + account. When all the method parameters are positive, the ROI needs to grow in all directions by the + specified amount, for example: + @code + A.adjustROI(2, 2, 2, 2); + @endcode + In this example, the matrix size is increased by 4 elements in each direction. The matrix is shifted + by 2 elements to the left and 2 elements up, which brings in all the necessary pixels for the + filtering with the 5x5 kernel. + + adjustROI forces the adjusted ROI to be inside of the parent matrix that is boundaries of the + adjusted ROI are constrained by boundaries of the parent matrix. For example, if the submatrix A is + located in the first row of a parent matrix and you called A.adjustROI(2, 2, 2, 2) then A will not + be increased in the upward direction. + + The function is used internally by the OpenCV filtering functions, like filter2D , morphological + operations, and so on. + @param dtop Shift of the top submatrix boundary upwards. + @param dbottom Shift of the bottom submatrix boundary downwards. + @param dleft Shift of the left submatrix boundary to the left. + @param dright Shift of the right submatrix boundary to the right. + @sa copyMakeBorder + */ + Mat& adjustROI( int dtop, int dbottom, int dleft, int dright ); + + /** @brief Extracts a rectangular submatrix. + + The operators make a new header for the specified sub-array of \*this . They are the most + generalized forms of Mat::row, Mat::col, Mat::rowRange, and Mat::colRange . For example, + `A(Range(0, 10), Range::all())` is equivalent to `A.rowRange(0, 10)`. Similarly to all of the above, + the operators are O(1) operations, that is, no matrix data is copied. + @param rowRange Start and end row of the extracted submatrix. The upper boundary is not included. To + select all the rows, use Range::all(). + @param colRange Start and end column of the extracted submatrix. The upper boundary is not included. + To select all the columns, use Range::all(). + */ + Mat operator()( Range rowRange, Range colRange ) const; + + /** @overload + @param roi Extracted submatrix specified as a rectangle. + */ + Mat operator()( const Rect& roi ) const; + + /** @overload + @param ranges Array of selected ranges along each array dimension. + */ + Mat operator()( const Range* ranges ) const; + + /** @overload + @param ranges Array of selected ranges along each array dimension. + */ + Mat operator()(const std::vector& ranges) const; + + template operator std::vector<_Tp>() const; + template operator Vec<_Tp, n>() const; + template operator Matx<_Tp, m, n>() const; + + template operator std::array<_Tp, _Nm>() const; + + /** @brief Reports whether the matrix is continuous or not. + + The method returns true if the matrix elements are stored continuously without gaps at the end of + each row. Otherwise, it returns false. Obviously, 1x1 or 1xN matrices are always continuous. + Matrices created with Mat::create are always continuous. But if you extract a part of the matrix + using Mat::col, Mat::diag, and so on, or constructed a matrix header for externally allocated data, + such matrices may no longer have this property. + + The continuity flag is stored as a bit in the Mat::flags field and is computed automatically when + you construct a matrix header. Thus, the continuity check is a very fast operation, though + theoretically it could be done as follows: + @code + // alternative implementation of Mat::isContinuous() + bool myCheckMatContinuity(const Mat& m) + { + //return (m.flags & Mat::CONTINUOUS_FLAG) != 0; + return m.rows == 1 || m.step == m.cols*m.elemSize(); + } + @endcode + The method is used in quite a few of OpenCV functions. The point is that element-wise operations + (such as arithmetic and logical operations, math functions, alpha blending, color space + transformations, and others) do not depend on the image geometry. Thus, if all the input and output + arrays are continuous, the functions can process them as very long single-row vectors. The example + below illustrates how an alpha-blending function can be implemented: + @code + template + void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) + { + const float alpha_scale = (float)std::numeric_limits::max(), + inv_scale = 1.f/alpha_scale; + + CV_Assert( src1.type() == src2.type() && + src1.type() == CV_MAKETYPE(traits::Depth::value, 4) && + src1.size() == src2.size()); + Size size = src1.size(); + dst.create(size, src1.type()); + + // here is the idiom: check the arrays for continuity and, + // if this is the case, + // treat the arrays as 1D vectors + if( src1.isContinuous() && src2.isContinuous() && dst.isContinuous() ) + { + size.width *= size.height; + size.height = 1; + } + size.width *= 4; + + for( int i = 0; i < size.height; i++ ) + { + // when the arrays are continuous, + // the outer loop is executed only once + const T* ptr1 = src1.ptr(i); + const T* ptr2 = src2.ptr(i); + T* dptr = dst.ptr(i); + + for( int j = 0; j < size.width; j += 4 ) + { + float alpha = ptr1[j+3]*inv_scale, beta = ptr2[j+3]*inv_scale; + dptr[j] = saturate_cast(ptr1[j]*alpha + ptr2[j]*beta); + dptr[j+1] = saturate_cast(ptr1[j+1]*alpha + ptr2[j+1]*beta); + dptr[j+2] = saturate_cast(ptr1[j+2]*alpha + ptr2[j+2]*beta); + dptr[j+3] = saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale); + } + } + } + @endcode + This approach, while being very simple, can boost the performance of a simple element-operation by + 10-20 percents, especially if the image is rather small and the operation is quite simple. + + Another OpenCV idiom in this function, a call of Mat::create for the destination array, that + allocates the destination array unless it already has the proper size and type. And while the newly + allocated arrays are always continuous, you still need to check the destination array because + Mat::create does not always allocate a new matrix. + */ + bool isContinuous() const; + + //! returns true if the matrix is a submatrix of another matrix + bool isSubmatrix() const; + + /** @brief Returns the matrix element size in bytes. + + The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , + the method returns 3\*sizeof(short) or 6. + */ + size_t elemSize() const; + + /** @brief Returns the size of each matrix element channel in bytes. + + The method returns the matrix element channel size in bytes, that is, it ignores the number of + channels. For example, if the matrix type is CV_16SC3 , the method returns sizeof(short) or 2. + */ + size_t elemSize1() const; + + /** @brief Returns the type of a matrix element. + + The method returns a matrix element type. This is an identifier compatible with the CvMat type + system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. + */ + int type() const; + + /** @brief Returns the depth of a matrix element. + + The method returns the identifier of the matrix element depth (the type of each individual channel). + For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of + matrix types contains the following values: + - CV_8U - 8-bit unsigned integers ( 0..255 ) + - CV_8S - 8-bit signed integers ( -128..127 ) + - CV_16U - 16-bit unsigned integers ( 0..65535 ) + - CV_16S - 16-bit signed integers ( -32768..32767 ) + - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) + - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) + - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) + */ + int depth() const; + + /** @brief Returns the number of matrix channels. + + The method returns the number of matrix channels. + */ + int channels() const; + + /** @brief Returns a normalized step. + + The method returns a matrix step divided by Mat::elemSize1() . It can be useful to quickly access an + arbitrary matrix element. + */ + size_t step1(int i=0) const; + + /** @brief Returns true if the array has no elements. + + The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and + resize() methods `M.total() == 0` does not imply that `M.data == NULL`. + */ + bool empty() const; + + /** @brief Returns the total number of array elements. + + The method returns the number of array elements (a number of pixels if the array represents an + image). + */ + size_t total() const; + + /** @brief Returns the total number of array elements. + + The method returns the number of elements within a certain sub-array slice with startDim <= dim < endDim + */ + size_t total(int startDim, int endDim=INT_MAX) const; + + /** + * @param elemChannels Number of channels or number of columns the matrix should have. + * For a 2-D matrix, when the matrix has only 1 column, then it should have + * elemChannels channels; When the matrix has only 1 channel, + * then it should have elemChannels columns. + * For a 3-D matrix, it should have only one channel. Furthermore, + * if the number of planes is not one, then the number of rows + * within every plane has to be 1; if the number of rows within + * every plane is not 1, then the number of planes has to be 1. + * @param depth The depth the matrix should have. Set it to -1 when any depth is fine. + * @param requireContinuous Set it to true to require the matrix to be continuous + * @return -1 if the requirement is not satisfied. + * Otherwise, it returns the number of elements in the matrix. Note + * that an element may have multiple channels. + * + * The following code demonstrates its usage for a 2-d matrix: + * @snippet snippets/core_mat_checkVector.cpp example-2d + * + * The following code demonstrates its usage for a 3-d matrix: + * @snippet snippets/core_mat_checkVector.cpp example-3d + */ + int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; + + /** @brief Returns a pointer to the specified matrix row. + + The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in + Mat::isContinuous to know how to use these methods. + @param i0 A 0-based row index. + */ + uchar* ptr(int i0=0); + /** @overload */ + const uchar* ptr(int i0=0) const; + + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + uchar* ptr(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + const uchar* ptr(int row, int col) const; + + /** @overload */ + uchar* ptr(int i0, int i1, int i2); + /** @overload */ + const uchar* ptr(int i0, int i1, int i2) const; + + /** @overload */ + uchar* ptr(const int* idx); + /** @overload */ + const uchar* ptr(const int* idx) const; + /** @overload */ + template uchar* ptr(const Vec& idx); + /** @overload */ + template const uchar* ptr(const Vec& idx) const; + + /** @overload */ + template _Tp* ptr(int i0=0); + /** @overload */ + template const _Tp* ptr(int i0=0) const; + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template _Tp* ptr(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template const _Tp* ptr(int row, int col) const; + /** @overload */ + template _Tp* ptr(int i0, int i1, int i2); + /** @overload */ + template const _Tp* ptr(int i0, int i1, int i2) const; + /** @overload */ + template _Tp* ptr(const int* idx); + /** @overload */ + template const _Tp* ptr(const int* idx) const; + /** @overload */ + template _Tp* ptr(const Vec& idx); + /** @overload */ + template const _Tp* ptr(const Vec& idx) const; + + /** @brief Returns a reference to the specified array element. + + The template methods return a reference to the specified array element. For the sake of higher + performance, the index range checks are only performed in the Debug configuration. + + Note that the variants with a single index (i) can be used to access elements of single-row or + single-column 2-dimensional arrays. That is, if, for example, A is a 1 x N floating-point matrix and + B is an M x 1 integer matrix, you can simply write `A.at(k+4)` and `B.at(2*i+1)` + instead of `A.at(0,k+4)` and `B.at(2*i+1,0)`, respectively. + + The example below initializes a Hilbert matrix: + @code + Mat H(100, 100, CV_64F); + for(int i = 0; i < H.rows; i++) + for(int j = 0; j < H.cols; j++) + H.at(i,j)=1./(i+j+1); + @endcode + + Keep in mind that the size identifier used in the at operator cannot be chosen at random. It depends + on the image from which you are trying to retrieve the data. The table below gives a better insight in this: + - If matrix is of type `CV_8U` then use `Mat.at(y,x)`. + - If matrix is of type `CV_8S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_16U` then use `Mat.at(y,x)`. + - If matrix is of type `CV_16S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_32S` then use `Mat.at(y,x)`. + - If matrix is of type `CV_32F` then use `Mat.at(y,x)`. + - If matrix is of type `CV_64F` then use `Mat.at(y,x)`. + + @param i0 Index along the dimension 0 + */ + template _Tp& at(int i0=0); + /** @overload + @param i0 Index along the dimension 0 + */ + template const _Tp& at(int i0=0) const; + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template _Tp& at(int row, int col); + /** @overload + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + template const _Tp& at(int row, int col) const; + + /** @overload + @param i0 Index along the dimension 0 + @param i1 Index along the dimension 1 + @param i2 Index along the dimension 2 + */ + template _Tp& at(int i0, int i1, int i2); + /** @overload + @param i0 Index along the dimension 0 + @param i1 Index along the dimension 1 + @param i2 Index along the dimension 2 + */ + template const _Tp& at(int i0, int i1, int i2) const; + + /** @overload + @param idx Array of Mat::dims indices. + */ + template _Tp& at(const int* idx); + /** @overload + @param idx Array of Mat::dims indices. + */ + template const _Tp& at(const int* idx) const; + + /** @overload */ + template _Tp& at(const Vec& idx); + /** @overload */ + template const _Tp& at(const Vec& idx) const; + + /** @overload + special versions for 2D arrays (especially convenient for referencing image pixels) + @param pt Element position specified as Point(j,i) . + */ + template _Tp& at(Point pt); + /** @overload + special versions for 2D arrays (especially convenient for referencing image pixels) + @param pt Element position specified as Point(j,i) . + */ + template const _Tp& at(Point pt) const; + + /** @brief Returns the matrix iterator and sets it to the first matrix element. + + The methods return the matrix read-only or read-write iterators. The use of matrix iterators is very + similar to the use of bi-directional STL iterators. In the example below, the alpha blending + function is rewritten using the matrix iterators: + @code + template + void alphaBlendRGBA(const Mat& src1, const Mat& src2, Mat& dst) + { + typedef Vec VT; + + const float alpha_scale = (float)std::numeric_limits::max(), + inv_scale = 1.f/alpha_scale; + + CV_Assert( src1.type() == src2.type() && + src1.type() == traits::Type::value && + src1.size() == src2.size()); + Size size = src1.size(); + dst.create(size, src1.type()); + + MatConstIterator_ it1 = src1.begin(), it1_end = src1.end(); + MatConstIterator_ it2 = src2.begin(); + MatIterator_ dst_it = dst.begin(); + + for( ; it1 != it1_end; ++it1, ++it2, ++dst_it ) + { + VT pix1 = *it1, pix2 = *it2; + float alpha = pix1[3]*inv_scale, beta = pix2[3]*inv_scale; + *dst_it = VT(saturate_cast(pix1[0]*alpha + pix2[0]*beta), + saturate_cast(pix1[1]*alpha + pix2[1]*beta), + saturate_cast(pix1[2]*alpha + pix2[2]*beta), + saturate_cast((1 - (1-alpha)*(1-beta))*alpha_scale)); + } + } + @endcode + */ + template MatIterator_<_Tp> begin(); + template MatConstIterator_<_Tp> begin() const; + + /** @brief Same as begin() but for inverse traversal + */ + template std::reverse_iterator> rbegin(); + template std::reverse_iterator> rbegin() const; + + /** @brief Returns the matrix iterator and sets it to the after-last matrix element. + + The methods return the matrix read-only or read-write iterators, set to the point following the last + matrix element. + */ + template MatIterator_<_Tp> end(); + template MatConstIterator_<_Tp> end() const; + + /** @brief Same as end() but for inverse traversal + */ + template std::reverse_iterator< MatIterator_<_Tp>> rend(); + template std::reverse_iterator< MatConstIterator_<_Tp>> rend() const; + + + /** @brief Runs the given functor over all matrix elements in parallel. + + The operation passed as argument has to be a function pointer, a function object or a lambda(C++11). + + Example 1. All of the operations below put 0xFF the first channel of all matrix elements: + @code + Mat image(1920, 1080, CV_8UC3); + typedef cv::Point3_ Pixel; + + // first. raw pointer access. + for (int r = 0; r < image.rows; ++r) { + Pixel* ptr = image.ptr(r, 0); + const Pixel* ptr_end = ptr + image.cols; + for (; ptr != ptr_end; ++ptr) { + ptr->x = 255; + } + } + + // Using MatIterator. (Simple but there are a Iterator's overhead) + for (Pixel &p : cv::Mat_(image)) { + p.x = 255; + } + + // Parallel execution with function object. + struct Operator { + void operator ()(Pixel &pixel, const int * position) { + pixel.x = 255; + } + }; + image.forEach(Operator()); + + // Parallel execution using C++11 lambda. + image.forEach([](Pixel &p, const int * position) -> void { + p.x = 255; + }); + @endcode + Example 2. Using the pixel's position: + @code + // Creating 3D matrix (255 x 255 x 255) typed uint8_t + // and initialize all elements by the value which equals elements position. + // i.e. pixels (x,y,z) = (1,2,3) is (b,g,r) = (1,2,3). + + int sizes[] = { 255, 255, 255 }; + typedef cv::Point3_ Pixel; + + Mat_ image = Mat::zeros(3, sizes, CV_8UC3); + + image.forEach([](Pixel& pixel, const int position[]) -> void { + pixel.x = position[0]; + pixel.y = position[1]; + pixel.z = position[2]; + }); + @endcode + */ + template void forEach(const Functor& operation); + /** @overload */ + template void forEach(const Functor& operation) const; + + Mat(Mat&& m) CV_NOEXCEPT; + Mat& operator = (Mat&& m); + + enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; + enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + //! the matrix dimensionality, >= 2 + int dims; + //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions + int rows, cols; + //! pointer to the data + uchar* data; + + //! helper fields used in locateROI and adjustROI + const uchar* datastart; + const uchar* dataend; + const uchar* datalimit; + + //! custom allocator + MatAllocator* allocator; + //! and the standard allocator + static MatAllocator* getStdAllocator(); + static MatAllocator* getDefaultAllocator(); + static void setDefaultAllocator(MatAllocator* allocator); + + //! internal use method: updates the continuity flag + void updateContinuityFlag(); + + //! interaction with UMat + UMatData* u; + + MatSize size; + MatStep step; + +protected: + template void forEach_impl(const Functor& operation); +}; + + +///////////////////////////////// Mat_<_Tp> //////////////////////////////////// + +/** @brief Template matrix class derived from Mat + +@code{.cpp} + template class Mat_ : public Mat + { + public: + // ... some specific methods + // and + // no new extra fields + }; +@endcode +The class `Mat_<_Tp>` is a *thin* template wrapper on top of the Mat class. It does not have any +extra data fields. Nor this class nor Mat has any virtual methods. Thus, references or pointers to +these two classes can be freely but carefully converted one to another. For example: +@code{.cpp} + // create a 100x100 8-bit matrix + Mat M(100,100,CV_8U); + // this will be compiled fine. no any data conversion will be done. + Mat_& M1 = (Mat_&)M; + // the program is likely to crash at the statement below + M1(99,99) = 1.f; +@endcode +While Mat is sufficient in most cases, Mat_ can be more convenient if you use a lot of element +access operations and if you know matrix type at the compilation time. Note that +`Mat::at(int y,int x)` and `Mat_::operator()(int y,int x)` do absolutely the same +and run at the same speed, but the latter is certainly shorter: +@code{.cpp} + Mat_ M(20,20); + for(int i = 0; i < M.rows; i++) + for(int j = 0; j < M.cols; j++) + M(i,j) = 1./(i+j+1); + Mat E, V; + eigen(M,E,V); + cout << E.at(0,0)/E.at(M.rows-1,0); +@endcode +To use Mat_ for multi-channel images/matrices, pass Vec as a Mat_ parameter: +@code{.cpp} + // allocate a 320x240 color image and fill it with green (in RGB space) + Mat_ img(240, 320, Vec3b(0,255,0)); + // now draw a diagonal white line + for(int i = 0; i < 100; i++) + img(i,i)=Vec3b(255,255,255); + // and now scramble the 2nd (red) channel of each pixel + for(int i = 0; i < img.rows; i++) + for(int j = 0; j < img.cols; j++) + img(i,j)[2] ^= (uchar)(i ^ j); +@endcode +Mat_ is fully compatible with C++11 range-based for loop. For example such loop +can be used to safely apply look-up table: +@code{.cpp} +void applyTable(Mat_& I, const uchar* const table) +{ + for(auto& pixel : I) + { + pixel = table[pixel]; + } +} +@endcode + */ +template class Mat_ : public Mat +{ +public: + typedef _Tp value_type; + typedef typename DataType<_Tp>::channel_type channel_type; + typedef MatIterator_<_Tp> iterator; + typedef MatConstIterator_<_Tp> const_iterator; + + //! default constructor + Mat_() CV_NOEXCEPT; + //! equivalent to Mat(_rows, _cols, DataType<_Tp>::type) + Mat_(int _rows, int _cols); + //! constructor that sets each matrix element to specified value + Mat_(int _rows, int _cols, const _Tp& value); + //! equivalent to Mat(_size, DataType<_Tp>::type) + explicit Mat_(Size _size); + //! constructor that sets each matrix element to specified value + Mat_(Size _size, const _Tp& value); + //! n-dim array constructor + Mat_(int _ndims, const int* _sizes); + //! n-dim array constructor that sets each matrix element to specified value + Mat_(int _ndims, const int* _sizes, const _Tp& value); + //! copy/conversion constructor. If m is of different type, it's converted + Mat_(const Mat& m); + //! copy constructor + Mat_(const Mat_& m); + //! constructs a matrix on top of user-allocated data. step is in bytes(!!!), regardless of the type + Mat_(int _rows, int _cols, _Tp* _data, size_t _step=AUTO_STEP); + //! constructs n-dim matrix on top of user-allocated data. steps are in bytes(!!!), regardless of the type + Mat_(int _ndims, const int* _sizes, _Tp* _data, const size_t* _steps=0); + //! selects a submatrix + Mat_(const Mat_& m, const Range& rowRange, const Range& colRange=Range::all()); + //! selects a submatrix + Mat_(const Mat_& m, const Rect& roi); + //! selects a submatrix, n-dim version + Mat_(const Mat_& m, const Range* ranges); + //! selects a submatrix, n-dim version + Mat_(const Mat_& m, const std::vector& ranges); + //! from a matrix expression + explicit Mat_(const MatExpr& e); + //! makes a matrix out of Vec, std::vector, Point_ or Point3_. The matrix will have a single column + explicit Mat_(const std::vector<_Tp>& vec, bool copyData=false); + template explicit Mat_(const Vec::channel_type, n>& vec, bool copyData=true); + template explicit Mat_(const Matx::channel_type, m, n>& mtx, bool copyData=true); + explicit Mat_(const Point_::channel_type>& pt, bool copyData=true); + explicit Mat_(const Point3_::channel_type>& pt, bool copyData=true); + explicit Mat_(const MatCommaInitializer_<_Tp>& commaInitializer); + + Mat_(std::initializer_list<_Tp> values); + explicit Mat_(const std::initializer_list sizes, const std::initializer_list<_Tp> values); + + template explicit Mat_(const std::array<_Tp, _Nm>& arr, bool copyData=false); + + Mat_& operator = (const Mat& m); + Mat_& operator = (const Mat_& m); + //! set all the elements to s. + Mat_& operator = (const _Tp& s); + //! assign a matrix expression + Mat_& operator = (const MatExpr& e); + + //! iterators; they are smart enough to skip gaps in the end of rows + iterator begin(); + iterator end(); + const_iterator begin() const; + const_iterator end() const; + + //reverse iterators + std::reverse_iterator rbegin(); + std::reverse_iterator rend(); + std::reverse_iterator rbegin() const; + std::reverse_iterator rend() const; + + //! template methods for operation over all matrix elements. + // the operations take care of skipping gaps in the end of rows (if any) + template void forEach(const Functor& operation); + template void forEach(const Functor& operation) const; + + //! equivalent to Mat::create(_rows, _cols, DataType<_Tp>::type) + void create(int _rows, int _cols); + //! equivalent to Mat::create(_size, DataType<_Tp>::type) + void create(Size _size); + //! equivalent to Mat::create(_ndims, _sizes, DatType<_Tp>::type) + void create(int _ndims, const int* _sizes); + //! equivalent to Mat::release() + void release(); + //! cross-product + Mat_ cross(const Mat_& m) const; + //! data type conversion + template operator Mat_() const; + //! overridden forms of Mat::row() etc. + Mat_ row(int y) const; + Mat_ col(int x) const; + Mat_ diag(int d=0) const; + CV_NODISCARD_STD Mat_ clone() const; + + //! overridden forms of Mat::elemSize() etc. + size_t elemSize() const; + size_t elemSize1() const; + int type() const; + int depth() const; + int channels() const; + size_t step1(int i=0) const; + //! returns step()/sizeof(_Tp) + size_t stepT(int i=0) const; + + //! overridden forms of Mat::zeros() etc. Data type is omitted, of course + CV_NODISCARD_STD static MatExpr zeros(int rows, int cols); + CV_NODISCARD_STD static MatExpr zeros(Size size); + CV_NODISCARD_STD static MatExpr zeros(int _ndims, const int* _sizes); + CV_NODISCARD_STD static MatExpr ones(int rows, int cols); + CV_NODISCARD_STD static MatExpr ones(Size size); + CV_NODISCARD_STD static MatExpr ones(int _ndims, const int* _sizes); + CV_NODISCARD_STD static MatExpr eye(int rows, int cols); + CV_NODISCARD_STD static MatExpr eye(Size size); + + //! some more overridden methods + Mat_& adjustROI( int dtop, int dbottom, int dleft, int dright ); + Mat_ operator()( const Range& rowRange, const Range& colRange ) const; + Mat_ operator()( const Rect& roi ) const; + Mat_ operator()( const Range* ranges ) const; + Mat_ operator()(const std::vector& ranges) const; + + //! more convenient forms of row and element access operators + _Tp* operator [](int y); + const _Tp* operator [](int y) const; + + //! returns reference to the specified element + _Tp& operator ()(const int* idx); + //! returns read-only reference to the specified element + const _Tp& operator ()(const int* idx) const; + + //! returns reference to the specified element + template _Tp& operator ()(const Vec& idx); + //! returns read-only reference to the specified element + template const _Tp& operator ()(const Vec& idx) const; + + //! returns reference to the specified element (1D case) + _Tp& operator ()(int idx0); + //! returns read-only reference to the specified element (1D case) + const _Tp& operator ()(int idx0) const; + //! returns reference to the specified element (2D case) + _Tp& operator ()(int row, int col); + //! returns read-only reference to the specified element (2D case) + const _Tp& operator ()(int row, int col) const; + //! returns reference to the specified element (3D case) + _Tp& operator ()(int idx0, int idx1, int idx2); + //! returns read-only reference to the specified element (3D case) + const _Tp& operator ()(int idx0, int idx1, int idx2) const; + + _Tp& operator ()(Point pt); + const _Tp& operator ()(Point pt) const; + + //! conversion to vector. + operator std::vector<_Tp>() const; + + //! conversion to array. + template operator std::array<_Tp, _Nm>() const; + + //! conversion to Vec + template operator Vec::channel_type, n>() const; + //! conversion to Matx + template operator Matx::channel_type, m, n>() const; + + Mat_(Mat_&& m); + Mat_& operator = (Mat_&& m); + + Mat_(Mat&& m); + Mat_& operator = (Mat&& m); + + Mat_(MatExpr&& e); +}; + +typedef Mat_ Mat1b; +typedef Mat_ Mat2b; +typedef Mat_ Mat3b; +typedef Mat_ Mat4b; + +typedef Mat_ Mat1s; +typedef Mat_ Mat2s; +typedef Mat_ Mat3s; +typedef Mat_ Mat4s; + +typedef Mat_ Mat1w; +typedef Mat_ Mat2w; +typedef Mat_ Mat3w; +typedef Mat_ Mat4w; + +typedef Mat_ Mat1i; +typedef Mat_ Mat2i; +typedef Mat_ Mat3i; +typedef Mat_ Mat4i; + +typedef Mat_ Mat1f; +typedef Mat_ Mat2f; +typedef Mat_ Mat3f; +typedef Mat_ Mat4f; + +typedef Mat_ Mat1d; +typedef Mat_ Mat2d; +typedef Mat_ Mat3d; +typedef Mat_ Mat4d; + +/** @todo document */ +class CV_EXPORTS UMat +{ +public: + //! default constructor + UMat(UMatUsageFlags usageFlags = USAGE_DEFAULT) CV_NOEXCEPT; + //! constructs 2D matrix of the specified size and type + // (_type is CV_8UC1, CV_64FC3, CV_32SC(12) etc.) + UMat(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + //! constructs 2D matrix and fills it with the specified value _s. + UMat(int rows, int cols, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(Size size, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! constructs n-dimensional matrix + UMat(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + UMat(int ndims, const int* sizes, int type, const Scalar& s, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! copy constructor + UMat(const UMat& m); + + //! creates a matrix header for a part of the bigger matrix + UMat(const UMat& m, const Range& rowRange, const Range& colRange=Range::all()); + UMat(const UMat& m, const Rect& roi); + UMat(const UMat& m, const Range* ranges); + UMat(const UMat& m, const std::vector& ranges); + + // FIXIT copyData=false is not implemented, drop this in favor of cv::Mat (OpenCV 5.0) + //! builds matrix from std::vector with or without copying the data + template explicit UMat(const std::vector<_Tp>& vec, bool copyData=false); + + //! destructor - calls release() + ~UMat(); + //! assignment operators + UMat& operator = (const UMat& m); + + Mat getMat(AccessFlag flags) const; + + //! returns a new matrix header for the specified row + UMat row(int y) const; + //! returns a new matrix header for the specified column + UMat col(int x) const; + //! ... for the specified row span + UMat rowRange(int startrow, int endrow) const; + UMat rowRange(const Range& r) const; + //! ... for the specified column span + UMat colRange(int startcol, int endcol) const; + UMat colRange(const Range& r) const; + //! ... for the specified diagonal + //! (d=0 - the main diagonal, + //! >0 - a diagonal from the upper half, + //! <0 - a diagonal from the lower half) + UMat diag(int d=0) const; + //! constructs a square diagonal matrix which main diagonal is vector "d" + CV_NODISCARD_STD static UMat diag(const UMat& d, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat diag(const UMat& d) { return diag(d, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + + //! returns deep copy of the matrix, i.e. the data is copied + CV_NODISCARD_STD UMat clone() const; + //! copies the matrix content to "m". + // It calls m.create(this->size(), this->type()). + void copyTo( OutputArray m ) const; + //! copies those matrix elements to "m" that are marked with non-zero mask elements. + void copyTo( OutputArray m, InputArray mask ) const; + //! converts matrix to another datatype with optional scaling. See cvConvertScale. + void convertTo( OutputArray m, int rtype, double alpha=1, double beta=0 ) const; + + void assignTo( UMat& m, int type=-1 ) const; + + //! sets every matrix element to s + UMat& operator = (const Scalar& s); + //! sets some of the matrix elements to s, according to the mask + UMat& setTo(InputArray value, InputArray mask=noArray()); + //! creates alternative matrix header for the same data, with different + // number of channels and/or different number of rows. see cvReshape. + UMat reshape(int cn, int rows=0) const; + UMat reshape(int cn, int newndims, const int* newsz) const; + + //! matrix transposition by means of matrix expressions + UMat t() const; + //! matrix inversion by means of matrix expressions + UMat inv(int method=DECOMP_LU) const; + //! per-element matrix multiplication by means of matrix expressions + UMat mul(InputArray m, double scale=1) const; + + //! computes dot-product + double dot(InputArray m) const; + + //! Matlab-style matrix initialization + CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat zeros(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat zeros(int rows, int cols, int type) { return zeros(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat zeros(Size size, int type) { return zeros(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat zeros(int ndims, const int* sz, int type) { return zeros(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat ones(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat ones(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat ones(int rows, int cols, int type) { return ones(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat ones(Size size, int type) { return ones(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat ones(int ndims, const int* sz, int type) { return ones(ndims, sz, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat eye(int rows, int cols, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat eye(Size size, int type, UMatUsageFlags usageFlags /*= USAGE_DEFAULT*/); + CV_NODISCARD_STD static UMat eye(int rows, int cols, int type) { return eye(rows, cols, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + CV_NODISCARD_STD static UMat eye(Size size, int type) { return eye(size, type, USAGE_DEFAULT); } // OpenCV 5.0: remove abi compatibility overload + + //! allocates new matrix data unless the matrix already has specified size and type. + // previous data is unreferenced if needed. + void create(int rows, int cols, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(Size size, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(int ndims, const int* sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + void create(const std::vector& sizes, int type, UMatUsageFlags usageFlags = USAGE_DEFAULT); + + //! increases the reference counter; use with care to avoid memleaks + void addref(); + //! decreases reference counter; + // deallocates the data when reference counter reaches 0. + void release(); + + //! deallocates the matrix data + void deallocate(); + //! internal use function; properly re-allocates _size, _step arrays + void copySize(const UMat& m); + + //! locates matrix header within a parent matrix. See below + void locateROI( Size& wholeSize, Point& ofs ) const; + //! moves/resizes the current matrix ROI inside the parent matrix. + UMat& adjustROI( int dtop, int dbottom, int dleft, int dright ); + //! extracts a rectangular sub-matrix + // (this is a generalized form of row, rowRange etc.) + UMat operator()( Range rowRange, Range colRange ) const; + UMat operator()( const Rect& roi ) const; + UMat operator()( const Range* ranges ) const; + UMat operator()(const std::vector& ranges) const; + + //! returns true iff the matrix data is continuous + // (i.e. when there are no gaps between successive rows). + // similar to CV_IS_MAT_CONT(cvmat->type) + bool isContinuous() const; + + //! returns true if the matrix is a submatrix of another matrix + bool isSubmatrix() const; + + //! returns element size in bytes, + // similar to CV_ELEM_SIZE(cvmat->type) + size_t elemSize() const; + //! returns the size of element channel in bytes. + size_t elemSize1() const; + //! returns element type, similar to CV_MAT_TYPE(cvmat->type) + int type() const; + //! returns element type, similar to CV_MAT_DEPTH(cvmat->type) + int depth() const; + //! returns element type, similar to CV_MAT_CN(cvmat->type) + int channels() const; + //! returns step/elemSize1() + size_t step1(int i=0) const; + //! returns true if matrix data is NULL + bool empty() const; + //! returns the total number of matrix elements + size_t total() const; + + //! returns N if the matrix is 1-channel (N x ptdim) or ptdim-channel (1 x N) or (N x 1); negative number otherwise + int checkVector(int elemChannels, int depth=-1, bool requireContinuous=true) const; + + UMat(UMat&& m); + UMat& operator = (UMat&& m); + + /*! Returns the OpenCL buffer handle on which UMat operates on. + The UMat instance should be kept alive during the use of the handle to prevent the buffer to be + returned to the OpenCV buffer pool. + */ + void* handle(AccessFlag accessFlags) const; + void ndoffset(size_t* ofs) const; + + enum { MAGIC_VAL = 0x42FF0000, AUTO_STEP = 0, CONTINUOUS_FLAG = CV_MAT_CONT_FLAG, SUBMATRIX_FLAG = CV_SUBMAT_FLAG }; + enum { MAGIC_MASK = 0xFFFF0000, TYPE_MASK = 0x00000FFF, DEPTH_MASK = 7 }; + + /*! includes several bit-fields: + - the magic signature + - continuity flag + - depth + - number of channels + */ + int flags; + + //! the matrix dimensionality, >= 2 + int dims; + + //! number of rows in the matrix; -1 when the matrix has more than 2 dimensions + int rows; + + //! number of columns in the matrix; -1 when the matrix has more than 2 dimensions + int cols; + + //! custom allocator + MatAllocator* allocator; + + //! usage flags for allocator; recommend do not set directly, instead set during construct/create/getUMat + UMatUsageFlags usageFlags; + + //! and the standard allocator + static MatAllocator* getStdAllocator(); + + //! internal use method: updates the continuity flag + void updateContinuityFlag(); + + //! black-box container of UMat data + UMatData* u; + + //! offset of the submatrix (or 0) + size_t offset; + + //! dimensional size of the matrix; accessible in various formats + MatSize size; + + //! number of bytes each matrix element/row/plane/dimension occupies + MatStep step; + +protected: +}; + + +/////////////////////////// multi-dimensional sparse matrix ////////////////////////// + +/** @brief The class SparseMat represents multi-dimensional sparse numerical arrays. + +Such a sparse array can store elements of any type that Mat can store. *Sparse* means that only +non-zero elements are stored (though, as a result of operations on a sparse matrix, some of its +stored elements can actually become 0. It is up to you to detect such elements and delete them +using SparseMat::erase ). The non-zero elements are stored in a hash table that grows when it is +filled so that the search time is O(1) in average (regardless of whether element is there or not). +Elements can be accessed using the following methods: +- Query operations (SparseMat::ptr and the higher-level SparseMat::ref, SparseMat::value and + SparseMat::find), for example: + @code + const int dims = 5; + int size[5] = {10, 10, 10, 10, 10}; + SparseMat sparse_mat(dims, size, CV_32F); + for(int i = 0; i < 1000; i++) + { + int idx[dims]; + for(int k = 0; k < dims; k++) + idx[k] = rand() % size[k]; + sparse_mat.ref(idx) += 1.f; + } + cout << "nnz = " << sparse_mat.nzcount() << endl; + @endcode +- Sparse matrix iterators. They are similar to MatIterator but different from NAryMatIterator. + That is, the iteration loop is familiar to STL users: + @code + // prints elements of a sparse floating-point matrix + // and the sum of elements. + SparseMatConstIterator_ + it = sparse_mat.begin(), + it_end = sparse_mat.end(); + double s = 0; + int dims = sparse_mat.dims(); + for(; it != it_end; ++it) + { + // print element indices and the element value + const SparseMat::Node* n = it.node(); + printf("("); + for(int i = 0; i < dims; i++) + printf("%d%s", n->idx[i], i < dims-1 ? ", " : ")"); + printf(": %g\n", it.value()); + s += *it; + } + printf("Element sum is %g\n", s); + @endcode + If you run this loop, you will notice that elements are not enumerated in a logical order + (lexicographical, and so on). They come in the same order as they are stored in the hash table + (semi-randomly). You may collect pointers to the nodes and sort them to get the proper ordering. + Note, however, that pointers to the nodes may become invalid when you add more elements to the + matrix. This may happen due to possible buffer reallocation. +- Combination of the above 2 methods when you need to process 2 or more sparse matrices + simultaneously. For example, this is how you can compute unnormalized cross-correlation of the 2 + floating-point sparse matrices: + @code + double cross_corr(const SparseMat& a, const SparseMat& b) + { + const SparseMat *_a = &a, *_b = &b; + // if b contains less elements than a, + // it is faster to iterate through b + if(_a->nzcount() > _b->nzcount()) + std::swap(_a, _b); + SparseMatConstIterator_ it = _a->begin(), + it_end = _a->end(); + double ccorr = 0; + for(; it != it_end; ++it) + { + // take the next element from the first matrix + float avalue = *it; + const Node* anode = it.node(); + // and try to find an element with the same index in the second matrix. + // since the hash value depends only on the element index, + // reuse the hash value stored in the node + float bvalue = _b->value(anode->idx,&anode->hashval); + ccorr += avalue*bvalue; + } + return ccorr; + } + @endcode + */ +class CV_EXPORTS SparseMat +{ +public: + typedef SparseMatIterator iterator; + typedef SparseMatConstIterator const_iterator; + + enum { MAGIC_VAL=0x42FD0000, MAX_DIM=32, HASH_SCALE=0x5bd1e995, HASH_BIT=0x80000000 }; + + //! the sparse matrix header + struct CV_EXPORTS Hdr + { + Hdr(int _dims, const int* _sizes, int _type); + void clear(); + int refcount; + int dims; + int valueOffset; + size_t nodeSize; + size_t nodeCount; + size_t freeList; + std::vector pool; + std::vector hashtab; + int size[MAX_DIM]; + }; + + //! sparse matrix node - element of a hash table + struct CV_EXPORTS Node + { + //! hash value + size_t hashval; + //! index of the next node in the same hash table entry + size_t next; + //! index of the matrix element + int idx[MAX_DIM]; + }; + + /** @brief Various SparseMat constructors. + */ + SparseMat(); + + /** @overload + @param dims Array dimensionality. + @param _sizes Sparce matrix size on all dementions. + @param _type Sparse matrix data type. + */ + SparseMat(int dims, const int* _sizes, int _type); + + /** @overload + @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted + to sparse representation. + */ + SparseMat(const SparseMat& m); + + /** @overload + @param m Source matrix for copy constructor. If m is dense matrix (ocvMat) then it will be converted + to sparse representation. + */ + explicit SparseMat(const Mat& m); + + //! the destructor + ~SparseMat(); + + //! assignment operator. This is O(1) operation, i.e. no data is copied + SparseMat& operator = (const SparseMat& m); + //! equivalent to the corresponding constructor + SparseMat& operator = (const Mat& m); + + //! creates full copy of the matrix + CV_NODISCARD_STD SparseMat clone() const; + + //! copies all the data to the destination matrix. All the previous content of m is erased + void copyTo( SparseMat& m ) const; + //! converts sparse matrix to dense matrix. + void copyTo( Mat& m ) const; + //! multiplies all the matrix elements by the specified scale factor alpha and converts the results to the specified data type + void convertTo( SparseMat& m, int rtype, double alpha=1 ) const; + //! converts sparse matrix to dense n-dim matrix with optional type conversion and scaling. + /*! + @param [out] m - output matrix; if it does not have a proper size or type before the operation, + it is reallocated + @param [in] rtype - desired output matrix type or, rather, the depth since the number of channels + are the same as the input has; if rtype is negative, the output matrix will have the + same type as the input. + @param [in] alpha - optional scale factor + @param [in] beta - optional delta added to the scaled values + */ + void convertTo( Mat& m, int rtype, double alpha=1, double beta=0 ) const; + + // not used now + void assignTo( SparseMat& m, int type=-1 ) const; + + //! reallocates sparse matrix. + /*! + If the matrix already had the proper size and type, + it is simply cleared with clear(), otherwise, + the old matrix is released (using release()) and the new one is allocated. + */ + void create(int dims, const int* _sizes, int _type); + //! sets all the sparse matrix elements to 0, which means clearing the hash table. + void clear(); + //! manually increments the reference counter to the header. + void addref(); + // decrements the header reference counter. When the counter reaches 0, the header and all the underlying data are deallocated. + void release(); + + //! converts sparse matrix to the old-style representation; all the elements are copied. + //operator CvSparseMat*() const; + //! returns the size of each element in bytes (not including the overhead - the space occupied by SparseMat::Node elements) + size_t elemSize() const; + //! returns elemSize()/channels() + size_t elemSize1() const; + + //! returns type of sparse matrix elements + int type() const; + //! returns the depth of sparse matrix elements + int depth() const; + //! returns the number of channels + int channels() const; + + //! returns the array of sizes, or NULL if the matrix is not allocated + const int* size() const; + //! returns the size of i-th matrix dimension (or 0) + int size(int i) const; + //! returns the matrix dimensionality + int dims() const; + //! returns the number of non-zero elements (=the number of hash table nodes) + size_t nzcount() const; + + //! computes the element hash value (1D case) + size_t hash(int i0) const; + //! computes the element hash value (2D case) + size_t hash(int i0, int i1) const; + //! computes the element hash value (3D case) + size_t hash(int i0, int i1, int i2) const; + //! computes the element hash value (nD case) + size_t hash(const int* idx) const; + + //!@{ + /*! + specialized variants for 1D, 2D, 3D cases and the generic_type one for n-D case. + return pointer to the matrix element. + - if the element is there (it's non-zero), the pointer to it is returned + - if it's not there and createMissing=false, NULL pointer is returned + - if it's not there and createMissing=true, then the new element + is created and initialized with 0. Pointer to it is returned + - if the optional hashval pointer is not NULL, the element hash value is + not computed, but *hashval is taken instead. + */ + //! returns pointer to the specified element (1D case) + uchar* ptr(int i0, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (2D case) + uchar* ptr(int i0, int i1, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (3D case) + uchar* ptr(int i0, int i1, int i2, bool createMissing, size_t* hashval=0); + //! returns pointer to the specified element (nD case) + uchar* ptr(const int* idx, bool createMissing, size_t* hashval=0); + //!@} + + //!@{ + /*! + return read-write reference to the specified sparse matrix element. + + `ref<_Tp>(i0,...[,hashval])` is equivalent to `*(_Tp*)ptr(i0,...,true[,hashval])`. + The methods always return a valid reference. + If the element did not exist, it is created and initialized with 0. + */ + //! returns reference to the specified element (1D case) + template _Tp& ref(int i0, size_t* hashval=0); + //! returns reference to the specified element (2D case) + template _Tp& ref(int i0, int i1, size_t* hashval=0); + //! returns reference to the specified element (3D case) + template _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); + //! returns reference to the specified element (nD case) + template _Tp& ref(const int* idx, size_t* hashval=0); + //!@} + + //!@{ + /*! + return value of the specified sparse matrix element. + + `value<_Tp>(i0,...[,hashval])` is equivalent to + @code + { const _Tp* p = find<_Tp>(i0,...[,hashval]); return p ? *p : _Tp(); } + @endcode + + That is, if the element did not exist, the methods return 0. + */ + //! returns value of the specified element (1D case) + template _Tp value(int i0, size_t* hashval=0) const; + //! returns value of the specified element (2D case) + template _Tp value(int i0, int i1, size_t* hashval=0) const; + //! returns value of the specified element (3D case) + template _Tp value(int i0, int i1, int i2, size_t* hashval=0) const; + //! returns value of the specified element (nD case) + template _Tp value(const int* idx, size_t* hashval=0) const; + //!@} + + //!@{ + /*! + Return pointer to the specified sparse matrix element if it exists + + `find<_Tp>(i0,...[,hashval])` is equivalent to `(_const Tp*)ptr(i0,...false[,hashval])`. + + If the specified element does not exist, the methods return NULL. + */ + //! returns pointer to the specified element (1D case) + template const _Tp* find(int i0, size_t* hashval=0) const; + //! returns pointer to the specified element (2D case) + template const _Tp* find(int i0, int i1, size_t* hashval=0) const; + //! returns pointer to the specified element (3D case) + template const _Tp* find(int i0, int i1, int i2, size_t* hashval=0) const; + //! returns pointer to the specified element (nD case) + template const _Tp* find(const int* idx, size_t* hashval=0) const; + //!@} + + //! erases the specified element (2D case) + void erase(int i0, int i1, size_t* hashval=0); + //! erases the specified element (3D case) + void erase(int i0, int i1, int i2, size_t* hashval=0); + //! erases the specified element (nD case) + void erase(const int* idx, size_t* hashval=0); + + //!@{ + /*! + return the sparse matrix iterator pointing to the first sparse matrix element + */ + //! returns the sparse matrix iterator at the matrix beginning + SparseMatIterator begin(); + //! returns the sparse matrix iterator at the matrix beginning + template SparseMatIterator_<_Tp> begin(); + //! returns the read-only sparse matrix iterator at the matrix beginning + SparseMatConstIterator begin() const; + //! returns the read-only sparse matrix iterator at the matrix beginning + template SparseMatConstIterator_<_Tp> begin() const; + //!@} + /*! + return the sparse matrix iterator pointing to the element following the last sparse matrix element + */ + //! returns the sparse matrix iterator at the matrix end + SparseMatIterator end(); + //! returns the read-only sparse matrix iterator at the matrix end + SparseMatConstIterator end() const; + //! returns the typed sparse matrix iterator at the matrix end + template SparseMatIterator_<_Tp> end(); + //! returns the typed read-only sparse matrix iterator at the matrix end + template SparseMatConstIterator_<_Tp> end() const; + + //! returns the value stored in the sparse martix node + template _Tp& value(Node* n); + //! returns the value stored in the sparse martix node + template const _Tp& value(const Node* n) const; + + ////////////// some internal-use methods /////////////// + Node* node(size_t nidx); + const Node* node(size_t nidx) const; + + uchar* newNode(const int* idx, size_t hashval); + void removeNode(size_t hidx, size_t nidx, size_t previdx); + void resizeHashTab(size_t newsize); + + int flags; + Hdr* hdr; +}; + + + +///////////////////////////////// SparseMat_<_Tp> //////////////////////////////////// + +/** @brief Template sparse n-dimensional array class derived from SparseMat + +SparseMat_ is a thin wrapper on top of SparseMat created in the same way as Mat_ . It simplifies +notation of some operations: +@code + int sz[] = {10, 20, 30}; + SparseMat_ M(3, sz); + ... + M.ref(1, 2, 3) = M(4, 5, 6) + M(7, 8, 9); +@endcode + */ +template class SparseMat_ : public SparseMat +{ +public: + typedef SparseMatIterator_<_Tp> iterator; + typedef SparseMatConstIterator_<_Tp> const_iterator; + + //! the default constructor + SparseMat_(); + //! the full constructor equivalent to SparseMat(dims, _sizes, DataType<_Tp>::type) + SparseMat_(int dims, const int* _sizes); + //! the copy constructor. If DataType<_Tp>.type != m.type(), the m elements are converted + SparseMat_(const SparseMat& m); + //! the copy constructor. This is O(1) operation - no data is copied + SparseMat_(const SparseMat_& m); + //! converts dense matrix to the sparse form + SparseMat_(const Mat& m); + //! converts the old-style sparse matrix to the C++ class. All the elements are copied + //SparseMat_(const CvSparseMat* m); + //! the assignment operator. If DataType<_Tp>.type != m.type(), the m elements are converted + SparseMat_& operator = (const SparseMat& m); + //! the assignment operator. This is O(1) operation - no data is copied + SparseMat_& operator = (const SparseMat_& m); + //! converts dense matrix to the sparse form + SparseMat_& operator = (const Mat& m); + + //! makes full copy of the matrix. All the elements are duplicated + CV_NODISCARD_STD SparseMat_ clone() const; + //! equivalent to cv::SparseMat::create(dims, _sizes, DataType<_Tp>::type) + void create(int dims, const int* _sizes); + //! converts sparse matrix to the old-style CvSparseMat. All the elements are copied + //operator CvSparseMat*() const; + + //! returns type of the matrix elements + int type() const; + //! returns depth of the matrix elements + int depth() const; + //! returns the number of channels in each matrix element + int channels() const; + + //! equivalent to SparseMat::ref<_Tp>(i0, hashval) + _Tp& ref(int i0, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(i0, i1, hashval) + _Tp& ref(int i0, int i1, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(i0, i1, i2, hashval) + _Tp& ref(int i0, int i1, int i2, size_t* hashval=0); + //! equivalent to SparseMat::ref<_Tp>(idx, hashval) + _Tp& ref(const int* idx, size_t* hashval=0); + + //! equivalent to SparseMat::value<_Tp>(i0, hashval) + _Tp operator()(int i0, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(i0, i1, hashval) + _Tp operator()(int i0, int i1, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(i0, i1, i2, hashval) + _Tp operator()(int i0, int i1, int i2, size_t* hashval=0) const; + //! equivalent to SparseMat::value<_Tp>(idx, hashval) + _Tp operator()(const int* idx, size_t* hashval=0) const; + + //! returns sparse matrix iterator pointing to the first sparse matrix element + SparseMatIterator_<_Tp> begin(); + //! returns read-only sparse matrix iterator pointing to the first sparse matrix element + SparseMatConstIterator_<_Tp> begin() const; + //! returns sparse matrix iterator pointing to the element following the last sparse matrix element + SparseMatIterator_<_Tp> end(); + //! returns read-only sparse matrix iterator pointing to the element following the last sparse matrix element + SparseMatConstIterator_<_Tp> end() const; +}; + + + +////////////////////////////////// MatConstIterator ////////////////////////////////// + +class CV_EXPORTS MatConstIterator +{ +public: + typedef uchar* value_type; + typedef ptrdiff_t difference_type; + typedef const uchar** pointer; + typedef uchar* reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! default constructor + MatConstIterator(); + //! constructor that sets the iterator to the beginning of the matrix + MatConstIterator(const Mat* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator(const Mat* _m, const int* _idx); + //! copy constructor + MatConstIterator(const MatConstIterator& it); + + //! copy operator + MatConstIterator& operator = (const MatConstIterator& it); + //! returns the current matrix element + const uchar* operator *() const; + //! returns the i-th matrix element, relative to the current + const uchar* operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatConstIterator& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatConstIterator& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatConstIterator& operator --(); + //! decrements the iterator + MatConstIterator operator --(int); + //! increments the iterator + MatConstIterator& operator ++(); + //! increments the iterator + MatConstIterator operator ++(int); + //! returns the current iterator position + Point pos() const; + //! returns the current iterator position + void pos(int* _idx) const; + + ptrdiff_t lpos() const; + void seek(ptrdiff_t ofs, bool relative = false); + void seek(const int* _idx, bool relative = false); + + const Mat* m; + size_t elemSize; + const uchar* ptr; + const uchar* sliceStart; + const uchar* sliceEnd; +}; + + + +////////////////////////////////// MatConstIterator_ ///////////////////////////////// + +/** @brief Matrix read-only iterator + */ +template +class MatConstIterator_ : public MatConstIterator +{ +public: + typedef _Tp value_type; + typedef ptrdiff_t difference_type; + typedef const _Tp* pointer; + typedef const _Tp& reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! default constructor + MatConstIterator_(); + //! constructor that sets the iterator to the beginning of the matrix + MatConstIterator_(const Mat_<_Tp>* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatConstIterator_(const Mat_<_Tp>* _m, const int* _idx); + //! copy constructor + MatConstIterator_(const MatConstIterator_& it); + + //! copy operator + MatConstIterator_& operator = (const MatConstIterator_& it); + //! returns the current matrix element + const _Tp& operator *() const; + //! returns the i-th matrix element, relative to the current + const _Tp& operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatConstIterator_& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatConstIterator_& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatConstIterator_& operator --(); + //! decrements the iterator + MatConstIterator_ operator --(int); + //! increments the iterator + MatConstIterator_& operator ++(); + //! increments the iterator + MatConstIterator_ operator ++(int); + //! returns the current iterator position + Point pos() const; +}; + + + +//////////////////////////////////// MatIterator_ //////////////////////////////////// + +/** @brief Matrix read-write iterator +*/ +template +class MatIterator_ : public MatConstIterator_<_Tp> +{ +public: + typedef _Tp* pointer; + typedef _Tp& reference; + + typedef std::random_access_iterator_tag iterator_category; + + //! the default constructor + MatIterator_(); + //! constructor that sets the iterator to the beginning of the matrix + MatIterator_(Mat_<_Tp>* _m); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, int _row, int _col=0); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, Point _pt); + //! constructor that sets the iterator to the specified element of the matrix + MatIterator_(Mat_<_Tp>* _m, const int* _idx); + //! copy constructor + MatIterator_(const MatIterator_& it); + //! copy operator + MatIterator_& operator = (const MatIterator_<_Tp>& it ); + + //! returns the current matrix element + _Tp& operator *() const; + //! returns the i-th matrix element, relative to the current + _Tp& operator [](ptrdiff_t i) const; + + //! shifts the iterator forward by the specified number of elements + MatIterator_& operator += (ptrdiff_t ofs); + //! shifts the iterator backward by the specified number of elements + MatIterator_& operator -= (ptrdiff_t ofs); + //! decrements the iterator + MatIterator_& operator --(); + //! decrements the iterator + MatIterator_ operator --(int); + //! increments the iterator + MatIterator_& operator ++(); + //! increments the iterator + MatIterator_ operator ++(int); +}; + + + +/////////////////////////////// SparseMatConstIterator /////////////////////////////// + +/** @brief Read-Only Sparse Matrix Iterator. + + Here is how to use the iterator to compute the sum of floating-point sparse matrix elements: + + \code + SparseMatConstIterator it = m.begin(), it_end = m.end(); + double s = 0; + CV_Assert( m.type() == CV_32F ); + for( ; it != it_end; ++it ) + s += it.value(); + \endcode +*/ +class CV_EXPORTS SparseMatConstIterator +{ +public: + //! the default constructor + SparseMatConstIterator(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatConstIterator(const SparseMat* _m); + //! the copy constructor + SparseMatConstIterator(const SparseMatConstIterator& it); + + //! the assignment operator + SparseMatConstIterator& operator = (const SparseMatConstIterator& it); + + //! template method returning the current matrix element + template const _Tp& value() const; + //! returns the current node of the sparse matrix. it.node->idx is the current element index + const SparseMat::Node* node() const; + + //! moves iterator to the previous element + SparseMatConstIterator& operator --(); + //! moves iterator to the previous element + SparseMatConstIterator operator --(int); + //! moves iterator to the next element + SparseMatConstIterator& operator ++(); + //! moves iterator to the next element + SparseMatConstIterator operator ++(int); + + //! moves iterator to the element after the last element + void seekEnd(); + + const SparseMat* m; + size_t hashidx; + uchar* ptr; +}; + + + +////////////////////////////////// SparseMatIterator ///////////////////////////////// + +/** @brief Read-write Sparse Matrix Iterator + + The class is similar to cv::SparseMatConstIterator, + but can be used for in-place modification of the matrix elements. +*/ +class CV_EXPORTS SparseMatIterator : public SparseMatConstIterator +{ +public: + //! the default constructor + SparseMatIterator(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatIterator(SparseMat* _m); + //! the full constructor setting the iterator to the specified sparse matrix element + SparseMatIterator(SparseMat* _m, const int* idx); + //! the copy constructor + SparseMatIterator(const SparseMatIterator& it); + + //! the assignment operator + SparseMatIterator& operator = (const SparseMatIterator& it); + //! returns read-write reference to the current sparse matrix element + template _Tp& value() const; + //! returns pointer to the current sparse matrix node. it.node->idx is the index of the current element (do not modify it!) + SparseMat::Node* node() const; + + //! moves iterator to the next element + SparseMatIterator& operator ++(); + //! moves iterator to the next element + SparseMatIterator operator ++(int); +}; + + + +/////////////////////////////// SparseMatConstIterator_ ////////////////////////////// + +/** @brief Template Read-Only Sparse Matrix Iterator Class. + + This is the derived from SparseMatConstIterator class that + introduces more convenient operator *() for accessing the current element. +*/ +template class SparseMatConstIterator_ : public SparseMatConstIterator +{ +public: + + typedef std::forward_iterator_tag iterator_category; + + //! the default constructor + SparseMatConstIterator_(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatConstIterator_(const SparseMat_<_Tp>* _m); + SparseMatConstIterator_(const SparseMat* _m); + //! the copy constructor + SparseMatConstIterator_(const SparseMatConstIterator_& it); + + //! the assignment operator + SparseMatConstIterator_& operator = (const SparseMatConstIterator_& it); + //! the element access operator + const _Tp& operator *() const; + + //! moves iterator to the next element + SparseMatConstIterator_& operator ++(); + //! moves iterator to the next element + SparseMatConstIterator_ operator ++(int); +}; + + + +///////////////////////////////// SparseMatIterator_ ///////////////////////////////// + +/** @brief Template Read-Write Sparse Matrix Iterator Class. + + This is the derived from cv::SparseMatConstIterator_ class that + introduces more convenient operator *() for accessing the current element. +*/ +template class SparseMatIterator_ : public SparseMatConstIterator_<_Tp> +{ +public: + + typedef std::forward_iterator_tag iterator_category; + + //! the default constructor + SparseMatIterator_(); + //! the full constructor setting the iterator to the first sparse matrix element + SparseMatIterator_(SparseMat_<_Tp>* _m); + SparseMatIterator_(SparseMat* _m); + //! the copy constructor + SparseMatIterator_(const SparseMatIterator_& it); + + //! the assignment operator + SparseMatIterator_& operator = (const SparseMatIterator_& it); + //! returns the reference to the current element + _Tp& operator *() const; + + //! moves the iterator to the next element + SparseMatIterator_& operator ++(); + //! moves the iterator to the next element + SparseMatIterator_ operator ++(int); +}; + + + +/////////////////////////////////// NAryMatIterator ////////////////////////////////// + +/** @brief n-ary multi-dimensional array iterator. + +Use the class to implement unary, binary, and, generally, n-ary element-wise operations on +multi-dimensional arrays. Some of the arguments of an n-ary function may be continuous arrays, some +may be not. It is possible to use conventional MatIterator 's for each array but incrementing all of +the iterators after each small operations may be a big overhead. In this case consider using +NAryMatIterator to iterate through several matrices simultaneously as long as they have the same +geometry (dimensionality and all the dimension sizes are the same). On each iteration `it.planes[0]`, +`it.planes[1]`,... will be the slices of the corresponding matrices. + +The example below illustrates how you can compute a normalized and threshold 3D color histogram: +@code + void computeNormalizedColorHist(const Mat& image, Mat& hist, int N, double minProb) + { + const int histSize[] = {N, N, N}; + + // make sure that the histogram has a proper size and type + hist.create(3, histSize, CV_32F); + + // and clear it + hist = Scalar(0); + + // the loop below assumes that the image + // is a 8-bit 3-channel. check it. + CV_Assert(image.type() == CV_8UC3); + MatConstIterator_ it = image.begin(), + it_end = image.end(); + for( ; it != it_end; ++it ) + { + const Vec3b& pix = *it; + hist.at(pix[0]*N/256, pix[1]*N/256, pix[2]*N/256) += 1.f; + } + + minProb *= image.rows*image.cols; + + // initialize iterator (the style is different from STL). + // after initialization the iterator will contain + // the number of slices or planes the iterator will go through. + // it simultaneously increments iterators for several matrices + // supplied as a null terminated list of pointers + const Mat* arrays[] = {&hist, 0}; + Mat planes[1]; + NAryMatIterator itNAry(arrays, planes, 1); + double s = 0; + // iterate through the matrix. on each iteration + // itNAry.planes[i] (of type Mat) will be set to the current plane + // of the i-th n-dim matrix passed to the iterator constructor. + for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) + { + threshold(itNAry.planes[0], itNAry.planes[0], minProb, 0, THRESH_TOZERO); + s += sum(itNAry.planes[0])[0]; + } + + s = 1./s; + itNAry = NAryMatIterator(arrays, planes, 1); + for(int p = 0; p < itNAry.nplanes; p++, ++itNAry) + itNAry.planes[0] *= s; + } +@endcode + */ +class CV_EXPORTS NAryMatIterator +{ +public: + //! the default constructor + NAryMatIterator(); + //! the full constructor taking arbitrary number of n-dim matrices + NAryMatIterator(const Mat** arrays, uchar** ptrs, int narrays=-1); + //! the full constructor taking arbitrary number of n-dim matrices + NAryMatIterator(const Mat** arrays, Mat* planes, int narrays=-1); + //! the separate iterator initialization method + void init(const Mat** arrays, Mat* planes, uchar** ptrs, int narrays=-1); + + //! proceeds to the next plane of every iterated matrix + NAryMatIterator& operator ++(); + //! proceeds to the next plane of every iterated matrix (postfix increment operator) + NAryMatIterator operator ++(int); + + //! the iterated arrays + const Mat** arrays; + //! the current planes + Mat* planes; + //! data pointers + uchar** ptrs; + //! the number of arrays + int narrays; + //! the number of hyper-planes that the iterator steps through + size_t nplanes; + //! the size of each segment (in elements) + size_t size; +protected: + int iterdepth; + size_t idx; +}; + + + +///////////////////////////////// Matrix Expressions ///////////////////////////////// + +class CV_EXPORTS MatOp +{ +public: + MatOp(); + virtual ~MatOp(); + + virtual bool elementWise(const MatExpr& expr) const; + virtual void assign(const MatExpr& expr, Mat& m, int type=-1) const = 0; + virtual void roi(const MatExpr& expr, const Range& rowRange, + const Range& colRange, MatExpr& res) const; + virtual void diag(const MatExpr& expr, int d, MatExpr& res) const; + virtual void augAssignAdd(const MatExpr& expr, Mat& m) const; + virtual void augAssignSubtract(const MatExpr& expr, Mat& m) const; + virtual void augAssignMultiply(const MatExpr& expr, Mat& m) const; + virtual void augAssignDivide(const MatExpr& expr, Mat& m) const; + virtual void augAssignAnd(const MatExpr& expr, Mat& m) const; + virtual void augAssignOr(const MatExpr& expr, Mat& m) const; + virtual void augAssignXor(const MatExpr& expr, Mat& m) const; + + virtual void add(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; + virtual void add(const MatExpr& expr1, const Scalar& s, MatExpr& res) const; + + virtual void subtract(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; + virtual void subtract(const Scalar& s, const MatExpr& expr, MatExpr& res) const; + + virtual void multiply(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; + virtual void multiply(const MatExpr& expr1, double s, MatExpr& res) const; + + virtual void divide(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res, double scale=1) const; + virtual void divide(double s, const MatExpr& expr, MatExpr& res) const; + + virtual void abs(const MatExpr& expr, MatExpr& res) const; + + virtual void transpose(const MatExpr& expr, MatExpr& res) const; + virtual void matmul(const MatExpr& expr1, const MatExpr& expr2, MatExpr& res) const; + virtual void invert(const MatExpr& expr, int method, MatExpr& res) const; + + virtual Size size(const MatExpr& expr) const; + virtual int type(const MatExpr& expr) const; +}; + +/** @brief Matrix expression representation +@anchor MatrixExpressions +This is a list of implemented matrix operations that can be combined in arbitrary complex +expressions (here A, B stand for matrices ( Mat ), s for a scalar ( Scalar ), alpha for a +real-valued scalar ( double )): +- Addition, subtraction, negation: `A+B`, `A-B`, `A+s`, `A-s`, `s+A`, `s-A`, `-A` +- Scaling: `A*alpha` +- Per-element multiplication and division: `A.mul(B)`, `A/B`, `alpha/A` +- Matrix multiplication: `A*B` +- Transposition: `A.t()` (means AT) +- Matrix inversion and pseudo-inversion, solving linear systems and least-squares problems: + `A.inv([method]) (~ A-1)`, `A.inv([method])*B (~ X: AX=B)` +- Comparison: `A cmpop B`, `A cmpop alpha`, `alpha cmpop A`, where *cmpop* is one of + `>`, `>=`, `==`, `!=`, `<=`, `<`. The result of comparison is an 8-bit single channel mask whose + elements are set to 255 (if the particular element or pair of elements satisfy the condition) or + 0. +- Bitwise logical operations: `A logicop B`, `A logicop s`, `s logicop A`, `~A`, where *logicop* is one of + `&`, `|`, `^`. +- Element-wise minimum and maximum: `min(A, B)`, `min(A, alpha)`, `max(A, B)`, `max(A, alpha)` +- Element-wise absolute value: `abs(A)` +- Cross-product, dot-product: `A.cross(B)`, `A.dot(B)` +- Any function of matrix or matrices and scalars that returns a matrix or a scalar, such as norm, + mean, sum, countNonZero, trace, determinant, repeat, and others. +- Matrix initializers ( Mat::eye(), Mat::zeros(), Mat::ones() ), matrix comma-separated + initializers, matrix constructors and operators that extract sub-matrices (see Mat description). +- Mat_() constructors to cast the result to the proper type. +@note Comma-separated initializers and probably some other operations may require additional +explicit Mat() or Mat_() constructor calls to resolve a possible ambiguity. + +Here are examples of matrix expressions: +@code + // compute pseudo-inverse of A, equivalent to A.inv(DECOMP_SVD) + SVD svd(A); + Mat pinvA = svd.vt.t()*Mat::diag(1./svd.w)*svd.u.t(); + + // compute the new vector of parameters in the Levenberg-Marquardt algorithm + x -= (A.t()*A + lambda*Mat::eye(A.cols,A.cols,A.type())).inv(DECOMP_CHOLESKY)*(A.t()*err); + + // sharpen image using "unsharp mask" algorithm + Mat blurred; double sigma = 1, threshold = 5, amount = 1; + GaussianBlur(img, blurred, Size(), sigma, sigma); + Mat lowContrastMask = abs(img - blurred) < threshold; + Mat sharpened = img*(1+amount) + blurred*(-amount); + img.copyTo(sharpened, lowContrastMask); +@endcode +*/ +class CV_EXPORTS MatExpr +{ +public: + MatExpr(); + explicit MatExpr(const Mat& m); + + MatExpr(const MatOp* _op, int _flags, const Mat& _a = Mat(), const Mat& _b = Mat(), + const Mat& _c = Mat(), double _alpha = 1, double _beta = 1, const Scalar& _s = Scalar()); + + operator Mat() const; + template operator Mat_<_Tp>() const; + + Size size() const; + int type() const; + + MatExpr row(int y) const; + MatExpr col(int x) const; + MatExpr diag(int d = 0) const; + MatExpr operator()( const Range& rowRange, const Range& colRange ) const; + MatExpr operator()( const Rect& roi ) const; + + MatExpr t() const; + MatExpr inv(int method = DECOMP_LU) const; + MatExpr mul(const MatExpr& e, double scale=1) const; + MatExpr mul(const Mat& m, double scale=1) const; + + Mat cross(const Mat& m) const; + double dot(const Mat& m) const; + + void swap(MatExpr& b); + + const MatOp* op; + int flags; + + Mat a, b, c; + double alpha, beta; + Scalar s; +}; + +//! @} core_basic + +//! @relates cv::MatExpr +//! @{ +CV_EXPORTS MatExpr operator + (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator + (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator + (const Scalar& s, const Mat& a); +CV_EXPORTS MatExpr operator + (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator + (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator + (const MatExpr& e, const Scalar& s); +CV_EXPORTS MatExpr operator + (const Scalar& s, const MatExpr& e); +CV_EXPORTS MatExpr operator + (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator + (const Mat& a, const Matx<_Tp, m, n>& b) { return a + Mat(b); } +template static inline +MatExpr operator + (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) + b; } + +CV_EXPORTS MatExpr operator - (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator - (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator - (const Scalar& s, const Mat& a); +CV_EXPORTS MatExpr operator - (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator - (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator - (const MatExpr& e, const Scalar& s); +CV_EXPORTS MatExpr operator - (const Scalar& s, const MatExpr& e); +CV_EXPORTS MatExpr operator - (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator - (const Mat& a, const Matx<_Tp, m, n>& b) { return a - Mat(b); } +template static inline +MatExpr operator - (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) - b; } + +CV_EXPORTS MatExpr operator - (const Mat& m); +CV_EXPORTS MatExpr operator - (const MatExpr& e); + +CV_EXPORTS MatExpr operator * (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator * (const Mat& a, double s); +CV_EXPORTS MatExpr operator * (double s, const Mat& a); +CV_EXPORTS MatExpr operator * (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator * (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator * (const MatExpr& e, double s); +CV_EXPORTS MatExpr operator * (double s, const MatExpr& e); +CV_EXPORTS MatExpr operator * (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator * (const Mat& a, const Matx<_Tp, m, n>& b) { return a * Mat(b); } +template static inline +MatExpr operator * (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) * b; } + +CV_EXPORTS MatExpr operator / (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator / (const Mat& a, double s); +CV_EXPORTS MatExpr operator / (double s, const Mat& a); +CV_EXPORTS MatExpr operator / (const MatExpr& e, const Mat& m); +CV_EXPORTS MatExpr operator / (const Mat& m, const MatExpr& e); +CV_EXPORTS MatExpr operator / (const MatExpr& e, double s); +CV_EXPORTS MatExpr operator / (double s, const MatExpr& e); +CV_EXPORTS MatExpr operator / (const MatExpr& e1, const MatExpr& e2); +template static inline +MatExpr operator / (const Mat& a, const Matx<_Tp, m, n>& b) { return a / Mat(b); } +template static inline +MatExpr operator / (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) / b; } + +CV_EXPORTS MatExpr operator < (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator < (const Mat& a, double s); +CV_EXPORTS MatExpr operator < (double s, const Mat& a); +template static inline +MatExpr operator < (const Mat& a, const Matx<_Tp, m, n>& b) { return a < Mat(b); } +template static inline +MatExpr operator < (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) < b; } + +CV_EXPORTS MatExpr operator <= (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator <= (const Mat& a, double s); +CV_EXPORTS MatExpr operator <= (double s, const Mat& a); +template static inline +MatExpr operator <= (const Mat& a, const Matx<_Tp, m, n>& b) { return a <= Mat(b); } +template static inline +MatExpr operator <= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) <= b; } + +CV_EXPORTS MatExpr operator == (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator == (const Mat& a, double s); +CV_EXPORTS MatExpr operator == (double s, const Mat& a); +template static inline +MatExpr operator == (const Mat& a, const Matx<_Tp, m, n>& b) { return a == Mat(b); } +template static inline +MatExpr operator == (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) == b; } + +CV_EXPORTS MatExpr operator != (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator != (const Mat& a, double s); +CV_EXPORTS MatExpr operator != (double s, const Mat& a); +template static inline +MatExpr operator != (const Mat& a, const Matx<_Tp, m, n>& b) { return a != Mat(b); } +template static inline +MatExpr operator != (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) != b; } + +CV_EXPORTS MatExpr operator >= (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator >= (const Mat& a, double s); +CV_EXPORTS MatExpr operator >= (double s, const Mat& a); +template static inline +MatExpr operator >= (const Mat& a, const Matx<_Tp, m, n>& b) { return a >= Mat(b); } +template static inline +MatExpr operator >= (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) >= b; } + +CV_EXPORTS MatExpr operator > (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator > (const Mat& a, double s); +CV_EXPORTS MatExpr operator > (double s, const Mat& a); +template static inline +MatExpr operator > (const Mat& a, const Matx<_Tp, m, n>& b) { return a > Mat(b); } +template static inline +MatExpr operator > (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) > b; } + +CV_EXPORTS MatExpr operator & (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator & (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator & (const Scalar& s, const Mat& a); +template static inline +MatExpr operator & (const Mat& a, const Matx<_Tp, m, n>& b) { return a & Mat(b); } +template static inline +MatExpr operator & (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) & b; } + +CV_EXPORTS MatExpr operator | (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator | (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator | (const Scalar& s, const Mat& a); +template static inline +MatExpr operator | (const Mat& a, const Matx<_Tp, m, n>& b) { return a | Mat(b); } +template static inline +MatExpr operator | (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) | b; } + +CV_EXPORTS MatExpr operator ^ (const Mat& a, const Mat& b); +CV_EXPORTS MatExpr operator ^ (const Mat& a, const Scalar& s); +CV_EXPORTS MatExpr operator ^ (const Scalar& s, const Mat& a); +template static inline +MatExpr operator ^ (const Mat& a, const Matx<_Tp, m, n>& b) { return a ^ Mat(b); } +template static inline +MatExpr operator ^ (const Matx<_Tp, m, n>& a, const Mat& b) { return Mat(a) ^ b; } + +CV_EXPORTS MatExpr operator ~(const Mat& m); + +CV_EXPORTS MatExpr min(const Mat& a, const Mat& b); +CV_EXPORTS MatExpr min(const Mat& a, double s); +CV_EXPORTS MatExpr min(double s, const Mat& a); +template static inline +MatExpr min (const Mat& a, const Matx<_Tp, m, n>& b) { return min(a, Mat(b)); } +template static inline +MatExpr min (const Matx<_Tp, m, n>& a, const Mat& b) { return min(Mat(a), b); } + +CV_EXPORTS MatExpr max(const Mat& a, const Mat& b); +CV_EXPORTS MatExpr max(const Mat& a, double s); +CV_EXPORTS MatExpr max(double s, const Mat& a); +template static inline +MatExpr max (const Mat& a, const Matx<_Tp, m, n>& b) { return max(a, Mat(b)); } +template static inline +MatExpr max (const Matx<_Tp, m, n>& a, const Mat& b) { return max(Mat(a), b); } + +/** @brief Calculates an absolute value of each matrix element. + +abs is a meta-function that is expanded to one of absdiff or convertScaleAbs forms: +- C = abs(A-B) is equivalent to `absdiff(A, B, C)` +- C = abs(A) is equivalent to `absdiff(A, Scalar::all(0), C)` +- C = `Mat_ >(abs(A*alpha + beta))` is equivalent to `convertScaleAbs(A, C, alpha, +beta)` + +The output matrix has the same size and the same type as the input one except for the last case, +where C is depth=CV_8U . +@param m matrix. +@sa @ref MatrixExpressions, absdiff, convertScaleAbs + */ +CV_EXPORTS MatExpr abs(const Mat& m); +/** @overload +@param e matrix expression. +*/ +CV_EXPORTS MatExpr abs(const MatExpr& e); +//! @} relates cv::MatExpr + +} // cv + +#include "opencv2/core/mat.inl.hpp" + +#endif // OPENCV_CORE_MAT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp index 0d9c557bce..bd0ba637b5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/mat.inl.hpp @@ -1,3422 +1,3422 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_MATRIX_OPERATIONS_HPP -#define OPENCV_CORE_MATRIX_OPERATIONS_HPP - -#ifndef __cplusplus -# error mat.inl.hpp header must be compiled as C++ -#endif - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 4127 5054 ) -#endif - -#if defined(CV_SKIP_DISABLE_CLANG_ENUM_WARNINGS) - // nothing -#elif defined(CV_FORCE_DISABLE_CLANG_ENUM_WARNINGS) - #define CV_DISABLE_CLANG_ENUM_WARNINGS -#elif defined(__clang__) && defined(__has_warning) - #if __has_warning("-Wdeprecated-enum-enum-conversion") && __has_warning("-Wdeprecated-anon-enum-enum-conversion") - #define CV_DISABLE_CLANG_ENUM_WARNINGS - #endif -#endif -#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" -#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion" -#endif - -namespace cv -{ -CV__DEBUG_NS_BEGIN - - -//! @cond IGNORED - -////////////////////////// Custom (raw) type wrapper ////////////////////////// - -template static inline -int rawType() -{ - CV_StaticAssert(sizeof(_Tp) <= CV_CN_MAX, "sizeof(_Tp) is too large"); - const int elemSize = sizeof(_Tp); - return (int)CV_MAKETYPE(CV_8U, elemSize); -} - -//////////////////////// Input/Output Arrays //////////////////////// - -inline void _InputArray::init(int _flags, const void* _obj) -{ flags = _flags; obj = (void*)_obj; } - -inline void _InputArray::init(int _flags, const void* _obj, Size _sz) -{ flags = _flags; obj = (void*)_obj; sz = _sz; } - -inline void* _InputArray::getObj() const { return obj; } -inline int _InputArray::getFlags() const { return flags; } -inline Size _InputArray::getSz() const { return sz; } - -inline _InputArray::_InputArray() { init(0 + NONE, 0); } -inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); } -inline _InputArray::_InputArray(const Mat& m) { init(+MAT+ACCESS_READ, &m); } -inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_READ, &vec); } -inline _InputArray::_InputArray(const UMat& m) { init(+UMAT+ACCESS_READ, &m); } -inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::vector<_Tp>& vec) -{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, arr.data(), Size(1, _Nm)); } - -template inline -_InputArray::_InputArray(const std::array& arr) -{ init(+STD_ARRAY_MAT + ACCESS_READ, arr.data(), Size(1, _Nm)); } - -inline -_InputArray::_InputArray(const std::vector& vec) -{ init(FIXED_TYPE + STD_BOOL_VECTOR + traits::Type::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_READ, &vec); } - -template inline -_InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, &mtx, Size(n, m)); } - -template inline -_InputArray::_InputArray(const _Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, vec, Size(n, 1)); } - -template inline -_InputArray::_InputArray(const Mat_<_Tp>& m) -{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_READ, &m); } - -inline _InputArray::_InputArray(const double& val) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); } - -inline _InputArray::_InputArray(const cuda::GpuMat& d_mat) -{ init(+CUDA_GPU_MAT + ACCESS_READ, &d_mat); } - -inline _InputArray::_InputArray(const std::vector& d_mat) -{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_READ, &d_mat);} - -inline _InputArray::_InputArray(const ogl::Buffer& buf) -{ init(+OPENGL_BUFFER + ACCESS_READ, &buf); } - -inline _InputArray::_InputArray(const cuda::HostMem& cuda_mem) -{ init(+CUDA_HOST_MEM + ACCESS_READ, &cuda_mem); } - -template inline -_InputArray _InputArray::rawIn(const std::vector<_Tp>& vec) -{ - _InputArray v; - v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_READ; - v.obj = (void*)&vec; - return v; -} - -template inline -_InputArray _InputArray::rawIn(const std::array<_Tp, _Nm>& arr) -{ - _InputArray v; - v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ; - v.obj = (void*)arr.data(); - v.sz = Size(1, _Nm); - return v; -} - -inline _InputArray::~_InputArray() {} - -inline Mat _InputArray::getMat(int i) const -{ - if( kind() == MAT && i < 0 ) - return *(const Mat*)obj; - return getMat_(i); -} - -inline bool _InputArray::isMat() const { return kind() == _InputArray::MAT; } -inline bool _InputArray::isUMat() const { return kind() == _InputArray::UMAT; } -inline bool _InputArray::isMatVector() const { return kind() == _InputArray::STD_VECTOR_MAT; } -inline bool _InputArray::isUMatVector() const { return kind() == _InputArray::STD_VECTOR_UMAT; } -inline bool _InputArray::isMatx() const { return kind() == _InputArray::MATX; } -inline bool _InputArray::isVector() const { return kind() == _InputArray::STD_VECTOR || - kind() == _InputArray::STD_BOOL_VECTOR || - (kind() == _InputArray::MATX && (sz.width <= 1 || sz.height <= 1)); } -inline bool _InputArray::isGpuMat() const { return kind() == _InputArray::CUDA_GPU_MAT; } -inline bool _InputArray::isGpuMatVector() const { return kind() == _InputArray::STD_VECTOR_CUDA_GPU_MAT; } - -//////////////////////////////////////////////////////////////////////////////////////// - -inline _OutputArray::_OutputArray() { init(+NONE + ACCESS_WRITE, 0); } -inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags + ACCESS_WRITE, _obj); } -inline _OutputArray::_OutputArray(Mat& m) { init(+MAT+ACCESS_WRITE, &m); } -inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_MAT + ACCESS_WRITE, &vec); } -inline _OutputArray::_OutputArray(UMat& m) { init(+UMAT + ACCESS_WRITE, &m); } -inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(std::vector<_Tp>& vec) -{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(std::array& arr) -{ init(+STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(Mat_<_Tp>& m) -{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } - -template inline -_OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } - -template inline -_OutputArray::_OutputArray(_Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } - -template inline -_OutputArray::_OutputArray(const std::vector<_Tp>& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(const std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(const std::array& arr) -{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } - -template inline -_OutputArray::_OutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } - -template inline -_OutputArray::_OutputArray(const Mat_<_Tp>& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } - -template inline -_OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } - -template inline -_OutputArray::_OutputArray(const _Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } - -inline _OutputArray::_OutputArray(cuda::GpuMat& d_mat) -{ init(+CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } - -inline _OutputArray::_OutputArray(std::vector& d_mat) -{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_WRITE, &d_mat);} - -inline _OutputArray::_OutputArray(ogl::Buffer& buf) -{ init(+OPENGL_BUFFER + ACCESS_WRITE, &buf); } - -inline _OutputArray::_OutputArray(cuda::HostMem& cuda_mem) -{ init(+CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } - -inline _OutputArray::_OutputArray(const Mat& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_WRITE, &m); } - -inline _OutputArray::_OutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_WRITE, &vec); } - -inline _OutputArray::_OutputArray(const UMat& m) -{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_WRITE, &m); } - -inline _OutputArray::_OutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } - -inline _OutputArray::_OutputArray(const cuda::GpuMat& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } - - -inline _OutputArray::_OutputArray(const ogl::Buffer& buf) -{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_WRITE, &buf); } - -inline _OutputArray::_OutputArray(const cuda::HostMem& cuda_mem) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } - -template inline -_OutputArray _OutputArray::rawOut(std::vector<_Tp>& vec) -{ - _OutputArray v; - v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_WRITE; - v.obj = (void*)&vec; - return v; -} - -template inline -_OutputArray _OutputArray::rawOut(std::array<_Tp, _Nm>& arr) -{ - _OutputArray v; - v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE; - v.obj = (void*)arr.data(); - v.sz = Size(1, _Nm); - return v; -} - -/////////////////////////////////////////////////////////////////////////////////////////// - -inline _InputOutputArray::_InputOutputArray() { init(0+ACCESS_RW, 0); } -inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags+ACCESS_RW, _obj); } -inline _InputOutputArray::_InputOutputArray(Mat& m) { init(+MAT+ACCESS_RW, &m); } -inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_RW, &vec); } -inline _InputOutputArray::_InputOutputArray(UMat& m) { init(+UMAT+ACCESS_RW, &m); } -inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec) -{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(std::array& arr) -{ init(+STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(std::vector >& vec) -{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(Mat_<_Tp>& m) -{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } - -template inline -_InputOutputArray::_InputOutputArray(Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } - -template inline -_InputOutputArray::_InputOutputArray(_Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } - -template inline -_InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(const std::array<_Tp, _Nm>& arr) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(const std::array& arr) -{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } - -template inline -_InputOutputArray::_InputOutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(const std::vector >& vec) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } - -template inline -_InputOutputArray::_InputOutputArray(const Mat_<_Tp>& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } - -template inline -_InputOutputArray::_InputOutputArray(const Matx<_Tp, m, n>& mtx) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } - -template inline -_InputOutputArray::_InputOutputArray(const _Tp* vec, int n) -{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } - -inline _InputOutputArray::_InputOutputArray(cuda::GpuMat& d_mat) -{ init(+CUDA_GPU_MAT + ACCESS_RW, &d_mat); } - -inline _InputOutputArray::_InputOutputArray(ogl::Buffer& buf) -{ init(+OPENGL_BUFFER + ACCESS_RW, &buf); } - -inline _InputOutputArray::_InputOutputArray(cuda::HostMem& cuda_mem) -{ init(+CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } - -inline _InputOutputArray::_InputOutputArray(const Mat& m) -{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_RW, &m); } - -inline _InputOutputArray::_InputOutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_RW, &vec); } - -inline _InputOutputArray::_InputOutputArray(const UMat& m) -{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_RW, &m); } - -inline _InputOutputArray::_InputOutputArray(const std::vector& vec) -{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_RW, &vec); } - -inline _InputOutputArray::_InputOutputArray(const cuda::GpuMat& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_RW, &d_mat); } - -inline _InputOutputArray::_InputOutputArray(const std::vector& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} - -template<> inline _InputOutputArray::_InputOutputArray(std::vector& d_mat) -{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} - -inline _InputOutputArray::_InputOutputArray(const ogl::Buffer& buf) -{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_RW, &buf); } - -inline _InputOutputArray::_InputOutputArray(const cuda::HostMem& cuda_mem) -{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } - -template inline -_InputOutputArray _InputOutputArray::rawInOut(std::vector<_Tp>& vec) -{ - _InputOutputArray v; - v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_RW; - v.obj = (void*)&vec; - return v; -} - -template inline -_InputOutputArray _InputOutputArray::rawInOut(std::array<_Tp, _Nm>& arr) -{ - _InputOutputArray v; - v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW; - v.obj = (void*)arr.data(); - v.sz = Size(1, _Nm); - return v; -} - - -template static inline _InputArray rawIn(_Tp& v) { return _InputArray::rawIn(v); } -template static inline _OutputArray rawOut(_Tp& v) { return _OutputArray::rawOut(v); } -template static inline _InputOutputArray rawInOut(_Tp& v) { return _InputOutputArray::rawInOut(v); } - -CV__DEBUG_NS_END - -//////////////////////////////////////////// Mat ////////////////////////////////////////// - -template inline -Mat::Mat(const std::vector<_Tp>& vec, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), - cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if(vec.empty()) - return; - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)&vec[0]; - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); -} - -template inline -Mat::Mat(const std::initializer_list<_Tp> list) - : Mat() -{ - CV_Assert(list.size() != 0); - Mat((int)list.size(), 1, traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); -} - -template inline -Mat::Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list) - : Mat() -{ - size_t size_total = 1; - for(auto s : sizes) - size_total *= s; - CV_Assert(list.size() != 0); - CV_Assert(size_total == list.size()); - Mat((int)sizes.size(), (int*)sizes.begin(), traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); -} - -template inline -Mat::Mat(const std::array<_Tp, _Nm>& arr, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)arr.size()), - cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if(arr.empty()) - return; - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)arr.data(); - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat((int)arr.size(), 1, traits::Type<_Tp>::value, (uchar*)arr.data()).copyTo(*this); -} - -template inline -Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)vec.val; - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat(n, 1, traits::Type<_Tp>::value, (void*)vec.val).copyTo(*this); -} - - -template inline -Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = cols * sizeof(_Tp); - step[1] = sizeof(_Tp); - datastart = data = (uchar*)M.val; - datalimit = dataend = datastart + rows * step[0]; - } - else - Mat(m, n, traits::Type<_Tp>::value, (uchar*)M.val).copyTo(*this); -} - -template inline -Mat::Mat(const Point_<_Tp>& pt, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)&pt.x; - datalimit = dataend = datastart + rows * step[0]; - } - else - { - create(2, 1, traits::Type<_Tp>::value); - ((_Tp*)data)[0] = pt.x; - ((_Tp*)data)[1] = pt.y; - } -} - -template inline -Mat::Mat(const Point3_<_Tp>& pt, bool copyData) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0), - datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) -{ - if( !copyData ) - { - step[0] = step[1] = sizeof(_Tp); - datastart = data = (uchar*)&pt.x; - datalimit = dataend = datastart + rows * step[0]; - } - else - { - create(3, 1, traits::Type<_Tp>::value); - ((_Tp*)data)[0] = pt.x; - ((_Tp*)data)[1] = pt.y; - ((_Tp*)data)[2] = pt.z; - } -} - -template inline -Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) - : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0), - datastart(0), dataend(0), allocator(0), u(0), size(&rows) -{ - *this = commaInitializer.operator Mat_<_Tp>(); -} - -inline -Mat Mat::row(int y) const -{ - return Mat(*this, Range(y, y + 1), Range::all()); -} - -inline -Mat Mat::col(int x) const -{ - return Mat(*this, Range::all(), Range(x, x + 1)); -} - -inline -Mat Mat::rowRange(int startrow, int endrow) const -{ - return Mat(*this, Range(startrow, endrow), Range::all()); -} - -inline -Mat Mat::rowRange(const Range& r) const -{ - return Mat(*this, r, Range::all()); -} - -inline -Mat Mat::colRange(int startcol, int endcol) const -{ - return Mat(*this, Range::all(), Range(startcol, endcol)); -} - -inline -Mat Mat::colRange(const Range& r) const -{ - return Mat(*this, Range::all(), r); -} - -inline -Mat Mat::operator()( Range _rowRange, Range _colRange ) const -{ - return Mat(*this, _rowRange, _colRange); -} - -inline -Mat Mat::operator()( const Rect& roi ) const -{ - return Mat(*this, roi); -} - -inline -Mat Mat::operator()(const Range* ranges) const -{ - return Mat(*this, ranges); -} - -inline -Mat Mat::operator()(const std::vector& ranges) const -{ - return Mat(*this, ranges); -} - -inline -bool Mat::isContinuous() const -{ - return (flags & CONTINUOUS_FLAG) != 0; -} - -inline -bool Mat::isSubmatrix() const -{ - return (flags & SUBMATRIX_FLAG) != 0; -} - -inline -size_t Mat::elemSize() const -{ - size_t res = dims > 0 ? step.p[dims - 1] : 0; - CV_DbgAssert(res != 0); - return res; -} - -inline -size_t Mat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int Mat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int Mat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int Mat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -uchar* Mat::ptr(int y) -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return data + step.p[0] * y; -} - -inline -const uchar* Mat::ptr(int y) const -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return data + step.p[0] * y; -} - -template inline -_Tp* Mat::ptr(int y) -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return (_Tp*)(data + step.p[0] * y); -} - -template inline -const _Tp* Mat::ptr(int y) const -{ - CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); - return (const _Tp*)(data + step.p[0] * y); -} - -inline -uchar* Mat::ptr(int i0, int i1) -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return data + i0 * step.p[0] + i1 * step.p[1]; -} - -inline -const uchar* Mat::ptr(int i0, int i1) const -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return data + i0 * step.p[0] + i1 * step.p[1]; -} - -template inline -_Tp* Mat::ptr(int i0, int i1) -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); -} - -template inline -const _Tp* Mat::ptr(int i0, int i1) const -{ - CV_DbgAssert(dims >= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); -} - -inline -uchar* Mat::ptr(int i0, int i1, int i2) -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; -} - -inline -const uchar* Mat::ptr(int i0, int i1, int i2) const -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; -} - -template inline -_Tp* Mat::ptr(int i0, int i1, int i2) -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); -} - -template inline -const _Tp* Mat::ptr(int i0, int i1, int i2) const -{ - CV_DbgAssert(dims >= 3); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); - return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); -} - -inline -uchar* Mat::ptr(const int* idx) -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return p; -} - -inline -const uchar* Mat::ptr(const int* idx) const -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return p; -} - -template inline -_Tp* Mat::ptr(const int* idx) -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return (_Tp*)p; -} - -template inline -const _Tp* Mat::ptr(const int* idx) const -{ - int i, d = dims; - uchar* p = data; - CV_DbgAssert( d >= 1 && p ); - for( i = 0; i < d; i++ ) - { - CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); - p += idx[i] * step.p[i]; - } - return (const _Tp*)p; -} - -template inline -uchar* Mat::ptr(const Vec& idx) -{ - return Mat::ptr(idx.val); -} - -template inline -const uchar* Mat::ptr(const Vec& idx) const -{ - return Mat::ptr(idx.val); -} - -template inline -_Tp* Mat::ptr(const Vec& idx) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return Mat::ptr<_Tp>(idx.val); -} - -template inline -const _Tp* Mat::ptr(const Vec& idx) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return Mat::ptr<_Tp>(idx.val); -} - - -template inline -_Tp& Mat::at(int i0, int i1) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((_Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -const _Tp& Mat::at(int i0, int i1) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((const _Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -_Tp& Mat::at(Point pt) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -const _Tp& Mat::at(Point pt) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); - CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); - return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -_Tp& Mat::at(int i0) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); - CV_DbgAssert(elemSize() == sizeof(_Tp)); - if( isContinuous() || size.p[0] == 1 ) - return ((_Tp*)data)[i0]; - if( size.p[1] == 1 ) - return *(_Tp*)(data + step.p[0] * i0); - int i = i0 / cols, j = i0 - i * cols; - return ((_Tp*)(data + step.p[0] * i))[j]; -} - -template inline -const _Tp& Mat::at(int i0) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); - CV_DbgAssert(elemSize() == sizeof(_Tp)); - if( isContinuous() || size.p[0] == 1 ) - return ((const _Tp*)data)[i0]; - if( size.p[1] == 1 ) - return *(const _Tp*)(data + step.p[0] * i0); - int i = i0 / cols, j = i0 - i * cols; - return ((const _Tp*)(data + step.p[0] * i))[j]; -} - -template inline -_Tp& Mat::at(int i0, int i1, int i2) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(_Tp*)ptr(i0, i1, i2); -} - -template inline -const _Tp& Mat::at(int i0, int i1, int i2) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(const _Tp*)ptr(i0, i1, i2); -} - -template inline -_Tp& Mat::at(const int* idx) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(_Tp*)ptr(idx); -} - -template inline -const _Tp& Mat::at(const int* idx) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(const _Tp*)ptr(idx); -} - -template inline -_Tp& Mat::at(const Vec& idx) -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(_Tp*)ptr(idx.val); -} - -template inline -const _Tp& Mat::at(const Vec& idx) const -{ - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return *(const _Tp*)ptr(idx.val); -} - -template inline -MatConstIterator_<_Tp> Mat::begin() const -{ - if (empty()) - return MatConstIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this); -} - -template inline -std::reverse_iterator> Mat::rbegin() const -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); - it += total(); - return std::reverse_iterator> (it); -} - -template inline -MatConstIterator_<_Tp> Mat::end() const -{ - if (empty()) - return MatConstIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); - it += total(); - return it; -} - -template inline -std::reverse_iterator> Mat::rend() const -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return std::reverse_iterator>((const Mat_<_Tp>*)this); -} - -template inline -MatIterator_<_Tp> Mat::begin() -{ - if (empty()) - return MatIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return MatIterator_<_Tp>((Mat_<_Tp>*)this); -} - -template inline -std::reverse_iterator> Mat::rbegin() -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatIterator_<_Tp> it((Mat_<_Tp>*)this); - it += total(); - return std::reverse_iterator>(it); -} - -template inline -MatIterator_<_Tp> Mat::end() -{ - if (empty()) - return MatIterator_<_Tp>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - MatIterator_<_Tp> it((Mat_<_Tp>*)this); - it += total(); - return it; -} - -template inline -std::reverse_iterator> Mat::rend() -{ - if (empty()) - return std::reverse_iterator>(); - CV_DbgAssert( elemSize() == sizeof(_Tp) ); - return std::reverse_iterator>(MatIterator_<_Tp>((Mat_<_Tp>*)this)); -} - -template inline -void Mat::forEach(const Functor& operation) { - this->forEach_impl<_Tp>(operation); -} - -template inline -void Mat::forEach(const Functor& operation) const { - // call as not const - (const_cast(this))->forEach<_Tp>(operation); -} - -template inline -Mat::operator std::vector<_Tp>() const -{ - std::vector<_Tp> v; - copyTo(v); - return v; -} - -template inline -Mat::operator std::array<_Tp, _Nm>() const -{ - std::array<_Tp, _Nm> v; - copyTo(v); - return v; -} - -template inline -Mat::operator Vec<_Tp, n>() const -{ - CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && - rows + cols - 1 == n && channels() == 1 ); - - if( isContinuous() && type() == traits::Type<_Tp>::value ) - return Vec<_Tp, n>((_Tp*)data); - Vec<_Tp, n> v; - Mat tmp(rows, cols, traits::Type<_Tp>::value, v.val); - convertTo(tmp, tmp.type()); - return v; -} - -template inline -Mat::operator Matx<_Tp, m, n>() const -{ - CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); - - if( isContinuous() && type() == traits::Type<_Tp>::value ) - return Matx<_Tp, m, n>((_Tp*)data); - Matx<_Tp, m, n> mtx; - Mat tmp(rows, cols, traits::Type<_Tp>::value, mtx.val); - convertTo(tmp, tmp.type()); - return mtx; -} - -template inline -void Mat::push_back(const _Tp& elem) -{ - if( !data ) - { - *this = Mat(1, 1, traits::Type<_Tp>::value, (void*)&elem).clone(); - return; - } - CV_Assert(traits::Type<_Tp>::value == type() && cols == 1 - /* && dims == 2 (cols == 1 implies dims == 2) */); - const uchar* tmp = dataend + step[0]; - if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) - { - *(_Tp*)(data + (size.p[0]++) * step.p[0]) = elem; - dataend = tmp; - } - else - push_back_(&elem); -} - -template inline -void Mat::push_back(const Mat_<_Tp>& m) -{ - push_back((const Mat&)m); -} - -template<> inline -void Mat::push_back(const MatExpr& expr) -{ - push_back(static_cast(expr)); -} - - -template inline -void Mat::push_back(const std::vector<_Tp>& v) -{ - push_back(Mat(v)); -} - - -///////////////////////////// MatSize //////////////////////////// - -inline -MatSize::MatSize(int* _p) CV_NOEXCEPT - : p(_p) {} - -inline -int MatSize::dims() const CV_NOEXCEPT -{ - return (p - 1)[0]; -} - -inline -Size MatSize::operator()() const -{ - CV_DbgAssert(dims() <= 2); - return Size(p[1], p[0]); -} - -inline -const int& MatSize::operator[](int i) const -{ - CV_DbgAssert(i < dims()); -#ifdef __OPENCV_BUILD - CV_DbgAssert(i >= 0); -#endif - return p[i]; -} - -inline -int& MatSize::operator[](int i) -{ - CV_DbgAssert(i < dims()); -#ifdef __OPENCV_BUILD - CV_DbgAssert(i >= 0); -#endif - return p[i]; -} - -inline -MatSize::operator const int*() const CV_NOEXCEPT -{ - return p; -} - -inline -bool MatSize::operator != (const MatSize& sz) const CV_NOEXCEPT -{ - return !(*this == sz); -} - - - -///////////////////////////// MatStep //////////////////////////// - -inline -MatStep::MatStep() CV_NOEXCEPT -{ - p = buf; p[0] = p[1] = 0; -} - -inline -MatStep::MatStep(size_t s) CV_NOEXCEPT -{ - p = buf; p[0] = s; p[1] = 0; -} - -inline -const size_t& MatStep::operator[](int i) const CV_NOEXCEPT -{ - return p[i]; -} - -inline -size_t& MatStep::operator[](int i) CV_NOEXCEPT -{ - return p[i]; -} - -inline MatStep::operator size_t() const -{ - CV_DbgAssert( p == buf ); - return buf[0]; -} - -inline MatStep& MatStep::operator = (size_t s) -{ - CV_DbgAssert( p == buf ); - buf[0] = s; - return *this; -} - - - -////////////////////////////// Mat_<_Tp> //////////////////////////// - -template inline -Mat_<_Tp>::Mat_() CV_NOEXCEPT - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; -} - -template inline -Mat_<_Tp>::Mat_(int _rows, int _cols) - : Mat(_rows, _cols, traits::Type<_Tp>::value) -{ -} - -template inline -Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value) - : Mat(_rows, _cols, traits::Type<_Tp>::value) -{ - *this = value; -} - -template inline -Mat_<_Tp>::Mat_(Size _sz) - : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) -{} - -template inline -Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) - : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) -{ - *this = value; -} - -template inline -Mat_<_Tp>::Mat_(int _dims, const int* _sz) - : Mat(_dims, _sz, traits::Type<_Tp>::value) -{} - -template inline -Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) - : Mat(_dims, _sz, traits::Type<_Tp>::value, Scalar(_s)) -{} - -template inline -Mat_<_Tp>::Mat_(int _dims, const int* _sz, _Tp* _data, const size_t* _steps) - : Mat(_dims, _sz, traits::Type<_Tp>::value, _data, _steps) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) - : Mat(m, ranges) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const std::vector& ranges) - : Mat(m, ranges) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat& m) - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; - *this = m; -} - -template inline -Mat_<_Tp>::Mat_(const Mat_& m) - : Mat(m) -{} - -template inline -Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) - : Mat(_rows, _cols, traits::Type<_Tp>::value, _data, steps) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) - : Mat(m, _rowRange, _colRange) -{} - -template inline -Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) - : Mat(m, roi) -{} - -template template inline -Mat_<_Tp>::Mat_(const Vec::channel_type, n>& vec, bool copyData) - : Mat(n / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&vec) -{ - CV_Assert(n%DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template template inline -Mat_<_Tp>::Mat_(const Matx::channel_type, m, n>& M, bool copyData) - : Mat(m, n / DataType<_Tp>::channels, traits::Type<_Tp>::value, (void*)&M) -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline -Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) - : Mat(2 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) -{ - CV_Assert(2 % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline -Mat_<_Tp>::Mat_(const Point3_::channel_type>& pt, bool copyData) - : Mat(3 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) -{ - CV_Assert(3 % DataType<_Tp>::channels == 0); - if( copyData ) - *this = clone(); -} - -template inline -Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) - : Mat(commaInitializer) -{} - -template inline -Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData) - : Mat(vec, copyData) -{} - -template inline -Mat_<_Tp>::Mat_(std::initializer_list<_Tp> list) - : Mat(list) -{} - -template inline -Mat_<_Tp>::Mat_(const std::initializer_list sizes, std::initializer_list<_Tp> list) - : Mat(sizes, list) -{} - -template template inline -Mat_<_Tp>::Mat_(const std::array<_Tp, _Nm>& arr, bool copyData) - : Mat(arr, copyData) -{} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m) -{ - if (m.empty()) - { - release(); - return *this; - } - if( traits::Type<_Tp>::value == m.type() ) - { - Mat::operator = (m); - return *this; - } - if( traits::Depth<_Tp>::value == m.depth() ) - { - return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0)); - } - CV_Assert(DataType<_Tp>::channels == m.channels() || m.empty()); - m.convertTo(*this, type()); - return *this; -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m) -{ - Mat::operator=(m); - return *this; -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s) -{ - typedef typename DataType<_Tp>::vec_type VT; - Mat::operator=(Scalar((const VT&)s)); - return *this; -} - -template inline -void Mat_<_Tp>::create(int _rows, int _cols) -{ - Mat::create(_rows, _cols, traits::Type<_Tp>::value); -} - -template inline -void Mat_<_Tp>::create(Size _sz) -{ - Mat::create(_sz, traits::Type<_Tp>::value); -} - -template inline -void Mat_<_Tp>::create(int _dims, const int* _sz) -{ - Mat::create(_dims, _sz, traits::Type<_Tp>::value); -} - -template inline -void Mat_<_Tp>::release() -{ - Mat::release(); - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; -} - -template inline -Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const -{ - return Mat_<_Tp>(Mat::cross(m)); -} - -template template inline -Mat_<_Tp>::operator Mat_() const -{ - return Mat_(static_cast(*this)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::row(int y) const -{ - return Mat_(*this, Range(y, y+1), Range::all()); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::col(int x) const -{ - return Mat_(*this, Range::all(), Range(x, x+1)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::diag(int d) const -{ - return Mat_(Mat::diag(d)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::clone() const -{ - return Mat_(Mat::clone()); -} - -template inline -size_t Mat_<_Tp>::elemSize() const -{ - CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) ); - return sizeof(_Tp); -} - -template inline -size_t Mat_<_Tp>::elemSize1() const -{ - CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp) / DataType<_Tp>::channels ); - return sizeof(_Tp) / DataType<_Tp>::channels; -} - -template inline -int Mat_<_Tp>::type() const -{ - CV_DbgAssert( Mat::type() == traits::Type<_Tp>::value ); - return traits::Type<_Tp>::value; -} - -template inline -int Mat_<_Tp>::depth() const -{ - CV_DbgAssert( Mat::depth() == traits::Depth<_Tp>::value ); - return traits::Depth<_Tp>::value; -} - -template inline -int Mat_<_Tp>::channels() const -{ - CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels ); - return DataType<_Tp>::channels; -} - -template inline -size_t Mat_<_Tp>::stepT(int i) const -{ - return step.p[i] / elemSize(); -} - -template inline -size_t Mat_<_Tp>::step1(int i) const -{ - return step.p[i] / elemSize1(); -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) -{ - return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const -{ - return Mat_<_Tp>(*this, _rowRange, _colRange); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const -{ - return Mat_<_Tp>(*this, roi); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const -{ - return Mat_<_Tp>(*this, ranges); -} - -template inline -Mat_<_Tp> Mat_<_Tp>::operator()(const std::vector& ranges) const -{ - return Mat_<_Tp>(*this, ranges); -} - -template inline -_Tp* Mat_<_Tp>::operator [](int y) -{ - CV_DbgAssert( 0 <= y && y < size.p[0] ); - return (_Tp*)(data + y*step.p[0]); -} - -template inline -const _Tp* Mat_<_Tp>::operator [](int y) const -{ - CV_DbgAssert( 0 <= y && y < size.p[0] ); - return (const _Tp*)(data + y*step.p[0]); -} - -template inline -_Tp& Mat_<_Tp>::operator ()(int i0, int i1) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((_Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((const _Tp*)(data + step.p[0] * i0))[i1]; -} - -template inline -_Tp& Mat_<_Tp>::operator ()(Point pt) -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(Point pt) const -{ - CV_DbgAssert(dims <= 2); - CV_DbgAssert(data); - CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); - CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); - CV_DbgAssert(type() == traits::Type<_Tp>::value); - return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; -} - -template inline -_Tp& Mat_<_Tp>::operator ()(const int* idx) -{ - return Mat::at<_Tp>(idx); -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(const int* idx) const -{ - return Mat::at<_Tp>(idx); -} - -template template inline -_Tp& Mat_<_Tp>::operator ()(const Vec& idx) -{ - return Mat::at<_Tp>(idx); -} - -template template inline -const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const -{ - return Mat::at<_Tp>(idx); -} - -template inline -_Tp& Mat_<_Tp>::operator ()(int i0) -{ - return this->at<_Tp>(i0); -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(int i0) const -{ - return this->at<_Tp>(i0); -} - -template inline -_Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) -{ - return this->at<_Tp>(i0, i1, i2); -} - -template inline -const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const -{ - return this->at<_Tp>(i0, i1, i2); -} - -template inline -Mat_<_Tp>::operator std::vector<_Tp>() const -{ - std::vector<_Tp> v; - copyTo(v); - return v; -} - -template template inline -Mat_<_Tp>::operator std::array<_Tp, _Nm>() const -{ - std::array<_Tp, _Nm> a; - copyTo(a); - return a; -} - -template template inline -Mat_<_Tp>::operator Vec::channel_type, n>() const -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - -#if defined _MSC_VER - const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) - return pMat->operator Vec::channel_type, n>(); -#else - return this->Mat::operator Vec::channel_type, n>(); -#endif -} - -template template inline -Mat_<_Tp>::operator Matx::channel_type, m, n>() const -{ - CV_Assert(n % DataType<_Tp>::channels == 0); - -#if defined _MSC_VER - const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) - Matx::channel_type, m, n> res = pMat->operator Matx::channel_type, m, n>(); - return res; -#else - Matx::channel_type, m, n> res = this->Mat::operator Matx::channel_type, m, n>(); - return res; -#endif -} - -template inline -MatConstIterator_<_Tp> Mat_<_Tp>::begin() const -{ - return Mat::begin<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rbegin() const -{ - return Mat::rbegin<_Tp>(); -} - -template inline -MatConstIterator_<_Tp> Mat_<_Tp>::end() const -{ - return Mat::end<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rend() const -{ - return Mat::rend<_Tp>(); -} - -template inline -MatIterator_<_Tp> Mat_<_Tp>::begin() -{ - return Mat::begin<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rbegin() -{ - return Mat::rbegin<_Tp>(); -} - -template inline -MatIterator_<_Tp> Mat_<_Tp>::end() -{ - return Mat::end<_Tp>(); -} - -template inline -std::reverse_iterator> Mat_<_Tp>::rend() -{ - return Mat::rend<_Tp>(); -} - -template template inline -void Mat_<_Tp>::forEach(const Functor& operation) { - Mat::forEach<_Tp, Functor>(operation); -} - -template template inline -void Mat_<_Tp>::forEach(const Functor& operation) const { - Mat::forEach<_Tp, Functor>(operation); -} - -template inline -Mat_<_Tp>::Mat_(Mat_&& m) - : Mat(std::move(m)) -{ -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (Mat_&& m) -{ - Mat::operator = (std::move(m)); - return *this; -} - -template inline -Mat_<_Tp>::Mat_(Mat&& m) - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; - *this = std::move(m); -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (Mat&& m) -{ - if (m.empty()) - { - release(); - return *this; - } - if( traits::Type<_Tp>::value == m.type() ) - { - Mat::operator = ((Mat&&)m); - return *this; - } - if( traits::Depth<_Tp>::value == m.depth() ) - { - Mat::operator = ((Mat&&)m.reshape(DataType<_Tp>::channels, m.dims, 0)); - return *this; - } - CV_DbgAssert(DataType<_Tp>::channels == m.channels()); - m.convertTo(*this, type()); - return *this; -} - -template inline -Mat_<_Tp>::Mat_(MatExpr&& e) - : Mat() -{ - flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; - *this = Mat(e); -} - - -///////////////////////////// SparseMat ///////////////////////////// - -inline -SparseMat SparseMat::clone() const -{ - SparseMat temp; - this->copyTo(temp); - return temp; -} - -inline -size_t SparseMat::elemSize() const -{ - return CV_ELEM_SIZE(flags); -} - -inline -size_t SparseMat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int SparseMat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int SparseMat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int SparseMat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -const int* SparseMat::size() const -{ - return hdr ? hdr->size : 0; -} - -inline -int SparseMat::size(int i) const -{ - if( hdr ) - { - CV_DbgAssert((unsigned)i < (unsigned)hdr->dims); - return hdr->size[i]; - } - return 0; -} - -inline -int SparseMat::dims() const -{ - return hdr ? hdr->dims : 0; -} - -inline -size_t SparseMat::nzcount() const -{ - return hdr ? hdr->nodeCount : 0; -} - -template inline -_Tp& SparseMat::ref(int i0, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); -} - -template inline -_Tp& SparseMat::ref(int i0, int i1, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); -} - -template inline -_Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval); -} - -template inline -_Tp& SparseMat::ref(const int* idx, size_t* hashval) -{ - return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval); -} - -template inline -_Tp SparseMat::value(int i0, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); - return p ? *p : _Tp(); -} - -template inline -_Tp SparseMat::value(int i0, int i1, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); - return p ? *p : _Tp(); -} - -template inline -_Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); - return p ? *p : _Tp(); -} - -template inline -_Tp SparseMat::value(const int* idx, size_t* hashval) const -{ - const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); - return p ? *p : _Tp(); -} - -template inline -const _Tp* SparseMat::find(int i0, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); -} - -template inline -const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); -} - -template inline -const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); -} - -template inline -const _Tp* SparseMat::find(const int* idx, size_t* hashval) const -{ - return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); -} - -template inline -_Tp& SparseMat::value(Node* n) -{ - return *(_Tp*)((uchar*)n + hdr->valueOffset); -} - -template inline -const _Tp& SparseMat::value(const Node* n) const -{ - return *(const _Tp*)((const uchar*)n + hdr->valueOffset); -} - -inline -SparseMat::Node* SparseMat::node(size_t nidx) -{ - return (Node*)(void*)&hdr->pool[nidx]; -} - -inline -const SparseMat::Node* SparseMat::node(size_t nidx) const -{ - return (const Node*)(const void*)&hdr->pool[nidx]; -} - -inline -SparseMatIterator SparseMat::begin() -{ - return SparseMatIterator(this); -} - -inline -SparseMatConstIterator SparseMat::begin() const -{ - return SparseMatConstIterator(this); -} - -inline -SparseMatIterator SparseMat::end() -{ - SparseMatIterator it(this); - it.seekEnd(); - return it; -} - -inline -SparseMatConstIterator SparseMat::end() const -{ - SparseMatConstIterator it(this); - it.seekEnd(); - return it; -} - -template inline -SparseMatIterator_<_Tp> SparseMat::begin() -{ - return SparseMatIterator_<_Tp>(this); -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat::begin() const -{ - return SparseMatConstIterator_<_Tp>(this); -} - -template inline -SparseMatIterator_<_Tp> SparseMat::end() -{ - SparseMatIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat::end() const -{ - SparseMatConstIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - - - -///////////////////////////// SparseMat_ //////////////////////////// - -template inline -SparseMat_<_Tp>::SparseMat_() -{ - flags = +MAGIC_VAL + traits::Type<_Tp>::value; -} - -template inline -SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes) - : SparseMat(_dims, _sizes, traits::Type<_Tp>::value) -{} - -template inline -SparseMat_<_Tp>::SparseMat_(const SparseMat& m) -{ - if( m.type() == traits::Type<_Tp>::value ) - *this = (const SparseMat_<_Tp>&)m; - else - m.convertTo(*this, traits::Type<_Tp>::value); -} - -template inline -SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m) -{ - this->flags = m.flags; - this->hdr = m.hdr; - if( this->hdr ) - CV_XADD(&this->hdr->refcount, 1); -} - -template inline -SparseMat_<_Tp>::SparseMat_(const Mat& m) -{ - SparseMat sm(m); - *this = sm; -} - -template inline -SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m) -{ - if( this != &m ) - { - if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); - release(); - flags = m.flags; - hdr = m.hdr; - } - return *this; -} - -template inline -SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat& m) -{ - if( m.type() == traits::Type<_Tp>::value ) - return (*this = (const SparseMat_<_Tp>&)m); - m.convertTo(*this, traits::Type<_Tp>::value); - return *this; -} - -template inline -SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const Mat& m) -{ - return (*this = SparseMat(m)); -} - -template inline -SparseMat_<_Tp> SparseMat_<_Tp>::clone() const -{ - SparseMat_<_Tp> m; - this->copyTo(m); - return m; -} - -template inline -void SparseMat_<_Tp>::create(int _dims, const int* _sizes) -{ - SparseMat::create(_dims, _sizes, traits::Type<_Tp>::value); -} - -template inline -int SparseMat_<_Tp>::type() const -{ - return traits::Type<_Tp>::value; -} - -template inline -int SparseMat_<_Tp>::depth() const -{ - return traits::Depth<_Tp>::value; -} - -template inline -int SparseMat_<_Tp>::channels() const -{ - return DataType<_Tp>::channels; -} - -template inline -_Tp& SparseMat_<_Tp>::ref(int i0, size_t* hashval) -{ - return SparseMat::ref<_Tp>(i0, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const -{ - return SparseMat::value<_Tp>(i0, hashval); -} - -template inline -_Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) -{ - return SparseMat::ref<_Tp>(i0, i1, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const -{ - return SparseMat::value<_Tp>(i0, i1, hashval); -} - -template inline -_Tp& SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval) -{ - return SparseMat::ref<_Tp>(i0, i1, i2, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const -{ - return SparseMat::value<_Tp>(i0, i1, i2, hashval); -} - -template inline -_Tp& SparseMat_<_Tp>::ref(const int* idx, size_t* hashval) -{ - return SparseMat::ref<_Tp>(idx, hashval); -} - -template inline -_Tp SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const -{ - return SparseMat::value<_Tp>(idx, hashval); -} - -template inline -SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin() -{ - return SparseMatIterator_<_Tp>(this); -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const -{ - return SparseMatConstIterator_<_Tp>(this); -} - -template inline -SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() -{ - SparseMatIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - -template inline -SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const -{ - SparseMatConstIterator_<_Tp> it(this); - it.seekEnd(); - return it; -} - - - -////////////////////////// MatConstIterator ///////////////////////// - -inline -MatConstIterator::MatConstIterator() - : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0) -{} - -inline -MatConstIterator::MatConstIterator(const Mat* _m) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - if( m && m->isContinuous() ) - { - CV_Assert(!m->empty()); - sliceStart = m->ptr(); - sliceEnd = sliceStart + m->total()*elemSize; - } - seek((const int*)0); -} - -inline -MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - CV_Assert(m && m->dims <= 2); - if( m->isContinuous() ) - { - CV_Assert(!m->empty()); - sliceStart = m->ptr(); - sliceEnd = sliceStart + m->total()*elemSize; - } - int idx[] = {_row, _col}; - seek(idx); -} - -inline -MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) - : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) -{ - CV_Assert(m && m->dims <= 2); - if( m->isContinuous() ) - { - CV_Assert(!m->empty()); - sliceStart = m->ptr(); - sliceEnd = sliceStart + m->total()*elemSize; - } - int idx[] = {_pt.y, _pt.x}; - seek(idx); -} - -inline -MatConstIterator::MatConstIterator(const MatConstIterator& it) - : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) -{} - -inline -MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it ) -{ - m = it.m; elemSize = it.elemSize; ptr = it.ptr; - sliceStart = it.sliceStart; sliceEnd = it.sliceEnd; - return *this; -} - -inline -const uchar* MatConstIterator::operator *() const -{ - return ptr; -} - -inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) -{ - if( !m || ofs == 0 ) - return *this; - ptrdiff_t ofsb = ofs*elemSize; - ptr += ofsb; - if( ptr < sliceStart || sliceEnd <= ptr ) - { - ptr -= ofsb; - seek(ofs, true); - } - return *this; -} - -inline -MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs) -{ - return (*this += -ofs); -} - -inline -MatConstIterator& MatConstIterator::operator --() -{ - if( m && (ptr -= elemSize) < sliceStart ) - { - ptr += elemSize; - seek(-1, true); - } - return *this; -} - -inline -MatConstIterator MatConstIterator::operator --(int) -{ - MatConstIterator b = *this; - *this += -1; - return b; -} - -inline -MatConstIterator& MatConstIterator::operator ++() -{ - if( m && (ptr += elemSize) >= sliceEnd ) - { - ptr -= elemSize; - seek(1, true); - } - return *this; -} - -inline MatConstIterator MatConstIterator::operator ++(int) -{ - MatConstIterator b = *this; - *this += 1; - return b; -} - - -static inline -bool operator == (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.m == b.m && a.ptr == b.ptr; -} - -static inline -bool operator != (const MatConstIterator& a, const MatConstIterator& b) -{ - return !(a == b); -} - -static inline -bool operator < (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr < b.ptr; -} - -static inline -bool operator > (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr > b.ptr; -} - -static inline -bool operator <= (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr <= b.ptr; -} - -static inline -bool operator >= (const MatConstIterator& a, const MatConstIterator& b) -{ - return a.ptr >= b.ptr; -} - -static inline -ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a) -{ - if( a.m != b.m ) - return ((size_t)(-1) >> 1); - if( a.sliceEnd == b.sliceEnd ) - return (b.ptr - a.ptr)/static_cast(b.elemSize); - - return b.lpos() - a.lpos(); -} - -static inline -MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs) -{ - MatConstIterator b = a; - return b += ofs; -} - -static inline -MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a) -{ - MatConstIterator b = a; - return b += ofs; -} - -static inline -MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) -{ - MatConstIterator b = a; - return b += -ofs; -} - - -inline -const uchar* MatConstIterator::operator [](ptrdiff_t i) const -{ - return *(*this + i); -} - - - -///////////////////////// MatConstIterator_ ///////////////////////// - -template inline -MatConstIterator_<_Tp>::MatConstIterator_() -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m) - : MatConstIterator(_m) -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col) - : MatConstIterator(_m, _row, _col) -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, Point _pt) - : MatConstIterator(_m, _pt) -{} - -template inline -MatConstIterator_<_Tp>::MatConstIterator_(const MatConstIterator_& it) - : MatConstIterator(it) -{} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it ) -{ - MatConstIterator::operator = (it); - return *this; -} - -template inline -const _Tp& MatConstIterator_<_Tp>::operator *() const -{ - return *(_Tp*)(this->ptr); -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs) -{ - MatConstIterator::operator += (ofs); - return *this; -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs) -{ - return (*this += -ofs); -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --() -{ - MatConstIterator::operator --(); - return *this; -} - -template inline -MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int) -{ - MatConstIterator_ b = *this; - MatConstIterator::operator --(); - return b; -} - -template inline -MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++() -{ - MatConstIterator::operator ++(); - return *this; -} - -template inline -MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int) -{ - MatConstIterator_ b = *this; - MatConstIterator::operator ++(); - return b; -} - - -template inline -Point MatConstIterator_<_Tp>::pos() const -{ - if( !m ) - return Point(); - CV_DbgAssert( m->dims <= 2 ); - if( m->isContinuous() ) - { - ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data; - int y = (int)(ofs / m->cols); - int x = (int)(ofs - (ptrdiff_t)y * m->cols); - return Point(x, y); - } - else - { - ptrdiff_t ofs = (uchar*)ptr - m->data; - int y = (int)(ofs / m->step); - int x = (int)((ofs - y * m->step)/sizeof(_Tp)); - return Point(x, y); - } -} - - -template static inline -bool operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) -{ - return a.m == b.m && a.ptr == b.ptr; -} - -template static inline -bool operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) -{ - return a.m != b.m || a.ptr != b.ptr; -} - -template static inline -MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatConstIterator_<_Tp>&)t; -} - -template static inline -MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatConstIterator_<_Tp>&)t; -} - -template static inline -MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a - ofs; - return (MatConstIterator_<_Tp>&)t; -} - -template inline -const _Tp& MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const -{ - return *(_Tp*)MatConstIterator::operator [](i); -} - - - -//////////////////////////// MatIterator_ /////////////////////////// - -template inline -MatIterator_<_Tp>::MatIterator_() - : MatConstIterator_<_Tp>() -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m) - : MatConstIterator_<_Tp>(_m) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col) - : MatConstIterator_<_Tp>(_m, _row, _col) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, Point _pt) - : MatConstIterator_<_Tp>(_m, _pt) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, const int* _idx) - : MatConstIterator_<_Tp>(_m, _idx) -{} - -template inline -MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) - : MatConstIterator_<_Tp>(it) -{} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it ) -{ - MatConstIterator::operator = (it); - return *this; -} - -template inline -_Tp& MatIterator_<_Tp>::operator *() const -{ - return *(_Tp*)(this->ptr); -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs) -{ - MatConstIterator::operator += (ofs); - return *this; -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs) -{ - MatConstIterator::operator += (-ofs); - return *this; -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator --() -{ - MatConstIterator::operator --(); - return *this; -} - -template inline -MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int) -{ - MatIterator_ b = *this; - MatConstIterator::operator --(); - return b; -} - -template inline -MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++() -{ - MatConstIterator::operator ++(); - return *this; -} - -template inline -MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int) -{ - MatIterator_ b = *this; - MatConstIterator::operator ++(); - return b; -} - -template inline -_Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const -{ - return *(*this + i); -} - - -template static inline -bool operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ - return a.m == b.m && a.ptr == b.ptr; -} - -template static inline -bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) -{ - return a.m != b.m || a.ptr != b.ptr; -} - -template static inline -MatIterator_<_Tp> operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatIterator_<_Tp>&)t; -} - -template static inline -MatIterator_<_Tp> operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) -{ - MatConstIterator t = (const MatConstIterator&)a + ofs; - return (MatIterator_<_Tp>&)t; -} - -template static inline -MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) -{ - MatConstIterator t = (const MatConstIterator&)a - ofs; - return (MatIterator_<_Tp>&)t; -} - - - -/////////////////////// SparseMatConstIterator ////////////////////// - -inline -SparseMatConstIterator::SparseMatConstIterator() - : m(0), hashidx(0), ptr(0) -{} - -inline -SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it) - : m(it.m), hashidx(it.hashidx), ptr(it.ptr) -{} - -inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it) -{ - if( this != &it ) - { - m = it.m; - hashidx = it.hashidx; - ptr = it.ptr; - } - return *this; -} - -template inline -const _Tp& SparseMatConstIterator::value() const -{ - return *(const _Tp*)ptr; -} - -inline -const SparseMat::Node* SparseMatConstIterator::node() const -{ - return (ptr && m && m->hdr) ? (const SparseMat::Node*)(const void*)(ptr - m->hdr->valueOffset) : 0; -} - -inline -SparseMatConstIterator SparseMatConstIterator::operator ++(int) -{ - SparseMatConstIterator it = *this; - ++*this; - return it; -} - -inline -void SparseMatConstIterator::seekEnd() -{ - if( m && m->hdr ) - { - hashidx = m->hdr->hashtab.size(); - ptr = 0; - } -} - - -static inline -bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ - return it1.m == it2.m && it1.ptr == it2.ptr; -} - -static inline -bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) -{ - return !(it1 == it2); -} - - - -///////////////////////// SparseMatIterator ///////////////////////// - -inline -SparseMatIterator::SparseMatIterator() -{} - -inline -SparseMatIterator::SparseMatIterator(SparseMat* _m) - : SparseMatConstIterator(_m) -{} - -inline -SparseMatIterator::SparseMatIterator(const SparseMatIterator& it) - : SparseMatConstIterator(it) -{} - -inline -SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it) -{ - (SparseMatConstIterator&)*this = it; - return *this; -} - -template inline -_Tp& SparseMatIterator::value() const -{ - return *(_Tp*)ptr; -} - -inline -SparseMat::Node* SparseMatIterator::node() const -{ - return (SparseMat::Node*)SparseMatConstIterator::node(); -} - -inline -SparseMatIterator& SparseMatIterator::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -inline -SparseMatIterator SparseMatIterator::operator ++(int) -{ - SparseMatIterator it = *this; - ++*this; - return it; -} - - - -////////////////////// SparseMatConstIterator_ ////////////////////// - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_() -{} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m) - : SparseMatConstIterator(_m) -{} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m) - : SparseMatConstIterator(_m) -{ - CV_Assert( _m->type() == traits::Type<_Tp>::value ); -} - -template inline -SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it) - : SparseMatConstIterator(it) -{} - -template inline -SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) -{ - return reinterpret_cast&> - (*reinterpret_cast(this) = - reinterpret_cast(it)); -} - -template inline -const _Tp& SparseMatConstIterator_<_Tp>::operator *() const -{ - return *(const _Tp*)this->ptr; -} - -template inline -SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -template inline -SparseMatConstIterator_<_Tp> SparseMatConstIterator_<_Tp>::operator ++(int) -{ - SparseMatConstIterator_<_Tp> it = *this; - SparseMatConstIterator::operator ++(); - return it; -} - - - -///////////////////////// SparseMatIterator_ //////////////////////// - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_() -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m) - : SparseMatConstIterator_<_Tp>(_m) -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m) - : SparseMatConstIterator_<_Tp>(_m) -{} - -template inline -SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) - : SparseMatConstIterator_<_Tp>(it) -{} - -template inline -SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) -{ - return reinterpret_cast&> - (*reinterpret_cast(this) = - reinterpret_cast(it)); -} - -template inline -_Tp& SparseMatIterator_<_Tp>::operator *() const -{ - return *(_Tp*)this->ptr; -} - -template inline -SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator ++() -{ - SparseMatConstIterator::operator ++(); - return *this; -} - -template inline -SparseMatIterator_<_Tp> SparseMatIterator_<_Tp>::operator ++(int) -{ - SparseMatIterator_<_Tp> it = *this; - SparseMatConstIterator::operator ++(); - return it; -} - - - -//////////////////////// MatCommaInitializer_ /////////////////////// - -template inline -MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m) - : it(_m) -{} - -template template inline -MatCommaInitializer_<_Tp>& MatCommaInitializer_<_Tp>::operator , (T2 v) -{ - CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() ); - *this->it = _Tp(v); - ++this->it; - return *this; -} - -template inline -MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const -{ - CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); - return Mat_<_Tp>(*this->it.m); -} - - -template static inline -MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val) -{ - MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m); - return (commaInitializer, val); -} - - - -///////////////////////// Matrix Expressions //////////////////////// - -inline -Mat& Mat::operator = (const MatExpr& e) -{ - e.op->assign(e, *this); - return *this; -} - -template inline -Mat_<_Tp>::Mat_(const MatExpr& e) -{ - e.op->assign(e, *this, traits::Type<_Tp>::value); -} - -template inline -Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e) -{ - e.op->assign(e, *this, traits::Type<_Tp>::value); - return *this; -} - -template inline -MatExpr Mat_<_Tp>::zeros(int rows, int cols) -{ - return Mat::zeros(rows, cols, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::zeros(Size sz) -{ - return Mat::zeros(sz, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::ones(int rows, int cols) -{ - return Mat::ones(rows, cols, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::ones(Size sz) -{ - return Mat::ones(sz, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::eye(int rows, int cols) -{ - return Mat::eye(rows, cols, traits::Type<_Tp>::value); -} - -template inline -MatExpr Mat_<_Tp>::eye(Size sz) -{ - return Mat::eye(sz, traits::Type<_Tp>::value); -} - -inline -MatExpr::MatExpr() - : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s() -{} - -inline -MatExpr::MatExpr(const MatOp* _op, int _flags, const Mat& _a, const Mat& _b, - const Mat& _c, double _alpha, double _beta, const Scalar& _s) - : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s) -{} - -inline -MatExpr::operator Mat() const -{ - Mat m; - op->assign(*this, m); - return m; -} - -template inline -MatExpr::operator Mat_<_Tp>() const -{ - Mat_<_Tp> m; - op->assign(*this, m, traits::Type<_Tp>::value); - return m; -} - - -template static inline -MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - return cv::min((const Mat&)a, (const Mat&)b); -} - -template static inline -MatExpr min(const Mat_<_Tp>& a, double s) -{ - return cv::min((const Mat&)a, s); -} - -template static inline -MatExpr min(double s, const Mat_<_Tp>& a) -{ - return cv::min((const Mat&)a, s); -} - -template static inline -MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) -{ - return cv::max((const Mat&)a, (const Mat&)b); -} - -template static inline -MatExpr max(const Mat_<_Tp>& a, double s) -{ - return cv::max((const Mat&)a, s); -} - -template static inline -MatExpr max(double s, const Mat_<_Tp>& a) -{ - return cv::max((const Mat&)a, s); -} - -template static inline -MatExpr abs(const Mat_<_Tp>& m) -{ - return cv::abs((const Mat&)m); -} - - -static inline -Mat& operator += (Mat& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, a); - return a; -} - -static inline -const Mat& operator += (const Mat& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator += (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignAdd(b, (Mat&)a); - return a; -} - -static inline -Mat& operator -= (Mat& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, a); - return a; -} - -static inline -const Mat& operator -= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator -= (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignSubtract(b, (Mat&)a); - return a; -} - -static inline -Mat& operator *= (Mat& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, a); - return a; -} - -static inline -const Mat& operator *= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator *= (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignMultiply(b, (Mat&)a); - return a; -} - -static inline -Mat& operator /= (Mat& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, a); - return a; -} - -static inline -const Mat& operator /= (const Mat& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, (Mat&)a); - return a; -} - -template static inline -Mat_<_Tp>& operator /= (Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, a); - return a; -} - -template static inline -const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b) -{ - b.op->augAssignDivide(b, (Mat&)a); - return a; -} - - -//////////////////////////////// UMat //////////////////////////////// - -template inline -UMat::UMat(const std::vector<_Tp>& vec, bool copyData) -: flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), -cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows) -{ - if(vec.empty()) - return; - if( !copyData ) - { - // !!!TODO!!! - CV_Error(Error::StsNotImplemented, ""); - } - else - Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); -} - -inline -UMat UMat::row(int y) const -{ - return UMat(*this, Range(y, y + 1), Range::all()); -} - -inline -UMat UMat::col(int x) const -{ - return UMat(*this, Range::all(), Range(x, x + 1)); -} - -inline -UMat UMat::rowRange(int startrow, int endrow) const -{ - return UMat(*this, Range(startrow, endrow), Range::all()); -} - -inline -UMat UMat::rowRange(const Range& r) const -{ - return UMat(*this, r, Range::all()); -} - -inline -UMat UMat::colRange(int startcol, int endcol) const -{ - return UMat(*this, Range::all(), Range(startcol, endcol)); -} - -inline -UMat UMat::colRange(const Range& r) const -{ - return UMat(*this, Range::all(), r); -} - -inline -UMat UMat::operator()( Range _rowRange, Range _colRange ) const -{ - return UMat(*this, _rowRange, _colRange); -} - -inline -UMat UMat::operator()( const Rect& roi ) const -{ - return UMat(*this, roi); -} - -inline -UMat UMat::operator()(const Range* ranges) const -{ - return UMat(*this, ranges); -} - -inline -UMat UMat::operator()(const std::vector& ranges) const -{ - return UMat(*this, ranges); -} - -inline -bool UMat::isContinuous() const -{ - return (flags & CONTINUOUS_FLAG) != 0; -} - -inline -bool UMat::isSubmatrix() const -{ - return (flags & SUBMATRIX_FLAG) != 0; -} - -inline -size_t UMat::elemSize() const -{ - size_t res = dims > 0 ? step.p[dims - 1] : 0; - CV_DbgAssert(res != 0); - return res; -} - -inline -size_t UMat::elemSize1() const -{ - return CV_ELEM_SIZE1(flags); -} - -inline -int UMat::type() const -{ - return CV_MAT_TYPE(flags); -} - -inline -int UMat::depth() const -{ - return CV_MAT_DEPTH(flags); -} - -inline -int UMat::channels() const -{ - return CV_MAT_CN(flags); -} - -inline -size_t UMat::step1(int i) const -{ - return step.p[i] / elemSize1(); -} - - -inline bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; } -inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; } -inline bool UMatData::deviceMemMapped() const { return (flags & DEVICE_MEM_MAPPED) != 0; } -inline bool UMatData::copyOnMap() const { return (flags & COPY_ON_MAP) != 0; } -inline bool UMatData::tempUMat() const { return (flags & TEMP_UMAT) != 0; } -inline bool UMatData::tempCopiedUMat() const { return (flags & TEMP_COPIED_UMAT) == TEMP_COPIED_UMAT; } - -inline void UMatData::markDeviceMemMapped(bool flag) -{ - if(flag) - flags |= DEVICE_MEM_MAPPED; - else - flags &= ~DEVICE_MEM_MAPPED; -} - -inline void UMatData::markHostCopyObsolete(bool flag) -{ - if(flag) - flags |= HOST_COPY_OBSOLETE; - else - flags &= ~HOST_COPY_OBSOLETE; -} -inline void UMatData::markDeviceCopyObsolete(bool flag) -{ - if(flag) - flags |= DEVICE_COPY_OBSOLETE; - else - flags &= ~DEVICE_COPY_OBSOLETE; -} - -//! @endcond - -static inline -void swap(MatExpr& a, MatExpr& b) { a.swap(b); } - -} //cv - -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS -#undef CV_DISABLE_CLANG_ENUM_WARNINGS -#pragma clang diagnostic pop -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_MATRIX_OPERATIONS_HPP +#define OPENCV_CORE_MATRIX_OPERATIONS_HPP + +#ifndef __cplusplus +# error mat.inl.hpp header must be compiled as C++ +#endif + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable: 4127 5054 ) +#endif + +#if defined(CV_SKIP_DISABLE_CLANG_ENUM_WARNINGS) + // nothing +#elif defined(CV_FORCE_DISABLE_CLANG_ENUM_WARNINGS) + #define CV_DISABLE_CLANG_ENUM_WARNINGS +#elif defined(__clang__) && defined(__has_warning) + #if __has_warning("-Wdeprecated-enum-enum-conversion") && __has_warning("-Wdeprecated-anon-enum-enum-conversion") + #define CV_DISABLE_CLANG_ENUM_WARNINGS + #endif +#endif +#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion" +#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion" +#endif + +namespace cv +{ +CV__DEBUG_NS_BEGIN + + +//! @cond IGNORED + +////////////////////////// Custom (raw) type wrapper ////////////////////////// + +template static inline +int rawType() +{ + CV_StaticAssert(sizeof(_Tp) <= CV_CN_MAX, "sizeof(_Tp) is too large"); + const int elemSize = sizeof(_Tp); + return (int)CV_MAKETYPE(CV_8U, elemSize); +} + +//////////////////////// Input/Output Arrays //////////////////////// + +inline void _InputArray::init(int _flags, const void* _obj) +{ flags = _flags; obj = (void*)_obj; } + +inline void _InputArray::init(int _flags, const void* _obj, Size _sz) +{ flags = _flags; obj = (void*)_obj; sz = _sz; } + +inline void* _InputArray::getObj() const { return obj; } +inline int _InputArray::getFlags() const { return flags; } +inline Size _InputArray::getSz() const { return sz; } + +inline _InputArray::_InputArray() { init(0 + NONE, 0); } +inline _InputArray::_InputArray(int _flags, void* _obj) { init(_flags, _obj); } +inline _InputArray::_InputArray(const Mat& m) { init(+MAT+ACCESS_READ, &m); } +inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_READ, &vec); } +inline _InputArray::_InputArray(const UMat& m) { init(+UMAT+ACCESS_READ, &m); } +inline _InputArray::_InputArray(const std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::vector<_Tp>& vec) +{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, arr.data(), Size(1, _Nm)); } + +template inline +_InputArray::_InputArray(const std::array& arr) +{ init(+STD_ARRAY_MAT + ACCESS_READ, arr.data(), Size(1, _Nm)); } + +inline +_InputArray::_InputArray(const std::vector& vec) +{ init(FIXED_TYPE + STD_BOOL_VECTOR + traits::Type::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_READ, &vec); } + +template inline +_InputArray::_InputArray(const Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, &mtx, Size(n, m)); } + +template inline +_InputArray::_InputArray(const _Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ, vec, Size(n, 1)); } + +template inline +_InputArray::_InputArray(const Mat_<_Tp>& m) +{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_READ, &m); } + +inline _InputArray::_InputArray(const double& val) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + CV_64F + ACCESS_READ, &val, Size(1,1)); } + +inline _InputArray::_InputArray(const cuda::GpuMat& d_mat) +{ init(+CUDA_GPU_MAT + ACCESS_READ, &d_mat); } + +inline _InputArray::_InputArray(const std::vector& d_mat) +{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_READ, &d_mat);} + +inline _InputArray::_InputArray(const ogl::Buffer& buf) +{ init(+OPENGL_BUFFER + ACCESS_READ, &buf); } + +inline _InputArray::_InputArray(const cuda::HostMem& cuda_mem) +{ init(+CUDA_HOST_MEM + ACCESS_READ, &cuda_mem); } + +template inline +_InputArray _InputArray::rawIn(const std::vector<_Tp>& vec) +{ + _InputArray v; + v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_READ; + v.obj = (void*)&vec; + return v; +} + +template inline +_InputArray _InputArray::rawIn(const std::array<_Tp, _Nm>& arr) +{ + _InputArray v; + v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_READ; + v.obj = (void*)arr.data(); + v.sz = Size(1, _Nm); + return v; +} + +inline _InputArray::~_InputArray() {} + +inline Mat _InputArray::getMat(int i) const +{ + if( kind() == MAT && i < 0 ) + return *(const Mat*)obj; + return getMat_(i); +} + +inline bool _InputArray::isMat() const { return kind() == _InputArray::MAT; } +inline bool _InputArray::isUMat() const { return kind() == _InputArray::UMAT; } +inline bool _InputArray::isMatVector() const { return kind() == _InputArray::STD_VECTOR_MAT; } +inline bool _InputArray::isUMatVector() const { return kind() == _InputArray::STD_VECTOR_UMAT; } +inline bool _InputArray::isMatx() const { return kind() == _InputArray::MATX; } +inline bool _InputArray::isVector() const { return kind() == _InputArray::STD_VECTOR || + kind() == _InputArray::STD_BOOL_VECTOR || + (kind() == _InputArray::MATX && (sz.width <= 1 || sz.height <= 1)); } +inline bool _InputArray::isGpuMat() const { return kind() == _InputArray::CUDA_GPU_MAT; } +inline bool _InputArray::isGpuMatVector() const { return kind() == _InputArray::STD_VECTOR_CUDA_GPU_MAT; } + +//////////////////////////////////////////////////////////////////////////////////////// + +inline _OutputArray::_OutputArray() { init(+NONE + ACCESS_WRITE, 0); } +inline _OutputArray::_OutputArray(int _flags, void* _obj) { init(_flags + ACCESS_WRITE, _obj); } +inline _OutputArray::_OutputArray(Mat& m) { init(+MAT+ACCESS_WRITE, &m); } +inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_MAT + ACCESS_WRITE, &vec); } +inline _OutputArray::_OutputArray(UMat& m) { init(+UMAT + ACCESS_WRITE, &m); } +inline _OutputArray::_OutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(std::vector<_Tp>& vec) +{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(std::array& arr) +{ init(+STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(Mat_<_Tp>& m) +{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } + +template inline +_OutputArray::_OutputArray(Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } + +template inline +_OutputArray::_OutputArray(_Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } + +template inline +_OutputArray::_OutputArray(const std::vector<_Tp>& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(const std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(const std::array& arr) +{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_WRITE, arr.data(), Size(1, _Nm)); } + +template inline +_OutputArray::_OutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &vec); } + +template inline +_OutputArray::_OutputArray(const Mat_<_Tp>& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_WRITE, &m); } + +template inline +_OutputArray::_OutputArray(const Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, &mtx, Size(n, m)); } + +template inline +_OutputArray::_OutputArray(const _Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE, vec, Size(n, 1)); } + +inline _OutputArray::_OutputArray(cuda::GpuMat& d_mat) +{ init(+CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } + +inline _OutputArray::_OutputArray(std::vector& d_mat) +{ init(+STD_VECTOR_CUDA_GPU_MAT + ACCESS_WRITE, &d_mat);} + +inline _OutputArray::_OutputArray(ogl::Buffer& buf) +{ init(+OPENGL_BUFFER + ACCESS_WRITE, &buf); } + +inline _OutputArray::_OutputArray(cuda::HostMem& cuda_mem) +{ init(+CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } + +inline _OutputArray::_OutputArray(const Mat& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_WRITE, &m); } + +inline _OutputArray::_OutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_WRITE, &vec); } + +inline _OutputArray::_OutputArray(const UMat& m) +{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_WRITE, &m); } + +inline _OutputArray::_OutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_WRITE, &vec); } + +inline _OutputArray::_OutputArray(const cuda::GpuMat& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_WRITE, &d_mat); } + + +inline _OutputArray::_OutputArray(const ogl::Buffer& buf) +{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_WRITE, &buf); } + +inline _OutputArray::_OutputArray(const cuda::HostMem& cuda_mem) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_WRITE, &cuda_mem); } + +template inline +_OutputArray _OutputArray::rawOut(std::vector<_Tp>& vec) +{ + _OutputArray v; + v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_WRITE; + v.obj = (void*)&vec; + return v; +} + +template inline +_OutputArray _OutputArray::rawOut(std::array<_Tp, _Nm>& arr) +{ + _OutputArray v; + v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_WRITE; + v.obj = (void*)arr.data(); + v.sz = Size(1, _Nm); + return v; +} + +/////////////////////////////////////////////////////////////////////////////////////////// + +inline _InputOutputArray::_InputOutputArray() { init(0+ACCESS_RW, 0); } +inline _InputOutputArray::_InputOutputArray(int _flags, void* _obj) { init(_flags+ACCESS_RW, _obj); } +inline _InputOutputArray::_InputOutputArray(Mat& m) { init(+MAT+ACCESS_RW, &m); } +inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_MAT+ACCESS_RW, &vec); } +inline _InputOutputArray::_InputOutputArray(UMat& m) { init(+UMAT+ACCESS_RW, &m); } +inline _InputOutputArray::_InputOutputArray(std::vector& vec) { init(+STD_VECTOR_UMAT+ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(std::vector<_Tp>& vec) +{ init(FIXED_TYPE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(std::array& arr) +{ init(+STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(std::vector >& vec) +{ init(FIXED_TYPE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(Mat_<_Tp>& m) +{ init(FIXED_TYPE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } + +template inline +_InputOutputArray::_InputOutputArray(Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } + +template inline +_InputOutputArray::_InputOutputArray(_Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } + +template inline +_InputOutputArray::_InputOutputArray(const std::vector<_Tp>& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(const std::array<_Tp, _Nm>& arr) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(const std::array& arr) +{ init(FIXED_SIZE + STD_ARRAY_MAT + ACCESS_RW, arr.data(), Size(1, _Nm)); } + +template inline +_InputOutputArray::_InputOutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_VECTOR + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(const std::vector >& vec) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_MAT + traits::Type<_Tp>::value + ACCESS_RW, &vec); } + +template inline +_InputOutputArray::_InputOutputArray(const Mat_<_Tp>& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + traits::Type<_Tp>::value + ACCESS_RW, &m); } + +template inline +_InputOutputArray::_InputOutputArray(const Matx<_Tp, m, n>& mtx) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, &mtx, Size(n, m)); } + +template inline +_InputOutputArray::_InputOutputArray(const _Tp* vec, int n) +{ init(FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW, vec, Size(n, 1)); } + +inline _InputOutputArray::_InputOutputArray(cuda::GpuMat& d_mat) +{ init(+CUDA_GPU_MAT + ACCESS_RW, &d_mat); } + +inline _InputOutputArray::_InputOutputArray(ogl::Buffer& buf) +{ init(+OPENGL_BUFFER + ACCESS_RW, &buf); } + +inline _InputOutputArray::_InputOutputArray(cuda::HostMem& cuda_mem) +{ init(+CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } + +inline _InputOutputArray::_InputOutputArray(const Mat& m) +{ init(FIXED_TYPE + FIXED_SIZE + MAT + ACCESS_RW, &m); } + +inline _InputOutputArray::_InputOutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_MAT + ACCESS_RW, &vec); } + +inline _InputOutputArray::_InputOutputArray(const UMat& m) +{ init(FIXED_TYPE + FIXED_SIZE + UMAT + ACCESS_RW, &m); } + +inline _InputOutputArray::_InputOutputArray(const std::vector& vec) +{ init(FIXED_SIZE + STD_VECTOR_UMAT + ACCESS_RW, &vec); } + +inline _InputOutputArray::_InputOutputArray(const cuda::GpuMat& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_GPU_MAT + ACCESS_RW, &d_mat); } + +inline _InputOutputArray::_InputOutputArray(const std::vector& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} + +template<> inline _InputOutputArray::_InputOutputArray(std::vector& d_mat) +{ init(FIXED_TYPE + FIXED_SIZE + STD_VECTOR_CUDA_GPU_MAT + ACCESS_RW, &d_mat);} + +inline _InputOutputArray::_InputOutputArray(const ogl::Buffer& buf) +{ init(FIXED_TYPE + FIXED_SIZE + OPENGL_BUFFER + ACCESS_RW, &buf); } + +inline _InputOutputArray::_InputOutputArray(const cuda::HostMem& cuda_mem) +{ init(FIXED_TYPE + FIXED_SIZE + CUDA_HOST_MEM + ACCESS_RW, &cuda_mem); } + +template inline +_InputOutputArray _InputOutputArray::rawInOut(std::vector<_Tp>& vec) +{ + _InputOutputArray v; + v.flags = _InputArray::FIXED_TYPE + _InputArray::STD_VECTOR + rawType<_Tp>() + ACCESS_RW; + v.obj = (void*)&vec; + return v; +} + +template inline +_InputOutputArray _InputOutputArray::rawInOut(std::array<_Tp, _Nm>& arr) +{ + _InputOutputArray v; + v.flags = FIXED_TYPE + FIXED_SIZE + MATX + traits::Type<_Tp>::value + ACCESS_RW; + v.obj = (void*)arr.data(); + v.sz = Size(1, _Nm); + return v; +} + + +template static inline _InputArray rawIn(_Tp& v) { return _InputArray::rawIn(v); } +template static inline _OutputArray rawOut(_Tp& v) { return _OutputArray::rawOut(v); } +template static inline _InputOutputArray rawInOut(_Tp& v) { return _InputOutputArray::rawInOut(v); } + +CV__DEBUG_NS_END + +//////////////////////////////////////////// Mat ////////////////////////////////////////// + +template inline +Mat::Mat(const std::vector<_Tp>& vec, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), + cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if(vec.empty()) + return; + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)&vec[0]; + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); +} + +template inline +Mat::Mat(const std::initializer_list<_Tp> list) + : Mat() +{ + CV_Assert(list.size() != 0); + Mat((int)list.size(), 1, traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); +} + +template inline +Mat::Mat(const std::initializer_list sizes, const std::initializer_list<_Tp> list) + : Mat() +{ + size_t size_total = 1; + for(auto s : sizes) + size_total *= s; + CV_Assert(list.size() != 0); + CV_Assert(size_total == list.size()); + Mat((int)sizes.size(), (int*)sizes.begin(), traits::Type<_Tp>::value, (uchar*)list.begin()).copyTo(*this); +} + +template inline +Mat::Mat(const std::array<_Tp, _Nm>& arr, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)arr.size()), + cols(1), data(0), datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if(arr.empty()) + return; + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)arr.data(); + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat((int)arr.size(), 1, traits::Type<_Tp>::value, (uchar*)arr.data()).copyTo(*this); +} + +template inline +Mat::Mat(const Vec<_Tp, n>& vec, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(n), cols(1), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)vec.val; + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat(n, 1, traits::Type<_Tp>::value, (void*)vec.val).copyTo(*this); +} + + +template inline +Mat::Mat(const Matx<_Tp,m,n>& M, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(m), cols(n), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = cols * sizeof(_Tp); + step[1] = sizeof(_Tp); + datastart = data = (uchar*)M.val; + datalimit = dataend = datastart + rows * step[0]; + } + else + Mat(m, n, traits::Type<_Tp>::value, (uchar*)M.val).copyTo(*this); +} + +template inline +Mat::Mat(const Point_<_Tp>& pt, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(2), cols(1), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)&pt.x; + datalimit = dataend = datastart + rows * step[0]; + } + else + { + create(2, 1, traits::Type<_Tp>::value); + ((_Tp*)data)[0] = pt.x; + ((_Tp*)data)[1] = pt.y; + } +} + +template inline +Mat::Mat(const Point3_<_Tp>& pt, bool copyData) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows(3), cols(1), data(0), + datastart(0), dataend(0), datalimit(0), allocator(0), u(0), size(&rows), step(0) +{ + if( !copyData ) + { + step[0] = step[1] = sizeof(_Tp); + datastart = data = (uchar*)&pt.x; + datalimit = dataend = datastart + rows * step[0]; + } + else + { + create(3, 1, traits::Type<_Tp>::value); + ((_Tp*)data)[0] = pt.x; + ((_Tp*)data)[1] = pt.y; + ((_Tp*)data)[2] = pt.z; + } +} + +template inline +Mat::Mat(const MatCommaInitializer_<_Tp>& commaInitializer) + : flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(0), rows(0), cols(0), data(0), + datastart(0), dataend(0), allocator(0), u(0), size(&rows) +{ + *this = commaInitializer.operator Mat_<_Tp>(); +} + +inline +Mat Mat::row(int y) const +{ + return Mat(*this, Range(y, y + 1), Range::all()); +} + +inline +Mat Mat::col(int x) const +{ + return Mat(*this, Range::all(), Range(x, x + 1)); +} + +inline +Mat Mat::rowRange(int startrow, int endrow) const +{ + return Mat(*this, Range(startrow, endrow), Range::all()); +} + +inline +Mat Mat::rowRange(const Range& r) const +{ + return Mat(*this, r, Range::all()); +} + +inline +Mat Mat::colRange(int startcol, int endcol) const +{ + return Mat(*this, Range::all(), Range(startcol, endcol)); +} + +inline +Mat Mat::colRange(const Range& r) const +{ + return Mat(*this, Range::all(), r); +} + +inline +Mat Mat::operator()( Range _rowRange, Range _colRange ) const +{ + return Mat(*this, _rowRange, _colRange); +} + +inline +Mat Mat::operator()( const Rect& roi ) const +{ + return Mat(*this, roi); +} + +inline +Mat Mat::operator()(const Range* ranges) const +{ + return Mat(*this, ranges); +} + +inline +Mat Mat::operator()(const std::vector& ranges) const +{ + return Mat(*this, ranges); +} + +inline +bool Mat::isContinuous() const +{ + return (flags & CONTINUOUS_FLAG) != 0; +} + +inline +bool Mat::isSubmatrix() const +{ + return (flags & SUBMATRIX_FLAG) != 0; +} + +inline +size_t Mat::elemSize() const +{ + size_t res = dims > 0 ? step.p[dims - 1] : 0; + CV_DbgAssert(res != 0); + return res; +} + +inline +size_t Mat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int Mat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int Mat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int Mat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +uchar* Mat::ptr(int y) +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return data + step.p[0] * y; +} + +inline +const uchar* Mat::ptr(int y) const +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return data + step.p[0] * y; +} + +template inline +_Tp* Mat::ptr(int y) +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return (_Tp*)(data + step.p[0] * y); +} + +template inline +const _Tp* Mat::ptr(int y) const +{ + CV_DbgAssert( y == 0 || (data && dims >= 1 && (unsigned)y < (unsigned)size.p[0]) ); + return (const _Tp*)(data + step.p[0] * y); +} + +inline +uchar* Mat::ptr(int i0, int i1) +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return data + i0 * step.p[0] + i1 * step.p[1]; +} + +inline +const uchar* Mat::ptr(int i0, int i1) const +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return data + i0 * step.p[0] + i1 * step.p[1]; +} + +template inline +_Tp* Mat::ptr(int i0, int i1) +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); +} + +template inline +const _Tp* Mat::ptr(int i0, int i1) const +{ + CV_DbgAssert(dims >= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1]); +} + +inline +uchar* Mat::ptr(int i0, int i1, int i2) +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; +} + +inline +const uchar* Mat::ptr(int i0, int i1, int i2) const +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]; +} + +template inline +_Tp* Mat::ptr(int i0, int i1, int i2) +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return (_Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); +} + +template inline +const _Tp* Mat::ptr(int i0, int i1, int i2) const +{ + CV_DbgAssert(dims >= 3); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]); + return (const _Tp*)(data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2]); +} + +inline +uchar* Mat::ptr(const int* idx) +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return p; +} + +inline +const uchar* Mat::ptr(const int* idx) const +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return p; +} + +template inline +_Tp* Mat::ptr(const int* idx) +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return (_Tp*)p; +} + +template inline +const _Tp* Mat::ptr(const int* idx) const +{ + int i, d = dims; + uchar* p = data; + CV_DbgAssert( d >= 1 && p ); + for( i = 0; i < d; i++ ) + { + CV_DbgAssert( (unsigned)idx[i] < (unsigned)size.p[i] ); + p += idx[i] * step.p[i]; + } + return (const _Tp*)p; +} + +template inline +uchar* Mat::ptr(const Vec& idx) +{ + return Mat::ptr(idx.val); +} + +template inline +const uchar* Mat::ptr(const Vec& idx) const +{ + return Mat::ptr(idx.val); +} + +template inline +_Tp* Mat::ptr(const Vec& idx) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return Mat::ptr<_Tp>(idx.val); +} + +template inline +const _Tp* Mat::ptr(const Vec& idx) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return Mat::ptr<_Tp>(idx.val); +} + + +template inline +_Tp& Mat::at(int i0, int i1) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((_Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +const _Tp& Mat::at(int i0, int i1) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((const _Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +_Tp& Mat::at(Point pt) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +const _Tp& Mat::at(Point pt) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)(pt.x * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels())); + CV_DbgAssert(CV_ELEM_SIZE1(traits::Depth<_Tp>::value) == elemSize1()); + return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +_Tp& Mat::at(int i0) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); + CV_DbgAssert(elemSize() == sizeof(_Tp)); + if( isContinuous() || size.p[0] == 1 ) + return ((_Tp*)data)[i0]; + if( size.p[1] == 1 ) + return *(_Tp*)(data + step.p[0] * i0); + int i = i0 / cols, j = i0 - i * cols; + return ((_Tp*)(data + step.p[0] * i))[j]; +} + +template inline +const _Tp& Mat::at(int i0) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)(size.p[0] * size.p[1])); + CV_DbgAssert(elemSize() == sizeof(_Tp)); + if( isContinuous() || size.p[0] == 1 ) + return ((const _Tp*)data)[i0]; + if( size.p[1] == 1 ) + return *(const _Tp*)(data + step.p[0] * i0); + int i = i0 / cols, j = i0 - i * cols; + return ((const _Tp*)(data + step.p[0] * i))[j]; +} + +template inline +_Tp& Mat::at(int i0, int i1, int i2) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(_Tp*)ptr(i0, i1, i2); +} + +template inline +const _Tp& Mat::at(int i0, int i1, int i2) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(const _Tp*)ptr(i0, i1, i2); +} + +template inline +_Tp& Mat::at(const int* idx) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(_Tp*)ptr(idx); +} + +template inline +const _Tp& Mat::at(const int* idx) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(const _Tp*)ptr(idx); +} + +template inline +_Tp& Mat::at(const Vec& idx) +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(_Tp*)ptr(idx.val); +} + +template inline +const _Tp& Mat::at(const Vec& idx) const +{ + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return *(const _Tp*)ptr(idx.val); +} + +template inline +MatConstIterator_<_Tp> Mat::begin() const +{ + if (empty()) + return MatConstIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return MatConstIterator_<_Tp>((const Mat_<_Tp>*)this); +} + +template inline +std::reverse_iterator> Mat::rbegin() const +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); + it += total(); + return std::reverse_iterator> (it); +} + +template inline +MatConstIterator_<_Tp> Mat::end() const +{ + if (empty()) + return MatConstIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatConstIterator_<_Tp> it((const Mat_<_Tp>*)this); + it += total(); + return it; +} + +template inline +std::reverse_iterator> Mat::rend() const +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return std::reverse_iterator>((const Mat_<_Tp>*)this); +} + +template inline +MatIterator_<_Tp> Mat::begin() +{ + if (empty()) + return MatIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return MatIterator_<_Tp>((Mat_<_Tp>*)this); +} + +template inline +std::reverse_iterator> Mat::rbegin() +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatIterator_<_Tp> it((Mat_<_Tp>*)this); + it += total(); + return std::reverse_iterator>(it); +} + +template inline +MatIterator_<_Tp> Mat::end() +{ + if (empty()) + return MatIterator_<_Tp>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + MatIterator_<_Tp> it((Mat_<_Tp>*)this); + it += total(); + return it; +} + +template inline +std::reverse_iterator> Mat::rend() +{ + if (empty()) + return std::reverse_iterator>(); + CV_DbgAssert( elemSize() == sizeof(_Tp) ); + return std::reverse_iterator>(MatIterator_<_Tp>((Mat_<_Tp>*)this)); +} + +template inline +void Mat::forEach(const Functor& operation) { + this->forEach_impl<_Tp>(operation); +} + +template inline +void Mat::forEach(const Functor& operation) const { + // call as not const + (const_cast(this))->forEach<_Tp>(operation); +} + +template inline +Mat::operator std::vector<_Tp>() const +{ + std::vector<_Tp> v; + copyTo(v); + return v; +} + +template inline +Mat::operator std::array<_Tp, _Nm>() const +{ + std::array<_Tp, _Nm> v; + copyTo(v); + return v; +} + +template inline +Mat::operator Vec<_Tp, n>() const +{ + CV_Assert( data && dims <= 2 && (rows == 1 || cols == 1) && + rows + cols - 1 == n && channels() == 1 ); + + if( isContinuous() && type() == traits::Type<_Tp>::value ) + return Vec<_Tp, n>((_Tp*)data); + Vec<_Tp, n> v; + Mat tmp(rows, cols, traits::Type<_Tp>::value, v.val); + convertTo(tmp, tmp.type()); + return v; +} + +template inline +Mat::operator Matx<_Tp, m, n>() const +{ + CV_Assert( data && dims <= 2 && rows == m && cols == n && channels() == 1 ); + + if( isContinuous() && type() == traits::Type<_Tp>::value ) + return Matx<_Tp, m, n>((_Tp*)data); + Matx<_Tp, m, n> mtx; + Mat tmp(rows, cols, traits::Type<_Tp>::value, mtx.val); + convertTo(tmp, tmp.type()); + return mtx; +} + +template inline +void Mat::push_back(const _Tp& elem) +{ + if( !data ) + { + *this = Mat(1, 1, traits::Type<_Tp>::value, (void*)&elem).clone(); + return; + } + CV_Assert(traits::Type<_Tp>::value == type() && cols == 1 + /* && dims == 2 (cols == 1 implies dims == 2) */); + const uchar* tmp = dataend + step[0]; + if( !isSubmatrix() && isContinuous() && tmp <= datalimit ) + { + *(_Tp*)(data + (size.p[0]++) * step.p[0]) = elem; + dataend = tmp; + } + else + push_back_(&elem); +} + +template inline +void Mat::push_back(const Mat_<_Tp>& m) +{ + push_back((const Mat&)m); +} + +template<> inline +void Mat::push_back(const MatExpr& expr) +{ + push_back(static_cast(expr)); +} + + +template inline +void Mat::push_back(const std::vector<_Tp>& v) +{ + push_back(Mat(v)); +} + + +///////////////////////////// MatSize //////////////////////////// + +inline +MatSize::MatSize(int* _p) CV_NOEXCEPT + : p(_p) {} + +inline +int MatSize::dims() const CV_NOEXCEPT +{ + return (p - 1)[0]; +} + +inline +Size MatSize::operator()() const +{ + CV_DbgAssert(dims() <= 2); + return Size(p[1], p[0]); +} + +inline +const int& MatSize::operator[](int i) const +{ + CV_DbgAssert(i < dims()); +#ifdef __OPENCV_BUILD + CV_DbgAssert(i >= 0); +#endif + return p[i]; +} + +inline +int& MatSize::operator[](int i) +{ + CV_DbgAssert(i < dims()); +#ifdef __OPENCV_BUILD + CV_DbgAssert(i >= 0); +#endif + return p[i]; +} + +inline +MatSize::operator const int*() const CV_NOEXCEPT +{ + return p; +} + +inline +bool MatSize::operator != (const MatSize& sz) const CV_NOEXCEPT +{ + return !(*this == sz); +} + + + +///////////////////////////// MatStep //////////////////////////// + +inline +MatStep::MatStep() CV_NOEXCEPT +{ + p = buf; p[0] = p[1] = 0; +} + +inline +MatStep::MatStep(size_t s) CV_NOEXCEPT +{ + p = buf; p[0] = s; p[1] = 0; +} + +inline +const size_t& MatStep::operator[](int i) const CV_NOEXCEPT +{ + return p[i]; +} + +inline +size_t& MatStep::operator[](int i) CV_NOEXCEPT +{ + return p[i]; +} + +inline MatStep::operator size_t() const +{ + CV_DbgAssert( p == buf ); + return buf[0]; +} + +inline MatStep& MatStep::operator = (size_t s) +{ + CV_DbgAssert( p == buf ); + buf[0] = s; + return *this; +} + + + +////////////////////////////// Mat_<_Tp> //////////////////////////// + +template inline +Mat_<_Tp>::Mat_() CV_NOEXCEPT + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; +} + +template inline +Mat_<_Tp>::Mat_(int _rows, int _cols) + : Mat(_rows, _cols, traits::Type<_Tp>::value) +{ +} + +template inline +Mat_<_Tp>::Mat_(int _rows, int _cols, const _Tp& value) + : Mat(_rows, _cols, traits::Type<_Tp>::value) +{ + *this = value; +} + +template inline +Mat_<_Tp>::Mat_(Size _sz) + : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) +{} + +template inline +Mat_<_Tp>::Mat_(Size _sz, const _Tp& value) + : Mat(_sz.height, _sz.width, traits::Type<_Tp>::value) +{ + *this = value; +} + +template inline +Mat_<_Tp>::Mat_(int _dims, const int* _sz) + : Mat(_dims, _sz, traits::Type<_Tp>::value) +{} + +template inline +Mat_<_Tp>::Mat_(int _dims, const int* _sz, const _Tp& _s) + : Mat(_dims, _sz, traits::Type<_Tp>::value, Scalar(_s)) +{} + +template inline +Mat_<_Tp>::Mat_(int _dims, const int* _sz, _Tp* _data, const size_t* _steps) + : Mat(_dims, _sz, traits::Type<_Tp>::value, _data, _steps) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const Range* ranges) + : Mat(m, ranges) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_<_Tp>& m, const std::vector& ranges) + : Mat(m, ranges) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat& m) + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; + *this = m; +} + +template inline +Mat_<_Tp>::Mat_(const Mat_& m) + : Mat(m) +{} + +template inline +Mat_<_Tp>::Mat_(int _rows, int _cols, _Tp* _data, size_t steps) + : Mat(_rows, _cols, traits::Type<_Tp>::value, _data, steps) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_& m, const Range& _rowRange, const Range& _colRange) + : Mat(m, _rowRange, _colRange) +{} + +template inline +Mat_<_Tp>::Mat_(const Mat_& m, const Rect& roi) + : Mat(m, roi) +{} + +template template inline +Mat_<_Tp>::Mat_(const Vec::channel_type, n>& vec, bool copyData) + : Mat(n / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&vec) +{ + CV_Assert(n%DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template template inline +Mat_<_Tp>::Mat_(const Matx::channel_type, m, n>& M, bool copyData) + : Mat(m, n / DataType<_Tp>::channels, traits::Type<_Tp>::value, (void*)&M) +{ + CV_Assert(n % DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template inline +Mat_<_Tp>::Mat_(const Point_::channel_type>& pt, bool copyData) + : Mat(2 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) +{ + CV_Assert(2 % DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template inline +Mat_<_Tp>::Mat_(const Point3_::channel_type>& pt, bool copyData) + : Mat(3 / DataType<_Tp>::channels, 1, traits::Type<_Tp>::value, (void*)&pt) +{ + CV_Assert(3 % DataType<_Tp>::channels == 0); + if( copyData ) + *this = clone(); +} + +template inline +Mat_<_Tp>::Mat_(const MatCommaInitializer_<_Tp>& commaInitializer) + : Mat(commaInitializer) +{} + +template inline +Mat_<_Tp>::Mat_(const std::vector<_Tp>& vec, bool copyData) + : Mat(vec, copyData) +{} + +template inline +Mat_<_Tp>::Mat_(std::initializer_list<_Tp> list) + : Mat(list) +{} + +template inline +Mat_<_Tp>::Mat_(const std::initializer_list sizes, std::initializer_list<_Tp> list) + : Mat(sizes, list) +{} + +template template inline +Mat_<_Tp>::Mat_(const std::array<_Tp, _Nm>& arr, bool copyData) + : Mat(arr, copyData) +{} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat& m) +{ + if (m.empty()) + { + release(); + return *this; + } + if( traits::Type<_Tp>::value == m.type() ) + { + Mat::operator = (m); + return *this; + } + if( traits::Depth<_Tp>::value == m.depth() ) + { + return (*this = m.reshape(DataType<_Tp>::channels, m.dims, 0)); + } + CV_Assert(DataType<_Tp>::channels == m.channels() || m.empty()); + m.convertTo(*this, type()); + return *this; +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const Mat_& m) +{ + Mat::operator=(m); + return *this; +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const _Tp& s) +{ + typedef typename DataType<_Tp>::vec_type VT; + Mat::operator=(Scalar((const VT&)s)); + return *this; +} + +template inline +void Mat_<_Tp>::create(int _rows, int _cols) +{ + Mat::create(_rows, _cols, traits::Type<_Tp>::value); +} + +template inline +void Mat_<_Tp>::create(Size _sz) +{ + Mat::create(_sz, traits::Type<_Tp>::value); +} + +template inline +void Mat_<_Tp>::create(int _dims, const int* _sz) +{ + Mat::create(_dims, _sz, traits::Type<_Tp>::value); +} + +template inline +void Mat_<_Tp>::release() +{ + Mat::release(); + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; +} + +template inline +Mat_<_Tp> Mat_<_Tp>::cross(const Mat_& m) const +{ + return Mat_<_Tp>(Mat::cross(m)); +} + +template template inline +Mat_<_Tp>::operator Mat_() const +{ + return Mat_(static_cast(*this)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::row(int y) const +{ + return Mat_(*this, Range(y, y+1), Range::all()); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::col(int x) const +{ + return Mat_(*this, Range::all(), Range(x, x+1)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::diag(int d) const +{ + return Mat_(Mat::diag(d)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::clone() const +{ + return Mat_(Mat::clone()); +} + +template inline +size_t Mat_<_Tp>::elemSize() const +{ + CV_DbgAssert( Mat::elemSize() == sizeof(_Tp) ); + return sizeof(_Tp); +} + +template inline +size_t Mat_<_Tp>::elemSize1() const +{ + CV_DbgAssert( Mat::elemSize1() == sizeof(_Tp) / DataType<_Tp>::channels ); + return sizeof(_Tp) / DataType<_Tp>::channels; +} + +template inline +int Mat_<_Tp>::type() const +{ + CV_DbgAssert( Mat::type() == traits::Type<_Tp>::value ); + return traits::Type<_Tp>::value; +} + +template inline +int Mat_<_Tp>::depth() const +{ + CV_DbgAssert( Mat::depth() == traits::Depth<_Tp>::value ); + return traits::Depth<_Tp>::value; +} + +template inline +int Mat_<_Tp>::channels() const +{ + CV_DbgAssert( Mat::channels() == DataType<_Tp>::channels ); + return DataType<_Tp>::channels; +} + +template inline +size_t Mat_<_Tp>::stepT(int i) const +{ + return step.p[i] / elemSize(); +} + +template inline +size_t Mat_<_Tp>::step1(int i) const +{ + return step.p[i] / elemSize1(); +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::adjustROI( int dtop, int dbottom, int dleft, int dright ) +{ + return (Mat_<_Tp>&)(Mat::adjustROI(dtop, dbottom, dleft, dright)); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()( const Range& _rowRange, const Range& _colRange ) const +{ + return Mat_<_Tp>(*this, _rowRange, _colRange); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()( const Rect& roi ) const +{ + return Mat_<_Tp>(*this, roi); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()( const Range* ranges ) const +{ + return Mat_<_Tp>(*this, ranges); +} + +template inline +Mat_<_Tp> Mat_<_Tp>::operator()(const std::vector& ranges) const +{ + return Mat_<_Tp>(*this, ranges); +} + +template inline +_Tp* Mat_<_Tp>::operator [](int y) +{ + CV_DbgAssert( 0 <= y && y < size.p[0] ); + return (_Tp*)(data + y*step.p[0]); +} + +template inline +const _Tp* Mat_<_Tp>::operator [](int y) const +{ + CV_DbgAssert( 0 <= y && y < size.p[0] ); + return (const _Tp*)(data + y*step.p[0]); +} + +template inline +_Tp& Mat_<_Tp>::operator ()(int i0, int i1) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((_Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(int i0, int i1) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((const _Tp*)(data + step.p[0] * i0))[i1]; +} + +template inline +_Tp& Mat_<_Tp>::operator ()(Point pt) +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((_Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(Point pt) const +{ + CV_DbgAssert(dims <= 2); + CV_DbgAssert(data); + CV_DbgAssert((unsigned)pt.y < (unsigned)size.p[0]); + CV_DbgAssert((unsigned)pt.x < (unsigned)size.p[1]); + CV_DbgAssert(type() == traits::Type<_Tp>::value); + return ((const _Tp*)(data + step.p[0] * pt.y))[pt.x]; +} + +template inline +_Tp& Mat_<_Tp>::operator ()(const int* idx) +{ + return Mat::at<_Tp>(idx); +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(const int* idx) const +{ + return Mat::at<_Tp>(idx); +} + +template template inline +_Tp& Mat_<_Tp>::operator ()(const Vec& idx) +{ + return Mat::at<_Tp>(idx); +} + +template template inline +const _Tp& Mat_<_Tp>::operator ()(const Vec& idx) const +{ + return Mat::at<_Tp>(idx); +} + +template inline +_Tp& Mat_<_Tp>::operator ()(int i0) +{ + return this->at<_Tp>(i0); +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(int i0) const +{ + return this->at<_Tp>(i0); +} + +template inline +_Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) +{ + return this->at<_Tp>(i0, i1, i2); +} + +template inline +const _Tp& Mat_<_Tp>::operator ()(int i0, int i1, int i2) const +{ + return this->at<_Tp>(i0, i1, i2); +} + +template inline +Mat_<_Tp>::operator std::vector<_Tp>() const +{ + std::vector<_Tp> v; + copyTo(v); + return v; +} + +template template inline +Mat_<_Tp>::operator std::array<_Tp, _Nm>() const +{ + std::array<_Tp, _Nm> a; + copyTo(a); + return a; +} + +template template inline +Mat_<_Tp>::operator Vec::channel_type, n>() const +{ + CV_Assert(n % DataType<_Tp>::channels == 0); + +#if defined _MSC_VER + const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) + return pMat->operator Vec::channel_type, n>(); +#else + return this->Mat::operator Vec::channel_type, n>(); +#endif +} + +template template inline +Mat_<_Tp>::operator Matx::channel_type, m, n>() const +{ + CV_Assert(n % DataType<_Tp>::channels == 0); + +#if defined _MSC_VER + const Mat* pMat = (const Mat*)this; // workaround for MSVS <= 2012 compiler bugs (but GCC 4.6 dislikes this workaround) + Matx::channel_type, m, n> res = pMat->operator Matx::channel_type, m, n>(); + return res; +#else + Matx::channel_type, m, n> res = this->Mat::operator Matx::channel_type, m, n>(); + return res; +#endif +} + +template inline +MatConstIterator_<_Tp> Mat_<_Tp>::begin() const +{ + return Mat::begin<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rbegin() const +{ + return Mat::rbegin<_Tp>(); +} + +template inline +MatConstIterator_<_Tp> Mat_<_Tp>::end() const +{ + return Mat::end<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rend() const +{ + return Mat::rend<_Tp>(); +} + +template inline +MatIterator_<_Tp> Mat_<_Tp>::begin() +{ + return Mat::begin<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rbegin() +{ + return Mat::rbegin<_Tp>(); +} + +template inline +MatIterator_<_Tp> Mat_<_Tp>::end() +{ + return Mat::end<_Tp>(); +} + +template inline +std::reverse_iterator> Mat_<_Tp>::rend() +{ + return Mat::rend<_Tp>(); +} + +template template inline +void Mat_<_Tp>::forEach(const Functor& operation) { + Mat::forEach<_Tp, Functor>(operation); +} + +template template inline +void Mat_<_Tp>::forEach(const Functor& operation) const { + Mat::forEach<_Tp, Functor>(operation); +} + +template inline +Mat_<_Tp>::Mat_(Mat_&& m) + : Mat(std::move(m)) +{ +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (Mat_&& m) +{ + Mat::operator = (std::move(m)); + return *this; +} + +template inline +Mat_<_Tp>::Mat_(Mat&& m) + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; + *this = std::move(m); +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (Mat&& m) +{ + if (m.empty()) + { + release(); + return *this; + } + if( traits::Type<_Tp>::value == m.type() ) + { + Mat::operator = ((Mat&&)m); + return *this; + } + if( traits::Depth<_Tp>::value == m.depth() ) + { + Mat::operator = ((Mat&&)m.reshape(DataType<_Tp>::channels, m.dims, 0)); + return *this; + } + CV_DbgAssert(DataType<_Tp>::channels == m.channels()); + m.convertTo(*this, type()); + return *this; +} + +template inline +Mat_<_Tp>::Mat_(MatExpr&& e) + : Mat() +{ + flags = (flags & ~CV_MAT_TYPE_MASK) + traits::Type<_Tp>::value; + *this = Mat(e); +} + + +///////////////////////////// SparseMat ///////////////////////////// + +inline +SparseMat SparseMat::clone() const +{ + SparseMat temp; + this->copyTo(temp); + return temp; +} + +inline +size_t SparseMat::elemSize() const +{ + return CV_ELEM_SIZE(flags); +} + +inline +size_t SparseMat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int SparseMat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int SparseMat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int SparseMat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +const int* SparseMat::size() const +{ + return hdr ? hdr->size : 0; +} + +inline +int SparseMat::size(int i) const +{ + if( hdr ) + { + CV_DbgAssert((unsigned)i < (unsigned)hdr->dims); + return hdr->size[i]; + } + return 0; +} + +inline +int SparseMat::dims() const +{ + return hdr ? hdr->dims : 0; +} + +inline +size_t SparseMat::nzcount() const +{ + return hdr ? hdr->nodeCount : 0; +} + +template inline +_Tp& SparseMat::ref(int i0, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(i0, true, hashval); +} + +template inline +_Tp& SparseMat::ref(int i0, int i1, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, true, hashval); +} + +template inline +_Tp& SparseMat::ref(int i0, int i1, int i2, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(i0, i1, i2, true, hashval); +} + +template inline +_Tp& SparseMat::ref(const int* idx, size_t* hashval) +{ + return *(_Tp*)((SparseMat*)this)->ptr(idx, true, hashval); +} + +template inline +_Tp SparseMat::value(int i0, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); + return p ? *p : _Tp(); +} + +template inline +_Tp SparseMat::value(int i0, int i1, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); + return p ? *p : _Tp(); +} + +template inline +_Tp SparseMat::value(int i0, int i1, int i2, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); + return p ? *p : _Tp(); +} + +template inline +_Tp SparseMat::value(const int* idx, size_t* hashval) const +{ + const _Tp* p = (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); + return p ? *p : _Tp(); +} + +template inline +const _Tp* SparseMat::find(int i0, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(i0, false, hashval); +} + +template inline +const _Tp* SparseMat::find(int i0, int i1, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, false, hashval); +} + +template inline +const _Tp* SparseMat::find(int i0, int i1, int i2, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(i0, i1, i2, false, hashval); +} + +template inline +const _Tp* SparseMat::find(const int* idx, size_t* hashval) const +{ + return (const _Tp*)((SparseMat*)this)->ptr(idx, false, hashval); +} + +template inline +_Tp& SparseMat::value(Node* n) +{ + return *(_Tp*)((uchar*)n + hdr->valueOffset); +} + +template inline +const _Tp& SparseMat::value(const Node* n) const +{ + return *(const _Tp*)((const uchar*)n + hdr->valueOffset); +} + +inline +SparseMat::Node* SparseMat::node(size_t nidx) +{ + return (Node*)(void*)&hdr->pool[nidx]; +} + +inline +const SparseMat::Node* SparseMat::node(size_t nidx) const +{ + return (const Node*)(const void*)&hdr->pool[nidx]; +} + +inline +SparseMatIterator SparseMat::begin() +{ + return SparseMatIterator(this); +} + +inline +SparseMatConstIterator SparseMat::begin() const +{ + return SparseMatConstIterator(this); +} + +inline +SparseMatIterator SparseMat::end() +{ + SparseMatIterator it(this); + it.seekEnd(); + return it; +} + +inline +SparseMatConstIterator SparseMat::end() const +{ + SparseMatConstIterator it(this); + it.seekEnd(); + return it; +} + +template inline +SparseMatIterator_<_Tp> SparseMat::begin() +{ + return SparseMatIterator_<_Tp>(this); +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat::begin() const +{ + return SparseMatConstIterator_<_Tp>(this); +} + +template inline +SparseMatIterator_<_Tp> SparseMat::end() +{ + SparseMatIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat::end() const +{ + SparseMatConstIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + + + +///////////////////////////// SparseMat_ //////////////////////////// + +template inline +SparseMat_<_Tp>::SparseMat_() +{ + flags = +MAGIC_VAL + traits::Type<_Tp>::value; +} + +template inline +SparseMat_<_Tp>::SparseMat_(int _dims, const int* _sizes) + : SparseMat(_dims, _sizes, traits::Type<_Tp>::value) +{} + +template inline +SparseMat_<_Tp>::SparseMat_(const SparseMat& m) +{ + if( m.type() == traits::Type<_Tp>::value ) + *this = (const SparseMat_<_Tp>&)m; + else + m.convertTo(*this, traits::Type<_Tp>::value); +} + +template inline +SparseMat_<_Tp>::SparseMat_(const SparseMat_<_Tp>& m) +{ + this->flags = m.flags; + this->hdr = m.hdr; + if( this->hdr ) + CV_XADD(&this->hdr->refcount, 1); +} + +template inline +SparseMat_<_Tp>::SparseMat_(const Mat& m) +{ + SparseMat sm(m); + *this = sm; +} + +template inline +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat_<_Tp>& m) +{ + if( this != &m ) + { + if( m.hdr ) CV_XADD(&m.hdr->refcount, 1); + release(); + flags = m.flags; + hdr = m.hdr; + } + return *this; +} + +template inline +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const SparseMat& m) +{ + if( m.type() == traits::Type<_Tp>::value ) + return (*this = (const SparseMat_<_Tp>&)m); + m.convertTo(*this, traits::Type<_Tp>::value); + return *this; +} + +template inline +SparseMat_<_Tp>& SparseMat_<_Tp>::operator = (const Mat& m) +{ + return (*this = SparseMat(m)); +} + +template inline +SparseMat_<_Tp> SparseMat_<_Tp>::clone() const +{ + SparseMat_<_Tp> m; + this->copyTo(m); + return m; +} + +template inline +void SparseMat_<_Tp>::create(int _dims, const int* _sizes) +{ + SparseMat::create(_dims, _sizes, traits::Type<_Tp>::value); +} + +template inline +int SparseMat_<_Tp>::type() const +{ + return traits::Type<_Tp>::value; +} + +template inline +int SparseMat_<_Tp>::depth() const +{ + return traits::Depth<_Tp>::value; +} + +template inline +int SparseMat_<_Tp>::channels() const +{ + return DataType<_Tp>::channels; +} + +template inline +_Tp& SparseMat_<_Tp>::ref(int i0, size_t* hashval) +{ + return SparseMat::ref<_Tp>(i0, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(int i0, size_t* hashval) const +{ + return SparseMat::value<_Tp>(i0, hashval); +} + +template inline +_Tp& SparseMat_<_Tp>::ref(int i0, int i1, size_t* hashval) +{ + return SparseMat::ref<_Tp>(i0, i1, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(int i0, int i1, size_t* hashval) const +{ + return SparseMat::value<_Tp>(i0, i1, hashval); +} + +template inline +_Tp& SparseMat_<_Tp>::ref(int i0, int i1, int i2, size_t* hashval) +{ + return SparseMat::ref<_Tp>(i0, i1, i2, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(int i0, int i1, int i2, size_t* hashval) const +{ + return SparseMat::value<_Tp>(i0, i1, i2, hashval); +} + +template inline +_Tp& SparseMat_<_Tp>::ref(const int* idx, size_t* hashval) +{ + return SparseMat::ref<_Tp>(idx, hashval); +} + +template inline +_Tp SparseMat_<_Tp>::operator()(const int* idx, size_t* hashval) const +{ + return SparseMat::value<_Tp>(idx, hashval); +} + +template inline +SparseMatIterator_<_Tp> SparseMat_<_Tp>::begin() +{ + return SparseMatIterator_<_Tp>(this); +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::begin() const +{ + return SparseMatConstIterator_<_Tp>(this); +} + +template inline +SparseMatIterator_<_Tp> SparseMat_<_Tp>::end() +{ + SparseMatIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + +template inline +SparseMatConstIterator_<_Tp> SparseMat_<_Tp>::end() const +{ + SparseMatConstIterator_<_Tp> it(this); + it.seekEnd(); + return it; +} + + + +////////////////////////// MatConstIterator ///////////////////////// + +inline +MatConstIterator::MatConstIterator() + : m(0), elemSize(0), ptr(0), sliceStart(0), sliceEnd(0) +{} + +inline +MatConstIterator::MatConstIterator(const Mat* _m) + : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) +{ + if( m && m->isContinuous() ) + { + CV_Assert(!m->empty()); + sliceStart = m->ptr(); + sliceEnd = sliceStart + m->total()*elemSize; + } + seek((const int*)0); +} + +inline +MatConstIterator::MatConstIterator(const Mat* _m, int _row, int _col) + : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) +{ + CV_Assert(m && m->dims <= 2); + if( m->isContinuous() ) + { + CV_Assert(!m->empty()); + sliceStart = m->ptr(); + sliceEnd = sliceStart + m->total()*elemSize; + } + int idx[] = {_row, _col}; + seek(idx); +} + +inline +MatConstIterator::MatConstIterator(const Mat* _m, Point _pt) + : m(_m), elemSize(_m->elemSize()), ptr(0), sliceStart(0), sliceEnd(0) +{ + CV_Assert(m && m->dims <= 2); + if( m->isContinuous() ) + { + CV_Assert(!m->empty()); + sliceStart = m->ptr(); + sliceEnd = sliceStart + m->total()*elemSize; + } + int idx[] = {_pt.y, _pt.x}; + seek(idx); +} + +inline +MatConstIterator::MatConstIterator(const MatConstIterator& it) + : m(it.m), elemSize(it.elemSize), ptr(it.ptr), sliceStart(it.sliceStart), sliceEnd(it.sliceEnd) +{} + +inline +MatConstIterator& MatConstIterator::operator = (const MatConstIterator& it ) +{ + m = it.m; elemSize = it.elemSize; ptr = it.ptr; + sliceStart = it.sliceStart; sliceEnd = it.sliceEnd; + return *this; +} + +inline +const uchar* MatConstIterator::operator *() const +{ + return ptr; +} + +inline MatConstIterator& MatConstIterator::operator += (ptrdiff_t ofs) +{ + if( !m || ofs == 0 ) + return *this; + ptrdiff_t ofsb = ofs*elemSize; + ptr += ofsb; + if( ptr < sliceStart || sliceEnd <= ptr ) + { + ptr -= ofsb; + seek(ofs, true); + } + return *this; +} + +inline +MatConstIterator& MatConstIterator::operator -= (ptrdiff_t ofs) +{ + return (*this += -ofs); +} + +inline +MatConstIterator& MatConstIterator::operator --() +{ + if( m && (ptr -= elemSize) < sliceStart ) + { + ptr += elemSize; + seek(-1, true); + } + return *this; +} + +inline +MatConstIterator MatConstIterator::operator --(int) +{ + MatConstIterator b = *this; + *this += -1; + return b; +} + +inline +MatConstIterator& MatConstIterator::operator ++() +{ + if( m && (ptr += elemSize) >= sliceEnd ) + { + ptr -= elemSize; + seek(1, true); + } + return *this; +} + +inline MatConstIterator MatConstIterator::operator ++(int) +{ + MatConstIterator b = *this; + *this += 1; + return b; +} + + +static inline +bool operator == (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.m == b.m && a.ptr == b.ptr; +} + +static inline +bool operator != (const MatConstIterator& a, const MatConstIterator& b) +{ + return !(a == b); +} + +static inline +bool operator < (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr < b.ptr; +} + +static inline +bool operator > (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr > b.ptr; +} + +static inline +bool operator <= (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr <= b.ptr; +} + +static inline +bool operator >= (const MatConstIterator& a, const MatConstIterator& b) +{ + return a.ptr >= b.ptr; +} + +static inline +ptrdiff_t operator - (const MatConstIterator& b, const MatConstIterator& a) +{ + if( a.m != b.m ) + return ((size_t)(-1) >> 1); + if( a.sliceEnd == b.sliceEnd ) + return (b.ptr - a.ptr)/static_cast(b.elemSize); + + return b.lpos() - a.lpos(); +} + +static inline +MatConstIterator operator + (const MatConstIterator& a, ptrdiff_t ofs) +{ + MatConstIterator b = a; + return b += ofs; +} + +static inline +MatConstIterator operator + (ptrdiff_t ofs, const MatConstIterator& a) +{ + MatConstIterator b = a; + return b += ofs; +} + +static inline +MatConstIterator operator - (const MatConstIterator& a, ptrdiff_t ofs) +{ + MatConstIterator b = a; + return b += -ofs; +} + + +inline +const uchar* MatConstIterator::operator [](ptrdiff_t i) const +{ + return *(*this + i); +} + + + +///////////////////////// MatConstIterator_ ///////////////////////// + +template inline +MatConstIterator_<_Tp>::MatConstIterator_() +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m) + : MatConstIterator(_m) +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, int _row, int _col) + : MatConstIterator(_m, _row, _col) +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const Mat_<_Tp>* _m, Point _pt) + : MatConstIterator(_m, _pt) +{} + +template inline +MatConstIterator_<_Tp>::MatConstIterator_(const MatConstIterator_& it) + : MatConstIterator(it) +{} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator = (const MatConstIterator_& it ) +{ + MatConstIterator::operator = (it); + return *this; +} + +template inline +const _Tp& MatConstIterator_<_Tp>::operator *() const +{ + return *(_Tp*)(this->ptr); +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator += (ptrdiff_t ofs) +{ + MatConstIterator::operator += (ofs); + return *this; +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator -= (ptrdiff_t ofs) +{ + return (*this += -ofs); +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator --() +{ + MatConstIterator::operator --(); + return *this; +} + +template inline +MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator --(int) +{ + MatConstIterator_ b = *this; + MatConstIterator::operator --(); + return b; +} + +template inline +MatConstIterator_<_Tp>& MatConstIterator_<_Tp>::operator ++() +{ + MatConstIterator::operator ++(); + return *this; +} + +template inline +MatConstIterator_<_Tp> MatConstIterator_<_Tp>::operator ++(int) +{ + MatConstIterator_ b = *this; + MatConstIterator::operator ++(); + return b; +} + + +template inline +Point MatConstIterator_<_Tp>::pos() const +{ + if( !m ) + return Point(); + CV_DbgAssert( m->dims <= 2 ); + if( m->isContinuous() ) + { + ptrdiff_t ofs = (const _Tp*)ptr - (const _Tp*)m->data; + int y = (int)(ofs / m->cols); + int x = (int)(ofs - (ptrdiff_t)y * m->cols); + return Point(x, y); + } + else + { + ptrdiff_t ofs = (uchar*)ptr - m->data; + int y = (int)(ofs / m->step); + int x = (int)((ofs - y * m->step)/sizeof(_Tp)); + return Point(x, y); + } +} + + +template static inline +bool operator == (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) +{ + return a.m == b.m && a.ptr == b.ptr; +} + +template static inline +bool operator != (const MatConstIterator_<_Tp>& a, const MatConstIterator_<_Tp>& b) +{ + return a.m != b.m || a.ptr != b.ptr; +} + +template static inline +MatConstIterator_<_Tp> operator + (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatConstIterator_<_Tp>&)t; +} + +template static inline +MatConstIterator_<_Tp> operator + (ptrdiff_t ofs, const MatConstIterator_<_Tp>& a) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatConstIterator_<_Tp>&)t; +} + +template static inline +MatConstIterator_<_Tp> operator - (const MatConstIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a - ofs; + return (MatConstIterator_<_Tp>&)t; +} + +template inline +const _Tp& MatConstIterator_<_Tp>::operator [](ptrdiff_t i) const +{ + return *(_Tp*)MatConstIterator::operator [](i); +} + + + +//////////////////////////// MatIterator_ /////////////////////////// + +template inline +MatIterator_<_Tp>::MatIterator_() + : MatConstIterator_<_Tp>() +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m) + : MatConstIterator_<_Tp>(_m) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, int _row, int _col) + : MatConstIterator_<_Tp>(_m, _row, _col) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, Point _pt) + : MatConstIterator_<_Tp>(_m, _pt) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(Mat_<_Tp>* _m, const int* _idx) + : MatConstIterator_<_Tp>(_m, _idx) +{} + +template inline +MatIterator_<_Tp>::MatIterator_(const MatIterator_& it) + : MatConstIterator_<_Tp>(it) +{} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator = (const MatIterator_<_Tp>& it ) +{ + MatConstIterator::operator = (it); + return *this; +} + +template inline +_Tp& MatIterator_<_Tp>::operator *() const +{ + return *(_Tp*)(this->ptr); +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator += (ptrdiff_t ofs) +{ + MatConstIterator::operator += (ofs); + return *this; +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator -= (ptrdiff_t ofs) +{ + MatConstIterator::operator += (-ofs); + return *this; +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator --() +{ + MatConstIterator::operator --(); + return *this; +} + +template inline +MatIterator_<_Tp> MatIterator_<_Tp>::operator --(int) +{ + MatIterator_ b = *this; + MatConstIterator::operator --(); + return b; +} + +template inline +MatIterator_<_Tp>& MatIterator_<_Tp>::operator ++() +{ + MatConstIterator::operator ++(); + return *this; +} + +template inline +MatIterator_<_Tp> MatIterator_<_Tp>::operator ++(int) +{ + MatIterator_ b = *this; + MatConstIterator::operator ++(); + return b; +} + +template inline +_Tp& MatIterator_<_Tp>::operator [](ptrdiff_t i) const +{ + return *(*this + i); +} + + +template static inline +bool operator == (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) +{ + return a.m == b.m && a.ptr == b.ptr; +} + +template static inline +bool operator != (const MatIterator_<_Tp>& a, const MatIterator_<_Tp>& b) +{ + return a.m != b.m || a.ptr != b.ptr; +} + +template static inline +MatIterator_<_Tp> operator + (const MatIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatIterator_<_Tp>&)t; +} + +template static inline +MatIterator_<_Tp> operator + (ptrdiff_t ofs, const MatIterator_<_Tp>& a) +{ + MatConstIterator t = (const MatConstIterator&)a + ofs; + return (MatIterator_<_Tp>&)t; +} + +template static inline +MatIterator_<_Tp> operator - (const MatIterator_<_Tp>& a, ptrdiff_t ofs) +{ + MatConstIterator t = (const MatConstIterator&)a - ofs; + return (MatIterator_<_Tp>&)t; +} + + + +/////////////////////// SparseMatConstIterator ////////////////////// + +inline +SparseMatConstIterator::SparseMatConstIterator() + : m(0), hashidx(0), ptr(0) +{} + +inline +SparseMatConstIterator::SparseMatConstIterator(const SparseMatConstIterator& it) + : m(it.m), hashidx(it.hashidx), ptr(it.ptr) +{} + +inline SparseMatConstIterator& SparseMatConstIterator::operator = (const SparseMatConstIterator& it) +{ + if( this != &it ) + { + m = it.m; + hashidx = it.hashidx; + ptr = it.ptr; + } + return *this; +} + +template inline +const _Tp& SparseMatConstIterator::value() const +{ + return *(const _Tp*)ptr; +} + +inline +const SparseMat::Node* SparseMatConstIterator::node() const +{ + return (ptr && m && m->hdr) ? (const SparseMat::Node*)(const void*)(ptr - m->hdr->valueOffset) : 0; +} + +inline +SparseMatConstIterator SparseMatConstIterator::operator ++(int) +{ + SparseMatConstIterator it = *this; + ++*this; + return it; +} + +inline +void SparseMatConstIterator::seekEnd() +{ + if( m && m->hdr ) + { + hashidx = m->hdr->hashtab.size(); + ptr = 0; + } +} + + +static inline +bool operator == (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) +{ + return it1.m == it2.m && it1.ptr == it2.ptr; +} + +static inline +bool operator != (const SparseMatConstIterator& it1, const SparseMatConstIterator& it2) +{ + return !(it1 == it2); +} + + + +///////////////////////// SparseMatIterator ///////////////////////// + +inline +SparseMatIterator::SparseMatIterator() +{} + +inline +SparseMatIterator::SparseMatIterator(SparseMat* _m) + : SparseMatConstIterator(_m) +{} + +inline +SparseMatIterator::SparseMatIterator(const SparseMatIterator& it) + : SparseMatConstIterator(it) +{} + +inline +SparseMatIterator& SparseMatIterator::operator = (const SparseMatIterator& it) +{ + (SparseMatConstIterator&)*this = it; + return *this; +} + +template inline +_Tp& SparseMatIterator::value() const +{ + return *(_Tp*)ptr; +} + +inline +SparseMat::Node* SparseMatIterator::node() const +{ + return (SparseMat::Node*)SparseMatConstIterator::node(); +} + +inline +SparseMatIterator& SparseMatIterator::operator ++() +{ + SparseMatConstIterator::operator ++(); + return *this; +} + +inline +SparseMatIterator SparseMatIterator::operator ++(int) +{ + SparseMatIterator it = *this; + ++*this; + return it; +} + + + +////////////////////// SparseMatConstIterator_ ////////////////////// + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_() +{} + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat_<_Tp>* _m) + : SparseMatConstIterator(_m) +{} + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMat* _m) + : SparseMatConstIterator(_m) +{ + CV_Assert( _m->type() == traits::Type<_Tp>::value ); +} + +template inline +SparseMatConstIterator_<_Tp>::SparseMatConstIterator_(const SparseMatConstIterator_<_Tp>& it) + : SparseMatConstIterator(it) +{} + +template inline +SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator = (const SparseMatConstIterator_<_Tp>& it) +{ + return reinterpret_cast&> + (*reinterpret_cast(this) = + reinterpret_cast(it)); +} + +template inline +const _Tp& SparseMatConstIterator_<_Tp>::operator *() const +{ + return *(const _Tp*)this->ptr; +} + +template inline +SparseMatConstIterator_<_Tp>& SparseMatConstIterator_<_Tp>::operator ++() +{ + SparseMatConstIterator::operator ++(); + return *this; +} + +template inline +SparseMatConstIterator_<_Tp> SparseMatConstIterator_<_Tp>::operator ++(int) +{ + SparseMatConstIterator_<_Tp> it = *this; + SparseMatConstIterator::operator ++(); + return it; +} + + + +///////////////////////// SparseMatIterator_ //////////////////////// + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_() +{} + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat_<_Tp>* _m) + : SparseMatConstIterator_<_Tp>(_m) +{} + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_(SparseMat* _m) + : SparseMatConstIterator_<_Tp>(_m) +{} + +template inline +SparseMatIterator_<_Tp>::SparseMatIterator_(const SparseMatIterator_<_Tp>& it) + : SparseMatConstIterator_<_Tp>(it) +{} + +template inline +SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator = (const SparseMatIterator_<_Tp>& it) +{ + return reinterpret_cast&> + (*reinterpret_cast(this) = + reinterpret_cast(it)); +} + +template inline +_Tp& SparseMatIterator_<_Tp>::operator *() const +{ + return *(_Tp*)this->ptr; +} + +template inline +SparseMatIterator_<_Tp>& SparseMatIterator_<_Tp>::operator ++() +{ + SparseMatConstIterator::operator ++(); + return *this; +} + +template inline +SparseMatIterator_<_Tp> SparseMatIterator_<_Tp>::operator ++(int) +{ + SparseMatIterator_<_Tp> it = *this; + SparseMatConstIterator::operator ++(); + return it; +} + + + +//////////////////////// MatCommaInitializer_ /////////////////////// + +template inline +MatCommaInitializer_<_Tp>::MatCommaInitializer_(Mat_<_Tp>* _m) + : it(_m) +{} + +template template inline +MatCommaInitializer_<_Tp>& MatCommaInitializer_<_Tp>::operator , (T2 v) +{ + CV_DbgAssert( this->it < ((const Mat_<_Tp>*)this->it.m)->end() ); + *this->it = _Tp(v); + ++this->it; + return *this; +} + +template inline +MatCommaInitializer_<_Tp>::operator Mat_<_Tp>() const +{ + CV_DbgAssert( this->it == ((const Mat_<_Tp>*)this->it.m)->end() ); + return Mat_<_Tp>(*this->it.m); +} + + +template static inline +MatCommaInitializer_<_Tp> operator << (const Mat_<_Tp>& m, T2 val) +{ + MatCommaInitializer_<_Tp> commaInitializer((Mat_<_Tp>*)&m); + return (commaInitializer, val); +} + + + +///////////////////////// Matrix Expressions //////////////////////// + +inline +Mat& Mat::operator = (const MatExpr& e) +{ + e.op->assign(e, *this); + return *this; +} + +template inline +Mat_<_Tp>::Mat_(const MatExpr& e) +{ + e.op->assign(e, *this, traits::Type<_Tp>::value); +} + +template inline +Mat_<_Tp>& Mat_<_Tp>::operator = (const MatExpr& e) +{ + e.op->assign(e, *this, traits::Type<_Tp>::value); + return *this; +} + +template inline +MatExpr Mat_<_Tp>::zeros(int rows, int cols) +{ + return Mat::zeros(rows, cols, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::zeros(Size sz) +{ + return Mat::zeros(sz, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::ones(int rows, int cols) +{ + return Mat::ones(rows, cols, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::ones(Size sz) +{ + return Mat::ones(sz, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::eye(int rows, int cols) +{ + return Mat::eye(rows, cols, traits::Type<_Tp>::value); +} + +template inline +MatExpr Mat_<_Tp>::eye(Size sz) +{ + return Mat::eye(sz, traits::Type<_Tp>::value); +} + +inline +MatExpr::MatExpr() + : op(0), flags(0), a(Mat()), b(Mat()), c(Mat()), alpha(0), beta(0), s() +{} + +inline +MatExpr::MatExpr(const MatOp* _op, int _flags, const Mat& _a, const Mat& _b, + const Mat& _c, double _alpha, double _beta, const Scalar& _s) + : op(_op), flags(_flags), a(_a), b(_b), c(_c), alpha(_alpha), beta(_beta), s(_s) +{} + +inline +MatExpr::operator Mat() const +{ + Mat m; + op->assign(*this, m); + return m; +} + +template inline +MatExpr::operator Mat_<_Tp>() const +{ + Mat_<_Tp> m; + op->assign(*this, m, traits::Type<_Tp>::value); + return m; +} + + +template static inline +MatExpr min(const Mat_<_Tp>& a, const Mat_<_Tp>& b) +{ + return cv::min((const Mat&)a, (const Mat&)b); +} + +template static inline +MatExpr min(const Mat_<_Tp>& a, double s) +{ + return cv::min((const Mat&)a, s); +} + +template static inline +MatExpr min(double s, const Mat_<_Tp>& a) +{ + return cv::min((const Mat&)a, s); +} + +template static inline +MatExpr max(const Mat_<_Tp>& a, const Mat_<_Tp>& b) +{ + return cv::max((const Mat&)a, (const Mat&)b); +} + +template static inline +MatExpr max(const Mat_<_Tp>& a, double s) +{ + return cv::max((const Mat&)a, s); +} + +template static inline +MatExpr max(double s, const Mat_<_Tp>& a) +{ + return cv::max((const Mat&)a, s); +} + +template static inline +MatExpr abs(const Mat_<_Tp>& m) +{ + return cv::abs((const Mat&)m); +} + + +static inline +Mat& operator += (Mat& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, a); + return a; +} + +static inline +const Mat& operator += (const Mat& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator += (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator += (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignAdd(b, (Mat&)a); + return a; +} + +static inline +Mat& operator -= (Mat& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, a); + return a; +} + +static inline +const Mat& operator -= (const Mat& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator -= (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator -= (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignSubtract(b, (Mat&)a); + return a; +} + +static inline +Mat& operator *= (Mat& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, a); + return a; +} + +static inline +const Mat& operator *= (const Mat& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator *= (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator *= (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignMultiply(b, (Mat&)a); + return a; +} + +static inline +Mat& operator /= (Mat& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, a); + return a; +} + +static inline +const Mat& operator /= (const Mat& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, (Mat&)a); + return a; +} + +template static inline +Mat_<_Tp>& operator /= (Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, a); + return a; +} + +template static inline +const Mat_<_Tp>& operator /= (const Mat_<_Tp>& a, const MatExpr& b) +{ + b.op->augAssignDivide(b, (Mat&)a); + return a; +} + + +//////////////////////////////// UMat //////////////////////////////// + +template inline +UMat::UMat(const std::vector<_Tp>& vec, bool copyData) +: flags(+MAGIC_VAL + traits::Type<_Tp>::value + CV_MAT_CONT_FLAG), dims(2), rows((int)vec.size()), +cols(1), allocator(0), usageFlags(USAGE_DEFAULT), u(0), offset(0), size(&rows) +{ + if(vec.empty()) + return; + if( !copyData ) + { + // !!!TODO!!! + CV_Error(Error::StsNotImplemented, ""); + } + else + Mat((int)vec.size(), 1, traits::Type<_Tp>::value, (uchar*)&vec[0]).copyTo(*this); +} + +inline +UMat UMat::row(int y) const +{ + return UMat(*this, Range(y, y + 1), Range::all()); +} + +inline +UMat UMat::col(int x) const +{ + return UMat(*this, Range::all(), Range(x, x + 1)); +} + +inline +UMat UMat::rowRange(int startrow, int endrow) const +{ + return UMat(*this, Range(startrow, endrow), Range::all()); +} + +inline +UMat UMat::rowRange(const Range& r) const +{ + return UMat(*this, r, Range::all()); +} + +inline +UMat UMat::colRange(int startcol, int endcol) const +{ + return UMat(*this, Range::all(), Range(startcol, endcol)); +} + +inline +UMat UMat::colRange(const Range& r) const +{ + return UMat(*this, Range::all(), r); +} + +inline +UMat UMat::operator()( Range _rowRange, Range _colRange ) const +{ + return UMat(*this, _rowRange, _colRange); +} + +inline +UMat UMat::operator()( const Rect& roi ) const +{ + return UMat(*this, roi); +} + +inline +UMat UMat::operator()(const Range* ranges) const +{ + return UMat(*this, ranges); +} + +inline +UMat UMat::operator()(const std::vector& ranges) const +{ + return UMat(*this, ranges); +} + +inline +bool UMat::isContinuous() const +{ + return (flags & CONTINUOUS_FLAG) != 0; +} + +inline +bool UMat::isSubmatrix() const +{ + return (flags & SUBMATRIX_FLAG) != 0; +} + +inline +size_t UMat::elemSize() const +{ + size_t res = dims > 0 ? step.p[dims - 1] : 0; + CV_DbgAssert(res != 0); + return res; +} + +inline +size_t UMat::elemSize1() const +{ + return CV_ELEM_SIZE1(flags); +} + +inline +int UMat::type() const +{ + return CV_MAT_TYPE(flags); +} + +inline +int UMat::depth() const +{ + return CV_MAT_DEPTH(flags); +} + +inline +int UMat::channels() const +{ + return CV_MAT_CN(flags); +} + +inline +size_t UMat::step1(int i) const +{ + return step.p[i] / elemSize1(); +} + + +inline bool UMatData::hostCopyObsolete() const { return (flags & HOST_COPY_OBSOLETE) != 0; } +inline bool UMatData::deviceCopyObsolete() const { return (flags & DEVICE_COPY_OBSOLETE) != 0; } +inline bool UMatData::deviceMemMapped() const { return (flags & DEVICE_MEM_MAPPED) != 0; } +inline bool UMatData::copyOnMap() const { return (flags & COPY_ON_MAP) != 0; } +inline bool UMatData::tempUMat() const { return (flags & TEMP_UMAT) != 0; } +inline bool UMatData::tempCopiedUMat() const { return (flags & TEMP_COPIED_UMAT) == TEMP_COPIED_UMAT; } + +inline void UMatData::markDeviceMemMapped(bool flag) +{ + if(flag) + flags |= DEVICE_MEM_MAPPED; + else + flags &= ~DEVICE_MEM_MAPPED; +} + +inline void UMatData::markHostCopyObsolete(bool flag) +{ + if(flag) + flags |= HOST_COPY_OBSOLETE; + else + flags &= ~HOST_COPY_OBSOLETE; +} +inline void UMatData::markDeviceCopyObsolete(bool flag) +{ + if(flag) + flags |= DEVICE_COPY_OBSOLETE; + else + flags &= ~DEVICE_COPY_OBSOLETE; +} + +//! @endcond + +static inline +void swap(MatExpr& a, MatExpr& b) { a.swap(b); } + +} //cv + +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +#ifdef CV_DISABLE_CLANG_ENUM_WARNINGS +#undef CV_DISABLE_CLANG_ENUM_WARNINGS +#pragma clang diagnostic pop +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp index 6216035aa9..ad13797da3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/matx.hpp @@ -1,544 +1,544 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_MATX_HPP -#define OPENCV_CORE_MATX_HPP - -#ifndef __cplusplus -# error matx.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/base.hpp" -#include "opencv2/core/traits.hpp" -#include "opencv2/core/saturate.hpp" - -#include - -namespace cv -{ - -//! @addtogroup core_basic -//! @{ - -//! @cond IGNORED -// FIXIT Remove this (especially CV_EXPORTS modifier) -struct CV_EXPORTS Matx_AddOp { Matx_AddOp() {} Matx_AddOp(const Matx_AddOp&) {} }; -struct CV_EXPORTS Matx_SubOp { Matx_SubOp() {} Matx_SubOp(const Matx_SubOp&) {} }; -struct CV_EXPORTS Matx_ScaleOp { Matx_ScaleOp() {} Matx_ScaleOp(const Matx_ScaleOp&) {} }; -struct CV_EXPORTS Matx_MulOp { Matx_MulOp() {} Matx_MulOp(const Matx_MulOp&) {} }; -struct CV_EXPORTS Matx_DivOp { Matx_DivOp() {} Matx_DivOp(const Matx_DivOp&) {} }; -struct CV_EXPORTS Matx_MatMulOp { Matx_MatMulOp() {} Matx_MatMulOp(const Matx_MatMulOp&) {} }; -struct CV_EXPORTS Matx_TOp { Matx_TOp() {} Matx_TOp(const Matx_TOp&) {} }; -//! @endcond - -////////////////////////////// Small Matrix /////////////////////////// - -/** @brief Template class for small matrices whose type and size are known at compilation time - -If you need a more flexible type, use Mat . The elements of the matrix M are accessible using the -M(i,j) notation. Most of the common matrix operations (see also @ref MatrixExpressions ) are -available. To do an operation on Matx that is not implemented, you can easily convert the matrix to -Mat and backwards: -@code{.cpp} - Matx33f m(1, 2, 3, - 4, 5, 6, - 7, 8, 9); - cout << sum(Mat(m*m.t())) << endl; -@endcode -Except of the plain constructor which takes a list of elements, Matx can be initialized from a C-array: -@code{.cpp} - float values[] = { 1, 2, 3}; - Matx31f m(values); -@endcode -In case if C++11 features are available, std::initializer_list can be also used to initialize Matx: -@code{.cpp} - Matx31f m = { 1, 2, 3}; -@endcode - */ -template class Matx -{ -public: - enum { - rows = m, - cols = n, - channels = rows*cols, -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - depth = traits::Type<_Tp>::value, - type = CV_MAKETYPE(depth, channels), -#endif - shortdim = (m < n ? m : n) - }; - - typedef _Tp value_type; - typedef Matx<_Tp, m, n> mat_type; - typedef Matx<_Tp, shortdim, 1> diag_type; - - //! default constructor - Matx(); - - explicit Matx(_Tp v0); //!< 1x1 matrix - Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11, - _Tp v12, _Tp v13); //!< 1x14, 2x7, 7x2 or 14x1 matrix - Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, - _Tp v4, _Tp v5, _Tp v6, _Tp v7, - _Tp v8, _Tp v9, _Tp v10, _Tp v11, - _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix - explicit Matx(const _Tp* vals); //!< initialize from a plain array - - Matx(std::initializer_list<_Tp>); //!< initialize from an initializer list - - CV_NODISCARD_STD static Matx all(_Tp alpha); - CV_NODISCARD_STD static Matx zeros(); - CV_NODISCARD_STD static Matx ones(); - CV_NODISCARD_STD static Matx eye(); - CV_NODISCARD_STD static Matx diag(const diag_type& d); - /** @brief Generates uniformly distributed random numbers - @param a Range boundary. - @param b The other range boundary (boundaries don't have to be ordered, the lower boundary is inclusive, - the upper one is exclusive). - */ - CV_NODISCARD_STD static Matx randu(_Tp a, _Tp b); - /** @brief Generates normally distributed random numbers - @param a Mean value. - @param b Standard deviation. - */ - CV_NODISCARD_STD static Matx randn(_Tp a, _Tp b); - - //! dot product computed with the default precision - _Tp dot(const Matx<_Tp, m, n>& v) const; - - //! dot product computed in double-precision arithmetics - double ddot(const Matx<_Tp, m, n>& v) const; - - //! conversion to another data type - template operator Matx() const; - - //! change the matrix shape - template Matx<_Tp, m1, n1> reshape() const; - - //! extract part of the matrix - template Matx<_Tp, m1, n1> get_minor(int base_row, int base_col) const; - - //! extract the matrix row - Matx<_Tp, 1, n> row(int i) const; - - //! extract the matrix column - Matx<_Tp, m, 1> col(int i) const; - - //! extract the matrix diagonal - diag_type diag() const; - - //! transpose the matrix - Matx<_Tp, n, m> t() const; - - //! invert the matrix - Matx<_Tp, n, m> inv(int method=DECOMP_LU, bool *p_is_ok = NULL) const; - - //! solve linear system - template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; - Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; - - //! multiply two matrices element-wise - Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; - - //! divide two matrices element-wise - Matx<_Tp, m, n> div(const Matx<_Tp, m, n>& a) const; - - //! element access - const _Tp& operator ()(int row, int col) const; - _Tp& operator ()(int row, int col); - - //! 1D element access - const _Tp& operator ()(int i) const; - _Tp& operator ()(int i); - - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); - template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp); - Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp); - template Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp); - Matx(const Matx<_Tp, n, m>& a, Matx_TOp); - - _Tp val[m*n]; ///< matrix elements -}; - -typedef Matx Matx12f; -typedef Matx Matx12d; -typedef Matx Matx13f; -typedef Matx Matx13d; -typedef Matx Matx14f; -typedef Matx Matx14d; -typedef Matx Matx16f; -typedef Matx Matx16d; - -typedef Matx Matx21f; -typedef Matx Matx21d; -typedef Matx Matx31f; -typedef Matx Matx31d; -typedef Matx Matx41f; -typedef Matx Matx41d; -typedef Matx Matx61f; -typedef Matx Matx61d; - -typedef Matx Matx22f; -typedef Matx Matx22d; -typedef Matx Matx23f; -typedef Matx Matx23d; -typedef Matx Matx32f; -typedef Matx Matx32d; - -typedef Matx Matx33f; -typedef Matx Matx33d; - -typedef Matx Matx34f; -typedef Matx Matx34d; -typedef Matx Matx43f; -typedef Matx Matx43d; - -typedef Matx Matx44f; -typedef Matx Matx44d; -typedef Matx Matx66f; -typedef Matx Matx66d; - -template static inline -double determinant(const Matx<_Tp, m, m>& a); - -template static inline -double trace(const Matx<_Tp, m, n>& a); - -template static inline -double norm(const Matx<_Tp, m, n>& M); - -template static inline -double norm(const Matx<_Tp, m, n>& M, int normType); - -template static inline -Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); - -template static inline -Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); - -template static inline -Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha); - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha); - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha); - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a); - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b); - -template static inline -Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b); - -template static inline -bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - -template static inline -bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); - - -/////////////////////// Vec (used as element of multi-channel images ///////////////////// - -/** @brief Template class for short numerical vectors, a partial case of Matx - -This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you -can perform basic arithmetical operations, access individual elements using [] operator etc. The -vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which -elements are dynamically allocated in the heap. - -The template takes 2 parameters: -@tparam _Tp element type -@tparam cn the number of elements - -In addition to the universal notation like Vec, you can use shorter aliases -for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. - -It is possible to convert Vec\ to/from Point_, Vec\ to/from Point3_ , and Vec\ -to CvScalar or Scalar_. Use operator[] to access the elements of Vec. - -All the expected vector operations are also implemented: -- v1 = v2 + v3 -- v1 = v2 - v3 -- v1 = v2 \* scale -- v1 = scale \* v2 -- v1 = -v2 -- v1 += v2 and other augmenting operations -- v1 == v2, v1 != v2 -- norm(v1) (euclidean norm) -The Vec class is commonly used to describe pixel types of multi-channel arrays. See Mat for details. -*/ -template class Vec : public Matx<_Tp, cn, 1> -{ -public: - typedef _Tp value_type; - enum { - channels = cn, -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - depth = Matx<_Tp, cn, 1>::depth, - type = CV_MAKETYPE(depth, channels), -#endif - _dummy_enum_finalizer = 0 - }; - - //! default constructor - Vec(); - - Vec(_Tp v0); //!< 1-element vector constructor - Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor - Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 14-element vector constructor - explicit Vec(const _Tp* values); - - Vec(std::initializer_list<_Tp>); - - Vec(const Vec<_Tp, cn>& v); - - static Vec all(_Tp alpha); - static Vec ones(); - static Vec randn(_Tp a, _Tp b); - static Vec randu(_Tp a, _Tp b); - static Vec zeros(); - static Vec diag(_Tp alpha) = delete; - static Vec eye() = delete; - - //! per-element multiplication - Vec mul(const Vec<_Tp, cn>& v) const; - - //! conjugation (makes sense for complex numbers and quaternions) - Vec conj() const; - - /*! - cross product of the two 3D vectors. - - For other dimensionalities the exception is raised - */ - Vec cross(const Vec& v) const; - //! conversion to another data type - template operator Vec() const; - - /*! element access */ - const _Tp& operator [](int i) const; - _Tp& operator[](int i); - const _Tp& operator ()(int i) const; - _Tp& operator ()(int i); - - Vec<_Tp, cn>& operator=(const Vec<_Tp, cn>& rhs) = default; - - Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); - Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); - template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); -}; - -/** @name Shorter aliases for the most popular specializations of Vec - @{ -*/ -typedef Vec Vec2b; -typedef Vec Vec3b; -typedef Vec Vec4b; - -typedef Vec Vec2s; -typedef Vec Vec3s; -typedef Vec Vec4s; - -typedef Vec Vec2w; -typedef Vec Vec3w; -typedef Vec Vec4w; - -typedef Vec Vec2i; -typedef Vec Vec3i; -typedef Vec Vec4i; -typedef Vec Vec6i; -typedef Vec Vec8i; - -typedef Vec Vec2f; -typedef Vec Vec3f; -typedef Vec Vec4f; -typedef Vec Vec6f; - -typedef Vec Vec2d; -typedef Vec Vec3d; -typedef Vec Vec4d; -typedef Vec Vec6d; -/** @} */ - -template inline -Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v); - -template static inline -Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); - -template static inline -Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); - -template static inline -Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a); - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a); - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a); - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha); - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha); - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha); - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a); - -template inline -Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); - -template inline -Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); - -//! @} core_basic - -} // cv - -#include "opencv2/core/matx.inl.hpp" - -#endif // OPENCV_CORE_MATX_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_MATX_HPP +#define OPENCV_CORE_MATX_HPP + +#ifndef __cplusplus +# error matx.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/base.hpp" +#include "opencv2/core/traits.hpp" +#include "opencv2/core/saturate.hpp" + +#include + +namespace cv +{ + +//! @addtogroup core_basic +//! @{ + +//! @cond IGNORED +// FIXIT Remove this (especially CV_EXPORTS modifier) +struct CV_EXPORTS Matx_AddOp { Matx_AddOp() {} Matx_AddOp(const Matx_AddOp&) {} }; +struct CV_EXPORTS Matx_SubOp { Matx_SubOp() {} Matx_SubOp(const Matx_SubOp&) {} }; +struct CV_EXPORTS Matx_ScaleOp { Matx_ScaleOp() {} Matx_ScaleOp(const Matx_ScaleOp&) {} }; +struct CV_EXPORTS Matx_MulOp { Matx_MulOp() {} Matx_MulOp(const Matx_MulOp&) {} }; +struct CV_EXPORTS Matx_DivOp { Matx_DivOp() {} Matx_DivOp(const Matx_DivOp&) {} }; +struct CV_EXPORTS Matx_MatMulOp { Matx_MatMulOp() {} Matx_MatMulOp(const Matx_MatMulOp&) {} }; +struct CV_EXPORTS Matx_TOp { Matx_TOp() {} Matx_TOp(const Matx_TOp&) {} }; +//! @endcond + +////////////////////////////// Small Matrix /////////////////////////// + +/** @brief Template class for small matrices whose type and size are known at compilation time + +If you need a more flexible type, use Mat . The elements of the matrix M are accessible using the +M(i,j) notation. Most of the common matrix operations (see also @ref MatrixExpressions ) are +available. To do an operation on Matx that is not implemented, you can easily convert the matrix to +Mat and backwards: +@code{.cpp} + Matx33f m(1, 2, 3, + 4, 5, 6, + 7, 8, 9); + cout << sum(Mat(m*m.t())) << endl; +@endcode +Except of the plain constructor which takes a list of elements, Matx can be initialized from a C-array: +@code{.cpp} + float values[] = { 1, 2, 3}; + Matx31f m(values); +@endcode +In case if C++11 features are available, std::initializer_list can be also used to initialize Matx: +@code{.cpp} + Matx31f m = { 1, 2, 3}; +@endcode + */ +template class Matx +{ +public: + enum { + rows = m, + cols = n, + channels = rows*cols, +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + depth = traits::Type<_Tp>::value, + type = CV_MAKETYPE(depth, channels), +#endif + shortdim = (m < n ? m : n) + }; + + typedef _Tp value_type; + typedef Matx<_Tp, m, n> mat_type; + typedef Matx<_Tp, shortdim, 1> diag_type; + + //! default constructor + Matx(); + + explicit Matx(_Tp v0); //!< 1x1 matrix + Matx(_Tp v0, _Tp v1); //!< 1x2 or 2x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2); //!< 1x3 or 3x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 1x4, 2x2 or 4x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 1x5 or 5x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 1x6, 2x3, 3x2 or 6x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 1x7 or 7x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 1x8, 2x4, 4x2 or 8x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 1x9, 3x3 or 9x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 1x10, 2x5 or 5x2 or 10x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, + _Tp v4, _Tp v5, _Tp v6, _Tp v7, + _Tp v8, _Tp v9, _Tp v10, _Tp v11); //!< 1x12, 2x6, 3x4, 4x3, 6x2 or 12x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, + _Tp v4, _Tp v5, _Tp v6, _Tp v7, + _Tp v8, _Tp v9, _Tp v10, _Tp v11, + _Tp v12, _Tp v13); //!< 1x14, 2x7, 7x2 or 14x1 matrix + Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, + _Tp v4, _Tp v5, _Tp v6, _Tp v7, + _Tp v8, _Tp v9, _Tp v10, _Tp v11, + _Tp v12, _Tp v13, _Tp v14, _Tp v15); //!< 1x16, 4x4 or 16x1 matrix + explicit Matx(const _Tp* vals); //!< initialize from a plain array + + Matx(std::initializer_list<_Tp>); //!< initialize from an initializer list + + CV_NODISCARD_STD static Matx all(_Tp alpha); + CV_NODISCARD_STD static Matx zeros(); + CV_NODISCARD_STD static Matx ones(); + CV_NODISCARD_STD static Matx eye(); + CV_NODISCARD_STD static Matx diag(const diag_type& d); + /** @brief Generates uniformly distributed random numbers + @param a Range boundary. + @param b The other range boundary (boundaries don't have to be ordered, the lower boundary is inclusive, + the upper one is exclusive). + */ + CV_NODISCARD_STD static Matx randu(_Tp a, _Tp b); + /** @brief Generates normally distributed random numbers + @param a Mean value. + @param b Standard deviation. + */ + CV_NODISCARD_STD static Matx randn(_Tp a, _Tp b); + + //! dot product computed with the default precision + _Tp dot(const Matx<_Tp, m, n>& v) const; + + //! dot product computed in double-precision arithmetics + double ddot(const Matx<_Tp, m, n>& v) const; + + //! conversion to another data type + template operator Matx() const; + + //! change the matrix shape + template Matx<_Tp, m1, n1> reshape() const; + + //! extract part of the matrix + template Matx<_Tp, m1, n1> get_minor(int base_row, int base_col) const; + + //! extract the matrix row + Matx<_Tp, 1, n> row(int i) const; + + //! extract the matrix column + Matx<_Tp, m, 1> col(int i) const; + + //! extract the matrix diagonal + diag_type diag() const; + + //! transpose the matrix + Matx<_Tp, n, m> t() const; + + //! invert the matrix + Matx<_Tp, n, m> inv(int method=DECOMP_LU, bool *p_is_ok = NULL) const; + + //! solve linear system + template Matx<_Tp, n, l> solve(const Matx<_Tp, m, l>& rhs, int flags=DECOMP_LU) const; + Vec<_Tp, n> solve(const Vec<_Tp, m>& rhs, int method) const; + + //! multiply two matrices element-wise + Matx<_Tp, m, n> mul(const Matx<_Tp, m, n>& a) const; + + //! divide two matrices element-wise + Matx<_Tp, m, n> div(const Matx<_Tp, m, n>& a) const; + + //! element access + const _Tp& operator ()(int row, int col) const; + _Tp& operator ()(int row, int col); + + //! 1D element access + const _Tp& operator ()(int i) const; + _Tp& operator ()(int i); + + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp); + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp); + template Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp); + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp); + Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp); + template Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp); + Matx(const Matx<_Tp, n, m>& a, Matx_TOp); + + _Tp val[m*n]; ///< matrix elements +}; + +typedef Matx Matx12f; +typedef Matx Matx12d; +typedef Matx Matx13f; +typedef Matx Matx13d; +typedef Matx Matx14f; +typedef Matx Matx14d; +typedef Matx Matx16f; +typedef Matx Matx16d; + +typedef Matx Matx21f; +typedef Matx Matx21d; +typedef Matx Matx31f; +typedef Matx Matx31d; +typedef Matx Matx41f; +typedef Matx Matx41d; +typedef Matx Matx61f; +typedef Matx Matx61d; + +typedef Matx Matx22f; +typedef Matx Matx22d; +typedef Matx Matx23f; +typedef Matx Matx23d; +typedef Matx Matx32f; +typedef Matx Matx32d; + +typedef Matx Matx33f; +typedef Matx Matx33d; + +typedef Matx Matx34f; +typedef Matx Matx34d; +typedef Matx Matx43f; +typedef Matx Matx43d; + +typedef Matx Matx44f; +typedef Matx Matx44d; +typedef Matx Matx66f; +typedef Matx Matx66d; + +template static inline +double determinant(const Matx<_Tp, m, m>& a); + +template static inline +double trace(const Matx<_Tp, m, n>& a); + +template static inline +double norm(const Matx<_Tp, m, n>& M); + +template static inline +double norm(const Matx<_Tp, m, n>& M, int normType); + +template static inline +Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); + +template static inline +Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b); + +template static inline +Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha); + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha); + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha); + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a); + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b); + +template static inline +Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b); + +template static inline +bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + +template static inline +bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b); + + +/////////////////////// Vec (used as element of multi-channel images ///////////////////// + +/** @brief Template class for short numerical vectors, a partial case of Matx + +This template class represents short numerical vectors (of 1, 2, 3, 4 ... elements) on which you +can perform basic arithmetical operations, access individual elements using [] operator etc. The +vectors are allocated on stack, as opposite to std::valarray, std::vector, cv::Mat etc., which +elements are dynamically allocated in the heap. + +The template takes 2 parameters: +@tparam _Tp element type +@tparam cn the number of elements + +In addition to the universal notation like Vec, you can use shorter aliases +for the most popular specialized variants of Vec, e.g. Vec3f ~ Vec. + +It is possible to convert Vec\ to/from Point_, Vec\ to/from Point3_ , and Vec\ +to CvScalar or Scalar_. Use operator[] to access the elements of Vec. + +All the expected vector operations are also implemented: +- v1 = v2 + v3 +- v1 = v2 - v3 +- v1 = v2 \* scale +- v1 = scale \* v2 +- v1 = -v2 +- v1 += v2 and other augmenting operations +- v1 == v2, v1 != v2 +- norm(v1) (euclidean norm) +The Vec class is commonly used to describe pixel types of multi-channel arrays. See Mat for details. +*/ +template class Vec : public Matx<_Tp, cn, 1> +{ +public: + typedef _Tp value_type; + enum { + channels = cn, +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + depth = Matx<_Tp, cn, 1>::depth, + type = CV_MAKETYPE(depth, channels), +#endif + _dummy_enum_finalizer = 0 + }; + + //! default constructor + Vec(); + + Vec(_Tp v0); //!< 1-element vector constructor + Vec(_Tp v0, _Tp v1); //!< 2-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2); //!< 3-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3); //!< 4-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4); //!< 5-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5); //!< 6-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6); //!< 7-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7); //!< 8-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8); //!< 9-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9); //!< 10-element vector constructor + Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13); //!< 14-element vector constructor + explicit Vec(const _Tp* values); + + Vec(std::initializer_list<_Tp>); + + Vec(const Vec<_Tp, cn>& v); + + static Vec all(_Tp alpha); + static Vec ones(); + static Vec randn(_Tp a, _Tp b); + static Vec randu(_Tp a, _Tp b); + static Vec zeros(); + static Vec diag(_Tp alpha) = delete; + static Vec eye() = delete; + + //! per-element multiplication + Vec mul(const Vec<_Tp, cn>& v) const; + + //! conjugation (makes sense for complex numbers and quaternions) + Vec conj() const; + + /*! + cross product of the two 3D vectors. + + For other dimensionalities the exception is raised + */ + Vec cross(const Vec& v) const; + //! conversion to another data type + template operator Vec() const; + + /*! element access */ + const _Tp& operator [](int i) const; + _Tp& operator[](int i); + const _Tp& operator ()(int i) const; + _Tp& operator ()(int i); + + Vec<_Tp, cn>& operator=(const Vec<_Tp, cn>& rhs) = default; + + Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp); + Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp); + template Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp); +}; + +/** @name Shorter aliases for the most popular specializations of Vec + @{ +*/ +typedef Vec Vec2b; +typedef Vec Vec3b; +typedef Vec Vec4b; + +typedef Vec Vec2s; +typedef Vec Vec3s; +typedef Vec Vec4s; + +typedef Vec Vec2w; +typedef Vec Vec3w; +typedef Vec Vec4w; + +typedef Vec Vec2i; +typedef Vec Vec3i; +typedef Vec Vec4i; +typedef Vec Vec6i; +typedef Vec Vec8i; + +typedef Vec Vec2f; +typedef Vec Vec3f; +typedef Vec Vec4f; +typedef Vec Vec6f; + +typedef Vec Vec2d; +typedef Vec Vec3d; +typedef Vec Vec4d; +typedef Vec Vec6d; +/** @} */ + +template inline +Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v); + +template static inline +Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); + +template static inline +Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b); + +template static inline +Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b); + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a); + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a); + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a); + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha); + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha); + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha); + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a); + +template inline +Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); + +template inline +Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2); + +//! @} core_basic + +} // cv + +#include "opencv2/core/matx.inl.hpp" + +#endif // OPENCV_CORE_MATX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp index 8b5b28087d..faa3e749d6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/matx.inl.hpp @@ -1,1115 +1,1115 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_MATX_INL_HPP -#define OPENCV_CORE_MATX_INL_HPP - -#ifndef __cplusplus -# error matx.inl.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/matx.hpp" - -namespace cv -{ - -//============================================================================== -// Helpers - -namespace internal -{ - -template struct Matx_DetOp -{ - double operator ()(const Matx<_Tp, m, m>& a) const - { - Matx<_Tp, m, m> temp = a; - double p = LU(temp.val, m*sizeof(_Tp), m, 0, 0, 0); - if( p == 0 ) - return p; - for( int i = 0; i < m; i++ ) - p *= temp(i, i); - return p; - } -}; - -template struct Matx_DetOp<_Tp, 1> -{ - double operator ()(const Matx<_Tp, 1, 1>& a) const - { - return a(0,0); - } -}; - -template struct Matx_DetOp<_Tp, 2> -{ - double operator ()(const Matx<_Tp, 2, 2>& a) const - { - return a(0,0)*a(1,1) - a(0,1)*a(1,0); - } -}; - -template struct Matx_DetOp<_Tp, 3> -{ - double operator ()(const Matx<_Tp, 3, 3>& a) const - { - return a(0,0)*(a(1,1)*a(2,2) - a(2,1)*a(1,2)) - - a(0,1)*(a(1,0)*a(2,2) - a(2,0)*a(1,2)) + - a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); - } -}; - -template Vec<_Tp, 2> inline conjugate(const Vec<_Tp, 2>& v) -{ - return Vec<_Tp, 2>(v[0], -v[1]); -} - -template Vec<_Tp, 4> inline conjugate(const Vec<_Tp, 4>& v) -{ - return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); -} - -} // internal:: - - -//============================================================================== -// Matx - -template class DataType< Matx<_Tp, m, n> > -{ -public: - typedef Matx<_Tp, m, n> value_type; - typedef Matx::work_type, m, n> work_type; - typedef _Tp channel_type; - typedef value_type vec_type; - - enum { generic_type = 0, - channels = m * n, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; -}; - - -namespace traits { -template -struct Depth< Matx<_Tp, m, n> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Matx<_Tp, m, n> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, n*m) }; }; -} // namespace - - -//! @brief Comma-separated Matrix Initializer -template class MatxCommaInitializer -{ -public: - MatxCommaInitializer(Matx<_Tp, m, n>* _mtx); - template MatxCommaInitializer<_Tp, m, n>& operator , (T2 val); - Matx<_Tp, m, n> operator *() const; - - Matx<_Tp, m, n>* dst; - int idx; -}; - -template static inline -MatxCommaInitializer<_Tp, m, n> operator << (const Matx<_Tp, m, n>& mtx, _T2 val) -{ - MatxCommaInitializer<_Tp, m, n> commaInitializer((Matx<_Tp, m, n>*)&mtx); - return (commaInitializer, val); -} - -template inline -MatxCommaInitializer<_Tp, m, n>::MatxCommaInitializer(Matx<_Tp, m, n>* _mtx) - : dst(_mtx), idx(0) -{} - -template template inline -MatxCommaInitializer<_Tp, m, n>& MatxCommaInitializer<_Tp, m, n>::operator , (_T2 value) -{ - CV_DbgAssert( idx < m*n ); - dst->val[idx++] = saturate_cast<_Tp>(value); - return *this; -} - -template inline -Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const -{ - CV_DbgAssert( idx == n*m ); - return *dst; -} - -////////////////////////////////// Matx Implementation /////////////////////////////////// - -template inline -Matx<_Tp, m, n>::Matx() -{ - for(int i = 0; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0) -{ - val[0] = v0; - for(int i = 1; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1) -{ - CV_StaticAssert(channels >= 2, "Matx should have at least 2 elements."); - val[0] = v0; val[1] = v1; - for(int i = 2; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2) -{ - CV_StaticAssert(channels >= 3, "Matx should have at least 3 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; - for(int i = 3; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3) -{ - CV_StaticAssert(channels >= 4, "Matx should have at least 4 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - for(int i = 4; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) -{ - CV_StaticAssert(channels >= 5, "Matx should have at least 5 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; - for(int i = 5; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) -{ - CV_StaticAssert(channels >= 6, "Matx should have at least 6 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; - for(int i = 6; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) -{ - CV_StaticAssert(channels >= 7, "Matx should have at least 7 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; - for(int i = 7; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) -{ - CV_StaticAssert(channels >= 8, "Matx should have at least 8 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - for(int i = 8; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) -{ - CV_StaticAssert(channels >= 9, "Matx should have at least 9 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; - for(int i = 9; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) -{ - CV_StaticAssert(channels >= 10, "Matx should have at least 10 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; - for(int i = 10; i < channels; i++) val[i] = _Tp(0); -} - - -template inline -Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11) -{ - CV_StaticAssert(channels >= 12, "Matx should have at least 12 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - for(int i = 12; i < channels; i++) val[i] = _Tp(0); -} - -template inline -Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) -{ - CV_StaticAssert(channels >= 14, "Matx should have at least 14 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - val[12] = v12; val[13] = v13; - for (int i = 14; i < channels; i++) val[i] = _Tp(0); -} - - -template inline -Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15) -{ - CV_StaticAssert(channels >= 16, "Matx should have at least 16 elements."); - val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; - val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; - val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; - val[12] = v12; val[13] = v13; val[14] = v14; val[15] = v15; - for(int i = 16; i < channels; i++) val[i] = _Tp(0); -} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -template inline -Matx<_Tp, m, n>::Matx(const _Tp* values) -{ - for( int i = 0; i < channels; i++ ) val[i] = values[i]; -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -template inline -Matx<_Tp, m, n>::Matx(std::initializer_list<_Tp> list) -{ - CV_DbgAssert(list.size() == channels); - int i = 0; - for(const auto& elem : list) - { - val[i++] = elem; - } -} - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha) -{ - Matx<_Tp, m, n> M; - for( int i = 0; i < m*n; i++ ) M.val[i] = alpha; - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::zeros() -{ - return all(0); -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::ones() -{ - return all(1); -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::eye() -{ - Matx<_Tp,m,n> M; - for(int i = 0; i < shortdim; i++) - M(i,i) = 1; - return M; -} - -template inline -_Tp Matx<_Tp, m, n>::dot(const Matx<_Tp, m, n>& M) const -{ - _Tp s = 0; - for( int i = 0; i < channels; i++ ) s += val[i]*M.val[i]; - return s; -} - -template inline -double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const -{ - double s = 0; - for( int i = 0; i < channels; i++ ) s += (double)val[i]*M.val[i]; - return s; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) -{ - Matx<_Tp,m,n> M; - for(int i = 0; i < shortdim; i++) - M(i,i) = d(i, 0); - return M; -} - -template template -inline Matx<_Tp, m, n>::operator Matx() const -{ - Matx M; - for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); - return M; -} - -template template inline -Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const -{ - CV_StaticAssert(m1*n1 == m*n, "Input and destination matrices must have the same number of elements"); - return (const Matx<_Tp, m1, n1>&)*this; -} - -template -template inline -Matx<_Tp, m1, n1> Matx<_Tp, m, n>::get_minor(int base_row, int base_col) const -{ - CV_DbgAssert(0 <= base_row && base_row+m1 <= m && 0 <= base_col && base_col+n1 <= n); - Matx<_Tp, m1, n1> s; - for( int di = 0; di < m1; di++ ) - for( int dj = 0; dj < n1; dj++ ) - s(di, dj) = (*this)(base_row+di, base_col+dj); - return s; -} - -template inline -Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const -{ - CV_DbgAssert((unsigned)i < (unsigned)m); - return Matx<_Tp, 1, n>(&val[i*n]); -} - -template inline -Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const -{ - CV_DbgAssert((unsigned)j < (unsigned)n); - Matx<_Tp, m, 1> v; - for( int i = 0; i < m; i++ ) - v.val[i] = val[i*n + j]; - return v; -} - -template inline -typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const -{ - diag_type d; - for( int i = 0; i < shortdim; i++ ) - d.val[i] = val[i*n + i]; - return d; -} - -template inline -const _Tp& Matx<_Tp, m, n>::operator()(int row_idx, int col_idx) const -{ - CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); - return this->val[row_idx*n + col_idx]; -} - -template inline -_Tp& Matx<_Tp, m, n>::operator ()(int row_idx, int col_idx) -{ - CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); - return val[row_idx*n + col_idx]; -} - -template inline -const _Tp& Matx<_Tp, m, n>::operator ()(int i) const -{ - CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); - CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); - return val[i]; -} - -template inline -_Tp& Matx<_Tp, m, n>::operator ()(int i) -{ - CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); - CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); - return val[i]; -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); -} - -template template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] * alpha); -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp) -{ - for( int i = 0; i < channels; i++ ) - val[i] = saturate_cast<_Tp>(a.val[i] / b.val[i]); -} - -template template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) -{ - for( int i = 0; i < m; i++ ) - for( int j = 0; j < n; j++ ) - { - _Tp s = 0; - for( int k = 0; k < l; k++ ) - s += a(i, k) * b(k, j); - val[i*n + j] = s; - } -} - -template inline -Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) -{ - for( int i = 0; i < m; i++ ) - for( int j = 0; j < n; j++ ) - val[i*n + j] = a(j, i); -} - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const -{ - return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); -} - -template inline -Matx<_Tp, m, n> Matx<_Tp, m, n>::div(const Matx<_Tp, m, n>& a) const -{ - return Matx<_Tp, m, n>(*this, a, Matx_DivOp()); -} - -template inline -Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const -{ - return Matx<_Tp, n, m>(*this, Matx_TOp()); -} - -template inline -Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const -{ - Matx<_Tp, n, 1> x = solve((const Matx<_Tp, m, 1>&)(rhs), method); - return (Vec<_Tp, n>&)(x); -} - -template static inline -double determinant(const Matx<_Tp, m, m>& a) -{ - return cv::internal::Matx_DetOp<_Tp, m>()(a); -} - -template static inline -double trace(const Matx<_Tp, m, n>& a) -{ - _Tp s = 0; - for( int i = 0; i < std::min(m, n); i++ ) - s += a(i,i); - return s; -} - -template static inline -double norm(const Matx<_Tp, m, n>& M) -{ - return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); -} - -template static inline -double norm(const Matx<_Tp, m, n>& M, int normType) -{ - switch(normType) { - case NORM_INF: - return (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); - case NORM_L1: - return (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); - case NORM_L2SQR: - return (double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); - default: - case NORM_L2: - return std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); - } -} - -template static inline -Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); - return a; -} - -template static inline -Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); - return a; -} - -template static inline -Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_AddOp()); -} - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_SubOp()); -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); - return a; -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = a.val[i] / alpha; - return a; -} - -template static inline -Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha) -{ - for( int i = 0; i < m*n; i++ ) - a.val[i] = a.val[i] / alpha; - return a; -} - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha) -{ - return Matx<_Tp, m, n>(a, 1.f/alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha) -{ - return Matx<_Tp, m, n>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) -{ - return Matx<_Tp, m, n>(a, -1, Matx_ScaleOp()); -} - -template static inline -Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) -{ - return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); -} - -template static inline -Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) -{ - Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); - return (const Vec<_Tp, m>&)(c); -} - -template static inline -bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - for( int i = 0; i < m*n; i++ ) - if( a.val[i] != b.val[i] ) return false; - return true; -} - -template static inline -bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) -{ - return !(a == b); -} - -//============================================================================== -// Vec - -template class DataType< Vec<_Tp, cn> > -{ -public: - typedef Vec<_Tp, cn> value_type; - typedef Vec::work_type, cn> work_type; - typedef _Tp channel_type; - typedef value_type vec_type; - - enum { generic_type = 0, - channels = cn, - fmt = DataType::fmt + ((channels - 1) << 8), -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - depth = DataType::depth, - type = CV_MAKETYPE(depth, channels), -#endif - _dummy_enum_finalizer = 0 - }; -}; - -namespace traits { -template -struct Depth< Vec<_Tp, cn> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Vec<_Tp, cn> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, cn) }; }; -} // namespace - -/** @brief Comma-separated Vec Initializer -*/ -template class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1> -{ -public: - VecCommaInitializer(Vec<_Tp, m>* _vec); - template VecCommaInitializer<_Tp, m>& operator , (T2 val); - Vec<_Tp, m> operator *() const; -}; - -template static inline -VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) -{ - VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); - return (commaInitializer, val); -} - -template inline -VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) - : MatxCommaInitializer<_Tp, cn, 1>(_vec) -{} - -template template inline -VecCommaInitializer<_Tp, cn>& VecCommaInitializer<_Tp, cn>::operator , (_T2 value) -{ - CV_DbgAssert( this->idx < cn ); - this->dst->val[this->idx++] = saturate_cast<_Tp>(value); - return *this; -} - -template inline -Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const -{ - CV_DbgAssert( this->idx == cn ); - return *this->dst; -} - - -template inline -Vec<_Tp, cn>::Vec() {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0) - : Matx<_Tp, cn, 1>(v0) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1) - : Matx<_Tp, cn, 1>(v0, v1) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2) - : Matx<_Tp, cn, 1>(v0, v1, v2) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {} - -template inline -Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) - : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) {} - -template inline -Vec<_Tp, cn>::Vec(const _Tp* values) - : Matx<_Tp, cn, 1>(values) {} - -template inline -Vec<_Tp, cn>::Vec(std::initializer_list<_Tp> list) - : Matx<_Tp, cn, 1>(list) {} - -template inline -Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) - : Matx<_Tp, cn, 1>(m.val) {} - -template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp op) - : Matx<_Tp, cn, 1>(a, b, op) {} - -template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp op) - : Matx<_Tp, cn, 1>(a, b, op) {} - -template template inline -Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) - : Matx<_Tp, cn, 1>(a, alpha, op) {} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) -{ - Vec v; - for( int i = 0; i < cn; i++ ) v.val[i] = alpha; - return v; -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::ones() -{ - return Vec::all(1); -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::zeros() -{ - return Vec::all(0); -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::mul(const Vec<_Tp, cn>& v) const -{ - Vec<_Tp, cn> w; - for( int i = 0; i < cn; i++ ) w.val[i] = saturate_cast<_Tp>(this->val[i]*v.val[i]); - return w; -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template<> inline -Vec Vec::conj() const -{ - return cv::internal::conjugate(*this); -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const -{ - CV_StaticAssert(cn == 3, "for arbitrary-size vector there is no cross-product defined"); - return Vec<_Tp, cn>(); -} - -template<> inline -Vec Vec::cross(const Vec& v) const -{ - return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], - this->val[2]*v.val[0] - this->val[0]*v.val[2], - this->val[0]*v.val[1] - this->val[1]*v.val[0]); -} - -template<> inline -Vec Vec::cross(const Vec& v) const -{ - return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], - this->val[2]*v.val[0] - this->val[0]*v.val[2], - this->val[0]*v.val[1] - this->val[1]*v.val[0]); -} - -template template inline -Vec<_Tp, cn>::operator Vec() const -{ - Vec v; - for( int i = 0; i < cn; i++ ) v.val[i] = saturate_cast(this->val[i]); - return v; -} - -template inline -const _Tp& Vec<_Tp, cn>::operator [](int i) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -_Tp& Vec<_Tp, cn>::operator [](int i) -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -const _Tp& Vec<_Tp, cn>::operator ()(int i) const -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -_Tp& Vec<_Tp, cn>::operator ()(int i) -{ - CV_DbgAssert( (unsigned)i < (unsigned)cn ); - return this->val[i]; -} - -template inline -Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v) -{ - double nv = norm(v); - return v * (nv ? 1./nv : 0.); -} - -template static inline -Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) -{ - for( int i = 0; i < cn; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); - return a; -} - -template static inline -Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) -{ - for( int i = 0; i < cn; i++ ) - a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); - return a; -} - -template static inline -Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) -{ - return Vec<_Tp, cn>(a, b, Matx_AddOp()); -} - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) -{ - return Vec<_Tp, cn>(a, b, Matx_SubOp()); -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) -{ - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*alpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) -{ - double ialpha = 1./alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) -{ - float ialpha = 1.f/alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) -{ - double ialpha = 1./alpha; - for( int i = 0; i < cn; i++ ) - a[i] = saturate_cast<_Tp>(a[i]*ialpha); - return a; -} - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a) -{ - return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha) -{ - return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha) -{ - return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha) -{ - return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); -} - -template static inline -Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a) -{ - Vec<_Tp,cn> t; - for( int i = 0; i < cn; i++ ) t.val[i] = saturate_cast<_Tp>(-a.val[i]); - return t; -} - -template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) -{ - return Vec<_Tp, 4>(saturate_cast<_Tp>(v1[0]*v2[0] - v1[1]*v2[1] - v1[2]*v2[2] - v1[3]*v2[3]), - saturate_cast<_Tp>(v1[0]*v2[1] + v1[1]*v2[0] + v1[2]*v2[3] - v1[3]*v2[2]), - saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), - saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); -} - -template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) -{ - v1 = v1 * v2; - return v1; -} - -} // cv:: - -#endif // OPENCV_CORE_MATX_INL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_MATX_INL_HPP +#define OPENCV_CORE_MATX_INL_HPP + +#ifndef __cplusplus +# error matx.inl.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/matx.hpp" + +namespace cv +{ + +//============================================================================== +// Helpers + +namespace internal +{ + +template struct Matx_DetOp +{ + double operator ()(const Matx<_Tp, m, m>& a) const + { + Matx<_Tp, m, m> temp = a; + double p = LU(temp.val, m*sizeof(_Tp), m, 0, 0, 0); + if( p == 0 ) + return p; + for( int i = 0; i < m; i++ ) + p *= temp(i, i); + return p; + } +}; + +template struct Matx_DetOp<_Tp, 1> +{ + double operator ()(const Matx<_Tp, 1, 1>& a) const + { + return a(0,0); + } +}; + +template struct Matx_DetOp<_Tp, 2> +{ + double operator ()(const Matx<_Tp, 2, 2>& a) const + { + return a(0,0)*a(1,1) - a(0,1)*a(1,0); + } +}; + +template struct Matx_DetOp<_Tp, 3> +{ + double operator ()(const Matx<_Tp, 3, 3>& a) const + { + return a(0,0)*(a(1,1)*a(2,2) - a(2,1)*a(1,2)) - + a(0,1)*(a(1,0)*a(2,2) - a(2,0)*a(1,2)) + + a(0,2)*(a(1,0)*a(2,1) - a(2,0)*a(1,1)); + } +}; + +template Vec<_Tp, 2> inline conjugate(const Vec<_Tp, 2>& v) +{ + return Vec<_Tp, 2>(v[0], -v[1]); +} + +template Vec<_Tp, 4> inline conjugate(const Vec<_Tp, 4>& v) +{ + return Vec<_Tp, 4>(v[0], -v[1], -v[2], -v[3]); +} + +} // internal:: + + +//============================================================================== +// Matx + +template class DataType< Matx<_Tp, m, n> > +{ +public: + typedef Matx<_Tp, m, n> value_type; + typedef Matx::work_type, m, n> work_type; + typedef _Tp channel_type; + typedef value_type vec_type; + + enum { generic_type = 0, + channels = m * n, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; +}; + + +namespace traits { +template +struct Depth< Matx<_Tp, m, n> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Matx<_Tp, m, n> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, n*m) }; }; +} // namespace + + +//! @brief Comma-separated Matrix Initializer +template class MatxCommaInitializer +{ +public: + MatxCommaInitializer(Matx<_Tp, m, n>* _mtx); + template MatxCommaInitializer<_Tp, m, n>& operator , (T2 val); + Matx<_Tp, m, n> operator *() const; + + Matx<_Tp, m, n>* dst; + int idx; +}; + +template static inline +MatxCommaInitializer<_Tp, m, n> operator << (const Matx<_Tp, m, n>& mtx, _T2 val) +{ + MatxCommaInitializer<_Tp, m, n> commaInitializer((Matx<_Tp, m, n>*)&mtx); + return (commaInitializer, val); +} + +template inline +MatxCommaInitializer<_Tp, m, n>::MatxCommaInitializer(Matx<_Tp, m, n>* _mtx) + : dst(_mtx), idx(0) +{} + +template template inline +MatxCommaInitializer<_Tp, m, n>& MatxCommaInitializer<_Tp, m, n>::operator , (_T2 value) +{ + CV_DbgAssert( idx < m*n ); + dst->val[idx++] = saturate_cast<_Tp>(value); + return *this; +} + +template inline +Matx<_Tp, m, n> MatxCommaInitializer<_Tp, m, n>::operator *() const +{ + CV_DbgAssert( idx == n*m ); + return *dst; +} + +////////////////////////////////// Matx Implementation /////////////////////////////////// + +template inline +Matx<_Tp, m, n>::Matx() +{ + for(int i = 0; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0) +{ + val[0] = v0; + for(int i = 1; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1) +{ + CV_StaticAssert(channels >= 2, "Matx should have at least 2 elements."); + val[0] = v0; val[1] = v1; + for(int i = 2; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2) +{ + CV_StaticAssert(channels >= 3, "Matx should have at least 3 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; + for(int i = 3; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3) +{ + CV_StaticAssert(channels >= 4, "Matx should have at least 4 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + for(int i = 4; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) +{ + CV_StaticAssert(channels >= 5, "Matx should have at least 5 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; val[4] = v4; + for(int i = 5; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) +{ + CV_StaticAssert(channels >= 6, "Matx should have at least 6 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; + for(int i = 6; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) +{ + CV_StaticAssert(channels >= 7, "Matx should have at least 7 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; + for(int i = 7; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) +{ + CV_StaticAssert(channels >= 8, "Matx should have at least 8 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + for(int i = 8; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) +{ + CV_StaticAssert(channels >= 9, "Matx should have at least 9 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; + for(int i = 9; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp, m, n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) +{ + CV_StaticAssert(channels >= 10, "Matx should have at least 10 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; + for(int i = 10; i < channels; i++) val[i] = _Tp(0); +} + + +template inline +Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11) +{ + CV_StaticAssert(channels >= 12, "Matx should have at least 12 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; + for(int i = 12; i < channels; i++) val[i] = _Tp(0); +} + +template inline +Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) +{ + CV_StaticAssert(channels >= 14, "Matx should have at least 14 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; + val[12] = v12; val[13] = v13; + for (int i = 14; i < channels; i++) val[i] = _Tp(0); +} + + +template inline +Matx<_Tp,m,n>::Matx(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13, _Tp v14, _Tp v15) +{ + CV_StaticAssert(channels >= 16, "Matx should have at least 16 elements."); + val[0] = v0; val[1] = v1; val[2] = v2; val[3] = v3; + val[4] = v4; val[5] = v5; val[6] = v6; val[7] = v7; + val[8] = v8; val[9] = v9; val[10] = v10; val[11] = v11; + val[12] = v12; val[13] = v13; val[14] = v14; val[15] = v15; + for(int i = 16; i < channels; i++) val[i] = _Tp(0); +} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +template inline +Matx<_Tp, m, n>::Matx(const _Tp* values) +{ + for( int i = 0; i < channels; i++ ) val[i] = values[i]; +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +template inline +Matx<_Tp, m, n>::Matx(std::initializer_list<_Tp> list) +{ + CV_DbgAssert(list.size() == channels); + int i = 0; + for(const auto& elem : list) + { + val[i++] = elem; + } +} + +template inline +Matx<_Tp, m, n> Matx<_Tp, m, n>::all(_Tp alpha) +{ + Matx<_Tp, m, n> M; + for( int i = 0; i < m*n; i++ ) M.val[i] = alpha; + return M; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::zeros() +{ + return all(0); +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::ones() +{ + return all(1); +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::eye() +{ + Matx<_Tp,m,n> M; + for(int i = 0; i < shortdim; i++) + M(i,i) = 1; + return M; +} + +template inline +_Tp Matx<_Tp, m, n>::dot(const Matx<_Tp, m, n>& M) const +{ + _Tp s = 0; + for( int i = 0; i < channels; i++ ) s += val[i]*M.val[i]; + return s; +} + +template inline +double Matx<_Tp, m, n>::ddot(const Matx<_Tp, m, n>& M) const +{ + double s = 0; + for( int i = 0; i < channels; i++ ) s += (double)val[i]*M.val[i]; + return s; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::diag(const typename Matx<_Tp,m,n>::diag_type& d) +{ + Matx<_Tp,m,n> M; + for(int i = 0; i < shortdim; i++) + M(i,i) = d(i, 0); + return M; +} + +template template +inline Matx<_Tp, m, n>::operator Matx() const +{ + Matx M; + for( int i = 0; i < m*n; i++ ) M.val[i] = saturate_cast(val[i]); + return M; +} + +template template inline +Matx<_Tp, m1, n1> Matx<_Tp, m, n>::reshape() const +{ + CV_StaticAssert(m1*n1 == m*n, "Input and destination matrices must have the same number of elements"); + return (const Matx<_Tp, m1, n1>&)*this; +} + +template +template inline +Matx<_Tp, m1, n1> Matx<_Tp, m, n>::get_minor(int base_row, int base_col) const +{ + CV_DbgAssert(0 <= base_row && base_row+m1 <= m && 0 <= base_col && base_col+n1 <= n); + Matx<_Tp, m1, n1> s; + for( int di = 0; di < m1; di++ ) + for( int dj = 0; dj < n1; dj++ ) + s(di, dj) = (*this)(base_row+di, base_col+dj); + return s; +} + +template inline +Matx<_Tp, 1, n> Matx<_Tp, m, n>::row(int i) const +{ + CV_DbgAssert((unsigned)i < (unsigned)m); + return Matx<_Tp, 1, n>(&val[i*n]); +} + +template inline +Matx<_Tp, m, 1> Matx<_Tp, m, n>::col(int j) const +{ + CV_DbgAssert((unsigned)j < (unsigned)n); + Matx<_Tp, m, 1> v; + for( int i = 0; i < m; i++ ) + v.val[i] = val[i*n + j]; + return v; +} + +template inline +typename Matx<_Tp, m, n>::diag_type Matx<_Tp, m, n>::diag() const +{ + diag_type d; + for( int i = 0; i < shortdim; i++ ) + d.val[i] = val[i*n + i]; + return d; +} + +template inline +const _Tp& Matx<_Tp, m, n>::operator()(int row_idx, int col_idx) const +{ + CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); + return this->val[row_idx*n + col_idx]; +} + +template inline +_Tp& Matx<_Tp, m, n>::operator ()(int row_idx, int col_idx) +{ + CV_DbgAssert( (unsigned)row_idx < (unsigned)m && (unsigned)col_idx < (unsigned)n ); + return val[row_idx*n + col_idx]; +} + +template inline +const _Tp& Matx<_Tp, m, n>::operator ()(int i) const +{ + CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); + CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); + return val[i]; +} + +template inline +_Tp& Matx<_Tp, m, n>::operator ()(int i) +{ + CV_StaticAssert(m == 1 || n == 1, "Single index indexation requires matrix to be a column or a row"); + CV_DbgAssert( (unsigned)i < (unsigned)(m+n-1) ); + return val[i]; +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_AddOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] + b.val[i]); +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_SubOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] - b.val[i]); +} + +template template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, _T2 alpha, Matx_ScaleOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] * alpha); +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_MulOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] * b.val[i]); +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b, Matx_DivOp) +{ + for( int i = 0; i < channels; i++ ) + val[i] = saturate_cast<_Tp>(a.val[i] / b.val[i]); +} + +template template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b, Matx_MatMulOp) +{ + for( int i = 0; i < m; i++ ) + for( int j = 0; j < n; j++ ) + { + _Tp s = 0; + for( int k = 0; k < l; k++ ) + s += a(i, k) * b(k, j); + val[i*n + j] = s; + } +} + +template inline +Matx<_Tp,m,n>::Matx(const Matx<_Tp, n, m>& a, Matx_TOp) +{ + for( int i = 0; i < m; i++ ) + for( int j = 0; j < n; j++ ) + val[i*n + j] = a(j, i); +} + +template inline +Matx<_Tp, m, n> Matx<_Tp, m, n>::mul(const Matx<_Tp, m, n>& a) const +{ + return Matx<_Tp, m, n>(*this, a, Matx_MulOp()); +} + +template inline +Matx<_Tp, m, n> Matx<_Tp, m, n>::div(const Matx<_Tp, m, n>& a) const +{ + return Matx<_Tp, m, n>(*this, a, Matx_DivOp()); +} + +template inline +Matx<_Tp, n, m> Matx<_Tp, m, n>::t() const +{ + return Matx<_Tp, n, m>(*this, Matx_TOp()); +} + +template inline +Vec<_Tp, n> Matx<_Tp, m, n>::solve(const Vec<_Tp, m>& rhs, int method) const +{ + Matx<_Tp, n, 1> x = solve((const Matx<_Tp, m, 1>&)(rhs), method); + return (Vec<_Tp, n>&)(x); +} + +template static inline +double determinant(const Matx<_Tp, m, m>& a) +{ + return cv::internal::Matx_DetOp<_Tp, m>()(a); +} + +template static inline +double trace(const Matx<_Tp, m, n>& a) +{ + _Tp s = 0; + for( int i = 0; i < std::min(m, n); i++ ) + s += a(i,i); + return s; +} + +template static inline +double norm(const Matx<_Tp, m, n>& M) +{ + return std::sqrt(normL2Sqr<_Tp, double>(M.val, m*n)); +} + +template static inline +double norm(const Matx<_Tp, m, n>& M, int normType) +{ + switch(normType) { + case NORM_INF: + return (double)normInf<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); + case NORM_L1: + return (double)normL1<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); + case NORM_L2SQR: + return (double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n); + default: + case NORM_L2: + return std::sqrt((double)normL2Sqr<_Tp, typename DataType<_Tp>::work_type>(M.val, m*n)); + } +} + +template static inline +Matx<_Tp1, m, n>& operator += (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); + return a; +} + +template static inline +Matx<_Tp1, m, n>& operator -= (Matx<_Tp1, m, n>& a, const Matx<_Tp2, m, n>& b) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); + return a; +} + +template static inline +Matx<_Tp, m, n> operator + (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + return Matx<_Tp, m, n>(a, b, Matx_AddOp()); +} + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + return Matx<_Tp, m, n>(a, b, Matx_SubOp()); +} + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, int alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); + return a; +} + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, float alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); + return a; +} + +template static inline +Matx<_Tp, m, n>& operator *= (Matx<_Tp, m, n>& a, double alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = saturate_cast<_Tp>(a.val[i] * alpha); + return a; +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, int alpha) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, float alpha) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, n>& a, double alpha) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (int alpha, const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (float alpha, const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (double alpha, const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, float alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = a.val[i] / alpha; + return a; +} + +template static inline +Matx<_Tp, m, n>& operator /= (Matx<_Tp, m, n>& a, double alpha) +{ + for( int i = 0; i < m*n; i++ ) + a.val[i] = a.val[i] / alpha; + return a; +} + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, float alpha) +{ + return Matx<_Tp, m, n>(a, 1.f/alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator / (const Matx<_Tp, m, n>& a, double alpha) +{ + return Matx<_Tp, m, n>(a, 1./alpha, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator - (const Matx<_Tp, m, n>& a) +{ + return Matx<_Tp, m, n>(a, -1, Matx_ScaleOp()); +} + +template static inline +Matx<_Tp, m, n> operator * (const Matx<_Tp, m, l>& a, const Matx<_Tp, l, n>& b) +{ + return Matx<_Tp, m, n>(a, b, Matx_MatMulOp()); +} + +template static inline +Vec<_Tp, m> operator * (const Matx<_Tp, m, n>& a, const Vec<_Tp, n>& b) +{ + Matx<_Tp, m, 1> c(a, b, Matx_MatMulOp()); + return (const Vec<_Tp, m>&)(c); +} + +template static inline +bool operator == (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + for( int i = 0; i < m*n; i++ ) + if( a.val[i] != b.val[i] ) return false; + return true; +} + +template static inline +bool operator != (const Matx<_Tp, m, n>& a, const Matx<_Tp, m, n>& b) +{ + return !(a == b); +} + +//============================================================================== +// Vec + +template class DataType< Vec<_Tp, cn> > +{ +public: + typedef Vec<_Tp, cn> value_type; + typedef Vec::work_type, cn> work_type; + typedef _Tp channel_type; + typedef value_type vec_type; + + enum { generic_type = 0, + channels = cn, + fmt = DataType::fmt + ((channels - 1) << 8), +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + depth = DataType::depth, + type = CV_MAKETYPE(depth, channels), +#endif + _dummy_enum_finalizer = 0 + }; +}; + +namespace traits { +template +struct Depth< Vec<_Tp, cn> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Vec<_Tp, cn> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, cn) }; }; +} // namespace + +/** @brief Comma-separated Vec Initializer +*/ +template class VecCommaInitializer : public MatxCommaInitializer<_Tp, m, 1> +{ +public: + VecCommaInitializer(Vec<_Tp, m>* _vec); + template VecCommaInitializer<_Tp, m>& operator , (T2 val); + Vec<_Tp, m> operator *() const; +}; + +template static inline +VecCommaInitializer<_Tp, cn> operator << (const Vec<_Tp, cn>& vec, _T2 val) +{ + VecCommaInitializer<_Tp, cn> commaInitializer((Vec<_Tp, cn>*)&vec); + return (commaInitializer, val); +} + +template inline +VecCommaInitializer<_Tp, cn>::VecCommaInitializer(Vec<_Tp, cn>* _vec) + : MatxCommaInitializer<_Tp, cn, 1>(_vec) +{} + +template template inline +VecCommaInitializer<_Tp, cn>& VecCommaInitializer<_Tp, cn>::operator , (_T2 value) +{ + CV_DbgAssert( this->idx < cn ); + this->dst->val[this->idx++] = saturate_cast<_Tp>(value); + return *this; +} + +template inline +Vec<_Tp, cn> VecCommaInitializer<_Tp, cn>::operator *() const +{ + CV_DbgAssert( this->idx == cn ); + return *this->dst; +} + + +template inline +Vec<_Tp, cn>::Vec() {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0) + : Matx<_Tp, cn, 1>(v0) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1) + : Matx<_Tp, cn, 1>(v0, v1) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2) + : Matx<_Tp, cn, 1>(v0, v1, v2) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9) {} + +template inline +Vec<_Tp, cn>::Vec(_Tp v0, _Tp v1, _Tp v2, _Tp v3, _Tp v4, _Tp v5, _Tp v6, _Tp v7, _Tp v8, _Tp v9, _Tp v10, _Tp v11, _Tp v12, _Tp v13) + : Matx<_Tp, cn, 1>(v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) {} + +template inline +Vec<_Tp, cn>::Vec(const _Tp* values) + : Matx<_Tp, cn, 1>(values) {} + +template inline +Vec<_Tp, cn>::Vec(std::initializer_list<_Tp> list) + : Matx<_Tp, cn, 1>(list) {} + +template inline +Vec<_Tp, cn>::Vec(const Vec<_Tp, cn>& m) + : Matx<_Tp, cn, 1>(m.val) {} + +template inline +Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_AddOp op) + : Matx<_Tp, cn, 1>(a, b, op) {} + +template inline +Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, const Matx<_Tp, cn, 1>& b, Matx_SubOp op) + : Matx<_Tp, cn, 1>(a, b, op) {} + +template template inline +Vec<_Tp, cn>::Vec(const Matx<_Tp, cn, 1>& a, _T2 alpha, Matx_ScaleOp op) + : Matx<_Tp, cn, 1>(a, alpha, op) {} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::all(_Tp alpha) +{ + Vec v; + for( int i = 0; i < cn; i++ ) v.val[i] = alpha; + return v; +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::ones() +{ + return Vec::all(1); +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::zeros() +{ + return Vec::all(0); +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::mul(const Vec<_Tp, cn>& v) const +{ + Vec<_Tp, cn> w; + for( int i = 0; i < cn; i++ ) w.val[i] = saturate_cast<_Tp>(this->val[i]*v.val[i]); + return w; +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template<> inline +Vec Vec::conj() const +{ + return cv::internal::conjugate(*this); +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::cross(const Vec<_Tp, cn>&) const +{ + CV_StaticAssert(cn == 3, "for arbitrary-size vector there is no cross-product defined"); + return Vec<_Tp, cn>(); +} + +template<> inline +Vec Vec::cross(const Vec& v) const +{ + return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], + this->val[2]*v.val[0] - this->val[0]*v.val[2], + this->val[0]*v.val[1] - this->val[1]*v.val[0]); +} + +template<> inline +Vec Vec::cross(const Vec& v) const +{ + return Vec(this->val[1]*v.val[2] - this->val[2]*v.val[1], + this->val[2]*v.val[0] - this->val[0]*v.val[2], + this->val[0]*v.val[1] - this->val[1]*v.val[0]); +} + +template template inline +Vec<_Tp, cn>::operator Vec() const +{ + Vec v; + for( int i = 0; i < cn; i++ ) v.val[i] = saturate_cast(this->val[i]); + return v; +} + +template inline +const _Tp& Vec<_Tp, cn>::operator [](int i) const +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +_Tp& Vec<_Tp, cn>::operator [](int i) +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +const _Tp& Vec<_Tp, cn>::operator ()(int i) const +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +_Tp& Vec<_Tp, cn>::operator ()(int i) +{ + CV_DbgAssert( (unsigned)i < (unsigned)cn ); + return this->val[i]; +} + +template inline +Vec<_Tp, cn> normalize(const Vec<_Tp, cn>& v) +{ + double nv = norm(v); + return v * (nv ? 1./nv : 0.); +} + +template static inline +Vec<_Tp1, cn>& operator += (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) +{ + for( int i = 0; i < cn; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] + b.val[i]); + return a; +} + +template static inline +Vec<_Tp1, cn>& operator -= (Vec<_Tp1, cn>& a, const Vec<_Tp2, cn>& b) +{ + for( int i = 0; i < cn; i++ ) + a.val[i] = saturate_cast<_Tp1>(a.val[i] - b.val[i]); + return a; +} + +template static inline +Vec<_Tp, cn> operator + (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) +{ + return Vec<_Tp, cn>(a, b, Matx_AddOp()); +} + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a, const Vec<_Tp, cn>& b) +{ + return Vec<_Tp, cn>(a, b, Matx_SubOp()); +} + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, int alpha) +{ + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*alpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, float alpha) +{ + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*alpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator *= (Vec<_Tp, cn>& a, double alpha) +{ + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*alpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, int alpha) +{ + double ialpha = 1./alpha; + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*ialpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, float alpha) +{ + float ialpha = 1.f/alpha; + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*ialpha); + return a; +} + +template static inline +Vec<_Tp, cn>& operator /= (Vec<_Tp, cn>& a, double alpha) +{ + double ialpha = 1./alpha; + for( int i = 0; i < cn; i++ ) + a[i] = saturate_cast<_Tp>(a[i]*ialpha); + return a; +} + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, int alpha) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (int alpha, const Vec<_Tp, cn>& a) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, float alpha) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (float alpha, const Vec<_Tp, cn>& a) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (const Vec<_Tp, cn>& a, double alpha) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator * (double alpha, const Vec<_Tp, cn>& a) +{ + return Vec<_Tp, cn>(a, alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, int alpha) +{ + return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, float alpha) +{ + return Vec<_Tp, cn>(a, 1.f/alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator / (const Vec<_Tp, cn>& a, double alpha) +{ + return Vec<_Tp, cn>(a, 1./alpha, Matx_ScaleOp()); +} + +template static inline +Vec<_Tp, cn> operator - (const Vec<_Tp, cn>& a) +{ + Vec<_Tp,cn> t; + for( int i = 0; i < cn; i++ ) t.val[i] = saturate_cast<_Tp>(-a.val[i]); + return t; +} + +template inline Vec<_Tp, 4> operator * (const Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) +{ + return Vec<_Tp, 4>(saturate_cast<_Tp>(v1[0]*v2[0] - v1[1]*v2[1] - v1[2]*v2[2] - v1[3]*v2[3]), + saturate_cast<_Tp>(v1[0]*v2[1] + v1[1]*v2[0] + v1[2]*v2[3] - v1[3]*v2[2]), + saturate_cast<_Tp>(v1[0]*v2[2] - v1[1]*v2[3] + v1[2]*v2[0] + v1[3]*v2[1]), + saturate_cast<_Tp>(v1[0]*v2[3] + v1[1]*v2[2] - v1[2]*v2[1] + v1[3]*v2[0])); +} + +template inline Vec<_Tp, 4>& operator *= (Vec<_Tp, 4>& v1, const Vec<_Tp, 4>& v2) +{ + v1 = v1 * v2; + return v1; +} + +} // cv:: + +#endif // OPENCV_CORE_MATX_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp index 7109006e19..573ba99ec3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/neon_utils.hpp @@ -1,128 +1,128 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HAL_NEON_UTILS_HPP -#define OPENCV_HAL_NEON_UTILS_HPP - -#include "opencv2/core/cvdef.h" - -//! @addtogroup core_utils_neon -//! @{ - -#if CV_NEON - -inline int32x2_t cv_vrnd_s32_f32(float32x2_t v) -{ - static int32x2_t v_sign = vdup_n_s32(1 << 31), - v_05 = vreinterpret_s32_f32(vdup_n_f32(0.5f)); - - int32x2_t v_addition = vorr_s32(v_05, vand_s32(v_sign, vreinterpret_s32_f32(v))); - return vcvt_s32_f32(vadd_f32(v, vreinterpret_f32_s32(v_addition))); -} - -inline int32x4_t cv_vrndq_s32_f32(float32x4_t v) -{ - static int32x4_t v_sign = vdupq_n_s32(1 << 31), - v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f)); - - int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(v))); - return vcvtq_s32_f32(vaddq_f32(v, vreinterpretq_f32_s32(v_addition))); -} - -inline uint32x2_t cv_vrnd_u32_f32(float32x2_t v) -{ - static float32x2_t v_05 = vdup_n_f32(0.5f); - return vcvt_u32_f32(vadd_f32(v, v_05)); -} - -inline uint32x4_t cv_vrndq_u32_f32(float32x4_t v) -{ - static float32x4_t v_05 = vdupq_n_f32(0.5f); - return vcvtq_u32_f32(vaddq_f32(v, v_05)); -} - -inline float32x4_t cv_vrecpq_f32(float32x4_t val) -{ - float32x4_t reciprocal = vrecpeq_f32(val); - reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); - reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); - return reciprocal; -} - -inline float32x2_t cv_vrecp_f32(float32x2_t val) -{ - float32x2_t reciprocal = vrecpe_f32(val); - reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); - reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); - return reciprocal; -} - -inline float32x4_t cv_vrsqrtq_f32(float32x4_t val) -{ - float32x4_t e = vrsqrteq_f32(val); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); - e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); - return e; -} - -inline float32x2_t cv_vrsqrt_f32(float32x2_t val) -{ - float32x2_t e = vrsqrte_f32(val); - e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); - e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); - return e; -} - -inline float32x4_t cv_vsqrtq_f32(float32x4_t val) -{ - return cv_vrecpq_f32(cv_vrsqrtq_f32(val)); -} - -inline float32x2_t cv_vsqrt_f32(float32x2_t val) -{ - return cv_vrecp_f32(cv_vrsqrt_f32(val)); -} - -#endif - -//! @} - -#endif // OPENCV_HAL_NEON_UTILS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HAL_NEON_UTILS_HPP +#define OPENCV_HAL_NEON_UTILS_HPP + +#include "opencv2/core/cvdef.h" + +//! @addtogroup core_utils_neon +//! @{ + +#if CV_NEON + +inline int32x2_t cv_vrnd_s32_f32(float32x2_t v) +{ + static int32x2_t v_sign = vdup_n_s32(1 << 31), + v_05 = vreinterpret_s32_f32(vdup_n_f32(0.5f)); + + int32x2_t v_addition = vorr_s32(v_05, vand_s32(v_sign, vreinterpret_s32_f32(v))); + return vcvt_s32_f32(vadd_f32(v, vreinterpret_f32_s32(v_addition))); +} + +inline int32x4_t cv_vrndq_s32_f32(float32x4_t v) +{ + static int32x4_t v_sign = vdupq_n_s32(1 << 31), + v_05 = vreinterpretq_s32_f32(vdupq_n_f32(0.5f)); + + int32x4_t v_addition = vorrq_s32(v_05, vandq_s32(v_sign, vreinterpretq_s32_f32(v))); + return vcvtq_s32_f32(vaddq_f32(v, vreinterpretq_f32_s32(v_addition))); +} + +inline uint32x2_t cv_vrnd_u32_f32(float32x2_t v) +{ + static float32x2_t v_05 = vdup_n_f32(0.5f); + return vcvt_u32_f32(vadd_f32(v, v_05)); +} + +inline uint32x4_t cv_vrndq_u32_f32(float32x4_t v) +{ + static float32x4_t v_05 = vdupq_n_f32(0.5f); + return vcvtq_u32_f32(vaddq_f32(v, v_05)); +} + +inline float32x4_t cv_vrecpq_f32(float32x4_t val) +{ + float32x4_t reciprocal = vrecpeq_f32(val); + reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); + reciprocal = vmulq_f32(vrecpsq_f32(val, reciprocal), reciprocal); + return reciprocal; +} + +inline float32x2_t cv_vrecp_f32(float32x2_t val) +{ + float32x2_t reciprocal = vrecpe_f32(val); + reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); + reciprocal = vmul_f32(vrecps_f32(val, reciprocal), reciprocal); + return reciprocal; +} + +inline float32x4_t cv_vrsqrtq_f32(float32x4_t val) +{ + float32x4_t e = vrsqrteq_f32(val); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); + e = vmulq_f32(vrsqrtsq_f32(vmulq_f32(e, e), val), e); + return e; +} + +inline float32x2_t cv_vrsqrt_f32(float32x2_t val) +{ + float32x2_t e = vrsqrte_f32(val); + e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); + e = vmul_f32(vrsqrts_f32(vmul_f32(e, e), val), e); + return e; +} + +inline float32x4_t cv_vsqrtq_f32(float32x4_t val) +{ + return cv_vrecpq_f32(cv_vrsqrtq_f32(val)); +} + +inline float32x2_t cv_vsqrt_f32(float32x2_t val) +{ + return cv_vrecp_f32(cv_vrsqrt_f32(val)); +} + +#endif + +//! @} + +#endif // OPENCV_HAL_NEON_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp index ab561691d8..891fd678b7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/ocl.hpp @@ -1,923 +1,923 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_OPENCL_HPP -#define OPENCV_OPENCL_HPP - -#include "opencv2/core.hpp" -#include -#include - -namespace cv { namespace ocl { - -//! @addtogroup core_opencl -//! @{ - -CV_EXPORTS_W bool haveOpenCL(); -CV_EXPORTS_W bool useOpenCL(); -CV_EXPORTS_W bool haveAmdBlas(); -CV_EXPORTS_W bool haveAmdFft(); -CV_EXPORTS_W void setUseOpenCL(bool flag); -CV_EXPORTS_W void finish(); - -CV_EXPORTS bool haveSVM(); - -class CV_EXPORTS Context; -class CV_EXPORTS_W_SIMPLE Device; -class CV_EXPORTS Kernel; -class CV_EXPORTS Program; -class CV_EXPORTS ProgramSource; -class CV_EXPORTS Queue; -class CV_EXPORTS PlatformInfo; -class CV_EXPORTS Image2D; - -class CV_EXPORTS_W_SIMPLE Device -{ -public: - CV_WRAP Device() CV_NOEXCEPT; - explicit Device(void* d); - Device(const Device& d); - Device& operator = (const Device& d); - Device(Device&& d) CV_NOEXCEPT; - Device& operator = (Device&& d) CV_NOEXCEPT; - CV_WRAP ~Device(); - - void set(void* d); - - enum - { - TYPE_DEFAULT = (1 << 0), - TYPE_CPU = (1 << 1), - TYPE_GPU = (1 << 2), - TYPE_ACCELERATOR = (1 << 3), - TYPE_DGPU = TYPE_GPU + (1 << 16), - TYPE_IGPU = TYPE_GPU + (1 << 17), - TYPE_ALL = 0xFFFFFFFF - }; - - CV_WRAP String name() const; - CV_WRAP String extensions() const; - CV_WRAP bool isExtensionSupported(const String& extensionName) const; - CV_WRAP String version() const; - CV_WRAP String vendorName() const; - CV_WRAP String OpenCL_C_Version() const; - CV_WRAP String OpenCLVersion() const; - CV_WRAP int deviceVersionMajor() const; - CV_WRAP int deviceVersionMinor() const; - CV_WRAP String driverVersion() const; - void* ptr() const; - - CV_WRAP int type() const; - - CV_WRAP int addressBits() const; - CV_WRAP bool available() const; - CV_WRAP bool compilerAvailable() const; - CV_WRAP bool linkerAvailable() const; - - enum - { - FP_DENORM=(1 << 0), - FP_INF_NAN=(1 << 1), - FP_ROUND_TO_NEAREST=(1 << 2), - FP_ROUND_TO_ZERO=(1 << 3), - FP_ROUND_TO_INF=(1 << 4), - FP_FMA=(1 << 5), - FP_SOFT_FLOAT=(1 << 6), - FP_CORRECTLY_ROUNDED_DIVIDE_SQRT=(1 << 7) - }; - CV_WRAP int doubleFPConfig() const; - CV_WRAP int singleFPConfig() const; - CV_WRAP int halfFPConfig() const; - - /// true if 'cl_khr_fp64' extension is available - CV_WRAP bool hasFP64() const; - /// true if 'cl_khr_fp16' extension is available - CV_WRAP bool hasFP16() const; - - CV_WRAP bool endianLittle() const; - CV_WRAP bool errorCorrectionSupport() const; - - enum - { - EXEC_KERNEL=(1 << 0), - EXEC_NATIVE_KERNEL=(1 << 1) - }; - CV_WRAP int executionCapabilities() const; - - CV_WRAP size_t globalMemCacheSize() const; - - enum - { - NO_CACHE=0, - READ_ONLY_CACHE=1, - READ_WRITE_CACHE=2 - }; - CV_WRAP int globalMemCacheType() const; - CV_WRAP int globalMemCacheLineSize() const; - CV_WRAP size_t globalMemSize() const; - - CV_WRAP size_t localMemSize() const; - enum - { - NO_LOCAL_MEM=0, - LOCAL_IS_LOCAL=1, - LOCAL_IS_GLOBAL=2 - }; - CV_WRAP int localMemType() const; - CV_WRAP bool hostUnifiedMemory() const; - - CV_WRAP bool imageSupport() const; - - CV_WRAP bool imageFromBufferSupport() const; - uint imagePitchAlignment() const; - uint imageBaseAddressAlignment() const; - - /// deprecated, use isExtensionSupported() method (probably with "cl_khr_subgroups" value) - CV_WRAP bool intelSubgroupsSupport() const; - - CV_WRAP size_t image2DMaxWidth() const; - CV_WRAP size_t image2DMaxHeight() const; - - CV_WRAP size_t image3DMaxWidth() const; - CV_WRAP size_t image3DMaxHeight() const; - CV_WRAP size_t image3DMaxDepth() const; - - CV_WRAP size_t imageMaxBufferSize() const; - CV_WRAP size_t imageMaxArraySize() const; - - enum - { - UNKNOWN_VENDOR=0, - VENDOR_AMD=1, - VENDOR_INTEL=2, - VENDOR_NVIDIA=3 - }; - CV_WRAP int vendorID() const; - // FIXIT - // dev.isAMD() doesn't work for OpenCL CPU devices from AMD OpenCL platform. - // This method should use platform name instead of vendor name. - // After fix restore code in arithm.cpp: ocl_compare() - CV_WRAP inline bool isAMD() const { return vendorID() == VENDOR_AMD; } - CV_WRAP inline bool isIntel() const { return vendorID() == VENDOR_INTEL; } - CV_WRAP inline bool isNVidia() const { return vendorID() == VENDOR_NVIDIA; } - - CV_WRAP int maxClockFrequency() const; - CV_WRAP int maxComputeUnits() const; - CV_WRAP int maxConstantArgs() const; - CV_WRAP size_t maxConstantBufferSize() const; - - CV_WRAP size_t maxMemAllocSize() const; - CV_WRAP size_t maxParameterSize() const; - - CV_WRAP int maxReadImageArgs() const; - CV_WRAP int maxWriteImageArgs() const; - CV_WRAP int maxSamplers() const; - - CV_WRAP size_t maxWorkGroupSize() const; - CV_WRAP int maxWorkItemDims() const; - void maxWorkItemSizes(size_t*) const; - - CV_WRAP int memBaseAddrAlign() const; - - CV_WRAP int nativeVectorWidthChar() const; - CV_WRAP int nativeVectorWidthShort() const; - CV_WRAP int nativeVectorWidthInt() const; - CV_WRAP int nativeVectorWidthLong() const; - CV_WRAP int nativeVectorWidthFloat() const; - CV_WRAP int nativeVectorWidthDouble() const; - CV_WRAP int nativeVectorWidthHalf() const; - - CV_WRAP int preferredVectorWidthChar() const; - CV_WRAP int preferredVectorWidthShort() const; - CV_WRAP int preferredVectorWidthInt() const; - CV_WRAP int preferredVectorWidthLong() const; - CV_WRAP int preferredVectorWidthFloat() const; - CV_WRAP int preferredVectorWidthDouble() const; - CV_WRAP int preferredVectorWidthHalf() const; - - CV_WRAP size_t printfBufferSize() const; - CV_WRAP size_t profilingTimerResolution() const; - - CV_WRAP static const Device& getDefault(); - - /** - * @param d OpenCL handle (cl_device_id). clRetainDevice() is called on success. - * - * @note Ownership of the passed device is passed to OpenCV on success. - * The caller should additionally call `clRetainDevice` on it if it intends - * to continue using the device. - */ - static Device fromHandle(void* d); - - struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - - -class CV_EXPORTS Context -{ -public: - Context() CV_NOEXCEPT; - explicit Context(int dtype); //!< @deprecated - ~Context(); - Context(const Context& c); - Context& operator= (const Context& c); - Context(Context&& c) CV_NOEXCEPT; - Context& operator = (Context&& c) CV_NOEXCEPT; - - /** @deprecated */ - bool create(); - /** @deprecated */ - bool create(int dtype); - - size_t ndevices() const; - Device& device(size_t idx) const; - Program getProg(const ProgramSource& prog, - const String& buildopt, String& errmsg); - void unloadProg(Program& prog); - - - /** Get thread-local OpenCL context (initialize if necessary) */ -#if 0 // OpenCV 5.0 - static Context& getDefault(); -#else - static Context& getDefault(bool initialize = true); -#endif - - /** @returns cl_context value */ - void* ptr() const; - - /** - * @brief Get OpenCL context property specified on context creation - * @param propertyId Property id (CL_CONTEXT_* as defined in cl_context_properties type) - * @returns Property value if property was specified on clCreateContext, or NULL if context created without the property - */ - void* getOpenCLContextProperty(int propertyId) const; - - bool useSVM() const; - void setUseSVM(bool enabled); - - /** - * @param context OpenCL handle (cl_context). clRetainContext() is called on success - */ - static Context fromHandle(void* context); - static Context fromDevice(const ocl::Device& device); - static Context create(const std::string& configuration); - - void release(); - - class CV_EXPORTS UserContext { - public: - virtual ~UserContext(); - }; - template - inline void setUserContext(const std::shared_ptr& userContext) { - setUserContext(typeid(T), userContext); - } - template - inline std::shared_ptr getUserContext() { - return std::dynamic_pointer_cast(getUserContext(typeid(T))); - } - void setUserContext(std::type_index typeId, const std::shared_ptr& userContext); - std::shared_ptr getUserContext(std::type_index typeId); - - struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -// TODO OpenCV 5.0 -//protected: - Impl* p; -}; - -/** @deprecated */ -class CV_EXPORTS Platform -{ -public: - Platform() CV_NOEXCEPT; - ~Platform(); - Platform(const Platform& p); - Platform& operator = (const Platform& p); - Platform(Platform&& p) CV_NOEXCEPT; - Platform& operator = (Platform&& p) CV_NOEXCEPT; - - void* ptr() const; - - /** @deprecated */ - static Platform& getDefault(); - - struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - -/** @brief Attaches OpenCL context to OpenCV -@note - OpenCV will check if available OpenCL platform has platformName name, then assign context to - OpenCV and call `clRetainContext` function. The deviceID device will be used as target device and - new command queue will be created. -@param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime -@param platformID ID of platform attached context was created for -@param context OpenCL context to be attached to OpenCV -@param deviceID ID of device, must be created from attached context -*/ -CV_EXPORTS void attachContext(const String& platformName, void* platformID, void* context, void* deviceID); - -/** @brief Convert OpenCL buffer to UMat -@note - OpenCL buffer (cl_mem_buffer) should contain 2D image data, compatible with OpenCV. Memory - content is not copied from `clBuffer` to UMat. Instead, buffer handle assigned to UMat and - `clRetainMemObject` is called. -@param cl_mem_buffer source clBuffer handle -@param step num of bytes in single row -@param rows number of rows -@param cols number of cols -@param type OpenCV type of image -@param dst destination UMat -*/ -CV_EXPORTS void convertFromBuffer(void* cl_mem_buffer, size_t step, int rows, int cols, int type, UMat& dst); - -/** @brief Convert OpenCL image2d_t to UMat -@note - OpenCL `image2d_t` (cl_mem_image), should be compatible with OpenCV UMat formats. Memory content - is copied from image to UMat with `clEnqueueCopyImageToBuffer` function. -@param cl_mem_image source image2d_t handle -@param dst destination UMat -*/ -CV_EXPORTS void convertFromImage(void* cl_mem_image, UMat& dst); - -// TODO Move to internal header -/// @deprecated -void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); - -class CV_EXPORTS Queue -{ -public: - Queue() CV_NOEXCEPT; - explicit Queue(const Context& c, const Device& d=Device()); - ~Queue(); - Queue(const Queue& q); - Queue& operator = (const Queue& q); - Queue(Queue&& q) CV_NOEXCEPT; - Queue& operator = (Queue&& q) CV_NOEXCEPT; - - bool create(const Context& c=Context(), const Device& d=Device()); - void finish(); - void* ptr() const; - static Queue& getDefault(); - - /// @brief Returns OpenCL command queue with enable profiling mode support - const Queue& getProfilingQueue() const; - - struct Impl; friend struct Impl; - inline Impl* getImpl() const { return p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - - -class CV_EXPORTS KernelArg -{ -public: - enum { LOCAL=1, READ_ONLY=2, WRITE_ONLY=4, READ_WRITE=6, CONSTANT=8, PTR_ONLY = 16, NO_SIZE=256 }; - KernelArg(int _flags, UMat* _m, int wscale=1, int iwscale=1, const void* _obj=0, size_t _sz=0); - KernelArg() CV_NOEXCEPT; - - static KernelArg Local(size_t localMemSize) - { return KernelArg(LOCAL, 0, 1, 1, 0, localMemSize); } - static KernelArg PtrWriteOnly(const UMat& m) - { return KernelArg(PTR_ONLY+WRITE_ONLY, (UMat*)&m); } - static KernelArg PtrReadOnly(const UMat& m) - { return KernelArg(PTR_ONLY+READ_ONLY, (UMat*)&m); } - static KernelArg PtrReadWrite(const UMat& m) - { return KernelArg(PTR_ONLY+READ_WRITE, (UMat*)&m); } - static KernelArg ReadWrite(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_WRITE, (UMat*)&m, wscale, iwscale); } - static KernelArg ReadWriteNoSize(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_WRITE+NO_SIZE, (UMat*)&m, wscale, iwscale); } - static KernelArg ReadOnly(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_ONLY, (UMat*)&m, wscale, iwscale); } - static KernelArg WriteOnly(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(WRITE_ONLY, (UMat*)&m, wscale, iwscale); } - static KernelArg ReadOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(READ_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } - static KernelArg WriteOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) - { return KernelArg(WRITE_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } - static KernelArg Constant(const Mat& m); - template static KernelArg Constant(const _Tp* arr, size_t n) - { return KernelArg(CONSTANT, 0, 1, 1, (void*)arr, n); } - - int flags; - UMat* m; - const void* obj; - size_t sz; - int wscale, iwscale; -}; - - -class CV_EXPORTS Kernel -{ -public: - Kernel() CV_NOEXCEPT; - Kernel(const char* kname, const Program& prog); - Kernel(const char* kname, const ProgramSource& prog, - const String& buildopts = String(), String* errmsg=0); - ~Kernel(); - Kernel(const Kernel& k); - Kernel& operator = (const Kernel& k); - Kernel(Kernel&& k) CV_NOEXCEPT; - Kernel& operator = (Kernel&& k) CV_NOEXCEPT; - - bool empty() const; - bool create(const char* kname, const Program& prog); - bool create(const char* kname, const ProgramSource& prog, - const String& buildopts, String* errmsg=0); - - int set(int i, const void* value, size_t sz); - int set(int i, const Image2D& image2D); - int set(int i, const UMat& m); - int set(int i, const KernelArg& arg); - template int set(int i, const _Tp& value) - { return set(i, &value, sizeof(value)); } - - -protected: - template inline - int set_args_(int i, const _Tp0& a0) { return set(i, a0); } - template inline - int set_args_(int i, const _Tp0& a0, const _Tps&... rest_args) { i = set(i, a0); return set_args_(i, rest_args...); } -public: - /** @brief Setup OpenCL Kernel arguments. - Avoid direct using of set(i, ...) methods. - @code - bool ok = kernel - .args( - srcUMat, dstUMat, - (float)some_float_param - ).run(ndims, globalSize, localSize); - if (!ok) return false; - @endcode - */ - template inline - Kernel& args(const _Tps&... kernel_args) { set_args_(0, kernel_args...); return *this; } - - /** @brief Run the OpenCL kernel (globalsize value may be adjusted) - - @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. - @param globalsize work items for each dimension. It is not the final globalsize passed to - OpenCL. Each dimension will be adjusted to the nearest integer divisible by the corresponding - value in localsize. If localsize is NULL, it will still be adjusted depending on dims. The - adjusted values are greater than or equal to the original values. - @param localsize work-group size for each dimension. - @param sync specify whether to wait for OpenCL computation to finish before return. - @param q command queue - - @note Use run_() if your kernel code doesn't support adjusted globalsize. - */ - bool run(int dims, size_t globalsize[], - size_t localsize[], bool sync, const Queue& q=Queue()); - - /** @brief Run the OpenCL kernel - * - * @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. - * @param globalsize work items for each dimension. This value is passed to OpenCL without changes. - * @param localsize work-group size for each dimension. - * @param sync specify whether to wait for OpenCL computation to finish before return. - * @param q command queue - */ - bool run_(int dims, size_t globalsize[], size_t localsize[], bool sync, const Queue& q=Queue()); - - bool runTask(bool sync, const Queue& q=Queue()); - - /** @brief Similar to synchronized run_() call with returning of kernel execution time - * - * Separate OpenCL command queue may be used (with CL_QUEUE_PROFILING_ENABLE) - * @return Execution time in nanoseconds or negative number on error - */ - int64 runProfiling(int dims, size_t globalsize[], size_t localsize[], const Queue& q=Queue()); - - size_t workGroupSize() const; - size_t preferedWorkGroupSizeMultiple() const; - bool compileWorkGroupSize(size_t wsz[]) const; - size_t localMemSize() const; - - void* ptr() const; - struct Impl; - -protected: - Impl* p; -}; - -class CV_EXPORTS Program -{ -public: - Program() CV_NOEXCEPT; - Program(const ProgramSource& src, - const String& buildflags, String& errmsg); - Program(const Program& prog); - Program& operator = (const Program& prog); - Program(Program&& prog) CV_NOEXCEPT; - Program& operator = (Program&& prog) CV_NOEXCEPT; - ~Program(); - - bool create(const ProgramSource& src, - const String& buildflags, String& errmsg); - - void* ptr() const; - - /** - * @brief Query device-specific program binary. - * - * Returns RAW OpenCL executable binary without additional attachments. - * - * @sa ProgramSource::fromBinary - * - * @param[out] binary output buffer - */ - void getBinary(std::vector& binary) const; - - struct Impl; friend struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -public: -#ifndef OPENCV_REMOVE_DEPRECATED_API - // TODO Remove this - CV_DEPRECATED bool read(const String& buf, const String& buildflags); // removed, use ProgramSource instead - CV_DEPRECATED bool write(String& buf) const; // removed, use getBinary() method instead (RAW OpenCL binary) - CV_DEPRECATED const ProgramSource& source() const; // implementation removed - CV_DEPRECATED String getPrefix() const; // deprecated, implementation replaced - CV_DEPRECATED static String getPrefix(const String& buildflags); // deprecated, implementation replaced -#endif -}; - - -class CV_EXPORTS ProgramSource -{ -public: - typedef uint64 hash_t; // deprecated - - ProgramSource() CV_NOEXCEPT; - explicit ProgramSource(const String& module, const String& name, const String& codeStr, const String& codeHash); - explicit ProgramSource(const String& prog); // deprecated - explicit ProgramSource(const char* prog); // deprecated - ~ProgramSource(); - ProgramSource(const ProgramSource& prog); - ProgramSource& operator = (const ProgramSource& prog); - ProgramSource(ProgramSource&& prog) CV_NOEXCEPT; - ProgramSource& operator = (ProgramSource&& prog) CV_NOEXCEPT; - - const String& source() const; // deprecated - hash_t hash() const; // deprecated - - - /** @brief Describe OpenCL program binary. - * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). - * - * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). - * - * This kind of binary is not portable between platforms in general - it is specific to OpenCL vendor / device / driver version. - * - * @param module name of program owner module - * @param name unique name of program (module+name is used as key for OpenCL program caching) - * @param binary buffer address. See buffer lifetime requirement in description. - * @param size buffer size - * @param buildOptions additional program-related build options passed to clBuildProgram() - * @return created ProgramSource object - */ - static ProgramSource fromBinary(const String& module, const String& name, - const unsigned char* binary, const size_t size, - const cv::String& buildOptions = cv::String()); - - /** @brief Describe OpenCL program in SPIR format. - * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). - * - * Supports SPIR 1.2 by default (pass '-spir-std=X.Y' in buildOptions to override this behavior) - * - * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). - * - * Programs in this format are portable between OpenCL implementations with 'khr_spir' extension: - * https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/cl_khr_spir.html - * (but they are not portable between different platforms: 32-bit / 64-bit) - * - * Note: these programs can't support vendor specific extensions, like 'cl_intel_subgroups'. - * - * @param module name of program owner module - * @param name unique name of program (module+name is used as key for OpenCL program caching) - * @param binary buffer address. See buffer lifetime requirement in description. - * @param size buffer size - * @param buildOptions additional program-related build options passed to clBuildProgram() - * (these options are added automatically: '-x spir' and '-spir-std=1.2') - * @return created ProgramSource object. - */ - static ProgramSource fromSPIR(const String& module, const String& name, - const unsigned char* binary, const size_t size, - const cv::String& buildOptions = cv::String()); - - //OpenCL 2.1+ only - //static Program fromSPIRV(const String& module, const String& name, - // const unsigned char* binary, const size_t size, - // const cv::String& buildOptions = cv::String()); - - struct Impl; friend struct Impl; - inline Impl* getImpl() const { return (Impl*)p; } - inline bool empty() const { return !p; } -protected: - Impl* p; -}; - -class CV_EXPORTS PlatformInfo -{ -public: - PlatformInfo() CV_NOEXCEPT; - /** - * @param id pointer cl_platform_id (cl_platform_id*) - */ - explicit PlatformInfo(void* id); - ~PlatformInfo(); - - PlatformInfo(const PlatformInfo& i); - PlatformInfo& operator =(const PlatformInfo& i); - PlatformInfo(PlatformInfo&& i) CV_NOEXCEPT; - PlatformInfo& operator = (PlatformInfo&& i) CV_NOEXCEPT; - - String name() const; - String vendor() const; - - /// See CL_PLATFORM_VERSION - String version() const; - int versionMajor() const; - int versionMinor() const; - - int deviceNumber() const; - void getDevice(Device& device, int d) const; - - struct Impl; - bool empty() const { return !p; } -protected: - Impl* p; -}; - -CV_EXPORTS CV_DEPRECATED const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf); -CV_EXPORTS const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf, size_t buf_size); -CV_EXPORTS const char* typeToStr(int t); -CV_EXPORTS const char* memopTypeToStr(int t); -CV_EXPORTS const char* vecopTypeToStr(int t); -CV_EXPORTS const char* getOpenCLErrorString(int errorCode); -CV_EXPORTS String kernelToStr(InputArray _kernel, int ddepth = -1, const char * name = NULL); -CV_EXPORTS void getPlatfomsInfo(std::vector& platform_info); - - -enum OclVectorStrategy -{ - // all matrices have its own vector width - OCL_VECTOR_OWN = 0, - // all matrices have maximal vector width among all matrices - // (useful for cases when matrices have different data types) - OCL_VECTOR_MAX = 1, - - // default strategy - OCL_VECTOR_DEFAULT = OCL_VECTOR_OWN -}; - -CV_EXPORTS int predictOptimalVectorWidth(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), - InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), - InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), - OclVectorStrategy strat = OCL_VECTOR_DEFAULT); - -CV_EXPORTS int checkOptimalVectorWidth(const int *vectorWidths, - InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), - InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), - InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), - OclVectorStrategy strat = OCL_VECTOR_DEFAULT); - -// with OCL_VECTOR_MAX strategy -CV_EXPORTS int predictOptimalVectorWidthMax(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), - InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), - InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray()); - -CV_EXPORTS void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m); - -class CV_EXPORTS Image2D -{ -public: - Image2D() CV_NOEXCEPT; - - /** - @param src UMat object from which to get image properties and data - @param norm flag to enable the use of normalized channel data types - @param alias flag indicating that the image should alias the src UMat. If true, changes to the - image or src will be reflected in both objects. - */ - explicit Image2D(const UMat &src, bool norm = false, bool alias = false); - Image2D(const Image2D & i); - ~Image2D(); - - Image2D & operator = (const Image2D & i); - Image2D(Image2D &&) CV_NOEXCEPT; - Image2D &operator=(Image2D &&) CV_NOEXCEPT; - - /** Indicates if creating an aliased image should succeed. - Depends on the underlying platform and the dimensions of the UMat. - */ - static bool canCreateAlias(const UMat &u); - - /** Indicates if the image format is supported. - */ - static bool isFormatSupported(int depth, int cn, bool norm); - - void* ptr() const; -protected: - struct Impl; - Impl* p; -}; - -class CV_EXPORTS Timer -{ -public: - Timer(const Queue& q); - ~Timer(); - void start(); - void stop(); - - uint64 durationNS() const; ///< duration in nanoseconds - -protected: - struct Impl; - Impl* const p; - -private: - Timer(const Timer&); // disabled - Timer& operator=(const Timer&); // disabled -}; - -CV_EXPORTS MatAllocator* getOpenCLAllocator(); - - -class CV_EXPORTS_W OpenCLExecutionContext -{ -public: - OpenCLExecutionContext() = default; - ~OpenCLExecutionContext() = default; - - OpenCLExecutionContext(const OpenCLExecutionContext&) = default; - OpenCLExecutionContext(OpenCLExecutionContext&&) = default; - - OpenCLExecutionContext& operator=(const OpenCLExecutionContext&) = default; - OpenCLExecutionContext& operator=(OpenCLExecutionContext&&) = default; - - /** Get associated ocl::Context */ - Context& getContext() const; - /** Get the single default associated ocl::Device */ - Device& getDevice() const; - /** Get the single ocl::Queue that is associated with the ocl::Context and - * the single default ocl::Device - */ - Queue& getQueue() const; - - bool useOpenCL() const; - void setUseOpenCL(bool flag); - - /** Get OpenCL execution context of current thread. - * - * Initialize OpenCL execution context if it is empty - * - create new - * - reuse context of the main thread (threadID = 0) - */ - static OpenCLExecutionContext& getCurrent(); - - /** Get OpenCL execution context of current thread (can be empty) */ - static OpenCLExecutionContext& getCurrentRef(); - - /** Bind this OpenCL execution context to current thread. - * - * Context can't be empty. - * - * @note clFinish is not called for queue of previous execution context - */ - void bind() const; - - /** Creates new execution context with same OpenCV context and device - * - * @param q OpenCL queue - */ - OpenCLExecutionContext cloneWithNewQueue(const ocl::Queue& q) const; - /** @overload */ - OpenCLExecutionContext cloneWithNewQueue() const; - - /** @brief Creates OpenCL execution context - * OpenCV will check if available OpenCL platform has platformName name, - * then assign context to OpenCV. - * The deviceID device will be used as target device and a new command queue will be created. - * - * @note On success, ownership of one reference of the context and device is taken. - * The caller should additionally call `clRetainContext` and/or `clRetainDevice` - * to increase the reference count if it wishes to continue using them. - * - * @param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime - * @param platformID ID of platform attached context was created for (cl_platform_id) - * @param context OpenCL context to be attached to OpenCV (cl_context) - * @param deviceID OpenCL device (cl_device_id) - */ - static OpenCLExecutionContext create(const std::string& platformName, void* platformID, void* context, void* deviceID); - - /** @brief Creates OpenCL execution context - * - * @param context non-empty OpenCL context - * @param device non-empty OpenCL device (must be a part of context) - * @param queue non-empty OpenCL queue for provided context and device - */ - static OpenCLExecutionContext create(const Context& context, const Device& device, const ocl::Queue& queue); - /** @overload */ - static OpenCLExecutionContext create(const Context& context, const Device& device); - - struct Impl; - inline bool empty() const { return !p; } - void release(); -protected: - std::shared_ptr p; -}; - -class OpenCLExecutionContextScope -{ - OpenCLExecutionContext ctx_; -public: - inline OpenCLExecutionContextScope(const OpenCLExecutionContext& ctx) - { - CV_Assert(!ctx.empty()); - ctx_ = OpenCLExecutionContext::getCurrentRef(); - ctx.bind(); - } - - inline ~OpenCLExecutionContextScope() - { - if (!ctx_.empty()) - { - ctx_.bind(); - } - } -}; - -#ifdef __OPENCV_BUILD -namespace internal { - -CV_EXPORTS bool isOpenCLForced(); -#define OCL_FORCE_CHECK(condition) (cv::ocl::internal::isOpenCLForced() || (condition)) - -CV_EXPORTS bool isPerformanceCheckBypassed(); -#define OCL_PERFORMANCE_CHECK(condition) (cv::ocl::internal::isPerformanceCheckBypassed() || (condition)) - -CV_EXPORTS bool isCLBuffer(UMat& u); - -} // namespace internal -#endif - -//! @} - -}} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_OPENCL_HPP +#define OPENCV_OPENCL_HPP + +#include "opencv2/core.hpp" +#include +#include + +namespace cv { namespace ocl { + +//! @addtogroup core_opencl +//! @{ + +CV_EXPORTS_W bool haveOpenCL(); +CV_EXPORTS_W bool useOpenCL(); +CV_EXPORTS_W bool haveAmdBlas(); +CV_EXPORTS_W bool haveAmdFft(); +CV_EXPORTS_W void setUseOpenCL(bool flag); +CV_EXPORTS_W void finish(); + +CV_EXPORTS bool haveSVM(); + +class CV_EXPORTS Context; +class CV_EXPORTS_W_SIMPLE Device; +class CV_EXPORTS Kernel; +class CV_EXPORTS Program; +class CV_EXPORTS ProgramSource; +class CV_EXPORTS Queue; +class CV_EXPORTS PlatformInfo; +class CV_EXPORTS Image2D; + +class CV_EXPORTS_W_SIMPLE Device +{ +public: + CV_WRAP Device() CV_NOEXCEPT; + explicit Device(void* d); + Device(const Device& d); + Device& operator = (const Device& d); + Device(Device&& d) CV_NOEXCEPT; + Device& operator = (Device&& d) CV_NOEXCEPT; + CV_WRAP ~Device(); + + void set(void* d); + + enum + { + TYPE_DEFAULT = (1 << 0), + TYPE_CPU = (1 << 1), + TYPE_GPU = (1 << 2), + TYPE_ACCELERATOR = (1 << 3), + TYPE_DGPU = TYPE_GPU + (1 << 16), + TYPE_IGPU = TYPE_GPU + (1 << 17), + TYPE_ALL = 0xFFFFFFFF + }; + + CV_WRAP String name() const; + CV_WRAP String extensions() const; + CV_WRAP bool isExtensionSupported(const String& extensionName) const; + CV_WRAP String version() const; + CV_WRAP String vendorName() const; + CV_WRAP String OpenCL_C_Version() const; + CV_WRAP String OpenCLVersion() const; + CV_WRAP int deviceVersionMajor() const; + CV_WRAP int deviceVersionMinor() const; + CV_WRAP String driverVersion() const; + void* ptr() const; + + CV_WRAP int type() const; + + CV_WRAP int addressBits() const; + CV_WRAP bool available() const; + CV_WRAP bool compilerAvailable() const; + CV_WRAP bool linkerAvailable() const; + + enum + { + FP_DENORM=(1 << 0), + FP_INF_NAN=(1 << 1), + FP_ROUND_TO_NEAREST=(1 << 2), + FP_ROUND_TO_ZERO=(1 << 3), + FP_ROUND_TO_INF=(1 << 4), + FP_FMA=(1 << 5), + FP_SOFT_FLOAT=(1 << 6), + FP_CORRECTLY_ROUNDED_DIVIDE_SQRT=(1 << 7) + }; + CV_WRAP int doubleFPConfig() const; + CV_WRAP int singleFPConfig() const; + CV_WRAP int halfFPConfig() const; + + /// true if 'cl_khr_fp64' extension is available + CV_WRAP bool hasFP64() const; + /// true if 'cl_khr_fp16' extension is available + CV_WRAP bool hasFP16() const; + + CV_WRAP bool endianLittle() const; + CV_WRAP bool errorCorrectionSupport() const; + + enum + { + EXEC_KERNEL=(1 << 0), + EXEC_NATIVE_KERNEL=(1 << 1) + }; + CV_WRAP int executionCapabilities() const; + + CV_WRAP size_t globalMemCacheSize() const; + + enum + { + NO_CACHE=0, + READ_ONLY_CACHE=1, + READ_WRITE_CACHE=2 + }; + CV_WRAP int globalMemCacheType() const; + CV_WRAP int globalMemCacheLineSize() const; + CV_WRAP size_t globalMemSize() const; + + CV_WRAP size_t localMemSize() const; + enum + { + NO_LOCAL_MEM=0, + LOCAL_IS_LOCAL=1, + LOCAL_IS_GLOBAL=2 + }; + CV_WRAP int localMemType() const; + CV_WRAP bool hostUnifiedMemory() const; + + CV_WRAP bool imageSupport() const; + + CV_WRAP bool imageFromBufferSupport() const; + uint imagePitchAlignment() const; + uint imageBaseAddressAlignment() const; + + /// deprecated, use isExtensionSupported() method (probably with "cl_khr_subgroups" value) + CV_WRAP bool intelSubgroupsSupport() const; + + CV_WRAP size_t image2DMaxWidth() const; + CV_WRAP size_t image2DMaxHeight() const; + + CV_WRAP size_t image3DMaxWidth() const; + CV_WRAP size_t image3DMaxHeight() const; + CV_WRAP size_t image3DMaxDepth() const; + + CV_WRAP size_t imageMaxBufferSize() const; + CV_WRAP size_t imageMaxArraySize() const; + + enum + { + UNKNOWN_VENDOR=0, + VENDOR_AMD=1, + VENDOR_INTEL=2, + VENDOR_NVIDIA=3 + }; + CV_WRAP int vendorID() const; + // FIXIT + // dev.isAMD() doesn't work for OpenCL CPU devices from AMD OpenCL platform. + // This method should use platform name instead of vendor name. + // After fix restore code in arithm.cpp: ocl_compare() + CV_WRAP inline bool isAMD() const { return vendorID() == VENDOR_AMD; } + CV_WRAP inline bool isIntel() const { return vendorID() == VENDOR_INTEL; } + CV_WRAP inline bool isNVidia() const { return vendorID() == VENDOR_NVIDIA; } + + CV_WRAP int maxClockFrequency() const; + CV_WRAP int maxComputeUnits() const; + CV_WRAP int maxConstantArgs() const; + CV_WRAP size_t maxConstantBufferSize() const; + + CV_WRAP size_t maxMemAllocSize() const; + CV_WRAP size_t maxParameterSize() const; + + CV_WRAP int maxReadImageArgs() const; + CV_WRAP int maxWriteImageArgs() const; + CV_WRAP int maxSamplers() const; + + CV_WRAP size_t maxWorkGroupSize() const; + CV_WRAP int maxWorkItemDims() const; + void maxWorkItemSizes(size_t*) const; + + CV_WRAP int memBaseAddrAlign() const; + + CV_WRAP int nativeVectorWidthChar() const; + CV_WRAP int nativeVectorWidthShort() const; + CV_WRAP int nativeVectorWidthInt() const; + CV_WRAP int nativeVectorWidthLong() const; + CV_WRAP int nativeVectorWidthFloat() const; + CV_WRAP int nativeVectorWidthDouble() const; + CV_WRAP int nativeVectorWidthHalf() const; + + CV_WRAP int preferredVectorWidthChar() const; + CV_WRAP int preferredVectorWidthShort() const; + CV_WRAP int preferredVectorWidthInt() const; + CV_WRAP int preferredVectorWidthLong() const; + CV_WRAP int preferredVectorWidthFloat() const; + CV_WRAP int preferredVectorWidthDouble() const; + CV_WRAP int preferredVectorWidthHalf() const; + + CV_WRAP size_t printfBufferSize() const; + CV_WRAP size_t profilingTimerResolution() const; + + CV_WRAP static const Device& getDefault(); + + /** + * @param d OpenCL handle (cl_device_id). clRetainDevice() is called on success. + * + * @note Ownership of the passed device is passed to OpenCV on success. + * The caller should additionally call `clRetainDevice` on it if it intends + * to continue using the device. + */ + static Device fromHandle(void* d); + + struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + + +class CV_EXPORTS Context +{ +public: + Context() CV_NOEXCEPT; + explicit Context(int dtype); //!< @deprecated + ~Context(); + Context(const Context& c); + Context& operator= (const Context& c); + Context(Context&& c) CV_NOEXCEPT; + Context& operator = (Context&& c) CV_NOEXCEPT; + + /** @deprecated */ + bool create(); + /** @deprecated */ + bool create(int dtype); + + size_t ndevices() const; + Device& device(size_t idx) const; + Program getProg(const ProgramSource& prog, + const String& buildopt, String& errmsg); + void unloadProg(Program& prog); + + + /** Get thread-local OpenCL context (initialize if necessary) */ +#if 0 // OpenCV 5.0 + static Context& getDefault(); +#else + static Context& getDefault(bool initialize = true); +#endif + + /** @returns cl_context value */ + void* ptr() const; + + /** + * @brief Get OpenCL context property specified on context creation + * @param propertyId Property id (CL_CONTEXT_* as defined in cl_context_properties type) + * @returns Property value if property was specified on clCreateContext, or NULL if context created without the property + */ + void* getOpenCLContextProperty(int propertyId) const; + + bool useSVM() const; + void setUseSVM(bool enabled); + + /** + * @param context OpenCL handle (cl_context). clRetainContext() is called on success + */ + static Context fromHandle(void* context); + static Context fromDevice(const ocl::Device& device); + static Context create(const std::string& configuration); + + void release(); + + class CV_EXPORTS UserContext { + public: + virtual ~UserContext(); + }; + template + inline void setUserContext(const std::shared_ptr& userContext) { + setUserContext(typeid(T), userContext); + } + template + inline std::shared_ptr getUserContext() { + return std::dynamic_pointer_cast(getUserContext(typeid(T))); + } + void setUserContext(std::type_index typeId, const std::shared_ptr& userContext); + std::shared_ptr getUserContext(std::type_index typeId); + + struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +// TODO OpenCV 5.0 +//protected: + Impl* p; +}; + +/** @deprecated */ +class CV_EXPORTS Platform +{ +public: + Platform() CV_NOEXCEPT; + ~Platform(); + Platform(const Platform& p); + Platform& operator = (const Platform& p); + Platform(Platform&& p) CV_NOEXCEPT; + Platform& operator = (Platform&& p) CV_NOEXCEPT; + + void* ptr() const; + + /** @deprecated */ + static Platform& getDefault(); + + struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + +/** @brief Attaches OpenCL context to OpenCV +@note + OpenCV will check if available OpenCL platform has platformName name, then assign context to + OpenCV and call `clRetainContext` function. The deviceID device will be used as target device and + new command queue will be created. +@param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime +@param platformID ID of platform attached context was created for +@param context OpenCL context to be attached to OpenCV +@param deviceID ID of device, must be created from attached context +*/ +CV_EXPORTS void attachContext(const String& platformName, void* platformID, void* context, void* deviceID); + +/** @brief Convert OpenCL buffer to UMat +@note + OpenCL buffer (cl_mem_buffer) should contain 2D image data, compatible with OpenCV. Memory + content is not copied from `clBuffer` to UMat. Instead, buffer handle assigned to UMat and + `clRetainMemObject` is called. +@param cl_mem_buffer source clBuffer handle +@param step num of bytes in single row +@param rows number of rows +@param cols number of cols +@param type OpenCV type of image +@param dst destination UMat +*/ +CV_EXPORTS void convertFromBuffer(void* cl_mem_buffer, size_t step, int rows, int cols, int type, UMat& dst); + +/** @brief Convert OpenCL image2d_t to UMat +@note + OpenCL `image2d_t` (cl_mem_image), should be compatible with OpenCV UMat formats. Memory content + is copied from image to UMat with `clEnqueueCopyImageToBuffer` function. +@param cl_mem_image source image2d_t handle +@param dst destination UMat +*/ +CV_EXPORTS void convertFromImage(void* cl_mem_image, UMat& dst); + +// TODO Move to internal header +/// @deprecated +void initializeContextFromHandle(Context& ctx, void* platform, void* context, void* device); + +class CV_EXPORTS Queue +{ +public: + Queue() CV_NOEXCEPT; + explicit Queue(const Context& c, const Device& d=Device()); + ~Queue(); + Queue(const Queue& q); + Queue& operator = (const Queue& q); + Queue(Queue&& q) CV_NOEXCEPT; + Queue& operator = (Queue&& q) CV_NOEXCEPT; + + bool create(const Context& c=Context(), const Device& d=Device()); + void finish(); + void* ptr() const; + static Queue& getDefault(); + + /// @brief Returns OpenCL command queue with enable profiling mode support + const Queue& getProfilingQueue() const; + + struct Impl; friend struct Impl; + inline Impl* getImpl() const { return p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + + +class CV_EXPORTS KernelArg +{ +public: + enum { LOCAL=1, READ_ONLY=2, WRITE_ONLY=4, READ_WRITE=6, CONSTANT=8, PTR_ONLY = 16, NO_SIZE=256 }; + KernelArg(int _flags, UMat* _m, int wscale=1, int iwscale=1, const void* _obj=0, size_t _sz=0); + KernelArg() CV_NOEXCEPT; + + static KernelArg Local(size_t localMemSize) + { return KernelArg(LOCAL, 0, 1, 1, 0, localMemSize); } + static KernelArg PtrWriteOnly(const UMat& m) + { return KernelArg(PTR_ONLY+WRITE_ONLY, (UMat*)&m); } + static KernelArg PtrReadOnly(const UMat& m) + { return KernelArg(PTR_ONLY+READ_ONLY, (UMat*)&m); } + static KernelArg PtrReadWrite(const UMat& m) + { return KernelArg(PTR_ONLY+READ_WRITE, (UMat*)&m); } + static KernelArg ReadWrite(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_WRITE, (UMat*)&m, wscale, iwscale); } + static KernelArg ReadWriteNoSize(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_WRITE+NO_SIZE, (UMat*)&m, wscale, iwscale); } + static KernelArg ReadOnly(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_ONLY, (UMat*)&m, wscale, iwscale); } + static KernelArg WriteOnly(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(WRITE_ONLY, (UMat*)&m, wscale, iwscale); } + static KernelArg ReadOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(READ_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } + static KernelArg WriteOnlyNoSize(const UMat& m, int wscale=1, int iwscale=1) + { return KernelArg(WRITE_ONLY+NO_SIZE, (UMat*)&m, wscale, iwscale); } + static KernelArg Constant(const Mat& m); + template static KernelArg Constant(const _Tp* arr, size_t n) + { return KernelArg(CONSTANT, 0, 1, 1, (void*)arr, n); } + + int flags; + UMat* m; + const void* obj; + size_t sz; + int wscale, iwscale; +}; + + +class CV_EXPORTS Kernel +{ +public: + Kernel() CV_NOEXCEPT; + Kernel(const char* kname, const Program& prog); + Kernel(const char* kname, const ProgramSource& prog, + const String& buildopts = String(), String* errmsg=0); + ~Kernel(); + Kernel(const Kernel& k); + Kernel& operator = (const Kernel& k); + Kernel(Kernel&& k) CV_NOEXCEPT; + Kernel& operator = (Kernel&& k) CV_NOEXCEPT; + + bool empty() const; + bool create(const char* kname, const Program& prog); + bool create(const char* kname, const ProgramSource& prog, + const String& buildopts, String* errmsg=0); + + int set(int i, const void* value, size_t sz); + int set(int i, const Image2D& image2D); + int set(int i, const UMat& m); + int set(int i, const KernelArg& arg); + template int set(int i, const _Tp& value) + { return set(i, &value, sizeof(value)); } + + +protected: + template inline + int set_args_(int i, const _Tp0& a0) { return set(i, a0); } + template inline + int set_args_(int i, const _Tp0& a0, const _Tps&... rest_args) { i = set(i, a0); return set_args_(i, rest_args...); } +public: + /** @brief Setup OpenCL Kernel arguments. + Avoid direct using of set(i, ...) methods. + @code + bool ok = kernel + .args( + srcUMat, dstUMat, + (float)some_float_param + ).run(ndims, globalSize, localSize); + if (!ok) return false; + @endcode + */ + template inline + Kernel& args(const _Tps&... kernel_args) { set_args_(0, kernel_args...); return *this; } + + /** @brief Run the OpenCL kernel (globalsize value may be adjusted) + + @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. + @param globalsize work items for each dimension. It is not the final globalsize passed to + OpenCL. Each dimension will be adjusted to the nearest integer divisible by the corresponding + value in localsize. If localsize is NULL, it will still be adjusted depending on dims. The + adjusted values are greater than or equal to the original values. + @param localsize work-group size for each dimension. + @param sync specify whether to wait for OpenCL computation to finish before return. + @param q command queue + + @note Use run_() if your kernel code doesn't support adjusted globalsize. + */ + bool run(int dims, size_t globalsize[], + size_t localsize[], bool sync, const Queue& q=Queue()); + + /** @brief Run the OpenCL kernel + * + * @param dims the work problem dimensions. It is the length of globalsize and localsize. It can be either 1, 2 or 3. + * @param globalsize work items for each dimension. This value is passed to OpenCL without changes. + * @param localsize work-group size for each dimension. + * @param sync specify whether to wait for OpenCL computation to finish before return. + * @param q command queue + */ + bool run_(int dims, size_t globalsize[], size_t localsize[], bool sync, const Queue& q=Queue()); + + bool runTask(bool sync, const Queue& q=Queue()); + + /** @brief Similar to synchronized run_() call with returning of kernel execution time + * + * Separate OpenCL command queue may be used (with CL_QUEUE_PROFILING_ENABLE) + * @return Execution time in nanoseconds or negative number on error + */ + int64 runProfiling(int dims, size_t globalsize[], size_t localsize[], const Queue& q=Queue()); + + size_t workGroupSize() const; + size_t preferedWorkGroupSizeMultiple() const; + bool compileWorkGroupSize(size_t wsz[]) const; + size_t localMemSize() const; + + void* ptr() const; + struct Impl; + +protected: + Impl* p; +}; + +class CV_EXPORTS Program +{ +public: + Program() CV_NOEXCEPT; + Program(const ProgramSource& src, + const String& buildflags, String& errmsg); + Program(const Program& prog); + Program& operator = (const Program& prog); + Program(Program&& prog) CV_NOEXCEPT; + Program& operator = (Program&& prog) CV_NOEXCEPT; + ~Program(); + + bool create(const ProgramSource& src, + const String& buildflags, String& errmsg); + + void* ptr() const; + + /** + * @brief Query device-specific program binary. + * + * Returns RAW OpenCL executable binary without additional attachments. + * + * @sa ProgramSource::fromBinary + * + * @param[out] binary output buffer + */ + void getBinary(std::vector& binary) const; + + struct Impl; friend struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +public: +#ifndef OPENCV_REMOVE_DEPRECATED_API + // TODO Remove this + CV_DEPRECATED bool read(const String& buf, const String& buildflags); // removed, use ProgramSource instead + CV_DEPRECATED bool write(String& buf) const; // removed, use getBinary() method instead (RAW OpenCL binary) + CV_DEPRECATED const ProgramSource& source() const; // implementation removed + CV_DEPRECATED String getPrefix() const; // deprecated, implementation replaced + CV_DEPRECATED static String getPrefix(const String& buildflags); // deprecated, implementation replaced +#endif +}; + + +class CV_EXPORTS ProgramSource +{ +public: + typedef uint64 hash_t; // deprecated + + ProgramSource() CV_NOEXCEPT; + explicit ProgramSource(const String& module, const String& name, const String& codeStr, const String& codeHash); + explicit ProgramSource(const String& prog); // deprecated + explicit ProgramSource(const char* prog); // deprecated + ~ProgramSource(); + ProgramSource(const ProgramSource& prog); + ProgramSource& operator = (const ProgramSource& prog); + ProgramSource(ProgramSource&& prog) CV_NOEXCEPT; + ProgramSource& operator = (ProgramSource&& prog) CV_NOEXCEPT; + + const String& source() const; // deprecated + hash_t hash() const; // deprecated + + + /** @brief Describe OpenCL program binary. + * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). + * + * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). + * + * This kind of binary is not portable between platforms in general - it is specific to OpenCL vendor / device / driver version. + * + * @param module name of program owner module + * @param name unique name of program (module+name is used as key for OpenCL program caching) + * @param binary buffer address. See buffer lifetime requirement in description. + * @param size buffer size + * @param buildOptions additional program-related build options passed to clBuildProgram() + * @return created ProgramSource object + */ + static ProgramSource fromBinary(const String& module, const String& name, + const unsigned char* binary, const size_t size, + const cv::String& buildOptions = cv::String()); + + /** @brief Describe OpenCL program in SPIR format. + * Do not call clCreateProgramWithBinary() and/or clBuildProgram(). + * + * Supports SPIR 1.2 by default (pass '-spir-std=X.Y' in buildOptions to override this behavior) + * + * Caller should guarantee binary buffer lifetime greater than ProgramSource object (and any of its copies). + * + * Programs in this format are portable between OpenCL implementations with 'khr_spir' extension: + * https://www.khronos.org/registry/OpenCL/sdk/2.0/docs/man/xhtml/cl_khr_spir.html + * (but they are not portable between different platforms: 32-bit / 64-bit) + * + * Note: these programs can't support vendor specific extensions, like 'cl_intel_subgroups'. + * + * @param module name of program owner module + * @param name unique name of program (module+name is used as key for OpenCL program caching) + * @param binary buffer address. See buffer lifetime requirement in description. + * @param size buffer size + * @param buildOptions additional program-related build options passed to clBuildProgram() + * (these options are added automatically: '-x spir' and '-spir-std=1.2') + * @return created ProgramSource object. + */ + static ProgramSource fromSPIR(const String& module, const String& name, + const unsigned char* binary, const size_t size, + const cv::String& buildOptions = cv::String()); + + //OpenCL 2.1+ only + //static Program fromSPIRV(const String& module, const String& name, + // const unsigned char* binary, const size_t size, + // const cv::String& buildOptions = cv::String()); + + struct Impl; friend struct Impl; + inline Impl* getImpl() const { return (Impl*)p; } + inline bool empty() const { return !p; } +protected: + Impl* p; +}; + +class CV_EXPORTS PlatformInfo +{ +public: + PlatformInfo() CV_NOEXCEPT; + /** + * @param id pointer cl_platform_id (cl_platform_id*) + */ + explicit PlatformInfo(void* id); + ~PlatformInfo(); + + PlatformInfo(const PlatformInfo& i); + PlatformInfo& operator =(const PlatformInfo& i); + PlatformInfo(PlatformInfo&& i) CV_NOEXCEPT; + PlatformInfo& operator = (PlatformInfo&& i) CV_NOEXCEPT; + + String name() const; + String vendor() const; + + /// See CL_PLATFORM_VERSION + String version() const; + int versionMajor() const; + int versionMinor() const; + + int deviceNumber() const; + void getDevice(Device& device, int d) const; + + struct Impl; + bool empty() const { return !p; } +protected: + Impl* p; +}; + +CV_EXPORTS CV_DEPRECATED const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf); +CV_EXPORTS const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf, size_t buf_size); +CV_EXPORTS const char* typeToStr(int t); +CV_EXPORTS const char* memopTypeToStr(int t); +CV_EXPORTS const char* vecopTypeToStr(int t); +CV_EXPORTS const char* getOpenCLErrorString(int errorCode); +CV_EXPORTS String kernelToStr(InputArray _kernel, int ddepth = -1, const char * name = NULL); +CV_EXPORTS void getPlatfomsInfo(std::vector& platform_info); + + +enum OclVectorStrategy +{ + // all matrices have its own vector width + OCL_VECTOR_OWN = 0, + // all matrices have maximal vector width among all matrices + // (useful for cases when matrices have different data types) + OCL_VECTOR_MAX = 1, + + // default strategy + OCL_VECTOR_DEFAULT = OCL_VECTOR_OWN +}; + +CV_EXPORTS int predictOptimalVectorWidth(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), + InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), + InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), + OclVectorStrategy strat = OCL_VECTOR_DEFAULT); + +CV_EXPORTS int checkOptimalVectorWidth(const int *vectorWidths, + InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), + InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), + InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray(), + OclVectorStrategy strat = OCL_VECTOR_DEFAULT); + +// with OCL_VECTOR_MAX strategy +CV_EXPORTS int predictOptimalVectorWidthMax(InputArray src1, InputArray src2 = noArray(), InputArray src3 = noArray(), + InputArray src4 = noArray(), InputArray src5 = noArray(), InputArray src6 = noArray(), + InputArray src7 = noArray(), InputArray src8 = noArray(), InputArray src9 = noArray()); + +CV_EXPORTS void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m); + +class CV_EXPORTS Image2D +{ +public: + Image2D() CV_NOEXCEPT; + + /** + @param src UMat object from which to get image properties and data + @param norm flag to enable the use of normalized channel data types + @param alias flag indicating that the image should alias the src UMat. If true, changes to the + image or src will be reflected in both objects. + */ + explicit Image2D(const UMat &src, bool norm = false, bool alias = false); + Image2D(const Image2D & i); + ~Image2D(); + + Image2D & operator = (const Image2D & i); + Image2D(Image2D &&) CV_NOEXCEPT; + Image2D &operator=(Image2D &&) CV_NOEXCEPT; + + /** Indicates if creating an aliased image should succeed. + Depends on the underlying platform and the dimensions of the UMat. + */ + static bool canCreateAlias(const UMat &u); + + /** Indicates if the image format is supported. + */ + static bool isFormatSupported(int depth, int cn, bool norm); + + void* ptr() const; +protected: + struct Impl; + Impl* p; +}; + +class CV_EXPORTS Timer +{ +public: + Timer(const Queue& q); + ~Timer(); + void start(); + void stop(); + + uint64 durationNS() const; ///< duration in nanoseconds + +protected: + struct Impl; + Impl* const p; + +private: + Timer(const Timer&); // disabled + Timer& operator=(const Timer&); // disabled +}; + +CV_EXPORTS MatAllocator* getOpenCLAllocator(); + + +class CV_EXPORTS_W OpenCLExecutionContext +{ +public: + OpenCLExecutionContext() = default; + ~OpenCLExecutionContext() = default; + + OpenCLExecutionContext(const OpenCLExecutionContext&) = default; + OpenCLExecutionContext(OpenCLExecutionContext&&) = default; + + OpenCLExecutionContext& operator=(const OpenCLExecutionContext&) = default; + OpenCLExecutionContext& operator=(OpenCLExecutionContext&&) = default; + + /** Get associated ocl::Context */ + Context& getContext() const; + /** Get the single default associated ocl::Device */ + Device& getDevice() const; + /** Get the single ocl::Queue that is associated with the ocl::Context and + * the single default ocl::Device + */ + Queue& getQueue() const; + + bool useOpenCL() const; + void setUseOpenCL(bool flag); + + /** Get OpenCL execution context of current thread. + * + * Initialize OpenCL execution context if it is empty + * - create new + * - reuse context of the main thread (threadID = 0) + */ + static OpenCLExecutionContext& getCurrent(); + + /** Get OpenCL execution context of current thread (can be empty) */ + static OpenCLExecutionContext& getCurrentRef(); + + /** Bind this OpenCL execution context to current thread. + * + * Context can't be empty. + * + * @note clFinish is not called for queue of previous execution context + */ + void bind() const; + + /** Creates new execution context with same OpenCV context and device + * + * @param q OpenCL queue + */ + OpenCLExecutionContext cloneWithNewQueue(const ocl::Queue& q) const; + /** @overload */ + OpenCLExecutionContext cloneWithNewQueue() const; + + /** @brief Creates OpenCL execution context + * OpenCV will check if available OpenCL platform has platformName name, + * then assign context to OpenCV. + * The deviceID device will be used as target device and a new command queue will be created. + * + * @note On success, ownership of one reference of the context and device is taken. + * The caller should additionally call `clRetainContext` and/or `clRetainDevice` + * to increase the reference count if it wishes to continue using them. + * + * @param platformName name of OpenCL platform to attach, this string is used to check if platform is available to OpenCV at runtime + * @param platformID ID of platform attached context was created for (cl_platform_id) + * @param context OpenCL context to be attached to OpenCV (cl_context) + * @param deviceID OpenCL device (cl_device_id) + */ + static OpenCLExecutionContext create(const std::string& platformName, void* platformID, void* context, void* deviceID); + + /** @brief Creates OpenCL execution context + * + * @param context non-empty OpenCL context + * @param device non-empty OpenCL device (must be a part of context) + * @param queue non-empty OpenCL queue for provided context and device + */ + static OpenCLExecutionContext create(const Context& context, const Device& device, const ocl::Queue& queue); + /** @overload */ + static OpenCLExecutionContext create(const Context& context, const Device& device); + + struct Impl; + inline bool empty() const { return !p; } + void release(); +protected: + std::shared_ptr p; +}; + +class OpenCLExecutionContextScope +{ + OpenCLExecutionContext ctx_; +public: + inline OpenCLExecutionContextScope(const OpenCLExecutionContext& ctx) + { + CV_Assert(!ctx.empty()); + ctx_ = OpenCLExecutionContext::getCurrentRef(); + ctx.bind(); + } + + inline ~OpenCLExecutionContextScope() + { + if (!ctx_.empty()) + { + ctx_.bind(); + } + } +}; + +#ifdef __OPENCV_BUILD +namespace internal { + +CV_EXPORTS bool isOpenCLForced(); +#define OCL_FORCE_CHECK(condition) (cv::ocl::internal::isOpenCLForced() || (condition)) + +CV_EXPORTS bool isPerformanceCheckBypassed(); +#define OCL_PERFORMANCE_CHECK(condition) (cv::ocl::internal::isPerformanceCheckBypassed() || (condition)) + +CV_EXPORTS bool isCLBuffer(UMat& u); + +} // namespace internal +#endif + +//! @} + +}} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp b/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp index 5366250a55..5334cf1f4f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/ocl_genbase.hpp @@ -1,69 +1,69 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_OPENCL_GENBASE_HPP -#define OPENCV_OPENCL_GENBASE_HPP - -//! @cond IGNORED - -namespace cv { -namespace ocl { - -class ProgramSource; - -namespace internal { - -struct CV_EXPORTS ProgramEntry -{ - const char* module; - const char* name; - const char* programCode; - const char* programHash; - ProgramSource* pProgramSource; - - operator ProgramSource& () const; -}; - -} } } // namespace - -//! @endcond - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_OPENCL_GENBASE_HPP +#define OPENCV_OPENCL_GENBASE_HPP + +//! @cond IGNORED + +namespace cv { +namespace ocl { + +class ProgramSource; + +namespace internal { + +struct CV_EXPORTS ProgramEntry +{ + const char* module; + const char* name; + const char* programCode; + const char* programHash; + ProgramSource* pProgramSource; + + operator ProgramSource& () const; +}; + +} } } // namespace + +//! @endcond + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp index 1369d14b85..14df750fc7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/ocl_defs.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. - -#ifndef OPENCV_CORE_OPENCL_DEFS_HPP -#define OPENCV_CORE_OPENCL_DEFS_HPP - -#include "opencv2/core/utility.hpp" -#include "cvconfig.h" - -namespace cv { namespace ocl { -#ifdef HAVE_OPENCL -/// Call is similar to useOpenCL() but doesn't try to load OpenCL runtime or create OpenCL context -CV_EXPORTS bool isOpenCLActivated(); -#else -static inline bool isOpenCLActivated() { return false; } -#endif -}} // namespace - - -//#define CV_OPENCL_RUN_ASSERT - -#ifdef HAVE_OPENCL - -#ifdef CV_OPENCL_RUN_VERBOSE -#define CV_OCL_RUN_(condition, func, ...) \ - { \ - if (cv::ocl::isOpenCLActivated() && (condition) && func) \ - { \ - printf("%s: OpenCL implementation is running\n", CV_Func); \ - fflush(stdout); \ - CV_IMPL_ADD(CV_IMPL_OCL); \ - return __VA_ARGS__; \ - } \ - else \ - { \ - printf("%s: Plain implementation is running\n", CV_Func); \ - fflush(stdout); \ - } \ - } -#elif defined CV_OPENCL_RUN_ASSERT -#define CV_OCL_RUN_(condition, func, ...) \ - { \ - if (cv::ocl::isOpenCLActivated() && (condition)) \ - { \ - if(func) \ - { \ - CV_IMPL_ADD(CV_IMPL_OCL); \ - } \ - else \ - { \ - CV_Error(cv::Error::StsAssert, #func); \ - } \ - return __VA_ARGS__; \ - } \ - } -#else -#define CV_OCL_RUN_(condition, func, ...) \ -try \ -{ \ - if (cv::ocl::isOpenCLActivated() && (condition) && func) \ - { \ - CV_IMPL_ADD(CV_IMPL_OCL); \ - return __VA_ARGS__; \ - } \ -} \ -catch (const cv::Exception& e) \ -{ \ - CV_UNUSED(e); /* TODO: Add some logging here */ \ -} -#endif - -#else -#define CV_OCL_RUN_(condition, func, ...) -#endif - -#define CV_OCL_RUN(condition, func) CV_OCL_RUN_(condition, func) - -#endif // OPENCV_CORE_OPENCL_DEFS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// Copyright (C) 2014, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef OPENCV_CORE_OPENCL_DEFS_HPP +#define OPENCV_CORE_OPENCL_DEFS_HPP + +#include "opencv2/core/utility.hpp" +#include "cvconfig.h" + +namespace cv { namespace ocl { +#ifdef HAVE_OPENCL +/// Call is similar to useOpenCL() but doesn't try to load OpenCL runtime or create OpenCL context +CV_EXPORTS bool isOpenCLActivated(); +#else +static inline bool isOpenCLActivated() { return false; } +#endif +}} // namespace + + +//#define CV_OPENCL_RUN_ASSERT + +#ifdef HAVE_OPENCL + +#ifdef CV_OPENCL_RUN_VERBOSE +#define CV_OCL_RUN_(condition, func, ...) \ + { \ + if (cv::ocl::isOpenCLActivated() && (condition) && func) \ + { \ + printf("%s: OpenCL implementation is running\n", CV_Func); \ + fflush(stdout); \ + CV_IMPL_ADD(CV_IMPL_OCL); \ + return __VA_ARGS__; \ + } \ + else \ + { \ + printf("%s: Plain implementation is running\n", CV_Func); \ + fflush(stdout); \ + } \ + } +#elif defined CV_OPENCL_RUN_ASSERT +#define CV_OCL_RUN_(condition, func, ...) \ + { \ + if (cv::ocl::isOpenCLActivated() && (condition)) \ + { \ + if(func) \ + { \ + CV_IMPL_ADD(CV_IMPL_OCL); \ + } \ + else \ + { \ + CV_Error(cv::Error::StsAssert, #func); \ + } \ + return __VA_ARGS__; \ + } \ + } +#else +#define CV_OCL_RUN_(condition, func, ...) \ +try \ +{ \ + if (cv::ocl::isOpenCLActivated() && (condition) && func) \ + { \ + CV_IMPL_ADD(CV_IMPL_OCL); \ + return __VA_ARGS__; \ + } \ +} \ +catch (const cv::Exception& e) \ +{ \ + CV_UNUSED(e); /* TODO: Add some logging here */ \ +} +#endif + +#else +#define CV_OCL_RUN_(condition, func, ...) +#endif + +#define CV_OCL_RUN(condition, func) CV_OCL_RUN_(condition, func) + +#endif // OPENCV_CORE_OPENCL_DEFS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp index 06c5f9b94d..845efba9fc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_info.hpp @@ -1,213 +1,213 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#include -#include - -#include -#include - -#ifndef DUMP_CONFIG_PROPERTY -#define DUMP_CONFIG_PROPERTY(...) -#endif - -#ifndef DUMP_MESSAGE_STDOUT -#define DUMP_MESSAGE_STDOUT(...) do { std::cout << __VA_ARGS__ << std::endl; } while (false) -#endif - -namespace cv { - -namespace { -static std::string bytesToStringRepr(size_t value) -{ - size_t b = value % 1024; - value /= 1024; - - size_t kb = value % 1024; - value /= 1024; - - size_t mb = value % 1024; - value /= 1024; - - size_t gb = value; - - std::ostringstream stream; - - if (gb > 0) - stream << gb << " GB "; - if (mb > 0) - stream << mb << " MB "; - if (kb > 0) - stream << kb << " KB "; - if (b > 0) - stream << b << " B"; - - std::string s = stream.str(); - if (s[s.size() - 1] == ' ') - s = s.substr(0, s.size() - 1); - return s; -} - -static String getDeviceTypeString(const cv::ocl::Device& device) -{ - if (device.type() == cv::ocl::Device::TYPE_CPU) { - return "CPU"; - } - - if (device.type() == cv::ocl::Device::TYPE_GPU) { - if (device.hostUnifiedMemory()) { - return "iGPU"; - } else { - return "dGPU"; - } - } - - return "unknown"; -} -} // namespace - -static void dumpOpenCLInformation() -{ - using namespace cv::ocl; - - try - { - if (!haveOpenCL() || !useOpenCL()) - { - DUMP_MESSAGE_STDOUT("OpenCL is disabled"); - DUMP_CONFIG_PROPERTY("cv_ocl", "disabled"); - return; - } - - std::vector platforms; - cv::ocl::getPlatfomsInfo(platforms); - if (platforms.empty()) - { - DUMP_MESSAGE_STDOUT("OpenCL is not available"); - DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); - return; - } - - DUMP_MESSAGE_STDOUT("OpenCL Platforms: "); - for (size_t i = 0; i < platforms.size(); i++) - { - const PlatformInfo* platform = &platforms[i]; - DUMP_MESSAGE_STDOUT(" " << platform->name()); - Device current_device; - for (int j = 0; j < platform->deviceNumber(); j++) - { - platform->getDevice(current_device, j); - String deviceTypeStr = getDeviceTypeString(current_device); - DUMP_MESSAGE_STDOUT( " " << deviceTypeStr << ": " << current_device.name() << " (" << current_device.version() << ")"); - DUMP_CONFIG_PROPERTY( cv::format("cv_ocl_platform_%d_device_%d", (int)i, j ), - cv::format("(Platform=%s)(Type=%s)(Name=%s)(Version=%s)", - platform->name().c_str(), deviceTypeStr.c_str(), current_device.name().c_str(), current_device.version().c_str()) ); - } - } - const Device& device = Device::getDefault(); - if (!device.available()) - CV_Error(Error::OpenCLInitError, "OpenCL device is not available"); - - DUMP_MESSAGE_STDOUT("Current OpenCL device: "); - - String deviceTypeStr = getDeviceTypeString(device); - DUMP_MESSAGE_STDOUT(" Type = " << deviceTypeStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceType", deviceTypeStr); - - DUMP_MESSAGE_STDOUT(" Name = " << device.name()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceName", device.name()); - - DUMP_MESSAGE_STDOUT(" Version = " << device.version()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceVersion", device.version()); - - DUMP_MESSAGE_STDOUT(" Driver version = " << device.driverVersion()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_driverVersion", device.driverVersion()); - - DUMP_MESSAGE_STDOUT(" Address bits = " << device.addressBits()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_addressBits", device.addressBits()); - - DUMP_MESSAGE_STDOUT(" Compute units = " << device.maxComputeUnits()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_maxComputeUnits", device.maxComputeUnits()); - - DUMP_MESSAGE_STDOUT(" Max work group size = " << device.maxWorkGroupSize()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_maxWorkGroupSize", device.maxWorkGroupSize()); - - std::string localMemorySizeStr = bytesToStringRepr(device.localMemSize()); - DUMP_MESSAGE_STDOUT(" Local memory size = " << localMemorySizeStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_localMemSize", device.localMemSize()); - - std::string maxMemAllocSizeStr = bytesToStringRepr(device.maxMemAllocSize()); - DUMP_MESSAGE_STDOUT(" Max memory allocation size = " << maxMemAllocSizeStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_maxMemAllocSize", device.maxMemAllocSize()); - - const char* doubleSupportStr = device.hasFP64() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Double support = " << doubleSupportStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_haveDoubleSupport", device.hasFP64()); - - const char* halfSupportStr = device.hasFP16() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Half support = " << halfSupportStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_haveHalfSupport", device.hasFP16()); - - const char* isUnifiedMemoryStr = device.hostUnifiedMemory() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Host unified memory = " << isUnifiedMemoryStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_hostUnifiedMemory", device.hostUnifiedMemory()); - - DUMP_MESSAGE_STDOUT(" Device extensions:"); - String extensionsStr = device.extensions(); - size_t pos = 0; - while (pos < extensionsStr.size()) - { - size_t pos2 = extensionsStr.find(' ', pos); - if (pos2 == String::npos) - pos2 = extensionsStr.size(); - if (pos2 > pos) - { - String extensionName = extensionsStr.substr(pos, pos2 - pos); - DUMP_MESSAGE_STDOUT(" " << extensionName); - } - pos = pos2 + 1; - } - DUMP_CONFIG_PROPERTY("cv_ocl_current_extensions", extensionsStr); - - const char* haveAmdBlasStr = haveAmdBlas() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Has AMD Blas = " << haveAmdBlasStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdBlas", haveAmdBlas()); - - const char* haveAmdFftStr = haveAmdFft() ? "Yes" : "No"; - DUMP_MESSAGE_STDOUT(" Has AMD Fft = " << haveAmdFftStr); - DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdFft", haveAmdFft()); - - - DUMP_MESSAGE_STDOUT(" Preferred vector width char = " << device.preferredVectorWidthChar()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthChar", device.preferredVectorWidthChar()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width short = " << device.preferredVectorWidthShort()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthShort", device.preferredVectorWidthShort()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width int = " << device.preferredVectorWidthInt()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthInt", device.preferredVectorWidthInt()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width long = " << device.preferredVectorWidthLong()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthLong", device.preferredVectorWidthLong()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width float = " << device.preferredVectorWidthFloat()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthFloat", device.preferredVectorWidthFloat()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width double = " << device.preferredVectorWidthDouble()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthDouble", device.preferredVectorWidthDouble()); - - DUMP_MESSAGE_STDOUT(" Preferred vector width half = " << device.preferredVectorWidthHalf()); - DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthHalf", device.preferredVectorWidthHalf()); - } - catch (...) - { - DUMP_MESSAGE_STDOUT("Exception. Can't dump OpenCL info"); - DUMP_MESSAGE_STDOUT("OpenCL device not available"); - DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); - } -} -#undef DUMP_MESSAGE_STDOUT -#undef DUMP_CONFIG_PROPERTY - -} // namespace +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#include +#include + +#include +#include + +#ifndef DUMP_CONFIG_PROPERTY +#define DUMP_CONFIG_PROPERTY(...) +#endif + +#ifndef DUMP_MESSAGE_STDOUT +#define DUMP_MESSAGE_STDOUT(...) do { std::cout << __VA_ARGS__ << std::endl; } while (false) +#endif + +namespace cv { + +namespace { +static std::string bytesToStringRepr(size_t value) +{ + size_t b = value % 1024; + value /= 1024; + + size_t kb = value % 1024; + value /= 1024; + + size_t mb = value % 1024; + value /= 1024; + + size_t gb = value; + + std::ostringstream stream; + + if (gb > 0) + stream << gb << " GB "; + if (mb > 0) + stream << mb << " MB "; + if (kb > 0) + stream << kb << " KB "; + if (b > 0) + stream << b << " B"; + + std::string s = stream.str(); + if (s[s.size() - 1] == ' ') + s = s.substr(0, s.size() - 1); + return s; +} + +static String getDeviceTypeString(const cv::ocl::Device& device) +{ + if (device.type() == cv::ocl::Device::TYPE_CPU) { + return "CPU"; + } + + if (device.type() == cv::ocl::Device::TYPE_GPU) { + if (device.hostUnifiedMemory()) { + return "iGPU"; + } else { + return "dGPU"; + } + } + + return "unknown"; +} +} // namespace + +static void dumpOpenCLInformation() +{ + using namespace cv::ocl; + + try + { + if (!haveOpenCL() || !useOpenCL()) + { + DUMP_MESSAGE_STDOUT("OpenCL is disabled"); + DUMP_CONFIG_PROPERTY("cv_ocl", "disabled"); + return; + } + + std::vector platforms; + cv::ocl::getPlatfomsInfo(platforms); + if (platforms.empty()) + { + DUMP_MESSAGE_STDOUT("OpenCL is not available"); + DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); + return; + } + + DUMP_MESSAGE_STDOUT("OpenCL Platforms: "); + for (size_t i = 0; i < platforms.size(); i++) + { + const PlatformInfo* platform = &platforms[i]; + DUMP_MESSAGE_STDOUT(" " << platform->name()); + Device current_device; + for (int j = 0; j < platform->deviceNumber(); j++) + { + platform->getDevice(current_device, j); + String deviceTypeStr = getDeviceTypeString(current_device); + DUMP_MESSAGE_STDOUT( " " << deviceTypeStr << ": " << current_device.name() << " (" << current_device.version() << ")"); + DUMP_CONFIG_PROPERTY( cv::format("cv_ocl_platform_%d_device_%d", (int)i, j ), + cv::format("(Platform=%s)(Type=%s)(Name=%s)(Version=%s)", + platform->name().c_str(), deviceTypeStr.c_str(), current_device.name().c_str(), current_device.version().c_str()) ); + } + } + const Device& device = Device::getDefault(); + if (!device.available()) + CV_Error(Error::OpenCLInitError, "OpenCL device is not available"); + + DUMP_MESSAGE_STDOUT("Current OpenCL device: "); + + String deviceTypeStr = getDeviceTypeString(device); + DUMP_MESSAGE_STDOUT(" Type = " << deviceTypeStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceType", deviceTypeStr); + + DUMP_MESSAGE_STDOUT(" Name = " << device.name()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceName", device.name()); + + DUMP_MESSAGE_STDOUT(" Version = " << device.version()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_deviceVersion", device.version()); + + DUMP_MESSAGE_STDOUT(" Driver version = " << device.driverVersion()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_driverVersion", device.driverVersion()); + + DUMP_MESSAGE_STDOUT(" Address bits = " << device.addressBits()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_addressBits", device.addressBits()); + + DUMP_MESSAGE_STDOUT(" Compute units = " << device.maxComputeUnits()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_maxComputeUnits", device.maxComputeUnits()); + + DUMP_MESSAGE_STDOUT(" Max work group size = " << device.maxWorkGroupSize()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_maxWorkGroupSize", device.maxWorkGroupSize()); + + std::string localMemorySizeStr = bytesToStringRepr(device.localMemSize()); + DUMP_MESSAGE_STDOUT(" Local memory size = " << localMemorySizeStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_localMemSize", device.localMemSize()); + + std::string maxMemAllocSizeStr = bytesToStringRepr(device.maxMemAllocSize()); + DUMP_MESSAGE_STDOUT(" Max memory allocation size = " << maxMemAllocSizeStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_maxMemAllocSize", device.maxMemAllocSize()); + + const char* doubleSupportStr = device.hasFP64() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Double support = " << doubleSupportStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_haveDoubleSupport", device.hasFP64()); + + const char* halfSupportStr = device.hasFP16() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Half support = " << halfSupportStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_haveHalfSupport", device.hasFP16()); + + const char* isUnifiedMemoryStr = device.hostUnifiedMemory() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Host unified memory = " << isUnifiedMemoryStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_hostUnifiedMemory", device.hostUnifiedMemory()); + + DUMP_MESSAGE_STDOUT(" Device extensions:"); + String extensionsStr = device.extensions(); + size_t pos = 0; + while (pos < extensionsStr.size()) + { + size_t pos2 = extensionsStr.find(' ', pos); + if (pos2 == String::npos) + pos2 = extensionsStr.size(); + if (pos2 > pos) + { + String extensionName = extensionsStr.substr(pos, pos2 - pos); + DUMP_MESSAGE_STDOUT(" " << extensionName); + } + pos = pos2 + 1; + } + DUMP_CONFIG_PROPERTY("cv_ocl_current_extensions", extensionsStr); + + const char* haveAmdBlasStr = haveAmdBlas() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Has AMD Blas = " << haveAmdBlasStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdBlas", haveAmdBlas()); + + const char* haveAmdFftStr = haveAmdFft() ? "Yes" : "No"; + DUMP_MESSAGE_STDOUT(" Has AMD Fft = " << haveAmdFftStr); + DUMP_CONFIG_PROPERTY("cv_ocl_current_AmdFft", haveAmdFft()); + + + DUMP_MESSAGE_STDOUT(" Preferred vector width char = " << device.preferredVectorWidthChar()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthChar", device.preferredVectorWidthChar()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width short = " << device.preferredVectorWidthShort()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthShort", device.preferredVectorWidthShort()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width int = " << device.preferredVectorWidthInt()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthInt", device.preferredVectorWidthInt()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width long = " << device.preferredVectorWidthLong()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthLong", device.preferredVectorWidthLong()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width float = " << device.preferredVectorWidthFloat()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthFloat", device.preferredVectorWidthFloat()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width double = " << device.preferredVectorWidthDouble()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthDouble", device.preferredVectorWidthDouble()); + + DUMP_MESSAGE_STDOUT(" Preferred vector width half = " << device.preferredVectorWidthHalf()); + DUMP_CONFIG_PROPERTY("cv_ocl_current_preferredVectorWidthHalf", device.preferredVectorWidthHalf()); + } + catch (...) + { + DUMP_MESSAGE_STDOUT("Exception. Can't dump OpenCL info"); + DUMP_MESSAGE_STDOUT("OpenCL device not available"); + DUMP_CONFIG_PROPERTY("cv_ocl", "not available"); + } +} +#undef DUMP_MESSAGE_STDOUT +#undef DUMP_CONFIG_PROPERTY + +} // namespace diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp index f6b840e3ba..7453082a67 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/opencl_svm.hpp @@ -1,81 +1,81 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OPENCL_SVM_HPP -#define OPENCV_CORE_OPENCL_SVM_HPP - -// -// Internal usage only (binary compatibility is not guaranteed) -// -#ifndef __OPENCV_BUILD -#error Internal header file -#endif - -#if defined(HAVE_OPENCL) && defined(HAVE_OPENCL_SVM) -#include "runtime/opencl_core.hpp" -#include "runtime/opencl_svm_20.hpp" -#include "runtime/opencl_svm_hsa_extension.hpp" - -namespace cv { namespace ocl { namespace svm { - -struct SVMCapabilities -{ - enum Value - { - SVM_COARSE_GRAIN_BUFFER = (1 << 0), - SVM_FINE_GRAIN_BUFFER = (1 << 1), - SVM_FINE_GRAIN_SYSTEM = (1 << 2), - SVM_ATOMICS = (1 << 3), - }; - int value_; - - SVMCapabilities(int capabilities = 0) : value_(capabilities) { } - operator int() const { return value_; } - - inline bool isNoSVMSupport() const { return value_ == 0; } - inline bool isSupportCoarseGrainBuffer() const { return (value_ & SVM_COARSE_GRAIN_BUFFER) != 0; } - inline bool isSupportFineGrainBuffer() const { return (value_ & SVM_FINE_GRAIN_BUFFER) != 0; } - inline bool isSupportFineGrainSystem() const { return (value_ & SVM_FINE_GRAIN_SYSTEM) != 0; } - inline bool isSupportAtomics() const { return (value_ & SVM_ATOMICS) != 0; } -}; - -CV_EXPORTS const SVMCapabilities getSVMCapabilitites(const ocl::Context& context); - -struct SVMFunctions -{ - clSVMAllocAMD_fn fn_clSVMAlloc; - clSVMFreeAMD_fn fn_clSVMFree; - clSetKernelArgSVMPointerAMD_fn fn_clSetKernelArgSVMPointer; - //clSetKernelExecInfoAMD_fn fn_clSetKernelExecInfo; - //clEnqueueSVMFreeAMD_fn fn_clEnqueueSVMFree; - clEnqueueSVMMemcpyAMD_fn fn_clEnqueueSVMMemcpy; - clEnqueueSVMMemFillAMD_fn fn_clEnqueueSVMMemFill; - clEnqueueSVMMapAMD_fn fn_clEnqueueSVMMap; - clEnqueueSVMUnmapAMD_fn fn_clEnqueueSVMUnmap; - - inline SVMFunctions() - : fn_clSVMAlloc(NULL), fn_clSVMFree(NULL), - fn_clSetKernelArgSVMPointer(NULL), /*fn_clSetKernelExecInfo(NULL),*/ - /*fn_clEnqueueSVMFree(NULL),*/ fn_clEnqueueSVMMemcpy(NULL), fn_clEnqueueSVMMemFill(NULL), - fn_clEnqueueSVMMap(NULL), fn_clEnqueueSVMUnmap(NULL) - { - // nothing - } - - inline bool isValid() const - { - return fn_clSVMAlloc != NULL && fn_clSVMFree && fn_clSetKernelArgSVMPointer && - /*fn_clSetKernelExecInfo && fn_clEnqueueSVMFree &&*/ fn_clEnqueueSVMMemcpy && - fn_clEnqueueSVMMemFill && fn_clEnqueueSVMMap && fn_clEnqueueSVMUnmap; - } -}; - -// We should guarantee that SVMFunctions lifetime is not less than context's lifetime -CV_EXPORTS const SVMFunctions* getSVMFunctions(const ocl::Context& context); - -CV_EXPORTS bool useSVM(UMatUsageFlags usageFlags); - -}}} //namespace cv::ocl::svm -#endif - -#endif // OPENCV_CORE_OPENCL_SVM_HPP -/* End of file. */ +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OPENCL_SVM_HPP +#define OPENCV_CORE_OPENCL_SVM_HPP + +// +// Internal usage only (binary compatibility is not guaranteed) +// +#ifndef __OPENCV_BUILD +#error Internal header file +#endif + +#if defined(HAVE_OPENCL) && defined(HAVE_OPENCL_SVM) +#include "runtime/opencl_core.hpp" +#include "runtime/opencl_svm_20.hpp" +#include "runtime/opencl_svm_hsa_extension.hpp" + +namespace cv { namespace ocl { namespace svm { + +struct SVMCapabilities +{ + enum Value + { + SVM_COARSE_GRAIN_BUFFER = (1 << 0), + SVM_FINE_GRAIN_BUFFER = (1 << 1), + SVM_FINE_GRAIN_SYSTEM = (1 << 2), + SVM_ATOMICS = (1 << 3), + }; + int value_; + + SVMCapabilities(int capabilities = 0) : value_(capabilities) { } + operator int() const { return value_; } + + inline bool isNoSVMSupport() const { return value_ == 0; } + inline bool isSupportCoarseGrainBuffer() const { return (value_ & SVM_COARSE_GRAIN_BUFFER) != 0; } + inline bool isSupportFineGrainBuffer() const { return (value_ & SVM_FINE_GRAIN_BUFFER) != 0; } + inline bool isSupportFineGrainSystem() const { return (value_ & SVM_FINE_GRAIN_SYSTEM) != 0; } + inline bool isSupportAtomics() const { return (value_ & SVM_ATOMICS) != 0; } +}; + +CV_EXPORTS const SVMCapabilities getSVMCapabilitites(const ocl::Context& context); + +struct SVMFunctions +{ + clSVMAllocAMD_fn fn_clSVMAlloc; + clSVMFreeAMD_fn fn_clSVMFree; + clSetKernelArgSVMPointerAMD_fn fn_clSetKernelArgSVMPointer; + //clSetKernelExecInfoAMD_fn fn_clSetKernelExecInfo; + //clEnqueueSVMFreeAMD_fn fn_clEnqueueSVMFree; + clEnqueueSVMMemcpyAMD_fn fn_clEnqueueSVMMemcpy; + clEnqueueSVMMemFillAMD_fn fn_clEnqueueSVMMemFill; + clEnqueueSVMMapAMD_fn fn_clEnqueueSVMMap; + clEnqueueSVMUnmapAMD_fn fn_clEnqueueSVMUnmap; + + inline SVMFunctions() + : fn_clSVMAlloc(NULL), fn_clSVMFree(NULL), + fn_clSetKernelArgSVMPointer(NULL), /*fn_clSetKernelExecInfo(NULL),*/ + /*fn_clEnqueueSVMFree(NULL),*/ fn_clEnqueueSVMMemcpy(NULL), fn_clEnqueueSVMMemFill(NULL), + fn_clEnqueueSVMMap(NULL), fn_clEnqueueSVMUnmap(NULL) + { + // nothing + } + + inline bool isValid() const + { + return fn_clSVMAlloc != NULL && fn_clSVMFree && fn_clSetKernelArgSVMPointer && + /*fn_clSetKernelExecInfo && fn_clEnqueueSVMFree &&*/ fn_clEnqueueSVMMemcpy && + fn_clEnqueueSVMMemFill && fn_clEnqueueSVMMap && fn_clEnqueueSVMUnmap; + } +}; + +// We should guarantee that SVMFunctions lifetime is not less than context's lifetime +CV_EXPORTS const SVMFunctions* getSVMFunctions(const ocl::Context& context); + +CV_EXPORTS bool useSVM(UMatUsageFlags usageFlags); + +}}} //namespace cv::ocl::svm +#endif + +#endif // OPENCV_CORE_OPENCL_SVM_HPP +/* End of file. */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp index 37e019110d..2749927bea 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clblas.hpp @@ -1,602 +1,602 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP -#error "Invalid usage" -#endif - -// generated by parser_clblas.py -#define clblasCaxpy clblasCaxpy_ -#define clblasCcopy clblasCcopy_ -#define clblasCdotc clblasCdotc_ -#define clblasCdotu clblasCdotu_ -#define clblasCgbmv clblasCgbmv_ -#define clblasCgemm clblasCgemm_ -#define clblasCgemv clblasCgemv_ -#define clblasCgerc clblasCgerc_ -#define clblasCgeru clblasCgeru_ -#define clblasChbmv clblasChbmv_ -#define clblasChemm clblasChemm_ -#define clblasChemv clblasChemv_ -#define clblasCher clblasCher_ -#define clblasCher2 clblasCher2_ -#define clblasCher2k clblasCher2k_ -#define clblasCherk clblasCherk_ -#define clblasChpmv clblasChpmv_ -#define clblasChpr clblasChpr_ -#define clblasChpr2 clblasChpr2_ -#define clblasCrotg clblasCrotg_ -#define clblasCscal clblasCscal_ -#define clblasCsrot clblasCsrot_ -#define clblasCsscal clblasCsscal_ -#define clblasCswap clblasCswap_ -#define clblasCsymm clblasCsymm_ -#define clblasCsyr2k clblasCsyr2k_ -#define clblasCsyrk clblasCsyrk_ -#define clblasCtbmv clblasCtbmv_ -#define clblasCtbsv clblasCtbsv_ -#define clblasCtpmv clblasCtpmv_ -#define clblasCtpsv clblasCtpsv_ -#define clblasCtrmm clblasCtrmm_ -#define clblasCtrmv clblasCtrmv_ -#define clblasCtrsm clblasCtrsm_ -#define clblasCtrsv clblasCtrsv_ -#define clblasDasum clblasDasum_ -#define clblasDaxpy clblasDaxpy_ -#define clblasDcopy clblasDcopy_ -#define clblasDdot clblasDdot_ -#define clblasDgbmv clblasDgbmv_ -#define clblasDgemm clblasDgemm_ -#define clblasDgemv clblasDgemv_ -#define clblasDger clblasDger_ -#define clblasDnrm2 clblasDnrm2_ -#define clblasDrot clblasDrot_ -#define clblasDrotg clblasDrotg_ -#define clblasDrotm clblasDrotm_ -#define clblasDrotmg clblasDrotmg_ -#define clblasDsbmv clblasDsbmv_ -#define clblasDscal clblasDscal_ -#define clblasDspmv clblasDspmv_ -#define clblasDspr clblasDspr_ -#define clblasDspr2 clblasDspr2_ -#define clblasDswap clblasDswap_ -#define clblasDsymm clblasDsymm_ -#define clblasDsymv clblasDsymv_ -#define clblasDsyr clblasDsyr_ -#define clblasDsyr2 clblasDsyr2_ -#define clblasDsyr2k clblasDsyr2k_ -#define clblasDsyrk clblasDsyrk_ -#define clblasDtbmv clblasDtbmv_ -#define clblasDtbsv clblasDtbsv_ -#define clblasDtpmv clblasDtpmv_ -#define clblasDtpsv clblasDtpsv_ -#define clblasDtrmm clblasDtrmm_ -#define clblasDtrmv clblasDtrmv_ -#define clblasDtrsm clblasDtrsm_ -#define clblasDtrsv clblasDtrsv_ -#define clblasDzasum clblasDzasum_ -#define clblasDznrm2 clblasDznrm2_ -#define clblasGetVersion clblasGetVersion_ -#define clblasSasum clblasSasum_ -#define clblasSaxpy clblasSaxpy_ -#define clblasScasum clblasScasum_ -#define clblasScnrm2 clblasScnrm2_ -#define clblasScopy clblasScopy_ -#define clblasSdot clblasSdot_ -#define clblasSetup clblasSetup_ -#define clblasSgbmv clblasSgbmv_ -#define clblasSgemm clblasSgemm_ -#define clblasSgemv clblasSgemv_ -#define clblasSger clblasSger_ -#define clblasSnrm2 clblasSnrm2_ -#define clblasSrot clblasSrot_ -#define clblasSrotg clblasSrotg_ -#define clblasSrotm clblasSrotm_ -#define clblasSrotmg clblasSrotmg_ -#define clblasSsbmv clblasSsbmv_ -#define clblasSscal clblasSscal_ -#define clblasSspmv clblasSspmv_ -#define clblasSspr clblasSspr_ -#define clblasSspr2 clblasSspr2_ -#define clblasSswap clblasSswap_ -#define clblasSsymm clblasSsymm_ -#define clblasSsymv clblasSsymv_ -#define clblasSsyr clblasSsyr_ -#define clblasSsyr2 clblasSsyr2_ -#define clblasSsyr2k clblasSsyr2k_ -#define clblasSsyrk clblasSsyrk_ -#define clblasStbmv clblasStbmv_ -#define clblasStbsv clblasStbsv_ -#define clblasStpmv clblasStpmv_ -#define clblasStpsv clblasStpsv_ -#define clblasStrmm clblasStrmm_ -#define clblasStrmv clblasStrmv_ -#define clblasStrsm clblasStrsm_ -#define clblasStrsv clblasStrsv_ -#define clblasTeardown clblasTeardown_ -#define clblasZaxpy clblasZaxpy_ -#define clblasZcopy clblasZcopy_ -#define clblasZdotc clblasZdotc_ -#define clblasZdotu clblasZdotu_ -#define clblasZdrot clblasZdrot_ -#define clblasZdscal clblasZdscal_ -#define clblasZgbmv clblasZgbmv_ -#define clblasZgemm clblasZgemm_ -#define clblasZgemv clblasZgemv_ -#define clblasZgerc clblasZgerc_ -#define clblasZgeru clblasZgeru_ -#define clblasZhbmv clblasZhbmv_ -#define clblasZhemm clblasZhemm_ -#define clblasZhemv clblasZhemv_ -#define clblasZher clblasZher_ -#define clblasZher2 clblasZher2_ -#define clblasZher2k clblasZher2k_ -#define clblasZherk clblasZherk_ -#define clblasZhpmv clblasZhpmv_ -#define clblasZhpr clblasZhpr_ -#define clblasZhpr2 clblasZhpr2_ -#define clblasZrotg clblasZrotg_ -#define clblasZscal clblasZscal_ -#define clblasZswap clblasZswap_ -#define clblasZsymm clblasZsymm_ -#define clblasZsyr2k clblasZsyr2k_ -#define clblasZsyrk clblasZsyrk_ -#define clblasZtbmv clblasZtbmv_ -#define clblasZtbsv clblasZtbsv_ -#define clblasZtpmv clblasZtpmv_ -#define clblasZtpsv clblasZtpsv_ -#define clblasZtrmm clblasZtrmm_ -#define clblasZtrmv clblasZtrmv_ -#define clblasZtrsm clblasZtrsm_ -#define clblasZtrsv clblasZtrsv_ -#define clblasiCamax clblasiCamax_ -#define clblasiDamax clblasiDamax_ -#define clblasiSamax clblasiSamax_ -#define clblasiZamax clblasiZamax_ - -#include - -// generated by parser_clblas.py -#undef clblasCaxpy -//#define clblasCaxpy clblasCaxpy_pfn -#undef clblasCcopy -//#define clblasCcopy clblasCcopy_pfn -#undef clblasCdotc -//#define clblasCdotc clblasCdotc_pfn -#undef clblasCdotu -//#define clblasCdotu clblasCdotu_pfn -#undef clblasCgbmv -//#define clblasCgbmv clblasCgbmv_pfn -#undef clblasCgemm -#define clblasCgemm clblasCgemm_pfn -#undef clblasCgemv -//#define clblasCgemv clblasCgemv_pfn -#undef clblasCgerc -//#define clblasCgerc clblasCgerc_pfn -#undef clblasCgeru -//#define clblasCgeru clblasCgeru_pfn -#undef clblasChbmv -//#define clblasChbmv clblasChbmv_pfn -#undef clblasChemm -//#define clblasChemm clblasChemm_pfn -#undef clblasChemv -//#define clblasChemv clblasChemv_pfn -#undef clblasCher -//#define clblasCher clblasCher_pfn -#undef clblasCher2 -//#define clblasCher2 clblasCher2_pfn -#undef clblasCher2k -//#define clblasCher2k clblasCher2k_pfn -#undef clblasCherk -//#define clblasCherk clblasCherk_pfn -#undef clblasChpmv -//#define clblasChpmv clblasChpmv_pfn -#undef clblasChpr -//#define clblasChpr clblasChpr_pfn -#undef clblasChpr2 -//#define clblasChpr2 clblasChpr2_pfn -#undef clblasCrotg -//#define clblasCrotg clblasCrotg_pfn -#undef clblasCscal -//#define clblasCscal clblasCscal_pfn -#undef clblasCsrot -//#define clblasCsrot clblasCsrot_pfn -#undef clblasCsscal -//#define clblasCsscal clblasCsscal_pfn -#undef clblasCswap -//#define clblasCswap clblasCswap_pfn -#undef clblasCsymm -//#define clblasCsymm clblasCsymm_pfn -#undef clblasCsyr2k -//#define clblasCsyr2k clblasCsyr2k_pfn -#undef clblasCsyrk -//#define clblasCsyrk clblasCsyrk_pfn -#undef clblasCtbmv -//#define clblasCtbmv clblasCtbmv_pfn -#undef clblasCtbsv -//#define clblasCtbsv clblasCtbsv_pfn -#undef clblasCtpmv -//#define clblasCtpmv clblasCtpmv_pfn -#undef clblasCtpsv -//#define clblasCtpsv clblasCtpsv_pfn -#undef clblasCtrmm -//#define clblasCtrmm clblasCtrmm_pfn -#undef clblasCtrmv -//#define clblasCtrmv clblasCtrmv_pfn -#undef clblasCtrsm -//#define clblasCtrsm clblasCtrsm_pfn -#undef clblasCtrsv -//#define clblasCtrsv clblasCtrsv_pfn -#undef clblasDasum -//#define clblasDasum clblasDasum_pfn -#undef clblasDaxpy -//#define clblasDaxpy clblasDaxpy_pfn -#undef clblasDcopy -//#define clblasDcopy clblasDcopy_pfn -#undef clblasDdot -//#define clblasDdot clblasDdot_pfn -#undef clblasDgbmv -//#define clblasDgbmv clblasDgbmv_pfn -#undef clblasDgemm -#define clblasDgemm clblasDgemm_pfn -#undef clblasDgemv -//#define clblasDgemv clblasDgemv_pfn -#undef clblasDger -//#define clblasDger clblasDger_pfn -#undef clblasDnrm2 -//#define clblasDnrm2 clblasDnrm2_pfn -#undef clblasDrot -//#define clblasDrot clblasDrot_pfn -#undef clblasDrotg -//#define clblasDrotg clblasDrotg_pfn -#undef clblasDrotm -//#define clblasDrotm clblasDrotm_pfn -#undef clblasDrotmg -//#define clblasDrotmg clblasDrotmg_pfn -#undef clblasDsbmv -//#define clblasDsbmv clblasDsbmv_pfn -#undef clblasDscal -//#define clblasDscal clblasDscal_pfn -#undef clblasDspmv -//#define clblasDspmv clblasDspmv_pfn -#undef clblasDspr -//#define clblasDspr clblasDspr_pfn -#undef clblasDspr2 -//#define clblasDspr2 clblasDspr2_pfn -#undef clblasDswap -//#define clblasDswap clblasDswap_pfn -#undef clblasDsymm -//#define clblasDsymm clblasDsymm_pfn -#undef clblasDsymv -//#define clblasDsymv clblasDsymv_pfn -#undef clblasDsyr -//#define clblasDsyr clblasDsyr_pfn -#undef clblasDsyr2 -//#define clblasDsyr2 clblasDsyr2_pfn -#undef clblasDsyr2k -//#define clblasDsyr2k clblasDsyr2k_pfn -#undef clblasDsyrk -//#define clblasDsyrk clblasDsyrk_pfn -#undef clblasDtbmv -//#define clblasDtbmv clblasDtbmv_pfn -#undef clblasDtbsv -//#define clblasDtbsv clblasDtbsv_pfn -#undef clblasDtpmv -//#define clblasDtpmv clblasDtpmv_pfn -#undef clblasDtpsv -//#define clblasDtpsv clblasDtpsv_pfn -#undef clblasDtrmm -//#define clblasDtrmm clblasDtrmm_pfn -#undef clblasDtrmv -//#define clblasDtrmv clblasDtrmv_pfn -#undef clblasDtrsm -//#define clblasDtrsm clblasDtrsm_pfn -#undef clblasDtrsv -//#define clblasDtrsv clblasDtrsv_pfn -#undef clblasDzasum -//#define clblasDzasum clblasDzasum_pfn -#undef clblasDznrm2 -//#define clblasDznrm2 clblasDznrm2_pfn -#undef clblasGetVersion -//#define clblasGetVersion clblasGetVersion_pfn -#undef clblasSasum -//#define clblasSasum clblasSasum_pfn -#undef clblasSaxpy -//#define clblasSaxpy clblasSaxpy_pfn -#undef clblasScasum -//#define clblasScasum clblasScasum_pfn -#undef clblasScnrm2 -//#define clblasScnrm2 clblasScnrm2_pfn -#undef clblasScopy -//#define clblasScopy clblasScopy_pfn -#undef clblasSdot -//#define clblasSdot clblasSdot_pfn -#undef clblasSetup -#define clblasSetup clblasSetup_pfn -#undef clblasSgbmv -//#define clblasSgbmv clblasSgbmv_pfn -#undef clblasSgemm -#define clblasSgemm clblasSgemm_pfn -#undef clblasSgemv -//#define clblasSgemv clblasSgemv_pfn -#undef clblasSger -//#define clblasSger clblasSger_pfn -#undef clblasSnrm2 -//#define clblasSnrm2 clblasSnrm2_pfn -#undef clblasSrot -//#define clblasSrot clblasSrot_pfn -#undef clblasSrotg -//#define clblasSrotg clblasSrotg_pfn -#undef clblasSrotm -//#define clblasSrotm clblasSrotm_pfn -#undef clblasSrotmg -//#define clblasSrotmg clblasSrotmg_pfn -#undef clblasSsbmv -//#define clblasSsbmv clblasSsbmv_pfn -#undef clblasSscal -//#define clblasSscal clblasSscal_pfn -#undef clblasSspmv -//#define clblasSspmv clblasSspmv_pfn -#undef clblasSspr -//#define clblasSspr clblasSspr_pfn -#undef clblasSspr2 -//#define clblasSspr2 clblasSspr2_pfn -#undef clblasSswap -//#define clblasSswap clblasSswap_pfn -#undef clblasSsymm -//#define clblasSsymm clblasSsymm_pfn -#undef clblasSsymv -//#define clblasSsymv clblasSsymv_pfn -#undef clblasSsyr -//#define clblasSsyr clblasSsyr_pfn -#undef clblasSsyr2 -//#define clblasSsyr2 clblasSsyr2_pfn -#undef clblasSsyr2k -//#define clblasSsyr2k clblasSsyr2k_pfn -#undef clblasSsyrk -//#define clblasSsyrk clblasSsyrk_pfn -#undef clblasStbmv -//#define clblasStbmv clblasStbmv_pfn -#undef clblasStbsv -//#define clblasStbsv clblasStbsv_pfn -#undef clblasStpmv -//#define clblasStpmv clblasStpmv_pfn -#undef clblasStpsv -//#define clblasStpsv clblasStpsv_pfn -#undef clblasStrmm -//#define clblasStrmm clblasStrmm_pfn -#undef clblasStrmv -//#define clblasStrmv clblasStrmv_pfn -#undef clblasStrsm -//#define clblasStrsm clblasStrsm_pfn -#undef clblasStrsv -//#define clblasStrsv clblasStrsv_pfn -#undef clblasTeardown -#define clblasTeardown clblasTeardown_pfn -#undef clblasZaxpy -//#define clblasZaxpy clblasZaxpy_pfn -#undef clblasZcopy -//#define clblasZcopy clblasZcopy_pfn -#undef clblasZdotc -//#define clblasZdotc clblasZdotc_pfn -#undef clblasZdotu -//#define clblasZdotu clblasZdotu_pfn -#undef clblasZdrot -//#define clblasZdrot clblasZdrot_pfn -#undef clblasZdscal -//#define clblasZdscal clblasZdscal_pfn -#undef clblasZgbmv -//#define clblasZgbmv clblasZgbmv_pfn -#undef clblasZgemm -#define clblasZgemm clblasZgemm_pfn -#undef clblasZgemv -//#define clblasZgemv clblasZgemv_pfn -#undef clblasZgerc -//#define clblasZgerc clblasZgerc_pfn -#undef clblasZgeru -//#define clblasZgeru clblasZgeru_pfn -#undef clblasZhbmv -//#define clblasZhbmv clblasZhbmv_pfn -#undef clblasZhemm -//#define clblasZhemm clblasZhemm_pfn -#undef clblasZhemv -//#define clblasZhemv clblasZhemv_pfn -#undef clblasZher -//#define clblasZher clblasZher_pfn -#undef clblasZher2 -//#define clblasZher2 clblasZher2_pfn -#undef clblasZher2k -//#define clblasZher2k clblasZher2k_pfn -#undef clblasZherk -//#define clblasZherk clblasZherk_pfn -#undef clblasZhpmv -//#define clblasZhpmv clblasZhpmv_pfn -#undef clblasZhpr -//#define clblasZhpr clblasZhpr_pfn -#undef clblasZhpr2 -//#define clblasZhpr2 clblasZhpr2_pfn -#undef clblasZrotg -//#define clblasZrotg clblasZrotg_pfn -#undef clblasZscal -//#define clblasZscal clblasZscal_pfn -#undef clblasZswap -//#define clblasZswap clblasZswap_pfn -#undef clblasZsymm -//#define clblasZsymm clblasZsymm_pfn -#undef clblasZsyr2k -//#define clblasZsyr2k clblasZsyr2k_pfn -#undef clblasZsyrk -//#define clblasZsyrk clblasZsyrk_pfn -#undef clblasZtbmv -//#define clblasZtbmv clblasZtbmv_pfn -#undef clblasZtbsv -//#define clblasZtbsv clblasZtbsv_pfn -#undef clblasZtpmv -//#define clblasZtpmv clblasZtpmv_pfn -#undef clblasZtpsv -//#define clblasZtpsv clblasZtpsv_pfn -#undef clblasZtrmm -//#define clblasZtrmm clblasZtrmm_pfn -#undef clblasZtrmv -//#define clblasZtrmv clblasZtrmv_pfn -#undef clblasZtrsm -//#define clblasZtrsm clblasZtrsm_pfn -#undef clblasZtrsv -//#define clblasZtrsv clblasZtrsv_pfn -#undef clblasiCamax -//#define clblasiCamax clblasiCamax_pfn -#undef clblasiDamax -//#define clblasiDamax clblasiDamax_pfn -#undef clblasiSamax -//#define clblasiSamax clblasiSamax_pfn -#undef clblasiZamax -//#define clblasiZamax clblasiZamax_pfn - -// generated by parser_clblas.py -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCaxpy)(size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, FloatComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgerc)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgeru)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemv)(clblasOrder order, clblasUplo uplo, size_t N, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, FloatComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, float alpha, const cl_mem A, size_t offa, size_t lda, float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCscal)(size_t N, cl_float2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDaxpy)(size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDger)(clblasOrder order, size_t M, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotg)(cl_mem DA, size_t offDA, cl_mem DB, size_t offDB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotmg)(cl_mem DD1, size_t offDD1, cl_mem DD2, size_t offDD2, cl_mem DX1, size_t offDX1, const cl_mem DY1, size_t offDY1, cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDzasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDznrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSaxpy)(size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasSetup)(); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSger)(clblasOrder order, size_t M, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotg)(cl_mem SA, size_t offSA, cl_mem SB, size_t offSB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotmg)(cl_mem SD1, size_t offSD1, cl_mem SD2, size_t offSD2, cl_mem SX1, size_t offSX1, const cl_mem SY1, size_t offSY1, cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT void (*clblasTeardown)(); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZaxpy)(size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, DoubleComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgerc)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgeru)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemv)(clblasOrder order, clblasUplo uplo, size_t N, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, DoubleComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, double alpha, const cl_mem A, size_t offa, size_t lda, double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZscal)(size_t N, cl_double2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiCamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiDamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiSamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); -//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiZamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP +#error "Invalid usage" +#endif + +// generated by parser_clblas.py +#define clblasCaxpy clblasCaxpy_ +#define clblasCcopy clblasCcopy_ +#define clblasCdotc clblasCdotc_ +#define clblasCdotu clblasCdotu_ +#define clblasCgbmv clblasCgbmv_ +#define clblasCgemm clblasCgemm_ +#define clblasCgemv clblasCgemv_ +#define clblasCgerc clblasCgerc_ +#define clblasCgeru clblasCgeru_ +#define clblasChbmv clblasChbmv_ +#define clblasChemm clblasChemm_ +#define clblasChemv clblasChemv_ +#define clblasCher clblasCher_ +#define clblasCher2 clblasCher2_ +#define clblasCher2k clblasCher2k_ +#define clblasCherk clblasCherk_ +#define clblasChpmv clblasChpmv_ +#define clblasChpr clblasChpr_ +#define clblasChpr2 clblasChpr2_ +#define clblasCrotg clblasCrotg_ +#define clblasCscal clblasCscal_ +#define clblasCsrot clblasCsrot_ +#define clblasCsscal clblasCsscal_ +#define clblasCswap clblasCswap_ +#define clblasCsymm clblasCsymm_ +#define clblasCsyr2k clblasCsyr2k_ +#define clblasCsyrk clblasCsyrk_ +#define clblasCtbmv clblasCtbmv_ +#define clblasCtbsv clblasCtbsv_ +#define clblasCtpmv clblasCtpmv_ +#define clblasCtpsv clblasCtpsv_ +#define clblasCtrmm clblasCtrmm_ +#define clblasCtrmv clblasCtrmv_ +#define clblasCtrsm clblasCtrsm_ +#define clblasCtrsv clblasCtrsv_ +#define clblasDasum clblasDasum_ +#define clblasDaxpy clblasDaxpy_ +#define clblasDcopy clblasDcopy_ +#define clblasDdot clblasDdot_ +#define clblasDgbmv clblasDgbmv_ +#define clblasDgemm clblasDgemm_ +#define clblasDgemv clblasDgemv_ +#define clblasDger clblasDger_ +#define clblasDnrm2 clblasDnrm2_ +#define clblasDrot clblasDrot_ +#define clblasDrotg clblasDrotg_ +#define clblasDrotm clblasDrotm_ +#define clblasDrotmg clblasDrotmg_ +#define clblasDsbmv clblasDsbmv_ +#define clblasDscal clblasDscal_ +#define clblasDspmv clblasDspmv_ +#define clblasDspr clblasDspr_ +#define clblasDspr2 clblasDspr2_ +#define clblasDswap clblasDswap_ +#define clblasDsymm clblasDsymm_ +#define clblasDsymv clblasDsymv_ +#define clblasDsyr clblasDsyr_ +#define clblasDsyr2 clblasDsyr2_ +#define clblasDsyr2k clblasDsyr2k_ +#define clblasDsyrk clblasDsyrk_ +#define clblasDtbmv clblasDtbmv_ +#define clblasDtbsv clblasDtbsv_ +#define clblasDtpmv clblasDtpmv_ +#define clblasDtpsv clblasDtpsv_ +#define clblasDtrmm clblasDtrmm_ +#define clblasDtrmv clblasDtrmv_ +#define clblasDtrsm clblasDtrsm_ +#define clblasDtrsv clblasDtrsv_ +#define clblasDzasum clblasDzasum_ +#define clblasDznrm2 clblasDznrm2_ +#define clblasGetVersion clblasGetVersion_ +#define clblasSasum clblasSasum_ +#define clblasSaxpy clblasSaxpy_ +#define clblasScasum clblasScasum_ +#define clblasScnrm2 clblasScnrm2_ +#define clblasScopy clblasScopy_ +#define clblasSdot clblasSdot_ +#define clblasSetup clblasSetup_ +#define clblasSgbmv clblasSgbmv_ +#define clblasSgemm clblasSgemm_ +#define clblasSgemv clblasSgemv_ +#define clblasSger clblasSger_ +#define clblasSnrm2 clblasSnrm2_ +#define clblasSrot clblasSrot_ +#define clblasSrotg clblasSrotg_ +#define clblasSrotm clblasSrotm_ +#define clblasSrotmg clblasSrotmg_ +#define clblasSsbmv clblasSsbmv_ +#define clblasSscal clblasSscal_ +#define clblasSspmv clblasSspmv_ +#define clblasSspr clblasSspr_ +#define clblasSspr2 clblasSspr2_ +#define clblasSswap clblasSswap_ +#define clblasSsymm clblasSsymm_ +#define clblasSsymv clblasSsymv_ +#define clblasSsyr clblasSsyr_ +#define clblasSsyr2 clblasSsyr2_ +#define clblasSsyr2k clblasSsyr2k_ +#define clblasSsyrk clblasSsyrk_ +#define clblasStbmv clblasStbmv_ +#define clblasStbsv clblasStbsv_ +#define clblasStpmv clblasStpmv_ +#define clblasStpsv clblasStpsv_ +#define clblasStrmm clblasStrmm_ +#define clblasStrmv clblasStrmv_ +#define clblasStrsm clblasStrsm_ +#define clblasStrsv clblasStrsv_ +#define clblasTeardown clblasTeardown_ +#define clblasZaxpy clblasZaxpy_ +#define clblasZcopy clblasZcopy_ +#define clblasZdotc clblasZdotc_ +#define clblasZdotu clblasZdotu_ +#define clblasZdrot clblasZdrot_ +#define clblasZdscal clblasZdscal_ +#define clblasZgbmv clblasZgbmv_ +#define clblasZgemm clblasZgemm_ +#define clblasZgemv clblasZgemv_ +#define clblasZgerc clblasZgerc_ +#define clblasZgeru clblasZgeru_ +#define clblasZhbmv clblasZhbmv_ +#define clblasZhemm clblasZhemm_ +#define clblasZhemv clblasZhemv_ +#define clblasZher clblasZher_ +#define clblasZher2 clblasZher2_ +#define clblasZher2k clblasZher2k_ +#define clblasZherk clblasZherk_ +#define clblasZhpmv clblasZhpmv_ +#define clblasZhpr clblasZhpr_ +#define clblasZhpr2 clblasZhpr2_ +#define clblasZrotg clblasZrotg_ +#define clblasZscal clblasZscal_ +#define clblasZswap clblasZswap_ +#define clblasZsymm clblasZsymm_ +#define clblasZsyr2k clblasZsyr2k_ +#define clblasZsyrk clblasZsyrk_ +#define clblasZtbmv clblasZtbmv_ +#define clblasZtbsv clblasZtbsv_ +#define clblasZtpmv clblasZtpmv_ +#define clblasZtpsv clblasZtpsv_ +#define clblasZtrmm clblasZtrmm_ +#define clblasZtrmv clblasZtrmv_ +#define clblasZtrsm clblasZtrsm_ +#define clblasZtrsv clblasZtrsv_ +#define clblasiCamax clblasiCamax_ +#define clblasiDamax clblasiDamax_ +#define clblasiSamax clblasiSamax_ +#define clblasiZamax clblasiZamax_ + +#include + +// generated by parser_clblas.py +#undef clblasCaxpy +//#define clblasCaxpy clblasCaxpy_pfn +#undef clblasCcopy +//#define clblasCcopy clblasCcopy_pfn +#undef clblasCdotc +//#define clblasCdotc clblasCdotc_pfn +#undef clblasCdotu +//#define clblasCdotu clblasCdotu_pfn +#undef clblasCgbmv +//#define clblasCgbmv clblasCgbmv_pfn +#undef clblasCgemm +#define clblasCgemm clblasCgemm_pfn +#undef clblasCgemv +//#define clblasCgemv clblasCgemv_pfn +#undef clblasCgerc +//#define clblasCgerc clblasCgerc_pfn +#undef clblasCgeru +//#define clblasCgeru clblasCgeru_pfn +#undef clblasChbmv +//#define clblasChbmv clblasChbmv_pfn +#undef clblasChemm +//#define clblasChemm clblasChemm_pfn +#undef clblasChemv +//#define clblasChemv clblasChemv_pfn +#undef clblasCher +//#define clblasCher clblasCher_pfn +#undef clblasCher2 +//#define clblasCher2 clblasCher2_pfn +#undef clblasCher2k +//#define clblasCher2k clblasCher2k_pfn +#undef clblasCherk +//#define clblasCherk clblasCherk_pfn +#undef clblasChpmv +//#define clblasChpmv clblasChpmv_pfn +#undef clblasChpr +//#define clblasChpr clblasChpr_pfn +#undef clblasChpr2 +//#define clblasChpr2 clblasChpr2_pfn +#undef clblasCrotg +//#define clblasCrotg clblasCrotg_pfn +#undef clblasCscal +//#define clblasCscal clblasCscal_pfn +#undef clblasCsrot +//#define clblasCsrot clblasCsrot_pfn +#undef clblasCsscal +//#define clblasCsscal clblasCsscal_pfn +#undef clblasCswap +//#define clblasCswap clblasCswap_pfn +#undef clblasCsymm +//#define clblasCsymm clblasCsymm_pfn +#undef clblasCsyr2k +//#define clblasCsyr2k clblasCsyr2k_pfn +#undef clblasCsyrk +//#define clblasCsyrk clblasCsyrk_pfn +#undef clblasCtbmv +//#define clblasCtbmv clblasCtbmv_pfn +#undef clblasCtbsv +//#define clblasCtbsv clblasCtbsv_pfn +#undef clblasCtpmv +//#define clblasCtpmv clblasCtpmv_pfn +#undef clblasCtpsv +//#define clblasCtpsv clblasCtpsv_pfn +#undef clblasCtrmm +//#define clblasCtrmm clblasCtrmm_pfn +#undef clblasCtrmv +//#define clblasCtrmv clblasCtrmv_pfn +#undef clblasCtrsm +//#define clblasCtrsm clblasCtrsm_pfn +#undef clblasCtrsv +//#define clblasCtrsv clblasCtrsv_pfn +#undef clblasDasum +//#define clblasDasum clblasDasum_pfn +#undef clblasDaxpy +//#define clblasDaxpy clblasDaxpy_pfn +#undef clblasDcopy +//#define clblasDcopy clblasDcopy_pfn +#undef clblasDdot +//#define clblasDdot clblasDdot_pfn +#undef clblasDgbmv +//#define clblasDgbmv clblasDgbmv_pfn +#undef clblasDgemm +#define clblasDgemm clblasDgemm_pfn +#undef clblasDgemv +//#define clblasDgemv clblasDgemv_pfn +#undef clblasDger +//#define clblasDger clblasDger_pfn +#undef clblasDnrm2 +//#define clblasDnrm2 clblasDnrm2_pfn +#undef clblasDrot +//#define clblasDrot clblasDrot_pfn +#undef clblasDrotg +//#define clblasDrotg clblasDrotg_pfn +#undef clblasDrotm +//#define clblasDrotm clblasDrotm_pfn +#undef clblasDrotmg +//#define clblasDrotmg clblasDrotmg_pfn +#undef clblasDsbmv +//#define clblasDsbmv clblasDsbmv_pfn +#undef clblasDscal +//#define clblasDscal clblasDscal_pfn +#undef clblasDspmv +//#define clblasDspmv clblasDspmv_pfn +#undef clblasDspr +//#define clblasDspr clblasDspr_pfn +#undef clblasDspr2 +//#define clblasDspr2 clblasDspr2_pfn +#undef clblasDswap +//#define clblasDswap clblasDswap_pfn +#undef clblasDsymm +//#define clblasDsymm clblasDsymm_pfn +#undef clblasDsymv +//#define clblasDsymv clblasDsymv_pfn +#undef clblasDsyr +//#define clblasDsyr clblasDsyr_pfn +#undef clblasDsyr2 +//#define clblasDsyr2 clblasDsyr2_pfn +#undef clblasDsyr2k +//#define clblasDsyr2k clblasDsyr2k_pfn +#undef clblasDsyrk +//#define clblasDsyrk clblasDsyrk_pfn +#undef clblasDtbmv +//#define clblasDtbmv clblasDtbmv_pfn +#undef clblasDtbsv +//#define clblasDtbsv clblasDtbsv_pfn +#undef clblasDtpmv +//#define clblasDtpmv clblasDtpmv_pfn +#undef clblasDtpsv +//#define clblasDtpsv clblasDtpsv_pfn +#undef clblasDtrmm +//#define clblasDtrmm clblasDtrmm_pfn +#undef clblasDtrmv +//#define clblasDtrmv clblasDtrmv_pfn +#undef clblasDtrsm +//#define clblasDtrsm clblasDtrsm_pfn +#undef clblasDtrsv +//#define clblasDtrsv clblasDtrsv_pfn +#undef clblasDzasum +//#define clblasDzasum clblasDzasum_pfn +#undef clblasDznrm2 +//#define clblasDznrm2 clblasDznrm2_pfn +#undef clblasGetVersion +//#define clblasGetVersion clblasGetVersion_pfn +#undef clblasSasum +//#define clblasSasum clblasSasum_pfn +#undef clblasSaxpy +//#define clblasSaxpy clblasSaxpy_pfn +#undef clblasScasum +//#define clblasScasum clblasScasum_pfn +#undef clblasScnrm2 +//#define clblasScnrm2 clblasScnrm2_pfn +#undef clblasScopy +//#define clblasScopy clblasScopy_pfn +#undef clblasSdot +//#define clblasSdot clblasSdot_pfn +#undef clblasSetup +#define clblasSetup clblasSetup_pfn +#undef clblasSgbmv +//#define clblasSgbmv clblasSgbmv_pfn +#undef clblasSgemm +#define clblasSgemm clblasSgemm_pfn +#undef clblasSgemv +//#define clblasSgemv clblasSgemv_pfn +#undef clblasSger +//#define clblasSger clblasSger_pfn +#undef clblasSnrm2 +//#define clblasSnrm2 clblasSnrm2_pfn +#undef clblasSrot +//#define clblasSrot clblasSrot_pfn +#undef clblasSrotg +//#define clblasSrotg clblasSrotg_pfn +#undef clblasSrotm +//#define clblasSrotm clblasSrotm_pfn +#undef clblasSrotmg +//#define clblasSrotmg clblasSrotmg_pfn +#undef clblasSsbmv +//#define clblasSsbmv clblasSsbmv_pfn +#undef clblasSscal +//#define clblasSscal clblasSscal_pfn +#undef clblasSspmv +//#define clblasSspmv clblasSspmv_pfn +#undef clblasSspr +//#define clblasSspr clblasSspr_pfn +#undef clblasSspr2 +//#define clblasSspr2 clblasSspr2_pfn +#undef clblasSswap +//#define clblasSswap clblasSswap_pfn +#undef clblasSsymm +//#define clblasSsymm clblasSsymm_pfn +#undef clblasSsymv +//#define clblasSsymv clblasSsymv_pfn +#undef clblasSsyr +//#define clblasSsyr clblasSsyr_pfn +#undef clblasSsyr2 +//#define clblasSsyr2 clblasSsyr2_pfn +#undef clblasSsyr2k +//#define clblasSsyr2k clblasSsyr2k_pfn +#undef clblasSsyrk +//#define clblasSsyrk clblasSsyrk_pfn +#undef clblasStbmv +//#define clblasStbmv clblasStbmv_pfn +#undef clblasStbsv +//#define clblasStbsv clblasStbsv_pfn +#undef clblasStpmv +//#define clblasStpmv clblasStpmv_pfn +#undef clblasStpsv +//#define clblasStpsv clblasStpsv_pfn +#undef clblasStrmm +//#define clblasStrmm clblasStrmm_pfn +#undef clblasStrmv +//#define clblasStrmv clblasStrmv_pfn +#undef clblasStrsm +//#define clblasStrsm clblasStrsm_pfn +#undef clblasStrsv +//#define clblasStrsv clblasStrsv_pfn +#undef clblasTeardown +#define clblasTeardown clblasTeardown_pfn +#undef clblasZaxpy +//#define clblasZaxpy clblasZaxpy_pfn +#undef clblasZcopy +//#define clblasZcopy clblasZcopy_pfn +#undef clblasZdotc +//#define clblasZdotc clblasZdotc_pfn +#undef clblasZdotu +//#define clblasZdotu clblasZdotu_pfn +#undef clblasZdrot +//#define clblasZdrot clblasZdrot_pfn +#undef clblasZdscal +//#define clblasZdscal clblasZdscal_pfn +#undef clblasZgbmv +//#define clblasZgbmv clblasZgbmv_pfn +#undef clblasZgemm +#define clblasZgemm clblasZgemm_pfn +#undef clblasZgemv +//#define clblasZgemv clblasZgemv_pfn +#undef clblasZgerc +//#define clblasZgerc clblasZgerc_pfn +#undef clblasZgeru +//#define clblasZgeru clblasZgeru_pfn +#undef clblasZhbmv +//#define clblasZhbmv clblasZhbmv_pfn +#undef clblasZhemm +//#define clblasZhemm clblasZhemm_pfn +#undef clblasZhemv +//#define clblasZhemv clblasZhemv_pfn +#undef clblasZher +//#define clblasZher clblasZher_pfn +#undef clblasZher2 +//#define clblasZher2 clblasZher2_pfn +#undef clblasZher2k +//#define clblasZher2k clblasZher2k_pfn +#undef clblasZherk +//#define clblasZherk clblasZherk_pfn +#undef clblasZhpmv +//#define clblasZhpmv clblasZhpmv_pfn +#undef clblasZhpr +//#define clblasZhpr clblasZhpr_pfn +#undef clblasZhpr2 +//#define clblasZhpr2 clblasZhpr2_pfn +#undef clblasZrotg +//#define clblasZrotg clblasZrotg_pfn +#undef clblasZscal +//#define clblasZscal clblasZscal_pfn +#undef clblasZswap +//#define clblasZswap clblasZswap_pfn +#undef clblasZsymm +//#define clblasZsymm clblasZsymm_pfn +#undef clblasZsyr2k +//#define clblasZsyr2k clblasZsyr2k_pfn +#undef clblasZsyrk +//#define clblasZsyrk clblasZsyrk_pfn +#undef clblasZtbmv +//#define clblasZtbmv clblasZtbmv_pfn +#undef clblasZtbsv +//#define clblasZtbsv clblasZtbsv_pfn +#undef clblasZtpmv +//#define clblasZtpmv clblasZtpmv_pfn +#undef clblasZtpsv +//#define clblasZtpsv clblasZtpsv_pfn +#undef clblasZtrmm +//#define clblasZtrmm clblasZtrmm_pfn +#undef clblasZtrmv +//#define clblasZtrmv clblasZtrmv_pfn +#undef clblasZtrsm +//#define clblasZtrsm clblasZtrsm_pfn +#undef clblasZtrsv +//#define clblasZtrsv clblasZtrsv_pfn +#undef clblasiCamax +//#define clblasiCamax clblasiCamax_pfn +#undef clblasiDamax +//#define clblasiDamax clblasiDamax_pfn +#undef clblasiSamax +//#define clblasiSamax clblasiSamax_pfn +#undef clblasiZamax +//#define clblasiZamax clblasiZamax_pfn + +// generated by parser_clblas.py +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCaxpy)(size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, FloatComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgerc)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCgeru)(clblasOrder order, size_t M, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChemv)(clblasOrder order, clblasUplo uplo, size_t N, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, FloatComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, float alpha, const cl_mem A, size_t offa, size_t lda, float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasChpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCscal)(size_t N, cl_float2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, FloatComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, FloatComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasCtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDaxpy)(size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDger)(clblasOrder order, size_t M, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotg)(cl_mem DA, size_t offDA, cl_mem DB, size_t offDB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDrotmg)(cl_mem DD1, size_t offDD1, cl_mem DD2, size_t offDD2, cl_mem DX1, size_t offDX1, const cl_mem DY1, size_t offDY1, cl_mem DPARAM, size_t offDparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_double beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_double beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_double alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDzasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasDznrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSaxpy)(size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScasum)(size_t N, cl_mem asum, size_t offAsum, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasScopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSdot)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasSetup)(); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSger)(clblasOrder order, size_t M, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSnrm2)(size_t N, cl_mem NRM2, size_t offNRM2, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_float C, cl_float S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotg)(cl_mem SA, size_t offSA, cl_mem SB, size_t offSB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotm)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, const cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSrotmg)(cl_mem SD1, size_t offSD1, cl_mem SD2, size_t offSD2, cl_mem SX1, size_t offSX1, const cl_mem SY1, size_t offSY1, cl_mem SPARAM, size_t offSparam, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSscal)(size_t N, cl_float alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_float beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSspr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_float beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsymv)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, cl_float beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_float alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasSsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_float beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, cl_float alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasStrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT void (*clblasTeardown)(); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZaxpy)(size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZcopy)(size_t N, const cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotc)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdotu)(size_t N, cl_mem dotProduct, size_t offDP, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdrot)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_double C, cl_double S, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZdscal)(size_t N, cl_double alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgbmv)(clblasOrder order, clblasTranspose trans, size_t M, size_t N, size_t KL, size_t KU, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemm)(clblasOrder order, clblasTranspose transA, clblasTranspose transB, size_t M, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgemv)(clblasOrder order, clblasTranspose transA, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem x, size_t offx, int incx, DoubleComplex beta, cl_mem y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgerc)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZgeru)(clblasOrder order, size_t M, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhbmv)(clblasOrder order, clblasUplo uplo, size_t N, size_t K, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhemv)(clblasOrder order, clblasUplo uplo, size_t N, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem X, size_t offx, int incx, DoubleComplex beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem A, size_t offa, size_t lda, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZher2k)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZherk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, double alpha, const cl_mem A, size_t offa, size_t lda, double beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpmv)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem AP, size_t offa, const cl_mem X, size_t offx, int incx, cl_double2 beta, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr)(clblasOrder order, clblasUplo uplo, size_t N, cl_double alpha, const cl_mem X, size_t offx, int incx, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZhpr2)(clblasOrder order, clblasUplo uplo, size_t N, cl_double2 alpha, const cl_mem X, size_t offx, int incx, const cl_mem Y, size_t offy, int incy, cl_mem AP, size_t offa, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZrotg)(cl_mem CA, size_t offCA, cl_mem CB, size_t offCB, cl_mem C, size_t offC, cl_mem S, size_t offS, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZscal)(size_t N, cl_double2 alpha, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZswap)(size_t N, cl_mem X, size_t offx, int incx, cl_mem Y, size_t offy, int incy, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsymm)(clblasOrder order, clblasSide side, clblasUplo uplo, size_t M, size_t N, cl_double2 alpha, const cl_mem A, size_t offa, size_t lda, const cl_mem B, size_t offb, size_t ldb, cl_double2 beta, cl_mem C, size_t offc, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyr2k)(clblasOrder order, clblasUplo uplo, clblasTranspose transAB, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, const cl_mem B, size_t offB, size_t ldb, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZsyrk)(clblasOrder order, clblasUplo uplo, clblasTranspose transA, size_t N, size_t K, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, DoubleComplex beta, cl_mem C, size_t offC, size_t ldc, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtbsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, size_t K, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem AP, size_t offa, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtpsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrmv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsm)(clblasOrder order, clblasSide side, clblasUplo uplo, clblasTranspose transA, clblasDiag diag, size_t M, size_t N, DoubleComplex alpha, const cl_mem A, size_t offA, size_t lda, cl_mem B, size_t offB, size_t ldb, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasZtrsv)(clblasOrder order, clblasUplo uplo, clblasTranspose trans, clblasDiag diag, size_t N, const cl_mem A, size_t offa, size_t lda, cl_mem X, size_t offx, int incx, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiCamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiDamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiSamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); +//extern CL_RUNTIME_EXPORT clblasStatus (*clblasiZamax)(size_t N, cl_mem iMax, size_t offiMax, const cl_mem X, size_t offx, int incx, cl_mem scratchBuff, cl_uint numCommandQueues, cl_command_queue* commandQueues, cl_uint numEventsInWaitList, const cl_event* eventWaitList, cl_event* events); diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp index c2d14a28f6..dff3b406a6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_clfft.hpp @@ -1,146 +1,146 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP -#error "Invalid usage" -#endif - -// generated by parser_clfft.py -#define clfftBakePlan clfftBakePlan_ -#define clfftCopyPlan clfftCopyPlan_ -#define clfftCreateDefaultPlan clfftCreateDefaultPlan_ -#define clfftDestroyPlan clfftDestroyPlan_ -#define clfftEnqueueTransform clfftEnqueueTransform_ -#define clfftGetLayout clfftGetLayout_ -#define clfftGetPlanBatchSize clfftGetPlanBatchSize_ -#define clfftGetPlanContext clfftGetPlanContext_ -#define clfftGetPlanDim clfftGetPlanDim_ -#define clfftGetPlanDistance clfftGetPlanDistance_ -#define clfftGetPlanInStride clfftGetPlanInStride_ -#define clfftGetPlanLength clfftGetPlanLength_ -#define clfftGetPlanOutStride clfftGetPlanOutStride_ -#define clfftGetPlanPrecision clfftGetPlanPrecision_ -#define clfftGetPlanScale clfftGetPlanScale_ -#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_ -#define clfftGetResultLocation clfftGetResultLocation_ -#define clfftGetTmpBufSize clfftGetTmpBufSize_ -#define clfftGetVersion clfftGetVersion_ -#define clfftSetLayout clfftSetLayout_ -#define clfftSetPlanBatchSize clfftSetPlanBatchSize_ -#define clfftSetPlanCallback clfftSetPlanCallback_ -#define clfftSetPlanDim clfftSetPlanDim_ -#define clfftSetPlanDistance clfftSetPlanDistance_ -#define clfftSetPlanInStride clfftSetPlanInStride_ -#define clfftSetPlanLength clfftSetPlanLength_ -#define clfftSetPlanOutStride clfftSetPlanOutStride_ -#define clfftSetPlanPrecision clfftSetPlanPrecision_ -#define clfftSetPlanScale clfftSetPlanScale_ -#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_ -#define clfftSetResultLocation clfftSetResultLocation_ -#define clfftSetup clfftSetup_ -#define clfftTeardown clfftTeardown_ - -#include - -// generated by parser_clfft.py -#undef clfftBakePlan -#define clfftBakePlan clfftBakePlan_pfn -#undef clfftCopyPlan -//#define clfftCopyPlan clfftCopyPlan_pfn -#undef clfftCreateDefaultPlan -#define clfftCreateDefaultPlan clfftCreateDefaultPlan_pfn -#undef clfftDestroyPlan -#define clfftDestroyPlan clfftDestroyPlan_pfn -#undef clfftEnqueueTransform -#define clfftEnqueueTransform clfftEnqueueTransform_pfn -#undef clfftGetLayout -//#define clfftGetLayout clfftGetLayout_pfn -#undef clfftGetPlanBatchSize -//#define clfftGetPlanBatchSize clfftGetPlanBatchSize_pfn -#undef clfftGetPlanContext -//#define clfftGetPlanContext clfftGetPlanContext_pfn -#undef clfftGetPlanDim -//#define clfftGetPlanDim clfftGetPlanDim_pfn -#undef clfftGetPlanDistance -//#define clfftGetPlanDistance clfftGetPlanDistance_pfn -#undef clfftGetPlanInStride -//#define clfftGetPlanInStride clfftGetPlanInStride_pfn -#undef clfftGetPlanLength -//#define clfftGetPlanLength clfftGetPlanLength_pfn -#undef clfftGetPlanOutStride -//#define clfftGetPlanOutStride clfftGetPlanOutStride_pfn -#undef clfftGetPlanPrecision -//#define clfftGetPlanPrecision clfftGetPlanPrecision_pfn -#undef clfftGetPlanScale -//#define clfftGetPlanScale clfftGetPlanScale_pfn -#undef clfftGetPlanTransposeResult -//#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_pfn -#undef clfftGetResultLocation -//#define clfftGetResultLocation clfftGetResultLocation_pfn -#undef clfftGetTmpBufSize -#define clfftGetTmpBufSize clfftGetTmpBufSize_pfn -#undef clfftGetVersion -#define clfftGetVersion clfftGetVersion_pfn -#undef clfftSetLayout -#define clfftSetLayout clfftSetLayout_pfn -#undef clfftSetPlanBatchSize -#define clfftSetPlanBatchSize clfftSetPlanBatchSize_pfn -#undef clfftSetPlanCallback -//#define clfftSetPlanCallback clfftSetPlanCallback_pfn -#undef clfftSetPlanDim -//#define clfftSetPlanDim clfftSetPlanDim_pfn -#undef clfftSetPlanDistance -#define clfftSetPlanDistance clfftSetPlanDistance_pfn -#undef clfftSetPlanInStride -#define clfftSetPlanInStride clfftSetPlanInStride_pfn -#undef clfftSetPlanLength -//#define clfftSetPlanLength clfftSetPlanLength_pfn -#undef clfftSetPlanOutStride -#define clfftSetPlanOutStride clfftSetPlanOutStride_pfn -#undef clfftSetPlanPrecision -#define clfftSetPlanPrecision clfftSetPlanPrecision_pfn -#undef clfftSetPlanScale -#define clfftSetPlanScale clfftSetPlanScale_pfn -#undef clfftSetPlanTransposeResult -//#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_pfn -#undef clfftSetResultLocation -#define clfftSetResultLocation clfftSetResultLocation_pfn -#undef clfftSetup -#define clfftSetup clfftSetup_pfn -#undef clfftTeardown -#define clfftTeardown clfftTeardown_pfn - -// generated by parser_clfft.py -extern CL_RUNTIME_EXPORT clfftStatus (*clfftBakePlan)(clfftPlanHandle plHandle, cl_uint numQueues, cl_command_queue* commQueueFFT, void (CL_CALLBACK* pfn_notify) (clfftPlanHandle plHandle, void* user_data), void* user_data); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftCopyPlan)(clfftPlanHandle* out_plHandle, cl_context new_context, clfftPlanHandle in_plHandle); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftCreateDefaultPlan)(clfftPlanHandle* plHandle, cl_context context, const clfftDim dim, const size_t* clLengths); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftDestroyPlan)(clfftPlanHandle* plHandle); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftEnqueueTransform)(clfftPlanHandle plHandle, clfftDirection dir, cl_uint numQueuesAndEvents, cl_command_queue* commQueues, cl_uint numWaitEvents, const cl_event* waitEvents, cl_event* outEvents, cl_mem* inputBuffers, cl_mem* outputBuffers, cl_mem tmpBuffer); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetLayout)(const clfftPlanHandle plHandle, clfftLayout* iLayout, clfftLayout* oLayout); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanBatchSize)(const clfftPlanHandle plHandle, size_t* batchSize); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanContext)(const clfftPlanHandle plHandle, cl_context* context); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDim)(const clfftPlanHandle plHandle, clfftDim* dim, cl_uint* size); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDistance)(const clfftPlanHandle plHandle, size_t* iDist, size_t* oDist); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanInStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanLength)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clLengths); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanOutStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanPrecision)(const clfftPlanHandle plHandle, clfftPrecision* precision); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanScale)(const clfftPlanHandle plHandle, clfftDirection dir, cl_float* scale); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanTransposeResult)(const clfftPlanHandle plHandle, clfftResultTransposed* transposed); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetResultLocation)(const clfftPlanHandle plHandle, clfftResultLocation* placeness); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetTmpBufSize)(const clfftPlanHandle plHandle, size_t* buffersize); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetLayout)(clfftPlanHandle plHandle, clfftLayout iLayout, clfftLayout oLayout); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanBatchSize)(clfftPlanHandle plHandle, size_t batchSize); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanCallback)(clfftPlanHandle plHandle, const char* funcName, const char* funcString, int localMemSize, clfftCallbackType callbackType, cl_mem* userdata, int numUserdataBuffers); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDim)(clfftPlanHandle plHandle, const clfftDim dim); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDistance)(clfftPlanHandle plHandle, size_t iDist, size_t oDist); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanInStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanLength)(clfftPlanHandle plHandle, const clfftDim dim, const size_t* clLengths); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanOutStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanPrecision)(clfftPlanHandle plHandle, clfftPrecision precision); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanScale)(clfftPlanHandle plHandle, clfftDirection dir, cl_float scale); -//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanTransposeResult)(clfftPlanHandle plHandle, clfftResultTransposed transposed); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetResultLocation)(clfftPlanHandle plHandle, clfftResultLocation placeness); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetup)(const clfftSetupData* setupData); -extern CL_RUNTIME_EXPORT clfftStatus (*clfftTeardown)(); +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP +#error "Invalid usage" +#endif + +// generated by parser_clfft.py +#define clfftBakePlan clfftBakePlan_ +#define clfftCopyPlan clfftCopyPlan_ +#define clfftCreateDefaultPlan clfftCreateDefaultPlan_ +#define clfftDestroyPlan clfftDestroyPlan_ +#define clfftEnqueueTransform clfftEnqueueTransform_ +#define clfftGetLayout clfftGetLayout_ +#define clfftGetPlanBatchSize clfftGetPlanBatchSize_ +#define clfftGetPlanContext clfftGetPlanContext_ +#define clfftGetPlanDim clfftGetPlanDim_ +#define clfftGetPlanDistance clfftGetPlanDistance_ +#define clfftGetPlanInStride clfftGetPlanInStride_ +#define clfftGetPlanLength clfftGetPlanLength_ +#define clfftGetPlanOutStride clfftGetPlanOutStride_ +#define clfftGetPlanPrecision clfftGetPlanPrecision_ +#define clfftGetPlanScale clfftGetPlanScale_ +#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_ +#define clfftGetResultLocation clfftGetResultLocation_ +#define clfftGetTmpBufSize clfftGetTmpBufSize_ +#define clfftGetVersion clfftGetVersion_ +#define clfftSetLayout clfftSetLayout_ +#define clfftSetPlanBatchSize clfftSetPlanBatchSize_ +#define clfftSetPlanCallback clfftSetPlanCallback_ +#define clfftSetPlanDim clfftSetPlanDim_ +#define clfftSetPlanDistance clfftSetPlanDistance_ +#define clfftSetPlanInStride clfftSetPlanInStride_ +#define clfftSetPlanLength clfftSetPlanLength_ +#define clfftSetPlanOutStride clfftSetPlanOutStride_ +#define clfftSetPlanPrecision clfftSetPlanPrecision_ +#define clfftSetPlanScale clfftSetPlanScale_ +#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_ +#define clfftSetResultLocation clfftSetResultLocation_ +#define clfftSetup clfftSetup_ +#define clfftTeardown clfftTeardown_ + +#include + +// generated by parser_clfft.py +#undef clfftBakePlan +#define clfftBakePlan clfftBakePlan_pfn +#undef clfftCopyPlan +//#define clfftCopyPlan clfftCopyPlan_pfn +#undef clfftCreateDefaultPlan +#define clfftCreateDefaultPlan clfftCreateDefaultPlan_pfn +#undef clfftDestroyPlan +#define clfftDestroyPlan clfftDestroyPlan_pfn +#undef clfftEnqueueTransform +#define clfftEnqueueTransform clfftEnqueueTransform_pfn +#undef clfftGetLayout +//#define clfftGetLayout clfftGetLayout_pfn +#undef clfftGetPlanBatchSize +//#define clfftGetPlanBatchSize clfftGetPlanBatchSize_pfn +#undef clfftGetPlanContext +//#define clfftGetPlanContext clfftGetPlanContext_pfn +#undef clfftGetPlanDim +//#define clfftGetPlanDim clfftGetPlanDim_pfn +#undef clfftGetPlanDistance +//#define clfftGetPlanDistance clfftGetPlanDistance_pfn +#undef clfftGetPlanInStride +//#define clfftGetPlanInStride clfftGetPlanInStride_pfn +#undef clfftGetPlanLength +//#define clfftGetPlanLength clfftGetPlanLength_pfn +#undef clfftGetPlanOutStride +//#define clfftGetPlanOutStride clfftGetPlanOutStride_pfn +#undef clfftGetPlanPrecision +//#define clfftGetPlanPrecision clfftGetPlanPrecision_pfn +#undef clfftGetPlanScale +//#define clfftGetPlanScale clfftGetPlanScale_pfn +#undef clfftGetPlanTransposeResult +//#define clfftGetPlanTransposeResult clfftGetPlanTransposeResult_pfn +#undef clfftGetResultLocation +//#define clfftGetResultLocation clfftGetResultLocation_pfn +#undef clfftGetTmpBufSize +#define clfftGetTmpBufSize clfftGetTmpBufSize_pfn +#undef clfftGetVersion +#define clfftGetVersion clfftGetVersion_pfn +#undef clfftSetLayout +#define clfftSetLayout clfftSetLayout_pfn +#undef clfftSetPlanBatchSize +#define clfftSetPlanBatchSize clfftSetPlanBatchSize_pfn +#undef clfftSetPlanCallback +//#define clfftSetPlanCallback clfftSetPlanCallback_pfn +#undef clfftSetPlanDim +//#define clfftSetPlanDim clfftSetPlanDim_pfn +#undef clfftSetPlanDistance +#define clfftSetPlanDistance clfftSetPlanDistance_pfn +#undef clfftSetPlanInStride +#define clfftSetPlanInStride clfftSetPlanInStride_pfn +#undef clfftSetPlanLength +//#define clfftSetPlanLength clfftSetPlanLength_pfn +#undef clfftSetPlanOutStride +#define clfftSetPlanOutStride clfftSetPlanOutStride_pfn +#undef clfftSetPlanPrecision +#define clfftSetPlanPrecision clfftSetPlanPrecision_pfn +#undef clfftSetPlanScale +#define clfftSetPlanScale clfftSetPlanScale_pfn +#undef clfftSetPlanTransposeResult +//#define clfftSetPlanTransposeResult clfftSetPlanTransposeResult_pfn +#undef clfftSetResultLocation +#define clfftSetResultLocation clfftSetResultLocation_pfn +#undef clfftSetup +#define clfftSetup clfftSetup_pfn +#undef clfftTeardown +#define clfftTeardown clfftTeardown_pfn + +// generated by parser_clfft.py +extern CL_RUNTIME_EXPORT clfftStatus (*clfftBakePlan)(clfftPlanHandle plHandle, cl_uint numQueues, cl_command_queue* commQueueFFT, void (CL_CALLBACK* pfn_notify) (clfftPlanHandle plHandle, void* user_data), void* user_data); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftCopyPlan)(clfftPlanHandle* out_plHandle, cl_context new_context, clfftPlanHandle in_plHandle); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftCreateDefaultPlan)(clfftPlanHandle* plHandle, cl_context context, const clfftDim dim, const size_t* clLengths); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftDestroyPlan)(clfftPlanHandle* plHandle); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftEnqueueTransform)(clfftPlanHandle plHandle, clfftDirection dir, cl_uint numQueuesAndEvents, cl_command_queue* commQueues, cl_uint numWaitEvents, const cl_event* waitEvents, cl_event* outEvents, cl_mem* inputBuffers, cl_mem* outputBuffers, cl_mem tmpBuffer); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetLayout)(const clfftPlanHandle plHandle, clfftLayout* iLayout, clfftLayout* oLayout); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanBatchSize)(const clfftPlanHandle plHandle, size_t* batchSize); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanContext)(const clfftPlanHandle plHandle, cl_context* context); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDim)(const clfftPlanHandle plHandle, clfftDim* dim, cl_uint* size); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanDistance)(const clfftPlanHandle plHandle, size_t* iDist, size_t* oDist); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanInStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanLength)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clLengths); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanOutStride)(const clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanPrecision)(const clfftPlanHandle plHandle, clfftPrecision* precision); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanScale)(const clfftPlanHandle plHandle, clfftDirection dir, cl_float* scale); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetPlanTransposeResult)(const clfftPlanHandle plHandle, clfftResultTransposed* transposed); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetResultLocation)(const clfftPlanHandle plHandle, clfftResultLocation* placeness); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetTmpBufSize)(const clfftPlanHandle plHandle, size_t* buffersize); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftGetVersion)(cl_uint* major, cl_uint* minor, cl_uint* patch); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetLayout)(clfftPlanHandle plHandle, clfftLayout iLayout, clfftLayout oLayout); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanBatchSize)(clfftPlanHandle plHandle, size_t batchSize); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanCallback)(clfftPlanHandle plHandle, const char* funcName, const char* funcString, int localMemSize, clfftCallbackType callbackType, cl_mem* userdata, int numUserdataBuffers); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDim)(clfftPlanHandle plHandle, const clfftDim dim); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanDistance)(clfftPlanHandle plHandle, size_t iDist, size_t oDist); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanInStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanLength)(clfftPlanHandle plHandle, const clfftDim dim, const size_t* clLengths); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanOutStride)(clfftPlanHandle plHandle, const clfftDim dim, size_t* clStrides); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanPrecision)(clfftPlanHandle plHandle, clfftPrecision precision); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanScale)(clfftPlanHandle plHandle, clfftDirection dir, cl_float scale); +//extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetPlanTransposeResult)(clfftPlanHandle plHandle, clfftResultTransposed transposed); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetResultLocation)(clfftPlanHandle plHandle, clfftResultLocation placeness); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftSetup)(const clfftSetupData* setupData); +extern CL_RUNTIME_EXPORT clfftStatus (*clfftTeardown)(); diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp index b170241e3c..28618a1f3a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core.hpp @@ -1,371 +1,371 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP -#error "Invalid usage" -#endif - -// generated by parser_cl.py -#define clBuildProgram clBuildProgram_ -#define clCompileProgram clCompileProgram_ -#define clCreateBuffer clCreateBuffer_ -#define clCreateCommandQueue clCreateCommandQueue_ -#define clCreateContext clCreateContext_ -#define clCreateContextFromType clCreateContextFromType_ -#define clCreateImage clCreateImage_ -#define clCreateImage2D clCreateImage2D_ -#define clCreateImage3D clCreateImage3D_ -#define clCreateKernel clCreateKernel_ -#define clCreateKernelsInProgram clCreateKernelsInProgram_ -#define clCreateProgramWithBinary clCreateProgramWithBinary_ -#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_ -#define clCreateProgramWithSource clCreateProgramWithSource_ -#define clCreateSampler clCreateSampler_ -#define clCreateSubBuffer clCreateSubBuffer_ -#define clCreateSubDevices clCreateSubDevices_ -#define clCreateUserEvent clCreateUserEvent_ -#define clEnqueueBarrier clEnqueueBarrier_ -#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_ -#define clEnqueueCopyBuffer clEnqueueCopyBuffer_ -#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_ -#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_ -#define clEnqueueCopyImage clEnqueueCopyImage_ -#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_ -#define clEnqueueFillBuffer clEnqueueFillBuffer_ -#define clEnqueueFillImage clEnqueueFillImage_ -#define clEnqueueMapBuffer clEnqueueMapBuffer_ -#define clEnqueueMapImage clEnqueueMapImage_ -#define clEnqueueMarker clEnqueueMarker_ -#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_ -#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_ -#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_ -#define clEnqueueNativeKernel clEnqueueNativeKernel_ -#define clEnqueueReadBuffer clEnqueueReadBuffer_ -#define clEnqueueReadBufferRect clEnqueueReadBufferRect_ -#define clEnqueueReadImage clEnqueueReadImage_ -#define clEnqueueTask clEnqueueTask_ -#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_ -#define clEnqueueWaitForEvents clEnqueueWaitForEvents_ -#define clEnqueueWriteBuffer clEnqueueWriteBuffer_ -#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_ -#define clEnqueueWriteImage clEnqueueWriteImage_ -#define clFinish clFinish_ -#define clFlush clFlush_ -#define clGetCommandQueueInfo clGetCommandQueueInfo_ -#define clGetContextInfo clGetContextInfo_ -#define clGetDeviceIDs clGetDeviceIDs_ -#define clGetDeviceInfo clGetDeviceInfo_ -#define clGetEventInfo clGetEventInfo_ -#define clGetEventProfilingInfo clGetEventProfilingInfo_ -#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_ -#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_ -#define clGetImageInfo clGetImageInfo_ -#define clGetKernelArgInfo clGetKernelArgInfo_ -#define clGetKernelInfo clGetKernelInfo_ -#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_ -#define clGetMemObjectInfo clGetMemObjectInfo_ -#define clGetPlatformIDs clGetPlatformIDs_ -#define clGetPlatformInfo clGetPlatformInfo_ -#define clGetProgramBuildInfo clGetProgramBuildInfo_ -#define clGetProgramInfo clGetProgramInfo_ -#define clGetSamplerInfo clGetSamplerInfo_ -#define clGetSupportedImageFormats clGetSupportedImageFormats_ -#define clLinkProgram clLinkProgram_ -#define clReleaseCommandQueue clReleaseCommandQueue_ -#define clReleaseContext clReleaseContext_ -#define clReleaseDevice clReleaseDevice_ -#define clReleaseEvent clReleaseEvent_ -#define clReleaseKernel clReleaseKernel_ -#define clReleaseMemObject clReleaseMemObject_ -#define clReleaseProgram clReleaseProgram_ -#define clReleaseSampler clReleaseSampler_ -#define clRetainCommandQueue clRetainCommandQueue_ -#define clRetainContext clRetainContext_ -#define clRetainDevice clRetainDevice_ -#define clRetainEvent clRetainEvent_ -#define clRetainKernel clRetainKernel_ -#define clRetainMemObject clRetainMemObject_ -#define clRetainProgram clRetainProgram_ -#define clRetainSampler clRetainSampler_ -#define clSetEventCallback clSetEventCallback_ -#define clSetKernelArg clSetKernelArg_ -#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_ -#define clSetUserEventStatus clSetUserEventStatus_ -#define clUnloadCompiler clUnloadCompiler_ -#define clUnloadPlatformCompiler clUnloadPlatformCompiler_ -#define clWaitForEvents clWaitForEvents_ - -#if defined __APPLE__ -#define CL_SILENCE_DEPRECATION -#include -#else -#include -#endif - -// generated by parser_cl.py -#undef clBuildProgram -#define clBuildProgram clBuildProgram_pfn -#undef clCompileProgram -#define clCompileProgram clCompileProgram_pfn -#undef clCreateBuffer -#define clCreateBuffer clCreateBuffer_pfn -#undef clCreateCommandQueue -#define clCreateCommandQueue clCreateCommandQueue_pfn -#undef clCreateContext -#define clCreateContext clCreateContext_pfn -#undef clCreateContextFromType -#define clCreateContextFromType clCreateContextFromType_pfn -#undef clCreateImage -#define clCreateImage clCreateImage_pfn -#undef clCreateImage2D -#define clCreateImage2D clCreateImage2D_pfn -#undef clCreateImage3D -#define clCreateImage3D clCreateImage3D_pfn -#undef clCreateKernel -#define clCreateKernel clCreateKernel_pfn -#undef clCreateKernelsInProgram -#define clCreateKernelsInProgram clCreateKernelsInProgram_pfn -#undef clCreateProgramWithBinary -#define clCreateProgramWithBinary clCreateProgramWithBinary_pfn -#undef clCreateProgramWithBuiltInKernels -#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_pfn -#undef clCreateProgramWithSource -#define clCreateProgramWithSource clCreateProgramWithSource_pfn -#undef clCreateSampler -#define clCreateSampler clCreateSampler_pfn -#undef clCreateSubBuffer -#define clCreateSubBuffer clCreateSubBuffer_pfn -#undef clCreateSubDevices -#define clCreateSubDevices clCreateSubDevices_pfn -#undef clCreateUserEvent -#define clCreateUserEvent clCreateUserEvent_pfn -#undef clEnqueueBarrier -#define clEnqueueBarrier clEnqueueBarrier_pfn -#undef clEnqueueBarrierWithWaitList -#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_pfn -#undef clEnqueueCopyBuffer -#define clEnqueueCopyBuffer clEnqueueCopyBuffer_pfn -#undef clEnqueueCopyBufferRect -#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_pfn -#undef clEnqueueCopyBufferToImage -#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_pfn -#undef clEnqueueCopyImage -#define clEnqueueCopyImage clEnqueueCopyImage_pfn -#undef clEnqueueCopyImageToBuffer -#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_pfn -#undef clEnqueueFillBuffer -#define clEnqueueFillBuffer clEnqueueFillBuffer_pfn -#undef clEnqueueFillImage -#define clEnqueueFillImage clEnqueueFillImage_pfn -#undef clEnqueueMapBuffer -#define clEnqueueMapBuffer clEnqueueMapBuffer_pfn -#undef clEnqueueMapImage -#define clEnqueueMapImage clEnqueueMapImage_pfn -#undef clEnqueueMarker -#define clEnqueueMarker clEnqueueMarker_pfn -#undef clEnqueueMarkerWithWaitList -#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_pfn -#undef clEnqueueMigrateMemObjects -#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_pfn -#undef clEnqueueNDRangeKernel -#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_pfn -#undef clEnqueueNativeKernel -#define clEnqueueNativeKernel clEnqueueNativeKernel_pfn -#undef clEnqueueReadBuffer -#define clEnqueueReadBuffer clEnqueueReadBuffer_pfn -#undef clEnqueueReadBufferRect -#define clEnqueueReadBufferRect clEnqueueReadBufferRect_pfn -#undef clEnqueueReadImage -#define clEnqueueReadImage clEnqueueReadImage_pfn -#undef clEnqueueTask -#define clEnqueueTask clEnqueueTask_pfn -#undef clEnqueueUnmapMemObject -#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_pfn -#undef clEnqueueWaitForEvents -#define clEnqueueWaitForEvents clEnqueueWaitForEvents_pfn -#undef clEnqueueWriteBuffer -#define clEnqueueWriteBuffer clEnqueueWriteBuffer_pfn -#undef clEnqueueWriteBufferRect -#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_pfn -#undef clEnqueueWriteImage -#define clEnqueueWriteImage clEnqueueWriteImage_pfn -#undef clFinish -#define clFinish clFinish_pfn -#undef clFlush -#define clFlush clFlush_pfn -#undef clGetCommandQueueInfo -#define clGetCommandQueueInfo clGetCommandQueueInfo_pfn -#undef clGetContextInfo -#define clGetContextInfo clGetContextInfo_pfn -#undef clGetDeviceIDs -#define clGetDeviceIDs clGetDeviceIDs_pfn -#undef clGetDeviceInfo -#define clGetDeviceInfo clGetDeviceInfo_pfn -#undef clGetEventInfo -#define clGetEventInfo clGetEventInfo_pfn -#undef clGetEventProfilingInfo -#define clGetEventProfilingInfo clGetEventProfilingInfo_pfn -#undef clGetExtensionFunctionAddress -#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_pfn -#undef clGetExtensionFunctionAddressForPlatform -#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_pfn -#undef clGetImageInfo -#define clGetImageInfo clGetImageInfo_pfn -#undef clGetKernelArgInfo -#define clGetKernelArgInfo clGetKernelArgInfo_pfn -#undef clGetKernelInfo -#define clGetKernelInfo clGetKernelInfo_pfn -#undef clGetKernelWorkGroupInfo -#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_pfn -#undef clGetMemObjectInfo -#define clGetMemObjectInfo clGetMemObjectInfo_pfn -#undef clGetPlatformIDs -#define clGetPlatformIDs clGetPlatformIDs_pfn -#undef clGetPlatformInfo -#define clGetPlatformInfo clGetPlatformInfo_pfn -#undef clGetProgramBuildInfo -#define clGetProgramBuildInfo clGetProgramBuildInfo_pfn -#undef clGetProgramInfo -#define clGetProgramInfo clGetProgramInfo_pfn -#undef clGetSamplerInfo -#define clGetSamplerInfo clGetSamplerInfo_pfn -#undef clGetSupportedImageFormats -#define clGetSupportedImageFormats clGetSupportedImageFormats_pfn -#undef clLinkProgram -#define clLinkProgram clLinkProgram_pfn -#undef clReleaseCommandQueue -#define clReleaseCommandQueue clReleaseCommandQueue_pfn -#undef clReleaseContext -#define clReleaseContext clReleaseContext_pfn -#undef clReleaseDevice -#define clReleaseDevice clReleaseDevice_pfn -#undef clReleaseEvent -#define clReleaseEvent clReleaseEvent_pfn -#undef clReleaseKernel -#define clReleaseKernel clReleaseKernel_pfn -#undef clReleaseMemObject -#define clReleaseMemObject clReleaseMemObject_pfn -#undef clReleaseProgram -#define clReleaseProgram clReleaseProgram_pfn -#undef clReleaseSampler -#define clReleaseSampler clReleaseSampler_pfn -#undef clRetainCommandQueue -#define clRetainCommandQueue clRetainCommandQueue_pfn -#undef clRetainContext -#define clRetainContext clRetainContext_pfn -#undef clRetainDevice -#define clRetainDevice clRetainDevice_pfn -#undef clRetainEvent -#define clRetainEvent clRetainEvent_pfn -#undef clRetainKernel -#define clRetainKernel clRetainKernel_pfn -#undef clRetainMemObject -#define clRetainMemObject clRetainMemObject_pfn -#undef clRetainProgram -#define clRetainProgram clRetainProgram_pfn -#undef clRetainSampler -#define clRetainSampler clRetainSampler_pfn -#undef clSetEventCallback -#define clSetEventCallback clSetEventCallback_pfn -#undef clSetKernelArg -#define clSetKernelArg clSetKernelArg_pfn -#undef clSetMemObjectDestructorCallback -#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_pfn -#undef clSetUserEventStatus -#define clSetUserEventStatus clSetUserEventStatus_pfn -#undef clUnloadCompiler -#define clUnloadCompiler clUnloadCompiler_pfn -#undef clUnloadPlatformCompiler -#define clUnloadPlatformCompiler clUnloadPlatformCompiler_pfn -#undef clWaitForEvents -#define clWaitForEvents clWaitForEvents_pfn - -// generated by parser_cl.py -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clBuildProgram)(cl_program, cl_uint, const cl_device_id*, const char*, void (CL_CALLBACK*) (cl_program, void*), void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCompileProgram)(cl_program, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, const char**, void (CL_CALLBACK*) (cl_program, void*), void*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateBuffer)(cl_context, cl_mem_flags, size_t, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_command_queue (CL_API_CALL*clCreateCommandQueue)(cl_context, cl_device_id, cl_command_queue_properties, cl_int*); -extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContext)(const cl_context_properties*, cl_uint, const cl_device_id*, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContextFromType)(const cl_context_properties*, cl_device_type, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage)(cl_context, cl_mem_flags, const cl_image_format*, const cl_image_desc*, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage2D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage3D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_kernel (CL_API_CALL*clCreateKernel)(cl_program, const char*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateKernelsInProgram)(cl_program, cl_uint, cl_kernel*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBinary)(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBuiltInKernels)(cl_context, cl_uint, const cl_device_id*, const char*, cl_int*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithSource)(cl_context, cl_uint, const char**, const size_t*, cl_int*); -extern CL_RUNTIME_EXPORT cl_sampler (CL_API_CALL*clCreateSampler)(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateSubBuffer)(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateSubDevices)(cl_device_id, const cl_device_partition_property*, cl_uint, cl_device_id*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_event (CL_API_CALL*clCreateUserEvent)(cl_context, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrier)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrierWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBuffer)(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferRect)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferToImage)(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImage)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImageToBuffer)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillBuffer)(cl_command_queue, cl_mem, const void*, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillImage)(cl_command_queue, cl_mem, const void*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapBuffer)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapImage)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarker)(cl_command_queue, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarkerWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMigrateMemObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_mem_migration_flags, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNDRangeKernel)(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNativeKernel)(cl_command_queue, void (CL_CALLBACK*) (void*), void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueTask)(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueUnmapMemObject)(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWaitForEvents)(cl_command_queue, cl_uint, const cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFinish)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFlush)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetCommandQueueInfo)(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetContextInfo)(cl_context, cl_context_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceIDs)(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceInfo)(cl_device_id, cl_device_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventInfo)(cl_event, cl_event_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventProfilingInfo)(cl_event, cl_profiling_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddress)(const char*); -extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddressForPlatform)(cl_platform_id, const char*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetImageInfo)(cl_mem, cl_image_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelArgInfo)(cl_kernel, cl_uint, cl_kernel_arg_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelInfo)(cl_kernel, cl_kernel_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelWorkGroupInfo)(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetMemObjectInfo)(cl_mem, cl_mem_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformIDs)(cl_uint, cl_platform_id*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformInfo)(cl_platform_id, cl_platform_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramBuildInfo)(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramInfo)(cl_program, cl_program_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSamplerInfo)(cl_sampler, cl_sampler_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSupportedImageFormats)(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*); -extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clLinkProgram)(cl_context, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, void (CL_CALLBACK*) (cl_program, void*), void*, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseCommandQueue)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseContext)(cl_context); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseDevice)(cl_device_id); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseEvent)(cl_event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseKernel)(cl_kernel); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseMemObject)(cl_mem); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseProgram)(cl_program); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseSampler)(cl_sampler); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainCommandQueue)(cl_command_queue); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainContext)(cl_context); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainDevice)(cl_device_id); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainEvent)(cl_event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainKernel)(cl_kernel); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainMemObject)(cl_mem); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainProgram)(cl_program); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainSampler)(cl_sampler); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetEventCallback)(cl_event, cl_int, void (CL_CALLBACK*) (cl_event, cl_int, void*), void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetKernelArg)(cl_kernel, cl_uint, size_t, const void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetMemObjectDestructorCallback)(cl_mem, void (CL_CALLBACK*) (cl_mem, void*), void*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetUserEventStatus)(cl_event, cl_int); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadCompiler)(); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadPlatformCompiler)(cl_platform_id); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clWaitForEvents)(cl_uint, const cl_event*); +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP +#error "Invalid usage" +#endif + +// generated by parser_cl.py +#define clBuildProgram clBuildProgram_ +#define clCompileProgram clCompileProgram_ +#define clCreateBuffer clCreateBuffer_ +#define clCreateCommandQueue clCreateCommandQueue_ +#define clCreateContext clCreateContext_ +#define clCreateContextFromType clCreateContextFromType_ +#define clCreateImage clCreateImage_ +#define clCreateImage2D clCreateImage2D_ +#define clCreateImage3D clCreateImage3D_ +#define clCreateKernel clCreateKernel_ +#define clCreateKernelsInProgram clCreateKernelsInProgram_ +#define clCreateProgramWithBinary clCreateProgramWithBinary_ +#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_ +#define clCreateProgramWithSource clCreateProgramWithSource_ +#define clCreateSampler clCreateSampler_ +#define clCreateSubBuffer clCreateSubBuffer_ +#define clCreateSubDevices clCreateSubDevices_ +#define clCreateUserEvent clCreateUserEvent_ +#define clEnqueueBarrier clEnqueueBarrier_ +#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_ +#define clEnqueueCopyBuffer clEnqueueCopyBuffer_ +#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_ +#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_ +#define clEnqueueCopyImage clEnqueueCopyImage_ +#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_ +#define clEnqueueFillBuffer clEnqueueFillBuffer_ +#define clEnqueueFillImage clEnqueueFillImage_ +#define clEnqueueMapBuffer clEnqueueMapBuffer_ +#define clEnqueueMapImage clEnqueueMapImage_ +#define clEnqueueMarker clEnqueueMarker_ +#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_ +#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_ +#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_ +#define clEnqueueNativeKernel clEnqueueNativeKernel_ +#define clEnqueueReadBuffer clEnqueueReadBuffer_ +#define clEnqueueReadBufferRect clEnqueueReadBufferRect_ +#define clEnqueueReadImage clEnqueueReadImage_ +#define clEnqueueTask clEnqueueTask_ +#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_ +#define clEnqueueWaitForEvents clEnqueueWaitForEvents_ +#define clEnqueueWriteBuffer clEnqueueWriteBuffer_ +#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_ +#define clEnqueueWriteImage clEnqueueWriteImage_ +#define clFinish clFinish_ +#define clFlush clFlush_ +#define clGetCommandQueueInfo clGetCommandQueueInfo_ +#define clGetContextInfo clGetContextInfo_ +#define clGetDeviceIDs clGetDeviceIDs_ +#define clGetDeviceInfo clGetDeviceInfo_ +#define clGetEventInfo clGetEventInfo_ +#define clGetEventProfilingInfo clGetEventProfilingInfo_ +#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_ +#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_ +#define clGetImageInfo clGetImageInfo_ +#define clGetKernelArgInfo clGetKernelArgInfo_ +#define clGetKernelInfo clGetKernelInfo_ +#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_ +#define clGetMemObjectInfo clGetMemObjectInfo_ +#define clGetPlatformIDs clGetPlatformIDs_ +#define clGetPlatformInfo clGetPlatformInfo_ +#define clGetProgramBuildInfo clGetProgramBuildInfo_ +#define clGetProgramInfo clGetProgramInfo_ +#define clGetSamplerInfo clGetSamplerInfo_ +#define clGetSupportedImageFormats clGetSupportedImageFormats_ +#define clLinkProgram clLinkProgram_ +#define clReleaseCommandQueue clReleaseCommandQueue_ +#define clReleaseContext clReleaseContext_ +#define clReleaseDevice clReleaseDevice_ +#define clReleaseEvent clReleaseEvent_ +#define clReleaseKernel clReleaseKernel_ +#define clReleaseMemObject clReleaseMemObject_ +#define clReleaseProgram clReleaseProgram_ +#define clReleaseSampler clReleaseSampler_ +#define clRetainCommandQueue clRetainCommandQueue_ +#define clRetainContext clRetainContext_ +#define clRetainDevice clRetainDevice_ +#define clRetainEvent clRetainEvent_ +#define clRetainKernel clRetainKernel_ +#define clRetainMemObject clRetainMemObject_ +#define clRetainProgram clRetainProgram_ +#define clRetainSampler clRetainSampler_ +#define clSetEventCallback clSetEventCallback_ +#define clSetKernelArg clSetKernelArg_ +#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_ +#define clSetUserEventStatus clSetUserEventStatus_ +#define clUnloadCompiler clUnloadCompiler_ +#define clUnloadPlatformCompiler clUnloadPlatformCompiler_ +#define clWaitForEvents clWaitForEvents_ + +#if defined __APPLE__ +#define CL_SILENCE_DEPRECATION +#include +#else +#include +#endif + +// generated by parser_cl.py +#undef clBuildProgram +#define clBuildProgram clBuildProgram_pfn +#undef clCompileProgram +#define clCompileProgram clCompileProgram_pfn +#undef clCreateBuffer +#define clCreateBuffer clCreateBuffer_pfn +#undef clCreateCommandQueue +#define clCreateCommandQueue clCreateCommandQueue_pfn +#undef clCreateContext +#define clCreateContext clCreateContext_pfn +#undef clCreateContextFromType +#define clCreateContextFromType clCreateContextFromType_pfn +#undef clCreateImage +#define clCreateImage clCreateImage_pfn +#undef clCreateImage2D +#define clCreateImage2D clCreateImage2D_pfn +#undef clCreateImage3D +#define clCreateImage3D clCreateImage3D_pfn +#undef clCreateKernel +#define clCreateKernel clCreateKernel_pfn +#undef clCreateKernelsInProgram +#define clCreateKernelsInProgram clCreateKernelsInProgram_pfn +#undef clCreateProgramWithBinary +#define clCreateProgramWithBinary clCreateProgramWithBinary_pfn +#undef clCreateProgramWithBuiltInKernels +#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_pfn +#undef clCreateProgramWithSource +#define clCreateProgramWithSource clCreateProgramWithSource_pfn +#undef clCreateSampler +#define clCreateSampler clCreateSampler_pfn +#undef clCreateSubBuffer +#define clCreateSubBuffer clCreateSubBuffer_pfn +#undef clCreateSubDevices +#define clCreateSubDevices clCreateSubDevices_pfn +#undef clCreateUserEvent +#define clCreateUserEvent clCreateUserEvent_pfn +#undef clEnqueueBarrier +#define clEnqueueBarrier clEnqueueBarrier_pfn +#undef clEnqueueBarrierWithWaitList +#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_pfn +#undef clEnqueueCopyBuffer +#define clEnqueueCopyBuffer clEnqueueCopyBuffer_pfn +#undef clEnqueueCopyBufferRect +#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_pfn +#undef clEnqueueCopyBufferToImage +#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_pfn +#undef clEnqueueCopyImage +#define clEnqueueCopyImage clEnqueueCopyImage_pfn +#undef clEnqueueCopyImageToBuffer +#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_pfn +#undef clEnqueueFillBuffer +#define clEnqueueFillBuffer clEnqueueFillBuffer_pfn +#undef clEnqueueFillImage +#define clEnqueueFillImage clEnqueueFillImage_pfn +#undef clEnqueueMapBuffer +#define clEnqueueMapBuffer clEnqueueMapBuffer_pfn +#undef clEnqueueMapImage +#define clEnqueueMapImage clEnqueueMapImage_pfn +#undef clEnqueueMarker +#define clEnqueueMarker clEnqueueMarker_pfn +#undef clEnqueueMarkerWithWaitList +#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_pfn +#undef clEnqueueMigrateMemObjects +#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_pfn +#undef clEnqueueNDRangeKernel +#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_pfn +#undef clEnqueueNativeKernel +#define clEnqueueNativeKernel clEnqueueNativeKernel_pfn +#undef clEnqueueReadBuffer +#define clEnqueueReadBuffer clEnqueueReadBuffer_pfn +#undef clEnqueueReadBufferRect +#define clEnqueueReadBufferRect clEnqueueReadBufferRect_pfn +#undef clEnqueueReadImage +#define clEnqueueReadImage clEnqueueReadImage_pfn +#undef clEnqueueTask +#define clEnqueueTask clEnqueueTask_pfn +#undef clEnqueueUnmapMemObject +#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_pfn +#undef clEnqueueWaitForEvents +#define clEnqueueWaitForEvents clEnqueueWaitForEvents_pfn +#undef clEnqueueWriteBuffer +#define clEnqueueWriteBuffer clEnqueueWriteBuffer_pfn +#undef clEnqueueWriteBufferRect +#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_pfn +#undef clEnqueueWriteImage +#define clEnqueueWriteImage clEnqueueWriteImage_pfn +#undef clFinish +#define clFinish clFinish_pfn +#undef clFlush +#define clFlush clFlush_pfn +#undef clGetCommandQueueInfo +#define clGetCommandQueueInfo clGetCommandQueueInfo_pfn +#undef clGetContextInfo +#define clGetContextInfo clGetContextInfo_pfn +#undef clGetDeviceIDs +#define clGetDeviceIDs clGetDeviceIDs_pfn +#undef clGetDeviceInfo +#define clGetDeviceInfo clGetDeviceInfo_pfn +#undef clGetEventInfo +#define clGetEventInfo clGetEventInfo_pfn +#undef clGetEventProfilingInfo +#define clGetEventProfilingInfo clGetEventProfilingInfo_pfn +#undef clGetExtensionFunctionAddress +#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_pfn +#undef clGetExtensionFunctionAddressForPlatform +#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_pfn +#undef clGetImageInfo +#define clGetImageInfo clGetImageInfo_pfn +#undef clGetKernelArgInfo +#define clGetKernelArgInfo clGetKernelArgInfo_pfn +#undef clGetKernelInfo +#define clGetKernelInfo clGetKernelInfo_pfn +#undef clGetKernelWorkGroupInfo +#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_pfn +#undef clGetMemObjectInfo +#define clGetMemObjectInfo clGetMemObjectInfo_pfn +#undef clGetPlatformIDs +#define clGetPlatformIDs clGetPlatformIDs_pfn +#undef clGetPlatformInfo +#define clGetPlatformInfo clGetPlatformInfo_pfn +#undef clGetProgramBuildInfo +#define clGetProgramBuildInfo clGetProgramBuildInfo_pfn +#undef clGetProgramInfo +#define clGetProgramInfo clGetProgramInfo_pfn +#undef clGetSamplerInfo +#define clGetSamplerInfo clGetSamplerInfo_pfn +#undef clGetSupportedImageFormats +#define clGetSupportedImageFormats clGetSupportedImageFormats_pfn +#undef clLinkProgram +#define clLinkProgram clLinkProgram_pfn +#undef clReleaseCommandQueue +#define clReleaseCommandQueue clReleaseCommandQueue_pfn +#undef clReleaseContext +#define clReleaseContext clReleaseContext_pfn +#undef clReleaseDevice +#define clReleaseDevice clReleaseDevice_pfn +#undef clReleaseEvent +#define clReleaseEvent clReleaseEvent_pfn +#undef clReleaseKernel +#define clReleaseKernel clReleaseKernel_pfn +#undef clReleaseMemObject +#define clReleaseMemObject clReleaseMemObject_pfn +#undef clReleaseProgram +#define clReleaseProgram clReleaseProgram_pfn +#undef clReleaseSampler +#define clReleaseSampler clReleaseSampler_pfn +#undef clRetainCommandQueue +#define clRetainCommandQueue clRetainCommandQueue_pfn +#undef clRetainContext +#define clRetainContext clRetainContext_pfn +#undef clRetainDevice +#define clRetainDevice clRetainDevice_pfn +#undef clRetainEvent +#define clRetainEvent clRetainEvent_pfn +#undef clRetainKernel +#define clRetainKernel clRetainKernel_pfn +#undef clRetainMemObject +#define clRetainMemObject clRetainMemObject_pfn +#undef clRetainProgram +#define clRetainProgram clRetainProgram_pfn +#undef clRetainSampler +#define clRetainSampler clRetainSampler_pfn +#undef clSetEventCallback +#define clSetEventCallback clSetEventCallback_pfn +#undef clSetKernelArg +#define clSetKernelArg clSetKernelArg_pfn +#undef clSetMemObjectDestructorCallback +#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_pfn +#undef clSetUserEventStatus +#define clSetUserEventStatus clSetUserEventStatus_pfn +#undef clUnloadCompiler +#define clUnloadCompiler clUnloadCompiler_pfn +#undef clUnloadPlatformCompiler +#define clUnloadPlatformCompiler clUnloadPlatformCompiler_pfn +#undef clWaitForEvents +#define clWaitForEvents clWaitForEvents_pfn + +// generated by parser_cl.py +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clBuildProgram)(cl_program, cl_uint, const cl_device_id*, const char*, void (CL_CALLBACK*) (cl_program, void*), void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCompileProgram)(cl_program, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, const char**, void (CL_CALLBACK*) (cl_program, void*), void*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateBuffer)(cl_context, cl_mem_flags, size_t, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_command_queue (CL_API_CALL*clCreateCommandQueue)(cl_context, cl_device_id, cl_command_queue_properties, cl_int*); +extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContext)(const cl_context_properties*, cl_uint, const cl_device_id*, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_context (CL_API_CALL*clCreateContextFromType)(const cl_context_properties*, cl_device_type, void (CL_CALLBACK*) (const char*, const void*, size_t, void*), void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage)(cl_context, cl_mem_flags, const cl_image_format*, const cl_image_desc*, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage2D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateImage3D)(cl_context, cl_mem_flags, const cl_image_format*, size_t, size_t, size_t, size_t, size_t, void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_kernel (CL_API_CALL*clCreateKernel)(cl_program, const char*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateKernelsInProgram)(cl_program, cl_uint, cl_kernel*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBinary)(cl_context, cl_uint, const cl_device_id*, const size_t*, const unsigned char**, cl_int*, cl_int*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithBuiltInKernels)(cl_context, cl_uint, const cl_device_id*, const char*, cl_int*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clCreateProgramWithSource)(cl_context, cl_uint, const char**, const size_t*, cl_int*); +extern CL_RUNTIME_EXPORT cl_sampler (CL_API_CALL*clCreateSampler)(cl_context, cl_bool, cl_addressing_mode, cl_filter_mode, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateSubBuffer)(cl_mem, cl_mem_flags, cl_buffer_create_type, const void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clCreateSubDevices)(cl_device_id, const cl_device_partition_property*, cl_uint, cl_device_id*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_event (CL_API_CALL*clCreateUserEvent)(cl_context, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrier)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueBarrierWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBuffer)(cl_command_queue, cl_mem, cl_mem, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferRect)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyBufferToImage)(cl_command_queue, cl_mem, cl_mem, size_t, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImage)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueCopyImageToBuffer)(cl_command_queue, cl_mem, cl_mem, const size_t*, const size_t*, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillBuffer)(cl_command_queue, cl_mem, const void*, size_t, size_t, size_t, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueFillImage)(cl_command_queue, cl_mem, const void*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapBuffer)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, size_t, size_t, cl_uint, const cl_event*, cl_event*, cl_int*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clEnqueueMapImage)(cl_command_queue, cl_mem, cl_bool, cl_map_flags, const size_t*, const size_t*, size_t*, size_t*, cl_uint, const cl_event*, cl_event*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarker)(cl_command_queue, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMarkerWithWaitList)(cl_command_queue, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueMigrateMemObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_mem_migration_flags, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNDRangeKernel)(cl_command_queue, cl_kernel, cl_uint, const size_t*, const size_t*, const size_t*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueNativeKernel)(cl_command_queue, void (CL_CALLBACK*) (void*), void*, size_t, cl_uint, const cl_mem*, const void**, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReadImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueTask)(cl_command_queue, cl_kernel, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueUnmapMemObject)(cl_command_queue, cl_mem, void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWaitForEvents)(cl_command_queue, cl_uint, const cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBuffer)(cl_command_queue, cl_mem, cl_bool, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteBufferRect)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, const size_t*, size_t, size_t, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueWriteImage)(cl_command_queue, cl_mem, cl_bool, const size_t*, const size_t*, size_t, size_t, const void*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFinish)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clFlush)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetCommandQueueInfo)(cl_command_queue, cl_command_queue_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetContextInfo)(cl_context, cl_context_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceIDs)(cl_platform_id, cl_device_type, cl_uint, cl_device_id*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetDeviceInfo)(cl_device_id, cl_device_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventInfo)(cl_event, cl_event_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetEventProfilingInfo)(cl_event, cl_profiling_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddress)(const char*); +extern CL_RUNTIME_EXPORT void* (CL_API_CALL*clGetExtensionFunctionAddressForPlatform)(cl_platform_id, const char*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetImageInfo)(cl_mem, cl_image_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelArgInfo)(cl_kernel, cl_uint, cl_kernel_arg_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelInfo)(cl_kernel, cl_kernel_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetKernelWorkGroupInfo)(cl_kernel, cl_device_id, cl_kernel_work_group_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetMemObjectInfo)(cl_mem, cl_mem_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformIDs)(cl_uint, cl_platform_id*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetPlatformInfo)(cl_platform_id, cl_platform_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramBuildInfo)(cl_program, cl_device_id, cl_program_build_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetProgramInfo)(cl_program, cl_program_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSamplerInfo)(cl_sampler, cl_sampler_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetSupportedImageFormats)(cl_context, cl_mem_flags, cl_mem_object_type, cl_uint, cl_image_format*, cl_uint*); +extern CL_RUNTIME_EXPORT cl_program (CL_API_CALL*clLinkProgram)(cl_context, cl_uint, const cl_device_id*, const char*, cl_uint, const cl_program*, void (CL_CALLBACK*) (cl_program, void*), void*, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseCommandQueue)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseContext)(cl_context); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseDevice)(cl_device_id); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseEvent)(cl_event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseKernel)(cl_kernel); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseMemObject)(cl_mem); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseProgram)(cl_program); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clReleaseSampler)(cl_sampler); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainCommandQueue)(cl_command_queue); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainContext)(cl_context); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainDevice)(cl_device_id); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainEvent)(cl_event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainKernel)(cl_kernel); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainMemObject)(cl_mem); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainProgram)(cl_program); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clRetainSampler)(cl_sampler); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetEventCallback)(cl_event, cl_int, void (CL_CALLBACK*) (cl_event, cl_int, void*), void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetKernelArg)(cl_kernel, cl_uint, size_t, const void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetMemObjectDestructorCallback)(cl_mem, void (CL_CALLBACK*) (cl_mem, void*), void*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clSetUserEventStatus)(cl_event, cl_int); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadCompiler)(); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clUnloadPlatformCompiler)(cl_platform_id); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clWaitForEvents)(cl_uint, const cl_event*); diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp index 418b5126c3..216b22b8a8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_core_wrappers.hpp @@ -1,272 +1,272 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP -#error "Invalid usage" -#endif - -// generated by parser_cl.py -#undef clBuildProgram -#define clBuildProgram clBuildProgram_fn -inline cl_int clBuildProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, void (CL_CALLBACK*p4) (cl_program, void*), void* p5) { return clBuildProgram_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCompileProgram -#define clCompileProgram clCompileProgram_fn -inline cl_int clCompileProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, const char** p6, void (CL_CALLBACK*p7) (cl_program, void*), void* p8) { return clCompileProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clCreateBuffer -#define clCreateBuffer clCreateBuffer_fn -inline cl_mem clCreateBuffer(cl_context p0, cl_mem_flags p1, size_t p2, void* p3, cl_int* p4) { return clCreateBuffer_pfn(p0, p1, p2, p3, p4); } -#undef clCreateCommandQueue -#define clCreateCommandQueue clCreateCommandQueue_fn -inline cl_command_queue clCreateCommandQueue(cl_context p0, cl_device_id p1, cl_command_queue_properties p2, cl_int* p3) { return clCreateCommandQueue_pfn(p0, p1, p2, p3); } -#undef clCreateContext -#define clCreateContext clCreateContext_fn -inline cl_context clCreateContext(const cl_context_properties* p0, cl_uint p1, const cl_device_id* p2, void (CL_CALLBACK*p3) (const char*, const void*, size_t, void*), void* p4, cl_int* p5) { return clCreateContext_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateContextFromType -#define clCreateContextFromType clCreateContextFromType_fn -inline cl_context clCreateContextFromType(const cl_context_properties* p0, cl_device_type p1, void (CL_CALLBACK*p2) (const char*, const void*, size_t, void*), void* p3, cl_int* p4) { return clCreateContextFromType_pfn(p0, p1, p2, p3, p4); } -#undef clCreateImage -#define clCreateImage clCreateImage_fn -inline cl_mem clCreateImage(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, const cl_image_desc* p3, void* p4, cl_int* p5) { return clCreateImage_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateImage2D -#define clCreateImage2D clCreateImage2D_fn -inline cl_mem clCreateImage2D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, void* p6, cl_int* p7) { return clCreateImage2D_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } -#undef clCreateImage3D -#define clCreateImage3D clCreateImage3D_fn -inline cl_mem clCreateImage3D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, size_t p6, size_t p7, void* p8, cl_int* p9) { return clCreateImage3D_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } -#undef clCreateKernel -#define clCreateKernel clCreateKernel_fn -inline cl_kernel clCreateKernel(cl_program p0, const char* p1, cl_int* p2) { return clCreateKernel_pfn(p0, p1, p2); } -#undef clCreateKernelsInProgram -#define clCreateKernelsInProgram clCreateKernelsInProgram_fn -inline cl_int clCreateKernelsInProgram(cl_program p0, cl_uint p1, cl_kernel* p2, cl_uint* p3) { return clCreateKernelsInProgram_pfn(p0, p1, p2, p3); } -#undef clCreateProgramWithBinary -#define clCreateProgramWithBinary clCreateProgramWithBinary_fn -inline cl_program clCreateProgramWithBinary(cl_context p0, cl_uint p1, const cl_device_id* p2, const size_t* p3, const unsigned char** p4, cl_int* p5, cl_int* p6) { return clCreateProgramWithBinary_pfn(p0, p1, p2, p3, p4, p5, p6); } -#undef clCreateProgramWithBuiltInKernels -#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_fn -inline cl_program clCreateProgramWithBuiltInKernels(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_int* p4) { return clCreateProgramWithBuiltInKernels_pfn(p0, p1, p2, p3, p4); } -#undef clCreateProgramWithSource -#define clCreateProgramWithSource clCreateProgramWithSource_fn -inline cl_program clCreateProgramWithSource(cl_context p0, cl_uint p1, const char** p2, const size_t* p3, cl_int* p4) { return clCreateProgramWithSource_pfn(p0, p1, p2, p3, p4); } -#undef clCreateSampler -#define clCreateSampler clCreateSampler_fn -inline cl_sampler clCreateSampler(cl_context p0, cl_bool p1, cl_addressing_mode p2, cl_filter_mode p3, cl_int* p4) { return clCreateSampler_pfn(p0, p1, p2, p3, p4); } -#undef clCreateSubBuffer -#define clCreateSubBuffer clCreateSubBuffer_fn -inline cl_mem clCreateSubBuffer(cl_mem p0, cl_mem_flags p1, cl_buffer_create_type p2, const void* p3, cl_int* p4) { return clCreateSubBuffer_pfn(p0, p1, p2, p3, p4); } -#undef clCreateSubDevices -#define clCreateSubDevices clCreateSubDevices_fn -inline cl_int clCreateSubDevices(cl_device_id p0, const cl_device_partition_property* p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clCreateSubDevices_pfn(p0, p1, p2, p3, p4); } -#undef clCreateUserEvent -#define clCreateUserEvent clCreateUserEvent_fn -inline cl_event clCreateUserEvent(cl_context p0, cl_int* p1) { return clCreateUserEvent_pfn(p0, p1); } -#undef clEnqueueBarrier -#define clEnqueueBarrier clEnqueueBarrier_fn -inline cl_int clEnqueueBarrier(cl_command_queue p0) { return clEnqueueBarrier_pfn(p0); } -#undef clEnqueueBarrierWithWaitList -#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_fn -inline cl_int clEnqueueBarrierWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueBarrierWithWaitList_pfn(p0, p1, p2, p3); } -#undef clEnqueueCopyBuffer -#define clEnqueueCopyBuffer clEnqueueCopyBuffer_fn -inline cl_int clEnqueueCopyBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueCopyBufferRect -#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_fn -inline cl_int clEnqueueCopyBufferRect(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, cl_uint p10, const cl_event* p11, cl_event* p12) { return clEnqueueCopyBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); } -#undef clEnqueueCopyBufferToImage -#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_fn -inline cl_int clEnqueueCopyBufferToImage(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBufferToImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueCopyImage -#define clEnqueueCopyImage clEnqueueCopyImage_fn -inline cl_int clEnqueueCopyImage(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueCopyImageToBuffer -#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_fn -inline cl_int clEnqueueCopyImageToBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImageToBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueFillBuffer -#define clEnqueueFillBuffer clEnqueueFillBuffer_fn -inline cl_int clEnqueueFillBuffer(cl_command_queue p0, cl_mem p1, const void* p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueFillBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueFillImage -#define clEnqueueFillImage clEnqueueFillImage_fn -inline cl_int clEnqueueFillImage(cl_command_queue p0, cl_mem p1, const void* p2, const size_t* p3, const size_t* p4, cl_uint p5, const cl_event* p6, cl_event* p7) { return clEnqueueFillImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } -#undef clEnqueueMapBuffer -#define clEnqueueMapBuffer clEnqueueMapBuffer_fn -inline void* clEnqueueMapBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8, cl_int* p9) { return clEnqueueMapBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } -#undef clEnqueueMapImage -#define clEnqueueMapImage clEnqueueMapImage_fn -inline void* clEnqueueMapImage(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, const size_t* p4, const size_t* p5, size_t* p6, size_t* p7, cl_uint p8, const cl_event* p9, cl_event* p10, cl_int* p11) { return clEnqueueMapImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); } -#undef clEnqueueMarker -#define clEnqueueMarker clEnqueueMarker_fn -inline cl_int clEnqueueMarker(cl_command_queue p0, cl_event* p1) { return clEnqueueMarker_pfn(p0, p1); } -#undef clEnqueueMarkerWithWaitList -#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_fn -inline cl_int clEnqueueMarkerWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueMarkerWithWaitList_pfn(p0, p1, p2, p3); } -#undef clEnqueueMigrateMemObjects -#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_fn -inline cl_int clEnqueueMigrateMemObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_mem_migration_flags p3, cl_uint p4, const cl_event* p5, cl_event* p6) { return clEnqueueMigrateMemObjects_pfn(p0, p1, p2, p3, p4, p5, p6); } -#undef clEnqueueNDRangeKernel -#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_fn -inline cl_int clEnqueueNDRangeKernel(cl_command_queue p0, cl_kernel p1, cl_uint p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueNDRangeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueNativeKernel -#define clEnqueueNativeKernel clEnqueueNativeKernel_fn -inline cl_int clEnqueueNativeKernel(cl_command_queue p0, void (CL_CALLBACK*p1) (void*), void* p2, size_t p3, cl_uint p4, const cl_mem* p5, const void** p6, cl_uint p7, const cl_event* p8, cl_event* p9) { return clEnqueueNativeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } -#undef clEnqueueReadBuffer -#define clEnqueueReadBuffer clEnqueueReadBuffer_fn -inline cl_int clEnqueueReadBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueReadBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueReadBufferRect -#define clEnqueueReadBufferRect clEnqueueReadBufferRect_fn -inline cl_int clEnqueueReadBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueReadBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } -#undef clEnqueueReadImage -#define clEnqueueReadImage clEnqueueReadImage_fn -inline cl_int clEnqueueReadImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueReadImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } -#undef clEnqueueTask -#define clEnqueueTask clEnqueueTask_fn -inline cl_int clEnqueueTask(cl_command_queue p0, cl_kernel p1, cl_uint p2, const cl_event* p3, cl_event* p4) { return clEnqueueTask_pfn(p0, p1, p2, p3, p4); } -#undef clEnqueueUnmapMemObject -#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_fn -inline cl_int clEnqueueUnmapMemObject(cl_command_queue p0, cl_mem p1, void* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueUnmapMemObject_pfn(p0, p1, p2, p3, p4, p5); } -#undef clEnqueueWaitForEvents -#define clEnqueueWaitForEvents clEnqueueWaitForEvents_fn -inline cl_int clEnqueueWaitForEvents(cl_command_queue p0, cl_uint p1, const cl_event* p2) { return clEnqueueWaitForEvents_pfn(p0, p1, p2); } -#undef clEnqueueWriteBuffer -#define clEnqueueWriteBuffer clEnqueueWriteBuffer_fn -inline cl_int clEnqueueWriteBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, const void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueWriteBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clEnqueueWriteBufferRect -#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_fn -inline cl_int clEnqueueWriteBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, const void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueWriteBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } -#undef clEnqueueWriteImage -#define clEnqueueWriteImage clEnqueueWriteImage_fn -inline cl_int clEnqueueWriteImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, const void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueWriteImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } -#undef clFinish -#define clFinish clFinish_fn -inline cl_int clFinish(cl_command_queue p0) { return clFinish_pfn(p0); } -#undef clFlush -#define clFlush clFlush_fn -inline cl_int clFlush(cl_command_queue p0) { return clFlush_pfn(p0); } -#undef clGetCommandQueueInfo -#define clGetCommandQueueInfo clGetCommandQueueInfo_fn -inline cl_int clGetCommandQueueInfo(cl_command_queue p0, cl_command_queue_info p1, size_t p2, void* p3, size_t* p4) { return clGetCommandQueueInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetContextInfo -#define clGetContextInfo clGetContextInfo_fn -inline cl_int clGetContextInfo(cl_context p0, cl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetContextInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetDeviceIDs -#define clGetDeviceIDs clGetDeviceIDs_fn -inline cl_int clGetDeviceIDs(cl_platform_id p0, cl_device_type p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clGetDeviceIDs_pfn(p0, p1, p2, p3, p4); } -#undef clGetDeviceInfo -#define clGetDeviceInfo clGetDeviceInfo_fn -inline cl_int clGetDeviceInfo(cl_device_id p0, cl_device_info p1, size_t p2, void* p3, size_t* p4) { return clGetDeviceInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetEventInfo -#define clGetEventInfo clGetEventInfo_fn -inline cl_int clGetEventInfo(cl_event p0, cl_event_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetEventProfilingInfo -#define clGetEventProfilingInfo clGetEventProfilingInfo_fn -inline cl_int clGetEventProfilingInfo(cl_event p0, cl_profiling_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventProfilingInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetExtensionFunctionAddress -#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_fn -inline void* clGetExtensionFunctionAddress(const char* p0) { return clGetExtensionFunctionAddress_pfn(p0); } -#undef clGetExtensionFunctionAddressForPlatform -#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_fn -inline void* clGetExtensionFunctionAddressForPlatform(cl_platform_id p0, const char* p1) { return clGetExtensionFunctionAddressForPlatform_pfn(p0, p1); } -#undef clGetImageInfo -#define clGetImageInfo clGetImageInfo_fn -inline cl_int clGetImageInfo(cl_mem p0, cl_image_info p1, size_t p2, void* p3, size_t* p4) { return clGetImageInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetKernelArgInfo -#define clGetKernelArgInfo clGetKernelArgInfo_fn -inline cl_int clGetKernelArgInfo(cl_kernel p0, cl_uint p1, cl_kernel_arg_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelArgInfo_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetKernelInfo -#define clGetKernelInfo clGetKernelInfo_fn -inline cl_int clGetKernelInfo(cl_kernel p0, cl_kernel_info p1, size_t p2, void* p3, size_t* p4) { return clGetKernelInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetKernelWorkGroupInfo -#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_fn -inline cl_int clGetKernelWorkGroupInfo(cl_kernel p0, cl_device_id p1, cl_kernel_work_group_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelWorkGroupInfo_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetMemObjectInfo -#define clGetMemObjectInfo clGetMemObjectInfo_fn -inline cl_int clGetMemObjectInfo(cl_mem p0, cl_mem_info p1, size_t p2, void* p3, size_t* p4) { return clGetMemObjectInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetPlatformIDs -#define clGetPlatformIDs clGetPlatformIDs_fn -inline cl_int clGetPlatformIDs(cl_uint p0, cl_platform_id* p1, cl_uint* p2) { return clGetPlatformIDs_pfn(p0, p1, p2); } -#undef clGetPlatformInfo -#define clGetPlatformInfo clGetPlatformInfo_fn -inline cl_int clGetPlatformInfo(cl_platform_id p0, cl_platform_info p1, size_t p2, void* p3, size_t* p4) { return clGetPlatformInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetProgramBuildInfo -#define clGetProgramBuildInfo clGetProgramBuildInfo_fn -inline cl_int clGetProgramBuildInfo(cl_program p0, cl_device_id p1, cl_program_build_info p2, size_t p3, void* p4, size_t* p5) { return clGetProgramBuildInfo_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetProgramInfo -#define clGetProgramInfo clGetProgramInfo_fn -inline cl_int clGetProgramInfo(cl_program p0, cl_program_info p1, size_t p2, void* p3, size_t* p4) { return clGetProgramInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetSamplerInfo -#define clGetSamplerInfo clGetSamplerInfo_fn -inline cl_int clGetSamplerInfo(cl_sampler p0, cl_sampler_info p1, size_t p2, void* p3, size_t* p4) { return clGetSamplerInfo_pfn(p0, p1, p2, p3, p4); } -#undef clGetSupportedImageFormats -#define clGetSupportedImageFormats clGetSupportedImageFormats_fn -inline cl_int clGetSupportedImageFormats(cl_context p0, cl_mem_flags p1, cl_mem_object_type p2, cl_uint p3, cl_image_format* p4, cl_uint* p5) { return clGetSupportedImageFormats_pfn(p0, p1, p2, p3, p4, p5); } -#undef clLinkProgram -#define clLinkProgram clLinkProgram_fn -inline cl_program clLinkProgram(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, void (CL_CALLBACK*p6) (cl_program, void*), void* p7, cl_int* p8) { return clLinkProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } -#undef clReleaseCommandQueue -#define clReleaseCommandQueue clReleaseCommandQueue_fn -inline cl_int clReleaseCommandQueue(cl_command_queue p0) { return clReleaseCommandQueue_pfn(p0); } -#undef clReleaseContext -#define clReleaseContext clReleaseContext_fn -inline cl_int clReleaseContext(cl_context p0) { return clReleaseContext_pfn(p0); } -#undef clReleaseDevice -#define clReleaseDevice clReleaseDevice_fn -inline cl_int clReleaseDevice(cl_device_id p0) { return clReleaseDevice_pfn(p0); } -#undef clReleaseEvent -#define clReleaseEvent clReleaseEvent_fn -inline cl_int clReleaseEvent(cl_event p0) { return clReleaseEvent_pfn(p0); } -#undef clReleaseKernel -#define clReleaseKernel clReleaseKernel_fn -inline cl_int clReleaseKernel(cl_kernel p0) { return clReleaseKernel_pfn(p0); } -#undef clReleaseMemObject -#define clReleaseMemObject clReleaseMemObject_fn -inline cl_int clReleaseMemObject(cl_mem p0) { return clReleaseMemObject_pfn(p0); } -#undef clReleaseProgram -#define clReleaseProgram clReleaseProgram_fn -inline cl_int clReleaseProgram(cl_program p0) { return clReleaseProgram_pfn(p0); } -#undef clReleaseSampler -#define clReleaseSampler clReleaseSampler_fn -inline cl_int clReleaseSampler(cl_sampler p0) { return clReleaseSampler_pfn(p0); } -#undef clRetainCommandQueue -#define clRetainCommandQueue clRetainCommandQueue_fn -inline cl_int clRetainCommandQueue(cl_command_queue p0) { return clRetainCommandQueue_pfn(p0); } -#undef clRetainContext -#define clRetainContext clRetainContext_fn -inline cl_int clRetainContext(cl_context p0) { return clRetainContext_pfn(p0); } -#undef clRetainDevice -#define clRetainDevice clRetainDevice_fn -inline cl_int clRetainDevice(cl_device_id p0) { return clRetainDevice_pfn(p0); } -#undef clRetainEvent -#define clRetainEvent clRetainEvent_fn -inline cl_int clRetainEvent(cl_event p0) { return clRetainEvent_pfn(p0); } -#undef clRetainKernel -#define clRetainKernel clRetainKernel_fn -inline cl_int clRetainKernel(cl_kernel p0) { return clRetainKernel_pfn(p0); } -#undef clRetainMemObject -#define clRetainMemObject clRetainMemObject_fn -inline cl_int clRetainMemObject(cl_mem p0) { return clRetainMemObject_pfn(p0); } -#undef clRetainProgram -#define clRetainProgram clRetainProgram_fn -inline cl_int clRetainProgram(cl_program p0) { return clRetainProgram_pfn(p0); } -#undef clRetainSampler -#define clRetainSampler clRetainSampler_fn -inline cl_int clRetainSampler(cl_sampler p0) { return clRetainSampler_pfn(p0); } -#undef clSetEventCallback -#define clSetEventCallback clSetEventCallback_fn -inline cl_int clSetEventCallback(cl_event p0, cl_int p1, void (CL_CALLBACK*p2) (cl_event, cl_int, void*), void* p3) { return clSetEventCallback_pfn(p0, p1, p2, p3); } -#undef clSetKernelArg -#define clSetKernelArg clSetKernelArg_fn -inline cl_int clSetKernelArg(cl_kernel p0, cl_uint p1, size_t p2, const void* p3) { return clSetKernelArg_pfn(p0, p1, p2, p3); } -#undef clSetMemObjectDestructorCallback -#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_fn -inline cl_int clSetMemObjectDestructorCallback(cl_mem p0, void (CL_CALLBACK*p1) (cl_mem, void*), void* p2) { return clSetMemObjectDestructorCallback_pfn(p0, p1, p2); } -#undef clSetUserEventStatus -#define clSetUserEventStatus clSetUserEventStatus_fn -inline cl_int clSetUserEventStatus(cl_event p0, cl_int p1) { return clSetUserEventStatus_pfn(p0, p1); } -#undef clUnloadCompiler -#define clUnloadCompiler clUnloadCompiler_fn -inline cl_int clUnloadCompiler() { return clUnloadCompiler_pfn(); } -#undef clUnloadPlatformCompiler -#define clUnloadPlatformCompiler clUnloadPlatformCompiler_fn -inline cl_int clUnloadPlatformCompiler(cl_platform_id p0) { return clUnloadPlatformCompiler_pfn(p0); } -#undef clWaitForEvents -#define clWaitForEvents clWaitForEvents_fn -inline cl_int clWaitForEvents(cl_uint p0, const cl_event* p1) { return clWaitForEvents_pfn(p0, p1); } +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP +#error "Invalid usage" +#endif + +// generated by parser_cl.py +#undef clBuildProgram +#define clBuildProgram clBuildProgram_fn +inline cl_int clBuildProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, void (CL_CALLBACK*p4) (cl_program, void*), void* p5) { return clBuildProgram_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCompileProgram +#define clCompileProgram clCompileProgram_fn +inline cl_int clCompileProgram(cl_program p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, const char** p6, void (CL_CALLBACK*p7) (cl_program, void*), void* p8) { return clCompileProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clCreateBuffer +#define clCreateBuffer clCreateBuffer_fn +inline cl_mem clCreateBuffer(cl_context p0, cl_mem_flags p1, size_t p2, void* p3, cl_int* p4) { return clCreateBuffer_pfn(p0, p1, p2, p3, p4); } +#undef clCreateCommandQueue +#define clCreateCommandQueue clCreateCommandQueue_fn +inline cl_command_queue clCreateCommandQueue(cl_context p0, cl_device_id p1, cl_command_queue_properties p2, cl_int* p3) { return clCreateCommandQueue_pfn(p0, p1, p2, p3); } +#undef clCreateContext +#define clCreateContext clCreateContext_fn +inline cl_context clCreateContext(const cl_context_properties* p0, cl_uint p1, const cl_device_id* p2, void (CL_CALLBACK*p3) (const char*, const void*, size_t, void*), void* p4, cl_int* p5) { return clCreateContext_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateContextFromType +#define clCreateContextFromType clCreateContextFromType_fn +inline cl_context clCreateContextFromType(const cl_context_properties* p0, cl_device_type p1, void (CL_CALLBACK*p2) (const char*, const void*, size_t, void*), void* p3, cl_int* p4) { return clCreateContextFromType_pfn(p0, p1, p2, p3, p4); } +#undef clCreateImage +#define clCreateImage clCreateImage_fn +inline cl_mem clCreateImage(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, const cl_image_desc* p3, void* p4, cl_int* p5) { return clCreateImage_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateImage2D +#define clCreateImage2D clCreateImage2D_fn +inline cl_mem clCreateImage2D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, void* p6, cl_int* p7) { return clCreateImage2D_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } +#undef clCreateImage3D +#define clCreateImage3D clCreateImage3D_fn +inline cl_mem clCreateImage3D(cl_context p0, cl_mem_flags p1, const cl_image_format* p2, size_t p3, size_t p4, size_t p5, size_t p6, size_t p7, void* p8, cl_int* p9) { return clCreateImage3D_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } +#undef clCreateKernel +#define clCreateKernel clCreateKernel_fn +inline cl_kernel clCreateKernel(cl_program p0, const char* p1, cl_int* p2) { return clCreateKernel_pfn(p0, p1, p2); } +#undef clCreateKernelsInProgram +#define clCreateKernelsInProgram clCreateKernelsInProgram_fn +inline cl_int clCreateKernelsInProgram(cl_program p0, cl_uint p1, cl_kernel* p2, cl_uint* p3) { return clCreateKernelsInProgram_pfn(p0, p1, p2, p3); } +#undef clCreateProgramWithBinary +#define clCreateProgramWithBinary clCreateProgramWithBinary_fn +inline cl_program clCreateProgramWithBinary(cl_context p0, cl_uint p1, const cl_device_id* p2, const size_t* p3, const unsigned char** p4, cl_int* p5, cl_int* p6) { return clCreateProgramWithBinary_pfn(p0, p1, p2, p3, p4, p5, p6); } +#undef clCreateProgramWithBuiltInKernels +#define clCreateProgramWithBuiltInKernels clCreateProgramWithBuiltInKernels_fn +inline cl_program clCreateProgramWithBuiltInKernels(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_int* p4) { return clCreateProgramWithBuiltInKernels_pfn(p0, p1, p2, p3, p4); } +#undef clCreateProgramWithSource +#define clCreateProgramWithSource clCreateProgramWithSource_fn +inline cl_program clCreateProgramWithSource(cl_context p0, cl_uint p1, const char** p2, const size_t* p3, cl_int* p4) { return clCreateProgramWithSource_pfn(p0, p1, p2, p3, p4); } +#undef clCreateSampler +#define clCreateSampler clCreateSampler_fn +inline cl_sampler clCreateSampler(cl_context p0, cl_bool p1, cl_addressing_mode p2, cl_filter_mode p3, cl_int* p4) { return clCreateSampler_pfn(p0, p1, p2, p3, p4); } +#undef clCreateSubBuffer +#define clCreateSubBuffer clCreateSubBuffer_fn +inline cl_mem clCreateSubBuffer(cl_mem p0, cl_mem_flags p1, cl_buffer_create_type p2, const void* p3, cl_int* p4) { return clCreateSubBuffer_pfn(p0, p1, p2, p3, p4); } +#undef clCreateSubDevices +#define clCreateSubDevices clCreateSubDevices_fn +inline cl_int clCreateSubDevices(cl_device_id p0, const cl_device_partition_property* p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clCreateSubDevices_pfn(p0, p1, p2, p3, p4); } +#undef clCreateUserEvent +#define clCreateUserEvent clCreateUserEvent_fn +inline cl_event clCreateUserEvent(cl_context p0, cl_int* p1) { return clCreateUserEvent_pfn(p0, p1); } +#undef clEnqueueBarrier +#define clEnqueueBarrier clEnqueueBarrier_fn +inline cl_int clEnqueueBarrier(cl_command_queue p0) { return clEnqueueBarrier_pfn(p0); } +#undef clEnqueueBarrierWithWaitList +#define clEnqueueBarrierWithWaitList clEnqueueBarrierWithWaitList_fn +inline cl_int clEnqueueBarrierWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueBarrierWithWaitList_pfn(p0, p1, p2, p3); } +#undef clEnqueueCopyBuffer +#define clEnqueueCopyBuffer clEnqueueCopyBuffer_fn +inline cl_int clEnqueueCopyBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueCopyBufferRect +#define clEnqueueCopyBufferRect clEnqueueCopyBufferRect_fn +inline cl_int clEnqueueCopyBufferRect(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, cl_uint p10, const cl_event* p11, cl_event* p12) { return clEnqueueCopyBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); } +#undef clEnqueueCopyBufferToImage +#define clEnqueueCopyBufferToImage clEnqueueCopyBufferToImage_fn +inline cl_int clEnqueueCopyBufferToImage(cl_command_queue p0, cl_mem p1, cl_mem p2, size_t p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyBufferToImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueCopyImage +#define clEnqueueCopyImage clEnqueueCopyImage_fn +inline cl_int clEnqueueCopyImage(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueCopyImageToBuffer +#define clEnqueueCopyImageToBuffer clEnqueueCopyImageToBuffer_fn +inline cl_int clEnqueueCopyImageToBuffer(cl_command_queue p0, cl_mem p1, cl_mem p2, const size_t* p3, const size_t* p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueCopyImageToBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueFillBuffer +#define clEnqueueFillBuffer clEnqueueFillBuffer_fn +inline cl_int clEnqueueFillBuffer(cl_command_queue p0, cl_mem p1, const void* p2, size_t p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueFillBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueFillImage +#define clEnqueueFillImage clEnqueueFillImage_fn +inline cl_int clEnqueueFillImage(cl_command_queue p0, cl_mem p1, const void* p2, const size_t* p3, const size_t* p4, cl_uint p5, const cl_event* p6, cl_event* p7) { return clEnqueueFillImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7); } +#undef clEnqueueMapBuffer +#define clEnqueueMapBuffer clEnqueueMapBuffer_fn +inline void* clEnqueueMapBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, size_t p4, size_t p5, cl_uint p6, const cl_event* p7, cl_event* p8, cl_int* p9) { return clEnqueueMapBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } +#undef clEnqueueMapImage +#define clEnqueueMapImage clEnqueueMapImage_fn +inline void* clEnqueueMapImage(cl_command_queue p0, cl_mem p1, cl_bool p2, cl_map_flags p3, const size_t* p4, const size_t* p5, size_t* p6, size_t* p7, cl_uint p8, const cl_event* p9, cl_event* p10, cl_int* p11) { return clEnqueueMapImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); } +#undef clEnqueueMarker +#define clEnqueueMarker clEnqueueMarker_fn +inline cl_int clEnqueueMarker(cl_command_queue p0, cl_event* p1) { return clEnqueueMarker_pfn(p0, p1); } +#undef clEnqueueMarkerWithWaitList +#define clEnqueueMarkerWithWaitList clEnqueueMarkerWithWaitList_fn +inline cl_int clEnqueueMarkerWithWaitList(cl_command_queue p0, cl_uint p1, const cl_event* p2, cl_event* p3) { return clEnqueueMarkerWithWaitList_pfn(p0, p1, p2, p3); } +#undef clEnqueueMigrateMemObjects +#define clEnqueueMigrateMemObjects clEnqueueMigrateMemObjects_fn +inline cl_int clEnqueueMigrateMemObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_mem_migration_flags p3, cl_uint p4, const cl_event* p5, cl_event* p6) { return clEnqueueMigrateMemObjects_pfn(p0, p1, p2, p3, p4, p5, p6); } +#undef clEnqueueNDRangeKernel +#define clEnqueueNDRangeKernel clEnqueueNDRangeKernel_fn +inline cl_int clEnqueueNDRangeKernel(cl_command_queue p0, cl_kernel p1, cl_uint p2, const size_t* p3, const size_t* p4, const size_t* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueNDRangeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueNativeKernel +#define clEnqueueNativeKernel clEnqueueNativeKernel_fn +inline cl_int clEnqueueNativeKernel(cl_command_queue p0, void (CL_CALLBACK*p1) (void*), void* p2, size_t p3, cl_uint p4, const cl_mem* p5, const void** p6, cl_uint p7, const cl_event* p8, cl_event* p9) { return clEnqueueNativeKernel_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9); } +#undef clEnqueueReadBuffer +#define clEnqueueReadBuffer clEnqueueReadBuffer_fn +inline cl_int clEnqueueReadBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueReadBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueReadBufferRect +#define clEnqueueReadBufferRect clEnqueueReadBufferRect_fn +inline cl_int clEnqueueReadBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueReadBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } +#undef clEnqueueReadImage +#define clEnqueueReadImage clEnqueueReadImage_fn +inline cl_int clEnqueueReadImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueReadImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } +#undef clEnqueueTask +#define clEnqueueTask clEnqueueTask_fn +inline cl_int clEnqueueTask(cl_command_queue p0, cl_kernel p1, cl_uint p2, const cl_event* p3, cl_event* p4) { return clEnqueueTask_pfn(p0, p1, p2, p3, p4); } +#undef clEnqueueUnmapMemObject +#define clEnqueueUnmapMemObject clEnqueueUnmapMemObject_fn +inline cl_int clEnqueueUnmapMemObject(cl_command_queue p0, cl_mem p1, void* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueUnmapMemObject_pfn(p0, p1, p2, p3, p4, p5); } +#undef clEnqueueWaitForEvents +#define clEnqueueWaitForEvents clEnqueueWaitForEvents_fn +inline cl_int clEnqueueWaitForEvents(cl_command_queue p0, cl_uint p1, const cl_event* p2) { return clEnqueueWaitForEvents_pfn(p0, p1, p2); } +#undef clEnqueueWriteBuffer +#define clEnqueueWriteBuffer clEnqueueWriteBuffer_fn +inline cl_int clEnqueueWriteBuffer(cl_command_queue p0, cl_mem p1, cl_bool p2, size_t p3, size_t p4, const void* p5, cl_uint p6, const cl_event* p7, cl_event* p8) { return clEnqueueWriteBuffer_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clEnqueueWriteBufferRect +#define clEnqueueWriteBufferRect clEnqueueWriteBufferRect_fn +inline cl_int clEnqueueWriteBufferRect(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, const size_t* p5, size_t p6, size_t p7, size_t p8, size_t p9, const void* p10, cl_uint p11, const cl_event* p12, cl_event* p13) { return clEnqueueWriteBufferRect_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); } +#undef clEnqueueWriteImage +#define clEnqueueWriteImage clEnqueueWriteImage_fn +inline cl_int clEnqueueWriteImage(cl_command_queue p0, cl_mem p1, cl_bool p2, const size_t* p3, const size_t* p4, size_t p5, size_t p6, const void* p7, cl_uint p8, const cl_event* p9, cl_event* p10) { return clEnqueueWriteImage_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); } +#undef clFinish +#define clFinish clFinish_fn +inline cl_int clFinish(cl_command_queue p0) { return clFinish_pfn(p0); } +#undef clFlush +#define clFlush clFlush_fn +inline cl_int clFlush(cl_command_queue p0) { return clFlush_pfn(p0); } +#undef clGetCommandQueueInfo +#define clGetCommandQueueInfo clGetCommandQueueInfo_fn +inline cl_int clGetCommandQueueInfo(cl_command_queue p0, cl_command_queue_info p1, size_t p2, void* p3, size_t* p4) { return clGetCommandQueueInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetContextInfo +#define clGetContextInfo clGetContextInfo_fn +inline cl_int clGetContextInfo(cl_context p0, cl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetContextInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetDeviceIDs +#define clGetDeviceIDs clGetDeviceIDs_fn +inline cl_int clGetDeviceIDs(cl_platform_id p0, cl_device_type p1, cl_uint p2, cl_device_id* p3, cl_uint* p4) { return clGetDeviceIDs_pfn(p0, p1, p2, p3, p4); } +#undef clGetDeviceInfo +#define clGetDeviceInfo clGetDeviceInfo_fn +inline cl_int clGetDeviceInfo(cl_device_id p0, cl_device_info p1, size_t p2, void* p3, size_t* p4) { return clGetDeviceInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetEventInfo +#define clGetEventInfo clGetEventInfo_fn +inline cl_int clGetEventInfo(cl_event p0, cl_event_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetEventProfilingInfo +#define clGetEventProfilingInfo clGetEventProfilingInfo_fn +inline cl_int clGetEventProfilingInfo(cl_event p0, cl_profiling_info p1, size_t p2, void* p3, size_t* p4) { return clGetEventProfilingInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetExtensionFunctionAddress +#define clGetExtensionFunctionAddress clGetExtensionFunctionAddress_fn +inline void* clGetExtensionFunctionAddress(const char* p0) { return clGetExtensionFunctionAddress_pfn(p0); } +#undef clGetExtensionFunctionAddressForPlatform +#define clGetExtensionFunctionAddressForPlatform clGetExtensionFunctionAddressForPlatform_fn +inline void* clGetExtensionFunctionAddressForPlatform(cl_platform_id p0, const char* p1) { return clGetExtensionFunctionAddressForPlatform_pfn(p0, p1); } +#undef clGetImageInfo +#define clGetImageInfo clGetImageInfo_fn +inline cl_int clGetImageInfo(cl_mem p0, cl_image_info p1, size_t p2, void* p3, size_t* p4) { return clGetImageInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetKernelArgInfo +#define clGetKernelArgInfo clGetKernelArgInfo_fn +inline cl_int clGetKernelArgInfo(cl_kernel p0, cl_uint p1, cl_kernel_arg_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelArgInfo_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetKernelInfo +#define clGetKernelInfo clGetKernelInfo_fn +inline cl_int clGetKernelInfo(cl_kernel p0, cl_kernel_info p1, size_t p2, void* p3, size_t* p4) { return clGetKernelInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetKernelWorkGroupInfo +#define clGetKernelWorkGroupInfo clGetKernelWorkGroupInfo_fn +inline cl_int clGetKernelWorkGroupInfo(cl_kernel p0, cl_device_id p1, cl_kernel_work_group_info p2, size_t p3, void* p4, size_t* p5) { return clGetKernelWorkGroupInfo_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetMemObjectInfo +#define clGetMemObjectInfo clGetMemObjectInfo_fn +inline cl_int clGetMemObjectInfo(cl_mem p0, cl_mem_info p1, size_t p2, void* p3, size_t* p4) { return clGetMemObjectInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetPlatformIDs +#define clGetPlatformIDs clGetPlatformIDs_fn +inline cl_int clGetPlatformIDs(cl_uint p0, cl_platform_id* p1, cl_uint* p2) { return clGetPlatformIDs_pfn(p0, p1, p2); } +#undef clGetPlatformInfo +#define clGetPlatformInfo clGetPlatformInfo_fn +inline cl_int clGetPlatformInfo(cl_platform_id p0, cl_platform_info p1, size_t p2, void* p3, size_t* p4) { return clGetPlatformInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetProgramBuildInfo +#define clGetProgramBuildInfo clGetProgramBuildInfo_fn +inline cl_int clGetProgramBuildInfo(cl_program p0, cl_device_id p1, cl_program_build_info p2, size_t p3, void* p4, size_t* p5) { return clGetProgramBuildInfo_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetProgramInfo +#define clGetProgramInfo clGetProgramInfo_fn +inline cl_int clGetProgramInfo(cl_program p0, cl_program_info p1, size_t p2, void* p3, size_t* p4) { return clGetProgramInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetSamplerInfo +#define clGetSamplerInfo clGetSamplerInfo_fn +inline cl_int clGetSamplerInfo(cl_sampler p0, cl_sampler_info p1, size_t p2, void* p3, size_t* p4) { return clGetSamplerInfo_pfn(p0, p1, p2, p3, p4); } +#undef clGetSupportedImageFormats +#define clGetSupportedImageFormats clGetSupportedImageFormats_fn +inline cl_int clGetSupportedImageFormats(cl_context p0, cl_mem_flags p1, cl_mem_object_type p2, cl_uint p3, cl_image_format* p4, cl_uint* p5) { return clGetSupportedImageFormats_pfn(p0, p1, p2, p3, p4, p5); } +#undef clLinkProgram +#define clLinkProgram clLinkProgram_fn +inline cl_program clLinkProgram(cl_context p0, cl_uint p1, const cl_device_id* p2, const char* p3, cl_uint p4, const cl_program* p5, void (CL_CALLBACK*p6) (cl_program, void*), void* p7, cl_int* p8) { return clLinkProgram_pfn(p0, p1, p2, p3, p4, p5, p6, p7, p8); } +#undef clReleaseCommandQueue +#define clReleaseCommandQueue clReleaseCommandQueue_fn +inline cl_int clReleaseCommandQueue(cl_command_queue p0) { return clReleaseCommandQueue_pfn(p0); } +#undef clReleaseContext +#define clReleaseContext clReleaseContext_fn +inline cl_int clReleaseContext(cl_context p0) { return clReleaseContext_pfn(p0); } +#undef clReleaseDevice +#define clReleaseDevice clReleaseDevice_fn +inline cl_int clReleaseDevice(cl_device_id p0) { return clReleaseDevice_pfn(p0); } +#undef clReleaseEvent +#define clReleaseEvent clReleaseEvent_fn +inline cl_int clReleaseEvent(cl_event p0) { return clReleaseEvent_pfn(p0); } +#undef clReleaseKernel +#define clReleaseKernel clReleaseKernel_fn +inline cl_int clReleaseKernel(cl_kernel p0) { return clReleaseKernel_pfn(p0); } +#undef clReleaseMemObject +#define clReleaseMemObject clReleaseMemObject_fn +inline cl_int clReleaseMemObject(cl_mem p0) { return clReleaseMemObject_pfn(p0); } +#undef clReleaseProgram +#define clReleaseProgram clReleaseProgram_fn +inline cl_int clReleaseProgram(cl_program p0) { return clReleaseProgram_pfn(p0); } +#undef clReleaseSampler +#define clReleaseSampler clReleaseSampler_fn +inline cl_int clReleaseSampler(cl_sampler p0) { return clReleaseSampler_pfn(p0); } +#undef clRetainCommandQueue +#define clRetainCommandQueue clRetainCommandQueue_fn +inline cl_int clRetainCommandQueue(cl_command_queue p0) { return clRetainCommandQueue_pfn(p0); } +#undef clRetainContext +#define clRetainContext clRetainContext_fn +inline cl_int clRetainContext(cl_context p0) { return clRetainContext_pfn(p0); } +#undef clRetainDevice +#define clRetainDevice clRetainDevice_fn +inline cl_int clRetainDevice(cl_device_id p0) { return clRetainDevice_pfn(p0); } +#undef clRetainEvent +#define clRetainEvent clRetainEvent_fn +inline cl_int clRetainEvent(cl_event p0) { return clRetainEvent_pfn(p0); } +#undef clRetainKernel +#define clRetainKernel clRetainKernel_fn +inline cl_int clRetainKernel(cl_kernel p0) { return clRetainKernel_pfn(p0); } +#undef clRetainMemObject +#define clRetainMemObject clRetainMemObject_fn +inline cl_int clRetainMemObject(cl_mem p0) { return clRetainMemObject_pfn(p0); } +#undef clRetainProgram +#define clRetainProgram clRetainProgram_fn +inline cl_int clRetainProgram(cl_program p0) { return clRetainProgram_pfn(p0); } +#undef clRetainSampler +#define clRetainSampler clRetainSampler_fn +inline cl_int clRetainSampler(cl_sampler p0) { return clRetainSampler_pfn(p0); } +#undef clSetEventCallback +#define clSetEventCallback clSetEventCallback_fn +inline cl_int clSetEventCallback(cl_event p0, cl_int p1, void (CL_CALLBACK*p2) (cl_event, cl_int, void*), void* p3) { return clSetEventCallback_pfn(p0, p1, p2, p3); } +#undef clSetKernelArg +#define clSetKernelArg clSetKernelArg_fn +inline cl_int clSetKernelArg(cl_kernel p0, cl_uint p1, size_t p2, const void* p3) { return clSetKernelArg_pfn(p0, p1, p2, p3); } +#undef clSetMemObjectDestructorCallback +#define clSetMemObjectDestructorCallback clSetMemObjectDestructorCallback_fn +inline cl_int clSetMemObjectDestructorCallback(cl_mem p0, void (CL_CALLBACK*p1) (cl_mem, void*), void* p2) { return clSetMemObjectDestructorCallback_pfn(p0, p1, p2); } +#undef clSetUserEventStatus +#define clSetUserEventStatus clSetUserEventStatus_fn +inline cl_int clSetUserEventStatus(cl_event p0, cl_int p1) { return clSetUserEventStatus_pfn(p0, p1); } +#undef clUnloadCompiler +#define clUnloadCompiler clUnloadCompiler_fn +inline cl_int clUnloadCompiler() { return clUnloadCompiler_pfn(); } +#undef clUnloadPlatformCompiler +#define clUnloadPlatformCompiler clUnloadPlatformCompiler_fn +inline cl_int clUnloadPlatformCompiler(cl_platform_id p0) { return clUnloadPlatformCompiler_pfn(p0); } +#undef clWaitForEvents +#define clWaitForEvents clWaitForEvents_fn +inline cl_int clWaitForEvents(cl_uint p0, const cl_event* p1) { return clWaitForEvents_pfn(p0, p1); } diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp index 8b0d4c8d6e..0b12aed6c6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl.hpp @@ -1,62 +1,62 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP -#error "Invalid usage" -#endif - -// generated by parser_cl.py -#define clCreateFromGLBuffer clCreateFromGLBuffer_ -#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_ -#define clCreateFromGLTexture clCreateFromGLTexture_ -#define clCreateFromGLTexture2D clCreateFromGLTexture2D_ -#define clCreateFromGLTexture3D clCreateFromGLTexture3D_ -#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_ -#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_ -#define clGetGLContextInfoKHR clGetGLContextInfoKHR_ -#define clGetGLObjectInfo clGetGLObjectInfo_ -#define clGetGLTextureInfo clGetGLTextureInfo_ - -#if defined __APPLE__ -#include -#else -#include -#endif - -// generated by parser_cl.py -#undef clCreateFromGLBuffer -#define clCreateFromGLBuffer clCreateFromGLBuffer_pfn -#undef clCreateFromGLRenderbuffer -#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_pfn -#undef clCreateFromGLTexture -#define clCreateFromGLTexture clCreateFromGLTexture_pfn -#undef clCreateFromGLTexture2D -#define clCreateFromGLTexture2D clCreateFromGLTexture2D_pfn -#undef clCreateFromGLTexture3D -#define clCreateFromGLTexture3D clCreateFromGLTexture3D_pfn -#undef clEnqueueAcquireGLObjects -#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_pfn -#undef clEnqueueReleaseGLObjects -#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_pfn -#undef clGetGLContextInfoKHR -#define clGetGLContextInfoKHR clGetGLContextInfoKHR_pfn -#undef clGetGLObjectInfo -#define clGetGLObjectInfo clGetGLObjectInfo_pfn -#undef clGetGLTextureInfo -#define clGetGLTextureInfo clGetGLTextureInfo_pfn - -#ifdef cl_khr_gl_sharing - -// generated by parser_cl.py -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLBuffer)(cl_context, cl_mem_flags, cl_GLuint, int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLRenderbuffer)(cl_context, cl_mem_flags, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture2D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture3D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueAcquireGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReleaseGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLContextInfoKHR)(const cl_context_properties*, cl_gl_context_info, size_t, void*, size_t*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLObjectInfo)(cl_mem, cl_gl_object_type*, cl_GLuint*); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLTextureInfo)(cl_mem, cl_gl_texture_info, size_t, void*, size_t*); - -#endif // cl_khr_gl_sharing +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP +#error "Invalid usage" +#endif + +// generated by parser_cl.py +#define clCreateFromGLBuffer clCreateFromGLBuffer_ +#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_ +#define clCreateFromGLTexture clCreateFromGLTexture_ +#define clCreateFromGLTexture2D clCreateFromGLTexture2D_ +#define clCreateFromGLTexture3D clCreateFromGLTexture3D_ +#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_ +#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_ +#define clGetGLContextInfoKHR clGetGLContextInfoKHR_ +#define clGetGLObjectInfo clGetGLObjectInfo_ +#define clGetGLTextureInfo clGetGLTextureInfo_ + +#if defined __APPLE__ +#include +#else +#include +#endif + +// generated by parser_cl.py +#undef clCreateFromGLBuffer +#define clCreateFromGLBuffer clCreateFromGLBuffer_pfn +#undef clCreateFromGLRenderbuffer +#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_pfn +#undef clCreateFromGLTexture +#define clCreateFromGLTexture clCreateFromGLTexture_pfn +#undef clCreateFromGLTexture2D +#define clCreateFromGLTexture2D clCreateFromGLTexture2D_pfn +#undef clCreateFromGLTexture3D +#define clCreateFromGLTexture3D clCreateFromGLTexture3D_pfn +#undef clEnqueueAcquireGLObjects +#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_pfn +#undef clEnqueueReleaseGLObjects +#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_pfn +#undef clGetGLContextInfoKHR +#define clGetGLContextInfoKHR clGetGLContextInfoKHR_pfn +#undef clGetGLObjectInfo +#define clGetGLObjectInfo clGetGLObjectInfo_pfn +#undef clGetGLTextureInfo +#define clGetGLTextureInfo clGetGLTextureInfo_pfn + +#ifdef cl_khr_gl_sharing + +// generated by parser_cl.py +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLBuffer)(cl_context, cl_mem_flags, cl_GLuint, int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLRenderbuffer)(cl_context, cl_mem_flags, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture2D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_mem (CL_API_CALL*clCreateFromGLTexture3D)(cl_context, cl_mem_flags, cl_GLenum, cl_GLint, cl_GLuint, cl_int*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueAcquireGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clEnqueueReleaseGLObjects)(cl_command_queue, cl_uint, const cl_mem*, cl_uint, const cl_event*, cl_event*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLContextInfoKHR)(const cl_context_properties*, cl_gl_context_info, size_t, void*, size_t*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLObjectInfo)(cl_mem, cl_gl_object_type*, cl_GLuint*); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL*clGetGLTextureInfo)(cl_mem, cl_gl_texture_info, size_t, void*, size_t*); + +#endif // cl_khr_gl_sharing diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp index 308673789d..12f342b2e4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/autogenerated/opencl_gl_wrappers.hpp @@ -1,42 +1,42 @@ -// -// AUTOGENERATED, DO NOT EDIT -// -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP -#error "Invalid usage" -#endif - -#ifdef cl_khr_gl_sharing - -// generated by parser_cl.py -#undef clCreateFromGLBuffer -#define clCreateFromGLBuffer clCreateFromGLBuffer_fn -inline cl_mem clCreateFromGLBuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, int* p3) { return clCreateFromGLBuffer_pfn(p0, p1, p2, p3); } -#undef clCreateFromGLRenderbuffer -#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_fn -inline cl_mem clCreateFromGLRenderbuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, cl_int* p3) { return clCreateFromGLRenderbuffer_pfn(p0, p1, p2, p3); } -#undef clCreateFromGLTexture -#define clCreateFromGLTexture clCreateFromGLTexture_fn -inline cl_mem clCreateFromGLTexture(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateFromGLTexture2D -#define clCreateFromGLTexture2D clCreateFromGLTexture2D_fn -inline cl_mem clCreateFromGLTexture2D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture2D_pfn(p0, p1, p2, p3, p4, p5); } -#undef clCreateFromGLTexture3D -#define clCreateFromGLTexture3D clCreateFromGLTexture3D_fn -inline cl_mem clCreateFromGLTexture3D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture3D_pfn(p0, p1, p2, p3, p4, p5); } -#undef clEnqueueAcquireGLObjects -#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_fn -inline cl_int clEnqueueAcquireGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueAcquireGLObjects_pfn(p0, p1, p2, p3, p4, p5); } -#undef clEnqueueReleaseGLObjects -#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_fn -inline cl_int clEnqueueReleaseGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueReleaseGLObjects_pfn(p0, p1, p2, p3, p4, p5); } -#undef clGetGLContextInfoKHR -#define clGetGLContextInfoKHR clGetGLContextInfoKHR_fn -inline cl_int clGetGLContextInfoKHR(const cl_context_properties* p0, cl_gl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLContextInfoKHR_pfn(p0, p1, p2, p3, p4); } -#undef clGetGLObjectInfo -#define clGetGLObjectInfo clGetGLObjectInfo_fn -inline cl_int clGetGLObjectInfo(cl_mem p0, cl_gl_object_type* p1, cl_GLuint* p2) { return clGetGLObjectInfo_pfn(p0, p1, p2); } -#undef clGetGLTextureInfo -#define clGetGLTextureInfo clGetGLTextureInfo_fn -inline cl_int clGetGLTextureInfo(cl_mem p0, cl_gl_texture_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLTextureInfo_pfn(p0, p1, p2, p3, p4); } - -#endif // cl_khr_gl_sharing +// +// AUTOGENERATED, DO NOT EDIT +// +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP +#error "Invalid usage" +#endif + +#ifdef cl_khr_gl_sharing + +// generated by parser_cl.py +#undef clCreateFromGLBuffer +#define clCreateFromGLBuffer clCreateFromGLBuffer_fn +inline cl_mem clCreateFromGLBuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, int* p3) { return clCreateFromGLBuffer_pfn(p0, p1, p2, p3); } +#undef clCreateFromGLRenderbuffer +#define clCreateFromGLRenderbuffer clCreateFromGLRenderbuffer_fn +inline cl_mem clCreateFromGLRenderbuffer(cl_context p0, cl_mem_flags p1, cl_GLuint p2, cl_int* p3) { return clCreateFromGLRenderbuffer_pfn(p0, p1, p2, p3); } +#undef clCreateFromGLTexture +#define clCreateFromGLTexture clCreateFromGLTexture_fn +inline cl_mem clCreateFromGLTexture(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateFromGLTexture2D +#define clCreateFromGLTexture2D clCreateFromGLTexture2D_fn +inline cl_mem clCreateFromGLTexture2D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture2D_pfn(p0, p1, p2, p3, p4, p5); } +#undef clCreateFromGLTexture3D +#define clCreateFromGLTexture3D clCreateFromGLTexture3D_fn +inline cl_mem clCreateFromGLTexture3D(cl_context p0, cl_mem_flags p1, cl_GLenum p2, cl_GLint p3, cl_GLuint p4, cl_int* p5) { return clCreateFromGLTexture3D_pfn(p0, p1, p2, p3, p4, p5); } +#undef clEnqueueAcquireGLObjects +#define clEnqueueAcquireGLObjects clEnqueueAcquireGLObjects_fn +inline cl_int clEnqueueAcquireGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueAcquireGLObjects_pfn(p0, p1, p2, p3, p4, p5); } +#undef clEnqueueReleaseGLObjects +#define clEnqueueReleaseGLObjects clEnqueueReleaseGLObjects_fn +inline cl_int clEnqueueReleaseGLObjects(cl_command_queue p0, cl_uint p1, const cl_mem* p2, cl_uint p3, const cl_event* p4, cl_event* p5) { return clEnqueueReleaseGLObjects_pfn(p0, p1, p2, p3, p4, p5); } +#undef clGetGLContextInfoKHR +#define clGetGLContextInfoKHR clGetGLContextInfoKHR_fn +inline cl_int clGetGLContextInfoKHR(const cl_context_properties* p0, cl_gl_context_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLContextInfoKHR_pfn(p0, p1, p2, p3, p4); } +#undef clGetGLObjectInfo +#define clGetGLObjectInfo clGetGLObjectInfo_fn +inline cl_int clGetGLObjectInfo(cl_mem p0, cl_gl_object_type* p1, cl_GLuint* p2) { return clGetGLObjectInfo_pfn(p0, p1, p2); } +#undef clGetGLTextureInfo +#define clGetGLTextureInfo clGetGLTextureInfo_fn +inline cl_int clGetGLTextureInfo(cl_mem p0, cl_gl_texture_info p1, size_t p2, void* p3, size_t* p4) { return clGetGLTextureInfo_pfn(p0, p1, p2, p3, p4); } + +#endif // cl_khr_gl_sharing diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp index 822f6cd2b3..ccddf8f76c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clblas.hpp @@ -1,53 +1,53 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP -#define OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP - -#ifdef HAVE_CLAMDBLAS - -#include "opencl_core.hpp" - -#include "autogenerated/opencl_clblas.hpp" - -#endif // HAVE_CLAMDBLAS - -#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP +#define OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP + +#ifdef HAVE_CLAMDBLAS + +#include "opencl_core.hpp" + +#include "autogenerated/opencl_clblas.hpp" + +#endif // HAVE_CLAMDBLAS + +#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDBLAS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp index 7dd51f3889..7f4af5e60b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_clfft.hpp @@ -1,53 +1,53 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP -#define OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP - -#ifdef HAVE_CLAMDFFT - -#include "opencl_core.hpp" - -#include "autogenerated/opencl_clfft.hpp" - -#endif // HAVE_CLAMDFFT - -#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP +#define OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP + +#ifdef HAVE_CLAMDFFT + +#include "opencl_core.hpp" + +#include "autogenerated/opencl_clfft.hpp" + +#endif // HAVE_CLAMDFFT + +#endif // OPENCV_CORE_OCL_RUNTIME_CLAMDFFT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp index 5802dd81d1..0404b3177a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core.hpp @@ -1,84 +1,84 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP - -#ifdef HAVE_OPENCL - -#ifndef CL_RUNTIME_EXPORT -#if (defined(BUILD_SHARED_LIBS) || defined(OPENCV_CORE_SHARED)) && (defined _WIN32 || defined WINCE) && \ - !(defined(__OPENCV_BUILD) && defined(OPENCV_MODULE_IS_PART_OF_WORLD)) -#define CL_RUNTIME_EXPORT __declspec(dllimport) -#else -#define CL_RUNTIME_EXPORT -#endif -#endif - -#ifdef HAVE_OPENCL_SVM -#define clSVMAlloc clSVMAlloc_ -#define clSVMFree clSVMFree_ -#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_ -#define clSetKernelExecInfo clSetKernelExecInfo_ -#define clEnqueueSVMFree clEnqueueSVMFree_ -#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_ -#define clEnqueueSVMMemFill clEnqueueSVMMemFill_ -#define clEnqueueSVMMap clEnqueueSVMMap_ -#define clEnqueueSVMUnmap clEnqueueSVMUnmap_ -#endif - -#include "autogenerated/opencl_core.hpp" - -#ifndef CL_DEVICE_DOUBLE_FP_CONFIG -#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 -#endif - -#ifndef CL_DEVICE_HALF_FP_CONFIG -#define CL_DEVICE_HALF_FP_CONFIG 0x1033 -#endif - -#ifndef CL_VERSION_1_2 -#define CV_REQUIRE_OPENCL_1_2_ERROR CV_Error(cv::Error::OpenCLApiCallError, "OpenCV compiled without OpenCL v1.2 support, so we can't use functionality from OpenCL v1.2") -#endif - -#endif // HAVE_OPENCL - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP + +#ifdef HAVE_OPENCL + +#ifndef CL_RUNTIME_EXPORT +#if (defined(BUILD_SHARED_LIBS) || defined(OPENCV_CORE_SHARED)) && (defined _WIN32 || defined WINCE) && \ + !(defined(__OPENCV_BUILD) && defined(OPENCV_MODULE_IS_PART_OF_WORLD)) +#define CL_RUNTIME_EXPORT __declspec(dllimport) +#else +#define CL_RUNTIME_EXPORT +#endif +#endif + +#ifdef HAVE_OPENCL_SVM +#define clSVMAlloc clSVMAlloc_ +#define clSVMFree clSVMFree_ +#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_ +#define clSetKernelExecInfo clSetKernelExecInfo_ +#define clEnqueueSVMFree clEnqueueSVMFree_ +#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_ +#define clEnqueueSVMMemFill clEnqueueSVMMemFill_ +#define clEnqueueSVMMap clEnqueueSVMMap_ +#define clEnqueueSVMUnmap clEnqueueSVMUnmap_ +#endif + +#include "autogenerated/opencl_core.hpp" + +#ifndef CL_DEVICE_DOUBLE_FP_CONFIG +#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 +#endif + +#ifndef CL_DEVICE_HALF_FP_CONFIG +#define CL_DEVICE_HALF_FP_CONFIG 0x1033 +#endif + +#ifndef CL_VERSION_1_2 +#define CV_REQUIRE_OPENCL_1_2_ERROR CV_Error(cv::Error::OpenCLApiCallError, "OpenCV compiled without OpenCL v1.2 support, so we can't use functionality from OpenCL v1.2") +#endif + +#endif // HAVE_OPENCL + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp index d1d5e15e09..38fcae9952 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_core_wrappers.hpp @@ -1,47 +1,47 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP - -#include "autogenerated/opencl_core_wrappers.hpp" - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP + +#include "autogenerated/opencl_core_wrappers.hpp" + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_WRAPPERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp index 8de4590fb8..659c7d8058 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl.hpp @@ -1,53 +1,53 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP - -#if defined HAVE_OPENCL && defined HAVE_OPENGL - -#include "opencl_core.hpp" - -#include "autogenerated/opencl_gl.hpp" - -#endif // defined HAVE_OPENCL && defined HAVE_OPENGL - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP + +#if defined HAVE_OPENCL && defined HAVE_OPENGL + +#include "opencl_core.hpp" + +#include "autogenerated/opencl_gl.hpp" + +#endif // defined HAVE_OPENCL && defined HAVE_OPENGL + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp index 861df4e8f7..9700004cae 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_gl_wrappers.hpp @@ -1,47 +1,47 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP - -#include "autogenerated/opencl_gl_wrappers.hpp" - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2010-2013, Advanced Micro Devices, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP + +#include "autogenerated/opencl_gl_wrappers.hpp" + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_GL_WRAPPERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp index 97e3741901..9636b19b02 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_20.hpp @@ -1,48 +1,48 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP - -#if defined(HAVE_OPENCL_SVM) -#include "opencl_core.hpp" - -#include "opencl_svm_definitions.hpp" - -#undef clSVMAlloc -#define clSVMAlloc clSVMAlloc_pfn -#undef clSVMFree -#define clSVMFree clSVMFree_pfn -#undef clSetKernelArgSVMPointer -#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_pfn -#undef clSetKernelExecInfo -//#define clSetKernelExecInfo clSetKernelExecInfo_pfn -#undef clEnqueueSVMFree -//#define clEnqueueSVMFree clEnqueueSVMFree_pfn -#undef clEnqueueSVMMemcpy -#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_pfn -#undef clEnqueueSVMMemFill -#define clEnqueueSVMMemFill clEnqueueSVMMemFill_pfn -#undef clEnqueueSVMMap -#define clEnqueueSVMMap clEnqueueSVMMap_pfn -#undef clEnqueueSVMUnmap -#define clEnqueueSVMUnmap clEnqueueSVMUnmap_pfn - -extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSVMAlloc)(cl_context context, cl_svm_mem_flags flags, size_t size, unsigned int alignment); -extern CL_RUNTIME_EXPORT void (CL_API_CALL *clSVMFree)(cl_context context, void* svm_pointer); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clSetKernelArgSVMPointer)(cl_kernel kernel, cl_uint arg_index, const void* arg_value); -//extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSetKernelExecInfo)(cl_kernel kernel, cl_kernel_exec_info param_name, size_t param_value_size, const void* param_value); -//extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMFree)(cl_command_queue command_queue, cl_uint num_svm_pointers, void* svm_pointers[], -// void (CL_CALLBACK *pfn_free_func)(cl_command_queue queue, cl_uint num_svm_pointers, void* svm_pointers[], void* user_data), void* user_data, -// cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemcpy)(cl_command_queue command_queue, cl_bool blocking_copy, void* dst_ptr, const void* src_ptr, size_t size, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemFill)(cl_command_queue command_queue, void* svm_ptr, const void* pattern, size_t pattern_size, size_t size, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMap)(cl_command_queue command_queue, cl_bool blocking_map, cl_map_flags map_flags, void* svm_ptr, size_t size, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); -extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMUnmap)(cl_command_queue command_queue, void* svm_ptr, - cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); - -#endif // HAVE_OPENCL_SVM - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP + +#if defined(HAVE_OPENCL_SVM) +#include "opencl_core.hpp" + +#include "opencl_svm_definitions.hpp" + +#undef clSVMAlloc +#define clSVMAlloc clSVMAlloc_pfn +#undef clSVMFree +#define clSVMFree clSVMFree_pfn +#undef clSetKernelArgSVMPointer +#define clSetKernelArgSVMPointer clSetKernelArgSVMPointer_pfn +#undef clSetKernelExecInfo +//#define clSetKernelExecInfo clSetKernelExecInfo_pfn +#undef clEnqueueSVMFree +//#define clEnqueueSVMFree clEnqueueSVMFree_pfn +#undef clEnqueueSVMMemcpy +#define clEnqueueSVMMemcpy clEnqueueSVMMemcpy_pfn +#undef clEnqueueSVMMemFill +#define clEnqueueSVMMemFill clEnqueueSVMMemFill_pfn +#undef clEnqueueSVMMap +#define clEnqueueSVMMap clEnqueueSVMMap_pfn +#undef clEnqueueSVMUnmap +#define clEnqueueSVMUnmap clEnqueueSVMUnmap_pfn + +extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSVMAlloc)(cl_context context, cl_svm_mem_flags flags, size_t size, unsigned int alignment); +extern CL_RUNTIME_EXPORT void (CL_API_CALL *clSVMFree)(cl_context context, void* svm_pointer); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clSetKernelArgSVMPointer)(cl_kernel kernel, cl_uint arg_index, const void* arg_value); +//extern CL_RUNTIME_EXPORT void* (CL_API_CALL *clSetKernelExecInfo)(cl_kernel kernel, cl_kernel_exec_info param_name, size_t param_value_size, const void* param_value); +//extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMFree)(cl_command_queue command_queue, cl_uint num_svm_pointers, void* svm_pointers[], +// void (CL_CALLBACK *pfn_free_func)(cl_command_queue queue, cl_uint num_svm_pointers, void* svm_pointers[], void* user_data), void* user_data, +// cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemcpy)(cl_command_queue command_queue, cl_bool blocking_copy, void* dst_ptr, const void* src_ptr, size_t size, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMemFill)(cl_command_queue command_queue, void* svm_ptr, const void* pattern, size_t pattern_size, size_t size, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMMap)(cl_command_queue command_queue, cl_bool blocking_map, cl_map_flags map_flags, void* svm_ptr, size_t size, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); +extern CL_RUNTIME_EXPORT cl_int (CL_API_CALL *clEnqueueSVMUnmap)(cl_command_queue command_queue, void* svm_ptr, + cl_uint num_events_in_wait_list, const cl_event* event_wait_list, cl_event* event); + +#endif // HAVE_OPENCL_SVM + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_2_0_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp index c6dcc776fb..97c927b44d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_definitions.hpp @@ -1,42 +1,42 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP - -#if defined(HAVE_OPENCL_SVM) -#if defined(CL_VERSION_2_0) - -// OpenCL 2.0 contains SVM definitions - -#else - -typedef cl_bitfield cl_device_svm_capabilities; -typedef cl_bitfield cl_svm_mem_flags; -typedef cl_uint cl_kernel_exec_info; - -// -// TODO Add real values after OpenCL 2.0 release -// - -#ifndef CL_DEVICE_SVM_CAPABILITIES -#define CL_DEVICE_SVM_CAPABILITIES 0x1053 - -#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) -#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) -#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) -#define CL_DEVICE_SVM_ATOMICS (1 << 3) -#endif - -#ifndef CL_MEM_SVM_FINE_GRAIN_BUFFER -#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) -#endif - -#ifndef CL_MEM_SVM_ATOMICS -#define CL_MEM_SVM_ATOMICS (1 << 11) -#endif - - -#endif // CL_VERSION_2_0 -#endif // HAVE_OPENCL_SVM - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP + +#if defined(HAVE_OPENCL_SVM) +#if defined(CL_VERSION_2_0) + +// OpenCL 2.0 contains SVM definitions + +#else + +typedef cl_bitfield cl_device_svm_capabilities; +typedef cl_bitfield cl_svm_mem_flags; +typedef cl_uint cl_kernel_exec_info; + +// +// TODO Add real values after OpenCL 2.0 release +// + +#ifndef CL_DEVICE_SVM_CAPABILITIES +#define CL_DEVICE_SVM_CAPABILITIES 0x1053 + +#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0) +#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1) +#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2) +#define CL_DEVICE_SVM_ATOMICS (1 << 3) +#endif + +#ifndef CL_MEM_SVM_FINE_GRAIN_BUFFER +#define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) +#endif + +#ifndef CL_MEM_SVM_ATOMICS +#define CL_MEM_SVM_ATOMICS (1 << 11) +#endif + + +#endif // CL_VERSION_2_0 +#endif // HAVE_OPENCL_SVM + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_DEFINITIONS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp index 9aa46a8f2f..497bc3de72 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp @@ -1,166 +1,166 @@ -/* See LICENSE file in the root OpenCV directory */ - -#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP -#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP - -#if defined(HAVE_OPENCL_SVM) -#include "opencl_core.hpp" - -#ifndef CL_DEVICE_SVM_CAPABILITIES_AMD -// -// Part of the file is an extract from the cl_ext.h file from AMD APP SDK package. -// Below is the original copyright. -// -/******************************************************************************* - * 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. - ******************************************************************************/ - -/******************************************* - * Shared Virtual Memory (SVM) extension - *******************************************/ -typedef cl_bitfield cl_device_svm_capabilities_amd; -typedef cl_bitfield cl_svm_mem_flags_amd; -typedef cl_uint cl_kernel_exec_info_amd; - -/* cl_device_info */ -#define CL_DEVICE_SVM_CAPABILITIES_AMD 0x1053 -#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT_AMD 0x1054 - -/* cl_device_svm_capabilities_amd */ -#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_AMD (1 << 0) -#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER_AMD (1 << 1) -#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM_AMD (1 << 2) -#define CL_DEVICE_SVM_ATOMICS_AMD (1 << 3) - -/* cl_svm_mem_flags_amd */ -#define CL_MEM_SVM_FINE_GRAIN_BUFFER_AMD (1 << 10) -#define CL_MEM_SVM_ATOMICS_AMD (1 << 11) - -/* cl_mem_info */ -#define CL_MEM_USES_SVM_POINTER_AMD 0x1109 - -/* cl_kernel_exec_info_amd */ -#define CL_KERNEL_EXEC_INFO_SVM_PTRS_AMD 0x11B6 -#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM_AMD 0x11B7 - -/* cl_command_type */ -#define CL_COMMAND_SVM_FREE_AMD 0x1209 -#define CL_COMMAND_SVM_MEMCPY_AMD 0x120A -#define CL_COMMAND_SVM_MEMFILL_AMD 0x120B -#define CL_COMMAND_SVM_MAP_AMD 0x120C -#define CL_COMMAND_SVM_UNMAP_AMD 0x120D - -typedef CL_API_ENTRY void* -(CL_API_CALL * clSVMAllocAMD_fn)( - cl_context /* context */, - cl_svm_mem_flags_amd /* flags */, - size_t /* size */, - unsigned int /* alignment */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY void -(CL_API_CALL * clSVMFreeAMD_fn)( - cl_context /* context */, - void* /* svm_pointer */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMFreeAMD_fn)( - cl_command_queue /* command_queue */, - cl_uint /* num_svm_pointers */, - void** /* svm_pointers */, - void (CL_CALLBACK *)( /*pfn_free_func*/ - cl_command_queue /* queue */, - cl_uint /* num_svm_pointers */, - void** /* svm_pointers */, - void* /* user_data */), - void* /* user_data */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMMemcpyAMD_fn)( - cl_command_queue /* command_queue */, - cl_bool /* blocking_copy */, - void* /* dst_ptr */, - const void* /* src_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMMemFillAMD_fn)( - cl_command_queue /* command_queue */, - void* /* svm_ptr */, - const void* /* pattern */, - size_t /* pattern_size */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMMapAMD_fn)( - cl_command_queue /* command_queue */, - cl_bool /* blocking_map */, - cl_map_flags /* map_flags */, - void* /* svm_ptr */, - size_t /* size */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clEnqueueSVMUnmapAMD_fn)( - cl_command_queue /* command_queue */, - void* /* svm_ptr */, - cl_uint /* num_events_in_wait_list */, - const cl_event* /* event_wait_list */, - cl_event* /* event */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clSetKernelArgSVMPointerAMD_fn)( - cl_kernel /* kernel */, - cl_uint /* arg_index */, - const void * /* arg_value */ -) CL_EXT_SUFFIX__VERSION_1_2; - -typedef CL_API_ENTRY cl_int -(CL_API_CALL * clSetKernelExecInfoAMD_fn)( - cl_kernel /* kernel */, - cl_kernel_exec_info_amd /* param_name */, - size_t /* param_value_size */, - const void * /* param_value */ -) CL_EXT_SUFFIX__VERSION_1_2; - -#endif - -#endif // HAVE_OPENCL_SVM - -#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP +/* See LICENSE file in the root OpenCV directory */ + +#ifndef OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP +#define OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP + +#if defined(HAVE_OPENCL_SVM) +#include "opencl_core.hpp" + +#ifndef CL_DEVICE_SVM_CAPABILITIES_AMD +// +// Part of the file is an extract from the cl_ext.h file from AMD APP SDK package. +// Below is the original copyright. +// +/******************************************************************************* + * 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. + ******************************************************************************/ + +/******************************************* + * Shared Virtual Memory (SVM) extension + *******************************************/ +typedef cl_bitfield cl_device_svm_capabilities_amd; +typedef cl_bitfield cl_svm_mem_flags_amd; +typedef cl_uint cl_kernel_exec_info_amd; + +/* cl_device_info */ +#define CL_DEVICE_SVM_CAPABILITIES_AMD 0x1053 +#define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT_AMD 0x1054 + +/* cl_device_svm_capabilities_amd */ +#define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_AMD (1 << 0) +#define CL_DEVICE_SVM_FINE_GRAIN_BUFFER_AMD (1 << 1) +#define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM_AMD (1 << 2) +#define CL_DEVICE_SVM_ATOMICS_AMD (1 << 3) + +/* cl_svm_mem_flags_amd */ +#define CL_MEM_SVM_FINE_GRAIN_BUFFER_AMD (1 << 10) +#define CL_MEM_SVM_ATOMICS_AMD (1 << 11) + +/* cl_mem_info */ +#define CL_MEM_USES_SVM_POINTER_AMD 0x1109 + +/* cl_kernel_exec_info_amd */ +#define CL_KERNEL_EXEC_INFO_SVM_PTRS_AMD 0x11B6 +#define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM_AMD 0x11B7 + +/* cl_command_type */ +#define CL_COMMAND_SVM_FREE_AMD 0x1209 +#define CL_COMMAND_SVM_MEMCPY_AMD 0x120A +#define CL_COMMAND_SVM_MEMFILL_AMD 0x120B +#define CL_COMMAND_SVM_MAP_AMD 0x120C +#define CL_COMMAND_SVM_UNMAP_AMD 0x120D + +typedef CL_API_ENTRY void* +(CL_API_CALL * clSVMAllocAMD_fn)( + cl_context /* context */, + cl_svm_mem_flags_amd /* flags */, + size_t /* size */, + unsigned int /* alignment */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY void +(CL_API_CALL * clSVMFreeAMD_fn)( + cl_context /* context */, + void* /* svm_pointer */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMFreeAMD_fn)( + cl_command_queue /* command_queue */, + cl_uint /* num_svm_pointers */, + void** /* svm_pointers */, + void (CL_CALLBACK *)( /*pfn_free_func*/ + cl_command_queue /* queue */, + cl_uint /* num_svm_pointers */, + void** /* svm_pointers */, + void* /* user_data */), + void* /* user_data */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMMemcpyAMD_fn)( + cl_command_queue /* command_queue */, + cl_bool /* blocking_copy */, + void* /* dst_ptr */, + const void* /* src_ptr */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMMemFillAMD_fn)( + cl_command_queue /* command_queue */, + void* /* svm_ptr */, + const void* /* pattern */, + size_t /* pattern_size */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMMapAMD_fn)( + cl_command_queue /* command_queue */, + cl_bool /* blocking_map */, + cl_map_flags /* map_flags */, + void* /* svm_ptr */, + size_t /* size */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clEnqueueSVMUnmapAMD_fn)( + cl_command_queue /* command_queue */, + void* /* svm_ptr */, + cl_uint /* num_events_in_wait_list */, + const cl_event* /* event_wait_list */, + cl_event* /* event */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clSetKernelArgSVMPointerAMD_fn)( + cl_kernel /* kernel */, + cl_uint /* arg_index */, + const void * /* arg_value */ +) CL_EXT_SUFFIX__VERSION_1_2; + +typedef CL_API_ENTRY cl_int +(CL_API_CALL * clSetKernelExecInfoAMD_fn)( + cl_kernel /* kernel */, + cl_kernel_exec_info_amd /* param_name */, + size_t /* param_value_size */, + const void * /* param_value */ +) CL_EXT_SUFFIX__VERSION_1_2; + +#endif + +#endif // HAVE_OPENCL_SVM + +#endif // OPENCV_CORE_OCL_RUNTIME_OPENCL_SVM_HSA_EXTENSION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp index 72387bd824..5d19f81f85 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/opengl.hpp @@ -1,733 +1,733 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OPENGL_HPP -#define OPENCV_CORE_OPENGL_HPP - -#ifndef __cplusplus -# error opengl.hpp header must be compiled as C++ -#endif - -#include "opencv2/core.hpp" -#include "ocl.hpp" - -namespace cv { namespace ogl { - -/** @addtogroup core_opengl -This section describes OpenGL interoperability. - -To enable OpenGL support, configure OpenCV using CMake with WITH_OPENGL=ON . Currently OpenGL is -supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not -supported). For GTK-2.0 backend gtkglext-1.0 library is required. - -To use OpenGL functionality you should first create OpenGL context (window or frame buffer). You can -do this with namedWindow function or with other OpenGL toolkit (GLUT, for example). -*/ -//! @{ - -/////////////////// OpenGL Objects /////////////////// - -/** @brief Smart pointer for OpenGL buffer object with reference counting. - -Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL -context. These can be used to store vertex data, pixel data retrieved from images or the -framebuffer, and a variety of other things. - -ogl::Buffer has interface similar with Mat interface and represents 2D array memory. - -ogl::Buffer supports memory transfers between host and device and also can be mapped to CUDA memory. - */ -class CV_EXPORTS Buffer -{ -public: - /** @brief The target defines how you intend to use the buffer object. - */ - enum Target - { - ARRAY_BUFFER = 0x8892, //!< The buffer will be used as a source for vertex data - ELEMENT_ARRAY_BUFFER = 0x8893, //!< The buffer will be used for indices (in glDrawElements, for example) - PIXEL_PACK_BUFFER = 0x88EB, //!< The buffer will be used for reading from OpenGL textures - PIXEL_UNPACK_BUFFER = 0x88EC //!< The buffer will be used for writing to OpenGL textures - }; - - enum Access - { - READ_ONLY = 0x88B8, - WRITE_ONLY = 0x88B9, - READ_WRITE = 0x88BA - }; - - /** @brief The constructors. - - Creates empty ogl::Buffer object, creates ogl::Buffer object from existed buffer ( abufId - parameter), allocates memory for ogl::Buffer object or copies from host/device memory. - */ - Buffer(); - - /** @overload - @param arows Number of rows in a 2D array. - @param acols Number of columns in a 2D array. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param abufId Buffer object name. - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param abufId Buffer object name. - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false); - - /** @overload - @param arows Number of rows in a 2D array. - @param acols Number of columns in a 2D array. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - explicit Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @brief Allocates memory for ogl::Buffer object. - - @param arows Number of rows in a 2D array. - @param acols Number of columns in a 2D array. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @brief Decrements the reference counter and destroys the buffer object if needed. - - The function will call setAutoRelease(true) . - */ - void release(); - - /** @brief Sets auto release mode. - - The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was - bound to a window it could be released at any time (user can close a window). If object's destructor - is called after destruction of the context it will cause an error. Thus ogl::Buffer doesn't destroy - OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). - This function can force ogl::Buffer destructor to destroy OpenGL object. - @param flag Auto release mode (if true, release will be called in object's destructor). - */ - void setAutoRelease(bool flag); - - /** @brief Copies from host/device memory to OpenGL buffer. - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). - @param target Buffer usage. See cv::ogl::Buffer::Target . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @overload */ - void copyFrom(InputArray arr, cuda::Stream& stream, Target target = ARRAY_BUFFER, bool autoRelease = false); - - /** @brief Copies from OpenGL buffer to host/device memory or another OpenGL buffer object. - - @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , std::vector or - ogl::Buffer ). - */ - void copyTo(OutputArray arr) const; - - /** @overload */ - void copyTo(OutputArray arr, cuda::Stream& stream) const; - - /** @brief Creates a full copy of the buffer object and the underlying data. - - @param target Buffer usage for destination buffer. - @param autoRelease Auto release mode for destination buffer. - */ - Buffer clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const; - - /** @brief Binds OpenGL buffer to the specified buffer binding point. - - @param target Binding point. See cv::ogl::Buffer::Target . - */ - void bind(Target target) const; - - /** @brief Unbind any buffers from the specified binding point. - - @param target Binding point. See cv::ogl::Buffer::Target . - */ - static void unbind(Target target); - - /** @brief Maps OpenGL buffer to host memory. - - mapHost maps to the client's address space the entire data store of the buffer object. The data can - then be directly read and/or written relative to the returned pointer, depending on the specified - access policy. - - A mapped data store must be unmapped with ogl::Buffer::unmapHost before its buffer object is used. - - This operation can lead to memory transfers between host and device. - - Only one buffer object can be mapped at a time. - @param access Access policy, indicating whether it will be possible to read from, write to, or both - read from and write to the buffer object's mapped data store. The symbolic constant must be - ogl::Buffer::READ_ONLY , ogl::Buffer::WRITE_ONLY or ogl::Buffer::READ_WRITE . - */ - Mat mapHost(Access access); - - /** @brief Unmaps OpenGL buffer. - */ - void unmapHost(); - - //! map to device memory (blocking) - cuda::GpuMat mapDevice(); - void unmapDevice(); - - /** @brief Maps OpenGL buffer to CUDA device memory. - - This operation doesn't copy data. Several buffer objects can be mapped to CUDA memory at a time. - - A mapped data store must be unmapped with ogl::Buffer::unmapDevice before its buffer object is used. - */ - cuda::GpuMat mapDevice(cuda::Stream& stream); - - /** @brief Unmaps OpenGL buffer. - */ - void unmapDevice(cuda::Stream& stream); - - int rows() const; - int cols() const; - Size size() const; - bool empty() const; - - int type() const; - int depth() const; - int channels() const; - int elemSize() const; - int elemSize1() const; - - //! get OpenGL opject id - unsigned int bufId() const; - - class Impl; - -private: - Ptr impl_; - int rows_; - int cols_; - int type_; -}; - -/** @brief Smart pointer for OpenGL 2D texture memory with reference counting. - */ -class CV_EXPORTS Texture2D -{ -public: - /** @brief An Image Format describes the way that the images in Textures store their data. - */ - enum Format - { - NONE = 0, - DEPTH_COMPONENT = 0x1902, //!< Depth - RGB = 0x1907, //!< Red, Green, Blue - RGBA = 0x1908 //!< Red, Green, Blue, Alpha - }; - - /** @brief The constructors. - - Creates empty ogl::Texture2D object, allocates memory for ogl::Texture2D object or copies from - host/device memory. - */ - Texture2D(); - - /** @overload */ - Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false); - - /** @overload */ - Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false); - - /** @overload - @param arows Number of rows. - @param acols Number of columns. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Texture2D(int arows, int acols, Format aformat, bool autoRelease = false); - - /** @overload - @param asize 2D array size. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - Texture2D(Size asize, Format aformat, bool autoRelease = false); - - /** @overload - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - explicit Texture2D(InputArray arr, bool autoRelease = false); - - /** @brief Allocates memory for ogl::Texture2D object. - - @param arows Number of rows. - @param acols Number of columns. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(int arows, int acols, Format aformat, bool autoRelease = false); - /** @overload - @param asize 2D array size. - @param aformat Image format. See cv::ogl::Texture2D::Format . - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void create(Size asize, Format aformat, bool autoRelease = false); - - /** @brief Decrements the reference counter and destroys the texture object if needed. - - The function will call setAutoRelease(true) . - */ - void release(); - - /** @brief Sets auto release mode. - - @param flag Auto release mode (if true, release will be called in object's destructor). - - The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was - bound to a window it could be released at any time (user can close a window). If object's destructor - is called after destruction of the context it will cause an error. Thus ogl::Texture2D doesn't - destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL - context). This function can force ogl::Texture2D destructor to destroy OpenGL object. - */ - void setAutoRelease(bool flag); - - /** @brief Copies from host/device memory to OpenGL texture. - - @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). - @param autoRelease Auto release mode (if true, release will be called in object's destructor). - */ - void copyFrom(InputArray arr, bool autoRelease = false); - - /** @brief Copies from OpenGL texture to host/device memory or another OpenGL texture object. - - @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , ogl::Buffer or - ogl::Texture2D ). - @param ddepth Destination depth. - @param autoRelease Auto release mode for destination buffer (if arr is OpenGL buffer or texture). - */ - void copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const; - - /** @brief Binds texture to current active texture unit for GL_TEXTURE_2D target. - */ - void bind() const; - - int rows() const; - int cols() const; - Size size() const; - bool empty() const; - - Format format() const; - - //! get OpenGL opject id - unsigned int texId() const; - - class Impl; - -private: - Ptr impl_; - int rows_; - int cols_; - Format format_; -}; - -/** @brief Wrapper for OpenGL Client-Side Vertex arrays. - -ogl::Arrays stores vertex data in ogl::Buffer objects. - */ -class CV_EXPORTS Arrays -{ -public: - /** @brief Default constructor - */ - Arrays(); - - /** @brief Sets an array of vertex coordinates. - @param vertex array with vertex coordinates, can be both host and device memory. - */ - void setVertexArray(InputArray vertex); - - /** @brief Resets vertex coordinates. - */ - void resetVertexArray(); - - /** @brief Sets an array of vertex colors. - @param color array with vertex colors, can be both host and device memory. - */ - void setColorArray(InputArray color); - - /** @brief Resets vertex colors. - */ - void resetColorArray(); - - /** @brief Sets an array of vertex normals. - @param normal array with vertex normals, can be both host and device memory. - */ - void setNormalArray(InputArray normal); - - /** @brief Resets vertex normals. - */ - void resetNormalArray(); - - /** @brief Sets an array of vertex texture coordinates. - @param texCoord array with vertex texture coordinates, can be both host and device memory. - */ - void setTexCoordArray(InputArray texCoord); - - /** @brief Resets vertex texture coordinates. - */ - void resetTexCoordArray(); - - /** @brief Releases all inner buffers. - */ - void release(); - - /** @brief Sets auto release mode all inner buffers. - @param flag Auto release mode. - */ - void setAutoRelease(bool flag); - - /** @brief Binds all vertex arrays. - */ - void bind() const; - - /** @brief Returns the vertex count. - */ - int size() const; - bool empty() const; - -private: - int size_; - Buffer vertex_; - Buffer color_; - Buffer normal_; - Buffer texCoord_; -}; - -/////////////////// Render Functions /////////////////// - -//! render mode -enum RenderModes { - POINTS = 0x0000, - LINES = 0x0001, - LINE_LOOP = 0x0002, - LINE_STRIP = 0x0003, - TRIANGLES = 0x0004, - TRIANGLE_STRIP = 0x0005, - TRIANGLE_FAN = 0x0006, - QUADS = 0x0007, - QUAD_STRIP = 0x0008, - POLYGON = 0x0009 -}; - -/** @brief Render OpenGL texture or primitives. -@param tex Texture to draw. -@param wndRect Region of window, where to draw a texture (normalized coordinates). -@param texRect Region of texture to draw (normalized coordinates). - */ -CV_EXPORTS void render(const Texture2D& tex, - Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), - Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)); - -/** @overload -@param arr Array of privitives vertices. -@param mode Render mode. One of cv::ogl::RenderModes -@param color Color for all vertices. Will be used if arr doesn't contain color array. -*/ -CV_EXPORTS void render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255)); - -/** @overload -@param arr Array of privitives vertices. -@param indices Array of vertices indices (host or device memory). -@param mode Render mode. One of cv::ogl::RenderModes -@param color Color for all vertices. Will be used if arr doesn't contain color array. -*/ -CV_EXPORTS void render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255)); - -/////////////////// CL-GL Interoperability Functions /////////////////// - -namespace ocl { -using namespace cv::ocl; - -// TODO static functions in the Context class -/** @brief Creates OpenCL context from GL. -@return Returns reference to OpenCL Context - */ -CV_EXPORTS Context& initializeContextFromGL(); - -} // namespace cv::ogl::ocl - -/** @brief Converts InputArray to Texture2D object. -@param src - source InputArray. -@param texture - destination Texture2D object. - */ -CV_EXPORTS void convertToGLTexture2D(InputArray src, Texture2D& texture); - -/** @brief Converts Texture2D object to OutputArray. -@param texture - source Texture2D object. -@param dst - destination OutputArray. - */ -CV_EXPORTS void convertFromGLTexture2D(const Texture2D& texture, OutputArray dst); - -/** @brief Maps Buffer object to process on CL side (convert to UMat). - -Function creates CL buffer from GL one, and then constructs UMat that can be used -to process buffer data with OpenCV functions. Note that in current implementation -UMat constructed this way doesn't own corresponding GL buffer object, so it is -the user responsibility to close down CL/GL buffers relationships by explicitly -calling unmapGLBuffer() function. -@param buffer - source Buffer object. -@param accessFlags - data access flags (ACCESS_READ|ACCESS_WRITE). -@return Returns UMat object - */ -CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, AccessFlag accessFlags = ACCESS_READ | ACCESS_WRITE); - -/** @brief Unmaps Buffer object (releases UMat, previously mapped from Buffer). - -Function must be called explicitly by the user for each UMat previously constructed -by the call to mapGLBuffer() function. -@param u - source UMat, created by mapGLBuffer(). - */ -CV_EXPORTS void unmapGLBuffer(UMat& u); - -//! @} -}} // namespace cv::ogl - -namespace cv { namespace cuda { - -/** @brief Sets a CUDA device and initializes it for the current thread with OpenGL interoperability. - -This function should be explicitly called after OpenGL context creation and before any CUDA calls. -@param device System index of a CUDA device starting with 0. -@ingroup core_opengl - */ -CV_EXPORTS void setGlDevice(int device = 0); - -}} - -//! @cond IGNORED - -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////// - -inline -cv::ogl::Buffer::Buffer(int arows, int acols, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) -{ - create(arows, acols, atype, target, autoRelease); -} - -inline -cv::ogl::Buffer::Buffer(Size asize, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) -{ - create(asize, atype, target, autoRelease); -} - -inline -void cv::ogl::Buffer::create(Size asize, int atype, Target target, bool autoRelease) -{ - create(asize.height, asize.width, atype, target, autoRelease); -} - -inline -int cv::ogl::Buffer::rows() const -{ - return rows_; -} - -inline -int cv::ogl::Buffer::cols() const -{ - return cols_; -} - -inline -cv::Size cv::ogl::Buffer::size() const -{ - return Size(cols_, rows_); -} - -inline -bool cv::ogl::Buffer::empty() const -{ - return rows_ == 0 || cols_ == 0; -} - -inline -int cv::ogl::Buffer::type() const -{ - return type_; -} - -inline -int cv::ogl::Buffer::depth() const -{ - return CV_MAT_DEPTH(type_); -} - -inline -int cv::ogl::Buffer::channels() const -{ - return CV_MAT_CN(type_); -} - -inline -int cv::ogl::Buffer::elemSize() const -{ - return CV_ELEM_SIZE(type_); -} - -inline -int cv::ogl::Buffer::elemSize1() const -{ - return CV_ELEM_SIZE1(type_); -} - -/////// - -inline -cv::ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) -{ - create(arows, acols, aformat, autoRelease); -} - -inline -cv::ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) -{ - create(asize, aformat, autoRelease); -} - -inline -void cv::ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease) -{ - create(asize.height, asize.width, aformat, autoRelease); -} - -inline -int cv::ogl::Texture2D::rows() const -{ - return rows_; -} - -inline -int cv::ogl::Texture2D::cols() const -{ - return cols_; -} - -inline -cv::Size cv::ogl::Texture2D::size() const -{ - return Size(cols_, rows_); -} - -inline -bool cv::ogl::Texture2D::empty() const -{ - return rows_ == 0 || cols_ == 0; -} - -inline -cv::ogl::Texture2D::Format cv::ogl::Texture2D::format() const -{ - return format_; -} - -/////// - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif -inline -cv::ogl::Arrays::Arrays() : size_(0) -{ -} -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - -inline -int cv::ogl::Arrays::size() const -{ - return size_; -} - -inline -bool cv::ogl::Arrays::empty() const -{ - return size_ == 0; -} - -//! @endcond - -#endif /* OPENCV_CORE_OPENGL_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OPENGL_HPP +#define OPENCV_CORE_OPENGL_HPP + +#ifndef __cplusplus +# error opengl.hpp header must be compiled as C++ +#endif + +#include "opencv2/core.hpp" +#include "ocl.hpp" + +namespace cv { namespace ogl { + +/** @addtogroup core_opengl +This section describes OpenGL interoperability. + +To enable OpenGL support, configure OpenCV using CMake with WITH_OPENGL=ON . Currently OpenGL is +supported only with WIN32, GTK and Qt backends on Windows and Linux (MacOS and Android are not +supported). For GTK-2.0 backend gtkglext-1.0 library is required. + +To use OpenGL functionality you should first create OpenGL context (window or frame buffer). You can +do this with namedWindow function or with other OpenGL toolkit (GLUT, for example). +*/ +//! @{ + +/////////////////// OpenGL Objects /////////////////// + +/** @brief Smart pointer for OpenGL buffer object with reference counting. + +Buffer Objects are OpenGL objects that store an array of unformatted memory allocated by the OpenGL +context. These can be used to store vertex data, pixel data retrieved from images or the +framebuffer, and a variety of other things. + +ogl::Buffer has interface similar with Mat interface and represents 2D array memory. + +ogl::Buffer supports memory transfers between host and device and also can be mapped to CUDA memory. + */ +class CV_EXPORTS Buffer +{ +public: + /** @brief The target defines how you intend to use the buffer object. + */ + enum Target + { + ARRAY_BUFFER = 0x8892, //!< The buffer will be used as a source for vertex data + ELEMENT_ARRAY_BUFFER = 0x8893, //!< The buffer will be used for indices (in glDrawElements, for example) + PIXEL_PACK_BUFFER = 0x88EB, //!< The buffer will be used for reading from OpenGL textures + PIXEL_UNPACK_BUFFER = 0x88EC //!< The buffer will be used for writing to OpenGL textures + }; + + enum Access + { + READ_ONLY = 0x88B8, + WRITE_ONLY = 0x88B9, + READ_WRITE = 0x88BA + }; + + /** @brief The constructors. + + Creates empty ogl::Buffer object, creates ogl::Buffer object from existed buffer ( abufId + parameter), allocates memory for ogl::Buffer object or copies from host/device memory. + */ + Buffer(); + + /** @overload + @param arows Number of rows in a 2D array. + @param acols Number of columns in a 2D array. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param abufId Buffer object name. + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(int arows, int acols, int atype, unsigned int abufId, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param abufId Buffer object name. + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(Size asize, int atype, unsigned int abufId, bool autoRelease = false); + + /** @overload + @param arows Number of rows in a 2D array. + @param acols Number of columns in a 2D array. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Buffer(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + explicit Buffer(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @brief Allocates memory for ogl::Buffer object. + + @param arows Number of rows in a 2D array. + @param acols Number of columns in a 2D array. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(int arows, int acols, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param atype Array type ( CV_8UC1, ..., CV_64FC4 ). See Mat for details. + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(Size asize, int atype, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @brief Decrements the reference counter and destroys the buffer object if needed. + + The function will call setAutoRelease(true) . + */ + void release(); + + /** @brief Sets auto release mode. + + The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was + bound to a window it could be released at any time (user can close a window). If object's destructor + is called after destruction of the context it will cause an error. Thus ogl::Buffer doesn't destroy + OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL context). + This function can force ogl::Buffer destructor to destroy OpenGL object. + @param flag Auto release mode (if true, release will be called in object's destructor). + */ + void setAutoRelease(bool flag); + + /** @brief Copies from host/device memory to OpenGL buffer. + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or std::vector ). + @param target Buffer usage. See cv::ogl::Buffer::Target . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void copyFrom(InputArray arr, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @overload */ + void copyFrom(InputArray arr, cuda::Stream& stream, Target target = ARRAY_BUFFER, bool autoRelease = false); + + /** @brief Copies from OpenGL buffer to host/device memory or another OpenGL buffer object. + + @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , std::vector or + ogl::Buffer ). + */ + void copyTo(OutputArray arr) const; + + /** @overload */ + void copyTo(OutputArray arr, cuda::Stream& stream) const; + + /** @brief Creates a full copy of the buffer object and the underlying data. + + @param target Buffer usage for destination buffer. + @param autoRelease Auto release mode for destination buffer. + */ + Buffer clone(Target target = ARRAY_BUFFER, bool autoRelease = false) const; + + /** @brief Binds OpenGL buffer to the specified buffer binding point. + + @param target Binding point. See cv::ogl::Buffer::Target . + */ + void bind(Target target) const; + + /** @brief Unbind any buffers from the specified binding point. + + @param target Binding point. See cv::ogl::Buffer::Target . + */ + static void unbind(Target target); + + /** @brief Maps OpenGL buffer to host memory. + + mapHost maps to the client's address space the entire data store of the buffer object. The data can + then be directly read and/or written relative to the returned pointer, depending on the specified + access policy. + + A mapped data store must be unmapped with ogl::Buffer::unmapHost before its buffer object is used. + + This operation can lead to memory transfers between host and device. + + Only one buffer object can be mapped at a time. + @param access Access policy, indicating whether it will be possible to read from, write to, or both + read from and write to the buffer object's mapped data store. The symbolic constant must be + ogl::Buffer::READ_ONLY , ogl::Buffer::WRITE_ONLY or ogl::Buffer::READ_WRITE . + */ + Mat mapHost(Access access); + + /** @brief Unmaps OpenGL buffer. + */ + void unmapHost(); + + //! map to device memory (blocking) + cuda::GpuMat mapDevice(); + void unmapDevice(); + + /** @brief Maps OpenGL buffer to CUDA device memory. + + This operation doesn't copy data. Several buffer objects can be mapped to CUDA memory at a time. + + A mapped data store must be unmapped with ogl::Buffer::unmapDevice before its buffer object is used. + */ + cuda::GpuMat mapDevice(cuda::Stream& stream); + + /** @brief Unmaps OpenGL buffer. + */ + void unmapDevice(cuda::Stream& stream); + + int rows() const; + int cols() const; + Size size() const; + bool empty() const; + + int type() const; + int depth() const; + int channels() const; + int elemSize() const; + int elemSize1() const; + + //! get OpenGL opject id + unsigned int bufId() const; + + class Impl; + +private: + Ptr impl_; + int rows_; + int cols_; + int type_; +}; + +/** @brief Smart pointer for OpenGL 2D texture memory with reference counting. + */ +class CV_EXPORTS Texture2D +{ +public: + /** @brief An Image Format describes the way that the images in Textures store their data. + */ + enum Format + { + NONE = 0, + DEPTH_COMPONENT = 0x1902, //!< Depth + RGB = 0x1907, //!< Red, Green, Blue + RGBA = 0x1908 //!< Red, Green, Blue, Alpha + }; + + /** @brief The constructors. + + Creates empty ogl::Texture2D object, allocates memory for ogl::Texture2D object or copies from + host/device memory. + */ + Texture2D(); + + /** @overload */ + Texture2D(int arows, int acols, Format aformat, unsigned int atexId, bool autoRelease = false); + + /** @overload */ + Texture2D(Size asize, Format aformat, unsigned int atexId, bool autoRelease = false); + + /** @overload + @param arows Number of rows. + @param acols Number of columns. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Texture2D(int arows, int acols, Format aformat, bool autoRelease = false); + + /** @overload + @param asize 2D array size. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + Texture2D(Size asize, Format aformat, bool autoRelease = false); + + /** @overload + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + explicit Texture2D(InputArray arr, bool autoRelease = false); + + /** @brief Allocates memory for ogl::Texture2D object. + + @param arows Number of rows. + @param acols Number of columns. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(int arows, int acols, Format aformat, bool autoRelease = false); + /** @overload + @param asize 2D array size. + @param aformat Image format. See cv::ogl::Texture2D::Format . + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void create(Size asize, Format aformat, bool autoRelease = false); + + /** @brief Decrements the reference counter and destroys the texture object if needed. + + The function will call setAutoRelease(true) . + */ + void release(); + + /** @brief Sets auto release mode. + + @param flag Auto release mode (if true, release will be called in object's destructor). + + The lifetime of the OpenGL object is tied to the lifetime of the context. If OpenGL context was + bound to a window it could be released at any time (user can close a window). If object's destructor + is called after destruction of the context it will cause an error. Thus ogl::Texture2D doesn't + destroy OpenGL object in destructor by default (all OpenGL resources will be released with OpenGL + context). This function can force ogl::Texture2D destructor to destroy OpenGL object. + */ + void setAutoRelease(bool flag); + + /** @brief Copies from host/device memory to OpenGL texture. + + @param arr Input array (host or device memory, it can be Mat , cuda::GpuMat or ogl::Buffer ). + @param autoRelease Auto release mode (if true, release will be called in object's destructor). + */ + void copyFrom(InputArray arr, bool autoRelease = false); + + /** @brief Copies from OpenGL texture to host/device memory or another OpenGL texture object. + + @param arr Destination array (host or device memory, can be Mat , cuda::GpuMat , ogl::Buffer or + ogl::Texture2D ). + @param ddepth Destination depth. + @param autoRelease Auto release mode for destination buffer (if arr is OpenGL buffer or texture). + */ + void copyTo(OutputArray arr, int ddepth = CV_32F, bool autoRelease = false) const; + + /** @brief Binds texture to current active texture unit for GL_TEXTURE_2D target. + */ + void bind() const; + + int rows() const; + int cols() const; + Size size() const; + bool empty() const; + + Format format() const; + + //! get OpenGL opject id + unsigned int texId() const; + + class Impl; + +private: + Ptr impl_; + int rows_; + int cols_; + Format format_; +}; + +/** @brief Wrapper for OpenGL Client-Side Vertex arrays. + +ogl::Arrays stores vertex data in ogl::Buffer objects. + */ +class CV_EXPORTS Arrays +{ +public: + /** @brief Default constructor + */ + Arrays(); + + /** @brief Sets an array of vertex coordinates. + @param vertex array with vertex coordinates, can be both host and device memory. + */ + void setVertexArray(InputArray vertex); + + /** @brief Resets vertex coordinates. + */ + void resetVertexArray(); + + /** @brief Sets an array of vertex colors. + @param color array with vertex colors, can be both host and device memory. + */ + void setColorArray(InputArray color); + + /** @brief Resets vertex colors. + */ + void resetColorArray(); + + /** @brief Sets an array of vertex normals. + @param normal array with vertex normals, can be both host and device memory. + */ + void setNormalArray(InputArray normal); + + /** @brief Resets vertex normals. + */ + void resetNormalArray(); + + /** @brief Sets an array of vertex texture coordinates. + @param texCoord array with vertex texture coordinates, can be both host and device memory. + */ + void setTexCoordArray(InputArray texCoord); + + /** @brief Resets vertex texture coordinates. + */ + void resetTexCoordArray(); + + /** @brief Releases all inner buffers. + */ + void release(); + + /** @brief Sets auto release mode all inner buffers. + @param flag Auto release mode. + */ + void setAutoRelease(bool flag); + + /** @brief Binds all vertex arrays. + */ + void bind() const; + + /** @brief Returns the vertex count. + */ + int size() const; + bool empty() const; + +private: + int size_; + Buffer vertex_; + Buffer color_; + Buffer normal_; + Buffer texCoord_; +}; + +/////////////////// Render Functions /////////////////// + +//! render mode +enum RenderModes { + POINTS = 0x0000, + LINES = 0x0001, + LINE_LOOP = 0x0002, + LINE_STRIP = 0x0003, + TRIANGLES = 0x0004, + TRIANGLE_STRIP = 0x0005, + TRIANGLE_FAN = 0x0006, + QUADS = 0x0007, + QUAD_STRIP = 0x0008, + POLYGON = 0x0009 +}; + +/** @brief Render OpenGL texture or primitives. +@param tex Texture to draw. +@param wndRect Region of window, where to draw a texture (normalized coordinates). +@param texRect Region of texture to draw (normalized coordinates). + */ +CV_EXPORTS void render(const Texture2D& tex, + Rect_ wndRect = Rect_(0.0, 0.0, 1.0, 1.0), + Rect_ texRect = Rect_(0.0, 0.0, 1.0, 1.0)); + +/** @overload +@param arr Array of privitives vertices. +@param mode Render mode. One of cv::ogl::RenderModes +@param color Color for all vertices. Will be used if arr doesn't contain color array. +*/ +CV_EXPORTS void render(const Arrays& arr, int mode = POINTS, Scalar color = Scalar::all(255)); + +/** @overload +@param arr Array of privitives vertices. +@param indices Array of vertices indices (host or device memory). +@param mode Render mode. One of cv::ogl::RenderModes +@param color Color for all vertices. Will be used if arr doesn't contain color array. +*/ +CV_EXPORTS void render(const Arrays& arr, InputArray indices, int mode = POINTS, Scalar color = Scalar::all(255)); + +/////////////////// CL-GL Interoperability Functions /////////////////// + +namespace ocl { +using namespace cv::ocl; + +// TODO static functions in the Context class +/** @brief Creates OpenCL context from GL. +@return Returns reference to OpenCL Context + */ +CV_EXPORTS Context& initializeContextFromGL(); + +} // namespace cv::ogl::ocl + +/** @brief Converts InputArray to Texture2D object. +@param src - source InputArray. +@param texture - destination Texture2D object. + */ +CV_EXPORTS void convertToGLTexture2D(InputArray src, Texture2D& texture); + +/** @brief Converts Texture2D object to OutputArray. +@param texture - source Texture2D object. +@param dst - destination OutputArray. + */ +CV_EXPORTS void convertFromGLTexture2D(const Texture2D& texture, OutputArray dst); + +/** @brief Maps Buffer object to process on CL side (convert to UMat). + +Function creates CL buffer from GL one, and then constructs UMat that can be used +to process buffer data with OpenCV functions. Note that in current implementation +UMat constructed this way doesn't own corresponding GL buffer object, so it is +the user responsibility to close down CL/GL buffers relationships by explicitly +calling unmapGLBuffer() function. +@param buffer - source Buffer object. +@param accessFlags - data access flags (ACCESS_READ|ACCESS_WRITE). +@return Returns UMat object + */ +CV_EXPORTS UMat mapGLBuffer(const Buffer& buffer, AccessFlag accessFlags = ACCESS_READ | ACCESS_WRITE); + +/** @brief Unmaps Buffer object (releases UMat, previously mapped from Buffer). + +Function must be called explicitly by the user for each UMat previously constructed +by the call to mapGLBuffer() function. +@param u - source UMat, created by mapGLBuffer(). + */ +CV_EXPORTS void unmapGLBuffer(UMat& u); + +//! @} +}} // namespace cv::ogl + +namespace cv { namespace cuda { + +/** @brief Sets a CUDA device and initializes it for the current thread with OpenGL interoperability. + +This function should be explicitly called after OpenGL context creation and before any CUDA calls. +@param device System index of a CUDA device starting with 0. +@ingroup core_opengl + */ +CV_EXPORTS void setGlDevice(int device = 0); + +}} + +//! @cond IGNORED + +//////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////// + +inline +cv::ogl::Buffer::Buffer(int arows, int acols, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) +{ + create(arows, acols, atype, target, autoRelease); +} + +inline +cv::ogl::Buffer::Buffer(Size asize, int atype, Target target, bool autoRelease) : rows_(0), cols_(0), type_(0) +{ + create(asize, atype, target, autoRelease); +} + +inline +void cv::ogl::Buffer::create(Size asize, int atype, Target target, bool autoRelease) +{ + create(asize.height, asize.width, atype, target, autoRelease); +} + +inline +int cv::ogl::Buffer::rows() const +{ + return rows_; +} + +inline +int cv::ogl::Buffer::cols() const +{ + return cols_; +} + +inline +cv::Size cv::ogl::Buffer::size() const +{ + return Size(cols_, rows_); +} + +inline +bool cv::ogl::Buffer::empty() const +{ + return rows_ == 0 || cols_ == 0; +} + +inline +int cv::ogl::Buffer::type() const +{ + return type_; +} + +inline +int cv::ogl::Buffer::depth() const +{ + return CV_MAT_DEPTH(type_); +} + +inline +int cv::ogl::Buffer::channels() const +{ + return CV_MAT_CN(type_); +} + +inline +int cv::ogl::Buffer::elemSize() const +{ + return CV_ELEM_SIZE(type_); +} + +inline +int cv::ogl::Buffer::elemSize1() const +{ + return CV_ELEM_SIZE1(type_); +} + +/////// + +inline +cv::ogl::Texture2D::Texture2D(int arows, int acols, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) +{ + create(arows, acols, aformat, autoRelease); +} + +inline +cv::ogl::Texture2D::Texture2D(Size asize, Format aformat, bool autoRelease) : rows_(0), cols_(0), format_(NONE) +{ + create(asize, aformat, autoRelease); +} + +inline +void cv::ogl::Texture2D::create(Size asize, Format aformat, bool autoRelease) +{ + create(asize.height, asize.width, aformat, autoRelease); +} + +inline +int cv::ogl::Texture2D::rows() const +{ + return rows_; +} + +inline +int cv::ogl::Texture2D::cols() const +{ + return cols_; +} + +inline +cv::Size cv::ogl::Texture2D::size() const +{ + return Size(cols_, rows_); +} + +inline +bool cv::ogl::Texture2D::empty() const +{ + return rows_ == 0 || cols_ == 0; +} + +inline +cv::ogl::Texture2D::Format cv::ogl::Texture2D::format() const +{ + return format_; +} + +/////// + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif +inline +cv::ogl::Arrays::Arrays() : size_(0) +{ +} +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + +inline +int cv::ogl::Arrays::size() const +{ + return size_; +} + +inline +bool cv::ogl::Arrays::empty() const +{ + return size_ == 0; +} + +//! @endcond + +#endif /* OPENCV_CORE_OPENGL_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp b/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp index f754b6f01b..7eeb2ab4c2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/operations.hpp @@ -1,612 +1,612 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_OPERATIONS_HPP -#define OPENCV_CORE_OPERATIONS_HPP - -#ifndef __cplusplus -# error operations.hpp header must be compiled as C++ -#endif - -#include - -#if defined(__GNUC__) || defined(__clang__) // at least GCC 3.1+, clang 3.5+ -# if defined(__MINGW_PRINTF_FORMAT) // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. -# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (__MINGW_PRINTF_FORMAT, string_idx, first_to_check))) -# else -# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (printf, string_idx, first_to_check))) -# endif -#else -# define CV_FORMAT_PRINTF(A, B) -#endif - -namespace cv -{ -//! @cond IGNORED - - -////////////////////////////// Matx methods depending on core API ///////////////////////////// - -namespace internal -{ - -template struct Matx_FastInvOp -{ - bool operator()(const Matx<_Tp, m, n>& a, Matx<_Tp, n, m>& b, int method) const - { - return invert(a, b, method) != 0; - } -}; - -template struct Matx_FastInvOp<_Tp, m, m> -{ - bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const - { - if (method == DECOMP_LU || method == DECOMP_CHOLESKY) - { - Matx<_Tp, m, m> temp = a; - - // assume that b is all 0's on input => make it a unity matrix - for (int i = 0; i < m; i++) - b(i, i) = (_Tp)1; - - if (method == DECOMP_CHOLESKY) - return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); - - return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; - } - else - { - return invert(a, b, method) != 0; - } - } -}; - -template struct Matx_FastInvOp<_Tp, 2, 2> -{ - bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int /*method*/) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - b(1,1) = a(0,0)*d; - b(0,0) = a(1,1)*d; - b(0,1) = -a(0,1)*d; - b(1,0) = -a(1,0)*d; - return true; - } -}; - -template struct Matx_FastInvOp<_Tp, 3, 3> -{ - bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int /*method*/) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; - b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d; - b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d; - - b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d; - b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d; - b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d; - - b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d; - b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d; - b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d; - return true; - } -}; - - -template struct Matx_FastSolveOp -{ - bool operator()(const Matx<_Tp, m, l>& a, const Matx<_Tp, m, n>& b, - Matx<_Tp, l, n>& x, int method) const - { - return cv::solve(a, b, x, method); - } -}; - -template struct Matx_FastSolveOp<_Tp, m, m, n> -{ - bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b, - Matx<_Tp, m, n>& x, int method) const - { - if (method == DECOMP_LU || method == DECOMP_CHOLESKY) - { - Matx<_Tp, m, m> temp = a; - x = b; - if( method == DECOMP_CHOLESKY ) - return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); - - return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; - } - else - { - return cv::solve(a, b, x, method); - } - } -}; - -template struct Matx_FastSolveOp<_Tp, 2, 2, 1> -{ - bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, - Matx<_Tp, 2, 1>& x, int) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d; - x(1) = (b(1)*a(0,0) - b(0)*a(1,0))*d; - return true; - } -}; - -template struct Matx_FastSolveOp<_Tp, 3, 3, 1> -{ - bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, - Matx<_Tp, 3, 1>& x, int) const - { - _Tp d = (_Tp)determinant(a); - if (d == 0) - return false; - d = 1/d; - x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - - a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) + - a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2))); - - x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) - - b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) + - a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0))); - - x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) - - a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) + - b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0))); - return true; - } -}; - -} // internal - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) -{ - Matx<_Tp,m,n> M; - cv::randu(M, Scalar(a), Scalar(b)); - return M; -} - -template inline -Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) -{ - Matx<_Tp,m,n> M; - cv::randn(M, Scalar(a), Scalar(b)); - return M; -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::randu(_Tp a, _Tp b) -{ - Vec<_Tp,cn> V; - cv::randu(V, Scalar(a), Scalar(b)); - return V; -} - -template inline -Vec<_Tp, cn> Vec<_Tp, cn>::randn(_Tp a, _Tp b) -{ - Vec<_Tp,cn> V; - cv::randn(V, Scalar(a), Scalar(b)); - return V; -} - -template inline -Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const -{ - Matx<_Tp, n, m> b; - bool ok = cv::internal::Matx_FastInvOp<_Tp, m, n>()(*this, b, method); - if (p_is_ok) *p_is_ok = ok; - return ok ? b : Matx<_Tp, n, m>::zeros(); -} - -template template inline -Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const -{ - Matx<_Tp, n, l> x; - bool ok = cv::internal::Matx_FastSolveOp<_Tp, m, n, l>()(*this, rhs, x, method); - return ok ? x : Matx<_Tp, n, l>::zeros(); -} - - - -////////////////////////// Augmenting algebraic & logical operations ////////////////////////// - -#define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ - static inline A& operator op (A& a, const B& b) { cvop; return a; } - -#define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \ - CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ - CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) - -#define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \ - template CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ - template CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) - -#define CV_MAT_AUG_OPERATOR_TN(op, cvop, A) \ - template static inline A& operator op (A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } \ - template static inline const A& operator op (const A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } - -CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat) -CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double) -CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double) -CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat) -CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (/=, cv::divide(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double) -CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double) -CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Mat) -CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Scalar) -CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat) -CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) -CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) -CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat) -CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat_<_Tp>) - -#undef CV_MAT_AUG_OPERATOR_TN -#undef CV_MAT_AUG_OPERATOR_T -#undef CV_MAT_AUG_OPERATOR -#undef CV_MAT_AUG_OPERATOR1 - - - -///////////////////////////////////////////// SVD ///////////////////////////////////////////// - -inline SVD::SVD() {} -inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } -inline void SVD::solveZ( InputArray m, OutputArray _dst ) -{ - Mat mtx = m.getMat(); - SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); - _dst.create(svd.vt.cols, 1, svd.vt.type()); - Mat dst = _dst.getMat(); - svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); -} - -template inline void - SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) -{ - CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); - Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); - SVD::compute(_a, _w, _u, _vt); - CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); -} - -template inline void -SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) -{ - CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); - Mat _a(a, false), _w(w, false); - SVD::compute(_a, _w); - CV_Assert(_w.data == (uchar*)&w.val[0]); -} - -template inline void -SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, - const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, - Matx<_Tp, n, nb>& dst ) -{ - CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); - Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); - SVD::backSubst(_w, _u, _vt, _rhs, _dst); - CV_Assert(_dst.data == (uchar*)&dst.val[0]); -} - - - -/////////////////////////////////// Multiply-with-Carry RNG /////////////////////////////////// - -inline RNG::RNG() { state = 0xffffffff; } -inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } - -inline RNG::operator uchar() { return (uchar)next(); } -inline RNG::operator schar() { return (schar)next(); } -inline RNG::operator ushort() { return (ushort)next(); } -inline RNG::operator short() { return (short)next(); } -inline RNG::operator int() { return (int)next(); } -inline RNG::operator unsigned() { return next(); } -inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } -inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; } - -inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); } -inline unsigned RNG::operator ()() { return next(); } - -inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); } -inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } -inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } - -inline bool RNG::operator ==(const RNG& other) const { return state == other.state; } - -inline unsigned RNG::next() -{ - state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32); - return (unsigned)state; -} - -//! returns the next uniformly-distributed random number of the specified type -template static inline _Tp randu() -{ - return (_Tp)theRNG(); -} - - -///////////////////////////////// Formatted output of cv::Mat ///////////////////////////////// - -static inline -Ptr format(InputArray mtx, Formatter::FormatType fmt) -{ - return Formatter::get(fmt)->format(mtx.getMat()); -} - -static inline -int print(Ptr fmtd, FILE* stream = stdout) -{ - int written = 0; - fmtd->reset(); - for(const char* str = fmtd->next(); str; str = fmtd->next()) - written += fputs(str, stream); - - return written; -} - -static inline -int print(const Mat& mtx, FILE* stream = stdout) -{ - return print(Formatter::get()->format(mtx), stream); -} - -static inline -int print(const UMat& mtx, FILE* stream = stdout) -{ - return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream); -} - -template static inline -int print(const std::vector >& vec, FILE* stream = stdout) -{ - return print(Formatter::get()->format(Mat(vec)), stream); -} - -template static inline -int print(const std::vector >& vec, FILE* stream = stdout) -{ - return print(Formatter::get()->format(Mat(vec)), stream); -} - -template static inline -int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) -{ - return print(Formatter::get()->format(cv::Mat(matx)), stream); -} - -//! @endcond - -///////////////////////////////// Formatted string generation ///////////////////////////////// - -/** @brief Returns a text string formatted using the printf-like expression. - -The function acts like sprintf but forms and returns an STL string. It can be used to form an error -message in the Exception constructor. -@param fmt printf-compatible formatting specifiers. - -**Note**: -|Type|Specifier| -|-|-| -|`const char*`|`%s`| -|`char`|`%c`| -|`float` / `double`|`%f`,`%g`| -|`int`, `long`, `long long`|`%d`, `%ld`, ``%lld`| -|`unsigned`, `unsigned long`, `unsigned long long`|`%u`, `%lu`, `%llu`| -|`uint64` -> `uintmax_t`, `int64` -> `intmax_t`|`%ju`, `%jd`| -|`size_t`|`%zu`| -@ingroup core_utils - */ -CV_EXPORTS String format(const char* fmt, ...) CV_FORMAT_PRINTF(1, 2); - -/****************************************************************************************\ -* Auxiliary algorithms * -\****************************************************************************************/ - -/** @brief Splits an element set into equivalency classes. - -The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements -into one or more equivalency classes, as described in - . The function returns the number of -equivalency classes. -@param vec Set of elements stored as a vector. -@param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is -a 0-based cluster index of `vec[i]`. -@param predicate Equivalence predicate (pointer to a boolean function of two arguments or an -instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The -predicate returns true when the elements are certainly in the same class, and returns false if they -may or may not be in the same class. -@ingroup core_cluster -*/ -template int -partition( const std::vector<_Tp>& vec, std::vector& labels, - _EqPredicate predicate=_EqPredicate()) -{ - int i, j, N = (int)vec.size(); - const _Tp* _vec = &vec[0]; - - const int PARENT=0; - const int RANK=1; - - std::vector _nodes(N*2); - int (*nodes)[2] = (int(*)[2])&_nodes[0]; - - // The first O(N) pass: create N single-vertex trees - for(i = 0; i < N; i++) - { - nodes[i][PARENT]=-1; - nodes[i][RANK] = 0; - } - - // The main O(N^2) pass: merge connected components - for( i = 0; i < N; i++ ) - { - int root = i; - - // find root - while( nodes[root][PARENT] >= 0 ) - root = nodes[root][PARENT]; - - for( j = 0; j < N; j++ ) - { - if( i == j || !predicate(_vec[i], _vec[j])) - continue; - int root2 = j; - - while( nodes[root2][PARENT] >= 0 ) - root2 = nodes[root2][PARENT]; - - if( root2 != root ) - { - // unite both trees - int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; - if( rank > rank2 ) - nodes[root2][PARENT] = root; - else - { - nodes[root][PARENT] = root2; - nodes[root2][RANK] += rank == rank2; - root = root2; - } - CV_Assert( nodes[root][PARENT] < 0 ); - - int k = j, parent; - - // compress the path from node2 to root - while( (parent = nodes[k][PARENT]) >= 0 ) - { - nodes[k][PARENT] = root; - k = parent; - } - - // compress the path from node to root - k = i; - while( (parent = nodes[k][PARENT]) >= 0 ) - { - nodes[k][PARENT] = root; - k = parent; - } - } - } - } - - // Final O(N) pass: enumerate classes - labels.resize(N); - int nclasses = 0; - - for( i = 0; i < N; i++ ) - { - int root = i; - while( nodes[root][PARENT] >= 0 ) - root = nodes[root][PARENT]; - // re-use the rank as the class label - if( nodes[root][RANK] >= 0 ) - nodes[root][RANK] = ~nclasses++; - labels[i] = ~nodes[root][RANK]; - } - - return nclasses; -} - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_OPERATIONS_HPP +#define OPENCV_CORE_OPERATIONS_HPP + +#ifndef __cplusplus +# error operations.hpp header must be compiled as C++ +#endif + +#include + +#if defined(__GNUC__) || defined(__clang__) // at least GCC 3.1+, clang 3.5+ +# if defined(__MINGW_PRINTF_FORMAT) // https://sourceforge.net/p/mingw-w64/wiki2/gnu%20printf/. +# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (__MINGW_PRINTF_FORMAT, string_idx, first_to_check))) +# else +# define CV_FORMAT_PRINTF(string_idx, first_to_check) __attribute__ ((format (printf, string_idx, first_to_check))) +# endif +#else +# define CV_FORMAT_PRINTF(A, B) +#endif + +namespace cv +{ +//! @cond IGNORED + + +////////////////////////////// Matx methods depending on core API ///////////////////////////// + +namespace internal +{ + +template struct Matx_FastInvOp +{ + bool operator()(const Matx<_Tp, m, n>& a, Matx<_Tp, n, m>& b, int method) const + { + return invert(a, b, method) != 0; + } +}; + +template struct Matx_FastInvOp<_Tp, m, m> +{ + bool operator()(const Matx<_Tp, m, m>& a, Matx<_Tp, m, m>& b, int method) const + { + if (method == DECOMP_LU || method == DECOMP_CHOLESKY) + { + Matx<_Tp, m, m> temp = a; + + // assume that b is all 0's on input => make it a unity matrix + for (int i = 0; i < m; i++) + b(i, i) = (_Tp)1; + + if (method == DECOMP_CHOLESKY) + return Cholesky(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m); + + return LU(temp.val, m*sizeof(_Tp), m, b.val, m*sizeof(_Tp), m) != 0; + } + else + { + return invert(a, b, method) != 0; + } + } +}; + +template struct Matx_FastInvOp<_Tp, 2, 2> +{ + bool operator()(const Matx<_Tp, 2, 2>& a, Matx<_Tp, 2, 2>& b, int /*method*/) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + b(1,1) = a(0,0)*d; + b(0,0) = a(1,1)*d; + b(0,1) = -a(0,1)*d; + b(1,0) = -a(1,0)*d; + return true; + } +}; + +template struct Matx_FastInvOp<_Tp, 3, 3> +{ + bool operator()(const Matx<_Tp, 3, 3>& a, Matx<_Tp, 3, 3>& b, int /*method*/) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + b(0,0) = (a(1,1) * a(2,2) - a(1,2) * a(2,1)) * d; + b(0,1) = (a(0,2) * a(2,1) - a(0,1) * a(2,2)) * d; + b(0,2) = (a(0,1) * a(1,2) - a(0,2) * a(1,1)) * d; + + b(1,0) = (a(1,2) * a(2,0) - a(1,0) * a(2,2)) * d; + b(1,1) = (a(0,0) * a(2,2) - a(0,2) * a(2,0)) * d; + b(1,2) = (a(0,2) * a(1,0) - a(0,0) * a(1,2)) * d; + + b(2,0) = (a(1,0) * a(2,1) - a(1,1) * a(2,0)) * d; + b(2,1) = (a(0,1) * a(2,0) - a(0,0) * a(2,1)) * d; + b(2,2) = (a(0,0) * a(1,1) - a(0,1) * a(1,0)) * d; + return true; + } +}; + + +template struct Matx_FastSolveOp +{ + bool operator()(const Matx<_Tp, m, l>& a, const Matx<_Tp, m, n>& b, + Matx<_Tp, l, n>& x, int method) const + { + return cv::solve(a, b, x, method); + } +}; + +template struct Matx_FastSolveOp<_Tp, m, m, n> +{ + bool operator()(const Matx<_Tp, m, m>& a, const Matx<_Tp, m, n>& b, + Matx<_Tp, m, n>& x, int method) const + { + if (method == DECOMP_LU || method == DECOMP_CHOLESKY) + { + Matx<_Tp, m, m> temp = a; + x = b; + if( method == DECOMP_CHOLESKY ) + return Cholesky(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n); + + return LU(temp.val, m*sizeof(_Tp), m, x.val, n*sizeof(_Tp), n) != 0; + } + else + { + return cv::solve(a, b, x, method); + } + } +}; + +template struct Matx_FastSolveOp<_Tp, 2, 2, 1> +{ + bool operator()(const Matx<_Tp, 2, 2>& a, const Matx<_Tp, 2, 1>& b, + Matx<_Tp, 2, 1>& x, int) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + x(0) = (b(0)*a(1,1) - b(1)*a(0,1))*d; + x(1) = (b(1)*a(0,0) - b(0)*a(1,0))*d; + return true; + } +}; + +template struct Matx_FastSolveOp<_Tp, 3, 3, 1> +{ + bool operator()(const Matx<_Tp, 3, 3>& a, const Matx<_Tp, 3, 1>& b, + Matx<_Tp, 3, 1>& x, int) const + { + _Tp d = (_Tp)determinant(a); + if (d == 0) + return false; + d = 1/d; + x(0) = d*(b(0)*(a(1,1)*a(2,2) - a(1,2)*a(2,1)) - + a(0,1)*(b(1)*a(2,2) - a(1,2)*b(2)) + + a(0,2)*(b(1)*a(2,1) - a(1,1)*b(2))); + + x(1) = d*(a(0,0)*(b(1)*a(2,2) - a(1,2)*b(2)) - + b(0)*(a(1,0)*a(2,2) - a(1,2)*a(2,0)) + + a(0,2)*(a(1,0)*b(2) - b(1)*a(2,0))); + + x(2) = d*(a(0,0)*(a(1,1)*b(2) - b(1)*a(2,1)) - + a(0,1)*(a(1,0)*b(2) - b(1)*a(2,0)) + + b(0)*(a(1,0)*a(2,1) - a(1,1)*a(2,0))); + return true; + } +}; + +} // internal + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::randu(_Tp a, _Tp b) +{ + Matx<_Tp,m,n> M; + cv::randu(M, Scalar(a), Scalar(b)); + return M; +} + +template inline +Matx<_Tp,m,n> Matx<_Tp,m,n>::randn(_Tp a, _Tp b) +{ + Matx<_Tp,m,n> M; + cv::randn(M, Scalar(a), Scalar(b)); + return M; +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::randu(_Tp a, _Tp b) +{ + Vec<_Tp,cn> V; + cv::randu(V, Scalar(a), Scalar(b)); + return V; +} + +template inline +Vec<_Tp, cn> Vec<_Tp, cn>::randn(_Tp a, _Tp b) +{ + Vec<_Tp,cn> V; + cv::randn(V, Scalar(a), Scalar(b)); + return V; +} + +template inline +Matx<_Tp, n, m> Matx<_Tp, m, n>::inv(int method, bool *p_is_ok /*= NULL*/) const +{ + Matx<_Tp, n, m> b; + bool ok = cv::internal::Matx_FastInvOp<_Tp, m, n>()(*this, b, method); + if (p_is_ok) *p_is_ok = ok; + return ok ? b : Matx<_Tp, n, m>::zeros(); +} + +template template inline +Matx<_Tp, n, l> Matx<_Tp, m, n>::solve(const Matx<_Tp, m, l>& rhs, int method) const +{ + Matx<_Tp, n, l> x; + bool ok = cv::internal::Matx_FastSolveOp<_Tp, m, n, l>()(*this, rhs, x, method); + return ok ? x : Matx<_Tp, n, l>::zeros(); +} + + + +////////////////////////// Augmenting algebraic & logical operations ////////////////////////// + +#define CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + static inline A& operator op (A& a, const B& b) { cvop; return a; } + +#define CV_MAT_AUG_OPERATOR(op, cvop, A, B) \ + CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) + +#define CV_MAT_AUG_OPERATOR_T(op, cvop, A, B) \ + template CV_MAT_AUG_OPERATOR1(op, cvop, A, B) \ + template CV_MAT_AUG_OPERATOR1(op, cvop, const A, B) + +#define CV_MAT_AUG_OPERATOR_TN(op, cvop, A) \ + template static inline A& operator op (A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } \ + template static inline const A& operator op (const A& a, const Matx<_Tp,m,n>& b) { cvop; return a; } + +CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (+=, cv::add(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(+=, cv::add(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(+=, cv::add(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (-=, cv::subtract(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(-=, cv::subtract(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(-=, cv::subtract(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat, Mat) +CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(*=, cv::gemm(a, b, 1, Mat(), 0, a, 0), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR (*=, a.convertTo(a, -1, b), Mat, double) +CV_MAT_AUG_OPERATOR_T(*=, a.convertTo(a, -1, b), Mat_<_Tp>, double) +CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat) +CV_MAT_AUG_OPERATOR_TN(*=, cv::gemm(a, Mat(b), 1, Mat(), 0, a, 0), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (/=, cv::divide(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(/=, cv::divide(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR (/=, a.convertTo((Mat&)a, -1, 1./b), Mat, double) +CV_MAT_AUG_OPERATOR_T(/=, a.convertTo((Mat&)a, -1, 1./b), Mat_<_Tp>, double) +CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(/=, cv::divide(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (&=, cv::bitwise_and(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(&=, cv::bitwise_and(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(&=, cv::bitwise_and(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (|=, cv::bitwise_or(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(|=, cv::bitwise_or(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(|=, cv::bitwise_or(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Mat) +CV_MAT_AUG_OPERATOR (^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat, Scalar) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Scalar) +CV_MAT_AUG_OPERATOR_T(^=, cv::bitwise_xor(a, b, (const Mat&)a), Mat_<_Tp>, Mat_<_Tp>) +CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat) +CV_MAT_AUG_OPERATOR_TN(^=, cv::bitwise_xor(a, Mat(b), (const Mat&)a), Mat_<_Tp>) + +#undef CV_MAT_AUG_OPERATOR_TN +#undef CV_MAT_AUG_OPERATOR_T +#undef CV_MAT_AUG_OPERATOR +#undef CV_MAT_AUG_OPERATOR1 + + + +///////////////////////////////////////////// SVD ///////////////////////////////////////////// + +inline SVD::SVD() {} +inline SVD::SVD( InputArray m, int flags ) { operator ()(m, flags); } +inline void SVD::solveZ( InputArray m, OutputArray _dst ) +{ + Mat mtx = m.getMat(); + SVD svd(mtx, (mtx.rows >= mtx.cols ? 0 : SVD::FULL_UV)); + _dst.create(svd.vt.cols, 1, svd.vt.type()); + Mat dst = _dst.getMat(); + svd.vt.row(svd.vt.rows-1).reshape(1,svd.vt.cols).copyTo(dst); +} + +template inline void + SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w, Matx<_Tp, m, nm>& u, Matx<_Tp, n, nm>& vt ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _a(a, false), _u(u, false), _w(w, false), _vt(vt, false); + SVD::compute(_a, _w, _u, _vt); + CV_Assert(_w.data == (uchar*)&w.val[0] && _u.data == (uchar*)&u.val[0] && _vt.data == (uchar*)&vt.val[0]); +} + +template inline void +SVD::compute( const Matx<_Tp, m, n>& a, Matx<_Tp, nm, 1>& w ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _a(a, false), _w(w, false); + SVD::compute(_a, _w); + CV_Assert(_w.data == (uchar*)&w.val[0]); +} + +template inline void +SVD::backSubst( const Matx<_Tp, nm, 1>& w, const Matx<_Tp, m, nm>& u, + const Matx<_Tp, n, nm>& vt, const Matx<_Tp, m, nb>& rhs, + Matx<_Tp, n, nb>& dst ) +{ + CV_StaticAssert( nm == MIN(m, n), "Invalid size of output vector."); + Mat _u(u, false), _w(w, false), _vt(vt, false), _rhs(rhs, false), _dst(dst, false); + SVD::backSubst(_w, _u, _vt, _rhs, _dst); + CV_Assert(_dst.data == (uchar*)&dst.val[0]); +} + + + +/////////////////////////////////// Multiply-with-Carry RNG /////////////////////////////////// + +inline RNG::RNG() { state = 0xffffffff; } +inline RNG::RNG(uint64 _state) { state = _state ? _state : 0xffffffff; } + +inline RNG::operator uchar() { return (uchar)next(); } +inline RNG::operator schar() { return (schar)next(); } +inline RNG::operator ushort() { return (ushort)next(); } +inline RNG::operator short() { return (short)next(); } +inline RNG::operator int() { return (int)next(); } +inline RNG::operator unsigned() { return next(); } +inline RNG::operator float() { return next()*2.3283064365386962890625e-10f; } +inline RNG::operator double() { unsigned t = next(); return (((uint64)t << 32) | next()) * 5.4210108624275221700372640043497e-20; } + +inline unsigned RNG::operator ()(unsigned N) { return (unsigned)uniform(0,N); } +inline unsigned RNG::operator ()() { return next(); } + +inline int RNG::uniform(int a, int b) { return a == b ? a : (int)(next() % (b - a) + a); } +inline float RNG::uniform(float a, float b) { return ((float)*this)*(b - a) + a; } +inline double RNG::uniform(double a, double b) { return ((double)*this)*(b - a) + a; } + +inline bool RNG::operator ==(const RNG& other) const { return state == other.state; } + +inline unsigned RNG::next() +{ + state = (uint64)(unsigned)state* /*CV_RNG_COEFF*/ 4164903690U + (unsigned)(state >> 32); + return (unsigned)state; +} + +//! returns the next uniformly-distributed random number of the specified type +template static inline _Tp randu() +{ + return (_Tp)theRNG(); +} + + +///////////////////////////////// Formatted output of cv::Mat ///////////////////////////////// + +static inline +Ptr format(InputArray mtx, Formatter::FormatType fmt) +{ + return Formatter::get(fmt)->format(mtx.getMat()); +} + +static inline +int print(Ptr fmtd, FILE* stream = stdout) +{ + int written = 0; + fmtd->reset(); + for(const char* str = fmtd->next(); str; str = fmtd->next()) + written += fputs(str, stream); + + return written; +} + +static inline +int print(const Mat& mtx, FILE* stream = stdout) +{ + return print(Formatter::get()->format(mtx), stream); +} + +static inline +int print(const UMat& mtx, FILE* stream = stdout) +{ + return print(Formatter::get()->format(mtx.getMat(ACCESS_READ)), stream); +} + +template static inline +int print(const std::vector >& vec, FILE* stream = stdout) +{ + return print(Formatter::get()->format(Mat(vec)), stream); +} + +template static inline +int print(const std::vector >& vec, FILE* stream = stdout) +{ + return print(Formatter::get()->format(Mat(vec)), stream); +} + +template static inline +int print(const Matx<_Tp, m, n>& matx, FILE* stream = stdout) +{ + return print(Formatter::get()->format(cv::Mat(matx)), stream); +} + +//! @endcond + +///////////////////////////////// Formatted string generation ///////////////////////////////// + +/** @brief Returns a text string formatted using the printf-like expression. + +The function acts like sprintf but forms and returns an STL string. It can be used to form an error +message in the Exception constructor. +@param fmt printf-compatible formatting specifiers. + +**Note**: +|Type|Specifier| +|-|-| +|`const char*`|`%s`| +|`char`|`%c`| +|`float` / `double`|`%f`,`%g`| +|`int`, `long`, `long long`|`%d`, `%ld`, ``%lld`| +|`unsigned`, `unsigned long`, `unsigned long long`|`%u`, `%lu`, `%llu`| +|`uint64` -> `uintmax_t`, `int64` -> `intmax_t`|`%ju`, `%jd`| +|`size_t`|`%zu`| +@ingroup core_utils + */ +CV_EXPORTS String format(const char* fmt, ...) CV_FORMAT_PRINTF(1, 2); + +/****************************************************************************************\ +* Auxiliary algorithms * +\****************************************************************************************/ + +/** @brief Splits an element set into equivalency classes. + +The generic function partition implements an \f$O(N^2)\f$ algorithm for splitting a set of \f$N\f$ elements +into one or more equivalency classes, as described in + . The function returns the number of +equivalency classes. +@param vec Set of elements stored as a vector. +@param labels Output vector of labels. It contains as many elements as vec. Each label labels[i] is +a 0-based cluster index of `vec[i]`. +@param predicate Equivalence predicate (pointer to a boolean function of two arguments or an +instance of the class that has the method bool operator()(const _Tp& a, const _Tp& b) ). The +predicate returns true when the elements are certainly in the same class, and returns false if they +may or may not be in the same class. +@ingroup core_cluster +*/ +template int +partition( const std::vector<_Tp>& vec, std::vector& labels, + _EqPredicate predicate=_EqPredicate()) +{ + int i, j, N = (int)vec.size(); + const _Tp* _vec = &vec[0]; + + const int PARENT=0; + const int RANK=1; + + std::vector _nodes(N*2); + int (*nodes)[2] = (int(*)[2])&_nodes[0]; + + // The first O(N) pass: create N single-vertex trees + for(i = 0; i < N; i++) + { + nodes[i][PARENT]=-1; + nodes[i][RANK] = 0; + } + + // The main O(N^2) pass: merge connected components + for( i = 0; i < N; i++ ) + { + int root = i; + + // find root + while( nodes[root][PARENT] >= 0 ) + root = nodes[root][PARENT]; + + for( j = 0; j < N; j++ ) + { + if( i == j || !predicate(_vec[i], _vec[j])) + continue; + int root2 = j; + + while( nodes[root2][PARENT] >= 0 ) + root2 = nodes[root2][PARENT]; + + if( root2 != root ) + { + // unite both trees + int rank = nodes[root][RANK], rank2 = nodes[root2][RANK]; + if( rank > rank2 ) + nodes[root2][PARENT] = root; + else + { + nodes[root][PARENT] = root2; + nodes[root2][RANK] += rank == rank2; + root = root2; + } + CV_Assert( nodes[root][PARENT] < 0 ); + + int k = j, parent; + + // compress the path from node2 to root + while( (parent = nodes[k][PARENT]) >= 0 ) + { + nodes[k][PARENT] = root; + k = parent; + } + + // compress the path from node to root + k = i; + while( (parent = nodes[k][PARENT]) >= 0 ) + { + nodes[k][PARENT] = root; + k = parent; + } + } + } + } + + // Final O(N) pass: enumerate classes + labels.resize(N); + int nclasses = 0; + + for( i = 0; i < N; i++ ) + { + int root = i; + while( nodes[root][PARENT] >= 0 ) + root = nodes[root][PARENT]; + // re-use the rank as the class label + if( nodes[root][RANK] >= 0 ) + nodes[root][RANK] = ~nclasses++; + labels[i] = ~nodes[root][RANK]; + } + + return nclasses; +} + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp b/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp index 6dfb59e81e..59fe978c26 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/optim.hpp @@ -1,307 +1,307 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the OpenCV Foundation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_OPTIM_HPP -#define OPENCV_OPTIM_HPP - -#include "opencv2/core.hpp" - -namespace cv -{ - -/** @addtogroup core_optim -The algorithms in this section minimize or maximize function value within specified constraints or -without any constraints. -@{ -*/ - -/** @brief Basic interface for all solvers - */ -class CV_EXPORTS MinProblemSolver : public Algorithm -{ -public: - /** @brief Represents function being optimized - */ - class CV_EXPORTS Function - { - public: - virtual ~Function() {} - virtual int getDims() const = 0; - virtual double getGradientEps() const; - virtual double calc(const double* x) const = 0; - virtual void getGradient(const double* x,double* grad); - }; - - /** @brief Getter for the optimized function. - - The optimized function is represented by Function interface, which requires derivatives to - implement the calc(double*) and getDim() methods to evaluate the function. - - @return Smart-pointer to an object that implements Function interface - it represents the - function that is being optimized. It can be empty, if no function was given so far. - */ - virtual Ptr getFunction() const = 0; - - /** @brief Setter for the optimized function. - - *It should be called at least once before the call to* minimize(), as default value is not usable. - - @param f The new function to optimize. - */ - virtual void setFunction(const Ptr& f) = 0; - - /** @brief Getter for the previously set terminal criteria for this algorithm. - - @return Deep copy of the terminal criteria used at the moment. - */ - virtual TermCriteria getTermCriteria() const = 0; - - /** @brief Set terminal criteria for solver. - - This method *is not necessary* to be called before the first call to minimize(), as the default - value is sensible. - - Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when - the function values at the vertices of simplex are within termcrit.epsilon range or simplex - becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes - first. - @param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure. - */ - virtual void setTermCriteria(const TermCriteria& termcrit) = 0; - - /** @brief actually runs the algorithm and performs the minimization. - - The sole input parameter determines the centroid of the starting simplex (roughly, it tells - where to start), all the others (terminal criteria, initial step, function to be minimized) are - supposed to be set via the setters before the call to this method or the default values (not - always sensible) will be used. - - @param x The initial point, that will become a centroid of an initial simplex. After the algorithm - will terminate, it will be set to the point where the algorithm stops, the point of possible - minimum. - @return The value of a function at the point found. - */ - virtual double minimize(InputOutputArray x) = 0; -}; - -/** @brief This class is used to perform the non-linear non-constrained minimization of a function, - -defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as -**downhill simplex method**. The basic idea about the method can be obtained from -. - -It should be noted, that this method, although deterministic, is rather a heuristic and therefore -may converge to a local minima, not necessary a global one. It is iterative optimization technique, -which at each step uses an information about the values of a function evaluated only at `n+1` -points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At -each step new point is chosen to evaluate function at, obtained value is compared with previous -ones and based on this information simplex changes it's shape , slowly moving to the local minimum. -Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear -Conjugate Gradient method (which is also implemented in optim). - -Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the -function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so -small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some -defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon. - -@note DownhillSolver is a derivative of the abstract interface -cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to -encapsulate the functionality, common to all non-linear optimization algorithms in the optim -module. - -@note term criteria should meet following condition: -@code - termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 -@endcode - */ -class CV_EXPORTS DownhillSolver : public MinProblemSolver -{ -public: - /** @brief Returns the initial step that will be used in downhill simplex algorithm. - - @param step Initial step that will be used in algorithm. Note, that although corresponding setter - accepts column-vectors as well as row-vectors, this method will return a row-vector. - @see DownhillSolver::setInitStep - */ - virtual void getInitStep(OutputArray step) const=0; - - /** @brief Sets the initial step that will be used in downhill simplex algorithm. - - Step, together with initial point (given in DownhillSolver::minimize) are two `n`-dimensional - vectors that are used to determine the shape of initial simplex. Roughly said, initial point - determines the position of a simplex (it will become simplex's centroid), while step determines the - spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are - the initial step and initial point respectively, the vertices of a simplex will be: - \f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes - projections of the initial step of *n*-th coordinate (the result of projection is treated to be - vector given by \f$s_i:=e_i\cdot\left\f$, where \f$e_i\f$ form canonical basis) - - @param step Initial step that will be used in algorithm. Roughly said, it determines the spread - (size in each dimension) of an initial simplex. - */ - virtual void setInitStep(InputArray step)=0; - - /** @brief This function returns the reference to the ready-to-use DownhillSolver object. - - All the parameters are optional, so this procedure can be called even without parameters at - all. In this case, the default values will be used. As default value for terminal criteria are - the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep() - should be called upon the obtained object, if the respective parameters were not given to - create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out - and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely - equivalent (and will drop the same errors in the same way, should invalid input be detected). - @param f Pointer to the function that will be minimized, similarly to the one you submit via - MinProblemSolver::setFunction. - @param initStep Initial step, that will be used to construct the initial simplex, similarly to the one - you submit via MinProblemSolver::setInitStep. - @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via - MinProblemSolver::setTermCriteria. - */ - static Ptr create(const Ptr& f=Ptr(), - InputArray initStep=Mat_(1,1,0.0), - TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); -}; - -/** @brief This class is used to perform the non-linear non-constrained minimization of a function -with known gradient, - -defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**. -The implementation was done based on the beautifully clear explanatory article [An Introduction to -the Conjugate Gradient Method Without the Agonizing -Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard -Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for -example ) for numerically solving the -systems of linear equations. - -It should be noted, that this method, although deterministic, is rather a heuristic method and -therefore may converge to a local minima, not necessary a global one. What is even more disastrous, -most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between -local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may -converge to it. Another obvious restriction is that it should be possible to compute the gradient of -a function at any point, thus it is preferable to have analytic expression for gradient and -computational burden should be born by the user. - -The latter responsibility is accomplished via the getGradient method of a -MinProblemSolver::Function interface (which represents function being optimized). This method takes -point a point in *n*-dimensional space (first argument represents the array of coordinates of that -point) and compute its gradient (it should be stored in the second argument as an array). - -@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface. - -@note term criteria should meet following condition: -@code - termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 - // or - termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0 -@endcode - */ -class CV_EXPORTS ConjGradSolver : public MinProblemSolver -{ -public: - /** @brief This function returns the reference to the ready-to-use ConjGradSolver object. - - All the parameters are optional, so this procedure can be called even without parameters at - all. In this case, the default values will be used. As default value for terminal criteria are - the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained - object, if the function was not given to create(). Otherwise, the two ways (submit it to - create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent - (and will drop the same errors in the same way, should invalid input be detected). - @param f Pointer to the function that will be minimized, similarly to the one you submit via - MinProblemSolver::setFunction. - @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via - MinProblemSolver::setTermCriteria. - */ - static Ptr create(const Ptr& f=Ptr(), - TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); -}; - -//! return codes for cv::solveLP() function -enum SolveLPResult -{ - SOLVELP_LOST = -3, //!< problem is feasible, but solver lost solution due to floating-point arithmetic errors - SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values) - SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed) - SOLVELP_SINGLE = 0, //!< there is only one maximum for target function - SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned -}; - -/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). - -What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as: - -\f[\mbox{Maximize } c\cdot x\\ - \mbox{Subject to:}\\ - Ax\leq b\\ - x\geq 0\f] - -Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1` -column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints. - -Simplex algorithm is one of many algorithms that are designed to handle this sort of problems -efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve -any problem written as above in polynomial time, while simplex method degenerates to exponential -time for some special cases), it is well-studied, easy to implement and is shown to work well for -real-life purposes. - -The particular implementation is taken almost verbatim from **Introduction to Algorithms, third -edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the -Bland's rule is used to prevent cycling. - -@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should -contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, -in the latter case it is understood to correspond to \f$c^T\f$. -@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above -and the remaining to \f$A\f$. It should contain 32- or 64-bit floating point numbers. -@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the -formulation above. It will contain 64-bit floating point numbers. -@param constr_eps allowed numeric disparity for constraints -@return One of cv::SolveLPResult - */ -CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z, double constr_eps); - -/** @overload */ -CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z); - -//! @} - -}// cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the OpenCV Foundation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_OPTIM_HPP +#define OPENCV_OPTIM_HPP + +#include "opencv2/core.hpp" + +namespace cv +{ + +/** @addtogroup core_optim +The algorithms in this section minimize or maximize function value within specified constraints or +without any constraints. +@{ +*/ + +/** @brief Basic interface for all solvers + */ +class CV_EXPORTS MinProblemSolver : public Algorithm +{ +public: + /** @brief Represents function being optimized + */ + class CV_EXPORTS Function + { + public: + virtual ~Function() {} + virtual int getDims() const = 0; + virtual double getGradientEps() const; + virtual double calc(const double* x) const = 0; + virtual void getGradient(const double* x,double* grad); + }; + + /** @brief Getter for the optimized function. + + The optimized function is represented by Function interface, which requires derivatives to + implement the calc(double*) and getDim() methods to evaluate the function. + + @return Smart-pointer to an object that implements Function interface - it represents the + function that is being optimized. It can be empty, if no function was given so far. + */ + virtual Ptr getFunction() const = 0; + + /** @brief Setter for the optimized function. + + *It should be called at least once before the call to* minimize(), as default value is not usable. + + @param f The new function to optimize. + */ + virtual void setFunction(const Ptr& f) = 0; + + /** @brief Getter for the previously set terminal criteria for this algorithm. + + @return Deep copy of the terminal criteria used at the moment. + */ + virtual TermCriteria getTermCriteria() const = 0; + + /** @brief Set terminal criteria for solver. + + This method *is not necessary* to be called before the first call to minimize(), as the default + value is sensible. + + Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when + the function values at the vertices of simplex are within termcrit.epsilon range or simplex + becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes + first. + @param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure. + */ + virtual void setTermCriteria(const TermCriteria& termcrit) = 0; + + /** @brief actually runs the algorithm and performs the minimization. + + The sole input parameter determines the centroid of the starting simplex (roughly, it tells + where to start), all the others (terminal criteria, initial step, function to be minimized) are + supposed to be set via the setters before the call to this method or the default values (not + always sensible) will be used. + + @param x The initial point, that will become a centroid of an initial simplex. After the algorithm + will terminate, it will be set to the point where the algorithm stops, the point of possible + minimum. + @return The value of a function at the point found. + */ + virtual double minimize(InputOutputArray x) = 0; +}; + +/** @brief This class is used to perform the non-linear non-constrained minimization of a function, + +defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as +**downhill simplex method**. The basic idea about the method can be obtained from +. + +It should be noted, that this method, although deterministic, is rather a heuristic and therefore +may converge to a local minima, not necessary a global one. It is iterative optimization technique, +which at each step uses an information about the values of a function evaluated only at `n+1` +points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At +each step new point is chosen to evaluate function at, obtained value is compared with previous +ones and based on this information simplex changes it's shape , slowly moving to the local minimum. +Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear +Conjugate Gradient method (which is also implemented in optim). + +Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the +function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so +small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some +defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon. + +@note DownhillSolver is a derivative of the abstract interface +cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to +encapsulate the functionality, common to all non-linear optimization algorithms in the optim +module. + +@note term criteria should meet following condition: +@code + termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 +@endcode + */ +class CV_EXPORTS DownhillSolver : public MinProblemSolver +{ +public: + /** @brief Returns the initial step that will be used in downhill simplex algorithm. + + @param step Initial step that will be used in algorithm. Note, that although corresponding setter + accepts column-vectors as well as row-vectors, this method will return a row-vector. + @see DownhillSolver::setInitStep + */ + virtual void getInitStep(OutputArray step) const=0; + + /** @brief Sets the initial step that will be used in downhill simplex algorithm. + + Step, together with initial point (given in DownhillSolver::minimize) are two `n`-dimensional + vectors that are used to determine the shape of initial simplex. Roughly said, initial point + determines the position of a simplex (it will become simplex's centroid), while step determines the + spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are + the initial step and initial point respectively, the vertices of a simplex will be: + \f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes + projections of the initial step of *n*-th coordinate (the result of projection is treated to be + vector given by \f$s_i:=e_i\cdot\left\f$, where \f$e_i\f$ form canonical basis) + + @param step Initial step that will be used in algorithm. Roughly said, it determines the spread + (size in each dimension) of an initial simplex. + */ + virtual void setInitStep(InputArray step)=0; + + /** @brief This function returns the reference to the ready-to-use DownhillSolver object. + + All the parameters are optional, so this procedure can be called even without parameters at + all. In this case, the default values will be used. As default value for terminal criteria are + the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep() + should be called upon the obtained object, if the respective parameters were not given to + create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out + and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely + equivalent (and will drop the same errors in the same way, should invalid input be detected). + @param f Pointer to the function that will be minimized, similarly to the one you submit via + MinProblemSolver::setFunction. + @param initStep Initial step, that will be used to construct the initial simplex, similarly to the one + you submit via MinProblemSolver::setInitStep. + @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via + MinProblemSolver::setTermCriteria. + */ + static Ptr create(const Ptr& f=Ptr(), + InputArray initStep=Mat_(1,1,0.0), + TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); +}; + +/** @brief This class is used to perform the non-linear non-constrained minimization of a function +with known gradient, + +defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**. +The implementation was done based on the beautifully clear explanatory article [An Introduction to +the Conjugate Gradient Method Without the Agonizing +Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard +Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for +example ) for numerically solving the +systems of linear equations. + +It should be noted, that this method, although deterministic, is rather a heuristic method and +therefore may converge to a local minima, not necessary a global one. What is even more disastrous, +most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between +local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may +converge to it. Another obvious restriction is that it should be possible to compute the gradient of +a function at any point, thus it is preferable to have analytic expression for gradient and +computational burden should be born by the user. + +The latter responsibility is accomplished via the getGradient method of a +MinProblemSolver::Function interface (which represents function being optimized). This method takes +point a point in *n*-dimensional space (first argument represents the array of coordinates of that +point) and compute its gradient (it should be stored in the second argument as an array). + +@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface. + +@note term criteria should meet following condition: +@code + termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0 + // or + termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0 +@endcode + */ +class CV_EXPORTS ConjGradSolver : public MinProblemSolver +{ +public: + /** @brief This function returns the reference to the ready-to-use ConjGradSolver object. + + All the parameters are optional, so this procedure can be called even without parameters at + all. In this case, the default values will be used. As default value for terminal criteria are + the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained + object, if the function was not given to create(). Otherwise, the two ways (submit it to + create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent + (and will drop the same errors in the same way, should invalid input be detected). + @param f Pointer to the function that will be minimized, similarly to the one you submit via + MinProblemSolver::setFunction. + @param termcrit Terminal criteria to the algorithm, similarly to the one you submit via + MinProblemSolver::setTermCriteria. + */ + static Ptr create(const Ptr& f=Ptr(), + TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001)); +}; + +//! return codes for cv::solveLP() function +enum SolveLPResult +{ + SOLVELP_LOST = -3, //!< problem is feasible, but solver lost solution due to floating-point arithmetic errors + SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values) + SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed) + SOLVELP_SINGLE = 0, //!< there is only one maximum for target function + SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned +}; + +/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method). + +What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as: + +\f[\mbox{Maximize } c\cdot x\\ + \mbox{Subject to:}\\ + Ax\leq b\\ + x\geq 0\f] + +Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1` +column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints. + +Simplex algorithm is one of many algorithms that are designed to handle this sort of problems +efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve +any problem written as above in polynomial time, while simplex method degenerates to exponential +time for some special cases), it is well-studied, easy to implement and is shown to work well for +real-life purposes. + +The particular implementation is taken almost verbatim from **Introduction to Algorithms, third +edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the +Bland's rule is used to prevent cycling. + +@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should +contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted, +in the latter case it is understood to correspond to \f$c^T\f$. +@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above +and the remaining to \f$A\f$. It should contain 32- or 64-bit floating point numbers. +@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the +formulation above. It will contain 64-bit floating point numbers. +@param constr_eps allowed numeric disparity for constraints +@return One of cv::SolveLPResult + */ +CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z, double constr_eps); + +/** @overload */ +CV_EXPORTS_W int solveLP(InputArray Func, InputArray Constr, OutputArray z); + +//! @} + +}// cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp b/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp index ba7a59ed53..8bb7d54911 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/ovx.hpp @@ -1,28 +1,28 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// Copyright (C) 2016, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. - -// OpenVX related definitions and declarations - -#pragma once -#ifndef OPENCV_OVX_HPP -#define OPENCV_OVX_HPP - -#include "cvdef.h" - -namespace cv -{ -/// Check if use of OpenVX is possible -CV_EXPORTS_W bool haveOpenVX(); - -/// Check if use of OpenVX is enabled -CV_EXPORTS_W bool useOpenVX(); - -/// Enable/disable use of OpenVX -CV_EXPORTS_W void setUseOpenVX(bool flag); -} // namespace cv - -#endif // OPENCV_OVX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// Copyright (C) 2016, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. + +// OpenVX related definitions and declarations + +#pragma once +#ifndef OPENCV_OVX_HPP +#define OPENCV_OVX_HPP + +#include "cvdef.h" + +namespace cv +{ +/// Check if use of OpenVX is possible +CV_EXPORTS_W bool haveOpenVX(); + +/// Check if use of OpenVX is enabled +CV_EXPORTS_W bool useOpenVX(); + +/// Enable/disable use of OpenVX +CV_EXPORTS_W void setUseOpenVX(bool flag); +} // namespace cv + +#endif // OPENCV_OVX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp index 95667e8bd6..b172cac34d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.openmp.hpp @@ -1,72 +1,72 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP -#define OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP - -#include "opencv2/core/parallel/parallel_backend.hpp" - -#if !defined(_OPENMP) && !defined(OPENCV_SKIP_OPENMP_PRESENSE_CHECK) -#error "This file must be compiled with enabled OpenMP" -#endif - -#include - -namespace cv { namespace parallel { namespace openmp { - -/** OpenMP parallel_for API implementation - * - * @sa setParallelForBackend - * @ingroup core_parallel_backend - */ -class ParallelForBackend : public ParallelForAPI -{ -protected: - int numThreads; - int numThreadsMax; -public: - ParallelForBackend() - { - numThreads = 0; - numThreadsMax = omp_get_max_threads(); - } - - virtual ~ParallelForBackend() {} - - virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE - { -#pragma omp parallel for schedule(dynamic) num_threads(numThreads > 0 ? numThreads : numThreadsMax) - for (int i = 0; i < tasks; ++i) - body_callback(i, i + 1, callback_data); - } - - virtual int getThreadNum() const CV_OVERRIDE - { - return omp_get_thread_num(); - } - - virtual int getNumThreads() const CV_OVERRIDE - { - return numThreads > 0 - ? numThreads - : numThreadsMax; - } - - virtual int setNumThreads(int nThreads) CV_OVERRIDE - { - int oldNumThreads = numThreads; - numThreads = nThreads; - // nothing needed as numThreads is used in #pragma omp parallel for directly - return oldNumThreads; - } - - const char* getName() const CV_OVERRIDE - { - return "openmp"; - } -}; - -}}} // namespace - -#endif // OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP +#define OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP + +#include "opencv2/core/parallel/parallel_backend.hpp" + +#if !defined(_OPENMP) && !defined(OPENCV_SKIP_OPENMP_PRESENSE_CHECK) +#error "This file must be compiled with enabled OpenMP" +#endif + +#include + +namespace cv { namespace parallel { namespace openmp { + +/** OpenMP parallel_for API implementation + * + * @sa setParallelForBackend + * @ingroup core_parallel_backend + */ +class ParallelForBackend : public ParallelForAPI +{ +protected: + int numThreads; + int numThreadsMax; +public: + ParallelForBackend() + { + numThreads = 0; + numThreadsMax = omp_get_max_threads(); + } + + virtual ~ParallelForBackend() {} + + virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE + { +#pragma omp parallel for schedule(dynamic) num_threads(numThreads > 0 ? numThreads : numThreadsMax) + for (int i = 0; i < tasks; ++i) + body_callback(i, i + 1, callback_data); + } + + virtual int getThreadNum() const CV_OVERRIDE + { + return omp_get_thread_num(); + } + + virtual int getNumThreads() const CV_OVERRIDE + { + return numThreads > 0 + ? numThreads + : numThreadsMax; + } + + virtual int setNumThreads(int nThreads) CV_OVERRIDE + { + int oldNumThreads = numThreads; + numThreads = nThreads; + // nothing needed as numThreads is used in #pragma omp parallel for directly + return oldNumThreads; + } + + const char* getName() const CV_OVERRIDE + { + return "openmp"; + } +}; + +}}} // namespace + +#endif // OPENCV_CORE_PARALLEL_FOR_OPENMP_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp index 8dce454649..04b0c4c6cb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/parallel/backend/parallel_for.tbb.hpp @@ -1,153 +1,153 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_PARALLEL_FOR_TBB_HPP -#define OPENCV_CORE_PARALLEL_FOR_TBB_HPP - -#include "opencv2/core/parallel/parallel_backend.hpp" -#include - -#ifndef TBB_SUPPRESS_DEPRECATED_MESSAGES // supress warning -#define TBB_SUPPRESS_DEPRECATED_MESSAGES 1 -#endif -#include "tbb/tbb.h" -#if !defined(TBB_INTERFACE_VERSION) -#error "Unknows/unsupported TBB version" -#endif - -#if TBB_INTERFACE_VERSION >= 8000 -#include "tbb/task_arena.h" -#endif - -namespace cv { namespace parallel { namespace tbb { - -using namespace ::tbb; - -#if TBB_INTERFACE_VERSION >= 8000 -static tbb::task_arena& getArena() -{ - static tbb::task_arena tbbArena(tbb::task_arena::automatic); - return tbbArena; -} -#else -static tbb::task_scheduler_init& getScheduler() -{ - static tbb::task_scheduler_init tbbScheduler(tbb::task_scheduler_init::deferred); - return tbbScheduler; -} -#endif - -/** TBB parallel_for API implementation - * - * @sa setParallelForBackend - * @ingroup core_parallel_backend - */ -class ParallelForBackend : public ParallelForAPI -{ -protected: - int numThreads; - int numThreadsMax; -public: - ParallelForBackend() - { - CV_LOG_INFO(NULL, "Initializing TBB parallel backend: TBB_INTERFACE_VERSION=" << TBB_INTERFACE_VERSION); - numThreads = 0; -#if TBB_INTERFACE_VERSION >= 8000 - (void)getArena(); -#else - (void)getScheduler(); -#endif - } - - virtual ~ParallelForBackend() {} - - class CallbackProxy - { - const FN_parallel_for_body_cb_t& callback; - void* const callback_data; - const int tasks; - public: - inline CallbackProxy(int tasks_, FN_parallel_for_body_cb_t& callback_, void* callback_data_) - : callback(callback_), callback_data(callback_data_), tasks(tasks_) - { - // nothing - } - - void operator()(const tbb::blocked_range& range) const - { - this->callback(range.begin(), range.end(), callback_data); - } - - void operator()() const - { - tbb::parallel_for(tbb::blocked_range(0, tasks), *this); - } - }; - - virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE - { - CallbackProxy task(tasks, body_callback, callback_data); -#if TBB_INTERFACE_VERSION >= 8000 - getArena().execute(task); -#else - task(); -#endif - } - - virtual int getThreadNum() const CV_OVERRIDE - { -#if TBB_INTERFACE_VERSION >= 9100 - return tbb::this_task_arena::current_thread_index(); -#elif TBB_INTERFACE_VERSION >= 8000 - return tbb::task_arena::current_thread_index(); -#else - return 0; -#endif - } - - virtual int getNumThreads() const CV_OVERRIDE - { -#if TBB_INTERFACE_VERSION >= 9100 - return getArena().max_concurrency(); -#elif TBB_INTERFACE_VERSION >= 8000 - return numThreads > 0 - ? numThreads - : tbb::task_scheduler_init::default_num_threads(); -#else - return getScheduler().is_active() - ? numThreads - : tbb::task_scheduler_init::default_num_threads(); -#endif - } - - virtual int setNumThreads(int nThreads) CV_OVERRIDE - { - int oldNumThreads = numThreads; - numThreads = nThreads; - -#if TBB_INTERFACE_VERSION >= 8000 - auto& tbbArena = getArena(); - if (tbbArena.is_active()) - tbbArena.terminate(); - if (numThreads > 0) - tbbArena.initialize(numThreads); -#else - auto& tbbScheduler = getScheduler(); - if (tbbScheduler.is_active()) - tbbScheduler.terminate(); - if (numThreads > 0) - tbbScheduler.initialize(numThreads); -#endif - return oldNumThreads; - } - - const char* getName() const CV_OVERRIDE - { - return "tbb"; - } -}; - -}}} // namespace - -#endif // OPENCV_CORE_PARALLEL_FOR_TBB_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_PARALLEL_FOR_TBB_HPP +#define OPENCV_CORE_PARALLEL_FOR_TBB_HPP + +#include "opencv2/core/parallel/parallel_backend.hpp" +#include + +#ifndef TBB_SUPPRESS_DEPRECATED_MESSAGES // supress warning +#define TBB_SUPPRESS_DEPRECATED_MESSAGES 1 +#endif +#include "tbb/tbb.h" +#if !defined(TBB_INTERFACE_VERSION) +#error "Unknows/unsupported TBB version" +#endif + +#if TBB_INTERFACE_VERSION >= 8000 +#include "tbb/task_arena.h" +#endif + +namespace cv { namespace parallel { namespace tbb { + +using namespace ::tbb; + +#if TBB_INTERFACE_VERSION >= 8000 +static tbb::task_arena& getArena() +{ + static tbb::task_arena tbbArena(tbb::task_arena::automatic); + return tbbArena; +} +#else +static tbb::task_scheduler_init& getScheduler() +{ + static tbb::task_scheduler_init tbbScheduler(tbb::task_scheduler_init::deferred); + return tbbScheduler; +} +#endif + +/** TBB parallel_for API implementation + * + * @sa setParallelForBackend + * @ingroup core_parallel_backend + */ +class ParallelForBackend : public ParallelForAPI +{ +protected: + int numThreads; + int numThreadsMax; +public: + ParallelForBackend() + { + CV_LOG_INFO(NULL, "Initializing TBB parallel backend: TBB_INTERFACE_VERSION=" << TBB_INTERFACE_VERSION); + numThreads = 0; +#if TBB_INTERFACE_VERSION >= 8000 + (void)getArena(); +#else + (void)getScheduler(); +#endif + } + + virtual ~ParallelForBackend() {} + + class CallbackProxy + { + const FN_parallel_for_body_cb_t& callback; + void* const callback_data; + const int tasks; + public: + inline CallbackProxy(int tasks_, FN_parallel_for_body_cb_t& callback_, void* callback_data_) + : callback(callback_), callback_data(callback_data_), tasks(tasks_) + { + // nothing + } + + void operator()(const tbb::blocked_range& range) const + { + this->callback(range.begin(), range.end(), callback_data); + } + + void operator()() const + { + tbb::parallel_for(tbb::blocked_range(0, tasks), *this); + } + }; + + virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) CV_OVERRIDE + { + CallbackProxy task(tasks, body_callback, callback_data); +#if TBB_INTERFACE_VERSION >= 8000 + getArena().execute(task); +#else + task(); +#endif + } + + virtual int getThreadNum() const CV_OVERRIDE + { +#if TBB_INTERFACE_VERSION >= 9100 + return tbb::this_task_arena::current_thread_index(); +#elif TBB_INTERFACE_VERSION >= 8000 + return tbb::task_arena::current_thread_index(); +#else + return 0; +#endif + } + + virtual int getNumThreads() const CV_OVERRIDE + { +#if TBB_INTERFACE_VERSION >= 9100 + return getArena().max_concurrency(); +#elif TBB_INTERFACE_VERSION >= 8000 + return numThreads > 0 + ? numThreads + : tbb::task_scheduler_init::default_num_threads(); +#else + return getScheduler().is_active() + ? numThreads + : tbb::task_scheduler_init::default_num_threads(); +#endif + } + + virtual int setNumThreads(int nThreads) CV_OVERRIDE + { + int oldNumThreads = numThreads; + numThreads = nThreads; + +#if TBB_INTERFACE_VERSION >= 8000 + auto& tbbArena = getArena(); + if (tbbArena.is_active()) + tbbArena.terminate(); + if (numThreads > 0) + tbbArena.initialize(numThreads); +#else + auto& tbbScheduler = getScheduler(); + if (tbbScheduler.is_active()) + tbbScheduler.terminate(); + if (numThreads > 0) + tbbScheduler.initialize(numThreads); +#endif + return oldNumThreads; + } + + const char* getName() const CV_OVERRIDE + { + return "tbb"; + } +}; + +}}} // namespace + +#endif // OPENCV_CORE_PARALLEL_FOR_TBB_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp b/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp index 37501e1eed..c3e8333c1c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/parallel/parallel_backend.hpp @@ -1,90 +1,90 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_PARALLEL_BACKEND_HPP -#define OPENCV_CORE_PARALLEL_BACKEND_HPP - -#include "opencv2/core/cvdef.h" -#include - -namespace cv { namespace parallel { -#ifndef CV_API_CALL -#define CV_API_CALL -#endif - -/** @addtogroup core_parallel_backend - * @{ - * API below is provided to resolve problem of CPU resource over-subscription by multiple thread pools from different multi-threading frameworks. - * This is common problem for cases when OpenCV compiled threading framework is different from the Users Applications framework. - * - * Applications can replace OpenCV `parallel_for()` backend with own implementation (to reuse Application's thread pool). - * - * - * ### Backend API usage examples - * - * #### Intel TBB - * - * - include header with simple implementation of TBB backend: - * @snippet parallel_backend/example-tbb.cpp tbb_include - * - execute backend replacement code: - * @snippet parallel_backend/example-tbb.cpp tbb_backend - * - configuration of compiler/linker options is responsibility of Application's scripts - * - * #### OpenMP - * - * - include header with simple implementation of OpenMP backend: - * @snippet parallel_backend/example-openmp.cpp openmp_include - * - execute backend replacement code: - * @snippet parallel_backend/example-openmp.cpp openmp_backend - * - Configuration of compiler/linker options is responsibility of Application's scripts - * - * - * ### Plugins support - * - * Runtime configuration options: - * - change backend priority: `OPENCV_PARALLEL_PRIORITY_=9999` - * - disable backend: `OPENCV_PARALLEL_PRIORITY_=0` - * - specify list of backends with high priority (>100000): `OPENCV_PARALLEL_PRIORITY_LIST=TBB,OPENMP`. Unknown backends are registered as new plugins. - * - */ - -/** Interface for parallel_for backends implementations - * - * @sa setParallelForBackend - */ -class CV_EXPORTS ParallelForAPI -{ -public: - virtual ~ParallelForAPI(); - - typedef void (CV_API_CALL *FN_parallel_for_body_cb_t)(int start, int end, void* data); - - virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) = 0; - - virtual int getThreadNum() const = 0; - - virtual int getNumThreads() const = 0; - - virtual int setNumThreads(int nThreads) = 0; - - virtual const char* getName() const = 0; -}; - -/** @brief Replace OpenCV parallel_for backend - * - * Application can replace OpenCV `parallel_for()` backend with own implementation. - * - * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). - */ -CV_EXPORTS void setParallelForBackend(const std::shared_ptr& api, bool propagateNumThreads = true); - -/** @brief Change OpenCV parallel_for backend - * - * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). - */ -CV_EXPORTS_W bool setParallelForBackend(const std::string& backendName, bool propagateNumThreads = true); - -//! @} -}} // namespace -#endif // OPENCV_CORE_PARALLEL_BACKEND_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_PARALLEL_BACKEND_HPP +#define OPENCV_CORE_PARALLEL_BACKEND_HPP + +#include "opencv2/core/cvdef.h" +#include + +namespace cv { namespace parallel { +#ifndef CV_API_CALL +#define CV_API_CALL +#endif + +/** @addtogroup core_parallel_backend + * @{ + * API below is provided to resolve problem of CPU resource over-subscription by multiple thread pools from different multi-threading frameworks. + * This is common problem for cases when OpenCV compiled threading framework is different from the Users Applications framework. + * + * Applications can replace OpenCV `parallel_for()` backend with own implementation (to reuse Application's thread pool). + * + * + * ### Backend API usage examples + * + * #### Intel TBB + * + * - include header with simple implementation of TBB backend: + * @snippet parallel_backend/example-tbb.cpp tbb_include + * - execute backend replacement code: + * @snippet parallel_backend/example-tbb.cpp tbb_backend + * - configuration of compiler/linker options is responsibility of Application's scripts + * + * #### OpenMP + * + * - include header with simple implementation of OpenMP backend: + * @snippet parallel_backend/example-openmp.cpp openmp_include + * - execute backend replacement code: + * @snippet parallel_backend/example-openmp.cpp openmp_backend + * - Configuration of compiler/linker options is responsibility of Application's scripts + * + * + * ### Plugins support + * + * Runtime configuration options: + * - change backend priority: `OPENCV_PARALLEL_PRIORITY_=9999` + * - disable backend: `OPENCV_PARALLEL_PRIORITY_=0` + * - specify list of backends with high priority (>100000): `OPENCV_PARALLEL_PRIORITY_LIST=TBB,OPENMP`. Unknown backends are registered as new plugins. + * + */ + +/** Interface for parallel_for backends implementations + * + * @sa setParallelForBackend + */ +class CV_EXPORTS ParallelForAPI +{ +public: + virtual ~ParallelForAPI(); + + typedef void (CV_API_CALL *FN_parallel_for_body_cb_t)(int start, int end, void* data); + + virtual void parallel_for(int tasks, FN_parallel_for_body_cb_t body_callback, void* callback_data) = 0; + + virtual int getThreadNum() const = 0; + + virtual int getNumThreads() const = 0; + + virtual int setNumThreads(int nThreads) = 0; + + virtual const char* getName() const = 0; +}; + +/** @brief Replace OpenCV parallel_for backend + * + * Application can replace OpenCV `parallel_for()` backend with own implementation. + * + * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). + */ +CV_EXPORTS void setParallelForBackend(const std::shared_ptr& api, bool propagateNumThreads = true); + +/** @brief Change OpenCV parallel_for backend + * + * @note This call is not thread-safe. Consider calling this function from the `main()` before any other OpenCV processing functions (and without any other created threads). + */ +CV_EXPORTS_W bool setParallelForBackend(const std::string& backendName, bool propagateNumThreads = true); + +//! @} +}} // namespace +#endif // OPENCV_CORE_PARALLEL_BACKEND_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp b/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp index cac3755aae..c6ddf6f0ca 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/persistence.hpp @@ -1,1274 +1,1274 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_PERSISTENCE_HPP -#define OPENCV_CORE_PERSISTENCE_HPP - -#ifndef CV_DOXYGEN -/// Define to support persistence legacy formats -#define CV__LEGACY_PERSISTENCE -#endif - -#ifndef __cplusplus -# error persistence.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/types.hpp" -#include "opencv2/core/mat.hpp" - -namespace cv { - -/** @addtogroup core_xml - -XML/YAML/JSON file storages. {#xml_storage} -======================= -Writing to a file storage. --------------------------- -You can store and then restore various OpenCV data structures to/from XML (), -YAML () or JSON () formats. Also, it is possible to store -and load arbitrarily complex data structures, which include OpenCV data structures, as well as -primitive data types (integer and floating-point numbers and text strings) as their elements. - -Use the following procedure to write something to XML, YAML or JSON: --# Create new FileStorage and open it for writing. It can be done with a single call to -FileStorage::FileStorage constructor that takes a filename, or you can use the default constructor -and then call FileStorage::open. Format of the file (XML, YAML or JSON) is determined from the filename -extension (".xml", ".yml"/".yaml" and ".json", respectively) --# Write all the data you want using the streaming operator `<<`, just like in the case of STL -streams. --# Close the file using FileStorage::release. FileStorage destructor also closes the file. - -Here is an example: -@code - #include "opencv2/core.hpp" - #include - - using namespace cv; - - int main(int, char** argv) - { - FileStorage fs("test.yml", FileStorage::WRITE); - - fs << "frameCount" << 5; - time_t rawtime; time(&rawtime); - fs << "calibrationDate" << asctime(localtime(&rawtime)); - Mat cameraMatrix = (Mat_(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); - Mat distCoeffs = (Mat_(5,1) << 0.1, 0.01, -0.001, 0, 0); - fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs; - fs << "features" << "["; - for( int i = 0; i < 3; i++ ) - { - int x = rand() % 640; - int y = rand() % 480; - uchar lbp = rand() % 256; - - fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; - for( int j = 0; j < 8; j++ ) - fs << ((lbp >> j) & 1); - fs << "]" << "}"; - } - fs << "]"; - fs.release(); - return 0; - } -@endcode -The sample above stores to YML an integer, a text string (calibration date), 2 matrices, and a custom -structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here -is output of the sample: -@code{.yaml} -%YAML:1.0 -frameCount: 5 -calibrationDate: "Fri Jun 17 14:09:29 2011\n" -cameraMatrix: !!opencv-matrix - rows: 3 - cols: 3 - dt: d - data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ] -distCoeffs: !!opencv-matrix - rows: 5 - cols: 1 - dt: d - data: [ 1.0000000000000001e-01, 1.0000000000000000e-02, - -1.0000000000000000e-03, 0., 0. ] -features: - - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] } - - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] } - - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] } -@endcode - -As an exercise, you can replace ".yml" with ".xml" or ".json" in the sample above and see, how the -corresponding XML file will look like. - -Several things can be noted by looking at the sample code and the output: - -- The produced YAML (and XML/JSON) consists of heterogeneous collections that can be nested. There are - 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings - each element has a name and is accessed by name. This is similar to structures and std::map in - C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by - indices. This is similar to arrays and std::vector in C/C++ and lists, tuples in Python. - "Heterogeneous" means that elements of each single collection can have different types. - - Top-level collection in YAML/XML/JSON is a mapping. Each matrix is stored as a mapping, and the matrix - elements are stored as a sequence. Then, there is a sequence of features, where each feature is - represented a mapping, and lbp value in a nested sequence. - -- When you write to a mapping (a structure), you write element name followed by its value. When you - write to a sequence, you simply write the elements one by one. OpenCV data structures (such as - cv::Mat) are written in absolutely the same way as simple C data structures - using `<<` - operator. - -- To write a mapping, you first write the special string `{` to the storage, then write the - elements as pairs (`fs << << `) and then write the closing - `}`. - -- To write a sequence, you first write the special string `[`, then write the elements, then - write the closing `]`. - -- In YAML/JSON (but not XML), mappings and sequences can be written in a compact Python-like inline - form. In the sample above matrix elements, as well as each feature, including its lbp value, is - stored in such inline form. To store a mapping/sequence in a compact form, put `:` after the - opening character, e.g. use `{:` instead of `{` and `[:` instead of `[`. When the - data is written to XML, those extra `:` are ignored. - -Reading data from a file storage. ---------------------------------- -To read the previously written XML, YAML or JSON file, do the following: --# Open the file storage using FileStorage::FileStorage constructor or FileStorage::open method. - In the current implementation the whole file is parsed and the whole representation of file - storage is built in memory as a hierarchy of file nodes (see FileNode) - --# Read the data you are interested in. Use FileStorage::operator [], FileNode::operator [] - and/or FileNodeIterator. - --# Close the storage using FileStorage::release. - -Here is how to read the file created by the code sample above: -@code - FileStorage fs2("test.yml", FileStorage::READ); - - // first method: use (type) operator on FileNode. - int frameCount = (int)fs2["frameCount"]; - - String date; - // second method: use FileNode::operator >> - fs2["calibrationDate"] >> date; - - Mat cameraMatrix2, distCoeffs2; - fs2["cameraMatrix"] >> cameraMatrix2; - fs2["distCoeffs"] >> distCoeffs2; - - cout << "frameCount: " << frameCount << endl - << "calibration date: " << date << endl - << "camera matrix: " << cameraMatrix2 << endl - << "distortion coeffs: " << distCoeffs2 << endl; - - FileNode features = fs2["features"]; - FileNodeIterator it = features.begin(), it_end = features.end(); - int idx = 0; - std::vector lbpval; - - // iterate through a sequence using FileNodeIterator - for( ; it != it_end; ++it, idx++ ) - { - cout << "feature #" << idx << ": "; - cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: ("; - // you can also easily read numerical arrays using FileNode >> std::vector operator. - (*it)["lbp"] >> lbpval; - for( int i = 0; i < (int)lbpval.size(); i++ ) - cout << " " << (int)lbpval[i]; - cout << ")" << endl; - } - fs2.release(); -@endcode - -Format specification {#format_spec} --------------------- -`([count]{u|c|w|s|i|f|d})`... where the characters correspond to fundamental C++ types: -- `u` 8-bit unsigned number -- `c` 8-bit signed number -- `w` 16-bit unsigned number -- `s` 16-bit signed number -- `i` 32-bit signed number -- `f` single precision floating-point number -- `d` double precision floating-point number -- `r` pointer, 32 lower bits of which are written as a signed integer. The type can be used to - store structures with links between the elements. - -`count` is the optional counter of values of a given type. For example, `2if` means that each array -element is a structure of 2 integers, followed by a single-precision floating-point number. The -equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u` -means that the array consists of bytes, and `2d` means the array consists of pairs of doubles. - -@see @ref samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp -*/ - -//! @{ - -/** @example samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp -A complete example using the FileStorage interface -Check @ref tutorial_file_input_output_with_xml_yml "the corresponding tutorial" for more details -*/ - -////////////////////////// XML & YAML I/O ////////////////////////// - -class CV_EXPORTS FileNode; -class CV_EXPORTS FileNodeIterator; - -/** @brief XML/YAML/JSON file storage class that encapsulates all the information necessary for writing or -reading data to/from a file. - */ -class CV_EXPORTS_W FileStorage -{ -public: - //! file storage mode - enum Mode - { - READ = 0, //!< value, open the file for reading - WRITE = 1, //!< value, open the file for writing - APPEND = 2, //!< value, open the file for appending - MEMORY = 4, /**< flag, read data from source or write data to the internal buffer (which is - returned by FileStorage::release) */ - FORMAT_MASK = (7<<3), //!< mask for format flags - FORMAT_AUTO = 0, //!< flag, auto format - FORMAT_XML = (1<<3), //!< flag, XML format - FORMAT_YAML = (2<<3), //!< flag, YAML format - FORMAT_JSON = (3<<3), //!< flag, JSON format - - BASE64 = 64, //!< flag, write rawdata in Base64 by default. (consider using WRITE_BASE64) - WRITE_BASE64 = BASE64 | WRITE, //!< flag, enable both WRITE and BASE64 - }; - enum State - { - UNDEFINED = 0, //!< Initial or uninitialized state. - VALUE_EXPECTED = 1, //!< Expecting a value in the current position. - NAME_EXPECTED = 2, //!< Expecting a key/name in the current position. - INSIDE_MAP = 4 //!< Indicates being inside a map (a set of key-value pairs). - }; - - /** @brief The constructors. - - The full constructor opens the file. Alternatively you can use the default constructor and then - call FileStorage::open. - */ - CV_WRAP FileStorage(); - - /** @overload - @copydoc open() - */ - CV_WRAP FileStorage(const String& filename, int flags, const String& encoding=String()); - - //! the destructor. calls release() - virtual ~FileStorage(); - - /** @brief Opens a file. - - See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release - before opening the file. - @param filename Name of the file to open or the text string to read the data from. - Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON - respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both - FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify - the output file format (e.g. mydata.xml, .yml etc.). A file name can also contain parameters. - You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to - FileStorage::BASE64 flag. - @param flags Mode of operation. One of FileStorage::Mode - @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and - you should use 8-bit encoding instead of it. - */ - CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String()); - - /** @brief Checks whether the file is opened. - - @returns true if the object is associated with the current file and false otherwise. It is a - good practice to call this method after you tried to open a file. - */ - CV_WRAP virtual bool isOpened() const; - - /** @brief Closes the file and releases all the memory buffers. - - Call this method after all I/O operations with the storage are finished. - */ - CV_WRAP virtual void release(); - - /** @brief Closes the file and releases all the memory buffers. - - Call this method after all I/O operations with the storage are finished. If the storage was - opened for writing data and FileStorage::WRITE was specified - */ - CV_WRAP virtual String releaseAndGetString(); - - /** @brief Returns the first element of the top-level mapping. - @returns The first element of the top-level mapping. - */ - CV_WRAP FileNode getFirstTopLevelNode() const; - - /** @brief Returns the top-level mapping - @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file. - However, YAML supports multiple streams and so there can be several. - @returns The top-level mapping. - */ - CV_WRAP FileNode root(int streamidx=0) const; - - /** @brief Returns the specified element of the top-level mapping. - @param nodename Name of the file node. - @returns Node with the given name. - */ - FileNode operator[](const String& nodename) const; - - /** @overload */ - CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; - - /** - * @brief Simplified writing API to use with bindings. - * @param name Name of the written object. When writing to sequences (a.k.a. "arrays"), pass an empty string. - * @param val Value of the written object. - */ - CV_WRAP void write(const String& name, int val); - /// @overload - CV_WRAP void write(const String& name, int64_t val); - /// @overload - CV_WRAP void write(const String& name, double val); - /// @overload - CV_WRAP void write(const String& name, const String& val); - /// @overload - CV_WRAP void write(const String& name, const Mat& val); - /// @overload - CV_WRAP void write(const String& name, const std::vector& val); - - /** @brief Writes multiple numbers. - - Writes one or more numbers of the specified format to the currently written structure. Usually it is - more convenient to use operator `<<` instead of this method. - @param fmt Specification of each array element, see @ref format_spec "format specification" - @param vec Pointer to the written array. - @param len Number of the uchar elements to write. - */ - void writeRaw( const String& fmt, const void* vec, size_t len ); - - /** @brief Writes a comment. - - The function writes a comment into file storage. The comments are skipped when the storage is read. - @param comment The written comment, single-line or multi-line - @param append If true, the function tries to put the comment at the end of current line. - Else if the comment is multi-line, or if it does not fit at the end of the current - line, the comment starts a new line. - */ - CV_WRAP void writeComment(const String& comment, bool append = false); - - /** @brief Starts to write a nested structure (sequence or a mapping). - @param name name of the structure. When writing to sequences (a.k.a. "arrays"), pass an empty string. - @param flags type of the structure (FileNode::MAP or FileNode::SEQ (both with optional FileNode::FLOW)). - @param typeName optional name of the type you store. The effect of setting this depends on the storage format. - I.e. if the format has a specification for storing type information, this parameter is used. - */ - CV_WRAP void startWriteStruct(const String& name, int flags, const String& typeName=String()); - - /** @brief Finishes writing nested structure (should pair startWriteStruct()) - */ - CV_WRAP void endWriteStruct(); - - /** @brief Returns the normalized object name for the specified name of a file. - @param filename Name of a file - @returns The normalized object name. - */ - static String getDefaultObjectName(const String& filename); - - /** @brief Returns the current format. - * @returns The current format, see FileStorage::Mode - */ - CV_WRAP int getFormat() const; - - int state; - std::string elname; - - class Impl; - Ptr p; -}; - -/** @brief File Storage Node class. - -The node is used to store each and every element of the file storage opened for reading. When -XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of -nodes. Each node can be a "leaf" that is contain a single number or a string, or be a collection of -other nodes. There can be named collections (mappings) where each element has a name and it is -accessed by a name, and ordered collections (sequences) where elements do not have names but rather -accessed by index. Type of the file node can be determined using FileNode::type method. - -Note that file nodes are only used for navigating file storages opened for reading. When a file -storage is opened for writing, no data is stored in memory after it is written. - */ -class CV_EXPORTS_W_SIMPLE FileNode -{ -public: - //! type of the file storage node - enum - { - NONE = 0, //!< empty node - INT = 1, //!< an integer - REAL = 2, //!< floating-point number - FLOAT = REAL, //!< synonym or REAL - STR = 3, //!< text string in UTF-8 encoding - STRING = STR, //!< synonym for STR - SEQ = 4, //!< sequence - MAP = 5, //!< mapping - TYPE_MASK = 7, - - FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer - UNIFORM = 8, //!< if set, means that all the collection elements are numbers of the same type (real's or int's). - //!< UNIFORM is used only when reading FileStorage; FLOW is used only when writing. So they share the same bit - EMPTY = 16, //!< empty structure (sequence or mapping) - NAMED = 32 //!< the node has a name (i.e. it is element of a mapping). - }; - /** @brief The constructors. - - These constructors are used to create a default file node, construct it from obsolete structures or - from the another file node. - */ - CV_WRAP FileNode(); - - /** @overload - @param fs Pointer to the file storage structure. - @param blockIdx Index of the memory block where the file node is stored - @param ofs Offset in bytes from the beginning of the serialized storage - - @deprecated - */ - FileNode(const FileStorage* fs, size_t blockIdx, size_t ofs); - - /** @overload - @param node File node to be used as initialization for the created file node. - */ - FileNode(const FileNode& node); - - FileNode& operator=(const FileNode& node); - - /** @brief Returns element of a mapping node or a sequence node. - @param nodename Name of an element in the mapping node. - @returns Returns the element with the given identifier. - */ - FileNode operator[](const String& nodename) const; - - /** @overload - @param nodename Name of an element in the mapping node. - */ - CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; - - /** @overload - @param i Index of an element in the sequence node. - */ - CV_WRAP_AS(at) FileNode operator[](int i) const; - - /** @brief Returns keys of a mapping node. - @returns Keys of a mapping node. - */ - CV_WRAP std::vector keys() const; - - /** @brief Returns type of the node. - @returns Type of the node. See FileNode::Type - */ - CV_WRAP int type() const; - - //! returns true if the node is empty - CV_WRAP bool empty() const; - //! returns true if the node is a "none" object - CV_WRAP bool isNone() const; - //! returns true if the node is a sequence - CV_WRAP bool isSeq() const; - //! returns true if the node is a mapping - CV_WRAP bool isMap() const; - //! returns true if the node is an integer - CV_WRAP bool isInt() const; - //! returns true if the node is a floating-point number - CV_WRAP bool isReal() const; - //! returns true if the node is a text string - CV_WRAP bool isString() const; - //! returns true if the node has a name - CV_WRAP bool isNamed() const; - //! returns the node name or an empty string if the node is nameless - CV_WRAP std::string name() const; - //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. - CV_WRAP size_t size() const; - //! returns raw size of the FileNode in bytes - CV_WRAP size_t rawSize() const; - //! returns the node content as an integer. If the node stores floating-point number, it is rounded. - operator int() const; - //! returns the node content as a signed 64bit integer. If the node stores floating-point number, it is rounded. - operator int64_t() const; - //! returns the node content as float - operator float() const; - //! returns the node content as double - operator double() const; - //! returns the node content as text string - inline operator std::string() const { return this->string(); } - - static bool isMap(int flags); - static bool isSeq(int flags); - static bool isCollection(int flags); - static bool isEmptyCollection(int flags); - static bool isFlow(int flags); - - uchar* ptr(); - const uchar* ptr() const; - - //! returns iterator pointing to the first node element - FileNodeIterator begin() const; - //! returns iterator pointing to the element following the last node element - FileNodeIterator end() const; - - /** @brief Reads node elements to the buffer with the specified format. - - Usually it is more convenient to use operator `>>` instead of this method. - @param fmt Specification of each array element. See @ref format_spec "format specification" - @param vec Pointer to the destination array. - @param len Number of bytes to read (buffer size limit). If it is greater than number of - remaining elements then all of them will be read. - */ - void readRaw( const String& fmt, void* vec, size_t len ) const; - - /** Internal method used when reading FileStorage. - Sets the type (int, real or string) and value of the previously created node. - */ - void setValue( int type, const void* value, int len=-1 ); - - //! Simplified reading API to use with bindings. - CV_WRAP double real() const; - //! Simplified reading API to use with bindings. - CV_WRAP std::string string() const; - //! Simplified reading API to use with bindings. - CV_WRAP Mat mat() const; - - //protected: - FileNode(FileStorage::Impl* fs, size_t blockIdx, size_t ofs); - - FileStorage::Impl* fs; - size_t blockIdx; - size_t ofs; -}; - - -/** @brief used to iterate through sequences and mappings. - - A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a - sequence, stored in node. See the data reading sample in the beginning of the section. - */ -class CV_EXPORTS FileNodeIterator -{ -public: - /** @brief The constructors. - - These constructors are used to create a default iterator, set it to specific element in a file node - or construct it from another iterator. - */ - FileNodeIterator(); - - /** @overload - @param node File node - the collection to iterate over; - it can be a scalar (equivalent to 1-element collection) or "none" (equivalent to empty collection). - @param seekEnd - true if iterator needs to be set after the last element of the node; - that is: - * node.begin() => FileNodeIterator(node, false) - * node.end() => FileNodeIterator(node, true) - */ - FileNodeIterator(const FileNode& node, bool seekEnd); - - /** @overload - @param it Iterator to be used as initialization for the created iterator. - */ - FileNodeIterator(const FileNodeIterator& it); - - FileNodeIterator& operator=(const FileNodeIterator& it); - - //! returns the currently observed element - FileNode operator *() const; - - //! moves iterator to the next node - FileNodeIterator& operator ++ (); - //! moves iterator to the next node - FileNodeIterator operator ++ (int); - //! moves iterator forward by the specified offset (possibly negative) - FileNodeIterator& operator += (int ofs); - - /** @brief Reads node elements to the buffer with the specified format. - - Usually it is more convenient to use operator `>>` instead of this method. - @param fmt Specification of each array element. See @ref format_spec "format specification" - @param vec Pointer to the destination array. - @param len Number of bytes to read (buffer size limit). If it is greater than number of - remaining elements then all of them will be read. - */ - FileNodeIterator& readRaw( const String& fmt, void* vec, - size_t len=(size_t)INT_MAX ); - - //! returns the number of remaining (not read yet) elements - size_t remaining() const; - - bool equalTo(const FileNodeIterator& it) const; - -protected: - FileStorage::Impl* fs; - size_t blockIdx; - size_t ofs; - size_t blockSize; - size_t nodeNElems; - size_t idx; -}; - -//! @} core_xml - -/////////////////// XML & YAML I/O implementation ////////////////// - -CV_EXPORTS void write( FileStorage& fs, const String& name, int value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, int64_t value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, float value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, double value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value ); -CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value ); -#ifdef CV__LEGACY_PERSISTENCE -CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); -CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); -#endif - -CV_EXPORTS void writeScalar( FileStorage& fs, int value ); -CV_EXPORTS void writeScalar( FileStorage& fs, int64_t value ); -CV_EXPORTS void writeScalar( FileStorage& fs, float value ); -CV_EXPORTS void writeScalar( FileStorage& fs, double value ); -CV_EXPORTS void writeScalar( FileStorage& fs, const String& value ); - -CV_EXPORTS void read(const FileNode& node, int& value, int default_value); -CV_EXPORTS void read(const FileNode& node, int64_t& value, int64_t default_value); -CV_EXPORTS void read(const FileNode& node, float& value, float default_value); -CV_EXPORTS void read(const FileNode& node, double& value, double default_value); -CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value); -CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() ); -CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() ); -#ifdef CV__LEGACY_PERSISTENCE -CV_EXPORTS void read(const FileNode& node, std::vector& keypoints); -CV_EXPORTS void read(const FileNode& node, std::vector& matches); -#endif -CV_EXPORTS void read(const FileNode& node, KeyPoint& value, const KeyPoint& default_value); -CV_EXPORTS void read(const FileNode& node, DMatch& value, const DMatch& default_value); - -template static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2])); -} - -template static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); -} - -template static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); -} - -template static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]); -} - -template static inline void read(const FileNode& node, Matx<_Tp, m, n>& value, const Matx<_Tp, m, n>& default_matx = Matx<_Tp, m, n>()) -{ - Mat temp; - read(node, temp); // read as a Mat class - - if (temp.empty()) - value = default_matx; - else - value = Matx<_Tp, m, n>(temp); -} - -template static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value) -{ - std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; - value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), - saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); -} - -static inline void read(const FileNode& node, Range& value, const Range& default_value) -{ - Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end); - read(node, temp, default_temp); - value.start = temp.x; value.end = temp.y; -} - -/** @brief Writes string to a file storage. - */ -CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str); - -//! @cond IGNORED - -namespace internal -{ - class CV_EXPORTS WriteStructContext - { - public: - WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String()); - ~WriteStructContext(); - private: - FileStorage* fs; - }; - - template class VecWriterProxy - { - public: - VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} - void operator()(const std::vector<_Tp>& vec) const - { - size_t count = vec.size(); - for (size_t i = 0; i < count; i++) - write(*fs, vec[i]); - } - private: - FileStorage* fs; - }; - - template class VecWriterProxy<_Tp, 1> - { - public: - VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} - void operator()(const std::vector<_Tp>& vec) const - { - int _fmt = traits::SafeFmt<_Tp>::fmt; - char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' }; - fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp)); - } - private: - FileStorage* fs; - }; - - template class VecReaderProxy - { - public: - VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} - void operator()(std::vector<_Tp>& vec, size_t count) const - { - count = std::min(count, it->remaining()); - vec.resize(count); - for (size_t i = 0; i < count; i++, ++(*it)) - read(**it, vec[i], _Tp()); - } - private: - FileNodeIterator* it; - }; - - template class VecReaderProxy<_Tp, 1> - { - public: - VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} - void operator()(std::vector<_Tp>& vec, size_t count) const - { - size_t remaining = it->remaining(); - size_t cn = DataType<_Tp>::channels; - int _fmt = traits::SafeFmt<_Tp>::fmt; - CV_Assert((_fmt >> 8) < 9); - char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' }; - CV_Assert((remaining % cn) == 0); - size_t remaining1 = remaining / cn; - count = count > remaining1 ? remaining1 : count; - vec.resize(count); - it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp)); - } - private: - FileNodeIterator* it; - }; - -} // internal - -//! @endcond - -template static inline -void write(FileStorage& fs, const _Tp& value) -{ - write(fs, String(), value); -} - -template<> inline -void write( FileStorage& fs, const int& value ) -{ - writeScalar(fs, value); -} - -template<> inline -void write( FileStorage& fs, const float& value ) -{ - writeScalar(fs, value); -} - -template<> inline -void write( FileStorage& fs, const double& value ) -{ - writeScalar(fs, value); -} - -template<> inline -void write( FileStorage& fs, const String& value ) -{ - writeScalar(fs, value); -} - -template static inline -void write(FileStorage& fs, const Point_<_Tp>& pt ) -{ - write(fs, pt.x); - write(fs, pt.y); -} - -template static inline -void write(FileStorage& fs, const Point3_<_Tp>& pt ) -{ - write(fs, pt.x); - write(fs, pt.y); - write(fs, pt.z); -} - -template static inline -void write(FileStorage& fs, const Size_<_Tp>& sz ) -{ - write(fs, sz.width); - write(fs, sz.height); -} - -template static inline -void write(FileStorage& fs, const Complex<_Tp>& c ) -{ - write(fs, c.re); - write(fs, c.im); -} - -template static inline -void write(FileStorage& fs, const Rect_<_Tp>& r ) -{ - write(fs, r.x); - write(fs, r.y); - write(fs, r.width); - write(fs, r.height); -} - -template static inline -void write(FileStorage& fs, const Vec<_Tp, cn>& v ) -{ - for(int i = 0; i < cn; i++) - write(fs, v.val[i]); -} - -template static inline -void write(FileStorage& fs, const Matx<_Tp, m, n>& x ) -{ - write(fs, Mat(x)); // write as a Mat class -} - -template static inline -void write(FileStorage& fs, const Scalar_<_Tp>& s ) -{ - write(fs, s.val[0]); - write(fs, s.val[1]); - write(fs, s.val[2]); - write(fs, s.val[3]); -} - -static inline -void write(FileStorage& fs, const Range& r ) -{ - write(fs, r.start); - write(fs, r.end); -} - -template static inline -void write( FileStorage& fs, const std::vector<_Tp>& vec ) -{ - cv::internal::VecWriterProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> w(&fs); - w(vec); -} - -template static inline -void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, pt); -} - -template static inline -void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, pt); -} - -template static inline -void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, sz); -} - -template static inline -void write(FileStorage& fs, const String& name, const Complex<_Tp>& c ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, c); -} - -template static inline -void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, r); -} - -template static inline -void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, v); -} - -template static inline -void write(FileStorage& fs, const String& name, const Matx<_Tp, m, n>& x ) -{ - write(fs, name, Mat(x)); // write as a Mat class -} - -template static inline -void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, s); -} - -static inline -void write(FileStorage& fs, const String& name, const Range& r ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, r); -} - -static inline -void write(FileStorage& fs, const String& name, const KeyPoint& kpt) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, kpt.pt.x); - write(fs, kpt.pt.y); - write(fs, kpt.size); - write(fs, kpt.angle); - write(fs, kpt.response); - write(fs, kpt.octave); - write(fs, kpt.class_id); -} - -static inline -void write(FileStorage& fs, const String& name, const DMatch& m) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); - write(fs, m.queryIdx); - write(fs, m.trainIdx); - write(fs, m.imgIdx); - write(fs, m.distance); -} - -template::value >::type* = nullptr> -static inline void write( FileStorage& fs, const String& name, const _Tp& val ) -{ - write(fs, name, static_cast(val)); -} - -template static inline -void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); - write(fs, vec); -} - -template static inline -void write( FileStorage& fs, const String& name, const std::vector< std::vector<_Tp> >& vec ) -{ - cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ); - for(size_t i = 0; i < vec.size(); i++) - { - cv::internal::WriteStructContext ws_(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); - write(fs, vec[i]); - } -} - -#ifdef CV__LEGACY_PERSISTENCE -// This code is not needed anymore, but it is preserved here to keep source compatibility -// Implementation is similar to templates instantiations -static inline void write(FileStorage& fs, const KeyPoint& kpt) { write(fs, String(), kpt); } -static inline void write(FileStorage& fs, const DMatch& m) { write(fs, String(), m); } -static inline void write(FileStorage& fs, const std::vector& vec) -{ - cv::internal::VecWriterProxy w(&fs); - w(vec); -} -static inline void write(FileStorage& fs, const std::vector& vec) -{ - cv::internal::VecWriterProxy w(&fs); - w(vec); - -} -#endif - - -static inline -void read(const FileNode& node, bool& value, bool default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = temp != 0; -} - -static inline -void read(const FileNode& node, uchar& value, uchar default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline -void read(const FileNode& node, schar& value, schar default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline -void read(const FileNode& node, ushort& value, ushort default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -static inline -void read(const FileNode& node, short& value, short default_value) -{ - int temp; - read(node, temp, (int)default_value); - value = saturate_cast(temp); -} - -template static inline -void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX ) -{ - cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); - r(vec, maxCount); -} - -template::value >::type* = nullptr> -static inline void read(const FileNode& node, _Tp& value, const _Tp& default_value = static_cast<_Tp>(0)) -{ - int temp; - read(node, temp, static_cast(default_value)); - value = static_cast<_Tp>(temp); -} - -template static inline -void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() ) -{ - if(node.empty()) - vec = default_value; - else - { - FileNodeIterator it = node.begin(); - read( it, vec ); - } -} - -static inline -void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) -{ - if(node.empty()) - vec = default_value; - else - read(node, vec); -} - -static inline -void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) -{ - if(node.empty()) - vec = default_value; - else - read(node, vec); -} - -/** @brief Writes data to a file storage. - */ -template static inline -FileStorage& operator << (FileStorage& fs, const _Tp& value) -{ - if( !fs.isOpened() ) - return fs; - if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP ) - CV_Error( Error::StsError, "No element name has been given" ); - write( fs, fs.elname, value ); - if( fs.state & FileStorage::INSIDE_MAP ) - fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP; - return fs; -} - -/** @brief Writes data to a file storage. - */ -static inline -FileStorage& operator << (FileStorage& fs, const char* str) -{ - return (fs << String(str)); -} - -/** @brief Writes data to a file storage. - */ -static inline -FileStorage& operator << (FileStorage& fs, char* value) -{ - return (fs << String(value)); -} - -/** @brief Reads data from a file storage. - */ -template static inline -FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value) -{ - read( *it, value, _Tp()); - return ++it; -} - -/** @brief Reads data from a file storage. - */ -template static inline -FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec) -{ - cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); - r(vec, (size_t)INT_MAX); - return it; -} - -/** @brief Reads data from a file storage. - */ -template static inline -void operator >> (const FileNode& n, _Tp& value) -{ - read( n, value, _Tp()); -} - -/** @brief Reads data from a file storage. - */ -template static inline -void operator >> (const FileNode& n, std::vector<_Tp>& vec) -{ - FileNodeIterator it = n.begin(); - it >> vec; -} - -/** @brief Reads KeyPoint from a file storage. -*/ -//It needs special handling because it contains two types of fields, int & float. -static inline -void operator >> (const FileNode& n, KeyPoint& kpt) -{ - FileNodeIterator it = n.begin(); - it >> kpt.pt.x >> kpt.pt.y >> kpt.size >> kpt.angle >> kpt.response >> kpt.octave >> kpt.class_id; -} - -#ifdef CV__LEGACY_PERSISTENCE -static inline -void operator >> (const FileNode& n, std::vector& vec) -{ - read(n, vec); -} -static inline -void operator >> (const FileNode& n, std::vector& vec) -{ - read(n, vec); -} -#endif - -/** @brief Reads DMatch from a file storage. -*/ -//It needs special handling because it contains two types of fields, int & float. -static inline -void operator >> (const FileNode& n, DMatch& m) -{ - FileNodeIterator it = n.begin(); - it >> m.queryIdx >> m.trainIdx >> m.imgIdx >> m.distance; -} - -CV_EXPORTS bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2); -CV_EXPORTS bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2); - -static inline -ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2) -{ - return it2.remaining() - it1.remaining(); -} - -static inline -bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2) -{ - return it1.remaining() > it2.remaining(); -} - -} // cv - -#endif // OPENCV_CORE_PERSISTENCE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_PERSISTENCE_HPP +#define OPENCV_CORE_PERSISTENCE_HPP + +#ifndef CV_DOXYGEN +/// Define to support persistence legacy formats +#define CV__LEGACY_PERSISTENCE +#endif + +#ifndef __cplusplus +# error persistence.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/types.hpp" +#include "opencv2/core/mat.hpp" + +namespace cv { + +/** @addtogroup core_xml + +XML/YAML/JSON file storages. {#xml_storage} +======================= +Writing to a file storage. +-------------------------- +You can store and then restore various OpenCV data structures to/from XML (), +YAML () or JSON () formats. Also, it is possible to store +and load arbitrarily complex data structures, which include OpenCV data structures, as well as +primitive data types (integer and floating-point numbers and text strings) as their elements. + +Use the following procedure to write something to XML, YAML or JSON: +-# Create new FileStorage and open it for writing. It can be done with a single call to +FileStorage::FileStorage constructor that takes a filename, or you can use the default constructor +and then call FileStorage::open. Format of the file (XML, YAML or JSON) is determined from the filename +extension (".xml", ".yml"/".yaml" and ".json", respectively) +-# Write all the data you want using the streaming operator `<<`, just like in the case of STL +streams. +-# Close the file using FileStorage::release. FileStorage destructor also closes the file. + +Here is an example: +@code + #include "opencv2/core.hpp" + #include + + using namespace cv; + + int main(int, char** argv) + { + FileStorage fs("test.yml", FileStorage::WRITE); + + fs << "frameCount" << 5; + time_t rawtime; time(&rawtime); + fs << "calibrationDate" << asctime(localtime(&rawtime)); + Mat cameraMatrix = (Mat_(3,3) << 1000, 0, 320, 0, 1000, 240, 0, 0, 1); + Mat distCoeffs = (Mat_(5,1) << 0.1, 0.01, -0.001, 0, 0); + fs << "cameraMatrix" << cameraMatrix << "distCoeffs" << distCoeffs; + fs << "features" << "["; + for( int i = 0; i < 3; i++ ) + { + int x = rand() % 640; + int y = rand() % 480; + uchar lbp = rand() % 256; + + fs << "{:" << "x" << x << "y" << y << "lbp" << "[:"; + for( int j = 0; j < 8; j++ ) + fs << ((lbp >> j) & 1); + fs << "]" << "}"; + } + fs << "]"; + fs.release(); + return 0; + } +@endcode +The sample above stores to YML an integer, a text string (calibration date), 2 matrices, and a custom +structure "feature", which includes feature coordinates and LBP (local binary pattern) value. Here +is output of the sample: +@code{.yaml} +%YAML:1.0 +frameCount: 5 +calibrationDate: "Fri Jun 17 14:09:29 2011\n" +cameraMatrix: !!opencv-matrix + rows: 3 + cols: 3 + dt: d + data: [ 1000., 0., 320., 0., 1000., 240., 0., 0., 1. ] +distCoeffs: !!opencv-matrix + rows: 5 + cols: 1 + dt: d + data: [ 1.0000000000000001e-01, 1.0000000000000000e-02, + -1.0000000000000000e-03, 0., 0. ] +features: + - { x:167, y:49, lbp:[ 1, 0, 0, 1, 1, 0, 1, 1 ] } + - { x:298, y:130, lbp:[ 0, 0, 0, 1, 0, 0, 1, 1 ] } + - { x:344, y:158, lbp:[ 1, 1, 0, 0, 0, 0, 1, 0 ] } +@endcode + +As an exercise, you can replace ".yml" with ".xml" or ".json" in the sample above and see, how the +corresponding XML file will look like. + +Several things can be noted by looking at the sample code and the output: + +- The produced YAML (and XML/JSON) consists of heterogeneous collections that can be nested. There are + 2 types of collections: named collections (mappings) and unnamed collections (sequences). In mappings + each element has a name and is accessed by name. This is similar to structures and std::map in + C/C++ and dictionaries in Python. In sequences elements do not have names, they are accessed by + indices. This is similar to arrays and std::vector in C/C++ and lists, tuples in Python. + "Heterogeneous" means that elements of each single collection can have different types. + + Top-level collection in YAML/XML/JSON is a mapping. Each matrix is stored as a mapping, and the matrix + elements are stored as a sequence. Then, there is a sequence of features, where each feature is + represented a mapping, and lbp value in a nested sequence. + +- When you write to a mapping (a structure), you write element name followed by its value. When you + write to a sequence, you simply write the elements one by one. OpenCV data structures (such as + cv::Mat) are written in absolutely the same way as simple C data structures - using `<<` + operator. + +- To write a mapping, you first write the special string `{` to the storage, then write the + elements as pairs (`fs << << `) and then write the closing + `}`. + +- To write a sequence, you first write the special string `[`, then write the elements, then + write the closing `]`. + +- In YAML/JSON (but not XML), mappings and sequences can be written in a compact Python-like inline + form. In the sample above matrix elements, as well as each feature, including its lbp value, is + stored in such inline form. To store a mapping/sequence in a compact form, put `:` after the + opening character, e.g. use `{:` instead of `{` and `[:` instead of `[`. When the + data is written to XML, those extra `:` are ignored. + +Reading data from a file storage. +--------------------------------- +To read the previously written XML, YAML or JSON file, do the following: +-# Open the file storage using FileStorage::FileStorage constructor or FileStorage::open method. + In the current implementation the whole file is parsed and the whole representation of file + storage is built in memory as a hierarchy of file nodes (see FileNode) + +-# Read the data you are interested in. Use FileStorage::operator [], FileNode::operator [] + and/or FileNodeIterator. + +-# Close the storage using FileStorage::release. + +Here is how to read the file created by the code sample above: +@code + FileStorage fs2("test.yml", FileStorage::READ); + + // first method: use (type) operator on FileNode. + int frameCount = (int)fs2["frameCount"]; + + String date; + // second method: use FileNode::operator >> + fs2["calibrationDate"] >> date; + + Mat cameraMatrix2, distCoeffs2; + fs2["cameraMatrix"] >> cameraMatrix2; + fs2["distCoeffs"] >> distCoeffs2; + + cout << "frameCount: " << frameCount << endl + << "calibration date: " << date << endl + << "camera matrix: " << cameraMatrix2 << endl + << "distortion coeffs: " << distCoeffs2 << endl; + + FileNode features = fs2["features"]; + FileNodeIterator it = features.begin(), it_end = features.end(); + int idx = 0; + std::vector lbpval; + + // iterate through a sequence using FileNodeIterator + for( ; it != it_end; ++it, idx++ ) + { + cout << "feature #" << idx << ": "; + cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: ("; + // you can also easily read numerical arrays using FileNode >> std::vector operator. + (*it)["lbp"] >> lbpval; + for( int i = 0; i < (int)lbpval.size(); i++ ) + cout << " " << (int)lbpval[i]; + cout << ")" << endl; + } + fs2.release(); +@endcode + +Format specification {#format_spec} +-------------------- +`([count]{u|c|w|s|i|f|d})`... where the characters correspond to fundamental C++ types: +- `u` 8-bit unsigned number +- `c` 8-bit signed number +- `w` 16-bit unsigned number +- `s` 16-bit signed number +- `i` 32-bit signed number +- `f` single precision floating-point number +- `d` double precision floating-point number +- `r` pointer, 32 lower bits of which are written as a signed integer. The type can be used to + store structures with links between the elements. + +`count` is the optional counter of values of a given type. For example, `2if` means that each array +element is a structure of 2 integers, followed by a single-precision floating-point number. The +equivalent notations of the above specification are `iif`, `2i1f` and so forth. Other examples: `u` +means that the array consists of bytes, and `2d` means the array consists of pairs of doubles. + +@see @ref samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp +*/ + +//! @{ + +/** @example samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp +A complete example using the FileStorage interface +Check @ref tutorial_file_input_output_with_xml_yml "the corresponding tutorial" for more details +*/ + +////////////////////////// XML & YAML I/O ////////////////////////// + +class CV_EXPORTS FileNode; +class CV_EXPORTS FileNodeIterator; + +/** @brief XML/YAML/JSON file storage class that encapsulates all the information necessary for writing or +reading data to/from a file. + */ +class CV_EXPORTS_W FileStorage +{ +public: + //! file storage mode + enum Mode + { + READ = 0, //!< value, open the file for reading + WRITE = 1, //!< value, open the file for writing + APPEND = 2, //!< value, open the file for appending + MEMORY = 4, /**< flag, read data from source or write data to the internal buffer (which is + returned by FileStorage::release) */ + FORMAT_MASK = (7<<3), //!< mask for format flags + FORMAT_AUTO = 0, //!< flag, auto format + FORMAT_XML = (1<<3), //!< flag, XML format + FORMAT_YAML = (2<<3), //!< flag, YAML format + FORMAT_JSON = (3<<3), //!< flag, JSON format + + BASE64 = 64, //!< flag, write rawdata in Base64 by default. (consider using WRITE_BASE64) + WRITE_BASE64 = BASE64 | WRITE, //!< flag, enable both WRITE and BASE64 + }; + enum State + { + UNDEFINED = 0, //!< Initial or uninitialized state. + VALUE_EXPECTED = 1, //!< Expecting a value in the current position. + NAME_EXPECTED = 2, //!< Expecting a key/name in the current position. + INSIDE_MAP = 4 //!< Indicates being inside a map (a set of key-value pairs). + }; + + /** @brief The constructors. + + The full constructor opens the file. Alternatively you can use the default constructor and then + call FileStorage::open. + */ + CV_WRAP FileStorage(); + + /** @overload + @copydoc open() + */ + CV_WRAP FileStorage(const String& filename, int flags, const String& encoding=String()); + + //! the destructor. calls release() + virtual ~FileStorage(); + + /** @brief Opens a file. + + See description of parameters in FileStorage::FileStorage. The method calls FileStorage::release + before opening the file. + @param filename Name of the file to open or the text string to read the data from. + Extension of the file (.xml, .yml/.yaml or .json) determines its format (XML, YAML or JSON + respectively). Also you can append .gz to work with compressed files, for example myHugeMatrix.xml.gz. If both + FileStorage::WRITE and FileStorage::MEMORY flags are specified, source is used just to specify + the output file format (e.g. mydata.xml, .yml etc.). A file name can also contain parameters. + You can use this format, "*?base64" (e.g. "file.json?base64" (case sensitive)), as an alternative to + FileStorage::BASE64 flag. + @param flags Mode of operation. One of FileStorage::Mode + @param encoding Encoding of the file. Note that UTF-16 XML encoding is not supported currently and + you should use 8-bit encoding instead of it. + */ + CV_WRAP virtual bool open(const String& filename, int flags, const String& encoding=String()); + + /** @brief Checks whether the file is opened. + + @returns true if the object is associated with the current file and false otherwise. It is a + good practice to call this method after you tried to open a file. + */ + CV_WRAP virtual bool isOpened() const; + + /** @brief Closes the file and releases all the memory buffers. + + Call this method after all I/O operations with the storage are finished. + */ + CV_WRAP virtual void release(); + + /** @brief Closes the file and releases all the memory buffers. + + Call this method after all I/O operations with the storage are finished. If the storage was + opened for writing data and FileStorage::WRITE was specified + */ + CV_WRAP virtual String releaseAndGetString(); + + /** @brief Returns the first element of the top-level mapping. + @returns The first element of the top-level mapping. + */ + CV_WRAP FileNode getFirstTopLevelNode() const; + + /** @brief Returns the top-level mapping + @param streamidx Zero-based index of the stream. In most cases there is only one stream in the file. + However, YAML supports multiple streams and so there can be several. + @returns The top-level mapping. + */ + CV_WRAP FileNode root(int streamidx=0) const; + + /** @brief Returns the specified element of the top-level mapping. + @param nodename Name of the file node. + @returns Node with the given name. + */ + FileNode operator[](const String& nodename) const; + + /** @overload */ + CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; + + /** + * @brief Simplified writing API to use with bindings. + * @param name Name of the written object. When writing to sequences (a.k.a. "arrays"), pass an empty string. + * @param val Value of the written object. + */ + CV_WRAP void write(const String& name, int val); + /// @overload + CV_WRAP void write(const String& name, int64_t val); + /// @overload + CV_WRAP void write(const String& name, double val); + /// @overload + CV_WRAP void write(const String& name, const String& val); + /// @overload + CV_WRAP void write(const String& name, const Mat& val); + /// @overload + CV_WRAP void write(const String& name, const std::vector& val); + + /** @brief Writes multiple numbers. + + Writes one or more numbers of the specified format to the currently written structure. Usually it is + more convenient to use operator `<<` instead of this method. + @param fmt Specification of each array element, see @ref format_spec "format specification" + @param vec Pointer to the written array. + @param len Number of the uchar elements to write. + */ + void writeRaw( const String& fmt, const void* vec, size_t len ); + + /** @brief Writes a comment. + + The function writes a comment into file storage. The comments are skipped when the storage is read. + @param comment The written comment, single-line or multi-line + @param append If true, the function tries to put the comment at the end of current line. + Else if the comment is multi-line, or if it does not fit at the end of the current + line, the comment starts a new line. + */ + CV_WRAP void writeComment(const String& comment, bool append = false); + + /** @brief Starts to write a nested structure (sequence or a mapping). + @param name name of the structure. When writing to sequences (a.k.a. "arrays"), pass an empty string. + @param flags type of the structure (FileNode::MAP or FileNode::SEQ (both with optional FileNode::FLOW)). + @param typeName optional name of the type you store. The effect of setting this depends on the storage format. + I.e. if the format has a specification for storing type information, this parameter is used. + */ + CV_WRAP void startWriteStruct(const String& name, int flags, const String& typeName=String()); + + /** @brief Finishes writing nested structure (should pair startWriteStruct()) + */ + CV_WRAP void endWriteStruct(); + + /** @brief Returns the normalized object name for the specified name of a file. + @param filename Name of a file + @returns The normalized object name. + */ + static String getDefaultObjectName(const String& filename); + + /** @brief Returns the current format. + * @returns The current format, see FileStorage::Mode + */ + CV_WRAP int getFormat() const; + + int state; + std::string elname; + + class Impl; + Ptr p; +}; + +/** @brief File Storage Node class. + +The node is used to store each and every element of the file storage opened for reading. When +XML/YAML file is read, it is first parsed and stored in the memory as a hierarchical collection of +nodes. Each node can be a "leaf" that is contain a single number or a string, or be a collection of +other nodes. There can be named collections (mappings) where each element has a name and it is +accessed by a name, and ordered collections (sequences) where elements do not have names but rather +accessed by index. Type of the file node can be determined using FileNode::type method. + +Note that file nodes are only used for navigating file storages opened for reading. When a file +storage is opened for writing, no data is stored in memory after it is written. + */ +class CV_EXPORTS_W_SIMPLE FileNode +{ +public: + //! type of the file storage node + enum + { + NONE = 0, //!< empty node + INT = 1, //!< an integer + REAL = 2, //!< floating-point number + FLOAT = REAL, //!< synonym or REAL + STR = 3, //!< text string in UTF-8 encoding + STRING = STR, //!< synonym for STR + SEQ = 4, //!< sequence + MAP = 5, //!< mapping + TYPE_MASK = 7, + + FLOW = 8, //!< compact representation of a sequence or mapping. Used only by YAML writer + UNIFORM = 8, //!< if set, means that all the collection elements are numbers of the same type (real's or int's). + //!< UNIFORM is used only when reading FileStorage; FLOW is used only when writing. So they share the same bit + EMPTY = 16, //!< empty structure (sequence or mapping) + NAMED = 32 //!< the node has a name (i.e. it is element of a mapping). + }; + /** @brief The constructors. + + These constructors are used to create a default file node, construct it from obsolete structures or + from the another file node. + */ + CV_WRAP FileNode(); + + /** @overload + @param fs Pointer to the file storage structure. + @param blockIdx Index of the memory block where the file node is stored + @param ofs Offset in bytes from the beginning of the serialized storage + + @deprecated + */ + FileNode(const FileStorage* fs, size_t blockIdx, size_t ofs); + + /** @overload + @param node File node to be used as initialization for the created file node. + */ + FileNode(const FileNode& node); + + FileNode& operator=(const FileNode& node); + + /** @brief Returns element of a mapping node or a sequence node. + @param nodename Name of an element in the mapping node. + @returns Returns the element with the given identifier. + */ + FileNode operator[](const String& nodename) const; + + /** @overload + @param nodename Name of an element in the mapping node. + */ + CV_WRAP_AS(getNode) FileNode operator[](const char* nodename) const; + + /** @overload + @param i Index of an element in the sequence node. + */ + CV_WRAP_AS(at) FileNode operator[](int i) const; + + /** @brief Returns keys of a mapping node. + @returns Keys of a mapping node. + */ + CV_WRAP std::vector keys() const; + + /** @brief Returns type of the node. + @returns Type of the node. See FileNode::Type + */ + CV_WRAP int type() const; + + //! returns true if the node is empty + CV_WRAP bool empty() const; + //! returns true if the node is a "none" object + CV_WRAP bool isNone() const; + //! returns true if the node is a sequence + CV_WRAP bool isSeq() const; + //! returns true if the node is a mapping + CV_WRAP bool isMap() const; + //! returns true if the node is an integer + CV_WRAP bool isInt() const; + //! returns true if the node is a floating-point number + CV_WRAP bool isReal() const; + //! returns true if the node is a text string + CV_WRAP bool isString() const; + //! returns true if the node has a name + CV_WRAP bool isNamed() const; + //! returns the node name or an empty string if the node is nameless + CV_WRAP std::string name() const; + //! returns the number of elements in the node, if it is a sequence or mapping, or 1 otherwise. + CV_WRAP size_t size() const; + //! returns raw size of the FileNode in bytes + CV_WRAP size_t rawSize() const; + //! returns the node content as an integer. If the node stores floating-point number, it is rounded. + operator int() const; + //! returns the node content as a signed 64bit integer. If the node stores floating-point number, it is rounded. + operator int64_t() const; + //! returns the node content as float + operator float() const; + //! returns the node content as double + operator double() const; + //! returns the node content as text string + inline operator std::string() const { return this->string(); } + + static bool isMap(int flags); + static bool isSeq(int flags); + static bool isCollection(int flags); + static bool isEmptyCollection(int flags); + static bool isFlow(int flags); + + uchar* ptr(); + const uchar* ptr() const; + + //! returns iterator pointing to the first node element + FileNodeIterator begin() const; + //! returns iterator pointing to the element following the last node element + FileNodeIterator end() const; + + /** @brief Reads node elements to the buffer with the specified format. + + Usually it is more convenient to use operator `>>` instead of this method. + @param fmt Specification of each array element. See @ref format_spec "format specification" + @param vec Pointer to the destination array. + @param len Number of bytes to read (buffer size limit). If it is greater than number of + remaining elements then all of them will be read. + */ + void readRaw( const String& fmt, void* vec, size_t len ) const; + + /** Internal method used when reading FileStorage. + Sets the type (int, real or string) and value of the previously created node. + */ + void setValue( int type, const void* value, int len=-1 ); + + //! Simplified reading API to use with bindings. + CV_WRAP double real() const; + //! Simplified reading API to use with bindings. + CV_WRAP std::string string() const; + //! Simplified reading API to use with bindings. + CV_WRAP Mat mat() const; + + //protected: + FileNode(FileStorage::Impl* fs, size_t blockIdx, size_t ofs); + + FileStorage::Impl* fs; + size_t blockIdx; + size_t ofs; +}; + + +/** @brief used to iterate through sequences and mappings. + + A standard STL notation, with node.begin(), node.end() denoting the beginning and the end of a + sequence, stored in node. See the data reading sample in the beginning of the section. + */ +class CV_EXPORTS FileNodeIterator +{ +public: + /** @brief The constructors. + + These constructors are used to create a default iterator, set it to specific element in a file node + or construct it from another iterator. + */ + FileNodeIterator(); + + /** @overload + @param node File node - the collection to iterate over; + it can be a scalar (equivalent to 1-element collection) or "none" (equivalent to empty collection). + @param seekEnd - true if iterator needs to be set after the last element of the node; + that is: + * node.begin() => FileNodeIterator(node, false) + * node.end() => FileNodeIterator(node, true) + */ + FileNodeIterator(const FileNode& node, bool seekEnd); + + /** @overload + @param it Iterator to be used as initialization for the created iterator. + */ + FileNodeIterator(const FileNodeIterator& it); + + FileNodeIterator& operator=(const FileNodeIterator& it); + + //! returns the currently observed element + FileNode operator *() const; + + //! moves iterator to the next node + FileNodeIterator& operator ++ (); + //! moves iterator to the next node + FileNodeIterator operator ++ (int); + //! moves iterator forward by the specified offset (possibly negative) + FileNodeIterator& operator += (int ofs); + + /** @brief Reads node elements to the buffer with the specified format. + + Usually it is more convenient to use operator `>>` instead of this method. + @param fmt Specification of each array element. See @ref format_spec "format specification" + @param vec Pointer to the destination array. + @param len Number of bytes to read (buffer size limit). If it is greater than number of + remaining elements then all of them will be read. + */ + FileNodeIterator& readRaw( const String& fmt, void* vec, + size_t len=(size_t)INT_MAX ); + + //! returns the number of remaining (not read yet) elements + size_t remaining() const; + + bool equalTo(const FileNodeIterator& it) const; + +protected: + FileStorage::Impl* fs; + size_t blockIdx; + size_t ofs; + size_t blockSize; + size_t nodeNElems; + size_t idx; +}; + +//! @} core_xml + +/////////////////// XML & YAML I/O implementation ////////////////// + +CV_EXPORTS void write( FileStorage& fs, const String& name, int value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, int64_t value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, float value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, double value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, const String& value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, const Mat& value ); +CV_EXPORTS void write( FileStorage& fs, const String& name, const SparseMat& value ); +#ifdef CV__LEGACY_PERSISTENCE +CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); +CV_EXPORTS void write( FileStorage& fs, const String& name, const std::vector& value); +#endif + +CV_EXPORTS void writeScalar( FileStorage& fs, int value ); +CV_EXPORTS void writeScalar( FileStorage& fs, int64_t value ); +CV_EXPORTS void writeScalar( FileStorage& fs, float value ); +CV_EXPORTS void writeScalar( FileStorage& fs, double value ); +CV_EXPORTS void writeScalar( FileStorage& fs, const String& value ); + +CV_EXPORTS void read(const FileNode& node, int& value, int default_value); +CV_EXPORTS void read(const FileNode& node, int64_t& value, int64_t default_value); +CV_EXPORTS void read(const FileNode& node, float& value, float default_value); +CV_EXPORTS void read(const FileNode& node, double& value, double default_value); +CV_EXPORTS void read(const FileNode& node, std::string& value, const std::string& default_value); +CV_EXPORTS void read(const FileNode& node, Mat& mat, const Mat& default_mat = Mat() ); +CV_EXPORTS void read(const FileNode& node, SparseMat& mat, const SparseMat& default_mat = SparseMat() ); +#ifdef CV__LEGACY_PERSISTENCE +CV_EXPORTS void read(const FileNode& node, std::vector& keypoints); +CV_EXPORTS void read(const FileNode& node, std::vector& matches); +#endif +CV_EXPORTS void read(const FileNode& node, KeyPoint& value, const KeyPoint& default_value); +CV_EXPORTS void read(const FileNode& node, DMatch& value, const DMatch& default_value); + +template static inline void read(const FileNode& node, Point_<_Tp>& value, const Point_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 2 ? default_value : Point_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); +} + +template static inline void read(const FileNode& node, Point3_<_Tp>& value, const Point3_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 3 ? default_value : Point3_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), + saturate_cast<_Tp>(temp[2])); +} + +template static inline void read(const FileNode& node, Size_<_Tp>& value, const Size_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 2 ? default_value : Size_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); +} + +template static inline void read(const FileNode& node, Complex<_Tp>& value, const Complex<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 2 ? default_value : Complex<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1])); +} + +template static inline void read(const FileNode& node, Rect_<_Tp>& value, const Rect_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 4 ? default_value : Rect_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), + saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); +} + +template static inline void read(const FileNode& node, Vec<_Tp, cn>& value, const Vec<_Tp, cn>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != cn ? default_value : Vec<_Tp, cn>(&temp[0]); +} + +template static inline void read(const FileNode& node, Matx<_Tp, m, n>& value, const Matx<_Tp, m, n>& default_matx = Matx<_Tp, m, n>()) +{ + Mat temp; + read(node, temp); // read as a Mat class + + if (temp.empty()) + value = default_matx; + else + value = Matx<_Tp, m, n>(temp); +} + +template static inline void read(const FileNode& node, Scalar_<_Tp>& value, const Scalar_<_Tp>& default_value) +{ + std::vector<_Tp> temp; FileNodeIterator it = node.begin(); it >> temp; + value = temp.size() != 4 ? default_value : Scalar_<_Tp>(saturate_cast<_Tp>(temp[0]), saturate_cast<_Tp>(temp[1]), + saturate_cast<_Tp>(temp[2]), saturate_cast<_Tp>(temp[3])); +} + +static inline void read(const FileNode& node, Range& value, const Range& default_value) +{ + Point2i temp(value.start, value.end); const Point2i default_temp = Point2i(default_value.start, default_value.end); + read(node, temp, default_temp); + value.start = temp.x; value.end = temp.y; +} + +/** @brief Writes string to a file storage. + */ +CV_EXPORTS FileStorage& operator << (FileStorage& fs, const String& str); + +//! @cond IGNORED + +namespace internal +{ + class CV_EXPORTS WriteStructContext + { + public: + WriteStructContext(FileStorage& _fs, const String& name, int flags, const String& typeName = String()); + ~WriteStructContext(); + private: + FileStorage* fs; + }; + + template class VecWriterProxy + { + public: + VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} + void operator()(const std::vector<_Tp>& vec) const + { + size_t count = vec.size(); + for (size_t i = 0; i < count; i++) + write(*fs, vec[i]); + } + private: + FileStorage* fs; + }; + + template class VecWriterProxy<_Tp, 1> + { + public: + VecWriterProxy( FileStorage* _fs ) : fs(_fs) {} + void operator()(const std::vector<_Tp>& vec) const + { + int _fmt = traits::SafeFmt<_Tp>::fmt; + char fmt[] = { (char)((_fmt >> 8) + '1'), (char)_fmt, '\0' }; + fs->writeRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, vec.size() * sizeof(_Tp)); + } + private: + FileStorage* fs; + }; + + template class VecReaderProxy + { + public: + VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} + void operator()(std::vector<_Tp>& vec, size_t count) const + { + count = std::min(count, it->remaining()); + vec.resize(count); + for (size_t i = 0; i < count; i++, ++(*it)) + read(**it, vec[i], _Tp()); + } + private: + FileNodeIterator* it; + }; + + template class VecReaderProxy<_Tp, 1> + { + public: + VecReaderProxy( FileNodeIterator* _it ) : it(_it) {} + void operator()(std::vector<_Tp>& vec, size_t count) const + { + size_t remaining = it->remaining(); + size_t cn = DataType<_Tp>::channels; + int _fmt = traits::SafeFmt<_Tp>::fmt; + CV_Assert((_fmt >> 8) < 9); + char fmt[] = { (char)((_fmt >> 8)+'1'), (char)_fmt, '\0' }; + CV_Assert((remaining % cn) == 0); + size_t remaining1 = remaining / cn; + count = count > remaining1 ? remaining1 : count; + vec.resize(count); + it->readRaw(fmt, !vec.empty() ? (uchar*)&vec[0] : 0, count*sizeof(_Tp)); + } + private: + FileNodeIterator* it; + }; + +} // internal + +//! @endcond + +template static inline +void write(FileStorage& fs, const _Tp& value) +{ + write(fs, String(), value); +} + +template<> inline +void write( FileStorage& fs, const int& value ) +{ + writeScalar(fs, value); +} + +template<> inline +void write( FileStorage& fs, const float& value ) +{ + writeScalar(fs, value); +} + +template<> inline +void write( FileStorage& fs, const double& value ) +{ + writeScalar(fs, value); +} + +template<> inline +void write( FileStorage& fs, const String& value ) +{ + writeScalar(fs, value); +} + +template static inline +void write(FileStorage& fs, const Point_<_Tp>& pt ) +{ + write(fs, pt.x); + write(fs, pt.y); +} + +template static inline +void write(FileStorage& fs, const Point3_<_Tp>& pt ) +{ + write(fs, pt.x); + write(fs, pt.y); + write(fs, pt.z); +} + +template static inline +void write(FileStorage& fs, const Size_<_Tp>& sz ) +{ + write(fs, sz.width); + write(fs, sz.height); +} + +template static inline +void write(FileStorage& fs, const Complex<_Tp>& c ) +{ + write(fs, c.re); + write(fs, c.im); +} + +template static inline +void write(FileStorage& fs, const Rect_<_Tp>& r ) +{ + write(fs, r.x); + write(fs, r.y); + write(fs, r.width); + write(fs, r.height); +} + +template static inline +void write(FileStorage& fs, const Vec<_Tp, cn>& v ) +{ + for(int i = 0; i < cn; i++) + write(fs, v.val[i]); +} + +template static inline +void write(FileStorage& fs, const Matx<_Tp, m, n>& x ) +{ + write(fs, Mat(x)); // write as a Mat class +} + +template static inline +void write(FileStorage& fs, const Scalar_<_Tp>& s ) +{ + write(fs, s.val[0]); + write(fs, s.val[1]); + write(fs, s.val[2]); + write(fs, s.val[3]); +} + +static inline +void write(FileStorage& fs, const Range& r ) +{ + write(fs, r.start); + write(fs, r.end); +} + +template static inline +void write( FileStorage& fs, const std::vector<_Tp>& vec ) +{ + cv::internal::VecWriterProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> w(&fs); + w(vec); +} + +template static inline +void write(FileStorage& fs, const String& name, const Point_<_Tp>& pt ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, pt); +} + +template static inline +void write(FileStorage& fs, const String& name, const Point3_<_Tp>& pt ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, pt); +} + +template static inline +void write(FileStorage& fs, const String& name, const Size_<_Tp>& sz ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, sz); +} + +template static inline +void write(FileStorage& fs, const String& name, const Complex<_Tp>& c ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, c); +} + +template static inline +void write(FileStorage& fs, const String& name, const Rect_<_Tp>& r ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, r); +} + +template static inline +void write(FileStorage& fs, const String& name, const Vec<_Tp, cn>& v ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, v); +} + +template static inline +void write(FileStorage& fs, const String& name, const Matx<_Tp, m, n>& x ) +{ + write(fs, name, Mat(x)); // write as a Mat class +} + +template static inline +void write(FileStorage& fs, const String& name, const Scalar_<_Tp>& s ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, s); +} + +static inline +void write(FileStorage& fs, const String& name, const Range& r ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, r); +} + +static inline +void write(FileStorage& fs, const String& name, const KeyPoint& kpt) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, kpt.pt.x); + write(fs, kpt.pt.y); + write(fs, kpt.size); + write(fs, kpt.angle); + write(fs, kpt.response); + write(fs, kpt.octave); + write(fs, kpt.class_id); +} + +static inline +void write(FileStorage& fs, const String& name, const DMatch& m) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+FileNode::FLOW); + write(fs, m.queryIdx); + write(fs, m.trainIdx); + write(fs, m.imgIdx); + write(fs, m.distance); +} + +template::value >::type* = nullptr> +static inline void write( FileStorage& fs, const String& name, const _Tp& val ) +{ + write(fs, name, static_cast(val)); +} + +template static inline +void write( FileStorage& fs, const String& name, const std::vector<_Tp>& vec ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); + write(fs, vec); +} + +template static inline +void write( FileStorage& fs, const String& name, const std::vector< std::vector<_Tp> >& vec ) +{ + cv::internal::WriteStructContext ws(fs, name, FileNode::SEQ); + for(size_t i = 0; i < vec.size(); i++) + { + cv::internal::WriteStructContext ws_(fs, name, FileNode::SEQ+(traits::SafeFmt<_Tp>::fmt != 0 ? FileNode::FLOW : 0)); + write(fs, vec[i]); + } +} + +#ifdef CV__LEGACY_PERSISTENCE +// This code is not needed anymore, but it is preserved here to keep source compatibility +// Implementation is similar to templates instantiations +static inline void write(FileStorage& fs, const KeyPoint& kpt) { write(fs, String(), kpt); } +static inline void write(FileStorage& fs, const DMatch& m) { write(fs, String(), m); } +static inline void write(FileStorage& fs, const std::vector& vec) +{ + cv::internal::VecWriterProxy w(&fs); + w(vec); +} +static inline void write(FileStorage& fs, const std::vector& vec) +{ + cv::internal::VecWriterProxy w(&fs); + w(vec); + +} +#endif + + +static inline +void read(const FileNode& node, bool& value, bool default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = temp != 0; +} + +static inline +void read(const FileNode& node, uchar& value, uchar default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +static inline +void read(const FileNode& node, schar& value, schar default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +static inline +void read(const FileNode& node, ushort& value, ushort default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +static inline +void read(const FileNode& node, short& value, short default_value) +{ + int temp; + read(node, temp, (int)default_value); + value = saturate_cast(temp); +} + +template static inline +void read( FileNodeIterator& it, std::vector<_Tp>& vec, size_t maxCount = (size_t)INT_MAX ) +{ + cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); + r(vec, maxCount); +} + +template::value >::type* = nullptr> +static inline void read(const FileNode& node, _Tp& value, const _Tp& default_value = static_cast<_Tp>(0)) +{ + int temp; + read(node, temp, static_cast(default_value)); + value = static_cast<_Tp>(temp); +} + +template static inline +void read( const FileNode& node, std::vector<_Tp>& vec, const std::vector<_Tp>& default_value = std::vector<_Tp>() ) +{ + if(node.empty()) + vec = default_value; + else + { + FileNodeIterator it = node.begin(); + read( it, vec ); + } +} + +static inline +void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) +{ + if(node.empty()) + vec = default_value; + else + read(node, vec); +} + +static inline +void read( const FileNode& node, std::vector& vec, const std::vector& default_value ) +{ + if(node.empty()) + vec = default_value; + else + read(node, vec); +} + +/** @brief Writes data to a file storage. + */ +template static inline +FileStorage& operator << (FileStorage& fs, const _Tp& value) +{ + if( !fs.isOpened() ) + return fs; + if( fs.state == FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP ) + CV_Error( Error::StsError, "No element name has been given" ); + write( fs, fs.elname, value ); + if( fs.state & FileStorage::INSIDE_MAP ) + fs.state = FileStorage::NAME_EXPECTED + FileStorage::INSIDE_MAP; + return fs; +} + +/** @brief Writes data to a file storage. + */ +static inline +FileStorage& operator << (FileStorage& fs, const char* str) +{ + return (fs << String(str)); +} + +/** @brief Writes data to a file storage. + */ +static inline +FileStorage& operator << (FileStorage& fs, char* value) +{ + return (fs << String(value)); +} + +/** @brief Reads data from a file storage. + */ +template static inline +FileNodeIterator& operator >> (FileNodeIterator& it, _Tp& value) +{ + read( *it, value, _Tp()); + return ++it; +} + +/** @brief Reads data from a file storage. + */ +template static inline +FileNodeIterator& operator >> (FileNodeIterator& it, std::vector<_Tp>& vec) +{ + cv::internal::VecReaderProxy<_Tp, traits::SafeFmt<_Tp>::fmt != 0> r(&it); + r(vec, (size_t)INT_MAX); + return it; +} + +/** @brief Reads data from a file storage. + */ +template static inline +void operator >> (const FileNode& n, _Tp& value) +{ + read( n, value, _Tp()); +} + +/** @brief Reads data from a file storage. + */ +template static inline +void operator >> (const FileNode& n, std::vector<_Tp>& vec) +{ + FileNodeIterator it = n.begin(); + it >> vec; +} + +/** @brief Reads KeyPoint from a file storage. +*/ +//It needs special handling because it contains two types of fields, int & float. +static inline +void operator >> (const FileNode& n, KeyPoint& kpt) +{ + FileNodeIterator it = n.begin(); + it >> kpt.pt.x >> kpt.pt.y >> kpt.size >> kpt.angle >> kpt.response >> kpt.octave >> kpt.class_id; +} + +#ifdef CV__LEGACY_PERSISTENCE +static inline +void operator >> (const FileNode& n, std::vector& vec) +{ + read(n, vec); +} +static inline +void operator >> (const FileNode& n, std::vector& vec) +{ + read(n, vec); +} +#endif + +/** @brief Reads DMatch from a file storage. +*/ +//It needs special handling because it contains two types of fields, int & float. +static inline +void operator >> (const FileNode& n, DMatch& m) +{ + FileNodeIterator it = n.begin(); + it >> m.queryIdx >> m.trainIdx >> m.imgIdx >> m.distance; +} + +CV_EXPORTS bool operator == (const FileNodeIterator& it1, const FileNodeIterator& it2); +CV_EXPORTS bool operator != (const FileNodeIterator& it1, const FileNodeIterator& it2); + +static inline +ptrdiff_t operator - (const FileNodeIterator& it1, const FileNodeIterator& it2) +{ + return it2.remaining() - it1.remaining(); +} + +static inline +bool operator < (const FileNodeIterator& it1, const FileNodeIterator& it2) +{ + return it1.remaining() > it2.remaining(); +} + +} // cv + +#endif // OPENCV_CORE_PERSISTENCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp index ab96ce2bae..e39065020c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.hpp @@ -1,1696 +1,1696 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang -#ifndef OPENCV_CORE_QUATERNION_HPP -#define OPENCV_CORE_QUATERNION_HPP - -#include -#include -#include -namespace cv -{ -//! @addtogroup core_quaternion -//! @{ - -//! Unit quaternion flag -enum QuatAssumeType -{ - /** - * This flag is specified by default. - * If this flag is specified, the input quaternions are assumed to be not unit quaternions. - * It can guarantee the correctness of the calculations, - * although the calculation speed will be slower than the flag QUAT_ASSUME_UNIT. - */ - QUAT_ASSUME_NOT_UNIT, - /** - * If this flag is specified, the input quaternions are assumed to be unit quaternions which - * will save some computations. However, if this flag is specified without unit quaternion, - * the program correctness of the result will not be guaranteed. - */ - QUAT_ASSUME_UNIT -}; - -class QuatEnum -{ -public: - /** @brief Enum of Euler angles type. - * - * Without considering the possibility of using two different convertions for the definition of the rotation axes , - * there exists twelve possible sequences of rotation axes, divided into two groups: - * - Proper Euler angles (Z-X-Z, X-Y-X, Y-Z-Y, Z-Y-Z, X-Z-X, Y-X-Y) - * - Tait–Bryan angles (X-Y-Z, Y-Z-X, Z-X-Y, X-Z-Y, Z-Y-X, Y-X-Z). - * - * The three elemental rotations may be [extrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_extrinsic_rotations) - * (rotations about the axes *xyz* of the original coordinate system, which is assumed to remain motionless), - * or [intrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations)(rotations about the axes of the rotating coordinate system *XYZ*, solidary with the moving body, which changes its orientation after each elemental rotation). - * - * - * Extrinsic and intrinsic rotations are relevant. - * - * The definition of the Euler angles is as following, - * - \f$\theta_1 \f$ represents the first rotation angle, - * - \f$\theta_2 \f$ represents the second rotation angle, - * - \f$\theta_3 \f$ represents the third rotation angle. - * - * For intrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =X(\theta_1) Y(\theta_2) Z(\theta_3) \f] - * For extrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =Z({\theta_3}) Y({\theta_2}) X({\theta_1})\f] - * where - * \f[X({\theta_1})={\begin{bmatrix}1&0&0\\0&\cos {\theta_1} &-\sin {\theta_1} \\0&\sin {\theta_1} &\cos {\theta_1} \\\end{bmatrix}}, - * Y({\theta_2})={\begin{bmatrix}\cos \theta_{2}&0&\sin \theta_{2}\\0&1 &0 \\\ -sin \theta_2& 0&\cos \theta_{2} \\\end{bmatrix}}, - * Z({\theta_3})={\begin{bmatrix}\cos\theta_{3} &-\sin \theta_3&0\\\sin \theta_3 &\cos \theta_3 &0\\0&0&1\\\end{bmatrix}}. - * \f] - * - * The function is designed according to this set of conventions: - * - [Right handed](https://en.wikipedia.org/wiki/Right_hand_rule) reference frames are adopted, and the [right hand rule](https://en.wikipedia.org/wiki/Right_hand_rule) is used to determine the sign of angles. - * - Each matrix is meant to represent an [active rotation](https://en.wikipedia.org/wiki/Active_and_passive_transformation) (the composing and composed matrices - * are supposed to act on the coordinates of vectors defined in the initial fixed reference frame and give as a result the coordinates of a rotated vector defined in the same reference frame). - * - For \f$\theta_1\f$ and \f$\theta_3\f$, the valid range is (−π, π]. - * - * For \f$\theta_2\f$, the valid range is [−π/2, π/2] or [0, π]. - * - * For Tait–Bryan angles, the valid range of \f$\theta_2\f$ is [−π/2, π/2]. When transforming a quaternion to Euler angles, the solution of Euler angles is unique in condition of \f$ \theta_2 \in (−π/2, π/2)\f$ . - * If \f$\theta_2 = −π/2 \f$ or \f$ \theta_2 = π/2\f$, there are infinite solutions. The common name for this situation is gimbal lock. - * For Proper Euler angles,the valid range of \f$\theta_2\f$ is in [0, π]. The solutions of Euler angles are unique in condition of \f$ \theta_2 \in (0, π)\f$ . If \f$\theta_2 =0 \f$ or \f$\theta_2 =π \f$, - * there are infinite solutions and gimbal lock will occur. - */ - enum EulerAnglesType - { - INT_XYZ, ///< Intrinsic rotations with the Euler angles type X-Y-Z - INT_XZY, ///< Intrinsic rotations with the Euler angles type X-Z-Y - INT_YXZ, ///< Intrinsic rotations with the Euler angles type Y-X-Z - INT_YZX, ///< Intrinsic rotations with the Euler angles type Y-Z-X - INT_ZXY, ///< Intrinsic rotations with the Euler angles type Z-X-Y - INT_ZYX, ///< Intrinsic rotations with the Euler angles type Z-Y-X - INT_XYX, ///< Intrinsic rotations with the Euler angles type X-Y-X - INT_XZX, ///< Intrinsic rotations with the Euler angles type X-Z-X - INT_YXY, ///< Intrinsic rotations with the Euler angles type Y-X-Y - INT_YZY, ///< Intrinsic rotations with the Euler angles type Y-Z-Y - INT_ZXZ, ///< Intrinsic rotations with the Euler angles type Z-X-Z - INT_ZYZ, ///< Intrinsic rotations with the Euler angles type Z-Y-Z - - EXT_XYZ, ///< Extrinsic rotations with the Euler angles type X-Y-Z - EXT_XZY, ///< Extrinsic rotations with the Euler angles type X-Z-Y - EXT_YXZ, ///< Extrinsic rotations with the Euler angles type Y-X-Z - EXT_YZX, ///< Extrinsic rotations with the Euler angles type Y-Z-X - EXT_ZXY, ///< Extrinsic rotations with the Euler angles type Z-X-Y - EXT_ZYX, ///< Extrinsic rotations with the Euler angles type Z-Y-X - EXT_XYX, ///< Extrinsic rotations with the Euler angles type X-Y-X - EXT_XZX, ///< Extrinsic rotations with the Euler angles type X-Z-X - EXT_YXY, ///< Extrinsic rotations with the Euler angles type Y-X-Y - EXT_YZY, ///< Extrinsic rotations with the Euler angles type Y-Z-Y - EXT_ZXZ, ///< Extrinsic rotations with the Euler angles type Z-X-Z - EXT_ZYZ, ///< Extrinsic rotations with the Euler angles type Z-Y-Z - #ifndef CV_DOXYGEN - EULER_ANGLES_MAX_VALUE - #endif - }; - -}; - -template class Quat; -template std::ostream& operator<<(std::ostream&, const Quat<_Tp>&); - -/** - * Quaternion is a number system that extends the complex numbers. It can be expressed as a - * rotation in three-dimensional space. - * A quaternion is generally represented in the form: - * \f[q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f] - * \f[q = [w, x, y, z]\f] - * \f[q = [w, \boldsymbol{v}] \f] - * \f[q = ||q||[\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] - * \f[q = ||q||[\cos\psi, \boldsymbol{u}\sin\psi]\f] - * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ represents rotation angle, - * \f$\boldsymbol{u} = [u_x, u_y, u_z]\f$ represents normalized rotation axis, - * and \f$||q||\f$ represents the norm of \f$q\f$. - * - * A unit quaternion is usually represents rotation, which has the form: - * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] - * - * To create a quaternion representing the rotation around the axis \f$\boldsymbol{u}\f$ - * with angle \f$\theta\f$, you can use - * ``` - * using namespace cv; - * double angle = CV_PI; - * Vec3d axis = {0, 0, 1}; - * Quatd q = Quatd::createFromAngleAxis(angle, axis); - * ``` - * - * You can simply use four same type number to create a quaternion - * ``` - * Quatd q(1, 2, 3, 4); - * ``` - * Or use a Vec4d or Vec4f vector. - * ``` - * Vec4d vec{1, 2, 3, 4}; - * Quatd q(vec); - * ``` - * - * ``` - * Vec4f vec{1, 2, 3, 4}; - * Quatf q(vec); - * ``` - * - * If you already have a 3x3 rotation matrix R, then you can use - * ``` - * Quatd q = Quatd::createFromRotMat(R); - * ``` - * - * If you already have a rotation vector rvec which has the form of `angle * axis`, then you can use - * ``` - * Quatd q = Quatd::createFromRvec(rvec); - * ``` - * - * To extract the rotation matrix from quaternion, see toRotMat3x3() - * - * To extract the Vec4d or Vec4f, see toVec() - * - * To extract the rotation vector, see toRotVec() - * - * If there are two quaternions \f$q_0, q_1\f$ are needed to interpolate, you can use nlerp(), slerp() or spline() - * ``` - * Quatd::nlerp(q0, q1, t) - * - * Quatd::slerp(q0, q1, t) - * - * Quatd::spline(q0, q0, q1, q1, t) - * ``` - * spline can smoothly connect rotations of multiple quaternions - * - * Three ways to get an element in Quaternion - * ``` - * Quatf q(1,2,3,4); - * std::cout << q.w << std::endl; // w=1, x=2, y=3, z=4 - * std::cout << q[0] << std::endl; // q[0]=1, q[1]=2, q[2]=3, q[3]=4 - * std::cout << q.at(0) << std::endl; - * ``` - */ -template -class Quat -{ - static_assert(std::is_floating_point<_Tp>::value, "Quaternion only make sense with type of float or double"); - using value_type = _Tp; -public: - static constexpr _Tp CV_QUAT_EPS = (_Tp)1.e-6; - static constexpr _Tp CV_QUAT_CONVERT_THRESHOLD = (_Tp)1.e-6; - - Quat(); - - /** - * @brief From Vec4d or Vec4f. - */ - explicit Quat(const Vec<_Tp, 4> &coeff); - - /** - * @brief from four numbers. - */ - Quat(_Tp w, _Tp x, _Tp y, _Tp z); - - /** - * @brief from an angle, axis. Axis will be normalized in this function. And - * it generates - * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] - * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ is the rotation angle. - */ - static Quat<_Tp> createFromAngleAxis(const _Tp angle, const Vec<_Tp, 3> &axis); - - /** - * @brief from a 3x3 rotation matrix. - */ - static Quat<_Tp> createFromRotMat(InputArray R); - - /** - * @brief from a rotation vector - * \f$r\f$ has the form \f$\theta \cdot \boldsymbol{u}\f$, where \f$\theta\f$ - * represents rotation angle and \f$\boldsymbol{u}\f$ represents normalized rotation axis. - * - * Angle and axis could be easily derived as: - * \f[ - * \begin{equation} - * \begin{split} - * \psi &= ||r||\\ - * \boldsymbol{u} &= \frac{r}{\theta} - * \end{split} - * \end{equation} - * \f] - * Then a quaternion can be calculated by - * \f[q = [\cos\psi, \boldsymbol{u}\sin\psi]\f] - * where \f$\psi = \theta / 2 \f$ - */ - static Quat<_Tp> createFromRvec(InputArray rvec); - - /** - * @brief - * from Euler angles - * - * A quaternion can be generated from Euler angles by combining the quaternion representations of the Euler rotations. - * - * For example, if we use intrinsic rotations in the order of X-Y-Z,\f$\theta_1 \f$ is rotation around the X-axis, \f$\theta_2 \f$ is rotation around the Y-axis, - * \f$\theta_3 \f$ is rotation around the Z-axis. The final quaternion q can be calculated by - * - * \f[ {q} = q_{X, \theta_1} q_{Y, \theta_2} q_{Z, \theta_3}\f] - * where \f$ q_{X, \theta_1} \f$ is created from @ref createFromXRot, \f$ q_{Y, \theta_2} \f$ is created from @ref createFromYRot, - * \f$ q_{Z, \theta_3} \f$ is created from @ref createFromZRot. - * @param angles the Euler angles in a vector of length 3 - * @param eulerAnglesType the convertion Euler angles type - */ - static Quat<_Tp> createFromEulerAngles(const Vec<_Tp, 3> &angles, QuatEnum::EulerAnglesType eulerAnglesType); - - /** - * @brief get a quaternion from a rotation about the Y-axis by \f$\theta\f$ . - * \f[q = \cos(\theta/2)+0 i+ sin(\theta/2) j +0k \f] - */ - static Quat<_Tp> createFromYRot(const _Tp theta); - - /** - * @brief get a quaternion from a rotation about the X-axis by \f$\theta\f$ . - * \f[q = \cos(\theta/2)+sin(\theta/2) i +0 j +0 k \f] - */ - static Quat<_Tp> createFromXRot(const _Tp theta); - - /** - * @brief get a quaternion from a rotation about the Z-axis by \f$\theta\f$. - * \f[q = \cos(\theta/2)+0 i +0 j +sin(\theta/2) k \f] - */ - static Quat<_Tp> createFromZRot(const _Tp theta); - - /** - * @brief a way to get element. - * @param index over a range [0, 3]. - * - * A quaternion q - * - * q.at(0) is equivalent to q.w, - * - * q.at(1) is equivalent to q.x, - * - * q.at(2) is equivalent to q.y, - * - * q.at(3) is equivalent to q.z. - */ - _Tp at(size_t index) const; - - /** - * @brief return the conjugate of this quaternion. - * \f[q.conjugate() = (w, -x, -y, -z).\f] - */ - Quat<_Tp> conjugate() const; - - /** - * - * @brief return the value of exponential value. - * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||})\sin||\boldsymbol{v}||\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example: - * ``` - * Quatd q{1,2,3,4}; - * cout << exp(q) << endl; - * ``` - */ - template - friend Quat exp(const Quat &q); - - /** - * @brief return the value of exponential value. - * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q{1,2,3,4}; - * cout << q.exp() << endl; - * ``` - */ - Quat<_Tp> exp() const; - - /** - * @brief return the value of logarithm function. - * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}.\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q1{1,2,3,4}; - * cout << log(q1) << endl; - * ``` - */ - template - friend Quat log(const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return the value of logarithm function. - * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}\f]. - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.log(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * Quatd q1(1,2,3,4); - * q1.normalize().log(assumeUnit); - * ``` - */ - Quat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of power function with index \f$x\f$. - * \f[q^x = ||q||(cos(x\theta) + \boldsymbol{u}sin(x\theta))).\f] - * @param q a quaternion. - * @param x index of exponentiation. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * power(q, 2.0); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * double angle = CV_PI; - * Vec3d axis{0, 0, 1}; - * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle - * power(q1, 2.0, assumeUnit);//This assumeUnit means q1 is a unit quaternion. - * ``` - * @note the type of the index should be the same as the quaternion. - */ - template - friend Quat power(const Quat &q, const T x, QuatAssumeType assumeUnit); - - /** - * @brief return the value of power function with index \f$x\f$. - * \f[q^x = ||q||(\cos(x\theta) + \boldsymbol{u}\sin(x\theta))).\f] - * @param x index of exponentiation. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.power(2.0); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * double angle = CV_PI; - * Vec3d axis{0, 0, 1}; - * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle - * q1.power(2.0, assumeUnit); //This assumeUnt means q1 is a unit quaternion - * ``` - */ - Quat<_Tp> power(const _Tp x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return \f$\sqrt{q}\f$. - * @param q a quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatf q(1,2,3,4); - * sqrt(q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = {1,0,0,0}; - * sqrt(q, assumeUnit); //This assumeUnit means q is a unit quaternion. - * ``` - */ - template - friend Quat sqrt(const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return \f$\sqrt{q}\f$. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatf q(1,2,3,4); - * q.sqrt(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = {1,0,0,0}; - * q.sqrt(assumeUnit); //This assumeUnit means q is a unit quaternion - * ``` - */ - Quat<_Tp> sqrt(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the value of power function with quaternion \f$q\f$. - * \f[p^q = e^{q\ln(p)}.\f] - * @param p base quaternion of power function. - * @param q index quaternion of power function. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion \f$p\f$ assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd p(1,2,3,4); - * Quatd q(5,6,7,8); - * power(p, q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * p = p.normalize(); - * power(p, q, assumeUnit); //This assumeUnit means p is a unit quaternion - * ``` - */ - template - friend Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return the value of power function with quaternion \f$q\f$. - * \f[p^q = e^{q\ln(p)}.\f] - * @param q index quaternion of power function. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd p(1,2,3,4); - * Quatd q(5,6,7,8); - * p.power(q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * p = p.normalize(); - * p.power(q, assumeUnit); //This assumeUnit means p is a unit quaternion - * ``` - */ - Quat<_Tp> power(const Quat<_Tp> &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. - * \f[p \times q = \frac{pq- qp}{2}\f] - * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}\f] - * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k \f] - * - * For example - * ``` - * Quatd q{1,2,3,4}; - * Quatd p{5,6,7,8}; - * crossProduct(p, q); - * ``` - */ - template - friend Quat crossProduct(const Quat &p, const Quat &q); - - /** - * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. - * \f[p \times q = \frac{pq- qp}{2}.\f] - * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}.\f] - * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k. \f] - * - * For example - * ``` - * Quatd q{1,2,3,4}; - * Quatd p{5,6,7,8}; - * p.crossProduct(q) - * ``` - */ - Quat<_Tp> crossProduct(const Quat<_Tp> &q) const; - - /** - * @brief return the norm of quaternion. - * \f[||q|| = \sqrt{w^2 + x^2 + y^2 + z^2}.\f] - */ - _Tp norm() const; - - /** - * @brief return a normalized \f$p\f$. - * \f[p = \frac{q}{||q||}\f] - * where \f$p\f$ satisfies \f$(p.x)^2 + (p.y)^2 + (p.z)^2 + (p.w)^2 = 1.\f$ - */ - Quat<_Tp> normalize() const; - - /** - * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ - * which satisfies \f$q * q^{-1} = 1\f$. - * @param q a quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * inv(q); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = q.normalize(); - * inv(q, assumeUnit);//This assumeUnit means p is a unit quaternion - * ``` - */ - template - friend Quat inv(const Quat &q, QuatAssumeType assumeUnit); - - /** - * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ - * satisfying \f$q * q^{-1} = 1\f$. - * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.inv(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q = q.normalize(); - * q.inv(assumeUnit); //assumeUnit means p is a unit quaternion - * ``` - */ - Quat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return sinh value of quaternion q, sinh could be calculated as: - * \f[\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * sinh(q); - * ``` - */ - template - friend Quat sinh(const Quat &q); - - /** - * @brief return sinh value of this quaternion, sinh could be calculated as: - * \f$\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f$ - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.sinh(); - * ``` - */ - Quat<_Tp> sinh() const; - - /** - * @brief return cosh value of quaternion q, cosh could be calculated as: - * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sin(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * cosh(q); - * ``` - */ - template - friend Quat cosh(const Quat &q); - - /** - * @brief return cosh value of this quaternion, cosh could be calculated as: - * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}sin(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.cosh(); - * ``` - */ - Quat<_Tp> cosh() const; - - /** - * @brief return tanh value of quaternion q, tanh could be calculated as: - * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * tanh(q); - * ``` - * @sa sinh, cosh - */ - template - friend Quat tanh(const Quat &q); - - /** - * @brief return tanh value of this quaternion, tanh could be calculated as: - * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.tanh(); - * ``` - * @sa sinh, cosh - */ - Quat<_Tp> tanh() const; - - /** - * @brief return tanh value of quaternion q, sin could be calculated as: - * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * sin(q); - * ``` - */ - template - friend Quat sin(const Quat &q); - - /** - * @brief return sin value of this quaternion, sin could be calculated as: - * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.sin(); - * ``` - */ - Quat<_Tp> sin() const; - - /** - * @brief return sin value of quaternion q, cos could be calculated as: - * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * cos(q); - * ``` - */ - template - friend Quat cos(const Quat &q); - - /** - * @brief return cos value of this quaternion, cos could be calculated as: - * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.cos(); - * ``` - */ - Quat<_Tp> cos() const; - - /** - * @brief return tan value of quaternion q, tan could be calculated as: - * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * tan(q); - * ``` - */ - template - friend Quat tan(const Quat &q); - - /** - * @brief return tan value of this quaternion, tan could be calculated as: - * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.tan(); - * ``` - */ - Quat<_Tp> tan() const; - - /** - * @brief return arcsin value of quaternion q, arcsin could be calculated as: - * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * asin(q); - * ``` - */ - template - friend Quat asin(const Quat &q); - - /** - * @brief return arcsin value of this quaternion, arcsin could be calculated as: - * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.asin(); - * ``` - */ - Quat<_Tp> asin() const; - - /** - * @brief return arccos value of quaternion q, arccos could be calculated as: - * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * acos(q); - * ``` - */ - template - friend Quat acos(const Quat &q); - - /** - * @brief return arccos value of this quaternion, arccos could be calculated as: - * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.acos(); - * ``` - */ - Quat<_Tp> acos() const; - - /** - * @brief return arctan value of quaternion q, arctan could be calculated as: - * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * atan(q); - * ``` - */ - template - friend Quat atan(const Quat &q); - - /** - * @brief return arctan value of this quaternion, arctan could be calculated as: - * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] - * where \f$\boldsymbol{v} = [x, y, z].\f$ - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.atan(); - * ``` - */ - Quat<_Tp> atan() const; - - /** - * @brief return arcsinh value of quaternion q, arcsinh could be calculated as: - * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * asinh(q); - * ``` - */ - template - friend Quat asinh(const Quat &q); - - /** - * @brief return arcsinh value of this quaternion, arcsinh could be calculated as: - * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.asinh(); - * ``` - */ - Quat<_Tp> asinh() const; - - /** - * @brief return arccosh value of quaternion q, arccosh could be calculated as: - * \f[arccosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * acosh(q); - * ``` - */ - template - friend Quat acosh(const Quat &q); - - /** - * @brief return arccosh value of this quaternion, arccosh could be calculated as: - * \f[arcosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.acosh(); - * ``` - */ - Quat<_Tp> acosh() const; - - /** - * @brief return arctanh value of quaternion q, arctanh could be calculated as: - * \f[arctanh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. - * @param q a quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * atanh(q); - * ``` - */ - template - friend Quat atanh(const Quat &q); - - /** - * @brief return arctanh value of this quaternion, arctanh could be calculated as: - * \f[arcsinh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.atanh(); - * ``` - */ - Quat<_Tp> atanh() const; - - /** - * @brief return true if this quaternion is a unit quaternion. - * @param eps tolerance scope of normalization. The eps could be defined as - * - * \f[eps = |1 - dotValue|\f] where \f[dotValue = (this.w^2 + this.x^2 + this,y^2 + this.z^2).\f] - * And this function will consider it is normalized when the dotValue over a range \f$[1-eps, 1+eps]\f$. - */ - bool isNormal(_Tp eps=CV_QUAT_EPS) const; - - /** - * @brief to throw an error if this quaternion is not a unit quaternion. - * @param eps tolerance scope of normalization. - * @sa isNormal - */ - void assertNormal(_Tp eps=CV_QUAT_EPS) const; - - /** - * @brief transform a quaternion to a 3x3 rotation matrix. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. Otherwise, this function will normalize this - * quaternion at first then do the transformation. - * - * @note Matrix A which is to be rotated should have the form - * \f[\begin{bmatrix} - * x_0& x_1& x_2&...&x_n\\ - * y_0& y_1& y_2&...&y_n\\ - * z_0& z_1& z_2&...&z_n - * \end{bmatrix}\f] - * where the same subscript represents a point. The shape of A assume to be [3, n] - * The points matrix A can be rotated by toRotMat3x3() * A. - * The result has 3 rows and n columns too. - - * For example - * ``` - * double angle = CV_PI; - * Vec3d axis{0,0,1}; - * Quatd q_unit = Quatd::createFromAngleAxis(angle, axis); //quaternion could also be get by interpolation by two or more quaternions. - * - * //assume there is two points (1,0,0) and (1,0,1) to be rotated - * Mat pointsA = (Mat_(2, 3) << 1,0,0,1,0,1); - * //change the shape - * pointsA = pointsA.t(); - * // rotate 180 degrees around the z axis - * Mat new_point = q_unit.toRotMat3x3() * pointsA; - * // print two points - * cout << new_point << endl; - * ``` - */ - Matx<_Tp, 3, 3> toRotMat3x3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief transform a quaternion to a 4x4 rotation matrix. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. Otherwise, this function will normalize this - * quaternion at first then do the transformation. - * - * The operations is similar as toRotMat3x3 - * except that the points matrix should have the form - * \f[\begin{bmatrix} - * x_0& x_1& x_2&...&x_n\\ - * y_0& y_1& y_2&...&y_n\\ - * z_0& z_1& z_2&...&z_n\\ - * 0&0&0&...&0 - * \end{bmatrix}\f] - * - * @sa toRotMat3x3 - */ - - Matx<_Tp, 4, 4> toRotMat4x4(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief transform the this quaternion to a Vec. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.toVec(); - * ``` - */ - Vec<_Tp, 4> toVec() const; - - /** - * @brief transform this quaternion to a Rotation vector. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. - * Rotation vector rVec is defined as: - * \f[ rVec = [\theta v_x, \theta v_y, \theta v_z]\f] - * where \f$\theta\f$ represents rotation angle, and \f$\boldsymbol{v}\f$ represents the normalized rotation axis. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.toRotVec(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q.normalize().toRotVec(assumeUnit); //answer is same as q.toRotVec(). - * ``` - */ - Vec<_Tp, 3> toRotVec(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief get the angle of quaternion, it returns the rotation angle. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. - * \f[\psi = 2 *arccos(\frac{w}{||q||})\f] - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.getAngle(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q.normalize().getAngle(assumeUnit);//same as q.getAngle(). - * ``` - * @note It always return the value between \f$[0, 2\pi]\f$. - */ - _Tp getAngle(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief get the axis of quaternion, it returns a vector of length 3. - * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and - * this function will save some computations. - * - * the unit axis \f$\boldsymbol{u}\f$ is defined by - * \f[\begin{equation} - * \begin{split} - * \boldsymbol{v} - * &= \boldsymbol{u} ||\boldsymbol{v}||\\ - * &= \boldsymbol{u}||q||sin(\frac{\theta}{2}) - * \end{split} - * \end{equation}\f] - * where \f$v=[x, y ,z]\f$ and \f$\theta\f$ represents rotation angle. - * - * - * For example - * ``` - * Quatd q(1,2,3,4); - * q.getAxis(); - * - * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; - * q.normalize().getAxis(assumeUnit);//same as q.getAxis() - * ``` - */ - Vec<_Tp, 3> getAxis(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; - - /** - * @brief return the dot between quaternion \f$q\f$ and this quaternion. - * - * dot(p, q) is a good metric of how close the quaternions are. - * Indeed, consider the unit quaternion difference \f$p^{-1} * q\f$, its real part is dot(p, q). - * At the same time its real part is equal to \f$\cos(\beta/2)\f$ where \f$\beta\f$ is - * an angle of rotation between p and q, i.e., - * Therefore, the closer dot(p, q) to 1, - * the smaller rotation between them. - * \f[p \cdot q = p.w \cdot q.w + p.x \cdot q.x + p.y \cdot q.y + p.z \cdot q.z\f] - * @param q the other quaternion. - * - * For example - * ``` - * Quatd q(1,2,3,4); - * Quatd p(5,6,7,8); - * p.dot(q); - * ``` - */ - _Tp dot(Quat<_Tp> q) const; - - /** - * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Linear Interpolation(Nlerp) - * For two quaternions, this interpolation curve can be displayed as: - * \f[Lerp(q_0, q_1, t) = (1 - t)q_0 + tq_1.\f] - * Obviously, the lerp will interpolate along a straight line if we think of \f$q_0\f$ and \f$q_1\f$ as a vector - * in a two-dimensional space. When \f$t = 0\f$, it returns \f$q_0\f$ and when \f$t= 1\f$, it returns \f$q_1\f$. - * \f$t\f$ should to be ranged in \f$[0, 1]\f$ normally. - * @param q0 a quaternion used in linear interpolation. - * @param q1 a quaternion used in linear interpolation. - * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. - * @note it returns a non-unit quaternion. - */ - static Quat<_Tp> lerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t); - - /** - * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Normalized Linear Interpolation(Nlerp). - * it returns a normalized quaternion of Linear Interpolation(Lerp). - * \f[ Nlerp(q_0, q_1, t) = \frac{(1 - t)q_0 + tq_1}{||(1 - t)q_0 + tq_1||}.\f] - * The interpolation will always choose the shortest path but the constant speed is not guaranteed. - * @param q0 a quaternion used in normalized linear interpolation. - * @param q1 a quaternion used in normalized linear interpolation. - * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. - * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all inputs - quaternion will be normalized inside the function. - * @sa lerp - */ - static Quat<_Tp> nlerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - @brief To calculate the interpolation between \f$q_0\f$ and \f$q_1\f$ by Spherical Linear - Interpolation(Slerp), which can be defined as: - \f[ Slerp(q_0, q_1, t) = \frac{\sin((1-t)\theta)}{\sin(\theta)}q_0 + \frac{\sin(t\theta)}{\sin(\theta)}q_1\f] - where \f$\theta\f$ can be calculated as: - \f[\theta=cos^{-1}(q_0\cdot q_1)\f] - resulting from the both of their norm is unit. - @param q0 a quaternion used in Slerp. - @param q1 a quaternion used in Slerp. - @param t percent of angle between \f$q_0\f$ and \f$q_1\f$ over a range [0, 1]. - @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternions. Otherwise, all input - quaternions will be normalized inside the function. - @param directChange if QUAT_ASSUME_UNIT, the interpolation will choose the nearest path. - @note If the interpolation angle is small, the error between Nlerp and Slerp is not so large. To improve efficiency and - avoid zero division error, we use Nlerp instead of Slerp. - */ - static Quat<_Tp> slerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, bool directChange=true); - - /** - * @brief To calculate the interpolation between \f$q_0\f$,\f$q_1\f$,\f$q_2\f$,\f$q_3\f$ by Spherical and quadrangle(Squad). This could be defined as: - * \f[Squad(q_i, s_i, s_{i+1}, q_{i+1}, t) = Slerp(Slerp(q_i, q_{i+1}, t), Slerp(s_i, s_{i+1}, t), 2t(1-t))\f] - * where - * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4})\f] - * - * The Squad expression is analogous to the \f$B\acute{e}zier\f$ curve, but involves spherical linear - * interpolation instead of simple linear interpolation. Each \f$s_i\f$ needs to be calculated by three - * quaternions. - * - * @param q0 the first quaternion. - * @param s0 the second quaternion. - * @param s1 the third quaternion. - * @param q1 thr fourth quaternion. - * @param t interpolation parameter of quadratic and linear interpolation over a range \f$[0, 1]\f$. - * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input - * quaternions will be normalized inside the function. - * @param directChange if QUAT_ASSUME_UNIT, squad will find the nearest path to interpolate. - * @sa interPoint, spline - */ - static Quat<_Tp> squad(const Quat<_Tp> &q0, const Quat<_Tp> &s0, - const Quat<_Tp> &s1, const Quat<_Tp> &q1, - const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, - bool directChange=true); - - /** - * @brief This is the part calculation of squad. - * To calculate the intermedia quaternion \f$s_i\f$ between each three quaternion - * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4}).\f] - * @param q0 the first quaternion. - * @param q1 the second quaternion. - * @param q2 the third quaternion. - * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input - * quaternions will be normalized inside the function. - * @sa squad - */ - static Quat<_Tp> interPoint(const Quat<_Tp> &q0, const Quat<_Tp> &q1, - const Quat<_Tp> &q2, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief to calculate a quaternion which is the result of a \f$C^1\f$ continuous - * spline curve constructed by squad at the ratio t. Here, the interpolation values are - * between \f$q_1\f$ and \f$q_2\f$. \f$q_0\f$ and \f$q_2\f$ are used to ensure the \f$C^1\f$ - * continuity. if t = 0, it returns \f$q_1\f$, if t = 1, it returns \f$q_2\f$. - * @param q0 the first input quaternion to ensure \f$C^1\f$ continuity. - * @param q1 the second input quaternion. - * @param q2 the third input quaternion. - * @param q3 the fourth input quaternion the same use of \f$q1\f$. - * @param t ratio over a range [0, 1]. - * @param assumeUnit if QUAT_ASSUME_UNIT, \f$q_0, q_1, q_2, q_3\f$ assume to be unit quaternion. Otherwise, all input - * quaternions will be normalized inside the function. - * - * For example: - * - * If there are three double quaternions \f$v_0, v_1, v_2\f$ waiting to be interpolated. - * - * Interpolation between \f$v_0\f$ and \f$v_1\f$ with a ratio \f$t_0\f$ could be calculated as - * ``` - * Quatd::spline(v0, v0, v1, v2, t0); - * ``` - * Interpolation between \f$v_1\f$ and \f$v_2\f$ with a ratio \f$t_0\f$ could be calculated as - * ``` - * Quatd::spline(v0, v1, v2, v2, t0); - * ``` - * @sa squad, slerp - */ - static Quat<_Tp> spline(const Quat<_Tp> &q0, const Quat<_Tp> &q1, - const Quat<_Tp> &q2, const Quat<_Tp> &q3, - const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - - /** - * @brief Return opposite quaternion \f$-p\f$ - * which satisfies \f$p + (-p) = 0.\f$ - * - * For example - * ``` - * Quatd q{1, 2, 3, 4}; - * std::cout << -q << std::endl; // [-1, -2, -3, -4] - * ``` - */ - Quat<_Tp> operator-() const; - - /** - * @brief return true if two quaternions p and q are nearly equal, i.e. when the absolute - * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_QUAT_EPS. - */ - bool operator==(const Quat<_Tp>&) const; - - /** - * @brief Addition operator of two quaternions p and q. - * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p + q << std::endl; //[6, 8, 10, 12] - * ``` - */ - Quat<_Tp> operator+(const Quat<_Tp>&) const; - - /** - * @brief Addition assignment operator of two quaternions p and q. - * It adds right operand to the left operand and assign the result to left operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p += q; // equivalent to p = p + q - * std::cout << p << std::endl; //[6, 8, 10, 12] - * - * ``` - */ - Quat<_Tp>& operator+=(const Quat<_Tp>&); - - /** - * @brief Subtraction operator of two quaternions p and q. - * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p - q << std::endl; //[-4, -4, -4, -4] - * ``` - */ - Quat<_Tp> operator-(const Quat<_Tp>&) const; - - /** - * @brief Subtraction assignment operator of two quaternions p and q. - * It subtracts right operand from the left operand and assign the result to left operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p -= q; // equivalent to p = p - q - * std::cout << p << std::endl; //[-4, -4, -4, -4] - * - * ``` - */ - Quat<_Tp>& operator-=(const Quat<_Tp>&); - - /** - * @brief Multiplication assignment operator of two quaternions q and p. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication: - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ - * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. - * \end{split} - * \end{equation} - * \f] - * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p *= q; // equivalent to p = p * q - * std::cout << p << std::endl; //[-60, 12, 30, 24] - * ``` - */ - Quat<_Tp>& operator*=(const Quat<_Tp>&); - - /** - * @brief Multiplication assignment operator of a quaternions and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z] * s\\ - * &=[w * s, x * s, y * s, z * s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * p *= s; // equivalent to p = p * s - * std::cout << p << std::endl; //[2.0, 4.0, 6.0, 8.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - Quat<_Tp>& operator*=(const _Tp s); - - /** - * @brief Multiplication operator of two quaternions q and p. - * Multiplies values on either side of the operator. - * - * Rule of quaternion multiplication: - * \f[ - * \begin{equation} - * \begin{split} - * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ - * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. - * \end{split} - * \end{equation} - * \f] - * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p * q << std::endl; //[-60, 12, 30, 24] - * ``` - */ - Quat<_Tp> operator*(const Quat<_Tp>&) const; - - /** - * @brief Division operator of a quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z] / s\\ - * &=[w/s, x/s, y/s, z/s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1, 1.5, 2] - * ``` - * @note the type of scalar should be equal to this quaternion. - */ - Quat<_Tp> operator/(const _Tp s) const; - - /** - * @brief Division operator of two quaternions p and q. - * Divides left hand operand by right hand operand. - * - * Rule of quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / q &= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * std::cout << p / q << std::endl; // equivalent to p * q.inv() - * ``` - */ - Quat<_Tp> operator/(const Quat<_Tp>&) const; - - /** - * @brief Division assignment operator of a quaternions and a scalar. - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of quaternion division with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p / s &= [w, x, y, z] / s\\ - * &=[w / s, x / s, y / s, z / s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0;; - * p /= s; // equivalent to p = p / s - * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - Quat<_Tp>& operator/=(const _Tp s); - - /** - * @brief Division assignment operator of two quaternions p and q; - * It divides left operand with the right operand and assign the result to left operand. - * - * Rule of quaternion division with a quaternion: - * \f[ - * \begin{equation} - * \begin{split} - * p / q&= p * q.inv()\\ - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * Quatd q{5, 6, 7, 8}; - * p /= q; // equivalent to p = p * q.inv() - * std::cout << p << std::endl; - * ``` - */ - Quat<_Tp>& operator/=(const Quat<_Tp>&); - - _Tp& operator[](std::size_t n); - - const _Tp& operator[](std::size_t n) const; - - /** - * @brief Subtraction operator of a scalar and a quaternions. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator-(const T s, const Quat&); - - /** - * @brief Subtraction operator of a quaternions and a scalar. - * Subtracts right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << p - scalar << std::endl; //[-1.0, 2, 3, 4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator-(const Quat&, const T s); - - /** - * @brief Addition operator of a quaternions and a scalar. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator+(const T s, const Quat&); - - /** - * @brief Addition operator of a quaternions and a scalar. - * Adds right hand operand from left hand operand. - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double scalar = 2.0; - * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator+(const Quat&, const T s); - - /** - * @brief Multiplication operator of a scalar and a quaternions. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z] * s\\ - * &=[w * s, x * s, y * s, z * s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * std::cout << s * p << std::endl; //[2.0, 4.0, 6.0, 8.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator*(const T s, const Quat&); - - /** - * @brief Multiplication operator of a quaternion and a scalar. - * It multiplies right operand with the left operand and assign the result to left operand. - * - * Rule of quaternion multiplication with a scalar: - * \f[ - * \begin{equation} - * \begin{split} - * p * s &= [w, x, y, z] * s\\ - * &=[w * s, x * s, y * s, z * s]. - * \end{split} - * \end{equation} - * \f] - * - * For example - * ``` - * Quatd p{1, 2, 3, 4}; - * double s = 2.0; - * std::cout << p * s << std::endl; //[2.0, 4.0, 6.0, 8.0] - * ``` - * @note the type of scalar should be equal to the quaternion. - */ - template - friend Quat cv::operator*(const Quat&, const T s); - - template - friend std::ostream& cv::operator<<(std::ostream&, const Quat&); - - /** - * @brief Transform a quaternion q to Euler angles. - * - * - * When transforming a quaternion \f$q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f$ to Euler angles, rotation matrix M can be calculated by: - * \f[ \begin{aligned} {M} &={\begin{bmatrix}1-2(y^{2}+z^{2})&2(xy-zx)&2(xz+yw)\\2(xy+zw)&1-2(x^{2}+z^{2})&2(yz-xw)\\2(xz-yw)&2(yz+xw)&1-2(x^{2}+y^{2})\end{bmatrix}}\end{aligned}.\f] - * On the other hand, the rotation matrix can be obtained from Euler angles. - * Using intrinsic rotations with Euler angles type XYZ as an example, - * \f$\theta_1 \f$, \f$\theta_2 \f$, \f$\theta_3 \f$ are three angles for Euler angles, the rotation matrix R can be calculated by:\f[R =X(\theta_1)Y(\theta_2)Z(\theta_3) - * ={\begin{bmatrix}\cos\theta_{2}\cos\theta_{3}&-\cos\theta_{2}\sin\theta_{3}&\sin\theta_{2}\\\cos\theta_{1}\sin\theta_{3}+\cos\theta_{3}\sin\theta_{1}\sin\theta_{2}&\cos\theta_{1}\cos\theta_{3}-\sin\theta_{1}\sin\theta_{2}\sin\theta_{3}&-\cos\theta_{2}\sin\theta_{1}\\\sin\theta_{1}\sin\theta_{3}-\cos\theta_{1}\cos\theta_{3}\sin\theta_{2}&\cos\theta_{3}\sin\theta_{1}+\cos\theta_{1}\sin\theta_{2}\sin\theta_{3}&\cos\theta_{1}\cos_{2}\end{bmatrix}}\f] - * Rotation matrix M and R are equal. As long as \f$ s_{2} \neq 1 \f$, by comparing each element of two matrices ,the solution is\f$\begin{cases} \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = arcsin(m_{13}) \\\theta_3 = \arctan2(-m_{12},m_{11}) \end{cases}\f$. - * - * When \f$ s_{2}=1\f$ or \f$ s_{2}=-1\f$, the gimbal lock occurs. The function will prompt "WARNING: Gimbal Lock will occur. Euler angles is non-unique. For intrinsic rotations, we set the third angle to 0, and for external rotation, we set the first angle to 0.". - * - * When \f$ s_{2}=1\f$ , - * The rotation matrix R is \f$R = {\begin{bmatrix}0&0&1\\\sin(\theta_1+\theta_3)&\cos(\theta_1+\theta_3)&0\\-\cos(\theta_1+\theta_3)&\sin(\theta_1+\theta_3)&0\end{bmatrix}}\f$. - * - * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{21},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. - * - * We set \f$ \theta_3 = 0\f$, the solution is \f$\begin{cases} \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \end{cases}\f$. - * - * When \f$ s_{2}=-1\f$, - * The rotation matrix R is \f$X_{1}Y_{2}Z_{3}={\begin{bmatrix}0&0&-1\\-\sin(\theta_1-\theta_3)&\cos(\theta_1-\theta_3)&0\\\cos(\theta_1-\theta_3)&\sin(\theta_1-\theta_3)&0\end{bmatrix}}\f$. - * - * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{32},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. - * - * We set \f$ \theta_3 = 0\f$, the solution is \f$ \begin{cases}\theta_1=\arctan2(m_{32},m_{22}) \\ \theta_2=-\pi/2\\ \theta_3=0\end{cases}\f$. - * - * Since \f$ sin \theta\in [-1,1] \f$ and \f$ cos \theta \in [-1,1] \f$, the unnormalized quaternion will cause computational troubles. For this reason, this function will normalize the quaternion at first and @ref QuatAssumeType is not needed. - * - * When the gimbal lock occurs, we set \f$\theta_3 = 0\f$ for intrinsic rotations or \f$\theta_1 = 0\f$ for extrinsic rotations. - * - * As a result, for every Euler angles type, we can get solution as shown in the following table. - * EulerAnglesType | Ordinary | \f$\theta_2 = π/2\f$ | \f$\theta_2 = -π/2\f$ - * ------------- | -------------| -------------| ------------- - * INT_XYZ|\f$ \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{12},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{32},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_XZY|\f$ \theta_1 = \arctan2(m_{32},m_{22})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{13},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{31},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{23},m_{33})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_YXZ|\f$ \theta_1 = \arctan2(m_{13},m_{33})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{12},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_YZX|\f$ \theta_1 = \arctan2(-m_{31},m_{11})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{23},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{13},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{13},m_{12})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_ZXY|\f$ \theta_1 = \arctan2(-m_{12},m_{22})\\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{31},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * INT_ZYX|\f$ \theta_1 = \arctan2(m_{21},m_{11})\\\theta_2 = \arcsin(-m_{31}) \\\theta_3= \arctan2(m_{32},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ - * EXT_XYZ|\f$ \theta_1 = \arctan2(m_{32},m_{33})\\\theta_2 = \arcsin(-m_{31}) \\\ \theta_3 = \arctan2(m_{21},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{23},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{22}) \f$ - * EXT_XZY|\f$ \theta_1 = \arctan2(-m_{23},m_{22})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{31},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{13},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{13},m_{12}) \f$ - * EXT_YXZ|\f$ \theta_1 = \arctan2(-m_{31},m_{33}) \\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{12},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ - * EXT_YZX|\f$ \theta_1 = \arctan2(m_{13},m_{11})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{32},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{31},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{23},m_{33}) \f$ - * EXT_ZXY|\f$ \theta_1 = \arctan2(m_{21},m_{22})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{13},m_{33})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{12},m_{11}) \f$|\f$ \theta_1= 0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{11}) \f$ - * EXT_ZYX|\f$ \theta_1 = \arctan2(-m_{12},m_{11})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{23},m_{33})\f$|\f$ \theta_1=0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{32},m_{22}) \f$ - * - * EulerAnglesType | Ordinary | \f$\theta_2 = 0\f$ | \f$\theta_2 = π\f$ - * ------------- | -------------| -------------| ------------- - * INT_XYX| \f$ \theta_1 = \arctan2(m_{21},-m_{31})\\\theta_2 =\arccos(m_{11}) \\\theta_3 = \arctan2(m_{12},m_{13}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_XZX| \f$ \theta_1 = \arctan2(m_{31},m_{21})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{13},-m_{12}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{32},m_{33})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_YXY| \f$ \theta_1 = \arctan2(m_{12},m_{32})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{21},-m_{23}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{31},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_YZY| \f$ \theta_1 = \arctan2(m_{32},-m_{12})\\\theta_2 = \arccos(m_{22}) \\\theta_3 =\arctan2(m_{23},m_{21}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{13},-m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_ZXZ| \f$ \theta_1 = \arctan2(-m_{13},m_{23})\\\theta_2 = \arccos(m_{33}) \\\theta_3 =\arctan2(m_{31},m_{32}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * INT_ZYZ| \f$ \theta_1 = \arctan2(m_{23},m_{13})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{32},-m_{31}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ - * EXT_XYX| \f$ \theta_1 = \arctan2(m_{12},m_{13}) \\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{21},-m_{31})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3= \arctan2(m_{23},m_{22}) \f$ - * EXT_XZX| \f$ \theta_1 = \arctan2(m_{13},-m_{12})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{31},m_{21})\f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{32},m_{33}) \f$ - * EXT_YXY| \f$ \theta_1 = \arctan2(m_{21},-m_{23})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{12},m_{32}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{31},m_{11}) \f$ - * EXT_YZY| \f$ \theta_1 = \arctan2(m_{23},m_{21}) \\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{32},-m_{12}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1=0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{13},-m_{11}) \f$ - * EXT_ZXZ| \f$ \theta_1 = \arctan2(m_{31},m_{32}) \\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(-m_{13},m_{23})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{22}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ - * EXT_ZYZ| \f$ \theta_1 = \arctan2(m_{32},-m_{31})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{23},m_{13}) \f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ - * - * @param eulerAnglesType the convertion Euler angles type - */ - - Vec<_Tp, 3> toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType); - - _Tp w, x, y, z; - -}; - -template -Quat inv(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat sinh(const Quat &q); - -template -Quat cosh(const Quat &q); - -template -Quat tanh(const Quat &q); - -template -Quat sin(const Quat &q); - -template -Quat cos(const Quat &q); - -template -Quat tan(const Quat &q); - -template -Quat asinh(const Quat &q); - -template -Quat acosh(const Quat &q); - -template -Quat atanh(const Quat &q); - -template -Quat asin(const Quat &q); - -template -Quat acos(const Quat &q); - -template -Quat atan(const Quat &q); - -template -Quat power(const Quat &q, const Quat &p, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat exp(const Quat &q); - -template -Quat log(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat power(const Quat& q, const T x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat crossProduct(const Quat &p, const Quat &q); - -template -Quat sqrt(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); - -template -Quat operator*(const T, const Quat&); - -template -Quat operator*(const Quat&, const T); - -template -std::ostream& operator<<(std::ostream&, const Quat&); - -using Quatd = Quat; -using Quatf = Quat; - -//! @} core -} - -#include "opencv2/core/quaternion.inl.hpp" - -#endif /* OPENCV_CORE_QUATERNION_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang +#ifndef OPENCV_CORE_QUATERNION_HPP +#define OPENCV_CORE_QUATERNION_HPP + +#include +#include +#include +namespace cv +{ +//! @addtogroup core_quaternion +//! @{ + +//! Unit quaternion flag +enum QuatAssumeType +{ + /** + * This flag is specified by default. + * If this flag is specified, the input quaternions are assumed to be not unit quaternions. + * It can guarantee the correctness of the calculations, + * although the calculation speed will be slower than the flag QUAT_ASSUME_UNIT. + */ + QUAT_ASSUME_NOT_UNIT, + /** + * If this flag is specified, the input quaternions are assumed to be unit quaternions which + * will save some computations. However, if this flag is specified without unit quaternion, + * the program correctness of the result will not be guaranteed. + */ + QUAT_ASSUME_UNIT +}; + +class QuatEnum +{ +public: + /** @brief Enum of Euler angles type. + * + * Without considering the possibility of using two different convertions for the definition of the rotation axes , + * there exists twelve possible sequences of rotation axes, divided into two groups: + * - Proper Euler angles (Z-X-Z, X-Y-X, Y-Z-Y, Z-Y-Z, X-Z-X, Y-X-Y) + * - Tait–Bryan angles (X-Y-Z, Y-Z-X, Z-X-Y, X-Z-Y, Z-Y-X, Y-X-Z). + * + * The three elemental rotations may be [extrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_extrinsic_rotations) + * (rotations about the axes *xyz* of the original coordinate system, which is assumed to remain motionless), + * or [intrinsic](https://en.wikipedia.org/wiki/Euler_angles#Definition_by_intrinsic_rotations)(rotations about the axes of the rotating coordinate system *XYZ*, solidary with the moving body, which changes its orientation after each elemental rotation). + * + * + * Extrinsic and intrinsic rotations are relevant. + * + * The definition of the Euler angles is as following, + * - \f$\theta_1 \f$ represents the first rotation angle, + * - \f$\theta_2 \f$ represents the second rotation angle, + * - \f$\theta_3 \f$ represents the third rotation angle. + * + * For intrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =X(\theta_1) Y(\theta_2) Z(\theta_3) \f] + * For extrinsic rotations in the order of X-Y-Z, the rotation matrix R can be calculated by:\f[R =Z({\theta_3}) Y({\theta_2}) X({\theta_1})\f] + * where + * \f[X({\theta_1})={\begin{bmatrix}1&0&0\\0&\cos {\theta_1} &-\sin {\theta_1} \\0&\sin {\theta_1} &\cos {\theta_1} \\\end{bmatrix}}, + * Y({\theta_2})={\begin{bmatrix}\cos \theta_{2}&0&\sin \theta_{2}\\0&1 &0 \\\ -sin \theta_2& 0&\cos \theta_{2} \\\end{bmatrix}}, + * Z({\theta_3})={\begin{bmatrix}\cos\theta_{3} &-\sin \theta_3&0\\\sin \theta_3 &\cos \theta_3 &0\\0&0&1\\\end{bmatrix}}. + * \f] + * + * The function is designed according to this set of conventions: + * - [Right handed](https://en.wikipedia.org/wiki/Right_hand_rule) reference frames are adopted, and the [right hand rule](https://en.wikipedia.org/wiki/Right_hand_rule) is used to determine the sign of angles. + * - Each matrix is meant to represent an [active rotation](https://en.wikipedia.org/wiki/Active_and_passive_transformation) (the composing and composed matrices + * are supposed to act on the coordinates of vectors defined in the initial fixed reference frame and give as a result the coordinates of a rotated vector defined in the same reference frame). + * - For \f$\theta_1\f$ and \f$\theta_3\f$, the valid range is (−π, π]. + * + * For \f$\theta_2\f$, the valid range is [−π/2, π/2] or [0, π]. + * + * For Tait–Bryan angles, the valid range of \f$\theta_2\f$ is [−π/2, π/2]. When transforming a quaternion to Euler angles, the solution of Euler angles is unique in condition of \f$ \theta_2 \in (−π/2, π/2)\f$ . + * If \f$\theta_2 = −π/2 \f$ or \f$ \theta_2 = π/2\f$, there are infinite solutions. The common name for this situation is gimbal lock. + * For Proper Euler angles,the valid range of \f$\theta_2\f$ is in [0, π]. The solutions of Euler angles are unique in condition of \f$ \theta_2 \in (0, π)\f$ . If \f$\theta_2 =0 \f$ or \f$\theta_2 =π \f$, + * there are infinite solutions and gimbal lock will occur. + */ + enum EulerAnglesType + { + INT_XYZ, ///< Intrinsic rotations with the Euler angles type X-Y-Z + INT_XZY, ///< Intrinsic rotations with the Euler angles type X-Z-Y + INT_YXZ, ///< Intrinsic rotations with the Euler angles type Y-X-Z + INT_YZX, ///< Intrinsic rotations with the Euler angles type Y-Z-X + INT_ZXY, ///< Intrinsic rotations with the Euler angles type Z-X-Y + INT_ZYX, ///< Intrinsic rotations with the Euler angles type Z-Y-X + INT_XYX, ///< Intrinsic rotations with the Euler angles type X-Y-X + INT_XZX, ///< Intrinsic rotations with the Euler angles type X-Z-X + INT_YXY, ///< Intrinsic rotations with the Euler angles type Y-X-Y + INT_YZY, ///< Intrinsic rotations with the Euler angles type Y-Z-Y + INT_ZXZ, ///< Intrinsic rotations with the Euler angles type Z-X-Z + INT_ZYZ, ///< Intrinsic rotations with the Euler angles type Z-Y-Z + + EXT_XYZ, ///< Extrinsic rotations with the Euler angles type X-Y-Z + EXT_XZY, ///< Extrinsic rotations with the Euler angles type X-Z-Y + EXT_YXZ, ///< Extrinsic rotations with the Euler angles type Y-X-Z + EXT_YZX, ///< Extrinsic rotations with the Euler angles type Y-Z-X + EXT_ZXY, ///< Extrinsic rotations with the Euler angles type Z-X-Y + EXT_ZYX, ///< Extrinsic rotations with the Euler angles type Z-Y-X + EXT_XYX, ///< Extrinsic rotations with the Euler angles type X-Y-X + EXT_XZX, ///< Extrinsic rotations with the Euler angles type X-Z-X + EXT_YXY, ///< Extrinsic rotations with the Euler angles type Y-X-Y + EXT_YZY, ///< Extrinsic rotations with the Euler angles type Y-Z-Y + EXT_ZXZ, ///< Extrinsic rotations with the Euler angles type Z-X-Z + EXT_ZYZ, ///< Extrinsic rotations with the Euler angles type Z-Y-Z + #ifndef CV_DOXYGEN + EULER_ANGLES_MAX_VALUE + #endif + }; + +}; + +template class Quat; +template std::ostream& operator<<(std::ostream&, const Quat<_Tp>&); + +/** + * Quaternion is a number system that extends the complex numbers. It can be expressed as a + * rotation in three-dimensional space. + * A quaternion is generally represented in the form: + * \f[q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f] + * \f[q = [w, x, y, z]\f] + * \f[q = [w, \boldsymbol{v}] \f] + * \f[q = ||q||[\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] + * \f[q = ||q||[\cos\psi, \boldsymbol{u}\sin\psi]\f] + * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ represents rotation angle, + * \f$\boldsymbol{u} = [u_x, u_y, u_z]\f$ represents normalized rotation axis, + * and \f$||q||\f$ represents the norm of \f$q\f$. + * + * A unit quaternion is usually represents rotation, which has the form: + * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] + * + * To create a quaternion representing the rotation around the axis \f$\boldsymbol{u}\f$ + * with angle \f$\theta\f$, you can use + * ``` + * using namespace cv; + * double angle = CV_PI; + * Vec3d axis = {0, 0, 1}; + * Quatd q = Quatd::createFromAngleAxis(angle, axis); + * ``` + * + * You can simply use four same type number to create a quaternion + * ``` + * Quatd q(1, 2, 3, 4); + * ``` + * Or use a Vec4d or Vec4f vector. + * ``` + * Vec4d vec{1, 2, 3, 4}; + * Quatd q(vec); + * ``` + * + * ``` + * Vec4f vec{1, 2, 3, 4}; + * Quatf q(vec); + * ``` + * + * If you already have a 3x3 rotation matrix R, then you can use + * ``` + * Quatd q = Quatd::createFromRotMat(R); + * ``` + * + * If you already have a rotation vector rvec which has the form of `angle * axis`, then you can use + * ``` + * Quatd q = Quatd::createFromRvec(rvec); + * ``` + * + * To extract the rotation matrix from quaternion, see toRotMat3x3() + * + * To extract the Vec4d or Vec4f, see toVec() + * + * To extract the rotation vector, see toRotVec() + * + * If there are two quaternions \f$q_0, q_1\f$ are needed to interpolate, you can use nlerp(), slerp() or spline() + * ``` + * Quatd::nlerp(q0, q1, t) + * + * Quatd::slerp(q0, q1, t) + * + * Quatd::spline(q0, q0, q1, q1, t) + * ``` + * spline can smoothly connect rotations of multiple quaternions + * + * Three ways to get an element in Quaternion + * ``` + * Quatf q(1,2,3,4); + * std::cout << q.w << std::endl; // w=1, x=2, y=3, z=4 + * std::cout << q[0] << std::endl; // q[0]=1, q[1]=2, q[2]=3, q[3]=4 + * std::cout << q.at(0) << std::endl; + * ``` + */ +template +class Quat +{ + static_assert(std::is_floating_point<_Tp>::value, "Quaternion only make sense with type of float or double"); + using value_type = _Tp; +public: + static constexpr _Tp CV_QUAT_EPS = (_Tp)1.e-6; + static constexpr _Tp CV_QUAT_CONVERT_THRESHOLD = (_Tp)1.e-6; + + Quat(); + + /** + * @brief From Vec4d or Vec4f. + */ + explicit Quat(const Vec<_Tp, 4> &coeff); + + /** + * @brief from four numbers. + */ + Quat(_Tp w, _Tp x, _Tp y, _Tp z); + + /** + * @brief from an angle, axis. Axis will be normalized in this function. And + * it generates + * \f[q = [\cos\psi, u_x\sin\psi,u_y\sin\psi, u_z\sin\psi].\f] + * where \f$\psi = \frac{\theta}{2}\f$, \f$\theta\f$ is the rotation angle. + */ + static Quat<_Tp> createFromAngleAxis(const _Tp angle, const Vec<_Tp, 3> &axis); + + /** + * @brief from a 3x3 rotation matrix. + */ + static Quat<_Tp> createFromRotMat(InputArray R); + + /** + * @brief from a rotation vector + * \f$r\f$ has the form \f$\theta \cdot \boldsymbol{u}\f$, where \f$\theta\f$ + * represents rotation angle and \f$\boldsymbol{u}\f$ represents normalized rotation axis. + * + * Angle and axis could be easily derived as: + * \f[ + * \begin{equation} + * \begin{split} + * \psi &= ||r||\\ + * \boldsymbol{u} &= \frac{r}{\theta} + * \end{split} + * \end{equation} + * \f] + * Then a quaternion can be calculated by + * \f[q = [\cos\psi, \boldsymbol{u}\sin\psi]\f] + * where \f$\psi = \theta / 2 \f$ + */ + static Quat<_Tp> createFromRvec(InputArray rvec); + + /** + * @brief + * from Euler angles + * + * A quaternion can be generated from Euler angles by combining the quaternion representations of the Euler rotations. + * + * For example, if we use intrinsic rotations in the order of X-Y-Z,\f$\theta_1 \f$ is rotation around the X-axis, \f$\theta_2 \f$ is rotation around the Y-axis, + * \f$\theta_3 \f$ is rotation around the Z-axis. The final quaternion q can be calculated by + * + * \f[ {q} = q_{X, \theta_1} q_{Y, \theta_2} q_{Z, \theta_3}\f] + * where \f$ q_{X, \theta_1} \f$ is created from @ref createFromXRot, \f$ q_{Y, \theta_2} \f$ is created from @ref createFromYRot, + * \f$ q_{Z, \theta_3} \f$ is created from @ref createFromZRot. + * @param angles the Euler angles in a vector of length 3 + * @param eulerAnglesType the convertion Euler angles type + */ + static Quat<_Tp> createFromEulerAngles(const Vec<_Tp, 3> &angles, QuatEnum::EulerAnglesType eulerAnglesType); + + /** + * @brief get a quaternion from a rotation about the Y-axis by \f$\theta\f$ . + * \f[q = \cos(\theta/2)+0 i+ sin(\theta/2) j +0k \f] + */ + static Quat<_Tp> createFromYRot(const _Tp theta); + + /** + * @brief get a quaternion from a rotation about the X-axis by \f$\theta\f$ . + * \f[q = \cos(\theta/2)+sin(\theta/2) i +0 j +0 k \f] + */ + static Quat<_Tp> createFromXRot(const _Tp theta); + + /** + * @brief get a quaternion from a rotation about the Z-axis by \f$\theta\f$. + * \f[q = \cos(\theta/2)+0 i +0 j +sin(\theta/2) k \f] + */ + static Quat<_Tp> createFromZRot(const _Tp theta); + + /** + * @brief a way to get element. + * @param index over a range [0, 3]. + * + * A quaternion q + * + * q.at(0) is equivalent to q.w, + * + * q.at(1) is equivalent to q.x, + * + * q.at(2) is equivalent to q.y, + * + * q.at(3) is equivalent to q.z. + */ + _Tp at(size_t index) const; + + /** + * @brief return the conjugate of this quaternion. + * \f[q.conjugate() = (w, -x, -y, -z).\f] + */ + Quat<_Tp> conjugate() const; + + /** + * + * @brief return the value of exponential value. + * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||})\sin||\boldsymbol{v}||\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example: + * ``` + * Quatd q{1,2,3,4}; + * cout << exp(q) << endl; + * ``` + */ + template + friend Quat exp(const Quat &q); + + /** + * @brief return the value of exponential value. + * \f[\exp(q) = e^w (\cos||\boldsymbol{v}||+ \frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q{1,2,3,4}; + * cout << q.exp() << endl; + * ``` + */ + Quat<_Tp> exp() const; + + /** + * @brief return the value of logarithm function. + * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}.\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q1{1,2,3,4}; + * cout << log(q1) << endl; + * ``` + */ + template + friend Quat log(const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return the value of logarithm function. + * \f[\ln(q) = \ln||q|| + \frac{\boldsymbol{v}}{||\boldsymbol{v}||}\arccos\frac{w}{||q||}\f]. + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.log(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * Quatd q1(1,2,3,4); + * q1.normalize().log(assumeUnit); + * ``` + */ + Quat<_Tp> log(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of power function with index \f$x\f$. + * \f[q^x = ||q||(cos(x\theta) + \boldsymbol{u}sin(x\theta))).\f] + * @param q a quaternion. + * @param x index of exponentiation. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * power(q, 2.0); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * double angle = CV_PI; + * Vec3d axis{0, 0, 1}; + * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle + * power(q1, 2.0, assumeUnit);//This assumeUnit means q1 is a unit quaternion. + * ``` + * @note the type of the index should be the same as the quaternion. + */ + template + friend Quat power(const Quat &q, const T x, QuatAssumeType assumeUnit); + + /** + * @brief return the value of power function with index \f$x\f$. + * \f[q^x = ||q||(\cos(x\theta) + \boldsymbol{u}\sin(x\theta))).\f] + * @param x index of exponentiation. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.power(2.0); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * double angle = CV_PI; + * Vec3d axis{0, 0, 1}; + * Quatd q1 = Quatd::createFromAngleAxis(angle, axis); //generate a unit quat by axis and angle + * q1.power(2.0, assumeUnit); //This assumeUnt means q1 is a unit quaternion + * ``` + */ + Quat<_Tp> power(const _Tp x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return \f$\sqrt{q}\f$. + * @param q a quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatf q(1,2,3,4); + * sqrt(q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = {1,0,0,0}; + * sqrt(q, assumeUnit); //This assumeUnit means q is a unit quaternion. + * ``` + */ + template + friend Quat sqrt(const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return \f$\sqrt{q}\f$. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatf q(1,2,3,4); + * q.sqrt(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = {1,0,0,0}; + * q.sqrt(assumeUnit); //This assumeUnit means q is a unit quaternion + * ``` + */ + Quat<_Tp> sqrt(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the value of power function with quaternion \f$q\f$. + * \f[p^q = e^{q\ln(p)}.\f] + * @param p base quaternion of power function. + * @param q index quaternion of power function. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion \f$p\f$ assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd p(1,2,3,4); + * Quatd q(5,6,7,8); + * power(p, q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * p = p.normalize(); + * power(p, q, assumeUnit); //This assumeUnit means p is a unit quaternion + * ``` + */ + template + friend Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return the value of power function with quaternion \f$q\f$. + * \f[p^q = e^{q\ln(p)}.\f] + * @param q index quaternion of power function. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd p(1,2,3,4); + * Quatd q(5,6,7,8); + * p.power(q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * p = p.normalize(); + * p.power(q, assumeUnit); //This assumeUnit means p is a unit quaternion + * ``` + */ + Quat<_Tp> power(const Quat<_Tp> &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. + * \f[p \times q = \frac{pq- qp}{2}\f] + * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}\f] + * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k \f] + * + * For example + * ``` + * Quatd q{1,2,3,4}; + * Quatd p{5,6,7,8}; + * crossProduct(p, q); + * ``` + */ + template + friend Quat crossProduct(const Quat &p, const Quat &q); + + /** + * @brief return the crossProduct between \f$p = (a, b, c, d) = (a, \boldsymbol{u})\f$ and \f$q = (w, x, y, z) = (w, \boldsymbol{v})\f$. + * \f[p \times q = \frac{pq- qp}{2}.\f] + * \f[p \times q = \boldsymbol{u} \times \boldsymbol{v}.\f] + * \f[p \times q = (cz-dy)i + (dx-bz)j + (by-xc)k. \f] + * + * For example + * ``` + * Quatd q{1,2,3,4}; + * Quatd p{5,6,7,8}; + * p.crossProduct(q) + * ``` + */ + Quat<_Tp> crossProduct(const Quat<_Tp> &q) const; + + /** + * @brief return the norm of quaternion. + * \f[||q|| = \sqrt{w^2 + x^2 + y^2 + z^2}.\f] + */ + _Tp norm() const; + + /** + * @brief return a normalized \f$p\f$. + * \f[p = \frac{q}{||q||}\f] + * where \f$p\f$ satisfies \f$(p.x)^2 + (p.y)^2 + (p.z)^2 + (p.w)^2 = 1.\f$ + */ + Quat<_Tp> normalize() const; + + /** + * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ + * which satisfies \f$q * q^{-1} = 1\f$. + * @param q a quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * inv(q); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = q.normalize(); + * inv(q, assumeUnit);//This assumeUnit means p is a unit quaternion + * ``` + */ + template + friend Quat inv(const Quat &q, QuatAssumeType assumeUnit); + + /** + * @brief return \f$q^{-1}\f$ which is an inverse of \f$q\f$ + * satisfying \f$q * q^{-1} = 1\f$. + * @param assumeUnit if QUAT_ASSUME_UNIT, quaternion q assume to be a unit quaternion and this function will save some computations. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.inv(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q = q.normalize(); + * q.inv(assumeUnit); //assumeUnit means p is a unit quaternion + * ``` + */ + Quat<_Tp> inv(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return sinh value of quaternion q, sinh could be calculated as: + * \f[\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * sinh(q); + * ``` + */ + template + friend Quat sinh(const Quat &q); + + /** + * @brief return sinh value of this quaternion, sinh could be calculated as: + * \f$\sinh(p) = \sin(w)\cos(||\boldsymbol{v}||) + \cosh(w)\frac{v}{||\boldsymbol{v}||}\sin||\boldsymbol{v}||\f$ + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.sinh(); + * ``` + */ + Quat<_Tp> sinh() const; + + /** + * @brief return cosh value of quaternion q, cosh could be calculated as: + * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sin(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * cosh(q); + * ``` + */ + template + friend Quat cosh(const Quat &q); + + /** + * @brief return cosh value of this quaternion, cosh could be calculated as: + * \f[\cosh(p) = \cosh(w) * \cos(||\boldsymbol{v}||) + \sinh(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}sin(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.cosh(); + * ``` + */ + Quat<_Tp> cosh() const; + + /** + * @brief return tanh value of quaternion q, tanh could be calculated as: + * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * tanh(q); + * ``` + * @sa sinh, cosh + */ + template + friend Quat tanh(const Quat &q); + + /** + * @brief return tanh value of this quaternion, tanh could be calculated as: + * \f[ \tanh(q) = \frac{\sinh(q)}{\cosh(q)}.\f] + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.tanh(); + * ``` + * @sa sinh, cosh + */ + Quat<_Tp> tanh() const; + + /** + * @brief return tanh value of quaternion q, sin could be calculated as: + * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * sin(q); + * ``` + */ + template + friend Quat sin(const Quat &q); + + /** + * @brief return sin value of this quaternion, sin could be calculated as: + * \f[\sin(p) = \sin(w) * \cosh(||\boldsymbol{v}||) + \cos(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.sin(); + * ``` + */ + Quat<_Tp> sin() const; + + /** + * @brief return sin value of quaternion q, cos could be calculated as: + * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * cos(q); + * ``` + */ + template + friend Quat cos(const Quat &q); + + /** + * @brief return cos value of this quaternion, cos could be calculated as: + * \f[\cos(p) = \cos(w) * \cosh(||\boldsymbol{v}||) - \sin(w)\frac{\boldsymbol{v}}{||\boldsymbol{v}||}\sinh(||\boldsymbol{v}||)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.cos(); + * ``` + */ + Quat<_Tp> cos() const; + + /** + * @brief return tan value of quaternion q, tan could be calculated as: + * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * tan(q); + * ``` + */ + template + friend Quat tan(const Quat &q); + + /** + * @brief return tan value of this quaternion, tan could be calculated as: + * \f[\tan(q) = \frac{\sin(q)}{\cos(q)}.\f] + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.tan(); + * ``` + */ + Quat<_Tp> tan() const; + + /** + * @brief return arcsin value of quaternion q, arcsin could be calculated as: + * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * asin(q); + * ``` + */ + template + friend Quat asin(const Quat &q); + + /** + * @brief return arcsin value of this quaternion, arcsin could be calculated as: + * \f[\arcsin(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arcsinh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.asin(); + * ``` + */ + Quat<_Tp> asin() const; + + /** + * @brief return arccos value of quaternion q, arccos could be calculated as: + * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * acos(q); + * ``` + */ + template + friend Quat acos(const Quat &q); + + /** + * @brief return arccos value of this quaternion, arccos could be calculated as: + * \f[\arccos(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arccosh(q)\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.acos(); + * ``` + */ + Quat<_Tp> acos() const; + + /** + * @brief return arctan value of quaternion q, arctan could be calculated as: + * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * atan(q); + * ``` + */ + template + friend Quat atan(const Quat &q); + + /** + * @brief return arctan value of this quaternion, arctan could be calculated as: + * \f[\arctan(q) = -\frac{\boldsymbol{v}}{||\boldsymbol{v}||}arctanh(q\frac{\boldsymbol{v}}{||\boldsymbol{v}||})\f] + * where \f$\boldsymbol{v} = [x, y, z].\f$ + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.atan(); + * ``` + */ + Quat<_Tp> atan() const; + + /** + * @brief return arcsinh value of quaternion q, arcsinh could be calculated as: + * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * asinh(q); + * ``` + */ + template + friend Quat asinh(const Quat &q); + + /** + * @brief return arcsinh value of this quaternion, arcsinh could be calculated as: + * \f[arcsinh(q) = \ln(q + \sqrt{q^2 + 1})\f]. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.asinh(); + * ``` + */ + Quat<_Tp> asinh() const; + + /** + * @brief return arccosh value of quaternion q, arccosh could be calculated as: + * \f[arccosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * acosh(q); + * ``` + */ + template + friend Quat acosh(const Quat &q); + + /** + * @brief return arccosh value of this quaternion, arccosh could be calculated as: + * \f[arcosh(q) = \ln(q + \sqrt{q^2 - 1})\f]. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.acosh(); + * ``` + */ + Quat<_Tp> acosh() const; + + /** + * @brief return arctanh value of quaternion q, arctanh could be calculated as: + * \f[arctanh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. + * @param q a quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * atanh(q); + * ``` + */ + template + friend Quat atanh(const Quat &q); + + /** + * @brief return arctanh value of this quaternion, arctanh could be calculated as: + * \f[arcsinh(q) = \frac{\ln(q + 1) - \ln(1 - q)}{2}\f]. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.atanh(); + * ``` + */ + Quat<_Tp> atanh() const; + + /** + * @brief return true if this quaternion is a unit quaternion. + * @param eps tolerance scope of normalization. The eps could be defined as + * + * \f[eps = |1 - dotValue|\f] where \f[dotValue = (this.w^2 + this.x^2 + this,y^2 + this.z^2).\f] + * And this function will consider it is normalized when the dotValue over a range \f$[1-eps, 1+eps]\f$. + */ + bool isNormal(_Tp eps=CV_QUAT_EPS) const; + + /** + * @brief to throw an error if this quaternion is not a unit quaternion. + * @param eps tolerance scope of normalization. + * @sa isNormal + */ + void assertNormal(_Tp eps=CV_QUAT_EPS) const; + + /** + * @brief transform a quaternion to a 3x3 rotation matrix. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. Otherwise, this function will normalize this + * quaternion at first then do the transformation. + * + * @note Matrix A which is to be rotated should have the form + * \f[\begin{bmatrix} + * x_0& x_1& x_2&...&x_n\\ + * y_0& y_1& y_2&...&y_n\\ + * z_0& z_1& z_2&...&z_n + * \end{bmatrix}\f] + * where the same subscript represents a point. The shape of A assume to be [3, n] + * The points matrix A can be rotated by toRotMat3x3() * A. + * The result has 3 rows and n columns too. + + * For example + * ``` + * double angle = CV_PI; + * Vec3d axis{0,0,1}; + * Quatd q_unit = Quatd::createFromAngleAxis(angle, axis); //quaternion could also be get by interpolation by two or more quaternions. + * + * //assume there is two points (1,0,0) and (1,0,1) to be rotated + * Mat pointsA = (Mat_(2, 3) << 1,0,0,1,0,1); + * //change the shape + * pointsA = pointsA.t(); + * // rotate 180 degrees around the z axis + * Mat new_point = q_unit.toRotMat3x3() * pointsA; + * // print two points + * cout << new_point << endl; + * ``` + */ + Matx<_Tp, 3, 3> toRotMat3x3(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief transform a quaternion to a 4x4 rotation matrix. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. Otherwise, this function will normalize this + * quaternion at first then do the transformation. + * + * The operations is similar as toRotMat3x3 + * except that the points matrix should have the form + * \f[\begin{bmatrix} + * x_0& x_1& x_2&...&x_n\\ + * y_0& y_1& y_2&...&y_n\\ + * z_0& z_1& z_2&...&z_n\\ + * 0&0&0&...&0 + * \end{bmatrix}\f] + * + * @sa toRotMat3x3 + */ + + Matx<_Tp, 4, 4> toRotMat4x4(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief transform the this quaternion to a Vec. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.toVec(); + * ``` + */ + Vec<_Tp, 4> toVec() const; + + /** + * @brief transform this quaternion to a Rotation vector. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. + * Rotation vector rVec is defined as: + * \f[ rVec = [\theta v_x, \theta v_y, \theta v_z]\f] + * where \f$\theta\f$ represents rotation angle, and \f$\boldsymbol{v}\f$ represents the normalized rotation axis. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.toRotVec(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q.normalize().toRotVec(assumeUnit); //answer is same as q.toRotVec(). + * ``` + */ + Vec<_Tp, 3> toRotVec(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief get the angle of quaternion, it returns the rotation angle. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. + * \f[\psi = 2 *arccos(\frac{w}{||q||})\f] + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.getAngle(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q.normalize().getAngle(assumeUnit);//same as q.getAngle(). + * ``` + * @note It always return the value between \f$[0, 2\pi]\f$. + */ + _Tp getAngle(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief get the axis of quaternion, it returns a vector of length 3. + * @param assumeUnit if QUAT_ASSUME_UNIT, this quaternion assume to be a unit quaternion and + * this function will save some computations. + * + * the unit axis \f$\boldsymbol{u}\f$ is defined by + * \f[\begin{equation} + * \begin{split} + * \boldsymbol{v} + * &= \boldsymbol{u} ||\boldsymbol{v}||\\ + * &= \boldsymbol{u}||q||sin(\frac{\theta}{2}) + * \end{split} + * \end{equation}\f] + * where \f$v=[x, y ,z]\f$ and \f$\theta\f$ represents rotation angle. + * + * + * For example + * ``` + * Quatd q(1,2,3,4); + * q.getAxis(); + * + * QuatAssumeType assumeUnit = QUAT_ASSUME_UNIT; + * q.normalize().getAxis(assumeUnit);//same as q.getAxis() + * ``` + */ + Vec<_Tp, 3> getAxis(QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT) const; + + /** + * @brief return the dot between quaternion \f$q\f$ and this quaternion. + * + * dot(p, q) is a good metric of how close the quaternions are. + * Indeed, consider the unit quaternion difference \f$p^{-1} * q\f$, its real part is dot(p, q). + * At the same time its real part is equal to \f$\cos(\beta/2)\f$ where \f$\beta\f$ is + * an angle of rotation between p and q, i.e., + * Therefore, the closer dot(p, q) to 1, + * the smaller rotation between them. + * \f[p \cdot q = p.w \cdot q.w + p.x \cdot q.x + p.y \cdot q.y + p.z \cdot q.z\f] + * @param q the other quaternion. + * + * For example + * ``` + * Quatd q(1,2,3,4); + * Quatd p(5,6,7,8); + * p.dot(q); + * ``` + */ + _Tp dot(Quat<_Tp> q) const; + + /** + * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Linear Interpolation(Nlerp) + * For two quaternions, this interpolation curve can be displayed as: + * \f[Lerp(q_0, q_1, t) = (1 - t)q_0 + tq_1.\f] + * Obviously, the lerp will interpolate along a straight line if we think of \f$q_0\f$ and \f$q_1\f$ as a vector + * in a two-dimensional space. When \f$t = 0\f$, it returns \f$q_0\f$ and when \f$t= 1\f$, it returns \f$q_1\f$. + * \f$t\f$ should to be ranged in \f$[0, 1]\f$ normally. + * @param q0 a quaternion used in linear interpolation. + * @param q1 a quaternion used in linear interpolation. + * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. + * @note it returns a non-unit quaternion. + */ + static Quat<_Tp> lerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t); + + /** + * @brief To calculate the interpolation from \f$q_0\f$ to \f$q_1\f$ by Normalized Linear Interpolation(Nlerp). + * it returns a normalized quaternion of Linear Interpolation(Lerp). + * \f[ Nlerp(q_0, q_1, t) = \frac{(1 - t)q_0 + tq_1}{||(1 - t)q_0 + tq_1||}.\f] + * The interpolation will always choose the shortest path but the constant speed is not guaranteed. + * @param q0 a quaternion used in normalized linear interpolation. + * @param q1 a quaternion used in normalized linear interpolation. + * @param t percent of vector \f$\overrightarrow{q_0q_1}\f$ over a range [0, 1]. + * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all inputs + quaternion will be normalized inside the function. + * @sa lerp + */ + static Quat<_Tp> nlerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + @brief To calculate the interpolation between \f$q_0\f$ and \f$q_1\f$ by Spherical Linear + Interpolation(Slerp), which can be defined as: + \f[ Slerp(q_0, q_1, t) = \frac{\sin((1-t)\theta)}{\sin(\theta)}q_0 + \frac{\sin(t\theta)}{\sin(\theta)}q_1\f] + where \f$\theta\f$ can be calculated as: + \f[\theta=cos^{-1}(q_0\cdot q_1)\f] + resulting from the both of their norm is unit. + @param q0 a quaternion used in Slerp. + @param q1 a quaternion used in Slerp. + @param t percent of angle between \f$q_0\f$ and \f$q_1\f$ over a range [0, 1]. + @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternions. Otherwise, all input + quaternions will be normalized inside the function. + @param directChange if QUAT_ASSUME_UNIT, the interpolation will choose the nearest path. + @note If the interpolation angle is small, the error between Nlerp and Slerp is not so large. To improve efficiency and + avoid zero division error, we use Nlerp instead of Slerp. + */ + static Quat<_Tp> slerp(const Quat<_Tp> &q0, const Quat &q1, const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, bool directChange=true); + + /** + * @brief To calculate the interpolation between \f$q_0\f$,\f$q_1\f$,\f$q_2\f$,\f$q_3\f$ by Spherical and quadrangle(Squad). This could be defined as: + * \f[Squad(q_i, s_i, s_{i+1}, q_{i+1}, t) = Slerp(Slerp(q_i, q_{i+1}, t), Slerp(s_i, s_{i+1}, t), 2t(1-t))\f] + * where + * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4})\f] + * + * The Squad expression is analogous to the \f$B\acute{e}zier\f$ curve, but involves spherical linear + * interpolation instead of simple linear interpolation. Each \f$s_i\f$ needs to be calculated by three + * quaternions. + * + * @param q0 the first quaternion. + * @param s0 the second quaternion. + * @param s1 the third quaternion. + * @param q1 thr fourth quaternion. + * @param t interpolation parameter of quadratic and linear interpolation over a range \f$[0, 1]\f$. + * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input + * quaternions will be normalized inside the function. + * @param directChange if QUAT_ASSUME_UNIT, squad will find the nearest path to interpolate. + * @sa interPoint, spline + */ + static Quat<_Tp> squad(const Quat<_Tp> &q0, const Quat<_Tp> &s0, + const Quat<_Tp> &s1, const Quat<_Tp> &q1, + const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT, + bool directChange=true); + + /** + * @brief This is the part calculation of squad. + * To calculate the intermedia quaternion \f$s_i\f$ between each three quaternion + * \f[s_i = q_i\exp(-\frac{\log(q^*_iq_{i+1}) + \log(q^*_iq_{i-1})}{4}).\f] + * @param q0 the first quaternion. + * @param q1 the second quaternion. + * @param q2 the third quaternion. + * @param assumeUnit if QUAT_ASSUME_UNIT, all input quaternions assume to be unit quaternion. Otherwise, all input + * quaternions will be normalized inside the function. + * @sa squad + */ + static Quat<_Tp> interPoint(const Quat<_Tp> &q0, const Quat<_Tp> &q1, + const Quat<_Tp> &q2, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief to calculate a quaternion which is the result of a \f$C^1\f$ continuous + * spline curve constructed by squad at the ratio t. Here, the interpolation values are + * between \f$q_1\f$ and \f$q_2\f$. \f$q_0\f$ and \f$q_2\f$ are used to ensure the \f$C^1\f$ + * continuity. if t = 0, it returns \f$q_1\f$, if t = 1, it returns \f$q_2\f$. + * @param q0 the first input quaternion to ensure \f$C^1\f$ continuity. + * @param q1 the second input quaternion. + * @param q2 the third input quaternion. + * @param q3 the fourth input quaternion the same use of \f$q1\f$. + * @param t ratio over a range [0, 1]. + * @param assumeUnit if QUAT_ASSUME_UNIT, \f$q_0, q_1, q_2, q_3\f$ assume to be unit quaternion. Otherwise, all input + * quaternions will be normalized inside the function. + * + * For example: + * + * If there are three double quaternions \f$v_0, v_1, v_2\f$ waiting to be interpolated. + * + * Interpolation between \f$v_0\f$ and \f$v_1\f$ with a ratio \f$t_0\f$ could be calculated as + * ``` + * Quatd::spline(v0, v0, v1, v2, t0); + * ``` + * Interpolation between \f$v_1\f$ and \f$v_2\f$ with a ratio \f$t_0\f$ could be calculated as + * ``` + * Quatd::spline(v0, v1, v2, v2, t0); + * ``` + * @sa squad, slerp + */ + static Quat<_Tp> spline(const Quat<_Tp> &q0, const Quat<_Tp> &q1, + const Quat<_Tp> &q2, const Quat<_Tp> &q3, + const _Tp t, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + + /** + * @brief Return opposite quaternion \f$-p\f$ + * which satisfies \f$p + (-p) = 0.\f$ + * + * For example + * ``` + * Quatd q{1, 2, 3, 4}; + * std::cout << -q << std::endl; // [-1, -2, -3, -4] + * ``` + */ + Quat<_Tp> operator-() const; + + /** + * @brief return true if two quaternions p and q are nearly equal, i.e. when the absolute + * value of each \f$p_i\f$ and \f$q_i\f$ is less than CV_QUAT_EPS. + */ + bool operator==(const Quat<_Tp>&) const; + + /** + * @brief Addition operator of two quaternions p and q. + * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$q_i\f$. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p + q << std::endl; //[6, 8, 10, 12] + * ``` + */ + Quat<_Tp> operator+(const Quat<_Tp>&) const; + + /** + * @brief Addition assignment operator of two quaternions p and q. + * It adds right operand to the left operand and assign the result to left operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p += q; // equivalent to p = p + q + * std::cout << p << std::endl; //[6, 8, 10, 12] + * + * ``` + */ + Quat<_Tp>& operator+=(const Quat<_Tp>&); + + /** + * @brief Subtraction operator of two quaternions p and q. + * It returns a new quaternion that each value is the sum of \f$p_i\f$ and \f$-q_i\f$. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p - q << std::endl; //[-4, -4, -4, -4] + * ``` + */ + Quat<_Tp> operator-(const Quat<_Tp>&) const; + + /** + * @brief Subtraction assignment operator of two quaternions p and q. + * It subtracts right operand from the left operand and assign the result to left operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p -= q; // equivalent to p = p - q + * std::cout << p << std::endl; //[-4, -4, -4, -4] + * + * ``` + */ + Quat<_Tp>& operator-=(const Quat<_Tp>&); + + /** + * @brief Multiplication assignment operator of two quaternions q and p. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication: + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ + * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. + * \end{split} + * \end{equation} + * \f] + * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p *= q; // equivalent to p = p * q + * std::cout << p << std::endl; //[-60, 12, 30, 24] + * ``` + */ + Quat<_Tp>& operator*=(const Quat<_Tp>&); + + /** + * @brief Multiplication assignment operator of a quaternions and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z] * s\\ + * &=[w * s, x * s, y * s, z * s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * p *= s; // equivalent to p = p * s + * std::cout << p << std::endl; //[2.0, 4.0, 6.0, 8.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + Quat<_Tp>& operator*=(const _Tp s); + + /** + * @brief Multiplication operator of two quaternions q and p. + * Multiplies values on either side of the operator. + * + * Rule of quaternion multiplication: + * \f[ + * \begin{equation} + * \begin{split} + * p * q &= [p_0, \boldsymbol{u}]*[q_0, \boldsymbol{v}]\\ + * &=[p_0q_0 - \boldsymbol{u}\cdot \boldsymbol{v}, p_0\boldsymbol{v} + q_0\boldsymbol{u}+ \boldsymbol{u}\times \boldsymbol{v}]. + * \end{split} + * \end{equation} + * \f] + * where \f$\cdot\f$ means dot product and \f$\times \f$ means cross product. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p * q << std::endl; //[-60, 12, 30, 24] + * ``` + */ + Quat<_Tp> operator*(const Quat<_Tp>&) const; + + /** + * @brief Division operator of a quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z] / s\\ + * &=[w/s, x/s, y/s, z/s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1, 1.5, 2] + * ``` + * @note the type of scalar should be equal to this quaternion. + */ + Quat<_Tp> operator/(const _Tp s) const; + + /** + * @brief Division operator of two quaternions p and q. + * Divides left hand operand by right hand operand. + * + * Rule of quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / q &= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * std::cout << p / q << std::endl; // equivalent to p * q.inv() + * ``` + */ + Quat<_Tp> operator/(const Quat<_Tp>&) const; + + /** + * @brief Division assignment operator of a quaternions and a scalar. + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of quaternion division with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p / s &= [w, x, y, z] / s\\ + * &=[w / s, x / s, y / s, z / s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0;; + * p /= s; // equivalent to p = p / s + * std::cout << p << std::endl; //[0.5, 1.0, 1.5, 2.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + Quat<_Tp>& operator/=(const _Tp s); + + /** + * @brief Division assignment operator of two quaternions p and q; + * It divides left operand with the right operand and assign the result to left operand. + * + * Rule of quaternion division with a quaternion: + * \f[ + * \begin{equation} + * \begin{split} + * p / q&= p * q.inv()\\ + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * Quatd q{5, 6, 7, 8}; + * p /= q; // equivalent to p = p * q.inv() + * std::cout << p << std::endl; + * ``` + */ + Quat<_Tp>& operator/=(const Quat<_Tp>&); + + _Tp& operator[](std::size_t n); + + const _Tp& operator[](std::size_t n) const; + + /** + * @brief Subtraction operator of a scalar and a quaternions. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << scalar - p << std::endl; //[1.0, -2, -3, -4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator-(const T s, const Quat&); + + /** + * @brief Subtraction operator of a quaternions and a scalar. + * Subtracts right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << p - scalar << std::endl; //[-1.0, 2, 3, 4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator-(const Quat&, const T s); + + /** + * @brief Addition operator of a quaternions and a scalar. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << scalar + p << std::endl; //[3.0, 2, 3, 4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator+(const T s, const Quat&); + + /** + * @brief Addition operator of a quaternions and a scalar. + * Adds right hand operand from left hand operand. + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double scalar = 2.0; + * std::cout << p + scalar << std::endl; //[3.0, 2, 3, 4] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator+(const Quat&, const T s); + + /** + * @brief Multiplication operator of a scalar and a quaternions. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z] * s\\ + * &=[w * s, x * s, y * s, z * s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * std::cout << s * p << std::endl; //[2.0, 4.0, 6.0, 8.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator*(const T s, const Quat&); + + /** + * @brief Multiplication operator of a quaternion and a scalar. + * It multiplies right operand with the left operand and assign the result to left operand. + * + * Rule of quaternion multiplication with a scalar: + * \f[ + * \begin{equation} + * \begin{split} + * p * s &= [w, x, y, z] * s\\ + * &=[w * s, x * s, y * s, z * s]. + * \end{split} + * \end{equation} + * \f] + * + * For example + * ``` + * Quatd p{1, 2, 3, 4}; + * double s = 2.0; + * std::cout << p * s << std::endl; //[2.0, 4.0, 6.0, 8.0] + * ``` + * @note the type of scalar should be equal to the quaternion. + */ + template + friend Quat cv::operator*(const Quat&, const T s); + + template + friend std::ostream& cv::operator<<(std::ostream&, const Quat&); + + /** + * @brief Transform a quaternion q to Euler angles. + * + * + * When transforming a quaternion \f$q = w + x\boldsymbol{i} + y\boldsymbol{j} + z\boldsymbol{k}\f$ to Euler angles, rotation matrix M can be calculated by: + * \f[ \begin{aligned} {M} &={\begin{bmatrix}1-2(y^{2}+z^{2})&2(xy-zx)&2(xz+yw)\\2(xy+zw)&1-2(x^{2}+z^{2})&2(yz-xw)\\2(xz-yw)&2(yz+xw)&1-2(x^{2}+y^{2})\end{bmatrix}}\end{aligned}.\f] + * On the other hand, the rotation matrix can be obtained from Euler angles. + * Using intrinsic rotations with Euler angles type XYZ as an example, + * \f$\theta_1 \f$, \f$\theta_2 \f$, \f$\theta_3 \f$ are three angles for Euler angles, the rotation matrix R can be calculated by:\f[R =X(\theta_1)Y(\theta_2)Z(\theta_3) + * ={\begin{bmatrix}\cos\theta_{2}\cos\theta_{3}&-\cos\theta_{2}\sin\theta_{3}&\sin\theta_{2}\\\cos\theta_{1}\sin\theta_{3}+\cos\theta_{3}\sin\theta_{1}\sin\theta_{2}&\cos\theta_{1}\cos\theta_{3}-\sin\theta_{1}\sin\theta_{2}\sin\theta_{3}&-\cos\theta_{2}\sin\theta_{1}\\\sin\theta_{1}\sin\theta_{3}-\cos\theta_{1}\cos\theta_{3}\sin\theta_{2}&\cos\theta_{3}\sin\theta_{1}+\cos\theta_{1}\sin\theta_{2}\sin\theta_{3}&\cos\theta_{1}\cos_{2}\end{bmatrix}}\f] + * Rotation matrix M and R are equal. As long as \f$ s_{2} \neq 1 \f$, by comparing each element of two matrices ,the solution is\f$\begin{cases} \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = arcsin(m_{13}) \\\theta_3 = \arctan2(-m_{12},m_{11}) \end{cases}\f$. + * + * When \f$ s_{2}=1\f$ or \f$ s_{2}=-1\f$, the gimbal lock occurs. The function will prompt "WARNING: Gimbal Lock will occur. Euler angles is non-unique. For intrinsic rotations, we set the third angle to 0, and for external rotation, we set the first angle to 0.". + * + * When \f$ s_{2}=1\f$ , + * The rotation matrix R is \f$R = {\begin{bmatrix}0&0&1\\\sin(\theta_1+\theta_3)&\cos(\theta_1+\theta_3)&0\\-\cos(\theta_1+\theta_3)&\sin(\theta_1+\theta_3)&0\end{bmatrix}}\f$. + * + * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{21},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. + * + * We set \f$ \theta_3 = 0\f$, the solution is \f$\begin{cases} \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \end{cases}\f$. + * + * When \f$ s_{2}=-1\f$, + * The rotation matrix R is \f$X_{1}Y_{2}Z_{3}={\begin{bmatrix}0&0&-1\\-\sin(\theta_1-\theta_3)&\cos(\theta_1-\theta_3)&0\\\cos(\theta_1-\theta_3)&\sin(\theta_1-\theta_3)&0\end{bmatrix}}\f$. + * + * The number of solutions is infinite with the condition \f$\begin{cases} \theta_1+\theta_3 = \arctan2(m_{32},m_{22})\\ \theta_2=\pi/2 \end{cases}\ \f$. + * + * We set \f$ \theta_3 = 0\f$, the solution is \f$ \begin{cases}\theta_1=\arctan2(m_{32},m_{22}) \\ \theta_2=-\pi/2\\ \theta_3=0\end{cases}\f$. + * + * Since \f$ sin \theta\in [-1,1] \f$ and \f$ cos \theta \in [-1,1] \f$, the unnormalized quaternion will cause computational troubles. For this reason, this function will normalize the quaternion at first and @ref QuatAssumeType is not needed. + * + * When the gimbal lock occurs, we set \f$\theta_3 = 0\f$ for intrinsic rotations or \f$\theta_1 = 0\f$ for extrinsic rotations. + * + * As a result, for every Euler angles type, we can get solution as shown in the following table. + * EulerAnglesType | Ordinary | \f$\theta_2 = π/2\f$ | \f$\theta_2 = -π/2\f$ + * ------------- | -------------| -------------| ------------- + * INT_XYZ|\f$ \theta_1 = \arctan2(-m_{23},m_{33})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{12},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{32},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_XZY|\f$ \theta_1 = \arctan2(m_{32},m_{22})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{13},m_{11}) \f$|\f$ \theta_1=\arctan2(m_{31},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{23},m_{33})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_YXZ|\f$ \theta_1 = \arctan2(m_{13},m_{33})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{12},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_YZX|\f$ \theta_1 = \arctan2(-m_{31},m_{11})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{23},m_{22}) \f$|\f$ \theta_1=\arctan2(m_{13},m_{33})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{13},m_{12})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_ZXY|\f$ \theta_1 = \arctan2(-m_{12},m_{22})\\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{31},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * INT_ZYX|\f$ \theta_1 = \arctan2(m_{21},m_{11})\\\theta_2 = \arcsin(-m_{31}) \\\theta_3= \arctan2(m_{32},m_{33}) \f$|\f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi/2\\ \theta_3=0 \f$|\f$ \theta_1=\arctan2(-m_{12},m_{22})\\ \theta_2=-\pi/2\\ \theta_3=0 \f$ + * EXT_XYZ|\f$ \theta_1 = \arctan2(m_{32},m_{33})\\\theta_2 = \arcsin(-m_{31}) \\\ \theta_3 = \arctan2(m_{21},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{23},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{22}) \f$ + * EXT_XZY|\f$ \theta_1 = \arctan2(-m_{23},m_{22})\\\theta_2 = \arcsin(m_{21}) \\\theta_3= \arctan2(-m_{31},m_{11})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{13},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{13},m_{12}) \f$ + * EXT_YXZ|\f$ \theta_1 = \arctan2(-m_{31},m_{33}) \\\theta_2 = \arcsin(m_{32}) \\\theta_3= \arctan2(-m_{12},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ + * EXT_YZX|\f$ \theta_1 = \arctan2(m_{13},m_{11})\\\theta_2 = -\arcsin(m_{12}) \\\theta_3= \arctan2(m_{32},m_{22})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{31},m_{33}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{23},m_{33}) \f$ + * EXT_ZXY|\f$ \theta_1 = \arctan2(m_{21},m_{22})\\\theta_2 = -\arcsin(m_{23}) \\\theta_3= \arctan2(m_{13},m_{33})\f$|\f$ \theta_1= 0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{12},m_{11}) \f$|\f$ \theta_1= 0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(-m_{12},m_{11}) \f$ + * EXT_ZYX|\f$ \theta_1 = \arctan2(-m_{12},m_{11})\\\theta_2 = \arcsin(m_{13}) \\\theta_3= \arctan2(-m_{23},m_{33})\f$|\f$ \theta_1=0\\ \theta_2=\pi/2\\ \theta_3=\arctan2(m_{21},m_{22}) \f$|\f$ \theta_1=0\\ \theta_2=-\pi/2\\ \theta_3=\arctan2(m_{32},m_{22}) \f$ + * + * EulerAnglesType | Ordinary | \f$\theta_2 = 0\f$ | \f$\theta_2 = π\f$ + * ------------- | -------------| -------------| ------------- + * INT_XYX| \f$ \theta_1 = \arctan2(m_{21},-m_{31})\\\theta_2 =\arccos(m_{11}) \\\theta_3 = \arctan2(m_{12},m_{13}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{23},m_{22})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_XZX| \f$ \theta_1 = \arctan2(m_{31},m_{21})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{13},-m_{12}) \f$| \f$ \theta_1=\arctan2(m_{32},m_{33})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{32},m_{33})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_YXY| \f$ \theta_1 = \arctan2(m_{12},m_{32})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{21},-m_{23}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(-m_{31},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_YZY| \f$ \theta_1 = \arctan2(m_{32},-m_{12})\\\theta_2 = \arccos(m_{22}) \\\theta_3 =\arctan2(m_{23},m_{21}) \f$| \f$ \theta_1=\arctan2(m_{13},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{13},-m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_ZXZ| \f$ \theta_1 = \arctan2(-m_{13},m_{23})\\\theta_2 = \arccos(m_{33}) \\\theta_3 =\arctan2(m_{31},m_{32}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{22})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * INT_ZYZ| \f$ \theta_1 = \arctan2(m_{23},m_{13})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{32},-m_{31}) \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=0\\ \theta_3=0 \f$| \f$ \theta_1=\arctan2(m_{21},m_{11})\\ \theta_2=\pi\\ \theta_3=0 \f$ + * EXT_XYX| \f$ \theta_1 = \arctan2(m_{12},m_{13}) \\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{21},-m_{31})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3= \arctan2(m_{23},m_{22}) \f$ + * EXT_XZX| \f$ \theta_1 = \arctan2(m_{13},-m_{12})\\\theta_2 = \arccos(m_{11}) \\\theta_3 = \arctan2(m_{31},m_{21})\f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{32},m_{33}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{32},m_{33}) \f$ + * EXT_YXY| \f$ \theta_1 = \arctan2(m_{21},-m_{23})\\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{12},m_{32}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(-m_{31},m_{11}) \f$ + * EXT_YZY| \f$ \theta_1 = \arctan2(m_{23},m_{21}) \\\theta_2 = \arccos(m_{22}) \\\theta_3 = \arctan2(m_{32},-m_{12}) \f$| \f$ \theta_1= 0\\ \theta_2=0\\ \theta_3=\arctan2(m_{13},m_{11}) \f$| \f$ \theta_1=0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{13},-m_{11}) \f$ + * EXT_ZXZ| \f$ \theta_1 = \arctan2(m_{31},m_{32}) \\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(-m_{13},m_{23})\f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{22}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ + * EXT_ZYZ| \f$ \theta_1 = \arctan2(m_{32},-m_{31})\\\theta_2 = \arccos(m_{33}) \\\theta_3 = \arctan2(m_{23},m_{13}) \f$| \f$ \theta_1=0\\ \theta_2=0\\ \theta_3=\arctan2(m_{21},m_{11}) \f$| \f$ \theta_1= 0\\ \theta_2=\pi\\ \theta_3=\arctan2(m_{21},m_{11}) \f$ + * + * @param eulerAnglesType the convertion Euler angles type + */ + + Vec<_Tp, 3> toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType); + + _Tp w, x, y, z; + +}; + +template +Quat inv(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat sinh(const Quat &q); + +template +Quat cosh(const Quat &q); + +template +Quat tanh(const Quat &q); + +template +Quat sin(const Quat &q); + +template +Quat cos(const Quat &q); + +template +Quat tan(const Quat &q); + +template +Quat asinh(const Quat &q); + +template +Quat acosh(const Quat &q); + +template +Quat atanh(const Quat &q); + +template +Quat asin(const Quat &q); + +template +Quat acos(const Quat &q); + +template +Quat atan(const Quat &q); + +template +Quat power(const Quat &q, const Quat &p, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat exp(const Quat &q); + +template +Quat log(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat power(const Quat& q, const T x, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat crossProduct(const Quat &p, const Quat &q); + +template +Quat sqrt(const Quat &q, QuatAssumeType assumeUnit=QUAT_ASSUME_NOT_UNIT); + +template +Quat operator*(const T, const Quat&); + +template +Quat operator*(const Quat&, const T); + +template +std::ostream& operator<<(std::ostream&, const Quat&); + +using Quatd = Quat; +using Quatf = Quat; + +//! @} core +} + +#include "opencv2/core/quaternion.inl.hpp" + +#endif /* OPENCV_CORE_QUATERNION_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp index 9d5a6d86f1..4204806a82 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/quaternion.inl.hpp @@ -1,1063 +1,1063 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. -// Third party copyrights are property of their respective owners. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Author: Liangqian Kong -// Longbu Wang - -#ifndef OPENCV_CORE_QUATERNION_INL_HPP -#define OPENCV_CORE_QUATERNION_INL_HPP - -#ifndef OPENCV_CORE_QUATERNION_HPP -#error This is not a standalone header. Include quaternion.hpp instead. -#endif - -//@cond IGNORE -/////////////////////////////////////////////////////////////////////////////////////// -//Implementation -namespace cv { - -template -Quat::Quat() : w(0), x(0), y(0), z(0) {} - -template -Quat::Quat(const Vec &coeff):w(coeff[0]), x(coeff[1]), y(coeff[2]), z(coeff[3]){} - -template -Quat::Quat(const T qw, const T qx, const T qy, const T qz):w(qw), x(qx), y(qy), z(qz){} - -template -Quat Quat::createFromAngleAxis(const T angle, const Vec &axis) -{ - T w, x, y, z; - T vNorm = std::sqrt(axis.dot(axis)); - if (vNorm < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "this quaternion does not represent a rotation"); - } - const T angle_half = angle * T(0.5); - w = std::cos(angle_half); - const T sin_v = std::sin(angle_half); - const T sin_norm = sin_v / vNorm; - x = sin_norm * axis[0]; - y = sin_norm * axis[1]; - z = sin_norm * axis[2]; - return Quat(w, x, y, z); -} - -template -Quat Quat::createFromRotMat(InputArray _R) -{ - CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); - if (_R.rows() != 3 || _R.cols() != 3) - { - CV_Error(Error::StsBadArg, "Cannot convert matrix to quaternion: rotation matrix should be a 3x3 matrix"); - } - Matx R; - _R.copyTo(R); - - T S, w, x, y, z; - T trace = R(0, 0) + R(1, 1) + R(2, 2); - if (trace > 0) - { - S = std::sqrt(trace + 1) * T(2); - x = (R(1, 2) - R(2, 1)) / S; - y = (R(2, 0) - R(0, 2)) / S; - z = (R(0, 1) - R(1, 0)) / S; - w = -T(0.25) * S; - } - else if (R(0, 0) > R(1, 1) && R(0, 0) > R(2, 2)) - { - - S = std::sqrt(T(1.0) + R(0, 0) - R(1, 1) - R(2, 2)) * T(2); - x = -T(0.25) * S; - y = -(R(1, 0) + R(0, 1)) / S; - z = -(R(0, 2) + R(2, 0)) / S; - w = (R(1, 2) - R(2, 1)) / S; - } - else if (R(1, 1) > R(2, 2)) - { - S = std::sqrt(T(1.0) - R(0, 0) + R(1, 1) - R(2, 2)) * T(2); - x = (R(0, 1) + R(1, 0)) / S; - y = T(0.25) * S; - z = (R(1, 2) + R(2, 1)) / S; - w = (R(0, 2) - R(2, 0)) / S; - } - else - { - S = std::sqrt(T(1.0) - R(0, 0) - R(1, 1) + R(2, 2)) * T(2); - x = (R(0, 2) + R(2, 0)) / S; - y = (R(1, 2) + R(2, 1)) / S; - z = T(0.25) * S; - w = -(R(0, 1) - R(1, 0)) / S; - } - return Quat (w, x, y, z); -} - -template -Quat Quat::createFromRvec(InputArray _rvec) -{ - if (!((_rvec.cols() == 1 && _rvec.rows() == 3) || (_rvec.cols() == 3 && _rvec.rows() == 1))) { - CV_Error(Error::StsBadArg, "Cannot convert rotation vector to quaternion: The length of rotation vector should be 3"); - } - Vec rvec; - _rvec.copyTo(rvec); - T psi = std::sqrt(rvec.dot(rvec)); - if (abs(psi) < CV_QUAT_EPS) { - return Quat (1, 0, 0, 0); - } - Vec axis = rvec / psi; - return createFromAngleAxis(psi, axis); -} - -template -inline Quat Quat::operator-() const -{ - return Quat(-w, -x, -y, -z); -} - - -template -inline bool Quat::operator==(const Quat &q) const -{ - return (abs(w - q.w) < CV_QUAT_EPS && abs(x - q.x) < CV_QUAT_EPS && abs(y - q.y) < CV_QUAT_EPS && abs(z - q.z) < CV_QUAT_EPS); -} - -template -inline Quat Quat::operator+(const Quat &q1) const -{ - return Quat(w + q1.w, x + q1.x, y + q1.y, z + q1.z); -} - -template -inline Quat operator+(const T a, const Quat& q) -{ - return Quat(q.w + a, q.x, q.y, q.z); -} - -template -inline Quat operator+(const Quat& q, const T a) -{ - return Quat(q.w + a, q.x, q.y, q.z); -} - -template -inline Quat operator-(const T a, const Quat& q) -{ - return Quat(a - q.w, -q.x, -q.y, -q.z); -} - -template -inline Quat operator-(const Quat& q, const T a) -{ - return Quat(q.w - a, q.x, q.y, q.z); -} - -template -inline Quat Quat::operator-(const Quat &q1) const -{ - return Quat(w - q1.w, x - q1.x, y - q1.y, z - q1.z); -} - -template -inline Quat& Quat::operator+=(const Quat &q1) -{ - w += q1.w; - x += q1.x; - y += q1.y; - z += q1.z; - return *this; -} - -template -inline Quat& Quat::operator-=(const Quat &q1) -{ - w -= q1.w; - x -= q1.x; - y -= q1.y; - z -= q1.z; - return *this; -} - -template -inline Quat Quat::operator*(const Quat &q1) const -{ - Vec q{w, x, y, z}; - Vec q2{q1.w, q1.x, q1.y, q1.z}; - return Quat(q * q2); -} - - -template -Quat operator*(const Quat &q1, const T a) -{ - return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); -} - -template -Quat operator*(const T a, const Quat &q1) -{ - return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); -} - -template -inline Quat& Quat::operator*=(const Quat &q1) -{ - T qw, qx, qy, qz; - qw = w * q1.w - x * q1.x - y * q1.y - z * q1.z; - qx = x * q1.w + w * q1.x + y * q1.z - z * q1.y; - qy = y * q1.w + w * q1.y + z * q1.x - x * q1.z; - qz = z * q1.w + w * q1.z + x * q1.y - y * q1.x; - w = qw; - x = qx; - y = qy; - z = qz; - return *this; -} - -template -inline Quat& Quat::operator/=(const Quat &q1) -{ - Quat q(*this * q1.inv()); - w = q.w; - x = q.x; - y = q.y; - z = q.z; - return *this; -} -template -Quat& Quat::operator*=(const T q1) -{ - w *= q1; - x *= q1; - y *= q1; - z *= q1; - return *this; -} - -template -inline Quat& Quat::operator/=(const T a) -{ - const T a_inv = 1.0 / a; - w *= a_inv; - x *= a_inv; - y *= a_inv; - z *= a_inv; - return *this; -} - -template -inline Quat Quat::operator/(const T a) const -{ - const T a_inv = T(1.0) / a; - return Quat(w * a_inv, x * a_inv, y * a_inv, z * a_inv); -} - -template -inline Quat Quat::operator/(const Quat &q) const -{ - return *this * q.inv(); -} - -template -inline const T& Quat::operator[](std::size_t n) const -{ - switch (n) { - case 0: - return w; - case 1: - return x; - case 2: - return y; - case 3: - return z; - default: - CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); - } -} - -template -inline T& Quat::operator[](std::size_t n) -{ - switch (n) { - case 0: - return w; - case 1: - return x; - case 2: - return y; - case 3: - return z; - default: - CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); - } -} - -template -std::ostream & operator<<(std::ostream &os, const Quat &q) -{ - os << "Quat " << Vec{q.w, q.x, q.y, q.z}; - return os; -} - -template -inline T Quat::at(size_t index) const -{ - return (*this)[index]; -} - -template -inline Quat Quat::conjugate() const -{ - return Quat(w, -x, -y, -z); -} - -template -inline T Quat::norm() const -{ - return std::sqrt(dot(*this)); -} - -template -Quat exp(const Quat &q) -{ - return q.exp(); -} - -template -Quat Quat::exp() const -{ - Vec v{x, y, z}; - T normV = std::sqrt(v.dot(v)); - T k = normV < CV_QUAT_EPS ? 1 : std::sin(normV) / normV; - return std::exp(w) * Quat(std::cos(normV), v[0] * k, v[1] * k, v[2] * k); -} - -template -Quat log(const Quat &q, QuatAssumeType assumeUnit) -{ - return q.log(assumeUnit); -} - -template -Quat Quat::log(QuatAssumeType assumeUnit) const -{ - Vec v{x, y, z}; - T vNorm = std::sqrt(v.dot(v)); - if (assumeUnit) - { - T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w) / vNorm; - return Quat(0, v[0] * k, v[1] * k, v[2] * k); - } - T qNorm = norm(); - if (qNorm < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "Cannot apply this quaternion to log function: undefined"); - } - T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w / qNorm) / vNorm; - return Quat(std::log(qNorm), v[0] * k, v[1] * k, v[2] *k); -} - -template -inline Quat power(const Quat &q1, const T alpha, QuatAssumeType assumeUnit) -{ - return q1.power(alpha, assumeUnit); -} - -template -inline Quat Quat::power(const T alpha, QuatAssumeType assumeUnit) const -{ - if (x * x + y * y + z * z > CV_QUAT_EPS) - { - T angle = getAngle(assumeUnit); - Vec axis = getAxis(assumeUnit); - if (assumeUnit) - { - return createFromAngleAxis(alpha * angle, axis); - } - return std::pow(norm(), alpha) * createFromAngleAxis(alpha * angle, axis); - } - else - { - return std::pow(norm(), alpha) * Quat(w, x, y, z); - } -} - - -template -inline Quat sqrt(const Quat &q, QuatAssumeType assumeUnit) -{ - return q.sqrt(assumeUnit); -} - -template -inline Quat Quat::sqrt(QuatAssumeType assumeUnit) const -{ - return power(0.5, assumeUnit); -} - - -template -inline Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit) -{ - return p.power(q, assumeUnit); -} - - -template -inline Quat Quat::power(const Quat &q, QuatAssumeType assumeUnit) const -{ - return cv::exp(q * log(assumeUnit)); -} - -template -inline T Quat::dot(Quat q1) const -{ - return w * q1.w + x * q1.x + y * q1.y + z * q1.z; -} - - -template -inline Quat crossProduct(const Quat &p, const Quat &q) -{ - return p.crossProduct(q); -} - - -template -inline Quat Quat::crossProduct(const Quat &q) const -{ - return Quat (0, y * q.z - z * q.y, z * q.x - x * q.z, x * q.y - q.x * y); -} - -template -inline Quat Quat::normalize() const -{ - T normVal = norm(); - if (normVal < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "Cannot normalize this quaternion: the norm is too small."); - } - return Quat(w / normVal, x / normVal, y / normVal, z / normVal) ; -} - -template -inline Quat inv(const Quat &q, QuatAssumeType assumeUnit) -{ - return q.inv(assumeUnit); -} - - -template -inline Quat Quat::inv(QuatAssumeType assumeUnit) const -{ - if (assumeUnit) - { - return conjugate(); - } - T norm2 = dot(*this); - if (norm2 < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "This quaternion do not have inverse quaternion"); - } - return conjugate() / norm2; -} - -template -inline Quat sinh(const Quat &q) -{ - return q.sinh(); -} - - -template -inline Quat Quat::sinh() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::cosh(w) * std::sin(vNorm) / vNorm; - return Quat(std::sinh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); -} - - -template -inline Quat cosh(const Quat &q) -{ - return q.cosh(); -} - - -template -inline Quat Quat::cosh() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::sinh(w) * std::sin(vNorm) / vNorm; - return Quat(std::cosh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); -} - -template -inline Quat tanh(const Quat &q) -{ - return q.tanh(); -} - -template -inline Quat Quat::tanh() const -{ - return sinh() * cosh().inv(); -} - - -template -inline Quat sin(const Quat &q) -{ - return q.sin(); -} - - -template -inline Quat Quat::sin() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::cos(w) * std::sinh(vNorm) / vNorm; - return Quat(std::sin(w) * std::cosh(vNorm), v[0] * k, v[1] * k, v[2] * k); -} - -template -inline Quat cos(const Quat &q) -{ - return q.cos(); -} - -template -inline Quat Quat::cos() const -{ - Vec v{x, y ,z}; - T vNorm = std::sqrt(v.dot(v)); - T k = vNorm < CV_QUAT_EPS ? 1 : std::sin(w) * std::sinh(vNorm) / vNorm; - return Quat(std::cos(w) * std::cosh(vNorm), -v[0] * k, -v[1] * k, -v[2] * k); -} - -template -inline Quat tan(const Quat &q) -{ - return q.tan(); -} - -template -inline Quat Quat::tan() const -{ - return sin() * cos().inv(); -} - -template -inline Quat asinh(const Quat &q) -{ - return q.asinh(); -} - -template -inline Quat Quat::asinh() const -{ - return cv::log(*this + cv::power(*this * *this + Quat(1, 0, 0, 0), 0.5)); -} - -template -inline Quat acosh(const Quat &q) -{ - return q.acosh(); -} - -template -inline Quat Quat::acosh() const -{ - return cv::log(*this + cv::power(*this * *this - Quat(1,0,0,0), 0.5)); -} - -template -inline Quat atanh(const Quat &q) -{ - return q.atanh(); -} - -template -inline Quat Quat::atanh() const -{ - Quat ident(1, 0, 0, 0); - Quat c1 = (ident + *this).log(); - Quat c2 = (ident - *this).log(); - return 0.5 * (c1 - c2); -} - -template -inline Quat asin(const Quat &q) -{ - return q.asin(); -} - -template -inline Quat Quat::asin() const -{ - Quat v(0, x, y, z); - T vNorm = v.norm(); - T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; - return -v / k * (*this * v / k).asinh(); -} - -template -inline Quat acos(const Quat &q) -{ - return q.acos(); -} - -template -inline Quat Quat::acos() const -{ - Quat v(0, x, y, z); - T vNorm = v.norm(); - T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; - return -v / k * acosh(); -} - -template -inline Quat atan(const Quat &q) -{ - return q.atan(); -} - -template -inline Quat Quat::atan() const -{ - Quat v(0, x, y, z); - T vNorm = v.norm(); - T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; - return -v / k * (*this * v / k).atanh(); -} - -template -inline T Quat::getAngle(QuatAssumeType assumeUnit) const -{ - if (assumeUnit) - { - return 2 * std::acos(w); - } - if (norm() < CV_QUAT_EPS) - { - CV_Error(Error::StsBadArg, "This quaternion does not represent a rotation"); - } - return 2 * std::acos(w / norm()); -} - -template -inline Vec Quat::getAxis(QuatAssumeType assumeUnit) const -{ - T angle = getAngle(assumeUnit); - const T sin_v = std::sin(angle * 0.5); - if (assumeUnit) - { - return Vec{x, y, z} / sin_v; - } - return Vec {x, y, z} / (norm() * sin_v); -} - -template -Matx Quat::toRotMat4x4(QuatAssumeType assumeUnit) const -{ - T a = w, b = x, c = y, d = z; - if (!assumeUnit) - { - Quat qTemp = normalize(); - a = qTemp.w; - b = qTemp.x; - c = qTemp.y; - d = qTemp.z; - } - Matx R{ - 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c) , 0, - 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b) , 0, - 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c), 0, - 0 , 0 , 0 , 1, - }; - return R; -} - -template -Matx Quat::toRotMat3x3(QuatAssumeType assumeUnit) const -{ - T a = w, b = x, c = y, d = z; - if (!assumeUnit) - { - Quat qTemp = normalize(); - a = qTemp.w; - b = qTemp.x; - c = qTemp.y; - d = qTemp.z; - } - Matx R{ - 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c), - 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b), - 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c) - }; - return R; -} - -template -Vec Quat::toRotVec(QuatAssumeType assumeUnit) const -{ - T angle = getAngle(assumeUnit); - Vec axis = getAxis(assumeUnit); - return angle * axis; -} - -template -Vec Quat::toVec() const -{ - return Vec{w, x, y, z}; -} - -template -Quat Quat::lerp(const Quat &q0, const Quat &q1, const T t) -{ - return (1 - t) * q0 + t * q1; -} - -template -Quat Quat::slerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit, bool directChange) -{ - Quat v0(q0); - Quat v1(q1); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - } - T cosTheta = v0.dot(v1); - constexpr T DOT_THRESHOLD = 0.995; - if (std::abs(cosTheta) > DOT_THRESHOLD) - { - return nlerp(v0, v1, t, QUAT_ASSUME_UNIT); - } - - if (directChange && cosTheta < 0) - { - v0 = -v0; - cosTheta = -cosTheta; - } - T sinTheta = std::sqrt(1 - cosTheta * cosTheta); - T angle = atan2(sinTheta, cosTheta); - return (std::sin((1 - t) * angle) / (sinTheta) * v0 + std::sin(t * angle) / (sinTheta) * v1).normalize(); -} - - -template -inline Quat Quat::nlerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit) -{ - Quat v0(q0), v1(q1); - if (v1.dot(v0) < 0) - { - v0 = -v0; - } - if (assumeUnit) - { - return ((1 - t) * v0 + t * v1).normalize(); - } - v0 = v0.normalize(); - v1 = v1.normalize(); - return ((1 - t) * v0 + t * v1).normalize(); -} - - -template -inline bool Quat::isNormal(T eps) const -{ - - double normVar = norm(); - if ((normVar > 1 - eps) && (normVar < 1 + eps)) - return true; - return false; -} - -template -inline void Quat::assertNormal(T eps) const -{ - if (!isNormal(eps)) - CV_Error(Error::StsBadArg, "Quaternion should be normalized"); -} - - -template -inline Quat Quat::squad(const Quat &q0, const Quat &q1, - const Quat &q2, const Quat &q3, - const T t, QuatAssumeType assumeUnit, - bool directChange) -{ - Quat v0(q0), v1(q1), v2(q2), v3(q3); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - v2 = v2.normalize(); - v3 = v3.normalize(); - } - - Quat c0 = slerp(v0, v3, t, assumeUnit, directChange); - Quat c1 = slerp(v1, v2, t, assumeUnit, directChange); - return slerp(c0, c1, 2 * t * (1 - t), assumeUnit, directChange); -} - -template -Quat Quat::interPoint(const Quat &q0, const Quat &q1, - const Quat &q2, QuatAssumeType assumeUnit) -{ - Quat v0(q0), v1(q1), v2(q2); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - v2 = v2.normalize(); - } - return v1 * cv::exp(-(cv::log(v1.conjugate() * v0, assumeUnit) + (cv::log(v1.conjugate() * v2, assumeUnit))) / 4); -} - -template -Quat Quat::spline(const Quat &q0, const Quat &q1, const Quat &q2, const Quat &q3, const T t, QuatAssumeType assumeUnit) -{ - Quat v0(q0), v1(q1), v2(q2), v3(q3); - if (!assumeUnit) - { - v0 = v0.normalize(); - v1 = v1.normalize(); - v2 = v2.normalize(); - v3 = v3.normalize(); - } - T cosTheta; - std::vector> vec{v0, v1, v2, v3}; - for (size_t i = 0; i < 3; ++i) - { - cosTheta = vec[i].dot(vec[i + 1]); - if (cosTheta < 0) - { - vec[i + 1] = -vec[i + 1]; - } - } - Quat s1 = interPoint(vec[0], vec[1], vec[2], QUAT_ASSUME_UNIT); - Quat s2 = interPoint(vec[1], vec[2], vec[3], QUAT_ASSUME_UNIT); - return squad(vec[1], s1, s2, vec[2], t, assumeUnit, QUAT_ASSUME_NOT_UNIT); -} - -namespace detail { - -template static -Quat createFromAxisRot(int axis, const T theta) -{ - if (axis == 0) - return Quat::createFromXRot(theta); - if (axis == 1) - return Quat::createFromYRot(theta); - if (axis == 2) - return Quat::createFromZRot(theta); - CV_Assert(0); -} - -inline bool isIntAngleType(QuatEnum::EulerAnglesType eulerAnglesType) -{ - return eulerAnglesType < QuatEnum::EXT_XYZ; -} - -inline bool isTaitBryan(QuatEnum::EulerAnglesType eulerAnglesType) -{ - return eulerAnglesType/6 == 1 || eulerAnglesType/6 == 3; -} -} // namespace detail - -template -Quat Quat::createFromYRot(const T theta) -{ - return Quat{std::cos(theta * 0.5f), 0, std::sin(theta * 0.5f), 0}; -} - -template -Quat Quat::createFromXRot(const T theta){ - return Quat{std::cos(theta * 0.5f), std::sin(theta * 0.5f), 0, 0}; -} - -template -Quat Quat::createFromZRot(const T theta){ - return Quat{std::cos(theta * 0.5f), 0, 0, std::sin(theta * 0.5f)}; -} - - -template -Quat Quat::createFromEulerAngles(const Vec &angles, QuatEnum::EulerAnglesType eulerAnglesType) { - CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); - static const int rotationAxis[24][3] = { - {0, 1, 2}, ///< Intrinsic rotations with the Euler angles type X-Y-Z - {0, 2, 1}, ///< Intrinsic rotations with the Euler angles type X-Z-Y - {1, 0, 2}, ///< Intrinsic rotations with the Euler angles type Y-X-Z - {1, 2, 0}, ///< Intrinsic rotations with the Euler angles type Y-Z-X - {2, 0, 1}, ///< Intrinsic rotations with the Euler angles type Z-X-Y - {2, 1, 0}, ///< Intrinsic rotations with the Euler angles type Z-Y-X - {0, 1, 0}, ///< Intrinsic rotations with the Euler angles type X-Y-X - {0, 2, 0}, ///< Intrinsic rotations with the Euler angles type X-Z-X - {1, 0, 1}, ///< Intrinsic rotations with the Euler angles type Y-X-Y - {1, 2, 1}, ///< Intrinsic rotations with the Euler angles type Y-Z-Y - {2, 0, 2}, ///< Intrinsic rotations with the Euler angles type Z-X-Z - {2, 1, 2}, ///< Intrinsic rotations with the Euler angles type Z-Y-Z - {0, 1, 2}, ///< Extrinsic rotations with the Euler angles type X-Y-Z - {0, 2, 1}, ///< Extrinsic rotations with the Euler angles type X-Z-Y - {1, 0, 2}, ///< Extrinsic rotations with the Euler angles type Y-X-Z - {1, 2, 0}, ///< Extrinsic rotations with the Euler angles type Y-Z-X - {2, 0, 1}, ///< Extrinsic rotations with the Euler angles type Z-X-Y - {2, 1, 0}, ///< Extrinsic rotations with the Euler angles type Z-Y-X - {0, 1, 0}, ///< Extrinsic rotations with the Euler angles type X-Y-X - {0, 2, 0}, ///< Extrinsic rotations with the Euler angles type X-Z-X - {1, 0, 1}, ///< Extrinsic rotations with the Euler angles type Y-X-Y - {1, 2, 1}, ///< Extrinsic rotations with the Euler angles type Y-Z-Y - {2, 0, 2}, ///< Extrinsic rotations with the Euler angles type Z-X-Z - {2, 1, 2} ///< Extrinsic rotations with the Euler angles type Z-Y-Z - }; - Quat q1 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][0], angles(0)); - Quat q2 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][1], angles(1)); - Quat q3 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][2], angles(2)); - if (detail::isIntAngleType(eulerAnglesType)) - { - return q1 * q2 * q3; - } - else // (!detail::isIntAngleType(eulerAnglesType)) - { - return q3 * q2 * q1; - } -} - -template -Vec Quat::toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType){ - CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); - Matx33d R = toRotMat3x3(); - enum { - C_ZERO, - C_PI, - C_PI_2, - N_CONSTANTS, - R_0_0 = N_CONSTANTS, R_0_1, R_0_2, - R_1_0, R_1_1, R_1_2, - R_2_0, R_2_1, R_2_2 - }; - static const T constants_[N_CONSTANTS] = { - 0, // C_ZERO - (T)CV_PI, // C_PI - (T)(CV_PI * 0.5) // C_PI_2, -C_PI_2 - }; - static const int rotationR_[24][12] = { - {+R_0_2, +R_1_0, +R_1_1, C_PI_2, +R_2_1, +R_1_1, -C_PI_2, -R_1_2, +R_2_2, +R_0_2, -R_0_1, +R_0_0}, // INT_XYZ - {+R_0_1, -R_1_2, +R_2_2, -C_PI_2, +R_2_0, +R_2_2, C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_2, +R_0_0}, // INT_XZY - {+R_1_2, -R_0_1, +R_0_0, -C_PI_2, +R_0_1, +R_0_0, C_PI_2, +R_0_2, +R_2_2, -R_1_2, +R_1_0, +R_1_1}, // INT_YXZ - {+R_1_0, +R_0_2, +R_2_2, C_PI_2, +R_0_2, +R_0_1, -C_PI_2, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1}, // INT_YZX - {+R_2_1, +R_1_0, +R_0_0, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, -R_0_1, +R_1_1, +R_2_1, -R_2_0, +R_2_2}, // INT_ZXY - {+R_2_0, -R_0_1, +R_1_1, -C_PI_2, +R_1_2, +R_1_1, C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_1, +R_2_2}, // INT_ZYX - {+R_0_0, +R_2_1, +R_2_2, C_ZERO, +R_1_2, +R_1_1, C_PI, +R_1_0, -R_2_0, +R_0_0, +R_0_1, +R_0_2}, // INT_XYX - {+R_0_0, +R_2_1, +R_2_2, C_ZERO, -R_2_1, +R_2_2, C_PI, +R_2_0, +R_1_0, +R_0_0, +R_0_2, -R_0_1}, // INT_XZX - {+R_1_1, +R_0_2, +R_0_0, C_ZERO, -R_2_0, +R_0_0, C_PI, +R_0_1, +R_2_1, +R_1_1, +R_1_0, -R_1_2}, // INT_YXY - {+R_1_1, +R_0_2, +R_0_0, C_ZERO, +R_0_2, -R_0_0, C_PI, +R_2_1, -R_0_1, +R_1_1, +R_1_2, +R_1_0}, // INT_YZY - {+R_2_2, +R_1_0, +R_1_1, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_0_2, -R_1_2, +R_2_2, +R_2_0, +R_2_1}, // INT_ZXZ - {+R_2_2, +R_1_0, +R_0_0, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_2, +R_0_2, +R_2_2, +R_2_1, -R_2_0}, // INT_ZYZ - - {+R_2_0, -C_PI_2, -R_0_1, +R_1_1, C_PI_2, +R_1_2, +R_1_1, +R_2_1, +R_2_2, -R_2_0, +R_1_0, +R_0_0}, // EXT_XYZ - {+R_1_0, C_PI_2, +R_0_2, +R_2_2, -C_PI_2, +R_0_2, +R_0_1, -R_1_2, +R_1_1, +R_1_0, -R_2_0, +R_0_0}, // EXT_XZY - {+R_2_1, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_2, +R_2_1, -R_0_1, +R_1_1}, // EXT_YXZ - {+R_0_2, -C_PI_2, -R_1_2, +R_2_2, C_PI_2, +R_2_0, +R_2_2, +R_0_2, +R_0_0, -R_0_1, +R_2_1, +R_1_1}, // EXT_YZX - {+R_1_2, -C_PI_2, -R_0_1, +R_0_0, C_PI_2, +R_0_1, +R_0_0, +R_1_0, +R_1_1, -R_1_2, +R_0_2, +R_2_2}, // EXT_ZXY - {+R_0_2, C_PI_2, +R_1_0, +R_1_1, -C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_0, +R_0_2, -R_1_2, +R_2_2}, // EXT_ZYX - {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_1_2, +R_1_1, +R_0_1, +R_0_2, +R_0_0, +R_1_0, -R_2_0}, // EXT_XYX - {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_2_1, +R_2_2, +R_0_2, -R_0_1, +R_0_0, +R_2_0, +R_1_0}, // EXT_XZX - {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1, +R_0_1, +R_2_1}, // EXT_YXY - {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, +R_0_2, -R_0_0, +R_1_2, +R_1_0, +R_1_1, +R_2_1, -R_0_1}, // EXT_YZY - {+R_2_2, C_ZERO, +R_1_0, +R_1_1, C_PI, +R_1_0, +R_0_0, +R_2_0, +R_2_1, +R_2_2, +R_0_2, -R_1_2}, // EXT_ZXZ - {+R_2_2, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_0, +R_0_0, +R_2_1, -R_2_0, +R_2_2, +R_1_2, +R_0_2}, // EXT_ZYZ - }; - T rotationR[12]; - for (int i = 0; i < 12; i++) - { - int id = rotationR_[eulerAnglesType][i]; - unsigned idx = std::abs(id); - T value = 0.0f; - if (idx < N_CONSTANTS) - { - value = constants_[idx]; - } - else - { - unsigned r_idx = idx - N_CONSTANTS; - CV_DbgAssert(r_idx < 9); - value = R.val[r_idx]; - } - bool isNegative = id < 0; - if (isNegative) - value = -value; - rotationR[i] = value; - } - Vec angles; - if (detail::isIntAngleType(eulerAnglesType)) - { - if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); - angles = {std::atan2(rotationR[1], rotationR[2]), rotationR[3], 0}; - return angles; - } - else if(abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); - angles = {std::atan2(rotationR[4], rotationR[5]), rotationR[6], 0}; - return angles; - } - } - else // (!detail::isIntAngleType(eulerAnglesType)) - { - if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); - angles = {0, rotationR[1], std::atan2(rotationR[2], rotationR[3])}; - return angles; - } - else if (abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) - { - CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); - angles = {0, rotationR[4], std::atan2(rotationR[5], rotationR[6])}; - return angles; - } - } - - angles(0) = std::atan2(rotationR[7], rotationR[8]); - if (detail::isTaitBryan(eulerAnglesType)) - angles(1) = std::acos(rotationR[9]); - else - angles(1) = std::asin(rotationR[9]); - angles(2) = std::atan2(rotationR[10], rotationR[11]); - return angles; -} - -} // namepsace -//! @endcond - -#endif /*OPENCV_CORE_QUATERNION_INL_HPP*/ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2020, Huawei Technologies Co., Ltd. All rights reserved. +// Third party copyrights are property of their respective owners. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +// Author: Liangqian Kong +// Longbu Wang + +#ifndef OPENCV_CORE_QUATERNION_INL_HPP +#define OPENCV_CORE_QUATERNION_INL_HPP + +#ifndef OPENCV_CORE_QUATERNION_HPP +#error This is not a standalone header. Include quaternion.hpp instead. +#endif + +//@cond IGNORE +/////////////////////////////////////////////////////////////////////////////////////// +//Implementation +namespace cv { + +template +Quat::Quat() : w(0), x(0), y(0), z(0) {} + +template +Quat::Quat(const Vec &coeff):w(coeff[0]), x(coeff[1]), y(coeff[2]), z(coeff[3]){} + +template +Quat::Quat(const T qw, const T qx, const T qy, const T qz):w(qw), x(qx), y(qy), z(qz){} + +template +Quat Quat::createFromAngleAxis(const T angle, const Vec &axis) +{ + T w, x, y, z; + T vNorm = std::sqrt(axis.dot(axis)); + if (vNorm < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "this quaternion does not represent a rotation"); + } + const T angle_half = angle * T(0.5); + w = std::cos(angle_half); + const T sin_v = std::sin(angle_half); + const T sin_norm = sin_v / vNorm; + x = sin_norm * axis[0]; + y = sin_norm * axis[1]; + z = sin_norm * axis[2]; + return Quat(w, x, y, z); +} + +template +Quat Quat::createFromRotMat(InputArray _R) +{ + CV_CheckTypeEQ(_R.type(), cv::traits::Type::value, ""); + if (_R.rows() != 3 || _R.cols() != 3) + { + CV_Error(Error::StsBadArg, "Cannot convert matrix to quaternion: rotation matrix should be a 3x3 matrix"); + } + Matx R; + _R.copyTo(R); + + T S, w, x, y, z; + T trace = R(0, 0) + R(1, 1) + R(2, 2); + if (trace > 0) + { + S = std::sqrt(trace + 1) * T(2); + x = (R(1, 2) - R(2, 1)) / S; + y = (R(2, 0) - R(0, 2)) / S; + z = (R(0, 1) - R(1, 0)) / S; + w = -T(0.25) * S; + } + else if (R(0, 0) > R(1, 1) && R(0, 0) > R(2, 2)) + { + + S = std::sqrt(T(1.0) + R(0, 0) - R(1, 1) - R(2, 2)) * T(2); + x = -T(0.25) * S; + y = -(R(1, 0) + R(0, 1)) / S; + z = -(R(0, 2) + R(2, 0)) / S; + w = (R(1, 2) - R(2, 1)) / S; + } + else if (R(1, 1) > R(2, 2)) + { + S = std::sqrt(T(1.0) - R(0, 0) + R(1, 1) - R(2, 2)) * T(2); + x = (R(0, 1) + R(1, 0)) / S; + y = T(0.25) * S; + z = (R(1, 2) + R(2, 1)) / S; + w = (R(0, 2) - R(2, 0)) / S; + } + else + { + S = std::sqrt(T(1.0) - R(0, 0) - R(1, 1) + R(2, 2)) * T(2); + x = (R(0, 2) + R(2, 0)) / S; + y = (R(1, 2) + R(2, 1)) / S; + z = T(0.25) * S; + w = -(R(0, 1) - R(1, 0)) / S; + } + return Quat (w, x, y, z); +} + +template +Quat Quat::createFromRvec(InputArray _rvec) +{ + if (!((_rvec.cols() == 1 && _rvec.rows() == 3) || (_rvec.cols() == 3 && _rvec.rows() == 1))) { + CV_Error(Error::StsBadArg, "Cannot convert rotation vector to quaternion: The length of rotation vector should be 3"); + } + Vec rvec; + _rvec.copyTo(rvec); + T psi = std::sqrt(rvec.dot(rvec)); + if (abs(psi) < CV_QUAT_EPS) { + return Quat (1, 0, 0, 0); + } + Vec axis = rvec / psi; + return createFromAngleAxis(psi, axis); +} + +template +inline Quat Quat::operator-() const +{ + return Quat(-w, -x, -y, -z); +} + + +template +inline bool Quat::operator==(const Quat &q) const +{ + return (abs(w - q.w) < CV_QUAT_EPS && abs(x - q.x) < CV_QUAT_EPS && abs(y - q.y) < CV_QUAT_EPS && abs(z - q.z) < CV_QUAT_EPS); +} + +template +inline Quat Quat::operator+(const Quat &q1) const +{ + return Quat(w + q1.w, x + q1.x, y + q1.y, z + q1.z); +} + +template +inline Quat operator+(const T a, const Quat& q) +{ + return Quat(q.w + a, q.x, q.y, q.z); +} + +template +inline Quat operator+(const Quat& q, const T a) +{ + return Quat(q.w + a, q.x, q.y, q.z); +} + +template +inline Quat operator-(const T a, const Quat& q) +{ + return Quat(a - q.w, -q.x, -q.y, -q.z); +} + +template +inline Quat operator-(const Quat& q, const T a) +{ + return Quat(q.w - a, q.x, q.y, q.z); +} + +template +inline Quat Quat::operator-(const Quat &q1) const +{ + return Quat(w - q1.w, x - q1.x, y - q1.y, z - q1.z); +} + +template +inline Quat& Quat::operator+=(const Quat &q1) +{ + w += q1.w; + x += q1.x; + y += q1.y; + z += q1.z; + return *this; +} + +template +inline Quat& Quat::operator-=(const Quat &q1) +{ + w -= q1.w; + x -= q1.x; + y -= q1.y; + z -= q1.z; + return *this; +} + +template +inline Quat Quat::operator*(const Quat &q1) const +{ + Vec q{w, x, y, z}; + Vec q2{q1.w, q1.x, q1.y, q1.z}; + return Quat(q * q2); +} + + +template +Quat operator*(const Quat &q1, const T a) +{ + return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); +} + +template +Quat operator*(const T a, const Quat &q1) +{ + return Quat(a * q1.w, a * q1.x, a * q1.y, a * q1.z); +} + +template +inline Quat& Quat::operator*=(const Quat &q1) +{ + T qw, qx, qy, qz; + qw = w * q1.w - x * q1.x - y * q1.y - z * q1.z; + qx = x * q1.w + w * q1.x + y * q1.z - z * q1.y; + qy = y * q1.w + w * q1.y + z * q1.x - x * q1.z; + qz = z * q1.w + w * q1.z + x * q1.y - y * q1.x; + w = qw; + x = qx; + y = qy; + z = qz; + return *this; +} + +template +inline Quat& Quat::operator/=(const Quat &q1) +{ + Quat q(*this * q1.inv()); + w = q.w; + x = q.x; + y = q.y; + z = q.z; + return *this; +} +template +Quat& Quat::operator*=(const T q1) +{ + w *= q1; + x *= q1; + y *= q1; + z *= q1; + return *this; +} + +template +inline Quat& Quat::operator/=(const T a) +{ + const T a_inv = 1.0 / a; + w *= a_inv; + x *= a_inv; + y *= a_inv; + z *= a_inv; + return *this; +} + +template +inline Quat Quat::operator/(const T a) const +{ + const T a_inv = T(1.0) / a; + return Quat(w * a_inv, x * a_inv, y * a_inv, z * a_inv); +} + +template +inline Quat Quat::operator/(const Quat &q) const +{ + return *this * q.inv(); +} + +template +inline const T& Quat::operator[](std::size_t n) const +{ + switch (n) { + case 0: + return w; + case 1: + return x; + case 2: + return y; + case 3: + return z; + default: + CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); + } +} + +template +inline T& Quat::operator[](std::size_t n) +{ + switch (n) { + case 0: + return w; + case 1: + return x; + case 2: + return y; + case 3: + return z; + default: + CV_Error(Error::StsOutOfRange, "subscript exceeds the index range"); + } +} + +template +std::ostream & operator<<(std::ostream &os, const Quat &q) +{ + os << "Quat " << Vec{q.w, q.x, q.y, q.z}; + return os; +} + +template +inline T Quat::at(size_t index) const +{ + return (*this)[index]; +} + +template +inline Quat Quat::conjugate() const +{ + return Quat(w, -x, -y, -z); +} + +template +inline T Quat::norm() const +{ + return std::sqrt(dot(*this)); +} + +template +Quat exp(const Quat &q) +{ + return q.exp(); +} + +template +Quat Quat::exp() const +{ + Vec v{x, y, z}; + T normV = std::sqrt(v.dot(v)); + T k = normV < CV_QUAT_EPS ? 1 : std::sin(normV) / normV; + return std::exp(w) * Quat(std::cos(normV), v[0] * k, v[1] * k, v[2] * k); +} + +template +Quat log(const Quat &q, QuatAssumeType assumeUnit) +{ + return q.log(assumeUnit); +} + +template +Quat Quat::log(QuatAssumeType assumeUnit) const +{ + Vec v{x, y, z}; + T vNorm = std::sqrt(v.dot(v)); + if (assumeUnit) + { + T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w) / vNorm; + return Quat(0, v[0] * k, v[1] * k, v[2] * k); + } + T qNorm = norm(); + if (qNorm < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "Cannot apply this quaternion to log function: undefined"); + } + T k = vNorm < CV_QUAT_EPS ? 1 : std::acos(w / qNorm) / vNorm; + return Quat(std::log(qNorm), v[0] * k, v[1] * k, v[2] *k); +} + +template +inline Quat power(const Quat &q1, const T alpha, QuatAssumeType assumeUnit) +{ + return q1.power(alpha, assumeUnit); +} + +template +inline Quat Quat::power(const T alpha, QuatAssumeType assumeUnit) const +{ + if (x * x + y * y + z * z > CV_QUAT_EPS) + { + T angle = getAngle(assumeUnit); + Vec axis = getAxis(assumeUnit); + if (assumeUnit) + { + return createFromAngleAxis(alpha * angle, axis); + } + return std::pow(norm(), alpha) * createFromAngleAxis(alpha * angle, axis); + } + else + { + return std::pow(norm(), alpha) * Quat(w, x, y, z); + } +} + + +template +inline Quat sqrt(const Quat &q, QuatAssumeType assumeUnit) +{ + return q.sqrt(assumeUnit); +} + +template +inline Quat Quat::sqrt(QuatAssumeType assumeUnit) const +{ + return power(0.5, assumeUnit); +} + + +template +inline Quat power(const Quat &p, const Quat &q, QuatAssumeType assumeUnit) +{ + return p.power(q, assumeUnit); +} + + +template +inline Quat Quat::power(const Quat &q, QuatAssumeType assumeUnit) const +{ + return cv::exp(q * log(assumeUnit)); +} + +template +inline T Quat::dot(Quat q1) const +{ + return w * q1.w + x * q1.x + y * q1.y + z * q1.z; +} + + +template +inline Quat crossProduct(const Quat &p, const Quat &q) +{ + return p.crossProduct(q); +} + + +template +inline Quat Quat::crossProduct(const Quat &q) const +{ + return Quat (0, y * q.z - z * q.y, z * q.x - x * q.z, x * q.y - q.x * y); +} + +template +inline Quat Quat::normalize() const +{ + T normVal = norm(); + if (normVal < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "Cannot normalize this quaternion: the norm is too small."); + } + return Quat(w / normVal, x / normVal, y / normVal, z / normVal) ; +} + +template +inline Quat inv(const Quat &q, QuatAssumeType assumeUnit) +{ + return q.inv(assumeUnit); +} + + +template +inline Quat Quat::inv(QuatAssumeType assumeUnit) const +{ + if (assumeUnit) + { + return conjugate(); + } + T norm2 = dot(*this); + if (norm2 < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "This quaternion do not have inverse quaternion"); + } + return conjugate() / norm2; +} + +template +inline Quat sinh(const Quat &q) +{ + return q.sinh(); +} + + +template +inline Quat Quat::sinh() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::cosh(w) * std::sin(vNorm) / vNorm; + return Quat(std::sinh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); +} + + +template +inline Quat cosh(const Quat &q) +{ + return q.cosh(); +} + + +template +inline Quat Quat::cosh() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::sinh(w) * std::sin(vNorm) / vNorm; + return Quat(std::cosh(w) * std::cos(vNorm), v[0] * k, v[1] * k, v[2] * k); +} + +template +inline Quat tanh(const Quat &q) +{ + return q.tanh(); +} + +template +inline Quat Quat::tanh() const +{ + return sinh() * cosh().inv(); +} + + +template +inline Quat sin(const Quat &q) +{ + return q.sin(); +} + + +template +inline Quat Quat::sin() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::cos(w) * std::sinh(vNorm) / vNorm; + return Quat(std::sin(w) * std::cosh(vNorm), v[0] * k, v[1] * k, v[2] * k); +} + +template +inline Quat cos(const Quat &q) +{ + return q.cos(); +} + +template +inline Quat Quat::cos() const +{ + Vec v{x, y ,z}; + T vNorm = std::sqrt(v.dot(v)); + T k = vNorm < CV_QUAT_EPS ? 1 : std::sin(w) * std::sinh(vNorm) / vNorm; + return Quat(std::cos(w) * std::cosh(vNorm), -v[0] * k, -v[1] * k, -v[2] * k); +} + +template +inline Quat tan(const Quat &q) +{ + return q.tan(); +} + +template +inline Quat Quat::tan() const +{ + return sin() * cos().inv(); +} + +template +inline Quat asinh(const Quat &q) +{ + return q.asinh(); +} + +template +inline Quat Quat::asinh() const +{ + return cv::log(*this + cv::power(*this * *this + Quat(1, 0, 0, 0), 0.5)); +} + +template +inline Quat acosh(const Quat &q) +{ + return q.acosh(); +} + +template +inline Quat Quat::acosh() const +{ + return cv::log(*this + cv::power(*this * *this - Quat(1,0,0,0), 0.5)); +} + +template +inline Quat atanh(const Quat &q) +{ + return q.atanh(); +} + +template +inline Quat Quat::atanh() const +{ + Quat ident(1, 0, 0, 0); + Quat c1 = (ident + *this).log(); + Quat c2 = (ident - *this).log(); + return 0.5 * (c1 - c2); +} + +template +inline Quat asin(const Quat &q) +{ + return q.asin(); +} + +template +inline Quat Quat::asin() const +{ + Quat v(0, x, y, z); + T vNorm = v.norm(); + T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; + return -v / k * (*this * v / k).asinh(); +} + +template +inline Quat acos(const Quat &q) +{ + return q.acos(); +} + +template +inline Quat Quat::acos() const +{ + Quat v(0, x, y, z); + T vNorm = v.norm(); + T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; + return -v / k * acosh(); +} + +template +inline Quat atan(const Quat &q) +{ + return q.atan(); +} + +template +inline Quat Quat::atan() const +{ + Quat v(0, x, y, z); + T vNorm = v.norm(); + T k = vNorm < CV_QUAT_EPS ? 1 : vNorm; + return -v / k * (*this * v / k).atanh(); +} + +template +inline T Quat::getAngle(QuatAssumeType assumeUnit) const +{ + if (assumeUnit) + { + return 2 * std::acos(w); + } + if (norm() < CV_QUAT_EPS) + { + CV_Error(Error::StsBadArg, "This quaternion does not represent a rotation"); + } + return 2 * std::acos(w / norm()); +} + +template +inline Vec Quat::getAxis(QuatAssumeType assumeUnit) const +{ + T angle = getAngle(assumeUnit); + const T sin_v = std::sin(angle * 0.5); + if (assumeUnit) + { + return Vec{x, y, z} / sin_v; + } + return Vec {x, y, z} / (norm() * sin_v); +} + +template +Matx Quat::toRotMat4x4(QuatAssumeType assumeUnit) const +{ + T a = w, b = x, c = y, d = z; + if (!assumeUnit) + { + Quat qTemp = normalize(); + a = qTemp.w; + b = qTemp.x; + c = qTemp.y; + d = qTemp.z; + } + Matx R{ + 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c) , 0, + 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b) , 0, + 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c), 0, + 0 , 0 , 0 , 1, + }; + return R; +} + +template +Matx Quat::toRotMat3x3(QuatAssumeType assumeUnit) const +{ + T a = w, b = x, c = y, d = z; + if (!assumeUnit) + { + Quat qTemp = normalize(); + a = qTemp.w; + b = qTemp.x; + c = qTemp.y; + d = qTemp.z; + } + Matx R{ + 1 - 2 * (c * c + d * d), 2 * (b * c - a * d) , 2 * (b * d + a * c), + 2 * (b * c + a * d) , 1 - 2 * (b * b + d * d), 2 * (c * d - a * b), + 2 * (b * d - a * c) , 2 * (c * d + a * b) , 1 - 2 * (b * b + c * c) + }; + return R; +} + +template +Vec Quat::toRotVec(QuatAssumeType assumeUnit) const +{ + T angle = getAngle(assumeUnit); + Vec axis = getAxis(assumeUnit); + return angle * axis; +} + +template +Vec Quat::toVec() const +{ + return Vec{w, x, y, z}; +} + +template +Quat Quat::lerp(const Quat &q0, const Quat &q1, const T t) +{ + return (1 - t) * q0 + t * q1; +} + +template +Quat Quat::slerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit, bool directChange) +{ + Quat v0(q0); + Quat v1(q1); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + } + T cosTheta = v0.dot(v1); + constexpr T DOT_THRESHOLD = 0.995; + if (std::abs(cosTheta) > DOT_THRESHOLD) + { + return nlerp(v0, v1, t, QUAT_ASSUME_UNIT); + } + + if (directChange && cosTheta < 0) + { + v0 = -v0; + cosTheta = -cosTheta; + } + T sinTheta = std::sqrt(1 - cosTheta * cosTheta); + T angle = atan2(sinTheta, cosTheta); + return (std::sin((1 - t) * angle) / (sinTheta) * v0 + std::sin(t * angle) / (sinTheta) * v1).normalize(); +} + + +template +inline Quat Quat::nlerp(const Quat &q0, const Quat &q1, const T t, QuatAssumeType assumeUnit) +{ + Quat v0(q0), v1(q1); + if (v1.dot(v0) < 0) + { + v0 = -v0; + } + if (assumeUnit) + { + return ((1 - t) * v0 + t * v1).normalize(); + } + v0 = v0.normalize(); + v1 = v1.normalize(); + return ((1 - t) * v0 + t * v1).normalize(); +} + + +template +inline bool Quat::isNormal(T eps) const +{ + + double normVar = norm(); + if ((normVar > 1 - eps) && (normVar < 1 + eps)) + return true; + return false; +} + +template +inline void Quat::assertNormal(T eps) const +{ + if (!isNormal(eps)) + CV_Error(Error::StsBadArg, "Quaternion should be normalized"); +} + + +template +inline Quat Quat::squad(const Quat &q0, const Quat &q1, + const Quat &q2, const Quat &q3, + const T t, QuatAssumeType assumeUnit, + bool directChange) +{ + Quat v0(q0), v1(q1), v2(q2), v3(q3); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + v2 = v2.normalize(); + v3 = v3.normalize(); + } + + Quat c0 = slerp(v0, v3, t, assumeUnit, directChange); + Quat c1 = slerp(v1, v2, t, assumeUnit, directChange); + return slerp(c0, c1, 2 * t * (1 - t), assumeUnit, directChange); +} + +template +Quat Quat::interPoint(const Quat &q0, const Quat &q1, + const Quat &q2, QuatAssumeType assumeUnit) +{ + Quat v0(q0), v1(q1), v2(q2); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + v2 = v2.normalize(); + } + return v1 * cv::exp(-(cv::log(v1.conjugate() * v0, assumeUnit) + (cv::log(v1.conjugate() * v2, assumeUnit))) / 4); +} + +template +Quat Quat::spline(const Quat &q0, const Quat &q1, const Quat &q2, const Quat &q3, const T t, QuatAssumeType assumeUnit) +{ + Quat v0(q0), v1(q1), v2(q2), v3(q3); + if (!assumeUnit) + { + v0 = v0.normalize(); + v1 = v1.normalize(); + v2 = v2.normalize(); + v3 = v3.normalize(); + } + T cosTheta; + std::vector> vec{v0, v1, v2, v3}; + for (size_t i = 0; i < 3; ++i) + { + cosTheta = vec[i].dot(vec[i + 1]); + if (cosTheta < 0) + { + vec[i + 1] = -vec[i + 1]; + } + } + Quat s1 = interPoint(vec[0], vec[1], vec[2], QUAT_ASSUME_UNIT); + Quat s2 = interPoint(vec[1], vec[2], vec[3], QUAT_ASSUME_UNIT); + return squad(vec[1], s1, s2, vec[2], t, assumeUnit, QUAT_ASSUME_NOT_UNIT); +} + +namespace detail { + +template static +Quat createFromAxisRot(int axis, const T theta) +{ + if (axis == 0) + return Quat::createFromXRot(theta); + if (axis == 1) + return Quat::createFromYRot(theta); + if (axis == 2) + return Quat::createFromZRot(theta); + CV_Assert(0); +} + +inline bool isIntAngleType(QuatEnum::EulerAnglesType eulerAnglesType) +{ + return eulerAnglesType < QuatEnum::EXT_XYZ; +} + +inline bool isTaitBryan(QuatEnum::EulerAnglesType eulerAnglesType) +{ + return eulerAnglesType/6 == 1 || eulerAnglesType/6 == 3; +} +} // namespace detail + +template +Quat Quat::createFromYRot(const T theta) +{ + return Quat{std::cos(theta * 0.5f), 0, std::sin(theta * 0.5f), 0}; +} + +template +Quat Quat::createFromXRot(const T theta){ + return Quat{std::cos(theta * 0.5f), std::sin(theta * 0.5f), 0, 0}; +} + +template +Quat Quat::createFromZRot(const T theta){ + return Quat{std::cos(theta * 0.5f), 0, 0, std::sin(theta * 0.5f)}; +} + + +template +Quat Quat::createFromEulerAngles(const Vec &angles, QuatEnum::EulerAnglesType eulerAnglesType) { + CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); + static const int rotationAxis[24][3] = { + {0, 1, 2}, ///< Intrinsic rotations with the Euler angles type X-Y-Z + {0, 2, 1}, ///< Intrinsic rotations with the Euler angles type X-Z-Y + {1, 0, 2}, ///< Intrinsic rotations with the Euler angles type Y-X-Z + {1, 2, 0}, ///< Intrinsic rotations with the Euler angles type Y-Z-X + {2, 0, 1}, ///< Intrinsic rotations with the Euler angles type Z-X-Y + {2, 1, 0}, ///< Intrinsic rotations with the Euler angles type Z-Y-X + {0, 1, 0}, ///< Intrinsic rotations with the Euler angles type X-Y-X + {0, 2, 0}, ///< Intrinsic rotations with the Euler angles type X-Z-X + {1, 0, 1}, ///< Intrinsic rotations with the Euler angles type Y-X-Y + {1, 2, 1}, ///< Intrinsic rotations with the Euler angles type Y-Z-Y + {2, 0, 2}, ///< Intrinsic rotations with the Euler angles type Z-X-Z + {2, 1, 2}, ///< Intrinsic rotations with the Euler angles type Z-Y-Z + {0, 1, 2}, ///< Extrinsic rotations with the Euler angles type X-Y-Z + {0, 2, 1}, ///< Extrinsic rotations with the Euler angles type X-Z-Y + {1, 0, 2}, ///< Extrinsic rotations with the Euler angles type Y-X-Z + {1, 2, 0}, ///< Extrinsic rotations with the Euler angles type Y-Z-X + {2, 0, 1}, ///< Extrinsic rotations with the Euler angles type Z-X-Y + {2, 1, 0}, ///< Extrinsic rotations with the Euler angles type Z-Y-X + {0, 1, 0}, ///< Extrinsic rotations with the Euler angles type X-Y-X + {0, 2, 0}, ///< Extrinsic rotations with the Euler angles type X-Z-X + {1, 0, 1}, ///< Extrinsic rotations with the Euler angles type Y-X-Y + {1, 2, 1}, ///< Extrinsic rotations with the Euler angles type Y-Z-Y + {2, 0, 2}, ///< Extrinsic rotations with the Euler angles type Z-X-Z + {2, 1, 2} ///< Extrinsic rotations with the Euler angles type Z-Y-Z + }; + Quat q1 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][0], angles(0)); + Quat q2 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][1], angles(1)); + Quat q3 = detail::createFromAxisRot(rotationAxis[eulerAnglesType][2], angles(2)); + if (detail::isIntAngleType(eulerAnglesType)) + { + return q1 * q2 * q3; + } + else // (!detail::isIntAngleType(eulerAnglesType)) + { + return q3 * q2 * q1; + } +} + +template +Vec Quat::toEulerAngles(QuatEnum::EulerAnglesType eulerAnglesType){ + CV_Assert(eulerAnglesType < QuatEnum::EulerAnglesType::EULER_ANGLES_MAX_VALUE); + Matx33d R = toRotMat3x3(); + enum { + C_ZERO, + C_PI, + C_PI_2, + N_CONSTANTS, + R_0_0 = N_CONSTANTS, R_0_1, R_0_2, + R_1_0, R_1_1, R_1_2, + R_2_0, R_2_1, R_2_2 + }; + static const T constants_[N_CONSTANTS] = { + 0, // C_ZERO + (T)CV_PI, // C_PI + (T)(CV_PI * 0.5) // C_PI_2, -C_PI_2 + }; + static const int rotationR_[24][12] = { + {+R_0_2, +R_1_0, +R_1_1, C_PI_2, +R_2_1, +R_1_1, -C_PI_2, -R_1_2, +R_2_2, +R_0_2, -R_0_1, +R_0_0}, // INT_XYZ + {+R_0_1, -R_1_2, +R_2_2, -C_PI_2, +R_2_0, +R_2_2, C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_2, +R_0_0}, // INT_XZY + {+R_1_2, -R_0_1, +R_0_0, -C_PI_2, +R_0_1, +R_0_0, C_PI_2, +R_0_2, +R_2_2, -R_1_2, +R_1_0, +R_1_1}, // INT_YXZ + {+R_1_0, +R_0_2, +R_2_2, C_PI_2, +R_0_2, +R_0_1, -C_PI_2, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1}, // INT_YZX + {+R_2_1, +R_1_0, +R_0_0, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, -R_0_1, +R_1_1, +R_2_1, -R_2_0, +R_2_2}, // INT_ZXY + {+R_2_0, -R_0_1, +R_1_1, -C_PI_2, +R_1_2, +R_1_1, C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_1, +R_2_2}, // INT_ZYX + {+R_0_0, +R_2_1, +R_2_2, C_ZERO, +R_1_2, +R_1_1, C_PI, +R_1_0, -R_2_0, +R_0_0, +R_0_1, +R_0_2}, // INT_XYX + {+R_0_0, +R_2_1, +R_2_2, C_ZERO, -R_2_1, +R_2_2, C_PI, +R_2_0, +R_1_0, +R_0_0, +R_0_2, -R_0_1}, // INT_XZX + {+R_1_1, +R_0_2, +R_0_0, C_ZERO, -R_2_0, +R_0_0, C_PI, +R_0_1, +R_2_1, +R_1_1, +R_1_0, -R_1_2}, // INT_YXY + {+R_1_1, +R_0_2, +R_0_0, C_ZERO, +R_0_2, -R_0_0, C_PI, +R_2_1, -R_0_1, +R_1_1, +R_1_2, +R_1_0}, // INT_YZY + {+R_2_2, +R_1_0, +R_1_1, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_0_2, -R_1_2, +R_2_2, +R_2_0, +R_2_1}, // INT_ZXZ + {+R_2_2, +R_1_0, +R_0_0, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_2, +R_0_2, +R_2_2, +R_2_1, -R_2_0}, // INT_ZYZ + + {+R_2_0, -C_PI_2, -R_0_1, +R_1_1, C_PI_2, +R_1_2, +R_1_1, +R_2_1, +R_2_2, -R_2_0, +R_1_0, +R_0_0}, // EXT_XYZ + {+R_1_0, C_PI_2, +R_0_2, +R_2_2, -C_PI_2, +R_0_2, +R_0_1, -R_1_2, +R_1_1, +R_1_0, -R_2_0, +R_0_0}, // EXT_XZY + {+R_2_1, C_PI_2, +R_1_0, +R_0_0, -C_PI_2, +R_1_0, +R_0_0, -R_2_0, +R_2_2, +R_2_1, -R_0_1, +R_1_1}, // EXT_YXZ + {+R_0_2, -C_PI_2, -R_1_2, +R_2_2, C_PI_2, +R_2_0, +R_2_2, +R_0_2, +R_0_0, -R_0_1, +R_2_1, +R_1_1}, // EXT_YZX + {+R_1_2, -C_PI_2, -R_0_1, +R_0_0, C_PI_2, +R_0_1, +R_0_0, +R_1_0, +R_1_1, -R_1_2, +R_0_2, +R_2_2}, // EXT_ZXY + {+R_0_2, C_PI_2, +R_1_0, +R_1_1, -C_PI_2, +R_2_1, +R_1_1, -R_0_1, +R_0_0, +R_0_2, -R_1_2, +R_2_2}, // EXT_ZYX + {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_1_2, +R_1_1, +R_0_1, +R_0_2, +R_0_0, +R_1_0, -R_2_0}, // EXT_XYX + {+R_0_0, C_ZERO, +R_2_1, +R_2_2, C_PI, +R_2_1, +R_2_2, +R_0_2, -R_0_1, +R_0_0, +R_2_0, +R_1_0}, // EXT_XZX + {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, -R_2_0, +R_0_0, +R_1_0, -R_1_2, +R_1_1, +R_0_1, +R_2_1}, // EXT_YXY + {+R_1_1, C_ZERO, +R_0_2, +R_0_0, C_PI, +R_0_2, -R_0_0, +R_1_2, +R_1_0, +R_1_1, +R_2_1, -R_0_1}, // EXT_YZY + {+R_2_2, C_ZERO, +R_1_0, +R_1_1, C_PI, +R_1_0, +R_0_0, +R_2_0, +R_2_1, +R_2_2, +R_0_2, -R_1_2}, // EXT_ZXZ + {+R_2_2, C_ZERO, +R_1_0, +R_0_0, C_PI, +R_1_0, +R_0_0, +R_2_1, -R_2_0, +R_2_2, +R_1_2, +R_0_2}, // EXT_ZYZ + }; + T rotationR[12]; + for (int i = 0; i < 12; i++) + { + int id = rotationR_[eulerAnglesType][i]; + unsigned idx = std::abs(id); + T value = 0.0f; + if (idx < N_CONSTANTS) + { + value = constants_[idx]; + } + else + { + unsigned r_idx = idx - N_CONSTANTS; + CV_DbgAssert(r_idx < 9); + value = R.val[r_idx]; + } + bool isNegative = id < 0; + if (isNegative) + value = -value; + rotationR[i] = value; + } + Vec angles; + if (detail::isIntAngleType(eulerAnglesType)) + { + if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); + angles = {std::atan2(rotationR[1], rotationR[2]), rotationR[3], 0}; + return angles; + } + else if(abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the third angle to 0"); + angles = {std::atan2(rotationR[4], rotationR[5]), rotationR[6], 0}; + return angles; + } + } + else // (!detail::isIntAngleType(eulerAnglesType)) + { + if (abs(rotationR[0] - 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); + angles = {0, rotationR[1], std::atan2(rotationR[2], rotationR[3])}; + return angles; + } + else if (abs(rotationR[0] + 1) < CV_QUAT_CONVERT_THRESHOLD) + { + CV_LOG_WARNING(NULL,"Gimbal Lock occurs. Euler angles are non-unique, we set the first angle to 0"); + angles = {0, rotationR[4], std::atan2(rotationR[5], rotationR[6])}; + return angles; + } + } + + angles(0) = std::atan2(rotationR[7], rotationR[8]); + if (detail::isTaitBryan(eulerAnglesType)) + angles(1) = std::acos(rotationR[9]); + else + angles(1) = std::asin(rotationR[9]); + angles(2) = std::atan2(rotationR[10], rotationR[11]); + return angles; +} + +} // namepsace +//! @endcond + +#endif /*OPENCV_CORE_QUATERNION_INL_HPP*/ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp b/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp index 04951d42f2..18ffd1c7af 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/saturate.hpp @@ -1,180 +1,180 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2014, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_SATURATE_HPP -#define OPENCV_CORE_SATURATE_HPP - -#include "opencv2/core/cvdef.h" -#include -#include "opencv2/core/fast_math.hpp" - -namespace cv -{ - -//! @addtogroup core_utils -//! @{ - -/////////////// saturate_cast (used in image & signal processing) /////////////////// - -/** @brief Template function for accurate conversion from one primitive type to another. - - The function saturate_cast resembles the standard C++ cast operations, such as static_cast\() - and others. It perform an efficient and accurate conversion from one primitive type to another - (see the introduction chapter). saturate in the name means that when the input value v is out of the - range of the target type, the result is not formed just by taking low bits of the input, but instead - the value is clipped. For example: - @code - uchar a = saturate_cast(-100); // a = 0 (UCHAR_MIN) - short b = saturate_cast(33333.33333); // b = 32767 (SHRT_MAX) - @endcode - Such clipping is done when the target type is unsigned char , signed char , unsigned short or - signed short . For 32-bit integers, no clipping is done. - - When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), - the floating-point value is first rounded to the nearest integer and then clipped if needed (when - the target type is 8- or 16-bit). - - @param v Function parameter. - @sa add, subtract, multiply, divide, Mat::convertTo - */ -template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(schar v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(ushort v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(short v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(unsigned v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(int v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(float v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(double v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(int64 v) { return _Tp(v); } -/** @overload */ -template static inline _Tp saturate_cast(uint64 v) { return _Tp(v); } - -template<> inline uchar saturate_cast(schar v) { return (uchar)std::max((int)v, 0); } -template<> inline uchar saturate_cast(ushort v) { return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); } -template<> inline uchar saturate_cast(int v) { return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } -template<> inline uchar saturate_cast(short v) { return saturate_cast((int)v); } -template<> inline uchar saturate_cast(unsigned v) { return (uchar)std::min(v, (unsigned)UCHAR_MAX); } -template<> inline uchar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline uchar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline uchar saturate_cast(int64 v) { return (uchar)((uint64)v <= (uint64)UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } -template<> inline uchar saturate_cast(uint64 v) { return (uchar)std::min(v, (uint64)UCHAR_MAX); } - -template<> inline schar saturate_cast(uchar v) { return (schar)std::min((int)v, SCHAR_MAX); } -template<> inline schar saturate_cast(ushort v) { return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); } -template<> inline schar saturate_cast(int v) { return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } -template<> inline schar saturate_cast(short v) { return saturate_cast((int)v); } -template<> inline schar saturate_cast(unsigned v) { return (schar)std::min(v, (unsigned)SCHAR_MAX); } -template<> inline schar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline schar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline schar saturate_cast(int64 v) { return (schar)((uint64)((int64)v-SCHAR_MIN) <= (uint64)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } -template<> inline schar saturate_cast(uint64 v) { return (schar)std::min(v, (uint64)SCHAR_MAX); } - -template<> inline ushort saturate_cast(schar v) { return (ushort)std::max((int)v, 0); } -template<> inline ushort saturate_cast(short v) { return (ushort)std::max((int)v, 0); } -template<> inline ushort saturate_cast(int v) { return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } -template<> inline ushort saturate_cast(unsigned v) { return (ushort)std::min(v, (unsigned)USHRT_MAX); } -template<> inline ushort saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline ushort saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline ushort saturate_cast(int64 v) { return (ushort)((uint64)v <= (uint64)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } -template<> inline ushort saturate_cast(uint64 v) { return (ushort)std::min(v, (uint64)USHRT_MAX); } - -template<> inline short saturate_cast(ushort v) { return (short)std::min((int)v, SHRT_MAX); } -template<> inline short saturate_cast(int v) { return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } -template<> inline short saturate_cast(unsigned v) { return (short)std::min(v, (unsigned)SHRT_MAX); } -template<> inline short saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline short saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } -template<> inline short saturate_cast(int64 v) { return (short)((uint64)((int64)v - SHRT_MIN) <= (uint64)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } -template<> inline short saturate_cast(uint64 v) { return (short)std::min(v, (uint64)SHRT_MAX); } - -template<> inline int saturate_cast(unsigned v) { return (int)std::min(v, (unsigned)INT_MAX); } -template<> inline int saturate_cast(int64 v) { return (int)((uint64)(v - INT_MIN) <= (uint64)UINT_MAX ? v : v > 0 ? INT_MAX : INT_MIN); } -template<> inline int saturate_cast(uint64 v) { return (int)std::min(v, (uint64)INT_MAX); } -template<> inline int saturate_cast(float v) { return cvRound(v); } -template<> inline int saturate_cast(double v) { return cvRound(v); } - -template<> inline unsigned saturate_cast(schar v) { return (unsigned)std::max(v, (schar)0); } -template<> inline unsigned saturate_cast(short v) { return (unsigned)std::max(v, (short)0); } -template<> inline unsigned saturate_cast(int v) { return (unsigned)std::max(v, (int)0); } -template<> inline unsigned saturate_cast(int64 v) { return (unsigned)((uint64)v <= (uint64)UINT_MAX ? v : v > 0 ? UINT_MAX : 0); } -template<> inline unsigned saturate_cast(uint64 v) { return (unsigned)std::min(v, (uint64)UINT_MAX); } -// we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. -template<> inline unsigned saturate_cast(float v) { return static_cast(cvRound(v)); } -template<> inline unsigned saturate_cast(double v) { return static_cast(cvRound(v)); } - -template<> inline uint64 saturate_cast(schar v) { return (uint64)std::max(v, (schar)0); } -template<> inline uint64 saturate_cast(short v) { return (uint64)std::max(v, (short)0); } -template<> inline uint64 saturate_cast(int v) { return (uint64)std::max(v, (int)0); } -template<> inline uint64 saturate_cast(int64 v) { return (uint64)std::max(v, (int64)0); } - -template<> inline int64 saturate_cast(uint64 v) { return (int64)std::min(v, (uint64)LLONG_MAX); } - -/** @overload */ -template static inline _Tp saturate_cast(hfloat v) { return saturate_cast<_Tp>((float)v); } - -// in theory, we could use a LUT for 8u/8s->16f conversion, -// but with hardware support for FP32->FP16 conversion the current approach is preferable -template<> inline hfloat saturate_cast(uchar v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(schar v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(ushort v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(short v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(unsigned v){ return hfloat((float)v); } -template<> inline hfloat saturate_cast(int v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(uint64 v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(int64 v) { return hfloat((float)v); } -template<> inline hfloat saturate_cast(float v) { return hfloat(v); } -template<> inline hfloat saturate_cast(double v) { return hfloat((float)v); } - -//! @} - -} // cv - -#endif // OPENCV_CORE_SATURATE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2014, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_SATURATE_HPP +#define OPENCV_CORE_SATURATE_HPP + +#include "opencv2/core/cvdef.h" +#include +#include "opencv2/core/fast_math.hpp" + +namespace cv +{ + +//! @addtogroup core_utils +//! @{ + +/////////////// saturate_cast (used in image & signal processing) /////////////////// + +/** @brief Template function for accurate conversion from one primitive type to another. + + The function saturate_cast resembles the standard C++ cast operations, such as static_cast\() + and others. It perform an efficient and accurate conversion from one primitive type to another + (see the introduction chapter). saturate in the name means that when the input value v is out of the + range of the target type, the result is not formed just by taking low bits of the input, but instead + the value is clipped. For example: + @code + uchar a = saturate_cast(-100); // a = 0 (UCHAR_MIN) + short b = saturate_cast(33333.33333); // b = 32767 (SHRT_MAX) + @endcode + Such clipping is done when the target type is unsigned char , signed char , unsigned short or + signed short . For 32-bit integers, no clipping is done. + + When the parameter is a floating-point value and the target type is an integer (8-, 16- or 32-bit), + the floating-point value is first rounded to the nearest integer and then clipped if needed (when + the target type is 8- or 16-bit). + + @param v Function parameter. + @sa add, subtract, multiply, divide, Mat::convertTo + */ +template static inline _Tp saturate_cast(uchar v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(schar v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(ushort v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(short v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(unsigned v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(int v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(float v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(double v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(int64 v) { return _Tp(v); } +/** @overload */ +template static inline _Tp saturate_cast(uint64 v) { return _Tp(v); } + +template<> inline uchar saturate_cast(schar v) { return (uchar)std::max((int)v, 0); } +template<> inline uchar saturate_cast(ushort v) { return (uchar)std::min((unsigned)v, (unsigned)UCHAR_MAX); } +template<> inline uchar saturate_cast(int v) { return (uchar)((unsigned)v <= UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } +template<> inline uchar saturate_cast(short v) { return saturate_cast((int)v); } +template<> inline uchar saturate_cast(unsigned v) { return (uchar)std::min(v, (unsigned)UCHAR_MAX); } +template<> inline uchar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline uchar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline uchar saturate_cast(int64 v) { return (uchar)((uint64)v <= (uint64)UCHAR_MAX ? v : v > 0 ? UCHAR_MAX : 0); } +template<> inline uchar saturate_cast(uint64 v) { return (uchar)std::min(v, (uint64)UCHAR_MAX); } + +template<> inline schar saturate_cast(uchar v) { return (schar)std::min((int)v, SCHAR_MAX); } +template<> inline schar saturate_cast(ushort v) { return (schar)std::min((unsigned)v, (unsigned)SCHAR_MAX); } +template<> inline schar saturate_cast(int v) { return (schar)((unsigned)(v-SCHAR_MIN) <= (unsigned)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } +template<> inline schar saturate_cast(short v) { return saturate_cast((int)v); } +template<> inline schar saturate_cast(unsigned v) { return (schar)std::min(v, (unsigned)SCHAR_MAX); } +template<> inline schar saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline schar saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline schar saturate_cast(int64 v) { return (schar)((uint64)((int64)v-SCHAR_MIN) <= (uint64)UCHAR_MAX ? v : v > 0 ? SCHAR_MAX : SCHAR_MIN); } +template<> inline schar saturate_cast(uint64 v) { return (schar)std::min(v, (uint64)SCHAR_MAX); } + +template<> inline ushort saturate_cast(schar v) { return (ushort)std::max((int)v, 0); } +template<> inline ushort saturate_cast(short v) { return (ushort)std::max((int)v, 0); } +template<> inline ushort saturate_cast(int v) { return (ushort)((unsigned)v <= (unsigned)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } +template<> inline ushort saturate_cast(unsigned v) { return (ushort)std::min(v, (unsigned)USHRT_MAX); } +template<> inline ushort saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline ushort saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline ushort saturate_cast(int64 v) { return (ushort)((uint64)v <= (uint64)USHRT_MAX ? v : v > 0 ? USHRT_MAX : 0); } +template<> inline ushort saturate_cast(uint64 v) { return (ushort)std::min(v, (uint64)USHRT_MAX); } + +template<> inline short saturate_cast(ushort v) { return (short)std::min((int)v, SHRT_MAX); } +template<> inline short saturate_cast(int v) { return (short)((unsigned)(v - SHRT_MIN) <= (unsigned)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } +template<> inline short saturate_cast(unsigned v) { return (short)std::min(v, (unsigned)SHRT_MAX); } +template<> inline short saturate_cast(float v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline short saturate_cast(double v) { int iv = cvRound(v); return saturate_cast(iv); } +template<> inline short saturate_cast(int64 v) { return (short)((uint64)((int64)v - SHRT_MIN) <= (uint64)USHRT_MAX ? v : v > 0 ? SHRT_MAX : SHRT_MIN); } +template<> inline short saturate_cast(uint64 v) { return (short)std::min(v, (uint64)SHRT_MAX); } + +template<> inline int saturate_cast(unsigned v) { return (int)std::min(v, (unsigned)INT_MAX); } +template<> inline int saturate_cast(int64 v) { return (int)((uint64)(v - INT_MIN) <= (uint64)UINT_MAX ? v : v > 0 ? INT_MAX : INT_MIN); } +template<> inline int saturate_cast(uint64 v) { return (int)std::min(v, (uint64)INT_MAX); } +template<> inline int saturate_cast(float v) { return cvRound(v); } +template<> inline int saturate_cast(double v) { return cvRound(v); } + +template<> inline unsigned saturate_cast(schar v) { return (unsigned)std::max(v, (schar)0); } +template<> inline unsigned saturate_cast(short v) { return (unsigned)std::max(v, (short)0); } +template<> inline unsigned saturate_cast(int v) { return (unsigned)std::max(v, (int)0); } +template<> inline unsigned saturate_cast(int64 v) { return (unsigned)((uint64)v <= (uint64)UINT_MAX ? v : v > 0 ? UINT_MAX : 0); } +template<> inline unsigned saturate_cast(uint64 v) { return (unsigned)std::min(v, (uint64)UINT_MAX); } +// we intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. +template<> inline unsigned saturate_cast(float v) { return static_cast(cvRound(v)); } +template<> inline unsigned saturate_cast(double v) { return static_cast(cvRound(v)); } + +template<> inline uint64 saturate_cast(schar v) { return (uint64)std::max(v, (schar)0); } +template<> inline uint64 saturate_cast(short v) { return (uint64)std::max(v, (short)0); } +template<> inline uint64 saturate_cast(int v) { return (uint64)std::max(v, (int)0); } +template<> inline uint64 saturate_cast(int64 v) { return (uint64)std::max(v, (int64)0); } + +template<> inline int64 saturate_cast(uint64 v) { return (int64)std::min(v, (uint64)LLONG_MAX); } + +/** @overload */ +template static inline _Tp saturate_cast(hfloat v) { return saturate_cast<_Tp>((float)v); } + +// in theory, we could use a LUT for 8u/8s->16f conversion, +// but with hardware support for FP32->FP16 conversion the current approach is preferable +template<> inline hfloat saturate_cast(uchar v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(schar v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(ushort v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(short v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(unsigned v){ return hfloat((float)v); } +template<> inline hfloat saturate_cast(int v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(uint64 v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(int64 v) { return hfloat((float)v); } +template<> inline hfloat saturate_cast(float v) { return hfloat(v); } +template<> inline hfloat saturate_cast(double v) { return hfloat((float)v); } + +//! @} + +} // cv + +#endif // OPENCV_CORE_SATURATE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp b/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp index 93453d5eea..2658d92c89 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/simd_intrinsics.hpp @@ -1,87 +1,87 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_SIMD_INTRINSICS_HPP -#define OPENCV_CORE_SIMD_INTRINSICS_HPP - -/** -Helper header to support SIMD intrinsics (universal intrinsics) in user code. -Intrinsics documentation: https://docs.opencv.org/4.x/df/d91/group__core__hal__intrin.html - - -Checks of target CPU instruction set based on compiler definitions don't work well enough. -More reliable solutions require utilization of configuration systems (like CMake). - -So, probably you need to specify your own configuration. - -You can do that via CMake in this way: - add_definitions(/DOPENCV_SIMD_CONFIG_HEADER=opencv_simd_config_custom.hpp) -or - add_definitions(/DOPENCV_SIMD_CONFIG_INCLUDE_DIR=1) - -Additionally you may need to add include directory to your files: - include_directories("${CMAKE_CURRENT_LIST_DIR}/opencv_config_${MYTARGET}") - -These files can be pre-generated for target configurations of your application -or generated by CMake on the fly (use CMAKE_BINARY_DIR for that). - -Notes: -- H/W capability checks are still responsibility of your application -- runtime dispatching is not covered by this helper header -*/ - -#ifdef __OPENCV_BUILD -#error "Use core/hal/intrin.hpp during OpenCV build" -#endif - -#ifdef OPENCV_HAL_INTRIN_HPP -#error "core/simd_intrinsics.hpp must be included before core/hal/intrin.hpp" -#endif - -#include "opencv2/core/cvdef.h" - -#ifdef OPENCV_SIMD_CONFIG_HEADER -#include CVAUX_STR(OPENCV_SIMD_CONFIG_HEADER) -#elif defined(OPENCV_SIMD_CONFIG_INCLUDE_DIR) -#include "opencv_simd_config.hpp" // corresponding directory should be added via -I compiler parameter -#else // custom config headers - -#if (!defined(CV_AVX_512F) || !CV_AVX_512F) && (defined(__AVX512__) || defined(__AVX512F__)) -# include -# undef CV_AVX_512F -# define CV_AVX_512F 1 -# ifndef OPENCV_SIMD_DONT_ASSUME_SKX // Skylake-X with AVX-512F/CD/BW/DQ/VL -# undef CV_AVX512_SKX -# define CV_AVX512_SKX 1 -# undef CV_AVX_512CD -# define CV_AVX_512CD 1 -# undef CV_AVX_512BW -# define CV_AVX_512BW 1 -# undef CV_AVX_512DQ -# define CV_AVX_512DQ 1 -# undef CV_AVX_512VL -# define CV_AVX_512VL 1 -# endif -#endif // AVX512 - -// GCC/Clang: -mavx2 -// MSVC: /arch:AVX2 -#if defined __AVX2__ -# include -# undef CV_AVX2 -# define CV_AVX2 1 -# if defined __F16C__ -# undef CV_FP16 -# define CV_FP16 1 -# endif -#endif - -#endif - -// SSE / NEON / VSX is handled by cv_cpu_dispatch.h compatibility block -#include "cv_cpu_dispatch.h" - -#include "hal/intrin.hpp" - -#endif // OPENCV_CORE_SIMD_INTRINSICS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_SIMD_INTRINSICS_HPP +#define OPENCV_CORE_SIMD_INTRINSICS_HPP + +/** +Helper header to support SIMD intrinsics (universal intrinsics) in user code. +Intrinsics documentation: https://docs.opencv.org/4.x/df/d91/group__core__hal__intrin.html + + +Checks of target CPU instruction set based on compiler definitions don't work well enough. +More reliable solutions require utilization of configuration systems (like CMake). + +So, probably you need to specify your own configuration. + +You can do that via CMake in this way: + add_definitions(/DOPENCV_SIMD_CONFIG_HEADER=opencv_simd_config_custom.hpp) +or + add_definitions(/DOPENCV_SIMD_CONFIG_INCLUDE_DIR=1) + +Additionally you may need to add include directory to your files: + include_directories("${CMAKE_CURRENT_LIST_DIR}/opencv_config_${MYTARGET}") + +These files can be pre-generated for target configurations of your application +or generated by CMake on the fly (use CMAKE_BINARY_DIR for that). + +Notes: +- H/W capability checks are still responsibility of your application +- runtime dispatching is not covered by this helper header +*/ + +#ifdef __OPENCV_BUILD +#error "Use core/hal/intrin.hpp during OpenCV build" +#endif + +#ifdef OPENCV_HAL_INTRIN_HPP +#error "core/simd_intrinsics.hpp must be included before core/hal/intrin.hpp" +#endif + +#include "opencv2/core/cvdef.h" + +#ifdef OPENCV_SIMD_CONFIG_HEADER +#include CVAUX_STR(OPENCV_SIMD_CONFIG_HEADER) +#elif defined(OPENCV_SIMD_CONFIG_INCLUDE_DIR) +#include "opencv_simd_config.hpp" // corresponding directory should be added via -I compiler parameter +#else // custom config headers + +#if (!defined(CV_AVX_512F) || !CV_AVX_512F) && (defined(__AVX512__) || defined(__AVX512F__)) +# include +# undef CV_AVX_512F +# define CV_AVX_512F 1 +# ifndef OPENCV_SIMD_DONT_ASSUME_SKX // Skylake-X with AVX-512F/CD/BW/DQ/VL +# undef CV_AVX512_SKX +# define CV_AVX512_SKX 1 +# undef CV_AVX_512CD +# define CV_AVX_512CD 1 +# undef CV_AVX_512BW +# define CV_AVX_512BW 1 +# undef CV_AVX_512DQ +# define CV_AVX_512DQ 1 +# undef CV_AVX_512VL +# define CV_AVX_512VL 1 +# endif +#endif // AVX512 + +// GCC/Clang: -mavx2 +// MSVC: /arch:AVX2 +#if defined __AVX2__ +# include +# undef CV_AVX2 +# define CV_AVX2 1 +# if defined __F16C__ +# undef CV_FP16 +# define CV_FP16 1 +# endif +#endif + +#endif + +// SSE / NEON / VSX is handled by cv_cpu_dispatch.h compatibility block +#include "cv_cpu_dispatch.h" + +#include "hal/intrin.hpp" + +#endif // OPENCV_CORE_SIMD_INTRINSICS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp b/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp index 17814896ab..485e15c473 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/softfloat.hpp @@ -1,514 +1,514 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -// This file is based on files from package issued with the following license: - -/*============================================================================ - -This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic -Package, Release 3c, by John R. Hauser. - -Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the -University of California. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions, and the following disclaimer. - - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions, and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - 3. Neither the name of the University nor the names of its contributors may - be used to endorse or promote products derived from this software without - specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE -DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -=============================================================================*/ - -#pragma once -#ifndef softfloat_h -#define softfloat_h 1 - -#include "cvdef.h" - -namespace cv -{ - -/** @addtogroup core_utils_softfloat - - [SoftFloat](http://www.jhauser.us/arithmetic/SoftFloat.html) is a software implementation - of floating-point calculations according to IEEE 754 standard. - All calculations are done in integers, that's why they are machine-independent and bit-exact. - This library can be useful in accuracy-critical parts like look-up tables generation, tests, etc. - OpenCV contains a subset of SoftFloat partially rewritten to C++. - - ### Types - - There are two basic types: @ref softfloat and @ref softdouble. - These types are binary compatible with float and double types respectively - and support conversions to/from them. - Other types from original SoftFloat library like fp16 or fp128 were thrown away - as well as quiet/signaling NaN support, on-the-fly rounding mode switch - and exception flags (though exceptions can be implemented in the future). - - ### Operations - - Both types support the following: - - Construction from signed and unsigned 32-bit and 64 integers, - float/double or raw binary representation - - Conversions between each other, to float or double and to int - using @ref cvRound, @ref cvTrunc, @ref cvFloor, @ref cvCeil or a bunch of - saturate_cast functions - - Add, subtract, multiply, divide, remainder, square root, FMA with absolute precision - - Comparison operations - - Explicit sign, exponent and significand manipulation through get/set methods, - number state indicators (isInf, isNan, isSubnormal) - - Type-specific constants like eps, minimum/maximum value, best pi approximation, etc. - - min(), max(), abs(), exp(), log() and pow() functions - -*/ -//! @{ - -struct softfloat; -struct softdouble; - -struct CV_EXPORTS softfloat -{ -public: - /** @brief Default constructor */ - softfloat() { v = 0; } - /** @brief Copy constructor */ - softfloat( const softfloat& c) { v = c.v; } - /** @brief Assign constructor */ - softfloat& operator=( const softfloat& c ) - { - if(&c != this) v = c.v; - return *this; - } - /** @brief Construct from raw - - Builds new value from raw binary representation - */ - static const softfloat fromRaw( const uint32_t a ) { softfloat x; x.v = a; return x; } - - /** @brief Construct from integer */ - explicit softfloat( const uint32_t ); - explicit softfloat( const uint64_t ); - explicit softfloat( const int32_t ); - explicit softfloat( const int64_t ); - -#ifdef CV_INT32_T_IS_LONG_INT - // for platforms with int32_t = long int - explicit softfloat( const int a ) { *this = softfloat(static_cast(a)); } -#endif - - /** @brief Construct from float */ - explicit softfloat( const float a ) { Cv32suf s; s.f = a; v = s.u; } - - /** @brief Type casts */ - operator softdouble() const; - operator float() const { Cv32suf s; s.u = v; return s.f; } - - /** @brief Basic arithmetics */ - softfloat operator + (const softfloat&) const; - softfloat operator - (const softfloat&) const; - softfloat operator * (const softfloat&) const; - softfloat operator / (const softfloat&) const; - softfloat operator - () const { softfloat x; x.v = v ^ (1U << 31); return x; } - - /** @brief Remainder operator - - A quote from original SoftFloat manual: - - > The IEEE Standard remainder operation computes the value - > a - n * b, where n is the integer closest to a / b. - > If a / b is exactly halfway between two integers, n is the even integer - > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. - > Depending on the relative magnitudes of the operands, the remainder functions - > can take considerably longer to execute than the other SoftFloat functions. - > This is an inherent characteristic of the remainder operation itself and is not a flaw - > in the SoftFloat implementation. - */ - softfloat operator % (const softfloat&) const; - - softfloat& operator += (const softfloat& a) { *this = *this + a; return *this; } - softfloat& operator -= (const softfloat& a) { *this = *this - a; return *this; } - softfloat& operator *= (const softfloat& a) { *this = *this * a; return *this; } - softfloat& operator /= (const softfloat& a) { *this = *this / a; return *this; } - softfloat& operator %= (const softfloat& a) { *this = *this % a; return *this; } - - /** @brief Comparison operations - - - Any operation with NaN produces false - + The only exception is when x is NaN: x != y for any y. - - Positive and negative zeros are equal - */ - bool operator == ( const softfloat& ) const; - bool operator != ( const softfloat& ) const; - bool operator > ( const softfloat& ) const; - bool operator >= ( const softfloat& ) const; - bool operator < ( const softfloat& ) const; - bool operator <= ( const softfloat& ) const; - - /** @brief NaN state indicator */ - inline bool isNaN() const { return (v & 0x7fffffff) > 0x7f800000; } - /** @brief Inf state indicator */ - inline bool isInf() const { return (v & 0x7fffffff) == 0x7f800000; } - /** @brief Subnormal number indicator */ - inline bool isSubnormal() const { return ((v >> 23) & 0xFF) == 0; } - - /** @brief Get sign bit */ - inline bool getSign() const { return (v >> 31) != 0; } - /** @brief Construct a copy with new sign bit */ - inline softfloat setSign(bool sign) const { softfloat x; x.v = (v & ((1U << 31) - 1)) | ((uint32_t)sign << 31); return x; } - /** @brief Get 0-based exponent */ - inline int getExp() const { return ((v >> 23) & 0xFF) - 127; } - /** @brief Construct a copy with new 0-based exponent */ - inline softfloat setExp(int e) const { softfloat x; x.v = (v & 0x807fffff) | (((e + 127) & 0xFF) << 23 ); return x; } - - /** @brief Get a fraction part - - Returns a number 1 <= x < 2 with the same significand - */ - inline softfloat getFrac() const - { - uint_fast32_t vv = (v & 0x007fffff) | (127 << 23); - return softfloat::fromRaw(vv); - } - /** @brief Construct a copy with provided significand - - Constructs a copy of a number with significand taken from parameter - */ - inline softfloat setFrac(const softfloat& s) const - { - softfloat x; - x.v = (v & 0xff800000) | (s.v & 0x007fffff); - return x; - } - - /** @brief Zero constant */ - static softfloat zero() { return softfloat::fromRaw( 0 ); } - /** @brief Positive infinity constant */ - static softfloat inf() { return softfloat::fromRaw( 0xFF << 23 ); } - /** @brief Default NaN constant */ - static softfloat nan() { return softfloat::fromRaw( 0x7fffffff ); } - /** @brief One constant */ - static softfloat one() { return softfloat::fromRaw( 127 << 23 ); } - /** @brief Smallest normalized value */ - static softfloat min() { return softfloat::fromRaw( 0x01 << 23 ); } - /** @brief Difference between 1 and next representable value */ - static softfloat eps() { return softfloat::fromRaw( (127 - 23) << 23 ); } - /** @brief Biggest finite value */ - static softfloat max() { return softfloat::fromRaw( (0xFF << 23) - 1 ); } - /** @brief Correct pi approximation */ - static softfloat pi() { return softfloat::fromRaw( 0x40490fdb ); } - - uint32_t v; -}; - -/*---------------------------------------------------------------------------- -*----------------------------------------------------------------------------*/ - -struct CV_EXPORTS softdouble -{ -public: - /** @brief Default constructor */ - softdouble() : v(0) { } - /** @brief Copy constructor */ - softdouble( const softdouble& c) { v = c.v; } - /** @brief Assign constructor */ - softdouble& operator=( const softdouble& c ) - { - if(&c != this) v = c.v; - return *this; - } - /** @brief Construct from raw - - Builds new value from raw binary representation - */ - static softdouble fromRaw( const uint64_t a ) { softdouble x; x.v = a; return x; } - - /** @brief Construct from integer */ - explicit softdouble( const uint32_t ); - explicit softdouble( const uint64_t ); - explicit softdouble( const int32_t ); - explicit softdouble( const int64_t ); - -#ifdef CV_INT32_T_IS_LONG_INT - // for platforms with int32_t = long int - explicit softdouble( const int a ) { *this = softdouble(static_cast(a)); } -#endif - - /** @brief Construct from double */ - explicit softdouble( const double a ) { Cv64suf s; s.f = a; v = s.u; } - - /** @brief Type casts */ - operator softfloat() const; - operator double() const { Cv64suf s; s.u = v; return s.f; } - - /** @brief Basic arithmetics */ - softdouble operator + (const softdouble&) const; - softdouble operator - (const softdouble&) const; - softdouble operator * (const softdouble&) const; - softdouble operator / (const softdouble&) const; - softdouble operator - () const { softdouble x; x.v = v ^ (1ULL << 63); return x; } - - /** @brief Remainder operator - - A quote from original SoftFloat manual: - - > The IEEE Standard remainder operation computes the value - > a - n * b, where n is the integer closest to a / b. - > If a / b is exactly halfway between two integers, n is the even integer - > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. - > Depending on the relative magnitudes of the operands, the remainder functions - > can take considerably longer to execute than the other SoftFloat functions. - > This is an inherent characteristic of the remainder operation itself and is not a flaw - > in the SoftFloat implementation. - */ - softdouble operator % (const softdouble&) const; - - softdouble& operator += (const softdouble& a) { *this = *this + a; return *this; } - softdouble& operator -= (const softdouble& a) { *this = *this - a; return *this; } - softdouble& operator *= (const softdouble& a) { *this = *this * a; return *this; } - softdouble& operator /= (const softdouble& a) { *this = *this / a; return *this; } - softdouble& operator %= (const softdouble& a) { *this = *this % a; return *this; } - - /** @brief Comparison operations - - - Any operation with NaN produces false - + The only exception is when x is NaN: x != y for any y. - - Positive and negative zeros are equal - */ - bool operator == ( const softdouble& ) const; - bool operator != ( const softdouble& ) const; - bool operator > ( const softdouble& ) const; - bool operator >= ( const softdouble& ) const; - bool operator < ( const softdouble& ) const; - bool operator <= ( const softdouble& ) const; - - /** @brief NaN state indicator */ - inline bool isNaN() const { return (v & 0x7fffffffffffffff) > 0x7ff0000000000000; } - /** @brief Inf state indicator */ - inline bool isInf() const { return (v & 0x7fffffffffffffff) == 0x7ff0000000000000; } - /** @brief Subnormal number indicator */ - inline bool isSubnormal() const { return ((v >> 52) & 0x7FF) == 0; } - - /** @brief Get sign bit */ - inline bool getSign() const { return (v >> 63) != 0; } - /** @brief Construct a copy with new sign bit */ - softdouble setSign(bool sign) const { softdouble x; x.v = (v & ((1ULL << 63) - 1)) | ((uint_fast64_t)(sign) << 63); return x; } - /** @brief Get 0-based exponent */ - inline int getExp() const { return ((v >> 52) & 0x7FF) - 1023; } - /** @brief Construct a copy with new 0-based exponent */ - inline softdouble setExp(int e) const - { - softdouble x; - x.v = (v & 0x800FFFFFFFFFFFFF) | ((uint_fast64_t)((e + 1023) & 0x7FF) << 52); - return x; - } - - /** @brief Get a fraction part - - Returns a number 1 <= x < 2 with the same significand - */ - inline softdouble getFrac() const - { - uint_fast64_t vv = (v & 0x000FFFFFFFFFFFFF) | ((uint_fast64_t)(1023) << 52); - return softdouble::fromRaw(vv); - } - /** @brief Construct a copy with provided significand - - Constructs a copy of a number with significand taken from parameter - */ - inline softdouble setFrac(const softdouble& s) const - { - softdouble x; - x.v = (v & 0xFFF0000000000000) | (s.v & 0x000FFFFFFFFFFFFF); - return x; - } - - /** @brief Zero constant */ - static softdouble zero() { return softdouble::fromRaw( 0 ); } - /** @brief Positive infinity constant */ - static softdouble inf() { return softdouble::fromRaw( (uint_fast64_t)(0x7FF) << 52 ); } - /** @brief Default NaN constant */ - static softdouble nan() { return softdouble::fromRaw( CV_BIG_INT(0x7FFFFFFFFFFFFFFF) ); } - /** @brief One constant */ - static softdouble one() { return softdouble::fromRaw( (uint_fast64_t)( 1023) << 52 ); } - /** @brief Smallest normalized value */ - static softdouble min() { return softdouble::fromRaw( (uint_fast64_t)( 0x01) << 52 ); } - /** @brief Difference between 1 and next representable value */ - static softdouble eps() { return softdouble::fromRaw( (uint_fast64_t)( 1023 - 52 ) << 52 ); } - /** @brief Biggest finite value */ - static softdouble max() { return softdouble::fromRaw( ((uint_fast64_t)(0x7FF) << 52) - 1 ); } - /** @brief Correct pi approximation */ - static softdouble pi() { return softdouble::fromRaw( CV_BIG_INT(0x400921FB54442D18) ); } - - uint64_t v; -}; - -/*---------------------------------------------------------------------------- -*----------------------------------------------------------------------------*/ - -/** @brief Fused Multiplication and Addition - -Computes (a*b)+c with single rounding -*/ -CV_EXPORTS softfloat mulAdd( const softfloat& a, const softfloat& b, const softfloat & c); -CV_EXPORTS softdouble mulAdd( const softdouble& a, const softdouble& b, const softdouble& c); - -/** @brief Square root */ -CV_EXPORTS softfloat sqrt( const softfloat& a ); -CV_EXPORTS softdouble sqrt( const softdouble& a ); -} - -/*---------------------------------------------------------------------------- -| Ported from OpenCV and added for usability -*----------------------------------------------------------------------------*/ - -/** @brief Truncates number to integer with minimum magnitude */ -CV_EXPORTS int cvTrunc(const cv::softfloat& a); -CV_EXPORTS int cvTrunc(const cv::softdouble& a); - -/** @brief Rounds a number to nearest even integer */ -CV_EXPORTS int cvRound(const cv::softfloat& a); -CV_EXPORTS int cvRound(const cv::softdouble& a); - -/** @brief Rounds a number to nearest even long long integer */ -CV_EXPORTS int64_t cvRound64(const cv::softdouble& a); - -/** @brief Rounds a number down to integer */ -CV_EXPORTS int cvFloor(const cv::softfloat& a); -CV_EXPORTS int cvFloor(const cv::softdouble& a); - -/** @brief Rounds number up to integer */ -CV_EXPORTS int cvCeil(const cv::softfloat& a); -CV_EXPORTS int cvCeil(const cv::softdouble& a); - -namespace cv -{ -/** @brief Saturate casts */ -template static inline _Tp saturate_cast(softfloat a) { return _Tp(a); } -template static inline _Tp saturate_cast(softdouble a) { return _Tp(a); } - -template<> inline uchar saturate_cast(softfloat a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } -template<> inline uchar saturate_cast(softdouble a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } - -template<> inline schar saturate_cast(softfloat a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } -template<> inline schar saturate_cast(softdouble a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } - -template<> inline ushort saturate_cast(softfloat a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } -template<> inline ushort saturate_cast(softdouble a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } - -template<> inline short saturate_cast(softfloat a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } -template<> inline short saturate_cast(softdouble a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } - -template<> inline int saturate_cast(softfloat a) { return cvRound(a); } -template<> inline int saturate_cast(softdouble a) { return cvRound(a); } - -template<> inline int64_t saturate_cast(softfloat a) { return cvRound(a); } -template<> inline int64_t saturate_cast(softdouble a) { return cvRound64(a); } - -/** @brief Saturate cast to unsigned integer and unsigned long long integer -We intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. -*/ -template<> inline unsigned saturate_cast(softfloat a) { return cvRound(a); } -template<> inline unsigned saturate_cast(softdouble a) { return cvRound(a); } - -template<> inline uint64_t saturate_cast(softfloat a) { return cvRound(a); } -template<> inline uint64_t saturate_cast(softdouble a) { return cvRound64(a); } - -/** @brief Min and Max functions */ -inline softfloat min(const softfloat& a, const softfloat& b) { return (a > b) ? b : a; } -inline softdouble min(const softdouble& a, const softdouble& b) { return (a > b) ? b : a; } - -inline softfloat max(const softfloat& a, const softfloat& b) { return (a > b) ? a : b; } -inline softdouble max(const softdouble& a, const softdouble& b) { return (a > b) ? a : b; } - -/** @brief Absolute value */ -inline softfloat abs( softfloat a) { softfloat x; x.v = a.v & ((1U << 31) - 1); return x; } -inline softdouble abs( softdouble a) { softdouble x; x.v = a.v & ((1ULL << 63) - 1); return x; } - -/** @brief Exponent - -Special cases: -- exp(NaN) is NaN -- exp(-Inf) == 0 -- exp(+Inf) == +Inf -*/ -CV_EXPORTS softfloat exp( const softfloat& a); -CV_EXPORTS softdouble exp( const softdouble& a); - -/** @brief Natural logarithm - -Special cases: -- log(NaN), log(x < 0) are NaN -- log(0) == -Inf -*/ -CV_EXPORTS softfloat log( const softfloat& a ); -CV_EXPORTS softdouble log( const softdouble& a ); - -/** @brief Raising to the power - -Special cases: -- x**NaN is NaN for any x -- ( |x| == 1 )**Inf is NaN -- ( |x| > 1 )**+Inf or ( |x| < 1 )**-Inf is +Inf -- ( |x| > 1 )**-Inf or ( |x| < 1 )**+Inf is 0 -- x ** 0 == 1 for any x -- x ** 1 == 1 for any x -- NaN ** y is NaN for any other y -- Inf**(y < 0) == 0 -- Inf ** y is +Inf for any other y -- (x < 0)**y is NaN for any other y if x can't be correctly rounded to integer -- 0 ** 0 == 1 -- 0 ** (y < 0) is +Inf -- 0 ** (y > 0) is 0 -*/ -CV_EXPORTS softfloat pow( const softfloat& a, const softfloat& b); -CV_EXPORTS softdouble pow( const softdouble& a, const softdouble& b); - -/** @brief Cube root - -Special cases: -- cbrt(NaN) is NaN -- cbrt(+/-Inf) is +/-Inf -*/ -CV_EXPORTS softfloat cbrt( const softfloat& a ); - -/** @brief Sine - -Special cases: -- sin(Inf) or sin(NaN) is NaN -- sin(x) == x when sin(x) is close to zero -*/ -CV_EXPORTS softdouble sin( const softdouble& a ); - -/** @brief Cosine - * -Special cases: -- cos(Inf) or cos(NaN) is NaN -- cos(x) == +/- 1 when cos(x) is close to +/- 1 -*/ -CV_EXPORTS softdouble cos( const softdouble& a ); - -//! @} core_utils_softfloat - -} // cv:: - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +// This file is based on files from package issued with the following license: + +/*============================================================================ + +This C header file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3c, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015, 2016, 2017 The Regents of the +University of California. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions, and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions, and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + 3. Neither the name of the University nor the names of its contributors may + be used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS", AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +=============================================================================*/ + +#pragma once +#ifndef softfloat_h +#define softfloat_h 1 + +#include "cvdef.h" + +namespace cv +{ + +/** @addtogroup core_utils_softfloat + + [SoftFloat](http://www.jhauser.us/arithmetic/SoftFloat.html) is a software implementation + of floating-point calculations according to IEEE 754 standard. + All calculations are done in integers, that's why they are machine-independent and bit-exact. + This library can be useful in accuracy-critical parts like look-up tables generation, tests, etc. + OpenCV contains a subset of SoftFloat partially rewritten to C++. + + ### Types + + There are two basic types: @ref softfloat and @ref softdouble. + These types are binary compatible with float and double types respectively + and support conversions to/from them. + Other types from original SoftFloat library like fp16 or fp128 were thrown away + as well as quiet/signaling NaN support, on-the-fly rounding mode switch + and exception flags (though exceptions can be implemented in the future). + + ### Operations + + Both types support the following: + - Construction from signed and unsigned 32-bit and 64 integers, + float/double or raw binary representation + - Conversions between each other, to float or double and to int + using @ref cvRound, @ref cvTrunc, @ref cvFloor, @ref cvCeil or a bunch of + saturate_cast functions + - Add, subtract, multiply, divide, remainder, square root, FMA with absolute precision + - Comparison operations + - Explicit sign, exponent and significand manipulation through get/set methods, + number state indicators (isInf, isNan, isSubnormal) + - Type-specific constants like eps, minimum/maximum value, best pi approximation, etc. + - min(), max(), abs(), exp(), log() and pow() functions + +*/ +//! @{ + +struct softfloat; +struct softdouble; + +struct CV_EXPORTS softfloat +{ +public: + /** @brief Default constructor */ + softfloat() { v = 0; } + /** @brief Copy constructor */ + softfloat( const softfloat& c) { v = c.v; } + /** @brief Assign constructor */ + softfloat& operator=( const softfloat& c ) + { + if(&c != this) v = c.v; + return *this; + } + /** @brief Construct from raw + + Builds new value from raw binary representation + */ + static const softfloat fromRaw( const uint32_t a ) { softfloat x; x.v = a; return x; } + + /** @brief Construct from integer */ + explicit softfloat( const uint32_t ); + explicit softfloat( const uint64_t ); + explicit softfloat( const int32_t ); + explicit softfloat( const int64_t ); + +#ifdef CV_INT32_T_IS_LONG_INT + // for platforms with int32_t = long int + explicit softfloat( const int a ) { *this = softfloat(static_cast(a)); } +#endif + + /** @brief Construct from float */ + explicit softfloat( const float a ) { Cv32suf s; s.f = a; v = s.u; } + + /** @brief Type casts */ + operator softdouble() const; + operator float() const { Cv32suf s; s.u = v; return s.f; } + + /** @brief Basic arithmetics */ + softfloat operator + (const softfloat&) const; + softfloat operator - (const softfloat&) const; + softfloat operator * (const softfloat&) const; + softfloat operator / (const softfloat&) const; + softfloat operator - () const { softfloat x; x.v = v ^ (1U << 31); return x; } + + /** @brief Remainder operator + + A quote from original SoftFloat manual: + + > The IEEE Standard remainder operation computes the value + > a - n * b, where n is the integer closest to a / b. + > If a / b is exactly halfway between two integers, n is the even integer + > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. + > Depending on the relative magnitudes of the operands, the remainder functions + > can take considerably longer to execute than the other SoftFloat functions. + > This is an inherent characteristic of the remainder operation itself and is not a flaw + > in the SoftFloat implementation. + */ + softfloat operator % (const softfloat&) const; + + softfloat& operator += (const softfloat& a) { *this = *this + a; return *this; } + softfloat& operator -= (const softfloat& a) { *this = *this - a; return *this; } + softfloat& operator *= (const softfloat& a) { *this = *this * a; return *this; } + softfloat& operator /= (const softfloat& a) { *this = *this / a; return *this; } + softfloat& operator %= (const softfloat& a) { *this = *this % a; return *this; } + + /** @brief Comparison operations + + - Any operation with NaN produces false + + The only exception is when x is NaN: x != y for any y. + - Positive and negative zeros are equal + */ + bool operator == ( const softfloat& ) const; + bool operator != ( const softfloat& ) const; + bool operator > ( const softfloat& ) const; + bool operator >= ( const softfloat& ) const; + bool operator < ( const softfloat& ) const; + bool operator <= ( const softfloat& ) const; + + /** @brief NaN state indicator */ + inline bool isNaN() const { return (v & 0x7fffffff) > 0x7f800000; } + /** @brief Inf state indicator */ + inline bool isInf() const { return (v & 0x7fffffff) == 0x7f800000; } + /** @brief Subnormal number indicator */ + inline bool isSubnormal() const { return ((v >> 23) & 0xFF) == 0; } + + /** @brief Get sign bit */ + inline bool getSign() const { return (v >> 31) != 0; } + /** @brief Construct a copy with new sign bit */ + inline softfloat setSign(bool sign) const { softfloat x; x.v = (v & ((1U << 31) - 1)) | ((uint32_t)sign << 31); return x; } + /** @brief Get 0-based exponent */ + inline int getExp() const { return ((v >> 23) & 0xFF) - 127; } + /** @brief Construct a copy with new 0-based exponent */ + inline softfloat setExp(int e) const { softfloat x; x.v = (v & 0x807fffff) | (((e + 127) & 0xFF) << 23 ); return x; } + + /** @brief Get a fraction part + + Returns a number 1 <= x < 2 with the same significand + */ + inline softfloat getFrac() const + { + uint_fast32_t vv = (v & 0x007fffff) | (127 << 23); + return softfloat::fromRaw(vv); + } + /** @brief Construct a copy with provided significand + + Constructs a copy of a number with significand taken from parameter + */ + inline softfloat setFrac(const softfloat& s) const + { + softfloat x; + x.v = (v & 0xff800000) | (s.v & 0x007fffff); + return x; + } + + /** @brief Zero constant */ + static softfloat zero() { return softfloat::fromRaw( 0 ); } + /** @brief Positive infinity constant */ + static softfloat inf() { return softfloat::fromRaw( 0xFF << 23 ); } + /** @brief Default NaN constant */ + static softfloat nan() { return softfloat::fromRaw( 0x7fffffff ); } + /** @brief One constant */ + static softfloat one() { return softfloat::fromRaw( 127 << 23 ); } + /** @brief Smallest normalized value */ + static softfloat min() { return softfloat::fromRaw( 0x01 << 23 ); } + /** @brief Difference between 1 and next representable value */ + static softfloat eps() { return softfloat::fromRaw( (127 - 23) << 23 ); } + /** @brief Biggest finite value */ + static softfloat max() { return softfloat::fromRaw( (0xFF << 23) - 1 ); } + /** @brief Correct pi approximation */ + static softfloat pi() { return softfloat::fromRaw( 0x40490fdb ); } + + uint32_t v; +}; + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ + +struct CV_EXPORTS softdouble +{ +public: + /** @brief Default constructor */ + softdouble() : v(0) { } + /** @brief Copy constructor */ + softdouble( const softdouble& c) { v = c.v; } + /** @brief Assign constructor */ + softdouble& operator=( const softdouble& c ) + { + if(&c != this) v = c.v; + return *this; + } + /** @brief Construct from raw + + Builds new value from raw binary representation + */ + static softdouble fromRaw( const uint64_t a ) { softdouble x; x.v = a; return x; } + + /** @brief Construct from integer */ + explicit softdouble( const uint32_t ); + explicit softdouble( const uint64_t ); + explicit softdouble( const int32_t ); + explicit softdouble( const int64_t ); + +#ifdef CV_INT32_T_IS_LONG_INT + // for platforms with int32_t = long int + explicit softdouble( const int a ) { *this = softdouble(static_cast(a)); } +#endif + + /** @brief Construct from double */ + explicit softdouble( const double a ) { Cv64suf s; s.f = a; v = s.u; } + + /** @brief Type casts */ + operator softfloat() const; + operator double() const { Cv64suf s; s.u = v; return s.f; } + + /** @brief Basic arithmetics */ + softdouble operator + (const softdouble&) const; + softdouble operator - (const softdouble&) const; + softdouble operator * (const softdouble&) const; + softdouble operator / (const softdouble&) const; + softdouble operator - () const { softdouble x; x.v = v ^ (1ULL << 63); return x; } + + /** @brief Remainder operator + + A quote from original SoftFloat manual: + + > The IEEE Standard remainder operation computes the value + > a - n * b, where n is the integer closest to a / b. + > If a / b is exactly halfway between two integers, n is the even integer + > closest to a / b. The IEEE Standard’s remainder operation is always exact and so requires no rounding. + > Depending on the relative magnitudes of the operands, the remainder functions + > can take considerably longer to execute than the other SoftFloat functions. + > This is an inherent characteristic of the remainder operation itself and is not a flaw + > in the SoftFloat implementation. + */ + softdouble operator % (const softdouble&) const; + + softdouble& operator += (const softdouble& a) { *this = *this + a; return *this; } + softdouble& operator -= (const softdouble& a) { *this = *this - a; return *this; } + softdouble& operator *= (const softdouble& a) { *this = *this * a; return *this; } + softdouble& operator /= (const softdouble& a) { *this = *this / a; return *this; } + softdouble& operator %= (const softdouble& a) { *this = *this % a; return *this; } + + /** @brief Comparison operations + + - Any operation with NaN produces false + + The only exception is when x is NaN: x != y for any y. + - Positive and negative zeros are equal + */ + bool operator == ( const softdouble& ) const; + bool operator != ( const softdouble& ) const; + bool operator > ( const softdouble& ) const; + bool operator >= ( const softdouble& ) const; + bool operator < ( const softdouble& ) const; + bool operator <= ( const softdouble& ) const; + + /** @brief NaN state indicator */ + inline bool isNaN() const { return (v & 0x7fffffffffffffff) > 0x7ff0000000000000; } + /** @brief Inf state indicator */ + inline bool isInf() const { return (v & 0x7fffffffffffffff) == 0x7ff0000000000000; } + /** @brief Subnormal number indicator */ + inline bool isSubnormal() const { return ((v >> 52) & 0x7FF) == 0; } + + /** @brief Get sign bit */ + inline bool getSign() const { return (v >> 63) != 0; } + /** @brief Construct a copy with new sign bit */ + softdouble setSign(bool sign) const { softdouble x; x.v = (v & ((1ULL << 63) - 1)) | ((uint_fast64_t)(sign) << 63); return x; } + /** @brief Get 0-based exponent */ + inline int getExp() const { return ((v >> 52) & 0x7FF) - 1023; } + /** @brief Construct a copy with new 0-based exponent */ + inline softdouble setExp(int e) const + { + softdouble x; + x.v = (v & 0x800FFFFFFFFFFFFF) | ((uint_fast64_t)((e + 1023) & 0x7FF) << 52); + return x; + } + + /** @brief Get a fraction part + + Returns a number 1 <= x < 2 with the same significand + */ + inline softdouble getFrac() const + { + uint_fast64_t vv = (v & 0x000FFFFFFFFFFFFF) | ((uint_fast64_t)(1023) << 52); + return softdouble::fromRaw(vv); + } + /** @brief Construct a copy with provided significand + + Constructs a copy of a number with significand taken from parameter + */ + inline softdouble setFrac(const softdouble& s) const + { + softdouble x; + x.v = (v & 0xFFF0000000000000) | (s.v & 0x000FFFFFFFFFFFFF); + return x; + } + + /** @brief Zero constant */ + static softdouble zero() { return softdouble::fromRaw( 0 ); } + /** @brief Positive infinity constant */ + static softdouble inf() { return softdouble::fromRaw( (uint_fast64_t)(0x7FF) << 52 ); } + /** @brief Default NaN constant */ + static softdouble nan() { return softdouble::fromRaw( CV_BIG_INT(0x7FFFFFFFFFFFFFFF) ); } + /** @brief One constant */ + static softdouble one() { return softdouble::fromRaw( (uint_fast64_t)( 1023) << 52 ); } + /** @brief Smallest normalized value */ + static softdouble min() { return softdouble::fromRaw( (uint_fast64_t)( 0x01) << 52 ); } + /** @brief Difference between 1 and next representable value */ + static softdouble eps() { return softdouble::fromRaw( (uint_fast64_t)( 1023 - 52 ) << 52 ); } + /** @brief Biggest finite value */ + static softdouble max() { return softdouble::fromRaw( ((uint_fast64_t)(0x7FF) << 52) - 1 ); } + /** @brief Correct pi approximation */ + static softdouble pi() { return softdouble::fromRaw( CV_BIG_INT(0x400921FB54442D18) ); } + + uint64_t v; +}; + +/*---------------------------------------------------------------------------- +*----------------------------------------------------------------------------*/ + +/** @brief Fused Multiplication and Addition + +Computes (a*b)+c with single rounding +*/ +CV_EXPORTS softfloat mulAdd( const softfloat& a, const softfloat& b, const softfloat & c); +CV_EXPORTS softdouble mulAdd( const softdouble& a, const softdouble& b, const softdouble& c); + +/** @brief Square root */ +CV_EXPORTS softfloat sqrt( const softfloat& a ); +CV_EXPORTS softdouble sqrt( const softdouble& a ); +} + +/*---------------------------------------------------------------------------- +| Ported from OpenCV and added for usability +*----------------------------------------------------------------------------*/ + +/** @brief Truncates number to integer with minimum magnitude */ +CV_EXPORTS int cvTrunc(const cv::softfloat& a); +CV_EXPORTS int cvTrunc(const cv::softdouble& a); + +/** @brief Rounds a number to nearest even integer */ +CV_EXPORTS int cvRound(const cv::softfloat& a); +CV_EXPORTS int cvRound(const cv::softdouble& a); + +/** @brief Rounds a number to nearest even long long integer */ +CV_EXPORTS int64_t cvRound64(const cv::softdouble& a); + +/** @brief Rounds a number down to integer */ +CV_EXPORTS int cvFloor(const cv::softfloat& a); +CV_EXPORTS int cvFloor(const cv::softdouble& a); + +/** @brief Rounds number up to integer */ +CV_EXPORTS int cvCeil(const cv::softfloat& a); +CV_EXPORTS int cvCeil(const cv::softdouble& a); + +namespace cv +{ +/** @brief Saturate casts */ +template static inline _Tp saturate_cast(softfloat a) { return _Tp(a); } +template static inline _Tp saturate_cast(softdouble a) { return _Tp(a); } + +template<> inline uchar saturate_cast(softfloat a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } +template<> inline uchar saturate_cast(softdouble a) { return (uchar)std::max(std::min(cvRound(a), (int)UCHAR_MAX), 0); } + +template<> inline schar saturate_cast(softfloat a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } +template<> inline schar saturate_cast(softdouble a) { return (schar)std::min(std::max(cvRound(a), (int)SCHAR_MIN), (int)SCHAR_MAX); } + +template<> inline ushort saturate_cast(softfloat a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } +template<> inline ushort saturate_cast(softdouble a) { return (ushort)std::max(std::min(cvRound(a), (int)USHRT_MAX), 0); } + +template<> inline short saturate_cast(softfloat a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } +template<> inline short saturate_cast(softdouble a) { return (short)std::min(std::max(cvRound(a), (int)SHRT_MIN), (int)SHRT_MAX); } + +template<> inline int saturate_cast(softfloat a) { return cvRound(a); } +template<> inline int saturate_cast(softdouble a) { return cvRound(a); } + +template<> inline int64_t saturate_cast(softfloat a) { return cvRound(a); } +template<> inline int64_t saturate_cast(softdouble a) { return cvRound64(a); } + +/** @brief Saturate cast to unsigned integer and unsigned long long integer +We intentionally do not clip negative numbers, to make -1 become 0xffffffff etc. +*/ +template<> inline unsigned saturate_cast(softfloat a) { return cvRound(a); } +template<> inline unsigned saturate_cast(softdouble a) { return cvRound(a); } + +template<> inline uint64_t saturate_cast(softfloat a) { return cvRound(a); } +template<> inline uint64_t saturate_cast(softdouble a) { return cvRound64(a); } + +/** @brief Min and Max functions */ +inline softfloat min(const softfloat& a, const softfloat& b) { return (a > b) ? b : a; } +inline softdouble min(const softdouble& a, const softdouble& b) { return (a > b) ? b : a; } + +inline softfloat max(const softfloat& a, const softfloat& b) { return (a > b) ? a : b; } +inline softdouble max(const softdouble& a, const softdouble& b) { return (a > b) ? a : b; } + +/** @brief Absolute value */ +inline softfloat abs( softfloat a) { softfloat x; x.v = a.v & ((1U << 31) - 1); return x; } +inline softdouble abs( softdouble a) { softdouble x; x.v = a.v & ((1ULL << 63) - 1); return x; } + +/** @brief Exponent + +Special cases: +- exp(NaN) is NaN +- exp(-Inf) == 0 +- exp(+Inf) == +Inf +*/ +CV_EXPORTS softfloat exp( const softfloat& a); +CV_EXPORTS softdouble exp( const softdouble& a); + +/** @brief Natural logarithm + +Special cases: +- log(NaN), log(x < 0) are NaN +- log(0) == -Inf +*/ +CV_EXPORTS softfloat log( const softfloat& a ); +CV_EXPORTS softdouble log( const softdouble& a ); + +/** @brief Raising to the power + +Special cases: +- x**NaN is NaN for any x +- ( |x| == 1 )**Inf is NaN +- ( |x| > 1 )**+Inf or ( |x| < 1 )**-Inf is +Inf +- ( |x| > 1 )**-Inf or ( |x| < 1 )**+Inf is 0 +- x ** 0 == 1 for any x +- x ** 1 == 1 for any x +- NaN ** y is NaN for any other y +- Inf**(y < 0) == 0 +- Inf ** y is +Inf for any other y +- (x < 0)**y is NaN for any other y if x can't be correctly rounded to integer +- 0 ** 0 == 1 +- 0 ** (y < 0) is +Inf +- 0 ** (y > 0) is 0 +*/ +CV_EXPORTS softfloat pow( const softfloat& a, const softfloat& b); +CV_EXPORTS softdouble pow( const softdouble& a, const softdouble& b); + +/** @brief Cube root + +Special cases: +- cbrt(NaN) is NaN +- cbrt(+/-Inf) is +/-Inf +*/ +CV_EXPORTS softfloat cbrt( const softfloat& a ); + +/** @brief Sine + +Special cases: +- sin(Inf) or sin(NaN) is NaN +- sin(x) == x when sin(x) is close to zero +*/ +CV_EXPORTS softdouble sin( const softdouble& a ); + +/** @brief Cosine + * +Special cases: +- cos(Inf) or cos(NaN) is NaN +- cos(x) == +/- 1 when cos(x) is close to +/- 1 +*/ +CV_EXPORTS softdouble cos( const softdouble& a ); + +//! @} core_utils_softfloat + +} // cv:: + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp index c0892e939f..0906583ea4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/sse_utils.hpp @@ -1,652 +1,652 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_SSE_UTILS_HPP -#define OPENCV_CORE_SSE_UTILS_HPP - -#ifndef __cplusplus -# error sse_utils.hpp header must be compiled as C++ -#endif - -#include "opencv2/core/cvdef.h" - -//! @addtogroup core_utils_sse -//! @{ - -#if CV_SSE2 - -inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g0); - __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g0); - __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_g1); - __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_g1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk3); - __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk3); - - __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk3); - __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk3); - - __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk2); - __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk2); - __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk3); - __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk3); - - v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk2); - v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk2); - v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk3); - v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk3); -} - -inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g1); - __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g1); - __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b0); - __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b0); - __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_b1); - __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_b1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk5); - __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk5); - - __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk5); - __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk5); - - __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk3); - __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk3); - __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk4); - __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk4); - __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk5); - __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk5); - - v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk3); - v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk3); - v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk4); - v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk4); - v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk5); - v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk5); -} - -inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_b0); - __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_b0); - __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b1); - __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b1); - __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_a0); - __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_a0); - __m128i layer1_chunk6 = _mm_unpacklo_epi8(v_g1, v_a1); - __m128i layer1_chunk7 = _mm_unpackhi_epi8(v_g1, v_a1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk6 = _mm_unpacklo_epi8(layer1_chunk3, layer1_chunk7); - __m128i layer2_chunk7 = _mm_unpackhi_epi8(layer1_chunk3, layer1_chunk7); - - __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk6 = _mm_unpacklo_epi8(layer2_chunk3, layer2_chunk7); - __m128i layer3_chunk7 = _mm_unpackhi_epi8(layer2_chunk3, layer2_chunk7); - - __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk4); - __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk4); - __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk5); - __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk5); - __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk6); - __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk6); - __m128i layer4_chunk6 = _mm_unpacklo_epi8(layer3_chunk3, layer3_chunk7); - __m128i layer4_chunk7 = _mm_unpackhi_epi8(layer3_chunk3, layer3_chunk7); - - v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk4); - v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk4); - v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk5); - v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk5); - v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk6); - v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk6); - v_a0 = _mm_unpacklo_epi8(layer4_chunk3, layer4_chunk7); - v_a1 = _mm_unpackhi_epi8(layer4_chunk3, layer4_chunk7); -} - -inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i v_mask = _mm_set1_epi16(0x00ff); - - __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer4_chunk2 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); - __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); - - __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); - __m128i layer3_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); - __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); - - __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); - __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); - - __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); - __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); - - v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); - v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); -} - -inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i v_mask = _mm_set1_epi16(0x00ff); - - __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); - __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); - __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); - - __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); - __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); - __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); - - __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); - __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); - __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); - - __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); - __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); - __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); - - v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); - v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); - v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); -} - -inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i v_mask = _mm_set1_epi16(0x00ff); - - __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); - __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); - __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer4_chunk6 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); - __m128i layer4_chunk3 = _mm_packus_epi16(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); - __m128i layer4_chunk7 = _mm_packus_epi16(_mm_srli_epi16(v_a0, 8), _mm_srli_epi16(v_a1, 8)); - - __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); - __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); - __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); - __m128i layer3_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); - __m128i layer3_chunk3 = _mm_packus_epi16(_mm_and_si128(layer4_chunk6, v_mask), _mm_and_si128(layer4_chunk7, v_mask)); - __m128i layer3_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk6, 8), _mm_srli_epi16(layer4_chunk7, 8)); - - __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); - __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); - __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); - __m128i layer2_chunk3 = _mm_packus_epi16(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); - __m128i layer2_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk6, 8), _mm_srli_epi16(layer3_chunk7, 8)); - - __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); - __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); - __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); - __m128i layer1_chunk3 = _mm_packus_epi16(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); - __m128i layer1_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk6, 8), _mm_srli_epi16(layer2_chunk7, 8)); - - v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); - v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); - v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_a0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); - v_g1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); - v_a1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk6, 8), _mm_srli_epi16(layer1_chunk7, 8)); -} - -inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g0); - __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g0); - __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_g1); - __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_g1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk2); - __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk3); - __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk3); - - __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk2); - __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk3); - __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk3); - - v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk2); - v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk2); - v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk3); - v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk3); -} - -inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g1); - __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g1); - __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b0); - __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b0); - __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_b1); - __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_b1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk3); - __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk4); - __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk5); - __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk5); - - __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk3); - __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk4); - __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk5); - __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk5); - - v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk3); - v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk3); - v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk4); - v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk4); - v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk5); - v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk5); -} - -inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_b0); - __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_b0); - __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b1); - __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b1); - __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_a0); - __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_a0); - __m128i layer1_chunk6 = _mm_unpacklo_epi16(v_g1, v_a1); - __m128i layer1_chunk7 = _mm_unpackhi_epi16(v_g1, v_a1); - - __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk4); - __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk5); - __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk6); - __m128i layer2_chunk6 = _mm_unpacklo_epi16(layer1_chunk3, layer1_chunk7); - __m128i layer2_chunk7 = _mm_unpackhi_epi16(layer1_chunk3, layer1_chunk7); - - __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk4); - __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk5); - __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk6); - __m128i layer3_chunk6 = _mm_unpacklo_epi16(layer2_chunk3, layer2_chunk7); - __m128i layer3_chunk7 = _mm_unpackhi_epi16(layer2_chunk3, layer2_chunk7); - - v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk4); - v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk4); - v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk5); - v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk5); - v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk6); - v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk6); - v_a0 = _mm_unpacklo_epi16(layer3_chunk3, layer3_chunk7); - v_a1 = _mm_unpackhi_epi16(layer3_chunk3, layer3_chunk7); -} - -#if CV_SSE4_1 - -inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) -{ - __m128i v_mask = _mm_set1_epi32(0x0000ffff); - - __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer3_chunk2 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); - __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); - - __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); - __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); - - __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); - __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); - - v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); - v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); -} - -inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, - __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) -{ - __m128i v_mask = _mm_set1_epi32(0x0000ffff); - - __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); - __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); - __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); - - __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); - __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); - __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); - - __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); - __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); - __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); - - v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); - v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); - v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); -} - -inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, - __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) -{ - __m128i v_mask = _mm_set1_epi32(0x0000ffff); - - __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); - __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); - __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); - __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); - __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); - __m128i layer3_chunk6 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); - __m128i layer3_chunk3 = _mm_packus_epi32(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); - __m128i layer3_chunk7 = _mm_packus_epi32(_mm_srli_epi32(v_a0, 16), _mm_srli_epi32(v_a1, 16)); - - __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); - __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); - __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); - __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); - __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); - __m128i layer2_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); - __m128i layer2_chunk3 = _mm_packus_epi32(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); - __m128i layer2_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk6, 16), _mm_srli_epi32(layer3_chunk7, 16)); - - __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); - __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); - __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); - __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); - __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); - __m128i layer1_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); - __m128i layer1_chunk3 = _mm_packus_epi32(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); - __m128i layer1_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk6, 16), _mm_srli_epi32(layer2_chunk7, 16)); - - v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); - v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); - v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); - v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); - v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); - v_a0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); - v_g1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); - v_a1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk6, 16), _mm_srli_epi32(layer1_chunk7, 16)); -} - -#endif // CV_SSE4_1 - -inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) -{ - __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g0); - __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g0); - __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_g1); - __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_g1); - - __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk2); - __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk2); - __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk3); - __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk3); - - v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk2); - v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk2); - v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk3); - v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk3); -} - -inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, - __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) -{ - __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g1); - __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g1); - __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b0); - __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b0); - __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_b1); - __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_b1); - - __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk3); - __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk3); - __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk4); - __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk4); - __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk5); - __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk5); - - v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk3); - v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk3); - v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk4); - v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk4); - v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk5); - v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk5); -} - -inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, - __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) -{ - __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_b0); - __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_b0); - __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b1); - __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b1); - __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_a0); - __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_a0); - __m128 layer1_chunk6 = _mm_unpacklo_ps(v_g1, v_a1); - __m128 layer1_chunk7 = _mm_unpackhi_ps(v_g1, v_a1); - - __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk4); - __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk4); - __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk5); - __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk5); - __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk6); - __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk6); - __m128 layer2_chunk6 = _mm_unpacklo_ps(layer1_chunk3, layer1_chunk7); - __m128 layer2_chunk7 = _mm_unpackhi_ps(layer1_chunk3, layer1_chunk7); - - v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk4); - v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk4); - v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk5); - v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk5); - v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk6); - v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk6); - v_a0 = _mm_unpacklo_ps(layer2_chunk3, layer2_chunk7); - v_a1 = _mm_unpackhi_ps(layer2_chunk3, layer2_chunk7); -} - -inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) -{ - enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; - - __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); - __m128 layer2_chunk2 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); - __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); - __m128 layer2_chunk3 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); - - __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); - __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); - __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); - __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); - - v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); - v_g0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); - v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); - v_g1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); -} - -inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, - __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) -{ - enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; - - __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); - __m128 layer2_chunk3 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); - __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); - __m128 layer2_chunk4 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); - __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); - __m128 layer2_chunk5 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); - - __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); - __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); - __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); - __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); - __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); - __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); - - v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); - v_g1 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); - v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); - v_b0 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); - v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); - v_b1 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); -} - -inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, - __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) -{ - enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; - - __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); - __m128 layer2_chunk4 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); - __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); - __m128 layer2_chunk5 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); - __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); - __m128 layer2_chunk6 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); - __m128 layer2_chunk3 = _mm_shuffle_ps(v_a0, v_a1, mask_lo); - __m128 layer2_chunk7 = _mm_shuffle_ps(v_a0, v_a1, mask_hi); - - __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); - __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); - __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); - __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); - __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); - __m128 layer1_chunk6 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); - __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_lo); - __m128 layer1_chunk7 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_hi); - - v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); - v_b0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); - v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); - v_b1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); - v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); - v_a0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); - v_g1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_lo); - v_a1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_hi); -} - -#endif // CV_SSE2 - -//! @} - -#endif //OPENCV_CORE_SSE_UTILS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_SSE_UTILS_HPP +#define OPENCV_CORE_SSE_UTILS_HPP + +#ifndef __cplusplus +# error sse_utils.hpp header must be compiled as C++ +#endif + +#include "opencv2/core/cvdef.h" + +//! @addtogroup core_utils_sse +//! @{ + +#if CV_SSE2 + +inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g0); + __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g0); + __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_g1); + __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_g1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk3); + __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk3); + + __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk3); + __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk3); + + __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk2); + __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk2); + __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk3); + __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk3); + + v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk2); + v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk2); + v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk3); + v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk3); +} + +inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_g1); + __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_g1); + __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b0); + __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b0); + __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_b1); + __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_b1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk5); + __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk5); + + __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk5); + __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk5); + + __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk3); + __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk3); + __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk4); + __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk4); + __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk5); + __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk5); + + v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk3); + v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk3); + v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk4); + v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk4); + v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk5); + v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk5); +} + +inline void _mm_deinterleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi8(v_r0, v_b0); + __m128i layer1_chunk1 = _mm_unpackhi_epi8(v_r0, v_b0); + __m128i layer1_chunk2 = _mm_unpacklo_epi8(v_r1, v_b1); + __m128i layer1_chunk3 = _mm_unpackhi_epi8(v_r1, v_b1); + __m128i layer1_chunk4 = _mm_unpacklo_epi8(v_g0, v_a0); + __m128i layer1_chunk5 = _mm_unpackhi_epi8(v_g0, v_a0); + __m128i layer1_chunk6 = _mm_unpacklo_epi8(v_g1, v_a1); + __m128i layer1_chunk7 = _mm_unpackhi_epi8(v_g1, v_a1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi8(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk1 = _mm_unpackhi_epi8(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk2 = _mm_unpacklo_epi8(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk3 = _mm_unpackhi_epi8(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk4 = _mm_unpacklo_epi8(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk5 = _mm_unpackhi_epi8(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk6 = _mm_unpacklo_epi8(layer1_chunk3, layer1_chunk7); + __m128i layer2_chunk7 = _mm_unpackhi_epi8(layer1_chunk3, layer1_chunk7); + + __m128i layer3_chunk0 = _mm_unpacklo_epi8(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk1 = _mm_unpackhi_epi8(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk2 = _mm_unpacklo_epi8(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk3 = _mm_unpackhi_epi8(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk4 = _mm_unpacklo_epi8(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk5 = _mm_unpackhi_epi8(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk6 = _mm_unpacklo_epi8(layer2_chunk3, layer2_chunk7); + __m128i layer3_chunk7 = _mm_unpackhi_epi8(layer2_chunk3, layer2_chunk7); + + __m128i layer4_chunk0 = _mm_unpacklo_epi8(layer3_chunk0, layer3_chunk4); + __m128i layer4_chunk1 = _mm_unpackhi_epi8(layer3_chunk0, layer3_chunk4); + __m128i layer4_chunk2 = _mm_unpacklo_epi8(layer3_chunk1, layer3_chunk5); + __m128i layer4_chunk3 = _mm_unpackhi_epi8(layer3_chunk1, layer3_chunk5); + __m128i layer4_chunk4 = _mm_unpacklo_epi8(layer3_chunk2, layer3_chunk6); + __m128i layer4_chunk5 = _mm_unpackhi_epi8(layer3_chunk2, layer3_chunk6); + __m128i layer4_chunk6 = _mm_unpacklo_epi8(layer3_chunk3, layer3_chunk7); + __m128i layer4_chunk7 = _mm_unpackhi_epi8(layer3_chunk3, layer3_chunk7); + + v_r0 = _mm_unpacklo_epi8(layer4_chunk0, layer4_chunk4); + v_r1 = _mm_unpackhi_epi8(layer4_chunk0, layer4_chunk4); + v_g0 = _mm_unpacklo_epi8(layer4_chunk1, layer4_chunk5); + v_g1 = _mm_unpackhi_epi8(layer4_chunk1, layer4_chunk5); + v_b0 = _mm_unpacklo_epi8(layer4_chunk2, layer4_chunk6); + v_b1 = _mm_unpackhi_epi8(layer4_chunk2, layer4_chunk6); + v_a0 = _mm_unpacklo_epi8(layer4_chunk3, layer4_chunk7); + v_a1 = _mm_unpackhi_epi8(layer4_chunk3, layer4_chunk7); +} + +inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i v_mask = _mm_set1_epi16(0x00ff); + + __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer4_chunk2 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); + __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); + + __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); + __m128i layer3_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); + __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); + + __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); + __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); + + __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk2 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); + __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); + + v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); + v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); +} + +inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i v_mask = _mm_set1_epi16(0x00ff); + + __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer4_chunk3 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); + __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); + __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); + + __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); + __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); + __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); + + __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); + __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); + __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); + + __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); + __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); + __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); + + v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); + v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); + v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); +} + +inline void _mm_interleave_epi8(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i v_mask = _mm_set1_epi16(0x00ff); + + __m128i layer4_chunk0 = _mm_packus_epi16(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer4_chunk4 = _mm_packus_epi16(_mm_srli_epi16(v_r0, 8), _mm_srli_epi16(v_r1, 8)); + __m128i layer4_chunk1 = _mm_packus_epi16(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer4_chunk5 = _mm_packus_epi16(_mm_srli_epi16(v_g0, 8), _mm_srli_epi16(v_g1, 8)); + __m128i layer4_chunk2 = _mm_packus_epi16(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer4_chunk6 = _mm_packus_epi16(_mm_srli_epi16(v_b0, 8), _mm_srli_epi16(v_b1, 8)); + __m128i layer4_chunk3 = _mm_packus_epi16(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); + __m128i layer4_chunk7 = _mm_packus_epi16(_mm_srli_epi16(v_a0, 8), _mm_srli_epi16(v_a1, 8)); + + __m128i layer3_chunk0 = _mm_packus_epi16(_mm_and_si128(layer4_chunk0, v_mask), _mm_and_si128(layer4_chunk1, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk0, 8), _mm_srli_epi16(layer4_chunk1, 8)); + __m128i layer3_chunk1 = _mm_packus_epi16(_mm_and_si128(layer4_chunk2, v_mask), _mm_and_si128(layer4_chunk3, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk2, 8), _mm_srli_epi16(layer4_chunk3, 8)); + __m128i layer3_chunk2 = _mm_packus_epi16(_mm_and_si128(layer4_chunk4, v_mask), _mm_and_si128(layer4_chunk5, v_mask)); + __m128i layer3_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk4, 8), _mm_srli_epi16(layer4_chunk5, 8)); + __m128i layer3_chunk3 = _mm_packus_epi16(_mm_and_si128(layer4_chunk6, v_mask), _mm_and_si128(layer4_chunk7, v_mask)); + __m128i layer3_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer4_chunk6, 8), _mm_srli_epi16(layer4_chunk7, 8)); + + __m128i layer2_chunk0 = _mm_packus_epi16(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk0, 8), _mm_srli_epi16(layer3_chunk1, 8)); + __m128i layer2_chunk1 = _mm_packus_epi16(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk2, 8), _mm_srli_epi16(layer3_chunk3, 8)); + __m128i layer2_chunk2 = _mm_packus_epi16(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk4, 8), _mm_srli_epi16(layer3_chunk5, 8)); + __m128i layer2_chunk3 = _mm_packus_epi16(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); + __m128i layer2_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer3_chunk6, 8), _mm_srli_epi16(layer3_chunk7, 8)); + + __m128i layer1_chunk0 = _mm_packus_epi16(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk0, 8), _mm_srli_epi16(layer2_chunk1, 8)); + __m128i layer1_chunk1 = _mm_packus_epi16(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk2, 8), _mm_srli_epi16(layer2_chunk3, 8)); + __m128i layer1_chunk2 = _mm_packus_epi16(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk6 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk4, 8), _mm_srli_epi16(layer2_chunk5, 8)); + __m128i layer1_chunk3 = _mm_packus_epi16(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); + __m128i layer1_chunk7 = _mm_packus_epi16(_mm_srli_epi16(layer2_chunk6, 8), _mm_srli_epi16(layer2_chunk7, 8)); + + v_r0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_b0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk0, 8), _mm_srli_epi16(layer1_chunk1, 8)); + v_r1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk2, 8), _mm_srli_epi16(layer1_chunk3, 8)); + v_g0 = _mm_packus_epi16(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_a0 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk4, 8), _mm_srli_epi16(layer1_chunk5, 8)); + v_g1 = _mm_packus_epi16(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); + v_a1 = _mm_packus_epi16(_mm_srli_epi16(layer1_chunk6, 8), _mm_srli_epi16(layer1_chunk7, 8)); +} + +inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g0); + __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g0); + __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_g1); + __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_g1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk2); + __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk3); + __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk3); + + __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk2); + __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk3); + __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk3); + + v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk2); + v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk2); + v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk3); + v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk3); +} + +inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_g1); + __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_g1); + __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b0); + __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b0); + __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_b1); + __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_b1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk3); + __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk4); + __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk5); + __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk5); + + __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk3); + __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk4); + __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk5); + __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk5); + + v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk3); + v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk3); + v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk4); + v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk4); + v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk5); + v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk5); +} + +inline void _mm_deinterleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i layer1_chunk0 = _mm_unpacklo_epi16(v_r0, v_b0); + __m128i layer1_chunk1 = _mm_unpackhi_epi16(v_r0, v_b0); + __m128i layer1_chunk2 = _mm_unpacklo_epi16(v_r1, v_b1); + __m128i layer1_chunk3 = _mm_unpackhi_epi16(v_r1, v_b1); + __m128i layer1_chunk4 = _mm_unpacklo_epi16(v_g0, v_a0); + __m128i layer1_chunk5 = _mm_unpackhi_epi16(v_g0, v_a0); + __m128i layer1_chunk6 = _mm_unpacklo_epi16(v_g1, v_a1); + __m128i layer1_chunk7 = _mm_unpackhi_epi16(v_g1, v_a1); + + __m128i layer2_chunk0 = _mm_unpacklo_epi16(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk1 = _mm_unpackhi_epi16(layer1_chunk0, layer1_chunk4); + __m128i layer2_chunk2 = _mm_unpacklo_epi16(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk3 = _mm_unpackhi_epi16(layer1_chunk1, layer1_chunk5); + __m128i layer2_chunk4 = _mm_unpacklo_epi16(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk5 = _mm_unpackhi_epi16(layer1_chunk2, layer1_chunk6); + __m128i layer2_chunk6 = _mm_unpacklo_epi16(layer1_chunk3, layer1_chunk7); + __m128i layer2_chunk7 = _mm_unpackhi_epi16(layer1_chunk3, layer1_chunk7); + + __m128i layer3_chunk0 = _mm_unpacklo_epi16(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk1 = _mm_unpackhi_epi16(layer2_chunk0, layer2_chunk4); + __m128i layer3_chunk2 = _mm_unpacklo_epi16(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk3 = _mm_unpackhi_epi16(layer2_chunk1, layer2_chunk5); + __m128i layer3_chunk4 = _mm_unpacklo_epi16(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk5 = _mm_unpackhi_epi16(layer2_chunk2, layer2_chunk6); + __m128i layer3_chunk6 = _mm_unpacklo_epi16(layer2_chunk3, layer2_chunk7); + __m128i layer3_chunk7 = _mm_unpackhi_epi16(layer2_chunk3, layer2_chunk7); + + v_r0 = _mm_unpacklo_epi16(layer3_chunk0, layer3_chunk4); + v_r1 = _mm_unpackhi_epi16(layer3_chunk0, layer3_chunk4); + v_g0 = _mm_unpacklo_epi16(layer3_chunk1, layer3_chunk5); + v_g1 = _mm_unpackhi_epi16(layer3_chunk1, layer3_chunk5); + v_b0 = _mm_unpacklo_epi16(layer3_chunk2, layer3_chunk6); + v_b1 = _mm_unpackhi_epi16(layer3_chunk2, layer3_chunk6); + v_a0 = _mm_unpacklo_epi16(layer3_chunk3, layer3_chunk7); + v_a1 = _mm_unpackhi_epi16(layer3_chunk3, layer3_chunk7); +} + +#if CV_SSE4_1 + +inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1) +{ + __m128i v_mask = _mm_set1_epi32(0x0000ffff); + + __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer3_chunk2 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); + __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); + + __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); + __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); + + __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk2 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); + __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); + + v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); + v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); +} + +inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, + __m128i & v_g1, __m128i & v_b0, __m128i & v_b1) +{ + __m128i v_mask = _mm_set1_epi32(0x0000ffff); + + __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer3_chunk3 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); + __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); + __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); + + __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); + __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); + __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); + + __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk3 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); + __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); + __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); + + v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_g1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); + v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); + v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); +} + +inline void _mm_interleave_epi16(__m128i & v_r0, __m128i & v_r1, __m128i & v_g0, __m128i & v_g1, + __m128i & v_b0, __m128i & v_b1, __m128i & v_a0, __m128i & v_a1) +{ + __m128i v_mask = _mm_set1_epi32(0x0000ffff); + + __m128i layer3_chunk0 = _mm_packus_epi32(_mm_and_si128(v_r0, v_mask), _mm_and_si128(v_r1, v_mask)); + __m128i layer3_chunk4 = _mm_packus_epi32(_mm_srli_epi32(v_r0, 16), _mm_srli_epi32(v_r1, 16)); + __m128i layer3_chunk1 = _mm_packus_epi32(_mm_and_si128(v_g0, v_mask), _mm_and_si128(v_g1, v_mask)); + __m128i layer3_chunk5 = _mm_packus_epi32(_mm_srli_epi32(v_g0, 16), _mm_srli_epi32(v_g1, 16)); + __m128i layer3_chunk2 = _mm_packus_epi32(_mm_and_si128(v_b0, v_mask), _mm_and_si128(v_b1, v_mask)); + __m128i layer3_chunk6 = _mm_packus_epi32(_mm_srli_epi32(v_b0, 16), _mm_srli_epi32(v_b1, 16)); + __m128i layer3_chunk3 = _mm_packus_epi32(_mm_and_si128(v_a0, v_mask), _mm_and_si128(v_a1, v_mask)); + __m128i layer3_chunk7 = _mm_packus_epi32(_mm_srli_epi32(v_a0, 16), _mm_srli_epi32(v_a1, 16)); + + __m128i layer2_chunk0 = _mm_packus_epi32(_mm_and_si128(layer3_chunk0, v_mask), _mm_and_si128(layer3_chunk1, v_mask)); + __m128i layer2_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk0, 16), _mm_srli_epi32(layer3_chunk1, 16)); + __m128i layer2_chunk1 = _mm_packus_epi32(_mm_and_si128(layer3_chunk2, v_mask), _mm_and_si128(layer3_chunk3, v_mask)); + __m128i layer2_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk2, 16), _mm_srli_epi32(layer3_chunk3, 16)); + __m128i layer2_chunk2 = _mm_packus_epi32(_mm_and_si128(layer3_chunk4, v_mask), _mm_and_si128(layer3_chunk5, v_mask)); + __m128i layer2_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk4, 16), _mm_srli_epi32(layer3_chunk5, 16)); + __m128i layer2_chunk3 = _mm_packus_epi32(_mm_and_si128(layer3_chunk6, v_mask), _mm_and_si128(layer3_chunk7, v_mask)); + __m128i layer2_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer3_chunk6, 16), _mm_srli_epi32(layer3_chunk7, 16)); + + __m128i layer1_chunk0 = _mm_packus_epi32(_mm_and_si128(layer2_chunk0, v_mask), _mm_and_si128(layer2_chunk1, v_mask)); + __m128i layer1_chunk4 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk0, 16), _mm_srli_epi32(layer2_chunk1, 16)); + __m128i layer1_chunk1 = _mm_packus_epi32(_mm_and_si128(layer2_chunk2, v_mask), _mm_and_si128(layer2_chunk3, v_mask)); + __m128i layer1_chunk5 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk2, 16), _mm_srli_epi32(layer2_chunk3, 16)); + __m128i layer1_chunk2 = _mm_packus_epi32(_mm_and_si128(layer2_chunk4, v_mask), _mm_and_si128(layer2_chunk5, v_mask)); + __m128i layer1_chunk6 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk4, 16), _mm_srli_epi32(layer2_chunk5, 16)); + __m128i layer1_chunk3 = _mm_packus_epi32(_mm_and_si128(layer2_chunk6, v_mask), _mm_and_si128(layer2_chunk7, v_mask)); + __m128i layer1_chunk7 = _mm_packus_epi32(_mm_srli_epi32(layer2_chunk6, 16), _mm_srli_epi32(layer2_chunk7, 16)); + + v_r0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk0, v_mask), _mm_and_si128(layer1_chunk1, v_mask)); + v_b0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk0, 16), _mm_srli_epi32(layer1_chunk1, 16)); + v_r1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk2, v_mask), _mm_and_si128(layer1_chunk3, v_mask)); + v_b1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk2, 16), _mm_srli_epi32(layer1_chunk3, 16)); + v_g0 = _mm_packus_epi32(_mm_and_si128(layer1_chunk4, v_mask), _mm_and_si128(layer1_chunk5, v_mask)); + v_a0 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk4, 16), _mm_srli_epi32(layer1_chunk5, 16)); + v_g1 = _mm_packus_epi32(_mm_and_si128(layer1_chunk6, v_mask), _mm_and_si128(layer1_chunk7, v_mask)); + v_a1 = _mm_packus_epi32(_mm_srli_epi32(layer1_chunk6, 16), _mm_srli_epi32(layer1_chunk7, 16)); +} + +#endif // CV_SSE4_1 + +inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) +{ + __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g0); + __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g0); + __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_g1); + __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_g1); + + __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk2); + __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk2); + __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk3); + __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk3); + + v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk2); + v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk2); + v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk3); + v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk3); +} + +inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, + __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) +{ + __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_g1); + __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_g1); + __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b0); + __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b0); + __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_b1); + __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_b1); + + __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk3); + __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk3); + __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk4); + __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk4); + __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk5); + __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk5); + + v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk3); + v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk3); + v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk4); + v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk4); + v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk5); + v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk5); +} + +inline void _mm_deinterleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, + __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) +{ + __m128 layer1_chunk0 = _mm_unpacklo_ps(v_r0, v_b0); + __m128 layer1_chunk1 = _mm_unpackhi_ps(v_r0, v_b0); + __m128 layer1_chunk2 = _mm_unpacklo_ps(v_r1, v_b1); + __m128 layer1_chunk3 = _mm_unpackhi_ps(v_r1, v_b1); + __m128 layer1_chunk4 = _mm_unpacklo_ps(v_g0, v_a0); + __m128 layer1_chunk5 = _mm_unpackhi_ps(v_g0, v_a0); + __m128 layer1_chunk6 = _mm_unpacklo_ps(v_g1, v_a1); + __m128 layer1_chunk7 = _mm_unpackhi_ps(v_g1, v_a1); + + __m128 layer2_chunk0 = _mm_unpacklo_ps(layer1_chunk0, layer1_chunk4); + __m128 layer2_chunk1 = _mm_unpackhi_ps(layer1_chunk0, layer1_chunk4); + __m128 layer2_chunk2 = _mm_unpacklo_ps(layer1_chunk1, layer1_chunk5); + __m128 layer2_chunk3 = _mm_unpackhi_ps(layer1_chunk1, layer1_chunk5); + __m128 layer2_chunk4 = _mm_unpacklo_ps(layer1_chunk2, layer1_chunk6); + __m128 layer2_chunk5 = _mm_unpackhi_ps(layer1_chunk2, layer1_chunk6); + __m128 layer2_chunk6 = _mm_unpacklo_ps(layer1_chunk3, layer1_chunk7); + __m128 layer2_chunk7 = _mm_unpackhi_ps(layer1_chunk3, layer1_chunk7); + + v_r0 = _mm_unpacklo_ps(layer2_chunk0, layer2_chunk4); + v_r1 = _mm_unpackhi_ps(layer2_chunk0, layer2_chunk4); + v_g0 = _mm_unpacklo_ps(layer2_chunk1, layer2_chunk5); + v_g1 = _mm_unpackhi_ps(layer2_chunk1, layer2_chunk5); + v_b0 = _mm_unpacklo_ps(layer2_chunk2, layer2_chunk6); + v_b1 = _mm_unpackhi_ps(layer2_chunk2, layer2_chunk6); + v_a0 = _mm_unpacklo_ps(layer2_chunk3, layer2_chunk7); + v_a1 = _mm_unpackhi_ps(layer2_chunk3, layer2_chunk7); +} + +inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1) +{ + enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; + + __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); + __m128 layer2_chunk2 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); + __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); + __m128 layer2_chunk3 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); + + __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); + __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); + __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); + __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); + + v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); + v_g0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); + v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); + v_g1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); +} + +inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, + __m128 & v_g1, __m128 & v_b0, __m128 & v_b1) +{ + enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; + + __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); + __m128 layer2_chunk3 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); + __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); + __m128 layer2_chunk4 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); + __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); + __m128 layer2_chunk5 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); + + __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); + __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); + __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); + __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); + __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); + __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); + + v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); + v_g1 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); + v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); + v_b0 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); + v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); + v_b1 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); +} + +inline void _mm_interleave_ps(__m128 & v_r0, __m128 & v_r1, __m128 & v_g0, __m128 & v_g1, + __m128 & v_b0, __m128 & v_b1, __m128 & v_a0, __m128 & v_a1) +{ + enum { mask_lo = _MM_SHUFFLE(2, 0, 2, 0), mask_hi = _MM_SHUFFLE(3, 1, 3, 1) }; + + __m128 layer2_chunk0 = _mm_shuffle_ps(v_r0, v_r1, mask_lo); + __m128 layer2_chunk4 = _mm_shuffle_ps(v_r0, v_r1, mask_hi); + __m128 layer2_chunk1 = _mm_shuffle_ps(v_g0, v_g1, mask_lo); + __m128 layer2_chunk5 = _mm_shuffle_ps(v_g0, v_g1, mask_hi); + __m128 layer2_chunk2 = _mm_shuffle_ps(v_b0, v_b1, mask_lo); + __m128 layer2_chunk6 = _mm_shuffle_ps(v_b0, v_b1, mask_hi); + __m128 layer2_chunk3 = _mm_shuffle_ps(v_a0, v_a1, mask_lo); + __m128 layer2_chunk7 = _mm_shuffle_ps(v_a0, v_a1, mask_hi); + + __m128 layer1_chunk0 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_lo); + __m128 layer1_chunk4 = _mm_shuffle_ps(layer2_chunk0, layer2_chunk1, mask_hi); + __m128 layer1_chunk1 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_lo); + __m128 layer1_chunk5 = _mm_shuffle_ps(layer2_chunk2, layer2_chunk3, mask_hi); + __m128 layer1_chunk2 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_lo); + __m128 layer1_chunk6 = _mm_shuffle_ps(layer2_chunk4, layer2_chunk5, mask_hi); + __m128 layer1_chunk3 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_lo); + __m128 layer1_chunk7 = _mm_shuffle_ps(layer2_chunk6, layer2_chunk7, mask_hi); + + v_r0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_lo); + v_b0 = _mm_shuffle_ps(layer1_chunk0, layer1_chunk1, mask_hi); + v_r1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_lo); + v_b1 = _mm_shuffle_ps(layer1_chunk2, layer1_chunk3, mask_hi); + v_g0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_lo); + v_a0 = _mm_shuffle_ps(layer1_chunk4, layer1_chunk5, mask_hi); + v_g1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_lo); + v_a1 = _mm_shuffle_ps(layer1_chunk6, layer1_chunk7, mask_hi); +} + +#endif // CV_SSE2 + +//! @} + +#endif //OPENCV_CORE_SSE_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp b/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp index d17dc4e508..522519389b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/traits.hpp @@ -1,417 +1,417 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_TRAITS_HPP -#define OPENCV_CORE_TRAITS_HPP - -#include "opencv2/core/cvdef.h" - -namespace cv -{ - -//#define OPENCV_TRAITS_ENABLE_DEPRECATED - -//! @addtogroup core_basic -//! @{ - -/** @brief Template "trait" class for OpenCV primitive data types. - -@note Deprecated. This is replaced by "single purpose" traits: traits::Type and traits::Depth - -A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed -short, int, float, double, or a tuple of values of one of these types, where all the values in the -tuple have the same type. Any primitive type from the list can be defined by an identifier in the -form CV_\{U|S|F}C(\), for example: uchar \~ CV_8UC1, 3-element -floating-point tuple \~ CV_32FC3, and so on. A universal OpenCV structure that is able to store a -single instance of such a primitive data type is Vec. Multiple instances of such a type can be -stored in a std::vector, Mat, Mat_, SparseMat, SparseMat_, or any other container that is able to -store Vec instances. - -The DataType class is basically used to provide a description of such primitive data types without -adding any fields or methods to the corresponding classes (and it is actually impossible to add -anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not -DataType itself that is used but its specialized versions, such as: -@code - template<> class DataType - { - typedef uchar value_type; - typedef int work_type; - typedef uchar channel_type; - enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U }; - }; - ... - template DataType > - { - typedef std::complex<_Tp> value_type; - typedef std::complex<_Tp> work_type; - typedef _Tp channel_type; - // DataDepth is another helper trait class - enum { depth = DataDepth<_Tp>::value, channels=2, - fmt=(channels-1)*256+DataDepth<_Tp>::fmt, - type=CV_MAKETYPE(depth, channels) }; - }; - ... -@endcode -The main purpose of this class is to convert compilation-time type information to an -OpenCV-compatible data type identifier, for example: -@code - // allocates a 30x40 floating-point matrix - Mat A(30, 40, DataType::type); - - Mat B = Mat_ >(3, 3); - // the statement below will print 6, 2 , that is depth == CV_64F, channels == 2 - cout << B.depth() << ", " << B.channels() << endl; -@endcode -So, such traits are used to tell OpenCV which data type you are working with, even if such a type is -not native to OpenCV. For example, the matrix B initialization above is compiled because OpenCV -defines the proper specialized template class DataType\ \> . This mechanism is also -useful (and used in OpenCV this way) for generic algorithms implementations. - -@note Default values were dropped to stop confusing developers about using of unsupported types (see #7599) -*/ -template class DataType -{ -public: -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - typedef _Tp value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 1, - depth = -1, - channels = 1, - fmt = 0, - type = CV_MAKETYPE(depth, channels) - }; -#endif -}; - -template<> class DataType -{ -public: - typedef bool value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8U, - channels = 1, - fmt = (int)'u', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef uchar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8U, - channels = 1, - fmt = (int)'u', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef schar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8S, - channels = 1, - fmt = (int)'c', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef schar value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_8S, - channels = 1, - fmt = (int)'c', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef ushort value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_16U, - channels = 1, - fmt = (int)'w', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef short value_type; - typedef int work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_16S, - channels = 1, - fmt = (int)'s', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef int value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_32S, - channels = 1, - fmt = (int)'i', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef float value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_32F, - channels = 1, - fmt = (int)'f', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef double value_type; - typedef value_type work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_64F, - channels = 1, - fmt = (int)'d', - type = CV_MAKETYPE(depth, channels) - }; -}; - -template<> class DataType -{ -public: - typedef hfloat value_type; - typedef float work_type; - typedef value_type channel_type; - typedef value_type vec_type; - enum { generic_type = 0, - depth = CV_16F, - channels = 1, - fmt = (int)'h', - type = CV_MAKETYPE(depth, channels) - }; -}; - -/** @brief A helper class for cv::DataType - -The class is specialized for each fundamental numerical data type supported by OpenCV. It provides -DataDepth::value constant. -*/ -template class DataDepth -{ -public: - enum - { - value = DataType<_Tp>::depth, - fmt = DataType<_Tp>::fmt - }; -}; - - -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - -template class TypeDepth -{ -#ifdef OPENCV_TRAITS_ENABLE_LEGACY_DEFAULTS - enum { depth = CV_USRTYPE1 }; - typedef void value_type; -#endif -}; - -template<> class TypeDepth -{ - enum { depth = CV_8U }; - typedef uchar value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_8S }; - typedef schar value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_16U }; - typedef ushort value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_16S }; - typedef short value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_32S }; - typedef int value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_32F }; - typedef float value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_64F }; - typedef double value_type; -}; - -template<> class TypeDepth -{ - enum { depth = CV_16F }; - typedef hfloat value_type; -}; - -#endif - -//! @} - -namespace traits { - -namespace internal { -#define CV_CREATE_MEMBER_CHECK(X) \ -template class CheckMember_##X { \ - struct Fallback { int X; }; \ - struct Derived : T, Fallback { }; \ - template struct Check; \ - typedef char CV_NO[1]; \ - typedef char CV_YES[2]; \ - template static CV_NO & func(Check *); \ - template static CV_YES & func(...); \ -public: \ - typedef CheckMember_##X type; \ - enum { value = sizeof(func(0)) == sizeof(CV_YES) }; \ -}; - -CV_CREATE_MEMBER_CHECK(fmt) -CV_CREATE_MEMBER_CHECK(type) - -} // namespace internal - - -template -struct Depth -{ enum { value = DataType::depth }; }; - -template -struct Type -{ enum { value = DataType::type }; }; - -/** Similar to traits::Type but has value = -1 in case of unknown type (instead of compiler error) */ -template >::value > -struct SafeType {}; - -template -struct SafeType -{ enum { value = -1 }; }; - -template -struct SafeType -{ enum { value = Type::value }; }; - - -template >::value > -struct SafeFmt {}; - -template -struct SafeFmt -{ enum { fmt = 0 }; }; - -template -struct SafeFmt -{ enum { fmt = DataType::fmt }; }; - - -} // namespace - -} // cv - -#endif // OPENCV_CORE_TRAITS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_TRAITS_HPP +#define OPENCV_CORE_TRAITS_HPP + +#include "opencv2/core/cvdef.h" + +namespace cv +{ + +//#define OPENCV_TRAITS_ENABLE_DEPRECATED + +//! @addtogroup core_basic +//! @{ + +/** @brief Template "trait" class for OpenCV primitive data types. + +@note Deprecated. This is replaced by "single purpose" traits: traits::Type and traits::Depth + +A primitive OpenCV data type is one of unsigned char, bool, signed char, unsigned short, signed +short, int, float, double, or a tuple of values of one of these types, where all the values in the +tuple have the same type. Any primitive type from the list can be defined by an identifier in the +form CV_\{U|S|F}C(\), for example: uchar \~ CV_8UC1, 3-element +floating-point tuple \~ CV_32FC3, and so on. A universal OpenCV structure that is able to store a +single instance of such a primitive data type is Vec. Multiple instances of such a type can be +stored in a std::vector, Mat, Mat_, SparseMat, SparseMat_, or any other container that is able to +store Vec instances. + +The DataType class is basically used to provide a description of such primitive data types without +adding any fields or methods to the corresponding classes (and it is actually impossible to add +anything to primitive C/C++ data types). This technique is known in C++ as class traits. It is not +DataType itself that is used but its specialized versions, such as: +@code + template<> class DataType + { + typedef uchar value_type; + typedef int work_type; + typedef uchar channel_type; + enum { channel_type = CV_8U, channels = 1, fmt='u', type = CV_8U }; + }; + ... + template DataType > + { + typedef std::complex<_Tp> value_type; + typedef std::complex<_Tp> work_type; + typedef _Tp channel_type; + // DataDepth is another helper trait class + enum { depth = DataDepth<_Tp>::value, channels=2, + fmt=(channels-1)*256+DataDepth<_Tp>::fmt, + type=CV_MAKETYPE(depth, channels) }; + }; + ... +@endcode +The main purpose of this class is to convert compilation-time type information to an +OpenCV-compatible data type identifier, for example: +@code + // allocates a 30x40 floating-point matrix + Mat A(30, 40, DataType::type); + + Mat B = Mat_ >(3, 3); + // the statement below will print 6, 2 , that is depth == CV_64F, channels == 2 + cout << B.depth() << ", " << B.channels() << endl; +@endcode +So, such traits are used to tell OpenCV which data type you are working with, even if such a type is +not native to OpenCV. For example, the matrix B initialization above is compiled because OpenCV +defines the proper specialized template class DataType\ \> . This mechanism is also +useful (and used in OpenCV this way) for generic algorithms implementations. + +@note Default values were dropped to stop confusing developers about using of unsupported types (see #7599) +*/ +template class DataType +{ +public: +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + typedef _Tp value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 1, + depth = -1, + channels = 1, + fmt = 0, + type = CV_MAKETYPE(depth, channels) + }; +#endif +}; + +template<> class DataType +{ +public: + typedef bool value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8U, + channels = 1, + fmt = (int)'u', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef uchar value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8U, + channels = 1, + fmt = (int)'u', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef schar value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8S, + channels = 1, + fmt = (int)'c', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef schar value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_8S, + channels = 1, + fmt = (int)'c', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef ushort value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_16U, + channels = 1, + fmt = (int)'w', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef short value_type; + typedef int work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_16S, + channels = 1, + fmt = (int)'s', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef int value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_32S, + channels = 1, + fmt = (int)'i', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef float value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_32F, + channels = 1, + fmt = (int)'f', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef double value_type; + typedef value_type work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_64F, + channels = 1, + fmt = (int)'d', + type = CV_MAKETYPE(depth, channels) + }; +}; + +template<> class DataType +{ +public: + typedef hfloat value_type; + typedef float work_type; + typedef value_type channel_type; + typedef value_type vec_type; + enum { generic_type = 0, + depth = CV_16F, + channels = 1, + fmt = (int)'h', + type = CV_MAKETYPE(depth, channels) + }; +}; + +/** @brief A helper class for cv::DataType + +The class is specialized for each fundamental numerical data type supported by OpenCV. It provides +DataDepth::value constant. +*/ +template class DataDepth +{ +public: + enum + { + value = DataType<_Tp>::depth, + fmt = DataType<_Tp>::fmt + }; +}; + + +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + +template class TypeDepth +{ +#ifdef OPENCV_TRAITS_ENABLE_LEGACY_DEFAULTS + enum { depth = CV_USRTYPE1 }; + typedef void value_type; +#endif +}; + +template<> class TypeDepth +{ + enum { depth = CV_8U }; + typedef uchar value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_8S }; + typedef schar value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_16U }; + typedef ushort value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_16S }; + typedef short value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_32S }; + typedef int value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_32F }; + typedef float value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_64F }; + typedef double value_type; +}; + +template<> class TypeDepth +{ + enum { depth = CV_16F }; + typedef hfloat value_type; +}; + +#endif + +//! @} + +namespace traits { + +namespace internal { +#define CV_CREATE_MEMBER_CHECK(X) \ +template class CheckMember_##X { \ + struct Fallback { int X; }; \ + struct Derived : T, Fallback { }; \ + template struct Check; \ + typedef char CV_NO[1]; \ + typedef char CV_YES[2]; \ + template static CV_NO & func(Check *); \ + template static CV_YES & func(...); \ +public: \ + typedef CheckMember_##X type; \ + enum { value = sizeof(func(0)) == sizeof(CV_YES) }; \ +}; + +CV_CREATE_MEMBER_CHECK(fmt) +CV_CREATE_MEMBER_CHECK(type) + +} // namespace internal + + +template +struct Depth +{ enum { value = DataType::depth }; }; + +template +struct Type +{ enum { value = DataType::type }; }; + +/** Similar to traits::Type but has value = -1 in case of unknown type (instead of compiler error) */ +template >::value > +struct SafeType {}; + +template +struct SafeType +{ enum { value = -1 }; }; + +template +struct SafeType +{ enum { value = Type::value }; }; + + +template >::value > +struct SafeFmt {}; + +template +struct SafeFmt +{ enum { fmt = 0 }; }; + +template +struct SafeFmt +{ enum { fmt = DataType::fmt }; }; + + +} // namespace + +} // cv + +#endif // OPENCV_CORE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/types.hpp b/3rdParty/opencv-4.11.0/opencv2/core/types.hpp index f69e499f36..64de0b2809 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/types.hpp @@ -1,2489 +1,2489 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_TYPES_HPP -#define OPENCV_CORE_TYPES_HPP - -#ifndef __cplusplus -# error types.hpp header must be compiled as C++ -#endif - -#include -#include -#include -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/matx.hpp" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4459) // declaration of '...' hides global declaration -#endif - -namespace cv -{ - -//! @addtogroup core_basic -//! @{ - -//////////////////////////////// Complex ////////////////////////////// - -/** @brief A complex number class. - - The template class is similar and compatible with std::complex, however it provides slightly - more convenient access to the real and imaginary parts using through the simple field access, as opposite - to std::complex::real() and std::complex::imag(). -*/ -template class Complex -{ -public: - - //! default constructor - Complex(); - Complex( _Tp _re, _Tp _im = 0 ); - - //! conversion to another data type - template operator Complex() const; - //! conjugation - Complex conj() const; - - _Tp re, im; ///< the real and the imaginary parts -}; - -typedef Complex Complexf; -typedef Complex Complexd; - -template class DataType< Complex<_Tp> > -{ -public: - typedef Complex<_Tp> value_type; - typedef value_type work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = DataType::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Complex<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Complex<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; -} // namespace - - -//////////////////////////////// Point_ //////////////////////////////// - -/** @brief Template class for 2D points specified by its coordinates `x` and `y`. - -An instance of the class is interchangeable with C structures, CvPoint and CvPoint2D32f . There is -also a cast operator to convert point coordinates to the specified type. The conversion from -floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion -uses this operation for each of the coordinates. Besides the class members listed in the -declaration above, the following operations on points are implemented: -@code - pt1 = pt2 + pt3; - pt1 = pt2 - pt3; - pt1 = pt2 * a; - pt1 = a * pt2; - pt1 = pt2 / a; - pt1 += pt2; - pt1 -= pt2; - pt1 *= a; - pt1 /= a; - double value = norm(pt); // L2 norm - pt1 == pt2; - pt1 != pt2; -@endcode -For your convenience, the following type aliases are defined: -@code - typedef Point_ Point2i; - typedef Point2i Point; - typedef Point_ Point2f; - typedef Point_ Point2d; -@endcode -Example: -@code - Point2f a(0.3f, 0.f), b(0.f, 0.4f); - Point pt = (a + b)*10.f; - cout << pt.x << ", " << pt.y << endl; -@endcode -*/ -template class Point_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Point_(); - Point_(_Tp _x, _Tp _y); -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 - Point_(const Point_& pt); - Point_(Point_&& pt) CV_NOEXCEPT = default; -#elif OPENCV_ABI_COMPATIBILITY < 500 - Point_(const Point_& pt) = default; - Point_(Point_&& pt) CV_NOEXCEPT = default; -#endif - Point_(const Size_<_Tp>& sz); - Point_(const Vec<_Tp, 2>& v); - -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 - Point_& operator = (const Point_& pt); - Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; -#elif OPENCV_ABI_COMPATIBILITY < 500 - Point_& operator = (const Point_& pt) = default; - Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; -#endif - //! conversion to another data type - template operator Point_<_Tp2>() const; - - //! conversion to the old-style C structures - operator Vec<_Tp, 2>() const; - - //! dot product - _Tp dot(const Point_& pt) const; - //! dot product computed in double-precision arithmetics - double ddot(const Point_& pt) const; - //! cross-product - double cross(const Point_& pt) const; - //! checks whether the point is inside the specified rectangle - bool inside(const Rect_<_Tp>& r) const; - _Tp x; //!< x coordinate of the point - _Tp y; //!< y coordinate of the point -}; - -typedef Point_ Point2i; -typedef Point_ Point2l; -typedef Point_ Point2f; -typedef Point_ Point2d; -typedef Point2i Point; - -template class DataType< Point_<_Tp> > -{ -public: - typedef Point_<_Tp> value_type; - typedef Point_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Point_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Point_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; -} // namespace - - -//////////////////////////////// Point3_ //////////////////////////////// - -/** @brief Template class for 3D points specified by its coordinates `x`, `y` and `z`. - -An instance of the class is interchangeable with the C structure CvPoint2D32f . Similarly to -Point_ , the coordinates of 3D points can be converted to another type. The vector arithmetic and -comparison operations are also supported. - -The following Point3_\<\> aliases are available: -@code - typedef Point3_ Point3i; - typedef Point3_ Point3f; - typedef Point3_ Point3d; -@endcode -@see cv::Point3i, cv::Point3f and cv::Point3d -*/ -template class Point3_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Point3_(); - Point3_(_Tp _x, _Tp _y, _Tp _z); -#if OPENCV_ABI_COMPATIBILITY < 500 - Point3_(const Point3_& pt) = default; - Point3_(Point3_&& pt) CV_NOEXCEPT = default; -#endif - explicit Point3_(const Point_<_Tp>& pt); - Point3_(const Vec<_Tp, 3>& v); - -#if OPENCV_ABI_COMPATIBILITY < 500 - Point3_& operator = (const Point3_& pt) = default; - Point3_& operator = (Point3_&& pt) CV_NOEXCEPT = default; -#endif - //! conversion to another data type - template operator Point3_<_Tp2>() const; - //! conversion to cv::Vec<> - operator Vec<_Tp, 3>() const; - - //! dot product - _Tp dot(const Point3_& pt) const; - //! dot product computed in double-precision arithmetics - double ddot(const Point3_& pt) const; - //! cross product of the 2 3D points - Point3_ cross(const Point3_& pt) const; - _Tp x; //!< x coordinate of the 3D point - _Tp y; //!< y coordinate of the 3D point - _Tp z; //!< z coordinate of the 3D point -}; - -typedef Point3_ Point3i; -typedef Point3_ Point3f; -typedef Point3_ Point3d; - -template class DataType< Point3_<_Tp> > -{ -public: - typedef Point3_<_Tp> value_type; - typedef Point3_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 3, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Point3_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Point3_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 3) }; }; -} // namespace - -//////////////////////////////// Size_ //////////////////////////////// - -/** @brief Template class for specifying the size of an image or rectangle. - -The class includes two members called width and height. The structure can be converted to and from -the old OpenCV structures CvSize and CvSize2D32f . The same set of arithmetic and comparison -operations as for Point_ is available. - -OpenCV defines the following Size_\<\> aliases: -@code - typedef Size_ Size2i; - typedef Size2i Size; - typedef Size_ Size2f; -@endcode -*/ -template class Size_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Size_(); - Size_(_Tp _width, _Tp _height); -#if OPENCV_ABI_COMPATIBILITY < 500 - Size_(const Size_& sz) = default; - Size_(Size_&& sz) CV_NOEXCEPT = default; -#endif - Size_(const Point_<_Tp>& pt); - -#if OPENCV_ABI_COMPATIBILITY < 500 - Size_& operator = (const Size_& sz) = default; - Size_& operator = (Size_&& sz) CV_NOEXCEPT = default; -#endif - //! the area (width*height) - _Tp area() const; - //! aspect ratio (width/height) - double aspectRatio() const; - //! true if empty - bool empty() const; - - //! conversion of another data type. - template operator Size_<_Tp2>() const; - - _Tp width; //!< the width - _Tp height; //!< the height -}; - -typedef Size_ Size2i; -typedef Size_ Size2l; -typedef Size_ Size2f; -typedef Size_ Size2d; -typedef Size2i Size; - -template class DataType< Size_<_Tp> > -{ -public: - typedef Size_<_Tp> value_type; - typedef Size_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = DataType::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Size_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Size_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; -} // namespace - -//////////////////////////////// Rect_ //////////////////////////////// - -/** @brief Template class for 2D rectangles - -described by the following parameters: -- Coordinates of the top-left corner. This is a default interpretation of Rect_::x and Rect_::y - in OpenCV. Though, in your algorithms you may count x and y from the bottom-left corner. -- Rectangle width and height. - -OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the -right and bottom boundaries are not. For example, the method Rect_::contains returns true if - -\f[x \leq pt.x < x+width, - y \leq pt.y < y+height\f] - -Virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_\ ) is -implemented as: -@code - for(int y = roi.y; y < roi.y + roi.height; y++) - for(int x = roi.x; x < roi.x + roi.width; x++) - { - // ... - } -@endcode -In addition to the class members, the following operations on rectangles are implemented: -- \f$\texttt{rect} = \texttt{rect} \pm \texttt{point}\f$ (shifting a rectangle by a certain offset) -- \f$\texttt{rect} = \texttt{rect} \pm \texttt{size}\f$ (expanding or shrinking a rectangle by a - certain amount) -- rect += point, rect -= point, rect += size, rect -= size (augmenting operations) -- rect = rect1 & rect2 (rectangle intersection) -- rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 ) -- rect &= rect1, rect |= rect1 (and the corresponding augmenting operations) -- rect == rect1, rect != rect1 (rectangle comparison) - -This is an example how the partial ordering on rectangles can be established (rect1 \f$\subseteq\f$ -rect2): -@code - template inline bool - operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2) - { - return (r1 & r2) == r1; - } -@endcode -For your convenience, the Rect_\<\> alias is available: cv::Rect -*/ -template class Rect_ -{ -public: - typedef _Tp value_type; - - //! default constructor - Rect_(); - Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); -#if OPENCV_ABI_COMPATIBILITY < 500 - Rect_(const Rect_& r) = default; - Rect_(Rect_&& r) CV_NOEXCEPT = default; -#endif - Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); - Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); - -#if OPENCV_ABI_COMPATIBILITY < 500 - Rect_& operator = (const Rect_& r) = default; - Rect_& operator = (Rect_&& r) CV_NOEXCEPT = default; -#endif - //! the top-left corner - Point_<_Tp> tl() const; - //! the bottom-right corner - Point_<_Tp> br() const; - - //! size (width, height) of the rectangle - Size_<_Tp> size() const; - //! area (width*height) of the rectangle - _Tp area() const; - //! true if empty - bool empty() const; - - //! conversion to another data type - template operator Rect_<_Tp2>() const; - - //! checks whether the rectangle contains the point - /*! @warning After OpenCV 4.11.0, when calling Rect.contains() with cv::Point2f / cv::Point2d point, point should not convert/round to int. - * ``` - * Rect_ r(0,0,500,500); Point_ pt(250.0f, 499.9f); - * r.contains(pt) returns false.(OpenCV 4.10.0 or before) - * r.contains(pt) returns true. (OpenCV 4.11.0 or later) - * ``` - */ - template inline bool contains(const Point_<_Tp2>& pt) const; - - _Tp x; //!< x coordinate of the top-left corner - _Tp y; //!< y coordinate of the top-left corner - _Tp width; //!< width of the rectangle - _Tp height; //!< height of the rectangle -}; - -typedef Rect_ Rect2i; -typedef Rect_ Rect2f; -typedef Rect_ Rect2d; -typedef Rect2i Rect; - -template class DataType< Rect_<_Tp> > -{ -public: - typedef Rect_<_Tp> value_type; - typedef Rect_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 4, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Rect_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Rect_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; -} // namespace - -///////////////////////////// RotatedRect ///////////////////////////// - -/** @brief The class represents rotated (i.e. not up-right) rectangles on a plane. - -Each rectangle is specified by the center point (mass center), length of each side (represented by -#Size2f structure) and the rotation angle in degrees. - -The sample below demonstrates how to use RotatedRect: -@snippet snippets/core_various.cpp RotatedRect_demo -![image](pics/rotatedrect.png) - -@sa CamShift, fitEllipse, minAreaRect, CvBox2D -*/ -class CV_EXPORTS_W_SIMPLE RotatedRect -{ -public: - //! default constructor - CV_WRAP RotatedRect(); - /** full constructor - @param center The rectangle mass center. - @param size Width and height of the rectangle. - @param angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., - the rectangle becomes an up-right rectangle. - */ - CV_WRAP RotatedRect(const Point2f& center, const Size2f& size, float angle); - /** - Any 3 end points of the RotatedRect. They must be given in order (either clockwise or - anticlockwise). - */ - CV_WRAP RotatedRect(const Point2f& point1, const Point2f& point2, const Point2f& point3); - - /** returns 4 vertices of the rotated rectangle - @param pts The points array for storing rectangle vertices. The order is _bottomLeft_, _topLeft_, topRight, bottomRight. - @note _Bottom_, _Top_, _Left_ and _Right_ sides refer to the original rectangle (angle is 0), - so after 180 degree rotation _bottomLeft_ point will be located at the top right corner of the - rectangle. - */ - void points(Point2f pts[]) const; - - CV_WRAP void points(CV_OUT std::vector& pts) const; - - //! returns the minimal up-right integer rectangle containing the rotated rectangle - CV_WRAP Rect boundingRect() const; - //! returns the minimal (exact) floating point rectangle containing the rotated rectangle, not intended for use with images - CV_WRAP Rect2f boundingRect2f() const; - //! returns the rectangle mass center - CV_PROP_RW Point2f center; - //! returns width and height of the rectangle - CV_PROP_RW Size2f size; - //! returns the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. - CV_PROP_RW float angle; -}; - -template<> class DataType< RotatedRect > -{ -public: - typedef RotatedRect value_type; - typedef value_type work_type; - typedef float channel_type; - - enum { generic_type = 0, - channels = (int)sizeof(value_type)/sizeof(channel_type), // 5 - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template<> -struct Depth< RotatedRect > { enum { value = Depth::value }; }; -template<> -struct Type< RotatedRect > { enum { value = CV_MAKETYPE(Depth::value, (int)sizeof(RotatedRect)/sizeof(float)) }; }; -} // namespace - - -//////////////////////////////// Range ///////////////////////////////// - -/** @brief Template class specifying a continuous subsequence (slice) of a sequence. - -The class is used to specify a row or a column span in a matrix ( Mat ) and for many other purposes. -Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is an -inclusive left boundary of the range and end is an exclusive right boundary of the range. Such a -half-opened interval is usually denoted as \f$[start,end)\f$ . - -The static method Range::all() returns a special variable that means "the whole sequence" or "the -whole range", just like " : " in Matlab or " ... " in Python. All the methods and functions in -OpenCV that take Range support this special Range::all() value. But, of course, in case of your own -custom processing, you will probably have to check and handle it explicitly: -@code - void my_function(..., const Range& r, ....) - { - if(r == Range::all()) { - // process all the data - } - else { - // process [r.start, r.end) - } - } -@endcode -*/ -class CV_EXPORTS Range -{ -public: - Range(); - Range(int _start, int _end); - int size() const; - bool empty() const; - static Range all(); - - int start, end; -}; - -template<> class DataType -{ -public: - typedef Range value_type; - typedef value_type work_type; - typedef int channel_type; - - enum { generic_type = 0, - channels = 2, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template<> -struct Depth< Range > { enum { value = Depth::value }; }; -template<> -struct Type< Range > { enum { value = CV_MAKETYPE(Depth::value, 2) }; }; -} // namespace - - -//////////////////////////////// Scalar_ /////////////////////////////// - -/** @brief Template class for a 4-element vector derived from Vec. - -Being derived from Vec\<_Tp, 4\> , Scalar\_ and Scalar can be used just as typical 4-element -vectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in -OpenCV to pass pixel values. -*/ -template class Scalar_ : public Vec<_Tp, 4> -{ -public: - //! default constructor - Scalar_(); - Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); - Scalar_(_Tp v0); - - Scalar_(const Scalar_& s); - Scalar_(Scalar_&& s) CV_NOEXCEPT; - - Scalar_& operator=(const Scalar_& s); - Scalar_& operator=(Scalar_&& s) CV_NOEXCEPT; - - template - Scalar_(const Vec<_Tp2, cn>& v); - - //! returns a scalar with all elements set to v0 - static Scalar_<_Tp> all(_Tp v0); - - //! conversion to another data type - template operator Scalar_() const; - - //! per-element product - Scalar_<_Tp> mul(const Scalar_<_Tp>& a, double scale=1 ) const; - - //! returns (v0, -v1, -v2, -v3) - Scalar_<_Tp> conj() const; - - //! returns true iff v1 == v2 == v3 == 0 - bool isReal() const; -}; - -typedef Scalar_ Scalar; - -template class DataType< Scalar_<_Tp> > -{ -public: - typedef Scalar_<_Tp> value_type; - typedef Scalar_::work_type> work_type; - typedef _Tp channel_type; - - enum { generic_type = 0, - channels = 4, - fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template -struct Depth< Scalar_<_Tp> > { enum { value = Depth<_Tp>::value }; }; -template -struct Type< Scalar_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; -} // namespace - - -/////////////////////////////// KeyPoint //////////////////////////////// - -/** @brief Data structure for salient point detectors. - -The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint -detectors, such as Harris corner detector, #FAST, %StarDetector, %SURF, %SIFT etc. - -The keypoint is characterized by the 2D position, scale (proportional to the diameter of the -neighborhood that needs to be taken into account), orientation and some other parameters. The -keypoint neighborhood is then analyzed by another algorithm that builds a descriptor (usually -represented as a feature vector). The keypoints representing the same object in different images -can then be matched using %KDTree or another method. -*/ -class CV_EXPORTS_W_SIMPLE KeyPoint -{ -public: - //! the default constructor - CV_WRAP KeyPoint(); - /** - @param pt x & y coordinates of the keypoint - @param size keypoint diameter - @param angle keypoint orientation - @param response keypoint detector response on the keypoint (that is, strength of the keypoint) - @param octave pyramid octave in which the keypoint has been detected - @param class_id object id - */ - KeyPoint(Point2f pt, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); - /** - @param x x-coordinate of the keypoint - @param y y-coordinate of the keypoint - @param size keypoint diameter - @param angle keypoint orientation - @param response keypoint detector response on the keypoint (that is, strength of the keypoint) - @param octave pyramid octave in which the keypoint has been detected - @param class_id object id - */ - CV_WRAP KeyPoint(float x, float y, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); - - size_t hash() const; - - /** - This method converts vector of keypoints to vector of points or the reverse, where each keypoint is - assigned the same size and the same orientation. - - @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB - @param points2f Array of (x,y) coordinates of each keypoint - @param keypointIndexes Array of indexes of keypoints to be converted to points. (Acts like a mask to - convert only specified keypoints) - */ - CV_WRAP static void convert(const std::vector& keypoints, - CV_OUT std::vector& points2f, - const std::vector& keypointIndexes=std::vector()); - /** @overload - @param points2f Array of (x,y) coordinates of each keypoint - @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB - @param size keypoint diameter - @param response keypoint detector response on the keypoint (that is, strength of the keypoint) - @param octave pyramid octave in which the keypoint has been detected - @param class_id object id - */ - CV_WRAP static void convert(const std::vector& points2f, - CV_OUT std::vector& keypoints, - float size=1, float response=1, int octave=0, int class_id=-1); - - /** - This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint - regions' intersection and area of keypoint regions' union (considering keypoint region as circle). - If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. - @param kp1 First keypoint - @param kp2 Second keypoint - */ - CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); - - CV_PROP_RW Point2f pt; //!< coordinates of the keypoints - CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood - CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); - //!< it's in [0,360) degrees and measured relative to - //!< image coordinate system, ie in clockwise. - CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling - CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted - CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) -}; - -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED -template<> class DataType -{ -public: - typedef KeyPoint value_type; - typedef float work_type; - typedef float channel_type; - - enum { generic_type = 0, - depth = DataType::depth, - channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 7 - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) - }; - - typedef Vec vec_type; -}; -#endif - - -//////////////////////////////// DMatch ///////////////////////////////// - -/** @brief Class for matching keypoint descriptors - -query descriptor index, train descriptor index, train image index, and distance between -descriptors. -*/ -class CV_EXPORTS_W_SIMPLE DMatch -{ -public: - CV_WRAP DMatch(); - CV_WRAP DMatch(int _queryIdx, int _trainIdx, float _distance); - CV_WRAP DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance); - - CV_PROP_RW int queryIdx; //!< query descriptor index - CV_PROP_RW int trainIdx; //!< train descriptor index - CV_PROP_RW int imgIdx; //!< train image index - - CV_PROP_RW float distance; - - // less is better - bool operator<(const DMatch &m) const; -}; - -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED -template<> class DataType -{ -public: - typedef DMatch value_type; - typedef int work_type; - typedef int channel_type; - - enum { generic_type = 0, - depth = DataType::depth, - channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 4 - fmt = DataType::fmt + ((channels - 1) << 8), - type = CV_MAKETYPE(depth, channels) - }; - - typedef Vec vec_type; -}; -#endif - - -///////////////////////////// TermCriteria ////////////////////////////// - -/** @brief The class defining termination criteria for iterative algorithms. - -You can initialize it by default constructor and then override any parameters, or the structure may -be fully initialized using the advanced variant of the constructor. -*/ -class CV_EXPORTS TermCriteria -{ -public: - /** - Criteria type, can be one of: COUNT, EPS or COUNT + EPS - */ - enum Type - { - COUNT=1, //!< the maximum number of iterations or elements to compute - MAX_ITER=COUNT, //!< ditto - EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops - }; - - //! default constructor - TermCriteria(); - /** - @param type The type of termination criteria, one of TermCriteria::Type - @param maxCount The maximum number of iterations or elements to compute. - @param epsilon The desired accuracy or change in parameters at which the iterative algorithm stops. - */ - TermCriteria(int type, int maxCount, double epsilon); - - inline bool isValid() const - { - const bool isCount = (type & COUNT) && maxCount > 0; - const bool isEps = (type & EPS) && !cvIsNaN(epsilon); - return isCount || isEps; - } - - int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS - int maxCount; //!< the maximum number of iterations/elements - double epsilon; //!< the desired accuracy -}; - - -//! @} core_basic - -///////////////////////// raster image moments ////////////////////////// - -//! @addtogroup imgproc_shape -//! @{ - -/** @brief struct returned by cv::moments - -The spatial moments \f$\texttt{Moments::m}_{ji}\f$ are computed as: - -\f[\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )\f] - -The central moments \f$\texttt{Moments::mu}_{ji}\f$ are computed as: - -\f[\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )\f] - -where \f$(\bar{x}, \bar{y})\f$ is the mass center: - -\f[\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}\f] - -The normalized central moments \f$\texttt{Moments::nu}_{ij}\f$ are computed as: - -\f[\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .\f] - -@note -\f$\texttt{mu}_{00}=\texttt{m}_{00}\f$, \f$\texttt{nu}_{00}=1\f$ -\f$\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0\f$ , hence the values are not -stored. - -The moments of a contour are defined in the same way but computed using the Green's formula (see -). So, due to a limited raster resolution, the moments -computed for a contour are slightly different from the moments computed for the same rasterized -contour. - -@note -Since the contour moments are computed using Green formula, you may get seemingly odd results for -contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours. - */ -class CV_EXPORTS_W_MAP Moments -{ -public: - //! the default constructor - Moments(); - //! the full constructor - Moments(double m00, double m10, double m01, double m20, double m11, - double m02, double m30, double m21, double m12, double m03 ); - ////! the conversion from CvMoments - //Moments( const CvMoments& moments ); - ////! the conversion to CvMoments - //operator CvMoments() const; - - //! @name spatial moments - //! @{ - CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; - //! @} - - //! @name central moments - //! @{ - CV_PROP_RW double mu20, mu11, mu02, mu30, mu21, mu12, mu03; - //! @} - - //! @name central normalized moments - //! @{ - CV_PROP_RW double nu20, nu11, nu02, nu30, nu21, nu12, nu03; - //! @} -}; - -template<> class DataType -{ -public: - typedef Moments value_type; - typedef double work_type; - typedef double channel_type; - - enum { generic_type = 0, - channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 24 - fmt = DataType::fmt + ((channels - 1) << 8) -#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED - ,depth = DataType::depth - ,type = CV_MAKETYPE(depth, channels) -#endif - }; - - typedef Vec vec_type; -}; - -namespace traits { -template<> -struct Depth< Moments > { enum { value = Depth::value }; }; -template<> -struct Type< Moments > { enum { value = CV_MAKETYPE(Depth::value, (int)(sizeof(Moments)/sizeof(double))) }; }; -} // namespace - -//! @} imgproc_shape - -//! @cond IGNORED - -///////////////////////////////////////////////////////////////////////// -///////////////////////////// Implementation //////////////////////////// -///////////////////////////////////////////////////////////////////////// - -//////////////////////////////// Complex //////////////////////////////// - -template inline -Complex<_Tp>::Complex() - : re(0), im(0) {} - -template inline -Complex<_Tp>::Complex( _Tp _re, _Tp _im ) - : re(_re), im(_im) {} - -template template inline -Complex<_Tp>::operator Complex() const -{ - return Complex(saturate_cast(re), saturate_cast(im)); -} - -template inline -Complex<_Tp> Complex<_Tp>::conj() const -{ - return Complex<_Tp>(re, -im); -} - - -template static inline -bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return a.re == b.re && a.im == b.im; -} - -template static inline -bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return a.re != b.re || a.im != b.im; -} - -template static inline -Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return Complex<_Tp>( a.re + b.re, a.im + b.im ); -} - -template static inline -Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - a.re += b.re; a.im += b.im; - return a; -} - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return Complex<_Tp>( a.re - b.re, a.im - b.im ); -} - -template static inline -Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - a.re -= b.re; a.im -= b.im; - return a; -} - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a) -{ - return Complex<_Tp>(-a.re, -a.im); -} - -template static inline -Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); -} - -template static inline -Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) -{ - return Complex<_Tp>( a.re*b, a.im*b ); -} - -template static inline -Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>( a.re*b, a.im*b ); -} - -template static inline -Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) -{ - return Complex<_Tp>( a.re + b, a.im ); -} - -template static inline -Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) -{ return Complex<_Tp>( a.re - b, a.im ); } - -template static inline -Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>( a.re + b, a.im ); -} - -template static inline -Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>( b - a.re, -a.im ); -} - -template static inline -Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) -{ - a.re += b; return a; -} - -template static inline -Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) -{ - a.re -= b; return a; -} - -template static inline -Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) -{ - a.re *= b; a.im *= b; return a; -} - -template static inline -double abs(const Complex<_Tp>& a) -{ - return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); -} - -template static inline -Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) -{ - double t = 1./((double)b.re*b.re + (double)b.im*b.im); - return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), - (_Tp)((-a.re*b.im + a.im*b.re)*t) ); -} - -template static inline -Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) -{ - a = a / b; - return a; -} - -template static inline -Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) -{ - _Tp t = (_Tp)1/b; - return Complex<_Tp>( a.re*t, a.im*t ); -} - -template static inline -Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) -{ - return Complex<_Tp>(b)/a; -} - -template static inline -Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) -{ - _Tp t = (_Tp)1/b; - a.re *= t; a.im *= t; return a; -} - - - -//////////////////////////////// 2D Point /////////////////////////////// - -template inline -Point_<_Tp>::Point_() - : x(0), y(0) {} - -template inline -Point_<_Tp>::Point_(_Tp _x, _Tp _y) - : x(_x), y(_y) {} - -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 -template inline -Point_<_Tp>::Point_(const Point_& pt) - : x(pt.x), y(pt.y) {} -#endif - -template inline -Point_<_Tp>::Point_(const Size_<_Tp>& sz) - : x(sz.width), y(sz.height) {} - -template inline -Point_<_Tp>::Point_(const Vec<_Tp,2>& v) - : x(v[0]), y(v[1]) {} - -#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 -template inline -Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) -{ - x = pt.x; y = pt.y; - return *this; -} -#endif - -template template inline -Point_<_Tp>::operator Point_<_Tp2>() const -{ - return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); -} - -template inline -Point_<_Tp>::operator Vec<_Tp, 2>() const -{ - return Vec<_Tp, 2>(x, y); -} - -template inline -_Tp Point_<_Tp>::dot(const Point_& pt) const -{ - return saturate_cast<_Tp>(x*pt.x + y*pt.y); -} - -template inline -double Point_<_Tp>::ddot(const Point_& pt) const -{ - return (double)x*(double)(pt.x) + (double)y*(double)(pt.y); -} - -template inline -double Point_<_Tp>::cross(const Point_& pt) const -{ - return (double)x*pt.y - (double)y*pt.x; -} - -template inline bool -Point_<_Tp>::inside( const Rect_<_Tp>& r ) const -{ - return r.contains(*this); -} - - -template static inline -Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) -{ - a.x += b.x; - a.y += b.y; - return a; -} - -template static inline -Point_<_Tp>& operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) -{ - a.x -= b.x; - a.y -= b.y; - return a; -} - -template static inline -Point_<_Tp>& operator *= (Point_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - return a; -} - -template static inline -Point_<_Tp>& operator *= (Point_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - return a; -} - -template static inline -Point_<_Tp>& operator *= (Point_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - return a; -} - -template static inline -Point_<_Tp>& operator /= (Point_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - return a; -} - -template static inline -Point_<_Tp>& operator /= (Point_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - return a; -} - -template static inline -Point_<_Tp>& operator /= (Point_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - return a; -} - -template static inline -double norm(const Point_<_Tp>& pt) -{ - return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); -} - -template static inline -bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y; -} - -template static inline -bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y; -} - -template static inline -Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); -} - -template static inline -Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); -} - -template static inline -Point_<_Tp> operator - (const Point_<_Tp>& a) -{ - return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); -} - -template static inline -Point_<_Tp> operator * (const Point_<_Tp>& a, int b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); -} - -template static inline -Point_<_Tp> operator * (int a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); -} - -template static inline -Point_<_Tp> operator * (const Point_<_Tp>& a, float b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); -} - -template static inline -Point_<_Tp> operator * (float a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); -} - -template static inline -Point_<_Tp> operator * (const Point_<_Tp>& a, double b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); -} - -template static inline -Point_<_Tp> operator * (double a, const Point_<_Tp>& b) -{ - return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); -} - -template static inline -Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) -{ - Matx<_Tp, 2, 1> tmp = a * Vec<_Tp,2>(b.x, b.y); - return Point_<_Tp>(tmp.val[0], tmp.val[1]); -} - -template static inline -Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) -{ - Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, 1); - return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} - -template static inline -Point_<_Tp> operator / (const Point_<_Tp>& a, int b) -{ - Point_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point_<_Tp> operator / (const Point_<_Tp>& a, float b) -{ - Point_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point_<_Tp> operator / (const Point_<_Tp>& a, double b) -{ - Point_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - - -template static inline _AccTp normL2Sqr(const Point_& pt); -template static inline _AccTp normL2Sqr(const Point_& pt); -template static inline _AccTp normL2Sqr(const Point_& pt); -template static inline _AccTp normL2Sqr(const Point_& pt); - -template<> inline int normL2Sqr(const Point_& pt) { return pt.dot(pt); } -template<> inline int64 normL2Sqr(const Point_& pt) { return pt.dot(pt); } -template<> inline float normL2Sqr(const Point_& pt) { return pt.dot(pt); } -template<> inline double normL2Sqr(const Point_& pt) { return pt.dot(pt); } - -template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } -template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } - - - -//////////////////////////////// 3D Point /////////////////////////////// - -template inline -Point3_<_Tp>::Point3_() - : x(0), y(0), z(0) {} - -template inline -Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) - : x(_x), y(_y), z(_z) {} - -template inline -Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) - : x(pt.x), y(pt.y), z(_Tp()) {} - -template inline -Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) - : x(v[0]), y(v[1]), z(v[2]) {} - -template template inline -Point3_<_Tp>::operator Point3_<_Tp2>() const -{ - return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); -} - -template inline -Point3_<_Tp>::operator Vec<_Tp, 3>() const -{ - return Vec<_Tp, 3>(x, y, z); -} - -template inline -_Tp Point3_<_Tp>::dot(const Point3_& pt) const -{ - return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); -} - -template inline -double Point3_<_Tp>::ddot(const Point3_& pt) const -{ - return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; -} - -template inline -Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const -{ - return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); -} - - -template static inline -Point3_<_Tp>& operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - a.x += b.x; - a.y += b.y; - a.z += b.z; - return a; -} - -template static inline -Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - a.x -= b.x; - a.y -= b.y; - a.z -= b.z; - return a; -} - -template static inline -Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - a.z = saturate_cast<_Tp>(a.z * b); - return a; -} - -template static inline -Point3_<_Tp>& operator *= (Point3_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - a.z = saturate_cast<_Tp>(a.z * b); - return a; -} - -template static inline -Point3_<_Tp>& operator *= (Point3_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x * b); - a.y = saturate_cast<_Tp>(a.y * b); - a.z = saturate_cast<_Tp>(a.z * b); - return a; -} - -template static inline -Point3_<_Tp>& operator /= (Point3_<_Tp>& a, int b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - a.z = saturate_cast<_Tp>(a.z / b); - return a; -} - -template static inline -Point3_<_Tp>& operator /= (Point3_<_Tp>& a, float b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - a.z = saturate_cast<_Tp>(a.z / b); - return a; -} - -template static inline -Point3_<_Tp>& operator /= (Point3_<_Tp>& a, double b) -{ - a.x = saturate_cast<_Tp>(a.x / b); - a.y = saturate_cast<_Tp>(a.y / b); - a.z = saturate_cast<_Tp>(a.z / b); - return a; -} - -template static inline -double norm(const Point3_<_Tp>& pt) -{ - return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); -} - -template static inline -bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y && a.z == b.z; -} - -template static inline -bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y || a.z != b.z; -} - -template static inline -Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), saturate_cast<_Tp>(a.z + b.z)); -} - -template static inline -Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y), saturate_cast<_Tp>(a.z - b.z)); -} - -template static inline -Point3_<_Tp> operator - (const Point3_<_Tp>& a) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y), saturate_cast<_Tp>(-a.z) ); -} - -template static inline -Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b), saturate_cast<_Tp>(a.z*b) ); -} - -template static inline -Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); -} - -template static inline -Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); -} - -template static inline -Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); -} - -template static inline -Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); -} - -template static inline -Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) -{ - return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); -} - -template static inline -Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) -{ - Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, b.z); - return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); -} - -template static inline -Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) -{ - return a * Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); -} - -template static inline -Point3_<_Tp> operator / (const Point3_<_Tp>& a, int b) -{ - Point3_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point3_<_Tp> operator / (const Point3_<_Tp>& a, float b) -{ - Point3_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Point3_<_Tp> operator / (const Point3_<_Tp>& a, double b) -{ - Point3_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - - - -////////////////////////////////// Size ///////////////////////////////// - -template inline -Size_<_Tp>::Size_() - : width(0), height(0) {} - -template inline -Size_<_Tp>::Size_(_Tp _width, _Tp _height) - : width(_width), height(_height) {} - -template inline -Size_<_Tp>::Size_(const Point_<_Tp>& pt) - : width(pt.x), height(pt.y) {} - -template template inline -Size_<_Tp>::operator Size_<_Tp2>() const -{ - return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); -} - -template inline -_Tp Size_<_Tp>::area() const -{ - const _Tp result = width * height; - CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer - || width == 0 || result / width == height); // make sure the result fits in the return value - return result; -} - -template inline -double Size_<_Tp>::aspectRatio() const -{ - return width / static_cast(height); -} - -template inline -bool Size_<_Tp>::empty() const -{ - return width <= 0 || height <= 0; -} - - -template static inline -Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b) -{ - a.width *= b; - a.height *= b; - return a; -} - -template static inline -Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) -{ - Size_<_Tp> tmp(a); - tmp *= b; - return tmp; -} - -template static inline -Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b) -{ - a.width /= b; - a.height /= b; - return a; -} - -template static inline -Size_<_Tp> operator / (const Size_<_Tp>& a, _Tp b) -{ - Size_<_Tp> tmp(a); - tmp /= b; - return tmp; -} - -template static inline -Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) -{ - a.width += b.width; - a.height += b.height; - return a; -} - -template static inline -Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - Size_<_Tp> tmp(a); - tmp += b; - return tmp; -} - -template static inline -Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) -{ - a.width -= b.width; - a.height -= b.height; - return a; -} - -template static inline -Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - Size_<_Tp> tmp(a); - tmp -= b; - return tmp; -} - -template static inline -bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - return a.width == b.width && a.height == b.height; -} - -template static inline -bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) -{ - return !(a == b); -} - - - -////////////////////////////////// Rect ///////////////////////////////// - -template inline -Rect_<_Tp>::Rect_() - : x(0), y(0), width(0), height(0) {} - -template inline -Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) - : x(_x), y(_y), width(_width), height(_height) {} - -template inline -Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) - : x(org.x), y(org.y), width(sz.width), height(sz.height) {} - -template inline -Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) -{ - x = std::min(pt1.x, pt2.x); - y = std::min(pt1.y, pt2.y); - width = std::max(pt1.x, pt2.x) - x; - height = std::max(pt1.y, pt2.y) - y; -} - -template inline -Point_<_Tp> Rect_<_Tp>::tl() const -{ - return Point_<_Tp>(x,y); -} - -template inline -Point_<_Tp> Rect_<_Tp>::br() const -{ - return Point_<_Tp>(x + width, y + height); -} - -template inline -Size_<_Tp> Rect_<_Tp>::size() const -{ - return Size_<_Tp>(width, height); -} - -template inline -_Tp Rect_<_Tp>::area() const -{ - const _Tp result = width * height; - if constexpr (std::numeric_limits<_Tp>::is_integer) - { - CV_DbgAssert(width == 0 || result / width == height); // make sure the result fits in the return value - } - return result; -} - -template inline -bool Rect_<_Tp>::empty() const -{ - return width <= 0 || height <= 0; -} - -template template inline -Rect_<_Tp>::operator Rect_<_Tp2>() const -{ - return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); -} - -template template inline -bool Rect_<_Tp>::contains(const Point_<_Tp2>& pt) const -{ - return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; -} -// See https://github.com/opencv/opencv/issues/26016 -template<> template<> inline -bool Rect_::contains(const Point_& pt) const -{ - // std::numeric_limits::digits is 31. - // std::numeric_limits::digits is 53. - // So conversion int->double does not lead to accuracy errors. - const Rect_ _rect(static_cast(x), static_cast(y), static_cast(width), static_cast(height)); - return _rect.contains(pt); -} -template<> template<> inline -bool Rect_::contains(const Point_& _pt) const -{ - // std::numeric_limits::digits is 24. - // std::numeric_limits::digits is 53. - // So conversion float->double does not lead to accuracy errors. - return contains(Point_(static_cast(_pt.x), static_cast(_pt.y))); -} - -template static inline -Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) -{ - a.x += b.x; - a.y += b.y; - return a; -} - -template static inline -Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) -{ - a.x -= b.x; - a.y -= b.y; - return a; -} - -template static inline -Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) -{ - a.width += b.width; - a.height += b.height; - return a; -} - -template static inline -Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) -{ - const _Tp width = a.width - b.width; - const _Tp height = a.height - b.height; - CV_DbgAssert(width >= 0 && height >= 0); - a.width = width; - a.height = height; - return a; -} - -template static inline -Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) -{ - if (a.empty() || b.empty()) { - a = Rect(); - return a; - } - const Rect_<_Tp>& Rx_min = (a.x < b.x) ? a : b; - const Rect_<_Tp>& Rx_max = (a.x < b.x) ? b : a; - const Rect_<_Tp>& Ry_min = (a.y < b.y) ? a : b; - const Rect_<_Tp>& Ry_max = (a.y < b.y) ? b : a; - // Looking at the formula below, we will compute Rx_min.width - (Rx_max.x - Rx_min.x) - // but we want to avoid overflows. Rx_min.width >= 0 and (Rx_max.x - Rx_min.x) >= 0 - // by definition so the difference does not overflow. The only thing that can overflow - // is (Rx_max.x - Rx_min.x). And it can only overflow if Rx_min.x < 0. - // Let us first deal with the following case. - if ((Rx_min.x < 0 && Rx_min.x + Rx_min.width < Rx_max.x) || - (Ry_min.y < 0 && Ry_min.y + Ry_min.height < Ry_max.y)) { - a = Rect(); - return a; - } - // We now know that either Rx_min.x >= 0, or - // Rx_min.x < 0 && Rx_min.x + Rx_min.width >= Rx_max.x and therefore - // Rx_min.width >= (Rx_max.x - Rx_min.x) which means (Rx_max.x - Rx_min.x) - // is inferior to a valid int and therefore does not overflow. - a.width = std::min(Rx_min.width - (Rx_max.x - Rx_min.x), Rx_max.width); - a.height = std::min(Ry_min.height - (Ry_max.y - Ry_min.y), Ry_max.height); - a.x = Rx_max.x; - a.y = Ry_max.y; - if (a.empty()) - a = Rect(); - return a; -} - -template static inline -Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) -{ - if (a.empty()) { - a = b; - } - else if (!b.empty()) { - _Tp x1 = std::min(a.x, b.x); - _Tp y1 = std::min(a.y, b.y); - a.width = std::max(a.x + a.width, b.x + b.width) - x1; - a.height = std::max(a.y + a.height, b.y + b.height) - y1; - a.x = x1; - a.y = y1; - } - return a; -} - -template static inline -bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; -} - -template static inline -bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; -} - -template static inline -Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) -{ - return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); -} - -template static inline -Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) -{ - return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); -} - -template static inline -Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) -{ - return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); -} - -template static inline -Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Size_<_Tp>& b) -{ - const _Tp width = a.width - b.width; - const _Tp height = a.height - b.height; - CV_DbgAssert(width >= 0 && height >= 0); - return Rect_<_Tp>( a.x, a.y, width, height ); -} - -template static inline -Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - Rect_<_Tp> c = a; - return c &= b; -} - -template static inline -Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) -{ - Rect_<_Tp> c = a; - return c |= b; -} - -/** - * @brief measure dissimilarity between two sample sets - * - * computes the complement of the Jaccard Index as described in . - * For rectangles this reduces to computing the intersection over the union. - */ -template static inline -double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) { - _Tp Aa = a.area(); - _Tp Ab = b.area(); - - if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) { - // jaccard_index = 1 -> distance = 0 - return 0.0; - } - - double Aab = (a & b).area(); - // distance = 1 - jaccard_index - return 1.0 - Aab / (Aa + Ab - Aab); -} - -/** @brief Finds out if there is any intersection between two rectangles - * - * mainly useful for language bindings - * @param a First rectangle - * @param b Second rectangle - * @return the area of the intersection - */ -CV_EXPORTS_W inline double rectangleIntersectionArea(const Rect2d& a, const Rect2d& b) { return (a & b).area(); } - -////////////////////////////// RotatedRect ////////////////////////////// - -inline -RotatedRect::RotatedRect() - : center(), size(), angle(0) {} - -inline -RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) - : center(_center), size(_size), angle(_angle) {} - -///////////////////////////////// Range ///////////////////////////////// - -inline -Range::Range() - : start(0), end(0) {} - -inline -Range::Range(int _start, int _end) - : start(_start), end(_end) {} - -inline -int Range::size() const -{ - return end - start; -} - -inline -bool Range::empty() const -{ - return start == end; -} - -inline -Range Range::all() -{ - return Range(INT_MIN, INT_MAX); -} - - -static inline -bool operator == (const Range& r1, const Range& r2) -{ - return r1.start == r2.start && r1.end == r2.end; -} - -static inline -bool operator != (const Range& r1, const Range& r2) -{ - return !(r1 == r2); -} - -static inline -bool operator !(const Range& r) -{ - return r.start == r.end; -} - -static inline -Range operator & (const Range& r1, const Range& r2) -{ - Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); - r.end = std::max(r.end, r.start); - return r; -} - -static inline -Range& operator &= (Range& r1, const Range& r2) -{ - r1 = r1 & r2; - return r1; -} - -static inline -Range operator + (const Range& r1, int delta) -{ - return Range(r1.start + delta, r1.end + delta); -} - -static inline -Range operator + (int delta, const Range& r1) -{ - return Range(r1.start + delta, r1.end + delta); -} - -static inline -Range operator - (const Range& r1, int delta) -{ - return r1 + (-delta); -} - - - -///////////////////////////////// Scalar //////////////////////////////// - -template inline -Scalar_<_Tp>::Scalar_() -{ - this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; -} - -template inline -Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) -{ - this->val[0] = v0; - this->val[1] = v1; - this->val[2] = v2; - this->val[3] = v3; -} - -template inline -Scalar_<_Tp>::Scalar_(const Scalar_<_Tp>& s) : Vec<_Tp, 4>(s) { -} - -template inline -Scalar_<_Tp>::Scalar_(Scalar_<_Tp>&& s) CV_NOEXCEPT { - this->val[0] = std::move(s.val[0]); - this->val[1] = std::move(s.val[1]); - this->val[2] = std::move(s.val[2]); - this->val[3] = std::move(s.val[3]); -} - -template inline -Scalar_<_Tp>& Scalar_<_Tp>::operator=(const Scalar_<_Tp>& s) { - this->val[0] = s.val[0]; - this->val[1] = s.val[1]; - this->val[2] = s.val[2]; - this->val[3] = s.val[3]; - return *this; -} - -template inline -Scalar_<_Tp>& Scalar_<_Tp>::operator=(Scalar_<_Tp>&& s) CV_NOEXCEPT { - this->val[0] = std::move(s.val[0]); - this->val[1] = std::move(s.val[1]); - this->val[2] = std::move(s.val[2]); - this->val[3] = std::move(s.val[3]); - return *this; -} - -template template inline -Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v) -{ - int i; - for( i = 0; i < (cn < 4 ? cn : 4); i++ ) - this->val[i] = cv::saturate_cast<_Tp>(v.val[i]); - for( ; i < 4; i++ ) - this->val[i] = 0; -} - -template inline -Scalar_<_Tp>::Scalar_(_Tp v0) -{ - this->val[0] = v0; - this->val[1] = this->val[2] = this->val[3] = 0; -} - -template inline -Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) -{ - return Scalar_<_Tp>(v0, v0, v0, v0); -} - - -template inline -Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& a, double scale ) const -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0] * a.val[0] * scale), - saturate_cast<_Tp>(this->val[1] * a.val[1] * scale), - saturate_cast<_Tp>(this->val[2] * a.val[2] * scale), - saturate_cast<_Tp>(this->val[3] * a.val[3] * scale)); -} - -template inline -Scalar_<_Tp> Scalar_<_Tp>::conj() const -{ - return Scalar_<_Tp>(saturate_cast<_Tp>( this->val[0]), - saturate_cast<_Tp>(-this->val[1]), - saturate_cast<_Tp>(-this->val[2]), - saturate_cast<_Tp>(-this->val[3])); -} - -template inline -bool Scalar_<_Tp>::isReal() const -{ - return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; -} - - -template template inline -Scalar_<_Tp>::operator Scalar_() const -{ - return Scalar_(saturate_cast(this->val[0]), - saturate_cast(this->val[1]), - saturate_cast(this->val[2]), - saturate_cast(this->val[3])); -} - - -template static inline -Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a.val[0] += b.val[0]; - a.val[1] += b.val[1]; - a.val[2] += b.val[2]; - a.val[3] += b.val[3]; - return a; -} - -template static inline -Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a.val[0] -= b.val[0]; - a.val[1] -= b.val[1]; - a.val[2] -= b.val[2]; - a.val[3] -= b.val[3]; - return a; -} - -template static inline -Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) -{ - a.val[0] *= v; - a.val[1] *= v; - a.val[2] *= v; - a.val[3] *= v; - return a; -} - -template static inline -bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) -{ - return a.val[0] == b.val[0] && a.val[1] == b.val[1] && - a.val[2] == b.val[2] && a.val[3] == b.val[3]; -} - -template static inline -bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) -{ - return a.val[0] != b.val[0] || a.val[1] != b.val[1] || - a.val[2] != b.val[2] || a.val[3] != b.val[3]; -} - -template static inline -Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(a.val[0] + b.val[0], - a.val[1] + b.val[1], - a.val[2] + b.val[2], - a.val[3] + b.val[3]); -} - -template static inline -Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), - saturate_cast<_Tp>(a.val[1] - b.val[1]), - saturate_cast<_Tp>(a.val[2] - b.val[2]), - saturate_cast<_Tp>(a.val[3] - b.val[3])); -} - -template static inline -Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) -{ - return Scalar_<_Tp>(a.val[0] * alpha, - a.val[1] * alpha, - a.val[2] * alpha, - a.val[3] * alpha); -} - -template static inline -Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) -{ - return a*alpha; -} - -template static inline -Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), - saturate_cast<_Tp>(-a.val[1]), - saturate_cast<_Tp>(-a.val[2]), - saturate_cast<_Tp>(-a.val[3])); -} - - -template static inline -Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), - saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), - saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), - saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); -} - -template static inline -Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a = a * b; - return a; -} - -template static inline -Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) -{ - return Scalar_<_Tp>(a.val[0] / alpha, - a.val[1] / alpha, - a.val[2] / alpha, - a.val[3] / alpha); -} - -template static inline -Scalar_ operator / (const Scalar_& a, float alpha) -{ - float s = 1 / alpha; - return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); -} - -template static inline -Scalar_ operator / (const Scalar_& a, double alpha) -{ - double s = 1 / alpha; - return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); -} - -template static inline -Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) -{ - a = a / alpha; - return a; -} - -template static inline -Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) -{ - _Tp s = a / (b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); - return b.conj() * s; -} - -template static inline -Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - return a * ((_Tp)1 / b); -} - -template static inline -Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) -{ - a = a / b; - return a; -} - -template static inline -Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) -{ - Matx c((Matx)a, b, Matx_MatMulOp()); - return reinterpret_cast(c); -} - -template<> inline -Scalar operator * (const Matx& a, const Scalar& b) -{ - Matx c(a, b, Matx_MatMulOp()); - return reinterpret_cast(c); -} - - - -//////////////////////////////// KeyPoint /////////////////////////////// - -inline -KeyPoint::KeyPoint() - : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} - -inline -KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle, float _response, int _octave, int _class_id) - : pt(_pt), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} - -inline -KeyPoint::KeyPoint(float x, float y, float _size, float _angle, float _response, int _octave, int _class_id) - : pt(x, y), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} - - - -///////////////////////////////// DMatch //////////////////////////////// - -inline -DMatch::DMatch() - : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} - -inline -DMatch::DMatch(int _queryIdx, int _trainIdx, float _distance) - : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} - -inline -DMatch::DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance) - : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} - -inline -bool DMatch::operator < (const DMatch &m) const -{ - return distance < m.distance; -} - - - -////////////////////////////// TermCriteria ///////////////////////////// - -inline -TermCriteria::TermCriteria() - : type(0), maxCount(0), epsilon(0) {} - -inline -TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) - : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} - -//! @endcond - -} // cv - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -#endif //OPENCV_CORE_TYPES_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_TYPES_HPP +#define OPENCV_CORE_TYPES_HPP + +#ifndef __cplusplus +# error types.hpp header must be compiled as C++ +#endif + +#include +#include +#include +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/matx.hpp" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4459) // declaration of '...' hides global declaration +#endif + +namespace cv +{ + +//! @addtogroup core_basic +//! @{ + +//////////////////////////////// Complex ////////////////////////////// + +/** @brief A complex number class. + + The template class is similar and compatible with std::complex, however it provides slightly + more convenient access to the real and imaginary parts using through the simple field access, as opposite + to std::complex::real() and std::complex::imag(). +*/ +template class Complex +{ +public: + + //! default constructor + Complex(); + Complex( _Tp _re, _Tp _im = 0 ); + + //! conversion to another data type + template operator Complex() const; + //! conjugation + Complex conj() const; + + _Tp re, im; ///< the real and the imaginary parts +}; + +typedef Complex Complexf; +typedef Complex Complexd; + +template class DataType< Complex<_Tp> > +{ +public: + typedef Complex<_Tp> value_type; + typedef value_type work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = DataType::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Complex<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Complex<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; +} // namespace + + +//////////////////////////////// Point_ //////////////////////////////// + +/** @brief Template class for 2D points specified by its coordinates `x` and `y`. + +An instance of the class is interchangeable with C structures, CvPoint and CvPoint2D32f . There is +also a cast operator to convert point coordinates to the specified type. The conversion from +floating-point coordinates to integer coordinates is done by rounding. Commonly, the conversion +uses this operation for each of the coordinates. Besides the class members listed in the +declaration above, the following operations on points are implemented: +@code + pt1 = pt2 + pt3; + pt1 = pt2 - pt3; + pt1 = pt2 * a; + pt1 = a * pt2; + pt1 = pt2 / a; + pt1 += pt2; + pt1 -= pt2; + pt1 *= a; + pt1 /= a; + double value = norm(pt); // L2 norm + pt1 == pt2; + pt1 != pt2; +@endcode +For your convenience, the following type aliases are defined: +@code + typedef Point_ Point2i; + typedef Point2i Point; + typedef Point_ Point2f; + typedef Point_ Point2d; +@endcode +Example: +@code + Point2f a(0.3f, 0.f), b(0.f, 0.4f); + Point pt = (a + b)*10.f; + cout << pt.x << ", " << pt.y << endl; +@endcode +*/ +template class Point_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Point_(); + Point_(_Tp _x, _Tp _y); +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 + Point_(const Point_& pt); + Point_(Point_&& pt) CV_NOEXCEPT = default; +#elif OPENCV_ABI_COMPATIBILITY < 500 + Point_(const Point_& pt) = default; + Point_(Point_&& pt) CV_NOEXCEPT = default; +#endif + Point_(const Size_<_Tp>& sz); + Point_(const Vec<_Tp, 2>& v); + +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 + Point_& operator = (const Point_& pt); + Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; +#elif OPENCV_ABI_COMPATIBILITY < 500 + Point_& operator = (const Point_& pt) = default; + Point_& operator = (Point_&& pt) CV_NOEXCEPT = default; +#endif + //! conversion to another data type + template operator Point_<_Tp2>() const; + + //! conversion to the old-style C structures + operator Vec<_Tp, 2>() const; + + //! dot product + _Tp dot(const Point_& pt) const; + //! dot product computed in double-precision arithmetics + double ddot(const Point_& pt) const; + //! cross-product + double cross(const Point_& pt) const; + //! checks whether the point is inside the specified rectangle + bool inside(const Rect_<_Tp>& r) const; + _Tp x; //!< x coordinate of the point + _Tp y; //!< y coordinate of the point +}; + +typedef Point_ Point2i; +typedef Point_ Point2l; +typedef Point_ Point2f; +typedef Point_ Point2d; +typedef Point2i Point; + +template class DataType< Point_<_Tp> > +{ +public: + typedef Point_<_Tp> value_type; + typedef Point_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Point_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Point_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; +} // namespace + + +//////////////////////////////// Point3_ //////////////////////////////// + +/** @brief Template class for 3D points specified by its coordinates `x`, `y` and `z`. + +An instance of the class is interchangeable with the C structure CvPoint2D32f . Similarly to +Point_ , the coordinates of 3D points can be converted to another type. The vector arithmetic and +comparison operations are also supported. + +The following Point3_\<\> aliases are available: +@code + typedef Point3_ Point3i; + typedef Point3_ Point3f; + typedef Point3_ Point3d; +@endcode +@see cv::Point3i, cv::Point3f and cv::Point3d +*/ +template class Point3_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Point3_(); + Point3_(_Tp _x, _Tp _y, _Tp _z); +#if OPENCV_ABI_COMPATIBILITY < 500 + Point3_(const Point3_& pt) = default; + Point3_(Point3_&& pt) CV_NOEXCEPT = default; +#endif + explicit Point3_(const Point_<_Tp>& pt); + Point3_(const Vec<_Tp, 3>& v); + +#if OPENCV_ABI_COMPATIBILITY < 500 + Point3_& operator = (const Point3_& pt) = default; + Point3_& operator = (Point3_&& pt) CV_NOEXCEPT = default; +#endif + //! conversion to another data type + template operator Point3_<_Tp2>() const; + //! conversion to cv::Vec<> + operator Vec<_Tp, 3>() const; + + //! dot product + _Tp dot(const Point3_& pt) const; + //! dot product computed in double-precision arithmetics + double ddot(const Point3_& pt) const; + //! cross product of the 2 3D points + Point3_ cross(const Point3_& pt) const; + _Tp x; //!< x coordinate of the 3D point + _Tp y; //!< y coordinate of the 3D point + _Tp z; //!< z coordinate of the 3D point +}; + +typedef Point3_ Point3i; +typedef Point3_ Point3f; +typedef Point3_ Point3d; + +template class DataType< Point3_<_Tp> > +{ +public: + typedef Point3_<_Tp> value_type; + typedef Point3_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 3, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Point3_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Point3_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 3) }; }; +} // namespace + +//////////////////////////////// Size_ //////////////////////////////// + +/** @brief Template class for specifying the size of an image or rectangle. + +The class includes two members called width and height. The structure can be converted to and from +the old OpenCV structures CvSize and CvSize2D32f . The same set of arithmetic and comparison +operations as for Point_ is available. + +OpenCV defines the following Size_\<\> aliases: +@code + typedef Size_ Size2i; + typedef Size2i Size; + typedef Size_ Size2f; +@endcode +*/ +template class Size_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Size_(); + Size_(_Tp _width, _Tp _height); +#if OPENCV_ABI_COMPATIBILITY < 500 + Size_(const Size_& sz) = default; + Size_(Size_&& sz) CV_NOEXCEPT = default; +#endif + Size_(const Point_<_Tp>& pt); + +#if OPENCV_ABI_COMPATIBILITY < 500 + Size_& operator = (const Size_& sz) = default; + Size_& operator = (Size_&& sz) CV_NOEXCEPT = default; +#endif + //! the area (width*height) + _Tp area() const; + //! aspect ratio (width/height) + double aspectRatio() const; + //! true if empty + bool empty() const; + + //! conversion of another data type. + template operator Size_<_Tp2>() const; + + _Tp width; //!< the width + _Tp height; //!< the height +}; + +typedef Size_ Size2i; +typedef Size_ Size2l; +typedef Size_ Size2f; +typedef Size_ Size2d; +typedef Size2i Size; + +template class DataType< Size_<_Tp> > +{ +public: + typedef Size_<_Tp> value_type; + typedef Size_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = DataType::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Size_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Size_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 2) }; }; +} // namespace + +//////////////////////////////// Rect_ //////////////////////////////// + +/** @brief Template class for 2D rectangles + +described by the following parameters: +- Coordinates of the top-left corner. This is a default interpretation of Rect_::x and Rect_::y + in OpenCV. Though, in your algorithms you may count x and y from the bottom-left corner. +- Rectangle width and height. + +OpenCV typically assumes that the top and left boundary of the rectangle are inclusive, while the +right and bottom boundaries are not. For example, the method Rect_::contains returns true if + +\f[x \leq pt.x < x+width, + y \leq pt.y < y+height\f] + +Virtually every loop over an image ROI in OpenCV (where ROI is specified by Rect_\ ) is +implemented as: +@code + for(int y = roi.y; y < roi.y + roi.height; y++) + for(int x = roi.x; x < roi.x + roi.width; x++) + { + // ... + } +@endcode +In addition to the class members, the following operations on rectangles are implemented: +- \f$\texttt{rect} = \texttt{rect} \pm \texttt{point}\f$ (shifting a rectangle by a certain offset) +- \f$\texttt{rect} = \texttt{rect} \pm \texttt{size}\f$ (expanding or shrinking a rectangle by a + certain amount) +- rect += point, rect -= point, rect += size, rect -= size (augmenting operations) +- rect = rect1 & rect2 (rectangle intersection) +- rect = rect1 | rect2 (minimum area rectangle containing rect1 and rect2 ) +- rect &= rect1, rect |= rect1 (and the corresponding augmenting operations) +- rect == rect1, rect != rect1 (rectangle comparison) + +This is an example how the partial ordering on rectangles can be established (rect1 \f$\subseteq\f$ +rect2): +@code + template inline bool + operator <= (const Rect_<_Tp>& r1, const Rect_<_Tp>& r2) + { + return (r1 & r2) == r1; + } +@endcode +For your convenience, the Rect_\<\> alias is available: cv::Rect +*/ +template class Rect_ +{ +public: + typedef _Tp value_type; + + //! default constructor + Rect_(); + Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height); +#if OPENCV_ABI_COMPATIBILITY < 500 + Rect_(const Rect_& r) = default; + Rect_(Rect_&& r) CV_NOEXCEPT = default; +#endif + Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz); + Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2); + +#if OPENCV_ABI_COMPATIBILITY < 500 + Rect_& operator = (const Rect_& r) = default; + Rect_& operator = (Rect_&& r) CV_NOEXCEPT = default; +#endif + //! the top-left corner + Point_<_Tp> tl() const; + //! the bottom-right corner + Point_<_Tp> br() const; + + //! size (width, height) of the rectangle + Size_<_Tp> size() const; + //! area (width*height) of the rectangle + _Tp area() const; + //! true if empty + bool empty() const; + + //! conversion to another data type + template operator Rect_<_Tp2>() const; + + //! checks whether the rectangle contains the point + /*! @warning After OpenCV 4.11.0, when calling Rect.contains() with cv::Point2f / cv::Point2d point, point should not convert/round to int. + * ``` + * Rect_ r(0,0,500,500); Point_ pt(250.0f, 499.9f); + * r.contains(pt) returns false.(OpenCV 4.10.0 or before) + * r.contains(pt) returns true. (OpenCV 4.11.0 or later) + * ``` + */ + template inline bool contains(const Point_<_Tp2>& pt) const; + + _Tp x; //!< x coordinate of the top-left corner + _Tp y; //!< y coordinate of the top-left corner + _Tp width; //!< width of the rectangle + _Tp height; //!< height of the rectangle +}; + +typedef Rect_ Rect2i; +typedef Rect_ Rect2f; +typedef Rect_ Rect2d; +typedef Rect2i Rect; + +template class DataType< Rect_<_Tp> > +{ +public: + typedef Rect_<_Tp> value_type; + typedef Rect_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 4, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Rect_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Rect_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; +} // namespace + +///////////////////////////// RotatedRect ///////////////////////////// + +/** @brief The class represents rotated (i.e. not up-right) rectangles on a plane. + +Each rectangle is specified by the center point (mass center), length of each side (represented by +#Size2f structure) and the rotation angle in degrees. + +The sample below demonstrates how to use RotatedRect: +@snippet snippets/core_various.cpp RotatedRect_demo +![image](pics/rotatedrect.png) + +@sa CamShift, fitEllipse, minAreaRect, CvBox2D +*/ +class CV_EXPORTS_W_SIMPLE RotatedRect +{ +public: + //! default constructor + CV_WRAP RotatedRect(); + /** full constructor + @param center The rectangle mass center. + @param size Width and height of the rectangle. + @param angle The rotation angle in a clockwise direction. When the angle is 0, 90, 180, 270 etc., + the rectangle becomes an up-right rectangle. + */ + CV_WRAP RotatedRect(const Point2f& center, const Size2f& size, float angle); + /** + Any 3 end points of the RotatedRect. They must be given in order (either clockwise or + anticlockwise). + */ + CV_WRAP RotatedRect(const Point2f& point1, const Point2f& point2, const Point2f& point3); + + /** returns 4 vertices of the rotated rectangle + @param pts The points array for storing rectangle vertices. The order is _bottomLeft_, _topLeft_, topRight, bottomRight. + @note _Bottom_, _Top_, _Left_ and _Right_ sides refer to the original rectangle (angle is 0), + so after 180 degree rotation _bottomLeft_ point will be located at the top right corner of the + rectangle. + */ + void points(Point2f pts[]) const; + + CV_WRAP void points(CV_OUT std::vector& pts) const; + + //! returns the minimal up-right integer rectangle containing the rotated rectangle + CV_WRAP Rect boundingRect() const; + //! returns the minimal (exact) floating point rectangle containing the rotated rectangle, not intended for use with images + CV_WRAP Rect2f boundingRect2f() const; + //! returns the rectangle mass center + CV_PROP_RW Point2f center; + //! returns width and height of the rectangle + CV_PROP_RW Size2f size; + //! returns the rotation angle. When the angle is 0, 90, 180, 270 etc., the rectangle becomes an up-right rectangle. + CV_PROP_RW float angle; +}; + +template<> class DataType< RotatedRect > +{ +public: + typedef RotatedRect value_type; + typedef value_type work_type; + typedef float channel_type; + + enum { generic_type = 0, + channels = (int)sizeof(value_type)/sizeof(channel_type), // 5 + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template<> +struct Depth< RotatedRect > { enum { value = Depth::value }; }; +template<> +struct Type< RotatedRect > { enum { value = CV_MAKETYPE(Depth::value, (int)sizeof(RotatedRect)/sizeof(float)) }; }; +} // namespace + + +//////////////////////////////// Range ///////////////////////////////// + +/** @brief Template class specifying a continuous subsequence (slice) of a sequence. + +The class is used to specify a row or a column span in a matrix ( Mat ) and for many other purposes. +Range(a,b) is basically the same as a:b in Matlab or a..b in Python. As in Python, start is an +inclusive left boundary of the range and end is an exclusive right boundary of the range. Such a +half-opened interval is usually denoted as \f$[start,end)\f$ . + +The static method Range::all() returns a special variable that means "the whole sequence" or "the +whole range", just like " : " in Matlab or " ... " in Python. All the methods and functions in +OpenCV that take Range support this special Range::all() value. But, of course, in case of your own +custom processing, you will probably have to check and handle it explicitly: +@code + void my_function(..., const Range& r, ....) + { + if(r == Range::all()) { + // process all the data + } + else { + // process [r.start, r.end) + } + } +@endcode +*/ +class CV_EXPORTS Range +{ +public: + Range(); + Range(int _start, int _end); + int size() const; + bool empty() const; + static Range all(); + + int start, end; +}; + +template<> class DataType +{ +public: + typedef Range value_type; + typedef value_type work_type; + typedef int channel_type; + + enum { generic_type = 0, + channels = 2, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template<> +struct Depth< Range > { enum { value = Depth::value }; }; +template<> +struct Type< Range > { enum { value = CV_MAKETYPE(Depth::value, 2) }; }; +} // namespace + + +//////////////////////////////// Scalar_ /////////////////////////////// + +/** @brief Template class for a 4-element vector derived from Vec. + +Being derived from Vec\<_Tp, 4\> , Scalar\_ and Scalar can be used just as typical 4-element +vectors. In addition, they can be converted to/from CvScalar . The type Scalar is widely used in +OpenCV to pass pixel values. +*/ +template class Scalar_ : public Vec<_Tp, 4> +{ +public: + //! default constructor + Scalar_(); + Scalar_(_Tp v0, _Tp v1, _Tp v2=0, _Tp v3=0); + Scalar_(_Tp v0); + + Scalar_(const Scalar_& s); + Scalar_(Scalar_&& s) CV_NOEXCEPT; + + Scalar_& operator=(const Scalar_& s); + Scalar_& operator=(Scalar_&& s) CV_NOEXCEPT; + + template + Scalar_(const Vec<_Tp2, cn>& v); + + //! returns a scalar with all elements set to v0 + static Scalar_<_Tp> all(_Tp v0); + + //! conversion to another data type + template operator Scalar_() const; + + //! per-element product + Scalar_<_Tp> mul(const Scalar_<_Tp>& a, double scale=1 ) const; + + //! returns (v0, -v1, -v2, -v3) + Scalar_<_Tp> conj() const; + + //! returns true iff v1 == v2 == v3 == 0 + bool isReal() const; +}; + +typedef Scalar_ Scalar; + +template class DataType< Scalar_<_Tp> > +{ +public: + typedef Scalar_<_Tp> value_type; + typedef Scalar_::work_type> work_type; + typedef _Tp channel_type; + + enum { generic_type = 0, + channels = 4, + fmt = traits::SafeFmt::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template +struct Depth< Scalar_<_Tp> > { enum { value = Depth<_Tp>::value }; }; +template +struct Type< Scalar_<_Tp> > { enum { value = CV_MAKETYPE(Depth<_Tp>::value, 4) }; }; +} // namespace + + +/////////////////////////////// KeyPoint //////////////////////////////// + +/** @brief Data structure for salient point detectors. + +The class instance stores a keypoint, i.e. a point feature found by one of many available keypoint +detectors, such as Harris corner detector, #FAST, %StarDetector, %SURF, %SIFT etc. + +The keypoint is characterized by the 2D position, scale (proportional to the diameter of the +neighborhood that needs to be taken into account), orientation and some other parameters. The +keypoint neighborhood is then analyzed by another algorithm that builds a descriptor (usually +represented as a feature vector). The keypoints representing the same object in different images +can then be matched using %KDTree or another method. +*/ +class CV_EXPORTS_W_SIMPLE KeyPoint +{ +public: + //! the default constructor + CV_WRAP KeyPoint(); + /** + @param pt x & y coordinates of the keypoint + @param size keypoint diameter + @param angle keypoint orientation + @param response keypoint detector response on the keypoint (that is, strength of the keypoint) + @param octave pyramid octave in which the keypoint has been detected + @param class_id object id + */ + KeyPoint(Point2f pt, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); + /** + @param x x-coordinate of the keypoint + @param y y-coordinate of the keypoint + @param size keypoint diameter + @param angle keypoint orientation + @param response keypoint detector response on the keypoint (that is, strength of the keypoint) + @param octave pyramid octave in which the keypoint has been detected + @param class_id object id + */ + CV_WRAP KeyPoint(float x, float y, float size, float angle=-1, float response=0, int octave=0, int class_id=-1); + + size_t hash() const; + + /** + This method converts vector of keypoints to vector of points or the reverse, where each keypoint is + assigned the same size and the same orientation. + + @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB + @param points2f Array of (x,y) coordinates of each keypoint + @param keypointIndexes Array of indexes of keypoints to be converted to points. (Acts like a mask to + convert only specified keypoints) + */ + CV_WRAP static void convert(const std::vector& keypoints, + CV_OUT std::vector& points2f, + const std::vector& keypointIndexes=std::vector()); + /** @overload + @param points2f Array of (x,y) coordinates of each keypoint + @param keypoints Keypoints obtained from any feature detection algorithm like SIFT/SURF/ORB + @param size keypoint diameter + @param response keypoint detector response on the keypoint (that is, strength of the keypoint) + @param octave pyramid octave in which the keypoint has been detected + @param class_id object id + */ + CV_WRAP static void convert(const std::vector& points2f, + CV_OUT std::vector& keypoints, + float size=1, float response=1, int octave=0, int class_id=-1); + + /** + This method computes overlap for pair of keypoints. Overlap is the ratio between area of keypoint + regions' intersection and area of keypoint regions' union (considering keypoint region as circle). + If they don't overlap, we get zero. If they coincide at same location with same size, we get 1. + @param kp1 First keypoint + @param kp2 Second keypoint + */ + CV_WRAP static float overlap(const KeyPoint& kp1, const KeyPoint& kp2); + + CV_PROP_RW Point2f pt; //!< coordinates of the keypoints + CV_PROP_RW float size; //!< diameter of the meaningful keypoint neighborhood + CV_PROP_RW float angle; //!< computed orientation of the keypoint (-1 if not applicable); + //!< it's in [0,360) degrees and measured relative to + //!< image coordinate system, ie in clockwise. + CV_PROP_RW float response; //!< the response by which the most strong keypoints have been selected. Can be used for the further sorting or subsampling + CV_PROP_RW int octave; //!< octave (pyramid layer) from which the keypoint has been extracted + CV_PROP_RW int class_id; //!< object class (if the keypoints need to be clustered by an object they belong to) +}; + +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED +template<> class DataType +{ +public: + typedef KeyPoint value_type; + typedef float work_type; + typedef float channel_type; + + enum { generic_type = 0, + depth = DataType::depth, + channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 7 + fmt = DataType::fmt + ((channels - 1) << 8), + type = CV_MAKETYPE(depth, channels) + }; + + typedef Vec vec_type; +}; +#endif + + +//////////////////////////////// DMatch ///////////////////////////////// + +/** @brief Class for matching keypoint descriptors + +query descriptor index, train descriptor index, train image index, and distance between +descriptors. +*/ +class CV_EXPORTS_W_SIMPLE DMatch +{ +public: + CV_WRAP DMatch(); + CV_WRAP DMatch(int _queryIdx, int _trainIdx, float _distance); + CV_WRAP DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance); + + CV_PROP_RW int queryIdx; //!< query descriptor index + CV_PROP_RW int trainIdx; //!< train descriptor index + CV_PROP_RW int imgIdx; //!< train image index + + CV_PROP_RW float distance; + + // less is better + bool operator<(const DMatch &m) const; +}; + +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED +template<> class DataType +{ +public: + typedef DMatch value_type; + typedef int work_type; + typedef int channel_type; + + enum { generic_type = 0, + depth = DataType::depth, + channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 4 + fmt = DataType::fmt + ((channels - 1) << 8), + type = CV_MAKETYPE(depth, channels) + }; + + typedef Vec vec_type; +}; +#endif + + +///////////////////////////// TermCriteria ////////////////////////////// + +/** @brief The class defining termination criteria for iterative algorithms. + +You can initialize it by default constructor and then override any parameters, or the structure may +be fully initialized using the advanced variant of the constructor. +*/ +class CV_EXPORTS TermCriteria +{ +public: + /** + Criteria type, can be one of: COUNT, EPS or COUNT + EPS + */ + enum Type + { + COUNT=1, //!< the maximum number of iterations or elements to compute + MAX_ITER=COUNT, //!< ditto + EPS=2 //!< the desired accuracy or change in parameters at which the iterative algorithm stops + }; + + //! default constructor + TermCriteria(); + /** + @param type The type of termination criteria, one of TermCriteria::Type + @param maxCount The maximum number of iterations or elements to compute. + @param epsilon The desired accuracy or change in parameters at which the iterative algorithm stops. + */ + TermCriteria(int type, int maxCount, double epsilon); + + inline bool isValid() const + { + const bool isCount = (type & COUNT) && maxCount > 0; + const bool isEps = (type & EPS) && !cvIsNaN(epsilon); + return isCount || isEps; + } + + int type; //!< the type of termination criteria: COUNT, EPS or COUNT + EPS + int maxCount; //!< the maximum number of iterations/elements + double epsilon; //!< the desired accuracy +}; + + +//! @} core_basic + +///////////////////////// raster image moments ////////////////////////// + +//! @addtogroup imgproc_shape +//! @{ + +/** @brief struct returned by cv::moments + +The spatial moments \f$\texttt{Moments::m}_{ji}\f$ are computed as: + +\f[\texttt{m} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot x^j \cdot y^i \right )\f] + +The central moments \f$\texttt{Moments::mu}_{ji}\f$ are computed as: + +\f[\texttt{mu} _{ji}= \sum _{x,y} \left ( \texttt{array} (x,y) \cdot (x - \bar{x} )^j \cdot (y - \bar{y} )^i \right )\f] + +where \f$(\bar{x}, \bar{y})\f$ is the mass center: + +\f[\bar{x} = \frac{\texttt{m}_{10}}{\texttt{m}_{00}} , \; \bar{y} = \frac{\texttt{m}_{01}}{\texttt{m}_{00}}\f] + +The normalized central moments \f$\texttt{Moments::nu}_{ij}\f$ are computed as: + +\f[\texttt{nu} _{ji}= \frac{\texttt{mu}_{ji}}{\texttt{m}_{00}^{(i+j)/2+1}} .\f] + +@note +\f$\texttt{mu}_{00}=\texttt{m}_{00}\f$, \f$\texttt{nu}_{00}=1\f$ +\f$\texttt{nu}_{10}=\texttt{mu}_{10}=\texttt{mu}_{01}=\texttt{mu}_{10}=0\f$ , hence the values are not +stored. + +The moments of a contour are defined in the same way but computed using the Green's formula (see +). So, due to a limited raster resolution, the moments +computed for a contour are slightly different from the moments computed for the same rasterized +contour. + +@note +Since the contour moments are computed using Green formula, you may get seemingly odd results for +contours with self-intersections, e.g. a zero area (m00) for butterfly-shaped contours. + */ +class CV_EXPORTS_W_MAP Moments +{ +public: + //! the default constructor + Moments(); + //! the full constructor + Moments(double m00, double m10, double m01, double m20, double m11, + double m02, double m30, double m21, double m12, double m03 ); + ////! the conversion from CvMoments + //Moments( const CvMoments& moments ); + ////! the conversion to CvMoments + //operator CvMoments() const; + + //! @name spatial moments + //! @{ + CV_PROP_RW double m00, m10, m01, m20, m11, m02, m30, m21, m12, m03; + //! @} + + //! @name central moments + //! @{ + CV_PROP_RW double mu20, mu11, mu02, mu30, mu21, mu12, mu03; + //! @} + + //! @name central normalized moments + //! @{ + CV_PROP_RW double nu20, nu11, nu02, nu30, nu21, nu12, nu03; + //! @} +}; + +template<> class DataType +{ +public: + typedef Moments value_type; + typedef double work_type; + typedef double channel_type; + + enum { generic_type = 0, + channels = (int)(sizeof(value_type)/sizeof(channel_type)), // 24 + fmt = DataType::fmt + ((channels - 1) << 8) +#ifdef OPENCV_TRAITS_ENABLE_DEPRECATED + ,depth = DataType::depth + ,type = CV_MAKETYPE(depth, channels) +#endif + }; + + typedef Vec vec_type; +}; + +namespace traits { +template<> +struct Depth< Moments > { enum { value = Depth::value }; }; +template<> +struct Type< Moments > { enum { value = CV_MAKETYPE(Depth::value, (int)(sizeof(Moments)/sizeof(double))) }; }; +} // namespace + +//! @} imgproc_shape + +//! @cond IGNORED + +///////////////////////////////////////////////////////////////////////// +///////////////////////////// Implementation //////////////////////////// +///////////////////////////////////////////////////////////////////////// + +//////////////////////////////// Complex //////////////////////////////// + +template inline +Complex<_Tp>::Complex() + : re(0), im(0) {} + +template inline +Complex<_Tp>::Complex( _Tp _re, _Tp _im ) + : re(_re), im(_im) {} + +template template inline +Complex<_Tp>::operator Complex() const +{ + return Complex(saturate_cast(re), saturate_cast(im)); +} + +template inline +Complex<_Tp> Complex<_Tp>::conj() const +{ + return Complex<_Tp>(re, -im); +} + + +template static inline +bool operator == (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return a.re == b.re && a.im == b.im; +} + +template static inline +bool operator != (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return a.re != b.re || a.im != b.im; +} + +template static inline +Complex<_Tp> operator + (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return Complex<_Tp>( a.re + b.re, a.im + b.im ); +} + +template static inline +Complex<_Tp>& operator += (Complex<_Tp>& a, const Complex<_Tp>& b) +{ + a.re += b.re; a.im += b.im; + return a; +} + +template static inline +Complex<_Tp> operator - (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return Complex<_Tp>( a.re - b.re, a.im - b.im ); +} + +template static inline +Complex<_Tp>& operator -= (Complex<_Tp>& a, const Complex<_Tp>& b) +{ + a.re -= b.re; a.im -= b.im; + return a; +} + +template static inline +Complex<_Tp> operator - (const Complex<_Tp>& a) +{ + return Complex<_Tp>(-a.re, -a.im); +} + +template static inline +Complex<_Tp> operator * (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + return Complex<_Tp>( a.re*b.re - a.im*b.im, a.re*b.im + a.im*b.re ); +} + +template static inline +Complex<_Tp> operator * (const Complex<_Tp>& a, _Tp b) +{ + return Complex<_Tp>( a.re*b, a.im*b ); +} + +template static inline +Complex<_Tp> operator * (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>( a.re*b, a.im*b ); +} + +template static inline +Complex<_Tp> operator + (const Complex<_Tp>& a, _Tp b) +{ + return Complex<_Tp>( a.re + b, a.im ); +} + +template static inline +Complex<_Tp> operator - (const Complex<_Tp>& a, _Tp b) +{ return Complex<_Tp>( a.re - b, a.im ); } + +template static inline +Complex<_Tp> operator + (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>( a.re + b, a.im ); +} + +template static inline +Complex<_Tp> operator - (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>( b - a.re, -a.im ); +} + +template static inline +Complex<_Tp>& operator += (Complex<_Tp>& a, _Tp b) +{ + a.re += b; return a; +} + +template static inline +Complex<_Tp>& operator -= (Complex<_Tp>& a, _Tp b) +{ + a.re -= b; return a; +} + +template static inline +Complex<_Tp>& operator *= (Complex<_Tp>& a, _Tp b) +{ + a.re *= b; a.im *= b; return a; +} + +template static inline +double abs(const Complex<_Tp>& a) +{ + return std::sqrt( (double)a.re*a.re + (double)a.im*a.im); +} + +template static inline +Complex<_Tp> operator / (const Complex<_Tp>& a, const Complex<_Tp>& b) +{ + double t = 1./((double)b.re*b.re + (double)b.im*b.im); + return Complex<_Tp>( (_Tp)((a.re*b.re + a.im*b.im)*t), + (_Tp)((-a.re*b.im + a.im*b.re)*t) ); +} + +template static inline +Complex<_Tp>& operator /= (Complex<_Tp>& a, const Complex<_Tp>& b) +{ + a = a / b; + return a; +} + +template static inline +Complex<_Tp> operator / (const Complex<_Tp>& a, _Tp b) +{ + _Tp t = (_Tp)1/b; + return Complex<_Tp>( a.re*t, a.im*t ); +} + +template static inline +Complex<_Tp> operator / (_Tp b, const Complex<_Tp>& a) +{ + return Complex<_Tp>(b)/a; +} + +template static inline +Complex<_Tp> operator /= (const Complex<_Tp>& a, _Tp b) +{ + _Tp t = (_Tp)1/b; + a.re *= t; a.im *= t; return a; +} + + + +//////////////////////////////// 2D Point /////////////////////////////// + +template inline +Point_<_Tp>::Point_() + : x(0), y(0) {} + +template inline +Point_<_Tp>::Point_(_Tp _x, _Tp _y) + : x(_x), y(_y) {} + +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 +template inline +Point_<_Tp>::Point_(const Point_& pt) + : x(pt.x), y(pt.y) {} +#endif + +template inline +Point_<_Tp>::Point_(const Size_<_Tp>& sz) + : x(sz.width), y(sz.height) {} + +template inline +Point_<_Tp>::Point_(const Vec<_Tp,2>& v) + : x(v[0]), y(v[1]) {} + +#if (defined(__GNUC__) && __GNUC__ < 5) && !defined(__clang__) // GCC 4.x bug. Details: https://github.com/opencv/opencv/pull/20837 +template inline +Point_<_Tp>& Point_<_Tp>::operator = (const Point_& pt) +{ + x = pt.x; y = pt.y; + return *this; +} +#endif + +template template inline +Point_<_Tp>::operator Point_<_Tp2>() const +{ + return Point_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y)); +} + +template inline +Point_<_Tp>::operator Vec<_Tp, 2>() const +{ + return Vec<_Tp, 2>(x, y); +} + +template inline +_Tp Point_<_Tp>::dot(const Point_& pt) const +{ + return saturate_cast<_Tp>(x*pt.x + y*pt.y); +} + +template inline +double Point_<_Tp>::ddot(const Point_& pt) const +{ + return (double)x*(double)(pt.x) + (double)y*(double)(pt.y); +} + +template inline +double Point_<_Tp>::cross(const Point_& pt) const +{ + return (double)x*pt.y - (double)y*pt.x; +} + +template inline bool +Point_<_Tp>::inside( const Rect_<_Tp>& r ) const +{ + return r.contains(*this); +} + + +template static inline +Point_<_Tp>& operator += (Point_<_Tp>& a, const Point_<_Tp>& b) +{ + a.x += b.x; + a.y += b.y; + return a; +} + +template static inline +Point_<_Tp>& operator -= (Point_<_Tp>& a, const Point_<_Tp>& b) +{ + a.x -= b.x; + a.y -= b.y; + return a; +} + +template static inline +Point_<_Tp>& operator *= (Point_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + return a; +} + +template static inline +Point_<_Tp>& operator *= (Point_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + return a; +} + +template static inline +Point_<_Tp>& operator *= (Point_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + return a; +} + +template static inline +Point_<_Tp>& operator /= (Point_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + return a; +} + +template static inline +Point_<_Tp>& operator /= (Point_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + return a; +} + +template static inline +Point_<_Tp>& operator /= (Point_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + return a; +} + +template static inline +double norm(const Point_<_Tp>& pt) +{ + return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y); +} + +template static inline +bool operator == (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return a.x == b.x && a.y == b.y; +} + +template static inline +bool operator != (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return a.x != b.x || a.y != b.y; +} + +template static inline +Point_<_Tp> operator + (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y) ); +} + +template static inline +Point_<_Tp> operator - (const Point_<_Tp>& a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y) ); +} + +template static inline +Point_<_Tp> operator - (const Point_<_Tp>& a) +{ + return Point_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y) ); +} + +template static inline +Point_<_Tp> operator * (const Point_<_Tp>& a, int b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); +} + +template static inline +Point_<_Tp> operator * (int a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); +} + +template static inline +Point_<_Tp> operator * (const Point_<_Tp>& a, float b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); +} + +template static inline +Point_<_Tp> operator * (float a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); +} + +template static inline +Point_<_Tp> operator * (const Point_<_Tp>& a, double b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b) ); +} + +template static inline +Point_<_Tp> operator * (double a, const Point_<_Tp>& b) +{ + return Point_<_Tp>( saturate_cast<_Tp>(b.x*a), saturate_cast<_Tp>(b.y*a) ); +} + +template static inline +Point_<_Tp> operator * (const Matx<_Tp, 2, 2>& a, const Point_<_Tp>& b) +{ + Matx<_Tp, 2, 1> tmp = a * Vec<_Tp,2>(b.x, b.y); + return Point_<_Tp>(tmp.val[0], tmp.val[1]); +} + +template static inline +Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point_<_Tp>& b) +{ + Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, 1); + return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); +} + +template static inline +Point_<_Tp> operator / (const Point_<_Tp>& a, int b) +{ + Point_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point_<_Tp> operator / (const Point_<_Tp>& a, float b) +{ + Point_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point_<_Tp> operator / (const Point_<_Tp>& a, double b) +{ + Point_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + + +template static inline _AccTp normL2Sqr(const Point_& pt); +template static inline _AccTp normL2Sqr(const Point_& pt); +template static inline _AccTp normL2Sqr(const Point_& pt); +template static inline _AccTp normL2Sqr(const Point_& pt); + +template<> inline int normL2Sqr(const Point_& pt) { return pt.dot(pt); } +template<> inline int64 normL2Sqr(const Point_& pt) { return pt.dot(pt); } +template<> inline float normL2Sqr(const Point_& pt) { return pt.dot(pt); } +template<> inline double normL2Sqr(const Point_& pt) { return pt.dot(pt); } + +template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } +template<> inline double normL2Sqr(const Point_& pt) { return pt.ddot(pt); } + + + +//////////////////////////////// 3D Point /////////////////////////////// + +template inline +Point3_<_Tp>::Point3_() + : x(0), y(0), z(0) {} + +template inline +Point3_<_Tp>::Point3_(_Tp _x, _Tp _y, _Tp _z) + : x(_x), y(_y), z(_z) {} + +template inline +Point3_<_Tp>::Point3_(const Point_<_Tp>& pt) + : x(pt.x), y(pt.y), z(_Tp()) {} + +template inline +Point3_<_Tp>::Point3_(const Vec<_Tp, 3>& v) + : x(v[0]), y(v[1]), z(v[2]) {} + +template template inline +Point3_<_Tp>::operator Point3_<_Tp2>() const +{ + return Point3_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(z)); +} + +template inline +Point3_<_Tp>::operator Vec<_Tp, 3>() const +{ + return Vec<_Tp, 3>(x, y, z); +} + +template inline +_Tp Point3_<_Tp>::dot(const Point3_& pt) const +{ + return saturate_cast<_Tp>(x*pt.x + y*pt.y + z*pt.z); +} + +template inline +double Point3_<_Tp>::ddot(const Point3_& pt) const +{ + return (double)x*pt.x + (double)y*pt.y + (double)z*pt.z; +} + +template inline +Point3_<_Tp> Point3_<_Tp>::cross(const Point3_<_Tp>& pt) const +{ + return Point3_<_Tp>(y*pt.z - z*pt.y, z*pt.x - x*pt.z, x*pt.y - y*pt.x); +} + + +template static inline +Point3_<_Tp>& operator += (Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + a.x += b.x; + a.y += b.y; + a.z += b.z; + return a; +} + +template static inline +Point3_<_Tp>& operator -= (Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + a.x -= b.x; + a.y -= b.y; + a.z -= b.z; + return a; +} + +template static inline +Point3_<_Tp>& operator *= (Point3_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + a.z = saturate_cast<_Tp>(a.z * b); + return a; +} + +template static inline +Point3_<_Tp>& operator *= (Point3_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + a.z = saturate_cast<_Tp>(a.z * b); + return a; +} + +template static inline +Point3_<_Tp>& operator *= (Point3_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x * b); + a.y = saturate_cast<_Tp>(a.y * b); + a.z = saturate_cast<_Tp>(a.z * b); + return a; +} + +template static inline +Point3_<_Tp>& operator /= (Point3_<_Tp>& a, int b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + a.z = saturate_cast<_Tp>(a.z / b); + return a; +} + +template static inline +Point3_<_Tp>& operator /= (Point3_<_Tp>& a, float b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + a.z = saturate_cast<_Tp>(a.z / b); + return a; +} + +template static inline +Point3_<_Tp>& operator /= (Point3_<_Tp>& a, double b) +{ + a.x = saturate_cast<_Tp>(a.x / b); + a.y = saturate_cast<_Tp>(a.y / b); + a.z = saturate_cast<_Tp>(a.z / b); + return a; +} + +template static inline +double norm(const Point3_<_Tp>& pt) +{ + return std::sqrt((double)pt.x*pt.x + (double)pt.y*pt.y + (double)pt.z*pt.z); +} + +template static inline +bool operator == (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return a.x == b.x && a.y == b.y && a.z == b.z; +} + +template static inline +bool operator != (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return a.x != b.x || a.y != b.y || a.z != b.z; +} + +template static inline +Point3_<_Tp> operator + (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x + b.x), saturate_cast<_Tp>(a.y + b.y), saturate_cast<_Tp>(a.z + b.z)); +} + +template static inline +Point3_<_Tp> operator - (const Point3_<_Tp>& a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x - b.x), saturate_cast<_Tp>(a.y - b.y), saturate_cast<_Tp>(a.z - b.z)); +} + +template static inline +Point3_<_Tp> operator - (const Point3_<_Tp>& a) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(-a.x), saturate_cast<_Tp>(-a.y), saturate_cast<_Tp>(-a.z) ); +} + +template static inline +Point3_<_Tp> operator * (const Point3_<_Tp>& a, int b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x*b), saturate_cast<_Tp>(a.y*b), saturate_cast<_Tp>(a.z*b) ); +} + +template static inline +Point3_<_Tp> operator * (int a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); +} + +template static inline +Point3_<_Tp> operator * (const Point3_<_Tp>& a, float b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); +} + +template static inline +Point3_<_Tp> operator * (float a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); +} + +template static inline +Point3_<_Tp> operator * (const Point3_<_Tp>& a, double b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(a.x * b), saturate_cast<_Tp>(a.y * b), saturate_cast<_Tp>(a.z * b) ); +} + +template static inline +Point3_<_Tp> operator * (double a, const Point3_<_Tp>& b) +{ + return Point3_<_Tp>( saturate_cast<_Tp>(b.x * a), saturate_cast<_Tp>(b.y * a), saturate_cast<_Tp>(b.z * a) ); +} + +template static inline +Point3_<_Tp> operator * (const Matx<_Tp, 3, 3>& a, const Point3_<_Tp>& b) +{ + Matx<_Tp, 3, 1> tmp = a * Vec<_Tp,3>(b.x, b.y, b.z); + return Point3_<_Tp>(tmp.val[0], tmp.val[1], tmp.val[2]); +} + +template static inline +Matx<_Tp, 4, 1> operator * (const Matx<_Tp, 4, 4>& a, const Point3_<_Tp>& b) +{ + return a * Matx<_Tp, 4, 1>(b.x, b.y, b.z, 1); +} + +template static inline +Point3_<_Tp> operator / (const Point3_<_Tp>& a, int b) +{ + Point3_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point3_<_Tp> operator / (const Point3_<_Tp>& a, float b) +{ + Point3_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Point3_<_Tp> operator / (const Point3_<_Tp>& a, double b) +{ + Point3_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + + + +////////////////////////////////// Size ///////////////////////////////// + +template inline +Size_<_Tp>::Size_() + : width(0), height(0) {} + +template inline +Size_<_Tp>::Size_(_Tp _width, _Tp _height) + : width(_width), height(_height) {} + +template inline +Size_<_Tp>::Size_(const Point_<_Tp>& pt) + : width(pt.x), height(pt.y) {} + +template template inline +Size_<_Tp>::operator Size_<_Tp2>() const +{ + return Size_<_Tp2>(saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); +} + +template inline +_Tp Size_<_Tp>::area() const +{ + const _Tp result = width * height; + CV_DbgAssert(!std::numeric_limits<_Tp>::is_integer + || width == 0 || result / width == height); // make sure the result fits in the return value + return result; +} + +template inline +double Size_<_Tp>::aspectRatio() const +{ + return width / static_cast(height); +} + +template inline +bool Size_<_Tp>::empty() const +{ + return width <= 0 || height <= 0; +} + + +template static inline +Size_<_Tp>& operator *= (Size_<_Tp>& a, _Tp b) +{ + a.width *= b; + a.height *= b; + return a; +} + +template static inline +Size_<_Tp> operator * (const Size_<_Tp>& a, _Tp b) +{ + Size_<_Tp> tmp(a); + tmp *= b; + return tmp; +} + +template static inline +Size_<_Tp>& operator /= (Size_<_Tp>& a, _Tp b) +{ + a.width /= b; + a.height /= b; + return a; +} + +template static inline +Size_<_Tp> operator / (const Size_<_Tp>& a, _Tp b) +{ + Size_<_Tp> tmp(a); + tmp /= b; + return tmp; +} + +template static inline +Size_<_Tp>& operator += (Size_<_Tp>& a, const Size_<_Tp>& b) +{ + a.width += b.width; + a.height += b.height; + return a; +} + +template static inline +Size_<_Tp> operator + (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + Size_<_Tp> tmp(a); + tmp += b; + return tmp; +} + +template static inline +Size_<_Tp>& operator -= (Size_<_Tp>& a, const Size_<_Tp>& b) +{ + a.width -= b.width; + a.height -= b.height; + return a; +} + +template static inline +Size_<_Tp> operator - (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + Size_<_Tp> tmp(a); + tmp -= b; + return tmp; +} + +template static inline +bool operator == (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + return a.width == b.width && a.height == b.height; +} + +template static inline +bool operator != (const Size_<_Tp>& a, const Size_<_Tp>& b) +{ + return !(a == b); +} + + + +////////////////////////////////// Rect ///////////////////////////////// + +template inline +Rect_<_Tp>::Rect_() + : x(0), y(0), width(0), height(0) {} + +template inline +Rect_<_Tp>::Rect_(_Tp _x, _Tp _y, _Tp _width, _Tp _height) + : x(_x), y(_y), width(_width), height(_height) {} + +template inline +Rect_<_Tp>::Rect_(const Point_<_Tp>& org, const Size_<_Tp>& sz) + : x(org.x), y(org.y), width(sz.width), height(sz.height) {} + +template inline +Rect_<_Tp>::Rect_(const Point_<_Tp>& pt1, const Point_<_Tp>& pt2) +{ + x = std::min(pt1.x, pt2.x); + y = std::min(pt1.y, pt2.y); + width = std::max(pt1.x, pt2.x) - x; + height = std::max(pt1.y, pt2.y) - y; +} + +template inline +Point_<_Tp> Rect_<_Tp>::tl() const +{ + return Point_<_Tp>(x,y); +} + +template inline +Point_<_Tp> Rect_<_Tp>::br() const +{ + return Point_<_Tp>(x + width, y + height); +} + +template inline +Size_<_Tp> Rect_<_Tp>::size() const +{ + return Size_<_Tp>(width, height); +} + +template inline +_Tp Rect_<_Tp>::area() const +{ + const _Tp result = width * height; + if constexpr (std::numeric_limits<_Tp>::is_integer) + { + CV_DbgAssert(width == 0 || result / width == height); // make sure the result fits in the return value + } + return result; +} + +template inline +bool Rect_<_Tp>::empty() const +{ + return width <= 0 || height <= 0; +} + +template template inline +Rect_<_Tp>::operator Rect_<_Tp2>() const +{ + return Rect_<_Tp2>(saturate_cast<_Tp2>(x), saturate_cast<_Tp2>(y), saturate_cast<_Tp2>(width), saturate_cast<_Tp2>(height)); +} + +template template inline +bool Rect_<_Tp>::contains(const Point_<_Tp2>& pt) const +{ + return x <= pt.x && pt.x < x + width && y <= pt.y && pt.y < y + height; +} +// See https://github.com/opencv/opencv/issues/26016 +template<> template<> inline +bool Rect_::contains(const Point_& pt) const +{ + // std::numeric_limits::digits is 31. + // std::numeric_limits::digits is 53. + // So conversion int->double does not lead to accuracy errors. + const Rect_ _rect(static_cast(x), static_cast(y), static_cast(width), static_cast(height)); + return _rect.contains(pt); +} +template<> template<> inline +bool Rect_::contains(const Point_& _pt) const +{ + // std::numeric_limits::digits is 24. + // std::numeric_limits::digits is 53. + // So conversion float->double does not lead to accuracy errors. + return contains(Point_(static_cast(_pt.x), static_cast(_pt.y))); +} + +template static inline +Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Point_<_Tp>& b ) +{ + a.x += b.x; + a.y += b.y; + return a; +} + +template static inline +Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Point_<_Tp>& b ) +{ + a.x -= b.x; + a.y -= b.y; + return a; +} + +template static inline +Rect_<_Tp>& operator += ( Rect_<_Tp>& a, const Size_<_Tp>& b ) +{ + a.width += b.width; + a.height += b.height; + return a; +} + +template static inline +Rect_<_Tp>& operator -= ( Rect_<_Tp>& a, const Size_<_Tp>& b ) +{ + const _Tp width = a.width - b.width; + const _Tp height = a.height - b.height; + CV_DbgAssert(width >= 0 && height >= 0); + a.width = width; + a.height = height; + return a; +} + +template static inline +Rect_<_Tp>& operator &= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) +{ + if (a.empty() || b.empty()) { + a = Rect(); + return a; + } + const Rect_<_Tp>& Rx_min = (a.x < b.x) ? a : b; + const Rect_<_Tp>& Rx_max = (a.x < b.x) ? b : a; + const Rect_<_Tp>& Ry_min = (a.y < b.y) ? a : b; + const Rect_<_Tp>& Ry_max = (a.y < b.y) ? b : a; + // Looking at the formula below, we will compute Rx_min.width - (Rx_max.x - Rx_min.x) + // but we want to avoid overflows. Rx_min.width >= 0 and (Rx_max.x - Rx_min.x) >= 0 + // by definition so the difference does not overflow. The only thing that can overflow + // is (Rx_max.x - Rx_min.x). And it can only overflow if Rx_min.x < 0. + // Let us first deal with the following case. + if ((Rx_min.x < 0 && Rx_min.x + Rx_min.width < Rx_max.x) || + (Ry_min.y < 0 && Ry_min.y + Ry_min.height < Ry_max.y)) { + a = Rect(); + return a; + } + // We now know that either Rx_min.x >= 0, or + // Rx_min.x < 0 && Rx_min.x + Rx_min.width >= Rx_max.x and therefore + // Rx_min.width >= (Rx_max.x - Rx_min.x) which means (Rx_max.x - Rx_min.x) + // is inferior to a valid int and therefore does not overflow. + a.width = std::min(Rx_min.width - (Rx_max.x - Rx_min.x), Rx_max.width); + a.height = std::min(Ry_min.height - (Ry_max.y - Ry_min.y), Ry_max.height); + a.x = Rx_max.x; + a.y = Ry_max.y; + if (a.empty()) + a = Rect(); + return a; +} + +template static inline +Rect_<_Tp>& operator |= ( Rect_<_Tp>& a, const Rect_<_Tp>& b ) +{ + if (a.empty()) { + a = b; + } + else if (!b.empty()) { + _Tp x1 = std::min(a.x, b.x); + _Tp y1 = std::min(a.y, b.y); + a.width = std::max(a.x + a.width, b.x + b.width) - x1; + a.height = std::max(a.y + a.height, b.y + b.height) - y1; + a.x = x1; + a.y = y1; + } + return a; +} + +template static inline +bool operator == (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + return a.x == b.x && a.y == b.y && a.width == b.width && a.height == b.height; +} + +template static inline +bool operator != (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + return a.x != b.x || a.y != b.y || a.width != b.width || a.height != b.height; +} + +template static inline +Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Point_<_Tp>& b) +{ + return Rect_<_Tp>( a.x + b.x, a.y + b.y, a.width, a.height ); +} + +template static inline +Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Point_<_Tp>& b) +{ + return Rect_<_Tp>( a.x - b.x, a.y - b.y, a.width, a.height ); +} + +template static inline +Rect_<_Tp> operator + (const Rect_<_Tp>& a, const Size_<_Tp>& b) +{ + return Rect_<_Tp>( a.x, a.y, a.width + b.width, a.height + b.height ); +} + +template static inline +Rect_<_Tp> operator - (const Rect_<_Tp>& a, const Size_<_Tp>& b) +{ + const _Tp width = a.width - b.width; + const _Tp height = a.height - b.height; + CV_DbgAssert(width >= 0 && height >= 0); + return Rect_<_Tp>( a.x, a.y, width, height ); +} + +template static inline +Rect_<_Tp> operator & (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + Rect_<_Tp> c = a; + return c &= b; +} + +template static inline +Rect_<_Tp> operator | (const Rect_<_Tp>& a, const Rect_<_Tp>& b) +{ + Rect_<_Tp> c = a; + return c |= b; +} + +/** + * @brief measure dissimilarity between two sample sets + * + * computes the complement of the Jaccard Index as described in . + * For rectangles this reduces to computing the intersection over the union. + */ +template static inline +double jaccardDistance(const Rect_<_Tp>& a, const Rect_<_Tp>& b) { + _Tp Aa = a.area(); + _Tp Ab = b.area(); + + if ((Aa + Ab) <= std::numeric_limits<_Tp>::epsilon()) { + // jaccard_index = 1 -> distance = 0 + return 0.0; + } + + double Aab = (a & b).area(); + // distance = 1 - jaccard_index + return 1.0 - Aab / (Aa + Ab - Aab); +} + +/** @brief Finds out if there is any intersection between two rectangles + * + * mainly useful for language bindings + * @param a First rectangle + * @param b Second rectangle + * @return the area of the intersection + */ +CV_EXPORTS_W inline double rectangleIntersectionArea(const Rect2d& a, const Rect2d& b) { return (a & b).area(); } + +////////////////////////////// RotatedRect ////////////////////////////// + +inline +RotatedRect::RotatedRect() + : center(), size(), angle(0) {} + +inline +RotatedRect::RotatedRect(const Point2f& _center, const Size2f& _size, float _angle) + : center(_center), size(_size), angle(_angle) {} + +///////////////////////////////// Range ///////////////////////////////// + +inline +Range::Range() + : start(0), end(0) {} + +inline +Range::Range(int _start, int _end) + : start(_start), end(_end) {} + +inline +int Range::size() const +{ + return end - start; +} + +inline +bool Range::empty() const +{ + return start == end; +} + +inline +Range Range::all() +{ + return Range(INT_MIN, INT_MAX); +} + + +static inline +bool operator == (const Range& r1, const Range& r2) +{ + return r1.start == r2.start && r1.end == r2.end; +} + +static inline +bool operator != (const Range& r1, const Range& r2) +{ + return !(r1 == r2); +} + +static inline +bool operator !(const Range& r) +{ + return r.start == r.end; +} + +static inline +Range operator & (const Range& r1, const Range& r2) +{ + Range r(std::max(r1.start, r2.start), std::min(r1.end, r2.end)); + r.end = std::max(r.end, r.start); + return r; +} + +static inline +Range& operator &= (Range& r1, const Range& r2) +{ + r1 = r1 & r2; + return r1; +} + +static inline +Range operator + (const Range& r1, int delta) +{ + return Range(r1.start + delta, r1.end + delta); +} + +static inline +Range operator + (int delta, const Range& r1) +{ + return Range(r1.start + delta, r1.end + delta); +} + +static inline +Range operator - (const Range& r1, int delta) +{ + return r1 + (-delta); +} + + + +///////////////////////////////// Scalar //////////////////////////////// + +template inline +Scalar_<_Tp>::Scalar_() +{ + this->val[0] = this->val[1] = this->val[2] = this->val[3] = 0; +} + +template inline +Scalar_<_Tp>::Scalar_(_Tp v0, _Tp v1, _Tp v2, _Tp v3) +{ + this->val[0] = v0; + this->val[1] = v1; + this->val[2] = v2; + this->val[3] = v3; +} + +template inline +Scalar_<_Tp>::Scalar_(const Scalar_<_Tp>& s) : Vec<_Tp, 4>(s) { +} + +template inline +Scalar_<_Tp>::Scalar_(Scalar_<_Tp>&& s) CV_NOEXCEPT { + this->val[0] = std::move(s.val[0]); + this->val[1] = std::move(s.val[1]); + this->val[2] = std::move(s.val[2]); + this->val[3] = std::move(s.val[3]); +} + +template inline +Scalar_<_Tp>& Scalar_<_Tp>::operator=(const Scalar_<_Tp>& s) { + this->val[0] = s.val[0]; + this->val[1] = s.val[1]; + this->val[2] = s.val[2]; + this->val[3] = s.val[3]; + return *this; +} + +template inline +Scalar_<_Tp>& Scalar_<_Tp>::operator=(Scalar_<_Tp>&& s) CV_NOEXCEPT { + this->val[0] = std::move(s.val[0]); + this->val[1] = std::move(s.val[1]); + this->val[2] = std::move(s.val[2]); + this->val[3] = std::move(s.val[3]); + return *this; +} + +template template inline +Scalar_<_Tp>::Scalar_(const Vec<_Tp2, cn>& v) +{ + int i; + for( i = 0; i < (cn < 4 ? cn : 4); i++ ) + this->val[i] = cv::saturate_cast<_Tp>(v.val[i]); + for( ; i < 4; i++ ) + this->val[i] = 0; +} + +template inline +Scalar_<_Tp>::Scalar_(_Tp v0) +{ + this->val[0] = v0; + this->val[1] = this->val[2] = this->val[3] = 0; +} + +template inline +Scalar_<_Tp> Scalar_<_Tp>::all(_Tp v0) +{ + return Scalar_<_Tp>(v0, v0, v0, v0); +} + + +template inline +Scalar_<_Tp> Scalar_<_Tp>::mul(const Scalar_<_Tp>& a, double scale ) const +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(this->val[0] * a.val[0] * scale), + saturate_cast<_Tp>(this->val[1] * a.val[1] * scale), + saturate_cast<_Tp>(this->val[2] * a.val[2] * scale), + saturate_cast<_Tp>(this->val[3] * a.val[3] * scale)); +} + +template inline +Scalar_<_Tp> Scalar_<_Tp>::conj() const +{ + return Scalar_<_Tp>(saturate_cast<_Tp>( this->val[0]), + saturate_cast<_Tp>(-this->val[1]), + saturate_cast<_Tp>(-this->val[2]), + saturate_cast<_Tp>(-this->val[3])); +} + +template inline +bool Scalar_<_Tp>::isReal() const +{ + return this->val[1] == 0 && this->val[2] == 0 && this->val[3] == 0; +} + + +template template inline +Scalar_<_Tp>::operator Scalar_() const +{ + return Scalar_(saturate_cast(this->val[0]), + saturate_cast(this->val[1]), + saturate_cast(this->val[2]), + saturate_cast(this->val[3])); +} + + +template static inline +Scalar_<_Tp>& operator += (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a.val[0] += b.val[0]; + a.val[1] += b.val[1]; + a.val[2] += b.val[2]; + a.val[3] += b.val[3]; + return a; +} + +template static inline +Scalar_<_Tp>& operator -= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a.val[0] -= b.val[0]; + a.val[1] -= b.val[1]; + a.val[2] -= b.val[2]; + a.val[3] -= b.val[3]; + return a; +} + +template static inline +Scalar_<_Tp>& operator *= ( Scalar_<_Tp>& a, _Tp v ) +{ + a.val[0] *= v; + a.val[1] *= v; + a.val[2] *= v; + a.val[3] *= v; + return a; +} + +template static inline +bool operator == ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) +{ + return a.val[0] == b.val[0] && a.val[1] == b.val[1] && + a.val[2] == b.val[2] && a.val[3] == b.val[3]; +} + +template static inline +bool operator != ( const Scalar_<_Tp>& a, const Scalar_<_Tp>& b ) +{ + return a.val[0] != b.val[0] || a.val[1] != b.val[1] || + a.val[2] != b.val[2] || a.val[3] != b.val[3]; +} + +template static inline +Scalar_<_Tp> operator + (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return Scalar_<_Tp>(a.val[0] + b.val[0], + a.val[1] + b.val[1], + a.val[2] + b.val[2], + a.val[3] + b.val[3]); +} + +template static inline +Scalar_<_Tp> operator - (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(a.val[0] - b.val[0]), + saturate_cast<_Tp>(a.val[1] - b.val[1]), + saturate_cast<_Tp>(a.val[2] - b.val[2]), + saturate_cast<_Tp>(a.val[3] - b.val[3])); +} + +template static inline +Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, _Tp alpha) +{ + return Scalar_<_Tp>(a.val[0] * alpha, + a.val[1] * alpha, + a.val[2] * alpha, + a.val[3] * alpha); +} + +template static inline +Scalar_<_Tp> operator * (_Tp alpha, const Scalar_<_Tp>& a) +{ + return a*alpha; +} + +template static inline +Scalar_<_Tp> operator - (const Scalar_<_Tp>& a) +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(-a.val[0]), + saturate_cast<_Tp>(-a.val[1]), + saturate_cast<_Tp>(-a.val[2]), + saturate_cast<_Tp>(-a.val[3])); +} + + +template static inline +Scalar_<_Tp> operator * (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return Scalar_<_Tp>(saturate_cast<_Tp>(a[0]*b[0] - a[1]*b[1] - a[2]*b[2] - a[3]*b[3]), + saturate_cast<_Tp>(a[0]*b[1] + a[1]*b[0] + a[2]*b[3] - a[3]*b[2]), + saturate_cast<_Tp>(a[0]*b[2] - a[1]*b[3] + a[2]*b[0] + a[3]*b[1]), + saturate_cast<_Tp>(a[0]*b[3] + a[1]*b[2] - a[2]*b[1] + a[3]*b[0])); +} + +template static inline +Scalar_<_Tp>& operator *= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a = a * b; + return a; +} + +template static inline +Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, _Tp alpha) +{ + return Scalar_<_Tp>(a.val[0] / alpha, + a.val[1] / alpha, + a.val[2] / alpha, + a.val[3] / alpha); +} + +template static inline +Scalar_ operator / (const Scalar_& a, float alpha) +{ + float s = 1 / alpha; + return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); +} + +template static inline +Scalar_ operator / (const Scalar_& a, double alpha) +{ + double s = 1 / alpha; + return Scalar_(a.val[0] * s, a.val[1] * s, a.val[2] * s, a.val[3] * s); +} + +template static inline +Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, _Tp alpha) +{ + a = a / alpha; + return a; +} + +template static inline +Scalar_<_Tp> operator / (_Tp a, const Scalar_<_Tp>& b) +{ + _Tp s = a / (b[0]*b[0] + b[1]*b[1] + b[2]*b[2] + b[3]*b[3]); + return b.conj() * s; +} + +template static inline +Scalar_<_Tp> operator / (const Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + return a * ((_Tp)1 / b); +} + +template static inline +Scalar_<_Tp>& operator /= (Scalar_<_Tp>& a, const Scalar_<_Tp>& b) +{ + a = a / b; + return a; +} + +template static inline +Scalar operator * (const Matx<_Tp, 4, 4>& a, const Scalar& b) +{ + Matx c((Matx)a, b, Matx_MatMulOp()); + return reinterpret_cast(c); +} + +template<> inline +Scalar operator * (const Matx& a, const Scalar& b) +{ + Matx c(a, b, Matx_MatMulOp()); + return reinterpret_cast(c); +} + + + +//////////////////////////////// KeyPoint /////////////////////////////// + +inline +KeyPoint::KeyPoint() + : pt(0,0), size(0), angle(-1), response(0), octave(0), class_id(-1) {} + +inline +KeyPoint::KeyPoint(Point2f _pt, float _size, float _angle, float _response, int _octave, int _class_id) + : pt(_pt), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} + +inline +KeyPoint::KeyPoint(float x, float y, float _size, float _angle, float _response, int _octave, int _class_id) + : pt(x, y), size(_size), angle(_angle), response(_response), octave(_octave), class_id(_class_id) {} + + + +///////////////////////////////// DMatch //////////////////////////////// + +inline +DMatch::DMatch() + : queryIdx(-1), trainIdx(-1), imgIdx(-1), distance(FLT_MAX) {} + +inline +DMatch::DMatch(int _queryIdx, int _trainIdx, float _distance) + : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(-1), distance(_distance) {} + +inline +DMatch::DMatch(int _queryIdx, int _trainIdx, int _imgIdx, float _distance) + : queryIdx(_queryIdx), trainIdx(_trainIdx), imgIdx(_imgIdx), distance(_distance) {} + +inline +bool DMatch::operator < (const DMatch &m) const +{ + return distance < m.distance; +} + + + +////////////////////////////// TermCriteria ///////////////////////////// + +inline +TermCriteria::TermCriteria() + : type(0), maxCount(0), epsilon(0) {} + +inline +TermCriteria::TermCriteria(int _type, int _maxCount, double _epsilon) + : type(_type), maxCount(_maxCount), epsilon(_epsilon) {} + +//! @endcond + +} // cv + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#endif //OPENCV_CORE_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/types_c.h b/3rdParty/opencv-4.11.0/opencv2/core/types_c.h index 473062a53f..02d4a4f680 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/types_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/core/types_c.h @@ -1,2110 +1,2110 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_TYPES_H -#define OPENCV_CORE_TYPES_H - -#ifdef CV__ENABLE_C_API_CTORS // invalid C API ctors (must be removed) -#if defined(_WIN32) && !defined(CV__SKIP_MESSAGE_MALFORMED_C_API_CTORS) -#error "C API ctors don't work on Win32: https://github.com/opencv/opencv/issues/15990" -#endif -#endif - -//#define CV__VALIDATE_UNUNITIALIZED_VARS 1 // C++11 & GCC only - -#ifdef __cplusplus - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#define CV_STRUCT_INITIALIZER {0,} -#else -#if defined(__GNUC__) && __GNUC__ == 4 // GCC 4.x warns on "= {}" initialization, fixed in GCC 5.0 -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#endif -#define CV_STRUCT_INITIALIZER {} -#endif - -#else -#define CV_STRUCT_INITIALIZER {0} -#endif - - -#ifdef HAVE_IPL -# ifndef __IPL_H__ -# if defined _WIN32 -# include -# else -# include -# endif -# endif -#elif defined __IPL_H__ -# define HAVE_IPL -#endif - -#include "opencv2/core/cvdef.h" - -#ifndef SKIP_INCLUDES -#include -#include -#include -#include -#endif // SKIP_INCLUDES - - - -#ifndef CV_DEFAULT -# ifdef __cplusplus -# define CV_DEFAULT(val) = val -# else -# define CV_DEFAULT(val) -# endif -#endif - -#ifndef CV_EXTERN_C_FUNCPTR -# ifdef __cplusplus -# define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } -# else -# define CV_EXTERN_C_FUNCPTR(x) typedef x -# endif -#endif - -#ifndef CVAPI -# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL -#endif - -#ifndef CV_IMPL -# define CV_IMPL CV_EXTERN_C -#endif - -#ifdef __cplusplus -# include "opencv2/core.hpp" -#endif - -/** @addtogroup core_c - @{ -*/ - -/** @brief This is the "metatype" used *only* as a function parameter. - -It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even -CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 -bytes of the header. In C++ interface the role of CvArr is played by InputArray and OutputArray. - */ -typedef void CvArr; - -typedef int CVStatus; - -/** @see cv::Error::Code */ -enum { - CV_StsOk= 0, /**< everything is ok */ - CV_StsBackTrace= -1, /**< pseudo error for back trace */ - CV_StsError= -2, /**< unknown /unspecified error */ - CV_StsInternal= -3, /**< internal error (bad state) */ - CV_StsNoMem= -4, /**< insufficient memory */ - CV_StsBadArg= -5, /**< function arg/param is bad */ - CV_StsBadFunc= -6, /**< unsupported function */ - CV_StsNoConv= -7, /**< iter. didn't converge */ - CV_StsAutoTrace= -8, /**< tracing */ - CV_HeaderIsNull= -9, /**< image header is NULL */ - CV_BadImageSize= -10, /**< image size is invalid */ - CV_BadOffset= -11, /**< offset is invalid */ - CV_BadDataPtr= -12, /**/ - CV_BadStep= -13, /**< image step is wrong, this may happen for a non-continuous matrix */ - CV_BadModelOrChSeq= -14, /**/ - CV_BadNumChannels= -15, /**< bad number of channels, for example, some functions accept only single channel matrices */ - CV_BadNumChannel1U= -16, /**/ - CV_BadDepth= -17, /**< input image depth is not supported by the function */ - CV_BadAlphaChannel= -18, /**/ - CV_BadOrder= -19, /**< number of dimensions is out of range */ - CV_BadOrigin= -20, /**< incorrect input origin */ - CV_BadAlign= -21, /**< incorrect input align */ - CV_BadCallBack= -22, /**/ - CV_BadTileSize= -23, /**/ - CV_BadCOI= -24, /**< input COI is not supported */ - CV_BadROISize= -25, /**< incorrect input roi */ - CV_MaskIsTiled= -26, /**/ - CV_StsNullPtr= -27, /**< null pointer */ - CV_StsVecLengthErr= -28, /**< incorrect vector length */ - CV_StsFilterStructContentErr= -29, /**< incorrect filter structure content */ - CV_StsKernelStructContentErr= -30, /**< incorrect transform kernel content */ - CV_StsFilterOffsetErr= -31, /**< incorrect filter offset value */ - CV_StsBadSize= -201, /**< the input/output structure size is incorrect */ - CV_StsDivByZero= -202, /**< division by zero */ - CV_StsInplaceNotSupported= -203, /**< in-place operation is not supported */ - CV_StsObjectNotFound= -204, /**< request can't be completed */ - CV_StsUnmatchedFormats= -205, /**< formats of input/output arrays differ */ - CV_StsBadFlag= -206, /**< flag is wrong or not supported */ - CV_StsBadPoint= -207, /**< bad CvPoint */ - CV_StsBadMask= -208, /**< bad format of mask (neither 8uC1 nor 8sC1)*/ - CV_StsUnmatchedSizes= -209, /**< sizes of input/output structures do not match */ - CV_StsUnsupportedFormat= -210, /**< the data format/type is not supported by the function*/ - CV_StsOutOfRange= -211, /**< some of parameters are out of range */ - CV_StsParseError= -212, /**< invalid syntax/structure of the parsed file */ - CV_StsNotImplemented= -213, /**< the requested function/feature is not implemented */ - CV_StsBadMemBlock= -214, /**< an allocated block has been corrupted */ - CV_StsAssert= -215, /**< assertion failed */ - CV_GpuNotSupported= -216, /**< no CUDA support */ - CV_GpuApiCallError= -217, /**< GPU API call error */ - CV_OpenGlNotSupported= -218, /**< no OpenGL support */ - CV_OpenGlApiCallError= -219, /**< OpenGL API call error */ - CV_OpenCLApiCallError= -220, /**< OpenCL API call error */ - CV_OpenCLDoubleNotSupported= -221, - CV_OpenCLInitError= -222, /**< OpenCL initialization error */ - CV_OpenCLNoAMDBlasFft= -223 -}; - -/****************************************************************************************\ -* Common macros and inline functions * -\****************************************************************************************/ - -/** absolute value without jumps */ -#ifndef __cplusplus -# define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) -#else -# define CV_IABS(a) abs(a) -#endif - - -#define cvInvSqrt(value) ((float)(1./sqrt(value))) -#define cvSqrt(value) ((float)sqrt(value)) - - -/*************** Random number generation *******************/ - -typedef uint64 CvRNG; - -#define CV_RNG_COEFF 4164903690U - -/** @brief Initializes a random number generator state. - -The function initializes a random number generator and returns the state. The pointer to the state -can be then passed to the cvRandInt, cvRandReal and cvRandArr functions. In the current -implementation a multiply-with-carry generator is used. -@param seed 64-bit value used to initiate a random sequence -@sa the C++ class RNG replaced CvRNG. - */ -CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1)) -{ - CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1; - return rng; -} - -/** @brief Returns a 32-bit unsigned integer and updates RNG. - -The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG -state. It is similar to the rand() function from the C runtime library, except that OpenCV functions -always generates a 32-bit random number, regardless of the platform. -@param rng CvRNG state initialized by cvRNG. - */ -CV_INLINE unsigned cvRandInt( CvRNG* rng ) -{ - uint64 temp = *rng; - temp = (uint64)(unsigned)temp*CV_RNG_COEFF + (temp >> 32); - *rng = temp; - return (unsigned)temp; -} - -/** @brief Returns a floating-point random number and updates RNG. - -The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not -included). -@param rng RNG state initialized by cvRNG - */ -CV_INLINE double cvRandReal( CvRNG* rng ) -{ - return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */; -} - -/****************************************************************************************\ -* Image type (IplImage) * -\****************************************************************************************/ - -#ifndef HAVE_IPL - -/* - * The following definitions (until #endif) - * is an extract from IPL headers. - * Copyright (c) 1995 Intel Corporation. - */ -#define IPL_DEPTH_SIGN 0x80000000 - -#define IPL_DEPTH_1U 1 -#define IPL_DEPTH_8U 8 -#define IPL_DEPTH_16U 16 -#define IPL_DEPTH_32F 32 - -#define IPL_DEPTH_8S (IPL_DEPTH_SIGN| 8) -#define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16) -#define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32) - -#define IPL_DATA_ORDER_PIXEL 0 -#define IPL_DATA_ORDER_PLANE 1 - -#define IPL_ORIGIN_TL 0 -#define IPL_ORIGIN_BL 1 - -#define IPL_ALIGN_4BYTES 4 -#define IPL_ALIGN_8BYTES 8 -#define IPL_ALIGN_16BYTES 16 -#define IPL_ALIGN_32BYTES 32 - -#define IPL_ALIGN_DWORD IPL_ALIGN_4BYTES -#define IPL_ALIGN_QWORD IPL_ALIGN_8BYTES - -#define IPL_BORDER_CONSTANT 0 -#define IPL_BORDER_REPLICATE 1 -#define IPL_BORDER_REFLECT 2 -#define IPL_BORDER_WRAP 3 - -#ifdef __cplusplus -typedef struct _IplImage IplImage; -CV_EXPORTS _IplImage cvIplImage(const cv::Mat& m); -#endif - -/** The IplImage is taken from the Intel Image Processing Library, in which the format is native. OpenCV -only supports a subset of possible IplImage formats, as outlined in the parameter list above. - -In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require -that the image size or ROI size of all source and destination images match exactly. On the other -hand, the Intel Image Processing Library processes the area of intersection between the source and -destination images (or ROIs), allowing them to vary independently. -*/ -typedef struct -_IplImage -{ - int nSize; /**< sizeof(IplImage) */ - int ID; /**< version (=0)*/ - int nChannels; /**< Most of OpenCV functions support 1,2,3 or 4 channels */ - int alphaChannel; /**< Ignored by OpenCV */ - int depth; /**< Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, - IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */ - char colorModel[4]; /**< Ignored by OpenCV */ - char channelSeq[4]; /**< ditto */ - int dataOrder; /**< 0 - interleaved color channels, 1 - separate color channels. - cvCreateImage can only create interleaved images */ - int origin; /**< 0 - top-left origin, - 1 - bottom-left origin (Windows bitmaps style). */ - int align; /**< Alignment of image rows (4 or 8). - OpenCV ignores it and uses widthStep instead. */ - int width; /**< Image width in pixels. */ - int height; /**< Image height in pixels. */ - struct _IplROI *roi; /**< Image ROI. If NULL, the whole image is selected. */ - struct _IplImage *maskROI; /**< Must be NULL. */ - void *imageId; /**< " " */ - struct _IplTileInfo *tileInfo; /**< " " */ - int imageSize; /**< Image data size in bytes - (==image->height*image->widthStep - in case of interleaved data)*/ - char *imageData; /**< Pointer to aligned image data. */ - int widthStep; /**< Size of aligned image row in bytes. */ - int BorderMode[4]; /**< Ignored by OpenCV. */ - int BorderConst[4]; /**< Ditto. */ - char *imageDataOrigin; /**< Pointer to very origin of image data - (not necessarily aligned) - - needed for correct deallocation */ - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - _IplImage() - { - memset(this, 0, sizeof(*this)); // valid for POD structure - nSize = sizeof(IplImage); - } - _IplImage(const cv::Mat& m) { *this = cvIplImage(m); } -#endif -} -IplImage; - -CV_INLINE IplImage cvIplImage() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - IplImage self = CV_STRUCT_INITIALIZER; self.nSize = sizeof(IplImage); return self; -#else - return _IplImage(); -#endif -} - -typedef struct _IplTileInfo IplTileInfo; - -typedef struct _IplROI -{ - int coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ - int xOffset; - int yOffset; - int width; - int height; -} -IplROI; - -typedef struct _IplConvKernel -{ - int nCols; - int nRows; - int anchorX; - int anchorY; - int *values; - int nShiftR; -} -IplConvKernel; - -typedef struct _IplConvKernelFP -{ - int nCols; - int nRows; - int anchorX; - int anchorY; - float *values; -} -IplConvKernelFP; - -#define IPL_IMAGE_HEADER 1 -#define IPL_IMAGE_DATA 2 -#define IPL_IMAGE_ROI 4 - -#endif/*HAVE_IPL*/ - -/** extra border mode */ -#define IPL_BORDER_REFLECT_101 4 -#define IPL_BORDER_TRANSPARENT 5 - -#define IPL_IMAGE_MAGIC_VAL ((int)sizeof(IplImage)) -#define CV_TYPE_NAME_IMAGE "opencv-image" - -#define CV_IS_IMAGE_HDR(img) \ - ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage)) - -#define CV_IS_IMAGE(img) \ - (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) - -/** for storing double-precision - floating point data in IplImage's */ -#define IPL_DEPTH_64F 64 - -/** get reference to pixel at (col,row), - for multi-channel images (col) should be multiplied by number of channels */ -#define CV_IMAGE_ELEM( image, elemtype, row, col ) \ - (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) - -/****************************************************************************************\ -* Matrix type (CvMat) * -\****************************************************************************************/ - -#define CV_AUTO_STEP 0x7fffffff -#define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) - -#define CV_MAGIC_MASK 0xFFFF0000 -#define CV_MAT_MAGIC_VAL 0x42420000 -#define CV_TYPE_NAME_MAT "opencv-matrix" - -#ifdef __cplusplus -typedef struct CvMat CvMat; -CV_INLINE CvMat cvMat(const cv::Mat& m); -#endif - -/** Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column -index) of a matrix can be retrieved or modified using CV_MAT_ELEM macro: - - uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j) - CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f; - -To access multiple-channel matrices, you can use -CV_MAT_ELEM(matrix, type, i, j\*nchannels + channel_idx). - -@deprecated CvMat is now obsolete; consider using Mat instead. - */ -typedef struct CvMat -{ - int type; - int step; - - /* for internal use only */ - int* refcount; - int hdr_refcount; - - union - { - uchar* ptr; - short* s; - int* i; - float* fl; - double* db; - } data; - -#ifdef __cplusplus - union - { - int rows; - int height; - }; - - union - { - int cols; - int width; - }; -#else - int rows; - int cols; -#endif - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvMat() {} - CvMat(const cv::Mat& m) { *this = cvMat(m); } -#endif -} -CvMat; - - -#define CV_IS_MAT_HDR(mat) \ - ((mat) != NULL && \ - (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ - ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0) - -#define CV_IS_MAT_HDR_Z(mat) \ - ((mat) != NULL && \ - (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ - ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0) - -#define CV_IS_MAT(mat) \ - (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL) - -#define CV_IS_MASK_ARR(mat) \ - (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0) - -#define CV_ARE_TYPES_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0) - -#define CV_ARE_CNS_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0) - -#define CV_ARE_DEPTHS_EQ(mat1, mat2) \ - ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0) - -#define CV_ARE_SIZES_EQ(mat1, mat2) \ - ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols) - -#define CV_IS_MAT_CONST(mat) \ - (((mat)->rows|(mat)->cols) == 1) - -#define IPL2CV_DEPTH(depth) \ - ((((CV_8U)+(CV_16U<<4)+(CV_32F<<8)+(CV_64F<<16)+(CV_8S<<20)+ \ - (CV_16S<<24)+(CV_32S<<28)) >> ((((depth) & 0xF0) >> 2) + \ - (((depth) & IPL_DEPTH_SIGN) ? 20 : 0))) & 15) - -/** Inline constructor. No data is allocated internally!!! - * (Use together with cvCreateData, or use cvCreateMat instead to - * get a matrix with allocated data): - */ -CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL)) -{ - CvMat m; - - assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F ); - type = CV_MAT_TYPE(type); - m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type; - m.cols = cols; - m.rows = rows; - m.step = m.cols*CV_ELEM_SIZE(type); - m.data.ptr = (uchar*)data; - m.refcount = NULL; - m.hdr_refcount = 0; - - return m; -} - -#ifdef __cplusplus - -CV_INLINE CvMat cvMat(const cv::Mat& m) -{ - CvMat self; - CV_DbgAssert(m.dims <= 2); - self = cvMat(m.rows, m.dims == 1 ? 1 : m.cols, m.type(), m.data); - self.step = (int)m.step[0]; - self.type = (self.type & ~cv::Mat::CONTINUOUS_FLAG) | (m.flags & cv::Mat::CONTINUOUS_FLAG); - return self; -} -CV_INLINE CvMat cvMat() -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMat self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMat(); -#endif -} -CV_INLINE CvMat cvMat(const CvMat& m) -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMat self = CV_STRUCT_INITIALIZER; memcpy(&self, &m, sizeof(self)); return self; -#else - return CvMat(m); -#endif -} - -#endif // __cplusplus - - -#define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size ) \ - (assert( (unsigned)(row) < (unsigned)(mat).rows && \ - (unsigned)(col) < (unsigned)(mat).cols ), \ - (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col)) - -#define CV_MAT_ELEM_PTR( mat, row, col ) \ - CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) ) - -#define CV_MAT_ELEM( mat, elemtype, row, col ) \ - (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype))) - -/** @brief Returns the particular element of single-channel floating-point matrix. - -The function is a fast replacement for cvGetReal2D in the case of single-channel floating-point -matrices. It is faster because it is inline, it does fewer checks for array type and array element -type, and it checks for the row and column ranges only in debug mode. -@param mat Input matrix -@param row The zero-based index of row -@param col The zero-based index of column - */ -CV_INLINE double cvmGet( const CvMat* mat, int row, int col ) -{ - int type; - - type = CV_MAT_TYPE(mat->type); - assert( (unsigned)row < (unsigned)mat->rows && - (unsigned)col < (unsigned)mat->cols ); - - if( type == CV_32FC1 ) - return ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; - else - { - assert( type == CV_64FC1 ); - return ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; - } -} - -/** @brief Sets a specific element of a single-channel floating-point matrix. - -The function is a fast replacement for cvSetReal2D in the case of single-channel floating-point -matrices. It is faster because it is inline, it does fewer checks for array type and array element -type, and it checks for the row and column ranges only in debug mode. -@param mat The matrix -@param row The zero-based index of row -@param col The zero-based index of column -@param value The new value of the matrix element - */ -CV_INLINE void cvmSet( CvMat* mat, int row, int col, double value ) -{ - int type; - type = CV_MAT_TYPE(mat->type); - assert( (unsigned)row < (unsigned)mat->rows && - (unsigned)col < (unsigned)mat->cols ); - - if( type == CV_32FC1 ) - ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value; - else - { - assert( type == CV_64FC1 ); - ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = value; - } -} - - -CV_INLINE int cvIplDepth( int type ) -{ - int depth = CV_MAT_DEPTH(type); - return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S || - depth == CV_32S ? IPL_DEPTH_SIGN : 0); -} - - -/****************************************************************************************\ -* Multi-dimensional dense array (CvMatND) * -\****************************************************************************************/ - -#define CV_MATND_MAGIC_VAL 0x42430000 -#define CV_TYPE_NAME_MATND "opencv-nd-matrix" - -#ifdef __cplusplus -typedef struct CvMatND CvMatND; -CV_EXPORTS CvMatND cvMatND(const cv::Mat& m); -#endif - -/** - @deprecated consider using cv::Mat instead - */ -typedef struct -CvMatND -{ - int type; - int dims; - - int* refcount; - int hdr_refcount; - - union - { - uchar* ptr; - float* fl; - double* db; - int* i; - short* s; - } data; - - struct - { - int size; - int step; - } - dim[CV_MAX_DIM]; - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvMatND() {} - CvMatND(const cv::Mat& m) { *this = cvMatND(m); } -#endif -} -CvMatND; - - -CV_INLINE CvMatND cvMatND() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvMatND self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMatND(); -#endif -} - -#define CV_IS_MATND_HDR(mat) \ - ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL) - -#define CV_IS_MATND(mat) \ - (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL) - - -/****************************************************************************************\ -* Multi-dimensional sparse array (CvSparseMat) * -\****************************************************************************************/ - -#define CV_SPARSE_MAT_MAGIC_VAL 0x42440000 -#define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix" - -struct CvSet; - -typedef struct CvSparseMat -{ - int type; - int dims; - int* refcount; - int hdr_refcount; - - struct CvSet* heap; - void** hashtable; - int hashsize; - int valoffset; - int idxoffset; - int size[CV_MAX_DIM]; - -#ifdef __cplusplus - CV_EXPORTS void copyToSparseMat(cv::SparseMat& m) const; -#endif -} -CvSparseMat; - -#ifdef __cplusplus -CV_EXPORTS CvSparseMat* cvCreateSparseMat(const cv::SparseMat& m); -#endif - -#define CV_IS_SPARSE_MAT_HDR(mat) \ - ((mat) != NULL && \ - (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL) - -#define CV_IS_SPARSE_MAT(mat) \ - CV_IS_SPARSE_MAT_HDR(mat) - -/**************** iteration through a sparse array *****************/ - -typedef struct CvSparseNode -{ - unsigned hashval; - struct CvSparseNode* next; -} -CvSparseNode; - -typedef struct CvSparseMatIterator -{ - CvSparseMat* mat; - CvSparseNode* node; - int curidx; -} -CvSparseMatIterator; - -#define CV_NODE_VAL(mat,node) ((void*)((uchar*)(node) + (mat)->valoffset)) -#define CV_NODE_IDX(mat,node) ((int*)((uchar*)(node) + (mat)->idxoffset)) - -/****************************************************************************************\ -* Histogram * -\****************************************************************************************/ - -typedef int CvHistType; - -#define CV_HIST_MAGIC_VAL 0x42450000 -#define CV_HIST_UNIFORM_FLAG (1 << 10) - -/** indicates whether bin ranges are set already or not */ -#define CV_HIST_RANGES_FLAG (1 << 11) - -#define CV_HIST_ARRAY 0 -#define CV_HIST_SPARSE 1 -#define CV_HIST_TREE CV_HIST_SPARSE - -/** should be used as a parameter only, - it turns to CV_HIST_UNIFORM_FLAG of hist->type */ -#define CV_HIST_UNIFORM 1 - -typedef struct CvHistogram -{ - int type; - CvArr* bins; - float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ - float** thresh2; /**< For non-uniform histograms. */ - CvMatND mat; /**< Embedded matrix header for array histograms. */ -} -CvHistogram; - -#define CV_IS_HIST( hist ) \ - ((hist) != NULL && \ - (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \ - (hist)->bins != NULL) - -#define CV_IS_UNIFORM_HIST( hist ) \ - (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0) - -#define CV_IS_SPARSE_HIST( hist ) \ - CV_IS_SPARSE_MAT((hist)->bins) - -#define CV_HIST_HAS_RANGES( hist ) \ - (((hist)->type & CV_HIST_RANGES_FLAG) != 0) - -/****************************************************************************************\ -* Other supplementary data type definitions * -\****************************************************************************************/ - -/*************************************** CvRect *****************************************/ -/** @sa Rect_ */ -typedef struct CvRect -{ - int x; - int y; - int width; - int height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvRect() __attribute__(( warning("Non-initialized variable") )) {}; - template CvRect(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 4); - x = y = width = height = 0; - if (list.size() == 4) - { - x = list.begin()[0]; y = list.begin()[1]; width = list.begin()[2]; height = list.begin()[3]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvRect(int _x = 0, int _y = 0, int w = 0, int h = 0): x(_x), y(_y), width(w), height(h) {} - template - CvRect(const cv::Rect_<_Tp>& r): x(cv::saturate_cast(r.x)), y(cv::saturate_cast(r.y)), width(cv::saturate_cast(r.width)), height(cv::saturate_cast(r.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Rect_<_Tp>() const { return cv::Rect_<_Tp>((_Tp)x, (_Tp)y, (_Tp)width, (_Tp)height); } -#endif -} -CvRect; - -/** constructs CvRect structure. */ -CV_INLINE CvRect cvRect( int x, int y, int width, int height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvRect r = {x, y, width, height}; -#else - CvRect r(x, y , width, height); -#endif - return r; -} -#ifdef __cplusplus -CV_INLINE CvRect cvRect(const cv::Rect& rc) { return cvRect(rc.x, rc.y, rc.width, rc.height); } -#endif - -CV_INLINE IplROI cvRectToROI( CvRect rect, int coi ) -{ - IplROI roi; - roi.xOffset = rect.x; - roi.yOffset = rect.y; - roi.width = rect.width; - roi.height = rect.height; - roi.coi = coi; - - return roi; -} - - -CV_INLINE CvRect cvROIToRect( IplROI roi ) -{ - return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height ); -} - -/*********************************** CvTermCriteria *************************************/ - -#define CV_TERMCRIT_ITER 1 -#define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER -#define CV_TERMCRIT_EPS 2 - -/** @sa TermCriteria - */ -typedef struct CvTermCriteria -{ - int type; /**< may be combination of - CV_TERMCRIT_ITER - CV_TERMCRIT_EPS */ - int max_iter; - double epsilon; -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvTermCriteria(int _type = 0, int _iter = 0, double _eps = 0) : type(_type), max_iter(_iter), epsilon(_eps) {} - CvTermCriteria(const cv::TermCriteria& t) : type(t.type), max_iter(t.maxCount), epsilon(t.epsilon) {} -#endif -#ifdef __cplusplus - operator cv::TermCriteria() const { return cv::TermCriteria(type, max_iter, epsilon); } -#endif -} -CvTermCriteria; - -CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvTermCriteria t = { type, max_iter, (float)epsilon}; -#else - CvTermCriteria t(type, max_iter, epsilon); -#endif - return t; -} -#ifdef __cplusplus -CV_INLINE CvTermCriteria cvTermCriteria(const cv::TermCriteria& t) { return cvTermCriteria(t.type, t.maxCount, t.epsilon); } -#endif - - -/******************************* CvPoint and variants ***********************************/ - -typedef struct CvPoint -{ - int x; - int y; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint(int _x = 0, int _y = 0): x(_x), y(_y) {} - template - CvPoint(const cv::Point_<_Tp>& pt): x((int)pt.x), y((int)pt.y) {} -#endif -#ifdef __cplusplus - template - operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } -#endif -} -CvPoint; - -/** constructs CvPoint structure. */ -CV_INLINE CvPoint cvPoint( int x, int y ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint p = {x, y}; -#else - CvPoint p(x, y); -#endif - return p; -} -#ifdef __cplusplus -CV_INLINE CvPoint cvPoint(const cv::Point& pt) { return cvPoint(pt.x, pt.y); } -#endif - -typedef struct CvPoint2D32f -{ - float x; - float y; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint2D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint2D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint2D32f(float _x = 0, float _y = 0): x(_x), y(_y) {} - template - CvPoint2D32f(const cv::Point_<_Tp>& pt): x((float)pt.x), y((float)pt.y) {} -#endif -#ifdef __cplusplus - template - operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } -#endif -} -CvPoint2D32f; - -/** constructs CvPoint2D32f structure. */ -CV_INLINE CvPoint2D32f cvPoint2D32f( double x, double y ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint2D32f p = { (float)x, (float)y }; -#else - CvPoint2D32f p((float)x, (float)y); -#endif - return p; -} - -#ifdef __cplusplus -template -CvPoint2D32f cvPoint2D32f(const cv::Point_<_Tp>& pt) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint2D32f p = { (float)pt.x, (float)pt.y }; -#else - CvPoint2D32f p((float)pt.x, (float)pt.y); -#endif - return p; -} -#endif - -/** converts CvPoint to CvPoint2D32f. */ -CV_INLINE CvPoint2D32f cvPointTo32f( CvPoint point ) -{ - return cvPoint2D32f( (float)point.x, (float)point.y ); -} - -/** converts CvPoint2D32f to CvPoint. */ -CV_INLINE CvPoint cvPointFrom32f( CvPoint2D32f point ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint ipt = { cvRound(point.x), cvRound(point.y) }; -#else - CvPoint ipt(cvRound(point.x), cvRound(point.y)); -#endif - return ipt; -} - - -typedef struct CvPoint3D32f -{ - float x; - float y; - float z; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint3D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint3D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 3); - x = y = z = 0; - if (list.size() == 3) - { - x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvPoint3D32f(float _x = 0, float _y = 0, float _z = 0): x(_x), y(_y), z(_z) {} - template - CvPoint3D32f(const cv::Point3_<_Tp>& pt): x((float)pt.x), y((float)pt.y), z((float)pt.z) {} -#endif -#ifdef __cplusplus - template - operator cv::Point3_<_Tp>() const { return cv::Point3_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y), cv::saturate_cast<_Tp>(z)); } -#endif -} -CvPoint3D32f; - -/** constructs CvPoint3D32f structure. */ -CV_INLINE CvPoint3D32f cvPoint3D32f( double x, double y, double z ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint3D32f p = { (float)x, (float)y, (float)z }; -#else - CvPoint3D32f p((float)x, (float)y, (float)z); -#endif - return p; -} - -#ifdef __cplusplus -template -CvPoint3D32f cvPoint3D32f(const cv::Point3_<_Tp>& pt) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvPoint3D32f p = { (float)pt.x, (float)pt.y, (float)pt.z }; -#else - CvPoint3D32f p((float)pt.x, (float)pt.y, (float)pt.z); -#endif - return p; -} -#endif - - -typedef struct CvPoint2D64f -{ - double x; - double y; -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint2D64f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint2D64f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - x = y = 0; - if (list.size() == 2) - { - x = list.begin()[0]; y = list.begin()[1]; - } - }; -#endif -} -CvPoint2D64f; - -/** constructs CvPoint2D64f structure.*/ -CV_INLINE CvPoint2D64f cvPoint2D64f( double x, double y ) -{ - CvPoint2D64f p = { x, y }; - return p; -} - - -typedef struct CvPoint3D64f -{ - double x; - double y; - double z; -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvPoint3D64f() __attribute__(( warning("Non-initialized variable") )) {} - template CvPoint3D64f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 3); - x = y = z = 0; - if (list.size() == 3) - { - x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; - } - }; -#endif -} -CvPoint3D64f; - -/** constructs CvPoint3D64f structure. */ -CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) -{ - CvPoint3D64f p = { x, y, z }; - return p; -} - - -/******************************** CvSize's & CvBox **************************************/ - -typedef struct CvSize -{ - int width; - int height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSize() __attribute__(( warning("Non-initialized variable") )) {} - template CvSize(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - width = 0; height = 0; - if (list.size() == 2) - { - width = list.begin()[0]; height = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvSize(int w = 0, int h = 0): width(w), height(h) {} - template - CvSize(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } -#endif -} -CvSize; - -/** constructs CvSize structure. */ -CV_INLINE CvSize cvSize( int width, int height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize s = { width, height }; -#else - CvSize s(width, height); -#endif - return s; -} - -#ifdef __cplusplus -CV_INLINE CvSize cvSize(const cv::Size& sz) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize s = { sz.width, sz.height }; -#else - CvSize s(sz.width, sz.height); -#endif - return s; -} -#endif - -typedef struct CvSize2D32f -{ - float width; - float height; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSize2D32f() __attribute__(( warning("Non-initialized variable") )) {} - template CvSize2D32f(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - width = 0; height = 0; - if (list.size() == 2) - { - width = list.begin()[0]; height = list.begin()[1]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvSize2D32f(float w = 0, float h = 0): width(w), height(h) {} - template - CvSize2D32f(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} -#endif -#ifdef __cplusplus - template - operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } -#endif -} -CvSize2D32f; - -/** constructs CvSize2D32f structure. */ -CV_INLINE CvSize2D32f cvSize2D32f( double width, double height ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize2D32f s = { (float)width, (float)height }; -#else - CvSize2D32f s((float)width, (float)height); -#endif - return s; -} -#ifdef __cplusplus -template -CvSize2D32f cvSize2D32f(const cv::Size_<_Tp>& sz) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvSize2D32f s = { (float)sz.width, (float)sz.height }; -#else - CvSize2D32f s((float)sz.width, (float)sz.height); -#endif - return s; -} -#endif - -/** @sa RotatedRect - */ -typedef struct CvBox2D -{ - CvPoint2D32f center; /**< Center of the box. */ - CvSize2D32f size; /**< Box width and length. */ - float angle; /**< Angle between the horizontal axis */ - /**< and the first side (i.e. length) in degrees */ - -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) : center(c), size(s), angle(a) {} - CvBox2D(const cv::RotatedRect& rr) : center(rr.center), size(rr.size), angle(rr.angle) {} -#endif -#ifdef __cplusplus - operator cv::RotatedRect() const { return cv::RotatedRect(center, size, angle); } -#endif -} -CvBox2D; - - -#ifdef __cplusplus -CV_INLINE CvBox2D cvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) -{ - CvBox2D self; - self.center = c; - self.size = s; - self.angle = a; - return self; -} -CV_INLINE CvBox2D cvBox2D(const cv::RotatedRect& rr) -{ - CvBox2D self; - self.center = cvPoint2D32f(rr.center); - self.size = cvSize2D32f(rr.size); - self.angle = rr.angle; - return self; -} -#endif - - -/** Line iterator state: */ -typedef struct CvLineIterator -{ - /** Pointer to the current point: */ - uchar* ptr; - - /* Bresenham algorithm state: */ - int err; - int plus_delta; - int minus_delta; - int plus_step; - int minus_step; -} -CvLineIterator; - - - -/************************************* CvSlice ******************************************/ -#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff -#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) - -typedef struct CvSlice -{ - int start_index, end_index; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvSlice() __attribute__(( warning("Non-initialized variable") )) {} - template CvSlice(const std::initializer_list<_Tp> list) - { - CV_Assert(list.size() == 0 || list.size() == 2); - start_index = end_index = 0; - if (list.size() == 2) - { - start_index = list.begin()[0]; end_index = list.begin()[1]; - } - }; -#endif -#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__) - CvSlice(int start = 0, int end = 0) : start_index(start), end_index(end) {} - CvSlice(const cv::Range& r) { *this = (r.start != INT_MIN && r.end != INT_MAX) ? CvSlice(r.start, r.end) : CvSlice(0, CV_WHOLE_SEQ_END_INDEX); } - operator cv::Range() const { return (start_index == 0 && end_index == CV_WHOLE_SEQ_END_INDEX ) ? cv::Range::all() : cv::Range(start_index, end_index); } -#endif -} -CvSlice; - -CV_INLINE CvSlice cvSlice( int start, int end ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__)) - CvSlice slice = { start, end }; -#else - CvSlice slice(start, end); -#endif - return slice; -} - -#if defined(__cplusplus) -CV_INLINE CvSlice cvSlice(const cv::Range& r) -{ - CvSlice slice = (r.start != INT_MIN && r.end != INT_MAX) ? cvSlice(r.start, r.end) : cvSlice(0, CV_WHOLE_SEQ_END_INDEX); - return slice; -} -#endif - - -/************************************* CvScalar *****************************************/ -/** @sa Scalar_ - */ -typedef struct CvScalar -{ - double val[4]; - -#ifdef CV__VALIDATE_UNUNITIALIZED_VARS - CvScalar() __attribute__(( warning("Non-initialized variable") )) {} - CvScalar(const std::initializer_list list) - { - CV_Assert(list.size() == 0 || list.size() == 4); - val[0] = val[1] = val[2] = val[3] = 0; - if (list.size() == 4) - { - val[0] = list.begin()[0]; val[1] = list.begin()[1]; val[2] = list.begin()[2]; val[3] = list.begin()[3]; - } - }; -#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) - CvScalar() {} - CvScalar(double d0, double d1 = 0, double d2 = 0, double d3 = 0) { val[0] = d0; val[1] = d1; val[2] = d2; val[3] = d3; } - template - CvScalar(const cv::Scalar_<_Tp>& s) { val[0] = s.val[0]; val[1] = s.val[1]; val[2] = s.val[2]; val[3] = s.val[3]; } - template - CvScalar(const cv::Vec<_Tp, cn>& v) - { - int i; - for( i = 0; i < (cn < 4 ? cn : 4); i++ ) val[i] = v.val[i]; - for( ; i < 4; i++ ) val[i] = 0; - } -#endif -#ifdef __cplusplus - template - operator cv::Scalar_<_Tp>() const { return cv::Scalar_<_Tp>(cv::saturate_cast<_Tp>(val[0]), cv::saturate_cast<_Tp>(val[1]), cv::saturate_cast<_Tp>(val[2]), cv::saturate_cast<_Tp>(val[3])); } -#endif -} -CvScalar; - -CV_INLINE CvScalar cvScalar( double val0, double val1 CV_DEFAULT(0), - double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0)) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0; scalar.val[1] = val1; - scalar.val[2] = val2; scalar.val[3] = val3; - return scalar; -} - -#ifdef __cplusplus -CV_INLINE CvScalar cvScalar() -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - return scalar; -} -CV_INLINE CvScalar cvScalar(const cv::Scalar& s) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = s.val[0]; - scalar.val[1] = s.val[1]; - scalar.val[2] = s.val[2]; - scalar.val[3] = s.val[3]; - return scalar; -} -#endif - -CV_INLINE CvScalar cvRealScalar( double val0 ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0; - scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; - return scalar; -} - -CV_INLINE CvScalar cvScalarAll( double val0123 ) -{ -#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) - CvScalar scalar = CV_STRUCT_INITIALIZER; -#else - CvScalar scalar; -#endif - scalar.val[0] = val0123; - scalar.val[1] = val0123; - scalar.val[2] = val0123; - scalar.val[3] = val0123; - return scalar; -} - -/****************************************************************************************\ -* Dynamic Data structures * -\****************************************************************************************/ - -/******************************** Memory storage ****************************************/ - -typedef struct CvMemBlock -{ - struct CvMemBlock* prev; - struct CvMemBlock* next; -} -CvMemBlock; - -#define CV_STORAGE_MAGIC_VAL 0x42890000 - -typedef struct CvMemStorage -{ - int signature; - CvMemBlock* bottom; /**< First allocated block. */ - CvMemBlock* top; /**< Current memory block - top of the stack. */ - struct CvMemStorage* parent; /**< We get new blocks from parent as needed. */ - int block_size; /**< Block size. */ - int free_space; /**< Remaining free space in current block. */ -} -CvMemStorage; - -#define CV_IS_STORAGE(storage) \ - ((storage) != NULL && \ - (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL) - - -typedef struct CvMemStoragePos -{ - CvMemBlock* top; - int free_space; -} -CvMemStoragePos; - - -/*********************************** Sequence *******************************************/ - -typedef struct CvSeqBlock -{ - struct CvSeqBlock* prev; /**< Previous sequence block. */ - struct CvSeqBlock* next; /**< Next sequence block. */ - int start_index; /**< Index of the first element in the block + */ - /**< sequence->first->start_index. */ - int count; /**< Number of elements in the block. */ - schar* data; /**< Pointer to the first element of the block. */ -} -CvSeqBlock; - - -#define CV_TREE_NODE_FIELDS(node_type) \ - int flags; /**< Miscellaneous flags. */ \ - int header_size; /**< Size of sequence header. */ \ - struct node_type* h_prev; /**< Previous sequence. */ \ - struct node_type* h_next; /**< Next sequence. */ \ - struct node_type* v_prev; /**< 2nd previous sequence. */ \ - struct node_type* v_next /**< 2nd next sequence. */ - -/** - Read/Write sequence. - Elements can be dynamically inserted to or deleted from the sequence. -*/ -#define CV_SEQUENCE_FIELDS() \ - CV_TREE_NODE_FIELDS(CvSeq); \ - int total; /**< Total number of elements. */ \ - int elem_size; /**< Size of sequence element in bytes. */ \ - schar* block_max; /**< Maximal bound of the last block. */ \ - schar* ptr; /**< Current write pointer. */ \ - int delta_elems; /**< Grow seq this many at a time. */ \ - CvMemStorage* storage; /**< Where the seq is stored. */ \ - CvSeqBlock* free_blocks; /**< Free blocks list. */ \ - CvSeqBlock* first; /**< Pointer to the first sequence block. */ - -typedef struct CvSeq -{ - CV_SEQUENCE_FIELDS() -} -CvSeq; - -#define CV_TYPE_NAME_SEQ "opencv-sequence" -#define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" - -/*************************************** Set ********************************************/ -/** @brief Set - Order is not preserved. There can be gaps between sequence elements. - After the element has been inserted it stays in the same place all the time. - The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. -*/ -#define CV_SET_ELEM_FIELDS(elem_type) \ - int flags; \ - struct elem_type* next_free; - -typedef struct CvSetElem -{ - CV_SET_ELEM_FIELDS(CvSetElem) -} -CvSetElem; - -#define CV_SET_FIELDS() \ - CV_SEQUENCE_FIELDS() \ - CvSetElem* free_elems; \ - int active_count; - -typedef struct CvSet -{ - CV_SET_FIELDS() -} -CvSet; - - -#define CV_SET_ELEM_IDX_MASK ((1 << 26) - 1) -#define CV_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) - -/** Checks whether the element pointed by ptr belongs to a set or not */ -#define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) - -/************************************* Graph ********************************************/ - -/** @name Graph - -We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, -pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in -another set. There is a singly-linked list of incoming/outcoming edges for each vertex. - -Each edge consists of: - -- Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively). - - A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not -distinguished during search operations. - -- Two pointers to next edges for the starting and ending vertices, where next[0] points to the -next edge in the vtx[0] adjacency list and next[1] points to the next edge in the vtx[1] -adjacency list. - -@see CvGraphEdge, CvGraphVtx, CvGraphVtx2D, CvGraph -@{ -*/ -#define CV_GRAPH_EDGE_FIELDS() \ - int flags; \ - float weight; \ - struct CvGraphEdge* next[2]; \ - struct CvGraphVtx* vtx[2]; - - -#define CV_GRAPH_VERTEX_FIELDS() \ - int flags; \ - struct CvGraphEdge* first; - - -typedef struct CvGraphEdge -{ - CV_GRAPH_EDGE_FIELDS() -} -CvGraphEdge; - -typedef struct CvGraphVtx -{ - CV_GRAPH_VERTEX_FIELDS() -} -CvGraphVtx; - -typedef struct CvGraphVtx2D -{ - CV_GRAPH_VERTEX_FIELDS() - CvPoint2D32f* ptr; -} -CvGraphVtx2D; - -/** - Graph is "derived" from the set (this is set a of vertices) - and includes another set (edges) -*/ -#define CV_GRAPH_FIELDS() \ - CV_SET_FIELDS() \ - CvSet* edges; - -typedef struct CvGraph -{ - CV_GRAPH_FIELDS() -} -CvGraph; - -#define CV_TYPE_NAME_GRAPH "opencv-graph" - -/** @} */ - -/*********************************** Chain/Contour *************************************/ - -typedef struct CvChain -{ - CV_SEQUENCE_FIELDS() - CvPoint origin; -} -CvChain; - -#define CV_CONTOUR_FIELDS() \ - CV_SEQUENCE_FIELDS() \ - CvRect rect; \ - int color; \ - int reserved[3]; - -typedef struct CvContour -{ - CV_CONTOUR_FIELDS() -} -CvContour; - -typedef CvContour CvPoint2DSeq; - -/****************************************************************************************\ -* Sequence types * -\****************************************************************************************/ - -#define CV_SEQ_MAGIC_VAL 0x42990000 - -#define CV_IS_SEQ(seq) \ - ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL) - -#define CV_SET_MAGIC_VAL 0x42980000 -#define CV_IS_SET(set) \ - ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL) - -#define CV_SEQ_ELTYPE_BITS 12 -#define CV_SEQ_ELTYPE_MASK ((1 << CV_SEQ_ELTYPE_BITS) - 1) - -#define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */ -#define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */ -#define CV_SEQ_ELTYPE_GENERIC 0 -#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/) -#define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */ -#define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */ -#define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */ -#define CV_SEQ_ELTYPE_GRAPH_VERTEX 0 /**< first_edge, &(x,y) */ -#define CV_SEQ_ELTYPE_TRIAN_ATR 0 /**< vertex of the binary tree */ -#define CV_SEQ_ELTYPE_CONNECTED_COMP 0 /**< connected component */ -#define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /**< (x,y,z) */ - -#define CV_SEQ_KIND_BITS 2 -#define CV_SEQ_KIND_MASK (((1 << CV_SEQ_KIND_BITS) - 1)<flags & CV_SEQ_ELTYPE_MASK) -#define CV_SEQ_KIND( seq ) ((seq)->flags & CV_SEQ_KIND_MASK ) - -/** flag checking */ -#define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) - -#define CV_IS_SEQ_CURVE( seq ) (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE) -#define CV_IS_SEQ_CLOSED( seq ) (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0) -#define CV_IS_SEQ_CONVEX( seq ) 0 -#define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) -#define CV_IS_SEQ_SIMPLE( seq ) 1 - -/** type checking macros */ -#define CV_IS_SEQ_POINT_SET( seq ) \ - ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) - -#define CV_IS_SEQ_POINT_SUBSET( seq ) \ - (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT) - -#define CV_IS_SEQ_POLYLINE( seq ) \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq)) - -#define CV_IS_SEQ_POLYGON( seq ) \ - (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq)) - -#define CV_IS_SEQ_CHAIN( seq ) \ - (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1) - -#define CV_IS_SEQ_CONTOUR( seq ) \ - (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq))) - -#define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \ - (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq )) - -#define CV_IS_SEQ_POLYGON_TREE( seq ) \ - (CV_SEQ_ELTYPE (seq) == CV_SEQ_ELTYPE_TRIAN_ATR && \ - CV_SEQ_KIND( seq ) == CV_SEQ_KIND_BIN_TREE ) - -#define CV_IS_GRAPH( seq ) \ - (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH) - -#define CV_IS_GRAPH_ORIENTED( seq ) \ - (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0) - -#define CV_IS_SUBDIV2D( seq ) \ - (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D) - -/****************************************************************************************/ -/* Sequence writer & reader */ -/****************************************************************************************/ - -#define CV_SEQ_WRITER_FIELDS() \ - int header_size; \ - CvSeq* seq; /**< the sequence written */ \ - CvSeqBlock* block; /**< current block */ \ - schar* ptr; /**< pointer to free space */ \ - schar* block_min; /**< pointer to the beginning of block*/\ - schar* block_max; /**< pointer to the end of block */ - -typedef struct CvSeqWriter -{ - CV_SEQ_WRITER_FIELDS() -} -CvSeqWriter; - - -#define CV_SEQ_READER_FIELDS() \ - int header_size; \ - CvSeq* seq; /**< sequence, beign read */ \ - CvSeqBlock* block; /**< current block */ \ - schar* ptr; /**< pointer to element be read next */ \ - schar* block_min; /**< pointer to the beginning of block */\ - schar* block_max; /**< pointer to the end of block */ \ - int delta_index;/**< = seq->first->start_index */ \ - schar* prev_elem; /**< pointer to previous element */ - -typedef struct CvSeqReader -{ - CV_SEQ_READER_FIELDS() -} -CvSeqReader; - -/****************************************************************************************/ -/* Operations on sequences */ -/****************************************************************************************/ - -#define CV_SEQ_ELEM( seq, elem_type, index ) \ -/** assert gives some guarantee that parameter is valid */ \ -( assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) && \ - (seq)->elem_size == sizeof(elem_type)), \ - (elem_type*)((seq)->first && (unsigned)index < \ - (unsigned)((seq)->first->count) ? \ - (seq)->first->data + (index) * sizeof(elem_type) : \ - cvGetSeqElem( (CvSeq*)(seq), (index) ))) -#define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) - -/** Add element to sequence: */ -#define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ -{ \ - if( (writer).ptr >= (writer).block_max ) \ - { \ - cvCreateSeqBlock( &writer); \ - } \ - memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ - (writer).ptr += (writer).seq->elem_size; \ -} - -#define CV_WRITE_SEQ_ELEM( elem, writer ) \ -{ \ - assert( (writer).seq->elem_size == sizeof(elem)); \ - if( (writer).ptr >= (writer).block_max ) \ - { \ - cvCreateSeqBlock( &writer); \ - } \ - assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ - memcpy((writer).ptr, &(elem), sizeof(elem)); \ - (writer).ptr += sizeof(elem); \ -} - - -/** Move reader position forward: */ -#define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ -{ \ - if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ - { \ - cvChangeSeqBlock( &(reader), 1 ); \ - } \ -} - - -/** Move reader position backward: */ -#define CV_PREV_SEQ_ELEM( elem_size, reader ) \ -{ \ - if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ - { \ - cvChangeSeqBlock( &(reader), -1 ); \ - } \ -} - -/** Read element and move read position forward: */ -#define CV_READ_SEQ_ELEM( elem, reader ) \ -{ \ - assert( (reader).seq->elem_size == sizeof(elem)); \ - memcpy( &(elem), (reader).ptr, sizeof((elem))); \ - CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ -} - -/** Read element and move read position backward: */ -#define CV_REV_READ_SEQ_ELEM( elem, reader ) \ -{ \ - assert( (reader).seq->elem_size == sizeof(elem)); \ - memcpy(&(elem), (reader).ptr, sizeof((elem))); \ - CV_PREV_SEQ_ELEM( sizeof(elem), reader ) \ -} - - -#define CV_READ_CHAIN_POINT( _pt, reader ) \ -{ \ - (_pt) = (reader).pt; \ - if( (reader).ptr ) \ - { \ - CV_READ_SEQ_ELEM( (reader).code, (reader)); \ - assert( ((reader).code & ~7) == 0 ); \ - (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ - (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ - } \ -} - -#define CV_CURRENT_POINT( reader ) (*((CvPoint*)((reader).ptr))) -#define CV_PREV_POINT( reader ) (*((CvPoint*)((reader).prev_elem))) - -#define CV_READ_EDGE( pt1, pt2, reader ) \ -{ \ - assert( sizeof(pt1) == sizeof(CvPoint) && \ - sizeof(pt2) == sizeof(CvPoint) && \ - reader.seq->elem_size == sizeof(CvPoint)); \ - (pt1) = CV_PREV_POINT( reader ); \ - (pt2) = CV_CURRENT_POINT( reader ); \ - (reader).prev_elem = (reader).ptr; \ - CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ -} - -/************ Graph macros ************/ - -/** Return next graph edge for given vertex: */ -#define CV_NEXT_GRAPH_EDGE( edge, vertex ) \ - (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)), \ - (edge)->next[(edge)->vtx[1] == (vertex)]) - - - -/****************************************************************************************\ -* Data structures for persistence (a.k.a serialization) functionality * -\****************************************************************************************/ - -#if 0 - -/** "black box" file storage */ -typedef struct CvFileStorage CvFileStorage; - -/** Storage flags: */ -#define CV_STORAGE_READ 0 -#define CV_STORAGE_WRITE 1 -#define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE -#define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE -#define CV_STORAGE_APPEND 2 -#define CV_STORAGE_MEMORY 4 -#define CV_STORAGE_FORMAT_MASK (7<<3) -#define CV_STORAGE_FORMAT_AUTO 0 -#define CV_STORAGE_FORMAT_XML 8 -#define CV_STORAGE_FORMAT_YAML 16 -#define CV_STORAGE_FORMAT_JSON 24 -#define CV_STORAGE_BASE64 64 -#define CV_STORAGE_WRITE_BASE64 (CV_STORAGE_BASE64 | CV_STORAGE_WRITE) - -/** @brief List of attributes. : - -In the current implementation, attributes are used to pass extra parameters when writing user -objects (see cvWrite). XML attributes inside tags are not supported, aside from the object type -specification (type_id attribute). -@see cvAttrList, cvAttrValue - */ -typedef struct CvAttrList -{ - const char** attr; /**< NULL-terminated array of (attribute_name,attribute_value) pairs. */ - struct CvAttrList* next; /**< Pointer to next chunk of the attributes list. */ -} -CvAttrList; - -/** initializes CvAttrList structure */ -CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL), - CvAttrList* next CV_DEFAULT(NULL) ) -{ - CvAttrList l; - l.attr = attr; - l.next = next; - - return l; -} - -struct CvTypeInfo; - -#define CV_NODE_NONE 0 -#define CV_NODE_INT 1 -#define CV_NODE_INTEGER CV_NODE_INT -#define CV_NODE_REAL 2 -#define CV_NODE_FLOAT CV_NODE_REAL -#define CV_NODE_STR 3 -#define CV_NODE_STRING CV_NODE_STR -#define CV_NODE_REF 4 /**< not used */ -#define CV_NODE_SEQ 5 -#define CV_NODE_MAP 6 -#define CV_NODE_TYPE_MASK 7 - -#define CV_NODE_TYPE(flags) ((flags) & CV_NODE_TYPE_MASK) - -/** file node flags */ -#define CV_NODE_FLOW 8 /**= CV_NODE_SEQ) -#define CV_NODE_IS_FLOW(flags) (((flags) & CV_NODE_FLOW) != 0) -#define CV_NODE_IS_EMPTY(flags) (((flags) & CV_NODE_EMPTY) != 0) -#define CV_NODE_IS_USER(flags) (((flags) & CV_NODE_USER) != 0) -#define CV_NODE_HAS_NAME(flags) (((flags) & CV_NODE_NAMED) != 0) - -#define CV_NODE_SEQ_SIMPLE 256 -#define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0) - -typedef struct CvString -{ - int len; - char* ptr; -} -CvString; - -/** All the keys (names) of elements in the read file storage - are stored in the hash to speed up the lookup operations: */ -typedef struct CvStringHashNode -{ - unsigned hashval; - CvString str; - struct CvStringHashNode* next; -} -CvStringHashNode; - -typedef struct CvGenericHash CvFileNodeHash; - -/** Basic element of the file storage - scalar or collection: */ -typedef struct CvFileNode -{ - int tag; - struct CvTypeInfo* info; /**< type information - (only for user-defined object, for others it is 0) */ - union - { - double f; /**< scalar floating-point number */ - int i; /**< scalar integer number */ - CvString str; /**< text string */ - CvSeq* seq; /**< sequence (ordered collection of file nodes) */ - CvFileNodeHash* map; /**< map (collection of named file nodes) */ - } data; -} -CvFileNode; - -#ifdef __cplusplus -extern "C" { -#endif -typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr ); -typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr ); -typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node ); -typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name, - const void* struct_ptr, CvAttrList attributes ); -typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr ); -#ifdef __cplusplus -} -#endif - -/** @brief Type information - -The structure contains information about one of the standard or user-defined types. Instances of the -type may or may not contain a pointer to the corresponding CvTypeInfo structure. In any case, there -is a way to find the type info structure for a given object using the cvTypeOf function. -Alternatively, type info can be found by type name using cvFindType, which is used when an object -is read from file storage. The user can register a new type with cvRegisterType that adds the type -information structure into the beginning of the type list. Thus, it is possible to create -specialized types from generic standard types and override the basic methods. - */ -typedef struct CvTypeInfo -{ - int flags; /**< not used */ - int header_size; /**< sizeof(CvTypeInfo) */ - struct CvTypeInfo* prev; /**< previous registered type in the list */ - struct CvTypeInfo* next; /**< next registered type in the list */ - const char* type_name; /**< type name, written to file storage */ - CvIsInstanceFunc is_instance; /**< checks if the passed object belongs to the type */ - CvReleaseFunc release; /**< releases object (memory etc.) */ - CvReadFunc read; /**< reads object from file storage */ - CvWriteFunc write; /**< writes object to file storage */ - CvCloneFunc clone; /**< creates a copy of the object */ -} -CvTypeInfo; -#endif - -/** @} */ - -#endif /*OPENCV_CORE_TYPES_H*/ - -/* End of file. */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_TYPES_H +#define OPENCV_CORE_TYPES_H + +#ifdef CV__ENABLE_C_API_CTORS // invalid C API ctors (must be removed) +#if defined(_WIN32) && !defined(CV__SKIP_MESSAGE_MALFORMED_C_API_CTORS) +#error "C API ctors don't work on Win32: https://github.com/opencv/opencv/issues/15990" +#endif +#endif + +//#define CV__VALIDATE_UNUNITIALIZED_VARS 1 // C++11 & GCC only + +#ifdef __cplusplus + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#define CV_STRUCT_INITIALIZER {0,} +#else +#if defined(__GNUC__) && __GNUC__ == 4 // GCC 4.x warns on "= {}" initialization, fixed in GCC 5.0 +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#endif +#define CV_STRUCT_INITIALIZER {} +#endif + +#else +#define CV_STRUCT_INITIALIZER {0} +#endif + + +#ifdef HAVE_IPL +# ifndef __IPL_H__ +# if defined _WIN32 +# include +# else +# include +# endif +# endif +#elif defined __IPL_H__ +# define HAVE_IPL +#endif + +#include "opencv2/core/cvdef.h" + +#ifndef SKIP_INCLUDES +#include +#include +#include +#include +#endif // SKIP_INCLUDES + + + +#ifndef CV_DEFAULT +# ifdef __cplusplus +# define CV_DEFAULT(val) = val +# else +# define CV_DEFAULT(val) +# endif +#endif + +#ifndef CV_EXTERN_C_FUNCPTR +# ifdef __cplusplus +# define CV_EXTERN_C_FUNCPTR(x) extern "C" { typedef x; } +# else +# define CV_EXTERN_C_FUNCPTR(x) typedef x +# endif +#endif + +#ifndef CVAPI +# define CVAPI(rettype) CV_EXTERN_C CV_EXPORTS rettype CV_CDECL +#endif + +#ifndef CV_IMPL +# define CV_IMPL CV_EXTERN_C +#endif + +#ifdef __cplusplus +# include "opencv2/core.hpp" +#endif + +/** @addtogroup core_c + @{ +*/ + +/** @brief This is the "metatype" used *only* as a function parameter. + +It denotes that the function accepts arrays of multiple types, such as IplImage*, CvMat* or even +CvSeq* sometimes. The particular array type is determined at runtime by analyzing the first 4 +bytes of the header. In C++ interface the role of CvArr is played by InputArray and OutputArray. + */ +typedef void CvArr; + +typedef int CVStatus; + +/** @see cv::Error::Code */ +enum { + CV_StsOk= 0, /**< everything is ok */ + CV_StsBackTrace= -1, /**< pseudo error for back trace */ + CV_StsError= -2, /**< unknown /unspecified error */ + CV_StsInternal= -3, /**< internal error (bad state) */ + CV_StsNoMem= -4, /**< insufficient memory */ + CV_StsBadArg= -5, /**< function arg/param is bad */ + CV_StsBadFunc= -6, /**< unsupported function */ + CV_StsNoConv= -7, /**< iter. didn't converge */ + CV_StsAutoTrace= -8, /**< tracing */ + CV_HeaderIsNull= -9, /**< image header is NULL */ + CV_BadImageSize= -10, /**< image size is invalid */ + CV_BadOffset= -11, /**< offset is invalid */ + CV_BadDataPtr= -12, /**/ + CV_BadStep= -13, /**< image step is wrong, this may happen for a non-continuous matrix */ + CV_BadModelOrChSeq= -14, /**/ + CV_BadNumChannels= -15, /**< bad number of channels, for example, some functions accept only single channel matrices */ + CV_BadNumChannel1U= -16, /**/ + CV_BadDepth= -17, /**< input image depth is not supported by the function */ + CV_BadAlphaChannel= -18, /**/ + CV_BadOrder= -19, /**< number of dimensions is out of range */ + CV_BadOrigin= -20, /**< incorrect input origin */ + CV_BadAlign= -21, /**< incorrect input align */ + CV_BadCallBack= -22, /**/ + CV_BadTileSize= -23, /**/ + CV_BadCOI= -24, /**< input COI is not supported */ + CV_BadROISize= -25, /**< incorrect input roi */ + CV_MaskIsTiled= -26, /**/ + CV_StsNullPtr= -27, /**< null pointer */ + CV_StsVecLengthErr= -28, /**< incorrect vector length */ + CV_StsFilterStructContentErr= -29, /**< incorrect filter structure content */ + CV_StsKernelStructContentErr= -30, /**< incorrect transform kernel content */ + CV_StsFilterOffsetErr= -31, /**< incorrect filter offset value */ + CV_StsBadSize= -201, /**< the input/output structure size is incorrect */ + CV_StsDivByZero= -202, /**< division by zero */ + CV_StsInplaceNotSupported= -203, /**< in-place operation is not supported */ + CV_StsObjectNotFound= -204, /**< request can't be completed */ + CV_StsUnmatchedFormats= -205, /**< formats of input/output arrays differ */ + CV_StsBadFlag= -206, /**< flag is wrong or not supported */ + CV_StsBadPoint= -207, /**< bad CvPoint */ + CV_StsBadMask= -208, /**< bad format of mask (neither 8uC1 nor 8sC1)*/ + CV_StsUnmatchedSizes= -209, /**< sizes of input/output structures do not match */ + CV_StsUnsupportedFormat= -210, /**< the data format/type is not supported by the function*/ + CV_StsOutOfRange= -211, /**< some of parameters are out of range */ + CV_StsParseError= -212, /**< invalid syntax/structure of the parsed file */ + CV_StsNotImplemented= -213, /**< the requested function/feature is not implemented */ + CV_StsBadMemBlock= -214, /**< an allocated block has been corrupted */ + CV_StsAssert= -215, /**< assertion failed */ + CV_GpuNotSupported= -216, /**< no CUDA support */ + CV_GpuApiCallError= -217, /**< GPU API call error */ + CV_OpenGlNotSupported= -218, /**< no OpenGL support */ + CV_OpenGlApiCallError= -219, /**< OpenGL API call error */ + CV_OpenCLApiCallError= -220, /**< OpenCL API call error */ + CV_OpenCLDoubleNotSupported= -221, + CV_OpenCLInitError= -222, /**< OpenCL initialization error */ + CV_OpenCLNoAMDBlasFft= -223 +}; + +/****************************************************************************************\ +* Common macros and inline functions * +\****************************************************************************************/ + +/** absolute value without jumps */ +#ifndef __cplusplus +# define CV_IABS(a) (((a) ^ ((a) < 0 ? -1 : 0)) - ((a) < 0 ? -1 : 0)) +#else +# define CV_IABS(a) abs(a) +#endif + + +#define cvInvSqrt(value) ((float)(1./sqrt(value))) +#define cvSqrt(value) ((float)sqrt(value)) + + +/*************** Random number generation *******************/ + +typedef uint64 CvRNG; + +#define CV_RNG_COEFF 4164903690U + +/** @brief Initializes a random number generator state. + +The function initializes a random number generator and returns the state. The pointer to the state +can be then passed to the cvRandInt, cvRandReal and cvRandArr functions. In the current +implementation a multiply-with-carry generator is used. +@param seed 64-bit value used to initiate a random sequence +@sa the C++ class RNG replaced CvRNG. + */ +CV_INLINE CvRNG cvRNG( int64 seed CV_DEFAULT(-1)) +{ + CvRNG rng = seed ? (uint64)seed : (uint64)(int64)-1; + return rng; +} + +/** @brief Returns a 32-bit unsigned integer and updates RNG. + +The function returns a uniformly-distributed random 32-bit unsigned integer and updates the RNG +state. It is similar to the rand() function from the C runtime library, except that OpenCV functions +always generates a 32-bit random number, regardless of the platform. +@param rng CvRNG state initialized by cvRNG. + */ +CV_INLINE unsigned cvRandInt( CvRNG* rng ) +{ + uint64 temp = *rng; + temp = (uint64)(unsigned)temp*CV_RNG_COEFF + (temp >> 32); + *rng = temp; + return (unsigned)temp; +} + +/** @brief Returns a floating-point random number and updates RNG. + +The function returns a uniformly-distributed random floating-point number between 0 and 1 (1 is not +included). +@param rng RNG state initialized by cvRNG + */ +CV_INLINE double cvRandReal( CvRNG* rng ) +{ + return cvRandInt(rng)*2.3283064365386962890625e-10 /* 2^-32 */; +} + +/****************************************************************************************\ +* Image type (IplImage) * +\****************************************************************************************/ + +#ifndef HAVE_IPL + +/* + * The following definitions (until #endif) + * is an extract from IPL headers. + * Copyright (c) 1995 Intel Corporation. + */ +#define IPL_DEPTH_SIGN 0x80000000 + +#define IPL_DEPTH_1U 1 +#define IPL_DEPTH_8U 8 +#define IPL_DEPTH_16U 16 +#define IPL_DEPTH_32F 32 + +#define IPL_DEPTH_8S (IPL_DEPTH_SIGN| 8) +#define IPL_DEPTH_16S (IPL_DEPTH_SIGN|16) +#define IPL_DEPTH_32S (IPL_DEPTH_SIGN|32) + +#define IPL_DATA_ORDER_PIXEL 0 +#define IPL_DATA_ORDER_PLANE 1 + +#define IPL_ORIGIN_TL 0 +#define IPL_ORIGIN_BL 1 + +#define IPL_ALIGN_4BYTES 4 +#define IPL_ALIGN_8BYTES 8 +#define IPL_ALIGN_16BYTES 16 +#define IPL_ALIGN_32BYTES 32 + +#define IPL_ALIGN_DWORD IPL_ALIGN_4BYTES +#define IPL_ALIGN_QWORD IPL_ALIGN_8BYTES + +#define IPL_BORDER_CONSTANT 0 +#define IPL_BORDER_REPLICATE 1 +#define IPL_BORDER_REFLECT 2 +#define IPL_BORDER_WRAP 3 + +#ifdef __cplusplus +typedef struct _IplImage IplImage; +CV_EXPORTS _IplImage cvIplImage(const cv::Mat& m); +#endif + +/** The IplImage is taken from the Intel Image Processing Library, in which the format is native. OpenCV +only supports a subset of possible IplImage formats, as outlined in the parameter list above. + +In addition to the above restrictions, OpenCV handles ROIs differently. OpenCV functions require +that the image size or ROI size of all source and destination images match exactly. On the other +hand, the Intel Image Processing Library processes the area of intersection between the source and +destination images (or ROIs), allowing them to vary independently. +*/ +typedef struct +_IplImage +{ + int nSize; /**< sizeof(IplImage) */ + int ID; /**< version (=0)*/ + int nChannels; /**< Most of OpenCV functions support 1,2,3 or 4 channels */ + int alphaChannel; /**< Ignored by OpenCV */ + int depth; /**< Pixel depth in bits: IPL_DEPTH_8U, IPL_DEPTH_8S, IPL_DEPTH_16S, + IPL_DEPTH_32S, IPL_DEPTH_32F and IPL_DEPTH_64F are supported. */ + char colorModel[4]; /**< Ignored by OpenCV */ + char channelSeq[4]; /**< ditto */ + int dataOrder; /**< 0 - interleaved color channels, 1 - separate color channels. + cvCreateImage can only create interleaved images */ + int origin; /**< 0 - top-left origin, + 1 - bottom-left origin (Windows bitmaps style). */ + int align; /**< Alignment of image rows (4 or 8). + OpenCV ignores it and uses widthStep instead. */ + int width; /**< Image width in pixels. */ + int height; /**< Image height in pixels. */ + struct _IplROI *roi; /**< Image ROI. If NULL, the whole image is selected. */ + struct _IplImage *maskROI; /**< Must be NULL. */ + void *imageId; /**< " " */ + struct _IplTileInfo *tileInfo; /**< " " */ + int imageSize; /**< Image data size in bytes + (==image->height*image->widthStep + in case of interleaved data)*/ + char *imageData; /**< Pointer to aligned image data. */ + int widthStep; /**< Size of aligned image row in bytes. */ + int BorderMode[4]; /**< Ignored by OpenCV. */ + int BorderConst[4]; /**< Ditto. */ + char *imageDataOrigin; /**< Pointer to very origin of image data + (not necessarily aligned) - + needed for correct deallocation */ + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + _IplImage() + { + memset(this, 0, sizeof(*this)); // valid for POD structure + nSize = sizeof(IplImage); + } + _IplImage(const cv::Mat& m) { *this = cvIplImage(m); } +#endif +} +IplImage; + +CV_INLINE IplImage cvIplImage() +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + IplImage self = CV_STRUCT_INITIALIZER; self.nSize = sizeof(IplImage); return self; +#else + return _IplImage(); +#endif +} + +typedef struct _IplTileInfo IplTileInfo; + +typedef struct _IplROI +{ + int coi; /**< 0 - no COI (all channels are selected), 1 - 0th channel is selected ...*/ + int xOffset; + int yOffset; + int width; + int height; +} +IplROI; + +typedef struct _IplConvKernel +{ + int nCols; + int nRows; + int anchorX; + int anchorY; + int *values; + int nShiftR; +} +IplConvKernel; + +typedef struct _IplConvKernelFP +{ + int nCols; + int nRows; + int anchorX; + int anchorY; + float *values; +} +IplConvKernelFP; + +#define IPL_IMAGE_HEADER 1 +#define IPL_IMAGE_DATA 2 +#define IPL_IMAGE_ROI 4 + +#endif/*HAVE_IPL*/ + +/** extra border mode */ +#define IPL_BORDER_REFLECT_101 4 +#define IPL_BORDER_TRANSPARENT 5 + +#define IPL_IMAGE_MAGIC_VAL ((int)sizeof(IplImage)) +#define CV_TYPE_NAME_IMAGE "opencv-image" + +#define CV_IS_IMAGE_HDR(img) \ + ((img) != NULL && ((const IplImage*)(img))->nSize == sizeof(IplImage)) + +#define CV_IS_IMAGE(img) \ + (CV_IS_IMAGE_HDR(img) && ((IplImage*)img)->imageData != NULL) + +/** for storing double-precision + floating point data in IplImage's */ +#define IPL_DEPTH_64F 64 + +/** get reference to pixel at (col,row), + for multi-channel images (col) should be multiplied by number of channels */ +#define CV_IMAGE_ELEM( image, elemtype, row, col ) \ + (((elemtype*)((image)->imageData + (image)->widthStep*(row)))[(col)]) + +/****************************************************************************************\ +* Matrix type (CvMat) * +\****************************************************************************************/ + +#define CV_AUTO_STEP 0x7fffffff +#define CV_WHOLE_ARR cvSlice( 0, 0x3fffffff ) + +#define CV_MAGIC_MASK 0xFFFF0000 +#define CV_MAT_MAGIC_VAL 0x42420000 +#define CV_TYPE_NAME_MAT "opencv-matrix" + +#ifdef __cplusplus +typedef struct CvMat CvMat; +CV_INLINE CvMat cvMat(const cv::Mat& m); +#endif + +/** Matrix elements are stored row by row. Element (i, j) (i - 0-based row index, j - 0-based column +index) of a matrix can be retrieved or modified using CV_MAT_ELEM macro: + + uchar pixval = CV_MAT_ELEM(grayimg, uchar, i, j) + CV_MAT_ELEM(cameraMatrix, float, 0, 2) = image.width*0.5f; + +To access multiple-channel matrices, you can use +CV_MAT_ELEM(matrix, type, i, j\*nchannels + channel_idx). + +@deprecated CvMat is now obsolete; consider using Mat instead. + */ +typedef struct CvMat +{ + int type; + int step; + + /* for internal use only */ + int* refcount; + int hdr_refcount; + + union + { + uchar* ptr; + short* s; + int* i; + float* fl; + double* db; + } data; + +#ifdef __cplusplus + union + { + int rows; + int height; + }; + + union + { + int cols; + int width; + }; +#else + int rows; + int cols; +#endif + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvMat() {} + CvMat(const cv::Mat& m) { *this = cvMat(m); } +#endif +} +CvMat; + + +#define CV_IS_MAT_HDR(mat) \ + ((mat) != NULL && \ + (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ + ((const CvMat*)(mat))->cols > 0 && ((const CvMat*)(mat))->rows > 0) + +#define CV_IS_MAT_HDR_Z(mat) \ + ((mat) != NULL && \ + (((const CvMat*)(mat))->type & CV_MAGIC_MASK) == CV_MAT_MAGIC_VAL && \ + ((const CvMat*)(mat))->cols >= 0 && ((const CvMat*)(mat))->rows >= 0) + +#define CV_IS_MAT(mat) \ + (CV_IS_MAT_HDR(mat) && ((const CvMat*)(mat))->data.ptr != NULL) + +#define CV_IS_MASK_ARR(mat) \ + (((mat)->type & (CV_MAT_TYPE_MASK & ~CV_8SC1)) == 0) + +#define CV_ARE_TYPES_EQ(mat1, mat2) \ + ((((mat1)->type ^ (mat2)->type) & CV_MAT_TYPE_MASK) == 0) + +#define CV_ARE_CNS_EQ(mat1, mat2) \ + ((((mat1)->type ^ (mat2)->type) & CV_MAT_CN_MASK) == 0) + +#define CV_ARE_DEPTHS_EQ(mat1, mat2) \ + ((((mat1)->type ^ (mat2)->type) & CV_MAT_DEPTH_MASK) == 0) + +#define CV_ARE_SIZES_EQ(mat1, mat2) \ + ((mat1)->rows == (mat2)->rows && (mat1)->cols == (mat2)->cols) + +#define CV_IS_MAT_CONST(mat) \ + (((mat)->rows|(mat)->cols) == 1) + +#define IPL2CV_DEPTH(depth) \ + ((((CV_8U)+(CV_16U<<4)+(CV_32F<<8)+(CV_64F<<16)+(CV_8S<<20)+ \ + (CV_16S<<24)+(CV_32S<<28)) >> ((((depth) & 0xF0) >> 2) + \ + (((depth) & IPL_DEPTH_SIGN) ? 20 : 0))) & 15) + +/** Inline constructor. No data is allocated internally!!! + * (Use together with cvCreateData, or use cvCreateMat instead to + * get a matrix with allocated data): + */ +CV_INLINE CvMat cvMat( int rows, int cols, int type, void* data CV_DEFAULT(NULL)) +{ + CvMat m; + + assert( (unsigned)CV_MAT_DEPTH(type) <= CV_64F ); + type = CV_MAT_TYPE(type); + m.type = CV_MAT_MAGIC_VAL | CV_MAT_CONT_FLAG | type; + m.cols = cols; + m.rows = rows; + m.step = m.cols*CV_ELEM_SIZE(type); + m.data.ptr = (uchar*)data; + m.refcount = NULL; + m.hdr_refcount = 0; + + return m; +} + +#ifdef __cplusplus + +CV_INLINE CvMat cvMat(const cv::Mat& m) +{ + CvMat self; + CV_DbgAssert(m.dims <= 2); + self = cvMat(m.rows, m.dims == 1 ? 1 : m.cols, m.type(), m.data); + self.step = (int)m.step[0]; + self.type = (self.type & ~cv::Mat::CONTINUOUS_FLAG) | (m.flags & cv::Mat::CONTINUOUS_FLAG); + return self; +} +CV_INLINE CvMat cvMat() +{ +#if !defined(CV__ENABLE_C_API_CTORS) + CvMat self = CV_STRUCT_INITIALIZER; return self; +#else + return CvMat(); +#endif +} +CV_INLINE CvMat cvMat(const CvMat& m) +{ +#if !defined(CV__ENABLE_C_API_CTORS) + CvMat self = CV_STRUCT_INITIALIZER; memcpy(&self, &m, sizeof(self)); return self; +#else + return CvMat(m); +#endif +} + +#endif // __cplusplus + + +#define CV_MAT_ELEM_PTR_FAST( mat, row, col, pix_size ) \ + (assert( (unsigned)(row) < (unsigned)(mat).rows && \ + (unsigned)(col) < (unsigned)(mat).cols ), \ + (mat).data.ptr + (size_t)(mat).step*(row) + (pix_size)*(col)) + +#define CV_MAT_ELEM_PTR( mat, row, col ) \ + CV_MAT_ELEM_PTR_FAST( mat, row, col, CV_ELEM_SIZE((mat).type) ) + +#define CV_MAT_ELEM( mat, elemtype, row, col ) \ + (*(elemtype*)CV_MAT_ELEM_PTR_FAST( mat, row, col, sizeof(elemtype))) + +/** @brief Returns the particular element of single-channel floating-point matrix. + +The function is a fast replacement for cvGetReal2D in the case of single-channel floating-point +matrices. It is faster because it is inline, it does fewer checks for array type and array element +type, and it checks for the row and column ranges only in debug mode. +@param mat Input matrix +@param row The zero-based index of row +@param col The zero-based index of column + */ +CV_INLINE double cvmGet( const CvMat* mat, int row, int col ) +{ + int type; + + type = CV_MAT_TYPE(mat->type); + assert( (unsigned)row < (unsigned)mat->rows && + (unsigned)col < (unsigned)mat->cols ); + + if( type == CV_32FC1 ) + return ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; + else + { + assert( type == CV_64FC1 ); + return ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col]; + } +} + +/** @brief Sets a specific element of a single-channel floating-point matrix. + +The function is a fast replacement for cvSetReal2D in the case of single-channel floating-point +matrices. It is faster because it is inline, it does fewer checks for array type and array element +type, and it checks for the row and column ranges only in debug mode. +@param mat The matrix +@param row The zero-based index of row +@param col The zero-based index of column +@param value The new value of the matrix element + */ +CV_INLINE void cvmSet( CvMat* mat, int row, int col, double value ) +{ + int type; + type = CV_MAT_TYPE(mat->type); + assert( (unsigned)row < (unsigned)mat->rows && + (unsigned)col < (unsigned)mat->cols ); + + if( type == CV_32FC1 ) + ((float*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = (float)value; + else + { + assert( type == CV_64FC1 ); + ((double*)(void*)(mat->data.ptr + (size_t)mat->step*row))[col] = value; + } +} + + +CV_INLINE int cvIplDepth( int type ) +{ + int depth = CV_MAT_DEPTH(type); + return CV_ELEM_SIZE1(depth)*8 | (depth == CV_8S || depth == CV_16S || + depth == CV_32S ? IPL_DEPTH_SIGN : 0); +} + + +/****************************************************************************************\ +* Multi-dimensional dense array (CvMatND) * +\****************************************************************************************/ + +#define CV_MATND_MAGIC_VAL 0x42430000 +#define CV_TYPE_NAME_MATND "opencv-nd-matrix" + +#ifdef __cplusplus +typedef struct CvMatND CvMatND; +CV_EXPORTS CvMatND cvMatND(const cv::Mat& m); +#endif + +/** + @deprecated consider using cv::Mat instead + */ +typedef struct +CvMatND +{ + int type; + int dims; + + int* refcount; + int hdr_refcount; + + union + { + uchar* ptr; + float* fl; + double* db; + int* i; + short* s; + } data; + + struct + { + int size; + int step; + } + dim[CV_MAX_DIM]; + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvMatND() {} + CvMatND(const cv::Mat& m) { *this = cvMatND(m); } +#endif +} +CvMatND; + + +CV_INLINE CvMatND cvMatND() +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvMatND self = CV_STRUCT_INITIALIZER; return self; +#else + return CvMatND(); +#endif +} + +#define CV_IS_MATND_HDR(mat) \ + ((mat) != NULL && (((const CvMatND*)(mat))->type & CV_MAGIC_MASK) == CV_MATND_MAGIC_VAL) + +#define CV_IS_MATND(mat) \ + (CV_IS_MATND_HDR(mat) && ((const CvMatND*)(mat))->data.ptr != NULL) + + +/****************************************************************************************\ +* Multi-dimensional sparse array (CvSparseMat) * +\****************************************************************************************/ + +#define CV_SPARSE_MAT_MAGIC_VAL 0x42440000 +#define CV_TYPE_NAME_SPARSE_MAT "opencv-sparse-matrix" + +struct CvSet; + +typedef struct CvSparseMat +{ + int type; + int dims; + int* refcount; + int hdr_refcount; + + struct CvSet* heap; + void** hashtable; + int hashsize; + int valoffset; + int idxoffset; + int size[CV_MAX_DIM]; + +#ifdef __cplusplus + CV_EXPORTS void copyToSparseMat(cv::SparseMat& m) const; +#endif +} +CvSparseMat; + +#ifdef __cplusplus +CV_EXPORTS CvSparseMat* cvCreateSparseMat(const cv::SparseMat& m); +#endif + +#define CV_IS_SPARSE_MAT_HDR(mat) \ + ((mat) != NULL && \ + (((const CvSparseMat*)(mat))->type & CV_MAGIC_MASK) == CV_SPARSE_MAT_MAGIC_VAL) + +#define CV_IS_SPARSE_MAT(mat) \ + CV_IS_SPARSE_MAT_HDR(mat) + +/**************** iteration through a sparse array *****************/ + +typedef struct CvSparseNode +{ + unsigned hashval; + struct CvSparseNode* next; +} +CvSparseNode; + +typedef struct CvSparseMatIterator +{ + CvSparseMat* mat; + CvSparseNode* node; + int curidx; +} +CvSparseMatIterator; + +#define CV_NODE_VAL(mat,node) ((void*)((uchar*)(node) + (mat)->valoffset)) +#define CV_NODE_IDX(mat,node) ((int*)((uchar*)(node) + (mat)->idxoffset)) + +/****************************************************************************************\ +* Histogram * +\****************************************************************************************/ + +typedef int CvHistType; + +#define CV_HIST_MAGIC_VAL 0x42450000 +#define CV_HIST_UNIFORM_FLAG (1 << 10) + +/** indicates whether bin ranges are set already or not */ +#define CV_HIST_RANGES_FLAG (1 << 11) + +#define CV_HIST_ARRAY 0 +#define CV_HIST_SPARSE 1 +#define CV_HIST_TREE CV_HIST_SPARSE + +/** should be used as a parameter only, + it turns to CV_HIST_UNIFORM_FLAG of hist->type */ +#define CV_HIST_UNIFORM 1 + +typedef struct CvHistogram +{ + int type; + CvArr* bins; + float thresh[CV_MAX_DIM][2]; /**< For uniform histograms. */ + float** thresh2; /**< For non-uniform histograms. */ + CvMatND mat; /**< Embedded matrix header for array histograms. */ +} +CvHistogram; + +#define CV_IS_HIST( hist ) \ + ((hist) != NULL && \ + (((CvHistogram*)(hist))->type & CV_MAGIC_MASK) == CV_HIST_MAGIC_VAL && \ + (hist)->bins != NULL) + +#define CV_IS_UNIFORM_HIST( hist ) \ + (((hist)->type & CV_HIST_UNIFORM_FLAG) != 0) + +#define CV_IS_SPARSE_HIST( hist ) \ + CV_IS_SPARSE_MAT((hist)->bins) + +#define CV_HIST_HAS_RANGES( hist ) \ + (((hist)->type & CV_HIST_RANGES_FLAG) != 0) + +/****************************************************************************************\ +* Other supplementary data type definitions * +\****************************************************************************************/ + +/*************************************** CvRect *****************************************/ +/** @sa Rect_ */ +typedef struct CvRect +{ + int x; + int y; + int width; + int height; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvRect() __attribute__(( warning("Non-initialized variable") )) {}; + template CvRect(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 4); + x = y = width = height = 0; + if (list.size() == 4) + { + x = list.begin()[0]; y = list.begin()[1]; width = list.begin()[2]; height = list.begin()[3]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvRect(int _x = 0, int _y = 0, int w = 0, int h = 0): x(_x), y(_y), width(w), height(h) {} + template + CvRect(const cv::Rect_<_Tp>& r): x(cv::saturate_cast(r.x)), y(cv::saturate_cast(r.y)), width(cv::saturate_cast(r.width)), height(cv::saturate_cast(r.height)) {} +#endif +#ifdef __cplusplus + template + operator cv::Rect_<_Tp>() const { return cv::Rect_<_Tp>((_Tp)x, (_Tp)y, (_Tp)width, (_Tp)height); } +#endif +} +CvRect; + +/** constructs CvRect structure. */ +CV_INLINE CvRect cvRect( int x, int y, int width, int height ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvRect r = {x, y, width, height}; +#else + CvRect r(x, y , width, height); +#endif + return r; +} +#ifdef __cplusplus +CV_INLINE CvRect cvRect(const cv::Rect& rc) { return cvRect(rc.x, rc.y, rc.width, rc.height); } +#endif + +CV_INLINE IplROI cvRectToROI( CvRect rect, int coi ) +{ + IplROI roi; + roi.xOffset = rect.x; + roi.yOffset = rect.y; + roi.width = rect.width; + roi.height = rect.height; + roi.coi = coi; + + return roi; +} + + +CV_INLINE CvRect cvROIToRect( IplROI roi ) +{ + return cvRect( roi.xOffset, roi.yOffset, roi.width, roi.height ); +} + +/*********************************** CvTermCriteria *************************************/ + +#define CV_TERMCRIT_ITER 1 +#define CV_TERMCRIT_NUMBER CV_TERMCRIT_ITER +#define CV_TERMCRIT_EPS 2 + +/** @sa TermCriteria + */ +typedef struct CvTermCriteria +{ + int type; /**< may be combination of + CV_TERMCRIT_ITER + CV_TERMCRIT_EPS */ + int max_iter; + double epsilon; +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvTermCriteria(int _type = 0, int _iter = 0, double _eps = 0) : type(_type), max_iter(_iter), epsilon(_eps) {} + CvTermCriteria(const cv::TermCriteria& t) : type(t.type), max_iter(t.maxCount), epsilon(t.epsilon) {} +#endif +#ifdef __cplusplus + operator cv::TermCriteria() const { return cv::TermCriteria(type, max_iter, epsilon); } +#endif +} +CvTermCriteria; + +CV_INLINE CvTermCriteria cvTermCriteria( int type, int max_iter, double epsilon ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvTermCriteria t = { type, max_iter, (float)epsilon}; +#else + CvTermCriteria t(type, max_iter, epsilon); +#endif + return t; +} +#ifdef __cplusplus +CV_INLINE CvTermCriteria cvTermCriteria(const cv::TermCriteria& t) { return cvTermCriteria(t.type, t.maxCount, t.epsilon); } +#endif + + +/******************************* CvPoint and variants ***********************************/ + +typedef struct CvPoint +{ + int x; + int y; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + x = y = 0; + if (list.size() == 2) + { + x = list.begin()[0]; y = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvPoint(int _x = 0, int _y = 0): x(_x), y(_y) {} + template + CvPoint(const cv::Point_<_Tp>& pt): x((int)pt.x), y((int)pt.y) {} +#endif +#ifdef __cplusplus + template + operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } +#endif +} +CvPoint; + +/** constructs CvPoint structure. */ +CV_INLINE CvPoint cvPoint( int x, int y ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint p = {x, y}; +#else + CvPoint p(x, y); +#endif + return p; +} +#ifdef __cplusplus +CV_INLINE CvPoint cvPoint(const cv::Point& pt) { return cvPoint(pt.x, pt.y); } +#endif + +typedef struct CvPoint2D32f +{ + float x; + float y; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint2D32f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint2D32f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + x = y = 0; + if (list.size() == 2) + { + x = list.begin()[0]; y = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvPoint2D32f(float _x = 0, float _y = 0): x(_x), y(_y) {} + template + CvPoint2D32f(const cv::Point_<_Tp>& pt): x((float)pt.x), y((float)pt.y) {} +#endif +#ifdef __cplusplus + template + operator cv::Point_<_Tp>() const { return cv::Point_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y)); } +#endif +} +CvPoint2D32f; + +/** constructs CvPoint2D32f structure. */ +CV_INLINE CvPoint2D32f cvPoint2D32f( double x, double y ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint2D32f p = { (float)x, (float)y }; +#else + CvPoint2D32f p((float)x, (float)y); +#endif + return p; +} + +#ifdef __cplusplus +template +CvPoint2D32f cvPoint2D32f(const cv::Point_<_Tp>& pt) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint2D32f p = { (float)pt.x, (float)pt.y }; +#else + CvPoint2D32f p((float)pt.x, (float)pt.y); +#endif + return p; +} +#endif + +/** converts CvPoint to CvPoint2D32f. */ +CV_INLINE CvPoint2D32f cvPointTo32f( CvPoint point ) +{ + return cvPoint2D32f( (float)point.x, (float)point.y ); +} + +/** converts CvPoint2D32f to CvPoint. */ +CV_INLINE CvPoint cvPointFrom32f( CvPoint2D32f point ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint ipt = { cvRound(point.x), cvRound(point.y) }; +#else + CvPoint ipt(cvRound(point.x), cvRound(point.y)); +#endif + return ipt; +} + + +typedef struct CvPoint3D32f +{ + float x; + float y; + float z; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint3D32f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint3D32f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 3); + x = y = z = 0; + if (list.size() == 3) + { + x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvPoint3D32f(float _x = 0, float _y = 0, float _z = 0): x(_x), y(_y), z(_z) {} + template + CvPoint3D32f(const cv::Point3_<_Tp>& pt): x((float)pt.x), y((float)pt.y), z((float)pt.z) {} +#endif +#ifdef __cplusplus + template + operator cv::Point3_<_Tp>() const { return cv::Point3_<_Tp>(cv::saturate_cast<_Tp>(x), cv::saturate_cast<_Tp>(y), cv::saturate_cast<_Tp>(z)); } +#endif +} +CvPoint3D32f; + +/** constructs CvPoint3D32f structure. */ +CV_INLINE CvPoint3D32f cvPoint3D32f( double x, double y, double z ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint3D32f p = { (float)x, (float)y, (float)z }; +#else + CvPoint3D32f p((float)x, (float)y, (float)z); +#endif + return p; +} + +#ifdef __cplusplus +template +CvPoint3D32f cvPoint3D32f(const cv::Point3_<_Tp>& pt) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvPoint3D32f p = { (float)pt.x, (float)pt.y, (float)pt.z }; +#else + CvPoint3D32f p((float)pt.x, (float)pt.y, (float)pt.z); +#endif + return p; +} +#endif + + +typedef struct CvPoint2D64f +{ + double x; + double y; +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint2D64f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint2D64f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + x = y = 0; + if (list.size() == 2) + { + x = list.begin()[0]; y = list.begin()[1]; + } + }; +#endif +} +CvPoint2D64f; + +/** constructs CvPoint2D64f structure.*/ +CV_INLINE CvPoint2D64f cvPoint2D64f( double x, double y ) +{ + CvPoint2D64f p = { x, y }; + return p; +} + + +typedef struct CvPoint3D64f +{ + double x; + double y; + double z; +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvPoint3D64f() __attribute__(( warning("Non-initialized variable") )) {} + template CvPoint3D64f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 3); + x = y = z = 0; + if (list.size() == 3) + { + x = list.begin()[0]; y = list.begin()[1]; z = list.begin()[2]; + } + }; +#endif +} +CvPoint3D64f; + +/** constructs CvPoint3D64f structure. */ +CV_INLINE CvPoint3D64f cvPoint3D64f( double x, double y, double z ) +{ + CvPoint3D64f p = { x, y, z }; + return p; +} + + +/******************************** CvSize's & CvBox **************************************/ + +typedef struct CvSize +{ + int width; + int height; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvSize() __attribute__(( warning("Non-initialized variable") )) {} + template CvSize(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + width = 0; height = 0; + if (list.size() == 2) + { + width = list.begin()[0]; height = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvSize(int w = 0, int h = 0): width(w), height(h) {} + template + CvSize(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} +#endif +#ifdef __cplusplus + template + operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } +#endif +} +CvSize; + +/** constructs CvSize structure. */ +CV_INLINE CvSize cvSize( int width, int height ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize s = { width, height }; +#else + CvSize s(width, height); +#endif + return s; +} + +#ifdef __cplusplus +CV_INLINE CvSize cvSize(const cv::Size& sz) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize s = { sz.width, sz.height }; +#else + CvSize s(sz.width, sz.height); +#endif + return s; +} +#endif + +typedef struct CvSize2D32f +{ + float width; + float height; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvSize2D32f() __attribute__(( warning("Non-initialized variable") )) {} + template CvSize2D32f(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + width = 0; height = 0; + if (list.size() == 2) + { + width = list.begin()[0]; height = list.begin()[1]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvSize2D32f(float w = 0, float h = 0): width(w), height(h) {} + template + CvSize2D32f(const cv::Size_<_Tp>& sz): width(cv::saturate_cast(sz.width)), height(cv::saturate_cast(sz.height)) {} +#endif +#ifdef __cplusplus + template + operator cv::Size_<_Tp>() const { return cv::Size_<_Tp>(cv::saturate_cast<_Tp>(width), cv::saturate_cast<_Tp>(height)); } +#endif +} +CvSize2D32f; + +/** constructs CvSize2D32f structure. */ +CV_INLINE CvSize2D32f cvSize2D32f( double width, double height ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize2D32f s = { (float)width, (float)height }; +#else + CvSize2D32f s((float)width, (float)height); +#endif + return s; +} +#ifdef __cplusplus +template +CvSize2D32f cvSize2D32f(const cv::Size_<_Tp>& sz) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvSize2D32f s = { (float)sz.width, (float)sz.height }; +#else + CvSize2D32f s((float)sz.width, (float)sz.height); +#endif + return s; +} +#endif + +/** @sa RotatedRect + */ +typedef struct CvBox2D +{ + CvPoint2D32f center; /**< Center of the box. */ + CvSize2D32f size; /**< Box width and length. */ + float angle; /**< Angle between the horizontal axis */ + /**< and the first side (i.e. length) in degrees */ + +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) : center(c), size(s), angle(a) {} + CvBox2D(const cv::RotatedRect& rr) : center(rr.center), size(rr.size), angle(rr.angle) {} +#endif +#ifdef __cplusplus + operator cv::RotatedRect() const { return cv::RotatedRect(center, size, angle); } +#endif +} +CvBox2D; + + +#ifdef __cplusplus +CV_INLINE CvBox2D cvBox2D(CvPoint2D32f c = CvPoint2D32f(), CvSize2D32f s = CvSize2D32f(), float a = 0) +{ + CvBox2D self; + self.center = c; + self.size = s; + self.angle = a; + return self; +} +CV_INLINE CvBox2D cvBox2D(const cv::RotatedRect& rr) +{ + CvBox2D self; + self.center = cvPoint2D32f(rr.center); + self.size = cvSize2D32f(rr.size); + self.angle = rr.angle; + return self; +} +#endif + + +/** Line iterator state: */ +typedef struct CvLineIterator +{ + /** Pointer to the current point: */ + uchar* ptr; + + /* Bresenham algorithm state: */ + int err; + int plus_delta; + int minus_delta; + int plus_step; + int minus_step; +} +CvLineIterator; + + + +/************************************* CvSlice ******************************************/ +#define CV_WHOLE_SEQ_END_INDEX 0x3fffffff +#define CV_WHOLE_SEQ cvSlice(0, CV_WHOLE_SEQ_END_INDEX) + +typedef struct CvSlice +{ + int start_index, end_index; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvSlice() __attribute__(( warning("Non-initialized variable") )) {} + template CvSlice(const std::initializer_list<_Tp> list) + { + CV_Assert(list.size() == 0 || list.size() == 2); + start_index = end_index = 0; + if (list.size() == 2) + { + start_index = list.begin()[0]; end_index = list.begin()[1]; + } + }; +#endif +#if defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__) + CvSlice(int start = 0, int end = 0) : start_index(start), end_index(end) {} + CvSlice(const cv::Range& r) { *this = (r.start != INT_MIN && r.end != INT_MAX) ? CvSlice(r.start, r.end) : CvSlice(0, CV_WHOLE_SEQ_END_INDEX); } + operator cv::Range() const { return (start_index == 0 && end_index == CV_WHOLE_SEQ_END_INDEX ) ? cv::Range::all() : cv::Range(start_index, end_index); } +#endif +} +CvSlice; + +CV_INLINE CvSlice cvSlice( int start, int end ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) && !defined(__CUDACC__)) + CvSlice slice = { start, end }; +#else + CvSlice slice(start, end); +#endif + return slice; +} + +#if defined(__cplusplus) +CV_INLINE CvSlice cvSlice(const cv::Range& r) +{ + CvSlice slice = (r.start != INT_MIN && r.end != INT_MAX) ? cvSlice(r.start, r.end) : cvSlice(0, CV_WHOLE_SEQ_END_INDEX); + return slice; +} +#endif + + +/************************************* CvScalar *****************************************/ +/** @sa Scalar_ + */ +typedef struct CvScalar +{ + double val[4]; + +#ifdef CV__VALIDATE_UNUNITIALIZED_VARS + CvScalar() __attribute__(( warning("Non-initialized variable") )) {} + CvScalar(const std::initializer_list list) + { + CV_Assert(list.size() == 0 || list.size() == 4); + val[0] = val[1] = val[2] = val[3] = 0; + if (list.size() == 4) + { + val[0] = list.begin()[0]; val[1] = list.begin()[1]; val[2] = list.begin()[2]; val[3] = list.begin()[3]; + } + }; +#elif defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus) + CvScalar() {} + CvScalar(double d0, double d1 = 0, double d2 = 0, double d3 = 0) { val[0] = d0; val[1] = d1; val[2] = d2; val[3] = d3; } + template + CvScalar(const cv::Scalar_<_Tp>& s) { val[0] = s.val[0]; val[1] = s.val[1]; val[2] = s.val[2]; val[3] = s.val[3]; } + template + CvScalar(const cv::Vec<_Tp, cn>& v) + { + int i; + for( i = 0; i < (cn < 4 ? cn : 4); i++ ) val[i] = v.val[i]; + for( ; i < 4; i++ ) val[i] = 0; + } +#endif +#ifdef __cplusplus + template + operator cv::Scalar_<_Tp>() const { return cv::Scalar_<_Tp>(cv::saturate_cast<_Tp>(val[0]), cv::saturate_cast<_Tp>(val[1]), cv::saturate_cast<_Tp>(val[2]), cv::saturate_cast<_Tp>(val[3])); } +#endif +} +CvScalar; + +CV_INLINE CvScalar cvScalar( double val0, double val1 CV_DEFAULT(0), + double val2 CV_DEFAULT(0), double val3 CV_DEFAULT(0)) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = val0; scalar.val[1] = val1; + scalar.val[2] = val2; scalar.val[3] = val3; + return scalar; +} + +#ifdef __cplusplus +CV_INLINE CvScalar cvScalar() +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; + return scalar; +} +CV_INLINE CvScalar cvScalar(const cv::Scalar& s) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = s.val[0]; + scalar.val[1] = s.val[1]; + scalar.val[2] = s.val[2]; + scalar.val[3] = s.val[3]; + return scalar; +} +#endif + +CV_INLINE CvScalar cvRealScalar( double val0 ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = val0; + scalar.val[1] = scalar.val[2] = scalar.val[3] = 0; + return scalar; +} + +CV_INLINE CvScalar cvScalarAll( double val0123 ) +{ +#if !(defined(CV__ENABLE_C_API_CTORS) && defined(__cplusplus)) + CvScalar scalar = CV_STRUCT_INITIALIZER; +#else + CvScalar scalar; +#endif + scalar.val[0] = val0123; + scalar.val[1] = val0123; + scalar.val[2] = val0123; + scalar.val[3] = val0123; + return scalar; +} + +/****************************************************************************************\ +* Dynamic Data structures * +\****************************************************************************************/ + +/******************************** Memory storage ****************************************/ + +typedef struct CvMemBlock +{ + struct CvMemBlock* prev; + struct CvMemBlock* next; +} +CvMemBlock; + +#define CV_STORAGE_MAGIC_VAL 0x42890000 + +typedef struct CvMemStorage +{ + int signature; + CvMemBlock* bottom; /**< First allocated block. */ + CvMemBlock* top; /**< Current memory block - top of the stack. */ + struct CvMemStorage* parent; /**< We get new blocks from parent as needed. */ + int block_size; /**< Block size. */ + int free_space; /**< Remaining free space in current block. */ +} +CvMemStorage; + +#define CV_IS_STORAGE(storage) \ + ((storage) != NULL && \ + (((CvMemStorage*)(storage))->signature & CV_MAGIC_MASK) == CV_STORAGE_MAGIC_VAL) + + +typedef struct CvMemStoragePos +{ + CvMemBlock* top; + int free_space; +} +CvMemStoragePos; + + +/*********************************** Sequence *******************************************/ + +typedef struct CvSeqBlock +{ + struct CvSeqBlock* prev; /**< Previous sequence block. */ + struct CvSeqBlock* next; /**< Next sequence block. */ + int start_index; /**< Index of the first element in the block + */ + /**< sequence->first->start_index. */ + int count; /**< Number of elements in the block. */ + schar* data; /**< Pointer to the first element of the block. */ +} +CvSeqBlock; + + +#define CV_TREE_NODE_FIELDS(node_type) \ + int flags; /**< Miscellaneous flags. */ \ + int header_size; /**< Size of sequence header. */ \ + struct node_type* h_prev; /**< Previous sequence. */ \ + struct node_type* h_next; /**< Next sequence. */ \ + struct node_type* v_prev; /**< 2nd previous sequence. */ \ + struct node_type* v_next /**< 2nd next sequence. */ + +/** + Read/Write sequence. + Elements can be dynamically inserted to or deleted from the sequence. +*/ +#define CV_SEQUENCE_FIELDS() \ + CV_TREE_NODE_FIELDS(CvSeq); \ + int total; /**< Total number of elements. */ \ + int elem_size; /**< Size of sequence element in bytes. */ \ + schar* block_max; /**< Maximal bound of the last block. */ \ + schar* ptr; /**< Current write pointer. */ \ + int delta_elems; /**< Grow seq this many at a time. */ \ + CvMemStorage* storage; /**< Where the seq is stored. */ \ + CvSeqBlock* free_blocks; /**< Free blocks list. */ \ + CvSeqBlock* first; /**< Pointer to the first sequence block. */ + +typedef struct CvSeq +{ + CV_SEQUENCE_FIELDS() +} +CvSeq; + +#define CV_TYPE_NAME_SEQ "opencv-sequence" +#define CV_TYPE_NAME_SEQ_TREE "opencv-sequence-tree" + +/*************************************** Set ********************************************/ +/** @brief Set + Order is not preserved. There can be gaps between sequence elements. + After the element has been inserted it stays in the same place all the time. + The MSB(most-significant or sign bit) of the first field (flags) is 0 iff the element exists. +*/ +#define CV_SET_ELEM_FIELDS(elem_type) \ + int flags; \ + struct elem_type* next_free; + +typedef struct CvSetElem +{ + CV_SET_ELEM_FIELDS(CvSetElem) +} +CvSetElem; + +#define CV_SET_FIELDS() \ + CV_SEQUENCE_FIELDS() \ + CvSetElem* free_elems; \ + int active_count; + +typedef struct CvSet +{ + CV_SET_FIELDS() +} +CvSet; + + +#define CV_SET_ELEM_IDX_MASK ((1 << 26) - 1) +#define CV_SET_ELEM_FREE_FLAG (1 << (sizeof(int)*8-1)) + +/** Checks whether the element pointed by ptr belongs to a set or not */ +#define CV_IS_SET_ELEM( ptr ) (((CvSetElem*)(ptr))->flags >= 0) + +/************************************* Graph ********************************************/ + +/** @name Graph + +We represent a graph as a set of vertices. Vertices contain their adjacency lists (more exactly, +pointers to first incoming or outcoming edge (or 0 if isolated vertex)). Edges are stored in +another set. There is a singly-linked list of incoming/outcoming edges for each vertex. + +Each edge consists of: + +- Two pointers to the starting and ending vertices (vtx[0] and vtx[1] respectively). + + A graph may be oriented or not. In the latter case, edges between vertex i to vertex j are not +distinguished during search operations. + +- Two pointers to next edges for the starting and ending vertices, where next[0] points to the +next edge in the vtx[0] adjacency list and next[1] points to the next edge in the vtx[1] +adjacency list. + +@see CvGraphEdge, CvGraphVtx, CvGraphVtx2D, CvGraph +@{ +*/ +#define CV_GRAPH_EDGE_FIELDS() \ + int flags; \ + float weight; \ + struct CvGraphEdge* next[2]; \ + struct CvGraphVtx* vtx[2]; + + +#define CV_GRAPH_VERTEX_FIELDS() \ + int flags; \ + struct CvGraphEdge* first; + + +typedef struct CvGraphEdge +{ + CV_GRAPH_EDGE_FIELDS() +} +CvGraphEdge; + +typedef struct CvGraphVtx +{ + CV_GRAPH_VERTEX_FIELDS() +} +CvGraphVtx; + +typedef struct CvGraphVtx2D +{ + CV_GRAPH_VERTEX_FIELDS() + CvPoint2D32f* ptr; +} +CvGraphVtx2D; + +/** + Graph is "derived" from the set (this is set a of vertices) + and includes another set (edges) +*/ +#define CV_GRAPH_FIELDS() \ + CV_SET_FIELDS() \ + CvSet* edges; + +typedef struct CvGraph +{ + CV_GRAPH_FIELDS() +} +CvGraph; + +#define CV_TYPE_NAME_GRAPH "opencv-graph" + +/** @} */ + +/*********************************** Chain/Contour *************************************/ + +typedef struct CvChain +{ + CV_SEQUENCE_FIELDS() + CvPoint origin; +} +CvChain; + +#define CV_CONTOUR_FIELDS() \ + CV_SEQUENCE_FIELDS() \ + CvRect rect; \ + int color; \ + int reserved[3]; + +typedef struct CvContour +{ + CV_CONTOUR_FIELDS() +} +CvContour; + +typedef CvContour CvPoint2DSeq; + +/****************************************************************************************\ +* Sequence types * +\****************************************************************************************/ + +#define CV_SEQ_MAGIC_VAL 0x42990000 + +#define CV_IS_SEQ(seq) \ + ((seq) != NULL && (((CvSeq*)(seq))->flags & CV_MAGIC_MASK) == CV_SEQ_MAGIC_VAL) + +#define CV_SET_MAGIC_VAL 0x42980000 +#define CV_IS_SET(set) \ + ((set) != NULL && (((CvSeq*)(set))->flags & CV_MAGIC_MASK) == CV_SET_MAGIC_VAL) + +#define CV_SEQ_ELTYPE_BITS 12 +#define CV_SEQ_ELTYPE_MASK ((1 << CV_SEQ_ELTYPE_BITS) - 1) + +#define CV_SEQ_ELTYPE_POINT CV_32SC2 /**< (x,y) */ +#define CV_SEQ_ELTYPE_CODE CV_8UC1 /**< freeman code: 0..7 */ +#define CV_SEQ_ELTYPE_GENERIC 0 +#define CV_SEQ_ELTYPE_PTR CV_MAKE_TYPE(CV_8U, 8 /*sizeof(void*)*/) +#define CV_SEQ_ELTYPE_PPOINT CV_SEQ_ELTYPE_PTR /**< &(x,y) */ +#define CV_SEQ_ELTYPE_INDEX CV_32SC1 /**< #(x,y) */ +#define CV_SEQ_ELTYPE_GRAPH_EDGE 0 /**< &next_o, &next_d, &vtx_o, &vtx_d */ +#define CV_SEQ_ELTYPE_GRAPH_VERTEX 0 /**< first_edge, &(x,y) */ +#define CV_SEQ_ELTYPE_TRIAN_ATR 0 /**< vertex of the binary tree */ +#define CV_SEQ_ELTYPE_CONNECTED_COMP 0 /**< connected component */ +#define CV_SEQ_ELTYPE_POINT3D CV_32FC3 /**< (x,y,z) */ + +#define CV_SEQ_KIND_BITS 2 +#define CV_SEQ_KIND_MASK (((1 << CV_SEQ_KIND_BITS) - 1)<flags & CV_SEQ_ELTYPE_MASK) +#define CV_SEQ_KIND( seq ) ((seq)->flags & CV_SEQ_KIND_MASK ) + +/** flag checking */ +#define CV_IS_SEQ_INDEX( seq ) ((CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_INDEX) && \ + (CV_SEQ_KIND(seq) == CV_SEQ_KIND_GENERIC)) + +#define CV_IS_SEQ_CURVE( seq ) (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE) +#define CV_IS_SEQ_CLOSED( seq ) (((seq)->flags & CV_SEQ_FLAG_CLOSED) != 0) +#define CV_IS_SEQ_CONVEX( seq ) 0 +#define CV_IS_SEQ_HOLE( seq ) (((seq)->flags & CV_SEQ_FLAG_HOLE) != 0) +#define CV_IS_SEQ_SIMPLE( seq ) 1 + +/** type checking macros */ +#define CV_IS_SEQ_POINT_SET( seq ) \ + ((CV_SEQ_ELTYPE(seq) == CV_32SC2 || CV_SEQ_ELTYPE(seq) == CV_32FC2)) + +#define CV_IS_SEQ_POINT_SUBSET( seq ) \ + (CV_IS_SEQ_INDEX( seq ) || CV_SEQ_ELTYPE(seq) == CV_SEQ_ELTYPE_PPOINT) + +#define CV_IS_SEQ_POLYLINE( seq ) \ + (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && CV_IS_SEQ_POINT_SET(seq)) + +#define CV_IS_SEQ_POLYGON( seq ) \ + (CV_IS_SEQ_POLYLINE(seq) && CV_IS_SEQ_CLOSED(seq)) + +#define CV_IS_SEQ_CHAIN( seq ) \ + (CV_SEQ_KIND(seq) == CV_SEQ_KIND_CURVE && (seq)->elem_size == 1) + +#define CV_IS_SEQ_CONTOUR( seq ) \ + (CV_IS_SEQ_CLOSED(seq) && (CV_IS_SEQ_POLYLINE(seq) || CV_IS_SEQ_CHAIN(seq))) + +#define CV_IS_SEQ_CHAIN_CONTOUR( seq ) \ + (CV_IS_SEQ_CHAIN( seq ) && CV_IS_SEQ_CLOSED( seq )) + +#define CV_IS_SEQ_POLYGON_TREE( seq ) \ + (CV_SEQ_ELTYPE (seq) == CV_SEQ_ELTYPE_TRIAN_ATR && \ + CV_SEQ_KIND( seq ) == CV_SEQ_KIND_BIN_TREE ) + +#define CV_IS_GRAPH( seq ) \ + (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_GRAPH) + +#define CV_IS_GRAPH_ORIENTED( seq ) \ + (((seq)->flags & CV_GRAPH_FLAG_ORIENTED) != 0) + +#define CV_IS_SUBDIV2D( seq ) \ + (CV_IS_SET(seq) && CV_SEQ_KIND((CvSet*)(seq)) == CV_SEQ_KIND_SUBDIV2D) + +/****************************************************************************************/ +/* Sequence writer & reader */ +/****************************************************************************************/ + +#define CV_SEQ_WRITER_FIELDS() \ + int header_size; \ + CvSeq* seq; /**< the sequence written */ \ + CvSeqBlock* block; /**< current block */ \ + schar* ptr; /**< pointer to free space */ \ + schar* block_min; /**< pointer to the beginning of block*/\ + schar* block_max; /**< pointer to the end of block */ + +typedef struct CvSeqWriter +{ + CV_SEQ_WRITER_FIELDS() +} +CvSeqWriter; + + +#define CV_SEQ_READER_FIELDS() \ + int header_size; \ + CvSeq* seq; /**< sequence, beign read */ \ + CvSeqBlock* block; /**< current block */ \ + schar* ptr; /**< pointer to element be read next */ \ + schar* block_min; /**< pointer to the beginning of block */\ + schar* block_max; /**< pointer to the end of block */ \ + int delta_index;/**< = seq->first->start_index */ \ + schar* prev_elem; /**< pointer to previous element */ + +typedef struct CvSeqReader +{ + CV_SEQ_READER_FIELDS() +} +CvSeqReader; + +/****************************************************************************************/ +/* Operations on sequences */ +/****************************************************************************************/ + +#define CV_SEQ_ELEM( seq, elem_type, index ) \ +/** assert gives some guarantee that parameter is valid */ \ +( assert(sizeof((seq)->first[0]) == sizeof(CvSeqBlock) && \ + (seq)->elem_size == sizeof(elem_type)), \ + (elem_type*)((seq)->first && (unsigned)index < \ + (unsigned)((seq)->first->count) ? \ + (seq)->first->data + (index) * sizeof(elem_type) : \ + cvGetSeqElem( (CvSeq*)(seq), (index) ))) +#define CV_GET_SEQ_ELEM( elem_type, seq, index ) CV_SEQ_ELEM( (seq), elem_type, (index) ) + +/** Add element to sequence: */ +#define CV_WRITE_SEQ_ELEM_VAR( elem_ptr, writer ) \ +{ \ + if( (writer).ptr >= (writer).block_max ) \ + { \ + cvCreateSeqBlock( &writer); \ + } \ + memcpy((writer).ptr, elem_ptr, (writer).seq->elem_size);\ + (writer).ptr += (writer).seq->elem_size; \ +} + +#define CV_WRITE_SEQ_ELEM( elem, writer ) \ +{ \ + assert( (writer).seq->elem_size == sizeof(elem)); \ + if( (writer).ptr >= (writer).block_max ) \ + { \ + cvCreateSeqBlock( &writer); \ + } \ + assert( (writer).ptr <= (writer).block_max - sizeof(elem));\ + memcpy((writer).ptr, &(elem), sizeof(elem)); \ + (writer).ptr += sizeof(elem); \ +} + + +/** Move reader position forward: */ +#define CV_NEXT_SEQ_ELEM( elem_size, reader ) \ +{ \ + if( ((reader).ptr += (elem_size)) >= (reader).block_max ) \ + { \ + cvChangeSeqBlock( &(reader), 1 ); \ + } \ +} + + +/** Move reader position backward: */ +#define CV_PREV_SEQ_ELEM( elem_size, reader ) \ +{ \ + if( ((reader).ptr -= (elem_size)) < (reader).block_min ) \ + { \ + cvChangeSeqBlock( &(reader), -1 ); \ + } \ +} + +/** Read element and move read position forward: */ +#define CV_READ_SEQ_ELEM( elem, reader ) \ +{ \ + assert( (reader).seq->elem_size == sizeof(elem)); \ + memcpy( &(elem), (reader).ptr, sizeof((elem))); \ + CV_NEXT_SEQ_ELEM( sizeof(elem), reader ) \ +} + +/** Read element and move read position backward: */ +#define CV_REV_READ_SEQ_ELEM( elem, reader ) \ +{ \ + assert( (reader).seq->elem_size == sizeof(elem)); \ + memcpy(&(elem), (reader).ptr, sizeof((elem))); \ + CV_PREV_SEQ_ELEM( sizeof(elem), reader ) \ +} + + +#define CV_READ_CHAIN_POINT( _pt, reader ) \ +{ \ + (_pt) = (reader).pt; \ + if( (reader).ptr ) \ + { \ + CV_READ_SEQ_ELEM( (reader).code, (reader)); \ + assert( ((reader).code & ~7) == 0 ); \ + (reader).pt.x += (reader).deltas[(int)(reader).code][0]; \ + (reader).pt.y += (reader).deltas[(int)(reader).code][1]; \ + } \ +} + +#define CV_CURRENT_POINT( reader ) (*((CvPoint*)((reader).ptr))) +#define CV_PREV_POINT( reader ) (*((CvPoint*)((reader).prev_elem))) + +#define CV_READ_EDGE( pt1, pt2, reader ) \ +{ \ + assert( sizeof(pt1) == sizeof(CvPoint) && \ + sizeof(pt2) == sizeof(CvPoint) && \ + reader.seq->elem_size == sizeof(CvPoint)); \ + (pt1) = CV_PREV_POINT( reader ); \ + (pt2) = CV_CURRENT_POINT( reader ); \ + (reader).prev_elem = (reader).ptr; \ + CV_NEXT_SEQ_ELEM( sizeof(CvPoint), (reader)); \ +} + +/************ Graph macros ************/ + +/** Return next graph edge for given vertex: */ +#define CV_NEXT_GRAPH_EDGE( edge, vertex ) \ + (assert((edge)->vtx[0] == (vertex) || (edge)->vtx[1] == (vertex)), \ + (edge)->next[(edge)->vtx[1] == (vertex)]) + + + +/****************************************************************************************\ +* Data structures for persistence (a.k.a serialization) functionality * +\****************************************************************************************/ + +#if 0 + +/** "black box" file storage */ +typedef struct CvFileStorage CvFileStorage; + +/** Storage flags: */ +#define CV_STORAGE_READ 0 +#define CV_STORAGE_WRITE 1 +#define CV_STORAGE_WRITE_TEXT CV_STORAGE_WRITE +#define CV_STORAGE_WRITE_BINARY CV_STORAGE_WRITE +#define CV_STORAGE_APPEND 2 +#define CV_STORAGE_MEMORY 4 +#define CV_STORAGE_FORMAT_MASK (7<<3) +#define CV_STORAGE_FORMAT_AUTO 0 +#define CV_STORAGE_FORMAT_XML 8 +#define CV_STORAGE_FORMAT_YAML 16 +#define CV_STORAGE_FORMAT_JSON 24 +#define CV_STORAGE_BASE64 64 +#define CV_STORAGE_WRITE_BASE64 (CV_STORAGE_BASE64 | CV_STORAGE_WRITE) + +/** @brief List of attributes. : + +In the current implementation, attributes are used to pass extra parameters when writing user +objects (see cvWrite). XML attributes inside tags are not supported, aside from the object type +specification (type_id attribute). +@see cvAttrList, cvAttrValue + */ +typedef struct CvAttrList +{ + const char** attr; /**< NULL-terminated array of (attribute_name,attribute_value) pairs. */ + struct CvAttrList* next; /**< Pointer to next chunk of the attributes list. */ +} +CvAttrList; + +/** initializes CvAttrList structure */ +CV_INLINE CvAttrList cvAttrList( const char** attr CV_DEFAULT(NULL), + CvAttrList* next CV_DEFAULT(NULL) ) +{ + CvAttrList l; + l.attr = attr; + l.next = next; + + return l; +} + +struct CvTypeInfo; + +#define CV_NODE_NONE 0 +#define CV_NODE_INT 1 +#define CV_NODE_INTEGER CV_NODE_INT +#define CV_NODE_REAL 2 +#define CV_NODE_FLOAT CV_NODE_REAL +#define CV_NODE_STR 3 +#define CV_NODE_STRING CV_NODE_STR +#define CV_NODE_REF 4 /**< not used */ +#define CV_NODE_SEQ 5 +#define CV_NODE_MAP 6 +#define CV_NODE_TYPE_MASK 7 + +#define CV_NODE_TYPE(flags) ((flags) & CV_NODE_TYPE_MASK) + +/** file node flags */ +#define CV_NODE_FLOW 8 /**= CV_NODE_SEQ) +#define CV_NODE_IS_FLOW(flags) (((flags) & CV_NODE_FLOW) != 0) +#define CV_NODE_IS_EMPTY(flags) (((flags) & CV_NODE_EMPTY) != 0) +#define CV_NODE_IS_USER(flags) (((flags) & CV_NODE_USER) != 0) +#define CV_NODE_HAS_NAME(flags) (((flags) & CV_NODE_NAMED) != 0) + +#define CV_NODE_SEQ_SIMPLE 256 +#define CV_NODE_SEQ_IS_SIMPLE(seq) (((seq)->flags & CV_NODE_SEQ_SIMPLE) != 0) + +typedef struct CvString +{ + int len; + char* ptr; +} +CvString; + +/** All the keys (names) of elements in the read file storage + are stored in the hash to speed up the lookup operations: */ +typedef struct CvStringHashNode +{ + unsigned hashval; + CvString str; + struct CvStringHashNode* next; +} +CvStringHashNode; + +typedef struct CvGenericHash CvFileNodeHash; + +/** Basic element of the file storage - scalar or collection: */ +typedef struct CvFileNode +{ + int tag; + struct CvTypeInfo* info; /**< type information + (only for user-defined object, for others it is 0) */ + union + { + double f; /**< scalar floating-point number */ + int i; /**< scalar integer number */ + CvString str; /**< text string */ + CvSeq* seq; /**< sequence (ordered collection of file nodes) */ + CvFileNodeHash* map; /**< map (collection of named file nodes) */ + } data; +} +CvFileNode; + +#ifdef __cplusplus +extern "C" { +#endif +typedef int (CV_CDECL *CvIsInstanceFunc)( const void* struct_ptr ); +typedef void (CV_CDECL *CvReleaseFunc)( void** struct_dblptr ); +typedef void* (CV_CDECL *CvReadFunc)( CvFileStorage* storage, CvFileNode* node ); +typedef void (CV_CDECL *CvWriteFunc)( CvFileStorage* storage, const char* name, + const void* struct_ptr, CvAttrList attributes ); +typedef void* (CV_CDECL *CvCloneFunc)( const void* struct_ptr ); +#ifdef __cplusplus +} +#endif + +/** @brief Type information + +The structure contains information about one of the standard or user-defined types. Instances of the +type may or may not contain a pointer to the corresponding CvTypeInfo structure. In any case, there +is a way to find the type info structure for a given object using the cvTypeOf function. +Alternatively, type info can be found by type name using cvFindType, which is used when an object +is read from file storage. The user can register a new type with cvRegisterType that adds the type +information structure into the beginning of the type list. Thus, it is possible to create +specialized types from generic standard types and override the basic methods. + */ +typedef struct CvTypeInfo +{ + int flags; /**< not used */ + int header_size; /**< sizeof(CvTypeInfo) */ + struct CvTypeInfo* prev; /**< previous registered type in the list */ + struct CvTypeInfo* next; /**< next registered type in the list */ + const char* type_name; /**< type name, written to file storage */ + CvIsInstanceFunc is_instance; /**< checks if the passed object belongs to the type */ + CvReleaseFunc release; /**< releases object (memory etc.) */ + CvReadFunc read; /**< reads object from file storage */ + CvWriteFunc write; /**< writes object to file storage */ + CvCloneFunc clone; /**< creates a copy of the object */ +} +CvTypeInfo; +#endif + +/** @} */ + +#endif /*OPENCV_CORE_TYPES_H*/ + +/* End of file. */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp index 985d20dcb4..cfe98401db 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utility.hpp @@ -1,1301 +1,1301 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2015, Itseez Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_CORE_UTILITY_H -#define OPENCV_CORE_UTILITY_H - -#ifndef __cplusplus -# error utility.hpp header must be compiled as C++ -#endif - -#if defined(check) -# warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. -#endif - -#include "opencv2/core.hpp" -#include - -#include - -#if !defined(_M_CEE) -#include // std::mutex, std::lock_guard -#endif - -namespace cv -{ - -//! @addtogroup core_utils -//! @{ - -/** @brief Automatically Allocated Buffer Class - - The class is used for temporary buffers in functions and methods. - If a temporary buffer is usually small (a few K's of memory), - but its size depends on the parameters, it makes sense to create a small - fixed-size array on stack and use it if it's large enough. If the required buffer size - is larger than the fixed size, another buffer of sufficient size is allocated dynamically - and released after the processing. Therefore, in typical cases, when the buffer size is small, - there is no overhead associated with malloc()/free(). - At the same time, there is no limit on the size of processed data. - - This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and - the number of stack-allocated elements. Here is how the class is used: - - \code - void my_func(const cv::Mat& m) - { - cv::AutoBuffer buf(1000); // create automatic buffer containing 1000 floats - - buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, - // otherwise the buffer of "m.rows" floats will be allocated - // dynamically and deallocated in cv::AutoBuffer destructor - ... - } - \endcode -*/ -#ifdef OPENCV_ENABLE_MEMORY_SANITIZER -template class AutoBuffer -#else -template class AutoBuffer -#endif -{ -public: - typedef _Tp value_type; - - //! the default constructor - AutoBuffer(); - //! constructor taking the real buffer size - explicit AutoBuffer(size_t _size); - - //! the copy constructor - AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf); - //! the assignment operator - AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf); - - //! destructor. calls deallocate() - ~AutoBuffer(); - - //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used - void allocate(size_t _size); - //! deallocates the buffer if it was dynamically allocated - void deallocate(); - //! resizes the buffer and preserves the content - void resize(size_t _size); - //! returns the current buffer size - size_t size() const; - //! returns pointer to the real buffer, stack-allocated or heap-allocated - inline _Tp* data() { return ptr; } - //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated - inline const _Tp* data() const { return ptr; } - -#if !defined(OPENCV_DISABLE_DEPRECATED_COMPATIBILITY) // use to .data() calls instead - //! returns pointer to the real buffer, stack-allocated or heap-allocated - operator _Tp* () { return ptr; } - //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated - operator const _Tp* () const { return ptr; } -#else - //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. - inline _Tp& operator[] (size_t i) { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } - //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. - inline const _Tp& operator[] (size_t i) const { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } -#endif - -protected: - //! pointer to the real buffer, can point to buf if the buffer is small enough - _Tp* ptr; - //! size of the real buffer - size_t sz; - //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements - _Tp buf[(fixed_size > 0) ? fixed_size : 1]; -}; - -/** @brief Sets/resets the break-on-error mode. - -When the break-on-error mode is set, the default error handler issues a hardware exception, which -can make debugging more convenient. - -\return the previous state - */ -CV_EXPORTS bool setBreakOnError(bool flag); - -extern "C" typedef int (*ErrorCallback)( int status, const char* func_name, - const char* err_msg, const char* file_name, - int line, void* userdata ); - - -/** @brief Sets the new error handler and the optional user data. - - The function sets the new error handler, called from cv::error(). - - \param errCallback the new error handler. If NULL, the default error handler is used. - \param userdata the optional user data pointer, passed to the callback. - \param prevUserdata the optional output parameter where the previous user data pointer is stored - - \return the previous error handler -*/ -CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); - -/** @brief Generates a unique temporary file name. - -This function generates a full, unique file path for a temporary file, -which can be used to create temporary files for various purposes. - -@param suffix (optional) The desired file extension or suffix for the temporary file (e.g., ".png", ".txt"). -If no suffix is provided (suffix = 0), the file will not have a specific extension. - -@return cv::String A full unique path for the temporary file. - -@note -- The function does not create the file, it only generates the name. -- The file name is unique for the system session. -- Works cross-platform (Windows, Linux, macOS). - */ -CV_EXPORTS String tempfile( const char* suffix = 0); - -/** @brief Searches for files matching the specified pattern in a directory. - -This function searches for files that match a given pattern (e.g., `*.jpg`) -in the specified directory. The search can be limited to the directory itself -or be recursive, including subdirectories. - -@param pattern The file search pattern, which can include wildcards like `*` -(for matching multiple characters) or `?` (for matching a single character). - -@param result Output vector where the file paths matching the search -pattern will be stored. -@param recursive (optional) Boolean flag indicating whether to search -subdirectories recursively. If true, the search will include all subdirectories. -The default value is `false`. - */ -CV_EXPORTS void glob(String pattern, std::vector& result, bool recursive = false); - -/** @brief OpenCV will try to set the number of threads for subsequent parallel regions. - -If threads == 1, OpenCV will disable threading optimizations and run all it's functions -sequentially. Passing threads \< 0 will reset threads number to system default. -The function is not thread-safe. It must not be called in parallel region or concurrent threads. - -OpenCV will try to run its functions with specified threads number, but some behaviour differs from -framework: -- `TBB` - User-defined parallel constructions will run with the same threads number, if - another is not specified. If later on user creates his own scheduler, OpenCV will use it. -- `OpenMP` - No special defined behaviour. -- `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its - functions sequentially. -- `GCD` - Supports only values \<= 0. -- `C=` - No special defined behaviour. -@param nthreads Number of threads used by OpenCV. -@sa getNumThreads, getThreadNum - */ -CV_EXPORTS_W void setNumThreads(int nthreads); - -/** @brief Returns the number of threads used by OpenCV for parallel regions. - -Always returns 1 if OpenCV is built without threading support. - -The exact meaning of return value depends on the threading framework used by OpenCV library: -- `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is - any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns - default number of threads used by TBB library. -- `OpenMP` - An upper bound on the number of threads that could be used to form a new team. -- `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions. -- `GCD` - Unsupported; returns the GCD thread pool limit (512) for compatibility. -- `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before - called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs, - available for the process. -@sa setNumThreads, getThreadNum - */ -CV_EXPORTS_W int getNumThreads(); - -/** @brief Returns the index of the currently executed thread within the current parallel region. Always -returns 0 if called outside of parallel region. - -@deprecated Current implementation doesn't corresponding to this documentation. - -The exact meaning of the return value depends on the threading framework used by OpenCV library: -- `TBB` - Unsupported with current 4.1 TBB release. Maybe will be supported in future. -- `OpenMP` - The thread number, within the current team, of the calling thread. -- `Concurrency` - An ID for the virtual processor that the current context is executing on (0 - for master thread and unique number for others, but not necessary 1,2,3,...). -- `GCD` - System calling thread's ID. Never returns 0 inside parallel region. -- `C=` - The index of the current parallel task. -@sa setNumThreads, getNumThreads - */ -CV_EXPORTS_W int getThreadNum(); - -/** @brief Returns full configuration time cmake output. - -Returned value is raw cmake output including version control system revision, compiler version, -compiler flags, enabled modules and third party libraries, etc. Output format depends on target -architecture. - */ -CV_EXPORTS_W const String& getBuildInformation(); - -/** @brief Returns library version string - -For example "3.4.1-dev". - -@sa getMajorVersion, getMinorVersion, getRevisionVersion -*/ -CV_EXPORTS_W String getVersionString(); - -/** @brief Returns major library version */ -CV_EXPORTS_W int getVersionMajor(); - -/** @brief Returns minor library version */ -CV_EXPORTS_W int getVersionMinor(); - -/** @brief Returns revision field of the library version */ -CV_EXPORTS_W int getVersionRevision(); - -/** @brief Returns the number of ticks. - -The function returns the number of ticks after the certain event (for example, when the machine was -turned on). It can be used to initialize RNG or to measure a function execution time by reading the -tick count before and after the function call. -@sa getTickFrequency, TickMeter - */ -CV_EXPORTS_W int64 getTickCount(); - -/** @brief Returns the number of ticks per second. - -The function returns the number of ticks per second. That is, the following code computes the -execution time in seconds: -@code - double t = (double)getTickCount(); - // do something ... - t = ((double)getTickCount() - t)/getTickFrequency(); -@endcode -@sa getTickCount, TickMeter - */ -CV_EXPORTS_W double getTickFrequency(); - -/** @brief a Class to measure passing time. - -The class computes passing time by counting the number of ticks per second. That is, the following code computes the -execution time in seconds: -@snippet snippets/core_various.cpp TickMeter_total - -It is also possible to compute the average time over multiple runs: -@snippet snippets/core_various.cpp TickMeter_average - -@sa getTickCount, getTickFrequency -*/ -class CV_EXPORTS_W TickMeter -{ -public: - //! the default constructor - CV_WRAP TickMeter() - { - reset(); - } - - //! starts counting ticks. - CV_WRAP void start() - { - startTime = cv::getTickCount(); - } - - //! stops counting ticks. - CV_WRAP void stop() - { - const int64 time = cv::getTickCount(); - if (startTime == 0) - return; - ++counter; - lastTime = time - startTime; - sumTime += lastTime; - startTime = 0; - } - - //! returns counted ticks. - CV_WRAP int64 getTimeTicks() const - { - return sumTime; - } - - //! returns passed time in microseconds. - CV_WRAP double getTimeMicro() const - { - return getTimeMilli()*1e3; - } - - //! returns passed time in milliseconds. - CV_WRAP double getTimeMilli() const - { - return getTimeSec()*1e3; - } - - //! returns passed time in seconds. - CV_WRAP double getTimeSec() const - { - return (double)getTimeTicks() / getTickFrequency(); - } - - //! returns counted ticks of the last iteration. - CV_WRAP int64 getLastTimeTicks() const - { - return lastTime; - } - - //! returns passed time of the last iteration in microseconds. - CV_WRAP double getLastTimeMicro() const - { - return getLastTimeMilli()*1e3; - } - - //! returns passed time of the last iteration in milliseconds. - CV_WRAP double getLastTimeMilli() const - { - return getLastTimeSec()*1e3; - } - - //! returns passed time of the last iteration in seconds. - CV_WRAP double getLastTimeSec() const - { - return (double)getLastTimeTicks() / getTickFrequency(); - } - - //! returns internal counter value. - CV_WRAP int64 getCounter() const - { - return counter; - } - - //! returns average FPS (frames per second) value. - CV_WRAP double getFPS() const - { - const double sec = getTimeSec(); - if (sec < DBL_EPSILON) - return 0.; - return counter / sec; - } - - //! returns average time in seconds - CV_WRAP double getAvgTimeSec() const - { - if (counter <= 0) - return 0.; - return getTimeSec() / counter; - } - - //! returns average time in milliseconds - CV_WRAP double getAvgTimeMilli() const - { - return getAvgTimeSec() * 1e3; - } - - //! resets internal values. - CV_WRAP void reset() - { - counter = 0; - sumTime = 0; - startTime = 0; - lastTime = 0; - } - -private: - int64 counter; - int64 sumTime; - int64 startTime; - int64 lastTime; -}; - -/** @brief output operator -@code -TickMeter tm; -tm.start(); -// do something ... -tm.stop(); -std::cout << tm; -@endcode -*/ - -static inline -std::ostream& operator << (std::ostream& out, const TickMeter& tm) -{ - return out << tm.getTimeSec() << "sec"; -} - -/** @brief Returns the number of CPU ticks. - -The function returns the current number of CPU ticks on some architectures (such as x86, x64, -PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for -very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU -systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU -with its own counter. So, theoretically (and practically) the subsequent calls to the function do -not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU -frequency depending on the load, the number of CPU clocks spent in some code cannot be directly -converted to time units. Therefore, getTickCount is generally a preferable solution for measuring -execution time. - */ -CV_EXPORTS_W int64 getCPUTickCount(); - -/** @brief Returns true if the specified feature is supported by the host hardware. - -The function returns true if the host hardware supports the specified feature. When user calls -setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until -setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code -in OpenCV. -@param feature The feature of interest, one of cv::CpuFeatures - */ -CV_EXPORTS_W bool checkHardwareSupport(int feature); - -/** @brief Returns feature name by ID - -Returns empty string if feature is not defined -*/ -CV_EXPORTS_W String getHardwareFeatureName(int feature); - -/** @brief Returns list of CPU features enabled during compilation. - -Returned value is a string containing space separated list of CPU features with following markers: - -- no markers - baseline features -- prefix `*` - features enabled in dispatcher -- suffix `?` - features enabled but not available in HW - -Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?` -*/ -CV_EXPORTS_W std::string getCPUFeaturesLine(); - -/** @brief Returns the number of logical CPUs available for the process. - */ -CV_EXPORTS_W int getNumberOfCPUs(); - - -/** @brief Aligns a pointer to the specified number of bytes. - -The function returns the aligned pointer of the same type as the input pointer: -\f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f] -@param ptr Aligned pointer. -@param n Alignment size that must be a power of two. - */ -template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) -{ - CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 - return (_Tp*)(((size_t)ptr + n-1) & -n); -} - -/** @brief Aligns a buffer size to the specified number of bytes. - -The function returns the minimum number that is greater than or equal to sz and is divisible by n : -\f[\texttt{(sz + n-1) & -n}\f] -@param sz Buffer size to align. -@param n Alignment size that must be a power of two. - */ -static inline size_t alignSize(size_t sz, int n) -{ - CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 - return (sz + n-1) & -n; -} - -/** @brief Integer division with result round up. - -Use this function instead of `ceil((float)a / b)` expressions. - -@sa alignSize -*/ -static inline int divUp(int a, unsigned int b) -{ - CV_DbgAssert(a >= 0); - return (a + b - 1) / b; -} -/** @overload */ -static inline size_t divUp(size_t a, unsigned int b) -{ - return (a + b - 1) / b; -} - -/** @brief Round first value up to the nearest multiple of second value. - -Use this function instead of `ceil((float)a / b) * b` expressions. - -@sa divUp -*/ -static inline int roundUp(int a, unsigned int b) -{ - CV_DbgAssert(a >= 0); - return a + b - 1 - (a + b -1) % b; -} -/** @overload */ -static inline size_t roundUp(size_t a, unsigned int b) -{ - return a + b - 1 - (a + b - 1) % b; -} - -/** @brief Alignment check of passed values - -Usage: `isAligned(...)` - -@note Alignment(N) must be a power of 2 (2**k, 2^k) -*/ -template static inline -bool isAligned(const T& data) -{ - CV_StaticAssert((N & (N - 1)) == 0, ""); // power of 2 - return (((size_t)data) & (N - 1)) == 0; -} -/** @overload */ -template static inline -bool isAligned(const void* p1) -{ - return isAligned((size_t)p1); -} -/** @overload */ -template static inline -bool isAligned(const void* p1, const void* p2) -{ - return isAligned(((size_t)p1)|((size_t)p2)); -} -/** @overload */ -template static inline -bool isAligned(const void* p1, const void* p2, const void* p3) -{ - return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)); -} -/** @overload */ -template static inline -bool isAligned(const void* p1, const void* p2, const void* p3, const void* p4) -{ - return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)|((size_t)p4)); -} - -/*! @brief Flags that allow to midify some functions behavior. Used as set of flags. -*/ -enum AlgorithmHint { - ALGO_HINT_DEFAULT = 0, //!< Default algorithm behaviour defined during OpenCV build - ALGO_HINT_ACCURATE = 1, //!< Use generic portable implementation - ALGO_HINT_APPROX = 2, //!< Allow alternative approximations to get faster implementation. Behaviour and result depends on a platform -}; - -/*! @brief Returns AlgorithmHint defined during OpenCV compilation. Defines #ALGO_HINT_DEFAULT behavior. - */ -CV_EXPORTS_W AlgorithmHint getDefaultAlgorithmHint(); - -/** @brief Enables or disables the optimized code. - -The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2, -and other instructions on the platforms that support it). It sets a global flag that is further -checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only -safe to call the function on the very top level in your application where you can be sure that no -other OpenCV function is currently executed. - -By default, the optimized code is enabled unless you disable it in CMake. The current status can be -retrieved using useOptimized. -@param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) -or not (onoff=false). - */ -CV_EXPORTS_W void setUseOptimized(bool onoff); - -/** @brief Returns the status of optimized code usage. - -The function returns true if the optimized code is enabled. Otherwise, it returns false. - */ -CV_EXPORTS_W bool useOptimized(); - -static inline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); } - -/////////////////////////////// Parallel Primitives ////////////////////////////////// - -/** @brief Base class for parallel data processors - -@ingroup core_parallel -*/ -class CV_EXPORTS ParallelLoopBody -{ -public: - virtual ~ParallelLoopBody(); - virtual void operator() (const Range& range) const = 0; -}; - -/** @brief Parallel data processor - -@ingroup core_parallel -*/ -CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); - -//! @ingroup core_parallel -class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody -{ -private: - std::function m_functor; -public: - inline - ParallelLoopBodyLambdaWrapper(std::function functor) - : m_functor(functor) - { - // nothing - } - - virtual void operator() (const cv::Range& range) const CV_OVERRIDE - { - m_functor(range); - } -}; - -//! @ingroup core_parallel -static inline -void parallel_for_(const Range& range, std::function functor, double nstripes=-1.) -{ - parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes); -} - - -/////////////////////////////// forEach method of cv::Mat //////////////////////////// -template inline -void Mat::forEach_impl(const Functor& operation) { - if (false) { - operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast(0)); - // If your compiler fails in this line. - // Please check that your functor signature is - // (_Tp&, const int*) <- multi-dimensional - // or (_Tp&, void*) <- in case you don't need current idx. - } - - CV_Assert(!empty()); - CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX); - const int LINES = static_cast(this->total() / this->size[this->dims - 1]); - - class PixelOperationWrapper :public ParallelLoopBody - { - public: - PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation) - : mat(frame), op(_operation) {} - virtual ~PixelOperationWrapper(){} - // ! Overloaded virtual operator - // convert range call to row call. - virtual void operator()(const Range &range) const CV_OVERRIDE - { - const int DIMS = mat->dims; - const int COLS = mat->size[DIMS - 1]; - if (DIMS <= 2) { - for (int row = range.start; row < range.end; ++row) { - this->rowCall2(row, COLS); - } - } else { - std::vector idx(DIMS); /// idx is modified in this->rowCall - idx[DIMS - 2] = range.start - 1; - - for (int line_num = range.start; line_num < range.end; ++line_num) { - idx[DIMS - 2]++; - for (int i = DIMS - 2; i >= 0; --i) { - if (idx[i] >= mat->size[i]) { - idx[i - 1] += idx[i] / mat->size[i]; - idx[i] %= mat->size[i]; - continue; // carry-over; - } - else { - break; - } - } - this->rowCall(&idx[0], COLS, DIMS); - } - } - } - private: - Mat_<_Tp>* const mat; - const Functor op; - // ! Call operator for each elements in this row. - inline void rowCall(int* const idx, const int COLS, const int DIMS) const { - int &col = idx[DIMS - 1]; - col = 0; - _Tp* pixel = &(mat->template at<_Tp>(idx)); - - while (col < COLS) { - op(*pixel, const_cast(idx)); - pixel++; col++; - } - col = 0; - } - // ! Call operator for each elements in this row. 2d mat special version. - inline void rowCall2(const int row, const int COLS) const { - union Index{ - int body[2]; - operator const int*() const { - return reinterpret_cast(this); - } - int& operator[](const int i) { - return body[i]; - } - } idx = {{row, 0}}; - // Special union is needed to avoid - // "error: array subscript is above array bounds [-Werror=array-bounds]" - // when call the functor `op` such that access idx[3]. - - _Tp* pixel = &(mat->template at<_Tp>(idx)); - const _Tp* const pixel_end = pixel + COLS; - while(pixel < pixel_end) { - op(*pixel++, static_cast(idx)); - idx[1]++; - } - } - PixelOperationWrapper& operator=(const PixelOperationWrapper &) { - CV_Assert(false); - // We can not remove this implementation because Visual Studio warning C4822. - return *this; - } - }; - - parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast*>(this), operation)); -} - -/////////////////////////// Synchronization Primitives /////////////////////////////// - -#if !defined(_M_CEE) -#ifndef OPENCV_DISABLE_THREAD_SUPPORT -typedef std::recursive_mutex Mutex; -typedef std::lock_guard AutoLock; -#else // OPENCV_DISABLE_THREAD_SUPPORT -// Custom (failing) implementation of `std::recursive_mutex`. -struct Mutex { - void lock(){ - CV_Error(cv::Error::StsNotImplemented, - "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); - } - void unlock(){ - CV_Error(cv::Error::StsNotImplemented, - "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); - } -}; -// Stub for cv::AutoLock when threads are disabled. -struct AutoLock { - AutoLock(Mutex &) { } -}; -#endif // OPENCV_DISABLE_THREAD_SUPPORT -#endif // !defined(_M_CEE) - - -/** @brief Designed for command line parsing - -The sample below demonstrates how to use CommandLineParser: -@code - CommandLineParser parser(argc, argv, keys); - parser.about("Application name v1.0.0"); - - if (parser.has("help")) - { - parser.printMessage(); - return 0; - } - - int N = parser.get("N"); - double fps = parser.get("fps"); - String path = parser.get("path"); - - use_time_stamp = parser.has("timestamp"); - - String img1 = parser.get(0); - String img2 = parser.get(1); - - int repeat = parser.get(2); - - if (!parser.check()) - { - parser.printErrors(); - return 0; - } -@endcode - -### Keys syntax - -The keys parameter is a string containing several blocks, each one is enclosed in curly braces and -describes one argument. Each argument contains three parts separated by the `|` symbol: - --# argument names is a list of option synonyms separated by standard space characters ' ' (to mark argument as positional, prefix it with the `@` symbol) --# default value will be used if the argument was not provided (can be empty) --# help message (can be empty) - -For example: - -@code{.cpp} - const String keys = - "{help h usage ? | | print this message }" - "{@image1 | | image1 for compare }" - "{@image2 || image2 for compare }" - "{@repeat |1 | number }" - "{path |. | path to file }" - "{fps | -1.0 | fps for output video }" - "{N count |100 | count of objects }" - "{ts timestamp | | use time stamp }" - ; -} -@endcode - -Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method. -Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their -actual value instead. -Note that whitespace characters other than standard spaces are considered part of the string. -Additionally, leading and trailing standard spaces around the help messages are ignored. - -String keys like `get("@image1")` return the empty string `""` by default - even with an empty default value. -Use the special `` default value to enforce that the returned string must not be empty. (like in `get("@image2")`) - -### Usage - -For the described keys: - -@code{.sh} - # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true) - $ ./app -N=200 1.png 2.jpg 19 -ts - - # Bad call - $ ./app -fps=aaa - ERRORS: - Parameter 'fps': can not convert: [aaa] to [double] -@endcode - */ -class CV_EXPORTS CommandLineParser -{ -public: - - /** @brief Constructor - - Initializes command line parser object - - @param argc number of command line arguments (from main()) - @param argv array of command line arguments (from main()) - @param keys string describing acceptable command line parameters (see class description for syntax) - */ - CommandLineParser(int argc, const char* const argv[], const String& keys); - - /** @brief Copy constructor */ - CommandLineParser(const CommandLineParser& parser); - - /** @brief Assignment operator */ - CommandLineParser& operator = (const CommandLineParser& parser); - - /** @brief Destructor */ - ~CommandLineParser(); - - /** @brief Returns application path - - This method returns the path to the executable from the command line (`argv[0]`). - - For example, if the application has been started with such a command: - @code{.sh} - $ ./bin/my-executable - @endcode - this method will return `./bin`. - */ - String getPathToApplication() const; - - /** @brief Access arguments by name - - Returns argument converted to selected type. If the argument is not known or can not be - converted to selected type, the error flag is set (can be checked with @ref check). - - For example, define: - @code{.cpp} - String keys = "{N count||}"; - @endcode - - Call: - @code{.sh} - $ ./my-app -N=20 - # or - $ ./my-app --count=20 - @endcode - - Access: - @code{.cpp} - int N = parser.get("N"); - @endcode - - @param name name of the argument - @param space_delete remove spaces from the left and right of the string - @tparam T the argument will be converted to this type if possible - - @note You can access positional arguments by their `@`-prefixed name: - @code{.cpp} - parser.get("@image"); - @endcode - */ - template - T get(const String& name, bool space_delete = true) const - { - T val = T(); - getByName(name, space_delete, ParamType::type, (void*)&val); - return val; - } - - /** @brief Access positional arguments by index - - Returns argument converted to selected type. Indexes are counted from zero. - - For example, define: - @code{.cpp} - String keys = "{@arg1||}{@arg2||}" - @endcode - - Call: - @code{.sh} - ./my-app abc qwe - @endcode - - Access arguments: - @code{.cpp} - String val_1 = parser.get(0); // returns "abc", arg1 - String val_2 = parser.get(1); // returns "qwe", arg2 - @endcode - - @param index index of the argument - @param space_delete remove spaces from the left and right of the string - @tparam T the argument will be converted to this type if possible - */ - template - T get(int index, bool space_delete = true) const - { - T val = T(); - getByIndex(index, space_delete, ParamType::type, (void*)&val); - return val; - } - - /** @brief Check if field was provided in the command line - - @param name argument name to check - */ - bool has(const String& name) const; - - /** @brief Check for parsing errors - - Returns false if error occurred while accessing the parameters (bad conversion, missing arguments, - etc.). Call @ref printErrors to print error messages list. - */ - bool check() const; - - /** @brief Set the about message - - The about message will be shown when @ref printMessage is called, right before arguments table. - */ - void about(const String& message); - - /** @brief Print help message - - This method will print standard help message containing the about message and arguments description. - - @sa about - */ - void printMessage() const; - - /** @brief Print list of errors occurred - - @sa check - */ - void printErrors() const; - -protected: - void getByName(const String& name, bool space_delete, Param type, void* dst) const; - void getByIndex(int index, bool space_delete, Param type, void* dst) const; - - struct Impl; - Impl* impl; -}; - -//! @} core_utils - -//! @cond IGNORED - -/////////////////////////////// AutoBuffer implementation //////////////////////////////////////// - -template inline -AutoBuffer<_Tp, fixed_size>::AutoBuffer() -{ - ptr = buf; - sz = fixed_size; -} - -template inline -AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) -{ - ptr = buf; - sz = fixed_size; - allocate(_size); -} - -template inline -AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf ) -{ - ptr = buf; - sz = fixed_size; - allocate(abuf.size()); - for( size_t i = 0; i < sz; i++ ) - ptr[i] = abuf.ptr[i]; -} - -template inline AutoBuffer<_Tp, fixed_size>& -AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf) -{ - if( this != &abuf ) - { - deallocate(); - allocate(abuf.size()); - for( size_t i = 0; i < sz; i++ ) - ptr[i] = abuf.ptr[i]; - } - return *this; -} - -template inline -AutoBuffer<_Tp, fixed_size>::~AutoBuffer() -{ deallocate(); } - -template inline void -AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) -{ - if(_size <= sz) - { - sz = _size; - return; - } - deallocate(); - sz = _size; - if(_size > fixed_size) - { - ptr = new _Tp[_size]; - } -} - -template inline void -AutoBuffer<_Tp, fixed_size>::deallocate() -{ - if( ptr != buf ) - { - delete[] ptr; - ptr = buf; - sz = fixed_size; - } -} - -template inline void -AutoBuffer<_Tp, fixed_size>::resize(size_t _size) -{ - if(_size <= sz) - { - sz = _size; - return; - } - size_t i, prevsize = sz, minsize = MIN(prevsize, _size); - _Tp* prevptr = ptr; - - ptr = _size > fixed_size ? new _Tp[_size] : buf; - sz = _size; - - if( ptr != prevptr ) - for( i = 0; i < minsize; i++ ) - ptr[i] = prevptr[i]; - for( i = prevsize; i < _size; i++ ) - ptr[i] = _Tp(); - - if( prevptr != buf ) - delete[] prevptr; -} - -template inline size_t -AutoBuffer<_Tp, fixed_size>::size() const -{ return sz; } - -//! @endcond - - -// Basic Node class for tree building -template -class CV_EXPORTS Node -{ -public: - Node() - { - m_pParent = 0; - } - Node(OBJECT& payload) : m_payload(payload) - { - m_pParent = 0; - } - ~Node() - { - removeChilds(); - if (m_pParent) - { - int idx = m_pParent->findChild(this); - if (idx >= 0) - m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx); - } - } - - Node* findChild(OBJECT& payload) const - { - for(size_t i = 0; i < this->m_childs.size(); i++) - { - if(this->m_childs[i]->m_payload == payload) - return this->m_childs[i]; - } - return NULL; - } - - int findChild(Node *pNode) const - { - for (size_t i = 0; i < this->m_childs.size(); i++) - { - if(this->m_childs[i] == pNode) - return (int)i; - } - return -1; - } - - void addChild(Node *pNode) - { - if(!pNode) - return; - - CV_Assert(pNode->m_pParent == 0); - pNode->m_pParent = this; - this->m_childs.push_back(pNode); - } - - void removeChilds() - { - for(size_t i = 0; i < m_childs.size(); i++) - { - m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming - delete m_childs[i]; - } - m_childs.clear(); - } - - int getDepth() - { - int count = 0; - Node *pParent = m_pParent; - while(pParent) count++, pParent = pParent->m_pParent; - return count; - } - -public: - OBJECT m_payload; - Node* m_pParent; - std::vector*> m_childs; -}; - - -namespace samples { - -//! @addtogroup core_utils_samples -// This section describes utility functions for OpenCV samples. -// -// @note Implementation of these utilities is not thread-safe. -// -//! @{ - -/** @brief Try to find requested data file - -Search directories: - -1. Directories passed via `addSamplesDataSearchPath()` -2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable -3. OPENCV_SAMPLES_DATA_PATH environment variable - If parameter value is not empty and nothing is found then stop searching. -4. Detects build/install path based on: - a. current working directory (CWD) - b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) -5. Scan `/{,data,samples/data}` directories if build directory is detected or the current directory is in source tree. -6. Scan `/share/OpenCV` directory if install directory is detected. - -@see cv::utils::findDataFile - -@param relative_path Relative path to data file -@param required Specify "file not found" handling. - If true, function prints information message and raises cv::Exception. - If false, function returns empty result -@param silentMode Disables messages -@return Returns path (absolute or relative to the current directory) or empty string if file is not found -*/ -CV_EXPORTS_W cv::String findFile(const cv::String& relative_path, bool required = true, bool silentMode = false); - -CV_EXPORTS_W cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode = false); - -inline cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode) -{ - cv::String res = findFile(relative_path, false, silentMode); - if (res.empty()) - return relative_path; - return res; -} - -/** @brief Override search data path by adding new search location - -Use this only to override default behavior -Passed paths are used in LIFO order. - -@param path Path to used samples data -*/ -CV_EXPORTS_W void addSamplesDataSearchPath(const cv::String& path); - -/** @brief Append samples search data sub directory - -General usage is to add OpenCV modules name (`/modules//samples/data` -> `/samples/data` + `modules//samples/data`). -Passed subdirectories are used in LIFO order. - -@param subdir samples data sub directory -*/ -CV_EXPORTS_W void addSamplesDataSearchSubDirectory(const cv::String& subdir); - -//! @} -} // namespace samples - -namespace utils { - -CV_EXPORTS int getThreadID(); - -} // namespace - -} //namespace cv - -#ifdef CV_COLLECT_IMPL_DATA -#include "opencv2/core/utils/instrumentation.hpp" -#else -/// Collect implementation data on OpenCV function call. Requires ENABLE_IMPL_COLLECTION build option. -#define CV_IMPL_ADD(impl) -#endif - -#endif //OPENCV_CORE_UTILITY_H +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2015, Itseez Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_CORE_UTILITY_H +#define OPENCV_CORE_UTILITY_H + +#ifndef __cplusplus +# error utility.hpp header must be compiled as C++ +#endif + +#if defined(check) +# warning Detected Apple 'check' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. +#endif + +#include "opencv2/core.hpp" +#include + +#include + +#if !defined(_M_CEE) +#include // std::mutex, std::lock_guard +#endif + +namespace cv +{ + +//! @addtogroup core_utils +//! @{ + +/** @brief Automatically Allocated Buffer Class + + The class is used for temporary buffers in functions and methods. + If a temporary buffer is usually small (a few K's of memory), + but its size depends on the parameters, it makes sense to create a small + fixed-size array on stack and use it if it's large enough. If the required buffer size + is larger than the fixed size, another buffer of sufficient size is allocated dynamically + and released after the processing. Therefore, in typical cases, when the buffer size is small, + there is no overhead associated with malloc()/free(). + At the same time, there is no limit on the size of processed data. + + This is what AutoBuffer does. The template takes 2 parameters - type of the buffer elements and + the number of stack-allocated elements. Here is how the class is used: + + \code + void my_func(const cv::Mat& m) + { + cv::AutoBuffer buf(1000); // create automatic buffer containing 1000 floats + + buf.allocate(m.rows); // if m.rows <= 1000, the pre-allocated buffer is used, + // otherwise the buffer of "m.rows" floats will be allocated + // dynamically and deallocated in cv::AutoBuffer destructor + ... + } + \endcode +*/ +#ifdef OPENCV_ENABLE_MEMORY_SANITIZER +template class AutoBuffer +#else +template class AutoBuffer +#endif +{ +public: + typedef _Tp value_type; + + //! the default constructor + AutoBuffer(); + //! constructor taking the real buffer size + explicit AutoBuffer(size_t _size); + + //! the copy constructor + AutoBuffer(const AutoBuffer<_Tp, fixed_size>& buf); + //! the assignment operator + AutoBuffer<_Tp, fixed_size>& operator = (const AutoBuffer<_Tp, fixed_size>& buf); + + //! destructor. calls deallocate() + ~AutoBuffer(); + + //! allocates the new buffer of size _size. if the _size is small enough, stack-allocated buffer is used + void allocate(size_t _size); + //! deallocates the buffer if it was dynamically allocated + void deallocate(); + //! resizes the buffer and preserves the content + void resize(size_t _size); + //! returns the current buffer size + size_t size() const; + //! returns pointer to the real buffer, stack-allocated or heap-allocated + inline _Tp* data() { return ptr; } + //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated + inline const _Tp* data() const { return ptr; } + +#if !defined(OPENCV_DISABLE_DEPRECATED_COMPATIBILITY) // use to .data() calls instead + //! returns pointer to the real buffer, stack-allocated or heap-allocated + operator _Tp* () { return ptr; } + //! returns read-only pointer to the real buffer, stack-allocated or heap-allocated + operator const _Tp* () const { return ptr; } +#else + //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. + inline _Tp& operator[] (size_t i) { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } + //! returns a reference to the element at specified location. No bounds checking is performed in Release builds. + inline const _Tp& operator[] (size_t i) const { CV_DbgCheckLT(i, sz, "out of range"); return ptr[i]; } +#endif + +protected: + //! pointer to the real buffer, can point to buf if the buffer is small enough + _Tp* ptr; + //! size of the real buffer + size_t sz; + //! pre-allocated buffer. At least 1 element to confirm C++ standard requirements + _Tp buf[(fixed_size > 0) ? fixed_size : 1]; +}; + +/** @brief Sets/resets the break-on-error mode. + +When the break-on-error mode is set, the default error handler issues a hardware exception, which +can make debugging more convenient. + +\return the previous state + */ +CV_EXPORTS bool setBreakOnError(bool flag); + +extern "C" typedef int (*ErrorCallback)( int status, const char* func_name, + const char* err_msg, const char* file_name, + int line, void* userdata ); + + +/** @brief Sets the new error handler and the optional user data. + + The function sets the new error handler, called from cv::error(). + + \param errCallback the new error handler. If NULL, the default error handler is used. + \param userdata the optional user data pointer, passed to the callback. + \param prevUserdata the optional output parameter where the previous user data pointer is stored + + \return the previous error handler +*/ +CV_EXPORTS ErrorCallback redirectError( ErrorCallback errCallback, void* userdata=0, void** prevUserdata=0); + +/** @brief Generates a unique temporary file name. + +This function generates a full, unique file path for a temporary file, +which can be used to create temporary files for various purposes. + +@param suffix (optional) The desired file extension or suffix for the temporary file (e.g., ".png", ".txt"). +If no suffix is provided (suffix = 0), the file will not have a specific extension. + +@return cv::String A full unique path for the temporary file. + +@note +- The function does not create the file, it only generates the name. +- The file name is unique for the system session. +- Works cross-platform (Windows, Linux, macOS). + */ +CV_EXPORTS String tempfile( const char* suffix = 0); + +/** @brief Searches for files matching the specified pattern in a directory. + +This function searches for files that match a given pattern (e.g., `*.jpg`) +in the specified directory. The search can be limited to the directory itself +or be recursive, including subdirectories. + +@param pattern The file search pattern, which can include wildcards like `*` +(for matching multiple characters) or `?` (for matching a single character). + +@param result Output vector where the file paths matching the search +pattern will be stored. +@param recursive (optional) Boolean flag indicating whether to search +subdirectories recursively. If true, the search will include all subdirectories. +The default value is `false`. + */ +CV_EXPORTS void glob(String pattern, std::vector& result, bool recursive = false); + +/** @brief OpenCV will try to set the number of threads for subsequent parallel regions. + +If threads == 1, OpenCV will disable threading optimizations and run all it's functions +sequentially. Passing threads \< 0 will reset threads number to system default. +The function is not thread-safe. It must not be called in parallel region or concurrent threads. + +OpenCV will try to run its functions with specified threads number, but some behaviour differs from +framework: +- `TBB` - User-defined parallel constructions will run with the same threads number, if + another is not specified. If later on user creates his own scheduler, OpenCV will use it. +- `OpenMP` - No special defined behaviour. +- `Concurrency` - If threads == 1, OpenCV will disable threading optimizations and run its + functions sequentially. +- `GCD` - Supports only values \<= 0. +- `C=` - No special defined behaviour. +@param nthreads Number of threads used by OpenCV. +@sa getNumThreads, getThreadNum + */ +CV_EXPORTS_W void setNumThreads(int nthreads); + +/** @brief Returns the number of threads used by OpenCV for parallel regions. + +Always returns 1 if OpenCV is built without threading support. + +The exact meaning of return value depends on the threading framework used by OpenCV library: +- `TBB` - The number of threads, that OpenCV will try to use for parallel regions. If there is + any tbb::thread_scheduler_init in user code conflicting with OpenCV, then function returns + default number of threads used by TBB library. +- `OpenMP` - An upper bound on the number of threads that could be used to form a new team. +- `Concurrency` - The number of threads, that OpenCV will try to use for parallel regions. +- `GCD` - Unsupported; returns the GCD thread pool limit (512) for compatibility. +- `C=` - The number of threads, that OpenCV will try to use for parallel regions, if before + called setNumThreads with threads \> 0, otherwise returns the number of logical CPUs, + available for the process. +@sa setNumThreads, getThreadNum + */ +CV_EXPORTS_W int getNumThreads(); + +/** @brief Returns the index of the currently executed thread within the current parallel region. Always +returns 0 if called outside of parallel region. + +@deprecated Current implementation doesn't corresponding to this documentation. + +The exact meaning of the return value depends on the threading framework used by OpenCV library: +- `TBB` - Unsupported with current 4.1 TBB release. Maybe will be supported in future. +- `OpenMP` - The thread number, within the current team, of the calling thread. +- `Concurrency` - An ID for the virtual processor that the current context is executing on (0 + for master thread and unique number for others, but not necessary 1,2,3,...). +- `GCD` - System calling thread's ID. Never returns 0 inside parallel region. +- `C=` - The index of the current parallel task. +@sa setNumThreads, getNumThreads + */ +CV_EXPORTS_W int getThreadNum(); + +/** @brief Returns full configuration time cmake output. + +Returned value is raw cmake output including version control system revision, compiler version, +compiler flags, enabled modules and third party libraries, etc. Output format depends on target +architecture. + */ +CV_EXPORTS_W const String& getBuildInformation(); + +/** @brief Returns library version string + +For example "3.4.1-dev". + +@sa getMajorVersion, getMinorVersion, getRevisionVersion +*/ +CV_EXPORTS_W String getVersionString(); + +/** @brief Returns major library version */ +CV_EXPORTS_W int getVersionMajor(); + +/** @brief Returns minor library version */ +CV_EXPORTS_W int getVersionMinor(); + +/** @brief Returns revision field of the library version */ +CV_EXPORTS_W int getVersionRevision(); + +/** @brief Returns the number of ticks. + +The function returns the number of ticks after the certain event (for example, when the machine was +turned on). It can be used to initialize RNG or to measure a function execution time by reading the +tick count before and after the function call. +@sa getTickFrequency, TickMeter + */ +CV_EXPORTS_W int64 getTickCount(); + +/** @brief Returns the number of ticks per second. + +The function returns the number of ticks per second. That is, the following code computes the +execution time in seconds: +@code + double t = (double)getTickCount(); + // do something ... + t = ((double)getTickCount() - t)/getTickFrequency(); +@endcode +@sa getTickCount, TickMeter + */ +CV_EXPORTS_W double getTickFrequency(); + +/** @brief a Class to measure passing time. + +The class computes passing time by counting the number of ticks per second. That is, the following code computes the +execution time in seconds: +@snippet snippets/core_various.cpp TickMeter_total + +It is also possible to compute the average time over multiple runs: +@snippet snippets/core_various.cpp TickMeter_average + +@sa getTickCount, getTickFrequency +*/ +class CV_EXPORTS_W TickMeter +{ +public: + //! the default constructor + CV_WRAP TickMeter() + { + reset(); + } + + //! starts counting ticks. + CV_WRAP void start() + { + startTime = cv::getTickCount(); + } + + //! stops counting ticks. + CV_WRAP void stop() + { + const int64 time = cv::getTickCount(); + if (startTime == 0) + return; + ++counter; + lastTime = time - startTime; + sumTime += lastTime; + startTime = 0; + } + + //! returns counted ticks. + CV_WRAP int64 getTimeTicks() const + { + return sumTime; + } + + //! returns passed time in microseconds. + CV_WRAP double getTimeMicro() const + { + return getTimeMilli()*1e3; + } + + //! returns passed time in milliseconds. + CV_WRAP double getTimeMilli() const + { + return getTimeSec()*1e3; + } + + //! returns passed time in seconds. + CV_WRAP double getTimeSec() const + { + return (double)getTimeTicks() / getTickFrequency(); + } + + //! returns counted ticks of the last iteration. + CV_WRAP int64 getLastTimeTicks() const + { + return lastTime; + } + + //! returns passed time of the last iteration in microseconds. + CV_WRAP double getLastTimeMicro() const + { + return getLastTimeMilli()*1e3; + } + + //! returns passed time of the last iteration in milliseconds. + CV_WRAP double getLastTimeMilli() const + { + return getLastTimeSec()*1e3; + } + + //! returns passed time of the last iteration in seconds. + CV_WRAP double getLastTimeSec() const + { + return (double)getLastTimeTicks() / getTickFrequency(); + } + + //! returns internal counter value. + CV_WRAP int64 getCounter() const + { + return counter; + } + + //! returns average FPS (frames per second) value. + CV_WRAP double getFPS() const + { + const double sec = getTimeSec(); + if (sec < DBL_EPSILON) + return 0.; + return counter / sec; + } + + //! returns average time in seconds + CV_WRAP double getAvgTimeSec() const + { + if (counter <= 0) + return 0.; + return getTimeSec() / counter; + } + + //! returns average time in milliseconds + CV_WRAP double getAvgTimeMilli() const + { + return getAvgTimeSec() * 1e3; + } + + //! resets internal values. + CV_WRAP void reset() + { + counter = 0; + sumTime = 0; + startTime = 0; + lastTime = 0; + } + +private: + int64 counter; + int64 sumTime; + int64 startTime; + int64 lastTime; +}; + +/** @brief output operator +@code +TickMeter tm; +tm.start(); +// do something ... +tm.stop(); +std::cout << tm; +@endcode +*/ + +static inline +std::ostream& operator << (std::ostream& out, const TickMeter& tm) +{ + return out << tm.getTimeSec() << "sec"; +} + +/** @brief Returns the number of CPU ticks. + +The function returns the current number of CPU ticks on some architectures (such as x86, x64, +PowerPC). On other platforms the function is equivalent to getTickCount. It can also be used for +very accurate time measurements, as well as for RNG initialization. Note that in case of multi-CPU +systems a thread, from which getCPUTickCount is called, can be suspended and resumed at another CPU +with its own counter. So, theoretically (and practically) the subsequent calls to the function do +not necessary return the monotonously increasing values. Also, since a modern CPU varies the CPU +frequency depending on the load, the number of CPU clocks spent in some code cannot be directly +converted to time units. Therefore, getTickCount is generally a preferable solution for measuring +execution time. + */ +CV_EXPORTS_W int64 getCPUTickCount(); + +/** @brief Returns true if the specified feature is supported by the host hardware. + +The function returns true if the host hardware supports the specified feature. When user calls +setUseOptimized(false), the subsequent calls to checkHardwareSupport() will return false until +setUseOptimized(true) is called. This way user can dynamically switch on and off the optimized code +in OpenCV. +@param feature The feature of interest, one of cv::CpuFeatures + */ +CV_EXPORTS_W bool checkHardwareSupport(int feature); + +/** @brief Returns feature name by ID + +Returns empty string if feature is not defined +*/ +CV_EXPORTS_W String getHardwareFeatureName(int feature); + +/** @brief Returns list of CPU features enabled during compilation. + +Returned value is a string containing space separated list of CPU features with following markers: + +- no markers - baseline features +- prefix `*` - features enabled in dispatcher +- suffix `?` - features enabled but not available in HW + +Example: `SSE SSE2 SSE3 *SSE4.1 *SSE4.2 *FP16 *AVX *AVX2 *AVX512-SKX?` +*/ +CV_EXPORTS_W std::string getCPUFeaturesLine(); + +/** @brief Returns the number of logical CPUs available for the process. + */ +CV_EXPORTS_W int getNumberOfCPUs(); + + +/** @brief Aligns a pointer to the specified number of bytes. + +The function returns the aligned pointer of the same type as the input pointer: +\f[\texttt{(_Tp*)(((size_t)ptr + n-1) & -n)}\f] +@param ptr Aligned pointer. +@param n Alignment size that must be a power of two. + */ +template static inline _Tp* alignPtr(_Tp* ptr, int n=(int)sizeof(_Tp)) +{ + CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 + return (_Tp*)(((size_t)ptr + n-1) & -n); +} + +/** @brief Aligns a buffer size to the specified number of bytes. + +The function returns the minimum number that is greater than or equal to sz and is divisible by n : +\f[\texttt{(sz + n-1) & -n}\f] +@param sz Buffer size to align. +@param n Alignment size that must be a power of two. + */ +static inline size_t alignSize(size_t sz, int n) +{ + CV_DbgAssert((n & (n - 1)) == 0); // n is a power of 2 + return (sz + n-1) & -n; +} + +/** @brief Integer division with result round up. + +Use this function instead of `ceil((float)a / b)` expressions. + +@sa alignSize +*/ +static inline int divUp(int a, unsigned int b) +{ + CV_DbgAssert(a >= 0); + return (a + b - 1) / b; +} +/** @overload */ +static inline size_t divUp(size_t a, unsigned int b) +{ + return (a + b - 1) / b; +} + +/** @brief Round first value up to the nearest multiple of second value. + +Use this function instead of `ceil((float)a / b) * b` expressions. + +@sa divUp +*/ +static inline int roundUp(int a, unsigned int b) +{ + CV_DbgAssert(a >= 0); + return a + b - 1 - (a + b -1) % b; +} +/** @overload */ +static inline size_t roundUp(size_t a, unsigned int b) +{ + return a + b - 1 - (a + b - 1) % b; +} + +/** @brief Alignment check of passed values + +Usage: `isAligned(...)` + +@note Alignment(N) must be a power of 2 (2**k, 2^k) +*/ +template static inline +bool isAligned(const T& data) +{ + CV_StaticAssert((N & (N - 1)) == 0, ""); // power of 2 + return (((size_t)data) & (N - 1)) == 0; +} +/** @overload */ +template static inline +bool isAligned(const void* p1) +{ + return isAligned((size_t)p1); +} +/** @overload */ +template static inline +bool isAligned(const void* p1, const void* p2) +{ + return isAligned(((size_t)p1)|((size_t)p2)); +} +/** @overload */ +template static inline +bool isAligned(const void* p1, const void* p2, const void* p3) +{ + return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)); +} +/** @overload */ +template static inline +bool isAligned(const void* p1, const void* p2, const void* p3, const void* p4) +{ + return isAligned(((size_t)p1)|((size_t)p2)|((size_t)p3)|((size_t)p4)); +} + +/*! @brief Flags that allow to midify some functions behavior. Used as set of flags. +*/ +enum AlgorithmHint { + ALGO_HINT_DEFAULT = 0, //!< Default algorithm behaviour defined during OpenCV build + ALGO_HINT_ACCURATE = 1, //!< Use generic portable implementation + ALGO_HINT_APPROX = 2, //!< Allow alternative approximations to get faster implementation. Behaviour and result depends on a platform +}; + +/*! @brief Returns AlgorithmHint defined during OpenCV compilation. Defines #ALGO_HINT_DEFAULT behavior. + */ +CV_EXPORTS_W AlgorithmHint getDefaultAlgorithmHint(); + +/** @brief Enables or disables the optimized code. + +The function can be used to dynamically turn on and off optimized dispatched code (code that uses SSE4.2, AVX/AVX2, +and other instructions on the platforms that support it). It sets a global flag that is further +checked by OpenCV functions. Since the flag is not checked in the inner OpenCV loops, it is only +safe to call the function on the very top level in your application where you can be sure that no +other OpenCV function is currently executed. + +By default, the optimized code is enabled unless you disable it in CMake. The current status can be +retrieved using useOptimized. +@param onoff The boolean flag specifying whether the optimized code should be used (onoff=true) +or not (onoff=false). + */ +CV_EXPORTS_W void setUseOptimized(bool onoff); + +/** @brief Returns the status of optimized code usage. + +The function returns true if the optimized code is enabled. Otherwise, it returns false. + */ +CV_EXPORTS_W bool useOptimized(); + +static inline size_t getElemSize(int type) { return (size_t)CV_ELEM_SIZE(type); } + +/////////////////////////////// Parallel Primitives ////////////////////////////////// + +/** @brief Base class for parallel data processors + +@ingroup core_parallel +*/ +class CV_EXPORTS ParallelLoopBody +{ +public: + virtual ~ParallelLoopBody(); + virtual void operator() (const Range& range) const = 0; +}; + +/** @brief Parallel data processor + +@ingroup core_parallel +*/ +CV_EXPORTS void parallel_for_(const Range& range, const ParallelLoopBody& body, double nstripes=-1.); + +//! @ingroup core_parallel +class ParallelLoopBodyLambdaWrapper : public ParallelLoopBody +{ +private: + std::function m_functor; +public: + inline + ParallelLoopBodyLambdaWrapper(std::function functor) + : m_functor(functor) + { + // nothing + } + + virtual void operator() (const cv::Range& range) const CV_OVERRIDE + { + m_functor(range); + } +}; + +//! @ingroup core_parallel +static inline +void parallel_for_(const Range& range, std::function functor, double nstripes=-1.) +{ + parallel_for_(range, ParallelLoopBodyLambdaWrapper(functor), nstripes); +} + + +/////////////////////////////// forEach method of cv::Mat //////////////////////////// +template inline +void Mat::forEach_impl(const Functor& operation) { + if (false) { + operation(*reinterpret_cast<_Tp*>(0), reinterpret_cast(0)); + // If your compiler fails in this line. + // Please check that your functor signature is + // (_Tp&, const int*) <- multi-dimensional + // or (_Tp&, void*) <- in case you don't need current idx. + } + + CV_Assert(!empty()); + CV_Assert(this->total() / this->size[this->dims - 1] <= INT_MAX); + const int LINES = static_cast(this->total() / this->size[this->dims - 1]); + + class PixelOperationWrapper :public ParallelLoopBody + { + public: + PixelOperationWrapper(Mat_<_Tp>* const frame, const Functor& _operation) + : mat(frame), op(_operation) {} + virtual ~PixelOperationWrapper(){} + // ! Overloaded virtual operator + // convert range call to row call. + virtual void operator()(const Range &range) const CV_OVERRIDE + { + const int DIMS = mat->dims; + const int COLS = mat->size[DIMS - 1]; + if (DIMS <= 2) { + for (int row = range.start; row < range.end; ++row) { + this->rowCall2(row, COLS); + } + } else { + std::vector idx(DIMS); /// idx is modified in this->rowCall + idx[DIMS - 2] = range.start - 1; + + for (int line_num = range.start; line_num < range.end; ++line_num) { + idx[DIMS - 2]++; + for (int i = DIMS - 2; i >= 0; --i) { + if (idx[i] >= mat->size[i]) { + idx[i - 1] += idx[i] / mat->size[i]; + idx[i] %= mat->size[i]; + continue; // carry-over; + } + else { + break; + } + } + this->rowCall(&idx[0], COLS, DIMS); + } + } + } + private: + Mat_<_Tp>* const mat; + const Functor op; + // ! Call operator for each elements in this row. + inline void rowCall(int* const idx, const int COLS, const int DIMS) const { + int &col = idx[DIMS - 1]; + col = 0; + _Tp* pixel = &(mat->template at<_Tp>(idx)); + + while (col < COLS) { + op(*pixel, const_cast(idx)); + pixel++; col++; + } + col = 0; + } + // ! Call operator for each elements in this row. 2d mat special version. + inline void rowCall2(const int row, const int COLS) const { + union Index{ + int body[2]; + operator const int*() const { + return reinterpret_cast(this); + } + int& operator[](const int i) { + return body[i]; + } + } idx = {{row, 0}}; + // Special union is needed to avoid + // "error: array subscript is above array bounds [-Werror=array-bounds]" + // when call the functor `op` such that access idx[3]. + + _Tp* pixel = &(mat->template at<_Tp>(idx)); + const _Tp* const pixel_end = pixel + COLS; + while(pixel < pixel_end) { + op(*pixel++, static_cast(idx)); + idx[1]++; + } + } + PixelOperationWrapper& operator=(const PixelOperationWrapper &) { + CV_Assert(false); + // We can not remove this implementation because Visual Studio warning C4822. + return *this; + } + }; + + parallel_for_(cv::Range(0, LINES), PixelOperationWrapper(reinterpret_cast*>(this), operation)); +} + +/////////////////////////// Synchronization Primitives /////////////////////////////// + +#if !defined(_M_CEE) +#ifndef OPENCV_DISABLE_THREAD_SUPPORT +typedef std::recursive_mutex Mutex; +typedef std::lock_guard AutoLock; +#else // OPENCV_DISABLE_THREAD_SUPPORT +// Custom (failing) implementation of `std::recursive_mutex`. +struct Mutex { + void lock(){ + CV_Error(cv::Error::StsNotImplemented, + "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); + } + void unlock(){ + CV_Error(cv::Error::StsNotImplemented, + "cv::Mutex is disabled by OPENCV_DISABLE_THREAD_SUPPORT=ON"); + } +}; +// Stub for cv::AutoLock when threads are disabled. +struct AutoLock { + AutoLock(Mutex &) { } +}; +#endif // OPENCV_DISABLE_THREAD_SUPPORT +#endif // !defined(_M_CEE) + + +/** @brief Designed for command line parsing + +The sample below demonstrates how to use CommandLineParser: +@code + CommandLineParser parser(argc, argv, keys); + parser.about("Application name v1.0.0"); + + if (parser.has("help")) + { + parser.printMessage(); + return 0; + } + + int N = parser.get("N"); + double fps = parser.get("fps"); + String path = parser.get("path"); + + use_time_stamp = parser.has("timestamp"); + + String img1 = parser.get(0); + String img2 = parser.get(1); + + int repeat = parser.get(2); + + if (!parser.check()) + { + parser.printErrors(); + return 0; + } +@endcode + +### Keys syntax + +The keys parameter is a string containing several blocks, each one is enclosed in curly braces and +describes one argument. Each argument contains three parts separated by the `|` symbol: + +-# argument names is a list of option synonyms separated by standard space characters ' ' (to mark argument as positional, prefix it with the `@` symbol) +-# default value will be used if the argument was not provided (can be empty) +-# help message (can be empty) + +For example: + +@code{.cpp} + const String keys = + "{help h usage ? | | print this message }" + "{@image1 | | image1 for compare }" + "{@image2 || image2 for compare }" + "{@repeat |1 | number }" + "{path |. | path to file }" + "{fps | -1.0 | fps for output video }" + "{N count |100 | count of objects }" + "{ts timestamp | | use time stamp }" + ; +} +@endcode + +Note that there are no default values for `help` and `timestamp` so we can check their presence using the `has()` method. +Arguments with default values are considered to be always present. Use the `get()` method in these cases to check their +actual value instead. +Note that whitespace characters other than standard spaces are considered part of the string. +Additionally, leading and trailing standard spaces around the help messages are ignored. + +String keys like `get("@image1")` return the empty string `""` by default - even with an empty default value. +Use the special `` default value to enforce that the returned string must not be empty. (like in `get("@image2")`) + +### Usage + +For the described keys: + +@code{.sh} + # Good call (3 positional parameters: image1, image2 and repeat; N is 200, ts is true) + $ ./app -N=200 1.png 2.jpg 19 -ts + + # Bad call + $ ./app -fps=aaa + ERRORS: + Parameter 'fps': can not convert: [aaa] to [double] +@endcode + */ +class CV_EXPORTS CommandLineParser +{ +public: + + /** @brief Constructor + + Initializes command line parser object + + @param argc number of command line arguments (from main()) + @param argv array of command line arguments (from main()) + @param keys string describing acceptable command line parameters (see class description for syntax) + */ + CommandLineParser(int argc, const char* const argv[], const String& keys); + + /** @brief Copy constructor */ + CommandLineParser(const CommandLineParser& parser); + + /** @brief Assignment operator */ + CommandLineParser& operator = (const CommandLineParser& parser); + + /** @brief Destructor */ + ~CommandLineParser(); + + /** @brief Returns application path + + This method returns the path to the executable from the command line (`argv[0]`). + + For example, if the application has been started with such a command: + @code{.sh} + $ ./bin/my-executable + @endcode + this method will return `./bin`. + */ + String getPathToApplication() const; + + /** @brief Access arguments by name + + Returns argument converted to selected type. If the argument is not known or can not be + converted to selected type, the error flag is set (can be checked with @ref check). + + For example, define: + @code{.cpp} + String keys = "{N count||}"; + @endcode + + Call: + @code{.sh} + $ ./my-app -N=20 + # or + $ ./my-app --count=20 + @endcode + + Access: + @code{.cpp} + int N = parser.get("N"); + @endcode + + @param name name of the argument + @param space_delete remove spaces from the left and right of the string + @tparam T the argument will be converted to this type if possible + + @note You can access positional arguments by their `@`-prefixed name: + @code{.cpp} + parser.get("@image"); + @endcode + */ + template + T get(const String& name, bool space_delete = true) const + { + T val = T(); + getByName(name, space_delete, ParamType::type, (void*)&val); + return val; + } + + /** @brief Access positional arguments by index + + Returns argument converted to selected type. Indexes are counted from zero. + + For example, define: + @code{.cpp} + String keys = "{@arg1||}{@arg2||}" + @endcode + + Call: + @code{.sh} + ./my-app abc qwe + @endcode + + Access arguments: + @code{.cpp} + String val_1 = parser.get(0); // returns "abc", arg1 + String val_2 = parser.get(1); // returns "qwe", arg2 + @endcode + + @param index index of the argument + @param space_delete remove spaces from the left and right of the string + @tparam T the argument will be converted to this type if possible + */ + template + T get(int index, bool space_delete = true) const + { + T val = T(); + getByIndex(index, space_delete, ParamType::type, (void*)&val); + return val; + } + + /** @brief Check if field was provided in the command line + + @param name argument name to check + */ + bool has(const String& name) const; + + /** @brief Check for parsing errors + + Returns false if error occurred while accessing the parameters (bad conversion, missing arguments, + etc.). Call @ref printErrors to print error messages list. + */ + bool check() const; + + /** @brief Set the about message + + The about message will be shown when @ref printMessage is called, right before arguments table. + */ + void about(const String& message); + + /** @brief Print help message + + This method will print standard help message containing the about message and arguments description. + + @sa about + */ + void printMessage() const; + + /** @brief Print list of errors occurred + + @sa check + */ + void printErrors() const; + +protected: + void getByName(const String& name, bool space_delete, Param type, void* dst) const; + void getByIndex(int index, bool space_delete, Param type, void* dst) const; + + struct Impl; + Impl* impl; +}; + +//! @} core_utils + +//! @cond IGNORED + +/////////////////////////////// AutoBuffer implementation //////////////////////////////////////// + +template inline +AutoBuffer<_Tp, fixed_size>::AutoBuffer() +{ + ptr = buf; + sz = fixed_size; +} + +template inline +AutoBuffer<_Tp, fixed_size>::AutoBuffer(size_t _size) +{ + ptr = buf; + sz = fixed_size; + allocate(_size); +} + +template inline +AutoBuffer<_Tp, fixed_size>::AutoBuffer(const AutoBuffer<_Tp, fixed_size>& abuf ) +{ + ptr = buf; + sz = fixed_size; + allocate(abuf.size()); + for( size_t i = 0; i < sz; i++ ) + ptr[i] = abuf.ptr[i]; +} + +template inline AutoBuffer<_Tp, fixed_size>& +AutoBuffer<_Tp, fixed_size>::operator = (const AutoBuffer<_Tp, fixed_size>& abuf) +{ + if( this != &abuf ) + { + deallocate(); + allocate(abuf.size()); + for( size_t i = 0; i < sz; i++ ) + ptr[i] = abuf.ptr[i]; + } + return *this; +} + +template inline +AutoBuffer<_Tp, fixed_size>::~AutoBuffer() +{ deallocate(); } + +template inline void +AutoBuffer<_Tp, fixed_size>::allocate(size_t _size) +{ + if(_size <= sz) + { + sz = _size; + return; + } + deallocate(); + sz = _size; + if(_size > fixed_size) + { + ptr = new _Tp[_size]; + } +} + +template inline void +AutoBuffer<_Tp, fixed_size>::deallocate() +{ + if( ptr != buf ) + { + delete[] ptr; + ptr = buf; + sz = fixed_size; + } +} + +template inline void +AutoBuffer<_Tp, fixed_size>::resize(size_t _size) +{ + if(_size <= sz) + { + sz = _size; + return; + } + size_t i, prevsize = sz, minsize = MIN(prevsize, _size); + _Tp* prevptr = ptr; + + ptr = _size > fixed_size ? new _Tp[_size] : buf; + sz = _size; + + if( ptr != prevptr ) + for( i = 0; i < minsize; i++ ) + ptr[i] = prevptr[i]; + for( i = prevsize; i < _size; i++ ) + ptr[i] = _Tp(); + + if( prevptr != buf ) + delete[] prevptr; +} + +template inline size_t +AutoBuffer<_Tp, fixed_size>::size() const +{ return sz; } + +//! @endcond + + +// Basic Node class for tree building +template +class CV_EXPORTS Node +{ +public: + Node() + { + m_pParent = 0; + } + Node(OBJECT& payload) : m_payload(payload) + { + m_pParent = 0; + } + ~Node() + { + removeChilds(); + if (m_pParent) + { + int idx = m_pParent->findChild(this); + if (idx >= 0) + m_pParent->m_childs.erase(m_pParent->m_childs.begin() + idx); + } + } + + Node* findChild(OBJECT& payload) const + { + for(size_t i = 0; i < this->m_childs.size(); i++) + { + if(this->m_childs[i]->m_payload == payload) + return this->m_childs[i]; + } + return NULL; + } + + int findChild(Node *pNode) const + { + for (size_t i = 0; i < this->m_childs.size(); i++) + { + if(this->m_childs[i] == pNode) + return (int)i; + } + return -1; + } + + void addChild(Node *pNode) + { + if(!pNode) + return; + + CV_Assert(pNode->m_pParent == 0); + pNode->m_pParent = this; + this->m_childs.push_back(pNode); + } + + void removeChilds() + { + for(size_t i = 0; i < m_childs.size(); i++) + { + m_childs[i]->m_pParent = 0; // avoid excessive parent vector trimming + delete m_childs[i]; + } + m_childs.clear(); + } + + int getDepth() + { + int count = 0; + Node *pParent = m_pParent; + while(pParent) count++, pParent = pParent->m_pParent; + return count; + } + +public: + OBJECT m_payload; + Node* m_pParent; + std::vector*> m_childs; +}; + + +namespace samples { + +//! @addtogroup core_utils_samples +// This section describes utility functions for OpenCV samples. +// +// @note Implementation of these utilities is not thread-safe. +// +//! @{ + +/** @brief Try to find requested data file + +Search directories: + +1. Directories passed via `addSamplesDataSearchPath()` +2. OPENCV_SAMPLES_DATA_PATH_HINT environment variable +3. OPENCV_SAMPLES_DATA_PATH environment variable + If parameter value is not empty and nothing is found then stop searching. +4. Detects build/install path based on: + a. current working directory (CWD) + b. and/or binary module location (opencv_core/opencv_world, doesn't work with static linkage) +5. Scan `/{,data,samples/data}` directories if build directory is detected or the current directory is in source tree. +6. Scan `/share/OpenCV` directory if install directory is detected. + +@see cv::utils::findDataFile + +@param relative_path Relative path to data file +@param required Specify "file not found" handling. + If true, function prints information message and raises cv::Exception. + If false, function returns empty result +@param silentMode Disables messages +@return Returns path (absolute or relative to the current directory) or empty string if file is not found +*/ +CV_EXPORTS_W cv::String findFile(const cv::String& relative_path, bool required = true, bool silentMode = false); + +CV_EXPORTS_W cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode = false); + +inline cv::String findFileOrKeep(const cv::String& relative_path, bool silentMode) +{ + cv::String res = findFile(relative_path, false, silentMode); + if (res.empty()) + return relative_path; + return res; +} + +/** @brief Override search data path by adding new search location + +Use this only to override default behavior +Passed paths are used in LIFO order. + +@param path Path to used samples data +*/ +CV_EXPORTS_W void addSamplesDataSearchPath(const cv::String& path); + +/** @brief Append samples search data sub directory + +General usage is to add OpenCV modules name (`/modules//samples/data` -> `/samples/data` + `modules//samples/data`). +Passed subdirectories are used in LIFO order. + +@param subdir samples data sub directory +*/ +CV_EXPORTS_W void addSamplesDataSearchSubDirectory(const cv::String& subdir); + +//! @} +} // namespace samples + +namespace utils { + +CV_EXPORTS int getThreadID(); + +} // namespace + +} //namespace cv + +#ifdef CV_COLLECT_IMPL_DATA +#include "opencv2/core/utils/instrumentation.hpp" +#else +/// Collect implementation data on OpenCV function call. Requires ENABLE_IMPL_COLLECTION build option. +#define CV_IMPL_ADD(impl) +#endif + +#endif //OPENCV_CORE_UTILITY_H diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp index f0adb6fe0a..79e933820a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.hpp @@ -1,29 +1,29 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ALLOCATOR_STATS_HPP -#define OPENCV_CORE_ALLOCATOR_STATS_HPP - -#include "../cvdef.h" - -namespace cv { namespace utils { - -class AllocatorStatisticsInterface -{ -protected: - AllocatorStatisticsInterface() {} - virtual ~AllocatorStatisticsInterface() {} -public: - virtual uint64_t getCurrentUsage() const = 0; - virtual uint64_t getTotalUsage() const = 0; - virtual uint64_t getNumberOfAllocations() const = 0; - virtual uint64_t getPeakUsage() const = 0; - - /** set peak usage = current usage */ - virtual void resetPeakUsage() = 0; -}; - -}} // namespace - -#endif // OPENCV_CORE_ALLOCATOR_STATS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ALLOCATOR_STATS_HPP +#define OPENCV_CORE_ALLOCATOR_STATS_HPP + +#include "../cvdef.h" + +namespace cv { namespace utils { + +class AllocatorStatisticsInterface +{ +protected: + AllocatorStatisticsInterface() {} + virtual ~AllocatorStatisticsInterface() {} +public: + virtual uint64_t getCurrentUsage() const = 0; + virtual uint64_t getTotalUsage() const = 0; + virtual uint64_t getNumberOfAllocations() const = 0; + virtual uint64_t getPeakUsage() const = 0; + + /** set peak usage = current usage */ + virtual void resetPeakUsage() = 0; +}; + +}} // namespace + +#endif // OPENCV_CORE_ALLOCATOR_STATS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp index 99ceabc547..bbc6cf8979 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/allocator_stats.impl.hpp @@ -1,106 +1,106 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP -#define OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP - -#include "./allocator_stats.hpp" - -//#define OPENCV_DISABLE_ALLOCATOR_STATS - -#include - -#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE -#if defined(__GNUC__) && (\ - (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) || \ - (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)) \ - ) -#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE int -#endif -#endif - -#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE -#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE long long -#endif - -namespace cv { namespace utils { - -#ifdef CV__ALLOCATOR_STATS_LOG -namespace { -#endif - -class AllocatorStatistics : public AllocatorStatisticsInterface -{ -#ifdef OPENCV_DISABLE_ALLOCATOR_STATS - -public: - AllocatorStatistics() {} - ~AllocatorStatistics() CV_OVERRIDE {} - - uint64_t getCurrentUsage() const CV_OVERRIDE { return 0; } - uint64_t getTotalUsage() const CV_OVERRIDE { return 0; } - uint64_t getNumberOfAllocations() const CV_OVERRIDE { return 0; } - uint64_t getPeakUsage() const CV_OVERRIDE { return 0; } - - /** set peak usage = current usage */ - void resetPeakUsage() CV_OVERRIDE {}; - - void onAllocate(size_t /*sz*/) {} - void onFree(size_t /*sz*/) {} - -#else - -protected: - typedef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE counter_t; - std::atomic curr, total, total_allocs, peak; -public: - AllocatorStatistics() {} - ~AllocatorStatistics() CV_OVERRIDE {} - - uint64_t getCurrentUsage() const CV_OVERRIDE { return (uint64_t)curr.load(); } - uint64_t getTotalUsage() const CV_OVERRIDE { return (uint64_t)total.load(); } - uint64_t getNumberOfAllocations() const CV_OVERRIDE { return (uint64_t)total_allocs.load(); } - uint64_t getPeakUsage() const CV_OVERRIDE { return (uint64_t)peak.load(); } - - /** set peak usage = current usage */ - void resetPeakUsage() CV_OVERRIDE { peak.store(curr.load()); } - - // Controller interface - void onAllocate(size_t sz) - { -#ifdef CV__ALLOCATOR_STATS_LOG - CV__ALLOCATOR_STATS_LOG(cv::format("allocate: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); -#endif - - counter_t new_curr = curr.fetch_add((counter_t)sz) + (counter_t)sz; - - // peak = std::max((uint64_t)peak, new_curr); - auto prev_peak = peak.load(); - while (prev_peak < new_curr) - { - if (peak.compare_exchange_weak(prev_peak, new_curr)) - break; - } - // end of peak = max(...) - - total += (counter_t)sz; - total_allocs++; - } - void onFree(size_t sz) - { -#ifdef CV__ALLOCATOR_STATS_LOG - CV__ALLOCATOR_STATS_LOG(cv::format("free: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); -#endif - curr -= (counter_t)sz; - } -#endif // OPENCV_DISABLE_ALLOCATOR_STATS -}; - -#ifdef CV__ALLOCATOR_STATS_LOG -} // namespace -#endif - -}} // namespace - -#endif // OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP +#define OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP + +#include "./allocator_stats.hpp" + +//#define OPENCV_DISABLE_ALLOCATOR_STATS + +#include + +#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE +#if defined(__GNUC__) && (\ + (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 4) || \ + (defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4) && !defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)) \ + ) +#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE int +#endif +#endif + +#ifndef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE +#define OPENCV_ALLOCATOR_STATS_COUNTER_TYPE long long +#endif + +namespace cv { namespace utils { + +#ifdef CV__ALLOCATOR_STATS_LOG +namespace { +#endif + +class AllocatorStatistics : public AllocatorStatisticsInterface +{ +#ifdef OPENCV_DISABLE_ALLOCATOR_STATS + +public: + AllocatorStatistics() {} + ~AllocatorStatistics() CV_OVERRIDE {} + + uint64_t getCurrentUsage() const CV_OVERRIDE { return 0; } + uint64_t getTotalUsage() const CV_OVERRIDE { return 0; } + uint64_t getNumberOfAllocations() const CV_OVERRIDE { return 0; } + uint64_t getPeakUsage() const CV_OVERRIDE { return 0; } + + /** set peak usage = current usage */ + void resetPeakUsage() CV_OVERRIDE {}; + + void onAllocate(size_t /*sz*/) {} + void onFree(size_t /*sz*/) {} + +#else + +protected: + typedef OPENCV_ALLOCATOR_STATS_COUNTER_TYPE counter_t; + std::atomic curr, total, total_allocs, peak; +public: + AllocatorStatistics() {} + ~AllocatorStatistics() CV_OVERRIDE {} + + uint64_t getCurrentUsage() const CV_OVERRIDE { return (uint64_t)curr.load(); } + uint64_t getTotalUsage() const CV_OVERRIDE { return (uint64_t)total.load(); } + uint64_t getNumberOfAllocations() const CV_OVERRIDE { return (uint64_t)total_allocs.load(); } + uint64_t getPeakUsage() const CV_OVERRIDE { return (uint64_t)peak.load(); } + + /** set peak usage = current usage */ + void resetPeakUsage() CV_OVERRIDE { peak.store(curr.load()); } + + // Controller interface + void onAllocate(size_t sz) + { +#ifdef CV__ALLOCATOR_STATS_LOG + CV__ALLOCATOR_STATS_LOG(cv::format("allocate: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); +#endif + + counter_t new_curr = curr.fetch_add((counter_t)sz) + (counter_t)sz; + + // peak = std::max((uint64_t)peak, new_curr); + auto prev_peak = peak.load(); + while (prev_peak < new_curr) + { + if (peak.compare_exchange_weak(prev_peak, new_curr)) + break; + } + // end of peak = max(...) + + total += (counter_t)sz; + total_allocs++; + } + void onFree(size_t sz) + { +#ifdef CV__ALLOCATOR_STATS_LOG + CV__ALLOCATOR_STATS_LOG(cv::format("free: %lld (curr=%lld)", (long long int)sz, (long long int)curr.load())); +#endif + curr -= (counter_t)sz; + } +#endif // OPENCV_DISABLE_ALLOCATOR_STATS +}; + +#ifdef CV__ALLOCATOR_STATS_LOG +} // namespace +#endif + +}} // namespace + +#endif // OPENCV_CORE_ALLOCATOR_STATS_IMPL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp index 93bc33aefd..8619ae4d1a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/filesystem.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_UTILS_FILESYSTEM_HPP -#define OPENCV_UTILS_FILESYSTEM_HPP - -namespace cv { namespace utils { namespace fs { - - -CV_EXPORTS bool exists(const cv::String& path); -CV_EXPORTS bool isDirectory(const cv::String& path); - -CV_EXPORTS void remove_all(const cv::String& path); - - -CV_EXPORTS cv::String getcwd(); - -/** @brief Converts path p to a canonical absolute path - * Symlinks are processed if there is support for them on running platform. - * - * @param path input path. Target file/directory should exist. - */ -CV_EXPORTS cv::String canonical(const cv::String& path); - -/** Join path components */ -CV_EXPORTS cv::String join(const cv::String& base, const cv::String& path); - -/** Get parent directory */ -CV_EXPORTS cv::String getParent(const cv::String &path); -CV_EXPORTS std::wstring getParent(const std::wstring& path); - -/** - * Generate a list of all files that match the globbing pattern. - * - * Result entries are prefixed by base directory path. - * - * @param directory base directory - * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results - * @param[out] result result of globing. - * @param recursive scan nested directories too - * @param includeDirectories include directories into results list - */ -CV_EXPORTS void glob(const cv::String& directory, const cv::String& pattern, - CV_OUT std::vector& result, - bool recursive = false, bool includeDirectories = false); - -/** - * Generate a list of all files that match the globbing pattern. - * - * @param directory base directory - * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results - * @param[out] result globbing result with relative paths from base directory - * @param recursive scan nested directories too - * @param includeDirectories include directories into results list - */ -CV_EXPORTS void glob_relative(const cv::String& directory, const cv::String& pattern, - CV_OUT std::vector& result, - bool recursive = false, bool includeDirectories = false); - - -CV_EXPORTS bool createDirectory(const cv::String& path); -CV_EXPORTS bool createDirectories(const cv::String& path); - -#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) -// TODO -//CV_EXPORTS cv::String getTempDirectory(); - -/** - * @brief Returns directory to store OpenCV cache files - * Create sub-directory in common OpenCV cache directory if it doesn't exist. - * @param sub_directory_name name of sub-directory. NULL or "" value asks to return root cache directory. - * @param configuration_name optional name of configuration parameter name which overrides default behavior. - * @return Path to cache directory. Returns empty string if cache directories support is not available. Returns "disabled" if cache disabled by user. - */ -CV_EXPORTS cv::String getCacheDirectory(const char* sub_directory_name, const char* configuration_name = NULL); - -#endif - -}}} // namespace - -#endif // OPENCV_UTILS_FILESYSTEM_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_UTILS_FILESYSTEM_HPP +#define OPENCV_UTILS_FILESYSTEM_HPP + +namespace cv { namespace utils { namespace fs { + + +CV_EXPORTS bool exists(const cv::String& path); +CV_EXPORTS bool isDirectory(const cv::String& path); + +CV_EXPORTS void remove_all(const cv::String& path); + + +CV_EXPORTS cv::String getcwd(); + +/** @brief Converts path p to a canonical absolute path + * Symlinks are processed if there is support for them on running platform. + * + * @param path input path. Target file/directory should exist. + */ +CV_EXPORTS cv::String canonical(const cv::String& path); + +/** Join path components */ +CV_EXPORTS cv::String join(const cv::String& base, const cv::String& path); + +/** Get parent directory */ +CV_EXPORTS cv::String getParent(const cv::String &path); +CV_EXPORTS std::wstring getParent(const std::wstring& path); + +/** + * Generate a list of all files that match the globbing pattern. + * + * Result entries are prefixed by base directory path. + * + * @param directory base directory + * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results + * @param[out] result result of globing. + * @param recursive scan nested directories too + * @param includeDirectories include directories into results list + */ +CV_EXPORTS void glob(const cv::String& directory, const cv::String& pattern, + CV_OUT std::vector& result, + bool recursive = false, bool includeDirectories = false); + +/** + * Generate a list of all files that match the globbing pattern. + * + * @param directory base directory + * @param pattern filter pattern (based on '*'/'?' symbols). Use empty string to disable filtering and return all results + * @param[out] result globbing result with relative paths from base directory + * @param recursive scan nested directories too + * @param includeDirectories include directories into results list + */ +CV_EXPORTS void glob_relative(const cv::String& directory, const cv::String& pattern, + CV_OUT std::vector& result, + bool recursive = false, bool includeDirectories = false); + + +CV_EXPORTS bool createDirectory(const cv::String& path); +CV_EXPORTS bool createDirectories(const cv::String& path); + +#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) +// TODO +//CV_EXPORTS cv::String getTempDirectory(); + +/** + * @brief Returns directory to store OpenCV cache files + * Create sub-directory in common OpenCV cache directory if it doesn't exist. + * @param sub_directory_name name of sub-directory. NULL or "" value asks to return root cache directory. + * @param configuration_name optional name of configuration parameter name which overrides default behavior. + * @return Path to cache directory. Returns empty string if cache directories support is not available. Returns "disabled" if cache disabled by user. + */ +CV_EXPORTS cv::String getCacheDirectory(const char* sub_directory_name, const char* configuration_name = NULL); + +#endif + +}}} // namespace + +#endif // OPENCV_UTILS_FILESYSTEM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp index 2ab87f6c87..930bc5d367 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/fp_control_utils.hpp @@ -1,69 +1,69 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_FP_CONTROL_UTILS_HPP -#define OPENCV_CORE_FP_CONTROL_UTILS_HPP - -namespace cv { - -namespace details { - -struct FPDenormalsModeState -{ - uint32_t reserved[16]; // 64-bytes -}; // FPDenormalsModeState - -CV_EXPORTS void setFPDenormalsIgnoreHint(bool ignore, CV_OUT FPDenormalsModeState& state); -CV_EXPORTS int saveFPDenormalsState(CV_OUT FPDenormalsModeState& state); -CV_EXPORTS bool restoreFPDenormalsState(const FPDenormalsModeState& state); - -class FPDenormalsIgnoreHintScope -{ -public: - inline explicit FPDenormalsIgnoreHintScope(bool ignore = true) - { - details::setFPDenormalsIgnoreHint(ignore, saved_state); - } - - inline explicit FPDenormalsIgnoreHintScope(const FPDenormalsModeState& state) - { - details::saveFPDenormalsState(saved_state); - details::restoreFPDenormalsState(state); - } - - inline ~FPDenormalsIgnoreHintScope() - { - details::restoreFPDenormalsState(saved_state); - } - -protected: - FPDenormalsModeState saved_state; -}; // FPDenormalsIgnoreHintScope - -class FPDenormalsIgnoreHintScopeNOOP -{ -public: - inline FPDenormalsIgnoreHintScopeNOOP(bool ignore = true) { CV_UNUSED(ignore); } - inline FPDenormalsIgnoreHintScopeNOOP(const FPDenormalsModeState& state) { CV_UNUSED(state); } - inline ~FPDenormalsIgnoreHintScopeNOOP() { } -}; // FPDenormalsIgnoreHintScopeNOOP - -} // namespace details - - -// Should depend on target compilation architecture only -// Note: previously added archs should NOT be removed to preserve ABI compatibility -#if defined(OPENCV_SUPPORTS_FP_DENORMALS_HINT) - // preserve configuration overloading through ports -#elif defined(__i386__) || defined(__x86_64__) || defined(_M_X64) || defined(_X86_) -typedef details::FPDenormalsIgnoreHintScope FPDenormalsIgnoreHintScope; -#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 1 -#else -#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 0 -typedef details::FPDenormalsIgnoreHintScopeNOOP FPDenormalsIgnoreHintScope; -#endif - -} // namespace cv - -#endif // OPENCV_CORE_FP_CONTROL_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_FP_CONTROL_UTILS_HPP +#define OPENCV_CORE_FP_CONTROL_UTILS_HPP + +namespace cv { + +namespace details { + +struct FPDenormalsModeState +{ + uint32_t reserved[16]; // 64-bytes +}; // FPDenormalsModeState + +CV_EXPORTS void setFPDenormalsIgnoreHint(bool ignore, CV_OUT FPDenormalsModeState& state); +CV_EXPORTS int saveFPDenormalsState(CV_OUT FPDenormalsModeState& state); +CV_EXPORTS bool restoreFPDenormalsState(const FPDenormalsModeState& state); + +class FPDenormalsIgnoreHintScope +{ +public: + inline explicit FPDenormalsIgnoreHintScope(bool ignore = true) + { + details::setFPDenormalsIgnoreHint(ignore, saved_state); + } + + inline explicit FPDenormalsIgnoreHintScope(const FPDenormalsModeState& state) + { + details::saveFPDenormalsState(saved_state); + details::restoreFPDenormalsState(state); + } + + inline ~FPDenormalsIgnoreHintScope() + { + details::restoreFPDenormalsState(saved_state); + } + +protected: + FPDenormalsModeState saved_state; +}; // FPDenormalsIgnoreHintScope + +class FPDenormalsIgnoreHintScopeNOOP +{ +public: + inline FPDenormalsIgnoreHintScopeNOOP(bool ignore = true) { CV_UNUSED(ignore); } + inline FPDenormalsIgnoreHintScopeNOOP(const FPDenormalsModeState& state) { CV_UNUSED(state); } + inline ~FPDenormalsIgnoreHintScopeNOOP() { } +}; // FPDenormalsIgnoreHintScopeNOOP + +} // namespace details + + +// Should depend on target compilation architecture only +// Note: previously added archs should NOT be removed to preserve ABI compatibility +#if defined(OPENCV_SUPPORTS_FP_DENORMALS_HINT) + // preserve configuration overloading through ports +#elif defined(__i386__) || defined(__x86_64__) || defined(_M_X64) || defined(_X86_) +typedef details::FPDenormalsIgnoreHintScope FPDenormalsIgnoreHintScope; +#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 1 +#else +#define OPENCV_SUPPORTS_FP_DENORMALS_HINT 0 +typedef details::FPDenormalsIgnoreHintScopeNOOP FPDenormalsIgnoreHintScope; +#endif + +} // namespace cv + +#endif // OPENCV_CORE_FP_CONTROL_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp index ef8ed40b11..3639867080 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/instrumentation.hpp @@ -1,125 +1,125 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_UTILS_INSTR_HPP -#define OPENCV_UTILS_INSTR_HPP - -#include -#include - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -#ifdef CV_COLLECT_IMPL_DATA -CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays -CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays -// Get stored implementation flags and functions names arrays -// Each implementation entry correspond to function name entry, so you can find which implementation was executed in which function -CV_EXPORTS int getImpl(std::vector &impl, std::vector &funName); - -CV_EXPORTS bool useCollection(); // return implementation collection state -CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state - -#define CV_IMPL_PLAIN 0x01 // native CPU OpenCV implementation -#define CV_IMPL_OCL 0x02 // OpenCL implementation -#define CV_IMPL_IPP 0x04 // IPP implementation -#define CV_IMPL_MT 0x10 // multithreaded implementation - -#undef CV_IMPL_ADD -#define CV_IMPL_ADD(impl) \ - if(cv::useCollection()) \ - { \ - cv::addImpl(impl, CV_Func); \ - } -#endif - -// Instrumentation external interface -namespace instr -{ - -#if !defined OPENCV_ABI_CHECK - -enum TYPE -{ - TYPE_GENERAL = 0, // OpenCV API function, e.g. exported function - TYPE_MARKER, // Information marker - TYPE_WRAPPER, // Wrapper function for implementation - TYPE_FUN, // Simple function call -}; - -enum IMPL -{ - IMPL_PLAIN = 0, - IMPL_IPP, - IMPL_OPENCL, -}; - -struct NodeDataTls -{ - NodeDataTls() - { - m_ticksTotal = 0; - } - uint64 m_ticksTotal; -}; - -class CV_EXPORTS NodeData -{ -public: - NodeData(const char* funName = 0, const char* fileName = NULL, int lineNum = 0, void* retAddress = NULL, bool alwaysExpand = false, cv::instr::TYPE instrType = TYPE_GENERAL, cv::instr::IMPL implType = IMPL_PLAIN); - NodeData(NodeData &ref); - ~NodeData(); - NodeData& operator=(const NodeData&); - - cv::String m_funName; - cv::instr::TYPE m_instrType; - cv::instr::IMPL m_implType; - const char* m_fileName; - int m_lineNum; - void* m_retAddress; - bool m_alwaysExpand; - bool m_funError; - - volatile int m_counter; - volatile uint64 m_ticksTotal; - TLSDataAccumulator m_tls; - int m_threads; - - // No synchronization - double getTotalMs() const { return ((double)m_ticksTotal / cv::getTickFrequency()) * 1000; } - double getMeanMs() const { return (((double)m_ticksTotal/m_counter) / cv::getTickFrequency()) * 1000; } -}; -bool operator==(const NodeData& lhs, const NodeData& rhs); - -typedef Node InstrNode; - -CV_EXPORTS InstrNode* getTrace(); - -#endif // !defined OPENCV_ABI_CHECK - - -CV_EXPORTS bool useInstrumentation(); -CV_EXPORTS void setUseInstrumentation(bool flag); -CV_EXPORTS void resetTrace(); - -enum FLAGS -{ - FLAGS_NONE = 0, - FLAGS_MAPPING = 0x01, - FLAGS_EXPAND_SAME_NAMES = 0x02, -}; - -CV_EXPORTS void setFlags(FLAGS modeFlags); -static inline void setFlags(int modeFlags) { setFlags((FLAGS)modeFlags); } -CV_EXPORTS FLAGS getFlags(); - -} // namespace instr - -//! @} - -} // namespace - -#endif // OPENCV_UTILS_TLS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_UTILS_INSTR_HPP +#define OPENCV_UTILS_INSTR_HPP + +#include +#include + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +#ifdef CV_COLLECT_IMPL_DATA +CV_EXPORTS void setImpl(int flags); // set implementation flags and reset storage arrays +CV_EXPORTS void addImpl(int flag, const char* func = 0); // add implementation and function name to storage arrays +// Get stored implementation flags and functions names arrays +// Each implementation entry correspond to function name entry, so you can find which implementation was executed in which function +CV_EXPORTS int getImpl(std::vector &impl, std::vector &funName); + +CV_EXPORTS bool useCollection(); // return implementation collection state +CV_EXPORTS void setUseCollection(bool flag); // set implementation collection state + +#define CV_IMPL_PLAIN 0x01 // native CPU OpenCV implementation +#define CV_IMPL_OCL 0x02 // OpenCL implementation +#define CV_IMPL_IPP 0x04 // IPP implementation +#define CV_IMPL_MT 0x10 // multithreaded implementation + +#undef CV_IMPL_ADD +#define CV_IMPL_ADD(impl) \ + if(cv::useCollection()) \ + { \ + cv::addImpl(impl, CV_Func); \ + } +#endif + +// Instrumentation external interface +namespace instr +{ + +#if !defined OPENCV_ABI_CHECK + +enum TYPE +{ + TYPE_GENERAL = 0, // OpenCV API function, e.g. exported function + TYPE_MARKER, // Information marker + TYPE_WRAPPER, // Wrapper function for implementation + TYPE_FUN, // Simple function call +}; + +enum IMPL +{ + IMPL_PLAIN = 0, + IMPL_IPP, + IMPL_OPENCL, +}; + +struct NodeDataTls +{ + NodeDataTls() + { + m_ticksTotal = 0; + } + uint64 m_ticksTotal; +}; + +class CV_EXPORTS NodeData +{ +public: + NodeData(const char* funName = 0, const char* fileName = NULL, int lineNum = 0, void* retAddress = NULL, bool alwaysExpand = false, cv::instr::TYPE instrType = TYPE_GENERAL, cv::instr::IMPL implType = IMPL_PLAIN); + NodeData(NodeData &ref); + ~NodeData(); + NodeData& operator=(const NodeData&); + + cv::String m_funName; + cv::instr::TYPE m_instrType; + cv::instr::IMPL m_implType; + const char* m_fileName; + int m_lineNum; + void* m_retAddress; + bool m_alwaysExpand; + bool m_funError; + + volatile int m_counter; + volatile uint64 m_ticksTotal; + TLSDataAccumulator m_tls; + int m_threads; + + // No synchronization + double getTotalMs() const { return ((double)m_ticksTotal / cv::getTickFrequency()) * 1000; } + double getMeanMs() const { return (((double)m_ticksTotal/m_counter) / cv::getTickFrequency()) * 1000; } +}; +bool operator==(const NodeData& lhs, const NodeData& rhs); + +typedef Node InstrNode; + +CV_EXPORTS InstrNode* getTrace(); + +#endif // !defined OPENCV_ABI_CHECK + + +CV_EXPORTS bool useInstrumentation(); +CV_EXPORTS void setUseInstrumentation(bool flag); +CV_EXPORTS void resetTrace(); + +enum FLAGS +{ + FLAGS_NONE = 0, + FLAGS_MAPPING = 0x01, + FLAGS_EXPAND_SAME_NAMES = 0x02, +}; + +CV_EXPORTS void setFlags(FLAGS modeFlags); +static inline void setFlags(int modeFlags) { setFlags((FLAGS)modeFlags); } +CV_EXPORTS FLAGS getFlags(); + +} // namespace instr + +//! @} + +} // namespace + +#endif // OPENCV_UTILS_TLS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp index 86ecdc0bd5..7d73f02b66 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.defines.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_LOGGER_DEFINES_HPP -#define OPENCV_LOGGER_DEFINES_HPP - -//! @addtogroup core_logging -//! @{ - -// Supported logging levels and their semantic -#define CV_LOG_LEVEL_SILENT 0 //!< for using in setLogLevel() call -#define CV_LOG_LEVEL_FATAL 1 //!< Fatal (critical) error (unrecoverable internal error) -#define CV_LOG_LEVEL_ERROR 2 //!< Error message -#define CV_LOG_LEVEL_WARN 3 //!< Warning message -#define CV_LOG_LEVEL_INFO 4 //!< Info message -#define CV_LOG_LEVEL_DEBUG 5 //!< Debug message. Disabled in the "Release" build. -#define CV_LOG_LEVEL_VERBOSE 6 //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. - -namespace cv { -namespace utils { -namespace logging { - -//! Supported logging levels and their semantic -enum LogLevel { - LOG_LEVEL_SILENT = 0, //!< for using in setLogVevel() call - LOG_LEVEL_FATAL = 1, //!< Fatal (critical) error (unrecoverable internal error) - LOG_LEVEL_ERROR = 2, //!< Error message - LOG_LEVEL_WARNING = 3, //!< Warning message - LOG_LEVEL_INFO = 4, //!< Info message - LOG_LEVEL_DEBUG = 5, //!< Debug message. Disabled in the "Release" build. - LOG_LEVEL_VERBOSE = 6, //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. -#ifndef CV_DOXYGEN - ENUM_LOG_LEVEL_FORCE_INT = INT_MAX -#endif -}; - -}}} // namespace - -//! @} - -#endif // OPENCV_LOGGER_DEFINES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_LOGGER_DEFINES_HPP +#define OPENCV_LOGGER_DEFINES_HPP + +//! @addtogroup core_logging +//! @{ + +// Supported logging levels and their semantic +#define CV_LOG_LEVEL_SILENT 0 //!< for using in setLogLevel() call +#define CV_LOG_LEVEL_FATAL 1 //!< Fatal (critical) error (unrecoverable internal error) +#define CV_LOG_LEVEL_ERROR 2 //!< Error message +#define CV_LOG_LEVEL_WARN 3 //!< Warning message +#define CV_LOG_LEVEL_INFO 4 //!< Info message +#define CV_LOG_LEVEL_DEBUG 5 //!< Debug message. Disabled in the "Release" build. +#define CV_LOG_LEVEL_VERBOSE 6 //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. + +namespace cv { +namespace utils { +namespace logging { + +//! Supported logging levels and their semantic +enum LogLevel { + LOG_LEVEL_SILENT = 0, //!< for using in setLogVevel() call + LOG_LEVEL_FATAL = 1, //!< Fatal (critical) error (unrecoverable internal error) + LOG_LEVEL_ERROR = 2, //!< Error message + LOG_LEVEL_WARNING = 3, //!< Warning message + LOG_LEVEL_INFO = 4, //!< Info message + LOG_LEVEL_DEBUG = 5, //!< Debug message. Disabled in the "Release" build. + LOG_LEVEL_VERBOSE = 6, //!< Verbose (trace) messages. Requires verbosity level. Disabled in the "Release" build. +#ifndef CV_DOXYGEN + ENUM_LOG_LEVEL_FORCE_INT = INT_MAX +#endif +}; + +}}} // namespace + +//! @} + +#endif // OPENCV_LOGGER_DEFINES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp index 5fc5fb74ae..accb860ada 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/logger.hpp @@ -1,218 +1,218 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_LOGGER_HPP -#define OPENCV_LOGGER_HPP - -#include -#include -#include // INT_MAX - -#include "logger.defines.hpp" -#include "logtag.hpp" - -namespace cv { -namespace utils { -namespace logging { - -//! @addtogroup core_logging -//! @{ - -/** Set global logging level -@return previous logging level -*/ -CV_EXPORTS LogLevel setLogLevel(LogLevel logLevel); -/** Get global logging level */ -CV_EXPORTS LogLevel getLogLevel(); - -CV_EXPORTS void registerLogTag(cv::utils::logging::LogTag* plogtag); - -CV_EXPORTS void setLogTagLevel(const char* tag, cv::utils::logging::LogLevel level); - -CV_EXPORTS cv::utils::logging::LogLevel getLogTagLevel(const char* tag); - -namespace internal { - -/** Get global log tag */ -CV_EXPORTS cv::utils::logging::LogTag* getGlobalLogTag(); - -/** Write log message */ -CV_EXPORTS void writeLogMessage(LogLevel logLevel, const char* message); - -/** Write log message */ -CV_EXPORTS void writeLogMessageEx(LogLevel logLevel, const char* tag, const char* file, int line, const char* func, const char* message); - -} // namespace - -struct LogTagAuto - : public LogTag -{ - inline LogTagAuto(const char* _name, LogLevel _level) - : LogTag(_name, _level) - { - registerLogTag(this); - } -}; - -/** - * \def CV_LOG_STRIP_LEVEL - * - * Define CV_LOG_STRIP_LEVEL=CV_LOG_LEVEL_[DEBUG|INFO|WARN|ERROR|FATAL|SILENT] to compile out anything at that and before that logging level - */ -#ifndef CV_LOG_STRIP_LEVEL -# if defined NDEBUG -# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG -# else -# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE -# endif -#endif - -#define CV_LOGTAG_PTR_CAST(expr) static_cast(expr) - -// CV_LOGTAG_EXPAND_NAME is intended to be re-defined (undef and then define again) -// to allows logging users to use a shorter name argument when calling -// CV_LOG_WITH_TAG or its related macros such as CV_LOG_INFO. -// -// This macro is intended to modify the tag argument as a string (token), via -// preprocessor token pasting or metaprogramming techniques. A typical usage -// is to apply a prefix, such as -// ...... #define CV_LOGTAG_EXPAND_NAME(tag) cv_logtag_##tag -// -// It is permitted to re-define to a hard-coded expression, ignoring the tag. -// This would work identically like the CV_LOGTAG_FALLBACK macro. -// -// Important: When the logging macro is called with tag being NULL, a user-defined -// CV_LOGTAG_EXPAND_NAME may expand it into cv_logtag_0, cv_logtag_NULL, or -// cv_logtag_nullptr. Use with care. Also be mindful of C++ symbol redefinitions. -// -// If there is significant amount of logging code with tag being NULL, it is -// recommended to use (re-define) CV_LOGTAG_FALLBACK to inject locally a default -// tag at the beginning of a compilation unit, to minimize lines of code changes. -// -#define CV_LOGTAG_EXPAND_NAME(tag) tag - -// CV_LOGTAG_FALLBACK is intended to be re-defined (undef and then define again) -// by any other compilation units to provide a log tag when the logging statement -// does not specify one. The macro needs to expand into a C++ expression that can -// be static_cast into (cv::utils::logging::LogTag*). Null (nullptr) is permitted. -#define CV_LOGTAG_FALLBACK nullptr - -// CV_LOGTAG_GLOBAL is the tag used when a log tag is not specified in the logging -// statement nor the compilation unit. The macro needs to expand into a C++ -// expression that can be static_cast into (cv::utils::logging::LogTag*). Must be -// non-null. Do not re-define. -#define CV_LOGTAG_GLOBAL cv::utils::logging::internal::getGlobalLogTag() - -#define CV_LOG_WITH_TAG(tag, msgLevel, extra_check0, extra_check1, ...) \ - for(;;) { \ - extra_check0; \ - const auto cv_temp_msglevel = (cv::utils::logging::LogLevel)(msgLevel); \ - if (cv_temp_msglevel >= (CV_LOG_STRIP_LEVEL)) break; \ - auto cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_EXPAND_NAME(tag)); \ - if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_FALLBACK); \ - if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_GLOBAL); \ - if (cv_temp_logtagptr && (cv_temp_msglevel > cv_temp_logtagptr->level)) break; \ - extra_check1; \ - std::stringstream cv_temp_logstream; \ - cv_temp_logstream << __VA_ARGS__; \ - cv::utils::logging::internal::writeLogMessageEx( \ - cv_temp_msglevel, \ - (cv_temp_logtagptr ? cv_temp_logtagptr->name : nullptr), \ - __FILE__, \ - __LINE__, \ - CV_Func, \ - cv_temp_logstream.str().c_str()); \ - break; \ - } - -#define CV_LOG_FATAL(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , , __VA_ARGS__) -#define CV_LOG_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , , __VA_ARGS__) -#define CV_LOG_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , , __VA_ARGS__) -#define CV_LOG_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , , __VA_ARGS__) -#define CV_LOG_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , , __VA_ARGS__) -#define CV_LOG_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , , __VA_ARGS__) - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO -#undef CV_LOG_INFO -#define CV_LOG_INFO(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG -#undef CV_LOG_DEBUG -#define CV_LOG_DEBUG(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE -#undef CV_LOG_VERBOSE -#define CV_LOG_VERBOSE(tag, v, ...) -#endif - -//! @cond IGNORED -#define CV__LOG_ONCE_CHECK_PRE \ - static bool _cv_log_once_ ## __LINE__ = false; \ - if (_cv_log_once_ ## __LINE__) break; - -#define CV__LOG_ONCE_CHECK_POST \ - _cv_log_once_ ## __LINE__ = true; - -#define CV__LOG_IF_CHECK(logging_cond) \ - if (!(logging_cond)) break; - -//! @endcond - - -// CV_LOG_ONCE_XXX macros - -#define CV_LOG_ONCE_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) -#define CV_LOG_ONCE_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO -#undef CV_LOG_ONCE_INFO -#define CV_LOG_ONCE_INFO(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG -#undef CV_LOG_ONCE_DEBUG -#define CV_LOG_ONCE_DEBUG(tag, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE -#undef CV_LOG_ONCE_VERBOSE -#define CV_LOG_ONCE_VERBOSE(tag, v, ...) -#endif - - -// CV_LOG_IF_XXX macros - -#define CV_LOG_IF_FATAL(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_ERROR(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_WARNING(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_INFO(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) -#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO -#undef CV_LOG_IF_INFO -#define CV_LOG_IF_INFO(tag, logging_cond, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG -#undef CV_LOG_IF_DEBUG -#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) -#endif - -#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE -#undef CV_LOG_IF_VERBOSE -#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) -#endif - - -//! @} - -}}} // namespace - -#endif // OPENCV_LOGGER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_LOGGER_HPP +#define OPENCV_LOGGER_HPP + +#include +#include +#include // INT_MAX + +#include "logger.defines.hpp" +#include "logtag.hpp" + +namespace cv { +namespace utils { +namespace logging { + +//! @addtogroup core_logging +//! @{ + +/** Set global logging level +@return previous logging level +*/ +CV_EXPORTS LogLevel setLogLevel(LogLevel logLevel); +/** Get global logging level */ +CV_EXPORTS LogLevel getLogLevel(); + +CV_EXPORTS void registerLogTag(cv::utils::logging::LogTag* plogtag); + +CV_EXPORTS void setLogTagLevel(const char* tag, cv::utils::logging::LogLevel level); + +CV_EXPORTS cv::utils::logging::LogLevel getLogTagLevel(const char* tag); + +namespace internal { + +/** Get global log tag */ +CV_EXPORTS cv::utils::logging::LogTag* getGlobalLogTag(); + +/** Write log message */ +CV_EXPORTS void writeLogMessage(LogLevel logLevel, const char* message); + +/** Write log message */ +CV_EXPORTS void writeLogMessageEx(LogLevel logLevel, const char* tag, const char* file, int line, const char* func, const char* message); + +} // namespace + +struct LogTagAuto + : public LogTag +{ + inline LogTagAuto(const char* _name, LogLevel _level) + : LogTag(_name, _level) + { + registerLogTag(this); + } +}; + +/** + * \def CV_LOG_STRIP_LEVEL + * + * Define CV_LOG_STRIP_LEVEL=CV_LOG_LEVEL_[DEBUG|INFO|WARN|ERROR|FATAL|SILENT] to compile out anything at that and before that logging level + */ +#ifndef CV_LOG_STRIP_LEVEL +# if defined NDEBUG +# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG +# else +# define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_VERBOSE +# endif +#endif + +#define CV_LOGTAG_PTR_CAST(expr) static_cast(expr) + +// CV_LOGTAG_EXPAND_NAME is intended to be re-defined (undef and then define again) +// to allows logging users to use a shorter name argument when calling +// CV_LOG_WITH_TAG or its related macros such as CV_LOG_INFO. +// +// This macro is intended to modify the tag argument as a string (token), via +// preprocessor token pasting or metaprogramming techniques. A typical usage +// is to apply a prefix, such as +// ...... #define CV_LOGTAG_EXPAND_NAME(tag) cv_logtag_##tag +// +// It is permitted to re-define to a hard-coded expression, ignoring the tag. +// This would work identically like the CV_LOGTAG_FALLBACK macro. +// +// Important: When the logging macro is called with tag being NULL, a user-defined +// CV_LOGTAG_EXPAND_NAME may expand it into cv_logtag_0, cv_logtag_NULL, or +// cv_logtag_nullptr. Use with care. Also be mindful of C++ symbol redefinitions. +// +// If there is significant amount of logging code with tag being NULL, it is +// recommended to use (re-define) CV_LOGTAG_FALLBACK to inject locally a default +// tag at the beginning of a compilation unit, to minimize lines of code changes. +// +#define CV_LOGTAG_EXPAND_NAME(tag) tag + +// CV_LOGTAG_FALLBACK is intended to be re-defined (undef and then define again) +// by any other compilation units to provide a log tag when the logging statement +// does not specify one. The macro needs to expand into a C++ expression that can +// be static_cast into (cv::utils::logging::LogTag*). Null (nullptr) is permitted. +#define CV_LOGTAG_FALLBACK nullptr + +// CV_LOGTAG_GLOBAL is the tag used when a log tag is not specified in the logging +// statement nor the compilation unit. The macro needs to expand into a C++ +// expression that can be static_cast into (cv::utils::logging::LogTag*). Must be +// non-null. Do not re-define. +#define CV_LOGTAG_GLOBAL cv::utils::logging::internal::getGlobalLogTag() + +#define CV_LOG_WITH_TAG(tag, msgLevel, extra_check0, extra_check1, ...) \ + for(;;) { \ + extra_check0; \ + const auto cv_temp_msglevel = (cv::utils::logging::LogLevel)(msgLevel); \ + if (cv_temp_msglevel >= (CV_LOG_STRIP_LEVEL)) break; \ + auto cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_EXPAND_NAME(tag)); \ + if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_FALLBACK); \ + if (!cv_temp_logtagptr) cv_temp_logtagptr = CV_LOGTAG_PTR_CAST(CV_LOGTAG_GLOBAL); \ + if (cv_temp_logtagptr && (cv_temp_msglevel > cv_temp_logtagptr->level)) break; \ + extra_check1; \ + std::stringstream cv_temp_logstream; \ + cv_temp_logstream << __VA_ARGS__; \ + cv::utils::logging::internal::writeLogMessageEx( \ + cv_temp_msglevel, \ + (cv_temp_logtagptr ? cv_temp_logtagptr->name : nullptr), \ + __FILE__, \ + __LINE__, \ + CV_Func, \ + cv_temp_logstream.str().c_str()); \ + break; \ + } + +#define CV_LOG_FATAL(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , , __VA_ARGS__) +#define CV_LOG_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , , __VA_ARGS__) +#define CV_LOG_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , , __VA_ARGS__) +#define CV_LOG_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , , __VA_ARGS__) +#define CV_LOG_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , , __VA_ARGS__) +#define CV_LOG_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , , __VA_ARGS__) + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO +#undef CV_LOG_INFO +#define CV_LOG_INFO(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG +#undef CV_LOG_DEBUG +#define CV_LOG_DEBUG(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE +#undef CV_LOG_VERBOSE +#define CV_LOG_VERBOSE(tag, v, ...) +#endif + +//! @cond IGNORED +#define CV__LOG_ONCE_CHECK_PRE \ + static bool _cv_log_once_ ## __LINE__ = false; \ + if (_cv_log_once_ ## __LINE__) break; + +#define CV__LOG_ONCE_CHECK_POST \ + _cv_log_once_ ## __LINE__ = true; + +#define CV__LOG_IF_CHECK(logging_cond) \ + if (!(logging_cond)) break; + +//! @endcond + + +// CV_LOG_ONCE_XXX macros + +#define CV_LOG_ONCE_ERROR(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_WARNING(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_INFO(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_DEBUG(tag, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) +#define CV_LOG_ONCE_VERBOSE(tag, v, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), CV__LOG_ONCE_CHECK_PRE, CV__LOG_ONCE_CHECK_POST, __VA_ARGS__) + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO +#undef CV_LOG_ONCE_INFO +#define CV_LOG_ONCE_INFO(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG +#undef CV_LOG_ONCE_DEBUG +#define CV_LOG_ONCE_DEBUG(tag, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE +#undef CV_LOG_ONCE_VERBOSE +#define CV_LOG_ONCE_VERBOSE(tag, v, ...) +#endif + + +// CV_LOG_IF_XXX macros + +#define CV_LOG_IF_FATAL(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_FATAL, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_ERROR(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_ERROR, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_WARNING(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_WARNING, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_INFO(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_INFO, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) CV_LOG_WITH_TAG(tag, cv::utils::logging::LOG_LEVEL_DEBUG, , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) +#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) CV_LOG_WITH_TAG(tag, (cv::utils::logging::LOG_LEVEL_VERBOSE + (int)(v)), , CV__LOG_IF_CHECK(logging_cond), __VA_ARGS__) + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_INFO +#undef CV_LOG_IF_INFO +#define CV_LOG_IF_INFO(tag, logging_cond, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_DEBUG +#undef CV_LOG_IF_DEBUG +#define CV_LOG_IF_DEBUG(tag, logging_cond, ...) +#endif + +#if CV_LOG_STRIP_LEVEL <= CV_LOG_LEVEL_VERBOSE +#undef CV_LOG_IF_VERBOSE +#define CV_LOG_IF_VERBOSE(tag, v, logging_cond, ...) +#endif + + +//! @} + +}}} // namespace + +#endif // OPENCV_LOGGER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp index d51f84decb..4089720767 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/logtag.hpp @@ -1,28 +1,28 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_CORE_LOGTAG_HPP -#define OPENCV_CORE_LOGTAG_HPP - -#include "opencv2/core/cvstd.hpp" -#include "logger.defines.hpp" - -namespace cv { -namespace utils { -namespace logging { - -struct LogTag -{ - const char* name; - LogLevel level; - - inline LogTag(const char* _name, LogLevel _level) - : name(_name) - , level(_level) - {} -}; - -}}} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_CORE_LOGTAG_HPP +#define OPENCV_CORE_LOGTAG_HPP + +#include "opencv2/core/cvstd.hpp" +#include "logger.defines.hpp" + +namespace cv { +namespace utils { +namespace logging { + +struct LogTag +{ + const char* name; + LogLevel level; + + inline LogTag(const char* _name, LogLevel _level) + : name(_name) + , level(_level) + {} +}; + +}}} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp index 042ca6c787..124caebc85 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/tls.hpp @@ -1,235 +1,235 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_UTILS_TLS_HPP -#define OPENCV_UTILS_TLS_HPP - -#ifndef OPENCV_CORE_UTILITY_H -#error "tls.hpp must be included after opencv2/core/utility.hpp or opencv2/core.hpp" -#endif - -namespace cv { - -//! @addtogroup core_utils -//! @{ - -namespace details { class TlsStorage; } - -/** TLS container base implementation - * - * Don't use directly. - * - * @sa TLSData, TLSDataAccumulator templates - */ -class CV_EXPORTS TLSDataContainer -{ -protected: - TLSDataContainer(); - virtual ~TLSDataContainer(); - - /// @deprecated use detachData() instead - void gatherData(std::vector &data) const; - /// get TLS data and detach all data from threads (similar to cleanup() call) - void detachData(std::vector& data); - - void* getData() const; - void release(); - -protected: - virtual void* createDataInstance() const = 0; - virtual void deleteDataInstance(void* pData) const = 0; - -private: - int key_; - - friend class cv::details::TlsStorage; // core/src/system.cpp - -public: - void cleanup(); //!< Release created TLS data container objects. It is similar to release() call, but it keeps TLS container valid. - -private: - // Disable copy/assign (noncopyable pattern) - TLSDataContainer(TLSDataContainer &) = delete; - TLSDataContainer& operator =(const TLSDataContainer &) = delete; -}; - - -/** @brief Simple TLS data class - * - * @sa TLSDataAccumulator - */ -template -class TLSData : protected TLSDataContainer -{ -public: - inline TLSData() {} - inline ~TLSData() { release(); } - - inline T* get() const { return (T*)getData(); } //!< Get data associated with key - inline T& getRef() const { T* ptr = (T*)getData(); CV_DbgAssert(ptr); return *ptr; } //!< Get data associated with key - - /// Release associated thread data - inline void cleanup() - { - TLSDataContainer::cleanup(); - } - -protected: - /// Wrapper to allocate data by template - virtual void* createDataInstance() const CV_OVERRIDE { return new T; } - /// Wrapper to release data by template - virtual void deleteDataInstance(void* pData) const CV_OVERRIDE { delete (T*)pData; } -}; - - -/// TLS data accumulator with gathering methods -template -class TLSDataAccumulator : public TLSData -{ - mutable cv::Mutex mutex; - mutable std::vector dataFromTerminatedThreads; - std::vector detachedData; - bool cleanupMode; -public: - TLSDataAccumulator() : cleanupMode(false) {} - ~TLSDataAccumulator() - { - release(); - } - - /** @brief Get data from all threads - * @deprecated replaced by detachData() - * - * Lifetime of vector data is valid until next detachData()/cleanup()/release() calls - * - * @param[out] data result buffer (should be empty) - */ - void gather(std::vector &data) const - { - CV_Assert(cleanupMode == false); // state is not valid - CV_Assert(data.empty()); - { - std::vector &dataVoid = reinterpret_cast&>(data); - TLSDataContainer::gatherData(dataVoid); - } - { - AutoLock lock(mutex); - data.reserve(data.size() + dataFromTerminatedThreads.size()); - for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) - { - data.push_back((T*)*i); - } - } - } - - /** @brief Get and detach data from all threads - * - * Call cleanupDetachedData() when returned vector is not needed anymore. - * - * @return Vector with associated data. Content is preserved (including lifetime of attached data pointers) until next detachData()/cleanupDetachedData()/cleanup()/release() calls - */ - std::vector& detachData() - { - CV_Assert(cleanupMode == false); // state is not valid - std::vector dataVoid; - { - TLSDataContainer::detachData(dataVoid); - } - { - AutoLock lock(mutex); - detachedData.reserve(dataVoid.size() + dataFromTerminatedThreads.size()); - for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) - { - detachedData.push_back((T*)*i); - } - dataFromTerminatedThreads.clear(); - for (typename std::vector::const_iterator i = dataVoid.begin(); i != dataVoid.end(); ++i) - { - detachedData.push_back((T*)(void*)*i); - } - } - dataVoid.clear(); - return detachedData; - } - - /// Release associated thread data returned by detachData() call - void cleanupDetachedData() - { - AutoLock lock(mutex); - cleanupMode = true; - _cleanupDetachedData(); - cleanupMode = false; - } - - /// Release associated thread data - void cleanup() - { - cleanupMode = true; - TLSDataContainer::cleanup(); - - AutoLock lock(mutex); - _cleanupDetachedData(); - _cleanupTerminatedData(); - cleanupMode = false; - } - - /// Release associated thread data and free TLS key - void release() - { - cleanupMode = true; - TLSDataContainer::release(); - { - AutoLock lock(mutex); - _cleanupDetachedData(); - _cleanupTerminatedData(); - } - } - -protected: - // synchronized - void _cleanupDetachedData() - { - for (typename std::vector::iterator i = detachedData.begin(); i != detachedData.end(); ++i) - { - deleteDataInstance((T*)*i); - } - detachedData.clear(); - } - - // synchronized - void _cleanupTerminatedData() - { - for (typename std::vector::iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) - { - deleteDataInstance((T*)*i); - } - dataFromTerminatedThreads.clear(); - } - -protected: - virtual void* createDataInstance() const CV_OVERRIDE - { - // Note: we can collect all allocated data here, but this would require raced mutex locks - return new T; - } - virtual void deleteDataInstance(void* pData) const CV_OVERRIDE - { - if (cleanupMode) - { - delete (T*)pData; - } - else - { - AutoLock lock(mutex); - dataFromTerminatedThreads.push_back((T*)pData); - } - } -}; - - -//! @} - -} // namespace - -#endif // OPENCV_UTILS_TLS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_UTILS_TLS_HPP +#define OPENCV_UTILS_TLS_HPP + +#ifndef OPENCV_CORE_UTILITY_H +#error "tls.hpp must be included after opencv2/core/utility.hpp or opencv2/core.hpp" +#endif + +namespace cv { + +//! @addtogroup core_utils +//! @{ + +namespace details { class TlsStorage; } + +/** TLS container base implementation + * + * Don't use directly. + * + * @sa TLSData, TLSDataAccumulator templates + */ +class CV_EXPORTS TLSDataContainer +{ +protected: + TLSDataContainer(); + virtual ~TLSDataContainer(); + + /// @deprecated use detachData() instead + void gatherData(std::vector &data) const; + /// get TLS data and detach all data from threads (similar to cleanup() call) + void detachData(std::vector& data); + + void* getData() const; + void release(); + +protected: + virtual void* createDataInstance() const = 0; + virtual void deleteDataInstance(void* pData) const = 0; + +private: + int key_; + + friend class cv::details::TlsStorage; // core/src/system.cpp + +public: + void cleanup(); //!< Release created TLS data container objects. It is similar to release() call, but it keeps TLS container valid. + +private: + // Disable copy/assign (noncopyable pattern) + TLSDataContainer(TLSDataContainer &) = delete; + TLSDataContainer& operator =(const TLSDataContainer &) = delete; +}; + + +/** @brief Simple TLS data class + * + * @sa TLSDataAccumulator + */ +template +class TLSData : protected TLSDataContainer +{ +public: + inline TLSData() {} + inline ~TLSData() { release(); } + + inline T* get() const { return (T*)getData(); } //!< Get data associated with key + inline T& getRef() const { T* ptr = (T*)getData(); CV_DbgAssert(ptr); return *ptr; } //!< Get data associated with key + + /// Release associated thread data + inline void cleanup() + { + TLSDataContainer::cleanup(); + } + +protected: + /// Wrapper to allocate data by template + virtual void* createDataInstance() const CV_OVERRIDE { return new T; } + /// Wrapper to release data by template + virtual void deleteDataInstance(void* pData) const CV_OVERRIDE { delete (T*)pData; } +}; + + +/// TLS data accumulator with gathering methods +template +class TLSDataAccumulator : public TLSData +{ + mutable cv::Mutex mutex; + mutable std::vector dataFromTerminatedThreads; + std::vector detachedData; + bool cleanupMode; +public: + TLSDataAccumulator() : cleanupMode(false) {} + ~TLSDataAccumulator() + { + release(); + } + + /** @brief Get data from all threads + * @deprecated replaced by detachData() + * + * Lifetime of vector data is valid until next detachData()/cleanup()/release() calls + * + * @param[out] data result buffer (should be empty) + */ + void gather(std::vector &data) const + { + CV_Assert(cleanupMode == false); // state is not valid + CV_Assert(data.empty()); + { + std::vector &dataVoid = reinterpret_cast&>(data); + TLSDataContainer::gatherData(dataVoid); + } + { + AutoLock lock(mutex); + data.reserve(data.size() + dataFromTerminatedThreads.size()); + for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) + { + data.push_back((T*)*i); + } + } + } + + /** @brief Get and detach data from all threads + * + * Call cleanupDetachedData() when returned vector is not needed anymore. + * + * @return Vector with associated data. Content is preserved (including lifetime of attached data pointers) until next detachData()/cleanupDetachedData()/cleanup()/release() calls + */ + std::vector& detachData() + { + CV_Assert(cleanupMode == false); // state is not valid + std::vector dataVoid; + { + TLSDataContainer::detachData(dataVoid); + } + { + AutoLock lock(mutex); + detachedData.reserve(dataVoid.size() + dataFromTerminatedThreads.size()); + for (typename std::vector::const_iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) + { + detachedData.push_back((T*)*i); + } + dataFromTerminatedThreads.clear(); + for (typename std::vector::const_iterator i = dataVoid.begin(); i != dataVoid.end(); ++i) + { + detachedData.push_back((T*)(void*)*i); + } + } + dataVoid.clear(); + return detachedData; + } + + /// Release associated thread data returned by detachData() call + void cleanupDetachedData() + { + AutoLock lock(mutex); + cleanupMode = true; + _cleanupDetachedData(); + cleanupMode = false; + } + + /// Release associated thread data + void cleanup() + { + cleanupMode = true; + TLSDataContainer::cleanup(); + + AutoLock lock(mutex); + _cleanupDetachedData(); + _cleanupTerminatedData(); + cleanupMode = false; + } + + /// Release associated thread data and free TLS key + void release() + { + cleanupMode = true; + TLSDataContainer::release(); + { + AutoLock lock(mutex); + _cleanupDetachedData(); + _cleanupTerminatedData(); + } + } + +protected: + // synchronized + void _cleanupDetachedData() + { + for (typename std::vector::iterator i = detachedData.begin(); i != detachedData.end(); ++i) + { + deleteDataInstance((T*)*i); + } + detachedData.clear(); + } + + // synchronized + void _cleanupTerminatedData() + { + for (typename std::vector::iterator i = dataFromTerminatedThreads.begin(); i != dataFromTerminatedThreads.end(); ++i) + { + deleteDataInstance((T*)*i); + } + dataFromTerminatedThreads.clear(); + } + +protected: + virtual void* createDataInstance() const CV_OVERRIDE + { + // Note: we can collect all allocated data here, but this would require raced mutex locks + return new T; + } + virtual void deleteDataInstance(void* pData) const CV_OVERRIDE + { + if (cleanupMode) + { + delete (T*)pData; + } + else + { + AutoLock lock(mutex); + dataFromTerminatedThreads.push_back((T*)pData); + } + } +}; + + +//! @} + +} // namespace + +#endif // OPENCV_UTILS_TLS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp b/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp index 74d1256c9f..ea43bbeea1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/utils/trace.hpp @@ -1,252 +1,252 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_TRACE_HPP -#define OPENCV_TRACE_HPP - -#include - -namespace cv { -namespace utils { -namespace trace { - -//! @addtogroup core_logging -//! @{ - -//! Macro to trace function -#define CV_TRACE_FUNCTION() - -#define CV_TRACE_FUNCTION_SKIP_NESTED() - -//! Trace code scope. -//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "initialize". -#define CV_TRACE_REGION(name_as_static_string_literal) -//! mark completed of the current opened region and create new one -//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "step1". -#define CV_TRACE_REGION_NEXT(name_as_static_string_literal) - -//! Macro to trace argument value -#define CV_TRACE_ARG(arg_id) - -//! Macro to trace argument value (expanded version) -#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) - -//! @cond IGNORED -#define CV_TRACE_NS cv::utils::trace - -#if !defined(OPENCV_DISABLE_TRACE) && defined(__EMSCRIPTEN__) -#define OPENCV_DISABLE_TRACE 1 -#endif - -namespace details { - -#ifndef __OPENCV_TRACE -# if defined __OPENCV_BUILD && !defined __OPENCV_TESTS && !defined __OPENCV_APPS -# define __OPENCV_TRACE 1 -# else -# define __OPENCV_TRACE 0 -# endif -#endif - -#ifndef CV_TRACE_FILENAME -# define CV_TRACE_FILENAME __FILE__ -#endif - -#ifndef CV__TRACE_FUNCTION -# if defined _MSC_VER -# define CV__TRACE_FUNCTION __FUNCSIG__ -# elif defined __GNUC__ -# define CV__TRACE_FUNCTION __PRETTY_FUNCTION__ -# else -# define CV__TRACE_FUNCTION "" -# endif -#endif - -//! Thread-local instance (usually allocated on stack) -class CV_EXPORTS Region -{ -public: - struct LocationExtraData; - struct LocationStaticStorage - { - LocationExtraData** ppExtra; ///< implementation specific data - const char* name; ///< region name (function name or other custom name) - const char* filename; ///< source code filename - int line; ///< source code line - int flags; ///< flags (implementation code path: Plain, IPP, OpenCL) - }; - - Region(const LocationStaticStorage& location); - inline ~Region() - { - if (implFlags != 0) - destroy(); - CV_DbgAssert(implFlags == 0); - CV_DbgAssert(pImpl == NULL); - } - - class Impl; - Impl* pImpl; // NULL if current region is not active - int implFlags; // see RegionFlag, 0 if region is ignored - - bool isActive() const { return pImpl != NULL; } - - void destroy(); -private: - Region(const Region&); // disabled - Region& operator= (const Region&); // disabled -}; - -//! Specify region flags -enum RegionLocationFlag { - REGION_FLAG_FUNCTION = (1 << 0), ///< region is function (=1) / nested named region (=0) - REGION_FLAG_APP_CODE = (1 << 1), ///< region is Application code (=1) / OpenCV library code (=0) - REGION_FLAG_SKIP_NESTED = (1 << 2), ///< avoid processing of nested regions - - REGION_FLAG_IMPL_IPP = (1 << 16), ///< region is part of IPP code path - REGION_FLAG_IMPL_OPENCL = (2 << 16), ///< region is part of OpenCL code path - REGION_FLAG_IMPL_OPENVX = (3 << 16), ///< region is part of OpenVX code path - - REGION_FLAG_IMPL_MASK = (15 << 16), - - REGION_FLAG_REGION_FORCE = (1 << 30), - REGION_FLAG_REGION_NEXT = (1 << 31), ///< close previous region (see #CV_TRACE_REGION_NEXT macro) - - ENUM_REGION_FLAG_FORCE_INT = INT_MAX -}; - -struct CV_EXPORTS TraceArg { -public: - struct ExtraData; - ExtraData** ppExtra; - const char* name; - int flags; -}; -/** @brief Add meta information to current region (function) - * See CV_TRACE_ARG macro - * @param arg argument information structure (global static cache) - * @param value argument value (can by dynamic string literal in case of string, static allocation is not required) - */ -CV_EXPORTS void traceArg(const TraceArg& arg, const char* value); -//! @overload -CV_EXPORTS void traceArg(const TraceArg& arg, int value); -//! @overload -CV_EXPORTS void traceArg(const TraceArg& arg, int64 value); -//! @overload -CV_EXPORTS void traceArg(const TraceArg& arg, double value); - -#define CV__TRACE_LOCATION_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_, loc_id), __LINE__) -#define CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_extra_, loc_id) , __LINE__) - -#define CV__TRACE_DEFINE_LOCATION_(loc_id, name, flags) \ - static CV_TRACE_NS::details::Region::LocationExtraData* CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) = 0; \ - static const CV_TRACE_NS::details::Region::LocationStaticStorage \ - CV__TRACE_LOCATION_VARNAME(loc_id) = { &(CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id)), name, CV_TRACE_FILENAME, __LINE__, flags}; - -#define CV__TRACE_DEFINE_LOCATION_FN(name, flags) CV__TRACE_DEFINE_LOCATION_(fn, name, ((flags) | CV_TRACE_NS::details::REGION_FLAG_FUNCTION)) - - -#define CV__TRACE_OPENCV_FUNCTION() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, 0); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_OPENCV_FUNCTION_NAME(name) \ - CV__TRACE_DEFINE_LOCATION_FN(name, 0); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_APP_FUNCTION() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_APP_FUNCTION_NAME(name) \ - CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - - -#define CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_OPENCV_FUNCTION_NAME_SKIP_NESTED(name) \ - CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - -#define CV__TRACE_APP_FUNCTION_SKIP_NESTED() \ - CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED | CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ - const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); - - -#define CV__TRACE_REGION_(name_as_static_string_literal, flags) \ - CV__TRACE_DEFINE_LOCATION_(region, name_as_static_string_literal, flags); \ - CV_TRACE_NS::details::Region CVAUX_CONCAT(__region_, __LINE__)(CV__TRACE_LOCATION_VARNAME(region)); - -#define CV__TRACE_REGION(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, 0) -#define CV__TRACE_REGION_NEXT(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, CV_TRACE_NS::details::REGION_FLAG_REGION_NEXT) - -#define CV__TRACE_ARG_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_ ## arg_id, __LINE__) -#define CV__TRACE_ARG_EXTRA_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_extra_ ## arg_id, __LINE__) - -#define CV__TRACE_DEFINE_ARG_(arg_id, name, flags) \ - static CV_TRACE_NS::details::TraceArg::ExtraData* CV__TRACE_ARG_EXTRA_VARNAME(arg_id) = 0; \ - static const CV_TRACE_NS::details::TraceArg \ - CV__TRACE_ARG_VARNAME(arg_id) = { &(CV__TRACE_ARG_EXTRA_VARNAME(arg_id)), name, flags }; - -#define CV__TRACE_ARG_VALUE(arg_id, arg_name, value) \ - CV__TRACE_DEFINE_ARG_(arg_id, arg_name, 0); \ - CV_TRACE_NS::details::traceArg((CV__TRACE_ARG_VARNAME(arg_id)), value); - -#define CV__TRACE_ARG(arg_id) CV_TRACE_ARG_VALUE(arg_id, #arg_id, (arg_id)) - -} // namespace - -#ifndef OPENCV_DISABLE_TRACE -#undef CV_TRACE_FUNCTION -#undef CV_TRACE_FUNCTION_SKIP_NESTED -#if __OPENCV_TRACE -#define CV_TRACE_FUNCTION CV__TRACE_OPENCV_FUNCTION -#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED -#else -#define CV_TRACE_FUNCTION CV__TRACE_APP_FUNCTION -#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_APP_FUNCTION_SKIP_NESTED -#endif - -#undef CV_TRACE_REGION -#define CV_TRACE_REGION CV__TRACE_REGION - -#undef CV_TRACE_REGION_NEXT -#define CV_TRACE_REGION_NEXT CV__TRACE_REGION_NEXT - -#undef CV_TRACE_ARG_VALUE -#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) \ - if (__region_fn.isActive()) \ - { \ - CV__TRACE_ARG_VALUE(arg_id, arg_name, value); \ - } - -#undef CV_TRACE_ARG -#define CV_TRACE_ARG CV__TRACE_ARG - -#endif // OPENCV_DISABLE_TRACE - -#ifdef OPENCV_TRACE_VERBOSE -#define CV_TRACE_FUNCTION_VERBOSE CV_TRACE_FUNCTION -#define CV_TRACE_REGION_VERBOSE CV_TRACE_REGION -#define CV_TRACE_REGION_NEXT_VERBOSE CV_TRACE_REGION_NEXT -#define CV_TRACE_ARG_VALUE_VERBOSE CV_TRACE_ARG_VALUE -#define CV_TRACE_ARG_VERBOSE CV_TRACE_ARG -#else -#define CV_TRACE_FUNCTION_VERBOSE(...) -#define CV_TRACE_REGION_VERBOSE(...) -#define CV_TRACE_REGION_NEXT_VERBOSE(...) -#define CV_TRACE_ARG_VALUE_VERBOSE(...) -#define CV_TRACE_ARG_VERBOSE(...) -#endif - -//! @endcond - -//! @} - -}}} // namespace - -#endif // OPENCV_TRACE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_TRACE_HPP +#define OPENCV_TRACE_HPP + +#include + +namespace cv { +namespace utils { +namespace trace { + +//! @addtogroup core_logging +//! @{ + +//! Macro to trace function +#define CV_TRACE_FUNCTION() + +#define CV_TRACE_FUNCTION_SKIP_NESTED() + +//! Trace code scope. +//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "initialize". +#define CV_TRACE_REGION(name_as_static_string_literal) +//! mark completed of the current opened region and create new one +//! @note Dynamic names are not supported in this macro (on stack or heap). Use string literals here only, like "step1". +#define CV_TRACE_REGION_NEXT(name_as_static_string_literal) + +//! Macro to trace argument value +#define CV_TRACE_ARG(arg_id) + +//! Macro to trace argument value (expanded version) +#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) + +//! @cond IGNORED +#define CV_TRACE_NS cv::utils::trace + +#if !defined(OPENCV_DISABLE_TRACE) && defined(__EMSCRIPTEN__) +#define OPENCV_DISABLE_TRACE 1 +#endif + +namespace details { + +#ifndef __OPENCV_TRACE +# if defined __OPENCV_BUILD && !defined __OPENCV_TESTS && !defined __OPENCV_APPS +# define __OPENCV_TRACE 1 +# else +# define __OPENCV_TRACE 0 +# endif +#endif + +#ifndef CV_TRACE_FILENAME +# define CV_TRACE_FILENAME __FILE__ +#endif + +#ifndef CV__TRACE_FUNCTION +# if defined _MSC_VER +# define CV__TRACE_FUNCTION __FUNCSIG__ +# elif defined __GNUC__ +# define CV__TRACE_FUNCTION __PRETTY_FUNCTION__ +# else +# define CV__TRACE_FUNCTION "" +# endif +#endif + +//! Thread-local instance (usually allocated on stack) +class CV_EXPORTS Region +{ +public: + struct LocationExtraData; + struct LocationStaticStorage + { + LocationExtraData** ppExtra; ///< implementation specific data + const char* name; ///< region name (function name or other custom name) + const char* filename; ///< source code filename + int line; ///< source code line + int flags; ///< flags (implementation code path: Plain, IPP, OpenCL) + }; + + Region(const LocationStaticStorage& location); + inline ~Region() + { + if (implFlags != 0) + destroy(); + CV_DbgAssert(implFlags == 0); + CV_DbgAssert(pImpl == NULL); + } + + class Impl; + Impl* pImpl; // NULL if current region is not active + int implFlags; // see RegionFlag, 0 if region is ignored + + bool isActive() const { return pImpl != NULL; } + + void destroy(); +private: + Region(const Region&); // disabled + Region& operator= (const Region&); // disabled +}; + +//! Specify region flags +enum RegionLocationFlag { + REGION_FLAG_FUNCTION = (1 << 0), ///< region is function (=1) / nested named region (=0) + REGION_FLAG_APP_CODE = (1 << 1), ///< region is Application code (=1) / OpenCV library code (=0) + REGION_FLAG_SKIP_NESTED = (1 << 2), ///< avoid processing of nested regions + + REGION_FLAG_IMPL_IPP = (1 << 16), ///< region is part of IPP code path + REGION_FLAG_IMPL_OPENCL = (2 << 16), ///< region is part of OpenCL code path + REGION_FLAG_IMPL_OPENVX = (3 << 16), ///< region is part of OpenVX code path + + REGION_FLAG_IMPL_MASK = (15 << 16), + + REGION_FLAG_REGION_FORCE = (1 << 30), + REGION_FLAG_REGION_NEXT = (1 << 31), ///< close previous region (see #CV_TRACE_REGION_NEXT macro) + + ENUM_REGION_FLAG_FORCE_INT = INT_MAX +}; + +struct CV_EXPORTS TraceArg { +public: + struct ExtraData; + ExtraData** ppExtra; + const char* name; + int flags; +}; +/** @brief Add meta information to current region (function) + * See CV_TRACE_ARG macro + * @param arg argument information structure (global static cache) + * @param value argument value (can by dynamic string literal in case of string, static allocation is not required) + */ +CV_EXPORTS void traceArg(const TraceArg& arg, const char* value); +//! @overload +CV_EXPORTS void traceArg(const TraceArg& arg, int value); +//! @overload +CV_EXPORTS void traceArg(const TraceArg& arg, int64 value); +//! @overload +CV_EXPORTS void traceArg(const TraceArg& arg, double value); + +#define CV__TRACE_LOCATION_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_, loc_id), __LINE__) +#define CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) CVAUX_CONCAT(CVAUX_CONCAT(__cv_trace_location_extra_, loc_id) , __LINE__) + +#define CV__TRACE_DEFINE_LOCATION_(loc_id, name, flags) \ + static CV_TRACE_NS::details::Region::LocationExtraData* CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id) = 0; \ + static const CV_TRACE_NS::details::Region::LocationStaticStorage \ + CV__TRACE_LOCATION_VARNAME(loc_id) = { &(CV__TRACE_LOCATION_EXTRA_VARNAME(loc_id)), name, CV_TRACE_FILENAME, __LINE__, flags}; + +#define CV__TRACE_DEFINE_LOCATION_FN(name, flags) CV__TRACE_DEFINE_LOCATION_(fn, name, ((flags) | CV_TRACE_NS::details::REGION_FLAG_FUNCTION)) + + +#define CV__TRACE_OPENCV_FUNCTION() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, 0); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_OPENCV_FUNCTION_NAME(name) \ + CV__TRACE_DEFINE_LOCATION_FN(name, 0); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_APP_FUNCTION() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_APP_FUNCTION_NAME(name) \ + CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + + +#define CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_OPENCV_FUNCTION_NAME_SKIP_NESTED(name) \ + CV__TRACE_DEFINE_LOCATION_FN(name, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + +#define CV__TRACE_APP_FUNCTION_SKIP_NESTED() \ + CV__TRACE_DEFINE_LOCATION_FN(CV__TRACE_FUNCTION, CV_TRACE_NS::details::REGION_FLAG_SKIP_NESTED | CV_TRACE_NS::details::REGION_FLAG_APP_CODE); \ + const CV_TRACE_NS::details::Region __region_fn(CV__TRACE_LOCATION_VARNAME(fn)); + + +#define CV__TRACE_REGION_(name_as_static_string_literal, flags) \ + CV__TRACE_DEFINE_LOCATION_(region, name_as_static_string_literal, flags); \ + CV_TRACE_NS::details::Region CVAUX_CONCAT(__region_, __LINE__)(CV__TRACE_LOCATION_VARNAME(region)); + +#define CV__TRACE_REGION(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, 0) +#define CV__TRACE_REGION_NEXT(name_as_static_string_literal) CV__TRACE_REGION_(name_as_static_string_literal, CV_TRACE_NS::details::REGION_FLAG_REGION_NEXT) + +#define CV__TRACE_ARG_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_ ## arg_id, __LINE__) +#define CV__TRACE_ARG_EXTRA_VARNAME(arg_id) CVAUX_CONCAT(__cv_trace_arg_extra_ ## arg_id, __LINE__) + +#define CV__TRACE_DEFINE_ARG_(arg_id, name, flags) \ + static CV_TRACE_NS::details::TraceArg::ExtraData* CV__TRACE_ARG_EXTRA_VARNAME(arg_id) = 0; \ + static const CV_TRACE_NS::details::TraceArg \ + CV__TRACE_ARG_VARNAME(arg_id) = { &(CV__TRACE_ARG_EXTRA_VARNAME(arg_id)), name, flags }; + +#define CV__TRACE_ARG_VALUE(arg_id, arg_name, value) \ + CV__TRACE_DEFINE_ARG_(arg_id, arg_name, 0); \ + CV_TRACE_NS::details::traceArg((CV__TRACE_ARG_VARNAME(arg_id)), value); + +#define CV__TRACE_ARG(arg_id) CV_TRACE_ARG_VALUE(arg_id, #arg_id, (arg_id)) + +} // namespace + +#ifndef OPENCV_DISABLE_TRACE +#undef CV_TRACE_FUNCTION +#undef CV_TRACE_FUNCTION_SKIP_NESTED +#if __OPENCV_TRACE +#define CV_TRACE_FUNCTION CV__TRACE_OPENCV_FUNCTION +#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_OPENCV_FUNCTION_SKIP_NESTED +#else +#define CV_TRACE_FUNCTION CV__TRACE_APP_FUNCTION +#define CV_TRACE_FUNCTION_SKIP_NESTED CV__TRACE_APP_FUNCTION_SKIP_NESTED +#endif + +#undef CV_TRACE_REGION +#define CV_TRACE_REGION CV__TRACE_REGION + +#undef CV_TRACE_REGION_NEXT +#define CV_TRACE_REGION_NEXT CV__TRACE_REGION_NEXT + +#undef CV_TRACE_ARG_VALUE +#define CV_TRACE_ARG_VALUE(arg_id, arg_name, value) \ + if (__region_fn.isActive()) \ + { \ + CV__TRACE_ARG_VALUE(arg_id, arg_name, value); \ + } + +#undef CV_TRACE_ARG +#define CV_TRACE_ARG CV__TRACE_ARG + +#endif // OPENCV_DISABLE_TRACE + +#ifdef OPENCV_TRACE_VERBOSE +#define CV_TRACE_FUNCTION_VERBOSE CV_TRACE_FUNCTION +#define CV_TRACE_REGION_VERBOSE CV_TRACE_REGION +#define CV_TRACE_REGION_NEXT_VERBOSE CV_TRACE_REGION_NEXT +#define CV_TRACE_ARG_VALUE_VERBOSE CV_TRACE_ARG_VALUE +#define CV_TRACE_ARG_VERBOSE CV_TRACE_ARG +#else +#define CV_TRACE_FUNCTION_VERBOSE(...) +#define CV_TRACE_REGION_VERBOSE(...) +#define CV_TRACE_REGION_NEXT_VERBOSE(...) +#define CV_TRACE_ARG_VALUE_VERBOSE(...) +#define CV_TRACE_ARG_VERBOSE(...) +#endif + +//! @endcond + +//! @} + +}}} // namespace + +#endif // OPENCV_TRACE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp b/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp index e224a7ae06..b37ce75135 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/va_intel.hpp @@ -1,75 +1,75 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -// Copyright (C) 2015, Itseez, Inc., all rights reserved. -// Third party copyrights are property of their respective owners. - -#ifndef OPENCV_CORE_VA_INTEL_HPP -#define OPENCV_CORE_VA_INTEL_HPP - -#ifndef __cplusplus -# error va_intel.hpp header must be compiled as C++ -#endif - -#include "opencv2/core.hpp" -#include "ocl.hpp" - -#if defined(HAVE_VA) -# include "va/va.h" -#else // HAVE_VA -# if !defined(_VA_H_) - typedef void* VADisplay; - typedef unsigned int VASurfaceID; -# endif // !_VA_H_ -#endif // HAVE_VA - -namespace cv { namespace va_intel { - -/** @addtogroup core_va_intel -This section describes Intel VA-API/OpenCL (CL-VA) interoperability. - -To enable basic VA interoperability build OpenCV with libva library integration enabled: `-DWITH_VA=ON` (corresponding dev package should be installed). - -To enable advanced CL-VA interoperability support on Intel HW, enable option: `-DWITH_VA_INTEL=ON` (OpenCL integration should be enabled which is the default setting). Special runtime environment should be set up in order to use this feature: correct combination of [libva](https://github.com/intel/libva), [OpenCL runtime](https://github.com/intel/compute-runtime) and [media driver](https://github.com/intel/media-driver) should be installed. - -Check usage example for details: samples/va_intel/va_intel_interop.cpp -*/ -//! @{ - -/////////////////// CL-VA Interoperability Functions /////////////////// - -namespace ocl { -using namespace cv::ocl; - -// TODO static functions in the Context class -/** @brief Creates OpenCL context from VA. -@param display - VADisplay for which CL interop should be established. -@param tryInterop - try to set up for interoperability, if true; set up for use slow copy if false. -@return Returns reference to OpenCL Context - */ -CV_EXPORTS Context& initializeContextFromVA(VADisplay display, bool tryInterop = true); - -} // namespace cv::va_intel::ocl - -/** @brief Converts InputArray to VASurfaceID object. -@param display - VADisplay object. -@param src - source InputArray. -@param surface - destination VASurfaceID object. -@param size - size of image represented by VASurfaceID object. - */ -CV_EXPORTS void convertToVASurface(VADisplay display, InputArray src, VASurfaceID surface, Size size); - -/** @brief Converts VASurfaceID object to OutputArray. -@param display - VADisplay object. -@param surface - source VASurfaceID object. -@param size - size of image represented by VASurfaceID object. -@param dst - destination OutputArray. - */ -CV_EXPORTS void convertFromVASurface(VADisplay display, VASurfaceID surface, Size size, OutputArray dst); - -//! @} - -}} // namespace cv::va_intel - -#endif /* OPENCV_CORE_VA_INTEL_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +// Copyright (C) 2015, Itseez, Inc., all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef OPENCV_CORE_VA_INTEL_HPP +#define OPENCV_CORE_VA_INTEL_HPP + +#ifndef __cplusplus +# error va_intel.hpp header must be compiled as C++ +#endif + +#include "opencv2/core.hpp" +#include "ocl.hpp" + +#if defined(HAVE_VA) +# include "va/va.h" +#else // HAVE_VA +# if !defined(_VA_H_) + typedef void* VADisplay; + typedef unsigned int VASurfaceID; +# endif // !_VA_H_ +#endif // HAVE_VA + +namespace cv { namespace va_intel { + +/** @addtogroup core_va_intel +This section describes Intel VA-API/OpenCL (CL-VA) interoperability. + +To enable basic VA interoperability build OpenCV with libva library integration enabled: `-DWITH_VA=ON` (corresponding dev package should be installed). + +To enable advanced CL-VA interoperability support on Intel HW, enable option: `-DWITH_VA_INTEL=ON` (OpenCL integration should be enabled which is the default setting). Special runtime environment should be set up in order to use this feature: correct combination of [libva](https://github.com/intel/libva), [OpenCL runtime](https://github.com/intel/compute-runtime) and [media driver](https://github.com/intel/media-driver) should be installed. + +Check usage example for details: samples/va_intel/va_intel_interop.cpp +*/ +//! @{ + +/////////////////// CL-VA Interoperability Functions /////////////////// + +namespace ocl { +using namespace cv::ocl; + +// TODO static functions in the Context class +/** @brief Creates OpenCL context from VA. +@param display - VADisplay for which CL interop should be established. +@param tryInterop - try to set up for interoperability, if true; set up for use slow copy if false. +@return Returns reference to OpenCL Context + */ +CV_EXPORTS Context& initializeContextFromVA(VADisplay display, bool tryInterop = true); + +} // namespace cv::va_intel::ocl + +/** @brief Converts InputArray to VASurfaceID object. +@param display - VADisplay object. +@param src - source InputArray. +@param surface - destination VASurfaceID object. +@param size - size of image represented by VASurfaceID object. + */ +CV_EXPORTS void convertToVASurface(VADisplay display, InputArray src, VASurfaceID surface, Size size); + +/** @brief Converts VASurfaceID object to OutputArray. +@param display - VADisplay object. +@param surface - source VASurfaceID object. +@param size - size of image represented by VASurfaceID object. +@param dst - destination OutputArray. + */ +CV_EXPORTS void convertFromVASurface(VADisplay display, VASurfaceID surface, Size size, OutputArray dst); + +//! @} + +}} // namespace cv::va_intel + +#endif /* OPENCV_CORE_VA_INTEL_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/core/version.hpp b/3rdParty/opencv-4.11.0/opencv2/core/version.hpp index 8a9621f68b..7c5eaa1437 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/version.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/version.hpp @@ -1,26 +1,26 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VERSION_HPP -#define OPENCV_VERSION_HPP - -#define CV_VERSION_MAJOR 4 -#define CV_VERSION_MINOR 11 -#define CV_VERSION_REVISION 0 -#define CV_VERSION_STATUS "" - -#define CVAUX_STR_EXP(__A) #__A -#define CVAUX_STR(__A) CVAUX_STR_EXP(__A) - -#define CVAUX_STRW_EXP(__A) L ## #__A -#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A) - -#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS - -/* old style version constants*/ -#define CV_MAJOR_VERSION CV_VERSION_MAJOR -#define CV_MINOR_VERSION CV_VERSION_MINOR -#define CV_SUBMINOR_VERSION CV_VERSION_REVISION - -#endif // OPENCV_VERSION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VERSION_HPP +#define OPENCV_VERSION_HPP + +#define CV_VERSION_MAJOR 4 +#define CV_VERSION_MINOR 11 +#define CV_VERSION_REVISION 0 +#define CV_VERSION_STATUS "" + +#define CVAUX_STR_EXP(__A) #__A +#define CVAUX_STR(__A) CVAUX_STR_EXP(__A) + +#define CVAUX_STRW_EXP(__A) L ## #__A +#define CVAUX_STRW(__A) CVAUX_STRW_EXP(__A) + +#define CV_VERSION CVAUX_STR(CV_VERSION_MAJOR) "." CVAUX_STR(CV_VERSION_MINOR) "." CVAUX_STR(CV_VERSION_REVISION) CV_VERSION_STATUS + +/* old style version constants*/ +#define CV_MAJOR_VERSION CV_VERSION_MAJOR +#define CV_MINOR_VERSION CV_VERSION_MINOR +#define CV_SUBMINOR_VERSION CV_VERSION_REVISION + +#endif // OPENCV_VERSION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp index c285c7edf2..79a1074d59 100644 --- a/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/core/vsx_utils.hpp @@ -1,1047 +1,1047 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_HAL_VSX_UTILS_HPP -#define OPENCV_HAL_VSX_UTILS_HPP - -#include "opencv2/core/cvdef.h" - -#ifndef SKIP_INCLUDES -# include -#endif - -//! @addtogroup core_utils_vsx -//! @{ -#if CV_VSX - -#define __VSX_S16__(c, v) (c){v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v} -#define __VSX_S8__(c, v) (c){v, v, v, v, v, v, v, v} -#define __VSX_S4__(c, v) (c){v, v, v, v} -#define __VSX_S2__(c, v) (c){v, v} - -typedef __vector unsigned char vec_uchar16; -#define vec_uchar16_set(...) (vec_uchar16){__VA_ARGS__} -#define vec_uchar16_sp(c) (__VSX_S16__(vec_uchar16, (unsigned char)c)) -#define vec_uchar16_c(v) ((vec_uchar16)(v)) -#define vec_uchar16_z vec_uchar16_sp(0) - -typedef __vector signed char vec_char16; -#define vec_char16_set(...) (vec_char16){__VA_ARGS__} -#define vec_char16_sp(c) (__VSX_S16__(vec_char16, (signed char)c)) -#define vec_char16_c(v) ((vec_char16)(v)) -#define vec_char16_z vec_char16_sp(0) - -typedef __vector unsigned short vec_ushort8; -#define vec_ushort8_set(...) (vec_ushort8){__VA_ARGS__} -#define vec_ushort8_sp(c) (__VSX_S8__(vec_ushort8, (unsigned short)c)) -#define vec_ushort8_c(v) ((vec_ushort8)(v)) -#define vec_ushort8_z vec_ushort8_sp(0) - -typedef __vector signed short vec_short8; -#define vec_short8_set(...) (vec_short8){__VA_ARGS__} -#define vec_short8_sp(c) (__VSX_S8__(vec_short8, (signed short)c)) -#define vec_short8_c(v) ((vec_short8)(v)) -#define vec_short8_z vec_short8_sp(0) - -typedef __vector unsigned int vec_uint4; -#define vec_uint4_set(...) (vec_uint4){__VA_ARGS__} -#define vec_uint4_sp(c) (__VSX_S4__(vec_uint4, (unsigned int)c)) -#define vec_uint4_c(v) ((vec_uint4)(v)) -#define vec_uint4_z vec_uint4_sp(0) - -typedef __vector signed int vec_int4; -#define vec_int4_set(...) (vec_int4){__VA_ARGS__} -#define vec_int4_sp(c) (__VSX_S4__(vec_int4, (signed int)c)) -#define vec_int4_c(v) ((vec_int4)(v)) -#define vec_int4_z vec_int4_sp(0) - -typedef __vector float vec_float4; -#define vec_float4_set(...) (vec_float4){__VA_ARGS__} -#define vec_float4_sp(c) (__VSX_S4__(vec_float4, c)) -#define vec_float4_c(v) ((vec_float4)(v)) -#define vec_float4_z vec_float4_sp(0) - -typedef __vector unsigned long long vec_udword2; -#define vec_udword2_set(...) (vec_udword2){__VA_ARGS__} -#define vec_udword2_sp(c) (__VSX_S2__(vec_udword2, (unsigned long long)c)) -#define vec_udword2_c(v) ((vec_udword2)(v)) -#define vec_udword2_z vec_udword2_sp(0) - -typedef __vector signed long long vec_dword2; -#define vec_dword2_set(...) (vec_dword2){__VA_ARGS__} -#define vec_dword2_sp(c) (__VSX_S2__(vec_dword2, (signed long long)c)) -#define vec_dword2_c(v) ((vec_dword2)(v)) -#define vec_dword2_z vec_dword2_sp(0) - -typedef __vector double vec_double2; -#define vec_double2_set(...) (vec_double2){__VA_ARGS__} -#define vec_double2_c(v) ((vec_double2)(v)) -#define vec_double2_sp(c) (__VSX_S2__(vec_double2, c)) -#define vec_double2_z vec_double2_sp(0) - -#define vec_bchar16 __vector __bool char -#define vec_bchar16_set(...) (vec_bchar16){__VA_ARGS__} -#define vec_bchar16_c(v) ((vec_bchar16)(v)) - -#define vec_bshort8 __vector __bool short -#define vec_bshort8_set(...) (vec_bshort8){__VA_ARGS__} -#define vec_bshort8_c(v) ((vec_bshort8)(v)) - -#define vec_bint4 __vector __bool int -#define vec_bint4_set(...) (vec_bint4){__VA_ARGS__} -#define vec_bint4_c(v) ((vec_bint4)(v)) - -#define vec_bdword2 __vector __bool long long -#define vec_bdword2_set(...) (vec_bdword2){__VA_ARGS__} -#define vec_bdword2_c(v) ((vec_bdword2)(v)) - -#define VSX_FINLINE(tp) extern inline tp __attribute__((always_inline)) - -#define VSX_REDIRECT_1RG(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) { return fn2(a); } - -#define VSX_REDIRECT_2RG(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a, const rg& b) { return fn2(a, b); } - -/* - * GCC VSX compatibility -**/ -#if defined(__GNUG__) && !defined(__clang__) - -// inline asm helper -#define VSX_IMPL_1RG(rt, rg, opc, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "=wa" (rs) : "wa" (a)); return rs; } - -#define VSX_IMPL_1VRG(rt, rg, opc, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ rt rs; __asm__ __volatile__(#opc" %0,%1" : "=v" (rs) : "v" (a)); return rs; } - -#define VSX_IMPL_2VRG_F(rt, rg, fopc, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a, const rg& b) \ -{ rt rs; __asm__ __volatile__(fopc : "=v" (rs) : "v" (a), "v" (b)); return rs; } - -#define VSX_IMPL_2VRG(rt, rg, opc, fnm) VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%1,%2", fnm) - -#if __GNUG__ < 8 - - // Support for int4 -> dword2 expanding multiply was added in GCC 8. - #ifdef vec_mule - #undef vec_mule - #endif - #ifdef vec_mulo - #undef vec_mulo - #endif - - VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mule, __builtin_vec_mule) - VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mulo, __builtin_vec_mulo) - VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mulo, __builtin_vec_mulo) - VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mulo, __builtin_vec_mulo) - VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mulo, __builtin_vec_mulo) - - // dword2 support arrived in ISA 2.07 and GCC 8+ - VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulosw, vec_mule) - VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmulouw, vec_mule) - VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulesw, vec_mulo) - VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmuleuw, vec_mulo) - -#endif - -#if __GNUG__ < 7 -// up to GCC 6 vec_mul only supports precisions and llong -# ifdef vec_mul -# undef vec_mul -# endif -/* - * there's no a direct instruction for supporting 8-bit, 16-bit multiplication in ISA 2.07, - * XLC Implement it by using instruction "multiply even", "multiply odd" and "permute" -**/ -# define VSX_IMPL_MULH(Tvec, cperm) \ - VSX_FINLINE(Tvec) vec_mul(const Tvec& a, const Tvec& b) \ - { \ - static const vec_uchar16 ev_od = {cperm}; \ - return vec_perm((Tvec)vec_mule(a, b), (Tvec)vec_mulo(a, b), ev_od); \ - } - #define VSX_IMPL_MULH_P16 0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30 - VSX_IMPL_MULH(vec_char16, VSX_IMPL_MULH_P16) - VSX_IMPL_MULH(vec_uchar16, VSX_IMPL_MULH_P16) - #define VSX_IMPL_MULH_P8 0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29 - VSX_IMPL_MULH(vec_short8, VSX_IMPL_MULH_P8) - VSX_IMPL_MULH(vec_ushort8, VSX_IMPL_MULH_P8) - // vmuluwm can be used for unsigned or signed integers, that's what they said - VSX_IMPL_2VRG(vec_int4, vec_int4, vmuluwm, vec_mul) - VSX_IMPL_2VRG(vec_uint4, vec_uint4, vmuluwm, vec_mul) - // redirect to GCC builtin vec_mul, since it already supports precisions and llong - VSX_REDIRECT_2RG(vec_float4, vec_float4, vec_mul, __builtin_vec_mul) - VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mul, __builtin_vec_mul) - VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mul, __builtin_vec_mul) - VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mul, __builtin_vec_mul) -#endif // __GNUG__ < 7 - -#if __GNUG__ < 6 -/* - * Instruction "compare greater than or equal" in ISA 2.07 only supports single - * and double precision. - * In XLC and new versions of GCC implement integers by using instruction "greater than" and NOR. -**/ -# ifdef vec_cmpge -# undef vec_cmpge -# endif -# ifdef vec_cmple -# undef vec_cmple -# endif -# define vec_cmple(a, b) vec_cmpge(b, a) -# define VSX_IMPL_CMPGE(rt, rg, opc, fnm) \ - VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%2,%1\n\t xxlnor %x0,%x0,%x0", fnm) - - VSX_IMPL_CMPGE(vec_bchar16, vec_char16, vcmpgtsb, vec_cmpge) - VSX_IMPL_CMPGE(vec_bchar16, vec_uchar16, vcmpgtub, vec_cmpge) - VSX_IMPL_CMPGE(vec_bshort8, vec_short8, vcmpgtsh, vec_cmpge) - VSX_IMPL_CMPGE(vec_bshort8, vec_ushort8, vcmpgtuh, vec_cmpge) - VSX_IMPL_CMPGE(vec_bint4, vec_int4, vcmpgtsw, vec_cmpge) - VSX_IMPL_CMPGE(vec_bint4, vec_uint4, vcmpgtuw, vec_cmpge) - VSX_IMPL_CMPGE(vec_bdword2, vec_dword2, vcmpgtsd, vec_cmpge) - VSX_IMPL_CMPGE(vec_bdword2, vec_udword2, vcmpgtud, vec_cmpge) - -// redirect to GCC builtin cmpge, since it already supports precisions - VSX_REDIRECT_2RG(vec_bint4, vec_float4, vec_cmpge, __builtin_vec_cmpge) - VSX_REDIRECT_2RG(vec_bdword2, vec_double2, vec_cmpge, __builtin_vec_cmpge) - -// up to gcc5 vec_nor doesn't support bool long long -# undef vec_nor - template - VSX_REDIRECT_2RG(T, T, vec_nor, __builtin_vec_nor) - - VSX_FINLINE(vec_bdword2) vec_nor(const vec_bdword2& a, const vec_bdword2& b) - { return vec_bdword2_c(__builtin_vec_nor(vec_dword2_c(a), vec_dword2_c(b))); } - -// vec_packs doesn't support double words in gcc4 and old versions of gcc5 -# undef vec_packs - VSX_REDIRECT_2RG(vec_char16, vec_short8, vec_packs, __builtin_vec_packs) - VSX_REDIRECT_2RG(vec_uchar16, vec_ushort8, vec_packs, __builtin_vec_packs) - VSX_REDIRECT_2RG(vec_short8, vec_int4, vec_packs, __builtin_vec_packs) - VSX_REDIRECT_2RG(vec_ushort8, vec_uint4, vec_packs, __builtin_vec_packs) - - VSX_IMPL_2VRG_F(vec_int4, vec_dword2, "vpksdss %0,%2,%1", vec_packs) - VSX_IMPL_2VRG_F(vec_uint4, vec_udword2, "vpkudus %0,%2,%1", vec_packs) -#endif // __GNUG__ < 6 - -#if __GNUG__ < 5 -// vec_xxpermdi in gcc4 missing little-endian supports just like clang -# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) -// same as vec_xxpermdi -# undef vec_vbpermq - VSX_IMPL_2VRG(vec_udword2, vec_uchar16, vbpermq, vec_vbpermq) - VSX_IMPL_2VRG(vec_dword2, vec_char16, vbpermq, vec_vbpermq) -#else -# define vec_permi vec_xxpermdi -#endif // __GNUG__ < 5 - -// shift left double by word immediate -#ifndef vec_sldw -# define vec_sldw __builtin_vsx_xxsldwi -#endif - -// vector population count -VSX_IMPL_1VRG(vec_uchar16, vec_uchar16, vpopcntb, vec_popcntu) -VSX_IMPL_1VRG(vec_uchar16, vec_char16, vpopcntb, vec_popcntu) -VSX_IMPL_1VRG(vec_ushort8, vec_ushort8, vpopcnth, vec_popcntu) -VSX_IMPL_1VRG(vec_ushort8, vec_short8, vpopcnth, vec_popcntu) -VSX_IMPL_1VRG(vec_uint4, vec_uint4, vpopcntw, vec_popcntu) -VSX_IMPL_1VRG(vec_uint4, vec_int4, vpopcntw, vec_popcntu) -VSX_IMPL_1VRG(vec_udword2, vec_udword2, vpopcntd, vec_popcntu) -VSX_IMPL_1VRG(vec_udword2, vec_dword2, vpopcntd, vec_popcntu) - -// converts between single and double-precision -VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) -VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) - -// converts word and doubleword to double-precision -#undef vec_ctd -VSX_IMPL_1RG(vec_double2, vec_int4, xvcvsxwdp, vec_ctdo) -VSX_IMPL_1RG(vec_double2, vec_uint4, xvcvuxwdp, vec_ctdo) -VSX_IMPL_1RG(vec_double2, vec_dword2, xvcvsxddp, vec_ctd) -VSX_IMPL_1RG(vec_double2, vec_udword2, xvcvuxddp, vec_ctd) - -// converts word and doubleword to single-precision -#undef vec_ctf -VSX_IMPL_1RG(vec_float4, vec_int4, xvcvsxwsp, vec_ctf) -VSX_IMPL_1RG(vec_float4, vec_uint4, xvcvuxwsp, vec_ctf) -VSX_IMPL_1RG(vec_float4, vec_dword2, xvcvsxdsp, vec_ctfo) -VSX_IMPL_1RG(vec_float4, vec_udword2, xvcvuxdsp, vec_ctfo) - -// converts single and double precision to signed word -#undef vec_cts -VSX_IMPL_1RG(vec_int4, vec_double2, xvcvdpsxws, vec_ctso) -VSX_IMPL_1RG(vec_int4, vec_float4, xvcvspsxws, vec_cts) - -// converts single and double precision to unsigned word -#undef vec_ctu -VSX_IMPL_1RG(vec_uint4, vec_double2, xvcvdpuxws, vec_ctuo) -VSX_IMPL_1RG(vec_uint4, vec_float4, xvcvspuxws, vec_ctu) - -// converts single and double precision to signed doubleword -#undef vec_ctsl -VSX_IMPL_1RG(vec_dword2, vec_double2, xvcvdpsxds, vec_ctsl) -VSX_IMPL_1RG(vec_dword2, vec_float4, xvcvspsxds, vec_ctslo) - -// converts single and double precision to unsigned doubleword -#undef vec_ctul -VSX_IMPL_1RG(vec_udword2, vec_double2, xvcvdpuxds, vec_ctul) -VSX_IMPL_1RG(vec_udword2, vec_float4, xvcvspuxds, vec_ctulo) - -// just in case if GCC doesn't define it -#ifndef vec_xl -# define vec_xl vec_vsx_ld -# define vec_xst vec_vsx_st -#endif - -#endif // GCC VSX compatibility - -/* - * CLANG VSX compatibility -**/ -#if defined(__clang__) && !defined(__IBMCPP__) - -/* - * CLANG doesn't support %x in the inline asm template which fixes register number - * when using any of the register constraints wa, wd, wf - * - * For more explanation checkout PowerPC and IBM RS6000 in https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html - * Also there's already an open bug https://bugs.llvm.org/show_bug.cgi?id=31837 - * - * So we're not able to use inline asm and only use built-in functions that CLANG supports - * and use __builtin_convertvector if clang missing any of vector conversions built-in functions - * - * todo: clang asm template bug is fixed, need to reconsider the current workarounds. -*/ - -// convert vector helper -#define VSX_IMPL_CONVERT(rt, rg, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) { return __builtin_convertvector(a, rt); } - -#ifndef vec_permi -#if __clang_major__ < 5 -// implement vec_permi in a dirty way -# define VSX_IMPL_CLANG_4_PERMI(Tvec) \ - VSX_FINLINE(Tvec) vec_permi(const Tvec& a, const Tvec& b, unsigned const char c) \ - { \ - switch (c) \ - { \ - case 0: \ - return vec_mergeh(a, b); \ - case 1: \ - return vec_mergel(vec_mergeh(a, a), b); \ - case 2: \ - return vec_mergeh(vec_mergel(a, a), b); \ - default: \ - return vec_mergel(a, b); \ - } \ - } - VSX_IMPL_CLANG_4_PERMI(vec_udword2) - VSX_IMPL_CLANG_4_PERMI(vec_dword2) - VSX_IMPL_CLANG_4_PERMI(vec_double2) - -// vec_xxsldwi is missing in clang 4 -# define vec_xxsldwi(a, b, c) vec_sld(a, b, (c) * 4) -#else -// vec_xxpermdi is missing little-endian supports in clang 4 just like gcc4 -# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) -#endif // __clang_major__ < 5 -#endif - -// shift left double by word immediate -#ifndef vec_sldw -# define vec_sldw vec_xxsldwi -#endif - -#if __clang_major__ < 13 -// Implement vec_rsqrt since clang only supports vec_rsqrte -#ifndef vec_rsqrt - VSX_FINLINE(vec_float4) vec_rsqrt(const vec_float4& a) - { return vec_div(vec_float4_sp(1), vec_sqrt(a)); } - - VSX_FINLINE(vec_double2) vec_rsqrt(const vec_double2& a) - { return vec_div(vec_double2_sp(1), vec_sqrt(a)); } -#endif - -// vec_promote missing support for doubleword -VSX_FINLINE(vec_dword2) vec_promote(long long a, int b) -{ - vec_dword2 ret = vec_dword2_z; - ret[b & 1] = a; - return ret; -} - -VSX_FINLINE(vec_udword2) vec_promote(unsigned long long a, int b) -{ - vec_udword2 ret = vec_udword2_z; - ret[b & 1] = a; - return ret; -} -#endif - -// vec_popcnt should return unsigned but clang has different thought just like gcc in vec_vpopcnt -#define VSX_IMPL_POPCNTU(Tvec, Tvec2, ucast) \ -VSX_FINLINE(Tvec) vec_popcntu(const Tvec2& a) \ -{ return ucast(vec_popcnt(a)); } -VSX_IMPL_POPCNTU(vec_uchar16, vec_char16, vec_uchar16_c); -VSX_IMPL_POPCNTU(vec_ushort8, vec_short8, vec_ushort8_c); -VSX_IMPL_POPCNTU(vec_uint4, vec_int4, vec_uint4_c); -VSX_IMPL_POPCNTU(vec_udword2, vec_dword2, vec_udword2_c); -// redirect unsigned types -VSX_REDIRECT_1RG(vec_uchar16, vec_uchar16, vec_popcntu, vec_popcnt) -VSX_REDIRECT_1RG(vec_ushort8, vec_ushort8, vec_popcntu, vec_popcnt) -VSX_REDIRECT_1RG(vec_uint4, vec_uint4, vec_popcntu, vec_popcnt) -VSX_REDIRECT_1RG(vec_udword2, vec_udword2, vec_popcntu, vec_popcnt) - -// converts between single and double precision -VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) -VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) - -// converts word and doubleword to double-precision -#ifdef vec_ctd -# undef vec_ctd -#endif -VSX_REDIRECT_1RG(vec_double2, vec_int4, vec_ctdo, __builtin_vsx_xvcvsxwdp) -VSX_REDIRECT_1RG(vec_double2, vec_uint4, vec_ctdo, __builtin_vsx_xvcvuxwdp) - -VSX_IMPL_CONVERT(vec_double2, vec_dword2, vec_ctd) -VSX_IMPL_CONVERT(vec_double2, vec_udword2, vec_ctd) - -// converts word and doubleword to single-precision -#if __clang_major__ > 4 -# undef vec_ctf -#endif -VSX_IMPL_CONVERT(vec_float4, vec_int4, vec_ctf) -VSX_IMPL_CONVERT(vec_float4, vec_uint4, vec_ctf) -VSX_REDIRECT_1RG(vec_float4, vec_dword2, vec_ctfo, __builtin_vsx_xvcvsxdsp) -VSX_REDIRECT_1RG(vec_float4, vec_udword2, vec_ctfo, __builtin_vsx_xvcvuxdsp) - -// converts single and double precision to signed word -#if __clang_major__ > 4 -# undef vec_cts -#endif -VSX_REDIRECT_1RG(vec_int4, vec_double2, vec_ctso, __builtin_vsx_xvcvdpsxws) -VSX_IMPL_CONVERT(vec_int4, vec_float4, vec_cts) - -// converts single and double precision to unsigned word -#if __clang_major__ > 4 -# undef vec_ctu -#endif -VSX_REDIRECT_1RG(vec_uint4, vec_double2, vec_ctuo, __builtin_vsx_xvcvdpuxws) -VSX_IMPL_CONVERT(vec_uint4, vec_float4, vec_ctu) - -// converts single and double precision to signed doubleword -#ifdef vec_ctsl -# undef vec_ctsl -#endif -VSX_IMPL_CONVERT(vec_dword2, vec_double2, vec_ctsl) -// __builtin_convertvector unable to convert, xvcvspsxds is missing on it -VSX_FINLINE(vec_dword2) vec_ctslo(const vec_float4& a) -{ return vec_ctsl(vec_cvfo(a)); } - -// converts single and double precision to unsigned doubleword -#ifdef vec_ctul -# undef vec_ctul -#endif -VSX_IMPL_CONVERT(vec_udword2, vec_double2, vec_ctul) -// __builtin_convertvector unable to convert, xvcvspuxds is missing on it -VSX_FINLINE(vec_udword2) vec_ctulo(const vec_float4& a) -{ return vec_ctul(vec_cvfo(a)); } - -#endif // CLANG VSX compatibility - -/* - * Common GCC, CLANG compatibility -**/ -#if defined(__GNUG__) && !defined(__IBMCPP__) - -#ifdef vec_cvf -# undef vec_cvf -#endif - -#define VSX_IMPL_CONV_EVEN_4_2(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ return fn2(vec_sldw(a, a, 1)); } - -VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_float4, vec_cvf, vec_cvfo) -VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_int4, vec_ctd, vec_ctdo) -VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_uint4, vec_ctd, vec_ctdo) - -VSX_IMPL_CONV_EVEN_4_2(vec_dword2, vec_float4, vec_ctsl, vec_ctslo) -VSX_IMPL_CONV_EVEN_4_2(vec_udword2, vec_float4, vec_ctul, vec_ctulo) - -#define VSX_IMPL_CONV_EVEN_2_4(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ \ - rt v4 = fn2(a); \ - return vec_sldw(v4, v4, 3); \ -} - -VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_double2, vec_cvf, vec_cvfo) -VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_dword2, vec_ctf, vec_ctfo) -VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_udword2, vec_ctf, vec_ctfo) - -VSX_IMPL_CONV_EVEN_2_4(vec_int4, vec_double2, vec_cts, vec_ctso) -VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo) - -// Only for Eigen! -/* - * changing behavior of conversion intrinsics for gcc has effect on Eigen - * so we redefine old behavior again only on gcc, clang -*/ -#if !defined(__clang__) || __clang_major__ > 4 - // ignoring second arg since Eigen only truncates toward zero -# define VSX_IMPL_CONV_2VARIANT(rt, rg, fnm, fn2) \ - VSX_FINLINE(rt) fnm(const rg& a, int only_truncate) \ - { \ - assert(only_truncate == 0); \ - CV_UNUSED(only_truncate); \ - return fn2(a); \ - } - VSX_IMPL_CONV_2VARIANT(vec_int4, vec_float4, vec_cts, vec_cts) - VSX_IMPL_CONV_2VARIANT(vec_uint4, vec_float4, vec_ctu, vec_ctu) - VSX_IMPL_CONV_2VARIANT(vec_float4, vec_int4, vec_ctf, vec_ctf) - VSX_IMPL_CONV_2VARIANT(vec_float4, vec_uint4, vec_ctf, vec_ctf) - // define vec_cts for converting double precision to signed doubleword - // which isn't compatible with xlc but its okay since Eigen only uses it for gcc - VSX_IMPL_CONV_2VARIANT(vec_dword2, vec_double2, vec_cts, vec_ctsl) -#endif // Eigen - -#endif // Common GCC, CLANG compatibility - -/* - * XLC VSX compatibility -**/ -#if defined(__IBMCPP__) - -// vector population count -#define vec_popcntu vec_popcnt - -// overload and redirect with setting second arg to zero -// since we only support conversions without the second arg -#define VSX_IMPL_OVERLOAD_Z2(rt, rg, fnm) \ -VSX_FINLINE(rt) fnm(const rg& a) { return fnm(a, 0); } - -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_int4, vec_ctd) -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_uint4, vec_ctd) -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_dword2, vec_ctd) -VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_udword2, vec_ctd) - -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_int4, vec_ctf) -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_uint4, vec_ctf) -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_dword2, vec_ctf) -VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_udword2, vec_ctf) - -VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_double2, vec_cts) -VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_float4, vec_cts) - -VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_double2, vec_ctu) -VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_float4, vec_ctu) - -VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_double2, vec_ctsl) -VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_float4, vec_ctsl) - -VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_double2, vec_ctul) -VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_float4, vec_ctul) - -// fixme: implement conversions of odd-numbered elements in a dirty way -// since xlc doesn't support VSX registers operand in inline asm. -#define VSX_IMPL_CONV_ODD_4_2(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) { return fn2(vec_sldw(a, a, 3)); } - -VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_float4, vec_cvfo, vec_cvf) -VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_int4, vec_ctdo, vec_ctd) -VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_uint4, vec_ctdo, vec_ctd) - -VSX_IMPL_CONV_ODD_4_2(vec_dword2, vec_float4, vec_ctslo, vec_ctsl) -VSX_IMPL_CONV_ODD_4_2(vec_udword2, vec_float4, vec_ctulo, vec_ctul) - -#define VSX_IMPL_CONV_ODD_2_4(rt, rg, fnm, fn2) \ -VSX_FINLINE(rt) fnm(const rg& a) \ -{ \ - rt v4 = fn2(a); \ - return vec_sldw(v4, v4, 1); \ -} - -VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_double2, vec_cvfo, vec_cvf) -VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_dword2, vec_ctfo, vec_ctf) -VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_udword2, vec_ctfo, vec_ctf) - -VSX_IMPL_CONV_ODD_2_4(vec_int4, vec_double2, vec_ctso, vec_cts) -VSX_IMPL_CONV_ODD_2_4(vec_uint4, vec_double2, vec_ctuo, vec_ctu) - -#endif // XLC VSX compatibility - -// ignore GCC warning that caused by -Wunused-but-set-variable in rare cases -#if defined(__GNUG__) && !defined(__clang__) -# define VSX_UNUSED(Tvec) Tvec __attribute__((__unused__)) -#else // CLANG, XLC -# define VSX_UNUSED(Tvec) Tvec -#endif - -// gcc can find his way in casting log int and XLC, CLANG ambiguous -#if defined(__clang__) || defined(__IBMCPP__) - VSX_FINLINE(vec_udword2) vec_splats(uint64 v) - { return vec_splats((unsigned long long) v); } - - VSX_FINLINE(vec_dword2) vec_splats(int64 v) - { return vec_splats((long long) v); } - - VSX_FINLINE(vec_udword2) vec_promote(uint64 a, int b) - { return vec_promote((unsigned long long) a, b); } - - VSX_FINLINE(vec_dword2) vec_promote(int64 a, int b) - { return vec_promote((long long) a, b); } -#endif - -/* - * implement vsx_ld(offset, pointer), vsx_st(vector, offset, pointer) - * load and set using offset depend on the pointer type - * - * implement vsx_ldf(offset, pointer), vsx_stf(vector, offset, pointer) - * load and set using offset depend on fixed bytes size - * - * Note: In clang vec_xl and vec_xst fails to load unaligned addresses - * so we are using vec_vsx_ld, vec_vsx_st instead -*/ - -#if defined(__clang__) && !defined(__IBMCPP__) -# define vsx_ldf vec_vsx_ld -# define vsx_stf vec_vsx_st -#else // GCC , XLC -# define vsx_ldf vec_xl -# define vsx_stf vec_xst -#endif - -#define VSX_OFFSET(o, p) ((o) * sizeof(*(p))) -#define vsx_ld(o, p) vsx_ldf(VSX_OFFSET(o, p), p) -#define vsx_st(v, o, p) vsx_stf(v, VSX_OFFSET(o, p), p) - -/* - * implement vsx_ld2(offset, pointer), vsx_st2(vector, offset, pointer) to load and store double words - * In GCC vec_xl and vec_xst it maps to vec_vsx_ld, vec_vsx_st which doesn't support long long - * and in CLANG we are using vec_vsx_ld, vec_vsx_st because vec_xl, vec_xst fails to load unaligned addresses - * - * In XLC vec_xl and vec_xst fail to cast int64(long int) to long long -*/ -#if (defined(__GNUG__) || defined(__clang__)) && !defined(__IBMCPP__) - VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) - { return vec_udword2_c(vsx_ldf(VSX_OFFSET(o, p), (unsigned int*)p)); } - - VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) - { return vec_dword2_c(vsx_ldf(VSX_OFFSET(o, p), (int*)p)); } - - VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) - { vsx_stf(vec_uint4_c(vec), VSX_OFFSET(o, p), (unsigned int*)p); } - - VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) - { vsx_stf(vec_int4_c(vec), VSX_OFFSET(o, p), (int*)p); } -#else // XLC - VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) - { return vsx_ldf(VSX_OFFSET(o, p), (unsigned long long*)p); } - - VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) - { return vsx_ldf(VSX_OFFSET(o, p), (long long*)p); } - - VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) - { vsx_stf(vec, VSX_OFFSET(o, p), (unsigned long long*)p); } - - VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) - { vsx_stf(vec, VSX_OFFSET(o, p), (long long*)p); } -#endif - -// Store lower 8 byte -#define vec_st_l8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 0) - -// Store higher 8 byte -#define vec_st_h8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 1) - -// Load 64-bits of integer data to lower part -#define VSX_IMPL_LOAD_L8(Tvec, Tp) \ -VSX_FINLINE(Tvec) vec_ld_l8(const Tp *p) \ -{ return ((Tvec)vec_promote(*((uint64*)p), 0)); } - -VSX_IMPL_LOAD_L8(vec_uchar16, uchar) -VSX_IMPL_LOAD_L8(vec_char16, schar) -VSX_IMPL_LOAD_L8(vec_ushort8, ushort) -VSX_IMPL_LOAD_L8(vec_short8, short) -VSX_IMPL_LOAD_L8(vec_uint4, uint) -VSX_IMPL_LOAD_L8(vec_int4, int) -VSX_IMPL_LOAD_L8(vec_float4, float) -VSX_IMPL_LOAD_L8(vec_udword2, uint64) -VSX_IMPL_LOAD_L8(vec_dword2, int64) -VSX_IMPL_LOAD_L8(vec_double2, double) - -// logical not -#define vec_not(a) vec_nor(a, a) - -// power9 yaya -// not equal -#ifndef vec_cmpne -# define vec_cmpne(a, b) vec_not(vec_cmpeq(a, b)) -#endif - -// absolute difference -#ifndef _ARCH_PWR9 -# undef vec_absd -# define vec_absd(a, b) vec_sub(vec_max(a, b), vec_min(a, b)) -#endif - -/* - * Implement vec_unpacklu and vec_unpackhu - * since vec_unpackl, vec_unpackh only support signed integers -**/ -#define VSX_IMPL_UNPACKU(rt, rg, zero) \ -VSX_FINLINE(rt) vec_unpacklu(const rg& a) \ -{ return (rt)(vec_mergel(a, zero)); } \ -VSX_FINLINE(rt) vec_unpackhu(const rg& a) \ -{ return (rt)(vec_mergeh(a, zero)); } - -VSX_IMPL_UNPACKU(vec_ushort8, vec_uchar16, vec_uchar16_z) -VSX_IMPL_UNPACKU(vec_uint4, vec_ushort8, vec_ushort8_z) -VSX_IMPL_UNPACKU(vec_udword2, vec_uint4, vec_uint4_z) - -/* - * Implement vec_mergesqe and vec_mergesqo - * Merges the sequence values of even and odd elements of two vectors -*/ -#define VSX_IMPL_PERM(rt, fnm, ...) \ -VSX_FINLINE(rt) fnm(const rt& a, const rt& b) \ -{ static const vec_uchar16 perm = {__VA_ARGS__}; return vec_perm(a, b, perm); } - -// 16 -#define perm16_mergesqe 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 -#define perm16_mergesqo 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 -VSX_IMPL_PERM(vec_uchar16, vec_mergesqe, perm16_mergesqe) -VSX_IMPL_PERM(vec_uchar16, vec_mergesqo, perm16_mergesqo) -VSX_IMPL_PERM(vec_char16, vec_mergesqe, perm16_mergesqe) -VSX_IMPL_PERM(vec_char16, vec_mergesqo, perm16_mergesqo) -// 8 -#define perm8_mergesqe 0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29 -#define perm8_mergesqo 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 -VSX_IMPL_PERM(vec_ushort8, vec_mergesqe, perm8_mergesqe) -VSX_IMPL_PERM(vec_ushort8, vec_mergesqo, perm8_mergesqo) -VSX_IMPL_PERM(vec_short8, vec_mergesqe, perm8_mergesqe) -VSX_IMPL_PERM(vec_short8, vec_mergesqo, perm8_mergesqo) -// 4 -#define perm4_mergesqe 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27 -#define perm4_mergesqo 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 -VSX_IMPL_PERM(vec_uint4, vec_mergesqe, perm4_mergesqe) -VSX_IMPL_PERM(vec_uint4, vec_mergesqo, perm4_mergesqo) -VSX_IMPL_PERM(vec_int4, vec_mergesqe, perm4_mergesqe) -VSX_IMPL_PERM(vec_int4, vec_mergesqo, perm4_mergesqo) -VSX_IMPL_PERM(vec_float4, vec_mergesqe, perm4_mergesqe) -VSX_IMPL_PERM(vec_float4, vec_mergesqo, perm4_mergesqo) -// 2 -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqe, vec_mergeh) -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqo, vec_mergel) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqe, vec_mergeh) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqo, vec_mergel) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqe, vec_mergeh) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqo, vec_mergel) - -/* - * Implement vec_mergesqh and vec_mergesql - * Merges the sequence most and least significant halves of two vectors -*/ -#define VSX_IMPL_MERGESQHL(Tvec) \ -VSX_FINLINE(Tvec) vec_mergesqh(const Tvec& a, const Tvec& b) \ -{ return (Tvec)vec_mergeh(vec_udword2_c(a), vec_udword2_c(b)); } \ -VSX_FINLINE(Tvec) vec_mergesql(const Tvec& a, const Tvec& b) \ -{ return (Tvec)vec_mergel(vec_udword2_c(a), vec_udword2_c(b)); } -VSX_IMPL_MERGESQHL(vec_uchar16) -VSX_IMPL_MERGESQHL(vec_char16) -VSX_IMPL_MERGESQHL(vec_ushort8) -VSX_IMPL_MERGESQHL(vec_short8) -VSX_IMPL_MERGESQHL(vec_uint4) -VSX_IMPL_MERGESQHL(vec_int4) -VSX_IMPL_MERGESQHL(vec_float4) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqh, vec_mergeh) -VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesql, vec_mergel) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqh, vec_mergeh) -VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesql, vec_mergel) -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqh, vec_mergeh) -VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesql, vec_mergel) - - -// 2 and 4 channels interleave for all types except 2 lanes -#define VSX_IMPL_ST_INTERLEAVE(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ -{ \ - vsx_stf(vec_mergeh(a, b), 0, ptr); \ - vsx_stf(vec_mergel(a, b), 16, ptr); \ -} \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, const Tvec& d, Tp* ptr) \ -{ \ - Tvec ac = vec_mergeh(a, c); \ - Tvec bd = vec_mergeh(b, d); \ - vsx_stf(vec_mergeh(ac, bd), 0, ptr); \ - vsx_stf(vec_mergel(ac, bd), 16, ptr); \ - ac = vec_mergel(a, c); \ - bd = vec_mergel(b, d); \ - vsx_stf(vec_mergeh(ac, bd), 32, ptr); \ - vsx_stf(vec_mergel(ac, bd), 48, ptr); \ -} -VSX_IMPL_ST_INTERLEAVE(uchar, vec_uchar16) -VSX_IMPL_ST_INTERLEAVE(schar, vec_char16) -VSX_IMPL_ST_INTERLEAVE(ushort, vec_ushort8) -VSX_IMPL_ST_INTERLEAVE(short, vec_short8) -VSX_IMPL_ST_INTERLEAVE(uint, vec_uint4) -VSX_IMPL_ST_INTERLEAVE(int, vec_int4) -VSX_IMPL_ST_INTERLEAVE(float, vec_float4) - -// 2 and 4 channels deinterleave for 16 lanes -#define VSX_IMPL_ST_DINTERLEAVE_8(Tp, Tvec) \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(16, ptr); \ - a = vec_mergesqe(v0, v1); \ - b = vec_mergesqo(v0, v1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(16, ptr); \ - Tvec v2 = vsx_ld(32, ptr); \ - Tvec v3 = vsx_ld(48, ptr); \ - Tvec m0 = vec_mergesqe(v0, v1); \ - Tvec m1 = vec_mergesqe(v2, v3); \ - a = vec_mergesqe(m0, m1); \ - c = vec_mergesqo(m0, m1); \ - m0 = vec_mergesqo(v0, v1); \ - m1 = vec_mergesqo(v2, v3); \ - b = vec_mergesqe(m0, m1); \ - d = vec_mergesqo(m0, m1); \ -} -VSX_IMPL_ST_DINTERLEAVE_8(uchar, vec_uchar16) -VSX_IMPL_ST_DINTERLEAVE_8(schar, vec_char16) - -// 2 and 4 channels deinterleave for 8 lanes -#define VSX_IMPL_ST_DINTERLEAVE_16(Tp, Tvec) \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(8, ptr); \ - a = vec_mergesqe(v0, v1); \ - b = vec_mergesqo(v0, v1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(8, ptr); \ - Tvec m0 = vec_mergeh(v0, v1); \ - Tvec m1 = vec_mergel(v0, v1); \ - Tvec ab0 = vec_mergeh(m0, m1); \ - Tvec cd0 = vec_mergel(m0, m1); \ - v0 = vsx_ld(16, ptr); \ - v1 = vsx_ld(24, ptr); \ - m0 = vec_mergeh(v0, v1); \ - m1 = vec_mergel(v0, v1); \ - Tvec ab1 = vec_mergeh(m0, m1); \ - Tvec cd1 = vec_mergel(m0, m1); \ - a = vec_mergesqh(ab0, ab1); \ - b = vec_mergesql(ab0, ab1); \ - c = vec_mergesqh(cd0, cd1); \ - d = vec_mergesql(cd0, cd1); \ -} -VSX_IMPL_ST_DINTERLEAVE_16(ushort, vec_ushort8) -VSX_IMPL_ST_DINTERLEAVE_16(short, vec_short8) - -// 2 and 4 channels deinterleave for 4 lanes -#define VSX_IMPL_ST_DINTERLEAVE_32(Tp, Tvec) \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - a = vsx_ld(0, ptr); \ - b = vsx_ld(4, ptr); \ - Tvec m0 = vec_mergeh(a, b); \ - Tvec m1 = vec_mergel(a, b); \ - a = vec_mergeh(m0, m1); \ - b = vec_mergel(m0, m1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = vsx_ld(0, ptr); \ - Tvec v1 = vsx_ld(4, ptr); \ - Tvec v2 = vsx_ld(8, ptr); \ - Tvec v3 = vsx_ld(12, ptr); \ - Tvec m0 = vec_mergeh(v0, v2); \ - Tvec m1 = vec_mergeh(v1, v3); \ - a = vec_mergeh(m0, m1); \ - b = vec_mergel(m0, m1); \ - m0 = vec_mergel(v0, v2); \ - m1 = vec_mergel(v1, v3); \ - c = vec_mergeh(m0, m1); \ - d = vec_mergel(m0, m1); \ -} -VSX_IMPL_ST_DINTERLEAVE_32(uint, vec_uint4) -VSX_IMPL_ST_DINTERLEAVE_32(int, vec_int4) -VSX_IMPL_ST_DINTERLEAVE_32(float, vec_float4) - -// 2 and 4 channels interleave and deinterleave for 2 lanes -#define VSX_IMPL_ST_D_INTERLEAVE_64(Tp, Tvec, ld_func, st_func) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ -{ \ - st_func(vec_mergeh(a, b), 0, ptr); \ - st_func(vec_mergel(a, b), 2, ptr); \ -} \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, const Tvec& d, Tp* ptr) \ -{ \ - st_func(vec_mergeh(a, b), 0, ptr); \ - st_func(vec_mergeh(c, d), 2, ptr); \ - st_func(vec_mergel(a, b), 4, ptr); \ - st_func(vec_mergel(c, d), 6, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ -{ \ - Tvec m0 = ld_func(0, ptr); \ - Tvec m1 = ld_func(2, ptr); \ - a = vec_mergeh(m0, m1); \ - b = vec_mergel(m0, m1); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ - Tvec& c, Tvec& d) \ -{ \ - Tvec v0 = ld_func(0, ptr); \ - Tvec v1 = ld_func(2, ptr); \ - Tvec v2 = ld_func(4, ptr); \ - Tvec v3 = ld_func(6, ptr); \ - a = vec_mergeh(v0, v2); \ - b = vec_mergel(v0, v2); \ - c = vec_mergeh(v1, v3); \ - d = vec_mergel(v1, v3); \ -} -VSX_IMPL_ST_D_INTERLEAVE_64(int64, vec_dword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_D_INTERLEAVE_64(uint64, vec_udword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_D_INTERLEAVE_64(double, vec_double2, vsx_ld, vsx_st) - -/* 3 channels */ -#define VSX_IMPL_ST_INTERLEAVE_3CH_16(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - static const vec_uchar16 a12 = {0, 16, 0, 1, 17, 0, 2, 18, 0, 3, 19, 0, 4, 20, 0, 5}; \ - static const vec_uchar16 a123 = {0, 1, 16, 3, 4, 17, 6, 7, 18, 9, 10, 19, 12, 13, 20, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ - static const vec_uchar16 b12 = {21, 0, 6, 22, 0, 7, 23, 0, 8, 24, 0, 9, 25, 0, 10, 26}; \ - static const vec_uchar16 b123 = {0, 21, 2, 3, 22, 5, 6, 23, 8, 9, 24, 11, 12, 25, 14, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 16, ptr); \ - static const vec_uchar16 c12 = {0, 11, 27, 0, 12, 28, 0, 13, 29, 0, 14, 30, 0, 15, 31, 0}; \ - static const vec_uchar16 c123 = {26, 1, 2, 27, 4, 5, 28, 7, 8, 29, 10, 11, 30, 13, 14, 31}; \ - vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 32, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = vsx_ld(0, ptr); \ - Tvec v2 = vsx_ld(16, ptr); \ - Tvec v3 = vsx_ld(32, ptr); \ - static const vec_uchar16 a12_perm = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 20, 23, 26, 29}; \ - a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ - static const vec_uchar16 b12_perm = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 21, 24, 27, 30}; \ - b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ - static const vec_uchar16 c12_perm = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 0, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 19, 22, 25, 28, 31}; \ - c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_16(uchar, vec_uchar16) -VSX_IMPL_ST_INTERLEAVE_3CH_16(schar, vec_char16) - -#define VSX_IMPL_ST_INTERLEAVE_3CH_8(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - static const vec_uchar16 a12 = {0, 1, 16, 17, 0, 0, 2, 3, 18, 19, 0, 0, 4, 5, 20, 21}; \ - static const vec_uchar16 a123 = {0, 1, 2, 3, 16, 17, 6, 7, 8, 9, 18, 19, 12, 13, 14, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ - static const vec_uchar16 b12 = {0, 0, 6, 7, 22, 23, 0, 0, 8, 9, 24, 25, 0, 0, 10, 11}; \ - static const vec_uchar16 b123 = {20, 21, 2, 3, 4, 5, 22, 23, 8, 9, 10, 11, 24, 25, 14, 15}; \ - vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 8, ptr); \ - static const vec_uchar16 c12 = {26, 27, 0, 0, 12, 13, 28, 29, 0, 0, 14, 15, 30, 31, 0, 0}; \ - static const vec_uchar16 c123 = {0, 1, 26, 27, 4, 5, 6, 7, 28, 29, 10, 11, 12, 13, 30, 31}; \ - vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 16, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = vsx_ld(0, ptr); \ - Tvec v2 = vsx_ld(8, ptr); \ - Tvec v3 = vsx_ld(16, ptr); \ - static const vec_uchar16 a12_perm = {0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31, 0, 0, 0, 0}; \ - static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 26, 27}; \ - a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ - static const vec_uchar16 b12_perm = {2, 3, 8, 9, 14, 15, 20, 21, 26, 27, 0, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 22, 23, 28, 29}; \ - b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ - static const vec_uchar16 c12_perm = {4, 5, 10, 11, 16, 17, 22, 23, 28, 29, 0, 0, 0, 0, 0, 0}; \ - static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 24, 25, 30, 31}; \ - c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_8(ushort, vec_ushort8) -VSX_IMPL_ST_INTERLEAVE_3CH_8(short, vec_short8) - -#define VSX_IMPL_ST_INTERLEAVE_3CH_4(Tp, Tvec) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - Tvec hbc = vec_mergeh(b, c); \ - static const vec_uchar16 ahbc = {0, 1, 2, 3, 16, 17, 18, 19, 20, 21, 22, 23, 4, 5, 6, 7}; \ - vsx_st(vec_perm(a, hbc, ahbc), 0, ptr); \ - Tvec lab = vec_mergel(a, b); \ - vsx_st(vec_sld(lab, hbc, 8), 4, ptr); \ - static const vec_uchar16 clab = {8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 12, 13, 14, 15};\ - vsx_st(vec_perm(c, lab, clab), 8, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = vsx_ld(0, ptr); \ - Tvec v2 = vsx_ld(4, ptr); \ - Tvec v3 = vsx_ld(8, ptr); \ - static const vec_uchar16 flp = {0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31}; \ - a = vec_perm(v1, vec_sld(v3, v2, 8), flp); \ - static const vec_uchar16 flp2 = {28, 29, 30, 31, 0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19}; \ - b = vec_perm(v2, vec_sld(v1, v3, 8), flp2); \ - c = vec_perm(vec_sld(v2, v1, 8), v3, flp); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_4(uint, vec_uint4) -VSX_IMPL_ST_INTERLEAVE_3CH_4(int, vec_int4) -VSX_IMPL_ST_INTERLEAVE_3CH_4(float, vec_float4) - -#define VSX_IMPL_ST_INTERLEAVE_3CH_2(Tp, Tvec, ld_func, st_func) \ -VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ - const Tvec& c, Tp* ptr) \ -{ \ - st_func(vec_mergeh(a, b), 0, ptr); \ - st_func(vec_permi(c, a, 1), 2, ptr); \ - st_func(vec_mergel(b, c), 4, ptr); \ -} \ -VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, \ - Tvec& b, Tvec& c) \ -{ \ - Tvec v1 = ld_func(0, ptr); \ - Tvec v2 = ld_func(2, ptr); \ - Tvec v3 = ld_func(4, ptr); \ - a = vec_permi(v1, v2, 1); \ - b = vec_permi(v1, v3, 2); \ - c = vec_permi(v2, v3, 1); \ -} -VSX_IMPL_ST_INTERLEAVE_3CH_2(int64, vec_dword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_INTERLEAVE_3CH_2(uint64, vec_udword2, vsx_ld2, vsx_st2) -VSX_IMPL_ST_INTERLEAVE_3CH_2(double, vec_double2, vsx_ld, vsx_st) - -#endif // CV_VSX - -//! @} - -#endif // OPENCV_HAL_VSX_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_HAL_VSX_UTILS_HPP +#define OPENCV_HAL_VSX_UTILS_HPP + +#include "opencv2/core/cvdef.h" + +#ifndef SKIP_INCLUDES +# include +#endif + +//! @addtogroup core_utils_vsx +//! @{ +#if CV_VSX + +#define __VSX_S16__(c, v) (c){v, v, v, v, v, v, v, v, v, v, v, v, v, v, v, v} +#define __VSX_S8__(c, v) (c){v, v, v, v, v, v, v, v} +#define __VSX_S4__(c, v) (c){v, v, v, v} +#define __VSX_S2__(c, v) (c){v, v} + +typedef __vector unsigned char vec_uchar16; +#define vec_uchar16_set(...) (vec_uchar16){__VA_ARGS__} +#define vec_uchar16_sp(c) (__VSX_S16__(vec_uchar16, (unsigned char)c)) +#define vec_uchar16_c(v) ((vec_uchar16)(v)) +#define vec_uchar16_z vec_uchar16_sp(0) + +typedef __vector signed char vec_char16; +#define vec_char16_set(...) (vec_char16){__VA_ARGS__} +#define vec_char16_sp(c) (__VSX_S16__(vec_char16, (signed char)c)) +#define vec_char16_c(v) ((vec_char16)(v)) +#define vec_char16_z vec_char16_sp(0) + +typedef __vector unsigned short vec_ushort8; +#define vec_ushort8_set(...) (vec_ushort8){__VA_ARGS__} +#define vec_ushort8_sp(c) (__VSX_S8__(vec_ushort8, (unsigned short)c)) +#define vec_ushort8_c(v) ((vec_ushort8)(v)) +#define vec_ushort8_z vec_ushort8_sp(0) + +typedef __vector signed short vec_short8; +#define vec_short8_set(...) (vec_short8){__VA_ARGS__} +#define vec_short8_sp(c) (__VSX_S8__(vec_short8, (signed short)c)) +#define vec_short8_c(v) ((vec_short8)(v)) +#define vec_short8_z vec_short8_sp(0) + +typedef __vector unsigned int vec_uint4; +#define vec_uint4_set(...) (vec_uint4){__VA_ARGS__} +#define vec_uint4_sp(c) (__VSX_S4__(vec_uint4, (unsigned int)c)) +#define vec_uint4_c(v) ((vec_uint4)(v)) +#define vec_uint4_z vec_uint4_sp(0) + +typedef __vector signed int vec_int4; +#define vec_int4_set(...) (vec_int4){__VA_ARGS__} +#define vec_int4_sp(c) (__VSX_S4__(vec_int4, (signed int)c)) +#define vec_int4_c(v) ((vec_int4)(v)) +#define vec_int4_z vec_int4_sp(0) + +typedef __vector float vec_float4; +#define vec_float4_set(...) (vec_float4){__VA_ARGS__} +#define vec_float4_sp(c) (__VSX_S4__(vec_float4, c)) +#define vec_float4_c(v) ((vec_float4)(v)) +#define vec_float4_z vec_float4_sp(0) + +typedef __vector unsigned long long vec_udword2; +#define vec_udword2_set(...) (vec_udword2){__VA_ARGS__} +#define vec_udword2_sp(c) (__VSX_S2__(vec_udword2, (unsigned long long)c)) +#define vec_udword2_c(v) ((vec_udword2)(v)) +#define vec_udword2_z vec_udword2_sp(0) + +typedef __vector signed long long vec_dword2; +#define vec_dword2_set(...) (vec_dword2){__VA_ARGS__} +#define vec_dword2_sp(c) (__VSX_S2__(vec_dword2, (signed long long)c)) +#define vec_dword2_c(v) ((vec_dword2)(v)) +#define vec_dword2_z vec_dword2_sp(0) + +typedef __vector double vec_double2; +#define vec_double2_set(...) (vec_double2){__VA_ARGS__} +#define vec_double2_c(v) ((vec_double2)(v)) +#define vec_double2_sp(c) (__VSX_S2__(vec_double2, c)) +#define vec_double2_z vec_double2_sp(0) + +#define vec_bchar16 __vector __bool char +#define vec_bchar16_set(...) (vec_bchar16){__VA_ARGS__} +#define vec_bchar16_c(v) ((vec_bchar16)(v)) + +#define vec_bshort8 __vector __bool short +#define vec_bshort8_set(...) (vec_bshort8){__VA_ARGS__} +#define vec_bshort8_c(v) ((vec_bshort8)(v)) + +#define vec_bint4 __vector __bool int +#define vec_bint4_set(...) (vec_bint4){__VA_ARGS__} +#define vec_bint4_c(v) ((vec_bint4)(v)) + +#define vec_bdword2 __vector __bool long long +#define vec_bdword2_set(...) (vec_bdword2){__VA_ARGS__} +#define vec_bdword2_c(v) ((vec_bdword2)(v)) + +#define VSX_FINLINE(tp) extern inline tp __attribute__((always_inline)) + +#define VSX_REDIRECT_1RG(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) { return fn2(a); } + +#define VSX_REDIRECT_2RG(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a, const rg& b) { return fn2(a, b); } + +/* + * GCC VSX compatibility +**/ +#if defined(__GNUG__) && !defined(__clang__) + +// inline asm helper +#define VSX_IMPL_1RG(rt, rg, opc, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ rt rs; __asm__ __volatile__(#opc" %x0,%x1" : "=wa" (rs) : "wa" (a)); return rs; } + +#define VSX_IMPL_1VRG(rt, rg, opc, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ rt rs; __asm__ __volatile__(#opc" %0,%1" : "=v" (rs) : "v" (a)); return rs; } + +#define VSX_IMPL_2VRG_F(rt, rg, fopc, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a, const rg& b) \ +{ rt rs; __asm__ __volatile__(fopc : "=v" (rs) : "v" (a), "v" (b)); return rs; } + +#define VSX_IMPL_2VRG(rt, rg, opc, fnm) VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%1,%2", fnm) + +#if __GNUG__ < 8 + + // Support for int4 -> dword2 expanding multiply was added in GCC 8. + #ifdef vec_mule + #undef vec_mule + #endif + #ifdef vec_mulo + #undef vec_mulo + #endif + + VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mule, __builtin_vec_mule) + VSX_REDIRECT_2RG(vec_ushort8, vec_uchar16, vec_mulo, __builtin_vec_mulo) + VSX_REDIRECT_2RG(vec_short8, vec_char16, vec_mulo, __builtin_vec_mulo) + VSX_REDIRECT_2RG(vec_int4, vec_short8, vec_mulo, __builtin_vec_mulo) + VSX_REDIRECT_2RG(vec_uint4, vec_ushort8, vec_mulo, __builtin_vec_mulo) + + // dword2 support arrived in ISA 2.07 and GCC 8+ + VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulosw, vec_mule) + VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmulouw, vec_mule) + VSX_IMPL_2VRG(vec_dword2, vec_int4, vmulesw, vec_mulo) + VSX_IMPL_2VRG(vec_udword2, vec_uint4, vmuleuw, vec_mulo) + +#endif + +#if __GNUG__ < 7 +// up to GCC 6 vec_mul only supports precisions and llong +# ifdef vec_mul +# undef vec_mul +# endif +/* + * there's no a direct instruction for supporting 8-bit, 16-bit multiplication in ISA 2.07, + * XLC Implement it by using instruction "multiply even", "multiply odd" and "permute" +**/ +# define VSX_IMPL_MULH(Tvec, cperm) \ + VSX_FINLINE(Tvec) vec_mul(const Tvec& a, const Tvec& b) \ + { \ + static const vec_uchar16 ev_od = {cperm}; \ + return vec_perm((Tvec)vec_mule(a, b), (Tvec)vec_mulo(a, b), ev_od); \ + } + #define VSX_IMPL_MULH_P16 0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30 + VSX_IMPL_MULH(vec_char16, VSX_IMPL_MULH_P16) + VSX_IMPL_MULH(vec_uchar16, VSX_IMPL_MULH_P16) + #define VSX_IMPL_MULH_P8 0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29 + VSX_IMPL_MULH(vec_short8, VSX_IMPL_MULH_P8) + VSX_IMPL_MULH(vec_ushort8, VSX_IMPL_MULH_P8) + // vmuluwm can be used for unsigned or signed integers, that's what they said + VSX_IMPL_2VRG(vec_int4, vec_int4, vmuluwm, vec_mul) + VSX_IMPL_2VRG(vec_uint4, vec_uint4, vmuluwm, vec_mul) + // redirect to GCC builtin vec_mul, since it already supports precisions and llong + VSX_REDIRECT_2RG(vec_float4, vec_float4, vec_mul, __builtin_vec_mul) + VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mul, __builtin_vec_mul) + VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mul, __builtin_vec_mul) + VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mul, __builtin_vec_mul) +#endif // __GNUG__ < 7 + +#if __GNUG__ < 6 +/* + * Instruction "compare greater than or equal" in ISA 2.07 only supports single + * and double precision. + * In XLC and new versions of GCC implement integers by using instruction "greater than" and NOR. +**/ +# ifdef vec_cmpge +# undef vec_cmpge +# endif +# ifdef vec_cmple +# undef vec_cmple +# endif +# define vec_cmple(a, b) vec_cmpge(b, a) +# define VSX_IMPL_CMPGE(rt, rg, opc, fnm) \ + VSX_IMPL_2VRG_F(rt, rg, #opc" %0,%2,%1\n\t xxlnor %x0,%x0,%x0", fnm) + + VSX_IMPL_CMPGE(vec_bchar16, vec_char16, vcmpgtsb, vec_cmpge) + VSX_IMPL_CMPGE(vec_bchar16, vec_uchar16, vcmpgtub, vec_cmpge) + VSX_IMPL_CMPGE(vec_bshort8, vec_short8, vcmpgtsh, vec_cmpge) + VSX_IMPL_CMPGE(vec_bshort8, vec_ushort8, vcmpgtuh, vec_cmpge) + VSX_IMPL_CMPGE(vec_bint4, vec_int4, vcmpgtsw, vec_cmpge) + VSX_IMPL_CMPGE(vec_bint4, vec_uint4, vcmpgtuw, vec_cmpge) + VSX_IMPL_CMPGE(vec_bdword2, vec_dword2, vcmpgtsd, vec_cmpge) + VSX_IMPL_CMPGE(vec_bdword2, vec_udword2, vcmpgtud, vec_cmpge) + +// redirect to GCC builtin cmpge, since it already supports precisions + VSX_REDIRECT_2RG(vec_bint4, vec_float4, vec_cmpge, __builtin_vec_cmpge) + VSX_REDIRECT_2RG(vec_bdword2, vec_double2, vec_cmpge, __builtin_vec_cmpge) + +// up to gcc5 vec_nor doesn't support bool long long +# undef vec_nor + template + VSX_REDIRECT_2RG(T, T, vec_nor, __builtin_vec_nor) + + VSX_FINLINE(vec_bdword2) vec_nor(const vec_bdword2& a, const vec_bdword2& b) + { return vec_bdword2_c(__builtin_vec_nor(vec_dword2_c(a), vec_dword2_c(b))); } + +// vec_packs doesn't support double words in gcc4 and old versions of gcc5 +# undef vec_packs + VSX_REDIRECT_2RG(vec_char16, vec_short8, vec_packs, __builtin_vec_packs) + VSX_REDIRECT_2RG(vec_uchar16, vec_ushort8, vec_packs, __builtin_vec_packs) + VSX_REDIRECT_2RG(vec_short8, vec_int4, vec_packs, __builtin_vec_packs) + VSX_REDIRECT_2RG(vec_ushort8, vec_uint4, vec_packs, __builtin_vec_packs) + + VSX_IMPL_2VRG_F(vec_int4, vec_dword2, "vpksdss %0,%2,%1", vec_packs) + VSX_IMPL_2VRG_F(vec_uint4, vec_udword2, "vpkudus %0,%2,%1", vec_packs) +#endif // __GNUG__ < 6 + +#if __GNUG__ < 5 +// vec_xxpermdi in gcc4 missing little-endian supports just like clang +# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) +// same as vec_xxpermdi +# undef vec_vbpermq + VSX_IMPL_2VRG(vec_udword2, vec_uchar16, vbpermq, vec_vbpermq) + VSX_IMPL_2VRG(vec_dword2, vec_char16, vbpermq, vec_vbpermq) +#else +# define vec_permi vec_xxpermdi +#endif // __GNUG__ < 5 + +// shift left double by word immediate +#ifndef vec_sldw +# define vec_sldw __builtin_vsx_xxsldwi +#endif + +// vector population count +VSX_IMPL_1VRG(vec_uchar16, vec_uchar16, vpopcntb, vec_popcntu) +VSX_IMPL_1VRG(vec_uchar16, vec_char16, vpopcntb, vec_popcntu) +VSX_IMPL_1VRG(vec_ushort8, vec_ushort8, vpopcnth, vec_popcntu) +VSX_IMPL_1VRG(vec_ushort8, vec_short8, vpopcnth, vec_popcntu) +VSX_IMPL_1VRG(vec_uint4, vec_uint4, vpopcntw, vec_popcntu) +VSX_IMPL_1VRG(vec_uint4, vec_int4, vpopcntw, vec_popcntu) +VSX_IMPL_1VRG(vec_udword2, vec_udword2, vpopcntd, vec_popcntu) +VSX_IMPL_1VRG(vec_udword2, vec_dword2, vpopcntd, vec_popcntu) + +// converts between single and double-precision +VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) +VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) + +// converts word and doubleword to double-precision +#undef vec_ctd +VSX_IMPL_1RG(vec_double2, vec_int4, xvcvsxwdp, vec_ctdo) +VSX_IMPL_1RG(vec_double2, vec_uint4, xvcvuxwdp, vec_ctdo) +VSX_IMPL_1RG(vec_double2, vec_dword2, xvcvsxddp, vec_ctd) +VSX_IMPL_1RG(vec_double2, vec_udword2, xvcvuxddp, vec_ctd) + +// converts word and doubleword to single-precision +#undef vec_ctf +VSX_IMPL_1RG(vec_float4, vec_int4, xvcvsxwsp, vec_ctf) +VSX_IMPL_1RG(vec_float4, vec_uint4, xvcvuxwsp, vec_ctf) +VSX_IMPL_1RG(vec_float4, vec_dword2, xvcvsxdsp, vec_ctfo) +VSX_IMPL_1RG(vec_float4, vec_udword2, xvcvuxdsp, vec_ctfo) + +// converts single and double precision to signed word +#undef vec_cts +VSX_IMPL_1RG(vec_int4, vec_double2, xvcvdpsxws, vec_ctso) +VSX_IMPL_1RG(vec_int4, vec_float4, xvcvspsxws, vec_cts) + +// converts single and double precision to unsigned word +#undef vec_ctu +VSX_IMPL_1RG(vec_uint4, vec_double2, xvcvdpuxws, vec_ctuo) +VSX_IMPL_1RG(vec_uint4, vec_float4, xvcvspuxws, vec_ctu) + +// converts single and double precision to signed doubleword +#undef vec_ctsl +VSX_IMPL_1RG(vec_dword2, vec_double2, xvcvdpsxds, vec_ctsl) +VSX_IMPL_1RG(vec_dword2, vec_float4, xvcvspsxds, vec_ctslo) + +// converts single and double precision to unsigned doubleword +#undef vec_ctul +VSX_IMPL_1RG(vec_udword2, vec_double2, xvcvdpuxds, vec_ctul) +VSX_IMPL_1RG(vec_udword2, vec_float4, xvcvspuxds, vec_ctulo) + +// just in case if GCC doesn't define it +#ifndef vec_xl +# define vec_xl vec_vsx_ld +# define vec_xst vec_vsx_st +#endif + +#endif // GCC VSX compatibility + +/* + * CLANG VSX compatibility +**/ +#if defined(__clang__) && !defined(__IBMCPP__) + +/* + * CLANG doesn't support %x in the inline asm template which fixes register number + * when using any of the register constraints wa, wd, wf + * + * For more explanation checkout PowerPC and IBM RS6000 in https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html + * Also there's already an open bug https://bugs.llvm.org/show_bug.cgi?id=31837 + * + * So we're not able to use inline asm and only use built-in functions that CLANG supports + * and use __builtin_convertvector if clang missing any of vector conversions built-in functions + * + * todo: clang asm template bug is fixed, need to reconsider the current workarounds. +*/ + +// convert vector helper +#define VSX_IMPL_CONVERT(rt, rg, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) { return __builtin_convertvector(a, rt); } + +#ifndef vec_permi +#if __clang_major__ < 5 +// implement vec_permi in a dirty way +# define VSX_IMPL_CLANG_4_PERMI(Tvec) \ + VSX_FINLINE(Tvec) vec_permi(const Tvec& a, const Tvec& b, unsigned const char c) \ + { \ + switch (c) \ + { \ + case 0: \ + return vec_mergeh(a, b); \ + case 1: \ + return vec_mergel(vec_mergeh(a, a), b); \ + case 2: \ + return vec_mergeh(vec_mergel(a, a), b); \ + default: \ + return vec_mergel(a, b); \ + } \ + } + VSX_IMPL_CLANG_4_PERMI(vec_udword2) + VSX_IMPL_CLANG_4_PERMI(vec_dword2) + VSX_IMPL_CLANG_4_PERMI(vec_double2) + +// vec_xxsldwi is missing in clang 4 +# define vec_xxsldwi(a, b, c) vec_sld(a, b, (c) * 4) +#else +// vec_xxpermdi is missing little-endian supports in clang 4 just like gcc4 +# define vec_permi(a, b, c) vec_xxpermdi(b, a, (3 ^ (((c) & 1) << 1 | (c) >> 1))) +#endif // __clang_major__ < 5 +#endif + +// shift left double by word immediate +#ifndef vec_sldw +# define vec_sldw vec_xxsldwi +#endif + +#if __clang_major__ < 13 +// Implement vec_rsqrt since clang only supports vec_rsqrte +#ifndef vec_rsqrt + VSX_FINLINE(vec_float4) vec_rsqrt(const vec_float4& a) + { return vec_div(vec_float4_sp(1), vec_sqrt(a)); } + + VSX_FINLINE(vec_double2) vec_rsqrt(const vec_double2& a) + { return vec_div(vec_double2_sp(1), vec_sqrt(a)); } +#endif + +// vec_promote missing support for doubleword +VSX_FINLINE(vec_dword2) vec_promote(long long a, int b) +{ + vec_dword2 ret = vec_dword2_z; + ret[b & 1] = a; + return ret; +} + +VSX_FINLINE(vec_udword2) vec_promote(unsigned long long a, int b) +{ + vec_udword2 ret = vec_udword2_z; + ret[b & 1] = a; + return ret; +} +#endif + +// vec_popcnt should return unsigned but clang has different thought just like gcc in vec_vpopcnt +#define VSX_IMPL_POPCNTU(Tvec, Tvec2, ucast) \ +VSX_FINLINE(Tvec) vec_popcntu(const Tvec2& a) \ +{ return ucast(vec_popcnt(a)); } +VSX_IMPL_POPCNTU(vec_uchar16, vec_char16, vec_uchar16_c); +VSX_IMPL_POPCNTU(vec_ushort8, vec_short8, vec_ushort8_c); +VSX_IMPL_POPCNTU(vec_uint4, vec_int4, vec_uint4_c); +VSX_IMPL_POPCNTU(vec_udword2, vec_dword2, vec_udword2_c); +// redirect unsigned types +VSX_REDIRECT_1RG(vec_uchar16, vec_uchar16, vec_popcntu, vec_popcnt) +VSX_REDIRECT_1RG(vec_ushort8, vec_ushort8, vec_popcntu, vec_popcnt) +VSX_REDIRECT_1RG(vec_uint4, vec_uint4, vec_popcntu, vec_popcnt) +VSX_REDIRECT_1RG(vec_udword2, vec_udword2, vec_popcntu, vec_popcnt) + +// converts between single and double precision +VSX_REDIRECT_1RG(vec_float4, vec_double2, vec_cvfo, __builtin_vsx_xvcvdpsp) +VSX_REDIRECT_1RG(vec_double2, vec_float4, vec_cvfo, __builtin_vsx_xvcvspdp) + +// converts word and doubleword to double-precision +#ifdef vec_ctd +# undef vec_ctd +#endif +VSX_REDIRECT_1RG(vec_double2, vec_int4, vec_ctdo, __builtin_vsx_xvcvsxwdp) +VSX_REDIRECT_1RG(vec_double2, vec_uint4, vec_ctdo, __builtin_vsx_xvcvuxwdp) + +VSX_IMPL_CONVERT(vec_double2, vec_dword2, vec_ctd) +VSX_IMPL_CONVERT(vec_double2, vec_udword2, vec_ctd) + +// converts word and doubleword to single-precision +#if __clang_major__ > 4 +# undef vec_ctf +#endif +VSX_IMPL_CONVERT(vec_float4, vec_int4, vec_ctf) +VSX_IMPL_CONVERT(vec_float4, vec_uint4, vec_ctf) +VSX_REDIRECT_1RG(vec_float4, vec_dword2, vec_ctfo, __builtin_vsx_xvcvsxdsp) +VSX_REDIRECT_1RG(vec_float4, vec_udword2, vec_ctfo, __builtin_vsx_xvcvuxdsp) + +// converts single and double precision to signed word +#if __clang_major__ > 4 +# undef vec_cts +#endif +VSX_REDIRECT_1RG(vec_int4, vec_double2, vec_ctso, __builtin_vsx_xvcvdpsxws) +VSX_IMPL_CONVERT(vec_int4, vec_float4, vec_cts) + +// converts single and double precision to unsigned word +#if __clang_major__ > 4 +# undef vec_ctu +#endif +VSX_REDIRECT_1RG(vec_uint4, vec_double2, vec_ctuo, __builtin_vsx_xvcvdpuxws) +VSX_IMPL_CONVERT(vec_uint4, vec_float4, vec_ctu) + +// converts single and double precision to signed doubleword +#ifdef vec_ctsl +# undef vec_ctsl +#endif +VSX_IMPL_CONVERT(vec_dword2, vec_double2, vec_ctsl) +// __builtin_convertvector unable to convert, xvcvspsxds is missing on it +VSX_FINLINE(vec_dword2) vec_ctslo(const vec_float4& a) +{ return vec_ctsl(vec_cvfo(a)); } + +// converts single and double precision to unsigned doubleword +#ifdef vec_ctul +# undef vec_ctul +#endif +VSX_IMPL_CONVERT(vec_udword2, vec_double2, vec_ctul) +// __builtin_convertvector unable to convert, xvcvspuxds is missing on it +VSX_FINLINE(vec_udword2) vec_ctulo(const vec_float4& a) +{ return vec_ctul(vec_cvfo(a)); } + +#endif // CLANG VSX compatibility + +/* + * Common GCC, CLANG compatibility +**/ +#if defined(__GNUG__) && !defined(__IBMCPP__) + +#ifdef vec_cvf +# undef vec_cvf +#endif + +#define VSX_IMPL_CONV_EVEN_4_2(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ return fn2(vec_sldw(a, a, 1)); } + +VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_float4, vec_cvf, vec_cvfo) +VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_int4, vec_ctd, vec_ctdo) +VSX_IMPL_CONV_EVEN_4_2(vec_double2, vec_uint4, vec_ctd, vec_ctdo) + +VSX_IMPL_CONV_EVEN_4_2(vec_dword2, vec_float4, vec_ctsl, vec_ctslo) +VSX_IMPL_CONV_EVEN_4_2(vec_udword2, vec_float4, vec_ctul, vec_ctulo) + +#define VSX_IMPL_CONV_EVEN_2_4(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ \ + rt v4 = fn2(a); \ + return vec_sldw(v4, v4, 3); \ +} + +VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_double2, vec_cvf, vec_cvfo) +VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_dword2, vec_ctf, vec_ctfo) +VSX_IMPL_CONV_EVEN_2_4(vec_float4, vec_udword2, vec_ctf, vec_ctfo) + +VSX_IMPL_CONV_EVEN_2_4(vec_int4, vec_double2, vec_cts, vec_ctso) +VSX_IMPL_CONV_EVEN_2_4(vec_uint4, vec_double2, vec_ctu, vec_ctuo) + +// Only for Eigen! +/* + * changing behavior of conversion intrinsics for gcc has effect on Eigen + * so we redefine old behavior again only on gcc, clang +*/ +#if !defined(__clang__) || __clang_major__ > 4 + // ignoring second arg since Eigen only truncates toward zero +# define VSX_IMPL_CONV_2VARIANT(rt, rg, fnm, fn2) \ + VSX_FINLINE(rt) fnm(const rg& a, int only_truncate) \ + { \ + assert(only_truncate == 0); \ + CV_UNUSED(only_truncate); \ + return fn2(a); \ + } + VSX_IMPL_CONV_2VARIANT(vec_int4, vec_float4, vec_cts, vec_cts) + VSX_IMPL_CONV_2VARIANT(vec_uint4, vec_float4, vec_ctu, vec_ctu) + VSX_IMPL_CONV_2VARIANT(vec_float4, vec_int4, vec_ctf, vec_ctf) + VSX_IMPL_CONV_2VARIANT(vec_float4, vec_uint4, vec_ctf, vec_ctf) + // define vec_cts for converting double precision to signed doubleword + // which isn't compatible with xlc but its okay since Eigen only uses it for gcc + VSX_IMPL_CONV_2VARIANT(vec_dword2, vec_double2, vec_cts, vec_ctsl) +#endif // Eigen + +#endif // Common GCC, CLANG compatibility + +/* + * XLC VSX compatibility +**/ +#if defined(__IBMCPP__) + +// vector population count +#define vec_popcntu vec_popcnt + +// overload and redirect with setting second arg to zero +// since we only support conversions without the second arg +#define VSX_IMPL_OVERLOAD_Z2(rt, rg, fnm) \ +VSX_FINLINE(rt) fnm(const rg& a) { return fnm(a, 0); } + +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_int4, vec_ctd) +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_uint4, vec_ctd) +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_dword2, vec_ctd) +VSX_IMPL_OVERLOAD_Z2(vec_double2, vec_udword2, vec_ctd) + +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_int4, vec_ctf) +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_uint4, vec_ctf) +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_dword2, vec_ctf) +VSX_IMPL_OVERLOAD_Z2(vec_float4, vec_udword2, vec_ctf) + +VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_double2, vec_cts) +VSX_IMPL_OVERLOAD_Z2(vec_int4, vec_float4, vec_cts) + +VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_double2, vec_ctu) +VSX_IMPL_OVERLOAD_Z2(vec_uint4, vec_float4, vec_ctu) + +VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_double2, vec_ctsl) +VSX_IMPL_OVERLOAD_Z2(vec_dword2, vec_float4, vec_ctsl) + +VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_double2, vec_ctul) +VSX_IMPL_OVERLOAD_Z2(vec_udword2, vec_float4, vec_ctul) + +// fixme: implement conversions of odd-numbered elements in a dirty way +// since xlc doesn't support VSX registers operand in inline asm. +#define VSX_IMPL_CONV_ODD_4_2(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) { return fn2(vec_sldw(a, a, 3)); } + +VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_float4, vec_cvfo, vec_cvf) +VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_int4, vec_ctdo, vec_ctd) +VSX_IMPL_CONV_ODD_4_2(vec_double2, vec_uint4, vec_ctdo, vec_ctd) + +VSX_IMPL_CONV_ODD_4_2(vec_dword2, vec_float4, vec_ctslo, vec_ctsl) +VSX_IMPL_CONV_ODD_4_2(vec_udword2, vec_float4, vec_ctulo, vec_ctul) + +#define VSX_IMPL_CONV_ODD_2_4(rt, rg, fnm, fn2) \ +VSX_FINLINE(rt) fnm(const rg& a) \ +{ \ + rt v4 = fn2(a); \ + return vec_sldw(v4, v4, 1); \ +} + +VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_double2, vec_cvfo, vec_cvf) +VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_dword2, vec_ctfo, vec_ctf) +VSX_IMPL_CONV_ODD_2_4(vec_float4, vec_udword2, vec_ctfo, vec_ctf) + +VSX_IMPL_CONV_ODD_2_4(vec_int4, vec_double2, vec_ctso, vec_cts) +VSX_IMPL_CONV_ODD_2_4(vec_uint4, vec_double2, vec_ctuo, vec_ctu) + +#endif // XLC VSX compatibility + +// ignore GCC warning that caused by -Wunused-but-set-variable in rare cases +#if defined(__GNUG__) && !defined(__clang__) +# define VSX_UNUSED(Tvec) Tvec __attribute__((__unused__)) +#else // CLANG, XLC +# define VSX_UNUSED(Tvec) Tvec +#endif + +// gcc can find his way in casting log int and XLC, CLANG ambiguous +#if defined(__clang__) || defined(__IBMCPP__) + VSX_FINLINE(vec_udword2) vec_splats(uint64 v) + { return vec_splats((unsigned long long) v); } + + VSX_FINLINE(vec_dword2) vec_splats(int64 v) + { return vec_splats((long long) v); } + + VSX_FINLINE(vec_udword2) vec_promote(uint64 a, int b) + { return vec_promote((unsigned long long) a, b); } + + VSX_FINLINE(vec_dword2) vec_promote(int64 a, int b) + { return vec_promote((long long) a, b); } +#endif + +/* + * implement vsx_ld(offset, pointer), vsx_st(vector, offset, pointer) + * load and set using offset depend on the pointer type + * + * implement vsx_ldf(offset, pointer), vsx_stf(vector, offset, pointer) + * load and set using offset depend on fixed bytes size + * + * Note: In clang vec_xl and vec_xst fails to load unaligned addresses + * so we are using vec_vsx_ld, vec_vsx_st instead +*/ + +#if defined(__clang__) && !defined(__IBMCPP__) +# define vsx_ldf vec_vsx_ld +# define vsx_stf vec_vsx_st +#else // GCC , XLC +# define vsx_ldf vec_xl +# define vsx_stf vec_xst +#endif + +#define VSX_OFFSET(o, p) ((o) * sizeof(*(p))) +#define vsx_ld(o, p) vsx_ldf(VSX_OFFSET(o, p), p) +#define vsx_st(v, o, p) vsx_stf(v, VSX_OFFSET(o, p), p) + +/* + * implement vsx_ld2(offset, pointer), vsx_st2(vector, offset, pointer) to load and store double words + * In GCC vec_xl and vec_xst it maps to vec_vsx_ld, vec_vsx_st which doesn't support long long + * and in CLANG we are using vec_vsx_ld, vec_vsx_st because vec_xl, vec_xst fails to load unaligned addresses + * + * In XLC vec_xl and vec_xst fail to cast int64(long int) to long long +*/ +#if (defined(__GNUG__) || defined(__clang__)) && !defined(__IBMCPP__) + VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) + { return vec_udword2_c(vsx_ldf(VSX_OFFSET(o, p), (unsigned int*)p)); } + + VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) + { return vec_dword2_c(vsx_ldf(VSX_OFFSET(o, p), (int*)p)); } + + VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) + { vsx_stf(vec_uint4_c(vec), VSX_OFFSET(o, p), (unsigned int*)p); } + + VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) + { vsx_stf(vec_int4_c(vec), VSX_OFFSET(o, p), (int*)p); } +#else // XLC + VSX_FINLINE(vec_udword2) vsx_ld2(long o, const uint64* p) + { return vsx_ldf(VSX_OFFSET(o, p), (unsigned long long*)p); } + + VSX_FINLINE(vec_dword2) vsx_ld2(long o, const int64* p) + { return vsx_ldf(VSX_OFFSET(o, p), (long long*)p); } + + VSX_FINLINE(void) vsx_st2(const vec_udword2& vec, long o, uint64* p) + { vsx_stf(vec, VSX_OFFSET(o, p), (unsigned long long*)p); } + + VSX_FINLINE(void) vsx_st2(const vec_dword2& vec, long o, int64* p) + { vsx_stf(vec, VSX_OFFSET(o, p), (long long*)p); } +#endif + +// Store lower 8 byte +#define vec_st_l8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 0) + +// Store higher 8 byte +#define vec_st_h8(v, p) *((uint64*)(p)) = vec_extract(vec_udword2_c(v), 1) + +// Load 64-bits of integer data to lower part +#define VSX_IMPL_LOAD_L8(Tvec, Tp) \ +VSX_FINLINE(Tvec) vec_ld_l8(const Tp *p) \ +{ return ((Tvec)vec_promote(*((uint64*)p), 0)); } + +VSX_IMPL_LOAD_L8(vec_uchar16, uchar) +VSX_IMPL_LOAD_L8(vec_char16, schar) +VSX_IMPL_LOAD_L8(vec_ushort8, ushort) +VSX_IMPL_LOAD_L8(vec_short8, short) +VSX_IMPL_LOAD_L8(vec_uint4, uint) +VSX_IMPL_LOAD_L8(vec_int4, int) +VSX_IMPL_LOAD_L8(vec_float4, float) +VSX_IMPL_LOAD_L8(vec_udword2, uint64) +VSX_IMPL_LOAD_L8(vec_dword2, int64) +VSX_IMPL_LOAD_L8(vec_double2, double) + +// logical not +#define vec_not(a) vec_nor(a, a) + +// power9 yaya +// not equal +#ifndef vec_cmpne +# define vec_cmpne(a, b) vec_not(vec_cmpeq(a, b)) +#endif + +// absolute difference +#ifndef _ARCH_PWR9 +# undef vec_absd +# define vec_absd(a, b) vec_sub(vec_max(a, b), vec_min(a, b)) +#endif + +/* + * Implement vec_unpacklu and vec_unpackhu + * since vec_unpackl, vec_unpackh only support signed integers +**/ +#define VSX_IMPL_UNPACKU(rt, rg, zero) \ +VSX_FINLINE(rt) vec_unpacklu(const rg& a) \ +{ return (rt)(vec_mergel(a, zero)); } \ +VSX_FINLINE(rt) vec_unpackhu(const rg& a) \ +{ return (rt)(vec_mergeh(a, zero)); } + +VSX_IMPL_UNPACKU(vec_ushort8, vec_uchar16, vec_uchar16_z) +VSX_IMPL_UNPACKU(vec_uint4, vec_ushort8, vec_ushort8_z) +VSX_IMPL_UNPACKU(vec_udword2, vec_uint4, vec_uint4_z) + +/* + * Implement vec_mergesqe and vec_mergesqo + * Merges the sequence values of even and odd elements of two vectors +*/ +#define VSX_IMPL_PERM(rt, fnm, ...) \ +VSX_FINLINE(rt) fnm(const rt& a, const rt& b) \ +{ static const vec_uchar16 perm = {__VA_ARGS__}; return vec_perm(a, b, perm); } + +// 16 +#define perm16_mergesqe 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 +#define perm16_mergesqo 1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31 +VSX_IMPL_PERM(vec_uchar16, vec_mergesqe, perm16_mergesqe) +VSX_IMPL_PERM(vec_uchar16, vec_mergesqo, perm16_mergesqo) +VSX_IMPL_PERM(vec_char16, vec_mergesqe, perm16_mergesqe) +VSX_IMPL_PERM(vec_char16, vec_mergesqo, perm16_mergesqo) +// 8 +#define perm8_mergesqe 0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29 +#define perm8_mergesqo 2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31 +VSX_IMPL_PERM(vec_ushort8, vec_mergesqe, perm8_mergesqe) +VSX_IMPL_PERM(vec_ushort8, vec_mergesqo, perm8_mergesqo) +VSX_IMPL_PERM(vec_short8, vec_mergesqe, perm8_mergesqe) +VSX_IMPL_PERM(vec_short8, vec_mergesqo, perm8_mergesqo) +// 4 +#define perm4_mergesqe 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27 +#define perm4_mergesqo 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 +VSX_IMPL_PERM(vec_uint4, vec_mergesqe, perm4_mergesqe) +VSX_IMPL_PERM(vec_uint4, vec_mergesqo, perm4_mergesqo) +VSX_IMPL_PERM(vec_int4, vec_mergesqe, perm4_mergesqe) +VSX_IMPL_PERM(vec_int4, vec_mergesqo, perm4_mergesqo) +VSX_IMPL_PERM(vec_float4, vec_mergesqe, perm4_mergesqe) +VSX_IMPL_PERM(vec_float4, vec_mergesqo, perm4_mergesqo) +// 2 +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqe, vec_mergeh) +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqo, vec_mergel) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqe, vec_mergeh) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqo, vec_mergel) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqe, vec_mergeh) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqo, vec_mergel) + +/* + * Implement vec_mergesqh and vec_mergesql + * Merges the sequence most and least significant halves of two vectors +*/ +#define VSX_IMPL_MERGESQHL(Tvec) \ +VSX_FINLINE(Tvec) vec_mergesqh(const Tvec& a, const Tvec& b) \ +{ return (Tvec)vec_mergeh(vec_udword2_c(a), vec_udword2_c(b)); } \ +VSX_FINLINE(Tvec) vec_mergesql(const Tvec& a, const Tvec& b) \ +{ return (Tvec)vec_mergel(vec_udword2_c(a), vec_udword2_c(b)); } +VSX_IMPL_MERGESQHL(vec_uchar16) +VSX_IMPL_MERGESQHL(vec_char16) +VSX_IMPL_MERGESQHL(vec_ushort8) +VSX_IMPL_MERGESQHL(vec_short8) +VSX_IMPL_MERGESQHL(vec_uint4) +VSX_IMPL_MERGESQHL(vec_int4) +VSX_IMPL_MERGESQHL(vec_float4) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesqh, vec_mergeh) +VSX_REDIRECT_2RG(vec_udword2, vec_udword2, vec_mergesql, vec_mergel) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesqh, vec_mergeh) +VSX_REDIRECT_2RG(vec_dword2, vec_dword2, vec_mergesql, vec_mergel) +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesqh, vec_mergeh) +VSX_REDIRECT_2RG(vec_double2, vec_double2, vec_mergesql, vec_mergel) + + +// 2 and 4 channels interleave for all types except 2 lanes +#define VSX_IMPL_ST_INTERLEAVE(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ +{ \ + vsx_stf(vec_mergeh(a, b), 0, ptr); \ + vsx_stf(vec_mergel(a, b), 16, ptr); \ +} \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, const Tvec& d, Tp* ptr) \ +{ \ + Tvec ac = vec_mergeh(a, c); \ + Tvec bd = vec_mergeh(b, d); \ + vsx_stf(vec_mergeh(ac, bd), 0, ptr); \ + vsx_stf(vec_mergel(ac, bd), 16, ptr); \ + ac = vec_mergel(a, c); \ + bd = vec_mergel(b, d); \ + vsx_stf(vec_mergeh(ac, bd), 32, ptr); \ + vsx_stf(vec_mergel(ac, bd), 48, ptr); \ +} +VSX_IMPL_ST_INTERLEAVE(uchar, vec_uchar16) +VSX_IMPL_ST_INTERLEAVE(schar, vec_char16) +VSX_IMPL_ST_INTERLEAVE(ushort, vec_ushort8) +VSX_IMPL_ST_INTERLEAVE(short, vec_short8) +VSX_IMPL_ST_INTERLEAVE(uint, vec_uint4) +VSX_IMPL_ST_INTERLEAVE(int, vec_int4) +VSX_IMPL_ST_INTERLEAVE(float, vec_float4) + +// 2 and 4 channels deinterleave for 16 lanes +#define VSX_IMPL_ST_DINTERLEAVE_8(Tp, Tvec) \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(16, ptr); \ + a = vec_mergesqe(v0, v1); \ + b = vec_mergesqo(v0, v1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(16, ptr); \ + Tvec v2 = vsx_ld(32, ptr); \ + Tvec v3 = vsx_ld(48, ptr); \ + Tvec m0 = vec_mergesqe(v0, v1); \ + Tvec m1 = vec_mergesqe(v2, v3); \ + a = vec_mergesqe(m0, m1); \ + c = vec_mergesqo(m0, m1); \ + m0 = vec_mergesqo(v0, v1); \ + m1 = vec_mergesqo(v2, v3); \ + b = vec_mergesqe(m0, m1); \ + d = vec_mergesqo(m0, m1); \ +} +VSX_IMPL_ST_DINTERLEAVE_8(uchar, vec_uchar16) +VSX_IMPL_ST_DINTERLEAVE_8(schar, vec_char16) + +// 2 and 4 channels deinterleave for 8 lanes +#define VSX_IMPL_ST_DINTERLEAVE_16(Tp, Tvec) \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(8, ptr); \ + a = vec_mergesqe(v0, v1); \ + b = vec_mergesqo(v0, v1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(8, ptr); \ + Tvec m0 = vec_mergeh(v0, v1); \ + Tvec m1 = vec_mergel(v0, v1); \ + Tvec ab0 = vec_mergeh(m0, m1); \ + Tvec cd0 = vec_mergel(m0, m1); \ + v0 = vsx_ld(16, ptr); \ + v1 = vsx_ld(24, ptr); \ + m0 = vec_mergeh(v0, v1); \ + m1 = vec_mergel(v0, v1); \ + Tvec ab1 = vec_mergeh(m0, m1); \ + Tvec cd1 = vec_mergel(m0, m1); \ + a = vec_mergesqh(ab0, ab1); \ + b = vec_mergesql(ab0, ab1); \ + c = vec_mergesqh(cd0, cd1); \ + d = vec_mergesql(cd0, cd1); \ +} +VSX_IMPL_ST_DINTERLEAVE_16(ushort, vec_ushort8) +VSX_IMPL_ST_DINTERLEAVE_16(short, vec_short8) + +// 2 and 4 channels deinterleave for 4 lanes +#define VSX_IMPL_ST_DINTERLEAVE_32(Tp, Tvec) \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + a = vsx_ld(0, ptr); \ + b = vsx_ld(4, ptr); \ + Tvec m0 = vec_mergeh(a, b); \ + Tvec m1 = vec_mergel(a, b); \ + a = vec_mergeh(m0, m1); \ + b = vec_mergel(m0, m1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = vsx_ld(0, ptr); \ + Tvec v1 = vsx_ld(4, ptr); \ + Tvec v2 = vsx_ld(8, ptr); \ + Tvec v3 = vsx_ld(12, ptr); \ + Tvec m0 = vec_mergeh(v0, v2); \ + Tvec m1 = vec_mergeh(v1, v3); \ + a = vec_mergeh(m0, m1); \ + b = vec_mergel(m0, m1); \ + m0 = vec_mergel(v0, v2); \ + m1 = vec_mergel(v1, v3); \ + c = vec_mergeh(m0, m1); \ + d = vec_mergel(m0, m1); \ +} +VSX_IMPL_ST_DINTERLEAVE_32(uint, vec_uint4) +VSX_IMPL_ST_DINTERLEAVE_32(int, vec_int4) +VSX_IMPL_ST_DINTERLEAVE_32(float, vec_float4) + +// 2 and 4 channels interleave and deinterleave for 2 lanes +#define VSX_IMPL_ST_D_INTERLEAVE_64(Tp, Tvec, ld_func, st_func) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, Tp* ptr) \ +{ \ + st_func(vec_mergeh(a, b), 0, ptr); \ + st_func(vec_mergel(a, b), 2, ptr); \ +} \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, const Tvec& d, Tp* ptr) \ +{ \ + st_func(vec_mergeh(a, b), 0, ptr); \ + st_func(vec_mergeh(c, d), 2, ptr); \ + st_func(vec_mergel(a, b), 4, ptr); \ + st_func(vec_mergel(c, d), 6, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b) \ +{ \ + Tvec m0 = ld_func(0, ptr); \ + Tvec m1 = ld_func(2, ptr); \ + a = vec_mergeh(m0, m1); \ + b = vec_mergel(m0, m1); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, \ + Tvec& c, Tvec& d) \ +{ \ + Tvec v0 = ld_func(0, ptr); \ + Tvec v1 = ld_func(2, ptr); \ + Tvec v2 = ld_func(4, ptr); \ + Tvec v3 = ld_func(6, ptr); \ + a = vec_mergeh(v0, v2); \ + b = vec_mergel(v0, v2); \ + c = vec_mergeh(v1, v3); \ + d = vec_mergel(v1, v3); \ +} +VSX_IMPL_ST_D_INTERLEAVE_64(int64, vec_dword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_D_INTERLEAVE_64(uint64, vec_udword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_D_INTERLEAVE_64(double, vec_double2, vsx_ld, vsx_st) + +/* 3 channels */ +#define VSX_IMPL_ST_INTERLEAVE_3CH_16(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + static const vec_uchar16 a12 = {0, 16, 0, 1, 17, 0, 2, 18, 0, 3, 19, 0, 4, 20, 0, 5}; \ + static const vec_uchar16 a123 = {0, 1, 16, 3, 4, 17, 6, 7, 18, 9, 10, 19, 12, 13, 20, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ + static const vec_uchar16 b12 = {21, 0, 6, 22, 0, 7, 23, 0, 8, 24, 0, 9, 25, 0, 10, 26}; \ + static const vec_uchar16 b123 = {0, 21, 2, 3, 22, 5, 6, 23, 8, 9, 24, 11, 12, 25, 14, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 16, ptr); \ + static const vec_uchar16 c12 = {0, 11, 27, 0, 12, 28, 0, 13, 29, 0, 14, 30, 0, 15, 31, 0}; \ + static const vec_uchar16 c123 = {26, 1, 2, 27, 4, 5, 28, 7, 8, 29, 10, 11, 30, 13, 14, 31}; \ + vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 32, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = vsx_ld(0, ptr); \ + Tvec v2 = vsx_ld(16, ptr); \ + Tvec v3 = vsx_ld(32, ptr); \ + static const vec_uchar16 a12_perm = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 17, 20, 23, 26, 29}; \ + a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ + static const vec_uchar16 b12_perm = {1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 18, 21, 24, 27, 30}; \ + b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ + static const vec_uchar16 c12_perm = {2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 0, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 19, 22, 25, 28, 31}; \ + c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_16(uchar, vec_uchar16) +VSX_IMPL_ST_INTERLEAVE_3CH_16(schar, vec_char16) + +#define VSX_IMPL_ST_INTERLEAVE_3CH_8(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + static const vec_uchar16 a12 = {0, 1, 16, 17, 0, 0, 2, 3, 18, 19, 0, 0, 4, 5, 20, 21}; \ + static const vec_uchar16 a123 = {0, 1, 2, 3, 16, 17, 6, 7, 8, 9, 18, 19, 12, 13, 14, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, a12), c, a123), 0, ptr); \ + static const vec_uchar16 b12 = {0, 0, 6, 7, 22, 23, 0, 0, 8, 9, 24, 25, 0, 0, 10, 11}; \ + static const vec_uchar16 b123 = {20, 21, 2, 3, 4, 5, 22, 23, 8, 9, 10, 11, 24, 25, 14, 15}; \ + vsx_st(vec_perm(vec_perm(a, b, b12), c, b123), 8, ptr); \ + static const vec_uchar16 c12 = {26, 27, 0, 0, 12, 13, 28, 29, 0, 0, 14, 15, 30, 31, 0, 0}; \ + static const vec_uchar16 c123 = {0, 1, 26, 27, 4, 5, 6, 7, 28, 29, 10, 11, 12, 13, 30, 31}; \ + vsx_st(vec_perm(vec_perm(a, b, c12), c, c123), 16, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = vsx_ld(0, ptr); \ + Tvec v2 = vsx_ld(8, ptr); \ + Tvec v3 = vsx_ld(16, ptr); \ + static const vec_uchar16 a12_perm = {0, 1, 6, 7, 12, 13, 18, 19, 24, 25, 30, 31, 0, 0, 0, 0}; \ + static const vec_uchar16 a123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 20, 21, 26, 27}; \ + a = vec_perm(vec_perm(v1, v2, a12_perm), v3, a123_perm); \ + static const vec_uchar16 b12_perm = {2, 3, 8, 9, 14, 15, 20, 21, 26, 27, 0, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 b123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 17, 22, 23, 28, 29}; \ + b = vec_perm(vec_perm(v1, v2, b12_perm), v3, b123_perm); \ + static const vec_uchar16 c12_perm = {4, 5, 10, 11, 16, 17, 22, 23, 28, 29, 0, 0, 0, 0, 0, 0}; \ + static const vec_uchar16 c123_perm = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 18, 19, 24, 25, 30, 31}; \ + c = vec_perm(vec_perm(v1, v2, c12_perm), v3, c123_perm); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_8(ushort, vec_ushort8) +VSX_IMPL_ST_INTERLEAVE_3CH_8(short, vec_short8) + +#define VSX_IMPL_ST_INTERLEAVE_3CH_4(Tp, Tvec) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + Tvec hbc = vec_mergeh(b, c); \ + static const vec_uchar16 ahbc = {0, 1, 2, 3, 16, 17, 18, 19, 20, 21, 22, 23, 4, 5, 6, 7}; \ + vsx_st(vec_perm(a, hbc, ahbc), 0, ptr); \ + Tvec lab = vec_mergel(a, b); \ + vsx_st(vec_sld(lab, hbc, 8), 4, ptr); \ + static const vec_uchar16 clab = {8, 9, 10, 11, 24, 25, 26, 27, 28, 29, 30, 31, 12, 13, 14, 15};\ + vsx_st(vec_perm(c, lab, clab), 8, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = vsx_ld(0, ptr); \ + Tvec v2 = vsx_ld(4, ptr); \ + Tvec v3 = vsx_ld(8, ptr); \ + static const vec_uchar16 flp = {0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19, 28, 29, 30, 31}; \ + a = vec_perm(v1, vec_sld(v3, v2, 8), flp); \ + static const vec_uchar16 flp2 = {28, 29, 30, 31, 0, 1, 2, 3, 12, 13, 14, 15, 16, 17, 18, 19}; \ + b = vec_perm(v2, vec_sld(v1, v3, 8), flp2); \ + c = vec_perm(vec_sld(v2, v1, 8), v3, flp); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_4(uint, vec_uint4) +VSX_IMPL_ST_INTERLEAVE_3CH_4(int, vec_int4) +VSX_IMPL_ST_INTERLEAVE_3CH_4(float, vec_float4) + +#define VSX_IMPL_ST_INTERLEAVE_3CH_2(Tp, Tvec, ld_func, st_func) \ +VSX_FINLINE(void) vec_st_interleave(const Tvec& a, const Tvec& b, \ + const Tvec& c, Tp* ptr) \ +{ \ + st_func(vec_mergeh(a, b), 0, ptr); \ + st_func(vec_permi(c, a, 1), 2, ptr); \ + st_func(vec_mergel(b, c), 4, ptr); \ +} \ +VSX_FINLINE(void) vec_ld_deinterleave(const Tp* ptr, Tvec& a, \ + Tvec& b, Tvec& c) \ +{ \ + Tvec v1 = ld_func(0, ptr); \ + Tvec v2 = ld_func(2, ptr); \ + Tvec v3 = ld_func(4, ptr); \ + a = vec_permi(v1, v2, 1); \ + b = vec_permi(v1, v3, 2); \ + c = vec_permi(v2, v3, 1); \ +} +VSX_IMPL_ST_INTERLEAVE_3CH_2(int64, vec_dword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_INTERLEAVE_3CH_2(uint64, vec_udword2, vsx_ld2, vsx_st2) +VSX_IMPL_ST_INTERLEAVE_3CH_2(double, vec_double2, vsx_ld, vsx_st) + +#endif // CV_VSX + +//! @} + +#endif // OPENCV_HAL_VSX_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/cvconfig.h b/3rdParty/opencv-4.11.0/opencv2/cvconfig.h index e1b1ee82bb..47c5735d79 100644 --- a/3rdParty/opencv-4.11.0/opencv2/cvconfig.h +++ b/3rdParty/opencv-4.11.0/opencv2/cvconfig.h @@ -1,155 +1,155 @@ -#ifndef OPENCV_CVCONFIG_H_INCLUDED -#define OPENCV_CVCONFIG_H_INCLUDED - -/* OpenCV compiled as static or dynamic libs */ -#define BUILD_SHARED_LIBS - -/* OpenCV intrinsics optimized code */ -#define CV_ENABLE_INTRINSICS - -/* OpenCV additional optimized code */ -/* #undef CV_DISABLE_OPTIMIZATION */ - -/* Compile for 'real' NVIDIA GPU architectures */ -#define CUDA_ARCH_BIN "" - -/* NVIDIA GPU features are used */ -#define CUDA_ARCH_FEATURES "" - -/* Compile for 'virtual' NVIDIA PTX architectures */ -#define CUDA_ARCH_PTX "" - -/* AMD's Basic Linear Algebra Subprograms Library*/ -/* #undef HAVE_CLAMDBLAS */ - -/* AMD's OpenCL Fast Fourier Transform Library*/ -/* #undef HAVE_CLAMDFFT */ - -/* Clp support */ -/* #undef HAVE_CLP */ - -/* NVIDIA CUDA Runtime API*/ -/* #undef HAVE_CUDA */ - -/* NVIDIA CUDA Basic Linear Algebra Subprograms (BLAS) API*/ -/* #undef HAVE_CUBLAS */ - -/* NVIDIA CUDA Deep Neural Network (cuDNN) API*/ -/* #undef HAVE_CUDNN */ - -/* NVIDIA CUDA Fast Fourier Transform (FFT) API*/ -/* #undef HAVE_CUFFT */ - -/* DirectX */ -#define HAVE_DIRECTX -#define HAVE_DIRECTX_NV12 -#define HAVE_D3D11 -#define HAVE_D3D10 -#define HAVE_D3D9 - -/* Eigen Matrix & Linear Algebra Library */ -/* #undef HAVE_EIGEN */ - -/* Geospatial Data Abstraction Library */ -/* #undef HAVE_GDAL */ - -/* Halide support */ -/* #undef HAVE_HALIDE */ - -/* Vulkan support */ -/* #undef HAVE_VULKAN */ - -/* Define to 1 if you have the header file. */ -#define HAVE_INTTYPES_H 1 - -/* Intel Integrated Performance Primitives */ -#define HAVE_IPP -#define HAVE_IPP_ICV -#define HAVE_IPP_IW -#define HAVE_IPP_IW_LL - -/* JPEG-2000 codec */ -#define HAVE_OPENJPEG -/* #undef HAVE_JASPER */ - -/* AVIF codec */ -/* #undef HAVE_AVIF */ - -/* IJG JPEG codec */ -#define HAVE_JPEG - -/* JPEG XL codec */ -/* #undef HAVE_JPEGXL */ - -/* GDCM DICOM codec */ -/* #undef HAVE_GDCM */ - -/* NVIDIA Video Decoding API*/ -/* #undef HAVE_NVCUVID */ -/* #undef HAVE_NVCUVID_HEADER */ -/* #undef HAVE_DYNLINK_NVCUVID_HEADER */ - -/* NVIDIA Video Encoding API*/ -/* #undef HAVE_NVCUVENC */ - -/* OpenCL Support */ -#define HAVE_OPENCL -/* #undef HAVE_OPENCL_STATIC */ -/* #undef HAVE_OPENCL_SVM */ - -/* NVIDIA OpenCL D3D Extensions support */ -#define HAVE_OPENCL_D3D11_NV - -/* OpenEXR codec */ -#define HAVE_OPENEXR - -/* OpenGL support*/ -/* #undef HAVE_OPENGL */ - -/* PNG codec */ -#define HAVE_PNG - -/* PNG codec */ -/* #undef HAVE_SPNG */ - -/* Posix threads (pthreads) */ -/* #undef HAVE_PTHREAD */ - -/* parallel_for with pthreads */ -/* #undef HAVE_PTHREADS_PF */ - -/* Intel Threading Building Blocks */ -/* #undef HAVE_TBB */ - -/* Ste||ar Group High Performance ParallelX */ -/* #undef HAVE_HPX */ - -/* TIFF codec */ -#define HAVE_TIFF - -/* Define if your processor stores words with the most significant byte - first (like Motorola and SPARC, unlike Intel and VAX). */ -/* #undef WORDS_BIGENDIAN */ - -/* VA library (libva) */ -/* #undef HAVE_VA */ - -/* Intel VA-API/OpenCL */ -/* #undef HAVE_VA_INTEL */ - -/* Lapack */ -/* #undef HAVE_LAPACK */ - -/* Library was compiled with functions instrumentation */ -/* #undef ENABLE_INSTRUMENTATION */ - -/* OpenVX */ -/* #undef HAVE_OPENVX */ - -/* OpenCV trace utilities */ -#define OPENCV_TRACE - -/* Library QR-code decoding */ -/* #undef HAVE_QUIRC */ - -#endif // OPENCV_CVCONFIG_H_INCLUDED +#ifndef OPENCV_CVCONFIG_H_INCLUDED +#define OPENCV_CVCONFIG_H_INCLUDED + +/* OpenCV compiled as static or dynamic libs */ +#define BUILD_SHARED_LIBS + +/* OpenCV intrinsics optimized code */ +#define CV_ENABLE_INTRINSICS + +/* OpenCV additional optimized code */ +/* #undef CV_DISABLE_OPTIMIZATION */ + +/* Compile for 'real' NVIDIA GPU architectures */ +#define CUDA_ARCH_BIN "" + +/* NVIDIA GPU features are used */ +#define CUDA_ARCH_FEATURES "" + +/* Compile for 'virtual' NVIDIA PTX architectures */ +#define CUDA_ARCH_PTX "" + +/* AMD's Basic Linear Algebra Subprograms Library*/ +/* #undef HAVE_CLAMDBLAS */ + +/* AMD's OpenCL Fast Fourier Transform Library*/ +/* #undef HAVE_CLAMDFFT */ + +/* Clp support */ +/* #undef HAVE_CLP */ + +/* NVIDIA CUDA Runtime API*/ +/* #undef HAVE_CUDA */ + +/* NVIDIA CUDA Basic Linear Algebra Subprograms (BLAS) API*/ +/* #undef HAVE_CUBLAS */ + +/* NVIDIA CUDA Deep Neural Network (cuDNN) API*/ +/* #undef HAVE_CUDNN */ + +/* NVIDIA CUDA Fast Fourier Transform (FFT) API*/ +/* #undef HAVE_CUFFT */ + +/* DirectX */ +#define HAVE_DIRECTX +#define HAVE_DIRECTX_NV12 +#define HAVE_D3D11 +#define HAVE_D3D10 +#define HAVE_D3D9 + +/* Eigen Matrix & Linear Algebra Library */ +/* #undef HAVE_EIGEN */ + +/* Geospatial Data Abstraction Library */ +/* #undef HAVE_GDAL */ + +/* Halide support */ +/* #undef HAVE_HALIDE */ + +/* Vulkan support */ +/* #undef HAVE_VULKAN */ + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Intel Integrated Performance Primitives */ +#define HAVE_IPP +#define HAVE_IPP_ICV +#define HAVE_IPP_IW +#define HAVE_IPP_IW_LL + +/* JPEG-2000 codec */ +#define HAVE_OPENJPEG +/* #undef HAVE_JASPER */ + +/* AVIF codec */ +/* #undef HAVE_AVIF */ + +/* IJG JPEG codec */ +#define HAVE_JPEG + +/* JPEG XL codec */ +/* #undef HAVE_JPEGXL */ + +/* GDCM DICOM codec */ +/* #undef HAVE_GDCM */ + +/* NVIDIA Video Decoding API*/ +/* #undef HAVE_NVCUVID */ +/* #undef HAVE_NVCUVID_HEADER */ +/* #undef HAVE_DYNLINK_NVCUVID_HEADER */ + +/* NVIDIA Video Encoding API*/ +/* #undef HAVE_NVCUVENC */ + +/* OpenCL Support */ +#define HAVE_OPENCL +/* #undef HAVE_OPENCL_STATIC */ +/* #undef HAVE_OPENCL_SVM */ + +/* NVIDIA OpenCL D3D Extensions support */ +#define HAVE_OPENCL_D3D11_NV + +/* OpenEXR codec */ +#define HAVE_OPENEXR + +/* OpenGL support*/ +/* #undef HAVE_OPENGL */ + +/* PNG codec */ +#define HAVE_PNG + +/* PNG codec */ +/* #undef HAVE_SPNG */ + +/* Posix threads (pthreads) */ +/* #undef HAVE_PTHREAD */ + +/* parallel_for with pthreads */ +/* #undef HAVE_PTHREADS_PF */ + +/* Intel Threading Building Blocks */ +/* #undef HAVE_TBB */ + +/* Ste||ar Group High Performance ParallelX */ +/* #undef HAVE_HPX */ + +/* TIFF codec */ +#define HAVE_TIFF + +/* Define if your processor stores words with the most significant byte + first (like Motorola and SPARC, unlike Intel and VAX). */ +/* #undef WORDS_BIGENDIAN */ + +/* VA library (libva) */ +/* #undef HAVE_VA */ + +/* Intel VA-API/OpenCL */ +/* #undef HAVE_VA_INTEL */ + +/* Lapack */ +/* #undef HAVE_LAPACK */ + +/* Library was compiled with functions instrumentation */ +/* #undef ENABLE_INSTRUMENTATION */ + +/* OpenVX */ +/* #undef HAVE_OPENVX */ + +/* OpenCV trace utilities */ +#define OPENCV_TRACE + +/* Library QR-code decoding */ +/* #undef HAVE_QUIRC */ + +#endif // OPENCV_CVCONFIG_H_INCLUDED diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn.hpp index f08efe815c..97f2fe3ffd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn.hpp @@ -1,78 +1,78 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_DNN_HPP -#define OPENCV_DNN_HPP - -// This is an umbrella header to include into you project. -// We are free to change headers layout in dnn subfolder, so please include -// this header for future compatibility - - -/** @defgroup dnn Deep Neural Network module - @{ - This module contains: - - API for new layers creation, layers are building bricks of neural networks; - - set of built-in most-useful Layers; - - API to construct and modify comprehensive neural networks from layers; - - functionality for loading serialized networks models from different frameworks. - - Functionality of this module is designed only for forward pass computations (i.e. network testing). - A network training is in principle not supported. - @} -*/ -/** @example samples/dnn/classification.cpp -Check @ref tutorial_dnn_googlenet "the corresponding tutorial" for more details -*/ -/** @example samples/dnn/colorization.cpp -*/ -/** @example samples/dnn/object_detection.cpp -Check @ref tutorial_dnn_yolo "the corresponding tutorial" for more details -*/ -/** @example samples/dnn/openpose.cpp -*/ -/** @example samples/dnn/segmentation.cpp -*/ -/** @example samples/dnn/text_detection.cpp -*/ -#include - -#endif /* OPENCV_DNN_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_DNN_HPP +#define OPENCV_DNN_HPP + +// This is an umbrella header to include into you project. +// We are free to change headers layout in dnn subfolder, so please include +// this header for future compatibility + + +/** @defgroup dnn Deep Neural Network module + @{ + This module contains: + - API for new layers creation, layers are building bricks of neural networks; + - set of built-in most-useful Layers; + - API to construct and modify comprehensive neural networks from layers; + - functionality for loading serialized networks models from different frameworks. + + Functionality of this module is designed only for forward pass computations (i.e. network testing). + A network training is in principle not supported. + @} +*/ +/** @example samples/dnn/classification.cpp +Check @ref tutorial_dnn_googlenet "the corresponding tutorial" for more details +*/ +/** @example samples/dnn/colorization.cpp +*/ +/** @example samples/dnn/object_detection.cpp +Check @ref tutorial_dnn_yolo "the corresponding tutorial" for more details +*/ +/** @example samples/dnn/openpose.cpp +*/ +/** @example samples/dnn/segmentation.cpp +*/ +/** @example samples/dnn/text_detection.cpp +*/ +#include + +#endif /* OPENCV_DNN_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp index 0475bac230..d9d1833780 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/all_layers.hpp @@ -1,1212 +1,1212 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_ALL_LAYERS_HPP -#define OPENCV_DNN_DNN_ALL_LAYERS_HPP -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ - -/** @defgroup dnnLayerList Partial List of Implemented Layers - @{ - This subsection of dnn module contains information about built-in layers and their descriptions. - - Classes listed here, in fact, provides C++ API for creating instances of built-in layers. - In addition to this way of layers instantiation, there is a more common factory API (see @ref dnnLayerFactory), it allows to create layers dynamically (by name) and register new ones. - You can use both API, but factory API is less convenient for native C++ programming and basically designed for use inside importers (see @ref readNetFromCaffe(), @ref readNetFromTorch(), @ref readNetFromTensorflow()). - - Built-in layers partially reproduce functionality of corresponding Caffe and Torch7 layers. - In particular, the following layers and Caffe importer were tested to reproduce Caffe functionality: - - Convolution - - Deconvolution - - Pooling - - InnerProduct - - TanH, ReLU, Sigmoid, BNLL, Power, AbsVal - - Softmax - - Reshape, Flatten, Slice, Split - - LRN - - MVN - - Dropout (since it does nothing on forward pass -)) -*/ - - class CV_EXPORTS BlankLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - /** - * Constant layer produces the same data blob at an every forward pass. - */ - class CV_EXPORTS ConstLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - //! LSTM recurrent layer - class CV_EXPORTS LSTMLayer : public Layer - { - public: - /** Creates instance of LSTM layer */ - static Ptr create(const LayerParams& params); - - /** @deprecated Use LayerParams::blobs instead. - @brief Set trained weights for LSTM layer. - - LSTM behavior on each step is defined by current input, previous output, previous cell state and learned weights. - - Let @f$x_t@f$ be current input, @f$h_t@f$ be current output, @f$c_t@f$ be current state. - Than current output and current cell state is computed as follows: - @f{eqnarray*}{ - h_t &= o_t \odot tanh(c_t), \\ - c_t &= f_t \odot c_{t-1} + i_t \odot g_t, \\ - @f} - where @f$\odot@f$ is per-element multiply operation and @f$i_t, f_t, o_t, g_t@f$ is internal gates that are computed using learned weights. - - Gates are computed as follows: - @f{eqnarray*}{ - i_t &= sigmoid&(W_{xi} x_t + W_{hi} h_{t-1} + b_i), \\ - f_t &= sigmoid&(W_{xf} x_t + W_{hf} h_{t-1} + b_f), \\ - o_t &= sigmoid&(W_{xo} x_t + W_{ho} h_{t-1} + b_o), \\ - g_t &= tanh &(W_{xg} x_t + W_{hg} h_{t-1} + b_g), \\ - @f} - where @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: - @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. - - For simplicity and performance purposes we use @f$ W_x = [W_{xi}; W_{xf}; W_{xo}, W_{xg}] @f$ - (i.e. @f$W_x@f$ is vertical concatenation of @f$ W_{x?} @f$), @f$ W_x \in R^{4N_h \times N_x} @f$. - The same for @f$ W_h = [W_{hi}; W_{hf}; W_{ho}, W_{hg}], W_h \in R^{4N_h \times N_h} @f$ - and for @f$ b = [b_i; b_f, b_o, b_g]@f$, @f$b \in R^{4N_h} @f$. - - @param Wh is matrix defining how previous output is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_h @f$) - @param Wx is matrix defining how current input is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_x @f$) - @param b is bias vector (i.e. according to above mentioned notation is @f$ b @f$) - */ - CV_DEPRECATED virtual void setWeights(const Mat &Wh, const Mat &Wx, const Mat &b) = 0; - - /** @brief Specifies shape of output blob which will be [[`T`], `N`] + @p outTailShape. - * @details If this parameter is empty or unset then @p outTailShape = [`Wh`.size(0)] will be used, - * where `Wh` is parameter from setWeights(). - */ - virtual void setOutShape(const MatShape &outTailShape = MatShape()) = 0; - - /** @deprecated Use flag `produce_cell_output` in LayerParams. - * @brief Specifies either interpret first dimension of input blob as timestamp dimension either as sample. - * - * If flag is set to true then shape of input blob will be interpreted as [`T`, `N`, `[data dims]`] where `T` specifies number of timestamps, `N` is number of independent streams. - * In this case each forward() call will iterate through `T` timestamps and update layer's state `T` times. - * - * If flag is set to false then shape of input blob will be interpreted as [`N`, `[data dims]`]. - * In this case each forward() call will make one iteration and produce one timestamp with shape [`N`, `[out dims]`]. - */ - CV_DEPRECATED virtual void setUseTimstampsDim(bool use = true) = 0; - - /** @deprecated Use flag `use_timestamp_dim` in LayerParams. - * @brief If this flag is set to true then layer will produce @f$ c_t @f$ as second output. - * @details Shape of the second output is the same as first output. - */ - CV_DEPRECATED virtual void setProduceCellOutput(bool produce = false) = 0; - - /* In common case it use single input with @f$x_t@f$ values to compute output(s) @f$h_t@f$ (and @f$c_t@f$). - * @param input should contain packed values @f$x_t@f$ - * @param output contains computed outputs: @f$h_t@f$ (and @f$c_t@f$ if setProduceCellOutput() flag was set to true). - * - * If setUseTimstampsDim() is set to true then @p input[0] should has at least two dimensions with the following shape: [`T`, `N`, `[data dims]`], - * where `T` specifies number of timestamps, `N` is number of independent streams (i.e. @f$ x_{t_0 + t}^{stream} @f$ is stored inside @p input[0][t, stream, ...]). - * - * If setUseTimstampsDim() is set to false then @p input[0] should contain single timestamp, its shape should has form [`N`, `[data dims]`] with at least one dimension. - * (i.e. @f$ x_{t}^{stream} @f$ is stored inside @p input[0][stream, ...]). - */ - - int inputNameToIndex(String inputName) CV_OVERRIDE; - int outputNameToIndex(const String& outputName) CV_OVERRIDE; - }; - - /** @brief GRU recurrent one-layer - * - * Accepts input sequence and computes the final hidden state for each element in the batch. - * - * - input[0] containing the features of the input sequence. - * input[0] should have shape [`T`, `N`, `data_dims`] where `T` is sequence length, `N` is batch size, `data_dims` is input size - * - output would have shape [`T`, `N`, `D` * `hidden_size`] where `D = 2` if layer is bidirectional otherwise `D = 1` - * - * Depends on the following attributes: - * - hidden_size - Number of neurons in the hidden layer - * - direction - RNN could be bidirectional or forward - * - * The final hidden state @f$ h_t @f$ computes by the following formulas: - * - @f{eqnarray*}{ - r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ - z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\ - n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\ - h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)} \\ - @f} - * Where @f$x_t@f$ is current input, @f$h_{(t-1)}@f$ is previous or initial hidden state. - * - * @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: - * @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. - * - * @f$\odot@f$ is per-element multiply operation. - */ - class CV_EXPORTS GRULayer : public Layer - { - public: - /** Creates instance of GRU layer */ - static Ptr create(const LayerParams& params); - }; - - /** @brief Classical recurrent layer - - Accepts two inputs @f$x_t@f$ and @f$h_{t-1}@f$ and compute two outputs @f$o_t@f$ and @f$h_t@f$. - - - input: should contain packed input @f$x_t@f$. - - output: should contain output @f$o_t@f$ (and @f$h_t@f$ if setProduceHiddenOutput() is set to true). - - input[0] should have shape [`T`, `N`, `data_dims`] where `T` and `N` is number of timestamps and number of independent samples of @f$x_t@f$ respectively. - - output[0] will have shape [`T`, `N`, @f$N_o@f$], where @f$N_o@f$ is number of rows in @f$ W_{xo} @f$ matrix. - - If setProduceHiddenOutput() is set to true then @p output[1] will contain a Mat with shape [`T`, `N`, @f$N_h@f$], where @f$N_h@f$ is number of rows in @f$ W_{hh} @f$ matrix. - */ - class CV_EXPORTS RNNLayer : public Layer - { - public: - /** Creates instance of RNNLayer */ - static Ptr create(const LayerParams& params); - - /** Setups learned weights. - - Recurrent-layer behavior on each step is defined by current input @f$ x_t @f$, previous state @f$ h_t @f$ and learned weights as follows: - @f{eqnarray*}{ - h_t &= tanh&(W_{hh} h_{t-1} + W_{xh} x_t + b_h), \\ - o_t &= tanh&(W_{ho} h_t + b_o), - @f} - - @param Wxh is @f$ W_{xh} @f$ matrix - @param bh is @f$ b_{h} @f$ vector - @param Whh is @f$ W_{hh} @f$ matrix - @param Who is @f$ W_{xo} @f$ matrix - @param bo is @f$ b_{o} @f$ vector - */ - virtual void setWeights(const Mat &Wxh, const Mat &bh, const Mat &Whh, const Mat &Who, const Mat &bo) = 0; - - /** @brief If this flag is set to true then layer will produce @f$ h_t @f$ as second output. - * @details Shape of the second output is the same as first output. - */ - virtual void setProduceHiddenOutput(bool produce = false) = 0; - - }; - - /** @brief This function performs array summation based - * on the Einstein summation convention. The function - * allows for concise expressions of various mathematical - * operations using subscripts. - * - * By default, the labels are placed in alphabetical - * order at the end of the output. - * For example: - * if `c = einsum("i,j", a, b)`, then `c[i,j] == a[i]*b[j]`. - * However, if `c = einsum("j,i", a, b)`, then `c[i,j] = a[j]*b[i]`. - * Alternatively, you can control the output order or prevent - * an axis from being summed/force an axis to be summed - * by providing indices for the output. - * For example: - * `diag(a)` -> `einsum("ii->i", a)` - * `sum(a, axis=0)` -> `einsum("i...->", a)` - * Subscripts at the beginning and end may be specified - * by putting an ellipsis "..." in the middle. - * For instance, the function `einsum("i...i", a)` takes - * the diagonal of the first and last dimensions of - * the operand, and `einsum("ij...,jk...->ik...")` performs - * the matrix product using the first two indices - * of each operand instead of the last two. - * When there is only one operand, no axes being summed, - * and no output parameter, this function returns - * a view into the operand instead of creating a copy. - */ - class CV_EXPORTS EinsumLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS BaseConvolutionLayer : public Layer - { - public: - CV_DEPRECATED_EXTERNAL Size kernel, stride, pad, dilation, adjustPad; - std::vector adjust_pads; - std::vector kernel_size, strides, dilations; - std::vector pads_begin, pads_end; - String padMode; - int numOutput; - }; - - class CV_EXPORTS ConvolutionLayer : public BaseConvolutionLayer - { - public: - static Ptr create(const LayerParams& params); - bool fusedActivation = false; - bool fusedAdd = false; - bool useWinograd = true; // Flag whether to use Winograd to speed up 3x3 convolution. - }; - - class CV_EXPORTS ConvolutionLayerInt8 : public BaseConvolutionLayer - { - public: - int input_zp, output_zp; - float input_sc, output_sc; - - // quantization type flag. The perChannel default is true, that means it contains the parameters - // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. - bool per_channel; - bool useWinograd = false; // Flag whether to use Winograd to speed up 3x3 convolution. - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS DeconvolutionLayer : public BaseConvolutionLayer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS LRNLayer : public Layer - { - public: - int type; - - int size; - float alpha, beta, bias; - bool normBySize; - - static Ptr create(const LayerParams& params); - }; - - - /** @brief ArgMax/ArgMin layer - * @note returns indices as floats, which means the supported range is [-2^24; 2^24] - */ - class CV_EXPORTS ArgLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** @brief Gather layer - */ - class CV_EXPORTS GatherLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** @brief GatherElements layer - * GatherElements takes two inputs data and indices of the same rank r >= 1 and an optional attribute axis and works such that: - * output[i][j][k] = data[index[i][j][k]][j][k] if axis = 0 and r = 3 - * output[i][j][k] = data[i][index[i][j][k]][k] if axis = 1 and r = 3 - * output[i][j][k] = data[i][j][index[i][j][k]] if axis = 2 and r = 3 - * - * Gather, on the other hand, takes a data tensor of rank r >= 1, and indices tensor of rank q, and works such that: - * it gathers the enteries along axis dimension of the input data indexed by indices and concatenates them in an output tensor of rank q + (r - 1) - * e.g. If axis = 0, let k = indices[i_{0}, ..., i_{q-1}] then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]: - **/ - class CV_EXPORTS GatherElementsLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS PoolingLayer : public Layer - { - public: - int type; - std::vector kernel_size, strides; - std::vector pads_begin, pads_end; - bool globalPooling; //!< Flag is true if at least one of the axes is global pooled. - std::vector isGlobalPooling; - bool computeMaxIdx; - String padMode; - bool ceilMode; - // If true for average pooling with padding, divide an every output region - // by a whole kernel area. Otherwise exclude zero padded values and divide - // by number of real values. - bool avePoolPaddedArea; - // ROIPooling parameters. - Size pooledSize; - float spatialScale; - // PSROIPooling parameters. - int psRoiOutChannels; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS PoolingLayerInt8 : public PoolingLayer - { - public: - int input_zp, output_zp; - float input_sc, output_sc; - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ReduceLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS SoftmaxLayer : public Layer - { - public: - bool logSoftMax; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS SoftmaxLayerInt8 : public SoftmaxLayer - { - public: - float output_sc; - int output_zp; - static Ptr create(const LayerParams& params); - }; - - /** - * `InnerProduct`, `MatMul` and `Gemm` operations are all implemented by Fully Connected Layer. - * Parameter `is_matmul` is used to distinguish `MatMul` and `Gemm` from `InnerProduct`. - */ - class CV_EXPORTS InnerProductLayer : public Layer - { - public: - int axis; - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS InnerProductLayerInt8 : public InnerProductLayer - { - public: - int input_zp, output_zp; - float input_sc, output_sc; - - // quantization type flag. The perChannel default is true, that means it contains the parameters - // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. - bool per_channel; - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS MVNLayer : public Layer - { - public: - float eps; - bool normVariance, acrossChannels; - - static Ptr create(const LayerParams& params); - }; - - /* Reshaping */ - - class CV_EXPORTS ReshapeLayer : public Layer - { - public: - MatShape newShapeDesc; - Range newShapeRange; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS FlattenLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS QuantizeLayer : public Layer - { - public: - std::vector scales; - std::vector zeropoints; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS DequantizeLayer : public Layer - { - public: - std::vector scales; - std::vector zeropoints; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS RequantizeLayer : public Layer - { - public: - float scale, shift; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ConcatLayer : public Layer - { - public: - int axis; - /** - * @brief Add zero padding in case of concatenation of blobs with different - * spatial sizes. - * - * Details: https://github.com/torch/nn/blob/master/doc/containers.md#depthconcat - */ - bool padding; - int paddingValue; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SplitLayer : public Layer - { - public: - int outputsCount; //!< Number of copies that will be produced (is ignored when negative). - - static Ptr create(const LayerParams ¶ms); - }; - - /** - * Slice layer has several modes: - * 1. Caffe mode - * @param[in] axis Axis of split operation - * @param[in] slice_point Array of split points - * - * Number of output blobs equals to number of split points plus one. The - * first blob is a slice on input from 0 to @p slice_point[0] - 1 by @p axis, - * the second output blob is a slice of input from @p slice_point[0] to - * @p slice_point[1] - 1 by @p axis and the last output blob is a slice of - * input from @p slice_point[-1] up to the end of @p axis size. - * - * 2. TensorFlow mode - * @param begin Vector of start indices - * @param size Vector of sizes - * - * More convenient numpy-like slice. One and only output blob - * is a slice `input[begin[0]:begin[0]+size[0], begin[1]:begin[1]+size[1], ...]` - * - * 3. Torch mode - * @param axis Axis of split operation - * - * Split input blob on the equal parts by @p axis. - */ - class CV_EXPORTS SliceLayer : public Layer - { - public: - /** - * @brief Vector of slice ranges. - * - * The first dimension equals number of output blobs. - * Inner vector has slice ranges for the first number of input dimensions. - */ - std::vector > sliceRanges; - std::vector > sliceSteps; - int axis; - int num_split; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS PermuteLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** - * Permute channels of 4-dimensional input blob. - * @param group Number of groups to split input channels and pick in turns - * into output blob. - * - * \f[ groupSize = \frac{number\ of\ channels}{group} \f] - * \f[ output(n, c, h, w) = input(n, groupSize \times (c \% group) + \lfloor \frac{c}{group} \rfloor, h, w) \f] - * Read more at https://arxiv.org/pdf/1707.01083.pdf - */ - class CV_EXPORTS ShuffleChannelLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - - int group; - }; - - /** - * @brief Adds extra values for specific axes. - * @param paddings Vector of paddings in format - * @code - * [ pad_before, pad_after, // [0]th dimension - * pad_before, pad_after, // [1]st dimension - * ... - * pad_before, pad_after ] // [n]th dimension - * @endcode - * that represents number of padded values at every dimension - * starting from the first one. The rest of dimensions won't - * be padded. - * @param value Value to be padded. Defaults to zero. - * @param type Padding type: 'constant', 'reflect' - * @param input_dims Torch's parameter. If @p input_dims is not equal to the - * actual input dimensionality then the `[0]th` dimension - * is considered as a batch dimension and @p paddings are shifted - * to a one dimension. Defaults to `-1` that means padding - * corresponding to @p paddings. - */ - class CV_EXPORTS PaddingLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /* Activations */ - class CV_EXPORTS ActivationLayer : public Layer - { - public: - virtual void forwardSlice(const float* src, float* dst, int len, - size_t outPlaneSize, int cn0, int cn1) const {} - virtual void forwardSlice(const int* src, const int* lut, int* dst, int len, - size_t outPlaneSize, int cn0, int cn1) const {} - virtual void forwardSlice(const int8_t* src, const int8_t* lut, int8_t* dst, int len, - size_t outPlaneSize, int cn0, int cn1) const {} - }; - - class CV_EXPORTS ReLULayer : public ActivationLayer - { - public: - float negativeSlope; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ReLU6Layer : public ActivationLayer - { - public: - float minValue, maxValue; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ChannelsPReLULayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ELULayer : public ActivationLayer - { - public: - float alpha; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS TanHLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SwishLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS MishLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SigmoidLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS BNLLLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AbsLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS PowerLayer : public ActivationLayer - { - public: - float power, scale, shift; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ExpLayer : public ActivationLayer - { - public: - float base, scale, shift; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CeilLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS FloorLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS LogLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS RoundLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SqrtLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS NotLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AcosLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AcoshLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AsinLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AsinhLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AtanLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AtanhLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CosLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CoshLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ErfLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS HardSwishLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SinLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SinhLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SoftplusLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SoftsignLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS TanLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS CeluLayer : public ActivationLayer - { - public: - float alpha; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS HardSigmoidLayer : public ActivationLayer - { - public: - float alpha; - float beta; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SeluLayer : public ActivationLayer - { - public: - float alpha; - float gamma; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS GeluLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS GeluApproximationLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ThresholdedReluLayer : public ActivationLayer - { - public: - float alpha; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ActivationLayerInt8 : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SignLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ShrinkLayer : public ActivationLayer - { - public: - float bias; - float lambd; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ReciprocalLayer : public ActivationLayer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - /* Layers used in semantic segmentation */ - - class CV_EXPORTS CropLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - /** @brief Element wise operation on inputs - - Extra optional parameters: - - "operation" as string. Values are "sum" (default), "prod", "max", "div", "min" - - "coeff" as float array. Specify weights of inputs for SUM operation - - "output_channels_mode" as string. Values are "same" (default, all input must have the same layout), "input_0", "input_0_truncate", "max_input_channels" - */ - class CV_EXPORTS EltwiseLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS EltwiseLayerInt8 : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS NaryEltwiseLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS BatchNormLayer : public ActivationLayer - { - public: - bool hasWeights, hasBias; - float epsilon; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS BatchNormLayerInt8 : public BatchNormLayer - { - public: - float input_sc, output_sc; - int input_zp, output_zp; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS MaxUnpoolLayer : public Layer - { - public: - Size poolKernel; - Size poolPad; - Size poolStride; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ScaleLayer : public Layer - { - public: - bool hasBias; - int axis; - String mode; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ScaleLayerInt8 : public ScaleLayer - { - public: - float output_sc; - int output_zp; - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ShiftLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ShiftLayerInt8 : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CompareLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS DataAugmentationLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CorrelationLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS AccumLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS FlowWarpLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS PriorBoxLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ReorgLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS RegionLayer : public Layer - { - public: - float nmsThreshold; - - static Ptr create(const LayerParams& params); - }; - - /** - * @brief Detection output layer. - * - * The layer size is: @f$ (1 \times 1 \times N \times 7) @f$ - * where N is [keep_top_k] parameter multiplied by batch size. Each row is: - * [image_id, label, confidence, xmin, ymin, xmax, ymax] - * where image_id is the index of image input in the batch. - */ - class CV_EXPORTS DetectionOutputLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** - * @brief \f$ L_p \f$ - normalization layer. - * @param p Normalization factor. The most common `p = 1` for \f$ L_1 \f$ - - * normalization or `p = 2` for \f$ L_2 \f$ - normalization or a custom one. - * @param eps Parameter \f$ \epsilon \f$ to prevent a division by zero. - * @param across_spatial If true, normalize an input across all non-batch dimensions. - * Otherwise normalize an every channel separately. - * - * Across spatial: - * @f[ - * norm = \sqrt[p]{\epsilon + \sum_{x, y, c} |src(x, y, c)|^p } \\ - * dst(x, y, c) = \frac{ src(x, y, c) }{norm} - * @f] - * - * Channel wise normalization: - * @f[ - * norm(c) = \sqrt[p]{\epsilon + \sum_{x, y} |src(x, y, c)|^p } \\ - * dst(x, y, c) = \frac{ src(x, y, c) }{norm(c)} - * @f] - * - * Where `x, y` - spatial coordinates, `c` - channel. - * - * An every sample in the batch is normalized separately. Optionally, - * output is scaled by the trained parameters. - */ - class CV_EXPORTS NormalizeBBoxLayer : public Layer - { - public: - float pnorm, epsilon; - CV_DEPRECATED_EXTERNAL bool acrossSpatial; - - static Ptr create(const LayerParams& params); - }; - - /** - * @brief Resize input 4-dimensional blob by nearest neighbor or bilinear strategy. - * - * Layer is used to support TensorFlow's resize_nearest_neighbor and resize_bilinear ops. - */ - class CV_EXPORTS ResizeLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - /** - * @brief Bilinear resize layer from https://github.com/cdmh/deeplab-public-ver2 - * - * It differs from @ref ResizeLayer in output shape and resize scales computations. - */ - class CV_EXPORTS InterpLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ProposalLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CropAndResizeLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS CumSumLayer : public Layer - { - public: - int exclusive; - int reverse; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ScatterLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS ScatterNDLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS TileLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS LayerNormLayer : public Layer - { - public: - CV_DEPRECATED_EXTERNAL bool hasBias; // Deprecated, preserve for compatibility - int axis; - float epsilon; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS GemmLayer : public Layer { - public: - bool trans_a; - bool trans_b; - float alpha; - float beta; - - static Ptr create(const LayerParams& params); - }; - - class CV_EXPORTS MatMulLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS ExpandLayer : public Layer - { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS InstanceNormLayer : public Layer { - public: - float epsilon; - - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS AttentionLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS GroupNormLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS DepthToSpaceLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS SpaceToDepthLayer : public Layer { - public: - static Ptr create(const LayerParams ¶ms); - }; - - class CV_EXPORTS TopKLayer : public Layer - { - public: - static Ptr create(const LayerParams& params); - }; - -//! @} -//! @} -CV__DNN_INLINE_NS_END -} -} -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_ALL_LAYERS_HPP +#define OPENCV_DNN_DNN_ALL_LAYERS_HPP +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ + +/** @defgroup dnnLayerList Partial List of Implemented Layers + @{ + This subsection of dnn module contains information about built-in layers and their descriptions. + + Classes listed here, in fact, provides C++ API for creating instances of built-in layers. + In addition to this way of layers instantiation, there is a more common factory API (see @ref dnnLayerFactory), it allows to create layers dynamically (by name) and register new ones. + You can use both API, but factory API is less convenient for native C++ programming and basically designed for use inside importers (see @ref readNetFromCaffe(), @ref readNetFromTorch(), @ref readNetFromTensorflow()). + + Built-in layers partially reproduce functionality of corresponding Caffe and Torch7 layers. + In particular, the following layers and Caffe importer were tested to reproduce Caffe functionality: + - Convolution + - Deconvolution + - Pooling + - InnerProduct + - TanH, ReLU, Sigmoid, BNLL, Power, AbsVal + - Softmax + - Reshape, Flatten, Slice, Split + - LRN + - MVN + - Dropout (since it does nothing on forward pass -)) +*/ + + class CV_EXPORTS BlankLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + /** + * Constant layer produces the same data blob at an every forward pass. + */ + class CV_EXPORTS ConstLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + //! LSTM recurrent layer + class CV_EXPORTS LSTMLayer : public Layer + { + public: + /** Creates instance of LSTM layer */ + static Ptr create(const LayerParams& params); + + /** @deprecated Use LayerParams::blobs instead. + @brief Set trained weights for LSTM layer. + + LSTM behavior on each step is defined by current input, previous output, previous cell state and learned weights. + + Let @f$x_t@f$ be current input, @f$h_t@f$ be current output, @f$c_t@f$ be current state. + Than current output and current cell state is computed as follows: + @f{eqnarray*}{ + h_t &= o_t \odot tanh(c_t), \\ + c_t &= f_t \odot c_{t-1} + i_t \odot g_t, \\ + @f} + where @f$\odot@f$ is per-element multiply operation and @f$i_t, f_t, o_t, g_t@f$ is internal gates that are computed using learned weights. + + Gates are computed as follows: + @f{eqnarray*}{ + i_t &= sigmoid&(W_{xi} x_t + W_{hi} h_{t-1} + b_i), \\ + f_t &= sigmoid&(W_{xf} x_t + W_{hf} h_{t-1} + b_f), \\ + o_t &= sigmoid&(W_{xo} x_t + W_{ho} h_{t-1} + b_o), \\ + g_t &= tanh &(W_{xg} x_t + W_{hg} h_{t-1} + b_g), \\ + @f} + where @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: + @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. + + For simplicity and performance purposes we use @f$ W_x = [W_{xi}; W_{xf}; W_{xo}, W_{xg}] @f$ + (i.e. @f$W_x@f$ is vertical concatenation of @f$ W_{x?} @f$), @f$ W_x \in R^{4N_h \times N_x} @f$. + The same for @f$ W_h = [W_{hi}; W_{hf}; W_{ho}, W_{hg}], W_h \in R^{4N_h \times N_h} @f$ + and for @f$ b = [b_i; b_f, b_o, b_g]@f$, @f$b \in R^{4N_h} @f$. + + @param Wh is matrix defining how previous output is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_h @f$) + @param Wx is matrix defining how current input is transformed to internal gates (i.e. according to above mentioned notation is @f$ W_x @f$) + @param b is bias vector (i.e. according to above mentioned notation is @f$ b @f$) + */ + CV_DEPRECATED virtual void setWeights(const Mat &Wh, const Mat &Wx, const Mat &b) = 0; + + /** @brief Specifies shape of output blob which will be [[`T`], `N`] + @p outTailShape. + * @details If this parameter is empty or unset then @p outTailShape = [`Wh`.size(0)] will be used, + * where `Wh` is parameter from setWeights(). + */ + virtual void setOutShape(const MatShape &outTailShape = MatShape()) = 0; + + /** @deprecated Use flag `produce_cell_output` in LayerParams. + * @brief Specifies either interpret first dimension of input blob as timestamp dimension either as sample. + * + * If flag is set to true then shape of input blob will be interpreted as [`T`, `N`, `[data dims]`] where `T` specifies number of timestamps, `N` is number of independent streams. + * In this case each forward() call will iterate through `T` timestamps and update layer's state `T` times. + * + * If flag is set to false then shape of input blob will be interpreted as [`N`, `[data dims]`]. + * In this case each forward() call will make one iteration and produce one timestamp with shape [`N`, `[out dims]`]. + */ + CV_DEPRECATED virtual void setUseTimstampsDim(bool use = true) = 0; + + /** @deprecated Use flag `use_timestamp_dim` in LayerParams. + * @brief If this flag is set to true then layer will produce @f$ c_t @f$ as second output. + * @details Shape of the second output is the same as first output. + */ + CV_DEPRECATED virtual void setProduceCellOutput(bool produce = false) = 0; + + /* In common case it use single input with @f$x_t@f$ values to compute output(s) @f$h_t@f$ (and @f$c_t@f$). + * @param input should contain packed values @f$x_t@f$ + * @param output contains computed outputs: @f$h_t@f$ (and @f$c_t@f$ if setProduceCellOutput() flag was set to true). + * + * If setUseTimstampsDim() is set to true then @p input[0] should has at least two dimensions with the following shape: [`T`, `N`, `[data dims]`], + * where `T` specifies number of timestamps, `N` is number of independent streams (i.e. @f$ x_{t_0 + t}^{stream} @f$ is stored inside @p input[0][t, stream, ...]). + * + * If setUseTimstampsDim() is set to false then @p input[0] should contain single timestamp, its shape should has form [`N`, `[data dims]`] with at least one dimension. + * (i.e. @f$ x_{t}^{stream} @f$ is stored inside @p input[0][stream, ...]). + */ + + int inputNameToIndex(String inputName) CV_OVERRIDE; + int outputNameToIndex(const String& outputName) CV_OVERRIDE; + }; + + /** @brief GRU recurrent one-layer + * + * Accepts input sequence and computes the final hidden state for each element in the batch. + * + * - input[0] containing the features of the input sequence. + * input[0] should have shape [`T`, `N`, `data_dims`] where `T` is sequence length, `N` is batch size, `data_dims` is input size + * - output would have shape [`T`, `N`, `D` * `hidden_size`] where `D = 2` if layer is bidirectional otherwise `D = 1` + * + * Depends on the following attributes: + * - hidden_size - Number of neurons in the hidden layer + * - direction - RNN could be bidirectional or forward + * + * The final hidden state @f$ h_t @f$ computes by the following formulas: + * + @f{eqnarray*}{ + r_t = \sigma(W_{ir} x_t + b_{ir} + W_{hr} h_{(t-1)} + b_{hr}) \\ + z_t = \sigma(W_{iz} x_t + b_{iz} + W_{hz} h_{(t-1)} + b_{hz}) \\ + n_t = \tanh(W_{in} x_t + b_{in} + r_t \odot (W_{hn} h_{(t-1)}+ b_{hn})) \\ + h_t = (1 - z_t) \odot n_t + z_t \odot h_{(t-1)} \\ + @f} + * Where @f$x_t@f$ is current input, @f$h_{(t-1)}@f$ is previous or initial hidden state. + * + * @f$W_{x?}@f$, @f$W_{h?}@f$ and @f$b_{?}@f$ are learned weights represented as matrices: + * @f$W_{x?} \in R^{N_h \times N_x}@f$, @f$W_{h?} \in R^{N_h \times N_h}@f$, @f$b_? \in R^{N_h}@f$. + * + * @f$\odot@f$ is per-element multiply operation. + */ + class CV_EXPORTS GRULayer : public Layer + { + public: + /** Creates instance of GRU layer */ + static Ptr create(const LayerParams& params); + }; + + /** @brief Classical recurrent layer + + Accepts two inputs @f$x_t@f$ and @f$h_{t-1}@f$ and compute two outputs @f$o_t@f$ and @f$h_t@f$. + + - input: should contain packed input @f$x_t@f$. + - output: should contain output @f$o_t@f$ (and @f$h_t@f$ if setProduceHiddenOutput() is set to true). + + input[0] should have shape [`T`, `N`, `data_dims`] where `T` and `N` is number of timestamps and number of independent samples of @f$x_t@f$ respectively. + + output[0] will have shape [`T`, `N`, @f$N_o@f$], where @f$N_o@f$ is number of rows in @f$ W_{xo} @f$ matrix. + + If setProduceHiddenOutput() is set to true then @p output[1] will contain a Mat with shape [`T`, `N`, @f$N_h@f$], where @f$N_h@f$ is number of rows in @f$ W_{hh} @f$ matrix. + */ + class CV_EXPORTS RNNLayer : public Layer + { + public: + /** Creates instance of RNNLayer */ + static Ptr create(const LayerParams& params); + + /** Setups learned weights. + + Recurrent-layer behavior on each step is defined by current input @f$ x_t @f$, previous state @f$ h_t @f$ and learned weights as follows: + @f{eqnarray*}{ + h_t &= tanh&(W_{hh} h_{t-1} + W_{xh} x_t + b_h), \\ + o_t &= tanh&(W_{ho} h_t + b_o), + @f} + + @param Wxh is @f$ W_{xh} @f$ matrix + @param bh is @f$ b_{h} @f$ vector + @param Whh is @f$ W_{hh} @f$ matrix + @param Who is @f$ W_{xo} @f$ matrix + @param bo is @f$ b_{o} @f$ vector + */ + virtual void setWeights(const Mat &Wxh, const Mat &bh, const Mat &Whh, const Mat &Who, const Mat &bo) = 0; + + /** @brief If this flag is set to true then layer will produce @f$ h_t @f$ as second output. + * @details Shape of the second output is the same as first output. + */ + virtual void setProduceHiddenOutput(bool produce = false) = 0; + + }; + + /** @brief This function performs array summation based + * on the Einstein summation convention. The function + * allows for concise expressions of various mathematical + * operations using subscripts. + * + * By default, the labels are placed in alphabetical + * order at the end of the output. + * For example: + * if `c = einsum("i,j", a, b)`, then `c[i,j] == a[i]*b[j]`. + * However, if `c = einsum("j,i", a, b)`, then `c[i,j] = a[j]*b[i]`. + * Alternatively, you can control the output order or prevent + * an axis from being summed/force an axis to be summed + * by providing indices for the output. + * For example: + * `diag(a)` -> `einsum("ii->i", a)` + * `sum(a, axis=0)` -> `einsum("i...->", a)` + * Subscripts at the beginning and end may be specified + * by putting an ellipsis "..." in the middle. + * For instance, the function `einsum("i...i", a)` takes + * the diagonal of the first and last dimensions of + * the operand, and `einsum("ij...,jk...->ik...")` performs + * the matrix product using the first two indices + * of each operand instead of the last two. + * When there is only one operand, no axes being summed, + * and no output parameter, this function returns + * a view into the operand instead of creating a copy. + */ + class CV_EXPORTS EinsumLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS BaseConvolutionLayer : public Layer + { + public: + CV_DEPRECATED_EXTERNAL Size kernel, stride, pad, dilation, adjustPad; + std::vector adjust_pads; + std::vector kernel_size, strides, dilations; + std::vector pads_begin, pads_end; + String padMode; + int numOutput; + }; + + class CV_EXPORTS ConvolutionLayer : public BaseConvolutionLayer + { + public: + static Ptr create(const LayerParams& params); + bool fusedActivation = false; + bool fusedAdd = false; + bool useWinograd = true; // Flag whether to use Winograd to speed up 3x3 convolution. + }; + + class CV_EXPORTS ConvolutionLayerInt8 : public BaseConvolutionLayer + { + public: + int input_zp, output_zp; + float input_sc, output_sc; + + // quantization type flag. The perChannel default is true, that means it contains the parameters + // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. + bool per_channel; + bool useWinograd = false; // Flag whether to use Winograd to speed up 3x3 convolution. + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS DeconvolutionLayer : public BaseConvolutionLayer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS LRNLayer : public Layer + { + public: + int type; + + int size; + float alpha, beta, bias; + bool normBySize; + + static Ptr create(const LayerParams& params); + }; + + + /** @brief ArgMax/ArgMin layer + * @note returns indices as floats, which means the supported range is [-2^24; 2^24] + */ + class CV_EXPORTS ArgLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** @brief Gather layer + */ + class CV_EXPORTS GatherLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** @brief GatherElements layer + * GatherElements takes two inputs data and indices of the same rank r >= 1 and an optional attribute axis and works such that: + * output[i][j][k] = data[index[i][j][k]][j][k] if axis = 0 and r = 3 + * output[i][j][k] = data[i][index[i][j][k]][k] if axis = 1 and r = 3 + * output[i][j][k] = data[i][j][index[i][j][k]] if axis = 2 and r = 3 + * + * Gather, on the other hand, takes a data tensor of rank r >= 1, and indices tensor of rank q, and works such that: + * it gathers the enteries along axis dimension of the input data indexed by indices and concatenates them in an output tensor of rank q + (r - 1) + * e.g. If axis = 0, let k = indices[i_{0}, ..., i_{q-1}] then output[i_{0}, ..., i_{q-1}, j_{0}, ..., j_{r-2}] = input[k , j_{0}, ..., j_{r-2}]: + **/ + class CV_EXPORTS GatherElementsLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS PoolingLayer : public Layer + { + public: + int type; + std::vector kernel_size, strides; + std::vector pads_begin, pads_end; + bool globalPooling; //!< Flag is true if at least one of the axes is global pooled. + std::vector isGlobalPooling; + bool computeMaxIdx; + String padMode; + bool ceilMode; + // If true for average pooling with padding, divide an every output region + // by a whole kernel area. Otherwise exclude zero padded values and divide + // by number of real values. + bool avePoolPaddedArea; + // ROIPooling parameters. + Size pooledSize; + float spatialScale; + // PSROIPooling parameters. + int psRoiOutChannels; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS PoolingLayerInt8 : public PoolingLayer + { + public: + int input_zp, output_zp; + float input_sc, output_sc; + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ReduceLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS SoftmaxLayer : public Layer + { + public: + bool logSoftMax; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS SoftmaxLayerInt8 : public SoftmaxLayer + { + public: + float output_sc; + int output_zp; + static Ptr create(const LayerParams& params); + }; + + /** + * `InnerProduct`, `MatMul` and `Gemm` operations are all implemented by Fully Connected Layer. + * Parameter `is_matmul` is used to distinguish `MatMul` and `Gemm` from `InnerProduct`. + */ + class CV_EXPORTS InnerProductLayer : public Layer + { + public: + int axis; + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS InnerProductLayerInt8 : public InnerProductLayer + { + public: + int input_zp, output_zp; + float input_sc, output_sc; + + // quantization type flag. The perChannel default is true, that means it contains the parameters + // of per-Channel quantization. Otherwise, that means this layer contains per-Tensor quantized parameters. + bool per_channel; + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS MVNLayer : public Layer + { + public: + float eps; + bool normVariance, acrossChannels; + + static Ptr create(const LayerParams& params); + }; + + /* Reshaping */ + + class CV_EXPORTS ReshapeLayer : public Layer + { + public: + MatShape newShapeDesc; + Range newShapeRange; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS FlattenLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS QuantizeLayer : public Layer + { + public: + std::vector scales; + std::vector zeropoints; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS DequantizeLayer : public Layer + { + public: + std::vector scales; + std::vector zeropoints; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS RequantizeLayer : public Layer + { + public: + float scale, shift; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ConcatLayer : public Layer + { + public: + int axis; + /** + * @brief Add zero padding in case of concatenation of blobs with different + * spatial sizes. + * + * Details: https://github.com/torch/nn/blob/master/doc/containers.md#depthconcat + */ + bool padding; + int paddingValue; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SplitLayer : public Layer + { + public: + int outputsCount; //!< Number of copies that will be produced (is ignored when negative). + + static Ptr create(const LayerParams ¶ms); + }; + + /** + * Slice layer has several modes: + * 1. Caffe mode + * @param[in] axis Axis of split operation + * @param[in] slice_point Array of split points + * + * Number of output blobs equals to number of split points plus one. The + * first blob is a slice on input from 0 to @p slice_point[0] - 1 by @p axis, + * the second output blob is a slice of input from @p slice_point[0] to + * @p slice_point[1] - 1 by @p axis and the last output blob is a slice of + * input from @p slice_point[-1] up to the end of @p axis size. + * + * 2. TensorFlow mode + * @param begin Vector of start indices + * @param size Vector of sizes + * + * More convenient numpy-like slice. One and only output blob + * is a slice `input[begin[0]:begin[0]+size[0], begin[1]:begin[1]+size[1], ...]` + * + * 3. Torch mode + * @param axis Axis of split operation + * + * Split input blob on the equal parts by @p axis. + */ + class CV_EXPORTS SliceLayer : public Layer + { + public: + /** + * @brief Vector of slice ranges. + * + * The first dimension equals number of output blobs. + * Inner vector has slice ranges for the first number of input dimensions. + */ + std::vector > sliceRanges; + std::vector > sliceSteps; + int axis; + int num_split; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS PermuteLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** + * Permute channels of 4-dimensional input blob. + * @param group Number of groups to split input channels and pick in turns + * into output blob. + * + * \f[ groupSize = \frac{number\ of\ channels}{group} \f] + * \f[ output(n, c, h, w) = input(n, groupSize \times (c \% group) + \lfloor \frac{c}{group} \rfloor, h, w) \f] + * Read more at https://arxiv.org/pdf/1707.01083.pdf + */ + class CV_EXPORTS ShuffleChannelLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + + int group; + }; + + /** + * @brief Adds extra values for specific axes. + * @param paddings Vector of paddings in format + * @code + * [ pad_before, pad_after, // [0]th dimension + * pad_before, pad_after, // [1]st dimension + * ... + * pad_before, pad_after ] // [n]th dimension + * @endcode + * that represents number of padded values at every dimension + * starting from the first one. The rest of dimensions won't + * be padded. + * @param value Value to be padded. Defaults to zero. + * @param type Padding type: 'constant', 'reflect' + * @param input_dims Torch's parameter. If @p input_dims is not equal to the + * actual input dimensionality then the `[0]th` dimension + * is considered as a batch dimension and @p paddings are shifted + * to a one dimension. Defaults to `-1` that means padding + * corresponding to @p paddings. + */ + class CV_EXPORTS PaddingLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /* Activations */ + class CV_EXPORTS ActivationLayer : public Layer + { + public: + virtual void forwardSlice(const float* src, float* dst, int len, + size_t outPlaneSize, int cn0, int cn1) const {} + virtual void forwardSlice(const int* src, const int* lut, int* dst, int len, + size_t outPlaneSize, int cn0, int cn1) const {} + virtual void forwardSlice(const int8_t* src, const int8_t* lut, int8_t* dst, int len, + size_t outPlaneSize, int cn0, int cn1) const {} + }; + + class CV_EXPORTS ReLULayer : public ActivationLayer + { + public: + float negativeSlope; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ReLU6Layer : public ActivationLayer + { + public: + float minValue, maxValue; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ChannelsPReLULayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ELULayer : public ActivationLayer + { + public: + float alpha; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS TanHLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SwishLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS MishLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SigmoidLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS BNLLLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AbsLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS PowerLayer : public ActivationLayer + { + public: + float power, scale, shift; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ExpLayer : public ActivationLayer + { + public: + float base, scale, shift; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CeilLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS FloorLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS LogLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS RoundLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SqrtLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS NotLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AcosLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AcoshLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AsinLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AsinhLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AtanLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AtanhLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CosLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CoshLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ErfLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS HardSwishLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SinLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SinhLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SoftplusLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SoftsignLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS TanLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS CeluLayer : public ActivationLayer + { + public: + float alpha; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS HardSigmoidLayer : public ActivationLayer + { + public: + float alpha; + float beta; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SeluLayer : public ActivationLayer + { + public: + float alpha; + float gamma; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS GeluLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS GeluApproximationLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ThresholdedReluLayer : public ActivationLayer + { + public: + float alpha; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ActivationLayerInt8 : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SignLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ShrinkLayer : public ActivationLayer + { + public: + float bias; + float lambd; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ReciprocalLayer : public ActivationLayer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + /* Layers used in semantic segmentation */ + + class CV_EXPORTS CropLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + /** @brief Element wise operation on inputs + + Extra optional parameters: + - "operation" as string. Values are "sum" (default), "prod", "max", "div", "min" + - "coeff" as float array. Specify weights of inputs for SUM operation + - "output_channels_mode" as string. Values are "same" (default, all input must have the same layout), "input_0", "input_0_truncate", "max_input_channels" + */ + class CV_EXPORTS EltwiseLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS EltwiseLayerInt8 : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS NaryEltwiseLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS BatchNormLayer : public ActivationLayer + { + public: + bool hasWeights, hasBias; + float epsilon; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS BatchNormLayerInt8 : public BatchNormLayer + { + public: + float input_sc, output_sc; + int input_zp, output_zp; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS MaxUnpoolLayer : public Layer + { + public: + Size poolKernel; + Size poolPad; + Size poolStride; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ScaleLayer : public Layer + { + public: + bool hasBias; + int axis; + String mode; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ScaleLayerInt8 : public ScaleLayer + { + public: + float output_sc; + int output_zp; + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ShiftLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ShiftLayerInt8 : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CompareLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS DataAugmentationLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CorrelationLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS AccumLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS FlowWarpLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS PriorBoxLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ReorgLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS RegionLayer : public Layer + { + public: + float nmsThreshold; + + static Ptr create(const LayerParams& params); + }; + + /** + * @brief Detection output layer. + * + * The layer size is: @f$ (1 \times 1 \times N \times 7) @f$ + * where N is [keep_top_k] parameter multiplied by batch size. Each row is: + * [image_id, label, confidence, xmin, ymin, xmax, ymax] + * where image_id is the index of image input in the batch. + */ + class CV_EXPORTS DetectionOutputLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** + * @brief \f$ L_p \f$ - normalization layer. + * @param p Normalization factor. The most common `p = 1` for \f$ L_1 \f$ - + * normalization or `p = 2` for \f$ L_2 \f$ - normalization or a custom one. + * @param eps Parameter \f$ \epsilon \f$ to prevent a division by zero. + * @param across_spatial If true, normalize an input across all non-batch dimensions. + * Otherwise normalize an every channel separately. + * + * Across spatial: + * @f[ + * norm = \sqrt[p]{\epsilon + \sum_{x, y, c} |src(x, y, c)|^p } \\ + * dst(x, y, c) = \frac{ src(x, y, c) }{norm} + * @f] + * + * Channel wise normalization: + * @f[ + * norm(c) = \sqrt[p]{\epsilon + \sum_{x, y} |src(x, y, c)|^p } \\ + * dst(x, y, c) = \frac{ src(x, y, c) }{norm(c)} + * @f] + * + * Where `x, y` - spatial coordinates, `c` - channel. + * + * An every sample in the batch is normalized separately. Optionally, + * output is scaled by the trained parameters. + */ + class CV_EXPORTS NormalizeBBoxLayer : public Layer + { + public: + float pnorm, epsilon; + CV_DEPRECATED_EXTERNAL bool acrossSpatial; + + static Ptr create(const LayerParams& params); + }; + + /** + * @brief Resize input 4-dimensional blob by nearest neighbor or bilinear strategy. + * + * Layer is used to support TensorFlow's resize_nearest_neighbor and resize_bilinear ops. + */ + class CV_EXPORTS ResizeLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + /** + * @brief Bilinear resize layer from https://github.com/cdmh/deeplab-public-ver2 + * + * It differs from @ref ResizeLayer in output shape and resize scales computations. + */ + class CV_EXPORTS InterpLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ProposalLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CropAndResizeLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS CumSumLayer : public Layer + { + public: + int exclusive; + int reverse; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ScatterLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS ScatterNDLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS TileLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS LayerNormLayer : public Layer + { + public: + CV_DEPRECATED_EXTERNAL bool hasBias; // Deprecated, preserve for compatibility + int axis; + float epsilon; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS GemmLayer : public Layer { + public: + bool trans_a; + bool trans_b; + float alpha; + float beta; + + static Ptr create(const LayerParams& params); + }; + + class CV_EXPORTS MatMulLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS ExpandLayer : public Layer + { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS InstanceNormLayer : public Layer { + public: + float epsilon; + + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS AttentionLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS GroupNormLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS DepthToSpaceLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS SpaceToDepthLayer : public Layer { + public: + static Ptr create(const LayerParams ¶ms); + }; + + class CV_EXPORTS TopKLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + +//! @} +//! @} +CV__DNN_INLINE_NS_END +} +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp index 938b4e7df6..059ce9b28e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/dict.hpp @@ -1,160 +1,160 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#include -#include -#include - -#include - -#ifndef OPENCV_DNN_DNN_DICT_HPP -#define OPENCV_DNN_DNN_DICT_HPP - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ - -/** @brief This struct stores the scalar value (or array) of one of the following type: double, cv::String or int64. - * @todo Maybe int64 is useless because double type exactly stores at least 2^52 integers. - */ -struct CV_EXPORTS_W DictValue -{ - DictValue(const DictValue &r); - explicit DictValue(bool i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i ? 1 : 0; } //!< Constructs integer scalar - explicit DictValue(int64 i = 0) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar - CV_WRAP explicit DictValue(int i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar - explicit DictValue(unsigned p) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = p; } //!< Constructs integer scalar - CV_WRAP explicit DictValue(double p) : type(Param::REAL), pd(new AutoBuffer) { (*pd)[0] = p; } //!< Constructs floating point scalar - CV_WRAP explicit DictValue(const String &s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< Constructs string scalar - explicit DictValue(const char *s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< @overload - - template - static DictValue arrayInt(TypeIter begin, int size); //!< Constructs integer array - template - static DictValue arrayReal(TypeIter begin, int size); //!< Constructs floating point array - template - static DictValue arrayString(TypeIter begin, int size); //!< Constructs array of strings - - template - T get(int idx = -1) const; //!< Tries to convert array element with specified index to requested type and returns its. - - int size() const; - - CV_WRAP bool isInt() const; - CV_WRAP bool isString() const; - CV_WRAP bool isReal() const; - - CV_WRAP int getIntValue(int idx = -1) const; - CV_WRAP double getRealValue(int idx = -1) const; - CV_WRAP String getStringValue(int idx = -1) const; - - DictValue &operator=(const DictValue &r); - - friend std::ostream &operator<<(std::ostream &stream, const DictValue &dictv); - - ~DictValue(); - -private: - - Param type; - - union - { - AutoBuffer *pi; - AutoBuffer *pd; - AutoBuffer *ps; - void *pv; - }; - - DictValue(Param _type, void *_p) : type(_type), pv(_p) {} - void release(); -}; - -/** @brief This class implements name-value dictionary, values are instances of DictValue. */ -class CV_EXPORTS Dict -{ - typedef std::map _Dict; - _Dict dict; - -public: - - //! Checks a presence of the @p key in the dictionary. - bool has(const String &key) const; - - //! If the @p key in the dictionary then returns pointer to its value, else returns NULL. - DictValue *ptr(const String &key); - - /** @overload */ - const DictValue *ptr(const String &key) const; - - //! If the @p key in the dictionary then returns its value, else an error will be generated. - const DictValue &get(const String &key) const; - - /** @overload */ - template - T get(const String &key) const; - - //! If the @p key in the dictionary then returns its value, else returns @p defaultValue. - template - T get(const String &key, const T &defaultValue) const; - - //! Sets new @p value for the @p key, or adds new key-value pair into the dictionary. - template - const T &set(const String &key, const T &value); - - //! Erase @p key from the dictionary. - void erase(const String &key); - - friend std::ostream &operator<<(std::ostream &stream, const Dict &dict); - - std::map::const_iterator begin() const; - - std::map::const_iterator end() const; -}; - -//! @} -CV__DNN_INLINE_NS_END -} -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#include +#include +#include + +#include + +#ifndef OPENCV_DNN_DNN_DICT_HPP +#define OPENCV_DNN_DNN_DICT_HPP + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ + +/** @brief This struct stores the scalar value (or array) of one of the following type: double, cv::String or int64. + * @todo Maybe int64 is useless because double type exactly stores at least 2^52 integers. + */ +struct CV_EXPORTS_W DictValue +{ + DictValue(const DictValue &r); + explicit DictValue(bool i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i ? 1 : 0; } //!< Constructs integer scalar + explicit DictValue(int64 i = 0) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar + CV_WRAP explicit DictValue(int i) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = i; } //!< Constructs integer scalar + explicit DictValue(unsigned p) : type(Param::INT), pi(new AutoBuffer) { (*pi)[0] = p; } //!< Constructs integer scalar + CV_WRAP explicit DictValue(double p) : type(Param::REAL), pd(new AutoBuffer) { (*pd)[0] = p; } //!< Constructs floating point scalar + CV_WRAP explicit DictValue(const String &s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< Constructs string scalar + explicit DictValue(const char *s) : type(Param::STRING), ps(new AutoBuffer) { (*ps)[0] = s; } //!< @overload + + template + static DictValue arrayInt(TypeIter begin, int size); //!< Constructs integer array + template + static DictValue arrayReal(TypeIter begin, int size); //!< Constructs floating point array + template + static DictValue arrayString(TypeIter begin, int size); //!< Constructs array of strings + + template + T get(int idx = -1) const; //!< Tries to convert array element with specified index to requested type and returns its. + + int size() const; + + CV_WRAP bool isInt() const; + CV_WRAP bool isString() const; + CV_WRAP bool isReal() const; + + CV_WRAP int getIntValue(int idx = -1) const; + CV_WRAP double getRealValue(int idx = -1) const; + CV_WRAP String getStringValue(int idx = -1) const; + + DictValue &operator=(const DictValue &r); + + friend std::ostream &operator<<(std::ostream &stream, const DictValue &dictv); + + ~DictValue(); + +private: + + Param type; + + union + { + AutoBuffer *pi; + AutoBuffer *pd; + AutoBuffer *ps; + void *pv; + }; + + DictValue(Param _type, void *_p) : type(_type), pv(_p) {} + void release(); +}; + +/** @brief This class implements name-value dictionary, values are instances of DictValue. */ +class CV_EXPORTS Dict +{ + typedef std::map _Dict; + _Dict dict; + +public: + + //! Checks a presence of the @p key in the dictionary. + bool has(const String &key) const; + + //! If the @p key in the dictionary then returns pointer to its value, else returns NULL. + DictValue *ptr(const String &key); + + /** @overload */ + const DictValue *ptr(const String &key) const; + + //! If the @p key in the dictionary then returns its value, else an error will be generated. + const DictValue &get(const String &key) const; + + /** @overload */ + template + T get(const String &key) const; + + //! If the @p key in the dictionary then returns its value, else returns @p defaultValue. + template + T get(const String &key, const T &defaultValue) const; + + //! Sets new @p value for the @p key, or adds new key-value pair into the dictionary. + template + const T &set(const String &key, const T &value); + + //! Erase @p key from the dictionary. + void erase(const String &key); + + friend std::ostream &operator<<(std::ostream &stream, const Dict &dict); + + std::map::const_iterator begin() const; + + std::map::const_iterator end() const; +}; + +//! @} +CV__DNN_INLINE_NS_END +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp index 105e973193..0077ae4853 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.hpp @@ -1,1946 +1,1946 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_HPP -#define OPENCV_DNN_DNN_HPP - -#include -#include -#include "opencv2/core/async.hpp" - -#include "../dnn/version.hpp" - -#include - -namespace cv { -namespace dnn { - -namespace accessor { -class DnnNetAccessor; // forward declaration -} - -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ - - typedef std::vector MatShape; - - /** - * @brief Enum of computation backends supported by layers. - * @see Net::setPreferableBackend - */ - enum Backend - { - //! DNN_BACKEND_DEFAULT equals to OPENCV_DNN_BACKEND_DEFAULT, which can be defined using CMake or a configuration parameter - DNN_BACKEND_DEFAULT = 0, - DNN_BACKEND_HALIDE, - DNN_BACKEND_INFERENCE_ENGINE, //!< Intel OpenVINO computational backend - //!< @note Tutorial how to build OpenCV with OpenVINO: @ref tutorial_dnn_openvino - DNN_BACKEND_OPENCV, - DNN_BACKEND_VKCOM, - DNN_BACKEND_CUDA, - DNN_BACKEND_WEBNN, - DNN_BACKEND_TIMVX, - DNN_BACKEND_CANN, -#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) -#if !defined(OPENCV_BINDING_PARSER) - DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() - DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() -#endif -#endif - }; - - /** - * @brief Enum of target devices for computations. - * @see Net::setPreferableTarget - */ - enum Target - { - DNN_TARGET_CPU = 0, - DNN_TARGET_OPENCL, - DNN_TARGET_OPENCL_FP16, - DNN_TARGET_MYRIAD, - DNN_TARGET_VULKAN, - DNN_TARGET_FPGA, //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin. - DNN_TARGET_CUDA, - DNN_TARGET_CUDA_FP16, - DNN_TARGET_HDDL, - DNN_TARGET_NPU, - DNN_TARGET_CPU_FP16, // Only the ARM platform is supported. Low precision computing, accelerate model inference. - }; - - /** - * @brief Enum of data layout for model inference. - * @see Image2BlobParams - */ - enum DataLayout - { - DNN_LAYOUT_UNKNOWN = 0, - DNN_LAYOUT_ND = 1, //!< OpenCV data layout for 2D data. - DNN_LAYOUT_NCHW = 2, //!< OpenCV data layout for 4D data. - DNN_LAYOUT_NCDHW = 3, //!< OpenCV data layout for 5D data. - DNN_LAYOUT_NHWC = 4, //!< Tensorflow-like data layout for 4D data. - DNN_LAYOUT_NDHWC = 5, //!< Tensorflow-like data layout for 5D data. - DNN_LAYOUT_PLANAR = 6, //!< Tensorflow-like data layout, it should only be used at tf or tflite model parsing. - }; - - CV_EXPORTS std::vector< std::pair > getAvailableBackends(); - CV_EXPORTS_W std::vector getAvailableTargets(dnn::Backend be); - - /** - * @brief Enables detailed logging of the DNN model loading with CV DNN API. - * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set. - * - * Diagnostic mode provides detailed logging of the model loading stage to explore - * potential problems (ex.: not implemented layer type). - * - * @note In diagnostic mode series of assertions will be skipped, it can lead to the - * expected application crash. - */ - CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode); - - /** @brief This class provides all data needed to initialize layer. - * - * It includes dictionary with scalar params (which can be read by using Dict interface), - * blob params #blobs and optional meta information: #name and #type of layer instance. - */ - class CV_EXPORTS LayerParams : public Dict - { - public: - //TODO: Add ability to name blob params - std::vector blobs; //!< List of learned parameters stored as blobs. - - String name; //!< Name of the layer instance (optional, can be used internal purposes). - String type; //!< Type name which was used for creating layer by layer factory (optional). - }; - - /** - * @brief Derivatives of this class encapsulates functions of certain backends. - */ - class BackendNode - { - public: - explicit BackendNode(int backendId); - - virtual ~BackendNode(); //!< Virtual destructor to make polymorphism. - - int backendId; //!< Backend identifier. - }; - - /** - * @brief Derivatives of this class wraps cv::Mat for different backends and targets. - */ - class BackendWrapper - { - public: - BackendWrapper(int backendId, int targetId); - - /** - * @brief Wrap cv::Mat for specific backend and target. - * @param[in] targetId Target identifier. - * @param[in] m cv::Mat for wrapping. - * - * Make CPU->GPU data transfer if it's require for the target. - */ - BackendWrapper(int targetId, const cv::Mat& m); - - /** - * @brief Make wrapper for reused cv::Mat. - * @param[in] base Wrapper of cv::Mat that will be reused. - * @param[in] shape Specific shape. - * - * Initialize wrapper from another one. It'll wrap the same host CPU - * memory and mustn't allocate memory on device(i.e. GPU). It might - * has different shape. Use in case of CPU memory reusing for reuse - * associated memory on device too. - */ - BackendWrapper(const Ptr& base, const MatShape& shape); - - virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism. - - /** - * @brief Transfer data to CPU host memory. - */ - virtual void copyToHost() = 0; - - /** - * @brief Indicate that an actual data is on CPU. - */ - virtual void setHostDirty() = 0; - - int backendId; //!< Backend identifier. - int targetId; //!< Target identifier. - }; - - class CV_EXPORTS ActivationLayer; - - /** @brief This interface class allows to build new Layers - are building blocks of networks. - * - * Each class, derived from Layer, must implement forward() method to compute outputs. - * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros. - */ - class CV_EXPORTS_W Layer : public Algorithm - { - public: - - //! List of learned parameters must be stored here to allow read them by using Net::getParam(). - CV_PROP_RW std::vector blobs; - - /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. - * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead - * @param[in] input vector of already allocated input blobs - * @param[out] output vector of already allocated output blobs - * - * This method is called after network has allocated all memory for input and output blobs - * and before inferencing. - */ - CV_DEPRECATED_EXTERNAL - virtual void finalize(const std::vector &input, std::vector &output); - - /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. - * @param[in] inputs vector of already allocated input blobs - * @param[out] outputs vector of already allocated output blobs - * - * This method is called after network has allocated all memory for input and output blobs - * and before inferencing. - */ - CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs); - - /** @brief Given the @p input blobs, computes the output @p blobs. - * @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead - * @param[in] input the input blobs. - * @param[out] output allocated output blobs, which will store results of the computation. - * @param[out] internals allocated internal blobs - */ - CV_DEPRECATED_EXTERNAL - virtual void forward(std::vector &input, std::vector &output, std::vector &internals); - - /** @brief Given the @p input blobs, computes the output @p blobs. - * @param[in] inputs the input blobs. - * @param[out] outputs allocated output blobs, which will store results of the computation. - * @param[out] internals allocated internal blobs - */ - virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); - - /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation. - * @param[in] scales input and output scales. - * @param[in] zeropoints input and output zeropoints. - * @param[out] params Quantized parameters required for fixed point implementation of that layer. - * @returns True if layer can be quantized. - */ - virtual bool tryQuantize(const std::vector > &scales, - const std::vector > &zeropoints, LayerParams& params); - - /** @brief Given the @p input blobs, computes the output @p blobs. - * @param[in] inputs the input blobs. - * @param[out] outputs allocated output blobs, which will store results of the computation. - * @param[out] internals allocated internal blobs - */ - void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); - - /** @brief - * @overload - * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead - */ - CV_DEPRECATED_EXTERNAL - void finalize(const std::vector &inputs, CV_OUT std::vector &outputs); - - /** @brief - * @overload - * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead - */ - CV_DEPRECATED std::vector finalize(const std::vector &inputs); - - /** @brief Allocates layer and computes output. - * @deprecated This method will be removed in the future release. - */ - CV_DEPRECATED CV_WRAP void run(const std::vector &inputs, CV_OUT std::vector &outputs, - CV_IN_OUT std::vector &internals); - - /** @brief Returns index of input blob into the input array. - * @param inputName label of input blob - * - * Each layer input and output can be labeled to easily identify them using "%[.output_name]" notation. - * This method maps label of input blob to its index into input vector. - */ - virtual int inputNameToIndex(String inputName); // FIXIT const - /** @brief Returns index of output blob in output array. - * @see inputNameToIndex() - */ - CV_WRAP virtual int outputNameToIndex(const String& outputName); // FIXIT const - - /** - * @brief Ask layer if it support specific backend for doing computations. - * @param[in] backendId computation backend identifier. - * @see Backend - */ - virtual bool supportBackend(int backendId); // FIXIT const - - /** - * @brief Returns Halide backend node. - * @param[in] inputs Input Halide buffers. - * @see BackendNode, BackendWrapper - * - * Input buffers should be exactly the same that will be used in forward invocations. - * Despite we can use Halide::ImageParam based on input shape only, - * it helps prevent some memory management issues (if something wrong, - * Halide tests will be failed). - */ - virtual Ptr initHalide(const std::vector > &inputs); - - virtual Ptr initNgraph(const std::vector > &inputs, const std::vector >& nodes); - - virtual Ptr initVkCom(const std::vector > &inputs, std::vector > &outputs); - - virtual Ptr initWebnn(const std::vector > &inputs, const std::vector >& nodes); - - /** - * @brief Returns a CUDA backend node - * - * @param context void pointer to CSLContext object - * @param inputs layer inputs - * @param outputs layer outputs - */ - virtual Ptr initCUDA( - void *context, - const std::vector>& inputs, - const std::vector>& outputs - ); - - /** - * @brief Returns a TimVX backend node - * - * @param timVxInfo void pointer to CSLContext object - * @param inputsWrapper layer inputs - * @param outputsWrapper layer outputs - * @param isLast if the node is the last one of the TimVX Graph. - */ - virtual Ptr initTimVX(void* timVxInfo, - const std::vector > &inputsWrapper, - const std::vector > &outputsWrapper, - bool isLast); - - /** - * @brief Returns a CANN backend node - * - * @param inputs input tensors of CANN operator - * @param outputs output tensors of CANN operator - * @param nodes nodes of input tensors - */ - virtual Ptr initCann(const std::vector > &inputs, - const std::vector > &outputs, - const std::vector >& nodes); - - /** - * @brief Automatic Halide scheduling based on layer hyper-parameters. - * @param[in] node Backend node with Halide functions. - * @param[in] inputs Blobs that will be used in forward invocations. - * @param[in] outputs Blobs that will be used in forward invocations. - * @param[in] targetId Target identifier - * @see BackendNode, Target - * - * Layer don't use own Halide::Func members because we can have applied - * layers fusing. In this way the fused function should be scheduled. - */ - virtual void applyHalideScheduler(Ptr& node, - const std::vector &inputs, - const std::vector &outputs, - int targetId) const; - - /** - * @brief Implement layers fusing. - * @param[in] node Backend node of bottom layer. - * @see BackendNode - * - * Actual for graph-based backends. If layer attached successfully, - * returns non-empty cv::Ptr to node of the same backend. - * Fuse only over the last function. - */ - virtual Ptr tryAttach(const Ptr& node); - - /** - * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case. - * @param[in] layer The subsequent activation layer. - * - * Returns true if the activation layer has been attached successfully. - */ - virtual bool setActivation(const Ptr& layer); - - /** - * @brief Try to fuse current layer with a next one - * @param[in] top Next layer to be fused. - * @returns True if fusion was performed. - */ - virtual bool tryFuse(Ptr& top); - - /** - * @brief Returns parameters of layers with channel-wise multiplication and addition. - * @param[out] scale Channel-wise multipliers. Total number of values should - * be equal to number of channels. - * @param[out] shift Channel-wise offsets. Total number of values should - * be equal to number of channels. - * - * Some layers can fuse their transformations with further layers. - * In example, convolution + batch normalization. This way base layer - * use weights from layer after it. Fused layer is skipped. - * By default, @p scale and @p shift are empty that means layer has no - * element-wise multiplications or additions. - */ - virtual void getScaleShift(Mat& scale, Mat& shift) const; - - /** - * @brief Returns scale and zeropoint of layers - * @param[out] scale Output scale - * @param[out] zeropoint Output zeropoint - * - * By default, @p scale is 1 and @p zeropoint is 0. - */ - virtual void getScaleZeropoint(float& scale, int& zeropoint) const; - - - /** - * @brief "Detaches" all the layers, attached to particular layer. - */ - virtual void unsetAttached(); - - virtual bool getMemoryShapes(const std::vector &inputs, - const int requiredOutputs, - std::vector &outputs, - std::vector &internals) const; - - virtual int64 getFLOPS(const std::vector &inputs, - const std::vector &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;} - - virtual bool updateMemoryShapes(const std::vector &inputs); - - CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes. - CV_PROP String type; //!< Type name which was used for creating layer by layer factory. - CV_PROP int preferableTarget; //!< prefer target for layer forwarding - - Layer(); - explicit Layer(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. - void setParamsFrom(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. - virtual ~Layer(); - }; - - /** @brief This class allows to create and manipulate comprehensive artificial neural networks. - * - * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances, - * and edges specify relationships between layers inputs and outputs. - * - * Each network layer has unique integer id and unique string name inside its network. - * LayerId can store either layer name or layer id. - * - * This class supports reference counting of its instances, i. e. copies point to the same instance. - */ - class CV_EXPORTS_W_SIMPLE Net - { - public: - - CV_WRAP Net(); //!< Default constructor. - CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore. - - /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR). - * @param[in] xml XML configuration file with network's topology. - * @param[in] bin Binary file with trained weights. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_WRAP static Net readFromModelOptimizer(CV_WRAP_FILE_PATH const String& xml, CV_WRAP_FILE_PATH const String& bin); - - /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). - * @param[in] bufferModelConfig buffer with model's configuration. - * @param[in] bufferWeights buffer with model's trained weights. - * @returns Net object. - */ - CV_WRAP static - Net readFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); - - /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). - * @param[in] bufferModelConfigPtr buffer pointer of model's configuration. - * @param[in] bufferModelConfigSize buffer size of model's configuration. - * @param[in] bufferWeightsPtr buffer pointer of model's trained weights. - * @param[in] bufferWeightsSize buffer size of model's trained weights. - * @returns Net object. - */ - static - Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, - const uchar* bufferWeightsPtr, size_t bufferWeightsSize); - - /** Returns true if there are no layers in the network. */ - CV_WRAP bool empty() const; - - /** @brief Dump net to String - * @returns String with structure, hyperparameters, backend, target and fusion - * Call method after setInput(). To see correct backend, target and fusion run after forward(). - */ - CV_WRAP String dump(); - /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file - * @param path path to output file with .dot extension - * @see dump() - */ - CV_WRAP void dumpToFile(CV_WRAP_FILE_PATH const String& path); - /** @brief Dump net structure, hyperparameters, backend, target and fusion to pbtxt file - * @param path path to output file with .pbtxt extension - * - * Use Netron (https://netron.app) to open the target file to visualize the model. - * Call method after setInput(). To see correct backend, target and fusion run after forward(). - */ - CV_WRAP void dumpToPbtxt(CV_WRAP_FILE_PATH const String& path); - - /** @brief Adds new layer to the net. - * @param name unique name of the adding layer. - * @param type typename of the adding layer (type must be registered in LayerRegister). - * @param dtype datatype of output blobs. - * @param params parameters which will be used to initialize the creating layer. - * @returns unique identifier of created layer, or -1 if a failure will happen. - */ - CV_WRAP int addLayer(const String &name, const String &type, const int &dtype, LayerParams ¶ms); - - /** @overload Datatype of output blobs set to default CV_32F */ - int addLayer(const String &name, const String &type, LayerParams ¶ms); - - /** @brief Adds new layer and connects its first input to the first output of previously added layer. - * @see addLayer() - */ - CV_WRAP int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams ¶ms); - - /** @overload */ - int addLayerToPrev(const String &name, const String &type, LayerParams ¶ms); - - /** @brief Converts string name of the layer to the integer identifier. - * @returns id of the layer, or -1 if the layer wasn't found. - */ - CV_WRAP int getLayerId(const String &layer) const; - - CV_WRAP std::vector getLayerNames() const; - - /** @brief Container for strings and integers. - * - * @deprecated Use getLayerId() with int result. - */ - typedef DictValue LayerId; - - /** @brief Returns pointer to layer with specified id or name which the network use. */ - CV_WRAP Ptr getLayer(int layerId) const; - /** @overload - * @deprecated Use int getLayerId(const String &layer) - */ - CV_WRAP inline Ptr getLayer(const String& layerName) const { return getLayer(getLayerId(layerName)); } - /** @overload - * @deprecated to be removed - */ - CV_WRAP Ptr getLayer(const LayerId& layerId) const; - - /** @brief Returns pointers to input layers of specific layer. */ - std::vector > getLayerInputs(int layerId) const; // FIXIT: CV_WRAP - - /** @brief Connects output of the first layer to input of the second layer. - * @param outPin descriptor of the first layer output. - * @param inpPin descriptor of the second layer input. - * - * Descriptors have the following template <layer_name>[.input_number]: - * - the first part of the template layer_name is string name of the added layer. - * If this part is empty then the network input pseudo layer will be used; - * - the second optional part of the template input_number - * is either number of the layer input, either label one. - * If this part is omitted then the first layer input will be used. - * - * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex() - */ - CV_WRAP void connect(String outPin, String inpPin); - - /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer. - * @param outLayerId identifier of the first layer - * @param outNum number of the first layer output - * @param inpLayerId identifier of the second layer - * @param inpNum number of the second layer input - */ - void connect(int outLayerId, int outNum, int inpLayerId, int inpNum); - - /** @brief Registers network output with name - * - * Function may create additional 'Identity' layer. - * - * @param outputName identifier of the output - * @param layerId identifier of the second layer - * @param outputPort number of the second layer input - * - * @returns index of bound layer (the same as layerId or newly created) - */ - int registerOutput(const std::string& outputName, int layerId, int outputPort); - - /** @brief Sets outputs names of the network input pseudo layer. - * - * Each net always has special own the network input pseudo layer with id=0. - * This layer stores the user blobs only and don't make any computations. - * In fact, this layer provides the only way to pass user data into the network. - * As any other layer, this layer can label its outputs and this function provides an easy way to do this. - */ - CV_WRAP void setInputsNames(const std::vector &inputBlobNames); - - /** @brief Specify shape of network input. - */ - CV_WRAP void setInputShape(const String &inputName, const MatShape& shape); - - /** @brief Runs forward pass to compute output of layer with name @p outputName. - * @param outputName name for layer which output is needed to get - * @return blob for first output of specified layer. - * @details By default runs forward pass for the whole network. - */ - CV_WRAP Mat forward(const String& outputName = String()); - - /** @brief Runs forward pass to compute output of layer with name @p outputName. - * @param outputName name for layer which output is needed to get - * @details By default runs forward pass for the whole network. - * - * This is an asynchronous version of forward(const String&). - * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required. - */ - CV_WRAP AsyncArray forwardAsync(const String& outputName = String()); - - /** @brief Runs forward pass to compute output of layer with name @p outputName. - * @param outputBlobs contains all output blobs for specified layer. - * @param outputName name for layer which output is needed to get - * @details If @p outputName is empty, runs forward pass for the whole network. - */ - CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, const String& outputName = String()); - - /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. - * @param outputBlobs contains blobs for first outputs of specified layers. - * @param outBlobNames names for layers which outputs are needed to get - */ - CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, - const std::vector& outBlobNames); - - /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. - * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames. - * @param outBlobNames names for layers which outputs are needed to get - */ - CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector >& outputBlobs, - const std::vector& outBlobNames); - - /** @brief Returns a quantized Net from a floating-point Net. - * @param calibData Calibration data to compute the quantization parameters. - * @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S. - * @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S. - * @param perChannel Quantization granularity of quantized Net. The default is true, that means quantize model - * in per-channel way (channel-wise). Set it false to quantize model in per-tensor way (or tensor-wise). - */ - CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype, bool perChannel=true); - - /** @brief Returns input scale and zeropoint for a quantized Net. - * @param scales output parameter for returning input scales. - * @param zeropoints output parameter for returning input zeropoints. - */ - CV_WRAP void getInputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; - - /** @brief Returns output scale and zeropoint for a quantized Net. - * @param scales output parameter for returning output scales. - * @param zeropoints output parameter for returning output zeropoints. - */ - CV_WRAP void getOutputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; - - /** - * @brief Compile Halide layers. - * @param[in] scheduler Path to YAML file with scheduling directives. - * @see setPreferableBackend - * - * Schedule layers that support Halide backend. Then compile them for - * specific target. For layers that not represented in scheduling file - * or if no manual scheduling used at all, automatic scheduling will be applied. - */ - CV_WRAP void setHalideScheduler(const String& scheduler); - - /** - * @brief Ask network to use specific computation backend where it supported. - * @param[in] backendId backend identifier. - * @see Backend - */ - CV_WRAP void setPreferableBackend(int backendId); - - /** - * @brief Ask network to make computations on specific target device. - * @param[in] targetId target identifier. - * @see Target - * - * List of supported combinations backend / target: - * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE | DNN_BACKEND_CUDA | - * |------------------------|--------------------|------------------------------|--------------------|-------------------| - * | DNN_TARGET_CPU | + | + | + | | - * | DNN_TARGET_OPENCL | + | + | + | | - * | DNN_TARGET_OPENCL_FP16 | + | + | | | - * | DNN_TARGET_MYRIAD | | + | | | - * | DNN_TARGET_FPGA | | + | | | - * | DNN_TARGET_CUDA | | | | + | - * | DNN_TARGET_CUDA_FP16 | | | | + | - * | DNN_TARGET_HDDL | | + | | | - */ - CV_WRAP void setPreferableTarget(int targetId); - - /** @brief Sets the new input value for the network - * @param blob A new blob. Should have CV_32F or CV_8U depth. - * @param name A name of input layer. - * @param scalefactor An optional normalization scale. - * @param mean An optional mean subtraction values. - * @see connect(String, String) to know format of the descriptor. - * - * If scale or mean values are specified, a final input blob is computed - * as: - * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f] - */ - CV_WRAP void setInput(CV_ND InputArray blob, const String& name = "", - double scalefactor = 1.0, const Scalar& mean = Scalar()); - - /** @brief Sets the new value for the learned param of the layer. - * @param layer name or id of the layer. - * @param numParam index of the layer parameter in the Layer::blobs array. - * @param blob the new value. - * @see Layer::blobs - * @note If shape of the new blob differs from the previous shape, - * then the following forward pass may fail. - */ - CV_WRAP void setParam(int layer, int numParam, CV_ND const Mat &blob); - CV_WRAP inline void setParam(const String& layerName, int numParam, CV_ND const Mat &blob) { return setParam(getLayerId(layerName), numParam, blob); } - - /** @brief Returns parameter blob of the layer. - * @param layer name or id of the layer. - * @param numParam index of the layer parameter in the Layer::blobs array. - * @see Layer::blobs - */ - CV_WRAP Mat getParam(int layer, int numParam = 0) const; - CV_WRAP inline Mat getParam(const String& layerName, int numParam = 0) const { return getParam(getLayerId(layerName), numParam); } - - /** @brief Returns indexes of layers with unconnected outputs. - * - * FIXIT: Rework API to registerOutput() approach, deprecate this call - */ - CV_WRAP std::vector getUnconnectedOutLayers() const; - - /** @brief Returns names of layers with unconnected outputs. - * - * FIXIT: Rework API to registerOutput() approach, deprecate this call - */ - CV_WRAP std::vector getUnconnectedOutLayersNames() const; - - /** @brief Returns input and output shapes for all layers in loaded model; - * preliminary inferencing isn't necessary. - * @param netInputShapes shapes for all input blobs in net input layer. - * @param layersIds output parameter for layer IDs. - * @param inLayersShapes output parameter for input layers shapes; - * order is the same as in layersIds - * @param outLayersShapes output parameter for output layers shapes; - * order is the same as in layersIds - */ - CV_WRAP void getLayersShapes(const std::vector& netInputShapes, - CV_OUT std::vector& layersIds, - CV_OUT std::vector >& inLayersShapes, - CV_OUT std::vector >& outLayersShapes) const; - - /** @overload */ - CV_WRAP void getLayersShapes(const MatShape& netInputShape, - CV_OUT std::vector& layersIds, - CV_OUT std::vector >& inLayersShapes, - CV_OUT std::vector >& outLayersShapes) const; - - /** @brief Returns input and output shapes for layer with specified - * id in loaded model; preliminary inferencing isn't necessary. - * @param netInputShape shape input blob in net input layer. - * @param layerId id for layer. - * @param inLayerShapes output parameter for input layers shapes; - * order is the same as in layersIds - * @param outLayerShapes output parameter for output layers shapes; - * order is the same as in layersIds - */ - void getLayerShapes(const MatShape& netInputShape, - const int layerId, - CV_OUT std::vector& inLayerShapes, - CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP - - /** @overload */ - void getLayerShapes(const std::vector& netInputShapes, - const int layerId, - CV_OUT std::vector& inLayerShapes, - CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP - - /** @brief Computes FLOP for whole loaded model with specified input shapes. - * @param netInputShapes vector of shapes for all net inputs. - * @returns computed FLOP. - */ - CV_WRAP int64 getFLOPS(const std::vector& netInputShapes) const; - /** @overload */ - CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const; - /** @overload */ - CV_WRAP int64 getFLOPS(const int layerId, - const std::vector& netInputShapes) const; - /** @overload */ - CV_WRAP int64 getFLOPS(const int layerId, - const MatShape& netInputShape) const; - - /** @brief Returns list of types for layer used in model. - * @param layersTypes output parameter for returning types. - */ - CV_WRAP void getLayerTypes(CV_OUT std::vector& layersTypes) const; - - /** @brief Returns count of layers of specified type. - * @param layerType type. - * @returns count of layers - */ - CV_WRAP int getLayersCount(const String& layerType) const; - - /** @brief Computes bytes number which are required to store - * all weights and intermediate blobs for model. - * @param netInputShapes vector of shapes for all net inputs. - * @param weights output parameter to store resulting bytes for weights. - * @param blobs output parameter to store resulting bytes for intermediate blobs. - */ - void getMemoryConsumption(const std::vector& netInputShapes, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP - /** @overload */ - CV_WRAP void getMemoryConsumption(const MatShape& netInputShape, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; - /** @overload */ - CV_WRAP void getMemoryConsumption(const int layerId, - const std::vector& netInputShapes, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; - /** @overload */ - CV_WRAP void getMemoryConsumption(const int layerId, - const MatShape& netInputShape, - CV_OUT size_t& weights, CV_OUT size_t& blobs) const; - - /** @brief Computes bytes number which are required to store - * all weights and intermediate blobs for each layer. - * @param netInputShapes vector of shapes for all net inputs. - * @param layerIds output vector to save layer IDs. - * @param weights output parameter to store resulting bytes for weights. - * @param blobs output parameter to store resulting bytes for intermediate blobs. - */ - void getMemoryConsumption(const std::vector& netInputShapes, - CV_OUT std::vector& layerIds, - CV_OUT std::vector& weights, - CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP - /** @overload */ - void getMemoryConsumption(const MatShape& netInputShape, - CV_OUT std::vector& layerIds, - CV_OUT std::vector& weights, - CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP - - /** @brief Enables or disables layer fusion in the network. - * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default. - */ - CV_WRAP void enableFusion(bool fusion); - - /** @brief Enables or disables the Winograd compute branch. The Winograd compute branch can speed up - * 3x3 Convolution at a small loss of accuracy. - * @param useWinograd true to enable the Winograd compute branch. The default is true. - */ - CV_WRAP void enableWinograd(bool useWinograd); - - /** @brief Returns overall time for inference and timings (in ticks) for layers. - * - * Indexes in returned vector correspond to layers ids. Some layers can be fused with others, - * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only. - * - * @param[out] timings vector for tick timings for all layers. - * @return overall ticks for model inference. - */ - CV_WRAP int64 getPerfProfile(CV_OUT std::vector& timings); - - - struct Impl; - inline Impl* getImpl() const { return impl.get(); } - inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } - friend class accessor::DnnNetAccessor; - protected: - Ptr impl; - }; - - /** @brief Reads a network model stored in Darknet model files. - * @param cfgFile path to the .cfg file with text description of the network architecture. - * @param darknetModel path to the .weights file with learned network. - * @returns Network object that ready to do forward, throw an exception in failure cases. - */ - CV_EXPORTS_W Net readNetFromDarknet(CV_WRAP_FILE_PATH const String &cfgFile, CV_WRAP_FILE_PATH const String &darknetModel = String()); - - /** @brief Reads a network model stored in Darknet model files. - * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. - * @param bufferModel A buffer contains a content of .weights file with learned network. - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromDarknet(const std::vector& bufferCfg, - const std::vector& bufferModel = std::vector()); - - /** @brief Reads a network model stored in Darknet model files. - * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. - * @param lenCfg Number of bytes to read from bufferCfg - * @param bufferModel A buffer contains a content of .weights file with learned network. - * @param lenModel Number of bytes to read from bufferModel - * @returns Net object. - */ - CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg, - const char *bufferModel = NULL, size_t lenModel = 0); - - /** @brief Reads a network model stored in Caffe framework's format. - * @param prototxt path to the .prototxt file with text description of the network architecture. - * @param caffeModel path to the .caffemodel file with learned network. - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromCaffe(CV_WRAP_FILE_PATH const String &prototxt, CV_WRAP_FILE_PATH const String &caffeModel = String()); - - /** @brief Reads a network model stored in Caffe model in memory. - * @param bufferProto buffer containing the content of the .prototxt file - * @param bufferModel buffer containing the content of the .caffemodel file - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromCaffe(const std::vector& bufferProto, - const std::vector& bufferModel = std::vector()); - - /** @brief Reads a network model stored in Caffe model in memory. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param bufferProto buffer containing the content of the .prototxt file - * @param lenProto length of bufferProto - * @param bufferModel buffer containing the content of the .caffemodel file - * @param lenModel length of bufferModel - * @returns Net object. - */ - CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto, - const char *bufferModel = NULL, size_t lenModel = 0); - - /** @brief Reads a network model stored in TensorFlow framework's format. - * @param model path to the .pb file with binary protobuf description of the network architecture - * @param config path to the .pbtxt file that contains text graph definition in protobuf format. - * Resulting Net object is built by text graph using weights from a binary one that - * let us make it more flexible. - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTensorflow(CV_WRAP_FILE_PATH const String &model, CV_WRAP_FILE_PATH const String &config = String()); - - /** @brief Reads a network model stored in TensorFlow framework's format. - * @param bufferModel buffer containing the content of the pb file - * @param bufferConfig buffer containing the content of the pbtxt file - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTensorflow(const std::vector& bufferModel, - const std::vector& bufferConfig = std::vector()); - - /** @brief Reads a network model stored in TensorFlow framework's format. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param bufferModel buffer containing the content of the pb file - * @param lenModel length of bufferModel - * @param bufferConfig buffer containing the content of the pbtxt file - * @param lenConfig length of bufferConfig - */ - CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel, - const char *bufferConfig = NULL, size_t lenConfig = 0); - - /** @brief Reads a network model stored in TFLite framework's format. - * @param model path to the .tflite file with binary flatbuffers description of the network architecture - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTFLite(CV_WRAP_FILE_PATH const String &model); - - /** @brief Reads a network model stored in TFLite framework's format. - * @param bufferModel buffer containing the content of the tflite file - * @returns Net object. - */ - CV_EXPORTS_W Net readNetFromTFLite(const std::vector& bufferModel); - - /** @brief Reads a network model stored in TFLite framework's format. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param bufferModel buffer containing the content of the tflite file - * @param lenModel length of bufferModel - */ - CV_EXPORTS Net readNetFromTFLite(const char *bufferModel, size_t lenModel); - - /** - * @brief Reads a network model stored in Torch7 framework's format. - * @param model path to the file, dumped from Torch by using torch.save() function. - * @param isBinary specifies whether the network was serialized in ascii mode or binary. - * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch. - * @returns Net object. - * - * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language, - * which has various bit-length on different systems. - * - * The loading file must contain serialized nn.Module object - * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors. - * - * List of supported layers (i.e. object instances derived from Torch nn.Module class): - * - nn.Sequential - * - nn.Parallel - * - nn.Concat - * - nn.Linear - * - nn.SpatialConvolution - * - nn.SpatialMaxPooling, nn.SpatialAveragePooling - * - nn.ReLU, nn.TanH, nn.Sigmoid - * - nn.Reshape - * - nn.SoftMax, nn.LogSoftMax - * - * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported. - */ - CV_EXPORTS_W Net readNetFromTorch(CV_WRAP_FILE_PATH const String &model, bool isBinary = true, bool evaluate = true); - - /** - * @brief Read deep learning network represented in one of the supported formats. - * @param[in] model Binary file contains trained weights. The following file - * extensions are expected for models from different frameworks: - * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) - * * `*.pb` (TensorFlow, https://www.tensorflow.org/) - * * `*.t7` | `*.net` (Torch, http://torch.ch/) - * * `*.weights` (Darknet, https://pjreddie.com/darknet/) - * * `*.bin` | `*.onnx` (OpenVINO, https://software.intel.com/openvino-toolkit) - * * `*.onnx` (ONNX, https://onnx.ai/) - * @param[in] config Text file contains network configuration. It could be a - * file with the following extensions: - * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) - * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) - * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) - * * `*.xml` (OpenVINO, https://software.intel.com/openvino-toolkit) - * @param[in] framework Explicit framework name tag to determine a format. - * @returns Net object. - * - * This function automatically detects an origin framework of trained model - * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, - * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config - * arguments does not matter. - */ - CV_EXPORTS_W Net readNet(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = "", const String& framework = ""); - - /** - * @brief Read deep learning network represented in one of the supported formats. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - * @param[in] framework Name of origin framework. - * @param[in] bufferModel A buffer with a content of binary file with weights - * @param[in] bufferConfig A buffer with a content of text file contains network configuration. - * @returns Net object. - */ - CV_EXPORTS_W Net readNet(const String& framework, const std::vector& bufferModel, - const std::vector& bufferConfig = std::vector()); - - /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework. - * @warning This function has the same limitations as readNetFromTorch(). - */ - CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true); - - /** @brief Load a network from Intel's Model Optimizer intermediate representation. - * @param[in] xml XML configuration file with network's topology. - * @param[in] bin Binary file with trained weights. - * @returns Net object. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_EXPORTS_W - Net readNetFromModelOptimizer(CV_WRAP_FILE_PATH const String &xml, CV_WRAP_FILE_PATH const String &bin = ""); - - /** @brief Load a network from Intel's Model Optimizer intermediate representation. - * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology. - * @param[in] bufferWeights Buffer contains binary data with trained weights. - * @returns Net object. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_EXPORTS_W - Net readNetFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); - - /** @brief Load a network from Intel's Model Optimizer intermediate representation. - * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology. - * @param[in] bufferModelConfigSize Binary size of XML configuration data. - * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights. - * @param[in] bufferWeightsSize Binary size of trained weights data. - * @returns Net object. - * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine - * backend. - */ - CV_EXPORTS - Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, - const uchar* bufferWeightsPtr, size_t bufferWeightsSize); - - /** @brief Reads a network model ONNX. - * @param onnxFile path to the .onnx file with text description of the network architecture. - * @returns Network object that ready to do forward, throw an exception in failure cases. - */ - CV_EXPORTS_W Net readNetFromONNX(CV_WRAP_FILE_PATH const String &onnxFile); - - /** @brief Reads a network model from ONNX - * in-memory buffer. - * @param buffer memory address of the first byte of the buffer. - * @param sizeBuffer size of the buffer. - * @returns Network object that ready to do forward, throw an exception - * in failure cases. - */ - CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer); - - /** @brief Reads a network model from ONNX - * in-memory buffer. - * @param buffer in-memory buffer that stores the ONNX model bytes. - * @returns Network object that ready to do forward, throw an exception - * in failure cases. - */ - CV_EXPORTS_W Net readNetFromONNX(const std::vector& buffer); - - /** @brief Creates blob from .pb file. - * @param path to the .pb file with input tensor. - * @returns Mat. - */ - CV_EXPORTS_W Mat readTensorFromONNX(CV_WRAP_FILE_PATH const String& path); - - /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center, - * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. - * @param image input image (with 1-, 3- or 4-channels). - * @param scalefactor multiplier for @p images values. - * @param size spatial size for output image - * @param mean scalar with mean values which are subtracted from channels. Values are intended - * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. - * @param swapRB flag which indicates that swap first and last channels - * in 3-channel image is necessary. - * @param crop flag which indicates whether image will be cropped after resize or not - * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. - * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding - * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. - * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. - * @returns 4-dimensional Mat with NCHW dimensions order. - * - * @note - * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. - */ - CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(), - const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, - int ddepth=CV_32F); - - /** @brief Creates 4-dimensional blob from image. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - */ - CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0, - const Size& size = Size(), const Scalar& mean = Scalar(), - bool swapRB=false, bool crop=false, int ddepth=CV_32F); - - - /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and - * crops @p images from center, subtract @p mean values, scales values by @p scalefactor, - * swap Blue and Red channels. - * @param images input images (all with 1-, 3- or 4-channels). - * @param size spatial size for output image - * @param mean scalar with mean values which are subtracted from channels. Values are intended - * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. - * @param scalefactor multiplier for @p images values. - * @param swapRB flag which indicates that swap first and last channels - * in 3-channel image is necessary. - * @param crop flag which indicates whether image will be cropped after resize or not - * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. - * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding - * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. - * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. - * @returns 4-dimensional Mat with NCHW dimensions order. - * - * @note - * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. - */ - CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0, - Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, - int ddepth=CV_32F); - - /** @brief Creates 4-dimensional blob from series of images. - * @details This is an overloaded member function, provided for convenience. - * It differs from the above function only in what argument(s) it accepts. - */ - CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob, - double scalefactor=1.0, Size size = Size(), - const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, - int ddepth=CV_32F); - - /** - * @brief Enum of image processing mode. - * To facilitate the specialization pre-processing requirements of the dnn model. - * For example, the `letter box` often used in the Yolo series of models. - * @see Image2BlobParams - */ - enum ImagePaddingMode - { - DNN_PMODE_NULL = 0, // !< Default. Resize to required input size without extra processing. - DNN_PMODE_CROP_CENTER = 1, // !< Image will be cropped after resize. - DNN_PMODE_LETTERBOX = 2, // !< Resize image to the desired size while preserving the aspect ratio of original image. - }; - - /** @brief Processing params of image to blob. - * - * It includes all possible image processing operations and corresponding parameters. - * - * @see blobFromImageWithParams - * - * @note - * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. - * The order and usage of `scalefactor`, `size`, `mean`, `swapRB`, and `ddepth` are consistent - * with the function of @ref blobFromImage. - */ - struct CV_EXPORTS_W_SIMPLE Image2BlobParams - { - CV_WRAP Image2BlobParams(); - CV_WRAP Image2BlobParams(const Scalar& scalefactor, const Size& size = Size(), const Scalar& mean = Scalar(), - bool swapRB = false, int ddepth = CV_32F, DataLayout datalayout = DNN_LAYOUT_NCHW, - ImagePaddingMode mode = DNN_PMODE_NULL, Scalar borderValue = 0.0); - - CV_PROP_RW Scalar scalefactor; //!< scalefactor multiplier for input image values. - CV_PROP_RW Size size; //!< Spatial size for output image. - CV_PROP_RW Scalar mean; //!< Scalar with mean values which are subtracted from channels. - CV_PROP_RW bool swapRB; //!< Flag which indicates that swap first and last channels - CV_PROP_RW int ddepth; //!< Depth of output blob. Choose CV_32F or CV_8U. - CV_PROP_RW DataLayout datalayout; //!< Order of output dimensions. Choose DNN_LAYOUT_NCHW or DNN_LAYOUT_NHWC. - CV_PROP_RW ImagePaddingMode paddingmode; //!< Image padding mode. @see ImagePaddingMode. - CV_PROP_RW Scalar borderValue; //!< Value used in padding mode for padding. - - /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. - * @param rBlob rect in blob coordinates. - * @param size original input image size. - * @returns rectangle in original image coordinates. - */ - CV_WRAP Rect blobRectToImageRect(const Rect &rBlob, const Size &size); - - /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. - * @param rBlob rect in blob coordinates. - * @param rImg result rect in image coordinates. - * @param size original input image size. - */ - CV_WRAP void blobRectsToImageRects(const std::vector &rBlob, CV_OUT std::vector& rImg, const Size& size); - }; - - /** @brief Creates 4-dimensional blob from image with given params. - * - * @details This function is an extension of @ref blobFromImage to meet more image preprocess needs. - * Given input image and preprocessing parameters, and function outputs the blob. - * - * @param image input image (all with 1-, 3- or 4-channels). - * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. - * @return 4-dimensional Mat. - */ - CV_EXPORTS_W Mat blobFromImageWithParams(InputArray image, const Image2BlobParams& param = Image2BlobParams()); - - /** @overload */ - CV_EXPORTS_W void blobFromImageWithParams(InputArray image, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); - - /** @brief Creates 4-dimensional blob from series of images with given params. - * - * @details This function is an extension of @ref blobFromImages to meet more image preprocess needs. - * Given input image and preprocessing parameters, and function outputs the blob. - * - * @param images input image (all with 1-, 3- or 4-channels). - * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. - * @returns 4-dimensional Mat. - */ - CV_EXPORTS_W Mat blobFromImagesWithParams(InputArrayOfArrays images, const Image2BlobParams& param = Image2BlobParams()); - - /** @overload */ - CV_EXPORTS_W void blobFromImagesWithParams(InputArrayOfArrays images, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); - - /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure - * (std::vector). - * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from - * which you would like to extract the images. - * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision - * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension - * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth). - */ - CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_); - - /** @brief Convert all weights of Caffe network to half precision floating point. - * @param src Path to origin model from Caffe framework contains single - * precision floating point weights (usually has `.caffemodel` extension). - * @param dst Path to destination model with updated weights. - * @param layersTypes Set of layers types which parameters will be converted. - * By default, converts only Convolutional and Fully-Connected layers' - * weights. - * - * @note Shrinked model has no origin float32 weights so it can't be used - * in origin Caffe framework anymore. However the structure of data - * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe. - * So the resulting model may be used there. - */ - CV_EXPORTS_W void shrinkCaffeModel(CV_WRAP_FILE_PATH const String& src, CV_WRAP_FILE_PATH const String& dst, - const std::vector& layersTypes = std::vector()); - - /** @brief Create a text representation for a binary network stored in protocol buffer format. - * @param[in] model A path to binary network. - * @param[in] output A path to output text file to be created. - * - * @note To reduce output file size, trained weights are not included. - */ - CV_EXPORTS_W void writeTextGraph(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& output); - - /** @brief Performs non maximum suppression given boxes and corresponding scores. - - * @param bboxes a set of bounding boxes to apply NMS. - * @param scores a set of corresponding confidences. - * @param score_threshold a threshold used to filter boxes by score. - * @param nms_threshold a threshold used in non maximum suppression. - * @param indices the kept indices of bboxes after NMS. - * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. - * @param top_k if `>0`, keep at most @p top_k picked indices. - */ - CV_EXPORTS void NMSBoxes(const std::vector& bboxes, const std::vector& scores, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - CV_EXPORTS_W void NMSBoxes(const std::vector& bboxes, const std::vector& scores, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector& bboxes, const std::vector& scores, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - /** @brief Performs batched non maximum suppression on given boxes and corresponding scores across different classes. - - * @param bboxes a set of bounding boxes to apply NMS. - * @param scores a set of corresponding confidences. - * @param class_ids a set of corresponding class ids. Ids are integer and usually start from 0. - * @param score_threshold a threshold used to filter boxes by score. - * @param nms_threshold a threshold used in non maximum suppression. - * @param indices the kept indices of bboxes after NMS. - * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. - * @param top_k if `>0`, keep at most @p top_k picked indices. - */ - CV_EXPORTS void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - CV_EXPORTS_W void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, - const float score_threshold, const float nms_threshold, - CV_OUT std::vector& indices, - const float eta = 1.f, const int top_k = 0); - - /** - * @brief Enum of Soft NMS methods. - * @see softNMSBoxes - */ - enum class SoftNMSMethod - { - SOFTNMS_LINEAR = 1, - SOFTNMS_GAUSSIAN = 2 - }; - - /** @brief Performs soft non maximum suppression given boxes and corresponding scores. - * Reference: https://arxiv.org/abs/1704.04503 - * @param bboxes a set of bounding boxes to apply Soft NMS. - * @param scores a set of corresponding confidences. - * @param updated_scores a set of corresponding updated confidences. - * @param score_threshold a threshold used to filter boxes by score. - * @param nms_threshold a threshold used in non maximum suppression. - * @param indices the kept indices of bboxes after NMS. - * @param top_k keep at most @p top_k picked indices. - * @param sigma parameter of Gaussian weighting. - * @param method Gaussian or linear. - * @see SoftNMSMethod - */ - CV_EXPORTS_W void softNMSBoxes(const std::vector& bboxes, - const std::vector& scores, - CV_OUT std::vector& updated_scores, - const float score_threshold, - const float nms_threshold, - CV_OUT std::vector& indices, - size_t top_k = 0, - const float sigma = 0.5, - SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN); - - - /** @brief This class is presented high-level API for neural networks. - * - * Model allows to set params for preprocessing input image. - * Model creates net from file with trained weights and config, - * sets preprocessing input and runs forward pass. - */ - class CV_EXPORTS_W_SIMPLE Model - { - public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - Model(); - - Model(const Model&) = default; - Model(Model&&) = default; - Model& operator=(const Model&) = default; - Model& operator=(Model&&) = default; - - /** - * @brief Create model from deep learning network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP Model(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP Model(const Net& network); - - /** @brief Set input size for frame. - * @param[in] size New input size. - * @note If shape of the new blob less than 0, then frame size not change. - */ - CV_WRAP Model& setInputSize(const Size& size); - - /** @overload - * @param[in] width New input width. - * @param[in] height New input height. - */ - CV_WRAP inline - Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); } - - /** @brief Set mean value for frame. - * @param[in] mean Scalar with mean values which are subtracted from channels. - */ - CV_WRAP Model& setInputMean(const Scalar& mean); - - /** @brief Set scalefactor value for frame. - * @param[in] scale Multiplier for frame values. - */ - CV_WRAP Model& setInputScale(const Scalar& scale); - - /** @brief Set flag crop for frame. - * @param[in] crop Flag which indicates whether image will be cropped after resize or not. - */ - CV_WRAP Model& setInputCrop(bool crop); - - /** @brief Set flag swapRB for frame. - * @param[in] swapRB Flag which indicates that swap first and last channels. - */ - CV_WRAP Model& setInputSwapRB(bool swapRB); - - /** @brief Set output names for frame. - * @param[in] outNames Names for output layers. - */ - CV_WRAP Model& setOutputNames(const std::vector& outNames); - - /** @brief Set preprocessing parameters for frame. - * @param[in] size New input size. - * @param[in] mean Scalar with mean values which are subtracted from channels. - * @param[in] scale Multiplier for frame values. - * @param[in] swapRB Flag which indicates that swap first and last channels. - * @param[in] crop Flag which indicates whether image will be cropped after resize or not. - * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) ) - */ - CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(), - const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false); - - /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs. - * @param[in] frame The input image. - * @param[out] outs Allocated output blobs, which will store results of the computation. - */ - CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const; - - - // ============================== Net proxy methods ============================== - // Never expose methods with network implementation details, like: - // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam - // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes - // - forward* methods, setInput - - /// @sa Net::setPreferableBackend - CV_WRAP Model& setPreferableBackend(dnn::Backend backendId); - /// @sa Net::setPreferableTarget - CV_WRAP Model& setPreferableTarget(dnn::Target targetId); - - /// @sa Net::enableWinograd - CV_WRAP Model& enableWinograd(bool useWinograd); - - CV_DEPRECATED_EXTERNAL - operator Net&() const { return getNetwork_(); } - - //protected: - internal/tests usage only - Net& getNetwork_() const; - inline Net& getNetwork_() { return const_cast(this)->getNetwork_(); } - - struct Impl; - inline Impl* getImpl() const { return impl.get(); } - inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } - protected: - Ptr impl; - }; - - /** @brief This class represents high-level API for classification models. - * - * ClassificationModel allows to set params for preprocessing input image. - * ClassificationModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and return top-1 prediction. - */ - class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model - { - public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - ClassificationModel(); - - /** - * @brief Create classification model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP ClassificationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP ClassificationModel(const Net& network); - - /** - * @brief Set enable/disable softmax post processing option. - * - * If this option is true, softmax is applied after forward inference within the classify() function - * to convert the confidences range to [0.0-1.0]. - * This function allows you to toggle this behavior. - * Please turn true when not contain softmax layer in model. - * @param[in] enable Set enable softmax post processing within the classify() function. - */ - CV_WRAP ClassificationModel& setEnableSoftmaxPostProcessing(bool enable); - - /** - * @brief Get enable/disable softmax post processing option. - * - * This option defaults to false, softmax post processing is not applied within the classify() function. - */ - CV_WRAP bool getEnableSoftmaxPostProcessing() const; - - /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction. - * @param[in] frame The input image. - */ - std::pair classify(InputArray frame); - - /** @overload */ - CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf); - }; - - /** @brief This class represents high-level API for keypoints models - * - * KeypointsModel allows to set params for preprocessing input image. - * KeypointsModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint - */ - class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model - { - public: - /** - * @brief Create keypoints model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP KeypointsModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP KeypointsModel(const Net& network); - - /** @brief Given the @p input frame, create input blob, run net - * @param[in] frame The input image. - * @param thresh minimum confidence threshold to select a keypoint - * @returns a vector holding the x and y coordinates of each detected keypoint - * - */ - CV_WRAP std::vector estimate(InputArray frame, float thresh=0.5); - }; - - /** @brief This class represents high-level API for segmentation models - * - * SegmentationModel allows to set params for preprocessing input image. - * SegmentationModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and returns the class prediction for each pixel. - */ - class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model - { - public: - /** - * @brief Create segmentation model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP SegmentationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP SegmentationModel(const Net& network); - - /** @brief Given the @p input frame, create input blob, run net - * @param[in] frame The input image. - * @param[out] mask Allocated class prediction for each pixel - */ - CV_WRAP void segment(InputArray frame, OutputArray mask); - }; - - /** @brief This class represents high-level API for object detection networks. - * - * DetectionModel allows to set params for preprocessing input image. - * DetectionModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and return result detections. - * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported. - */ - class CV_EXPORTS_W_SIMPLE DetectionModel : public Model - { - public: - /** - * @brief Create detection model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP DetectionModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); - - /** - * @brief Create model from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP DetectionModel(const Net& network); - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code (need to fix bindings first) - DetectionModel(); - - /** - * @brief nmsAcrossClasses defaults to false, - * such that when non max suppression is used during the detect() function, it will do so per-class. - * This function allows you to toggle this behaviour. - * @param[in] value The new value for nmsAcrossClasses - */ - CV_WRAP DetectionModel& setNmsAcrossClasses(bool value); - - /** - * @brief Getter for nmsAcrossClasses. This variable defaults to false, - * such that when non max suppression is used during the detect() function, it will do so only per-class - */ - CV_WRAP bool getNmsAcrossClasses(); - - /** @brief Given the @p input frame, create input blob, run net and return result detections. - * @param[in] frame The input image. - * @param[out] classIds Class indexes in result detection. - * @param[out] confidences A set of corresponding confidences. - * @param[out] boxes A set of bounding boxes. - * @param[in] confThreshold A threshold used to filter boxes by confidences. - * @param[in] nmsThreshold A threshold used in non maximum suppression. - */ - CV_WRAP void detect(InputArray frame, CV_OUT std::vector& classIds, - CV_OUT std::vector& confidences, CV_OUT std::vector& boxes, - float confThreshold = 0.5f, float nmsThreshold = 0.0f); - }; - - -/** @brief This class represents high-level API for text recognition networks. - * - * TextRecognitionModel allows to set params for preprocessing input image. - * TextRecognitionModel creates net from file with trained weights and config, - * sets preprocessing input, runs forward pass and return recognition result. - * For TextRecognitionModel, CRNN-CTC is supported. - */ -class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model -{ -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextRecognitionModel(); - - /** - * @brief Create Text Recognition model from deep learning network - * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method - * @param[in] network Net object - */ - CV_WRAP TextRecognitionModel(const Net& network); - - /** - * @brief Create text recognition model from network represented in one of the supported formats - * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method - * @param[in] model Binary file contains trained weights - * @param[in] config Text file contains network configuration - */ - CV_WRAP inline - TextRecognitionModel(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") - : TextRecognitionModel(readNet(model, config)) { /* nothing */ } - - /** - * @brief Set the decoding method of translating the network output into string - * @param[in] decodeType The decoding method of translating the network output into string, currently supported type: - * - `"CTC-greedy"` greedy decoding for the output of CTC-based methods - * - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods - */ - CV_WRAP - TextRecognitionModel& setDecodeType(const std::string& decodeType); - - /** - * @brief Get the decoding method - * @return the decoding method - */ - CV_WRAP - const std::string& getDecodeType() const; - - /** - * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage - * @param[in] beamSize Beam size for search - * @param[in] vocPruneSize Parameter to optimize big vocabulary search, - * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune. - */ - CV_WRAP - TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0); - - /** - * @brief Set the vocabulary for recognition. - * @param[in] vocabulary the associated vocabulary of the network. - */ - CV_WRAP - TextRecognitionModel& setVocabulary(const std::vector& vocabulary); - - /** - * @brief Get the vocabulary for recognition. - * @return vocabulary the associated vocabulary - */ - CV_WRAP - const std::vector& getVocabulary() const; - - /** - * @brief Given the @p input frame, create input blob, run net and return recognition result - * @param[in] frame The input image - * @return The text recognition result - */ - CV_WRAP - std::string recognize(InputArray frame) const; - - /** - * @brief Given the @p input frame, create input blob, run net and return recognition result - * @param[in] frame The input image - * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs - * @param[out] results A set of text recognition results. - */ - CV_WRAP - void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector& results) const; -}; - - -/** @brief Base class for text detection networks - */ -class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model -{ -protected: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextDetectionModel(); - -public: - - /** @brief Performs detection - * - * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. - * - * Each result is quadrangle's 4 points in this order: - * - bottom-left - * - top-left - * - top-right - * - bottom-right - * - * Use cv::getPerspectiveTransform function to retrieve image region without perspective transformations. - * - * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output. - * - * @param[in] frame The input image - * @param[out] detections array with detections' quadrangles (4 points per result) - * @param[out] confidences array with detection confidences - */ - CV_WRAP - void detect( - InputArray frame, - CV_OUT std::vector< std::vector >& detections, - CV_OUT std::vector& confidences - ) const; - - /** @overload */ - CV_WRAP - void detect( - InputArray frame, - CV_OUT std::vector< std::vector >& detections - ) const; - - /** @brief Performs detection - * - * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. - * - * Each result is rotated rectangle. - * - * @note Result may be inaccurate in case of strong perspective transformations. - * - * @param[in] frame the input image - * @param[out] detections array with detections' RotationRect results - * @param[out] confidences array with detection confidences - */ - CV_WRAP - void detectTextRectangles( - InputArray frame, - CV_OUT std::vector& detections, - CV_OUT std::vector& confidences - ) const; - - /** @overload */ - CV_WRAP - void detectTextRectangles( - InputArray frame, - CV_OUT std::vector& detections - ) const; -}; - -/** @brief This class represents high-level API for text detection DL networks compatible with EAST model. - * - * Configurable parameters: - * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f - * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f - */ -class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel -{ -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextDetectionModel_EAST(); - - /** - * @brief Create text detection algorithm from deep learning network - * @param[in] network Net object - */ - CV_WRAP TextDetectionModel_EAST(const Net& network); - - /** - * @brief Create text detection model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP inline - TextDetectionModel_EAST(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") - : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ } - - /** - * @brief Set the detection confidence threshold - * @param[in] confThreshold A threshold used to filter boxes by confidences - */ - CV_WRAP - TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold); - - /** - * @brief Get the detection confidence threshold - */ - CV_WRAP - float getConfidenceThreshold() const; - - /** - * @brief Set the detection NMS filter threshold - * @param[in] nmsThreshold A threshold used in non maximum suppression - */ - CV_WRAP - TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold); - - /** - * @brief Get the detection confidence threshold - */ - CV_WRAP - float getNMSThreshold() const; -}; - -/** @brief This class represents high-level API for text detection DL networks compatible with DB model. - * - * Related publications: @cite liao2020real - * Paper: https://arxiv.org/abs/1911.08947 - * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB - * - * Configurable parameters: - * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3. - * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f - * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0. - * - (int) maxCandidates - The max number of the output results. - */ -class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel -{ -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - TextDetectionModel_DB(); - - /** - * @brief Create text detection algorithm from deep learning network. - * @param[in] network Net object. - */ - CV_WRAP TextDetectionModel_DB(const Net& network); - - /** - * @brief Create text detection model from network represented in one of the supported formats. - * An order of @p model and @p config arguments does not matter. - * @param[in] model Binary file contains trained weights. - * @param[in] config Text file contains network configuration. - */ - CV_WRAP inline - TextDetectionModel_DB(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") - : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ } - - CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold); - CV_WRAP float getBinaryThreshold() const; - - CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold); - CV_WRAP float getPolygonThreshold() const; - - CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio); - CV_WRAP double getUnclipRatio() const; - - CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates); - CV_WRAP int getMaxCandidates() const; -}; - -//! @} -CV__DNN_INLINE_NS_END -} -} - -#include -#include - -/// @deprecated Include this header directly from application. Automatic inclusion will be removed -#include - -#endif /* OPENCV_DNN_DNN_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_HPP +#define OPENCV_DNN_DNN_HPP + +#include +#include +#include "opencv2/core/async.hpp" + +#include "../dnn/version.hpp" + +#include + +namespace cv { +namespace dnn { + +namespace accessor { +class DnnNetAccessor; // forward declaration +} + +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ + + typedef std::vector MatShape; + + /** + * @brief Enum of computation backends supported by layers. + * @see Net::setPreferableBackend + */ + enum Backend + { + //! DNN_BACKEND_DEFAULT equals to OPENCV_DNN_BACKEND_DEFAULT, which can be defined using CMake or a configuration parameter + DNN_BACKEND_DEFAULT = 0, + DNN_BACKEND_HALIDE, + DNN_BACKEND_INFERENCE_ENGINE, //!< Intel OpenVINO computational backend + //!< @note Tutorial how to build OpenCV with OpenVINO: @ref tutorial_dnn_openvino + DNN_BACKEND_OPENCV, + DNN_BACKEND_VKCOM, + DNN_BACKEND_CUDA, + DNN_BACKEND_WEBNN, + DNN_BACKEND_TIMVX, + DNN_BACKEND_CANN, +#if defined(__OPENCV_BUILD) || defined(BUILD_PLUGIN) +#if !defined(OPENCV_BINDING_PARSER) + DNN_BACKEND_INFERENCE_ENGINE_NGRAPH = 1000000, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() + DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019, // internal - use DNN_BACKEND_INFERENCE_ENGINE + setInferenceEngineBackendType() +#endif +#endif + }; + + /** + * @brief Enum of target devices for computations. + * @see Net::setPreferableTarget + */ + enum Target + { + DNN_TARGET_CPU = 0, + DNN_TARGET_OPENCL, + DNN_TARGET_OPENCL_FP16, + DNN_TARGET_MYRIAD, + DNN_TARGET_VULKAN, + DNN_TARGET_FPGA, //!< FPGA device with CPU fallbacks using Inference Engine's Heterogeneous plugin. + DNN_TARGET_CUDA, + DNN_TARGET_CUDA_FP16, + DNN_TARGET_HDDL, + DNN_TARGET_NPU, + DNN_TARGET_CPU_FP16, // Only the ARM platform is supported. Low precision computing, accelerate model inference. + }; + + /** + * @brief Enum of data layout for model inference. + * @see Image2BlobParams + */ + enum DataLayout + { + DNN_LAYOUT_UNKNOWN = 0, + DNN_LAYOUT_ND = 1, //!< OpenCV data layout for 2D data. + DNN_LAYOUT_NCHW = 2, //!< OpenCV data layout for 4D data. + DNN_LAYOUT_NCDHW = 3, //!< OpenCV data layout for 5D data. + DNN_LAYOUT_NHWC = 4, //!< Tensorflow-like data layout for 4D data. + DNN_LAYOUT_NDHWC = 5, //!< Tensorflow-like data layout for 5D data. + DNN_LAYOUT_PLANAR = 6, //!< Tensorflow-like data layout, it should only be used at tf or tflite model parsing. + }; + + CV_EXPORTS std::vector< std::pair > getAvailableBackends(); + CV_EXPORTS_W std::vector getAvailableTargets(dnn::Backend be); + + /** + * @brief Enables detailed logging of the DNN model loading with CV DNN API. + * @param[in] isDiagnosticsMode Indicates whether diagnostic mode should be set. + * + * Diagnostic mode provides detailed logging of the model loading stage to explore + * potential problems (ex.: not implemented layer type). + * + * @note In diagnostic mode series of assertions will be skipped, it can lead to the + * expected application crash. + */ + CV_EXPORTS void enableModelDiagnostics(bool isDiagnosticsMode); + + /** @brief This class provides all data needed to initialize layer. + * + * It includes dictionary with scalar params (which can be read by using Dict interface), + * blob params #blobs and optional meta information: #name and #type of layer instance. + */ + class CV_EXPORTS LayerParams : public Dict + { + public: + //TODO: Add ability to name blob params + std::vector blobs; //!< List of learned parameters stored as blobs. + + String name; //!< Name of the layer instance (optional, can be used internal purposes). + String type; //!< Type name which was used for creating layer by layer factory (optional). + }; + + /** + * @brief Derivatives of this class encapsulates functions of certain backends. + */ + class BackendNode + { + public: + explicit BackendNode(int backendId); + + virtual ~BackendNode(); //!< Virtual destructor to make polymorphism. + + int backendId; //!< Backend identifier. + }; + + /** + * @brief Derivatives of this class wraps cv::Mat for different backends and targets. + */ + class BackendWrapper + { + public: + BackendWrapper(int backendId, int targetId); + + /** + * @brief Wrap cv::Mat for specific backend and target. + * @param[in] targetId Target identifier. + * @param[in] m cv::Mat for wrapping. + * + * Make CPU->GPU data transfer if it's require for the target. + */ + BackendWrapper(int targetId, const cv::Mat& m); + + /** + * @brief Make wrapper for reused cv::Mat. + * @param[in] base Wrapper of cv::Mat that will be reused. + * @param[in] shape Specific shape. + * + * Initialize wrapper from another one. It'll wrap the same host CPU + * memory and mustn't allocate memory on device(i.e. GPU). It might + * has different shape. Use in case of CPU memory reusing for reuse + * associated memory on device too. + */ + BackendWrapper(const Ptr& base, const MatShape& shape); + + virtual ~BackendWrapper(); //!< Virtual destructor to make polymorphism. + + /** + * @brief Transfer data to CPU host memory. + */ + virtual void copyToHost() = 0; + + /** + * @brief Indicate that an actual data is on CPU. + */ + virtual void setHostDirty() = 0; + + int backendId; //!< Backend identifier. + int targetId; //!< Target identifier. + }; + + class CV_EXPORTS ActivationLayer; + + /** @brief This interface class allows to build new Layers - are building blocks of networks. + * + * Each class, derived from Layer, must implement forward() method to compute outputs. + * Also before using the new layer into networks you must register your layer by using one of @ref dnnLayerFactory "LayerFactory" macros. + */ + class CV_EXPORTS_W Layer : public Algorithm + { + public: + + //! List of learned parameters must be stored here to allow read them by using Net::getParam(). + CV_PROP_RW std::vector blobs; + + /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. + * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead + * @param[in] input vector of already allocated input blobs + * @param[out] output vector of already allocated output blobs + * + * This method is called after network has allocated all memory for input and output blobs + * and before inferencing. + */ + CV_DEPRECATED_EXTERNAL + virtual void finalize(const std::vector &input, std::vector &output); + + /** @brief Computes and sets internal parameters according to inputs, outputs and blobs. + * @param[in] inputs vector of already allocated input blobs + * @param[out] outputs vector of already allocated output blobs + * + * This method is called after network has allocated all memory for input and output blobs + * and before inferencing. + */ + CV_WRAP virtual void finalize(InputArrayOfArrays inputs, OutputArrayOfArrays outputs); + + /** @brief Given the @p input blobs, computes the output @p blobs. + * @deprecated Use Layer::forward(InputArrayOfArrays, OutputArrayOfArrays, OutputArrayOfArrays) instead + * @param[in] input the input blobs. + * @param[out] output allocated output blobs, which will store results of the computation. + * @param[out] internals allocated internal blobs + */ + CV_DEPRECATED_EXTERNAL + virtual void forward(std::vector &input, std::vector &output, std::vector &internals); + + /** @brief Given the @p input blobs, computes the output @p blobs. + * @param[in] inputs the input blobs. + * @param[out] outputs allocated output blobs, which will store results of the computation. + * @param[out] internals allocated internal blobs + */ + virtual void forward(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); + + /** @brief Tries to quantize the given layer and compute the quantization parameters required for fixed point implementation. + * @param[in] scales input and output scales. + * @param[in] zeropoints input and output zeropoints. + * @param[out] params Quantized parameters required for fixed point implementation of that layer. + * @returns True if layer can be quantized. + */ + virtual bool tryQuantize(const std::vector > &scales, + const std::vector > &zeropoints, LayerParams& params); + + /** @brief Given the @p input blobs, computes the output @p blobs. + * @param[in] inputs the input blobs. + * @param[out] outputs allocated output blobs, which will store results of the computation. + * @param[out] internals allocated internal blobs + */ + void forward_fallback(InputArrayOfArrays inputs, OutputArrayOfArrays outputs, OutputArrayOfArrays internals); + + /** @brief + * @overload + * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead + */ + CV_DEPRECATED_EXTERNAL + void finalize(const std::vector &inputs, CV_OUT std::vector &outputs); + + /** @brief + * @overload + * @deprecated Use Layer::finalize(InputArrayOfArrays, OutputArrayOfArrays) instead + */ + CV_DEPRECATED std::vector finalize(const std::vector &inputs); + + /** @brief Allocates layer and computes output. + * @deprecated This method will be removed in the future release. + */ + CV_DEPRECATED CV_WRAP void run(const std::vector &inputs, CV_OUT std::vector &outputs, + CV_IN_OUT std::vector &internals); + + /** @brief Returns index of input blob into the input array. + * @param inputName label of input blob + * + * Each layer input and output can be labeled to easily identify them using "%[.output_name]" notation. + * This method maps label of input blob to its index into input vector. + */ + virtual int inputNameToIndex(String inputName); // FIXIT const + /** @brief Returns index of output blob in output array. + * @see inputNameToIndex() + */ + CV_WRAP virtual int outputNameToIndex(const String& outputName); // FIXIT const + + /** + * @brief Ask layer if it support specific backend for doing computations. + * @param[in] backendId computation backend identifier. + * @see Backend + */ + virtual bool supportBackend(int backendId); // FIXIT const + + /** + * @brief Returns Halide backend node. + * @param[in] inputs Input Halide buffers. + * @see BackendNode, BackendWrapper + * + * Input buffers should be exactly the same that will be used in forward invocations. + * Despite we can use Halide::ImageParam based on input shape only, + * it helps prevent some memory management issues (if something wrong, + * Halide tests will be failed). + */ + virtual Ptr initHalide(const std::vector > &inputs); + + virtual Ptr initNgraph(const std::vector > &inputs, const std::vector >& nodes); + + virtual Ptr initVkCom(const std::vector > &inputs, std::vector > &outputs); + + virtual Ptr initWebnn(const std::vector > &inputs, const std::vector >& nodes); + + /** + * @brief Returns a CUDA backend node + * + * @param context void pointer to CSLContext object + * @param inputs layer inputs + * @param outputs layer outputs + */ + virtual Ptr initCUDA( + void *context, + const std::vector>& inputs, + const std::vector>& outputs + ); + + /** + * @brief Returns a TimVX backend node + * + * @param timVxInfo void pointer to CSLContext object + * @param inputsWrapper layer inputs + * @param outputsWrapper layer outputs + * @param isLast if the node is the last one of the TimVX Graph. + */ + virtual Ptr initTimVX(void* timVxInfo, + const std::vector > &inputsWrapper, + const std::vector > &outputsWrapper, + bool isLast); + + /** + * @brief Returns a CANN backend node + * + * @param inputs input tensors of CANN operator + * @param outputs output tensors of CANN operator + * @param nodes nodes of input tensors + */ + virtual Ptr initCann(const std::vector > &inputs, + const std::vector > &outputs, + const std::vector >& nodes); + + /** + * @brief Automatic Halide scheduling based on layer hyper-parameters. + * @param[in] node Backend node with Halide functions. + * @param[in] inputs Blobs that will be used in forward invocations. + * @param[in] outputs Blobs that will be used in forward invocations. + * @param[in] targetId Target identifier + * @see BackendNode, Target + * + * Layer don't use own Halide::Func members because we can have applied + * layers fusing. In this way the fused function should be scheduled. + */ + virtual void applyHalideScheduler(Ptr& node, + const std::vector &inputs, + const std::vector &outputs, + int targetId) const; + + /** + * @brief Implement layers fusing. + * @param[in] node Backend node of bottom layer. + * @see BackendNode + * + * Actual for graph-based backends. If layer attached successfully, + * returns non-empty cv::Ptr to node of the same backend. + * Fuse only over the last function. + */ + virtual Ptr tryAttach(const Ptr& node); + + /** + * @brief Tries to attach to the layer the subsequent activation layer, i.e. do the layer fusion in a partial case. + * @param[in] layer The subsequent activation layer. + * + * Returns true if the activation layer has been attached successfully. + */ + virtual bool setActivation(const Ptr& layer); + + /** + * @brief Try to fuse current layer with a next one + * @param[in] top Next layer to be fused. + * @returns True if fusion was performed. + */ + virtual bool tryFuse(Ptr& top); + + /** + * @brief Returns parameters of layers with channel-wise multiplication and addition. + * @param[out] scale Channel-wise multipliers. Total number of values should + * be equal to number of channels. + * @param[out] shift Channel-wise offsets. Total number of values should + * be equal to number of channels. + * + * Some layers can fuse their transformations with further layers. + * In example, convolution + batch normalization. This way base layer + * use weights from layer after it. Fused layer is skipped. + * By default, @p scale and @p shift are empty that means layer has no + * element-wise multiplications or additions. + */ + virtual void getScaleShift(Mat& scale, Mat& shift) const; + + /** + * @brief Returns scale and zeropoint of layers + * @param[out] scale Output scale + * @param[out] zeropoint Output zeropoint + * + * By default, @p scale is 1 and @p zeropoint is 0. + */ + virtual void getScaleZeropoint(float& scale, int& zeropoint) const; + + + /** + * @brief "Detaches" all the layers, attached to particular layer. + */ + virtual void unsetAttached(); + + virtual bool getMemoryShapes(const std::vector &inputs, + const int requiredOutputs, + std::vector &outputs, + std::vector &internals) const; + + virtual int64 getFLOPS(const std::vector &inputs, + const std::vector &outputs) const {CV_UNUSED(inputs); CV_UNUSED(outputs); return 0;} + + virtual bool updateMemoryShapes(const std::vector &inputs); + + CV_PROP String name; //!< Name of the layer instance, can be used for logging or other internal purposes. + CV_PROP String type; //!< Type name which was used for creating layer by layer factory. + CV_PROP int preferableTarget; //!< prefer target for layer forwarding + + Layer(); + explicit Layer(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. + void setParamsFrom(const LayerParams ¶ms); //!< Initializes only #name, #type and #blobs fields. + virtual ~Layer(); + }; + + /** @brief This class allows to create and manipulate comprehensive artificial neural networks. + * + * Neural network is presented as directed acyclic graph (DAG), where vertices are Layer instances, + * and edges specify relationships between layers inputs and outputs. + * + * Each network layer has unique integer id and unique string name inside its network. + * LayerId can store either layer name or layer id. + * + * This class supports reference counting of its instances, i. e. copies point to the same instance. + */ + class CV_EXPORTS_W_SIMPLE Net + { + public: + + CV_WRAP Net(); //!< Default constructor. + CV_WRAP ~Net(); //!< Destructor frees the net only if there aren't references to the net anymore. + + /** @brief Create a network from Intel's Model Optimizer intermediate representation (IR). + * @param[in] xml XML configuration file with network's topology. + * @param[in] bin Binary file with trained weights. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_WRAP static Net readFromModelOptimizer(CV_WRAP_FILE_PATH const String& xml, CV_WRAP_FILE_PATH const String& bin); + + /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). + * @param[in] bufferModelConfig buffer with model's configuration. + * @param[in] bufferWeights buffer with model's trained weights. + * @returns Net object. + */ + CV_WRAP static + Net readFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); + + /** @brief Create a network from Intel's Model Optimizer in-memory buffers with intermediate representation (IR). + * @param[in] bufferModelConfigPtr buffer pointer of model's configuration. + * @param[in] bufferModelConfigSize buffer size of model's configuration. + * @param[in] bufferWeightsPtr buffer pointer of model's trained weights. + * @param[in] bufferWeightsSize buffer size of model's trained weights. + * @returns Net object. + */ + static + Net readFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, + const uchar* bufferWeightsPtr, size_t bufferWeightsSize); + + /** Returns true if there are no layers in the network. */ + CV_WRAP bool empty() const; + + /** @brief Dump net to String + * @returns String with structure, hyperparameters, backend, target and fusion + * Call method after setInput(). To see correct backend, target and fusion run after forward(). + */ + CV_WRAP String dump(); + /** @brief Dump net structure, hyperparameters, backend, target and fusion to dot file + * @param path path to output file with .dot extension + * @see dump() + */ + CV_WRAP void dumpToFile(CV_WRAP_FILE_PATH const String& path); + /** @brief Dump net structure, hyperparameters, backend, target and fusion to pbtxt file + * @param path path to output file with .pbtxt extension + * + * Use Netron (https://netron.app) to open the target file to visualize the model. + * Call method after setInput(). To see correct backend, target and fusion run after forward(). + */ + CV_WRAP void dumpToPbtxt(CV_WRAP_FILE_PATH const String& path); + + /** @brief Adds new layer to the net. + * @param name unique name of the adding layer. + * @param type typename of the adding layer (type must be registered in LayerRegister). + * @param dtype datatype of output blobs. + * @param params parameters which will be used to initialize the creating layer. + * @returns unique identifier of created layer, or -1 if a failure will happen. + */ + CV_WRAP int addLayer(const String &name, const String &type, const int &dtype, LayerParams ¶ms); + + /** @overload Datatype of output blobs set to default CV_32F */ + int addLayer(const String &name, const String &type, LayerParams ¶ms); + + /** @brief Adds new layer and connects its first input to the first output of previously added layer. + * @see addLayer() + */ + CV_WRAP int addLayerToPrev(const String &name, const String &type, const int &dtype, LayerParams ¶ms); + + /** @overload */ + int addLayerToPrev(const String &name, const String &type, LayerParams ¶ms); + + /** @brief Converts string name of the layer to the integer identifier. + * @returns id of the layer, or -1 if the layer wasn't found. + */ + CV_WRAP int getLayerId(const String &layer) const; + + CV_WRAP std::vector getLayerNames() const; + + /** @brief Container for strings and integers. + * + * @deprecated Use getLayerId() with int result. + */ + typedef DictValue LayerId; + + /** @brief Returns pointer to layer with specified id or name which the network use. */ + CV_WRAP Ptr getLayer(int layerId) const; + /** @overload + * @deprecated Use int getLayerId(const String &layer) + */ + CV_WRAP inline Ptr getLayer(const String& layerName) const { return getLayer(getLayerId(layerName)); } + /** @overload + * @deprecated to be removed + */ + CV_WRAP Ptr getLayer(const LayerId& layerId) const; + + /** @brief Returns pointers to input layers of specific layer. */ + std::vector > getLayerInputs(int layerId) const; // FIXIT: CV_WRAP + + /** @brief Connects output of the first layer to input of the second layer. + * @param outPin descriptor of the first layer output. + * @param inpPin descriptor of the second layer input. + * + * Descriptors have the following template <layer_name>[.input_number]: + * - the first part of the template layer_name is string name of the added layer. + * If this part is empty then the network input pseudo layer will be used; + * - the second optional part of the template input_number + * is either number of the layer input, either label one. + * If this part is omitted then the first layer input will be used. + * + * @see setNetInputs(), Layer::inputNameToIndex(), Layer::outputNameToIndex() + */ + CV_WRAP void connect(String outPin, String inpPin); + + /** @brief Connects #@p outNum output of the first layer to #@p inNum input of the second layer. + * @param outLayerId identifier of the first layer + * @param outNum number of the first layer output + * @param inpLayerId identifier of the second layer + * @param inpNum number of the second layer input + */ + void connect(int outLayerId, int outNum, int inpLayerId, int inpNum); + + /** @brief Registers network output with name + * + * Function may create additional 'Identity' layer. + * + * @param outputName identifier of the output + * @param layerId identifier of the second layer + * @param outputPort number of the second layer input + * + * @returns index of bound layer (the same as layerId or newly created) + */ + int registerOutput(const std::string& outputName, int layerId, int outputPort); + + /** @brief Sets outputs names of the network input pseudo layer. + * + * Each net always has special own the network input pseudo layer with id=0. + * This layer stores the user blobs only and don't make any computations. + * In fact, this layer provides the only way to pass user data into the network. + * As any other layer, this layer can label its outputs and this function provides an easy way to do this. + */ + CV_WRAP void setInputsNames(const std::vector &inputBlobNames); + + /** @brief Specify shape of network input. + */ + CV_WRAP void setInputShape(const String &inputName, const MatShape& shape); + + /** @brief Runs forward pass to compute output of layer with name @p outputName. + * @param outputName name for layer which output is needed to get + * @return blob for first output of specified layer. + * @details By default runs forward pass for the whole network. + */ + CV_WRAP Mat forward(const String& outputName = String()); + + /** @brief Runs forward pass to compute output of layer with name @p outputName. + * @param outputName name for layer which output is needed to get + * @details By default runs forward pass for the whole network. + * + * This is an asynchronous version of forward(const String&). + * dnn::DNN_BACKEND_INFERENCE_ENGINE backend is required. + */ + CV_WRAP AsyncArray forwardAsync(const String& outputName = String()); + + /** @brief Runs forward pass to compute output of layer with name @p outputName. + * @param outputBlobs contains all output blobs for specified layer. + * @param outputName name for layer which output is needed to get + * @details If @p outputName is empty, runs forward pass for the whole network. + */ + CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, const String& outputName = String()); + + /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. + * @param outputBlobs contains blobs for first outputs of specified layers. + * @param outBlobNames names for layers which outputs are needed to get + */ + CV_WRAP void forward(CV_ND OutputArrayOfArrays outputBlobs, + const std::vector& outBlobNames); + + /** @brief Runs forward pass to compute outputs of layers listed in @p outBlobNames. + * @param outputBlobs contains all output blobs for each layer specified in @p outBlobNames. + * @param outBlobNames names for layers which outputs are needed to get + */ + CV_WRAP_AS(forwardAndRetrieve) void forward(CV_OUT std::vector >& outputBlobs, + const std::vector& outBlobNames); + + /** @brief Returns a quantized Net from a floating-point Net. + * @param calibData Calibration data to compute the quantization parameters. + * @param inputsDtype Datatype of quantized net's inputs. Can be CV_32F or CV_8S. + * @param outputsDtype Datatype of quantized net's outputs. Can be CV_32F or CV_8S. + * @param perChannel Quantization granularity of quantized Net. The default is true, that means quantize model + * in per-channel way (channel-wise). Set it false to quantize model in per-tensor way (or tensor-wise). + */ + CV_WRAP Net quantize(InputArrayOfArrays calibData, int inputsDtype, int outputsDtype, bool perChannel=true); + + /** @brief Returns input scale and zeropoint for a quantized Net. + * @param scales output parameter for returning input scales. + * @param zeropoints output parameter for returning input zeropoints. + */ + CV_WRAP void getInputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; + + /** @brief Returns output scale and zeropoint for a quantized Net. + * @param scales output parameter for returning output scales. + * @param zeropoints output parameter for returning output zeropoints. + */ + CV_WRAP void getOutputDetails(CV_OUT std::vector& scales, CV_OUT std::vector& zeropoints) const; + + /** + * @brief Compile Halide layers. + * @param[in] scheduler Path to YAML file with scheduling directives. + * @see setPreferableBackend + * + * Schedule layers that support Halide backend. Then compile them for + * specific target. For layers that not represented in scheduling file + * or if no manual scheduling used at all, automatic scheduling will be applied. + */ + CV_WRAP void setHalideScheduler(const String& scheduler); + + /** + * @brief Ask network to use specific computation backend where it supported. + * @param[in] backendId backend identifier. + * @see Backend + */ + CV_WRAP void setPreferableBackend(int backendId); + + /** + * @brief Ask network to make computations on specific target device. + * @param[in] targetId target identifier. + * @see Target + * + * List of supported combinations backend / target: + * | | DNN_BACKEND_OPENCV | DNN_BACKEND_INFERENCE_ENGINE | DNN_BACKEND_HALIDE | DNN_BACKEND_CUDA | + * |------------------------|--------------------|------------------------------|--------------------|-------------------| + * | DNN_TARGET_CPU | + | + | + | | + * | DNN_TARGET_OPENCL | + | + | + | | + * | DNN_TARGET_OPENCL_FP16 | + | + | | | + * | DNN_TARGET_MYRIAD | | + | | | + * | DNN_TARGET_FPGA | | + | | | + * | DNN_TARGET_CUDA | | | | + | + * | DNN_TARGET_CUDA_FP16 | | | | + | + * | DNN_TARGET_HDDL | | + | | | + */ + CV_WRAP void setPreferableTarget(int targetId); + + /** @brief Sets the new input value for the network + * @param blob A new blob. Should have CV_32F or CV_8U depth. + * @param name A name of input layer. + * @param scalefactor An optional normalization scale. + * @param mean An optional mean subtraction values. + * @see connect(String, String) to know format of the descriptor. + * + * If scale or mean values are specified, a final input blob is computed + * as: + * \f[input(n,c,h,w) = scalefactor \times (blob(n,c,h,w) - mean_c)\f] + */ + CV_WRAP void setInput(CV_ND InputArray blob, const String& name = "", + double scalefactor = 1.0, const Scalar& mean = Scalar()); + + /** @brief Sets the new value for the learned param of the layer. + * @param layer name or id of the layer. + * @param numParam index of the layer parameter in the Layer::blobs array. + * @param blob the new value. + * @see Layer::blobs + * @note If shape of the new blob differs from the previous shape, + * then the following forward pass may fail. + */ + CV_WRAP void setParam(int layer, int numParam, CV_ND const Mat &blob); + CV_WRAP inline void setParam(const String& layerName, int numParam, CV_ND const Mat &blob) { return setParam(getLayerId(layerName), numParam, blob); } + + /** @brief Returns parameter blob of the layer. + * @param layer name or id of the layer. + * @param numParam index of the layer parameter in the Layer::blobs array. + * @see Layer::blobs + */ + CV_WRAP Mat getParam(int layer, int numParam = 0) const; + CV_WRAP inline Mat getParam(const String& layerName, int numParam = 0) const { return getParam(getLayerId(layerName), numParam); } + + /** @brief Returns indexes of layers with unconnected outputs. + * + * FIXIT: Rework API to registerOutput() approach, deprecate this call + */ + CV_WRAP std::vector getUnconnectedOutLayers() const; + + /** @brief Returns names of layers with unconnected outputs. + * + * FIXIT: Rework API to registerOutput() approach, deprecate this call + */ + CV_WRAP std::vector getUnconnectedOutLayersNames() const; + + /** @brief Returns input and output shapes for all layers in loaded model; + * preliminary inferencing isn't necessary. + * @param netInputShapes shapes for all input blobs in net input layer. + * @param layersIds output parameter for layer IDs. + * @param inLayersShapes output parameter for input layers shapes; + * order is the same as in layersIds + * @param outLayersShapes output parameter for output layers shapes; + * order is the same as in layersIds + */ + CV_WRAP void getLayersShapes(const std::vector& netInputShapes, + CV_OUT std::vector& layersIds, + CV_OUT std::vector >& inLayersShapes, + CV_OUT std::vector >& outLayersShapes) const; + + /** @overload */ + CV_WRAP void getLayersShapes(const MatShape& netInputShape, + CV_OUT std::vector& layersIds, + CV_OUT std::vector >& inLayersShapes, + CV_OUT std::vector >& outLayersShapes) const; + + /** @brief Returns input and output shapes for layer with specified + * id in loaded model; preliminary inferencing isn't necessary. + * @param netInputShape shape input blob in net input layer. + * @param layerId id for layer. + * @param inLayerShapes output parameter for input layers shapes; + * order is the same as in layersIds + * @param outLayerShapes output parameter for output layers shapes; + * order is the same as in layersIds + */ + void getLayerShapes(const MatShape& netInputShape, + const int layerId, + CV_OUT std::vector& inLayerShapes, + CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP + + /** @overload */ + void getLayerShapes(const std::vector& netInputShapes, + const int layerId, + CV_OUT std::vector& inLayerShapes, + CV_OUT std::vector& outLayerShapes) const; // FIXIT: CV_WRAP + + /** @brief Computes FLOP for whole loaded model with specified input shapes. + * @param netInputShapes vector of shapes for all net inputs. + * @returns computed FLOP. + */ + CV_WRAP int64 getFLOPS(const std::vector& netInputShapes) const; + /** @overload */ + CV_WRAP int64 getFLOPS(const MatShape& netInputShape) const; + /** @overload */ + CV_WRAP int64 getFLOPS(const int layerId, + const std::vector& netInputShapes) const; + /** @overload */ + CV_WRAP int64 getFLOPS(const int layerId, + const MatShape& netInputShape) const; + + /** @brief Returns list of types for layer used in model. + * @param layersTypes output parameter for returning types. + */ + CV_WRAP void getLayerTypes(CV_OUT std::vector& layersTypes) const; + + /** @brief Returns count of layers of specified type. + * @param layerType type. + * @returns count of layers + */ + CV_WRAP int getLayersCount(const String& layerType) const; + + /** @brief Computes bytes number which are required to store + * all weights and intermediate blobs for model. + * @param netInputShapes vector of shapes for all net inputs. + * @param weights output parameter to store resulting bytes for weights. + * @param blobs output parameter to store resulting bytes for intermediate blobs. + */ + void getMemoryConsumption(const std::vector& netInputShapes, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; // FIXIT: CV_WRAP + /** @overload */ + CV_WRAP void getMemoryConsumption(const MatShape& netInputShape, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; + /** @overload */ + CV_WRAP void getMemoryConsumption(const int layerId, + const std::vector& netInputShapes, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; + /** @overload */ + CV_WRAP void getMemoryConsumption(const int layerId, + const MatShape& netInputShape, + CV_OUT size_t& weights, CV_OUT size_t& blobs) const; + + /** @brief Computes bytes number which are required to store + * all weights and intermediate blobs for each layer. + * @param netInputShapes vector of shapes for all net inputs. + * @param layerIds output vector to save layer IDs. + * @param weights output parameter to store resulting bytes for weights. + * @param blobs output parameter to store resulting bytes for intermediate blobs. + */ + void getMemoryConsumption(const std::vector& netInputShapes, + CV_OUT std::vector& layerIds, + CV_OUT std::vector& weights, + CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP + /** @overload */ + void getMemoryConsumption(const MatShape& netInputShape, + CV_OUT std::vector& layerIds, + CV_OUT std::vector& weights, + CV_OUT std::vector& blobs) const; // FIXIT: CV_WRAP + + /** @brief Enables or disables layer fusion in the network. + * @param fusion true to enable the fusion, false to disable. The fusion is enabled by default. + */ + CV_WRAP void enableFusion(bool fusion); + + /** @brief Enables or disables the Winograd compute branch. The Winograd compute branch can speed up + * 3x3 Convolution at a small loss of accuracy. + * @param useWinograd true to enable the Winograd compute branch. The default is true. + */ + CV_WRAP void enableWinograd(bool useWinograd); + + /** @brief Returns overall time for inference and timings (in ticks) for layers. + * + * Indexes in returned vector correspond to layers ids. Some layers can be fused with others, + * in this case zero ticks count will be return for that skipped layers. Supported by DNN_BACKEND_OPENCV on DNN_TARGET_CPU only. + * + * @param[out] timings vector for tick timings for all layers. + * @return overall ticks for model inference. + */ + CV_WRAP int64 getPerfProfile(CV_OUT std::vector& timings); + + + struct Impl; + inline Impl* getImpl() const { return impl.get(); } + inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } + friend class accessor::DnnNetAccessor; + protected: + Ptr impl; + }; + + /** @brief Reads a network model stored in Darknet model files. + * @param cfgFile path to the .cfg file with text description of the network architecture. + * @param darknetModel path to the .weights file with learned network. + * @returns Network object that ready to do forward, throw an exception in failure cases. + */ + CV_EXPORTS_W Net readNetFromDarknet(CV_WRAP_FILE_PATH const String &cfgFile, CV_WRAP_FILE_PATH const String &darknetModel = String()); + + /** @brief Reads a network model stored in Darknet model files. + * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. + * @param bufferModel A buffer contains a content of .weights file with learned network. + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromDarknet(const std::vector& bufferCfg, + const std::vector& bufferModel = std::vector()); + + /** @brief Reads a network model stored in Darknet model files. + * @param bufferCfg A buffer contains a content of .cfg file with text description of the network architecture. + * @param lenCfg Number of bytes to read from bufferCfg + * @param bufferModel A buffer contains a content of .weights file with learned network. + * @param lenModel Number of bytes to read from bufferModel + * @returns Net object. + */ + CV_EXPORTS Net readNetFromDarknet(const char *bufferCfg, size_t lenCfg, + const char *bufferModel = NULL, size_t lenModel = 0); + + /** @brief Reads a network model stored in Caffe framework's format. + * @param prototxt path to the .prototxt file with text description of the network architecture. + * @param caffeModel path to the .caffemodel file with learned network. + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromCaffe(CV_WRAP_FILE_PATH const String &prototxt, CV_WRAP_FILE_PATH const String &caffeModel = String()); + + /** @brief Reads a network model stored in Caffe model in memory. + * @param bufferProto buffer containing the content of the .prototxt file + * @param bufferModel buffer containing the content of the .caffemodel file + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromCaffe(const std::vector& bufferProto, + const std::vector& bufferModel = std::vector()); + + /** @brief Reads a network model stored in Caffe model in memory. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param bufferProto buffer containing the content of the .prototxt file + * @param lenProto length of bufferProto + * @param bufferModel buffer containing the content of the .caffemodel file + * @param lenModel length of bufferModel + * @returns Net object. + */ + CV_EXPORTS Net readNetFromCaffe(const char *bufferProto, size_t lenProto, + const char *bufferModel = NULL, size_t lenModel = 0); + + /** @brief Reads a network model stored in TensorFlow framework's format. + * @param model path to the .pb file with binary protobuf description of the network architecture + * @param config path to the .pbtxt file that contains text graph definition in protobuf format. + * Resulting Net object is built by text graph using weights from a binary one that + * let us make it more flexible. + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTensorflow(CV_WRAP_FILE_PATH const String &model, CV_WRAP_FILE_PATH const String &config = String()); + + /** @brief Reads a network model stored in TensorFlow framework's format. + * @param bufferModel buffer containing the content of the pb file + * @param bufferConfig buffer containing the content of the pbtxt file + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTensorflow(const std::vector& bufferModel, + const std::vector& bufferConfig = std::vector()); + + /** @brief Reads a network model stored in TensorFlow framework's format. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param bufferModel buffer containing the content of the pb file + * @param lenModel length of bufferModel + * @param bufferConfig buffer containing the content of the pbtxt file + * @param lenConfig length of bufferConfig + */ + CV_EXPORTS Net readNetFromTensorflow(const char *bufferModel, size_t lenModel, + const char *bufferConfig = NULL, size_t lenConfig = 0); + + /** @brief Reads a network model stored in TFLite framework's format. + * @param model path to the .tflite file with binary flatbuffers description of the network architecture + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTFLite(CV_WRAP_FILE_PATH const String &model); + + /** @brief Reads a network model stored in TFLite framework's format. + * @param bufferModel buffer containing the content of the tflite file + * @returns Net object. + */ + CV_EXPORTS_W Net readNetFromTFLite(const std::vector& bufferModel); + + /** @brief Reads a network model stored in TFLite framework's format. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param bufferModel buffer containing the content of the tflite file + * @param lenModel length of bufferModel + */ + CV_EXPORTS Net readNetFromTFLite(const char *bufferModel, size_t lenModel); + + /** + * @brief Reads a network model stored in Torch7 framework's format. + * @param model path to the file, dumped from Torch by using torch.save() function. + * @param isBinary specifies whether the network was serialized in ascii mode or binary. + * @param evaluate specifies testing phase of network. If true, it's similar to evaluate() method in Torch. + * @returns Net object. + * + * @note Ascii mode of Torch serializer is more preferable, because binary mode extensively use `long` type of C language, + * which has various bit-length on different systems. + * + * The loading file must contain serialized nn.Module object + * with importing network. Try to eliminate a custom objects from serialazing data to avoid importing errors. + * + * List of supported layers (i.e. object instances derived from Torch nn.Module class): + * - nn.Sequential + * - nn.Parallel + * - nn.Concat + * - nn.Linear + * - nn.SpatialConvolution + * - nn.SpatialMaxPooling, nn.SpatialAveragePooling + * - nn.ReLU, nn.TanH, nn.Sigmoid + * - nn.Reshape + * - nn.SoftMax, nn.LogSoftMax + * + * Also some equivalents of these classes from cunn, cudnn, and fbcunn may be successfully imported. + */ + CV_EXPORTS_W Net readNetFromTorch(CV_WRAP_FILE_PATH const String &model, bool isBinary = true, bool evaluate = true); + + /** + * @brief Read deep learning network represented in one of the supported formats. + * @param[in] model Binary file contains trained weights. The following file + * extensions are expected for models from different frameworks: + * * `*.caffemodel` (Caffe, http://caffe.berkeleyvision.org/) + * * `*.pb` (TensorFlow, https://www.tensorflow.org/) + * * `*.t7` | `*.net` (Torch, http://torch.ch/) + * * `*.weights` (Darknet, https://pjreddie.com/darknet/) + * * `*.bin` | `*.onnx` (OpenVINO, https://software.intel.com/openvino-toolkit) + * * `*.onnx` (ONNX, https://onnx.ai/) + * @param[in] config Text file contains network configuration. It could be a + * file with the following extensions: + * * `*.prototxt` (Caffe, http://caffe.berkeleyvision.org/) + * * `*.pbtxt` (TensorFlow, https://www.tensorflow.org/) + * * `*.cfg` (Darknet, https://pjreddie.com/darknet/) + * * `*.xml` (OpenVINO, https://software.intel.com/openvino-toolkit) + * @param[in] framework Explicit framework name tag to determine a format. + * @returns Net object. + * + * This function automatically detects an origin framework of trained model + * and calls an appropriate function such @ref readNetFromCaffe, @ref readNetFromTensorflow, + * @ref readNetFromTorch or @ref readNetFromDarknet. An order of @p model and @p config + * arguments does not matter. + */ + CV_EXPORTS_W Net readNet(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = "", const String& framework = ""); + + /** + * @brief Read deep learning network represented in one of the supported formats. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + * @param[in] framework Name of origin framework. + * @param[in] bufferModel A buffer with a content of binary file with weights + * @param[in] bufferConfig A buffer with a content of text file contains network configuration. + * @returns Net object. + */ + CV_EXPORTS_W Net readNet(const String& framework, const std::vector& bufferModel, + const std::vector& bufferConfig = std::vector()); + + /** @brief Loads blob which was serialized as torch.Tensor object of Torch7 framework. + * @warning This function has the same limitations as readNetFromTorch(). + */ + CV_EXPORTS_W Mat readTorchBlob(const String &filename, bool isBinary = true); + + /** @brief Load a network from Intel's Model Optimizer intermediate representation. + * @param[in] xml XML configuration file with network's topology. + * @param[in] bin Binary file with trained weights. + * @returns Net object. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_EXPORTS_W + Net readNetFromModelOptimizer(CV_WRAP_FILE_PATH const String &xml, CV_WRAP_FILE_PATH const String &bin = ""); + + /** @brief Load a network from Intel's Model Optimizer intermediate representation. + * @param[in] bufferModelConfig Buffer contains XML configuration with network's topology. + * @param[in] bufferWeights Buffer contains binary data with trained weights. + * @returns Net object. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_EXPORTS_W + Net readNetFromModelOptimizer(const std::vector& bufferModelConfig, const std::vector& bufferWeights); + + /** @brief Load a network from Intel's Model Optimizer intermediate representation. + * @param[in] bufferModelConfigPtr Pointer to buffer which contains XML configuration with network's topology. + * @param[in] bufferModelConfigSize Binary size of XML configuration data. + * @param[in] bufferWeightsPtr Pointer to buffer which contains binary data with trained weights. + * @param[in] bufferWeightsSize Binary size of trained weights data. + * @returns Net object. + * Networks imported from Intel's Model Optimizer are launched in Intel's Inference Engine + * backend. + */ + CV_EXPORTS + Net readNetFromModelOptimizer(const uchar* bufferModelConfigPtr, size_t bufferModelConfigSize, + const uchar* bufferWeightsPtr, size_t bufferWeightsSize); + + /** @brief Reads a network model ONNX. + * @param onnxFile path to the .onnx file with text description of the network architecture. + * @returns Network object that ready to do forward, throw an exception in failure cases. + */ + CV_EXPORTS_W Net readNetFromONNX(CV_WRAP_FILE_PATH const String &onnxFile); + + /** @brief Reads a network model from ONNX + * in-memory buffer. + * @param buffer memory address of the first byte of the buffer. + * @param sizeBuffer size of the buffer. + * @returns Network object that ready to do forward, throw an exception + * in failure cases. + */ + CV_EXPORTS Net readNetFromONNX(const char* buffer, size_t sizeBuffer); + + /** @brief Reads a network model from ONNX + * in-memory buffer. + * @param buffer in-memory buffer that stores the ONNX model bytes. + * @returns Network object that ready to do forward, throw an exception + * in failure cases. + */ + CV_EXPORTS_W Net readNetFromONNX(const std::vector& buffer); + + /** @brief Creates blob from .pb file. + * @param path to the .pb file with input tensor. + * @returns Mat. + */ + CV_EXPORTS_W Mat readTensorFromONNX(CV_WRAP_FILE_PATH const String& path); + + /** @brief Creates 4-dimensional blob from image. Optionally resizes and crops @p image from center, + * subtract @p mean values, scales values by @p scalefactor, swap Blue and Red channels. + * @param image input image (with 1-, 3- or 4-channels). + * @param scalefactor multiplier for @p images values. + * @param size spatial size for output image + * @param mean scalar with mean values which are subtracted from channels. Values are intended + * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. + * @param swapRB flag which indicates that swap first and last channels + * in 3-channel image is necessary. + * @param crop flag which indicates whether image will be cropped after resize or not + * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. + * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding + * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. + * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. + * @returns 4-dimensional Mat with NCHW dimensions order. + * + * @note + * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. + */ + CV_EXPORTS_W Mat blobFromImage(InputArray image, double scalefactor=1.0, const Size& size = Size(), + const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, + int ddepth=CV_32F); + + /** @brief Creates 4-dimensional blob from image. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + */ + CV_EXPORTS void blobFromImage(InputArray image, OutputArray blob, double scalefactor=1.0, + const Size& size = Size(), const Scalar& mean = Scalar(), + bool swapRB=false, bool crop=false, int ddepth=CV_32F); + + + /** @brief Creates 4-dimensional blob from series of images. Optionally resizes and + * crops @p images from center, subtract @p mean values, scales values by @p scalefactor, + * swap Blue and Red channels. + * @param images input images (all with 1-, 3- or 4-channels). + * @param size spatial size for output image + * @param mean scalar with mean values which are subtracted from channels. Values are intended + * to be in (mean-R, mean-G, mean-B) order if @p image has BGR ordering and @p swapRB is true. + * @param scalefactor multiplier for @p images values. + * @param swapRB flag which indicates that swap first and last channels + * in 3-channel image is necessary. + * @param crop flag which indicates whether image will be cropped after resize or not + * @param ddepth Depth of output blob. Choose CV_32F or CV_8U. + * @details if @p crop is true, input image is resized so one side after resize is equal to corresponding + * dimension in @p size and another one is equal or larger. Then, crop from the center is performed. + * If @p crop is false, direct resize without cropping and preserving aspect ratio is performed. + * @returns 4-dimensional Mat with NCHW dimensions order. + * + * @note + * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. + */ + CV_EXPORTS_W Mat blobFromImages(InputArrayOfArrays images, double scalefactor=1.0, + Size size = Size(), const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, + int ddepth=CV_32F); + + /** @brief Creates 4-dimensional blob from series of images. + * @details This is an overloaded member function, provided for convenience. + * It differs from the above function only in what argument(s) it accepts. + */ + CV_EXPORTS void blobFromImages(InputArrayOfArrays images, OutputArray blob, + double scalefactor=1.0, Size size = Size(), + const Scalar& mean = Scalar(), bool swapRB=false, bool crop=false, + int ddepth=CV_32F); + + /** + * @brief Enum of image processing mode. + * To facilitate the specialization pre-processing requirements of the dnn model. + * For example, the `letter box` often used in the Yolo series of models. + * @see Image2BlobParams + */ + enum ImagePaddingMode + { + DNN_PMODE_NULL = 0, // !< Default. Resize to required input size without extra processing. + DNN_PMODE_CROP_CENTER = 1, // !< Image will be cropped after resize. + DNN_PMODE_LETTERBOX = 2, // !< Resize image to the desired size while preserving the aspect ratio of original image. + }; + + /** @brief Processing params of image to blob. + * + * It includes all possible image processing operations and corresponding parameters. + * + * @see blobFromImageWithParams + * + * @note + * The order and usage of `scalefactor` and `mean` are (input - mean) * scalefactor. + * The order and usage of `scalefactor`, `size`, `mean`, `swapRB`, and `ddepth` are consistent + * with the function of @ref blobFromImage. + */ + struct CV_EXPORTS_W_SIMPLE Image2BlobParams + { + CV_WRAP Image2BlobParams(); + CV_WRAP Image2BlobParams(const Scalar& scalefactor, const Size& size = Size(), const Scalar& mean = Scalar(), + bool swapRB = false, int ddepth = CV_32F, DataLayout datalayout = DNN_LAYOUT_NCHW, + ImagePaddingMode mode = DNN_PMODE_NULL, Scalar borderValue = 0.0); + + CV_PROP_RW Scalar scalefactor; //!< scalefactor multiplier for input image values. + CV_PROP_RW Size size; //!< Spatial size for output image. + CV_PROP_RW Scalar mean; //!< Scalar with mean values which are subtracted from channels. + CV_PROP_RW bool swapRB; //!< Flag which indicates that swap first and last channels + CV_PROP_RW int ddepth; //!< Depth of output blob. Choose CV_32F or CV_8U. + CV_PROP_RW DataLayout datalayout; //!< Order of output dimensions. Choose DNN_LAYOUT_NCHW or DNN_LAYOUT_NHWC. + CV_PROP_RW ImagePaddingMode paddingmode; //!< Image padding mode. @see ImagePaddingMode. + CV_PROP_RW Scalar borderValue; //!< Value used in padding mode for padding. + + /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. + * @param rBlob rect in blob coordinates. + * @param size original input image size. + * @returns rectangle in original image coordinates. + */ + CV_WRAP Rect blobRectToImageRect(const Rect &rBlob, const Size &size); + + /** @brief Get rectangle coordinates in original image system from rectangle in blob coordinates. + * @param rBlob rect in blob coordinates. + * @param rImg result rect in image coordinates. + * @param size original input image size. + */ + CV_WRAP void blobRectsToImageRects(const std::vector &rBlob, CV_OUT std::vector& rImg, const Size& size); + }; + + /** @brief Creates 4-dimensional blob from image with given params. + * + * @details This function is an extension of @ref blobFromImage to meet more image preprocess needs. + * Given input image and preprocessing parameters, and function outputs the blob. + * + * @param image input image (all with 1-, 3- or 4-channels). + * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. + * @return 4-dimensional Mat. + */ + CV_EXPORTS_W Mat blobFromImageWithParams(InputArray image, const Image2BlobParams& param = Image2BlobParams()); + + /** @overload */ + CV_EXPORTS_W void blobFromImageWithParams(InputArray image, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); + + /** @brief Creates 4-dimensional blob from series of images with given params. + * + * @details This function is an extension of @ref blobFromImages to meet more image preprocess needs. + * Given input image and preprocessing parameters, and function outputs the blob. + * + * @param images input image (all with 1-, 3- or 4-channels). + * @param param struct of Image2BlobParams, contains all parameters needed by processing of image to blob. + * @returns 4-dimensional Mat. + */ + CV_EXPORTS_W Mat blobFromImagesWithParams(InputArrayOfArrays images, const Image2BlobParams& param = Image2BlobParams()); + + /** @overload */ + CV_EXPORTS_W void blobFromImagesWithParams(InputArrayOfArrays images, OutputArray blob, const Image2BlobParams& param = Image2BlobParams()); + + /** @brief Parse a 4D blob and output the images it contains as 2D arrays through a simpler data structure + * (std::vector). + * @param[in] blob_ 4 dimensional array (images, channels, height, width) in floating point precision (CV_32F) from + * which you would like to extract the images. + * @param[out] images_ array of 2D Mat containing the images extracted from the blob in floating point precision + * (CV_32F). They are non normalized neither mean added. The number of returned images equals the first dimension + * of the blob (batch size). Every image has a number of channels equals to the second dimension of the blob (depth). + */ + CV_EXPORTS_W void imagesFromBlob(const cv::Mat& blob_, OutputArrayOfArrays images_); + + /** @brief Convert all weights of Caffe network to half precision floating point. + * @param src Path to origin model from Caffe framework contains single + * precision floating point weights (usually has `.caffemodel` extension). + * @param dst Path to destination model with updated weights. + * @param layersTypes Set of layers types which parameters will be converted. + * By default, converts only Convolutional and Fully-Connected layers' + * weights. + * + * @note Shrinked model has no origin float32 weights so it can't be used + * in origin Caffe framework anymore. However the structure of data + * is taken from NVidia's Caffe fork: https://github.com/NVIDIA/caffe. + * So the resulting model may be used there. + */ + CV_EXPORTS_W void shrinkCaffeModel(CV_WRAP_FILE_PATH const String& src, CV_WRAP_FILE_PATH const String& dst, + const std::vector& layersTypes = std::vector()); + + /** @brief Create a text representation for a binary network stored in protocol buffer format. + * @param[in] model A path to binary network. + * @param[in] output A path to output text file to be created. + * + * @note To reduce output file size, trained weights are not included. + */ + CV_EXPORTS_W void writeTextGraph(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& output); + + /** @brief Performs non maximum suppression given boxes and corresponding scores. + + * @param bboxes a set of bounding boxes to apply NMS. + * @param scores a set of corresponding confidences. + * @param score_threshold a threshold used to filter boxes by score. + * @param nms_threshold a threshold used in non maximum suppression. + * @param indices the kept indices of bboxes after NMS. + * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. + * @param top_k if `>0`, keep at most @p top_k picked indices. + */ + CV_EXPORTS void NMSBoxes(const std::vector& bboxes, const std::vector& scores, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + CV_EXPORTS_W void NMSBoxes(const std::vector& bboxes, const std::vector& scores, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + CV_EXPORTS_AS(NMSBoxesRotated) void NMSBoxes(const std::vector& bboxes, const std::vector& scores, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + /** @brief Performs batched non maximum suppression on given boxes and corresponding scores across different classes. + + * @param bboxes a set of bounding boxes to apply NMS. + * @param scores a set of corresponding confidences. + * @param class_ids a set of corresponding class ids. Ids are integer and usually start from 0. + * @param score_threshold a threshold used to filter boxes by score. + * @param nms_threshold a threshold used in non maximum suppression. + * @param indices the kept indices of bboxes after NMS. + * @param eta a coefficient in adaptive threshold formula: \f$nms\_threshold_{i+1}=eta\cdot nms\_threshold_i\f$. + * @param top_k if `>0`, keep at most @p top_k picked indices. + */ + CV_EXPORTS void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + CV_EXPORTS_W void NMSBoxesBatched(const std::vector& bboxes, const std::vector& scores, const std::vector& class_ids, + const float score_threshold, const float nms_threshold, + CV_OUT std::vector& indices, + const float eta = 1.f, const int top_k = 0); + + /** + * @brief Enum of Soft NMS methods. + * @see softNMSBoxes + */ + enum class SoftNMSMethod + { + SOFTNMS_LINEAR = 1, + SOFTNMS_GAUSSIAN = 2 + }; + + /** @brief Performs soft non maximum suppression given boxes and corresponding scores. + * Reference: https://arxiv.org/abs/1704.04503 + * @param bboxes a set of bounding boxes to apply Soft NMS. + * @param scores a set of corresponding confidences. + * @param updated_scores a set of corresponding updated confidences. + * @param score_threshold a threshold used to filter boxes by score. + * @param nms_threshold a threshold used in non maximum suppression. + * @param indices the kept indices of bboxes after NMS. + * @param top_k keep at most @p top_k picked indices. + * @param sigma parameter of Gaussian weighting. + * @param method Gaussian or linear. + * @see SoftNMSMethod + */ + CV_EXPORTS_W void softNMSBoxes(const std::vector& bboxes, + const std::vector& scores, + CV_OUT std::vector& updated_scores, + const float score_threshold, + const float nms_threshold, + CV_OUT std::vector& indices, + size_t top_k = 0, + const float sigma = 0.5, + SoftNMSMethod method = SoftNMSMethod::SOFTNMS_GAUSSIAN); + + + /** @brief This class is presented high-level API for neural networks. + * + * Model allows to set params for preprocessing input image. + * Model creates net from file with trained weights and config, + * sets preprocessing input and runs forward pass. + */ + class CV_EXPORTS_W_SIMPLE Model + { + public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + Model(); + + Model(const Model&) = default; + Model(Model&&) = default; + Model& operator=(const Model&) = default; + Model& operator=(Model&&) = default; + + /** + * @brief Create model from deep learning network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP Model(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP Model(const Net& network); + + /** @brief Set input size for frame. + * @param[in] size New input size. + * @note If shape of the new blob less than 0, then frame size not change. + */ + CV_WRAP Model& setInputSize(const Size& size); + + /** @overload + * @param[in] width New input width. + * @param[in] height New input height. + */ + CV_WRAP inline + Model& setInputSize(int width, int height) { return setInputSize(Size(width, height)); } + + /** @brief Set mean value for frame. + * @param[in] mean Scalar with mean values which are subtracted from channels. + */ + CV_WRAP Model& setInputMean(const Scalar& mean); + + /** @brief Set scalefactor value for frame. + * @param[in] scale Multiplier for frame values. + */ + CV_WRAP Model& setInputScale(const Scalar& scale); + + /** @brief Set flag crop for frame. + * @param[in] crop Flag which indicates whether image will be cropped after resize or not. + */ + CV_WRAP Model& setInputCrop(bool crop); + + /** @brief Set flag swapRB for frame. + * @param[in] swapRB Flag which indicates that swap first and last channels. + */ + CV_WRAP Model& setInputSwapRB(bool swapRB); + + /** @brief Set output names for frame. + * @param[in] outNames Names for output layers. + */ + CV_WRAP Model& setOutputNames(const std::vector& outNames); + + /** @brief Set preprocessing parameters for frame. + * @param[in] size New input size. + * @param[in] mean Scalar with mean values which are subtracted from channels. + * @param[in] scale Multiplier for frame values. + * @param[in] swapRB Flag which indicates that swap first and last channels. + * @param[in] crop Flag which indicates whether image will be cropped after resize or not. + * blob(n, c, y, x) = scale * resize( frame(y, x, c) ) - mean(c) ) + */ + CV_WRAP void setInputParams(double scale = 1.0, const Size& size = Size(), + const Scalar& mean = Scalar(), bool swapRB = false, bool crop = false); + + /** @brief Given the @p input frame, create input blob, run net and return the output @p blobs. + * @param[in] frame The input image. + * @param[out] outs Allocated output blobs, which will store results of the computation. + */ + CV_WRAP void predict(InputArray frame, OutputArrayOfArrays outs) const; + + + // ============================== Net proxy methods ============================== + // Never expose methods with network implementation details, like: + // - addLayer, addLayerToPrev, connect, setInputsNames, setInputShape, setParam, getParam + // - getLayer*, getUnconnectedOutLayers, getUnconnectedOutLayersNames, getLayersShapes + // - forward* methods, setInput + + /// @sa Net::setPreferableBackend + CV_WRAP Model& setPreferableBackend(dnn::Backend backendId); + /// @sa Net::setPreferableTarget + CV_WRAP Model& setPreferableTarget(dnn::Target targetId); + + /// @sa Net::enableWinograd + CV_WRAP Model& enableWinograd(bool useWinograd); + + CV_DEPRECATED_EXTERNAL + operator Net&() const { return getNetwork_(); } + + //protected: - internal/tests usage only + Net& getNetwork_() const; + inline Net& getNetwork_() { return const_cast(this)->getNetwork_(); } + + struct Impl; + inline Impl* getImpl() const { return impl.get(); } + inline Impl& getImplRef() const { CV_DbgAssert(impl); return *impl.get(); } + protected: + Ptr impl; + }; + + /** @brief This class represents high-level API for classification models. + * + * ClassificationModel allows to set params for preprocessing input image. + * ClassificationModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and return top-1 prediction. + */ + class CV_EXPORTS_W_SIMPLE ClassificationModel : public Model + { + public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + ClassificationModel(); + + /** + * @brief Create classification model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP ClassificationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP ClassificationModel(const Net& network); + + /** + * @brief Set enable/disable softmax post processing option. + * + * If this option is true, softmax is applied after forward inference within the classify() function + * to convert the confidences range to [0.0-1.0]. + * This function allows you to toggle this behavior. + * Please turn true when not contain softmax layer in model. + * @param[in] enable Set enable softmax post processing within the classify() function. + */ + CV_WRAP ClassificationModel& setEnableSoftmaxPostProcessing(bool enable); + + /** + * @brief Get enable/disable softmax post processing option. + * + * This option defaults to false, softmax post processing is not applied within the classify() function. + */ + CV_WRAP bool getEnableSoftmaxPostProcessing() const; + + /** @brief Given the @p input frame, create input blob, run net and return top-1 prediction. + * @param[in] frame The input image. + */ + std::pair classify(InputArray frame); + + /** @overload */ + CV_WRAP void classify(InputArray frame, CV_OUT int& classId, CV_OUT float& conf); + }; + + /** @brief This class represents high-level API for keypoints models + * + * KeypointsModel allows to set params for preprocessing input image. + * KeypointsModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and returns the x and y coordinates of each detected keypoint + */ + class CV_EXPORTS_W_SIMPLE KeypointsModel: public Model + { + public: + /** + * @brief Create keypoints model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP KeypointsModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP KeypointsModel(const Net& network); + + /** @brief Given the @p input frame, create input blob, run net + * @param[in] frame The input image. + * @param thresh minimum confidence threshold to select a keypoint + * @returns a vector holding the x and y coordinates of each detected keypoint + * + */ + CV_WRAP std::vector estimate(InputArray frame, float thresh=0.5); + }; + + /** @brief This class represents high-level API for segmentation models + * + * SegmentationModel allows to set params for preprocessing input image. + * SegmentationModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and returns the class prediction for each pixel. + */ + class CV_EXPORTS_W_SIMPLE SegmentationModel: public Model + { + public: + /** + * @brief Create segmentation model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP SegmentationModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP SegmentationModel(const Net& network); + + /** @brief Given the @p input frame, create input blob, run net + * @param[in] frame The input image. + * @param[out] mask Allocated class prediction for each pixel + */ + CV_WRAP void segment(InputArray frame, OutputArray mask); + }; + + /** @brief This class represents high-level API for object detection networks. + * + * DetectionModel allows to set params for preprocessing input image. + * DetectionModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and return result detections. + * For DetectionModel SSD, Faster R-CNN, YOLO topologies are supported. + */ + class CV_EXPORTS_W_SIMPLE DetectionModel : public Model + { + public: + /** + * @brief Create detection model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP DetectionModel(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config = ""); + + /** + * @brief Create model from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP DetectionModel(const Net& network); + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code (need to fix bindings first) + DetectionModel(); + + /** + * @brief nmsAcrossClasses defaults to false, + * such that when non max suppression is used during the detect() function, it will do so per-class. + * This function allows you to toggle this behaviour. + * @param[in] value The new value for nmsAcrossClasses + */ + CV_WRAP DetectionModel& setNmsAcrossClasses(bool value); + + /** + * @brief Getter for nmsAcrossClasses. This variable defaults to false, + * such that when non max suppression is used during the detect() function, it will do so only per-class + */ + CV_WRAP bool getNmsAcrossClasses(); + + /** @brief Given the @p input frame, create input blob, run net and return result detections. + * @param[in] frame The input image. + * @param[out] classIds Class indexes in result detection. + * @param[out] confidences A set of corresponding confidences. + * @param[out] boxes A set of bounding boxes. + * @param[in] confThreshold A threshold used to filter boxes by confidences. + * @param[in] nmsThreshold A threshold used in non maximum suppression. + */ + CV_WRAP void detect(InputArray frame, CV_OUT std::vector& classIds, + CV_OUT std::vector& confidences, CV_OUT std::vector& boxes, + float confThreshold = 0.5f, float nmsThreshold = 0.0f); + }; + + +/** @brief This class represents high-level API for text recognition networks. + * + * TextRecognitionModel allows to set params for preprocessing input image. + * TextRecognitionModel creates net from file with trained weights and config, + * sets preprocessing input, runs forward pass and return recognition result. + * For TextRecognitionModel, CRNN-CTC is supported. + */ +class CV_EXPORTS_W_SIMPLE TextRecognitionModel : public Model +{ +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextRecognitionModel(); + + /** + * @brief Create Text Recognition model from deep learning network + * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method + * @param[in] network Net object + */ + CV_WRAP TextRecognitionModel(const Net& network); + + /** + * @brief Create text recognition model from network represented in one of the supported formats + * Call setDecodeType() and setVocabulary() after constructor to initialize the decoding method + * @param[in] model Binary file contains trained weights + * @param[in] config Text file contains network configuration + */ + CV_WRAP inline + TextRecognitionModel(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") + : TextRecognitionModel(readNet(model, config)) { /* nothing */ } + + /** + * @brief Set the decoding method of translating the network output into string + * @param[in] decodeType The decoding method of translating the network output into string, currently supported type: + * - `"CTC-greedy"` greedy decoding for the output of CTC-based methods + * - `"CTC-prefix-beam-search"` Prefix beam search decoding for the output of CTC-based methods + */ + CV_WRAP + TextRecognitionModel& setDecodeType(const std::string& decodeType); + + /** + * @brief Get the decoding method + * @return the decoding method + */ + CV_WRAP + const std::string& getDecodeType() const; + + /** + * @brief Set the decoding method options for `"CTC-prefix-beam-search"` decode usage + * @param[in] beamSize Beam size for search + * @param[in] vocPruneSize Parameter to optimize big vocabulary search, + * only take top @p vocPruneSize tokens in each search step, @p vocPruneSize <= 0 stands for disable this prune. + */ + CV_WRAP + TextRecognitionModel& setDecodeOptsCTCPrefixBeamSearch(int beamSize, int vocPruneSize = 0); + + /** + * @brief Set the vocabulary for recognition. + * @param[in] vocabulary the associated vocabulary of the network. + */ + CV_WRAP + TextRecognitionModel& setVocabulary(const std::vector& vocabulary); + + /** + * @brief Get the vocabulary for recognition. + * @return vocabulary the associated vocabulary + */ + CV_WRAP + const std::vector& getVocabulary() const; + + /** + * @brief Given the @p input frame, create input blob, run net and return recognition result + * @param[in] frame The input image + * @return The text recognition result + */ + CV_WRAP + std::string recognize(InputArray frame) const; + + /** + * @brief Given the @p input frame, create input blob, run net and return recognition result + * @param[in] frame The input image + * @param[in] roiRects List of text detection regions of interest (cv::Rect, CV_32SC4). ROIs is be cropped as the network inputs + * @param[out] results A set of text recognition results. + */ + CV_WRAP + void recognize(InputArray frame, InputArrayOfArrays roiRects, CV_OUT std::vector& results) const; +}; + + +/** @brief Base class for text detection networks + */ +class CV_EXPORTS_W_SIMPLE TextDetectionModel : public Model +{ +protected: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextDetectionModel(); + +public: + + /** @brief Performs detection + * + * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. + * + * Each result is quadrangle's 4 points in this order: + * - bottom-left + * - top-left + * - top-right + * - bottom-right + * + * Use cv::getPerspectiveTransform function to retrieve image region without perspective transformations. + * + * @note If DL model doesn't support that kind of output then result may be derived from detectTextRectangles() output. + * + * @param[in] frame The input image + * @param[out] detections array with detections' quadrangles (4 points per result) + * @param[out] confidences array with detection confidences + */ + CV_WRAP + void detect( + InputArray frame, + CV_OUT std::vector< std::vector >& detections, + CV_OUT std::vector& confidences + ) const; + + /** @overload */ + CV_WRAP + void detect( + InputArray frame, + CV_OUT std::vector< std::vector >& detections + ) const; + + /** @brief Performs detection + * + * Given the input @p frame, prepare network input, run network inference, post-process network output and return result detections. + * + * Each result is rotated rectangle. + * + * @note Result may be inaccurate in case of strong perspective transformations. + * + * @param[in] frame the input image + * @param[out] detections array with detections' RotationRect results + * @param[out] confidences array with detection confidences + */ + CV_WRAP + void detectTextRectangles( + InputArray frame, + CV_OUT std::vector& detections, + CV_OUT std::vector& confidences + ) const; + + /** @overload */ + CV_WRAP + void detectTextRectangles( + InputArray frame, + CV_OUT std::vector& detections + ) const; +}; + +/** @brief This class represents high-level API for text detection DL networks compatible with EAST model. + * + * Configurable parameters: + * - (float) confThreshold - used to filter boxes by confidences, default: 0.5f + * - (float) nmsThreshold - used in non maximum suppression, default: 0.0f + */ +class CV_EXPORTS_W_SIMPLE TextDetectionModel_EAST : public TextDetectionModel +{ +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextDetectionModel_EAST(); + + /** + * @brief Create text detection algorithm from deep learning network + * @param[in] network Net object + */ + CV_WRAP TextDetectionModel_EAST(const Net& network); + + /** + * @brief Create text detection model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP inline + TextDetectionModel_EAST(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") + : TextDetectionModel_EAST(readNet(model, config)) { /* nothing */ } + + /** + * @brief Set the detection confidence threshold + * @param[in] confThreshold A threshold used to filter boxes by confidences + */ + CV_WRAP + TextDetectionModel_EAST& setConfidenceThreshold(float confThreshold); + + /** + * @brief Get the detection confidence threshold + */ + CV_WRAP + float getConfidenceThreshold() const; + + /** + * @brief Set the detection NMS filter threshold + * @param[in] nmsThreshold A threshold used in non maximum suppression + */ + CV_WRAP + TextDetectionModel_EAST& setNMSThreshold(float nmsThreshold); + + /** + * @brief Get the detection confidence threshold + */ + CV_WRAP + float getNMSThreshold() const; +}; + +/** @brief This class represents high-level API for text detection DL networks compatible with DB model. + * + * Related publications: @cite liao2020real + * Paper: https://arxiv.org/abs/1911.08947 + * For more information about the hyper-parameters setting, please refer to https://github.com/MhLiao/DB + * + * Configurable parameters: + * - (float) binaryThreshold - The threshold of the binary map. It is usually set to 0.3. + * - (float) polygonThreshold - The threshold of text polygons. It is usually set to 0.5, 0.6, and 0.7. Default is 0.5f + * - (double) unclipRatio - The unclip ratio of the detected text region, which determines the output size. It is usually set to 2.0. + * - (int) maxCandidates - The max number of the output results. + */ +class CV_EXPORTS_W_SIMPLE TextDetectionModel_DB : public TextDetectionModel +{ +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + TextDetectionModel_DB(); + + /** + * @brief Create text detection algorithm from deep learning network. + * @param[in] network Net object. + */ + CV_WRAP TextDetectionModel_DB(const Net& network); + + /** + * @brief Create text detection model from network represented in one of the supported formats. + * An order of @p model and @p config arguments does not matter. + * @param[in] model Binary file contains trained weights. + * @param[in] config Text file contains network configuration. + */ + CV_WRAP inline + TextDetectionModel_DB(CV_WRAP_FILE_PATH const std::string& model, CV_WRAP_FILE_PATH const std::string& config = "") + : TextDetectionModel_DB(readNet(model, config)) { /* nothing */ } + + CV_WRAP TextDetectionModel_DB& setBinaryThreshold(float binaryThreshold); + CV_WRAP float getBinaryThreshold() const; + + CV_WRAP TextDetectionModel_DB& setPolygonThreshold(float polygonThreshold); + CV_WRAP float getPolygonThreshold() const; + + CV_WRAP TextDetectionModel_DB& setUnclipRatio(double unclipRatio); + CV_WRAP double getUnclipRatio() const; + + CV_WRAP TextDetectionModel_DB& setMaxCandidates(int maxCandidates); + CV_WRAP int getMaxCandidates() const; +}; + +//! @} +CV__DNN_INLINE_NS_END +} +} + +#include +#include + +/// @deprecated Include this header directly from application. Automatic inclusion will be removed +#include + +#endif /* OPENCV_DNN_DNN_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp index 27ff5bd7fd..8312a418f3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/dnn.inl.hpp @@ -1,412 +1,412 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_INL_HPP -#define OPENCV_DNN_DNN_INL_HPP - -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -template -DictValue DictValue::arrayInt(TypeIter begin, int size) -{ - DictValue res(Param::INT, new AutoBuffer(size)); - for (int j = 0; j < size; begin++, j++) - (*res.pi)[j] = *begin; - return res; -} - -template -DictValue DictValue::arrayReal(TypeIter begin, int size) -{ - DictValue res(Param::REAL, new AutoBuffer(size)); - for (int j = 0; j < size; begin++, j++) - (*res.pd)[j] = *begin; - return res; -} - -template -DictValue DictValue::arrayString(TypeIter begin, int size) -{ - DictValue res(Param::STRING, new AutoBuffer(size)); - for (int j = 0; j < size; begin++, j++) - (*res.ps)[j] = *begin; - return res; -} - -template<> -inline DictValue DictValue::get(int idx) const -{ - CV_Assert(idx == -1); - return *this; -} - -template<> -inline int64 DictValue::get(int idx) const -{ - CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); - idx = (idx == -1) ? 0 : idx; - - if (type == Param::INT) - { - return (*pi)[idx]; - } - else if (type == Param::REAL) - { - double doubleValue = (*pd)[idx]; - - double fracpart, intpart; - fracpart = std::modf(doubleValue, &intpart); - CV_Assert(fracpart == 0.0); - - return (int64)doubleValue; - } - else if (type == Param::STRING) - { - return std::atoi((*ps)[idx].c_str()); - } - else - { - CV_Assert(isInt() || isReal() || isString()); - return 0; - } -} - -template<> -inline int DictValue::get(int idx) const -{ - return (int)get(idx); -} - -inline int DictValue::getIntValue(int idx) const -{ - return (int)get(idx); -} - -template<> -inline unsigned DictValue::get(int idx) const -{ - return (unsigned)get(idx); -} - -template<> -inline bool DictValue::get(int idx) const -{ - return (get(idx) != 0); -} - -template<> -inline double DictValue::get(int idx) const -{ - CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); - idx = (idx == -1) ? 0 : idx; - - if (type == Param::REAL) - { - return (*pd)[idx]; - } - else if (type == Param::INT) - { - return (double)(*pi)[idx]; - } - else if (type == Param::STRING) - { - return std::atof((*ps)[idx].c_str()); - } - else - { - CV_Assert(isReal() || isInt() || isString()); - return 0; - } -} - -inline double DictValue::getRealValue(int idx) const -{ - return get(idx); -} - -template<> -inline float DictValue::get(int idx) const -{ - return (float)get(idx); -} - -template<> -inline String DictValue::get(int idx) const -{ - CV_Assert(isString()); - CV_Assert((idx == -1 && ps->size() == 1) || (idx >= 0 && idx < (int)ps->size())); - return (*ps)[(idx == -1) ? 0 : idx]; -} - - -inline String DictValue::getStringValue(int idx) const -{ - return get(idx); -} - -inline void DictValue::release() -{ - switch (type) - { - case Param::INT: - delete pi; - break; - case Param::STRING: - delete ps; - break; - case Param::REAL: - delete pd; - break; - case Param::BOOLEAN: - case Param::MAT: - case Param::MAT_VECTOR: - case Param::ALGORITHM: - case Param::FLOAT: - case Param::UNSIGNED_INT: - case Param::UINT64: - case Param::UCHAR: - case Param::SCALAR: - break; // unhandled - } -} - -inline DictValue::~DictValue() -{ - release(); -} - -inline DictValue & DictValue::operator=(const DictValue &r) -{ - if (&r == this) - return *this; - - if (r.type == Param::INT) - { - AutoBuffer *tmp = new AutoBuffer(*r.pi); - release(); - pi = tmp; - } - else if (r.type == Param::STRING) - { - AutoBuffer *tmp = new AutoBuffer(*r.ps); - release(); - ps = tmp; - } - else if (r.type == Param::REAL) - { - AutoBuffer *tmp = new AutoBuffer(*r.pd); - release(); - pd = tmp; - } - - type = r.type; - - return *this; -} - -inline DictValue::DictValue(const DictValue &r) - : pv(NULL) -{ - type = r.type; - - if (r.type == Param::INT) - pi = new AutoBuffer(*r.pi); - else if (r.type == Param::STRING) - ps = new AutoBuffer(*r.ps); - else if (r.type == Param::REAL) - pd = new AutoBuffer(*r.pd); -} - -inline bool DictValue::isString() const -{ - return (type == Param::STRING); -} - -inline bool DictValue::isInt() const -{ - return (type == Param::INT); -} - -inline bool DictValue::isReal() const -{ - return (type == Param::REAL || type == Param::INT); -} - -inline int DictValue::size() const -{ - switch (type) - { - case Param::INT: - return (int)pi->size(); - case Param::STRING: - return (int)ps->size(); - case Param::REAL: - return (int)pd->size(); - case Param::BOOLEAN: - case Param::MAT: - case Param::MAT_VECTOR: - case Param::ALGORITHM: - case Param::FLOAT: - case Param::UNSIGNED_INT: - case Param::UINT64: - case Param::UCHAR: - case Param::SCALAR: - break; // unhandled - } - CV_Error_(Error::StsInternal, ("Unhandled type (%d)", static_cast(type))); -} - -inline std::ostream &operator<<(std::ostream &stream, const DictValue &dictv) -{ - int i; - - if (dictv.isInt()) - { - for (i = 0; i < dictv.size() - 1; i++) - stream << dictv.get(i) << ", "; - stream << dictv.get(i); - } - else if (dictv.isReal()) - { - for (i = 0; i < dictv.size() - 1; i++) - stream << dictv.get(i) << ", "; - stream << dictv.get(i); - } - else if (dictv.isString()) - { - for (i = 0; i < dictv.size() - 1; i++) - stream << "\"" << dictv.get(i) << "\", "; - stream << dictv.get(i); - } - - return stream; -} - -///////////////////////////////////////////////////////////////// - -inline bool Dict::has(const String &key) const -{ - return dict.count(key) != 0; -} - -inline DictValue *Dict::ptr(const String &key) -{ - _Dict::iterator i = dict.find(key); - return (i == dict.end()) ? NULL : &i->second; -} - -inline const DictValue *Dict::ptr(const String &key) const -{ - _Dict::const_iterator i = dict.find(key); - return (i == dict.end()) ? NULL : &i->second; -} - -inline const DictValue &Dict::get(const String &key) const -{ - _Dict::const_iterator i = dict.find(key); - if (i == dict.end()) - CV_Error(Error::StsObjectNotFound, "Required argument \"" + key + "\" not found into dictionary"); - return i->second; -} - -template -inline T Dict::get(const String &key) const -{ - return this->get(key).get(); -} - -template -inline T Dict::get(const String &key, const T &defaultValue) const -{ - _Dict::const_iterator i = dict.find(key); - - if (i != dict.end()) - return i->second.get(); - else - return defaultValue; -} - -template -inline const T &Dict::set(const String &key, const T &value) -{ - _Dict::iterator i = dict.find(key); - - if (i != dict.end()) - i->second = DictValue(value); - else - dict.insert(std::make_pair(key, DictValue(value))); - - return value; -} - -inline void Dict::erase(const String &key) -{ - dict.erase(key); -} - -inline std::ostream &operator<<(std::ostream &stream, const Dict &dict) -{ - Dict::_Dict::const_iterator it; - for (it = dict.dict.begin(); it != dict.dict.end(); it++) - stream << it->first << " : " << it->second << "\n"; - - return stream; -} - -inline std::map::const_iterator Dict::begin() const -{ - return dict.begin(); -} - -inline std::map::const_iterator Dict::end() const -{ - return dict.end(); -} - -CV__DNN_INLINE_NS_END -} -} - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_INL_HPP +#define OPENCV_DNN_DNN_INL_HPP + +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +template +DictValue DictValue::arrayInt(TypeIter begin, int size) +{ + DictValue res(Param::INT, new AutoBuffer(size)); + for (int j = 0; j < size; begin++, j++) + (*res.pi)[j] = *begin; + return res; +} + +template +DictValue DictValue::arrayReal(TypeIter begin, int size) +{ + DictValue res(Param::REAL, new AutoBuffer(size)); + for (int j = 0; j < size; begin++, j++) + (*res.pd)[j] = *begin; + return res; +} + +template +DictValue DictValue::arrayString(TypeIter begin, int size) +{ + DictValue res(Param::STRING, new AutoBuffer(size)); + for (int j = 0; j < size; begin++, j++) + (*res.ps)[j] = *begin; + return res; +} + +template<> +inline DictValue DictValue::get(int idx) const +{ + CV_Assert(idx == -1); + return *this; +} + +template<> +inline int64 DictValue::get(int idx) const +{ + CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); + idx = (idx == -1) ? 0 : idx; + + if (type == Param::INT) + { + return (*pi)[idx]; + } + else if (type == Param::REAL) + { + double doubleValue = (*pd)[idx]; + + double fracpart, intpart; + fracpart = std::modf(doubleValue, &intpart); + CV_Assert(fracpart == 0.0); + + return (int64)doubleValue; + } + else if (type == Param::STRING) + { + return std::atoi((*ps)[idx].c_str()); + } + else + { + CV_Assert(isInt() || isReal() || isString()); + return 0; + } +} + +template<> +inline int DictValue::get(int idx) const +{ + return (int)get(idx); +} + +inline int DictValue::getIntValue(int idx) const +{ + return (int)get(idx); +} + +template<> +inline unsigned DictValue::get(int idx) const +{ + return (unsigned)get(idx); +} + +template<> +inline bool DictValue::get(int idx) const +{ + return (get(idx) != 0); +} + +template<> +inline double DictValue::get(int idx) const +{ + CV_Assert((idx == -1 && size() == 1) || (idx >= 0 && idx < size())); + idx = (idx == -1) ? 0 : idx; + + if (type == Param::REAL) + { + return (*pd)[idx]; + } + else if (type == Param::INT) + { + return (double)(*pi)[idx]; + } + else if (type == Param::STRING) + { + return std::atof((*ps)[idx].c_str()); + } + else + { + CV_Assert(isReal() || isInt() || isString()); + return 0; + } +} + +inline double DictValue::getRealValue(int idx) const +{ + return get(idx); +} + +template<> +inline float DictValue::get(int idx) const +{ + return (float)get(idx); +} + +template<> +inline String DictValue::get(int idx) const +{ + CV_Assert(isString()); + CV_Assert((idx == -1 && ps->size() == 1) || (idx >= 0 && idx < (int)ps->size())); + return (*ps)[(idx == -1) ? 0 : idx]; +} + + +inline String DictValue::getStringValue(int idx) const +{ + return get(idx); +} + +inline void DictValue::release() +{ + switch (type) + { + case Param::INT: + delete pi; + break; + case Param::STRING: + delete ps; + break; + case Param::REAL: + delete pd; + break; + case Param::BOOLEAN: + case Param::MAT: + case Param::MAT_VECTOR: + case Param::ALGORITHM: + case Param::FLOAT: + case Param::UNSIGNED_INT: + case Param::UINT64: + case Param::UCHAR: + case Param::SCALAR: + break; // unhandled + } +} + +inline DictValue::~DictValue() +{ + release(); +} + +inline DictValue & DictValue::operator=(const DictValue &r) +{ + if (&r == this) + return *this; + + if (r.type == Param::INT) + { + AutoBuffer *tmp = new AutoBuffer(*r.pi); + release(); + pi = tmp; + } + else if (r.type == Param::STRING) + { + AutoBuffer *tmp = new AutoBuffer(*r.ps); + release(); + ps = tmp; + } + else if (r.type == Param::REAL) + { + AutoBuffer *tmp = new AutoBuffer(*r.pd); + release(); + pd = tmp; + } + + type = r.type; + + return *this; +} + +inline DictValue::DictValue(const DictValue &r) + : pv(NULL) +{ + type = r.type; + + if (r.type == Param::INT) + pi = new AutoBuffer(*r.pi); + else if (r.type == Param::STRING) + ps = new AutoBuffer(*r.ps); + else if (r.type == Param::REAL) + pd = new AutoBuffer(*r.pd); +} + +inline bool DictValue::isString() const +{ + return (type == Param::STRING); +} + +inline bool DictValue::isInt() const +{ + return (type == Param::INT); +} + +inline bool DictValue::isReal() const +{ + return (type == Param::REAL || type == Param::INT); +} + +inline int DictValue::size() const +{ + switch (type) + { + case Param::INT: + return (int)pi->size(); + case Param::STRING: + return (int)ps->size(); + case Param::REAL: + return (int)pd->size(); + case Param::BOOLEAN: + case Param::MAT: + case Param::MAT_VECTOR: + case Param::ALGORITHM: + case Param::FLOAT: + case Param::UNSIGNED_INT: + case Param::UINT64: + case Param::UCHAR: + case Param::SCALAR: + break; // unhandled + } + CV_Error_(Error::StsInternal, ("Unhandled type (%d)", static_cast(type))); +} + +inline std::ostream &operator<<(std::ostream &stream, const DictValue &dictv) +{ + int i; + + if (dictv.isInt()) + { + for (i = 0; i < dictv.size() - 1; i++) + stream << dictv.get(i) << ", "; + stream << dictv.get(i); + } + else if (dictv.isReal()) + { + for (i = 0; i < dictv.size() - 1; i++) + stream << dictv.get(i) << ", "; + stream << dictv.get(i); + } + else if (dictv.isString()) + { + for (i = 0; i < dictv.size() - 1; i++) + stream << "\"" << dictv.get(i) << "\", "; + stream << dictv.get(i); + } + + return stream; +} + +///////////////////////////////////////////////////////////////// + +inline bool Dict::has(const String &key) const +{ + return dict.count(key) != 0; +} + +inline DictValue *Dict::ptr(const String &key) +{ + _Dict::iterator i = dict.find(key); + return (i == dict.end()) ? NULL : &i->second; +} + +inline const DictValue *Dict::ptr(const String &key) const +{ + _Dict::const_iterator i = dict.find(key); + return (i == dict.end()) ? NULL : &i->second; +} + +inline const DictValue &Dict::get(const String &key) const +{ + _Dict::const_iterator i = dict.find(key); + if (i == dict.end()) + CV_Error(Error::StsObjectNotFound, "Required argument \"" + key + "\" not found into dictionary"); + return i->second; +} + +template +inline T Dict::get(const String &key) const +{ + return this->get(key).get(); +} + +template +inline T Dict::get(const String &key, const T &defaultValue) const +{ + _Dict::const_iterator i = dict.find(key); + + if (i != dict.end()) + return i->second.get(); + else + return defaultValue; +} + +template +inline const T &Dict::set(const String &key, const T &value) +{ + _Dict::iterator i = dict.find(key); + + if (i != dict.end()) + i->second = DictValue(value); + else + dict.insert(std::make_pair(key, DictValue(value))); + + return value; +} + +inline void Dict::erase(const String &key) +{ + dict.erase(key); +} + +inline std::ostream &operator<<(std::ostream &stream, const Dict &dict) +{ + Dict::_Dict::const_iterator it; + for (it = dict.dict.begin(); it != dict.dict.end(); it++) + stream << it->first << " : " << it->second << "\n"; + + return stream; +} + +inline std::map::const_iterator Dict::begin() const +{ + return dict.begin(); +} + +inline std::map::const_iterator Dict::end() const +{ + return dict.end(); +} + +CV__DNN_INLINE_NS_END +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp index deabe8839e..1133da562e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.details.hpp @@ -1,78 +1,78 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -#ifndef OPENCV_DNN_LAYER_DETAILS_HPP -#define OPENCV_DNN_LAYER_DETAILS_HPP - -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -/** @brief Registers layer constructor in runtime. -* @param type string, containing type name of the layer. -* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. -* @details This macros must be placed inside the function code. -*/ -#define CV_DNN_REGISTER_LAYER_FUNC(type, constructorFunc) \ - cv::dnn::LayerFactory::registerLayer(#type, constructorFunc); - -/** @brief Registers layer class in runtime. - * @param type string, containing type name of the layer. - * @param class C++ class, derived from Layer. - * @details This macros must be placed inside the function code. - */ -#define CV_DNN_REGISTER_LAYER_CLASS(type, class) \ - cv::dnn::LayerFactory::registerLayer(#type, cv::dnn::details::_layerDynamicRegisterer); - -/** @brief Registers layer constructor on module load time. -* @param type string, containing type name of the layer. -* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. -* @details This macros must be placed outside the function code. -*/ -#define CV_DNN_REGISTER_LAYER_FUNC_STATIC(type, constructorFunc) \ -static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, constructorFunc); - -/** @brief Registers layer class on module load time. - * @param type string, containing type name of the layer. - * @param class C++ class, derived from Layer. - * @details This macros must be placed outside the function code. - */ -#define CV_DNN_REGISTER_LAYER_CLASS_STATIC(type, class) \ -Ptr __LayerStaticRegisterer_func_##type(LayerParams ¶ms) \ - { return Ptr(new class(params)); } \ -static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, __LayerStaticRegisterer_func_##type); - -namespace details { - -template -Ptr _layerDynamicRegisterer(LayerParams ¶ms) -{ - return Ptr(LayerClass::create(params)); -} - -//allows automatically register created layer on module load time -class _LayerStaticRegisterer -{ - String type; -public: - - _LayerStaticRegisterer(const String &layerType, LayerFactory::Constructor layerConstructor) - { - this->type = layerType; - LayerFactory::registerLayer(layerType, layerConstructor); - } - - ~_LayerStaticRegisterer() - { - LayerFactory::unregisterLayer(type); - } -}; - -} // namespace -CV__DNN_INLINE_NS_END -}} // namespace - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +#ifndef OPENCV_DNN_LAYER_DETAILS_HPP +#define OPENCV_DNN_LAYER_DETAILS_HPP + +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +/** @brief Registers layer constructor in runtime. +* @param type string, containing type name of the layer. +* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. +* @details This macros must be placed inside the function code. +*/ +#define CV_DNN_REGISTER_LAYER_FUNC(type, constructorFunc) \ + cv::dnn::LayerFactory::registerLayer(#type, constructorFunc); + +/** @brief Registers layer class in runtime. + * @param type string, containing type name of the layer. + * @param class C++ class, derived from Layer. + * @details This macros must be placed inside the function code. + */ +#define CV_DNN_REGISTER_LAYER_CLASS(type, class) \ + cv::dnn::LayerFactory::registerLayer(#type, cv::dnn::details::_layerDynamicRegisterer); + +/** @brief Registers layer constructor on module load time. +* @param type string, containing type name of the layer. +* @param constructorFunc pointer to the function of type LayerRegister::Constructor, which creates the layer. +* @details This macros must be placed outside the function code. +*/ +#define CV_DNN_REGISTER_LAYER_FUNC_STATIC(type, constructorFunc) \ +static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, constructorFunc); + +/** @brief Registers layer class on module load time. + * @param type string, containing type name of the layer. + * @param class C++ class, derived from Layer. + * @details This macros must be placed outside the function code. + */ +#define CV_DNN_REGISTER_LAYER_CLASS_STATIC(type, class) \ +Ptr __LayerStaticRegisterer_func_##type(LayerParams ¶ms) \ + { return Ptr(new class(params)); } \ +static cv::dnn::details::_LayerStaticRegisterer __LayerStaticRegisterer_##type(#type, __LayerStaticRegisterer_func_##type); + +namespace details { + +template +Ptr _layerDynamicRegisterer(LayerParams ¶ms) +{ + return Ptr(LayerClass::create(params)); +} + +//allows automatically register created layer on module load time +class _LayerStaticRegisterer +{ + String type; +public: + + _LayerStaticRegisterer(const String &layerType, LayerFactory::Constructor layerConstructor) + { + this->type = layerType; + LayerFactory::registerLayer(layerType, layerConstructor); + } + + ~_LayerStaticRegisterer() + { + LayerFactory::unregisterLayer(type); + } +}; + +} // namespace +CV__DNN_INLINE_NS_END +}} // namespace + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp index 44607ff9fa..a4d167564d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/layer.hpp @@ -1,88 +1,88 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_DNN_LAYER_HPP -#define OPENCV_DNN_LAYER_HPP -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN -//! @addtogroup dnn -//! @{ -//! -//! @defgroup dnnLayerFactory Utilities for New Layers Registration -//! @{ - -/** @brief %Layer factory allows to create instances of registered layers. */ -class CV_EXPORTS LayerFactory -{ -public: - - //! Each Layer class must provide this function to the factory - typedef Ptr(*Constructor)(LayerParams ¶ms); - - //! Registers the layer class with typename @p type and specified @p constructor. Thread-safe. - static void registerLayer(const String &type, Constructor constructor); - - //! Unregisters registered layer with specified type name. Thread-safe. - static void unregisterLayer(const String &type); - - //! Check if layer is registered. - static bool isLayerRegistered(const std::string& type); - - /** @brief Creates instance of registered layer. - * @param type type name of creating layer. - * @param params parameters which will be used for layer initialization. - * @note Thread-safe. - */ - static Ptr createLayerInstance(const String &type, LayerParams& params); - -private: - LayerFactory(); -}; - -//! @} -//! @} -CV__DNN_INLINE_NS_END -} -} -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_DNN_LAYER_HPP +#define OPENCV_DNN_LAYER_HPP +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN +//! @addtogroup dnn +//! @{ +//! +//! @defgroup dnnLayerFactory Utilities for New Layers Registration +//! @{ + +/** @brief %Layer factory allows to create instances of registered layers. */ +class CV_EXPORTS LayerFactory +{ +public: + + //! Each Layer class must provide this function to the factory + typedef Ptr(*Constructor)(LayerParams ¶ms); + + //! Registers the layer class with typename @p type and specified @p constructor. Thread-safe. + static void registerLayer(const String &type, Constructor constructor); + + //! Unregisters registered layer with specified type name. Thread-safe. + static void unregisterLayer(const String &type); + + //! Check if layer is registered. + static bool isLayerRegistered(const std::string& type); + + /** @brief Creates instance of registered layer. + * @param type type name of creating layer. + * @param params parameters which will be used for layer initialization. + * @note Thread-safe. + */ + static Ptr createLayerInstance(const String &type, LayerParams& params); + +private: + LayerFactory(); +}; + +//! @} +//! @} +CV__DNN_INLINE_NS_END +} +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp index 5391017440..0ad8797ddd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/shape_utils.hpp @@ -1,290 +1,290 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_DNN_DNN_SHAPE_UTILS_HPP -#define OPENCV_DNN_DNN_SHAPE_UTILS_HPP - -#include -#include // CV_MAX_DIM -#include -#include -#include - -namespace cv { -namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -//Slicing - -struct _Range : public cv::Range -{ - _Range(const Range &r) : cv::Range(r) {} - _Range(int start_, int size_ = 1) : cv::Range(start_, start_ + size_) {} -}; - -static inline Mat slice(const Mat &m, const _Range &r0) -{ - Range ranges[CV_MAX_DIM]; - for (int i = 1; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - return m(&ranges[0]); -} - -static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1) -{ - CV_Assert(m.dims >= 2); - Range ranges[CV_MAX_DIM]; - for (int i = 2; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - ranges[1] = r1; - return m(&ranges[0]); -} - -static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2) -{ - CV_Assert(m.dims >= 3); - Range ranges[CV_MAX_DIM]; - for (int i = 3; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - ranges[1] = r1; - ranges[2] = r2; - return m(&ranges[0]); -} - -static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2, const _Range &r3) -{ - CV_Assert(m.dims >= 4); - Range ranges[CV_MAX_DIM]; - for (int i = 4; i < m.dims; i++) - ranges[i] = Range::all(); - ranges[0] = r0; - ranges[1] = r1; - ranges[2] = r2; - ranges[3] = r3; - return m(&ranges[0]); -} - -static inline Mat getPlane(const Mat &m, int n, int cn) -{ - CV_Assert(m.dims > 2); - int sz[CV_MAX_DIM]; - for(int i = 2; i < m.dims; i++) - { - sz[i-2] = m.size.p[i]; - } - return Mat(m.dims - 2, sz, m.type(), (void*)m.ptr(n, cn)); -} - -static inline MatShape shape(const int* dims, const int n) -{ - MatShape shape; - shape.assign(dims, dims + n); - return shape; -} - -static inline MatShape shape(const Mat& mat) -{ - return shape(mat.size.p, mat.dims); -} - -static inline MatShape shape(const MatSize& sz) -{ - return shape(sz.p, sz.dims()); -} - -static inline MatShape shape(const UMat& mat) -{ - return shape(mat.size.p, mat.dims); -} - -#if 0 // issues with MatExpr wrapped into InputArray -static inline -MatShape shape(InputArray input) -{ - int sz[CV_MAX_DIM]; - int ndims = input.sizend(sz); - return shape(sz, ndims); -} -#endif - -namespace {inline bool is_neg(int i) { return i < 0; }} - -static inline MatShape shape(int a0, int a1=-1, int a2=-1, int a3=-1) -{ - int dims[] = {a0, a1, a2, a3}; - MatShape s = shape(dims, 4); - s.erase(std::remove_if(s.begin(), s.end(), is_neg), s.end()); - return s; -} - -static inline int total(const MatShape& shape, int start = -1, int end = -1) -{ - if (shape.empty()) - return 0; - - int dims = (int)shape.size(); - - if (start == -1) start = 0; - if (end == -1) end = dims; - - CV_CheckLE(0, start, ""); - CV_CheckLE(start, end, ""); - CV_CheckLE(end, dims, ""); - - int elems = 1; - for (int i = start; i < end; i++) - { - elems *= shape[i]; - } - return elems; -} - -// TODO: rename to countDimsElements() -static inline int total(const Mat& mat, int start = -1, int end = -1) -{ - if (mat.empty()) - return 0; - - int dims = mat.dims; - - if (start == -1) start = 0; - if (end == -1) end = dims; - - CV_CheckLE(0, start, ""); - CV_CheckLE(start, end, ""); - CV_CheckLE(end, dims, ""); - - int elems = 1; - for (int i = start; i < end; i++) - { - elems *= mat.size[i]; - } - return elems; -} - -static inline MatShape concat(const MatShape& a, const MatShape& b) -{ - MatShape c = a; - c.insert(c.end(), b.begin(), b.end()); - - return c; -} - -template -static inline std::string toString(const std::vector<_Tp>& shape, const String& name = "") -{ - std::ostringstream ss; - if (!name.empty()) - ss << name << ' '; - ss << '['; - for(size_t i = 0, n = shape.size(); i < n; ++i) - ss << ' ' << shape[i]; - ss << " ]"; - return ss.str(); -} - -template -static inline void print(const std::vector<_Tp>& shape, const String& name = "") -{ - std::cout << toString(shape, name) << std::endl; -} -template -static inline std::ostream& operator<<(std::ostream &out, const std::vector<_Tp>& shape) -{ - out << toString(shape); - return out; -} - -/// @brief Converts axis from `[-dims; dims)` (similar to Python's slice notation) to `[0; dims)` range. -static inline -int normalize_axis(int axis, int dims) -{ - CV_Check(axis, axis >= -dims && axis < dims, ""); - axis = (axis < 0) ? (dims + axis) : axis; - CV_DbgCheck(axis, axis >= 0 && axis < dims, ""); - return axis; -} - -static inline -int normalize_axis(int axis, const MatShape& shape) -{ - return normalize_axis(axis, (int)shape.size()); -} - -static inline -Range normalize_axis_range(const Range& r, int axisSize) -{ - if (r == Range::all()) - return Range(0, axisSize); - CV_CheckGE(r.start, 0, ""); - Range clamped(r.start, - r.end > 0 ? std::min(r.end, axisSize) : axisSize + r.end + 1); - CV_DbgCheckGE(clamped.start, 0, ""); - CV_CheckLT(clamped.start, clamped.end, ""); - CV_CheckLE(clamped.end, axisSize, ""); - return clamped; -} - -static inline -bool isAllOnes(const MatShape &inputShape, int startPos, int endPos) -{ - CV_Assert(!inputShape.empty()); - - CV_CheckGE((int) inputShape.size(), startPos, ""); - CV_CheckGE(startPos, 0, ""); - CV_CheckLE(startPos, endPos, ""); - CV_CheckLE((size_t)endPos, inputShape.size(), ""); - - for (size_t i = startPos; i < endPos; i++) - { - if (inputShape[i] != 1) - return false; - } - return true; -} - -CV__DNN_INLINE_NS_END -} -} -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_DNN_DNN_SHAPE_UTILS_HPP +#define OPENCV_DNN_DNN_SHAPE_UTILS_HPP + +#include +#include // CV_MAX_DIM +#include +#include +#include + +namespace cv { +namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +//Slicing + +struct _Range : public cv::Range +{ + _Range(const Range &r) : cv::Range(r) {} + _Range(int start_, int size_ = 1) : cv::Range(start_, start_ + size_) {} +}; + +static inline Mat slice(const Mat &m, const _Range &r0) +{ + Range ranges[CV_MAX_DIM]; + for (int i = 1; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + return m(&ranges[0]); +} + +static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1) +{ + CV_Assert(m.dims >= 2); + Range ranges[CV_MAX_DIM]; + for (int i = 2; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + ranges[1] = r1; + return m(&ranges[0]); +} + +static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2) +{ + CV_Assert(m.dims >= 3); + Range ranges[CV_MAX_DIM]; + for (int i = 3; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + ranges[1] = r1; + ranges[2] = r2; + return m(&ranges[0]); +} + +static inline Mat slice(const Mat &m, const _Range &r0, const _Range &r1, const _Range &r2, const _Range &r3) +{ + CV_Assert(m.dims >= 4); + Range ranges[CV_MAX_DIM]; + for (int i = 4; i < m.dims; i++) + ranges[i] = Range::all(); + ranges[0] = r0; + ranges[1] = r1; + ranges[2] = r2; + ranges[3] = r3; + return m(&ranges[0]); +} + +static inline Mat getPlane(const Mat &m, int n, int cn) +{ + CV_Assert(m.dims > 2); + int sz[CV_MAX_DIM]; + for(int i = 2; i < m.dims; i++) + { + sz[i-2] = m.size.p[i]; + } + return Mat(m.dims - 2, sz, m.type(), (void*)m.ptr(n, cn)); +} + +static inline MatShape shape(const int* dims, const int n) +{ + MatShape shape; + shape.assign(dims, dims + n); + return shape; +} + +static inline MatShape shape(const Mat& mat) +{ + return shape(mat.size.p, mat.dims); +} + +static inline MatShape shape(const MatSize& sz) +{ + return shape(sz.p, sz.dims()); +} + +static inline MatShape shape(const UMat& mat) +{ + return shape(mat.size.p, mat.dims); +} + +#if 0 // issues with MatExpr wrapped into InputArray +static inline +MatShape shape(InputArray input) +{ + int sz[CV_MAX_DIM]; + int ndims = input.sizend(sz); + return shape(sz, ndims); +} +#endif + +namespace {inline bool is_neg(int i) { return i < 0; }} + +static inline MatShape shape(int a0, int a1=-1, int a2=-1, int a3=-1) +{ + int dims[] = {a0, a1, a2, a3}; + MatShape s = shape(dims, 4); + s.erase(std::remove_if(s.begin(), s.end(), is_neg), s.end()); + return s; +} + +static inline int total(const MatShape& shape, int start = -1, int end = -1) +{ + if (shape.empty()) + return 0; + + int dims = (int)shape.size(); + + if (start == -1) start = 0; + if (end == -1) end = dims; + + CV_CheckLE(0, start, ""); + CV_CheckLE(start, end, ""); + CV_CheckLE(end, dims, ""); + + int elems = 1; + for (int i = start; i < end; i++) + { + elems *= shape[i]; + } + return elems; +} + +// TODO: rename to countDimsElements() +static inline int total(const Mat& mat, int start = -1, int end = -1) +{ + if (mat.empty()) + return 0; + + int dims = mat.dims; + + if (start == -1) start = 0; + if (end == -1) end = dims; + + CV_CheckLE(0, start, ""); + CV_CheckLE(start, end, ""); + CV_CheckLE(end, dims, ""); + + int elems = 1; + for (int i = start; i < end; i++) + { + elems *= mat.size[i]; + } + return elems; +} + +static inline MatShape concat(const MatShape& a, const MatShape& b) +{ + MatShape c = a; + c.insert(c.end(), b.begin(), b.end()); + + return c; +} + +template +static inline std::string toString(const std::vector<_Tp>& shape, const String& name = "") +{ + std::ostringstream ss; + if (!name.empty()) + ss << name << ' '; + ss << '['; + for(size_t i = 0, n = shape.size(); i < n; ++i) + ss << ' ' << shape[i]; + ss << " ]"; + return ss.str(); +} + +template +static inline void print(const std::vector<_Tp>& shape, const String& name = "") +{ + std::cout << toString(shape, name) << std::endl; +} +template +static inline std::ostream& operator<<(std::ostream &out, const std::vector<_Tp>& shape) +{ + out << toString(shape); + return out; +} + +/// @brief Converts axis from `[-dims; dims)` (similar to Python's slice notation) to `[0; dims)` range. +static inline +int normalize_axis(int axis, int dims) +{ + CV_Check(axis, axis >= -dims && axis < dims, ""); + axis = (axis < 0) ? (dims + axis) : axis; + CV_DbgCheck(axis, axis >= 0 && axis < dims, ""); + return axis; +} + +static inline +int normalize_axis(int axis, const MatShape& shape) +{ + return normalize_axis(axis, (int)shape.size()); +} + +static inline +Range normalize_axis_range(const Range& r, int axisSize) +{ + if (r == Range::all()) + return Range(0, axisSize); + CV_CheckGE(r.start, 0, ""); + Range clamped(r.start, + r.end > 0 ? std::min(r.end, axisSize) : axisSize + r.end + 1); + CV_DbgCheckGE(clamped.start, 0, ""); + CV_CheckLT(clamped.start, clamped.end, ""); + CV_CheckLE(clamped.end, axisSize, ""); + return clamped; +} + +static inline +bool isAllOnes(const MatShape &inputShape, int startPos, int endPos) +{ + CV_Assert(!inputShape.empty()); + + CV_CheckGE((int) inputShape.size(), startPos, ""); + CV_CheckGE(startPos, 0, ""); + CV_CheckLE(startPos, endPos, ""); + CV_CheckLE((size_t)endPos, inputShape.size(), ""); + + for (size_t i = startPos; i < endPos; i++) + { + if (inputShape[i] != 1) + return false; + } + return true; +} + +CV__DNN_INLINE_NS_END +} +} +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp index fdce655e37..71dd3ab8d6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/debug_utils.hpp @@ -1,24 +1,24 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_DNN_UTILS_DEBUG_UTILS_HPP -#define OPENCV_DNN_UTILS_DEBUG_UTILS_HPP - -#include "../dnn.hpp" - -namespace cv { namespace dnn { -CV__DNN_INLINE_NS_BEGIN - -/** - * @brief Skip model import after diagnostic run in readNet() functions. - * @param[in] skip Indicates whether to skip the import. - * - * This is an internal OpenCV function not intended for users. - */ -CV_EXPORTS void skipModelImport(bool skip); - -CV__DNN_INLINE_NS_END -}} // namespace - -#endif // OPENCV_DNN_UTILS_DEBUG_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_DNN_UTILS_DEBUG_UTILS_HPP +#define OPENCV_DNN_UTILS_DEBUG_UTILS_HPP + +#include "../dnn.hpp" + +namespace cv { namespace dnn { +CV__DNN_INLINE_NS_BEGIN + +/** + * @brief Skip model import after diagnostic run in readNet() functions. + * @param[in] skip Indicates whether to skip the import. + * + * This is an internal OpenCV function not intended for users. + */ +CV_EXPORTS void skipModelImport(bool skip); + +CV__DNN_INLINE_NS_END +}} // namespace + +#endif // OPENCV_DNN_UTILS_DEBUG_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp index fba659671a..b81806ed5a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/utils/inference_engine.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. - -#ifndef OPENCV_DNN_UTILS_INF_ENGINE_HPP -#define OPENCV_DNN_UTILS_INF_ENGINE_HPP - -#include "../dnn.hpp" - -namespace cv { namespace dnn { -CV__DNN_INLINE_NS_BEGIN - - -/* Values for 'OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE' parameter */ -/// @deprecated -#define CV_DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_API "NN_BUILDER" -/// @deprecated -#define CV_DNN_BACKEND_INFERENCE_ENGINE_NGRAPH "NGRAPH" - -/** @brief Returns Inference Engine internal backend API. - * - * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. - * - * `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable) is ignored since 4.6.0. - * - * @deprecated - */ -CV_EXPORTS_W cv::String getInferenceEngineBackendType(); - -/** @brief Specify Inference Engine internal backend API. - * - * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. - * - * @returns previous value of internal backend API - * - * @deprecated - */ -CV_EXPORTS_W cv::String setInferenceEngineBackendType(const cv::String& newBackendType); - - -/** @brief Release a Myriad device (binded by OpenCV). - * - * Single Myriad device cannot be shared across multiple processes which uses - * Inference Engine's Myriad plugin. - */ -CV_EXPORTS_W void resetMyriadDevice(); - - -/* Values for 'OPENCV_DNN_IE_VPU_TYPE' parameter */ -#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_UNSPECIFIED "" -/// Intel(R) Movidius(TM) Neural Compute Stick, NCS (USB 03e7:2150), Myriad2 (https://software.intel.com/en-us/movidius-ncs) -#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_2 "Myriad2" -/// Intel(R) Neural Compute Stick 2, NCS2 (USB 03e7:2485), MyriadX (https://software.intel.com/ru-ru/neural-compute-stick) -#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X "MyriadX" -#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_ARM_COMPUTE "ARM_COMPUTE" -#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_X86 "X86" - - -/** @brief Returns Inference Engine VPU type. - * - * See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros. - */ -CV_EXPORTS_W cv::String getInferenceEngineVPUType(); - -/** @brief Returns Inference Engine CPU type. - * - * Specify OpenVINO plugin: CPU or ARM. - */ -CV_EXPORTS_W cv::String getInferenceEngineCPUType(); - -/** @brief Release a HDDL plugin. - */ -CV_EXPORTS_W void releaseHDDLPlugin(); - - -CV__DNN_INLINE_NS_END -}} // namespace - -#endif // OPENCV_DNN_UTILS_INF_ENGINE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. + +#ifndef OPENCV_DNN_UTILS_INF_ENGINE_HPP +#define OPENCV_DNN_UTILS_INF_ENGINE_HPP + +#include "../dnn.hpp" + +namespace cv { namespace dnn { +CV__DNN_INLINE_NS_BEGIN + + +/* Values for 'OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE' parameter */ +/// @deprecated +#define CV_DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_API "NN_BUILDER" +/// @deprecated +#define CV_DNN_BACKEND_INFERENCE_ENGINE_NGRAPH "NGRAPH" + +/** @brief Returns Inference Engine internal backend API. + * + * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. + * + * `OPENCV_DNN_BACKEND_INFERENCE_ENGINE_TYPE` runtime parameter (environment variable) is ignored since 4.6.0. + * + * @deprecated + */ +CV_EXPORTS_W cv::String getInferenceEngineBackendType(); + +/** @brief Specify Inference Engine internal backend API. + * + * See values of `CV_DNN_BACKEND_INFERENCE_ENGINE_*` macros. + * + * @returns previous value of internal backend API + * + * @deprecated + */ +CV_EXPORTS_W cv::String setInferenceEngineBackendType(const cv::String& newBackendType); + + +/** @brief Release a Myriad device (binded by OpenCV). + * + * Single Myriad device cannot be shared across multiple processes which uses + * Inference Engine's Myriad plugin. + */ +CV_EXPORTS_W void resetMyriadDevice(); + + +/* Values for 'OPENCV_DNN_IE_VPU_TYPE' parameter */ +#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_UNSPECIFIED "" +/// Intel(R) Movidius(TM) Neural Compute Stick, NCS (USB 03e7:2150), Myriad2 (https://software.intel.com/en-us/movidius-ncs) +#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_2 "Myriad2" +/// Intel(R) Neural Compute Stick 2, NCS2 (USB 03e7:2485), MyriadX (https://software.intel.com/ru-ru/neural-compute-stick) +#define CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X "MyriadX" +#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_ARM_COMPUTE "ARM_COMPUTE" +#define CV_DNN_INFERENCE_ENGINE_CPU_TYPE_X86 "X86" + + +/** @brief Returns Inference Engine VPU type. + * + * See values of `CV_DNN_INFERENCE_ENGINE_VPU_TYPE_*` macros. + */ +CV_EXPORTS_W cv::String getInferenceEngineVPUType(); + +/** @brief Returns Inference Engine CPU type. + * + * Specify OpenVINO plugin: CPU or ARM. + */ +CV_EXPORTS_W cv::String getInferenceEngineCPUType(); + +/** @brief Release a HDDL plugin. + */ +CV_EXPORTS_W void releaseHDDLPlugin(); + + +CV__DNN_INLINE_NS_END +}} // namespace + +#endif // OPENCV_DNN_UTILS_INF_ENGINE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp b/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp index a651e05826..5cf0870b44 100644 --- a/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/dnn/version.hpp @@ -1,21 +1,21 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_DNN_VERSION_HPP -#define OPENCV_DNN_VERSION_HPP - -/// Use with major OpenCV version only. -#define OPENCV_DNN_API_VERSION 20241223 - -#if !defined CV_DOXYGEN && !defined CV_STATIC_ANALYSIS && !defined CV_DNN_DONT_ADD_INLINE_NS -#define CV__DNN_INLINE_NS __CV_CAT(dnn4_v, OPENCV_DNN_API_VERSION) -#define CV__DNN_INLINE_NS_BEGIN namespace CV__DNN_INLINE_NS { -#define CV__DNN_INLINE_NS_END } -namespace cv { namespace dnn { namespace CV__DNN_INLINE_NS { } using namespace CV__DNN_INLINE_NS; }} -#else -#define CV__DNN_INLINE_NS_BEGIN -#define CV__DNN_INLINE_NS_END -#endif - -#endif // OPENCV_DNN_VERSION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_DNN_VERSION_HPP +#define OPENCV_DNN_VERSION_HPP + +/// Use with major OpenCV version only. +#define OPENCV_DNN_API_VERSION 20241223 + +#if !defined CV_DOXYGEN && !defined CV_STATIC_ANALYSIS && !defined CV_DNN_DONT_ADD_INLINE_NS +#define CV__DNN_INLINE_NS __CV_CAT(dnn4_v, OPENCV_DNN_API_VERSION) +#define CV__DNN_INLINE_NS_BEGIN namespace CV__DNN_INLINE_NS { +#define CV__DNN_INLINE_NS_END } +namespace cv { namespace dnn { namespace CV__DNN_INLINE_NS { } using namespace CV__DNN_INLINE_NS; }} +#else +#define CV__DNN_INLINE_NS_BEGIN +#define CV__DNN_INLINE_NS_END +#endif + +#endif // OPENCV_DNN_VERSION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/features2d.hpp b/3rdParty/opencv-4.11.0/opencv2/features2d.hpp index 43dcd02ee3..b4c4dde712 100644 --- a/3rdParty/opencv-4.11.0/opencv2/features2d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/features2d.hpp @@ -1,1602 +1,1602 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_FEATURES_2D_HPP -#define OPENCV_FEATURES_2D_HPP - -#include "opencv2/opencv_modules.hpp" -#include "opencv2/core.hpp" - -#ifdef HAVE_OPENCV_FLANN -#include "opencv2/flann/miniflann.hpp" -#endif - -/** - @defgroup features2d 2D Features Framework - @{ - @defgroup features2d_main Feature Detection and Description - @defgroup features2d_match Descriptor Matchers - - Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables - you to easily switch between different algorithms solving the same problem. This section is - devoted to matching descriptors that are represented as vectors in a multidimensional space. - All objects that implement vector descriptor matchers inherit the DescriptorMatcher interface. - - @defgroup features2d_draw Drawing Function of Keypoints and Matches - @defgroup features2d_category Object Categorization - - This section describes approaches based on local 2D features and used to categorize objects. - - @defgroup feature2d_hal Hardware Acceleration Layer - @{ - @defgroup features2d_hal_interface Interface - @} - @} - */ - -namespace cv -{ - -//! @addtogroup features2d_main -//! @{ - -// //! writes vector of keypoints to the file storage -// CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector& keypoints); -// //! reads vector of keypoints from the specified file storage node -// CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector& keypoints); - -/** @brief A class filters a vector of keypoints. - - Because now it is difficult to provide a convenient interface for all usage scenarios of the - keypoints filter class, it has only several needed by now static methods. - */ -class CV_EXPORTS KeyPointsFilter -{ -public: - KeyPointsFilter(){} - - /* - * Remove keypoints within borderPixels of an image edge. - */ - static void runByImageBorder( std::vector& keypoints, Size imageSize, int borderSize ); - /* - * Remove keypoints of sizes out of range. - */ - static void runByKeypointSize( std::vector& keypoints, float minSize, - float maxSize=FLT_MAX ); - /* - * Remove keypoints from some image by mask for pixels of this image. - */ - static void runByPixelsMask( std::vector& keypoints, const Mat& mask ); - /* - * Remove objects from some image and a vector of points by mask for pixels of this image - */ - static void runByPixelsMask2VectorPoint(std::vector &keypoints, std::vector > &removeFrom, const Mat &mask); - /* - * Remove duplicated keypoints. - */ - static void removeDuplicated( std::vector& keypoints ); - /* - * Remove duplicated keypoints and sort the remaining keypoints - */ - static void removeDuplicatedSorted( std::vector& keypoints ); - - /* - * Retain the specified number of the best keypoints (according to the response) - */ - static void retainBest( std::vector& keypoints, int npoints ); -}; - - -/************************************ Base Classes ************************************/ - -/** @brief Abstract base class for 2D image feature detectors and descriptor extractors -*/ -#ifdef __EMSCRIPTEN__ -class CV_EXPORTS_W Feature2D : public Algorithm -#else -class CV_EXPORTS_W Feature2D : public virtual Algorithm -#endif -{ -public: - virtual ~Feature2D(); - - /** @brief Detects keypoints in an image (first variant) or image set (second variant). - - @param image Image. - @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set - of keypoints detected in images[i] . - @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer - matrix with non-zero values in the region of interest. - */ - CV_WRAP virtual void detect( InputArray image, - CV_OUT std::vector& keypoints, - InputArray mask=noArray() ); - - /** @overload - @param images Image set. - @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set - of keypoints detected in images[i] . - @param masks Masks for each input image specifying where to look for keypoints (optional). - masks[i] is a mask for images[i]. - */ - CV_WRAP virtual void detect( InputArrayOfArrays images, - CV_OUT std::vector >& keypoints, - InputArrayOfArrays masks=noArray() ); - - /** @brief Computes the descriptors for a set of keypoints detected in an image (first variant) or image set - (second variant). - - @param image Image. - @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be - computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint - with several dominant orientations (for each orientation). - @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are - descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the - descriptor for keypoint j-th keypoint. - */ - CV_WRAP virtual void compute( InputArray image, - CV_OUT CV_IN_OUT std::vector& keypoints, - OutputArray descriptors ); - - /** @overload - - @param images Image set. - @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be - computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint - with several dominant orientations (for each orientation). - @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are - descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the - descriptor for keypoint j-th keypoint. - */ - CV_WRAP virtual void compute( InputArrayOfArrays images, - CV_OUT CV_IN_OUT std::vector >& keypoints, - OutputArrayOfArrays descriptors ); - - /** Detects keypoints and computes the descriptors */ - CV_WRAP virtual void detectAndCompute( InputArray image, InputArray mask, - CV_OUT std::vector& keypoints, - OutputArray descriptors, - bool useProvidedKeypoints=false ); - - CV_WRAP virtual int descriptorSize() const; - CV_WRAP virtual int descriptorType() const; - CV_WRAP virtual int defaultNorm() const; - - CV_WRAP void write( const String& fileName ) const; - - CV_WRAP void read( const String& fileName ); - - virtual void write( FileStorage&) const CV_OVERRIDE; - - // see corresponding cv::Algorithm method - CV_WRAP virtual void read( const FileNode&) CV_OVERRIDE; - - //! Return true if detector object is empty - CV_WRAP virtual bool empty() const CV_OVERRIDE; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - // see corresponding cv::Algorithm method - CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } -#if CV_VERSION_MAJOR < 5 - inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } -#endif -}; - -/** Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch -between different algorithms solving the same problem. All objects that implement keypoint detectors -inherit the FeatureDetector interface. */ -typedef Feature2D FeatureDetector; - -/** Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you -to easily switch between different algorithms solving the same problem. This section is devoted to -computing descriptors represented as vectors in a multidimensional space. All objects that implement -the vector descriptor extractors inherit the DescriptorExtractor interface. - */ -typedef Feature2D DescriptorExtractor; - - -/** @brief Class for implementing the wrapper which makes detectors and extractors to be affine invariant, -described as ASIFT in @cite YM11 . -*/ -class CV_EXPORTS_W AffineFeature : public Feature2D -{ -public: - /** - @param backend The detector/extractor you want to use as backend. - @param maxTilt The highest power index of tilt factor. 5 is used in the paper as tilt sampling range n. - @param minTilt The lowest power index of tilt factor. 0 is used in the paper. - @param tiltStep Tilt sampling step \f$\delta_t\f$ in Algorithm 1 in the paper. - @param rotateStepBase Rotation sampling step factor b in Algorithm 1 in the paper. - */ - CV_WRAP static Ptr create(const Ptr& backend, - int maxTilt = 5, int minTilt = 0, float tiltStep = 1.4142135623730951f, float rotateStepBase = 72); - - CV_WRAP virtual void setViewParams(const std::vector& tilts, const std::vector& rolls) = 0; - CV_WRAP virtual void getViewParams(std::vector& tilts, std::vector& rolls) const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -typedef AffineFeature AffineFeatureDetector; -typedef AffineFeature AffineDescriptorExtractor; - - -/** @brief Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform -(SIFT) algorithm by D. Lowe @cite Lowe04 . -*/ -class CV_EXPORTS_W SIFT : public Feature2D -{ -public: - /** - @param nfeatures The number of best features to retain. The features are ranked by their scores - (measured in SIFT algorithm as the local contrast) - - @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The - number of octaves is computed automatically from the image resolution. - - @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform - (low-contrast) regions. The larger the threshold, the less features are produced by the detector. - - @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When - nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set - this argument to 0.09. - - @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning - is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are - filtered out (more features are retained). - - @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image - is captured with a weak camera with soft lenses, you might want to reduce the number. - - @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps - index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option - is disabled by default. - */ - CV_WRAP static Ptr create(int nfeatures = 0, int nOctaveLayers = 3, - double contrastThreshold = 0.04, double edgeThreshold = 10, - double sigma = 1.6, bool enable_precise_upscale = false); - - /** @brief Create SIFT with specified descriptorType. - @param nfeatures The number of best features to retain. The features are ranked by their scores - (measured in SIFT algorithm as the local contrast) - - @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The - number of octaves is computed automatically from the image resolution. - - @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform - (low-contrast) regions. The larger the threshold, the less features are produced by the detector. - - @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When - nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set - this argument to 0.09. - - @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning - is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are - filtered out (more features are retained). - - @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image - is captured with a weak camera with soft lenses, you might want to reduce the number. - - @param descriptorType The type of descriptors. Only CV_32F and CV_8U are supported. - - @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps - index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option - is disabled by default. - */ - CV_WRAP static Ptr create(int nfeatures, int nOctaveLayers, - double contrastThreshold, double edgeThreshold, - double sigma, int descriptorType, bool enable_precise_upscale = false); - - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - CV_WRAP virtual void setNFeatures(int maxFeatures) = 0; - CV_WRAP virtual int getNFeatures() const = 0; - - CV_WRAP virtual void setNOctaveLayers(int nOctaveLayers) = 0; - CV_WRAP virtual int getNOctaveLayers() const = 0; - - CV_WRAP virtual void setContrastThreshold(double contrastThreshold) = 0; - CV_WRAP virtual double getContrastThreshold() const = 0; - - CV_WRAP virtual void setEdgeThreshold(double edgeThreshold) = 0; - CV_WRAP virtual double getEdgeThreshold() const = 0; - - CV_WRAP virtual void setSigma(double sigma) = 0; - CV_WRAP virtual double getSigma() const = 0; -}; - -typedef SIFT SiftFeatureDetector; -typedef SIFT SiftDescriptorExtractor; - - -/** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 . - */ -class CV_EXPORTS_W BRISK : public Feature2D -{ -public: - /** @brief The BRISK constructor - - @param thresh AGAST detection threshold score. - @param octaves detection octaves. Use 0 to do single scale. - @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a - keypoint. - */ - CV_WRAP static Ptr create(int thresh=30, int octaves=3, float patternScale=1.0f); - - /** @brief The BRISK constructor for a custom pattern - - @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for - keypoint scale 1). - @param numberList defines the number of sampling points on the sampling circle. Must be the same - size as radiusList.. - @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint - scale 1). - @param dMin threshold for the long pairings used for orientation determination (in pixels for - keypoint scale 1). - @param indexChange index remapping of the bits. */ - CV_WRAP static Ptr create(const std::vector &radiusList, const std::vector &numberList, - float dMax=5.85f, float dMin=8.2f, const std::vector& indexChange=std::vector()); - - /** @brief The BRISK constructor for a custom pattern, detection threshold and octaves - - @param thresh AGAST detection threshold score. - @param octaves detection octaves. Use 0 to do single scale. - @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for - keypoint scale 1). - @param numberList defines the number of sampling points on the sampling circle. Must be the same - size as radiusList.. - @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint - scale 1). - @param dMin threshold for the long pairings used for orientation determination (in pixels for - keypoint scale 1). - @param indexChange index remapping of the bits. */ - CV_WRAP static Ptr create(int thresh, int octaves, const std::vector &radiusList, - const std::vector &numberList, float dMax=5.85f, float dMin=8.2f, - const std::vector& indexChange=std::vector()); - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - /** @brief Set detection threshold. - @param threshold AGAST detection threshold score. - */ - CV_WRAP virtual void setThreshold(int threshold) = 0; - CV_WRAP virtual int getThreshold() const = 0; - - /** @brief Set detection octaves. - @param octaves detection octaves. Use 0 to do single scale. - */ - CV_WRAP virtual void setOctaves(int octaves) = 0; - CV_WRAP virtual int getOctaves() const = 0; - /** @brief Set detection patternScale. - @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a - keypoint. - */ - CV_WRAP virtual void setPatternScale(float patternScale) = 0; - CV_WRAP virtual float getPatternScale() const = 0; -}; - -/** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor - -described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, selects -the strongest features using FAST or Harris response, finds their orientation using first-order -moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or -k-tuples) are rotated according to the measured orientation). - */ -class CV_EXPORTS_W ORB : public Feature2D -{ -public: - enum ScoreType { HARRIS_SCORE=0, FAST_SCORE=1 }; - static const int kBytes = 32; - - /** @brief The ORB constructor - - @param nfeatures The maximum number of features to retain. - @param scaleFactor Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical - pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor - will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor - will mean that to cover certain scale range you will need more pyramid levels and so the speed - will suffer. - @param nlevels The number of pyramid levels. The smallest level will have linear size equal to - input_image_linear_size/pow(scaleFactor, nlevels - firstLevel). - @param edgeThreshold This is size of the border where the features are not detected. It should - roughly match the patchSize parameter. - @param firstLevel The level of pyramid to put source image to. Previous layers are filled - with upscaled source image. - @param WTA_K The number of points that produce each element of the oriented BRIEF descriptor. The - default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, - so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 - random points (of course, those point coordinates are random, but they are generated from the - pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel - rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such - output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, - denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each - bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3). - @param scoreType The default HARRIS_SCORE means that Harris algorithm is used to rank features - (the score is written to KeyPoint::score and is used to retain best nfeatures features); - FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints, - but it is a little faster to compute. - @param patchSize size of the patch used by the oriented BRIEF descriptor. Of course, on smaller - pyramid layers the perceived image area covered by a feature will be larger. - @param fastThreshold the fast threshold - */ - CV_WRAP static Ptr create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31, - int firstLevel=0, int WTA_K=2, ORB::ScoreType scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20); - - CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; - CV_WRAP virtual int getMaxFeatures() const = 0; - - CV_WRAP virtual void setScaleFactor(double scaleFactor) = 0; - CV_WRAP virtual double getScaleFactor() const = 0; - - CV_WRAP virtual void setNLevels(int nlevels) = 0; - CV_WRAP virtual int getNLevels() const = 0; - - CV_WRAP virtual void setEdgeThreshold(int edgeThreshold) = 0; - CV_WRAP virtual int getEdgeThreshold() const = 0; - - CV_WRAP virtual void setFirstLevel(int firstLevel) = 0; - CV_WRAP virtual int getFirstLevel() const = 0; - - CV_WRAP virtual void setWTA_K(int wta_k) = 0; - CV_WRAP virtual int getWTA_K() const = 0; - - CV_WRAP virtual void setScoreType(ORB::ScoreType scoreType) = 0; - CV_WRAP virtual ORB::ScoreType getScoreType() const = 0; - - CV_WRAP virtual void setPatchSize(int patchSize) = 0; - CV_WRAP virtual int getPatchSize() const = 0; - - CV_WRAP virtual void setFastThreshold(int fastThreshold) = 0; - CV_WRAP virtual int getFastThreshold() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @brief Maximally stable extremal region extractor - -The class encapsulates all the parameters of the %MSER extraction algorithm (see [wiki -article](http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions)). - -- there are two different implementation of %MSER: one for grey image, one for color image - -- the grey image algorithm is taken from: @cite nister2008linear ; the paper claims to be faster -than union-find method; it actually get 1.5~2m/s on my centrino L7200 1.2GHz laptop. - -- the color image algorithm is taken from: @cite forssen2007maximally ; it should be much slower -than grey image method ( 3~4 times ) - -- (Python) A complete example showing the use of the %MSER detector can be found at samples/python/mser.py -*/ -class CV_EXPORTS_W MSER : public Feature2D -{ -public: - /** @brief Full constructor for %MSER detector - - @param delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$ - @param min_area prune the area which smaller than minArea - @param max_area prune the area which bigger than maxArea - @param max_variation prune the area have similar size to its children - @param min_diversity for color image, trace back to cut off mser with diversity less than min_diversity - @param max_evolution for color image, the evolution steps - @param area_threshold for color image, the area threshold to cause re-initialize - @param min_margin for color image, ignore too small margin - @param edge_blur_size for color image, the aperture size for edge blur - */ - CV_WRAP static Ptr create( int delta=5, int min_area=60, int max_area=14400, - double max_variation=0.25, double min_diversity=.2, - int max_evolution=200, double area_threshold=1.01, - double min_margin=0.003, int edge_blur_size=5 ); - - /** @brief Detect %MSER regions - - @param image input image (8UC1, 8UC3 or 8UC4, must be greater or equal than 3x3) - @param msers resulting list of point sets - @param bboxes resulting bounding boxes - */ - CV_WRAP virtual void detectRegions( InputArray image, - CV_OUT std::vector >& msers, - CV_OUT std::vector& bboxes ) = 0; - - CV_WRAP virtual void setDelta(int delta) = 0; - CV_WRAP virtual int getDelta() const = 0; - - CV_WRAP virtual void setMinArea(int minArea) = 0; - CV_WRAP virtual int getMinArea() const = 0; - - CV_WRAP virtual void setMaxArea(int maxArea) = 0; - CV_WRAP virtual int getMaxArea() const = 0; - - CV_WRAP virtual void setMaxVariation(double maxVariation) = 0; - CV_WRAP virtual double getMaxVariation() const = 0; - - CV_WRAP virtual void setMinDiversity(double minDiversity) = 0; - CV_WRAP virtual double getMinDiversity() const = 0; - - CV_WRAP virtual void setMaxEvolution(int maxEvolution) = 0; - CV_WRAP virtual int getMaxEvolution() const = 0; - - CV_WRAP virtual void setAreaThreshold(double areaThreshold) = 0; - CV_WRAP virtual double getAreaThreshold() const = 0; - - CV_WRAP virtual void setMinMargin(double min_margin) = 0; - CV_WRAP virtual double getMinMargin() const = 0; - - CV_WRAP virtual void setEdgeBlurSize(int edge_blur_size) = 0; - CV_WRAP virtual int getEdgeBlurSize() const = 0; - - CV_WRAP virtual void setPass2Only(bool f) = 0; - CV_WRAP virtual bool getPass2Only() const = 0; - - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - - -/** @brief Wrapping class for feature detection using the FAST method. : - */ -class CV_EXPORTS_W FastFeatureDetector : public Feature2D -{ -public: - enum DetectorType - { - TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2 - }; - enum - { - THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002 - }; - - - CV_WRAP static Ptr create( int threshold=10, - bool nonmaxSuppression=true, - FastFeatureDetector::DetectorType type=FastFeatureDetector::TYPE_9_16 ); - - CV_WRAP virtual void setThreshold(int threshold) = 0; - CV_WRAP virtual int getThreshold() const = 0; - - CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; - CV_WRAP virtual bool getNonmaxSuppression() const = 0; - - CV_WRAP virtual void setType(FastFeatureDetector::DetectorType type) = 0; - CV_WRAP virtual FastFeatureDetector::DetectorType getType() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @overload */ -CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression=true ); - -/** @brief Detects corners using the FAST algorithm - -@param image grayscale image where keypoints (corners) are detected. -@param keypoints keypoints detected on the image. -@param threshold threshold on difference between intensity of the central pixel and pixels of a -circle around this pixel. -@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners -(keypoints). -@param type one of the three neighborhoods as defined in the paper: -FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12, -FastFeatureDetector::TYPE_5_8 - -Detects corners using the FAST algorithm by @cite Rosten06 . - -@note In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8, -cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner -detection, use cv.FAST.detect() method. - */ -CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression, FastFeatureDetector::DetectorType type ); - - -/** @brief Wrapping class for feature detection using the AGAST method. : - */ -class CV_EXPORTS_W AgastFeatureDetector : public Feature2D -{ -public: - enum DetectorType - { - AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3, - }; - - enum - { - THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001, - }; - - CV_WRAP static Ptr create( int threshold=10, - bool nonmaxSuppression=true, - AgastFeatureDetector::DetectorType type = AgastFeatureDetector::OAST_9_16); - - CV_WRAP virtual void setThreshold(int threshold) = 0; - CV_WRAP virtual int getThreshold() const = 0; - - CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; - CV_WRAP virtual bool getNonmaxSuppression() const = 0; - - CV_WRAP virtual void setType(AgastFeatureDetector::DetectorType type) = 0; - CV_WRAP virtual AgastFeatureDetector::DetectorType getType() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @overload */ -CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression=true ); - -/** @brief Detects corners using the AGAST algorithm - -@param image grayscale image where keypoints (corners) are detected. -@param keypoints keypoints detected on the image. -@param threshold threshold on difference between intensity of the central pixel and pixels of a -circle around this pixel. -@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners -(keypoints). -@param type one of the four neighborhoods as defined in the paper: -AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, -AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16 - -For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results. -The 32-bit binary tree tables were generated automatically from original code using perl script. -The perl script and examples of tree generation are placed in features2d/doc folder. -Detects corners using the AGAST algorithm by @cite mair2010_agast . - - */ -CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, - int threshold, bool nonmaxSuppression, AgastFeatureDetector::DetectorType type ); - -/** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. : - */ -class CV_EXPORTS_W GFTTDetector : public Feature2D -{ -public: - CV_WRAP static Ptr create( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, - int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); - CV_WRAP static Ptr create( int maxCorners, double qualityLevel, double minDistance, - int blockSize, int gradiantSize, bool useHarrisDetector=false, double k=0.04 ); - CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; - CV_WRAP virtual int getMaxFeatures() const = 0; - - CV_WRAP virtual void setQualityLevel(double qlevel) = 0; - CV_WRAP virtual double getQualityLevel() const = 0; - - CV_WRAP virtual void setMinDistance(double minDistance) = 0; - CV_WRAP virtual double getMinDistance() const = 0; - - CV_WRAP virtual void setBlockSize(int blockSize) = 0; - CV_WRAP virtual int getBlockSize() const = 0; - - CV_WRAP virtual void setGradientSize(int gradientSize_) = 0; - CV_WRAP virtual int getGradientSize() = 0; - - CV_WRAP virtual void setHarrisDetector(bool val) = 0; - CV_WRAP virtual bool getHarrisDetector() const = 0; - - CV_WRAP virtual void setK(double k) = 0; - CV_WRAP virtual double getK() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @brief Class for extracting blobs from an image. : - -The class implements a simple algorithm for extracting blobs from an image: - -1. Convert the source image to binary images by applying thresholding with several thresholds from - minThreshold (inclusive) to maxThreshold (exclusive) with distance thresholdStep between - neighboring thresholds. -2. Extract connected components from every binary image by findContours and calculate their - centers. -3. Group centers from several binary images by their coordinates. Close centers form one group that - corresponds to one blob, which is controlled by the minDistBetweenBlobs parameter. -4. From the groups, estimate final centers of blobs and their radiuses and return as locations and - sizes of keypoints. - -This class performs several filtrations of returned blobs. You should set filterBy\* to true/false -to turn on/off corresponding filtration. Available filtrations: - -- **By color**. This filter compares the intensity of a binary image at the center of a blob to -blobColor. If they differ, the blob is filtered out. Use blobColor = 0 to extract dark blobs -and blobColor = 255 to extract light blobs. -- **By area**. Extracted blobs have an area between minArea (inclusive) and maxArea (exclusive). -- **By circularity**. Extracted blobs have circularity -(\f$\frac{4*\pi*Area}{perimeter * perimeter}\f$) between minCircularity (inclusive) and -maxCircularity (exclusive). -- **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio -between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive). -- **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between -minConvexity (inclusive) and maxConvexity (exclusive). - -Default values of parameters are tuned to extract dark circular blobs. - */ -class CV_EXPORTS_W SimpleBlobDetector : public Feature2D -{ -public: - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW float thresholdStep; - CV_PROP_RW float minThreshold; - CV_PROP_RW float maxThreshold; - CV_PROP_RW size_t minRepeatability; - CV_PROP_RW float minDistBetweenBlobs; - - CV_PROP_RW bool filterByColor; - CV_PROP_RW uchar blobColor; - - CV_PROP_RW bool filterByArea; - CV_PROP_RW float minArea, maxArea; - - CV_PROP_RW bool filterByCircularity; - CV_PROP_RW float minCircularity, maxCircularity; - - CV_PROP_RW bool filterByInertia; - CV_PROP_RW float minInertiaRatio, maxInertiaRatio; - - CV_PROP_RW bool filterByConvexity; - CV_PROP_RW float minConvexity, maxConvexity; - - CV_PROP_RW bool collectContours; - - void read( const FileNode& fn ); - void write( FileStorage& fs ) const; - }; - - CV_WRAP static Ptr - create(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); - - CV_WRAP virtual void setParams(const SimpleBlobDetector::Params& params ) = 0; - CV_WRAP virtual SimpleBlobDetector::Params getParams() const = 0; - - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - CV_WRAP virtual const std::vector >& getBlobContours() const; -}; - - -/** @brief Class implementing the KAZE keypoint detector and descriptor extractor, described in @cite ABD12 . - -@note AKAZE descriptor can only be used with KAZE or AKAZE keypoints .. [ABD12] KAZE Features. Pablo -F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on Computer Vision -(ECCV), Fiorenze, Italy, October 2012. -*/ -class CV_EXPORTS_W KAZE : public Feature2D -{ -public: - enum DiffusivityType - { - DIFF_PM_G1 = 0, - DIFF_PM_G2 = 1, - DIFF_WEICKERT = 2, - DIFF_CHARBONNIER = 3 - }; - - /** @brief The KAZE constructor - - @param extended Set to enable extraction of extended (128-byte) descriptor. - @param upright Set to enable use of upright descriptors (non rotation-invariant). - @param threshold Detector response threshold to accept point - @param nOctaves Maximum octave evolution of the image - @param nOctaveLayers Default number of sublevels per scale level - @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or - DIFF_CHARBONNIER - */ - CV_WRAP static Ptr create(bool extended=false, bool upright=false, - float threshold = 0.001f, - int nOctaves = 4, int nOctaveLayers = 4, - KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2); - - CV_WRAP virtual void setExtended(bool extended) = 0; - CV_WRAP virtual bool getExtended() const = 0; - - CV_WRAP virtual void setUpright(bool upright) = 0; - CV_WRAP virtual bool getUpright() const = 0; - - CV_WRAP virtual void setThreshold(double threshold) = 0; - CV_WRAP virtual double getThreshold() const = 0; - - CV_WRAP virtual void setNOctaves(int octaves) = 0; - CV_WRAP virtual int getNOctaves() const = 0; - - CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; - CV_WRAP virtual int getNOctaveLayers() const = 0; - - CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; - CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; -}; - -/** @brief Class implementing the AKAZE keypoint detector and descriptor extractor, described in @cite ANB13. - -@details AKAZE descriptors can only be used with KAZE or AKAZE keypoints. This class is thread-safe. - -@note When you need descriptors use Feature2D::detectAndCompute, which -provides better performance. When using Feature2D::detect followed by -Feature2D::compute scale space pyramid is computed twice. - -@note AKAZE implements T-API. When image is passed as UMat some parts of the algorithm -will use OpenCL. - -@note [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear -Scale Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. In -British Machine Vision Conference (BMVC), Bristol, UK, September 2013. - -*/ -class CV_EXPORTS_W AKAZE : public Feature2D -{ -public: - // AKAZE descriptor type - enum DescriptorType - { - DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation - DESCRIPTOR_KAZE = 3, - DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation - DESCRIPTOR_MLDB = 5 - }; - - /** @brief The AKAZE constructor - - @param descriptor_type Type of the extracted descriptor: DESCRIPTOR_KAZE, - DESCRIPTOR_KAZE_UPRIGHT, DESCRIPTOR_MLDB or DESCRIPTOR_MLDB_UPRIGHT. - @param descriptor_size Size of the descriptor in bits. 0 -\> Full size - @param descriptor_channels Number of channels in the descriptor (1, 2, 3) - @param threshold Detector response threshold to accept point - @param nOctaves Maximum octave evolution of the image - @param nOctaveLayers Default number of sublevels per scale level - @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or - DIFF_CHARBONNIER - @param max_points Maximum amount of returned points. In case if image contains - more features, then the features with highest response are returned. - Negative value means no limitation. - */ - CV_WRAP static Ptr create(AKAZE::DescriptorType descriptor_type = AKAZE::DESCRIPTOR_MLDB, - int descriptor_size = 0, int descriptor_channels = 3, - float threshold = 0.001f, int nOctaves = 4, - int nOctaveLayers = 4, KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2, - int max_points = -1); - - CV_WRAP virtual void setDescriptorType(AKAZE::DescriptorType dtype) = 0; - CV_WRAP virtual AKAZE::DescriptorType getDescriptorType() const = 0; - - CV_WRAP virtual void setDescriptorSize(int dsize) = 0; - CV_WRAP virtual int getDescriptorSize() const = 0; - - CV_WRAP virtual void setDescriptorChannels(int dch) = 0; - CV_WRAP virtual int getDescriptorChannels() const = 0; - - CV_WRAP virtual void setThreshold(double threshold) = 0; - CV_WRAP virtual double getThreshold() const = 0; - - CV_WRAP virtual void setNOctaves(int octaves) = 0; - CV_WRAP virtual int getNOctaves() const = 0; - - CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; - CV_WRAP virtual int getNOctaveLayers() const = 0; - - CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; - CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; - CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; - - CV_WRAP virtual void setMaxPoints(int max_points) = 0; - CV_WRAP virtual int getMaxPoints() const = 0; -}; - - -/****************************************************************************************\ -* Distance * -\****************************************************************************************/ - -template -struct CV_EXPORTS Accumulator -{ - typedef T Type; -}; - -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; -template<> struct Accumulator { typedef float Type; }; - -/* - * Squared Euclidean distance functor - */ -template -struct CV_EXPORTS SL2 -{ - static const NormTypes normType = NORM_L2SQR; - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return normL2Sqr(a, b, size); - } -}; - -/* - * Euclidean distance functor - */ -template -struct L2 -{ - static const NormTypes normType = NORM_L2; - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return (ResultType)std::sqrt((double)normL2Sqr(a, b, size)); - } -}; - -/* - * Manhattan distance (city block distance) functor - */ -template -struct L1 -{ - static const NormTypes normType = NORM_L1; - typedef T ValueType; - typedef typename Accumulator::Type ResultType; - - ResultType operator()( const T* a, const T* b, int size ) const - { - return normL1(a, b, size); - } -}; - -//! @} features2d_main - -/****************************************************************************************\ -* DescriptorMatcher * -\****************************************************************************************/ - -//! @addtogroup features2d_match -//! @{ - -/** @brief Abstract base class for matching keypoint descriptors. - -It has two groups of match methods: for matching descriptors of an image with another image or with -an image set. - */ -class CV_EXPORTS_W DescriptorMatcher : public Algorithm -{ -public: - enum MatcherType - { - FLANNBASED = 1, - BRUTEFORCE = 2, - BRUTEFORCE_L1 = 3, - BRUTEFORCE_HAMMING = 4, - BRUTEFORCE_HAMMINGLUT = 5, - BRUTEFORCE_SL2 = 6 - }; - - virtual ~DescriptorMatcher(); - - /** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor - collection. - - If the collection is not empty, the new descriptors are added to existing train descriptors. - - @param descriptors Descriptors to add. Each descriptors[i] is a set of descriptors from the same - train image. - */ - CV_WRAP virtual void add( InputArrayOfArrays descriptors ); - - /** @brief Returns a constant link to the train descriptor collection trainDescCollection . - */ - CV_WRAP const std::vector& getTrainDescriptors() const; - - /** @brief Clears the train descriptor collections. - */ - CV_WRAP virtual void clear() CV_OVERRIDE; - - /** @brief Returns true if there are no train descriptors in the both collections. - */ - CV_WRAP virtual bool empty() const CV_OVERRIDE; - - /** @brief Returns true if the descriptor matcher supports masking permissible matches. - */ - CV_WRAP virtual bool isMaskSupported() const = 0; - - /** @brief Trains a descriptor matcher - - Trains a descriptor matcher (for example, the flann index). In all methods to match, the method - train() is run every time before matching. Some descriptor matchers (for example, BruteForceMatcher) - have an empty implementation of this method. Other matchers really train their inner structures (for - example, FlannBasedMatcher trains flann::Index ). - */ - CV_WRAP virtual void train(); - - /** @brief Finds the best match for each descriptor from a query set. - - @param queryDescriptors Query set of descriptors. - @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors - collection stored in the class object. - @param matches Matches. If a query descriptor is masked out in mask , no match is added for this - descriptor. So, matches size may be smaller than the query descriptors count. - @param mask Mask specifying permissible matches between an input query and train matrices of - descriptors. - - In the first variant of this method, the train descriptors are passed as an input argument. In the - second variant of the method, train descriptors collection that was set by DescriptorMatcher::add is - used. Optional mask (or masks) can be passed to specify which query and training descriptors can be - matched. Namely, queryDescriptors[i] can be matched with trainDescriptors[j] only if - mask.at\(i,j) is non-zero. - */ - CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors, - CV_OUT std::vector& matches, InputArray mask=noArray() ) const; - - /** @brief Finds the k best matches for each descriptor from a query set. - - @param queryDescriptors Query set of descriptors. - @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors - collection stored in the class object. - @param mask Mask specifying permissible matches between an input query and train matrices of - descriptors. - @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. - @param k Count of best matches found per each query descriptor or less if a query descriptor has - less than k possible matches in total. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - - These extended variants of DescriptorMatcher::match methods find several best matches for each query - descriptor. The matches are returned in the distance increasing order. See DescriptorMatcher::match - for the details about query and train descriptors. - */ - CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors, - CV_OUT std::vector >& matches, int k, - InputArray mask=noArray(), bool compactResult=false ) const; - - /** @brief For each query descriptor, finds the training descriptors not farther than the specified distance. - - @param queryDescriptors Query set of descriptors. - @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors - collection stored in the class object. - @param matches Found matches. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - @param maxDistance Threshold for the distance between matched descriptors. Distance means here - metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured - in Pixels)! - @param mask Mask specifying permissible matches between an input query and train matrices of - descriptors. - - For each query descriptor, the methods find such training descriptors that the distance between the - query descriptor and the training descriptor is equal or smaller than maxDistance. Found matches are - returned in the distance increasing order. - */ - CV_WRAP void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors, - CV_OUT std::vector >& matches, float maxDistance, - InputArray mask=noArray(), bool compactResult=false ) const; - - /** @overload - @param queryDescriptors Query set of descriptors. - @param matches Matches. If a query descriptor is masked out in mask , no match is added for this - descriptor. So, matches size may be smaller than the query descriptors count. - @param masks Set of masks. Each masks[i] specifies permissible matches between the input query - descriptors and stored train descriptors from the i-th image trainDescCollection[i]. - */ - CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector& matches, - InputArrayOfArrays masks=noArray() ); - /** @overload - @param queryDescriptors Query set of descriptors. - @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. - @param k Count of best matches found per each query descriptor or less if a query descriptor has - less than k possible matches in total. - @param masks Set of masks. Each masks[i] specifies permissible matches between the input query - descriptors and stored train descriptors from the i-th image trainDescCollection[i]. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - */ - CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ); - /** @overload - @param queryDescriptors Query set of descriptors. - @param matches Found matches. - @param maxDistance Threshold for the distance between matched descriptors. Distance means here - metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured - in Pixels)! - @param masks Set of masks. Each masks[i] specifies permissible matches between the input query - descriptors and stored train descriptors from the i-th image trainDescCollection[i]. - @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is - false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, - the matches vector does not contain matches for fully masked-out query descriptors. - */ - CV_WRAP void radiusMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ); - - - CV_WRAP void write( const String& fileName ) const - { - FileStorage fs(fileName, FileStorage::WRITE); - write(fs); - } - - CV_WRAP void read( const String& fileName ) - { - FileStorage fs(fileName, FileStorage::READ); - read(fs.root()); - } - // Reads matcher object from a file node - // see corresponding cv::Algorithm method - CV_WRAP virtual void read( const FileNode& ) CV_OVERRIDE; - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const CV_OVERRIDE; - - /** @brief Clones the matcher. - - @param emptyTrainData If emptyTrainData is false, the method creates a deep copy of the object, - that is, copies both parameters and train data. If emptyTrainData is true, the method creates an - object copy with the current parameters but with empty train data. - */ - CV_WRAP CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const = 0; - - /** @brief Creates a descriptor matcher of a given type with the default parameters (using default - constructor). - - @param descriptorMatcherType Descriptor matcher type. Now the following matcher types are - supported: - - `BruteForce` (it uses L2 ) - - `BruteForce-L1` - - `BruteForce-Hamming` - - `BruteForce-Hamming(2)` - - `FlannBased` - */ - CV_WRAP static Ptr create( const String& descriptorMatcherType ); - - CV_WRAP static Ptr create( const DescriptorMatcher::MatcherType& matcherType ); - - - // see corresponding cv::Algorithm method - CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } -#if CV_VERSION_MAJOR < 5 - inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } -#endif - -protected: - /** - * Class to work with descriptors from several images as with one merged matrix. - * It is used e.g. in FlannBasedMatcher. - */ - class CV_EXPORTS DescriptorCollection - { - public: - DescriptorCollection(); - DescriptorCollection( const DescriptorCollection& collection ); - virtual ~DescriptorCollection(); - - // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. - void set( const std::vector& descriptors ); - virtual void clear(); - - const Mat& getDescriptors() const; - Mat getDescriptor( int imgIdx, int localDescIdx ) const; - Mat getDescriptor( int globalDescIdx ) const; - void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; - - int size() const; - - protected: - Mat mergedDescriptors; - std::vector startIdxs; - }; - - //! In fact the matching is implemented only by the following two methods. These methods suppose - //! that the class object has been trained already. Public match methods call these methods - //! after calling train(). - virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; - virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; - - static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx ); - static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx ); - - CV_NODISCARD_STD static Mat clone_op( Mat m ) { return m.clone(); } - void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const; - - //! Collection of descriptors from train images. - std::vector trainDescCollection; - std::vector utrainDescCollection; -}; - -/** @brief Brute-force descriptor matcher. - -For each descriptor in the first set, this matcher finds the closest descriptor in the second set -by trying each one. This descriptor matcher supports masking permissible matches of descriptor -sets. - */ -class CV_EXPORTS_W BFMatcher : public DescriptorMatcher -{ -public: - /** @brief Brute-force matcher constructor (obsolete). Please use BFMatcher.create() - * - * - */ - CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false ); - - virtual ~BFMatcher() {} - - virtual bool isMaskSupported() const CV_OVERRIDE { return true; } - - /** @brief Brute-force matcher create method. - @param normType One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are - preferable choices for SIFT and SURF descriptors, NORM_HAMMING should be used with ORB, BRISK and - BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor - description). - @param crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k - nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with - k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the - matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent - pairs. Such technique usually produces best results with minimal number of outliers when there are - enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper. - */ - CV_WRAP static Ptr create( int normType=NORM_L2, bool crossCheck=false ) ; - - CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; -protected: - virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - - int normType; - bool crossCheck; -}; - -#if defined(HAVE_OPENCV_FLANN) || defined(CV_DOXYGEN) - -/** @brief Flann-based descriptor matcher. - -This matcher trains cv::flann::Index on a train descriptor collection and calls its nearest search -methods to find the best matches. So, this matcher may be faster when matching a large train -collection than the brute force matcher. FlannBasedMatcher does not support masking permissible -matches of descriptor sets because flann::Index does not support this. : - */ -class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher -{ -public: - CV_WRAP FlannBasedMatcher( const Ptr& indexParams=makePtr(), - const Ptr& searchParams=makePtr() ); - - virtual void add( InputArrayOfArrays descriptors ) CV_OVERRIDE; - virtual void clear() CV_OVERRIDE; - - // Reads matcher object from a file node - virtual void read( const FileNode& ) CV_OVERRIDE; - // Writes matcher object to a file storage - virtual void write( FileStorage& ) const CV_OVERRIDE; - - virtual void train() CV_OVERRIDE; - virtual bool isMaskSupported() const CV_OVERRIDE; - - CV_WRAP static Ptr create(); - - CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; -protected: - static void convertToDMatches( const DescriptorCollection& descriptors, - const Mat& indices, const Mat& distances, - std::vector >& matches ); - - virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, - InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; - - Ptr indexParams; - Ptr searchParams; - Ptr flannIndex; - - DescriptorCollection mergedDescriptors; - int addedDescCount; -}; - -#endif - -//! @} features2d_match - -/****************************************************************************************\ -* Drawing functions * -\****************************************************************************************/ - -//! @addtogroup features2d_draw -//! @{ - -enum struct DrawMatchesFlags -{ - DEFAULT = 0, //!< Output image matrix will be created (Mat::create), - //!< i.e. existing memory of output image may be reused. - //!< Two source image, matches and single keypoints will be drawn. - //!< For each keypoint only the center point will be drawn (without - //!< the circle around keypoint with keypoint size and orientation). - DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create). - //!< Matches will be drawn on existing content of output image. - NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn. - DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and - //!< orientation will be drawn. -}; -CV_ENUM_FLAGS(DrawMatchesFlags) - -/** @brief Draws keypoints. - -@param image Source image. -@param keypoints Keypoints from the source image. -@param outImage Output image. Its content depends on the flags value defining what is drawn in the -output image. See possible flags bit values below. -@param color Color of keypoints. -@param flags Flags setting drawing features. Possible flags bit values are defined by -DrawMatchesFlags. See details above in drawMatches . - -@note -For Python API, flags are modified as cv.DRAW_MATCHES_FLAGS_DEFAULT, -cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG, -cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS - */ -CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector& keypoints, InputOutputArray outImage, - const Scalar& color=Scalar::all(-1), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -/** @brief Draws the found matches of keypoints from two images. - -@param img1 First source image. -@param keypoints1 Keypoints from the first source image. -@param img2 Second source image. -@param keypoints2 Keypoints from the second source image. -@param matches1to2 Matches from the first image to the second one, which means that keypoints1[i] -has a corresponding point in keypoints2[matches[i]] . -@param outImg Output image. Its content depends on the flags value defining what is drawn in the -output image. See possible flags bit values below. -@param matchColor Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) -, the color is generated randomly. -@param singlePointColor Color of single keypoints (circles), which means that keypoints do not -have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly. -@param matchesMask Mask determining which matches are drawn. If the mask is empty, all matches are -drawn. -@param flags Flags setting drawing features. Possible flags bit values are defined by -DrawMatchesFlags. - -This function draws matches of keypoints from two images in the output image. Match is a line -connecting two keypoints (circles). See cv::DrawMatchesFlags. - */ -CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, - InputArray img2, const std::vector& keypoints2, - const std::vector& matches1to2, InputOutputArray outImg, - const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), - const std::vector& matchesMask=std::vector(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -/** @overload */ -CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, - InputArray img2, const std::vector& keypoints2, - const std::vector& matches1to2, InputOutputArray outImg, - const int matchesThickness, const Scalar& matchColor=Scalar::all(-1), - const Scalar& singlePointColor=Scalar::all(-1), const std::vector& matchesMask=std::vector(), - DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector& keypoints1, - InputArray img2, const std::vector& keypoints2, - const std::vector >& matches1to2, InputOutputArray outImg, - const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), - const std::vector >& matchesMask=std::vector >(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); - -//! @} features2d_draw - -/****************************************************************************************\ -* Functions to evaluate the feature detectors and [generic] descriptor extractors * -\****************************************************************************************/ - -//! @addtogroup features2d_main -//! @{ - -CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, - std::vector* keypoints1, std::vector* keypoints2, - float& repeatability, int& correspCount, - const Ptr& fdetector=Ptr() ); - -CV_EXPORTS void computeRecallPrecisionCurve( const std::vector >& matches1to2, - const std::vector >& correctMatches1to2Mask, - std::vector& recallPrecisionCurve ); - -CV_EXPORTS float getRecall( const std::vector& recallPrecisionCurve, float l_precision ); -CV_EXPORTS int getNearestPoint( const std::vector& recallPrecisionCurve, float l_precision ); - -//! @} - -/****************************************************************************************\ -* Bag of visual words * -\****************************************************************************************/ - -//! @addtogroup features2d_category -//! @{ - -/** @brief Abstract base class for training the *bag of visual words* vocabulary from a set of descriptors. - -For details, see, for example, *Visual Categorization with Bags of Keypoints* by Gabriella Csurka, -Christopher R. Dance, Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. : - */ -class CV_EXPORTS_W BOWTrainer -{ -public: - BOWTrainer(); - virtual ~BOWTrainer(); - - /** @brief Adds descriptors to a training set. - - @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a - descriptor. - - The training set is clustered using clustermethod to construct the vocabulary. - */ - CV_WRAP void add( const Mat& descriptors ); - - /** @brief Returns a training set of descriptors. - */ - CV_WRAP const std::vector& getDescriptors() const; - - /** @brief Returns the count of all descriptors stored in the training set. - */ - CV_WRAP int descriptorsCount() const; - - CV_WRAP virtual void clear(); - - /** @overload */ - CV_WRAP virtual Mat cluster() const = 0; - - /** @brief Clusters train descriptors. - - @param descriptors Descriptors to cluster. Each row of the descriptors matrix is a descriptor. - Descriptors are not added to the inner train descriptor set. - - The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first - variant of the method, train descriptors stored in the object are clustered. In the second variant, - input descriptors are clustered. - */ - CV_WRAP virtual Mat cluster( const Mat& descriptors ) const = 0; - -protected: - std::vector descriptors; - int size; -}; - -/** @brief kmeans -based class to train visual vocabulary using the *bag of visual words* approach. : - */ -class CV_EXPORTS_W BOWKMeansTrainer : public BOWTrainer -{ -public: - /** @brief The constructor. - - @see cv::kmeans - */ - CV_WRAP BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), - int attempts=3, int flags=KMEANS_PP_CENTERS ); - virtual ~BOWKMeansTrainer(); - - // Returns trained vocabulary (i.e. cluster centers). - CV_WRAP virtual Mat cluster() const CV_OVERRIDE; - CV_WRAP virtual Mat cluster( const Mat& descriptors ) const CV_OVERRIDE; - -protected: - - int clusterCount; - TermCriteria termcrit; - int attempts; - int flags; -}; - -/** @brief Class to compute an image descriptor using the *bag of visual words*. - -Such a computation consists of the following steps: - -1. Compute descriptors for a given image and its keypoints set. -2. Find the nearest visual words from the vocabulary for each keypoint descriptor. -3. Compute the bag-of-words image descriptor as is a normalized histogram of vocabulary words -encountered in the image. The i-th bin of the histogram is a frequency of i-th word of the -vocabulary in the given image. - */ -class CV_EXPORTS_W BOWImgDescriptorExtractor -{ -public: - /** @brief The constructor. - - @param dextractor Descriptor extractor that is used to compute descriptors for an input image and - its keypoints. - @param dmatcher Descriptor matcher that is used to find the nearest word of the trained vocabulary - for each keypoint descriptor of the image. - */ - CV_WRAP BOWImgDescriptorExtractor( const Ptr& dextractor, - const Ptr& dmatcher ); - /** @overload */ - BOWImgDescriptorExtractor( const Ptr& dmatcher ); - virtual ~BOWImgDescriptorExtractor(); - - /** @brief Sets a visual vocabulary. - - @param vocabulary Vocabulary (can be trained using the inheritor of BOWTrainer ). Each row of the - vocabulary is a visual word (cluster center). - */ - CV_WRAP void setVocabulary( const Mat& vocabulary ); - - /** @brief Returns the set vocabulary. - */ - CV_WRAP const Mat& getVocabulary() const; - - /** @brief Computes an image descriptor using the set visual vocabulary. - - @param image Image, for which the descriptor is computed. - @param keypoints Keypoints detected in the input image. - @param imgDescriptor Computed output image descriptor. - @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that - pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) - returned if it is non-zero. - @param descriptors Descriptors of the image keypoints that are returned if they are non-zero. - */ - void compute( InputArray image, std::vector& keypoints, OutputArray imgDescriptor, - std::vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); - /** @overload - @param keypointDescriptors Computed descriptors to match with vocabulary. - @param imgDescriptor Computed output image descriptor. - @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that - pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) - returned if it is non-zero. - */ - void compute( InputArray keypointDescriptors, OutputArray imgDescriptor, - std::vector >* pointIdxsOfClusters=0 ); - // compute() is not constant because DescriptorMatcher::match is not constant - - CV_WRAP_AS(compute) void compute2( const Mat& image, std::vector& keypoints, CV_OUT Mat& imgDescriptor ) - { compute(image,keypoints,imgDescriptor); } - - /** @brief Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0. - */ - CV_WRAP int descriptorSize() const; - - /** @brief Returns an image descriptor type. - */ - CV_WRAP int descriptorType() const; - -protected: - Mat vocabulary; - Ptr dextractor; - Ptr dmatcher; -}; - -//! @} features2d_category - -} /* namespace cv */ - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_FEATURES_2D_HPP +#define OPENCV_FEATURES_2D_HPP + +#include "opencv2/opencv_modules.hpp" +#include "opencv2/core.hpp" + +#ifdef HAVE_OPENCV_FLANN +#include "opencv2/flann/miniflann.hpp" +#endif + +/** + @defgroup features2d 2D Features Framework + @{ + @defgroup features2d_main Feature Detection and Description + @defgroup features2d_match Descriptor Matchers + + Matchers of keypoint descriptors in OpenCV have wrappers with a common interface that enables + you to easily switch between different algorithms solving the same problem. This section is + devoted to matching descriptors that are represented as vectors in a multidimensional space. + All objects that implement vector descriptor matchers inherit the DescriptorMatcher interface. + + @defgroup features2d_draw Drawing Function of Keypoints and Matches + @defgroup features2d_category Object Categorization + + This section describes approaches based on local 2D features and used to categorize objects. + + @defgroup feature2d_hal Hardware Acceleration Layer + @{ + @defgroup features2d_hal_interface Interface + @} + @} + */ + +namespace cv +{ + +//! @addtogroup features2d_main +//! @{ + +// //! writes vector of keypoints to the file storage +// CV_EXPORTS void write(FileStorage& fs, const String& name, const std::vector& keypoints); +// //! reads vector of keypoints from the specified file storage node +// CV_EXPORTS void read(const FileNode& node, CV_OUT std::vector& keypoints); + +/** @brief A class filters a vector of keypoints. + + Because now it is difficult to provide a convenient interface for all usage scenarios of the + keypoints filter class, it has only several needed by now static methods. + */ +class CV_EXPORTS KeyPointsFilter +{ +public: + KeyPointsFilter(){} + + /* + * Remove keypoints within borderPixels of an image edge. + */ + static void runByImageBorder( std::vector& keypoints, Size imageSize, int borderSize ); + /* + * Remove keypoints of sizes out of range. + */ + static void runByKeypointSize( std::vector& keypoints, float minSize, + float maxSize=FLT_MAX ); + /* + * Remove keypoints from some image by mask for pixels of this image. + */ + static void runByPixelsMask( std::vector& keypoints, const Mat& mask ); + /* + * Remove objects from some image and a vector of points by mask for pixels of this image + */ + static void runByPixelsMask2VectorPoint(std::vector &keypoints, std::vector > &removeFrom, const Mat &mask); + /* + * Remove duplicated keypoints. + */ + static void removeDuplicated( std::vector& keypoints ); + /* + * Remove duplicated keypoints and sort the remaining keypoints + */ + static void removeDuplicatedSorted( std::vector& keypoints ); + + /* + * Retain the specified number of the best keypoints (according to the response) + */ + static void retainBest( std::vector& keypoints, int npoints ); +}; + + +/************************************ Base Classes ************************************/ + +/** @brief Abstract base class for 2D image feature detectors and descriptor extractors +*/ +#ifdef __EMSCRIPTEN__ +class CV_EXPORTS_W Feature2D : public Algorithm +#else +class CV_EXPORTS_W Feature2D : public virtual Algorithm +#endif +{ +public: + virtual ~Feature2D(); + + /** @brief Detects keypoints in an image (first variant) or image set (second variant). + + @param image Image. + @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set + of keypoints detected in images[i] . + @param mask Mask specifying where to look for keypoints (optional). It must be a 8-bit integer + matrix with non-zero values in the region of interest. + */ + CV_WRAP virtual void detect( InputArray image, + CV_OUT std::vector& keypoints, + InputArray mask=noArray() ); + + /** @overload + @param images Image set. + @param keypoints The detected keypoints. In the second variant of the method keypoints[i] is a set + of keypoints detected in images[i] . + @param masks Masks for each input image specifying where to look for keypoints (optional). + masks[i] is a mask for images[i]. + */ + CV_WRAP virtual void detect( InputArrayOfArrays images, + CV_OUT std::vector >& keypoints, + InputArrayOfArrays masks=noArray() ); + + /** @brief Computes the descriptors for a set of keypoints detected in an image (first variant) or image set + (second variant). + + @param image Image. + @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be + computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint + with several dominant orientations (for each orientation). + @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are + descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the + descriptor for keypoint j-th keypoint. + */ + CV_WRAP virtual void compute( InputArray image, + CV_OUT CV_IN_OUT std::vector& keypoints, + OutputArray descriptors ); + + /** @overload + + @param images Image set. + @param keypoints Input collection of keypoints. Keypoints for which a descriptor cannot be + computed are removed. Sometimes new keypoints can be added, for example: SIFT duplicates keypoint + with several dominant orientations (for each orientation). + @param descriptors Computed descriptors. In the second variant of the method descriptors[i] are + descriptors computed for a keypoints[i]. Row j is the keypoints (or keypoints[i]) is the + descriptor for keypoint j-th keypoint. + */ + CV_WRAP virtual void compute( InputArrayOfArrays images, + CV_OUT CV_IN_OUT std::vector >& keypoints, + OutputArrayOfArrays descriptors ); + + /** Detects keypoints and computes the descriptors */ + CV_WRAP virtual void detectAndCompute( InputArray image, InputArray mask, + CV_OUT std::vector& keypoints, + OutputArray descriptors, + bool useProvidedKeypoints=false ); + + CV_WRAP virtual int descriptorSize() const; + CV_WRAP virtual int descriptorType() const; + CV_WRAP virtual int defaultNorm() const; + + CV_WRAP void write( const String& fileName ) const; + + CV_WRAP void read( const String& fileName ); + + virtual void write( FileStorage&) const CV_OVERRIDE; + + // see corresponding cv::Algorithm method + CV_WRAP virtual void read( const FileNode&) CV_OVERRIDE; + + //! Return true if detector object is empty + CV_WRAP virtual bool empty() const CV_OVERRIDE; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + // see corresponding cv::Algorithm method + CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } +#if CV_VERSION_MAJOR < 5 + inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } +#endif +}; + +/** Feature detectors in OpenCV have wrappers with a common interface that enables you to easily switch +between different algorithms solving the same problem. All objects that implement keypoint detectors +inherit the FeatureDetector interface. */ +typedef Feature2D FeatureDetector; + +/** Extractors of keypoint descriptors in OpenCV have wrappers with a common interface that enables you +to easily switch between different algorithms solving the same problem. This section is devoted to +computing descriptors represented as vectors in a multidimensional space. All objects that implement +the vector descriptor extractors inherit the DescriptorExtractor interface. + */ +typedef Feature2D DescriptorExtractor; + + +/** @brief Class for implementing the wrapper which makes detectors and extractors to be affine invariant, +described as ASIFT in @cite YM11 . +*/ +class CV_EXPORTS_W AffineFeature : public Feature2D +{ +public: + /** + @param backend The detector/extractor you want to use as backend. + @param maxTilt The highest power index of tilt factor. 5 is used in the paper as tilt sampling range n. + @param minTilt The lowest power index of tilt factor. 0 is used in the paper. + @param tiltStep Tilt sampling step \f$\delta_t\f$ in Algorithm 1 in the paper. + @param rotateStepBase Rotation sampling step factor b in Algorithm 1 in the paper. + */ + CV_WRAP static Ptr create(const Ptr& backend, + int maxTilt = 5, int minTilt = 0, float tiltStep = 1.4142135623730951f, float rotateStepBase = 72); + + CV_WRAP virtual void setViewParams(const std::vector& tilts, const std::vector& rolls) = 0; + CV_WRAP virtual void getViewParams(std::vector& tilts, std::vector& rolls) const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +typedef AffineFeature AffineFeatureDetector; +typedef AffineFeature AffineDescriptorExtractor; + + +/** @brief Class for extracting keypoints and computing descriptors using the Scale Invariant Feature Transform +(SIFT) algorithm by D. Lowe @cite Lowe04 . +*/ +class CV_EXPORTS_W SIFT : public Feature2D +{ +public: + /** + @param nfeatures The number of best features to retain. The features are ranked by their scores + (measured in SIFT algorithm as the local contrast) + + @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The + number of octaves is computed automatically from the image resolution. + + @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform + (low-contrast) regions. The larger the threshold, the less features are produced by the detector. + + @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When + nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set + this argument to 0.09. + + @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning + is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are + filtered out (more features are retained). + + @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image + is captured with a weak camera with soft lenses, you might want to reduce the number. + + @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps + index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option + is disabled by default. + */ + CV_WRAP static Ptr create(int nfeatures = 0, int nOctaveLayers = 3, + double contrastThreshold = 0.04, double edgeThreshold = 10, + double sigma = 1.6, bool enable_precise_upscale = false); + + /** @brief Create SIFT with specified descriptorType. + @param nfeatures The number of best features to retain. The features are ranked by their scores + (measured in SIFT algorithm as the local contrast) + + @param nOctaveLayers The number of layers in each octave. 3 is the value used in D. Lowe paper. The + number of octaves is computed automatically from the image resolution. + + @param contrastThreshold The contrast threshold used to filter out weak features in semi-uniform + (low-contrast) regions. The larger the threshold, the less features are produced by the detector. + + @note The contrast threshold will be divided by nOctaveLayers when the filtering is applied. When + nOctaveLayers is set to default and if you want to use the value used in D. Lowe paper, 0.03, set + this argument to 0.09. + + @param edgeThreshold The threshold used to filter out edge-like features. Note that the its meaning + is different from the contrastThreshold, i.e. the larger the edgeThreshold, the less features are + filtered out (more features are retained). + + @param sigma The sigma of the Gaussian applied to the input image at the octave \#0. If your image + is captured with a weak camera with soft lenses, you might want to reduce the number. + + @param descriptorType The type of descriptors. Only CV_32F and CV_8U are supported. + + @param enable_precise_upscale Whether to enable precise upscaling in the scale pyramid, which maps + index \f$\texttt{x}\f$ to \f$\texttt{2x}\f$. This prevents localization bias. The option + is disabled by default. + */ + CV_WRAP static Ptr create(int nfeatures, int nOctaveLayers, + double contrastThreshold, double edgeThreshold, + double sigma, int descriptorType, bool enable_precise_upscale = false); + + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + CV_WRAP virtual void setNFeatures(int maxFeatures) = 0; + CV_WRAP virtual int getNFeatures() const = 0; + + CV_WRAP virtual void setNOctaveLayers(int nOctaveLayers) = 0; + CV_WRAP virtual int getNOctaveLayers() const = 0; + + CV_WRAP virtual void setContrastThreshold(double contrastThreshold) = 0; + CV_WRAP virtual double getContrastThreshold() const = 0; + + CV_WRAP virtual void setEdgeThreshold(double edgeThreshold) = 0; + CV_WRAP virtual double getEdgeThreshold() const = 0; + + CV_WRAP virtual void setSigma(double sigma) = 0; + CV_WRAP virtual double getSigma() const = 0; +}; + +typedef SIFT SiftFeatureDetector; +typedef SIFT SiftDescriptorExtractor; + + +/** @brief Class implementing the BRISK keypoint detector and descriptor extractor, described in @cite LCS11 . + */ +class CV_EXPORTS_W BRISK : public Feature2D +{ +public: + /** @brief The BRISK constructor + + @param thresh AGAST detection threshold score. + @param octaves detection octaves. Use 0 to do single scale. + @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a + keypoint. + */ + CV_WRAP static Ptr create(int thresh=30, int octaves=3, float patternScale=1.0f); + + /** @brief The BRISK constructor for a custom pattern + + @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for + keypoint scale 1). + @param numberList defines the number of sampling points on the sampling circle. Must be the same + size as radiusList.. + @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint + scale 1). + @param dMin threshold for the long pairings used for orientation determination (in pixels for + keypoint scale 1). + @param indexChange index remapping of the bits. */ + CV_WRAP static Ptr create(const std::vector &radiusList, const std::vector &numberList, + float dMax=5.85f, float dMin=8.2f, const std::vector& indexChange=std::vector()); + + /** @brief The BRISK constructor for a custom pattern, detection threshold and octaves + + @param thresh AGAST detection threshold score. + @param octaves detection octaves. Use 0 to do single scale. + @param radiusList defines the radii (in pixels) where the samples around a keypoint are taken (for + keypoint scale 1). + @param numberList defines the number of sampling points on the sampling circle. Must be the same + size as radiusList.. + @param dMax threshold for the short pairings used for descriptor formation (in pixels for keypoint + scale 1). + @param dMin threshold for the long pairings used for orientation determination (in pixels for + keypoint scale 1). + @param indexChange index remapping of the bits. */ + CV_WRAP static Ptr create(int thresh, int octaves, const std::vector &radiusList, + const std::vector &numberList, float dMax=5.85f, float dMin=8.2f, + const std::vector& indexChange=std::vector()); + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + /** @brief Set detection threshold. + @param threshold AGAST detection threshold score. + */ + CV_WRAP virtual void setThreshold(int threshold) = 0; + CV_WRAP virtual int getThreshold() const = 0; + + /** @brief Set detection octaves. + @param octaves detection octaves. Use 0 to do single scale. + */ + CV_WRAP virtual void setOctaves(int octaves) = 0; + CV_WRAP virtual int getOctaves() const = 0; + /** @brief Set detection patternScale. + @param patternScale apply this scale to the pattern used for sampling the neighbourhood of a + keypoint. + */ + CV_WRAP virtual void setPatternScale(float patternScale) = 0; + CV_WRAP virtual float getPatternScale() const = 0; +}; + +/** @brief Class implementing the ORB (*oriented BRIEF*) keypoint detector and descriptor extractor + +described in @cite RRKB11 . The algorithm uses FAST in pyramids to detect stable keypoints, selects +the strongest features using FAST or Harris response, finds their orientation using first-order +moments and computes the descriptors using BRIEF (where the coordinates of random point pairs (or +k-tuples) are rotated according to the measured orientation). + */ +class CV_EXPORTS_W ORB : public Feature2D +{ +public: + enum ScoreType { HARRIS_SCORE=0, FAST_SCORE=1 }; + static const int kBytes = 32; + + /** @brief The ORB constructor + + @param nfeatures The maximum number of features to retain. + @param scaleFactor Pyramid decimation ratio, greater than 1. scaleFactor==2 means the classical + pyramid, where each next level has 4x less pixels than the previous, but such a big scale factor + will degrade feature matching scores dramatically. On the other hand, too close to 1 scale factor + will mean that to cover certain scale range you will need more pyramid levels and so the speed + will suffer. + @param nlevels The number of pyramid levels. The smallest level will have linear size equal to + input_image_linear_size/pow(scaleFactor, nlevels - firstLevel). + @param edgeThreshold This is size of the border where the features are not detected. It should + roughly match the patchSize parameter. + @param firstLevel The level of pyramid to put source image to. Previous layers are filled + with upscaled source image. + @param WTA_K The number of points that produce each element of the oriented BRIEF descriptor. The + default value 2 means the BRIEF where we take a random point pair and compare their brightnesses, + so we get 0/1 response. Other possible values are 3 and 4. For example, 3 means that we take 3 + random points (of course, those point coordinates are random, but they are generated from the + pre-defined seed, so each element of BRIEF descriptor is computed deterministically from the pixel + rectangle), find point of maximum brightness and output index of the winner (0, 1 or 2). Such + output will occupy 2 bits, and therefore it will need a special variant of Hamming distance, + denoted as NORM_HAMMING2 (2 bits per bin). When WTA_K=4, we take 4 random points to compute each + bin (that will also occupy 2 bits with possible values 0, 1, 2 or 3). + @param scoreType The default HARRIS_SCORE means that Harris algorithm is used to rank features + (the score is written to KeyPoint::score and is used to retain best nfeatures features); + FAST_SCORE is alternative value of the parameter that produces slightly less stable keypoints, + but it is a little faster to compute. + @param patchSize size of the patch used by the oriented BRIEF descriptor. Of course, on smaller + pyramid layers the perceived image area covered by a feature will be larger. + @param fastThreshold the fast threshold + */ + CV_WRAP static Ptr create(int nfeatures=500, float scaleFactor=1.2f, int nlevels=8, int edgeThreshold=31, + int firstLevel=0, int WTA_K=2, ORB::ScoreType scoreType=ORB::HARRIS_SCORE, int patchSize=31, int fastThreshold=20); + + CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; + CV_WRAP virtual int getMaxFeatures() const = 0; + + CV_WRAP virtual void setScaleFactor(double scaleFactor) = 0; + CV_WRAP virtual double getScaleFactor() const = 0; + + CV_WRAP virtual void setNLevels(int nlevels) = 0; + CV_WRAP virtual int getNLevels() const = 0; + + CV_WRAP virtual void setEdgeThreshold(int edgeThreshold) = 0; + CV_WRAP virtual int getEdgeThreshold() const = 0; + + CV_WRAP virtual void setFirstLevel(int firstLevel) = 0; + CV_WRAP virtual int getFirstLevel() const = 0; + + CV_WRAP virtual void setWTA_K(int wta_k) = 0; + CV_WRAP virtual int getWTA_K() const = 0; + + CV_WRAP virtual void setScoreType(ORB::ScoreType scoreType) = 0; + CV_WRAP virtual ORB::ScoreType getScoreType() const = 0; + + CV_WRAP virtual void setPatchSize(int patchSize) = 0; + CV_WRAP virtual int getPatchSize() const = 0; + + CV_WRAP virtual void setFastThreshold(int fastThreshold) = 0; + CV_WRAP virtual int getFastThreshold() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @brief Maximally stable extremal region extractor + +The class encapsulates all the parameters of the %MSER extraction algorithm (see [wiki +article](http://en.wikipedia.org/wiki/Maximally_stable_extremal_regions)). + +- there are two different implementation of %MSER: one for grey image, one for color image + +- the grey image algorithm is taken from: @cite nister2008linear ; the paper claims to be faster +than union-find method; it actually get 1.5~2m/s on my centrino L7200 1.2GHz laptop. + +- the color image algorithm is taken from: @cite forssen2007maximally ; it should be much slower +than grey image method ( 3~4 times ) + +- (Python) A complete example showing the use of the %MSER detector can be found at samples/python/mser.py +*/ +class CV_EXPORTS_W MSER : public Feature2D +{ +public: + /** @brief Full constructor for %MSER detector + + @param delta it compares \f$(size_{i}-size_{i-delta})/size_{i-delta}\f$ + @param min_area prune the area which smaller than minArea + @param max_area prune the area which bigger than maxArea + @param max_variation prune the area have similar size to its children + @param min_diversity for color image, trace back to cut off mser with diversity less than min_diversity + @param max_evolution for color image, the evolution steps + @param area_threshold for color image, the area threshold to cause re-initialize + @param min_margin for color image, ignore too small margin + @param edge_blur_size for color image, the aperture size for edge blur + */ + CV_WRAP static Ptr create( int delta=5, int min_area=60, int max_area=14400, + double max_variation=0.25, double min_diversity=.2, + int max_evolution=200, double area_threshold=1.01, + double min_margin=0.003, int edge_blur_size=5 ); + + /** @brief Detect %MSER regions + + @param image input image (8UC1, 8UC3 or 8UC4, must be greater or equal than 3x3) + @param msers resulting list of point sets + @param bboxes resulting bounding boxes + */ + CV_WRAP virtual void detectRegions( InputArray image, + CV_OUT std::vector >& msers, + CV_OUT std::vector& bboxes ) = 0; + + CV_WRAP virtual void setDelta(int delta) = 0; + CV_WRAP virtual int getDelta() const = 0; + + CV_WRAP virtual void setMinArea(int minArea) = 0; + CV_WRAP virtual int getMinArea() const = 0; + + CV_WRAP virtual void setMaxArea(int maxArea) = 0; + CV_WRAP virtual int getMaxArea() const = 0; + + CV_WRAP virtual void setMaxVariation(double maxVariation) = 0; + CV_WRAP virtual double getMaxVariation() const = 0; + + CV_WRAP virtual void setMinDiversity(double minDiversity) = 0; + CV_WRAP virtual double getMinDiversity() const = 0; + + CV_WRAP virtual void setMaxEvolution(int maxEvolution) = 0; + CV_WRAP virtual int getMaxEvolution() const = 0; + + CV_WRAP virtual void setAreaThreshold(double areaThreshold) = 0; + CV_WRAP virtual double getAreaThreshold() const = 0; + + CV_WRAP virtual void setMinMargin(double min_margin) = 0; + CV_WRAP virtual double getMinMargin() const = 0; + + CV_WRAP virtual void setEdgeBlurSize(int edge_blur_size) = 0; + CV_WRAP virtual int getEdgeBlurSize() const = 0; + + CV_WRAP virtual void setPass2Only(bool f) = 0; + CV_WRAP virtual bool getPass2Only() const = 0; + + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + + +/** @brief Wrapping class for feature detection using the FAST method. : + */ +class CV_EXPORTS_W FastFeatureDetector : public Feature2D +{ +public: + enum DetectorType + { + TYPE_5_8 = 0, TYPE_7_12 = 1, TYPE_9_16 = 2 + }; + enum + { + THRESHOLD = 10000, NONMAX_SUPPRESSION=10001, FAST_N=10002 + }; + + + CV_WRAP static Ptr create( int threshold=10, + bool nonmaxSuppression=true, + FastFeatureDetector::DetectorType type=FastFeatureDetector::TYPE_9_16 ); + + CV_WRAP virtual void setThreshold(int threshold) = 0; + CV_WRAP virtual int getThreshold() const = 0; + + CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; + CV_WRAP virtual bool getNonmaxSuppression() const = 0; + + CV_WRAP virtual void setType(FastFeatureDetector::DetectorType type) = 0; + CV_WRAP virtual FastFeatureDetector::DetectorType getType() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @overload */ +CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression=true ); + +/** @brief Detects corners using the FAST algorithm + +@param image grayscale image where keypoints (corners) are detected. +@param keypoints keypoints detected on the image. +@param threshold threshold on difference between intensity of the central pixel and pixels of a +circle around this pixel. +@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners +(keypoints). +@param type one of the three neighborhoods as defined in the paper: +FastFeatureDetector::TYPE_9_16, FastFeatureDetector::TYPE_7_12, +FastFeatureDetector::TYPE_5_8 + +Detects corners using the FAST algorithm by @cite Rosten06 . + +@note In Python API, types are given as cv.FAST_FEATURE_DETECTOR_TYPE_5_8, +cv.FAST_FEATURE_DETECTOR_TYPE_7_12 and cv.FAST_FEATURE_DETECTOR_TYPE_9_16. For corner +detection, use cv.FAST.detect() method. + */ +CV_EXPORTS void FAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression, FastFeatureDetector::DetectorType type ); + + +/** @brief Wrapping class for feature detection using the AGAST method. : + */ +class CV_EXPORTS_W AgastFeatureDetector : public Feature2D +{ +public: + enum DetectorType + { + AGAST_5_8 = 0, AGAST_7_12d = 1, AGAST_7_12s = 2, OAST_9_16 = 3, + }; + + enum + { + THRESHOLD = 10000, NONMAX_SUPPRESSION = 10001, + }; + + CV_WRAP static Ptr create( int threshold=10, + bool nonmaxSuppression=true, + AgastFeatureDetector::DetectorType type = AgastFeatureDetector::OAST_9_16); + + CV_WRAP virtual void setThreshold(int threshold) = 0; + CV_WRAP virtual int getThreshold() const = 0; + + CV_WRAP virtual void setNonmaxSuppression(bool f) = 0; + CV_WRAP virtual bool getNonmaxSuppression() const = 0; + + CV_WRAP virtual void setType(AgastFeatureDetector::DetectorType type) = 0; + CV_WRAP virtual AgastFeatureDetector::DetectorType getType() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @overload */ +CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression=true ); + +/** @brief Detects corners using the AGAST algorithm + +@param image grayscale image where keypoints (corners) are detected. +@param keypoints keypoints detected on the image. +@param threshold threshold on difference between intensity of the central pixel and pixels of a +circle around this pixel. +@param nonmaxSuppression if true, non-maximum suppression is applied to detected corners +(keypoints). +@param type one of the four neighborhoods as defined in the paper: +AgastFeatureDetector::AGAST_5_8, AgastFeatureDetector::AGAST_7_12d, +AgastFeatureDetector::AGAST_7_12s, AgastFeatureDetector::OAST_9_16 + +For non-Intel platforms, there is a tree optimised variant of AGAST with same numerical results. +The 32-bit binary tree tables were generated automatically from original code using perl script. +The perl script and examples of tree generation are placed in features2d/doc folder. +Detects corners using the AGAST algorithm by @cite mair2010_agast . + + */ +CV_EXPORTS void AGAST( InputArray image, CV_OUT std::vector& keypoints, + int threshold, bool nonmaxSuppression, AgastFeatureDetector::DetectorType type ); + +/** @brief Wrapping class for feature detection using the goodFeaturesToTrack function. : + */ +class CV_EXPORTS_W GFTTDetector : public Feature2D +{ +public: + CV_WRAP static Ptr create( int maxCorners=1000, double qualityLevel=0.01, double minDistance=1, + int blockSize=3, bool useHarrisDetector=false, double k=0.04 ); + CV_WRAP static Ptr create( int maxCorners, double qualityLevel, double minDistance, + int blockSize, int gradiantSize, bool useHarrisDetector=false, double k=0.04 ); + CV_WRAP virtual void setMaxFeatures(int maxFeatures) = 0; + CV_WRAP virtual int getMaxFeatures() const = 0; + + CV_WRAP virtual void setQualityLevel(double qlevel) = 0; + CV_WRAP virtual double getQualityLevel() const = 0; + + CV_WRAP virtual void setMinDistance(double minDistance) = 0; + CV_WRAP virtual double getMinDistance() const = 0; + + CV_WRAP virtual void setBlockSize(int blockSize) = 0; + CV_WRAP virtual int getBlockSize() const = 0; + + CV_WRAP virtual void setGradientSize(int gradientSize_) = 0; + CV_WRAP virtual int getGradientSize() = 0; + + CV_WRAP virtual void setHarrisDetector(bool val) = 0; + CV_WRAP virtual bool getHarrisDetector() const = 0; + + CV_WRAP virtual void setK(double k) = 0; + CV_WRAP virtual double getK() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @brief Class for extracting blobs from an image. : + +The class implements a simple algorithm for extracting blobs from an image: + +1. Convert the source image to binary images by applying thresholding with several thresholds from + minThreshold (inclusive) to maxThreshold (exclusive) with distance thresholdStep between + neighboring thresholds. +2. Extract connected components from every binary image by findContours and calculate their + centers. +3. Group centers from several binary images by their coordinates. Close centers form one group that + corresponds to one blob, which is controlled by the minDistBetweenBlobs parameter. +4. From the groups, estimate final centers of blobs and their radiuses and return as locations and + sizes of keypoints. + +This class performs several filtrations of returned blobs. You should set filterBy\* to true/false +to turn on/off corresponding filtration. Available filtrations: + +- **By color**. This filter compares the intensity of a binary image at the center of a blob to +blobColor. If they differ, the blob is filtered out. Use blobColor = 0 to extract dark blobs +and blobColor = 255 to extract light blobs. +- **By area**. Extracted blobs have an area between minArea (inclusive) and maxArea (exclusive). +- **By circularity**. Extracted blobs have circularity +(\f$\frac{4*\pi*Area}{perimeter * perimeter}\f$) between minCircularity (inclusive) and +maxCircularity (exclusive). +- **By ratio of the minimum inertia to maximum inertia**. Extracted blobs have this ratio +between minInertiaRatio (inclusive) and maxInertiaRatio (exclusive). +- **By convexity**. Extracted blobs have convexity (area / area of blob convex hull) between +minConvexity (inclusive) and maxConvexity (exclusive). + +Default values of parameters are tuned to extract dark circular blobs. + */ +class CV_EXPORTS_W SimpleBlobDetector : public Feature2D +{ +public: + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW float thresholdStep; + CV_PROP_RW float minThreshold; + CV_PROP_RW float maxThreshold; + CV_PROP_RW size_t minRepeatability; + CV_PROP_RW float minDistBetweenBlobs; + + CV_PROP_RW bool filterByColor; + CV_PROP_RW uchar blobColor; + + CV_PROP_RW bool filterByArea; + CV_PROP_RW float minArea, maxArea; + + CV_PROP_RW bool filterByCircularity; + CV_PROP_RW float minCircularity, maxCircularity; + + CV_PROP_RW bool filterByInertia; + CV_PROP_RW float minInertiaRatio, maxInertiaRatio; + + CV_PROP_RW bool filterByConvexity; + CV_PROP_RW float minConvexity, maxConvexity; + + CV_PROP_RW bool collectContours; + + void read( const FileNode& fn ); + void write( FileStorage& fs ) const; + }; + + CV_WRAP static Ptr + create(const SimpleBlobDetector::Params ¶meters = SimpleBlobDetector::Params()); + + CV_WRAP virtual void setParams(const SimpleBlobDetector::Params& params ) = 0; + CV_WRAP virtual SimpleBlobDetector::Params getParams() const = 0; + + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + CV_WRAP virtual const std::vector >& getBlobContours() const; +}; + + +/** @brief Class implementing the KAZE keypoint detector and descriptor extractor, described in @cite ABD12 . + +@note AKAZE descriptor can only be used with KAZE or AKAZE keypoints .. [ABD12] KAZE Features. Pablo +F. Alcantarilla, Adrien Bartoli and Andrew J. Davison. In European Conference on Computer Vision +(ECCV), Fiorenze, Italy, October 2012. +*/ +class CV_EXPORTS_W KAZE : public Feature2D +{ +public: + enum DiffusivityType + { + DIFF_PM_G1 = 0, + DIFF_PM_G2 = 1, + DIFF_WEICKERT = 2, + DIFF_CHARBONNIER = 3 + }; + + /** @brief The KAZE constructor + + @param extended Set to enable extraction of extended (128-byte) descriptor. + @param upright Set to enable use of upright descriptors (non rotation-invariant). + @param threshold Detector response threshold to accept point + @param nOctaves Maximum octave evolution of the image + @param nOctaveLayers Default number of sublevels per scale level + @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or + DIFF_CHARBONNIER + */ + CV_WRAP static Ptr create(bool extended=false, bool upright=false, + float threshold = 0.001f, + int nOctaves = 4, int nOctaveLayers = 4, + KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2); + + CV_WRAP virtual void setExtended(bool extended) = 0; + CV_WRAP virtual bool getExtended() const = 0; + + CV_WRAP virtual void setUpright(bool upright) = 0; + CV_WRAP virtual bool getUpright() const = 0; + + CV_WRAP virtual void setThreshold(double threshold) = 0; + CV_WRAP virtual double getThreshold() const = 0; + + CV_WRAP virtual void setNOctaves(int octaves) = 0; + CV_WRAP virtual int getNOctaves() const = 0; + + CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; + CV_WRAP virtual int getNOctaveLayers() const = 0; + + CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; + CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; +}; + +/** @brief Class implementing the AKAZE keypoint detector and descriptor extractor, described in @cite ANB13. + +@details AKAZE descriptors can only be used with KAZE or AKAZE keypoints. This class is thread-safe. + +@note When you need descriptors use Feature2D::detectAndCompute, which +provides better performance. When using Feature2D::detect followed by +Feature2D::compute scale space pyramid is computed twice. + +@note AKAZE implements T-API. When image is passed as UMat some parts of the algorithm +will use OpenCL. + +@note [ANB13] Fast Explicit Diffusion for Accelerated Features in Nonlinear +Scale Spaces. Pablo F. Alcantarilla, Jesús Nuevo and Adrien Bartoli. In +British Machine Vision Conference (BMVC), Bristol, UK, September 2013. + +*/ +class CV_EXPORTS_W AKAZE : public Feature2D +{ +public: + // AKAZE descriptor type + enum DescriptorType + { + DESCRIPTOR_KAZE_UPRIGHT = 2, ///< Upright descriptors, not invariant to rotation + DESCRIPTOR_KAZE = 3, + DESCRIPTOR_MLDB_UPRIGHT = 4, ///< Upright descriptors, not invariant to rotation + DESCRIPTOR_MLDB = 5 + }; + + /** @brief The AKAZE constructor + + @param descriptor_type Type of the extracted descriptor: DESCRIPTOR_KAZE, + DESCRIPTOR_KAZE_UPRIGHT, DESCRIPTOR_MLDB or DESCRIPTOR_MLDB_UPRIGHT. + @param descriptor_size Size of the descriptor in bits. 0 -\> Full size + @param descriptor_channels Number of channels in the descriptor (1, 2, 3) + @param threshold Detector response threshold to accept point + @param nOctaves Maximum octave evolution of the image + @param nOctaveLayers Default number of sublevels per scale level + @param diffusivity Diffusivity type. DIFF_PM_G1, DIFF_PM_G2, DIFF_WEICKERT or + DIFF_CHARBONNIER + @param max_points Maximum amount of returned points. In case if image contains + more features, then the features with highest response are returned. + Negative value means no limitation. + */ + CV_WRAP static Ptr create(AKAZE::DescriptorType descriptor_type = AKAZE::DESCRIPTOR_MLDB, + int descriptor_size = 0, int descriptor_channels = 3, + float threshold = 0.001f, int nOctaves = 4, + int nOctaveLayers = 4, KAZE::DiffusivityType diffusivity = KAZE::DIFF_PM_G2, + int max_points = -1); + + CV_WRAP virtual void setDescriptorType(AKAZE::DescriptorType dtype) = 0; + CV_WRAP virtual AKAZE::DescriptorType getDescriptorType() const = 0; + + CV_WRAP virtual void setDescriptorSize(int dsize) = 0; + CV_WRAP virtual int getDescriptorSize() const = 0; + + CV_WRAP virtual void setDescriptorChannels(int dch) = 0; + CV_WRAP virtual int getDescriptorChannels() const = 0; + + CV_WRAP virtual void setThreshold(double threshold) = 0; + CV_WRAP virtual double getThreshold() const = 0; + + CV_WRAP virtual void setNOctaves(int octaves) = 0; + CV_WRAP virtual int getNOctaves() const = 0; + + CV_WRAP virtual void setNOctaveLayers(int octaveLayers) = 0; + CV_WRAP virtual int getNOctaveLayers() const = 0; + + CV_WRAP virtual void setDiffusivity(KAZE::DiffusivityType diff) = 0; + CV_WRAP virtual KAZE::DiffusivityType getDiffusivity() const = 0; + CV_WRAP virtual String getDefaultName() const CV_OVERRIDE; + + CV_WRAP virtual void setMaxPoints(int max_points) = 0; + CV_WRAP virtual int getMaxPoints() const = 0; +}; + + +/****************************************************************************************\ +* Distance * +\****************************************************************************************/ + +template +struct CV_EXPORTS Accumulator +{ + typedef T Type; +}; + +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; +template<> struct Accumulator { typedef float Type; }; + +/* + * Squared Euclidean distance functor + */ +template +struct CV_EXPORTS SL2 +{ + static const NormTypes normType = NORM_L2SQR; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return normL2Sqr(a, b, size); + } +}; + +/* + * Euclidean distance functor + */ +template +struct L2 +{ + static const NormTypes normType = NORM_L2; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return (ResultType)std::sqrt((double)normL2Sqr(a, b, size)); + } +}; + +/* + * Manhattan distance (city block distance) functor + */ +template +struct L1 +{ + static const NormTypes normType = NORM_L1; + typedef T ValueType; + typedef typename Accumulator::Type ResultType; + + ResultType operator()( const T* a, const T* b, int size ) const + { + return normL1(a, b, size); + } +}; + +//! @} features2d_main + +/****************************************************************************************\ +* DescriptorMatcher * +\****************************************************************************************/ + +//! @addtogroup features2d_match +//! @{ + +/** @brief Abstract base class for matching keypoint descriptors. + +It has two groups of match methods: for matching descriptors of an image with another image or with +an image set. + */ +class CV_EXPORTS_W DescriptorMatcher : public Algorithm +{ +public: + enum MatcherType + { + FLANNBASED = 1, + BRUTEFORCE = 2, + BRUTEFORCE_L1 = 3, + BRUTEFORCE_HAMMING = 4, + BRUTEFORCE_HAMMINGLUT = 5, + BRUTEFORCE_SL2 = 6 + }; + + virtual ~DescriptorMatcher(); + + /** @brief Adds descriptors to train a CPU(trainDescCollectionis) or GPU(utrainDescCollectionis) descriptor + collection. + + If the collection is not empty, the new descriptors are added to existing train descriptors. + + @param descriptors Descriptors to add. Each descriptors[i] is a set of descriptors from the same + train image. + */ + CV_WRAP virtual void add( InputArrayOfArrays descriptors ); + + /** @brief Returns a constant link to the train descriptor collection trainDescCollection . + */ + CV_WRAP const std::vector& getTrainDescriptors() const; + + /** @brief Clears the train descriptor collections. + */ + CV_WRAP virtual void clear() CV_OVERRIDE; + + /** @brief Returns true if there are no train descriptors in the both collections. + */ + CV_WRAP virtual bool empty() const CV_OVERRIDE; + + /** @brief Returns true if the descriptor matcher supports masking permissible matches. + */ + CV_WRAP virtual bool isMaskSupported() const = 0; + + /** @brief Trains a descriptor matcher + + Trains a descriptor matcher (for example, the flann index). In all methods to match, the method + train() is run every time before matching. Some descriptor matchers (for example, BruteForceMatcher) + have an empty implementation of this method. Other matchers really train their inner structures (for + example, FlannBasedMatcher trains flann::Index ). + */ + CV_WRAP virtual void train(); + + /** @brief Finds the best match for each descriptor from a query set. + + @param queryDescriptors Query set of descriptors. + @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors + collection stored in the class object. + @param matches Matches. If a query descriptor is masked out in mask , no match is added for this + descriptor. So, matches size may be smaller than the query descriptors count. + @param mask Mask specifying permissible matches between an input query and train matrices of + descriptors. + + In the first variant of this method, the train descriptors are passed as an input argument. In the + second variant of the method, train descriptors collection that was set by DescriptorMatcher::add is + used. Optional mask (or masks) can be passed to specify which query and training descriptors can be + matched. Namely, queryDescriptors[i] can be matched with trainDescriptors[j] only if + mask.at\(i,j) is non-zero. + */ + CV_WRAP void match( InputArray queryDescriptors, InputArray trainDescriptors, + CV_OUT std::vector& matches, InputArray mask=noArray() ) const; + + /** @brief Finds the k best matches for each descriptor from a query set. + + @param queryDescriptors Query set of descriptors. + @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors + collection stored in the class object. + @param mask Mask specifying permissible matches between an input query and train matrices of + descriptors. + @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. + @param k Count of best matches found per each query descriptor or less if a query descriptor has + less than k possible matches in total. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + + These extended variants of DescriptorMatcher::match methods find several best matches for each query + descriptor. The matches are returned in the distance increasing order. See DescriptorMatcher::match + for the details about query and train descriptors. + */ + CV_WRAP void knnMatch( InputArray queryDescriptors, InputArray trainDescriptors, + CV_OUT std::vector >& matches, int k, + InputArray mask=noArray(), bool compactResult=false ) const; + + /** @brief For each query descriptor, finds the training descriptors not farther than the specified distance. + + @param queryDescriptors Query set of descriptors. + @param trainDescriptors Train set of descriptors. This set is not added to the train descriptors + collection stored in the class object. + @param matches Found matches. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + @param maxDistance Threshold for the distance between matched descriptors. Distance means here + metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured + in Pixels)! + @param mask Mask specifying permissible matches between an input query and train matrices of + descriptors. + + For each query descriptor, the methods find such training descriptors that the distance between the + query descriptor and the training descriptor is equal or smaller than maxDistance. Found matches are + returned in the distance increasing order. + */ + CV_WRAP void radiusMatch( InputArray queryDescriptors, InputArray trainDescriptors, + CV_OUT std::vector >& matches, float maxDistance, + InputArray mask=noArray(), bool compactResult=false ) const; + + /** @overload + @param queryDescriptors Query set of descriptors. + @param matches Matches. If a query descriptor is masked out in mask , no match is added for this + descriptor. So, matches size may be smaller than the query descriptors count. + @param masks Set of masks. Each masks[i] specifies permissible matches between the input query + descriptors and stored train descriptors from the i-th image trainDescCollection[i]. + */ + CV_WRAP void match( InputArray queryDescriptors, CV_OUT std::vector& matches, + InputArrayOfArrays masks=noArray() ); + /** @overload + @param queryDescriptors Query set of descriptors. + @param matches Matches. Each matches[i] is k or less matches for the same query descriptor. + @param k Count of best matches found per each query descriptor or less if a query descriptor has + less than k possible matches in total. + @param masks Set of masks. Each masks[i] specifies permissible matches between the input query + descriptors and stored train descriptors from the i-th image trainDescCollection[i]. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + */ + CV_WRAP void knnMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ); + /** @overload + @param queryDescriptors Query set of descriptors. + @param matches Found matches. + @param maxDistance Threshold for the distance between matched descriptors. Distance means here + metric distance (e.g. Hamming distance), not the distance between coordinates (which is measured + in Pixels)! + @param masks Set of masks. Each masks[i] specifies permissible matches between the input query + descriptors and stored train descriptors from the i-th image trainDescCollection[i]. + @param compactResult Parameter used when the mask (or masks) is not empty. If compactResult is + false, the matches vector has the same size as queryDescriptors rows. If compactResult is true, + the matches vector does not contain matches for fully masked-out query descriptors. + */ + CV_WRAP void radiusMatch( InputArray queryDescriptors, CV_OUT std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ); + + + CV_WRAP void write( const String& fileName ) const + { + FileStorage fs(fileName, FileStorage::WRITE); + write(fs); + } + + CV_WRAP void read( const String& fileName ) + { + FileStorage fs(fileName, FileStorage::READ); + read(fs.root()); + } + // Reads matcher object from a file node + // see corresponding cv::Algorithm method + CV_WRAP virtual void read( const FileNode& ) CV_OVERRIDE; + // Writes matcher object to a file storage + virtual void write( FileStorage& ) const CV_OVERRIDE; + + /** @brief Clones the matcher. + + @param emptyTrainData If emptyTrainData is false, the method creates a deep copy of the object, + that is, copies both parameters and train data. If emptyTrainData is true, the method creates an + object copy with the current parameters but with empty train data. + */ + CV_WRAP CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const = 0; + + /** @brief Creates a descriptor matcher of a given type with the default parameters (using default + constructor). + + @param descriptorMatcherType Descriptor matcher type. Now the following matcher types are + supported: + - `BruteForce` (it uses L2 ) + - `BruteForce-L1` + - `BruteForce-Hamming` + - `BruteForce-Hamming(2)` + - `FlannBased` + */ + CV_WRAP static Ptr create( const String& descriptorMatcherType ); + + CV_WRAP static Ptr create( const DescriptorMatcher::MatcherType& matcherType ); + + + // see corresponding cv::Algorithm method + CV_WRAP inline void write(FileStorage& fs, const String& name) const { Algorithm::write(fs, name); } +#if CV_VERSION_MAJOR < 5 + inline void write(const Ptr& fs, const String& name) const { CV_Assert(fs); Algorithm::write(*fs, name); } +#endif + +protected: + /** + * Class to work with descriptors from several images as with one merged matrix. + * It is used e.g. in FlannBasedMatcher. + */ + class CV_EXPORTS DescriptorCollection + { + public: + DescriptorCollection(); + DescriptorCollection( const DescriptorCollection& collection ); + virtual ~DescriptorCollection(); + + // Vector of matrices "descriptors" will be merged to one matrix "mergedDescriptors" here. + void set( const std::vector& descriptors ); + virtual void clear(); + + const Mat& getDescriptors() const; + Mat getDescriptor( int imgIdx, int localDescIdx ) const; + Mat getDescriptor( int globalDescIdx ) const; + void getLocalIdx( int globalDescIdx, int& imgIdx, int& localDescIdx ) const; + + int size() const; + + protected: + Mat mergedDescriptors; + std::vector startIdxs; + }; + + //! In fact the matching is implemented only by the following two methods. These methods suppose + //! that the class object has been trained already. Public match methods call these methods + //! after calling train(). + virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; + virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) = 0; + + static bool isPossibleMatch( InputArray mask, int queryIdx, int trainIdx ); + static bool isMaskedOut( InputArrayOfArrays masks, int queryIdx ); + + CV_NODISCARD_STD static Mat clone_op( Mat m ) { return m.clone(); } + void checkMasks( InputArrayOfArrays masks, int queryDescriptorsCount ) const; + + //! Collection of descriptors from train images. + std::vector trainDescCollection; + std::vector utrainDescCollection; +}; + +/** @brief Brute-force descriptor matcher. + +For each descriptor in the first set, this matcher finds the closest descriptor in the second set +by trying each one. This descriptor matcher supports masking permissible matches of descriptor +sets. + */ +class CV_EXPORTS_W BFMatcher : public DescriptorMatcher +{ +public: + /** @brief Brute-force matcher constructor (obsolete). Please use BFMatcher.create() + * + * + */ + CV_WRAP BFMatcher( int normType=NORM_L2, bool crossCheck=false ); + + virtual ~BFMatcher() {} + + virtual bool isMaskSupported() const CV_OVERRIDE { return true; } + + /** @brief Brute-force matcher create method. + @param normType One of NORM_L1, NORM_L2, NORM_HAMMING, NORM_HAMMING2. L1 and L2 norms are + preferable choices for SIFT and SURF descriptors, NORM_HAMMING should be used with ORB, BRISK and + BRIEF, NORM_HAMMING2 should be used with ORB when WTA_K==3 or 4 (see ORB::ORB constructor + description). + @param crossCheck If it is false, this is will be default BFMatcher behaviour when it finds the k + nearest neighbors for each query descriptor. If crossCheck==true, then the knnMatch() method with + k=1 will only return pairs (i,j) such that for i-th query descriptor the j-th descriptor in the + matcher's collection is the nearest and vice versa, i.e. the BFMatcher will only return consistent + pairs. Such technique usually produces best results with minimal number of outliers when there are + enough matches. This is alternative to the ratio test, used by D. Lowe in SIFT paper. + */ + CV_WRAP static Ptr create( int normType=NORM_L2, bool crossCheck=false ) ; + + CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; +protected: + virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + + int normType; + bool crossCheck; +}; + +#if defined(HAVE_OPENCV_FLANN) || defined(CV_DOXYGEN) + +/** @brief Flann-based descriptor matcher. + +This matcher trains cv::flann::Index on a train descriptor collection and calls its nearest search +methods to find the best matches. So, this matcher may be faster when matching a large train +collection than the brute force matcher. FlannBasedMatcher does not support masking permissible +matches of descriptor sets because flann::Index does not support this. : + */ +class CV_EXPORTS_W FlannBasedMatcher : public DescriptorMatcher +{ +public: + CV_WRAP FlannBasedMatcher( const Ptr& indexParams=makePtr(), + const Ptr& searchParams=makePtr() ); + + virtual void add( InputArrayOfArrays descriptors ) CV_OVERRIDE; + virtual void clear() CV_OVERRIDE; + + // Reads matcher object from a file node + virtual void read( const FileNode& ) CV_OVERRIDE; + // Writes matcher object to a file storage + virtual void write( FileStorage& ) const CV_OVERRIDE; + + virtual void train() CV_OVERRIDE; + virtual bool isMaskSupported() const CV_OVERRIDE; + + CV_WRAP static Ptr create(); + + CV_NODISCARD_STD virtual Ptr clone( bool emptyTrainData=false ) const CV_OVERRIDE; +protected: + static void convertToDMatches( const DescriptorCollection& descriptors, + const Mat& indices, const Mat& distances, + std::vector >& matches ); + + virtual void knnMatchImpl( InputArray queryDescriptors, std::vector >& matches, int k, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + virtual void radiusMatchImpl( InputArray queryDescriptors, std::vector >& matches, float maxDistance, + InputArrayOfArrays masks=noArray(), bool compactResult=false ) CV_OVERRIDE; + + Ptr indexParams; + Ptr searchParams; + Ptr flannIndex; + + DescriptorCollection mergedDescriptors; + int addedDescCount; +}; + +#endif + +//! @} features2d_match + +/****************************************************************************************\ +* Drawing functions * +\****************************************************************************************/ + +//! @addtogroup features2d_draw +//! @{ + +enum struct DrawMatchesFlags +{ + DEFAULT = 0, //!< Output image matrix will be created (Mat::create), + //!< i.e. existing memory of output image may be reused. + //!< Two source image, matches and single keypoints will be drawn. + //!< For each keypoint only the center point will be drawn (without + //!< the circle around keypoint with keypoint size and orientation). + DRAW_OVER_OUTIMG = 1, //!< Output image matrix will not be created (Mat::create). + //!< Matches will be drawn on existing content of output image. + NOT_DRAW_SINGLE_POINTS = 2, //!< Single keypoints will not be drawn. + DRAW_RICH_KEYPOINTS = 4 //!< For each keypoint the circle around keypoint with keypoint size and + //!< orientation will be drawn. +}; +CV_ENUM_FLAGS(DrawMatchesFlags) + +/** @brief Draws keypoints. + +@param image Source image. +@param keypoints Keypoints from the source image. +@param outImage Output image. Its content depends on the flags value defining what is drawn in the +output image. See possible flags bit values below. +@param color Color of keypoints. +@param flags Flags setting drawing features. Possible flags bit values are defined by +DrawMatchesFlags. See details above in drawMatches . + +@note +For Python API, flags are modified as cv.DRAW_MATCHES_FLAGS_DEFAULT, +cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS, cv.DRAW_MATCHES_FLAGS_DRAW_OVER_OUTIMG, +cv.DRAW_MATCHES_FLAGS_NOT_DRAW_SINGLE_POINTS + */ +CV_EXPORTS_W void drawKeypoints( InputArray image, const std::vector& keypoints, InputOutputArray outImage, + const Scalar& color=Scalar::all(-1), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +/** @brief Draws the found matches of keypoints from two images. + +@param img1 First source image. +@param keypoints1 Keypoints from the first source image. +@param img2 Second source image. +@param keypoints2 Keypoints from the second source image. +@param matches1to2 Matches from the first image to the second one, which means that keypoints1[i] +has a corresponding point in keypoints2[matches[i]] . +@param outImg Output image. Its content depends on the flags value defining what is drawn in the +output image. See possible flags bit values below. +@param matchColor Color of matches (lines and connected keypoints). If matchColor==Scalar::all(-1) +, the color is generated randomly. +@param singlePointColor Color of single keypoints (circles), which means that keypoints do not +have the matches. If singlePointColor==Scalar::all(-1) , the color is generated randomly. +@param matchesMask Mask determining which matches are drawn. If the mask is empty, all matches are +drawn. +@param flags Flags setting drawing features. Possible flags bit values are defined by +DrawMatchesFlags. + +This function draws matches of keypoints from two images in the output image. Match is a line +connecting two keypoints (circles). See cv::DrawMatchesFlags. + */ +CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, + InputArray img2, const std::vector& keypoints2, + const std::vector& matches1to2, InputOutputArray outImg, + const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), + const std::vector& matchesMask=std::vector(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +/** @overload */ +CV_EXPORTS_W void drawMatches( InputArray img1, const std::vector& keypoints1, + InputArray img2, const std::vector& keypoints2, + const std::vector& matches1to2, InputOutputArray outImg, + const int matchesThickness, const Scalar& matchColor=Scalar::all(-1), + const Scalar& singlePointColor=Scalar::all(-1), const std::vector& matchesMask=std::vector(), + DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +CV_EXPORTS_AS(drawMatchesKnn) void drawMatches( InputArray img1, const std::vector& keypoints1, + InputArray img2, const std::vector& keypoints2, + const std::vector >& matches1to2, InputOutputArray outImg, + const Scalar& matchColor=Scalar::all(-1), const Scalar& singlePointColor=Scalar::all(-1), + const std::vector >& matchesMask=std::vector >(), DrawMatchesFlags flags=DrawMatchesFlags::DEFAULT ); + +//! @} features2d_draw + +/****************************************************************************************\ +* Functions to evaluate the feature detectors and [generic] descriptor extractors * +\****************************************************************************************/ + +//! @addtogroup features2d_main +//! @{ + +CV_EXPORTS void evaluateFeatureDetector( const Mat& img1, const Mat& img2, const Mat& H1to2, + std::vector* keypoints1, std::vector* keypoints2, + float& repeatability, int& correspCount, + const Ptr& fdetector=Ptr() ); + +CV_EXPORTS void computeRecallPrecisionCurve( const std::vector >& matches1to2, + const std::vector >& correctMatches1to2Mask, + std::vector& recallPrecisionCurve ); + +CV_EXPORTS float getRecall( const std::vector& recallPrecisionCurve, float l_precision ); +CV_EXPORTS int getNearestPoint( const std::vector& recallPrecisionCurve, float l_precision ); + +//! @} + +/****************************************************************************************\ +* Bag of visual words * +\****************************************************************************************/ + +//! @addtogroup features2d_category +//! @{ + +/** @brief Abstract base class for training the *bag of visual words* vocabulary from a set of descriptors. + +For details, see, for example, *Visual Categorization with Bags of Keypoints* by Gabriella Csurka, +Christopher R. Dance, Lixin Fan, Jutta Willamowski, Cedric Bray, 2004. : + */ +class CV_EXPORTS_W BOWTrainer +{ +public: + BOWTrainer(); + virtual ~BOWTrainer(); + + /** @brief Adds descriptors to a training set. + + @param descriptors Descriptors to add to a training set. Each row of the descriptors matrix is a + descriptor. + + The training set is clustered using clustermethod to construct the vocabulary. + */ + CV_WRAP void add( const Mat& descriptors ); + + /** @brief Returns a training set of descriptors. + */ + CV_WRAP const std::vector& getDescriptors() const; + + /** @brief Returns the count of all descriptors stored in the training set. + */ + CV_WRAP int descriptorsCount() const; + + CV_WRAP virtual void clear(); + + /** @overload */ + CV_WRAP virtual Mat cluster() const = 0; + + /** @brief Clusters train descriptors. + + @param descriptors Descriptors to cluster. Each row of the descriptors matrix is a descriptor. + Descriptors are not added to the inner train descriptor set. + + The vocabulary consists of cluster centers. So, this method returns the vocabulary. In the first + variant of the method, train descriptors stored in the object are clustered. In the second variant, + input descriptors are clustered. + */ + CV_WRAP virtual Mat cluster( const Mat& descriptors ) const = 0; + +protected: + std::vector descriptors; + int size; +}; + +/** @brief kmeans -based class to train visual vocabulary using the *bag of visual words* approach. : + */ +class CV_EXPORTS_W BOWKMeansTrainer : public BOWTrainer +{ +public: + /** @brief The constructor. + + @see cv::kmeans + */ + CV_WRAP BOWKMeansTrainer( int clusterCount, const TermCriteria& termcrit=TermCriteria(), + int attempts=3, int flags=KMEANS_PP_CENTERS ); + virtual ~BOWKMeansTrainer(); + + // Returns trained vocabulary (i.e. cluster centers). + CV_WRAP virtual Mat cluster() const CV_OVERRIDE; + CV_WRAP virtual Mat cluster( const Mat& descriptors ) const CV_OVERRIDE; + +protected: + + int clusterCount; + TermCriteria termcrit; + int attempts; + int flags; +}; + +/** @brief Class to compute an image descriptor using the *bag of visual words*. + +Such a computation consists of the following steps: + +1. Compute descriptors for a given image and its keypoints set. +2. Find the nearest visual words from the vocabulary for each keypoint descriptor. +3. Compute the bag-of-words image descriptor as is a normalized histogram of vocabulary words +encountered in the image. The i-th bin of the histogram is a frequency of i-th word of the +vocabulary in the given image. + */ +class CV_EXPORTS_W BOWImgDescriptorExtractor +{ +public: + /** @brief The constructor. + + @param dextractor Descriptor extractor that is used to compute descriptors for an input image and + its keypoints. + @param dmatcher Descriptor matcher that is used to find the nearest word of the trained vocabulary + for each keypoint descriptor of the image. + */ + CV_WRAP BOWImgDescriptorExtractor( const Ptr& dextractor, + const Ptr& dmatcher ); + /** @overload */ + BOWImgDescriptorExtractor( const Ptr& dmatcher ); + virtual ~BOWImgDescriptorExtractor(); + + /** @brief Sets a visual vocabulary. + + @param vocabulary Vocabulary (can be trained using the inheritor of BOWTrainer ). Each row of the + vocabulary is a visual word (cluster center). + */ + CV_WRAP void setVocabulary( const Mat& vocabulary ); + + /** @brief Returns the set vocabulary. + */ + CV_WRAP const Mat& getVocabulary() const; + + /** @brief Computes an image descriptor using the set visual vocabulary. + + @param image Image, for which the descriptor is computed. + @param keypoints Keypoints detected in the input image. + @param imgDescriptor Computed output image descriptor. + @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that + pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) + returned if it is non-zero. + @param descriptors Descriptors of the image keypoints that are returned if they are non-zero. + */ + void compute( InputArray image, std::vector& keypoints, OutputArray imgDescriptor, + std::vector >* pointIdxsOfClusters=0, Mat* descriptors=0 ); + /** @overload + @param keypointDescriptors Computed descriptors to match with vocabulary. + @param imgDescriptor Computed output image descriptor. + @param pointIdxsOfClusters Indices of keypoints that belong to the cluster. This means that + pointIdxsOfClusters[i] are keypoint indices that belong to the i -th cluster (word of vocabulary) + returned if it is non-zero. + */ + void compute( InputArray keypointDescriptors, OutputArray imgDescriptor, + std::vector >* pointIdxsOfClusters=0 ); + // compute() is not constant because DescriptorMatcher::match is not constant + + CV_WRAP_AS(compute) void compute2( const Mat& image, std::vector& keypoints, CV_OUT Mat& imgDescriptor ) + { compute(image,keypoints,imgDescriptor); } + + /** @brief Returns an image descriptor size if the vocabulary is set. Otherwise, it returns 0. + */ + CV_WRAP int descriptorSize() const; + + /** @brief Returns an image descriptor type. + */ + CV_WRAP int descriptorType() const; + +protected: + Mat vocabulary; + Ptr dextractor; + Ptr dmatcher; +}; + +//! @} features2d_category + +} /* namespace cv */ + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp b/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp index 69c97639ee..e81df0ad08 100644 --- a/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/features2d/features2d.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/features2d.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/features2d.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h b/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h index 4ce2b999fd..bc3b084264 100644 --- a/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h +++ b/3rdParty/opencv-4.11.0/opencv2/features2d/hal/interface.h @@ -1,33 +1,33 @@ -#ifndef OPENCV_FEATURE2D_HAL_INTERFACE_H -#define OPENCV_FEATURE2D_HAL_INTERFACE_H - -#include "opencv2/core/cvdef.h" -//! @addtogroup features2d_hal_interface -//! @{ - -//! @name Fast feature detector types -//! @sa cv::FastFeatureDetector -//! @{ -#define CV_HAL_TYPE_5_8 0 -#define CV_HAL_TYPE_7_12 1 -#define CV_HAL_TYPE_9_16 2 -//! @} - -//! @name Key point -//! @sa cv::KeyPoint -//! @{ -struct CV_EXPORTS cvhalKeyPoint -{ - float x; - float y; - float size; - float angle; - float response; - int octave; - int class_id; -}; -//! @} - -//! @} - -#endif +#ifndef OPENCV_FEATURE2D_HAL_INTERFACE_H +#define OPENCV_FEATURE2D_HAL_INTERFACE_H + +#include "opencv2/core/cvdef.h" +//! @addtogroup features2d_hal_interface +//! @{ + +//! @name Fast feature detector types +//! @sa cv::FastFeatureDetector +//! @{ +#define CV_HAL_TYPE_5_8 0 +#define CV_HAL_TYPE_7_12 1 +#define CV_HAL_TYPE_9_16 2 +//! @} + +//! @name Key point +//! @sa cv::KeyPoint +//! @{ +struct CV_EXPORTS cvhalKeyPoint +{ + float x; + float y; + float size; + float angle; + float response; + int octave; + int class_id; +}; +//! @} + +//! @} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/flann.hpp b/3rdParty/opencv-4.11.0/opencv2/flann.hpp index 7f142ca7be..90ee59e0b8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann.hpp @@ -1,629 +1,629 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_FLANN_HPP -#define OPENCV_FLANN_HPP - -#include "opencv2/core.hpp" -#include "opencv2/flann/miniflann.hpp" -#include "opencv2/flann/flann_base.hpp" - -/** -@defgroup flann Clustering and Search in Multi-Dimensional Spaces - -This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate -Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest -neighbor search in large datasets and for high dimensional features. More information about FLANN -can be found in @cite Muja2009 . -*/ - -namespace cvflann -{ - CV_EXPORTS flann_distance_t flann_distance_type(); - CV_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order); -} - - -namespace cv -{ -namespace flann -{ - - -//! @addtogroup flann -//! @{ - -template struct CvType {}; -template <> struct CvType { static int type() { return CV_8U; } }; -template <> struct CvType { static int type() { return CV_8S; } }; -template <> struct CvType { static int type() { return CV_16U; } }; -template <> struct CvType { static int type() { return CV_16S; } }; -template <> struct CvType { static int type() { return CV_32S; } }; -template <> struct CvType { static int type() { return CV_32F; } }; -template <> struct CvType { static int type() { return CV_64F; } }; - - -// bring the flann parameters into this namespace -using ::cvflann::get_param; -using ::cvflann::print_params; - -// bring the flann distances into this namespace -using ::cvflann::L2_Simple; -using ::cvflann::L2; -using ::cvflann::L1; -using ::cvflann::MinkowskiDistance; -using ::cvflann::MaxDistance; -using ::cvflann::HammingLUT; -using ::cvflann::Hamming; -using ::cvflann::Hamming2; -using ::cvflann::DNAmmingLUT; -using ::cvflann::DNAmming2; -using ::cvflann::HistIntersectionDistance; -using ::cvflann::HellingerDistance; -using ::cvflann::ChiSquareDistance; -using ::cvflann::KL_Divergence; - - -/** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which -the index is built. - -`Distance` functor specifies the metric to be used to calculate the distance between two points. -There are several `Distance` functors that are readily available: - -cv::cvflann::L2_Simple - Squared Euclidean distance functor. -This is the simpler, unrolled version. This is preferable for very low dimensionality data (eg 3D points) - -cv::flann::L2 - Squared Euclidean distance functor, optimized version. - -cv::flann::L1 - Manhattan distance functor, optimized version. - -cv::flann::MinkowskiDistance - The Minkowski distance functor. -This is highly optimised with loop unrolling. -The computation of squared root at the end is omitted for efficiency. - -cv::flann::MaxDistance - The max distance functor. It computes the -maximum distance between two vectors. This distance is not a valid kdtree distance, it's not -dimensionwise additive. - -cv::flann::HammingLUT - %Hamming distance functor. It counts the bit -differences between two strings using a lookup table implementation. - -cv::flann::Hamming - %Hamming distance functor. Population count is -performed using library calls, if available. Lookup table implementation is used as a fallback. - -cv::flann::Hamming2 - %Hamming distance functor. Population count is -implemented in 12 arithmetic operations (one of which is multiplication). - -cv::flann::DNAmmingLUT - %Adaptation of the Hamming distance functor to DNA comparison. -As the four bases A, C, G, T of the DNA (or A, G, C, U for RNA) can be coded on 2 bits, -it counts the bits pairs differences between two sequences using a lookup table implementation. - -cv::flann::DNAmming2 - %Adaptation of the Hamming distance functor to DNA comparison. -Bases differences count are vectorised thanks to arithmetic operations using standard -registers (AVX2 and AVX-512 should come in a near future). - -cv::flann::HistIntersectionDistance - The histogram -intersection distance functor. - -cv::flann::HellingerDistance - The Hellinger distance functor. - -cv::flann::ChiSquareDistance - The chi-square distance functor. - -cv::flann::KL_Divergence - The Kullback-Leibler divergence functor. - -Although the provided implementations cover a vast range of cases, it is also possible to use -a custom implementation. The distance functor is a class whose `operator()` computes the distance -between two features. If the distance is also a kd-tree compatible distance, it should also provide an -`accum_dist()` method that computes the distance between individual feature dimensions. - -In addition to `operator()` and `accum_dist()`, a distance functor should also define the -`ElementType` and the `ResultType` as the types of the elements it operates on and the type of the -result it computes. If a distance functor can be used as a kd-tree distance (meaning that the full -distance between a pair of features can be accumulated from the partial distances between the -individual dimensions) a typedef `is_kdtree_distance` should be present inside the distance functor. -If the distance is not a kd-tree distance, but it's a distance in a vector space (the individual -dimensions of the elements it operates on can be accessed independently) a typedef -`is_vector_space_distance` should be defined inside the functor. If neither typedef is defined, the -distance is assumed to be a metric distance and will only be used with indexes operating on -generic metric distances. - */ -template -class GenericIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - /** @brief Constructs a nearest neighbor search index for a given dataset. - - @param features Matrix of containing the features(points) to index. The size of the matrix is - num_features x feature_dimensionality and the data type of the elements in the matrix must - coincide with the type of the index. - @param params Structure containing the index parameters. The type of index that will be - constructed depends on the type of this parameter. See the description. - @param distance - - The method constructs a fast search structure from a set of features using the specified algorithm - with specified parameters, as defined by params. params is a reference to one of the following class - IndexParams descendants: - - - **LinearIndexParams** When passing an object of this type, the index will perform a linear, - brute-force search. : - @code - struct LinearIndexParams : public IndexParams - { - }; - @endcode - - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of - a set of randomized kd-trees which will be searched in parallel. : - @code - struct KDTreeIndexParams : public IndexParams - { - KDTreeIndexParams( int trees = 4 ); - }; - @endcode - - **HierarchicalClusteringIndexParams** When passing an object of this type the index constructed - will be a hierarchical tree of clusters, dividing each set of points into n clusters whose centers - are picked among the points without further refinement of their position. - This algorithm fits both floating, integer and binary vectors. : - @code - struct HierarchicalClusteringIndexParams : public IndexParams - { - HierarchicalClusteringIndexParams( - int branching = 32, - flann_centers_init_t centers_init = CENTERS_RANDOM, - int trees = 4, - int leaf_size = 100); - - }; - @endcode - - **KMeansIndexParams** When passing an object of this type the index constructed will be a - hierarchical k-means tree (one tree by default), dividing each set of points into n clusters - whose barycenters are refined iteratively. - Note that this algorithm has been extended to the support of binary vectors as an alternative - to LSH when knn search speed is the criterium. It will also outperform LSH when processing - directly (i.e. without the use of MCA/PCA) datasets whose points share mostly the same values - for most of the dimensions. It is recommended to set more than one tree with binary data. : - @code - struct KMeansIndexParams : public IndexParams - { - KMeansIndexParams( - int branching = 32, - int iterations = 11, - flann_centers_init_t centers_init = CENTERS_RANDOM, - float cb_index = 0.2, - int trees = 1); - }; - @endcode - - **CompositeIndexParams** When using a parameters object of this type the index created - combines the randomized kd-trees and the hierarchical k-means tree. : - @code - struct CompositeIndexParams : public IndexParams - { - CompositeIndexParams( - int trees = 4, - int branching = 32, - int iterations = 11, - flann_centers_init_t centers_init = CENTERS_RANDOM, - float cb_index = 0.2 ); - }; - @endcode - - **LshIndexParams** When using a parameters object of this type the index created uses - multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search - by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd - International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007). - This algorithm is designed for binary vectors. : - @code - struct LshIndexParams : public IndexParams - { - LshIndexParams( - int table_number, - int key_size, - int multi_probe_level ); - }; - @endcode - - **AutotunedIndexParams** When passing an object of this type the index created is - automatically tuned to offer the best performance, by choosing the optimal index type - (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. : - @code - struct AutotunedIndexParams : public IndexParams - { - AutotunedIndexParams( - float target_precision = 0.9, - float build_weight = 0.01, - float memory_weight = 0, - float sample_fraction = 0.1 ); - }; - @endcode - - **SavedIndexParams** This object type is used for loading a previously saved index from the - disk. : - @code - struct SavedIndexParams : public IndexParams - { - SavedIndexParams( String filename ); - }; - @endcode - */ - GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance()); - - ~GenericIndex(); - - /** @brief Performs a K-nearest neighbor search for a given query point using the index. - - @param query The query point - @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have - at least knn size. - @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have - at least knn size. - @param knn Number of nearest neighbors to search for. - @param params SearchParams - */ - void knnSearch(const std::vector& query, std::vector& indices, - std::vector& dists, int knn, const ::cvflann::SearchParams& params); - void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); - - /** @brief Performs a radius nearest neighbor search for a given query point using the index. - - @param query The query point. - @param indices Vector that will contain the indices of the nearest neighbors found. - @param dists Vector that will contain the distances to the nearest neighbors found. It has the same - number of elements as indices. - @param radius The search radius. - @param params SearchParams - - This function returns the number of nearest neighbors found. - */ - int radiusSearch(const std::vector& query, std::vector& indices, - std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); - int radiusSearch(const Mat& query, Mat& indices, Mat& dists, - DistanceType radius, const ::cvflann::SearchParams& params); - - void save(String filename) { nnIndex->save(filename); } - - int veclen() const { return nnIndex->veclen(); } - - int size() const { return (int)nnIndex->size(); } - - ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); } - - CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); } - -private: - ::cvflann::Index* nnIndex; - Mat _dataset; -}; - -//! @cond IGNORED - -#define FLANN_DISTANCE_CHECK \ - if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \ - printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\ - "the distance using cvflann::set_distance_type. This is no longer working as expected "\ - "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\ - "for example for L1 distance use: GenericIndex< L1 > \n"); \ - } - - -template -GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance) -: _dataset(dataset) -{ - CV_Assert(dataset.type() == CvType::type()); - CV_Assert(dataset.isContinuous()); - ::cvflann::Matrix m_dataset((ElementType*)_dataset.ptr(0), _dataset.rows, _dataset.cols); - - nnIndex = new ::cvflann::Index(m_dataset, params, distance); - - FLANN_DISTANCE_CHECK - - nnIndex->buildIndex(); -} - -template -GenericIndex::~GenericIndex() -{ - delete nnIndex; -} - -template -void GenericIndex::knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) -{ - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - FLANN_DISTANCE_CHECK - - nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams); -} - - -template -void GenericIndex::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) -{ - CV_Assert(queries.type() == CvType::type()); - CV_Assert(queries.isContinuous()); - ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - FLANN_DISTANCE_CHECK - - nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); -} - -template -int GenericIndex::radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) -{ - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - FLANN_DISTANCE_CHECK - - return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); -} - -template -int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) -{ - CV_Assert(query.type() == CvType::type()); - CV_Assert(query.isContinuous()); - ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - FLANN_DISTANCE_CHECK - - return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); -} - -/** - * @deprecated Use GenericIndex class instead - */ -template -class Index_ -{ -public: - typedef typename L2::ElementType ElementType; - typedef typename L2::ResultType DistanceType; - - CV_DEPRECATED Index_(const Mat& dataset, const ::cvflann::IndexParams& params) - { - printf("[WARNING] The cv::flann::Index_ class is deperecated, use cv::flann::GenericIndex instead\n"); - - CV_Assert(dataset.type() == CvType::type()); - CV_Assert(dataset.isContinuous()); - ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); - - if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { - nnIndex_L1 = NULL; - nnIndex_L2 = new ::cvflann::Index< L2 >(m_dataset, params); - } - else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { - nnIndex_L1 = new ::cvflann::Index< L1 >(m_dataset, params); - nnIndex_L2 = NULL; - } - else { - printf("[ERROR] cv::flann::Index_ only provides backwards compatibility for the L1 and L2 distances. " - "For other distance types you must use cv::flann::GenericIndex\n"); - CV_Assert(0); - } - if (nnIndex_L1) nnIndex_L1->buildIndex(); - if (nnIndex_L2) nnIndex_L2->buildIndex(); - } - CV_DEPRECATED ~Index_() - { - if (nnIndex_L1) delete nnIndex_L1; - if (nnIndex_L2) delete nnIndex_L2; - } - - CV_DEPRECATED void knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) - { - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams); - if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams); - } - CV_DEPRECATED void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) - { - CV_Assert(queries.type() == CvType::type()); - CV_Assert(queries.isContinuous()); - ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); - if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); - } - - CV_DEPRECATED int radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) - { - ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); - ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); - ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); - - if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - } - - CV_DEPRECATED int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) - { - CV_Assert(query.type() == CvType::type()); - CV_Assert(query.isContinuous()); - ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); - - CV_Assert(indices.type() == CV_32S); - CV_Assert(indices.isContinuous()); - ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); - - CV_Assert(dists.type() == CvType::type()); - CV_Assert(dists.isContinuous()); - ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); - - if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); - } - - CV_DEPRECATED void save(String filename) - { - if (nnIndex_L1) nnIndex_L1->save(filename); - if (nnIndex_L2) nnIndex_L2->save(filename); - } - - CV_DEPRECATED int veclen() const - { - if (nnIndex_L1) return nnIndex_L1->veclen(); - if (nnIndex_L2) return nnIndex_L2->veclen(); - } - - CV_DEPRECATED int size() const - { - if (nnIndex_L1) return nnIndex_L1->size(); - if (nnIndex_L2) return nnIndex_L2->size(); - } - - CV_DEPRECATED ::cvflann::IndexParams getParameters() - { - if (nnIndex_L1) return nnIndex_L1->getParameters(); - if (nnIndex_L2) return nnIndex_L2->getParameters(); - - } - - CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() - { - if (nnIndex_L1) return nnIndex_L1->getIndexParameters(); - if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); - } - -private: - // providing backwards compatibility for L2 and L1 distances (most common) - ::cvflann::Index< L2 >* nnIndex_L2; - ::cvflann::Index< L1 >* nnIndex_L1; -}; - -//! @endcond - -/** @brief Clusters features using hierarchical k-means algorithm. - -@param features The points to be clustered. The matrix must have elements of type -Distance::ElementType. -@param centers The centers of the clusters obtained. The matrix must have type -Distance::CentersType. The number of rows in this matrix represents the number of clusters desired, -however, because of the way the cut in the hierarchical tree is chosen, the number of clusters -computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of -clusters desired, where branching is the tree's branching factor (see description of the -KMeansIndexParams). -@param params Parameters used in the construction of the hierarchical k-means tree. -@param d Distance to be used for clustering. - -The method clusters the given feature vectors by constructing a hierarchical k-means tree and -choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters -found. - */ -template -int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params, - Distance d = Distance()) -{ - typedef typename Distance::ElementType ElementType; - typedef typename Distance::CentersType CentersType; - - CV_Assert(features.type() == CvType::type()); - CV_Assert(features.isContinuous()); - ::cvflann::Matrix m_features((ElementType*)features.ptr(0), features.rows, features.cols); - - CV_Assert(centers.type() == CvType::type()); - CV_Assert(centers.isContinuous()); - ::cvflann::Matrix m_centers((CentersType*)centers.ptr(0), centers.rows, centers.cols); - - return ::cvflann::hierarchicalClustering(m_features, m_centers, params, d); -} - -//! @cond IGNORED - -template -CV_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params) -{ - printf("[WARNING] cv::flann::hierarchicalClustering is deprecated, use " - "cv::flann::hierarchicalClustering instead\n"); - - if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { - return hierarchicalClustering< L2 >(features, centers, params); - } - else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { - return hierarchicalClustering< L1 >(features, centers, params); - } - else { - printf("[ERROR] cv::flann::hierarchicalClustering only provides backwards " - "compatibility for the L1 and L2 distances. " - "For other distance types you must use cv::flann::hierarchicalClustering\n"); - CV_Assert(0); - } -} - -//! @endcond - -//! @} flann - -} } // namespace cv::flann - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_FLANN_HPP +#define OPENCV_FLANN_HPP + +#include "opencv2/core.hpp" +#include "opencv2/flann/miniflann.hpp" +#include "opencv2/flann/flann_base.hpp" + +/** +@defgroup flann Clustering and Search in Multi-Dimensional Spaces + +This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate +Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest +neighbor search in large datasets and for high dimensional features. More information about FLANN +can be found in @cite Muja2009 . +*/ + +namespace cvflann +{ + CV_EXPORTS flann_distance_t flann_distance_type(); + CV_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order); +} + + +namespace cv +{ +namespace flann +{ + + +//! @addtogroup flann +//! @{ + +template struct CvType {}; +template <> struct CvType { static int type() { return CV_8U; } }; +template <> struct CvType { static int type() { return CV_8S; } }; +template <> struct CvType { static int type() { return CV_16U; } }; +template <> struct CvType { static int type() { return CV_16S; } }; +template <> struct CvType { static int type() { return CV_32S; } }; +template <> struct CvType { static int type() { return CV_32F; } }; +template <> struct CvType { static int type() { return CV_64F; } }; + + +// bring the flann parameters into this namespace +using ::cvflann::get_param; +using ::cvflann::print_params; + +// bring the flann distances into this namespace +using ::cvflann::L2_Simple; +using ::cvflann::L2; +using ::cvflann::L1; +using ::cvflann::MinkowskiDistance; +using ::cvflann::MaxDistance; +using ::cvflann::HammingLUT; +using ::cvflann::Hamming; +using ::cvflann::Hamming2; +using ::cvflann::DNAmmingLUT; +using ::cvflann::DNAmming2; +using ::cvflann::HistIntersectionDistance; +using ::cvflann::HellingerDistance; +using ::cvflann::ChiSquareDistance; +using ::cvflann::KL_Divergence; + + +/** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which +the index is built. + +`Distance` functor specifies the metric to be used to calculate the distance between two points. +There are several `Distance` functors that are readily available: + +cv::cvflann::L2_Simple - Squared Euclidean distance functor. +This is the simpler, unrolled version. This is preferable for very low dimensionality data (eg 3D points) + +cv::flann::L2 - Squared Euclidean distance functor, optimized version. + +cv::flann::L1 - Manhattan distance functor, optimized version. + +cv::flann::MinkowskiDistance - The Minkowski distance functor. +This is highly optimised with loop unrolling. +The computation of squared root at the end is omitted for efficiency. + +cv::flann::MaxDistance - The max distance functor. It computes the +maximum distance between two vectors. This distance is not a valid kdtree distance, it's not +dimensionwise additive. + +cv::flann::HammingLUT - %Hamming distance functor. It counts the bit +differences between two strings using a lookup table implementation. + +cv::flann::Hamming - %Hamming distance functor. Population count is +performed using library calls, if available. Lookup table implementation is used as a fallback. + +cv::flann::Hamming2 - %Hamming distance functor. Population count is +implemented in 12 arithmetic operations (one of which is multiplication). + +cv::flann::DNAmmingLUT - %Adaptation of the Hamming distance functor to DNA comparison. +As the four bases A, C, G, T of the DNA (or A, G, C, U for RNA) can be coded on 2 bits, +it counts the bits pairs differences between two sequences using a lookup table implementation. + +cv::flann::DNAmming2 - %Adaptation of the Hamming distance functor to DNA comparison. +Bases differences count are vectorised thanks to arithmetic operations using standard +registers (AVX2 and AVX-512 should come in a near future). + +cv::flann::HistIntersectionDistance - The histogram +intersection distance functor. + +cv::flann::HellingerDistance - The Hellinger distance functor. + +cv::flann::ChiSquareDistance - The chi-square distance functor. + +cv::flann::KL_Divergence - The Kullback-Leibler divergence functor. + +Although the provided implementations cover a vast range of cases, it is also possible to use +a custom implementation. The distance functor is a class whose `operator()` computes the distance +between two features. If the distance is also a kd-tree compatible distance, it should also provide an +`accum_dist()` method that computes the distance between individual feature dimensions. + +In addition to `operator()` and `accum_dist()`, a distance functor should also define the +`ElementType` and the `ResultType` as the types of the elements it operates on and the type of the +result it computes. If a distance functor can be used as a kd-tree distance (meaning that the full +distance between a pair of features can be accumulated from the partial distances between the +individual dimensions) a typedef `is_kdtree_distance` should be present inside the distance functor. +If the distance is not a kd-tree distance, but it's a distance in a vector space (the individual +dimensions of the elements it operates on can be accessed independently) a typedef +`is_vector_space_distance` should be defined inside the functor. If neither typedef is defined, the +distance is assumed to be a metric distance and will only be used with indexes operating on +generic metric distances. + */ +template +class GenericIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + /** @brief Constructs a nearest neighbor search index for a given dataset. + + @param features Matrix of containing the features(points) to index. The size of the matrix is + num_features x feature_dimensionality and the data type of the elements in the matrix must + coincide with the type of the index. + @param params Structure containing the index parameters. The type of index that will be + constructed depends on the type of this parameter. See the description. + @param distance + + The method constructs a fast search structure from a set of features using the specified algorithm + with specified parameters, as defined by params. params is a reference to one of the following class + IndexParams descendants: + + - **LinearIndexParams** When passing an object of this type, the index will perform a linear, + brute-force search. : + @code + struct LinearIndexParams : public IndexParams + { + }; + @endcode + - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of + a set of randomized kd-trees which will be searched in parallel. : + @code + struct KDTreeIndexParams : public IndexParams + { + KDTreeIndexParams( int trees = 4 ); + }; + @endcode + - **HierarchicalClusteringIndexParams** When passing an object of this type the index constructed + will be a hierarchical tree of clusters, dividing each set of points into n clusters whose centers + are picked among the points without further refinement of their position. + This algorithm fits both floating, integer and binary vectors. : + @code + struct HierarchicalClusteringIndexParams : public IndexParams + { + HierarchicalClusteringIndexParams( + int branching = 32, + flann_centers_init_t centers_init = CENTERS_RANDOM, + int trees = 4, + int leaf_size = 100); + + }; + @endcode + - **KMeansIndexParams** When passing an object of this type the index constructed will be a + hierarchical k-means tree (one tree by default), dividing each set of points into n clusters + whose barycenters are refined iteratively. + Note that this algorithm has been extended to the support of binary vectors as an alternative + to LSH when knn search speed is the criterium. It will also outperform LSH when processing + directly (i.e. without the use of MCA/PCA) datasets whose points share mostly the same values + for most of the dimensions. It is recommended to set more than one tree with binary data. : + @code + struct KMeansIndexParams : public IndexParams + { + KMeansIndexParams( + int branching = 32, + int iterations = 11, + flann_centers_init_t centers_init = CENTERS_RANDOM, + float cb_index = 0.2, + int trees = 1); + }; + @endcode + - **CompositeIndexParams** When using a parameters object of this type the index created + combines the randomized kd-trees and the hierarchical k-means tree. : + @code + struct CompositeIndexParams : public IndexParams + { + CompositeIndexParams( + int trees = 4, + int branching = 32, + int iterations = 11, + flann_centers_init_t centers_init = CENTERS_RANDOM, + float cb_index = 0.2 ); + }; + @endcode + - **LshIndexParams** When using a parameters object of this type the index created uses + multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search + by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd + International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007). + This algorithm is designed for binary vectors. : + @code + struct LshIndexParams : public IndexParams + { + LshIndexParams( + int table_number, + int key_size, + int multi_probe_level ); + }; + @endcode + - **AutotunedIndexParams** When passing an object of this type the index created is + automatically tuned to offer the best performance, by choosing the optimal index type + (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. : + @code + struct AutotunedIndexParams : public IndexParams + { + AutotunedIndexParams( + float target_precision = 0.9, + float build_weight = 0.01, + float memory_weight = 0, + float sample_fraction = 0.1 ); + }; + @endcode + - **SavedIndexParams** This object type is used for loading a previously saved index from the + disk. : + @code + struct SavedIndexParams : public IndexParams + { + SavedIndexParams( String filename ); + }; + @endcode + */ + GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance()); + + ~GenericIndex(); + + /** @brief Performs a K-nearest neighbor search for a given query point using the index. + + @param query The query point + @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have + at least knn size. + @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have + at least knn size. + @param knn Number of nearest neighbors to search for. + @param params SearchParams + */ + void knnSearch(const std::vector& query, std::vector& indices, + std::vector& dists, int knn, const ::cvflann::SearchParams& params); + void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params); + + /** @brief Performs a radius nearest neighbor search for a given query point using the index. + + @param query The query point. + @param indices Vector that will contain the indices of the nearest neighbors found. + @param dists Vector that will contain the distances to the nearest neighbors found. It has the same + number of elements as indices. + @param radius The search radius. + @param params SearchParams + + This function returns the number of nearest neighbors found. + */ + int radiusSearch(const std::vector& query, std::vector& indices, + std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& params); + int radiusSearch(const Mat& query, Mat& indices, Mat& dists, + DistanceType radius, const ::cvflann::SearchParams& params); + + void save(String filename) { nnIndex->save(filename); } + + int veclen() const { return nnIndex->veclen(); } + + int size() const { return (int)nnIndex->size(); } + + ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); } + + CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); } + +private: + ::cvflann::Index* nnIndex; + Mat _dataset; +}; + +//! @cond IGNORED + +#define FLANN_DISTANCE_CHECK \ + if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \ + printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\ + "the distance using cvflann::set_distance_type. This is no longer working as expected "\ + "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\ + "for example for L1 distance use: GenericIndex< L1 > \n"); \ + } + + +template +GenericIndex::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance) +: _dataset(dataset) +{ + CV_Assert(dataset.type() == CvType::type()); + CV_Assert(dataset.isContinuous()); + ::cvflann::Matrix m_dataset((ElementType*)_dataset.ptr(0), _dataset.rows, _dataset.cols); + + nnIndex = new ::cvflann::Index(m_dataset, params, distance); + + FLANN_DISTANCE_CHECK + + nnIndex->buildIndex(); +} + +template +GenericIndex::~GenericIndex() +{ + delete nnIndex; +} + +template +void GenericIndex::knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) +{ + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + FLANN_DISTANCE_CHECK + + nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams); +} + + +template +void GenericIndex::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) +{ + CV_Assert(queries.type() == CvType::type()); + CV_Assert(queries.isContinuous()); + ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + FLANN_DISTANCE_CHECK + + nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); +} + +template +int GenericIndex::radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) +{ + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + FLANN_DISTANCE_CHECK + + return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); +} + +template +int GenericIndex::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) +{ + CV_Assert(query.type() == CvType::type()); + CV_Assert(query.isContinuous()); + ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + FLANN_DISTANCE_CHECK + + return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); +} + +/** + * @deprecated Use GenericIndex class instead + */ +template +class Index_ +{ +public: + typedef typename L2::ElementType ElementType; + typedef typename L2::ResultType DistanceType; + + CV_DEPRECATED Index_(const Mat& dataset, const ::cvflann::IndexParams& params) + { + printf("[WARNING] The cv::flann::Index_ class is deperecated, use cv::flann::GenericIndex instead\n"); + + CV_Assert(dataset.type() == CvType::type()); + CV_Assert(dataset.isContinuous()); + ::cvflann::Matrix m_dataset((ElementType*)dataset.ptr(0), dataset.rows, dataset.cols); + + if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { + nnIndex_L1 = NULL; + nnIndex_L2 = new ::cvflann::Index< L2 >(m_dataset, params); + } + else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { + nnIndex_L1 = new ::cvflann::Index< L1 >(m_dataset, params); + nnIndex_L2 = NULL; + } + else { + printf("[ERROR] cv::flann::Index_ only provides backwards compatibility for the L1 and L2 distances. " + "For other distance types you must use cv::flann::GenericIndex\n"); + CV_Assert(0); + } + if (nnIndex_L1) nnIndex_L1->buildIndex(); + if (nnIndex_L2) nnIndex_L2->buildIndex(); + } + CV_DEPRECATED ~Index_() + { + if (nnIndex_L1) delete nnIndex_L1; + if (nnIndex_L2) delete nnIndex_L2; + } + + CV_DEPRECATED void knnSearch(const std::vector& query, std::vector& indices, std::vector& dists, int knn, const ::cvflann::SearchParams& searchParams) + { + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams); + if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams); + } + CV_DEPRECATED void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams) + { + CV_Assert(queries.type() == CvType::type()); + CV_Assert(queries.isContinuous()); + ::cvflann::Matrix m_queries((ElementType*)queries.ptr(0), queries.rows, queries.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); + if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams); + } + + CV_DEPRECATED int radiusSearch(const std::vector& query, std::vector& indices, std::vector& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) + { + ::cvflann::Matrix m_query((ElementType*)&query[0], 1, query.size()); + ::cvflann::Matrix m_indices(&indices[0], 1, indices.size()); + ::cvflann::Matrix m_dists(&dists[0], 1, dists.size()); + + if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + } + + CV_DEPRECATED int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams) + { + CV_Assert(query.type() == CvType::type()); + CV_Assert(query.isContinuous()); + ::cvflann::Matrix m_query((ElementType*)query.ptr(0), query.rows, query.cols); + + CV_Assert(indices.type() == CV_32S); + CV_Assert(indices.isContinuous()); + ::cvflann::Matrix m_indices((int*)indices.ptr(0), indices.rows, indices.cols); + + CV_Assert(dists.type() == CvType::type()); + CV_Assert(dists.isContinuous()); + ::cvflann::Matrix m_dists((DistanceType*)dists.ptr(0), dists.rows, dists.cols); + + if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams); + } + + CV_DEPRECATED void save(String filename) + { + if (nnIndex_L1) nnIndex_L1->save(filename); + if (nnIndex_L2) nnIndex_L2->save(filename); + } + + CV_DEPRECATED int veclen() const + { + if (nnIndex_L1) return nnIndex_L1->veclen(); + if (nnIndex_L2) return nnIndex_L2->veclen(); + } + + CV_DEPRECATED int size() const + { + if (nnIndex_L1) return nnIndex_L1->size(); + if (nnIndex_L2) return nnIndex_L2->size(); + } + + CV_DEPRECATED ::cvflann::IndexParams getParameters() + { + if (nnIndex_L1) return nnIndex_L1->getParameters(); + if (nnIndex_L2) return nnIndex_L2->getParameters(); + + } + + CV_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() + { + if (nnIndex_L1) return nnIndex_L1->getIndexParameters(); + if (nnIndex_L2) return nnIndex_L2->getIndexParameters(); + } + +private: + // providing backwards compatibility for L2 and L1 distances (most common) + ::cvflann::Index< L2 >* nnIndex_L2; + ::cvflann::Index< L1 >* nnIndex_L1; +}; + +//! @endcond + +/** @brief Clusters features using hierarchical k-means algorithm. + +@param features The points to be clustered. The matrix must have elements of type +Distance::ElementType. +@param centers The centers of the clusters obtained. The matrix must have type +Distance::CentersType. The number of rows in this matrix represents the number of clusters desired, +however, because of the way the cut in the hierarchical tree is chosen, the number of clusters +computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of +clusters desired, where branching is the tree's branching factor (see description of the +KMeansIndexParams). +@param params Parameters used in the construction of the hierarchical k-means tree. +@param d Distance to be used for clustering. + +The method clusters the given feature vectors by constructing a hierarchical k-means tree and +choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters +found. + */ +template +int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params, + Distance d = Distance()) +{ + typedef typename Distance::ElementType ElementType; + typedef typename Distance::CentersType CentersType; + + CV_Assert(features.type() == CvType::type()); + CV_Assert(features.isContinuous()); + ::cvflann::Matrix m_features((ElementType*)features.ptr(0), features.rows, features.cols); + + CV_Assert(centers.type() == CvType::type()); + CV_Assert(centers.isContinuous()); + ::cvflann::Matrix m_centers((CentersType*)centers.ptr(0), centers.rows, centers.cols); + + return ::cvflann::hierarchicalClustering(m_features, m_centers, params, d); +} + +//! @cond IGNORED + +template +CV_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params) +{ + printf("[WARNING] cv::flann::hierarchicalClustering is deprecated, use " + "cv::flann::hierarchicalClustering instead\n"); + + if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) { + return hierarchicalClustering< L2 >(features, centers, params); + } + else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) { + return hierarchicalClustering< L1 >(features, centers, params); + } + else { + printf("[ERROR] cv::flann::hierarchicalClustering only provides backwards " + "compatibility for the L1 and L2 distances. " + "For other distance types you must use cv::flann::hierarchicalClustering\n"); + CV_Assert(0); + } +} + +//! @endcond + +//! @} flann + +} } // namespace cv::flann + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h b/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h index a59f8c5fbf..03877ab6ad 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/all_indices.h @@ -1,162 +1,162 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - - -#ifndef OPENCV_FLANN_ALL_INDICES_H_ -#define OPENCV_FLANN_ALL_INDICES_H_ - -//! @cond IGNORED - -#include "general.h" - -#include "nn_index.h" -#include "kdtree_index.h" -#include "kdtree_single_index.h" -#include "kmeans_index.h" -#include "composite_index.h" -#include "linear_index.h" -#include "hierarchical_clustering_index.h" -#include "lsh_index.h" -#include "autotuned_index.h" - - -namespace cvflann -{ - -template -struct index_creator -{ - static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) - { - flann_algorithm_t index_type = get_param(params, "algorithm"); - - NNIndex* nnIndex; - switch (index_type) { - case FLANN_INDEX_LINEAR: - nnIndex = new LinearIndex(dataset, params, distance); - break; - case FLANN_INDEX_KDTREE_SINGLE: - nnIndex = new KDTreeSingleIndex(dataset, params, distance); - break; - case FLANN_INDEX_KDTREE: - nnIndex = new KDTreeIndex(dataset, params, distance); - break; - case FLANN_INDEX_KMEANS: - nnIndex = new KMeansIndex(dataset, params, distance); - break; - case FLANN_INDEX_COMPOSITE: - nnIndex = new CompositeIndex(dataset, params, distance); - break; - case FLANN_INDEX_AUTOTUNED: - nnIndex = new AutotunedIndex(dataset, params, distance); - break; - case FLANN_INDEX_HIERARCHICAL: - nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); - break; - case FLANN_INDEX_LSH: - nnIndex = new LshIndex(dataset, params, distance); - break; - default: - FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); - } - - return nnIndex; - } -}; - -template -struct index_creator -{ - static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) - { - flann_algorithm_t index_type = get_param(params, "algorithm"); - - NNIndex* nnIndex; - switch (index_type) { - case FLANN_INDEX_LINEAR: - nnIndex = new LinearIndex(dataset, params, distance); - break; - case FLANN_INDEX_KMEANS: - nnIndex = new KMeansIndex(dataset, params, distance); - break; - case FLANN_INDEX_HIERARCHICAL: - nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); - break; - case FLANN_INDEX_LSH: - nnIndex = new LshIndex(dataset, params, distance); - break; - default: - FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); - } - - return nnIndex; - } -}; - -template -struct index_creator -{ - static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) - { - flann_algorithm_t index_type = get_param(params, "algorithm"); - - NNIndex* nnIndex; - switch (index_type) { - case FLANN_INDEX_LINEAR: - nnIndex = new LinearIndex(dataset, params, distance); - break; - case FLANN_INDEX_KMEANS: - nnIndex = new KMeansIndex(dataset, params, distance); - break; - case FLANN_INDEX_HIERARCHICAL: - nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); - break; - case FLANN_INDEX_LSH: - nnIndex = new LshIndex(dataset, params, distance); - break; - default: - FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); - } - - return nnIndex; - } -}; - -template -NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance) -{ - return index_creator::create(dataset, params,distance); -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_ALL_INDICES_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + + +#ifndef OPENCV_FLANN_ALL_INDICES_H_ +#define OPENCV_FLANN_ALL_INDICES_H_ + +//! @cond IGNORED + +#include "general.h" + +#include "nn_index.h" +#include "kdtree_index.h" +#include "kdtree_single_index.h" +#include "kmeans_index.h" +#include "composite_index.h" +#include "linear_index.h" +#include "hierarchical_clustering_index.h" +#include "lsh_index.h" +#include "autotuned_index.h" + + +namespace cvflann +{ + +template +struct index_creator +{ + static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) + { + flann_algorithm_t index_type = get_param(params, "algorithm"); + + NNIndex* nnIndex; + switch (index_type) { + case FLANN_INDEX_LINEAR: + nnIndex = new LinearIndex(dataset, params, distance); + break; + case FLANN_INDEX_KDTREE_SINGLE: + nnIndex = new KDTreeSingleIndex(dataset, params, distance); + break; + case FLANN_INDEX_KDTREE: + nnIndex = new KDTreeIndex(dataset, params, distance); + break; + case FLANN_INDEX_KMEANS: + nnIndex = new KMeansIndex(dataset, params, distance); + break; + case FLANN_INDEX_COMPOSITE: + nnIndex = new CompositeIndex(dataset, params, distance); + break; + case FLANN_INDEX_AUTOTUNED: + nnIndex = new AutotunedIndex(dataset, params, distance); + break; + case FLANN_INDEX_HIERARCHICAL: + nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); + break; + case FLANN_INDEX_LSH: + nnIndex = new LshIndex(dataset, params, distance); + break; + default: + FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); + } + + return nnIndex; + } +}; + +template +struct index_creator +{ + static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) + { + flann_algorithm_t index_type = get_param(params, "algorithm"); + + NNIndex* nnIndex; + switch (index_type) { + case FLANN_INDEX_LINEAR: + nnIndex = new LinearIndex(dataset, params, distance); + break; + case FLANN_INDEX_KMEANS: + nnIndex = new KMeansIndex(dataset, params, distance); + break; + case FLANN_INDEX_HIERARCHICAL: + nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); + break; + case FLANN_INDEX_LSH: + nnIndex = new LshIndex(dataset, params, distance); + break; + default: + FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); + } + + return nnIndex; + } +}; + +template +struct index_creator +{ + static NNIndex* create(const Matrix& dataset, const IndexParams& params, const Distance& distance) + { + flann_algorithm_t index_type = get_param(params, "algorithm"); + + NNIndex* nnIndex; + switch (index_type) { + case FLANN_INDEX_LINEAR: + nnIndex = new LinearIndex(dataset, params, distance); + break; + case FLANN_INDEX_KMEANS: + nnIndex = new KMeansIndex(dataset, params, distance); + break; + case FLANN_INDEX_HIERARCHICAL: + nnIndex = new HierarchicalClusteringIndex(dataset, params, distance); + break; + case FLANN_INDEX_LSH: + nnIndex = new LshIndex(dataset, params, distance); + break; + default: + FLANN_THROW(cv::Error::StsBadArg, "Unknown index type"); + } + + return nnIndex; + } +}; + +template +NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance) +{ + return index_creator::create(dataset, params,distance); +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_ALL_INDICES_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h b/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h index 110858ef70..d5870a0181 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/allocator.h @@ -1,196 +1,196 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_ALLOCATOR_H_ -#define OPENCV_FLANN_ALLOCATOR_H_ - -//! @cond IGNORED - -#include -#include - - -namespace cvflann -{ - -/** - * Allocates (using C's malloc) a generic type T. - * - * Params: - * count = number of instances to allocate. - * Returns: pointer (of type T*) to memory buffer - */ -template -T* allocate(size_t count = 1) -{ - T* mem = (T*) ::malloc(sizeof(T)*count); - return mem; -} - - -/** - * Pooled storage allocator - * - * The following routines allow for the efficient allocation of storage in - * small chunks from a specified pool. Rather than allowing each structure - * to be freed individually, an entire pool of storage is freed at once. - * This method has two advantages over just using malloc() and free(). First, - * it is far more efficient for allocating small objects, as there is - * no overhead for remembering all the information needed to free each - * object or consolidating fragmented memory. Second, the decision about - * how long to keep an object is made at the time of allocation, and there - * is no need to track down all the objects to free them. - * - */ - -const size_t WORDSIZE=16; -const size_t BLOCKSIZE=8192; - -class PooledAllocator -{ - /* We maintain memory alignment to word boundaries by requiring that all - allocations be in multiples of the machine wordsize. */ - /* Size of machine word in bytes. Must be power of 2. */ - /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ - - - int remaining; /* Number of bytes left in current block of storage. */ - void* base; /* Pointer to base of current block of storage. */ - void* loc; /* Current location in block to next allocate memory. */ - int blocksize; - - -public: - int usedMemory; - int wastedMemory; - - /** - Default constructor. Initializes a new pool. - */ - PooledAllocator(int blockSize = BLOCKSIZE) - { - blocksize = blockSize; - remaining = 0; - base = NULL; - loc = NULL; - - usedMemory = 0; - wastedMemory = 0; - } - - /** - * Destructor. Frees all the memory allocated in this pool. - */ - ~PooledAllocator() - { - void* prev; - - while (base != NULL) { - prev = *((void**) base); /* Get pointer to prev block. */ - ::free(base); - base = prev; - } - } - - /** - * Returns a pointer to a piece of new memory of the given size in bytes - * allocated from the pool. - */ - void* allocateMemory(int size) - { - int blockSize; - - /* Round size up to a multiple of wordsize. The following expression - only works for WORDSIZE that is a power of 2, by masking last bits of - incremented size to zero. - */ - size = (size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); - - /* Check whether a new block must be allocated. Note that the first word - of a block is reserved for a pointer to the previous block. - */ - if (size > remaining) { - - wastedMemory += remaining; - - /* Allocate new storage. */ - blockSize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? - size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; - - // use the standard C malloc to allocate memory - void* m = ::malloc(blockSize); - if (!m) { - fprintf(stderr,"Failed to allocate memory.\n"); - return NULL; - } - - /* Fill first word of new block with pointer to previous block. */ - ((void**) m)[0] = base; - base = m; - - int shift = 0; - //int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); - - remaining = blockSize - sizeof(void*) - shift; - loc = ((char*)m + sizeof(void*) + shift); - } - void* rloc = loc; - loc = (char*)loc + size; - remaining -= size; - - usedMemory += size; - - return rloc; - } - - /** - * Allocates (using this pool) a generic type T. - * - * Params: - * count = number of instances to allocate. - * Returns: pointer (of type T*) to memory buffer - */ - template - T* allocate(size_t count = 1) - { - T* mem = (T*) this->allocateMemory((int)(sizeof(T)*count)); - return mem; - } - -private: - PooledAllocator(const PooledAllocator &); // copy disabled - PooledAllocator& operator=(const PooledAllocator &); // assign disabled -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_ALLOCATOR_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_ALLOCATOR_H_ +#define OPENCV_FLANN_ALLOCATOR_H_ + +//! @cond IGNORED + +#include +#include + + +namespace cvflann +{ + +/** + * Allocates (using C's malloc) a generic type T. + * + * Params: + * count = number of instances to allocate. + * Returns: pointer (of type T*) to memory buffer + */ +template +T* allocate(size_t count = 1) +{ + T* mem = (T*) ::malloc(sizeof(T)*count); + return mem; +} + + +/** + * Pooled storage allocator + * + * The following routines allow for the efficient allocation of storage in + * small chunks from a specified pool. Rather than allowing each structure + * to be freed individually, an entire pool of storage is freed at once. + * This method has two advantages over just using malloc() and free(). First, + * it is far more efficient for allocating small objects, as there is + * no overhead for remembering all the information needed to free each + * object or consolidating fragmented memory. Second, the decision about + * how long to keep an object is made at the time of allocation, and there + * is no need to track down all the objects to free them. + * + */ + +const size_t WORDSIZE=16; +const size_t BLOCKSIZE=8192; + +class PooledAllocator +{ + /* We maintain memory alignment to word boundaries by requiring that all + allocations be in multiples of the machine wordsize. */ + /* Size of machine word in bytes. Must be power of 2. */ + /* Minimum number of bytes requested at a time from the system. Must be multiple of WORDSIZE. */ + + + int remaining; /* Number of bytes left in current block of storage. */ + void* base; /* Pointer to base of current block of storage. */ + void* loc; /* Current location in block to next allocate memory. */ + int blocksize; + + +public: + int usedMemory; + int wastedMemory; + + /** + Default constructor. Initializes a new pool. + */ + PooledAllocator(int blockSize = BLOCKSIZE) + { + blocksize = blockSize; + remaining = 0; + base = NULL; + loc = NULL; + + usedMemory = 0; + wastedMemory = 0; + } + + /** + * Destructor. Frees all the memory allocated in this pool. + */ + ~PooledAllocator() + { + void* prev; + + while (base != NULL) { + prev = *((void**) base); /* Get pointer to prev block. */ + ::free(base); + base = prev; + } + } + + /** + * Returns a pointer to a piece of new memory of the given size in bytes + * allocated from the pool. + */ + void* allocateMemory(int size) + { + int blockSize; + + /* Round size up to a multiple of wordsize. The following expression + only works for WORDSIZE that is a power of 2, by masking last bits of + incremented size to zero. + */ + size = (size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); + + /* Check whether a new block must be allocated. Note that the first word + of a block is reserved for a pointer to the previous block. + */ + if (size > remaining) { + + wastedMemory += remaining; + + /* Allocate new storage. */ + blockSize = (size + sizeof(void*) + (WORDSIZE-1) > BLOCKSIZE) ? + size + sizeof(void*) + (WORDSIZE-1) : BLOCKSIZE; + + // use the standard C malloc to allocate memory + void* m = ::malloc(blockSize); + if (!m) { + fprintf(stderr,"Failed to allocate memory.\n"); + return NULL; + } + + /* Fill first word of new block with pointer to previous block. */ + ((void**) m)[0] = base; + base = m; + + int shift = 0; + //int shift = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & (WORDSIZE-1))) & (WORDSIZE-1); + + remaining = blockSize - sizeof(void*) - shift; + loc = ((char*)m + sizeof(void*) + shift); + } + void* rloc = loc; + loc = (char*)loc + size; + remaining -= size; + + usedMemory += size; + + return rloc; + } + + /** + * Allocates (using this pool) a generic type T. + * + * Params: + * count = number of instances to allocate. + * Returns: pointer (of type T*) to memory buffer + */ + template + T* allocate(size_t count = 1) + { + T* mem = (T*) this->allocateMemory((int)(sizeof(T)*count)); + return mem; + } + +private: + PooledAllocator(const PooledAllocator &); // copy disabled + PooledAllocator& operator=(const PooledAllocator &); // assign disabled +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_ALLOCATOR_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/any.h b/3rdParty/opencv-4.11.0/opencv2/flann/any.h index bc7df1039c..2228bd1cfc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/any.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/any.h @@ -1,355 +1,355 @@ -#ifndef OPENCV_FLANN_ANY_H_ -#define OPENCV_FLANN_ANY_H_ -/* - * (C) Copyright Christopher Diggins 2005-2011 - * (C) Copyright Pablo Aguilar 2005 - * (C) Copyright Kevlin Henney 2001 - * - * Distributed under the Boost Software License, Version 1.0. (See - * accompanying file LICENSE_1_0.txt or copy at - * http://www.boost.org/LICENSE_1_0.txt - * - * Adapted for FLANN by Marius Muja - */ - -//! @cond IGNORED - -#include "defines.h" -#include -#include -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/utility.hpp" - -namespace cvflann -{ - -namespace anyimpl -{ - -struct bad_any_cast : public std::exception -{ - bad_any_cast() = default; - - bad_any_cast(const char* src, const char* dst) - : message_(cv::format("cvflann::bad_any_cast(from %s to %s)", src, dst)) {} - - - const char* what() const noexcept override - { - return message_.c_str(); - } - -private: - std::string message_{"cvflann::bad_any_cast"}; -}; - -#ifndef CV_THROW_IF_TYPE_MISMATCH -#define CV_THROW_IF_TYPE_MISMATCH(src_type_info, dst_type_info) \ - if ((src_type_info) != (dst_type_info)) \ - throw cvflann::anyimpl::bad_any_cast((src_type_info).name(), \ - (dst_type_info).name()) -#endif - -struct empty_any -{ -}; - -inline std::ostream& operator <<(std::ostream& out, const empty_any&) -{ - out << "[empty_any]"; - return out; -} - -struct base_any_policy -{ - virtual void static_delete(void** x) = 0; - virtual void copy_from_value(void const* src, void** dest) = 0; - virtual void clone(void* const* src, void** dest) = 0; - virtual void move(void* const* src, void** dest) = 0; - virtual void* get_value(void** src) = 0; - virtual const void* get_value(void* const * src) = 0; - virtual ::size_t get_size() = 0; - virtual const std::type_info& type() = 0; - virtual void print(std::ostream& out, void* const* src) = 0; - virtual ~base_any_policy() {} -}; - -template -struct typed_base_any_policy : base_any_policy -{ - virtual ::size_t get_size() CV_OVERRIDE { return sizeof(T); } - virtual const std::type_info& type() CV_OVERRIDE { return typeid(T); } - -}; - -template -struct small_any_policy CV_FINAL : typed_base_any_policy -{ - virtual void static_delete(void**) CV_OVERRIDE { } - virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE - { - new (dest) T(* reinterpret_cast(src)); - } - virtual void clone(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } - virtual void move(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } - virtual void* get_value(void** src) CV_OVERRIDE { return reinterpret_cast(src); } - virtual const void* get_value(void* const * src) CV_OVERRIDE { return reinterpret_cast(src); } - virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(src); } -}; - -template -struct big_any_policy CV_FINAL : typed_base_any_policy -{ - virtual void static_delete(void** x) CV_OVERRIDE - { - if (* x) delete (* reinterpret_cast(x)); - *x = NULL; - } - virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE - { - *dest = new T(*reinterpret_cast(src)); - } - virtual void clone(void* const* src, void** dest) CV_OVERRIDE - { - *dest = new T(**reinterpret_cast(src)); - } - virtual void move(void* const* src, void** dest) CV_OVERRIDE - { - (*reinterpret_cast(dest))->~T(); - **reinterpret_cast(dest) = **reinterpret_cast(src); - } - virtual void* get_value(void** src) CV_OVERRIDE { return *src; } - virtual const void* get_value(void* const * src) CV_OVERRIDE { return *src; } - virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(*src); } -}; - -template<> inline void big_any_policy::print(std::ostream& out, void* const* src) -{ - out << int(*reinterpret_cast(*src)); -} - -template<> inline void big_any_policy::print(std::ostream& out, void* const* src) -{ - out << int(*reinterpret_cast(*src)); -} - -template<> inline void big_any_policy::print(std::ostream& out, void* const* src) -{ - out << (*reinterpret_cast(*src)).c_str(); -} - -template -struct choose_policy -{ - typedef big_any_policy type; -}; - -template -struct choose_policy -{ - typedef small_any_policy type; -}; - -struct any; - -/// Choosing the policy for an any type is illegal, but should never happen. -/// This is designed to throw a compiler error. -template<> -struct choose_policy -{ - typedef void type; -}; - -/// Specializations for small types. -#define SMALL_POLICY(TYPE) \ - template<> \ - struct choose_policy { typedef small_any_policy type; \ - } - -SMALL_POLICY(signed char); -SMALL_POLICY(unsigned char); -SMALL_POLICY(signed short); -SMALL_POLICY(unsigned short); -SMALL_POLICY(signed int); -SMALL_POLICY(unsigned int); -SMALL_POLICY(signed long); -SMALL_POLICY(unsigned long); -SMALL_POLICY(float); -SMALL_POLICY(bool); - -#undef SMALL_POLICY - -template -class SinglePolicy -{ - SinglePolicy(); - SinglePolicy(const SinglePolicy& other); - SinglePolicy& operator=(const SinglePolicy& other); - -public: - static base_any_policy* get_policy(); -}; - -/// This function will return a different policy for each type. -template -inline base_any_policy* SinglePolicy::get_policy() -{ - static typename choose_policy::type policy; - return &policy; -} - -} // namespace anyimpl - -struct any -{ -private: - // fields - anyimpl::base_any_policy* policy; - void* object; - -public: - /// Initializing constructor. - template - any(const T& x) - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { - assign(x); - } - - /// Empty constructor. - any() - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { } - - /// Special initializing constructor for string literals. - any(const char* x) - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { - assign(x); - } - - /// Copy constructor. - any(const any& x) - : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) - { - assign(x); - } - - /// Destructor. - ~any() - { - policy->static_delete(&object); - } - - /// Assignment function from another any. - any& assign(const any& x) - { - reset(); - policy = x.policy; - policy->clone(&x.object, &object); - return *this; - } - - /// Assignment function. - template - any& assign(const T& x) - { - reset(); - policy = anyimpl::SinglePolicy::get_policy(); - policy->copy_from_value(&x, &object); - return *this; - } - - /// Assignment operator. - template - any& operator=(const T& x) - { - return assign(x); - } - - /// Assignment operator. Template-based version above doesn't work as expected. We need regular assignment operator here. - any& operator=(const any& x) - { - return assign(x); - } - - /// Assignment operator, specialed for literal strings. - /// They have types like const char [6] which don't work as expected. - any& operator=(const char* x) - { - return assign(x); - } - - /// Utility functions - any& swap(any& x) - { - std::swap(policy, x.policy); - std::swap(object, x.object); - return *this; - } - - /// Cast operator. You can only cast to the original type. - template - T& cast() - { - CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); - T* r = reinterpret_cast(policy->get_value(&object)); - return *r; - } - - /// Cast operator. You can only cast to the original type. - template - const T& cast() const - { - CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); - const T* r = reinterpret_cast(policy->get_value(&object)); - return *r; - } - - /// Returns true if the any contains no value. - bool empty() const - { - return policy->type() == typeid(anyimpl::empty_any); - } - - /// Frees any allocated memory, and sets the value to NULL. - void reset() - { - policy->static_delete(&object); - policy = anyimpl::SinglePolicy::get_policy(); - } - - /// Returns true if the two types are the same. - bool compatible(const any& x) const - { - return policy->type() == x.policy->type(); - } - - /// Returns if the type is compatible with the policy - template - bool has_type() - { - return policy->type() == typeid(T); - } - - const std::type_info& type() const - { - return policy->type(); - } - - friend std::ostream& operator <<(std::ostream& out, const any& any_val); -}; - -inline std::ostream& operator <<(std::ostream& out, const any& any_val) -{ - any_val.policy->print(out,&any_val.object); - return out; -} - -} - -//! @endcond - -#endif // OPENCV_FLANN_ANY_H_ +#ifndef OPENCV_FLANN_ANY_H_ +#define OPENCV_FLANN_ANY_H_ +/* + * (C) Copyright Christopher Diggins 2005-2011 + * (C) Copyright Pablo Aguilar 2005 + * (C) Copyright Kevlin Henney 2001 + * + * Distributed under the Boost Software License, Version 1.0. (See + * accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt + * + * Adapted for FLANN by Marius Muja + */ + +//! @cond IGNORED + +#include "defines.h" +#include +#include +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/utility.hpp" + +namespace cvflann +{ + +namespace anyimpl +{ + +struct bad_any_cast : public std::exception +{ + bad_any_cast() = default; + + bad_any_cast(const char* src, const char* dst) + : message_(cv::format("cvflann::bad_any_cast(from %s to %s)", src, dst)) {} + + + const char* what() const noexcept override + { + return message_.c_str(); + } + +private: + std::string message_{"cvflann::bad_any_cast"}; +}; + +#ifndef CV_THROW_IF_TYPE_MISMATCH +#define CV_THROW_IF_TYPE_MISMATCH(src_type_info, dst_type_info) \ + if ((src_type_info) != (dst_type_info)) \ + throw cvflann::anyimpl::bad_any_cast((src_type_info).name(), \ + (dst_type_info).name()) +#endif + +struct empty_any +{ +}; + +inline std::ostream& operator <<(std::ostream& out, const empty_any&) +{ + out << "[empty_any]"; + return out; +} + +struct base_any_policy +{ + virtual void static_delete(void** x) = 0; + virtual void copy_from_value(void const* src, void** dest) = 0; + virtual void clone(void* const* src, void** dest) = 0; + virtual void move(void* const* src, void** dest) = 0; + virtual void* get_value(void** src) = 0; + virtual const void* get_value(void* const * src) = 0; + virtual ::size_t get_size() = 0; + virtual const std::type_info& type() = 0; + virtual void print(std::ostream& out, void* const* src) = 0; + virtual ~base_any_policy() {} +}; + +template +struct typed_base_any_policy : base_any_policy +{ + virtual ::size_t get_size() CV_OVERRIDE { return sizeof(T); } + virtual const std::type_info& type() CV_OVERRIDE { return typeid(T); } + +}; + +template +struct small_any_policy CV_FINAL : typed_base_any_policy +{ + virtual void static_delete(void**) CV_OVERRIDE { } + virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE + { + new (dest) T(* reinterpret_cast(src)); + } + virtual void clone(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } + virtual void move(void* const* src, void** dest) CV_OVERRIDE { *dest = *src; } + virtual void* get_value(void** src) CV_OVERRIDE { return reinterpret_cast(src); } + virtual const void* get_value(void* const * src) CV_OVERRIDE { return reinterpret_cast(src); } + virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(src); } +}; + +template +struct big_any_policy CV_FINAL : typed_base_any_policy +{ + virtual void static_delete(void** x) CV_OVERRIDE + { + if (* x) delete (* reinterpret_cast(x)); + *x = NULL; + } + virtual void copy_from_value(void const* src, void** dest) CV_OVERRIDE + { + *dest = new T(*reinterpret_cast(src)); + } + virtual void clone(void* const* src, void** dest) CV_OVERRIDE + { + *dest = new T(**reinterpret_cast(src)); + } + virtual void move(void* const* src, void** dest) CV_OVERRIDE + { + (*reinterpret_cast(dest))->~T(); + **reinterpret_cast(dest) = **reinterpret_cast(src); + } + virtual void* get_value(void** src) CV_OVERRIDE { return *src; } + virtual const void* get_value(void* const * src) CV_OVERRIDE { return *src; } + virtual void print(std::ostream& out, void* const* src) CV_OVERRIDE { out << *reinterpret_cast(*src); } +}; + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << int(*reinterpret_cast(*src)); +} + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << int(*reinterpret_cast(*src)); +} + +template<> inline void big_any_policy::print(std::ostream& out, void* const* src) +{ + out << (*reinterpret_cast(*src)).c_str(); +} + +template +struct choose_policy +{ + typedef big_any_policy type; +}; + +template +struct choose_policy +{ + typedef small_any_policy type; +}; + +struct any; + +/// Choosing the policy for an any type is illegal, but should never happen. +/// This is designed to throw a compiler error. +template<> +struct choose_policy +{ + typedef void type; +}; + +/// Specializations for small types. +#define SMALL_POLICY(TYPE) \ + template<> \ + struct choose_policy { typedef small_any_policy type; \ + } + +SMALL_POLICY(signed char); +SMALL_POLICY(unsigned char); +SMALL_POLICY(signed short); +SMALL_POLICY(unsigned short); +SMALL_POLICY(signed int); +SMALL_POLICY(unsigned int); +SMALL_POLICY(signed long); +SMALL_POLICY(unsigned long); +SMALL_POLICY(float); +SMALL_POLICY(bool); + +#undef SMALL_POLICY + +template +class SinglePolicy +{ + SinglePolicy(); + SinglePolicy(const SinglePolicy& other); + SinglePolicy& operator=(const SinglePolicy& other); + +public: + static base_any_policy* get_policy(); +}; + +/// This function will return a different policy for each type. +template +inline base_any_policy* SinglePolicy::get_policy() +{ + static typename choose_policy::type policy; + return &policy; +} + +} // namespace anyimpl + +struct any +{ +private: + // fields + anyimpl::base_any_policy* policy; + void* object; + +public: + /// Initializing constructor. + template + any(const T& x) + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { + assign(x); + } + + /// Empty constructor. + any() + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { } + + /// Special initializing constructor for string literals. + any(const char* x) + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { + assign(x); + } + + /// Copy constructor. + any(const any& x) + : policy(anyimpl::SinglePolicy::get_policy()), object(NULL) + { + assign(x); + } + + /// Destructor. + ~any() + { + policy->static_delete(&object); + } + + /// Assignment function from another any. + any& assign(const any& x) + { + reset(); + policy = x.policy; + policy->clone(&x.object, &object); + return *this; + } + + /// Assignment function. + template + any& assign(const T& x) + { + reset(); + policy = anyimpl::SinglePolicy::get_policy(); + policy->copy_from_value(&x, &object); + return *this; + } + + /// Assignment operator. + template + any& operator=(const T& x) + { + return assign(x); + } + + /// Assignment operator. Template-based version above doesn't work as expected. We need regular assignment operator here. + any& operator=(const any& x) + { + return assign(x); + } + + /// Assignment operator, specialed for literal strings. + /// They have types like const char [6] which don't work as expected. + any& operator=(const char* x) + { + return assign(x); + } + + /// Utility functions + any& swap(any& x) + { + std::swap(policy, x.policy); + std::swap(object, x.object); + return *this; + } + + /// Cast operator. You can only cast to the original type. + template + T& cast() + { + CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); + T* r = reinterpret_cast(policy->get_value(&object)); + return *r; + } + + /// Cast operator. You can only cast to the original type. + template + const T& cast() const + { + CV_THROW_IF_TYPE_MISMATCH(policy->type(), typeid(T)); + const T* r = reinterpret_cast(policy->get_value(&object)); + return *r; + } + + /// Returns true if the any contains no value. + bool empty() const + { + return policy->type() == typeid(anyimpl::empty_any); + } + + /// Frees any allocated memory, and sets the value to NULL. + void reset() + { + policy->static_delete(&object); + policy = anyimpl::SinglePolicy::get_policy(); + } + + /// Returns true if the two types are the same. + bool compatible(const any& x) const + { + return policy->type() == x.policy->type(); + } + + /// Returns if the type is compatible with the policy + template + bool has_type() + { + return policy->type() == typeid(T); + } + + const std::type_info& type() const + { + return policy->type(); + } + + friend std::ostream& operator <<(std::ostream& out, const any& any_val); +}; + +inline std::ostream& operator <<(std::ostream& out, const any& any_val) +{ + any_val.policy->print(out,&any_val.object); + return out; +} + +} + +//! @endcond + +#endif // OPENCV_FLANN_ANY_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h index 32a0ab0852..d90f739aff 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/autotuned_index.h @@ -1,594 +1,594 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ -#ifndef OPENCV_FLANN_AUTOTUNED_INDEX_H_ -#define OPENCV_FLANN_AUTOTUNED_INDEX_H_ - -//! @cond IGNORED - -#include - -#include "nn_index.h" -#include "ground_truth.h" -#include "index_testing.h" -#include "sampling.h" -#include "kdtree_index.h" -#include "kdtree_single_index.h" -#include "kmeans_index.h" -#include "composite_index.h" -#include "linear_index.h" -#include "logger.h" - -namespace cvflann -{ - -template -NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance); - - -struct AutotunedIndexParams : public IndexParams -{ - AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1) - { - (*this)["algorithm"] = FLANN_INDEX_AUTOTUNED; - // precision desired (used for autotuning, -1 otherwise) - (*this)["target_precision"] = target_precision; - // build tree time weighting factor - (*this)["build_weight"] = build_weight; - // index memory weighting factor - (*this)["memory_weight"] = memory_weight; - // what fraction of the dataset to use for autotuning - (*this)["sample_fraction"] = sample_fraction; - } -}; - - -template -class AutotunedIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - AutotunedIndex(const Matrix& inputData, const IndexParams& params = AutotunedIndexParams(), Distance d = Distance()) : - dataset_(inputData), distance_(d) - { - target_precision_ = get_param(params, "target_precision",0.8f); - build_weight_ = get_param(params,"build_weight", 0.01f); - memory_weight_ = get_param(params, "memory_weight", 0.0f); - sample_fraction_ = get_param(params,"sample_fraction", 0.1f); - bestIndex_ = NULL; - speedup_ = 0; - } - - AutotunedIndex(const AutotunedIndex&); - AutotunedIndex& operator=(const AutotunedIndex&); - - virtual ~AutotunedIndex() - { - if (bestIndex_ != NULL) { - delete bestIndex_; - bestIndex_ = NULL; - } - } - - /** - * Method responsible with building the index. - */ - virtual void buildIndex() CV_OVERRIDE - { - std::ostringstream stream; - bestParams_ = estimateBuildParams(); - print_params(bestParams_, stream); - Logger::info("----------------------------------------------------\n"); - Logger::info("Autotuned parameters:\n"); - Logger::info("%s", stream.str().c_str()); - Logger::info("----------------------------------------------------\n"); - - bestIndex_ = create_index_by_type(dataset_, bestParams_, distance_); - bestIndex_->buildIndex(); - speedup_ = estimateSearchParams(bestSearchParams_); - stream.str(std::string()); - print_params(bestSearchParams_, stream); - Logger::info("----------------------------------------------------\n"); - Logger::info("Search parameters:\n"); - Logger::info("%s", stream.str().c_str()); - Logger::info("----------------------------------------------------\n"); - } - - /** - * Saves the index to a stream - */ - virtual void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, (int)bestIndex_->getType()); - bestIndex_->saveIndex(stream); - save_value(stream, get_param(bestSearchParams_, "checks")); - } - - /** - * Loads the index from a stream - */ - virtual void loadIndex(FILE* stream) CV_OVERRIDE - { - int index_type; - - load_value(stream, index_type); - IndexParams params; - params["algorithm"] = (flann_algorithm_t)index_type; - bestIndex_ = create_index_by_type(dataset_, params, distance_); - bestIndex_->loadIndex(stream); - int checks; - load_value(stream, checks); - bestSearchParams_["checks"] = checks; - } - - /** - * Method that searches for nearest-neighbors - */ - virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - int checks = get_param(searchParams,"checks",FLANN_CHECKS_AUTOTUNED); - if (checks == FLANN_CHECKS_AUTOTUNED) { - bestIndex_->findNeighbors(result, vec, bestSearchParams_); - } - else { - bestIndex_->findNeighbors(result, vec, searchParams); - } - } - - - IndexParams getParameters() const CV_OVERRIDE - { - return bestIndex_->getParameters(); - } - - SearchParams getSearchParameters() const - { - return bestSearchParams_; - } - - float getSpeedup() const - { - return speedup_; - } - - - /** - * Number of features in this index. - */ - virtual size_t size() const CV_OVERRIDE - { - return bestIndex_->size(); - } - - /** - * The length of each vector in this index. - */ - virtual size_t veclen() const CV_OVERRIDE - { - return bestIndex_->veclen(); - } - - /** - * The amount of memory (in bytes) this index uses. - */ - virtual int usedMemory() const CV_OVERRIDE - { - return bestIndex_->usedMemory(); - } - - /** - * Algorithm name - */ - virtual flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_AUTOTUNED; - } - -private: - - struct CostData - { - float searchTimeCost; - float buildTimeCost; - float memoryCost; - float totalCost; - IndexParams params; - }; - - void evaluate_kmeans(CostData& cost) - { - StartStopTimer t; - int checks; - const int nn = 1; - - Logger::info("KMeansTree using params: max_iterations=%d, branching=%d\n", - get_param(cost.params,"iterations"), - get_param(cost.params,"branching")); - KMeansIndex kmeans(sampledDataset_, cost.params, distance_); - // measure index build time - t.start(); - kmeans.buildIndex(); - t.stop(); - float buildTime = (float)t.value; - - // measure search time - float searchTime = test_index_precision(kmeans, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); - - float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); - cost.memoryCost = (kmeans.usedMemory() + datasetMemory) / datasetMemory; - cost.searchTimeCost = searchTime; - cost.buildTimeCost = buildTime; - Logger::info("KMeansTree buildTime=%g, searchTime=%g, build_weight=%g\n", buildTime, searchTime, build_weight_); - } - - - void evaluate_kdtree(CostData& cost) - { - StartStopTimer t; - int checks; - const int nn = 1; - - Logger::info("KDTree using params: trees=%d\n", get_param(cost.params,"trees")); - KDTreeIndex kdtree(sampledDataset_, cost.params, distance_); - - t.start(); - kdtree.buildIndex(); - t.stop(); - float buildTime = (float)t.value; - - //measure search time - float searchTime = test_index_precision(kdtree, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); - - float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); - cost.memoryCost = (kdtree.usedMemory() + datasetMemory) / datasetMemory; - cost.searchTimeCost = searchTime; - cost.buildTimeCost = buildTime; - Logger::info("KDTree buildTime=%g, searchTime=%g\n", buildTime, searchTime); - } - - - // struct KMeansSimpleDownhillFunctor { - // - // Autotune& autotuner; - // KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} - // - // float operator()(int* params) { - // - // float maxFloat = numeric_limits::max(); - // - // if (params[0]<2) return maxFloat; - // if (params[1]<0) return maxFloat; - // - // CostData c; - // c.params["algorithm"] = KMEANS; - // c.params["centers-init"] = CENTERS_RANDOM; - // c.params["branching"] = params[0]; - // c.params["max-iterations"] = params[1]; - // - // autotuner.evaluate_kmeans(c); - // - // return c.timeCost; - // - // } - // }; - // - // struct KDTreeSimpleDownhillFunctor { - // - // Autotune& autotuner; - // KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} - // - // float operator()(int* params) { - // float maxFloat = numeric_limits::max(); - // - // if (params[0]<1) return maxFloat; - // - // CostData c; - // c.params["algorithm"] = KDTREE; - // c.params["trees"] = params[0]; - // - // autotuner.evaluate_kdtree(c); - // - // return c.timeCost; - // - // } - // }; - - - - void optimizeKMeans(std::vector& costs) - { - Logger::info("KMEANS, Step 1: Exploring parameter space\n"); - - // explore kmeans parameters space using combinations of the parameters below - int maxIterations[] = { 1, 5, 10, 15 }; - int branchingFactors[] = { 16, 32, 64, 128, 256 }; - - int kmeansParamSpaceSize = FLANN_ARRAY_LEN(maxIterations) * FLANN_ARRAY_LEN(branchingFactors); - costs.reserve(costs.size() + kmeansParamSpaceSize); - - // evaluate kmeans for all parameter combinations - for (size_t i = 0; i < FLANN_ARRAY_LEN(maxIterations); ++i) { - for (size_t j = 0; j < FLANN_ARRAY_LEN(branchingFactors); ++j) { - CostData cost; - cost.params["algorithm"] = FLANN_INDEX_KMEANS; - cost.params["centers_init"] = FLANN_CENTERS_RANDOM; - cost.params["iterations"] = maxIterations[i]; - cost.params["branching"] = branchingFactors[j]; - - evaluate_kmeans(cost); - costs.push_back(cost); - } - } - - // Logger::info("KMEANS, Step 2: simplex-downhill optimization\n"); - // - // const int n = 2; - // // choose initial simplex points as the best parameters so far - // int kmeansNMPoints[n*(n+1)]; - // float kmeansVals[n+1]; - // for (int i=0;i& costs) - { - Logger::info("KD-TREE, Step 1: Exploring parameter space\n"); - - // explore kd-tree parameters space using the parameters below - int testTrees[] = { 1, 4, 8, 16, 32 }; - - // evaluate kdtree for all parameter combinations - for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) { - CostData cost; - cost.params["algorithm"] = FLANN_INDEX_KDTREE; - cost.params["trees"] = testTrees[i]; - - evaluate_kdtree(cost); - costs.push_back(cost); - } - - // Logger::info("KD-TREE, Step 2: simplex-downhill optimization\n"); - // - // const int n = 1; - // // choose initial simplex points as the best parameters so far - // int kdtreeNMPoints[n*(n+1)]; - // float kdtreeVals[n+1]; - // for (int i=0;i costs; - - int sampleSize = int(sample_fraction_ * dataset_.rows); - int testSampleSize = std::min(sampleSize / 10, 1000); - - Logger::info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d, target precision: %g\n", dataset_.rows, sampleSize, testSampleSize, target_precision_); - - // For a very small dataset, it makes no sense to build any fancy index, just - // use linear search - if (testSampleSize < 10) { - Logger::info("Choosing linear, dataset too small\n"); - return LinearIndexParams(); - } - - // We use a fraction of the original dataset to speedup the autotune algorithm - sampledDataset_ = random_sample(dataset_, sampleSize); - // We use a cross-validation approach, first we sample a testset from the dataset - testDataset_ = random_sample(sampledDataset_, testSampleSize, true); - - // We compute the ground truth using linear search - Logger::info("Computing ground truth... \n"); - gt_matches_ = Matrix(new int[testDataset_.rows], testDataset_.rows, 1); - StartStopTimer t; - t.start(); - compute_ground_truth(sampledDataset_, testDataset_, gt_matches_, 0, distance_); - t.stop(); - - CostData linear_cost; - linear_cost.searchTimeCost = (float)t.value; - linear_cost.buildTimeCost = 0; - linear_cost.memoryCost = 0; - linear_cost.params["algorithm"] = FLANN_INDEX_LINEAR; - - costs.push_back(linear_cost); - - // Start parameter autotune process - Logger::info("Autotuning parameters...\n"); - - optimizeKMeans(costs); - optimizeKDTree(costs); - - float bestTimeCost = costs[0].searchTimeCost; - for (size_t i = 0; i < costs.size(); ++i) { - float timeCost = costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost; - if (timeCost < bestTimeCost) { - bestTimeCost = timeCost; - } - } - - float bestCost = costs[0].searchTimeCost / bestTimeCost; - IndexParams bestParams = costs[0].params; - if (bestTimeCost > 0) { - for (size_t i = 0; i < costs.size(); ++i) { - float crtCost = (costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost) / bestTimeCost + - memory_weight_ * costs[i].memoryCost; - if (crtCost < bestCost) { - bestCost = crtCost; - bestParams = costs[i].params; - } - } - } - - delete[] gt_matches_.data; - delete[] testDataset_.data; - delete[] sampledDataset_.data; - - return bestParams; - } - - - - /** - * Estimates the search time parameters needed to get the desired precision. - * Precondition: the index is built - * Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search. - */ - float estimateSearchParams(SearchParams& searchParams) - { - const int nn = 1; - const size_t SAMPLE_COUNT = 1000; - - CV_Assert(bestIndex_ != NULL && "Requires a valid index"); // must have a valid index - - float speedup = 0; - - int samples = (int)std::min(dataset_.rows / 10, SAMPLE_COUNT); - if (samples > 0) { - Matrix testDataset = random_sample(dataset_, samples); - - Logger::info("Computing ground truth\n"); - - // we need to compute the ground truth first - Matrix gt_matches(new int[testDataset.rows], testDataset.rows, 1); - StartStopTimer t; - t.start(); - compute_ground_truth(dataset_, testDataset, gt_matches, 1, distance_); - t.stop(); - float linear = (float)t.value; - - int checks; - Logger::info("Estimating number of checks\n"); - - float searchTime; - float cb_index; - if (bestIndex_->getType() == FLANN_INDEX_KMEANS) { - Logger::info("KMeans algorithm, estimating cluster border factor\n"); - KMeansIndex* kmeans = (KMeansIndex*)bestIndex_; - float bestSearchTime = -1; - float best_cb_index = -1; - int best_checks = -1; - for (cb_index = 0; cb_index < 1.1f; cb_index += 0.2f) { - kmeans->set_cb_index(cb_index); - searchTime = test_index_precision(*kmeans, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); - if ((searchTime < bestSearchTime) || (bestSearchTime == -1)) { - bestSearchTime = searchTime; - best_cb_index = cb_index; - best_checks = checks; - } - } - searchTime = bestSearchTime; - cb_index = best_cb_index; - checks = best_checks; - - kmeans->set_cb_index(best_cb_index); - Logger::info("Optimum cb_index: %g\n", cb_index); - bestParams_["cb_index"] = cb_index; - } - else { - searchTime = test_index_precision(*bestIndex_, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); - } - - Logger::info("Required number of checks: %d \n", checks); - searchParams["checks"] = checks; - - speedup = linear / searchTime; - - delete[] gt_matches.data; - delete[] testDataset.data; - } - - return speedup; - } - -private: - NNIndex* bestIndex_; - - IndexParams bestParams_; - SearchParams bestSearchParams_; - - Matrix sampledDataset_; - Matrix testDataset_; - Matrix gt_matches_; - - float speedup_; - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - /** - * Index parameters - */ - float target_precision_; - float build_weight_; - float memory_weight_; - float sample_fraction_; - - Distance distance_; - - -}; -} - -//! @endcond - -#endif /* OPENCV_FLANN_AUTOTUNED_INDEX_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ +#ifndef OPENCV_FLANN_AUTOTUNED_INDEX_H_ +#define OPENCV_FLANN_AUTOTUNED_INDEX_H_ + +//! @cond IGNORED + +#include + +#include "nn_index.h" +#include "ground_truth.h" +#include "index_testing.h" +#include "sampling.h" +#include "kdtree_index.h" +#include "kdtree_single_index.h" +#include "kmeans_index.h" +#include "composite_index.h" +#include "linear_index.h" +#include "logger.h" + +namespace cvflann +{ + +template +NNIndex* create_index_by_type(const Matrix& dataset, const IndexParams& params, const Distance& distance); + + +struct AutotunedIndexParams : public IndexParams +{ + AutotunedIndexParams(float target_precision = 0.8, float build_weight = 0.01, float memory_weight = 0, float sample_fraction = 0.1) + { + (*this)["algorithm"] = FLANN_INDEX_AUTOTUNED; + // precision desired (used for autotuning, -1 otherwise) + (*this)["target_precision"] = target_precision; + // build tree time weighting factor + (*this)["build_weight"] = build_weight; + // index memory weighting factor + (*this)["memory_weight"] = memory_weight; + // what fraction of the dataset to use for autotuning + (*this)["sample_fraction"] = sample_fraction; + } +}; + + +template +class AutotunedIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + AutotunedIndex(const Matrix& inputData, const IndexParams& params = AutotunedIndexParams(), Distance d = Distance()) : + dataset_(inputData), distance_(d) + { + target_precision_ = get_param(params, "target_precision",0.8f); + build_weight_ = get_param(params,"build_weight", 0.01f); + memory_weight_ = get_param(params, "memory_weight", 0.0f); + sample_fraction_ = get_param(params,"sample_fraction", 0.1f); + bestIndex_ = NULL; + speedup_ = 0; + } + + AutotunedIndex(const AutotunedIndex&); + AutotunedIndex& operator=(const AutotunedIndex&); + + virtual ~AutotunedIndex() + { + if (bestIndex_ != NULL) { + delete bestIndex_; + bestIndex_ = NULL; + } + } + + /** + * Method responsible with building the index. + */ + virtual void buildIndex() CV_OVERRIDE + { + std::ostringstream stream; + bestParams_ = estimateBuildParams(); + print_params(bestParams_, stream); + Logger::info("----------------------------------------------------\n"); + Logger::info("Autotuned parameters:\n"); + Logger::info("%s", stream.str().c_str()); + Logger::info("----------------------------------------------------\n"); + + bestIndex_ = create_index_by_type(dataset_, bestParams_, distance_); + bestIndex_->buildIndex(); + speedup_ = estimateSearchParams(bestSearchParams_); + stream.str(std::string()); + print_params(bestSearchParams_, stream); + Logger::info("----------------------------------------------------\n"); + Logger::info("Search parameters:\n"); + Logger::info("%s", stream.str().c_str()); + Logger::info("----------------------------------------------------\n"); + } + + /** + * Saves the index to a stream + */ + virtual void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, (int)bestIndex_->getType()); + bestIndex_->saveIndex(stream); + save_value(stream, get_param(bestSearchParams_, "checks")); + } + + /** + * Loads the index from a stream + */ + virtual void loadIndex(FILE* stream) CV_OVERRIDE + { + int index_type; + + load_value(stream, index_type); + IndexParams params; + params["algorithm"] = (flann_algorithm_t)index_type; + bestIndex_ = create_index_by_type(dataset_, params, distance_); + bestIndex_->loadIndex(stream); + int checks; + load_value(stream, checks); + bestSearchParams_["checks"] = checks; + } + + /** + * Method that searches for nearest-neighbors + */ + virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + int checks = get_param(searchParams,"checks",FLANN_CHECKS_AUTOTUNED); + if (checks == FLANN_CHECKS_AUTOTUNED) { + bestIndex_->findNeighbors(result, vec, bestSearchParams_); + } + else { + bestIndex_->findNeighbors(result, vec, searchParams); + } + } + + + IndexParams getParameters() const CV_OVERRIDE + { + return bestIndex_->getParameters(); + } + + SearchParams getSearchParameters() const + { + return bestSearchParams_; + } + + float getSpeedup() const + { + return speedup_; + } + + + /** + * Number of features in this index. + */ + virtual size_t size() const CV_OVERRIDE + { + return bestIndex_->size(); + } + + /** + * The length of each vector in this index. + */ + virtual size_t veclen() const CV_OVERRIDE + { + return bestIndex_->veclen(); + } + + /** + * The amount of memory (in bytes) this index uses. + */ + virtual int usedMemory() const CV_OVERRIDE + { + return bestIndex_->usedMemory(); + } + + /** + * Algorithm name + */ + virtual flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_AUTOTUNED; + } + +private: + + struct CostData + { + float searchTimeCost; + float buildTimeCost; + float memoryCost; + float totalCost; + IndexParams params; + }; + + void evaluate_kmeans(CostData& cost) + { + StartStopTimer t; + int checks; + const int nn = 1; + + Logger::info("KMeansTree using params: max_iterations=%d, branching=%d\n", + get_param(cost.params,"iterations"), + get_param(cost.params,"branching")); + KMeansIndex kmeans(sampledDataset_, cost.params, distance_); + // measure index build time + t.start(); + kmeans.buildIndex(); + t.stop(); + float buildTime = (float)t.value; + + // measure search time + float searchTime = test_index_precision(kmeans, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); + + float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); + cost.memoryCost = (kmeans.usedMemory() + datasetMemory) / datasetMemory; + cost.searchTimeCost = searchTime; + cost.buildTimeCost = buildTime; + Logger::info("KMeansTree buildTime=%g, searchTime=%g, build_weight=%g\n", buildTime, searchTime, build_weight_); + } + + + void evaluate_kdtree(CostData& cost) + { + StartStopTimer t; + int checks; + const int nn = 1; + + Logger::info("KDTree using params: trees=%d\n", get_param(cost.params,"trees")); + KDTreeIndex kdtree(sampledDataset_, cost.params, distance_); + + t.start(); + kdtree.buildIndex(); + t.stop(); + float buildTime = (float)t.value; + + //measure search time + float searchTime = test_index_precision(kdtree, sampledDataset_, testDataset_, gt_matches_, target_precision_, checks, distance_, nn); + + float datasetMemory = float(sampledDataset_.rows * sampledDataset_.cols * sizeof(float)); + cost.memoryCost = (kdtree.usedMemory() + datasetMemory) / datasetMemory; + cost.searchTimeCost = searchTime; + cost.buildTimeCost = buildTime; + Logger::info("KDTree buildTime=%g, searchTime=%g\n", buildTime, searchTime); + } + + + // struct KMeansSimpleDownhillFunctor { + // + // Autotune& autotuner; + // KMeansSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} + // + // float operator()(int* params) { + // + // float maxFloat = numeric_limits::max(); + // + // if (params[0]<2) return maxFloat; + // if (params[1]<0) return maxFloat; + // + // CostData c; + // c.params["algorithm"] = KMEANS; + // c.params["centers-init"] = CENTERS_RANDOM; + // c.params["branching"] = params[0]; + // c.params["max-iterations"] = params[1]; + // + // autotuner.evaluate_kmeans(c); + // + // return c.timeCost; + // + // } + // }; + // + // struct KDTreeSimpleDownhillFunctor { + // + // Autotune& autotuner; + // KDTreeSimpleDownhillFunctor(Autotune& autotuner_) : autotuner(autotuner_) {} + // + // float operator()(int* params) { + // float maxFloat = numeric_limits::max(); + // + // if (params[0]<1) return maxFloat; + // + // CostData c; + // c.params["algorithm"] = KDTREE; + // c.params["trees"] = params[0]; + // + // autotuner.evaluate_kdtree(c); + // + // return c.timeCost; + // + // } + // }; + + + + void optimizeKMeans(std::vector& costs) + { + Logger::info("KMEANS, Step 1: Exploring parameter space\n"); + + // explore kmeans parameters space using combinations of the parameters below + int maxIterations[] = { 1, 5, 10, 15 }; + int branchingFactors[] = { 16, 32, 64, 128, 256 }; + + int kmeansParamSpaceSize = FLANN_ARRAY_LEN(maxIterations) * FLANN_ARRAY_LEN(branchingFactors); + costs.reserve(costs.size() + kmeansParamSpaceSize); + + // evaluate kmeans for all parameter combinations + for (size_t i = 0; i < FLANN_ARRAY_LEN(maxIterations); ++i) { + for (size_t j = 0; j < FLANN_ARRAY_LEN(branchingFactors); ++j) { + CostData cost; + cost.params["algorithm"] = FLANN_INDEX_KMEANS; + cost.params["centers_init"] = FLANN_CENTERS_RANDOM; + cost.params["iterations"] = maxIterations[i]; + cost.params["branching"] = branchingFactors[j]; + + evaluate_kmeans(cost); + costs.push_back(cost); + } + } + + // Logger::info("KMEANS, Step 2: simplex-downhill optimization\n"); + // + // const int n = 2; + // // choose initial simplex points as the best parameters so far + // int kmeansNMPoints[n*(n+1)]; + // float kmeansVals[n+1]; + // for (int i=0;i& costs) + { + Logger::info("KD-TREE, Step 1: Exploring parameter space\n"); + + // explore kd-tree parameters space using the parameters below + int testTrees[] = { 1, 4, 8, 16, 32 }; + + // evaluate kdtree for all parameter combinations + for (size_t i = 0; i < FLANN_ARRAY_LEN(testTrees); ++i) { + CostData cost; + cost.params["algorithm"] = FLANN_INDEX_KDTREE; + cost.params["trees"] = testTrees[i]; + + evaluate_kdtree(cost); + costs.push_back(cost); + } + + // Logger::info("KD-TREE, Step 2: simplex-downhill optimization\n"); + // + // const int n = 1; + // // choose initial simplex points as the best parameters so far + // int kdtreeNMPoints[n*(n+1)]; + // float kdtreeVals[n+1]; + // for (int i=0;i costs; + + int sampleSize = int(sample_fraction_ * dataset_.rows); + int testSampleSize = std::min(sampleSize / 10, 1000); + + Logger::info("Entering autotuning, dataset size: %d, sampleSize: %d, testSampleSize: %d, target precision: %g\n", dataset_.rows, sampleSize, testSampleSize, target_precision_); + + // For a very small dataset, it makes no sense to build any fancy index, just + // use linear search + if (testSampleSize < 10) { + Logger::info("Choosing linear, dataset too small\n"); + return LinearIndexParams(); + } + + // We use a fraction of the original dataset to speedup the autotune algorithm + sampledDataset_ = random_sample(dataset_, sampleSize); + // We use a cross-validation approach, first we sample a testset from the dataset + testDataset_ = random_sample(sampledDataset_, testSampleSize, true); + + // We compute the ground truth using linear search + Logger::info("Computing ground truth... \n"); + gt_matches_ = Matrix(new int[testDataset_.rows], testDataset_.rows, 1); + StartStopTimer t; + t.start(); + compute_ground_truth(sampledDataset_, testDataset_, gt_matches_, 0, distance_); + t.stop(); + + CostData linear_cost; + linear_cost.searchTimeCost = (float)t.value; + linear_cost.buildTimeCost = 0; + linear_cost.memoryCost = 0; + linear_cost.params["algorithm"] = FLANN_INDEX_LINEAR; + + costs.push_back(linear_cost); + + // Start parameter autotune process + Logger::info("Autotuning parameters...\n"); + + optimizeKMeans(costs); + optimizeKDTree(costs); + + float bestTimeCost = costs[0].searchTimeCost; + for (size_t i = 0; i < costs.size(); ++i) { + float timeCost = costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost; + if (timeCost < bestTimeCost) { + bestTimeCost = timeCost; + } + } + + float bestCost = costs[0].searchTimeCost / bestTimeCost; + IndexParams bestParams = costs[0].params; + if (bestTimeCost > 0) { + for (size_t i = 0; i < costs.size(); ++i) { + float crtCost = (costs[i].buildTimeCost * build_weight_ + costs[i].searchTimeCost) / bestTimeCost + + memory_weight_ * costs[i].memoryCost; + if (crtCost < bestCost) { + bestCost = crtCost; + bestParams = costs[i].params; + } + } + } + + delete[] gt_matches_.data; + delete[] testDataset_.data; + delete[] sampledDataset_.data; + + return bestParams; + } + + + + /** + * Estimates the search time parameters needed to get the desired precision. + * Precondition: the index is built + * Postcondition: the searchParams will have the optimum params set, also the speedup obtained over linear search. + */ + float estimateSearchParams(SearchParams& searchParams) + { + const int nn = 1; + const size_t SAMPLE_COUNT = 1000; + + CV_Assert(bestIndex_ != NULL && "Requires a valid index"); // must have a valid index + + float speedup = 0; + + int samples = (int)std::min(dataset_.rows / 10, SAMPLE_COUNT); + if (samples > 0) { + Matrix testDataset = random_sample(dataset_, samples); + + Logger::info("Computing ground truth\n"); + + // we need to compute the ground truth first + Matrix gt_matches(new int[testDataset.rows], testDataset.rows, 1); + StartStopTimer t; + t.start(); + compute_ground_truth(dataset_, testDataset, gt_matches, 1, distance_); + t.stop(); + float linear = (float)t.value; + + int checks; + Logger::info("Estimating number of checks\n"); + + float searchTime; + float cb_index; + if (bestIndex_->getType() == FLANN_INDEX_KMEANS) { + Logger::info("KMeans algorithm, estimating cluster border factor\n"); + KMeansIndex* kmeans = (KMeansIndex*)bestIndex_; + float bestSearchTime = -1; + float best_cb_index = -1; + int best_checks = -1; + for (cb_index = 0; cb_index < 1.1f; cb_index += 0.2f) { + kmeans->set_cb_index(cb_index); + searchTime = test_index_precision(*kmeans, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); + if ((searchTime < bestSearchTime) || (bestSearchTime == -1)) { + bestSearchTime = searchTime; + best_cb_index = cb_index; + best_checks = checks; + } + } + searchTime = bestSearchTime; + cb_index = best_cb_index; + checks = best_checks; + + kmeans->set_cb_index(best_cb_index); + Logger::info("Optimum cb_index: %g\n", cb_index); + bestParams_["cb_index"] = cb_index; + } + else { + searchTime = test_index_precision(*bestIndex_, dataset_, testDataset, gt_matches, target_precision_, checks, distance_, nn, 1); + } + + Logger::info("Required number of checks: %d \n", checks); + searchParams["checks"] = checks; + + speedup = linear / searchTime; + + delete[] gt_matches.data; + delete[] testDataset.data; + } + + return speedup; + } + +private: + NNIndex* bestIndex_; + + IndexParams bestParams_; + SearchParams bestSearchParams_; + + Matrix sampledDataset_; + Matrix testDataset_; + Matrix gt_matches_; + + float speedup_; + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + /** + * Index parameters + */ + float target_precision_; + float build_weight_; + float memory_weight_; + float sample_fraction_; + + Distance distance_; + + +}; +} + +//! @endcond + +#endif /* OPENCV_FLANN_AUTOTUNED_INDEX_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h index 1edaf557a3..37a6223f88 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/composite_index.h @@ -1,196 +1,196 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_COMPOSITE_INDEX_H_ -#define OPENCV_FLANN_COMPOSITE_INDEX_H_ - -//! @cond IGNORED - -#include "nn_index.h" -#include "kdtree_index.h" -#include "kmeans_index.h" - -namespace cvflann -{ - -/** - * Index parameters for the CompositeIndex. - */ -struct CompositeIndexParams : public IndexParams -{ - CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, - flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 ) - { - (*this)["algorithm"] = FLANN_INDEX_KMEANS; - // number of randomized trees to use (for kdtree) - (*this)["trees"] = trees; - // branching factor - (*this)["branching"] = branching; - // max iterations to perform in one kmeans clustering (kmeans tree) - (*this)["iterations"] = iterations; - // algorithm used for picking the initial cluster centers for kmeans tree - (*this)["centers_init"] = centers_init; - // cluster boundary index. Used when searching the kmeans tree - (*this)["cb_index"] = cb_index; - } -}; - - -/** - * This index builds a kd-tree index and a k-means index and performs nearest - * neighbour search both indexes. This gives a slight boost in search performance - * as some of the neighbours that are missed by one index are found by the other. - */ -template -class CompositeIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - /** - * Index constructor - * @param inputData dataset containing the points to index - * @param params Index parameters - * @param d Distance functor - */ - CompositeIndex(const Matrix& inputData, const IndexParams& params = CompositeIndexParams(), - Distance d = Distance()) : index_params_(params) - { - kdtree_index_ = new KDTreeIndex(inputData, params, d); - kmeans_index_ = new KMeansIndex(inputData, params, d); - - } - - CompositeIndex(const CompositeIndex&); - CompositeIndex& operator=(const CompositeIndex&); - - virtual ~CompositeIndex() - { - delete kdtree_index_; - delete kmeans_index_; - } - - /** - * @return The index type - */ - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_COMPOSITE; - } - - /** - * @return Size of the index - */ - size_t size() const CV_OVERRIDE - { - return kdtree_index_->size(); - } - - /** - * \returns The dimensionality of the features in this index. - */ - size_t veclen() const CV_OVERRIDE - { - return kdtree_index_->veclen(); - } - - /** - * \returns The amount of memory (in bytes) used by the index. - */ - int usedMemory() const CV_OVERRIDE - { - return kmeans_index_->usedMemory() + kdtree_index_->usedMemory(); - } - - /** - * \brief Builds the index - */ - void buildIndex() CV_OVERRIDE - { - Logger::info("Building kmeans tree...\n"); - kmeans_index_->buildIndex(); - Logger::info("Building kdtree tree...\n"); - kdtree_index_->buildIndex(); - } - - /** - * \brief Saves the index to a stream - * \param stream The stream to save the index to - */ - void saveIndex(FILE* stream) CV_OVERRIDE - { - kmeans_index_->saveIndex(stream); - kdtree_index_->saveIndex(stream); - } - - /** - * \brief Loads the index from a stream - * \param stream The stream from which the index is loaded - */ - void loadIndex(FILE* stream) CV_OVERRIDE - { - kmeans_index_->loadIndex(stream); - kdtree_index_->loadIndex(stream); - } - - /** - * \returns The index parameters - */ - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - - /** - * \brief Method that searches for nearest-neighbours - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - kmeans_index_->findNeighbors(result, vec, searchParams); - kdtree_index_->findNeighbors(result, vec, searchParams); - } - -private: - /** The k-means index */ - KMeansIndex* kmeans_index_; - - /** The kd-tree index */ - KDTreeIndex* kdtree_index_; - - /** The index parameters */ - const IndexParams index_params_; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_COMPOSITE_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_COMPOSITE_INDEX_H_ +#define OPENCV_FLANN_COMPOSITE_INDEX_H_ + +//! @cond IGNORED + +#include "nn_index.h" +#include "kdtree_index.h" +#include "kmeans_index.h" + +namespace cvflann +{ + +/** + * Index parameters for the CompositeIndex. + */ +struct CompositeIndexParams : public IndexParams +{ + CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, + flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, float cb_index = 0.2 ) + { + (*this)["algorithm"] = FLANN_INDEX_KMEANS; + // number of randomized trees to use (for kdtree) + (*this)["trees"] = trees; + // branching factor + (*this)["branching"] = branching; + // max iterations to perform in one kmeans clustering (kmeans tree) + (*this)["iterations"] = iterations; + // algorithm used for picking the initial cluster centers for kmeans tree + (*this)["centers_init"] = centers_init; + // cluster boundary index. Used when searching the kmeans tree + (*this)["cb_index"] = cb_index; + } +}; + + +/** + * This index builds a kd-tree index and a k-means index and performs nearest + * neighbour search both indexes. This gives a slight boost in search performance + * as some of the neighbours that are missed by one index are found by the other. + */ +template +class CompositeIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + /** + * Index constructor + * @param inputData dataset containing the points to index + * @param params Index parameters + * @param d Distance functor + */ + CompositeIndex(const Matrix& inputData, const IndexParams& params = CompositeIndexParams(), + Distance d = Distance()) : index_params_(params) + { + kdtree_index_ = new KDTreeIndex(inputData, params, d); + kmeans_index_ = new KMeansIndex(inputData, params, d); + + } + + CompositeIndex(const CompositeIndex&); + CompositeIndex& operator=(const CompositeIndex&); + + virtual ~CompositeIndex() + { + delete kdtree_index_; + delete kmeans_index_; + } + + /** + * @return The index type + */ + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_COMPOSITE; + } + + /** + * @return Size of the index + */ + size_t size() const CV_OVERRIDE + { + return kdtree_index_->size(); + } + + /** + * \returns The dimensionality of the features in this index. + */ + size_t veclen() const CV_OVERRIDE + { + return kdtree_index_->veclen(); + } + + /** + * \returns The amount of memory (in bytes) used by the index. + */ + int usedMemory() const CV_OVERRIDE + { + return kmeans_index_->usedMemory() + kdtree_index_->usedMemory(); + } + + /** + * \brief Builds the index + */ + void buildIndex() CV_OVERRIDE + { + Logger::info("Building kmeans tree...\n"); + kmeans_index_->buildIndex(); + Logger::info("Building kdtree tree...\n"); + kdtree_index_->buildIndex(); + } + + /** + * \brief Saves the index to a stream + * \param stream The stream to save the index to + */ + void saveIndex(FILE* stream) CV_OVERRIDE + { + kmeans_index_->saveIndex(stream); + kdtree_index_->saveIndex(stream); + } + + /** + * \brief Loads the index from a stream + * \param stream The stream from which the index is loaded + */ + void loadIndex(FILE* stream) CV_OVERRIDE + { + kmeans_index_->loadIndex(stream); + kdtree_index_->loadIndex(stream); + } + + /** + * \returns The index parameters + */ + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + + /** + * \brief Method that searches for nearest-neighbours + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + kmeans_index_->findNeighbors(result, vec, searchParams); + kdtree_index_->findNeighbors(result, vec, searchParams); + } + +private: + /** The k-means index */ + KMeansIndex* kmeans_index_; + + /** The kd-tree index */ + KDTreeIndex* kdtree_index_; + + /** The index parameters */ + const IndexParams index_params_; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_COMPOSITE_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/config.h b/3rdParty/opencv-4.11.0/opencv2/flann/config.h index fd08448a29..c9342c00c3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/config.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/config.h @@ -1,42 +1,42 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - - -#ifndef OPENCV_FLANN_CONFIG_H_ -#define OPENCV_FLANN_CONFIG_H_ - -//! @cond IGNORED - -#ifdef FLANN_VERSION_ -#undef FLANN_VERSION_ -#endif -#define FLANN_VERSION_ "1.6.10" - -//! @endcond - -#endif /* OPENCV_FLANN_CONFIG_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + + +#ifndef OPENCV_FLANN_CONFIG_H_ +#define OPENCV_FLANN_CONFIG_H_ + +//! @cond IGNORED + +#ifdef FLANN_VERSION_ +#undef FLANN_VERSION_ +#endif +#define FLANN_VERSION_ "1.6.10" + +//! @endcond + +#endif /* OPENCV_FLANN_CONFIG_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/defines.h b/3rdParty/opencv-4.11.0/opencv2/flann/defines.h index 9669aa56d9..8ab83293ff 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/defines.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/defines.h @@ -1,169 +1,169 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - - -#ifndef OPENCV_FLANN_DEFINES_H_ -#define OPENCV_FLANN_DEFINES_H_ - -//! @cond IGNORED - -#include "config.h" - -#ifdef FLANN_EXPORT -#undef FLANN_EXPORT -#endif -#ifdef _WIN32 -/* win32 dll export/import directives */ - #ifdef FLANN_EXPORTS - #define FLANN_EXPORT __declspec(dllexport) - #elif defined(FLANN_STATIC) - #define FLANN_EXPORT - #else - #define FLANN_EXPORT __declspec(dllimport) - #endif -#else -/* unix needs nothing */ - #define FLANN_EXPORT -#endif - - -#undef FLANN_PLATFORM_32_BIT -#undef FLANN_PLATFORM_64_BIT -#if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64 -#define FLANN_PLATFORM_64_BIT -#else -#define FLANN_PLATFORM_32_BIT -#endif - - -#undef FLANN_ARRAY_LEN -#define FLANN_ARRAY_LEN(a) (sizeof(a)/sizeof(a[0])) - -namespace cvflann { - -/* Nearest neighbour index algorithms */ -enum flann_algorithm_t -{ - FLANN_INDEX_LINEAR = 0, - FLANN_INDEX_KDTREE = 1, - FLANN_INDEX_KMEANS = 2, - FLANN_INDEX_COMPOSITE = 3, - FLANN_INDEX_KDTREE_SINGLE = 4, - FLANN_INDEX_HIERARCHICAL = 5, - FLANN_INDEX_LSH = 6, - FLANN_INDEX_SAVED = 254, - FLANN_INDEX_AUTOTUNED = 255, - - // deprecated constants, should use the FLANN_INDEX_* ones instead - LINEAR = 0, - KDTREE = 1, - KMEANS = 2, - COMPOSITE = 3, - KDTREE_SINGLE = 4, - SAVED = 254, - AUTOTUNED = 255 -}; - - - -enum flann_centers_init_t -{ - FLANN_CENTERS_RANDOM = 0, - FLANN_CENTERS_GONZALES = 1, - FLANN_CENTERS_KMEANSPP = 2, - FLANN_CENTERS_GROUPWISE = 3, - - // deprecated constants, should use the FLANN_CENTERS_* ones instead - CENTERS_RANDOM = 0, - CENTERS_GONZALES = 1, - CENTERS_KMEANSPP = 2 -}; - -enum flann_log_level_t -{ - FLANN_LOG_NONE = 0, - FLANN_LOG_FATAL = 1, - FLANN_LOG_ERROR = 2, - FLANN_LOG_WARN = 3, - FLANN_LOG_INFO = 4 -}; - -enum flann_distance_t -{ - FLANN_DIST_EUCLIDEAN = 1, - FLANN_DIST_L2 = 1, - FLANN_DIST_MANHATTAN = 2, - FLANN_DIST_L1 = 2, - FLANN_DIST_MINKOWSKI = 3, - FLANN_DIST_MAX = 4, - FLANN_DIST_HIST_INTERSECT = 5, - FLANN_DIST_HELLINGER = 6, - FLANN_DIST_CHI_SQUARE = 7, - FLANN_DIST_CS = 7, - FLANN_DIST_KULLBACK_LEIBLER = 8, - FLANN_DIST_KL = 8, - FLANN_DIST_HAMMING = 9, - FLANN_DIST_DNAMMING = 10, - - // deprecated constants, should use the FLANN_DIST_* ones instead - EUCLIDEAN = 1, - MANHATTAN = 2, - MINKOWSKI = 3, - MAX_DIST = 4, - HIST_INTERSECT = 5, - HELLINGER = 6, - CS = 7, - KL = 8, - KULLBACK_LEIBLER = 8 -}; - -enum flann_datatype_t -{ - FLANN_INT8 = 0, - FLANN_INT16 = 1, - FLANN_INT32 = 2, - FLANN_INT64 = 3, - FLANN_UINT8 = 4, - FLANN_UINT16 = 5, - FLANN_UINT32 = 6, - FLANN_UINT64 = 7, - FLANN_FLOAT32 = 8, - FLANN_FLOAT64 = 9 -}; - -enum -{ - FLANN_CHECKS_UNLIMITED = -1, - FLANN_CHECKS_AUTOTUNED = -2 -}; - -} - -//! @endcond - -#endif /* OPENCV_FLANN_DEFINES_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + + +#ifndef OPENCV_FLANN_DEFINES_H_ +#define OPENCV_FLANN_DEFINES_H_ + +//! @cond IGNORED + +#include "config.h" + +#ifdef FLANN_EXPORT +#undef FLANN_EXPORT +#endif +#ifdef _WIN32 +/* win32 dll export/import directives */ + #ifdef FLANN_EXPORTS + #define FLANN_EXPORT __declspec(dllexport) + #elif defined(FLANN_STATIC) + #define FLANN_EXPORT + #else + #define FLANN_EXPORT __declspec(dllimport) + #endif +#else +/* unix needs nothing */ + #define FLANN_EXPORT +#endif + + +#undef FLANN_PLATFORM_32_BIT +#undef FLANN_PLATFORM_64_BIT +#if defined __amd64__ || defined __x86_64__ || defined _WIN64 || defined _M_X64 +#define FLANN_PLATFORM_64_BIT +#else +#define FLANN_PLATFORM_32_BIT +#endif + + +#undef FLANN_ARRAY_LEN +#define FLANN_ARRAY_LEN(a) (sizeof(a)/sizeof(a[0])) + +namespace cvflann { + +/* Nearest neighbour index algorithms */ +enum flann_algorithm_t +{ + FLANN_INDEX_LINEAR = 0, + FLANN_INDEX_KDTREE = 1, + FLANN_INDEX_KMEANS = 2, + FLANN_INDEX_COMPOSITE = 3, + FLANN_INDEX_KDTREE_SINGLE = 4, + FLANN_INDEX_HIERARCHICAL = 5, + FLANN_INDEX_LSH = 6, + FLANN_INDEX_SAVED = 254, + FLANN_INDEX_AUTOTUNED = 255, + + // deprecated constants, should use the FLANN_INDEX_* ones instead + LINEAR = 0, + KDTREE = 1, + KMEANS = 2, + COMPOSITE = 3, + KDTREE_SINGLE = 4, + SAVED = 254, + AUTOTUNED = 255 +}; + + + +enum flann_centers_init_t +{ + FLANN_CENTERS_RANDOM = 0, + FLANN_CENTERS_GONZALES = 1, + FLANN_CENTERS_KMEANSPP = 2, + FLANN_CENTERS_GROUPWISE = 3, + + // deprecated constants, should use the FLANN_CENTERS_* ones instead + CENTERS_RANDOM = 0, + CENTERS_GONZALES = 1, + CENTERS_KMEANSPP = 2 +}; + +enum flann_log_level_t +{ + FLANN_LOG_NONE = 0, + FLANN_LOG_FATAL = 1, + FLANN_LOG_ERROR = 2, + FLANN_LOG_WARN = 3, + FLANN_LOG_INFO = 4 +}; + +enum flann_distance_t +{ + FLANN_DIST_EUCLIDEAN = 1, + FLANN_DIST_L2 = 1, + FLANN_DIST_MANHATTAN = 2, + FLANN_DIST_L1 = 2, + FLANN_DIST_MINKOWSKI = 3, + FLANN_DIST_MAX = 4, + FLANN_DIST_HIST_INTERSECT = 5, + FLANN_DIST_HELLINGER = 6, + FLANN_DIST_CHI_SQUARE = 7, + FLANN_DIST_CS = 7, + FLANN_DIST_KULLBACK_LEIBLER = 8, + FLANN_DIST_KL = 8, + FLANN_DIST_HAMMING = 9, + FLANN_DIST_DNAMMING = 10, + + // deprecated constants, should use the FLANN_DIST_* ones instead + EUCLIDEAN = 1, + MANHATTAN = 2, + MINKOWSKI = 3, + MAX_DIST = 4, + HIST_INTERSECT = 5, + HELLINGER = 6, + CS = 7, + KL = 8, + KULLBACK_LEIBLER = 8 +}; + +enum flann_datatype_t +{ + FLANN_INT8 = 0, + FLANN_INT16 = 1, + FLANN_INT32 = 2, + FLANN_INT64 = 3, + FLANN_UINT8 = 4, + FLANN_UINT16 = 5, + FLANN_UINT32 = 6, + FLANN_UINT64 = 7, + FLANN_FLOAT32 = 8, + FLANN_FLOAT64 = 9 +}; + +enum +{ + FLANN_CHECKS_UNLIMITED = -1, + FLANN_CHECKS_AUTOTUNED = -2 +}; + +} + +//! @endcond + +#endif /* OPENCV_FLANN_DEFINES_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/dist.h b/3rdParty/opencv-4.11.0/opencv2/flann/dist.h index d78c3ff65c..3029ebb5ef 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/dist.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/dist.h @@ -1,1292 +1,1292 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_DIST_H_ -#define OPENCV_FLANN_DIST_H_ - -//! @cond IGNORED - -#include -#include -#include -#ifdef _MSC_VER -typedef unsigned __int32 uint32_t; -typedef unsigned __int64 uint64_t; -#else -#include -#endif - -#include "defines.h" - -#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) -# include -#endif - -#if defined(__ARM_NEON) && !defined(__CUDACC__) -# include "arm_neon.h" -#endif - -namespace cvflann -{ - -template -inline T abs(T x) { return (x<0) ? -x : x; } - -template<> -inline int abs(int x) { return ::abs(x); } - -template<> -inline float abs(float x) { return fabsf(x); } - -template<> -inline double abs(double x) { return fabs(x); } - - -template -inline TargetType round(float x) { return static_cast(x); } - -template<> -inline unsigned int round(float x) { return static_cast(x + 0.5f); } - -template<> -inline unsigned short round(float x) { return static_cast(x + 0.5f); } - -template<> -inline unsigned char round(float x) { return static_cast(x + 0.5f); } - -template<> -inline long long round(float x) { return static_cast(x + 0.5f); } - -template<> -inline long round(float x) { return static_cast(x + 0.5f); } - -template<> -inline int round(float x) { return static_cast(x + 0.5f) - (x<0); } - -template<> -inline short round(float x) { return static_cast(x + 0.5f) - (x<0); } - -template<> -inline char round(float x) { return static_cast(x + 0.5f) - (x<0); } - - -template -inline TargetType round(double x) { return static_cast(x); } - -template<> -inline unsigned int round(double x) { return static_cast(x + 0.5); } - -template<> -inline unsigned short round(double x) { return static_cast(x + 0.5); } - -template<> -inline unsigned char round(double x) { return static_cast(x + 0.5); } - -template<> -inline long long round(double x) { return static_cast(x + 0.5); } - -template<> -inline long round(double x) { return static_cast(x + 0.5); } - -template<> -inline int round(double x) { return static_cast(x + 0.5) - (x<0); } - -template<> -inline short round(double x) { return static_cast(x + 0.5) - (x<0); } - -template<> -inline char round(double x) { return static_cast(x + 0.5) - (x<0); } - - -template -struct Accumulator { typedef T Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; -template<> -struct Accumulator { typedef float Type; }; - -#undef True -#undef False - -class True -{ -public: - static const bool val = true; -}; - -class False -{ -public: - static const bool val = false; -}; - - -/* - * This is a "zero iterator". It basically behaves like a zero filled - * array to all algorithms that use arrays as iterators (STL style). - * It's useful when there's a need to compute the distance between feature - * and origin it and allows for better compiler optimisation than using a - * zero-filled array. - */ -template -struct ZeroIterator -{ - - T operator*() - { - return 0; - } - - T operator[](int) - { - return 0; - } - - const ZeroIterator& operator ++() - { - return *this; - } - - ZeroIterator operator ++(int) - { - return *this; - } - - ZeroIterator& operator+=(int) - { - return *this; - } - -}; - - - -/** - * Squared Euclidean distance functor. - * - * This is the simpler, unrolled version. This is preferable for - * very low dimensionality data (eg 3D points) - */ -template -struct L2_Simple -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - ResultType result = ResultType(); - ResultType diff; - for(size_t i = 0; i < size; ++i ) { - diff = (ResultType)(*a++ - *b++); - result += diff*diff; - } - return result; - } - - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return (a-b)*(a-b); - } -}; - - - -/** - * Squared Euclidean distance functor, optimized version - */ -template -struct L2 -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the squared Euclidean distance between two vectors. - * - * This is highly optimised, with loop unrolling, as it is one - * of the most expensive inner loops. - * - * The computation of squared root at the end is omitted for - * efficiency. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = (ResultType)(a[0] - b[0]); - diff1 = (ResultType)(a[1] - b[1]); - diff2 = (ResultType)(a[2] - b[2]); - diff3 = (ResultType)(a[3] - b[3]); - result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = (ResultType)(*a++ - *b++); - result += diff0 * diff0; - } - return result; - } - - /** - * Partial euclidean distance, using just one dimension. This is used by the - * kd-tree when computing partial distances while traversing the tree. - * - * Squared root is omitted for efficiency. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return (a-b)*(a-b); - } -}; - - -/* - * Manhattan distance functor, optimized version - */ -template -struct L1 -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the Manhattan (L_1) distance between two vectors. - * - * This is highly optimised, with loop unrolling, as it is one - * of the most expensive inner loops. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = (ResultType)abs(a[0] - b[0]); - diff1 = (ResultType)abs(a[1] - b[1]); - diff2 = (ResultType)abs(a[2] - b[2]); - diff3 = (ResultType)abs(a[3] - b[3]); - result += diff0 + diff1 + diff2 + diff3; - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = (ResultType)abs(*a++ - *b++); - result += diff0; - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return abs(a-b); - } -}; - - - -template -struct MinkowskiDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - int order; - - MinkowskiDistance(int order_) : order(order_) {} - - /** - * Compute the Minkowski (L_p) distance between two vectors. - * - * This is highly optimised, with loop unrolling, as it is one - * of the most expensive inner loops. - * - * The computation of squared root at the end is omitted for - * efficiency. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = (ResultType)abs(a[0] - b[0]); - diff1 = (ResultType)abs(a[1] - b[1]); - diff2 = (ResultType)abs(a[2] - b[2]); - diff3 = (ResultType)abs(a[3] - b[3]); - result += pow(diff0,order) + pow(diff1,order) + pow(diff2,order) + pow(diff3,order); - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = (ResultType)abs(*a++ - *b++); - result += pow(diff0,order); - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return pow(static_cast(abs(a-b)),order); - } -}; - - - -template -struct MaxDistance -{ - typedef False is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the max distance (L_infinity) between two vectors. - * - * This distance is not a valid kdtree distance, it's not dimensionwise additive. - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = abs(a[0] - b[0]); - diff1 = abs(a[1] - b[1]); - diff2 = abs(a[2] - b[2]); - diff3 = abs(a[3] - b[3]); - if (diff0>result) {result = diff0; } - if (diff1>result) {result = diff1; } - if (diff2>result) {result = diff2; } - if (diff3>result) {result = diff3; } - a += 4; - b += 4; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - diff0 = abs(*a++ - *b++); - result = (diff0>result) ? diff0 : result; - } - return result; - } - - /* This distance functor is not dimension-wise additive, which - * makes it an invalid kd-tree distance, not implementing the accum_dist method */ - -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** - * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor - * bit count of A exclusive XOR'ed with B - */ -struct HammingLUT -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef unsigned char ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** this will count the bits in a ^ b - */ - template - ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const - { - static const uchar popCountTable[] = - { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 - }; - ResultType result = 0; - const unsigned char* b2 = reinterpret_cast (b); - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i] ^ b2[i]]; - } - return result; - } - - - ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const - { - (void)b; - static const uchar popCountTable[] = - { - 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, - 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 - }; - ResultType result = 0; - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i]]; - } - return result; - } -}; - -/** - * Hamming distance functor (pop count between two binary vectors, i.e. xor them and count the number of bits set) - * That code was taken from brief.cpp in OpenCV - */ -template -struct Hamming -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - - typedef T ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - template - ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - ResultType result = 0; -#if defined(__ARM_NEON) && !defined(__CUDACC__) - { - const unsigned char* a2 = reinterpret_cast (a); - const unsigned char* b2 = reinterpret_cast (b); - uint32x4_t bits = vmovq_n_u32(0); - for (size_t i = 0; i < size; i += 16) { - uint8x16_t A_vec = vld1q_u8 (a2 + i); - uint8x16_t B_vec = vld1q_u8 (b2 + i); - uint8x16_t AxorB = veorq_u8 (A_vec, B_vec); - uint8x16_t bitsSet = vcntq_u8 (AxorB); - uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); - uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); - bits = vaddq_u32(bits, bitSet4); - } - uint64x2_t bitSet2 = vpaddlq_u32 (bits); - result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); - result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); - } -#elif defined(__GNUC__) - { - //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) - typedef unsigned long long pop_t; - const size_t modulo = size % sizeof(pop_t); - const pop_t* a2 = reinterpret_cast (a); - const pop_t* b2 = reinterpret_cast (b); - const pop_t* a2_end = a2 + (size / sizeof(pop_t)); - - for (; a2 != a2_end; ++a2, ++b2) result += __builtin_popcountll((*a2) ^ (*b2)); - - if (modulo) { - //in the case where size is not dividable by sizeof(size_t) - //need to mask off the bits at the end - pop_t a_final = 0, b_final = 0; - memcpy(&a_final, a2, modulo); - memcpy(&b_final, b2, modulo); - result += __builtin_popcountll(a_final ^ b_final); - } - } -#else // NO NEON and NOT GNUC - HammingLUT lut; - result = lut(reinterpret_cast (a), - reinterpret_cast (b), size); -#endif - return result; - } - - - template - ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const - { - (void)b; - ResultType result = 0; -#if defined(__ARM_NEON) && !defined(__CUDACC__) - { - const unsigned char* a2 = reinterpret_cast (a); - uint32x4_t bits = vmovq_n_u32(0); - for (size_t i = 0; i < size; i += 16) { - uint8x16_t A_vec = vld1q_u8 (a2 + i); - uint8x16_t bitsSet = vcntq_u8 (A_vec); - uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); - uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); - bits = vaddq_u32(bits, bitSet4); - } - uint64x2_t bitSet2 = vpaddlq_u32 (bits); - result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); - result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); - } -#elif defined(__GNUC__) - { - //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) - typedef unsigned long long pop_t; - const size_t modulo = size % sizeof(pop_t); - const pop_t* a2 = reinterpret_cast (a); - const pop_t* a2_end = a2 + (size / sizeof(pop_t)); - - for (; a2 != a2_end; ++a2) result += __builtin_popcountll(*a2); - - if (modulo) { - //in the case where size is not dividable by sizeof(size_t) - //need to mask off the bits at the end - pop_t a_final = 0; - memcpy(&a_final, a2, modulo); - result += __builtin_popcountll(a_final); - } - } -#else // NO NEON and NOT GNUC - HammingLUT lut; - result = lut(reinterpret_cast (a), b, size); -#endif - return result; - } -}; - -template -struct Hamming2 -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef T ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** This is popcount_3() from: - * http://en.wikipedia.org/wiki/Hamming_weight */ - unsigned int popcnt32(uint32_t n) const - { - n -= ((n >> 1) & 0x55555555); - n = (n & 0x33333333) + ((n >> 2) & 0x33333333); - return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24; - } - -#ifdef FLANN_PLATFORM_64_BIT - unsigned int popcnt64(uint64_t n) const - { - n -= ((n >> 1) & 0x5555555555555555); - n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); - return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; - } -#endif - - template - ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - const uint64_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa ^ *pb); - ++pa; - ++pb; - } -#else - const uint32_t* pa = reinterpret_cast(a); - const uint32_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa ^ *pb); - ++pa; - ++pb; - } -#endif - return result; - } - - - template - ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - - (void)b; -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa); - ++pa; - } -#else - const uint32_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa); - ++pa; - } -#endif - return result; - } - -private: -#ifdef FLANN_PLATFORM_64_BIT - static const size_t long_word_size_ = sizeof(uint64_t)/sizeof(unsigned char); -#else - static const size_t long_word_size_ = sizeof(uint32_t)/sizeof(unsigned char); -#endif -}; - - - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -struct DNAmmingLUT -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef unsigned char ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** this will count the bits in a ^ b - */ - template - ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const - { - static const uchar popCountTable[] = - { - 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 - }; - ResultType result = 0; - const unsigned char* b2 = reinterpret_cast (b); - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i] ^ b2[i]]; - } - return result; - } - - - ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const - { - (void)b; - static const uchar popCountTable[] = - { - 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, - 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 - }; - ResultType result = 0; - for (size_t i = 0; i < size; i++) { - result += popCountTable[a[i]]; - } - return result; - } -}; - - -template -struct DNAmming2 -{ - typedef False is_kdtree_distance; - typedef False is_vector_space_distance; - - typedef T ElementType; - typedef int ResultType; - typedef ElementType CentersType; - - /** This is popcount_3() from: - * http://en.wikipedia.org/wiki/Hamming_weight */ - unsigned int popcnt32(uint32_t n) const - { - n = ((n >> 1) | n) & 0x55555555; - n = (n & 0x33333333) + ((n >> 2) & 0x33333333); - return (((n + (n >> 4))& 0x0F0F0F0F)* 0x01010101) >> 24; - } - -#ifdef FLANN_PLATFORM_64_BIT - unsigned int popcnt64(uint64_t n) const - { - n = ((n >> 1) | n) & 0x5555555555555555; - n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); - return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; - } -#endif - - template - ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - const uint64_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa ^ *pb); - ++pa; - ++pb; - } -#else - const uint32_t* pa = reinterpret_cast(a); - const uint32_t* pb = reinterpret_cast(b); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa ^ *pb); - ++pa; - ++pb; - } -#endif - return result; - } - - - template - ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const - { - CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); - - (void)b; -#ifdef FLANN_PLATFORM_64_BIT - const uint64_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt64(*pa); - ++pa; - } -#else - const uint32_t* pa = reinterpret_cast(a); - ResultType result = 0; - size /= long_word_size_; - for(size_t i = 0; i < size; ++i ) { - result += popcnt32(*pa); - ++pa; - } -#endif - return result; - } - -private: -#ifdef FLANN_PLATFORM_64_BIT - static const size_t long_word_size_= sizeof(uint64_t)/sizeof(unsigned char); -#else - static const size_t long_word_size_= sizeof(uint32_t)/sizeof(unsigned char); -#endif -}; - - - -template -struct HistIntersectionDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the histogram intersection distance - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType min0, min1, min2, min3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - min0 = (ResultType)(a[0] < b[0] ? a[0] : b[0]); - min1 = (ResultType)(a[1] < b[1] ? a[1] : b[1]); - min2 = (ResultType)(a[2] < b[2] ? a[2] : b[2]); - min3 = (ResultType)(a[3] < b[3] ? a[3] : b[3]); - result += min0 + min1 + min2 + min3; - a += 4; - b += 4; - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - /* Process last 0-3 pixels. Not needed for standard vector lengths. */ - while (a < last) { - min0 = (ResultType)(*a < *b ? *a : *b); - result += min0; - ++a; - ++b; - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - return a -struct HellingerDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the Hellinger distance - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const - { - ResultType result = ResultType(); - ResultType diff0, diff1, diff2, diff3; - Iterator1 last = a + size; - Iterator1 lastgroup = last - 3; - - /* Process 4 items with each loop for efficiency. */ - while (a < lastgroup) { - diff0 = sqrt(static_cast(a[0])) - sqrt(static_cast(b[0])); - diff1 = sqrt(static_cast(a[1])) - sqrt(static_cast(b[1])); - diff2 = sqrt(static_cast(a[2])) - sqrt(static_cast(b[2])); - diff3 = sqrt(static_cast(a[3])) - sqrt(static_cast(b[3])); - result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; - a += 4; - b += 4; - } - while (a < last) { - diff0 = sqrt(static_cast(*a++)) - sqrt(static_cast(*b++)); - result += diff0 * diff0; - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - ResultType diff = sqrt(static_cast(a)) - sqrt(static_cast(b)); - return diff * diff; - } -}; - - -template -struct ChiSquareDistance -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the chi-square distance - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - ResultType sum, diff; - Iterator1 last = a + size; - - while (a < last) { - sum = (ResultType)(*a + *b); - if (sum>0) { - diff = (ResultType)(*a - *b); - result += diff*diff/sum; - } - ++a; - ++b; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - ResultType result = ResultType(); - ResultType sum, diff; - - sum = (ResultType)(a+b); - if (sum>0) { - diff = (ResultType)(a-b); - result = diff*diff/sum; - } - return result; - } -}; - - -template -struct KL_Divergence -{ - typedef True is_kdtree_distance; - typedef True is_vector_space_distance; - - typedef T ElementType; - typedef typename Accumulator::Type ResultType; - typedef ResultType CentersType; - - /** - * Compute the Kullback-Leibler divergence - */ - template - ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const - { - ResultType result = ResultType(); - Iterator1 last = a + size; - - while (a < last) { - if ( *a != 0 && *b != 0 ) { - ResultType ratio = (ResultType)(*a / *b); - if (ratio>0) { - result += *a * log(ratio); - } - } - ++a; - ++b; - - if ((worst_dist>0)&&(result>worst_dist)) { - return result; - } - } - return result; - } - - /** - * Partial distance, used by the kd-tree. - */ - template - inline ResultType accum_dist(const U& a, const V& b, int) const - { - ResultType result = ResultType(); - if( a != 0 && b != 0 ) { - ResultType ratio = (ResultType)(a / b); - if (ratio>0) { - result = a * log(ratio); - } - } - return result; - } -}; - - -/* - * Depending on processed distances, some of them are already squared (e.g. L2) - * and some are not (e.g.Hamming). In KMeans++ for instance we want to be sure - * we are working on ^2 distances, thus following templates to ensure that. - */ -template -struct squareDistance -{ - typedef typename Distance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist*dist; } -}; - - -template -struct squareDistance, ElementType> -{ - typedef typename L2_Simple::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - -template -struct squareDistance, ElementType> -{ - typedef typename L2::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - - -template -struct squareDistance, ElementType> -{ - typedef typename MinkowskiDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - -template -struct squareDistance, ElementType> -{ - typedef typename HellingerDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - -template -struct squareDistance, ElementType> -{ - typedef typename ChiSquareDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - - -template -typename Distance::ResultType ensureSquareDistance( typename Distance::ResultType dist ) -{ - typedef typename Distance::ElementType ElementType; - - squareDistance dummy; - return dummy( dist ); -} - - -/* - * ...a template to tell the user if the distance he is working with is actually squared - */ - -template -struct isSquareDist -{ - bool operator()() { return false; } -}; - - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - -template -struct isSquareDist, ElementType> -{ - bool operator()() { return true; } -}; - - -template -bool isSquareDistance() -{ - typedef typename Distance::ElementType ElementType; - - isSquareDist dummy; - return dummy(); -} - -/* - * ...and a template to ensure the user that he will process the normal distance, - * and not squared distance, without losing processing time calling sqrt(ensureSquareDistance) - * that will result in doing actually sqrt(dist*dist) for L1 distance for instance. - */ -template -struct simpleDistance -{ - typedef typename Distance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return dist; } -}; - - -template -struct simpleDistance, ElementType> -{ - typedef typename L2_Simple::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - -template -struct simpleDistance, ElementType> -{ - typedef typename L2::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - - -template -struct simpleDistance, ElementType> -{ - typedef typename MinkowskiDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - -template -struct simpleDistance, ElementType> -{ - typedef typename HellingerDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - -template -struct simpleDistance, ElementType> -{ - typedef typename ChiSquareDistance::ResultType ResultType; - ResultType operator()( ResultType dist ) { return sqrt(dist); } -}; - - -template -typename Distance::ResultType ensureSimpleDistance( typename Distance::ResultType dist ) -{ - typedef typename Distance::ElementType ElementType; - - simpleDistance dummy; - return dummy( dist ); -} - -} - -//! @endcond - -#endif //OPENCV_FLANN_DIST_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_DIST_H_ +#define OPENCV_FLANN_DIST_H_ + +//! @cond IGNORED + +#include +#include +#include +#ifdef _MSC_VER +typedef unsigned __int32 uint32_t; +typedef unsigned __int64 uint64_t; +#else +#include +#endif + +#include "defines.h" + +#if defined _WIN32 && (defined(_M_ARM) || defined(_M_ARM64)) +# include +#endif + +#if defined(__ARM_NEON) && !defined(__CUDACC__) +# include "arm_neon.h" +#endif + +namespace cvflann +{ + +template +inline T abs(T x) { return (x<0) ? -x : x; } + +template<> +inline int abs(int x) { return ::abs(x); } + +template<> +inline float abs(float x) { return fabsf(x); } + +template<> +inline double abs(double x) { return fabs(x); } + + +template +inline TargetType round(float x) { return static_cast(x); } + +template<> +inline unsigned int round(float x) { return static_cast(x + 0.5f); } + +template<> +inline unsigned short round(float x) { return static_cast(x + 0.5f); } + +template<> +inline unsigned char round(float x) { return static_cast(x + 0.5f); } + +template<> +inline long long round(float x) { return static_cast(x + 0.5f); } + +template<> +inline long round(float x) { return static_cast(x + 0.5f); } + +template<> +inline int round(float x) { return static_cast(x + 0.5f) - (x<0); } + +template<> +inline short round(float x) { return static_cast(x + 0.5f) - (x<0); } + +template<> +inline char round(float x) { return static_cast(x + 0.5f) - (x<0); } + + +template +inline TargetType round(double x) { return static_cast(x); } + +template<> +inline unsigned int round(double x) { return static_cast(x + 0.5); } + +template<> +inline unsigned short round(double x) { return static_cast(x + 0.5); } + +template<> +inline unsigned char round(double x) { return static_cast(x + 0.5); } + +template<> +inline long long round(double x) { return static_cast(x + 0.5); } + +template<> +inline long round(double x) { return static_cast(x + 0.5); } + +template<> +inline int round(double x) { return static_cast(x + 0.5) - (x<0); } + +template<> +inline short round(double x) { return static_cast(x + 0.5) - (x<0); } + +template<> +inline char round(double x) { return static_cast(x + 0.5) - (x<0); } + + +template +struct Accumulator { typedef T Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; +template<> +struct Accumulator { typedef float Type; }; + +#undef True +#undef False + +class True +{ +public: + static const bool val = true; +}; + +class False +{ +public: + static const bool val = false; +}; + + +/* + * This is a "zero iterator". It basically behaves like a zero filled + * array to all algorithms that use arrays as iterators (STL style). + * It's useful when there's a need to compute the distance between feature + * and origin it and allows for better compiler optimisation than using a + * zero-filled array. + */ +template +struct ZeroIterator +{ + + T operator*() + { + return 0; + } + + T operator[](int) + { + return 0; + } + + const ZeroIterator& operator ++() + { + return *this; + } + + ZeroIterator operator ++(int) + { + return *this; + } + + ZeroIterator& operator+=(int) + { + return *this; + } + +}; + + + +/** + * Squared Euclidean distance functor. + * + * This is the simpler, unrolled version. This is preferable for + * very low dimensionality data (eg 3D points) + */ +template +struct L2_Simple +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + ResultType result = ResultType(); + ResultType diff; + for(size_t i = 0; i < size; ++i ) { + diff = (ResultType)(*a++ - *b++); + result += diff*diff; + } + return result; + } + + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return (a-b)*(a-b); + } +}; + + + +/** + * Squared Euclidean distance functor, optimized version + */ +template +struct L2 +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the squared Euclidean distance between two vectors. + * + * This is highly optimised, with loop unrolling, as it is one + * of the most expensive inner loops. + * + * The computation of squared root at the end is omitted for + * efficiency. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = (ResultType)(a[0] - b[0]); + diff1 = (ResultType)(a[1] - b[1]); + diff2 = (ResultType)(a[2] - b[2]); + diff3 = (ResultType)(a[3] - b[3]); + result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = (ResultType)(*a++ - *b++); + result += diff0 * diff0; + } + return result; + } + + /** + * Partial euclidean distance, using just one dimension. This is used by the + * kd-tree when computing partial distances while traversing the tree. + * + * Squared root is omitted for efficiency. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return (a-b)*(a-b); + } +}; + + +/* + * Manhattan distance functor, optimized version + */ +template +struct L1 +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the Manhattan (L_1) distance between two vectors. + * + * This is highly optimised, with loop unrolling, as it is one + * of the most expensive inner loops. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = (ResultType)abs(a[0] - b[0]); + diff1 = (ResultType)abs(a[1] - b[1]); + diff2 = (ResultType)abs(a[2] - b[2]); + diff3 = (ResultType)abs(a[3] - b[3]); + result += diff0 + diff1 + diff2 + diff3; + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = (ResultType)abs(*a++ - *b++); + result += diff0; + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return abs(a-b); + } +}; + + + +template +struct MinkowskiDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + int order; + + MinkowskiDistance(int order_) : order(order_) {} + + /** + * Compute the Minkowski (L_p) distance between two vectors. + * + * This is highly optimised, with loop unrolling, as it is one + * of the most expensive inner loops. + * + * The computation of squared root at the end is omitted for + * efficiency. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = (ResultType)abs(a[0] - b[0]); + diff1 = (ResultType)abs(a[1] - b[1]); + diff2 = (ResultType)abs(a[2] - b[2]); + diff3 = (ResultType)abs(a[3] - b[3]); + result += pow(diff0,order) + pow(diff1,order) + pow(diff2,order) + pow(diff3,order); + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = (ResultType)abs(*a++ - *b++); + result += pow(diff0,order); + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return pow(static_cast(abs(a-b)),order); + } +}; + + + +template +struct MaxDistance +{ + typedef False is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the max distance (L_infinity) between two vectors. + * + * This distance is not a valid kdtree distance, it's not dimensionwise additive. + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = abs(a[0] - b[0]); + diff1 = abs(a[1] - b[1]); + diff2 = abs(a[2] - b[2]); + diff3 = abs(a[3] - b[3]); + if (diff0>result) {result = diff0; } + if (diff1>result) {result = diff1; } + if (diff2>result) {result = diff2; } + if (diff3>result) {result = diff3; } + a += 4; + b += 4; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + diff0 = abs(*a++ - *b++); + result = (diff0>result) ? diff0 : result; + } + return result; + } + + /* This distance functor is not dimension-wise additive, which + * makes it an invalid kd-tree distance, not implementing the accum_dist method */ + +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** + * Hamming distance functor - counts the bit differences between two strings - useful for the Brief descriptor + * bit count of A exclusive XOR'ed with B + */ +struct HammingLUT +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef unsigned char ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** this will count the bits in a ^ b + */ + template + ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const + { + static const uchar popCountTable[] = + { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + }; + ResultType result = 0; + const unsigned char* b2 = reinterpret_cast (b); + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i] ^ b2[i]]; + } + return result; + } + + + ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const + { + (void)b; + static const uchar popCountTable[] = + { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 + }; + ResultType result = 0; + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i]]; + } + return result; + } +}; + +/** + * Hamming distance functor (pop count between two binary vectors, i.e. xor them and count the number of bits set) + * That code was taken from brief.cpp in OpenCV + */ +template +struct Hamming +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + + typedef T ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + template + ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + ResultType result = 0; +#if defined(__ARM_NEON) && !defined(__CUDACC__) + { + const unsigned char* a2 = reinterpret_cast (a); + const unsigned char* b2 = reinterpret_cast (b); + uint32x4_t bits = vmovq_n_u32(0); + for (size_t i = 0; i < size; i += 16) { + uint8x16_t A_vec = vld1q_u8 (a2 + i); + uint8x16_t B_vec = vld1q_u8 (b2 + i); + uint8x16_t AxorB = veorq_u8 (A_vec, B_vec); + uint8x16_t bitsSet = vcntq_u8 (AxorB); + uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); + uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); + bits = vaddq_u32(bits, bitSet4); + } + uint64x2_t bitSet2 = vpaddlq_u32 (bits); + result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); + result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); + } +#elif defined(__GNUC__) + { + //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) + typedef unsigned long long pop_t; + const size_t modulo = size % sizeof(pop_t); + const pop_t* a2 = reinterpret_cast (a); + const pop_t* b2 = reinterpret_cast (b); + const pop_t* a2_end = a2 + (size / sizeof(pop_t)); + + for (; a2 != a2_end; ++a2, ++b2) result += __builtin_popcountll((*a2) ^ (*b2)); + + if (modulo) { + //in the case where size is not dividable by sizeof(size_t) + //need to mask off the bits at the end + pop_t a_final = 0, b_final = 0; + memcpy(&a_final, a2, modulo); + memcpy(&b_final, b2, modulo); + result += __builtin_popcountll(a_final ^ b_final); + } + } +#else // NO NEON and NOT GNUC + HammingLUT lut; + result = lut(reinterpret_cast (a), + reinterpret_cast (b), size); +#endif + return result; + } + + + template + ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const + { + (void)b; + ResultType result = 0; +#if defined(__ARM_NEON) && !defined(__CUDACC__) + { + const unsigned char* a2 = reinterpret_cast (a); + uint32x4_t bits = vmovq_n_u32(0); + for (size_t i = 0; i < size; i += 16) { + uint8x16_t A_vec = vld1q_u8 (a2 + i); + uint8x16_t bitsSet = vcntq_u8 (A_vec); + uint16x8_t bitSet8 = vpaddlq_u8 (bitsSet); + uint32x4_t bitSet4 = vpaddlq_u16 (bitSet8); + bits = vaddq_u32(bits, bitSet4); + } + uint64x2_t bitSet2 = vpaddlq_u32 (bits); + result = vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),0); + result += vgetq_lane_s32 (vreinterpretq_s32_u64(bitSet2),2); + } +#elif defined(__GNUC__) + { + //for portability just use unsigned long -- and use the __builtin_popcountll (see docs for __builtin_popcountll) + typedef unsigned long long pop_t; + const size_t modulo = size % sizeof(pop_t); + const pop_t* a2 = reinterpret_cast (a); + const pop_t* a2_end = a2 + (size / sizeof(pop_t)); + + for (; a2 != a2_end; ++a2) result += __builtin_popcountll(*a2); + + if (modulo) { + //in the case where size is not dividable by sizeof(size_t) + //need to mask off the bits at the end + pop_t a_final = 0; + memcpy(&a_final, a2, modulo); + result += __builtin_popcountll(a_final); + } + } +#else // NO NEON and NOT GNUC + HammingLUT lut; + result = lut(reinterpret_cast (a), b, size); +#endif + return result; + } +}; + +template +struct Hamming2 +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef T ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** This is popcount_3() from: + * http://en.wikipedia.org/wiki/Hamming_weight */ + unsigned int popcnt32(uint32_t n) const + { + n -= ((n >> 1) & 0x55555555); + n = (n & 0x33333333) + ((n >> 2) & 0x33333333); + return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24; + } + +#ifdef FLANN_PLATFORM_64_BIT + unsigned int popcnt64(uint64_t n) const + { + n -= ((n >> 1) & 0x5555555555555555); + n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); + return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; + } +#endif + + template + ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + const uint64_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa ^ *pb); + ++pa; + ++pb; + } +#else + const uint32_t* pa = reinterpret_cast(a); + const uint32_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa ^ *pb); + ++pa; + ++pb; + } +#endif + return result; + } + + + template + ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + + (void)b; +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa); + ++pa; + } +#else + const uint32_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa); + ++pa; + } +#endif + return result; + } + +private: +#ifdef FLANN_PLATFORM_64_BIT + static const size_t long_word_size_ = sizeof(uint64_t)/sizeof(unsigned char); +#else + static const size_t long_word_size_ = sizeof(uint32_t)/sizeof(unsigned char); +#endif +}; + + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +struct DNAmmingLUT +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef unsigned char ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** this will count the bits in a ^ b + */ + template + ResultType operator()(const unsigned char* a, const Iterator2 b, size_t size) const + { + static const uchar popCountTable[] = + { + 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 + }; + ResultType result = 0; + const unsigned char* b2 = reinterpret_cast (b); + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i] ^ b2[i]]; + } + return result; + } + + + ResultType operator()(const unsigned char* a, const ZeroIterator b, size_t size) const + { + (void)b; + static const uchar popCountTable[] = + { + 0, 1, 1, 1, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 1, 2, 2, 2, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, + 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4, 2, 3, 3, 3, 3, 4, 4, 4, 3, 4, 4, 4, 3, 4, 4, 4 + }; + ResultType result = 0; + for (size_t i = 0; i < size; i++) { + result += popCountTable[a[i]]; + } + return result; + } +}; + + +template +struct DNAmming2 +{ + typedef False is_kdtree_distance; + typedef False is_vector_space_distance; + + typedef T ElementType; + typedef int ResultType; + typedef ElementType CentersType; + + /** This is popcount_3() from: + * http://en.wikipedia.org/wiki/Hamming_weight */ + unsigned int popcnt32(uint32_t n) const + { + n = ((n >> 1) | n) & 0x55555555; + n = (n & 0x33333333) + ((n >> 2) & 0x33333333); + return (((n + (n >> 4))& 0x0F0F0F0F)* 0x01010101) >> 24; + } + +#ifdef FLANN_PLATFORM_64_BIT + unsigned int popcnt64(uint64_t n) const + { + n = ((n >> 1) | n) & 0x5555555555555555; + n = (n & 0x3333333333333333) + ((n >> 2) & 0x3333333333333333); + return (((n + (n >> 4))& 0x0f0f0f0f0f0f0f0f)* 0x0101010101010101) >> 56; + } +#endif + + template + ResultType operator()(const Iterator1 a, const Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + const uint64_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa ^ *pb); + ++pa; + ++pb; + } +#else + const uint32_t* pa = reinterpret_cast(a); + const uint32_t* pb = reinterpret_cast(b); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa ^ *pb); + ++pa; + ++pb; + } +#endif + return result; + } + + + template + ResultType operator()(const Iterator1 a, ZeroIterator b, size_t size, ResultType /*worst_dist*/ = -1) const + { + CV_DbgAssert(!(size % long_word_size_) && "vectors size must be multiple of long words size (i.e. 8)"); + + (void)b; +#ifdef FLANN_PLATFORM_64_BIT + const uint64_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt64(*pa); + ++pa; + } +#else + const uint32_t* pa = reinterpret_cast(a); + ResultType result = 0; + size /= long_word_size_; + for(size_t i = 0; i < size; ++i ) { + result += popcnt32(*pa); + ++pa; + } +#endif + return result; + } + +private: +#ifdef FLANN_PLATFORM_64_BIT + static const size_t long_word_size_= sizeof(uint64_t)/sizeof(unsigned char); +#else + static const size_t long_word_size_= sizeof(uint32_t)/sizeof(unsigned char); +#endif +}; + + + +template +struct HistIntersectionDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the histogram intersection distance + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType min0, min1, min2, min3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + min0 = (ResultType)(a[0] < b[0] ? a[0] : b[0]); + min1 = (ResultType)(a[1] < b[1] ? a[1] : b[1]); + min2 = (ResultType)(a[2] < b[2] ? a[2] : b[2]); + min3 = (ResultType)(a[3] < b[3] ? a[3] : b[3]); + result += min0 + min1 + min2 + min3; + a += 4; + b += 4; + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + /* Process last 0-3 pixels. Not needed for standard vector lengths. */ + while (a < last) { + min0 = (ResultType)(*a < *b ? *a : *b); + result += min0; + ++a; + ++b; + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + return a +struct HellingerDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the Hellinger distance + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType /*worst_dist*/ = -1) const + { + ResultType result = ResultType(); + ResultType diff0, diff1, diff2, diff3; + Iterator1 last = a + size; + Iterator1 lastgroup = last - 3; + + /* Process 4 items with each loop for efficiency. */ + while (a < lastgroup) { + diff0 = sqrt(static_cast(a[0])) - sqrt(static_cast(b[0])); + diff1 = sqrt(static_cast(a[1])) - sqrt(static_cast(b[1])); + diff2 = sqrt(static_cast(a[2])) - sqrt(static_cast(b[2])); + diff3 = sqrt(static_cast(a[3])) - sqrt(static_cast(b[3])); + result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; + a += 4; + b += 4; + } + while (a < last) { + diff0 = sqrt(static_cast(*a++)) - sqrt(static_cast(*b++)); + result += diff0 * diff0; + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + ResultType diff = sqrt(static_cast(a)) - sqrt(static_cast(b)); + return diff * diff; + } +}; + + +template +struct ChiSquareDistance +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the chi-square distance + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + ResultType sum, diff; + Iterator1 last = a + size; + + while (a < last) { + sum = (ResultType)(*a + *b); + if (sum>0) { + diff = (ResultType)(*a - *b); + result += diff*diff/sum; + } + ++a; + ++b; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + ResultType result = ResultType(); + ResultType sum, diff; + + sum = (ResultType)(a+b); + if (sum>0) { + diff = (ResultType)(a-b); + result = diff*diff/sum; + } + return result; + } +}; + + +template +struct KL_Divergence +{ + typedef True is_kdtree_distance; + typedef True is_vector_space_distance; + + typedef T ElementType; + typedef typename Accumulator::Type ResultType; + typedef ResultType CentersType; + + /** + * Compute the Kullback-Leibler divergence + */ + template + ResultType operator()(Iterator1 a, Iterator2 b, size_t size, ResultType worst_dist = -1) const + { + ResultType result = ResultType(); + Iterator1 last = a + size; + + while (a < last) { + if ( *a != 0 && *b != 0 ) { + ResultType ratio = (ResultType)(*a / *b); + if (ratio>0) { + result += *a * log(ratio); + } + } + ++a; + ++b; + + if ((worst_dist>0)&&(result>worst_dist)) { + return result; + } + } + return result; + } + + /** + * Partial distance, used by the kd-tree. + */ + template + inline ResultType accum_dist(const U& a, const V& b, int) const + { + ResultType result = ResultType(); + if( a != 0 && b != 0 ) { + ResultType ratio = (ResultType)(a / b); + if (ratio>0) { + result = a * log(ratio); + } + } + return result; + } +}; + + +/* + * Depending on processed distances, some of them are already squared (e.g. L2) + * and some are not (e.g.Hamming). In KMeans++ for instance we want to be sure + * we are working on ^2 distances, thus following templates to ensure that. + */ +template +struct squareDistance +{ + typedef typename Distance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist*dist; } +}; + + +template +struct squareDistance, ElementType> +{ + typedef typename L2_Simple::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + +template +struct squareDistance, ElementType> +{ + typedef typename L2::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + + +template +struct squareDistance, ElementType> +{ + typedef typename MinkowskiDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + +template +struct squareDistance, ElementType> +{ + typedef typename HellingerDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + +template +struct squareDistance, ElementType> +{ + typedef typename ChiSquareDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + + +template +typename Distance::ResultType ensureSquareDistance( typename Distance::ResultType dist ) +{ + typedef typename Distance::ElementType ElementType; + + squareDistance dummy; + return dummy( dist ); +} + + +/* + * ...a template to tell the user if the distance he is working with is actually squared + */ + +template +struct isSquareDist +{ + bool operator()() { return false; } +}; + + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + +template +struct isSquareDist, ElementType> +{ + bool operator()() { return true; } +}; + + +template +bool isSquareDistance() +{ + typedef typename Distance::ElementType ElementType; + + isSquareDist dummy; + return dummy(); +} + +/* + * ...and a template to ensure the user that he will process the normal distance, + * and not squared distance, without losing processing time calling sqrt(ensureSquareDistance) + * that will result in doing actually sqrt(dist*dist) for L1 distance for instance. + */ +template +struct simpleDistance +{ + typedef typename Distance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return dist; } +}; + + +template +struct simpleDistance, ElementType> +{ + typedef typename L2_Simple::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + +template +struct simpleDistance, ElementType> +{ + typedef typename L2::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + + +template +struct simpleDistance, ElementType> +{ + typedef typename MinkowskiDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + +template +struct simpleDistance, ElementType> +{ + typedef typename HellingerDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + +template +struct simpleDistance, ElementType> +{ + typedef typename ChiSquareDistance::ResultType ResultType; + ResultType operator()( ResultType dist ) { return sqrt(dist); } +}; + + +template +typename Distance::ResultType ensureSimpleDistance( typename Distance::ResultType dist ) +{ + typedef typename Distance::ElementType ElementType; + + simpleDistance dummy; + return dummy( dist ); +} + +} + +//! @endcond + +#endif //OPENCV_FLANN_DIST_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h b/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h index 7cfb12fbe3..c176f2e4ef 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/dummy.h @@ -1,16 +1,16 @@ - -#ifndef OPENCV_FLANN_DUMMY_H_ -#define OPENCV_FLANN_DUMMY_H_ - -//! @cond IGNORED - -namespace cvflann -{ - -CV_DEPRECATED inline void dummyfunc() {} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_DUMMY_H_ */ + +#ifndef OPENCV_FLANN_DUMMY_H_ +#define OPENCV_FLANN_DUMMY_H_ + +//! @cond IGNORED + +namespace cvflann +{ + +CV_DEPRECATED inline void dummyfunc() {} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_DUMMY_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h b/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h index a3f0be6fa8..676cb0b71e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/dynamic_bitset.h @@ -1,160 +1,160 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -/*********************************************************************** - * Author: Vincent Rabaud - *************************************************************************/ - -#ifndef OPENCV_FLANN_DYNAMIC_BITSET_H_ -#define OPENCV_FLANN_DYNAMIC_BITSET_H_ - -//! @cond IGNORED - -#ifndef FLANN_USE_BOOST -# define FLANN_USE_BOOST 0 -#endif -//#define FLANN_USE_BOOST 1 -#if FLANN_USE_BOOST -#include -typedef boost::dynamic_bitset<> DynamicBitset; -#else - -#include - -#include "dist.h" - -namespace cvflann { - -/** Class re-implementing the boost version of it - * This helps not depending on boost, it also does not do the bound checks - * and has a way to reset a block for speed - */ -class DynamicBitset -{ -public: - /** default constructor - */ - DynamicBitset() : size_(0) - { - } - - /** only constructor we use in our code - * @param sz the size of the bitset (in bits) - */ - DynamicBitset(size_t sz) - { - resize(sz); - reset(); - } - - /** Sets all the bits to 0 - */ - void clear() - { - std::fill(bitset_.begin(), bitset_.end(), 0); - } - - /** @brief checks if the bitset is empty - * @return true if the bitset is empty - */ - bool empty() const - { - return bitset_.empty(); - } - - /** set all the bits to 0 - */ - void reset() - { - std::fill(bitset_.begin(), bitset_.end(), 0); - } - - /** @brief set one bit to 0 - */ - void reset(size_t index) - { - bitset_[index / cell_bit_size_] &= ~(size_t(1) << (index % cell_bit_size_)); - } - - /** @brief sets a specific bit to 0, and more bits too - * This function is useful when resetting a given set of bits so that the - * whole bitset ends up being 0: if that's the case, we don't care about setting - * other bits to 0 - */ - void reset_block(size_t index) - { - bitset_[index / cell_bit_size_] = 0; - } - - /** resize the bitset so that it contains at least sz bits - */ - void resize(size_t sz) - { - size_ = sz; - bitset_.resize(sz / cell_bit_size_ + 1); - } - - /** set a bit to true - * @param index the index of the bit to set to 1 - */ - void set(size_t index) - { - bitset_[index / cell_bit_size_] |= size_t(1) << (index % cell_bit_size_); - } - - /** gives the number of contained bits - */ - size_t size() const - { - return size_; - } - - /** check if a bit is set - * @param index the index of the bit to check - * @return true if the bit is set - */ - bool test(size_t index) const - { - return (bitset_[index / cell_bit_size_] & (size_t(1) << (index % cell_bit_size_))) != 0; - } - -private: - std::vector bitset_; - size_t size_; - static const unsigned int cell_bit_size_ = CHAR_BIT * sizeof(size_t); -}; - -} // namespace cvflann - -#endif - -//! @endcond - -#endif // OPENCV_FLANN_DYNAMIC_BITSET_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +/*********************************************************************** + * Author: Vincent Rabaud + *************************************************************************/ + +#ifndef OPENCV_FLANN_DYNAMIC_BITSET_H_ +#define OPENCV_FLANN_DYNAMIC_BITSET_H_ + +//! @cond IGNORED + +#ifndef FLANN_USE_BOOST +# define FLANN_USE_BOOST 0 +#endif +//#define FLANN_USE_BOOST 1 +#if FLANN_USE_BOOST +#include +typedef boost::dynamic_bitset<> DynamicBitset; +#else + +#include + +#include "dist.h" + +namespace cvflann { + +/** Class re-implementing the boost version of it + * This helps not depending on boost, it also does not do the bound checks + * and has a way to reset a block for speed + */ +class DynamicBitset +{ +public: + /** default constructor + */ + DynamicBitset() : size_(0) + { + } + + /** only constructor we use in our code + * @param sz the size of the bitset (in bits) + */ + DynamicBitset(size_t sz) + { + resize(sz); + reset(); + } + + /** Sets all the bits to 0 + */ + void clear() + { + std::fill(bitset_.begin(), bitset_.end(), 0); + } + + /** @brief checks if the bitset is empty + * @return true if the bitset is empty + */ + bool empty() const + { + return bitset_.empty(); + } + + /** set all the bits to 0 + */ + void reset() + { + std::fill(bitset_.begin(), bitset_.end(), 0); + } + + /** @brief set one bit to 0 + */ + void reset(size_t index) + { + bitset_[index / cell_bit_size_] &= ~(size_t(1) << (index % cell_bit_size_)); + } + + /** @brief sets a specific bit to 0, and more bits too + * This function is useful when resetting a given set of bits so that the + * whole bitset ends up being 0: if that's the case, we don't care about setting + * other bits to 0 + */ + void reset_block(size_t index) + { + bitset_[index / cell_bit_size_] = 0; + } + + /** resize the bitset so that it contains at least sz bits + */ + void resize(size_t sz) + { + size_ = sz; + bitset_.resize(sz / cell_bit_size_ + 1); + } + + /** set a bit to true + * @param index the index of the bit to set to 1 + */ + void set(size_t index) + { + bitset_[index / cell_bit_size_] |= size_t(1) << (index % cell_bit_size_); + } + + /** gives the number of contained bits + */ + size_t size() const + { + return size_; + } + + /** check if a bit is set + * @param index the index of the bit to check + * @return true if the bit is set + */ + bool test(size_t index) const + { + return (bitset_[index / cell_bit_size_] & (size_t(1) << (index % cell_bit_size_))) != 0; + } + +private: + std::vector bitset_; + size_t size_; + static const unsigned int cell_bit_size_ = CHAR_BIT * sizeof(size_t); +}; + +} // namespace cvflann + +#endif + +//! @endcond + +#endif // OPENCV_FLANN_DYNAMIC_BITSET_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp b/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp index 58ba51ee1e..227683f979 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann/flann.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/flann.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/flann.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp b/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp index a516dfa26e..af0b380bbf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann/flann_base.hpp @@ -1,312 +1,312 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_BASE_HPP_ -#define OPENCV_FLANN_BASE_HPP_ - -//! @cond IGNORED - -#include -#include - -#include "general.h" -#include "matrix.h" -#include "params.h" -#include "saving.h" - -#include "all_indices.h" - -namespace cvflann -{ -class FILEScopeGuard { - -public: - explicit FILEScopeGuard(FILE* file) { - file_ = file; - }; - - ~FILEScopeGuard() { - fclose(file_); - }; - -private: - FILE* file_; -}; - - -/** - * Sets the log level used for all flann functions - * @param level Verbosity level - */ -inline void log_verbosity(int level) -{ - if (level >= 0) { - Logger::setLevel(level); - } -} - -/** - * (Deprecated) Index parameters for creating a saved index. - */ -struct SavedIndexParams : public IndexParams -{ - SavedIndexParams(cv::String filename) - { - (* this)["algorithm"] = FLANN_INDEX_SAVED; - (*this)["filename"] = filename; - } -}; - -template -NNIndex* load_saved_index(const Matrix& dataset, const cv::String& filename, Distance distance) -{ - typedef typename Distance::ElementType ElementType; - - FILE* fin = fopen(filename.c_str(), "rb"); - if (fin == NULL) { - return NULL; - } - FILEScopeGuard fscgd(fin); - - IndexHeader header = load_header(fin); - if (header.data_type != Datatype::type()) { - FLANN_THROW(cv::Error::StsError, "Datatype of saved index is different than of the one to be created."); - } - if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) { - FLANN_THROW(cv::Error::StsError, "The index saved belongs to a different dataset"); - } - - IndexParams params; - params["algorithm"] = header.index_type; - NNIndex* nnIndex = create_index_by_type(dataset, params, distance); - nnIndex->loadIndex(fin); - - return nnIndex; -} - - -template -class Index : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - Index(const Matrix& features, const IndexParams& params, Distance distance = Distance() ) - :index_params_(params) - { - flann_algorithm_t index_type = get_param(params,"algorithm"); - loaded_ = false; - - if (index_type == FLANN_INDEX_SAVED) { - nnIndex_ = load_saved_index(features, get_param(params,"filename"), distance); - loaded_ = true; - } - else { - nnIndex_ = create_index_by_type(features, params, distance); - } - } - - ~Index() - { - delete nnIndex_; - } - - /** - * Builds the index. - */ - void buildIndex() CV_OVERRIDE - { - if (!loaded_) { - nnIndex_->buildIndex(); - } - } - - void save(cv::String filename) - { - FILE* fout = fopen(filename.c_str(), "wb"); - if (fout == NULL) { - FLANN_THROW(cv::Error::StsError, "Cannot open file"); - } - save_header(fout, *nnIndex_); - saveIndex(fout); - fclose(fout); - } - - /** - * \brief Saves the index to a stream - * \param stream The stream to save the index to - */ - virtual void saveIndex(FILE* stream) CV_OVERRIDE - { - nnIndex_->saveIndex(stream); - } - - /** - * \brief Loads the index from a stream - * \param stream The stream from which the index is loaded - */ - virtual void loadIndex(FILE* stream) CV_OVERRIDE - { - nnIndex_->loadIndex(stream); - } - - /** - * \returns number of features in this index. - */ - size_t veclen() const CV_OVERRIDE - { - return nnIndex_->veclen(); - } - - /** - * \returns The dimensionality of the features in this index. - */ - size_t size() const CV_OVERRIDE - { - return nnIndex_->size(); - } - - /** - * \returns The index type (kdtree, kmeans,...) - */ - flann_algorithm_t getType() const CV_OVERRIDE - { - return nnIndex_->getType(); - } - - /** - * \returns The amount of memory (in bytes) used by the index. - */ - virtual int usedMemory() const CV_OVERRIDE - { - return nnIndex_->usedMemory(); - } - - - /** - * \returns The index parameters - */ - IndexParams getParameters() const CV_OVERRIDE - { - return nnIndex_->getParameters(); - } - - /** - * \brief Perform k-nearest neighbor search - * \param[in] queries The query points for which to find the nearest neighbors - * \param[out] indices The indices of the nearest neighbors found - * \param[out] dists Distances to the nearest neighbors found - * \param[in] knn Number of nearest neighbors to return - * \param[in] params Search parameters - */ - void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE - { - nnIndex_->knnSearch(queries, indices, dists, knn, params); - } - - /** - * \brief Perform radius search - * \param[in] query The query point - * \param[out] indices The indinces of the neighbors found within the given radius - * \param[out] dists The distances to the nearest neighbors found - * \param[in] radius The radius used for search - * \param[in] params Search parameters - * \returns Number of neighbors found - */ - int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) CV_OVERRIDE - { - return nnIndex_->radiusSearch(query, indices, dists, radius, params); - } - - /** - * \brief Method that searches for nearest-neighbours - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - nnIndex_->findNeighbors(result, vec, searchParams); - } - - /** - * \brief Returns actual index - */ - CV_DEPRECATED NNIndex* getIndex() - { - return nnIndex_; - } - - /** - * \brief Returns index parameters. - * \deprecated use getParameters() instead. - */ - CV_DEPRECATED const IndexParams* getIndexParameters() - { - return &index_params_; - } - -private: - /** Pointer to actual index class */ - NNIndex* nnIndex_; - /** Indices if the index was loaded from a file */ - bool loaded_; - /** Parameters passed to the index */ - IndexParams index_params_; - - Index(const Index &); // copy disabled - Index& operator=(const Index &); // assign disabled -}; - -/** - * Performs a hierarchical clustering of the points passed as argument and then takes a cut in the - * the clustering tree to return a flat clustering. - * @param[in] points Points to be clustered - * @param centers The computed cluster centres. Matrix should be preallocated and centers.rows is the - * number of clusters requested. - * @param params Clustering parameters (The same as for cvflann::KMeansIndex) - * @param d Distance to be used for clustering (eg: cvflann::L2) - * @return number of clusters computed (can be different than clusters.rows and is the highest number - * of the form (branching-1)*K+1 smaller than clusters.rows). - */ -template -int hierarchicalClustering(const Matrix& points, Matrix& centers, - const KMeansIndexParams& params, Distance d = Distance()) -{ - KMeansIndex kmeans(points, params, d); - kmeans.buildIndex(); - - int clusterNum = kmeans.getClusterCenters(centers); - return clusterNum; -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_BASE_HPP_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_BASE_HPP_ +#define OPENCV_FLANN_BASE_HPP_ + +//! @cond IGNORED + +#include +#include + +#include "general.h" +#include "matrix.h" +#include "params.h" +#include "saving.h" + +#include "all_indices.h" + +namespace cvflann +{ +class FILEScopeGuard { + +public: + explicit FILEScopeGuard(FILE* file) { + file_ = file; + }; + + ~FILEScopeGuard() { + fclose(file_); + }; + +private: + FILE* file_; +}; + + +/** + * Sets the log level used for all flann functions + * @param level Verbosity level + */ +inline void log_verbosity(int level) +{ + if (level >= 0) { + Logger::setLevel(level); + } +} + +/** + * (Deprecated) Index parameters for creating a saved index. + */ +struct SavedIndexParams : public IndexParams +{ + SavedIndexParams(cv::String filename) + { + (* this)["algorithm"] = FLANN_INDEX_SAVED; + (*this)["filename"] = filename; + } +}; + +template +NNIndex* load_saved_index(const Matrix& dataset, const cv::String& filename, Distance distance) +{ + typedef typename Distance::ElementType ElementType; + + FILE* fin = fopen(filename.c_str(), "rb"); + if (fin == NULL) { + return NULL; + } + FILEScopeGuard fscgd(fin); + + IndexHeader header = load_header(fin); + if (header.data_type != Datatype::type()) { + FLANN_THROW(cv::Error::StsError, "Datatype of saved index is different than of the one to be created."); + } + if ((size_t(header.rows) != dataset.rows)||(size_t(header.cols) != dataset.cols)) { + FLANN_THROW(cv::Error::StsError, "The index saved belongs to a different dataset"); + } + + IndexParams params; + params["algorithm"] = header.index_type; + NNIndex* nnIndex = create_index_by_type(dataset, params, distance); + nnIndex->loadIndex(fin); + + return nnIndex; +} + + +template +class Index : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + Index(const Matrix& features, const IndexParams& params, Distance distance = Distance() ) + :index_params_(params) + { + flann_algorithm_t index_type = get_param(params,"algorithm"); + loaded_ = false; + + if (index_type == FLANN_INDEX_SAVED) { + nnIndex_ = load_saved_index(features, get_param(params,"filename"), distance); + loaded_ = true; + } + else { + nnIndex_ = create_index_by_type(features, params, distance); + } + } + + ~Index() + { + delete nnIndex_; + } + + /** + * Builds the index. + */ + void buildIndex() CV_OVERRIDE + { + if (!loaded_) { + nnIndex_->buildIndex(); + } + } + + void save(cv::String filename) + { + FILE* fout = fopen(filename.c_str(), "wb"); + if (fout == NULL) { + FLANN_THROW(cv::Error::StsError, "Cannot open file"); + } + save_header(fout, *nnIndex_); + saveIndex(fout); + fclose(fout); + } + + /** + * \brief Saves the index to a stream + * \param stream The stream to save the index to + */ + virtual void saveIndex(FILE* stream) CV_OVERRIDE + { + nnIndex_->saveIndex(stream); + } + + /** + * \brief Loads the index from a stream + * \param stream The stream from which the index is loaded + */ + virtual void loadIndex(FILE* stream) CV_OVERRIDE + { + nnIndex_->loadIndex(stream); + } + + /** + * \returns number of features in this index. + */ + size_t veclen() const CV_OVERRIDE + { + return nnIndex_->veclen(); + } + + /** + * \returns The dimensionality of the features in this index. + */ + size_t size() const CV_OVERRIDE + { + return nnIndex_->size(); + } + + /** + * \returns The index type (kdtree, kmeans,...) + */ + flann_algorithm_t getType() const CV_OVERRIDE + { + return nnIndex_->getType(); + } + + /** + * \returns The amount of memory (in bytes) used by the index. + */ + virtual int usedMemory() const CV_OVERRIDE + { + return nnIndex_->usedMemory(); + } + + + /** + * \returns The index parameters + */ + IndexParams getParameters() const CV_OVERRIDE + { + return nnIndex_->getParameters(); + } + + /** + * \brief Perform k-nearest neighbor search + * \param[in] queries The query points for which to find the nearest neighbors + * \param[out] indices The indices of the nearest neighbors found + * \param[out] dists Distances to the nearest neighbors found + * \param[in] knn Number of nearest neighbors to return + * \param[in] params Search parameters + */ + void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE + { + nnIndex_->knnSearch(queries, indices, dists, knn, params); + } + + /** + * \brief Perform radius search + * \param[in] query The query point + * \param[out] indices The indinces of the neighbors found within the given radius + * \param[out] dists The distances to the nearest neighbors found + * \param[in] radius The radius used for search + * \param[in] params Search parameters + * \returns Number of neighbors found + */ + int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) CV_OVERRIDE + { + return nnIndex_->radiusSearch(query, indices, dists, radius, params); + } + + /** + * \brief Method that searches for nearest-neighbours + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + nnIndex_->findNeighbors(result, vec, searchParams); + } + + /** + * \brief Returns actual index + */ + CV_DEPRECATED NNIndex* getIndex() + { + return nnIndex_; + } + + /** + * \brief Returns index parameters. + * \deprecated use getParameters() instead. + */ + CV_DEPRECATED const IndexParams* getIndexParameters() + { + return &index_params_; + } + +private: + /** Pointer to actual index class */ + NNIndex* nnIndex_; + /** Indices if the index was loaded from a file */ + bool loaded_; + /** Parameters passed to the index */ + IndexParams index_params_; + + Index(const Index &); // copy disabled + Index& operator=(const Index &); // assign disabled +}; + +/** + * Performs a hierarchical clustering of the points passed as argument and then takes a cut in the + * the clustering tree to return a flat clustering. + * @param[in] points Points to be clustered + * @param centers The computed cluster centres. Matrix should be preallocated and centers.rows is the + * number of clusters requested. + * @param params Clustering parameters (The same as for cvflann::KMeansIndex) + * @param d Distance to be used for clustering (eg: cvflann::L2) + * @return number of clusters computed (can be different than clusters.rows and is the highest number + * of the form (branching-1)*K+1 smaller than clusters.rows). + */ +template +int hierarchicalClustering(const Matrix& points, Matrix& centers, + const KMeansIndexParams& params, Distance d = Distance()) +{ + KMeansIndex kmeans(points, params, d); + kmeans.buildIndex(); + + int clusterNum = kmeans.getClusterCenters(centers); + return clusterNum; +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_BASE_HPP_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/general.h b/3rdParty/opencv-4.11.0/opencv2/flann/general.h index eeb07e41f9..e65cba2f8a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/general.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/general.h @@ -1,65 +1,65 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_GENERAL_H_ -#define OPENCV_FLANN_GENERAL_H_ - -#include "opencv2/core/version.hpp" - -#if CV_VERSION_MAJOR <= 4 - -//! @cond IGNORED - -#include "opencv2/core.hpp" - -namespace cvflann -{ - -class FLANNException : public cv::Exception -{ -public: - FLANNException(const char* message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } - - FLANNException(const cv::String& message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } -}; - -} - -#define FLANN_THROW(TYPE, STR) throw FLANNException(STR) - -#else - -#define FLANN_THROW(TYPE, STR) CV_Error(TYPE, STR) - -#endif - -//! @endcond - -#endif /* OPENCV_FLANN_GENERAL_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_GENERAL_H_ +#define OPENCV_FLANN_GENERAL_H_ + +#include "opencv2/core/version.hpp" + +#if CV_VERSION_MAJOR <= 4 + +//! @cond IGNORED + +#include "opencv2/core.hpp" + +namespace cvflann +{ + +class FLANNException : public cv::Exception +{ +public: + FLANNException(const char* message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } + + FLANNException(const cv::String& message) : cv::Exception(0, message, "", __FILE__, __LINE__) { } +}; + +} + +#define FLANN_THROW(TYPE, STR) throw FLANNException(STR) + +#else + +#define FLANN_THROW(TYPE, STR) CV_Error(TYPE, STR) + +#endif + +//! @endcond + +#endif /* OPENCV_FLANN_GENERAL_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h b/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h index b859e6a030..17f2a8e848 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/ground_truth.h @@ -1,98 +1,98 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_GROUND_TRUTH_H_ -#define OPENCV_FLANN_GROUND_TRUTH_H_ - -//! @cond IGNORED - -#include "dist.h" -#include "matrix.h" - - -namespace cvflann -{ - -template -void find_nearest(const Matrix& dataset, typename Distance::ElementType* query, int* matches, int nn, - int skip = 0, Distance distance = Distance()) -{ - typedef typename Distance::ResultType DistanceType; - int n = nn + skip; - - std::vector match(n); - std::vector dists(n); - - dists[0] = distance(dataset[0], query, dataset.cols); - match[0] = 0; - int dcnt = 1; - - for (size_t i=1; i=1 && dists[j] -void compute_ground_truth(const Matrix& dataset, const Matrix& testset, Matrix& matches, - int skip=0, Distance d = Distance()) -{ - for (size_t i=0; i(dataset, testset[i], matches[i], (int)matches.cols, skip, d); - } -} - - -} - -//! @endcond - -#endif //OPENCV_FLANN_GROUND_TRUTH_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_GROUND_TRUTH_H_ +#define OPENCV_FLANN_GROUND_TRUTH_H_ + +//! @cond IGNORED + +#include "dist.h" +#include "matrix.h" + + +namespace cvflann +{ + +template +void find_nearest(const Matrix& dataset, typename Distance::ElementType* query, int* matches, int nn, + int skip = 0, Distance distance = Distance()) +{ + typedef typename Distance::ResultType DistanceType; + int n = nn + skip; + + std::vector match(n); + std::vector dists(n); + + dists[0] = distance(dataset[0], query, dataset.cols); + match[0] = 0; + int dcnt = 1; + + for (size_t i=1; i=1 && dists[j] +void compute_ground_truth(const Matrix& dataset, const Matrix& testset, Matrix& matches, + int skip=0, Distance d = Distance()) +{ + for (size_t i=0; i(dataset, testset[i], matches[i], (int)matches.cols, skip, d); + } +} + + +} + +//! @endcond + +#endif //OPENCV_FLANN_GROUND_TRUTH_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/heap.h b/3rdParty/opencv-4.11.0/opencv2/flann/heap.h index 488073d760..8cace20449 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/heap.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/heap.h @@ -1,244 +1,244 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_HEAP_H_ -#define OPENCV_FLANN_HEAP_H_ - -//! @cond IGNORED - -#include -#include - -#include - -namespace cvflann -{ - -// TODO: Define x > y operator and use std::greater instead -template -struct greater -{ - bool operator()(const T& x, const T& y) const - { - return y < x; - } -}; - -/** - * Priority Queue Implementation - * - * The priority queue is implemented with a heap. A heap is a complete - * (full) binary tree in which each parent is less than both of its - * children, but the order of the children is unspecified. - */ -template -class Heap -{ - /** - * Storage array for the heap. - * Type T must be comparable. - */ - std::vector heap; -public: - /** - * \brief Constructs a heap with a pre-allocated capacity - * - * \param capacity heap maximum capacity - */ - Heap(const int capacity) - { - reserve(capacity); - } - - /** - * \brief Move-constructs a heap from an external vector - * - * \param vec external vector - */ - Heap(std::vector&& vec) - : heap(std::move(vec)) - { - std::make_heap(heap.begin(), heap.end(), greater()); - } - - /** - * - * \returns heap size - */ - int size() const - { - return (int)heap.size(); - } - - /** - * - * \returns heap capacity - */ - int capacity() const - { - return (int)heap.capacity(); - } - - /** - * \brief Tests if the heap is empty - * - * \returns true is heap empty, false otherwise - */ - bool empty() - { - return heap.empty(); - } - - /** - * \brief Clears the heap. - */ - void clear() - { - heap.clear(); - } - - /** - * \brief Sets the heap maximum capacity. - * - * \param capacity heap maximum capacity - */ - void reserve(const int capacity) - { - heap.reserve(capacity); - } - - /** - * \brief Inserts a new element in the heap. - * - * We select the next empty leaf node, and then keep moving any larger - * parents down until the right location is found to store this element. - * - * \param value the new element to be inserted in the heap - */ - void insert(T value) - { - /* If heap is full, then return without adding this element. */ - if (size() == capacity()) { - return; - } - - heap.push_back(value); - std::push_heap(heap.begin(), heap.end(), greater()); - } - - /** - * \brief Returns the node of minimum value from the heap (top of the heap). - * - * \param[out] value parameter used to return the min element - * \returns false if heap empty - */ - bool popMin(T& value) - { - if (empty()) { - return false; - } - - value = heap[0]; - std::pop_heap(heap.begin(), heap.end(), greater()); - heap.pop_back(); - - return true; /* Return old last node. */ - } - - /** - * \brief Returns a shared heap for the given memory pool ID. - * - * It constructs the heap if it does not already exists. - * - * \param poolId a user-chosen hashable ID for identifying the heap. - * For thread-safe operations, using current thread ID is a good choice. - * \param capacity heap maximum capacity - * \param iterThreshold remove heaps that were not reused for more than specified iterations count - * if iterThreshold value is less 2, it will be internally adjusted to twice the number of CPU threads - * \returns pointer to the heap - */ - template - static cv::Ptr> getPooledInstance( - const HashableT& poolId, const int capacity, int iterThreshold = 0) - { - static cv::Mutex mutex; - const cv::AutoLock lock(mutex); - - struct HeapMapValueType { - cv::Ptr> heapPtr; - int iterCounter; - }; - typedef std::unordered_map HeapMapType; - - static HeapMapType heapsPool; - typename HeapMapType::iterator heapIt = heapsPool.find(poolId); - - if (heapIt == heapsPool.end()) - { - // Construct the heap as it does not already exists - HeapMapValueType heapAndTimePair = {cv::makePtr>(capacity), 0}; - const std::pair& emplaceResult = heapsPool.emplace(poolId, std::move(heapAndTimePair)); - CV_CheckEQ(static_cast(emplaceResult.second), 1, "Failed to insert the heap into its memory pool"); - heapIt = emplaceResult.first; - } - else - { - CV_CheckEQ(heapIt->second.heapPtr.use_count(), 1, "Cannot modify a heap that is currently accessed by another caller"); - heapIt->second.heapPtr->clear(); - heapIt->second.heapPtr->reserve(capacity); - heapIt->second.iterCounter = 0; - } - - if (iterThreshold <= 1) { - iterThreshold = 2 * cv::getNumThreads(); - } - - // Remove heaps that were not reused for more than given iterThreshold - typename HeapMapType::iterator cleanupIt = heapsPool.begin(); - while (cleanupIt != heapsPool.end()) - { - if (cleanupIt->second.iterCounter++ > iterThreshold) - { - CV_Assert(cleanupIt != heapIt); - cleanupIt = heapsPool.erase(cleanupIt); - continue; - } - ++cleanupIt; - } - - return heapIt->second.heapPtr; - } -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_HEAP_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_HEAP_H_ +#define OPENCV_FLANN_HEAP_H_ + +//! @cond IGNORED + +#include +#include + +#include + +namespace cvflann +{ + +// TODO: Define x > y operator and use std::greater instead +template +struct greater +{ + bool operator()(const T& x, const T& y) const + { + return y < x; + } +}; + +/** + * Priority Queue Implementation + * + * The priority queue is implemented with a heap. A heap is a complete + * (full) binary tree in which each parent is less than both of its + * children, but the order of the children is unspecified. + */ +template +class Heap +{ + /** + * Storage array for the heap. + * Type T must be comparable. + */ + std::vector heap; +public: + /** + * \brief Constructs a heap with a pre-allocated capacity + * + * \param capacity heap maximum capacity + */ + Heap(const int capacity) + { + reserve(capacity); + } + + /** + * \brief Move-constructs a heap from an external vector + * + * \param vec external vector + */ + Heap(std::vector&& vec) + : heap(std::move(vec)) + { + std::make_heap(heap.begin(), heap.end(), greater()); + } + + /** + * + * \returns heap size + */ + int size() const + { + return (int)heap.size(); + } + + /** + * + * \returns heap capacity + */ + int capacity() const + { + return (int)heap.capacity(); + } + + /** + * \brief Tests if the heap is empty + * + * \returns true is heap empty, false otherwise + */ + bool empty() + { + return heap.empty(); + } + + /** + * \brief Clears the heap. + */ + void clear() + { + heap.clear(); + } + + /** + * \brief Sets the heap maximum capacity. + * + * \param capacity heap maximum capacity + */ + void reserve(const int capacity) + { + heap.reserve(capacity); + } + + /** + * \brief Inserts a new element in the heap. + * + * We select the next empty leaf node, and then keep moving any larger + * parents down until the right location is found to store this element. + * + * \param value the new element to be inserted in the heap + */ + void insert(T value) + { + /* If heap is full, then return without adding this element. */ + if (size() == capacity()) { + return; + } + + heap.push_back(value); + std::push_heap(heap.begin(), heap.end(), greater()); + } + + /** + * \brief Returns the node of minimum value from the heap (top of the heap). + * + * \param[out] value parameter used to return the min element + * \returns false if heap empty + */ + bool popMin(T& value) + { + if (empty()) { + return false; + } + + value = heap[0]; + std::pop_heap(heap.begin(), heap.end(), greater()); + heap.pop_back(); + + return true; /* Return old last node. */ + } + + /** + * \brief Returns a shared heap for the given memory pool ID. + * + * It constructs the heap if it does not already exists. + * + * \param poolId a user-chosen hashable ID for identifying the heap. + * For thread-safe operations, using current thread ID is a good choice. + * \param capacity heap maximum capacity + * \param iterThreshold remove heaps that were not reused for more than specified iterations count + * if iterThreshold value is less 2, it will be internally adjusted to twice the number of CPU threads + * \returns pointer to the heap + */ + template + static cv::Ptr> getPooledInstance( + const HashableT& poolId, const int capacity, int iterThreshold = 0) + { + static cv::Mutex mutex; + const cv::AutoLock lock(mutex); + + struct HeapMapValueType { + cv::Ptr> heapPtr; + int iterCounter; + }; + typedef std::unordered_map HeapMapType; + + static HeapMapType heapsPool; + typename HeapMapType::iterator heapIt = heapsPool.find(poolId); + + if (heapIt == heapsPool.end()) + { + // Construct the heap as it does not already exists + HeapMapValueType heapAndTimePair = {cv::makePtr>(capacity), 0}; + const std::pair& emplaceResult = heapsPool.emplace(poolId, std::move(heapAndTimePair)); + CV_CheckEQ(static_cast(emplaceResult.second), 1, "Failed to insert the heap into its memory pool"); + heapIt = emplaceResult.first; + } + else + { + CV_CheckEQ(heapIt->second.heapPtr.use_count(), 1, "Cannot modify a heap that is currently accessed by another caller"); + heapIt->second.heapPtr->clear(); + heapIt->second.heapPtr->reserve(capacity); + heapIt->second.iterCounter = 0; + } + + if (iterThreshold <= 1) { + iterThreshold = 2 * cv::getNumThreads(); + } + + // Remove heaps that were not reused for more than given iterThreshold + typename HeapMapType::iterator cleanupIt = heapsPool.begin(); + while (cleanupIt != heapsPool.end()) + { + if (cleanupIt->second.iterCounter++ > iterThreshold) + { + CV_Assert(cleanupIt != heapIt); + cleanupIt = heapsPool.erase(cleanupIt); + continue; + } + ++cleanupIt; + } + + return heapIt->second.heapPtr; + } +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_HEAP_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h index 31eef2b406..60662e7714 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/hierarchical_clustering_index.h @@ -1,846 +1,846 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ -#define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include -#include - -#include "general.h" -#include "nn_index.h" -#include "dist.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - - -namespace cvflann -{ - -struct HierarchicalClusteringIndexParams : public IndexParams -{ - HierarchicalClusteringIndexParams(int branching = 32, - flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, - int trees = 4, int leaf_size = 100) - { - (*this)["algorithm"] = FLANN_INDEX_HIERARCHICAL; - // The branching factor used in the hierarchical clustering - (*this)["branching"] = branching; - // Algorithm used for picking the initial cluster centers - (*this)["centers_init"] = centers_init; - // number of parallel trees to build - (*this)["trees"] = trees; - // maximum leaf size - (*this)["leaf_size"] = leaf_size; - } -}; - - -/** - * Hierarchical index - * - * Contains a tree constructed through a hierarchical clustering - * and other information for indexing a set of points for nearest-neighbour matching. - */ -template -class HierarchicalClusteringIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - -private: - - - typedef void (HierarchicalClusteringIndex::* centersAlgFunction)(int, int*, int, int*, int&); - - /** - * The function used for choosing the cluster centers. - */ - centersAlgFunction chooseCenters; - - - - /** - * Chooses the initial centers in the k-means clustering in a random manner. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * indices_length = length of indices vector - * - */ - void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length) - { - UniqueRandom r(indices_length); - - int index; - for (index=0; index=0 && rnd < n); - - centers[0] = dsindices[rnd]; - - int index; - for (index=1; indexbest_val) { - best_val = dist; - best_index = j; - } - } - if (best_index!=-1) { - centers[index] = dsindices[best_index]; - } - else { - break; - } - } - centers_length = index; - } - - - /** - * Chooses the initial centers in the k-means using the algorithm - * proposed in the KMeans++ paper: - * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding - * - * Implementation of this function was converted from the one provided in Arthur's code. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * Returns: - */ - void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length) - { - int n = indices_length; - - double currentPot = 0; - DistanceType* closestDistSq = new DistanceType[n]; - - // Choose one random center and set the closestDistSq values - int index = rand_int(n); - CV_DbgAssert(index >=0 && index < n); - centers[0] = dsindices[index]; - - // Computing distance^2 will have the advantage of even higher probability further to pick new centers - // far from previous centers (and this complies to "k-means++: the advantages of careful seeding" article) - for (int i = 0; i < n; i++) { - closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); - closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); - currentPot += closestDistSq[i]; - } - - - const int numLocalTries = 1; - - // Choose each center - int centerCount; - for (centerCount = 1; centerCount < k; centerCount++) { - - // Repeat several trials - double bestNewPot = -1; - int bestNewIndex = 0; - for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { - - // Choose our center - have to be slightly careful to return a valid answer even accounting - // for possible rounding errors - double randVal = rand_double(currentPot); - for (index = 0; index < n-1; index++) { - if (randVal <= closestDistSq[index]) break; - else randVal -= closestDistSq[index]; - } - - // Compute the new potential - double newPot = 0; - for (int i = 0; i < n; i++) { - DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); - newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - - // Store the best result - if ((bestNewPot < 0)||(newPot < bestNewPot)) { - bestNewPot = newPot; - bestNewIndex = index; - } - } - - // Add the appropriate center - centers[centerCount] = dsindices[bestNewIndex]; - currentPot = bestNewPot; - for (int i = 0; i < n; i++) { - DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols); - closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - } - - centers_length = centerCount; - - delete[] closestDistSq; - } - - - /** - * Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel): - * select the first point of the list as a candidate, then parse the points list. If another - * point is further than current candidate from the other centers, test if it is a good center - * of a local aggregation. If it is, replace current candidate by this point. And so on... - * - * Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points, - * this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex - * class that pick centers among existing points instead of computing the barycenters, there is a real - * improvement. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * Returns: - */ - void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length) - { - const float kSpeedUpFactor = 1.3f; - - int n = indices_length; - - DistanceType* closestDistSq = new DistanceType[n]; - - // Choose one random center and set the closestDistSq values - int index = rand_int(n); - CV_DbgAssert(index >=0 && index < n); - centers[0] = dsindices[index]; - - for (int i = 0; i < n; i++) { - closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); - } - - - // Choose each center - int centerCount; - for (centerCount = 1; centerCount < k; centerCount++) { - - // Repeat several trials - double bestNewPot = -1; - int bestNewIndex = 0; - DistanceType furthest = 0; - for (index = 0; index < n; index++) { - - // We will test only the potential of the points further than current candidate - if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) { - - // Compute the new potential - double newPot = 0; - for (int i = 0; i < n; i++) { - newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols) - , closestDistSq[i] ); - } - - // Store the best result - if ((bestNewPot < 0)||(newPot <= bestNewPot)) { - bestNewPot = newPot; - bestNewIndex = index; - furthest = closestDistSq[index]; - } - } - } - - // Add the appropriate center - centers[centerCount] = dsindices[bestNewIndex]; - for (int i = 0; i < n; i++) { - closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols) - , closestDistSq[i] ); - } - } - - centers_length = centerCount; - - delete[] closestDistSq; - } - - -public: - - - /** - * Index constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the hierarchical k-means algorithm - */ - HierarchicalClusteringIndex(const Matrix& inputData, const IndexParams& index_params = HierarchicalClusteringIndexParams(), - Distance d = Distance()) - : dataset(inputData), params(index_params), root(NULL), indices(NULL), distance(d) - { - memoryCounter = 0; - - size_ = dataset.rows; - veclen_ = dataset.cols; - - branching_ = get_param(params,"branching",32); - centers_init_ = get_param(params,"centers_init", FLANN_CENTERS_RANDOM); - trees_ = get_param(params,"trees",4); - leaf_size_ = get_param(params,"leaf_size",100); - - if (centers_init_==FLANN_CENTERS_RANDOM) { - chooseCenters = &HierarchicalClusteringIndex::chooseCentersRandom; - } - else if (centers_init_==FLANN_CENTERS_GONZALES) { - chooseCenters = &HierarchicalClusteringIndex::chooseCentersGonzales; - } - else if (centers_init_==FLANN_CENTERS_KMEANSPP) { - chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp; - } - else if (centers_init_==FLANN_CENTERS_GROUPWISE) { - chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser; - } - else { - FLANN_THROW(cv::Error::StsError, "Unknown algorithm for choosing initial centers."); - } - - root = new NodePtr[trees_]; - indices = new int*[trees_]; - - for (int i=0; i(); - computeClustering(root[i], indices[i], (int)size_, branching_,0); - } - } - - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_HIERARCHICAL; - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, branching_); - save_value(stream, trees_); - save_value(stream, centers_init_); - save_value(stream, leaf_size_); - save_value(stream, memoryCounter); - for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - - const int maxChecks = get_param(searchParams,"checks",32); - const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); - - // Priority queue storing intermediate branches in the best-bin-first search - const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); - - std::vector checked(size_,false); - int checks = 0; - for (int i=0; i= maxChecks) && result.full()) - break; - } - - BranchSt branch; - while (heap->popMin(branch) && (checks BranchSt; - - - - void save_tree(FILE* stream, NodePtr node, int num) - { - save_value(stream, *node); - if (node->childs==NULL) { - int indices_offset = (int)(node->indices - indices[num]); - save_value(stream, indices_offset); - } - else { - for(int i=0; ichilds[i], num); - } - } - } - - - void load_tree(FILE* stream, NodePtr& node, int num) - { - node = pool.allocate(); - load_value(stream, *node); - if (node->childs==NULL) { - int indices_offset; - load_value(stream, indices_offset); - node->indices = indices[num] + indices_offset; - } - else { - node->childs = pool.allocate(branching_); - for(int i=0; ichilds[i], num); - } - } - } - - - /** - * Release the inner elements of indices[] - */ - void free_indices() - { - if (indices!=NULL) { - for(int i=0; inew_dist) { - labels[i] = j; - dist = new_dist; - } - } - cost += dist; - } - } - - /** - * The method responsible with actually doing the recursive hierarchical - * clustering - * - * Params: - * node = the node to cluster - * indices = indices of the points belonging to the current node - * branching = the branching factor to use in the clustering - * - * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) - */ - void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level) - { - node->size = indices_length; - node->level = level; - - if (indices_length < leaf_size_) { // leaf node - node->indices = dsindices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - std::vector centers(branching); - std::vector labels(indices_length); - - int centers_length; - (this->*chooseCenters)(branching, dsindices, indices_length, ¢ers[0], centers_length); - - if (centers_lengthindices = dsindices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - - // assign points to clusters - DistanceType cost; - computeLabels(dsindices, indices_length, ¢ers[0], centers_length, &labels[0], cost); - - node->childs = pool.allocate(branching); - int start = 0; - int end = start; - for (int i=0; ichilds[i] = pool.allocate(); - node->childs[i]->pivot = centers[i]; - node->childs[i]->indices = NULL; - computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1); - start=end; - } - } - - - - /** - * Performs one descent in the hierarchical k-means tree. The branches not - * visited are stored in a priority queue. - * - * Params: - * node = node to explore - * result = container for the k-nearest neighbors found - * vec = query points - * checks = how many points in the dataset have been checked so far - * maxChecks = maximum dataset points to checks - */ - - - void findNN(NodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, - const cv::Ptr>& heap, std::vector& checked, bool explore_all_trees = false) - { - if (node->childs==NULL) { - if (!explore_all_trees && (checks>=maxChecks) && result.full()) { - return; - } - for (int i=0; isize; ++i) { - int index = node->indices[i]; - if (!checked[index]) { - DistanceType dist = distance(dataset[index], vec, veclen_); - result.addPoint(dist, index); - checked[index] = true; - ++checks; - } - } - } - else { - DistanceType* domain_distances = new DistanceType[branching_]; - int best_index = 0; - domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_); - for (int i=1; ichilds[i]->pivot], veclen_); - if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); - } - } - delete[] domain_distances; - findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked, explore_all_trees); - } - } - -private: - - - /** - * The dataset used by this index - */ - const Matrix dataset; - - /** - * Parameters used by this index - */ - IndexParams params; - - - /** - * Number of features in the dataset. - */ - size_t size_; - - /** - * Length of each feature. - */ - size_t veclen_; - - /** - * The root node in the tree. - */ - NodePtr* root; - - /** - * Array of indices to vectors in the dataset. - */ - int** indices; - - - /** - * The distance - */ - Distance distance; - - /** - * Pooled memory allocator. - * - * Using a pooled memory allocator is more efficient - * than allocating memory directly when there is a large - * number small of memory allocations. - */ - PooledAllocator pool; - - /** - * Memory occupied by the index. - */ - int memoryCounter; - - /** index parameters */ - int branching_; - int trees_; - flann_centers_init_t centers_init_; - int leaf_size_; - - -}; - -} - -//! @endcond - -#endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ +#define OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include +#include + +#include "general.h" +#include "nn_index.h" +#include "dist.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + + +namespace cvflann +{ + +struct HierarchicalClusteringIndexParams : public IndexParams +{ + HierarchicalClusteringIndexParams(int branching = 32, + flann_centers_init_t centers_init = FLANN_CENTERS_RANDOM, + int trees = 4, int leaf_size = 100) + { + (*this)["algorithm"] = FLANN_INDEX_HIERARCHICAL; + // The branching factor used in the hierarchical clustering + (*this)["branching"] = branching; + // Algorithm used for picking the initial cluster centers + (*this)["centers_init"] = centers_init; + // number of parallel trees to build + (*this)["trees"] = trees; + // maximum leaf size + (*this)["leaf_size"] = leaf_size; + } +}; + + +/** + * Hierarchical index + * + * Contains a tree constructed through a hierarchical clustering + * and other information for indexing a set of points for nearest-neighbour matching. + */ +template +class HierarchicalClusteringIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + +private: + + + typedef void (HierarchicalClusteringIndex::* centersAlgFunction)(int, int*, int, int*, int&); + + /** + * The function used for choosing the cluster centers. + */ + centersAlgFunction chooseCenters; + + + + /** + * Chooses the initial centers in the k-means clustering in a random manner. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * indices_length = length of indices vector + * + */ + void chooseCentersRandom(int k, int* dsindices, int indices_length, int* centers, int& centers_length) + { + UniqueRandom r(indices_length); + + int index; + for (index=0; index=0 && rnd < n); + + centers[0] = dsindices[rnd]; + + int index; + for (index=1; indexbest_val) { + best_val = dist; + best_index = j; + } + } + if (best_index!=-1) { + centers[index] = dsindices[best_index]; + } + else { + break; + } + } + centers_length = index; + } + + + /** + * Chooses the initial centers in the k-means using the algorithm + * proposed in the KMeans++ paper: + * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding + * + * Implementation of this function was converted from the one provided in Arthur's code. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * Returns: + */ + void chooseCentersKMeanspp(int k, int* dsindices, int indices_length, int* centers, int& centers_length) + { + int n = indices_length; + + double currentPot = 0; + DistanceType* closestDistSq = new DistanceType[n]; + + // Choose one random center and set the closestDistSq values + int index = rand_int(n); + CV_DbgAssert(index >=0 && index < n); + centers[0] = dsindices[index]; + + // Computing distance^2 will have the advantage of even higher probability further to pick new centers + // far from previous centers (and this complies to "k-means++: the advantages of careful seeding" article) + for (int i = 0; i < n; i++) { + closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); + closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); + currentPot += closestDistSq[i]; + } + + + const int numLocalTries = 1; + + // Choose each center + int centerCount; + for (centerCount = 1; centerCount < k; centerCount++) { + + // Repeat several trials + double bestNewPot = -1; + int bestNewIndex = 0; + for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { + + // Choose our center - have to be slightly careful to return a valid answer even accounting + // for possible rounding errors + double randVal = rand_double(currentPot); + for (index = 0; index < n-1; index++) { + if (randVal <= closestDistSq[index]) break; + else randVal -= closestDistSq[index]; + } + + // Compute the new potential + double newPot = 0; + for (int i = 0; i < n; i++) { + DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); + newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + + // Store the best result + if ((bestNewPot < 0)||(newPot < bestNewPot)) { + bestNewPot = newPot; + bestNewIndex = index; + } + } + + // Add the appropriate center + centers[centerCount] = dsindices[bestNewIndex]; + currentPot = bestNewPot; + for (int i = 0; i < n; i++) { + DistanceType dist = distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols); + closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + } + + centers_length = centerCount; + + delete[] closestDistSq; + } + + + /** + * Chooses the initial centers in a way inspired by Gonzales (by Pierre-Emmanuel Viel): + * select the first point of the list as a candidate, then parse the points list. If another + * point is further than current candidate from the other centers, test if it is a good center + * of a local aggregation. If it is, replace current candidate by this point. And so on... + * + * Used with KMeansIndex that computes centers coordinates by averaging positions of clusters points, + * this doesn't make a real difference with previous methods. But used with HierarchicalClusteringIndex + * class that pick centers among existing points instead of computing the barycenters, there is a real + * improvement. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * Returns: + */ + void GroupWiseCenterChooser(int k, int* dsindices, int indices_length, int* centers, int& centers_length) + { + const float kSpeedUpFactor = 1.3f; + + int n = indices_length; + + DistanceType* closestDistSq = new DistanceType[n]; + + // Choose one random center and set the closestDistSq values + int index = rand_int(n); + CV_DbgAssert(index >=0 && index < n); + centers[0] = dsindices[index]; + + for (int i = 0; i < n; i++) { + closestDistSq[i] = distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols); + } + + + // Choose each center + int centerCount; + for (centerCount = 1; centerCount < k; centerCount++) { + + // Repeat several trials + double bestNewPot = -1; + int bestNewIndex = 0; + DistanceType furthest = 0; + for (index = 0; index < n; index++) { + + // We will test only the potential of the points further than current candidate + if( closestDistSq[index] > kSpeedUpFactor * (float)furthest ) { + + // Compute the new potential + double newPot = 0; + for (int i = 0; i < n; i++) { + newPot += std::min( distance(dataset[dsindices[i]], dataset[dsindices[index]], dataset.cols) + , closestDistSq[i] ); + } + + // Store the best result + if ((bestNewPot < 0)||(newPot <= bestNewPot)) { + bestNewPot = newPot; + bestNewIndex = index; + furthest = closestDistSq[index]; + } + } + } + + // Add the appropriate center + centers[centerCount] = dsindices[bestNewIndex]; + for (int i = 0; i < n; i++) { + closestDistSq[i] = std::min( distance(dataset[dsindices[i]], dataset[dsindices[bestNewIndex]], dataset.cols) + , closestDistSq[i] ); + } + } + + centers_length = centerCount; + + delete[] closestDistSq; + } + + +public: + + + /** + * Index constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the hierarchical k-means algorithm + */ + HierarchicalClusteringIndex(const Matrix& inputData, const IndexParams& index_params = HierarchicalClusteringIndexParams(), + Distance d = Distance()) + : dataset(inputData), params(index_params), root(NULL), indices(NULL), distance(d) + { + memoryCounter = 0; + + size_ = dataset.rows; + veclen_ = dataset.cols; + + branching_ = get_param(params,"branching",32); + centers_init_ = get_param(params,"centers_init", FLANN_CENTERS_RANDOM); + trees_ = get_param(params,"trees",4); + leaf_size_ = get_param(params,"leaf_size",100); + + if (centers_init_==FLANN_CENTERS_RANDOM) { + chooseCenters = &HierarchicalClusteringIndex::chooseCentersRandom; + } + else if (centers_init_==FLANN_CENTERS_GONZALES) { + chooseCenters = &HierarchicalClusteringIndex::chooseCentersGonzales; + } + else if (centers_init_==FLANN_CENTERS_KMEANSPP) { + chooseCenters = &HierarchicalClusteringIndex::chooseCentersKMeanspp; + } + else if (centers_init_==FLANN_CENTERS_GROUPWISE) { + chooseCenters = &HierarchicalClusteringIndex::GroupWiseCenterChooser; + } + else { + FLANN_THROW(cv::Error::StsError, "Unknown algorithm for choosing initial centers."); + } + + root = new NodePtr[trees_]; + indices = new int*[trees_]; + + for (int i=0; i(); + computeClustering(root[i], indices[i], (int)size_, branching_,0); + } + } + + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_HIERARCHICAL; + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, branching_); + save_value(stream, trees_); + save_value(stream, centers_init_); + save_value(stream, leaf_size_); + save_value(stream, memoryCounter); + for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + + const int maxChecks = get_param(searchParams,"checks",32); + const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); + + // Priority queue storing intermediate branches in the best-bin-first search + const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); + + std::vector checked(size_,false); + int checks = 0; + for (int i=0; i= maxChecks) && result.full()) + break; + } + + BranchSt branch; + while (heap->popMin(branch) && (checks BranchSt; + + + + void save_tree(FILE* stream, NodePtr node, int num) + { + save_value(stream, *node); + if (node->childs==NULL) { + int indices_offset = (int)(node->indices - indices[num]); + save_value(stream, indices_offset); + } + else { + for(int i=0; ichilds[i], num); + } + } + } + + + void load_tree(FILE* stream, NodePtr& node, int num) + { + node = pool.allocate(); + load_value(stream, *node); + if (node->childs==NULL) { + int indices_offset; + load_value(stream, indices_offset); + node->indices = indices[num] + indices_offset; + } + else { + node->childs = pool.allocate(branching_); + for(int i=0; ichilds[i], num); + } + } + } + + + /** + * Release the inner elements of indices[] + */ + void free_indices() + { + if (indices!=NULL) { + for(int i=0; inew_dist) { + labels[i] = j; + dist = new_dist; + } + } + cost += dist; + } + } + + /** + * The method responsible with actually doing the recursive hierarchical + * clustering + * + * Params: + * node = the node to cluster + * indices = indices of the points belonging to the current node + * branching = the branching factor to use in the clustering + * + * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) + */ + void computeClustering(NodePtr node, int* dsindices, int indices_length, int branching, int level) + { + node->size = indices_length; + node->level = level; + + if (indices_length < leaf_size_) { // leaf node + node->indices = dsindices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + std::vector centers(branching); + std::vector labels(indices_length); + + int centers_length; + (this->*chooseCenters)(branching, dsindices, indices_length, ¢ers[0], centers_length); + + if (centers_lengthindices = dsindices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + + // assign points to clusters + DistanceType cost; + computeLabels(dsindices, indices_length, ¢ers[0], centers_length, &labels[0], cost); + + node->childs = pool.allocate(branching); + int start = 0; + int end = start; + for (int i=0; ichilds[i] = pool.allocate(); + node->childs[i]->pivot = centers[i]; + node->childs[i]->indices = NULL; + computeClustering(node->childs[i],dsindices+start, end-start, branching, level+1); + start=end; + } + } + + + + /** + * Performs one descent in the hierarchical k-means tree. The branches not + * visited are stored in a priority queue. + * + * Params: + * node = node to explore + * result = container for the k-nearest neighbors found + * vec = query points + * checks = how many points in the dataset have been checked so far + * maxChecks = maximum dataset points to checks + */ + + + void findNN(NodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, + const cv::Ptr>& heap, std::vector& checked, bool explore_all_trees = false) + { + if (node->childs==NULL) { + if (!explore_all_trees && (checks>=maxChecks) && result.full()) { + return; + } + for (int i=0; isize; ++i) { + int index = node->indices[i]; + if (!checked[index]) { + DistanceType dist = distance(dataset[index], vec, veclen_); + result.addPoint(dist, index); + checked[index] = true; + ++checks; + } + } + } + else { + DistanceType* domain_distances = new DistanceType[branching_]; + int best_index = 0; + domain_distances[best_index] = distance(vec, dataset[node->childs[best_index]->pivot], veclen_); + for (int i=1; ichilds[i]->pivot], veclen_); + if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); + } + } + delete[] domain_distances; + findNN(node->childs[best_index],result,vec, checks, maxChecks, heap, checked, explore_all_trees); + } + } + +private: + + + /** + * The dataset used by this index + */ + const Matrix dataset; + + /** + * Parameters used by this index + */ + IndexParams params; + + + /** + * Number of features in the dataset. + */ + size_t size_; + + /** + * Length of each feature. + */ + size_t veclen_; + + /** + * The root node in the tree. + */ + NodePtr* root; + + /** + * Array of indices to vectors in the dataset. + */ + int** indices; + + + /** + * The distance + */ + Distance distance; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool; + + /** + * Memory occupied by the index. + */ + int memoryCounter; + + /** index parameters */ + int branching_; + int trees_; + flann_centers_init_t centers_init_; + int leaf_size_; + + +}; + +} + +//! @endcond + +#endif /* OPENCV_FLANN_HIERARCHICAL_CLUSTERING_INDEX_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h b/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h index 972c453984..4c00143326 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/index_testing.h @@ -1,319 +1,319 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_INDEX_TESTING_H_ -#define OPENCV_FLANN_INDEX_TESTING_H_ - -//! @cond IGNORED - -#include -#include - -#include "matrix.h" -#include "nn_index.h" -#include "result_set.h" -#include "logger.h" -#include "timer.h" - - -namespace cvflann -{ - -inline int countCorrectMatches(int* neighbors, int* groundTruth, int n) -{ - int count = 0; - for (int i=0; i -typename Distance::ResultType computeDistanceRaport(const Matrix& inputData, typename Distance::ElementType* target, - int* neighbors, int* groundTruth, int veclen, int n, const Distance& distance) -{ - typedef typename Distance::ResultType DistanceType; - - DistanceType ret = 0; - for (int i=0; i -float search_with_ground_truth(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, int nn, int checks, - float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches) -{ - typedef typename Distance::ResultType DistanceType; - - if (matches.cols resultSet(nn+skipMatches); - SearchParams searchParams(checks); - - std::vector indices(nn+skipMatches); - std::vector dists(nn+skipMatches); - int* neighbors = &indices[skipMatches]; - - int correct = 0; - DistanceType distR = 0; - StartStopTimer t; - int repeats = 0; - while (t.value<0.2) { - repeats++; - t.start(); - correct = 0; - distR = 0; - for (size_t i = 0; i < testData.rows; i++) { - resultSet.init(&indices[0], &dists[0]); - index.findNeighbors(resultSet, testData[i], searchParams); - - correct += countCorrectMatches(neighbors,matches[i], nn); - distR += computeDistanceRaport(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance); - } - t.stop(); - } - time = float(t.value/repeats); - - float precicion = (float)correct/(nn*testData.rows); - - dist = distR/(testData.rows*nn); - - Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n", - checks, precicion, time, 1000.0 * time / testData.rows, dist); - - return precicion; -} - - -template -float test_index_checks(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, - int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0) -{ - typedef typename Distance::ResultType DistanceType; - - Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); - Logger::info("---------------------------------------------------------\n"); - - float time = 0; - DistanceType dist = 0; - precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches); - - return time; -} - -template -float test_index_precision(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, - float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0) -{ - typedef typename Distance::ResultType DistanceType; - const float SEARCH_EPS = 0.001f; - - Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); - Logger::info("---------------------------------------------------------\n"); - - int c2 = 1; - float p2; - int c1 = 1; - //float p1; - float time; - DistanceType dist; - - p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); - - if (p2>precision) { - Logger::info("Got as close as I can\n"); - checks = c2; - return time; - } - - while (p2SEARCH_EPS) { - Logger::info("Start linear estimation\n"); - // after we got to values in the vecinity of the desired precision - // use linear approximation get a better estimation - - cx = (c1+c2)/2; - realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); - while (fabs(realPrecision-precision)>SEARCH_EPS) { - - if (realPrecision -void test_index_precisions(NNIndex& index, const Matrix& inputData, - const Matrix& testData, const Matrix& matches, - float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0) -{ - typedef typename Distance::ResultType DistanceType; - - const float SEARCH_EPS = 0.001; - - // make sure precisions array is sorted - std::sort(precisions, precisions+precisions_length); - - int pindex = 0; - float precision = precisions[pindex]; - - Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); - Logger::info("---------------------------------------------------------\n"); - - int c2 = 1; - float p2; - - int c1 = 1; - - float time; - DistanceType dist; - - p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); - - // if precision for 1 run down the tree is already - // better then some of the requested precisions, then - // skip those - while (precisions[pindex] 0)&&(time > maxTime)&&(p2SEARCH_EPS) { - Logger::info("Start linear estimation\n"); - // after we got to values in the vecinity of the desired precision - // use linear approximation get a better estimation - - cx = (c1+c2)/2; - realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); - while (fabs(realPrecision-precision)>SEARCH_EPS) { - - if (realPrecision +#include + +#include "matrix.h" +#include "nn_index.h" +#include "result_set.h" +#include "logger.h" +#include "timer.h" + + +namespace cvflann +{ + +inline int countCorrectMatches(int* neighbors, int* groundTruth, int n) +{ + int count = 0; + for (int i=0; i +typename Distance::ResultType computeDistanceRaport(const Matrix& inputData, typename Distance::ElementType* target, + int* neighbors, int* groundTruth, int veclen, int n, const Distance& distance) +{ + typedef typename Distance::ResultType DistanceType; + + DistanceType ret = 0; + for (int i=0; i +float search_with_ground_truth(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, int nn, int checks, + float& time, typename Distance::ResultType& dist, const Distance& distance, int skipMatches) +{ + typedef typename Distance::ResultType DistanceType; + + if (matches.cols resultSet(nn+skipMatches); + SearchParams searchParams(checks); + + std::vector indices(nn+skipMatches); + std::vector dists(nn+skipMatches); + int* neighbors = &indices[skipMatches]; + + int correct = 0; + DistanceType distR = 0; + StartStopTimer t; + int repeats = 0; + while (t.value<0.2) { + repeats++; + t.start(); + correct = 0; + distR = 0; + for (size_t i = 0; i < testData.rows; i++) { + resultSet.init(&indices[0], &dists[0]); + index.findNeighbors(resultSet, testData[i], searchParams); + + correct += countCorrectMatches(neighbors,matches[i], nn); + distR += computeDistanceRaport(inputData, testData[i], neighbors, matches[i], (int)testData.cols, nn, distance); + } + t.stop(); + } + time = float(t.value/repeats); + + float precicion = (float)correct/(nn*testData.rows); + + dist = distR/(testData.rows*nn); + + Logger::info("%8d %10.4g %10.5g %10.5g %10.5g\n", + checks, precicion, time, 1000.0 * time / testData.rows, dist); + + return precicion; +} + + +template +float test_index_checks(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, + int checks, float& precision, const Distance& distance, int nn = 1, int skipMatches = 0) +{ + typedef typename Distance::ResultType DistanceType; + + Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); + Logger::info("---------------------------------------------------------\n"); + + float time = 0; + DistanceType dist = 0; + precision = search_with_ground_truth(index, inputData, testData, matches, nn, checks, time, dist, distance, skipMatches); + + return time; +} + +template +float test_index_precision(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, + float precision, int& checks, const Distance& distance, int nn = 1, int skipMatches = 0) +{ + typedef typename Distance::ResultType DistanceType; + const float SEARCH_EPS = 0.001f; + + Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); + Logger::info("---------------------------------------------------------\n"); + + int c2 = 1; + float p2; + int c1 = 1; + //float p1; + float time; + DistanceType dist; + + p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); + + if (p2>precision) { + Logger::info("Got as close as I can\n"); + checks = c2; + return time; + } + + while (p2SEARCH_EPS) { + Logger::info("Start linear estimation\n"); + // after we got to values in the vecinity of the desired precision + // use linear approximation get a better estimation + + cx = (c1+c2)/2; + realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); + while (fabs(realPrecision-precision)>SEARCH_EPS) { + + if (realPrecision +void test_index_precisions(NNIndex& index, const Matrix& inputData, + const Matrix& testData, const Matrix& matches, + float* precisions, int precisions_length, const Distance& distance, int nn = 1, int skipMatches = 0, float maxTime = 0) +{ + typedef typename Distance::ResultType DistanceType; + + const float SEARCH_EPS = 0.001; + + // make sure precisions array is sorted + std::sort(precisions, precisions+precisions_length); + + int pindex = 0; + float precision = precisions[pindex]; + + Logger::info(" Nodes Precision(%) Time(s) Time/vec(ms) Mean dist\n"); + Logger::info("---------------------------------------------------------\n"); + + int c2 = 1; + float p2; + + int c1 = 1; + + float time; + DistanceType dist; + + p2 = search_with_ground_truth(index, inputData, testData, matches, nn, c2, time, dist, distance, skipMatches); + + // if precision for 1 run down the tree is already + // better then some of the requested precisions, then + // skip those + while (precisions[pindex] 0)&&(time > maxTime)&&(p2SEARCH_EPS) { + Logger::info("Start linear estimation\n"); + // after we got to values in the vecinity of the desired precision + // use linear approximation get a better estimation + + cx = (c1+c2)/2; + realPrecision = search_with_ground_truth(index, inputData, testData, matches, nn, cx, time, dist, distance, skipMatches); + while (fabs(realPrecision-precision)>SEARCH_EPS) { + + if (realPrecision -#include -#include - -#include "nn_index.h" -#include "dynamic_bitset.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - - -namespace cvflann -{ - -struct KDTreeIndexParams : public IndexParams -{ - KDTreeIndexParams(int trees = 4) - { - (*this)["algorithm"] = FLANN_INDEX_KDTREE; - (*this)["trees"] = trees; - } -}; - - -/** - * Randomized kd-tree index - * - * Contains the k-d trees and other information for indexing a set of points - * for nearest-neighbor matching. - */ -template -class KDTreeIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - - /** - * KDTree constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the kdtree algorithm - */ - KDTreeIndex(const Matrix& inputData, const IndexParams& params = KDTreeIndexParams(), - Distance d = Distance() ) : - dataset_(inputData), index_params_(params), distance_(d) - { - size_ = dataset_.rows; - veclen_ = dataset_.cols; - - trees_ = get_param(index_params_,"trees",4); - tree_roots_ = new NodePtr[trees_]; - - // Create a permutable array of indices to the input vectors. - vind_.resize(size_); - for (size_t i = 0; i < size_; ++i) { - vind_[i] = int(i); - } - - mean_ = new DistanceType[veclen_]; - var_ = new DistanceType[veclen_]; - } - - - KDTreeIndex(const KDTreeIndex&); - KDTreeIndex& operator=(const KDTreeIndex&); - - /** - * Standard destructor - */ - ~KDTreeIndex() - { - if (tree_roots_!=NULL) { - delete[] tree_roots_; - } - delete[] mean_; - delete[] var_; - } - - /** - * Builds the index - */ - void buildIndex() CV_OVERRIDE - { - /* Construct the randomized trees. */ - for (int i = 0; i < trees_; i++) { - /* Randomize the order of vectors to allow for unbiased sampling. */ -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::randShuffle(vind_); -#else - std::random_shuffle(vind_.begin(), vind_.end()); -#endif - - tree_roots_[i] = divideTree(&vind_[0], int(size_) ); - } - } - - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_KDTREE; - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, trees_); - for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - const int maxChecks = get_param(searchParams,"checks", 32); - const float epsError = 1+get_param(searchParams,"eps",0.0f); - const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); - - if (maxChecks==FLANN_CHECKS_UNLIMITED) { - getExactNeighbors(result, vec, epsError); - } - else { - getNeighbors(result, vec, maxChecks, epsError, explore_all_trees); - } - } - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - -private: - - - /*--------------------- Internal Data Structures --------------------------*/ - struct Node - { - /** - * Dimension used for subdivision. - */ - int divfeat; - /** - * The values used for subdivision. - */ - DistanceType divval; - /** - * The child nodes. - */ - Node* child1, * child2; - }; - typedef Node* NodePtr; - typedef BranchStruct BranchSt; - typedef BranchSt* Branch; - - - - void save_tree(FILE* stream, NodePtr tree) - { - save_value(stream, *tree); - if (tree->child1!=NULL) { - save_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - save_tree(stream, tree->child2); - } - } - - - void load_tree(FILE* stream, NodePtr& tree) - { - tree = pool_.allocate(); - load_value(stream, *tree); - if (tree->child1!=NULL) { - load_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - load_tree(stream, tree->child2); - } - } - - - /** - * Create a tree node that subdivides the list of vecs from vind[first] - * to vind[last]. The routine is called recursively on each sublist. - * Place a pointer to this new tree node in the location pTree. - * - * Params: pTree = the new node to create - * first = index of the first vector - * last = index of the last vector - */ - NodePtr divideTree(int* ind, int count) - { - NodePtr node = pool_.allocate(); // allocate memory - - /* If too few exemplars remain, then make this a leaf node. */ - if ( count == 1) { - node->child1 = node->child2 = NULL; /* Mark as leaf node. */ - node->divfeat = *ind; /* Store index of this vec. */ - } - else { - int idx; - int cutfeat; - DistanceType cutval; - meanSplit(ind, count, idx, cutfeat, cutval); - - node->divfeat = cutfeat; - node->divval = cutval; - node->child1 = divideTree(ind, idx); - node->child2 = divideTree(ind+idx, count-idx); - } - - return node; - } - - - /** - * Choose which feature to use in order to subdivide this set of vectors. - * Make a random choice among those with the highest variance, and use - * its variance as the threshold value. - */ - void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval) - { - memset(mean_,0,veclen_*sizeof(DistanceType)); - memset(var_,0,veclen_*sizeof(DistanceType)); - - /* Compute mean values. Only the first SAMPLE_MEAN values need to be - sampled to get a good estimate. - */ - int cnt = std::min((int)SAMPLE_MEAN+1, count); - for (int j = 0; j < cnt; ++j) { - ElementType* v = dataset_[ind[j]]; - for (size_t k=0; kcount/2) index = lim1; - else if (lim2 v[topind[num-1]])) { - /* Put this element at end of topind. */ - if (num < RAND_DIM) { - topind[num++] = i; /* Add to list. */ - } - else { - topind[num-1] = i; /* Replace last element. */ - } - /* Bubble end value down to right location by repeated swapping. */ - int j = num - 1; - while (j > 0 && v[topind[j]] > v[topind[j-1]]) { - std::swap(topind[j], topind[j-1]); - --j; - } - } - } - /* Select a random integer in range [0,num-1], and return that index. */ - int rnd = rand_int(num); - return (int)topind[rnd]; - } - - - /** - * Subdivide the list of points by a plane perpendicular on axe corresponding - * to the 'cutfeat' dimension at 'cutval' position. - * - * On return: - * dataset[ind[0..lim1-1]][cutfeat]cutval - */ - void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) - { - /* Move vector indices for left subtree to front of list. */ - int left = 0; - int right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - lim1 = left; - right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; - while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - lim2 = left; - } - - /** - * Performs an exact nearest neighbor search. The exact search performs a full - * traversal of the tree. - */ - void getExactNeighbors(ResultSet& result, const ElementType* vec, float epsError) - { - // checkID -= 1; /* Set a different unique ID for each search. */ - - if (trees_ > 1) { - fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search"); - } - if (trees_>0) { - searchLevelExact(result, vec, tree_roots_[0], 0.0, epsError); - } - CV_Assert(result.full()); - } - - /** - * Performs the approximate nearest-neighbor search. The search is approximate - * because the tree traversal is abandoned after a given number of descends in - * the tree. - */ - void getNeighbors(ResultSet& result, const ElementType* vec, - int maxCheck, float epsError, bool explore_all_trees = false) - { - int i; - BranchSt branch; - int checkCount = 0; - DynamicBitset checked(size_); - - // Priority queue storing intermediate branches in the best-bin-first search - const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); - - /* Search once through each tree down to root. */ - for (i = 0; i < trees_; ++i) { - searchLevel(result, vec, tree_roots_[i], 0, checkCount, maxCheck, - epsError, heap, checked, explore_all_trees); - if (!explore_all_trees && (checkCount >= maxCheck) && result.full()) - break; - } - - /* Keep searching other branches from heap until finished. */ - while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { - searchLevel(result, vec, branch.node, branch.mindist, checkCount, maxCheck, - epsError, heap, checked, false); - } - - CV_Assert(result.full()); - } - - - /** - * Search starting from a given node of the tree. Based on any mismatches at - * higher levels, all exemplars below this level must have a distance of - * at least "mindistsq". - */ - void searchLevel(ResultSet& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck, - float epsError, const cv::Ptr>& heap, DynamicBitset& checked, bool explore_all_trees = false) - { - if (result_set.worstDist()child1 == NULL)&&(node->child2 == NULL)) { - /* Do not check same node more than once when searching multiple trees. - Once a vector is checked, we set its location in vind to the - current checkID. - */ - int index = node->divfeat; - if ( checked.test(index) || - (!explore_all_trees && (checkCount>=maxCheck) && result_set.full()) ) { - return; - } - checked.set(index); - checkCount++; - - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result_set.addPoint(dist,index); - - return; - } - - /* Which child branch should be taken first? */ - ElementType val = vec[node->divfeat]; - DistanceType diff = val - node->divval; - NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; - NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; - - /* Create a branch record for the branch not taken. Add distance - of this feature boundary (we don't attempt to correct for any - use of this feature in a parent node, which is unlikely to - happen and would have only a small effect). Don't bother - adding more branches to heap after halfway point, as cost of - adding exceeds their value. - */ - - DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); - // if (2 * checkCount < maxCheck || !result.full()) { - if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) { - heap->insert( BranchSt(otherChild, new_distsq) ); - } - - /* Call recursively to search next level down. */ - searchLevel(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked); - } - - /** - * Performs an exact search in the tree starting from a node. - */ - void searchLevelExact(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) - { - /* If this is a leaf node, then do check and return. */ - if ((node->child1 == NULL)&&(node->child2 == NULL)) { - int index = node->divfeat; - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result_set.addPoint(dist,index); - return; - } - - /* Which child branch should be taken first? */ - ElementType val = vec[node->divfeat]; - DistanceType diff = val - node->divval; - NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; - NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; - - /* Create a branch record for the branch not taken. Add distance - of this feature boundary (we don't attempt to correct for any - use of this feature in a parent node, which is unlikely to - happen and would have only a small effect). Don't bother - adding more branches to heap after halfway point, as cost of - adding exceeds their value. - */ - - DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); - - /* Call recursively to search next level down. */ - searchLevelExact(result_set, vec, bestChild, mindist, epsError); - - if (new_distsq*epsError<=result_set.worstDist()) { - searchLevelExact(result_set, vec, otherChild, new_distsq, epsError); - } - } - - -private: - - enum - { - /** - * To improve efficiency, only SAMPLE_MEAN random values are used to - * compute the mean and variance at each level when building a tree. - * A value of 100 seems to perform as well as using all values. - */ - SAMPLE_MEAN = 100, - /** - * Top random dimensions to consider - * - * When creating random trees, the dimension on which to subdivide is - * selected at random from among the top RAND_DIM dimensions with the - * highest variance. A value of 5 works well. - */ - RAND_DIM=5 - }; - - - /** - * Number of randomized trees that are used - */ - int trees_; - - /** - * Array of indices to vectors in the dataset. - */ - std::vector vind_; - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - IndexParams index_params_; - - size_t size_; - size_t veclen_; - - - DistanceType* mean_; - DistanceType* var_; - - - /** - * Array of k-d trees used to find neighbours. - */ - NodePtr* tree_roots_; - - /** - * Pooled memory allocator. - * - * Using a pooled memory allocator is more efficient - * than allocating memory directly when there is a large - * number small of memory allocations. - */ - PooledAllocator pool_; - - Distance distance_; - - -}; // class KDTreeForest - -} - -//! @endcond - -#endif //OPENCV_FLANN_KDTREE_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_KDTREE_INDEX_H_ +#define OPENCV_FLANN_KDTREE_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include + +#include "nn_index.h" +#include "dynamic_bitset.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + + +namespace cvflann +{ + +struct KDTreeIndexParams : public IndexParams +{ + KDTreeIndexParams(int trees = 4) + { + (*this)["algorithm"] = FLANN_INDEX_KDTREE; + (*this)["trees"] = trees; + } +}; + + +/** + * Randomized kd-tree index + * + * Contains the k-d trees and other information for indexing a set of points + * for nearest-neighbor matching. + */ +template +class KDTreeIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + + /** + * KDTree constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the kdtree algorithm + */ + KDTreeIndex(const Matrix& inputData, const IndexParams& params = KDTreeIndexParams(), + Distance d = Distance() ) : + dataset_(inputData), index_params_(params), distance_(d) + { + size_ = dataset_.rows; + veclen_ = dataset_.cols; + + trees_ = get_param(index_params_,"trees",4); + tree_roots_ = new NodePtr[trees_]; + + // Create a permutable array of indices to the input vectors. + vind_.resize(size_); + for (size_t i = 0; i < size_; ++i) { + vind_[i] = int(i); + } + + mean_ = new DistanceType[veclen_]; + var_ = new DistanceType[veclen_]; + } + + + KDTreeIndex(const KDTreeIndex&); + KDTreeIndex& operator=(const KDTreeIndex&); + + /** + * Standard destructor + */ + ~KDTreeIndex() + { + if (tree_roots_!=NULL) { + delete[] tree_roots_; + } + delete[] mean_; + delete[] var_; + } + + /** + * Builds the index + */ + void buildIndex() CV_OVERRIDE + { + /* Construct the randomized trees. */ + for (int i = 0; i < trees_; i++) { + /* Randomize the order of vectors to allow for unbiased sampling. */ +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::randShuffle(vind_); +#else + std::random_shuffle(vind_.begin(), vind_.end()); +#endif + + tree_roots_[i] = divideTree(&vind_[0], int(size_) ); + } + } + + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_KDTREE; + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, trees_); + for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + const int maxChecks = get_param(searchParams,"checks", 32); + const float epsError = 1+get_param(searchParams,"eps",0.0f); + const bool explore_all_trees = get_param(searchParams,"explore_all_trees",false); + + if (maxChecks==FLANN_CHECKS_UNLIMITED) { + getExactNeighbors(result, vec, epsError); + } + else { + getNeighbors(result, vec, maxChecks, epsError, explore_all_trees); + } + } + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + +private: + + + /*--------------------- Internal Data Structures --------------------------*/ + struct Node + { + /** + * Dimension used for subdivision. + */ + int divfeat; + /** + * The values used for subdivision. + */ + DistanceType divval; + /** + * The child nodes. + */ + Node* child1, * child2; + }; + typedef Node* NodePtr; + typedef BranchStruct BranchSt; + typedef BranchSt* Branch; + + + + void save_tree(FILE* stream, NodePtr tree) + { + save_value(stream, *tree); + if (tree->child1!=NULL) { + save_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + save_tree(stream, tree->child2); + } + } + + + void load_tree(FILE* stream, NodePtr& tree) + { + tree = pool_.allocate(); + load_value(stream, *tree); + if (tree->child1!=NULL) { + load_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + load_tree(stream, tree->child2); + } + } + + + /** + * Create a tree node that subdivides the list of vecs from vind[first] + * to vind[last]. The routine is called recursively on each sublist. + * Place a pointer to this new tree node in the location pTree. + * + * Params: pTree = the new node to create + * first = index of the first vector + * last = index of the last vector + */ + NodePtr divideTree(int* ind, int count) + { + NodePtr node = pool_.allocate(); // allocate memory + + /* If too few exemplars remain, then make this a leaf node. */ + if ( count == 1) { + node->child1 = node->child2 = NULL; /* Mark as leaf node. */ + node->divfeat = *ind; /* Store index of this vec. */ + } + else { + int idx; + int cutfeat; + DistanceType cutval; + meanSplit(ind, count, idx, cutfeat, cutval); + + node->divfeat = cutfeat; + node->divval = cutval; + node->child1 = divideTree(ind, idx); + node->child2 = divideTree(ind+idx, count-idx); + } + + return node; + } + + + /** + * Choose which feature to use in order to subdivide this set of vectors. + * Make a random choice among those with the highest variance, and use + * its variance as the threshold value. + */ + void meanSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval) + { + memset(mean_,0,veclen_*sizeof(DistanceType)); + memset(var_,0,veclen_*sizeof(DistanceType)); + + /* Compute mean values. Only the first SAMPLE_MEAN values need to be + sampled to get a good estimate. + */ + int cnt = std::min((int)SAMPLE_MEAN+1, count); + for (int j = 0; j < cnt; ++j) { + ElementType* v = dataset_[ind[j]]; + for (size_t k=0; kcount/2) index = lim1; + else if (lim2 v[topind[num-1]])) { + /* Put this element at end of topind. */ + if (num < RAND_DIM) { + topind[num++] = i; /* Add to list. */ + } + else { + topind[num-1] = i; /* Replace last element. */ + } + /* Bubble end value down to right location by repeated swapping. */ + int j = num - 1; + while (j > 0 && v[topind[j]] > v[topind[j-1]]) { + std::swap(topind[j], topind[j-1]); + --j; + } + } + } + /* Select a random integer in range [0,num-1], and return that index. */ + int rnd = rand_int(num); + return (int)topind[rnd]; + } + + + /** + * Subdivide the list of points by a plane perpendicular on axe corresponding + * to the 'cutfeat' dimension at 'cutval' position. + * + * On return: + * dataset[ind[0..lim1-1]][cutfeat]cutval + */ + void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) + { + /* Move vector indices for left subtree to front of list. */ + int left = 0; + int right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + lim1 = left; + right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; + while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + lim2 = left; + } + + /** + * Performs an exact nearest neighbor search. The exact search performs a full + * traversal of the tree. + */ + void getExactNeighbors(ResultSet& result, const ElementType* vec, float epsError) + { + // checkID -= 1; /* Set a different unique ID for each search. */ + + if (trees_ > 1) { + fprintf(stderr,"It doesn't make any sense to use more than one tree for exact search"); + } + if (trees_>0) { + searchLevelExact(result, vec, tree_roots_[0], 0.0, epsError); + } + CV_Assert(result.full()); + } + + /** + * Performs the approximate nearest-neighbor search. The search is approximate + * because the tree traversal is abandoned after a given number of descends in + * the tree. + */ + void getNeighbors(ResultSet& result, const ElementType* vec, + int maxCheck, float epsError, bool explore_all_trees = false) + { + int i; + BranchSt branch; + int checkCount = 0; + DynamicBitset checked(size_); + + // Priority queue storing intermediate branches in the best-bin-first search + const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); + + /* Search once through each tree down to root. */ + for (i = 0; i < trees_; ++i) { + searchLevel(result, vec, tree_roots_[i], 0, checkCount, maxCheck, + epsError, heap, checked, explore_all_trees); + if (!explore_all_trees && (checkCount >= maxCheck) && result.full()) + break; + } + + /* Keep searching other branches from heap until finished. */ + while ( heap->popMin(branch) && (checkCount < maxCheck || !result.full() )) { + searchLevel(result, vec, branch.node, branch.mindist, checkCount, maxCheck, + epsError, heap, checked, false); + } + + CV_Assert(result.full()); + } + + + /** + * Search starting from a given node of the tree. Based on any mismatches at + * higher levels, all exemplars below this level must have a distance of + * at least "mindistsq". + */ + void searchLevel(ResultSet& result_set, const ElementType* vec, NodePtr node, DistanceType mindist, int& checkCount, int maxCheck, + float epsError, const cv::Ptr>& heap, DynamicBitset& checked, bool explore_all_trees = false) + { + if (result_set.worstDist()child1 == NULL)&&(node->child2 == NULL)) { + /* Do not check same node more than once when searching multiple trees. + Once a vector is checked, we set its location in vind to the + current checkID. + */ + int index = node->divfeat; + if ( checked.test(index) || + (!explore_all_trees && (checkCount>=maxCheck) && result_set.full()) ) { + return; + } + checked.set(index); + checkCount++; + + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result_set.addPoint(dist,index); + + return; + } + + /* Which child branch should be taken first? */ + ElementType val = vec[node->divfeat]; + DistanceType diff = val - node->divval; + NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; + NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; + + /* Create a branch record for the branch not taken. Add distance + of this feature boundary (we don't attempt to correct for any + use of this feature in a parent node, which is unlikely to + happen and would have only a small effect). Don't bother + adding more branches to heap after halfway point, as cost of + adding exceeds their value. + */ + + DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); + // if (2 * checkCount < maxCheck || !result.full()) { + if ((new_distsq*epsError < result_set.worstDist())|| !result_set.full()) { + heap->insert( BranchSt(otherChild, new_distsq) ); + } + + /* Call recursively to search next level down. */ + searchLevel(result_set, vec, bestChild, mindist, checkCount, maxCheck, epsError, heap, checked); + } + + /** + * Performs an exact search in the tree starting from a node. + */ + void searchLevelExact(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindist, const float epsError) + { + /* If this is a leaf node, then do check and return. */ + if ((node->child1 == NULL)&&(node->child2 == NULL)) { + int index = node->divfeat; + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result_set.addPoint(dist,index); + return; + } + + /* Which child branch should be taken first? */ + ElementType val = vec[node->divfeat]; + DistanceType diff = val - node->divval; + NodePtr bestChild = (diff < 0) ? node->child1 : node->child2; + NodePtr otherChild = (diff < 0) ? node->child2 : node->child1; + + /* Create a branch record for the branch not taken. Add distance + of this feature boundary (we don't attempt to correct for any + use of this feature in a parent node, which is unlikely to + happen and would have only a small effect). Don't bother + adding more branches to heap after halfway point, as cost of + adding exceeds their value. + */ + + DistanceType new_distsq = mindist + distance_.accum_dist(val, node->divval, node->divfeat); + + /* Call recursively to search next level down. */ + searchLevelExact(result_set, vec, bestChild, mindist, epsError); + + if (new_distsq*epsError<=result_set.worstDist()) { + searchLevelExact(result_set, vec, otherChild, new_distsq, epsError); + } + } + + +private: + + enum + { + /** + * To improve efficiency, only SAMPLE_MEAN random values are used to + * compute the mean and variance at each level when building a tree. + * A value of 100 seems to perform as well as using all values. + */ + SAMPLE_MEAN = 100, + /** + * Top random dimensions to consider + * + * When creating random trees, the dimension on which to subdivide is + * selected at random from among the top RAND_DIM dimensions with the + * highest variance. A value of 5 works well. + */ + RAND_DIM=5 + }; + + + /** + * Number of randomized trees that are used + */ + int trees_; + + /** + * Array of indices to vectors in the dataset. + */ + std::vector vind_; + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + IndexParams index_params_; + + size_t size_; + size_t veclen_; + + + DistanceType* mean_; + DistanceType* var_; + + + /** + * Array of k-d trees used to find neighbours. + */ + NodePtr* tree_roots_; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool_; + + Distance distance_; + + +}; // class KDTreeForest + +} + +//! @endcond + +#endif //OPENCV_FLANN_KDTREE_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h index 5a5f8140f1..ed95c3db7d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/kdtree_single_index.h @@ -1,645 +1,645 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ -#define OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include - -#include "nn_index.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - -namespace cvflann -{ - -struct KDTreeSingleIndexParams : public IndexParams -{ - KDTreeSingleIndexParams(int leaf_max_size = 10, bool reorder = true, int dim = -1) - { - (*this)["algorithm"] = FLANN_INDEX_KDTREE_SINGLE; - (*this)["leaf_max_size"] = leaf_max_size; - (*this)["reorder"] = reorder; - (*this)["dim"] = dim; - } -}; - - -/** - * Randomized kd-tree index - * - * Contains the k-d trees and other information for indexing a set of points - * for nearest-neighbor matching. - */ -template -class KDTreeSingleIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - - /** - * KDTree constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the kdtree algorithm - */ - KDTreeSingleIndex(const Matrix& inputData, const IndexParams& params = KDTreeSingleIndexParams(), - Distance d = Distance() ) : - dataset_(inputData), index_params_(params), distance_(d) - { - size_ = dataset_.rows; - dim_ = dataset_.cols; - root_node_ = 0; - int dim_param = get_param(params,"dim",-1); - if (dim_param>0) dim_ = dim_param; - leaf_max_size_ = get_param(params,"leaf_max_size",10); - reorder_ = get_param(params,"reorder",true); - - // Create a permutable array of indices to the input vectors. - vind_.resize(size_); - for (size_t i = 0; i < size_; i++) { - vind_[i] = (int)i; - } - } - - KDTreeSingleIndex(const KDTreeSingleIndex&); - KDTreeSingleIndex& operator=(const KDTreeSingleIndex&); - - /** - * Standard destructor - */ - ~KDTreeSingleIndex() - { - if (reorder_) delete[] data_.data; - } - - /** - * Builds the index - */ - void buildIndex() CV_OVERRIDE - { - computeBoundingBox(root_bbox_); - root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree - - if (reorder_) { - delete[] data_.data; - data_ = cvflann::Matrix(new ElementType[size_*dim_], size_, dim_); - for (size_t i=0; i& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE - { - CV_Assert(queries.cols == veclen()); - CV_Assert(indices.rows >= queries.rows); - CV_Assert(dists.rows >= queries.rows); - CV_Assert(int(indices.cols) >= knn); - CV_Assert(int(dists.cols) >= knn); - - KNNSimpleResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.init(indices[i], dists[i]); - findNeighbors(resultSet, queries[i], params); - } - } - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - - /** - * Find set of nearest neighbors to vec. Their indices are stored inside - * the result object. - * - * Params: - * result = the result object in which the indices of the nearest-neighbors are stored - * vec = the vector for which to search the nearest neighbors - * maxCheck = the maximum number of restarts (in a best-bin-first manner) - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - float epsError = 1+get_param(searchParams,"eps",0.0f); - - std::vector dists(dim_,0); - DistanceType distsq = computeInitialDistances(vec, dists); - searchLevel(result, vec, root_node_, distsq, dists, epsError); - } - -private: - - - /*--------------------- Internal Data Structures --------------------------*/ - struct Node - { - /** - * Indices of points in leaf node - */ - int left, right; - /** - * Dimension used for subdivision. - */ - int divfeat; - /** - * The values used for subdivision. - */ - DistanceType divlow, divhigh; - /** - * The child nodes. - */ - Node* child1, * child2; - }; - typedef Node* NodePtr; - - - struct Interval - { - DistanceType low, high; - }; - - typedef std::vector BoundingBox; - - typedef BranchStruct BranchSt; - typedef BranchSt* Branch; - - - - - void save_tree(FILE* stream, NodePtr tree) - { - save_value(stream, *tree); - if (tree->child1!=NULL) { - save_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - save_tree(stream, tree->child2); - } - } - - - void load_tree(FILE* stream, NodePtr& tree) - { - tree = pool_.allocate(); - load_value(stream, *tree); - if (tree->child1!=NULL) { - load_tree(stream, tree->child1); - } - if (tree->child2!=NULL) { - load_tree(stream, tree->child2); - } - } - - - void computeBoundingBox(BoundingBox& bbox) - { - bbox.resize(dim_); - for (size_t i=0; ibbox[i].high) bbox[i].high = (DistanceType)dataset_[k][i]; - } - } - } - - - /** - * Create a tree node that subdivides the list of vecs from vind[first] - * to vind[last]. The routine is called recursively on each sublist. - * Place a pointer to this new tree node in the location pTree. - * - * Params: pTree = the new node to create - * first = index of the first vector - * last = index of the last vector - */ - NodePtr divideTree(int left, int right, BoundingBox& bbox) - { - NodePtr node = pool_.allocate(); // allocate memory - - /* If too few exemplars remain, then make this a leaf node. */ - if ( (right-left) <= leaf_max_size_) { - node->child1 = node->child2 = NULL; /* Mark as leaf node. */ - node->left = left; - node->right = right; - - // compute bounding-box of leaf points - for (size_t i=0; idataset_[vind_[k]][i]) bbox[i].low=(DistanceType)dataset_[vind_[k]][i]; - if (bbox[i].highdivfeat = cutfeat; - - BoundingBox left_bbox(bbox); - left_bbox[cutfeat].high = cutval; - node->child1 = divideTree(left, left+idx, left_bbox); - - BoundingBox right_bbox(bbox); - right_bbox[cutfeat].low = cutval; - node->child2 = divideTree(left+idx, right, right_bbox); - - node->divlow = left_bbox[cutfeat].high; - node->divhigh = right_bbox[cutfeat].low; - - for (size_t i=0; imax_elem) max_elem = val; - } - } - - void middleSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) - { - // find the largest span from the approximate bounding box - ElementType max_span = bbox[0].high-bbox[0].low; - cutfeat = 0; - cutval = (bbox[0].high+bbox[0].low)/2; - for (size_t i=1; imax_span) { - max_span = span; - cutfeat = i; - cutval = (bbox[i].high+bbox[i].low)/2; - } - } - - // compute exact span on the found dimension - ElementType min_elem, max_elem; - computeMinMax(ind, count, cutfeat, min_elem, max_elem); - cutval = (min_elem+max_elem)/2; - max_span = max_elem - min_elem; - - // check if a dimension of a largest span exists - size_t k = cutfeat; - for (size_t i=0; imax_span) { - computeMinMax(ind, count, i, min_elem, max_elem); - span = max_elem - min_elem; - if (span>max_span) { - max_span = span; - cutfeat = i; - cutval = (min_elem+max_elem)/2; - } - } - } - int lim1, lim2; - planeSplit(ind, count, cutfeat, cutval, lim1, lim2); - - if (lim1>count/2) index = lim1; - else if (lim2max_span) { - max_span = span; - } - } - DistanceType max_spread = -1; - cutfeat = 0; - for (size_t i=0; i(DistanceType)((1-EPS)*max_span)) { - ElementType min_elem, max_elem; - computeMinMax(ind, count, (int)i, min_elem, max_elem); - DistanceType spread = (DistanceType)(max_elem-min_elem); - if (spread>max_spread) { - cutfeat = (int)i; - max_spread = spread; - } - } - } - // split in the middle - DistanceType split_val = (bbox[cutfeat].low+bbox[cutfeat].high)/2; - ElementType min_elem, max_elem; - computeMinMax(ind, count, cutfeat, min_elem, max_elem); - - if (split_valmax_elem) cutval = (DistanceType)max_elem; - else cutval = split_val; - - int lim1, lim2; - planeSplit(ind, count, cutfeat, cutval, lim1, lim2); - - if (lim1>count/2) index = lim1; - else if (lim2cutval - */ - void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) - { - /* Move vector indices for left subtree to front of list. */ - int left = 0; - int right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - /* If either list is empty, it means that all remaining features - * are identical. Split in the middle to maintain a balanced tree. - */ - lim1 = left; - right = count-1; - for (;; ) { - while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; - while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; - if (left>right) break; - std::swap(ind[left], ind[right]); ++left; --right; - } - lim2 = left; - } - - DistanceType computeInitialDistances(const ElementType* vec, std::vector& dists) - { - DistanceType distsq = 0.0; - - for (size_t i = 0; i < dim_; ++i) { - if (vec[i] < root_bbox_[i].low) { - dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, (int)i); - distsq += dists[i]; - } - if (vec[i] > root_bbox_[i].high) { - dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, (int)i); - distsq += dists[i]; - } - } - - return distsq; - } - - /** - * Performs an exact search in the tree starting from a node. - */ - void searchLevel(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, - std::vector& dists, const float epsError) - { - /* If this is a leaf node, then do check and return. */ - if ((node->child1 == NULL)&&(node->child2 == NULL)) { - DistanceType worst_dist = result_set.worstDist(); - if (reorder_) { - for (int i=node->left; iright; ++i) { - DistanceType dist = distance_(vec, data_[i], dim_, worst_dist); - if (distleft; iright; ++i) { - DistanceType dist = distance_(vec, data_[vind_[i]], dim_, worst_dist); - if (distdivfeat; - ElementType val = vec[idx]; - DistanceType diff1 = val - node->divlow; - DistanceType diff2 = val - node->divhigh; - - NodePtr bestChild; - NodePtr otherChild; - DistanceType cut_dist; - if ((diff1+diff2)<0) { - bestChild = node->child1; - otherChild = node->child2; - cut_dist = distance_.accum_dist(val, node->divhigh, idx); - } - else { - bestChild = node->child2; - otherChild = node->child1; - cut_dist = distance_.accum_dist( val, node->divlow, idx); - } - - /* Call recursively to search next level down. */ - searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); - - DistanceType dst = dists[idx]; - mindistsq = mindistsq + cut_dist - dst; - dists[idx] = cut_dist; - if (mindistsq*epsError<=result_set.worstDist()) { - searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); - } - dists[idx] = dst; - } - -private: - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - IndexParams index_params_; - - int leaf_max_size_; - bool reorder_; - - - /** - * Array of indices to vectors in the dataset. - */ - std::vector vind_; - - Matrix data_; - - size_t size_; - size_t dim_; - - /** - * Array of k-d trees used to find neighbours. - */ - NodePtr root_node_; - - BoundingBox root_bbox_; - - /** - * Pooled memory allocator. - * - * Using a pooled memory allocator is more efficient - * than allocating memory directly when there is a large - * number small of memory allocations. - */ - PooledAllocator pool_; - - Distance distance_; -}; // class KDTree - -} - -//! @endcond - -#endif //OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ +#define OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include + +#include "nn_index.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + +namespace cvflann +{ + +struct KDTreeSingleIndexParams : public IndexParams +{ + KDTreeSingleIndexParams(int leaf_max_size = 10, bool reorder = true, int dim = -1) + { + (*this)["algorithm"] = FLANN_INDEX_KDTREE_SINGLE; + (*this)["leaf_max_size"] = leaf_max_size; + (*this)["reorder"] = reorder; + (*this)["dim"] = dim; + } +}; + + +/** + * Randomized kd-tree index + * + * Contains the k-d trees and other information for indexing a set of points + * for nearest-neighbor matching. + */ +template +class KDTreeSingleIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + + /** + * KDTree constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the kdtree algorithm + */ + KDTreeSingleIndex(const Matrix& inputData, const IndexParams& params = KDTreeSingleIndexParams(), + Distance d = Distance() ) : + dataset_(inputData), index_params_(params), distance_(d) + { + size_ = dataset_.rows; + dim_ = dataset_.cols; + root_node_ = 0; + int dim_param = get_param(params,"dim",-1); + if (dim_param>0) dim_ = dim_param; + leaf_max_size_ = get_param(params,"leaf_max_size",10); + reorder_ = get_param(params,"reorder",true); + + // Create a permutable array of indices to the input vectors. + vind_.resize(size_); + for (size_t i = 0; i < size_; i++) { + vind_[i] = (int)i; + } + } + + KDTreeSingleIndex(const KDTreeSingleIndex&); + KDTreeSingleIndex& operator=(const KDTreeSingleIndex&); + + /** + * Standard destructor + */ + ~KDTreeSingleIndex() + { + if (reorder_) delete[] data_.data; + } + + /** + * Builds the index + */ + void buildIndex() CV_OVERRIDE + { + computeBoundingBox(root_bbox_); + root_node_ = divideTree(0, (int)size_, root_bbox_ ); // construct the tree + + if (reorder_) { + delete[] data_.data; + data_ = cvflann::Matrix(new ElementType[size_*dim_], size_, dim_); + for (size_t i=0; i& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE + { + CV_Assert(queries.cols == veclen()); + CV_Assert(indices.rows >= queries.rows); + CV_Assert(dists.rows >= queries.rows); + CV_Assert(int(indices.cols) >= knn); + CV_Assert(int(dists.cols) >= knn); + + KNNSimpleResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.init(indices[i], dists[i]); + findNeighbors(resultSet, queries[i], params); + } + } + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + + /** + * Find set of nearest neighbors to vec. Their indices are stored inside + * the result object. + * + * Params: + * result = the result object in which the indices of the nearest-neighbors are stored + * vec = the vector for which to search the nearest neighbors + * maxCheck = the maximum number of restarts (in a best-bin-first manner) + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + float epsError = 1+get_param(searchParams,"eps",0.0f); + + std::vector dists(dim_,0); + DistanceType distsq = computeInitialDistances(vec, dists); + searchLevel(result, vec, root_node_, distsq, dists, epsError); + } + +private: + + + /*--------------------- Internal Data Structures --------------------------*/ + struct Node + { + /** + * Indices of points in leaf node + */ + int left, right; + /** + * Dimension used for subdivision. + */ + int divfeat; + /** + * The values used for subdivision. + */ + DistanceType divlow, divhigh; + /** + * The child nodes. + */ + Node* child1, * child2; + }; + typedef Node* NodePtr; + + + struct Interval + { + DistanceType low, high; + }; + + typedef std::vector BoundingBox; + + typedef BranchStruct BranchSt; + typedef BranchSt* Branch; + + + + + void save_tree(FILE* stream, NodePtr tree) + { + save_value(stream, *tree); + if (tree->child1!=NULL) { + save_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + save_tree(stream, tree->child2); + } + } + + + void load_tree(FILE* stream, NodePtr& tree) + { + tree = pool_.allocate(); + load_value(stream, *tree); + if (tree->child1!=NULL) { + load_tree(stream, tree->child1); + } + if (tree->child2!=NULL) { + load_tree(stream, tree->child2); + } + } + + + void computeBoundingBox(BoundingBox& bbox) + { + bbox.resize(dim_); + for (size_t i=0; ibbox[i].high) bbox[i].high = (DistanceType)dataset_[k][i]; + } + } + } + + + /** + * Create a tree node that subdivides the list of vecs from vind[first] + * to vind[last]. The routine is called recursively on each sublist. + * Place a pointer to this new tree node in the location pTree. + * + * Params: pTree = the new node to create + * first = index of the first vector + * last = index of the last vector + */ + NodePtr divideTree(int left, int right, BoundingBox& bbox) + { + NodePtr node = pool_.allocate(); // allocate memory + + /* If too few exemplars remain, then make this a leaf node. */ + if ( (right-left) <= leaf_max_size_) { + node->child1 = node->child2 = NULL; /* Mark as leaf node. */ + node->left = left; + node->right = right; + + // compute bounding-box of leaf points + for (size_t i=0; idataset_[vind_[k]][i]) bbox[i].low=(DistanceType)dataset_[vind_[k]][i]; + if (bbox[i].highdivfeat = cutfeat; + + BoundingBox left_bbox(bbox); + left_bbox[cutfeat].high = cutval; + node->child1 = divideTree(left, left+idx, left_bbox); + + BoundingBox right_bbox(bbox); + right_bbox[cutfeat].low = cutval; + node->child2 = divideTree(left+idx, right, right_bbox); + + node->divlow = left_bbox[cutfeat].high; + node->divhigh = right_bbox[cutfeat].low; + + for (size_t i=0; imax_elem) max_elem = val; + } + } + + void middleSplit(int* ind, int count, int& index, int& cutfeat, DistanceType& cutval, const BoundingBox& bbox) + { + // find the largest span from the approximate bounding box + ElementType max_span = bbox[0].high-bbox[0].low; + cutfeat = 0; + cutval = (bbox[0].high+bbox[0].low)/2; + for (size_t i=1; imax_span) { + max_span = span; + cutfeat = i; + cutval = (bbox[i].high+bbox[i].low)/2; + } + } + + // compute exact span on the found dimension + ElementType min_elem, max_elem; + computeMinMax(ind, count, cutfeat, min_elem, max_elem); + cutval = (min_elem+max_elem)/2; + max_span = max_elem - min_elem; + + // check if a dimension of a largest span exists + size_t k = cutfeat; + for (size_t i=0; imax_span) { + computeMinMax(ind, count, i, min_elem, max_elem); + span = max_elem - min_elem; + if (span>max_span) { + max_span = span; + cutfeat = i; + cutval = (min_elem+max_elem)/2; + } + } + } + int lim1, lim2; + planeSplit(ind, count, cutfeat, cutval, lim1, lim2); + + if (lim1>count/2) index = lim1; + else if (lim2max_span) { + max_span = span; + } + } + DistanceType max_spread = -1; + cutfeat = 0; + for (size_t i=0; i(DistanceType)((1-EPS)*max_span)) { + ElementType min_elem, max_elem; + computeMinMax(ind, count, (int)i, min_elem, max_elem); + DistanceType spread = (DistanceType)(max_elem-min_elem); + if (spread>max_spread) { + cutfeat = (int)i; + max_spread = spread; + } + } + } + // split in the middle + DistanceType split_val = (bbox[cutfeat].low+bbox[cutfeat].high)/2; + ElementType min_elem, max_elem; + computeMinMax(ind, count, cutfeat, min_elem, max_elem); + + if (split_valmax_elem) cutval = (DistanceType)max_elem; + else cutval = split_val; + + int lim1, lim2; + planeSplit(ind, count, cutfeat, cutval, lim1, lim2); + + if (lim1>count/2) index = lim1; + else if (lim2cutval + */ + void planeSplit(int* ind, int count, int cutfeat, DistanceType cutval, int& lim1, int& lim2) + { + /* Move vector indices for left subtree to front of list. */ + int left = 0; + int right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]=cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + /* If either list is empty, it means that all remaining features + * are identical. Split in the middle to maintain a balanced tree. + */ + lim1 = left; + right = count-1; + for (;; ) { + while (left<=right && dataset_[ind[left]][cutfeat]<=cutval) ++left; + while (left<=right && dataset_[ind[right]][cutfeat]>cutval) --right; + if (left>right) break; + std::swap(ind[left], ind[right]); ++left; --right; + } + lim2 = left; + } + + DistanceType computeInitialDistances(const ElementType* vec, std::vector& dists) + { + DistanceType distsq = 0.0; + + for (size_t i = 0; i < dim_; ++i) { + if (vec[i] < root_bbox_[i].low) { + dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].low, (int)i); + distsq += dists[i]; + } + if (vec[i] > root_bbox_[i].high) { + dists[i] = distance_.accum_dist(vec[i], root_bbox_[i].high, (int)i); + distsq += dists[i]; + } + } + + return distsq; + } + + /** + * Performs an exact search in the tree starting from a node. + */ + void searchLevel(ResultSet& result_set, const ElementType* vec, const NodePtr node, DistanceType mindistsq, + std::vector& dists, const float epsError) + { + /* If this is a leaf node, then do check and return. */ + if ((node->child1 == NULL)&&(node->child2 == NULL)) { + DistanceType worst_dist = result_set.worstDist(); + if (reorder_) { + for (int i=node->left; iright; ++i) { + DistanceType dist = distance_(vec, data_[i], dim_, worst_dist); + if (distleft; iright; ++i) { + DistanceType dist = distance_(vec, data_[vind_[i]], dim_, worst_dist); + if (distdivfeat; + ElementType val = vec[idx]; + DistanceType diff1 = val - node->divlow; + DistanceType diff2 = val - node->divhigh; + + NodePtr bestChild; + NodePtr otherChild; + DistanceType cut_dist; + if ((diff1+diff2)<0) { + bestChild = node->child1; + otherChild = node->child2; + cut_dist = distance_.accum_dist(val, node->divhigh, idx); + } + else { + bestChild = node->child2; + otherChild = node->child1; + cut_dist = distance_.accum_dist( val, node->divlow, idx); + } + + /* Call recursively to search next level down. */ + searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); + + DistanceType dst = dists[idx]; + mindistsq = mindistsq + cut_dist - dst; + dists[idx] = cut_dist; + if (mindistsq*epsError<=result_set.worstDist()) { + searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); + } + dists[idx] = dst; + } + +private: + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + IndexParams index_params_; + + int leaf_max_size_; + bool reorder_; + + + /** + * Array of indices to vectors in the dataset. + */ + std::vector vind_; + + Matrix data_; + + size_t size_; + size_t dim_; + + /** + * Array of k-d trees used to find neighbours. + */ + NodePtr root_node_; + + BoundingBox root_bbox_; + + /** + * Pooled memory allocator. + * + * Using a pooled memory allocator is more efficient + * than allocating memory directly when there is a large + * number small of memory allocations. + */ + PooledAllocator pool_; + + Distance distance_; +}; // class KDTree + +} + +//! @endcond + +#endif //OPENCV_FLANN_KDTREE_SINGLE_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h index 77aa7c2564..fd7fe2bd39 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/kmeans_index.h @@ -1,1819 +1,1819 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_KMEANS_INDEX_H_ -#define OPENCV_FLANN_KMEANS_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include -#include - -#include "general.h" -#include "nn_index.h" -#include "dist.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" -#include "logger.h" - -#define BITS_PER_CHAR 8 -#define BITS_PER_BASE 2 // for DNA/RNA sequences -#define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE) -#define HISTOS_PER_BASE (1< -class KMeansIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - typedef typename Distance::CentersType CentersType; - - typedef typename Distance::is_kdtree_distance is_kdtree_distance; - typedef typename Distance::is_vector_space_distance is_vector_space_distance; - - - - typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&); - - /** - * The function used for choosing the cluster centers. - */ - centersAlgFunction chooseCenters; - - - - /** - * Chooses the initial centers in the k-means clustering in a random manner. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * indices_length = length of indices vector - * - */ - void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length) - { - UniqueRandom r(indices_length); - - int index; - for (index=0; index=0 && rnd < n); - - centers[0] = indices[rnd]; - - int index; - for (index=1; indexbest_val) { - best_val = dist; - best_index = j; - } - } - if (best_index!=-1) { - centers[index] = indices[best_index]; - } - else { - break; - } - } - centers_length = index; - } - - - /** - * Chooses the initial centers in the k-means using the algorithm - * proposed in the KMeans++ paper: - * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding - * - * Implementation of this function was converted from the one provided in Arthur's code. - * - * Params: - * k = number of centers - * vecs = the dataset of points - * indices = indices in the dataset - * Returns: - */ - void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length) - { - int n = indices_length; - - double currentPot = 0; - DistanceType* closestDistSq = new DistanceType[n]; - - // Choose one random center and set the closestDistSq values - int index = rand_int(n); - CV_DbgAssert(index >=0 && index < n); - centers[0] = indices[index]; - - for (int i = 0; i < n; i++) { - closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); - closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); - currentPot += closestDistSq[i]; - } - - - const int numLocalTries = 1; - - // Choose each center - int centerCount; - for (centerCount = 1; centerCount < k; centerCount++) { - - // Repeat several trials - double bestNewPot = -1; - int bestNewIndex = -1; - for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { - - // Choose our center - have to be slightly careful to return a valid answer even accounting - // for possible rounding errors - double randVal = rand_double(currentPot); - for (index = 0; index < n-1; index++) { - if (randVal <= closestDistSq[index]) break; - else randVal -= closestDistSq[index]; - } - - // Compute the new potential - double newPot = 0; - for (int i = 0; i < n; i++) { - DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); - newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - - // Store the best result - if ((bestNewPot < 0)||(newPot < bestNewPot)) { - bestNewPot = newPot; - bestNewIndex = index; - } - } - - // Add the appropriate center - centers[centerCount] = indices[bestNewIndex]; - currentPot = bestNewPot; - for (int i = 0; i < n; i++) { - DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols); - closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); - } - } - - centers_length = centerCount; - - delete[] closestDistSq; - } - - - -public: - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_KMEANS; - } - - template - class KMeansDistanceComputer : public cv::ParallelLoopBody - { - public: - KMeansDistanceComputer(Distance _distance, const Matrix& _dataset, - const int _branching, const int* _indices, const CentersContainerType& _dcenters, - const size_t _veclen, std::vector &_new_centroids, - std::vector &_sq_dists) - : distance(_distance) - , dataset(_dataset) - , branching(_branching) - , indices(_indices) - , dcenters(_dcenters) - , veclen(_veclen) - , new_centroids(_new_centroids) - , sq_dists(_sq_dists) - { - } - - void operator()(const cv::Range& range) const CV_OVERRIDE - { - const int begin = range.start; - const int end = range.end; - - for( int i = begin; inew_sq_dist) { - new_centroid = j; - sq_dist = new_sq_dist; - } - } - sq_dists[i] = sq_dist; - new_centroids[i] = new_centroid; - } - } - - private: - Distance distance; - const Matrix& dataset; - const int branching; - const int* indices; - const CentersContainerType& dcenters; - const size_t veclen; - std::vector &new_centroids; - std::vector &sq_dists; - KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; } - }; - - /** - * Index constructor - * - * Params: - * inputData = dataset with the input features - * params = parameters passed to the hierarchical k-means algorithm - */ - KMeansIndex(const Matrix& inputData, const IndexParams& params = KMeansIndexParams(), - Distance d = Distance()) - : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d) - { - memoryCounter_ = 0; - - size_ = dataset_.rows; - veclen_ = dataset_.cols; - - branching_ = get_param(params,"branching",32); - trees_ = get_param(params,"trees",1); - iterations_ = get_param(params,"iterations",11); - if (iterations_<0) { - iterations_ = (std::numeric_limits::max)(); - } - centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM); - - if (centers_init_==FLANN_CENTERS_RANDOM) { - chooseCenters = &KMeansIndex::chooseCentersRandom; - } - else if (centers_init_==FLANN_CENTERS_GONZALES) { - chooseCenters = &KMeansIndex::chooseCentersGonzales; - } - else if (centers_init_==FLANN_CENTERS_KMEANSPP) { - chooseCenters = &KMeansIndex::chooseCentersKMeanspp; - } - else { - FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers."); - } - cb_index_ = 0.4f; - - root_ = new KMeansNodePtr[trees_]; - indices_ = new int*[trees_]; - - for (int i=0; i(); - std::memset(root_[i], 0, sizeof(KMeansNode)); - - Distance* dummy = NULL; - computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy); - - computeClustering(root_[i], indices_[i], (int)size_, branching_,0); - } - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream, branching_); - save_value(stream, iterations_); - save_value(stream, memoryCounter_); - save_value(stream, cb_index_); - save_value(stream, trees_); - for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE - { - - const int maxChecks = get_param(searchParams,"checks",32); - - if (maxChecks==FLANN_CHECKS_UNLIMITED) { - findExactNN(root_[0], result, vec); - } - else { - // Priority queue storing intermediate branches in the best-bin-first search - const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); - - int checks = 0; - for (int i=0; i= maxChecks) && result.full()) - break; - } - - BranchSt branch; - while (heap->popMin(branch) && (checks& centers) - { - int numClusters = centers.rows; - if (numClusters<1) { - FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1"); - } - - DistanceType variance; - KMeansNodePtr* clusters = new KMeansNodePtr[numClusters]; - - int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance); - - Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount); - - for (int i=0; ipivot; - for (size_t j=0; j BranchSt; - - - - - void save_tree(FILE* stream, KMeansNodePtr node, int num) - { - save_value(stream, *node); - save_value(stream, *(node->pivot), (int)veclen_); - if (node->childs==NULL) { - int indices_offset = (int)(node->indices - indices_[num]); - save_value(stream, indices_offset); - } - else { - for(int i=0; ichilds[i], num); - } - } - } - - - void load_tree(FILE* stream, KMeansNodePtr& node, int num) - { - node = pool_.allocate(); - load_value(stream, *node); - node->pivot = new CentersType[veclen_]; - load_value(stream, *(node->pivot), (int)veclen_); - if (node->childs==NULL) { - int indices_offset; - load_value(stream, indices_offset); - node->indices = indices_[num] + indices_offset; - } - else { - node->childs = pool_.allocate(branching_); - for(int i=0; ichilds[i], num); - } - } - } - - - /** - * Helper function - */ - void free_centers(KMeansNodePtr node) - { - delete[] node->pivot; - if (node->childs!=NULL) { - for (int k=0; kchilds[k]); - } - } - } - - void free_centers() - { - if (root_ != NULL) { - for(int i=0; i(), veclen_); - } - float length = static_cast(indices_length); - for (size_t j=0; j( mean[j] / static_cast(indices_length) ); - } - variance /= static_cast( length ); - variance -= distance_(mean, ZeroIterator(), veclen_); - - DistanceType radius = 0; - for (unsigned int i=0; iradius) { - radius = tmp; - } - } - - node->variance = variance; - node->radius = radius; - node->pivot = mean; - } - - - void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length) - { - const unsigned int accumulator_veclen = static_cast( - veclen_*sizeof(CentersType)*BITS_PER_CHAR); - - unsigned long long variance = 0ull; - CentersType* mean = new CentersType[veclen_]; - memoryCounter_ += int(veclen_*sizeof(CentersType)); - unsigned int* mean_accumulator = new unsigned int[accumulator_veclen]; - - memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen); - - for (unsigned int i=0; i( ensureSquareDistance( - distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); - unsigned char* vec = (unsigned char*)dataset_[indices[i]]; - for (size_t k=0, l=0; k>1) & 0x01; - mean_accumulator[k+2] += (vec[l]>>2) & 0x01; - mean_accumulator[k+3] += (vec[l]>>3) & 0x01; - mean_accumulator[k+4] += (vec[l]>>4) & 0x01; - mean_accumulator[k+5] += (vec[l]>>5) & 0x01; - mean_accumulator[k+6] += (vec[l]>>6) & 0x01; - mean_accumulator[k+7] += (vec[l]>>7) & 0x01; - } - } - double cnt = static_cast(indices_length); - unsigned char* char_mean = (unsigned char*)mean; - for (size_t k=0, l=0; k( - (((int)(0.5 + (double)(mean_accumulator[k]) / cnt))) - | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1) - | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2) - | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3) - | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4) - | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5) - | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6) - | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7)); - } - variance = static_cast( - 0.5 + static_cast(variance) / static_cast(indices_length)); - variance -= static_cast( - ensureSquareDistance( - distance_(mean, ZeroIterator(), veclen_))); - - DistanceType radius = 0; - for (unsigned int i=0; iradius) { - radius = tmp; - } - } - - node->variance = static_cast(variance); - node->radius = radius; - node->pivot = mean; - - delete[] mean_accumulator; - } - - - void computeDnaNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length) - { - const unsigned int histos_veclen = static_cast( - veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); - - unsigned long long variance = 0ull; - unsigned int* histograms = new unsigned int[histos_veclen]; - memset(histograms, 0, sizeof(unsigned int)*histos_veclen); - - for (unsigned int i=0; i( ensureSquareDistance( - distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); - - unsigned char* vec = (unsigned char*)dataset_[indices[i]]; - for (size_t k=0, l=0; k>2) & 0x03)]++; - histograms[k + 8 + ((vec[l]>>4) & 0x03)]++; - histograms[k +12 + ((vec[l]>>6) & 0x03)]++; - } - } - - CentersType* mean = new CentersType[veclen_]; - memoryCounter_ += int(veclen_*sizeof(CentersType)); - unsigned char* char_mean = (unsigned char*)mean; - unsigned int* h = histograms; - for (size_t k=0, l=0; k h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 - : h[k] > h[k+3] ? 0x00 : 0x11 - : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 - : h[k+1] > h[k+3] ? 0x01 : 0x11) - | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 - : h[k+4] > h[k+7] ? 0x00 : 0x1100 - : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 - : h[k+5] > h[k+7] ? 0x0100 : 0x1100) - | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 - : h[k+8] >h[k+11] ? 0x00 : 0x110000 - : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 - : h[k+9] >h[k+11] ? 0x010000 : 0x110000) - | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 - : h[k+12] >h[k+15] ? 0x00 : 0x11000000 - : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 - : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); - } - variance = static_cast( - 0.5 + static_cast(variance) / static_cast(indices_length)); - variance -= static_cast( - ensureSquareDistance( - distance_(mean, ZeroIterator(), veclen_))); - - DistanceType radius = 0; - for (unsigned int i=0; iradius) { - radius = tmp; - } - } - - node->variance = static_cast(variance); - node->radius = radius; - node->pivot = mean; - - delete[] histograms; - } - - - template - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const DistType* identifier) - { - (void)identifier; - computeNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::HammingLUT* identifier) - { - (void)identifier; - computeBitfieldNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::Hamming* identifier) - { - (void)identifier; - computeBitfieldNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::Hamming2* identifier) - { - (void)identifier; - computeBitfieldNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::DNAmmingLUT* identifier) - { - (void)identifier; - computeDnaNodeStatistics(node, indices, indices_length); - } - - void computeNodeStatistics(KMeansNodePtr node, int* indices, - unsigned int indices_length, - const cvflann::DNAmming2* identifier) - { - (void)identifier; - computeDnaNodeStatistics(node, indices, indices_length); - } - - - void refineClustering(int* indices, int indices_length, int branching, CentersType** centers, - std::vector& radiuses, int* belongs_to, int* count) - { - cv::AutoBuffer dcenters_buf(branching*veclen_); - Matrix dcenters(dcenters_buf.data(), branching, veclen_); - - bool converged = false; - int iteration = 0; - while (!converged && iteration new_centroids(indices_length); - std::vector sq_dists(indices_length); - - // reassign points to clusters - KMeansDistanceComputer > invoker( - distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists); - parallel_for_(cv::Range(0, (int)indices_length), invoker); - - for (int i=0; i < (int)indices_length; ++i) { - DistanceType sq_dist(sq_dists[i]); - int new_centroid(new_centroids[i]); - if (sq_dist > radiuses[new_centroid]) { - radiuses[new_centroid] = sq_dist; - } - if (new_centroid != belongs_to[i]) { - count[belongs_to[i]]--; - count[new_centroid]++; - belongs_to[i] = new_centroid; - converged = false; - } - } - - for (int i=0; i& radiuses, int* belongs_to, int* count) - { - for (int i=0; i( - veclen_*sizeof(ElementType)*BITS_PER_CHAR); - cv::AutoBuffer dcenters_buf(branching*accumulator_veclen); - Matrix dcenters(dcenters_buf.data(), branching, accumulator_veclen); - - bool converged = false; - int iteration = 0; - while (!converged && iteration>1) & 0x01; - dcenter[k+2] += (vec[l]>>2) & 0x01; - dcenter[k+3] += (vec[l]>>3) & 0x01; - dcenter[k+4] += (vec[l]>>4) & 0x01; - dcenter[k+5] += (vec[l]>>5) & 0x01; - dcenter[k+6] += (vec[l]>>6) & 0x01; - dcenter[k+7] += (vec[l]>>7) & 0x01; - } - } - for (int i=0; i(count[i]); - unsigned int* dcenter = dcenters[i]; - unsigned char* charCenter = (unsigned char*)centers[i]; - for (size_t k=0, l=0; k( - (((int)(0.5 + (double)(dcenter[k]) / cnt))) - | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1) - | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2) - | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3) - | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4) - | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5) - | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6) - | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7)); - } - } - - std::vector new_centroids(indices_length); - std::vector dists(indices_length); - - // reassign points to clusters - KMeansDistanceComputer invoker( - distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); - parallel_for_(cv::Range(0, (int)indices_length), invoker); - - for (int i=0; i < indices_length; ++i) { - DistanceType dist(dists[i]); - int new_centroid(new_centroids[i]); - if (dist > radiuses[new_centroid]) { - radiuses[new_centroid] = dist; - } - if (new_centroid != belongs_to[i]) { - count[belongs_to[i]]--; - count[new_centroid]++; - belongs_to[i] = new_centroid; - converged = false; - } - } - - for (int i=0; i& radiuses, int* belongs_to, int* count) - { - for (int i=0; i( - veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); - cv::AutoBuffer histos_buf(branching*histos_veclen); - Matrix histos(histos_buf.data(), branching, histos_veclen); - - bool converged = false; - int iteration = 0; - while (!converged && iteration>2) & 0x03)]++; - h[k + 8 + ((vec[l]>>4) & 0x03)]++; - h[k +12 + ((vec[l]>>6) & 0x03)]++; - } - } - for (int i=0; i h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 - : h[k] > h[k+3] ? 0x00 : 0x11 - : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 - : h[k+1] > h[k+3] ? 0x01 : 0x11) - | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 - : h[k+4] > h[k+7] ? 0x00 : 0x1100 - : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 - : h[k+5] > h[k+7] ? 0x0100 : 0x1100) - | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 - : h[k+8] >h[k+11] ? 0x00 : 0x110000 - : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 - : h[k+9] >h[k+11] ? 0x010000 : 0x110000) - | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 - : h[k+12] >h[k+15] ? 0x00 : 0x11000000 - : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 - : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); - } - } - - std::vector new_centroids(indices_length); - std::vector dists(indices_length); - - // reassign points to clusters - KMeansDistanceComputer invoker( - distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); - parallel_for_(cv::Range(0, (int)indices_length), invoker); - - for (int i=0; i < indices_length; ++i) { - DistanceType dist(dists[i]); - int new_centroid(new_centroids[i]); - if (dist > radiuses[new_centroid]) { - radiuses[new_centroid] = dist; - } - if (new_centroid != belongs_to[i]) { - count[belongs_to[i]]--; - count[new_centroid]++; - belongs_to[i] = new_centroid; - converged = false; - } - } - - for (int i=0; i& radiuses, int* belongs_to, int* count) - { - // compute kmeans clustering for each of the resulting clusters - node->childs = pool_.allocate(branching); - int start = 0; - int end = start; - for (int c=0; c(), veclen_); - variance += d; - mean_radius += static_cast( sqrt(d) ); - std::swap(indices[i],indices[end]); - std::swap(belongs_to[i],belongs_to[end]); - end++; - } - } - variance /= s; - mean_radius /= s; - variance -= distance_(centers[c], ZeroIterator(), veclen_); - - node->childs[c] = pool_.allocate(); - std::memset(node->childs[c], 0, sizeof(KMeansNode)); - node->childs[c]->radius = radiuses[c]; - node->childs[c]->pivot = centers[c]; - node->childs[c]->variance = variance; - node->childs[c]->mean_radius = mean_radius; - computeClustering(node->childs[c],indices+start, end-start, branching, level+1); - start=end; - } - } - - - void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length, - int branching, int level, CentersType** centers, - std::vector& radiuses, int* belongs_to, int* count) - { - // compute kmeans clustering for each of the resulting clusters - node->childs = pool_.allocate(branching); - int start = 0; - int end = start; - for (int c=0; c(), veclen_); - variance += static_cast( ensureSquareDistance(d) ); - mean_radius += ensureSimpleDistance(d); - std::swap(indices[i],indices[end]); - std::swap(belongs_to[i],belongs_to[end]); - end++; - } - } - mean_radius = static_cast( - 0.5f + static_cast(mean_radius) / static_cast(s)); - variance = static_cast( - 0.5 + static_cast(variance) / static_cast(s)); - variance -= static_cast( - ensureSquareDistance( - distance_(centers[c], ZeroIterator(), veclen_))); - - node->childs[c] = pool_.allocate(); - std::memset(node->childs[c], 0, sizeof(KMeansNode)); - node->childs[c]->radius = radiuses[c]; - node->childs[c]->pivot = centers[c]; - node->childs[c]->variance = static_cast(variance); - node->childs[c]->mean_radius = mean_radius; - computeClustering(node->childs[c],indices+start, end-start, branching, level+1); - start=end; - } - } - - - template - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const DistType* identifier) - { - (void)identifier; - refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - /** - * The methods responsible with doing the recursive hierarchical clustering on - * binary vectors. - * As some might have heard that KMeans on binary data doesn't make sense, - * it's worth a little explanation why it actually fairly works. As - * with the Hierarchical Clustering algortihm, we seed several centers for the - * current node by picking some of its points. Then in a first pass each point - * of the node is then related to its closest center. Now let's have a look at - * the 5 central dimensions of the 9 following points: - * - * xxxxxx11100xxxxx (1) - * xxxxxx11010xxxxx (2) - * xxxxxx11001xxxxx (3) - * xxxxxx10110xxxxx (4) - * xxxxxx10101xxxxx (5) - * xxxxxx10011xxxxx (6) - * xxxxxx01110xxxxx (7) - * xxxxxx01101xxxxx (8) - * xxxxxx01011xxxxx (9) - * sum _____ - * of 1: 66555 - * - * Even if the barycenter notion doesn't apply, we can set a center - * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing - * on for these points. - * - * Note that convergence isn't ensured anymore. In practice, using Gonzales - * as seeding algorithm should be fine for getting convergence ("iterations" - * value can be set to -1). But with KMeans++ seeding you should definitely - * set a maximum number of iterations (but make it higher than the "iterations" - * default value of 11). - * - * Params: - * node = the node to cluster - * indices = indices of the points belonging to the current node - * indices_length = number of points in the current node - * branching = the branching factor to use in the clustering - * level = 0 for the root node, it increases with the subdivision levels - * centers = clusters centers to compute - * radiuses = radiuses of clusters - * belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to - * count = array storing the number of indices for a given center id - * identifier = dummy pointer on an instance of Distance (use to branch correctly among templates) - */ - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::HammingLUT* identifier) - { - (void)identifier; - refineBitfieldClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::Hamming* identifier) - { - (void)identifier; - refineBitfieldClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::Hamming2* identifier) - { - (void)identifier; - refineBitfieldClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier) - { - (void)identifier; - refineDnaClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - void refineAndSplitClustering( - KMeansNodePtr node, int* indices, int indices_length, int branching, - int level, CentersType** centers, std::vector& radiuses, - int* belongs_to, int* count, const cvflann::DNAmming2* identifier) - { - (void)identifier; - refineDnaClustering( - indices, indices_length, branching, centers, radiuses, belongs_to, count); - - computeAnyBitfieldSubClustering(node, indices, indices_length, branching, - level, centers, radiuses, belongs_to, count); - } - - - /** - * The method responsible with actually doing the recursive hierarchical - * clustering - * - * Params: - * node = the node to cluster - * indices = indices of the points belonging to the current node - * branching = the branching factor to use in the clustering - * - * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) - */ - void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level) - { - node->size = indices_length; - node->level = level; - - if (indices_length < branching) { - node->indices = indices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - cv::AutoBuffer centers_idx_buf(branching); - int* centers_idx = centers_idx_buf.data(); - int centers_length; - (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length); - - if (centers_lengthindices = indices; - std::sort(node->indices,node->indices+indices_length); - node->childs = NULL; - return; - } - - - std::vector radiuses(branching); - cv::AutoBuffer count_buf(branching); - int* count = count_buf.data(); - for (int i=0; i belongs_to_buf(indices_length); - int* belongs_to = belongs_to_buf.data(); - for (int i=0; inew_sq_dist) { - belongs_to[i] = j; - sq_dist = new_sq_dist; - } - } - if (sq_dist>radiuses[belongs_to[i]]) { - radiuses[belongs_to[i]] = sq_dist; - } - count[belongs_to[i]]++; - } - - CentersType** centers = new CentersType*[branching]; - - Distance* dummy = NULL; - refineAndSplitClustering(node, indices, indices_length, branching, level, - centers, radiuses, belongs_to, count, dummy); - - delete[] centers; - } - - - /** - * Performs one descent in the hierarchical k-means tree. The branches not - * visited are stored in a priority queue. - * - * Params: - * node = node to explore - * result = container for the k-nearest neighbors found - * vec = query points - * checks = how many points in the dataset have been checked so far - * maxChecks = maximum dataset points to checks - */ - - - void findNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, - const cv::Ptr>& heap) - { - // Ignore those clusters that are too far away - { - DistanceType bsq = distance_(vec, node->pivot, veclen_); - DistanceType rsq = node->radius; - DistanceType wsq = result.worstDist(); - - if (isSquareDistance()) - { - DistanceType val = bsq-rsq-wsq; - if ((val>0) && (val*val > 4*rsq*wsq)) - return; - } - else - { - if (bsq-rsq > wsq) - return; - } - } - - if (node->childs==NULL) { - if ((checks>=maxChecks) && result.full()) { - return; - } - checks += node->size; - for (int i=0; isize; ++i) { - int index = node->indices[i]; - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result.addPoint(dist, index); - } - } - else { - DistanceType* domain_distances = new DistanceType[branching_]; - int closest_center = exploreNodeBranches(node, vec, domain_distances, heap); - delete[] domain_distances; - findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap); - } - } - - /** - * Helper function that computes the nearest childs of a node to a given query point. - * Params: - * node = the node - * q = the query point - * distances = array with the distances to each child node. - * Returns: - */ - int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr>& heap) - { - - int best_index = 0; - domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_); - for (int i=1; ichilds[i]->pivot, veclen_); - if (domain_distances[i]childs[best_index]->pivot; - for (int i=0; i( - cb_index_*node->childs[i]->variance ); - - // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q); - // if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); - } - } - - return best_index; - } - - - /** - * Function the performs exact nearest neighbor search by traversing the entire tree. - */ - void findExactNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec) - { - // Ignore those clusters that are too far away - { - DistanceType bsq = distance_(vec, node->pivot, veclen_); - DistanceType rsq = node->radius; - DistanceType wsq = result.worstDist(); - - if (isSquareDistance()) - { - DistanceType val = bsq-rsq-wsq; - if ((val>0) && (val*val > 4*rsq*wsq)) - return; - } - else - { - if (bsq-rsq > wsq) - return; - } - } - - - if (node->childs==NULL) { - for (int i=0; isize; ++i) { - int index = node->indices[i]; - DistanceType dist = distance_(dataset_[index], vec, veclen_); - result.addPoint(dist, index); - } - } - else { - int* sort_indices = new int[branching_]; - - getCenterOrdering(node, vec, sort_indices); - - for (int i=0; ichilds[sort_indices[i]],result,vec); - } - - delete[] sort_indices; - } - } - - - /** - * Helper function. - * - * I computes the order in which to traverse the child nodes of a particular node. - */ - void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices) - { - DistanceType* domain_distances = new DistanceType[branching_]; - for (int i=0; ichilds[i]->pivot, veclen_); - - int j=0; - while (domain_distances[j]j; --k) { - domain_distances[k] = domain_distances[k-1]; - sort_indices[k] = sort_indices[k-1]; - } - domain_distances[j] = dist; - sort_indices[j] = i; - } - delete[] domain_distances; - } - - /** - * Method that computes the squared distance from the query point q - * from inside region with center c to the border between this - * region and the region with center p - */ - DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q) - { - DistanceType sum = 0; - DistanceType sum2 = 0; - - for (int i=0; ivariance*root->size; - - while (clusterCount::max)(); - int splitIndex = -1; - - for (int i=0; ichilds != NULL) { - - DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size; - - for (int j=0; jchilds[j]->variance*clusters[i]->childs[j]->size; - } - if (variance clusters_length) break; - - meanVariance = minVariance; - - // split node - KMeansNodePtr toSplit = clusters[splitIndex]; - clusters[splitIndex] = toSplit->childs[0]; - for (int i=1; ichilds[i]; - } - } - - varianceValue = meanVariance/root->size; - return clusterCount; - } - -private: - /** The branching factor used in the hierarchical k-means clustering */ - int branching_; - - /** Number of kmeans trees (default is one) */ - int trees_; - - /** Maximum number of iterations to use when performing k-means clustering */ - int iterations_; - - /** Algorithm for choosing the cluster centers */ - flann_centers_init_t centers_init_; - - /** - * Cluster border index. This is used in the tree search phase when determining - * the closest cluster to explore next. A zero value takes into account only - * the cluster centres, a value greater then zero also take into account the size - * of the cluster. - */ - float cb_index_; - - /** - * The dataset used by this index - */ - const Matrix dataset_; - - /** Index parameters */ - IndexParams index_params_; - - /** - * Number of features in the dataset. - */ - size_t size_; - - /** - * Length of each feature. - */ - size_t veclen_; - - /** - * The root node in the tree. - */ - KMeansNodePtr* root_; - - /** - * Array of indices to vectors in the dataset. - */ - int** indices_; - - /** - * The distance - */ - Distance distance_; - - /** - * Pooled memory allocator. - */ - PooledAllocator pool_; - - /** - * Memory occupied by the index. - */ - int memoryCounter_; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_KMEANS_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_KMEANS_INDEX_H_ +#define OPENCV_FLANN_KMEANS_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include +#include + +#include "general.h" +#include "nn_index.h" +#include "dist.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" +#include "logger.h" + +#define BITS_PER_CHAR 8 +#define BITS_PER_BASE 2 // for DNA/RNA sequences +#define BASE_PER_CHAR (BITS_PER_CHAR/BITS_PER_BASE) +#define HISTOS_PER_BASE (1< +class KMeansIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + typedef typename Distance::CentersType CentersType; + + typedef typename Distance::is_kdtree_distance is_kdtree_distance; + typedef typename Distance::is_vector_space_distance is_vector_space_distance; + + + + typedef void (KMeansIndex::* centersAlgFunction)(int, int*, int, int*, int&); + + /** + * The function used for choosing the cluster centers. + */ + centersAlgFunction chooseCenters; + + + + /** + * Chooses the initial centers in the k-means clustering in a random manner. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * indices_length = length of indices vector + * + */ + void chooseCentersRandom(int k, int* indices, int indices_length, int* centers, int& centers_length) + { + UniqueRandom r(indices_length); + + int index; + for (index=0; index=0 && rnd < n); + + centers[0] = indices[rnd]; + + int index; + for (index=1; indexbest_val) { + best_val = dist; + best_index = j; + } + } + if (best_index!=-1) { + centers[index] = indices[best_index]; + } + else { + break; + } + } + centers_length = index; + } + + + /** + * Chooses the initial centers in the k-means using the algorithm + * proposed in the KMeans++ paper: + * Arthur, David; Vassilvitskii, Sergei - k-means++: The Advantages of Careful Seeding + * + * Implementation of this function was converted from the one provided in Arthur's code. + * + * Params: + * k = number of centers + * vecs = the dataset of points + * indices = indices in the dataset + * Returns: + */ + void chooseCentersKMeanspp(int k, int* indices, int indices_length, int* centers, int& centers_length) + { + int n = indices_length; + + double currentPot = 0; + DistanceType* closestDistSq = new DistanceType[n]; + + // Choose one random center and set the closestDistSq values + int index = rand_int(n); + CV_DbgAssert(index >=0 && index < n); + centers[0] = indices[index]; + + for (int i = 0; i < n; i++) { + closestDistSq[i] = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); + closestDistSq[i] = ensureSquareDistance( closestDistSq[i] ); + currentPot += closestDistSq[i]; + } + + + const int numLocalTries = 1; + + // Choose each center + int centerCount; + for (centerCount = 1; centerCount < k; centerCount++) { + + // Repeat several trials + double bestNewPot = -1; + int bestNewIndex = -1; + for (int localTrial = 0; localTrial < numLocalTries; localTrial++) { + + // Choose our center - have to be slightly careful to return a valid answer even accounting + // for possible rounding errors + double randVal = rand_double(currentPot); + for (index = 0; index < n-1; index++) { + if (randVal <= closestDistSq[index]) break; + else randVal -= closestDistSq[index]; + } + + // Compute the new potential + double newPot = 0; + for (int i = 0; i < n; i++) { + DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[index]], dataset_.cols); + newPot += std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + + // Store the best result + if ((bestNewPot < 0)||(newPot < bestNewPot)) { + bestNewPot = newPot; + bestNewIndex = index; + } + } + + // Add the appropriate center + centers[centerCount] = indices[bestNewIndex]; + currentPot = bestNewPot; + for (int i = 0; i < n; i++) { + DistanceType dist = distance_(dataset_[indices[i]], dataset_[indices[bestNewIndex]], dataset_.cols); + closestDistSq[i] = std::min( ensureSquareDistance(dist), closestDistSq[i] ); + } + } + + centers_length = centerCount; + + delete[] closestDistSq; + } + + + +public: + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_KMEANS; + } + + template + class KMeansDistanceComputer : public cv::ParallelLoopBody + { + public: + KMeansDistanceComputer(Distance _distance, const Matrix& _dataset, + const int _branching, const int* _indices, const CentersContainerType& _dcenters, + const size_t _veclen, std::vector &_new_centroids, + std::vector &_sq_dists) + : distance(_distance) + , dataset(_dataset) + , branching(_branching) + , indices(_indices) + , dcenters(_dcenters) + , veclen(_veclen) + , new_centroids(_new_centroids) + , sq_dists(_sq_dists) + { + } + + void operator()(const cv::Range& range) const CV_OVERRIDE + { + const int begin = range.start; + const int end = range.end; + + for( int i = begin; inew_sq_dist) { + new_centroid = j; + sq_dist = new_sq_dist; + } + } + sq_dists[i] = sq_dist; + new_centroids[i] = new_centroid; + } + } + + private: + Distance distance; + const Matrix& dataset; + const int branching; + const int* indices; + const CentersContainerType& dcenters; + const size_t veclen; + std::vector &new_centroids; + std::vector &sq_dists; + KMeansDistanceComputer& operator=( const KMeansDistanceComputer & ) { return *this; } + }; + + /** + * Index constructor + * + * Params: + * inputData = dataset with the input features + * params = parameters passed to the hierarchical k-means algorithm + */ + KMeansIndex(const Matrix& inputData, const IndexParams& params = KMeansIndexParams(), + Distance d = Distance()) + : dataset_(inputData), index_params_(params), root_(NULL), indices_(NULL), distance_(d) + { + memoryCounter_ = 0; + + size_ = dataset_.rows; + veclen_ = dataset_.cols; + + branching_ = get_param(params,"branching",32); + trees_ = get_param(params,"trees",1); + iterations_ = get_param(params,"iterations",11); + if (iterations_<0) { + iterations_ = (std::numeric_limits::max)(); + } + centers_init_ = get_param(params,"centers_init",FLANN_CENTERS_RANDOM); + + if (centers_init_==FLANN_CENTERS_RANDOM) { + chooseCenters = &KMeansIndex::chooseCentersRandom; + } + else if (centers_init_==FLANN_CENTERS_GONZALES) { + chooseCenters = &KMeansIndex::chooseCentersGonzales; + } + else if (centers_init_==FLANN_CENTERS_KMEANSPP) { + chooseCenters = &KMeansIndex::chooseCentersKMeanspp; + } + else { + FLANN_THROW(cv::Error::StsBadArg, "Unknown algorithm for choosing initial centers."); + } + cb_index_ = 0.4f; + + root_ = new KMeansNodePtr[trees_]; + indices_ = new int*[trees_]; + + for (int i=0; i(); + std::memset(root_[i], 0, sizeof(KMeansNode)); + + Distance* dummy = NULL; + computeNodeStatistics(root_[i], indices_[i], (unsigned int)size_, dummy); + + computeClustering(root_[i], indices_[i], (int)size_, branching_,0); + } + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream, branching_); + save_value(stream, iterations_); + save_value(stream, memoryCounter_); + save_value(stream, cb_index_); + save_value(stream, trees_); + for (int i=0; i& result, const ElementType* vec, const SearchParams& searchParams) CV_OVERRIDE + { + + const int maxChecks = get_param(searchParams,"checks",32); + + if (maxChecks==FLANN_CHECKS_UNLIMITED) { + findExactNN(root_[0], result, vec); + } + else { + // Priority queue storing intermediate branches in the best-bin-first search + const cv::Ptr>& heap = Heap::getPooledInstance(cv::utils::getThreadID(), (int)size_); + + int checks = 0; + for (int i=0; i= maxChecks) && result.full()) + break; + } + + BranchSt branch; + while (heap->popMin(branch) && (checks& centers) + { + int numClusters = centers.rows; + if (numClusters<1) { + FLANN_THROW(cv::Error::StsBadArg, "Number of clusters must be at least 1"); + } + + DistanceType variance; + KMeansNodePtr* clusters = new KMeansNodePtr[numClusters]; + + int clusterCount = getMinVarianceClusters(root_[0], clusters, numClusters, variance); + + Logger::info("Clusters requested: %d, returning %d\n",numClusters, clusterCount); + + for (int i=0; ipivot; + for (size_t j=0; j BranchSt; + + + + + void save_tree(FILE* stream, KMeansNodePtr node, int num) + { + save_value(stream, *node); + save_value(stream, *(node->pivot), (int)veclen_); + if (node->childs==NULL) { + int indices_offset = (int)(node->indices - indices_[num]); + save_value(stream, indices_offset); + } + else { + for(int i=0; ichilds[i], num); + } + } + } + + + void load_tree(FILE* stream, KMeansNodePtr& node, int num) + { + node = pool_.allocate(); + load_value(stream, *node); + node->pivot = new CentersType[veclen_]; + load_value(stream, *(node->pivot), (int)veclen_); + if (node->childs==NULL) { + int indices_offset; + load_value(stream, indices_offset); + node->indices = indices_[num] + indices_offset; + } + else { + node->childs = pool_.allocate(branching_); + for(int i=0; ichilds[i], num); + } + } + } + + + /** + * Helper function + */ + void free_centers(KMeansNodePtr node) + { + delete[] node->pivot; + if (node->childs!=NULL) { + for (int k=0; kchilds[k]); + } + } + } + + void free_centers() + { + if (root_ != NULL) { + for(int i=0; i(), veclen_); + } + float length = static_cast(indices_length); + for (size_t j=0; j( mean[j] / static_cast(indices_length) ); + } + variance /= static_cast( length ); + variance -= distance_(mean, ZeroIterator(), veclen_); + + DistanceType radius = 0; + for (unsigned int i=0; iradius) { + radius = tmp; + } + } + + node->variance = variance; + node->radius = radius; + node->pivot = mean; + } + + + void computeBitfieldNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length) + { + const unsigned int accumulator_veclen = static_cast( + veclen_*sizeof(CentersType)*BITS_PER_CHAR); + + unsigned long long variance = 0ull; + CentersType* mean = new CentersType[veclen_]; + memoryCounter_ += int(veclen_*sizeof(CentersType)); + unsigned int* mean_accumulator = new unsigned int[accumulator_veclen]; + + memset(mean_accumulator, 0, sizeof(unsigned int)*accumulator_veclen); + + for (unsigned int i=0; i( ensureSquareDistance( + distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); + unsigned char* vec = (unsigned char*)dataset_[indices[i]]; + for (size_t k=0, l=0; k>1) & 0x01; + mean_accumulator[k+2] += (vec[l]>>2) & 0x01; + mean_accumulator[k+3] += (vec[l]>>3) & 0x01; + mean_accumulator[k+4] += (vec[l]>>4) & 0x01; + mean_accumulator[k+5] += (vec[l]>>5) & 0x01; + mean_accumulator[k+6] += (vec[l]>>6) & 0x01; + mean_accumulator[k+7] += (vec[l]>>7) & 0x01; + } + } + double cnt = static_cast(indices_length); + unsigned char* char_mean = (unsigned char*)mean; + for (size_t k=0, l=0; k( + (((int)(0.5 + (double)(mean_accumulator[k]) / cnt))) + | (((int)(0.5 + (double)(mean_accumulator[k+1]) / cnt))<<1) + | (((int)(0.5 + (double)(mean_accumulator[k+2]) / cnt))<<2) + | (((int)(0.5 + (double)(mean_accumulator[k+3]) / cnt))<<3) + | (((int)(0.5 + (double)(mean_accumulator[k+4]) / cnt))<<4) + | (((int)(0.5 + (double)(mean_accumulator[k+5]) / cnt))<<5) + | (((int)(0.5 + (double)(mean_accumulator[k+6]) / cnt))<<6) + | (((int)(0.5 + (double)(mean_accumulator[k+7]) / cnt))<<7)); + } + variance = static_cast( + 0.5 + static_cast(variance) / static_cast(indices_length)); + variance -= static_cast( + ensureSquareDistance( + distance_(mean, ZeroIterator(), veclen_))); + + DistanceType radius = 0; + for (unsigned int i=0; iradius) { + radius = tmp; + } + } + + node->variance = static_cast(variance); + node->radius = radius; + node->pivot = mean; + + delete[] mean_accumulator; + } + + + void computeDnaNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length) + { + const unsigned int histos_veclen = static_cast( + veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); + + unsigned long long variance = 0ull; + unsigned int* histograms = new unsigned int[histos_veclen]; + memset(histograms, 0, sizeof(unsigned int)*histos_veclen); + + for (unsigned int i=0; i( ensureSquareDistance( + distance_(dataset_[indices[i]], ZeroIterator(), veclen_))); + + unsigned char* vec = (unsigned char*)dataset_[indices[i]]; + for (size_t k=0, l=0; k>2) & 0x03)]++; + histograms[k + 8 + ((vec[l]>>4) & 0x03)]++; + histograms[k +12 + ((vec[l]>>6) & 0x03)]++; + } + } + + CentersType* mean = new CentersType[veclen_]; + memoryCounter_ += int(veclen_*sizeof(CentersType)); + unsigned char* char_mean = (unsigned char*)mean; + unsigned int* h = histograms; + for (size_t k=0, l=0; k h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 + : h[k] > h[k+3] ? 0x00 : 0x11 + : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 + : h[k+1] > h[k+3] ? 0x01 : 0x11) + | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 + : h[k+4] > h[k+7] ? 0x00 : 0x1100 + : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 + : h[k+5] > h[k+7] ? 0x0100 : 0x1100) + | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 + : h[k+8] >h[k+11] ? 0x00 : 0x110000 + : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 + : h[k+9] >h[k+11] ? 0x010000 : 0x110000) + | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 + : h[k+12] >h[k+15] ? 0x00 : 0x11000000 + : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 + : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); + } + variance = static_cast( + 0.5 + static_cast(variance) / static_cast(indices_length)); + variance -= static_cast( + ensureSquareDistance( + distance_(mean, ZeroIterator(), veclen_))); + + DistanceType radius = 0; + for (unsigned int i=0; iradius) { + radius = tmp; + } + } + + node->variance = static_cast(variance); + node->radius = radius; + node->pivot = mean; + + delete[] histograms; + } + + + template + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const DistType* identifier) + { + (void)identifier; + computeNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::HammingLUT* identifier) + { + (void)identifier; + computeBitfieldNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::Hamming* identifier) + { + (void)identifier; + computeBitfieldNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::Hamming2* identifier) + { + (void)identifier; + computeBitfieldNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::DNAmmingLUT* identifier) + { + (void)identifier; + computeDnaNodeStatistics(node, indices, indices_length); + } + + void computeNodeStatistics(KMeansNodePtr node, int* indices, + unsigned int indices_length, + const cvflann::DNAmming2* identifier) + { + (void)identifier; + computeDnaNodeStatistics(node, indices, indices_length); + } + + + void refineClustering(int* indices, int indices_length, int branching, CentersType** centers, + std::vector& radiuses, int* belongs_to, int* count) + { + cv::AutoBuffer dcenters_buf(branching*veclen_); + Matrix dcenters(dcenters_buf.data(), branching, veclen_); + + bool converged = false; + int iteration = 0; + while (!converged && iteration new_centroids(indices_length); + std::vector sq_dists(indices_length); + + // reassign points to clusters + KMeansDistanceComputer > invoker( + distance_, dataset_, branching, indices, dcenters, veclen_, new_centroids, sq_dists); + parallel_for_(cv::Range(0, (int)indices_length), invoker); + + for (int i=0; i < (int)indices_length; ++i) { + DistanceType sq_dist(sq_dists[i]); + int new_centroid(new_centroids[i]); + if (sq_dist > radiuses[new_centroid]) { + radiuses[new_centroid] = sq_dist; + } + if (new_centroid != belongs_to[i]) { + count[belongs_to[i]]--; + count[new_centroid]++; + belongs_to[i] = new_centroid; + converged = false; + } + } + + for (int i=0; i& radiuses, int* belongs_to, int* count) + { + for (int i=0; i( + veclen_*sizeof(ElementType)*BITS_PER_CHAR); + cv::AutoBuffer dcenters_buf(branching*accumulator_veclen); + Matrix dcenters(dcenters_buf.data(), branching, accumulator_veclen); + + bool converged = false; + int iteration = 0; + while (!converged && iteration>1) & 0x01; + dcenter[k+2] += (vec[l]>>2) & 0x01; + dcenter[k+3] += (vec[l]>>3) & 0x01; + dcenter[k+4] += (vec[l]>>4) & 0x01; + dcenter[k+5] += (vec[l]>>5) & 0x01; + dcenter[k+6] += (vec[l]>>6) & 0x01; + dcenter[k+7] += (vec[l]>>7) & 0x01; + } + } + for (int i=0; i(count[i]); + unsigned int* dcenter = dcenters[i]; + unsigned char* charCenter = (unsigned char*)centers[i]; + for (size_t k=0, l=0; k( + (((int)(0.5 + (double)(dcenter[k]) / cnt))) + | (((int)(0.5 + (double)(dcenter[k+1]) / cnt))<<1) + | (((int)(0.5 + (double)(dcenter[k+2]) / cnt))<<2) + | (((int)(0.5 + (double)(dcenter[k+3]) / cnt))<<3) + | (((int)(0.5 + (double)(dcenter[k+4]) / cnt))<<4) + | (((int)(0.5 + (double)(dcenter[k+5]) / cnt))<<5) + | (((int)(0.5 + (double)(dcenter[k+6]) / cnt))<<6) + | (((int)(0.5 + (double)(dcenter[k+7]) / cnt))<<7)); + } + } + + std::vector new_centroids(indices_length); + std::vector dists(indices_length); + + // reassign points to clusters + KMeansDistanceComputer invoker( + distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); + parallel_for_(cv::Range(0, (int)indices_length), invoker); + + for (int i=0; i < indices_length; ++i) { + DistanceType dist(dists[i]); + int new_centroid(new_centroids[i]); + if (dist > radiuses[new_centroid]) { + radiuses[new_centroid] = dist; + } + if (new_centroid != belongs_to[i]) { + count[belongs_to[i]]--; + count[new_centroid]++; + belongs_to[i] = new_centroid; + converged = false; + } + } + + for (int i=0; i& radiuses, int* belongs_to, int* count) + { + for (int i=0; i( + veclen_*sizeof(CentersType)*(HISTOS_PER_BASE*BASE_PER_CHAR)); + cv::AutoBuffer histos_buf(branching*histos_veclen); + Matrix histos(histos_buf.data(), branching, histos_veclen); + + bool converged = false; + int iteration = 0; + while (!converged && iteration>2) & 0x03)]++; + h[k + 8 + ((vec[l]>>4) & 0x03)]++; + h[k +12 + ((vec[l]>>6) & 0x03)]++; + } + } + for (int i=0; i h[k+1] ? h[k+2] > h[k+3] ? h[k] > h[k+2] ? 0x00 : 0x10 + : h[k] > h[k+3] ? 0x00 : 0x11 + : h[k+2] > h[k+3] ? h[k+1] > h[k+2] ? 0x01 : 0x10 + : h[k+1] > h[k+3] ? 0x01 : 0x11) + | (h[k+4]>h[k+5] ? h[k+6] > h[k+7] ? h[k+4] > h[k+6] ? 0x00 : 0x1000 + : h[k+4] > h[k+7] ? 0x00 : 0x1100 + : h[k+6] > h[k+7] ? h[k+5] > h[k+6] ? 0x0100 : 0x1000 + : h[k+5] > h[k+7] ? 0x0100 : 0x1100) + | (h[k+8]>h[k+9] ? h[k+10]>h[k+11] ? h[k+8] >h[k+10] ? 0x00 : 0x100000 + : h[k+8] >h[k+11] ? 0x00 : 0x110000 + : h[k+10]>h[k+11] ? h[k+9] >h[k+10] ? 0x010000 : 0x100000 + : h[k+9] >h[k+11] ? 0x010000 : 0x110000) + | (h[k+12]>h[k+13] ? h[k+14]>h[k+15] ? h[k+12] >h[k+14] ? 0x00 : 0x10000000 + : h[k+12] >h[k+15] ? 0x00 : 0x11000000 + : h[k+14]>h[k+15] ? h[k+13] >h[k+14] ? 0x01000000 : 0x10000000 + : h[k+13] >h[k+15] ? 0x01000000 : 0x11000000); + } + } + + std::vector new_centroids(indices_length); + std::vector dists(indices_length); + + // reassign points to clusters + KMeansDistanceComputer invoker( + distance_, dataset_, branching, indices, centers, veclen_, new_centroids, dists); + parallel_for_(cv::Range(0, (int)indices_length), invoker); + + for (int i=0; i < indices_length; ++i) { + DistanceType dist(dists[i]); + int new_centroid(new_centroids[i]); + if (dist > radiuses[new_centroid]) { + radiuses[new_centroid] = dist; + } + if (new_centroid != belongs_to[i]) { + count[belongs_to[i]]--; + count[new_centroid]++; + belongs_to[i] = new_centroid; + converged = false; + } + } + + for (int i=0; i& radiuses, int* belongs_to, int* count) + { + // compute kmeans clustering for each of the resulting clusters + node->childs = pool_.allocate(branching); + int start = 0; + int end = start; + for (int c=0; c(), veclen_); + variance += d; + mean_radius += static_cast( sqrt(d) ); + std::swap(indices[i],indices[end]); + std::swap(belongs_to[i],belongs_to[end]); + end++; + } + } + variance /= s; + mean_radius /= s; + variance -= distance_(centers[c], ZeroIterator(), veclen_); + + node->childs[c] = pool_.allocate(); + std::memset(node->childs[c], 0, sizeof(KMeansNode)); + node->childs[c]->radius = radiuses[c]; + node->childs[c]->pivot = centers[c]; + node->childs[c]->variance = variance; + node->childs[c]->mean_radius = mean_radius; + computeClustering(node->childs[c],indices+start, end-start, branching, level+1); + start=end; + } + } + + + void computeAnyBitfieldSubClustering(KMeansNodePtr node, int* indices, int indices_length, + int branching, int level, CentersType** centers, + std::vector& radiuses, int* belongs_to, int* count) + { + // compute kmeans clustering for each of the resulting clusters + node->childs = pool_.allocate(branching); + int start = 0; + int end = start; + for (int c=0; c(), veclen_); + variance += static_cast( ensureSquareDistance(d) ); + mean_radius += ensureSimpleDistance(d); + std::swap(indices[i],indices[end]); + std::swap(belongs_to[i],belongs_to[end]); + end++; + } + } + mean_radius = static_cast( + 0.5f + static_cast(mean_radius) / static_cast(s)); + variance = static_cast( + 0.5 + static_cast(variance) / static_cast(s)); + variance -= static_cast( + ensureSquareDistance( + distance_(centers[c], ZeroIterator(), veclen_))); + + node->childs[c] = pool_.allocate(); + std::memset(node->childs[c], 0, sizeof(KMeansNode)); + node->childs[c]->radius = radiuses[c]; + node->childs[c]->pivot = centers[c]; + node->childs[c]->variance = static_cast(variance); + node->childs[c]->mean_radius = mean_radius; + computeClustering(node->childs[c],indices+start, end-start, branching, level+1); + start=end; + } + } + + + template + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const DistType* identifier) + { + (void)identifier; + refineClustering(indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + /** + * The methods responsible with doing the recursive hierarchical clustering on + * binary vectors. + * As some might have heard that KMeans on binary data doesn't make sense, + * it's worth a little explanation why it actually fairly works. As + * with the Hierarchical Clustering algortihm, we seed several centers for the + * current node by picking some of its points. Then in a first pass each point + * of the node is then related to its closest center. Now let's have a look at + * the 5 central dimensions of the 9 following points: + * + * xxxxxx11100xxxxx (1) + * xxxxxx11010xxxxx (2) + * xxxxxx11001xxxxx (3) + * xxxxxx10110xxxxx (4) + * xxxxxx10101xxxxx (5) + * xxxxxx10011xxxxx (6) + * xxxxxx01110xxxxx (7) + * xxxxxx01101xxxxx (8) + * xxxxxx01011xxxxx (9) + * sum _____ + * of 1: 66555 + * + * Even if the barycenter notion doesn't apply, we can set a center + * xxxxxx11111xxxxx that will better fit the five dimensions we are focusing + * on for these points. + * + * Note that convergence isn't ensured anymore. In practice, using Gonzales + * as seeding algorithm should be fine for getting convergence ("iterations" + * value can be set to -1). But with KMeans++ seeding you should definitely + * set a maximum number of iterations (but make it higher than the "iterations" + * default value of 11). + * + * Params: + * node = the node to cluster + * indices = indices of the points belonging to the current node + * indices_length = number of points in the current node + * branching = the branching factor to use in the clustering + * level = 0 for the root node, it increases with the subdivision levels + * centers = clusters centers to compute + * radiuses = radiuses of clusters + * belongs_to = LookUp Table returning, for a given indice id, the center id it belongs to + * count = array storing the number of indices for a given center id + * identifier = dummy pointer on an instance of Distance (use to branch correctly among templates) + */ + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::HammingLUT* identifier) + { + (void)identifier; + refineBitfieldClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::Hamming* identifier) + { + (void)identifier; + refineBitfieldClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::Hamming2* identifier) + { + (void)identifier; + refineBitfieldClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::DNAmmingLUT* identifier) + { + (void)identifier; + refineDnaClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + void refineAndSplitClustering( + KMeansNodePtr node, int* indices, int indices_length, int branching, + int level, CentersType** centers, std::vector& radiuses, + int* belongs_to, int* count, const cvflann::DNAmming2* identifier) + { + (void)identifier; + refineDnaClustering( + indices, indices_length, branching, centers, radiuses, belongs_to, count); + + computeAnyBitfieldSubClustering(node, indices, indices_length, branching, + level, centers, radiuses, belongs_to, count); + } + + + /** + * The method responsible with actually doing the recursive hierarchical + * clustering + * + * Params: + * node = the node to cluster + * indices = indices of the points belonging to the current node + * branching = the branching factor to use in the clustering + * + * TODO: for 1-sized clusters don't store a cluster center (it's the same as the single cluster point) + */ + void computeClustering(KMeansNodePtr node, int* indices, int indices_length, int branching, int level) + { + node->size = indices_length; + node->level = level; + + if (indices_length < branching) { + node->indices = indices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + cv::AutoBuffer centers_idx_buf(branching); + int* centers_idx = centers_idx_buf.data(); + int centers_length; + (this->*chooseCenters)(branching, indices, indices_length, centers_idx, centers_length); + + if (centers_lengthindices = indices; + std::sort(node->indices,node->indices+indices_length); + node->childs = NULL; + return; + } + + + std::vector radiuses(branching); + cv::AutoBuffer count_buf(branching); + int* count = count_buf.data(); + for (int i=0; i belongs_to_buf(indices_length); + int* belongs_to = belongs_to_buf.data(); + for (int i=0; inew_sq_dist) { + belongs_to[i] = j; + sq_dist = new_sq_dist; + } + } + if (sq_dist>radiuses[belongs_to[i]]) { + radiuses[belongs_to[i]] = sq_dist; + } + count[belongs_to[i]]++; + } + + CentersType** centers = new CentersType*[branching]; + + Distance* dummy = NULL; + refineAndSplitClustering(node, indices, indices_length, branching, level, + centers, radiuses, belongs_to, count, dummy); + + delete[] centers; + } + + + /** + * Performs one descent in the hierarchical k-means tree. The branches not + * visited are stored in a priority queue. + * + * Params: + * node = node to explore + * result = container for the k-nearest neighbors found + * vec = query points + * checks = how many points in the dataset have been checked so far + * maxChecks = maximum dataset points to checks + */ + + + void findNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec, int& checks, int maxChecks, + const cv::Ptr>& heap) + { + // Ignore those clusters that are too far away + { + DistanceType bsq = distance_(vec, node->pivot, veclen_); + DistanceType rsq = node->radius; + DistanceType wsq = result.worstDist(); + + if (isSquareDistance()) + { + DistanceType val = bsq-rsq-wsq; + if ((val>0) && (val*val > 4*rsq*wsq)) + return; + } + else + { + if (bsq-rsq > wsq) + return; + } + } + + if (node->childs==NULL) { + if ((checks>=maxChecks) && result.full()) { + return; + } + checks += node->size; + for (int i=0; isize; ++i) { + int index = node->indices[i]; + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result.addPoint(dist, index); + } + } + else { + DistanceType* domain_distances = new DistanceType[branching_]; + int closest_center = exploreNodeBranches(node, vec, domain_distances, heap); + delete[] domain_distances; + findNN(node->childs[closest_center],result,vec, checks, maxChecks, heap); + } + } + + /** + * Helper function that computes the nearest childs of a node to a given query point. + * Params: + * node = the node + * q = the query point + * distances = array with the distances to each child node. + * Returns: + */ + int exploreNodeBranches(KMeansNodePtr node, const ElementType* q, DistanceType* domain_distances, const cv::Ptr>& heap) + { + + int best_index = 0; + domain_distances[best_index] = distance_(q, node->childs[best_index]->pivot, veclen_); + for (int i=1; ichilds[i]->pivot, veclen_); + if (domain_distances[i]childs[best_index]->pivot; + for (int i=0; i( + cb_index_*node->childs[i]->variance ); + + // float dist_to_border = getDistanceToBorder(node.childs[i].pivot,best_center,q); + // if (domain_distances[i]insert(BranchSt(node->childs[i],domain_distances[i])); + } + } + + return best_index; + } + + + /** + * Function the performs exact nearest neighbor search by traversing the entire tree. + */ + void findExactNN(KMeansNodePtr node, ResultSet& result, const ElementType* vec) + { + // Ignore those clusters that are too far away + { + DistanceType bsq = distance_(vec, node->pivot, veclen_); + DistanceType rsq = node->radius; + DistanceType wsq = result.worstDist(); + + if (isSquareDistance()) + { + DistanceType val = bsq-rsq-wsq; + if ((val>0) && (val*val > 4*rsq*wsq)) + return; + } + else + { + if (bsq-rsq > wsq) + return; + } + } + + + if (node->childs==NULL) { + for (int i=0; isize; ++i) { + int index = node->indices[i]; + DistanceType dist = distance_(dataset_[index], vec, veclen_); + result.addPoint(dist, index); + } + } + else { + int* sort_indices = new int[branching_]; + + getCenterOrdering(node, vec, sort_indices); + + for (int i=0; ichilds[sort_indices[i]],result,vec); + } + + delete[] sort_indices; + } + } + + + /** + * Helper function. + * + * I computes the order in which to traverse the child nodes of a particular node. + */ + void getCenterOrdering(KMeansNodePtr node, const ElementType* q, int* sort_indices) + { + DistanceType* domain_distances = new DistanceType[branching_]; + for (int i=0; ichilds[i]->pivot, veclen_); + + int j=0; + while (domain_distances[j]j; --k) { + domain_distances[k] = domain_distances[k-1]; + sort_indices[k] = sort_indices[k-1]; + } + domain_distances[j] = dist; + sort_indices[j] = i; + } + delete[] domain_distances; + } + + /** + * Method that computes the squared distance from the query point q + * from inside region with center c to the border between this + * region and the region with center p + */ + DistanceType getDistanceToBorder(DistanceType* p, DistanceType* c, DistanceType* q) + { + DistanceType sum = 0; + DistanceType sum2 = 0; + + for (int i=0; ivariance*root->size; + + while (clusterCount::max)(); + int splitIndex = -1; + + for (int i=0; ichilds != NULL) { + + DistanceType variance = meanVariance - clusters[i]->variance*clusters[i]->size; + + for (int j=0; jchilds[j]->variance*clusters[i]->childs[j]->size; + } + if (variance clusters_length) break; + + meanVariance = minVariance; + + // split node + KMeansNodePtr toSplit = clusters[splitIndex]; + clusters[splitIndex] = toSplit->childs[0]; + for (int i=1; ichilds[i]; + } + } + + varianceValue = meanVariance/root->size; + return clusterCount; + } + +private: + /** The branching factor used in the hierarchical k-means clustering */ + int branching_; + + /** Number of kmeans trees (default is one) */ + int trees_; + + /** Maximum number of iterations to use when performing k-means clustering */ + int iterations_; + + /** Algorithm for choosing the cluster centers */ + flann_centers_init_t centers_init_; + + /** + * Cluster border index. This is used in the tree search phase when determining + * the closest cluster to explore next. A zero value takes into account only + * the cluster centres, a value greater then zero also take into account the size + * of the cluster. + */ + float cb_index_; + + /** + * The dataset used by this index + */ + const Matrix dataset_; + + /** Index parameters */ + IndexParams index_params_; + + /** + * Number of features in the dataset. + */ + size_t size_; + + /** + * Length of each feature. + */ + size_t veclen_; + + /** + * The root node in the tree. + */ + KMeansNodePtr* root_; + + /** + * Array of indices to vectors in the dataset. + */ + int** indices_; + + /** + * The distance + */ + Distance distance_; + + /** + * Pooled memory allocator. + */ + PooledAllocator pool_; + + /** + * Memory occupied by the index. + */ + int memoryCounter_; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_KMEANS_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h index 6dc91caa1a..6428c0d7ef 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/linear_index.h @@ -1,135 +1,135 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_LINEAR_INDEX_H_ -#define OPENCV_FLANN_LINEAR_INDEX_H_ - -//! @cond IGNORED - -#include "nn_index.h" - -namespace cvflann -{ - -struct LinearIndexParams : public IndexParams -{ - LinearIndexParams() - { - (* this)["algorithm"] = FLANN_INDEX_LINEAR; - } -}; - -template -class LinearIndex : public NNIndex -{ -public: - - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - - LinearIndex(const Matrix& inputData, const IndexParams& params = LinearIndexParams(), - Distance d = Distance()) : - dataset_(inputData), index_params_(params), distance_(d) - { - } - - LinearIndex(const LinearIndex&); - LinearIndex& operator=(const LinearIndex&); - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_LINEAR; - } - - - size_t size() const CV_OVERRIDE - { - return dataset_.rows; - } - - size_t veclen() const CV_OVERRIDE - { - return dataset_.cols; - } - - - int usedMemory() const CV_OVERRIDE - { - return 0; - } - - void buildIndex() CV_OVERRIDE - { - /* nothing to do here for linear search */ - } - - void saveIndex(FILE*) CV_OVERRIDE - { - /* nothing to do here for linear search */ - } - - - void loadIndex(FILE*) CV_OVERRIDE - { - /* nothing to do here for linear search */ - - index_params_["algorithm"] = getType(); - } - - void findNeighbors(ResultSet& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE - { - ElementType* data = dataset_.data; - for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) { - DistanceType dist = distance_(data, vec, dataset_.cols); - resultSet.addPoint(dist, (int)i); - } - } - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - -private: - /** The dataset */ - const Matrix dataset_; - /** Index parameters */ - IndexParams index_params_; - /** Index distance */ - Distance distance_; - -}; - -} - -//! @endcond - -#endif // OPENCV_FLANN_LINEAR_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_LINEAR_INDEX_H_ +#define OPENCV_FLANN_LINEAR_INDEX_H_ + +//! @cond IGNORED + +#include "nn_index.h" + +namespace cvflann +{ + +struct LinearIndexParams : public IndexParams +{ + LinearIndexParams() + { + (* this)["algorithm"] = FLANN_INDEX_LINEAR; + } +}; + +template +class LinearIndex : public NNIndex +{ +public: + + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + + LinearIndex(const Matrix& inputData, const IndexParams& params = LinearIndexParams(), + Distance d = Distance()) : + dataset_(inputData), index_params_(params), distance_(d) + { + } + + LinearIndex(const LinearIndex&); + LinearIndex& operator=(const LinearIndex&); + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_LINEAR; + } + + + size_t size() const CV_OVERRIDE + { + return dataset_.rows; + } + + size_t veclen() const CV_OVERRIDE + { + return dataset_.cols; + } + + + int usedMemory() const CV_OVERRIDE + { + return 0; + } + + void buildIndex() CV_OVERRIDE + { + /* nothing to do here for linear search */ + } + + void saveIndex(FILE*) CV_OVERRIDE + { + /* nothing to do here for linear search */ + } + + + void loadIndex(FILE*) CV_OVERRIDE + { + /* nothing to do here for linear search */ + + index_params_["algorithm"] = getType(); + } + + void findNeighbors(ResultSet& resultSet, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE + { + ElementType* data = dataset_.data; + for (size_t i = 0; i < dataset_.rows; ++i, data += dataset_.cols) { + DistanceType dist = distance_(data, vec, dataset_.cols); + resultSet.addPoint(dist, (int)i); + } + } + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + +private: + /** The dataset */ + const Matrix dataset_; + /** Index parameters */ + IndexParams index_params_; + /** Index distance */ + Distance distance_; + +}; + +} + +//! @endcond + +#endif // OPENCV_FLANN_LINEAR_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/logger.h b/3rdParty/opencv-4.11.0/opencv2/flann/logger.h index 7708dfa2b8..31f9bbd77f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/logger.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/logger.h @@ -1,138 +1,138 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_LOGGER_H -#define OPENCV_FLANN_LOGGER_H - -//! @cond IGNORED - -#include -#include - -#include "defines.h" - - -namespace cvflann -{ - -class Logger -{ - Logger() : stream(stdout), logLevel(FLANN_LOG_WARN) {} - - ~Logger() - { - if ((stream!=NULL)&&(stream!=stdout)) { - fclose(stream); - } - } - - static Logger& instance() - { - static Logger logger; - return logger; - } - - void _setDestination(const char* name) - { - if (name==NULL) { - stream = stdout; - } - else { -#ifdef _MSC_VER - if (fopen_s(&stream, name, "w") != 0) - stream = NULL; -#else - stream = fopen(name,"w"); -#endif - if (stream == NULL) { - stream = stdout; - } - } - } - - int _log(int level, const char* fmt, va_list arglist) - { - if (level > logLevel ) return -1; - int ret = vfprintf(stream, fmt, arglist); - return ret; - } - -public: - /** - * Sets the logging level. All messages with lower priority will be ignored. - * @param level Logging level - */ - static void setLevel(int level) { instance().logLevel = level; } - - /** - * Sets the logging destination - * @param name Filename or NULL for console - */ - static void setDestination(const char* name) { instance()._setDestination(name); } - - /** - * Print log message - * @param level Log level - * @param fmt Message format - */ - static int log(int level, const char* fmt, ...) - { - va_list arglist; - va_start(arglist, fmt); - int ret = instance()._log(level,fmt,arglist); - va_end(arglist); - return ret; - } - -#define LOG_METHOD(NAME,LEVEL) \ - static int NAME(const char* fmt, ...) \ - { \ - va_list ap; \ - va_start(ap, fmt); \ - int ret = instance()._log(LEVEL, fmt, ap); \ - va_end(ap); \ - return ret; \ - } - - LOG_METHOD(fatal, FLANN_LOG_FATAL) - LOG_METHOD(error, FLANN_LOG_ERROR) - LOG_METHOD(warn, FLANN_LOG_WARN) - LOG_METHOD(info, FLANN_LOG_INFO) - -private: - FILE* stream; - int logLevel; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_LOGGER_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_LOGGER_H +#define OPENCV_FLANN_LOGGER_H + +//! @cond IGNORED + +#include +#include + +#include "defines.h" + + +namespace cvflann +{ + +class Logger +{ + Logger() : stream(stdout), logLevel(FLANN_LOG_WARN) {} + + ~Logger() + { + if ((stream!=NULL)&&(stream!=stdout)) { + fclose(stream); + } + } + + static Logger& instance() + { + static Logger logger; + return logger; + } + + void _setDestination(const char* name) + { + if (name==NULL) { + stream = stdout; + } + else { +#ifdef _MSC_VER + if (fopen_s(&stream, name, "w") != 0) + stream = NULL; +#else + stream = fopen(name,"w"); +#endif + if (stream == NULL) { + stream = stdout; + } + } + } + + int _log(int level, const char* fmt, va_list arglist) + { + if (level > logLevel ) return -1; + int ret = vfprintf(stream, fmt, arglist); + return ret; + } + +public: + /** + * Sets the logging level. All messages with lower priority will be ignored. + * @param level Logging level + */ + static void setLevel(int level) { instance().logLevel = level; } + + /** + * Sets the logging destination + * @param name Filename or NULL for console + */ + static void setDestination(const char* name) { instance()._setDestination(name); } + + /** + * Print log message + * @param level Log level + * @param fmt Message format + */ + static int log(int level, const char* fmt, ...) + { + va_list arglist; + va_start(arglist, fmt); + int ret = instance()._log(level,fmt,arglist); + va_end(arglist); + return ret; + } + +#define LOG_METHOD(NAME,LEVEL) \ + static int NAME(const char* fmt, ...) \ + { \ + va_list ap; \ + va_start(ap, fmt); \ + int ret = instance()._log(LEVEL, fmt, ap); \ + va_end(ap); \ + return ret; \ + } + + LOG_METHOD(fatal, FLANN_LOG_FATAL) + LOG_METHOD(error, FLANN_LOG_ERROR) + LOG_METHOD(warn, FLANN_LOG_WARN) + LOG_METHOD(info, FLANN_LOG_INFO) + +private: + FILE* stream; + int logLevel; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_LOGGER_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h index 955549174d..b5e87f6041 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_index.h @@ -1,403 +1,403 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -/*********************************************************************** - * Author: Vincent Rabaud - *************************************************************************/ - -#ifndef OPENCV_FLANN_LSH_INDEX_H_ -#define OPENCV_FLANN_LSH_INDEX_H_ - -//! @cond IGNORED - -#include -#include -#include -#include - -#include "nn_index.h" -#include "matrix.h" -#include "result_set.h" -#include "heap.h" -#include "lsh_table.h" -#include "allocator.h" -#include "random.h" -#include "saving.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) //disable unreachable code -#endif - -namespace cvflann -{ - -struct LshIndexParams : public IndexParams -{ - LshIndexParams(int table_number = 12, int key_size = 20, int multi_probe_level = 2) - { - (*this)["algorithm"] = FLANN_INDEX_LSH; - // The number of hash tables to use - (*this)["table_number"] = table_number; - // The length of the key in the hash tables - (*this)["key_size"] = key_size; - // Number of levels to use in multi-probe (0 for standard LSH) - (*this)["multi_probe_level"] = multi_probe_level; - } -}; - -/** - * Locality-sensitive hashing index - * - * Contains the tables and other information for indexing a set of points - * for nearest-neighbor matching. - */ -template -class LshIndex : public NNIndex -{ -public: - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - - /** Constructor - * @param input_data dataset with the input features - * @param params parameters passed to the LSH algorithm - * @param d the distance used - */ - LshIndex(const Matrix& input_data, const IndexParams& params = LshIndexParams(), - Distance d = Distance()) : - dataset_(input_data), index_params_(params), distance_(d) - { - // cv::flann::IndexParams sets integer params as 'int', so it is used with get_param - // in place of 'unsigned int' - table_number_ = get_param(index_params_,"table_number",12); - key_size_ = get_param(index_params_,"key_size",20); - multi_probe_level_ = get_param(index_params_,"multi_probe_level",2); - - feature_size_ = (unsigned)dataset_.cols; - fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); - } - - - LshIndex(const LshIndex&); - LshIndex& operator=(const LshIndex&); - - /** - * Builds the index - */ - void buildIndex() CV_OVERRIDE - { - tables_.resize(table_number_); - for (int i = 0; i < table_number_; ++i) { - lsh::LshTable& table = tables_[i]; - table = lsh::LshTable(feature_size_, key_size_); - - // Add the features to the table - table.add(dataset_); - } - } - - flann_algorithm_t getType() const CV_OVERRIDE - { - return FLANN_INDEX_LSH; - } - - - void saveIndex(FILE* stream) CV_OVERRIDE - { - save_value(stream,table_number_); - save_value(stream,key_size_); - save_value(stream,multi_probe_level_); - save_value(stream, dataset_); - } - - void loadIndex(FILE* stream) CV_OVERRIDE - { - load_value(stream, table_number_); - load_value(stream, key_size_); - load_value(stream, multi_probe_level_); - load_value(stream, dataset_); - // Building the index is so fast we can afford not storing it - buildIndex(); - - index_params_["algorithm"] = getType(); - index_params_["table_number"] = table_number_; - index_params_["key_size"] = key_size_; - index_params_["multi_probe_level"] = multi_probe_level_; - } - - /** - * Returns size of index. - */ - size_t size() const CV_OVERRIDE - { - return dataset_.rows; - } - - /** - * Returns the length of an index feature. - */ - size_t veclen() const CV_OVERRIDE - { - return feature_size_; - } - - /** - * Computes the index memory usage - * Returns: memory used by the index - */ - int usedMemory() const CV_OVERRIDE - { - return (int)(dataset_.rows * sizeof(int)); - } - - - IndexParams getParameters() const CV_OVERRIDE - { - return index_params_; - } - - /** - * \brief Perform k-nearest neighbor search - * \param[in] queries The query points for which to find the nearest neighbors - * \param[out] indices The indices of the nearest neighbors found - * \param[out] dists Distances to the nearest neighbors found - * \param[in] knn Number of nearest neighbors to return - * \param[in] params Search parameters - */ - virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE - { - CV_Assert(queries.cols == veclen()); - CV_Assert(indices.rows >= queries.rows); - CV_Assert(dists.rows >= queries.rows); - CV_Assert(int(indices.cols) >= knn); - CV_Assert(int(dists.cols) >= knn); - - - KNNUniqueResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.clear(); - std::fill_n(indices[i], knn, -1); - std::fill_n(dists[i], knn, std::numeric_limits::max()); - findNeighbors(resultSet, queries[i], params); - if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); - else resultSet.copy(indices[i], dists[i], knn); - } - } - - - /** - * Find set of nearest neighbors to vec. Their indices are stored inside - * the result object. - * - * Params: - * result = the result object in which the indices of the nearest-neighbors are stored - * vec = the vector for which to search the nearest neighbors - * maxCheck = the maximum number of restarts (in a best-bin-first manner) - */ - void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE - { - getNeighbors(vec, result); - } - -private: - /** Defines the comparator on score and index - */ - typedef std::pair ScoreIndexPair; - struct SortScoreIndexPairOnSecond - { - bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const - { - return left.second < right.second; - } - }; - - /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH - * @param key the key we build neighbors from - * @param lowest_index the lowest index of the bit set - * @param level the multi-probe level we are at - * @param xor_masks all the xor mask - */ - void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, - std::vector& xor_masks) - { - xor_masks.push_back(key); - if (level == 0) return; - for (int index = lowest_index - 1; index >= 0; --index) { - // Create a new key - lsh::BucketKey new_key = key | (1 << index); - fill_xor_mask(new_key, index, level - 1, xor_masks); - } - } - - /** Performs the approximate nearest-neighbor search. - * @param vec the feature to analyze - * @param do_radius flag indicating if we check the radius too - * @param radius the radius if it is a radius search - * @param do_k flag indicating if we limit the number of nn - * @param k_nn the number of nearest neighbors - * @param checked_average used for debugging - */ - void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn, - float& /*checked_average*/) - { - static std::vector score_index_heap; - - if (do_k) { - unsigned int worst_score = std::numeric_limits::max(); - typename std::vector >::const_iterator table = tables_.begin(); - typename std::vector >::const_iterator table_end = tables_.end(); - for (; table != table_end; ++table) { - size_t key = table->getKey(vec); - std::vector::const_iterator xor_mask = xor_masks_.begin(); - std::vector::const_iterator xor_mask_end = xor_masks_.end(); - for (; xor_mask != xor_mask_end; ++xor_mask) { - size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); - if (bucket == 0) continue; - - // Go over each descriptor index - std::vector::const_iterator training_index = bucket->begin(); - std::vector::const_iterator last_training_index = bucket->end(); - DistanceType hamming_distance; - - // Process the rest of the candidates - for (; training_index < last_training_index; ++training_index) { - hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); - - if (hamming_distance < worst_score) { - // Insert the new element - score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); - std::push_heap(score_index_heap.begin(), score_index_heap.end()); - - if (score_index_heap.size() > (unsigned int)k_nn) { - // Remove the highest distance value as we have too many elements - std::pop_heap(score_index_heap.begin(), score_index_heap.end()); - score_index_heap.pop_back(); - // Keep track of the worst score - worst_score = score_index_heap.front().first; - } - } - } - } - } - } - else { - typename std::vector >::const_iterator table = tables_.begin(); - typename std::vector >::const_iterator table_end = tables_.end(); - for (; table != table_end; ++table) { - size_t key = table->getKey(vec); - std::vector::const_iterator xor_mask = xor_masks_.begin(); - std::vector::const_iterator xor_mask_end = xor_masks_.end(); - for (; xor_mask != xor_mask_end; ++xor_mask) { - size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); - if (bucket == 0) continue; - - // Go over each descriptor index - std::vector::const_iterator training_index = bucket->begin(); - std::vector::const_iterator last_training_index = bucket->end(); - DistanceType hamming_distance; - - // Process the rest of the candidates - for (; training_index < last_training_index; ++training_index) { - // Compute the Hamming distance - hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); - if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); - } - } - } - } - } - - /** Performs the approximate nearest-neighbor search. - * This is a slower version than the above as it uses the ResultSet - * @param vec the feature to analyze - */ - void getNeighbors(const ElementType* vec, ResultSet& result) - { - typename std::vector >::const_iterator table = tables_.begin(); - typename std::vector >::const_iterator table_end = tables_.end(); - for (; table != table_end; ++table) { - size_t key = table->getKey(vec); - std::vector::const_iterator xor_mask = xor_masks_.begin(); - std::vector::const_iterator xor_mask_end = xor_masks_.end(); - for (; xor_mask != xor_mask_end; ++xor_mask) { - size_t sub_key = key ^ (*xor_mask); - const lsh::Bucket* bucket = table->getBucketFromKey((lsh::BucketKey)sub_key); - if (bucket == 0) continue; - - // Go over each descriptor index - std::vector::const_iterator training_index = bucket->begin(); - std::vector::const_iterator last_training_index = bucket->end(); - DistanceType hamming_distance; - - // Process the rest of the candidates - for (; training_index < last_training_index; ++training_index) { - // Compute the Hamming distance - hamming_distance = distance_(vec, dataset_[*training_index], (int)dataset_.cols); - result.addPoint(hamming_distance, *training_index); - } - } - } - } - - /** The different hash tables */ - std::vector > tables_; - - /** The data the LSH tables where built from */ - Matrix dataset_; - - /** The size of the features (as ElementType[]) */ - unsigned int feature_size_; - - IndexParams index_params_; - - /** table number */ - int table_number_; - /** key size */ - int key_size_; - /** How far should we look for neighbors in multi-probe LSH */ - int multi_probe_level_; - - /** The XOR masks to apply to a key to get the neighboring buckets */ - std::vector xor_masks_; - - Distance distance_; -}; -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -//! @endcond - -#endif //OPENCV_FLANN_LSH_INDEX_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +/*********************************************************************** + * Author: Vincent Rabaud + *************************************************************************/ + +#ifndef OPENCV_FLANN_LSH_INDEX_H_ +#define OPENCV_FLANN_LSH_INDEX_H_ + +//! @cond IGNORED + +#include +#include +#include +#include + +#include "nn_index.h" +#include "matrix.h" +#include "result_set.h" +#include "heap.h" +#include "lsh_table.h" +#include "allocator.h" +#include "random.h" +#include "saving.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) //disable unreachable code +#endif + +namespace cvflann +{ + +struct LshIndexParams : public IndexParams +{ + LshIndexParams(int table_number = 12, int key_size = 20, int multi_probe_level = 2) + { + (*this)["algorithm"] = FLANN_INDEX_LSH; + // The number of hash tables to use + (*this)["table_number"] = table_number; + // The length of the key in the hash tables + (*this)["key_size"] = key_size; + // Number of levels to use in multi-probe (0 for standard LSH) + (*this)["multi_probe_level"] = multi_probe_level; + } +}; + +/** + * Locality-sensitive hashing index + * + * Contains the tables and other information for indexing a set of points + * for nearest-neighbor matching. + */ +template +class LshIndex : public NNIndex +{ +public: + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + + /** Constructor + * @param input_data dataset with the input features + * @param params parameters passed to the LSH algorithm + * @param d the distance used + */ + LshIndex(const Matrix& input_data, const IndexParams& params = LshIndexParams(), + Distance d = Distance()) : + dataset_(input_data), index_params_(params), distance_(d) + { + // cv::flann::IndexParams sets integer params as 'int', so it is used with get_param + // in place of 'unsigned int' + table_number_ = get_param(index_params_,"table_number",12); + key_size_ = get_param(index_params_,"key_size",20); + multi_probe_level_ = get_param(index_params_,"multi_probe_level",2); + + feature_size_ = (unsigned)dataset_.cols; + fill_xor_mask(0, key_size_, multi_probe_level_, xor_masks_); + } + + + LshIndex(const LshIndex&); + LshIndex& operator=(const LshIndex&); + + /** + * Builds the index + */ + void buildIndex() CV_OVERRIDE + { + tables_.resize(table_number_); + for (int i = 0; i < table_number_; ++i) { + lsh::LshTable& table = tables_[i]; + table = lsh::LshTable(feature_size_, key_size_); + + // Add the features to the table + table.add(dataset_); + } + } + + flann_algorithm_t getType() const CV_OVERRIDE + { + return FLANN_INDEX_LSH; + } + + + void saveIndex(FILE* stream) CV_OVERRIDE + { + save_value(stream,table_number_); + save_value(stream,key_size_); + save_value(stream,multi_probe_level_); + save_value(stream, dataset_); + } + + void loadIndex(FILE* stream) CV_OVERRIDE + { + load_value(stream, table_number_); + load_value(stream, key_size_); + load_value(stream, multi_probe_level_); + load_value(stream, dataset_); + // Building the index is so fast we can afford not storing it + buildIndex(); + + index_params_["algorithm"] = getType(); + index_params_["table_number"] = table_number_; + index_params_["key_size"] = key_size_; + index_params_["multi_probe_level"] = multi_probe_level_; + } + + /** + * Returns size of index. + */ + size_t size() const CV_OVERRIDE + { + return dataset_.rows; + } + + /** + * Returns the length of an index feature. + */ + size_t veclen() const CV_OVERRIDE + { + return feature_size_; + } + + /** + * Computes the index memory usage + * Returns: memory used by the index + */ + int usedMemory() const CV_OVERRIDE + { + return (int)(dataset_.rows * sizeof(int)); + } + + + IndexParams getParameters() const CV_OVERRIDE + { + return index_params_; + } + + /** + * \brief Perform k-nearest neighbor search + * \param[in] queries The query points for which to find the nearest neighbors + * \param[out] indices The indices of the nearest neighbors found + * \param[out] dists Distances to the nearest neighbors found + * \param[in] knn Number of nearest neighbors to return + * \param[in] params Search parameters + */ + virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) CV_OVERRIDE + { + CV_Assert(queries.cols == veclen()); + CV_Assert(indices.rows >= queries.rows); + CV_Assert(dists.rows >= queries.rows); + CV_Assert(int(indices.cols) >= knn); + CV_Assert(int(dists.cols) >= knn); + + + KNNUniqueResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.clear(); + std::fill_n(indices[i], knn, -1); + std::fill_n(dists[i], knn, std::numeric_limits::max()); + findNeighbors(resultSet, queries[i], params); + if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); + else resultSet.copy(indices[i], dists[i], knn); + } + } + + + /** + * Find set of nearest neighbors to vec. Their indices are stored inside + * the result object. + * + * Params: + * result = the result object in which the indices of the nearest-neighbors are stored + * vec = the vector for which to search the nearest neighbors + * maxCheck = the maximum number of restarts (in a best-bin-first manner) + */ + void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& /*searchParams*/) CV_OVERRIDE + { + getNeighbors(vec, result); + } + +private: + /** Defines the comparator on score and index + */ + typedef std::pair ScoreIndexPair; + struct SortScoreIndexPairOnSecond + { + bool operator()(const ScoreIndexPair& left, const ScoreIndexPair& right) const + { + return left.second < right.second; + } + }; + + /** Fills the different xor masks to use when getting the neighbors in multi-probe LSH + * @param key the key we build neighbors from + * @param lowest_index the lowest index of the bit set + * @param level the multi-probe level we are at + * @param xor_masks all the xor mask + */ + void fill_xor_mask(lsh::BucketKey key, int lowest_index, unsigned int level, + std::vector& xor_masks) + { + xor_masks.push_back(key); + if (level == 0) return; + for (int index = lowest_index - 1; index >= 0; --index) { + // Create a new key + lsh::BucketKey new_key = key | (1 << index); + fill_xor_mask(new_key, index, level - 1, xor_masks); + } + } + + /** Performs the approximate nearest-neighbor search. + * @param vec the feature to analyze + * @param do_radius flag indicating if we check the radius too + * @param radius the radius if it is a radius search + * @param do_k flag indicating if we limit the number of nn + * @param k_nn the number of nearest neighbors + * @param checked_average used for debugging + */ + void getNeighbors(const ElementType* vec, bool /*do_radius*/, float radius, bool do_k, unsigned int k_nn, + float& /*checked_average*/) + { + static std::vector score_index_heap; + + if (do_k) { + unsigned int worst_score = std::numeric_limits::max(); + typename std::vector >::const_iterator table = tables_.begin(); + typename std::vector >::const_iterator table_end = tables_.end(); + for (; table != table_end; ++table) { + size_t key = table->getKey(vec); + std::vector::const_iterator xor_mask = xor_masks_.begin(); + std::vector::const_iterator xor_mask_end = xor_masks_.end(); + for (; xor_mask != xor_mask_end; ++xor_mask) { + size_t sub_key = key ^ (*xor_mask); + const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); + if (bucket == 0) continue; + + // Go over each descriptor index + std::vector::const_iterator training_index = bucket->begin(); + std::vector::const_iterator last_training_index = bucket->end(); + DistanceType hamming_distance; + + // Process the rest of the candidates + for (; training_index < last_training_index; ++training_index) { + hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); + + if (hamming_distance < worst_score) { + // Insert the new element + score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); + std::push_heap(score_index_heap.begin(), score_index_heap.end()); + + if (score_index_heap.size() > (unsigned int)k_nn) { + // Remove the highest distance value as we have too many elements + std::pop_heap(score_index_heap.begin(), score_index_heap.end()); + score_index_heap.pop_back(); + // Keep track of the worst score + worst_score = score_index_heap.front().first; + } + } + } + } + } + } + else { + typename std::vector >::const_iterator table = tables_.begin(); + typename std::vector >::const_iterator table_end = tables_.end(); + for (; table != table_end; ++table) { + size_t key = table->getKey(vec); + std::vector::const_iterator xor_mask = xor_masks_.begin(); + std::vector::const_iterator xor_mask_end = xor_masks_.end(); + for (; xor_mask != xor_mask_end; ++xor_mask) { + size_t sub_key = key ^ (*xor_mask); + const lsh::Bucket* bucket = table->getBucketFromKey(sub_key); + if (bucket == 0) continue; + + // Go over each descriptor index + std::vector::const_iterator training_index = bucket->begin(); + std::vector::const_iterator last_training_index = bucket->end(); + DistanceType hamming_distance; + + // Process the rest of the candidates + for (; training_index < last_training_index; ++training_index) { + // Compute the Hamming distance + hamming_distance = distance_(vec, dataset_[*training_index], dataset_.cols); + if (hamming_distance < radius) score_index_heap.push_back(ScoreIndexPair(hamming_distance, training_index)); + } + } + } + } + } + + /** Performs the approximate nearest-neighbor search. + * This is a slower version than the above as it uses the ResultSet + * @param vec the feature to analyze + */ + void getNeighbors(const ElementType* vec, ResultSet& result) + { + typename std::vector >::const_iterator table = tables_.begin(); + typename std::vector >::const_iterator table_end = tables_.end(); + for (; table != table_end; ++table) { + size_t key = table->getKey(vec); + std::vector::const_iterator xor_mask = xor_masks_.begin(); + std::vector::const_iterator xor_mask_end = xor_masks_.end(); + for (; xor_mask != xor_mask_end; ++xor_mask) { + size_t sub_key = key ^ (*xor_mask); + const lsh::Bucket* bucket = table->getBucketFromKey((lsh::BucketKey)sub_key); + if (bucket == 0) continue; + + // Go over each descriptor index + std::vector::const_iterator training_index = bucket->begin(); + std::vector::const_iterator last_training_index = bucket->end(); + DistanceType hamming_distance; + + // Process the rest of the candidates + for (; training_index < last_training_index; ++training_index) { + // Compute the Hamming distance + hamming_distance = distance_(vec, dataset_[*training_index], (int)dataset_.cols); + result.addPoint(hamming_distance, *training_index); + } + } + } + } + + /** The different hash tables */ + std::vector > tables_; + + /** The data the LSH tables where built from */ + Matrix dataset_; + + /** The size of the features (as ElementType[]) */ + unsigned int feature_size_; + + IndexParams index_params_; + + /** table number */ + int table_number_; + /** key size */ + int key_size_; + /** How far should we look for neighbors in multi-probe LSH */ + int multi_probe_level_; + + /** The XOR masks to apply to a key to get the neighboring buckets */ + std::vector xor_masks_; + + Distance distance_; +}; +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +//! @endcond + +#endif //OPENCV_FLANN_LSH_INDEX_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h index 9c72d11d52..3f51457cbb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/lsh_table.h @@ -1,522 +1,522 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -/*********************************************************************** - * Author: Vincent Rabaud - *************************************************************************/ - -#ifndef OPENCV_FLANN_LSH_TABLE_H_ -#define OPENCV_FLANN_LSH_TABLE_H_ - -//! @cond IGNORED - -#include -#include -#include -#include -// TODO as soon as we use C++0x, use the code in USE_UNORDERED_MAP -#ifdef __GXX_EXPERIMENTAL_CXX0X__ -# define USE_UNORDERED_MAP 1 -#else -# define USE_UNORDERED_MAP 0 -#endif -#if USE_UNORDERED_MAP -#include -#else -#include -#endif -#include -#include - -#include "dynamic_bitset.h" -#include "matrix.h" - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) //disable unreachable code -#endif - - -namespace cvflann -{ - -namespace lsh -{ - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** What is stored in an LSH bucket - */ -typedef uint32_t FeatureIndex; -/** The id from which we can get a bucket back in an LSH table - */ -typedef unsigned int BucketKey; - -/** A bucket in an LSH table - */ -typedef std::vector Bucket; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** POD for stats about an LSH table - */ -struct LshStats -{ - std::vector bucket_sizes_; - size_t n_buckets_; - size_t bucket_size_mean_; - size_t bucket_size_median_; - size_t bucket_size_min_; - size_t bucket_size_max_; - size_t bucket_size_std_dev; - /** Each contained vector contains three value: beginning/end for interval, number of elements in the bin - */ - std::vector > size_histogram_; -}; - -/** Overload the << operator for LshStats - * @param out the streams - * @param stats the stats to display - * @return the streams - */ -inline std::ostream& operator <<(std::ostream& out, const LshStats& stats) -{ - int w = 20; - out << "Lsh Table Stats:\n" << std::setw(w) << std::setiosflags(std::ios::right) << "N buckets : " - << stats.n_buckets_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "mean size : " - << std::setiosflags(std::ios::left) << stats.bucket_size_mean_ << "\n" << std::setw(w) - << std::setiosflags(std::ios::right) << "median size : " << stats.bucket_size_median_ << "\n" << std::setw(w) - << std::setiosflags(std::ios::right) << "min size : " << std::setiosflags(std::ios::left) - << stats.bucket_size_min_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "max size : " - << std::setiosflags(std::ios::left) << stats.bucket_size_max_; - - // Display the histogram - out << std::endl << std::setw(w) << std::setiosflags(std::ios::right) << "histogram : " - << std::setiosflags(std::ios::left); - for (std::vector >::const_iterator iterator = stats.size_histogram_.begin(), end = - stats.size_histogram_.end(); iterator != end; ++iterator) out << (*iterator)[0] << "-" << (*iterator)[1] << ": " << (*iterator)[2] << ", "; - - return out; -} - - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Lsh hash table. As its key is a sub-feature, and as usually - * the size of it is pretty small, we keep it as a continuous memory array. - * The value is an index in the corpus of features (we keep it as an unsigned - * int for pure memory reasons, it could be a size_t) - */ -template -class LshTable -{ -public: - /** A container of all the feature indices. Optimized for space - */ -#if USE_UNORDERED_MAP - typedef std::unordered_map BucketsSpace; -#else - typedef std::map BucketsSpace; -#endif - - /** A container of all the feature indices. Optimized for speed - */ - typedef std::vector BucketsSpeed; - - /** Default constructor - */ - LshTable() - { - key_size_ = 0; - feature_size_ = 0; - speed_level_ = kArray; - } - - /** Default constructor - * Create the mask and allocate the memory - * @param feature_size is the size of the feature (considered as a ElementType[]) - * @param key_size is the number of bits that are turned on in the feature - */ - LshTable(unsigned int feature_size, unsigned int key_size) - { - feature_size_ = feature_size; - CV_UNUSED(key_size); - CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); - } - - /** Add a feature to the table - * @param value the value to store for that feature - * @param feature the feature itself - */ - void add(unsigned int value, const ElementType* feature) - { - // Add the value to the corresponding bucket - BucketKey key = (lsh::BucketKey)getKey(feature); - - switch (speed_level_) { - case kArray: - // That means we get the buckets from an array - buckets_speed_[key].push_back(value); - break; - case kBitsetHash: - // That means we can check the bitset for the presence of a key - key_bitset_.set(key); - buckets_space_[key].push_back(value); - break; - case kHash: - { - // That means we have to check for the hash table for the presence of a key - buckets_space_[key].push_back(value); - break; - } - } - } - - /** Add a set of features to the table - * @param dataset the values to store - */ - void add(Matrix dataset) - { -#if USE_UNORDERED_MAP - buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); -#endif - // Add the features to the table - for (unsigned int i = 0; i < dataset.rows; ++i) add(i, dataset[i]); - // Now that the table is full, optimize it for speed/space - optimize(); - } - - /** Get a bucket given the key - */ - inline const Bucket* getBucketFromKey(BucketKey key) const - { - // Generate other buckets - switch (speed_level_) { - case kArray: - // That means we get the buckets from an array - return &buckets_speed_[key]; - break; - case kBitsetHash: - // That means we can check the bitset for the presence of a key - if (key_bitset_.test(key)) return &buckets_space_.find(key)->second; - else return 0; - break; - case kHash: - { - // That means we have to check for the hash table for the presence of a key - BucketsSpace::const_iterator bucket_it, bucket_end = buckets_space_.end(); - bucket_it = buckets_space_.find(key); - // Stop here if that bucket does not exist - if (bucket_it == bucket_end) return 0; - else return &bucket_it->second; - break; - } - } - return 0; - } - - /** Compute the sub-signature of a feature - */ - size_t getKey(const ElementType* /*feature*/) const - { - CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); - return 0; - } - - /** Get statistics about the table - */ - LshStats getStats() const; - -private: - /** defines the speed fo the implementation - * kArray uses a vector for storing data - * kBitsetHash uses a hash map but checks for the validity of a key with a bitset - * kHash uses a hash map only - */ - enum SpeedLevel - { - kArray, kBitsetHash, kHash - }; - - /** Initialize some variables - */ - void initialize(size_t key_size) - { - const size_t key_size_lower_bound = 1; - //a value (size_t(1) << key_size) must fit the size_t type so key_size has to be strictly less than size of size_t - const size_t key_size_upper_bound = (std::min)(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT); - if (key_size < key_size_lower_bound || key_size >= key_size_upper_bound) - { - CV_Error(cv::Error::StsBadArg, cv::format("Invalid key_size (=%d). Valid values for your system are %d <= key_size < %d.", (int)key_size, (int)key_size_lower_bound, (int)key_size_upper_bound)); - } - - speed_level_ = kHash; - key_size_ = (unsigned)key_size; - } - - /** Optimize the table for speed/space - */ - void optimize() - { - // If we are already using the fast storage, no need to do anything - if (speed_level_ == kArray) return; - - // Use an array if it will be more than half full - if (buckets_space_.size() > ((size_t(1) << key_size_) / 2)) { - speed_level_ = kArray; - // Fill the array version of it - buckets_speed_.resize(size_t(1) << key_size_); - for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) buckets_speed_[key_bucket->first] = key_bucket->second; - - // Empty the hash table - buckets_space_.clear(); - return; - } - - // If the bitset is going to use less than 10% of the RAM of the hash map (at least 1 size_t for the key and two - // for the vector) or less than 512MB (key_size_ <= 30) - if (((std::max(buckets_space_.size(), buckets_speed_.size()) * CHAR_BIT * 3 * sizeof(BucketKey)) / 10 - >= (size_t(1) << key_size_)) || (key_size_ <= 32)) { - speed_level_ = kBitsetHash; - key_bitset_.resize(size_t(1) << key_size_); - key_bitset_.reset(); - // Try with the BucketsSpace - for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) key_bitset_.set(key_bucket->first); - } - else { - speed_level_ = kHash; - key_bitset_.clear(); - } - } - - /** The vector of all the buckets if they are held for speed - */ - BucketsSpeed buckets_speed_; - - /** The hash table of all the buckets in case we cannot use the speed version - */ - BucketsSpace buckets_space_; - - /** What is used to store the data */ - SpeedLevel speed_level_; - - /** If the subkey is small enough, it will keep track of which subkeys are set through that bitset - * That is just a speedup so that we don't look in the hash table (which can be mush slower that checking a bitset) - */ - DynamicBitset key_bitset_; - - /** The size of the sub-signature in bits - */ - unsigned int key_size_; - - unsigned int feature_size_; - - // Members only used for the unsigned char specialization - /** The mask to apply to a feature to get the hash key - * Only used in the unsigned char case - */ - std::vector mask_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// -// Specialization for unsigned char - -template<> -inline LshTable::LshTable(unsigned int feature_size, unsigned int subsignature_size) -{ - feature_size_ = feature_size; - initialize(subsignature_size); - // Allocate the mask - mask_ = std::vector((feature_size * sizeof(char) + sizeof(size_t) - 1) / sizeof(size_t), 0); - - // A bit brutal but fast to code - std::vector indices(feature_size * CHAR_BIT); - for (size_t i = 0; i < feature_size * CHAR_BIT; ++i) indices[i] = (int)i; -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::randShuffle(indices); -#else - std::random_shuffle(indices.begin(), indices.end()); -#endif - - // Generate a random set of order of subsignature_size_ bits - for (unsigned int i = 0; i < key_size_; ++i) { - size_t index = indices[i]; - - // Set that bit in the mask - size_t divisor = CHAR_BIT * sizeof(size_t); - size_t idx = index / divisor; //pick the right size_t index - mask_[idx] |= size_t(1) << (index % divisor); //use modulo to find the bit offset - } - - // Set to 1 if you want to display the mask for debug -#if 0 - { - size_t bcount = 0; - BOOST_FOREACH(size_t mask_block, mask_){ - out << std::setw(sizeof(size_t) * CHAR_BIT / 4) << std::setfill('0') << std::hex << mask_block - << std::endl; - bcount += __builtin_popcountll(mask_block); - } - out << "bit count : " << std::dec << bcount << std::endl; - out << "mask size : " << mask_.size() << std::endl; - return out; - } -#endif -} - -/** Return the Subsignature of a feature - * @param feature the feature to analyze - */ -template<> -inline size_t LshTable::getKey(const unsigned char* feature) const -{ - // no need to check if T is dividable by sizeof(size_t) like in the Hamming - // distance computation as we have a mask - // FIXIT: This is bad assumption, because we reading tail bytes after of the allocated features buffer - const size_t* feature_block_ptr = reinterpret_cast ((const void*)feature); - - // Figure out the subsignature of the feature - // Given the feature ABCDEF, and the mask 001011, the output will be - // 000CEF - size_t subsignature = 0; - size_t bit_index = 1; - - for (unsigned i = 0; i < feature_size_; i += sizeof(size_t)) { - // get the mask and signature blocks - size_t feature_block; - if (i <= feature_size_ - sizeof(size_t)) - { - feature_block = *feature_block_ptr; - } - else - { - size_t tmp = 0; - memcpy(&tmp, feature_block_ptr, feature_size_ - i); // preserve bytes order - feature_block = tmp; - } - size_t mask_block = mask_[i / sizeof(size_t)]; - while (mask_block) { - // Get the lowest set bit in the mask block - size_t lowest_bit = mask_block & ~(mask_block - 1); - // Add it to the current subsignature if necessary - subsignature += (feature_block & lowest_bit) ? bit_index : 0; - // Reset the bit in the mask block - mask_block ^= lowest_bit; - // increment the bit index for the subsignature - bit_index <<= 1; - } - // Check the next feature block - ++feature_block_ptr; - } - return subsignature; -} - -template<> -inline LshStats LshTable::getStats() const -{ - LshStats stats; - stats.bucket_size_mean_ = 0; - if ((buckets_speed_.empty()) && (buckets_space_.empty())) { - stats.n_buckets_ = 0; - stats.bucket_size_median_ = 0; - stats.bucket_size_min_ = 0; - stats.bucket_size_max_ = 0; - return stats; - } - - if (!buckets_speed_.empty()) { - for (BucketsSpeed::const_iterator pbucket = buckets_speed_.begin(); pbucket != buckets_speed_.end(); ++pbucket) { - stats.bucket_sizes_.push_back((lsh::FeatureIndex)pbucket->size()); - stats.bucket_size_mean_ += pbucket->size(); - } - stats.bucket_size_mean_ /= buckets_speed_.size(); - stats.n_buckets_ = buckets_speed_.size(); - } - else { - for (BucketsSpace::const_iterator x = buckets_space_.begin(); x != buckets_space_.end(); ++x) { - stats.bucket_sizes_.push_back((lsh::FeatureIndex)x->second.size()); - stats.bucket_size_mean_ += x->second.size(); - } - stats.bucket_size_mean_ /= buckets_space_.size(); - stats.n_buckets_ = buckets_space_.size(); - } - - std::sort(stats.bucket_sizes_.begin(), stats.bucket_sizes_.end()); - - // BOOST_FOREACH(int size, stats.bucket_sizes_) - // std::cout << size << " "; - // std::cout << std::endl; - stats.bucket_size_median_ = stats.bucket_sizes_[stats.bucket_sizes_.size() / 2]; - stats.bucket_size_min_ = stats.bucket_sizes_.front(); - stats.bucket_size_max_ = stats.bucket_sizes_.back(); - - // TODO compute mean and std - /*float mean, stddev; - stats.bucket_size_mean_ = mean; - stats.bucket_size_std_dev = stddev;*/ - - // Include a histogram of the buckets - unsigned int bin_start = 0; - unsigned int bin_end = 20; - bool is_new_bin = true; - for (std::vector::iterator iterator = stats.bucket_sizes_.begin(), end = stats.bucket_sizes_.end(); iterator - != end; ) - if (*iterator < bin_end) { - if (is_new_bin) { - stats.size_histogram_.push_back(std::vector(3, 0)); - stats.size_histogram_.back()[0] = bin_start; - stats.size_histogram_.back()[1] = bin_end - 1; - is_new_bin = false; - } - ++stats.size_histogram_.back()[2]; - ++iterator; - } - else { - bin_start += 20; - bin_end += 20; - is_new_bin = true; - } - - return stats; -} - -// End the two namespaces -} -} - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -//! @endcond - -#endif /* OPENCV_FLANN_LSH_TABLE_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +/*********************************************************************** + * Author: Vincent Rabaud + *************************************************************************/ + +#ifndef OPENCV_FLANN_LSH_TABLE_H_ +#define OPENCV_FLANN_LSH_TABLE_H_ + +//! @cond IGNORED + +#include +#include +#include +#include +// TODO as soon as we use C++0x, use the code in USE_UNORDERED_MAP +#ifdef __GXX_EXPERIMENTAL_CXX0X__ +# define USE_UNORDERED_MAP 1 +#else +# define USE_UNORDERED_MAP 0 +#endif +#if USE_UNORDERED_MAP +#include +#else +#include +#endif +#include +#include + +#include "dynamic_bitset.h" +#include "matrix.h" + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) //disable unreachable code +#endif + + +namespace cvflann +{ + +namespace lsh +{ + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** What is stored in an LSH bucket + */ +typedef uint32_t FeatureIndex; +/** The id from which we can get a bucket back in an LSH table + */ +typedef unsigned int BucketKey; + +/** A bucket in an LSH table + */ +typedef std::vector Bucket; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** POD for stats about an LSH table + */ +struct LshStats +{ + std::vector bucket_sizes_; + size_t n_buckets_; + size_t bucket_size_mean_; + size_t bucket_size_median_; + size_t bucket_size_min_; + size_t bucket_size_max_; + size_t bucket_size_std_dev; + /** Each contained vector contains three value: beginning/end for interval, number of elements in the bin + */ + std::vector > size_histogram_; +}; + +/** Overload the << operator for LshStats + * @param out the streams + * @param stats the stats to display + * @return the streams + */ +inline std::ostream& operator <<(std::ostream& out, const LshStats& stats) +{ + int w = 20; + out << "Lsh Table Stats:\n" << std::setw(w) << std::setiosflags(std::ios::right) << "N buckets : " + << stats.n_buckets_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "mean size : " + << std::setiosflags(std::ios::left) << stats.bucket_size_mean_ << "\n" << std::setw(w) + << std::setiosflags(std::ios::right) << "median size : " << stats.bucket_size_median_ << "\n" << std::setw(w) + << std::setiosflags(std::ios::right) << "min size : " << std::setiosflags(std::ios::left) + << stats.bucket_size_min_ << "\n" << std::setw(w) << std::setiosflags(std::ios::right) << "max size : " + << std::setiosflags(std::ios::left) << stats.bucket_size_max_; + + // Display the histogram + out << std::endl << std::setw(w) << std::setiosflags(std::ios::right) << "histogram : " + << std::setiosflags(std::ios::left); + for (std::vector >::const_iterator iterator = stats.size_histogram_.begin(), end = + stats.size_histogram_.end(); iterator != end; ++iterator) out << (*iterator)[0] << "-" << (*iterator)[1] << ": " << (*iterator)[2] << ", "; + + return out; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Lsh hash table. As its key is a sub-feature, and as usually + * the size of it is pretty small, we keep it as a continuous memory array. + * The value is an index in the corpus of features (we keep it as an unsigned + * int for pure memory reasons, it could be a size_t) + */ +template +class LshTable +{ +public: + /** A container of all the feature indices. Optimized for space + */ +#if USE_UNORDERED_MAP + typedef std::unordered_map BucketsSpace; +#else + typedef std::map BucketsSpace; +#endif + + /** A container of all the feature indices. Optimized for speed + */ + typedef std::vector BucketsSpeed; + + /** Default constructor + */ + LshTable() + { + key_size_ = 0; + feature_size_ = 0; + speed_level_ = kArray; + } + + /** Default constructor + * Create the mask and allocate the memory + * @param feature_size is the size of the feature (considered as a ElementType[]) + * @param key_size is the number of bits that are turned on in the feature + */ + LshTable(unsigned int feature_size, unsigned int key_size) + { + feature_size_ = feature_size; + CV_UNUSED(key_size); + CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); + } + + /** Add a feature to the table + * @param value the value to store for that feature + * @param feature the feature itself + */ + void add(unsigned int value, const ElementType* feature) + { + // Add the value to the corresponding bucket + BucketKey key = (lsh::BucketKey)getKey(feature); + + switch (speed_level_) { + case kArray: + // That means we get the buckets from an array + buckets_speed_[key].push_back(value); + break; + case kBitsetHash: + // That means we can check the bitset for the presence of a key + key_bitset_.set(key); + buckets_space_[key].push_back(value); + break; + case kHash: + { + // That means we have to check for the hash table for the presence of a key + buckets_space_[key].push_back(value); + break; + } + } + } + + /** Add a set of features to the table + * @param dataset the values to store + */ + void add(Matrix dataset) + { +#if USE_UNORDERED_MAP + buckets_space_.rehash((buckets_space_.size() + dataset.rows) * 1.2); +#endif + // Add the features to the table + for (unsigned int i = 0; i < dataset.rows; ++i) add(i, dataset[i]); + // Now that the table is full, optimize it for speed/space + optimize(); + } + + /** Get a bucket given the key + */ + inline const Bucket* getBucketFromKey(BucketKey key) const + { + // Generate other buckets + switch (speed_level_) { + case kArray: + // That means we get the buckets from an array + return &buckets_speed_[key]; + break; + case kBitsetHash: + // That means we can check the bitset for the presence of a key + if (key_bitset_.test(key)) return &buckets_space_.find(key)->second; + else return 0; + break; + case kHash: + { + // That means we have to check for the hash table for the presence of a key + BucketsSpace::const_iterator bucket_it, bucket_end = buckets_space_.end(); + bucket_it = buckets_space_.find(key); + // Stop here if that bucket does not exist + if (bucket_it == bucket_end) return 0; + else return &bucket_it->second; + break; + } + } + return 0; + } + + /** Compute the sub-signature of a feature + */ + size_t getKey(const ElementType* /*feature*/) const + { + CV_Error(cv::Error::StsUnsupportedFormat, "LSH is not implemented for that type" ); + return 0; + } + + /** Get statistics about the table + */ + LshStats getStats() const; + +private: + /** defines the speed fo the implementation + * kArray uses a vector for storing data + * kBitsetHash uses a hash map but checks for the validity of a key with a bitset + * kHash uses a hash map only + */ + enum SpeedLevel + { + kArray, kBitsetHash, kHash + }; + + /** Initialize some variables + */ + void initialize(size_t key_size) + { + const size_t key_size_lower_bound = 1; + //a value (size_t(1) << key_size) must fit the size_t type so key_size has to be strictly less than size of size_t + const size_t key_size_upper_bound = (std::min)(sizeof(BucketKey) * CHAR_BIT + 1, sizeof(size_t) * CHAR_BIT); + if (key_size < key_size_lower_bound || key_size >= key_size_upper_bound) + { + CV_Error(cv::Error::StsBadArg, cv::format("Invalid key_size (=%d). Valid values for your system are %d <= key_size < %d.", (int)key_size, (int)key_size_lower_bound, (int)key_size_upper_bound)); + } + + speed_level_ = kHash; + key_size_ = (unsigned)key_size; + } + + /** Optimize the table for speed/space + */ + void optimize() + { + // If we are already using the fast storage, no need to do anything + if (speed_level_ == kArray) return; + + // Use an array if it will be more than half full + if (buckets_space_.size() > ((size_t(1) << key_size_) / 2)) { + speed_level_ = kArray; + // Fill the array version of it + buckets_speed_.resize(size_t(1) << key_size_); + for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) buckets_speed_[key_bucket->first] = key_bucket->second; + + // Empty the hash table + buckets_space_.clear(); + return; + } + + // If the bitset is going to use less than 10% of the RAM of the hash map (at least 1 size_t for the key and two + // for the vector) or less than 512MB (key_size_ <= 30) + if (((std::max(buckets_space_.size(), buckets_speed_.size()) * CHAR_BIT * 3 * sizeof(BucketKey)) / 10 + >= (size_t(1) << key_size_)) || (key_size_ <= 32)) { + speed_level_ = kBitsetHash; + key_bitset_.resize(size_t(1) << key_size_); + key_bitset_.reset(); + // Try with the BucketsSpace + for (BucketsSpace::const_iterator key_bucket = buckets_space_.begin(); key_bucket != buckets_space_.end(); ++key_bucket) key_bitset_.set(key_bucket->first); + } + else { + speed_level_ = kHash; + key_bitset_.clear(); + } + } + + /** The vector of all the buckets if they are held for speed + */ + BucketsSpeed buckets_speed_; + + /** The hash table of all the buckets in case we cannot use the speed version + */ + BucketsSpace buckets_space_; + + /** What is used to store the data */ + SpeedLevel speed_level_; + + /** If the subkey is small enough, it will keep track of which subkeys are set through that bitset + * That is just a speedup so that we don't look in the hash table (which can be mush slower that checking a bitset) + */ + DynamicBitset key_bitset_; + + /** The size of the sub-signature in bits + */ + unsigned int key_size_; + + unsigned int feature_size_; + + // Members only used for the unsigned char specialization + /** The mask to apply to a feature to get the hash key + * Only used in the unsigned char case + */ + std::vector mask_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Specialization for unsigned char + +template<> +inline LshTable::LshTable(unsigned int feature_size, unsigned int subsignature_size) +{ + feature_size_ = feature_size; + initialize(subsignature_size); + // Allocate the mask + mask_ = std::vector((feature_size * sizeof(char) + sizeof(size_t) - 1) / sizeof(size_t), 0); + + // A bit brutal but fast to code + std::vector indices(feature_size * CHAR_BIT); + for (size_t i = 0; i < feature_size * CHAR_BIT; ++i) indices[i] = (int)i; +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::randShuffle(indices); +#else + std::random_shuffle(indices.begin(), indices.end()); +#endif + + // Generate a random set of order of subsignature_size_ bits + for (unsigned int i = 0; i < key_size_; ++i) { + size_t index = indices[i]; + + // Set that bit in the mask + size_t divisor = CHAR_BIT * sizeof(size_t); + size_t idx = index / divisor; //pick the right size_t index + mask_[idx] |= size_t(1) << (index % divisor); //use modulo to find the bit offset + } + + // Set to 1 if you want to display the mask for debug +#if 0 + { + size_t bcount = 0; + BOOST_FOREACH(size_t mask_block, mask_){ + out << std::setw(sizeof(size_t) * CHAR_BIT / 4) << std::setfill('0') << std::hex << mask_block + << std::endl; + bcount += __builtin_popcountll(mask_block); + } + out << "bit count : " << std::dec << bcount << std::endl; + out << "mask size : " << mask_.size() << std::endl; + return out; + } +#endif +} + +/** Return the Subsignature of a feature + * @param feature the feature to analyze + */ +template<> +inline size_t LshTable::getKey(const unsigned char* feature) const +{ + // no need to check if T is dividable by sizeof(size_t) like in the Hamming + // distance computation as we have a mask + // FIXIT: This is bad assumption, because we reading tail bytes after of the allocated features buffer + const size_t* feature_block_ptr = reinterpret_cast ((const void*)feature); + + // Figure out the subsignature of the feature + // Given the feature ABCDEF, and the mask 001011, the output will be + // 000CEF + size_t subsignature = 0; + size_t bit_index = 1; + + for (unsigned i = 0; i < feature_size_; i += sizeof(size_t)) { + // get the mask and signature blocks + size_t feature_block; + if (i <= feature_size_ - sizeof(size_t)) + { + feature_block = *feature_block_ptr; + } + else + { + size_t tmp = 0; + memcpy(&tmp, feature_block_ptr, feature_size_ - i); // preserve bytes order + feature_block = tmp; + } + size_t mask_block = mask_[i / sizeof(size_t)]; + while (mask_block) { + // Get the lowest set bit in the mask block + size_t lowest_bit = mask_block & ~(mask_block - 1); + // Add it to the current subsignature if necessary + subsignature += (feature_block & lowest_bit) ? bit_index : 0; + // Reset the bit in the mask block + mask_block ^= lowest_bit; + // increment the bit index for the subsignature + bit_index <<= 1; + } + // Check the next feature block + ++feature_block_ptr; + } + return subsignature; +} + +template<> +inline LshStats LshTable::getStats() const +{ + LshStats stats; + stats.bucket_size_mean_ = 0; + if ((buckets_speed_.empty()) && (buckets_space_.empty())) { + stats.n_buckets_ = 0; + stats.bucket_size_median_ = 0; + stats.bucket_size_min_ = 0; + stats.bucket_size_max_ = 0; + return stats; + } + + if (!buckets_speed_.empty()) { + for (BucketsSpeed::const_iterator pbucket = buckets_speed_.begin(); pbucket != buckets_speed_.end(); ++pbucket) { + stats.bucket_sizes_.push_back((lsh::FeatureIndex)pbucket->size()); + stats.bucket_size_mean_ += pbucket->size(); + } + stats.bucket_size_mean_ /= buckets_speed_.size(); + stats.n_buckets_ = buckets_speed_.size(); + } + else { + for (BucketsSpace::const_iterator x = buckets_space_.begin(); x != buckets_space_.end(); ++x) { + stats.bucket_sizes_.push_back((lsh::FeatureIndex)x->second.size()); + stats.bucket_size_mean_ += x->second.size(); + } + stats.bucket_size_mean_ /= buckets_space_.size(); + stats.n_buckets_ = buckets_space_.size(); + } + + std::sort(stats.bucket_sizes_.begin(), stats.bucket_sizes_.end()); + + // BOOST_FOREACH(int size, stats.bucket_sizes_) + // std::cout << size << " "; + // std::cout << std::endl; + stats.bucket_size_median_ = stats.bucket_sizes_[stats.bucket_sizes_.size() / 2]; + stats.bucket_size_min_ = stats.bucket_sizes_.front(); + stats.bucket_size_max_ = stats.bucket_sizes_.back(); + + // TODO compute mean and std + /*float mean, stddev; + stats.bucket_size_mean_ = mean; + stats.bucket_size_std_dev = stddev;*/ + + // Include a histogram of the buckets + unsigned int bin_start = 0; + unsigned int bin_end = 20; + bool is_new_bin = true; + for (std::vector::iterator iterator = stats.bucket_sizes_.begin(), end = stats.bucket_sizes_.end(); iterator + != end; ) + if (*iterator < bin_end) { + if (is_new_bin) { + stats.size_histogram_.push_back(std::vector(3, 0)); + stats.size_histogram_.back()[0] = bin_start; + stats.size_histogram_.back()[1] = bin_end - 1; + is_new_bin = false; + } + ++stats.size_histogram_.back()[2]; + ++iterator; + } + else { + bin_start += 20; + bin_end += 20; + is_new_bin = true; + } + + return stats; +} + +// End the two namespaces +} +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +//! @endcond + +#endif /* OPENCV_FLANN_LSH_TABLE_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h b/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h index 5dc326d63e..bfbf91ef5c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/matrix.h @@ -1,121 +1,121 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_DATASET_H_ -#define OPENCV_FLANN_DATASET_H_ - -//! @cond IGNORED - -#include - -#include "opencv2/core/cvdef.h" -#include "opencv2/flann/defines.h" - -namespace cvflann -{ - -/** - * Class that implements a simple rectangular matrix stored in a memory buffer and - * provides convenient matrix-like access using the [] operators. - */ -template -class Matrix -{ -public: - typedef T type; - - size_t rows; - size_t cols; - size_t stride; - T* data; - - Matrix() : rows(0), cols(0), stride(0), data(NULL) - { - } - - Matrix(T* data_, size_t rows_, size_t cols_, size_t stride_ = 0) : - rows(rows_), cols(cols_), stride(stride_), data(data_) - { - if (stride==0) stride = cols; - } - - /** - * Convenience function for deallocating the storage data. - */ - CV_DEPRECATED void free() - { - fprintf(stderr, "The cvflann::Matrix::free() method is deprecated " - "and it does not do any memory deallocation any more. You are" - "responsible for deallocating the matrix memory (by doing" - "'delete[] matrix.data' for example)"); - } - - /** - * Operator that return a (pointer to a) row of the data. - */ - T* operator[](size_t index) const - { - return data+index*stride; - } -}; - - -class UntypedMatrix -{ -public: - size_t rows; - size_t cols; - void* data; - flann_datatype_t type; - - UntypedMatrix(void* data_, long rows_, long cols_) : - rows(rows_), cols(cols_), data(data_) - { - } - - ~UntypedMatrix() - { - } - - - template - Matrix as() - { - return Matrix((T*)data, rows, cols); - } -}; - - - -} - -//! @endcond - -#endif //OPENCV_FLANN_DATASET_H_ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_DATASET_H_ +#define OPENCV_FLANN_DATASET_H_ + +//! @cond IGNORED + +#include + +#include "opencv2/core/cvdef.h" +#include "opencv2/flann/defines.h" + +namespace cvflann +{ + +/** + * Class that implements a simple rectangular matrix stored in a memory buffer and + * provides convenient matrix-like access using the [] operators. + */ +template +class Matrix +{ +public: + typedef T type; + + size_t rows; + size_t cols; + size_t stride; + T* data; + + Matrix() : rows(0), cols(0), stride(0), data(NULL) + { + } + + Matrix(T* data_, size_t rows_, size_t cols_, size_t stride_ = 0) : + rows(rows_), cols(cols_), stride(stride_), data(data_) + { + if (stride==0) stride = cols; + } + + /** + * Convenience function for deallocating the storage data. + */ + CV_DEPRECATED void free() + { + fprintf(stderr, "The cvflann::Matrix::free() method is deprecated " + "and it does not do any memory deallocation any more. You are" + "responsible for deallocating the matrix memory (by doing" + "'delete[] matrix.data' for example)"); + } + + /** + * Operator that return a (pointer to a) row of the data. + */ + T* operator[](size_t index) const + { + return data+index*stride; + } +}; + + +class UntypedMatrix +{ +public: + size_t rows; + size_t cols; + void* data; + flann_datatype_t type; + + UntypedMatrix(void* data_, long rows_, long cols_) : + rows(rows_), cols(cols_), data(data_) + { + } + + ~UntypedMatrix() + { + } + + + template + Matrix as() + { + return Matrix((T*)data, rows, cols); + } +}; + + + +} + +//! @endcond + +#endif //OPENCV_FLANN_DATASET_H_ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp b/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp index 6eea73a060..b8df92d758 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/flann/miniflann.hpp @@ -1,185 +1,185 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_MINIFLANN_HPP -#define OPENCV_MINIFLANN_HPP - -//! @cond IGNORED - -#include "opencv2/core.hpp" -#include "opencv2/flann/defines.h" - -namespace cv -{ - -namespace flann -{ - -enum FlannIndexType { - FLANN_INDEX_TYPE_8U = CV_8U, - FLANN_INDEX_TYPE_8S = CV_8S, - FLANN_INDEX_TYPE_16U = CV_16U, - FLANN_INDEX_TYPE_16S = CV_16S, - FLANN_INDEX_TYPE_32S = CV_32S, - FLANN_INDEX_TYPE_32F = CV_32F, - FLANN_INDEX_TYPE_64F = CV_64F, - FLANN_INDEX_TYPE_STRING, - FLANN_INDEX_TYPE_BOOL, - FLANN_INDEX_TYPE_ALGORITHM, - LAST_VALUE_FLANN_INDEX_TYPE = FLANN_INDEX_TYPE_ALGORITHM -}; - -struct CV_EXPORTS IndexParams -{ - IndexParams(); - ~IndexParams(); - - String getString(const String& key, const String& defaultVal=String()) const; - int getInt(const String& key, int defaultVal=-1) const; - double getDouble(const String& key, double defaultVal=-1) const; - - void setString(const String& key, const String& value); - void setInt(const String& key, int value); - void setDouble(const String& key, double value); - void setFloat(const String& key, float value); - void setBool(const String& key, bool value); - void setAlgorithm(int value); - - // FIXIT: replace by void write(FileStorage& fs) const + read() - void getAll(std::vector& names, - std::vector& types, - std::vector& strValues, - std::vector& numValues) const; - - void* params; - -private: - IndexParams(const IndexParams &); // copy disabled - IndexParams& operator=(const IndexParams &); // assign disabled -}; - -struct CV_EXPORTS KDTreeIndexParams : public IndexParams -{ - KDTreeIndexParams(int trees=4); -}; - -struct CV_EXPORTS LinearIndexParams : public IndexParams -{ - LinearIndexParams(); -}; - -struct CV_EXPORTS CompositeIndexParams : public IndexParams -{ - CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, - cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); -}; - -struct CV_EXPORTS AutotunedIndexParams : public IndexParams -{ - AutotunedIndexParams(float target_precision = 0.8f, float build_weight = 0.01f, - float memory_weight = 0, float sample_fraction = 0.1f); -}; - -struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams -{ - HierarchicalClusteringIndexParams(int branching = 32, - cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100 ); -}; - -struct CV_EXPORTS KMeansIndexParams : public IndexParams -{ - KMeansIndexParams(int branching = 32, int iterations = 11, - cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); -}; - -struct CV_EXPORTS LshIndexParams : public IndexParams -{ - LshIndexParams(int table_number, int key_size, int multi_probe_level); -}; - -struct CV_EXPORTS SavedIndexParams : public IndexParams -{ - SavedIndexParams(const String& filename); -}; - -struct CV_EXPORTS SearchParams : public IndexParams -{ - SearchParams( int checks, float eps, bool sorted, bool explore_all_trees ); - SearchParams( int checks = 32, float eps = 0, bool sorted = true ); -}; - -class CV_EXPORTS_W Index -{ -public: - CV_WRAP Index(); - CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); - virtual ~Index(); - - CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); - CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, - OutputArray dists, int knn, const SearchParams& params=SearchParams()); - - CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices, - OutputArray dists, double radius, int maxResults, - const SearchParams& params=SearchParams()); - - CV_WRAP virtual void save(const String& filename) const; - CV_WRAP virtual bool load(InputArray features, const String& filename); - CV_WRAP virtual void release(); - CV_WRAP cvflann::flann_distance_t getDistance() const; - CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const; - -protected: - bool load_(const String& filename); - - cvflann::flann_distance_t distType; - cvflann::flann_algorithm_t algo; - int featureType; - void* index; - Mat features_clone; // index may store features pointer internally for searching, so avoid dangling pointers: https://github.com/opencv/opencv/issues/17553 -}; - -} } // namespace cv::flann - -//! @endcond - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_MINIFLANN_HPP +#define OPENCV_MINIFLANN_HPP + +//! @cond IGNORED + +#include "opencv2/core.hpp" +#include "opencv2/flann/defines.h" + +namespace cv +{ + +namespace flann +{ + +enum FlannIndexType { + FLANN_INDEX_TYPE_8U = CV_8U, + FLANN_INDEX_TYPE_8S = CV_8S, + FLANN_INDEX_TYPE_16U = CV_16U, + FLANN_INDEX_TYPE_16S = CV_16S, + FLANN_INDEX_TYPE_32S = CV_32S, + FLANN_INDEX_TYPE_32F = CV_32F, + FLANN_INDEX_TYPE_64F = CV_64F, + FLANN_INDEX_TYPE_STRING, + FLANN_INDEX_TYPE_BOOL, + FLANN_INDEX_TYPE_ALGORITHM, + LAST_VALUE_FLANN_INDEX_TYPE = FLANN_INDEX_TYPE_ALGORITHM +}; + +struct CV_EXPORTS IndexParams +{ + IndexParams(); + ~IndexParams(); + + String getString(const String& key, const String& defaultVal=String()) const; + int getInt(const String& key, int defaultVal=-1) const; + double getDouble(const String& key, double defaultVal=-1) const; + + void setString(const String& key, const String& value); + void setInt(const String& key, int value); + void setDouble(const String& key, double value); + void setFloat(const String& key, float value); + void setBool(const String& key, bool value); + void setAlgorithm(int value); + + // FIXIT: replace by void write(FileStorage& fs) const + read() + void getAll(std::vector& names, + std::vector& types, + std::vector& strValues, + std::vector& numValues) const; + + void* params; + +private: + IndexParams(const IndexParams &); // copy disabled + IndexParams& operator=(const IndexParams &); // assign disabled +}; + +struct CV_EXPORTS KDTreeIndexParams : public IndexParams +{ + KDTreeIndexParams(int trees=4); +}; + +struct CV_EXPORTS LinearIndexParams : public IndexParams +{ + LinearIndexParams(); +}; + +struct CV_EXPORTS CompositeIndexParams : public IndexParams +{ + CompositeIndexParams(int trees = 4, int branching = 32, int iterations = 11, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); +}; + +struct CV_EXPORTS AutotunedIndexParams : public IndexParams +{ + AutotunedIndexParams(float target_precision = 0.8f, float build_weight = 0.01f, + float memory_weight = 0, float sample_fraction = 0.1f); +}; + +struct CV_EXPORTS HierarchicalClusteringIndexParams : public IndexParams +{ + HierarchicalClusteringIndexParams(int branching = 32, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, int trees = 4, int leaf_size = 100 ); +}; + +struct CV_EXPORTS KMeansIndexParams : public IndexParams +{ + KMeansIndexParams(int branching = 32, int iterations = 11, + cvflann::flann_centers_init_t centers_init = cvflann::FLANN_CENTERS_RANDOM, float cb_index = 0.2f ); +}; + +struct CV_EXPORTS LshIndexParams : public IndexParams +{ + LshIndexParams(int table_number, int key_size, int multi_probe_level); +}; + +struct CV_EXPORTS SavedIndexParams : public IndexParams +{ + SavedIndexParams(const String& filename); +}; + +struct CV_EXPORTS SearchParams : public IndexParams +{ + SearchParams( int checks, float eps, bool sorted, bool explore_all_trees ); + SearchParams( int checks = 32, float eps = 0, bool sorted = true ); +}; + +class CV_EXPORTS_W Index +{ +public: + CV_WRAP Index(); + CV_WRAP Index(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); + virtual ~Index(); + + CV_WRAP virtual void build(InputArray features, const IndexParams& params, cvflann::flann_distance_t distType=cvflann::FLANN_DIST_L2); + CV_WRAP virtual void knnSearch(InputArray query, OutputArray indices, + OutputArray dists, int knn, const SearchParams& params=SearchParams()); + + CV_WRAP virtual int radiusSearch(InputArray query, OutputArray indices, + OutputArray dists, double radius, int maxResults, + const SearchParams& params=SearchParams()); + + CV_WRAP virtual void save(const String& filename) const; + CV_WRAP virtual bool load(InputArray features, const String& filename); + CV_WRAP virtual void release(); + CV_WRAP cvflann::flann_distance_t getDistance() const; + CV_WRAP cvflann::flann_algorithm_t getAlgorithm() const; + +protected: + bool load_(const String& filename); + + cvflann::flann_distance_t distType; + cvflann::flann_algorithm_t algo; + int featureType; + void* index; + Mat features_clone; // index may store features pointer internally for searching, so avoid dangling pointers: https://github.com/opencv/opencv/issues/17553 +}; + +} } // namespace cv::flann + +//! @endcond + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h b/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h index ae1dd9efed..23a1de7453 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/nn_index.h @@ -1,180 +1,180 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_NNINDEX_H -#define OPENCV_FLANN_NNINDEX_H - -#include "matrix.h" -#include "result_set.h" -#include "params.h" - -//! @cond IGNORED - -namespace cvflann -{ - -/** - * Nearest-neighbour index base class - */ -template -class NNIndex -{ - typedef typename Distance::ElementType ElementType; - typedef typename Distance::ResultType DistanceType; - -public: - - virtual ~NNIndex() {} - - /** - * \brief Builds the index - */ - virtual void buildIndex() = 0; - - /** - * \brief Perform k-nearest neighbor search - * \param[in] queries The query points for which to find the nearest neighbors - * \param[out] indices The indices of the nearest neighbors found - * \param[out] dists Distances to the nearest neighbors found - * \param[in] knn Number of nearest neighbors to return - * \param[in] params Search parameters - */ - virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) - { - CV_Assert(queries.cols == veclen()); - CV_Assert(indices.rows >= queries.rows); - CV_Assert(dists.rows >= queries.rows); - CV_Assert(int(indices.cols) >= knn); - CV_Assert(int(dists.cols) >= knn); - -#if 0 - KNNResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.init(indices[i], dists[i]); - findNeighbors(resultSet, queries[i], params); - } -#else - KNNUniqueResultSet resultSet(knn); - for (size_t i = 0; i < queries.rows; i++) { - resultSet.clear(); - findNeighbors(resultSet, queries[i], params); - if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); - else resultSet.copy(indices[i], dists[i], knn); - } -#endif - } - - /** - * \brief Perform radius search - * \param[in] query The query point - * \param[out] indices The indinces of the neighbors found within the given radius - * \param[out] dists The distances to the nearest neighbors found - * \param[in] radius The radius used for search - * \param[in] params Search parameters - * \returns Number of neighbors found - */ - virtual int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) - { - if (query.rows != 1) { - fprintf(stderr, "I can only search one feature at a time for range search\n"); - return -1; - } - CV_Assert(query.cols == veclen()); - CV_Assert(indices.cols == dists.cols); - - int n = 0; - int* indices_ptr = NULL; - DistanceType* dists_ptr = NULL; - if (indices.cols > 0) { - n = (int)indices.cols; - indices_ptr = indices[0]; - dists_ptr = dists[0]; - } - - RadiusUniqueResultSet resultSet((DistanceType)radius); - resultSet.clear(); - findNeighbors(resultSet, query[0], params); - if (n>0) { - if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices_ptr, dists_ptr, n); - else resultSet.copy(indices_ptr, dists_ptr, n); - } - - return (int)resultSet.size(); - } - - /** - * \brief Saves the index to a stream - * \param stream The stream to save the index to - */ - virtual void saveIndex(FILE* stream) = 0; - - /** - * \brief Loads the index from a stream - * \param stream The stream from which the index is loaded - */ - virtual void loadIndex(FILE* stream) = 0; - - /** - * \returns number of features in this index. - */ - virtual size_t size() const = 0; - - /** - * \returns The dimensionality of the features in this index. - */ - virtual size_t veclen() const = 0; - - /** - * \returns The amount of memory (in bytes) used by the index. - */ - virtual int usedMemory() const = 0; - - /** - * \returns The index type (kdtree, kmeans,...) - */ - virtual flann_algorithm_t getType() const = 0; - - /** - * \returns The index parameters - */ - virtual IndexParams getParameters() const = 0; - - - /** - * \brief Method that searches for nearest-neighbours - */ - virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) = 0; -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_NNINDEX_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_NNINDEX_H +#define OPENCV_FLANN_NNINDEX_H + +#include "matrix.h" +#include "result_set.h" +#include "params.h" + +//! @cond IGNORED + +namespace cvflann +{ + +/** + * Nearest-neighbour index base class + */ +template +class NNIndex +{ + typedef typename Distance::ElementType ElementType; + typedef typename Distance::ResultType DistanceType; + +public: + + virtual ~NNIndex() {} + + /** + * \brief Builds the index + */ + virtual void buildIndex() = 0; + + /** + * \brief Perform k-nearest neighbor search + * \param[in] queries The query points for which to find the nearest neighbors + * \param[out] indices The indices of the nearest neighbors found + * \param[out] dists Distances to the nearest neighbors found + * \param[in] knn Number of nearest neighbors to return + * \param[in] params Search parameters + */ + virtual void knnSearch(const Matrix& queries, Matrix& indices, Matrix& dists, int knn, const SearchParams& params) + { + CV_Assert(queries.cols == veclen()); + CV_Assert(indices.rows >= queries.rows); + CV_Assert(dists.rows >= queries.rows); + CV_Assert(int(indices.cols) >= knn); + CV_Assert(int(dists.cols) >= knn); + +#if 0 + KNNResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.init(indices[i], dists[i]); + findNeighbors(resultSet, queries[i], params); + } +#else + KNNUniqueResultSet resultSet(knn); + for (size_t i = 0; i < queries.rows; i++) { + resultSet.clear(); + findNeighbors(resultSet, queries[i], params); + if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices[i], dists[i], knn); + else resultSet.copy(indices[i], dists[i], knn); + } +#endif + } + + /** + * \brief Perform radius search + * \param[in] query The query point + * \param[out] indices The indinces of the neighbors found within the given radius + * \param[out] dists The distances to the nearest neighbors found + * \param[in] radius The radius used for search + * \param[in] params Search parameters + * \returns Number of neighbors found + */ + virtual int radiusSearch(const Matrix& query, Matrix& indices, Matrix& dists, float radius, const SearchParams& params) + { + if (query.rows != 1) { + fprintf(stderr, "I can only search one feature at a time for range search\n"); + return -1; + } + CV_Assert(query.cols == veclen()); + CV_Assert(indices.cols == dists.cols); + + int n = 0; + int* indices_ptr = NULL; + DistanceType* dists_ptr = NULL; + if (indices.cols > 0) { + n = (int)indices.cols; + indices_ptr = indices[0]; + dists_ptr = dists[0]; + } + + RadiusUniqueResultSet resultSet((DistanceType)radius); + resultSet.clear(); + findNeighbors(resultSet, query[0], params); + if (n>0) { + if (get_param(params,"sorted",true)) resultSet.sortAndCopy(indices_ptr, dists_ptr, n); + else resultSet.copy(indices_ptr, dists_ptr, n); + } + + return (int)resultSet.size(); + } + + /** + * \brief Saves the index to a stream + * \param stream The stream to save the index to + */ + virtual void saveIndex(FILE* stream) = 0; + + /** + * \brief Loads the index from a stream + * \param stream The stream from which the index is loaded + */ + virtual void loadIndex(FILE* stream) = 0; + + /** + * \returns number of features in this index. + */ + virtual size_t size() const = 0; + + /** + * \returns The dimensionality of the features in this index. + */ + virtual size_t veclen() const = 0; + + /** + * \returns The amount of memory (in bytes) used by the index. + */ + virtual int usedMemory() const = 0; + + /** + * \returns The index type (kdtree, kmeans,...) + */ + virtual flann_algorithm_t getType() const = 0; + + /** + * \returns The index parameters + */ + virtual IndexParams getParameters() const = 0; + + + /** + * \brief Method that searches for nearest-neighbours + */ + virtual void findNeighbors(ResultSet& result, const ElementType* vec, const SearchParams& searchParams) = 0; +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_NNINDEX_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h b/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h index 1eb26ad75d..5cc45ad1b3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/object_factory.h @@ -1,95 +1,95 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_OBJECT_FACTORY_H_ -#define OPENCV_FLANN_OBJECT_FACTORY_H_ - -//! @cond IGNORED - -#include - -namespace cvflann -{ - -class CreatorNotFound -{ -}; - -template -class ObjectFactory -{ - typedef ObjectFactory ThisClass; - typedef std::map ObjectRegistry; - - // singleton class, private constructor - ObjectFactory() {} - -public: - - bool subscribe(UniqueIdType id, ObjectCreator creator) - { - if (object_registry.find(id) != object_registry.end()) return false; - - object_registry[id] = creator; - return true; - } - - bool unregister(UniqueIdType id) - { - return object_registry.erase(id) == 1; - } - - ObjectCreator create(UniqueIdType id) - { - typename ObjectRegistry::const_iterator iter = object_registry.find(id); - - if (iter == object_registry.end()) { - throw CreatorNotFound(); - } - - return iter->second; - } - - static ThisClass& instance() - { - static ThisClass the_factory; - return the_factory; - } -private: - ObjectRegistry object_registry; -}; - -} - -//! @endcond - -#endif /* OPENCV_FLANN_OBJECT_FACTORY_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_OBJECT_FACTORY_H_ +#define OPENCV_FLANN_OBJECT_FACTORY_H_ + +//! @cond IGNORED + +#include + +namespace cvflann +{ + +class CreatorNotFound +{ +}; + +template +class ObjectFactory +{ + typedef ObjectFactory ThisClass; + typedef std::map ObjectRegistry; + + // singleton class, private constructor + ObjectFactory() {} + +public: + + bool subscribe(UniqueIdType id, ObjectCreator creator) + { + if (object_registry.find(id) != object_registry.end()) return false; + + object_registry[id] = creator; + return true; + } + + bool unregister(UniqueIdType id) + { + return object_registry.erase(id) == 1; + } + + ObjectCreator create(UniqueIdType id) + { + typename ObjectRegistry::const_iterator iter = object_registry.find(id); + + if (iter == object_registry.end()) { + throw CreatorNotFound(); + } + + return iter->second; + } + + static ThisClass& instance() + { + static ThisClass the_factory; + return the_factory; + } +private: + ObjectRegistry object_registry; +}; + +} + +//! @endcond + +#endif /* OPENCV_FLANN_OBJECT_FACTORY_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/params.h b/3rdParty/opencv-4.11.0/opencv2/flann/params.h index 04aac83a42..1a8e127035 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/params.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/params.h @@ -1,126 +1,126 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - - -#ifndef OPENCV_FLANN_PARAMS_H_ -#define OPENCV_FLANN_PARAMS_H_ - -//! @cond IGNORED - -#include "any.h" -#include "general.h" -#include -#include - - -namespace cvflann -{ - -typedef std::map IndexParams; - -struct SearchParams : public IndexParams -{ - SearchParams(int checks = 32, float eps = 0, bool sorted = true ) - { - init(checks, eps, sorted, false); - } - - SearchParams(int checks, float eps, bool sorted, bool explore_all_trees ) - { - init(checks, eps, sorted, explore_all_trees); - } - - void init(int checks = 32, float eps = 0, bool sorted = true, bool explore_all_trees = false ) - { - // how many leafs to visit when searching for neighbours (-1 for unlimited) - (*this)["checks"] = checks; - // search for eps-approximate neighbours (default: 0) - (*this)["eps"] = eps; - // only for radius search, require neighbours sorted by distance (default: true) - (*this)["sorted"] = sorted; - // if false, search stops at the tree reaching the number of max checks (original behavior). - // When true, we do a descent in each tree and. Like before the alternative paths - // stored in the heap are not be processed further when max checks is reached. - (*this)["explore_all_trees"] = explore_all_trees; - } -}; - - -template -T get_param(const IndexParams& params, const cv::String& name, const T& default_value) -{ - IndexParams::const_iterator it = params.find(name); - if (it != params.end()) { - try { - return it->second.cast(); - } catch (const std::exception& e) { - CV_Error_(cv::Error::StsBadArg, - ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); - } - } - else { - return default_value; - } -} - -template -T get_param(const IndexParams& params, const cv::String& name) -{ - IndexParams::const_iterator it = params.find(name); - if (it != params.end()) { - try { - return it->second.cast(); - } catch (const std::exception& e) { - CV_Error_(cv::Error::StsBadArg, - ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); - } - } - else { - FLANN_THROW(cv::Error::StsBadArg, cv::String("Missing parameter '")+name+cv::String("' in the parameters given")); - } -} - -inline void print_params(const IndexParams& params, std::ostream& stream) -{ - IndexParams::const_iterator it; - - for(it=params.begin(); it!=params.end(); ++it) { - stream << it->first << " : " << it->second << std::endl; - } -} - -inline void print_params(const IndexParams& params) -{ - print_params(params, std::cout); -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_PARAMS_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2011 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2011 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + + +#ifndef OPENCV_FLANN_PARAMS_H_ +#define OPENCV_FLANN_PARAMS_H_ + +//! @cond IGNORED + +#include "any.h" +#include "general.h" +#include +#include + + +namespace cvflann +{ + +typedef std::map IndexParams; + +struct SearchParams : public IndexParams +{ + SearchParams(int checks = 32, float eps = 0, bool sorted = true ) + { + init(checks, eps, sorted, false); + } + + SearchParams(int checks, float eps, bool sorted, bool explore_all_trees ) + { + init(checks, eps, sorted, explore_all_trees); + } + + void init(int checks = 32, float eps = 0, bool sorted = true, bool explore_all_trees = false ) + { + // how many leafs to visit when searching for neighbours (-1 for unlimited) + (*this)["checks"] = checks; + // search for eps-approximate neighbours (default: 0) + (*this)["eps"] = eps; + // only for radius search, require neighbours sorted by distance (default: true) + (*this)["sorted"] = sorted; + // if false, search stops at the tree reaching the number of max checks (original behavior). + // When true, we do a descent in each tree and. Like before the alternative paths + // stored in the heap are not be processed further when max checks is reached. + (*this)["explore_all_trees"] = explore_all_trees; + } +}; + + +template +T get_param(const IndexParams& params, const cv::String& name, const T& default_value) +{ + IndexParams::const_iterator it = params.find(name); + if (it != params.end()) { + try { + return it->second.cast(); + } catch (const std::exception& e) { + CV_Error_(cv::Error::StsBadArg, + ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); + } + } + else { + return default_value; + } +} + +template +T get_param(const IndexParams& params, const cv::String& name) +{ + IndexParams::const_iterator it = params.find(name); + if (it != params.end()) { + try { + return it->second.cast(); + } catch (const std::exception& e) { + CV_Error_(cv::Error::StsBadArg, + ("FLANN '%s' param type mismatch: %s", name.c_str(), e.what())); + } + } + else { + FLANN_THROW(cv::Error::StsBadArg, cv::String("Missing parameter '")+name+cv::String("' in the parameters given")); + } +} + +inline void print_params(const IndexParams& params, std::ostream& stream) +{ + IndexParams::const_iterator it; + + for(it=params.begin(); it!=params.end(); ++it) { + stream << it->first << " : " << it->second << std::endl; + } +} + +inline void print_params(const IndexParams& params) +{ + print_params(params, std::cout); +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_PARAMS_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/random.h b/3rdParty/opencv-4.11.0/opencv2/flann/random.h index 4ad50c43a0..5a12ef3046 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/random.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/random.h @@ -1,156 +1,156 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_RANDOM_H -#define OPENCV_FLANN_RANDOM_H - -//! @cond IGNORED - -#include -#include -#include - -namespace cvflann -{ - -inline int rand() -{ -#ifndef OPENCV_FLANN_USE_STD_RAND -# if INT_MAX == RAND_MAX - int v = cv::theRNG().next() & INT_MAX; -# else - int v = cv::theRNG().uniform(0, RAND_MAX + 1); -# endif -#else - int v = std::rand(); -#endif // OPENCV_FLANN_USE_STD_RAND - return v; -} - -/** - * Seeds the random number generator - * @param seed Random seed - */ -inline void seed_random(unsigned int seed) -{ -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::theRNG() = cv::RNG(seed); -#else - std::srand(seed); -#endif -} - -/* - * Generates a random double value. - */ -/** - * Generates a random double value. - * @param high Upper limit - * @param low Lower limit - * @return Random double value - */ -inline double rand_double(double high = 1.0, double low = 0) -{ - return low + ((high-low) * (rand() / (RAND_MAX + 1.0))); -} - -/** - * Generates a random integer value. - * @param high Upper limit - * @param low Lower limit - * @return Random integer value - */ -inline int rand_int(int high = RAND_MAX, int low = 0) -{ - return low + (int) ( double(high-low) * (rand() / (RAND_MAX + 1.0))); -} - -/** - * Random number generator that returns a distinct number from - * the [0,n) interval each time. - */ -class UniqueRandom -{ - std::vector vals_; - int size_; - int counter_; - -public: - /** - * Constructor. - * @param n Size of the interval from which to generate - */ - UniqueRandom(int n) - { - init(n); - } - - /** - * Initializes the number generator. - * @param n the size of the interval from which to generate random numbers. - */ - void init(int n) - { - // create and initialize an array of size n - vals_.resize(n); - size_ = n; - for (int i = 0; i < size_; ++i) vals_[i] = i; - - // shuffle the elements in the array -#ifndef OPENCV_FLANN_USE_STD_RAND - cv::randShuffle(vals_); -#else - std::random_shuffle(vals_.begin(), vals_.end()); -#endif - - counter_ = 0; - } - - /** - * Return a distinct random integer in greater or equal to 0 and less - * than 'n' on each call. It should be called maximum 'n' times. - * Returns: a random integer - */ - int next() - { - if (counter_ == size_) { - return -1; - } - else { - return vals_[counter_++]; - } - } -}; - -} - -//! @endcond - -#endif //OPENCV_FLANN_RANDOM_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_RANDOM_H +#define OPENCV_FLANN_RANDOM_H + +//! @cond IGNORED + +#include +#include +#include + +namespace cvflann +{ + +inline int rand() +{ +#ifndef OPENCV_FLANN_USE_STD_RAND +# if INT_MAX == RAND_MAX + int v = cv::theRNG().next() & INT_MAX; +# else + int v = cv::theRNG().uniform(0, RAND_MAX + 1); +# endif +#else + int v = std::rand(); +#endif // OPENCV_FLANN_USE_STD_RAND + return v; +} + +/** + * Seeds the random number generator + * @param seed Random seed + */ +inline void seed_random(unsigned int seed) +{ +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::theRNG() = cv::RNG(seed); +#else + std::srand(seed); +#endif +} + +/* + * Generates a random double value. + */ +/** + * Generates a random double value. + * @param high Upper limit + * @param low Lower limit + * @return Random double value + */ +inline double rand_double(double high = 1.0, double low = 0) +{ + return low + ((high-low) * (rand() / (RAND_MAX + 1.0))); +} + +/** + * Generates a random integer value. + * @param high Upper limit + * @param low Lower limit + * @return Random integer value + */ +inline int rand_int(int high = RAND_MAX, int low = 0) +{ + return low + (int) ( double(high-low) * (rand() / (RAND_MAX + 1.0))); +} + +/** + * Random number generator that returns a distinct number from + * the [0,n) interval each time. + */ +class UniqueRandom +{ + std::vector vals_; + int size_; + int counter_; + +public: + /** + * Constructor. + * @param n Size of the interval from which to generate + */ + UniqueRandom(int n) + { + init(n); + } + + /** + * Initializes the number generator. + * @param n the size of the interval from which to generate random numbers. + */ + void init(int n) + { + // create and initialize an array of size n + vals_.resize(n); + size_ = n; + for (int i = 0; i < size_; ++i) vals_[i] = i; + + // shuffle the elements in the array +#ifndef OPENCV_FLANN_USE_STD_RAND + cv::randShuffle(vals_); +#else + std::random_shuffle(vals_.begin(), vals_.end()); +#endif + + counter_ = 0; + } + + /** + * Return a distinct random integer in greater or equal to 0 and less + * than 'n' on each call. It should be called maximum 'n' times. + * Returns: a random integer + */ + int next() + { + if (counter_ == size_) { + return -1; + } + else { + return vals_[counter_++]; + } + } +}; + +} + +//! @endcond + +#endif //OPENCV_FLANN_RANDOM_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h b/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h index 08f711c694..aa679df71c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/result_set.h @@ -1,548 +1,548 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_RESULTSET_H -#define OPENCV_FLANN_RESULTSET_H - -//! @cond IGNORED - -#include -#include -#include -#include -#include -#include - -#include "opencv2/core/base.hpp" -#include "opencv2/core/cvdef.h" - -namespace cvflann -{ - -/* This record represents a branch point when finding neighbors in - the tree. It contains a record of the minimum distance to the query - point, as well as the node at which the search resumes. - */ - -template -struct BranchStruct -{ - T node; /* Tree node at which search resumes */ - DistanceType mindist; /* Minimum distance to query for all nodes below. */ - - BranchStruct() {} - BranchStruct(const T& aNode, DistanceType dist) : node(aNode), mindist(dist) {} - - bool operator<(const BranchStruct& rhs) const - { - return mindist -class ResultSet -{ -public: - virtual ~ResultSet() {} - - virtual bool full() const = 0; - - virtual void addPoint(DistanceType dist, int index) = 0; - - virtual DistanceType worstDist() const = 0; - -}; - -/** - * KNNSimpleResultSet does not ensure that the element it holds are unique. - * Is used in those cases where the nearest neighbour algorithm used does not - * attempt to insert the same element multiple times. - */ -template -class KNNSimpleResultSet : public ResultSet -{ - int* indices; - DistanceType* dists; - int capacity; - int count; - DistanceType worst_distance_; - -public: - KNNSimpleResultSet(int capacity_) : capacity(capacity_), count(0) - { - } - - void init(int* indices_, DistanceType* dists_) - { - indices = indices_; - dists = dists_; - count = 0; - worst_distance_ = (std::numeric_limits::max)(); - dists[capacity-1] = worst_distance_; - } - - size_t size() const - { - return count; - } - - bool full() const CV_OVERRIDE - { - return count == capacity; - } - - - void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - if (dist >= worst_distance_) return; - int i; - for (i=count; i>0; --i) { -#ifdef FLANN_FIRST_MATCH - if ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) -#else - if (dists[i-1]>dist) -#endif - { - if (i -class KNNResultSet : public ResultSet -{ - int* indices; - DistanceType* dists; - int capacity; - int count; - DistanceType worst_distance_; - -public: - KNNResultSet(int capacity_) - : indices(NULL), dists(NULL), capacity(capacity_), count(0), worst_distance_(0) - { - } - - void init(int* indices_, DistanceType* dists_) - { - indices = indices_; - dists = dists_; - count = 0; - worst_distance_ = (std::numeric_limits::max)(); - dists[capacity-1] = worst_distance_; - } - - size_t size() const - { - return count; - } - - bool full() const CV_OVERRIDE - { - return count == capacity; - } - - - void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - CV_DbgAssert(indices); - CV_DbgAssert(dists); - if (dist >= worst_distance_) return; - int i; - for (i = count; i > 0; --i) { -#ifdef FLANN_FIRST_MATCH - if ( (dists[i-1]<=dist) && ((dist!=dists[i-1])||(indices[i-1]<=index)) ) -#else - if (dists[i-1]<=dist) -#endif - { - // Check for duplicate indices - for (int j = i; dists[j] == dist && j--;) { - if (indices[j] == index) { - return; - } - } - break; - } - } - - if (count < capacity) ++count; - for (int j = count-1; j > i; --j) { - dists[j] = dists[j-1]; - indices[j] = indices[j-1]; - } - dists[i] = dist; - indices[i] = index; - worst_distance_ = dists[capacity-1]; - } - - DistanceType worstDist() const CV_OVERRIDE - { - return worst_distance_; - } -}; - - -/** - * A result-set class used when performing a radius based search. - */ -template -class RadiusResultSet : public ResultSet -{ - DistanceType radius; - int* indices; - DistanceType* dists; - size_t capacity; - size_t count; - -public: - RadiusResultSet(DistanceType radius_, int* indices_, DistanceType* dists_, int capacity_) : - radius(radius_), indices(indices_), dists(dists_), capacity(capacity_) - { - init(); - } - - ~RadiusResultSet() - { - } - - void init() - { - count = 0; - } - - size_t size() const - { - return count; - } - - bool full() const - { - return true; - } - - void addPoint(DistanceType dist, int index) - { - if (dist0)&&(count < capacity)) { - dists[count] = dist; - indices[count] = index; - } - count++; - } - } - - DistanceType worstDist() const - { - return radius; - } - -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the k NN neighbors - * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays - */ -template -class UniqueResultSet : public ResultSet -{ -public: - struct DistIndex - { - DistIndex(DistanceType dist, unsigned int index) : - dist_(dist), index_(index) - { - } - bool operator<(const DistIndex dist_index) const - { - return (dist_ < dist_index.dist_) || ((dist_ == dist_index.dist_) && index_ < dist_index.index_); - } - DistanceType dist_; - unsigned int index_; - }; - - /** Default constructor */ - UniqueResultSet() : - is_full_(false), worst_distance_(std::numeric_limits::max()) - { - } - - /** Check the status of the set - * @return true if we have k NN - */ - inline bool full() const CV_OVERRIDE - { - return is_full_; - } - - /** Remove all elements in the set - */ - virtual void clear() = 0; - - /** Copy the set to two C arrays - * @param indices pointer to a C array of indices - * @param dist pointer to a C array of distances - * @param n_neighbors the number of neighbors to copy - */ - virtual void copy(int* indices, DistanceType* dist, int n_neighbors = -1) const - { - if (n_neighbors < 0) { - for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = - dist_indices_.end(); dist_index != dist_index_end; ++dist_index, ++indices, ++dist) { - *indices = dist_index->index_; - *dist = dist_index->dist_; - } - } - else { - int i = 0; - for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = - dist_indices_.end(); (dist_index != dist_index_end) && (i < n_neighbors); ++dist_index, ++indices, ++dist, ++i) { - *indices = dist_index->index_; - *dist = dist_index->dist_; - } - } - } - - /** Copy the set to two C arrays but sort it according to the distance first - * @param indices pointer to a C array of indices - * @param dist pointer to a C array of distances - * @param n_neighbors the number of neighbors to copy - */ - virtual void sortAndCopy(int* indices, DistanceType* dist, int n_neighbors = -1) const - { - copy(indices, dist, n_neighbors); - } - - /** The number of neighbors in the set - */ - size_t size() const - { - return dist_indices_.size(); - } - - /** The distance of the furthest neighbor - * If we don't have enough neighbors, it returns the max possible value - */ - inline DistanceType worstDist() const CV_OVERRIDE - { - return worst_distance_; - } -protected: - /** Flag to say if the set is full */ - bool is_full_; - - /** The worst distance found so far */ - DistanceType worst_distance_; - - /** The best candidates so far */ - std::set dist_indices_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the k NN neighbors - * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays - */ -template -class KNNUniqueResultSet : public UniqueResultSet -{ -public: - /** Constructor - * @param capacity the number of neighbors to store at max - */ - KNNUniqueResultSet(unsigned int capacity) : capacity_(capacity) - { - this->is_full_ = false; - this->clear(); - } - - /** Add a possible candidate to the best neighbors - * @param dist distance for that neighbor - * @param index index of that neighbor - */ - inline void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - // Don't do anything if we are worse than the worst - if (dist >= worst_distance_) return; - dist_indices_.insert(DistIndex(dist, index)); - - if (is_full_) { - if (dist_indices_.size() > capacity_) { - dist_indices_.erase(*dist_indices_.rbegin()); - worst_distance_ = dist_indices_.rbegin()->dist_; - } - } - else if (dist_indices_.size() == capacity_) { - is_full_ = true; - worst_distance_ = dist_indices_.rbegin()->dist_; - } - } - - /** Remove all elements in the set - */ - void clear() CV_OVERRIDE - { - dist_indices_.clear(); - worst_distance_ = std::numeric_limits::max(); - is_full_ = false; - } - -protected: - typedef typename UniqueResultSet::DistIndex DistIndex; - using UniqueResultSet::is_full_; - using UniqueResultSet::worst_distance_; - using UniqueResultSet::dist_indices_; - - /** The number of neighbors to keep */ - unsigned int capacity_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the radius nearest neighbors - * It is more accurate than RadiusResult as it is not limited in the number of neighbors - */ -template -class RadiusUniqueResultSet : public UniqueResultSet -{ -public: - /** Constructor - * @param radius the maximum distance of a neighbor - */ - RadiusUniqueResultSet(DistanceType radius) : - radius_(radius) - { - is_full_ = true; - } - - /** Add a possible candidate to the best neighbors - * @param dist distance for that neighbor - * @param index index of that neighbor - */ - void addPoint(DistanceType dist, int index) CV_OVERRIDE - { - if (dist <= radius_) dist_indices_.insert(DistIndex(dist, index)); - } - - /** Remove all elements in the set - */ - inline void clear() CV_OVERRIDE - { - dist_indices_.clear(); - } - - - /** Check the status of the set - * @return alwys false - */ - inline bool full() const CV_OVERRIDE - { - return true; - } - - /** The distance of the furthest neighbor - * If we don't have enough neighbors, it returns the max possible value - */ - inline DistanceType worstDist() const CV_OVERRIDE - { - return radius_; - } -private: - typedef typename UniqueResultSet::DistIndex DistIndex; - using UniqueResultSet::dist_indices_; - using UniqueResultSet::is_full_; - - /** The furthest distance a neighbor can be */ - DistanceType radius_; -}; - -//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - -/** Class that holds the k NN neighbors within a radius distance - */ -template -class KNNRadiusUniqueResultSet : public KNNUniqueResultSet -{ -public: - /** Constructor - * @param capacity the number of neighbors to store at max - * @param radius the maximum distance of a neighbor - */ - KNNRadiusUniqueResultSet(unsigned int capacity, DistanceType radius) - { - this->capacity_ = capacity; - this->radius_ = radius; - this->dist_indices_.reserve(capacity_); - this->clear(); - } - - /** Remove all elements in the set - */ - void clear() - { - dist_indices_.clear(); - worst_distance_ = radius_; - is_full_ = false; - } -private: - using KNNUniqueResultSet::dist_indices_; - using KNNUniqueResultSet::is_full_; - using KNNUniqueResultSet::worst_distance_; - - /** The maximum number of neighbors to consider */ - unsigned int capacity_; - - /** The maximum distance of a neighbor */ - DistanceType radius_; -}; -} - -//! @endcond - -#endif //OPENCV_FLANN_RESULTSET_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_RESULTSET_H +#define OPENCV_FLANN_RESULTSET_H + +//! @cond IGNORED + +#include +#include +#include +#include +#include +#include + +#include "opencv2/core/base.hpp" +#include "opencv2/core/cvdef.h" + +namespace cvflann +{ + +/* This record represents a branch point when finding neighbors in + the tree. It contains a record of the minimum distance to the query + point, as well as the node at which the search resumes. + */ + +template +struct BranchStruct +{ + T node; /* Tree node at which search resumes */ + DistanceType mindist; /* Minimum distance to query for all nodes below. */ + + BranchStruct() {} + BranchStruct(const T& aNode, DistanceType dist) : node(aNode), mindist(dist) {} + + bool operator<(const BranchStruct& rhs) const + { + return mindist +class ResultSet +{ +public: + virtual ~ResultSet() {} + + virtual bool full() const = 0; + + virtual void addPoint(DistanceType dist, int index) = 0; + + virtual DistanceType worstDist() const = 0; + +}; + +/** + * KNNSimpleResultSet does not ensure that the element it holds are unique. + * Is used in those cases where the nearest neighbour algorithm used does not + * attempt to insert the same element multiple times. + */ +template +class KNNSimpleResultSet : public ResultSet +{ + int* indices; + DistanceType* dists; + int capacity; + int count; + DistanceType worst_distance_; + +public: + KNNSimpleResultSet(int capacity_) : capacity(capacity_), count(0) + { + } + + void init(int* indices_, DistanceType* dists_) + { + indices = indices_; + dists = dists_; + count = 0; + worst_distance_ = (std::numeric_limits::max)(); + dists[capacity-1] = worst_distance_; + } + + size_t size() const + { + return count; + } + + bool full() const CV_OVERRIDE + { + return count == capacity; + } + + + void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + if (dist >= worst_distance_) return; + int i; + for (i=count; i>0; --i) { +#ifdef FLANN_FIRST_MATCH + if ( (dists[i-1]>dist) || ((dist==dists[i-1])&&(indices[i-1]>index)) ) +#else + if (dists[i-1]>dist) +#endif + { + if (i +class KNNResultSet : public ResultSet +{ + int* indices; + DistanceType* dists; + int capacity; + int count; + DistanceType worst_distance_; + +public: + KNNResultSet(int capacity_) + : indices(NULL), dists(NULL), capacity(capacity_), count(0), worst_distance_(0) + { + } + + void init(int* indices_, DistanceType* dists_) + { + indices = indices_; + dists = dists_; + count = 0; + worst_distance_ = (std::numeric_limits::max)(); + dists[capacity-1] = worst_distance_; + } + + size_t size() const + { + return count; + } + + bool full() const CV_OVERRIDE + { + return count == capacity; + } + + + void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + CV_DbgAssert(indices); + CV_DbgAssert(dists); + if (dist >= worst_distance_) return; + int i; + for (i = count; i > 0; --i) { +#ifdef FLANN_FIRST_MATCH + if ( (dists[i-1]<=dist) && ((dist!=dists[i-1])||(indices[i-1]<=index)) ) +#else + if (dists[i-1]<=dist) +#endif + { + // Check for duplicate indices + for (int j = i; dists[j] == dist && j--;) { + if (indices[j] == index) { + return; + } + } + break; + } + } + + if (count < capacity) ++count; + for (int j = count-1; j > i; --j) { + dists[j] = dists[j-1]; + indices[j] = indices[j-1]; + } + dists[i] = dist; + indices[i] = index; + worst_distance_ = dists[capacity-1]; + } + + DistanceType worstDist() const CV_OVERRIDE + { + return worst_distance_; + } +}; + + +/** + * A result-set class used when performing a radius based search. + */ +template +class RadiusResultSet : public ResultSet +{ + DistanceType radius; + int* indices; + DistanceType* dists; + size_t capacity; + size_t count; + +public: + RadiusResultSet(DistanceType radius_, int* indices_, DistanceType* dists_, int capacity_) : + radius(radius_), indices(indices_), dists(dists_), capacity(capacity_) + { + init(); + } + + ~RadiusResultSet() + { + } + + void init() + { + count = 0; + } + + size_t size() const + { + return count; + } + + bool full() const + { + return true; + } + + void addPoint(DistanceType dist, int index) + { + if (dist0)&&(count < capacity)) { + dists[count] = dist; + indices[count] = index; + } + count++; + } + } + + DistanceType worstDist() const + { + return radius; + } + +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the k NN neighbors + * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays + */ +template +class UniqueResultSet : public ResultSet +{ +public: + struct DistIndex + { + DistIndex(DistanceType dist, unsigned int index) : + dist_(dist), index_(index) + { + } + bool operator<(const DistIndex dist_index) const + { + return (dist_ < dist_index.dist_) || ((dist_ == dist_index.dist_) && index_ < dist_index.index_); + } + DistanceType dist_; + unsigned int index_; + }; + + /** Default constructor */ + UniqueResultSet() : + is_full_(false), worst_distance_(std::numeric_limits::max()) + { + } + + /** Check the status of the set + * @return true if we have k NN + */ + inline bool full() const CV_OVERRIDE + { + return is_full_; + } + + /** Remove all elements in the set + */ + virtual void clear() = 0; + + /** Copy the set to two C arrays + * @param indices pointer to a C array of indices + * @param dist pointer to a C array of distances + * @param n_neighbors the number of neighbors to copy + */ + virtual void copy(int* indices, DistanceType* dist, int n_neighbors = -1) const + { + if (n_neighbors < 0) { + for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = + dist_indices_.end(); dist_index != dist_index_end; ++dist_index, ++indices, ++dist) { + *indices = dist_index->index_; + *dist = dist_index->dist_; + } + } + else { + int i = 0; + for (typename std::set::const_iterator dist_index = dist_indices_.begin(), dist_index_end = + dist_indices_.end(); (dist_index != dist_index_end) && (i < n_neighbors); ++dist_index, ++indices, ++dist, ++i) { + *indices = dist_index->index_; + *dist = dist_index->dist_; + } + } + } + + /** Copy the set to two C arrays but sort it according to the distance first + * @param indices pointer to a C array of indices + * @param dist pointer to a C array of distances + * @param n_neighbors the number of neighbors to copy + */ + virtual void sortAndCopy(int* indices, DistanceType* dist, int n_neighbors = -1) const + { + copy(indices, dist, n_neighbors); + } + + /** The number of neighbors in the set + */ + size_t size() const + { + return dist_indices_.size(); + } + + /** The distance of the furthest neighbor + * If we don't have enough neighbors, it returns the max possible value + */ + inline DistanceType worstDist() const CV_OVERRIDE + { + return worst_distance_; + } +protected: + /** Flag to say if the set is full */ + bool is_full_; + + /** The worst distance found so far */ + DistanceType worst_distance_; + + /** The best candidates so far */ + std::set dist_indices_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the k NN neighbors + * Faster than KNNResultSet as it uses a binary heap and does not maintain two arrays + */ +template +class KNNUniqueResultSet : public UniqueResultSet +{ +public: + /** Constructor + * @param capacity the number of neighbors to store at max + */ + KNNUniqueResultSet(unsigned int capacity) : capacity_(capacity) + { + this->is_full_ = false; + this->clear(); + } + + /** Add a possible candidate to the best neighbors + * @param dist distance for that neighbor + * @param index index of that neighbor + */ + inline void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + // Don't do anything if we are worse than the worst + if (dist >= worst_distance_) return; + dist_indices_.insert(DistIndex(dist, index)); + + if (is_full_) { + if (dist_indices_.size() > capacity_) { + dist_indices_.erase(*dist_indices_.rbegin()); + worst_distance_ = dist_indices_.rbegin()->dist_; + } + } + else if (dist_indices_.size() == capacity_) { + is_full_ = true; + worst_distance_ = dist_indices_.rbegin()->dist_; + } + } + + /** Remove all elements in the set + */ + void clear() CV_OVERRIDE + { + dist_indices_.clear(); + worst_distance_ = std::numeric_limits::max(); + is_full_ = false; + } + +protected: + typedef typename UniqueResultSet::DistIndex DistIndex; + using UniqueResultSet::is_full_; + using UniqueResultSet::worst_distance_; + using UniqueResultSet::dist_indices_; + + /** The number of neighbors to keep */ + unsigned int capacity_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the radius nearest neighbors + * It is more accurate than RadiusResult as it is not limited in the number of neighbors + */ +template +class RadiusUniqueResultSet : public UniqueResultSet +{ +public: + /** Constructor + * @param radius the maximum distance of a neighbor + */ + RadiusUniqueResultSet(DistanceType radius) : + radius_(radius) + { + is_full_ = true; + } + + /** Add a possible candidate to the best neighbors + * @param dist distance for that neighbor + * @param index index of that neighbor + */ + void addPoint(DistanceType dist, int index) CV_OVERRIDE + { + if (dist <= radius_) dist_indices_.insert(DistIndex(dist, index)); + } + + /** Remove all elements in the set + */ + inline void clear() CV_OVERRIDE + { + dist_indices_.clear(); + } + + + /** Check the status of the set + * @return alwys false + */ + inline bool full() const CV_OVERRIDE + { + return true; + } + + /** The distance of the furthest neighbor + * If we don't have enough neighbors, it returns the max possible value + */ + inline DistanceType worstDist() const CV_OVERRIDE + { + return radius_; + } +private: + typedef typename UniqueResultSet::DistIndex DistIndex; + using UniqueResultSet::dist_indices_; + using UniqueResultSet::is_full_; + + /** The furthest distance a neighbor can be */ + DistanceType radius_; +}; + +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +/** Class that holds the k NN neighbors within a radius distance + */ +template +class KNNRadiusUniqueResultSet : public KNNUniqueResultSet +{ +public: + /** Constructor + * @param capacity the number of neighbors to store at max + * @param radius the maximum distance of a neighbor + */ + KNNRadiusUniqueResultSet(unsigned int capacity, DistanceType radius) + { + this->capacity_ = capacity; + this->radius_ = radius; + this->dist_indices_.reserve(capacity_); + this->clear(); + } + + /** Remove all elements in the set + */ + void clear() + { + dist_indices_.clear(); + worst_distance_ = radius_; + is_full_ = false; + } +private: + using KNNUniqueResultSet::dist_indices_; + using KNNUniqueResultSet::is_full_; + using KNNUniqueResultSet::worst_distance_; + + /** The maximum number of neighbors to consider */ + unsigned int capacity_; + + /** The maximum distance of a neighbor */ + DistanceType radius_; +}; +} + +//! @endcond + +#endif //OPENCV_FLANN_RESULTSET_H diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h b/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h index c8b3a4fe84..4e452b9bba 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/sampling.h @@ -1,84 +1,84 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - - -#ifndef OPENCV_FLANN_SAMPLING_H_ -#define OPENCV_FLANN_SAMPLING_H_ - -//! @cond IGNORED - -#include "matrix.h" -#include "random.h" - -namespace cvflann -{ - -template -Matrix random_sample(Matrix& srcMatrix, long size, bool remove = false) -{ - Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); - - T* src,* dest; - for (long i=0; i -Matrix random_sample(const Matrix& srcMatrix, size_t size) -{ - UniqueRandom rand((int)srcMatrix.rows); - Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); - - T* src,* dest; - for (size_t i=0; i +Matrix random_sample(Matrix& srcMatrix, long size, bool remove = false) +{ + Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); + + T* src,* dest; + for (long i=0; i +Matrix random_sample(const Matrix& srcMatrix, size_t size) +{ + UniqueRandom rand((int)srcMatrix.rows); + Matrix newSet(new T[size * srcMatrix.cols], size,srcMatrix.cols); + + T* src,* dest; + for (size_t i=0; i -#include - -#include "general.h" -#include "nn_index.h" - -#ifdef FLANN_SIGNATURE_ -#undef FLANN_SIGNATURE_ -#endif -#define FLANN_SIGNATURE_ "FLANN_INDEX" - -namespace cvflann -{ - -template -struct Datatype {}; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_INT8; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_INT16; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_INT32; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_UINT8; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_UINT16; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_UINT32; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT32; } }; -template<> -struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT64; } }; - - -/** - * Structure representing the index header. - */ -struct IndexHeader -{ - char signature[16]; - char version[16]; - flann_datatype_t data_type; - flann_algorithm_t index_type; - size_t rows; - size_t cols; -}; - -/** - * Saves index header to stream - * - * @param stream - Stream to save to - * @param index - The index to save - */ -template -void save_header(FILE* stream, const NNIndex& index) -{ - IndexHeader header; - memset(header.signature, 0, sizeof(header.signature)); - strcpy(header.signature, FLANN_SIGNATURE_); - memset(header.version, 0, sizeof(header.version)); - strcpy(header.version, FLANN_VERSION_); - header.data_type = Datatype::type(); - header.index_type = index.getType(); - header.rows = index.size(); - header.cols = index.veclen(); - - std::fwrite(&header, sizeof(header),1,stream); -} - - -/** - * - * @param stream - Stream to load from - * @return Index header - */ -inline IndexHeader load_header(FILE* stream) -{ - IndexHeader header; - size_t read_size = fread(&header,sizeof(header),1,stream); - - if (read_size!=(size_t)1) { - FLANN_THROW(cv::Error::StsError, "Invalid index file, cannot read"); - } - - if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) { - FLANN_THROW(cv::Error::StsError, "Invalid index file, wrong signature"); - } - - return header; - -} - - -template -void save_value(FILE* stream, const T& value, size_t count = 1) -{ - fwrite(&value, sizeof(value),count, stream); -} - -template -void save_value(FILE* stream, const cvflann::Matrix& value) -{ - fwrite(&value, sizeof(value),1, stream); - fwrite(value.data, sizeof(T),value.rows*value.cols, stream); -} - -template -void save_value(FILE* stream, const std::vector& value) -{ - size_t size = value.size(); - fwrite(&size, sizeof(size_t), 1, stream); - fwrite(&value[0], sizeof(T), size, stream); -} - -template -void load_value(FILE* stream, T& value, size_t count = 1) -{ - size_t read_cnt = fread(&value, sizeof(value), count, stream); - if (read_cnt != count) { - FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); - } -} - -template -void load_value(FILE* stream, cvflann::Matrix& value) -{ - size_t read_cnt = fread(&value, sizeof(value), 1, stream); - if (read_cnt != 1) { - FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); - } - value.data = new T[value.rows*value.cols]; - read_cnt = fread(value.data, sizeof(T), value.rows*value.cols, stream); - if (read_cnt != (size_t)(value.rows*value.cols)) { - FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); - } -} - - -template -void load_value(FILE* stream, std::vector& value) -{ - size_t size; - size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); - if (read_cnt!=1) { - FLANN_THROW(cv::Error::StsError, "Cannot read from file"); - } - value.resize(size); - read_cnt = fread(&value[0], sizeof(T), size, stream); - if (read_cnt != size) { - FLANN_THROW(cv::Error::StsError, "Cannot read from file"); - } -} - -} - -//! @endcond - -#endif /* OPENCV_FLANN_SAVING_H_ */ +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE NNIndexGOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_SAVING_H_ +#define OPENCV_FLANN_SAVING_H_ + +//! @cond IGNORED + +#include +#include + +#include "general.h" +#include "nn_index.h" + +#ifdef FLANN_SIGNATURE_ +#undef FLANN_SIGNATURE_ +#endif +#define FLANN_SIGNATURE_ "FLANN_INDEX" + +namespace cvflann +{ + +template +struct Datatype {}; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_INT8; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_INT16; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_INT32; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_UINT8; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_UINT16; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_UINT32; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT32; } }; +template<> +struct Datatype { static flann_datatype_t type() { return FLANN_FLOAT64; } }; + + +/** + * Structure representing the index header. + */ +struct IndexHeader +{ + char signature[16]; + char version[16]; + flann_datatype_t data_type; + flann_algorithm_t index_type; + size_t rows; + size_t cols; +}; + +/** + * Saves index header to stream + * + * @param stream - Stream to save to + * @param index - The index to save + */ +template +void save_header(FILE* stream, const NNIndex& index) +{ + IndexHeader header; + memset(header.signature, 0, sizeof(header.signature)); + strcpy(header.signature, FLANN_SIGNATURE_); + memset(header.version, 0, sizeof(header.version)); + strcpy(header.version, FLANN_VERSION_); + header.data_type = Datatype::type(); + header.index_type = index.getType(); + header.rows = index.size(); + header.cols = index.veclen(); + + std::fwrite(&header, sizeof(header),1,stream); +} + + +/** + * + * @param stream - Stream to load from + * @return Index header + */ +inline IndexHeader load_header(FILE* stream) +{ + IndexHeader header; + size_t read_size = fread(&header,sizeof(header),1,stream); + + if (read_size!=(size_t)1) { + FLANN_THROW(cv::Error::StsError, "Invalid index file, cannot read"); + } + + if (strcmp(header.signature,FLANN_SIGNATURE_)!=0) { + FLANN_THROW(cv::Error::StsError, "Invalid index file, wrong signature"); + } + + return header; + +} + + +template +void save_value(FILE* stream, const T& value, size_t count = 1) +{ + fwrite(&value, sizeof(value),count, stream); +} + +template +void save_value(FILE* stream, const cvflann::Matrix& value) +{ + fwrite(&value, sizeof(value),1, stream); + fwrite(value.data, sizeof(T),value.rows*value.cols, stream); +} + +template +void save_value(FILE* stream, const std::vector& value) +{ + size_t size = value.size(); + fwrite(&size, sizeof(size_t), 1, stream); + fwrite(&value[0], sizeof(T), size, stream); +} + +template +void load_value(FILE* stream, T& value, size_t count = 1) +{ + size_t read_cnt = fread(&value, sizeof(value), count, stream); + if (read_cnt != count) { + FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); + } +} + +template +void load_value(FILE* stream, cvflann::Matrix& value) +{ + size_t read_cnt = fread(&value, sizeof(value), 1, stream); + if (read_cnt != 1) { + FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); + } + value.data = new T[value.rows*value.cols]; + read_cnt = fread(value.data, sizeof(T), value.rows*value.cols, stream); + if (read_cnt != (size_t)(value.rows*value.cols)) { + FLANN_THROW(cv::Error::StsParseError, "Cannot read from file"); + } +} + + +template +void load_value(FILE* stream, std::vector& value) +{ + size_t size; + size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); + if (read_cnt!=1) { + FLANN_THROW(cv::Error::StsError, "Cannot read from file"); + } + value.resize(size); + read_cnt = fread(&value[0], sizeof(T), size, stream); + if (read_cnt != size) { + FLANN_THROW(cv::Error::StsError, "Cannot read from file"); + } +} + +} + +//! @endcond + +#endif /* OPENCV_FLANN_SAVING_H_ */ diff --git a/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h b/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h index ea5a94b060..02970148b2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h +++ b/3rdParty/opencv-4.11.0/opencv2/flann/simplex_downhill.h @@ -1,190 +1,190 @@ -/*********************************************************************** - * Software License Agreement (BSD License) - * - * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. - * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. - * - * THE BSD LICENSE - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - *************************************************************************/ - -#ifndef OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ -#define OPENCV_FLANN_SIMPLEX_DOWNHILL_H_ - -//! @cond IGNORED - -namespace cvflann -{ - -/** - Adds val to array vals (and point to array points) and keeping the arrays sorted by vals. - */ -template -void addValue(int pos, float val, float* vals, T* point, T* points, int n) -{ - vals[pos] = val; - for (int i=0; i0 && vals[j] -float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL ) -{ - const int MAX_ITERATIONS = 10; - - CV_DbgAssert(n>0); - - T* p_o = new T[n]; - T* p_r = new T[n]; - T* p_e = new T[n]; - - int alpha = 1; - - int iterations = 0; - - bool ownVals = false; - if (vals == NULL) { - ownVals = true; - vals = new float[n+1]; - for (int i=0; i MAX_ITERATIONS) break; - - // compute average of simplex points (except the highest point) - for (int j=0; j=vals[0])&&(val_r=vals[n]) { - for (int i=0; i +void addValue(int pos, float val, float* vals, T* point, T* points, int n) +{ + vals[pos] = val; + for (int i=0; i0 && vals[j] +float optimizeSimplexDownhill(T* points, int n, F func, float* vals = NULL ) +{ + const int MAX_ITERATIONS = 10; + + CV_DbgAssert(n>0); + + T* p_o = new T[n]; + T* p_r = new T[n]; + T* p_e = new T[n]; + + int alpha = 1; + + int iterations = 0; + + bool ownVals = false; + if (vals == NULL) { + ownVals = true; + vals = new float[n+1]; + for (int i=0; i MAX_ITERATIONS) break; + + // compute average of simplex points (except the highest point) + for (int j=0; j=vals[0])&&(val_r=vals[n]) { + for (int i=0; i -#include "opencv2/core.hpp" -#include "opencv2/core/utility.hpp" - -namespace cvflann -{ - -/** - * A start-stop timer class. - * - * Can be used to time portions of code. - */ -class StartStopTimer -{ - int64 startTime; - -public: - /** - * Value of the timer. - */ - double value; - - - /** - * Constructor. - */ - StartStopTimer() - : startTime(0) - { - reset(); - } - - /** - * Starts the timer. - */ - void start() - { - startTime = cv::getTickCount(); - } - - /** - * Stops the timer and updates timer value. - */ - void stop() - { - int64 stopTime = cv::getTickCount(); - value += ( (double)stopTime - startTime) / cv::getTickFrequency(); - } - - /** - * Resets the timer value to 0. - */ - void reset() - { - value = 0; - } - -}; - -} - -//! @endcond - -#endif // FLANN_TIMER_H +/*********************************************************************** + * Software License Agreement (BSD License) + * + * Copyright 2008-2009 Marius Muja (mariusm@cs.ubc.ca). All rights reserved. + * Copyright 2008-2009 David G. Lowe (lowe@cs.ubc.ca). All rights reserved. + * + * THE BSD LICENSE + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + *************************************************************************/ + +#ifndef OPENCV_FLANN_TIMER_H +#define OPENCV_FLANN_TIMER_H + +//! @cond IGNORED + +#include +#include "opencv2/core.hpp" +#include "opencv2/core/utility.hpp" + +namespace cvflann +{ + +/** + * A start-stop timer class. + * + * Can be used to time portions of code. + */ +class StartStopTimer +{ + int64 startTime; + +public: + /** + * Value of the timer. + */ + double value; + + + /** + * Constructor. + */ + StartStopTimer() + : startTime(0) + { + reset(); + } + + /** + * Starts the timer. + */ + void start() + { + startTime = cv::getTickCount(); + } + + /** + * Stops the timer and updates timer value. + */ + void stop() + { + int64 stopTime = cv::getTickCount(); + value += ( (double)stopTime - startTime) / cv::getTickFrequency(); + } + + /** + * Resets the timer value to 0. + */ + void reset() + { + value = 0; + } + +}; + +} + +//! @endcond + +#endif // FLANN_TIMER_H diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi.hpp index fa36a92a38..2087641023 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_HPP -#define OPENCV_GAPI_HPP - -#include - -/** \defgroup gapi_ref G-API framework -@{ - @defgroup gapi_main_classes G-API Main Classes - @defgroup gapi_data_objects G-API Data Types - @{ - @defgroup gapi_meta_args G-API Metadata Descriptors - @} - @defgroup gapi_std_backends G-API Standard Backends - @defgroup gapi_compile_args G-API Graph Compilation Arguments - @defgroup gapi_serialization G-API Serialization functionality -@} - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Include these files here to avoid cyclic dependency between -// Desync & GKernel & GComputation & GStreamingCompiled. -#include -#include - -#endif // OPENCV_GAPI_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_HPP +#define OPENCV_GAPI_HPP + +#include + +/** \defgroup gapi_ref G-API framework +@{ + @defgroup gapi_main_classes G-API Main Classes + @defgroup gapi_data_objects G-API Data Types + @{ + @defgroup gapi_meta_args G-API Metadata Descriptors + @} + @defgroup gapi_std_backends G-API Standard Backends + @defgroup gapi_compile_args G-API Graph Compilation Arguments + @defgroup gapi_serialization G-API Serialization functionality +@} + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Include these files here to avoid cyclic dependency between +// Desync & GKernel & GComputation & GStreamingCompiled. +#include +#include + +#endif // OPENCV_GAPI_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp index 370e4ccf86..60bb2c5074 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/core.hpp @@ -1,1911 +1,1911 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_CORE_HPP -#define OPENCV_GAPI_CORE_HPP - -#include -#include // std::tuple - -#include -#include - -#include -#include -#include -#include - -/** \defgroup gapi_core G-API Core functionality -@{ - @defgroup gapi_math Graph API: Math operations - @defgroup gapi_pixelwise Graph API: Pixelwise operations - @defgroup gapi_matrixop Graph API: Operations on matrices - @defgroup gapi_transform Graph API: Image and channel composition functions -@} - */ - -namespace cv { namespace gapi { -/** - * @brief This namespace contains G-API Operation Types for OpenCV - * Core module functionality. - */ -namespace core { - using GResize = cv::gapi::imgproc::GResize; - using GResizeP = cv::gapi::imgproc::GResizeP; - - using GMat2 = std::tuple; - using GMat3 = std::tuple; // FIXME: how to avoid this? - using GMat4 = std::tuple; - using GMatScalar = std::tuple; - - G_TYPED_KERNEL(GAdd, , "org.opencv.core.math.add") { - static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { - if (ddepth == -1) - { - // OpenCV: When the input arrays in add/subtract/multiply/divide - // functions have different depths, the output array depth must be - // explicitly specified! - // See artim_op() @ arithm.cpp - GAPI_Assert(a.chan == b.chan); - GAPI_Assert(a.depth == b.depth); - return a; - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GAddC, , "org.opencv.core.math.addC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { - GAPI_Assert(a.chan <= 4); - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSub, , "org.opencv.core.math.sub") { - static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { - if (ddepth == -1) - { - // This macro should select a larger data depth from a and b - // considering the number of channels in the same - // FIXME!!! Clarify if it is valid for sub() - GAPI_Assert(a.chan == b.chan); - ddepth = std::max(a.depth, b.depth); - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSubC, , "org.opencv.core.math.subC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSubRC,, "org.opencv.core.math.subRC") { - static GMatDesc outMeta(GScalarDesc, GMatDesc b, int ddepth) { - return b.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMul, , "org.opencv.core.math.mul") { - static GMatDesc outMeta(GMatDesc a, GMatDesc, double, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMulCOld, , "org.opencv.core.math.mulCOld") { - static GMatDesc outMeta(GMatDesc a, double, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMulC, , "org.opencv.core.math.mulC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMulS, , "org.opencv.core.math.muls") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; // FIXME: Merge with MulC - - G_TYPED_KERNEL(GDiv, , "org.opencv.core.math.div") { - static GMatDesc outMeta(GMatDesc a, GMatDesc b, double, int ddepth) { - if (ddepth == -1) - { - GAPI_Assert(a.depth == b.depth); - return b; - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GDivC, , "org.opencv.core.math.divC") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc, double, int ddepth) { - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GDivRC, , "org.opencv.core.math.divRC") { - static GMatDesc outMeta(GScalarDesc, GMatDesc b, double, int ddepth) { - return b.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GMean, , "org.opencv.core.math.mean") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL_M(GPolarToCart, , "org.opencv.core.math.polarToCart") { - static std::tuple outMeta(GMatDesc, GMatDesc a, bool) { - return std::make_tuple(a, a); - } - }; - - G_TYPED_KERNEL_M(GCartToPolar, , "org.opencv.core.math.cartToPolar") { - static std::tuple outMeta(GMatDesc x, GMatDesc, bool) { - return std::make_tuple(x, x); - } - }; - - G_TYPED_KERNEL(GPhase, , "org.opencv.core.math.phase") { - static GMatDesc outMeta(const GMatDesc &inx, const GMatDesc &, bool) { - return inx; - } - }; - - G_TYPED_KERNEL(GMask, , "org.opencv.core.pixelwise.mask") { - static GMatDesc outMeta(GMatDesc in, GMatDesc) { - return in; - } - }; - - G_TYPED_KERNEL(GCmpGT, , "org.opencv.core.pixelwise.compare.cmpGT") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpGE, , "org.opencv.core.pixelwise.compare.cmpGE") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLE, , "org.opencv.core.pixelwise.compare.cmpLE") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLT, , "org.opencv.core.pixelwise.compare.cmpLT") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpEQ, , "org.opencv.core.pixelwise.compare.cmpEQ") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpNE, , "org.opencv.core.pixelwise.compare.cmpNE") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpGTScalar, , "org.opencv.core.pixelwise.compare.cmpGTScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpGEScalar, , "org.opencv.core.pixelwise.compare.cmpGEScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLEScalar, , "org.opencv.core.pixelwise.compare.cmpLEScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpLTScalar, , "org.opencv.core.pixelwise.compare.cmpLTScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpEQScalar, , "org.opencv.core.pixelwise.compare.cmpEQScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GCmpNEScalar, , "org.opencv.core.pixelwise.compare.cmpNEScalar") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a.withDepth(CV_8U); - } - }; - - G_TYPED_KERNEL(GAnd, , "org.opencv.core.pixelwise.bitwise_and") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GAndS, , "org.opencv.core.pixelwise.bitwise_andS") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GOr, , "org.opencv.core.pixelwise.bitwise_or") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GOrS, , "org.opencv.core.pixelwise.bitwise_orS") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GXor, , "org.opencv.core.pixelwise.bitwise_xor") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GXorS, , "org.opencv.core.pixelwise.bitwise_xorS") { - static GMatDesc outMeta(GMatDesc a, GScalarDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GNot, , "org.opencv.core.pixelwise.bitwise_not") { - static GMatDesc outMeta(GMatDesc a) { - return a; - } - }; - - G_TYPED_KERNEL(GSelect, , "org.opencv.core.pixelwise.select") { - static GMatDesc outMeta(GMatDesc a, GMatDesc, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GMin, , "org.opencv.core.matrixop.min") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GMax, , "org.opencv.core.matrixop.max") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GAbsDiff, , "org.opencv.core.matrixop.absdiff") { - static GMatDesc outMeta(GMatDesc a, GMatDesc) { - return a; - } - }; - - G_TYPED_KERNEL(GAbsDiffC, , "org.opencv.core.matrixop.absdiffC") { - static GMatDesc outMeta(const GMatDesc& a, const GScalarDesc&) { - return a; - } - }; - - G_TYPED_KERNEL(GSum, , "org.opencv.core.matrixop.sum") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL(GCountNonZero, (GMat)>, "org.opencv.core.matrixop.countNonZero") { - static GOpaqueDesc outMeta(GMatDesc in) { - GAPI_Assert(in.chan == 1); - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GAddW, , "org.opencv.core.matrixop.addweighted") { - static GMatDesc outMeta(GMatDesc a, double, GMatDesc b, double, double, int ddepth) { - if (ddepth == -1) - { - // OpenCV: When the input arrays in add/subtract/multiply/divide - // functions have different depths, the output array depth must be - // explicitly specified! - // See artim_op() @ arithm.cpp - GAPI_Assert(a.chan == b.chan); - GAPI_Assert(a.depth == b.depth); - return a; - } - return a.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GNormL1, , "org.opencv.core.matrixop.norml1") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL(GNormL2, , "org.opencv.core.matrixop.norml2") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL(GNormInf, , "org.opencv.core.matrixop.norminf") { - static GScalarDesc outMeta(GMatDesc) { - return empty_scalar_desc(); - } - }; - - G_TYPED_KERNEL_M(GIntegral, , "org.opencv.core.matrixop.integral") { - static std::tuple outMeta(GMatDesc in, int sd, int sqd) { - return std::make_tuple(in.withSizeDelta(1,1).withDepth(sd), - in.withSizeDelta(1,1).withDepth(sqd)); - } - }; - - G_TYPED_KERNEL(GThreshold, , "org.opencv.core.matrixop.threshold") { - static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc, int) { - return in; - } - }; - - - G_TYPED_KERNEL_M(GThresholdOT, , "org.opencv.core.matrixop.thresholdOT") { - static std::tuple outMeta(GMatDesc in, GScalarDesc, int) { - return std::make_tuple(in, empty_scalar_desc()); - } - }; - - G_TYPED_KERNEL(GInRange, , "org.opencv.core.matrixop.inrange") { - static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL_M(GSplit3, , "org.opencv.core.transform.split3") { - static std::tuple outMeta(GMatDesc in) { - const auto out_depth = in.depth; - const auto out_desc = in.withType(out_depth, 1); - return std::make_tuple(out_desc, out_desc, out_desc); - } - }; - - G_TYPED_KERNEL_M(GSplit4, ,"org.opencv.core.transform.split4") { - static std::tuple outMeta(GMatDesc in) { - const auto out_depth = in.depth; - const auto out_desc = in.withType(out_depth, 1); - return std::make_tuple(out_desc, out_desc, out_desc, out_desc); - } - }; - - G_TYPED_KERNEL(GMerge3, , "org.opencv.core.transform.merge3") { - static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc) { - // Preserve depth and add channel component - return in.withType(in.depth, 3); - } - }; - - G_TYPED_KERNEL(GMerge4, , "org.opencv.core.transform.merge4") { - static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc, GMatDesc) { - // Preserve depth and add channel component - return in.withType(in.depth, 4); - } - }; - - G_TYPED_KERNEL(GRemap, , "org.opencv.core.transform.remap") { - static GMatDesc outMeta(GMatDesc in, Mat m1, Mat, int, int, Scalar) { - return in.withSize(m1.size()); - } - }; - - G_TYPED_KERNEL(GFlip, , "org.opencv.core.transform.flip") { - static GMatDesc outMeta(GMatDesc in, int) { - return in; - } - }; - - // TODO: eliminate the need in this kernel (streaming) - G_TYPED_KERNEL(GCrop, , "org.opencv.core.transform.crop") { - static GMatDesc outMeta(GMatDesc in, Rect rc) { - return in.withSize(Size(rc.width, rc.height)); - } - }; - - G_TYPED_KERNEL(GConcatHor, , "org.opencv.imgproc.transform.concatHor") { - static GMatDesc outMeta(GMatDesc l, GMatDesc r) { - return l.withSizeDelta(+r.size.width, 0); - } - }; - - G_TYPED_KERNEL(GConcatVert, , "org.opencv.imgproc.transform.concatVert") { - static GMatDesc outMeta(GMatDesc t, GMatDesc b) { - return t.withSizeDelta(0, +b.size.height); - } - }; - - G_TYPED_KERNEL(GLUT, , "org.opencv.core.transform.LUT") { - static GMatDesc outMeta(GMatDesc in, Mat) { - return in; - } - }; - - G_TYPED_KERNEL(GConvertTo, , "org.opencv.core.transform.convertTo") { - static GMatDesc outMeta(GMatDesc in, int rdepth, double, double) { - return rdepth < 0 ? in : in.withDepth(rdepth); - } - }; - - G_TYPED_KERNEL(GSqrt, , "org.opencv.core.math.sqrt") { - static GMatDesc outMeta(GMatDesc in) { - return in; - } - }; - - G_TYPED_KERNEL(GNormalize, , "org.opencv.core.normalize") { - static GMatDesc outMeta(GMatDesc in, double, double, int, int ddepth) { - // unlike opencv doesn't have a mask as a parameter - return (ddepth < 0 ? in : in.withDepth(ddepth)); - } - }; - - G_TYPED_KERNEL(GWarpPerspective, , "org.opencv.core.warpPerspective") { - static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int borderMode, const cv::Scalar&) { - GAPI_Assert((borderMode == cv::BORDER_CONSTANT || borderMode == cv::BORDER_REPLICATE) && - "cv::gapi::warpPerspective supports only cv::BORDER_CONSTANT and cv::BORDER_REPLICATE border modes"); - return in.withType(in.depth, in.chan).withSize(dsize); - } - }; - - G_TYPED_KERNEL(GWarpAffine, , "org.opencv.core.warpAffine") { - static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int border_mode, const cv::Scalar&) { - GAPI_Assert(border_mode != cv::BORDER_TRANSPARENT && - "cv::BORDER_TRANSPARENT mode is not supported in cv::gapi::warpAffine"); - return in.withType(in.depth, in.chan).withSize(dsize); - } - }; - - G_TYPED_KERNEL( - GKMeansND, - ,GMat,GMat>(GMat,int,GMat,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeansND") { - - static std::tuple - outMeta(const GMatDesc& in, int K, const GMatDesc& bestLabels, const TermCriteria&, int, - KmeansFlags flags) { - GAPI_Assert(in.depth == CV_32F); - std::vector amount_n_dim = detail::checkVector(in); - int amount = amount_n_dim[0], dim = amount_n_dim[1]; - if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given - { // which means that kmeans will consider the following: - amount = in.size.height; - dim = in.size.width * in.chan; - } - // kmeans sets these labels' sizes when no bestLabels given: - GMatDesc out_labels(CV_32S, 1, Size{1, amount}); - // kmeans always sets these centers' sizes: - GMatDesc centers (CV_32F, 1, Size{dim, K}); - if (flags & KMEANS_USE_INITIAL_LABELS) - { - GAPI_Assert(bestLabels.depth == CV_32S); - int labels_amount = detail::checkVector(bestLabels, 1u); - GAPI_Assert(labels_amount == amount); - out_labels = bestLabels; // kmeans preserves bestLabels' sizes if given - } - return std::make_tuple(empty_gopaque_desc(), out_labels, centers); - } - }; - - G_TYPED_KERNEL( - GKMeansNDNoInit, - ,GMat,GMat>(GMat,int,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeansNDNoInit") { - - static std::tuple - outMeta(const GMatDesc& in, int K, const TermCriteria&, int, KmeansFlags flags) { - GAPI_Assert( !(flags & KMEANS_USE_INITIAL_LABELS) ); - GAPI_Assert(in.depth == CV_32F); - std::vector amount_n_dim = detail::checkVector(in); - int amount = amount_n_dim[0], dim = amount_n_dim[1]; - if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given - { // which means that kmeans will consider the following: - amount = in.size.height; - dim = in.size.width * in.chan; - } - GMatDesc out_labels(CV_32S, 1, Size{1, amount}); - GMatDesc centers (CV_32F, 1, Size{dim, K}); - return std::make_tuple(empty_gopaque_desc(), out_labels, centers); - } - }; - - G_TYPED_KERNEL(GKMeans2D, ,GArray,GArray> - (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeans2D") { - static std::tuple - outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { - return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GKMeans3D, ,GArray,GArray> - (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, - "org.opencv.core.kmeans3D") { - static std::tuple - outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { - return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GTranspose, , "org.opencv.core.transpose") { - static GMatDesc outMeta(GMatDesc in) { - return in.withSize({in.size.height, in.size.width}); - } - }; -} // namespace core - -namespace streaming { - -// Operations for Streaming (declared in this header for convenience) -G_TYPED_KERNEL(GSize, (GMat)>, "org.opencv.streaming.size") { - static GOpaqueDesc outMeta(const GMatDesc&) { - return empty_gopaque_desc(); - } -}; - -G_TYPED_KERNEL(GSizeR, (GOpaque)>, "org.opencv.streaming.sizeR") { - static GOpaqueDesc outMeta(const GOpaqueDesc&) { - return empty_gopaque_desc(); - } -}; - -G_TYPED_KERNEL(GSizeMF, (GFrame)>, "org.opencv.streaming.sizeMF") { - static GOpaqueDesc outMeta(const GFrameDesc&) { - return empty_gopaque_desc(); - } -}; -} // namespace streaming - -//! @addtogroup gapi_math -//! @{ - -/** @brief Calculates the per-element sum of two matrices. - -The function add calculates sum of two matrices of the same size and the same number of channels: -\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] - -The function can be replaced with matrix expressions: - \f[\texttt{dst} = \texttt{src1} + \texttt{src2}\f] - -The input matrices and the output matrix can all have the same or different depths. For example, you -can add a 16-bit unsigned matrix to a 8-bit signed matrix and store the sum as a 32-bit -floating-point matrix. Depth of the output matrix is determined by the ddepth parameter. -If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have -the same depth as the input matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.add" -@param src1 first input matrix. -@param src2 second input matrix. -@param ddepth optional depth of the output matrix. -@sa sub, addWeighted -*/ -GAPI_EXPORTS_W GMat add(const GMat& src1, const GMat& src2, int ddepth = -1); - -/** @brief Calculates the per-element sum of matrix and given scalar. - -The function addC adds a given scalar value to each element of given matrix. -The function can be replaced with matrix expressions: - - \f[\texttt{dst} = \texttt{src1} + \texttt{c}\f] - -Depth of the output matrix is determined by the ddepth parameter. -If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. -The matrices can be single or multi channel. Output matrix must have the same size and number of channels as the input matrix. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.addC" -@param src1 first input matrix. -@param c scalar value to be added. -@param ddepth optional depth of the output matrix. -@sa sub, addWeighted -*/ -GAPI_EXPORTS_W GMat addC(const GMat& src1, const GScalar& c, int ddepth = -1); -//! @overload -GAPI_EXPORTS_W GMat addC(const GScalar& c, const GMat& src1, int ddepth = -1); - -/** @brief Calculates the per-element difference between two matrices. - -The function sub calculates difference between two matrices, when both matrices have the same size and the same number of -channels: - \f[\texttt{dst}(I) = \texttt{src1}(I) - \texttt{src2}(I)\f] - -The function can be replaced with matrix expressions: -\f[\texttt{dst} = \texttt{src1} - \texttt{src2}\f] - -The input matrices and the output matrix can all have the same or different depths. For example, you -can subtract two 8-bit unsigned matrices store the result as a 16-bit signed matrix. -Depth of the output matrix is determined by the ddepth parameter. -If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have -the same depth as the input matrices. The matrices can be single or multi channel. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.sub" -@param src1 first input matrix. -@param src2 second input matrix. -@param ddepth optional depth of the output matrix. -@sa add, addC - */ -GAPI_EXPORTS_W GMat sub(const GMat& src1, const GMat& src2, int ddepth = -1); - -/** @brief Calculates the per-element difference between matrix and given scalar. - -The function can be replaced with matrix expressions: - \f[\texttt{dst} = \texttt{src} - \texttt{c}\f] - -Depth of the output matrix is determined by the ddepth parameter. -If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. -The matrices can be single or multi channel. Output matrix must have the same size as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.subC" -@param src first input matrix. -@param c scalar value to subtracted. -@param ddepth optional depth of the output matrix. -@sa add, addC, subRC - */ -GAPI_EXPORTS_W GMat subC(const GMat& src, const GScalar& c, int ddepth = -1); - -/** @brief Calculates the per-element difference between given scalar and the matrix. - -The function can be replaced with matrix expressions: - \f[\texttt{dst} = \texttt{c} - \texttt{src}\f] - -Depth of the output matrix is determined by the ddepth parameter. -If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. -The matrices can be single or multi channel. Output matrix must have the same size as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.subRC" -@param c scalar value to subtract from. -@param src input matrix to be subtracted. -@param ddepth optional depth of the output matrix. -@sa add, addC, subC - */ -GAPI_EXPORTS_W GMat subRC(const GScalar& c, const GMat& src, int ddepth = -1); - -/** @brief Calculates the per-element scaled product of two matrices. - -The function mul calculates the per-element product of two matrices: - -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] - -If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have -the same depth as the input matrices. The matrices can be single or multi channel. -Output matrix must have the same size as input matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.mul" -@param src1 first input matrix. -@param src2 second input matrix of the same size and the same depth as src1. -@param scale optional scale factor. -@param ddepth optional depth of the output matrix. -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat mul(const GMat& src1, const GMat& src2, double scale = 1.0, int ddepth = -1); - -/** @brief Multiplies matrix by scalar. - -The function mulC multiplies each element of matrix src by given scalar value: - -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I) \cdot \texttt{multiplier} )\f] - -The matrices can be single or multi channel. Output matrix must have the same size as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.mulC" -@param src input matrix. -@param multiplier factor to be multiplied. -@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat mulC(const GMat& src, double multiplier, int ddepth = -1); -//! @overload -GAPI_EXPORTS_W GMat mulC(const GMat& src, const GScalar& multiplier, int ddepth = -1); // FIXME: merge with mulc -//! @overload -GAPI_EXPORTS_W GMat mulC(const GScalar& multiplier, const GMat& src, int ddepth = -1); // FIXME: merge with mulc - -/** @brief Performs per-element division of two matrices. - -The function divides one matrix by another: -\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] - -For integer types when src2(I) is zero, dst(I) will also be zero. -Floating point case returns Inf/NaN (according to IEEE). - -Different channels of -multi-channel matrices are processed independently. -The matrices can be single or multi channel. Output matrix must have the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.div" -@param src1 first input matrix. -@param src2 second input matrix of the same size and depth as src1. -@param scale scalar factor. -@param ddepth optional depth of the output matrix; you can only pass -1 when src1.depth() == src2.depth(). -@sa mul, add, sub -*/ -GAPI_EXPORTS_W GMat div(const GMat& src1, const GMat& src2, double scale, int ddepth = -1); - -/** @brief Divides matrix by scalar. - -The function divC divides each element of matrix src by given scalar value: - -\f[\texttt{dst(I) = saturate(src(I)*scale/divisor)}\f] - -When divisor is zero, dst(I) will also be zero. Different channels of -multi-channel matrices are processed independently. -The matrices can be single or multi channel. Output matrix must have the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.divC" -@param src input matrix. -@param divisor number to be divided by. -@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. -@param scale scale factor. -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat divC(const GMat& src, const GScalar& divisor, double scale, int ddepth = -1); - -/** @brief Divides scalar by matrix. - -The function divRC divides given scalar by each element of matrix src and keep the division result in new matrix of the same size and type as src: - -\f[\texttt{dst(I) = saturate(divident*scale/src(I))}\f] - -When src(I) is zero, dst(I) will also be zero. Different channels of -multi-channel matrices are processed independently. -The matrices can be single or multi channel. Output matrix must have the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.divRC" -@param src input matrix. -@param divident number to be divided. -@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. -@param scale scale factor -@sa add, sub, div, addWeighted -*/ -GAPI_EXPORTS_W GMat divRC(const GScalar& divident, const GMat& src, double scale, int ddepth = -1); - -/** @brief Applies a mask to a matrix. - -The function mask set value from given matrix if the corresponding pixel value in mask matrix set to true, -and set the matrix value to 0 otherwise. - -Supported src matrix data types are @ref CV_8UC1, @ref CV_16SC1, @ref CV_16UC1. Supported mask data type is @ref CV_8UC1. - -@note Function textual ID is "org.opencv.core.math.mask" -@param src input matrix. -@param mask input mask matrix. -*/ -GAPI_EXPORTS_W GMat mask(const GMat& src, const GMat& mask); - -/** @brief Calculates an average (mean) of matrix elements. - -The function mean calculates the mean value M of matrix elements, -independently for each channel, and return it. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.math.mean" -@param src input matrix. -@sa countNonZero, min, max -*/ -GAPI_EXPORTS_W GScalar mean(const GMat& src); - -/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. - -The function polarToCart calculates the Cartesian coordinates of each 2D -vector represented by the corresponding elements of magnitude and angle: -\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] - -The relative accuracy of the estimated coordinates is about 1e-6. - -First output is a matrix of x-coordinates of 2D vectors. -Second output is a matrix of y-coordinates of 2D vectors. -Both output must have the same size and depth as input matrices. - -@note Function textual ID is "org.opencv.core.math.polarToCart" - -@param magnitude input floating-point @ref CV_32FC1 matrix (1xN) of magnitudes of 2D vectors; -@param angle input floating-point @ref CV_32FC1 matrix (1xN) of angles of 2D vectors. -@param angleInDegrees when true, the input angles are measured in -degrees, otherwise, they are measured in radians. -@sa cartToPolar, exp, log, pow, sqrt -*/ -GAPI_EXPORTS_W std::tuple polarToCart(const GMat& magnitude, const GMat& angle, - bool angleInDegrees = false); - -/** @brief Calculates the magnitude and angle of 2D vectors. - -The function cartToPolar calculates either the magnitude, angle, or both -for every 2D vector (x(I),y(I)): -\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] - -The angles are calculated with accuracy about 0.3 degrees. For the point -(0,0), the angle is set to 0. - -First output is a matrix of magnitudes of the same size and depth as input x. -Second output is a matrix of angles that has the same size and depth as -x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). - -@note Function textual ID is "org.opencv.core.math.cartToPolar" - -@param x matrix of @ref CV_32FC1 x-coordinates. -@param y array of @ref CV_32FC1 y-coordinates. -@param angleInDegrees a flag, indicating whether the angles are measured -in radians (which is by default), or in degrees. -@sa polarToCart -*/ -GAPI_EXPORTS_W std::tuple cartToPolar(const GMat& x, const GMat& y, - bool angleInDegrees = false); - -/** @brief Calculates the rotation angle of 2D vectors. - -The function cv::phase calculates the rotation angle of each 2D vector that -is formed from the corresponding elements of x and y : -\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] - -The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , -the corresponding angle(I) is set to 0. -@param x input floating-point array of x-coordinates of 2D vectors. -@param y input array of y-coordinates of 2D vectors; it must have the -same size and the same type as x. -@param angleInDegrees when true, the function calculates the angle in -degrees, otherwise, they are measured in radians. -@return array of vector angles; it has the same size and same type as x. -*/ -GAPI_EXPORTS_W GMat phase(const GMat& x, const GMat &y, bool angleInDegrees = false); - -/** @brief Calculates a square root of array elements. - -The function cv::gapi::sqrt calculates a square root of each input array element. -In case of multi-channel arrays, each channel is processed -independently. The accuracy is approximately the same as of the built-in -std::sqrt . -@param src input floating-point array. -@return output array of the same size and type as src. -*/ -GAPI_EXPORTS_W GMat sqrt(const GMat &src); - -//! @} gapi_math -//! -//! @addtogroup gapi_pixelwise -//! @{ - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater compare to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) > \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: -\f[\texttt{dst} = \texttt{src1} > \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices/matrix. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGT" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpLE, cmpGE, cmpLT -*/ -GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGTScalar" -*/ -GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less than elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) < \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} < \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices/matrix. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLT" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpLE, cmpGE, cmpGT -*/ -GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLTScalar" -*/ -GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater or equal compare to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) >= \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} >= \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGE" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpLE, cmpGT, cmpLT -*/ -GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLGEcalar" -*/ -GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less or equal compare to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) <= \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} <= \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLE" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpGT, cmpGE, cmpLT -*/ -GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLEScalar" -*/ -GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are equal to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) == \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} == \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQ" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpNE -*/ -GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQScalar" -*/ -GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GScalar& src2); - -/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are not equal to elements in second. - -The function compares elements of two matrices src1 and src2 of the same size: - \f[\texttt{dst} (I) = \texttt{src1} (I) != \texttt{src2} (I)\f] - -When the comparison result is true, the corresponding element of output -array is set to 255. The comparison operations can be replaced with the -equivalent matrix expressions: - \f[\texttt{dst} = \texttt{src1} != \texttt{src2}\f] - -Output matrix of depth @ref CV_8U must have the same size and the same number of channels as - the input matrices. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNE" -@param src1 first input matrix. -@param src2 second input matrix/scalar of the same depth as first input matrix. -@sa min, max, threshold, cmpEQ -*/ -GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNEScalar" -*/ -GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GScalar& src2); - -/** @brief computes bitwise conjunction of the two matrixes (src1 & src2) -Calculates the per-element bit-wise logical conjunction of two matrices of the same size. - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_and" - -@param src1 first input matrix. -@param src2 second input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_andS" -@param src1 first input matrix. -@param src2 scalar, which will be per-lemenetly conjuncted with elements of src1. -*/ -GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GScalar& src2); - -/** @brief computes bitwise disjunction of the two matrixes (src1 | src2) -Calculates the per-element bit-wise logical disjunction of two matrices of the same size. - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_or" - -@param src1 first input matrix. -@param src2 second input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_orS" -@param src1 first input matrix. -@param src2 scalar, which will be per-lemenetly disjuncted with elements of src1. -*/ -GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GScalar& src2); - - -/** @brief computes bitwise logical "exclusive or" of the two matrixes (src1 ^ src2) -Calculates the per-element bit-wise logical "exclusive or" of two matrices of the same size. - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xor" - -@param src1 first input matrix. -@param src2 second input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GMat& src2); -/** @overload -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xorS" -@param src1 first input matrix. -@param src2 scalar, for which per-lemenet "logical or" operation on elements of src1 will be performed. -*/ -GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GScalar& src2); - - -/** @brief Inverts every bit of an array. - -The function bitwise_not calculates per-element bit-wise inversion of the input -matrix: -\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] - -In case of floating-point matrices, their machine-specific bit -representations (usually IEEE754-compliant) are used for the operation. -In case of multi-channel matrices, each channel is processed -independently. Output matrix must have the same size and depth as the input -matrix. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.bitwise_not" - -@param src input matrix. -*/ -GAPI_EXPORTS_W GMat bitwise_not(const GMat& src); - -/** @brief Select values from either first or second of input matrices by given mask. -The function set to the output matrix either the value from the first input matrix if corresponding value of mask matrix is 255, - or value from the second input matrix (if value of mask matrix set to 0). - -Input mask matrix must be of @ref CV_8UC1 type, two other inout matrices and output matrix should be of the same type. The size should -be the same for all input and output matrices. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.pixelwise.select" - -@param src1 first input matrix. -@param src2 second input matrix. -@param mask mask input matrix. -*/ -GAPI_EXPORTS_W GMat select(const GMat& src1, const GMat& src2, const GMat& mask); - -//! @} gapi_pixelwise - - -//! @addtogroup gapi_matrixop -//! @{ -/** @brief Calculates per-element minimum of two matrices. - -The function min calculates the per-element minimum of two matrices of the same size, number of channels and depth: -\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] - where I is a multi-dimensional index of matrix elements. In case of - multi-channel matrices, each channel is processed independently. -Output matrix must be of the same size and depth as src1. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.min" -@param src1 first input matrix. -@param src2 second input matrix of the same size and depth as src1. -@sa max, cmpEQ, cmpLT, cmpLE -*/ -GAPI_EXPORTS_W GMat min(const GMat& src1, const GMat& src2); - -/** @brief Calculates per-element maximum of two matrices. - -The function max calculates the per-element maximum of two matrices of the same size, number of channels and depth: -\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] - where I is a multi-dimensional index of matrix elements. In case of - multi-channel matrices, each channel is processed independently. -Output matrix must be of the same size and depth as src1. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.max" -@param src1 first input matrix. -@param src2 second input matrix of the same size and depth as src1. -@sa min, compare, cmpEQ, cmpGT, cmpGE -*/ -GAPI_EXPORTS_W GMat max(const GMat& src1, const GMat& src2); - -/** @brief Calculates the per-element absolute difference between two matrices. - -The function absDiff calculates absolute difference between two matrices of the same size and depth: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] - where I is a multi-dimensional index of matrix elements. In case of - multi-channel matrices, each channel is processed independently. -Output matrix must have the same size and depth as input matrices. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.absdiff" -@param src1 first input matrix. -@param src2 second input matrix. -@sa abs -*/ -GAPI_EXPORTS_W GMat absDiff(const GMat& src1, const GMat& src2); - -/** @brief Calculates absolute value of matrix elements. - -The function abs calculates absolute difference between matrix elements and given scalar value: - \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{matC}(I)|)\f] - where matC is constructed from given scalar c and has the same sizes and depth as input matrix src. - -Output matrix must be of the same size and depth as src. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.absdiffC" -@param src input matrix. -@param c scalar to be subtracted. -@sa min, max -*/ -GAPI_EXPORTS_W GMat absDiffC(const GMat& src, const GScalar& c); - -/** @brief Calculates sum of all matrix elements. - -The function sum calculates sum of all matrix elements, independently for each channel. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.sum" -@param src input matrix. -@sa countNonZero, mean, min, max -*/ -GAPI_EXPORTS_W GScalar sum(const GMat& src); - -/** @brief Counts non-zero array elements. - -The function returns the number of non-zero elements in src : -\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] - -Supported matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.countNonZero" -@param src input single-channel matrix. -@sa mean, min, max -*/ -GAPI_EXPORTS_W GOpaque countNonZero(const GMat& src); - -/** @brief Calculates the weighted sum of two matrices. - -The function addWeighted calculates the weighted sum of two matrices as follows: -\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] -where I is a multi-dimensional index of array elements. In case of multi-channel matrices, each -channel is processed independently. - -The function can be replaced with a matrix expression: - \f[\texttt{dst}(I) = \texttt{alpha} * \texttt{src1}(I) - \texttt{beta} * \texttt{src2}(I) + \texttt{gamma} \f] - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.addweighted" -@param src1 first input matrix. -@param alpha weight of the first matrix elements. -@param src2 second input matrix of the same size and channel number as src1. -@param beta weight of the second matrix elements. -@param gamma scalar added to each sum. -@param ddepth optional depth of the output matrix. -@sa add, sub -*/ -GAPI_EXPORTS_W GMat addWeighted(const GMat& src1, double alpha, const GMat& src2, double beta, double gamma, int ddepth = -1); - -/** @brief Calculates the absolute L1 norm of a matrix. - -This version of normL1 calculates the absolute L1 norm of src. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{1} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ -\f} - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.norml1" -@param src input matrix. -@sa normL2, normInf -*/ -GAPI_EXPORTS_W GScalar normL1(const GMat& src); - -/** @brief Calculates the absolute L2 norm of a matrix. - -This version of normL2 calculates the absolute L2 norm of src. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{2} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ -\f} - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -@note Function textual ID is "org.opencv.core.matrixop.norml2" -@param src input matrix. -@sa normL1, normInf -*/ -GAPI_EXPORTS_W GScalar normL2(const GMat& src); - -/** @brief Calculates the absolute infinite norm of a matrix. - -This version of normInf calculates the absolute infinite norm of src. - -As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. -The \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ -is calculated as follows -\f{align*} - \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 -\f} -and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is -\f{align*} - \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. -\f} - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.core.matrixop.norminf" -@param src input matrix. -@sa normL1, normL2 -*/ -GAPI_EXPORTS_W GScalar normInf(const GMat& src); - -/** @brief Calculates the integral of an image. - -The function calculates one or more integral images for the source image as follows: - -\f[\texttt{sum} (X,Y) = \sum _{x integral(const GMat& src, int sdepth = -1, int sqdepth = -1); - -/** @brief Applies a fixed-level threshold to each matrix element. - -The function applies fixed-level thresholding to a single- or multiple-channel matrix. -The function is typically used to get a bi-level (binary) image out of a grayscale image ( cmp functions could be also used for -this purpose) or for removing a noise, that is, filtering out pixels with too small or too large -values. There are several types of thresholding supported by the function. They are determined by -type parameter. - -Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the -above values. In these cases, the function determines the optimal threshold value using the Otsu's -or Triangle algorithm and uses it instead of the specified thresh . The function returns the -computed threshold value in addititon to thresholded matrix. -The Otsu's and Triangle methods are implemented only for 8-bit matrices. - -Input image should be single channel only in case of cv::THRESH_OTSU or cv::THRESH_TRIANGLE flags. -Output matrix must be of the same size and depth as src. - -@note Function textual ID is "org.opencv.core.matrixop.threshold" - -@param src input matrix (@ref CV_8UC1, @ref CV_8UC3, or @ref CV_32FC1). -@param thresh threshold value. -@param maxval maximum value to use with the cv::THRESH_BINARY and cv::THRESH_BINARY_INV thresholding -types. -@param type thresholding type (see the cv::ThresholdTypes). - -@sa min, max, cmpGT, cmpLE, cmpGE, cmpLT - */ -GAPI_EXPORTS_W GMat threshold(const GMat& src, const GScalar& thresh, const GScalar& maxval, int type); -/** @overload -This function applicable for all threshold types except cv::THRESH_OTSU and cv::THRESH_TRIANGLE -@note Function textual ID is "org.opencv.core.matrixop.thresholdOT" -*/ -GAPI_EXPORTS_W std::tuple threshold(const GMat& src, const GScalar& maxval, int type); - -/** @brief Applies a range-level threshold to each matrix element. - -The function applies range-level thresholding to a single- or multiple-channel matrix. -It sets output pixel value to OxFF if the corresponding pixel value of input matrix is in specified range,or 0 otherwise. - -Input and output matrices must be CV_8UC1. - -@note Function textual ID is "org.opencv.core.matrixop.inRange" - -@param src input matrix (CV_8UC1). -@param threshLow lower boundary value. -@param threshUp upper boundary value. - -@sa threshold - */ -GAPI_EXPORTS_W GMat inRange(const GMat& src, const GScalar& threshLow, const GScalar& threshUp); - -//! @} gapi_matrixop - -//! @addtogroup gapi_transform -//! @{ -/** @brief Creates one 4-channel matrix out of 4 single-channel ones. - -The function merges several matrices to make a single multi-channel matrix. That is, each -element of the output matrix will be a concatenation of the elements of the input matrices, where -elements of i-th input matrix are treated as mv[i].channels()-element vectors. -Output matrix must be of @ref CV_8UC4 type. - -The function split4 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.merge4" - -@param src1 first input @ref CV_8UC1 matrix to be merged. -@param src2 second input @ref CV_8UC1 matrix to be merged. -@param src3 third input @ref CV_8UC1 matrix to be merged. -@param src4 fourth input @ref CV_8UC1 matrix to be merged. -@sa merge3, split4, split3 -*/ -GAPI_EXPORTS_W GMat merge4(const GMat& src1, const GMat& src2, const GMat& src3, const GMat& src4); - -/** @brief Creates one 3-channel matrix out of 3 single-channel ones. - -The function merges several matrices to make a single multi-channel matrix. That is, each -element of the output matrix will be a concatenation of the elements of the input matrices, where -elements of i-th input matrix are treated as mv[i].channels()-element vectors. -Output matrix must be of @ref CV_8UC3 type. - -The function split3 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.merge3" - -@param src1 first input @ref CV_8UC1 matrix to be merged. -@param src2 second input @ref CV_8UC1 matrix to be merged. -@param src3 third input @ref CV_8UC1 matrix to be merged. -@sa merge4, split4, split3 -*/ -GAPI_EXPORTS_W GMat merge3(const GMat& src1, const GMat& src2, const GMat& src3); - -/** @brief Divides a 4-channel matrix into 4 single-channel matrices. - -The function splits a 4-channel matrix into 4 single-channel matrices: -\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] - -All output matrices must be of @ref CV_8UC1 type. - -The function merge4 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.split4" - -@param src input @ref CV_8UC4 matrix. -@sa split3, merge3, merge4 -*/ -GAPI_EXPORTS_W std::tuple split4(const GMat& src); - -/** @brief Divides a 3-channel matrix into 3 single-channel matrices. - -The function splits a 3-channel matrix into 3 single-channel matrices: -\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] - -All output matrices must be of @ref CV_8UC1 type. - -The function merge3 does the reverse operation. - -@note - - Function textual ID is "org.opencv.core.transform.split3" - -@param src input @ref CV_8UC3 matrix. -@sa split4, merge3, merge4 -*/ -GAPI_EXPORTS_W std::tuple split3(const GMat& src); - -/** @brief Applies a generic geometrical transformation to an image. - -The function remap transforms the source image using the specified map: - -\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] - -where values of pixels with non-integer coordinates are computed using one of available -interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps -in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in -\f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to -convert from floating to fixed-point representations of a map is that they can yield much faster -(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), -cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. -Output image must be of the same size and depth as input one. - -@note - - Function textual ID is "org.opencv.core.transform.remap" - - Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - -@param src Source image. -@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2, -CV_32FC1, or CV_32FC2. -@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map -if map1 is (x,y) points), respectively. -@param interpolation Interpolation method (see cv::InterpolationFlags). The methods #INTER_AREA -and #INTER_LINEAR_EXACT are not supported by this function. -@param borderMode Pixel extrapolation method (see cv::BorderTypes). When -borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that -corresponds to the "outliers" in the source image are not modified by the function. -@param borderValue Value used in case of a constant border. By default, it is 0. - */ -GAPI_EXPORTS_W GMat remap(const GMat& src, const Mat& map1, const Mat& map2, - int interpolation, int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @brief Flips a 2D matrix around vertical, horizontal, or both axes. - -The function flips the matrix in one of three different ways (row -and column indices are 0-based): -\f[\texttt{dst} _{ij} = -\left\{ -\begin{array}{l l} -\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ -\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ -\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ -\end{array} -\right.\f] -The example scenarios of using the function are the following: -* Vertical flipping of the image (flipCode == 0) to switch between - top-left and bottom-left image origin. This is a typical operation - in video processing on Microsoft Windows\* OS. -* Horizontal flipping of the image with the subsequent horizontal - shift and absolute difference calculation to check for a - vertical-axis symmetry (flipCode \> 0). -* Simultaneous horizontal and vertical flipping of the image with - the subsequent shift and absolute difference calculation to check - for a central symmetry (flipCode \< 0). -* Reversing the order of point arrays (flipCode \> 0 or - flipCode == 0). -Output image must be of the same depth as input one, size should be correct for given flipCode. - -@note Function textual ID is "org.opencv.core.transform.flip" - -@param src input matrix. -@param flipCode a flag to specify how to flip the array; 0 means -flipping around the x-axis and positive value (for example, 1) means -flipping around y-axis. Negative value (for example, -1) means flipping -around both axes. -@sa remap -*/ -GAPI_EXPORTS_W GMat flip(const GMat& src, int flipCode); - -/** @brief Crops a 2D matrix. - -The function crops the matrix by given cv::Rect. - -Output matrix must be of the same depth as input one, size is specified by given rect size. - -@note Function textual ID is "org.opencv.core.transform.crop" - -@param src input matrix. -@param rect a rect to crop a matrix to -@sa resize -*/ -GAPI_EXPORTS_W GMat crop(const GMat& src, const Rect& rect); - -/** @brief Applies horizontal concatenation to given matrices. - -The function horizontally concatenates two GMat matrices (with the same number of rows). -@code{.cpp} - GMat A = { 1, 4, - 2, 5, - 3, 6 }; - GMat B = { 7, 10, - 8, 11, - 9, 12 }; - - GMat C = gapi::concatHor(A, B); - //C: - //[1, 4, 7, 10; - // 2, 5, 8, 11; - // 3, 6, 9, 12] -@endcode -Output matrix must the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.imgproc.transform.concatHor" - -@param src1 first input matrix to be considered for horizontal concatenation. -@param src2 second input matrix to be considered for horizontal concatenation. -@sa concatVert -*/ -GAPI_EXPORTS_W GMat concatHor(const GMat& src1, const GMat& src2); - -/** @overload -The function horizontally concatenates given number of GMat matrices (with the same number of columns). -Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. - -@param v vector of input matrices to be concatenated horizontally. -*/ -GAPI_EXPORTS_W GMat concatHor(const std::vector &v); - -/** @brief Applies vertical concatenation to given matrices. - -The function vertically concatenates two GMat matrices (with the same number of cols). - @code{.cpp} - GMat A = { 1, 7, - 2, 8, - 3, 9 }; - GMat B = { 4, 10, - 5, 11, - 6, 12 }; - - GMat C = gapi::concatVert(A, B); - //C: - //[1, 7; - // 2, 8; - // 3, 9; - // 4, 10; - // 5, 11; - // 6, 12] - @endcode - -Output matrix must the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. - -@note Function textual ID is "org.opencv.imgproc.transform.concatVert" - -@param src1 first input matrix to be considered for vertical concatenation. -@param src2 second input matrix to be considered for vertical concatenation. -@sa concatHor -*/ -GAPI_EXPORTS_W GMat concatVert(const GMat& src1, const GMat& src2); - -/** @overload -The function vertically concatenates given number of GMat matrices (with the same number of columns). -Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. - -@param v vector of input matrices to be concatenated vertically. -*/ -GAPI_EXPORTS_W GMat concatVert(const std::vector &v); - - -/** @brief Performs a look-up table transform of a matrix. - -The function LUT fills the output matrix with values from the look-up table. Indices of the entries -are taken from the input matrix. That is, the function processes each element of src as follows: -\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I))}\f] - -Supported matrix data types are @ref CV_8UC1. -Output is a matrix of the same size and number of channels as src, and the same depth as lut. - -@note Function textual ID is "org.opencv.core.transform.LUT" - -@param src input matrix of 8-bit elements. -@param lut look-up table of 256 elements; in case of multi-channel input array, the table should -either have a single channel (in this case the same table is used for all channels) or the same -number of channels as in the input matrix. -*/ -GAPI_EXPORTS_W GMat LUT(const GMat& src, const Mat& lut); - -/** @brief Converts a matrix to another data depth with optional scaling. - -The method converts source pixel values to the target data depth. saturate_cast\<\> is applied at -the end to avoid possible overflows: - -\f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] -Output matrix must be of the same size as input one. - -@note Function textual ID is "org.opencv.core.transform.convertTo" -@param src input matrix to be converted from. -@param rdepth desired output matrix depth or, rather, the depth since the number of channels are the -same as the input has; if rdepth is negative, the output matrix will have the same depth as the input. -@param alpha optional scale factor. -@param beta optional delta added to the scaled values. - */ -GAPI_EXPORTS_W GMat convertTo(const GMat& src, int rdepth, double alpha=1, double beta=0); - -/** @brief Normalizes the norm or value range of an array. - -The function normalizes scale and shift the input array elements so that -\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] -(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that -\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] -when normType=NORM_MINMAX (for dense arrays only). - -@note Function textual ID is "org.opencv.core.normalize" - -@param src input array. -@param alpha norm value to normalize to or the lower range boundary in case of the range -normalization. -@param beta upper range boundary in case of the range normalization; it is not used for the norm -normalization. -@param norm_type normalization type (see cv::NormTypes). -@param ddepth when negative, the output array has the same type as src; otherwise, it has the same -number of channels as src and the depth =ddepth. -@sa norm, Mat::convertTo -*/ -GAPI_EXPORTS_W GMat normalize(const GMat& src, double alpha, double beta, - int norm_type, int ddepth = -1); - -/** @brief Applies a perspective transformation to an image. - -The function warpPerspective transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert -and then put in the formula above instead of M. The function cannot operate in-place. - -@param src input image. -@param M \f$3\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the -optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). -@param borderValue value used in case of a constant border; by default, it equals 0. - -@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform - */ -GAPI_EXPORTS_W GMat warpPerspective(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, - int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); - -/** @brief Applies an affine transformation to an image. - -The function warpAffine transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted -with #invertAffineTransform and then put in the formula above instead of M. The function cannot -operate in-place. - -@param src input image. -@param M \f$2\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (see #InterpolationFlags) and the optional -flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (see #BorderTypes); -borderMode=#BORDER_TRANSPARENT isn't supported -@param borderValue value used in case of a constant border; by default, it is 0. - -@sa warpPerspective, resize, remap, getRectSubPix, transform - */ -GAPI_EXPORTS_W GMat warpAffine(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, - int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); -//! @} gapi_transform - -/** @brief Finds centers of clusters and groups input samples around the clusters. - -The function kmeans implements a k-means algorithm that finds the centers of K clusters -and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ -contains a 0-based cluster index for the \f$i^{th}\f$ sample. - -@note - - Function textual ID is "org.opencv.core.kmeansND" - - In case of an N-dimentional points' set given, input GMat can have the following traits: -2 dimensions, a single row or column if there are N channels, -or N columns if there is a single channel. Mat should have @ref CV_32F depth. - - Although, if GMat with height != 1, width != 1, channels != 1 given as data, n-dimensional -samples are considered given in amount of A, where A = height, n = width * channels. - - In case of GMat given as data: - - the output labels are returned as 1-channel GMat with sizes -width = 1, height = A, where A is samples amount, or width = bestLabels.width, -height = bestLabels.height if bestLabels given; - - the cluster centers are returned as 1-channel GMat with sizes -width = n, height = K, where n is samples' dimentionality and K is clusters' amount. - - As one of possible usages, if you want to control the initial labels for each attempt -by yourself, you can utilize just the core of the function. To do that, set the number -of attempts to 1, initialize labels each time using a custom algorithm, pass them with the -( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. - -@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. -Function can take GArray, GArray for 2D and 3D cases or GMat for any -dimentionality and channels. -@param K Number of clusters to split the set by. -@param bestLabels Optional input integer array that can store the supposed initial cluster indices -for every sample. Used when ( flags = #KMEANS_USE_INITIAL_LABELS ) flag is set. -@param criteria The algorithm termination criteria, that is, the maximum number of iterations -and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of -the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops. -@param attempts Flag to specify the number of times the algorithm is executed using different -initial labellings. The algorithm returns the labels that yield the best compactness (see the first -function return value). -@param flags Flag that can take values of cv::KmeansFlags . - -@return - - Compactness measure that is computed as -\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] -after every attempt. The best (minimum) value is chosen and the corresponding labels and the -compactness value are returned by the function. - - Integer array that stores the cluster indices for every sample. - - Array of the cluster centers. -*/ -GAPI_EXPORTS_W std::tuple,GMat,GMat> -kmeans(const GMat& data, const int K, const GMat& bestLabels, - const TermCriteria& criteria, const int attempts, const KmeansFlags flags); - -/** @overload -@note - - Function textual ID is "org.opencv.core.kmeansNDNoInit" - - #KMEANS_USE_INITIAL_LABELS flag must not be set while using this overload. - */ -GAPI_EXPORTS_W std::tuple,GMat,GMat> -kmeans(const GMat& data, const int K, const TermCriteria& criteria, const int attempts, - const KmeansFlags flags); - -/** @overload -@note Function textual ID is "org.opencv.core.kmeans2D" - */ -GAPI_EXPORTS_W std::tuple,GArray,GArray> -kmeans(const GArray& data, const int K, const GArray& bestLabels, - const TermCriteria& criteria, const int attempts, const KmeansFlags flags); - -/** @overload -@note Function textual ID is "org.opencv.core.kmeans3D" - */ -GAPI_EXPORTS_W std::tuple,GArray,GArray> -kmeans(const GArray& data, const int K, const GArray& bestLabels, - const TermCriteria& criteria, const int attempts, const KmeansFlags flags); - - -/** @brief Transposes a matrix. - -The function transposes the matrix: -\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] - -@note - - Function textual ID is "org.opencv.core.transpose" - - No complex conjugation is done in case of a complex matrix. It should be done separately if needed. - -@param src input array. -*/ -GAPI_EXPORTS_W GMat transpose(const GMat& src); - - -namespace streaming { -/** @brief Gets dimensions from Mat. - -@note Function textual ID is "org.opencv.streaming.size" - -@param src Input tensor -@return Size (tensor dimensions). -*/ -GAPI_EXPORTS_W GOpaque size(const GMat& src); - -/** @overload -Gets dimensions from rectangle. - -@note Function textual ID is "org.opencv.streaming.sizeR" - -@param r Input rectangle. -@return Size (rectangle dimensions). -*/ -GAPI_EXPORTS_W GOpaque size(const GOpaque& r); - -/** @brief Gets dimensions from MediaFrame. - -@note Function textual ID is "org.opencv.streaming.sizeMF" - -@param src Input frame -@return Size (frame dimensions). -*/ -GAPI_EXPORTS_W GOpaque size(const GFrame& src); -} //namespace streaming -} //namespace gapi -} //namespace cv - -#endif //OPENCV_GAPI_CORE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_CORE_HPP +#define OPENCV_GAPI_CORE_HPP + +#include +#include // std::tuple + +#include +#include + +#include +#include +#include +#include + +/** \defgroup gapi_core G-API Core functionality +@{ + @defgroup gapi_math Graph API: Math operations + @defgroup gapi_pixelwise Graph API: Pixelwise operations + @defgroup gapi_matrixop Graph API: Operations on matrices + @defgroup gapi_transform Graph API: Image and channel composition functions +@} + */ + +namespace cv { namespace gapi { +/** + * @brief This namespace contains G-API Operation Types for OpenCV + * Core module functionality. + */ +namespace core { + using GResize = cv::gapi::imgproc::GResize; + using GResizeP = cv::gapi::imgproc::GResizeP; + + using GMat2 = std::tuple; + using GMat3 = std::tuple; // FIXME: how to avoid this? + using GMat4 = std::tuple; + using GMatScalar = std::tuple; + + G_TYPED_KERNEL(GAdd, , "org.opencv.core.math.add") { + static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { + if (ddepth == -1) + { + // OpenCV: When the input arrays in add/subtract/multiply/divide + // functions have different depths, the output array depth must be + // explicitly specified! + // See artim_op() @ arithm.cpp + GAPI_Assert(a.chan == b.chan); + GAPI_Assert(a.depth == b.depth); + return a; + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GAddC, , "org.opencv.core.math.addC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { + GAPI_Assert(a.chan <= 4); + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSub, , "org.opencv.core.math.sub") { + static GMatDesc outMeta(GMatDesc a, GMatDesc b, int ddepth) { + if (ddepth == -1) + { + // This macro should select a larger data depth from a and b + // considering the number of channels in the same + // FIXME!!! Clarify if it is valid for sub() + GAPI_Assert(a.chan == b.chan); + ddepth = std::max(a.depth, b.depth); + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSubC, , "org.opencv.core.math.subC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSubRC,, "org.opencv.core.math.subRC") { + static GMatDesc outMeta(GScalarDesc, GMatDesc b, int ddepth) { + return b.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMul, , "org.opencv.core.math.mul") { + static GMatDesc outMeta(GMatDesc a, GMatDesc, double, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMulCOld, , "org.opencv.core.math.mulCOld") { + static GMatDesc outMeta(GMatDesc a, double, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMulC, , "org.opencv.core.math.mulC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMulS, , "org.opencv.core.math.muls") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; // FIXME: Merge with MulC + + G_TYPED_KERNEL(GDiv, , "org.opencv.core.math.div") { + static GMatDesc outMeta(GMatDesc a, GMatDesc b, double, int ddepth) { + if (ddepth == -1) + { + GAPI_Assert(a.depth == b.depth); + return b; + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GDivC, , "org.opencv.core.math.divC") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc, double, int ddepth) { + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GDivRC, , "org.opencv.core.math.divRC") { + static GMatDesc outMeta(GScalarDesc, GMatDesc b, double, int ddepth) { + return b.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GMean, , "org.opencv.core.math.mean") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL_M(GPolarToCart, , "org.opencv.core.math.polarToCart") { + static std::tuple outMeta(GMatDesc, GMatDesc a, bool) { + return std::make_tuple(a, a); + } + }; + + G_TYPED_KERNEL_M(GCartToPolar, , "org.opencv.core.math.cartToPolar") { + static std::tuple outMeta(GMatDesc x, GMatDesc, bool) { + return std::make_tuple(x, x); + } + }; + + G_TYPED_KERNEL(GPhase, , "org.opencv.core.math.phase") { + static GMatDesc outMeta(const GMatDesc &inx, const GMatDesc &, bool) { + return inx; + } + }; + + G_TYPED_KERNEL(GMask, , "org.opencv.core.pixelwise.mask") { + static GMatDesc outMeta(GMatDesc in, GMatDesc) { + return in; + } + }; + + G_TYPED_KERNEL(GCmpGT, , "org.opencv.core.pixelwise.compare.cmpGT") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpGE, , "org.opencv.core.pixelwise.compare.cmpGE") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLE, , "org.opencv.core.pixelwise.compare.cmpLE") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLT, , "org.opencv.core.pixelwise.compare.cmpLT") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpEQ, , "org.opencv.core.pixelwise.compare.cmpEQ") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpNE, , "org.opencv.core.pixelwise.compare.cmpNE") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpGTScalar, , "org.opencv.core.pixelwise.compare.cmpGTScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpGEScalar, , "org.opencv.core.pixelwise.compare.cmpGEScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLEScalar, , "org.opencv.core.pixelwise.compare.cmpLEScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpLTScalar, , "org.opencv.core.pixelwise.compare.cmpLTScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpEQScalar, , "org.opencv.core.pixelwise.compare.cmpEQScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GCmpNEScalar, , "org.opencv.core.pixelwise.compare.cmpNEScalar") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a.withDepth(CV_8U); + } + }; + + G_TYPED_KERNEL(GAnd, , "org.opencv.core.pixelwise.bitwise_and") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GAndS, , "org.opencv.core.pixelwise.bitwise_andS") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GOr, , "org.opencv.core.pixelwise.bitwise_or") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GOrS, , "org.opencv.core.pixelwise.bitwise_orS") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GXor, , "org.opencv.core.pixelwise.bitwise_xor") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GXorS, , "org.opencv.core.pixelwise.bitwise_xorS") { + static GMatDesc outMeta(GMatDesc a, GScalarDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GNot, , "org.opencv.core.pixelwise.bitwise_not") { + static GMatDesc outMeta(GMatDesc a) { + return a; + } + }; + + G_TYPED_KERNEL(GSelect, , "org.opencv.core.pixelwise.select") { + static GMatDesc outMeta(GMatDesc a, GMatDesc, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GMin, , "org.opencv.core.matrixop.min") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GMax, , "org.opencv.core.matrixop.max") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GAbsDiff, , "org.opencv.core.matrixop.absdiff") { + static GMatDesc outMeta(GMatDesc a, GMatDesc) { + return a; + } + }; + + G_TYPED_KERNEL(GAbsDiffC, , "org.opencv.core.matrixop.absdiffC") { + static GMatDesc outMeta(const GMatDesc& a, const GScalarDesc&) { + return a; + } + }; + + G_TYPED_KERNEL(GSum, , "org.opencv.core.matrixop.sum") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL(GCountNonZero, (GMat)>, "org.opencv.core.matrixop.countNonZero") { + static GOpaqueDesc outMeta(GMatDesc in) { + GAPI_Assert(in.chan == 1); + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GAddW, , "org.opencv.core.matrixop.addweighted") { + static GMatDesc outMeta(GMatDesc a, double, GMatDesc b, double, double, int ddepth) { + if (ddepth == -1) + { + // OpenCV: When the input arrays in add/subtract/multiply/divide + // functions have different depths, the output array depth must be + // explicitly specified! + // See artim_op() @ arithm.cpp + GAPI_Assert(a.chan == b.chan); + GAPI_Assert(a.depth == b.depth); + return a; + } + return a.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GNormL1, , "org.opencv.core.matrixop.norml1") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL(GNormL2, , "org.opencv.core.matrixop.norml2") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL(GNormInf, , "org.opencv.core.matrixop.norminf") { + static GScalarDesc outMeta(GMatDesc) { + return empty_scalar_desc(); + } + }; + + G_TYPED_KERNEL_M(GIntegral, , "org.opencv.core.matrixop.integral") { + static std::tuple outMeta(GMatDesc in, int sd, int sqd) { + return std::make_tuple(in.withSizeDelta(1,1).withDepth(sd), + in.withSizeDelta(1,1).withDepth(sqd)); + } + }; + + G_TYPED_KERNEL(GThreshold, , "org.opencv.core.matrixop.threshold") { + static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc, int) { + return in; + } + }; + + + G_TYPED_KERNEL_M(GThresholdOT, , "org.opencv.core.matrixop.thresholdOT") { + static std::tuple outMeta(GMatDesc in, GScalarDesc, int) { + return std::make_tuple(in, empty_scalar_desc()); + } + }; + + G_TYPED_KERNEL(GInRange, , "org.opencv.core.matrixop.inrange") { + static GMatDesc outMeta(GMatDesc in, GScalarDesc, GScalarDesc) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL_M(GSplit3, , "org.opencv.core.transform.split3") { + static std::tuple outMeta(GMatDesc in) { + const auto out_depth = in.depth; + const auto out_desc = in.withType(out_depth, 1); + return std::make_tuple(out_desc, out_desc, out_desc); + } + }; + + G_TYPED_KERNEL_M(GSplit4, ,"org.opencv.core.transform.split4") { + static std::tuple outMeta(GMatDesc in) { + const auto out_depth = in.depth; + const auto out_desc = in.withType(out_depth, 1); + return std::make_tuple(out_desc, out_desc, out_desc, out_desc); + } + }; + + G_TYPED_KERNEL(GMerge3, , "org.opencv.core.transform.merge3") { + static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc) { + // Preserve depth and add channel component + return in.withType(in.depth, 3); + } + }; + + G_TYPED_KERNEL(GMerge4, , "org.opencv.core.transform.merge4") { + static GMatDesc outMeta(GMatDesc in, GMatDesc, GMatDesc, GMatDesc) { + // Preserve depth and add channel component + return in.withType(in.depth, 4); + } + }; + + G_TYPED_KERNEL(GRemap, , "org.opencv.core.transform.remap") { + static GMatDesc outMeta(GMatDesc in, Mat m1, Mat, int, int, Scalar) { + return in.withSize(m1.size()); + } + }; + + G_TYPED_KERNEL(GFlip, , "org.opencv.core.transform.flip") { + static GMatDesc outMeta(GMatDesc in, int) { + return in; + } + }; + + // TODO: eliminate the need in this kernel (streaming) + G_TYPED_KERNEL(GCrop, , "org.opencv.core.transform.crop") { + static GMatDesc outMeta(GMatDesc in, Rect rc) { + return in.withSize(Size(rc.width, rc.height)); + } + }; + + G_TYPED_KERNEL(GConcatHor, , "org.opencv.imgproc.transform.concatHor") { + static GMatDesc outMeta(GMatDesc l, GMatDesc r) { + return l.withSizeDelta(+r.size.width, 0); + } + }; + + G_TYPED_KERNEL(GConcatVert, , "org.opencv.imgproc.transform.concatVert") { + static GMatDesc outMeta(GMatDesc t, GMatDesc b) { + return t.withSizeDelta(0, +b.size.height); + } + }; + + G_TYPED_KERNEL(GLUT, , "org.opencv.core.transform.LUT") { + static GMatDesc outMeta(GMatDesc in, Mat) { + return in; + } + }; + + G_TYPED_KERNEL(GConvertTo, , "org.opencv.core.transform.convertTo") { + static GMatDesc outMeta(GMatDesc in, int rdepth, double, double) { + return rdepth < 0 ? in : in.withDepth(rdepth); + } + }; + + G_TYPED_KERNEL(GSqrt, , "org.opencv.core.math.sqrt") { + static GMatDesc outMeta(GMatDesc in) { + return in; + } + }; + + G_TYPED_KERNEL(GNormalize, , "org.opencv.core.normalize") { + static GMatDesc outMeta(GMatDesc in, double, double, int, int ddepth) { + // unlike opencv doesn't have a mask as a parameter + return (ddepth < 0 ? in : in.withDepth(ddepth)); + } + }; + + G_TYPED_KERNEL(GWarpPerspective, , "org.opencv.core.warpPerspective") { + static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int borderMode, const cv::Scalar&) { + GAPI_Assert((borderMode == cv::BORDER_CONSTANT || borderMode == cv::BORDER_REPLICATE) && + "cv::gapi::warpPerspective supports only cv::BORDER_CONSTANT and cv::BORDER_REPLICATE border modes"); + return in.withType(in.depth, in.chan).withSize(dsize); + } + }; + + G_TYPED_KERNEL(GWarpAffine, , "org.opencv.core.warpAffine") { + static GMatDesc outMeta(GMatDesc in, const Mat&, Size dsize, int, int border_mode, const cv::Scalar&) { + GAPI_Assert(border_mode != cv::BORDER_TRANSPARENT && + "cv::BORDER_TRANSPARENT mode is not supported in cv::gapi::warpAffine"); + return in.withType(in.depth, in.chan).withSize(dsize); + } + }; + + G_TYPED_KERNEL( + GKMeansND, + ,GMat,GMat>(GMat,int,GMat,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeansND") { + + static std::tuple + outMeta(const GMatDesc& in, int K, const GMatDesc& bestLabels, const TermCriteria&, int, + KmeansFlags flags) { + GAPI_Assert(in.depth == CV_32F); + std::vector amount_n_dim = detail::checkVector(in); + int amount = amount_n_dim[0], dim = amount_n_dim[1]; + if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given + { // which means that kmeans will consider the following: + amount = in.size.height; + dim = in.size.width * in.chan; + } + // kmeans sets these labels' sizes when no bestLabels given: + GMatDesc out_labels(CV_32S, 1, Size{1, amount}); + // kmeans always sets these centers' sizes: + GMatDesc centers (CV_32F, 1, Size{dim, K}); + if (flags & KMEANS_USE_INITIAL_LABELS) + { + GAPI_Assert(bestLabels.depth == CV_32S); + int labels_amount = detail::checkVector(bestLabels, 1u); + GAPI_Assert(labels_amount == amount); + out_labels = bestLabels; // kmeans preserves bestLabels' sizes if given + } + return std::make_tuple(empty_gopaque_desc(), out_labels, centers); + } + }; + + G_TYPED_KERNEL( + GKMeansNDNoInit, + ,GMat,GMat>(GMat,int,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeansNDNoInit") { + + static std::tuple + outMeta(const GMatDesc& in, int K, const TermCriteria&, int, KmeansFlags flags) { + GAPI_Assert( !(flags & KMEANS_USE_INITIAL_LABELS) ); + GAPI_Assert(in.depth == CV_32F); + std::vector amount_n_dim = detail::checkVector(in); + int amount = amount_n_dim[0], dim = amount_n_dim[1]; + if (amount == -1) // Mat with height != 1, width != 1, channels != 1 given + { // which means that kmeans will consider the following: + amount = in.size.height; + dim = in.size.width * in.chan; + } + GMatDesc out_labels(CV_32S, 1, Size{1, amount}); + GMatDesc centers (CV_32F, 1, Size{dim, K}); + return std::make_tuple(empty_gopaque_desc(), out_labels, centers); + } + }; + + G_TYPED_KERNEL(GKMeans2D, ,GArray,GArray> + (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeans2D") { + static std::tuple + outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { + return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GKMeans3D, ,GArray,GArray> + (GArray,int,GArray,TermCriteria,int,KmeansFlags)>, + "org.opencv.core.kmeans3D") { + static std::tuple + outMeta(const GArrayDesc&,int,const GArrayDesc&,const TermCriteria&,int,KmeansFlags) { + return std::make_tuple(empty_gopaque_desc(), empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GTranspose, , "org.opencv.core.transpose") { + static GMatDesc outMeta(GMatDesc in) { + return in.withSize({in.size.height, in.size.width}); + } + }; +} // namespace core + +namespace streaming { + +// Operations for Streaming (declared in this header for convenience) +G_TYPED_KERNEL(GSize, (GMat)>, "org.opencv.streaming.size") { + static GOpaqueDesc outMeta(const GMatDesc&) { + return empty_gopaque_desc(); + } +}; + +G_TYPED_KERNEL(GSizeR, (GOpaque)>, "org.opencv.streaming.sizeR") { + static GOpaqueDesc outMeta(const GOpaqueDesc&) { + return empty_gopaque_desc(); + } +}; + +G_TYPED_KERNEL(GSizeMF, (GFrame)>, "org.opencv.streaming.sizeMF") { + static GOpaqueDesc outMeta(const GFrameDesc&) { + return empty_gopaque_desc(); + } +}; +} // namespace streaming + +//! @addtogroup gapi_math +//! @{ + +/** @brief Calculates the per-element sum of two matrices. + +The function add calculates sum of two matrices of the same size and the same number of channels: +\f[\texttt{dst}(I) = \texttt{saturate} ( \texttt{src1}(I) + \texttt{src2}(I)) \quad \texttt{if mask}(I) \ne0\f] + +The function can be replaced with matrix expressions: + \f[\texttt{dst} = \texttt{src1} + \texttt{src2}\f] + +The input matrices and the output matrix can all have the same or different depths. For example, you +can add a 16-bit unsigned matrix to a 8-bit signed matrix and store the sum as a 32-bit +floating-point matrix. Depth of the output matrix is determined by the ddepth parameter. +If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have +the same depth as the input matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.add" +@param src1 first input matrix. +@param src2 second input matrix. +@param ddepth optional depth of the output matrix. +@sa sub, addWeighted +*/ +GAPI_EXPORTS_W GMat add(const GMat& src1, const GMat& src2, int ddepth = -1); + +/** @brief Calculates the per-element sum of matrix and given scalar. + +The function addC adds a given scalar value to each element of given matrix. +The function can be replaced with matrix expressions: + + \f[\texttt{dst} = \texttt{src1} + \texttt{c}\f] + +Depth of the output matrix is determined by the ddepth parameter. +If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. +The matrices can be single or multi channel. Output matrix must have the same size and number of channels as the input matrix. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.addC" +@param src1 first input matrix. +@param c scalar value to be added. +@param ddepth optional depth of the output matrix. +@sa sub, addWeighted +*/ +GAPI_EXPORTS_W GMat addC(const GMat& src1, const GScalar& c, int ddepth = -1); +//! @overload +GAPI_EXPORTS_W GMat addC(const GScalar& c, const GMat& src1, int ddepth = -1); + +/** @brief Calculates the per-element difference between two matrices. + +The function sub calculates difference between two matrices, when both matrices have the same size and the same number of +channels: + \f[\texttt{dst}(I) = \texttt{src1}(I) - \texttt{src2}(I)\f] + +The function can be replaced with matrix expressions: +\f[\texttt{dst} = \texttt{src1} - \texttt{src2}\f] + +The input matrices and the output matrix can all have the same or different depths. For example, you +can subtract two 8-bit unsigned matrices store the result as a 16-bit signed matrix. +Depth of the output matrix is determined by the ddepth parameter. +If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have +the same depth as the input matrices. The matrices can be single or multi channel. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.sub" +@param src1 first input matrix. +@param src2 second input matrix. +@param ddepth optional depth of the output matrix. +@sa add, addC + */ +GAPI_EXPORTS_W GMat sub(const GMat& src1, const GMat& src2, int ddepth = -1); + +/** @brief Calculates the per-element difference between matrix and given scalar. + +The function can be replaced with matrix expressions: + \f[\texttt{dst} = \texttt{src} - \texttt{c}\f] + +Depth of the output matrix is determined by the ddepth parameter. +If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. +The matrices can be single or multi channel. Output matrix must have the same size as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.subC" +@param src first input matrix. +@param c scalar value to subtracted. +@param ddepth optional depth of the output matrix. +@sa add, addC, subRC + */ +GAPI_EXPORTS_W GMat subC(const GMat& src, const GScalar& c, int ddepth = -1); + +/** @brief Calculates the per-element difference between given scalar and the matrix. + +The function can be replaced with matrix expressions: + \f[\texttt{dst} = \texttt{c} - \texttt{src}\f] + +Depth of the output matrix is determined by the ddepth parameter. +If ddepth is set to default -1, the depth of output matrix will be the same as the depth of input matrix. +The matrices can be single or multi channel. Output matrix must have the same size as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.subRC" +@param c scalar value to subtract from. +@param src input matrix to be subtracted. +@param ddepth optional depth of the output matrix. +@sa add, addC, subC + */ +GAPI_EXPORTS_W GMat subRC(const GScalar& c, const GMat& src, int ddepth = -1); + +/** @brief Calculates the per-element scaled product of two matrices. + +The function mul calculates the per-element product of two matrices: + +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{scale} \cdot \texttt{src1} (I) \cdot \texttt{src2} (I))\f] + +If src1.depth() == src2.depth(), ddepth can be set to the default -1. In this case, the output matrix will have +the same depth as the input matrices. The matrices can be single or multi channel. +Output matrix must have the same size as input matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.mul" +@param src1 first input matrix. +@param src2 second input matrix of the same size and the same depth as src1. +@param scale optional scale factor. +@param ddepth optional depth of the output matrix. +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat mul(const GMat& src1, const GMat& src2, double scale = 1.0, int ddepth = -1); + +/** @brief Multiplies matrix by scalar. + +The function mulC multiplies each element of matrix src by given scalar value: + +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I) \cdot \texttt{multiplier} )\f] + +The matrices can be single or multi channel. Output matrix must have the same size as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.mulC" +@param src input matrix. +@param multiplier factor to be multiplied. +@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat mulC(const GMat& src, double multiplier, int ddepth = -1); +//! @overload +GAPI_EXPORTS_W GMat mulC(const GMat& src, const GScalar& multiplier, int ddepth = -1); // FIXME: merge with mulc +//! @overload +GAPI_EXPORTS_W GMat mulC(const GScalar& multiplier, const GMat& src, int ddepth = -1); // FIXME: merge with mulc + +/** @brief Performs per-element division of two matrices. + +The function divides one matrix by another: +\f[\texttt{dst(I) = saturate(src1(I)*scale/src2(I))}\f] + +For integer types when src2(I) is zero, dst(I) will also be zero. +Floating point case returns Inf/NaN (according to IEEE). + +Different channels of +multi-channel matrices are processed independently. +The matrices can be single or multi channel. Output matrix must have the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.div" +@param src1 first input matrix. +@param src2 second input matrix of the same size and depth as src1. +@param scale scalar factor. +@param ddepth optional depth of the output matrix; you can only pass -1 when src1.depth() == src2.depth(). +@sa mul, add, sub +*/ +GAPI_EXPORTS_W GMat div(const GMat& src1, const GMat& src2, double scale, int ddepth = -1); + +/** @brief Divides matrix by scalar. + +The function divC divides each element of matrix src by given scalar value: + +\f[\texttt{dst(I) = saturate(src(I)*scale/divisor)}\f] + +When divisor is zero, dst(I) will also be zero. Different channels of +multi-channel matrices are processed independently. +The matrices can be single or multi channel. Output matrix must have the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.divC" +@param src input matrix. +@param divisor number to be divided by. +@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. +@param scale scale factor. +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat divC(const GMat& src, const GScalar& divisor, double scale, int ddepth = -1); + +/** @brief Divides scalar by matrix. + +The function divRC divides given scalar by each element of matrix src and keep the division result in new matrix of the same size and type as src: + +\f[\texttt{dst(I) = saturate(divident*scale/src(I))}\f] + +When src(I) is zero, dst(I) will also be zero. Different channels of +multi-channel matrices are processed independently. +The matrices can be single or multi channel. Output matrix must have the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.divRC" +@param src input matrix. +@param divident number to be divided. +@param ddepth optional depth of the output matrix. If -1, the depth of output matrix will be the same as input matrix depth. +@param scale scale factor +@sa add, sub, div, addWeighted +*/ +GAPI_EXPORTS_W GMat divRC(const GScalar& divident, const GMat& src, double scale, int ddepth = -1); + +/** @brief Applies a mask to a matrix. + +The function mask set value from given matrix if the corresponding pixel value in mask matrix set to true, +and set the matrix value to 0 otherwise. + +Supported src matrix data types are @ref CV_8UC1, @ref CV_16SC1, @ref CV_16UC1. Supported mask data type is @ref CV_8UC1. + +@note Function textual ID is "org.opencv.core.math.mask" +@param src input matrix. +@param mask input mask matrix. +*/ +GAPI_EXPORTS_W GMat mask(const GMat& src, const GMat& mask); + +/** @brief Calculates an average (mean) of matrix elements. + +The function mean calculates the mean value M of matrix elements, +independently for each channel, and return it. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.math.mean" +@param src input matrix. +@sa countNonZero, min, max +*/ +GAPI_EXPORTS_W GScalar mean(const GMat& src); + +/** @brief Calculates x and y coordinates of 2D vectors from their magnitude and angle. + +The function polarToCart calculates the Cartesian coordinates of each 2D +vector represented by the corresponding elements of magnitude and angle: +\f[\begin{array}{l} \texttt{x} (I) = \texttt{magnitude} (I) \cos ( \texttt{angle} (I)) \\ \texttt{y} (I) = \texttt{magnitude} (I) \sin ( \texttt{angle} (I)) \\ \end{array}\f] + +The relative accuracy of the estimated coordinates is about 1e-6. + +First output is a matrix of x-coordinates of 2D vectors. +Second output is a matrix of y-coordinates of 2D vectors. +Both output must have the same size and depth as input matrices. + +@note Function textual ID is "org.opencv.core.math.polarToCart" + +@param magnitude input floating-point @ref CV_32FC1 matrix (1xN) of magnitudes of 2D vectors; +@param angle input floating-point @ref CV_32FC1 matrix (1xN) of angles of 2D vectors. +@param angleInDegrees when true, the input angles are measured in +degrees, otherwise, they are measured in radians. +@sa cartToPolar, exp, log, pow, sqrt +*/ +GAPI_EXPORTS_W std::tuple polarToCart(const GMat& magnitude, const GMat& angle, + bool angleInDegrees = false); + +/** @brief Calculates the magnitude and angle of 2D vectors. + +The function cartToPolar calculates either the magnitude, angle, or both +for every 2D vector (x(I),y(I)): +\f[\begin{array}{l} \texttt{magnitude} (I)= \sqrt{\texttt{x}(I)^2+\texttt{y}(I)^2} , \\ \texttt{angle} (I)= \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))[ \cdot180 / \pi ] \end{array}\f] + +The angles are calculated with accuracy about 0.3 degrees. For the point +(0,0), the angle is set to 0. + +First output is a matrix of magnitudes of the same size and depth as input x. +Second output is a matrix of angles that has the same size and depth as +x; the angles are measured in radians (from 0 to 2\*Pi) or in degrees (0 to 360 degrees). + +@note Function textual ID is "org.opencv.core.math.cartToPolar" + +@param x matrix of @ref CV_32FC1 x-coordinates. +@param y array of @ref CV_32FC1 y-coordinates. +@param angleInDegrees a flag, indicating whether the angles are measured +in radians (which is by default), or in degrees. +@sa polarToCart +*/ +GAPI_EXPORTS_W std::tuple cartToPolar(const GMat& x, const GMat& y, + bool angleInDegrees = false); + +/** @brief Calculates the rotation angle of 2D vectors. + +The function cv::phase calculates the rotation angle of each 2D vector that +is formed from the corresponding elements of x and y : +\f[\texttt{angle} (I) = \texttt{atan2} ( \texttt{y} (I), \texttt{x} (I))\f] + +The angle estimation accuracy is about 0.3 degrees. When x(I)=y(I)=0 , +the corresponding angle(I) is set to 0. +@param x input floating-point array of x-coordinates of 2D vectors. +@param y input array of y-coordinates of 2D vectors; it must have the +same size and the same type as x. +@param angleInDegrees when true, the function calculates the angle in +degrees, otherwise, they are measured in radians. +@return array of vector angles; it has the same size and same type as x. +*/ +GAPI_EXPORTS_W GMat phase(const GMat& x, const GMat &y, bool angleInDegrees = false); + +/** @brief Calculates a square root of array elements. + +The function cv::gapi::sqrt calculates a square root of each input array element. +In case of multi-channel arrays, each channel is processed +independently. The accuracy is approximately the same as of the built-in +std::sqrt . +@param src input floating-point array. +@return output array of the same size and type as src. +*/ +GAPI_EXPORTS_W GMat sqrt(const GMat &src); + +//! @} gapi_math +//! +//! @addtogroup gapi_pixelwise +//! @{ + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater compare to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) > \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: +\f[\texttt{dst} = \texttt{src1} > \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices/matrix. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGT" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpLE, cmpGE, cmpLT +*/ +GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGTScalar" +*/ +GAPI_EXPORTS_W GMat cmpGT(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less than elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) < \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} < \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices/matrix. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLT" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpLE, cmpGE, cmpGT +*/ +GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLTScalar" +*/ +GAPI_EXPORTS_W GMat cmpLT(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are greater or equal compare to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) >= \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} >= \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpGE" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpLE, cmpGT, cmpLT +*/ +GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLGEcalar" +*/ +GAPI_EXPORTS_W GMat cmpGE(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are less or equal compare to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) <= \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} <= \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLE" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpGT, cmpGE, cmpLT +*/ +GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpLEScalar" +*/ +GAPI_EXPORTS_W GMat cmpLE(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are equal to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) == \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} == \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQ" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpNE +*/ +GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpEQScalar" +*/ +GAPI_EXPORTS_W GMat cmpEQ(const GMat& src1, const GScalar& src2); + +/** @brief Performs the per-element comparison of two matrices checking if elements from first matrix are not equal to elements in second. + +The function compares elements of two matrices src1 and src2 of the same size: + \f[\texttt{dst} (I) = \texttt{src1} (I) != \texttt{src2} (I)\f] + +When the comparison result is true, the corresponding element of output +array is set to 255. The comparison operations can be replaced with the +equivalent matrix expressions: + \f[\texttt{dst} = \texttt{src1} != \texttt{src2}\f] + +Output matrix of depth @ref CV_8U must have the same size and the same number of channels as + the input matrices. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNE" +@param src1 first input matrix. +@param src2 second input matrix/scalar of the same depth as first input matrix. +@sa min, max, threshold, cmpEQ +*/ +GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.compare.cmpNEScalar" +*/ +GAPI_EXPORTS_W GMat cmpNE(const GMat& src1, const GScalar& src2); + +/** @brief computes bitwise conjunction of the two matrixes (src1 & src2) +Calculates the per-element bit-wise logical conjunction of two matrices of the same size. + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_and" + +@param src1 first input matrix. +@param src2 second input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_andS" +@param src1 first input matrix. +@param src2 scalar, which will be per-lemenetly conjuncted with elements of src1. +*/ +GAPI_EXPORTS_W GMat bitwise_and(const GMat& src1, const GScalar& src2); + +/** @brief computes bitwise disjunction of the two matrixes (src1 | src2) +Calculates the per-element bit-wise logical disjunction of two matrices of the same size. + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_or" + +@param src1 first input matrix. +@param src2 second input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_orS" +@param src1 first input matrix. +@param src2 scalar, which will be per-lemenetly disjuncted with elements of src1. +*/ +GAPI_EXPORTS_W GMat bitwise_or(const GMat& src1, const GScalar& src2); + + +/** @brief computes bitwise logical "exclusive or" of the two matrixes (src1 ^ src2) +Calculates the per-element bit-wise logical "exclusive or" of two matrices of the same size. + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xor" + +@param src1 first input matrix. +@param src2 second input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GMat& src2); +/** @overload +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_xorS" +@param src1 first input matrix. +@param src2 scalar, for which per-lemenet "logical or" operation on elements of src1 will be performed. +*/ +GAPI_EXPORTS_W GMat bitwise_xor(const GMat& src1, const GScalar& src2); + + +/** @brief Inverts every bit of an array. + +The function bitwise_not calculates per-element bit-wise inversion of the input +matrix: +\f[\texttt{dst} (I) = \neg \texttt{src} (I)\f] + +In case of floating-point matrices, their machine-specific bit +representations (usually IEEE754-compliant) are used for the operation. +In case of multi-channel matrices, each channel is processed +independently. Output matrix must have the same size and depth as the input +matrix. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.bitwise_not" + +@param src input matrix. +*/ +GAPI_EXPORTS_W GMat bitwise_not(const GMat& src); + +/** @brief Select values from either first or second of input matrices by given mask. +The function set to the output matrix either the value from the first input matrix if corresponding value of mask matrix is 255, + or value from the second input matrix (if value of mask matrix set to 0). + +Input mask matrix must be of @ref CV_8UC1 type, two other inout matrices and output matrix should be of the same type. The size should +be the same for all input and output matrices. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.pixelwise.select" + +@param src1 first input matrix. +@param src2 second input matrix. +@param mask mask input matrix. +*/ +GAPI_EXPORTS_W GMat select(const GMat& src1, const GMat& src2, const GMat& mask); + +//! @} gapi_pixelwise + + +//! @addtogroup gapi_matrixop +//! @{ +/** @brief Calculates per-element minimum of two matrices. + +The function min calculates the per-element minimum of two matrices of the same size, number of channels and depth: +\f[\texttt{dst} (I)= \min ( \texttt{src1} (I), \texttt{src2} (I))\f] + where I is a multi-dimensional index of matrix elements. In case of + multi-channel matrices, each channel is processed independently. +Output matrix must be of the same size and depth as src1. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.min" +@param src1 first input matrix. +@param src2 second input matrix of the same size and depth as src1. +@sa max, cmpEQ, cmpLT, cmpLE +*/ +GAPI_EXPORTS_W GMat min(const GMat& src1, const GMat& src2); + +/** @brief Calculates per-element maximum of two matrices. + +The function max calculates the per-element maximum of two matrices of the same size, number of channels and depth: +\f[\texttt{dst} (I)= \max ( \texttt{src1} (I), \texttt{src2} (I))\f] + where I is a multi-dimensional index of matrix elements. In case of + multi-channel matrices, each channel is processed independently. +Output matrix must be of the same size and depth as src1. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.max" +@param src1 first input matrix. +@param src2 second input matrix of the same size and depth as src1. +@sa min, compare, cmpEQ, cmpGT, cmpGE +*/ +GAPI_EXPORTS_W GMat max(const GMat& src1, const GMat& src2); + +/** @brief Calculates the per-element absolute difference between two matrices. + +The function absDiff calculates absolute difference between two matrices of the same size and depth: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{src2}(I)|)\f] + where I is a multi-dimensional index of matrix elements. In case of + multi-channel matrices, each channel is processed independently. +Output matrix must have the same size and depth as input matrices. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.absdiff" +@param src1 first input matrix. +@param src2 second input matrix. +@sa abs +*/ +GAPI_EXPORTS_W GMat absDiff(const GMat& src1, const GMat& src2); + +/** @brief Calculates absolute value of matrix elements. + +The function abs calculates absolute difference between matrix elements and given scalar value: + \f[\texttt{dst}(I) = \texttt{saturate} (| \texttt{src1}(I) - \texttt{matC}(I)|)\f] + where matC is constructed from given scalar c and has the same sizes and depth as input matrix src. + +Output matrix must be of the same size and depth as src. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.absdiffC" +@param src input matrix. +@param c scalar to be subtracted. +@sa min, max +*/ +GAPI_EXPORTS_W GMat absDiffC(const GMat& src, const GScalar& c); + +/** @brief Calculates sum of all matrix elements. + +The function sum calculates sum of all matrix elements, independently for each channel. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.sum" +@param src input matrix. +@sa countNonZero, mean, min, max +*/ +GAPI_EXPORTS_W GScalar sum(const GMat& src); + +/** @brief Counts non-zero array elements. + +The function returns the number of non-zero elements in src : +\f[\sum _{I: \; \texttt{src} (I) \ne0 } 1\f] + +Supported matrix data types are @ref CV_8UC1, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.countNonZero" +@param src input single-channel matrix. +@sa mean, min, max +*/ +GAPI_EXPORTS_W GOpaque countNonZero(const GMat& src); + +/** @brief Calculates the weighted sum of two matrices. + +The function addWeighted calculates the weighted sum of two matrices as follows: +\f[\texttt{dst} (I)= \texttt{saturate} ( \texttt{src1} (I)* \texttt{alpha} + \texttt{src2} (I)* \texttt{beta} + \texttt{gamma} )\f] +where I is a multi-dimensional index of array elements. In case of multi-channel matrices, each +channel is processed independently. + +The function can be replaced with a matrix expression: + \f[\texttt{dst}(I) = \texttt{alpha} * \texttt{src1}(I) - \texttt{beta} * \texttt{src2}(I) + \texttt{gamma} \f] + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.addweighted" +@param src1 first input matrix. +@param alpha weight of the first matrix elements. +@param src2 second input matrix of the same size and channel number as src1. +@param beta weight of the second matrix elements. +@param gamma scalar added to each sum. +@param ddepth optional depth of the output matrix. +@sa add, sub +*/ +GAPI_EXPORTS_W GMat addWeighted(const GMat& src1, double alpha, const GMat& src2, double beta, double gamma, int ddepth = -1); + +/** @brief Calculates the absolute L1 norm of a matrix. + +This version of normL1 calculates the absolute L1 norm of src. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{1} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_1} &= |-1| + |2| = 3 \\ +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_1} &= |0.5| + |0.5| = 1 \\ +\f} + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.norml1" +@param src input matrix. +@sa normL2, normInf +*/ +GAPI_EXPORTS_W GScalar normL1(const GMat& src); + +/** @brief Calculates the absolute L2 norm of a matrix. + +This version of normL2 calculates the absolute L2 norm of src. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{2} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_2} &= \sqrt{(-1)^{2} + (2)^{2}} = \sqrt{5} \\ +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_2} &= \sqrt{(0.5)^{2} + (0.5)^{2}} = \sqrt{0.5} \\ +\f} + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +@note Function textual ID is "org.opencv.core.matrixop.norml2" +@param src input matrix. +@sa normL1, normInf +*/ +GAPI_EXPORTS_W GScalar normL2(const GMat& src); + +/** @brief Calculates the absolute infinite norm of a matrix. + +This version of normInf calculates the absolute infinite norm of src. + +As example for one array consider the function \f$r(x)= \begin{pmatrix} x \\ 1-x \end{pmatrix}, x \in [-1;1]\f$. +The \f$ L_{\infty} \f$ norm for the sample value \f$r(-1) = \begin{pmatrix} -1 \\ 2 \end{pmatrix}\f$ +is calculated as follows +\f{align*} + \| r(-1) \|_{L_\infty} &= \max(|-1|,|2|) = 2 +\f} +and for \f$r(0.5) = \begin{pmatrix} 0.5 \\ 0.5 \end{pmatrix}\f$ the calculation is +\f{align*} + \| r(0.5) \|_{L_\infty} &= \max(|0.5|,|0.5|) = 0.5. +\f} + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.core.matrixop.norminf" +@param src input matrix. +@sa normL1, normL2 +*/ +GAPI_EXPORTS_W GScalar normInf(const GMat& src); + +/** @brief Calculates the integral of an image. + +The function calculates one or more integral images for the source image as follows: + +\f[\texttt{sum} (X,Y) = \sum _{x integral(const GMat& src, int sdepth = -1, int sqdepth = -1); + +/** @brief Applies a fixed-level threshold to each matrix element. + +The function applies fixed-level thresholding to a single- or multiple-channel matrix. +The function is typically used to get a bi-level (binary) image out of a grayscale image ( cmp functions could be also used for +this purpose) or for removing a noise, that is, filtering out pixels with too small or too large +values. There are several types of thresholding supported by the function. They are determined by +type parameter. + +Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the +above values. In these cases, the function determines the optimal threshold value using the Otsu's +or Triangle algorithm and uses it instead of the specified thresh . The function returns the +computed threshold value in addititon to thresholded matrix. +The Otsu's and Triangle methods are implemented only for 8-bit matrices. + +Input image should be single channel only in case of cv::THRESH_OTSU or cv::THRESH_TRIANGLE flags. +Output matrix must be of the same size and depth as src. + +@note Function textual ID is "org.opencv.core.matrixop.threshold" + +@param src input matrix (@ref CV_8UC1, @ref CV_8UC3, or @ref CV_32FC1). +@param thresh threshold value. +@param maxval maximum value to use with the cv::THRESH_BINARY and cv::THRESH_BINARY_INV thresholding +types. +@param type thresholding type (see the cv::ThresholdTypes). + +@sa min, max, cmpGT, cmpLE, cmpGE, cmpLT + */ +GAPI_EXPORTS_W GMat threshold(const GMat& src, const GScalar& thresh, const GScalar& maxval, int type); +/** @overload +This function applicable for all threshold types except cv::THRESH_OTSU and cv::THRESH_TRIANGLE +@note Function textual ID is "org.opencv.core.matrixop.thresholdOT" +*/ +GAPI_EXPORTS_W std::tuple threshold(const GMat& src, const GScalar& maxval, int type); + +/** @brief Applies a range-level threshold to each matrix element. + +The function applies range-level thresholding to a single- or multiple-channel matrix. +It sets output pixel value to OxFF if the corresponding pixel value of input matrix is in specified range,or 0 otherwise. + +Input and output matrices must be CV_8UC1. + +@note Function textual ID is "org.opencv.core.matrixop.inRange" + +@param src input matrix (CV_8UC1). +@param threshLow lower boundary value. +@param threshUp upper boundary value. + +@sa threshold + */ +GAPI_EXPORTS_W GMat inRange(const GMat& src, const GScalar& threshLow, const GScalar& threshUp); + +//! @} gapi_matrixop + +//! @addtogroup gapi_transform +//! @{ +/** @brief Creates one 4-channel matrix out of 4 single-channel ones. + +The function merges several matrices to make a single multi-channel matrix. That is, each +element of the output matrix will be a concatenation of the elements of the input matrices, where +elements of i-th input matrix are treated as mv[i].channels()-element vectors. +Output matrix must be of @ref CV_8UC4 type. + +The function split4 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.merge4" + +@param src1 first input @ref CV_8UC1 matrix to be merged. +@param src2 second input @ref CV_8UC1 matrix to be merged. +@param src3 third input @ref CV_8UC1 matrix to be merged. +@param src4 fourth input @ref CV_8UC1 matrix to be merged. +@sa merge3, split4, split3 +*/ +GAPI_EXPORTS_W GMat merge4(const GMat& src1, const GMat& src2, const GMat& src3, const GMat& src4); + +/** @brief Creates one 3-channel matrix out of 3 single-channel ones. + +The function merges several matrices to make a single multi-channel matrix. That is, each +element of the output matrix will be a concatenation of the elements of the input matrices, where +elements of i-th input matrix are treated as mv[i].channels()-element vectors. +Output matrix must be of @ref CV_8UC3 type. + +The function split3 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.merge3" + +@param src1 first input @ref CV_8UC1 matrix to be merged. +@param src2 second input @ref CV_8UC1 matrix to be merged. +@param src3 third input @ref CV_8UC1 matrix to be merged. +@sa merge4, split4, split3 +*/ +GAPI_EXPORTS_W GMat merge3(const GMat& src1, const GMat& src2, const GMat& src3); + +/** @brief Divides a 4-channel matrix into 4 single-channel matrices. + +The function splits a 4-channel matrix into 4 single-channel matrices: +\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] + +All output matrices must be of @ref CV_8UC1 type. + +The function merge4 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.split4" + +@param src input @ref CV_8UC4 matrix. +@sa split3, merge3, merge4 +*/ +GAPI_EXPORTS_W std::tuple split4(const GMat& src); + +/** @brief Divides a 3-channel matrix into 3 single-channel matrices. + +The function splits a 3-channel matrix into 3 single-channel matrices: +\f[\texttt{mv} [c](I) = \texttt{src} (I)_c\f] + +All output matrices must be of @ref CV_8UC1 type. + +The function merge3 does the reverse operation. + +@note + - Function textual ID is "org.opencv.core.transform.split3" + +@param src input @ref CV_8UC3 matrix. +@sa split4, merge3, merge4 +*/ +GAPI_EXPORTS_W std::tuple split3(const GMat& src); + +/** @brief Applies a generic geometrical transformation to an image. + +The function remap transforms the source image using the specified map: + +\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] + +where values of pixels with non-integer coordinates are computed using one of available +interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps +in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in +\f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to +convert from floating to fixed-point representations of a map is that they can yield much faster +(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), +cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. +Output image must be of the same size and depth as input one. + +@note + - Function textual ID is "org.opencv.core.transform.remap" + - Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + +@param src Source image. +@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2, +CV_32FC1, or CV_32FC2. +@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map +if map1 is (x,y) points), respectively. +@param interpolation Interpolation method (see cv::InterpolationFlags). The methods #INTER_AREA +and #INTER_LINEAR_EXACT are not supported by this function. +@param borderMode Pixel extrapolation method (see cv::BorderTypes). When +borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that +corresponds to the "outliers" in the source image are not modified by the function. +@param borderValue Value used in case of a constant border. By default, it is 0. + */ +GAPI_EXPORTS_W GMat remap(const GMat& src, const Mat& map1, const Mat& map2, + int interpolation, int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @brief Flips a 2D matrix around vertical, horizontal, or both axes. + +The function flips the matrix in one of three different ways (row +and column indices are 0-based): +\f[\texttt{dst} _{ij} = +\left\{ +\begin{array}{l l} +\texttt{src} _{\texttt{src.rows}-i-1,j} & if\; \texttt{flipCode} = 0 \\ +\texttt{src} _{i, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} > 0 \\ +\texttt{src} _{ \texttt{src.rows} -i-1, \texttt{src.cols} -j-1} & if\; \texttt{flipCode} < 0 \\ +\end{array} +\right.\f] +The example scenarios of using the function are the following: +* Vertical flipping of the image (flipCode == 0) to switch between + top-left and bottom-left image origin. This is a typical operation + in video processing on Microsoft Windows\* OS. +* Horizontal flipping of the image with the subsequent horizontal + shift and absolute difference calculation to check for a + vertical-axis symmetry (flipCode \> 0). +* Simultaneous horizontal and vertical flipping of the image with + the subsequent shift and absolute difference calculation to check + for a central symmetry (flipCode \< 0). +* Reversing the order of point arrays (flipCode \> 0 or + flipCode == 0). +Output image must be of the same depth as input one, size should be correct for given flipCode. + +@note Function textual ID is "org.opencv.core.transform.flip" + +@param src input matrix. +@param flipCode a flag to specify how to flip the array; 0 means +flipping around the x-axis and positive value (for example, 1) means +flipping around y-axis. Negative value (for example, -1) means flipping +around both axes. +@sa remap +*/ +GAPI_EXPORTS_W GMat flip(const GMat& src, int flipCode); + +/** @brief Crops a 2D matrix. + +The function crops the matrix by given cv::Rect. + +Output matrix must be of the same depth as input one, size is specified by given rect size. + +@note Function textual ID is "org.opencv.core.transform.crop" + +@param src input matrix. +@param rect a rect to crop a matrix to +@sa resize +*/ +GAPI_EXPORTS_W GMat crop(const GMat& src, const Rect& rect); + +/** @brief Applies horizontal concatenation to given matrices. + +The function horizontally concatenates two GMat matrices (with the same number of rows). +@code{.cpp} + GMat A = { 1, 4, + 2, 5, + 3, 6 }; + GMat B = { 7, 10, + 8, 11, + 9, 12 }; + + GMat C = gapi::concatHor(A, B); + //C: + //[1, 4, 7, 10; + // 2, 5, 8, 11; + // 3, 6, 9, 12] +@endcode +Output matrix must the same number of rows and depth as the src1 and src2, and the sum of cols of the src1 and src2. +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.imgproc.transform.concatHor" + +@param src1 first input matrix to be considered for horizontal concatenation. +@param src2 second input matrix to be considered for horizontal concatenation. +@sa concatVert +*/ +GAPI_EXPORTS_W GMat concatHor(const GMat& src1, const GMat& src2); + +/** @overload +The function horizontally concatenates given number of GMat matrices (with the same number of columns). +Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. + +@param v vector of input matrices to be concatenated horizontally. +*/ +GAPI_EXPORTS_W GMat concatHor(const std::vector &v); + +/** @brief Applies vertical concatenation to given matrices. + +The function vertically concatenates two GMat matrices (with the same number of cols). + @code{.cpp} + GMat A = { 1, 7, + 2, 8, + 3, 9 }; + GMat B = { 4, 10, + 5, 11, + 6, 12 }; + + GMat C = gapi::concatVert(A, B); + //C: + //[1, 7; + // 2, 8; + // 3, 9; + // 4, 10; + // 5, 11; + // 6, 12] + @endcode + +Output matrix must the same number of cols and depth as the src1 and src2, and the sum of rows of the src1 and src2. +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. + +@note Function textual ID is "org.opencv.imgproc.transform.concatVert" + +@param src1 first input matrix to be considered for vertical concatenation. +@param src2 second input matrix to be considered for vertical concatenation. +@sa concatHor +*/ +GAPI_EXPORTS_W GMat concatVert(const GMat& src1, const GMat& src2); + +/** @overload +The function vertically concatenates given number of GMat matrices (with the same number of columns). +Output matrix must the same number of columns and depth as the input matrices, and the sum of rows of input matrices. + +@param v vector of input matrices to be concatenated vertically. +*/ +GAPI_EXPORTS_W GMat concatVert(const std::vector &v); + + +/** @brief Performs a look-up table transform of a matrix. + +The function LUT fills the output matrix with values from the look-up table. Indices of the entries +are taken from the input matrix. That is, the function processes each element of src as follows: +\f[\texttt{dst} (I) \leftarrow \texttt{lut(src(I))}\f] + +Supported matrix data types are @ref CV_8UC1. +Output is a matrix of the same size and number of channels as src, and the same depth as lut. + +@note Function textual ID is "org.opencv.core.transform.LUT" + +@param src input matrix of 8-bit elements. +@param lut look-up table of 256 elements; in case of multi-channel input array, the table should +either have a single channel (in this case the same table is used for all channels) or the same +number of channels as in the input matrix. +*/ +GAPI_EXPORTS_W GMat LUT(const GMat& src, const Mat& lut); + +/** @brief Converts a matrix to another data depth with optional scaling. + +The method converts source pixel values to the target data depth. saturate_cast\<\> is applied at +the end to avoid possible overflows: + +\f[m(x,y) = saturate \_ cast( \alpha (*this)(x,y) + \beta )\f] +Output matrix must be of the same size as input one. + +@note Function textual ID is "org.opencv.core.transform.convertTo" +@param src input matrix to be converted from. +@param rdepth desired output matrix depth or, rather, the depth since the number of channels are the +same as the input has; if rdepth is negative, the output matrix will have the same depth as the input. +@param alpha optional scale factor. +@param beta optional delta added to the scaled values. + */ +GAPI_EXPORTS_W GMat convertTo(const GMat& src, int rdepth, double alpha=1, double beta=0); + +/** @brief Normalizes the norm or value range of an array. + +The function normalizes scale and shift the input array elements so that +\f[\| \texttt{dst} \| _{L_p}= \texttt{alpha}\f] +(where p=Inf, 1 or 2) when normType=NORM_INF, NORM_L1, or NORM_L2, respectively; or so that +\f[\min _I \texttt{dst} (I)= \texttt{alpha} , \, \, \max _I \texttt{dst} (I)= \texttt{beta}\f] +when normType=NORM_MINMAX (for dense arrays only). + +@note Function textual ID is "org.opencv.core.normalize" + +@param src input array. +@param alpha norm value to normalize to or the lower range boundary in case of the range +normalization. +@param beta upper range boundary in case of the range normalization; it is not used for the norm +normalization. +@param norm_type normalization type (see cv::NormTypes). +@param ddepth when negative, the output array has the same type as src; otherwise, it has the same +number of channels as src and the depth =ddepth. +@sa norm, Mat::convertTo +*/ +GAPI_EXPORTS_W GMat normalize(const GMat& src, double alpha, double beta, + int norm_type, int ddepth = -1); + +/** @brief Applies a perspective transformation to an image. + +The function warpPerspective transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , + \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert +and then put in the formula above instead of M. The function cannot operate in-place. + +@param src input image. +@param M \f$3\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the +optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). +@param borderValue value used in case of a constant border; by default, it equals 0. + +@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform + */ +GAPI_EXPORTS_W GMat warpPerspective(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, + int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); + +/** @brief Applies an affine transformation to an image. + +The function warpAffine transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted +with #invertAffineTransform and then put in the formula above instead of M. The function cannot +operate in-place. + +@param src input image. +@param M \f$2\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (see #InterpolationFlags) and the optional +flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (see #BorderTypes); +borderMode=#BORDER_TRANSPARENT isn't supported +@param borderValue value used in case of a constant border; by default, it is 0. + +@sa warpPerspective, resize, remap, getRectSubPix, transform + */ +GAPI_EXPORTS_W GMat warpAffine(const GMat& src, const Mat& M, const Size& dsize, int flags = cv::INTER_LINEAR, + int borderMode = cv::BORDER_CONSTANT, const Scalar& borderValue = Scalar()); +//! @} gapi_transform + +/** @brief Finds centers of clusters and groups input samples around the clusters. + +The function kmeans implements a k-means algorithm that finds the centers of K clusters +and groups the input samples around the clusters. As an output, \f$\texttt{bestLabels}_i\f$ +contains a 0-based cluster index for the \f$i^{th}\f$ sample. + +@note + - Function textual ID is "org.opencv.core.kmeansND" + - In case of an N-dimentional points' set given, input GMat can have the following traits: +2 dimensions, a single row or column if there are N channels, +or N columns if there is a single channel. Mat should have @ref CV_32F depth. + - Although, if GMat with height != 1, width != 1, channels != 1 given as data, n-dimensional +samples are considered given in amount of A, where A = height, n = width * channels. + - In case of GMat given as data: + - the output labels are returned as 1-channel GMat with sizes +width = 1, height = A, where A is samples amount, or width = bestLabels.width, +height = bestLabels.height if bestLabels given; + - the cluster centers are returned as 1-channel GMat with sizes +width = n, height = K, where n is samples' dimentionality and K is clusters' amount. + - As one of possible usages, if you want to control the initial labels for each attempt +by yourself, you can utilize just the core of the function. To do that, set the number +of attempts to 1, initialize labels each time using a custom algorithm, pass them with the +( flags = #KMEANS_USE_INITIAL_LABELS ) flag, and then choose the best (most-compact) clustering. + +@param data Data for clustering. An array of N-Dimensional points with float coordinates is needed. +Function can take GArray, GArray for 2D and 3D cases or GMat for any +dimentionality and channels. +@param K Number of clusters to split the set by. +@param bestLabels Optional input integer array that can store the supposed initial cluster indices +for every sample. Used when ( flags = #KMEANS_USE_INITIAL_LABELS ) flag is set. +@param criteria The algorithm termination criteria, that is, the maximum number of iterations +and/or the desired accuracy. The accuracy is specified as criteria.epsilon. As soon as each of +the cluster centers moves by less than criteria.epsilon on some iteration, the algorithm stops. +@param attempts Flag to specify the number of times the algorithm is executed using different +initial labellings. The algorithm returns the labels that yield the best compactness (see the first +function return value). +@param flags Flag that can take values of cv::KmeansFlags . + +@return + - Compactness measure that is computed as +\f[\sum _i \| \texttt{samples} _i - \texttt{centers} _{ \texttt{labels} _i} \| ^2\f] +after every attempt. The best (minimum) value is chosen and the corresponding labels and the +compactness value are returned by the function. + - Integer array that stores the cluster indices for every sample. + - Array of the cluster centers. +*/ +GAPI_EXPORTS_W std::tuple,GMat,GMat> +kmeans(const GMat& data, const int K, const GMat& bestLabels, + const TermCriteria& criteria, const int attempts, const KmeansFlags flags); + +/** @overload +@note + - Function textual ID is "org.opencv.core.kmeansNDNoInit" + - #KMEANS_USE_INITIAL_LABELS flag must not be set while using this overload. + */ +GAPI_EXPORTS_W std::tuple,GMat,GMat> +kmeans(const GMat& data, const int K, const TermCriteria& criteria, const int attempts, + const KmeansFlags flags); + +/** @overload +@note Function textual ID is "org.opencv.core.kmeans2D" + */ +GAPI_EXPORTS_W std::tuple,GArray,GArray> +kmeans(const GArray& data, const int K, const GArray& bestLabels, + const TermCriteria& criteria, const int attempts, const KmeansFlags flags); + +/** @overload +@note Function textual ID is "org.opencv.core.kmeans3D" + */ +GAPI_EXPORTS_W std::tuple,GArray,GArray> +kmeans(const GArray& data, const int K, const GArray& bestLabels, + const TermCriteria& criteria, const int attempts, const KmeansFlags flags); + + +/** @brief Transposes a matrix. + +The function transposes the matrix: +\f[\texttt{dst} (i,j) = \texttt{src} (j,i)\f] + +@note + - Function textual ID is "org.opencv.core.transpose" + - No complex conjugation is done in case of a complex matrix. It should be done separately if needed. + +@param src input array. +*/ +GAPI_EXPORTS_W GMat transpose(const GMat& src); + + +namespace streaming { +/** @brief Gets dimensions from Mat. + +@note Function textual ID is "org.opencv.streaming.size" + +@param src Input tensor +@return Size (tensor dimensions). +*/ +GAPI_EXPORTS_W GOpaque size(const GMat& src); + +/** @overload +Gets dimensions from rectangle. + +@note Function textual ID is "org.opencv.streaming.sizeR" + +@param r Input rectangle. +@return Size (rectangle dimensions). +*/ +GAPI_EXPORTS_W GOpaque size(const GOpaque& r); + +/** @brief Gets dimensions from MediaFrame. + +@note Function textual ID is "org.opencv.streaming.sizeMF" + +@param src Input frame +@return Size (frame dimensions). +*/ +GAPI_EXPORTS_W GOpaque size(const GFrame& src); +} //namespace streaming +} //namespace gapi +} //namespace cv + +#endif //OPENCV_GAPI_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp index c30df2a295..ee86fb72c2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/core.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CPU_CORE_API_HPP -#define OPENCV_GAPI_CPU_CORE_API_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { -namespace gapi { -namespace core { -namespace cpu { - -GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -} // namespace cpu -} // namespace core -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_CORE_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CPU_CORE_API_HPP +#define OPENCV_GAPI_CPU_CORE_API_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { +namespace gapi { +namespace core { +namespace cpu { + +GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +} // namespace cpu +} // namespace core +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_CORE_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp index 86071bf7c4..eb5f784747 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/gcpukernel.hpp @@ -1,542 +1,542 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2022 Intel Corporation - - -#ifndef OPENCV_GAPI_GCPUKERNEL_HPP -#define OPENCV_GAPI_GCPUKERNEL_HPP - -#if defined _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) // "Unreachable code" on postprocess(...) call inside OCVCallHelper -#endif - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include //suppress_unused_warning -#include - -// FIXME: namespace scheme for backends? -namespace cv { - -namespace gimpl -{ - // Forward-declare an internal class - class GCPUExecutable; -} // namespace gimpl - -namespace gapi -{ -/** - * @brief This namespace contains G-API CPU backend functions, - * structures, and symbols. - */ -namespace cpu -{ - /** - * \addtogroup gapi_std_backends - * @{ - * - * @brief G-API backends available in this OpenCV version - * - * G-API backends play a corner stone role in G-API execution - * stack. Every backend is hardware-oriented and thus can run its - * kernels efficiently on the target platform. - * - * Backends are usually "black boxes" for G-API users -- on the API - * side, all backends are represented as different objects of the - * same class cv::gapi::GBackend. - * User can manipulate with backends by specifying which kernels to use. - * - * @sa @ref gapi_hld - */ - - /** - * @brief Get a reference to CPU (OpenCV) backend. - * - * This is the default backend in G-API at the moment, providing - * broader functional coverage but losing some graph model - * advantages. Provided mostly for reference and prototyping - * purposes. - * - * @sa gapi_std_backends - */ - GAPI_EXPORTS cv::gapi::GBackend backend(); - /** @} */ - - class GOCVFunctor; - - //! @cond IGNORED - template - GOCVFunctor ocv_kernel(const Callable& c); - - template - GOCVFunctor ocv_kernel(Callable& c); - //! @endcond - -} // namespace cpu -} // namespace gapi - -// Represents arguments which are passed to a wrapped CPU function -// FIXME: put into detail? -class GAPI_EXPORTS GCPUContext -{ -public: - // Generic accessor API - template - const T& inArg(int input) { return m_args.at(input).get(); } - - // Syntax sugar - const cv::Mat& inMat(int input); - cv::Mat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() - - const cv::Scalar& inVal(int input); - cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() - cv::MediaFrame& outFrame(int output); - template std::vector& outVecR(int output) // FIXME: the same issue - { - return outVecRef(output).wref(); - } - template T& outOpaqueR(int output) // FIXME: the same issue - { - return outOpaqueRef(output).wref(); - } - - GArg state() - { - return m_state; - } - -protected: - detail::VectorRef& outVecRef(int output); - detail::OpaqueRef& outOpaqueRef(int output); - - std::vector m_args; - GArg m_state; - - //FIXME: avoid conversion of arguments from internal representation to OpenCV one on each call - //to OCV kernel. (This can be achieved by a two single time conversions in GCPUExecutable::run, - //once on enter for input and output arguments, and once before return for output arguments only - std::unordered_map m_results; - - friend class gimpl::GCPUExecutable; -}; - -class GAPI_EXPORTS GCPUKernel -{ -public: - // This function is a kernel's execution entry point (does the processing work) - using RunF = std::function; - // This function is a stateful kernel's setup routine (configures state) - using SetupF = std::function; - - GCPUKernel(); - GCPUKernel(const RunF& runF, const SetupF& setupF = nullptr); - - RunF m_runF = nullptr; - SetupF m_setupF = nullptr; - - bool m_isStateful = false; -}; - -// FIXME: This is an ugly ad-hoc implementation. TODO: refactor - -namespace detail -{ -template struct get_in; -template<> struct get_in -{ - static cv::Mat get(GCPUContext &ctx, int idx) { return ctx.inMat(idx); } -}; -template<> struct get_in -{ - static cv::Mat get(GCPUContext &ctx, int idx) { return get_in::get(ctx, idx); } -}; -template<> struct get_in -{ - static cv::MediaFrame get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } -}; -template<> struct get_in -{ - static cv::Scalar get(GCPUContext &ctx, int idx) { return ctx.inVal(idx); } -}; -template struct get_in > -{ - static const std::vector& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; -template struct get_in > -{ - static const U& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; - -//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system -template struct get_in> >: public get_in> > -{ -}; - -//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system -template<> struct get_in >: public get_in > -{ -}; - -template struct get_in -{ - static T get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -struct tracked_cv_mat{ - tracked_cv_mat(cv::Mat& m) : r{m}, original_data{m.data} {} - cv::Mat r; - uchar* original_data; - - operator cv::Mat& (){ return r;} - void validate() const{ - if (r.data != original_data) - { - util::throw_error - (std::logic_error - ("OpenCV kernel output parameter was reallocated. \n" - "Incorrect meta data was provided ?")); - } - } -}; - -template -void postprocess(Outputs&... outs) -{ - struct - { - void operator()(tracked_cv_mat* bm) { bm->validate(); } - void operator()(...) { } - - } validate; - //dummy array to unfold parameter pack - int dummy[] = { 0, (validate(&outs), 0)... }; - cv::util::suppress_unused_warning(dummy); -} - -template struct get_out; -template<> struct get_out -{ - static tracked_cv_mat get(GCPUContext &ctx, int idx) - { - auto& r = ctx.outMatR(idx); - return {r}; - } -}; -template<> struct get_out -{ - static tracked_cv_mat get(GCPUContext &ctx, int idx) - { - return get_out::get(ctx, idx); - } -}; -template<> struct get_out -{ - static cv::Scalar& get(GCPUContext &ctx, int idx) - { - return ctx.outValR(idx); - } -}; -template<> struct get_out -{ - static cv::MediaFrame& get(GCPUContext &ctx, int idx) - { - return ctx.outFrame(idx); - } -}; -template struct get_out> -{ - static std::vector& get(GCPUContext &ctx, int idx) - { - return ctx.outVecR(idx); - } -}; - -//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system -template<> struct get_out >: public get_out > -{ -}; - -// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system -template struct get_out> >: public get_out> > -{ -}; - -template struct get_out> -{ - static U& get(GCPUContext &ctx, int idx) - { - return ctx.outOpaqueR(idx); - } -}; - -template -struct OCVSetupHelper; - -template -struct OCVSetupHelper> -{ - // Using 'auto' return type and 'decltype' specifier in both 'setup_impl' versions - // to check existence of required 'Impl::setup' functions. - // While 'decltype' specifier accepts expression we pass expression with 'comma-operator' - // where first operand of comma-operator is call attempt to desired 'Impl::setup' and - // the second operand is 'void()' expression. - // - // SFINAE for 'Impl::setup' which accepts compile arguments. - template - static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, - GArg &state, const GCompileArgs &compileArgs, - detail::Seq) -> - decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., - std::declval - >::type - >(), - compileArgs) - , void()) - { - // TODO: unique_ptr <-> shared_ptr conversion ? - // To check: Conversion is possible only if the state which should be passed to - // 'setup' user callback isn't required to have previous value - std::shared_ptr stPtr; - Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr, compileArgs); - state = GArg(stPtr); - } - - // SFINAE for 'Impl::setup' which doesn't accept compile arguments. - template - static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, - GArg &state, const GCompileArgs &/* compileArgs */, - detail::Seq) -> - decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., - std::declval - >::type - >() - ) - , void()) - { - // The same comment as in 'setup' above. - std::shared_ptr stPtr; - Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr); - state = GArg(stPtr); - } - - static void setup(const GMetaArgs &metaArgs, const GArgs &args, - GArg& state, const GCompileArgs &compileArgs) - { - setup_impl(metaArgs, args, state, compileArgs, - typename detail::MkSeq::type()); - } -}; - -// OCVCallHelper is a helper class to call stateless OCV kernels and OCV kernel functors. -template -struct OCVCallHelper; - -// FIXME: probably can be simplified with std::apply or analogue. -template -struct OCVCallHelper, std::tuple> -{ - template - struct call_and_postprocess - { - template - static void call(Inputs&&... ins, Outputs&&... outs) - { - //not using a std::forward on outs is deliberate in order to - //cause compilation error, by trying to bind rvalue references to lvalue references - Impl::run(std::forward(ins)..., outs...); - postprocess(outs...); - } - - template - static void call(Impl& impl, Inputs&&... ins, Outputs&&... outs) - { - impl(std::forward(ins)..., outs...); - } - }; - - template - static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) - { - //Make sure that OpenCV kernels do not reallocate memory for output parameters - //by comparing it's state (data ptr) before and after the call. - //This is done by converting each output Mat into tracked_cv_mat object, and binding - //them to parameters of ad-hoc function - call_and_postprocess::get(ctx, IIs))...> - ::call(get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); - } - - template - static void call_impl(cv::GCPUContext &ctx, Impl& impl, - detail::Seq, detail::Seq) - { - call_and_postprocess::get(ctx, IIs))...> - ::call(impl, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); - } - - static void call(GCPUContext &ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } - - // NB: Same as call but calling the object - // This necessary for kernel implementations that have a state - // and are represented as an object - static void callFunctor(cv::GCPUContext &ctx, Impl& impl) - { - call_impl(ctx, impl, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -// OCVStCallHelper is a helper class to call stateful OCV kernels. -template -struct OCVStCallHelper; - -template -struct OCVStCallHelper, std::tuple> : - OCVCallHelper, std::tuple> -{ - template - struct call_and_postprocess - { - template - static void call(typename Impl::State& st, Inputs&&... ins, Outputs&&... outs) - { - Impl::run(std::forward(ins)..., outs..., st); - postprocess(outs...); - } - }; - - template - static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) - { - auto& st = *ctx.state().get>(); - call_and_postprocess::get(ctx, IIs))...> - ::call(st, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); - } - - static void call(GCPUContext &ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -} // namespace detail - -template -class GCPUKernelImpl: public cv::detail::KernelTag -{ - using CallHelper = cv::detail::OCVCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } - static cv::GCPUKernel kernel() { return GCPUKernel(&CallHelper::call); } -}; - -template -class GCPUStKernelImpl: public cv::detail::KernelTag -{ - using StSetupHelper = detail::OCVSetupHelper; - using StCallHelper = detail::OCVStCallHelper; - -public: - using API = K; - using State = S; - - static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } - static cv::GCPUKernel kernel() { return GCPUKernel(&StCallHelper::call, - &StSetupHelper::setup); } -}; - -#define GAPI_OCV_KERNEL(Name, API) struct Name: public cv::GCPUKernelImpl - -// TODO: Reuse Anatoliy's logic for support of types with commas in macro. -// Retrieve the common part from Anatoliy's logic to the separate place. -#define GAPI_OCV_KERNEL_ST(Name, API, State) \ - struct Name: public cv::GCPUStKernelImpl \ - -/// @private -class gapi::cpu::GOCVFunctor : public gapi::GFunctor -{ -public: - using Impl = std::function; - using Meta = cv::GKernel::M; - - GOCVFunctor(const char* id, const Meta &meta, const Impl& impl) - : gapi::GFunctor(id), impl_{GCPUKernel(impl), meta} - { - } - - GKernelImpl impl() const override { return impl_; } - gapi::GBackend backend() const override { return gapi::cpu::backend(); } - -private: - GKernelImpl impl_; -}; - -//! @cond IGNORED -template -gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(Callable& c) -{ - using P = cv::detail::OCVCallHelper; - return GOCVFunctor{ K::id() - , &K::getOutMeta - , std::bind(&P::callFunctor, std::placeholders::_1, std::ref(c)) - }; -} - -template -gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(const Callable& c) -{ - using P = cv::detail::OCVCallHelper; - return GOCVFunctor{ K::id() - , &K::getOutMeta - , std::bind(&P::callFunctor, std::placeholders::_1, c) - }; -} -//! @endcond - -} // namespace cv - -#if defined _MSC_VER -#pragma warning(pop) -#endif - -#endif // OPENCV_GAPI_GCPUKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2022 Intel Corporation + + +#ifndef OPENCV_GAPI_GCPUKERNEL_HPP +#define OPENCV_GAPI_GCPUKERNEL_HPP + +#if defined _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) // "Unreachable code" on postprocess(...) call inside OCVCallHelper +#endif + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include //suppress_unused_warning +#include + +// FIXME: namespace scheme for backends? +namespace cv { + +namespace gimpl +{ + // Forward-declare an internal class + class GCPUExecutable; +} // namespace gimpl + +namespace gapi +{ +/** + * @brief This namespace contains G-API CPU backend functions, + * structures, and symbols. + */ +namespace cpu +{ + /** + * \addtogroup gapi_std_backends + * @{ + * + * @brief G-API backends available in this OpenCV version + * + * G-API backends play a corner stone role in G-API execution + * stack. Every backend is hardware-oriented and thus can run its + * kernels efficiently on the target platform. + * + * Backends are usually "black boxes" for G-API users -- on the API + * side, all backends are represented as different objects of the + * same class cv::gapi::GBackend. + * User can manipulate with backends by specifying which kernels to use. + * + * @sa @ref gapi_hld + */ + + /** + * @brief Get a reference to CPU (OpenCV) backend. + * + * This is the default backend in G-API at the moment, providing + * broader functional coverage but losing some graph model + * advantages. Provided mostly for reference and prototyping + * purposes. + * + * @sa gapi_std_backends + */ + GAPI_EXPORTS cv::gapi::GBackend backend(); + /** @} */ + + class GOCVFunctor; + + //! @cond IGNORED + template + GOCVFunctor ocv_kernel(const Callable& c); + + template + GOCVFunctor ocv_kernel(Callable& c); + //! @endcond + +} // namespace cpu +} // namespace gapi + +// Represents arguments which are passed to a wrapped CPU function +// FIXME: put into detail? +class GAPI_EXPORTS GCPUContext +{ +public: + // Generic accessor API + template + const T& inArg(int input) { return m_args.at(input).get(); } + + // Syntax sugar + const cv::Mat& inMat(int input); + cv::Mat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() + + const cv::Scalar& inVal(int input); + cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() + cv::MediaFrame& outFrame(int output); + template std::vector& outVecR(int output) // FIXME: the same issue + { + return outVecRef(output).wref(); + } + template T& outOpaqueR(int output) // FIXME: the same issue + { + return outOpaqueRef(output).wref(); + } + + GArg state() + { + return m_state; + } + +protected: + detail::VectorRef& outVecRef(int output); + detail::OpaqueRef& outOpaqueRef(int output); + + std::vector m_args; + GArg m_state; + + //FIXME: avoid conversion of arguments from internal representation to OpenCV one on each call + //to OCV kernel. (This can be achieved by a two single time conversions in GCPUExecutable::run, + //once on enter for input and output arguments, and once before return for output arguments only + std::unordered_map m_results; + + friend class gimpl::GCPUExecutable; +}; + +class GAPI_EXPORTS GCPUKernel +{ +public: + // This function is a kernel's execution entry point (does the processing work) + using RunF = std::function; + // This function is a stateful kernel's setup routine (configures state) + using SetupF = std::function; + + GCPUKernel(); + GCPUKernel(const RunF& runF, const SetupF& setupF = nullptr); + + RunF m_runF = nullptr; + SetupF m_setupF = nullptr; + + bool m_isStateful = false; +}; + +// FIXME: This is an ugly ad-hoc implementation. TODO: refactor + +namespace detail +{ +template struct get_in; +template<> struct get_in +{ + static cv::Mat get(GCPUContext &ctx, int idx) { return ctx.inMat(idx); } +}; +template<> struct get_in +{ + static cv::Mat get(GCPUContext &ctx, int idx) { return get_in::get(ctx, idx); } +}; +template<> struct get_in +{ + static cv::MediaFrame get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } +}; +template<> struct get_in +{ + static cv::Scalar get(GCPUContext &ctx, int idx) { return ctx.inVal(idx); } +}; +template struct get_in > +{ + static const std::vector& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; +template struct get_in > +{ + static const U& get(GCPUContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; + +//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system +template struct get_in> >: public get_in> > +{ +}; + +//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +//FIXME(dm): GOpaque/GOpaque conversion should be done more gracefully in the system +template<> struct get_in >: public get_in > +{ +}; + +template struct get_in +{ + static T get(GCPUContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +struct tracked_cv_mat{ + tracked_cv_mat(cv::Mat& m) : r{m}, original_data{m.data} {} + cv::Mat r; + uchar* original_data; + + operator cv::Mat& (){ return r;} + void validate() const{ + if (r.data != original_data) + { + util::throw_error + (std::logic_error + ("OpenCV kernel output parameter was reallocated. \n" + "Incorrect meta data was provided ?")); + } + } +}; + +template +void postprocess(Outputs&... outs) +{ + struct + { + void operator()(tracked_cv_mat* bm) { bm->validate(); } + void operator()(...) { } + + } validate; + //dummy array to unfold parameter pack + int dummy[] = { 0, (validate(&outs), 0)... }; + cv::util::suppress_unused_warning(dummy); +} + +template struct get_out; +template<> struct get_out +{ + static tracked_cv_mat get(GCPUContext &ctx, int idx) + { + auto& r = ctx.outMatR(idx); + return {r}; + } +}; +template<> struct get_out +{ + static tracked_cv_mat get(GCPUContext &ctx, int idx) + { + return get_out::get(ctx, idx); + } +}; +template<> struct get_out +{ + static cv::Scalar& get(GCPUContext &ctx, int idx) + { + return ctx.outValR(idx); + } +}; +template<> struct get_out +{ + static cv::MediaFrame& get(GCPUContext &ctx, int idx) + { + return ctx.outFrame(idx); + } +}; +template struct get_out> +{ + static std::vector& get(GCPUContext &ctx, int idx) + { + return ctx.outVecR(idx); + } +}; + +//FIXME(dm): GArray/GArray conversion should be done more gracefully in the system +template<> struct get_out >: public get_out > +{ +}; + +// FIXME(dm): GArray>/GArray> conversion should be done more gracefully in the system +template struct get_out> >: public get_out> > +{ +}; + +template struct get_out> +{ + static U& get(GCPUContext &ctx, int idx) + { + return ctx.outOpaqueR(idx); + } +}; + +template +struct OCVSetupHelper; + +template +struct OCVSetupHelper> +{ + // Using 'auto' return type and 'decltype' specifier in both 'setup_impl' versions + // to check existence of required 'Impl::setup' functions. + // While 'decltype' specifier accepts expression we pass expression with 'comma-operator' + // where first operand of comma-operator is call attempt to desired 'Impl::setup' and + // the second operand is 'void()' expression. + // + // SFINAE for 'Impl::setup' which accepts compile arguments. + template + static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, + GArg &state, const GCompileArgs &compileArgs, + detail::Seq) -> + decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., + std::declval + >::type + >(), + compileArgs) + , void()) + { + // TODO: unique_ptr <-> shared_ptr conversion ? + // To check: Conversion is possible only if the state which should be passed to + // 'setup' user callback isn't required to have previous value + std::shared_ptr stPtr; + Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr, compileArgs); + state = GArg(stPtr); + } + + // SFINAE for 'Impl::setup' which doesn't accept compile arguments. + template + static auto setup_impl(const GMetaArgs &metaArgs, const GArgs &args, + GArg &state, const GCompileArgs &/* compileArgs */, + detail::Seq) -> + decltype(Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., + std::declval + >::type + >() + ) + , void()) + { + // The same comment as in 'setup' above. + std::shared_ptr stPtr; + Impl::setup(detail::get_in_meta(metaArgs, args, IIs)..., stPtr); + state = GArg(stPtr); + } + + static void setup(const GMetaArgs &metaArgs, const GArgs &args, + GArg& state, const GCompileArgs &compileArgs) + { + setup_impl(metaArgs, args, state, compileArgs, + typename detail::MkSeq::type()); + } +}; + +// OCVCallHelper is a helper class to call stateless OCV kernels and OCV kernel functors. +template +struct OCVCallHelper; + +// FIXME: probably can be simplified with std::apply or analogue. +template +struct OCVCallHelper, std::tuple> +{ + template + struct call_and_postprocess + { + template + static void call(Inputs&&... ins, Outputs&&... outs) + { + //not using a std::forward on outs is deliberate in order to + //cause compilation error, by trying to bind rvalue references to lvalue references + Impl::run(std::forward(ins)..., outs...); + postprocess(outs...); + } + + template + static void call(Impl& impl, Inputs&&... ins, Outputs&&... outs) + { + impl(std::forward(ins)..., outs...); + } + }; + + template + static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) + { + //Make sure that OpenCV kernels do not reallocate memory for output parameters + //by comparing it's state (data ptr) before and after the call. + //This is done by converting each output Mat into tracked_cv_mat object, and binding + //them to parameters of ad-hoc function + call_and_postprocess::get(ctx, IIs))...> + ::call(get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); + } + + template + static void call_impl(cv::GCPUContext &ctx, Impl& impl, + detail::Seq, detail::Seq) + { + call_and_postprocess::get(ctx, IIs))...> + ::call(impl, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); + } + + static void call(GCPUContext &ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } + + // NB: Same as call but calling the object + // This necessary for kernel implementations that have a state + // and are represented as an object + static void callFunctor(cv::GCPUContext &ctx, Impl& impl) + { + call_impl(ctx, impl, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +// OCVStCallHelper is a helper class to call stateful OCV kernels. +template +struct OCVStCallHelper; + +template +struct OCVStCallHelper, std::tuple> : + OCVCallHelper, std::tuple> +{ + template + struct call_and_postprocess + { + template + static void call(typename Impl::State& st, Inputs&&... ins, Outputs&&... outs) + { + Impl::run(std::forward(ins)..., outs..., st); + postprocess(outs...); + } + }; + + template + static void call_impl(GCPUContext &ctx, detail::Seq, detail::Seq) + { + auto& st = *ctx.state().get>(); + call_and_postprocess::get(ctx, IIs))...> + ::call(st, get_in::get(ctx, IIs)..., get_out::get(ctx, OIs)...); + } + + static void call(GCPUContext &ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +} // namespace detail + +template +class GCPUKernelImpl: public cv::detail::KernelTag +{ + using CallHelper = cv::detail::OCVCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } + static cv::GCPUKernel kernel() { return GCPUKernel(&CallHelper::call); } +}; + +template +class GCPUStKernelImpl: public cv::detail::KernelTag +{ + using StSetupHelper = detail::OCVSetupHelper; + using StCallHelper = detail::OCVStCallHelper; + +public: + using API = K; + using State = S; + + static cv::gapi::GBackend backend() { return cv::gapi::cpu::backend(); } + static cv::GCPUKernel kernel() { return GCPUKernel(&StCallHelper::call, + &StSetupHelper::setup); } +}; + +#define GAPI_OCV_KERNEL(Name, API) struct Name: public cv::GCPUKernelImpl + +// TODO: Reuse Anatoliy's logic for support of types with commas in macro. +// Retrieve the common part from Anatoliy's logic to the separate place. +#define GAPI_OCV_KERNEL_ST(Name, API, State) \ + struct Name: public cv::GCPUStKernelImpl \ + +/// @private +class gapi::cpu::GOCVFunctor : public gapi::GFunctor +{ +public: + using Impl = std::function; + using Meta = cv::GKernel::M; + + GOCVFunctor(const char* id, const Meta &meta, const Impl& impl) + : gapi::GFunctor(id), impl_{GCPUKernel(impl), meta} + { + } + + GKernelImpl impl() const override { return impl_; } + gapi::GBackend backend() const override { return gapi::cpu::backend(); } + +private: + GKernelImpl impl_; +}; + +//! @cond IGNORED +template +gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(Callable& c) +{ + using P = cv::detail::OCVCallHelper; + return GOCVFunctor{ K::id() + , &K::getOutMeta + , std::bind(&P::callFunctor, std::placeholders::_1, std::ref(c)) + }; +} + +template +gapi::cpu::GOCVFunctor gapi::cpu::ocv_kernel(const Callable& c) +{ + using P = cv::detail::OCVCallHelper; + return GOCVFunctor{ K::id() + , &K::getOutMeta + , std::bind(&P::callFunctor, std::placeholders::_1, c) + }; +} +//! @endcond + +} // namespace cv + +#if defined _MSC_VER +#pragma warning(pop) +#endif + +#endif // OPENCV_GAPI_GCPUKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp index 4001a77d3b..0b96db08ae 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/imgproc.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CPU_IMGPROC_API_HPP -#define OPENCV_GAPI_CPU_IMGPROC_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace imgproc { -namespace cpu { - -GAPI_EXPORTS GKernelPackage kernels(); - -} // namespace cpu -} // namespace imgproc -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_IMGPROC_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CPU_IMGPROC_API_HPP +#define OPENCV_GAPI_CPU_IMGPROC_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace imgproc { +namespace cpu { + +GAPI_EXPORTS GKernelPackage kernels(); + +} // namespace cpu +} // namespace imgproc +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_IMGPROC_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp index 047e935716..03dbe904cc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/ot.hpp @@ -1,29 +1,29 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CPU_OT_API_HPP -#define OPENCV_GAPI_CPU_OT_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -/** - * @brief This namespace contains G-API Operation Types for - * VAS Object Tracking module functionality. - */ -namespace ot { -namespace cpu { -GAPI_EXPORTS_W GKernelPackage kernels(); -} // namespace cpu -} // namespace ot -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_OT_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CPU_OT_API_HPP +#define OPENCV_GAPI_CPU_OT_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +/** + * @brief This namespace contains G-API Operation Types for + * VAS Object Tracking module functionality. + */ +namespace ot { +namespace cpu { +GAPI_EXPORTS_W GKernelPackage kernels(); +} // namespace cpu +} // namespace ot +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_OT_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp index 9a8109c34e..e2a2242bd0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/stereo.hpp @@ -1,48 +1,48 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_CPU_STEREO_API_HPP -#define OPENCV_GAPI_CPU_STEREO_API_HPP - -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace calib3d { -namespace cpu { - -GAPI_EXPORTS GKernelPackage kernels(); - -/** @brief Structure for the Stereo operation initialization parameters.*/ -struct GAPI_EXPORTS StereoInitParam { - StereoInitParam(int nD, int bS, double bL, double f): - numDisparities(nD), blockSize(bS), baseline(bL), focus(f) {} - - StereoInitParam() = default; - - int numDisparities = 0; - int blockSize = 21; - double baseline = 63.5; - double focus = 3.6; -}; - -} // namespace cpu -} // namespace calib3d -} // namespace gapi - -namespace detail { - - template<> struct CompileArgTag { - static const char* tag() { - return "org.opencv.stereoInit"; - } -}; - -} // namespace detail -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_STEREO_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_CPU_STEREO_API_HPP +#define OPENCV_GAPI_CPU_STEREO_API_HPP + +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace calib3d { +namespace cpu { + +GAPI_EXPORTS GKernelPackage kernels(); + +/** @brief Structure for the Stereo operation initialization parameters.*/ +struct GAPI_EXPORTS StereoInitParam { + StereoInitParam(int nD, int bS, double bL, double f): + numDisparities(nD), blockSize(bS), baseline(bL), focus(f) {} + + StereoInitParam() = default; + + int numDisparities = 0; + int blockSize = 21; + double baseline = 63.5; + double focus = 3.6; +}; + +} // namespace cpu +} // namespace calib3d +} // namespace gapi + +namespace detail { + + template<> struct CompileArgTag { + static const char* tag() { + return "org.opencv.stereoInit"; + } +}; + +} // namespace detail +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_STEREO_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp index 934822456e..d3c1f2e670 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/cpu/video.hpp @@ -1,25 +1,25 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_CPU_VIDEO_API_HPP -#define OPENCV_GAPI_CPU_VIDEO_API_HPP - -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace video { -namespace cpu { - -GAPI_EXPORTS GKernelPackage kernels(); - -} // namespace cpu -} // namespace video -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_CPU_VIDEO_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_CPU_VIDEO_API_HPP +#define OPENCV_GAPI_CPU_VIDEO_API_HPP + +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace video { +namespace cpu { + +GAPI_EXPORTS GKernelPackage kernels(); + +} // namespace cpu +} // namespace video +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_CPU_VIDEO_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp index 634a3a85d0..a4329d6f50 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/core.hpp @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_CORE_HPP -#define OPENCV_GAPI_FLUID_CORE_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { namespace gapi { namespace core { namespace fluid { - -GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -}}}} - -#endif // OPENCV_GAPI_FLUID_CORE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_CORE_HPP +#define OPENCV_GAPI_FLUID_CORE_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { namespace gapi { namespace core { namespace fluid { + +GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +}}}} + +#endif // OPENCV_GAPI_FLUID_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp index 2efd98b50e..551f0a398f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidbuffer.hpp @@ -1,154 +1,154 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_BUFFER_HPP -#define OPENCV_GAPI_FLUID_BUFFER_HPP - -#include -#include // accumulate -#include // ostream -#include // uint8_t - -#include -#include - -#include - -namespace cv { -namespace gapi { -namespace fluid { - -struct Border -{ - // This constructor is required to support existing kernels which are part of G-API - Border(int _type, cv::Scalar _val) : type(_type), value(_val) {} - - int type; - cv::Scalar value; -}; - -using BorderOpt = util::optional; - -bool operator == (const Border& b1, const Border& b2); - -class GAPI_EXPORTS Buffer; - -class GAPI_EXPORTS View -{ -public: - struct Cache - { - std::vector m_linePtrs; - GMatDesc m_desc; - int m_border_size = 0; - - inline const uint8_t* linePtr(int index) const - { - // "out_of_window" check: - // user must not request the lines which are outside of specified kernel window - GAPI_DbgAssert(index >= -m_border_size - && index < -m_border_size + static_cast(m_linePtrs.size())); - return m_linePtrs[index + m_border_size]; - } - }; - - const inline uint8_t* InLineB(int index) const // -(w-1)/2...0...+(w-1)/2 for Filters - { - return m_cache->linePtr(index); - } - - template const inline T* InLine(int i) const - { - const uint8_t* ptr = this->InLineB(i); - return reinterpret_cast(ptr); - } - - inline operator bool() const { return m_priv != nullptr; } - bool ready() const; - inline int length() const { return m_cache->m_desc.size.width; } - int y() const; - - inline const GMatDesc& meta() const { return m_cache->m_desc; } - - class GAPI_EXPORTS Priv; // internal use only - Priv& priv(); // internal use only - const Priv& priv() const; // internal use only - - View(); - View(std::unique_ptr&& p); - View(View&& v); - View& operator=(View&& v); - ~View(); - -private: - std::unique_ptr m_priv; - const Cache* m_cache = nullptr; -}; - -class GAPI_EXPORTS Buffer -{ -public: - struct Cache - { - std::vector m_linePtrs; - GMatDesc m_desc; - }; - - // Default constructor (executable creation stage, - // all following initialization performed in Priv::init()) - Buffer(); - // Scratch constructor (user kernels) - Buffer(const cv::GMatDesc &desc); - - // Constructor for intermediate buffers (for tests) - Buffer(const cv::GMatDesc &desc, - int max_line_consumption, int border_size, - int skew, - int wlpi, - BorderOpt border); - // Constructor for in/out buffers (for tests) - Buffer(const cv::Mat &data, bool is_input); - ~Buffer(); - Buffer& operator=(Buffer&&); - - inline uint8_t* OutLineB(int index = 0) - { - return m_cache->m_linePtrs[index]; - } - - template inline T* OutLine(int index = 0) - { - uint8_t* ptr = this->OutLineB(index); - return reinterpret_cast(ptr); - } - - int y() const; - - int linesReady() const; - void debug(std::ostream &os) const; - inline int length() const { return m_cache->m_desc.size.width; } - int lpi() const; // LPI for WRITER - - inline const GMatDesc& meta() const { return m_cache->m_desc; } - - View mkView(int borderSize, bool ownStorage); - void addView(const View* v); - - class GAPI_EXPORTS Priv; // internal use only - Priv& priv(); // internal use only - const Priv& priv() const; // internal use only - -private: - std::unique_ptr m_priv; - const Cache* m_cache; -}; - -} // namespace cv::gapi::fluid -} // namespace cv::gapi -} // namespace cv - -#endif // OPENCV_GAPI_FLUID_BUFFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_BUFFER_HPP +#define OPENCV_GAPI_FLUID_BUFFER_HPP + +#include +#include // accumulate +#include // ostream +#include // uint8_t + +#include +#include + +#include + +namespace cv { +namespace gapi { +namespace fluid { + +struct Border +{ + // This constructor is required to support existing kernels which are part of G-API + Border(int _type, cv::Scalar _val) : type(_type), value(_val) {} + + int type; + cv::Scalar value; +}; + +using BorderOpt = util::optional; + +bool operator == (const Border& b1, const Border& b2); + +class GAPI_EXPORTS Buffer; + +class GAPI_EXPORTS View +{ +public: + struct Cache + { + std::vector m_linePtrs; + GMatDesc m_desc; + int m_border_size = 0; + + inline const uint8_t* linePtr(int index) const + { + // "out_of_window" check: + // user must not request the lines which are outside of specified kernel window + GAPI_DbgAssert(index >= -m_border_size + && index < -m_border_size + static_cast(m_linePtrs.size())); + return m_linePtrs[index + m_border_size]; + } + }; + + const inline uint8_t* InLineB(int index) const // -(w-1)/2...0...+(w-1)/2 for Filters + { + return m_cache->linePtr(index); + } + + template const inline T* InLine(int i) const + { + const uint8_t* ptr = this->InLineB(i); + return reinterpret_cast(ptr); + } + + inline operator bool() const { return m_priv != nullptr; } + bool ready() const; + inline int length() const { return m_cache->m_desc.size.width; } + int y() const; + + inline const GMatDesc& meta() const { return m_cache->m_desc; } + + class GAPI_EXPORTS Priv; // internal use only + Priv& priv(); // internal use only + const Priv& priv() const; // internal use only + + View(); + View(std::unique_ptr&& p); + View(View&& v); + View& operator=(View&& v); + ~View(); + +private: + std::unique_ptr m_priv; + const Cache* m_cache = nullptr; +}; + +class GAPI_EXPORTS Buffer +{ +public: + struct Cache + { + std::vector m_linePtrs; + GMatDesc m_desc; + }; + + // Default constructor (executable creation stage, + // all following initialization performed in Priv::init()) + Buffer(); + // Scratch constructor (user kernels) + Buffer(const cv::GMatDesc &desc); + + // Constructor for intermediate buffers (for tests) + Buffer(const cv::GMatDesc &desc, + int max_line_consumption, int border_size, + int skew, + int wlpi, + BorderOpt border); + // Constructor for in/out buffers (for tests) + Buffer(const cv::Mat &data, bool is_input); + ~Buffer(); + Buffer& operator=(Buffer&&); + + inline uint8_t* OutLineB(int index = 0) + { + return m_cache->m_linePtrs[index]; + } + + template inline T* OutLine(int index = 0) + { + uint8_t* ptr = this->OutLineB(index); + return reinterpret_cast(ptr); + } + + int y() const; + + int linesReady() const; + void debug(std::ostream &os) const; + inline int length() const { return m_cache->m_desc.size.width; } + int lpi() const; // LPI for WRITER + + inline const GMatDesc& meta() const { return m_cache->m_desc; } + + View mkView(int borderSize, bool ownStorage); + void addView(const View* v); + + class GAPI_EXPORTS Priv; // internal use only + Priv& priv(); // internal use only + const Priv& priv() const; // internal use only + +private: + std::unique_ptr m_priv; + const Cache* m_cache; +}; + +} // namespace cv::gapi::fluid +} // namespace cv::gapi +} // namespace cv + +#endif // OPENCV_GAPI_FLUID_BUFFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp index 87d42a6fc5..c3ae9dfdd6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/gfluidkernel.hpp @@ -1,442 +1,442 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_KERNEL_HPP -#define OPENCV_GAPI_FLUID_KERNEL_HPP - -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -// FIXME: namespace scheme for backends? -namespace cv { - -namespace gapi -{ -/** - * @brief This namespace contains G-API Fluid backend functions, structures, and symbols. - */ -namespace fluid -{ - /** - * \addtogroup gapi_std_backends G-API Standard Backends - * @{ - */ - /** - * @brief Get a reference to Fluid backend. - * - * @sa gapi_std_backends - */ - GAPI_EXPORTS cv::gapi::GBackend backend(); - /** @} */ -} // namespace fluid -} // namespace gapi - - -class GAPI_EXPORTS GFluidKernel -{ -public: - enum class Kind - { - Filter, - Resize, - YUV420toRGB //Color conversion of 4:2:0 chroma sub-sampling formats (NV12, I420 ..etc) to RGB - }; - - // This function is a generic "doWork" callback - using F = std::function &)>; - - // This function is a generic "initScratch" callback - using IS = std::function; - - // This function is a generic "resetScratch" callback - using RS = std::function; - - // This function describes kernel metadata inference rule. - using M = std::function; - - // This function is a generic "getBorder" callback (extracts border-related data from kernel's input parameters) - using B = std::function; - - // This function is a generic "getWindow" callback (extracts window-related data from kernel's input parameters) - using GW = std::function; - - // FIXME: move implementations out of header file - GFluidKernel() {} - GFluidKernel(Kind k, int l, bool scratch, const F& f, const IS &is, const RS &rs, const B& b, const GW& win) - : m_kind(k) - , m_lpi(l) - , m_scratch(scratch) - , m_f(f) - , m_is(is) - , m_rs(rs) - , m_b(b) - , m_gw(win) {} - - Kind m_kind; - const int m_lpi = -1; - const bool m_scratch = false; - - const F m_f; - const IS m_is; - const RS m_rs; - const B m_b; - const GW m_gw; -}; - -// FIXME!!! -// This is the temporary and experimental API -// which should be replaced by runtime roi-based scheduling -/** \addtogroup gapi_compile_args - * @{ - */ -/** - * @brief This structure allows to control the output image region - * which Fluid backend will produce in the graph. - * - * This feature is useful for external tiling and parallelism, but - * will be deprecated in the future releases. - */ -struct GFluidOutputRois -{ - std::vector rois; -}; - -/** - * @brief This structure forces Fluid backend to generate multiple - * parallel output regions in the graph. These regions execute in parallel. - * - * This feature may be deprecated in the future releases. - */ -struct GFluidParallelOutputRois -{ - std::vector parallel_rois; -}; - -/** - * @brief This structure allows to customize the way how Fluid executes - * parallel regions. - * - * For example, user can utilize his own threading runtime via this parameter. - * The `parallel_for` member functor is called by the Fluid runtime with the - * following arguments: - * - * @param size Size of the parallel range to process - * @param f A function which should be called for every integer index - * in this range by the specified parallel_for implementation. - * - * This feature may be deprecated in the future releases. - */ -struct GFluidParallelFor -{ - //this function accepts: - // - size of the "parallel" range as the first argument - // - and a function to be called on the range items, designated by item index - std::function)> parallel_for; -}; -/** @} gapi_compile_args */ - -namespace detail -{ -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.fluid.outputRois"; } -}; - -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.fluid.parallelFor"; } -}; - -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.fluid.parallelOutputRois"; } -}; - -} // namespace detail - -namespace detail -{ -template struct fluid_get_in; -template<> struct fluid_get_in -{ - static const cv::gapi::fluid::View& get(const cv::GArgs &in_args, int idx) - { - return *in_args[idx].unsafe_get(); - } -}; - -template<> struct fluid_get_in -{ - // FIXME: change to return by reference when moved to own::Scalar - static cv::Scalar get(const cv::GArgs &in_args, int idx) - { - return in_args[idx].unsafe_get(); - } -}; - -template struct fluid_get_in> -{ - static const std::vector& get(const cv::GArgs &in_args, int idx) - { - return in_args.at(idx).unsafe_get().rref(); - } -}; - -template struct fluid_get_in> -{ - static const U& get(const cv::GArgs &in_args, int idx) - { - return in_args.at(idx).unsafe_get().rref(); - } -}; - -template struct fluid_get_in -{ - static const T& get(const cv::GArgs &in_args, int idx) - { - return in_args[idx].unsafe_get(); - } -}; - -template -struct scratch_helper; - -template -struct scratch_helper -{ - // Init - template - static void help_init_impl(const cv::GMetaArgs &metas, - const cv::GArgs &in_args, - gapi::fluid::Buffer &scratch_buf, - detail::Seq) - { - Impl::initScratch(get_in_meta(metas, in_args, IIs)..., scratch_buf); - } - - static void help_init(const cv::GMetaArgs &metas, - const cv::GArgs &in_args, - gapi::fluid::Buffer &b) - { - help_init_impl(metas, in_args, b, typename detail::MkSeq::type()); - } - - // Reset - static void help_reset(gapi::fluid::Buffer &b) - { - Impl::resetScratch(b); - } -}; - -template -struct scratch_helper -{ - static void help_init(const cv::GMetaArgs &, - const cv::GArgs &, - gapi::fluid::Buffer &) - { - GAPI_Error("InternalError"); - } - static void help_reset(gapi::fluid::Buffer &) - { - GAPI_Error("InternalError"); - } -}; - -template struct is_gmat_type -{ - static const constexpr bool value = std::is_same::value; -}; - -template -struct get_border_helper; - -template -struct get_border_helper -{ - template - static gapi::fluid::BorderOpt get_border_impl(const GMetaArgs &metas, - const cv::GArgs &in_args, - cv::detail::Seq) - { - return util::make_optional(Impl::getBorder(cv::detail::get_in_meta(metas, in_args, IIs)...)); - } - - static gapi::fluid::BorderOpt help(const GMetaArgs &metas, - const cv::GArgs &in_args) - { - return get_border_impl(metas, in_args, typename detail::MkSeq::type()); - } -}; - -template -struct get_border_helper -{ - static gapi::fluid::BorderOpt help(const cv::GMetaArgs &, - const cv::GArgs &) - { - return {}; - } -}; - -template -struct get_window_helper; - -template -struct get_window_helper -{ - template - static int get_window_impl(const GMetaArgs &metas, - const cv::GArgs &in_args, - cv::detail::Seq) - { - return Impl::getWindow(cv::detail::get_in_meta(metas, in_args, IIs)...); - } - - static int help(const GMetaArgs &metas, const cv::GArgs &in_args) - { - return get_window_impl(metas, in_args, typename detail::MkSeq::type()); - } -}; - -template -struct get_window_helper -{ - static int help(const cv::GMetaArgs &, - const cv::GArgs &) - { - return Impl::Window; - } -}; - -template -struct has_Window -{ -private: - template - static constexpr auto Check(U*) -> typename std::is_same::type; - - template - static constexpr std::false_type Check(...); - - typedef decltype(Check(0)) Result; - -public: - static constexpr bool value = Result::value; -}; - -template -struct callCustomGetBorder; - -template -struct callCustomGetBorder -{ - static constexpr bool value = (Impl::Window != 1); -}; - -template -struct callCustomGetBorder -{ - static constexpr bool value = true; -}; - -template -struct FluidCallHelper; - -template -struct FluidCallHelper, std::tuple, UseScratch> -{ - static_assert(all_satisfy::value, "return type must be GMat"); - static_assert(contains::value, "input must contain at least one GMat"); - - // Execution dispatcher //////////////////////////////////////////////////// - template - static void call_impl(const cv::GArgs &in_args, - const std::vector &out_bufs, - detail::Seq, - detail::Seq) - { - Impl::run(fluid_get_in::get(in_args, IIs)..., *out_bufs[OIs]...); - } - - static void call(const cv::GArgs &in_args, - const std::vector &out_bufs) - { - constexpr int numOuts = (sizeof...(Outs)) + (UseScratch ? 1 : 0); - call_impl(in_args, out_bufs, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } - - // Scratch buffer initialization dispatcher //////////////////////////////// - static void init_scratch(const GMetaArgs &metas, - const cv::GArgs &in_args, - gapi::fluid::Buffer &b) - { - scratch_helper::help_init(metas, in_args, b); - } - - // Scratch buffer reset dispatcher ///////////////////////////////////////// - static void reset_scratch(gapi::fluid::Buffer &scratch_buf) - { - scratch_helper::help_reset(scratch_buf); - } - - static gapi::fluid::BorderOpt getBorder(const GMetaArgs &metas, const cv::GArgs &in_args) - { - constexpr bool hasWindow = has_Window::value; - - // User must provide "init" callback if Window != 1 - // TODO: move to constexpr if when we enable C++17 - return get_border_helper::value, Impl, Ins...>::help(metas, in_args); - } - - static int getWindow(const GMetaArgs &metas, const cv::GArgs &in_args) - { - constexpr bool callCustomGetWindow = !(has_Window::value); - return get_window_helper::help(metas, in_args); - } -}; -} // namespace detail - - -template -class GFluidKernelImpl : public cv::detail::KernelTag -{ - static const int LPI = 1; - static const auto Kind = GFluidKernel::Kind::Filter; - using P = detail::FluidCallHelper; - -public: - using API = K; - - static GFluidKernel kernel() - { - // FIXME: call() and getOutMeta() needs to be renamed so it is clear these - // functions are internal wrappers, not user API - return GFluidKernel(Impl::Kind, Impl::LPI, - UseScratch, - &P::call, &P::init_scratch, &P::reset_scratch, &P::getBorder, &P::getWindow); - } - - static cv::gapi::GBackend backend() { return cv::gapi::fluid::backend(); } -}; - -#define GAPI_FLUID_KERNEL(Name, API, Scratch) struct Name: public cv::GFluidKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GCPUKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_KERNEL_HPP +#define OPENCV_GAPI_FLUID_KERNEL_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +// FIXME: namespace scheme for backends? +namespace cv { + +namespace gapi +{ +/** + * @brief This namespace contains G-API Fluid backend functions, structures, and symbols. + */ +namespace fluid +{ + /** + * \addtogroup gapi_std_backends G-API Standard Backends + * @{ + */ + /** + * @brief Get a reference to Fluid backend. + * + * @sa gapi_std_backends + */ + GAPI_EXPORTS cv::gapi::GBackend backend(); + /** @} */ +} // namespace fluid +} // namespace gapi + + +class GAPI_EXPORTS GFluidKernel +{ +public: + enum class Kind + { + Filter, + Resize, + YUV420toRGB //Color conversion of 4:2:0 chroma sub-sampling formats (NV12, I420 ..etc) to RGB + }; + + // This function is a generic "doWork" callback + using F = std::function &)>; + + // This function is a generic "initScratch" callback + using IS = std::function; + + // This function is a generic "resetScratch" callback + using RS = std::function; + + // This function describes kernel metadata inference rule. + using M = std::function; + + // This function is a generic "getBorder" callback (extracts border-related data from kernel's input parameters) + using B = std::function; + + // This function is a generic "getWindow" callback (extracts window-related data from kernel's input parameters) + using GW = std::function; + + // FIXME: move implementations out of header file + GFluidKernel() {} + GFluidKernel(Kind k, int l, bool scratch, const F& f, const IS &is, const RS &rs, const B& b, const GW& win) + : m_kind(k) + , m_lpi(l) + , m_scratch(scratch) + , m_f(f) + , m_is(is) + , m_rs(rs) + , m_b(b) + , m_gw(win) {} + + Kind m_kind; + const int m_lpi = -1; + const bool m_scratch = false; + + const F m_f; + const IS m_is; + const RS m_rs; + const B m_b; + const GW m_gw; +}; + +// FIXME!!! +// This is the temporary and experimental API +// which should be replaced by runtime roi-based scheduling +/** \addtogroup gapi_compile_args + * @{ + */ +/** + * @brief This structure allows to control the output image region + * which Fluid backend will produce in the graph. + * + * This feature is useful for external tiling and parallelism, but + * will be deprecated in the future releases. + */ +struct GFluidOutputRois +{ + std::vector rois; +}; + +/** + * @brief This structure forces Fluid backend to generate multiple + * parallel output regions in the graph. These regions execute in parallel. + * + * This feature may be deprecated in the future releases. + */ +struct GFluidParallelOutputRois +{ + std::vector parallel_rois; +}; + +/** + * @brief This structure allows to customize the way how Fluid executes + * parallel regions. + * + * For example, user can utilize his own threading runtime via this parameter. + * The `parallel_for` member functor is called by the Fluid runtime with the + * following arguments: + * + * @param size Size of the parallel range to process + * @param f A function which should be called for every integer index + * in this range by the specified parallel_for implementation. + * + * This feature may be deprecated in the future releases. + */ +struct GFluidParallelFor +{ + //this function accepts: + // - size of the "parallel" range as the first argument + // - and a function to be called on the range items, designated by item index + std::function)> parallel_for; +}; +/** @} gapi_compile_args */ + +namespace detail +{ +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.fluid.outputRois"; } +}; + +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.fluid.parallelFor"; } +}; + +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.fluid.parallelOutputRois"; } +}; + +} // namespace detail + +namespace detail +{ +template struct fluid_get_in; +template<> struct fluid_get_in +{ + static const cv::gapi::fluid::View& get(const cv::GArgs &in_args, int idx) + { + return *in_args[idx].unsafe_get(); + } +}; + +template<> struct fluid_get_in +{ + // FIXME: change to return by reference when moved to own::Scalar + static cv::Scalar get(const cv::GArgs &in_args, int idx) + { + return in_args[idx].unsafe_get(); + } +}; + +template struct fluid_get_in> +{ + static const std::vector& get(const cv::GArgs &in_args, int idx) + { + return in_args.at(idx).unsafe_get().rref(); + } +}; + +template struct fluid_get_in> +{ + static const U& get(const cv::GArgs &in_args, int idx) + { + return in_args.at(idx).unsafe_get().rref(); + } +}; + +template struct fluid_get_in +{ + static const T& get(const cv::GArgs &in_args, int idx) + { + return in_args[idx].unsafe_get(); + } +}; + +template +struct scratch_helper; + +template +struct scratch_helper +{ + // Init + template + static void help_init_impl(const cv::GMetaArgs &metas, + const cv::GArgs &in_args, + gapi::fluid::Buffer &scratch_buf, + detail::Seq) + { + Impl::initScratch(get_in_meta(metas, in_args, IIs)..., scratch_buf); + } + + static void help_init(const cv::GMetaArgs &metas, + const cv::GArgs &in_args, + gapi::fluid::Buffer &b) + { + help_init_impl(metas, in_args, b, typename detail::MkSeq::type()); + } + + // Reset + static void help_reset(gapi::fluid::Buffer &b) + { + Impl::resetScratch(b); + } +}; + +template +struct scratch_helper +{ + static void help_init(const cv::GMetaArgs &, + const cv::GArgs &, + gapi::fluid::Buffer &) + { + GAPI_Error("InternalError"); + } + static void help_reset(gapi::fluid::Buffer &) + { + GAPI_Error("InternalError"); + } +}; + +template struct is_gmat_type +{ + static const constexpr bool value = std::is_same::value; +}; + +template +struct get_border_helper; + +template +struct get_border_helper +{ + template + static gapi::fluid::BorderOpt get_border_impl(const GMetaArgs &metas, + const cv::GArgs &in_args, + cv::detail::Seq) + { + return util::make_optional(Impl::getBorder(cv::detail::get_in_meta(metas, in_args, IIs)...)); + } + + static gapi::fluid::BorderOpt help(const GMetaArgs &metas, + const cv::GArgs &in_args) + { + return get_border_impl(metas, in_args, typename detail::MkSeq::type()); + } +}; + +template +struct get_border_helper +{ + static gapi::fluid::BorderOpt help(const cv::GMetaArgs &, + const cv::GArgs &) + { + return {}; + } +}; + +template +struct get_window_helper; + +template +struct get_window_helper +{ + template + static int get_window_impl(const GMetaArgs &metas, + const cv::GArgs &in_args, + cv::detail::Seq) + { + return Impl::getWindow(cv::detail::get_in_meta(metas, in_args, IIs)...); + } + + static int help(const GMetaArgs &metas, const cv::GArgs &in_args) + { + return get_window_impl(metas, in_args, typename detail::MkSeq::type()); + } +}; + +template +struct get_window_helper +{ + static int help(const cv::GMetaArgs &, + const cv::GArgs &) + { + return Impl::Window; + } +}; + +template +struct has_Window +{ +private: + template + static constexpr auto Check(U*) -> typename std::is_same::type; + + template + static constexpr std::false_type Check(...); + + typedef decltype(Check(0)) Result; + +public: + static constexpr bool value = Result::value; +}; + +template +struct callCustomGetBorder; + +template +struct callCustomGetBorder +{ + static constexpr bool value = (Impl::Window != 1); +}; + +template +struct callCustomGetBorder +{ + static constexpr bool value = true; +}; + +template +struct FluidCallHelper; + +template +struct FluidCallHelper, std::tuple, UseScratch> +{ + static_assert(all_satisfy::value, "return type must be GMat"); + static_assert(contains::value, "input must contain at least one GMat"); + + // Execution dispatcher //////////////////////////////////////////////////// + template + static void call_impl(const cv::GArgs &in_args, + const std::vector &out_bufs, + detail::Seq, + detail::Seq) + { + Impl::run(fluid_get_in::get(in_args, IIs)..., *out_bufs[OIs]...); + } + + static void call(const cv::GArgs &in_args, + const std::vector &out_bufs) + { + constexpr int numOuts = (sizeof...(Outs)) + (UseScratch ? 1 : 0); + call_impl(in_args, out_bufs, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } + + // Scratch buffer initialization dispatcher //////////////////////////////// + static void init_scratch(const GMetaArgs &metas, + const cv::GArgs &in_args, + gapi::fluid::Buffer &b) + { + scratch_helper::help_init(metas, in_args, b); + } + + // Scratch buffer reset dispatcher ///////////////////////////////////////// + static void reset_scratch(gapi::fluid::Buffer &scratch_buf) + { + scratch_helper::help_reset(scratch_buf); + } + + static gapi::fluid::BorderOpt getBorder(const GMetaArgs &metas, const cv::GArgs &in_args) + { + constexpr bool hasWindow = has_Window::value; + + // User must provide "init" callback if Window != 1 + // TODO: move to constexpr if when we enable C++17 + return get_border_helper::value, Impl, Ins...>::help(metas, in_args); + } + + static int getWindow(const GMetaArgs &metas, const cv::GArgs &in_args) + { + constexpr bool callCustomGetWindow = !(has_Window::value); + return get_window_helper::help(metas, in_args); + } +}; +} // namespace detail + + +template +class GFluidKernelImpl : public cv::detail::KernelTag +{ + static const int LPI = 1; + static const auto Kind = GFluidKernel::Kind::Filter; + using P = detail::FluidCallHelper; + +public: + using API = K; + + static GFluidKernel kernel() + { + // FIXME: call() and getOutMeta() needs to be renamed so it is clear these + // functions are internal wrappers, not user API + return GFluidKernel(Impl::Kind, Impl::LPI, + UseScratch, + &P::call, &P::init_scratch, &P::reset_scratch, &P::getBorder, &P::getWindow); + } + + static cv::gapi::GBackend backend() { return cv::gapi::fluid::backend(); } +}; + +#define GAPI_FLUID_KERNEL(Name, API, Scratch) struct Name: public cv::GFluidKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GCPUKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp index 31fc2446dc..a4e8ac0f99 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/fluid/imgproc.hpp @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_FLUID_IMGPROC_HPP -#define OPENCV_GAPI_FLUID_IMGPROC_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { namespace gapi { namespace imgproc { namespace fluid { - -GAPI_EXPORTS_W GKernelPackage kernels(); - -}}}} - -#endif // OPENCV_GAPI_FLUID_IMGPROC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_FLUID_IMGPROC_HPP +#define OPENCV_GAPI_FLUID_IMGPROC_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { namespace gapi { namespace imgproc { namespace fluid { + +GAPI_EXPORTS_W GKernelPackage kernels(); + +}}}} + +#endif // OPENCV_GAPI_FLUID_IMGPROC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp index 3c06d851f0..2a8315f9d8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/garg.hpp @@ -1,311 +1,311 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GARG_HPP -#define OPENCV_GAPI_GARG_HPP - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cv { - -class GArg; - -namespace detail { - template - using is_garg = std::is_same::type>; -} - -// Parameter holder class for a node -// Depending on platform capabilities, can either support arbitrary types -// (as `boost::any`) or a limited number of types (as `boot::variant`). -// FIXME: put into "details" as a user shouldn't use it in his code -class GAPI_EXPORTS GArg -{ -public: - GArg() {} - - template::value, int>::type = 0> - explicit GArg(const T &t) - : kind(detail::GTypeTraits::kind) - , opaque_kind(detail::GOpaqueTraits::kind) - , value(detail::wrap_gapi_helper::wrap(t)) - { - } - - template::value, int>::type = 0> - explicit GArg(T &&t) - : kind(detail::GTypeTraits::type>::kind) - , opaque_kind(detail::GOpaqueTraits::type>::kind) - , value(detail::wrap_gapi_helper::wrap(t)) - { - } - - template inline T& get() - { - return util::any_cast::type>(value); - } - - template inline const T& get() const - { - return util::any_cast::type>(value); - } - - template inline T& unsafe_get() - { - return util::unsafe_any_cast::type>(value); - } - - template inline const T& unsafe_get() const - { - return util::unsafe_any_cast::type>(value); - } - - detail::ArgKind kind = detail::ArgKind::OPAQUE_VAL; - detail::OpaqueKind opaque_kind = detail::OpaqueKind::CV_UNKNOWN; - -protected: - util::any value; -}; - -using GArgs = std::vector; - -// FIXME: Express as M::type -// FIXME: Move to a separate file! -using GRunArgBase = util::variant< -#if !defined(GAPI_STANDALONE) - cv::UMat, -#endif // !defined(GAPI_STANDALONE) - cv::RMat, - cv::gapi::wip::IStreamSource::Ptr, - cv::Mat, - cv::Scalar, - cv::detail::VectorRef, - cv::detail::OpaqueRef, - cv::MediaFrame - >; - -namespace detail { -template -struct in_variant; - -template -struct in_variant > - : std::integral_constant::value > { -}; -} // namespace detail - -struct GAPI_EXPORTS GRunArg: public GRunArgBase -{ - // Metadata information here - using Meta = std::unordered_map; - Meta meta; - - // Mimic the old GRunArg semantics here, old of the times when - // GRunArg was an alias to variant<> - GRunArg(); - GRunArg(const cv::GRunArg &arg); - GRunArg(cv::GRunArg &&arg); - - GRunArg& operator= (const GRunArg &arg); - GRunArg& operator= (GRunArg &&arg); - - template - GRunArg(const T &t, - const Meta &m = Meta{}, - typename std::enable_if< detail::in_variant::value, int>::type = 0) - : GRunArgBase(t) - , meta(m) - { - } - template - GRunArg(T &&t, - const Meta &m = Meta{}, - typename std::enable_if< detail::in_variant::value, int>::type = 0) - : GRunArgBase(std::move(t)) - , meta(m) - { - } - template auto operator= (const T &t) - -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& - { - GRunArgBase::operator=(t); - return *this; - } - template auto operator= (T&& t) - -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& - { - GRunArgBase::operator=(std::move(t)); - return *this; - } -}; -using GRunArgs = std::vector; - -// TODO: Think about the addition operator -/** - * @brief This operator allows to complement the input vector at runtime. - * - * It's an ordinary overload of addition assignment operator. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgs usage - * - */ -inline GRunArgs& operator += (GRunArgs &lhs, const GRunArgs &rhs) -{ - lhs.reserve(lhs.size() + rhs.size()); - lhs.insert(lhs.end(), rhs.begin(), rhs.end()); - return lhs; -} - -namespace gapi -{ -namespace wip -{ -/** - * @brief This aggregate type represents all types which G-API can - * handle (via variant). - * - * It only exists to overcome C++ language limitations (where a - * `using`-defined class can't be forward-declared). - */ -struct GAPI_EXPORTS Data: public GRunArg -{ - using GRunArg::GRunArg; - template - Data& operator= (const T& t) { GRunArg::operator=(t); return *this; } - template - Data& operator= (T&& t) { GRunArg::operator=(std::move(t)); return *this; } -}; -} // namespace wip -} // namespace gapi - -using GRunArgP = util::variant< -#if !defined(GAPI_STANDALONE) - cv::UMat*, -#endif // !defined(GAPI_STANDALONE) - cv::Mat*, - cv::RMat*, - cv::Scalar*, - cv::MediaFrame*, - cv::detail::VectorRef, - cv::detail::OpaqueRef - >; -using GRunArgsP = std::vector; - -// TODO: Think about the addition operator -/** - * @brief This operator allows to complement the output vector at runtime. - * - * It's an ordinary overload of addition assignment operator. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgsP usage - * - */ -inline GRunArgsP& operator += (GRunArgsP &lhs, const GRunArgsP &rhs) -{ - lhs.reserve(lhs.size() + rhs.size()); - lhs.insert(lhs.end(), rhs.begin(), rhs.end()); - return lhs; -} - -namespace gapi -{ -/** - * \addtogroup gapi_serialization - * @{ - * - * @brief G-API functions and classes for serialization and deserialization. - */ - -/** @brief Wraps deserialized output GRunArgs to GRunArgsP which can be used by GCompiled. - * - * Since it's impossible to get modifiable output arguments from deserialization - * it needs to be wrapped by this function. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind after deserialization - * - * @param out_args deserialized GRunArgs. - * @return the same GRunArgs wrapped in GRunArgsP. - * @see deserialize - */ -GAPI_EXPORTS cv::GRunArgsP bind(cv::GRunArgs &out_args); - -/** @brief Wraps output GRunArgsP available during graph execution to GRunArgs which can be serialized. - * - * GRunArgsP is pointer-to-value, so to be serialized they need to be binded to real values - * which this function does. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind before serialization - * - * @param out output GRunArgsP available during graph execution. - * @return the same GRunArgsP wrapped in serializable GRunArgs. - * @see serialize - */ -GAPI_EXPORTS cv::GRunArg bind(cv::GRunArgP &out); // FIXME: think more about it -/** @} */ -} - -template inline GRunArgs gin(const Ts&... args) -{ - return GRunArgs{ GRunArg(detail::wrap_host_helper::wrap_in(args))... }; -} - -template inline GRunArgsP gout(Ts&... args) -{ - return GRunArgsP{ GRunArgP(detail::wrap_host_helper::wrap_out(args))... }; -} - -struct GTypeInfo; -using GTypesInfo = std::vector; - -// FIXME: Needed for python bridge, must be moved to more appropriate header -namespace detail { -struct ExtractArgsCallback -{ - cv::GRunArgs operator()(const cv::GTypesInfo& info) const { return c(info); } - using CallBackT = std::function; - CallBackT c; -}; - -struct ExtractMetaCallback -{ - cv::GMetaArgs operator()(const cv::GTypesInfo& info) const { return c(info); } - using CallBackT = std::function; - CallBackT c; -}; - -void constructGraphOutputs(const cv::GTypesInfo &out_info, - cv::GRunArgs &args, - cv::GRunArgsP &outs); -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_GARG_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GARG_HPP +#define OPENCV_GAPI_GARG_HPP + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cv { + +class GArg; + +namespace detail { + template + using is_garg = std::is_same::type>; +} + +// Parameter holder class for a node +// Depending on platform capabilities, can either support arbitrary types +// (as `boost::any`) or a limited number of types (as `boot::variant`). +// FIXME: put into "details" as a user shouldn't use it in his code +class GAPI_EXPORTS GArg +{ +public: + GArg() {} + + template::value, int>::type = 0> + explicit GArg(const T &t) + : kind(detail::GTypeTraits::kind) + , opaque_kind(detail::GOpaqueTraits::kind) + , value(detail::wrap_gapi_helper::wrap(t)) + { + } + + template::value, int>::type = 0> + explicit GArg(T &&t) + : kind(detail::GTypeTraits::type>::kind) + , opaque_kind(detail::GOpaqueTraits::type>::kind) + , value(detail::wrap_gapi_helper::wrap(t)) + { + } + + template inline T& get() + { + return util::any_cast::type>(value); + } + + template inline const T& get() const + { + return util::any_cast::type>(value); + } + + template inline T& unsafe_get() + { + return util::unsafe_any_cast::type>(value); + } + + template inline const T& unsafe_get() const + { + return util::unsafe_any_cast::type>(value); + } + + detail::ArgKind kind = detail::ArgKind::OPAQUE_VAL; + detail::OpaqueKind opaque_kind = detail::OpaqueKind::CV_UNKNOWN; + +protected: + util::any value; +}; + +using GArgs = std::vector; + +// FIXME: Express as M::type +// FIXME: Move to a separate file! +using GRunArgBase = util::variant< +#if !defined(GAPI_STANDALONE) + cv::UMat, +#endif // !defined(GAPI_STANDALONE) + cv::RMat, + cv::gapi::wip::IStreamSource::Ptr, + cv::Mat, + cv::Scalar, + cv::detail::VectorRef, + cv::detail::OpaqueRef, + cv::MediaFrame + >; + +namespace detail { +template +struct in_variant; + +template +struct in_variant > + : std::integral_constant::value > { +}; +} // namespace detail + +struct GAPI_EXPORTS GRunArg: public GRunArgBase +{ + // Metadata information here + using Meta = std::unordered_map; + Meta meta; + + // Mimic the old GRunArg semantics here, old of the times when + // GRunArg was an alias to variant<> + GRunArg(); + GRunArg(const cv::GRunArg &arg); + GRunArg(cv::GRunArg &&arg); + + GRunArg& operator= (const GRunArg &arg); + GRunArg& operator= (GRunArg &&arg); + + template + GRunArg(const T &t, + const Meta &m = Meta{}, + typename std::enable_if< detail::in_variant::value, int>::type = 0) + : GRunArgBase(t) + , meta(m) + { + } + template + GRunArg(T &&t, + const Meta &m = Meta{}, + typename std::enable_if< detail::in_variant::value, int>::type = 0) + : GRunArgBase(std::move(t)) + , meta(m) + { + } + template auto operator= (const T &t) + -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& + { + GRunArgBase::operator=(t); + return *this; + } + template auto operator= (T&& t) + -> typename std::enable_if< detail::in_variant::value, cv::GRunArg>::type& + { + GRunArgBase::operator=(std::move(t)); + return *this; + } +}; +using GRunArgs = std::vector; + +// TODO: Think about the addition operator +/** + * @brief This operator allows to complement the input vector at runtime. + * + * It's an ordinary overload of addition assignment operator. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgs usage + * + */ +inline GRunArgs& operator += (GRunArgs &lhs, const GRunArgs &rhs) +{ + lhs.reserve(lhs.size() + rhs.size()); + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; +} + +namespace gapi +{ +namespace wip +{ +/** + * @brief This aggregate type represents all types which G-API can + * handle (via variant). + * + * It only exists to overcome C++ language limitations (where a + * `using`-defined class can't be forward-declared). + */ +struct GAPI_EXPORTS Data: public GRunArg +{ + using GRunArg::GRunArg; + template + Data& operator= (const T& t) { GRunArg::operator=(t); return *this; } + template + Data& operator= (T&& t) { GRunArg::operator=(std::move(t)); return *this; } +}; +} // namespace wip +} // namespace gapi + +using GRunArgP = util::variant< +#if !defined(GAPI_STANDALONE) + cv::UMat*, +#endif // !defined(GAPI_STANDALONE) + cv::Mat*, + cv::RMat*, + cv::Scalar*, + cv::MediaFrame*, + cv::detail::VectorRef, + cv::detail::OpaqueRef + >; +using GRunArgsP = std::vector; + +// TODO: Think about the addition operator +/** + * @brief This operator allows to complement the output vector at runtime. + * + * It's an ordinary overload of addition assignment operator. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GRunArgsP usage + * + */ +inline GRunArgsP& operator += (GRunArgsP &lhs, const GRunArgsP &rhs) +{ + lhs.reserve(lhs.size() + rhs.size()); + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; +} + +namespace gapi +{ +/** + * \addtogroup gapi_serialization + * @{ + * + * @brief G-API functions and classes for serialization and deserialization. + */ + +/** @brief Wraps deserialized output GRunArgs to GRunArgsP which can be used by GCompiled. + * + * Since it's impossible to get modifiable output arguments from deserialization + * it needs to be wrapped by this function. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind after deserialization + * + * @param out_args deserialized GRunArgs. + * @return the same GRunArgs wrapped in GRunArgsP. + * @see deserialize + */ +GAPI_EXPORTS cv::GRunArgsP bind(cv::GRunArgs &out_args); + +/** @brief Wraps output GRunArgsP available during graph execution to GRunArgs which can be serialized. + * + * GRunArgsP is pointer-to-value, so to be serialized they need to be binded to real values + * which this function does. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp bind before serialization + * + * @param out output GRunArgsP available during graph execution. + * @return the same GRunArgsP wrapped in serializable GRunArgs. + * @see serialize + */ +GAPI_EXPORTS cv::GRunArg bind(cv::GRunArgP &out); // FIXME: think more about it +/** @} */ +} + +template inline GRunArgs gin(const Ts&... args) +{ + return GRunArgs{ GRunArg(detail::wrap_host_helper::wrap_in(args))... }; +} + +template inline GRunArgsP gout(Ts&... args) +{ + return GRunArgsP{ GRunArgP(detail::wrap_host_helper::wrap_out(args))... }; +} + +struct GTypeInfo; +using GTypesInfo = std::vector; + +// FIXME: Needed for python bridge, must be moved to more appropriate header +namespace detail { +struct ExtractArgsCallback +{ + cv::GRunArgs operator()(const cv::GTypesInfo& info) const { return c(info); } + using CallBackT = std::function; + CallBackT c; +}; + +struct ExtractMetaCallback +{ + cv::GMetaArgs operator()(const cv::GTypesInfo& info) const { return c(info); } + using CallBackT = std::function; + CallBackT c; +}; + +void constructGraphOutputs(const cv::GTypesInfo &out_info, + cv::GRunArgs &args, + cv::GRunArgsP &outs); +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_GARG_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp index f04ca521d8..a2951993f2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/garray.hpp @@ -1,440 +1,440 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GARRAY_HPP -#define OPENCV_GAPI_GARRAY_HPP - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -#include // flatten_g only! -#include // flatten_g only! - -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; -template class GArray; - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GArrayDesc -{ - // FIXME: Body - // FIXME: Also implement proper operator== then - bool operator== (const GArrayDesc&) const { return true; } -}; -template GArrayDesc descr_of(const std::vector &) { return {};} -GAPI_EXPORTS_W inline GArrayDesc empty_array_desc() {return {}; } -/** @} */ - -std::ostream& operator<<(std::ostream& os, const cv::GArrayDesc &desc); - -namespace detail -{ - // ConstructVec is a callback which stores information about T and is used by - // G-API runtime to construct arrays in host memory (T remains opaque for G-API). - // ConstructVec is carried into G-API internals by GArrayU. - // Currently it is suitable for Host (CPU) plugins only, real offload may require - // more information for manual memory allocation on-device. - class VectorRef; - using ConstructVec = std::function; - - // This is the base struct for GArrayU type holder - struct TypeHintBase{virtual ~TypeHintBase() = default;}; - - // This class holds type of initial GArray to be checked from GArrayU - template - struct TypeHint final : public TypeHintBase{}; - - // This class strips type information from GArray and makes it usable - // in the G-API graph compiler (expression unrolling, graph generation, etc). - // Part of GProtoArg. - class GAPI_EXPORTS GArrayU - { - public: - GArrayU(const GNode &n, std::size_t out); // Operation result constructor - - template - bool holds() const; // Check if was created from GArray - - GOrigin& priv(); // Internal use only - const GOrigin& priv() const; // Internal use only - - protected: - GArrayU(); // Default constructor - GArrayU(const detail::VectorRef& vref); // Constant value constructor - template friend class cv::GArray; // (available to GArray only) - - void setConstructFcn(ConstructVec &&cv); // Store T-aware constructor - - template - void specifyType(); // Store type of initial GArray - - template - void storeKind(); - - void setKind(cv::detail::OpaqueKind); - - std::shared_ptr m_priv; - std::shared_ptr m_hint; - }; - - template - bool GArrayU::holds() const{ - GAPI_Assert(m_hint != nullptr); - using U = typename std::decay::type; - return dynamic_cast*>(m_hint.get()) != nullptr; - } - - template - void GArrayU::specifyType(){ - m_hint.reset(new TypeHint::type>); - } - - template - void GArrayU::storeKind(){ - setKind(cv::detail::GOpaqueTraits::kind); - } - - // This class represents a typed STL vector reference. - // Depending on origins, this reference may be either "just a" reference to - // an object created externally, OR actually own the underlying object - // (be value holder). - class BasicVectorRef - { - public: - // These fields are set by the derived class(es) - std::size_t m_elemSize = 0ul; - cv::GArrayDesc m_desc; - virtual ~BasicVectorRef() {} - - virtual void mov(BasicVectorRef &ref) = 0; - virtual const void* ptr() const = 0; - virtual std::size_t size() const = 0; - }; - - template class VectorRefT final: public BasicVectorRef - { - using empty_t = util::monostate; - using ro_ext_t = const std::vector *; - using rw_ext_t = std::vector *; - using rw_own_t = std::vector ; - util::variant m_ref; - - inline bool isEmpty() const { return util::holds_alternative(m_ref); } - inline bool isROExt() const { return util::holds_alternative(m_ref); } - inline bool isRWExt() const { return util::holds_alternative(m_ref); } - inline bool isRWOwn() const { return util::holds_alternative(m_ref); } - - void init(const std::vector* vec = nullptr) - { - m_elemSize = sizeof(T); - if (vec) m_desc = cv::descr_of(*vec); - } - - public: - VectorRefT() { init(); } - virtual ~VectorRefT() {} - - explicit VectorRefT(const std::vector& vec) : m_ref(&vec) { init(&vec); } - explicit VectorRefT(std::vector& vec) : m_ref(&vec) { init(&vec); } - explicit VectorRefT(std::vector&& vec) : m_ref(std::move(vec)) { init(&vec); } - - // Reset a VectorRefT. Called only for objects instantiated - // internally in G-API (e.g. temporary GArray's within a - // computation). Reset here means both initialization - // (creating an object) and reset (discarding its existing - // content before the next execution). Must never be called - // for external VectorRefTs. - void reset() - { - if (isEmpty()) - { - std::vector empty_vector; - m_desc = cv::descr_of(empty_vector); - m_ref = std::move(empty_vector); - GAPI_Assert(isRWOwn()); - } - else if (isRWOwn()) - { - util::get(m_ref).clear(); - } - else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes - } - - // Obtain a WRITE reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - std::vector& wref() - { - GAPI_Assert(isRWExt() || isRWOwn()); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - // Obtain a READ reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - const std::vector& rref() const - { - // ANY vector can be accessed for reading, even if it declared for - // output. Example -- a GComputation from [in] to [out1,out2] - // where [out2] is a result of operation applied to [out1]: - // - // GComputation boundary - // . . . . . . . - // . . - // [in] ----> foo() ----> [out1] - // . . : - // . . . .:. . . - // . V . - // . bar() ---> [out2] - // . . . . . . . . . . . . - // - if (isROExt()) return *util::get(m_ref); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - virtual void mov(BasicVectorRef &v) override { - VectorRefT *tv = dynamic_cast*>(&v); - GAPI_Assert(tv != nullptr); - wref() = std::move(tv->wref()); - } - - virtual const void* ptr() const override { return &rref(); } - virtual std::size_t size() const override { return rref().size(); } - }; - - // This class strips type information from VectorRefT<> and makes it usable - // in the G-API executables (carrying run-time data/information to kernels). - // Part of GRunArg. - // Its methods are typed proxies to VectorRefT. - // VectorRef maintains "reference" semantics so two copies of VectoRef refer - // to the same underlying object. - // FIXME: Put a good explanation on why cv::OutputArray doesn't fit this role - class VectorRef - { - std::shared_ptr m_ref; - cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; - - template inline void check() const - { - GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); - GAPI_Assert(sizeof(T) == m_ref->m_elemSize); - } - - public: - VectorRef() = default; - template explicit VectorRef(const std::vector& vec) - : m_ref(new VectorRefT(vec)) - , m_kind(GOpaqueTraits::kind) - {} - template explicit VectorRef(std::vector& vec) - : m_ref(new VectorRefT(vec)) - , m_kind(GOpaqueTraits::kind) - {} - template explicit VectorRef(std::vector&& vec) - : m_ref(new VectorRefT(std::move(vec))) - , m_kind(GOpaqueTraits::kind) - {} - - cv::detail::OpaqueKind getKind() const - { - return m_kind; - } - - template void reset() - { - if (!m_ref) m_ref.reset(new VectorRefT()); - check(); - storeKind(); - static_cast&>(*m_ref).reset(); - } - - template - void storeKind() - { - m_kind = cv::detail::GOpaqueTraits::kind; - } - - template std::vector& wref() - { - check(); - return static_cast&>(*m_ref).wref(); - } - - template const std::vector& rref() const - { - check(); - return static_cast&>(*m_ref).rref(); - } - - // Check if was created for/from std::vector - template bool holds() const - { - if (!m_ref) return false; - using U = typename std::decay::type; - return dynamic_cast*>(m_ref.get()) != nullptr; - } - - void mov(VectorRef &v) - { - m_ref->mov(*v.m_ref); - } - - cv::GArrayDesc descr_of() const - { - return m_ref->m_desc; - } - - std::size_t size() const - { - return m_ref->size(); - } - - // May be used to uniquely identify this object internally - const void *ptr() const { return m_ref->ptr(); } - }; - - // Helper (FIXME: work-around?) - // stripping G types to their host types - // like cv::GArray would still map to std::vector - // but not to std::vector -#if defined(GAPI_STANDALONE) -# define FLATTEN_NS cv::gapi::own -#else -# define FLATTEN_NS cv -#endif - template struct flatten_g; - template<> struct flatten_g { using type = FLATTEN_NS::Mat; }; - template<> struct flatten_g { using type = FLATTEN_NS::Scalar; }; - template struct flatten_g> { using type = std::vector; }; - template struct flatten_g { using type = T; }; -#undef FLATTEN_NS - // FIXME: the above mainly duplicates "ProtoToParam" thing from gtyped.hpp - // but I decided not to include gtyped here - probably worth moving that stuff - // to some common place? (DM) -} // namespace detail - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief `cv::GArray` template class represents a list of objects - * of class `T` in the graph. - * - * `cv::GArray` describes a functional relationship between - * operations consuming and producing arrays of objects of class - * `T`. The primary purpose of `cv::GArray` is to represent a - * dynamic list of objects -- where the size of the list is not known - * at the graph construction or compile time. Examples include: corner - * and feature detectors (`cv::GArray`), object detection - * and tracking results (`cv::GArray`). Programmers can use - * their own types with `cv::GArray` in the custom operations. - * - * Similar to `cv::GScalar`, `cv::GArray` may be value-initialized - * -- in this case a graph-constant value is associated with the object. - * - * `GArray` is a virtual counterpart of `std::vector`, which is - * usually used to represent the `GArray` data in G-API during the - * execution. - * - * @sa `cv::GOpaque` - */ -template class GArray -{ -public: - // Host type (or Flat type) - the type this GArray is actually - // specified to. - /// @private - using HT = typename detail::flatten_g::type>::type; - - /** - * @brief Constructs a value-initialized `cv::GArray` - * - * `cv::GArray` objects may have their values - * be associated at graph construction time. It is useful when - * some operation has a `cv::GArray` input which doesn't change during - * the program execution, and is set only once. In this case, - * there is no need to declare such `cv::GArray` as a graph input. - * - * @note The value of `cv::GArray` may be overwritten by assigning some - * other `cv::GArray` to the object using `operator=` -- on the - * assignment, the old association or value is discarded. - * - * @param v a std::vector to associate with this - * `cv::GArray` object. Vector data is copied into the - * `cv::GArray` (no reference to the passed data is held). - */ - explicit GArray(const std::vector& v) // Constant value constructor - : m_ref(detail::GArrayU(detail::VectorRef(v))) { putDetails(); } - - /** - * @overload - * @brief Constructs a value-initialized `cv::GArray` - * - * @param v a std::vector to associate with this - * `cv::GArray` object. Vector data is moved into the `cv::GArray`. - */ - explicit GArray(std::vector&& v) // Move-constructor - : m_ref(detail::GArrayU(detail::VectorRef(std::move(v)))) { putDetails(); } - - /** - * @brief Constructs an empty `cv::GArray` - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty `cv::GArray` is assigned to a result - * of some operation, it obtains a functional link to this - * operation (and is not empty anymore). - */ - GArray() { putDetails(); } // Empty constructor - - /// @private - explicit GArray(detail::GArrayU &&ref) // GArrayU-based constructor - : m_ref(ref) { putDetails(); } // (used by GCall, not for users) - - /// @private - detail::GArrayU strip() const { - return m_ref; - } - /// @private - static void VCtor(detail::VectorRef& vref) { - vref.reset(); - } - -private: - void putDetails() { - m_ref.setConstructFcn(&VCtor); - m_ref.specifyType(); // FIXME: to unify those 2 to avoid excessive dynamic_cast - m_ref.storeKind(); // - } - - detail::GArrayU m_ref; -}; - -/** @} */ - -} // namespace cv - -#endif // OPENCV_GAPI_GARRAY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GARRAY_HPP +#define OPENCV_GAPI_GARRAY_HPP + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include // flatten_g only! +#include // flatten_g only! + +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; +template class GArray; + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GArrayDesc +{ + // FIXME: Body + // FIXME: Also implement proper operator== then + bool operator== (const GArrayDesc&) const { return true; } +}; +template GArrayDesc descr_of(const std::vector &) { return {};} +GAPI_EXPORTS_W inline GArrayDesc empty_array_desc() {return {}; } +/** @} */ + +std::ostream& operator<<(std::ostream& os, const cv::GArrayDesc &desc); + +namespace detail +{ + // ConstructVec is a callback which stores information about T and is used by + // G-API runtime to construct arrays in host memory (T remains opaque for G-API). + // ConstructVec is carried into G-API internals by GArrayU. + // Currently it is suitable for Host (CPU) plugins only, real offload may require + // more information for manual memory allocation on-device. + class VectorRef; + using ConstructVec = std::function; + + // This is the base struct for GArrayU type holder + struct TypeHintBase{virtual ~TypeHintBase() = default;}; + + // This class holds type of initial GArray to be checked from GArrayU + template + struct TypeHint final : public TypeHintBase{}; + + // This class strips type information from GArray and makes it usable + // in the G-API graph compiler (expression unrolling, graph generation, etc). + // Part of GProtoArg. + class GAPI_EXPORTS GArrayU + { + public: + GArrayU(const GNode &n, std::size_t out); // Operation result constructor + + template + bool holds() const; // Check if was created from GArray + + GOrigin& priv(); // Internal use only + const GOrigin& priv() const; // Internal use only + + protected: + GArrayU(); // Default constructor + GArrayU(const detail::VectorRef& vref); // Constant value constructor + template friend class cv::GArray; // (available to GArray only) + + void setConstructFcn(ConstructVec &&cv); // Store T-aware constructor + + template + void specifyType(); // Store type of initial GArray + + template + void storeKind(); + + void setKind(cv::detail::OpaqueKind); + + std::shared_ptr m_priv; + std::shared_ptr m_hint; + }; + + template + bool GArrayU::holds() const{ + GAPI_Assert(m_hint != nullptr); + using U = typename std::decay::type; + return dynamic_cast*>(m_hint.get()) != nullptr; + } + + template + void GArrayU::specifyType(){ + m_hint.reset(new TypeHint::type>); + } + + template + void GArrayU::storeKind(){ + setKind(cv::detail::GOpaqueTraits::kind); + } + + // This class represents a typed STL vector reference. + // Depending on origins, this reference may be either "just a" reference to + // an object created externally, OR actually own the underlying object + // (be value holder). + class BasicVectorRef + { + public: + // These fields are set by the derived class(es) + std::size_t m_elemSize = 0ul; + cv::GArrayDesc m_desc; + virtual ~BasicVectorRef() {} + + virtual void mov(BasicVectorRef &ref) = 0; + virtual const void* ptr() const = 0; + virtual std::size_t size() const = 0; + }; + + template class VectorRefT final: public BasicVectorRef + { + using empty_t = util::monostate; + using ro_ext_t = const std::vector *; + using rw_ext_t = std::vector *; + using rw_own_t = std::vector ; + util::variant m_ref; + + inline bool isEmpty() const { return util::holds_alternative(m_ref); } + inline bool isROExt() const { return util::holds_alternative(m_ref); } + inline bool isRWExt() const { return util::holds_alternative(m_ref); } + inline bool isRWOwn() const { return util::holds_alternative(m_ref); } + + void init(const std::vector* vec = nullptr) + { + m_elemSize = sizeof(T); + if (vec) m_desc = cv::descr_of(*vec); + } + + public: + VectorRefT() { init(); } + virtual ~VectorRefT() {} + + explicit VectorRefT(const std::vector& vec) : m_ref(&vec) { init(&vec); } + explicit VectorRefT(std::vector& vec) : m_ref(&vec) { init(&vec); } + explicit VectorRefT(std::vector&& vec) : m_ref(std::move(vec)) { init(&vec); } + + // Reset a VectorRefT. Called only for objects instantiated + // internally in G-API (e.g. temporary GArray's within a + // computation). Reset here means both initialization + // (creating an object) and reset (discarding its existing + // content before the next execution). Must never be called + // for external VectorRefTs. + void reset() + { + if (isEmpty()) + { + std::vector empty_vector; + m_desc = cv::descr_of(empty_vector); + m_ref = std::move(empty_vector); + GAPI_Assert(isRWOwn()); + } + else if (isRWOwn()) + { + util::get(m_ref).clear(); + } + else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes + } + + // Obtain a WRITE reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + std::vector& wref() + { + GAPI_Assert(isRWExt() || isRWOwn()); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + // Obtain a READ reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + const std::vector& rref() const + { + // ANY vector can be accessed for reading, even if it declared for + // output. Example -- a GComputation from [in] to [out1,out2] + // where [out2] is a result of operation applied to [out1]: + // + // GComputation boundary + // . . . . . . . + // . . + // [in] ----> foo() ----> [out1] + // . . : + // . . . .:. . . + // . V . + // . bar() ---> [out2] + // . . . . . . . . . . . . + // + if (isROExt()) return *util::get(m_ref); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + virtual void mov(BasicVectorRef &v) override { + VectorRefT *tv = dynamic_cast*>(&v); + GAPI_Assert(tv != nullptr); + wref() = std::move(tv->wref()); + } + + virtual const void* ptr() const override { return &rref(); } + virtual std::size_t size() const override { return rref().size(); } + }; + + // This class strips type information from VectorRefT<> and makes it usable + // in the G-API executables (carrying run-time data/information to kernels). + // Part of GRunArg. + // Its methods are typed proxies to VectorRefT. + // VectorRef maintains "reference" semantics so two copies of VectoRef refer + // to the same underlying object. + // FIXME: Put a good explanation on why cv::OutputArray doesn't fit this role + class VectorRef + { + std::shared_ptr m_ref; + cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; + + template inline void check() const + { + GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); + GAPI_Assert(sizeof(T) == m_ref->m_elemSize); + } + + public: + VectorRef() = default; + template explicit VectorRef(const std::vector& vec) + : m_ref(new VectorRefT(vec)) + , m_kind(GOpaqueTraits::kind) + {} + template explicit VectorRef(std::vector& vec) + : m_ref(new VectorRefT(vec)) + , m_kind(GOpaqueTraits::kind) + {} + template explicit VectorRef(std::vector&& vec) + : m_ref(new VectorRefT(std::move(vec))) + , m_kind(GOpaqueTraits::kind) + {} + + cv::detail::OpaqueKind getKind() const + { + return m_kind; + } + + template void reset() + { + if (!m_ref) m_ref.reset(new VectorRefT()); + check(); + storeKind(); + static_cast&>(*m_ref).reset(); + } + + template + void storeKind() + { + m_kind = cv::detail::GOpaqueTraits::kind; + } + + template std::vector& wref() + { + check(); + return static_cast&>(*m_ref).wref(); + } + + template const std::vector& rref() const + { + check(); + return static_cast&>(*m_ref).rref(); + } + + // Check if was created for/from std::vector + template bool holds() const + { + if (!m_ref) return false; + using U = typename std::decay::type; + return dynamic_cast*>(m_ref.get()) != nullptr; + } + + void mov(VectorRef &v) + { + m_ref->mov(*v.m_ref); + } + + cv::GArrayDesc descr_of() const + { + return m_ref->m_desc; + } + + std::size_t size() const + { + return m_ref->size(); + } + + // May be used to uniquely identify this object internally + const void *ptr() const { return m_ref->ptr(); } + }; + + // Helper (FIXME: work-around?) + // stripping G types to their host types + // like cv::GArray would still map to std::vector + // but not to std::vector +#if defined(GAPI_STANDALONE) +# define FLATTEN_NS cv::gapi::own +#else +# define FLATTEN_NS cv +#endif + template struct flatten_g; + template<> struct flatten_g { using type = FLATTEN_NS::Mat; }; + template<> struct flatten_g { using type = FLATTEN_NS::Scalar; }; + template struct flatten_g> { using type = std::vector; }; + template struct flatten_g { using type = T; }; +#undef FLATTEN_NS + // FIXME: the above mainly duplicates "ProtoToParam" thing from gtyped.hpp + // but I decided not to include gtyped here - probably worth moving that stuff + // to some common place? (DM) +} // namespace detail + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief `cv::GArray` template class represents a list of objects + * of class `T` in the graph. + * + * `cv::GArray` describes a functional relationship between + * operations consuming and producing arrays of objects of class + * `T`. The primary purpose of `cv::GArray` is to represent a + * dynamic list of objects -- where the size of the list is not known + * at the graph construction or compile time. Examples include: corner + * and feature detectors (`cv::GArray`), object detection + * and tracking results (`cv::GArray`). Programmers can use + * their own types with `cv::GArray` in the custom operations. + * + * Similar to `cv::GScalar`, `cv::GArray` may be value-initialized + * -- in this case a graph-constant value is associated with the object. + * + * `GArray` is a virtual counterpart of `std::vector`, which is + * usually used to represent the `GArray` data in G-API during the + * execution. + * + * @sa `cv::GOpaque` + */ +template class GArray +{ +public: + // Host type (or Flat type) - the type this GArray is actually + // specified to. + /// @private + using HT = typename detail::flatten_g::type>::type; + + /** + * @brief Constructs a value-initialized `cv::GArray` + * + * `cv::GArray` objects may have their values + * be associated at graph construction time. It is useful when + * some operation has a `cv::GArray` input which doesn't change during + * the program execution, and is set only once. In this case, + * there is no need to declare such `cv::GArray` as a graph input. + * + * @note The value of `cv::GArray` may be overwritten by assigning some + * other `cv::GArray` to the object using `operator=` -- on the + * assignment, the old association or value is discarded. + * + * @param v a std::vector to associate with this + * `cv::GArray` object. Vector data is copied into the + * `cv::GArray` (no reference to the passed data is held). + */ + explicit GArray(const std::vector& v) // Constant value constructor + : m_ref(detail::GArrayU(detail::VectorRef(v))) { putDetails(); } + + /** + * @overload + * @brief Constructs a value-initialized `cv::GArray` + * + * @param v a std::vector to associate with this + * `cv::GArray` object. Vector data is moved into the `cv::GArray`. + */ + explicit GArray(std::vector&& v) // Move-constructor + : m_ref(detail::GArrayU(detail::VectorRef(std::move(v)))) { putDetails(); } + + /** + * @brief Constructs an empty `cv::GArray` + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty `cv::GArray` is assigned to a result + * of some operation, it obtains a functional link to this + * operation (and is not empty anymore). + */ + GArray() { putDetails(); } // Empty constructor + + /// @private + explicit GArray(detail::GArrayU &&ref) // GArrayU-based constructor + : m_ref(ref) { putDetails(); } // (used by GCall, not for users) + + /// @private + detail::GArrayU strip() const { + return m_ref; + } + /// @private + static void VCtor(detail::VectorRef& vref) { + vref.reset(); + } + +private: + void putDetails() { + m_ref.setConstructFcn(&VCtor); + m_ref.specifyType(); // FIXME: to unify those 2 to avoid excessive dynamic_cast + m_ref.storeKind(); // + } + + detail::GArrayU m_ref; +}; + +/** @} */ + +} // namespace cv + +#endif // OPENCV_GAPI_GARRAY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp index 8f3a10c7d7..f49b59822d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gasync_context.hpp @@ -1,63 +1,63 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_GASYNC_CONTEXT_HPP -#define OPENCV_GAPI_GASYNC_CONTEXT_HPP - -#if !defined(GAPI_STANDALONE) -# include -#else // Without OpenCV -# include -#endif // !defined(GAPI_STANDALONE) - -#include - -namespace cv { -namespace gapi{ - -/** - * @brief This namespace contains experimental G-API functionality, - * functions or structures in this namespace are subjects to change or - * removal in the future releases. This namespace also contains - * functions which API is not stabilized yet. - */ -namespace wip { - -/** - * @brief A class to group async requests to cancel them in a single shot. - * - * GAsyncContext is passed as an argument to async() and async_apply() functions - */ - -class GAPI_EXPORTS GAsyncContext{ - std::atomic cancelation_requested = {false}; -public: - /** - * @brief Start cancellation process for an associated request. - * - * User still has to wait for each individual request (either via callback or according std::future object) to make sure it actually canceled. - * - * @return true if it was a first request to cancel the context - */ - bool cancel(); - - /** - * @brief Returns true if cancellation was requested for this context. - * - * @return true if cancellation was requested for this context - */ - bool isCanceled() const; -}; - -class GAPI_EXPORTS GAsyncCanceled : public std::exception { -public: - virtual const char* what() const noexcept CV_OVERRIDE; -}; -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif //OPENCV_GAPI_GASYNC_CONTEXT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_GASYNC_CONTEXT_HPP +#define OPENCV_GAPI_GASYNC_CONTEXT_HPP + +#if !defined(GAPI_STANDALONE) +# include +#else // Without OpenCV +# include +#endif // !defined(GAPI_STANDALONE) + +#include + +namespace cv { +namespace gapi{ + +/** + * @brief This namespace contains experimental G-API functionality, + * functions or structures in this namespace are subjects to change or + * removal in the future releases. This namespace also contains + * functions which API is not stabilized yet. + */ +namespace wip { + +/** + * @brief A class to group async requests to cancel them in a single shot. + * + * GAsyncContext is passed as an argument to async() and async_apply() functions + */ + +class GAPI_EXPORTS GAsyncContext{ + std::atomic cancelation_requested = {false}; +public: + /** + * @brief Start cancellation process for an associated request. + * + * User still has to wait for each individual request (either via callback or according std::future object) to make sure it actually canceled. + * + * @return true if it was a first request to cancel the context + */ + bool cancel(); + + /** + * @brief Returns true if cancellation was requested for this context. + * + * @return true if cancellation was requested for this context + */ + bool isCanceled() const; +}; + +class GAPI_EXPORTS GAsyncCanceled : public std::exception { +public: + virtual const char* what() const noexcept CV_OVERRIDE; +}; +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif //OPENCV_GAPI_GASYNC_CONTEXT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp index df6baf6183..8d1b8d6010 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcall.hpp @@ -1,78 +1,78 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GCALL_HPP -#define OPENCV_GAPI_GCALL_HPP - -#include // GArg -#include // GMat -#include // GScalar -#include // GFrame -#include // GArray -#include // GOpaque - -namespace cv { - -struct GKernel; - -// The whole idea of this class is to represent an operation -// which is applied to arguments. This is part of public API, -// since it is what users should use to define kernel interfaces. - -class GAPI_EXPORTS GCall final -{ -public: - class Priv; - - explicit GCall(const GKernel &k); - ~GCall(); - - template - GCall& pass(Ts&&... args) - { - setArgs({cv::GArg(std::move(args))...}); - return *this; - } - - // A generic yield method - obtain a link to operator's particular GMat output - GMat yield (int output = 0); - GMatP yieldP (int output = 0); - GScalar yieldScalar(int output = 0); - GFrame yieldFrame (int output = 0); - - template GArray yieldArray(int output = 0) - { - return GArray(yieldArray(output)); - } - - template GOpaque yieldOpaque(int output = 0) - { - return GOpaque(yieldOpaque(output)); - } - - // Internal use only - Priv& priv(); - const Priv& priv() const; - - // GKernel and params can be modified, it's needed for infer, - // because information about output shapes doesn't exist in compile time - GKernel& kernel(); - cv::util::any& params(); - - void setArgs(std::vector &&args); - -protected: - std::shared_ptr m_priv; - - // Public versions return a typed array or opaque, those are implementation details - detail::GArrayU yieldArray(int output = 0); - detail::GOpaqueU yieldOpaque(int output = 0); -}; - -} // namespace cv - -#endif // OPENCV_GAPI_GCALL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GCALL_HPP +#define OPENCV_GAPI_GCALL_HPP + +#include // GArg +#include // GMat +#include // GScalar +#include // GFrame +#include // GArray +#include // GOpaque + +namespace cv { + +struct GKernel; + +// The whole idea of this class is to represent an operation +// which is applied to arguments. This is part of public API, +// since it is what users should use to define kernel interfaces. + +class GAPI_EXPORTS GCall final +{ +public: + class Priv; + + explicit GCall(const GKernel &k); + ~GCall(); + + template + GCall& pass(Ts&&... args) + { + setArgs({cv::GArg(std::move(args))...}); + return *this; + } + + // A generic yield method - obtain a link to operator's particular GMat output + GMat yield (int output = 0); + GMatP yieldP (int output = 0); + GScalar yieldScalar(int output = 0); + GFrame yieldFrame (int output = 0); + + template GArray yieldArray(int output = 0) + { + return GArray(yieldArray(output)); + } + + template GOpaque yieldOpaque(int output = 0) + { + return GOpaque(yieldOpaque(output)); + } + + // Internal use only + Priv& priv(); + const Priv& priv() const; + + // GKernel and params can be modified, it's needed for infer, + // because information about output shapes doesn't exist in compile time + GKernel& kernel(); + cv::util::any& params(); + + void setArgs(std::vector &&args); + +protected: + std::shared_ptr m_priv; + + // Public versions return a typed array or opaque, those are implementation details + detail::GArrayU yieldArray(int output = 0); + detail::GOpaqueU yieldOpaque(int output = 0); +}; + +} // namespace cv + +#endif // OPENCV_GAPI_GCALL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp index 97bd9cb2dc..c61110e4d5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcommon.hpp @@ -1,309 +1,309 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMMON_HPP -#define OPENCV_GAPI_GCOMMON_HPP - -#include // std::hash -#include // std::vector -#include // decay - -#include - -#include -#include -#include -#include -#include -#include - -namespace cv { - -class GMat; // FIXME: forward declaration for GOpaqueTraits - -namespace detail -{ - // This is a trait-like structure to mark backend-specific compile arguments - // with tags - template struct CompileArgTag; - - // These structures are tags which separate kernels and transformations - struct KernelTag - {}; - struct TransformTag - {}; - - // This enum is utilized mostly by GArray and GOpaque to store and recognize their internal data - // types (aka Host type). Also it is widely used during serialization routine. - enum class OpaqueKind: int - { - CV_UNKNOWN, // Unknown, generic, opaque-to-GAPI data type unsupported in graph seriallization - CV_BOOL, // bool user G-API data - CV_INT, // int user G-API data - CV_INT64, // int64_t user G-API data - CV_DOUBLE, // double user G-API data - CV_FLOAT, // float user G-API data - CV_UINT64, // uint64_t user G-API data - CV_STRING, // std::string user G-API data - CV_POINT, // cv::Point user G-API data - CV_POINT2F, // cv::Point2f user G-API data - CV_POINT3F, // cv::Point3f user G-API data - CV_SIZE, // cv::Size user G-API data - CV_RECT, // cv::Rect user G-API data - CV_SCALAR, // cv::Scalar user G-API data - CV_MAT, // cv::Mat user G-API data - CV_DRAW_PRIM, // cv::gapi::wip::draw::Prim user G-API data - }; - - // Type traits helper which simplifies the extraction of kind from type - template struct GOpaqueTraits; - template struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UNKNOWN; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT64; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_DOUBLE; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_FLOAT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UINT64; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_BOOL; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_STRING; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SIZE; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SCALAR; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT2F; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT3F; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_RECT; }; - template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; - template<> struct GOpaqueTraits - { static constexpr const OpaqueKind kind = OpaqueKind::CV_DRAW_PRIM; }; - using GOpaqueTraitsArrayTypes = std::tuple; - // GOpaque is not supporting cv::Mat and cv::Scalar since there are GScalar and GMat types - using GOpaqueTraitsOpaqueTypes = std::tuple; -} // namespace detail - -// This definition is here because it is reused by both public(?) and internal -// modules. Keeping it here wouldn't expose public details (e.g., API-level) -// to components which are internal and operate on a lower-level entities -// (e.g., compiler, backends). -// FIXME: merge with ArgKind? -// FIXME: replace with variant[format desc]? -enum class GShape: int -{ - GMAT, - GSCALAR, - GARRAY, - GOPAQUE, - GFRAME, -}; - -namespace gapi { -namespace s11n { -namespace detail { -template struct wrap_serialize; -} // namespace detail -} // namespace s11n -} // namespace gapi - - -struct GCompileArg; - -namespace detail { - template - using is_compile_arg = std::is_same::type>; -} // namespace detail - -// CompileArg is an unified interface over backend-specific compilation -// information -// FIXME: Move to a separate file? -/** \addtogroup gapi_compile_args - * @{ - * - * @brief Compilation arguments: data structures controlling the - * compilation process - * - * G-API comes with a number of graph compilation options which can be - * passed to cv::GComputation::apply() or - * cv::GComputation::compile(). Known compilation options are listed - * in this page, while extra backends may introduce their own - * compilation options (G-API transparently accepts _everything_ which - * can be passed to cv::compile_args(), it depends on underlying - * backends if an option would be interpreted or not). - * - * For example, if an example computation is executed like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_decl_apply - * - * Extra parameter specifying which kernels to compile with can be - * passed like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp apply_with_param - */ - -/** - * @brief Represents an arbitrary compilation argument. - * - * Any value can be wrapped into cv::GCompileArg, but only known ones - * (to G-API or its backends) can be interpreted correctly. - * - * Normally objects of this class shouldn't be created manually, use - * cv::compile_args() function which automatically wraps everything - * passed in (a variadic template parameter pack) into a vector of - * cv::GCompileArg objects. - */ -struct GCompileArg -{ -public: - // NB: Required for pythnon bindings - GCompileArg() = default; - - std::string tag; - - // FIXME: use decay in GArg/other trait-based wrapper before leg is shot! - template::value, int>::type = 0> - explicit GCompileArg(T &&t) - : tag(detail::CompileArgTag::type>::tag()) - , serializeF(cv::gapi::s11n::detail::has_S11N_spec::value ? - &cv::gapi::s11n::detail::wrap_serialize::serialize : - nullptr) - , arg(t) - { - } - - template T& get() - { - return util::any_cast(arg); - } - - template const T& get() const - { - return util::any_cast(arg); - } - - void serialize(cv::gapi::s11n::IOStream& os) const - { - if (serializeF) - { - serializeF(os, *this); - } - } - -private: - std::function serializeF; - util::any arg; -}; - -using GCompileArgs = std::vector; - -inline cv::GCompileArgs& operator += ( cv::GCompileArgs &lhs, - const cv::GCompileArgs &rhs) -{ - lhs.reserve(lhs.size() + rhs.size()); - lhs.insert(lhs.end(), rhs.begin(), rhs.end()); - return lhs; -} - -/** - * @brief Wraps a list of arguments (a parameter pack) into a vector of - * compilation arguments (cv::GCompileArg). - */ -template GCompileArgs compile_args(Ts&&... args) -{ - return GCompileArgs{ GCompileArg(args)... }; -} - -namespace gapi -{ -/** - * @brief Retrieves particular compilation argument by its type from - * cv::GCompileArgs - */ -template -inline cv::util::optional getCompileArg(const cv::GCompileArgs &args) -{ - for (auto &compile_arg : args) - { - if (compile_arg.tag == cv::detail::CompileArgTag::tag()) - { - return cv::util::optional(compile_arg.get()); - } - } - return cv::util::optional(); -} - -namespace s11n { -namespace detail { -template struct wrap_serialize -{ - static void serialize(IOStream& os, const GCompileArg& arg) - { - using DT = typename std::decay::type; - S11N
::serialize(os, arg.get
()); - } -}; -} // namespace detail -} // namespace s11n -} // namespace gapi - -/** @} gapi_compile_args */ - -/** - * @brief Ask G-API to dump compiled graph in Graphviz format under - * the given file name. - * - * Specifies a graph dump path (path to .dot file to be generated). - * G-API will dump a .dot file under specified path during a - * compilation process if this flag is passed. - */ -struct graph_dump_path -{ - std::string m_dump_path; -}; - -/** - * @brief Ask G-API to use threaded executor when cv::GComputation - * is compiled via cv::GComputation::compile method. - * - * Specifies a number of threads that should be used by executor. - */ -struct GAPI_EXPORTS use_threaded_executor -{ - use_threaded_executor(); - explicit use_threaded_executor(const uint32_t nthreads); - - uint32_t num_threads; -}; - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.graph_dump_path"; } - }; - - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.threaded_executor"; } - }; -} - -} // namespace cv - -// std::hash overload for GShape -namespace std -{ -template<> struct hash -{ - size_t operator() (cv::GShape sh) const - { - return std::hash()(static_cast(sh)); - } -}; -} // namespace std - - -#endif // OPENCV_GAPI_GCOMMON_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMMON_HPP +#define OPENCV_GAPI_GCOMMON_HPP + +#include // std::hash +#include // std::vector +#include // decay + +#include + +#include +#include +#include +#include +#include +#include + +namespace cv { + +class GMat; // FIXME: forward declaration for GOpaqueTraits + +namespace detail +{ + // This is a trait-like structure to mark backend-specific compile arguments + // with tags + template struct CompileArgTag; + + // These structures are tags which separate kernels and transformations + struct KernelTag + {}; + struct TransformTag + {}; + + // This enum is utilized mostly by GArray and GOpaque to store and recognize their internal data + // types (aka Host type). Also it is widely used during serialization routine. + enum class OpaqueKind: int + { + CV_UNKNOWN, // Unknown, generic, opaque-to-GAPI data type unsupported in graph seriallization + CV_BOOL, // bool user G-API data + CV_INT, // int user G-API data + CV_INT64, // int64_t user G-API data + CV_DOUBLE, // double user G-API data + CV_FLOAT, // float user G-API data + CV_UINT64, // uint64_t user G-API data + CV_STRING, // std::string user G-API data + CV_POINT, // cv::Point user G-API data + CV_POINT2F, // cv::Point2f user G-API data + CV_POINT3F, // cv::Point3f user G-API data + CV_SIZE, // cv::Size user G-API data + CV_RECT, // cv::Rect user G-API data + CV_SCALAR, // cv::Scalar user G-API data + CV_MAT, // cv::Mat user G-API data + CV_DRAW_PRIM, // cv::gapi::wip::draw::Prim user G-API data + }; + + // Type traits helper which simplifies the extraction of kind from type + template struct GOpaqueTraits; + template struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UNKNOWN; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_INT64; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_DOUBLE; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_FLOAT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_UINT64; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_BOOL; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_STRING; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SIZE; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_SCALAR; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT2F; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_POINT3F; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_RECT; }; + template<> struct GOpaqueTraits { static constexpr const OpaqueKind kind = OpaqueKind::CV_MAT; }; + template<> struct GOpaqueTraits + { static constexpr const OpaqueKind kind = OpaqueKind::CV_DRAW_PRIM; }; + using GOpaqueTraitsArrayTypes = std::tuple; + // GOpaque is not supporting cv::Mat and cv::Scalar since there are GScalar and GMat types + using GOpaqueTraitsOpaqueTypes = std::tuple; +} // namespace detail + +// This definition is here because it is reused by both public(?) and internal +// modules. Keeping it here wouldn't expose public details (e.g., API-level) +// to components which are internal and operate on a lower-level entities +// (e.g., compiler, backends). +// FIXME: merge with ArgKind? +// FIXME: replace with variant[format desc]? +enum class GShape: int +{ + GMAT, + GSCALAR, + GARRAY, + GOPAQUE, + GFRAME, +}; + +namespace gapi { +namespace s11n { +namespace detail { +template struct wrap_serialize; +} // namespace detail +} // namespace s11n +} // namespace gapi + + +struct GCompileArg; + +namespace detail { + template + using is_compile_arg = std::is_same::type>; +} // namespace detail + +// CompileArg is an unified interface over backend-specific compilation +// information +// FIXME: Move to a separate file? +/** \addtogroup gapi_compile_args + * @{ + * + * @brief Compilation arguments: data structures controlling the + * compilation process + * + * G-API comes with a number of graph compilation options which can be + * passed to cv::GComputation::apply() or + * cv::GComputation::compile(). Known compilation options are listed + * in this page, while extra backends may introduce their own + * compilation options (G-API transparently accepts _everything_ which + * can be passed to cv::compile_args(), it depends on underlying + * backends if an option would be interpreted or not). + * + * For example, if an example computation is executed like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_decl_apply + * + * Extra parameter specifying which kernels to compile with can be + * passed like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp apply_with_param + */ + +/** + * @brief Represents an arbitrary compilation argument. + * + * Any value can be wrapped into cv::GCompileArg, but only known ones + * (to G-API or its backends) can be interpreted correctly. + * + * Normally objects of this class shouldn't be created manually, use + * cv::compile_args() function which automatically wraps everything + * passed in (a variadic template parameter pack) into a vector of + * cv::GCompileArg objects. + */ +struct GCompileArg +{ +public: + // NB: Required for pythnon bindings + GCompileArg() = default; + + std::string tag; + + // FIXME: use decay in GArg/other trait-based wrapper before leg is shot! + template::value, int>::type = 0> + explicit GCompileArg(T &&t) + : tag(detail::CompileArgTag::type>::tag()) + , serializeF(cv::gapi::s11n::detail::has_S11N_spec::value ? + &cv::gapi::s11n::detail::wrap_serialize::serialize : + nullptr) + , arg(t) + { + } + + template T& get() + { + return util::any_cast(arg); + } + + template const T& get() const + { + return util::any_cast(arg); + } + + void serialize(cv::gapi::s11n::IOStream& os) const + { + if (serializeF) + { + serializeF(os, *this); + } + } + +private: + std::function serializeF; + util::any arg; +}; + +using GCompileArgs = std::vector; + +inline cv::GCompileArgs& operator += ( cv::GCompileArgs &lhs, + const cv::GCompileArgs &rhs) +{ + lhs.reserve(lhs.size() + rhs.size()); + lhs.insert(lhs.end(), rhs.begin(), rhs.end()); + return lhs; +} + +/** + * @brief Wraps a list of arguments (a parameter pack) into a vector of + * compilation arguments (cv::GCompileArg). + */ +template GCompileArgs compile_args(Ts&&... args) +{ + return GCompileArgs{ GCompileArg(args)... }; +} + +namespace gapi +{ +/** + * @brief Retrieves particular compilation argument by its type from + * cv::GCompileArgs + */ +template +inline cv::util::optional getCompileArg(const cv::GCompileArgs &args) +{ + for (auto &compile_arg : args) + { + if (compile_arg.tag == cv::detail::CompileArgTag::tag()) + { + return cv::util::optional(compile_arg.get()); + } + } + return cv::util::optional(); +} + +namespace s11n { +namespace detail { +template struct wrap_serialize +{ + static void serialize(IOStream& os, const GCompileArg& arg) + { + using DT = typename std::decay::type; + S11N
::serialize(os, arg.get
()); + } +}; +} // namespace detail +} // namespace s11n +} // namespace gapi + +/** @} gapi_compile_args */ + +/** + * @brief Ask G-API to dump compiled graph in Graphviz format under + * the given file name. + * + * Specifies a graph dump path (path to .dot file to be generated). + * G-API will dump a .dot file under specified path during a + * compilation process if this flag is passed. + */ +struct graph_dump_path +{ + std::string m_dump_path; +}; + +/** + * @brief Ask G-API to use threaded executor when cv::GComputation + * is compiled via cv::GComputation::compile method. + * + * Specifies a number of threads that should be used by executor. + */ +struct GAPI_EXPORTS use_threaded_executor +{ + use_threaded_executor(); + explicit use_threaded_executor(const uint32_t nthreads); + + uint32_t num_threads; +}; + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.graph_dump_path"; } + }; + + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.threaded_executor"; } + }; +} + +} // namespace cv + +// std::hash overload for GShape +namespace std +{ +template<> struct hash +{ + size_t operator() (cv::GShape sh) const + { + return std::hash()(static_cast(sh)); + } +}; +} // namespace std + + +#endif // OPENCV_GAPI_GCOMMON_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp index d827e478e4..ac36783d62 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled.hpp @@ -1,232 +1,232 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPILED_HPP -#define OPENCV_GAPI_GCOMPILED_HPP - -#include - -#include -#include -#include - -namespace cv { - -// This class represents a compiled computation. -// In theory (and ideally), it can be used w/o the rest of APIs. -// In theory (and ideally), it can be serialized/deserialized. -// It can enable scenarious like deployment to an autonomous devince, FuSa, etc. -// -// Currently GCompiled assumes all GMats you used to pass data to G-API -// are valid and not destroyed while you use a GCompiled object. -// -// FIXME: In future, there should be a way to name I/O objects and specify it -// to GCompiled externally (for example, when it is loaded on the target system). - -/** - * \addtogroup gapi_main_classes - * @{ - */ -/** - * @brief Represents a compiled computation (graph). Can only be used - * with image / data formats & resolutions it was compiled for, with - * some exceptions. - * - * This class represents a product of graph compilation (calling - * cv::GComputation::compile()). Objects of this class actually do - * data processing, and graph execution is incapsulated into objects - * of this class. Execution model itself depends on kernels and - * backends which were using during the compilation, see @ref - * gapi_compile_args for details. - * - * In a general case, GCompiled objects can be applied to data only in - * that formats/resolutions they were compiled for (see @ref - * gapi_meta_args). However, if the underlying backends allow, a - * compiled object can be _reshaped_ to handle data (images) of - * different resolution, though formats and types must remain the same. - * - * GCompiled is very similar to `std::function<>` in its semantics -- - * running it looks like a function call in the user code. - * - * At the moment, GCompiled objects are not reentrant -- generally, - * the objects are stateful since graph execution itself is a stateful - * process and this state is now maintained in GCompiled's own memory - * (not on the process stack). - * - * At the same time, two different GCompiled objects produced from the - * single cv::GComputation are completely independent and can be used - * concurrently. - * - * @sa GStreamingCompiled - */ -class GAPI_EXPORTS GCompiled -{ -public: - /// @private - class GAPI_EXPORTS Priv; - - /** - * @brief Constructs an empty object - */ - GCompiled(); - - /** - * @brief Run the compiled computation, a generic version. - * - * @param ins vector of inputs to process. - * @param outs vector of outputs to produce. - * - * Input/output vectors must have the same number of elements as - * defined in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::Mat needs to be passed where cv::GMat has been - * declared as input, and so on). Run-time exception is generated - * otherwise. - * - * Objects in output vector may remain empty (like cv::Mat) -- - * G-API will automatically initialize output objects to proper formats. - * - * @note Don't construct GRunArgs/GRunArgsP objects manually, use - * cv::gin()/cv::gout() wrappers instead. - */ - void operator() (GRunArgs &&ins, GRunArgsP &&outs); // Generic arg-to-arg -#if !defined(GAPI_STANDALONE) - - /** - * @brief Execute an unary computation - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Mat for unary computation - * process. - */ - void operator() (cv::Mat in, cv::Mat &out); // Unary overload - - /** - * @brief Execute an unary computation - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Scalar for unary computation - * process. - */ - void operator() (cv::Mat in, cv::Scalar &out); // Unary overload (scalar) - - /** - * @brief Execute a binary computation - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Mat for binary computation - * process. - */ - void operator() (cv::Mat in1, cv::Mat in2, cv::Mat &out); // Binary overload - - /** - * @brief Execute an binary computation - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Scalar for binary computation - * process. - */ - void operator() (cv::Mat in1, cv::Mat in2, cv::Scalar &out); // Binary overload (scalar) - - /** - * @brief Execute a computation with arbitrary number of - * inputs/outputs. - * - * @overload - * @param ins vector of input cv::Mat objects to process by the - * computation. - * @param outs vector of output cv::Mat objects to produce by the - * computation. - * - * Numbers of elements in ins/outs vectors must match numbers of - * inputs/outputs which were used to define the source GComputation. - */ - void operator() (const std::vector &ins, // Compatibility overload - const std::vector &outs); -#endif // !defined(GAPI_STANDALONE) - /// @private - Priv& priv(); - - /** - * @brief Check if compiled object is valid (non-empty) - * - * @return true if the object is runnable (valid), false otherwise - */ - explicit operator bool () const; - - /** - * @brief Vector of metadata this graph was compiled for. - * - * @return Unless _reshape_ is not supported, return value is the - * same vector which was passed to cv::GComputation::compile() to - * produce this compiled object. Otherwise, it is the latest - * metadata vector passed to reshape() (if that call was - * successful). - */ - const GMetaArgs& metas() const; // Meta passed to compile() - - /** - * @brief Vector of metadata descriptions of graph outputs - * - * @return vector with formats/resolutions of graph's output - * objects, auto-inferred from input metadata vector by - * operations which form this computation. - * - * @note GCompiled objects produced from the same - * cv::GComputiation graph with different input metas may return - * different values in this vector. - */ - const GMetaArgs& outMetas() const; - - /** - * @brief Check if the underlying backends support reshape or not. - * - * @return true if supported, false otherwise. - */ - bool canReshape() const; - - /** - * @brief Reshape a compiled graph to support new image - * resolutions. - * - * Throws an exception if an error occurs. - * - * @param inMetas new metadata to reshape on. Vector size and - * metadata shapes must match the computation's protocol. - * @param args compilation arguments to use. - */ - // FIXME: Why it requires compile args? - void reshape(const GMetaArgs& inMetas, const GCompileArgs& args); - - /** - * @brief Prepare inner kernels states for a new video-stream. - * - * GCompiled objects may be used to process video streams frame by frame. - * In this case, a GCompiled is called on every image frame individually. - * Starting OpenCV 4.4, some kernels in the graph may have their internal - * states (see GAPI_OCV_KERNEL_ST for the OpenCV backend). - * In this case, if user starts processing another video stream with - * this GCompiled, this method needs to be called to let kernels re-initialize - * their internal states to a new video stream. - */ - void prepareForNewStream(); - -protected: - /// @private - std::shared_ptr m_priv; -}; -/** @} */ - -} - -#endif // OPENCV_GAPI_GCOMPILED_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPILED_HPP +#define OPENCV_GAPI_GCOMPILED_HPP + +#include + +#include +#include +#include + +namespace cv { + +// This class represents a compiled computation. +// In theory (and ideally), it can be used w/o the rest of APIs. +// In theory (and ideally), it can be serialized/deserialized. +// It can enable scenarious like deployment to an autonomous devince, FuSa, etc. +// +// Currently GCompiled assumes all GMats you used to pass data to G-API +// are valid and not destroyed while you use a GCompiled object. +// +// FIXME: In future, there should be a way to name I/O objects and specify it +// to GCompiled externally (for example, when it is loaded on the target system). + +/** + * \addtogroup gapi_main_classes + * @{ + */ +/** + * @brief Represents a compiled computation (graph). Can only be used + * with image / data formats & resolutions it was compiled for, with + * some exceptions. + * + * This class represents a product of graph compilation (calling + * cv::GComputation::compile()). Objects of this class actually do + * data processing, and graph execution is incapsulated into objects + * of this class. Execution model itself depends on kernels and + * backends which were using during the compilation, see @ref + * gapi_compile_args for details. + * + * In a general case, GCompiled objects can be applied to data only in + * that formats/resolutions they were compiled for (see @ref + * gapi_meta_args). However, if the underlying backends allow, a + * compiled object can be _reshaped_ to handle data (images) of + * different resolution, though formats and types must remain the same. + * + * GCompiled is very similar to `std::function<>` in its semantics -- + * running it looks like a function call in the user code. + * + * At the moment, GCompiled objects are not reentrant -- generally, + * the objects are stateful since graph execution itself is a stateful + * process and this state is now maintained in GCompiled's own memory + * (not on the process stack). + * + * At the same time, two different GCompiled objects produced from the + * single cv::GComputation are completely independent and can be used + * concurrently. + * + * @sa GStreamingCompiled + */ +class GAPI_EXPORTS GCompiled +{ +public: + /// @private + class GAPI_EXPORTS Priv; + + /** + * @brief Constructs an empty object + */ + GCompiled(); + + /** + * @brief Run the compiled computation, a generic version. + * + * @param ins vector of inputs to process. + * @param outs vector of outputs to produce. + * + * Input/output vectors must have the same number of elements as + * defined in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::Mat needs to be passed where cv::GMat has been + * declared as input, and so on). Run-time exception is generated + * otherwise. + * + * Objects in output vector may remain empty (like cv::Mat) -- + * G-API will automatically initialize output objects to proper formats. + * + * @note Don't construct GRunArgs/GRunArgsP objects manually, use + * cv::gin()/cv::gout() wrappers instead. + */ + void operator() (GRunArgs &&ins, GRunArgsP &&outs); // Generic arg-to-arg +#if !defined(GAPI_STANDALONE) + + /** + * @brief Execute an unary computation + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Mat for unary computation + * process. + */ + void operator() (cv::Mat in, cv::Mat &out); // Unary overload + + /** + * @brief Execute an unary computation + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Scalar for unary computation + * process. + */ + void operator() (cv::Mat in, cv::Scalar &out); // Unary overload (scalar) + + /** + * @brief Execute a binary computation + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Mat for binary computation + * process. + */ + void operator() (cv::Mat in1, cv::Mat in2, cv::Mat &out); // Binary overload + + /** + * @brief Execute an binary computation + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Scalar for binary computation + * process. + */ + void operator() (cv::Mat in1, cv::Mat in2, cv::Scalar &out); // Binary overload (scalar) + + /** + * @brief Execute a computation with arbitrary number of + * inputs/outputs. + * + * @overload + * @param ins vector of input cv::Mat objects to process by the + * computation. + * @param outs vector of output cv::Mat objects to produce by the + * computation. + * + * Numbers of elements in ins/outs vectors must match numbers of + * inputs/outputs which were used to define the source GComputation. + */ + void operator() (const std::vector &ins, // Compatibility overload + const std::vector &outs); +#endif // !defined(GAPI_STANDALONE) + /// @private + Priv& priv(); + + /** + * @brief Check if compiled object is valid (non-empty) + * + * @return true if the object is runnable (valid), false otherwise + */ + explicit operator bool () const; + + /** + * @brief Vector of metadata this graph was compiled for. + * + * @return Unless _reshape_ is not supported, return value is the + * same vector which was passed to cv::GComputation::compile() to + * produce this compiled object. Otherwise, it is the latest + * metadata vector passed to reshape() (if that call was + * successful). + */ + const GMetaArgs& metas() const; // Meta passed to compile() + + /** + * @brief Vector of metadata descriptions of graph outputs + * + * @return vector with formats/resolutions of graph's output + * objects, auto-inferred from input metadata vector by + * operations which form this computation. + * + * @note GCompiled objects produced from the same + * cv::GComputiation graph with different input metas may return + * different values in this vector. + */ + const GMetaArgs& outMetas() const; + + /** + * @brief Check if the underlying backends support reshape or not. + * + * @return true if supported, false otherwise. + */ + bool canReshape() const; + + /** + * @brief Reshape a compiled graph to support new image + * resolutions. + * + * Throws an exception if an error occurs. + * + * @param inMetas new metadata to reshape on. Vector size and + * metadata shapes must match the computation's protocol. + * @param args compilation arguments to use. + */ + // FIXME: Why it requires compile args? + void reshape(const GMetaArgs& inMetas, const GCompileArgs& args); + + /** + * @brief Prepare inner kernels states for a new video-stream. + * + * GCompiled objects may be used to process video streams frame by frame. + * In this case, a GCompiled is called on every image frame individually. + * Starting OpenCV 4.4, some kernels in the graph may have their internal + * states (see GAPI_OCV_KERNEL_ST for the OpenCV backend). + * In this case, if user starts processing another video stream with + * this GCompiled, this method needs to be called to let kernels re-initialize + * their internal states to a new video stream. + */ + void prepareForNewStream(); + +protected: + /// @private + std::shared_ptr m_priv; +}; +/** @} */ + +} + +#endif // OPENCV_GAPI_GCOMPILED_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp index c3a1c05610..a0c2917d6a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompiled_async.hpp @@ -1,73 +1,73 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPILED_ASYNC_HPP -#define OPENCV_GAPI_GCOMPILED_ASYNC_HPP - -#include //for std::future -#include //for std::exception_ptr -#include //for std::function -#include -#include - -namespace cv { - //fwd declaration - class GCompiled; - -namespace gapi{ -namespace wip { - class GAsyncContext; - /** - These functions asynchronously (i.e. probably on a separate thread of execution) call GCompiled::operator() member function of their first argument with copies of rest of arguments (except callback) passed in. - The difference between the function is the way to get the completion notification (via callback or a waiting on std::future object) - If exception is occurred during execution of apply it is transferred to the callback (via function parameter) or passed to future (and will be thrown on call to std::future::get) - - N.B. : - Input arguments are copied on call to async function (actually on call to cv::gin) and thus do not have to outlive the actual completion of asynchronous activity. - While output arguments are "captured" by reference(pointer) and therefore _must_ outlive the asynchronous activity - (i.e. live at least until callback is called or future is unblocked) - - @param gcmpld Compiled computation (graph) to start asynchronously - @param callback Callback to be called when execution of gcmpld is done - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - */ - GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs); - - /** @overload - @param gcmpld Compiled computation (graph) to run asynchronously - @param callback Callback to be called when execution of gcmpld is done - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - @param ctx Context this request belongs to - @see async GAsyncContext - */ - GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); - - /** @overload - @param gcmpld Compiled computation (graph) to run asynchronously - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - @return std::future object to wait for completion of async operation - @see async - */ - GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs); - - /** - @param gcmpld Compiled computation (graph) to run asynchronously - @param ins Input parameters for gcmpld - @param outs Output parameters for gcmpld - @param ctx Context this request belongs to - @return std::future object to wait for completion of async operation - @see async GAsyncContext - */ - GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GCOMPILED_ASYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPILED_ASYNC_HPP +#define OPENCV_GAPI_GCOMPILED_ASYNC_HPP + +#include //for std::future +#include //for std::exception_ptr +#include //for std::function +#include +#include + +namespace cv { + //fwd declaration + class GCompiled; + +namespace gapi{ +namespace wip { + class GAsyncContext; + /** + These functions asynchronously (i.e. probably on a separate thread of execution) call GCompiled::operator() member function of their first argument with copies of rest of arguments (except callback) passed in. + The difference between the function is the way to get the completion notification (via callback or a waiting on std::future object) + If exception is occurred during execution of apply it is transferred to the callback (via function parameter) or passed to future (and will be thrown on call to std::future::get) + + N.B. : + Input arguments are copied on call to async function (actually on call to cv::gin) and thus do not have to outlive the actual completion of asynchronous activity. + While output arguments are "captured" by reference(pointer) and therefore _must_ outlive the asynchronous activity + (i.e. live at least until callback is called or future is unblocked) + + @param gcmpld Compiled computation (graph) to start asynchronously + @param callback Callback to be called when execution of gcmpld is done + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + */ + GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs); + + /** @overload + @param gcmpld Compiled computation (graph) to run asynchronously + @param callback Callback to be called when execution of gcmpld is done + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + @param ctx Context this request belongs to + @see async GAsyncContext + */ + GAPI_EXPORTS void async(GCompiled& gcmpld, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); + + /** @overload + @param gcmpld Compiled computation (graph) to run asynchronously + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + @return std::future object to wait for completion of async operation + @see async + */ + GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs); + + /** + @param gcmpld Compiled computation (graph) to run asynchronously + @param ins Input parameters for gcmpld + @param outs Output parameters for gcmpld + @param ctx Context this request belongs to + @return std::future object to wait for completion of async operation + @see async GAsyncContext + */ + GAPI_EXPORTS std::future async(GCompiled& gcmpld, GRunArgs &&ins, GRunArgsP &&outs, GAsyncContext& ctx); +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GCOMPILED_ASYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp index e286766967..df0ce34045 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcompoundkernel.hpp @@ -1,139 +1,139 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPOUNDKERNEL_HPP -#define OPENCV_GAPI_GCOMPOUNDKERNEL_HPP - -#include -#include -#include -#include - -namespace cv { -namespace gapi -{ -namespace compound -{ - // FIXME User does not need to know about this function - // Needs that user may define compound kernels(as cpu kernels) - GAPI_EXPORTS cv::gapi::GBackend backend(); -} // namespace compound -} // namespace gapi - -namespace detail -{ - -struct GCompoundContext -{ - explicit GCompoundContext(const GArgs& in_args); - template - const T& inArg(int input) { return m_args.at(input).get(); } - - GArgs m_args; - GArgs m_results; -}; - -class GAPI_EXPORTS GCompoundKernel -{ -// Compound kernel must use all of it's inputs -public: - using F = std::function; - - explicit GCompoundKernel(const F& f); - void apply(GCompoundContext& ctx); - -protected: - F m_f; -}; - -template struct get_compound_in -{ - static T get(GCompoundContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -template struct get_compound_in> -{ - static cv::GArray get(GCompoundContext &ctx, int idx) - { - auto array = cv::GArray(); - ctx.m_args[idx] = GArg(array); - return array; - } -}; - -template struct get_compound_in> -{ - static cv::GOpaque get(GCompoundContext &ctx, int idx) - { - auto opaq = cv::GOpaque(); - ctx.m_args[idx] = GArg(opaq); - return opaq; - } -}; - -template<> struct get_compound_in -{ - static cv::GMatP get(GCompoundContext &ctx, int idx) - { - auto mat = cv::GMatP(); - ctx.m_args[idx] = GArg(mat); - return mat; - } -}; - -template -struct GCompoundCallHelper; - -template -struct GCompoundCallHelper, std::tuple > -{ - template - static void expand_impl(GCompoundContext &ctx, detail::Seq, detail::Seq) - { - auto result = Impl::expand(get_compound_in::get(ctx, IIs)...); - auto tuple_return = tuple_wrap_helper::get(std::move(result)); - ctx.m_results = { cv::GArg(std::get(tuple_return))... }; - } - - static void expand(GCompoundContext &ctx) - { - expand_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -template -class GCompoundKernelImpl: public cv::detail::GCompoundCallHelper, - public cv::detail::KernelTag -{ - using P = cv::detail::GCompoundCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::compound::backend(); } - static GCompoundKernel kernel() { return GCompoundKernel(&P::expand); } -}; - -} // namespace detail - - -/** - * Declares a new compound kernel. See this - * [documentation chapter](@ref gapi_kernel_compound) - * on compound kernels for more details. - * - * @param Name type name for new kernel - * @param API the interface this kernel implements - */ -#define GAPI_COMPOUND_KERNEL(Name, API) \ - struct Name: public cv::detail::GCompoundKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GCOMPOUNDKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPOUNDKERNEL_HPP +#define OPENCV_GAPI_GCOMPOUNDKERNEL_HPP + +#include +#include +#include +#include + +namespace cv { +namespace gapi +{ +namespace compound +{ + // FIXME User does not need to know about this function + // Needs that user may define compound kernels(as cpu kernels) + GAPI_EXPORTS cv::gapi::GBackend backend(); +} // namespace compound +} // namespace gapi + +namespace detail +{ + +struct GCompoundContext +{ + explicit GCompoundContext(const GArgs& in_args); + template + const T& inArg(int input) { return m_args.at(input).get(); } + + GArgs m_args; + GArgs m_results; +}; + +class GAPI_EXPORTS GCompoundKernel +{ +// Compound kernel must use all of it's inputs +public: + using F = std::function; + + explicit GCompoundKernel(const F& f); + void apply(GCompoundContext& ctx); + +protected: + F m_f; +}; + +template struct get_compound_in +{ + static T get(GCompoundContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +template struct get_compound_in> +{ + static cv::GArray get(GCompoundContext &ctx, int idx) + { + auto array = cv::GArray(); + ctx.m_args[idx] = GArg(array); + return array; + } +}; + +template struct get_compound_in> +{ + static cv::GOpaque get(GCompoundContext &ctx, int idx) + { + auto opaq = cv::GOpaque(); + ctx.m_args[idx] = GArg(opaq); + return opaq; + } +}; + +template<> struct get_compound_in +{ + static cv::GMatP get(GCompoundContext &ctx, int idx) + { + auto mat = cv::GMatP(); + ctx.m_args[idx] = GArg(mat); + return mat; + } +}; + +template +struct GCompoundCallHelper; + +template +struct GCompoundCallHelper, std::tuple > +{ + template + static void expand_impl(GCompoundContext &ctx, detail::Seq, detail::Seq) + { + auto result = Impl::expand(get_compound_in::get(ctx, IIs)...); + auto tuple_return = tuple_wrap_helper::get(std::move(result)); + ctx.m_results = { cv::GArg(std::get(tuple_return))... }; + } + + static void expand(GCompoundContext &ctx) + { + expand_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +template +class GCompoundKernelImpl: public cv::detail::GCompoundCallHelper, + public cv::detail::KernelTag +{ + using P = cv::detail::GCompoundCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::compound::backend(); } + static GCompoundKernel kernel() { return GCompoundKernel(&P::expand); } +}; + +} // namespace detail + + +/** + * Declares a new compound kernel. See this + * [documentation chapter](@ref gapi_kernel_compound) + * on compound kernels for more details. + * + * @param Name type name for new kernel + * @param API the interface this kernel implements + */ +#define GAPI_COMPOUND_KERNEL(Name, API) \ + struct Name: public cv::detail::GCompoundKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GCOMPOUNDKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp index 4803c7d999..196eb37c6b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation.hpp @@ -1,581 +1,581 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GCOMPUTATION_HPP -#define OPENCV_GAPI_GCOMPUTATION_HPP - -#include - -#include -#include -#include -#include -#include -#include - -namespace cv { - -namespace detail -{ - // FIXME: move to algorithm, cover with separate tests - // FIXME: replace with O(1) version (both memory and compilation time) - template - struct last_type; - - template - struct last_type { using type = T;}; - - template - struct last_type { using type = typename last_type::type; }; - - template - using last_type_t = typename last_type::type; -} - -// Forward-declare the serialization objects -namespace gapi { -namespace s11n { - struct IIStream; - struct IOStream; -} // namespace s11n -} // namespace gapi - -/** - * \addtogroup gapi_main_classes - * @{ - * - * @brief G-API classes for constructed and compiled graphs. - */ - -/** - * @brief GComputation class represents a captured computation - * graph. GComputation objects form boundaries for expression code - * user writes with G-API, allowing to compile and execute it. - * - * G-API computations are defined with input/output data - * objects. G-API will track automatically which operations connect - * specified outputs to the inputs, forming up a call graph to be - * executed. The below example expresses calculation of Sobel operator - * for edge detection (\f$G = \sqrt{G_x^2 + G_y^2}\f$): - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_def - * - * Full pipeline can be now captured with this object declaration: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_full - * - * Input/output data objects on which a call graph should be - * reconstructed are passed using special wrappers cv::GIn and - * cv::GOut. G-API will track automatically which operations form a - * path from inputs to outputs and build the execution graph appropriately. - * - * Note that cv::GComputation doesn't take ownership on data objects - * it is defined. Moreover, multiple GComputation objects may be - * defined on the same expressions, e.g. a smaller pipeline which - * expects that image gradients are already pre-calculated may be - * defined like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_sub - * - * The resulting graph would expect two inputs and produce one - * output. In this case, it doesn't matter if gx/gy data objects are - * results of cv::gapi::Sobel operators -- G-API will stop unrolling - * expressions and building the underlying graph one reaching this - * data objects. - * - * The way how GComputation is defined is important as its definition - * specifies graph _protocol_ -- the way how the graph should be - * used. Protocol is defined by number of inputs, number of outputs, - * and shapes of inputs and outputs. - * - * In the above example, sobelEdge expects one Mat on input and - * produces one Mat; while sobelEdgeSub expects two Mats on input and - * produces one Mat. GComputation's protocol defines how other - * computation methods should be used -- cv::GComputation::compile() and - * cv::GComputation::apply(). For example, if a graph is defined on - * two GMat inputs, two cv::Mat objects have to be passed to apply() - * for execution. GComputation checks protocol correctness in runtime - * so passing a different number of objects in apply() or passing - * cv::Scalar instead of cv::Mat there would compile well as a C++ - * source but raise an exception in run-time. G-API also comes with a - * typed wrapper cv::GComputationT<> which introduces this type-checking in - * compile-time. - * - * cv::GComputation itself is a thin object which just captures what - * the graph is. The compiled graph (which actually process data) is - * represented by class GCompiled. Use compile() method to generate a - * compiled graph with given compile options. cv::GComputation can - * also be used to process data with implicit graph compilation - * on-the-fly, see apply() for details. - * - * GComputation is a reference-counted object -- once defined, all its - * copies will refer to the same instance. - * - * @sa GCompiled - */ -class GAPI_EXPORTS_W GComputation -{ -public: - class Priv; - typedef std::function Generator; - - // Various constructors enable different ways to define a computation: ///// - // 1. Generic constructors - /** - * @brief Define a computation using a generator function. - * - * Graph can be defined in-place directly at the moment of its - * construction with a lambda: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_gen - * - * This may be useful since all temporary objects (cv::GMats) and - * namespaces can be localized to scope of lambda, without - * contaminating the parent scope with probably unnecessary objects - * and information. - * - * @param gen generator function which returns a cv::GComputation, - * see Generator. - */ - GComputation(const Generator& gen); // Generator - // overload - - /** - * @brief Generic GComputation constructor. - * - * Constructs a new graph with a given protocol, specified as a - * flow of operations connecting input/output objects. Throws if - * the passed boundaries are invalid, e.g. if there's no - * functional dependency (path) between given outputs and inputs. - * - * @param ins Input data vector. - * @param outs Output data vector. - * - * @note Don't construct GProtoInputArgs/GProtoOutputArgs objects - * directly, use cv::GIn()/cv::GOut() wrapper functions instead. - * - * @sa @ref gapi_data_objects - */ - GAPI_WRAP GComputation(GProtoInputArgs &&ins, - GProtoOutputArgs &&outs); // Arg-to-arg overload - - // 2. Syntax sugar and compatibility overloads - /** - * @brief Defines an unary (one input -- one output) computation - * - * @overload - * @param in input GMat of the defined unary computation - * @param out output GMat of the defined unary computation - */ - GAPI_WRAP GComputation(GMat in, GMat out); // Unary overload - - /** - * @brief Defines an unary (one input -- one output) computation - * - * @overload - * @param in input GMat of the defined unary computation - * @param out output GScalar of the defined unary computation - */ - GAPI_WRAP GComputation(GMat in, GScalar out); // Unary overload (scalar) - - /** - * @brief Defines a binary (two inputs -- one output) computation - * - * @overload - * @param in1 first input GMat of the defined binary computation - * @param in2 second input GMat of the defined binary computation - * @param out output GMat of the defined binary computation - */ - GAPI_WRAP GComputation(GMat in1, GMat in2, GMat out); // Binary overload - - /** - * @brief Defines a binary (two inputs -- one output) computation - * - * @overload - * @param in1 first input GMat of the defined binary computation - * @param in2 second input GMat of the defined binary computation - * @param out output GScalar of the defined binary computation - */ - GComputation(GMat in1, GMat in2, GScalar out); // Binary - // overload - // (scalar) - - /** - * @brief Defines a computation with arbitrary input/output number. - * - * @overload - * @param ins vector of inputs GMats for this computation - * @param outs vector of outputs GMats for this computation - * - * Use this overload for cases when number of computation - * inputs/outputs is not known in compile-time -- e.g. when graph - * is programmatically generated to build an image pyramid with - * the given number of levels, etc. - */ - GComputation(const std::vector &ins, // Compatibility overload - const std::vector &outs); - - // Various versions of apply(): //////////////////////////////////////////// - // 1. Generic apply() - /** - * @brief Compile graph on-the-fly and immediately execute it on - * the inputs data vectors. - * - * Number of input/output data objects must match GComputation's - * protocol, also types of host data objects (cv::Mat, cv::Scalar) - * must match the shapes of data objects from protocol (cv::GMat, - * cv::GScalar). If there's a mismatch, a run-time exception will - * be generated. - * - * Internally, a cv::GCompiled object is created for the given - * input format configuration, which then is executed on the input - * data immediately. cv::GComputation caches compiled objects - * produced within apply() -- if this method would be called next - * time with the same input parameters (image formats, image - * resolution, etc), the underlying compiled graph will be reused - * without recompilation. If new metadata doesn't match the cached - * one, the underlying compiled graph is regenerated. - * - * @note compile() always triggers a compilation process and - * produces a new GCompiled object regardless if a similar one has - * been cached via apply() or not. - * - * @param ins vector of input data to process. Don't create - * GRunArgs object manually, use cv::gin() wrapper instead. - * @param outs vector of output data to fill results in. cv::Mat - * objects may be empty in this vector, G-API will automatically - * initialize it with the required format & dimensions. Don't - * create GRunArgsP object manually, use cv::gout() wrapper instead. - * @param args a list of compilation arguments to pass to the - * underlying compilation process. Don't create GCompileArgs - * object manually, use cv::compile_args() wrapper instead. - * - * @sa @ref gapi_data_objects, @ref gapi_compile_args - */ - void apply(GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); // Arg-to-arg overload - - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP GRunArgs apply(const cv::detail::ExtractArgsCallback &callback, - GCompileArgs &&args = {}); - - /// @private -- Exclude this function from OpenCV documentation - void apply(const std::vector& ins, // Compatibility overload - const std::vector& outs, - GCompileArgs &&args = {}); - - // 2. Syntax sugar and compatibility overloads -#if !defined(GAPI_STANDALONE) - /** - * @brief Execute an unary computation (with compilation on the fly) - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Mat for unary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in, cv::Mat &out, GCompileArgs &&args = {}); // Unary overload - - /** - * @brief Execute an unary computation (with compilation on the fly) - * - * @overload - * @param in input cv::Mat for unary computation - * @param out output cv::Scalar for unary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in, cv::Scalar &out, GCompileArgs &&args = {}); // Unary overload (scalar) - - /** - * @brief Execute a binary computation (with compilation on the fly) - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Mat for binary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in1, cv::Mat in2, cv::Mat &out, GCompileArgs &&args = {}); // Binary overload - - /** - * @brief Execute an binary computation (with compilation on the fly) - * - * @overload - * @param in1 first input cv::Mat for binary computation - * @param in2 second input cv::Mat for binary computation - * @param out output cv::Scalar for binary computation - * @param args compilation arguments for underlying compilation - * process. - */ - void apply(cv::Mat in1, cv::Mat in2, cv::Scalar &out, GCompileArgs &&args = {}); // Binary overload (scalar) - - /** - * @brief Execute a computation with arbitrary number of - * inputs/outputs (with compilation on-the-fly). - * - * @overload - * @param ins vector of input cv::Mat objects to process by the - * computation. - * @param outs vector of output cv::Mat objects to produce by the - * computation. - * @param args compilation arguments for underlying compilation - * process. - * - * Numbers of elements in ins/outs vectors must match numbers of - * inputs/outputs which were used to define this GComputation. - */ - void apply(const std::vector& ins, // Compatibility overload - std::vector& outs, - GCompileArgs &&args = {}); -#endif // !defined(GAPI_STANDALONE) - // Various versions of compile(): ////////////////////////////////////////// - // 1. Generic compile() - requires metas to be passed as vector - /** - * @brief Compile the computation for specific input format(s). - * - * This method triggers compilation process and produces a new - * GCompiled object which then can process data of the given - * format. Passing data with different format to the compiled - * computation will generate a run-time exception. - * - * @param in_metas vector of input metadata configuration. Grab - * metadata from real data objects (like cv::Mat or cv::Scalar) - * using cv::descr_of(), or create it on your own. - * @param args compilation arguments for this compilation - * process. Compilation arguments directly affect what kind of - * executable object would be produced, e.g. which kernels (and - * thus, devices) would be used to execute computation. - * - * @return GCompiled, an executable computation compiled - * specifically for the given input parameters. - * - * @sa @ref gapi_compile_args - */ - GCompiled compile(GMetaArgs &&in_metas, GCompileArgs &&args = {}); - - // 2. Syntax sugar - variadic list of metas, no extra compile args - // FIXME: SFINAE looks ugly in the generated documentation - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced. - * - * @return GCompiled, an executable computation compiled - * specifically for the given input parameters. - */ - template - auto compile(const Ts&... metas) -> - typename std::enable_if::value, GCompiled>::type - { - return compile(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); - } - - // 3. Syntax sugar - variadic list of metas, extra compile args - // (seems optional parameters don't work well when there's an variadic template - // comes first) - // - // Ideally it should look like: - // - // template - // GCompiled compile(const Ts&... metas, GCompileArgs &&args) - // - // But not all compilers can handle this (and seems they shouldn't be able to). - // FIXME: SFINAE looks ugly in the generated documentation - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced, - * followed by GCompileArgs object representing compilation - * arguments for this process. - * - * @return GCompiled, an executable computation compiled - * specifically for the given input parameters. - */ - template - auto compile(const Ts&... meta_and_compile_args) -> - typename std::enable_if::value - && std::is_same >::value, - GCompiled>::type - { - //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill - return compile(std::make_tuple(meta_and_compile_args...), - typename detail::MkSeq::type()); - } - - - // FIXME: Document properly in the Doxygen format - // Video-oriented pipeline compilation: - // 1. A generic version - /** - * @brief Compile the computation for streaming mode. - * - * This method triggers compilation process and produces a new - * GStreamingCompiled object which then can process video stream - * data of the given format. Passing a stream in a different - * format to the compiled computation will generate a run-time - * exception. - * - * @param in_metas vector of input metadata configuration. Grab - * metadata from real data objects (like cv::Mat or cv::Scalar) - * using cv::descr_of(), or create it on your own. - * - * @param args compilation arguments for this compilation - * process. Compilation arguments directly affect what kind of - * executable object would be produced, e.g. which kernels (and - * thus, devices) would be used to execute computation. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled specifically for the given input - * parameters. - * - * @sa @ref gapi_compile_args - */ - GAPI_WRAP GStreamingCompiled compileStreaming(GMetaArgs &&in_metas, GCompileArgs &&args = {}); - - /** - * @brief Compile the computation for streaming mode. - * - * This method triggers compilation process and produces a new - * GStreamingCompiled object which then can process video stream - * data in any format. Underlying mechanisms will be adjusted to - * every new input video stream automatically, but please note that - * _not all_ existing backends support this (see reshape()). - * - * @param args compilation arguments for this compilation - * process. Compilation arguments directly affect what kind of - * executable object would be produced, e.g. which kernels (and - * thus, devices) would be used to execute computation. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled for any input image format. - * - * @sa @ref gapi_compile_args - */ - GAPI_WRAP GStreamingCompiled compileStreaming(GCompileArgs &&args = {}); - - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP GStreamingCompiled compileStreaming(const cv::detail::ExtractMetaCallback &callback, - GCompileArgs &&args = {}); - - // 2. Direct metadata version - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled specifically for the given input - * parameters. - */ - template - auto compileStreaming(const Ts&... metas) -> - typename std::enable_if::value, GStreamingCompiled>::type - { - return compileStreaming(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); - } - - // 2. Direct metadata + compile arguments version - /** - * @overload - * - * Takes a variadic parameter pack with metadata - * descriptors for which a compiled object needs to be produced, - * followed by GCompileArgs object representing compilation - * arguments for this process. - * - * @return GStreamingCompiled, a streaming-oriented executable - * computation compiled specifically for the given input - * parameters. - */ - template - auto compileStreaming(const Ts&... meta_and_compile_args) -> - typename std::enable_if::value - && std::is_same >::value, - GStreamingCompiled>::type - { - //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill - return compileStreaming(std::make_tuple(meta_and_compile_args...), - typename detail::MkSeq::type()); - } - - // Internal use only - /// @private - Priv& priv(); - /// @private - const Priv& priv() const; - /// @private - explicit GComputation(cv::gapi::s11n::IIStream &); - /// @private - void serialize(cv::gapi::s11n::IOStream &) const; - -protected: - - // 4. Helper methods for (3) - /// @private - template - GCompiled compile(const std::tuple &meta_and_compile_args, detail::Seq) - { - GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; - GCompileArgs comp_args = std::get(meta_and_compile_args); - return compile(std::move(meta_args), std::move(comp_args)); - } - template - GStreamingCompiled compileStreaming(const std::tuple &meta_and_compile_args, detail::Seq) - { - GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; - GCompileArgs comp_args = std::get(meta_and_compile_args); - return compileStreaming(std::move(meta_args), std::move(comp_args)); - } - void recompile(GMetaArgs&& in_metas, GCompileArgs &&args); - /// @private - std::shared_ptr m_priv; -}; -/** @} */ - -namespace gapi -{ - // FIXME: all these standalone functions need to be added to some - // common documentation section - /** - * @brief Define an tagged island (subgraph) within a computation. - * - * Declare an Island tagged with `name` and defined from `ins` to `outs` - * (exclusively, as ins/outs are data objects, and regioning is done on - * operations level). - * Throws if any operation between `ins` and `outs` are already assigned - * to another island. - * - * Islands allow to partition graph into subgraphs, fine-tuning - * the way it is scheduled by the underlying executor. - * - * @param name name of the Island to create - * @param ins vector of input data objects where the subgraph - * begins - * @param outs vector of output data objects where the subgraph - * ends. - * - * The way how an island is defined is similar to how - * cv::GComputation is defined on input/output data objects. - * Same rules apply here as well -- if there's no functional - * dependency between inputs and outputs or there's not enough - * input data objects were specified to properly calculate all - * outputs, an exception is thrown. - * - * Use cv::GIn() / cv::GOut() to specify input/output vectors. - */ - void GAPI_EXPORTS island(const std::string &name, - GProtoInputArgs &&ins, - GProtoOutputArgs &&outs); -} // namespace gapi - -} // namespace cv -#endif // OPENCV_GAPI_GCOMPUTATION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GCOMPUTATION_HPP +#define OPENCV_GAPI_GCOMPUTATION_HPP + +#include + +#include +#include +#include +#include +#include +#include + +namespace cv { + +namespace detail +{ + // FIXME: move to algorithm, cover with separate tests + // FIXME: replace with O(1) version (both memory and compilation time) + template + struct last_type; + + template + struct last_type { using type = T;}; + + template + struct last_type { using type = typename last_type::type; }; + + template + using last_type_t = typename last_type::type; +} + +// Forward-declare the serialization objects +namespace gapi { +namespace s11n { + struct IIStream; + struct IOStream; +} // namespace s11n +} // namespace gapi + +/** + * \addtogroup gapi_main_classes + * @{ + * + * @brief G-API classes for constructed and compiled graphs. + */ + +/** + * @brief GComputation class represents a captured computation + * graph. GComputation objects form boundaries for expression code + * user writes with G-API, allowing to compile and execute it. + * + * G-API computations are defined with input/output data + * objects. G-API will track automatically which operations connect + * specified outputs to the inputs, forming up a call graph to be + * executed. The below example expresses calculation of Sobel operator + * for edge detection (\f$G = \sqrt{G_x^2 + G_y^2}\f$): + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_def + * + * Full pipeline can be now captured with this object declaration: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_full + * + * Input/output data objects on which a call graph should be + * reconstructed are passed using special wrappers cv::GIn and + * cv::GOut. G-API will track automatically which operations form a + * path from inputs to outputs and build the execution graph appropriately. + * + * Note that cv::GComputation doesn't take ownership on data objects + * it is defined. Moreover, multiple GComputation objects may be + * defined on the same expressions, e.g. a smaller pipeline which + * expects that image gradients are already pre-calculated may be + * defined like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_cap_sub + * + * The resulting graph would expect two inputs and produce one + * output. In this case, it doesn't matter if gx/gy data objects are + * results of cv::gapi::Sobel operators -- G-API will stop unrolling + * expressions and building the underlying graph one reaching this + * data objects. + * + * The way how GComputation is defined is important as its definition + * specifies graph _protocol_ -- the way how the graph should be + * used. Protocol is defined by number of inputs, number of outputs, + * and shapes of inputs and outputs. + * + * In the above example, sobelEdge expects one Mat on input and + * produces one Mat; while sobelEdgeSub expects two Mats on input and + * produces one Mat. GComputation's protocol defines how other + * computation methods should be used -- cv::GComputation::compile() and + * cv::GComputation::apply(). For example, if a graph is defined on + * two GMat inputs, two cv::Mat objects have to be passed to apply() + * for execution. GComputation checks protocol correctness in runtime + * so passing a different number of objects in apply() or passing + * cv::Scalar instead of cv::Mat there would compile well as a C++ + * source but raise an exception in run-time. G-API also comes with a + * typed wrapper cv::GComputationT<> which introduces this type-checking in + * compile-time. + * + * cv::GComputation itself is a thin object which just captures what + * the graph is. The compiled graph (which actually process data) is + * represented by class GCompiled. Use compile() method to generate a + * compiled graph with given compile options. cv::GComputation can + * also be used to process data with implicit graph compilation + * on-the-fly, see apply() for details. + * + * GComputation is a reference-counted object -- once defined, all its + * copies will refer to the same instance. + * + * @sa GCompiled + */ +class GAPI_EXPORTS_W GComputation +{ +public: + class Priv; + typedef std::function Generator; + + // Various constructors enable different ways to define a computation: ///// + // 1. Generic constructors + /** + * @brief Define a computation using a generator function. + * + * Graph can be defined in-place directly at the moment of its + * construction with a lambda: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp graph_gen + * + * This may be useful since all temporary objects (cv::GMats) and + * namespaces can be localized to scope of lambda, without + * contaminating the parent scope with probably unnecessary objects + * and information. + * + * @param gen generator function which returns a cv::GComputation, + * see Generator. + */ + GComputation(const Generator& gen); // Generator + // overload + + /** + * @brief Generic GComputation constructor. + * + * Constructs a new graph with a given protocol, specified as a + * flow of operations connecting input/output objects. Throws if + * the passed boundaries are invalid, e.g. if there's no + * functional dependency (path) between given outputs and inputs. + * + * @param ins Input data vector. + * @param outs Output data vector. + * + * @note Don't construct GProtoInputArgs/GProtoOutputArgs objects + * directly, use cv::GIn()/cv::GOut() wrapper functions instead. + * + * @sa @ref gapi_data_objects + */ + GAPI_WRAP GComputation(GProtoInputArgs &&ins, + GProtoOutputArgs &&outs); // Arg-to-arg overload + + // 2. Syntax sugar and compatibility overloads + /** + * @brief Defines an unary (one input -- one output) computation + * + * @overload + * @param in input GMat of the defined unary computation + * @param out output GMat of the defined unary computation + */ + GAPI_WRAP GComputation(GMat in, GMat out); // Unary overload + + /** + * @brief Defines an unary (one input -- one output) computation + * + * @overload + * @param in input GMat of the defined unary computation + * @param out output GScalar of the defined unary computation + */ + GAPI_WRAP GComputation(GMat in, GScalar out); // Unary overload (scalar) + + /** + * @brief Defines a binary (two inputs -- one output) computation + * + * @overload + * @param in1 first input GMat of the defined binary computation + * @param in2 second input GMat of the defined binary computation + * @param out output GMat of the defined binary computation + */ + GAPI_WRAP GComputation(GMat in1, GMat in2, GMat out); // Binary overload + + /** + * @brief Defines a binary (two inputs -- one output) computation + * + * @overload + * @param in1 first input GMat of the defined binary computation + * @param in2 second input GMat of the defined binary computation + * @param out output GScalar of the defined binary computation + */ + GComputation(GMat in1, GMat in2, GScalar out); // Binary + // overload + // (scalar) + + /** + * @brief Defines a computation with arbitrary input/output number. + * + * @overload + * @param ins vector of inputs GMats for this computation + * @param outs vector of outputs GMats for this computation + * + * Use this overload for cases when number of computation + * inputs/outputs is not known in compile-time -- e.g. when graph + * is programmatically generated to build an image pyramid with + * the given number of levels, etc. + */ + GComputation(const std::vector &ins, // Compatibility overload + const std::vector &outs); + + // Various versions of apply(): //////////////////////////////////////////// + // 1. Generic apply() + /** + * @brief Compile graph on-the-fly and immediately execute it on + * the inputs data vectors. + * + * Number of input/output data objects must match GComputation's + * protocol, also types of host data objects (cv::Mat, cv::Scalar) + * must match the shapes of data objects from protocol (cv::GMat, + * cv::GScalar). If there's a mismatch, a run-time exception will + * be generated. + * + * Internally, a cv::GCompiled object is created for the given + * input format configuration, which then is executed on the input + * data immediately. cv::GComputation caches compiled objects + * produced within apply() -- if this method would be called next + * time with the same input parameters (image formats, image + * resolution, etc), the underlying compiled graph will be reused + * without recompilation. If new metadata doesn't match the cached + * one, the underlying compiled graph is regenerated. + * + * @note compile() always triggers a compilation process and + * produces a new GCompiled object regardless if a similar one has + * been cached via apply() or not. + * + * @param ins vector of input data to process. Don't create + * GRunArgs object manually, use cv::gin() wrapper instead. + * @param outs vector of output data to fill results in. cv::Mat + * objects may be empty in this vector, G-API will automatically + * initialize it with the required format & dimensions. Don't + * create GRunArgsP object manually, use cv::gout() wrapper instead. + * @param args a list of compilation arguments to pass to the + * underlying compilation process. Don't create GCompileArgs + * object manually, use cv::compile_args() wrapper instead. + * + * @sa @ref gapi_data_objects, @ref gapi_compile_args + */ + void apply(GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); // Arg-to-arg overload + + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP GRunArgs apply(const cv::detail::ExtractArgsCallback &callback, + GCompileArgs &&args = {}); + + /// @private -- Exclude this function from OpenCV documentation + void apply(const std::vector& ins, // Compatibility overload + const std::vector& outs, + GCompileArgs &&args = {}); + + // 2. Syntax sugar and compatibility overloads +#if !defined(GAPI_STANDALONE) + /** + * @brief Execute an unary computation (with compilation on the fly) + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Mat for unary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in, cv::Mat &out, GCompileArgs &&args = {}); // Unary overload + + /** + * @brief Execute an unary computation (with compilation on the fly) + * + * @overload + * @param in input cv::Mat for unary computation + * @param out output cv::Scalar for unary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in, cv::Scalar &out, GCompileArgs &&args = {}); // Unary overload (scalar) + + /** + * @brief Execute a binary computation (with compilation on the fly) + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Mat for binary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in1, cv::Mat in2, cv::Mat &out, GCompileArgs &&args = {}); // Binary overload + + /** + * @brief Execute an binary computation (with compilation on the fly) + * + * @overload + * @param in1 first input cv::Mat for binary computation + * @param in2 second input cv::Mat for binary computation + * @param out output cv::Scalar for binary computation + * @param args compilation arguments for underlying compilation + * process. + */ + void apply(cv::Mat in1, cv::Mat in2, cv::Scalar &out, GCompileArgs &&args = {}); // Binary overload (scalar) + + /** + * @brief Execute a computation with arbitrary number of + * inputs/outputs (with compilation on-the-fly). + * + * @overload + * @param ins vector of input cv::Mat objects to process by the + * computation. + * @param outs vector of output cv::Mat objects to produce by the + * computation. + * @param args compilation arguments for underlying compilation + * process. + * + * Numbers of elements in ins/outs vectors must match numbers of + * inputs/outputs which were used to define this GComputation. + */ + void apply(const std::vector& ins, // Compatibility overload + std::vector& outs, + GCompileArgs &&args = {}); +#endif // !defined(GAPI_STANDALONE) + // Various versions of compile(): ////////////////////////////////////////// + // 1. Generic compile() - requires metas to be passed as vector + /** + * @brief Compile the computation for specific input format(s). + * + * This method triggers compilation process and produces a new + * GCompiled object which then can process data of the given + * format. Passing data with different format to the compiled + * computation will generate a run-time exception. + * + * @param in_metas vector of input metadata configuration. Grab + * metadata from real data objects (like cv::Mat or cv::Scalar) + * using cv::descr_of(), or create it on your own. + * @param args compilation arguments for this compilation + * process. Compilation arguments directly affect what kind of + * executable object would be produced, e.g. which kernels (and + * thus, devices) would be used to execute computation. + * + * @return GCompiled, an executable computation compiled + * specifically for the given input parameters. + * + * @sa @ref gapi_compile_args + */ + GCompiled compile(GMetaArgs &&in_metas, GCompileArgs &&args = {}); + + // 2. Syntax sugar - variadic list of metas, no extra compile args + // FIXME: SFINAE looks ugly in the generated documentation + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced. + * + * @return GCompiled, an executable computation compiled + * specifically for the given input parameters. + */ + template + auto compile(const Ts&... metas) -> + typename std::enable_if::value, GCompiled>::type + { + return compile(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); + } + + // 3. Syntax sugar - variadic list of metas, extra compile args + // (seems optional parameters don't work well when there's an variadic template + // comes first) + // + // Ideally it should look like: + // + // template + // GCompiled compile(const Ts&... metas, GCompileArgs &&args) + // + // But not all compilers can handle this (and seems they shouldn't be able to). + // FIXME: SFINAE looks ugly in the generated documentation + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced, + * followed by GCompileArgs object representing compilation + * arguments for this process. + * + * @return GCompiled, an executable computation compiled + * specifically for the given input parameters. + */ + template + auto compile(const Ts&... meta_and_compile_args) -> + typename std::enable_if::value + && std::is_same >::value, + GCompiled>::type + { + //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill + return compile(std::make_tuple(meta_and_compile_args...), + typename detail::MkSeq::type()); + } + + + // FIXME: Document properly in the Doxygen format + // Video-oriented pipeline compilation: + // 1. A generic version + /** + * @brief Compile the computation for streaming mode. + * + * This method triggers compilation process and produces a new + * GStreamingCompiled object which then can process video stream + * data of the given format. Passing a stream in a different + * format to the compiled computation will generate a run-time + * exception. + * + * @param in_metas vector of input metadata configuration. Grab + * metadata from real data objects (like cv::Mat or cv::Scalar) + * using cv::descr_of(), or create it on your own. + * + * @param args compilation arguments for this compilation + * process. Compilation arguments directly affect what kind of + * executable object would be produced, e.g. which kernels (and + * thus, devices) would be used to execute computation. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled specifically for the given input + * parameters. + * + * @sa @ref gapi_compile_args + */ + GAPI_WRAP GStreamingCompiled compileStreaming(GMetaArgs &&in_metas, GCompileArgs &&args = {}); + + /** + * @brief Compile the computation for streaming mode. + * + * This method triggers compilation process and produces a new + * GStreamingCompiled object which then can process video stream + * data in any format. Underlying mechanisms will be adjusted to + * every new input video stream automatically, but please note that + * _not all_ existing backends support this (see reshape()). + * + * @param args compilation arguments for this compilation + * process. Compilation arguments directly affect what kind of + * executable object would be produced, e.g. which kernels (and + * thus, devices) would be used to execute computation. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled for any input image format. + * + * @sa @ref gapi_compile_args + */ + GAPI_WRAP GStreamingCompiled compileStreaming(GCompileArgs &&args = {}); + + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP GStreamingCompiled compileStreaming(const cv::detail::ExtractMetaCallback &callback, + GCompileArgs &&args = {}); + + // 2. Direct metadata version + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled specifically for the given input + * parameters. + */ + template + auto compileStreaming(const Ts&... metas) -> + typename std::enable_if::value, GStreamingCompiled>::type + { + return compileStreaming(GMetaArgs{GMetaArg(metas)...}, GCompileArgs()); + } + + // 2. Direct metadata + compile arguments version + /** + * @overload + * + * Takes a variadic parameter pack with metadata + * descriptors for which a compiled object needs to be produced, + * followed by GCompileArgs object representing compilation + * arguments for this process. + * + * @return GStreamingCompiled, a streaming-oriented executable + * computation compiled specifically for the given input + * parameters. + */ + template + auto compileStreaming(const Ts&... meta_and_compile_args) -> + typename std::enable_if::value + && std::is_same >::value, + GStreamingCompiled>::type + { + //FIXME: wrapping meta_and_compile_args into a tuple to unwrap them inside a helper function is the overkill + return compileStreaming(std::make_tuple(meta_and_compile_args...), + typename detail::MkSeq::type()); + } + + // Internal use only + /// @private + Priv& priv(); + /// @private + const Priv& priv() const; + /// @private + explicit GComputation(cv::gapi::s11n::IIStream &); + /// @private + void serialize(cv::gapi::s11n::IOStream &) const; + +protected: + + // 4. Helper methods for (3) + /// @private + template + GCompiled compile(const std::tuple &meta_and_compile_args, detail::Seq) + { + GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; + GCompileArgs comp_args = std::get(meta_and_compile_args); + return compile(std::move(meta_args), std::move(comp_args)); + } + template + GStreamingCompiled compileStreaming(const std::tuple &meta_and_compile_args, detail::Seq) + { + GMetaArgs meta_args = {GMetaArg(std::get(meta_and_compile_args))...}; + GCompileArgs comp_args = std::get(meta_and_compile_args); + return compileStreaming(std::move(meta_args), std::move(comp_args)); + } + void recompile(GMetaArgs&& in_metas, GCompileArgs &&args); + /// @private + std::shared_ptr m_priv; +}; +/** @} */ + +namespace gapi +{ + // FIXME: all these standalone functions need to be added to some + // common documentation section + /** + * @brief Define an tagged island (subgraph) within a computation. + * + * Declare an Island tagged with `name` and defined from `ins` to `outs` + * (exclusively, as ins/outs are data objects, and regioning is done on + * operations level). + * Throws if any operation between `ins` and `outs` are already assigned + * to another island. + * + * Islands allow to partition graph into subgraphs, fine-tuning + * the way it is scheduled by the underlying executor. + * + * @param name name of the Island to create + * @param ins vector of input data objects where the subgraph + * begins + * @param outs vector of output data objects where the subgraph + * ends. + * + * The way how an island is defined is similar to how + * cv::GComputation is defined on input/output data objects. + * Same rules apply here as well -- if there's no functional + * dependency between inputs and outputs or there's not enough + * input data objects were specified to properly calculate all + * outputs, an exception is thrown. + * + * Use cv::GIn() / cv::GOut() to specify input/output vectors. + */ + void GAPI_EXPORTS island(const std::string &name, + GProtoInputArgs &&ins, + GProtoOutputArgs &&outs); +} // namespace gapi + +} // namespace cv +#endif // OPENCV_GAPI_GCOMPUTATION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp index c55410ebfa..8af603efea 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gcomputation_async.hpp @@ -1,69 +1,69 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP -#define OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP - - -#include //for std::future -#include //for std::exception_ptr -#include //for std::function -#include //for GRunArgs, GRunArgsP -#include //for GCompileArgs -#include - - -namespace cv { - //fwd declaration - class GComputation; -namespace gapi { -namespace wip { - class GAsyncContext; - /** In contrast to async() functions, these do call GComputation::apply() member function of the GComputation passed in. - - @param gcomp Computation (graph) to run asynchronously - @param callback Callback to be called when execution of gcomp is done - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @see async - */ - GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); - /** @overload - @param gcomp Computation (graph) to run asynchronously - @param callback Callback to be called when execution of gcomp is done - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @param ctx Context this request belongs to - @see async_apply async GAsyncContext - */ - GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); - /** @overload - @param gcomp Computation (graph) to run asynchronously - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @return std::future object to wait for completion of async operation - @see async_apply async - */ - GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); - /** @overload - @param gcomp Computation (graph) to run asynchronously - @param ins Input parameters for gcomp - @param outs Output parameters for gcomp - @param args Compile arguments to pass to GComputation::apply() - @param ctx Context this request belongs to - @return std::future object to wait for completion of async operation - @see async_apply async GAsyncContext - */ - GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); -} // namespace wip -} // namespace gapi -} // namespace cv - - -#endif //OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP +#define OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP + + +#include //for std::future +#include //for std::exception_ptr +#include //for std::function +#include //for GRunArgs, GRunArgsP +#include //for GCompileArgs +#include + + +namespace cv { + //fwd declaration + class GComputation; +namespace gapi { +namespace wip { + class GAsyncContext; + /** In contrast to async() functions, these do call GComputation::apply() member function of the GComputation passed in. + + @param gcomp Computation (graph) to run asynchronously + @param callback Callback to be called when execution of gcomp is done + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @see async + */ + GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); + /** @overload + @param gcomp Computation (graph) to run asynchronously + @param callback Callback to be called when execution of gcomp is done + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @param ctx Context this request belongs to + @see async_apply async GAsyncContext + */ + GAPI_EXPORTS void async_apply(GComputation& gcomp, std::function&& callback, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); + /** @overload + @param gcomp Computation (graph) to run asynchronously + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @return std::future object to wait for completion of async operation + @see async_apply async + */ + GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args = {}); + /** @overload + @param gcomp Computation (graph) to run asynchronously + @param ins Input parameters for gcomp + @param outs Output parameters for gcomp + @param args Compile arguments to pass to GComputation::apply() + @param ctx Context this request belongs to + @return std::future object to wait for completion of async operation + @see async_apply async GAsyncContext + */ + GAPI_EXPORTS std::future async_apply(GComputation& gcomp, GRunArgs &&ins, GRunArgsP &&outs, GCompileArgs &&args, GAsyncContext& ctx); +} // namespace wip +} // namespace gapi +} // namespace cv + + +#endif //OPENCV_GAPI_GCOMPUTATION_ASYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp index 7aefbe9e18..54fb30789e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gframe.hpp @@ -1,113 +1,113 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GFRAME_HPP -#define OPENCV_GAPI_GFRAME_HPP - -#include -#include // std::shared_ptr - -#include -#include // GShape - -#include -#include - -// TODO GAPI_EXPORTS or so -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief GFrame class represents an image or media frame in the graph. - * - * GFrame doesn't store any data itself, instead it describes a - * functional relationship between operations consuming and producing - * GFrame objects. - * - * GFrame is introduced to handle various media formats (e.g., NV12 or - * I420) under the same type. Various image formats may differ in the - * number of planes (e.g. two for NV12, three for I420) and the pixel - * layout inside. GFrame type allows to handle these media formats in - * the graph uniformly -- the graph structure will not change if the - * media format changes, e.g. a different camera or decoder is used - * with the same graph. G-API provides a number of operations which - * operate directly on GFrame, like `infer<>()` or - * renderFrame(); these operations are expected to handle different - * media formats inside. There is also a number of accessor - * operations like BGR(), Y(), UV() -- these operations provide - * access to frame's data in the familiar cv::GMat form, which can be - * used with the majority of the existing G-API operations. These - * accessor functions may perform color space conversion on the fly if - * the image format of the GFrame they are applied to differs from the - * operation's semantic (e.g. the BGR() accessor is called on an NV12 - * image frame). - * - * GFrame is a virtual counterpart of cv::MediaFrame. - * - * @sa cv::MediaFrame, cv::GFrameDesc, BGR(), Y(), UV(), infer<>(). - */ -class GAPI_EXPORTS_W_SIMPLE GFrame -{ -public: - /** - * @brief Constructs an empty GFrame - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty GFrame is assigned to a result of some - * operation, it obtains a functional link to this operation (and - * is not empty anymore). - */ - GAPI_WRAP GFrame(); // Empty constructor - - /// @private - GFrame(const GNode &n, std::size_t out); // Operation result constructor - /// @private - GOrigin& priv(); // Internal use only - /// @private - const GOrigin& priv() const; // Internal use only - -private: - std::shared_ptr m_priv; -}; -/** @} */ - -enum class MediaFormat: int -{ - BGR = 0, - NV12, - GRAY, -}; - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS GFrameDesc -{ - MediaFormat fmt; - cv::Size size; - - bool operator== (const GFrameDesc &) const; -}; -static inline GFrameDesc empty_gframe_desc() { return GFrameDesc{}; } -/** @} */ - -class MediaFrame; -GAPI_EXPORTS GFrameDesc descr_of(const MediaFrame &frame); - -GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GFrameDesc &desc); - -} // namespace cv - -#endif // OPENCV_GAPI_GFRAME_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GFRAME_HPP +#define OPENCV_GAPI_GFRAME_HPP + +#include +#include // std::shared_ptr + +#include +#include // GShape + +#include +#include + +// TODO GAPI_EXPORTS or so +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief GFrame class represents an image or media frame in the graph. + * + * GFrame doesn't store any data itself, instead it describes a + * functional relationship between operations consuming and producing + * GFrame objects. + * + * GFrame is introduced to handle various media formats (e.g., NV12 or + * I420) under the same type. Various image formats may differ in the + * number of planes (e.g. two for NV12, three for I420) and the pixel + * layout inside. GFrame type allows to handle these media formats in + * the graph uniformly -- the graph structure will not change if the + * media format changes, e.g. a different camera or decoder is used + * with the same graph. G-API provides a number of operations which + * operate directly on GFrame, like `infer<>()` or + * renderFrame(); these operations are expected to handle different + * media formats inside. There is also a number of accessor + * operations like BGR(), Y(), UV() -- these operations provide + * access to frame's data in the familiar cv::GMat form, which can be + * used with the majority of the existing G-API operations. These + * accessor functions may perform color space conversion on the fly if + * the image format of the GFrame they are applied to differs from the + * operation's semantic (e.g. the BGR() accessor is called on an NV12 + * image frame). + * + * GFrame is a virtual counterpart of cv::MediaFrame. + * + * @sa cv::MediaFrame, cv::GFrameDesc, BGR(), Y(), UV(), infer<>(). + */ +class GAPI_EXPORTS_W_SIMPLE GFrame +{ +public: + /** + * @brief Constructs an empty GFrame + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty GFrame is assigned to a result of some + * operation, it obtains a functional link to this operation (and + * is not empty anymore). + */ + GAPI_WRAP GFrame(); // Empty constructor + + /// @private + GFrame(const GNode &n, std::size_t out); // Operation result constructor + /// @private + GOrigin& priv(); // Internal use only + /// @private + const GOrigin& priv() const; // Internal use only + +private: + std::shared_ptr m_priv; +}; +/** @} */ + +enum class MediaFormat: int +{ + BGR = 0, + NV12, + GRAY, +}; + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS GFrameDesc +{ + MediaFormat fmt; + cv::Size size; + + bool operator== (const GFrameDesc &) const; +}; +static inline GFrameDesc empty_gframe_desc() { return GFrameDesc{}; } +/** @} */ + +class MediaFrame; +GAPI_EXPORTS GFrameDesc descr_of(const MediaFrame &frame); + +GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GFrameDesc &desc); + +} // namespace cv + +#endif // OPENCV_GAPI_GFRAME_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp index 2cfd0fb877..6ec6bf573d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gkernel.hpp @@ -1,757 +1,757 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GKERNEL_HPP -#define OPENCV_GAPI_GKERNEL_HPP - -#include -#include -#include // string -#include // false_type, true_type -#include // map (for GKernelPackage) -#include // tuple - -#include // CompileArgTag -#include // Seq -#include -#include // GArg -#include // GMetaArg -#include // GTypeTraits -#include //suppress_unused_warning -#include - -namespace cv { - -struct GTypeInfo -{ - GShape shape; - cv::detail::OpaqueKind kind; - detail::HostCtor ctor; -}; - -using GShapes = std::vector; -using GKinds = std::vector; -using GCtors = std::vector; -using GTypesInfo = std::vector; - -// GKernel describes kernel API to the system -// FIXME: add attributes of a kernel, (e.g. number and types -// of inputs, etc) -struct GAPI_EXPORTS GKernel -{ - using M = std::function; - - std::string name; // kernel ID, defined by its API (signature) - std::string tag; // some (implementation-specific) tag - M outMeta; // generic adaptor to API::outMeta(...) - GShapes outShapes; // types (shapes) kernel's outputs - GKinds inKinds; // kinds of kernel's inputs (fixme: below) - GCtors outCtors; // captured constructors for template output types - GKinds outKinds; // kinds of kernel's outputs (fixme: below) -}; -// TODO: It's questionable if inKinds should really be here. Instead, -// this information could come from meta. - -// GKernelImpl describes particular kernel implementation to the system -struct GAPI_EXPORTS GKernelImpl -{ - util::any opaque; // backend-specific opaque info - GKernel::M outMeta; // for deserialized graphs, the outMeta is taken here -}; - -template class GKernelTypeM; - -namespace detail -{ - //////////////////////////////////////////////////////////////////////////// - // yield() is used in graph construction time as a generic method to obtain - // lazy "return value" of G-API operations - // - template struct Yield; - template<> struct Yield - { - static inline cv::GMat yield(cv::GCall &call, int i) { return call.yield(i); } - }; - template<> struct Yield - { - static inline cv::GMatP yield(cv::GCall &call, int i) { return call.yieldP(i); } - }; - template<> struct Yield - { - static inline cv::GScalar yield(cv::GCall &call, int i) { return call.yieldScalar(i); } - }; - template struct Yield > - { - static inline cv::GArray yield(cv::GCall &call, int i) { return call.yieldArray(i); } - }; - template struct Yield > - { - static inline cv::GOpaque yield(cv::GCall &call, int i) { return call.yieldOpaque(i); } - }; - template<> struct Yield - { - static inline cv::GFrame yield(cv::GCall &call, int i) { return call.yieldFrame(i); } - }; - - //////////////////////////////////////////////////////////////////////////// - // Helper classes which brings outputMeta() marshalling to kernel - // implementations - // - // 1. MetaType establishes G#Type -> G#Meta mapping between G-API dynamic - // types and its metadata descriptor types. - // This mapping is used to transform types to call outMeta() callback. - template struct MetaType; - template<> struct MetaType { using type = GMatDesc; }; - template<> struct MetaType { using type = GMatDesc; }; - template<> struct MetaType { using type = GFrameDesc; }; - template<> struct MetaType { using type = GScalarDesc; }; - template struct MetaType > { using type = GArrayDesc; }; - template struct MetaType > { using type = GOpaqueDesc; }; - template struct MetaType { using type = T; }; // opaque args passed as-is - // FIXME: Move it to type traits? - - // 2. Hacky test based on MetaType to check if we operate on G-* type or not - template using is_nongapi_type = std::is_same::type>; - - // 3. Two ways to transform input arguments to its meta - for G-* and non-G* types: - template - typename std::enable_if::value, typename MetaType::type> - ::type get_in_meta(const GMetaArgs &in_meta, const GArgs &, int idx) - { - return util::get::type>(in_meta.at(idx)); - } - - template - typename std::enable_if::value, T> - ::type get_in_meta(const GMetaArgs &, const GArgs &in_args, int idx) - { - return in_args.at(idx).template get(); - } - - // 4. The MetaHelper itself: an entity which generates outMeta() call - // based on kernel signature, with arguments properly substituted. - // 4.1 - case for multiple return values - // FIXME: probably can be simplified with std::apply or analogue. - template - struct MetaHelper; - - template - struct MetaHelper, std::tuple > - { - template - static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, - const GArgs &in_args, - detail::Seq, - detail::Seq) - { - // FIXME: decay? - using R = std::tuple::type...>; - const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); - return GMetaArgs{ GMetaArg(std::get(r))... }; - } - // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) - - static GMetaArgs getOutMeta(const GMetaArgs &in_meta, - const GArgs &in_args) - { - return getOutMeta_impl(in_meta, - in_args, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } - }; - - // 4.1 - case for a single return value - // FIXME: How to avoid duplication here? - template - struct MetaHelper, Out > - { - template - static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, - const GArgs &in_args, - detail::Seq) - { - // FIXME: decay? - using R = typename MetaType::type; - const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); - return GMetaArgs{ GMetaArg(r) }; - } - // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) - - static GMetaArgs getOutMeta(const GMetaArgs &in_meta, - const GArgs &in_args) - { - return getOutMeta_impl(in_meta, - in_args, - typename detail::MkSeq::type()); - } - }; - - //////////////////////////////////////////////////////////////////////////// - // Helper class to introduce tags to calls. By default there's no tag - struct NoTag { - static constexpr const char *tag() { return ""; } - }; - -} // namespace detail - -// GKernelType and GKernelTypeM are base classes which implement typed ::on() -// method based on kernel signature. GKernelTypeM stands for multiple-return-value kernels -// -// G_TYPED_KERNEL and G_TYPED_KERNEL_M macros inherit user classes from GKernelType and -// GKernelTypeM respectively. - -template -class GKernelTypeM(Args...)> > - : public detail::MetaHelper, std::tuple> - , public detail::NoTag -{ - template - static std::tuple yield(cv::GCall &call, detail::Seq) - { - return std::make_tuple(detail::Yield::yield(call, IIs)...); - } - -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - // TODO: Args&&... here? - static std::tuple on(Args... args) - { - cv::GCall call(GKernel{ K::id() - , K::tag() - , &K::getOutMeta - , {detail::GTypeTraits::shape...} - , {detail::GTypeTraits::op_kind...} - , {detail::GObtainCtor::get()...} - , {detail::GTypeTraits::op_kind...}}); - call.pass(args...); // TODO: std::forward() here? - return yield(call, typename detail::MkSeq::type()); - } -}; - -template class GKernelType; - -template -class GKernelType > - : public detail::MetaHelper, R> - , public detail::NoTag -{ -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - static R on(Args... args) - { - cv::GCall call(GKernel{ K::id() - , K::tag() - , &K::getOutMeta - , {detail::GTypeTraits::shape} - , {detail::GTypeTraits::op_kind...} - , {detail::GObtainCtor::get()} - , {detail::GTypeTraits::op_kind}}); - call.pass(args...); - return detail::Yield::yield(call, 0); - } -}; - -namespace detail { -// This tiny class eliminates the semantic difference between -// GKernelType and GKernelTypeM. -template class KernelTypeMedium; - -template -class KernelTypeMedium(Args...)>> : - public cv::GKernelTypeM(Args...)>> {}; - -template -class KernelTypeMedium> : - public cv::GKernelType> {}; -} // namespace detail - -} // namespace cv - - -// FIXME: I don't know a better way so far. Feel free to suggest one -// The problem is that every typed kernel should have ::id() but body -// of the class is defined by user (with outMeta, other stuff) - -//! @cond IGNORED -#define G_ID_HELPER_CLASS(Class) Class##IdHelper - -#define G_ID_HELPER_BODY(Class, Id) \ - struct G_ID_HELPER_CLASS(Class) \ - { \ - static constexpr const char * id() {return Id;} \ - }; \ -//! @endcond - -#define GET_G_TYPED_KERNEL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, NAME, ...) NAME -#define COMBINE_SIGNATURE(...) __VA_ARGS__ -// Ensure correct __VA_ARGS__ expansion on Windows -#define __WRAP_VAARGS(x) x - -/** - * Helper for G_TYPED_KERNEL declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) - * for more details. - * - * @param Class type name for this operation. - * @param API an `std::function<>`-like signature for the operation; - * return type is a single value or a tuple of multiple values. - * @param Id string identifier for the operation. Must be unique. - */ -#define G_TYPED_KERNEL_HELPER(Class, API, Id) \ - G_ID_HELPER_BODY(Class, Id) \ - struct Class final: public cv::detail::KernelTypeMedium, \ - public G_ID_HELPER_CLASS(Class) -// {body} is to be defined by user - -#define G_TYPED_KERNEL_HELPER_2(Class, _1, _2, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2), Id) - -#define G_TYPED_KERNEL_HELPER_3(Class, _1, _2, _3, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3), Id) - -#define G_TYPED_KERNEL_HELPER_4(Class, _1, _2, _3, _4, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4), Id) - -#define G_TYPED_KERNEL_HELPER_5(Class, _1, _2, _3, _4, _5, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5), Id) - -#define G_TYPED_KERNEL_HELPER_6(Class, _1, _2, _3, _4, _5, _6, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6), Id) - -#define G_TYPED_KERNEL_HELPER_7(Class, _1, _2, _3, _4, _5, _6, _7, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7), Id) - -#define G_TYPED_KERNEL_HELPER_8(Class, _1, _2, _3, _4, _5, _6, _7, _8, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8), Id) - -#define G_TYPED_KERNEL_HELPER_9(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9), Id) - -#define G_TYPED_KERNEL_HELPER_10(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, Id) \ -G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10), Id) - -/** - * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) - * for more details. - * - * @param Class type name for this operation. - */ -#define G_TYPED_KERNEL(Class, ...) __WRAP_VAARGS(GET_G_TYPED_KERNEL(__VA_ARGS__, \ - G_TYPED_KERNEL_HELPER_10, \ - G_TYPED_KERNEL_HELPER_9, \ - G_TYPED_KERNEL_HELPER_8, \ - G_TYPED_KERNEL_HELPER_7, \ - G_TYPED_KERNEL_HELPER_6, \ - G_TYPED_KERNEL_HELPER_5, \ - G_TYPED_KERNEL_HELPER_4, \ - G_TYPED_KERNEL_HELPER_3, \ - G_TYPED_KERNEL_HELPER_2, \ - G_TYPED_KERNEL_HELPER)(Class, __VA_ARGS__)) \ - -/** - * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) for more details. - * - * @deprecated This macro is deprecated in favor of `G_TYPED_KERNEL` that is used for declaring any - * G-API Operation. - * - * @param Class type name for this operation. - */ -#define G_TYPED_KERNEL_M G_TYPED_KERNEL - -#define G_API_OP G_TYPED_KERNEL -#define G_API_OP_M G_API_OP - -namespace cv -{ -namespace gapi -{ - // Prework: model "Device" API before it gets to G-API headers. - // FIXME: Don't mix with internal Backends class! - /// @private - class GAPI_EXPORTS GBackend - { - public: - class Priv; - - // TODO: make it template (call `new` within??) - GBackend(); - explicit GBackend(std::shared_ptr &&p); - - Priv& priv(); - const Priv& priv() const; - std::size_t hash() const; - - bool operator== (const GBackend &rhs) const; - - private: - std::shared_ptr m_priv; - }; - - inline bool operator != (const GBackend &lhs, const GBackend &rhs) - { - return !(lhs == rhs); - } -} // namespace gapi -} // namespace cv - -namespace std -{ - template<> struct hash - { - std::size_t operator() (const cv::gapi::GBackend &b) const - { - return b.hash(); - } - }; -} // namespace std - -namespace cv { - class GAPI_EXPORTS_W_SIMPLE GKernelPackage; - -namespace gapi { - GAPI_EXPORTS_W cv::GKernelPackage combine(const cv::GKernelPackage &lhs, - const cv::GKernelPackage &rhs); - - /// @private - class GFunctor - { - public: - virtual cv::GKernelImpl impl() const = 0; - virtual cv::gapi::GBackend backend() const = 0; - const char* id() const { return m_id; } - - virtual ~GFunctor() = default; - protected: - GFunctor(const char* id) : m_id(id) { } - private: - const char* m_id; - }; -} // namespace gapi - - /** \addtogroup gapi_compile_args - * @{ - */ - - // FIXME: Hide implementation - /** - * @brief A container class for heterogeneous kernel - * implementation collections and graph transformations. - * - * GKernelPackage is a special container class which stores kernel - * _implementations_ and graph _transformations_. Objects of this class - * are created and passed to cv::GComputation::compile() to specify - * which kernels to use and which transformations to apply in the - * compiled graph. GKernelPackage may contain kernels of - * different backends, e.g. be heterogeneous. - * - * The most easy way to create a kernel package is to use function - * cv::gapi::kernels(). This template functions takes kernel - * implementations in form of type list (variadic template) and - * generates a kernel package atop of that. - * - * Kernel packages can be also generated programmatically, starting - * with an empty package (created with the default constructor) - * and then by populating it with kernels via call to - * GKernelPackage::include(). Note this method is also a template - * one since G-API kernel and transformation implementations are _types_, - * not objects. - * - * Finally, two kernel packages can be combined into a new one - * with function cv::gapi::combine(). - */ - class GAPI_EXPORTS_W_SIMPLE GKernelPackage - { - - /// @private - using M = std::unordered_map>; - - /// @private - M m_id_kernels; - - /// @private - std::vector m_transformations; - - protected: - /// @private - // Remove ALL implementations of the given API (identified by ID) - void removeAPI(const std::string &id); - - /// @private - // Partial include() specialization for kernels - template - typename std::enable_if<(std::is_base_of::value), void>::type - includeHelper() - { - auto backend = KImpl::backend(); - auto kernel_id = KImpl::API::id(); - auto kernel_impl = GKernelImpl{KImpl::kernel(), &KImpl::API::getOutMeta}; - removeAPI(kernel_id); - - m_id_kernels[kernel_id] = std::make_pair(backend, kernel_impl); - } - - /// @private - // Partial include() specialization for transformations - template - typename std::enable_if<(std::is_base_of::value), void>::type - includeHelper() - { - m_transformations.emplace_back(TImpl::transformation()); - } - - public: - void include(const cv::gapi::GFunctor& functor); - - /** - * @brief Returns total number of kernels - * in the package (across all backends included) - * - * @return a number of kernels in the package - */ - GAPI_WRAP std::size_t size() const; - - /** - * @brief Returns vector of transformations included in the package - * - * @return vector of transformations included in the package - */ - const std::vector& get_transformations() const; - - /** - * @brief Returns vector of kernel ids included in the package - * - * @return vector of kernel ids included in the package - */ - std::vector get_kernel_ids() const; - - /** - * @brief Test if a particular kernel _implementation_ KImpl is - * included in this kernel package. - * - * @sa includesAPI() - * - * @note cannot be applied to transformations - * - * @return true if there is such kernel, false otherwise. - */ - template - bool includes() const - { - static_assert(std::is_base_of::value, - "includes() can be applied to kernels only"); - - auto kernel_it = m_id_kernels.find(KImpl::API::id()); - return kernel_it != m_id_kernels.end() && - kernel_it->second.first == KImpl::backend(); - } - - /** - * @brief Remove all kernels associated with the given backend - * from the package. - * - * Does nothing if there's no kernels of this backend in the package. - * - * @param backend backend which kernels to remove - */ - void remove(const cv::gapi::GBackend& backend); - - /** - * @brief Remove all kernels implementing the given API from - * the package. - * - * Does nothing if there's no kernels implementing the given interface. - */ - template - void remove() - { - removeAPI(KAPI::id()); - } - - // FIXME: Rename to includes() and distinguish API/impl case by - // statically? - /** - * Check if package contains ANY implementation of a kernel API - * by API type. - */ - template - bool includesAPI() const - { - return includesAPI(KAPI::id()); - } - - /// @private - bool includesAPI(const std::string &id) const; - - // FIXME: The below comment is wrong, and who needs this function? - /** - * @brief Find a kernel (by its API) - * - * Returns implementation corresponding id. - * Throws if nothing found. - * - * @return Backend which hosts matching kernel implementation. - * - */ - template - cv::gapi::GBackend lookup() const - { - return lookup(KAPI::id()).first; - } - - /// @private - std::pair - lookup(const std::string &id) const; - - // FIXME: No overwrites allowed? - /** - * @brief Put a new kernel implementation or a new transformation - * KImpl into the package. - */ - template - void include() - { - includeHelper(); - } - - /** - * @brief Adds a new kernel based on it's backend and id into the kernel package - * - * @param backend backend associated with the kernel - * @param kernel_id a name/id of the kernel - */ - void include(const cv::gapi::GBackend& backend, const std::string& kernel_id); - - /** - * @brief Lists all backends which are included into package - * - * @return vector of backends - */ - std::vector backends() const; - - // TODO: Doxygen bug -- it wants me to place this comment - // here, not below. - /** - * @brief Create a new package based on `lhs` and `rhs`. - * - * @param lhs "Left-hand-side" package in the process - * @param rhs "Right-hand-side" package in the process - * @return a new kernel package. - */ - friend GAPI_EXPORTS GKernelPackage cv::gapi::combine(const GKernelPackage &lhs, - const GKernelPackage &rhs); - }; - /** @} */ - -namespace gapi { - using GKernelPackage = cv::GKernelPackage; // Keep backward compatibility - - /** \addtogroup gapi_compile_args - * @{ - */ - - /** - * @brief Create a kernel package object containing kernels - * and transformations specified in variadic template argument. - * - * In G-API, kernel implementations and transformations are _types_. - * Every backend has its own kernel API (like GAPI_OCV_KERNEL() and - * GAPI_FLUID_KERNEL()) but all of that APIs define a new type for - * each kernel implementation. - * - * Use this function to pass kernel implementations (defined in - * either way) and transformations to the system. Example: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp kernels_snippet - * - * Note that kernels() itself is a function returning object, not - * a type, so having `()` at the end is important -- it must be a - * function call. - */ - template GKernelPackage kernels() - { - // FIXME: currently there is no check that transformations' signatures are unique - // and won't be any intersection in graph compilation stage - static_assert(cv::detail::all_unique::value, "Kernels API must be unique"); - - GKernelPackage pkg; - - // For those who wonder - below is a trick to call a number of - // methods based on parameter pack (zeroes just help hiding these - // calls into a sequence which helps to expand this parameter pack). - // Just note that `f(),a` always equals to `a` (with f() called!) - // and parentheses are used to hide function call in the expanded sequence. - // Leading 0 helps to handle case when KK is an empty list (kernels<>()). - int unused[] = { 0, (pkg.include(), 0)... }; - cv::util::suppress_unused_warning(unused); - return pkg; - } - - template - GKernelPackage kernels(FF&... functors) - { - GKernelPackage pkg; - int unused[] = { 0, (pkg.include(functors), 0)... }; - cv::util::suppress_unused_warning(unused); - return pkg; - } - - /** @} */ - - /** - * @brief Combines multiple G-API kernel packages into one - * - * @overload - * - * This function successively combines the passed kernel packages using a right fold. - * Calling `combine(a, b, c)` is equal to `combine(a, combine(b, c))`. - * - * @return The resulting kernel package - */ - template - cv::GKernelPackage combine(const cv::GKernelPackage &a, const cv::GKernelPackage &b, Ps&&... rest) - { - return combine(a, combine(b, rest...)); - } - // NB(DM): Variadic-arg version in Python may require the same - // approach as used in GComputation::compile/apply. - - /** \addtogroup gapi_compile_args - * @{ - */ - /** - * @brief cv::gapi::use_only() is a special combinator which hints G-API to use only - * kernels specified in cv::GComputation::compile() (and not to extend kernels available by - * default with that package). - */ - struct GAPI_EXPORTS use_only - { - GKernelPackage pkg; - }; - /** @} */ - -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.kernel_package"; } - }; - - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.use_only"; } - }; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_GKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GKERNEL_HPP +#define OPENCV_GAPI_GKERNEL_HPP + +#include +#include +#include // string +#include // false_type, true_type +#include // map (for GKernelPackage) +#include // tuple + +#include // CompileArgTag +#include // Seq +#include +#include // GArg +#include // GMetaArg +#include // GTypeTraits +#include //suppress_unused_warning +#include + +namespace cv { + +struct GTypeInfo +{ + GShape shape; + cv::detail::OpaqueKind kind; + detail::HostCtor ctor; +}; + +using GShapes = std::vector; +using GKinds = std::vector; +using GCtors = std::vector; +using GTypesInfo = std::vector; + +// GKernel describes kernel API to the system +// FIXME: add attributes of a kernel, (e.g. number and types +// of inputs, etc) +struct GAPI_EXPORTS GKernel +{ + using M = std::function; + + std::string name; // kernel ID, defined by its API (signature) + std::string tag; // some (implementation-specific) tag + M outMeta; // generic adaptor to API::outMeta(...) + GShapes outShapes; // types (shapes) kernel's outputs + GKinds inKinds; // kinds of kernel's inputs (fixme: below) + GCtors outCtors; // captured constructors for template output types + GKinds outKinds; // kinds of kernel's outputs (fixme: below) +}; +// TODO: It's questionable if inKinds should really be here. Instead, +// this information could come from meta. + +// GKernelImpl describes particular kernel implementation to the system +struct GAPI_EXPORTS GKernelImpl +{ + util::any opaque; // backend-specific opaque info + GKernel::M outMeta; // for deserialized graphs, the outMeta is taken here +}; + +template class GKernelTypeM; + +namespace detail +{ + //////////////////////////////////////////////////////////////////////////// + // yield() is used in graph construction time as a generic method to obtain + // lazy "return value" of G-API operations + // + template struct Yield; + template<> struct Yield + { + static inline cv::GMat yield(cv::GCall &call, int i) { return call.yield(i); } + }; + template<> struct Yield + { + static inline cv::GMatP yield(cv::GCall &call, int i) { return call.yieldP(i); } + }; + template<> struct Yield + { + static inline cv::GScalar yield(cv::GCall &call, int i) { return call.yieldScalar(i); } + }; + template struct Yield > + { + static inline cv::GArray yield(cv::GCall &call, int i) { return call.yieldArray(i); } + }; + template struct Yield > + { + static inline cv::GOpaque yield(cv::GCall &call, int i) { return call.yieldOpaque(i); } + }; + template<> struct Yield + { + static inline cv::GFrame yield(cv::GCall &call, int i) { return call.yieldFrame(i); } + }; + + //////////////////////////////////////////////////////////////////////////// + // Helper classes which brings outputMeta() marshalling to kernel + // implementations + // + // 1. MetaType establishes G#Type -> G#Meta mapping between G-API dynamic + // types and its metadata descriptor types. + // This mapping is used to transform types to call outMeta() callback. + template struct MetaType; + template<> struct MetaType { using type = GMatDesc; }; + template<> struct MetaType { using type = GMatDesc; }; + template<> struct MetaType { using type = GFrameDesc; }; + template<> struct MetaType { using type = GScalarDesc; }; + template struct MetaType > { using type = GArrayDesc; }; + template struct MetaType > { using type = GOpaqueDesc; }; + template struct MetaType { using type = T; }; // opaque args passed as-is + // FIXME: Move it to type traits? + + // 2. Hacky test based on MetaType to check if we operate on G-* type or not + template using is_nongapi_type = std::is_same::type>; + + // 3. Two ways to transform input arguments to its meta - for G-* and non-G* types: + template + typename std::enable_if::value, typename MetaType::type> + ::type get_in_meta(const GMetaArgs &in_meta, const GArgs &, int idx) + { + return util::get::type>(in_meta.at(idx)); + } + + template + typename std::enable_if::value, T> + ::type get_in_meta(const GMetaArgs &, const GArgs &in_args, int idx) + { + return in_args.at(idx).template get(); + } + + // 4. The MetaHelper itself: an entity which generates outMeta() call + // based on kernel signature, with arguments properly substituted. + // 4.1 - case for multiple return values + // FIXME: probably can be simplified with std::apply or analogue. + template + struct MetaHelper; + + template + struct MetaHelper, std::tuple > + { + template + static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, + const GArgs &in_args, + detail::Seq, + detail::Seq) + { + // FIXME: decay? + using R = std::tuple::type...>; + const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); + return GMetaArgs{ GMetaArg(std::get(r))... }; + } + // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) + + static GMetaArgs getOutMeta(const GMetaArgs &in_meta, + const GArgs &in_args) + { + return getOutMeta_impl(in_meta, + in_args, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } + }; + + // 4.1 - case for a single return value + // FIXME: How to avoid duplication here? + template + struct MetaHelper, Out > + { + template + static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta, + const GArgs &in_args, + detail::Seq) + { + // FIXME: decay? + using R = typename MetaType::type; + const R r = K::outMeta( get_in_meta(in_meta, in_args, IIs)... ); + return GMetaArgs{ GMetaArg(r) }; + } + // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?) + + static GMetaArgs getOutMeta(const GMetaArgs &in_meta, + const GArgs &in_args) + { + return getOutMeta_impl(in_meta, + in_args, + typename detail::MkSeq::type()); + } + }; + + //////////////////////////////////////////////////////////////////////////// + // Helper class to introduce tags to calls. By default there's no tag + struct NoTag { + static constexpr const char *tag() { return ""; } + }; + +} // namespace detail + +// GKernelType and GKernelTypeM are base classes which implement typed ::on() +// method based on kernel signature. GKernelTypeM stands for multiple-return-value kernels +// +// G_TYPED_KERNEL and G_TYPED_KERNEL_M macros inherit user classes from GKernelType and +// GKernelTypeM respectively. + +template +class GKernelTypeM(Args...)> > + : public detail::MetaHelper, std::tuple> + , public detail::NoTag +{ + template + static std::tuple yield(cv::GCall &call, detail::Seq) + { + return std::make_tuple(detail::Yield::yield(call, IIs)...); + } + +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + // TODO: Args&&... here? + static std::tuple on(Args... args) + { + cv::GCall call(GKernel{ K::id() + , K::tag() + , &K::getOutMeta + , {detail::GTypeTraits::shape...} + , {detail::GTypeTraits::op_kind...} + , {detail::GObtainCtor::get()...} + , {detail::GTypeTraits::op_kind...}}); + call.pass(args...); // TODO: std::forward() here? + return yield(call, typename detail::MkSeq::type()); + } +}; + +template class GKernelType; + +template +class GKernelType > + : public detail::MetaHelper, R> + , public detail::NoTag +{ +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + static R on(Args... args) + { + cv::GCall call(GKernel{ K::id() + , K::tag() + , &K::getOutMeta + , {detail::GTypeTraits::shape} + , {detail::GTypeTraits::op_kind...} + , {detail::GObtainCtor::get()} + , {detail::GTypeTraits::op_kind}}); + call.pass(args...); + return detail::Yield::yield(call, 0); + } +}; + +namespace detail { +// This tiny class eliminates the semantic difference between +// GKernelType and GKernelTypeM. +template class KernelTypeMedium; + +template +class KernelTypeMedium(Args...)>> : + public cv::GKernelTypeM(Args...)>> {}; + +template +class KernelTypeMedium> : + public cv::GKernelType> {}; +} // namespace detail + +} // namespace cv + + +// FIXME: I don't know a better way so far. Feel free to suggest one +// The problem is that every typed kernel should have ::id() but body +// of the class is defined by user (with outMeta, other stuff) + +//! @cond IGNORED +#define G_ID_HELPER_CLASS(Class) Class##IdHelper + +#define G_ID_HELPER_BODY(Class, Id) \ + struct G_ID_HELPER_CLASS(Class) \ + { \ + static constexpr const char * id() {return Id;} \ + }; \ +//! @endcond + +#define GET_G_TYPED_KERNEL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, NAME, ...) NAME +#define COMBINE_SIGNATURE(...) __VA_ARGS__ +// Ensure correct __VA_ARGS__ expansion on Windows +#define __WRAP_VAARGS(x) x + +/** + * Helper for G_TYPED_KERNEL declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) + * for more details. + * + * @param Class type name for this operation. + * @param API an `std::function<>`-like signature for the operation; + * return type is a single value or a tuple of multiple values. + * @param Id string identifier for the operation. Must be unique. + */ +#define G_TYPED_KERNEL_HELPER(Class, API, Id) \ + G_ID_HELPER_BODY(Class, Id) \ + struct Class final: public cv::detail::KernelTypeMedium, \ + public G_ID_HELPER_CLASS(Class) +// {body} is to be defined by user + +#define G_TYPED_KERNEL_HELPER_2(Class, _1, _2, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2), Id) + +#define G_TYPED_KERNEL_HELPER_3(Class, _1, _2, _3, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3), Id) + +#define G_TYPED_KERNEL_HELPER_4(Class, _1, _2, _3, _4, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4), Id) + +#define G_TYPED_KERNEL_HELPER_5(Class, _1, _2, _3, _4, _5, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5), Id) + +#define G_TYPED_KERNEL_HELPER_6(Class, _1, _2, _3, _4, _5, _6, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6), Id) + +#define G_TYPED_KERNEL_HELPER_7(Class, _1, _2, _3, _4, _5, _6, _7, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7), Id) + +#define G_TYPED_KERNEL_HELPER_8(Class, _1, _2, _3, _4, _5, _6, _7, _8, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8), Id) + +#define G_TYPED_KERNEL_HELPER_9(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9), Id) + +#define G_TYPED_KERNEL_HELPER_10(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, Id) \ +G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10), Id) + +/** + * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) + * for more details. + * + * @param Class type name for this operation. + */ +#define G_TYPED_KERNEL(Class, ...) __WRAP_VAARGS(GET_G_TYPED_KERNEL(__VA_ARGS__, \ + G_TYPED_KERNEL_HELPER_10, \ + G_TYPED_KERNEL_HELPER_9, \ + G_TYPED_KERNEL_HELPER_8, \ + G_TYPED_KERNEL_HELPER_7, \ + G_TYPED_KERNEL_HELPER_6, \ + G_TYPED_KERNEL_HELPER_5, \ + G_TYPED_KERNEL_HELPER_4, \ + G_TYPED_KERNEL_HELPER_3, \ + G_TYPED_KERNEL_HELPER_2, \ + G_TYPED_KERNEL_HELPER)(Class, __VA_ARGS__)) \ + +/** + * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) for more details. + * + * @deprecated This macro is deprecated in favor of `G_TYPED_KERNEL` that is used for declaring any + * G-API Operation. + * + * @param Class type name for this operation. + */ +#define G_TYPED_KERNEL_M G_TYPED_KERNEL + +#define G_API_OP G_TYPED_KERNEL +#define G_API_OP_M G_API_OP + +namespace cv +{ +namespace gapi +{ + // Prework: model "Device" API before it gets to G-API headers. + // FIXME: Don't mix with internal Backends class! + /// @private + class GAPI_EXPORTS GBackend + { + public: + class Priv; + + // TODO: make it template (call `new` within??) + GBackend(); + explicit GBackend(std::shared_ptr &&p); + + Priv& priv(); + const Priv& priv() const; + std::size_t hash() const; + + bool operator== (const GBackend &rhs) const; + + private: + std::shared_ptr m_priv; + }; + + inline bool operator != (const GBackend &lhs, const GBackend &rhs) + { + return !(lhs == rhs); + } +} // namespace gapi +} // namespace cv + +namespace std +{ + template<> struct hash + { + std::size_t operator() (const cv::gapi::GBackend &b) const + { + return b.hash(); + } + }; +} // namespace std + +namespace cv { + class GAPI_EXPORTS_W_SIMPLE GKernelPackage; + +namespace gapi { + GAPI_EXPORTS_W cv::GKernelPackage combine(const cv::GKernelPackage &lhs, + const cv::GKernelPackage &rhs); + + /// @private + class GFunctor + { + public: + virtual cv::GKernelImpl impl() const = 0; + virtual cv::gapi::GBackend backend() const = 0; + const char* id() const { return m_id; } + + virtual ~GFunctor() = default; + protected: + GFunctor(const char* id) : m_id(id) { } + private: + const char* m_id; + }; +} // namespace gapi + + /** \addtogroup gapi_compile_args + * @{ + */ + + // FIXME: Hide implementation + /** + * @brief A container class for heterogeneous kernel + * implementation collections and graph transformations. + * + * GKernelPackage is a special container class which stores kernel + * _implementations_ and graph _transformations_. Objects of this class + * are created and passed to cv::GComputation::compile() to specify + * which kernels to use and which transformations to apply in the + * compiled graph. GKernelPackage may contain kernels of + * different backends, e.g. be heterogeneous. + * + * The most easy way to create a kernel package is to use function + * cv::gapi::kernels(). This template functions takes kernel + * implementations in form of type list (variadic template) and + * generates a kernel package atop of that. + * + * Kernel packages can be also generated programmatically, starting + * with an empty package (created with the default constructor) + * and then by populating it with kernels via call to + * GKernelPackage::include(). Note this method is also a template + * one since G-API kernel and transformation implementations are _types_, + * not objects. + * + * Finally, two kernel packages can be combined into a new one + * with function cv::gapi::combine(). + */ + class GAPI_EXPORTS_W_SIMPLE GKernelPackage + { + + /// @private + using M = std::unordered_map>; + + /// @private + M m_id_kernels; + + /// @private + std::vector m_transformations; + + protected: + /// @private + // Remove ALL implementations of the given API (identified by ID) + void removeAPI(const std::string &id); + + /// @private + // Partial include() specialization for kernels + template + typename std::enable_if<(std::is_base_of::value), void>::type + includeHelper() + { + auto backend = KImpl::backend(); + auto kernel_id = KImpl::API::id(); + auto kernel_impl = GKernelImpl{KImpl::kernel(), &KImpl::API::getOutMeta}; + removeAPI(kernel_id); + + m_id_kernels[kernel_id] = std::make_pair(backend, kernel_impl); + } + + /// @private + // Partial include() specialization for transformations + template + typename std::enable_if<(std::is_base_of::value), void>::type + includeHelper() + { + m_transformations.emplace_back(TImpl::transformation()); + } + + public: + void include(const cv::gapi::GFunctor& functor); + + /** + * @brief Returns total number of kernels + * in the package (across all backends included) + * + * @return a number of kernels in the package + */ + GAPI_WRAP std::size_t size() const; + + /** + * @brief Returns vector of transformations included in the package + * + * @return vector of transformations included in the package + */ + const std::vector& get_transformations() const; + + /** + * @brief Returns vector of kernel ids included in the package + * + * @return vector of kernel ids included in the package + */ + std::vector get_kernel_ids() const; + + /** + * @brief Test if a particular kernel _implementation_ KImpl is + * included in this kernel package. + * + * @sa includesAPI() + * + * @note cannot be applied to transformations + * + * @return true if there is such kernel, false otherwise. + */ + template + bool includes() const + { + static_assert(std::is_base_of::value, + "includes() can be applied to kernels only"); + + auto kernel_it = m_id_kernels.find(KImpl::API::id()); + return kernel_it != m_id_kernels.end() && + kernel_it->second.first == KImpl::backend(); + } + + /** + * @brief Remove all kernels associated with the given backend + * from the package. + * + * Does nothing if there's no kernels of this backend in the package. + * + * @param backend backend which kernels to remove + */ + void remove(const cv::gapi::GBackend& backend); + + /** + * @brief Remove all kernels implementing the given API from + * the package. + * + * Does nothing if there's no kernels implementing the given interface. + */ + template + void remove() + { + removeAPI(KAPI::id()); + } + + // FIXME: Rename to includes() and distinguish API/impl case by + // statically? + /** + * Check if package contains ANY implementation of a kernel API + * by API type. + */ + template + bool includesAPI() const + { + return includesAPI(KAPI::id()); + } + + /// @private + bool includesAPI(const std::string &id) const; + + // FIXME: The below comment is wrong, and who needs this function? + /** + * @brief Find a kernel (by its API) + * + * Returns implementation corresponding id. + * Throws if nothing found. + * + * @return Backend which hosts matching kernel implementation. + * + */ + template + cv::gapi::GBackend lookup() const + { + return lookup(KAPI::id()).first; + } + + /// @private + std::pair + lookup(const std::string &id) const; + + // FIXME: No overwrites allowed? + /** + * @brief Put a new kernel implementation or a new transformation + * KImpl into the package. + */ + template + void include() + { + includeHelper(); + } + + /** + * @brief Adds a new kernel based on it's backend and id into the kernel package + * + * @param backend backend associated with the kernel + * @param kernel_id a name/id of the kernel + */ + void include(const cv::gapi::GBackend& backend, const std::string& kernel_id); + + /** + * @brief Lists all backends which are included into package + * + * @return vector of backends + */ + std::vector backends() const; + + // TODO: Doxygen bug -- it wants me to place this comment + // here, not below. + /** + * @brief Create a new package based on `lhs` and `rhs`. + * + * @param lhs "Left-hand-side" package in the process + * @param rhs "Right-hand-side" package in the process + * @return a new kernel package. + */ + friend GAPI_EXPORTS GKernelPackage cv::gapi::combine(const GKernelPackage &lhs, + const GKernelPackage &rhs); + }; + /** @} */ + +namespace gapi { + using GKernelPackage = cv::GKernelPackage; // Keep backward compatibility + + /** \addtogroup gapi_compile_args + * @{ + */ + + /** + * @brief Create a kernel package object containing kernels + * and transformations specified in variadic template argument. + * + * In G-API, kernel implementations and transformations are _types_. + * Every backend has its own kernel API (like GAPI_OCV_KERNEL() and + * GAPI_FLUID_KERNEL()) but all of that APIs define a new type for + * each kernel implementation. + * + * Use this function to pass kernel implementations (defined in + * either way) and transformations to the system. Example: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp kernels_snippet + * + * Note that kernels() itself is a function returning object, not + * a type, so having `()` at the end is important -- it must be a + * function call. + */ + template GKernelPackage kernels() + { + // FIXME: currently there is no check that transformations' signatures are unique + // and won't be any intersection in graph compilation stage + static_assert(cv::detail::all_unique::value, "Kernels API must be unique"); + + GKernelPackage pkg; + + // For those who wonder - below is a trick to call a number of + // methods based on parameter pack (zeroes just help hiding these + // calls into a sequence which helps to expand this parameter pack). + // Just note that `f(),a` always equals to `a` (with f() called!) + // and parentheses are used to hide function call in the expanded sequence. + // Leading 0 helps to handle case when KK is an empty list (kernels<>()). + int unused[] = { 0, (pkg.include(), 0)... }; + cv::util::suppress_unused_warning(unused); + return pkg; + } + + template + GKernelPackage kernels(FF&... functors) + { + GKernelPackage pkg; + int unused[] = { 0, (pkg.include(functors), 0)... }; + cv::util::suppress_unused_warning(unused); + return pkg; + } + + /** @} */ + + /** + * @brief Combines multiple G-API kernel packages into one + * + * @overload + * + * This function successively combines the passed kernel packages using a right fold. + * Calling `combine(a, b, c)` is equal to `combine(a, combine(b, c))`. + * + * @return The resulting kernel package + */ + template + cv::GKernelPackage combine(const cv::GKernelPackage &a, const cv::GKernelPackage &b, Ps&&... rest) + { + return combine(a, combine(b, rest...)); + } + // NB(DM): Variadic-arg version in Python may require the same + // approach as used in GComputation::compile/apply. + + /** \addtogroup gapi_compile_args + * @{ + */ + /** + * @brief cv::gapi::use_only() is a special combinator which hints G-API to use only + * kernels specified in cv::GComputation::compile() (and not to extend kernels available by + * default with that package). + */ + struct GAPI_EXPORTS use_only + { + GKernelPackage pkg; + }; + /** @} */ + +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.kernel_package"; } + }; + + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.use_only"; } + }; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_GKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp index 27ac65e78f..6d6f74ff7f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gmat.hpp @@ -1,292 +1,292 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GMAT_HPP -#define OPENCV_GAPI_GMAT_HPP - -#include -#include // std::shared_ptr - -#include -#include // GShape - -#include - -// TODO GAPI_EXPORTS or so -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; - -/** \addtogroup gapi_data_objects - * @{ - * - * @brief G-API data objects used to build G-API expressions. - * - * These objects do not own any particular data (except compile-time - * associated values like with cv::GScalar or `cv::GArray`) and are - * used only to construct graphs. - * - * Every graph in G-API starts and ends with data objects. - * - * Once constructed and compiled, G-API operates with regular host-side - * data instead. Refer to the below table to find the mapping between - * G-API and regular data types when passing input and output data - * structures to G-API: - * - * G-API data type | I/O data type - * ------------------ | ------------- - * cv::GMat | cv::Mat, cv::UMat, cv::RMat - * cv::GScalar | cv::Scalar - * `cv::GArray` | std::vector - * `cv::GOpaque` | T - * cv::GFrame | cv::MediaFrame - */ - -/** - * @brief GMat class represents image or tensor data in the - * graph. - * - * GMat doesn't store any data itself, instead it describes a - * functional relationship between operations consuming and producing - * GMat objects. - * - * GMat is a virtual counterpart of Mat and UMat, but it - * doesn't mean G-API use Mat or UMat objects internally to represent - * GMat objects -- the internal data representation may be - * backend-specific or optimized out at all. - * - * @sa Mat, GMatDesc - */ -class GAPI_EXPORTS_W_SIMPLE GMat -{ -public: - /** - * @brief Constructs an empty GMat - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty GMat is assigned to a result of some - * operation, it obtains a functional link to this operation (and - * is not empty anymore). - */ - GAPI_WRAP GMat(); // Empty constructor - - /** - * @brief Constructs a value-initialized GMat - * - * GMat may be associated with a buffer at graph construction time. - * It is useful when some operation has a Mat input which doesn't - * change during the program execution, and is set only once. - * In this case, there's no need to declare such GMat as graph input. - * - * @param m a cv::Mat buffer to associate with this GMat object. - */ - GAPI_WRAP explicit GMat(cv::Mat m); // Value-initialization constructor - - /// @private - GMat(const GNode &n, std::size_t out); // Operation result constructor - /// @private - GOrigin& priv(); // Internal use only - /// @private - const GOrigin& priv() const; // Internal use only - -private: - std::shared_ptr m_priv; -}; - -class GAPI_EXPORTS GMatP : public GMat -{ -public: - using GMat::GMat; -}; - -class RMat; - -/** @} */ - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GMatDesc -{ - // FIXME: Default initializers in C++14 - GAPI_PROP int depth; - GAPI_PROP int chan; - GAPI_PROP cv::Size size; // NB.: no multi-dimensional cases covered yet - GAPI_PROP bool planar; - GAPI_PROP std::vector dims; // FIXME: Maybe it's real questionable to have it here - - GAPI_WRAP GMatDesc(int d, int c, cv::Size s, bool p = false) - : depth(d), chan(c), size(s), planar(p) {} - - GAPI_WRAP GMatDesc(int d, const std::vector &dd) - : depth(d), chan(-1), size{-1,-1}, planar(false), dims(dd) {} - - GAPI_WRAP GMatDesc(int d, std::vector &&dd) - : depth(d), chan(-1), size{-1,-1}, planar(false), dims(std::move(dd)) {} - - GAPI_WRAP GMatDesc() : GMatDesc(-1, -1, {-1,-1}) {} - - inline bool operator== (const GMatDesc &rhs) const - { - return depth == rhs.depth - && chan == rhs.chan - && size == rhs.size - && planar == rhs.planar - && dims == rhs.dims; - } - - inline bool operator!= (const GMatDesc &rhs) const - { - return !(*this == rhs); - } - - bool isND() const { return !dims.empty(); } - - // Checks if the passed mat can be described by this descriptor - // (it handles the case when - // 1-channel mat can be reinterpreted as is (1-channel mat) - // and as a 3-channel planar mat with height divided by 3) - bool canDescribe(const cv::Mat& mat) const; - - bool canDescribe(const cv::RMat& mat) const; - - // Meta combinator: return a new GMatDesc which differs in size by delta - // (all other fields are taken unchanged from this GMatDesc) - // FIXME: a better name? - GAPI_WRAP GMatDesc withSizeDelta(cv::Size delta) const - { - GMatDesc desc(*this); - desc.size += delta; - return desc; - } - // Meta combinator: return a new GMatDesc which differs in size by delta - // (all other fields are taken unchanged from this GMatDesc) - // - // This is an overload. - GAPI_WRAP GMatDesc withSizeDelta(int dx, int dy) const - { - return withSizeDelta(cv::Size{dx,dy}); - } - - GAPI_WRAP GMatDesc withSize(cv::Size sz) const - { - GMatDesc desc(*this); - desc.size = sz; - return desc; - } - - // Meta combinator: return a new GMatDesc with specified data depth. - // (all other fields are taken unchanged from this GMatDesc) - GAPI_WRAP GMatDesc withDepth(int ddepth) const - { - GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); - GMatDesc desc(*this); - if (ddepth != -1) desc.depth = ddepth; - return desc; - } - - // Meta combinator: return a new GMatDesc with specified data depth - // and number of channels. - // (all other fields are taken unchanged from this GMatDesc) - GAPI_WRAP GMatDesc withType(int ddepth, int dchan) const - { - GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); - GMatDesc desc = withDepth(ddepth); - desc.chan = dchan; - return desc; - } - - // Meta combinator: return a new GMatDesc with planar flag set - // (no size changes are performed, only channel interpretation is changed - // (interleaved -> planar) - GAPI_WRAP GMatDesc asPlanar() const - { - GAPI_Assert(planar == false); - GMatDesc desc(*this); - desc.planar = true; - return desc; - } - - // Meta combinator: return a new GMatDesc - // reinterpreting 1-channel input as planar image - // (size height is divided by plane number) - GAPI_WRAP GMatDesc asPlanar(int planes) const - { - GAPI_Assert(planar == false); - GAPI_Assert(chan == 1); - GAPI_Assert(planes > 1); - GAPI_Assert(size.height % planes == 0); - GMatDesc desc(*this); - desc.size.height /= planes; - desc.chan = planes; - return desc.asPlanar(); - } - - // Meta combinator: return a new GMatDesc with planar flag set to false - // (no size changes are performed, only channel interpretation is changed - // (planar -> interleaved) - GAPI_WRAP GMatDesc asInterleaved() const - { - GAPI_Assert(planar == true); - GMatDesc desc(*this); - desc.planar = false; - return desc; - } -}; - -static inline GMatDesc empty_gmat_desc() { return GMatDesc{-1,-1,{-1,-1}}; } - -namespace gapi { namespace detail { -/** Checks GMatDesc fields if the passed matrix is a set of n-dimentional points. -@param in GMatDesc to check. -@param n expected dimensionality. -@return the amount of points. In case input matrix can't be described as vector of points -of expected dimensionality, returns -1. - */ -int checkVector(const GMatDesc& in, const size_t n); - -/** @overload - -Checks GMatDesc fields if the passed matrix can be described as a set of points of any -dimensionality. - -@return array of two elements in form of std::vector: the amount of points -and their calculated dimensionality. In case input matrix can't be described as vector of points, -returns {-1, -1}. - */ -std::vector checkVector(const GMatDesc& in); -}} // namespace gapi::detail - -#if !defined(GAPI_STANDALONE) -GAPI_EXPORTS GMatDesc descr_of(const cv::UMat &mat); -#endif // !defined(GAPI_STANDALONE) - -//Fwd declarations -namespace gapi { namespace own { - class Mat; - GAPI_EXPORTS GMatDesc descr_of(const Mat &mat); -}}//gapi::own - -GAPI_EXPORTS GMatDesc descr_of(const RMat &mat); - -#if !defined(GAPI_STANDALONE) -GAPI_EXPORTS GMatDesc descr_of(const cv::Mat &mat); -#else -using gapi::own::descr_of; -#endif - -/** @} */ - -GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GMatDesc &desc); - -} // namespace cv - -#endif // OPENCV_GAPI_GMAT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GMAT_HPP +#define OPENCV_GAPI_GMAT_HPP + +#include +#include // std::shared_ptr + +#include +#include // GShape + +#include + +// TODO GAPI_EXPORTS or so +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; + +/** \addtogroup gapi_data_objects + * @{ + * + * @brief G-API data objects used to build G-API expressions. + * + * These objects do not own any particular data (except compile-time + * associated values like with cv::GScalar or `cv::GArray`) and are + * used only to construct graphs. + * + * Every graph in G-API starts and ends with data objects. + * + * Once constructed and compiled, G-API operates with regular host-side + * data instead. Refer to the below table to find the mapping between + * G-API and regular data types when passing input and output data + * structures to G-API: + * + * G-API data type | I/O data type + * ------------------ | ------------- + * cv::GMat | cv::Mat, cv::UMat, cv::RMat + * cv::GScalar | cv::Scalar + * `cv::GArray` | std::vector + * `cv::GOpaque` | T + * cv::GFrame | cv::MediaFrame + */ + +/** + * @brief GMat class represents image or tensor data in the + * graph. + * + * GMat doesn't store any data itself, instead it describes a + * functional relationship between operations consuming and producing + * GMat objects. + * + * GMat is a virtual counterpart of Mat and UMat, but it + * doesn't mean G-API use Mat or UMat objects internally to represent + * GMat objects -- the internal data representation may be + * backend-specific or optimized out at all. + * + * @sa Mat, GMatDesc + */ +class GAPI_EXPORTS_W_SIMPLE GMat +{ +public: + /** + * @brief Constructs an empty GMat + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty GMat is assigned to a result of some + * operation, it obtains a functional link to this operation (and + * is not empty anymore). + */ + GAPI_WRAP GMat(); // Empty constructor + + /** + * @brief Constructs a value-initialized GMat + * + * GMat may be associated with a buffer at graph construction time. + * It is useful when some operation has a Mat input which doesn't + * change during the program execution, and is set only once. + * In this case, there's no need to declare such GMat as graph input. + * + * @param m a cv::Mat buffer to associate with this GMat object. + */ + GAPI_WRAP explicit GMat(cv::Mat m); // Value-initialization constructor + + /// @private + GMat(const GNode &n, std::size_t out); // Operation result constructor + /// @private + GOrigin& priv(); // Internal use only + /// @private + const GOrigin& priv() const; // Internal use only + +private: + std::shared_ptr m_priv; +}; + +class GAPI_EXPORTS GMatP : public GMat +{ +public: + using GMat::GMat; +}; + +class RMat; + +/** @} */ + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GMatDesc +{ + // FIXME: Default initializers in C++14 + GAPI_PROP int depth; + GAPI_PROP int chan; + GAPI_PROP cv::Size size; // NB.: no multi-dimensional cases covered yet + GAPI_PROP bool planar; + GAPI_PROP std::vector dims; // FIXME: Maybe it's real questionable to have it here + + GAPI_WRAP GMatDesc(int d, int c, cv::Size s, bool p = false) + : depth(d), chan(c), size(s), planar(p) {} + + GAPI_WRAP GMatDesc(int d, const std::vector &dd) + : depth(d), chan(-1), size{-1,-1}, planar(false), dims(dd) {} + + GAPI_WRAP GMatDesc(int d, std::vector &&dd) + : depth(d), chan(-1), size{-1,-1}, planar(false), dims(std::move(dd)) {} + + GAPI_WRAP GMatDesc() : GMatDesc(-1, -1, {-1,-1}) {} + + inline bool operator== (const GMatDesc &rhs) const + { + return depth == rhs.depth + && chan == rhs.chan + && size == rhs.size + && planar == rhs.planar + && dims == rhs.dims; + } + + inline bool operator!= (const GMatDesc &rhs) const + { + return !(*this == rhs); + } + + bool isND() const { return !dims.empty(); } + + // Checks if the passed mat can be described by this descriptor + // (it handles the case when + // 1-channel mat can be reinterpreted as is (1-channel mat) + // and as a 3-channel planar mat with height divided by 3) + bool canDescribe(const cv::Mat& mat) const; + + bool canDescribe(const cv::RMat& mat) const; + + // Meta combinator: return a new GMatDesc which differs in size by delta + // (all other fields are taken unchanged from this GMatDesc) + // FIXME: a better name? + GAPI_WRAP GMatDesc withSizeDelta(cv::Size delta) const + { + GMatDesc desc(*this); + desc.size += delta; + return desc; + } + // Meta combinator: return a new GMatDesc which differs in size by delta + // (all other fields are taken unchanged from this GMatDesc) + // + // This is an overload. + GAPI_WRAP GMatDesc withSizeDelta(int dx, int dy) const + { + return withSizeDelta(cv::Size{dx,dy}); + } + + GAPI_WRAP GMatDesc withSize(cv::Size sz) const + { + GMatDesc desc(*this); + desc.size = sz; + return desc; + } + + // Meta combinator: return a new GMatDesc with specified data depth. + // (all other fields are taken unchanged from this GMatDesc) + GAPI_WRAP GMatDesc withDepth(int ddepth) const + { + GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); + GMatDesc desc(*this); + if (ddepth != -1) desc.depth = ddepth; + return desc; + } + + // Meta combinator: return a new GMatDesc with specified data depth + // and number of channels. + // (all other fields are taken unchanged from this GMatDesc) + GAPI_WRAP GMatDesc withType(int ddepth, int dchan) const + { + GAPI_Assert(CV_MAT_CN(ddepth) == 1 || ddepth == -1); + GMatDesc desc = withDepth(ddepth); + desc.chan = dchan; + return desc; + } + + // Meta combinator: return a new GMatDesc with planar flag set + // (no size changes are performed, only channel interpretation is changed + // (interleaved -> planar) + GAPI_WRAP GMatDesc asPlanar() const + { + GAPI_Assert(planar == false); + GMatDesc desc(*this); + desc.planar = true; + return desc; + } + + // Meta combinator: return a new GMatDesc + // reinterpreting 1-channel input as planar image + // (size height is divided by plane number) + GAPI_WRAP GMatDesc asPlanar(int planes) const + { + GAPI_Assert(planar == false); + GAPI_Assert(chan == 1); + GAPI_Assert(planes > 1); + GAPI_Assert(size.height % planes == 0); + GMatDesc desc(*this); + desc.size.height /= planes; + desc.chan = planes; + return desc.asPlanar(); + } + + // Meta combinator: return a new GMatDesc with planar flag set to false + // (no size changes are performed, only channel interpretation is changed + // (planar -> interleaved) + GAPI_WRAP GMatDesc asInterleaved() const + { + GAPI_Assert(planar == true); + GMatDesc desc(*this); + desc.planar = false; + return desc; + } +}; + +static inline GMatDesc empty_gmat_desc() { return GMatDesc{-1,-1,{-1,-1}}; } + +namespace gapi { namespace detail { +/** Checks GMatDesc fields if the passed matrix is a set of n-dimentional points. +@param in GMatDesc to check. +@param n expected dimensionality. +@return the amount of points. In case input matrix can't be described as vector of points +of expected dimensionality, returns -1. + */ +int checkVector(const GMatDesc& in, const size_t n); + +/** @overload + +Checks GMatDesc fields if the passed matrix can be described as a set of points of any +dimensionality. + +@return array of two elements in form of std::vector: the amount of points +and their calculated dimensionality. In case input matrix can't be described as vector of points, +returns {-1, -1}. + */ +std::vector checkVector(const GMatDesc& in); +}} // namespace gapi::detail + +#if !defined(GAPI_STANDALONE) +GAPI_EXPORTS GMatDesc descr_of(const cv::UMat &mat); +#endif // !defined(GAPI_STANDALONE) + +//Fwd declarations +namespace gapi { namespace own { + class Mat; + GAPI_EXPORTS GMatDesc descr_of(const Mat &mat); +}}//gapi::own + +GAPI_EXPORTS GMatDesc descr_of(const RMat &mat); + +#if !defined(GAPI_STANDALONE) +GAPI_EXPORTS GMatDesc descr_of(const cv::Mat &mat); +#else +using gapi::own::descr_of; +#endif + +/** @} */ + +GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const cv::GMatDesc &desc); + +} // namespace cv + +#endif // OPENCV_GAPI_GMAT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp index f9aac032e4..f21182c19f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gmetaarg.hpp @@ -1,80 +1,80 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GMETAARG_HPP -#define OPENCV_GAPI_GMETAARG_HPP - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -namespace cv -{ -// FIXME: Rename to GMeta? -// FIXME: user shouldn't deal with it - put to detail? -// GMetaArg is an union type over descriptions of G-types which can serve as -// GComputation's in/output slots. -// -// GMetaArg objects are passed as arguments to GComputation::compile() -// to specify which data a compiled computation should be specialized on. -// For manual compile(), user must supply this metadata, in case of apply() -// this metadata is taken from arguments computation should operate on. -// -// The first type (monostate) is equal to "uninitialized"/"unresolved" meta. -using GMetaArg = util::variant - < util::monostate - , GMatDesc - , GScalarDesc - , GArrayDesc - , GOpaqueDesc - , GFrameDesc - >; -GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const GMetaArg &); - -using GMetaArgs = std::vector; - -namespace detail -{ - // These traits are used by GComputation::compile() - - // FIXME: is_constructible doesn't work as variant doesn't do any SFINAE - // in its current template constructor - - template struct is_meta_descr : std::false_type {}; - template<> struct is_meta_descr : std::true_type {}; - template<> struct is_meta_descr : std::true_type {}; - template<> struct is_meta_descr : std::true_type {}; - template<> struct is_meta_descr : std::true_type {}; - - template - using are_meta_descrs = all_satisfy; - - template - using are_meta_descrs_but_last = all_satisfy::type>; - -} // namespace detail - -// Note: descr_of(std::vector<..>) returns a GArrayDesc, while -// descrs_of(std::vector<..>) returns an array of Meta args! -class UMat; -GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); -GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); -namespace gapi { namespace own { - GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); -}} // namespace gapi::own - -} // namespace cv - -#endif // OPENCV_GAPI_GMETAARG_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GMETAARG_HPP +#define OPENCV_GAPI_GMETAARG_HPP + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +namespace cv +{ +// FIXME: Rename to GMeta? +// FIXME: user shouldn't deal with it - put to detail? +// GMetaArg is an union type over descriptions of G-types which can serve as +// GComputation's in/output slots. +// +// GMetaArg objects are passed as arguments to GComputation::compile() +// to specify which data a compiled computation should be specialized on. +// For manual compile(), user must supply this metadata, in case of apply() +// this metadata is taken from arguments computation should operate on. +// +// The first type (monostate) is equal to "uninitialized"/"unresolved" meta. +using GMetaArg = util::variant + < util::monostate + , GMatDesc + , GScalarDesc + , GArrayDesc + , GOpaqueDesc + , GFrameDesc + >; +GAPI_EXPORTS std::ostream& operator<<(std::ostream& os, const GMetaArg &); + +using GMetaArgs = std::vector; + +namespace detail +{ + // These traits are used by GComputation::compile() + + // FIXME: is_constructible doesn't work as variant doesn't do any SFINAE + // in its current template constructor + + template struct is_meta_descr : std::false_type {}; + template<> struct is_meta_descr : std::true_type {}; + template<> struct is_meta_descr : std::true_type {}; + template<> struct is_meta_descr : std::true_type {}; + template<> struct is_meta_descr : std::true_type {}; + + template + using are_meta_descrs = all_satisfy; + + template + using are_meta_descrs_but_last = all_satisfy::type>; + +} // namespace detail + +// Note: descr_of(std::vector<..>) returns a GArrayDesc, while +// descrs_of(std::vector<..>) returns an array of Meta args! +class UMat; +GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); +GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); +namespace gapi { namespace own { + GAPI_EXPORTS cv::GMetaArgs descrs_of(const std::vector &vec); +}} // namespace gapi::own + +} // namespace cv + +#endif // OPENCV_GAPI_GMETAARG_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp index 207556f0b7..a3f98a9867 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gopaque.hpp @@ -1,369 +1,369 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GOPAQUE_HPP -#define OPENCV_GAPI_GOPAQUE_HPP - -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include // OpaqueKind -#include // TypeHintBase - -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; -template class GOpaque; - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GOpaqueDesc -{ - // FIXME: Body - // FIXME: Also implement proper operator== then - bool operator== (const GOpaqueDesc&) const { return true; } -}; -template GOpaqueDesc descr_of(const U &) { return {};} -GAPI_EXPORTS_W inline GOpaqueDesc empty_gopaque_desc() {return {}; } -/** @} */ - -std::ostream& operator<<(std::ostream& os, const cv::GOpaqueDesc &desc); - -namespace detail -{ - // ConstructOpaque is a callback which stores information about T and is used by - // G-API runtime to construct an object in host memory (T remains opaque for G-API). - // ConstructOpaque is carried into G-API internals by GOpaqueU. - // Currently it is suitable for Host (CPU) plugins only, real offload may require - // more information for manual memory allocation on-device. - class OpaqueRef; - using ConstructOpaque = std::function; - - // FIXME: garray.hpp already contains hint classes (for actual T type verification), - // need to think where it can be moved (currently opaque uses it from garray) - - // This class strips type information from GOpaque and makes it usable - // in the G-API graph compiler (expression unrolling, graph generation, etc). - // Part of GProtoArg. - class GAPI_EXPORTS GOpaqueU - { - public: - GOpaqueU(const GNode &n, std::size_t out); // Operation result constructor - - template - bool holds() const; // Check if was created from GOpaque - - GOrigin& priv(); // Internal use only - const GOrigin& priv() const; // Internal use only - - protected: - GOpaqueU(); // Default constructor - template friend class cv::GOpaque; // (available for GOpaque only) - - void setConstructFcn(ConstructOpaque &&cv); // Store T-aware constructor - - template - void specifyType(); // Store type of initial GOpaque - - template - void storeKind(); - - void setKind(cv::detail::OpaqueKind); - - std::shared_ptr m_priv; - std::shared_ptr m_hint; - }; - - template - bool GOpaqueU::holds() const{ - GAPI_Assert(m_hint != nullptr); - using U = util::decay_t; - return dynamic_cast*>(m_hint.get()) != nullptr; - } - - template - void GOpaqueU::specifyType(){ - m_hint.reset(new TypeHint>); - } - - template - void GOpaqueU::storeKind(){ - // FIXME: Add assert here on cv::Mat and cv::Scalar? - setKind(cv::detail::GOpaqueTraits::kind); - } - - // This class represents a typed object reference. - // Depending on origins, this reference may be either "just a" reference to - // an object created externally, OR actually own the underlying object - // (be value holder). - class BasicOpaqueRef - { - public: - cv::GOpaqueDesc m_desc; - virtual ~BasicOpaqueRef() {} - - virtual void mov(BasicOpaqueRef &ref) = 0; - virtual const void* ptr() const = 0; - virtual void set(const cv::util::any &a) = 0; - }; - - template class OpaqueRefT final: public BasicOpaqueRef - { - using empty_t = util::monostate; - using ro_ext_t = const T *; - using rw_ext_t = T *; - using rw_own_t = T ; - util::variant m_ref; - - inline bool isEmpty() const { return util::holds_alternative(m_ref); } - inline bool isROExt() const { return util::holds_alternative(m_ref); } - inline bool isRWExt() const { return util::holds_alternative(m_ref); } - inline bool isRWOwn() const { return util::holds_alternative(m_ref); } - - void init(const T* obj = nullptr) - { - if (obj) m_desc = cv::descr_of(*obj); - } - - public: - OpaqueRefT() { init(); } - virtual ~OpaqueRefT() {} - - explicit OpaqueRefT(const T& obj) : m_ref(&obj) { init(&obj); } - explicit OpaqueRefT( T& obj) : m_ref(&obj) { init(&obj); } - explicit OpaqueRefT( T&& obj) : m_ref(std::move(obj)) { init(&obj); } - - // Reset a OpaqueRefT. Called only for objects instantiated - // internally in G-API (e.g. temporary GOpaque's within a - // computation). Reset here means both initialization - // (creating an object) and reset (discarding its existing - // content before the next execution). Must never be called - // for external OpaqueRefTs. - void reset() - { - if (isEmpty()) - { - T empty_obj{}; - m_desc = cv::descr_of(empty_obj); - m_ref = std::move(empty_obj); - GAPI_Assert(isRWOwn()); - } - else if (isRWOwn()) - { - util::get(m_ref) = {}; - } - else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes - } - - // Obtain a WRITE reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - T& wref() - { - GAPI_Assert(isRWExt() || isRWOwn()); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - // Obtain a READ reference to underlying object - // Used by CPU kernel API wrappers when a kernel execution frame - // is created - const T& rref() const - { - // ANY object can be accessed for reading, even if it declared for - // output. Example -- a GComputation from [in] to [out1,out2] - // where [out2] is a result of operation applied to [out1]: - // - // GComputation boundary - // . . . . . . . - // . . - // [in] ----> foo() ----> [out1] - // . . : - // . . . .:. . . - // . V . - // . bar() ---> [out2] - // . . . . . . . . . . . . - // - if (isROExt()) return *util::get(m_ref); - if (isRWExt()) return *util::get(m_ref); - if (isRWOwn()) return util::get(m_ref); - util::throw_error(std::logic_error("Impossible happened")); - } - - virtual void mov(BasicOpaqueRef &v) override { - OpaqueRefT *tv = dynamic_cast*>(&v); - GAPI_Assert(tv != nullptr); - wref() = std::move(tv->wref()); - } - - virtual const void* ptr() const override { return &rref(); } - - virtual void set(const cv::util::any &a) override { - wref() = util::any_cast(a); - } - }; - - // This class strips type information from OpaqueRefT<> and makes it usable - // in the G-API executables (carrying run-time data/information to kernels). - // Part of GRunArg. - // Its methods are typed proxies to OpaqueRefT. - // OpaqueRef maintains "reference" semantics so two copies of OpaqueRef refer - // to the same underlying object. - class OpaqueRef - { - std::shared_ptr m_ref; - cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; - - template inline void check() const - { - GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); - } - - public: - OpaqueRef() = default; - - template< - typename T, - typename = util::are_different_t - > - // FIXME: probably won't work with const object - explicit OpaqueRef(T&& obj) : - m_ref(new OpaqueRefT>(std::forward(obj))), - m_kind(GOpaqueTraits>::kind) {} - - cv::detail::OpaqueKind getKind() const - { - return m_kind; - } - - template void reset() - { - if (!m_ref) m_ref.reset(new OpaqueRefT()); - check(); - storeKind(); - static_cast&>(*m_ref).reset(); - } - - template - void storeKind() - { - m_kind = cv::detail::GOpaqueTraits::kind; - } - - template T& wref() - { - check(); - return static_cast&>(*m_ref).wref(); - } - - template const T& rref() const - { - check(); - return static_cast&>(*m_ref).rref(); - } - - void mov(OpaqueRef &v) - { - m_ref->mov(*v.m_ref); - } - - cv::GOpaqueDesc descr_of() const - { - return m_ref->m_desc; - } - - // May be used to uniquely identify this object internally - const void *ptr() const { return m_ref->ptr(); } - - // Introduced for in-graph meta handling - OpaqueRef& operator= (const cv::util::any &a) - { - m_ref->set(a); - return *this; - } - }; -} // namespace detail - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief `cv::GOpaque` template class represents an object of - * class `T` in the graph. - * - * `cv::GOpaque` describes a functional relationship between operations - * consuming and producing object of class `T`. `cv::GOpaque` is - * designed to extend G-API with user-defined data types, which are - * often required with user-defined operations. G-API can't apply any - * optimizations to user-defined types since these types are opaque to - * the framework. However, there is a number of G-API operations - * declared with `cv::GOpaque` as a return type, - * e.g. cv::gapi::streaming::timestamp() or cv::gapi::streaming::size(). - * - * @sa `cv::GArray` - */ -template class GOpaque -{ -public: - // Host type (or Flat type) - the type this GOpaque is actually - // specified to. - /// @private - using HT = typename detail::flatten_g>::type; - - /** - * @brief Constructs an empty `cv::GOpaque` - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty `cv::GOpaque` is assigned to a result - * of some operation, it obtains a functional link to this - * operation (and is not empty anymore). - */ - GOpaque() { putDetails(); } // Empty constructor - - /// @private - explicit GOpaque(detail::GOpaqueU &&ref) // GOpaqueU-based constructor - : m_ref(ref) { putDetails(); } // (used by GCall, not for users) - - /// @private - detail::GOpaqueU strip() const { - return m_ref; - } - /// @private - static void Ctor(detail::OpaqueRef& ref) { - ref.reset(); - } -private: - void putDetails() { - m_ref.setConstructFcn(&Ctor); - m_ref.specifyType(); - m_ref.storeKind(); - } - - detail::GOpaqueU m_ref; -}; - -/** @} */ - -} // namespace cv - -#endif // OPENCV_GAPI_GOPAQUE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GOPAQUE_HPP +#define OPENCV_GAPI_GOPAQUE_HPP + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include // OpaqueKind +#include // TypeHintBase + +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; +template class GOpaque; + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GOpaqueDesc +{ + // FIXME: Body + // FIXME: Also implement proper operator== then + bool operator== (const GOpaqueDesc&) const { return true; } +}; +template GOpaqueDesc descr_of(const U &) { return {};} +GAPI_EXPORTS_W inline GOpaqueDesc empty_gopaque_desc() {return {}; } +/** @} */ + +std::ostream& operator<<(std::ostream& os, const cv::GOpaqueDesc &desc); + +namespace detail +{ + // ConstructOpaque is a callback which stores information about T and is used by + // G-API runtime to construct an object in host memory (T remains opaque for G-API). + // ConstructOpaque is carried into G-API internals by GOpaqueU. + // Currently it is suitable for Host (CPU) plugins only, real offload may require + // more information for manual memory allocation on-device. + class OpaqueRef; + using ConstructOpaque = std::function; + + // FIXME: garray.hpp already contains hint classes (for actual T type verification), + // need to think where it can be moved (currently opaque uses it from garray) + + // This class strips type information from GOpaque and makes it usable + // in the G-API graph compiler (expression unrolling, graph generation, etc). + // Part of GProtoArg. + class GAPI_EXPORTS GOpaqueU + { + public: + GOpaqueU(const GNode &n, std::size_t out); // Operation result constructor + + template + bool holds() const; // Check if was created from GOpaque + + GOrigin& priv(); // Internal use only + const GOrigin& priv() const; // Internal use only + + protected: + GOpaqueU(); // Default constructor + template friend class cv::GOpaque; // (available for GOpaque only) + + void setConstructFcn(ConstructOpaque &&cv); // Store T-aware constructor + + template + void specifyType(); // Store type of initial GOpaque + + template + void storeKind(); + + void setKind(cv::detail::OpaqueKind); + + std::shared_ptr m_priv; + std::shared_ptr m_hint; + }; + + template + bool GOpaqueU::holds() const{ + GAPI_Assert(m_hint != nullptr); + using U = util::decay_t; + return dynamic_cast*>(m_hint.get()) != nullptr; + } + + template + void GOpaqueU::specifyType(){ + m_hint.reset(new TypeHint>); + } + + template + void GOpaqueU::storeKind(){ + // FIXME: Add assert here on cv::Mat and cv::Scalar? + setKind(cv::detail::GOpaqueTraits::kind); + } + + // This class represents a typed object reference. + // Depending on origins, this reference may be either "just a" reference to + // an object created externally, OR actually own the underlying object + // (be value holder). + class BasicOpaqueRef + { + public: + cv::GOpaqueDesc m_desc; + virtual ~BasicOpaqueRef() {} + + virtual void mov(BasicOpaqueRef &ref) = 0; + virtual const void* ptr() const = 0; + virtual void set(const cv::util::any &a) = 0; + }; + + template class OpaqueRefT final: public BasicOpaqueRef + { + using empty_t = util::monostate; + using ro_ext_t = const T *; + using rw_ext_t = T *; + using rw_own_t = T ; + util::variant m_ref; + + inline bool isEmpty() const { return util::holds_alternative(m_ref); } + inline bool isROExt() const { return util::holds_alternative(m_ref); } + inline bool isRWExt() const { return util::holds_alternative(m_ref); } + inline bool isRWOwn() const { return util::holds_alternative(m_ref); } + + void init(const T* obj = nullptr) + { + if (obj) m_desc = cv::descr_of(*obj); + } + + public: + OpaqueRefT() { init(); } + virtual ~OpaqueRefT() {} + + explicit OpaqueRefT(const T& obj) : m_ref(&obj) { init(&obj); } + explicit OpaqueRefT( T& obj) : m_ref(&obj) { init(&obj); } + explicit OpaqueRefT( T&& obj) : m_ref(std::move(obj)) { init(&obj); } + + // Reset a OpaqueRefT. Called only for objects instantiated + // internally in G-API (e.g. temporary GOpaque's within a + // computation). Reset here means both initialization + // (creating an object) and reset (discarding its existing + // content before the next execution). Must never be called + // for external OpaqueRefTs. + void reset() + { + if (isEmpty()) + { + T empty_obj{}; + m_desc = cv::descr_of(empty_obj); + m_ref = std::move(empty_obj); + GAPI_Assert(isRWOwn()); + } + else if (isRWOwn()) + { + util::get(m_ref) = {}; + } + else GAPI_Error("InternalError"); // shouldn't be called in *EXT modes + } + + // Obtain a WRITE reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + T& wref() + { + GAPI_Assert(isRWExt() || isRWOwn()); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + // Obtain a READ reference to underlying object + // Used by CPU kernel API wrappers when a kernel execution frame + // is created + const T& rref() const + { + // ANY object can be accessed for reading, even if it declared for + // output. Example -- a GComputation from [in] to [out1,out2] + // where [out2] is a result of operation applied to [out1]: + // + // GComputation boundary + // . . . . . . . + // . . + // [in] ----> foo() ----> [out1] + // . . : + // . . . .:. . . + // . V . + // . bar() ---> [out2] + // . . . . . . . . . . . . + // + if (isROExt()) return *util::get(m_ref); + if (isRWExt()) return *util::get(m_ref); + if (isRWOwn()) return util::get(m_ref); + util::throw_error(std::logic_error("Impossible happened")); + } + + virtual void mov(BasicOpaqueRef &v) override { + OpaqueRefT *tv = dynamic_cast*>(&v); + GAPI_Assert(tv != nullptr); + wref() = std::move(tv->wref()); + } + + virtual const void* ptr() const override { return &rref(); } + + virtual void set(const cv::util::any &a) override { + wref() = util::any_cast(a); + } + }; + + // This class strips type information from OpaqueRefT<> and makes it usable + // in the G-API executables (carrying run-time data/information to kernels). + // Part of GRunArg. + // Its methods are typed proxies to OpaqueRefT. + // OpaqueRef maintains "reference" semantics so two copies of OpaqueRef refer + // to the same underlying object. + class OpaqueRef + { + std::shared_ptr m_ref; + cv::detail::OpaqueKind m_kind = cv::detail::OpaqueKind::CV_UNKNOWN; + + template inline void check() const + { + GAPI_DbgAssert(dynamic_cast*>(m_ref.get()) != nullptr); + } + + public: + OpaqueRef() = default; + + template< + typename T, + typename = util::are_different_t + > + // FIXME: probably won't work with const object + explicit OpaqueRef(T&& obj) : + m_ref(new OpaqueRefT>(std::forward(obj))), + m_kind(GOpaqueTraits>::kind) {} + + cv::detail::OpaqueKind getKind() const + { + return m_kind; + } + + template void reset() + { + if (!m_ref) m_ref.reset(new OpaqueRefT()); + check(); + storeKind(); + static_cast&>(*m_ref).reset(); + } + + template + void storeKind() + { + m_kind = cv::detail::GOpaqueTraits::kind; + } + + template T& wref() + { + check(); + return static_cast&>(*m_ref).wref(); + } + + template const T& rref() const + { + check(); + return static_cast&>(*m_ref).rref(); + } + + void mov(OpaqueRef &v) + { + m_ref->mov(*v.m_ref); + } + + cv::GOpaqueDesc descr_of() const + { + return m_ref->m_desc; + } + + // May be used to uniquely identify this object internally + const void *ptr() const { return m_ref->ptr(); } + + // Introduced for in-graph meta handling + OpaqueRef& operator= (const cv::util::any &a) + { + m_ref->set(a); + return *this; + } + }; +} // namespace detail + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief `cv::GOpaque` template class represents an object of + * class `T` in the graph. + * + * `cv::GOpaque` describes a functional relationship between operations + * consuming and producing object of class `T`. `cv::GOpaque` is + * designed to extend G-API with user-defined data types, which are + * often required with user-defined operations. G-API can't apply any + * optimizations to user-defined types since these types are opaque to + * the framework. However, there is a number of G-API operations + * declared with `cv::GOpaque` as a return type, + * e.g. cv::gapi::streaming::timestamp() or cv::gapi::streaming::size(). + * + * @sa `cv::GArray` + */ +template class GOpaque +{ +public: + // Host type (or Flat type) - the type this GOpaque is actually + // specified to. + /// @private + using HT = typename detail::flatten_g>::type; + + /** + * @brief Constructs an empty `cv::GOpaque` + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty `cv::GOpaque` is assigned to a result + * of some operation, it obtains a functional link to this + * operation (and is not empty anymore). + */ + GOpaque() { putDetails(); } // Empty constructor + + /// @private + explicit GOpaque(detail::GOpaqueU &&ref) // GOpaqueU-based constructor + : m_ref(ref) { putDetails(); } // (used by GCall, not for users) + + /// @private + detail::GOpaqueU strip() const { + return m_ref; + } + /// @private + static void Ctor(detail::OpaqueRef& ref) { + ref.reset(); + } +private: + void putDetails() { + m_ref.setConstructFcn(&Ctor); + m_ref.specifyType(); + m_ref.storeKind(); + } + + detail::GOpaqueU m_ref; +}; + +/** @} */ + +} // namespace cv + +#endif // OPENCV_GAPI_GOPAQUE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp index fd16f0a7c6..a2b5d83bc1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gproto.hpp @@ -1,159 +1,159 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GPROTO_HPP -#define OPENCV_GAPI_GPROTO_HPP - -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include - -namespace cv { - -// FIXME: user shouldn't deal with it - put to detail? -// GProtoArg is an union type over G-types which can serve as -// GComputation's in/output slots. In other words, GProtoArg -// wraps any type which can serve as G-API exchange type. -// -// In Runtime, GProtoArgs are substituted with appropriate GRunArgs. -// -// GProtoArg objects are constructed in-place when user describes -// (captures) computations, user doesn't interact with these types -// directly. -using GProtoArg = util::variant - < GMat - , GMatP - , GFrame - , GScalar - , detail::GArrayU // instead of GArray - , detail::GOpaqueU // instead of GOpaque - >; - -using GProtoArgs = std::vector; - -namespace detail -{ -template inline GProtoArgs packArgs(Ts... args) -{ - return GProtoArgs{ GProtoArg(wrap_gapi_helper::wrap(args))... }; -} - -} - -template -struct GIOProtoArgs -{ -public: - // NB: Used by python wrapper - GIOProtoArgs() = default; - explicit GIOProtoArgs(const GProtoArgs& args) : m_args(args) {} - explicit GIOProtoArgs(GProtoArgs &&args) : m_args(std::move(args)) {} - - GProtoArgs m_args; - - // TODO: Think about the addition operator - /** - * @brief This operator allows to complement the proto vectors at runtime. - * - * It's an ordinary overload of addition assignment operator. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GIOProtoArgs usage - * - */ - template - friend GIOProtoArgs& operator += (GIOProtoArgs &lhs, const GIOProtoArgs &rhs); -}; - -template -cv::GIOProtoArgs& operator += (cv::GIOProtoArgs &lhs, const cv::GIOProtoArgs &rhs) -{ - lhs.m_args.reserve(lhs.m_args.size() + rhs.m_args.size()); - lhs.m_args.insert(lhs.m_args.end(), rhs.m_args.begin(), rhs.m_args.end()); - return lhs; -} - -struct In_Tag{}; -struct Out_Tag{}; - -using GProtoInputArgs = GIOProtoArgs; -using GProtoOutputArgs = GIOProtoArgs; - -// Perfect forwarding -template inline GProtoInputArgs GIn(Ts&&... ts) -{ - return GProtoInputArgs(detail::packArgs(std::forward(ts)...)); -} - -template inline GProtoOutputArgs GOut(Ts&&... ts) -{ - return GProtoOutputArgs(detail::packArgs(std::forward(ts)...)); -} - -namespace detail -{ - // Extract elements form tuple - // FIXME: Someday utilize a generic tuple_to_vec<> routine - template - static GProtoOutputArgs getGOut_impl(const std::tuple& ts, detail::Seq) - { - return GProtoOutputArgs{ detail::packArgs(std::get(ts)...)}; - } -} - -template inline GProtoOutputArgs GOut(const std::tuple& ts) -{ - // TODO: think of std::forward(ts) - return detail::getGOut_impl(ts, typename detail::MkSeq::type()); -} - -// Takes rvalue as input arg -template inline GProtoOutputArgs GOut(std::tuple&& ts) -{ - // TODO: think of std::forward(ts) - return detail::getGOut_impl(ts, typename detail::MkSeq::type()); -} - -// Extract run-time arguments from node origin -// Can be used to extract constant values associated with G-objects -// (like GScalar) at graph construction time -GRunArg value_of(const GOrigin &origin); - -// Transform run-time computation arguments into a collection of metadata -// extracted from that arguments -GMetaArg GAPI_EXPORTS descr_of(const GRunArg &arg ); -GMetaArgs GAPI_EXPORTS descr_of(const GRunArgs &args); - -// Transform run-time operation result argument into metadata extracted from that argument -// Used to compare the metadata, which generated at compile time with the metadata result operation in run time -GMetaArg GAPI_EXPORTS descr_of(const GRunArgP& argp); - -// Checks if run-time computation argument can be described by metadata -bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArg& arg); -bool GAPI_EXPORTS can_describe(const GMetaArgs& metas, const GRunArgs& args); - -// Checks if run-time computation result argument can be described by metadata. -// Used to check if the metadata generated at compile time -// coincides with output arguments passed to computation in cpu and ocl backends -bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArgP& argp); - -// Validates input arguments -void GAPI_EXPORTS validate_input_arg(const GRunArg& arg); -void GAPI_EXPORTS validate_input_args(const GRunArgs& args); - -} // namespace cv - -#endif // OPENCV_GAPI_GPROTO_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GPROTO_HPP +#define OPENCV_GAPI_GPROTO_HPP + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace cv { + +// FIXME: user shouldn't deal with it - put to detail? +// GProtoArg is an union type over G-types which can serve as +// GComputation's in/output slots. In other words, GProtoArg +// wraps any type which can serve as G-API exchange type. +// +// In Runtime, GProtoArgs are substituted with appropriate GRunArgs. +// +// GProtoArg objects are constructed in-place when user describes +// (captures) computations, user doesn't interact with these types +// directly. +using GProtoArg = util::variant + < GMat + , GMatP + , GFrame + , GScalar + , detail::GArrayU // instead of GArray + , detail::GOpaqueU // instead of GOpaque + >; + +using GProtoArgs = std::vector; + +namespace detail +{ +template inline GProtoArgs packArgs(Ts... args) +{ + return GProtoArgs{ GProtoArg(wrap_gapi_helper::wrap(args))... }; +} + +} + +template +struct GIOProtoArgs +{ +public: + // NB: Used by python wrapper + GIOProtoArgs() = default; + explicit GIOProtoArgs(const GProtoArgs& args) : m_args(args) {} + explicit GIOProtoArgs(GProtoArgs &&args) : m_args(std::move(args)) {} + + GProtoArgs m_args; + + // TODO: Think about the addition operator + /** + * @brief This operator allows to complement the proto vectors at runtime. + * + * It's an ordinary overload of addition assignment operator. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/dynamic_graph_snippets.cpp GIOProtoArgs usage + * + */ + template + friend GIOProtoArgs& operator += (GIOProtoArgs &lhs, const GIOProtoArgs &rhs); +}; + +template +cv::GIOProtoArgs& operator += (cv::GIOProtoArgs &lhs, const cv::GIOProtoArgs &rhs) +{ + lhs.m_args.reserve(lhs.m_args.size() + rhs.m_args.size()); + lhs.m_args.insert(lhs.m_args.end(), rhs.m_args.begin(), rhs.m_args.end()); + return lhs; +} + +struct In_Tag{}; +struct Out_Tag{}; + +using GProtoInputArgs = GIOProtoArgs; +using GProtoOutputArgs = GIOProtoArgs; + +// Perfect forwarding +template inline GProtoInputArgs GIn(Ts&&... ts) +{ + return GProtoInputArgs(detail::packArgs(std::forward(ts)...)); +} + +template inline GProtoOutputArgs GOut(Ts&&... ts) +{ + return GProtoOutputArgs(detail::packArgs(std::forward(ts)...)); +} + +namespace detail +{ + // Extract elements form tuple + // FIXME: Someday utilize a generic tuple_to_vec<> routine + template + static GProtoOutputArgs getGOut_impl(const std::tuple& ts, detail::Seq) + { + return GProtoOutputArgs{ detail::packArgs(std::get(ts)...)}; + } +} + +template inline GProtoOutputArgs GOut(const std::tuple& ts) +{ + // TODO: think of std::forward(ts) + return detail::getGOut_impl(ts, typename detail::MkSeq::type()); +} + +// Takes rvalue as input arg +template inline GProtoOutputArgs GOut(std::tuple&& ts) +{ + // TODO: think of std::forward(ts) + return detail::getGOut_impl(ts, typename detail::MkSeq::type()); +} + +// Extract run-time arguments from node origin +// Can be used to extract constant values associated with G-objects +// (like GScalar) at graph construction time +GRunArg value_of(const GOrigin &origin); + +// Transform run-time computation arguments into a collection of metadata +// extracted from that arguments +GMetaArg GAPI_EXPORTS descr_of(const GRunArg &arg ); +GMetaArgs GAPI_EXPORTS descr_of(const GRunArgs &args); + +// Transform run-time operation result argument into metadata extracted from that argument +// Used to compare the metadata, which generated at compile time with the metadata result operation in run time +GMetaArg GAPI_EXPORTS descr_of(const GRunArgP& argp); + +// Checks if run-time computation argument can be described by metadata +bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArg& arg); +bool GAPI_EXPORTS can_describe(const GMetaArgs& metas, const GRunArgs& args); + +// Checks if run-time computation result argument can be described by metadata. +// Used to check if the metadata generated at compile time +// coincides with output arguments passed to computation in cpu and ocl backends +bool GAPI_EXPORTS can_describe(const GMetaArg& meta, const GRunArgP& argp); + +// Validates input arguments +void GAPI_EXPORTS validate_input_arg(const GRunArg& arg); +void GAPI_EXPORTS validate_input_args(const GRunArgs& args); + +} // namespace cv + +#endif // OPENCV_GAPI_GPROTO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp index c5498fe95f..a7ee59577c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/core.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GPU_CORE_API_HPP -#define OPENCV_GAPI_GPU_CORE_API_HPP -/** @file -* @deprecated Use instead. -*/ - -#include - -namespace cv { -namespace gapi { -namespace core { -namespace gpu { - using namespace ocl; -} // namespace gpu -} // namespace core -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_GPU_CORE_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GPU_CORE_API_HPP +#define OPENCV_GAPI_GPU_CORE_API_HPP +/** @file +* @deprecated Use instead. +*/ + +#include + +namespace cv { +namespace gapi { +namespace core { +namespace gpu { + using namespace ocl; +} // namespace gpu +} // namespace core +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_GPU_CORE_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp index 9373ed79de..b52c21de6b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/ggpukernel.hpp @@ -1,18 +1,18 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GGPUKERNEL_HPP -#define OPENCV_GAPI_GGPUKERNEL_HPP -/** @file -* @deprecated Use instead. -*/ - -#include -#define GAPI_GPU_KERNEL GAPI_OCL_KERNEL - - -#endif // OPENCV_GAPI_GGPUKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GGPUKERNEL_HPP +#define OPENCV_GAPI_GGPUKERNEL_HPP +/** @file +* @deprecated Use instead. +*/ + +#include +#define GAPI_GPU_KERNEL GAPI_OCL_KERNEL + + +#endif // OPENCV_GAPI_GGPUKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp index cc0a93d884..b0df7ae331 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gpu/imgproc.hpp @@ -1,28 +1,28 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GPU_IMGPROC_API_HPP -#define OPENCV_GAPI_GPU_IMGPROC_API_HPP -/** @file -* @deprecated Use instead. -*/ - -#include - - -namespace cv { -namespace gapi { -namespace imgproc { -namespace gpu { - using namespace ocl; -} // namespace gpu -} // namespace imgproc -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_GPU_IMGPROC_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GPU_IMGPROC_API_HPP +#define OPENCV_GAPI_GPU_IMGPROC_API_HPP +/** @file +* @deprecated Use instead. +*/ + +#include + + +namespace cv { +namespace gapi { +namespace imgproc { +namespace gpu { + using namespace ocl; +} // namespace gpu +} // namespace imgproc +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_GPU_IMGPROC_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp index 03a70dfc32..de0dfe1383 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gscalar.hpp @@ -1,140 +1,140 @@ -// This file is part of OpenCV project. - -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GSCALAR_HPP -#define OPENCV_GAPI_GSCALAR_HPP - -#include - -#include -#include // GShape -#include - -namespace cv -{ -// Forward declaration; GNode and GOrigin are an internal -// (user-inaccessible) classes. -class GNode; -struct GOrigin; - -/** \addtogroup gapi_data_objects - * @{ - */ -/** - * @brief GScalar class represents cv::Scalar data in the graph. - * - * GScalar may be associated with a cv::Scalar value, which becomes - * its constant value bound in graph compile time. cv::GScalar describes a - * functional relationship between operations consuming and producing - * GScalar objects. - * - * GScalar is a virtual counterpart of cv::Scalar, which is usually used - * to represent the GScalar data in G-API during the execution. - * - * @sa Scalar - */ -class GAPI_EXPORTS_W_SIMPLE GScalar -{ -public: - /** - * @brief Constructs an empty GScalar - * - * Normally, empty G-API data objects denote a starting point of - * the graph. When an empty GScalar is assigned to a result of some - * operation, it obtains a functional link to this operation (and - * is not empty anymore). - */ - GAPI_WRAP GScalar(); - - /** - * @brief Constructs a value-initialized GScalar - * - * GScalars may have their values be associated at graph - * construction time. It is useful when some operation has a - * GScalar input which doesn't change during the program - * execution, and is set only once. In this case, there is no need - * to declare such GScalar as a graph input. - * - * @note The value of GScalar may be overwritten by assigning some - * other GScalar to the object using `operator=` -- on the - * assignment, the old GScalar value is discarded. - * - * @param s a cv::Scalar value to associate with this GScalar object. - */ - GAPI_WRAP - explicit GScalar(const cv::Scalar& s); - - /** - * @overload - * @brief Constructs a value-initialized GScalar - * - * @param s a cv::Scalar value to associate with this GScalar object. - */ - explicit GScalar(cv::Scalar&& s); // Constant value move-constructor from cv::Scalar - - /** - * @overload - * @brief Constructs a value-initialized GScalar - * - * @param v0 A `double` value to associate with this GScalar. Note - * that only the first component of a four-component cv::Scalar is - * set to this value, with others remain zeros. - * - * This constructor overload is not marked `explicit` and can be - * used in G-API expression code like this: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp gscalar_implicit - * - * Here operator+(GMat,GScalar) is used to wrap cv::gapi::addC() - * and a value-initialized GScalar is created on the fly. - * - * @overload - */ - GScalar(double v0); // Constant value constructor from double - - /// @private - GScalar(const GNode &n, std::size_t out); // Operation result constructor - /// @private - GOrigin& priv(); // Internal use only - /// @private - const GOrigin& priv() const; // Internal use only - -private: - std::shared_ptr m_priv; -}; - -/** @} */ - -/** - * \addtogroup gapi_meta_args - * @{ - */ -struct GAPI_EXPORTS_W_SIMPLE GScalarDesc -{ - // NB.: right now it is empty - - inline bool operator== (const GScalarDesc &) const - { - return true; // NB: implement this method if GScalar meta appears - } - - inline bool operator!= (const GScalarDesc &rhs) const - { - return !(*this == rhs); - } -}; - -GAPI_EXPORTS_W inline GScalarDesc empty_scalar_desc() { return GScalarDesc(); } - -GAPI_EXPORTS GScalarDesc descr_of(const cv::Scalar &scalar); - -std::ostream& operator<<(std::ostream& os, const cv::GScalarDesc &desc); - -} // namespace cv - -#endif // OPENCV_GAPI_GSCALAR_HPP +// This file is part of OpenCV project. + +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GSCALAR_HPP +#define OPENCV_GAPI_GSCALAR_HPP + +#include + +#include +#include // GShape +#include + +namespace cv +{ +// Forward declaration; GNode and GOrigin are an internal +// (user-inaccessible) classes. +class GNode; +struct GOrigin; + +/** \addtogroup gapi_data_objects + * @{ + */ +/** + * @brief GScalar class represents cv::Scalar data in the graph. + * + * GScalar may be associated with a cv::Scalar value, which becomes + * its constant value bound in graph compile time. cv::GScalar describes a + * functional relationship between operations consuming and producing + * GScalar objects. + * + * GScalar is a virtual counterpart of cv::Scalar, which is usually used + * to represent the GScalar data in G-API during the execution. + * + * @sa Scalar + */ +class GAPI_EXPORTS_W_SIMPLE GScalar +{ +public: + /** + * @brief Constructs an empty GScalar + * + * Normally, empty G-API data objects denote a starting point of + * the graph. When an empty GScalar is assigned to a result of some + * operation, it obtains a functional link to this operation (and + * is not empty anymore). + */ + GAPI_WRAP GScalar(); + + /** + * @brief Constructs a value-initialized GScalar + * + * GScalars may have their values be associated at graph + * construction time. It is useful when some operation has a + * GScalar input which doesn't change during the program + * execution, and is set only once. In this case, there is no need + * to declare such GScalar as a graph input. + * + * @note The value of GScalar may be overwritten by assigning some + * other GScalar to the object using `operator=` -- on the + * assignment, the old GScalar value is discarded. + * + * @param s a cv::Scalar value to associate with this GScalar object. + */ + GAPI_WRAP + explicit GScalar(const cv::Scalar& s); + + /** + * @overload + * @brief Constructs a value-initialized GScalar + * + * @param s a cv::Scalar value to associate with this GScalar object. + */ + explicit GScalar(cv::Scalar&& s); // Constant value move-constructor from cv::Scalar + + /** + * @overload + * @brief Constructs a value-initialized GScalar + * + * @param v0 A `double` value to associate with this GScalar. Note + * that only the first component of a four-component cv::Scalar is + * set to this value, with others remain zeros. + * + * This constructor overload is not marked `explicit` and can be + * used in G-API expression code like this: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp gscalar_implicit + * + * Here operator+(GMat,GScalar) is used to wrap cv::gapi::addC() + * and a value-initialized GScalar is created on the fly. + * + * @overload + */ + GScalar(double v0); // Constant value constructor from double + + /// @private + GScalar(const GNode &n, std::size_t out); // Operation result constructor + /// @private + GOrigin& priv(); // Internal use only + /// @private + const GOrigin& priv() const; // Internal use only + +private: + std::shared_ptr m_priv; +}; + +/** @} */ + +/** + * \addtogroup gapi_meta_args + * @{ + */ +struct GAPI_EXPORTS_W_SIMPLE GScalarDesc +{ + // NB.: right now it is empty + + inline bool operator== (const GScalarDesc &) const + { + return true; // NB: implement this method if GScalar meta appears + } + + inline bool operator!= (const GScalarDesc &rhs) const + { + return !(*this == rhs); + } +}; + +GAPI_EXPORTS_W inline GScalarDesc empty_scalar_desc() { return GScalarDesc(); } + +GAPI_EXPORTS GScalarDesc descr_of(const cv::Scalar &scalar); + +std::ostream& operator<<(std::ostream& os, const cv::GScalarDesc &desc); + +} // namespace cv + +#endif // OPENCV_GAPI_GSCALAR_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp index 8d4e15aa99..d413195b81 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gstreaming.hpp @@ -1,430 +1,430 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GSTREAMING_COMPILED_HPP -#define OPENCV_GAPI_GSTREAMING_COMPILED_HPP - -#include -#include - -#include -#include -#include -#include -#include - -namespace cv { - -template using optional = cv::util::optional; - -namespace detail { -template struct wref_spec { - using type = T; -}; -template struct wref_spec > { - using type = T; -}; - -template -struct OptRef { - struct OptHolder { - virtual void mov(RefHolder &h) = 0; - virtual void reset() = 0; - virtual ~OptHolder() = default; - using Ptr = std::shared_ptr; - }; - template struct Holder final: OptHolder { - std::reference_wrapper > m_opt_ref; - - explicit Holder(cv::optional& opt) : m_opt_ref(std::ref(opt)) { - } - virtual void mov(RefHolder &h) override { - using U = typename wref_spec::type; - m_opt_ref.get() = cv::util::make_optional(std::move(h.template wref())); - } - virtual void reset() override { - m_opt_ref.get().reset(); - } - }; - template - explicit OptRef(cv::optional& t) : m_opt{new Holder(t)} {} - void mov(RefHolder &h) { m_opt->mov(h); } - void reset() { m_opt->reset();} -private: - typename OptHolder::Ptr m_opt; -}; -using OptionalVectorRef = OptRef; -using OptionalOpaqueRef = OptRef; -} // namespace detail - -// TODO: Keep it in sync with GRunArgP (derive the type automatically?) -using GOptRunArgP = util::variant< - optional*, - optional*, - optional*, - optional*, - cv::detail::OptionalVectorRef, - cv::detail::OptionalOpaqueRef ->; -using GOptRunArgsP = std::vector; - -using GOptRunArg = util::variant< - optional, - optional, - optional, - optional, - optional, - optional ->; -using GOptRunArgs = std::vector; - -namespace detail { - -template inline GOptRunArgP wrap_opt_arg(optional& arg) { - // By default, T goes to an OpaqueRef. All other types are specialized - return GOptRunArgP{OptionalOpaqueRef(arg)}; -} - -template inline GOptRunArgP wrap_opt_arg(optional >& arg) { - return GOptRunArgP{OptionalVectorRef(arg)}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &m) { - return GOptRunArgP{&m}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &m) { - return GOptRunArgP{&m}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &f) { - return GOptRunArgP{&f}; -} - -template<> inline GOptRunArgP wrap_opt_arg(optional &s) { - return GOptRunArgP{&s}; -} - -} // namespace detail - -// Now cv::gout() may produce an empty vector (see "dynamic graphs"), so -// there may be a conflict between these two. State here that Opt version -// _must_ have at least one input for this overload -template -inline GOptRunArgsP gout(optional&arg, optional&... args) -{ - return GOptRunArgsP{ detail::wrap_opt_arg(arg), detail::wrap_opt_arg(args)... }; -} - -/** - * \addtogroup gapi_main_classes - * @{ - */ -/** - * @brief Represents a computation (graph) compiled for streaming. - * - * This class represents a product of graph compilation (calling - * cv::GComputation::compileStreaming()). Objects of this class - * actually do stream processing, and the whole pipeline execution - * complexity is incapsulated into objects of this class. Execution - * model has two levels: at the very top, the execution of a - * heterogeneous graph is aggressively pipelined; at the very bottom - * the execution of every internal block is determined by its - * associated backend. Backends are selected based on kernel packages - * passed via compilation arguments ( see @ref gapi_compile_args, - * GNetworkPackage, GKernelPackage for details). - * - * GStreamingCompiled objects have a "player" semantics -- there are - * methods like start() and stop(). GStreamingCompiled has a full - * control over a videostream and so is stateful. You need to specify the - * input stream data using setSource() and then call start() to - * actually start processing. After that, use pull() or try_pull() to - * obtain next processed data frame from the graph in a blocking or - * non-blocking way, respectively. - * - * Currently a single GStreamingCompiled can process only one video - * streat at time. Produce multiple GStreamingCompiled objects to run the - * same graph on multiple video streams. - * - * @sa GCompiled - */ -class GAPI_EXPORTS_W_SIMPLE GStreamingCompiled -{ -public: - class GAPI_EXPORTS Priv; - GAPI_WRAP GStreamingCompiled(); - - // FIXME: More overloads? - /** - * @brief Specify the input data to GStreamingCompiled for - * processing, a generic version. - * - * Use gin() to create an input parameter vector. - * - * Input vectors must have the same number of elements as defined - * in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::Mat needs to be passed where cv::GMat has been - * declared as input, and so on). Run-time exception is generated - * on type mismatch. - * - * In contrast with regular GCompiled, user can also pass an - * object of type GVideoCapture for a GMat parameter of the parent - * GComputation. The compiled pipeline will start fetching data - * from that GVideoCapture and feeding it into the - * pipeline. Pipeline stops when a GVideoCapture marks end of the - * stream (or when stop() is called). - * - * Passing a regular Mat for a GMat parameter makes it "infinite" - * source -- pipeline may run forever feeding with this Mat until - * stopped explicitly. - * - * Currently only a single GVideoCapture is supported as input. If - * the parent GComputation is declared with multiple input GMat's, - * one of those can be specified as GVideoCapture but all others - * must be regular Mat objects. - * - * Throws if pipeline is already running. Use stop() and then - * setSource() to run the graph on a new video stream. - * - * @note This method is not thread-safe (with respect to the user - * side) at the moment. Protect the access if - * start()/stop()/setSource() may be called on the same object in - * multiple threads in your application. - * - * @param ins vector of inputs to process. - * @sa gin - */ - void setSource(GRunArgs &&ins); - - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP void setSource(const cv::detail::ExtractArgsCallback& callback); - - /** - * @brief Specify an input video stream for a single-input - * computation pipeline. - * - * Throws if pipeline is already running. Use stop() and then - * setSource() to run the graph on a new video stream. - * - * @overload - * @param s a shared pointer to IStreamSource representing the - * input video stream. - */ - void setSource(const gapi::wip::IStreamSource::Ptr& s); - - /** - * @brief Constructs and specifies an input video stream for a - * single-input computation pipeline with the given parameters. - * - * Throws if pipeline is already running. Use stop() and then - * setSource() to run the graph on a new video stream. - * - * @overload - * @param args arguments used to construct and initialize a stream - * source. - */ - template - void setSource(Args&&... args) { - setSource(cv::gapi::wip::make_src(std::forward(args)...)); - } - - /** - * @brief Start the pipeline execution. - * - * Use pull()/try_pull() to obtain data. Throws an exception if - * a video source was not specified. - * - * setSource() must be called first, even if the pipeline has been - * working already and then stopped (explicitly via stop() or due - * stream completion) - * - * @note This method is not thread-safe (with respect to the user - * side) at the moment. Protect the access if - * start()/stop()/setSource() may be called on the same object in - * multiple threads in your application. - */ - GAPI_WRAP void start(); - - /** - * @brief Get the next processed frame from the pipeline. - * - * Use gout() to create an output parameter vector. - * - * Output vectors must have the same number of elements as defined - * in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::Mat needs to be passed where cv::GMat has been - * declared as output, and so on). Run-time exception is generated - * on type mismatch. - * - * This method writes new data into objects passed via output - * vector. If there is no data ready yet, this method blocks. Use - * try_pull() if you need a non-blocking version. - * - * @param outs vector of output parameters to obtain. - * @return true if next result has been obtained, - * false marks end of the stream. - */ - bool pull(cv::GRunArgsP &&outs); - - // NB: Used from python - /// @private -- Exclude this function from OpenCV documentation - GAPI_WRAP std::tuple> pull(); - - /** - * @brief Get some next available data from the pipeline. - * - * This method takes a vector of cv::optional object. An object is - * assigned to some value if this value is available (ready) at - * the time of the call, and resets the object to empty() if it is - * not. - * - * This is a blocking method which guarantees that some data has - * been written to the output vector on return. - * - * Using this method only makes sense if the graph has - * desynchronized parts (see cv::gapi::desync). If there is no - * desynchronized parts in the graph, the behavior of this - * method is identical to the regular pull() (all data objects are - * produced synchronously in the output vector). - * - * Use gout() to create an output parameter vector. - * - * Output vectors must have the same number of elements as defined - * in the cv::GComputation protocol (at the moment of its - * construction). Shapes of elements also must conform to protocol - * (e.g. cv::optional needs to be passed where cv::GMat - * has been declared as output, and so on). Run-time exception is - * generated on type mismatch. - * - * This method writes new data into objects passed via output - * vector. If there is no data ready yet, this method blocks. Use - * try_pull() if you need a non-blocking version. - * - * @param outs vector of output parameters to obtain. - * @return true if next result has been obtained, - * false marks end of the stream. - * - * @sa cv::gapi::desync - */ - bool pull(cv::GOptRunArgsP &&outs); - - /** - * @brief Try to get the next processed frame from the pipeline. - * - * Use gout() to create an output parameter vector. - * - * This method writes new data into objects passed via output - * vector. If there is no data ready yet, the output vector - * remains unchanged and false is returned. - * - * @return true if data has been obtained, and false if it was - * not. Note: false here doesn't mark the end of the stream. - */ - bool try_pull(cv::GRunArgsP &&outs); - - /** - * @brief Stop (abort) processing the pipeline. - * - * Note - it is not pause but a complete stop. Calling start() - * will cause G-API to start processing the stream from the early beginning. - * - * Throws if the pipeline is not running. - */ - GAPI_WRAP void stop(); - - /** - * @brief Test if the pipeline is running. - * - * @note This method is not thread-safe (with respect to the user - * side) at the moment. Protect the access if - * start()/stop()/setSource() may be called on the same object in - * multiple threads in your application. - * - * @return true if the current stream is not over yet. - */ - GAPI_WRAP bool running() const; - - /// @private - Priv& priv(); - - /** - * @brief Check if compiled object is valid (non-empty) - * - * @return true if the object is runnable (valid), false otherwise - */ - explicit operator bool () const; - - /** - * @brief Vector of metadata this graph was compiled for. - * - * @return Unless _reshape_ is not supported, return value is the - * same vector which was passed to cv::GComputation::compile() to - * produce this compiled object. Otherwise, it is the latest - * metadata vector passed to reshape() (if that call was - * successful). - */ - const GMetaArgs& metas() const; // Meta passed to compile() - - /** - * @brief Vector of metadata descriptions of graph outputs - * - * @return vector with formats/resolutions of graph's output - * objects, auto-inferred from input metadata vector by - * operations which form this computation. - * - * @note GCompiled objects produced from the same - * cv::GComputiation graph with different input metas may return - * different values in this vector. - */ - const GMetaArgs& outMetas() const; - -protected: - /// @private - std::shared_ptr m_priv; -}; - -namespace gapi { - -/** - * @brief This namespace contains G-API functions, structures, and - * symbols related to the Streaming execution mode. - * - * Some of the operations defined in this namespace (e.g. size(), - * BGR(), etc.) can be used in the traditional execution mode too. - */ -namespace streaming { -/** - * @brief Specify queue capacity for streaming execution. - * - * In the streaming mode the pipeline steps are connected with queues - * and this compile argument controls every queue's size. - */ -struct GAPI_EXPORTS_W_SIMPLE queue_capacity -{ - GAPI_WRAP - explicit queue_capacity(size_t cap = 1) : capacity(cap) { } - GAPI_PROP_RW - size_t capacity; -}; -} // namespace streaming -} // namespace gapi - -namespace detail -{ -template<> struct CompileArgTag -{ - static const char* tag() { return "gapi.queue_capacity"; } -}; -} - -/** @} gapi_main_classes */ - -} - -#endif // OPENCV_GAPI_GSTREAMING_COMPILED_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GSTREAMING_COMPILED_HPP +#define OPENCV_GAPI_GSTREAMING_COMPILED_HPP + +#include +#include + +#include +#include +#include +#include +#include + +namespace cv { + +template using optional = cv::util::optional; + +namespace detail { +template struct wref_spec { + using type = T; +}; +template struct wref_spec > { + using type = T; +}; + +template +struct OptRef { + struct OptHolder { + virtual void mov(RefHolder &h) = 0; + virtual void reset() = 0; + virtual ~OptHolder() = default; + using Ptr = std::shared_ptr; + }; + template struct Holder final: OptHolder { + std::reference_wrapper > m_opt_ref; + + explicit Holder(cv::optional& opt) : m_opt_ref(std::ref(opt)) { + } + virtual void mov(RefHolder &h) override { + using U = typename wref_spec::type; + m_opt_ref.get() = cv::util::make_optional(std::move(h.template wref())); + } + virtual void reset() override { + m_opt_ref.get().reset(); + } + }; + template + explicit OptRef(cv::optional& t) : m_opt{new Holder(t)} {} + void mov(RefHolder &h) { m_opt->mov(h); } + void reset() { m_opt->reset();} +private: + typename OptHolder::Ptr m_opt; +}; +using OptionalVectorRef = OptRef; +using OptionalOpaqueRef = OptRef; +} // namespace detail + +// TODO: Keep it in sync with GRunArgP (derive the type automatically?) +using GOptRunArgP = util::variant< + optional*, + optional*, + optional*, + optional*, + cv::detail::OptionalVectorRef, + cv::detail::OptionalOpaqueRef +>; +using GOptRunArgsP = std::vector; + +using GOptRunArg = util::variant< + optional, + optional, + optional, + optional, + optional, + optional +>; +using GOptRunArgs = std::vector; + +namespace detail { + +template inline GOptRunArgP wrap_opt_arg(optional& arg) { + // By default, T goes to an OpaqueRef. All other types are specialized + return GOptRunArgP{OptionalOpaqueRef(arg)}; +} + +template inline GOptRunArgP wrap_opt_arg(optional >& arg) { + return GOptRunArgP{OptionalVectorRef(arg)}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &m) { + return GOptRunArgP{&m}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &m) { + return GOptRunArgP{&m}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &f) { + return GOptRunArgP{&f}; +} + +template<> inline GOptRunArgP wrap_opt_arg(optional &s) { + return GOptRunArgP{&s}; +} + +} // namespace detail + +// Now cv::gout() may produce an empty vector (see "dynamic graphs"), so +// there may be a conflict between these two. State here that Opt version +// _must_ have at least one input for this overload +template +inline GOptRunArgsP gout(optional&arg, optional&... args) +{ + return GOptRunArgsP{ detail::wrap_opt_arg(arg), detail::wrap_opt_arg(args)... }; +} + +/** + * \addtogroup gapi_main_classes + * @{ + */ +/** + * @brief Represents a computation (graph) compiled for streaming. + * + * This class represents a product of graph compilation (calling + * cv::GComputation::compileStreaming()). Objects of this class + * actually do stream processing, and the whole pipeline execution + * complexity is incapsulated into objects of this class. Execution + * model has two levels: at the very top, the execution of a + * heterogeneous graph is aggressively pipelined; at the very bottom + * the execution of every internal block is determined by its + * associated backend. Backends are selected based on kernel packages + * passed via compilation arguments ( see @ref gapi_compile_args, + * GNetworkPackage, GKernelPackage for details). + * + * GStreamingCompiled objects have a "player" semantics -- there are + * methods like start() and stop(). GStreamingCompiled has a full + * control over a videostream and so is stateful. You need to specify the + * input stream data using setSource() and then call start() to + * actually start processing. After that, use pull() or try_pull() to + * obtain next processed data frame from the graph in a blocking or + * non-blocking way, respectively. + * + * Currently a single GStreamingCompiled can process only one video + * streat at time. Produce multiple GStreamingCompiled objects to run the + * same graph on multiple video streams. + * + * @sa GCompiled + */ +class GAPI_EXPORTS_W_SIMPLE GStreamingCompiled +{ +public: + class GAPI_EXPORTS Priv; + GAPI_WRAP GStreamingCompiled(); + + // FIXME: More overloads? + /** + * @brief Specify the input data to GStreamingCompiled for + * processing, a generic version. + * + * Use gin() to create an input parameter vector. + * + * Input vectors must have the same number of elements as defined + * in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::Mat needs to be passed where cv::GMat has been + * declared as input, and so on). Run-time exception is generated + * on type mismatch. + * + * In contrast with regular GCompiled, user can also pass an + * object of type GVideoCapture for a GMat parameter of the parent + * GComputation. The compiled pipeline will start fetching data + * from that GVideoCapture and feeding it into the + * pipeline. Pipeline stops when a GVideoCapture marks end of the + * stream (or when stop() is called). + * + * Passing a regular Mat for a GMat parameter makes it "infinite" + * source -- pipeline may run forever feeding with this Mat until + * stopped explicitly. + * + * Currently only a single GVideoCapture is supported as input. If + * the parent GComputation is declared with multiple input GMat's, + * one of those can be specified as GVideoCapture but all others + * must be regular Mat objects. + * + * Throws if pipeline is already running. Use stop() and then + * setSource() to run the graph on a new video stream. + * + * @note This method is not thread-safe (with respect to the user + * side) at the moment. Protect the access if + * start()/stop()/setSource() may be called on the same object in + * multiple threads in your application. + * + * @param ins vector of inputs to process. + * @sa gin + */ + void setSource(GRunArgs &&ins); + + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP void setSource(const cv::detail::ExtractArgsCallback& callback); + + /** + * @brief Specify an input video stream for a single-input + * computation pipeline. + * + * Throws if pipeline is already running. Use stop() and then + * setSource() to run the graph on a new video stream. + * + * @overload + * @param s a shared pointer to IStreamSource representing the + * input video stream. + */ + void setSource(const gapi::wip::IStreamSource::Ptr& s); + + /** + * @brief Constructs and specifies an input video stream for a + * single-input computation pipeline with the given parameters. + * + * Throws if pipeline is already running. Use stop() and then + * setSource() to run the graph on a new video stream. + * + * @overload + * @param args arguments used to construct and initialize a stream + * source. + */ + template + void setSource(Args&&... args) { + setSource(cv::gapi::wip::make_src(std::forward(args)...)); + } + + /** + * @brief Start the pipeline execution. + * + * Use pull()/try_pull() to obtain data. Throws an exception if + * a video source was not specified. + * + * setSource() must be called first, even if the pipeline has been + * working already and then stopped (explicitly via stop() or due + * stream completion) + * + * @note This method is not thread-safe (with respect to the user + * side) at the moment. Protect the access if + * start()/stop()/setSource() may be called on the same object in + * multiple threads in your application. + */ + GAPI_WRAP void start(); + + /** + * @brief Get the next processed frame from the pipeline. + * + * Use gout() to create an output parameter vector. + * + * Output vectors must have the same number of elements as defined + * in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::Mat needs to be passed where cv::GMat has been + * declared as output, and so on). Run-time exception is generated + * on type mismatch. + * + * This method writes new data into objects passed via output + * vector. If there is no data ready yet, this method blocks. Use + * try_pull() if you need a non-blocking version. + * + * @param outs vector of output parameters to obtain. + * @return true if next result has been obtained, + * false marks end of the stream. + */ + bool pull(cv::GRunArgsP &&outs); + + // NB: Used from python + /// @private -- Exclude this function from OpenCV documentation + GAPI_WRAP std::tuple> pull(); + + /** + * @brief Get some next available data from the pipeline. + * + * This method takes a vector of cv::optional object. An object is + * assigned to some value if this value is available (ready) at + * the time of the call, and resets the object to empty() if it is + * not. + * + * This is a blocking method which guarantees that some data has + * been written to the output vector on return. + * + * Using this method only makes sense if the graph has + * desynchronized parts (see cv::gapi::desync). If there is no + * desynchronized parts in the graph, the behavior of this + * method is identical to the regular pull() (all data objects are + * produced synchronously in the output vector). + * + * Use gout() to create an output parameter vector. + * + * Output vectors must have the same number of elements as defined + * in the cv::GComputation protocol (at the moment of its + * construction). Shapes of elements also must conform to protocol + * (e.g. cv::optional needs to be passed where cv::GMat + * has been declared as output, and so on). Run-time exception is + * generated on type mismatch. + * + * This method writes new data into objects passed via output + * vector. If there is no data ready yet, this method blocks. Use + * try_pull() if you need a non-blocking version. + * + * @param outs vector of output parameters to obtain. + * @return true if next result has been obtained, + * false marks end of the stream. + * + * @sa cv::gapi::desync + */ + bool pull(cv::GOptRunArgsP &&outs); + + /** + * @brief Try to get the next processed frame from the pipeline. + * + * Use gout() to create an output parameter vector. + * + * This method writes new data into objects passed via output + * vector. If there is no data ready yet, the output vector + * remains unchanged and false is returned. + * + * @return true if data has been obtained, and false if it was + * not. Note: false here doesn't mark the end of the stream. + */ + bool try_pull(cv::GRunArgsP &&outs); + + /** + * @brief Stop (abort) processing the pipeline. + * + * Note - it is not pause but a complete stop. Calling start() + * will cause G-API to start processing the stream from the early beginning. + * + * Throws if the pipeline is not running. + */ + GAPI_WRAP void stop(); + + /** + * @brief Test if the pipeline is running. + * + * @note This method is not thread-safe (with respect to the user + * side) at the moment. Protect the access if + * start()/stop()/setSource() may be called on the same object in + * multiple threads in your application. + * + * @return true if the current stream is not over yet. + */ + GAPI_WRAP bool running() const; + + /// @private + Priv& priv(); + + /** + * @brief Check if compiled object is valid (non-empty) + * + * @return true if the object is runnable (valid), false otherwise + */ + explicit operator bool () const; + + /** + * @brief Vector of metadata this graph was compiled for. + * + * @return Unless _reshape_ is not supported, return value is the + * same vector which was passed to cv::GComputation::compile() to + * produce this compiled object. Otherwise, it is the latest + * metadata vector passed to reshape() (if that call was + * successful). + */ + const GMetaArgs& metas() const; // Meta passed to compile() + + /** + * @brief Vector of metadata descriptions of graph outputs + * + * @return vector with formats/resolutions of graph's output + * objects, auto-inferred from input metadata vector by + * operations which form this computation. + * + * @note GCompiled objects produced from the same + * cv::GComputiation graph with different input metas may return + * different values in this vector. + */ + const GMetaArgs& outMetas() const; + +protected: + /// @private + std::shared_ptr m_priv; +}; + +namespace gapi { + +/** + * @brief This namespace contains G-API functions, structures, and + * symbols related to the Streaming execution mode. + * + * Some of the operations defined in this namespace (e.g. size(), + * BGR(), etc.) can be used in the traditional execution mode too. + */ +namespace streaming { +/** + * @brief Specify queue capacity for streaming execution. + * + * In the streaming mode the pipeline steps are connected with queues + * and this compile argument controls every queue's size. + */ +struct GAPI_EXPORTS_W_SIMPLE queue_capacity +{ + GAPI_WRAP + explicit queue_capacity(size_t cap = 1) : capacity(cap) { } + GAPI_PROP_RW + size_t capacity; +}; +} // namespace streaming +} // namespace gapi + +namespace detail +{ +template<> struct CompileArgTag +{ + static const char* tag() { return "gapi.queue_capacity"; } +}; +} + +/** @} gapi_main_classes */ + +} + +#endif // OPENCV_GAPI_GSTREAMING_COMPILED_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp index ae904d8164..ce88c894d7 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gtransform.hpp @@ -1,103 +1,103 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_GTRANSFORM_HPP -#define OPENCV_GAPI_GTRANSFORM_HPP - -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace cv -{ - -struct GAPI_EXPORTS GTransform -{ - // FIXME: consider another simplified - // class instead of GComputation - using F = std::function; - - std::string description; - F pattern; - F substitute; - - GTransform(const std::string& d, const F &p, const F &s) : description(d), pattern(p), substitute(s) {} -}; - -namespace detail -{ - -template -struct TransHelper; - -template -struct TransHelper, Out> -{ - template - static GComputation invoke(Callable f, Seq, Seq) - { - const std::tuple ins; - const auto r = tuple_wrap_helper::get(f(std::get(ins)...)); - return GComputation(cv::GIn(std::get(ins)...), - cv::GOut(std::get(r)...)); - } - - static GComputation get_pattern() - { - return invoke(K::pattern, typename MkSeq::type(), - typename MkSeq::type>::value>::type()); - } - static GComputation get_substitute() - { - return invoke(K::substitute, typename MkSeq::type(), - typename MkSeq::type>::value>::type()); - } -}; -} // namespace detail - -template -class GTransformImpl; - -template -class GTransformImpl> : public cv::detail::TransHelper, R>, - public cv::detail::TransformTag -{ -public: - // FIXME: currently there is no check that transformations' signatures are unique - // and won't be any intersection in graph compilation stage - using API = K; - - static GTransform transformation() - { - return GTransform(K::descr(), &K::get_pattern, &K::get_substitute); - } -}; -} // namespace cv - -#define G_DESCR_HELPER_CLASS(Class) Class##DescrHelper - -#define G_DESCR_HELPER_BODY(Class, Descr) \ - namespace detail \ - { \ - struct G_DESCR_HELPER_CLASS(Class) \ - { \ - static constexpr const char *descr() { return Descr; } \ - }; \ - } - -#define GAPI_TRANSFORM(Class, API, Descr) \ - G_DESCR_HELPER_BODY(Class, Descr) \ - struct Class final : public cv::GTransformImpl, \ - public detail::G_DESCR_HELPER_CLASS(Class) - -#endif // OPENCV_GAPI_GTRANSFORM_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_GTRANSFORM_HPP +#define OPENCV_GAPI_GTRANSFORM_HPP + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace cv +{ + +struct GAPI_EXPORTS GTransform +{ + // FIXME: consider another simplified + // class instead of GComputation + using F = std::function; + + std::string description; + F pattern; + F substitute; + + GTransform(const std::string& d, const F &p, const F &s) : description(d), pattern(p), substitute(s) {} +}; + +namespace detail +{ + +template +struct TransHelper; + +template +struct TransHelper, Out> +{ + template + static GComputation invoke(Callable f, Seq, Seq) + { + const std::tuple ins; + const auto r = tuple_wrap_helper::get(f(std::get(ins)...)); + return GComputation(cv::GIn(std::get(ins)...), + cv::GOut(std::get(r)...)); + } + + static GComputation get_pattern() + { + return invoke(K::pattern, typename MkSeq::type(), + typename MkSeq::type>::value>::type()); + } + static GComputation get_substitute() + { + return invoke(K::substitute, typename MkSeq::type(), + typename MkSeq::type>::value>::type()); + } +}; +} // namespace detail + +template +class GTransformImpl; + +template +class GTransformImpl> : public cv::detail::TransHelper, R>, + public cv::detail::TransformTag +{ +public: + // FIXME: currently there is no check that transformations' signatures are unique + // and won't be any intersection in graph compilation stage + using API = K; + + static GTransform transformation() + { + return GTransform(K::descr(), &K::get_pattern, &K::get_substitute); + } +}; +} // namespace cv + +#define G_DESCR_HELPER_CLASS(Class) Class##DescrHelper + +#define G_DESCR_HELPER_BODY(Class, Descr) \ + namespace detail \ + { \ + struct G_DESCR_HELPER_CLASS(Class) \ + { \ + static constexpr const char *descr() { return Descr; } \ + }; \ + } + +#define GAPI_TRANSFORM(Class, API, Descr) \ + G_DESCR_HELPER_BODY(Class, Descr) \ + struct Class final : public cv::GTransformImpl, \ + public detail::G_DESCR_HELPER_CLASS(Class) + +#endif // OPENCV_GAPI_GTRANSFORM_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp index cbf5f8f417..c42d64a761 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gtype_traits.hpp @@ -1,242 +1,242 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GTYPE_TRAITS_HPP -#define OPENCV_GAPI_GTYPE_TRAITS_HPP - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace cv -{ -namespace detail -{ - template - struct contains_shape_field : std::false_type {}; - - template - struct contains_shape_field> : - std::is_same::type, GShape> - {}; - - template - struct has_gshape : contains_shape_field {}; - - // FIXME: These traits and enum and possible numerous switch(kind) - // block may be replaced with a special Handler object or with - // a double dispatch - enum class ArgKind: int - { - OPAQUE_VAL, // Unknown, generic, opaque-to-GAPI data type - STATIC - // Note: OPAQUE is sometimes defined in Win sys headers -#if !defined(OPAQUE) && !defined(CV_DOXYGEN) - OPAQUE = OPAQUE_VAL, // deprecated value used for compatibility, use OPAQUE_VAL instead -#endif - GOBJREF, // reference to object - GMAT, // a cv::GMat - GMATP, // a cv::GMatP - GFRAME, // a cv::GFrame - GSCALAR, // a cv::GScalar - GARRAY, // a cv::GArrayU (note - exactly GArrayU, not GArray!) - GOPAQUE, // a cv::GOpaqueU (note - exactly GOpaqueU, not GOpaque!) - }; - - // Describe G-API types (G-types) with traits. Mostly used by - // cv::GArg to store meta information about types passed into - // operation arguments. Please note that cv::GComputation is - // defined on GProtoArgs, not GArgs! - template struct GTypeTraits; - template struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::OPAQUE_VAL; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GMAT; - static constexpr const GShape shape = GShape::GMAT; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GMATP; - static constexpr const GShape shape = GShape::GMAT; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GFRAME; - static constexpr const GShape shape = GShape::GFRAME; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template<> struct GTypeTraits - { - static constexpr const ArgKind kind = ArgKind::GSCALAR; - static constexpr const GShape shape = GShape::GSCALAR; - static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; - }; - template struct GTypeTraits > - { - static constexpr const ArgKind kind = ArgKind::GARRAY; - static constexpr const GShape shape = GShape::GARRAY; - static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; - using host_type = std::vector; - using strip_type = cv::detail::VectorRef; - static cv::detail::GArrayU wrap_value(const cv::GArray &t) { return t.strip();} - static cv::detail::VectorRef wrap_in (const std::vector &t) { return detail::VectorRef(t); } - static cv::detail::VectorRef wrap_out ( std::vector &t) { return detail::VectorRef(t); } - }; - template struct GTypeTraits > - { - static constexpr const ArgKind kind = ArgKind::GOPAQUE; - static constexpr const GShape shape = GShape::GOPAQUE; - static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; - using host_type = T; - using strip_type = cv::detail::OpaqueRef; - static cv::detail::GOpaqueU wrap_value(const cv::GOpaque &t) { return t.strip();} - static cv::detail::OpaqueRef wrap_in (const T &t) { return detail::OpaqueRef(t); } - static cv::detail::OpaqueRef wrap_out ( T &t) { return detail::OpaqueRef(t); } - }; - - // Tests if Trait for type T requires extra marshalling ("custom wrap") or not. - // If Traits has wrap_value() defined, it does. - template struct has_custom_wrap - { - template class check; - template static std::true_type test(check::wrap_value)> *); - template static std::false_type test(...); - using type = decltype(test(nullptr)); - static const constexpr bool value = std::is_same(nullptr))>::value; - }; - - // Resolve a Host type back to its associated G-Type. - // FIXME: Probably it can be avoided - // FIXME: GMatP is not present here. - // (Actually these traits is used only to check - // if associated G-type has custom wrap functions - // and GMat behavior is correct for GMatP) - template struct GTypeOf; -#if !defined(GAPI_STANDALONE) - template<> struct GTypeOf { using type = cv::GMat; }; -#endif // !defined(GAPI_STANDALONE) - template<> struct GTypeOf { using type = cv::GMat; }; - template<> struct GTypeOf { using type = cv::GMat; }; - template<> struct GTypeOf { using type = cv::GScalar; }; - template struct GTypeOf > { using type = cv::GArray; }; - template struct GTypeOf { using type = cv::GOpaque;}; - template<> struct GTypeOf { using type = cv::GFrame; }; - - // FIXME: This is not quite correct since IStreamSource may - // produce not only Mat but also MediaFrame, Scalar and vector - // data. TODO: Extend the type dispatching on these types too. - template<> struct GTypeOf { using type = cv::GMat;}; - template using g_type_of_t = typename GTypeOf::type; - - // Marshalling helper for G-types and its Host types. Helps G-API - // to store G types in internal generic containers for further - // processing. Implements the following callbacks: - // - // * wrap() - converts user-facing G-type into an internal one - // for internal storage. - // Used when G-API operation is instantiated (G::on(), - // etc) during expressing a pipeline. Mostly returns input - // value "as is" except the case when G-type is a template. For - // template G-classes, calls custom wrap() from Traits. - // The value returned by wrap() is then wrapped into GArg() and - // stored in G-API metadata. - // - // Example: - // - cv::GMat arguments are passed as-is. - // - integers, pointers, STL containers, user types are passed as-is. - // - cv::GArray is converted to cv::GArrayU. - // - // * wrap_in() / wrap_out() - convert Host type associated with - // G-type to internal representation type. - // - // - For "simple" (non-template) G-types, returns value as-is. - // Example: cv::GMat has host type cv::Mat, when user passes a - // cv::Mat, system stores it internally as cv::Mat. - // - // - For "complex" (template) G-types, utilizes custom - // wrap_in()/wrap_out() as described in Traits. - // Example: cv::GArray has host type std::vector, when - // user passes a std::vector, system stores it - // internally as VectorRef (with stripped away). - template struct WrapValue - { - static auto wrap(const T& t) -> - typename std::remove_reference::type - { - return static_cast::type>(t); - } - - template static U wrap_in (const U &u) { return u; } - template static U* wrap_out(U &u) { return &u; } - }; - template struct WrapValue::value>::type> - { - static auto wrap(const T& t) -> decltype(GTypeTraits::wrap_value(t)) - { - return GTypeTraits::wrap_value(t); - } - template static auto wrap_in (const U &u) -> typename GTypeTraits::strip_type - { - static_assert(!(cv::detail::has_gshape>::value - || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), - "gin/gout must not be used with G* classes or cv::gapi::own::*"); - return GTypeTraits::wrap_in(u); - } - template static auto wrap_out(U &u) -> typename GTypeTraits::strip_type - { - static_assert(!(cv::detail::has_gshape>::value - || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), - "gin/gout must not be used with G* classes or cv::gapi::own::*"); - return GTypeTraits::wrap_out(u); - } - }; - - template using wrap_gapi_helper = WrapValue::type>; - template using wrap_host_helper = WrapValue >::type>; - -// Union type for various user-defined type constructors (GArray, -// GOpaque, etc) -// -// TODO: Replace construct-only API with a more generic one (probably -// with bits of introspection) -// -// Not required for non-user-defined types (GMat, GScalar, etc) -using HostCtor = util::variant - < util::monostate - , detail::ConstructVec - , detail::ConstructOpaque - >; - -template struct GObtainCtor { - static HostCtor get() { return HostCtor{}; } -}; -template struct GObtainCtor > { - static HostCtor get() { return HostCtor{ConstructVec{&GArray::VCtor}}; } -}; -template struct GObtainCtor > { - static HostCtor get() { return HostCtor{ConstructOpaque{&GOpaque::Ctor}}; } -}; -} // namespace detail -} // namespace cv - -#endif // OPENCV_GAPI_GTYPE_TRAITS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GTYPE_TRAITS_HPP +#define OPENCV_GAPI_GTYPE_TRAITS_HPP + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace cv +{ +namespace detail +{ + template + struct contains_shape_field : std::false_type {}; + + template + struct contains_shape_field> : + std::is_same::type, GShape> + {}; + + template + struct has_gshape : contains_shape_field {}; + + // FIXME: These traits and enum and possible numerous switch(kind) + // block may be replaced with a special Handler object or with + // a double dispatch + enum class ArgKind: int + { + OPAQUE_VAL, // Unknown, generic, opaque-to-GAPI data type - STATIC + // Note: OPAQUE is sometimes defined in Win sys headers +#if !defined(OPAQUE) && !defined(CV_DOXYGEN) + OPAQUE = OPAQUE_VAL, // deprecated value used for compatibility, use OPAQUE_VAL instead +#endif + GOBJREF, // reference to object + GMAT, // a cv::GMat + GMATP, // a cv::GMatP + GFRAME, // a cv::GFrame + GSCALAR, // a cv::GScalar + GARRAY, // a cv::GArrayU (note - exactly GArrayU, not GArray!) + GOPAQUE, // a cv::GOpaqueU (note - exactly GOpaqueU, not GOpaque!) + }; + + // Describe G-API types (G-types) with traits. Mostly used by + // cv::GArg to store meta information about types passed into + // operation arguments. Please note that cv::GComputation is + // defined on GProtoArgs, not GArgs! + template struct GTypeTraits; + template struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::OPAQUE_VAL; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GMAT; + static constexpr const GShape shape = GShape::GMAT; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GMATP; + static constexpr const GShape shape = GShape::GMAT; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GFRAME; + static constexpr const GShape shape = GShape::GFRAME; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template<> struct GTypeTraits + { + static constexpr const ArgKind kind = ArgKind::GSCALAR; + static constexpr const GShape shape = GShape::GSCALAR; + static constexpr const OpaqueKind op_kind = OpaqueKind::CV_UNKNOWN; + }; + template struct GTypeTraits > + { + static constexpr const ArgKind kind = ArgKind::GARRAY; + static constexpr const GShape shape = GShape::GARRAY; + static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; + using host_type = std::vector; + using strip_type = cv::detail::VectorRef; + static cv::detail::GArrayU wrap_value(const cv::GArray &t) { return t.strip();} + static cv::detail::VectorRef wrap_in (const std::vector &t) { return detail::VectorRef(t); } + static cv::detail::VectorRef wrap_out ( std::vector &t) { return detail::VectorRef(t); } + }; + template struct GTypeTraits > + { + static constexpr const ArgKind kind = ArgKind::GOPAQUE; + static constexpr const GShape shape = GShape::GOPAQUE; + static constexpr const OpaqueKind op_kind = GOpaqueTraits::kind; + using host_type = T; + using strip_type = cv::detail::OpaqueRef; + static cv::detail::GOpaqueU wrap_value(const cv::GOpaque &t) { return t.strip();} + static cv::detail::OpaqueRef wrap_in (const T &t) { return detail::OpaqueRef(t); } + static cv::detail::OpaqueRef wrap_out ( T &t) { return detail::OpaqueRef(t); } + }; + + // Tests if Trait for type T requires extra marshalling ("custom wrap") or not. + // If Traits has wrap_value() defined, it does. + template struct has_custom_wrap + { + template class check; + template static std::true_type test(check::wrap_value)> *); + template static std::false_type test(...); + using type = decltype(test(nullptr)); + static const constexpr bool value = std::is_same(nullptr))>::value; + }; + + // Resolve a Host type back to its associated G-Type. + // FIXME: Probably it can be avoided + // FIXME: GMatP is not present here. + // (Actually these traits is used only to check + // if associated G-type has custom wrap functions + // and GMat behavior is correct for GMatP) + template struct GTypeOf; +#if !defined(GAPI_STANDALONE) + template<> struct GTypeOf { using type = cv::GMat; }; +#endif // !defined(GAPI_STANDALONE) + template<> struct GTypeOf { using type = cv::GMat; }; + template<> struct GTypeOf { using type = cv::GMat; }; + template<> struct GTypeOf { using type = cv::GScalar; }; + template struct GTypeOf > { using type = cv::GArray; }; + template struct GTypeOf { using type = cv::GOpaque;}; + template<> struct GTypeOf { using type = cv::GFrame; }; + + // FIXME: This is not quite correct since IStreamSource may + // produce not only Mat but also MediaFrame, Scalar and vector + // data. TODO: Extend the type dispatching on these types too. + template<> struct GTypeOf { using type = cv::GMat;}; + template using g_type_of_t = typename GTypeOf::type; + + // Marshalling helper for G-types and its Host types. Helps G-API + // to store G types in internal generic containers for further + // processing. Implements the following callbacks: + // + // * wrap() - converts user-facing G-type into an internal one + // for internal storage. + // Used when G-API operation is instantiated (G::on(), + // etc) during expressing a pipeline. Mostly returns input + // value "as is" except the case when G-type is a template. For + // template G-classes, calls custom wrap() from Traits. + // The value returned by wrap() is then wrapped into GArg() and + // stored in G-API metadata. + // + // Example: + // - cv::GMat arguments are passed as-is. + // - integers, pointers, STL containers, user types are passed as-is. + // - cv::GArray is converted to cv::GArrayU. + // + // * wrap_in() / wrap_out() - convert Host type associated with + // G-type to internal representation type. + // + // - For "simple" (non-template) G-types, returns value as-is. + // Example: cv::GMat has host type cv::Mat, when user passes a + // cv::Mat, system stores it internally as cv::Mat. + // + // - For "complex" (template) G-types, utilizes custom + // wrap_in()/wrap_out() as described in Traits. + // Example: cv::GArray has host type std::vector, when + // user passes a std::vector, system stores it + // internally as VectorRef (with stripped away). + template struct WrapValue + { + static auto wrap(const T& t) -> + typename std::remove_reference::type + { + return static_cast::type>(t); + } + + template static U wrap_in (const U &u) { return u; } + template static U* wrap_out(U &u) { return &u; } + }; + template struct WrapValue::value>::type> + { + static auto wrap(const T& t) -> decltype(GTypeTraits::wrap_value(t)) + { + return GTypeTraits::wrap_value(t); + } + template static auto wrap_in (const U &u) -> typename GTypeTraits::strip_type + { + static_assert(!(cv::detail::has_gshape>::value + || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), + "gin/gout must not be used with G* classes or cv::gapi::own::*"); + return GTypeTraits::wrap_in(u); + } + template static auto wrap_out(U &u) -> typename GTypeTraits::strip_type + { + static_assert(!(cv::detail::has_gshape>::value + || cv::detail::contains::type, GAPI_OWN_TYPES_LIST>::value), + "gin/gout must not be used with G* classes or cv::gapi::own::*"); + return GTypeTraits::wrap_out(u); + } + }; + + template using wrap_gapi_helper = WrapValue::type>; + template using wrap_host_helper = WrapValue >::type>; + +// Union type for various user-defined type constructors (GArray, +// GOpaque, etc) +// +// TODO: Replace construct-only API with a more generic one (probably +// with bits of introspection) +// +// Not required for non-user-defined types (GMat, GScalar, etc) +using HostCtor = util::variant + < util::monostate + , detail::ConstructVec + , detail::ConstructOpaque + >; + +template struct GObtainCtor { + static HostCtor get() { return HostCtor{}; } +}; +template struct GObtainCtor > { + static HostCtor get() { return HostCtor{ConstructVec{&GArray::VCtor}}; } +}; +template struct GObtainCtor > { + static HostCtor get() { return HostCtor{ConstructOpaque{&GOpaque::Ctor}}; } +}; +} // namespace detail +} // namespace cv + +#endif // OPENCV_GAPI_GTYPE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp index 0bd1cdf7a9..2acc2f7ffb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/gtyped.hpp @@ -1,246 +1,246 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GTYPED_HPP -#define OPENCV_GAPI_GTYPED_HPP -#if !defined(GAPI_STANDALONE) - -#include - -#include -#include -#include -#include - -namespace cv { - -namespace detail -{ - // FIXME: How to prevent coolhackers from extending it by their own types? - // FIXME: ...Should we care? - template struct ProtoToParam; - template<> struct ProtoToParam { using type = cv::Mat; }; - template<> struct ProtoToParam { using type = cv::Scalar; }; - template struct ProtoToParam > { using type = std::vector; }; - template<> struct ProtoToParam> { using type = std::vector; }; - template struct ProtoToParam > { using type = U; }; - template using ProtoToParamT = typename ProtoToParam::type; - - template struct ProtoToMeta; - template<> struct ProtoToMeta { using type = cv::GMatDesc; }; - template<> struct ProtoToMeta { using type = cv::GScalarDesc; }; - template struct ProtoToMeta > { using type = cv::GArrayDesc; }; - template struct ProtoToMeta > { using type = cv::GOpaqueDesc; }; - template using ProtoToMetaT = typename ProtoToMeta::type; - - //workaround for MSVC 19.0 bug - template - auto make_default()->decltype(T{}) {return {};} -} // detail - -/** - * @brief This class is a typed wrapper over a regular GComputation. - * - * `std::function<>`-like template parameter specifies the graph - * signature so methods so the object's constructor, methods like - * `apply()` and the derived `GCompiledT::operator()` also become - * typed. - * - * There is no need to use cv::gin() or cv::gout() modifiers with - * objects of this class. Instead, all input arguments are followed - * by all output arguments in the order from the template argument - * signature. - * - * Refer to the following example. Regular (untyped) code is written this way: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Untyped_Example - * - * Here: - * - * - cv::GComputation object is created with a lambda constructor - * where it is defined as a two-input, one-output graph. - * - * - Its method `apply()` in fact takes arbitrary number of arguments - * (as vectors) so user can pass wrong number of inputs/outputs - * here. C++ compiler wouldn't notice that since the cv::GComputation - * API is polymorphic, and only a run-time error will be generated. - * - * Now the same code written with typed API: - * - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Typed_Example - * - * The key difference is: - * - * - Now the constructor lambda *must take* parameters and *must - * return* values as defined in the `GComputationT<>` signature. - * - Its method `apply()` does not require any extra specifiers to - * separate input arguments from the output ones - * - A `GCompiledT` (compilation product) takes input/output - * arguments with no extra specifiers as well. - */ -template class GComputationT; - -// Single return value implementation -template class GComputationT -{ -public: - typedef std::function Gen; - - class GCompiledT - { - private: - friend class GComputationT; - - cv::GCompiled m_comp; - - explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} - - public: - GCompiledT() {} - - void operator()(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT &outArg) - { - m_comp(cv::gin(inArgs...), cv::gout(outArg)); - } - - explicit operator bool() const - { - return static_cast(m_comp); - } - }; - -private: - typedef std::pair Captured; - - Captured capture(const Gen& g, Args... args) - { - return Captured(g(args...), cv::GIn(args...)); - } - - Captured m_capture; - cv::GComputation m_comp; - -public: - GComputationT(const Gen &generator) - : m_capture(capture(generator, detail::make_default()...)) - , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), - cv::GOut(m_capture.first)) - { - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT &outArg, - GCompileArgs &&args) - { - m_comp.apply(cv::gin(inArgs...), cv::gout(outArg), std::move(args)); - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT &outArg) - { - apply(inArgs..., outArg, GCompileArgs()); - } - - - GCompiledT compile(detail::ProtoToMetaT... inDescs) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); - } - - GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); - } -}; - -// Multiple (fixed) return value implementation. FIXME: How to avoid copy-paste? -template class GComputationT(Args...)> -{ -public: - typedef std::function(Args...)> Gen; - - class GCompiledT - { - private: - friend class GComputationT(Args...)>; - - cv::GCompiled m_comp; - explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} - - public: - GCompiledT() {} - - void operator()(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT&... outArgs) - { - m_comp(cv::gin(inArgs...), cv::gout(outArgs...)); - } - - explicit operator bool() const - { - return static_cast(m_comp); - } - }; - -private: - typedef std::pair Captured; - - template - Captured capture(GProtoArgs &&args, const std::tuple &rr, detail::Seq) - { - return Captured(cv::GOut(std::get(rr)...).m_args, args); - } - - Captured capture(const Gen& g, Args... args) - { - return capture(cv::GIn(args...).m_args, g(args...), typename detail::MkSeq::type()); - } - - Captured m_capture; - cv::GComputation m_comp; - -public: - GComputationT(const Gen &generator) - : m_capture(capture(generator, detail::make_default()...)) - , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), - cv::GProtoOutputArgs(std::move(m_capture.first))) - { - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT&... outArgs, - GCompileArgs &&args) - { - m_comp.apply(cv::gin(inArgs...), cv::gout(outArgs...), std::move(args)); - } - - void apply(detail::ProtoToParamT... inArgs, - detail::ProtoToParamT&... outArgs) - { - apply(inArgs..., outArgs..., GCompileArgs()); - } - - - GCompiledT compile(detail::ProtoToMetaT... inDescs) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); - } - - GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) - { - GMetaArgs inMetas = { GMetaArg(inDescs)... }; - return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); - } -}; - -} // namespace cv -#endif // !defined(GAPI_STANDALONE) -#endif // OPENCV_GAPI_GTYPED_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GTYPED_HPP +#define OPENCV_GAPI_GTYPED_HPP +#if !defined(GAPI_STANDALONE) + +#include + +#include +#include +#include +#include + +namespace cv { + +namespace detail +{ + // FIXME: How to prevent coolhackers from extending it by their own types? + // FIXME: ...Should we care? + template struct ProtoToParam; + template<> struct ProtoToParam { using type = cv::Mat; }; + template<> struct ProtoToParam { using type = cv::Scalar; }; + template struct ProtoToParam > { using type = std::vector; }; + template<> struct ProtoToParam> { using type = std::vector; }; + template struct ProtoToParam > { using type = U; }; + template using ProtoToParamT = typename ProtoToParam::type; + + template struct ProtoToMeta; + template<> struct ProtoToMeta { using type = cv::GMatDesc; }; + template<> struct ProtoToMeta { using type = cv::GScalarDesc; }; + template struct ProtoToMeta > { using type = cv::GArrayDesc; }; + template struct ProtoToMeta > { using type = cv::GOpaqueDesc; }; + template using ProtoToMetaT = typename ProtoToMeta::type; + + //workaround for MSVC 19.0 bug + template + auto make_default()->decltype(T{}) {return {};} +} // detail + +/** + * @brief This class is a typed wrapper over a regular GComputation. + * + * `std::function<>`-like template parameter specifies the graph + * signature so methods so the object's constructor, methods like + * `apply()` and the derived `GCompiledT::operator()` also become + * typed. + * + * There is no need to use cv::gin() or cv::gout() modifiers with + * objects of this class. Instead, all input arguments are followed + * by all output arguments in the order from the template argument + * signature. + * + * Refer to the following example. Regular (untyped) code is written this way: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Untyped_Example + * + * Here: + * + * - cv::GComputation object is created with a lambda constructor + * where it is defined as a two-input, one-output graph. + * + * - Its method `apply()` in fact takes arbitrary number of arguments + * (as vectors) so user can pass wrong number of inputs/outputs + * here. C++ compiler wouldn't notice that since the cv::GComputation + * API is polymorphic, and only a run-time error will be generated. + * + * Now the same code written with typed API: + * + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp Typed_Example + * + * The key difference is: + * + * - Now the constructor lambda *must take* parameters and *must + * return* values as defined in the `GComputationT<>` signature. + * - Its method `apply()` does not require any extra specifiers to + * separate input arguments from the output ones + * - A `GCompiledT` (compilation product) takes input/output + * arguments with no extra specifiers as well. + */ +template class GComputationT; + +// Single return value implementation +template class GComputationT +{ +public: + typedef std::function Gen; + + class GCompiledT + { + private: + friend class GComputationT; + + cv::GCompiled m_comp; + + explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} + + public: + GCompiledT() {} + + void operator()(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT &outArg) + { + m_comp(cv::gin(inArgs...), cv::gout(outArg)); + } + + explicit operator bool() const + { + return static_cast(m_comp); + } + }; + +private: + typedef std::pair Captured; + + Captured capture(const Gen& g, Args... args) + { + return Captured(g(args...), cv::GIn(args...)); + } + + Captured m_capture; + cv::GComputation m_comp; + +public: + GComputationT(const Gen &generator) + : m_capture(capture(generator, detail::make_default()...)) + , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), + cv::GOut(m_capture.first)) + { + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT &outArg, + GCompileArgs &&args) + { + m_comp.apply(cv::gin(inArgs...), cv::gout(outArg), std::move(args)); + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT &outArg) + { + apply(inArgs..., outArg, GCompileArgs()); + } + + + GCompiledT compile(detail::ProtoToMetaT... inDescs) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); + } + + GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); + } +}; + +// Multiple (fixed) return value implementation. FIXME: How to avoid copy-paste? +template class GComputationT(Args...)> +{ +public: + typedef std::function(Args...)> Gen; + + class GCompiledT + { + private: + friend class GComputationT(Args...)>; + + cv::GCompiled m_comp; + explicit GCompiledT(const cv::GCompiled &comp) : m_comp(comp) {} + + public: + GCompiledT() {} + + void operator()(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT&... outArgs) + { + m_comp(cv::gin(inArgs...), cv::gout(outArgs...)); + } + + explicit operator bool() const + { + return static_cast(m_comp); + } + }; + +private: + typedef std::pair Captured; + + template + Captured capture(GProtoArgs &&args, const std::tuple &rr, detail::Seq) + { + return Captured(cv::GOut(std::get(rr)...).m_args, args); + } + + Captured capture(const Gen& g, Args... args) + { + return capture(cv::GIn(args...).m_args, g(args...), typename detail::MkSeq::type()); + } + + Captured m_capture; + cv::GComputation m_comp; + +public: + GComputationT(const Gen &generator) + : m_capture(capture(generator, detail::make_default()...)) + , m_comp(cv::GProtoInputArgs(std::move(m_capture.second)), + cv::GProtoOutputArgs(std::move(m_capture.first))) + { + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT&... outArgs, + GCompileArgs &&args) + { + m_comp.apply(cv::gin(inArgs...), cv::gout(outArgs...), std::move(args)); + } + + void apply(detail::ProtoToParamT... inArgs, + detail::ProtoToParamT&... outArgs) + { + apply(inArgs..., outArgs..., GCompileArgs()); + } + + + GCompiledT compile(detail::ProtoToMetaT... inDescs) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), GCompileArgs())); + } + + GCompiledT compile(detail::ProtoToMetaT... inDescs, GCompileArgs &&args) + { + GMetaArgs inMetas = { GMetaArg(inDescs)... }; + return GCompiledT(m_comp.compile(std::move(inMetas), std::move(args))); + } +}; + +} // namespace cv +#endif // !defined(GAPI_STANDALONE) +#endif // OPENCV_GAPI_GTYPED_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp index 67a34fbbc9..96aaa5a447 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/imgproc.hpp @@ -1,1769 +1,1769 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_IMGPROC_HPP -#define OPENCV_GAPI_IMGPROC_HPP - -#include - -#include // std::tuple - -#include -#include -#include - - -/** \defgroup gapi_imgproc G-API Image processing functionality -@{ - @defgroup gapi_filters Graph API: Image filters - @defgroup gapi_colorconvert Graph API: Converting image from one color space to another - @defgroup gapi_feature Graph API: Image Feature Detection - @defgroup gapi_shape Graph API: Image Structural Analysis and Shape Descriptors - @defgroup gapi_transform Graph API: Image and channel composition functions -@} - */ - -namespace { -void validateFindingContoursMeta(const int depth, const int chan, const int mode) -{ - GAPI_Assert(chan == 1); - switch (mode) - { - case cv::RETR_CCOMP: - GAPI_Assert(depth == CV_8U || depth == CV_32S); - break; - case cv::RETR_FLOODFILL: - GAPI_Assert(depth == CV_32S); - break; - default: - GAPI_Assert(depth == CV_8U); - break; - } -} -} // anonymous namespace - -namespace cv { namespace gapi { - -/** - * @brief This namespace contains G-API Operation Types for OpenCV - * ImgProc module functionality. - */ -namespace imgproc { - using GMat2 = std::tuple; - using GMat3 = std::tuple; // FIXME: how to avoid this? - using GFindContoursOutput = std::tuple>,GArray>; - - G_TYPED_KERNEL(GFilter2D, , "org.opencv.imgproc.filters.filter2D") { - static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Point, Scalar, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GSepFilter, , "org.opencv.imgproc.filters.sepfilter") { - static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Mat, Point, Scalar, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GBoxFilter, , "org.opencv.imgproc.filters.boxfilter") { - static GMatDesc outMeta(GMatDesc in, int ddepth, Size, Point, bool, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GBlur, , "org.opencv.imgproc.filters.blur") { - static GMatDesc outMeta(GMatDesc in, Size, Point, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GGaussBlur, , "org.opencv.imgproc.filters.gaussianBlur") { - static GMatDesc outMeta(GMatDesc in, Size, double, double, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GMedianBlur, , "org.opencv.imgproc.filters.medianBlur") { - static GMatDesc outMeta(GMatDesc in, int) { - return in; - } - }; - - G_TYPED_KERNEL(GErode, , "org.opencv.imgproc.filters.erode") { - static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GDilate, , "org.opencv.imgproc.filters.dilate") { - static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GMorphologyEx, , - "org.opencv.imgproc.filters.morphologyEx") { - static GMatDesc outMeta(const GMatDesc &in, MorphTypes, Mat, Point, int, - BorderTypes, Scalar) { - return in; - } - }; - - G_TYPED_KERNEL(GSobel, , "org.opencv.imgproc.filters.sobel") { - static GMatDesc outMeta(GMatDesc in, int ddepth, int, int, int, double, double, int, Scalar) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL_M(GSobelXY, , "org.opencv.imgproc.filters.sobelxy") { - static std::tuple outMeta(GMatDesc in, int ddepth, int, int, double, double, int, Scalar) { - return std::make_tuple(in.withDepth(ddepth), in.withDepth(ddepth)); - } - }; - - G_TYPED_KERNEL(GLaplacian, , - "org.opencv.imgproc.filters.laplacian") { - static GMatDesc outMeta(GMatDesc in, int ddepth, int, double, double, int) { - return in.withDepth(ddepth); - } - }; - - G_TYPED_KERNEL(GBilateralFilter, , - "org.opencv.imgproc.filters.bilateralfilter") { - static GMatDesc outMeta(GMatDesc in, int, double, double, int) { - return in; - } - }; - - G_TYPED_KERNEL(GEqHist, , "org.opencv.imgproc.equalizeHist") { - static GMatDesc outMeta(GMatDesc in) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GCanny, , "org.opencv.imgproc.feature.canny") { - static GMatDesc outMeta(GMatDesc in, double, double, int, bool) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GGoodFeatures, - (GMat,int,double,double,Mat,int,bool,double)>, - "org.opencv.imgproc.feature.goodFeaturesToTrack") { - static GArrayDesc outMeta(GMatDesc, int, double, double, const Mat&, int, bool, double) { - return empty_array_desc(); - } - }; - - using RetrMode = RetrievalModes; - using ContMethod = ContourApproximationModes; - G_TYPED_KERNEL(GFindContours, >(GMat,RetrMode,ContMethod,GOpaque)>, - "org.opencv.imgproc.shape.findContours") - { - static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return empty_array_desc(); - } - }; - - // FIXME oc: make default value offset = Point() - G_TYPED_KERNEL(GFindContoursNoOffset, >(GMat,RetrMode,ContMethod)>, - "org.opencv.imgproc.shape.findContoursNoOffset") - { - static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return empty_array_desc(); - } - }; - - G_TYPED_KERNEL(GFindContoursH,)>, - "org.opencv.imgproc.shape.findContoursH") - { - static std::tuple - outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - }; - - // FIXME oc: make default value offset = Point() - G_TYPED_KERNEL(GFindContoursHNoOffset,, - "org.opencv.imgproc.shape.findContoursHNoOffset") - { - static std::tuple - outMeta(GMatDesc in, RetrMode mode, ContMethod) - { - validateFindingContoursMeta(in.depth, in.chan, mode); - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GBoundingRectMat, (GMat)>, - "org.opencv.imgproc.shape.boundingRectMat") { - static GOpaqueDesc outMeta(GMatDesc in) { - if (in.depth == CV_8U) - { - GAPI_Assert(in.chan == 1); - } - else - { - GAPI_Assert (in.depth == CV_32S || in.depth == CV_32F); - int amount = detail::checkVector(in, 2u); - GAPI_Assert(amount != -1 && - "Input Mat can't be described as vector of 2-dimentional points"); - } - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GBoundingRectVector32S, (GArray)>, - "org.opencv.imgproc.shape.boundingRectVector32S") { - static GOpaqueDesc outMeta(GArrayDesc) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GBoundingRectVector32F, (GArray)>, - "org.opencv.imgproc.shape.boundingRectVector32F") { - static GOpaqueDesc outMeta(GArrayDesc) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DMat, (GMat,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DMat") { - static GOpaqueDesc outMeta(GMatDesc in,DistanceTypes,double,double,double) { - int amount = detail::checkVector(in, 2u); - GAPI_Assert(amount != -1 && - "Input Mat can't be described as vector of 2-dimentional points"); - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DVector32S, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DVector32S") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DVector32F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DVector32F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine2DVector64F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine2DVector64F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DMat, (GMat,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DMat") { - static GOpaqueDesc outMeta(GMatDesc in,int,double,double,double) { - int amount = detail::checkVector(in, 3u); - GAPI_Assert(amount != -1 && - "Input Mat can't be described as vector of 3-dimentional points"); - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DVector32S, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DVector32S") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DVector32F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DVector32F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GFitLine3DVector64F, - (GArray,DistanceTypes,double,double,double)>, - "org.opencv.imgproc.shape.fitLine3DVector64F") { - static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { - return empty_gopaque_desc(); - } - }; - - G_TYPED_KERNEL(GBGR2RGB, , "org.opencv.imgproc.colorconvert.bgr2rgb") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GRGB2YUV, , "org.opencv.imgproc.colorconvert.rgb2yuv") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GYUV2RGB, , "org.opencv.imgproc.colorconvert.yuv2rgb") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GBGR2I420, , "org.opencv.imgproc.colorconvert.bgr2i420") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - GAPI_Assert(in.size.height % 2 == 0); - return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); - } - }; - - G_TYPED_KERNEL(GRGB2I420, , "org.opencv.imgproc.colorconvert.rgb2i420") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - GAPI_Assert(in.size.height % 2 == 0); - return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); - } - }; - - G_TYPED_KERNEL(GI4202BGR, , "org.opencv.imgproc.colorconvert.i4202bgr") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 1); - GAPI_Assert(in.size.height % 3 == 0); - return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); - } - }; - - G_TYPED_KERNEL(GI4202RGB, , "org.opencv.imgproc.colorconvert.i4202rgb") { - static GMatDesc outMeta(GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 1); - GAPI_Assert(in.size.height % 3 == 0); - return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); - } - }; - - G_TYPED_KERNEL(GNV12toRGB, , "org.opencv.imgproc.colorconvert.nv12torgb") { - static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { - GAPI_Assert(in_y.chan == 1); - GAPI_Assert(in_uv.chan == 2); - GAPI_Assert(in_y.depth == CV_8U); - GAPI_Assert(in_uv.depth == CV_8U); - // UV size should be aligned with Y - GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); - GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); - return in_y.withType(CV_8U, 3); // type will be CV_8UC3; - } - }; - - G_TYPED_KERNEL(GNV12toBGR, , "org.opencv.imgproc.colorconvert.nv12tobgr") { - static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { - GAPI_Assert(in_y.chan == 1); - GAPI_Assert(in_uv.chan == 2); - GAPI_Assert(in_y.depth == CV_8U); - GAPI_Assert(in_uv.depth == CV_8U); - // UV size should be aligned with Y - GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); - GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); - return in_y.withType(CV_8U, 3); // type will be CV_8UC3; - } - }; - - G_TYPED_KERNEL(GRGB2Lab, , "org.opencv.imgproc.colorconvert.rgb2lab") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GBGR2LUV, , "org.opencv.imgproc.colorconvert.bgr2luv") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GLUV2BGR, , "org.opencv.imgproc.colorconvert.luv2bgr") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GYUV2BGR, , "org.opencv.imgproc.colorconvert.yuv2bgr") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GBGR2YUV, , "org.opencv.imgproc.colorconvert.bgr2yuv") { - static GMatDesc outMeta(GMatDesc in) { - return in; // type still remains CV_8UC3; - } - }; - - G_TYPED_KERNEL(GRGB2Gray, , "org.opencv.imgproc.colorconvert.rgb2gray") { - static GMatDesc outMeta(GMatDesc in) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GRGB2GrayCustom, , "org.opencv.imgproc.colorconvert.rgb2graycustom") { - static GMatDesc outMeta(GMatDesc in, float, float, float) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GBGR2Gray, , "org.opencv.imgproc.colorconvert.bgr2gray") { - static GMatDesc outMeta(GMatDesc in) { - return in.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GBayerGR2RGB, , "org.opencv.imgproc.colorconvert.bayergr2rgb") { - static cv::GMatDesc outMeta(cv::GMatDesc in) { - return in.withType(CV_8U, 3); - } - }; - - G_TYPED_KERNEL(GRGB2HSV, , "org.opencv.imgproc.colorconvert.rgb2hsv") { - static cv::GMatDesc outMeta(cv::GMatDesc in) { - return in; - } - }; - - G_TYPED_KERNEL(GRGB2YUV422, , "org.opencv.imgproc.colorconvert.rgb2yuv422") { - static cv::GMatDesc outMeta(cv::GMatDesc in) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - return in.withType(in.depth, 2); - } - }; - - G_TYPED_KERNEL(GNV12toRGBp, , "org.opencv.imgproc.colorconvert.nv12torgbp") { - static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { - GAPI_Assert(inY.depth == CV_8U); - GAPI_Assert(inUV.depth == CV_8U); - GAPI_Assert(inY.chan == 1); - GAPI_Assert(inY.planar == false); - GAPI_Assert(inUV.chan == 2); - GAPI_Assert(inUV.planar == false); - GAPI_Assert(inY.size.width == 2 * inUV.size.width); - GAPI_Assert(inY.size.height == 2 * inUV.size.height); - return inY.withType(CV_8U, 3).asPlanar(); - } - }; - - G_TYPED_KERNEL(GNV12toGray, , "org.opencv.imgproc.colorconvert.nv12togray") { - static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { - GAPI_Assert(inY.depth == CV_8U); - GAPI_Assert(inUV.depth == CV_8U); - GAPI_Assert(inY.chan == 1); - GAPI_Assert(inY.planar == false); - GAPI_Assert(inUV.chan == 2); - GAPI_Assert(inUV.planar == false); - - GAPI_Assert(inY.size.width == 2 * inUV.size.width); - GAPI_Assert(inY.size.height == 2 * inUV.size.height); - return inY.withType(CV_8U, 1); - } - }; - - G_TYPED_KERNEL(GNV12toBGRp, , "org.opencv.imgproc.colorconvert.nv12tobgrp") { - static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { - GAPI_Assert(inY.depth == CV_8U); - GAPI_Assert(inUV.depth == CV_8U); - GAPI_Assert(inY.chan == 1); - GAPI_Assert(inY.planar == false); - GAPI_Assert(inUV.chan == 2); - GAPI_Assert(inUV.planar == false); - GAPI_Assert(inY.size.width == 2 * inUV.size.width); - GAPI_Assert(inY.size.height == 2 * inUV.size.height); - return inY.withType(CV_8U, 3).asPlanar(); - } - }; - - G_TYPED_KERNEL(GResize, , "org.opencv.imgproc.transform.resize") { - static GMatDesc outMeta(GMatDesc in, Size sz, double fx, double fy, int /*interp*/) { - if (sz.width != 0 && sz.height != 0) - { - return in.withSize(sz); - } - else - { - int outSz_w = saturate_cast(in.size.width * fx); - int outSz_h = saturate_cast(in.size.height * fy); - GAPI_Assert(outSz_w > 0 && outSz_h > 0); - return in.withSize(Size(outSz_w, outSz_h)); - } - } - }; - - G_TYPED_KERNEL(GResizeP, , "org.opencv.imgproc.transform.resizeP") { - static GMatDesc outMeta(GMatDesc in, Size sz, int interp) { - GAPI_Assert(in.depth == CV_8U); - GAPI_Assert(in.chan == 3); - GAPI_Assert(in.planar); - GAPI_Assert(interp == cv::INTER_LINEAR); - return in.withSize(sz); - } - }; - -} //namespace imgproc - -//! @addtogroup gapi_filters -//! @{ -/** @brief Applies a separable linear filter to a matrix(image). - -The function applies a separable linear filter to the matrix. That is, first, every row of src is -filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D -kernel kernelY. The final result is returned. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - In case of floating-point computation, rounding to nearest even is procedeed -if hardware supports it (if not - to nearest value). - - Function textual ID is "org.opencv.imgproc.filters.sepfilter" -@param src Source image. -@param ddepth desired depth of the destination image (the following combinations of src.depth() and ddepth are supported: - - src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F - src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F - src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F - src.depth() = CV_64F, ddepth = -1/CV_64F - -when ddepth=-1, the output image will have the same depth as the source) -@param kernelX Coefficients for filtering each row. -@param kernelY Coefficients for filtering each column. -@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor -is at the kernel center. -@param delta Value added to the filtered results before storing them. -@param borderType Pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa boxFilter, gaussianBlur, medianBlur - */ -GAPI_EXPORTS_W GMat sepFilter(const GMat& src, int ddepth, const Mat& kernelX, const Mat& kernelY, const Point& anchor /*FIXME: = Point(-1,-1)*/, - const Scalar& delta /*FIXME = GScalar(0)*/, int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Convolves an image with the kernel. - -The function applies an arbitrary linear filter to an image. When -the aperture is partially outside the image, the function interpolates outlier pixel values -according to the specified border mode. - -The function does actually compute correlation, not the convolution: - -\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] - -That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip -the kernel using flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - -anchor.y - 1)`. - -Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same size and number of channels an input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.filter2D" - -@param src input image. -@param ddepth desired depth of the destination image -@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point -matrix; if you want to apply different kernels to different channels, split the image into -separate color planes using split and process them individually. -@param anchor anchor of the kernel that indicates the relative position of a filtered point within -the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor -is at the kernel center. -@param delta optional value added to the filtered pixels before storing them in dst. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa sepFilter - */ -GAPI_EXPORTS_W GMat filter2D(const GMat& src, int ddepth, const Mat& kernel, const Point& anchor = Point(-1,-1), const Scalar& delta = Scalar(0), - int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); - - -/** @brief Blurs an image using the box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] - -where - -\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise} \end{cases}\f] - -Unnormalized box filter is useful for computing various integral characteristics over each pixel -neighborhood, such as covariance matrices of image derivatives (used in dense optical flow -algorithms, and so on). If you need to compute pixel sums over variable-size windows, use cv::integral. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.boxfilter" - -@param src Source image. -@param dtype the output image depth (-1 to set the input image data type). -@param ksize blurring kernel size. -@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor -is at the kernel center. -@param normalize flag, specifying whether the kernel is normalized by its area or not. -@param borderType Pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa sepFilter, gaussianBlur, medianBlur, integral - */ -GAPI_EXPORTS_W GMat boxFilter(const GMat& src, int dtype, const Size& ksize, const Point& anchor = Point(-1,-1), - bool normalize = true, int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Blurs an image using the normalized box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] - -The call `blur(src, ksize, anchor, borderType)` is equivalent to `boxFilter(src, src.type(), ksize, anchor, -true, borderType)`. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.blur" - -@param src Source image. -@param ksize blurring kernel size. -@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel -center. -@param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur - */ -GAPI_EXPORTS_W GMat blur(const GMat& src, const Size& ksize, const Point& anchor = Point(-1,-1), - int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); - - -//GAPI_EXPORTS_W void blur( InputArray src, OutputArray dst, - // Size ksize, Point anchor = Point(-1,-1), - // int borderType = BORDER_DEFAULT ); - - -/** @brief Blurs an image using a Gaussian filter. - -The function filter2Ds the source image with the specified Gaussian kernel. -Output image must have the same type and number of channels an input image. - -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.gaussianBlur" - -@param src input image; -@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be -positive and odd. Or, they can be zero's and then they are computed from sigma. -@param sigmaX Gaussian kernel standard deviation in X direction. -@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be -equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, -respectively (see cv::getGaussianKernel for details); to fully control the result regardless of -possible future modifications of all this semantics, it is recommended to specify all of ksize, -sigmaX, and sigmaY. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa sepFilter, boxFilter, medianBlur - */ -GAPI_EXPORTS_W GMat gaussianBlur(const GMat& src, const Size& ksize, double sigmaX, double sigmaY = 0, - int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); - -/** @brief Blurs an image using the median filter. - -The function smoothes an image using the median filter with the \f$\texttt{ksize} \times -\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. -The median filter uses cv::BORDER_REPLICATE internally to cope with border pixels, see cv::BorderTypes - - Function textual ID is "org.opencv.imgproc.filters.medianBlur" - -@param src input matrix (image) -@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... -@sa boxFilter, gaussianBlur - */ -GAPI_EXPORTS_W GMat medianBlur(const GMat& src, int ksize); - -/** @brief Erodes an image by using a specific structuring element. - -The function erodes the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the minimum is taken: - -\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.erode" - -@param src input image -@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular -structuring element is used. Kernel can be created using getStructuringElement. -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times erosion is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa dilate, morphologyEx - */ -GAPI_EXPORTS_W GMat erode(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Erodes an image by using 3 by 3 rectangular structuring element. - -The function erodes the source image using the rectangular structuring element with rectangle center as an anchor. -Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.erode" - -@param src input image -@param iterations number of times erosion is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa erode, dilate3x3 - */ -GAPI_EXPORTS_W GMat erode3x3(const GMat& src, int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Dilates an image by using a specific structuring element. - -The function dilates the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the maximum is taken: -\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.dilate" - -@param src input image. -@param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular -structuring element is used. Kernel can be created using getStructuringElement -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times dilation is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa erode, morphologyEx, getStructuringElement - */ -GAPI_EXPORTS_W GMat dilate(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Dilates an image by using 3 by 3 rectangular structuring element. - -The function dilates the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the maximum is taken: -\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. -Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. -Output image must have the same type, size, and number of channels as the input image. -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.dilate" - -@param src input image. -@param iterations number of times dilation is applied. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of a constant border -@sa dilate, erode3x3 - */ - -GAPI_EXPORTS_W GMat dilate3x3(const GMat& src, int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue()); - -/** @brief Performs advanced morphological transformations. - -The function can perform advanced morphological transformations using an erosion and dilation as -basic operations. - -Any of the operations can be done in-place. In case of multi-channel images, each channel is -processed independently. - -@note - - Function textual ID is "org.opencv.imgproc.filters.morphologyEx" - - The number of iterations is the number of times erosion or dilatation operation will be -applied. For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to -apply successively: erode -> erode -> dilate -> dilate -(and not erode -> dilate -> erode -> dilate). - -@param src Input image. -@param op Type of a morphological operation, see #MorphTypes -@param kernel Structuring element. It can be created using #getStructuringElement. -@param anchor Anchor position within the element. Both negative values mean that the anchor is at -the kernel center. -@param iterations Number of times erosion and dilation are applied. -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param borderValue Border value in case of a constant border. The default value has a special -meaning. -@sa dilate, erode, getStructuringElement - */ -GAPI_EXPORTS_W GMat morphologyEx(const GMat &src, const MorphTypes op, const Mat &kernel, - const Point &anchor = Point(-1,-1), - const int iterations = 1, - const BorderTypes borderType = BORDER_CONSTANT, - const Scalar &borderValue = morphologyDefaultBorderValue()); - -/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - -In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to -calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ -kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first -or the second x- or y- derivatives. - -There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr -filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is - -\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] - -for the x-derivative, or transposed for the y-derivative. - -The function calculates an image derivative by convolving the image with the appropriate kernel: - -\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] - -The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less -resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) -or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first -case corresponds to a kernel of: - -\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] - -The second case corresponds to a kernel of: - -\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] - -@note - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.sobel" - -@param src input image. -@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of - 8-bit input images it will result in truncated derivatives. -@param dx order of the derivative x. -@param dy order of the derivative y. -@param ksize size of the extended Sobel kernel; it must be odd. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see cv::getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa filter2D, gaussianBlur, cartToPolar - */ -GAPI_EXPORTS_W GMat Sobel(const GMat& src, int ddepth, int dx, int dy, int ksize = 3, - double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - -In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to -calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ -kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first -or the second x- or y- derivatives. - -There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr -filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is - -\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] - -for the x-derivative, or transposed for the y-derivative. - -The function calculates an image derivative by convolving the image with the appropriate kernel: - -\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] - -The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less -resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) -or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first -case corresponds to a kernel of: - -\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] - -The second case corresponds to a kernel of: - -\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] - -@note - - First returned matrix correspons to dx derivative while the second one to dy. - - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. - - Function textual ID is "org.opencv.imgproc.filters.sobelxy" - -@param src input image. -@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of - 8-bit input images it will result in truncated derivatives. -@param order order of the derivatives. -@param ksize size of the extended Sobel kernel; it must be odd. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see cv::getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see cv::BorderTypes -@param borderValue border value in case of constant border type -@sa filter2D, gaussianBlur, cartToPolar - */ -GAPI_EXPORTS_W std::tuple SobelXY(const GMat& src, int ddepth, int order, int ksize = 3, - double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT, - const Scalar& borderValue = Scalar(0)); - -/** @brief Calculates the Laplacian of an image. - -The function calculates the Laplacian of the source image by adding up the second x and y -derivatives calculated using the Sobel operator: - -\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] - -This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image -with the following \f$3 \times 3\f$ aperture: - -\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] - -@note Function textual ID is "org.opencv.imgproc.filters.laplacian" - -@param src Source image. -@param ddepth Desired depth of the destination image. -@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for -details. The size must be positive and odd. -@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is -applied. See #getDerivKernels for details. -@param delta Optional delta value that is added to the results prior to storing them in dst . -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@return Destination image of the same size and the same number of channels as src. -@sa Sobel, Scharr - */ -GAPI_EXPORTS_W GMat Laplacian(const GMat& src, int ddepth, int ksize = 1, - double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT); - -/** @brief Applies the bilateral filter to an image. - -The function applies bilateral filtering to the input image, as described in -http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html -bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is -very slow compared to most filters. - -_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< -10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very -strong effect, making the image look "cartoonish". - -_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time -applications, and perhaps d=9 for offline applications that need heavy noise filtering. - -This filter does not work inplace. - -@note Function textual ID is "org.opencv.imgproc.filters.bilateralfilter" - -@param src Source 8-bit or floating-point, 1-channel or 3-channel image. -@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, -it is computed from sigmaSpace. -@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that -farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting -in larger areas of semi-equal color. -@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that -farther pixels will influence each other as long as their colors are close enough (see sigmaColor -). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is -proportional to sigmaSpace. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes -@return Destination image of the same size and type as src. - */ -GAPI_EXPORTS_W GMat bilateralFilter(const GMat& src, int d, double sigmaColor, double sigmaSpace, - int borderType = BORDER_DEFAULT); - -//! @} gapi_filters - -//! @addtogroup gapi_feature -//! @{ -/** @brief Finds edges in an image using the Canny algorithm. - -The function finds edges in the input image and marks them in the output map edges using the -Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The -largest value is used to find initial segments of strong edges. See - - -@note Function textual ID is "org.opencv.imgproc.feature.canny" - -@param image 8-bit input image. -@param threshold1 first threshold for the hysteresis procedure. -@param threshold2 second threshold for the hysteresis procedure. -@param apertureSize aperture size for the Sobel operator. -@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm -\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( -L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( -L2gradient=false ). - */ -GAPI_EXPORTS_W GMat Canny(const GMat& image, double threshold1, double threshold2, - int apertureSize = 3, bool L2gradient = false); - -/** @brief Determines strong corners on an image. - -The function finds the most prominent corners in the image or in the specified image region, as -described in @cite Shi94 - -- Function calculates the corner quality measure at every source image pixel using the - #cornerMinEigenVal or #cornerHarris . -- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are - retained). -- The corners with the minimal eigenvalue less than - \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. -- The remaining corners are sorted by the quality measure in the descending order. -- Function throws away each corner for which there is a stronger corner at a distance less than - maxDistance. - -The function can be used to initialize a point-based tracker of an object. - -@note - - If the function is called with different values A and B of the parameter qualityLevel , and -A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector -with qualityLevel=B . - - Function textual ID is "org.opencv.imgproc.feature.goodFeaturesToTrack" - -@param image Input 8-bit or floating-point 32-bit, single-channel image. -@param maxCorners Maximum number of corners to return. If there are more corners than are found, -the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set -and all detected corners are returned. -@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The -parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue -(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the -quality measure less than the product are rejected. For example, if the best corner has the -quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure -less than 15 are rejected. -@param minDistance Minimum possible Euclidean distance between the returned corners. -@param mask Optional region of interest. If the image is not empty (it needs to have the type -CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. -@param blockSize Size of an average block for computing a derivative covariation matrix over each -pixel neighborhood. See cornerEigenValsAndVecs . -@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) -or #cornerMinEigenVal. -@param k Free parameter of the Harris detector. - -@return vector of detected corners. - */ -GAPI_EXPORTS_W GArray goodFeaturesToTrack(const GMat &image, - int maxCorners, - double qualityLevel, - double minDistance, - const Mat &mask = Mat(), - int blockSize = 3, - bool useHarrisDetector = false, - double k = 0.04); - -/** @brief Equalizes the histogram of a grayscale image. - -//! @} gapi_feature - -The function equalizes the histogram of the input image using the following algorithm: - -- Calculate the histogram \f$H\f$ for src . -- Normalize the histogram so that the sum of histogram bins is 255. -- Compute the integral of the histogram: -\f[H'_i = \sum _{0 \le j < i} H(j)\f] -- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ - -The algorithm normalizes the brightness and increases the contrast of the image. -@note - - The returned image is of the same size and type as input. - - Function textual ID is "org.opencv.imgproc.equalizeHist" - -@param src Source 8-bit single channel image. - */ -GAPI_EXPORTS_W GMat equalizeHist(const GMat& src); - -//! @addtogroup gapi_shape -//! @{ -/** @brief Finds contours in a binary image. - -The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . -The contours are a useful tool for shape analysis and object detection and recognition. -See squares.cpp in the OpenCV sample directory. - -@note Function textual ID is "org.opencv.imgproc.shape.findContours" - -@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero -pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , -#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. -If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer -image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL then @ref CV_32SC1 is supported only. -@param mode Contour retrieval mode, see #RetrievalModes -@param method Contour approximation method, see #ContourApproximationModes -@param offset Optional offset by which every contour point is shifted. This is useful if the -contours are extracted from the image ROI and then they should be analyzed in the whole image -context. - -@return GArray of detected contours. Each contour is stored as a GArray of points. - */ -GAPI_EXPORTS GArray> -findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, - const GOpaque &offset); - -// FIXME oc: make default value offset = Point() -/** @overload -@note Function textual ID is "org.opencv.imgproc.shape.findContoursNoOffset" - */ -GAPI_EXPORTS GArray> -findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); - -/** @brief Finds contours and their hierarchy in a binary image. - -The function retrieves contours from the binary image using the algorithm @cite Suzuki85 -and calculates their hierarchy. -The contours are a useful tool for shape analysis and object detection and recognition. -See squares.cpp in the OpenCV sample directory. - -@note Function textual ID is "org.opencv.imgproc.shape.findContoursH" - -@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero -pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , -#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. -If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer -image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL -- @ref CV_32SC1 supports only. -@param mode Contour retrieval mode, see #RetrievalModes -@param method Contour approximation method, see #ContourApproximationModes -@param offset Optional offset by which every contour point is shifted. This is useful if the -contours are extracted from the image ROI and then they should be analyzed in the whole image -context. - -@return - - GArray of detected contours. Each contour is stored as a GArray of points. - - Optional output GArray of cv::Vec4i, containing information about the image topology. -It has as many elements as the number of contours. For each i-th contour contours[i], the elements -hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based -indices in contours of the next and previous contours at the same hierarchical level, the first -child contour and the parent contour, respectively. If for the contour i there are no next, -previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. - */ -GAPI_EXPORTS std::tuple>,GArray> -findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, - const GOpaque &offset); - -// FIXME oc: make default value offset = Point() -/** @overload -@note Function textual ID is "org.opencv.imgproc.shape.findContoursHNoOffset" - */ -GAPI_EXPORTS std::tuple>,GArray> -findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); - -/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels -of gray-scale image. - -The function calculates and returns the minimal up-right bounding rectangle for the specified -point set or non-zero pixels of gray-scale image. - -@note - - Function textual ID is "org.opencv.imgproc.shape.boundingRectMat" - - In case of a 2D points' set given, Mat should be 2-dimensional, have a single row or column -if there are 2 channels, or have 2 columns if there is a single channel. Mat should have either -@ref CV_32S or @ref CV_32F depth - -@param src Input gray-scale image @ref CV_8UC1; or input set of @ref CV_32S or @ref CV_32F -2D points stored in Mat. - */ -GAPI_EXPORTS_W GOpaque boundingRect(const GMat& src); - -/** @overload - -Calculates the up-right bounding rectangle of a point set. - -@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32S" - -@param src Input 2D point set, stored in std::vector. - */ -GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); - -/** @overload - -Calculates the up-right bounding rectangle of a point set. - -@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32F" - -@param src Input 2D point set, stored in std::vector. - */ -GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); - -/** @brief Fits a line to a 2D point set. - -The function fits a line to a 2D point set by minimizing \f$\sum_i \rho(r_i)\f$ where -\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance -function, one of the following: -- DIST_L2 -\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] -- DIST_L1 -\f[\rho (r) = r\f] -- DIST_L12 -\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] -- DIST_FAIR -\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] -- DIST_WELSCH -\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] -- DIST_HUBER -\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] - -The algorithm is based on the M-estimator ( ) technique -that iteratively fits the line using the weighted least-squares algorithm. After each iteration the -weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . - -@note - - Function textual ID is "org.opencv.imgproc.shape.fitLine2DMat" - - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row -or column if there are N channels, or have N columns if there is a single channel. - -@param src Input set of 2D points stored in one of possible containers: Mat, -std::vector, std::vector, std::vector. -@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER -and @ref DIST_C are not supported. -@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value -is chosen. -@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the -line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. -@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. -If it is 0, a default value is chosen. - -@return Output line parameters: a vector of 4 elements (like Vec4f) - (vx, vy, x0, y0), -where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line. - */ -GAPI_EXPORTS GOpaque fitLine2D(const GMat& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32S" - - */ -GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32F" - - */ -GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector64F" - - */ -GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @brief Fits a line to a 3D point set. - -The function fits a line to a 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where -\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance -function, one of the following: -- DIST_L2 -\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] -- DIST_L1 -\f[\rho (r) = r\f] -- DIST_L12 -\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] -- DIST_FAIR -\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] -- DIST_WELSCH -\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] -- DIST_HUBER -\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] - -The algorithm is based on the M-estimator ( ) technique -that iteratively fits the line using the weighted least-squares algorithm. After each iteration the -weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . - -@note - - Function textual ID is "org.opencv.imgproc.shape.fitLine3DMat" - - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row -or column if there are N channels, or have N columns if there is a single channel. - -@param src Input set of 3D points stored in one of possible containers: Mat, -std::vector, std::vector, std::vector. -@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER -and @ref DIST_C are not supported. -@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value -is chosen. -@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the -line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. -@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. -If it is 0, a default value is chosen. - -@return Output line parameters: a vector of 6 elements (like Vec6f) - (vx, vy, vz, x0, y0, z0), -where (vx, vy, vz) is a normalized vector collinear to the line and (x0, y0, z0) is a point on -the line. - */ -GAPI_EXPORTS GOpaque fitLine3D(const GMat& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32S" - - */ -GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32F" - - */ -GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -/** @overload - -@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector64F" - - */ -GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, - const double param = 0., const double reps = 0., - const double aeps = 0.); - -//! @} gapi_shape - -//! @addtogroup gapi_colorconvert -//! @{ -/** @brief Converts an image from BGR color space to RGB color space. - -The function converts an input image from BGR color space to RGB. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image is 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2rgb" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa RGB2BGR -*/ -GAPI_EXPORTS_W GMat BGR2RGB(const GMat& src); - -/** @brief Converts an image from RGB color space to gray-scaled. - -The conventional ranges for R, G, and B channel values are 0 to 255. -Resulting gray color value computed as -\f[\texttt{dst} (I)= \texttt{0.299} * \texttt{src}(I).R + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.114} * \texttt{src}(I).B \f] - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2gray" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@sa RGB2YUV - */ -GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src); - -/** @overload -Resulting gray color value computed as -\f[\texttt{dst} (I)= \texttt{rY} * \texttt{src}(I).R + \texttt{gY} * \texttt{src}(I).G + \texttt{bY} * \texttt{src}(I).B \f] - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2graycustom" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@param rY float multiplier for R channel. -@param gY float multiplier for G channel. -@param bY float multiplier for B channel. -@sa RGB2YUV - */ -GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src, float rY, float gY, float bY); - -/** @brief Converts an image from BGR color space to gray-scaled. - -The conventional ranges for B, G, and R channel values are 0 to 255. -Resulting gray color value computed as -\f[\texttt{dst} (I)= \texttt{0.114} * \texttt{src}(I).B + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.299} * \texttt{src}(I).R \f] - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2gray" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@sa BGR2LUV - */ -GAPI_EXPORTS_W GMat BGR2Gray(const GMat& src); - -/** @brief Converts an image from RGB color space to YUV color space. - -The function converts an input image from RGB color space to YUV. -The conventional ranges for R, G, and B channel values are 0 to 255. - -In case of linear transformations, the range does not matter. But in case of a non-linear -transformation, an input RGB image should be normalized to the proper value range to get the correct -results, like here, at RGB \f$\rightarrow\f$ Y\*u\*v\* transformation. -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa YUV2RGB, RGB2Lab -*/ -GAPI_EXPORTS_W GMat RGB2YUV(const GMat& src); - -/** @brief Converts an image from BGR color space to I420 color space. - -The function converts an input image from BGR color space to I420. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. -Width of I420 output image must be the same as width of input image. -Height of I420 output image must be equal 3/2 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2i420" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa I4202BGR -*/ -GAPI_EXPORTS_W GMat BGR2I420(const GMat& src); - -/** @brief Converts an image from RGB color space to I420 color space. - -The function converts an input image from RGB color space to I420. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. -Width of I420 output image must be the same as width of input image. -Height of I420 output image must be equal 3/2 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2i420" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa I4202RGB -*/ -GAPI_EXPORTS_W GMat RGB2I420(const GMat& src); - -/** @brief Converts an image from I420 color space to BGR color space. - -The function converts an input image from I420 color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. -Width of BGR output image must be the same as width of input image. -Height of BGR output image must be equal 2/3 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202bgr" - -@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@sa BGR2I420 -*/ -GAPI_EXPORTS_W GMat I4202BGR(const GMat& src); - -/** @brief Converts an image from I420 color space to BGR color space. - -The function converts an input image from I420 color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. -Width of RGB output image must be the same as width of input image. -Height of RGB output image must be equal 2/3 from height of input image. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202rgb" - -@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@sa RGB2I420 -*/ -GAPI_EXPORTS_W GMat I4202RGB(const GMat& src); - -/** @brief Converts an image from BGR color space to LUV color space. - -The function converts an input image from BGR color space to LUV. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2luv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa RGB2Lab, RGB2LUV -*/ -GAPI_EXPORTS_W GMat BGR2LUV(const GMat& src); - -/** @brief Converts an image from LUV color space to BGR color space. - -The function converts an input image from LUV color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.luv2bgr" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa BGR2LUV -*/ -GAPI_EXPORTS_W GMat LUV2BGR(const GMat& src); - -/** @brief Converts an image from YUV color space to BGR color space. - -The function converts an input image from YUV color space to BGR. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2bgr" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa BGR2YUV -*/ -GAPI_EXPORTS_W GMat YUV2BGR(const GMat& src); - -/** @brief Converts an image from BGR color space to YUV color space. - -The function converts an input image from BGR color space to YUV. -The conventional ranges for B, G, and R channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2yuv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@sa YUV2BGR -*/ -GAPI_EXPORTS_W GMat BGR2YUV(const GMat& src); - -/** @brief Converts an image from RGB color space to Lab color space. - -The function converts an input image from BGR color space to Lab. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2lab" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. -@sa RGB2YUV, RGB2LUV -*/ -GAPI_EXPORTS_W GMat RGB2Lab(const GMat& src); - -/** @brief Converts an image from YUV color space to RGB. -The function converts an input image from YUV color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2rgb" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. - -@sa RGB2Lab, RGB2YUV -*/ -GAPI_EXPORTS_W GMat YUV2RGB(const GMat& src); - -/** @brief Converts an image from NV12 (YUV420p) color space to RGB. -The function converts an input image from NV12 color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgb" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toBGR -*/ -GAPI_EXPORTS_W GMat NV12toRGB(const GMat& src_y, const GMat& src_uv); - -/** @brief Converts an image from NV12 (YUV420p) color space to gray-scaled. -The function converts an input image from NV12 color space to gray-scaled. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 1-channel image @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12togray" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toBGR -*/ -GAPI_EXPORTS_W GMat NV12toGray(const GMat& src_y, const GMat& src_uv); - -/** @brief Converts an image from NV12 (YUV420p) color space to BGR. -The function converts an input image from NV12 color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12tobgr" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat NV12toBGR(const GMat& src_y, const GMat& src_uv); - -/** @brief Converts an image from BayerGR color space to RGB. -The function converts an input image from BayerGR color space to RGB. -The conventional ranges for G, R, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.bayergr2rgb" - -@param src_gr input image: 8-bit unsigned 1-channel image @ref CV_8UC1. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat BayerGR2RGB(const GMat& src_gr); - -/** @brief Converts an image from RGB color space to HSV. -The function converts an input image from RGB color space to HSV. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2hsv" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat RGB2HSV(const GMat& src); - -/** @brief Converts an image from RGB color space to YUV422. -The function converts an input image from RGB color space to YUV422. -The conventional ranges for R, G, and B channel values are 0 to 255. - -Output image must be 8-bit unsigned 2-channel image @ref CV_8UC2. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv422" - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. - -@sa YUV2BGR, NV12toRGB -*/ -GAPI_EXPORTS_W GMat RGB2YUV422(const GMat& src); - -/** @brief Converts an image from NV12 (YUV420p) color space to RGB. -The function converts an input image from NV12 color space to RGB. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. -Planar image memory layout is three planes laying in the memory contiguously, -so the image height should be plane_height*plane_number, -image type is @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toBGRp, NV12toRGB -*/ -GAPI_EXPORTS GMatP NV12toRGBp(const GMat &src_y, const GMat &src_uv); - -/** @brief Converts an image from NV12 (YUV420p) color space to BGR. -The function converts an input image from NV12 color space to BGR. -The conventional ranges for Y, U, and V channel values are 0 to 255. - -Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. -Planar image memory layout is three planes laying in the memory contiguously, -so the image height should be plane_height*plane_number, -image type is @ref CV_8UC1. - -@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" - -@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. - -@sa YUV2RGB, NV12toRGBp, NV12toBGR -*/ -GAPI_EXPORTS GMatP NV12toBGRp(const GMat &src_y, const GMat &src_uv); - -//! @} gapi_colorconvert -//! @addtogroup gapi_transform -//! @{ -/** @brief Resizes an image. - -The function resizes the image src down to or up to the specified size. - -Output image size will have the size dsize (when dsize is non-zero) or the size computed from -src.size(), fx, and fy; the depth of output is the same as of src. - -If you want to resize src so that it fits the pre-created dst, -you may call the function as follows: -@code - // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - resize(src, dst, dst.size(), 0, 0, interpolation); -@endcode -If you want to decimate the image by factor of 2 in each direction, you can call the function this -way: -@code - // specify fx and fy and let the function compute the destination image size. - resize(src, dst, Size(), 0.5, 0.5, interpolation); -@endcode -To shrink an image, it will generally look best with cv::INTER_AREA interpolation, whereas to -enlarge an image, it will generally look best with cv::INTER_CUBIC (slow) or cv::INTER_LINEAR -(faster but still looks OK). - -@note Function textual ID is "org.opencv.imgproc.transform.resize" - -@param src input image. -@param dsize output image size; if it equals zero, it is computed as: - \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] - Either dsize or both fx and fy must be non-zero. -@param fx scale factor along the horizontal axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.width/src.cols}\f] -@param fy scale factor along the vertical axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.height/src.rows}\f] -@param interpolation interpolation method, see cv::InterpolationFlags - -@sa warpAffine, warpPerspective, remap, resizeP - */ -GAPI_EXPORTS_W GMat resize(const GMat& src, const Size& dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR); - -/** @brief Resizes a planar image. - -The function resizes the image src down to or up to the specified size. -Planar image memory layout is three planes laying in the memory contiguously, -so the image height should be plane_height*plane_number, image type is @ref CV_8UC1. - -Output image size will have the size dsize, the depth of output is the same as of src. - -@note Function textual ID is "org.opencv.imgproc.transform.resizeP" - -@param src input image, must be of @ref CV_8UC1 type; -@param dsize output image size; -@param interpolation interpolation method, only cv::INTER_LINEAR is supported at the moment - -@sa warpAffine, warpPerspective, remap, resize - */ -GAPI_EXPORTS GMatP resizeP(const GMatP& src, const Size& dsize, int interpolation = cv::INTER_LINEAR); - -//! @} gapi_transform -} //namespace gapi -} //namespace cv - -#endif // OPENCV_GAPI_IMGPROC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_IMGPROC_HPP +#define OPENCV_GAPI_IMGPROC_HPP + +#include + +#include // std::tuple + +#include +#include +#include + + +/** \defgroup gapi_imgproc G-API Image processing functionality +@{ + @defgroup gapi_filters Graph API: Image filters + @defgroup gapi_colorconvert Graph API: Converting image from one color space to another + @defgroup gapi_feature Graph API: Image Feature Detection + @defgroup gapi_shape Graph API: Image Structural Analysis and Shape Descriptors + @defgroup gapi_transform Graph API: Image and channel composition functions +@} + */ + +namespace { +void validateFindingContoursMeta(const int depth, const int chan, const int mode) +{ + GAPI_Assert(chan == 1); + switch (mode) + { + case cv::RETR_CCOMP: + GAPI_Assert(depth == CV_8U || depth == CV_32S); + break; + case cv::RETR_FLOODFILL: + GAPI_Assert(depth == CV_32S); + break; + default: + GAPI_Assert(depth == CV_8U); + break; + } +} +} // anonymous namespace + +namespace cv { namespace gapi { + +/** + * @brief This namespace contains G-API Operation Types for OpenCV + * ImgProc module functionality. + */ +namespace imgproc { + using GMat2 = std::tuple; + using GMat3 = std::tuple; // FIXME: how to avoid this? + using GFindContoursOutput = std::tuple>,GArray>; + + G_TYPED_KERNEL(GFilter2D, , "org.opencv.imgproc.filters.filter2D") { + static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Point, Scalar, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GSepFilter, , "org.opencv.imgproc.filters.sepfilter") { + static GMatDesc outMeta(GMatDesc in, int ddepth, Mat, Mat, Point, Scalar, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GBoxFilter, , "org.opencv.imgproc.filters.boxfilter") { + static GMatDesc outMeta(GMatDesc in, int ddepth, Size, Point, bool, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GBlur, , "org.opencv.imgproc.filters.blur") { + static GMatDesc outMeta(GMatDesc in, Size, Point, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GGaussBlur, , "org.opencv.imgproc.filters.gaussianBlur") { + static GMatDesc outMeta(GMatDesc in, Size, double, double, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GMedianBlur, , "org.opencv.imgproc.filters.medianBlur") { + static GMatDesc outMeta(GMatDesc in, int) { + return in; + } + }; + + G_TYPED_KERNEL(GErode, , "org.opencv.imgproc.filters.erode") { + static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GDilate, , "org.opencv.imgproc.filters.dilate") { + static GMatDesc outMeta(GMatDesc in, Mat, Point, int, int, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GMorphologyEx, , + "org.opencv.imgproc.filters.morphologyEx") { + static GMatDesc outMeta(const GMatDesc &in, MorphTypes, Mat, Point, int, + BorderTypes, Scalar) { + return in; + } + }; + + G_TYPED_KERNEL(GSobel, , "org.opencv.imgproc.filters.sobel") { + static GMatDesc outMeta(GMatDesc in, int ddepth, int, int, int, double, double, int, Scalar) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL_M(GSobelXY, , "org.opencv.imgproc.filters.sobelxy") { + static std::tuple outMeta(GMatDesc in, int ddepth, int, int, double, double, int, Scalar) { + return std::make_tuple(in.withDepth(ddepth), in.withDepth(ddepth)); + } + }; + + G_TYPED_KERNEL(GLaplacian, , + "org.opencv.imgproc.filters.laplacian") { + static GMatDesc outMeta(GMatDesc in, int ddepth, int, double, double, int) { + return in.withDepth(ddepth); + } + }; + + G_TYPED_KERNEL(GBilateralFilter, , + "org.opencv.imgproc.filters.bilateralfilter") { + static GMatDesc outMeta(GMatDesc in, int, double, double, int) { + return in; + } + }; + + G_TYPED_KERNEL(GEqHist, , "org.opencv.imgproc.equalizeHist") { + static GMatDesc outMeta(GMatDesc in) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GCanny, , "org.opencv.imgproc.feature.canny") { + static GMatDesc outMeta(GMatDesc in, double, double, int, bool) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GGoodFeatures, + (GMat,int,double,double,Mat,int,bool,double)>, + "org.opencv.imgproc.feature.goodFeaturesToTrack") { + static GArrayDesc outMeta(GMatDesc, int, double, double, const Mat&, int, bool, double) { + return empty_array_desc(); + } + }; + + using RetrMode = RetrievalModes; + using ContMethod = ContourApproximationModes; + G_TYPED_KERNEL(GFindContours, >(GMat,RetrMode,ContMethod,GOpaque)>, + "org.opencv.imgproc.shape.findContours") + { + static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return empty_array_desc(); + } + }; + + // FIXME oc: make default value offset = Point() + G_TYPED_KERNEL(GFindContoursNoOffset, >(GMat,RetrMode,ContMethod)>, + "org.opencv.imgproc.shape.findContoursNoOffset") + { + static GArrayDesc outMeta(GMatDesc in, RetrMode mode, ContMethod) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return empty_array_desc(); + } + }; + + G_TYPED_KERNEL(GFindContoursH,)>, + "org.opencv.imgproc.shape.findContoursH") + { + static std::tuple + outMeta(GMatDesc in, RetrMode mode, ContMethod, GOpaqueDesc) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + }; + + // FIXME oc: make default value offset = Point() + G_TYPED_KERNEL(GFindContoursHNoOffset,, + "org.opencv.imgproc.shape.findContoursHNoOffset") + { + static std::tuple + outMeta(GMatDesc in, RetrMode mode, ContMethod) + { + validateFindingContoursMeta(in.depth, in.chan, mode); + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GBoundingRectMat, (GMat)>, + "org.opencv.imgproc.shape.boundingRectMat") { + static GOpaqueDesc outMeta(GMatDesc in) { + if (in.depth == CV_8U) + { + GAPI_Assert(in.chan == 1); + } + else + { + GAPI_Assert (in.depth == CV_32S || in.depth == CV_32F); + int amount = detail::checkVector(in, 2u); + GAPI_Assert(amount != -1 && + "Input Mat can't be described as vector of 2-dimentional points"); + } + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GBoundingRectVector32S, (GArray)>, + "org.opencv.imgproc.shape.boundingRectVector32S") { + static GOpaqueDesc outMeta(GArrayDesc) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GBoundingRectVector32F, (GArray)>, + "org.opencv.imgproc.shape.boundingRectVector32F") { + static GOpaqueDesc outMeta(GArrayDesc) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DMat, (GMat,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DMat") { + static GOpaqueDesc outMeta(GMatDesc in,DistanceTypes,double,double,double) { + int amount = detail::checkVector(in, 2u); + GAPI_Assert(amount != -1 && + "Input Mat can't be described as vector of 2-dimentional points"); + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DVector32S, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DVector32S") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DVector32F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DVector32F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine2DVector64F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine2DVector64F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DMat, (GMat,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DMat") { + static GOpaqueDesc outMeta(GMatDesc in,int,double,double,double) { + int amount = detail::checkVector(in, 3u); + GAPI_Assert(amount != -1 && + "Input Mat can't be described as vector of 3-dimentional points"); + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DVector32S, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DVector32S") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DVector32F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DVector32F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GFitLine3DVector64F, + (GArray,DistanceTypes,double,double,double)>, + "org.opencv.imgproc.shape.fitLine3DVector64F") { + static GOpaqueDesc outMeta(GArrayDesc,DistanceTypes,double,double,double) { + return empty_gopaque_desc(); + } + }; + + G_TYPED_KERNEL(GBGR2RGB, , "org.opencv.imgproc.colorconvert.bgr2rgb") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GRGB2YUV, , "org.opencv.imgproc.colorconvert.rgb2yuv") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GYUV2RGB, , "org.opencv.imgproc.colorconvert.yuv2rgb") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GBGR2I420, , "org.opencv.imgproc.colorconvert.bgr2i420") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + GAPI_Assert(in.size.height % 2 == 0); + return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); + } + }; + + G_TYPED_KERNEL(GRGB2I420, , "org.opencv.imgproc.colorconvert.rgb2i420") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + GAPI_Assert(in.size.height % 2 == 0); + return in.withType(in.depth, 1).withSize(Size(in.size.width, in.size.height * 3 / 2)); + } + }; + + G_TYPED_KERNEL(GI4202BGR, , "org.opencv.imgproc.colorconvert.i4202bgr") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 1); + GAPI_Assert(in.size.height % 3 == 0); + return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); + } + }; + + G_TYPED_KERNEL(GI4202RGB, , "org.opencv.imgproc.colorconvert.i4202rgb") { + static GMatDesc outMeta(GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 1); + GAPI_Assert(in.size.height % 3 == 0); + return in.withType(in.depth, 3).withSize(Size(in.size.width, in.size.height * 2 / 3)); + } + }; + + G_TYPED_KERNEL(GNV12toRGB, , "org.opencv.imgproc.colorconvert.nv12torgb") { + static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { + GAPI_Assert(in_y.chan == 1); + GAPI_Assert(in_uv.chan == 2); + GAPI_Assert(in_y.depth == CV_8U); + GAPI_Assert(in_uv.depth == CV_8U); + // UV size should be aligned with Y + GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); + GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); + return in_y.withType(CV_8U, 3); // type will be CV_8UC3; + } + }; + + G_TYPED_KERNEL(GNV12toBGR, , "org.opencv.imgproc.colorconvert.nv12tobgr") { + static GMatDesc outMeta(GMatDesc in_y, GMatDesc in_uv) { + GAPI_Assert(in_y.chan == 1); + GAPI_Assert(in_uv.chan == 2); + GAPI_Assert(in_y.depth == CV_8U); + GAPI_Assert(in_uv.depth == CV_8U); + // UV size should be aligned with Y + GAPI_Assert(in_y.size.width == 2 * in_uv.size.width); + GAPI_Assert(in_y.size.height == 2 * in_uv.size.height); + return in_y.withType(CV_8U, 3); // type will be CV_8UC3; + } + }; + + G_TYPED_KERNEL(GRGB2Lab, , "org.opencv.imgproc.colorconvert.rgb2lab") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GBGR2LUV, , "org.opencv.imgproc.colorconvert.bgr2luv") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GLUV2BGR, , "org.opencv.imgproc.colorconvert.luv2bgr") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GYUV2BGR, , "org.opencv.imgproc.colorconvert.yuv2bgr") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GBGR2YUV, , "org.opencv.imgproc.colorconvert.bgr2yuv") { + static GMatDesc outMeta(GMatDesc in) { + return in; // type still remains CV_8UC3; + } + }; + + G_TYPED_KERNEL(GRGB2Gray, , "org.opencv.imgproc.colorconvert.rgb2gray") { + static GMatDesc outMeta(GMatDesc in) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GRGB2GrayCustom, , "org.opencv.imgproc.colorconvert.rgb2graycustom") { + static GMatDesc outMeta(GMatDesc in, float, float, float) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GBGR2Gray, , "org.opencv.imgproc.colorconvert.bgr2gray") { + static GMatDesc outMeta(GMatDesc in) { + return in.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GBayerGR2RGB, , "org.opencv.imgproc.colorconvert.bayergr2rgb") { + static cv::GMatDesc outMeta(cv::GMatDesc in) { + return in.withType(CV_8U, 3); + } + }; + + G_TYPED_KERNEL(GRGB2HSV, , "org.opencv.imgproc.colorconvert.rgb2hsv") { + static cv::GMatDesc outMeta(cv::GMatDesc in) { + return in; + } + }; + + G_TYPED_KERNEL(GRGB2YUV422, , "org.opencv.imgproc.colorconvert.rgb2yuv422") { + static cv::GMatDesc outMeta(cv::GMatDesc in) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + return in.withType(in.depth, 2); + } + }; + + G_TYPED_KERNEL(GNV12toRGBp, , "org.opencv.imgproc.colorconvert.nv12torgbp") { + static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { + GAPI_Assert(inY.depth == CV_8U); + GAPI_Assert(inUV.depth == CV_8U); + GAPI_Assert(inY.chan == 1); + GAPI_Assert(inY.planar == false); + GAPI_Assert(inUV.chan == 2); + GAPI_Assert(inUV.planar == false); + GAPI_Assert(inY.size.width == 2 * inUV.size.width); + GAPI_Assert(inY.size.height == 2 * inUV.size.height); + return inY.withType(CV_8U, 3).asPlanar(); + } + }; + + G_TYPED_KERNEL(GNV12toGray, , "org.opencv.imgproc.colorconvert.nv12togray") { + static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { + GAPI_Assert(inY.depth == CV_8U); + GAPI_Assert(inUV.depth == CV_8U); + GAPI_Assert(inY.chan == 1); + GAPI_Assert(inY.planar == false); + GAPI_Assert(inUV.chan == 2); + GAPI_Assert(inUV.planar == false); + + GAPI_Assert(inY.size.width == 2 * inUV.size.width); + GAPI_Assert(inY.size.height == 2 * inUV.size.height); + return inY.withType(CV_8U, 1); + } + }; + + G_TYPED_KERNEL(GNV12toBGRp, , "org.opencv.imgproc.colorconvert.nv12tobgrp") { + static GMatDesc outMeta(GMatDesc inY, GMatDesc inUV) { + GAPI_Assert(inY.depth == CV_8U); + GAPI_Assert(inUV.depth == CV_8U); + GAPI_Assert(inY.chan == 1); + GAPI_Assert(inY.planar == false); + GAPI_Assert(inUV.chan == 2); + GAPI_Assert(inUV.planar == false); + GAPI_Assert(inY.size.width == 2 * inUV.size.width); + GAPI_Assert(inY.size.height == 2 * inUV.size.height); + return inY.withType(CV_8U, 3).asPlanar(); + } + }; + + G_TYPED_KERNEL(GResize, , "org.opencv.imgproc.transform.resize") { + static GMatDesc outMeta(GMatDesc in, Size sz, double fx, double fy, int /*interp*/) { + if (sz.width != 0 && sz.height != 0) + { + return in.withSize(sz); + } + else + { + int outSz_w = saturate_cast(in.size.width * fx); + int outSz_h = saturate_cast(in.size.height * fy); + GAPI_Assert(outSz_w > 0 && outSz_h > 0); + return in.withSize(Size(outSz_w, outSz_h)); + } + } + }; + + G_TYPED_KERNEL(GResizeP, , "org.opencv.imgproc.transform.resizeP") { + static GMatDesc outMeta(GMatDesc in, Size sz, int interp) { + GAPI_Assert(in.depth == CV_8U); + GAPI_Assert(in.chan == 3); + GAPI_Assert(in.planar); + GAPI_Assert(interp == cv::INTER_LINEAR); + return in.withSize(sz); + } + }; + +} //namespace imgproc + +//! @addtogroup gapi_filters +//! @{ +/** @brief Applies a separable linear filter to a matrix(image). + +The function applies a separable linear filter to the matrix. That is, first, every row of src is +filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D +kernel kernelY. The final result is returned. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - In case of floating-point computation, rounding to nearest even is procedeed +if hardware supports it (if not - to nearest value). + - Function textual ID is "org.opencv.imgproc.filters.sepfilter" +@param src Source image. +@param ddepth desired depth of the destination image (the following combinations of src.depth() and ddepth are supported: + + src.depth() = CV_8U, ddepth = -1/CV_16S/CV_32F/CV_64F + src.depth() = CV_16U/CV_16S, ddepth = -1/CV_32F/CV_64F + src.depth() = CV_32F, ddepth = -1/CV_32F/CV_64F + src.depth() = CV_64F, ddepth = -1/CV_64F + +when ddepth=-1, the output image will have the same depth as the source) +@param kernelX Coefficients for filtering each row. +@param kernelY Coefficients for filtering each column. +@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor +is at the kernel center. +@param delta Value added to the filtered results before storing them. +@param borderType Pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa boxFilter, gaussianBlur, medianBlur + */ +GAPI_EXPORTS_W GMat sepFilter(const GMat& src, int ddepth, const Mat& kernelX, const Mat& kernelY, const Point& anchor /*FIXME: = Point(-1,-1)*/, + const Scalar& delta /*FIXME = GScalar(0)*/, int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Convolves an image with the kernel. + +The function applies an arbitrary linear filter to an image. When +the aperture is partially outside the image, the function interpolates outlier pixel values +according to the specified border mode. + +The function does actually compute correlation, not the convolution: + +\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] + +That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip +the kernel using flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - +anchor.y - 1)`. + +Supported matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same size and number of channels an input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.filter2D" + +@param src input image. +@param ddepth desired depth of the destination image +@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point +matrix; if you want to apply different kernels to different channels, split the image into +separate color planes using split and process them individually. +@param anchor anchor of the kernel that indicates the relative position of a filtered point within +the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor +is at the kernel center. +@param delta optional value added to the filtered pixels before storing them in dst. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa sepFilter + */ +GAPI_EXPORTS_W GMat filter2D(const GMat& src, int ddepth, const Mat& kernel, const Point& anchor = Point(-1,-1), const Scalar& delta = Scalar(0), + int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); + + +/** @brief Blurs an image using the box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] + +where + +\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise} \end{cases}\f] + +Unnormalized box filter is useful for computing various integral characteristics over each pixel +neighborhood, such as covariance matrices of image derivatives (used in dense optical flow +algorithms, and so on). If you need to compute pixel sums over variable-size windows, use cv::integral. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.boxfilter" + +@param src Source image. +@param dtype the output image depth (-1 to set the input image data type). +@param ksize blurring kernel size. +@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor +is at the kernel center. +@param normalize flag, specifying whether the kernel is normalized by its area or not. +@param borderType Pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa sepFilter, gaussianBlur, medianBlur, integral + */ +GAPI_EXPORTS_W GMat boxFilter(const GMat& src, int dtype, const Size& ksize, const Point& anchor = Point(-1,-1), + bool normalize = true, int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Blurs an image using the normalized box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] + +The call `blur(src, ksize, anchor, borderType)` is equivalent to `boxFilter(src, src.type(), ksize, anchor, +true, borderType)`. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.blur" + +@param src Source image. +@param ksize blurring kernel size. +@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel +center. +@param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur + */ +GAPI_EXPORTS_W GMat blur(const GMat& src, const Size& ksize, const Point& anchor = Point(-1,-1), + int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); + + +//GAPI_EXPORTS_W void blur( InputArray src, OutputArray dst, + // Size ksize, Point anchor = Point(-1,-1), + // int borderType = BORDER_DEFAULT ); + + +/** @brief Blurs an image using a Gaussian filter. + +The function filter2Ds the source image with the specified Gaussian kernel. +Output image must have the same type and number of channels an input image. + +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.gaussianBlur" + +@param src input image; +@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be +positive and odd. Or, they can be zero's and then they are computed from sigma. +@param sigmaX Gaussian kernel standard deviation in X direction. +@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be +equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, +respectively (see cv::getGaussianKernel for details); to fully control the result regardless of +possible future modifications of all this semantics, it is recommended to specify all of ksize, +sigmaX, and sigmaY. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa sepFilter, boxFilter, medianBlur + */ +GAPI_EXPORTS_W GMat gaussianBlur(const GMat& src, const Size& ksize, double sigmaX, double sigmaY = 0, + int borderType = BORDER_DEFAULT, const Scalar& borderValue = Scalar(0)); + +/** @brief Blurs an image using the median filter. + +The function smoothes an image using the median filter with the \f$\texttt{ksize} \times +\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. +The median filter uses cv::BORDER_REPLICATE internally to cope with border pixels, see cv::BorderTypes + - Function textual ID is "org.opencv.imgproc.filters.medianBlur" + +@param src input matrix (image) +@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... +@sa boxFilter, gaussianBlur + */ +GAPI_EXPORTS_W GMat medianBlur(const GMat& src, int ksize); + +/** @brief Erodes an image by using a specific structuring element. + +The function erodes the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the minimum is taken: + +\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.erode" + +@param src input image +@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular +structuring element is used. Kernel can be created using getStructuringElement. +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times erosion is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa dilate, morphologyEx + */ +GAPI_EXPORTS_W GMat erode(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Erodes an image by using 3 by 3 rectangular structuring element. + +The function erodes the source image using the rectangular structuring element with rectangle center as an anchor. +Erosion can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.erode" + +@param src input image +@param iterations number of times erosion is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa erode, dilate3x3 + */ +GAPI_EXPORTS_W GMat erode3x3(const GMat& src, int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Dilates an image by using a specific structuring element. + +The function dilates the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the maximum is taken: +\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.dilate" + +@param src input image. +@param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular +structuring element is used. Kernel can be created using getStructuringElement +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times dilation is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa erode, morphologyEx, getStructuringElement + */ +GAPI_EXPORTS_W GMat dilate(const GMat& src, const Mat& kernel, const Point& anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Dilates an image by using 3 by 3 rectangular structuring element. + +The function dilates the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the maximum is taken: +\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +Dilation can be applied several (iterations) times. In case of multi-channel images, each channel is processed independently. +Supported input matrix data types are @ref CV_8UC1, @ref CV_8UC3, @ref CV_16UC1, @ref CV_16SC1, and @ref CV_32FC1. +Output image must have the same type, size, and number of channels as the input image. +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.dilate" + +@param src input image. +@param iterations number of times dilation is applied. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of a constant border +@sa dilate, erode3x3 + */ + +GAPI_EXPORTS_W GMat dilate3x3(const GMat& src, int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue()); + +/** @brief Performs advanced morphological transformations. + +The function can perform advanced morphological transformations using an erosion and dilation as +basic operations. + +Any of the operations can be done in-place. In case of multi-channel images, each channel is +processed independently. + +@note + - Function textual ID is "org.opencv.imgproc.filters.morphologyEx" + - The number of iterations is the number of times erosion or dilatation operation will be +applied. For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to +apply successively: erode -> erode -> dilate -> dilate +(and not erode -> dilate -> erode -> dilate). + +@param src Input image. +@param op Type of a morphological operation, see #MorphTypes +@param kernel Structuring element. It can be created using #getStructuringElement. +@param anchor Anchor position within the element. Both negative values mean that the anchor is at +the kernel center. +@param iterations Number of times erosion and dilation are applied. +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param borderValue Border value in case of a constant border. The default value has a special +meaning. +@sa dilate, erode, getStructuringElement + */ +GAPI_EXPORTS_W GMat morphologyEx(const GMat &src, const MorphTypes op, const Mat &kernel, + const Point &anchor = Point(-1,-1), + const int iterations = 1, + const BorderTypes borderType = BORDER_CONSTANT, + const Scalar &borderValue = morphologyDefaultBorderValue()); + +/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. + +In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to +calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ +kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first +or the second x- or y- derivatives. + +There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr +filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is + +\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] + +for the x-derivative, or transposed for the y-derivative. + +The function calculates an image derivative by convolving the image with the appropriate kernel: + +\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] + +The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less +resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) +or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first +case corresponds to a kernel of: + +\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] + +The second case corresponds to a kernel of: + +\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] + +@note + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.sobel" + +@param src input image. +@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of + 8-bit input images it will result in truncated derivatives. +@param dx order of the derivative x. +@param dy order of the derivative y. +@param ksize size of the extended Sobel kernel; it must be odd. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see cv::getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa filter2D, gaussianBlur, cartToPolar + */ +GAPI_EXPORTS_W GMat Sobel(const GMat& src, int ddepth, int dx, int dy, int ksize = 3, + double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. + +In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to +calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ +kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first +or the second x- or y- derivatives. + +There is also the special value `ksize = FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr +filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is + +\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] + +for the x-derivative, or transposed for the y-derivative. + +The function calculates an image derivative by convolving the image with the appropriate kernel: + +\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] + +The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less +resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) +or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first +case corresponds to a kernel of: + +\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] + +The second case corresponds to a kernel of: + +\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] + +@note + - First returned matrix correspons to dx derivative while the second one to dy. + - Rounding to nearest even is procedeed if hardware supports it, if not - to nearest. + - Function textual ID is "org.opencv.imgproc.filters.sobelxy" + +@param src input image. +@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of + 8-bit input images it will result in truncated derivatives. +@param order order of the derivatives. +@param ksize size of the extended Sobel kernel; it must be odd. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see cv::getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see cv::BorderTypes +@param borderValue border value in case of constant border type +@sa filter2D, gaussianBlur, cartToPolar + */ +GAPI_EXPORTS_W std::tuple SobelXY(const GMat& src, int ddepth, int order, int ksize = 3, + double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT, + const Scalar& borderValue = Scalar(0)); + +/** @brief Calculates the Laplacian of an image. + +The function calculates the Laplacian of the source image by adding up the second x and y +derivatives calculated using the Sobel operator: + +\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] + +This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image +with the following \f$3 \times 3\f$ aperture: + +\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] + +@note Function textual ID is "org.opencv.imgproc.filters.laplacian" + +@param src Source image. +@param ddepth Desired depth of the destination image. +@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for +details. The size must be positive and odd. +@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is +applied. See #getDerivKernels for details. +@param delta Optional delta value that is added to the results prior to storing them in dst . +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@return Destination image of the same size and the same number of channels as src. +@sa Sobel, Scharr + */ +GAPI_EXPORTS_W GMat Laplacian(const GMat& src, int ddepth, int ksize = 1, + double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT); + +/** @brief Applies the bilateral filter to an image. + +The function applies bilateral filtering to the input image, as described in +http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html +bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is +very slow compared to most filters. + +_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< +10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very +strong effect, making the image look "cartoonish". + +_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time +applications, and perhaps d=9 for offline applications that need heavy noise filtering. + +This filter does not work inplace. + +@note Function textual ID is "org.opencv.imgproc.filters.bilateralfilter" + +@param src Source 8-bit or floating-point, 1-channel or 3-channel image. +@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, +it is computed from sigmaSpace. +@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that +farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting +in larger areas of semi-equal color. +@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that +farther pixels will influence each other as long as their colors are close enough (see sigmaColor +). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is +proportional to sigmaSpace. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes +@return Destination image of the same size and type as src. + */ +GAPI_EXPORTS_W GMat bilateralFilter(const GMat& src, int d, double sigmaColor, double sigmaSpace, + int borderType = BORDER_DEFAULT); + +//! @} gapi_filters + +//! @addtogroup gapi_feature +//! @{ +/** @brief Finds edges in an image using the Canny algorithm. + +The function finds edges in the input image and marks them in the output map edges using the +Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The +largest value is used to find initial segments of strong edges. See + + +@note Function textual ID is "org.opencv.imgproc.feature.canny" + +@param image 8-bit input image. +@param threshold1 first threshold for the hysteresis procedure. +@param threshold2 second threshold for the hysteresis procedure. +@param apertureSize aperture size for the Sobel operator. +@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm +\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( +L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( +L2gradient=false ). + */ +GAPI_EXPORTS_W GMat Canny(const GMat& image, double threshold1, double threshold2, + int apertureSize = 3, bool L2gradient = false); + +/** @brief Determines strong corners on an image. + +The function finds the most prominent corners in the image or in the specified image region, as +described in @cite Shi94 + +- Function calculates the corner quality measure at every source image pixel using the + #cornerMinEigenVal or #cornerHarris . +- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are + retained). +- The corners with the minimal eigenvalue less than + \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. +- The remaining corners are sorted by the quality measure in the descending order. +- Function throws away each corner for which there is a stronger corner at a distance less than + maxDistance. + +The function can be used to initialize a point-based tracker of an object. + +@note + - If the function is called with different values A and B of the parameter qualityLevel , and +A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector +with qualityLevel=B . + - Function textual ID is "org.opencv.imgproc.feature.goodFeaturesToTrack" + +@param image Input 8-bit or floating-point 32-bit, single-channel image. +@param maxCorners Maximum number of corners to return. If there are more corners than are found, +the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set +and all detected corners are returned. +@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The +parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue +(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the +quality measure less than the product are rejected. For example, if the best corner has the +quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure +less than 15 are rejected. +@param minDistance Minimum possible Euclidean distance between the returned corners. +@param mask Optional region of interest. If the image is not empty (it needs to have the type +CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. +@param blockSize Size of an average block for computing a derivative covariation matrix over each +pixel neighborhood. See cornerEigenValsAndVecs . +@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) +or #cornerMinEigenVal. +@param k Free parameter of the Harris detector. + +@return vector of detected corners. + */ +GAPI_EXPORTS_W GArray goodFeaturesToTrack(const GMat &image, + int maxCorners, + double qualityLevel, + double minDistance, + const Mat &mask = Mat(), + int blockSize = 3, + bool useHarrisDetector = false, + double k = 0.04); + +/** @brief Equalizes the histogram of a grayscale image. + +//! @} gapi_feature + +The function equalizes the histogram of the input image using the following algorithm: + +- Calculate the histogram \f$H\f$ for src . +- Normalize the histogram so that the sum of histogram bins is 255. +- Compute the integral of the histogram: +\f[H'_i = \sum _{0 \le j < i} H(j)\f] +- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ + +The algorithm normalizes the brightness and increases the contrast of the image. +@note + - The returned image is of the same size and type as input. + - Function textual ID is "org.opencv.imgproc.equalizeHist" + +@param src Source 8-bit single channel image. + */ +GAPI_EXPORTS_W GMat equalizeHist(const GMat& src); + +//! @addtogroup gapi_shape +//! @{ +/** @brief Finds contours in a binary image. + +The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . +The contours are a useful tool for shape analysis and object detection and recognition. +See squares.cpp in the OpenCV sample directory. + +@note Function textual ID is "org.opencv.imgproc.shape.findContours" + +@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero +pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , +#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. +If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer +image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL then @ref CV_32SC1 is supported only. +@param mode Contour retrieval mode, see #RetrievalModes +@param method Contour approximation method, see #ContourApproximationModes +@param offset Optional offset by which every contour point is shifted. This is useful if the +contours are extracted from the image ROI and then they should be analyzed in the whole image +context. + +@return GArray of detected contours. Each contour is stored as a GArray of points. + */ +GAPI_EXPORTS GArray> +findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, + const GOpaque &offset); + +// FIXME oc: make default value offset = Point() +/** @overload +@note Function textual ID is "org.opencv.imgproc.shape.findContoursNoOffset" + */ +GAPI_EXPORTS GArray> +findContours(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); + +/** @brief Finds contours and their hierarchy in a binary image. + +The function retrieves contours from the binary image using the algorithm @cite Suzuki85 +and calculates their hierarchy. +The contours are a useful tool for shape analysis and object detection and recognition. +See squares.cpp in the OpenCV sample directory. + +@note Function textual ID is "org.opencv.imgproc.shape.findContoursH" + +@param src Input gray-scale image @ref CV_8UC1. Non-zero pixels are treated as 1's. Zero +pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , +#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. +If mode equals to #RETR_CCOMP, the input can also be a 32-bit integer +image of labels ( @ref CV_32SC1 ). If #RETR_FLOODFILL -- @ref CV_32SC1 supports only. +@param mode Contour retrieval mode, see #RetrievalModes +@param method Contour approximation method, see #ContourApproximationModes +@param offset Optional offset by which every contour point is shifted. This is useful if the +contours are extracted from the image ROI and then they should be analyzed in the whole image +context. + +@return + - GArray of detected contours. Each contour is stored as a GArray of points. + - Optional output GArray of cv::Vec4i, containing information about the image topology. +It has as many elements as the number of contours. For each i-th contour contours[i], the elements +hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based +indices in contours of the next and previous contours at the same hierarchical level, the first +child contour and the parent contour, respectively. If for the contour i there are no next, +previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. + */ +GAPI_EXPORTS std::tuple>,GArray> +findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method, + const GOpaque &offset); + +// FIXME oc: make default value offset = Point() +/** @overload +@note Function textual ID is "org.opencv.imgproc.shape.findContoursHNoOffset" + */ +GAPI_EXPORTS std::tuple>,GArray> +findContoursH(const GMat &src, const RetrievalModes mode, const ContourApproximationModes method); + +/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels +of gray-scale image. + +The function calculates and returns the minimal up-right bounding rectangle for the specified +point set or non-zero pixels of gray-scale image. + +@note + - Function textual ID is "org.opencv.imgproc.shape.boundingRectMat" + - In case of a 2D points' set given, Mat should be 2-dimensional, have a single row or column +if there are 2 channels, or have 2 columns if there is a single channel. Mat should have either +@ref CV_32S or @ref CV_32F depth + +@param src Input gray-scale image @ref CV_8UC1; or input set of @ref CV_32S or @ref CV_32F +2D points stored in Mat. + */ +GAPI_EXPORTS_W GOpaque boundingRect(const GMat& src); + +/** @overload + +Calculates the up-right bounding rectangle of a point set. + +@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32S" + +@param src Input 2D point set, stored in std::vector. + */ +GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); + +/** @overload + +Calculates the up-right bounding rectangle of a point set. + +@note Function textual ID is "org.opencv.imgproc.shape.boundingRectVector32F" + +@param src Input 2D point set, stored in std::vector. + */ +GAPI_EXPORTS_W GOpaque boundingRect(const GArray& src); + +/** @brief Fits a line to a 2D point set. + +The function fits a line to a 2D point set by minimizing \f$\sum_i \rho(r_i)\f$ where +\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance +function, one of the following: +- DIST_L2 +\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] +- DIST_L1 +\f[\rho (r) = r\f] +- DIST_L12 +\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] +- DIST_FAIR +\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] +- DIST_WELSCH +\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] +- DIST_HUBER +\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] + +The algorithm is based on the M-estimator ( ) technique +that iteratively fits the line using the weighted least-squares algorithm. After each iteration the +weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . + +@note + - Function textual ID is "org.opencv.imgproc.shape.fitLine2DMat" + - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row +or column if there are N channels, or have N columns if there is a single channel. + +@param src Input set of 2D points stored in one of possible containers: Mat, +std::vector, std::vector, std::vector. +@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER +and @ref DIST_C are not supported. +@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value +is chosen. +@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the +line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. +@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. +If it is 0, a default value is chosen. + +@return Output line parameters: a vector of 4 elements (like Vec4f) - (vx, vy, x0, y0), +where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line. + */ +GAPI_EXPORTS GOpaque fitLine2D(const GMat& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32S" + + */ +GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector32F" + + */ +GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine2DVector64F" + + */ +GAPI_EXPORTS GOpaque fitLine2D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @brief Fits a line to a 3D point set. + +The function fits a line to a 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where +\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance +function, one of the following: +- DIST_L2 +\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] +- DIST_L1 +\f[\rho (r) = r\f] +- DIST_L12 +\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] +- DIST_FAIR +\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] +- DIST_WELSCH +\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] +- DIST_HUBER +\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] + +The algorithm is based on the M-estimator ( ) technique +that iteratively fits the line using the weighted least-squares algorithm. After each iteration the +weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . + +@note + - Function textual ID is "org.opencv.imgproc.shape.fitLine3DMat" + - In case of an N-dimentional points' set given, Mat should be 2-dimensional, have a single row +or column if there are N channels, or have N columns if there is a single channel. + +@param src Input set of 3D points stored in one of possible containers: Mat, +std::vector, std::vector, std::vector. +@param distType Distance used by the M-estimator, see #DistanceTypes. @ref DIST_USER +and @ref DIST_C are not supported. +@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value +is chosen. +@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the +line). 1.0 would be a good default value for reps. If it is 0, a default value is chosen. +@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for aeps. +If it is 0, a default value is chosen. + +@return Output line parameters: a vector of 6 elements (like Vec6f) - (vx, vy, vz, x0, y0, z0), +where (vx, vy, vz) is a normalized vector collinear to the line and (x0, y0, z0) is a point on +the line. + */ +GAPI_EXPORTS GOpaque fitLine3D(const GMat& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32S" + + */ +GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector32F" + + */ +GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +/** @overload + +@note Function textual ID is "org.opencv.imgproc.shape.fitLine3DVector64F" + + */ +GAPI_EXPORTS GOpaque fitLine3D(const GArray& src, const DistanceTypes distType, + const double param = 0., const double reps = 0., + const double aeps = 0.); + +//! @} gapi_shape + +//! @addtogroup gapi_colorconvert +//! @{ +/** @brief Converts an image from BGR color space to RGB color space. + +The function converts an input image from BGR color space to RGB. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image is 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2rgb" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa RGB2BGR +*/ +GAPI_EXPORTS_W GMat BGR2RGB(const GMat& src); + +/** @brief Converts an image from RGB color space to gray-scaled. + +The conventional ranges for R, G, and B channel values are 0 to 255. +Resulting gray color value computed as +\f[\texttt{dst} (I)= \texttt{0.299} * \texttt{src}(I).R + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.114} * \texttt{src}(I).B \f] + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2gray" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@sa RGB2YUV + */ +GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src); + +/** @overload +Resulting gray color value computed as +\f[\texttt{dst} (I)= \texttt{rY} * \texttt{src}(I).R + \texttt{gY} * \texttt{src}(I).G + \texttt{bY} * \texttt{src}(I).B \f] + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2graycustom" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@param rY float multiplier for R channel. +@param gY float multiplier for G channel. +@param bY float multiplier for B channel. +@sa RGB2YUV + */ +GAPI_EXPORTS_W GMat RGB2Gray(const GMat& src, float rY, float gY, float bY); + +/** @brief Converts an image from BGR color space to gray-scaled. + +The conventional ranges for B, G, and R channel values are 0 to 255. +Resulting gray color value computed as +\f[\texttt{dst} (I)= \texttt{0.114} * \texttt{src}(I).B + \texttt{0.587} * \texttt{src}(I).G + \texttt{0.299} * \texttt{src}(I).R \f] + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2gray" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@sa BGR2LUV + */ +GAPI_EXPORTS_W GMat BGR2Gray(const GMat& src); + +/** @brief Converts an image from RGB color space to YUV color space. + +The function converts an input image from RGB color space to YUV. +The conventional ranges for R, G, and B channel values are 0 to 255. + +In case of linear transformations, the range does not matter. But in case of a non-linear +transformation, an input RGB image should be normalized to the proper value range to get the correct +results, like here, at RGB \f$\rightarrow\f$ Y\*u\*v\* transformation. +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa YUV2RGB, RGB2Lab +*/ +GAPI_EXPORTS_W GMat RGB2YUV(const GMat& src); + +/** @brief Converts an image from BGR color space to I420 color space. + +The function converts an input image from BGR color space to I420. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. +Width of I420 output image must be the same as width of input image. +Height of I420 output image must be equal 3/2 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2i420" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa I4202BGR +*/ +GAPI_EXPORTS_W GMat BGR2I420(const GMat& src); + +/** @brief Converts an image from RGB color space to I420 color space. + +The function converts an input image from RGB color space to I420. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 1-channel image. @ref CV_8UC1. +Width of I420 output image must be the same as width of input image. +Height of I420 output image must be equal 3/2 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2i420" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa I4202RGB +*/ +GAPI_EXPORTS_W GMat RGB2I420(const GMat& src); + +/** @brief Converts an image from I420 color space to BGR color space. + +The function converts an input image from I420 color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. +Width of BGR output image must be the same as width of input image. +Height of BGR output image must be equal 2/3 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202bgr" + +@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@sa BGR2I420 +*/ +GAPI_EXPORTS_W GMat I4202BGR(const GMat& src); + +/** @brief Converts an image from I420 color space to BGR color space. + +The function converts an input image from I420 color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image. @ref CV_8UC3. +Width of RGB output image must be the same as width of input image. +Height of RGB output image must be equal 2/3 from height of input image. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.i4202rgb" + +@param src input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@sa RGB2I420 +*/ +GAPI_EXPORTS_W GMat I4202RGB(const GMat& src); + +/** @brief Converts an image from BGR color space to LUV color space. + +The function converts an input image from BGR color space to LUV. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2luv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa RGB2Lab, RGB2LUV +*/ +GAPI_EXPORTS_W GMat BGR2LUV(const GMat& src); + +/** @brief Converts an image from LUV color space to BGR color space. + +The function converts an input image from LUV color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.luv2bgr" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa BGR2LUV +*/ +GAPI_EXPORTS_W GMat LUV2BGR(const GMat& src); + +/** @brief Converts an image from YUV color space to BGR color space. + +The function converts an input image from YUV color space to BGR. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2bgr" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa BGR2YUV +*/ +GAPI_EXPORTS_W GMat YUV2BGR(const GMat& src); + +/** @brief Converts an image from BGR color space to YUV color space. + +The function converts an input image from BGR color space to YUV. +The conventional ranges for B, G, and R channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bgr2yuv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@sa YUV2BGR +*/ +GAPI_EXPORTS_W GMat BGR2YUV(const GMat& src); + +/** @brief Converts an image from RGB color space to Lab color space. + +The function converts an input image from BGR color space to Lab. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2lab" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC1. +@sa RGB2YUV, RGB2LUV +*/ +GAPI_EXPORTS_W GMat RGB2Lab(const GMat& src); + +/** @brief Converts an image from YUV color space to RGB. +The function converts an input image from YUV color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.yuv2rgb" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. + +@sa RGB2Lab, RGB2YUV +*/ +GAPI_EXPORTS_W GMat YUV2RGB(const GMat& src); + +/** @brief Converts an image from NV12 (YUV420p) color space to RGB. +The function converts an input image from NV12 color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgb" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toBGR +*/ +GAPI_EXPORTS_W GMat NV12toRGB(const GMat& src_y, const GMat& src_uv); + +/** @brief Converts an image from NV12 (YUV420p) color space to gray-scaled. +The function converts an input image from NV12 color space to gray-scaled. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 1-channel image @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12togray" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toBGR +*/ +GAPI_EXPORTS_W GMat NV12toGray(const GMat& src_y, const GMat& src_uv); + +/** @brief Converts an image from NV12 (YUV420p) color space to BGR. +The function converts an input image from NV12 color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12tobgr" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat NV12toBGR(const GMat& src_y, const GMat& src_uv); + +/** @brief Converts an image from BayerGR color space to RGB. +The function converts an input image from BayerGR color space to RGB. +The conventional ranges for G, R, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.bayergr2rgb" + +@param src_gr input image: 8-bit unsigned 1-channel image @ref CV_8UC1. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat BayerGR2RGB(const GMat& src_gr); + +/** @brief Converts an image from RGB color space to HSV. +The function converts an input image from RGB color space to HSV. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 3-channel image @ref CV_8UC3. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2hsv" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat RGB2HSV(const GMat& src); + +/** @brief Converts an image from RGB color space to YUV422. +The function converts an input image from RGB color space to YUV422. +The conventional ranges for R, G, and B channel values are 0 to 255. + +Output image must be 8-bit unsigned 2-channel image @ref CV_8UC2. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.rgb2yuv422" + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3. + +@sa YUV2BGR, NV12toRGB +*/ +GAPI_EXPORTS_W GMat RGB2YUV422(const GMat& src); + +/** @brief Converts an image from NV12 (YUV420p) color space to RGB. +The function converts an input image from NV12 color space to RGB. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. +Planar image memory layout is three planes laying in the memory contiguously, +so the image height should be plane_height*plane_number, +image type is @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toBGRp, NV12toRGB +*/ +GAPI_EXPORTS GMatP NV12toRGBp(const GMat &src_y, const GMat &src_uv); + +/** @brief Converts an image from NV12 (YUV420p) color space to BGR. +The function converts an input image from NV12 color space to BGR. +The conventional ranges for Y, U, and V channel values are 0 to 255. + +Output image must be 8-bit unsigned planar 3-channel image @ref CV_8UC1. +Planar image memory layout is three planes laying in the memory contiguously, +so the image height should be plane_height*plane_number, +image type is @ref CV_8UC1. + +@note Function textual ID is "org.opencv.imgproc.colorconvert.nv12torgbp" + +@param src_y input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param src_uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2. + +@sa YUV2RGB, NV12toRGBp, NV12toBGR +*/ +GAPI_EXPORTS GMatP NV12toBGRp(const GMat &src_y, const GMat &src_uv); + +//! @} gapi_colorconvert +//! @addtogroup gapi_transform +//! @{ +/** @brief Resizes an image. + +The function resizes the image src down to or up to the specified size. + +Output image size will have the size dsize (when dsize is non-zero) or the size computed from +src.size(), fx, and fy; the depth of output is the same as of src. + +If you want to resize src so that it fits the pre-created dst, +you may call the function as follows: +@code + // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + resize(src, dst, dst.size(), 0, 0, interpolation); +@endcode +If you want to decimate the image by factor of 2 in each direction, you can call the function this +way: +@code + // specify fx and fy and let the function compute the destination image size. + resize(src, dst, Size(), 0.5, 0.5, interpolation); +@endcode +To shrink an image, it will generally look best with cv::INTER_AREA interpolation, whereas to +enlarge an image, it will generally look best with cv::INTER_CUBIC (slow) or cv::INTER_LINEAR +(faster but still looks OK). + +@note Function textual ID is "org.opencv.imgproc.transform.resize" + +@param src input image. +@param dsize output image size; if it equals zero, it is computed as: + \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] + Either dsize or both fx and fy must be non-zero. +@param fx scale factor along the horizontal axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.width/src.cols}\f] +@param fy scale factor along the vertical axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.height/src.rows}\f] +@param interpolation interpolation method, see cv::InterpolationFlags + +@sa warpAffine, warpPerspective, remap, resizeP + */ +GAPI_EXPORTS_W GMat resize(const GMat& src, const Size& dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR); + +/** @brief Resizes a planar image. + +The function resizes the image src down to or up to the specified size. +Planar image memory layout is three planes laying in the memory contiguously, +so the image height should be plane_height*plane_number, image type is @ref CV_8UC1. + +Output image size will have the size dsize, the depth of output is the same as of src. + +@note Function textual ID is "org.opencv.imgproc.transform.resizeP" + +@param src input image, must be of @ref CV_8UC1 type; +@param dsize output image size; +@param interpolation interpolation method, only cv::INTER_LINEAR is supported at the moment + +@sa warpAffine, warpPerspective, remap, resize + */ +GAPI_EXPORTS GMatP resizeP(const GMatP& src, const Size& dsize, int interpolation = cv::INTER_LINEAR); + +//! @} gapi_transform +} //namespace gapi +} //namespace cv + +#endif // OPENCV_GAPI_IMGPROC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp index 4aa2484f02..abbd32ba20 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer.hpp @@ -1,717 +1,717 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_INFER_HPP -#define OPENCV_GAPI_INFER_HPP - -// FIXME: Inference API is currently only available in full mode -#if !defined(GAPI_STANDALONE) - -#include -#include // string -#include // tuple -#include // is_same, false_type - -#include // all_satisfy -#include // any<> -#include // GKernelType[M], GBackend -#include // GArg -#include // CompileArgTag -#include // GMetaArg - -namespace cv { - -template class GNetworkType; - -namespace detail { - -// Infer /////////////////////////////////////////////////////////////////////// -template -struct accepted_infer_types { - static constexpr const auto value = - std::is_same::type, cv::GMat>::value - || std::is_same::type, cv::GFrame>::value; -}; - -template -using valid_infer_types = all_satisfy; - -// Infer2 ////////////////////////////////////////////////////////////////////// - -template -struct valid_infer2_types; - -// Terminal case 1 (50/50 success) -template -struct valid_infer2_types< std::tuple, std::tuple > { - // By default, Nets are limited to GMat argument types only - // for infer2, every GMat argument may translate to either - // GArray or GArray. GArray<> part is stripped - // already at this point. - static constexpr const auto value = - std::is_same::type, cv::GMat>::value - || std::is_same::type, cv::Rect>::value; -}; - -// Terminal case 2 (100% failure) -template -struct valid_infer2_types< std::tuple<>, std::tuple > - : public std::false_type { -}; - -// Terminal case 3 (100% failure) -template -struct valid_infer2_types< std::tuple, std::tuple<> > - : public std::false_type { -}; - -// Recursion -- generic -template -struct valid_infer2_types< std::tuple, std::tuple > { - static constexpr const auto value = - valid_infer2_types< std::tuple, std::tuple >::value - && valid_infer2_types< std::tuple, std::tuple >::value; -}; - -// Struct stores network input/output names. -// Used by infer -struct InOutInfo -{ - std::vector in_names; - std::vector out_names; -}; - -template -class GInferOutputsTyped -{ -public: - GInferOutputsTyped() = default; - GInferOutputsTyped(std::shared_ptr call) - : m_priv(std::make_shared(std::move(call))) - { - } - - OutT at(const std::string& name) - { - auto it = m_priv->blobs.find(name); - if (it == m_priv->blobs.end()) { - // FIXME: Avoid modifying GKernel - auto shape = cv::detail::GTypeTraits::shape; - auto kind = cv::detail::GTypeTraits::op_kind; - m_priv->call->kernel().outShapes.push_back(shape); - m_priv->call->kernel().outCtors.emplace_back(cv::detail::GObtainCtor::get()); - m_priv->call->kernel().outKinds.emplace_back(kind); - auto out_idx = static_cast(m_priv->blobs.size()); - it = m_priv->blobs.emplace(name, - cv::detail::Yield::yield(*(m_priv->call), out_idx)).first; - m_priv->info->out_names.push_back(name); - } - return it->second; - } -private: - struct Priv - { - Priv(std::shared_ptr c) - : call(std::move(c)), info(cv::util::any_cast(&call->params())) - { - } - - std::shared_ptr call; - InOutInfo* info = nullptr; - std::unordered_map blobs; - }; - - std::shared_ptr m_priv; -}; - -template -class GInferInputsTyped -{ -public: - GInferInputsTyped() - : m_priv(std::make_shared()) - { - } - - template - GInferInputsTyped& setInput(const std::string& name, U in) - { - m_priv->blobs.emplace(std::piecewise_construct, - std::forward_as_tuple(name), - std::forward_as_tuple(in)); - return *this; - } - - using StorageT = cv::util::variant; - StorageT& operator[](const std::string& name) { - return m_priv->blobs[name]; - } - - using Map = std::unordered_map; - const Map& getBlobs() const { - return m_priv->blobs; - } - -private: - struct Priv - { - std::unordered_map blobs; - }; - - std::shared_ptr m_priv; -}; - -template -std::shared_ptr makeCall(const std::string &tag, - std::vector &&args, - std::vector &&names, - cv::GKinds &&kinds) { - auto call = std::make_shared(GKernel{ - InferT::id(), - tag, - InferT::getOutMeta, - {}, // outShape will be filled later - std::move(kinds), - {}, // outCtors will be filled later - {}, // outKinds will be filled later - }); - - call->setArgs(std::move(args)); - call->params() = cv::detail::InOutInfo{std::move(names), {}}; - - return call; -} - -} // namespace detail - -// TODO: maybe tuple_wrap_helper from util.hpp may help with this. -// Multiple-return-value network definition (specialized base class) -template -class GNetworkType(Args...)> > -{ -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - using Result = OutArgs; - using API = std::function; - - using ResultL = std::tuple< cv::GArray... >; -}; - -// Single-return-value network definition (specialized base class) -template -class GNetworkType > -{ -public: - using InArgs = std::tuple; - using OutArgs = std::tuple; - - using Result = R; - using API = std::function; - - using ResultL = cv::GArray; -}; - -// InferAPI: Accepts either GMat or GFrame for very individual network's input -template -struct InferAPI { - using type = typename std::enable_if - < detail::valid_infer_types::value - && std::tuple_size::value == sizeof...(Ts) - , std::function - >::type; -}; - -// InferAPIRoi: Accepts a rectangle and either GMat or GFrame -template -struct InferAPIRoi { - using type = typename std::enable_if - < detail::valid_infer_types::value - && std::tuple_size::value == 1u - , std::function, T)> - >::type; -}; - -// InferAPIList: Accepts a list of rectangles and list of GMat/GFrames; -// crops every input. -template -struct InferAPIList { - using type = typename std::enable_if - < detail::valid_infer_types::value - && std::tuple_size::value == sizeof...(Ts) - , std::function, Ts...)> - >::type; -}; - -// APIList2 is also template to allow different calling options -// (GArray vs GArray per input) -template -struct InferAPIList2 { - using type = typename std::enable_if - < detail::valid_infer_types::value && - cv::detail::valid_infer2_types< typename Net::InArgs - , std::tuple >::value, - std::function...)> - >::type; -}; - -// Base "Infer" kernel. Note - for whatever network, kernel ID -// is always the same. Different inference calls are distinguished by -// network _tag_ (an extra field in GCall) -// -// getOutMeta is a stub callback collected by G-API kernel subsystem -// automatically. This is a rare case when this callback is defined by -// a particular backend, not by a network itself. -struct GInferBase { - static constexpr const char * id() { - return "org.opencv.dnn.infer"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// Base "InferROI" kernel. -// All notes from "Infer" kernel apply here as well. -struct GInferROIBase { - static constexpr const char * id() { - return "org.opencv.dnn.infer-roi"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// Base "Infer list" kernel. -// All notes from "Infer" kernel apply here as well. -struct GInferListBase { - static constexpr const char * id() { - return "org.opencv.dnn.infer-roi-list-1"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// Base "Infer list 2" kernel. -// All notes from "Infer" kernel apply here as well. -struct GInferList2Base { - static constexpr const char * id() { - return "org.opencv.dnn.infer-roi-list-2"; // Universal stub - } - static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { - return GMetaArgs{}; // One more universal stub - } -}; - -// A generic inference kernel. API (::on()) is fully defined by the Net -// template parameter. -// Acts as a regular kernel in graph (via KernelTypeMedium). -template -struct GInfer final - : public GInferBase - , public detail::KernelTypeMedium< GInfer - , typename InferAPI::type > { - using GInferBase::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - -// A specific roi-inference kernel. API (::on()) is fixed here and -// verified against Net. -template -struct GInferROI final - : public GInferROIBase - , public detail::KernelTypeMedium< GInferROI - , typename InferAPIRoi::type > { - using GInferROIBase::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - - -// A generic roi-list inference kernel. API (::on()) is derived from -// the Net template parameter (see more in infer<> overload). -template -struct GInferList final - : public GInferListBase - , public detail::KernelTypeMedium< GInferList - , typename InferAPIList::type > { - using GInferListBase::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - -// An even more generic roi-list inference kernel. API (::on()) is -// derived from the Net template parameter (see more in infer<> -// overload). -// Takes an extra variadic template list to reflect how this network -// was called (with Rects or GMats as array parameters) -template -struct GInferList2 final - : public GInferList2Base - , public detail::KernelTypeMedium< GInferList2 - , typename InferAPIList2::type > { - using GInferList2Base::getOutMeta; // FIXME: name lookup conflict workaround? - - static constexpr const char* tag() { return Net::tag(); } -}; - -/** - * @brief G-API object used to collect network inputs - */ -using GInferInputs = cv::detail::GInferInputsTyped; - -/** - * @brief G-API object used to collect the list of network inputs - */ -using GInferListInputs = cv::detail::GInferInputsTyped, cv::GArray>; - -/** - * @brief G-API object used to collect network outputs - */ -using GInferOutputs = cv::detail::GInferOutputsTyped; - -/** - * @brief G-API object used to collect the list of network outputs - */ -using GInferListOutputs = cv::detail::GInferOutputsTyped>; - -namespace detail { -void inline unpackBlobs(const cv::GInferInputs::Map& blobs, - std::vector& args, - std::vector& names, - cv::GKinds& kinds) -{ - for (auto&& p : blobs) { - names.emplace_back(p.first); - switch (p.second.index()) { - case cv::GInferInputs::StorageT::index_of(): - args.emplace_back(cv::util::get(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); - break; - case cv::GInferInputs::StorageT::index_of(): - args.emplace_back(cv::util::get(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_UNKNOWN); - break; - default: - GAPI_Error("InternalError"); - } - } -} - -template -struct InferROITraits; - -template <> -struct InferROITraits -{ - using outType = cv::GInferOutputs; - using inType = cv::GOpaque; -}; - -template <> -struct InferROITraits -{ - using outType = cv::GInferListOutputs; - using inType = cv::GArray; -}; - -template -typename InferROITraits::outType -inferGenericROI(const std::string& tag, - const typename InferROITraits::inType& in, - const cv::GInferInputs& inputs) -{ - std::vector args; - std::vector names; - cv::GKinds kinds; - - args.emplace_back(in); - kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); - - unpackBlobs(inputs.getBlobs(), args, names, kinds); - - auto call = cv::detail::makeCall(tag, - std::move(args), - std::move(names), - std::move(kinds)); - - return {std::move(call)}; -} - -} // namespace detail -} // namespace cv - -// FIXME: Probably the signature makes a function/tuple/function round-trip -#define G_API_NET(Class, API, Tag) \ - struct Class final: public cv::GNetworkType { \ - static constexpr const char * tag() { return Tag; } \ - } - -namespace cv { -namespace gapi { - -/** @brief Calculates response for the specified network (template - * parameter) for the specified region in the source image. - * Currently expects a single-input network only. - * - * @tparam A network type defined with G_API_NET() macro. - * @param in input image where to take ROI from. - * @param roi an object describing the region of interest - * in the source image. May be calculated in the same graph dynamically. - * @return an object of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * objects of appropriate type is returned. - * @sa G_API_NET() - */ -template -typename Net::Result infer(cv::GOpaque roi, T in) { - return GInferROI::on(roi, in); -} - -/** @brief Calculates responses for the specified network (template - * parameter) for every region in the source image. - * - * @tparam A network type defined with G_API_NET() macro. - * @param roi a list of rectangles describing regions of interest - * in the source image. Usually an output of object detector or tracker. - * @param args network's input parameters as specified in G_API_NET() macro. - * NOTE: verified to work reliably with 1-input topologies only. - * @return a list of objects of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * GArray<> objects is returned with the appropriate types inside. - * @sa G_API_NET() - */ -template -typename Net::ResultL infer(cv::GArray roi, Args&&... args) { - return GInferList::on(roi, std::forward(args)...); -} - -/** @brief Calculates responses for the specified network (template - * parameter) for every region in the source image, extended version. - * - * @tparam A network type defined with G_API_NET() macro. - * @param image A source image containing regions of interest - * @param args GArray<> objects of cv::Rect or cv::GMat, one per every - * network input: - * - If a cv::GArray is passed, the appropriate - * regions are taken from `image` and preprocessed to this particular - * network input; - * - If a cv::GArray is passed, the underlying data traited - * as tensor (no automatic preprocessing happen). - * @return a list of objects of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * GArray<> objects is returned with the appropriate types inside. - * @sa G_API_NET() - */ - -template -typename Net::ResultL infer2(T image, cv::GArray... args) { - // FIXME: Declared as "2" because in the current form it steals - // overloads from the regular infer - return GInferList2::on(image, args...); -} - -/** - * @brief Calculates response for the specified network (template - * parameter) given the input data. - * - * @tparam A network type defined with G_API_NET() macro. - * @param args network's input parameters as specified in G_API_NET() macro. - * @return an object of return type as defined in G_API_NET(). - * If a network has multiple return values (defined with a tuple), a tuple of - * objects of appropriate type is returned. - * @sa G_API_NET() - */ -template -typename Net::Result infer(Args&&... args) { - return GInfer::on(std::forward(args)...); -} - -/** - * @brief Generic network type: input and output layers are configured dynamically at runtime - * - * Unlike the network types defined with G_API_NET macro, this one - * doesn't fix number of network inputs and outputs at the compilation stage - * thus providing user with an opportunity to program them in runtime. - */ -struct Generic { }; - -/** - * @brief Calculates response for generic network - * - * @param tag a network tag - * @param inputs networks's inputs - * @return a GInferOutputs - */ -template cv::GInferOutputs -infer(const std::string& tag, const cv::GInferInputs& inputs) -{ - std::vector args; - std::vector names; - cv::GKinds kinds; - - cv::detail::unpackBlobs(inputs.getBlobs(), args, names, kinds); - - auto call = cv::detail::makeCall(tag, - std::move(args), - std::move(names), - std::move(kinds)); - - return cv::GInferOutputs{std::move(call)}; -} - -/** @brief Calculates response for the generic network - * for the specified region in the source image. - * Currently expects a single-input network only. - * - * @param tag a network tag - * @param roi a an object describing the region of interest - * in the source image. May be calculated in the same graph dynamically. - * @param inputs networks's inputs - * @return a cv::GInferOutputs - */ -template cv::GInferOutputs -infer(const std::string& tag, const cv::GOpaque& roi, const cv::GInferInputs& inputs) -{ - return cv::detail::inferGenericROI(tag, roi, inputs); -} - -/** @brief Calculates responses for the specified network - * for every region in the source image. - * - * @param tag a network tag - * @param rois a list of rectangles describing regions of interest - * in the source image. Usually an output of object detector or tracker. - * @param inputs networks's inputs - * @return a cv::GInferListOutputs - */ -template cv::GInferListOutputs -infer(const std::string& tag, const cv::GArray& rois, const cv::GInferInputs& inputs) -{ - return cv::detail::inferGenericROI(tag, rois, inputs); -} - -/** @brief Calculates responses for the specified network - * for every region in the source image, extended version. - * - * @param tag a network tag - * @param in a source image containing regions of interest. - * @param inputs networks's inputs - * @return a cv::GInferListOutputs - */ -template -typename std::enable_if::value, cv::GInferListOutputs>::type -infer2(const std::string& tag, - const Input& in, - const cv::GInferListInputs& inputs) -{ - std::vector args; - std::vector names; - cv::GKinds kinds; - - args.emplace_back(in); - auto k = cv::detail::GOpaqueTraits::kind; - kinds.emplace_back(k); - - for (auto&& p : inputs.getBlobs()) { - names.emplace_back(p.first); - switch (p.second.index()) { - case cv::GInferListInputs::StorageT::index_of>(): - args.emplace_back(cv::util::get>(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); - break; - case cv::GInferListInputs::StorageT::index_of>(): - args.emplace_back(cv::util::get>(p.second)); - kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); - break; - default: - GAPI_Error("InternalError"); - } - } - - auto call = cv::detail::makeCall(tag, - std::move(args), - std::move(names), - std::move(kinds)); - - return cv::GInferListOutputs{std::move(call)}; -} - -} // namespace gapi -} // namespace cv - -#endif // GAPI_STANDALONE - -namespace cv { -namespace gapi { - -// Note: the below code _is_ part of STANDALONE build, -// just to make our compiler code compileable. - -// A type-erased form of network parameters. -// Similar to how a type-erased GKernel is represented and used. -/// @private -struct GAPI_EXPORTS_W_SIMPLE GNetParam { - std::string tag; // FIXME: const? - GBackend backend; // Specifies the execution model - util::any params; // Backend-interpreted parameter structure -}; - -/** \addtogroup gapi_compile_args - * @{ - */ -/** - * @brief A container class for network configurations. Similar to - * GKernelPackage. Use cv::gapi::networks() to construct this object. - * - * @sa cv::gapi::networks - */ -struct GAPI_EXPORTS_W_SIMPLE GNetPackage { - GAPI_WRAP GNetPackage() = default; - GAPI_WRAP explicit GNetPackage(std::vector nets); - explicit GNetPackage(std::initializer_list ii); - std::vector backends() const; - std::vector networks; -}; -/** @} gapi_compile_args */ -} // namespace gapi - -namespace detail { -template -gapi::GNetParam strip(T&& t) { - return gapi::GNetParam { t.tag() - , t.backend() - , t.params() - }; -} - -template<> struct CompileArgTag { - static const char* tag() { return "gapi.net_package"; } -}; - -} // namespace cv::detail - -namespace gapi { -template -cv::gapi::GNetPackage networks(Args&&... args) { - return cv::gapi::GNetPackage({ cv::detail::strip(args)... }); -} - -inline cv::gapi::GNetPackage& operator += ( cv::gapi::GNetPackage& lhs, - const cv::gapi::GNetPackage& rhs) { - lhs.networks.reserve(lhs.networks.size() + rhs.networks.size()); - lhs.networks.insert(lhs.networks.end(), rhs.networks.begin(), rhs.networks.end()); - return lhs; -} - -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_INFER_HPP +#define OPENCV_GAPI_INFER_HPP + +// FIXME: Inference API is currently only available in full mode +#if !defined(GAPI_STANDALONE) + +#include +#include // string +#include // tuple +#include // is_same, false_type + +#include // all_satisfy +#include // any<> +#include // GKernelType[M], GBackend +#include // GArg +#include // CompileArgTag +#include // GMetaArg + +namespace cv { + +template class GNetworkType; + +namespace detail { + +// Infer /////////////////////////////////////////////////////////////////////// +template +struct accepted_infer_types { + static constexpr const auto value = + std::is_same::type, cv::GMat>::value + || std::is_same::type, cv::GFrame>::value; +}; + +template +using valid_infer_types = all_satisfy; + +// Infer2 ////////////////////////////////////////////////////////////////////// + +template +struct valid_infer2_types; + +// Terminal case 1 (50/50 success) +template +struct valid_infer2_types< std::tuple, std::tuple > { + // By default, Nets are limited to GMat argument types only + // for infer2, every GMat argument may translate to either + // GArray or GArray. GArray<> part is stripped + // already at this point. + static constexpr const auto value = + std::is_same::type, cv::GMat>::value + || std::is_same::type, cv::Rect>::value; +}; + +// Terminal case 2 (100% failure) +template +struct valid_infer2_types< std::tuple<>, std::tuple > + : public std::false_type { +}; + +// Terminal case 3 (100% failure) +template +struct valid_infer2_types< std::tuple, std::tuple<> > + : public std::false_type { +}; + +// Recursion -- generic +template +struct valid_infer2_types< std::tuple, std::tuple > { + static constexpr const auto value = + valid_infer2_types< std::tuple, std::tuple >::value + && valid_infer2_types< std::tuple, std::tuple >::value; +}; + +// Struct stores network input/output names. +// Used by infer +struct InOutInfo +{ + std::vector in_names; + std::vector out_names; +}; + +template +class GInferOutputsTyped +{ +public: + GInferOutputsTyped() = default; + GInferOutputsTyped(std::shared_ptr call) + : m_priv(std::make_shared(std::move(call))) + { + } + + OutT at(const std::string& name) + { + auto it = m_priv->blobs.find(name); + if (it == m_priv->blobs.end()) { + // FIXME: Avoid modifying GKernel + auto shape = cv::detail::GTypeTraits::shape; + auto kind = cv::detail::GTypeTraits::op_kind; + m_priv->call->kernel().outShapes.push_back(shape); + m_priv->call->kernel().outCtors.emplace_back(cv::detail::GObtainCtor::get()); + m_priv->call->kernel().outKinds.emplace_back(kind); + auto out_idx = static_cast(m_priv->blobs.size()); + it = m_priv->blobs.emplace(name, + cv::detail::Yield::yield(*(m_priv->call), out_idx)).first; + m_priv->info->out_names.push_back(name); + } + return it->second; + } +private: + struct Priv + { + Priv(std::shared_ptr c) + : call(std::move(c)), info(cv::util::any_cast(&call->params())) + { + } + + std::shared_ptr call; + InOutInfo* info = nullptr; + std::unordered_map blobs; + }; + + std::shared_ptr m_priv; +}; + +template +class GInferInputsTyped +{ +public: + GInferInputsTyped() + : m_priv(std::make_shared()) + { + } + + template + GInferInputsTyped& setInput(const std::string& name, U in) + { + m_priv->blobs.emplace(std::piecewise_construct, + std::forward_as_tuple(name), + std::forward_as_tuple(in)); + return *this; + } + + using StorageT = cv::util::variant; + StorageT& operator[](const std::string& name) { + return m_priv->blobs[name]; + } + + using Map = std::unordered_map; + const Map& getBlobs() const { + return m_priv->blobs; + } + +private: + struct Priv + { + std::unordered_map blobs; + }; + + std::shared_ptr m_priv; +}; + +template +std::shared_ptr makeCall(const std::string &tag, + std::vector &&args, + std::vector &&names, + cv::GKinds &&kinds) { + auto call = std::make_shared(GKernel{ + InferT::id(), + tag, + InferT::getOutMeta, + {}, // outShape will be filled later + std::move(kinds), + {}, // outCtors will be filled later + {}, // outKinds will be filled later + }); + + call->setArgs(std::move(args)); + call->params() = cv::detail::InOutInfo{std::move(names), {}}; + + return call; +} + +} // namespace detail + +// TODO: maybe tuple_wrap_helper from util.hpp may help with this. +// Multiple-return-value network definition (specialized base class) +template +class GNetworkType(Args...)> > +{ +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + using Result = OutArgs; + using API = std::function; + + using ResultL = std::tuple< cv::GArray... >; +}; + +// Single-return-value network definition (specialized base class) +template +class GNetworkType > +{ +public: + using InArgs = std::tuple; + using OutArgs = std::tuple; + + using Result = R; + using API = std::function; + + using ResultL = cv::GArray; +}; + +// InferAPI: Accepts either GMat or GFrame for very individual network's input +template +struct InferAPI { + using type = typename std::enable_if + < detail::valid_infer_types::value + && std::tuple_size::value == sizeof...(Ts) + , std::function + >::type; +}; + +// InferAPIRoi: Accepts a rectangle and either GMat or GFrame +template +struct InferAPIRoi { + using type = typename std::enable_if + < detail::valid_infer_types::value + && std::tuple_size::value == 1u + , std::function, T)> + >::type; +}; + +// InferAPIList: Accepts a list of rectangles and list of GMat/GFrames; +// crops every input. +template +struct InferAPIList { + using type = typename std::enable_if + < detail::valid_infer_types::value + && std::tuple_size::value == sizeof...(Ts) + , std::function, Ts...)> + >::type; +}; + +// APIList2 is also template to allow different calling options +// (GArray vs GArray per input) +template +struct InferAPIList2 { + using type = typename std::enable_if + < detail::valid_infer_types::value && + cv::detail::valid_infer2_types< typename Net::InArgs + , std::tuple >::value, + std::function...)> + >::type; +}; + +// Base "Infer" kernel. Note - for whatever network, kernel ID +// is always the same. Different inference calls are distinguished by +// network _tag_ (an extra field in GCall) +// +// getOutMeta is a stub callback collected by G-API kernel subsystem +// automatically. This is a rare case when this callback is defined by +// a particular backend, not by a network itself. +struct GInferBase { + static constexpr const char * id() { + return "org.opencv.dnn.infer"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// Base "InferROI" kernel. +// All notes from "Infer" kernel apply here as well. +struct GInferROIBase { + static constexpr const char * id() { + return "org.opencv.dnn.infer-roi"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// Base "Infer list" kernel. +// All notes from "Infer" kernel apply here as well. +struct GInferListBase { + static constexpr const char * id() { + return "org.opencv.dnn.infer-roi-list-1"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// Base "Infer list 2" kernel. +// All notes from "Infer" kernel apply here as well. +struct GInferList2Base { + static constexpr const char * id() { + return "org.opencv.dnn.infer-roi-list-2"; // Universal stub + } + static GMetaArgs getOutMeta(const GMetaArgs &, const GArgs &) { + return GMetaArgs{}; // One more universal stub + } +}; + +// A generic inference kernel. API (::on()) is fully defined by the Net +// template parameter. +// Acts as a regular kernel in graph (via KernelTypeMedium). +template +struct GInfer final + : public GInferBase + , public detail::KernelTypeMedium< GInfer + , typename InferAPI::type > { + using GInferBase::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + +// A specific roi-inference kernel. API (::on()) is fixed here and +// verified against Net. +template +struct GInferROI final + : public GInferROIBase + , public detail::KernelTypeMedium< GInferROI + , typename InferAPIRoi::type > { + using GInferROIBase::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + + +// A generic roi-list inference kernel. API (::on()) is derived from +// the Net template parameter (see more in infer<> overload). +template +struct GInferList final + : public GInferListBase + , public detail::KernelTypeMedium< GInferList + , typename InferAPIList::type > { + using GInferListBase::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + +// An even more generic roi-list inference kernel. API (::on()) is +// derived from the Net template parameter (see more in infer<> +// overload). +// Takes an extra variadic template list to reflect how this network +// was called (with Rects or GMats as array parameters) +template +struct GInferList2 final + : public GInferList2Base + , public detail::KernelTypeMedium< GInferList2 + , typename InferAPIList2::type > { + using GInferList2Base::getOutMeta; // FIXME: name lookup conflict workaround? + + static constexpr const char* tag() { return Net::tag(); } +}; + +/** + * @brief G-API object used to collect network inputs + */ +using GInferInputs = cv::detail::GInferInputsTyped; + +/** + * @brief G-API object used to collect the list of network inputs + */ +using GInferListInputs = cv::detail::GInferInputsTyped, cv::GArray>; + +/** + * @brief G-API object used to collect network outputs + */ +using GInferOutputs = cv::detail::GInferOutputsTyped; + +/** + * @brief G-API object used to collect the list of network outputs + */ +using GInferListOutputs = cv::detail::GInferOutputsTyped>; + +namespace detail { +void inline unpackBlobs(const cv::GInferInputs::Map& blobs, + std::vector& args, + std::vector& names, + cv::GKinds& kinds) +{ + for (auto&& p : blobs) { + names.emplace_back(p.first); + switch (p.second.index()) { + case cv::GInferInputs::StorageT::index_of(): + args.emplace_back(cv::util::get(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); + break; + case cv::GInferInputs::StorageT::index_of(): + args.emplace_back(cv::util::get(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_UNKNOWN); + break; + default: + GAPI_Error("InternalError"); + } + } +} + +template +struct InferROITraits; + +template <> +struct InferROITraits +{ + using outType = cv::GInferOutputs; + using inType = cv::GOpaque; +}; + +template <> +struct InferROITraits +{ + using outType = cv::GInferListOutputs; + using inType = cv::GArray; +}; + +template +typename InferROITraits::outType +inferGenericROI(const std::string& tag, + const typename InferROITraits::inType& in, + const cv::GInferInputs& inputs) +{ + std::vector args; + std::vector names; + cv::GKinds kinds; + + args.emplace_back(in); + kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); + + unpackBlobs(inputs.getBlobs(), args, names, kinds); + + auto call = cv::detail::makeCall(tag, + std::move(args), + std::move(names), + std::move(kinds)); + + return {std::move(call)}; +} + +} // namespace detail +} // namespace cv + +// FIXME: Probably the signature makes a function/tuple/function round-trip +#define G_API_NET(Class, API, Tag) \ + struct Class final: public cv::GNetworkType { \ + static constexpr const char * tag() { return Tag; } \ + } + +namespace cv { +namespace gapi { + +/** @brief Calculates response for the specified network (template + * parameter) for the specified region in the source image. + * Currently expects a single-input network only. + * + * @tparam A network type defined with G_API_NET() macro. + * @param in input image where to take ROI from. + * @param roi an object describing the region of interest + * in the source image. May be calculated in the same graph dynamically. + * @return an object of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * objects of appropriate type is returned. + * @sa G_API_NET() + */ +template +typename Net::Result infer(cv::GOpaque roi, T in) { + return GInferROI::on(roi, in); +} + +/** @brief Calculates responses for the specified network (template + * parameter) for every region in the source image. + * + * @tparam A network type defined with G_API_NET() macro. + * @param roi a list of rectangles describing regions of interest + * in the source image. Usually an output of object detector or tracker. + * @param args network's input parameters as specified in G_API_NET() macro. + * NOTE: verified to work reliably with 1-input topologies only. + * @return a list of objects of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * GArray<> objects is returned with the appropriate types inside. + * @sa G_API_NET() + */ +template +typename Net::ResultL infer(cv::GArray roi, Args&&... args) { + return GInferList::on(roi, std::forward(args)...); +} + +/** @brief Calculates responses for the specified network (template + * parameter) for every region in the source image, extended version. + * + * @tparam A network type defined with G_API_NET() macro. + * @param image A source image containing regions of interest + * @param args GArray<> objects of cv::Rect or cv::GMat, one per every + * network input: + * - If a cv::GArray is passed, the appropriate + * regions are taken from `image` and preprocessed to this particular + * network input; + * - If a cv::GArray is passed, the underlying data traited + * as tensor (no automatic preprocessing happen). + * @return a list of objects of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * GArray<> objects is returned with the appropriate types inside. + * @sa G_API_NET() + */ + +template +typename Net::ResultL infer2(T image, cv::GArray... args) { + // FIXME: Declared as "2" because in the current form it steals + // overloads from the regular infer + return GInferList2::on(image, args...); +} + +/** + * @brief Calculates response for the specified network (template + * parameter) given the input data. + * + * @tparam A network type defined with G_API_NET() macro. + * @param args network's input parameters as specified in G_API_NET() macro. + * @return an object of return type as defined in G_API_NET(). + * If a network has multiple return values (defined with a tuple), a tuple of + * objects of appropriate type is returned. + * @sa G_API_NET() + */ +template +typename Net::Result infer(Args&&... args) { + return GInfer::on(std::forward(args)...); +} + +/** + * @brief Generic network type: input and output layers are configured dynamically at runtime + * + * Unlike the network types defined with G_API_NET macro, this one + * doesn't fix number of network inputs and outputs at the compilation stage + * thus providing user with an opportunity to program them in runtime. + */ +struct Generic { }; + +/** + * @brief Calculates response for generic network + * + * @param tag a network tag + * @param inputs networks's inputs + * @return a GInferOutputs + */ +template cv::GInferOutputs +infer(const std::string& tag, const cv::GInferInputs& inputs) +{ + std::vector args; + std::vector names; + cv::GKinds kinds; + + cv::detail::unpackBlobs(inputs.getBlobs(), args, names, kinds); + + auto call = cv::detail::makeCall(tag, + std::move(args), + std::move(names), + std::move(kinds)); + + return cv::GInferOutputs{std::move(call)}; +} + +/** @brief Calculates response for the generic network + * for the specified region in the source image. + * Currently expects a single-input network only. + * + * @param tag a network tag + * @param roi a an object describing the region of interest + * in the source image. May be calculated in the same graph dynamically. + * @param inputs networks's inputs + * @return a cv::GInferOutputs + */ +template cv::GInferOutputs +infer(const std::string& tag, const cv::GOpaque& roi, const cv::GInferInputs& inputs) +{ + return cv::detail::inferGenericROI(tag, roi, inputs); +} + +/** @brief Calculates responses for the specified network + * for every region in the source image. + * + * @param tag a network tag + * @param rois a list of rectangles describing regions of interest + * in the source image. Usually an output of object detector or tracker. + * @param inputs networks's inputs + * @return a cv::GInferListOutputs + */ +template cv::GInferListOutputs +infer(const std::string& tag, const cv::GArray& rois, const cv::GInferInputs& inputs) +{ + return cv::detail::inferGenericROI(tag, rois, inputs); +} + +/** @brief Calculates responses for the specified network + * for every region in the source image, extended version. + * + * @param tag a network tag + * @param in a source image containing regions of interest. + * @param inputs networks's inputs + * @return a cv::GInferListOutputs + */ +template +typename std::enable_if::value, cv::GInferListOutputs>::type +infer2(const std::string& tag, + const Input& in, + const cv::GInferListInputs& inputs) +{ + std::vector args; + std::vector names; + cv::GKinds kinds; + + args.emplace_back(in); + auto k = cv::detail::GOpaqueTraits::kind; + kinds.emplace_back(k); + + for (auto&& p : inputs.getBlobs()) { + names.emplace_back(p.first); + switch (p.second.index()) { + case cv::GInferListInputs::StorageT::index_of>(): + args.emplace_back(cv::util::get>(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_MAT); + break; + case cv::GInferListInputs::StorageT::index_of>(): + args.emplace_back(cv::util::get>(p.second)); + kinds.emplace_back(cv::detail::OpaqueKind::CV_RECT); + break; + default: + GAPI_Error("InternalError"); + } + } + + auto call = cv::detail::makeCall(tag, + std::move(args), + std::move(names), + std::move(kinds)); + + return cv::GInferListOutputs{std::move(call)}; +} + +} // namespace gapi +} // namespace cv + +#endif // GAPI_STANDALONE + +namespace cv { +namespace gapi { + +// Note: the below code _is_ part of STANDALONE build, +// just to make our compiler code compileable. + +// A type-erased form of network parameters. +// Similar to how a type-erased GKernel is represented and used. +/// @private +struct GAPI_EXPORTS_W_SIMPLE GNetParam { + std::string tag; // FIXME: const? + GBackend backend; // Specifies the execution model + util::any params; // Backend-interpreted parameter structure +}; + +/** \addtogroup gapi_compile_args + * @{ + */ +/** + * @brief A container class for network configurations. Similar to + * GKernelPackage. Use cv::gapi::networks() to construct this object. + * + * @sa cv::gapi::networks + */ +struct GAPI_EXPORTS_W_SIMPLE GNetPackage { + GAPI_WRAP GNetPackage() = default; + GAPI_WRAP explicit GNetPackage(std::vector nets); + explicit GNetPackage(std::initializer_list ii); + std::vector backends() const; + std::vector networks; +}; +/** @} gapi_compile_args */ +} // namespace gapi + +namespace detail { +template +gapi::GNetParam strip(T&& t) { + return gapi::GNetParam { t.tag() + , t.backend() + , t.params() + }; +} + +template<> struct CompileArgTag { + static const char* tag() { return "gapi.net_package"; } +}; + +} // namespace cv::detail + +namespace gapi { +template +cv::gapi::GNetPackage networks(Args&&... args) { + return cv::gapi::GNetPackage({ cv::detail::strip(args)... }); +} + +inline cv::gapi::GNetPackage& operator += ( cv::gapi::GNetPackage& lhs, + const cv::gapi::GNetPackage& rhs) { + lhs.networks.reserve(lhs.networks.size() + rhs.networks.size()); + lhs.networks.insert(lhs.networks.end(), rhs.networks.begin(), rhs.networks.end()); + return lhs; +} + +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp index c2416f388c..94272dea55 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ie.hpp @@ -1,70 +1,70 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_BINDINGS_IE_HPP -#define OPENCV_GAPI_INFER_BINDINGS_IE_HPP - -#include -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS -#include // GKernelPackage -#include // Params - -#include - -namespace cv { -namespace gapi { -namespace ie { - -// NB: Used by python wrapper -// This class can be marked as SIMPLE, because it's implemented as pimpl -class GAPI_EXPORTS_W_SIMPLE PyParams { -public: - GAPI_WRAP - PyParams() = default; - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &model, - const std::string &weights, - const std::string &device); - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &model, - const std::string &device); - - GAPI_WRAP - PyParams& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR); - - GAPI_WRAP - PyParams& cfgNumRequests(size_t nireq); - - GAPI_WRAP - PyParams& cfgBatchSize(const size_t size); - - GBackend backend() const; - std::string tag() const; - cv::util::any params() const; - -private: - std::shared_ptr> m_priv; -}; - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &model, - const std::string &weights, - const std::string &device); - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &model, - const std::string &device); -} // namespace ie -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_BINDINGS_IE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_BINDINGS_IE_HPP +#define OPENCV_GAPI_INFER_BINDINGS_IE_HPP + +#include +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS +#include // GKernelPackage +#include // Params + +#include + +namespace cv { +namespace gapi { +namespace ie { + +// NB: Used by python wrapper +// This class can be marked as SIMPLE, because it's implemented as pimpl +class GAPI_EXPORTS_W_SIMPLE PyParams { +public: + GAPI_WRAP + PyParams() = default; + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &model, + const std::string &weights, + const std::string &device); + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &model, + const std::string &device); + + GAPI_WRAP + PyParams& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR); + + GAPI_WRAP + PyParams& cfgNumRequests(size_t nireq); + + GAPI_WRAP + PyParams& cfgBatchSize(const size_t size); + + GBackend backend() const; + std::string tag() const; + cv::util::any params() const; + +private: + std::shared_ptr> m_priv; +}; + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &model, + const std::string &weights, + const std::string &device); + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &model, + const std::string &device); +} // namespace ie +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_BINDINGS_IE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp index 4fa0a8db64..f7bb259924 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_onnx.hpp @@ -1,74 +1,74 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level -// directory of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP -#define OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP - -#include // GKernelPackage -#include // Params -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS -#include - -#include - -namespace cv { -namespace gapi { -namespace onnx { - -// NB: Used by python wrapper -// This class can be marked as SIMPLE, because it's implemented as pimpl -class GAPI_EXPORTS_W_SIMPLE PyParams { -public: - GAPI_WRAP - PyParams() = default; - - GAPI_WRAP - PyParams(const std::string& tag, const std::string& model_path); - - GAPI_WRAP - PyParams& cfgMeanStd(const std::string &layer_name, - const cv::Scalar &m, - const cv::Scalar &s); - GAPI_WRAP - PyParams& cfgNormalize(const std::string &layer_name, bool flag); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::OpenVINO ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::DirectML ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::CoreML ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::CUDA ep); - - GAPI_WRAP - PyParams& cfgAddExecutionProvider(ep::TensorRT ep); - - GAPI_WRAP - PyParams& cfgDisableMemPattern(); - - GAPI_WRAP - PyParams& cfgSessionOptions(const std::map& options); - - GAPI_WRAP - PyParams& cfgOptLevel(const int opt_level); - - GBackend backend() const; - std::string tag() const; - cv::util::any params() const; - -private: - std::shared_ptr> m_priv; -}; - -GAPI_EXPORTS_W PyParams params(const std::string& tag, const std::string& model_path); - -} // namespace onnx -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level +// directory of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP +#define OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP + +#include // GKernelPackage +#include // Params +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS +#include + +#include + +namespace cv { +namespace gapi { +namespace onnx { + +// NB: Used by python wrapper +// This class can be marked as SIMPLE, because it's implemented as pimpl +class GAPI_EXPORTS_W_SIMPLE PyParams { +public: + GAPI_WRAP + PyParams() = default; + + GAPI_WRAP + PyParams(const std::string& tag, const std::string& model_path); + + GAPI_WRAP + PyParams& cfgMeanStd(const std::string &layer_name, + const cv::Scalar &m, + const cv::Scalar &s); + GAPI_WRAP + PyParams& cfgNormalize(const std::string &layer_name, bool flag); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::OpenVINO ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::DirectML ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::CoreML ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::CUDA ep); + + GAPI_WRAP + PyParams& cfgAddExecutionProvider(ep::TensorRT ep); + + GAPI_WRAP + PyParams& cfgDisableMemPattern(); + + GAPI_WRAP + PyParams& cfgSessionOptions(const std::map& options); + + GAPI_WRAP + PyParams& cfgOptLevel(const int opt_level); + + GBackend backend() const; + std::string tag() const; + cv::util::any params() const; + +private: + std::shared_ptr> m_priv; +}; + +GAPI_EXPORTS_W PyParams params(const std::string& tag, const std::string& model_path); + +} // namespace onnx +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_BINDINGS_ONNX_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp index 5cf371f1f2..08f5c83a3f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/bindings_ov.hpp @@ -1,128 +1,128 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_BINDINGS_OV_HPP -#define OPENCV_GAPI_INFER_BINDINGS_OV_HPP - -#include -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS -#include // GKernelPackage -#include // Params - -#include - -namespace cv { -namespace gapi { -namespace ov { - -// NB: Used by python wrapper -// This class can be marked as SIMPLE, because it's implemented as pimpl -class GAPI_EXPORTS_W_SIMPLE PyParams { -public: - GAPI_WRAP - PyParams() = default; - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &model_path, - const std::string &bin_path, - const std::string &device); - - GAPI_WRAP - PyParams(const std::string &tag, - const std::string &blob_path, - const std::string &device); - - GAPI_WRAP - PyParams& cfgPluginConfig( - const std::map &config); - - GAPI_WRAP - PyParams& cfgInputTensorLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgInputTensorLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgInputModelLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgInputModelLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgOutputTensorLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgOutputTensorLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgOutputModelLayout(std::string tensor_layout); - - GAPI_WRAP - PyParams& cfgOutputModelLayout( - std::map layout_map); - - GAPI_WRAP - PyParams& cfgOutputTensorPrecision(int precision); - - GAPI_WRAP - PyParams& cfgOutputTensorPrecision( - std::map precision_map); - - GAPI_WRAP - PyParams& cfgReshape(std::vector new_shape); - - GAPI_WRAP - PyParams& cfgReshape( - std::map> new_shape_map); - - GAPI_WRAP - PyParams& cfgNumRequests(const size_t nireq); - - GAPI_WRAP - PyParams& cfgMean(std::vector mean_values); - - GAPI_WRAP - PyParams& cfgMean( - std::map> mean_map); - - GAPI_WRAP - PyParams& cfgScale(std::vector scale_values); - - GAPI_WRAP - PyParams& cfgScale( - std::map> scale_map); - - GAPI_WRAP - PyParams& cfgResize(int interpolation); - - GAPI_WRAP - PyParams& cfgResize(std::map interpolation); - - GBackend backend() const; - std::string tag() const; - cv::util::any params() const; - -private: - std::shared_ptr> m_priv; -}; - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &model_path, - const std::string &weights, - const std::string &device); - -GAPI_EXPORTS_W PyParams params(const std::string &tag, - const std::string &bin_path, - const std::string &device); -} // namespace ov -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_BINDINGS_OV_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_BINDINGS_OV_HPP +#define OPENCV_GAPI_INFER_BINDINGS_OV_HPP + +#include +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS +#include // GKernelPackage +#include // Params + +#include + +namespace cv { +namespace gapi { +namespace ov { + +// NB: Used by python wrapper +// This class can be marked as SIMPLE, because it's implemented as pimpl +class GAPI_EXPORTS_W_SIMPLE PyParams { +public: + GAPI_WRAP + PyParams() = default; + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &model_path, + const std::string &bin_path, + const std::string &device); + + GAPI_WRAP + PyParams(const std::string &tag, + const std::string &blob_path, + const std::string &device); + + GAPI_WRAP + PyParams& cfgPluginConfig( + const std::map &config); + + GAPI_WRAP + PyParams& cfgInputTensorLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgInputTensorLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgInputModelLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgInputModelLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgOutputTensorLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgOutputTensorLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgOutputModelLayout(std::string tensor_layout); + + GAPI_WRAP + PyParams& cfgOutputModelLayout( + std::map layout_map); + + GAPI_WRAP + PyParams& cfgOutputTensorPrecision(int precision); + + GAPI_WRAP + PyParams& cfgOutputTensorPrecision( + std::map precision_map); + + GAPI_WRAP + PyParams& cfgReshape(std::vector new_shape); + + GAPI_WRAP + PyParams& cfgReshape( + std::map> new_shape_map); + + GAPI_WRAP + PyParams& cfgNumRequests(const size_t nireq); + + GAPI_WRAP + PyParams& cfgMean(std::vector mean_values); + + GAPI_WRAP + PyParams& cfgMean( + std::map> mean_map); + + GAPI_WRAP + PyParams& cfgScale(std::vector scale_values); + + GAPI_WRAP + PyParams& cfgScale( + std::map> scale_map); + + GAPI_WRAP + PyParams& cfgResize(int interpolation); + + GAPI_WRAP + PyParams& cfgResize(std::map interpolation); + + GBackend backend() const; + std::string tag() const; + cv::util::any params() const; + +private: + std::shared_ptr> m_priv; +}; + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &model_path, + const std::string &weights, + const std::string &device); + +GAPI_EXPORTS_W PyParams params(const std::string &tag, + const std::string &bin_path, + const std::string &device); +} // namespace ov +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_BINDINGS_OV_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp index 4552d2db34..9f9518d0b8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ie.hpp @@ -1,711 +1,711 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019-2023 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_IE_HPP -#define OPENCV_GAPI_INFER_IE_HPP - -#include -#include -#include -#include -#include // tuple, tuple_size -#include - -#include -#include - -#include // GAPI_EXPORTS -#include // GKernelPackage -#include // Generic -#include // Preproc Dev & Ctx - -namespace cv { -namespace gapi { -// FIXME: introduce a new sub-namespace for NN? - -/** - * @brief This namespace contains G-API OpenVINO backend functions, - * structures, and symbols. - */ -namespace ie { - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -/** - * Specifies how G-API and IE should trait input data - * - * In OpenCV, the same cv::Mat is used to represent both - * image and tensor data. Sometimes those are hardly distinguishable, - * so this extra parameter is used to give G-API a hint. - * - * This hint controls how G-API reinterprets the data when converting - * it to IE Blob format (and which layout/etc is assigned to this data). - */ -enum class TraitAs: int -{ - TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor and passes dimensions as-is - IMAGE //!< G-API traits an associated cv::Mat as an image so creates an "image" blob (NCHW/NHWC, etc) -}; - -using IEConfig = std::map; - -enum InferMode {Sync, Async}; - -namespace detail { - -template -using AttrMap = std::map; -// NB: This type is used to hold in/out layers -// attributes such as precision, layout, shape etc. -// -// User can provide attributes either: -// 1. cv::util::monostate - No value specified explicitly. -// 2. Attr - value specified explicitly that should be broadcasted to all layers. -// 3. AttrMap[str->T] - map specifies value for particular layer. -template -using LayerVariantAttr = cv::util::variant< cv::util::monostate - , AttrMap - , Attr>; - -struct ParamDesc { - std::string model_path; - std::string weights_path; - std::string device_id; - - std::vector input_names; - std::vector output_names; - - using ConstInput = std::pair; - std::unordered_map const_inputs; - - std::size_t num_in; - std::size_t num_out; - - enum class Kind {Load, Import}; - Kind kind; - bool is_generic; - IEConfig config; - - std::map> reshape_table; - std::unordered_set layer_names_to_reshape; - - // NB: Number of asyncrhonious infer requests - size_t nireq; - - // NB: An optional config to setup RemoteContext for IE - cv::util::any context_config; - - // NB: batch_size can't be equal to 1 by default, because some of models - // have 2D (Layout::NC) input and if the first dimension not equal to 1 - // net.setBatchSize(1) will overwrite it. - cv::optional batch_size; - - cv::optional vpl_preproc_device; - cv::optional vpl_preproc_ctx; - - InferMode mode; - - using PrecisionT = int; - using PrecisionMapT = std::unordered_map; - // NB: This parameter can contain: - // 1. cv::util::monostate - Don't specify precision, but use default from IR/Blob. - // 2. PrecisionT (CV_8U, CV_32F, ...) - Specifies precision for all output layers. - // 3. PrecisionMapT ({{"layer0", CV_32F}, {"layer1", CV_16F}} - Specifies precision for certain output layer. - // cv::util::monostate is default value that means precision wasn't specified. - using PrecisionVariantT = cv::util::variant; - - PrecisionVariantT output_precision; - LayerVariantAttr input_layout; - LayerVariantAttr output_layout; - LayerVariantAttr interpolation; -}; -} // namespace detail - -// FIXME: this is probably a shared (reusable) thing -template -struct PortCfg { - using In = std::array - < std::string - , std::tuple_size::value >; - using Out = std::array - < std::string - , std::tuple_size::value >; -}; - -/** - * @brief This structure provides functions - * that fill inference parameters for "OpenVINO Toolkit" model. - */ -template class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and specifies default values for other - inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". - - @param model Path to topology IR (.xml file). - @param weights Path to weights (.bin file). - @param device target device to use. - */ - Params(const std::string &model, - const std::string &weights, - const std::string &device) - : desc{ model, weights, device, {}, {}, {} - , std::tuple_size::value // num_in - , std::tuple_size::value // num_out - , detail::ParamDesc::Kind::Load - , false - , {} - , {} - , {} - , 1u - , {} - , {} - , {} - , {} - , InferMode::Async - , {} - , {} - , {} - , {} } { - } - - /** @overload - Use this constructor to work with pre-compiled network. - Model is imported from a pre-compiled blob. - - @param model Path to model. - @param device target device to use. - */ - Params(const std::string &model, - const std::string &device) - : desc{ model, {}, device, {}, {}, {} - , std::tuple_size::value // num_in - , std::tuple_size::value // num_out - , detail::ParamDesc::Kind::Import - , false - , {} - , {} - , {} - , 1u - , {} - , {} - , {} - , {} - , InferMode::Async - , {} - , {} - , {} - , {} } { - } - - /** @brief Specifies sequence of network input layers names for inference. - - The function is used to associate cv::gapi::infer<> inputs with the model inputs. - Number of names has to match the number of network inputs as defined in G_API_NET(). - In case a network has only single input layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains names of input layers. - @return reference to this parameter structure. - */ - Params& cfgInputLayers(const typename PortCfg::In &layer_names) { - desc.input_names.clear(); - desc.input_names.reserve(layer_names.size()); - std::copy(layer_names.begin(), layer_names.end(), - std::back_inserter(desc.input_names)); - return *this; - } - - /** @brief Specifies sequence of network output layers names for inference. - - The function is used to associate cv::gapi::infer<> outputs with the model outputs. - Number of names has to match the number of network outputs as defined in G_API_NET(). - In case a network has only single output layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of outputs - as defined in the @ref G_API_NET. Contains names of output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { - desc.output_names.clear(); - desc.output_names.reserve(layer_names.size()); - std::copy(layer_names.begin(), layer_names.end(), - std::back_inserter(desc.output_names)); - return *this; - } - - /** @brief Specifies a constant input. - - The function is used to set a constant input. This input has to be - a preprocessed tensor if its type is TENSOR. Need to provide name of the - network layer which will receive provided data. - - @param layer_name Name of network layer. - @param data cv::Mat that contains data which will be associated with network layer. - @param hint Input type @sa cv::gapi::ie::TraitAs. - @return reference to this parameter structure. - */ - Params& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR) { - desc.const_inputs[layer_name] = {data, hint}; - return *this; - } - - /** @brief Specifies OpenVINO plugin configuration. - - The function is used to set configuration for OpenVINO plugin. Some parameters - can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html - to check information about specific plugin. - - @param cfg Map of pairs: (config parameter name, config parameter value). - @return reference to this parameter structure. - */ - Params& pluginConfig(const IEConfig& cfg) { - desc.config = cfg; - return *this; - } - - /** @overload - Function with a rvalue parameter. - - @param cfg rvalue map of pairs: (config parameter name, config parameter value). - @return reference to this parameter structure. - */ - Params& pluginConfig(IEConfig&& cfg) { - desc.config = std::move(cfg); - return *this; - } - - /** @brief Specifies configuration for RemoteContext in InferenceEngine. - - When RemoteContext is configured the backend imports the networks using the context. - It also expects cv::MediaFrames to be actually remote, to operate with blobs via the context. - - @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. - @return reference to this parameter structure. - */ - Params& cfgContextParams(const cv::util::any& ctx_cfg) { - desc.context_config = ctx_cfg; - return *this; - } - - /** @overload - Function with an rvalue parameter. - - @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. - @return reference to this parameter structure. - */ - Params& cfgContextParams(cv::util::any&& ctx_cfg) { - desc.context_config = std::move(ctx_cfg); - return *this; - } - - /** @brief Specifies number of asynchronous inference requests. - - @param nireq Number of inference asynchronous requests. - @return reference to this parameter structure. - */ - Params& cfgNumRequests(size_t nireq) { - GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); - desc.nireq = nireq; - return *this; - } - - /** @brief Specifies new input shapes for the network inputs. - - The function is used to specify new input shapes for the network inputs. - Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1networkNetwork.html - for additional information. - - @param reshape_table Map of pairs: name of corresponding data and its dimension. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(const std::map>& reshape_table) { - desc.reshape_table = reshape_table; - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::map>&& reshape_table) { - desc.reshape_table = std::move(reshape_table); - return *this; - } - - /** @overload - - @param layer_name Name of layer. - @param layer_dims New dimensions for this layer. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(const std::string& layer_name, const std::vector& layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::string&& layer_name, std::vector&& layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload - - @param layer_names set of names of network layers that will be used for network reshape. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(const std::unordered_set& layer_names) { - desc.layer_names_to_reshape = layer_names; - return *this; - } - - /** @overload - - @param layer_names rvalue set of the selected layers will be reshaped automatically - its input image size. - @return reference to this parameter structure. - */ - Params& cfgInputReshape(std::unordered_set&& layer_names) { - desc.layer_names_to_reshape = std::move(layer_names); - return *this; - } - - /** @brief Specifies the inference batch size. - - The function is used to specify inference batch size. - Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1CNNNetwork.html#a8e9d19270a48aab50cb5b1c43eecb8e9 for additional information - - @param size batch size which will be used. - @return reference to this parameter structure. - */ - Params& cfgBatchSize(const size_t size) { - desc.batch_size = cv::util::make_optional(size); - return *this; - } - - Params& cfgPreprocessingParams(const cv::gapi::wip::onevpl::Device &device, - const cv::gapi::wip::onevpl::Context &ctx) { - desc.vpl_preproc_device = cv::util::make_optional(device); - desc.vpl_preproc_ctx = cv::util::make_optional(ctx); - return *this; - } - - /** @brief Specifies which api will be used to run inference. - - The function is used to specify mode for OpenVINO inference. - OpenVINO has two options to run inference: - 1. Asynchronous (using StartAsync: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a405293e8423d82a5b45f642a3bef0d24) - 2. Synchronous (using Infer: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a3391ce30894abde730523e9ca9371ce8) - By default asynchronous mode is used. - - @param mode Inference mode which will be used. - @return reference to this parameter structure. - */ - Params& cfgInferMode(InferMode mode) { - desc.mode = mode; - return *this; - } - - /** @brief Specifies the output precision for model. - - The function is used to set an output precision for model. - - @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { - desc.output_precision = precision; - return *this; - } - - /** @overload - - @param precision_map Map of pairs: name of corresponding output layer - and its precision in OpenCV format (CV_8U, CV_32F, ...) - @return reference to this parameter structure. - */ - Params& - cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { - desc.output_precision = precision_map; - return *this; - } - - /** @brief Specifies the input layout for model. - - The function is used to set an input layout for model. - - @param layout Layout in string representation ("NCHW", "NHWC", etc) - will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& cfgInputLayout(std::string layout) { - desc.input_layout = std::move(layout); - return *this; - } - - /** @overload - - @param layout_map Map of pairs: name of corresponding input layer - and its layout in string representation ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgInputLayout(detail::AttrMap layout_map) { - desc.input_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies the output layout for model. - - The function is used to set an output layout for model. - - @param layout Layout in string representation ("NCHW", "NHWC", etc) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputLayout(std::string layout) { - desc.output_layout = std::move(layout); - return *this; - } - - /** @overload - - @param layout_map Map of pairs: name of corresponding output layer - and its layout in string representation ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgOutputLayout(detail::AttrMap layout_map) { - desc.output_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies resize interpolation algorithm. - * - The function is used to configure resize preprocessing for input layer. - - @param interpolation Resize interpolation algorithm. - Supported algorithms: #INTER_LINEAR, #INTER_AREA. - @return reference to this parameter structure. - */ - Params& cfgResize(int interpolation) { - desc.interpolation = interpolation; - return *this; - } - - /** @overload - - @param interpolation Map of pairs: name of corresponding input layer - and its resize algorithm. - @return reference to this parameter structure. - */ - Params& cfgResize(detail::AttrMap interpolation) { - desc.interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ie::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; -}; - -/* -* @brief This structure provides functions for generic network type that -* fill inference parameters. -* @see struct Generic -*/ -template<> -class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and sets default values for other - inference description parameters. Model is loaded and compiled using OpenVINO Toolkit. - - @param tag string tag of the network for which these parameters are intended. - @param model path to topology IR (.xml file). - @param weights path to weights (.bin file). - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &model, - const std::string &weights, - const std::string &device) - : desc{ model, weights, device, {}, {}, {}, 0u, 0u, - detail::ParamDesc::Kind::Load, true, {}, {}, {}, 1u, - {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, - m_tag(tag) { - } - - /** @overload - - This constructor for pre-compiled networks. Model is imported from pre-compiled - blob. - - @param tag string tag of the network for which these parameters are intended. - @param model path to model. - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &model, - const std::string &device) - : desc{ model, {}, device, {}, {}, {}, 0u, 0u, - detail::ParamDesc::Kind::Import, true, {}, {}, {}, 1u, - {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, - m_tag(tag) { - } - - /** @see ie::Params::pluginConfig. */ - Params& pluginConfig(const IEConfig& cfg) { - desc.config = cfg; - return *this; - } - - /** @overload */ - Params& pluginConfig(IEConfig&& cfg) { - desc.config = std::move(cfg); - return *this; - } - - /** @see ie::Params::constInput. */ - Params& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR) { - desc.const_inputs[layer_name] = {data, hint}; - return *this; - } - - /** @see ie::Params::cfgNumRequests. */ - Params& cfgNumRequests(size_t nireq) { - GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); - desc.nireq = nireq; - return *this; - } - - /** @see ie::Params::cfgInputReshape */ - Params& cfgInputReshape(const std::map>&reshape_table) { - desc.reshape_table = reshape_table; - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::map> && reshape_table) { - desc.reshape_table = std::move(reshape_table); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::string && layer_name, std::vector && layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(const std::string & layer_name, const std::vector&layer_dims) { - desc.reshape_table.emplace(layer_name, layer_dims); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(std::unordered_set && layer_names) { - desc.layer_names_to_reshape = std::move(layer_names); - return *this; - } - - /** @overload */ - Params& cfgInputReshape(const std::unordered_set&layer_names) { - desc.layer_names_to_reshape = layer_names; - return *this; - } - - /** @see ie::Params::cfgBatchSize */ - Params& cfgBatchSize(const size_t size) { - desc.batch_size = cv::util::make_optional(size); - return *this; - } - - /** @see ie::Params::cfgInferAPI */ - Params& cfgInferMode(InferMode mode) { - desc.mode = mode; - return *this; - } - - /** @see ie::Params::cfgOutputPrecision */ - Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { - desc.output_precision = precision; - return *this; - } - - /** @overload */ - Params& - cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { - desc.output_precision = precision_map; - return *this; - } - - /** @see ie::Params::cfgInputLayout */ - Params& cfgInputLayout(std::string layout) { - desc.input_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgInputLayout(detail::AttrMap layout_map) { - desc.input_layout = std::move(layout_map); - return *this; - } - - /** @see ie::Params::cfgOutputLayout */ - Params& cfgOutputLayout(std::string layout) { - desc.output_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgOutputLayout(detail::AttrMap layout_map) { - desc.output_layout = std::move(layout_map); - return *this; - } - - /** @see ie::Params::cfgResize */ - Params& cfgResize(int interpolation) { - desc.interpolation = interpolation; - return *this; - } - - /** @overload */ - Params& cfgResize(detail::AttrMap interpolation) { - desc.interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ie::backend(); } - std::string tag() const { return m_tag; } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; - std::string m_tag; -}; - -} // namespace ie -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_IE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019-2023 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_IE_HPP +#define OPENCV_GAPI_INFER_IE_HPP + +#include +#include +#include +#include +#include // tuple, tuple_size +#include + +#include +#include + +#include // GAPI_EXPORTS +#include // GKernelPackage +#include // Generic +#include // Preproc Dev & Ctx + +namespace cv { +namespace gapi { +// FIXME: introduce a new sub-namespace for NN? + +/** + * @brief This namespace contains G-API OpenVINO backend functions, + * structures, and symbols. + */ +namespace ie { + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +/** + * Specifies how G-API and IE should trait input data + * + * In OpenCV, the same cv::Mat is used to represent both + * image and tensor data. Sometimes those are hardly distinguishable, + * so this extra parameter is used to give G-API a hint. + * + * This hint controls how G-API reinterprets the data when converting + * it to IE Blob format (and which layout/etc is assigned to this data). + */ +enum class TraitAs: int +{ + TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor and passes dimensions as-is + IMAGE //!< G-API traits an associated cv::Mat as an image so creates an "image" blob (NCHW/NHWC, etc) +}; + +using IEConfig = std::map; + +enum InferMode {Sync, Async}; + +namespace detail { + +template +using AttrMap = std::map; +// NB: This type is used to hold in/out layers +// attributes such as precision, layout, shape etc. +// +// User can provide attributes either: +// 1. cv::util::monostate - No value specified explicitly. +// 2. Attr - value specified explicitly that should be broadcasted to all layers. +// 3. AttrMap[str->T] - map specifies value for particular layer. +template +using LayerVariantAttr = cv::util::variant< cv::util::monostate + , AttrMap + , Attr>; + +struct ParamDesc { + std::string model_path; + std::string weights_path; + std::string device_id; + + std::vector input_names; + std::vector output_names; + + using ConstInput = std::pair; + std::unordered_map const_inputs; + + std::size_t num_in; + std::size_t num_out; + + enum class Kind {Load, Import}; + Kind kind; + bool is_generic; + IEConfig config; + + std::map> reshape_table; + std::unordered_set layer_names_to_reshape; + + // NB: Number of asyncrhonious infer requests + size_t nireq; + + // NB: An optional config to setup RemoteContext for IE + cv::util::any context_config; + + // NB: batch_size can't be equal to 1 by default, because some of models + // have 2D (Layout::NC) input and if the first dimension not equal to 1 + // net.setBatchSize(1) will overwrite it. + cv::optional batch_size; + + cv::optional vpl_preproc_device; + cv::optional vpl_preproc_ctx; + + InferMode mode; + + using PrecisionT = int; + using PrecisionMapT = std::unordered_map; + // NB: This parameter can contain: + // 1. cv::util::monostate - Don't specify precision, but use default from IR/Blob. + // 2. PrecisionT (CV_8U, CV_32F, ...) - Specifies precision for all output layers. + // 3. PrecisionMapT ({{"layer0", CV_32F}, {"layer1", CV_16F}} - Specifies precision for certain output layer. + // cv::util::monostate is default value that means precision wasn't specified. + using PrecisionVariantT = cv::util::variant; + + PrecisionVariantT output_precision; + LayerVariantAttr input_layout; + LayerVariantAttr output_layout; + LayerVariantAttr interpolation; +}; +} // namespace detail + +// FIXME: this is probably a shared (reusable) thing +template +struct PortCfg { + using In = std::array + < std::string + , std::tuple_size::value >; + using Out = std::array + < std::string + , std::tuple_size::value >; +}; + +/** + * @brief This structure provides functions + * that fill inference parameters for "OpenVINO Toolkit" model. + */ +template class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and specifies default values for other + inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". + + @param model Path to topology IR (.xml file). + @param weights Path to weights (.bin file). + @param device target device to use. + */ + Params(const std::string &model, + const std::string &weights, + const std::string &device) + : desc{ model, weights, device, {}, {}, {} + , std::tuple_size::value // num_in + , std::tuple_size::value // num_out + , detail::ParamDesc::Kind::Load + , false + , {} + , {} + , {} + , 1u + , {} + , {} + , {} + , {} + , InferMode::Async + , {} + , {} + , {} + , {} } { + } + + /** @overload + Use this constructor to work with pre-compiled network. + Model is imported from a pre-compiled blob. + + @param model Path to model. + @param device target device to use. + */ + Params(const std::string &model, + const std::string &device) + : desc{ model, {}, device, {}, {}, {} + , std::tuple_size::value // num_in + , std::tuple_size::value // num_out + , detail::ParamDesc::Kind::Import + , false + , {} + , {} + , {} + , 1u + , {} + , {} + , {} + , {} + , InferMode::Async + , {} + , {} + , {} + , {} } { + } + + /** @brief Specifies sequence of network input layers names for inference. + + The function is used to associate cv::gapi::infer<> inputs with the model inputs. + Number of names has to match the number of network inputs as defined in G_API_NET(). + In case a network has only single input layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains names of input layers. + @return reference to this parameter structure. + */ + Params& cfgInputLayers(const typename PortCfg::In &layer_names) { + desc.input_names.clear(); + desc.input_names.reserve(layer_names.size()); + std::copy(layer_names.begin(), layer_names.end(), + std::back_inserter(desc.input_names)); + return *this; + } + + /** @brief Specifies sequence of network output layers names for inference. + + The function is used to associate cv::gapi::infer<> outputs with the model outputs. + Number of names has to match the number of network outputs as defined in G_API_NET(). + In case a network has only single output layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of outputs + as defined in the @ref G_API_NET. Contains names of output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { + desc.output_names.clear(); + desc.output_names.reserve(layer_names.size()); + std::copy(layer_names.begin(), layer_names.end(), + std::back_inserter(desc.output_names)); + return *this; + } + + /** @brief Specifies a constant input. + + The function is used to set a constant input. This input has to be + a preprocessed tensor if its type is TENSOR. Need to provide name of the + network layer which will receive provided data. + + @param layer_name Name of network layer. + @param data cv::Mat that contains data which will be associated with network layer. + @param hint Input type @sa cv::gapi::ie::TraitAs. + @return reference to this parameter structure. + */ + Params& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR) { + desc.const_inputs[layer_name] = {data, hint}; + return *this; + } + + /** @brief Specifies OpenVINO plugin configuration. + + The function is used to set configuration for OpenVINO plugin. Some parameters + can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html + to check information about specific plugin. + + @param cfg Map of pairs: (config parameter name, config parameter value). + @return reference to this parameter structure. + */ + Params& pluginConfig(const IEConfig& cfg) { + desc.config = cfg; + return *this; + } + + /** @overload + Function with a rvalue parameter. + + @param cfg rvalue map of pairs: (config parameter name, config parameter value). + @return reference to this parameter structure. + */ + Params& pluginConfig(IEConfig&& cfg) { + desc.config = std::move(cfg); + return *this; + } + + /** @brief Specifies configuration for RemoteContext in InferenceEngine. + + When RemoteContext is configured the backend imports the networks using the context. + It also expects cv::MediaFrames to be actually remote, to operate with blobs via the context. + + @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. + @return reference to this parameter structure. + */ + Params& cfgContextParams(const cv::util::any& ctx_cfg) { + desc.context_config = ctx_cfg; + return *this; + } + + /** @overload + Function with an rvalue parameter. + + @param ctx_cfg cv::util::any value which holds InferenceEngine::ParamMap. + @return reference to this parameter structure. + */ + Params& cfgContextParams(cv::util::any&& ctx_cfg) { + desc.context_config = std::move(ctx_cfg); + return *this; + } + + /** @brief Specifies number of asynchronous inference requests. + + @param nireq Number of inference asynchronous requests. + @return reference to this parameter structure. + */ + Params& cfgNumRequests(size_t nireq) { + GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); + desc.nireq = nireq; + return *this; + } + + /** @brief Specifies new input shapes for the network inputs. + + The function is used to specify new input shapes for the network inputs. + Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1networkNetwork.html + for additional information. + + @param reshape_table Map of pairs: name of corresponding data and its dimension. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(const std::map>& reshape_table) { + desc.reshape_table = reshape_table; + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::map>&& reshape_table) { + desc.reshape_table = std::move(reshape_table); + return *this; + } + + /** @overload + + @param layer_name Name of layer. + @param layer_dims New dimensions for this layer. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(const std::string& layer_name, const std::vector& layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::string&& layer_name, std::vector&& layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload + + @param layer_names set of names of network layers that will be used for network reshape. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(const std::unordered_set& layer_names) { + desc.layer_names_to_reshape = layer_names; + return *this; + } + + /** @overload + + @param layer_names rvalue set of the selected layers will be reshaped automatically + its input image size. + @return reference to this parameter structure. + */ + Params& cfgInputReshape(std::unordered_set&& layer_names) { + desc.layer_names_to_reshape = std::move(layer_names); + return *this; + } + + /** @brief Specifies the inference batch size. + + The function is used to specify inference batch size. + Follow https://docs.openvinotoolkit.org/latest/classInferenceEngine_1_1CNNNetwork.html#a8e9d19270a48aab50cb5b1c43eecb8e9 for additional information + + @param size batch size which will be used. + @return reference to this parameter structure. + */ + Params& cfgBatchSize(const size_t size) { + desc.batch_size = cv::util::make_optional(size); + return *this; + } + + Params& cfgPreprocessingParams(const cv::gapi::wip::onevpl::Device &device, + const cv::gapi::wip::onevpl::Context &ctx) { + desc.vpl_preproc_device = cv::util::make_optional(device); + desc.vpl_preproc_ctx = cv::util::make_optional(ctx); + return *this; + } + + /** @brief Specifies which api will be used to run inference. + + The function is used to specify mode for OpenVINO inference. + OpenVINO has two options to run inference: + 1. Asynchronous (using StartAsync: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a405293e8423d82a5b45f642a3bef0d24) + 2. Synchronous (using Infer: https://docs.openvino.ai/latest/classInferenceEngine_1_1InferRequest.html#doxid-class-inference-engine-1-1-infer-request-1a3391ce30894abde730523e9ca9371ce8) + By default asynchronous mode is used. + + @param mode Inference mode which will be used. + @return reference to this parameter structure. + */ + Params& cfgInferMode(InferMode mode) { + desc.mode = mode; + return *this; + } + + /** @brief Specifies the output precision for model. + + The function is used to set an output precision for model. + + @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { + desc.output_precision = precision; + return *this; + } + + /** @overload + + @param precision_map Map of pairs: name of corresponding output layer + and its precision in OpenCV format (CV_8U, CV_32F, ...) + @return reference to this parameter structure. + */ + Params& + cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { + desc.output_precision = precision_map; + return *this; + } + + /** @brief Specifies the input layout for model. + + The function is used to set an input layout for model. + + @param layout Layout in string representation ("NCHW", "NHWC", etc) + will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& cfgInputLayout(std::string layout) { + desc.input_layout = std::move(layout); + return *this; + } + + /** @overload + + @param layout_map Map of pairs: name of corresponding input layer + and its layout in string representation ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgInputLayout(detail::AttrMap layout_map) { + desc.input_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies the output layout for model. + + The function is used to set an output layout for model. + + @param layout Layout in string representation ("NCHW", "NHWC", etc) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputLayout(std::string layout) { + desc.output_layout = std::move(layout); + return *this; + } + + /** @overload + + @param layout_map Map of pairs: name of corresponding output layer + and its layout in string representation ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgOutputLayout(detail::AttrMap layout_map) { + desc.output_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies resize interpolation algorithm. + * + The function is used to configure resize preprocessing for input layer. + + @param interpolation Resize interpolation algorithm. + Supported algorithms: #INTER_LINEAR, #INTER_AREA. + @return reference to this parameter structure. + */ + Params& cfgResize(int interpolation) { + desc.interpolation = interpolation; + return *this; + } + + /** @overload + + @param interpolation Map of pairs: name of corresponding input layer + and its resize algorithm. + @return reference to this parameter structure. + */ + Params& cfgResize(detail::AttrMap interpolation) { + desc.interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ie::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; +}; + +/* +* @brief This structure provides functions for generic network type that +* fill inference parameters. +* @see struct Generic +*/ +template<> +class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and sets default values for other + inference description parameters. Model is loaded and compiled using OpenVINO Toolkit. + + @param tag string tag of the network for which these parameters are intended. + @param model path to topology IR (.xml file). + @param weights path to weights (.bin file). + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &model, + const std::string &weights, + const std::string &device) + : desc{ model, weights, device, {}, {}, {}, 0u, 0u, + detail::ParamDesc::Kind::Load, true, {}, {}, {}, 1u, + {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, + m_tag(tag) { + } + + /** @overload + + This constructor for pre-compiled networks. Model is imported from pre-compiled + blob. + + @param tag string tag of the network for which these parameters are intended. + @param model path to model. + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &model, + const std::string &device) + : desc{ model, {}, device, {}, {}, {}, 0u, 0u, + detail::ParamDesc::Kind::Import, true, {}, {}, {}, 1u, + {}, {}, {}, {}, InferMode::Async, {}, {}, {}, {} }, + m_tag(tag) { + } + + /** @see ie::Params::pluginConfig. */ + Params& pluginConfig(const IEConfig& cfg) { + desc.config = cfg; + return *this; + } + + /** @overload */ + Params& pluginConfig(IEConfig&& cfg) { + desc.config = std::move(cfg); + return *this; + } + + /** @see ie::Params::constInput. */ + Params& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR) { + desc.const_inputs[layer_name] = {data, hint}; + return *this; + } + + /** @see ie::Params::cfgNumRequests. */ + Params& cfgNumRequests(size_t nireq) { + GAPI_Assert(nireq > 0 && "Number of infer requests must be greater than zero!"); + desc.nireq = nireq; + return *this; + } + + /** @see ie::Params::cfgInputReshape */ + Params& cfgInputReshape(const std::map>&reshape_table) { + desc.reshape_table = reshape_table; + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::map> && reshape_table) { + desc.reshape_table = std::move(reshape_table); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::string && layer_name, std::vector && layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(const std::string & layer_name, const std::vector&layer_dims) { + desc.reshape_table.emplace(layer_name, layer_dims); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(std::unordered_set && layer_names) { + desc.layer_names_to_reshape = std::move(layer_names); + return *this; + } + + /** @overload */ + Params& cfgInputReshape(const std::unordered_set&layer_names) { + desc.layer_names_to_reshape = layer_names; + return *this; + } + + /** @see ie::Params::cfgBatchSize */ + Params& cfgBatchSize(const size_t size) { + desc.batch_size = cv::util::make_optional(size); + return *this; + } + + /** @see ie::Params::cfgInferAPI */ + Params& cfgInferMode(InferMode mode) { + desc.mode = mode; + return *this; + } + + /** @see ie::Params::cfgOutputPrecision */ + Params& cfgOutputPrecision(detail::ParamDesc::PrecisionT precision) { + desc.output_precision = precision; + return *this; + } + + /** @overload */ + Params& + cfgOutputPrecision(detail::ParamDesc::PrecisionMapT precision_map) { + desc.output_precision = precision_map; + return *this; + } + + /** @see ie::Params::cfgInputLayout */ + Params& cfgInputLayout(std::string layout) { + desc.input_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgInputLayout(detail::AttrMap layout_map) { + desc.input_layout = std::move(layout_map); + return *this; + } + + /** @see ie::Params::cfgOutputLayout */ + Params& cfgOutputLayout(std::string layout) { + desc.output_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgOutputLayout(detail::AttrMap layout_map) { + desc.output_layout = std::move(layout_map); + return *this; + } + + /** @see ie::Params::cfgResize */ + Params& cfgResize(int interpolation) { + desc.interpolation = interpolation; + return *this; + } + + /** @overload */ + Params& cfgResize(detail::AttrMap interpolation) { + desc.interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ie::backend(); } + std::string tag() const { return m_tag; } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; + std::string m_tag; +}; + +} // namespace ie +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_IE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp index 9d93246da1..eb6316b446 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/onnx.hpp @@ -1,759 +1,759 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_ONNX_HPP -#define OPENCV_GAPI_INFER_ONNX_HPP - -#include -#include -#include -#include // tuple, tuple_size -#include - -#include -#include -#include - -#include // GAPI_EXPORTS -#include // GKernelPackage -#include // Generic - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API ONNX Runtime backend functions, structures, and symbols. - */ -namespace onnx { - -/** - * @brief This namespace contains Execution Providers structures for G-API ONNX Runtime backend. - */ -namespace ep { - -/** - * @brief This structure provides functions - * that fill inference options for ONNX CoreML Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml-execution-provider - */ -struct GAPI_EXPORTS_W_SIMPLE CoreML { - /** @brief Class constructor. - - Constructs CoreML parameters. - - */ - GAPI_WRAP - CoreML() = default; - - /** @brief Limit CoreML Execution Provider to run on CPU only. - - This function is used to limit CoreML to run on CPU only. - Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_use_cpu_only - - @return reference to this parameter structure. - */ - GAPI_WRAP - CoreML& cfgUseCPUOnly() { - use_cpu_only = true; - return *this; - } - - /** @brief Enable CoreML EP to run on a subgraph in the body of a control flow ONNX operator (i.e. a Loop, Scan or If operator). - - This function is used to enable CoreML EP to run on - a subgraph of a control flow of ONNX operation. - Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_enable_on_subgraph - - @return reference to this parameter structure. - */ - GAPI_WRAP - CoreML& cfgEnableOnSubgraph() { - enable_on_subgraph = true; - return *this; - } - - /** @brief Enable CoreML EP to run only on Apple Neural Engine. - - This function is used to enable CoreML EP to run only on Apple Neural Engine. - Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_only_enable_device_with_ane - - @return reference to this parameter structure. - */ - GAPI_WRAP - CoreML& cfgEnableOnlyNeuralEngine() { - enable_only_ane = true; - return *this; - } - - bool use_cpu_only = false; - bool enable_on_subgraph = false; - bool enable_only_ane = false; -}; - -/** - * @brief This structure provides functions - * that fill inference options for CUDA Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-execution-provider - */ -struct GAPI_EXPORTS_W_SIMPLE CUDA { - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - CUDA() = default; - - /** @brief Class constructor. - - Constructs CUDA parameters based on device type information. - - @param dev_id Target device id to use. - */ - GAPI_WRAP - explicit CUDA(const int dev_id) - : device_id(dev_id) { - } - - int device_id; -}; - -/** - * @brief This structure provides functions - * that fill inference options for TensorRT Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#tensorrt-execution-provider - */ -struct GAPI_EXPORTS_W_SIMPLE TensorRT { - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - TensorRT() = default; - - /** @brief Class constructor. - - Constructs TensorRT parameters based on device type information. - - @param dev_id Target device id to use. - */ - GAPI_WRAP - explicit TensorRT(const int dev_id) - : device_id(dev_id) { - } - - int device_id; -}; - -/** - * @brief This structure provides functions - * that fill inference options for ONNX OpenVINO Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html#summary-of-options - */ -struct GAPI_EXPORTS_W_SIMPLE OpenVINO { - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - OpenVINO() = default; - - /** @brief Class constructor. - - Constructs OpenVINO parameters based on device type information. - - @param dev_type Target device type to use. ("CPU", "GPU", "GPU.0" etc) - */ - GAPI_WRAP - explicit OpenVINO(const std::string &dev_type) - : device_type(dev_type) { - } - - /** @brief Class constructor. - - Constructs OpenVINO parameters based on map of options passed. - - * @param params A map of parameter names and their corresponding string values. - */ - GAPI_WRAP - explicit OpenVINO(const std::map& params) - : params_map(params) { - } - - /** @brief Specifies OpenVINO Execution Provider cache dir. - - This function is used to explicitly specify the path to save and load - the blobs enabling model caching feature. - - @param dir Path to the directory what will be used as cache. - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgCacheDir(const std::string &dir) { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - cache_dir = dir; - return *this; - } - - /** @brief Specifies OpenVINO Execution Provider number of threads. - - This function is used to override the accelerator default value - of number of threads with this value at runtime. - - @param nthreads Number of threads. - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgNumThreads(size_t nthreads) { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - num_of_threads = nthreads; - return *this; - } - - /** @brief Enables OpenVINO Execution Provider opencl throttling. - - This function is used to enable OpenCL queue throttling for GPU devices - (reduces CPU utilization when using GPU). - - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgEnableOpenCLThrottling() { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - enable_opencl_throttling = true; - return *this; - } - - /** @brief Enables OpenVINO Execution Provider dynamic shapes. - - This function is used to enable OpenCL queue throttling for GPU devices - (reduces CPU utilization when using GPU). - This function is used to enable work with dynamic shaped models - whose shape will be set dynamically based on the infer input - image/data shape at run time in CPU. - - @return reference to this parameter structure. - */ - GAPI_WRAP - OpenVINO& cfgEnableDynamicShapes() { - if (!params_map.empty()) { - cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" - "created from the parameters map.")); - } - enable_dynamic_shapes = true; - return *this; - } - - std::string device_type; - std::string cache_dir; - size_t num_of_threads = 0; - bool enable_opencl_throttling = false; - bool enable_dynamic_shapes = false; - std::map params_map; -}; - -/** - * @brief This structure provides functions - * that fill inference options for ONNX DirectML Execution Provider. - * Please follow https://onnxruntime.ai/docs/execution-providers/DirectML-ExecutionProvider.html#directml-execution-provider - */ -class GAPI_EXPORTS_W_SIMPLE DirectML { -public: - // NB: Used from python. - /// @private -- Exclude this constructor from OpenCV documentation - GAPI_WRAP - DirectML() = default; - - /** @brief Class constructor. - - Constructs DirectML parameters based on device id. - - @param device_id Target device id to use. ("0", "1", etc) - */ - GAPI_WRAP - explicit DirectML(const int device_id) : ddesc(device_id) { }; - - /** @brief Class constructor. - - Constructs DirectML parameters based on adapter name. - - @param adapter_name Target adapter_name to use. - */ - GAPI_WRAP - explicit DirectML(const std::string &adapter_name) : ddesc(adapter_name) { }; - - using DeviceDesc = cv::util::variant; - DeviceDesc ddesc; -}; - -using EP = cv::util::variant< cv::util::monostate - , OpenVINO - , DirectML - , CoreML - , CUDA - , TensorRT>; - -} // namespace ep - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -enum class TraitAs: int { - TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor - // and passes dimensions as-is - IMAGE //!< G-API traits an associated cv::Mat as an image so - // creates an "image" blob (NCHW/NHWC, etc) -}; - -using PostProc = std::function &, - std::unordered_map &)>; - -namespace detail { -/** -* @brief This structure contains description of inference parameters -* which is specific to ONNX models. -*/ -struct ParamDesc { - std::string model_path; //!< Path to model. - - // NB: nun_* may differ from topology's real input/output port numbers - // (e.g. topology's partial execution) - std::size_t num_in; //!< How many inputs are defined in the operation - std::size_t num_out; //!< How many outputs are defined in the operation - - // NB: Here order follows the `Net` API - std::vector input_names; //!< Names of input network layers. - std::vector output_names; //!< Names of output network layers. - - using ConstInput = std::pair; - std::unordered_map const_inputs; //!< Map with pair of name of network layer and ConstInput which will be associated with this. - - std::vector mean; //!< Mean values for preprocessing. - std::vector stdev; //!< Standard deviation values for preprocessing. - - std::vector out_metas; //!< Out meta information about your output (type, dimension). - PostProc custom_post_proc; //!< Post processing function. - - std::vector normalize; //!< Vector of bool values that enabled or disabled normalize of input data. - - std::vector names_to_remap; //!< Names of output layers that will be processed in PostProc function. - - bool is_generic; - - // TODO: Needs to modify the rest of ParamDesc accordingly to support - // both generic and non-generic options without duplication - // (as it was done for the OV IE backend) - // These values are pushed into the respective vector<> fields above - // when the generic infer parameters are unpacked (see GONNXBackendImpl::unpackKernel) - std::unordered_map > generic_mstd; - std::unordered_map generic_norm; - - std::map session_options; - std::vector execution_providers; - bool disable_mem_pattern; - cv::util::optional opt_level; -}; -} // namespace detail - -template -struct PortCfg { - using In = std::array - < std::string - , std::tuple_size::value >; - using Out = std::array - < std::string - , std::tuple_size::value >; - using NormCoefs = std::array - < cv::Scalar - , std::tuple_size::value >; - using Normalize = std::array - < bool - , std::tuple_size::value >; -}; - -/** - * Contains description of inference parameters and kit of functions that - * fill this parameters. - */ -template class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and sets default values for other - inference description parameters. - - @param model Path to model (.onnx file). - */ - Params(const std::string &model) { - desc.model_path = model; - desc.num_in = std::tuple_size::value; - desc.num_out = std::tuple_size::value; - desc.is_generic = false; - desc.disable_mem_pattern = false; - } - - /** @brief Specifies sequence of network input layers names for inference. - - The function is used to associate data of graph inputs with input layers of - network topology. Number of names has to match the number of network inputs. If a network - has only one input layer, there is no need to call it as the layer is - associated with input automatically but this doesn't prevent you from - doing it yourself. Count of names has to match to number of network inputs. - - @param layer_names std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains names of input layers. - @return the reference on modified object. - */ - Params& cfgInputLayers(const typename PortCfg::In &layer_names) { - desc.input_names.assign(layer_names.begin(), layer_names.end()); - return *this; - } - - /** @brief Specifies sequence of output layers names for inference. - - The function is used to associate data of graph outputs with output layers of - network topology. If a network has only one output layer, there is no need to call it - as the layer is associated with output automatically but this doesn't prevent - you from doing it yourself. Count of names has to match to number of network - outputs or you can set your own output but for this case you have to - additionally use @ref cfgPostProc function. - - @param layer_names std::array where N is the number of outputs - as defined in the @ref G_API_NET. Contains names of output layers. - @return the reference on modified object. - */ - Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { - desc.output_names.assign(layer_names.begin(), layer_names.end()); - return *this; - } - - /** @brief Sets a constant input. - - The function is used to set constant input. This input has to be - a prepared tensor since preprocessing is disabled for this case. You should - provide name of network layer which will receive provided data. - - @param layer_name Name of network layer. - @param data cv::Mat that contains data which will be associated with network layer. - @param hint Type of input (TENSOR). - @return the reference on modified object. - */ - Params& constInput(const std::string &layer_name, - const cv::Mat &data, - TraitAs hint = TraitAs::TENSOR) { - desc.const_inputs[layer_name] = {data, hint}; - return *this; - } - - /** @brief Specifies mean value and standard deviation for preprocessing. - - The function is used to set mean value and standard deviation for preprocessing - of input data. - - @param m std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains mean values. - @param s std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains standard deviation values. - @return the reference on modified object. - */ - Params& cfgMeanStd(const typename PortCfg::NormCoefs &m, - const typename PortCfg::NormCoefs &s) { - desc.mean.assign(m.begin(), m.end()); - desc.stdev.assign(s.begin(), s.end()); - return *this; - } - - /** @brief Configures graph output and provides the post processing function from user. - - The function is used when you work with networks with dynamic outputs. - Since we can't know dimensions of inference result needs provide them for - construction of graph output. This dimensions can differ from inference result. - So you have to provide @ref PostProc function that gets information from inference - result and fill output which is constructed by dimensions from out_metas. - - @param out_metas Out meta information about your output (type, dimension). - @param remap_function Post processing function, which has two parameters. First is onnx - result, second is graph output. Both parameters is std::map that contain pair of - layer's name and cv::Mat. - @return the reference on modified object. - */ - Params& cfgPostProc(const std::vector &out_metas, - const PostProc &remap_function) { - desc.out_metas = out_metas; - desc.custom_post_proc = remap_function; - return *this; - } - - /** @overload - Function with a rvalue parameters. - - @param out_metas rvalue out meta information about your output (type, dimension). - @param remap_function rvalue post processing function, which has two parameters. First is onnx - result, second is graph output. Both parameters is std::map that contain pair of - layer's name and cv::Mat. - @return the reference on modified object. - */ - Params& cfgPostProc(std::vector &&out_metas, - PostProc &&remap_function) { - desc.out_metas = std::move(out_metas); - desc.custom_post_proc = std::move(remap_function); - return *this; - } - - /** @overload - The function has additional parameter names_to_remap. This parameter provides - information about output layers which will be used for inference and post - processing function. - - @param out_metas Out meta information. - @param remap_function Post processing function. - @param names_to_remap Names of output layers. network's inference will - be done on these layers. Inference's result will be processed in post processing - function using these names. - @return the reference on modified object. - */ - Params& cfgPostProc(const std::vector &out_metas, - const PostProc &remap_function, - const std::vector &names_to_remap) { - desc.out_metas = out_metas; - desc.custom_post_proc = remap_function; - desc.names_to_remap = names_to_remap; - return *this; - } - - /** @overload - Function with a rvalue parameters and additional parameter names_to_remap. - - @param out_metas rvalue out meta information. - @param remap_function rvalue post processing function. - @param names_to_remap rvalue names of output layers. network's inference will - be done on these layers. Inference's result will be processed in post processing - function using these names. - @return the reference on modified object. - */ - Params& cfgPostProc(std::vector &&out_metas, - PostProc &&remap_function, - std::vector &&names_to_remap) { - desc.out_metas = std::move(out_metas); - desc.custom_post_proc = std::move(remap_function); - desc.names_to_remap = std::move(names_to_remap); - return *this; - } - - /** @brief Specifies normalize parameter for preprocessing. - - The function is used to set normalize parameter for preprocessing of input data. - - @param normalizations std::array where N is the number of inputs - as defined in the @ref G_API_NET. Сontains bool values that enabled or disabled - normalize of input data. - @return the reference on modified object. - */ - Params& cfgNormalize(const typename PortCfg::Normalize &normalizations) { - desc.normalize.assign(normalizations.begin(), normalizations.end()); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime OpenVINO Execution Provider options. - - @param ep OpenVINO Execution Provider options. - @see cv::gapi::onnx::ep::OpenVINO. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::OpenVINO&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime DirectML Execution Provider options. - - @param ep DirectML Execution Provider options. - @see cv::gapi::onnx::ep::DirectML. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::DirectML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime CoreML Execution Provider options. - - @param ep CoreML Execution Provider options. - @see cv::gapi::onnx::ep::CoreML. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::CoreML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime CUDA Execution Provider options. - - @param ep CUDA Execution Provider options. - @see cv::gapi::onnx::ep::CUDA. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::CUDA&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Adds execution provider for runtime. - - The function is used to add ONNX Runtime TensorRT Execution Provider options. - - @param ep TensorRT Execution Provider options. - @see cv::gapi::onnx::ep::TensorRT. - - @return the reference on modified object. - */ - Params& cfgAddExecutionProvider(ep::TensorRT&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - return *this; - } - - /** @brief Disables the memory pattern optimization. - - @return the reference on modified object. - */ - Params& cfgDisableMemPattern() { - desc.disable_mem_pattern = true; - return *this; - } - - /** @brief Configures session options for ONNX Runtime. - - This function is used to set various session options for the ONNX Runtime - session by accepting a map of key-value pairs. - - @param options A map of session option to be applied to the ONNX Runtime session. - @return the reference on modified object. - */ - Params& cfgSessionOptions(const std::map& options) { - desc.session_options.insert(options.begin(), options.end()); - return *this; - } - - /** @brief Configures optimization level for ONNX Runtime. - - @param opt_level [optimization level]: Valid values are 0 (disable), 1 (basic), 2 (extended), 99 (all). - Please see onnxruntime_c_api.h (enum GraphOptimizationLevel) for the full list of all optimization levels. - @return the reference on modified object. - */ - Params& cfgOptLevel(const int opt_level) { - desc.opt_level = cv::util::make_optional(opt_level); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::onnx::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; -}; - -/* -* @brief This structure provides functions for generic network type that -* fill inference parameters. -* @see struct Generic -*/ -template<> -class Params { -public: - /** @brief Class constructor. - - Constructs Params based on input information and sets default values for other - inference description parameters. - - @param tag string tag of the network for which these parameters are intended. - @param model_path path to model file (.onnx file). - */ - Params(const std::string& tag, const std::string& model_path) - : desc{ model_path, 0u, 0u, {}, {}, {}, {}, {}, {}, {}, {}, {}, true, {}, {}, {}, {}, false, {} }, m_tag(tag) {} - - /** @see onnx::Params::cfgMeanStdDev. */ - void cfgMeanStdDev(const std::string &layer, - const cv::Scalar &m, - const cv::Scalar &s) { - desc.generic_mstd[layer] = std::make_pair(m, s); - } - - /** @see onnx::Params::cfgNormalize. */ - void cfgNormalize(const std::string &layer, bool flag) { - desc.generic_norm[layer] = flag; - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::OpenVINO&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::DirectML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::CoreML&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::CUDA&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgAddExecutionProvider. */ - void cfgAddExecutionProvider(ep::TensorRT&& ep) { - desc.execution_providers.emplace_back(std::move(ep)); - } - - /** @see onnx::Params::cfgDisableMemPattern. */ - void cfgDisableMemPattern() { - desc.disable_mem_pattern = true; - } - - /** @see onnx::Params::cfgSessionOptions. */ - void cfgSessionOptions(const std::map& options) { - desc.session_options.insert(options.begin(), options.end()); - } - -/** @see onnx::Params::cfgOptLevel. */ - void cfgOptLevel(const int opt_level) { - desc.opt_level = cv::util::make_optional(opt_level); - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::onnx::backend(); } - std::string tag() const { return m_tag; } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) -protected: - detail::ParamDesc desc; - std::string m_tag; -}; - -} // namespace onnx -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_INFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_ONNX_HPP +#define OPENCV_GAPI_INFER_ONNX_HPP + +#include +#include +#include +#include // tuple, tuple_size +#include + +#include +#include +#include + +#include // GAPI_EXPORTS +#include // GKernelPackage +#include // Generic + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API ONNX Runtime backend functions, structures, and symbols. + */ +namespace onnx { + +/** + * @brief This namespace contains Execution Providers structures for G-API ONNX Runtime backend. + */ +namespace ep { + +/** + * @brief This structure provides functions + * that fill inference options for ONNX CoreML Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml-execution-provider + */ +struct GAPI_EXPORTS_W_SIMPLE CoreML { + /** @brief Class constructor. + + Constructs CoreML parameters. + + */ + GAPI_WRAP + CoreML() = default; + + /** @brief Limit CoreML Execution Provider to run on CPU only. + + This function is used to limit CoreML to run on CPU only. + Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_use_cpu_only + + @return reference to this parameter structure. + */ + GAPI_WRAP + CoreML& cfgUseCPUOnly() { + use_cpu_only = true; + return *this; + } + + /** @brief Enable CoreML EP to run on a subgraph in the body of a control flow ONNX operator (i.e. a Loop, Scan or If operator). + + This function is used to enable CoreML EP to run on + a subgraph of a control flow of ONNX operation. + Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_enable_on_subgraph + + @return reference to this parameter structure. + */ + GAPI_WRAP + CoreML& cfgEnableOnSubgraph() { + enable_on_subgraph = true; + return *this; + } + + /** @brief Enable CoreML EP to run only on Apple Neural Engine. + + This function is used to enable CoreML EP to run only on Apple Neural Engine. + Please follow: https://onnxruntime.ai/docs/execution-providers/CoreML-ExecutionProvider.html#coreml_flag_only_enable_device_with_ane + + @return reference to this parameter structure. + */ + GAPI_WRAP + CoreML& cfgEnableOnlyNeuralEngine() { + enable_only_ane = true; + return *this; + } + + bool use_cpu_only = false; + bool enable_on_subgraph = false; + bool enable_only_ane = false; +}; + +/** + * @brief This structure provides functions + * that fill inference options for CUDA Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#cuda-execution-provider + */ +struct GAPI_EXPORTS_W_SIMPLE CUDA { + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + CUDA() = default; + + /** @brief Class constructor. + + Constructs CUDA parameters based on device type information. + + @param dev_id Target device id to use. + */ + GAPI_WRAP + explicit CUDA(const int dev_id) + : device_id(dev_id) { + } + + int device_id; +}; + +/** + * @brief This structure provides functions + * that fill inference options for TensorRT Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/TensorRT-ExecutionProvider.html#tensorrt-execution-provider + */ +struct GAPI_EXPORTS_W_SIMPLE TensorRT { + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + TensorRT() = default; + + /** @brief Class constructor. + + Constructs TensorRT parameters based on device type information. + + @param dev_id Target device id to use. + */ + GAPI_WRAP + explicit TensorRT(const int dev_id) + : device_id(dev_id) { + } + + int device_id; +}; + +/** + * @brief This structure provides functions + * that fill inference options for ONNX OpenVINO Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/OpenVINO-ExecutionProvider.html#summary-of-options + */ +struct GAPI_EXPORTS_W_SIMPLE OpenVINO { + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + OpenVINO() = default; + + /** @brief Class constructor. + + Constructs OpenVINO parameters based on device type information. + + @param dev_type Target device type to use. ("CPU", "GPU", "GPU.0" etc) + */ + GAPI_WRAP + explicit OpenVINO(const std::string &dev_type) + : device_type(dev_type) { + } + + /** @brief Class constructor. + + Constructs OpenVINO parameters based on map of options passed. + + * @param params A map of parameter names and their corresponding string values. + */ + GAPI_WRAP + explicit OpenVINO(const std::map& params) + : params_map(params) { + } + + /** @brief Specifies OpenVINO Execution Provider cache dir. + + This function is used to explicitly specify the path to save and load + the blobs enabling model caching feature. + + @param dir Path to the directory what will be used as cache. + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgCacheDir(const std::string &dir) { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + cache_dir = dir; + return *this; + } + + /** @brief Specifies OpenVINO Execution Provider number of threads. + + This function is used to override the accelerator default value + of number of threads with this value at runtime. + + @param nthreads Number of threads. + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgNumThreads(size_t nthreads) { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + num_of_threads = nthreads; + return *this; + } + + /** @brief Enables OpenVINO Execution Provider opencl throttling. + + This function is used to enable OpenCL queue throttling for GPU devices + (reduces CPU utilization when using GPU). + + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgEnableOpenCLThrottling() { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + enable_opencl_throttling = true; + return *this; + } + + /** @brief Enables OpenVINO Execution Provider dynamic shapes. + + This function is used to enable OpenCL queue throttling for GPU devices + (reduces CPU utilization when using GPU). + This function is used to enable work with dynamic shaped models + whose shape will be set dynamically based on the infer input + image/data shape at run time in CPU. + + @return reference to this parameter structure. + */ + GAPI_WRAP + OpenVINO& cfgEnableDynamicShapes() { + if (!params_map.empty()) { + cv::util::throw_error(std::logic_error("ep::OpenVINO cannot be changed if" + "created from the parameters map.")); + } + enable_dynamic_shapes = true; + return *this; + } + + std::string device_type; + std::string cache_dir; + size_t num_of_threads = 0; + bool enable_opencl_throttling = false; + bool enable_dynamic_shapes = false; + std::map params_map; +}; + +/** + * @brief This structure provides functions + * that fill inference options for ONNX DirectML Execution Provider. + * Please follow https://onnxruntime.ai/docs/execution-providers/DirectML-ExecutionProvider.html#directml-execution-provider + */ +class GAPI_EXPORTS_W_SIMPLE DirectML { +public: + // NB: Used from python. + /// @private -- Exclude this constructor from OpenCV documentation + GAPI_WRAP + DirectML() = default; + + /** @brief Class constructor. + + Constructs DirectML parameters based on device id. + + @param device_id Target device id to use. ("0", "1", etc) + */ + GAPI_WRAP + explicit DirectML(const int device_id) : ddesc(device_id) { }; + + /** @brief Class constructor. + + Constructs DirectML parameters based on adapter name. + + @param adapter_name Target adapter_name to use. + */ + GAPI_WRAP + explicit DirectML(const std::string &adapter_name) : ddesc(adapter_name) { }; + + using DeviceDesc = cv::util::variant; + DeviceDesc ddesc; +}; + +using EP = cv::util::variant< cv::util::monostate + , OpenVINO + , DirectML + , CoreML + , CUDA + , TensorRT>; + +} // namespace ep + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +enum class TraitAs: int { + TENSOR, //!< G-API traits an associated cv::Mat as a raw tensor + // and passes dimensions as-is + IMAGE //!< G-API traits an associated cv::Mat as an image so + // creates an "image" blob (NCHW/NHWC, etc) +}; + +using PostProc = std::function &, + std::unordered_map &)>; + +namespace detail { +/** +* @brief This structure contains description of inference parameters +* which is specific to ONNX models. +*/ +struct ParamDesc { + std::string model_path; //!< Path to model. + + // NB: nun_* may differ from topology's real input/output port numbers + // (e.g. topology's partial execution) + std::size_t num_in; //!< How many inputs are defined in the operation + std::size_t num_out; //!< How many outputs are defined in the operation + + // NB: Here order follows the `Net` API + std::vector input_names; //!< Names of input network layers. + std::vector output_names; //!< Names of output network layers. + + using ConstInput = std::pair; + std::unordered_map const_inputs; //!< Map with pair of name of network layer and ConstInput which will be associated with this. + + std::vector mean; //!< Mean values for preprocessing. + std::vector stdev; //!< Standard deviation values for preprocessing. + + std::vector out_metas; //!< Out meta information about your output (type, dimension). + PostProc custom_post_proc; //!< Post processing function. + + std::vector normalize; //!< Vector of bool values that enabled or disabled normalize of input data. + + std::vector names_to_remap; //!< Names of output layers that will be processed in PostProc function. + + bool is_generic; + + // TODO: Needs to modify the rest of ParamDesc accordingly to support + // both generic and non-generic options without duplication + // (as it was done for the OV IE backend) + // These values are pushed into the respective vector<> fields above + // when the generic infer parameters are unpacked (see GONNXBackendImpl::unpackKernel) + std::unordered_map > generic_mstd; + std::unordered_map generic_norm; + + std::map session_options; + std::vector execution_providers; + bool disable_mem_pattern; + cv::util::optional opt_level; +}; +} // namespace detail + +template +struct PortCfg { + using In = std::array + < std::string + , std::tuple_size::value >; + using Out = std::array + < std::string + , std::tuple_size::value >; + using NormCoefs = std::array + < cv::Scalar + , std::tuple_size::value >; + using Normalize = std::array + < bool + , std::tuple_size::value >; +}; + +/** + * Contains description of inference parameters and kit of functions that + * fill this parameters. + */ +template class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and sets default values for other + inference description parameters. + + @param model Path to model (.onnx file). + */ + Params(const std::string &model) { + desc.model_path = model; + desc.num_in = std::tuple_size::value; + desc.num_out = std::tuple_size::value; + desc.is_generic = false; + desc.disable_mem_pattern = false; + } + + /** @brief Specifies sequence of network input layers names for inference. + + The function is used to associate data of graph inputs with input layers of + network topology. Number of names has to match the number of network inputs. If a network + has only one input layer, there is no need to call it as the layer is + associated with input automatically but this doesn't prevent you from + doing it yourself. Count of names has to match to number of network inputs. + + @param layer_names std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains names of input layers. + @return the reference on modified object. + */ + Params& cfgInputLayers(const typename PortCfg::In &layer_names) { + desc.input_names.assign(layer_names.begin(), layer_names.end()); + return *this; + } + + /** @brief Specifies sequence of output layers names for inference. + + The function is used to associate data of graph outputs with output layers of + network topology. If a network has only one output layer, there is no need to call it + as the layer is associated with output automatically but this doesn't prevent + you from doing it yourself. Count of names has to match to number of network + outputs or you can set your own output but for this case you have to + additionally use @ref cfgPostProc function. + + @param layer_names std::array where N is the number of outputs + as defined in the @ref G_API_NET. Contains names of output layers. + @return the reference on modified object. + */ + Params& cfgOutputLayers(const typename PortCfg::Out &layer_names) { + desc.output_names.assign(layer_names.begin(), layer_names.end()); + return *this; + } + + /** @brief Sets a constant input. + + The function is used to set constant input. This input has to be + a prepared tensor since preprocessing is disabled for this case. You should + provide name of network layer which will receive provided data. + + @param layer_name Name of network layer. + @param data cv::Mat that contains data which will be associated with network layer. + @param hint Type of input (TENSOR). + @return the reference on modified object. + */ + Params& constInput(const std::string &layer_name, + const cv::Mat &data, + TraitAs hint = TraitAs::TENSOR) { + desc.const_inputs[layer_name] = {data, hint}; + return *this; + } + + /** @brief Specifies mean value and standard deviation for preprocessing. + + The function is used to set mean value and standard deviation for preprocessing + of input data. + + @param m std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains mean values. + @param s std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains standard deviation values. + @return the reference on modified object. + */ + Params& cfgMeanStd(const typename PortCfg::NormCoefs &m, + const typename PortCfg::NormCoefs &s) { + desc.mean.assign(m.begin(), m.end()); + desc.stdev.assign(s.begin(), s.end()); + return *this; + } + + /** @brief Configures graph output and provides the post processing function from user. + + The function is used when you work with networks with dynamic outputs. + Since we can't know dimensions of inference result needs provide them for + construction of graph output. This dimensions can differ from inference result. + So you have to provide @ref PostProc function that gets information from inference + result and fill output which is constructed by dimensions from out_metas. + + @param out_metas Out meta information about your output (type, dimension). + @param remap_function Post processing function, which has two parameters. First is onnx + result, second is graph output. Both parameters is std::map that contain pair of + layer's name and cv::Mat. + @return the reference on modified object. + */ + Params& cfgPostProc(const std::vector &out_metas, + const PostProc &remap_function) { + desc.out_metas = out_metas; + desc.custom_post_proc = remap_function; + return *this; + } + + /** @overload + Function with a rvalue parameters. + + @param out_metas rvalue out meta information about your output (type, dimension). + @param remap_function rvalue post processing function, which has two parameters. First is onnx + result, second is graph output. Both parameters is std::map that contain pair of + layer's name and cv::Mat. + @return the reference on modified object. + */ + Params& cfgPostProc(std::vector &&out_metas, + PostProc &&remap_function) { + desc.out_metas = std::move(out_metas); + desc.custom_post_proc = std::move(remap_function); + return *this; + } + + /** @overload + The function has additional parameter names_to_remap. This parameter provides + information about output layers which will be used for inference and post + processing function. + + @param out_metas Out meta information. + @param remap_function Post processing function. + @param names_to_remap Names of output layers. network's inference will + be done on these layers. Inference's result will be processed in post processing + function using these names. + @return the reference on modified object. + */ + Params& cfgPostProc(const std::vector &out_metas, + const PostProc &remap_function, + const std::vector &names_to_remap) { + desc.out_metas = out_metas; + desc.custom_post_proc = remap_function; + desc.names_to_remap = names_to_remap; + return *this; + } + + /** @overload + Function with a rvalue parameters and additional parameter names_to_remap. + + @param out_metas rvalue out meta information. + @param remap_function rvalue post processing function. + @param names_to_remap rvalue names of output layers. network's inference will + be done on these layers. Inference's result will be processed in post processing + function using these names. + @return the reference on modified object. + */ + Params& cfgPostProc(std::vector &&out_metas, + PostProc &&remap_function, + std::vector &&names_to_remap) { + desc.out_metas = std::move(out_metas); + desc.custom_post_proc = std::move(remap_function); + desc.names_to_remap = std::move(names_to_remap); + return *this; + } + + /** @brief Specifies normalize parameter for preprocessing. + + The function is used to set normalize parameter for preprocessing of input data. + + @param normalizations std::array where N is the number of inputs + as defined in the @ref G_API_NET. Сontains bool values that enabled or disabled + normalize of input data. + @return the reference on modified object. + */ + Params& cfgNormalize(const typename PortCfg::Normalize &normalizations) { + desc.normalize.assign(normalizations.begin(), normalizations.end()); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime OpenVINO Execution Provider options. + + @param ep OpenVINO Execution Provider options. + @see cv::gapi::onnx::ep::OpenVINO. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::OpenVINO&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime DirectML Execution Provider options. + + @param ep DirectML Execution Provider options. + @see cv::gapi::onnx::ep::DirectML. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::DirectML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime CoreML Execution Provider options. + + @param ep CoreML Execution Provider options. + @see cv::gapi::onnx::ep::CoreML. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::CoreML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime CUDA Execution Provider options. + + @param ep CUDA Execution Provider options. + @see cv::gapi::onnx::ep::CUDA. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::CUDA&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Adds execution provider for runtime. + + The function is used to add ONNX Runtime TensorRT Execution Provider options. + + @param ep TensorRT Execution Provider options. + @see cv::gapi::onnx::ep::TensorRT. + + @return the reference on modified object. + */ + Params& cfgAddExecutionProvider(ep::TensorRT&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + return *this; + } + + /** @brief Disables the memory pattern optimization. + + @return the reference on modified object. + */ + Params& cfgDisableMemPattern() { + desc.disable_mem_pattern = true; + return *this; + } + + /** @brief Configures session options for ONNX Runtime. + + This function is used to set various session options for the ONNX Runtime + session by accepting a map of key-value pairs. + + @param options A map of session option to be applied to the ONNX Runtime session. + @return the reference on modified object. + */ + Params& cfgSessionOptions(const std::map& options) { + desc.session_options.insert(options.begin(), options.end()); + return *this; + } + + /** @brief Configures optimization level for ONNX Runtime. + + @param opt_level [optimization level]: Valid values are 0 (disable), 1 (basic), 2 (extended), 99 (all). + Please see onnxruntime_c_api.h (enum GraphOptimizationLevel) for the full list of all optimization levels. + @return the reference on modified object. + */ + Params& cfgOptLevel(const int opt_level) { + desc.opt_level = cv::util::make_optional(opt_level); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::onnx::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; +}; + +/* +* @brief This structure provides functions for generic network type that +* fill inference parameters. +* @see struct Generic +*/ +template<> +class Params { +public: + /** @brief Class constructor. + + Constructs Params based on input information and sets default values for other + inference description parameters. + + @param tag string tag of the network for which these parameters are intended. + @param model_path path to model file (.onnx file). + */ + Params(const std::string& tag, const std::string& model_path) + : desc{ model_path, 0u, 0u, {}, {}, {}, {}, {}, {}, {}, {}, {}, true, {}, {}, {}, {}, false, {} }, m_tag(tag) {} + + /** @see onnx::Params::cfgMeanStdDev. */ + void cfgMeanStdDev(const std::string &layer, + const cv::Scalar &m, + const cv::Scalar &s) { + desc.generic_mstd[layer] = std::make_pair(m, s); + } + + /** @see onnx::Params::cfgNormalize. */ + void cfgNormalize(const std::string &layer, bool flag) { + desc.generic_norm[layer] = flag; + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::OpenVINO&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::DirectML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::CoreML&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::CUDA&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgAddExecutionProvider. */ + void cfgAddExecutionProvider(ep::TensorRT&& ep) { + desc.execution_providers.emplace_back(std::move(ep)); + } + + /** @see onnx::Params::cfgDisableMemPattern. */ + void cfgDisableMemPattern() { + desc.disable_mem_pattern = true; + } + + /** @see onnx::Params::cfgSessionOptions. */ + void cfgSessionOptions(const std::map& options) { + desc.session_options.insert(options.begin(), options.end()); + } + +/** @see onnx::Params::cfgOptLevel. */ + void cfgOptLevel(const int opt_level) { + desc.opt_level = cv::util::make_optional(opt_level); + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::onnx::backend(); } + std::string tag() const { return m_tag; } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) +protected: + detail::ParamDesc desc; + std::string m_tag; +}; + +} // namespace onnx +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_INFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp index 9a3fc5659d..782792489b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/ov.hpp @@ -1,709 +1,709 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_INFER_OV_HPP -#define OPENCV_GAPI_INFER_OV_HPP - -#include - -#include -#include // GAPI_EXPORTS -#include // GKernelType[M], GBackend -#include // Generic - -#include - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API OpenVINO 2.0 backend functions, - * structures, and symbols. - */ -namespace ov { - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -namespace detail { - -template -using AttrMap = std::map; -// NB: This type is supposed to be used to hold in/out layers -// attributes such as precision, layout, shape etc. -// -// User can provide attributes either: -// 1. cv::util::monostate - No value specified explicitly. -// 2. Attr - value specified explicitly that should be broadcasted to all layers. -// 3. AttrMap[str->T] - map specifies value for particular layer. -template -using LayerVariantAttr = cv::util::variant< cv::util::monostate - , AttrMap - , Attr>; - -struct ParamDesc { - struct Model { - - Model(const std::string &model_path_, - const std::string &bin_path_) - : model_path(model_path_), bin_path(bin_path_) { - } - - std::string model_path; - std::string bin_path; - - LayerVariantAttr input_tensor_layout; - LayerVariantAttr input_model_layout; - LayerVariantAttr output_tensor_layout; - LayerVariantAttr output_model_layout; - LayerVariantAttr output_tensor_precision; - - LayerVariantAttr> new_shapes; - - LayerVariantAttr> mean_values; - LayerVariantAttr> scale_values; - - LayerVariantAttr interpolation; - }; - - struct CompiledModel { - std::string blob_path; - }; - - using Kind = cv::util::variant; - - ParamDesc(Kind &&kind_, - const std::string &device_, - const bool is_generic_, - const size_t num_in_, - const size_t num_out_) - : kind(std::move(kind_)), device(device_), - is_generic(is_generic_), - num_in(num_in_), num_out(num_out_) { - } - - Kind kind; - - std::string device; - bool is_generic; - - std::size_t num_in; - std::size_t num_out; - - std::vector input_names; - std::vector output_names; - - using PluginConfigT = std::map; - PluginConfigT config; - - size_t nireq = 1; -}; - -// NB: Just helper to avoid code duplication. -static detail::ParamDesc::Model& -getModelToSetAttrOrThrow(detail::ParamDesc::Kind &kind, - const std::string &attr_name) { - if (cv::util::holds_alternative(kind)) { - cv::util::throw_error( - std::logic_error("Specifying " + attr_name + " isn't" - " possible for compiled model.")); - } - GAPI_Assert(cv::util::holds_alternative(kind)); - return cv::util::get(kind); -} - -} // namespace detail - -/** - * @brief This structure provides functions - * that fill inference parameters for "OpenVINO Toolkit" model. - */ -template struct Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and specifies default values for other - inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". - - @param model_path Path to a model. - @param bin_path Path to a data file. - For IR format (*.bin): - If path is empty, will try to read a bin file with the same name as xml. - If the bin file with the same name is not found, will load IR without weights. - For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. - @param device target device to use. - */ - Params(const std::string &model_path, - const std::string &bin_path, - const std::string &device) - : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} - , device - , false /* is generic */ - , std::tuple_size::value - , std::tuple_size::value) { - } - - /** @overload - Use this constructor to work with pre-compiled network. - Model is imported from a pre-compiled blob. - - @param blob_path path to the compiled model (*.blob). - @param device target device to use. - */ - Params(const std::string &blob_path, - const std::string &device) - : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} - , device - , false /* is generic */ - , std::tuple_size::value - , std::tuple_size::value) { - } - - /** @brief Specifies sequence of network input layers names for inference. - - The function is used to associate cv::gapi::infer<> inputs with the model inputs. - Number of names has to match the number of network inputs as defined in G_API_NET(). - In case a network has only single input layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of inputs - as defined in the @ref G_API_NET. Contains names of input layers. - @return reference to this parameter structure. - */ - Params& cfgInputLayers(const std::vector &layer_names) { - m_desc.input_names = layer_names; - return *this; - } - - /** @brief Specifies sequence of network output layers names for inference. - - The function is used to associate cv::gapi::infer<> outputs with the model outputs. - Number of names has to match the number of network outputs as defined in G_API_NET(). - In case a network has only single output layer, there is no need to specify name manually. - - @param layer_names std::array where N is the number of outputs - as defined in the @ref G_API_NET. Contains names of output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputLayers(const std::vector &layer_names) { - m_desc.output_names = layer_names; - return *this; - } - - /** @brief Specifies OpenVINO plugin configuration. - - The function is used to set configuration for OpenVINO plugin. Some parameters - can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html - to check information about specific plugin. - - @param config Map of pairs: (config parameter name, config parameter value). - @return reference to this parameter structure. - */ - Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { - m_desc.config = config; - return *this; - } - - /** @brief Specifies tensor layout for an input layer. - - The function is used to set tensor layout for an input layer. - - @param layout Tensor layout ("NCHW", "NWHC", etc) - will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& cfgInputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding input layer - and its tensor layout represented in std::string ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgInputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies model layout for an input layer. - - The function is used to set model layout for an input layer. - - @param layout Model layout ("NCHW", "NHWC", etc) - will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& cfgInputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding input layer - and its model layout ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgInputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies tensor layout for an output layer. - - The function is used to set tensor layout for an output layer. - - @param layout Tensor layout ("NCHW", "NWHC", etc) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding output layer - and its tensor layout represented in std::string ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgOutputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies model layout for an output layer. - - The function is used to set model layout for an output layer. - - @param layout Model layout ("NCHW", "NHWC", etc) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout); - return *this; - } - - /** @overload - @param layout_map Map of pairs: name of corresponding output layer - and its model layout ("NCHW", "NHWC", etc) - @return reference to this parameter structure. - */ - Params& - cfgOutputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout_map); - return *this; - } - - /** @brief Specifies tensor precision for an output layer. - - The function is used to set tensor precision for an output layer.. - - @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) - will be applied to all output layers. - @return reference to this parameter structure. - */ - Params& cfgOutputTensorPrecision(int precision) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = precision; - return *this; - } - - /** @overload - - @param precision_map Map of pairs: name of corresponding output layer - and its precision in OpenCV format (CV_8U, CV_32F, ...) - @return reference to this parameter structure. - */ - Params& - cfgOutputTensorPrecision(detail::AttrMap precision_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = std::move(precision_map); - return *this; - } - - /** @brief Specifies the new shape for input layers. - - The function is used to set new shape for input layers. - - @param new_shape New shape will be applied to all input layers. - @return reference to this parameter structure. - */ - Params& - cfgReshape(std::vector new_shape) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape); - return *this; - } - - /** @overload - - @param new_shape_map Map of pairs: name of corresponding output layer - and its new shape. - @return reference to this parameter structure. - */ - Params& - cfgReshape(detail::AttrMap> new_shape_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape_map); - return *this; - } - - /** @brief Specifies number of asynchronous inference requests. - - @param nireq Number of inference asynchronous requests. - @return reference to this parameter structure. - */ - Params& cfgNumRequests(const size_t nireq) { - if (nireq == 0) { - cv::util::throw_error( - std::logic_error("Number of inference requests" - " must be greater than zero.")); - } - m_desc.nireq = nireq; - return *this; - } - - /** @brief Specifies mean values for preprocessing. - * - The function is used to set mean values for input layer preprocessing. - - @param mean_values Float vector contains mean values - @return reference to this parameter structure. - */ - Params& cfgMean(std::vector mean_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_values); - return *this; - } - - /** @overload - - @param mean_map Map of pairs: name of corresponding input layer - and its mean values. - @return reference to this parameter structure. - */ - Params& cfgMean(detail::AttrMap> mean_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_map); - return *this; - } - - /** @brief Specifies scale values for preprocessing. - * - The function is used to set scale values for input layer preprocessing. - - @param scale_values Float vector contains scale values - @return reference to this parameter structure. - */ - Params& cfgScale(std::vector scale_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_values); - return *this; - } - - /** @overload - - @param scale_map Map of pairs: name of corresponding input layer - and its mean values. - @return reference to this parameter structure. - */ - Params& cfgScale(detail::AttrMap> scale_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_map); - return *this; - } - - /** @brief Specifies resize interpolation algorithm. - * - The function is used to configure resize preprocessing for input layer. - - @param interpolation Resize interpolation algorithm. - Supported algorithms: #INTER_NEAREST, #INTER_LINEAR, #INTER_CUBIC. - @return reference to this parameter structure. - */ - Params& cfgResize(int interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - /** @overload - - @param interpolation Map of pairs: name of corresponding input layer - and its resize algorithm. - @return reference to this parameter structure. - */ - Params& cfgResize(detail::AttrMap interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ov::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { m_desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc m_desc; -}; - -/* -* @brief This structure provides functions for generic network type that -* fill inference parameters. -* @see struct Generic -*/ -template<> -class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and specifies default values for other - inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". - - @param tag string tag of the network for which these parameters are intended. - @param model_path Path to a model. - @param bin_path Path to a data file. - For IR format (*.bin): - If path is empty, will try to read a bin file with the same name as xml. - If the bin file with the same name is not found, will load IR without weights. - For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &model_path, - const std::string &bin_path, - const std::string &device) - : m_tag(tag), - m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} - , device - , true /* is generic */ - , 0u - , 0u) { - } - - /** @overload - - This constructor for pre-compiled networks. Model is imported from pre-compiled - blob. - - @param tag string tag of the network for which these parameters are intended. - @param blob_path path to the compiled model (*.blob). - @param device target device to use. - */ - Params(const std::string &tag, - const std::string &blob_path, - const std::string &device) - : m_tag(tag), - m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} - , device - , true /* is generic */ - , 0u - , 0u) { - } - - /** @see ov::Params::cfgPluginConfig. */ - Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { - m_desc.config = config; - return *this; - } - - /** @see ov::Params::cfgInputTensorLayout. */ - Params& cfgInputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgInputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") - .input_tensor_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgInputModelLayout. */ - Params& cfgInputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgInputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") - .input_model_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgOutputTensorLayout. */ - Params& cfgOutputTensorLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgOutputTensorLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") - .output_tensor_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgOutputModelLayout. */ - Params& cfgOutputModelLayout(std::string layout) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout); - return *this; - } - - /** @overload */ - Params& - cfgOutputModelLayout(detail::AttrMap layout_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") - .output_model_layout = std::move(layout_map); - return *this; - } - - /** @see ov::Params::cfgOutputTensorPrecision. */ - Params& cfgOutputTensorPrecision(int precision) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = precision; - return *this; - } - - /** @overload */ - Params& - cfgOutputTensorPrecision(detail::AttrMap precision_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") - .output_tensor_precision = std::move(precision_map); - return *this; - } - - /** @see ov::Params::cfgReshape. */ - Params& cfgReshape(std::vector new_shape) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape); - return *this; - } - - /** @overload */ - Params& - cfgReshape(detail::AttrMap> new_shape_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") - .new_shapes = std::move(new_shape_map); - return *this; - } - - /** @see ov::Params::cfgNumRequests. */ - Params& cfgNumRequests(const size_t nireq) { - if (nireq == 0) { - cv::util::throw_error( - std::logic_error("Number of inference requests" - " must be greater than zero.")); - } - m_desc.nireq = nireq; - return *this; - } - - /** @see ov::Params::cfgMean. */ - Params& cfgMean(std::vector mean_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_values); - return *this; - } - - /** @overload */ - Params& cfgMean(detail::AttrMap> mean_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") - .mean_values = std::move(mean_map); - return *this; - } - - /** @see ov::Params::cfgScale. */ - Params& cfgScale(std::vector scale_values) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_values); - return *this; - } - - /** @overload */ - Params& cfgScale(detail::AttrMap> scale_map) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") - .scale_values = std::move(scale_map); - return *this; - } - - /** @see ov::Params::cfgResize. */ - Params& cfgResize(int interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - /** @overload */ - Params& cfgResize(detail::AttrMap interpolation) { - detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") - .interpolation = std::move(interpolation); - return *this; - } - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::ov::backend(); } - std::string tag() const { return m_tag; } - cv::util::any params() const { return { m_desc }; } - // END(G-API's network parametrization API) - -protected: - std::string m_tag; - detail::ParamDesc m_desc; -}; - -} // namespace ov - -namespace wip { namespace ov { -/** - * @brief Ask G-API OpenVINO backend to run only inference of model provided. - * - * G-API OpenVINO backend will perform only the inference of the model provided - * without populating input and copying back output data. - * This mode is used to evaluate the pure inference performance of the model without - * taking into account the i/o data transfer. - */ -struct benchmark_mode { }; - -} // namespace ov -} // namespace wip - -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.wip.ov.benchmark_mode"; } - }; -} - -} // namespace cv - -#endif // OPENCV_GAPI_INFER_OV_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_INFER_OV_HPP +#define OPENCV_GAPI_INFER_OV_HPP + +#include + +#include +#include // GAPI_EXPORTS +#include // GKernelType[M], GBackend +#include // Generic + +#include + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API OpenVINO 2.0 backend functions, + * structures, and symbols. + */ +namespace ov { + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +namespace detail { + +template +using AttrMap = std::map; +// NB: This type is supposed to be used to hold in/out layers +// attributes such as precision, layout, shape etc. +// +// User can provide attributes either: +// 1. cv::util::monostate - No value specified explicitly. +// 2. Attr - value specified explicitly that should be broadcasted to all layers. +// 3. AttrMap[str->T] - map specifies value for particular layer. +template +using LayerVariantAttr = cv::util::variant< cv::util::monostate + , AttrMap + , Attr>; + +struct ParamDesc { + struct Model { + + Model(const std::string &model_path_, + const std::string &bin_path_) + : model_path(model_path_), bin_path(bin_path_) { + } + + std::string model_path; + std::string bin_path; + + LayerVariantAttr input_tensor_layout; + LayerVariantAttr input_model_layout; + LayerVariantAttr output_tensor_layout; + LayerVariantAttr output_model_layout; + LayerVariantAttr output_tensor_precision; + + LayerVariantAttr> new_shapes; + + LayerVariantAttr> mean_values; + LayerVariantAttr> scale_values; + + LayerVariantAttr interpolation; + }; + + struct CompiledModel { + std::string blob_path; + }; + + using Kind = cv::util::variant; + + ParamDesc(Kind &&kind_, + const std::string &device_, + const bool is_generic_, + const size_t num_in_, + const size_t num_out_) + : kind(std::move(kind_)), device(device_), + is_generic(is_generic_), + num_in(num_in_), num_out(num_out_) { + } + + Kind kind; + + std::string device; + bool is_generic; + + std::size_t num_in; + std::size_t num_out; + + std::vector input_names; + std::vector output_names; + + using PluginConfigT = std::map; + PluginConfigT config; + + size_t nireq = 1; +}; + +// NB: Just helper to avoid code duplication. +static detail::ParamDesc::Model& +getModelToSetAttrOrThrow(detail::ParamDesc::Kind &kind, + const std::string &attr_name) { + if (cv::util::holds_alternative(kind)) { + cv::util::throw_error( + std::logic_error("Specifying " + attr_name + " isn't" + " possible for compiled model.")); + } + GAPI_Assert(cv::util::holds_alternative(kind)); + return cv::util::get(kind); +} + +} // namespace detail + +/** + * @brief This structure provides functions + * that fill inference parameters for "OpenVINO Toolkit" model. + */ +template struct Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and specifies default values for other + inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". + + @param model_path Path to a model. + @param bin_path Path to a data file. + For IR format (*.bin): + If path is empty, will try to read a bin file with the same name as xml. + If the bin file with the same name is not found, will load IR without weights. + For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. + @param device target device to use. + */ + Params(const std::string &model_path, + const std::string &bin_path, + const std::string &device) + : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} + , device + , false /* is generic */ + , std::tuple_size::value + , std::tuple_size::value) { + } + + /** @overload + Use this constructor to work with pre-compiled network. + Model is imported from a pre-compiled blob. + + @param blob_path path to the compiled model (*.blob). + @param device target device to use. + */ + Params(const std::string &blob_path, + const std::string &device) + : m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} + , device + , false /* is generic */ + , std::tuple_size::value + , std::tuple_size::value) { + } + + /** @brief Specifies sequence of network input layers names for inference. + + The function is used to associate cv::gapi::infer<> inputs with the model inputs. + Number of names has to match the number of network inputs as defined in G_API_NET(). + In case a network has only single input layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of inputs + as defined in the @ref G_API_NET. Contains names of input layers. + @return reference to this parameter structure. + */ + Params& cfgInputLayers(const std::vector &layer_names) { + m_desc.input_names = layer_names; + return *this; + } + + /** @brief Specifies sequence of network output layers names for inference. + + The function is used to associate cv::gapi::infer<> outputs with the model outputs. + Number of names has to match the number of network outputs as defined in G_API_NET(). + In case a network has only single output layer, there is no need to specify name manually. + + @param layer_names std::array where N is the number of outputs + as defined in the @ref G_API_NET. Contains names of output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputLayers(const std::vector &layer_names) { + m_desc.output_names = layer_names; + return *this; + } + + /** @brief Specifies OpenVINO plugin configuration. + + The function is used to set configuration for OpenVINO plugin. Some parameters + can be different for each plugin. Please follow https://docs.openvinotoolkit.org/latest/index.html + to check information about specific plugin. + + @param config Map of pairs: (config parameter name, config parameter value). + @return reference to this parameter structure. + */ + Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { + m_desc.config = config; + return *this; + } + + /** @brief Specifies tensor layout for an input layer. + + The function is used to set tensor layout for an input layer. + + @param layout Tensor layout ("NCHW", "NWHC", etc) + will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& cfgInputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding input layer + and its tensor layout represented in std::string ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgInputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies model layout for an input layer. + + The function is used to set model layout for an input layer. + + @param layout Model layout ("NCHW", "NHWC", etc) + will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& cfgInputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding input layer + and its model layout ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgInputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies tensor layout for an output layer. + + The function is used to set tensor layout for an output layer. + + @param layout Tensor layout ("NCHW", "NWHC", etc) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding output layer + and its tensor layout represented in std::string ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgOutputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies model layout for an output layer. + + The function is used to set model layout for an output layer. + + @param layout Model layout ("NCHW", "NHWC", etc) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout); + return *this; + } + + /** @overload + @param layout_map Map of pairs: name of corresponding output layer + and its model layout ("NCHW", "NHWC", etc) + @return reference to this parameter structure. + */ + Params& + cfgOutputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout_map); + return *this; + } + + /** @brief Specifies tensor precision for an output layer. + + The function is used to set tensor precision for an output layer.. + + @param precision Precision in OpenCV format (CV_8U, CV_32F, ...) + will be applied to all output layers. + @return reference to this parameter structure. + */ + Params& cfgOutputTensorPrecision(int precision) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = precision; + return *this; + } + + /** @overload + + @param precision_map Map of pairs: name of corresponding output layer + and its precision in OpenCV format (CV_8U, CV_32F, ...) + @return reference to this parameter structure. + */ + Params& + cfgOutputTensorPrecision(detail::AttrMap precision_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = std::move(precision_map); + return *this; + } + + /** @brief Specifies the new shape for input layers. + + The function is used to set new shape for input layers. + + @param new_shape New shape will be applied to all input layers. + @return reference to this parameter structure. + */ + Params& + cfgReshape(std::vector new_shape) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape); + return *this; + } + + /** @overload + + @param new_shape_map Map of pairs: name of corresponding output layer + and its new shape. + @return reference to this parameter structure. + */ + Params& + cfgReshape(detail::AttrMap> new_shape_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape_map); + return *this; + } + + /** @brief Specifies number of asynchronous inference requests. + + @param nireq Number of inference asynchronous requests. + @return reference to this parameter structure. + */ + Params& cfgNumRequests(const size_t nireq) { + if (nireq == 0) { + cv::util::throw_error( + std::logic_error("Number of inference requests" + " must be greater than zero.")); + } + m_desc.nireq = nireq; + return *this; + } + + /** @brief Specifies mean values for preprocessing. + * + The function is used to set mean values for input layer preprocessing. + + @param mean_values Float vector contains mean values + @return reference to this parameter structure. + */ + Params& cfgMean(std::vector mean_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_values); + return *this; + } + + /** @overload + + @param mean_map Map of pairs: name of corresponding input layer + and its mean values. + @return reference to this parameter structure. + */ + Params& cfgMean(detail::AttrMap> mean_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_map); + return *this; + } + + /** @brief Specifies scale values for preprocessing. + * + The function is used to set scale values for input layer preprocessing. + + @param scale_values Float vector contains scale values + @return reference to this parameter structure. + */ + Params& cfgScale(std::vector scale_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_values); + return *this; + } + + /** @overload + + @param scale_map Map of pairs: name of corresponding input layer + and its mean values. + @return reference to this parameter structure. + */ + Params& cfgScale(detail::AttrMap> scale_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_map); + return *this; + } + + /** @brief Specifies resize interpolation algorithm. + * + The function is used to configure resize preprocessing for input layer. + + @param interpolation Resize interpolation algorithm. + Supported algorithms: #INTER_NEAREST, #INTER_LINEAR, #INTER_CUBIC. + @return reference to this parameter structure. + */ + Params& cfgResize(int interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + /** @overload + + @param interpolation Map of pairs: name of corresponding input layer + and its resize algorithm. + @return reference to this parameter structure. + */ + Params& cfgResize(detail::AttrMap interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ov::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { m_desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc m_desc; +}; + +/* +* @brief This structure provides functions for generic network type that +* fill inference parameters. +* @see struct Generic +*/ +template<> +class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and specifies default values for other + inference description parameters. Model is loaded and compiled using "OpenVINO Toolkit". + + @param tag string tag of the network for which these parameters are intended. + @param model_path Path to a model. + @param bin_path Path to a data file. + For IR format (*.bin): + If path is empty, will try to read a bin file with the same name as xml. + If the bin file with the same name is not found, will load IR without weights. + For PDPD (*.pdmodel) and ONNX (*.onnx) formats bin_path isn't used. + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &model_path, + const std::string &bin_path, + const std::string &device) + : m_tag(tag), + m_desc( detail::ParamDesc::Kind{detail::ParamDesc::Model{model_path, bin_path}} + , device + , true /* is generic */ + , 0u + , 0u) { + } + + /** @overload + + This constructor for pre-compiled networks. Model is imported from pre-compiled + blob. + + @param tag string tag of the network for which these parameters are intended. + @param blob_path path to the compiled model (*.blob). + @param device target device to use. + */ + Params(const std::string &tag, + const std::string &blob_path, + const std::string &device) + : m_tag(tag), + m_desc( detail::ParamDesc::Kind{detail::ParamDesc::CompiledModel{blob_path}} + , device + , true /* is generic */ + , 0u + , 0u) { + } + + /** @see ov::Params::cfgPluginConfig. */ + Params& cfgPluginConfig(const detail::ParamDesc::PluginConfigT &config) { + m_desc.config = config; + return *this; + } + + /** @see ov::Params::cfgInputTensorLayout. */ + Params& cfgInputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgInputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input tensor layout") + .input_tensor_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgInputModelLayout. */ + Params& cfgInputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgInputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "input model layout") + .input_model_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgOutputTensorLayout. */ + Params& cfgOutputTensorLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgOutputTensorLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor layout") + .output_tensor_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgOutputModelLayout. */ + Params& cfgOutputModelLayout(std::string layout) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout); + return *this; + } + + /** @overload */ + Params& + cfgOutputModelLayout(detail::AttrMap layout_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output model layout") + .output_model_layout = std::move(layout_map); + return *this; + } + + /** @see ov::Params::cfgOutputTensorPrecision. */ + Params& cfgOutputTensorPrecision(int precision) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = precision; + return *this; + } + + /** @overload */ + Params& + cfgOutputTensorPrecision(detail::AttrMap precision_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "output tensor precision") + .output_tensor_precision = std::move(precision_map); + return *this; + } + + /** @see ov::Params::cfgReshape. */ + Params& cfgReshape(std::vector new_shape) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape); + return *this; + } + + /** @overload */ + Params& + cfgReshape(detail::AttrMap> new_shape_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "reshape") + .new_shapes = std::move(new_shape_map); + return *this; + } + + /** @see ov::Params::cfgNumRequests. */ + Params& cfgNumRequests(const size_t nireq) { + if (nireq == 0) { + cv::util::throw_error( + std::logic_error("Number of inference requests" + " must be greater than zero.")); + } + m_desc.nireq = nireq; + return *this; + } + + /** @see ov::Params::cfgMean. */ + Params& cfgMean(std::vector mean_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_values); + return *this; + } + + /** @overload */ + Params& cfgMean(detail::AttrMap> mean_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "mean values") + .mean_values = std::move(mean_map); + return *this; + } + + /** @see ov::Params::cfgScale. */ + Params& cfgScale(std::vector scale_values) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_values); + return *this; + } + + /** @overload */ + Params& cfgScale(detail::AttrMap> scale_map) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "scale values") + .scale_values = std::move(scale_map); + return *this; + } + + /** @see ov::Params::cfgResize. */ + Params& cfgResize(int interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + /** @overload */ + Params& cfgResize(detail::AttrMap interpolation) { + detail::getModelToSetAttrOrThrow(m_desc.kind, "resize preprocessing") + .interpolation = std::move(interpolation); + return *this; + } + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::ov::backend(); } + std::string tag() const { return m_tag; } + cv::util::any params() const { return { m_desc }; } + // END(G-API's network parametrization API) + +protected: + std::string m_tag; + detail::ParamDesc m_desc; +}; + +} // namespace ov + +namespace wip { namespace ov { +/** + * @brief Ask G-API OpenVINO backend to run only inference of model provided. + * + * G-API OpenVINO backend will perform only the inference of the model provided + * without populating input and copying back output data. + * This mode is used to evaluate the pure inference performance of the model without + * taking into account the i/o data transfer. + */ +struct benchmark_mode { }; + +} // namespace ov +} // namespace wip + +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.wip.ov.benchmark_mode"; } + }; +} + +} // namespace cv + +#endif // OPENCV_GAPI_INFER_OV_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp index 33dfa25e01..e39d6fd4c6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/infer/parsers.hpp @@ -1,138 +1,138 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_PARSERS_HPP -#define OPENCV_GAPI_PARSERS_HPP - -#include // std::tuple - -#include -#include - -namespace cv { namespace gapi { -namespace nn { -namespace parsers { - using GRects = GArray; - using GDetections = std::tuple, GArray>; - - G_TYPED_KERNEL(GParseSSDBL, , float, int)>, - "org.opencv.nn.parsers.parseSSD_BL") { - static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, float, int) { - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - }; - - G_TYPED_KERNEL(GParseSSD, , float, bool, bool)>, - "org.opencv.nn.parsers.parseSSD") { - static GArrayDesc outMeta(const GMatDesc&, const GOpaqueDesc&, float, bool, bool) { - return empty_array_desc(); - } - }; - - G_TYPED_KERNEL(GParseYolo, , float, float, std::vector)>, - "org.opencv.nn.parsers.parseYolo") { - static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, - float, float, const std::vector&) { - return std::make_tuple(empty_array_desc(), empty_array_desc()); - } - static const std::vector& defaultAnchors() { - static std::vector anchors { - 0.57273f, 0.677385f, 1.87446f, 2.06253f, 3.33843f, 5.47434f, 7.88282f, 3.52778f, 9.77052f, 9.16828f - }; - return anchors; - } - }; -} // namespace parsers -} // namespace nn - -/** @brief Parses output of SSD network. - -Extracts detection information (box, confidence, label) from SSD output and -filters it by given confidence and label. - -@note Function textual ID is "org.opencv.nn.parsers.parseSSD_BL" - -@param in Input CV_32F tensor with {1,1,N,7} dimensions. -@param inSz Size to project detected boxes to (size of the input image). -@param confidenceThreshold If confidence of the -detection is smaller than confidence threshold, detection is rejected. -@param filterLabel If provided (!= -1), only detections with -given label will get to the output. -@return a tuple with a vector of detected boxes and a vector of appropriate labels. -*/ -GAPI_EXPORTS_W std::tuple, GArray> parseSSD(const GMat& in, - const GOpaque& inSz, - const float confidenceThreshold = 0.5f, - const int filterLabel = -1); - -/** @brief Parses output of SSD network. - -Extracts detection information (box, confidence) from SSD output and -filters it by given confidence and by going out of bounds. - -@note Function textual ID is "org.opencv.nn.parsers.parseSSD" - -@param in Input CV_32F tensor with {1,1,N,7} dimensions. -@param inSz Size to project detected boxes to (size of the input image). -@param confidenceThreshold If confidence of the -detection is smaller than confidence threshold, detection is rejected. -@param alignmentToSquare If provided true, bounding boxes are extended to squares. -The center of the rectangle remains unchanged, the side of the square is -the larger side of the rectangle. -@param filterOutOfBounds If provided true, out-of-frame boxes are filtered. -@return a vector of detected bounding boxes. -*/ -GAPI_EXPORTS_W GArray parseSSD(const GMat& in, - const GOpaque& inSz, - const float confidenceThreshold, - const bool alignmentToSquare, - const bool filterOutOfBounds); - -/** @brief Parses output of Yolo network. - -Extracts detection information (box, confidence, label) from Yolo output, -filters it by given confidence and performs non-maximum suppression for overlapping boxes. - -@note Function textual ID is "org.opencv.nn.parsers.parseYolo" - -@param in Input CV_32F tensor with {1,13,13,N} dimensions, N should satisfy: -\f[\texttt{N} = (\texttt{num_classes} + \texttt{5}) * \texttt{5},\f] -where num_classes - a number of classes Yolo network was trained with. -@param inSz Size to project detected boxes to (size of the input image). -@param confidenceThreshold If confidence of the -detection is smaller than confidence threshold, detection is rejected. -@param nmsThreshold Non-maximum suppression threshold which controls minimum -relative box intersection area required for rejecting the box with a smaller confidence. -If 1.f, nms is not performed and no boxes are rejected. -@param anchors Anchors Yolo network was trained with. -@note The default anchor values are specified for YOLO v2 Tiny as described in Intel Open Model Zoo -documentation. -@return a tuple with a vector of detected boxes and a vector of appropriate labels. -*/ -GAPI_EXPORTS_W std::tuple, GArray> parseYolo(const GMat& in, - const GOpaque& inSz, - const float confidenceThreshold = 0.5f, - const float nmsThreshold = 0.5f, - const std::vector& anchors - = nn::parsers::GParseYolo::defaultAnchors()); - -} // namespace gapi -} // namespace cv - -// Reimport parseSSD & parseYolo under their initial namespace -namespace cv { -namespace gapi { -namespace streaming { - -using cv::gapi::parseSSD; -using cv::gapi::parseYolo; - -} // namespace streaming -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_PARSERS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_PARSERS_HPP +#define OPENCV_GAPI_PARSERS_HPP + +#include // std::tuple + +#include +#include + +namespace cv { namespace gapi { +namespace nn { +namespace parsers { + using GRects = GArray; + using GDetections = std::tuple, GArray>; + + G_TYPED_KERNEL(GParseSSDBL, , float, int)>, + "org.opencv.nn.parsers.parseSSD_BL") { + static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, float, int) { + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + }; + + G_TYPED_KERNEL(GParseSSD, , float, bool, bool)>, + "org.opencv.nn.parsers.parseSSD") { + static GArrayDesc outMeta(const GMatDesc&, const GOpaqueDesc&, float, bool, bool) { + return empty_array_desc(); + } + }; + + G_TYPED_KERNEL(GParseYolo, , float, float, std::vector)>, + "org.opencv.nn.parsers.parseYolo") { + static std::tuple outMeta(const GMatDesc&, const GOpaqueDesc&, + float, float, const std::vector&) { + return std::make_tuple(empty_array_desc(), empty_array_desc()); + } + static const std::vector& defaultAnchors() { + static std::vector anchors { + 0.57273f, 0.677385f, 1.87446f, 2.06253f, 3.33843f, 5.47434f, 7.88282f, 3.52778f, 9.77052f, 9.16828f + }; + return anchors; + } + }; +} // namespace parsers +} // namespace nn + +/** @brief Parses output of SSD network. + +Extracts detection information (box, confidence, label) from SSD output and +filters it by given confidence and label. + +@note Function textual ID is "org.opencv.nn.parsers.parseSSD_BL" + +@param in Input CV_32F tensor with {1,1,N,7} dimensions. +@param inSz Size to project detected boxes to (size of the input image). +@param confidenceThreshold If confidence of the +detection is smaller than confidence threshold, detection is rejected. +@param filterLabel If provided (!= -1), only detections with +given label will get to the output. +@return a tuple with a vector of detected boxes and a vector of appropriate labels. +*/ +GAPI_EXPORTS_W std::tuple, GArray> parseSSD(const GMat& in, + const GOpaque& inSz, + const float confidenceThreshold = 0.5f, + const int filterLabel = -1); + +/** @brief Parses output of SSD network. + +Extracts detection information (box, confidence) from SSD output and +filters it by given confidence and by going out of bounds. + +@note Function textual ID is "org.opencv.nn.parsers.parseSSD" + +@param in Input CV_32F tensor with {1,1,N,7} dimensions. +@param inSz Size to project detected boxes to (size of the input image). +@param confidenceThreshold If confidence of the +detection is smaller than confidence threshold, detection is rejected. +@param alignmentToSquare If provided true, bounding boxes are extended to squares. +The center of the rectangle remains unchanged, the side of the square is +the larger side of the rectangle. +@param filterOutOfBounds If provided true, out-of-frame boxes are filtered. +@return a vector of detected bounding boxes. +*/ +GAPI_EXPORTS_W GArray parseSSD(const GMat& in, + const GOpaque& inSz, + const float confidenceThreshold, + const bool alignmentToSquare, + const bool filterOutOfBounds); + +/** @brief Parses output of Yolo network. + +Extracts detection information (box, confidence, label) from Yolo output, +filters it by given confidence and performs non-maximum suppression for overlapping boxes. + +@note Function textual ID is "org.opencv.nn.parsers.parseYolo" + +@param in Input CV_32F tensor with {1,13,13,N} dimensions, N should satisfy: +\f[\texttt{N} = (\texttt{num_classes} + \texttt{5}) * \texttt{5},\f] +where num_classes - a number of classes Yolo network was trained with. +@param inSz Size to project detected boxes to (size of the input image). +@param confidenceThreshold If confidence of the +detection is smaller than confidence threshold, detection is rejected. +@param nmsThreshold Non-maximum suppression threshold which controls minimum +relative box intersection area required for rejecting the box with a smaller confidence. +If 1.f, nms is not performed and no boxes are rejected. +@param anchors Anchors Yolo network was trained with. +@note The default anchor values are specified for YOLO v2 Tiny as described in Intel Open Model Zoo +documentation. +@return a tuple with a vector of detected boxes and a vector of appropriate labels. +*/ +GAPI_EXPORTS_W std::tuple, GArray> parseYolo(const GMat& in, + const GOpaque& inSz, + const float confidenceThreshold = 0.5f, + const float nmsThreshold = 0.5f, + const std::vector& anchors + = nn::parsers::GParseYolo::defaultAnchors()); + +} // namespace gapi +} // namespace cv + +// Reimport parseSSD & parseYolo under their initial namespace +namespace cv { +namespace gapi { +namespace streaming { + +using cv::gapi::parseSSD; +using cv::gapi::parseYolo; + +} // namespace streaming +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_PARSERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp index c959832ef0..1470f00d04 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/media.hpp @@ -1,258 +1,258 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_MEDIA_HPP -#define OPENCV_GAPI_MEDIA_HPP - -#include // unique_ptr<>, shared_ptr<> -#include // array<> -#include // function<> -#include // forward<>() - -#include -#include - -// Forward declaration -namespace cv { -namespace gapi { -namespace s11n { -struct IOStream; -struct IIStream; -} // namespace s11n -} // namespace gapi -} // namespace cv - -namespace cv { - -/** \addtogroup gapi_data_structures - * @{ - * - * @brief Extra G-API data structures used to pass input/output data - * to the graph for processing. - */ - -/** - * @brief cv::MediaFrame class represents an image/media frame - * obtained from an external source. - * - * cv::MediaFrame represents image data as specified in - * cv::MediaFormat. cv::MediaFrame is designed to be a thin wrapper over some - * external memory of buffer; the class itself provides an uniform - * interface over such types of memory. cv::MediaFrame wraps data from - * a camera driver or from a media codec and provides an abstraction - * layer over this memory to G-API. MediaFrame defines a compact interface - * to access and manage the underlying data; the implementation is - * fully defined by the associated Adapter (which is usually - * user-defined). - * - * @sa cv::RMat - */ -class GAPI_EXPORTS MediaFrame { -public: - /// This enum defines different types of cv::MediaFrame provided - /// access to the underlying data. Note that different flags can't - /// be combined in this version. - enum class Access { - R, ///< Access data for reading - W, ///< Access data for writing - }; - class IAdapter; - class View; - using AdapterPtr = std::unique_ptr; - - /** - * @brief Constructs an empty MediaFrame - * - * The constructed object has no any data associated with it. - */ - MediaFrame(); - - /** - * @brief Constructs a MediaFrame with the given - * Adapter. MediaFrame takes ownership over the passed adapter. - * - * @param p an unique pointer to instance of IAdapter derived class. - */ - explicit MediaFrame(AdapterPtr &&p); - - /** - * @overload - * @brief Constructs a MediaFrame with the given parameters for - * the Adapter. The adapter of type `T` is costructed on the fly. - * - * @param args list of arguments to construct an adapter of type - * `T`. - */ - template static cv::MediaFrame Create(Args&&... args); - - /** - * @brief Obtain access to the underlying data with the given - * mode. - * - * Depending on the associated Adapter and the data wrapped, this - * method may be cheap (e.g., the underlying memory is local) or - * costly (if the underlying memory is external or device - * memory). - * - * @param mode an access mode flag - * @return a MediaFrame::View object. The views should be handled - * carefully, refer to the MediaFrame::View documentation for details. - */ - View access(Access mode) const; - - /** - * @brief Returns a media frame descriptor -- the information - * about the media format, dimensions, etc. - * @return a cv::GFrameDesc - */ - cv::GFrameDesc desc() const; - - // FIXME: design a better solution - // Should be used only if the actual adapter provides implementation - /// @private -- exclude from the OpenCV documentation for now. - cv::util::any blobParams() const; - - /** - * @brief Casts and returns the associated MediaFrame adapter to - * the particular adapter type `T`, returns nullptr if the type is - * different. - * - * This method may be useful if the adapter type is known by the - * caller, and some lower level access to the memory is required. - * Depending on the memory type, it may be more efficient than - * access(). - * - * @return a pointer to the adapter object, nullptr if the adapter - * type is different. - */ - template T* get() const { - static_assert(std::is_base_of::value, - "T is not derived from cv::MediaFrame::IAdapter!"); - auto* adapter = getAdapter(); - GAPI_Assert(adapter != nullptr); - return dynamic_cast(adapter); - } - - /** - * @brief Serialize MediaFrame's data to a byte array. - * - * @note The actual logic is implemented by frame's adapter class. - * Does nothing by default. - * - * @param os Bytestream to store serialized MediaFrame data in. - */ - void serialize(cv::gapi::s11n::IOStream& os) const; - -private: - struct Priv; - std::shared_ptr m; - IAdapter* getAdapter() const; -}; - -template -inline cv::MediaFrame cv::MediaFrame::Create(Args&&... args) { - std::unique_ptr ptr(new T(std::forward(args)...)); - return cv::MediaFrame(std::move(ptr)); -} - -/** - * @brief Provides access to the MediaFrame's underlying data. - * - * This object contains the necessary information to access the pixel - * data of the associated MediaFrame: arrays of pointers and strides - * (distance between every plane row, in bytes) for every image - * plane, as defined in cv::MediaFormat. - * There may be up to four image planes in MediaFrame. - * - * Depending on the MediaFrame::Access flag passed in - * MediaFrame::access(), a MediaFrame::View may be read- or - * write-only. - * - * Depending on the MediaFrame::IAdapter implementation associated - * with the parent MediaFrame, writing to memory with - * MediaFrame::Access::R flag may have no effect or lead to - * undefined behavior. Same applies to reading the memory with - * MediaFrame::Access::W flag -- again, depending on the IAdapter - * implementation, the host-side buffer the view provides access to - * may have no current data stored in (so in-place editing of the - * buffer contents may not be possible). - * - * MediaFrame::View objects must be handled carefully, as an external - * resource associated with MediaFrame may be locked for the time the - * MediaFrame::View object exists. Obtaining MediaFrame::View should - * be seen as "map" and destroying it as "unmap" in the "map/unmap" - * idiom (applicable to OpenCL, device memory, remote - * memory). - * - * When a MediaFrame buffer is accessed for writing, and the memory - * under MediaFrame::View::Ptrs is altered, the data synchronization - * of a host-side and device/remote buffer is not guaranteed until the - * MediaFrame::View is destroyed. In other words, the real data on the - * device or in a remote target may be updated at the MediaFrame::View - * destruction only -- but it depends on the associated - * MediaFrame::IAdapter implementation. - */ -class GAPI_EXPORTS MediaFrame::View final { -public: - static constexpr const size_t MAX_PLANES = 4; - using Ptrs = std::array; - using Strides = std::array; // in bytes - using Callback = std::function; - - /// @private - View(Ptrs&& ptrs, Strides&& strs, Callback &&cb = [](){}); - - /// @private - View(const View&) = delete; - - /// @private - View(View&&) = default; - - /// @private - View& operator = (const View&) = delete; - - ~View(); - - Ptrs ptr; ///< Array of image plane pointers - Strides stride; ///< Array of image plane strides, in bytes. - -private: - Callback m_cb; -}; - -/** - * @brief An interface class for MediaFrame data adapters. - * - * Implement this interface to wrap media data in the MediaFrame. It - * makes sense to implement this class if there is a custom - * cv::gapi::wip::IStreamSource defined -- in this case, a stream - * source can produce MediaFrame objects with this adapter and the - * media data may be passed to graph without any copy. For example, a - * GStreamer-based stream source can implement an adapter over - * `GstBuffer` and G-API will transparently use it in the graph. - */ -class GAPI_EXPORTS MediaFrame::IAdapter { -public: - virtual ~IAdapter() = 0; - virtual cv::GFrameDesc meta() const = 0; - virtual MediaFrame::View access(MediaFrame::Access) = 0; - // FIXME: design a better solution - // The default implementation does nothing - virtual cv::util::any blobParams() const; - virtual void serialize(cv::gapi::s11n::IOStream&) { - GAPI_Error("Generic serialize method of MediaFrame::IAdapter does nothing by default. " - "Please, implement it in derived class to properly serialize the object."); - } - virtual void deserialize(cv::gapi::s11n::IIStream&) { - GAPI_Error("Generic deserialize method of MediaFrame::IAdapter does nothing by default. " - "Please, implement it in derived class to properly deserialize the object."); - } -}; -/** @} */ - -} //namespace cv - -#endif // OPENCV_GAPI_MEDIA_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_MEDIA_HPP +#define OPENCV_GAPI_MEDIA_HPP + +#include // unique_ptr<>, shared_ptr<> +#include // array<> +#include // function<> +#include // forward<>() + +#include +#include + +// Forward declaration +namespace cv { +namespace gapi { +namespace s11n { +struct IOStream; +struct IIStream; +} // namespace s11n +} // namespace gapi +} // namespace cv + +namespace cv { + +/** \addtogroup gapi_data_structures + * @{ + * + * @brief Extra G-API data structures used to pass input/output data + * to the graph for processing. + */ + +/** + * @brief cv::MediaFrame class represents an image/media frame + * obtained from an external source. + * + * cv::MediaFrame represents image data as specified in + * cv::MediaFormat. cv::MediaFrame is designed to be a thin wrapper over some + * external memory of buffer; the class itself provides an uniform + * interface over such types of memory. cv::MediaFrame wraps data from + * a camera driver or from a media codec and provides an abstraction + * layer over this memory to G-API. MediaFrame defines a compact interface + * to access and manage the underlying data; the implementation is + * fully defined by the associated Adapter (which is usually + * user-defined). + * + * @sa cv::RMat + */ +class GAPI_EXPORTS MediaFrame { +public: + /// This enum defines different types of cv::MediaFrame provided + /// access to the underlying data. Note that different flags can't + /// be combined in this version. + enum class Access { + R, ///< Access data for reading + W, ///< Access data for writing + }; + class IAdapter; + class View; + using AdapterPtr = std::unique_ptr; + + /** + * @brief Constructs an empty MediaFrame + * + * The constructed object has no any data associated with it. + */ + MediaFrame(); + + /** + * @brief Constructs a MediaFrame with the given + * Adapter. MediaFrame takes ownership over the passed adapter. + * + * @param p an unique pointer to instance of IAdapter derived class. + */ + explicit MediaFrame(AdapterPtr &&p); + + /** + * @overload + * @brief Constructs a MediaFrame with the given parameters for + * the Adapter. The adapter of type `T` is costructed on the fly. + * + * @param args list of arguments to construct an adapter of type + * `T`. + */ + template static cv::MediaFrame Create(Args&&... args); + + /** + * @brief Obtain access to the underlying data with the given + * mode. + * + * Depending on the associated Adapter and the data wrapped, this + * method may be cheap (e.g., the underlying memory is local) or + * costly (if the underlying memory is external or device + * memory). + * + * @param mode an access mode flag + * @return a MediaFrame::View object. The views should be handled + * carefully, refer to the MediaFrame::View documentation for details. + */ + View access(Access mode) const; + + /** + * @brief Returns a media frame descriptor -- the information + * about the media format, dimensions, etc. + * @return a cv::GFrameDesc + */ + cv::GFrameDesc desc() const; + + // FIXME: design a better solution + // Should be used only if the actual adapter provides implementation + /// @private -- exclude from the OpenCV documentation for now. + cv::util::any blobParams() const; + + /** + * @brief Casts and returns the associated MediaFrame adapter to + * the particular adapter type `T`, returns nullptr if the type is + * different. + * + * This method may be useful if the adapter type is known by the + * caller, and some lower level access to the memory is required. + * Depending on the memory type, it may be more efficient than + * access(). + * + * @return a pointer to the adapter object, nullptr if the adapter + * type is different. + */ + template T* get() const { + static_assert(std::is_base_of::value, + "T is not derived from cv::MediaFrame::IAdapter!"); + auto* adapter = getAdapter(); + GAPI_Assert(adapter != nullptr); + return dynamic_cast(adapter); + } + + /** + * @brief Serialize MediaFrame's data to a byte array. + * + * @note The actual logic is implemented by frame's adapter class. + * Does nothing by default. + * + * @param os Bytestream to store serialized MediaFrame data in. + */ + void serialize(cv::gapi::s11n::IOStream& os) const; + +private: + struct Priv; + std::shared_ptr m; + IAdapter* getAdapter() const; +}; + +template +inline cv::MediaFrame cv::MediaFrame::Create(Args&&... args) { + std::unique_ptr ptr(new T(std::forward(args)...)); + return cv::MediaFrame(std::move(ptr)); +} + +/** + * @brief Provides access to the MediaFrame's underlying data. + * + * This object contains the necessary information to access the pixel + * data of the associated MediaFrame: arrays of pointers and strides + * (distance between every plane row, in bytes) for every image + * plane, as defined in cv::MediaFormat. + * There may be up to four image planes in MediaFrame. + * + * Depending on the MediaFrame::Access flag passed in + * MediaFrame::access(), a MediaFrame::View may be read- or + * write-only. + * + * Depending on the MediaFrame::IAdapter implementation associated + * with the parent MediaFrame, writing to memory with + * MediaFrame::Access::R flag may have no effect or lead to + * undefined behavior. Same applies to reading the memory with + * MediaFrame::Access::W flag -- again, depending on the IAdapter + * implementation, the host-side buffer the view provides access to + * may have no current data stored in (so in-place editing of the + * buffer contents may not be possible). + * + * MediaFrame::View objects must be handled carefully, as an external + * resource associated with MediaFrame may be locked for the time the + * MediaFrame::View object exists. Obtaining MediaFrame::View should + * be seen as "map" and destroying it as "unmap" in the "map/unmap" + * idiom (applicable to OpenCL, device memory, remote + * memory). + * + * When a MediaFrame buffer is accessed for writing, and the memory + * under MediaFrame::View::Ptrs is altered, the data synchronization + * of a host-side and device/remote buffer is not guaranteed until the + * MediaFrame::View is destroyed. In other words, the real data on the + * device or in a remote target may be updated at the MediaFrame::View + * destruction only -- but it depends on the associated + * MediaFrame::IAdapter implementation. + */ +class GAPI_EXPORTS MediaFrame::View final { +public: + static constexpr const size_t MAX_PLANES = 4; + using Ptrs = std::array; + using Strides = std::array; // in bytes + using Callback = std::function; + + /// @private + View(Ptrs&& ptrs, Strides&& strs, Callback &&cb = [](){}); + + /// @private + View(const View&) = delete; + + /// @private + View(View&&) = default; + + /// @private + View& operator = (const View&) = delete; + + ~View(); + + Ptrs ptr; ///< Array of image plane pointers + Strides stride; ///< Array of image plane strides, in bytes. + +private: + Callback m_cb; +}; + +/** + * @brief An interface class for MediaFrame data adapters. + * + * Implement this interface to wrap media data in the MediaFrame. It + * makes sense to implement this class if there is a custom + * cv::gapi::wip::IStreamSource defined -- in this case, a stream + * source can produce MediaFrame objects with this adapter and the + * media data may be passed to graph without any copy. For example, a + * GStreamer-based stream source can implement an adapter over + * `GstBuffer` and G-API will transparently use it in the graph. + */ +class GAPI_EXPORTS MediaFrame::IAdapter { +public: + virtual ~IAdapter() = 0; + virtual cv::GFrameDesc meta() const = 0; + virtual MediaFrame::View access(MediaFrame::Access) = 0; + // FIXME: design a better solution + // The default implementation does nothing + virtual cv::util::any blobParams() const; + virtual void serialize(cv::gapi::s11n::IOStream&) { + GAPI_Error("Generic serialize method of MediaFrame::IAdapter does nothing by default. " + "Please, implement it in derived class to properly serialize the object."); + } + virtual void deserialize(cv::gapi::s11n::IIStream&) { + GAPI_Error("Generic deserialize method of MediaFrame::IAdapter does nothing by default. " + "Please, implement it in derived class to properly deserialize the object."); + } +}; +/** @} */ + +} //namespace cv + +#endif // OPENCV_GAPI_MEDIA_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp index 28e67bc318..4a1b9f6db6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/infer.hpp @@ -1,66 +1,66 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2022 Intel Corporation - -#ifndef OPENCV_GAPI_OAK_INFER_HPP -#define OPENCV_GAPI_OAK_INFER_HPP - -#include -#include -#include -#include - -#include -#include - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace oak { - -namespace detail { -/** -* @brief This structure contains description of inference parameters -* which is specific to OAK models. -*/ -struct ParamDesc { - std::string blob_file; -}; -} // namespace detail - -/** - * Contains description of inference parameters and kit of functions that - * fill this parameters. - */ -template class Params { -public: - /** @brief Class constructor. - - Constructs Params based on model information and sets default values for other - inference description parameters. - - @param model Path to model (.blob file) - */ - explicit Params(const std::string &model) { - desc.blob_file = model; - }; - - // BEGIN(G-API's network parametrization API) - GBackend backend() const { return cv::gapi::oak::backend(); } - std::string tag() const { return Net::tag(); } - cv::util::any params() const { return { desc }; } - // END(G-API's network parametrization API) - -protected: - detail::ParamDesc desc; -}; - -} // namespace oak -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_OAK_INFER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2022 Intel Corporation + +#ifndef OPENCV_GAPI_OAK_INFER_HPP +#define OPENCV_GAPI_OAK_INFER_HPP + +#include +#include +#include +#include + +#include +#include + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace oak { + +namespace detail { +/** +* @brief This structure contains description of inference parameters +* which is specific to OAK models. +*/ +struct ParamDesc { + std::string blob_file; +}; +} // namespace detail + +/** + * Contains description of inference parameters and kit of functions that + * fill this parameters. + */ +template class Params { +public: + /** @brief Class constructor. + + Constructs Params based on model information and sets default values for other + inference description parameters. + + @param model Path to model (.blob file) + */ + explicit Params(const std::string &model) { + desc.blob_file = model; + }; + + // BEGIN(G-API's network parametrization API) + GBackend backend() const { return cv::gapi::oak::backend(); } + std::string tag() const { return Net::tag(); } + cv::util::any params() const { return { desc }; } + // END(G-API's network parametrization API) + +protected: + detail::ParamDesc desc; +}; + +} // namespace oak +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_OAK_INFER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp index 88d1a5d085..8b56b8a365 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/oak/oak.hpp @@ -1,158 +1,158 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_OAK_HPP -#define OPENCV_GAPI_OAK_HPP - -#include // IStreamSource -#include // GKernelPackage -#include // GOptRunArgsP - -namespace cv { -namespace gapi { -namespace oak { - -// FIXME: copypasted from dai library -struct EncoderConfig { - /** - * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) - */ - enum class RateControlMode: int { CBR, VBR }; - - /** - * Encoding profile, H264, H265 or MJPEG - */ - enum class Profile: int { H264_BASELINE, H264_HIGH, H264_MAIN, H265_MAIN, MJPEG }; - /** - * Specifies preferred bitrate (kb) of compressed output bitstream - */ - std::int32_t bitrate = 8000; - /** - * Every x number of frames a keyframe will be inserted - */ - std::int32_t keyframeFrequency = 30; - /** - * Specifies maximum bitrate (kb) of compressed output bitstream - */ - std::int32_t maxBitrate = 8000; - /** - * Specifies number of B frames to be inserted - */ - std::int32_t numBFrames = 0; - /** - * This options specifies how many frames are available in this nodes pool (can help if - * receiver node is slow at consuming - */ - std::uint32_t numFramesPool = 4; - /** - * Encoding profile, H264, H265 or MJPEG - */ - Profile profile = Profile::H265_MAIN; - /** - * Value between 0-100% (approximates quality) - */ - std::int32_t quality = 80; - /** - * Lossless mode ([M]JPEG only) - */ - bool lossless = false; - /** - * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) - */ - RateControlMode rateCtrlMode = RateControlMode::CBR; - /** - * Input and compressed output frame width - */ - std::int32_t width = 1920; - /** - * Input and compressed output frame height - */ - std::int32_t height = 1080; - /** - * Frame rate - */ - float frameRate = 30.0f; -}; - -G_API_OP(GEncFrame, (GFrame, EncoderConfig)>, "org.opencv.oak.enc_frame") { - static GArrayDesc outMeta(const GFrameDesc&, const EncoderConfig&) { - return cv::empty_array_desc(); - } -}; - -G_API_OP(GSobelXY, , "org.opencv.oak.sobelxy") { - static GFrameDesc outMeta(const GFrameDesc& in, const cv::Mat&, const cv::Mat&) { - return in; - } -}; - -G_API_OP(GCopy, , "org.opencv.oak.copy") { - static GFrameDesc outMeta(const GFrameDesc& in) { - return in; - } -}; - -// FIXME: add documentation on operations below - -GAPI_EXPORTS GArray encode(const GFrame& in, const EncoderConfig&); - -GAPI_EXPORTS GFrame sobelXY(const GFrame& in, - const cv::Mat& hk, - const cv::Mat& vk); - -GAPI_EXPORTS GFrame copy(const GFrame& in); - -// OAK backend & kernels //////////////////////////////////////////////////////// -GAPI_EXPORTS cv::gapi::GBackend backend(); -GAPI_EXPORTS cv::gapi::GKernelPackage kernels(); - -// Camera object /////////////////////////////////////////////////////////////// - -struct GAPI_EXPORTS ColorCameraParams { - /** - * Format of the frame one gets from the camera - */ - bool interleaved = false; - - // FIXME: extend - enum class BoardSocket: int { RGB, BGR }; - - BoardSocket board_socket = BoardSocket::RGB; - - // FIXME: extend - enum class Resolution: int { THE_1080_P }; - - Resolution resolution = Resolution::THE_1080_P; -}; - -class GAPI_EXPORTS ColorCamera: public cv::gapi::wip::IStreamSource { - cv::MediaFrame m_dummy; - ColorCameraParams m_params; - - virtual bool pull(cv::gapi::wip::Data &data) override; - virtual GMetaArg descr_of() const override; - -public: - ColorCamera(); - explicit ColorCamera(const ColorCameraParams& params); -}; - -} // namespace oak -} // namespace gapi - -namespace detail { -template<> struct CompileArgTag { - static const char* tag() { return "gapi.oak.colorCameraParams"; } -}; - -template<> struct CompileArgTag { - static const char* tag() { return "gapi.oak.encoderConfig"; } -}; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_OAK_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_OAK_HPP +#define OPENCV_GAPI_OAK_HPP + +#include // IStreamSource +#include // GKernelPackage +#include // GOptRunArgsP + +namespace cv { +namespace gapi { +namespace oak { + +// FIXME: copypasted from dai library +struct EncoderConfig { + /** + * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) + */ + enum class RateControlMode: int { CBR, VBR }; + + /** + * Encoding profile, H264, H265 or MJPEG + */ + enum class Profile: int { H264_BASELINE, H264_HIGH, H264_MAIN, H265_MAIN, MJPEG }; + /** + * Specifies preferred bitrate (kb) of compressed output bitstream + */ + std::int32_t bitrate = 8000; + /** + * Every x number of frames a keyframe will be inserted + */ + std::int32_t keyframeFrequency = 30; + /** + * Specifies maximum bitrate (kb) of compressed output bitstream + */ + std::int32_t maxBitrate = 8000; + /** + * Specifies number of B frames to be inserted + */ + std::int32_t numBFrames = 0; + /** + * This options specifies how many frames are available in this nodes pool (can help if + * receiver node is slow at consuming + */ + std::uint32_t numFramesPool = 4; + /** + * Encoding profile, H264, H265 or MJPEG + */ + Profile profile = Profile::H265_MAIN; + /** + * Value between 0-100% (approximates quality) + */ + std::int32_t quality = 80; + /** + * Lossless mode ([M]JPEG only) + */ + bool lossless = false; + /** + * Rate control mode specifies if constant or variable bitrate should be used (H264 / H265) + */ + RateControlMode rateCtrlMode = RateControlMode::CBR; + /** + * Input and compressed output frame width + */ + std::int32_t width = 1920; + /** + * Input and compressed output frame height + */ + std::int32_t height = 1080; + /** + * Frame rate + */ + float frameRate = 30.0f; +}; + +G_API_OP(GEncFrame, (GFrame, EncoderConfig)>, "org.opencv.oak.enc_frame") { + static GArrayDesc outMeta(const GFrameDesc&, const EncoderConfig&) { + return cv::empty_array_desc(); + } +}; + +G_API_OP(GSobelXY, , "org.opencv.oak.sobelxy") { + static GFrameDesc outMeta(const GFrameDesc& in, const cv::Mat&, const cv::Mat&) { + return in; + } +}; + +G_API_OP(GCopy, , "org.opencv.oak.copy") { + static GFrameDesc outMeta(const GFrameDesc& in) { + return in; + } +}; + +// FIXME: add documentation on operations below + +GAPI_EXPORTS GArray encode(const GFrame& in, const EncoderConfig&); + +GAPI_EXPORTS GFrame sobelXY(const GFrame& in, + const cv::Mat& hk, + const cv::Mat& vk); + +GAPI_EXPORTS GFrame copy(const GFrame& in); + +// OAK backend & kernels //////////////////////////////////////////////////////// +GAPI_EXPORTS cv::gapi::GBackend backend(); +GAPI_EXPORTS cv::gapi::GKernelPackage kernels(); + +// Camera object /////////////////////////////////////////////////////////////// + +struct GAPI_EXPORTS ColorCameraParams { + /** + * Format of the frame one gets from the camera + */ + bool interleaved = false; + + // FIXME: extend + enum class BoardSocket: int { RGB, BGR }; + + BoardSocket board_socket = BoardSocket::RGB; + + // FIXME: extend + enum class Resolution: int { THE_1080_P }; + + Resolution resolution = Resolution::THE_1080_P; +}; + +class GAPI_EXPORTS ColorCamera: public cv::gapi::wip::IStreamSource { + cv::MediaFrame m_dummy; + ColorCameraParams m_params; + + virtual bool pull(cv::gapi::wip::Data &data) override; + virtual GMetaArg descr_of() const override; + +public: + ColorCamera(); + explicit ColorCamera(const ColorCameraParams& params); +}; + +} // namespace oak +} // namespace gapi + +namespace detail { +template<> struct CompileArgTag { + static const char* tag() { return "gapi.oak.colorCameraParams"; } +}; + +template<> struct CompileArgTag { + static const char* tag() { return "gapi.oak.encoderConfig"; } +}; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_OAK_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp index cc48253ff8..b79aace0ca 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/core.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OCL_CORE_API_HPP -#define OPENCV_GAPI_OCL_CORE_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace core { -namespace ocl { - -GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -} // namespace ocl -} // namespace core -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_OCL_CORE_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OCL_CORE_API_HPP +#define OPENCV_GAPI_OCL_CORE_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace core { +namespace ocl { + +GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +} // namespace ocl +} // namespace core +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_OCL_CORE_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp index 5a0e04ac49..b09082282f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/goclkernel.hpp @@ -1,260 +1,260 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GOCLKERNEL_HPP -#define OPENCV_GAPI_GOCLKERNEL_HPP - -#include -#include -#include -#include - -#include -#include -#include -#include - -// FIXME: namespace scheme for backends? -namespace cv { - -namespace gimpl -{ - // Forward-declare an internal class - class GOCLExecutable; -} // namespace gimpl - -namespace gapi -{ -/** - * @brief This namespace contains G-API OpenCL backend functions, structures, and symbols. - */ -namespace ocl -{ - /** - * \addtogroup gapi_std_backends G-API Standard Backends - * @{ - */ - /** - * @brief Get a reference to OCL backend. - * - * At the moment, the OCL backend is built atop of OpenCV - * "Transparent API" (T-API), see cv::UMat for details. - * - * @sa gapi_std_backends - */ - GAPI_EXPORTS cv::gapi::GBackend backend(); - /** @} */ -} // namespace ocl -} // namespace gapi - - -// Represents arguments which are passed to a wrapped OCL function -// FIXME: put into detail? -class GAPI_EXPORTS GOCLContext -{ -public: - // Generic accessor API - template - const T& inArg(int input) { return m_args.at(input).get(); } - - // Syntax sugar - const cv::UMat& inMat(int input); - cv::UMat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() - - const cv::Scalar& inVal(int input); - cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() - template std::vector& outVecR(int output) // FIXME: the same issue - { - return outVecRef(output).wref(); - } - template T& outOpaqueR(int output) // FIXME: the same issue - { - return outOpaqueRef(output).wref(); - } - -protected: - detail::VectorRef& outVecRef(int output); - detail::OpaqueRef& outOpaqueRef(int output); - - std::vector m_args; - std::unordered_map m_results; - - - friend class gimpl::GOCLExecutable; -}; - -class GAPI_EXPORTS GOCLKernel -{ -public: - // This function is kernel's execution entry point (does the processing work) - using F = std::function; - - GOCLKernel(); - explicit GOCLKernel(const F& f); - - void apply(GOCLContext &ctx); - -protected: - F m_f; -}; - -// FIXME: This is an ugly ad-hoc implementation. TODO: refactor - -namespace detail -{ -template struct ocl_get_in; -template<> struct ocl_get_in -{ - static cv::UMat get(GOCLContext &ctx, int idx) { return ctx.inMat(idx); } -}; -template<> struct ocl_get_in -{ - static cv::Scalar get(GOCLContext &ctx, int idx) { return ctx.inVal(idx); } -}; -template struct ocl_get_in > -{ - static const std::vector& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; -template<> struct ocl_get_in -{ - static cv::MediaFrame get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } -}; -template struct ocl_get_in > -{ - static const U& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } -}; -template struct ocl_get_in -{ - static T get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -struct tracked_cv_umat{ - //TODO Think if T - API could reallocate UMat to a proper size - how do we handle this ? - //tracked_cv_umat(cv::UMat& m) : r{(m)}, original_data{m.getMat(ACCESS_RW).data} {} - tracked_cv_umat(cv::UMat& m) : r(m), original_data{ nullptr } {} - cv::UMat &r; // FIXME: It was a value (not a reference) before. - // Actually OCL backend should allocate its internal data! - uchar* original_data; - - operator cv::UMat& (){ return r;} - void validate() const{ - //if (r.getMat(ACCESS_RW).data != original_data) - //{ - // util::throw_error - // (std::logic_error - // ("OpenCV kernel output parameter was reallocated. \n" - // "Incorrect meta data was provided ?")); - //} - - } -}; - -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) // unreachable code -#endif -template -void postprocess_ocl(Outputs&... outs) -{ - struct - { - void operator()(tracked_cv_umat* bm) { bm->validate(); } - void operator()(...) { } - - } validate; - //dummy array to unfold parameter pack - int dummy[] = { 0, (validate(&outs), 0)... }; - cv::util::suppress_unused_warning(dummy); -} -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -template struct ocl_get_out; -template<> struct ocl_get_out -{ - static tracked_cv_umat get(GOCLContext &ctx, int idx) - { - auto& r = ctx.outMatR(idx); - return{ r }; - } -}; -template<> struct ocl_get_out -{ - static cv::Scalar& get(GOCLContext &ctx, int idx) - { - return ctx.outValR(idx); - } -}; -template struct ocl_get_out > -{ - static std::vector& get(GOCLContext &ctx, int idx) { return ctx.outVecR(idx); } -}; -template struct ocl_get_out > -{ - static U& get(GOCLContext &ctx, int idx) { return ctx.outOpaqueR(idx); } -}; - -template -struct OCLCallHelper; - -// FIXME: probably can be simplified with std::apply or analogue. -template -struct OCLCallHelper, std::tuple > -{ - template - struct call_and_postprocess - { - template - static void call(Inputs&&... ins, Outputs&&... outs) - { - //not using a std::forward on outs is deliberate in order to - //cause compilation error, by trying to bind rvalue references to lvalue references - Impl::run(std::forward(ins)..., outs...); - - postprocess_ocl(outs...); - } - }; - - template - static void call_impl(GOCLContext &ctx, detail::Seq, detail::Seq) - { - //TODO: Make sure that OpenCV kernels do not reallocate memory for output parameters - //by comparing it's state (data ptr) before and after the call. - //Convert own::Scalar to cv::Scalar before call kernel and run kernel - //convert cv::Scalar to own::Scalar after call kernel and write back results - call_and_postprocess::get(ctx, IIs))...>::call(ocl_get_in::get(ctx, IIs)..., ocl_get_out::get(ctx, OIs)...); - } - - static void call(GOCLContext &ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -} // namespace detail - -template -class GOCLKernelImpl: public cv::detail::OCLCallHelper, - public cv::detail::KernelTag -{ - using P = detail::OCLCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::ocl::backend(); } - static cv::GOCLKernel kernel() { return GOCLKernel(&P::call); } -}; - -#define GAPI_OCL_KERNEL(Name, API) struct Name: public cv::GOCLKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GOCLKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GOCLKERNEL_HPP +#define OPENCV_GAPI_GOCLKERNEL_HPP + +#include +#include +#include +#include + +#include +#include +#include +#include + +// FIXME: namespace scheme for backends? +namespace cv { + +namespace gimpl +{ + // Forward-declare an internal class + class GOCLExecutable; +} // namespace gimpl + +namespace gapi +{ +/** + * @brief This namespace contains G-API OpenCL backend functions, structures, and symbols. + */ +namespace ocl +{ + /** + * \addtogroup gapi_std_backends G-API Standard Backends + * @{ + */ + /** + * @brief Get a reference to OCL backend. + * + * At the moment, the OCL backend is built atop of OpenCV + * "Transparent API" (T-API), see cv::UMat for details. + * + * @sa gapi_std_backends + */ + GAPI_EXPORTS cv::gapi::GBackend backend(); + /** @} */ +} // namespace ocl +} // namespace gapi + + +// Represents arguments which are passed to a wrapped OCL function +// FIXME: put into detail? +class GAPI_EXPORTS GOCLContext +{ +public: + // Generic accessor API + template + const T& inArg(int input) { return m_args.at(input).get(); } + + // Syntax sugar + const cv::UMat& inMat(int input); + cv::UMat& outMatR(int output); // FIXME: Avoid cv::Mat m = ctx.outMatR() + + const cv::Scalar& inVal(int input); + cv::Scalar& outValR(int output); // FIXME: Avoid cv::Scalar s = ctx.outValR() + template std::vector& outVecR(int output) // FIXME: the same issue + { + return outVecRef(output).wref(); + } + template T& outOpaqueR(int output) // FIXME: the same issue + { + return outOpaqueRef(output).wref(); + } + +protected: + detail::VectorRef& outVecRef(int output); + detail::OpaqueRef& outOpaqueRef(int output); + + std::vector m_args; + std::unordered_map m_results; + + + friend class gimpl::GOCLExecutable; +}; + +class GAPI_EXPORTS GOCLKernel +{ +public: + // This function is kernel's execution entry point (does the processing work) + using F = std::function; + + GOCLKernel(); + explicit GOCLKernel(const F& f); + + void apply(GOCLContext &ctx); + +protected: + F m_f; +}; + +// FIXME: This is an ugly ad-hoc implementation. TODO: refactor + +namespace detail +{ +template struct ocl_get_in; +template<> struct ocl_get_in +{ + static cv::UMat get(GOCLContext &ctx, int idx) { return ctx.inMat(idx); } +}; +template<> struct ocl_get_in +{ + static cv::Scalar get(GOCLContext &ctx, int idx) { return ctx.inVal(idx); } +}; +template struct ocl_get_in > +{ + static const std::vector& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; +template<> struct ocl_get_in +{ + static cv::MediaFrame get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } +}; +template struct ocl_get_in > +{ + static const U& get(GOCLContext &ctx, int idx) { return ctx.inArg(idx).rref(); } +}; +template struct ocl_get_in +{ + static T get(GOCLContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +struct tracked_cv_umat{ + //TODO Think if T - API could reallocate UMat to a proper size - how do we handle this ? + //tracked_cv_umat(cv::UMat& m) : r{(m)}, original_data{m.getMat(ACCESS_RW).data} {} + tracked_cv_umat(cv::UMat& m) : r(m), original_data{ nullptr } {} + cv::UMat &r; // FIXME: It was a value (not a reference) before. + // Actually OCL backend should allocate its internal data! + uchar* original_data; + + operator cv::UMat& (){ return r;} + void validate() const{ + //if (r.getMat(ACCESS_RW).data != original_data) + //{ + // util::throw_error + // (std::logic_error + // ("OpenCV kernel output parameter was reallocated. \n" + // "Incorrect meta data was provided ?")); + //} + + } +}; + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) // unreachable code +#endif +template +void postprocess_ocl(Outputs&... outs) +{ + struct + { + void operator()(tracked_cv_umat* bm) { bm->validate(); } + void operator()(...) { } + + } validate; + //dummy array to unfold parameter pack + int dummy[] = { 0, (validate(&outs), 0)... }; + cv::util::suppress_unused_warning(dummy); +} +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +template struct ocl_get_out; +template<> struct ocl_get_out +{ + static tracked_cv_umat get(GOCLContext &ctx, int idx) + { + auto& r = ctx.outMatR(idx); + return{ r }; + } +}; +template<> struct ocl_get_out +{ + static cv::Scalar& get(GOCLContext &ctx, int idx) + { + return ctx.outValR(idx); + } +}; +template struct ocl_get_out > +{ + static std::vector& get(GOCLContext &ctx, int idx) { return ctx.outVecR(idx); } +}; +template struct ocl_get_out > +{ + static U& get(GOCLContext &ctx, int idx) { return ctx.outOpaqueR(idx); } +}; + +template +struct OCLCallHelper; + +// FIXME: probably can be simplified with std::apply or analogue. +template +struct OCLCallHelper, std::tuple > +{ + template + struct call_and_postprocess + { + template + static void call(Inputs&&... ins, Outputs&&... outs) + { + //not using a std::forward on outs is deliberate in order to + //cause compilation error, by trying to bind rvalue references to lvalue references + Impl::run(std::forward(ins)..., outs...); + + postprocess_ocl(outs...); + } + }; + + template + static void call_impl(GOCLContext &ctx, detail::Seq, detail::Seq) + { + //TODO: Make sure that OpenCV kernels do not reallocate memory for output parameters + //by comparing it's state (data ptr) before and after the call. + //Convert own::Scalar to cv::Scalar before call kernel and run kernel + //convert cv::Scalar to own::Scalar after call kernel and write back results + call_and_postprocess::get(ctx, IIs))...>::call(ocl_get_in::get(ctx, IIs)..., ocl_get_out::get(ctx, OIs)...); + } + + static void call(GOCLContext &ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +} // namespace detail + +template +class GOCLKernelImpl: public cv::detail::OCLCallHelper, + public cv::detail::KernelTag +{ + using P = detail::OCLCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::ocl::backend(); } + static cv::GOCLKernel kernel() { return GOCLKernel(&P::call); } +}; + +#define GAPI_OCL_KERNEL(Name, API) struct Name: public cv::GOCLKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GOCLKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp index 10c20bd0f2..1bb5911b18 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ocl/imgproc.hpp @@ -1,27 +1,27 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OCL_IMGPROC_API_HPP -#define OPENCV_GAPI_OCL_IMGPROC_API_HPP - -#include // GAPI_EXPORTS -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace imgproc { -namespace ocl { - - GAPI_EXPORTS GKernelPackage kernels(); - -} // namespace ocl -} // namespace imgproc -} // namespace gapi -} // namespace cv - - -#endif // OPENCV_GAPI_OCL_IMGPROC_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OCL_IMGPROC_API_HPP +#define OPENCV_GAPI_OCL_IMGPROC_API_HPP + +#include // GAPI_EXPORTS +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace imgproc { +namespace ocl { + + GAPI_EXPORTS GKernelPackage kernels(); + +} // namespace ocl +} // namespace imgproc +} // namespace gapi +} // namespace cv + + +#endif // OPENCV_GAPI_OCL_IMGPROC_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp index 57b8c857e8..7c2c42d8a2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/opencv_includes.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. - -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OPENCV_INCLUDES_HPP -#define OPENCV_GAPI_OPENCV_INCLUDES_HPP - -#if !defined(GAPI_STANDALONE) -# include -# include -# include -# include -#define GAPI_OWN_TYPES_LIST cv::gapi::own::Rect, \ - cv::gapi::own::Size, \ - cv::gapi::own::Point, \ - cv::gapi::own::Point2f, \ - cv::gapi::own::Scalar, \ - cv::gapi::own::Mat -#else // Without OpenCV -# include -# include // cv::gapi::own::Rect/Size/Point -# include // cv::gapi::own::Scalar -# include -// replacement of cv's structures: -namespace cv { - using Rect = gapi::own::Rect; - using Size = gapi::own::Size; - using Point = gapi::own::Point; - using Point2f = gapi::own::Point2f; - using Point3f = gapi::own::Point3f; - using Scalar = gapi::own::Scalar; - using Mat = gapi::own::Mat; -} // namespace cv -#define GAPI_OWN_TYPES_LIST cv::gapi::own::VoidType - -#endif // !defined(GAPI_STANDALONE) - -#endif // OPENCV_GAPI_OPENCV_INCLUDES_HPP +// This file is part of OpenCV project. + +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OPENCV_INCLUDES_HPP +#define OPENCV_GAPI_OPENCV_INCLUDES_HPP + +#if !defined(GAPI_STANDALONE) +# include +# include +# include +# include +#define GAPI_OWN_TYPES_LIST cv::gapi::own::Rect, \ + cv::gapi::own::Size, \ + cv::gapi::own::Point, \ + cv::gapi::own::Point2f, \ + cv::gapi::own::Scalar, \ + cv::gapi::own::Mat +#else // Without OpenCV +# include +# include // cv::gapi::own::Rect/Size/Point +# include // cv::gapi::own::Scalar +# include +// replacement of cv's structures: +namespace cv { + using Rect = gapi::own::Rect; + using Size = gapi::own::Size; + using Point = gapi::own::Point; + using Point2f = gapi::own::Point2f; + using Point3f = gapi::own::Point3f; + using Scalar = gapi::own::Scalar; + using Mat = gapi::own::Mat; +} // namespace cv +#define GAPI_OWN_TYPES_LIST cv::gapi::own::VoidType + +#endif // !defined(GAPI_STANDALONE) + +#endif // OPENCV_GAPI_OPENCV_INCLUDES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp index 525f5ad1fe..6794b44b6e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/operators.hpp @@ -1,70 +1,70 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OPERATORS_HPP -#define OPENCV_GAPI_OPERATORS_HPP - -#include -#include - -namespace cv -{ -GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator+(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator-(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, float rhs); -GAPI_EXPORTS cv::GMat operator*(float lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator*(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator/(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator~(const cv::GMat& lhs); - -GAPI_EXPORTS cv::GMat operator&(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator|(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator^(const cv::GScalar& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GScalar& rhs); - -GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GMat& rhs); - -GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GScalar& rhs); -GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GScalar& rhs); - -GAPI_EXPORTS cv::GMat operator>(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator>=(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator<=(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator==(const cv::GScalar& lhs, const cv::GMat& rhs); -GAPI_EXPORTS cv::GMat operator!=(const cv::GScalar& lhs, const cv::GMat& rhs); -} // cv - -#endif // OPENCV_GAPI_OPERATORS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OPERATORS_HPP +#define OPENCV_GAPI_OPERATORS_HPP + +#include +#include + +namespace cv +{ +GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator+(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator+(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator-(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator-(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, float rhs); +GAPI_EXPORTS cv::GMat operator*(float lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator*(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator*(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator/(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator/(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator~(const cv::GMat& lhs); + +GAPI_EXPORTS cv::GMat operator&(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator|(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator^(const cv::GScalar& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator&(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator|(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator^(const cv::GMat& lhs, const cv::GScalar& rhs); + +GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GMat& rhs); + +GAPI_EXPORTS cv::GMat operator>(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator>=(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator<(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator<=(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator==(const cv::GMat& lhs, const cv::GScalar& rhs); +GAPI_EXPORTS cv::GMat operator!=(const cv::GMat& lhs, const cv::GScalar& rhs); + +GAPI_EXPORTS cv::GMat operator>(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator>=(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator<=(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator==(const cv::GScalar& lhs, const cv::GMat& rhs); +GAPI_EXPORTS cv::GMat operator!=(const cv::GScalar& lhs, const cv::GMat& rhs); +} // cv + +#endif // OPENCV_GAPI_OPERATORS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp index 1da0c18932..b73d7e6ee0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/ot.hpp @@ -1,194 +1,194 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_OT_HPP -#define OPENCV_GAPI_OT_HPP - -#include -#include -#include - -namespace cv { -namespace gapi { -/** - * @brief This namespace contains G-API Operation Types for - * VAS Object Tracking module functionality. - */ -namespace ot { - -/** - * @enum TrackingStatus - * - * Tracking status twin for vas::ot::TrackingStatus - */ -enum TrackingStatus -{ - NEW = 0, /**< The object is newly added. */ - TRACKED, /**< The object is being tracked. */ - LOST /**< The object gets lost now. The object can be tracked again - by specifying detected object manually. */ -}; - -struct GAPI_EXPORTS_W_SIMPLE ObjectTrackerParams -{ - /** - * Maximum number of trackable objects in a frame. - * Valid range: 1 <= max_num_objects. Or it can be -1 if there is no limitation - * of maximum number in X86. KMB/TBH has limitation up to 1024. - * Default value is -1 which means there is no limitation in X86. KMB/TBH is -1 means 200. - */ - GAPI_PROP_RW int32_t max_num_objects = -1; - - /** - * Input color format. Supports 0(BGR), 1(NV12), 2(BGRX) and 4(I420) - */ - GAPI_PROP_RW int32_t input_image_format = 0; - - /** - * Specifies whether tracker to use detection class for keeping id of an object. - * If it is true, new detection will be associated from previous tracking only when - * those two have same class. - * class id of an object is fixed across video frames. - * If it is false, new detection can be associated across different-class objects. - * In this case, the class id of an object may change across video frames depending on the tracker input. - * It is recommended to turn this option off when it is likely that detector confuses the class of object. - * For example, when detector confuses bicycle and motorbike. Turning this option off will increase - * the tracking reliability as tracker will ignore the class label of detector. - * @n - * Default value is true. - */ - GAPI_PROP_RW bool tracking_per_class = true; - - bool operator==(const ObjectTrackerParams& other) const - { - return max_num_objects == other.max_num_objects - && input_image_format == other.input_image_format - && tracking_per_class == other.tracking_per_class; - } -}; - -using GTrackedInfo = std::tuple, cv::GArray, cv::GArray, cv::GArray>; - -G_API_OP(GTrackFromMat, , cv::GArray, float)>, "com.intel.track_from_mat") -{ - static std::tuple outMeta(cv::GMatDesc, cv::GArrayDesc, cv::GArrayDesc, float) - { - return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), - cv::empty_array_desc(), cv::empty_array_desc()); - } -}; - -G_API_OP(GTrackFromFrame, , cv::GArray, float)>, "com.intel.track_from_frame") -{ - static std::tuple outMeta(cv::GFrameDesc, cv::GArrayDesc, cv::GArrayDesc, float) - { - return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), - cv::empty_array_desc(), cv::empty_array_desc()); - } -}; - -/** - * @brief Tracks objects with video frames. - * If a detected object is overlapped enough with one of tracked object, the tracked object's - * informationis updated with the input detected object. - * On the other hand, if a detected object is overlapped with none of tracked objects, - * the detected object is newly added and ObjectTracker starts to track the object. - * In zero term tracking type, ObjectTracker clears tracked objects in case that empty - * list of detected objects is passed in. - * - * @param mat Input frame. - * @param detected_rects Detected objects rectangles in the input frame. - * @param detected_class_labels Detected objects class labels in the input frame. - * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. - * The valid range is [0.005 ~ 0.5]. - * @return Tracking results of target objects. - * cv::GArray Array of rectangles for tracked objects. - * cv::GArray Array of detected objects labels. - * cv::GArray Array of tracking IDs for objects. - * Numbering sequence starts from 1. - * The value 0 means the tracking ID of this object has - * not been assigned. - * cv::GArray Array of tracking statuses for objects. - */ -GAPI_EXPORTS_W std::tuple, - cv::GArray, - cv::GArray, - cv::GArray> - track(const cv::GMat& mat, - const cv::GArray& detected_rects, - const cv::GArray& detected_class_labels, - float delta); - - -/** - @overload - * @brief Tracks objects with video frames. Overload of track(...) for frame as GFrame. - * - * @param frame Input frame. - * @param detected_rects Detected objects rectangles in the input frame. - * @param detected_class_labels Detected objects class labels in the input frame. - * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. - * The valid range is [0.005 ~ 0.5]. - * @return Tracking results of target objects. - * @return Tracking results of target objects. - * cv::GArray Array of rectangles for tracked objects. - * cv::GArray Array of detected objects labels. - * cv::GArray Array of tracking IDs for objects. - * Numbering sequence starts from 1. - * The value 0 means the tracking ID of this object has - * not been assigned. - * cv::GArray Array of tracking statuses for objects. - */ -GAPI_EXPORTS_W std::tuple, - cv::GArray, - cv::GArray, - cv::GArray> - track(const cv::GFrame& frame, - const cv::GArray& detected_rects, - const cv::GArray& detected_class_labels, - float delta); -} // namespace ot -} // namespace gapi -} // namespace cv - -// FIXME: move to a separate file? -namespace cv -{ -namespace detail -{ -template<> struct CompileArgTag -{ - static const char* tag() - { - return "cv.gapi.ot.object_tracker_params"; - } -}; -} // namespace detail - -namespace gapi -{ -namespace s11n -{ -namespace detail -{ -template<> struct S11N { - static void serialize(IOStream &os, const cv::gapi::ot::ObjectTrackerParams &p) { - os << p. max_num_objects << p.input_image_format << p.tracking_per_class; - } - static cv::gapi::ot::ObjectTrackerParams deserialize(IIStream &is) { - cv::gapi::ot::ObjectTrackerParams p; - is >> p. max_num_objects >> p.input_image_format >> p.tracking_per_class; - return p; - } -}; -} // namespace detail -} // namespace s11n -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_OT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_OT_HPP +#define OPENCV_GAPI_OT_HPP + +#include +#include +#include + +namespace cv { +namespace gapi { +/** + * @brief This namespace contains G-API Operation Types for + * VAS Object Tracking module functionality. + */ +namespace ot { + +/** + * @enum TrackingStatus + * + * Tracking status twin for vas::ot::TrackingStatus + */ +enum TrackingStatus +{ + NEW = 0, /**< The object is newly added. */ + TRACKED, /**< The object is being tracked. */ + LOST /**< The object gets lost now. The object can be tracked again + by specifying detected object manually. */ +}; + +struct GAPI_EXPORTS_W_SIMPLE ObjectTrackerParams +{ + /** + * Maximum number of trackable objects in a frame. + * Valid range: 1 <= max_num_objects. Or it can be -1 if there is no limitation + * of maximum number in X86. KMB/TBH has limitation up to 1024. + * Default value is -1 which means there is no limitation in X86. KMB/TBH is -1 means 200. + */ + GAPI_PROP_RW int32_t max_num_objects = -1; + + /** + * Input color format. Supports 0(BGR), 1(NV12), 2(BGRX) and 4(I420) + */ + GAPI_PROP_RW int32_t input_image_format = 0; + + /** + * Specifies whether tracker to use detection class for keeping id of an object. + * If it is true, new detection will be associated from previous tracking only when + * those two have same class. + * class id of an object is fixed across video frames. + * If it is false, new detection can be associated across different-class objects. + * In this case, the class id of an object may change across video frames depending on the tracker input. + * It is recommended to turn this option off when it is likely that detector confuses the class of object. + * For example, when detector confuses bicycle and motorbike. Turning this option off will increase + * the tracking reliability as tracker will ignore the class label of detector. + * @n + * Default value is true. + */ + GAPI_PROP_RW bool tracking_per_class = true; + + bool operator==(const ObjectTrackerParams& other) const + { + return max_num_objects == other.max_num_objects + && input_image_format == other.input_image_format + && tracking_per_class == other.tracking_per_class; + } +}; + +using GTrackedInfo = std::tuple, cv::GArray, cv::GArray, cv::GArray>; + +G_API_OP(GTrackFromMat, , cv::GArray, float)>, "com.intel.track_from_mat") +{ + static std::tuple outMeta(cv::GMatDesc, cv::GArrayDesc, cv::GArrayDesc, float) + { + return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), + cv::empty_array_desc(), cv::empty_array_desc()); + } +}; + +G_API_OP(GTrackFromFrame, , cv::GArray, float)>, "com.intel.track_from_frame") +{ + static std::tuple outMeta(cv::GFrameDesc, cv::GArrayDesc, cv::GArrayDesc, float) + { + return std::make_tuple(cv::empty_array_desc(), cv::empty_array_desc(), + cv::empty_array_desc(), cv::empty_array_desc()); + } +}; + +/** + * @brief Tracks objects with video frames. + * If a detected object is overlapped enough with one of tracked object, the tracked object's + * informationis updated with the input detected object. + * On the other hand, if a detected object is overlapped with none of tracked objects, + * the detected object is newly added and ObjectTracker starts to track the object. + * In zero term tracking type, ObjectTracker clears tracked objects in case that empty + * list of detected objects is passed in. + * + * @param mat Input frame. + * @param detected_rects Detected objects rectangles in the input frame. + * @param detected_class_labels Detected objects class labels in the input frame. + * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. + * The valid range is [0.005 ~ 0.5]. + * @return Tracking results of target objects. + * cv::GArray Array of rectangles for tracked objects. + * cv::GArray Array of detected objects labels. + * cv::GArray Array of tracking IDs for objects. + * Numbering sequence starts from 1. + * The value 0 means the tracking ID of this object has + * not been assigned. + * cv::GArray Array of tracking statuses for objects. + */ +GAPI_EXPORTS_W std::tuple, + cv::GArray, + cv::GArray, + cv::GArray> + track(const cv::GMat& mat, + const cv::GArray& detected_rects, + const cv::GArray& detected_class_labels, + float delta); + + +/** + @overload + * @brief Tracks objects with video frames. Overload of track(...) for frame as GFrame. + * + * @param frame Input frame. + * @param detected_rects Detected objects rectangles in the input frame. + * @param detected_class_labels Detected objects class labels in the input frame. + * @param delta Frame_delta_t Delta time between two consecutive tracking in seconds. + * The valid range is [0.005 ~ 0.5]. + * @return Tracking results of target objects. + * @return Tracking results of target objects. + * cv::GArray Array of rectangles for tracked objects. + * cv::GArray Array of detected objects labels. + * cv::GArray Array of tracking IDs for objects. + * Numbering sequence starts from 1. + * The value 0 means the tracking ID of this object has + * not been assigned. + * cv::GArray Array of tracking statuses for objects. + */ +GAPI_EXPORTS_W std::tuple, + cv::GArray, + cv::GArray, + cv::GArray> + track(const cv::GFrame& frame, + const cv::GArray& detected_rects, + const cv::GArray& detected_class_labels, + float delta); +} // namespace ot +} // namespace gapi +} // namespace cv + +// FIXME: move to a separate file? +namespace cv +{ +namespace detail +{ +template<> struct CompileArgTag +{ + static const char* tag() + { + return "cv.gapi.ot.object_tracker_params"; + } +}; +} // namespace detail + +namespace gapi +{ +namespace s11n +{ +namespace detail +{ +template<> struct S11N { + static void serialize(IOStream &os, const cv::gapi::ot::ObjectTrackerParams &p) { + os << p. max_num_objects << p.input_image_format << p.tracking_per_class; + } + static cv::gapi::ot::ObjectTrackerParams deserialize(IIStream &is) { + cv::gapi::ot::ObjectTrackerParams p; + is >> p. max_num_objects >> p.input_image_format >> p.tracking_per_class; + return p; + } +}; +} // namespace detail +} // namespace s11n +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_OT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp index 9e8be33272..ab2fb896f1 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/assert.hpp @@ -1,60 +1,60 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_ASSERT_HPP -#define OPENCV_GAPI_OWN_ASSERT_HPP - -#include - -#define GAPI_DbgAssertNoOp(expr) { \ - constexpr bool _assert_tmp = false && (expr); \ - cv::util::suppress_unused_warning(_assert_tmp); \ -} - -#if !defined(GAPI_STANDALONE) -#include -#define GAPI_Assert CV_Assert - -#if defined _DEBUG || defined CV_STATIC_ANALYSIS -# define GAPI_DbgAssert CV_DbgAssert -#else -# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) -#endif - -#define GAPI_Error(msg) CV_Error(cv::Error::StsError, msg) - -#else -#include -#include -#include - -namespace detail -{ - [[noreturn]] inline void assert_abort(const char* str, int line, const char* file, const char* func) - { - std::stringstream ss; - ss << file << ":" << line << ": Assertion " << str << " in function " << func << " failed\n"; - cv::util::throw_error(std::logic_error(ss.str())); - } -} - -#define GAPI_Assert(expr) \ -{ if (!(expr)) ::detail::assert_abort(#expr, __LINE__, __FILE__, __func__); } - -#ifdef NDEBUG -# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) -#else -# define GAPI_DbgAssert(expr) GAPI_Assert(expr) -#endif - -#define GAPI_Error(msg) { \ - ::detail::assert_abort(msg, __LINE__, __FILE__, __func__); \ -} - -#endif // GAPI_STANDALONE - -#endif // OPENCV_GAPI_OWN_ASSERT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_ASSERT_HPP +#define OPENCV_GAPI_OWN_ASSERT_HPP + +#include + +#define GAPI_DbgAssertNoOp(expr) { \ + constexpr bool _assert_tmp = false && (expr); \ + cv::util::suppress_unused_warning(_assert_tmp); \ +} + +#if !defined(GAPI_STANDALONE) +#include +#define GAPI_Assert CV_Assert + +#if defined _DEBUG || defined CV_STATIC_ANALYSIS +# define GAPI_DbgAssert CV_DbgAssert +#else +# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) +#endif + +#define GAPI_Error(msg) CV_Error(cv::Error::StsError, msg) + +#else +#include +#include +#include + +namespace detail +{ + [[noreturn]] inline void assert_abort(const char* str, int line, const char* file, const char* func) + { + std::stringstream ss; + ss << file << ":" << line << ": Assertion " << str << " in function " << func << " failed\n"; + cv::util::throw_error(std::logic_error(ss.str())); + } +} + +#define GAPI_Assert(expr) \ +{ if (!(expr)) ::detail::assert_abort(#expr, __LINE__, __FILE__, __func__); } + +#ifdef NDEBUG +# define GAPI_DbgAssert(expr) GAPI_DbgAssertNoOp(expr) +#else +# define GAPI_DbgAssert(expr) GAPI_Assert(expr) +#endif + +#define GAPI_Error(msg) { \ + ::detail::assert_abort(msg, __LINE__, __FILE__, __func__); \ +} + +#endif // GAPI_STANDALONE + +#endif // OPENCV_GAPI_OWN_ASSERT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp index 2380a1bbed..f587e24787 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/convert.hpp @@ -1,55 +1,55 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_CONVERT_HPP -#define OPENCV_GAPI_OWN_CONVERT_HPP - -#if !defined(GAPI_STANDALONE) - -#include -#include - -namespace cv -{ - template - std::vector to_own(const cv::MatSize &sz) { - std::vector result(sz.dims()); - for (int i = 0; i < sz.dims(); i++) { - // Note: cv::MatSize is not iterable - result[i] = static_cast(sz[i]); - } - return result; - } - - cv::gapi::own::Mat to_own(Mat&&) = delete; - - inline cv::gapi::own::Mat to_own(Mat const& m) { - return (m.dims == 2) - ? cv::gapi::own::Mat{m.rows, m.cols, m.type(), m.data, m.step} - : cv::gapi::own::Mat{to_own(m.size), m.type(), m.data}; - } - -namespace gapi -{ -namespace own -{ - - inline cv::Mat to_ocv(Mat const& m) { - return m.dims.empty() - ? cv::Mat{m.rows, m.cols, m.type(), m.data, m.step} - : cv::Mat{m.dims, m.type(), m.data}; - } - - cv::Mat to_ocv(Mat&&) = delete; - -} // namespace own -} // namespace gapi -} // namespace cv - -#endif // !defined(GAPI_STANDALONE) - -#endif // OPENCV_GAPI_OWN_CONVERT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_CONVERT_HPP +#define OPENCV_GAPI_OWN_CONVERT_HPP + +#if !defined(GAPI_STANDALONE) + +#include +#include + +namespace cv +{ + template + std::vector to_own(const cv::MatSize &sz) { + std::vector result(sz.dims()); + for (int i = 0; i < sz.dims(); i++) { + // Note: cv::MatSize is not iterable + result[i] = static_cast(sz[i]); + } + return result; + } + + cv::gapi::own::Mat to_own(Mat&&) = delete; + + inline cv::gapi::own::Mat to_own(Mat const& m) { + return (m.dims == 2) + ? cv::gapi::own::Mat{m.rows, m.cols, m.type(), m.data, m.step} + : cv::gapi::own::Mat{to_own(m.size), m.type(), m.data}; + } + +namespace gapi +{ +namespace own +{ + + inline cv::Mat to_ocv(Mat const& m) { + return m.dims.empty() + ? cv::Mat{m.rows, m.cols, m.type(), m.data, m.step} + : cv::Mat{m.dims, m.type(), m.data}; + } + + cv::Mat to_ocv(Mat&&) = delete; + +} // namespace own +} // namespace gapi +} // namespace cv + +#endif // !defined(GAPI_STANDALONE) + +#endif // OPENCV_GAPI_OWN_CONVERT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp index 38296c9b7c..d3bef98e98 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/cvdefs.hpp @@ -1,166 +1,166 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_CV_DEFS_HPP -#define OPENCV_GAPI_CV_DEFS_HPP - -#if defined(GAPI_STANDALONE) -// Simulate OpenCV definitions taken from various -// OpenCV interface headers if G-API is built in a -// standalone mode. - -// interface.h: - -typedef unsigned char uchar; -typedef char schar; - -typedef unsigned short ushort; - -#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" - -#define CV_CN_MAX 512 -#define CV_CN_SHIFT 3 -#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) - -#define CV_8U 0 -#define CV_8S 1 -#define CV_16U 2 -#define CV_16S 3 -#define CV_32S 4 -#define CV_32F 5 -#define CV_64F 6 -#define CV_16F 7 - -#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) -#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) - -#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) -#define CV_MAKE_TYPE CV_MAKETYPE - -#define CV_8UC1 CV_MAKETYPE(CV_8U,1) -#define CV_8UC2 CV_MAKETYPE(CV_8U,2) -#define CV_8UC3 CV_MAKETYPE(CV_8U,3) -#define CV_8UC4 CV_MAKETYPE(CV_8U,4) -#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) - -#define CV_8SC1 CV_MAKETYPE(CV_8S,1) -#define CV_8SC2 CV_MAKETYPE(CV_8S,2) -#define CV_8SC3 CV_MAKETYPE(CV_8S,3) -#define CV_8SC4 CV_MAKETYPE(CV_8S,4) -#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) - -#define CV_16UC1 CV_MAKETYPE(CV_16U,1) -#define CV_16UC2 CV_MAKETYPE(CV_16U,2) -#define CV_16UC3 CV_MAKETYPE(CV_16U,3) -#define CV_16UC4 CV_MAKETYPE(CV_16U,4) -#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) - -#define CV_16SC1 CV_MAKETYPE(CV_16S,1) -#define CV_16SC2 CV_MAKETYPE(CV_16S,2) -#define CV_16SC3 CV_MAKETYPE(CV_16S,3) -#define CV_16SC4 CV_MAKETYPE(CV_16S,4) -#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) - -#define CV_32SC1 CV_MAKETYPE(CV_32S,1) -#define CV_32SC2 CV_MAKETYPE(CV_32S,2) -#define CV_32SC3 CV_MAKETYPE(CV_32S,3) -#define CV_32SC4 CV_MAKETYPE(CV_32S,4) -#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) - -#define CV_16FC1 CV_MAKETYPE(CV_16F,1) -#define CV_16FC2 CV_MAKETYPE(CV_16F,2) -#define CV_16FC3 CV_MAKETYPE(CV_16F,3) -#define CV_16FC4 CV_MAKETYPE(CV_16F,4) -#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) - -#define CV_32FC1 CV_MAKETYPE(CV_32F,1) -#define CV_32FC2 CV_MAKETYPE(CV_32F,2) -#define CV_32FC3 CV_MAKETYPE(CV_32F,3) -#define CV_32FC4 CV_MAKETYPE(CV_32F,4) -#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) - -#define CV_64FC1 CV_MAKETYPE(CV_64F,1) -#define CV_64FC2 CV_MAKETYPE(CV_64F,2) -#define CV_64FC3 CV_MAKETYPE(CV_64F,3) -#define CV_64FC4 CV_MAKETYPE(CV_64F,4) -#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) - -// cvdef.h: - -#ifndef CV_ALWAYS_INLINE -# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) -# define CV_ALWAYS_INLINE inline __attribute__((always_inline)) -# elif defined(_MSC_VER) -# define CV_ALWAYS_INLINE __forceinline -# else -# define CV_ALWAYS_INLINE inline -# endif -#endif - -#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) -#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) -#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) -#define CV_MAT_CONT_FLAG_SHIFT 14 -#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) -#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) -#define CV_IS_CONT_MAT CV_IS_MAT_CONT -#define CV_SUBMAT_FLAG_SHIFT 15 -#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) -#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) - -//** Size of each channel item, -// 0x8442211 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ -#define CV_ELEM_SIZE1(type) \ - ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15) - -#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) - -/** 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */ -#define CV_ELEM_SIZE(type) \ - (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3)) - -#ifndef CV_OVERRIDE -# define CV_OVERRIDE override -#endif - -// base.h: -namespace cv -{ -enum BorderTypes { - BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` - BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` - BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` - BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` - BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` - BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` - - BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 - BORDER_ISOLATED = 16 //!< do not look outside of ROI -}; -// imgproc.hpp: -enum InterpolationFlags{ - INTER_NEAREST = 0, - INTER_LINEAR = 1, - INTER_CUBIC = 2, - INTER_AREA = 3, - INTER_LANCZOS4 = 4, - INTER_LINEAR_EXACT = 5, - INTER_MAX = 7, -}; -} // namespace cv - -static inline int cvFloor( double value ) -{ - int i = (int)value; - return i - (i > value); -} - -#endif // defined(GAPI_STANDALONE) - -#endif // OPENCV_GAPI_CV_DEFS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_CV_DEFS_HPP +#define OPENCV_GAPI_CV_DEFS_HPP + +#if defined(GAPI_STANDALONE) +// Simulate OpenCV definitions taken from various +// OpenCV interface headers if G-API is built in a +// standalone mode. + +// interface.h: + +typedef unsigned char uchar; +typedef char schar; + +typedef unsigned short ushort; + +#define CV_USRTYPE1 (void)"CV_USRTYPE1 support has been dropped in OpenCV 4.0" + +#define CV_CN_MAX 512 +#define CV_CN_SHIFT 3 +#define CV_DEPTH_MAX (1 << CV_CN_SHIFT) + +#define CV_8U 0 +#define CV_8S 1 +#define CV_16U 2 +#define CV_16S 3 +#define CV_32S 4 +#define CV_32F 5 +#define CV_64F 6 +#define CV_16F 7 + +#define CV_MAT_DEPTH_MASK (CV_DEPTH_MAX - 1) +#define CV_MAT_DEPTH(flags) ((flags) & CV_MAT_DEPTH_MASK) + +#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT)) +#define CV_MAKE_TYPE CV_MAKETYPE + +#define CV_8UC1 CV_MAKETYPE(CV_8U,1) +#define CV_8UC2 CV_MAKETYPE(CV_8U,2) +#define CV_8UC3 CV_MAKETYPE(CV_8U,3) +#define CV_8UC4 CV_MAKETYPE(CV_8U,4) +#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n)) + +#define CV_8SC1 CV_MAKETYPE(CV_8S,1) +#define CV_8SC2 CV_MAKETYPE(CV_8S,2) +#define CV_8SC3 CV_MAKETYPE(CV_8S,3) +#define CV_8SC4 CV_MAKETYPE(CV_8S,4) +#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n)) + +#define CV_16UC1 CV_MAKETYPE(CV_16U,1) +#define CV_16UC2 CV_MAKETYPE(CV_16U,2) +#define CV_16UC3 CV_MAKETYPE(CV_16U,3) +#define CV_16UC4 CV_MAKETYPE(CV_16U,4) +#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n)) + +#define CV_16SC1 CV_MAKETYPE(CV_16S,1) +#define CV_16SC2 CV_MAKETYPE(CV_16S,2) +#define CV_16SC3 CV_MAKETYPE(CV_16S,3) +#define CV_16SC4 CV_MAKETYPE(CV_16S,4) +#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n)) + +#define CV_32SC1 CV_MAKETYPE(CV_32S,1) +#define CV_32SC2 CV_MAKETYPE(CV_32S,2) +#define CV_32SC3 CV_MAKETYPE(CV_32S,3) +#define CV_32SC4 CV_MAKETYPE(CV_32S,4) +#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n)) + +#define CV_16FC1 CV_MAKETYPE(CV_16F,1) +#define CV_16FC2 CV_MAKETYPE(CV_16F,2) +#define CV_16FC3 CV_MAKETYPE(CV_16F,3) +#define CV_16FC4 CV_MAKETYPE(CV_16F,4) +#define CV_16FC(n) CV_MAKETYPE(CV_16F,(n)) + +#define CV_32FC1 CV_MAKETYPE(CV_32F,1) +#define CV_32FC2 CV_MAKETYPE(CV_32F,2) +#define CV_32FC3 CV_MAKETYPE(CV_32F,3) +#define CV_32FC4 CV_MAKETYPE(CV_32F,4) +#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n)) + +#define CV_64FC1 CV_MAKETYPE(CV_64F,1) +#define CV_64FC2 CV_MAKETYPE(CV_64F,2) +#define CV_64FC3 CV_MAKETYPE(CV_64F,3) +#define CV_64FC4 CV_MAKETYPE(CV_64F,4) +#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n)) + +// cvdef.h: + +#ifndef CV_ALWAYS_INLINE +# if defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 1)) +# define CV_ALWAYS_INLINE inline __attribute__((always_inline)) +# elif defined(_MSC_VER) +# define CV_ALWAYS_INLINE __forceinline +# else +# define CV_ALWAYS_INLINE inline +# endif +#endif + +#define CV_MAT_CN_MASK ((CV_CN_MAX - 1) << CV_CN_SHIFT) +#define CV_MAT_CN(flags) ((((flags) & CV_MAT_CN_MASK) >> CV_CN_SHIFT) + 1) +#define CV_MAT_TYPE_MASK (CV_DEPTH_MAX*CV_CN_MAX - 1) +#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) +#define CV_MAT_CONT_FLAG_SHIFT 14 +#define CV_MAT_CONT_FLAG (1 << CV_MAT_CONT_FLAG_SHIFT) +#define CV_IS_MAT_CONT(flags) ((flags) & CV_MAT_CONT_FLAG) +#define CV_IS_CONT_MAT CV_IS_MAT_CONT +#define CV_SUBMAT_FLAG_SHIFT 15 +#define CV_SUBMAT_FLAG (1 << CV_SUBMAT_FLAG_SHIFT) +#define CV_IS_SUBMAT(flags) ((flags) & CV_MAT_SUBMAT_FLAG) + +//** Size of each channel item, +// 0x8442211 = 1000 0100 0100 0010 0010 0001 0001 ~ array of sizeof(arr_type_elem) */ +#define CV_ELEM_SIZE1(type) \ + ((((sizeof(size_t)<<28)|0x8442211) >> CV_MAT_DEPTH(type)*4) & 15) + +#define CV_MAT_TYPE(flags) ((flags) & CV_MAT_TYPE_MASK) + +/** 0x3a50 = 11 10 10 01 01 00 00 ~ array of log2(sizeof(arr_type_elem)) */ +#define CV_ELEM_SIZE(type) \ + (CV_MAT_CN(type) << ((((sizeof(size_t)/4+1)*16384|0x3a50) >> CV_MAT_DEPTH(type)*2) & 3)) + +#ifndef CV_OVERRIDE +# define CV_OVERRIDE override +#endif + +// base.h: +namespace cv +{ +enum BorderTypes { + BORDER_CONSTANT = 0, //!< `iiiiii|abcdefgh|iiiiiii` with some specified `i` + BORDER_REPLICATE = 1, //!< `aaaaaa|abcdefgh|hhhhhhh` + BORDER_REFLECT = 2, //!< `fedcba|abcdefgh|hgfedcb` + BORDER_WRAP = 3, //!< `cdefgh|abcdefgh|abcdefg` + BORDER_REFLECT_101 = 4, //!< `gfedcb|abcdefgh|gfedcba` + BORDER_TRANSPARENT = 5, //!< `uvwxyz|abcdefgh|ijklmno` + + BORDER_REFLECT101 = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_DEFAULT = BORDER_REFLECT_101, //!< same as BORDER_REFLECT_101 + BORDER_ISOLATED = 16 //!< do not look outside of ROI +}; +// imgproc.hpp: +enum InterpolationFlags{ + INTER_NEAREST = 0, + INTER_LINEAR = 1, + INTER_CUBIC = 2, + INTER_AREA = 3, + INTER_LANCZOS4 = 4, + INTER_LINEAR_EXACT = 5, + INTER_MAX = 7, +}; +} // namespace cv + +static inline int cvFloor( double value ) +{ + int i = (int)value; + return i - (i > value); +} + +#endif // defined(GAPI_STANDALONE) + +#endif // OPENCV_GAPI_CV_DEFS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp index 67534df13f..c36f4003d0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/exports.hpp @@ -1,42 +1,42 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_TYPES_HPP -#define OPENCV_GAPI_OWN_TYPES_HPP - -# if defined(__OPENCV_BUILD) -# include -# define GAPI_EXPORTS CV_EXPORTS - /* special informative macros for wrapper generators */ -# define GAPI_PROP CV_PROP -# define GAPI_PROP_RW CV_PROP_RW -# define GAPI_WRAP CV_WRAP -# define GAPI_EXPORTS_W_SIMPLE CV_EXPORTS_W_SIMPLE -# define GAPI_EXPORTS_W CV_EXPORTS_W -# else -# define GAPI_PROP -# define GAPI_PROP_RW -# define GAPI_WRAP -# define GAPI_EXPORTS -# define GAPI_EXPORTS_W_SIMPLE -# define GAPI_EXPORTS_W - -#if 0 // Note: the following version currently is not needed for non-OpenCV build -# if defined _WIN32 -# define GAPI_EXPORTS __declspec(dllexport) -# elif defined __GNUC__ && __GNUC__ >= 4 -# define GAPI_EXPORTS __attribute__ ((visibility ("default"))) -# endif - -# ifndef GAPI_EXPORTS -# define GAPI_EXPORTS -# endif -#endif - -# endif - -#endif // OPENCV_GAPI_OWN_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_TYPES_HPP +#define OPENCV_GAPI_OWN_TYPES_HPP + +# if defined(__OPENCV_BUILD) +# include +# define GAPI_EXPORTS CV_EXPORTS + /* special informative macros for wrapper generators */ +# define GAPI_PROP CV_PROP +# define GAPI_PROP_RW CV_PROP_RW +# define GAPI_WRAP CV_WRAP +# define GAPI_EXPORTS_W_SIMPLE CV_EXPORTS_W_SIMPLE +# define GAPI_EXPORTS_W CV_EXPORTS_W +# else +# define GAPI_PROP +# define GAPI_PROP_RW +# define GAPI_WRAP +# define GAPI_EXPORTS +# define GAPI_EXPORTS_W_SIMPLE +# define GAPI_EXPORTS_W + +#if 0 // Note: the following version currently is not needed for non-OpenCV build +# if defined _WIN32 +# define GAPI_EXPORTS __declspec(dllexport) +# elif defined __GNUC__ && __GNUC__ >= 4 +# define GAPI_EXPORTS __attribute__ ((visibility ("default"))) +# endif + +# ifndef GAPI_EXPORTS +# define GAPI_EXPORTS +# endif +#endif + +# endif + +#endif // OPENCV_GAPI_OWN_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp index 50adca2d0f..ce9c0bf362 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/mat.hpp @@ -1,354 +1,354 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_MAT_HPP -#define OPENCV_GAPI_OWN_MAT_HPP - -#include -#include -#include -#include -#include - -#include //std::shared_ptr -#include //std::memcpy -#include //std::accumulate -#include -#include - -namespace cv { namespace gapi { namespace own { - namespace detail { - template - void assign_row(void* ptr, int cols, Scalar const& s) - { - auto p = static_cast(ptr); - for (int c = 0; c < cols; c++) - { - for (int ch = 0; ch < channels; ch++) - { - p[c * channels + ch] = saturate(s[ch], roundd); - } - } - } - - inline size_t default_step(int type, int cols) - { - return CV_ELEM_SIZE(type) * cols; - } - //Matrix header, i.e. fields that are unique to each Mat object. - //Devoted class is needed to implement custom behavior on move (erasing state of moved from object) - struct MatHeader{ - enum { AUTO_STEP = 0}; - enum { TYPE_MASK = 0x00000FFF }; - - MatHeader() = default; - - MatHeader(int _rows, int _cols, int type, void* _data, size_t _step) - : flags((type & TYPE_MASK)), rows(_rows), cols(_cols), data((uchar*)_data), step(_step == AUTO_STEP ? detail::default_step(type, _cols) : _step) - {} - - MatHeader(const std::vector &_dims, int type, void* _data) - : flags((type & TYPE_MASK)), data((uchar*)_data), step(0), dims(_dims) - {} - - MatHeader(const MatHeader& ) = default; - MatHeader(MatHeader&& src) : MatHeader(src) // reuse copy constructor here - { - MatHeader empty; //give it a name to call copy(not move) assignment below - src = empty; - } - MatHeader& operator=(const MatHeader& ) = default; - MatHeader& operator=(MatHeader&& src) - { - *this = src; //calling a copy assignment here, not move one - MatHeader empty; //give it a name to call copy(not move) assignment below - src = empty; - return *this; - } - /*! includes several bit-fields: - - depth - - number of channels - */ - int flags = 0; - - //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions - int rows = 0, cols = 0; - //! pointer to the data - uchar* data = nullptr; - size_t step = 0; - //! dimensions (ND-case) - std::vector dims; - }; - } // namespace detail - //concise version of cv::Mat suitable for GAPI needs (used when no dependence on OpenCV is required) - class Mat : public detail::MatHeader{ - public: - - Mat() = default; - - /** @overload - @param _rows Number of rows in a 2D array. - @param _cols Number of columns in a 2D array. - @param _type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or - CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. - @param _data Pointer to the user data. Matrix constructors that take data and step parameters do not - allocate matrix data. Instead, they just initialize the matrix header that points to the specified - data, which means that no data is copied. This operation is very efficient and can be used to - process external data using OpenCV functions. The external data is not automatically deallocated, so - you should take care of it. - @param _step Number of bytes each matrix row occupies. The value should include the padding bytes at - the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed - and the actual step is calculated as cols*elemSize(). See Mat::elemSize. - */ - Mat(int _rows, int _cols, int _type, void* _data, size_t _step = AUTO_STEP) - : MatHeader (_rows, _cols, _type, _data, _step) - {} - - Mat(const std::vector &_dims, int _type, void* _data) - : MatHeader (_dims, _type, _data) - {} - - Mat(std::vector &&_dims, int _type, void* _data) - : MatHeader (std::move(_dims), _type, _data) - {} - - Mat(Mat const& src, const Rect& roi ) - : Mat(src) - { - rows = roi.height; - cols = roi.width; - data = ptr(roi.y, roi.x); - } - - Mat(Mat const& ) = default; - Mat(Mat&& ) = default; - - Mat& operator=(Mat const& ) = default; - Mat& operator=(Mat&& ) = default; - - /** @brief Sets all or some of the array elements to the specified value. - @param s Assigned scalar converted to the actual array type. - */ - Mat& operator = (const Scalar& s) - { - constexpr unsigned max_channels = 4; //Scalar can't fit more than 4 - using func_p_t = void (*)(void*, int, Scalar const&); - using detail::assign_row; - #define TABLE_ENTRY(type) {assign_row, assign_row, assign_row, assign_row} - static constexpr func_p_t func_tbl[][max_channels] = { - TABLE_ENTRY(uchar), - TABLE_ENTRY(schar), - TABLE_ENTRY(ushort), - TABLE_ENTRY(short), - TABLE_ENTRY(int), - TABLE_ENTRY(float), - TABLE_ENTRY(double) - }; - #undef TABLE_ENTRY - - static_assert(CV_8U == 0 && CV_8S == 1 && CV_16U == 2 && CV_16S == 3 - && CV_32S == 4 && CV_32F == 5 && CV_64F == 6, - "OCV type ids used as indexes to array, thus exact numbers are important!" - ); - - const auto depth = static_cast(this->depth()); - GAPI_Assert(depth < sizeof(func_tbl)/sizeof(func_tbl[0])); - - if (dims.empty()) - { - const auto channels = static_cast(this->channels()); - GAPI_Assert(channels <= max_channels); - - auto* f = func_tbl[depth][channels - 1]; - for (int r = 0; r < rows; ++r) - { - (*f)(static_cast(ptr(r)), cols, s ); - } - } - else - { - auto* f = func_tbl[depth][0]; - // FIXME: better to refactor assign_row to use std::size_t by default - (*f)(static_cast(data), static_cast(total()), s); - } - return *this; - } - - /** @brief Returns the matrix element size in bytes. - - The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , - the method returns 3\*sizeof(short) or 6. - */ - size_t elemSize() const - { - return CV_ELEM_SIZE(type()); - } - /** @brief Returns the type of a matrix element. - - The method returns a matrix element type. This is an identifier compatible with the CvMat type - system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. - */ - int type() const {return CV_MAT_TYPE(flags);} - - /** @brief Returns the depth of a matrix element. - - The method returns the identifier of the matrix element depth (the type of each individual channel). - For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of - matrix types contains the following values: - - CV_8U - 8-bit unsigned integers ( 0..255 ) - - CV_8S - 8-bit signed integers ( -128..127 ) - - CV_16U - 16-bit unsigned integers ( 0..65535 ) - - CV_16S - 16-bit signed integers ( -32768..32767 ) - - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) - - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) - - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) - */ - int depth() const {return CV_MAT_DEPTH(flags);} - - /** @brief Returns the number of matrix channels. - - The method returns the number of matrix channels. - If matrix is N-dimensional, -1 is returned. - */ - int channels() const {return dims.empty() ? CV_MAT_CN(flags) : -1;} - - /** - @param _rows New number of rows. - @param _cols New number of columns. - @param _type New matrix type. - */ - void create(int _rows, int _cols, int _type) - { - create(Size{_cols, _rows}, _type); - } - /** @overload - @param _size Alternative new matrix size specification: Size(cols, rows) - @param _type New matrix type. - */ - void create(Size _size, int _type) - { - GAPI_Assert(_size.height >= 0 && _size.width >= 0); - if (_size != Size{cols, rows} ) - { - Mat tmp{_size.height, _size.width, _type, nullptr}; - tmp.memory.reset(new uchar[ tmp.step * tmp.rows], [](uchar * p){delete[] p;}); - tmp.data = tmp.memory.get(); - - *this = std::move(tmp); - } - } - - void create(const std::vector &_dims, int _type) - { - // FIXME: make a proper reallocation-on-demands - // WARNING: no tensor views, so no strides - Mat tmp{_dims, _type, nullptr}; - // FIXME: this accumulate duplicates a lot - const auto sz = std::accumulate(_dims.begin(), _dims.end(), 1, std::multiplies()); - tmp.memory.reset(new uchar[CV_ELEM_SIZE(_type)*sz], [](uchar * p){delete[] p;}); - tmp.data = tmp.memory.get(); - *this = std::move(tmp); - } - - /** @brief Creates a full copy of the matrix and the underlying data. - - The method creates a full copy of the matrix. The original step[] is not taken into account. - So, the copy has a continuous buffer occupying total() * elemSize() bytes. - */ - Mat clone() const - { - Mat m; - copyTo(m); - return m; - } - - /** @brief Copies the matrix to another one. - - The method copies the matrix data to another matrix. Before copying the data, the method invokes : - @code - m.create(this->size(), this->type()); - @endcode - so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the - function does not handle the case of a partial overlap between the source and the destination - matrices. - */ - void copyTo(Mat& dst) const - { - if (dims.empty()) - { - dst.create(rows, cols, type()); - for (int r = 0; r < rows; ++r) - { - std::copy_n(ptr(r), detail::default_step(type(),cols), dst.ptr(r)); - } - } - else - { - dst.create(dims, depth()); - std::copy_n(data, total()*elemSize(), data); - } - } - - /** @brief Returns true if the array has no elements. - - The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and - resize() methods `M.total() == 0` does not imply that `M.data == NULL`. - */ - bool empty() const - { - return data == 0 || total() == 0; - } - - /** @brief Returns the total number of array elements. - - The method returns the number of array elements (a number of pixels if the array represents an - image). - */ - size_t total() const - { - return dims.empty() - ? (static_cast(rows) * cols) - : std::accumulate(dims.begin(), dims.end(), static_cast(1), std::multiplies()); - } - - /** @overload - @param roi Extracted submatrix specified as a rectangle. - */ - Mat operator()( const Rect& roi ) const - { - return Mat{*this, roi}; - } - - - /** @brief Returns a pointer to the specified matrix row. - - The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in - Mat::isContinuous to know how to use these methods. - @param row Index along the dimension 0 - @param col Index along the dimension 1 - */ - uchar* ptr(int row, int col = 0) - { - return const_cast(const_cast(this)->ptr(row,col)); - } - /** @overload */ - const uchar* ptr(int row, int col = 0) const - { - return data + step * row + CV_ELEM_SIZE(type()) * col; - } - - - private: - //actual memory allocated for storage, or nullptr if object is non owning view to over memory - std::shared_ptr memory; - }; - -} //namespace own -} //namespace gapi -} //namespace cv - -#endif /* OPENCV_GAPI_OWN_MAT_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_MAT_HPP +#define OPENCV_GAPI_OWN_MAT_HPP + +#include +#include +#include +#include +#include + +#include //std::shared_ptr +#include //std::memcpy +#include //std::accumulate +#include +#include + +namespace cv { namespace gapi { namespace own { + namespace detail { + template + void assign_row(void* ptr, int cols, Scalar const& s) + { + auto p = static_cast(ptr); + for (int c = 0; c < cols; c++) + { + for (int ch = 0; ch < channels; ch++) + { + p[c * channels + ch] = saturate(s[ch], roundd); + } + } + } + + inline size_t default_step(int type, int cols) + { + return CV_ELEM_SIZE(type) * cols; + } + //Matrix header, i.e. fields that are unique to each Mat object. + //Devoted class is needed to implement custom behavior on move (erasing state of moved from object) + struct MatHeader{ + enum { AUTO_STEP = 0}; + enum { TYPE_MASK = 0x00000FFF }; + + MatHeader() = default; + + MatHeader(int _rows, int _cols, int type, void* _data, size_t _step) + : flags((type & TYPE_MASK)), rows(_rows), cols(_cols), data((uchar*)_data), step(_step == AUTO_STEP ? detail::default_step(type, _cols) : _step) + {} + + MatHeader(const std::vector &_dims, int type, void* _data) + : flags((type & TYPE_MASK)), data((uchar*)_data), step(0), dims(_dims) + {} + + MatHeader(const MatHeader& ) = default; + MatHeader(MatHeader&& src) : MatHeader(src) // reuse copy constructor here + { + MatHeader empty; //give it a name to call copy(not move) assignment below + src = empty; + } + MatHeader& operator=(const MatHeader& ) = default; + MatHeader& operator=(MatHeader&& src) + { + *this = src; //calling a copy assignment here, not move one + MatHeader empty; //give it a name to call copy(not move) assignment below + src = empty; + return *this; + } + /*! includes several bit-fields: + - depth + - number of channels + */ + int flags = 0; + + //! the number of rows and columns or (-1, -1) when the matrix has more than 2 dimensions + int rows = 0, cols = 0; + //! pointer to the data + uchar* data = nullptr; + size_t step = 0; + //! dimensions (ND-case) + std::vector dims; + }; + } // namespace detail + //concise version of cv::Mat suitable for GAPI needs (used when no dependence on OpenCV is required) + class Mat : public detail::MatHeader{ + public: + + Mat() = default; + + /** @overload + @param _rows Number of rows in a 2D array. + @param _cols Number of columns in a 2D array. + @param _type Array type. Use CV_8UC1, ..., CV_64FC4 to create 1-4 channel matrices, or + CV_8UC(n), ..., CV_64FC(n) to create multi-channel (up to CV_CN_MAX channels) matrices. + @param _data Pointer to the user data. Matrix constructors that take data and step parameters do not + allocate matrix data. Instead, they just initialize the matrix header that points to the specified + data, which means that no data is copied. This operation is very efficient and can be used to + process external data using OpenCV functions. The external data is not automatically deallocated, so + you should take care of it. + @param _step Number of bytes each matrix row occupies. The value should include the padding bytes at + the end of each row, if any. If the parameter is missing (set to AUTO_STEP ), no padding is assumed + and the actual step is calculated as cols*elemSize(). See Mat::elemSize. + */ + Mat(int _rows, int _cols, int _type, void* _data, size_t _step = AUTO_STEP) + : MatHeader (_rows, _cols, _type, _data, _step) + {} + + Mat(const std::vector &_dims, int _type, void* _data) + : MatHeader (_dims, _type, _data) + {} + + Mat(std::vector &&_dims, int _type, void* _data) + : MatHeader (std::move(_dims), _type, _data) + {} + + Mat(Mat const& src, const Rect& roi ) + : Mat(src) + { + rows = roi.height; + cols = roi.width; + data = ptr(roi.y, roi.x); + } + + Mat(Mat const& ) = default; + Mat(Mat&& ) = default; + + Mat& operator=(Mat const& ) = default; + Mat& operator=(Mat&& ) = default; + + /** @brief Sets all or some of the array elements to the specified value. + @param s Assigned scalar converted to the actual array type. + */ + Mat& operator = (const Scalar& s) + { + constexpr unsigned max_channels = 4; //Scalar can't fit more than 4 + using func_p_t = void (*)(void*, int, Scalar const&); + using detail::assign_row; + #define TABLE_ENTRY(type) {assign_row, assign_row, assign_row, assign_row} + static constexpr func_p_t func_tbl[][max_channels] = { + TABLE_ENTRY(uchar), + TABLE_ENTRY(schar), + TABLE_ENTRY(ushort), + TABLE_ENTRY(short), + TABLE_ENTRY(int), + TABLE_ENTRY(float), + TABLE_ENTRY(double) + }; + #undef TABLE_ENTRY + + static_assert(CV_8U == 0 && CV_8S == 1 && CV_16U == 2 && CV_16S == 3 + && CV_32S == 4 && CV_32F == 5 && CV_64F == 6, + "OCV type ids used as indexes to array, thus exact numbers are important!" + ); + + const auto depth = static_cast(this->depth()); + GAPI_Assert(depth < sizeof(func_tbl)/sizeof(func_tbl[0])); + + if (dims.empty()) + { + const auto channels = static_cast(this->channels()); + GAPI_Assert(channels <= max_channels); + + auto* f = func_tbl[depth][channels - 1]; + for (int r = 0; r < rows; ++r) + { + (*f)(static_cast(ptr(r)), cols, s ); + } + } + else + { + auto* f = func_tbl[depth][0]; + // FIXME: better to refactor assign_row to use std::size_t by default + (*f)(static_cast(data), static_cast(total()), s); + } + return *this; + } + + /** @brief Returns the matrix element size in bytes. + + The method returns the matrix element size in bytes. For example, if the matrix type is CV_16SC3 , + the method returns 3\*sizeof(short) or 6. + */ + size_t elemSize() const + { + return CV_ELEM_SIZE(type()); + } + /** @brief Returns the type of a matrix element. + + The method returns a matrix element type. This is an identifier compatible with the CvMat type + system, like CV_16SC3 or 16-bit signed 3-channel array, and so on. + */ + int type() const {return CV_MAT_TYPE(flags);} + + /** @brief Returns the depth of a matrix element. + + The method returns the identifier of the matrix element depth (the type of each individual channel). + For example, for a 16-bit signed element array, the method returns CV_16S . A complete list of + matrix types contains the following values: + - CV_8U - 8-bit unsigned integers ( 0..255 ) + - CV_8S - 8-bit signed integers ( -128..127 ) + - CV_16U - 16-bit unsigned integers ( 0..65535 ) + - CV_16S - 16-bit signed integers ( -32768..32767 ) + - CV_32S - 32-bit signed integers ( -2147483648..2147483647 ) + - CV_32F - 32-bit floating-point numbers ( -FLT_MAX..FLT_MAX, INF, NAN ) + - CV_64F - 64-bit floating-point numbers ( -DBL_MAX..DBL_MAX, INF, NAN ) + */ + int depth() const {return CV_MAT_DEPTH(flags);} + + /** @brief Returns the number of matrix channels. + + The method returns the number of matrix channels. + If matrix is N-dimensional, -1 is returned. + */ + int channels() const {return dims.empty() ? CV_MAT_CN(flags) : -1;} + + /** + @param _rows New number of rows. + @param _cols New number of columns. + @param _type New matrix type. + */ + void create(int _rows, int _cols, int _type) + { + create(Size{_cols, _rows}, _type); + } + /** @overload + @param _size Alternative new matrix size specification: Size(cols, rows) + @param _type New matrix type. + */ + void create(Size _size, int _type) + { + GAPI_Assert(_size.height >= 0 && _size.width >= 0); + if (_size != Size{cols, rows} ) + { + Mat tmp{_size.height, _size.width, _type, nullptr}; + tmp.memory.reset(new uchar[ tmp.step * tmp.rows], [](uchar * p){delete[] p;}); + tmp.data = tmp.memory.get(); + + *this = std::move(tmp); + } + } + + void create(const std::vector &_dims, int _type) + { + // FIXME: make a proper reallocation-on-demands + // WARNING: no tensor views, so no strides + Mat tmp{_dims, _type, nullptr}; + // FIXME: this accumulate duplicates a lot + const auto sz = std::accumulate(_dims.begin(), _dims.end(), 1, std::multiplies()); + tmp.memory.reset(new uchar[CV_ELEM_SIZE(_type)*sz], [](uchar * p){delete[] p;}); + tmp.data = tmp.memory.get(); + *this = std::move(tmp); + } + + /** @brief Creates a full copy of the matrix and the underlying data. + + The method creates a full copy of the matrix. The original step[] is not taken into account. + So, the copy has a continuous buffer occupying total() * elemSize() bytes. + */ + Mat clone() const + { + Mat m; + copyTo(m); + return m; + } + + /** @brief Copies the matrix to another one. + + The method copies the matrix data to another matrix. Before copying the data, the method invokes : + @code + m.create(this->size(), this->type()); + @endcode + so that the destination matrix is reallocated if needed. While m.copyTo(m); works flawlessly, the + function does not handle the case of a partial overlap between the source and the destination + matrices. + */ + void copyTo(Mat& dst) const + { + if (dims.empty()) + { + dst.create(rows, cols, type()); + for (int r = 0; r < rows; ++r) + { + std::copy_n(ptr(r), detail::default_step(type(),cols), dst.ptr(r)); + } + } + else + { + dst.create(dims, depth()); + std::copy_n(data, total()*elemSize(), data); + } + } + + /** @brief Returns true if the array has no elements. + + The method returns true if Mat::total() is 0 or if Mat::data is NULL. Because of pop_back() and + resize() methods `M.total() == 0` does not imply that `M.data == NULL`. + */ + bool empty() const + { + return data == 0 || total() == 0; + } + + /** @brief Returns the total number of array elements. + + The method returns the number of array elements (a number of pixels if the array represents an + image). + */ + size_t total() const + { + return dims.empty() + ? (static_cast(rows) * cols) + : std::accumulate(dims.begin(), dims.end(), static_cast(1), std::multiplies()); + } + + /** @overload + @param roi Extracted submatrix specified as a rectangle. + */ + Mat operator()( const Rect& roi ) const + { + return Mat{*this, roi}; + } + + + /** @brief Returns a pointer to the specified matrix row. + + The methods return `uchar*` or typed pointer to the specified matrix row. See the sample in + Mat::isContinuous to know how to use these methods. + @param row Index along the dimension 0 + @param col Index along the dimension 1 + */ + uchar* ptr(int row, int col = 0) + { + return const_cast(const_cast(this)->ptr(row,col)); + } + /** @overload */ + const uchar* ptr(int row, int col = 0) const + { + return data + step * row + CV_ELEM_SIZE(type()) * col; + } + + + private: + //actual memory allocated for storage, or nullptr if object is non owning view to over memory + std::shared_ptr memory; + }; + +} //namespace own +} //namespace gapi +} //namespace cv + +#endif /* OPENCV_GAPI_OWN_MAT_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp index e068543e8c..74eaecf57e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/saturate.hpp @@ -1,83 +1,83 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_OWN_SATURATE_HPP -#define OPENCV_GAPI_OWN_SATURATE_HPP - -#include - -#include - -#include -#include - -namespace cv { namespace gapi { namespace own { -//----------------------------- -// -// Numeric cast with saturation -// -//----------------------------- - -template::value && - std::is_integral::value && - std::is_integral::value> > -static CV_ALWAYS_INLINE DST saturate(SRC x) -{ - if (sizeof(DST) > sizeof(SRC)) - return static_cast(x); - - // compiler must recognize this saturation, - // so compile saturate(a + b) with adds - // instruction (e.g.: _mm_adds_epi16 if x86) - return x < std::numeric_limits::min()? - std::numeric_limits::min(): - x > std::numeric_limits::max()? - std::numeric_limits::max(): - static_cast(x); -} -template -static CV_ALWAYS_INLINE T saturate(T x) -{ - return x; -} - -template::value, bool> = true > -static CV_ALWAYS_INLINE DST saturate(SRC x, R) -{ - return static_cast(x); -} -template::value && - std::is_integral::value , bool> = true > -static CV_ALWAYS_INLINE DST saturate(SRC x, R) -{ - return saturate(x); -} -// Note, that OpenCV rounds differently: -// - like std::round() for add, subtract -// - like std::rint() for multiply, divide -template::value && - std::is_floating_point::value, bool> = true > -static CV_ALWAYS_INLINE DST saturate(SRC x, R round) -{ - int ix = static_cast(round(x)); - return saturate(ix); -} - -// explicit suffix 'd' for double type -inline double ceild(double x) { return ceil(x); } -inline double floord(double x) { return floor(x); } -inline double roundd(double x) { return round(x); } -inline double rintd(double x) { return rint(x); } - -} //namespace own -} //namespace gapi -} //namespace cv -#endif /* OPENCV_GAPI_OWN_SATURATE_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_OWN_SATURATE_HPP +#define OPENCV_GAPI_OWN_SATURATE_HPP + +#include + +#include + +#include +#include + +namespace cv { namespace gapi { namespace own { +//----------------------------- +// +// Numeric cast with saturation +// +//----------------------------- + +template::value && + std::is_integral::value && + std::is_integral::value> > +static CV_ALWAYS_INLINE DST saturate(SRC x) +{ + if (sizeof(DST) > sizeof(SRC)) + return static_cast(x); + + // compiler must recognize this saturation, + // so compile saturate(a + b) with adds + // instruction (e.g.: _mm_adds_epi16 if x86) + return x < std::numeric_limits::min()? + std::numeric_limits::min(): + x > std::numeric_limits::max()? + std::numeric_limits::max(): + static_cast(x); +} +template +static CV_ALWAYS_INLINE T saturate(T x) +{ + return x; +} + +template::value, bool> = true > +static CV_ALWAYS_INLINE DST saturate(SRC x, R) +{ + return static_cast(x); +} +template::value && + std::is_integral::value , bool> = true > +static CV_ALWAYS_INLINE DST saturate(SRC x, R) +{ + return saturate(x); +} +// Note, that OpenCV rounds differently: +// - like std::round() for add, subtract +// - like std::rint() for multiply, divide +template::value && + std::is_floating_point::value, bool> = true > +static CV_ALWAYS_INLINE DST saturate(SRC x, R round) +{ + int ix = static_cast(round(x)); + return saturate(ix); +} + +// explicit suffix 'd' for double type +inline double ceild(double x) { return ceil(x); } +inline double floord(double x) { return floor(x); } +inline double roundd(double x) { return round(x); } +inline double rintd(double x) { return rint(x); } + +} //namespace own +} //namespace gapi +} //namespace cv +#endif /* OPENCV_GAPI_OWN_SATURATE_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp index 02da06ca7a..3b107befcc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/scalar.hpp @@ -1,47 +1,47 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_GAPI_OWN_SCALAR_HPP -#define OPENCV_GAPI_GAPI_OWN_SCALAR_HPP - -#include - -namespace cv -{ -namespace gapi -{ -namespace own -{ - -class GAPI_EXPORTS Scalar -{ -public: - Scalar() = default; - explicit Scalar(double v0) { val[0] = v0; } - Scalar(double v0, double v1, double v2 = 0, double v3 = 0) - : val{v0, v1, v2, v3} - { - } - - const double& operator[](int i) const { return val[i]; } - double& operator[](int i) { return val[i]; } - - static Scalar all(double v0) { return Scalar(v0, v0, v0, v0); } - - double val[4] = {0}; -}; - -inline bool operator==(const Scalar& lhs, const Scalar& rhs) -{ - return std::equal(std::begin(lhs.val), std::end(lhs.val), std::begin(rhs.val)); -} - -} // namespace own -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GAPI_OWN_SCALAR_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_GAPI_OWN_SCALAR_HPP +#define OPENCV_GAPI_GAPI_OWN_SCALAR_HPP + +#include + +namespace cv +{ +namespace gapi +{ +namespace own +{ + +class GAPI_EXPORTS Scalar +{ +public: + Scalar() = default; + explicit Scalar(double v0) { val[0] = v0; } + Scalar(double v0, double v1, double v2 = 0, double v3 = 0) + : val{v0, v1, v2, v3} + { + } + + const double& operator[](int i) const { return val[i]; } + double& operator[](int i) { return val[i]; } + + static Scalar all(double v0) { return Scalar(v0, v0, v0, v0); } + + double val[4] = {0}; +}; + +inline bool operator==(const Scalar& lhs, const Scalar& rhs) +{ + return std::equal(std::begin(lhs.val), std::end(lhs.val), std::begin(rhs.val)); +} + +} // namespace own +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GAPI_OWN_SCALAR_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp index ef01056db1..211b5c85ff 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/own/types.hpp @@ -1,162 +1,162 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_TYPES_HPP -#define OPENCV_GAPI_TYPES_HPP - -#include // std::max, std::min -#include - -namespace cv -{ -namespace gapi -{ - -/** - * @brief This namespace contains G-API own data structures used in - * its standalone mode build. - */ -namespace own -{ - -class Point -{ -public: - Point() = default; - Point(int _x, int _y) : x(_x), y(_y) {} - - int x = 0; - int y = 0; -}; - -class Point2f -{ -public: - Point2f() = default; - Point2f(float _x, float _y) : x(_x), y(_y) {} - - float x = 0.f; - float y = 0.f; -}; - -class Point3f -{ -public: - Point3f() = default; - Point3f(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} - - float x = 0.f; - float y = 0.f; - float z = 0.f; -}; - -class Rect -{ -public: - Rect() = default; - Rect(int _x, int _y, int _width, int _height) : x(_x), y(_y), width(_width), height(_height) {} -#if !defined(GAPI_STANDALONE) - Rect(const cv::Rect& other) : x(other.x), y(other.y), width(other.width), height(other.height) {} - inline Rect& operator=(const cv::Rect& other) - { - x = other.x; - y = other.x; - width = other.width; - height = other.height; - return *this; - } -#endif // !defined(GAPI_STANDALONE) - - int x = 0; //!< x coordinate of the top-left corner - int y = 0; //!< y coordinate of the top-left corner - int width = 0; //!< width of the rectangle - int height = 0; //!< height of the rectangle -}; - -inline bool operator==(const Rect& lhs, const Rect& rhs) -{ - return lhs.x == rhs.x && lhs.y == rhs.y && lhs.width == rhs.width && lhs.height == rhs.height; -} - -inline bool operator!=(const Rect& lhs, const Rect& rhs) -{ - return !(lhs == rhs); -} - -inline Rect& operator&=(Rect& lhs, const Rect& rhs) -{ - int x1 = std::max(lhs.x, rhs.x); - int y1 = std::max(lhs.y, rhs.y); - lhs.width = std::min(lhs.x + lhs.width, rhs.x + rhs.width) - x1; - lhs.height = std::min(lhs.y + lhs.height, rhs.y + rhs.height) - y1; - lhs.x = x1; - lhs.y = y1; - if( lhs.width <= 0 || lhs.height <= 0 ) - lhs = Rect(); - return lhs; -} - -inline Rect operator&(const Rect& lhs, const Rect& rhs) -{ - Rect result = lhs; - return result &= rhs; -} - -inline std::ostream& operator<<(std::ostream& o, const Rect& rect) -{ - return o << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; -} - -class Size -{ -public: - Size() = default; - Size(int _width, int _height) : width(_width), height(_height) {} -#if !defined(GAPI_STANDALONE) - Size(const cv::Size& other) : width(other.width), height(other.height) {} - inline Size& operator=(const cv::Size& rhs) - { - width = rhs.width; - height = rhs.height; - return *this; - } -#endif // !defined(GAPI_STANDALONE) - - int width = 0; - int height = 0; -}; - -inline Size& operator+=(Size& lhs, const Size& rhs) -{ - lhs.width += rhs.width; - lhs.height += rhs.height; - return lhs; -} - -inline bool operator==(const Size& lhs, const Size& rhs) -{ - return lhs.width == rhs.width && lhs.height == rhs.height; -} - -inline bool operator!=(const Size& lhs, const Size& rhs) -{ - return !(lhs == rhs); -} - - -inline std::ostream& operator<<(std::ostream& o, const Size& s) -{ - o << "[" << s.width << " x " << s.height << "]"; - return o; -} - -struct VoidType {}; -} // namespace own -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_TYPES_HPP +#define OPENCV_GAPI_TYPES_HPP + +#include // std::max, std::min +#include + +namespace cv +{ +namespace gapi +{ + +/** + * @brief This namespace contains G-API own data structures used in + * its standalone mode build. + */ +namespace own +{ + +class Point +{ +public: + Point() = default; + Point(int _x, int _y) : x(_x), y(_y) {} + + int x = 0; + int y = 0; +}; + +class Point2f +{ +public: + Point2f() = default; + Point2f(float _x, float _y) : x(_x), y(_y) {} + + float x = 0.f; + float y = 0.f; +}; + +class Point3f +{ +public: + Point3f() = default; + Point3f(float _x, float _y, float _z) : x(_x), y(_y), z(_z) {} + + float x = 0.f; + float y = 0.f; + float z = 0.f; +}; + +class Rect +{ +public: + Rect() = default; + Rect(int _x, int _y, int _width, int _height) : x(_x), y(_y), width(_width), height(_height) {} +#if !defined(GAPI_STANDALONE) + Rect(const cv::Rect& other) : x(other.x), y(other.y), width(other.width), height(other.height) {} + inline Rect& operator=(const cv::Rect& other) + { + x = other.x; + y = other.x; + width = other.width; + height = other.height; + return *this; + } +#endif // !defined(GAPI_STANDALONE) + + int x = 0; //!< x coordinate of the top-left corner + int y = 0; //!< y coordinate of the top-left corner + int width = 0; //!< width of the rectangle + int height = 0; //!< height of the rectangle +}; + +inline bool operator==(const Rect& lhs, const Rect& rhs) +{ + return lhs.x == rhs.x && lhs.y == rhs.y && lhs.width == rhs.width && lhs.height == rhs.height; +} + +inline bool operator!=(const Rect& lhs, const Rect& rhs) +{ + return !(lhs == rhs); +} + +inline Rect& operator&=(Rect& lhs, const Rect& rhs) +{ + int x1 = std::max(lhs.x, rhs.x); + int y1 = std::max(lhs.y, rhs.y); + lhs.width = std::min(lhs.x + lhs.width, rhs.x + rhs.width) - x1; + lhs.height = std::min(lhs.y + lhs.height, rhs.y + rhs.height) - y1; + lhs.x = x1; + lhs.y = y1; + if( lhs.width <= 0 || lhs.height <= 0 ) + lhs = Rect(); + return lhs; +} + +inline Rect operator&(const Rect& lhs, const Rect& rhs) +{ + Rect result = lhs; + return result &= rhs; +} + +inline std::ostream& operator<<(std::ostream& o, const Rect& rect) +{ + return o << "[" << rect.width << " x " << rect.height << " from (" << rect.x << ", " << rect.y << ")]"; +} + +class Size +{ +public: + Size() = default; + Size(int _width, int _height) : width(_width), height(_height) {} +#if !defined(GAPI_STANDALONE) + Size(const cv::Size& other) : width(other.width), height(other.height) {} + inline Size& operator=(const cv::Size& rhs) + { + width = rhs.width; + height = rhs.height; + return *this; + } +#endif // !defined(GAPI_STANDALONE) + + int width = 0; + int height = 0; +}; + +inline Size& operator+=(Size& lhs, const Size& rhs) +{ + lhs.width += rhs.width; + lhs.height += rhs.height; + return lhs; +} + +inline bool operator==(const Size& lhs, const Size& rhs) +{ + return lhs.width == rhs.width && lhs.height == rhs.height; +} + +inline bool operator!=(const Size& lhs, const Size& rhs) +{ + return !(lhs == rhs); +} + + +inline std::ostream& operator<<(std::ostream& o, const Size& s) +{ + o << "[" << s.width << " x " << s.height << "]"; + return o; +} + +struct VoidType {}; +} // namespace own +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp index 5a5ca46a0d..20e8812b3a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/core.hpp @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - - -#ifndef OPENCV_GAPI_PLAIDML_CORE_HPP -#define OPENCV_GAPI_PLAIDML_CORE_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { namespace gapi { namespace core { namespace plaidml { - -GAPI_EXPORTS cv::GKernelPackage kernels(); - -}}}} - -#endif // OPENCV_GAPI_PLAIDML_CORE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + + +#ifndef OPENCV_GAPI_PLAIDML_CORE_HPP +#define OPENCV_GAPI_PLAIDML_CORE_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { namespace gapi { namespace core { namespace plaidml { + +GAPI_EXPORTS cv::GKernelPackage kernels(); + +}}}} + +#endif // OPENCV_GAPI_PLAIDML_CORE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp index f7e0c98e37..e22ecc7211 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/gplaidmlkernel.hpp @@ -1,140 +1,140 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation -// - - -#ifndef OPENCV_GAPI_GPLAIDMLKERNEL_HPP -#define OPENCV_GAPI_GPLAIDMLKERNEL_HPP - -#include -#include - -namespace plaidml -{ -namespace edsl -{ - class Tensor; -} // namespace edsl -} // namespace plaidml - -namespace cv -{ -namespace gapi -{ -namespace plaidml -{ - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -} // namespace plaidml -} // namespace gapi - -struct GPlaidMLContext -{ - // Generic accessor API - template - const T& inArg(int input) { return m_args.at(input).get(); } - - // Syntax sugar - const plaidml::edsl::Tensor& inTensor(int input) - { - return inArg(input); - } - - plaidml::edsl::Tensor& outTensor(int output) - { - return *(m_results.at(output).get()); - } - - std::vector m_args; - std::unordered_map m_results; -}; - -class GAPI_EXPORTS GPlaidMLKernel -{ -public: - using F = std::function; - - GPlaidMLKernel() = default; - explicit GPlaidMLKernel(const F& f) : m_f(f) {} - - void apply(GPlaidMLContext &ctx) const - { - GAPI_Assert(m_f); - m_f(ctx); - } - -protected: - F m_f; -}; - - -namespace detail -{ - -template struct plaidml_get_in; -template<> struct plaidml_get_in -{ - static const plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) - { - return ctx.inTensor(idx); - } -}; - -template struct plaidml_get_in -{ - static T get(GPlaidMLContext &ctx, int idx) { return ctx.inArg(idx); } -}; - -template struct plaidml_get_out; -template<> struct plaidml_get_out -{ - static plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) - { - return ctx.outTensor(idx); - } -}; - -template -struct PlaidMLCallHelper; - -template -struct PlaidMLCallHelper, std::tuple > -{ - template - static void call_impl(GPlaidMLContext &ctx, detail::Seq, detail::Seq) - { - Impl::run(plaidml_get_in::get(ctx, IIs)..., plaidml_get_out::get(ctx, OIs)...); - } - - static void call(GPlaidMLContext& ctx) - { - call_impl(ctx, - typename detail::MkSeq::type(), - typename detail::MkSeq::type()); - } -}; - -} // namespace detail - -template -class GPlaidMLKernelImpl: public cv::detail::PlaidMLCallHelper, - public cv::detail::KernelTag -{ - using P = detail::PlaidMLCallHelper; - -public: - using API = K; - - static cv::gapi::GBackend backend() { return cv::gapi::plaidml::backend(); } - static cv::GPlaidMLKernel kernel() { return GPlaidMLKernel(&P::call); } -}; - -#define GAPI_PLAIDML_KERNEL(Name, API) struct Name: public cv::GPlaidMLKernelImpl - -} // namespace cv - -#endif // OPENCV_GAPI_GPLAIDMLKERNEL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation +// + + +#ifndef OPENCV_GAPI_GPLAIDMLKERNEL_HPP +#define OPENCV_GAPI_GPLAIDMLKERNEL_HPP + +#include +#include + +namespace plaidml +{ +namespace edsl +{ + class Tensor; +} // namespace edsl +} // namespace plaidml + +namespace cv +{ +namespace gapi +{ +namespace plaidml +{ + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +} // namespace plaidml +} // namespace gapi + +struct GPlaidMLContext +{ + // Generic accessor API + template + const T& inArg(int input) { return m_args.at(input).get(); } + + // Syntax sugar + const plaidml::edsl::Tensor& inTensor(int input) + { + return inArg(input); + } + + plaidml::edsl::Tensor& outTensor(int output) + { + return *(m_results.at(output).get()); + } + + std::vector m_args; + std::unordered_map m_results; +}; + +class GAPI_EXPORTS GPlaidMLKernel +{ +public: + using F = std::function; + + GPlaidMLKernel() = default; + explicit GPlaidMLKernel(const F& f) : m_f(f) {} + + void apply(GPlaidMLContext &ctx) const + { + GAPI_Assert(m_f); + m_f(ctx); + } + +protected: + F m_f; +}; + + +namespace detail +{ + +template struct plaidml_get_in; +template<> struct plaidml_get_in +{ + static const plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) + { + return ctx.inTensor(idx); + } +}; + +template struct plaidml_get_in +{ + static T get(GPlaidMLContext &ctx, int idx) { return ctx.inArg(idx); } +}; + +template struct plaidml_get_out; +template<> struct plaidml_get_out +{ + static plaidml::edsl::Tensor& get(GPlaidMLContext& ctx, int idx) + { + return ctx.outTensor(idx); + } +}; + +template +struct PlaidMLCallHelper; + +template +struct PlaidMLCallHelper, std::tuple > +{ + template + static void call_impl(GPlaidMLContext &ctx, detail::Seq, detail::Seq) + { + Impl::run(plaidml_get_in::get(ctx, IIs)..., plaidml_get_out::get(ctx, OIs)...); + } + + static void call(GPlaidMLContext& ctx) + { + call_impl(ctx, + typename detail::MkSeq::type(), + typename detail::MkSeq::type()); + } +}; + +} // namespace detail + +template +class GPlaidMLKernelImpl: public cv::detail::PlaidMLCallHelper, + public cv::detail::KernelTag +{ + using P = detail::PlaidMLCallHelper; + +public: + using API = K; + + static cv::gapi::GBackend backend() { return cv::gapi::plaidml::backend(); } + static cv::GPlaidMLKernel kernel() { return GPlaidMLKernel(&P::call); } +}; + +#define GAPI_PLAIDML_KERNEL(Name, API) struct Name: public cv::GPlaidMLKernelImpl + +} // namespace cv + +#endif // OPENCV_GAPI_GPLAIDMLKERNEL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp index 67f7a59e7d..3207a8cb2e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/plaidml/plaidml.hpp @@ -1,53 +1,53 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - - -#ifndef OPENCV_GAPI_PLAIDML_PLAIDML_HPP -#define OPENCV_GAPI_PLAIDML_PLAIDML_HPP - -#include -#include // CompileArgTag - -namespace cv -{ -namespace gapi -{ - -/** - * @brief This namespace contains G-API PlaidML backend functions, - * structures, and symbols. - */ -namespace plaidml -{ - -/** \addtogroup gapi_compile_args - * @{ - */ -/** - * @brief This structure represents the basic parameters for the experimental - * PlaidML backend. - */ -struct config -{ - std::string dev_id; //!< Device ID. Refer to PlaidML documentation for details. - std::string trg_id; //!< Target ID. Refer to PlaidML documentation for details. -}; -/** @} gapi_compile_args */ - -} // namespace plaidml -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.plaidml.config"; } - }; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_PLAIDML_PLAIDML_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + + +#ifndef OPENCV_GAPI_PLAIDML_PLAIDML_HPP +#define OPENCV_GAPI_PLAIDML_PLAIDML_HPP + +#include +#include // CompileArgTag + +namespace cv +{ +namespace gapi +{ + +/** + * @brief This namespace contains G-API PlaidML backend functions, + * structures, and symbols. + */ +namespace plaidml +{ + +/** \addtogroup gapi_compile_args + * @{ + */ +/** + * @brief This structure represents the basic parameters for the experimental + * PlaidML backend. + */ +struct config +{ + std::string dev_id; //!< Device ID. Refer to PlaidML documentation for details. + std::string trg_id; //!< Target ID. Refer to PlaidML documentation for details. +}; +/** @} gapi_compile_args */ + +} // namespace plaidml +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.plaidml.config"; } + }; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_PLAIDML_PLAIDML_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp index 00d15f849c..1857a938d5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/python/python.hpp @@ -1,71 +1,71 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - - -#ifndef OPENCV_GAPI_PYTHON_API_HPP -#define OPENCV_GAPI_PYTHON_API_HPP - -#include // GKernelPackage -#include // GAPI_EXPORTS - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API Python backend functions, - * structures, and symbols. - * - * This functionality is required to enable G-API custom operations - * and kernels when using G-API from Python, no need to use it in the - * C++ form. - */ -namespace python { - -GAPI_EXPORTS cv::gapi::GBackend backend(); - -struct GPythonContext -{ - const cv::GArgs &ins; - const cv::GMetaArgs &in_metas; - const cv::GTypesInfo &out_info; - - cv::optional m_state; -}; - -using Impl = std::function; -using Setup = std::function; - -class GAPI_EXPORTS GPythonKernel -{ -public: - GPythonKernel() = default; - GPythonKernel(Impl run, Setup setup); - - Impl run; - Setup setup = nullptr; - bool is_stateful = false; -}; - -class GAPI_EXPORTS GPythonFunctor : public cv::gapi::GFunctor -{ -public: - using Meta = cv::GKernel::M; - - GPythonFunctor(const char* id, const Meta& meta, const Impl& impl, - const Setup& setup = nullptr); - - GKernelImpl impl() const override; - gapi::GBackend backend() const override; - -private: - GKernelImpl impl_; -}; - -} // namespace python -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_PYTHON_API_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + + +#ifndef OPENCV_GAPI_PYTHON_API_HPP +#define OPENCV_GAPI_PYTHON_API_HPP + +#include // GKernelPackage +#include // GAPI_EXPORTS + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API Python backend functions, + * structures, and symbols. + * + * This functionality is required to enable G-API custom operations + * and kernels when using G-API from Python, no need to use it in the + * C++ form. + */ +namespace python { + +GAPI_EXPORTS cv::gapi::GBackend backend(); + +struct GPythonContext +{ + const cv::GArgs &ins; + const cv::GMetaArgs &in_metas; + const cv::GTypesInfo &out_info; + + cv::optional m_state; +}; + +using Impl = std::function; +using Setup = std::function; + +class GAPI_EXPORTS GPythonKernel +{ +public: + GPythonKernel() = default; + GPythonKernel(Impl run, Setup setup); + + Impl run; + Setup setup = nullptr; + bool is_stateful = false; +}; + +class GAPI_EXPORTS GPythonFunctor : public cv::gapi::GFunctor +{ +public: + using Meta = cv::GKernel::M; + + GPythonFunctor(const char* id, const Meta& meta, const Impl& impl, + const Setup& setup = nullptr); + + GKernelImpl impl() const override; + gapi::GBackend backend() const override; + +private: + GKernelImpl impl_; +}; + +} // namespace python +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_PYTHON_API_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp index 8360e30698..52e55b0d80 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/render.hpp @@ -1,14 +1,14 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_RENDER_ROOT_HPP -#define OPENCV_GAPI_RENDER_ROOT_HPP - -// This file is just a shortcut to render/render.hpp - -#include - -#endif // OPENCV_GAPI_RENDER_ROOT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_RENDER_ROOT_HPP +#define OPENCV_GAPI_RENDER_ROOT_HPP + +// This file is just a shortcut to render/render.hpp + +#include + +#endif // OPENCV_GAPI_RENDER_ROOT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp index 5da8d80244..8d93a6efc0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render.hpp @@ -1,196 +1,196 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2020 Intel Corporation - - -#ifndef OPENCV_GAPI_RENDER_HPP -#define OPENCV_GAPI_RENDER_HPP - -#include - -#include - -/** \defgroup gapi_draw G-API Drawing and composition functionality - * @{ - * - * @brief Functions for in-graph drawing. - * - * @note This is a Work in Progress functionality and APIs may - * change in the future releases. - * - * G-API can do some in-graph drawing with a generic operations and a - * set of [rendering primitives](@ref gapi_draw_prims). - * In contrast with traditional OpenCV, in G-API user need to form a - * *rendering list* of primitives to draw. This list can be built - * manually or generated within a graph. This list is passed to - * [special operations or functions](@ref gapi_draw_api) where all - * primitives are interpreted and applied to the image. - * - * For example, in a complex pipeline a list of detected objects - * can be translated in-graph to a list of cv::gapi::wip::draw::Rect - * primitives to highlight those with bounding boxes, or a list of - * detected faces can be translated in-graph to a list of - * cv::gapi::wip::draw::Mosaic primitives to hide sensitive content - * or protect privacy. - * - * Like any other operations, rendering in G-API can be reimplemented - * by different backends. Currently only an OpenCV-based backend is - * available. - * - * In addition to the graph-level operations, there are also regular - * (immediate) OpenCV-like functions are available -- see - * cv::gapi::wip::draw::render(). These functions are just wrappers - * over regular G-API and build the rendering graphs on the fly, so - * take compilation arguments as parameters. - * - * Currently this API is more machine-oriented than human-oriented. - * The main purpose is to translate a set of domain-specific objects - * to a list of primitives to draw. For example, in order to generate - * a picture like this: - * - * ![](modules/gapi/doc/pics/render_example.png) - * - * Rendering list needs to be generated as follows: - * - * @include modules/gapi/samples/draw_example.cpp - * - * @defgroup gapi_draw_prims Drawing primitives - * @defgroup gapi_draw_api Drawing operations and functions - * @} - */ - -namespace cv -{ -namespace gapi -{ -namespace wip -{ -namespace draw -{ - -using GMat2 = std::tuple; -using GMatDesc2 = std::tuple; - -//! @addtogroup gapi_draw_api -//! @{ -/** @brief The function renders on the input image passed drawing primitivies - -@param bgr input image: 8-bit unsigned 3-channel image @ref CV_8UC3. -@param prims vector of drawing primitivies -@param args graph compile time parameters -*/ -void GAPI_EXPORTS_W render(cv::Mat& bgr, - const Prims& prims, - cv::GCompileArgs&& args = {}); - -/** @brief The function renders on two NV12 planes passed drawing primitivies - -@param y_plane input image: 8-bit unsigned 1-channel image @ref CV_8UC1. -@param uv_plane input image: 8-bit unsigned 2-channel image @ref CV_8UC2. -@param prims vector of drawing primitivies -@param args graph compile time parameters -*/ -void GAPI_EXPORTS_W render(cv::Mat& y_plane, - cv::Mat& uv_plane, - const Prims& prims, - cv::GCompileArgs&& args = {}); - -/** @brief The function renders on the input media frame passed drawing primitivies - -@param frame input Media Frame : @ref cv::MediaFrame. -@param prims vector of drawing primitivies -@param args graph compile time parameters -*/ -void GAPI_EXPORTS render(cv::MediaFrame& frame, - const Prims& prims, - cv::GCompileArgs&& args = {}); - - -G_TYPED_KERNEL_M(GRenderNV12, )>, "org.opencv.render.nv12") -{ - static GMatDesc2 outMeta(GMatDesc y_plane, GMatDesc uv_plane, GArrayDesc) - { - return std::make_tuple(y_plane, uv_plane); - } -}; - -G_TYPED_KERNEL(GRenderBGR, )>, "org.opencv.render.bgr") -{ - static GMatDesc outMeta(GMatDesc bgr, GArrayDesc) - { - return bgr; - } -}; - -G_TYPED_KERNEL(GRenderFrame, )>, "org.opencv.render.frame") -{ - static GFrameDesc outMeta(GFrameDesc desc, GArrayDesc) - { - return desc; - } -}; - -/** @brief Renders on 3 channels input - -Output image must be 8-bit unsigned planar 3-channel image - -@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3 -@param prims draw primitives -*/ -GAPI_EXPORTS_W GMat render3ch(const GMat& src, const GArray& prims); - -/** @brief Renders on two planes - -Output y image must be 8-bit unsigned planar 1-channel image @ref CV_8UC1 -uv image must be 8-bit unsigned planar 2-channel image @ref CV_8UC2 - -@param y input image: 8-bit unsigned 1-channel image @ref CV_8UC1 -@param uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2 -@param prims draw primitives -*/ -GAPI_EXPORTS_W GMat2 renderNV12(const GMat& y, - const GMat& uv, - const GArray& prims); - -/** @brief Renders Media Frame - -Output media frame frame cv::MediaFrame - -@param m_frame input image: cv::MediaFrame @ref cv::MediaFrame -@param prims draw primitives -*/ -GAPI_EXPORTS GFrame renderFrame(const GFrame& m_frame, - const GArray& prims); - -//! @} gapi_draw_api - -} // namespace draw -} // namespace wip - -/** - * @brief This namespace contains G-API CPU rendering backend functions, - * structures, and symbols. See @ref gapi_draw for details. - */ -namespace render -{ -namespace ocv -{ - GAPI_EXPORTS_W cv::GKernelPackage kernels(); - -} // namespace ocv -} // namespace render -} // namespace gapi - -namespace detail -{ - template<> struct CompileArgTag - { - static const char* tag() { return "gapi.freetype_font"; } - }; -} // namespace detail - -} // namespace cv - -#endif // OPENCV_GAPI_RENDER_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2020 Intel Corporation + + +#ifndef OPENCV_GAPI_RENDER_HPP +#define OPENCV_GAPI_RENDER_HPP + +#include + +#include + +/** \defgroup gapi_draw G-API Drawing and composition functionality + * @{ + * + * @brief Functions for in-graph drawing. + * + * @note This is a Work in Progress functionality and APIs may + * change in the future releases. + * + * G-API can do some in-graph drawing with a generic operations and a + * set of [rendering primitives](@ref gapi_draw_prims). + * In contrast with traditional OpenCV, in G-API user need to form a + * *rendering list* of primitives to draw. This list can be built + * manually or generated within a graph. This list is passed to + * [special operations or functions](@ref gapi_draw_api) where all + * primitives are interpreted and applied to the image. + * + * For example, in a complex pipeline a list of detected objects + * can be translated in-graph to a list of cv::gapi::wip::draw::Rect + * primitives to highlight those with bounding boxes, or a list of + * detected faces can be translated in-graph to a list of + * cv::gapi::wip::draw::Mosaic primitives to hide sensitive content + * or protect privacy. + * + * Like any other operations, rendering in G-API can be reimplemented + * by different backends. Currently only an OpenCV-based backend is + * available. + * + * In addition to the graph-level operations, there are also regular + * (immediate) OpenCV-like functions are available -- see + * cv::gapi::wip::draw::render(). These functions are just wrappers + * over regular G-API and build the rendering graphs on the fly, so + * take compilation arguments as parameters. + * + * Currently this API is more machine-oriented than human-oriented. + * The main purpose is to translate a set of domain-specific objects + * to a list of primitives to draw. For example, in order to generate + * a picture like this: + * + * ![](modules/gapi/doc/pics/render_example.png) + * + * Rendering list needs to be generated as follows: + * + * @include modules/gapi/samples/draw_example.cpp + * + * @defgroup gapi_draw_prims Drawing primitives + * @defgroup gapi_draw_api Drawing operations and functions + * @} + */ + +namespace cv +{ +namespace gapi +{ +namespace wip +{ +namespace draw +{ + +using GMat2 = std::tuple; +using GMatDesc2 = std::tuple; + +//! @addtogroup gapi_draw_api +//! @{ +/** @brief The function renders on the input image passed drawing primitivies + +@param bgr input image: 8-bit unsigned 3-channel image @ref CV_8UC3. +@param prims vector of drawing primitivies +@param args graph compile time parameters +*/ +void GAPI_EXPORTS_W render(cv::Mat& bgr, + const Prims& prims, + cv::GCompileArgs&& args = {}); + +/** @brief The function renders on two NV12 planes passed drawing primitivies + +@param y_plane input image: 8-bit unsigned 1-channel image @ref CV_8UC1. +@param uv_plane input image: 8-bit unsigned 2-channel image @ref CV_8UC2. +@param prims vector of drawing primitivies +@param args graph compile time parameters +*/ +void GAPI_EXPORTS_W render(cv::Mat& y_plane, + cv::Mat& uv_plane, + const Prims& prims, + cv::GCompileArgs&& args = {}); + +/** @brief The function renders on the input media frame passed drawing primitivies + +@param frame input Media Frame : @ref cv::MediaFrame. +@param prims vector of drawing primitivies +@param args graph compile time parameters +*/ +void GAPI_EXPORTS render(cv::MediaFrame& frame, + const Prims& prims, + cv::GCompileArgs&& args = {}); + + +G_TYPED_KERNEL_M(GRenderNV12, )>, "org.opencv.render.nv12") +{ + static GMatDesc2 outMeta(GMatDesc y_plane, GMatDesc uv_plane, GArrayDesc) + { + return std::make_tuple(y_plane, uv_plane); + } +}; + +G_TYPED_KERNEL(GRenderBGR, )>, "org.opencv.render.bgr") +{ + static GMatDesc outMeta(GMatDesc bgr, GArrayDesc) + { + return bgr; + } +}; + +G_TYPED_KERNEL(GRenderFrame, )>, "org.opencv.render.frame") +{ + static GFrameDesc outMeta(GFrameDesc desc, GArrayDesc) + { + return desc; + } +}; + +/** @brief Renders on 3 channels input + +Output image must be 8-bit unsigned planar 3-channel image + +@param src input image: 8-bit unsigned 3-channel image @ref CV_8UC3 +@param prims draw primitives +*/ +GAPI_EXPORTS_W GMat render3ch(const GMat& src, const GArray& prims); + +/** @brief Renders on two planes + +Output y image must be 8-bit unsigned planar 1-channel image @ref CV_8UC1 +uv image must be 8-bit unsigned planar 2-channel image @ref CV_8UC2 + +@param y input image: 8-bit unsigned 1-channel image @ref CV_8UC1 +@param uv input image: 8-bit unsigned 2-channel image @ref CV_8UC2 +@param prims draw primitives +*/ +GAPI_EXPORTS_W GMat2 renderNV12(const GMat& y, + const GMat& uv, + const GArray& prims); + +/** @brief Renders Media Frame + +Output media frame frame cv::MediaFrame + +@param m_frame input image: cv::MediaFrame @ref cv::MediaFrame +@param prims draw primitives +*/ +GAPI_EXPORTS GFrame renderFrame(const GFrame& m_frame, + const GArray& prims); + +//! @} gapi_draw_api + +} // namespace draw +} // namespace wip + +/** + * @brief This namespace contains G-API CPU rendering backend functions, + * structures, and symbols. See @ref gapi_draw for details. + */ +namespace render +{ +namespace ocv +{ + GAPI_EXPORTS_W cv::GKernelPackage kernels(); + +} // namespace ocv +} // namespace render +} // namespace gapi + +namespace detail +{ + template<> struct CompileArgTag + { + static const char* tag() { return "gapi.freetype_font"; } + }; +} // namespace detail + +} // namespace cv + +#endif // OPENCV_GAPI_RENDER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp index e892fd2652..6d70e3a877 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/render/render_types.hpp @@ -1,359 +1,359 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_RENDER_TYPES_HPP -#define OPENCV_GAPI_RENDER_TYPES_HPP - -#include -#include - -#include -#include -#include - -namespace cv -{ -namespace gapi -{ -namespace wip -{ -namespace draw -{ - -/** - * @brief This structure specifies which FreeType font to use by FText primitives. - */ -struct freetype_font -{ - /*@{*/ - std::string path; //!< The path to the font file (.ttf) - /*@{*/ -}; - -//! @addtogroup gapi_draw_prims -//! @{ -/** - * @brief This structure represents a text string to draw. - * - * Parameters match cv::putText(). - */ -struct GAPI_EXPORTS_W_SIMPLE Text -{ - /** - * @brief Text constructor - * - * @param text_ The text string to be drawn - * @param org_ The bottom-left corner of the text string in the image - * @param ff_ The font type, see #HersheyFonts - * @param fs_ The font scale factor that is multiplied by the font-specific base size - * @param color_ The text color - * @param thick_ The thickness of the lines used to draw a text - * @param lt_ The line type. See #LineTypes - * @param bottom_left_origin_ When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner - */ - GAPI_WRAP - Text(const std::string& text_, - const cv::Point& org_, - int ff_, - double fs_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - bool bottom_left_origin_ = false) : - text(text_), org(org_), ff(ff_), fs(fs_), - color(color_), thick(thick_), lt(lt_), bottom_left_origin(bottom_left_origin_) - { - } - - GAPI_WRAP - Text() = default; - - /*@{*/ - GAPI_PROP_RW std::string text; //!< The text string to be drawn - GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the text string in the image - GAPI_PROP_RW int ff; //!< The font type, see #HersheyFonts - GAPI_PROP_RW double fs; //!< The font scale factor that is multiplied by the font-specific base size - GAPI_PROP_RW cv::Scalar color; //!< The text color - GAPI_PROP_RW int thick; //!< The thickness of the lines used to draw a text - GAPI_PROP_RW int lt; //!< The line type. See #LineTypes - GAPI_PROP_RW bool bottom_left_origin; //!< When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner - /*@{*/ -}; - -/** - * @brief This structure represents a text string to draw using - * FreeType renderer. - * - * If OpenCV is built without FreeType support, this primitive will - * fail at the execution stage. - */ -struct FText -{ - /** - * @brief FText constructor - * - * @param text_ The text string to be drawn - * @param org_ The bottom-left corner of the text string in the image - * @param fh_ The height of text - * @param color_ The text color - */ - FText(const std::wstring& text_, - const cv::Point& org_, - int fh_, - const cv::Scalar& color_) : - text(text_), org(org_), fh(fh_), color(color_) - { - } - - FText() = default; - - /*@{*/ - std::wstring text; //!< The text string to be drawn - cv::Point org; //!< The bottom-left corner of the text string in the image - int fh; //!< The height of text - cv::Scalar color; //!< The text color - /*@{*/ -}; - -/** - * @brief This structure represents a rectangle to draw. - * - * Parameters match cv::rectangle(). - */ -struct GAPI_EXPORTS_W_SIMPLE Rect -{ - /** - * @brief Rect constructor - * - * @param rect_ Coordinates of the rectangle - * @param color_ The bottom-left corner of the text string in the image - * @param thick_ The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle - * @param lt_ The type of the line. See #LineTypes - * @param shift_ The number of fractional bits in the point coordinates - */ - Rect(const cv::Rect& rect_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - rect(rect_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Rect() = default; - - /*@{*/ - GAPI_PROP_RW cv::Rect rect; //!< Coordinates of the rectangle - GAPI_PROP_RW cv::Scalar color; //!< The rectangle color or brightness (grayscale image) - GAPI_PROP_RW int thick; //!< The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle - GAPI_PROP_RW int lt; //!< The type of the line. See #LineTypes - GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates - /*@{*/ -}; - -/** - * @brief This structure represents a circle to draw. - * - * Parameters match cv::circle(). - */ -struct GAPI_EXPORTS_W_SIMPLE Circle -{ - /** - * @brief Circle constructor - * - * @param center_ The center of the circle - * @param radius_ The radius of the circle - * @param color_ The color of the circle - * @param thick_ The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn - * @param lt_ The Type of the circle boundary. See #LineTypes - * @param shift_ The Number of fractional bits in the coordinates of the center and in the radius value - */ - GAPI_WRAP - Circle(const cv::Point& center_, - int radius_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - center(center_), radius(radius_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Circle() = default; - - /*@{*/ - GAPI_PROP_RW cv::Point center; //!< The center of the circle - GAPI_PROP_RW int radius; //!< The radius of the circle - GAPI_PROP_RW cv::Scalar color; //!< The color of the circle - GAPI_PROP_RW int thick; //!< The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn - GAPI_PROP_RW int lt; //!< The Type of the circle boundary. See #LineTypes - GAPI_PROP_RW int shift; //!< The Number of fractional bits in the coordinates of the center and in the radius value - /*@{*/ -}; - -/** - * @brief This structure represents a line to draw. - * - * Parameters match cv::line(). - */ -struct GAPI_EXPORTS_W_SIMPLE Line -{ - /** - * @brief Line constructor - * - * @param pt1_ The first point of the line segment - * @param pt2_ The second point of the line segment - * @param color_ The line color - * @param thick_ The thickness of line - * @param lt_ The Type of the line. See #LineTypes - * @param shift_ The number of fractional bits in the point coordinates - */ - GAPI_WRAP - Line(const cv::Point& pt1_, - const cv::Point& pt2_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - pt1(pt1_), pt2(pt2_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Line() = default; - - /*@{*/ - GAPI_PROP_RW cv::Point pt1; //!< The first point of the line segment - GAPI_PROP_RW cv::Point pt2; //!< The second point of the line segment - GAPI_PROP_RW cv::Scalar color; //!< The line color - GAPI_PROP_RW int thick; //!< The thickness of line - GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes - GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates - /*@{*/ -}; - -/** - * @brief This structure represents a mosaicing operation. - * - * Mosaicing is a very basic method to obfuscate regions in the image. - */ -struct GAPI_EXPORTS_W_SIMPLE Mosaic -{ - /** - * @brief Mosaic constructor - * - * @param mos_ Coordinates of the mosaic - * @param cellSz_ Cell size (same for X, Y) - * @param decim_ Decimation (0 stands for no decimation) - */ - Mosaic(const cv::Rect& mos_, - int cellSz_, - int decim_) : - mos(mos_), cellSz(cellSz_), decim(decim_) - { - } - - GAPI_WRAP - Mosaic() : cellSz(0), decim(0) {} - - /*@{*/ - GAPI_PROP_RW cv::Rect mos; //!< Coordinates of the mosaic - GAPI_PROP_RW int cellSz; //!< Cell size (same for X, Y) - GAPI_PROP_RW int decim; //!< Decimation (0 stands for no decimation) - /*@{*/ -}; - -/** - * @brief This structure represents an image to draw. - * - * Image is blended on a frame using the specified mask. - */ -struct GAPI_EXPORTS_W_SIMPLE Image -{ - /** - * @brief Mosaic constructor - * - * @param org_ The bottom-left corner of the image - * @param img_ Image to draw - * @param alpha_ Alpha channel for image to draw (same size and number of channels) - */ - GAPI_WRAP - Image(const cv::Point& org_, - const cv::Mat& img_, - const cv::Mat& alpha_) : - org(org_), img(img_), alpha(alpha_) - { - } - - GAPI_WRAP - Image() = default; - - /*@{*/ - GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the image - GAPI_PROP_RW cv::Mat img; //!< Image to draw - GAPI_PROP_RW cv::Mat alpha; //!< Alpha channel for image to draw (same size and number of channels) - /*@{*/ -}; - -/** - * @brief This structure represents a polygon to draw. - */ -struct GAPI_EXPORTS_W_SIMPLE Poly -{ - /** - * @brief Mosaic constructor - * - * @param points_ Points to connect - * @param color_ The line color - * @param thick_ The thickness of line - * @param lt_ The Type of the line. See #LineTypes - * @param shift_ The number of fractional bits in the point coordinate - */ - GAPI_WRAP - Poly(const std::vector& points_, - const cv::Scalar& color_, - int thick_ = 1, - int lt_ = 8, - int shift_ = 0) : - points(points_), color(color_), thick(thick_), lt(lt_), shift(shift_) - { - } - - GAPI_WRAP - Poly() = default; - - /*@{*/ - GAPI_PROP_RW std::vector points; //!< Points to connect - GAPI_PROP_RW cv::Scalar color; //!< The line color - GAPI_PROP_RW int thick; //!< The thickness of line - GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes - GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinate - /*@{*/ -}; - -using Prim = util::variant - < Text - , FText - , Rect - , Circle - , Line - , Mosaic - , Image - , Poly - >; - -using Prims = std::vector; -//! @} gapi_draw_prims - -} // namespace draw -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_RENDER_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_RENDER_TYPES_HPP +#define OPENCV_GAPI_RENDER_TYPES_HPP + +#include +#include + +#include +#include +#include + +namespace cv +{ +namespace gapi +{ +namespace wip +{ +namespace draw +{ + +/** + * @brief This structure specifies which FreeType font to use by FText primitives. + */ +struct freetype_font +{ + /*@{*/ + std::string path; //!< The path to the font file (.ttf) + /*@{*/ +}; + +//! @addtogroup gapi_draw_prims +//! @{ +/** + * @brief This structure represents a text string to draw. + * + * Parameters match cv::putText(). + */ +struct GAPI_EXPORTS_W_SIMPLE Text +{ + /** + * @brief Text constructor + * + * @param text_ The text string to be drawn + * @param org_ The bottom-left corner of the text string in the image + * @param ff_ The font type, see #HersheyFonts + * @param fs_ The font scale factor that is multiplied by the font-specific base size + * @param color_ The text color + * @param thick_ The thickness of the lines used to draw a text + * @param lt_ The line type. See #LineTypes + * @param bottom_left_origin_ When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner + */ + GAPI_WRAP + Text(const std::string& text_, + const cv::Point& org_, + int ff_, + double fs_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + bool bottom_left_origin_ = false) : + text(text_), org(org_), ff(ff_), fs(fs_), + color(color_), thick(thick_), lt(lt_), bottom_left_origin(bottom_left_origin_) + { + } + + GAPI_WRAP + Text() = default; + + /*@{*/ + GAPI_PROP_RW std::string text; //!< The text string to be drawn + GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the text string in the image + GAPI_PROP_RW int ff; //!< The font type, see #HersheyFonts + GAPI_PROP_RW double fs; //!< The font scale factor that is multiplied by the font-specific base size + GAPI_PROP_RW cv::Scalar color; //!< The text color + GAPI_PROP_RW int thick; //!< The thickness of the lines used to draw a text + GAPI_PROP_RW int lt; //!< The line type. See #LineTypes + GAPI_PROP_RW bool bottom_left_origin; //!< When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner + /*@{*/ +}; + +/** + * @brief This structure represents a text string to draw using + * FreeType renderer. + * + * If OpenCV is built without FreeType support, this primitive will + * fail at the execution stage. + */ +struct FText +{ + /** + * @brief FText constructor + * + * @param text_ The text string to be drawn + * @param org_ The bottom-left corner of the text string in the image + * @param fh_ The height of text + * @param color_ The text color + */ + FText(const std::wstring& text_, + const cv::Point& org_, + int fh_, + const cv::Scalar& color_) : + text(text_), org(org_), fh(fh_), color(color_) + { + } + + FText() = default; + + /*@{*/ + std::wstring text; //!< The text string to be drawn + cv::Point org; //!< The bottom-left corner of the text string in the image + int fh; //!< The height of text + cv::Scalar color; //!< The text color + /*@{*/ +}; + +/** + * @brief This structure represents a rectangle to draw. + * + * Parameters match cv::rectangle(). + */ +struct GAPI_EXPORTS_W_SIMPLE Rect +{ + /** + * @brief Rect constructor + * + * @param rect_ Coordinates of the rectangle + * @param color_ The bottom-left corner of the text string in the image + * @param thick_ The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle + * @param lt_ The type of the line. See #LineTypes + * @param shift_ The number of fractional bits in the point coordinates + */ + Rect(const cv::Rect& rect_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + rect(rect_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Rect() = default; + + /*@{*/ + GAPI_PROP_RW cv::Rect rect; //!< Coordinates of the rectangle + GAPI_PROP_RW cv::Scalar color; //!< The rectangle color or brightness (grayscale image) + GAPI_PROP_RW int thick; //!< The thickness of lines that make up the rectangle. Negative values, like #FILLED, mean that the function has to draw a filled rectangle + GAPI_PROP_RW int lt; //!< The type of the line. See #LineTypes + GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates + /*@{*/ +}; + +/** + * @brief This structure represents a circle to draw. + * + * Parameters match cv::circle(). + */ +struct GAPI_EXPORTS_W_SIMPLE Circle +{ + /** + * @brief Circle constructor + * + * @param center_ The center of the circle + * @param radius_ The radius of the circle + * @param color_ The color of the circle + * @param thick_ The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn + * @param lt_ The Type of the circle boundary. See #LineTypes + * @param shift_ The Number of fractional bits in the coordinates of the center and in the radius value + */ + GAPI_WRAP + Circle(const cv::Point& center_, + int radius_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + center(center_), radius(radius_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Circle() = default; + + /*@{*/ + GAPI_PROP_RW cv::Point center; //!< The center of the circle + GAPI_PROP_RW int radius; //!< The radius of the circle + GAPI_PROP_RW cv::Scalar color; //!< The color of the circle + GAPI_PROP_RW int thick; //!< The thickness of the circle outline, if positive. Negative values, like #FILLED, mean that a filled circle is to be drawn + GAPI_PROP_RW int lt; //!< The Type of the circle boundary. See #LineTypes + GAPI_PROP_RW int shift; //!< The Number of fractional bits in the coordinates of the center and in the radius value + /*@{*/ +}; + +/** + * @brief This structure represents a line to draw. + * + * Parameters match cv::line(). + */ +struct GAPI_EXPORTS_W_SIMPLE Line +{ + /** + * @brief Line constructor + * + * @param pt1_ The first point of the line segment + * @param pt2_ The second point of the line segment + * @param color_ The line color + * @param thick_ The thickness of line + * @param lt_ The Type of the line. See #LineTypes + * @param shift_ The number of fractional bits in the point coordinates + */ + GAPI_WRAP + Line(const cv::Point& pt1_, + const cv::Point& pt2_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + pt1(pt1_), pt2(pt2_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Line() = default; + + /*@{*/ + GAPI_PROP_RW cv::Point pt1; //!< The first point of the line segment + GAPI_PROP_RW cv::Point pt2; //!< The second point of the line segment + GAPI_PROP_RW cv::Scalar color; //!< The line color + GAPI_PROP_RW int thick; //!< The thickness of line + GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes + GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinates + /*@{*/ +}; + +/** + * @brief This structure represents a mosaicing operation. + * + * Mosaicing is a very basic method to obfuscate regions in the image. + */ +struct GAPI_EXPORTS_W_SIMPLE Mosaic +{ + /** + * @brief Mosaic constructor + * + * @param mos_ Coordinates of the mosaic + * @param cellSz_ Cell size (same for X, Y) + * @param decim_ Decimation (0 stands for no decimation) + */ + Mosaic(const cv::Rect& mos_, + int cellSz_, + int decim_) : + mos(mos_), cellSz(cellSz_), decim(decim_) + { + } + + GAPI_WRAP + Mosaic() : cellSz(0), decim(0) {} + + /*@{*/ + GAPI_PROP_RW cv::Rect mos; //!< Coordinates of the mosaic + GAPI_PROP_RW int cellSz; //!< Cell size (same for X, Y) + GAPI_PROP_RW int decim; //!< Decimation (0 stands for no decimation) + /*@{*/ +}; + +/** + * @brief This structure represents an image to draw. + * + * Image is blended on a frame using the specified mask. + */ +struct GAPI_EXPORTS_W_SIMPLE Image +{ + /** + * @brief Mosaic constructor + * + * @param org_ The bottom-left corner of the image + * @param img_ Image to draw + * @param alpha_ Alpha channel for image to draw (same size and number of channels) + */ + GAPI_WRAP + Image(const cv::Point& org_, + const cv::Mat& img_, + const cv::Mat& alpha_) : + org(org_), img(img_), alpha(alpha_) + { + } + + GAPI_WRAP + Image() = default; + + /*@{*/ + GAPI_PROP_RW cv::Point org; //!< The bottom-left corner of the image + GAPI_PROP_RW cv::Mat img; //!< Image to draw + GAPI_PROP_RW cv::Mat alpha; //!< Alpha channel for image to draw (same size and number of channels) + /*@{*/ +}; + +/** + * @brief This structure represents a polygon to draw. + */ +struct GAPI_EXPORTS_W_SIMPLE Poly +{ + /** + * @brief Mosaic constructor + * + * @param points_ Points to connect + * @param color_ The line color + * @param thick_ The thickness of line + * @param lt_ The Type of the line. See #LineTypes + * @param shift_ The number of fractional bits in the point coordinate + */ + GAPI_WRAP + Poly(const std::vector& points_, + const cv::Scalar& color_, + int thick_ = 1, + int lt_ = 8, + int shift_ = 0) : + points(points_), color(color_), thick(thick_), lt(lt_), shift(shift_) + { + } + + GAPI_WRAP + Poly() = default; + + /*@{*/ + GAPI_PROP_RW std::vector points; //!< Points to connect + GAPI_PROP_RW cv::Scalar color; //!< The line color + GAPI_PROP_RW int thick; //!< The thickness of line + GAPI_PROP_RW int lt; //!< The Type of the line. See #LineTypes + GAPI_PROP_RW int shift; //!< The number of fractional bits in the point coordinate + /*@{*/ +}; + +using Prim = util::variant + < Text + , FText + , Rect + , Circle + , Line + , Mosaic + , Image + , Poly + >; + +using Prims = std::vector; +//! @} gapi_draw_prims + +} // namespace draw +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_RENDER_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp index 12c700e455..46989191b3 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/rmat.hpp @@ -1,160 +1,160 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_RMAT_HPP -#define OPENCV_GAPI_RMAT_HPP - -#include -#include - -// Forward declaration -namespace cv { -namespace gapi { -namespace s11n { -struct IOStream; -struct IIStream; -} // namespace s11n -} // namespace gapi -} // namespace cv - -namespace cv { - -// "Remote Mat", a general class which provides an abstraction layer over the data -// storage and placement (host, remote device etc) and allows to access this data. -// -// The device specific implementation is hidden in the RMat::IAdapter class -// -// The basic flow is the following: -// * Backend which is aware of the remote device: -// - Implements own AdapterT class which is derived from RMat::IAdapter -// - Wraps device memory into RMat via make_rmat utility function: -// cv::RMat rmat = cv::make_rmat(args); -// -// * End user: -// - Writes the code which works with RMats without any knowledge of the remote device: -// void func(const cv::RMat& in_rmat, cv::RMat& out_rmat) { -// // Fetch input data from the device, get mapped memory for output -// cv::RMat::View in_view = in_rmat.access(Access::R); -// cv::RMat::View out_view = out_rmat.access(Access::W); -// performCalculations(in_view, out_view); -// // data from out_view is transferred to the device when out_view is destroyed -// } -/** \addtogroup gapi_data_structures - * @{ - */ -class GAPI_EXPORTS RMat -{ -public: - // A lightweight wrapper on image data: - // - Doesn't own the memory; - // - Doesn't implement copy semantics (it's assumed that a view is created each time - // wrapped data is being accessed); - // - Has an optional callback which is called when the view is destroyed. - class GAPI_EXPORTS View - { - public: - using DestroyCallback = std::function; - using stepsT = std::vector; - - View() = default; - View(const GMatDesc& desc, uchar* data, const stepsT& steps = {}, DestroyCallback&& cb = nullptr); - View(const GMatDesc& desc, uchar* data, size_t step, DestroyCallback&& cb = nullptr); - - View(const View&) = delete; - View& operator=(const View&) = delete; - View(View&&) = default; - View& operator=(View&& v); - ~View() { if (m_cb) m_cb(); } - - cv::Size size() const { return m_desc.size; } - const std::vector& dims() const { return m_desc.dims; } - int cols() const { return m_desc.size.width; } - int rows() const { return m_desc.size.height; } - int type() const; - int depth() const { return m_desc.depth; } - int chan() const { return m_desc.chan; } - size_t elemSize() const { return CV_ELEM_SIZE(type()); } - - template T* ptr(int y = 0) { - return reinterpret_cast(m_data + step()*y); - } - template const T* ptr(int y = 0) const { - return reinterpret_cast(m_data + step()*y); - } - template T* ptr(int y, int x) { - return reinterpret_cast(m_data + step()*y + step(1)*x); - } - template const T* ptr(int y, int x) const { - return reinterpret_cast(m_data + step()*y + step(1)*x); - } - size_t step(size_t i = 0) const { GAPI_DbgAssert(i; - - RMat() = default; - RMat(AdapterP&& a) : m_adapter(std::move(a)) {} - GMatDesc desc() const { return m_adapter->desc(); } - - // Note: When accessed for write there is no guarantee that returned view - // will contain actual snapshot of the mapped device memory - // (no guarantee that fetch from a device is performed). The only - // guaranty is that when the view is destroyed, its data will be - // transferred to the device - View access(Access a) const { return m_adapter->access(a); } - - // Cast underlying RMat adapter to the particular adapter type, - // return nullptr if underlying type is different - template T* get() const - { - static_assert(std::is_base_of::value, "T is not derived from IAdapter!"); - GAPI_Assert(m_adapter != nullptr); - return dynamic_cast(m_adapter.get()); - } - - void serialize(cv::gapi::s11n::IOStream& os) const { - m_adapter->serialize(os); - } - -private: - AdapterP m_adapter = nullptr; -}; - -template -RMat make_rmat(Ts&&... args) { return { std::make_shared(std::forward(args)...) }; } -/** @} */ - -} //namespace cv - -#endif /* OPENCV_GAPI_RMAT_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_RMAT_HPP +#define OPENCV_GAPI_RMAT_HPP + +#include +#include + +// Forward declaration +namespace cv { +namespace gapi { +namespace s11n { +struct IOStream; +struct IIStream; +} // namespace s11n +} // namespace gapi +} // namespace cv + +namespace cv { + +// "Remote Mat", a general class which provides an abstraction layer over the data +// storage and placement (host, remote device etc) and allows to access this data. +// +// The device specific implementation is hidden in the RMat::IAdapter class +// +// The basic flow is the following: +// * Backend which is aware of the remote device: +// - Implements own AdapterT class which is derived from RMat::IAdapter +// - Wraps device memory into RMat via make_rmat utility function: +// cv::RMat rmat = cv::make_rmat(args); +// +// * End user: +// - Writes the code which works with RMats without any knowledge of the remote device: +// void func(const cv::RMat& in_rmat, cv::RMat& out_rmat) { +// // Fetch input data from the device, get mapped memory for output +// cv::RMat::View in_view = in_rmat.access(Access::R); +// cv::RMat::View out_view = out_rmat.access(Access::W); +// performCalculations(in_view, out_view); +// // data from out_view is transferred to the device when out_view is destroyed +// } +/** \addtogroup gapi_data_structures + * @{ + */ +class GAPI_EXPORTS RMat +{ +public: + // A lightweight wrapper on image data: + // - Doesn't own the memory; + // - Doesn't implement copy semantics (it's assumed that a view is created each time + // wrapped data is being accessed); + // - Has an optional callback which is called when the view is destroyed. + class GAPI_EXPORTS View + { + public: + using DestroyCallback = std::function; + using stepsT = std::vector; + + View() = default; + View(const GMatDesc& desc, uchar* data, const stepsT& steps = {}, DestroyCallback&& cb = nullptr); + View(const GMatDesc& desc, uchar* data, size_t step, DestroyCallback&& cb = nullptr); + + View(const View&) = delete; + View& operator=(const View&) = delete; + View(View&&) = default; + View& operator=(View&& v); + ~View() { if (m_cb) m_cb(); } + + cv::Size size() const { return m_desc.size; } + const std::vector& dims() const { return m_desc.dims; } + int cols() const { return m_desc.size.width; } + int rows() const { return m_desc.size.height; } + int type() const; + int depth() const { return m_desc.depth; } + int chan() const { return m_desc.chan; } + size_t elemSize() const { return CV_ELEM_SIZE(type()); } + + template T* ptr(int y = 0) { + return reinterpret_cast(m_data + step()*y); + } + template const T* ptr(int y = 0) const { + return reinterpret_cast(m_data + step()*y); + } + template T* ptr(int y, int x) { + return reinterpret_cast(m_data + step()*y + step(1)*x); + } + template const T* ptr(int y, int x) const { + return reinterpret_cast(m_data + step()*y + step(1)*x); + } + size_t step(size_t i = 0) const { GAPI_DbgAssert(i; + + RMat() = default; + RMat(AdapterP&& a) : m_adapter(std::move(a)) {} + GMatDesc desc() const { return m_adapter->desc(); } + + // Note: When accessed for write there is no guarantee that returned view + // will contain actual snapshot of the mapped device memory + // (no guarantee that fetch from a device is performed). The only + // guaranty is that when the view is destroyed, its data will be + // transferred to the device + View access(Access a) const { return m_adapter->access(a); } + + // Cast underlying RMat adapter to the particular adapter type, + // return nullptr if underlying type is different + template T* get() const + { + static_assert(std::is_base_of::value, "T is not derived from IAdapter!"); + GAPI_Assert(m_adapter != nullptr); + return dynamic_cast(m_adapter.get()); + } + + void serialize(cv::gapi::s11n::IOStream& os) const { + m_adapter->serialize(os); + } + +private: + AdapterP m_adapter = nullptr; +}; + +template +RMat make_rmat(Ts&&... args) { return { std::make_shared(std::forward(args)...) }; } +/** @} */ + +} //namespace cv + +#endif /* OPENCV_GAPI_RMAT_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp index 16c162e7f1..a94f55c249 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n.hpp @@ -1,513 +1,513 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - -#ifndef OPENCV_GAPI_S11N_HPP -#define OPENCV_GAPI_S11N_HPP - -#include -#include -#include -#include -#include -#include -#include -#include - -// FIXME: caused by deserialize_runarg -#if defined _MSC_VER -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - -namespace cv { -namespace gapi { - -/** -* \addtogroup gapi_serialization -* @{ -*/ - -namespace detail { - GAPI_EXPORTS cv::GComputation getGraph(const std::vector &bytes); - - GAPI_EXPORTS cv::GMetaArgs getMetaArgs(const std::vector &bytes); - - GAPI_EXPORTS cv::GRunArgs getRunArgs(const std::vector &bytes); - - GAPI_EXPORTS std::vector getVectorOfStrings(const std::vector &bytes); - - template - cv::GCompileArgs getCompileArgs(const std::vector &bytes); - - template - cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes); -} // namespace detail - -/** @brief Serialize a graph represented by GComputation into an array of bytes. - * - * Check different overloads for more examples. - * @param c GComputation to serialize. - * @return serialized vector of bytes. - */ -GAPI_EXPORTS std::vector serialize(const cv::GComputation &c); - -/** @overload - * @param ca GCompileArgs to serialize. - */ -GAPI_EXPORTS std::vector serialize(const cv::GCompileArgs& ca); - -/** @overload - * @param ma GMetaArgs to serialize. - */ -GAPI_EXPORTS std::vector serialize(const cv::GMetaArgs& ma); - -/** @overload - * @param ra GRunArgs to serialize. - */ -GAPI_EXPORTS std::vector serialize(const cv::GRunArgs& ra); - -/** @overload - * @param vs std::vector to serialize. - */ -GAPI_EXPORTS std::vector serialize(const std::vector& vs); - -/** - * @private - */ -template static inline -T deserialize(const std::vector &bytes); - -/** @brief Deserialize GComputation from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized GComputation object. - */ -template<> inline -cv::GComputation deserialize(const std::vector &bytes) { - return detail::getGraph(bytes); -} - -/** @brief Deserialize GMetaArgs from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized GMetaArgs object. - */ -template<> inline -cv::GMetaArgs deserialize(const std::vector &bytes) { - return detail::getMetaArgs(bytes); -} - -/** @brief Deserialize GRunArgs from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized GRunArgs object. - */ -template<> inline -cv::GRunArgs deserialize(const std::vector &bytes) { - return detail::getRunArgs(bytes); -} - -/** @brief Deserialize std::vector from a byte array. - * - * Check different overloads for more examples. - * @param bytes serialized vector of bytes. - * @return deserialized std::vector object. - */ -template<> inline -std::vector deserialize(const std::vector &bytes) { - return detail::getVectorOfStrings(bytes); -} - -/** - * @brief Deserialize GCompileArgs which types were specified in the template from a byte array. - * - * @note cv::gapi::s11n::detail::S11N template specialization must be provided to make a custom type - * in GCompileArgs deserializable. - * - * @param bytes vector of bytes to deserialize GCompileArgs object from. - * @return GCompileArgs object. - * @see GCompileArgs cv::gapi::s11n::detail::S11N - */ -template inline -typename std::enable_if::value, GCompileArgs>:: -type deserialize(const std::vector &bytes) { - return detail::getCompileArgs(bytes); -} - -/** - * @brief Deserialize GRunArgs including RMat and MediaFrame objects if any from a byte array. - * - * Adapter types are specified in the template. - * @note To be used properly specified adapter types must overload their deserialize() method. - * @param bytes vector of bytes to deserialize GRunArgs object from. - * @return GRunArgs including RMat and MediaFrame objects if any. - * @see RMat MediaFrame - */ -template inline -typename std::enable_if::value, GRunArgs>:: -type deserialize(const std::vector &bytes) { - return detail::getRunArgsWithAdapters(bytes); -} -} // namespace gapi -} // namespace cv - -namespace cv { -namespace gapi { -namespace s11n { - -/** @brief This structure is an interface for serialization routines. - * - * It's main purpose is to provide multiple overloads for operator<<() - * with basic C++ in addition to OpenCV/G-API types. - * - * This sctructure can be inherited and further extended with additional types. - * - * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter - * in serialize() method. - */ -struct GAPI_EXPORTS IOStream { - virtual ~IOStream() = default; - // Define the native support for basic C++ types at the API level: - virtual IOStream& operator<< (bool) = 0; - virtual IOStream& operator<< (char) = 0; - virtual IOStream& operator<< (unsigned char) = 0; - virtual IOStream& operator<< (short) = 0; - virtual IOStream& operator<< (unsigned short) = 0; - virtual IOStream& operator<< (int) = 0; - virtual IOStream& operator<< (uint32_t) = 0; - virtual IOStream& operator<< (uint64_t) = 0; - virtual IOStream& operator<< (float) = 0; - virtual IOStream& operator<< (double) = 0; - virtual IOStream& operator<< (const std::string&) = 0; -}; - -/** @brief This structure is an interface for deserialization routines. - * - * It's main purpose is to provide multiple overloads for operator>>() - * with basic C++ in addition to OpenCV/G-API types. - * - * This structure can be inherited and further extended with additional types. - * - * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter - * in deserialize() method. - */ -struct GAPI_EXPORTS IIStream { - virtual ~IIStream() = default; - virtual IIStream& operator>> (bool &) = 0; - virtual IIStream& operator>> (std::vector::reference) = 0; - virtual IIStream& operator>> (char &) = 0; - virtual IIStream& operator>> (unsigned char &) = 0; - virtual IIStream& operator>> (short &) = 0; - virtual IIStream& operator>> (unsigned short &) = 0; - virtual IIStream& operator>> (int &) = 0; - virtual IIStream& operator>> (float &) = 0; - virtual IIStream& operator>> (double &) = 0; - virtual IIStream& operator >> (uint32_t &) = 0; - virtual IIStream& operator >> (uint64_t &) = 0; - virtual IIStream& operator>> (std::string &) = 0; -}; - -namespace detail { -GAPI_EXPORTS std::unique_ptr getInStream(const std::vector &bytes); -} // namespace detail - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// S11N operators -// Note: operators for basic types are defined in IIStream/IOStream - -// OpenCV types //////////////////////////////////////////////////////////////// - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point &pt); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point &pt); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point2f &pt); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point2f &pt); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point3f &pt); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point3f &pt); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Size &sz); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Size &sz); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Rect &rc); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Rect &rc); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Scalar &s); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Scalar &s); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Mat &m); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Mat &m); - -// FIXME: for GRunArgs serialization -#if !defined(GAPI_STANDALONE) -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::UMat & um); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::UMat & um); -#endif // !defined(GAPI_STANDALONE) - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::RMat &r); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::RMat &r); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::gapi::wip::IStreamSource::Ptr &issptr); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::gapi::wip::IStreamSource::Ptr &issptr); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::VectorRef &vr); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::VectorRef &vr); - -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::OpaqueRef &opr); -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::OpaqueRef &opr); - -/// @private -- Exclude this function from OpenCV documentation -GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::MediaFrame &mf); -/// @private -- Exclude this function from OpenCV documentation -GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::MediaFrame &mf); - -// Generic STL types //////////////////////////////////////////////////////////////// -template -IOStream& operator<< (IOStream& os, const std::map &m) { - const uint32_t sz = static_cast(m.size()); - os << sz; - for (const auto& it : m) os << it.first << it.second; - return os; -} -template -IIStream& operator>> (IIStream& is, std::map &m) { - m.clear(); - uint32_t sz = 0u; - is >> sz; - for (std::size_t i = 0; i < sz; ++i) { - K k{}; - V v{}; - is >> k >> v; - m[k] = v; - } - return is; -} - -template -IOStream& operator<< (IOStream& os, const std::unordered_map &m) { - const uint32_t sz = static_cast(m.size()); - os << sz; - for (auto &&it : m) os << it.first << it.second; - return os; -} -template -IIStream& operator>> (IIStream& is, std::unordered_map &m) { - m.clear(); - uint32_t sz = 0u; - is >> sz; - for (std::size_t i = 0; i < sz; ++i) { - K k{}; - V v{}; - is >> k >> v; - m[k] = v; - } - return is; -} - -template -IOStream& operator<< (IOStream& os, const std::vector &ts) { - const uint32_t sz = static_cast(ts.size()); - os << sz; - for (auto &&v : ts) os << v; - return os; -} -template -IIStream& operator>> (IIStream& is, std::vector &ts) { - uint32_t sz = 0u; - is >> sz; - if (sz == 0u) { - ts.clear(); - } - else { - ts.resize(sz); - for (std::size_t i = 0; i < sz; ++i) is >> ts[i]; - } - return is; -} - -// Generic: variant serialization -namespace detail { -template -IOStream& put_v(IOStream&, const V&, std::size_t) { - GAPI_Error("variant>>: requested index is invalid"); -} - -template -IOStream& put_v(IOStream& os, const V& v, std::size_t x) { - return (x == 0u) - ? os << cv::util::get(v) - : put_v(os, v, x-1); -} - -template -IIStream& get_v(IIStream&, V&, std::size_t, std::size_t) { - GAPI_Error("variant<<: requested index is invalid"); -} - -template -IIStream& get_v(IIStream& is, V& v, std::size_t i, std::size_t gi) { - if (i == gi) { - X x{}; - is >> x; - v = V{std::move(x)}; - return is; - } else return get_v(is, v, i+1, gi); -} -} // namespace detail - -//! @overload -template -IOStream& operator<< (IOStream& os, const cv::util::variant &v) { - os << static_cast(v.index()); - return detail::put_v, Ts...>(os, v, v.index()); -} -//! @overload -template -IIStream& operator>> (IIStream& is, cv::util::variant &v) { - int idx = -1; - is >> idx; - GAPI_Assert(idx >= 0 && idx < (int)sizeof...(Ts)); - return detail::get_v, Ts...>(is, v, 0u, idx); -} - -// FIXME: consider a better solution -/// @private -- Exclude this function from OpenCV documentation -template -void getRunArgByIdx (IIStream& is, cv::util::variant &v, uint32_t idx) { - is = detail::get_v, Ts...>(is, v, 0u, idx); -} -} // namespace s11n - -namespace detail -{ -template struct try_deserialize_comparg; - -template<> struct try_deserialize_comparg> { -static cv::util::optional exec(const std::string&, cv::gapi::s11n::IIStream&) { - return { }; - } -}; - -template -struct try_deserialize_comparg> { -static cv::util::optional exec(const std::string& tag, cv::gapi::s11n::IIStream& is) { - if (tag == cv::detail::CompileArgTag::tag()) { - static_assert(cv::gapi::s11n::detail::has_S11N_spec::value, - "cv::gapi::deserialize expects Types to have S11N " - "specializations with deserialization callbacks!"); - return cv::util::optional( - GCompileArg { cv::gapi::s11n::detail::S11N::deserialize(is) }); - } - return try_deserialize_comparg>::exec(tag, is); -} -}; - -template -struct deserialize_arg_with_adapter; - -template -struct deserialize_arg_with_adapter { -static GRunArg exec(cv::gapi::s11n::IIStream& is) { - std::unique_ptr ptr(new TA); - ptr->deserialize(is); - return GRunArg { RA(std::move(ptr)) }; -} -}; - -template -struct deserialize_arg_with_adapter { -static GRunArg exec(cv::gapi::s11n::IIStream&) { - GAPI_Error("No suitable adapter class found during RMat/MediaFrame deserialization. " - "Please, make sure you've passed them in cv::gapi::deserialize() template"); - return GRunArg{}; -} -}; - -template -struct deserialize_runarg { -static GRunArg exec(cv::gapi::s11n::IIStream& is, uint32_t idx) { - if (idx == GRunArg::index_of()) { - // Type or void (if not found) - using TA = typename cv::util::find_adapter_impl::type; - return deserialize_arg_with_adapter::exec(is); - } else if (idx == GRunArg::index_of()) { - // Type or void (if not found) - using TA = typename cv::util::find_adapter_impl::type; - return deserialize_arg_with_adapter::exec(is); - } else { // not an adapter holding type runarg - use default deserialization - GRunArg arg; - getRunArgByIdx(is, arg, idx); - return arg; - } -} -}; - -template -inline cv::util::optional tryDeserializeCompArg(const std::string& tag, - const std::vector& sArg) { - std::unique_ptr pArgIs = cv::gapi::s11n::detail::getInStream(sArg); - return try_deserialize_comparg>::exec(tag, *pArgIs); -} - -template -cv::GCompileArgs getCompileArgs(const std::vector &sArgs) { - cv::GCompileArgs args; - - std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(sArgs); - cv::gapi::s11n::IIStream& is = *pIs; - - uint32_t sz = 0; - is >> sz; - for (uint32_t i = 0; i < sz; ++i) { - std::string tag; - is >> tag; - - std::vector sArg; - is >> sArg; - - cv::util::optional dArg = - cv::gapi::detail::tryDeserializeCompArg(tag, sArg); - - if (dArg.has_value()) - { - args.push_back(dArg.value()); - } - } - - return args; -} - -template -cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes) { - std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(bytes); - cv::gapi::s11n::IIStream& is = *pIs; - cv::GRunArgs args; - - uint32_t sz = 0; - is >> sz; - for (uint32_t i = 0; i < sz; ++i) { - uint32_t idx = 0; - is >> idx; - args.push_back(cv::gapi::detail::deserialize_runarg::exec(is, idx)); - } - - return args; -} -} // namespace detail -/** @} */ - -} // namespace gapi -} // namespace cv - -#if defined _MSC_VER -#pragma warning(pop) -#endif - -#endif // OPENCV_GAPI_S11N_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + +#ifndef OPENCV_GAPI_S11N_HPP +#define OPENCV_GAPI_S11N_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +// FIXME: caused by deserialize_runarg +#if defined _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + +namespace cv { +namespace gapi { + +/** +* \addtogroup gapi_serialization +* @{ +*/ + +namespace detail { + GAPI_EXPORTS cv::GComputation getGraph(const std::vector &bytes); + + GAPI_EXPORTS cv::GMetaArgs getMetaArgs(const std::vector &bytes); + + GAPI_EXPORTS cv::GRunArgs getRunArgs(const std::vector &bytes); + + GAPI_EXPORTS std::vector getVectorOfStrings(const std::vector &bytes); + + template + cv::GCompileArgs getCompileArgs(const std::vector &bytes); + + template + cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes); +} // namespace detail + +/** @brief Serialize a graph represented by GComputation into an array of bytes. + * + * Check different overloads for more examples. + * @param c GComputation to serialize. + * @return serialized vector of bytes. + */ +GAPI_EXPORTS std::vector serialize(const cv::GComputation &c); + +/** @overload + * @param ca GCompileArgs to serialize. + */ +GAPI_EXPORTS std::vector serialize(const cv::GCompileArgs& ca); + +/** @overload + * @param ma GMetaArgs to serialize. + */ +GAPI_EXPORTS std::vector serialize(const cv::GMetaArgs& ma); + +/** @overload + * @param ra GRunArgs to serialize. + */ +GAPI_EXPORTS std::vector serialize(const cv::GRunArgs& ra); + +/** @overload + * @param vs std::vector to serialize. + */ +GAPI_EXPORTS std::vector serialize(const std::vector& vs); + +/** + * @private + */ +template static inline +T deserialize(const std::vector &bytes); + +/** @brief Deserialize GComputation from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized GComputation object. + */ +template<> inline +cv::GComputation deserialize(const std::vector &bytes) { + return detail::getGraph(bytes); +} + +/** @brief Deserialize GMetaArgs from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized GMetaArgs object. + */ +template<> inline +cv::GMetaArgs deserialize(const std::vector &bytes) { + return detail::getMetaArgs(bytes); +} + +/** @brief Deserialize GRunArgs from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized GRunArgs object. + */ +template<> inline +cv::GRunArgs deserialize(const std::vector &bytes) { + return detail::getRunArgs(bytes); +} + +/** @brief Deserialize std::vector from a byte array. + * + * Check different overloads for more examples. + * @param bytes serialized vector of bytes. + * @return deserialized std::vector object. + */ +template<> inline +std::vector deserialize(const std::vector &bytes) { + return detail::getVectorOfStrings(bytes); +} + +/** + * @brief Deserialize GCompileArgs which types were specified in the template from a byte array. + * + * @note cv::gapi::s11n::detail::S11N template specialization must be provided to make a custom type + * in GCompileArgs deserializable. + * + * @param bytes vector of bytes to deserialize GCompileArgs object from. + * @return GCompileArgs object. + * @see GCompileArgs cv::gapi::s11n::detail::S11N + */ +template inline +typename std::enable_if::value, GCompileArgs>:: +type deserialize(const std::vector &bytes) { + return detail::getCompileArgs(bytes); +} + +/** + * @brief Deserialize GRunArgs including RMat and MediaFrame objects if any from a byte array. + * + * Adapter types are specified in the template. + * @note To be used properly specified adapter types must overload their deserialize() method. + * @param bytes vector of bytes to deserialize GRunArgs object from. + * @return GRunArgs including RMat and MediaFrame objects if any. + * @see RMat MediaFrame + */ +template inline +typename std::enable_if::value, GRunArgs>:: +type deserialize(const std::vector &bytes) { + return detail::getRunArgsWithAdapters(bytes); +} +} // namespace gapi +} // namespace cv + +namespace cv { +namespace gapi { +namespace s11n { + +/** @brief This structure is an interface for serialization routines. + * + * It's main purpose is to provide multiple overloads for operator<<() + * with basic C++ in addition to OpenCV/G-API types. + * + * This sctructure can be inherited and further extended with additional types. + * + * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter + * in serialize() method. + */ +struct GAPI_EXPORTS IOStream { + virtual ~IOStream() = default; + // Define the native support for basic C++ types at the API level: + virtual IOStream& operator<< (bool) = 0; + virtual IOStream& operator<< (char) = 0; + virtual IOStream& operator<< (unsigned char) = 0; + virtual IOStream& operator<< (short) = 0; + virtual IOStream& operator<< (unsigned short) = 0; + virtual IOStream& operator<< (int) = 0; + virtual IOStream& operator<< (uint32_t) = 0; + virtual IOStream& operator<< (uint64_t) = 0; + virtual IOStream& operator<< (float) = 0; + virtual IOStream& operator<< (double) = 0; + virtual IOStream& operator<< (const std::string&) = 0; +}; + +/** @brief This structure is an interface for deserialization routines. + * + * It's main purpose is to provide multiple overloads for operator>>() + * with basic C++ in addition to OpenCV/G-API types. + * + * This structure can be inherited and further extended with additional types. + * + * For example, it is utilized in cv::gapi::s11n::detail::S11N as input parameter + * in deserialize() method. + */ +struct GAPI_EXPORTS IIStream { + virtual ~IIStream() = default; + virtual IIStream& operator>> (bool &) = 0; + virtual IIStream& operator>> (std::vector::reference) = 0; + virtual IIStream& operator>> (char &) = 0; + virtual IIStream& operator>> (unsigned char &) = 0; + virtual IIStream& operator>> (short &) = 0; + virtual IIStream& operator>> (unsigned short &) = 0; + virtual IIStream& operator>> (int &) = 0; + virtual IIStream& operator>> (float &) = 0; + virtual IIStream& operator>> (double &) = 0; + virtual IIStream& operator >> (uint32_t &) = 0; + virtual IIStream& operator >> (uint64_t &) = 0; + virtual IIStream& operator>> (std::string &) = 0; +}; + +namespace detail { +GAPI_EXPORTS std::unique_ptr getInStream(const std::vector &bytes); +} // namespace detail + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// S11N operators +// Note: operators for basic types are defined in IIStream/IOStream + +// OpenCV types //////////////////////////////////////////////////////////////// + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point &pt); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point &pt); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point2f &pt); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point2f &pt); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Point3f &pt); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Point3f &pt); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Size &sz); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Size &sz); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Rect &rc); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Rect &rc); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Scalar &s); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Scalar &s); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::Mat &m); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::Mat &m); + +// FIXME: for GRunArgs serialization +#if !defined(GAPI_STANDALONE) +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::UMat & um); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::UMat & um); +#endif // !defined(GAPI_STANDALONE) + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::RMat &r); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::RMat &r); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::gapi::wip::IStreamSource::Ptr &issptr); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::gapi::wip::IStreamSource::Ptr &issptr); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::VectorRef &vr); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::VectorRef &vr); + +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::detail::OpaqueRef &opr); +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::detail::OpaqueRef &opr); + +/// @private -- Exclude this function from OpenCV documentation +GAPI_EXPORTS IOStream& operator<< (IOStream& os, const cv::MediaFrame &mf); +/// @private -- Exclude this function from OpenCV documentation +GAPI_EXPORTS IIStream& operator>> (IIStream& is, cv::MediaFrame &mf); + +// Generic STL types //////////////////////////////////////////////////////////////// +template +IOStream& operator<< (IOStream& os, const std::map &m) { + const uint32_t sz = static_cast(m.size()); + os << sz; + for (const auto& it : m) os << it.first << it.second; + return os; +} +template +IIStream& operator>> (IIStream& is, std::map &m) { + m.clear(); + uint32_t sz = 0u; + is >> sz; + for (std::size_t i = 0; i < sz; ++i) { + K k{}; + V v{}; + is >> k >> v; + m[k] = v; + } + return is; +} + +template +IOStream& operator<< (IOStream& os, const std::unordered_map &m) { + const uint32_t sz = static_cast(m.size()); + os << sz; + for (auto &&it : m) os << it.first << it.second; + return os; +} +template +IIStream& operator>> (IIStream& is, std::unordered_map &m) { + m.clear(); + uint32_t sz = 0u; + is >> sz; + for (std::size_t i = 0; i < sz; ++i) { + K k{}; + V v{}; + is >> k >> v; + m[k] = v; + } + return is; +} + +template +IOStream& operator<< (IOStream& os, const std::vector &ts) { + const uint32_t sz = static_cast(ts.size()); + os << sz; + for (auto &&v : ts) os << v; + return os; +} +template +IIStream& operator>> (IIStream& is, std::vector &ts) { + uint32_t sz = 0u; + is >> sz; + if (sz == 0u) { + ts.clear(); + } + else { + ts.resize(sz); + for (std::size_t i = 0; i < sz; ++i) is >> ts[i]; + } + return is; +} + +// Generic: variant serialization +namespace detail { +template +IOStream& put_v(IOStream&, const V&, std::size_t) { + GAPI_Error("variant>>: requested index is invalid"); +} + +template +IOStream& put_v(IOStream& os, const V& v, std::size_t x) { + return (x == 0u) + ? os << cv::util::get(v) + : put_v(os, v, x-1); +} + +template +IIStream& get_v(IIStream&, V&, std::size_t, std::size_t) { + GAPI_Error("variant<<: requested index is invalid"); +} + +template +IIStream& get_v(IIStream& is, V& v, std::size_t i, std::size_t gi) { + if (i == gi) { + X x{}; + is >> x; + v = V{std::move(x)}; + return is; + } else return get_v(is, v, i+1, gi); +} +} // namespace detail + +//! @overload +template +IOStream& operator<< (IOStream& os, const cv::util::variant &v) { + os << static_cast(v.index()); + return detail::put_v, Ts...>(os, v, v.index()); +} +//! @overload +template +IIStream& operator>> (IIStream& is, cv::util::variant &v) { + int idx = -1; + is >> idx; + GAPI_Assert(idx >= 0 && idx < (int)sizeof...(Ts)); + return detail::get_v, Ts...>(is, v, 0u, idx); +} + +// FIXME: consider a better solution +/// @private -- Exclude this function from OpenCV documentation +template +void getRunArgByIdx (IIStream& is, cv::util::variant &v, uint32_t idx) { + is = detail::get_v, Ts...>(is, v, 0u, idx); +} +} // namespace s11n + +namespace detail +{ +template struct try_deserialize_comparg; + +template<> struct try_deserialize_comparg> { +static cv::util::optional exec(const std::string&, cv::gapi::s11n::IIStream&) { + return { }; + } +}; + +template +struct try_deserialize_comparg> { +static cv::util::optional exec(const std::string& tag, cv::gapi::s11n::IIStream& is) { + if (tag == cv::detail::CompileArgTag::tag()) { + static_assert(cv::gapi::s11n::detail::has_S11N_spec::value, + "cv::gapi::deserialize expects Types to have S11N " + "specializations with deserialization callbacks!"); + return cv::util::optional( + GCompileArg { cv::gapi::s11n::detail::S11N::deserialize(is) }); + } + return try_deserialize_comparg>::exec(tag, is); +} +}; + +template +struct deserialize_arg_with_adapter; + +template +struct deserialize_arg_with_adapter { +static GRunArg exec(cv::gapi::s11n::IIStream& is) { + std::unique_ptr ptr(new TA); + ptr->deserialize(is); + return GRunArg { RA(std::move(ptr)) }; +} +}; + +template +struct deserialize_arg_with_adapter { +static GRunArg exec(cv::gapi::s11n::IIStream&) { + GAPI_Error("No suitable adapter class found during RMat/MediaFrame deserialization. " + "Please, make sure you've passed them in cv::gapi::deserialize() template"); + return GRunArg{}; +} +}; + +template +struct deserialize_runarg { +static GRunArg exec(cv::gapi::s11n::IIStream& is, uint32_t idx) { + if (idx == GRunArg::index_of()) { + // Type or void (if not found) + using TA = typename cv::util::find_adapter_impl::type; + return deserialize_arg_with_adapter::exec(is); + } else if (idx == GRunArg::index_of()) { + // Type or void (if not found) + using TA = typename cv::util::find_adapter_impl::type; + return deserialize_arg_with_adapter::exec(is); + } else { // not an adapter holding type runarg - use default deserialization + GRunArg arg; + getRunArgByIdx(is, arg, idx); + return arg; + } +} +}; + +template +inline cv::util::optional tryDeserializeCompArg(const std::string& tag, + const std::vector& sArg) { + std::unique_ptr pArgIs = cv::gapi::s11n::detail::getInStream(sArg); + return try_deserialize_comparg>::exec(tag, *pArgIs); +} + +template +cv::GCompileArgs getCompileArgs(const std::vector &sArgs) { + cv::GCompileArgs args; + + std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(sArgs); + cv::gapi::s11n::IIStream& is = *pIs; + + uint32_t sz = 0; + is >> sz; + for (uint32_t i = 0; i < sz; ++i) { + std::string tag; + is >> tag; + + std::vector sArg; + is >> sArg; + + cv::util::optional dArg = + cv::gapi::detail::tryDeserializeCompArg(tag, sArg); + + if (dArg.has_value()) + { + args.push_back(dArg.value()); + } + } + + return args; +} + +template +cv::GRunArgs getRunArgsWithAdapters(const std::vector &bytes) { + std::unique_ptr pIs = cv::gapi::s11n::detail::getInStream(bytes); + cv::gapi::s11n::IIStream& is = *pIs; + cv::GRunArgs args; + + uint32_t sz = 0; + is >> sz; + for (uint32_t i = 0; i < sz; ++i) { + uint32_t idx = 0; + is >> idx; + args.push_back(cv::gapi::detail::deserialize_runarg::exec(is, idx)); + } + + return args; +} +} // namespace detail +/** @} */ + +} // namespace gapi +} // namespace cv + +#if defined _MSC_VER +#pragma warning(pop) +#endif + +#endif // OPENCV_GAPI_S11N_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp index 13e8110bfc..760e8515f6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/s11n/base.hpp @@ -1,80 +1,80 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - -#ifndef OPENCV_GAPI_S11N_BASE_HPP -#define OPENCV_GAPI_S11N_BASE_HPP - -#include -#include - -namespace cv { -namespace gapi { - -/** - * @brief This namespace contains G-API serialization and - * deserialization functions and data structures. - */ -namespace s11n { -struct IOStream; -struct IIStream; - -namespace detail { - -//! @addtogroup gapi_serialization -//! @{ - -struct NotImplemented { -}; - -/** @brief This structure allows to implement serialization routines for custom types. - * - * The default S11N for custom types is not implemented. - * - * @note When providing an overloaded implementation for S11N with your type - * don't inherit it from NotImplemented structure. - * - * @note There are lots of overloaded >> and << operators for basic and OpenCV/G-API types - * which can be utilized when serializing a custom type. - * - * Example of usage: - * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp S11N usage - * - */ -template -struct S11N: public NotImplemented { - /** - * @brief This function allows user to serialize their custom type. - * - * @note The default overload throws an exception if called. User need to - * properly overload the function to use it. - */ - static void serialize(IOStream &, const T &) { - GAPI_Error("No serialization routine is provided!"); - } - /** - * @brief This function allows user to deserialize their custom type. - * - * @note The default overload throws an exception if called. User need to - * properly overload the function to use it. - */ - static T deserialize(IIStream &) { - GAPI_Error("No deserialization routine is provided!"); - } -}; - -/// @private -- Exclude this struct from OpenCV documentation -template struct has_S11N_spec { - static constexpr bool value = !std::is_base_of::type>>::value; -}; -//! @} gapi_serialization - -} // namespace detail -} // namespace s11n -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_S11N_BASE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + +#ifndef OPENCV_GAPI_S11N_BASE_HPP +#define OPENCV_GAPI_S11N_BASE_HPP + +#include +#include + +namespace cv { +namespace gapi { + +/** + * @brief This namespace contains G-API serialization and + * deserialization functions and data structures. + */ +namespace s11n { +struct IOStream; +struct IIStream; + +namespace detail { + +//! @addtogroup gapi_serialization +//! @{ + +struct NotImplemented { +}; + +/** @brief This structure allows to implement serialization routines for custom types. + * + * The default S11N for custom types is not implemented. + * + * @note When providing an overloaded implementation for S11N with your type + * don't inherit it from NotImplemented structure. + * + * @note There are lots of overloaded >> and << operators for basic and OpenCV/G-API types + * which can be utilized when serializing a custom type. + * + * Example of usage: + * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp S11N usage + * + */ +template +struct S11N: public NotImplemented { + /** + * @brief This function allows user to serialize their custom type. + * + * @note The default overload throws an exception if called. User need to + * properly overload the function to use it. + */ + static void serialize(IOStream &, const T &) { + GAPI_Error("No serialization routine is provided!"); + } + /** + * @brief This function allows user to deserialize their custom type. + * + * @note The default overload throws an exception if called. User need to + * properly overload the function to use it. + */ + static T deserialize(IIStream &) { + GAPI_Error("No deserialization routine is provided!"); + } +}; + +/// @private -- Exclude this struct from OpenCV documentation +template struct has_S11N_spec { + static constexpr bool value = !std::is_base_of::type>>::value; +}; +//! @} gapi_serialization + +} // namespace detail +} // namespace s11n +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_S11N_BASE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp index fce9c37436..9b00267082 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/stereo.hpp @@ -1,85 +1,85 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distereoibution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STEREO_HPP -#define OPENCV_GAPI_STEREO_HPP - -#include -#include -#include - -namespace cv { -namespace gapi { - -/** - * The enum specified format of result that you get from @ref cv::gapi::stereo. - */ -enum class StereoOutputFormat { - DEPTH_FLOAT16, ///< Floating point 16 bit value, CV_16FC1. - ///< This identifier is deprecated, use DEPTH_16F instead. - DEPTH_FLOAT32, ///< Floating point 32 bit value, CV_32FC1 - ///< This identifier is deprecated, use DEPTH_16F instead. - DISPARITY_FIXED16_11_5, ///< 16 bit signed: first bit for sign, - ///< 10 bits for integer part, - ///< 5 bits for fractional part. - ///< This identifier is deprecated, - ///< use DISPARITY_16Q_10_5 instead. - DISPARITY_FIXED16_12_4, ///< 16 bit signed: first bit for sign, - ///< 11 bits for integer part, - ///< 4 bits for fractional part. - ///< This identifier is deprecated, - ///< use DISPARITY_16Q_11_4 instead. - DEPTH_16F = DEPTH_FLOAT16, ///< Same as DEPTH_FLOAT16 - DEPTH_32F = DEPTH_FLOAT32, ///< Same as DEPTH_FLOAT32 - DISPARITY_16Q_10_5 = DISPARITY_FIXED16_11_5, ///< Same as DISPARITY_FIXED16_11_5 - DISPARITY_16Q_11_4 = DISPARITY_FIXED16_12_4 ///< Same as DISPARITY_FIXED16_12_4 -}; - - -/** - * @brief This namespace contains G-API Operation Types for Stereo and - * related functionality. - */ -namespace calib3d { - -G_TYPED_KERNEL(GStereo, , "org.opencv.stereo") { - static GMatDesc outMeta(const GMatDesc &left, const GMatDesc &right, const StereoOutputFormat of) { - GAPI_Assert(left.chan == 1); - GAPI_Assert(left.depth == CV_8U); - - GAPI_Assert(right.chan == 1); - GAPI_Assert(right.depth == CV_8U); - - switch(of) { - case StereoOutputFormat::DEPTH_FLOAT16: - return left.withDepth(CV_16FC1); - case StereoOutputFormat::DEPTH_FLOAT32: - return left.withDepth(CV_32FC1); - case StereoOutputFormat::DISPARITY_FIXED16_11_5: - case StereoOutputFormat::DISPARITY_FIXED16_12_4: - return left.withDepth(CV_16SC1); - default: - GAPI_Error("Unknown output format!"); - } - } -}; - -} // namespace calib3d - -/** @brief Computes disparity/depth map for the specified stereo-pair. -The function computes disparity or depth map depending on passed StereoOutputFormat argument. - -@param left 8-bit single-channel left image of @ref CV_8UC1 type. -@param right 8-bit single-channel right image of @ref CV_8UC1 type. -@param of enum to specified output kind: depth or disparity and corresponding type -*/ -GAPI_EXPORTS GMat stereo(const GMat& left, - const GMat& right, - const StereoOutputFormat of = StereoOutputFormat::DEPTH_FLOAT32); -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STEREO_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distereoibution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STEREO_HPP +#define OPENCV_GAPI_STEREO_HPP + +#include +#include +#include + +namespace cv { +namespace gapi { + +/** + * The enum specified format of result that you get from @ref cv::gapi::stereo. + */ +enum class StereoOutputFormat { + DEPTH_FLOAT16, ///< Floating point 16 bit value, CV_16FC1. + ///< This identifier is deprecated, use DEPTH_16F instead. + DEPTH_FLOAT32, ///< Floating point 32 bit value, CV_32FC1 + ///< This identifier is deprecated, use DEPTH_16F instead. + DISPARITY_FIXED16_11_5, ///< 16 bit signed: first bit for sign, + ///< 10 bits for integer part, + ///< 5 bits for fractional part. + ///< This identifier is deprecated, + ///< use DISPARITY_16Q_10_5 instead. + DISPARITY_FIXED16_12_4, ///< 16 bit signed: first bit for sign, + ///< 11 bits for integer part, + ///< 4 bits for fractional part. + ///< This identifier is deprecated, + ///< use DISPARITY_16Q_11_4 instead. + DEPTH_16F = DEPTH_FLOAT16, ///< Same as DEPTH_FLOAT16 + DEPTH_32F = DEPTH_FLOAT32, ///< Same as DEPTH_FLOAT32 + DISPARITY_16Q_10_5 = DISPARITY_FIXED16_11_5, ///< Same as DISPARITY_FIXED16_11_5 + DISPARITY_16Q_11_4 = DISPARITY_FIXED16_12_4 ///< Same as DISPARITY_FIXED16_12_4 +}; + + +/** + * @brief This namespace contains G-API Operation Types for Stereo and + * related functionality. + */ +namespace calib3d { + +G_TYPED_KERNEL(GStereo, , "org.opencv.stereo") { + static GMatDesc outMeta(const GMatDesc &left, const GMatDesc &right, const StereoOutputFormat of) { + GAPI_Assert(left.chan == 1); + GAPI_Assert(left.depth == CV_8U); + + GAPI_Assert(right.chan == 1); + GAPI_Assert(right.depth == CV_8U); + + switch(of) { + case StereoOutputFormat::DEPTH_FLOAT16: + return left.withDepth(CV_16FC1); + case StereoOutputFormat::DEPTH_FLOAT32: + return left.withDepth(CV_32FC1); + case StereoOutputFormat::DISPARITY_FIXED16_11_5: + case StereoOutputFormat::DISPARITY_FIXED16_12_4: + return left.withDepth(CV_16SC1); + default: + GAPI_Error("Unknown output format!"); + } + } +}; + +} // namespace calib3d + +/** @brief Computes disparity/depth map for the specified stereo-pair. +The function computes disparity or depth map depending on passed StereoOutputFormat argument. + +@param left 8-bit single-channel left image of @ref CV_8UC1 type. +@param right 8-bit single-channel right image of @ref CV_8UC1 type. +@param of enum to specified output kind: depth or disparity and corresponding type +*/ +GAPI_EXPORTS GMat stereo(const GMat& left, + const GMat& right, + const StereoOutputFormat of = StereoOutputFormat::DEPTH_FLOAT32); +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STEREO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp index 6ceb395733..9c2185c1ab 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/cap.hpp @@ -1,149 +1,149 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_CAP_HPP -#define OPENCV_GAPI_STREAMING_CAP_HPP - -/** - * YOUR ATTENTION PLEASE! - * - * This is a header-only implementation of cv::VideoCapture-based - * Stream source. It is not built by default with G-API as G-API - * doesn't depend on videoio module. - * - * If you want to use it in your application, please make sure - * videioio is available in your OpenCV package and is linked to your - * application. - * - * Note for developers: please don't put videoio dependency in G-API - * because of this file. - */ -#include -#include - -#include -#include -#include - -namespace cv { -namespace gapi { -namespace wip { - -/** - * @brief OpenCV's VideoCapture-based streaming source. - * - * This class implements IStreamSource interface. - * Its constructor takes the same parameters as cv::VideoCapture does. - * - * Please make sure that videoio OpenCV module is available before using - * this in your application (G-API doesn't depend on it directly). - * - * @note stream sources are passed to G-API via shared pointers, so - * please gapi::make_src<> to create objects and ptr() to pass a - * GCaptureSource to cv::gin(). - */ -class GCaptureSource: public IStreamSource -{ -public: - explicit GCaptureSource(int id, const std::map &properties = {}) - : cap(id) { prep(properties); } - - explicit GCaptureSource(const std::string &path, - const std::map &properties = {}) - : cap(path) { prep(properties); } - - void set(int propid, double value) { - cap.set(propid, value); - } - - // TODO: Add more constructor overloads to make it - // fully compatible with VideoCapture's interface. - -protected: - cv::VideoCapture cap; - cv::Mat first; - bool first_pulled = false; - int64_t counter = 0; - - void prep(const std::map &properties) - { - for (const auto &it : properties) { - cap.set(it.first, it.second); - } - - // Prepare first frame to report its meta to engine - // when needed - GAPI_Assert(first.empty()); - cv::Mat tmp; - if (!cap.read(tmp)) - { - GAPI_Error("Couldn't grab the very first frame"); - } - // NOTE: Some decode/media VideoCapture backends continue - // owning the video buffer under cv::Mat so in order to - // process it safely in a highly concurrent pipeline, clone() - // is the only right way. - first = tmp.clone(); - } - - virtual bool pull(cv::gapi::wip::Data &data) override - { - if (!first_pulled) - { - GAPI_Assert(!first.empty()); - first_pulled = true; - data = first; // no need to clone here since it was cloned already - } - else - { - if (!cap.isOpened()) return false; - - cv::Mat frame; - if (!cap.read(frame)) - { - // end-of-stream happened - return false; - } - // Same reason to clone as in prep() - data = frame.clone(); - } - // Tag data with seq_id/ts - const auto now = std::chrono::system_clock::now(); - const auto dur = std::chrono::duration_cast - (now.time_since_epoch()); - data.meta[cv::gapi::streaming::meta_tag::timestamp] = int64_t{dur.count()}; - data.meta[cv::gapi::streaming::meta_tag::seq_id] = int64_t{counter++}; - return true; - } - - virtual GMetaArg descr_of() const override - { - GAPI_Assert(!first.empty()); - return cv::GMetaArg{cv::descr_of(first)}; - } -}; - -// NB: Overload for using from python -GAPI_EXPORTS_W cv::Ptr -inline make_capture_src(const std::string& path, - const std::map& properties = {}) -{ - return make_src(path, properties); -} - -// NB: Overload for using from python -GAPI_EXPORTS_W cv::Ptr -inline make_capture_src(const int id, - const std::map& properties = {}) -{ - return make_src(id, properties); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_CAP_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_CAP_HPP +#define OPENCV_GAPI_STREAMING_CAP_HPP + +/** + * YOUR ATTENTION PLEASE! + * + * This is a header-only implementation of cv::VideoCapture-based + * Stream source. It is not built by default with G-API as G-API + * doesn't depend on videoio module. + * + * If you want to use it in your application, please make sure + * videioio is available in your OpenCV package and is linked to your + * application. + * + * Note for developers: please don't put videoio dependency in G-API + * because of this file. + */ +#include +#include + +#include +#include +#include + +namespace cv { +namespace gapi { +namespace wip { + +/** + * @brief OpenCV's VideoCapture-based streaming source. + * + * This class implements IStreamSource interface. + * Its constructor takes the same parameters as cv::VideoCapture does. + * + * Please make sure that videoio OpenCV module is available before using + * this in your application (G-API doesn't depend on it directly). + * + * @note stream sources are passed to G-API via shared pointers, so + * please gapi::make_src<> to create objects and ptr() to pass a + * GCaptureSource to cv::gin(). + */ +class GCaptureSource: public IStreamSource +{ +public: + explicit GCaptureSource(int id, const std::map &properties = {}) + : cap(id) { prep(properties); } + + explicit GCaptureSource(const std::string &path, + const std::map &properties = {}) + : cap(path) { prep(properties); } + + void set(int propid, double value) { + cap.set(propid, value); + } + + // TODO: Add more constructor overloads to make it + // fully compatible with VideoCapture's interface. + +protected: + cv::VideoCapture cap; + cv::Mat first; + bool first_pulled = false; + int64_t counter = 0; + + void prep(const std::map &properties) + { + for (const auto &it : properties) { + cap.set(it.first, it.second); + } + + // Prepare first frame to report its meta to engine + // when needed + GAPI_Assert(first.empty()); + cv::Mat tmp; + if (!cap.read(tmp)) + { + GAPI_Error("Couldn't grab the very first frame"); + } + // NOTE: Some decode/media VideoCapture backends continue + // owning the video buffer under cv::Mat so in order to + // process it safely in a highly concurrent pipeline, clone() + // is the only right way. + first = tmp.clone(); + } + + virtual bool pull(cv::gapi::wip::Data &data) override + { + if (!first_pulled) + { + GAPI_Assert(!first.empty()); + first_pulled = true; + data = first; // no need to clone here since it was cloned already + } + else + { + if (!cap.isOpened()) return false; + + cv::Mat frame; + if (!cap.read(frame)) + { + // end-of-stream happened + return false; + } + // Same reason to clone as in prep() + data = frame.clone(); + } + // Tag data with seq_id/ts + const auto now = std::chrono::system_clock::now(); + const auto dur = std::chrono::duration_cast + (now.time_since_epoch()); + data.meta[cv::gapi::streaming::meta_tag::timestamp] = int64_t{dur.count()}; + data.meta[cv::gapi::streaming::meta_tag::seq_id] = int64_t{counter++}; + return true; + } + + virtual GMetaArg descr_of() const override + { + GAPI_Assert(!first.empty()); + return cv::GMetaArg{cv::descr_of(first)}; + } +}; + +// NB: Overload for using from python +GAPI_EXPORTS_W cv::Ptr +inline make_capture_src(const std::string& path, + const std::map& properties = {}) +{ + return make_src(path, properties); +} + +// NB: Overload for using from python +GAPI_EXPORTS_W cv::Ptr +inline make_capture_src(const int id, + const std::map& properties = {}) +{ + return make_src(id, properties); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_CAP_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp index eebb9d8328..0e04f5beb9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/desync.hpp @@ -1,86 +1,86 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020-2021 Intel Corporation - - -#ifndef OPENCV_GAPI_GSTREAMING_DESYNC_HPP -#define OPENCV_GAPI_GSTREAMING_DESYNC_HPP - -#include - -#include -#include -#include -#include -#include - -namespace cv { -namespace gapi { -namespace streaming { - -namespace detail { -struct GDesync { - static const char *id() { - return "org.opencv.streaming.desync"; - } - - // An universal yield for desync. - // Yields output objects according to the input Types... - // Reuses gkernel machinery. - // FIXME: This function can be generic and declared in gkernel.hpp - // (it is there already, but a part of GKernelType[M] - template - static std::tuple yield(cv::GCall &call, cv::detail::Seq) { - return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); - } -}; - -template -G desync(const G &g) { - cv::GKernel k{ - GDesync::id() // kernel id - , "" // kernel tag - , [](const GMetaArgs &a, const GArgs &) {return a;} // outMeta callback - , {cv::detail::GTypeTraits::shape} // output Shape - , {cv::detail::GTypeTraits::op_kind} // input data kinds - , {cv::detail::GObtainCtor::get()} // output template ctors - , {cv::detail::GTypeTraits::op_kind} // output data kinds - }; - cv::GCall call(std::move(k)); - call.pass(g); - return std::get<0>(GDesync::yield(call, cv::detail::MkSeq<1>::type())); -} -} // namespace detail - -/** - * @brief Starts a desynchronized branch in the graph. - * - * This operation takes a single G-API data object and returns a - * graph-level "duplicate" of this object. - * - * Operations which use this data object can be desynchronized - * from the rest of the graph. - * - * This operation has no effect when a GComputation is compiled with - * regular cv::GComputation::compile(), since cv::GCompiled objects - * always produce their full output vectors. - * - * This operation only makes sense when a GComputation is compiled in - * streaming mode with cv::GComputation::compileStreaming(). If this - * operation is used and there are desynchronized outputs, the user - * should use a special version of cv::GStreamingCompiled::pull() - * which produces an array of cv::util::optional<> objects. - * - * @note This feature is highly experimental now and is currently - * limited to a single GMat/GFrame argument only. - */ -GAPI_EXPORTS GMat desync(const GMat &g); -GAPI_EXPORTS GFrame desync(const GFrame &f); - -} // namespace streaming -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GSTREAMING_DESYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020-2021 Intel Corporation + + +#ifndef OPENCV_GAPI_GSTREAMING_DESYNC_HPP +#define OPENCV_GAPI_GSTREAMING_DESYNC_HPP + +#include + +#include +#include +#include +#include +#include + +namespace cv { +namespace gapi { +namespace streaming { + +namespace detail { +struct GDesync { + static const char *id() { + return "org.opencv.streaming.desync"; + } + + // An universal yield for desync. + // Yields output objects according to the input Types... + // Reuses gkernel machinery. + // FIXME: This function can be generic and declared in gkernel.hpp + // (it is there already, but a part of GKernelType[M] + template + static std::tuple yield(cv::GCall &call, cv::detail::Seq) { + return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); + } +}; + +template +G desync(const G &g) { + cv::GKernel k{ + GDesync::id() // kernel id + , "" // kernel tag + , [](const GMetaArgs &a, const GArgs &) {return a;} // outMeta callback + , {cv::detail::GTypeTraits::shape} // output Shape + , {cv::detail::GTypeTraits::op_kind} // input data kinds + , {cv::detail::GObtainCtor::get()} // output template ctors + , {cv::detail::GTypeTraits::op_kind} // output data kinds + }; + cv::GCall call(std::move(k)); + call.pass(g); + return std::get<0>(GDesync::yield(call, cv::detail::MkSeq<1>::type())); +} +} // namespace detail + +/** + * @brief Starts a desynchronized branch in the graph. + * + * This operation takes a single G-API data object and returns a + * graph-level "duplicate" of this object. + * + * Operations which use this data object can be desynchronized + * from the rest of the graph. + * + * This operation has no effect when a GComputation is compiled with + * regular cv::GComputation::compile(), since cv::GCompiled objects + * always produce their full output vectors. + * + * This operation only makes sense when a GComputation is compiled in + * streaming mode with cv::GComputation::compileStreaming(). If this + * operation is used and there are desynchronized outputs, the user + * should use a special version of cv::GStreamingCompiled::pull() + * which produces an array of cv::util::optional<> objects. + * + * @note This feature is highly experimental now and is currently + * limited to a single GMat/GFrame argument only. + */ +GAPI_EXPORTS GMat desync(const GMat &g); +GAPI_EXPORTS GFrame desync(const GFrame &f); + +} // namespace streaming +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GSTREAMING_DESYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp index 27bd110ac2..739a3852a6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/format.hpp @@ -1,94 +1,94 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_GSTREAMING_FORMAT_HPP -#define OPENCV_GAPI_GSTREAMING_FORMAT_HPP - -#include // GKernelPackage - -namespace cv { -namespace gapi { -namespace streaming { - -GAPI_EXPORTS cv::GKernelPackage kernels(); - -G_API_OP(GBGR, , "org.opencv.streaming.BGR") -{ - static GMatDesc outMeta(const GFrameDesc& in) { return GMatDesc{CV_8U, 3, in.size}; } -}; - -G_API_OP(GY, , "org.opencv.streaming.Y") { - static GMatDesc outMeta(const GFrameDesc& frameDesc) { - return GMatDesc { CV_8U, 1, frameDesc.size , false }; - } -}; - -G_API_OP(GUV, , "org.opencv.streaming.UV") { - static GMatDesc outMeta(const GFrameDesc& frameDesc) { - return GMatDesc { CV_8U, 2, cv::Size(frameDesc.size.width / 2, frameDesc.size.height / 2), - false }; - } -}; - -/** @brief Gets bgr plane from input frame - -@note Function textual ID is "org.opencv.streaming.BGR" - -@param in Input frame -@return Image in BGR format -*/ -GAPI_EXPORTS cv::GMat BGR(const cv::GFrame& in); - -/** @brief Extracts Y plane from media frame. - -Output image is 8-bit 1-channel image of @ref CV_8UC1. - -@note Function textual ID is "org.opencv.streaming.Y" - -@param frame input media frame. -*/ -GAPI_EXPORTS GMat Y(const cv::GFrame& frame); - -/** @brief Extracts UV plane from media frame. - -Output image is 8-bit 2-channel image of @ref CV_8UC2. - -@note Function textual ID is "org.opencv.streaming.UV" - -@param frame input media frame. -*/ -GAPI_EXPORTS GMat UV(const cv::GFrame& frame); -} // namespace streaming - -//! @addtogroup gapi_transform -//! @{ -/** @brief Makes a copy of the input image. Note that this copy may be not real -(no actual data copied). Use this function to maintain graph contracts, -e.g when graph's input needs to be passed directly to output, like in Streaming mode. - -@note Function textual ID is "org.opencv.streaming.copy" - -@param in Input image -@return Copy of the input -*/ -GAPI_EXPORTS_W GMat copy(const GMat& in); - -/** @brief Makes a copy of the input frame. Note that this copy may be not real -(no actual data copied). Use this function to maintain graph contracts, -e.g when graph's input needs to be passed directly to output, like in Streaming mode. - -@note Function textual ID is "org.opencv.streaming.copy" - -@param in Input frame -@return Copy of the input -*/ -GAPI_EXPORTS GFrame copy(const GFrame& in); -//! @} gapi_transform - -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GSTREAMING_FORMAT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_GSTREAMING_FORMAT_HPP +#define OPENCV_GAPI_GSTREAMING_FORMAT_HPP + +#include // GKernelPackage + +namespace cv { +namespace gapi { +namespace streaming { + +GAPI_EXPORTS cv::GKernelPackage kernels(); + +G_API_OP(GBGR, , "org.opencv.streaming.BGR") +{ + static GMatDesc outMeta(const GFrameDesc& in) { return GMatDesc{CV_8U, 3, in.size}; } +}; + +G_API_OP(GY, , "org.opencv.streaming.Y") { + static GMatDesc outMeta(const GFrameDesc& frameDesc) { + return GMatDesc { CV_8U, 1, frameDesc.size , false }; + } +}; + +G_API_OP(GUV, , "org.opencv.streaming.UV") { + static GMatDesc outMeta(const GFrameDesc& frameDesc) { + return GMatDesc { CV_8U, 2, cv::Size(frameDesc.size.width / 2, frameDesc.size.height / 2), + false }; + } +}; + +/** @brief Gets bgr plane from input frame + +@note Function textual ID is "org.opencv.streaming.BGR" + +@param in Input frame +@return Image in BGR format +*/ +GAPI_EXPORTS cv::GMat BGR(const cv::GFrame& in); + +/** @brief Extracts Y plane from media frame. + +Output image is 8-bit 1-channel image of @ref CV_8UC1. + +@note Function textual ID is "org.opencv.streaming.Y" + +@param frame input media frame. +*/ +GAPI_EXPORTS GMat Y(const cv::GFrame& frame); + +/** @brief Extracts UV plane from media frame. + +Output image is 8-bit 2-channel image of @ref CV_8UC2. + +@note Function textual ID is "org.opencv.streaming.UV" + +@param frame input media frame. +*/ +GAPI_EXPORTS GMat UV(const cv::GFrame& frame); +} // namespace streaming + +//! @addtogroup gapi_transform +//! @{ +/** @brief Makes a copy of the input image. Note that this copy may be not real +(no actual data copied). Use this function to maintain graph contracts, +e.g when graph's input needs to be passed directly to output, like in Streaming mode. + +@note Function textual ID is "org.opencv.streaming.copy" + +@param in Input image +@return Copy of the input +*/ +GAPI_EXPORTS_W GMat copy(const GMat& in); + +/** @brief Makes a copy of the input frame. Note that this copy may be not real +(no actual data copied). Use this function to maintain graph contracts, +e.g when graph's input needs to be passed directly to output, like in Streaming mode. + +@note Function textual ID is "org.opencv.streaming.copy" + +@param in Input frame +@return Copy of the input +*/ +GAPI_EXPORTS GFrame copy(const GFrame& in); +//! @} gapi_transform + +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GSTREAMING_FORMAT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp index d70b783c84..c566656cb6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamerpipeline.hpp @@ -1,59 +1,59 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP -#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP - -#include -#include - -#include -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace gst { - -class GAPI_EXPORTS_W GStreamerPipeline -{ -public: - class Priv; - - GAPI_WRAP explicit GStreamerPipeline(const std::string& pipeline); - IStreamSource::Ptr getStreamingSource(const std::string& appsinkName, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT); - virtual ~GStreamerPipeline(); - -protected: - explicit GStreamerPipeline(std::unique_ptr priv); - - std::unique_ptr m_priv; -}; - -} // namespace gst - -using GStreamerPipeline = gst::GStreamerPipeline; - -// NB: Function for using from python -// FIXME: a separate function is created due to absence of wrappers for `shared_ptr<> ` -// Ideally would be to wrap the `GStreamerPipeline::getStreamingSource()` method as is -GAPI_EXPORTS_W cv::Ptr -inline get_streaming_source(cv::Ptr& pipeline, - const std::string& appsinkName, - const GStreamerSource::OutputType outputType - = GStreamerSource::OutputType::MAT) -{ - return pipeline->getStreamingSource(appsinkName, outputType); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP +#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP + +#include +#include + +#include +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace gst { + +class GAPI_EXPORTS_W GStreamerPipeline +{ +public: + class Priv; + + GAPI_WRAP explicit GStreamerPipeline(const std::string& pipeline); + IStreamSource::Ptr getStreamingSource(const std::string& appsinkName, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT); + virtual ~GStreamerPipeline(); + +protected: + explicit GStreamerPipeline(std::unique_ptr priv); + + std::unique_ptr m_priv; +}; + +} // namespace gst + +using GStreamerPipeline = gst::GStreamerPipeline; + +// NB: Function for using from python +// FIXME: a separate function is created due to absence of wrappers for `shared_ptr<> ` +// Ideally would be to wrap the `GStreamerPipeline::getStreamingSource()` method as is +GAPI_EXPORTS_W cv::Ptr +inline get_streaming_source(cv::Ptr& pipeline, + const std::string& appsinkName, + const GStreamerSource::OutputType outputType + = GStreamerSource::OutputType::MAT) +{ + return pipeline->getStreamingSource(appsinkName, outputType); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERPIPELINE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp index 266131c934..8b8a5ae312 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/gstreamer/gstreamersource.hpp @@ -1,97 +1,97 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP -#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP - -#include -#include - -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace gst { - -/** - * @brief OpenCV's GStreamer streaming source. - * Streams cv::Mat-s/cv::MediaFrame from passed GStreamer pipeline. - * - * This class implements IStreamSource interface. - * - * To create GStreamerSource instance you need to pass 'pipeline' and, optionally, 'outputType' - * arguments into constructor. - * 'pipeline' should represent GStreamer pipeline in form of textual description. - * Almost any custom pipeline is supported which can be successfully ran via gst-launch. - * The only two limitations are: - * - there should be __one__ appsink element in the pipeline to pass data to OpenCV app. - * Pipeline can actually contain many sink elements, but it must have one and only one - * appsink among them. - * - * - data passed to appsink should be video-frame in NV12 or GRAY8 format. - * - * 'outputType' is used to select type of output data to produce: 'cv::MediaFrame' or 'cv::Mat'. - * To produce 'cv::MediaFrame'-s you need to pass 'GStreamerSource::OutputType::FRAME' and, - * correspondingly, 'GStreamerSource::OutputType::MAT' to produce 'cv::Mat'-s. - * Please note, that in the last case, output 'cv::Mat' will be of BGR format, internal conversion - * from NV12 / GRAY8 GStreamer data will happen. - * Default value for 'outputType' is 'GStreamerSource::OutputType::MAT'. - * - * @note Stream sources are passed to G-API via shared pointers, so please use gapi::make_src<> - * to create objects and ptr() to pass a GStreamerSource to cv::gin(). - * - * @note You need to build OpenCV with GStreamer support to use this class. - */ - -class GStreamerPipelineFacade; - -class GAPI_EXPORTS GStreamerSource : public IStreamSource -{ -public: - class Priv; - - // Indicates what type of data should be produced by GStreamerSource: cv::MediaFrame or cv::Mat - enum class OutputType { - FRAME, - MAT - }; - - GStreamerSource(const std::string& pipeline, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT); - GStreamerSource(std::shared_ptr pipeline, - const std::string& appsinkName, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT); - - bool pull(cv::gapi::wip::Data& data) override; - GMetaArg descr_of() const override; - ~GStreamerSource() override; - -protected: - explicit GStreamerSource(std::unique_ptr priv); - - std::unique_ptr m_priv; -}; - -} // namespace gst - -using GStreamerSource = gst::GStreamerSource; - -// NB: Overload for using from python -GAPI_EXPORTS_W cv::Ptr -inline make_gst_src(const std::string& pipeline, - const GStreamerSource::OutputType outputType = - GStreamerSource::OutputType::MAT) -{ - return make_src(pipeline, outputType); -} -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP +#define OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP + +#include +#include + +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace gst { + +/** + * @brief OpenCV's GStreamer streaming source. + * Streams cv::Mat-s/cv::MediaFrame from passed GStreamer pipeline. + * + * This class implements IStreamSource interface. + * + * To create GStreamerSource instance you need to pass 'pipeline' and, optionally, 'outputType' + * arguments into constructor. + * 'pipeline' should represent GStreamer pipeline in form of textual description. + * Almost any custom pipeline is supported which can be successfully ran via gst-launch. + * The only two limitations are: + * - there should be __one__ appsink element in the pipeline to pass data to OpenCV app. + * Pipeline can actually contain many sink elements, but it must have one and only one + * appsink among them. + * + * - data passed to appsink should be video-frame in NV12 or GRAY8 format. + * + * 'outputType' is used to select type of output data to produce: 'cv::MediaFrame' or 'cv::Mat'. + * To produce 'cv::MediaFrame'-s you need to pass 'GStreamerSource::OutputType::FRAME' and, + * correspondingly, 'GStreamerSource::OutputType::MAT' to produce 'cv::Mat'-s. + * Please note, that in the last case, output 'cv::Mat' will be of BGR format, internal conversion + * from NV12 / GRAY8 GStreamer data will happen. + * Default value for 'outputType' is 'GStreamerSource::OutputType::MAT'. + * + * @note Stream sources are passed to G-API via shared pointers, so please use gapi::make_src<> + * to create objects and ptr() to pass a GStreamerSource to cv::gin(). + * + * @note You need to build OpenCV with GStreamer support to use this class. + */ + +class GStreamerPipelineFacade; + +class GAPI_EXPORTS GStreamerSource : public IStreamSource +{ +public: + class Priv; + + // Indicates what type of data should be produced by GStreamerSource: cv::MediaFrame or cv::Mat + enum class OutputType { + FRAME, + MAT + }; + + GStreamerSource(const std::string& pipeline, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT); + GStreamerSource(std::shared_ptr pipeline, + const std::string& appsinkName, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT); + + bool pull(cv::gapi::wip::Data& data) override; + GMetaArg descr_of() const override; + ~GStreamerSource() override; + +protected: + explicit GStreamerSource(std::unique_ptr priv); + + std::unique_ptr m_priv; +}; + +} // namespace gst + +using GStreamerSource = gst::GStreamerSource; + +// NB: Overload for using from python +GAPI_EXPORTS_W cv::Ptr +inline make_gst_src(const std::string& pipeline, + const GStreamerSource::OutputType outputType = + GStreamerSource::OutputType::MAT) +{ + return make_src(pipeline, outputType); +} +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_GSTREAMER_GSTREAMERSOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp index 5cae3b4938..cdd3d371cb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/meta.hpp @@ -1,80 +1,80 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_GSTREAMING_META_HPP -#define OPENCV_GAPI_GSTREAMING_META_HPP - -#include -#include -#include -#include - -namespace cv { -namespace gapi { -namespace streaming { - -// FIXME: the name is debatable -namespace meta_tag { -static constexpr const char * timestamp = "org.opencv.gapi.meta.timestamp"; -static constexpr const char * seq_id = "org.opencv.gapi.meta.seq_id"; -} // namespace meta_tag - -namespace detail { -struct GMeta { - static const char *id() { - return "org.opencv.streaming.meta"; - } - // A universal yield for meta(), same as in GDesync - template - static std::tuple yield(cv::GCall &call, cv::detail::Seq) { - return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); - } - // Also a universal outMeta stub here - static GMetaArgs getOutMeta(const GMetaArgs &args, const GArgs &) { - return args; - } -}; -} // namespace detail - -template -cv::GOpaque meta(G g, const std::string &tag) { - using O = cv::GOpaque; - cv::GKernel k{ - detail::GMeta::id() // kernel id - , tag // kernel tag. Use meta tag here - , &detail::GMeta::getOutMeta // outMeta callback - , {cv::detail::GTypeTraits::shape} // output Shape - , {cv::detail::GTypeTraits::op_kind} // input data kinds - , {cv::detail::GObtainCtor::get()} // output template ctors - , {cv::detail::GTypeTraits::op_kind} // output data kind - }; - cv::GCall call(std::move(k)); - call.pass(g); - return std::get<0>(detail::GMeta::yield(call, cv::detail::MkSeq<1>::type())); -} - -template -cv::GOpaque timestamp(G g) { - return meta(g, meta_tag::timestamp); -} - -template -cv::GOpaque seq_id(G g) { - return meta(g, meta_tag::seq_id); -} - -template -cv::GOpaque seqNo(G g) { - // Old name, compatibility only - return seq_id(g); -} - -} // namespace streaming -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_GSTREAMING_META_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_GSTREAMING_META_HPP +#define OPENCV_GAPI_GSTREAMING_META_HPP + +#include +#include +#include +#include + +namespace cv { +namespace gapi { +namespace streaming { + +// FIXME: the name is debatable +namespace meta_tag { +static constexpr const char * timestamp = "org.opencv.gapi.meta.timestamp"; +static constexpr const char * seq_id = "org.opencv.gapi.meta.seq_id"; +} // namespace meta_tag + +namespace detail { +struct GMeta { + static const char *id() { + return "org.opencv.streaming.meta"; + } + // A universal yield for meta(), same as in GDesync + template + static std::tuple yield(cv::GCall &call, cv::detail::Seq) { + return std::make_tuple(cv::detail::Yield::yield(call, IIs)...); + } + // Also a universal outMeta stub here + static GMetaArgs getOutMeta(const GMetaArgs &args, const GArgs &) { + return args; + } +}; +} // namespace detail + +template +cv::GOpaque meta(G g, const std::string &tag) { + using O = cv::GOpaque; + cv::GKernel k{ + detail::GMeta::id() // kernel id + , tag // kernel tag. Use meta tag here + , &detail::GMeta::getOutMeta // outMeta callback + , {cv::detail::GTypeTraits::shape} // output Shape + , {cv::detail::GTypeTraits::op_kind} // input data kinds + , {cv::detail::GObtainCtor::get()} // output template ctors + , {cv::detail::GTypeTraits::op_kind} // output data kind + }; + cv::GCall call(std::move(k)); + call.pass(g); + return std::get<0>(detail::GMeta::yield(call, cv::detail::MkSeq<1>::type())); +} + +template +cv::GOpaque timestamp(G g) { + return meta(g, meta_tag::timestamp); +} + +template +cv::GOpaque seq_id(G g) { + return meta(g, meta_tag::seq_id); +} + +template +cv::GOpaque seqNo(G g) { + // Old name, compatibility only + return seq_id(g); +} + +} // namespace streaming +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_GSTREAMING_META_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp index 0f850198b6..b670aebd1d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/accel_types.hpp @@ -1,76 +1,76 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2022 Intel Corporation - -#ifndef GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP -#define GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP - -#include -#include - -#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -enum class AccelType: uint8_t { - HOST, - DX11, - VAAPI, - - LAST_VALUE = std::numeric_limits::max() -}; - -GAPI_EXPORTS const char* to_cstring(AccelType type); - -struct IDeviceSelector; -struct GAPI_EXPORTS Device { - friend struct IDeviceSelector; - using Ptr = void*; - - ~Device(); - const std::string& get_name() const; - Ptr get_ptr() const; - AccelType get_type() const; -private: - Device(Ptr device_ptr, const std::string& device_name, - AccelType device_type); - - std::string name; - Ptr ptr; - AccelType type; -}; - -struct GAPI_EXPORTS Context { - friend struct IDeviceSelector; - using Ptr = void*; - - ~Context(); - Ptr get_ptr() const; - AccelType get_type() const; -private: - Context(Ptr ctx_ptr, AccelType ctx_type); - Ptr ptr; - AccelType type; -}; - -GAPI_EXPORTS Device create_host_device(); -GAPI_EXPORTS Context create_host_context(); - -GAPI_EXPORTS Device create_dx11_device(Device::Ptr device_ptr, - const std::string& device_name); -GAPI_EXPORTS Context create_dx11_context(Context::Ptr ctx_ptr); - -GAPI_EXPORTS Device create_vaapi_device(Device::Ptr device_ptr, - const std::string& device_name); -GAPI_EXPORTS Context create_vaapi_context(Context::Ptr ctx_ptr); -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2022 Intel Corporation + +#ifndef GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP +#define GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP + +#include +#include + +#include "opencv2/gapi/own/exports.hpp" // GAPI_EXPORTS + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +enum class AccelType: uint8_t { + HOST, + DX11, + VAAPI, + + LAST_VALUE = std::numeric_limits::max() +}; + +GAPI_EXPORTS const char* to_cstring(AccelType type); + +struct IDeviceSelector; +struct GAPI_EXPORTS Device { + friend struct IDeviceSelector; + using Ptr = void*; + + ~Device(); + const std::string& get_name() const; + Ptr get_ptr() const; + AccelType get_type() const; +private: + Device(Ptr device_ptr, const std::string& device_name, + AccelType device_type); + + std::string name; + Ptr ptr; + AccelType type; +}; + +struct GAPI_EXPORTS Context { + friend struct IDeviceSelector; + using Ptr = void*; + + ~Context(); + Ptr get_ptr() const; + AccelType get_type() const; +private: + Context(Ptr ctx_ptr, AccelType ctx_type); + Ptr ptr; + AccelType type; +}; + +GAPI_EXPORTS Device create_host_device(); +GAPI_EXPORTS Context create_host_context(); + +GAPI_EXPORTS Device create_dx11_device(Device::Ptr device_ptr, + const std::string& device_name); +GAPI_EXPORTS Context create_dx11_context(Context::Ptr ctx_ptr); + +GAPI_EXPORTS Device create_vaapi_device(Device::Ptr device_ptr, + const std::string& device_name); +GAPI_EXPORTS Context create_vaapi_context(Context::Ptr ctx_ptr); +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // GAPI_STREAMING_ONEVPL_ACCEL_TYPES_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp index b55f88e617..0db9a86e58 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/cfg_params.hpp @@ -1,209 +1,209 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP -#define OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP - -#include -#include -#include - -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -/** - * @brief Public class is using for creation of onevpl::GSource instances. - * - * Class members available through methods @ref CfgParam::get_name() and @ref CfgParam::get_value() are used by - * onevpl::GSource inner logic to create or find oneVPL particular implementation - * (software/hardware, specific API version and etc.). - * - * @note Because oneVPL may provide several implementations which are satisfying with multiple (or single one) @ref CfgParam - * criteria therefore it is possible to configure `preferred` parameters. This kind of CfgParams are created - * using `is_major = false` argument in @ref CfgParam::create method and are not used by creating oneVPL particular implementations. - * Instead they fill out a "score table" to select preferable implementation from available list. Implementation are satisfying - * with most of these optional params would be chosen. - * If no one optional CfgParam params were present then first of available oneVPL implementation would be applied. - * Please get on https://spec.oneapi.io/versions/latest/elements/oneVPL/source/API_ref/VPL_disp_api_func.html?highlight=mfxcreateconfig#mfxsetconfigfilterproperty - * for using OneVPL configuration. In this schema `mfxU8 *name` represents @ref CfgParam::get_name() and - * `mfxVariant value` is @ref CfgParam::get_value() - */ -struct GAPI_EXPORTS CfgParam { - using name_t = std::string; - using value_t = cv::util::variant; - /** - * @brief frames_pool_size_name - * - * Special configuration parameter name for onevp::GSource: - * - * @note frames_pool_size_name allows to allocate surfaces pool appropriate size to keep - * decoded frames in accelerator memory ready before - * they would be consumed by onevp::GSource::pull operation. If you see - * a lot of WARNING about lack of free surface then it's time to increase - * frames_pool_size_name but be aware of accelerator free memory volume. - * If not set then MFX implementation use - * mfxFrameAllocRequest::NumFrameSuggested behavior - * - */ - static constexpr const char *frames_pool_size_name() { return "frames_pool_size"; } - static CfgParam create_frames_pool_size(size_t value); - - /** - * @brief acceleration_mode_name - * - * Special configuration parameter names for onevp::GSource: - * - * @note acceleration_mode_name allows to activate hardware acceleration & - * device memory management. - * Supported values: - * - MFX_ACCEL_MODE_VIA_D3D11 Will activate DX11 acceleration and will produces - * MediaFrames with data allocated in DX11 device memory - * - * If not set then MFX implementation will use default acceleration behavior: - * all decoding operation uses default GPU resources but MediaFrame produces - * data allocated by using host RAM - * - */ - static constexpr const char *acceleration_mode_name() { return "mfxImplDescription.AccelerationMode"; } - static CfgParam create_acceleration_mode(uint32_t value); - static CfgParam create_acceleration_mode(const char* value); - - /** - * @brief decoder_id_name - * - * Special configuration parameter names for onevp::GSource: - * - * @note decoder_id_name allows to specify VPL decoder type which MUST present - * in case of RAW video input data and MUST NOT present as CfgParam if video - * stream incapsulated into container(*.mp4, *.mkv and so on). In latter case - * onevp::GSource will determine it automatically - * Supported values: - * - MFX_CODEC_AVC - * - MFX_CODEC_HEVC - * - MFX_CODEC_MPEG2 - * - MFX_CODEC_VC1 - * - MFX_CODEC_CAPTURE - * - MFX_CODEC_VP9 - * - MFX_CODEC_AV1 - * - */ - static constexpr const char *decoder_id_name() { return "mfxImplDescription.mfxDecoderDescription.decoder.CodecID"; } - static CfgParam create_decoder_id(uint32_t value); - static CfgParam create_decoder_id(const char* value); - - static constexpr const char *implementation_name() { return "mfxImplDescription.Impl"; } - static CfgParam create_implementation(uint32_t value); - static CfgParam create_implementation(const char* value); - - - static constexpr const char *vpp_frames_pool_size_name() { return "vpp_frames_pool_size"; } - static CfgParam create_vpp_frames_pool_size(size_t value); - - static constexpr const char *vpp_in_width_name() { return "vpp.In.Width"; } - static CfgParam create_vpp_in_width(uint16_t value); - - static constexpr const char *vpp_in_height_name() { return "vpp.In.Height"; } - static CfgParam create_vpp_in_height(uint16_t value); - - static constexpr const char *vpp_in_crop_x_name() { return "vpp.In.CropX"; } - static CfgParam create_vpp_in_crop_x(uint16_t value); - - static constexpr const char *vpp_in_crop_y_name() { return "vpp.In.CropY"; } - static CfgParam create_vpp_in_crop_y(uint16_t value); - - static constexpr const char *vpp_in_crop_w_name() { return "vpp.In.CropW"; } - static CfgParam create_vpp_in_crop_w(uint16_t value); - - static constexpr const char *vpp_in_crop_h_name() { return "vpp.In.CropH"; } - static CfgParam create_vpp_in_crop_h(uint16_t value); - - - static constexpr const char *vpp_out_fourcc_name() { return "vpp.Out.FourCC"; } - static CfgParam create_vpp_out_fourcc(uint32_t value); - - static constexpr const char *vpp_out_chroma_format_name() { return "vpp.Out.ChromaFormat"; } - static CfgParam create_vpp_out_chroma_format(uint16_t value); - - static constexpr const char *vpp_out_width_name() { return "vpp.Out.Width"; } - static CfgParam create_vpp_out_width(uint16_t value); - - static constexpr const char *vpp_out_height_name() { return "vpp.Out.Height"; } - static CfgParam create_vpp_out_height(uint16_t value); - - static constexpr const char *vpp_out_crop_x_name() { return "vpp.Out.CropX"; } - static CfgParam create_vpp_out_crop_x(uint16_t value); - - static constexpr const char *vpp_out_crop_y_name() { return "vpp.Out.CropY"; } - static CfgParam create_vpp_out_crop_y(uint16_t value); - - static constexpr const char *vpp_out_crop_w_name() { return "vpp.Out.CropW"; } - static CfgParam create_vpp_out_crop_w(uint16_t value); - - static constexpr const char *vpp_out_crop_h_name() { return "vpp.Out.CropH"; } - static CfgParam create_vpp_out_crop_h(uint16_t value); - - static constexpr const char *vpp_out_pic_struct_name() { return "vpp.Out.PicStruct"; } - static CfgParam create_vpp_out_pic_struct(uint16_t value); - - static constexpr const char *vpp_out_framerate_n_name() { return "vpp.Out.FrameRateExtN"; } - static CfgParam create_vpp_out_framerate_n(uint32_t value); - - static constexpr const char *vpp_out_framerate_d_name() { return "vpp.Out.FrameRateExtD"; } - static CfgParam create_vpp_out_framerate_d(uint32_t value); - - /** - * Create generic onevp::GSource configuration parameter. - * - *@param name name of parameter. - *@param value value of parameter. - *@param is_major TRUE if parameter MUST be provided by OneVPL inner implementation, FALSE for optional (for resolve multiple available implementations). - * - */ - template - static CfgParam create(const std::string& name, ValueType&& value, bool is_major = true) { - CfgParam param(name, CfgParam::value_t(std::forward(value)), is_major); - return param; - } - - struct Priv; - - const name_t& get_name() const; - const value_t& get_value() const; - bool is_major() const; - std::string to_string() const; - - bool operator==(const CfgParam& rhs) const; - bool operator< (const CfgParam& rhs) const; - bool operator!=(const CfgParam& rhs) const; - - CfgParam& operator=(const CfgParam& src); - CfgParam& operator=(CfgParam&& src); - CfgParam(const CfgParam& src); - CfgParam(CfgParam&& src); - ~CfgParam(); -private: - CfgParam(const std::string& param_name, value_t&& param_value, bool is_major_param); - std::shared_ptr m_priv; -}; - -} //namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP +#define OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP + +#include +#include +#include + +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +/** + * @brief Public class is using for creation of onevpl::GSource instances. + * + * Class members available through methods @ref CfgParam::get_name() and @ref CfgParam::get_value() are used by + * onevpl::GSource inner logic to create or find oneVPL particular implementation + * (software/hardware, specific API version and etc.). + * + * @note Because oneVPL may provide several implementations which are satisfying with multiple (or single one) @ref CfgParam + * criteria therefore it is possible to configure `preferred` parameters. This kind of CfgParams are created + * using `is_major = false` argument in @ref CfgParam::create method and are not used by creating oneVPL particular implementations. + * Instead they fill out a "score table" to select preferable implementation from available list. Implementation are satisfying + * with most of these optional params would be chosen. + * If no one optional CfgParam params were present then first of available oneVPL implementation would be applied. + * Please get on https://spec.oneapi.io/versions/latest/elements/oneVPL/source/API_ref/VPL_disp_api_func.html?highlight=mfxcreateconfig#mfxsetconfigfilterproperty + * for using OneVPL configuration. In this schema `mfxU8 *name` represents @ref CfgParam::get_name() and + * `mfxVariant value` is @ref CfgParam::get_value() + */ +struct GAPI_EXPORTS CfgParam { + using name_t = std::string; + using value_t = cv::util::variant; + /** + * @brief frames_pool_size_name + * + * Special configuration parameter name for onevp::GSource: + * + * @note frames_pool_size_name allows to allocate surfaces pool appropriate size to keep + * decoded frames in accelerator memory ready before + * they would be consumed by onevp::GSource::pull operation. If you see + * a lot of WARNING about lack of free surface then it's time to increase + * frames_pool_size_name but be aware of accelerator free memory volume. + * If not set then MFX implementation use + * mfxFrameAllocRequest::NumFrameSuggested behavior + * + */ + static constexpr const char *frames_pool_size_name() { return "frames_pool_size"; } + static CfgParam create_frames_pool_size(size_t value); + + /** + * @brief acceleration_mode_name + * + * Special configuration parameter names for onevp::GSource: + * + * @note acceleration_mode_name allows to activate hardware acceleration & + * device memory management. + * Supported values: + * - MFX_ACCEL_MODE_VIA_D3D11 Will activate DX11 acceleration and will produces + * MediaFrames with data allocated in DX11 device memory + * + * If not set then MFX implementation will use default acceleration behavior: + * all decoding operation uses default GPU resources but MediaFrame produces + * data allocated by using host RAM + * + */ + static constexpr const char *acceleration_mode_name() { return "mfxImplDescription.AccelerationMode"; } + static CfgParam create_acceleration_mode(uint32_t value); + static CfgParam create_acceleration_mode(const char* value); + + /** + * @brief decoder_id_name + * + * Special configuration parameter names for onevp::GSource: + * + * @note decoder_id_name allows to specify VPL decoder type which MUST present + * in case of RAW video input data and MUST NOT present as CfgParam if video + * stream incapsulated into container(*.mp4, *.mkv and so on). In latter case + * onevp::GSource will determine it automatically + * Supported values: + * - MFX_CODEC_AVC + * - MFX_CODEC_HEVC + * - MFX_CODEC_MPEG2 + * - MFX_CODEC_VC1 + * - MFX_CODEC_CAPTURE + * - MFX_CODEC_VP9 + * - MFX_CODEC_AV1 + * + */ + static constexpr const char *decoder_id_name() { return "mfxImplDescription.mfxDecoderDescription.decoder.CodecID"; } + static CfgParam create_decoder_id(uint32_t value); + static CfgParam create_decoder_id(const char* value); + + static constexpr const char *implementation_name() { return "mfxImplDescription.Impl"; } + static CfgParam create_implementation(uint32_t value); + static CfgParam create_implementation(const char* value); + + + static constexpr const char *vpp_frames_pool_size_name() { return "vpp_frames_pool_size"; } + static CfgParam create_vpp_frames_pool_size(size_t value); + + static constexpr const char *vpp_in_width_name() { return "vpp.In.Width"; } + static CfgParam create_vpp_in_width(uint16_t value); + + static constexpr const char *vpp_in_height_name() { return "vpp.In.Height"; } + static CfgParam create_vpp_in_height(uint16_t value); + + static constexpr const char *vpp_in_crop_x_name() { return "vpp.In.CropX"; } + static CfgParam create_vpp_in_crop_x(uint16_t value); + + static constexpr const char *vpp_in_crop_y_name() { return "vpp.In.CropY"; } + static CfgParam create_vpp_in_crop_y(uint16_t value); + + static constexpr const char *vpp_in_crop_w_name() { return "vpp.In.CropW"; } + static CfgParam create_vpp_in_crop_w(uint16_t value); + + static constexpr const char *vpp_in_crop_h_name() { return "vpp.In.CropH"; } + static CfgParam create_vpp_in_crop_h(uint16_t value); + + + static constexpr const char *vpp_out_fourcc_name() { return "vpp.Out.FourCC"; } + static CfgParam create_vpp_out_fourcc(uint32_t value); + + static constexpr const char *vpp_out_chroma_format_name() { return "vpp.Out.ChromaFormat"; } + static CfgParam create_vpp_out_chroma_format(uint16_t value); + + static constexpr const char *vpp_out_width_name() { return "vpp.Out.Width"; } + static CfgParam create_vpp_out_width(uint16_t value); + + static constexpr const char *vpp_out_height_name() { return "vpp.Out.Height"; } + static CfgParam create_vpp_out_height(uint16_t value); + + static constexpr const char *vpp_out_crop_x_name() { return "vpp.Out.CropX"; } + static CfgParam create_vpp_out_crop_x(uint16_t value); + + static constexpr const char *vpp_out_crop_y_name() { return "vpp.Out.CropY"; } + static CfgParam create_vpp_out_crop_y(uint16_t value); + + static constexpr const char *vpp_out_crop_w_name() { return "vpp.Out.CropW"; } + static CfgParam create_vpp_out_crop_w(uint16_t value); + + static constexpr const char *vpp_out_crop_h_name() { return "vpp.Out.CropH"; } + static CfgParam create_vpp_out_crop_h(uint16_t value); + + static constexpr const char *vpp_out_pic_struct_name() { return "vpp.Out.PicStruct"; } + static CfgParam create_vpp_out_pic_struct(uint16_t value); + + static constexpr const char *vpp_out_framerate_n_name() { return "vpp.Out.FrameRateExtN"; } + static CfgParam create_vpp_out_framerate_n(uint32_t value); + + static constexpr const char *vpp_out_framerate_d_name() { return "vpp.Out.FrameRateExtD"; } + static CfgParam create_vpp_out_framerate_d(uint32_t value); + + /** + * Create generic onevp::GSource configuration parameter. + * + *@param name name of parameter. + *@param value value of parameter. + *@param is_major TRUE if parameter MUST be provided by OneVPL inner implementation, FALSE for optional (for resolve multiple available implementations). + * + */ + template + static CfgParam create(const std::string& name, ValueType&& value, bool is_major = true) { + CfgParam param(name, CfgParam::value_t(std::forward(value)), is_major); + return param; + } + + struct Priv; + + const name_t& get_name() const; + const value_t& get_value() const; + bool is_major() const; + std::string to_string() const; + + bool operator==(const CfgParam& rhs) const; + bool operator< (const CfgParam& rhs) const; + bool operator!=(const CfgParam& rhs) const; + + CfgParam& operator=(const CfgParam& src); + CfgParam& operator=(CfgParam&& src); + CfgParam(const CfgParam& src); + CfgParam(CfgParam&& src); + ~CfgParam(); +private: + CfgParam(const std::string& param_name, value_t&& param_value, bool is_major_param); + std::shared_ptr m_priv; +}; + +} //namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_ONEVPL_CFG_PARAMS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp index 89f1b1a330..ec683a7527 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/data_provider_interface.hpp @@ -1,105 +1,105 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP -#define GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP -#include -#include -#include - -#include // GAPI_EXPORTS -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -struct GAPI_EXPORTS DataProviderException : public std::exception { - DataProviderException(const std::string& descr); - DataProviderException(std::string&& descr); - - virtual ~DataProviderException() = default; - virtual const char* what() const noexcept override; -private: - std::string reason; -}; - -struct GAPI_EXPORTS DataProviderSystemErrorException final : public DataProviderException { - DataProviderSystemErrorException(int error_code, const std::string& description = std::string()); - ~DataProviderSystemErrorException() = default; -}; - -struct GAPI_EXPORTS DataProviderUnsupportedException final : public DataProviderException { - DataProviderUnsupportedException(const std::string& description); - ~DataProviderUnsupportedException() = default; -}; - -struct GAPI_EXPORTS DataProviderImplementationException : public DataProviderException { - DataProviderImplementationException(const std::string& description); - ~DataProviderImplementationException() = default; -}; -/** - * @brief Public interface allows to customize extraction of video stream data - * used by onevpl::GSource instead of reading stream from file (by default). - * - * Interface implementation constructor MUST provide consistency and creates fully operable object. - * If error happened implementation MUST throw `DataProviderException` kind exceptions - * - * @note Interface implementation MUST manage stream and other constructed resources by itself to avoid any kind of leak. - * For simple interface implementation example please see `StreamDataProvider` in `tests/streaming/gapi_streaming_tests.cpp` - */ -struct GAPI_EXPORTS IDataProvider { - using Ptr = std::shared_ptr; - using mfx_codec_id_type = uint32_t; - - /** - * NB: here is supposed to be forward declaration of mfxBitstream - * But according to current oneVPL implementation it is impossible to forward - * declare untagged struct mfxBitstream. - * - * IDataProvider makes sense only for HAVE_VPL is ON and to keep IDataProvider - * interface API/ABI compliant between core library and user application layer - * let's introduce wrapper mfx_bitstream which inherits mfxBitstream in private - * G-API code section and declare forward for wrapper mfx_bitstream here - */ - struct mfx_bitstream; - - virtual ~IDataProvider() = default; - - /** - * The function is used by onevpl::GSource to extract codec id from data - * - */ - virtual mfx_codec_id_type get_mfx_codec_id() const = 0; - - /** - * The function is used by onevpl::GSource to extract binary data stream from @ref IDataProvider - * implementation. - * - * It MUST throw `DataProviderException` kind exceptions in fail cases. - * It MUST return MFX_ERR_MORE_DATA in EOF which considered as not-fail case. - * - * @param in_out_bitsream the input-output reference on MFX bitstream buffer which MUST be empty at the first request - * to allow implementation to allocate it by itself and to return back. Subsequent invocation of `fetch_bitstream_data` - * MUST use the previously used in_out_bitsream to avoid skipping rest of frames which haven't been consumed - * @return true for fetched data, false on EOF and throws exception on error - */ - virtual bool fetch_bitstream_data(std::shared_ptr &in_out_bitsream) = 0; - - /** - * The function is used by onevpl::GSource to check more binary data availability. - * - * It MUST return TRUE in case of EOF and NO_THROW exceptions. - * - * @return boolean value which detects end of stream - */ - virtual bool empty() const = 0; -}; -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP +#define GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP +#include +#include +#include + +#include // GAPI_EXPORTS +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +struct GAPI_EXPORTS DataProviderException : public std::exception { + DataProviderException(const std::string& descr); + DataProviderException(std::string&& descr); + + virtual ~DataProviderException() = default; + virtual const char* what() const noexcept override; +private: + std::string reason; +}; + +struct GAPI_EXPORTS DataProviderSystemErrorException final : public DataProviderException { + DataProviderSystemErrorException(int error_code, const std::string& description = std::string()); + ~DataProviderSystemErrorException() = default; +}; + +struct GAPI_EXPORTS DataProviderUnsupportedException final : public DataProviderException { + DataProviderUnsupportedException(const std::string& description); + ~DataProviderUnsupportedException() = default; +}; + +struct GAPI_EXPORTS DataProviderImplementationException : public DataProviderException { + DataProviderImplementationException(const std::string& description); + ~DataProviderImplementationException() = default; +}; +/** + * @brief Public interface allows to customize extraction of video stream data + * used by onevpl::GSource instead of reading stream from file (by default). + * + * Interface implementation constructor MUST provide consistency and creates fully operable object. + * If error happened implementation MUST throw `DataProviderException` kind exceptions + * + * @note Interface implementation MUST manage stream and other constructed resources by itself to avoid any kind of leak. + * For simple interface implementation example please see `StreamDataProvider` in `tests/streaming/gapi_streaming_tests.cpp` + */ +struct GAPI_EXPORTS IDataProvider { + using Ptr = std::shared_ptr; + using mfx_codec_id_type = uint32_t; + + /** + * NB: here is supposed to be forward declaration of mfxBitstream + * But according to current oneVPL implementation it is impossible to forward + * declare untagged struct mfxBitstream. + * + * IDataProvider makes sense only for HAVE_VPL is ON and to keep IDataProvider + * interface API/ABI compliant between core library and user application layer + * let's introduce wrapper mfx_bitstream which inherits mfxBitstream in private + * G-API code section and declare forward for wrapper mfx_bitstream here + */ + struct mfx_bitstream; + + virtual ~IDataProvider() = default; + + /** + * The function is used by onevpl::GSource to extract codec id from data + * + */ + virtual mfx_codec_id_type get_mfx_codec_id() const = 0; + + /** + * The function is used by onevpl::GSource to extract binary data stream from @ref IDataProvider + * implementation. + * + * It MUST throw `DataProviderException` kind exceptions in fail cases. + * It MUST return MFX_ERR_MORE_DATA in EOF which considered as not-fail case. + * + * @param in_out_bitsream the input-output reference on MFX bitstream buffer which MUST be empty at the first request + * to allow implementation to allocate it by itself and to return back. Subsequent invocation of `fetch_bitstream_data` + * MUST use the previously used in_out_bitsream to avoid skipping rest of frames which haven't been consumed + * @return true for fetched data, false on EOF and throws exception on error + */ + virtual bool fetch_bitstream_data(std::shared_ptr &in_out_bitsream) = 0; + + /** + * The function is used by onevpl::GSource to check more binary data availability. + * + * It MUST return TRUE in case of EOF and NO_THROW exceptions. + * + * @return boolean value which detects end of stream + */ + virtual bool empty() const = 0; +}; +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // GAPI_STREAMING_ONEVPL_ONEVPL_DATA_PROVIDER_INTERFACE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp index 4bb099fb3c..8b547e1aba 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/default.hpp @@ -1,29 +1,29 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2022 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP -#define OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP - -#include // GAPI_EXPORTS -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { - -/** - * @brief Provides default device selector based on config. - */ -GAPI_EXPORTS std::shared_ptr getDefaultDeviceSelector(const std::vector& cfg_params); - -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2022 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP +#define OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP + +#include // GAPI_EXPORTS +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { + +/** + * @brief Provides default device selector based on config. + */ +GAPI_EXPORTS std::shared_ptr getDefaultDeviceSelector(const std::vector& cfg_params); + +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_ONEVPL_UTILS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp index 3cde3e4483..2e2d879fba 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/device_selector_interface.hpp @@ -1,61 +1,61 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP -#define GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP - -#include -#include -#include -#include - -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { -struct GAPI_EXPORTS IDeviceSelector { - using Ptr = std::shared_ptr; - - struct GAPI_EXPORTS Score { - friend struct IDeviceSelector; - using Type = int16_t; - static constexpr Type MaxActivePriority = std::numeric_limits::max(); - static constexpr Type MinActivePriority = 0; - static constexpr Type MaxPassivePriority = MinActivePriority - 1; - static constexpr Type MinPassivePriority = std::numeric_limits::min(); - - Score(Type val); - ~Score(); - - operator Type () const; - Type get() const; - friend bool operator< (Score lhs, Score rhs) { - return lhs.get() < rhs.get(); - } - private: - Type value; - }; - - using DeviceScoreTable = std::map; - using DeviceContexts = std::vector; - - virtual ~IDeviceSelector(); - virtual DeviceScoreTable select_devices() const = 0; - virtual DeviceContexts select_context() = 0; -protected: - template - static Entity create(Args &&...args) { - return Entity(std::forward(args)...); - } -}; -} // namespace onevpl -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP +#define GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP + +#include +#include +#include +#include + +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { +struct GAPI_EXPORTS IDeviceSelector { + using Ptr = std::shared_ptr; + + struct GAPI_EXPORTS Score { + friend struct IDeviceSelector; + using Type = int16_t; + static constexpr Type MaxActivePriority = std::numeric_limits::max(); + static constexpr Type MinActivePriority = 0; + static constexpr Type MaxPassivePriority = MinActivePriority - 1; + static constexpr Type MinPassivePriority = std::numeric_limits::min(); + + Score(Type val); + ~Score(); + + operator Type () const; + Type get() const; + friend bool operator< (Score lhs, Score rhs) { + return lhs.get() < rhs.get(); + } + private: + Type value; + }; + + using DeviceScoreTable = std::map; + using DeviceContexts = std::vector; + + virtual ~IDeviceSelector(); + virtual DeviceScoreTable select_devices() const = 0; + virtual DeviceContexts select_context() = 0; +protected: + template + static Entity create(Args &&...args) { + return Entity(std::forward(args)...); + } +}; +} // namespace onevpl +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // GAPI_STREAMING_ONEVPL_DEVICE_SELECTOR_INTERFACE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp index 4d1fa2aad7..04dc2e246d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/onevpl/source.hpp @@ -1,94 +1,94 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP -#define OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP - -#include -#include -#include -#include -#include -#include - -namespace cv { -namespace gapi { -namespace wip { -namespace onevpl { -using CfgParams = std::vector; - -/** - * @brief G-API streaming source based on OneVPL implementation. - * - * This class implements IStreamSource interface. - * Its constructor takes source file path (in usual way) or @ref onevpl::IDataProvider - * interface implementation (for not file-based sources). It also allows to pass-through - * oneVPL configuration parameters by using several @ref onevpl::CfgParam. - * - * @note stream sources are passed to G-API via shared pointers, so - * please gapi::make_onevpl_src<> to create objects and ptr() to pass a - * GSource to cv::gin(). - */ -class GAPI_EXPORTS GSource : public IStreamSource -{ -public: - struct Priv; - - GSource(const std::string& filePath, - const CfgParams& cfg_params = CfgParams{}); - - GSource(const std::string& filePath, - const CfgParams& cfg_params, - const std::string& device_id, - void* accel_device_ptr, - void* accel_ctx_ptr); - - GSource(const std::string& filePath, - const CfgParams& cfg_params, - const Device &device, const Context &ctx); - - GSource(const std::string& filePath, - const CfgParams& cfg_params, - std::shared_ptr selector); - - - GSource(std::shared_ptr source, - const CfgParams& cfg_params = CfgParams{}); - - GSource(std::shared_ptr source, - const CfgParams& cfg_params, - const std::string& device_id, - void* accel_device_ptr, - void* accel_ctx_ptr); - - GSource(std::shared_ptr source, - const CfgParams& cfg_params, - std::shared_ptr selector); - - ~GSource() override; - - bool pull(cv::gapi::wip::Data& data) override; - GMetaArg descr_of() const override; - -private: - explicit GSource(std::unique_ptr&& impl); - std::unique_ptr m_priv; -}; -} // namespace onevpl - -using GVPLSource = onevpl::GSource; - -template -GAPI_EXPORTS_W cv::Ptr inline make_onevpl_src(Args&&... args) -{ - return make_src(std::forward(args)...); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP +#define OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP + +#include +#include +#include +#include +#include +#include + +namespace cv { +namespace gapi { +namespace wip { +namespace onevpl { +using CfgParams = std::vector; + +/** + * @brief G-API streaming source based on OneVPL implementation. + * + * This class implements IStreamSource interface. + * Its constructor takes source file path (in usual way) or @ref onevpl::IDataProvider + * interface implementation (for not file-based sources). It also allows to pass-through + * oneVPL configuration parameters by using several @ref onevpl::CfgParam. + * + * @note stream sources are passed to G-API via shared pointers, so + * please gapi::make_onevpl_src<> to create objects and ptr() to pass a + * GSource to cv::gin(). + */ +class GAPI_EXPORTS GSource : public IStreamSource +{ +public: + struct Priv; + + GSource(const std::string& filePath, + const CfgParams& cfg_params = CfgParams{}); + + GSource(const std::string& filePath, + const CfgParams& cfg_params, + const std::string& device_id, + void* accel_device_ptr, + void* accel_ctx_ptr); + + GSource(const std::string& filePath, + const CfgParams& cfg_params, + const Device &device, const Context &ctx); + + GSource(const std::string& filePath, + const CfgParams& cfg_params, + std::shared_ptr selector); + + + GSource(std::shared_ptr source, + const CfgParams& cfg_params = CfgParams{}); + + GSource(std::shared_ptr source, + const CfgParams& cfg_params, + const std::string& device_id, + void* accel_device_ptr, + void* accel_ctx_ptr); + + GSource(std::shared_ptr source, + const CfgParams& cfg_params, + std::shared_ptr selector); + + ~GSource() override; + + bool pull(cv::gapi::wip::Data& data) override; + GMetaArg descr_of() const override; + +private: + explicit GSource(std::unique_ptr&& impl); + std::unique_ptr m_priv; +}; +} // namespace onevpl + +using GVPLSource = onevpl::GSource; + +template +GAPI_EXPORTS_W cv::Ptr inline make_onevpl_src(Args&&... args) +{ + return make_src(std::forward(args)...); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_ONEVPL_ONEVPL_SOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp index e01902fd7f..bd385ed16e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/queue_source.hpp @@ -1,67 +1,67 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2023 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP -#define OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP - -#include // shared_ptr -#include // is_base_of - -#include // GRunArgs -#include // GMetaArg + all descr_of -#include // IStreamSource - -namespace cv { -namespace gapi { -namespace wip { -struct Data; // fwd-declare to avoid circular? header dependencies - -class GAPI_EXPORTS QueueSourceBase: public cv::gapi::wip::IStreamSource { - class Priv; - std::shared_ptr m_priv; - // FIXME: Need to understand how it works with IStreamSource's shared_from_this - // Can we avoid having too many shared_ptrs here? - -public: - explicit QueueSourceBase(const cv::GMetaArg &m); - void push(Data &&data); - virtual bool pull(Data &data) override; - virtual void halt() override; - virtual GMetaArg descr_of() const override; - virtual ~QueueSourceBase() = default; -}; - -/** - * @brief Queued streaming pipeline source. - * - */ -template -class QueueSource final: public QueueSourceBase -{ -public: - using Meta = decltype(cv::descr_of(T{})); - explicit QueueSource(Meta m) : QueueSourceBase(GMetaArg{m}) { - } - void push(T t) { - QueueSourceBase::push(Data{t}); - } -}; - -class GAPI_EXPORTS QueueInput { - std::vector > m_sources; - -public: - explicit QueueInput(const cv::GMetaArgs &args); - - void push(cv::GRunArgs &&ins); - operator cv::GRunArgs(); -}; - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2023 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP +#define OPENCV_GAPI_STREAMING_QUEUE_SOURCE_HPP + +#include // shared_ptr +#include // is_base_of + +#include // GRunArgs +#include // GMetaArg + all descr_of +#include // IStreamSource + +namespace cv { +namespace gapi { +namespace wip { +struct Data; // fwd-declare to avoid circular? header dependencies + +class GAPI_EXPORTS QueueSourceBase: public cv::gapi::wip::IStreamSource { + class Priv; + std::shared_ptr m_priv; + // FIXME: Need to understand how it works with IStreamSource's shared_from_this + // Can we avoid having too many shared_ptrs here? + +public: + explicit QueueSourceBase(const cv::GMetaArg &m); + void push(Data &&data); + virtual bool pull(Data &data) override; + virtual void halt() override; + virtual GMetaArg descr_of() const override; + virtual ~QueueSourceBase() = default; +}; + +/** + * @brief Queued streaming pipeline source. + * + */ +template +class QueueSource final: public QueueSourceBase +{ +public: + using Meta = decltype(cv::descr_of(T{})); + explicit QueueSource(Meta m) : QueueSourceBase(GMetaArg{m}) { + } + void push(T t) { + QueueSourceBase::push(Data{t}); + } +}; + +class GAPI_EXPORTS QueueInput { + std::vector > m_sources; + +public: + explicit QueueInput(const cv::GMetaArgs &args); + + void push(cv::GRunArgs &&ins); + operator cv::GRunArgs(); +}; + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp index 9b02f03ffc..267469ad1b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/source.hpp @@ -1,67 +1,67 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2019 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_SOURCE_HPP -#define OPENCV_GAPI_STREAMING_SOURCE_HPP - -#include // shared_ptr -#include // is_base_of - -#include // GMetaArg - - -namespace cv { -namespace gapi { -namespace wip { -struct Data; // forward-declaration of Data to avoid circular dependencies - -/** - * @brief Abstract streaming pipeline source. - * - * Implement this interface if you want customize the way how data is - * streaming into GStreamingCompiled. - * - * Objects implementing this interface can be passed to - * GStreamingCompiled using setSource() with cv::gin(). Regular - * compiled graphs (GCompiled) don't support input objects of this - * type. - * - * Default cv::VideoCapture-based implementation is available, see - * cv::gapi::wip::GCaptureSource. - * - * @note stream sources are passed to G-API via shared pointers, so - * please use ptr() when passing a IStreamSource implementation to - * cv::gin(). - */ -class IStreamSource: public std::enable_shared_from_this -{ -public: - using Ptr = std::shared_ptr; - Ptr ptr() { return shared_from_this(); } - virtual bool pull(Data &data) = 0; - virtual GMetaArg descr_of() const = 0; - virtual void halt() { - // Do nothing by default to maintain compatibility with the existing sources... - // In fact needs to be decorated atop of the child classes to maintain the behavior - // FIXME: Make it mandatory in OpenCV 5.0 - }; - virtual ~IStreamSource() = default; -}; - -template -IStreamSource::Ptr inline make_src(Args&&... args) -{ - static_assert(std::is_base_of::value, - "T must implement the cv::gapi::IStreamSource interface!"); - auto src_ptr = std::make_shared(std::forward(args)...); - return src_ptr->ptr(); -} - -} // namespace wip -} // namespace gapi -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2019 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_SOURCE_HPP +#define OPENCV_GAPI_STREAMING_SOURCE_HPP + +#include // shared_ptr +#include // is_base_of + +#include // GMetaArg + + +namespace cv { +namespace gapi { +namespace wip { +struct Data; // forward-declaration of Data to avoid circular dependencies + +/** + * @brief Abstract streaming pipeline source. + * + * Implement this interface if you want customize the way how data is + * streaming into GStreamingCompiled. + * + * Objects implementing this interface can be passed to + * GStreamingCompiled using setSource() with cv::gin(). Regular + * compiled graphs (GCompiled) don't support input objects of this + * type. + * + * Default cv::VideoCapture-based implementation is available, see + * cv::gapi::wip::GCaptureSource. + * + * @note stream sources are passed to G-API via shared pointers, so + * please use ptr() when passing a IStreamSource implementation to + * cv::gin(). + */ +class IStreamSource: public std::enable_shared_from_this +{ +public: + using Ptr = std::shared_ptr; + Ptr ptr() { return shared_from_this(); } + virtual bool pull(Data &data) = 0; + virtual GMetaArg descr_of() const = 0; + virtual void halt() { + // Do nothing by default to maintain compatibility with the existing sources... + // In fact needs to be decorated atop of the child classes to maintain the behavior + // FIXME: Make it mandatory in OpenCV 5.0 + }; + virtual ~IStreamSource() = default; +}; + +template +IStreamSource::Ptr inline make_src(Args&&... args) +{ + static_assert(std::is_base_of::value, + "T must implement the cv::gapi::IStreamSource interface!"); + auto src_ptr = std::make_shared(std::forward(args)...); + return src_ptr->ptr(); +} + +} // namespace wip +} // namespace gapi +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_SOURCE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp index 921a96c7cb..5801e6f00a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/streaming/sync.hpp @@ -1,30 +1,30 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2021 Intel Corporation - -#ifndef OPENCV_GAPI_STREAMING_SYNC_HPP -#define OPENCV_GAPI_STREAMING_SYNC_HPP - -namespace cv { -namespace gapi { -namespace streaming { - -enum class sync_policy { - dont_sync, - drop -}; - -} // namespace streaming -} // namespace gapi - -namespace detail { - template<> struct CompileArgTag { - static const char* tag() { return "gapi.streaming.sync_policy"; } - }; - -} // namespace detail -} // namespace cv - -#endif // OPENCV_GAPI_STREAMING_SYNC_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2021 Intel Corporation + +#ifndef OPENCV_GAPI_STREAMING_SYNC_HPP +#define OPENCV_GAPI_STREAMING_SYNC_HPP + +namespace cv { +namespace gapi { +namespace streaming { + +enum class sync_policy { + dont_sync, + drop +}; + +} // namespace streaming +} // namespace gapi + +namespace detail { + template<> struct CompileArgTag { + static const char* tag() { return "gapi.streaming.sync_policy"; } + }; + +} // namespace detail +} // namespace cv + +#endif // OPENCV_GAPI_STREAMING_SYNC_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp index d5c575ca0a..94451c7717 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/any.hpp @@ -1,190 +1,190 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_ANY_HPP -#define OPENCV_GAPI_UTIL_ANY_HPP - -#include -#include -#include -#include - -#include - -#if defined(_MSC_VER) - // disable MSVC warning on "multiple copy constructors specified" -# pragma warning(disable: 4521) -#endif - -namespace cv -{ - -namespace internal -{ - template - T down_cast(Source operand) - { -#if defined(__GXX_RTTI) || defined(_CPPRTTI) - return dynamic_cast(operand); -#else -#ifdef __GNUC__ -#warning used static cast instead of dynamic because RTTI is disabled -#else -#pragma message("WARNING: used static cast instead of dynamic because RTTI is disabled") -#endif - return static_cast(operand); -#endif - } -} - -namespace util -{ - class bad_any_cast : public std::bad_cast - { - public: - virtual const char* what() const noexcept override - { - return "Bad any cast"; - } - }; - - //modeled against C++17 std::any - - class any - { - private: - struct holder; - using holder_ptr = std::unique_ptr; - struct holder - { - virtual holder_ptr clone() = 0; - virtual ~holder() = default; - }; - - template - struct holder_impl : holder - { - value_t v; - template - holder_impl(arg_t&& a) : v(std::forward(a)) {} - holder_ptr clone() override { return holder_ptr(new holder_impl (v));} - }; - - holder_ptr hldr; - public: - template - any(value_t&& arg) : hldr(new holder_impl::type>( std::forward(arg))) {} - - any(any const& src) : hldr( src.hldr ? src.hldr->clone() : nullptr) {} - //simple hack in order not to write enable_if for the template constructor - any(any & src) : any (const_cast(src)) {} - - any() = default; - any(any&& ) = default; - - any& operator=(any&&) = default; - - any& operator=(any const& src) - { - any copy(src); - swap(*this, copy); - return *this; - } - - template - friend value_t* any_cast(any* operand); - - template - friend const value_t* any_cast(const any* operand); - - template - friend value_t& unsafe_any_cast(any& operand); - - template - friend const value_t& unsafe_any_cast(const any& operand); - - friend void swap(any & lhs, any& rhs) - { - swap(lhs.hldr, rhs.hldr); - } - - }; - - template - value_t* any_cast(any* operand) - { - auto casted = internal::down_cast::type> *>(operand->hldr.get()); - if (casted){ - return & (casted->v); - } - return nullptr; - } - - template - const value_t* any_cast(const any* operand) - { - auto casted = internal::down_cast::type> *>(operand->hldr.get()); - if (casted){ - return & (casted->v); - } - return nullptr; - } - - template - value_t& any_cast(any& operand) - { - auto ptr = any_cast(&operand); - if (ptr) - { - return *ptr; - } - - throw_error(bad_any_cast()); - } - - - template - const value_t& any_cast(const any& operand) - { - auto ptr = any_cast(&operand); - if (ptr) - { - return *ptr; - } - - throw_error(bad_any_cast()); - } - - template - inline value_t& unsafe_any_cast(any& operand) - { -#ifdef DEBUG - return any_cast(operand); -#else - return static_cast::type> *>(operand.hldr.get())->v; -#endif - } - - template - inline const value_t& unsafe_any_cast(const any& operand) - { -#ifdef DEBUG - return any_cast(operand); -#else - return static_cast::type> *>(operand.hldr.get())->v; -#endif - } - -} // namespace util -} // namespace cv - -#if defined(_MSC_VER) - // Enable "multiple copy constructors specified" back -# pragma warning(default: 4521) -#endif - -#endif // OPENCV_GAPI_UTIL_ANY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_ANY_HPP +#define OPENCV_GAPI_UTIL_ANY_HPP + +#include +#include +#include +#include + +#include + +#if defined(_MSC_VER) + // disable MSVC warning on "multiple copy constructors specified" +# pragma warning(disable: 4521) +#endif + +namespace cv +{ + +namespace internal +{ + template + T down_cast(Source operand) + { +#if defined(__GXX_RTTI) || defined(_CPPRTTI) + return dynamic_cast(operand); +#else +#ifdef __GNUC__ +#warning used static cast instead of dynamic because RTTI is disabled +#else +#pragma message("WARNING: used static cast instead of dynamic because RTTI is disabled") +#endif + return static_cast(operand); +#endif + } +} + +namespace util +{ + class bad_any_cast : public std::bad_cast + { + public: + virtual const char* what() const noexcept override + { + return "Bad any cast"; + } + }; + + //modeled against C++17 std::any + + class any + { + private: + struct holder; + using holder_ptr = std::unique_ptr; + struct holder + { + virtual holder_ptr clone() = 0; + virtual ~holder() = default; + }; + + template + struct holder_impl : holder + { + value_t v; + template + holder_impl(arg_t&& a) : v(std::forward(a)) {} + holder_ptr clone() override { return holder_ptr(new holder_impl (v));} + }; + + holder_ptr hldr; + public: + template + any(value_t&& arg) : hldr(new holder_impl::type>( std::forward(arg))) {} + + any(any const& src) : hldr( src.hldr ? src.hldr->clone() : nullptr) {} + //simple hack in order not to write enable_if for the template constructor + any(any & src) : any (const_cast(src)) {} + + any() = default; + any(any&& ) = default; + + any& operator=(any&&) = default; + + any& operator=(any const& src) + { + any copy(src); + swap(*this, copy); + return *this; + } + + template + friend value_t* any_cast(any* operand); + + template + friend const value_t* any_cast(const any* operand); + + template + friend value_t& unsafe_any_cast(any& operand); + + template + friend const value_t& unsafe_any_cast(const any& operand); + + friend void swap(any & lhs, any& rhs) + { + swap(lhs.hldr, rhs.hldr); + } + + }; + + template + value_t* any_cast(any* operand) + { + auto casted = internal::down_cast::type> *>(operand->hldr.get()); + if (casted){ + return & (casted->v); + } + return nullptr; + } + + template + const value_t* any_cast(const any* operand) + { + auto casted = internal::down_cast::type> *>(operand->hldr.get()); + if (casted){ + return & (casted->v); + } + return nullptr; + } + + template + value_t& any_cast(any& operand) + { + auto ptr = any_cast(&operand); + if (ptr) + { + return *ptr; + } + + throw_error(bad_any_cast()); + } + + + template + const value_t& any_cast(const any& operand) + { + auto ptr = any_cast(&operand); + if (ptr) + { + return *ptr; + } + + throw_error(bad_any_cast()); + } + + template + inline value_t& unsafe_any_cast(any& operand) + { +#ifdef DEBUG + return any_cast(operand); +#else + return static_cast::type> *>(operand.hldr.get())->v; +#endif + } + + template + inline const value_t& unsafe_any_cast(const any& operand) + { +#ifdef DEBUG + return any_cast(operand); +#else + return static_cast::type> *>(operand.hldr.get())->v; +#endif + } + +} // namespace util +} // namespace cv + +#if defined(_MSC_VER) + // Enable "multiple copy constructors specified" back +# pragma warning(default: 4521) +#endif + +#endif // OPENCV_GAPI_UTIL_ANY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp index 5f620ff3ed..a41a97145d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/compiler_hints.hpp @@ -1,19 +1,19 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - -#ifndef OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP -#define OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP - -namespace cv -{ -namespace util -{ - //! Utility template function to prevent "unused" warnings by various compilers. - template void suppress_unused_warning( const T& ) {} -} // namespace util -} // namespace cv - -#endif /* OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + +#ifndef OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP +#define OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP + +namespace cv +{ +namespace util +{ + //! Utility template function to prevent "unused" warnings by various compilers. + template void suppress_unused_warning( const T& ) {} +} // namespace util +} // namespace cv + +#endif /* OPENCV_GAPI_UTIL_COMPILER_HINTS_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp index 34a856986f..1a1121eb21 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/copy_through_move.hpp @@ -1,34 +1,34 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP -#define OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP - -#include //decay_t - -namespace cv -{ -namespace util -{ - //This is a tool to move initialize captures of a lambda in C++11 - template - struct copy_through_move_t{ - T value; - const T& get() const {return value;} - T& get() {return value;} - copy_through_move_t(T&& g) : value(std::move(g)) {} - copy_through_move_t(copy_through_move_t&&) = default; - copy_through_move_t(copy_through_move_t const& lhs) : copy_through_move_t(std::move(const_cast(lhs))) {} - }; - - template - copy_through_move_t> copy_through_move(T&& t){ - return std::forward(t); - } -} // namespace util -} // namespace cv - -#endif /* OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP */ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP +#define OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP + +#include //decay_t + +namespace cv +{ +namespace util +{ + //This is a tool to move initialize captures of a lambda in C++11 + template + struct copy_through_move_t{ + T value; + const T& get() const {return value;} + T& get() {return value;} + copy_through_move_t(T&& g) : value(std::move(g)) {} + copy_through_move_t(copy_through_move_t&&) = default; + copy_through_move_t(copy_through_move_t const& lhs) : copy_through_move_t(std::move(const_cast(lhs))) {} + }; + + template + copy_through_move_t> copy_through_move(T&& t){ + return std::forward(t); + } +} // namespace util +} // namespace cv + +#endif /* OPENCV_GAPI_UTIL_COPY_THROUGH_MOVE_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp index 3b6877d2aa..dca03cadad 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/optional.hpp @@ -1,178 +1,178 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_OPTIONAL_HPP -#define OPENCV_GAPI_UTIL_OPTIONAL_HPP - -#include - -// A poor man's `optional` implementation, incompletely modeled against C++17 spec. -namespace cv -{ -namespace util -{ - class bad_optional_access: public std::exception - { - public: - virtual const char *what() const noexcept override - { - return "Bad optional access"; - } - }; - - // TODO: nullopt_t - - // Interface /////////////////////////////////////////////////////////////// - template class optional - { - public: - // Constructors - // NB.: there were issues with Clang 3.8 when =default() was used - // instead {} - optional() {} - optional(const optional&) = default; - explicit optional(T&&) noexcept; - explicit optional(const T&) noexcept; - optional(optional&&) noexcept; - // TODO: optional(nullopt_t) noexcept; - // TODO: optional(const optional &) - // TODO: optional(optional &&) - // TODO: optional(Args&&...) - // TODO: optional(initializer_list) - // TODO: optional(U&& value); - - // Assignment - optional& operator=(const optional&) = default; - optional& operator=(optional&&); - - // Observers - T* operator-> (); - const T* operator-> () const; - T& operator* (); - const T& operator* () const; - // TODO: && versions - - operator bool() const noexcept; - bool has_value() const noexcept; - - T& value(); - const T& value() const; - // TODO: && versions - - template - T value_or(U &&default_value) const; - - void swap(optional &other) noexcept; - void reset() noexcept; - // TODO: emplace - - // TODO: operator==, !=, <, <=, >, >= - - private: - struct nothing {}; - util::variant m_holder; - }; - - template - optional::type> make_optional(T&& value); - - // TODO: Args... and initializer_list versions - - // Implementation ////////////////////////////////////////////////////////// - template optional::optional(T &&v) noexcept - : m_holder(std::move(v)) - { - } - - template optional::optional(const T &v) noexcept - : m_holder(v) - { - } - - template optional::optional(optional&& rhs) noexcept - : m_holder(std::move(rhs.m_holder)) - { - rhs.reset(); - } - - template optional& optional::operator=(optional&& rhs) - { - m_holder = std::move(rhs.m_holder); - rhs.reset(); - return *this; - } - - template T* optional::operator-> () - { - return & *(*this); - } - - template const T* optional::operator-> () const - { - return & *(*this); - } - - template T& optional::operator* () - { - return this->value(); - } - - template const T& optional::operator* () const - { - return this->value(); - } - - template optional::operator bool() const noexcept - { - return this->has_value(); - } - - template bool optional::has_value() const noexcept - { - return util::holds_alternative(m_holder); - } - - template T& optional::value() - { - if (!this->has_value()) - throw_error(bad_optional_access()); - return util::get(m_holder); - } - - template const T& optional::value() const - { - if (!this->has_value()) - throw_error(bad_optional_access()); - return util::get(m_holder); - } - - template - template T optional::value_or(U &&default_value) const - { - return (this->has_value() ? this->value() : T(default_value)); - } - - template void optional::swap(optional &other) noexcept - { - m_holder.swap(other.m_holder); - } - - template void optional::reset() noexcept - { - if (this->has_value()) - m_holder = nothing{}; - } - - template - optional::type> make_optional(T&& value) - { - return optional::type>(std::forward(value)); - } -} // namespace util -} // namespace cv - -#endif // OPENCV_GAPI_UTIL_OPTIONAL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_OPTIONAL_HPP +#define OPENCV_GAPI_UTIL_OPTIONAL_HPP + +#include + +// A poor man's `optional` implementation, incompletely modeled against C++17 spec. +namespace cv +{ +namespace util +{ + class bad_optional_access: public std::exception + { + public: + virtual const char *what() const noexcept override + { + return "Bad optional access"; + } + }; + + // TODO: nullopt_t + + // Interface /////////////////////////////////////////////////////////////// + template class optional + { + public: + // Constructors + // NB.: there were issues with Clang 3.8 when =default() was used + // instead {} + optional() {} + optional(const optional&) = default; + explicit optional(T&&) noexcept; + explicit optional(const T&) noexcept; + optional(optional&&) noexcept; + // TODO: optional(nullopt_t) noexcept; + // TODO: optional(const optional &) + // TODO: optional(optional &&) + // TODO: optional(Args&&...) + // TODO: optional(initializer_list) + // TODO: optional(U&& value); + + // Assignment + optional& operator=(const optional&) = default; + optional& operator=(optional&&); + + // Observers + T* operator-> (); + const T* operator-> () const; + T& operator* (); + const T& operator* () const; + // TODO: && versions + + operator bool() const noexcept; + bool has_value() const noexcept; + + T& value(); + const T& value() const; + // TODO: && versions + + template + T value_or(U &&default_value) const; + + void swap(optional &other) noexcept; + void reset() noexcept; + // TODO: emplace + + // TODO: operator==, !=, <, <=, >, >= + + private: + struct nothing {}; + util::variant m_holder; + }; + + template + optional::type> make_optional(T&& value); + + // TODO: Args... and initializer_list versions + + // Implementation ////////////////////////////////////////////////////////// + template optional::optional(T &&v) noexcept + : m_holder(std::move(v)) + { + } + + template optional::optional(const T &v) noexcept + : m_holder(v) + { + } + + template optional::optional(optional&& rhs) noexcept + : m_holder(std::move(rhs.m_holder)) + { + rhs.reset(); + } + + template optional& optional::operator=(optional&& rhs) + { + m_holder = std::move(rhs.m_holder); + rhs.reset(); + return *this; + } + + template T* optional::operator-> () + { + return & *(*this); + } + + template const T* optional::operator-> () const + { + return & *(*this); + } + + template T& optional::operator* () + { + return this->value(); + } + + template const T& optional::operator* () const + { + return this->value(); + } + + template optional::operator bool() const noexcept + { + return this->has_value(); + } + + template bool optional::has_value() const noexcept + { + return util::holds_alternative(m_holder); + } + + template T& optional::value() + { + if (!this->has_value()) + throw_error(bad_optional_access()); + return util::get(m_holder); + } + + template const T& optional::value() const + { + if (!this->has_value()) + throw_error(bad_optional_access()); + return util::get(m_holder); + } + + template + template T optional::value_or(U &&default_value) const + { + return (this->has_value() ? this->value() : T(default_value)); + } + + template void optional::swap(optional &other) noexcept + { + m_holder.swap(other.m_holder); + } + + template void optional::reset() noexcept + { + if (this->has_value()) + m_holder = nothing{}; + } + + template + optional::type> make_optional(T&& value) + { + return optional::type>(std::forward(value)); + } +} // namespace util +} // namespace cv + +#endif // OPENCV_GAPI_UTIL_OPTIONAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp index bcbcf0adce..689bf583cf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/throw.hpp @@ -1,36 +1,36 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_THROW_HPP -#define OPENCV_GAPI_UTIL_THROW_HPP - -#include // std::forward - -#if !defined(__EXCEPTIONS) -#include -#include -#endif - -namespace cv -{ -namespace util -{ -template -[[noreturn]] void throw_error(ExceptionType &&e) -{ -#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) - throw std::forward(e); -#else - fprintf(stderr, "An exception thrown! %s\n" , e.what()); - fflush(stderr); - abort(); -#endif -} -} // namespace util -} // namespace cv - -#endif // OPENCV_GAPI_UTIL_THROW_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_THROW_HPP +#define OPENCV_GAPI_UTIL_THROW_HPP + +#include // std::forward + +#if !defined(__EXCEPTIONS) +#include +#include +#endif + +namespace cv +{ +namespace util +{ +template +[[noreturn]] void throw_error(ExceptionType &&e) +{ +#if defined(__EXCEPTIONS) || defined(_CPPUNWIND) + throw std::forward(e); +#else + fprintf(stderr, "An exception thrown! %s\n" , e.what()); + fflush(stderr); + abort(); +#endif +} +} // namespace util +} // namespace cv + +#endif // OPENCV_GAPI_UTIL_THROW_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp index 43160250d7..637f18460b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/type_traits.hpp @@ -1,31 +1,31 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP -#define OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP - -#include - -namespace cv -{ -namespace util -{ - //these are C++14 parts of type_traits : - template< bool B, class T = void > - using enable_if_t = typename std::enable_if::type; - - template - using decay_t = typename std::decay::type; - - //this is not part of C++14 but still, of pretty common usage - template - using are_different_t = enable_if_t< !std::is_same, decay_t>::value, V>; - -} // namespace cv -} // namespace util - -#endif // OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP +#define OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP + +#include + +namespace cv +{ +namespace util +{ + //these are C++14 parts of type_traits : + template< bool B, class T = void > + using enable_if_t = typename std::enable_if::type; + + template + using decay_t = typename std::decay::type; + + //this is not part of C++14 but still, of pretty common usage + template + using are_different_t = enable_if_t< !std::is_same, decay_t>::value, V>; + +} // namespace cv +} // namespace util + +#endif // OPENCV_GAPI_UTIL_TYPE_TRAITS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp index 31f518a322..3be46d7ec2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/util.hpp @@ -1,190 +1,190 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018-2019 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_HPP -#define OPENCV_GAPI_UTIL_HPP - -#include - -// \cond HIDDEN_SYMBOLS -// This header file contains some generic utility functions which are -// used in other G-API Public API headers. -// -// PLEASE don't put any stuff here if it is NOT used in public API headers! - -namespace cv -{ -namespace detail -{ - // Recursive integer sequence type, useful for enumerating elements of - // template parameter packs. - template struct Seq { using next = Seq; }; - template struct MkSeq { using type = typename MkSeq::type::next; }; - template<> struct MkSeq<0>{ using type = Seq<>; }; - - // Checks if elements of variadic template satisfy the given Predicate. - // Implemented via tuple, with an interface to accept plain type lists - template class, typename, typename...> struct all_satisfy; - - template class F, typename T, typename... Ts> - struct all_satisfy > - { - static const constexpr bool value = F::value - && all_satisfy >::value; - }; - template class F, typename T> - struct all_satisfy > - { - static const constexpr bool value = F::value; - }; - - template class F, typename T, typename... Ts> - struct all_satisfy: public all_satisfy > {}; - - // Permute given tuple type C with given integer sequence II - // Sequence may be less than tuple C size. - template struct permute_tuple; - - template - struct permute_tuple > - { - using type = std::tuple< typename std::tuple_element::type... >; - }; - - // Given T..., generates a type sequence of sizeof...(T)-1 elements - // which is T... without its last element - // Implemented via tuple, with an interface to accept plain type lists - template struct all_but_last; - - template - struct all_but_last > - { - using C = std::tuple; - using S = typename MkSeq::value - 1>::type; - using type = typename permute_tuple::type; - }; - - template - struct all_but_last: public all_but_last > {}; - - template - using all_but_last_t = typename all_but_last::type; - - // NB.: This is here because there's no constexpr std::max in C++11 - template struct max_of_t - { - static constexpr const std::size_t rest = max_of_t::value; - static constexpr const std::size_t value = rest > S0 ? rest : S0; - }; - template struct max_of_t - { - static constexpr const std::size_t value = S; - }; - - template - struct contains : std::false_type{}; - - template - struct contains : std::integral_constant::value || - contains::value> {}; - template - struct contains> : std::integral_constant::value> {}; - - template - struct all_unique : std::true_type{}; - - template - struct all_unique : std::integral_constant::value && - all_unique::value> {}; - - template - struct tuple_wrap_helper; - - template struct tuple_wrap_helper - { - using type = std::tuple; - static type get(T&& obj) { return std::make_tuple(std::move(obj)); } - }; - - template - struct tuple_wrap_helper> - { - using type = std::tuple; - static type get(std::tuple&& objs) { return std::forward>(objs); } - }; - - template - struct make_void { typedef void type;}; - - template - using void_t = typename make_void::type; - -} // namespace detail - -namespace util -{ -template -struct overload_lamba_set; - -template -struct overload_lamba_set : public L1 -{ - overload_lamba_set(L1&& lambda) : L1(std::move(lambda)) {} - overload_lamba_set(const L1& lambda) : L1(lambda) {} - - using L1::operator(); -}; - -template -struct overload_lamba_set : public L1, public overload_lamba_set -{ - using base_type = overload_lamba_set; - overload_lamba_set(L1 &&lambda1, L&& ...lambdas): - L1(std::move(lambda1)), - base_type(std::forward(lambdas)...) {} - - overload_lamba_set(const L1 &lambda1, L&& ...lambdas): - L1(lambda1), - base_type(std::forward(lambdas)...) {} - - using L1::operator(); - using base_type::operator(); -}; - -template -overload_lamba_set overload_lambdas(L&& ...lambdas) -{ - return overload_lamba_set(std::forward(lambdas)...); -} - -template -struct find_adapter_impl; - -template -struct find_adapter_impl -{ - using type = typename std::conditional::value, - T, - void>::type; - static constexpr bool found = std::is_base_of::value; -}; - -template -struct find_adapter_impl -{ - using type = typename std::conditional::value, - T, - typename find_adapter_impl::type>::type; - static constexpr bool found = std::is_base_of::value || - find_adapter_impl::found; -}; -} // namespace util -} // namespace cv - -// \endcond - -#endif // OPENCV_GAPI_UTIL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018-2019 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_HPP +#define OPENCV_GAPI_UTIL_HPP + +#include + +// \cond HIDDEN_SYMBOLS +// This header file contains some generic utility functions which are +// used in other G-API Public API headers. +// +// PLEASE don't put any stuff here if it is NOT used in public API headers! + +namespace cv +{ +namespace detail +{ + // Recursive integer sequence type, useful for enumerating elements of + // template parameter packs. + template struct Seq { using next = Seq; }; + template struct MkSeq { using type = typename MkSeq::type::next; }; + template<> struct MkSeq<0>{ using type = Seq<>; }; + + // Checks if elements of variadic template satisfy the given Predicate. + // Implemented via tuple, with an interface to accept plain type lists + template class, typename, typename...> struct all_satisfy; + + template class F, typename T, typename... Ts> + struct all_satisfy > + { + static const constexpr bool value = F::value + && all_satisfy >::value; + }; + template class F, typename T> + struct all_satisfy > + { + static const constexpr bool value = F::value; + }; + + template class F, typename T, typename... Ts> + struct all_satisfy: public all_satisfy > {}; + + // Permute given tuple type C with given integer sequence II + // Sequence may be less than tuple C size. + template struct permute_tuple; + + template + struct permute_tuple > + { + using type = std::tuple< typename std::tuple_element::type... >; + }; + + // Given T..., generates a type sequence of sizeof...(T)-1 elements + // which is T... without its last element + // Implemented via tuple, with an interface to accept plain type lists + template struct all_but_last; + + template + struct all_but_last > + { + using C = std::tuple; + using S = typename MkSeq::value - 1>::type; + using type = typename permute_tuple::type; + }; + + template + struct all_but_last: public all_but_last > {}; + + template + using all_but_last_t = typename all_but_last::type; + + // NB.: This is here because there's no constexpr std::max in C++11 + template struct max_of_t + { + static constexpr const std::size_t rest = max_of_t::value; + static constexpr const std::size_t value = rest > S0 ? rest : S0; + }; + template struct max_of_t + { + static constexpr const std::size_t value = S; + }; + + template + struct contains : std::false_type{}; + + template + struct contains : std::integral_constant::value || + contains::value> {}; + template + struct contains> : std::integral_constant::value> {}; + + template + struct all_unique : std::true_type{}; + + template + struct all_unique : std::integral_constant::value && + all_unique::value> {}; + + template + struct tuple_wrap_helper; + + template struct tuple_wrap_helper + { + using type = std::tuple; + static type get(T&& obj) { return std::make_tuple(std::move(obj)); } + }; + + template + struct tuple_wrap_helper> + { + using type = std::tuple; + static type get(std::tuple&& objs) { return std::forward>(objs); } + }; + + template + struct make_void { typedef void type;}; + + template + using void_t = typename make_void::type; + +} // namespace detail + +namespace util +{ +template +struct overload_lamba_set; + +template +struct overload_lamba_set : public L1 +{ + overload_lamba_set(L1&& lambda) : L1(std::move(lambda)) {} + overload_lamba_set(const L1& lambda) : L1(lambda) {} + + using L1::operator(); +}; + +template +struct overload_lamba_set : public L1, public overload_lamba_set +{ + using base_type = overload_lamba_set; + overload_lamba_set(L1 &&lambda1, L&& ...lambdas): + L1(std::move(lambda1)), + base_type(std::forward(lambdas)...) {} + + overload_lamba_set(const L1 &lambda1, L&& ...lambdas): + L1(lambda1), + base_type(std::forward(lambdas)...) {} + + using L1::operator(); + using base_type::operator(); +}; + +template +overload_lamba_set overload_lambdas(L&& ...lambdas) +{ + return overload_lamba_set(std::forward(lambdas)...); +} + +template +struct find_adapter_impl; + +template +struct find_adapter_impl +{ + using type = typename std::conditional::value, + T, + void>::type; + static constexpr bool found = std::is_base_of::value; +}; + +template +struct find_adapter_impl +{ + using type = typename std::conditional::value, + T, + typename find_adapter_impl::type>::type; + static constexpr bool found = std::is_base_of::value || + find_adapter_impl::found; +}; +} // namespace util +} // namespace cv + +// \endcond + +#endif // OPENCV_GAPI_UTIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp index 8b68e79ec5..48b55646c5 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/util/variant.hpp @@ -1,667 +1,667 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2018 Intel Corporation - - -#ifndef OPENCV_GAPI_UTIL_VARIANT_HPP -#define OPENCV_GAPI_UTIL_VARIANT_HPP - -#include -#include - -#include -#include -#include // max_of_t -#include - -// A poor man's `variant` implementation, incompletely modeled against C++17 spec. -namespace cv -{ -namespace util -{ - namespace detail - { - template - struct type_list_index_helper - { - static const constexpr bool is_same = std::is_same::value; - static const constexpr std::size_t value = - std::conditional, type_list_index_helper>::type::value; - }; - - template - struct type_list_index_helper - { - static_assert(std::is_same::value, "Type not found"); - static const constexpr std::size_t value = I; - }; - } - - template - struct type_list_index - { - static const constexpr std::size_t value = detail::type_list_index_helper<0, Target, Types...>::value; - }; - - template - struct type_list_element - { - using type = typename std::tuple_element >::type; - }; - - class bad_variant_access: public std::exception - { - public: - virtual const char *what() const noexcept override - { - return "Bad variant access"; - } - }; - - // Interface /////////////////////////////////////////////////////////////// - struct monostate {}; - inline bool operator==(const util::monostate&, const util::monostate&) - { - return true; - } - - template // FIXME: no references, arrays, and void - class variant - { - // FIXME: Replace with std::aligned_union after gcc4.8 support is dropped - static constexpr const std::size_t S = cv::detail::max_of_t::value; - static constexpr const std::size_t A = cv::detail::max_of_t::value; - using Memory = typename std::aligned_storage::type[1]; - - template struct cctr_h { - static void help(Memory memory, const Memory from) { - new (memory) T(*reinterpret_cast(from)); - } - }; - - template struct mctr_h { - static void help(Memory memory, void *pval) { - new (memory) T(std::move(*reinterpret_cast(pval))); - } - }; - - //FIXME: unify with cctr_h and mctr_h - template struct cnvrt_ctor_h { - static void help(Memory memory, void* from) { - using util::decay_t; - new (memory) decay_t(std::forward(*reinterpret_cast*>(from))); - } - }; - - template struct copy_h { - static void help(Memory to, const Memory from) { - *reinterpret_cast(to) = *reinterpret_cast(from); - } - }; - - template struct move_h { - static void help(Memory to, Memory from) { - *reinterpret_cast(to) = std::move(*reinterpret_cast(from)); - } - }; - - //FIXME: unify with copy_h and move_h - template struct cnvrt_assign_h { - static void help(Memory to, void* from) { - using util::decay_t; - *reinterpret_cast*>(to) = std::forward(*reinterpret_cast*>(from)); - } - }; - - template struct swap_h { - static void help(Memory to, Memory from) { - std::swap(*reinterpret_cast(to), *reinterpret_cast(from)); - } - }; - - template struct dtor_h { - static void help(Memory memory) { - (void) memory; // MSCV warning - reinterpret_cast(memory)->~T(); - } - }; - - template struct equal_h { - static bool help(const Memory lhs, const Memory rhs) { - const T& t_lhs = *reinterpret_cast(lhs); - const T& t_rhs = *reinterpret_cast(rhs); - return t_lhs == t_rhs; - } - }; - - typedef void (*CCtr) (Memory, const Memory); // Copy c-tor (variant) - typedef void (*MCtr) (Memory, void*); // Generic move c-tor - typedef void (*Copy) (Memory, const Memory); // Copy assignment - typedef void (*Move) (Memory, Memory); // Move assignment - - typedef void (*Swap) (Memory, Memory); // Swap - typedef void (*Dtor) (Memory); // Destructor - - using cnvrt_assgn_t = void (*) (Memory, void*); // Converting assignment (via std::forward) - using cnvrt_ctor_t = void (*) (Memory, void*); // Converting constructor (via std::forward) - - typedef bool (*Equal)(const Memory, const Memory); // Equality test (external) - - static constexpr std::array cctrs(){ return {{(&cctr_h::help)...}};} - static constexpr std::array mctrs(){ return {{(&mctr_h::help)...}};} - static constexpr std::array cpyrs(){ return {{(©_h::help)...}};} - static constexpr std::array mvers(){ return {{(&move_h::help)...}};} - static constexpr std::array swprs(){ return {{(&swap_h::help)...}};} - static constexpr std::array dtors(){ return {{(&dtor_h::help)...}};} - - template - struct conditional_ref : std::conditional::type&, typename std::remove_reference::type > {}; - - template - using conditional_ref_t = typename conditional_ref::type; - - - template - static constexpr std::array cnvrt_assgnrs(){ - return {{(&cnvrt_assign_h>::help)...}}; - } - - template - static constexpr std::array cnvrt_ctors(){ - return {{(&cnvrt_ctor_h>::help)...}}; - } - - std::size_t m_index = 0; - - protected: - template friend T& get(variant &v); - template friend const T& get(const variant &v); - template friend T* get_if(variant *v) noexcept; - template friend const T* get_if(const variant *v) noexcept; - - template friend bool operator==(const variant &lhs, - const variant &rhs); - Memory memory; - - public: - // Constructors - variant() noexcept; - variant(const variant& other); - variant(variant&& other) noexcept; - // are_different_t is a SFINAE trick to avoid variant(T &&t) with T=variant - // for some reason, this version is called instead of variant(variant&& o) when - // variant is used in STL containers (examples: vector assignment). - template< - typename T, - typename = util::are_different_t - > - explicit variant(T&& t); - // template explicit variant(Args&&... args); - // FIXME: other constructors - - // Destructor - ~variant(); - - // Assignment - variant& operator=(const variant& rhs); - variant& operator=(variant &&rhs) noexcept; - - // SFINAE trick to avoid operator=(T&&) with T=variant<>, see comment above - template< - typename T, - typename = util::are_different_t - > - variant& operator=(T&& t) noexcept; - - // Observers - std::size_t index() const noexcept; - // FIXME: valueless_by_exception() - - // Modifiers - // FIXME: emplace() - void swap(variant &rhs) noexcept; - - // Non-C++17x! - template static constexpr std::size_t index_of(); - }; - - // FIMXE: visit - template - T* get_if(util::variant* v) noexcept; - - template - const T* get_if(const util::variant* v) noexcept; - - template - T& get(util::variant &v); - - template - const T& get(const util::variant &v); - - template - typename util::type_list_element::type& get(util::variant &v); - - template - const typename util::type_list_element::type& get(const util::variant &v); - - template - bool holds_alternative(const util::variant &v) noexcept; - - - // Visitor - namespace detail - { - struct visitor_interface {}; - - // Class `visitor_return_type_deduction_helper` - // introduces solution for deduction `return_type` in `visit` function in common way - // for both Lambda and class Visitor and keep one interface invocation point: `visit` only - // his helper class is required to unify return_type deduction mechanism because - // for Lambda it is possible to take type of `decltype(visitor(get<0>(var)))` - // but for class Visitor there is no operator() in base case, - // because it provides `operator() (std::size_t index, ...)` - // So `visitor_return_type_deduction_helper` expose `operator()` - // uses only for class Visitor only for deduction `return type` in visit() - template - struct visitor_return_type_deduction_helper - { - using return_type = R; - - // to be used in Lambda return type deduction context only - template - return_type operator() (T&&); - }; - } - - // Special purpose `static_visitor` can receive additional arguments - template - struct static_visitor : public detail::visitor_interface, - public detail::visitor_return_type_deduction_helper { - - // assign responsibility for return type deduction to helper class - using return_type = typename detail::visitor_return_type_deduction_helper::return_type; - using detail::visitor_return_type_deduction_helper::operator(); - friend Impl; - - template - return_type operator() (std::size_t index, VariantValue&& value, Args&& ...args) - { - suppress_unused_warning(index); - return static_cast(this)-> visit( - std::forward(value), - std::forward(args)...); - } - }; - - // Special purpose `static_indexed_visitor` can receive additional arguments - // And make forwarding current variant index as runtime function argument to its `Impl` - template - struct static_indexed_visitor : public detail::visitor_interface, - public detail::visitor_return_type_deduction_helper { - - // assign responsibility for return type deduction to helper class - using return_type = typename detail::visitor_return_type_deduction_helper::return_type; - using detail::visitor_return_type_deduction_helper::operator(); - friend Impl; - - template - return_type operator() (std::size_t Index, VariantValue&& value, Args&& ...args) - { - return static_cast(this)-> visit(Index, - std::forward(value), - std::forward(args)...); - } - }; - - template - struct variant_size; - - template - struct variant_size> - : std::integral_constant { }; - // FIXME: T&&, const TT&& versions. - - // Implementation ////////////////////////////////////////////////////////// - template - variant::variant() noexcept - { - typedef typename std::tuple_element<0, std::tuple >::type TFirst; - new (memory) TFirst(); - } - - template - variant::variant(const variant &other) - : m_index(other.m_index) - { - (cctrs()[m_index])(memory, other.memory); - } - - template - variant::variant(variant &&other) noexcept - : m_index(other.m_index) - { - (mctrs()[m_index])(memory, other.memory); - } - - template - template - variant::variant(T&& t) - : m_index(util::type_list_index, Ts...>::value) - { - const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; - (cnvrt_ctors()[m_index])(memory, const_cast *>(&t)); - } - - template - variant::~variant() - { - (dtors()[m_index])(memory); - } - - template - variant& variant::operator=(const variant &rhs) - { - if (m_index != rhs.m_index) - { - (dtors()[ m_index])(memory); - (cctrs()[rhs.m_index])(memory, rhs.memory); - m_index = rhs.m_index; - } - else - { - (cpyrs()[rhs.m_index])(memory, rhs.memory); - } - return *this; - } - - template - variant& variant::operator=(variant &&rhs) noexcept - { - if (m_index != rhs.m_index) - { - (dtors()[ m_index])(memory); - (mctrs()[rhs.m_index])(memory, rhs.memory); - m_index = rhs.m_index; - } - else - { - (mvers()[rhs.m_index])(memory, rhs.memory); - } - return *this; - } - - template - template - variant& variant::operator=(T&& t) noexcept - { - using decayed_t = util::decay_t; - // FIXME: No version with implicit type conversion available! - const constexpr std::size_t t_index = - util::type_list_index::value; - - const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; - - if (t_index != m_index) - { - (dtors()[m_index])(memory); - (cnvrt_ctors()[t_index])(memory, &t); - m_index = t_index; - } - else - { - (cnvrt_assgnrs()[m_index])(memory, &t); - } - return *this; - - } - - template - std::size_t util::variant::index() const noexcept - { - return m_index; - } - - template - void variant::swap(variant &rhs) noexcept - { - if (m_index == rhs.index()) - { - (swprs()[m_index](memory, rhs.memory)); - } - else - { - variant tmp(std::move(*this)); - *this = std::move(rhs); - rhs = std::move(tmp); - } - } - - template - template - constexpr std::size_t variant::index_of() - { - return util::type_list_index::value; // FIXME: tests! - } - - template - T* get_if(util::variant* v) noexcept - { - const constexpr std::size_t t_index = - util::type_list_index::value; - - if (v && v->index() == t_index) - return (T*)(&v->memory); // workaround for ICC 2019 - // original code: return reinterpret_cast(v.memory); - return nullptr; - } - - template - const T* get_if(const util::variant* v) noexcept - { - const constexpr std::size_t t_index = - util::type_list_index::value; - - if (v && v->index() == t_index) - return (const T*)(&v->memory); // workaround for ICC 2019 - // original code: return reinterpret_cast(v.memory); - return nullptr; - } - - template - T& get(util::variant &v) - { - if (auto* p = get_if(&v)) - return *p; - else - throw_error(bad_variant_access()); - } - - template - const T& get(const util::variant &v) - { - if (auto* p = get_if(&v)) - return *p; - else - throw_error(bad_variant_access()); - } - - template - typename util::type_list_element::type& get(util::variant &v) - { - using ReturnType = typename util::type_list_element::type; - return const_cast(get(static_cast &>(v))); - } - - template - const typename util::type_list_element::type& get(const util::variant &v) - { - static_assert(Index < sizeof...(Types), - "`Index` it out of bound of `util::variant` type list"); - using ReturnType = typename util::type_list_element::type; - return get(v); - } - - template - bool holds_alternative(const util::variant &v) noexcept - { - return v.index() == util::variant::template index_of(); - } - -#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif - - template bool operator==(const variant &lhs, - const variant &rhs) - { - using V = variant; - - // Instantiate table only here since it requires operator== for - // should have operator== only if this one is used, not in general - static const std::array eqs = { - {(&V::template equal_h::help)...} - }; - if (lhs.index() != rhs.index()) - return false; - return (eqs[lhs.index()])(lhs.memory, rhs.memory); - } - -#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) -#pragma GCC diagnostic pop -#endif - - template bool operator!=(const variant &lhs, - const variant &rhs) - { - return !(lhs == rhs); - } - -namespace detail -{ - // terminate recursion implementation for `non-void` ReturnType - template - ReturnType apply_visitor_impl(Visitor&&, Variant&, - std::true_type, std::false_type, - VisitorArgs&& ...) - { - return {}; - } - - // terminate recursion implementation for `void` ReturnType - template - void apply_visitor_impl(Visitor&&, Variant&, - std::true_type, std::true_type, - VisitorArgs&& ...) - { - } - - // Intermediate resursion processor for Lambda Visitors - template - typename std::enable_if::type>::value, ReturnType>::type - apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, - std::integral_constant should_no_return, - VisitorArgs&& ...args) - { - static_assert(std::is_same(v)))>::value, - "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" - " must return the same type"); - suppress_unused_warning(not_processed); - if (v.index() == CurIndex) - { - return visitor.operator()(get(v), std::forward(args)... ); - } - - using is_variant_processed_t = std::integral_constant= ElemCount>; - return apply_visitor_impl( - std::forward(visitor), - std::forward(v), - is_variant_processed_t{}, - should_no_return, - std::forward(args)...); - } - - //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() - template - typename std::enable_if::type>, - typename std::decay::type>::value, ReturnType>::type - invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) - { - return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); - } - - //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() - template - typename std::enable_if::type>, - typename std::decay::type>::value, ReturnType>::type - invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) - { - return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); - } - - // Intermediate recursion processor for special case `visitor_interface` derived Visitors - template - typename std::enable_if::type>::value, ReturnType>::type - apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, - std::integral_constant should_no_return, - VisitorArgs&& ...args) - { - static_assert(std::is_same(v)))>::value, - "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" - " must return the same type"); - suppress_unused_warning(not_processed); - if (v.index() == CurIndex) - { - return invoke_class_visitor(visitor, get(v), std::forward(args)... ); - } - - using is_variant_processed_t = std::integral_constant= ElemCount>; - return apply_visitor_impl( - std::forward(visitor), - std::forward(v), - is_variant_processed_t{}, - should_no_return, - std::forward(args)...); - } -} // namespace detail - - template - auto visit(Visitor &visitor, const Variant& var, VisitorArg &&...args) -> decltype(visitor(get<0>(var))) - { - constexpr std::size_t varsize = util::variant_size::value; - static_assert(varsize != 0, "utils::variant must contains one type at least "); - using is_variant_processed_t = std::false_type; - - using ReturnType = decltype(visitor(get<0>(var))); - using return_t = std::is_same; - return detail::apply_visitor_impl( - std::forward(visitor), - var, is_variant_processed_t{}, - return_t{}, - std::forward(args)...); - } - - template - auto visit(Visitor&& visitor, const Variant& var) -> decltype(visitor(get<0>(var))) - { - constexpr std::size_t varsize = util::variant_size::value; - static_assert(varsize != 0, "utils::variant must contains one type at least "); - using is_variant_processed_t = std::false_type; - - using ReturnType = decltype(visitor(get<0>(var))); - using return_t = std::is_same; - return detail::apply_visitor_impl( - std::forward(visitor), - var, is_variant_processed_t{}, - return_t{}); - } -} // namespace util -} // namespace cv - -#endif // OPENCV_GAPI_UTIL_VARIANT_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2018 Intel Corporation + + +#ifndef OPENCV_GAPI_UTIL_VARIANT_HPP +#define OPENCV_GAPI_UTIL_VARIANT_HPP + +#include +#include + +#include +#include +#include // max_of_t +#include + +// A poor man's `variant` implementation, incompletely modeled against C++17 spec. +namespace cv +{ +namespace util +{ + namespace detail + { + template + struct type_list_index_helper + { + static const constexpr bool is_same = std::is_same::value; + static const constexpr std::size_t value = + std::conditional, type_list_index_helper>::type::value; + }; + + template + struct type_list_index_helper + { + static_assert(std::is_same::value, "Type not found"); + static const constexpr std::size_t value = I; + }; + } + + template + struct type_list_index + { + static const constexpr std::size_t value = detail::type_list_index_helper<0, Target, Types...>::value; + }; + + template + struct type_list_element + { + using type = typename std::tuple_element >::type; + }; + + class bad_variant_access: public std::exception + { + public: + virtual const char *what() const noexcept override + { + return "Bad variant access"; + } + }; + + // Interface /////////////////////////////////////////////////////////////// + struct monostate {}; + inline bool operator==(const util::monostate&, const util::monostate&) + { + return true; + } + + template // FIXME: no references, arrays, and void + class variant + { + // FIXME: Replace with std::aligned_union after gcc4.8 support is dropped + static constexpr const std::size_t S = cv::detail::max_of_t::value; + static constexpr const std::size_t A = cv::detail::max_of_t::value; + using Memory = typename std::aligned_storage::type[1]; + + template struct cctr_h { + static void help(Memory memory, const Memory from) { + new (memory) T(*reinterpret_cast(from)); + } + }; + + template struct mctr_h { + static void help(Memory memory, void *pval) { + new (memory) T(std::move(*reinterpret_cast(pval))); + } + }; + + //FIXME: unify with cctr_h and mctr_h + template struct cnvrt_ctor_h { + static void help(Memory memory, void* from) { + using util::decay_t; + new (memory) decay_t(std::forward(*reinterpret_cast*>(from))); + } + }; + + template struct copy_h { + static void help(Memory to, const Memory from) { + *reinterpret_cast(to) = *reinterpret_cast(from); + } + }; + + template struct move_h { + static void help(Memory to, Memory from) { + *reinterpret_cast(to) = std::move(*reinterpret_cast(from)); + } + }; + + //FIXME: unify with copy_h and move_h + template struct cnvrt_assign_h { + static void help(Memory to, void* from) { + using util::decay_t; + *reinterpret_cast*>(to) = std::forward(*reinterpret_cast*>(from)); + } + }; + + template struct swap_h { + static void help(Memory to, Memory from) { + std::swap(*reinterpret_cast(to), *reinterpret_cast(from)); + } + }; + + template struct dtor_h { + static void help(Memory memory) { + (void) memory; // MSCV warning + reinterpret_cast(memory)->~T(); + } + }; + + template struct equal_h { + static bool help(const Memory lhs, const Memory rhs) { + const T& t_lhs = *reinterpret_cast(lhs); + const T& t_rhs = *reinterpret_cast(rhs); + return t_lhs == t_rhs; + } + }; + + typedef void (*CCtr) (Memory, const Memory); // Copy c-tor (variant) + typedef void (*MCtr) (Memory, void*); // Generic move c-tor + typedef void (*Copy) (Memory, const Memory); // Copy assignment + typedef void (*Move) (Memory, Memory); // Move assignment + + typedef void (*Swap) (Memory, Memory); // Swap + typedef void (*Dtor) (Memory); // Destructor + + using cnvrt_assgn_t = void (*) (Memory, void*); // Converting assignment (via std::forward) + using cnvrt_ctor_t = void (*) (Memory, void*); // Converting constructor (via std::forward) + + typedef bool (*Equal)(const Memory, const Memory); // Equality test (external) + + static constexpr std::array cctrs(){ return {{(&cctr_h::help)...}};} + static constexpr std::array mctrs(){ return {{(&mctr_h::help)...}};} + static constexpr std::array cpyrs(){ return {{(©_h::help)...}};} + static constexpr std::array mvers(){ return {{(&move_h::help)...}};} + static constexpr std::array swprs(){ return {{(&swap_h::help)...}};} + static constexpr std::array dtors(){ return {{(&dtor_h::help)...}};} + + template + struct conditional_ref : std::conditional::type&, typename std::remove_reference::type > {}; + + template + using conditional_ref_t = typename conditional_ref::type; + + + template + static constexpr std::array cnvrt_assgnrs(){ + return {{(&cnvrt_assign_h>::help)...}}; + } + + template + static constexpr std::array cnvrt_ctors(){ + return {{(&cnvrt_ctor_h>::help)...}}; + } + + std::size_t m_index = 0; + + protected: + template friend T& get(variant &v); + template friend const T& get(const variant &v); + template friend T* get_if(variant *v) noexcept; + template friend const T* get_if(const variant *v) noexcept; + + template friend bool operator==(const variant &lhs, + const variant &rhs); + Memory memory; + + public: + // Constructors + variant() noexcept; + variant(const variant& other); + variant(variant&& other) noexcept; + // are_different_t is a SFINAE trick to avoid variant(T &&t) with T=variant + // for some reason, this version is called instead of variant(variant&& o) when + // variant is used in STL containers (examples: vector assignment). + template< + typename T, + typename = util::are_different_t + > + explicit variant(T&& t); + // template explicit variant(Args&&... args); + // FIXME: other constructors + + // Destructor + ~variant(); + + // Assignment + variant& operator=(const variant& rhs); + variant& operator=(variant &&rhs) noexcept; + + // SFINAE trick to avoid operator=(T&&) with T=variant<>, see comment above + template< + typename T, + typename = util::are_different_t + > + variant& operator=(T&& t) noexcept; + + // Observers + std::size_t index() const noexcept; + // FIXME: valueless_by_exception() + + // Modifiers + // FIXME: emplace() + void swap(variant &rhs) noexcept; + + // Non-C++17x! + template static constexpr std::size_t index_of(); + }; + + // FIMXE: visit + template + T* get_if(util::variant* v) noexcept; + + template + const T* get_if(const util::variant* v) noexcept; + + template + T& get(util::variant &v); + + template + const T& get(const util::variant &v); + + template + typename util::type_list_element::type& get(util::variant &v); + + template + const typename util::type_list_element::type& get(const util::variant &v); + + template + bool holds_alternative(const util::variant &v) noexcept; + + + // Visitor + namespace detail + { + struct visitor_interface {}; + + // Class `visitor_return_type_deduction_helper` + // introduces solution for deduction `return_type` in `visit` function in common way + // for both Lambda and class Visitor and keep one interface invocation point: `visit` only + // his helper class is required to unify return_type deduction mechanism because + // for Lambda it is possible to take type of `decltype(visitor(get<0>(var)))` + // but for class Visitor there is no operator() in base case, + // because it provides `operator() (std::size_t index, ...)` + // So `visitor_return_type_deduction_helper` expose `operator()` + // uses only for class Visitor only for deduction `return type` in visit() + template + struct visitor_return_type_deduction_helper + { + using return_type = R; + + // to be used in Lambda return type deduction context only + template + return_type operator() (T&&); + }; + } + + // Special purpose `static_visitor` can receive additional arguments + template + struct static_visitor : public detail::visitor_interface, + public detail::visitor_return_type_deduction_helper { + + // assign responsibility for return type deduction to helper class + using return_type = typename detail::visitor_return_type_deduction_helper::return_type; + using detail::visitor_return_type_deduction_helper::operator(); + friend Impl; + + template + return_type operator() (std::size_t index, VariantValue&& value, Args&& ...args) + { + suppress_unused_warning(index); + return static_cast(this)-> visit( + std::forward(value), + std::forward(args)...); + } + }; + + // Special purpose `static_indexed_visitor` can receive additional arguments + // And make forwarding current variant index as runtime function argument to its `Impl` + template + struct static_indexed_visitor : public detail::visitor_interface, + public detail::visitor_return_type_deduction_helper { + + // assign responsibility for return type deduction to helper class + using return_type = typename detail::visitor_return_type_deduction_helper::return_type; + using detail::visitor_return_type_deduction_helper::operator(); + friend Impl; + + template + return_type operator() (std::size_t Index, VariantValue&& value, Args&& ...args) + { + return static_cast(this)-> visit(Index, + std::forward(value), + std::forward(args)...); + } + }; + + template + struct variant_size; + + template + struct variant_size> + : std::integral_constant { }; + // FIXME: T&&, const TT&& versions. + + // Implementation ////////////////////////////////////////////////////////// + template + variant::variant() noexcept + { + typedef typename std::tuple_element<0, std::tuple >::type TFirst; + new (memory) TFirst(); + } + + template + variant::variant(const variant &other) + : m_index(other.m_index) + { + (cctrs()[m_index])(memory, other.memory); + } + + template + variant::variant(variant &&other) noexcept + : m_index(other.m_index) + { + (mctrs()[m_index])(memory, other.memory); + } + + template + template + variant::variant(T&& t) + : m_index(util::type_list_index, Ts...>::value) + { + const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; + (cnvrt_ctors()[m_index])(memory, const_cast *>(&t)); + } + + template + variant::~variant() + { + (dtors()[m_index])(memory); + } + + template + variant& variant::operator=(const variant &rhs) + { + if (m_index != rhs.m_index) + { + (dtors()[ m_index])(memory); + (cctrs()[rhs.m_index])(memory, rhs.memory); + m_index = rhs.m_index; + } + else + { + (cpyrs()[rhs.m_index])(memory, rhs.memory); + } + return *this; + } + + template + variant& variant::operator=(variant &&rhs) noexcept + { + if (m_index != rhs.m_index) + { + (dtors()[ m_index])(memory); + (mctrs()[rhs.m_index])(memory, rhs.memory); + m_index = rhs.m_index; + } + else + { + (mvers()[rhs.m_index])(memory, rhs.memory); + } + return *this; + } + + template + template + variant& variant::operator=(T&& t) noexcept + { + using decayed_t = util::decay_t; + // FIXME: No version with implicit type conversion available! + const constexpr std::size_t t_index = + util::type_list_index::value; + + const constexpr bool is_lvalue_arg = std::is_lvalue_reference::value; + + if (t_index != m_index) + { + (dtors()[m_index])(memory); + (cnvrt_ctors()[t_index])(memory, &t); + m_index = t_index; + } + else + { + (cnvrt_assgnrs()[m_index])(memory, &t); + } + return *this; + + } + + template + std::size_t util::variant::index() const noexcept + { + return m_index; + } + + template + void variant::swap(variant &rhs) noexcept + { + if (m_index == rhs.index()) + { + (swprs()[m_index](memory, rhs.memory)); + } + else + { + variant tmp(std::move(*this)); + *this = std::move(rhs); + rhs = std::move(tmp); + } + } + + template + template + constexpr std::size_t variant::index_of() + { + return util::type_list_index::value; // FIXME: tests! + } + + template + T* get_if(util::variant* v) noexcept + { + const constexpr std::size_t t_index = + util::type_list_index::value; + + if (v && v->index() == t_index) + return (T*)(&v->memory); // workaround for ICC 2019 + // original code: return reinterpret_cast(v.memory); + return nullptr; + } + + template + const T* get_if(const util::variant* v) noexcept + { + const constexpr std::size_t t_index = + util::type_list_index::value; + + if (v && v->index() == t_index) + return (const T*)(&v->memory); // workaround for ICC 2019 + // original code: return reinterpret_cast(v.memory); + return nullptr; + } + + template + T& get(util::variant &v) + { + if (auto* p = get_if(&v)) + return *p; + else + throw_error(bad_variant_access()); + } + + template + const T& get(const util::variant &v) + { + if (auto* p = get_if(&v)) + return *p; + else + throw_error(bad_variant_access()); + } + + template + typename util::type_list_element::type& get(util::variant &v) + { + using ReturnType = typename util::type_list_element::type; + return const_cast(get(static_cast &>(v))); + } + + template + const typename util::type_list_element::type& get(const util::variant &v) + { + static_assert(Index < sizeof...(Types), + "`Index` it out of bound of `util::variant` type list"); + using ReturnType = typename util::type_list_element::type; + return get(v); + } + + template + bool holds_alternative(const util::variant &v) noexcept + { + return v.index() == util::variant::template index_of(); + } + +#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" +#endif + + template bool operator==(const variant &lhs, + const variant &rhs) + { + using V = variant; + + // Instantiate table only here since it requires operator== for + // should have operator== only if this one is used, not in general + static const std::array eqs = { + {(&V::template equal_h::help)...} + }; + if (lhs.index() != rhs.index()) + return false; + return (eqs[lhs.index()])(lhs.memory, rhs.memory); + } + +#if defined(__GNUC__) && (__GNUC__ == 11 || __GNUC__ == 12) +#pragma GCC diagnostic pop +#endif + + template bool operator!=(const variant &lhs, + const variant &rhs) + { + return !(lhs == rhs); + } + +namespace detail +{ + // terminate recursion implementation for `non-void` ReturnType + template + ReturnType apply_visitor_impl(Visitor&&, Variant&, + std::true_type, std::false_type, + VisitorArgs&& ...) + { + return {}; + } + + // terminate recursion implementation for `void` ReturnType + template + void apply_visitor_impl(Visitor&&, Variant&, + std::true_type, std::true_type, + VisitorArgs&& ...) + { + } + + // Intermediate resursion processor for Lambda Visitors + template + typename std::enable_if::type>::value, ReturnType>::type + apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, + std::integral_constant should_no_return, + VisitorArgs&& ...args) + { + static_assert(std::is_same(v)))>::value, + "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" + " must return the same type"); + suppress_unused_warning(not_processed); + if (v.index() == CurIndex) + { + return visitor.operator()(get(v), std::forward(args)... ); + } + + using is_variant_processed_t = std::integral_constant= ElemCount>; + return apply_visitor_impl( + std::forward(visitor), + std::forward(v), + is_variant_processed_t{}, + should_no_return, + std::forward(args)...); + } + + //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() + template + typename std::enable_if::type>, + typename std::decay::type>::value, ReturnType>::type + invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) + { + return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); + } + + //Visual Studio 2014 compilation fix: cast visitor to base class before invoke operator() + template + typename std::enable_if::type>, + typename std::decay::type>::value, ReturnType>::type + invoke_class_visitor(Visitor& visitor, Value&& v, VisitorArgs&&...args) + { + return static_cast::type>&>(visitor).operator() (CurIndex, std::forward(v), std::forward(args)... ); + } + + // Intermediate recursion processor for special case `visitor_interface` derived Visitors + template + typename std::enable_if::type>::value, ReturnType>::type + apply_visitor_impl(Visitor&& visitor, Variant&& v, std::false_type not_processed, + std::integral_constant should_no_return, + VisitorArgs&& ...args) + { + static_assert(std::is_same(v)))>::value, + "Different `ReturnType`s detected! All `Visitor::visit` or `overload_lamba_set`" + " must return the same type"); + suppress_unused_warning(not_processed); + if (v.index() == CurIndex) + { + return invoke_class_visitor(visitor, get(v), std::forward(args)... ); + } + + using is_variant_processed_t = std::integral_constant= ElemCount>; + return apply_visitor_impl( + std::forward(visitor), + std::forward(v), + is_variant_processed_t{}, + should_no_return, + std::forward(args)...); + } +} // namespace detail + + template + auto visit(Visitor &visitor, const Variant& var, VisitorArg &&...args) -> decltype(visitor(get<0>(var))) + { + constexpr std::size_t varsize = util::variant_size::value; + static_assert(varsize != 0, "utils::variant must contains one type at least "); + using is_variant_processed_t = std::false_type; + + using ReturnType = decltype(visitor(get<0>(var))); + using return_t = std::is_same; + return detail::apply_visitor_impl( + std::forward(visitor), + var, is_variant_processed_t{}, + return_t{}, + std::forward(args)...); + } + + template + auto visit(Visitor&& visitor, const Variant& var) -> decltype(visitor(get<0>(var))) + { + constexpr std::size_t varsize = util::variant_size::value; + static_assert(varsize != 0, "utils::variant must contains one type at least "); + using is_variant_processed_t = std::false_type; + + using ReturnType = decltype(visitor(get<0>(var))); + using return_t = std::is_same; + return detail::apply_visitor_impl( + std::forward(visitor), + var, is_variant_processed_t{}, + return_t{}); + } +} // namespace util +} // namespace cv + +#endif // OPENCV_GAPI_UTIL_VARIANT_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp b/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp index 65f0a4b7ec..4dcc1d4182 100644 --- a/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/gapi/video.hpp @@ -1,364 +1,364 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// -// Copyright (C) 2020 Intel Corporation - -#ifndef OPENCV_GAPI_VIDEO_HPP -#define OPENCV_GAPI_VIDEO_HPP - -#include // std::tuple - -#include - - -/** \defgroup gapi_video G-API Video processing functionality - */ - -namespace cv { namespace gapi { - -/** @brief Structure for the Kalman filter's initialization parameters.*/ - -struct GAPI_EXPORTS KalmanParams -{ - // initial state - - //! corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) - Mat state; - //! posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) - Mat errorCov; - - // dynamic system description - - //! state transition matrix (A) - Mat transitionMatrix; - //! measurement matrix (H) - Mat measurementMatrix; - //! process noise covariance matrix (Q) - Mat processNoiseCov; - //! measurement noise covariance matrix (R) - Mat measurementNoiseCov; - //! control matrix (B) (Optional: not used if there's no control) - Mat controlMatrix; -}; - -/** - * @brief This namespace contains G-API Operations and functions for - * video-oriented algorithms, like optical flow and background subtraction. - */ -namespace video -{ -using GBuildPyrOutput = std::tuple, GScalar>; - -using GOptFlowLKOutput = std::tuple, - cv::GArray, - cv::GArray>; - -G_TYPED_KERNEL(GBuildOptFlowPyramid, , - "org.opencv.video.buildOpticalFlowPyramid") -{ - static std::tuple - outMeta(GMatDesc,const Size&,GScalarDesc,bool,int,int,bool) - { - return std::make_tuple(empty_array_desc(), empty_scalar_desc()); - } -}; - -G_TYPED_KERNEL(GCalcOptFlowLK, - ,cv::GArray,Size, - GScalar,TermCriteria,int,double)>, - "org.opencv.video.calcOpticalFlowPyrLK") -{ - static std::tuple outMeta(GMatDesc,GMatDesc,GArrayDesc, - GArrayDesc,const Size&,GScalarDesc, - const TermCriteria&,int,double) - { - return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); - } - -}; - -G_TYPED_KERNEL(GCalcOptFlowLKForPyr, - ,cv::GArray, - cv::GArray,cv::GArray,Size,GScalar, - TermCriteria,int,double)>, - "org.opencv.video.calcOpticalFlowPyrLKForPyr") -{ - static std::tuple outMeta(GArrayDesc,GArrayDesc, - GArrayDesc,GArrayDesc, - const Size&,GScalarDesc, - const TermCriteria&,int,double) - { - return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); - } -}; - -enum BackgroundSubtractorType -{ - TYPE_BS_MOG2, - TYPE_BS_KNN -}; - -/** @brief Structure for the Background Subtractor operation's initialization parameters.*/ - -struct BackgroundSubtractorParams -{ - //! Type of the Background Subtractor operation. - BackgroundSubtractorType operation = TYPE_BS_MOG2; - - //! Length of the history. - int history = 500; - - //! For MOG2: Threshold on the squared Mahalanobis distance between the pixel - //! and the model to decide whether a pixel is well described by - //! the background model. - //! For KNN: Threshold on the squared distance between the pixel and the sample - //! to decide whether a pixel is close to that sample. - double threshold = 16; - - //! If true, the algorithm will detect shadows and mark them. - bool detectShadows = true; - - //! The value between 0 and 1 that indicates how fast - //! the background model is learnt. - //! Negative parameter value makes the algorithm use some automatically - //! chosen learning rate. - double learningRate = -1; - - //! default constructor - BackgroundSubtractorParams() {} - - /** Full constructor - @param op MOG2/KNN Background Subtractor type. - @param histLength Length of the history. - @param thrshld For MOG2: Threshold on the squared Mahalanobis distance between - the pixel and the model to decide whether a pixel is well described by the background model. - For KNN: Threshold on the squared distance between the pixel and the sample to decide - whether a pixel is close to that sample. - @param detect If true, the algorithm will detect shadows and mark them. It decreases the - speed a bit, so if you do not need this feature, set the parameter to false. - @param lRate The value between 0 and 1 that indicates how fast the background model is learnt. - Negative parameter value makes the algorithm to use some automatically chosen learning rate. - */ - BackgroundSubtractorParams(BackgroundSubtractorType op, int histLength, - double thrshld, bool detect, double lRate) : operation(op), - history(histLength), - threshold(thrshld), - detectShadows(detect), - learningRate(lRate){} -}; - -G_TYPED_KERNEL(GBackgroundSubtractor, , - "org.opencv.video.BackgroundSubtractor") -{ - static GMatDesc outMeta(const GMatDesc& in, const BackgroundSubtractorParams& bsParams) - { - GAPI_Assert(bsParams.history >= 0); - GAPI_Assert(bsParams.learningRate <= 1); - return in.withType(CV_8U, 1); - } -}; - -void checkParams(const cv::gapi::KalmanParams& kfParams, - const cv::GMatDesc& measurement, const cv::GMatDesc& control = {}); - -G_TYPED_KERNEL(GKalmanFilter, , GMat, KalmanParams)>, - "org.opencv.video.KalmanFilter") -{ - static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, - const GMatDesc& control, const KalmanParams& kfParams) - { - checkParams(kfParams, measurement, control); - return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); - } -}; - -G_TYPED_KERNEL(GKalmanFilterNoControl, , KalmanParams)>, "org.opencv.video.KalmanFilterNoControl") -{ - static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, const KalmanParams& kfParams) - { - checkParams(kfParams, measurement); - return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); - } -}; -} //namespace video - -//! @addtogroup gapi_video -//! @{ -/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. - -@note Function textual ID is "org.opencv.video.buildOpticalFlowPyramid" - -@param img 8-bit input image. -@param winSize window size of optical flow algorithm. Must be not less than winSize - argument of calcOpticalFlowPyrLK. It is needed to calculate required - padding for pyramid levels. -@param maxLevel 0-based maximal pyramid level number. -@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is - constructed without the gradients then calcOpticalFlowPyrLK will calculate - them internally. -@param pyrBorder the border mode for pyramid layers. -@param derivBorder the border mode for gradients. -@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false - to force data copying. - -@return - - output pyramid. - - number of levels in constructed pyramid. Can be less than maxLevel. - */ -GAPI_EXPORTS std::tuple, GScalar> -buildOpticalFlowPyramid(const GMat &img, - const Size &winSize, - const GScalar &maxLevel, - bool withDerivatives = true, - int pyrBorder = BORDER_REFLECT_101, - int derivBorder = BORDER_CONSTANT, - bool tryReuseInputImage = true); - -/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade -method with pyramids. - -See @cite Bouguet00 . - -@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLK" - -@param prevImg first 8-bit input image (GMat) or pyramid (GArray) constructed by -buildOpticalFlowPyramid. -@param nextImg second input image (GMat) or pyramid (GArray) of the same size and the same -type as prevImg. -@param prevPts GArray of 2D points for which the flow needs to be found; point coordinates must be -single-precision floating-point numbers. -@param predPts GArray of 2D points initial for the flow search; make sense only when -OPTFLOW_USE_INITIAL_FLOW flag is passed; in that case the vector must have the same size as in -the input. -@param winSize size of the search window at each pyramid level. -@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single -level), if set to 1, two levels are used, and so on; if pyramids are passed to input then -algorithm will use as many levels as pyramids have but no more than maxLevel. -@param criteria parameter, specifying the termination criteria of the iterative search algorithm -(after the specified maximum number of iterations criteria.maxCount or when the search window -moves by less than criteria.epsilon). -@param flags operation flags: - - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is - not set, then prevPts is copied to nextPts and is considered the initial estimate. - - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see - minEigThreshold description); if the flag is not set, then L1 distance between patches - around the original and a moved point, divided by number of pixels in a window, is used as a - error measure. -@param minEigThresh the algorithm calculates the minimum eigen value of a 2x2 normal matrix of -optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided -by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding -feature is filtered out and its flow is not processed, so it allows to remove bad points and get a -performance boost. - -@return - - GArray of 2D points (with single-precision floating-point coordinates) -containing the calculated new positions of input features in the second image. - - status GArray (of unsigned chars); each element of the vector is set to 1 if -the flow for the corresponding features has been found, otherwise, it is set to 0. - - GArray of errors (doubles); each element of the vector is set to an error for the -corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't -found then the error is not defined (use the status parameter to find such cases). - */ -GAPI_EXPORTS std::tuple, GArray, GArray> -calcOpticalFlowPyrLK(const GMat &prevImg, - const GMat &nextImg, - const GArray &prevPts, - const GArray &predPts, - const Size &winSize = Size(21, 21), - const GScalar &maxLevel = 3, - const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | - TermCriteria::EPS, - 30, 0.01), - int flags = 0, - double minEigThresh = 1e-4); - -/** -@overload -@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLKForPyr" -*/ -GAPI_EXPORTS std::tuple, GArray, GArray> -calcOpticalFlowPyrLK(const GArray &prevPyr, - const GArray &nextPyr, - const GArray &prevPts, - const GArray &predPts, - const Size &winSize = Size(21, 21), - const GScalar &maxLevel = 3, - const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | - TermCriteria::EPS, - 30, 0.01), - int flags = 0, - double minEigThresh = 1e-4); - -/** @brief Gaussian Mixture-based or K-nearest neighbours-based Background/Foreground Segmentation Algorithm. -The operation generates a foreground mask. - -@return Output image is foreground mask, i.e. 8-bit unsigned 1-channel (binary) matrix @ref CV_8UC1. - -@note Functional textual ID is "org.opencv.video.BackgroundSubtractor" - -@param src input image: Floating point frame is used without scaling and should be in range [0,255]. -@param bsParams Set of initialization parameters for Background Subtractor kernel. -*/ -GAPI_EXPORTS GMat BackgroundSubtractor(const GMat& src, const cv::gapi::video::BackgroundSubtractorParams& bsParams); - -/** @brief Standard Kalman filter algorithm . - -@note Functional textual ID is "org.opencv.video.KalmanFilter" - -@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. -@param haveMeasurement dynamic input flag that indicates whether we get measurements -at a particular iteration . -@param control input matrix: 32-bit or 64-bit float 1-channel matrix contains control data -for changing dynamic system. -@param kfParams Set of initialization parameters for Kalman filter kernel. - -@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float -1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. - -@details If measurement matrix is given (haveMeasurements == true), corrected state will -be returned which corresponds to the pipeline -cv::KalmanFilter::predict(control) -> cv::KalmanFilter::correct(measurement). -Otherwise, predicted state will be returned which corresponds to the call of -cv::KalmanFilter::predict(control). -@sa cv::KalmanFilter -*/ -GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, - const GMat& control, const cv::gapi::KalmanParams& kfParams); - -/** @overload -The case of Standard Kalman filter algorithm when there is no control in a dynamic system. -In this case the controlMatrix is empty and control vector is absent. - -@note Function textual ID is "org.opencv.video.KalmanFilterNoControl" - -@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. -@param haveMeasurement dynamic input flag that indicates whether we get measurements -at a particular iteration. -@param kfParams Set of initialization parameters for Kalman filter kernel. - -@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float -1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. - -@sa cv::KalmanFilter - */ -GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, - const cv::gapi::KalmanParams& kfParams); - -//! @} gapi_video -} //namespace gapi -} //namespace cv - - -namespace cv { namespace detail { -template<> struct CompileArgTag -{ - static const char* tag() - { - return "org.opencv.video.background_substractor_params"; - } -}; -} // namespace detail -} // namespace cv - -#endif // OPENCV_GAPI_VIDEO_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// +// Copyright (C) 2020 Intel Corporation + +#ifndef OPENCV_GAPI_VIDEO_HPP +#define OPENCV_GAPI_VIDEO_HPP + +#include // std::tuple + +#include + + +/** \defgroup gapi_video G-API Video processing functionality + */ + +namespace cv { namespace gapi { + +/** @brief Structure for the Kalman filter's initialization parameters.*/ + +struct GAPI_EXPORTS KalmanParams +{ + // initial state + + //! corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) + Mat state; + //! posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) + Mat errorCov; + + // dynamic system description + + //! state transition matrix (A) + Mat transitionMatrix; + //! measurement matrix (H) + Mat measurementMatrix; + //! process noise covariance matrix (Q) + Mat processNoiseCov; + //! measurement noise covariance matrix (R) + Mat measurementNoiseCov; + //! control matrix (B) (Optional: not used if there's no control) + Mat controlMatrix; +}; + +/** + * @brief This namespace contains G-API Operations and functions for + * video-oriented algorithms, like optical flow and background subtraction. + */ +namespace video +{ +using GBuildPyrOutput = std::tuple, GScalar>; + +using GOptFlowLKOutput = std::tuple, + cv::GArray, + cv::GArray>; + +G_TYPED_KERNEL(GBuildOptFlowPyramid, , + "org.opencv.video.buildOpticalFlowPyramid") +{ + static std::tuple + outMeta(GMatDesc,const Size&,GScalarDesc,bool,int,int,bool) + { + return std::make_tuple(empty_array_desc(), empty_scalar_desc()); + } +}; + +G_TYPED_KERNEL(GCalcOptFlowLK, + ,cv::GArray,Size, + GScalar,TermCriteria,int,double)>, + "org.opencv.video.calcOpticalFlowPyrLK") +{ + static std::tuple outMeta(GMatDesc,GMatDesc,GArrayDesc, + GArrayDesc,const Size&,GScalarDesc, + const TermCriteria&,int,double) + { + return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); + } + +}; + +G_TYPED_KERNEL(GCalcOptFlowLKForPyr, + ,cv::GArray, + cv::GArray,cv::GArray,Size,GScalar, + TermCriteria,int,double)>, + "org.opencv.video.calcOpticalFlowPyrLKForPyr") +{ + static std::tuple outMeta(GArrayDesc,GArrayDesc, + GArrayDesc,GArrayDesc, + const Size&,GScalarDesc, + const TermCriteria&,int,double) + { + return std::make_tuple(empty_array_desc(), empty_array_desc(), empty_array_desc()); + } +}; + +enum BackgroundSubtractorType +{ + TYPE_BS_MOG2, + TYPE_BS_KNN +}; + +/** @brief Structure for the Background Subtractor operation's initialization parameters.*/ + +struct BackgroundSubtractorParams +{ + //! Type of the Background Subtractor operation. + BackgroundSubtractorType operation = TYPE_BS_MOG2; + + //! Length of the history. + int history = 500; + + //! For MOG2: Threshold on the squared Mahalanobis distance between the pixel + //! and the model to decide whether a pixel is well described by + //! the background model. + //! For KNN: Threshold on the squared distance between the pixel and the sample + //! to decide whether a pixel is close to that sample. + double threshold = 16; + + //! If true, the algorithm will detect shadows and mark them. + bool detectShadows = true; + + //! The value between 0 and 1 that indicates how fast + //! the background model is learnt. + //! Negative parameter value makes the algorithm use some automatically + //! chosen learning rate. + double learningRate = -1; + + //! default constructor + BackgroundSubtractorParams() {} + + /** Full constructor + @param op MOG2/KNN Background Subtractor type. + @param histLength Length of the history. + @param thrshld For MOG2: Threshold on the squared Mahalanobis distance between + the pixel and the model to decide whether a pixel is well described by the background model. + For KNN: Threshold on the squared distance between the pixel and the sample to decide + whether a pixel is close to that sample. + @param detect If true, the algorithm will detect shadows and mark them. It decreases the + speed a bit, so if you do not need this feature, set the parameter to false. + @param lRate The value between 0 and 1 that indicates how fast the background model is learnt. + Negative parameter value makes the algorithm to use some automatically chosen learning rate. + */ + BackgroundSubtractorParams(BackgroundSubtractorType op, int histLength, + double thrshld, bool detect, double lRate) : operation(op), + history(histLength), + threshold(thrshld), + detectShadows(detect), + learningRate(lRate){} +}; + +G_TYPED_KERNEL(GBackgroundSubtractor, , + "org.opencv.video.BackgroundSubtractor") +{ + static GMatDesc outMeta(const GMatDesc& in, const BackgroundSubtractorParams& bsParams) + { + GAPI_Assert(bsParams.history >= 0); + GAPI_Assert(bsParams.learningRate <= 1); + return in.withType(CV_8U, 1); + } +}; + +void checkParams(const cv::gapi::KalmanParams& kfParams, + const cv::GMatDesc& measurement, const cv::GMatDesc& control = {}); + +G_TYPED_KERNEL(GKalmanFilter, , GMat, KalmanParams)>, + "org.opencv.video.KalmanFilter") +{ + static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, + const GMatDesc& control, const KalmanParams& kfParams) + { + checkParams(kfParams, measurement, control); + return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); + } +}; + +G_TYPED_KERNEL(GKalmanFilterNoControl, , KalmanParams)>, "org.opencv.video.KalmanFilterNoControl") +{ + static GMatDesc outMeta(const GMatDesc& measurement, const GOpaqueDesc&, const KalmanParams& kfParams) + { + checkParams(kfParams, measurement); + return measurement.withSize(Size(1, kfParams.transitionMatrix.rows)); + } +}; +} //namespace video + +//! @addtogroup gapi_video +//! @{ +/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. + +@note Function textual ID is "org.opencv.video.buildOpticalFlowPyramid" + +@param img 8-bit input image. +@param winSize window size of optical flow algorithm. Must be not less than winSize + argument of calcOpticalFlowPyrLK. It is needed to calculate required + padding for pyramid levels. +@param maxLevel 0-based maximal pyramid level number. +@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is + constructed without the gradients then calcOpticalFlowPyrLK will calculate + them internally. +@param pyrBorder the border mode for pyramid layers. +@param derivBorder the border mode for gradients. +@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false + to force data copying. + +@return + - output pyramid. + - number of levels in constructed pyramid. Can be less than maxLevel. + */ +GAPI_EXPORTS std::tuple, GScalar> +buildOpticalFlowPyramid(const GMat &img, + const Size &winSize, + const GScalar &maxLevel, + bool withDerivatives = true, + int pyrBorder = BORDER_REFLECT_101, + int derivBorder = BORDER_CONSTANT, + bool tryReuseInputImage = true); + +/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade +method with pyramids. + +See @cite Bouguet00 . + +@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLK" + +@param prevImg first 8-bit input image (GMat) or pyramid (GArray) constructed by +buildOpticalFlowPyramid. +@param nextImg second input image (GMat) or pyramid (GArray) of the same size and the same +type as prevImg. +@param prevPts GArray of 2D points for which the flow needs to be found; point coordinates must be +single-precision floating-point numbers. +@param predPts GArray of 2D points initial for the flow search; make sense only when +OPTFLOW_USE_INITIAL_FLOW flag is passed; in that case the vector must have the same size as in +the input. +@param winSize size of the search window at each pyramid level. +@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single +level), if set to 1, two levels are used, and so on; if pyramids are passed to input then +algorithm will use as many levels as pyramids have but no more than maxLevel. +@param criteria parameter, specifying the termination criteria of the iterative search algorithm +(after the specified maximum number of iterations criteria.maxCount or when the search window +moves by less than criteria.epsilon). +@param flags operation flags: + - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is + not set, then prevPts is copied to nextPts and is considered the initial estimate. + - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see + minEigThreshold description); if the flag is not set, then L1 distance between patches + around the original and a moved point, divided by number of pixels in a window, is used as a + error measure. +@param minEigThresh the algorithm calculates the minimum eigen value of a 2x2 normal matrix of +optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided +by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding +feature is filtered out and its flow is not processed, so it allows to remove bad points and get a +performance boost. + +@return + - GArray of 2D points (with single-precision floating-point coordinates) +containing the calculated new positions of input features in the second image. + - status GArray (of unsigned chars); each element of the vector is set to 1 if +the flow for the corresponding features has been found, otherwise, it is set to 0. + - GArray of errors (doubles); each element of the vector is set to an error for the +corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't +found then the error is not defined (use the status parameter to find such cases). + */ +GAPI_EXPORTS std::tuple, GArray, GArray> +calcOpticalFlowPyrLK(const GMat &prevImg, + const GMat &nextImg, + const GArray &prevPts, + const GArray &predPts, + const Size &winSize = Size(21, 21), + const GScalar &maxLevel = 3, + const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | + TermCriteria::EPS, + 30, 0.01), + int flags = 0, + double minEigThresh = 1e-4); + +/** +@overload +@note Function textual ID is "org.opencv.video.calcOpticalFlowPyrLKForPyr" +*/ +GAPI_EXPORTS std::tuple, GArray, GArray> +calcOpticalFlowPyrLK(const GArray &prevPyr, + const GArray &nextPyr, + const GArray &prevPts, + const GArray &predPts, + const Size &winSize = Size(21, 21), + const GScalar &maxLevel = 3, + const TermCriteria &criteria = TermCriteria(TermCriteria::COUNT | + TermCriteria::EPS, + 30, 0.01), + int flags = 0, + double minEigThresh = 1e-4); + +/** @brief Gaussian Mixture-based or K-nearest neighbours-based Background/Foreground Segmentation Algorithm. +The operation generates a foreground mask. + +@return Output image is foreground mask, i.e. 8-bit unsigned 1-channel (binary) matrix @ref CV_8UC1. + +@note Functional textual ID is "org.opencv.video.BackgroundSubtractor" + +@param src input image: Floating point frame is used without scaling and should be in range [0,255]. +@param bsParams Set of initialization parameters for Background Subtractor kernel. +*/ +GAPI_EXPORTS GMat BackgroundSubtractor(const GMat& src, const cv::gapi::video::BackgroundSubtractorParams& bsParams); + +/** @brief Standard Kalman filter algorithm . + +@note Functional textual ID is "org.opencv.video.KalmanFilter" + +@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. +@param haveMeasurement dynamic input flag that indicates whether we get measurements +at a particular iteration . +@param control input matrix: 32-bit or 64-bit float 1-channel matrix contains control data +for changing dynamic system. +@param kfParams Set of initialization parameters for Kalman filter kernel. + +@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float +1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. + +@details If measurement matrix is given (haveMeasurements == true), corrected state will +be returned which corresponds to the pipeline +cv::KalmanFilter::predict(control) -> cv::KalmanFilter::correct(measurement). +Otherwise, predicted state will be returned which corresponds to the call of +cv::KalmanFilter::predict(control). +@sa cv::KalmanFilter +*/ +GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, + const GMat& control, const cv::gapi::KalmanParams& kfParams); + +/** @overload +The case of Standard Kalman filter algorithm when there is no control in a dynamic system. +In this case the controlMatrix is empty and control vector is absent. + +@note Function textual ID is "org.opencv.video.KalmanFilterNoControl" + +@param measurement input matrix: 32-bit or 64-bit float 1-channel matrix containing measurements. +@param haveMeasurement dynamic input flag that indicates whether we get measurements +at a particular iteration. +@param kfParams Set of initialization parameters for Kalman filter kernel. + +@return Output matrix is predicted or corrected state. They can be 32-bit or 64-bit float +1-channel matrix @ref CV_32FC1 or @ref CV_64FC1. + +@sa cv::KalmanFilter + */ +GAPI_EXPORTS GMat KalmanFilter(const GMat& measurement, const GOpaque& haveMeasurement, + const cv::gapi::KalmanParams& kfParams); + +//! @} gapi_video +} //namespace gapi +} //namespace cv + + +namespace cv { namespace detail { +template<> struct CompileArgTag +{ + static const char* tag() + { + return "org.opencv.video.background_substractor_params"; + } +}; +} // namespace detail +} // namespace cv + +#endif // OPENCV_GAPI_VIDEO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/highgui.hpp b/3rdParty/opencv-4.11.0/opencv2/highgui.hpp index 81437f4ef1..5f69721ce9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/highgui.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/highgui.hpp @@ -1,830 +1,830 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HIGHGUI_HPP -#define OPENCV_HIGHGUI_HPP - -#include "opencv2/core.hpp" -#ifdef HAVE_OPENCV_IMGCODECS -#include "opencv2/imgcodecs.hpp" -#endif -#ifdef HAVE_OPENCV_VIDEOIO -#include "opencv2/videoio.hpp" -#endif - -/** -@defgroup highgui High-level GUI - -While OpenCV was designed for use in full-scale applications and can be used within functionally -rich UI frameworks (such as Qt\*, WinForms\*, or Cocoa\*) or without any UI at all, sometimes there -it is required to try functionality quickly and visualize the results. This is what the HighGUI -module has been designed for. - -It provides easy interface to: - -- Create and manipulate windows that can display images and "remember" their content (no need to - handle repaint events from OS). -- Add trackbars to the windows, handle simple mouse events as well as keyboard commands. - -@{ - @defgroup highgui_window_flags Flags related creating and manipulating HighGUI windows and mouse events - @defgroup highgui_opengl OpenGL support - @defgroup highgui_qt Qt New Functions - - ![image](pics/qtgui.png) - - This figure explains new functionality implemented with Qt\* GUI. The new GUI provides a statusbar, - a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. - If you cannot see the control panel, press Ctrl+P or right-click any Qt window and select **Display - properties window**. - - - To attach a trackbar, the window name parameter must be NULL. - - - To attach a buttonbar, a button must be created. If the last bar attached to the control panel - is a buttonbar, the new button is added to the right of the last button. If the last bar - attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is - created. Then, a new button is attached to it. - - See below the example used to generate the figure: - - @include highgui_qt.cpp - - @defgroup highgui_winrt WinRT support - - This figure explains new functionality implemented with WinRT GUI. The new GUI provides an Image control, - and a slider panel. Slider panel holds trackbars attached to it. - - Sliders are attached below the image control. Every new slider is added below the previous one. - - See below the example used to generate the figure: - @code - void sample_app::MainPage::ShowWindow() - { - static cv::String windowName("sample"); - cv::winrt_initContainer(this->cvContainer); - cv::namedWindow(windowName); // not required - - cv::Mat image = cv::imread("Assets/sample.jpg"); - cv::Mat converted = cv::Mat(image.rows, image.cols, CV_8UC4); - cv::cvtColor(image, converted, COLOR_BGR2BGRA); - cv::imshow(windowName, converted); // this will create window if it hasn't been created before - - int state = 42; - cv::TrackbarCallback callback = [](int pos, void* userdata) - { - if (pos == 0) { - cv::destroyWindow(windowName); - } - }; - cv::TrackbarCallback callbackTwin = [](int pos, void* userdata) - { - if (pos >= 70) { - cv::destroyAllWindows(); - } - }; - cv::createTrackbar("Sample trackbar", windowName, &state, 100, callback); - cv::createTrackbar("Twin brother", windowName, &state, 100, callbackTwin); - } - @endcode -@} -*/ - -///////////////////////// graphical user interface ////////////////////////// -namespace cv -{ - -//! @addtogroup highgui -//! @{ - -//! @addtogroup highgui_window_flags -//! @{ - -//! Flags for cv::namedWindow -enum WindowFlags { - WINDOW_NORMAL = 0x00000000, //!< the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size. - WINDOW_AUTOSIZE = 0x00000001, //!< the user cannot resize the window, the size is constrainted by the image displayed. - WINDOW_OPENGL = 0x00001000, //!< window with opengl support. - - WINDOW_FULLSCREEN = 1, //!< change the window to fullscreen. - WINDOW_FREERATIO = 0x00000100, //!< the image expends as much as it can (no ratio constraint). - WINDOW_KEEPRATIO = 0x00000000, //!< the ratio of the image is respected. - WINDOW_GUI_EXPANDED=0x00000000, //!< status bar and tool bar - WINDOW_GUI_NORMAL = 0x00000010, //!< old fashious way - }; - -//! Flags for cv::setWindowProperty / cv::getWindowProperty -enum WindowPropertyFlags { - WND_PROP_FULLSCREEN = 0, //!< fullscreen property (can be WINDOW_NORMAL or WINDOW_FULLSCREEN). - WND_PROP_AUTOSIZE = 1, //!< autosize property (can be WINDOW_NORMAL or WINDOW_AUTOSIZE). - WND_PROP_ASPECT_RATIO = 2, //!< window's aspect ration (can be set to WINDOW_FREERATIO or WINDOW_KEEPRATIO). - WND_PROP_OPENGL = 3, //!< opengl support. - WND_PROP_VISIBLE = 4, //!< checks whether the window exists and is visible - WND_PROP_TOPMOST = 5, //!< property to toggle normal window being topmost or not - WND_PROP_VSYNC = 6 //!< enable or disable VSYNC (in OpenGL mode) - }; - -//! Mouse Events see cv::MouseCallback -enum MouseEventTypes { - EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window. - EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed. - EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed. - EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed. - EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released. - EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released. - EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released. - EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked. - EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked. - EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked. - EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively. - EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively. - }; - -//! Mouse Event Flags see cv::MouseCallback -enum MouseEventFlags { - EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down. - EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down. - EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down. - EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed. - EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed. - EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed. - }; - -//! @} highgui_window_flags - -//! @addtogroup highgui_qt -//! @{ - -//! Qt font weight -enum QtFontWeights { - QT_FONT_LIGHT = 25, //!< Weight of 25 - QT_FONT_NORMAL = 50, //!< Weight of 50 - QT_FONT_DEMIBOLD = 63, //!< Weight of 63 - QT_FONT_BOLD = 75, //!< Weight of 75 - QT_FONT_BLACK = 87 //!< Weight of 87 - }; - -//! Qt font style -enum QtFontStyles { - QT_STYLE_NORMAL = 0, //!< Normal font. - QT_STYLE_ITALIC = 1, //!< Italic font. - QT_STYLE_OBLIQUE = 2 //!< Oblique font. - }; - -//! Qt "button" type -enum QtButtonTypes { - QT_PUSH_BUTTON = 0, //!< Push button. - QT_CHECKBOX = 1, //!< Checkbox button. - QT_RADIOBOX = 2, //!< Radiobox button. - QT_NEW_BUTTONBAR = 1024 //!< Button should create a new buttonbar - }; - -//! @} highgui_qt - -/** @brief Callback function for mouse events. see cv::setMouseCallback -@param event one of the cv::MouseEventTypes constants. -@param x The x-coordinate of the mouse event. -@param y The y-coordinate of the mouse event. -@param flags one of the cv::MouseEventFlags constants. -@param userdata The optional parameter. - */ -typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); - -/** @brief Callback function for Trackbar see cv::createTrackbar -@param pos current position of the specified trackbar. -@param userdata The optional parameter. - */ -typedef void (*TrackbarCallback)(int pos, void* userdata); - -/** @brief Callback function defined to be called every frame. See cv::setOpenGlDrawCallback -@param userdata The optional parameter. - */ -typedef void (*OpenGlDrawCallback)(void* userdata); - -/** @brief Callback function for a button created by cv::createButton -@param state current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. -@param userdata The optional parameter. - */ -typedef void (*ButtonCallback)(int state, void* userdata); - -/** @brief Creates a window. - -The function namedWindow creates a window that can be used as a placeholder for images and -trackbars. Created windows are referred to by their names. - -If a window with the same name already exists, the function does nothing. - -You can call cv::destroyWindow or cv::destroyAllWindows to close the window and de-allocate any associated -memory usage. For a simple program, you do not really have to call these functions because all the -resources and windows of the application are closed automatically by the operating system upon exit. - -@note Qt backend supports additional flags: - - **WINDOW_NORMAL or WINDOW_AUTOSIZE:** WINDOW_NORMAL enables you to resize the - window, whereas WINDOW_AUTOSIZE adjusts automatically the window size to fit the - displayed image (see imshow ), and you cannot change the window size manually. - - **WINDOW_FREERATIO or WINDOW_KEEPRATIO:** WINDOW_FREERATIO adjusts the image - with no respect to its ratio, whereas WINDOW_KEEPRATIO keeps the image ratio. - - **WINDOW_GUI_NORMAL or WINDOW_GUI_EXPANDED:** WINDOW_GUI_NORMAL is the old way to draw the window - without statusbar and toolbar, whereas WINDOW_GUI_EXPANDED is a new enhanced GUI. -By default, flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO | WINDOW_GUI_EXPANDED - -@param winname Name of the window in the window caption that may be used as a window identifier. -@param flags Flags of the window. The supported flags are: (cv::WindowFlags) - */ -CV_EXPORTS_W void namedWindow(const String& winname, int flags = WINDOW_AUTOSIZE); - -/** @brief Destroys the specified window. - -The function destroyWindow destroys the window with the given name. - -@param winname Name of the window to be destroyed. - */ -CV_EXPORTS_W void destroyWindow(const String& winname); - -/** @brief Destroys all of the HighGUI windows. - -The function destroyAllWindows destroys all of the opened HighGUI windows. - */ -CV_EXPORTS_W void destroyAllWindows(); - - -/** @brief HighGUI backend used. - -The function returns HighGUI backend name used: could be COCOA, GTK2/3, QT, WAYLAND or WIN32. -Returns empty string if there is no available UI backend. - */ -CV_EXPORTS_W const std::string currentUIFramework(); - - -CV_EXPORTS_W int startWindowThread(); - -/** @brief Similar to #waitKey, but returns full key code. - -@note Key code is implementation specific and depends on used backend: QT/GTK/Win32/etc - -*/ -CV_EXPORTS_W int waitKeyEx(int delay = 0); - -/** @brief Waits for a pressed key. - -The function waitKey waits for a key event infinitely (when \f$\texttt{delay}\leq 0\f$ ) or for delay -milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the -function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is -running on your computer at that time. It returns the code of the pressed key or -1 if no key was -pressed before the specified time had elapsed. To check for a key press but not wait for it, use -#pollKey. - -@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle -GUI events, so one of them needs to be called periodically for normal event processing unless -HighGUI is used within an environment that takes care of event processing. - -@note The function only works if there is at least one HighGUI window created and the window is -active. If there are several HighGUI windows, any of them can be active. - -@param delay Delay in milliseconds. 0 is the special value that means "forever". - */ -CV_EXPORTS_W int waitKey(int delay = 0); - -/** @brief Polls for a pressed key. - -The function pollKey polls for a key event without waiting. It returns the code of the pressed key -or -1 if no key was pressed since the last invocation. To wait until a key was pressed, use #waitKey. - -@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle -GUI events, so one of them needs to be called periodically for normal event processing unless -HighGUI is used within an environment that takes care of event processing. - -@note The function only works if there is at least one HighGUI window created and the window is -active. If there are several HighGUI windows, any of them can be active. - */ -CV_EXPORTS_W int pollKey(); - -/** @brief Displays an image in the specified window. - -The function imshow displays an image in the specified window. If the window was created with the -cv::WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution. -Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth: - -- If the image is 8-bit unsigned, it is displayed as is. -- If the image is 16-bit unsigned, the pixels are divided by 256. That is, the - value range [0,255\*256] is mapped to [0,255]. -- If the image is 32-bit or 64-bit floating-point, the pixel values are multiplied by 255. That is, the - value range [0,1] is mapped to [0,255]. -- 32-bit integer images are not processed anymore due to ambiguouty of required transform. - Convert to 8-bit unsigned matrix using a custom preprocessing specific to image's context. - -If window was created with OpenGL support, cv::imshow also support ogl::Buffer , ogl::Texture2D and -cuda::GpuMat as input. - -If the window was not created before this function, it is assumed creating a window with cv::WINDOW_AUTOSIZE. - -If you need to show an image that is bigger than the screen resolution, you will need to call namedWindow("", WINDOW_NORMAL) before the imshow. - -@note This function should be followed by a call to cv::waitKey or cv::pollKey to perform GUI -housekeeping tasks that are necessary to actually show the given image and make the window respond -to mouse and keyboard events. Otherwise, it won't display the image and the window might lock up. -For example, **waitKey(0)** will display the window infinitely until any keypress (it is suitable -for image display). **waitKey(25)** will display a frame and wait approximately 25 ms for a key -press (suitable for displaying a video frame-by-frame). To remove the window, use cv::destroyWindow. - -@note [__Windows Backend Only__] Pressing Ctrl+C will copy the image to the clipboard. Pressing Ctrl+S will show a dialog to save the image. -@note [__Wayland Backend Only__] Supoorting format is extended. -- If the image is 8-bit signed, the pixels are biased by 128. That is, the - value range [-128,127] is mapped to [0,255]. -- If the image is 16-bit signed, the pixels are divided by 256 and biased by 128. That is, the - value range [-32768,32767] is mapped to [0,255]. - -@param winname Name of the window. -@param mat Image to be shown. - */ -CV_EXPORTS_W void imshow(const String& winname, InputArray mat); - -/** @brief Resizes the window to the specified size - -@note The specified window size is for the image area. Toolbars are not counted. -Only windows created without cv::WINDOW_AUTOSIZE flag can be resized. - -@param winname Window name. -@param width The new window width. -@param height The new window height. - */ -CV_EXPORTS_W void resizeWindow(const String& winname, int width, int height); - -/** @overload -@param winname Window name. -@param size The new window size. -*/ -CV_EXPORTS_W void resizeWindow(const String& winname, const cv::Size& size); - -/** @brief Moves the window to the specified position - -@param winname Name of the window. -@param x The new x-coordinate of the window. -@param y The new y-coordinate of the window. - -@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. - */ -CV_EXPORTS_W void moveWindow(const String& winname, int x, int y); - -/** @brief Changes parameters of a window dynamically. - -The function setWindowProperty enables changing properties of a window. - -@param winname Name of the window. -@param prop_id Window property to edit. The supported operation flags are: (cv::WindowPropertyFlags) -@param prop_value New value of the window property. The supported flags are: (cv::WindowFlags) - -@note [__Wayland Backend Only__] This function is not supported. - */ -CV_EXPORTS_W void setWindowProperty(const String& winname, int prop_id, double prop_value); - -/** @brief Updates window title -@param winname Name of the window. -@param title New title. -*/ -CV_EXPORTS_W void setWindowTitle(const String& winname, const String& title); - -/** @brief Provides parameters of a window. - -The function getWindowProperty returns properties of a window. - -@param winname Name of the window. -@param prop_id Window property to retrieve. The following operation flags are available: (cv::WindowPropertyFlags) - -@sa setWindowProperty - -@note [__Wayland Backend Only__] This function is not supported. - */ -CV_EXPORTS_W double getWindowProperty(const String& winname, int prop_id); - -/** @brief Provides rectangle of image in the window. - -The function getWindowImageRect returns the client screen coordinates, width and height of the image rendering area. - -@param winname Name of the window. - -@sa resizeWindow moveWindow - -@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. - */ -CV_EXPORTS_W Rect getWindowImageRect(const String& winname); - -/** @example samples/cpp/create_mask.cpp -This program demonstrates using mouse events and how to make and use a mask image (black and white) . -*/ -/** @brief Sets mouse handler for the specified window - -@param winname Name of the window. -@param onMouse Callback function for mouse events. See OpenCV samples on how to specify and use the callback. -@param userdata The optional parameter passed to the callback. - */ -CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0); - -/** @brief Gets the mouse-wheel motion delta, when handling mouse-wheel events cv::EVENT_MOUSEWHEEL and -cv::EVENT_MOUSEHWHEEL. - -For regular mice with a scroll-wheel, delta will be a multiple of 120. The value 120 corresponds to -a one notch rotation of the wheel or the threshold for action to be taken and one such action should -occur for each delta. Some high-precision mice with higher-resolution freely-rotating wheels may -generate smaller values. - -For cv::EVENT_MOUSEWHEEL positive and negative values mean forward and backward scrolling, -respectively. For cv::EVENT_MOUSEHWHEEL, where available, positive and negative values mean right and -left scrolling, respectively. - -@note Mouse-wheel events are currently supported only on Windows and Cocoa. - -@param flags The mouse callback flags parameter. - */ -CV_EXPORTS int getMouseWheelDelta(int flags); - -/** @brief Allows users to select a ROI on the given image. - -The function creates a window and allows users to select a ROI using the mouse. -Controls: use `space` or `enter` to finish selection, use key `c` to cancel selection (function will return the zero cv::Rect). - -@param windowName name of the window where selection process will be shown. -@param img image to select a ROI. -@param showCrosshair if true crosshair of selection rectangle will be shown. -@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of -selection rectangle will correspont to the initial mouse position. -@param printNotice if true a notice to select ROI or cancel selection will be printed in console. -@return selected ROI or empty rect if selection canceled. - -@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). -After finish of work an empty callback will be set for the used window. - */ -CV_EXPORTS_W Rect selectROI(const String& windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); - -/** @overload - */ -CV_EXPORTS_W Rect selectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); - -/** @brief Allows users to select multiple ROIs on the given image. - -The function creates a window and allows users to select multiple ROIs using the mouse. -Controls: use `space` or `enter` to finish current selection and start a new one, -use `esc` to terminate multiple ROI selection process. - -@param windowName name of the window where selection process will be shown. -@param img image to select a ROI. -@param boundingBoxes selected ROIs. -@param showCrosshair if true crosshair of selection rectangle will be shown. -@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of -selection rectangle will correspont to the initial mouse position. -@param printNotice if true a notice to select ROI or cancel selection will be printed in console. - -@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). -After finish of work an empty callback will be set for the used window. - */ -CV_EXPORTS_W void selectROIs(const String& windowName, InputArray img, - CV_OUT std::vector& boundingBoxes, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); - -/** @brief Creates a trackbar and attaches it to the specified window. - -The function createTrackbar creates a trackbar (a slider or range control) with the specified name -and range, assigns a variable value to be a position synchronized with the trackbar and specifies -the callback function onChange to be called on the trackbar position change. The created trackbar is -displayed in the specified window winname. - -@note [__Qt Backend Only__] winname can be empty if the trackbar should be attached to the -control panel. - -Clicking the label of each trackbar enables editing the trackbar values manually. - -@param trackbarname Name of the created trackbar. -@param winname Name of the window that will contain the trackbar. -@param value Pointer to the integer value that will be changed by the trackbar. -Pass `nullptr` if the value pointer is not used. In this case, manually handle -the trackbar position in the callback function. -@param count Maximum position of the trackbar. -@param onChange Pointer to the function to be called every time the slider changes position. -This function should have the prototype void Foo(int, void\*);, where the first parameter is -the trackbar position, and the second parameter is the user data (see the next parameter). -If the callback is a nullptr, no callbacks are called, but the trackbar's value will still be -updated automatically. -@param userdata Optional user data that is passed to the callback. -@note If the `value` pointer is `nullptr`, the trackbar position must be manually managed. -Call the callback function manually with the desired initial value to avoid runtime warnings. -@see \ref tutorial_trackbar - */ -CV_EXPORTS int createTrackbar(const String& trackbarname, const String& winname, - int* value, int count, - TrackbarCallback onChange = 0, - void* userdata = 0); - -/** @brief Returns the trackbar position. - -The function returns the current position of the specified trackbar. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of the trackbar. - */ -CV_EXPORTS_W int getTrackbarPos(const String& trackbarname, const String& winname); - -/** @brief Sets the trackbar position. - -The function sets the position of the specified trackbar in the specified window. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of trackbar. -@param pos New position. - */ -CV_EXPORTS_W void setTrackbarPos(const String& trackbarname, const String& winname, int pos); - -/** @brief Sets the trackbar maximum position. - -The function sets the maximum position of the specified trackbar in the specified window. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of trackbar. -@param maxval New maximum position. - */ -CV_EXPORTS_W void setTrackbarMax(const String& trackbarname, const String& winname, int maxval); - -/** @brief Sets the trackbar minimum position. - -The function sets the minimum position of the specified trackbar in the specified window. - -@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control -panel. - -@param trackbarname Name of the trackbar. -@param winname Name of the window that is the parent of trackbar. -@param minval New minimum position. - */ -CV_EXPORTS_W void setTrackbarMin(const String& trackbarname, const String& winname, int minval); - -//! @addtogroup highgui_opengl OpenGL support -//! @{ - -/** @brief Displays OpenGL 2D texture in the specified window. - -@param winname Name of the window. -@param tex OpenGL 2D texture data. - */ -CV_EXPORTS void imshow(const String& winname, const ogl::Texture2D& tex); - -/** @brief Sets a callback function to be called to draw on top of displayed image. - -The function setOpenGlDrawCallback can be used to draw 3D data on the window. See the example of -callback function below: -@code - void on_opengl(void* param) - { - glLoadIdentity(); - - glTranslated(0.0, 0.0, -1.0); - - glRotatef( 55, 1, 0, 0 ); - glRotatef( 45, 0, 1, 0 ); - glRotatef( 0, 0, 0, 1 ); - - static const int coords[6][4][3] = { - { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, - { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, - { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, - { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, - { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, - { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } - }; - - for (int i = 0; i < 6; ++i) { - glColor3ub( i*20, 100+i*10, i*42 ); - glBegin(GL_QUADS); - for (int j = 0; j < 4; ++j) { - glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); - } - glEnd(); - } - } -@endcode - -@param winname Name of the window. -@param onOpenGlDraw Pointer to the function to be called every frame. This function should be -prototyped as void Foo(void\*) . -@param userdata Pointer passed to the callback function.(__Optional__) - */ -CV_EXPORTS void setOpenGlDrawCallback(const String& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0); - -/** @brief Sets the specified window as current OpenGL context. - -@param winname Name of the window. - */ -CV_EXPORTS void setOpenGlContext(const String& winname); - -/** @brief Force window to redraw its context and call draw callback ( See cv::setOpenGlDrawCallback ). - -@param winname Name of the window. - */ -CV_EXPORTS void updateWindow(const String& winname); - -//! @} highgui_opengl - -//! @addtogroup highgui_qt -//! @{ - -/** @brief QtFont available only for Qt. See cv::fontQt - */ -struct QtFont -{ - const char* nameFont; //!< Name of the font - Scalar color; //!< Color of the font. Scalar(blue_component, green_component, red_component[, alpha_component]) - int font_face; //!< See cv::QtFontStyles - const int* ascii; //!< font data and metrics - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; //!< slope coefficient: 0 - normal, >0 - italic - int thickness; //!< See cv::QtFontWeights - float dx; //!< horizontal interval between letters - int line_type; //!< PointSize -}; - -/** @brief Creates the font to draw a text on an image. - -The function fontQt creates a cv::QtFont object. This cv::QtFont is not compatible with putText . - -A basic usage of this function is the following: : -@code - QtFont font = fontQt("Times"); - addText( img1, "Hello World !", Point(50,50), font); -@endcode - -@param nameFont Name of the font. The name should match the name of a system font (such as -*Times*). If the font is not found, a default one is used. -@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the -font is set to a system-dependent default value. Generally, this is 12 points. -@param color Color of the font in BGRA where A = 255 is fully transparent. Use the macro CV_RGB -for simplicity. -@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. -@param style Font style. Available operation flags are : cv::QtFontStyles -@param spacing Spacing between characters. It can be negative or positive. - */ -CV_EXPORTS QtFont fontQt(const String& nameFont, int pointSize = -1, - Scalar color = Scalar::all(0), int weight = QT_FONT_NORMAL, - int style = QT_STYLE_NORMAL, int spacing = 0); - -/** @brief Draws a text on the image. - -The function addText draws *text* on the image *img* using a specific font *font* (see example cv::fontQt -) - -@param img 8-bit 3-channel image where the text should be drawn. -@param text Text to write on an image. -@param org Point(x,y) where the text should start on an image. -@param font Font to use to draw a text. - */ -CV_EXPORTS void addText( const Mat& img, const String& text, Point org, const QtFont& font); - -/** @brief Draws a text on the image. - -@param img 8-bit 3-channel image where the text should be drawn. -@param text Text to write on an image. -@param org Point(x,y) where the text should start on an image. -@param nameFont Name of the font. The name should match the name of a system font (such as -*Times*). If the font is not found, a default one is used. -@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the -font is set to a system-dependent default value. Generally, this is 12 points. -@param color Color of the font in BGRA where A = 255 is fully transparent. -@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. -@param style Font style. Available operation flags are : cv::QtFontStyles -@param spacing Spacing between characters. It can be negative or positive. - */ -CV_EXPORTS_W void addText(const Mat& img, const String& text, Point org, const String& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), - int weight = QT_FONT_NORMAL, int style = QT_STYLE_NORMAL, int spacing = 0); - -/** @brief Displays a text on a window image as an overlay for a specified duration. - -The function displayOverlay displays useful information/tips on top of the window for a certain -amount of time *delayms*. The function does not modify the image, displayed in the window, that is, -after the specified delay the original content of the window is restored. - -@param winname Name of the window. -@param text Overlay text to write on a window image. -@param delayms The period (in milliseconds), during which the overlay text is displayed. If this -function is called before the previous overlay text timed out, the timer is restarted and the text -is updated. If this value is zero, the text never disappears. - */ -CV_EXPORTS_W void displayOverlay(const String& winname, const String& text, int delayms = 0); - -/** @brief Displays a text on the window statusbar during the specified period of time. - -The function displayStatusBar displays useful information/tips on top of the window for a certain -amount of time *delayms* . This information is displayed on the window statusbar (the window must be -created with the CV_GUI_EXPANDED flags). - -@param winname Name of the window. -@param text Text to write on the window statusbar. -@param delayms Duration (in milliseconds) to display the text. If this function is called before -the previous text timed out, the timer is restarted and the text is updated. If this value is -zero, the text never disappears. - */ -CV_EXPORTS_W void displayStatusBar(const String& winname, const String& text, int delayms = 0); - -/** @brief Saves parameters of the specified window. - -The function saveWindowParameters saves size, location, flags, trackbars value, zoom and panning -location of the window windowName. - -@param windowName Name of the window. - */ -CV_EXPORTS void saveWindowParameters(const String& windowName); - -/** @brief Loads parameters of the specified window. - -The function loadWindowParameters loads size, location, flags, trackbars value, zoom and panning -location of the window windowName. - -@param windowName Name of the window. - */ -CV_EXPORTS void loadWindowParameters(const String& windowName); - -CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); - -CV_EXPORTS void stopLoop(); - -/** @brief Attaches a button to the control panel. - -The function createButton attaches a button to the control panel. Each button is added to a -buttonbar to the right of the last button. A new buttonbar is created if nothing was attached to the -control panel before, or if the last element attached to the control panel was a trackbar or if the -QT_NEW_BUTTONBAR flag is added to the type. - -See below various examples of the cv::createButton function call: : -@code - createButton("",callbackButton);//create a push button "button 0", that will call callbackButton. - createButton("button2",callbackButton,NULL,QT_CHECKBOX,0); - createButton("button3",callbackButton,&value); - createButton("button5",callbackButton1,NULL,QT_RADIOBOX); - createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON,1); - createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON|QT_NEW_BUTTONBAR);// create a push button in a new row -@endcode - -@param bar_name Name of the button. -@param on_change Pointer to the function to be called every time the button changes its state. -This function should be prototyped as void Foo(int state,\*void); . *state* is the current state -of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. -@param userdata Pointer passed to the callback function. -@param type Optional type of the button. Available types are: (cv::QtButtonTypes) -@param initial_button_state Default state of the button. Use for checkbox and radiobox. Its -value could be 0 or 1. (__Optional__) -*/ -CV_EXPORTS int createButton( const String& bar_name, ButtonCallback on_change, - void* userdata = 0, int type = QT_PUSH_BUTTON, - bool initial_button_state = false); - -//! @} highgui_qt - -//! @} highgui - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HIGHGUI_HPP +#define OPENCV_HIGHGUI_HPP + +#include "opencv2/core.hpp" +#ifdef HAVE_OPENCV_IMGCODECS +#include "opencv2/imgcodecs.hpp" +#endif +#ifdef HAVE_OPENCV_VIDEOIO +#include "opencv2/videoio.hpp" +#endif + +/** +@defgroup highgui High-level GUI + +While OpenCV was designed for use in full-scale applications and can be used within functionally +rich UI frameworks (such as Qt\*, WinForms\*, or Cocoa\*) or without any UI at all, sometimes there +it is required to try functionality quickly and visualize the results. This is what the HighGUI +module has been designed for. + +It provides easy interface to: + +- Create and manipulate windows that can display images and "remember" their content (no need to + handle repaint events from OS). +- Add trackbars to the windows, handle simple mouse events as well as keyboard commands. + +@{ + @defgroup highgui_window_flags Flags related creating and manipulating HighGUI windows and mouse events + @defgroup highgui_opengl OpenGL support + @defgroup highgui_qt Qt New Functions + + ![image](pics/qtgui.png) + + This figure explains new functionality implemented with Qt\* GUI. The new GUI provides a statusbar, + a toolbar, and a control panel. The control panel can have trackbars and buttonbars attached to it. + If you cannot see the control panel, press Ctrl+P or right-click any Qt window and select **Display + properties window**. + + - To attach a trackbar, the window name parameter must be NULL. + + - To attach a buttonbar, a button must be created. If the last bar attached to the control panel + is a buttonbar, the new button is added to the right of the last button. If the last bar + attached to the control panel is a trackbar, or the control panel is empty, a new buttonbar is + created. Then, a new button is attached to it. + + See below the example used to generate the figure: + + @include highgui_qt.cpp + + @defgroup highgui_winrt WinRT support + + This figure explains new functionality implemented with WinRT GUI. The new GUI provides an Image control, + and a slider panel. Slider panel holds trackbars attached to it. + + Sliders are attached below the image control. Every new slider is added below the previous one. + + See below the example used to generate the figure: + @code + void sample_app::MainPage::ShowWindow() + { + static cv::String windowName("sample"); + cv::winrt_initContainer(this->cvContainer); + cv::namedWindow(windowName); // not required + + cv::Mat image = cv::imread("Assets/sample.jpg"); + cv::Mat converted = cv::Mat(image.rows, image.cols, CV_8UC4); + cv::cvtColor(image, converted, COLOR_BGR2BGRA); + cv::imshow(windowName, converted); // this will create window if it hasn't been created before + + int state = 42; + cv::TrackbarCallback callback = [](int pos, void* userdata) + { + if (pos == 0) { + cv::destroyWindow(windowName); + } + }; + cv::TrackbarCallback callbackTwin = [](int pos, void* userdata) + { + if (pos >= 70) { + cv::destroyAllWindows(); + } + }; + cv::createTrackbar("Sample trackbar", windowName, &state, 100, callback); + cv::createTrackbar("Twin brother", windowName, &state, 100, callbackTwin); + } + @endcode +@} +*/ + +///////////////////////// graphical user interface ////////////////////////// +namespace cv +{ + +//! @addtogroup highgui +//! @{ + +//! @addtogroup highgui_window_flags +//! @{ + +//! Flags for cv::namedWindow +enum WindowFlags { + WINDOW_NORMAL = 0x00000000, //!< the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size. + WINDOW_AUTOSIZE = 0x00000001, //!< the user cannot resize the window, the size is constrainted by the image displayed. + WINDOW_OPENGL = 0x00001000, //!< window with opengl support. + + WINDOW_FULLSCREEN = 1, //!< change the window to fullscreen. + WINDOW_FREERATIO = 0x00000100, //!< the image expends as much as it can (no ratio constraint). + WINDOW_KEEPRATIO = 0x00000000, //!< the ratio of the image is respected. + WINDOW_GUI_EXPANDED=0x00000000, //!< status bar and tool bar + WINDOW_GUI_NORMAL = 0x00000010, //!< old fashious way + }; + +//! Flags for cv::setWindowProperty / cv::getWindowProperty +enum WindowPropertyFlags { + WND_PROP_FULLSCREEN = 0, //!< fullscreen property (can be WINDOW_NORMAL or WINDOW_FULLSCREEN). + WND_PROP_AUTOSIZE = 1, //!< autosize property (can be WINDOW_NORMAL or WINDOW_AUTOSIZE). + WND_PROP_ASPECT_RATIO = 2, //!< window's aspect ration (can be set to WINDOW_FREERATIO or WINDOW_KEEPRATIO). + WND_PROP_OPENGL = 3, //!< opengl support. + WND_PROP_VISIBLE = 4, //!< checks whether the window exists and is visible + WND_PROP_TOPMOST = 5, //!< property to toggle normal window being topmost or not + WND_PROP_VSYNC = 6 //!< enable or disable VSYNC (in OpenGL mode) + }; + +//! Mouse Events see cv::MouseCallback +enum MouseEventTypes { + EVENT_MOUSEMOVE = 0, //!< indicates that the mouse pointer has moved over the window. + EVENT_LBUTTONDOWN = 1, //!< indicates that the left mouse button is pressed. + EVENT_RBUTTONDOWN = 2, //!< indicates that the right mouse button is pressed. + EVENT_MBUTTONDOWN = 3, //!< indicates that the middle mouse button is pressed. + EVENT_LBUTTONUP = 4, //!< indicates that left mouse button is released. + EVENT_RBUTTONUP = 5, //!< indicates that right mouse button is released. + EVENT_MBUTTONUP = 6, //!< indicates that middle mouse button is released. + EVENT_LBUTTONDBLCLK = 7, //!< indicates that left mouse button is double clicked. + EVENT_RBUTTONDBLCLK = 8, //!< indicates that right mouse button is double clicked. + EVENT_MBUTTONDBLCLK = 9, //!< indicates that middle mouse button is double clicked. + EVENT_MOUSEWHEEL = 10,//!< positive and negative values mean forward and backward scrolling, respectively. + EVENT_MOUSEHWHEEL = 11 //!< positive and negative values mean right and left scrolling, respectively. + }; + +//! Mouse Event Flags see cv::MouseCallback +enum MouseEventFlags { + EVENT_FLAG_LBUTTON = 1, //!< indicates that the left mouse button is down. + EVENT_FLAG_RBUTTON = 2, //!< indicates that the right mouse button is down. + EVENT_FLAG_MBUTTON = 4, //!< indicates that the middle mouse button is down. + EVENT_FLAG_CTRLKEY = 8, //!< indicates that CTRL Key is pressed. + EVENT_FLAG_SHIFTKEY = 16,//!< indicates that SHIFT Key is pressed. + EVENT_FLAG_ALTKEY = 32 //!< indicates that ALT Key is pressed. + }; + +//! @} highgui_window_flags + +//! @addtogroup highgui_qt +//! @{ + +//! Qt font weight +enum QtFontWeights { + QT_FONT_LIGHT = 25, //!< Weight of 25 + QT_FONT_NORMAL = 50, //!< Weight of 50 + QT_FONT_DEMIBOLD = 63, //!< Weight of 63 + QT_FONT_BOLD = 75, //!< Weight of 75 + QT_FONT_BLACK = 87 //!< Weight of 87 + }; + +//! Qt font style +enum QtFontStyles { + QT_STYLE_NORMAL = 0, //!< Normal font. + QT_STYLE_ITALIC = 1, //!< Italic font. + QT_STYLE_OBLIQUE = 2 //!< Oblique font. + }; + +//! Qt "button" type +enum QtButtonTypes { + QT_PUSH_BUTTON = 0, //!< Push button. + QT_CHECKBOX = 1, //!< Checkbox button. + QT_RADIOBOX = 2, //!< Radiobox button. + QT_NEW_BUTTONBAR = 1024 //!< Button should create a new buttonbar + }; + +//! @} highgui_qt + +/** @brief Callback function for mouse events. see cv::setMouseCallback +@param event one of the cv::MouseEventTypes constants. +@param x The x-coordinate of the mouse event. +@param y The y-coordinate of the mouse event. +@param flags one of the cv::MouseEventFlags constants. +@param userdata The optional parameter. + */ +typedef void (*MouseCallback)(int event, int x, int y, int flags, void* userdata); + +/** @brief Callback function for Trackbar see cv::createTrackbar +@param pos current position of the specified trackbar. +@param userdata The optional parameter. + */ +typedef void (*TrackbarCallback)(int pos, void* userdata); + +/** @brief Callback function defined to be called every frame. See cv::setOpenGlDrawCallback +@param userdata The optional parameter. + */ +typedef void (*OpenGlDrawCallback)(void* userdata); + +/** @brief Callback function for a button created by cv::createButton +@param state current state of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. +@param userdata The optional parameter. + */ +typedef void (*ButtonCallback)(int state, void* userdata); + +/** @brief Creates a window. + +The function namedWindow creates a window that can be used as a placeholder for images and +trackbars. Created windows are referred to by their names. + +If a window with the same name already exists, the function does nothing. + +You can call cv::destroyWindow or cv::destroyAllWindows to close the window and de-allocate any associated +memory usage. For a simple program, you do not really have to call these functions because all the +resources and windows of the application are closed automatically by the operating system upon exit. + +@note Qt backend supports additional flags: + - **WINDOW_NORMAL or WINDOW_AUTOSIZE:** WINDOW_NORMAL enables you to resize the + window, whereas WINDOW_AUTOSIZE adjusts automatically the window size to fit the + displayed image (see imshow ), and you cannot change the window size manually. + - **WINDOW_FREERATIO or WINDOW_KEEPRATIO:** WINDOW_FREERATIO adjusts the image + with no respect to its ratio, whereas WINDOW_KEEPRATIO keeps the image ratio. + - **WINDOW_GUI_NORMAL or WINDOW_GUI_EXPANDED:** WINDOW_GUI_NORMAL is the old way to draw the window + without statusbar and toolbar, whereas WINDOW_GUI_EXPANDED is a new enhanced GUI. +By default, flags == WINDOW_AUTOSIZE | WINDOW_KEEPRATIO | WINDOW_GUI_EXPANDED + +@param winname Name of the window in the window caption that may be used as a window identifier. +@param flags Flags of the window. The supported flags are: (cv::WindowFlags) + */ +CV_EXPORTS_W void namedWindow(const String& winname, int flags = WINDOW_AUTOSIZE); + +/** @brief Destroys the specified window. + +The function destroyWindow destroys the window with the given name. + +@param winname Name of the window to be destroyed. + */ +CV_EXPORTS_W void destroyWindow(const String& winname); + +/** @brief Destroys all of the HighGUI windows. + +The function destroyAllWindows destroys all of the opened HighGUI windows. + */ +CV_EXPORTS_W void destroyAllWindows(); + + +/** @brief HighGUI backend used. + +The function returns HighGUI backend name used: could be COCOA, GTK2/3, QT, WAYLAND or WIN32. +Returns empty string if there is no available UI backend. + */ +CV_EXPORTS_W const std::string currentUIFramework(); + + +CV_EXPORTS_W int startWindowThread(); + +/** @brief Similar to #waitKey, but returns full key code. + +@note Key code is implementation specific and depends on used backend: QT/GTK/Win32/etc + +*/ +CV_EXPORTS_W int waitKeyEx(int delay = 0); + +/** @brief Waits for a pressed key. + +The function waitKey waits for a key event infinitely (when \f$\texttt{delay}\leq 0\f$ ) or for delay +milliseconds, when it is positive. Since the OS has a minimum time between switching threads, the +function will not wait exactly delay ms, it will wait at least delay ms, depending on what else is +running on your computer at that time. It returns the code of the pressed key or -1 if no key was +pressed before the specified time had elapsed. To check for a key press but not wait for it, use +#pollKey. + +@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle +GUI events, so one of them needs to be called periodically for normal event processing unless +HighGUI is used within an environment that takes care of event processing. + +@note The function only works if there is at least one HighGUI window created and the window is +active. If there are several HighGUI windows, any of them can be active. + +@param delay Delay in milliseconds. 0 is the special value that means "forever". + */ +CV_EXPORTS_W int waitKey(int delay = 0); + +/** @brief Polls for a pressed key. + +The function pollKey polls for a key event without waiting. It returns the code of the pressed key +or -1 if no key was pressed since the last invocation. To wait until a key was pressed, use #waitKey. + +@note The functions #waitKey and #pollKey are the only methods in HighGUI that can fetch and handle +GUI events, so one of them needs to be called periodically for normal event processing unless +HighGUI is used within an environment that takes care of event processing. + +@note The function only works if there is at least one HighGUI window created and the window is +active. If there are several HighGUI windows, any of them can be active. + */ +CV_EXPORTS_W int pollKey(); + +/** @brief Displays an image in the specified window. + +The function imshow displays an image in the specified window. If the window was created with the +cv::WINDOW_AUTOSIZE flag, the image is shown with its original size, however it is still limited by the screen resolution. +Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth: + +- If the image is 8-bit unsigned, it is displayed as is. +- If the image is 16-bit unsigned, the pixels are divided by 256. That is, the + value range [0,255\*256] is mapped to [0,255]. +- If the image is 32-bit or 64-bit floating-point, the pixel values are multiplied by 255. That is, the + value range [0,1] is mapped to [0,255]. +- 32-bit integer images are not processed anymore due to ambiguouty of required transform. + Convert to 8-bit unsigned matrix using a custom preprocessing specific to image's context. + +If window was created with OpenGL support, cv::imshow also support ogl::Buffer , ogl::Texture2D and +cuda::GpuMat as input. + +If the window was not created before this function, it is assumed creating a window with cv::WINDOW_AUTOSIZE. + +If you need to show an image that is bigger than the screen resolution, you will need to call namedWindow("", WINDOW_NORMAL) before the imshow. + +@note This function should be followed by a call to cv::waitKey or cv::pollKey to perform GUI +housekeeping tasks that are necessary to actually show the given image and make the window respond +to mouse and keyboard events. Otherwise, it won't display the image and the window might lock up. +For example, **waitKey(0)** will display the window infinitely until any keypress (it is suitable +for image display). **waitKey(25)** will display a frame and wait approximately 25 ms for a key +press (suitable for displaying a video frame-by-frame). To remove the window, use cv::destroyWindow. + +@note [__Windows Backend Only__] Pressing Ctrl+C will copy the image to the clipboard. Pressing Ctrl+S will show a dialog to save the image. +@note [__Wayland Backend Only__] Supoorting format is extended. +- If the image is 8-bit signed, the pixels are biased by 128. That is, the + value range [-128,127] is mapped to [0,255]. +- If the image is 16-bit signed, the pixels are divided by 256 and biased by 128. That is, the + value range [-32768,32767] is mapped to [0,255]. + +@param winname Name of the window. +@param mat Image to be shown. + */ +CV_EXPORTS_W void imshow(const String& winname, InputArray mat); + +/** @brief Resizes the window to the specified size + +@note The specified window size is for the image area. Toolbars are not counted. +Only windows created without cv::WINDOW_AUTOSIZE flag can be resized. + +@param winname Window name. +@param width The new window width. +@param height The new window height. + */ +CV_EXPORTS_W void resizeWindow(const String& winname, int width, int height); + +/** @overload +@param winname Window name. +@param size The new window size. +*/ +CV_EXPORTS_W void resizeWindow(const String& winname, const cv::Size& size); + +/** @brief Moves the window to the specified position + +@param winname Name of the window. +@param x The new x-coordinate of the window. +@param y The new y-coordinate of the window. + +@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. + */ +CV_EXPORTS_W void moveWindow(const String& winname, int x, int y); + +/** @brief Changes parameters of a window dynamically. + +The function setWindowProperty enables changing properties of a window. + +@param winname Name of the window. +@param prop_id Window property to edit. The supported operation flags are: (cv::WindowPropertyFlags) +@param prop_value New value of the window property. The supported flags are: (cv::WindowFlags) + +@note [__Wayland Backend Only__] This function is not supported. + */ +CV_EXPORTS_W void setWindowProperty(const String& winname, int prop_id, double prop_value); + +/** @brief Updates window title +@param winname Name of the window. +@param title New title. +*/ +CV_EXPORTS_W void setWindowTitle(const String& winname, const String& title); + +/** @brief Provides parameters of a window. + +The function getWindowProperty returns properties of a window. + +@param winname Name of the window. +@param prop_id Window property to retrieve. The following operation flags are available: (cv::WindowPropertyFlags) + +@sa setWindowProperty + +@note [__Wayland Backend Only__] This function is not supported. + */ +CV_EXPORTS_W double getWindowProperty(const String& winname, int prop_id); + +/** @brief Provides rectangle of image in the window. + +The function getWindowImageRect returns the client screen coordinates, width and height of the image rendering area. + +@param winname Name of the window. + +@sa resizeWindow moveWindow + +@note [__Wayland Backend Only__] This function is not supported by the Wayland protocol limitation. + */ +CV_EXPORTS_W Rect getWindowImageRect(const String& winname); + +/** @example samples/cpp/create_mask.cpp +This program demonstrates using mouse events and how to make and use a mask image (black and white) . +*/ +/** @brief Sets mouse handler for the specified window + +@param winname Name of the window. +@param onMouse Callback function for mouse events. See OpenCV samples on how to specify and use the callback. +@param userdata The optional parameter passed to the callback. + */ +CV_EXPORTS void setMouseCallback(const String& winname, MouseCallback onMouse, void* userdata = 0); + +/** @brief Gets the mouse-wheel motion delta, when handling mouse-wheel events cv::EVENT_MOUSEWHEEL and +cv::EVENT_MOUSEHWHEEL. + +For regular mice with a scroll-wheel, delta will be a multiple of 120. The value 120 corresponds to +a one notch rotation of the wheel or the threshold for action to be taken and one such action should +occur for each delta. Some high-precision mice with higher-resolution freely-rotating wheels may +generate smaller values. + +For cv::EVENT_MOUSEWHEEL positive and negative values mean forward and backward scrolling, +respectively. For cv::EVENT_MOUSEHWHEEL, where available, positive and negative values mean right and +left scrolling, respectively. + +@note Mouse-wheel events are currently supported only on Windows and Cocoa. + +@param flags The mouse callback flags parameter. + */ +CV_EXPORTS int getMouseWheelDelta(int flags); + +/** @brief Allows users to select a ROI on the given image. + +The function creates a window and allows users to select a ROI using the mouse. +Controls: use `space` or `enter` to finish selection, use key `c` to cancel selection (function will return the zero cv::Rect). + +@param windowName name of the window where selection process will be shown. +@param img image to select a ROI. +@param showCrosshair if true crosshair of selection rectangle will be shown. +@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of +selection rectangle will correspont to the initial mouse position. +@param printNotice if true a notice to select ROI or cancel selection will be printed in console. +@return selected ROI or empty rect if selection canceled. + +@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). +After finish of work an empty callback will be set for the used window. + */ +CV_EXPORTS_W Rect selectROI(const String& windowName, InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); + +/** @overload + */ +CV_EXPORTS_W Rect selectROI(InputArray img, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); + +/** @brief Allows users to select multiple ROIs on the given image. + +The function creates a window and allows users to select multiple ROIs using the mouse. +Controls: use `space` or `enter` to finish current selection and start a new one, +use `esc` to terminate multiple ROI selection process. + +@param windowName name of the window where selection process will be shown. +@param img image to select a ROI. +@param boundingBoxes selected ROIs. +@param showCrosshair if true crosshair of selection rectangle will be shown. +@param fromCenter if true center of selection will match initial mouse position. In opposite case a corner of +selection rectangle will correspont to the initial mouse position. +@param printNotice if true a notice to select ROI or cancel selection will be printed in console. + +@note The function sets it's own mouse callback for specified window using cv::setMouseCallback(windowName, ...). +After finish of work an empty callback will be set for the used window. + */ +CV_EXPORTS_W void selectROIs(const String& windowName, InputArray img, + CV_OUT std::vector& boundingBoxes, bool showCrosshair = true, bool fromCenter = false, bool printNotice = true); + +/** @brief Creates a trackbar and attaches it to the specified window. + +The function createTrackbar creates a trackbar (a slider or range control) with the specified name +and range, assigns a variable value to be a position synchronized with the trackbar and specifies +the callback function onChange to be called on the trackbar position change. The created trackbar is +displayed in the specified window winname. + +@note [__Qt Backend Only__] winname can be empty if the trackbar should be attached to the +control panel. + +Clicking the label of each trackbar enables editing the trackbar values manually. + +@param trackbarname Name of the created trackbar. +@param winname Name of the window that will contain the trackbar. +@param value Pointer to the integer value that will be changed by the trackbar. +Pass `nullptr` if the value pointer is not used. In this case, manually handle +the trackbar position in the callback function. +@param count Maximum position of the trackbar. +@param onChange Pointer to the function to be called every time the slider changes position. +This function should have the prototype void Foo(int, void\*);, where the first parameter is +the trackbar position, and the second parameter is the user data (see the next parameter). +If the callback is a nullptr, no callbacks are called, but the trackbar's value will still be +updated automatically. +@param userdata Optional user data that is passed to the callback. +@note If the `value` pointer is `nullptr`, the trackbar position must be manually managed. +Call the callback function manually with the desired initial value to avoid runtime warnings. +@see \ref tutorial_trackbar + */ +CV_EXPORTS int createTrackbar(const String& trackbarname, const String& winname, + int* value, int count, + TrackbarCallback onChange = 0, + void* userdata = 0); + +/** @brief Returns the trackbar position. + +The function returns the current position of the specified trackbar. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of the trackbar. + */ +CV_EXPORTS_W int getTrackbarPos(const String& trackbarname, const String& winname); + +/** @brief Sets the trackbar position. + +The function sets the position of the specified trackbar in the specified window. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of trackbar. +@param pos New position. + */ +CV_EXPORTS_W void setTrackbarPos(const String& trackbarname, const String& winname, int pos); + +/** @brief Sets the trackbar maximum position. + +The function sets the maximum position of the specified trackbar in the specified window. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of trackbar. +@param maxval New maximum position. + */ +CV_EXPORTS_W void setTrackbarMax(const String& trackbarname, const String& winname, int maxval); + +/** @brief Sets the trackbar minimum position. + +The function sets the minimum position of the specified trackbar in the specified window. + +@note [__Qt Backend Only__] winname can be empty if the trackbar is attached to the control +panel. + +@param trackbarname Name of the trackbar. +@param winname Name of the window that is the parent of trackbar. +@param minval New minimum position. + */ +CV_EXPORTS_W void setTrackbarMin(const String& trackbarname, const String& winname, int minval); + +//! @addtogroup highgui_opengl OpenGL support +//! @{ + +/** @brief Displays OpenGL 2D texture in the specified window. + +@param winname Name of the window. +@param tex OpenGL 2D texture data. + */ +CV_EXPORTS void imshow(const String& winname, const ogl::Texture2D& tex); + +/** @brief Sets a callback function to be called to draw on top of displayed image. + +The function setOpenGlDrawCallback can be used to draw 3D data on the window. See the example of +callback function below: +@code + void on_opengl(void* param) + { + glLoadIdentity(); + + glTranslated(0.0, 0.0, -1.0); + + glRotatef( 55, 1, 0, 0 ); + glRotatef( 45, 0, 1, 0 ); + glRotatef( 0, 0, 0, 1 ); + + static const int coords[6][4][3] = { + { { +1, -1, -1 }, { -1, -1, -1 }, { -1, +1, -1 }, { +1, +1, -1 } }, + { { +1, +1, -1 }, { -1, +1, -1 }, { -1, +1, +1 }, { +1, +1, +1 } }, + { { +1, -1, +1 }, { +1, -1, -1 }, { +1, +1, -1 }, { +1, +1, +1 } }, + { { -1, -1, -1 }, { -1, -1, +1 }, { -1, +1, +1 }, { -1, +1, -1 } }, + { { +1, -1, +1 }, { -1, -1, +1 }, { -1, -1, -1 }, { +1, -1, -1 } }, + { { -1, -1, +1 }, { +1, -1, +1 }, { +1, +1, +1 }, { -1, +1, +1 } } + }; + + for (int i = 0; i < 6; ++i) { + glColor3ub( i*20, 100+i*10, i*42 ); + glBegin(GL_QUADS); + for (int j = 0; j < 4; ++j) { + glVertex3d(0.2 * coords[i][j][0], 0.2 * coords[i][j][1], 0.2 * coords[i][j][2]); + } + glEnd(); + } + } +@endcode + +@param winname Name of the window. +@param onOpenGlDraw Pointer to the function to be called every frame. This function should be +prototyped as void Foo(void\*) . +@param userdata Pointer passed to the callback function.(__Optional__) + */ +CV_EXPORTS void setOpenGlDrawCallback(const String& winname, OpenGlDrawCallback onOpenGlDraw, void* userdata = 0); + +/** @brief Sets the specified window as current OpenGL context. + +@param winname Name of the window. + */ +CV_EXPORTS void setOpenGlContext(const String& winname); + +/** @brief Force window to redraw its context and call draw callback ( See cv::setOpenGlDrawCallback ). + +@param winname Name of the window. + */ +CV_EXPORTS void updateWindow(const String& winname); + +//! @} highgui_opengl + +//! @addtogroup highgui_qt +//! @{ + +/** @brief QtFont available only for Qt. See cv::fontQt + */ +struct QtFont +{ + const char* nameFont; //!< Name of the font + Scalar color; //!< Color of the font. Scalar(blue_component, green_component, red_component[, alpha_component]) + int font_face; //!< See cv::QtFontStyles + const int* ascii; //!< font data and metrics + const int* greek; + const int* cyrillic; + float hscale, vscale; + float shear; //!< slope coefficient: 0 - normal, >0 - italic + int thickness; //!< See cv::QtFontWeights + float dx; //!< horizontal interval between letters + int line_type; //!< PointSize +}; + +/** @brief Creates the font to draw a text on an image. + +The function fontQt creates a cv::QtFont object. This cv::QtFont is not compatible with putText . + +A basic usage of this function is the following: : +@code + QtFont font = fontQt("Times"); + addText( img1, "Hello World !", Point(50,50), font); +@endcode + +@param nameFont Name of the font. The name should match the name of a system font (such as +*Times*). If the font is not found, a default one is used. +@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the +font is set to a system-dependent default value. Generally, this is 12 points. +@param color Color of the font in BGRA where A = 255 is fully transparent. Use the macro CV_RGB +for simplicity. +@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. +@param style Font style. Available operation flags are : cv::QtFontStyles +@param spacing Spacing between characters. It can be negative or positive. + */ +CV_EXPORTS QtFont fontQt(const String& nameFont, int pointSize = -1, + Scalar color = Scalar::all(0), int weight = QT_FONT_NORMAL, + int style = QT_STYLE_NORMAL, int spacing = 0); + +/** @brief Draws a text on the image. + +The function addText draws *text* on the image *img* using a specific font *font* (see example cv::fontQt +) + +@param img 8-bit 3-channel image where the text should be drawn. +@param text Text to write on an image. +@param org Point(x,y) where the text should start on an image. +@param font Font to use to draw a text. + */ +CV_EXPORTS void addText( const Mat& img, const String& text, Point org, const QtFont& font); + +/** @brief Draws a text on the image. + +@param img 8-bit 3-channel image where the text should be drawn. +@param text Text to write on an image. +@param org Point(x,y) where the text should start on an image. +@param nameFont Name of the font. The name should match the name of a system font (such as +*Times*). If the font is not found, a default one is used. +@param pointSize Size of the font. If not specified, equal zero or negative, the point size of the +font is set to a system-dependent default value. Generally, this is 12 points. +@param color Color of the font in BGRA where A = 255 is fully transparent. +@param weight Font weight. Available operation flags are : cv::QtFontWeights You can also specify a positive integer for better control. +@param style Font style. Available operation flags are : cv::QtFontStyles +@param spacing Spacing between characters. It can be negative or positive. + */ +CV_EXPORTS_W void addText(const Mat& img, const String& text, Point org, const String& nameFont, int pointSize = -1, Scalar color = Scalar::all(0), + int weight = QT_FONT_NORMAL, int style = QT_STYLE_NORMAL, int spacing = 0); + +/** @brief Displays a text on a window image as an overlay for a specified duration. + +The function displayOverlay displays useful information/tips on top of the window for a certain +amount of time *delayms*. The function does not modify the image, displayed in the window, that is, +after the specified delay the original content of the window is restored. + +@param winname Name of the window. +@param text Overlay text to write on a window image. +@param delayms The period (in milliseconds), during which the overlay text is displayed. If this +function is called before the previous overlay text timed out, the timer is restarted and the text +is updated. If this value is zero, the text never disappears. + */ +CV_EXPORTS_W void displayOverlay(const String& winname, const String& text, int delayms = 0); + +/** @brief Displays a text on the window statusbar during the specified period of time. + +The function displayStatusBar displays useful information/tips on top of the window for a certain +amount of time *delayms* . This information is displayed on the window statusbar (the window must be +created with the CV_GUI_EXPANDED flags). + +@param winname Name of the window. +@param text Text to write on the window statusbar. +@param delayms Duration (in milliseconds) to display the text. If this function is called before +the previous text timed out, the timer is restarted and the text is updated. If this value is +zero, the text never disappears. + */ +CV_EXPORTS_W void displayStatusBar(const String& winname, const String& text, int delayms = 0); + +/** @brief Saves parameters of the specified window. + +The function saveWindowParameters saves size, location, flags, trackbars value, zoom and panning +location of the window windowName. + +@param windowName Name of the window. + */ +CV_EXPORTS void saveWindowParameters(const String& windowName); + +/** @brief Loads parameters of the specified window. + +The function loadWindowParameters loads size, location, flags, trackbars value, zoom and panning +location of the window windowName. + +@param windowName Name of the window. + */ +CV_EXPORTS void loadWindowParameters(const String& windowName); + +CV_EXPORTS int startLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); + +CV_EXPORTS void stopLoop(); + +/** @brief Attaches a button to the control panel. + +The function createButton attaches a button to the control panel. Each button is added to a +buttonbar to the right of the last button. A new buttonbar is created if nothing was attached to the +control panel before, or if the last element attached to the control panel was a trackbar or if the +QT_NEW_BUTTONBAR flag is added to the type. + +See below various examples of the cv::createButton function call: : +@code + createButton("",callbackButton);//create a push button "button 0", that will call callbackButton. + createButton("button2",callbackButton,NULL,QT_CHECKBOX,0); + createButton("button3",callbackButton,&value); + createButton("button5",callbackButton1,NULL,QT_RADIOBOX); + createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON,1); + createButton("button6",callbackButton2,NULL,QT_PUSH_BUTTON|QT_NEW_BUTTONBAR);// create a push button in a new row +@endcode + +@param bar_name Name of the button. +@param on_change Pointer to the function to be called every time the button changes its state. +This function should be prototyped as void Foo(int state,\*void); . *state* is the current state +of the button. It could be -1 for a push button, 0 or 1 for a check/radio box button. +@param userdata Pointer passed to the callback function. +@param type Optional type of the button. Available types are: (cv::QtButtonTypes) +@param initial_button_state Default state of the button. Use for checkbox and radiobox. Its +value could be 0 or 1. (__Optional__) +*/ +CV_EXPORTS int createButton( const String& bar_name, ButtonCallback on_change, + void* userdata = 0, int type = QT_PUSH_BUTTON, + bool initial_button_state = false); + +//! @} highgui_qt + +//! @} highgui + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp index 2fba53db0f..160c9cf4af 100644 --- a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/highgui.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/highgui.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h index 4c7ede3c71..e508e14975 100644 --- a/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/highgui/highgui_c.h @@ -1,251 +1,251 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_HIGHGUI_H -#define OPENCV_HIGHGUI_H - -#include "opencv2/core/core_c.h" -#include "opencv2/imgproc/imgproc_c.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** @addtogroup highgui_c - @{ - */ - -/****************************************************************************************\ -* Basic GUI functions * -\****************************************************************************************/ -//YV -//-----------New for Qt -/* For font */ -enum { CV_FONT_LIGHT = 25,//QFont::Light, - CV_FONT_NORMAL = 50,//QFont::Normal, - CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, - CV_FONT_BOLD = 75,//QFont::Bold, - CV_FONT_BLACK = 87 //QFont::Black -}; - -enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal, - CV_STYLE_ITALIC = 1,//QFont::StyleItalic, - CV_STYLE_OBLIQUE = 2 //QFont::StyleOblique -}; -/* ---------*/ - -//for color cvScalar(blue_component, green_component, red_component[, alpha_component]) -//and alpha= 0 <-> 0xFF (not transparent <-> transparent) -CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); - -CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); - -CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); -CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); - -CVAPI(void) cvSaveWindowParameters(const char* name); -CVAPI(void) cvLoadWindowParameters(const char* name); -CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); -CVAPI(void) cvStopLoop( void ); - -typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); -enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; -CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)); -//---------------------- - - -/* this function is used to set some external parameters in case of X Window */ -CVAPI(int) cvInitSystem( int argc, char** argv ); - -CVAPI(int) cvStartWindowThread( void ); - -// --------- YV --------- -enum -{ - //These 3 flags are used by cvSet/GetWindowProperty - CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property - CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property - CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property - CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support - CV_WND_PROP_VISIBLE = 4, - - //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size - CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed - CV_WINDOW_OPENGL = 0x00001000, //window with opengl support - - //Those flags are only for Qt - CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar - CV_GUI_NORMAL = 0x00000010, //old fashious way - - //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty - CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen - CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) - CV_WINDOW_KEEPRATIO = 0x00000000//the ration image is respected. -}; - -/* create window */ -CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOSIZE) ); - -/* Set and Get Property of the window */ -CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value); -CVAPI(double) cvGetWindowProperty(const char* name, int prop_id); - -/* display image within window (highgui windows remember their content) */ -CVAPI(void) cvShowImage( const char* name, const CvArr* image ); - -/* resize/move window */ -CVAPI(void) cvResizeWindow( const char* name, int width, int height ); -CVAPI(void) cvMoveWindow( const char* name, int x, int y ); - - -/* destroy window and all the trackers associated with it */ -CVAPI(void) cvDestroyWindow( const char* name ); - -CVAPI(void) cvDestroyAllWindows(void); - -/* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ -CVAPI(void*) cvGetWindowHandle( const char* name ); - -/* get name of highgui window given its native handle */ -CVAPI(const char*) cvGetWindowName( void* window_handle ); - - -typedef void (CV_CDECL *CvTrackbarCallback)(int pos); - -/* create trackbar and display it on top of given window, set callback */ -CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name, - int* value, int count, CvTrackbarCallback on_change CV_DEFAULT(NULL)); - -typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); - -CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name, - int* value, int count, CvTrackbarCallback2 on_change, - void* userdata CV_DEFAULT(0)); - -/* retrieve or set trackbar position */ -CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); -CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ); -CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval); -CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval); - -enum -{ - CV_EVENT_MOUSEMOVE =0, - CV_EVENT_LBUTTONDOWN =1, - CV_EVENT_RBUTTONDOWN =2, - CV_EVENT_MBUTTONDOWN =3, - CV_EVENT_LBUTTONUP =4, - CV_EVENT_RBUTTONUP =5, - CV_EVENT_MBUTTONUP =6, - CV_EVENT_LBUTTONDBLCLK =7, - CV_EVENT_RBUTTONDBLCLK =8, - CV_EVENT_MBUTTONDBLCLK =9, - CV_EVENT_MOUSEWHEEL =10, - CV_EVENT_MOUSEHWHEEL =11 -}; - -enum -{ - CV_EVENT_FLAG_LBUTTON =1, - CV_EVENT_FLAG_RBUTTON =2, - CV_EVENT_FLAG_MBUTTON =4, - CV_EVENT_FLAG_CTRLKEY =8, - CV_EVENT_FLAG_SHIFTKEY =16, - CV_EVENT_FLAG_ALTKEY =32 -}; - - -#define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits - -typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); - -/* assign callback for mouse events */ -CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, - void* param CV_DEFAULT(NULL)); - -/* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ -CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); - -// OpenGL support - -typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); -CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); - -CVAPI(void) cvSetOpenGlContext(const char* window_name); -CVAPI(void) cvUpdateWindow(const char* window_name); - - -/****************************************************************************************\ - -* Obsolete functions/synonyms * -\****************************************************************************************/ - -#define cvAddSearchPath(path) -#define cvvInitSystem cvInitSystem -#define cvvNamedWindow cvNamedWindow -#define cvvShowImage cvShowImage -#define cvvResizeWindow cvResizeWindow -#define cvvDestroyWindow cvDestroyWindow -#define cvvCreateTrackbar cvCreateTrackbar -#define cvvAddSearchPath cvAddSearchPath -#define cvvWaitKey(name) cvWaitKey(0) -#define cvvWaitKeyEx(name,delay) cvWaitKey(delay) -#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE -#define set_preprocess_func cvSetPreprocessFuncWin32 -#define set_postprocess_func cvSetPostprocessFuncWin32 - -#if defined _WIN32 - -CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback); -CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback); -#define cvSetPreprocessFuncWin32(callback) cvSetPreprocessFuncWin32_((const void*)(callback)) -#define cvSetPostprocessFuncWin32(callback) cvSetPostprocessFuncWin32_((const void*)(callback)) - -#endif - -/** @} highgui_c */ - -#ifdef __cplusplus -} -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// Intel License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of Intel Corporation may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_HIGHGUI_H +#define OPENCV_HIGHGUI_H + +#include "opencv2/core/core_c.h" +#include "opencv2/imgproc/imgproc_c.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup highgui_c + @{ + */ + +/****************************************************************************************\ +* Basic GUI functions * +\****************************************************************************************/ +//YV +//-----------New for Qt +/* For font */ +enum { CV_FONT_LIGHT = 25,//QFont::Light, + CV_FONT_NORMAL = 50,//QFont::Normal, + CV_FONT_DEMIBOLD = 63,//QFont::DemiBold, + CV_FONT_BOLD = 75,//QFont::Bold, + CV_FONT_BLACK = 87 //QFont::Black +}; + +enum { CV_STYLE_NORMAL = 0,//QFont::StyleNormal, + CV_STYLE_ITALIC = 1,//QFont::StyleItalic, + CV_STYLE_OBLIQUE = 2 //QFont::StyleOblique +}; +/* ---------*/ + +//for color cvScalar(blue_component, green_component, red_component[, alpha_component]) +//and alpha= 0 <-> 0xFF (not transparent <-> transparent) +CVAPI(CvFont) cvFontQt(const char* nameFont, int pointSize CV_DEFAULT(-1), CvScalar color CV_DEFAULT(cvScalarAll(0)), int weight CV_DEFAULT(CV_FONT_NORMAL), int style CV_DEFAULT(CV_STYLE_NORMAL), int spacing CV_DEFAULT(0)); + +CVAPI(void) cvAddText(const CvArr* img, const char* text, CvPoint org, CvFont *arg2); + +CVAPI(void) cvDisplayOverlay(const char* name, const char* text, int delayms CV_DEFAULT(0)); +CVAPI(void) cvDisplayStatusBar(const char* name, const char* text, int delayms CV_DEFAULT(0)); + +CVAPI(void) cvSaveWindowParameters(const char* name); +CVAPI(void) cvLoadWindowParameters(const char* name); +CVAPI(int) cvStartLoop(int (*pt2Func)(int argc, char *argv[]), int argc, char* argv[]); +CVAPI(void) cvStopLoop( void ); + +typedef void (CV_CDECL *CvButtonCallback)(int state, void* userdata); +enum {CV_PUSH_BUTTON = 0, CV_CHECKBOX = 1, CV_RADIOBOX = 2}; +CVAPI(int) cvCreateButton( const char* button_name CV_DEFAULT(NULL),CvButtonCallback on_change CV_DEFAULT(NULL), void* userdata CV_DEFAULT(NULL) , int button_type CV_DEFAULT(CV_PUSH_BUTTON), int initial_button_state CV_DEFAULT(0)); +//---------------------- + + +/* this function is used to set some external parameters in case of X Window */ +CVAPI(int) cvInitSystem( int argc, char** argv ); + +CVAPI(int) cvStartWindowThread( void ); + +// --------- YV --------- +enum +{ + //These 3 flags are used by cvSet/GetWindowProperty + CV_WND_PROP_FULLSCREEN = 0, //to change/get window's fullscreen property + CV_WND_PROP_AUTOSIZE = 1, //to change/get window's autosize property + CV_WND_PROP_ASPECTRATIO= 2, //to change/get window's aspectratio property + CV_WND_PROP_OPENGL = 3, //to change/get window's opengl support + CV_WND_PROP_VISIBLE = 4, + + //These 2 flags are used by cvNamedWindow and cvSet/GetWindowProperty + CV_WINDOW_NORMAL = 0x00000000, //the user can resize the window (no constraint) / also use to switch a fullscreen window to a normal size + CV_WINDOW_AUTOSIZE = 0x00000001, //the user cannot resize the window, the size is constrainted by the image displayed + CV_WINDOW_OPENGL = 0x00001000, //window with opengl support + + //Those flags are only for Qt + CV_GUI_EXPANDED = 0x00000000, //status bar and tool bar + CV_GUI_NORMAL = 0x00000010, //old fashious way + + //These 3 flags are used by cvNamedWindow and cvSet/GetWindowProperty + CV_WINDOW_FULLSCREEN = 1,//change the window to fullscreen + CV_WINDOW_FREERATIO = 0x00000100,//the image expends as much as it can (no ratio constraint) + CV_WINDOW_KEEPRATIO = 0x00000000//the ration image is respected. +}; + +/* create window */ +CVAPI(int) cvNamedWindow( const char* name, int flags CV_DEFAULT(CV_WINDOW_AUTOSIZE) ); + +/* Set and Get Property of the window */ +CVAPI(void) cvSetWindowProperty(const char* name, int prop_id, double prop_value); +CVAPI(double) cvGetWindowProperty(const char* name, int prop_id); + +/* display image within window (highgui windows remember their content) */ +CVAPI(void) cvShowImage( const char* name, const CvArr* image ); + +/* resize/move window */ +CVAPI(void) cvResizeWindow( const char* name, int width, int height ); +CVAPI(void) cvMoveWindow( const char* name, int x, int y ); + + +/* destroy window and all the trackers associated with it */ +CVAPI(void) cvDestroyWindow( const char* name ); + +CVAPI(void) cvDestroyAllWindows(void); + +/* get native window handle (HWND in case of Win32 and Widget in case of X Window) */ +CVAPI(void*) cvGetWindowHandle( const char* name ); + +/* get name of highgui window given its native handle */ +CVAPI(const char*) cvGetWindowName( void* window_handle ); + + +typedef void (CV_CDECL *CvTrackbarCallback)(int pos); + +/* create trackbar and display it on top of given window, set callback */ +CVAPI(int) cvCreateTrackbar( const char* trackbar_name, const char* window_name, + int* value, int count, CvTrackbarCallback on_change CV_DEFAULT(NULL)); + +typedef void (CV_CDECL *CvTrackbarCallback2)(int pos, void* userdata); + +CVAPI(int) cvCreateTrackbar2( const char* trackbar_name, const char* window_name, + int* value, int count, CvTrackbarCallback2 on_change, + void* userdata CV_DEFAULT(0)); + +/* retrieve or set trackbar position */ +CVAPI(int) cvGetTrackbarPos( const char* trackbar_name, const char* window_name ); +CVAPI(void) cvSetTrackbarPos( const char* trackbar_name, const char* window_name, int pos ); +CVAPI(void) cvSetTrackbarMax(const char* trackbar_name, const char* window_name, int maxval); +CVAPI(void) cvSetTrackbarMin(const char* trackbar_name, const char* window_name, int minval); + +enum +{ + CV_EVENT_MOUSEMOVE =0, + CV_EVENT_LBUTTONDOWN =1, + CV_EVENT_RBUTTONDOWN =2, + CV_EVENT_MBUTTONDOWN =3, + CV_EVENT_LBUTTONUP =4, + CV_EVENT_RBUTTONUP =5, + CV_EVENT_MBUTTONUP =6, + CV_EVENT_LBUTTONDBLCLK =7, + CV_EVENT_RBUTTONDBLCLK =8, + CV_EVENT_MBUTTONDBLCLK =9, + CV_EVENT_MOUSEWHEEL =10, + CV_EVENT_MOUSEHWHEEL =11 +}; + +enum +{ + CV_EVENT_FLAG_LBUTTON =1, + CV_EVENT_FLAG_RBUTTON =2, + CV_EVENT_FLAG_MBUTTON =4, + CV_EVENT_FLAG_CTRLKEY =8, + CV_EVENT_FLAG_SHIFTKEY =16, + CV_EVENT_FLAG_ALTKEY =32 +}; + + +#define CV_GET_WHEEL_DELTA(flags) ((short)((flags >> 16) & 0xffff)) // upper 16 bits + +typedef void (CV_CDECL *CvMouseCallback )(int event, int x, int y, int flags, void* param); + +/* assign callback for mouse events */ +CVAPI(void) cvSetMouseCallback( const char* window_name, CvMouseCallback on_mouse, + void* param CV_DEFAULT(NULL)); + +/* wait for key event infinitely (delay<=0) or for "delay" milliseconds */ +CVAPI(int) cvWaitKey(int delay CV_DEFAULT(0)); + +// OpenGL support + +typedef void (CV_CDECL *CvOpenGlDrawCallback)(void* userdata); +CVAPI(void) cvSetOpenGlDrawCallback(const char* window_name, CvOpenGlDrawCallback callback, void* userdata CV_DEFAULT(NULL)); + +CVAPI(void) cvSetOpenGlContext(const char* window_name); +CVAPI(void) cvUpdateWindow(const char* window_name); + + +/****************************************************************************************\ + +* Obsolete functions/synonyms * +\****************************************************************************************/ + +#define cvAddSearchPath(path) +#define cvvInitSystem cvInitSystem +#define cvvNamedWindow cvNamedWindow +#define cvvShowImage cvShowImage +#define cvvResizeWindow cvResizeWindow +#define cvvDestroyWindow cvDestroyWindow +#define cvvCreateTrackbar cvCreateTrackbar +#define cvvAddSearchPath cvAddSearchPath +#define cvvWaitKey(name) cvWaitKey(0) +#define cvvWaitKeyEx(name,delay) cvWaitKey(delay) +#define HG_AUTOSIZE CV_WINDOW_AUTOSIZE +#define set_preprocess_func cvSetPreprocessFuncWin32 +#define set_postprocess_func cvSetPostprocessFuncWin32 + +#if defined _WIN32 + +CVAPI(void) cvSetPreprocessFuncWin32_(const void* callback); +CVAPI(void) cvSetPostprocessFuncWin32_(const void* callback); +#define cvSetPreprocessFuncWin32(callback) cvSetPreprocessFuncWin32_((const void*)(callback)) +#define cvSetPostprocessFuncWin32(callback) cvSetPostprocessFuncWin32_((const void*)(callback)) + +#endif + +/** @} highgui_c */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp b/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp index 4f12c18173..cd648c2c6e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs.hpp @@ -1,603 +1,603 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_IMGCODECS_HPP -#define OPENCV_IMGCODECS_HPP - -#include "opencv2/core.hpp" - -/** - @defgroup imgcodecs Image file reading and writing - @{ - @defgroup imgcodecs_flags Flags used for image file reading and writing - @defgroup imgcodecs_ios iOS glue - @defgroup imgcodecs_macosx MacOS(OSX) glue - @} -*/ - -//////////////////////////////// image codec //////////////////////////////// -namespace cv -{ - -//! @addtogroup imgcodecs -//! @{ - -//! @addtogroup imgcodecs_flags -//! @{ - -//! Imread flags -enum ImreadModes { - IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation. - IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion). - IMREAD_COLOR_BGR = 1, //!< If set, always convert image to the 3 channel BGR color image. - IMREAD_COLOR = 1, //!< Same as IMREAD_COLOR_BGR. - IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. - IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. - IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. - IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. - IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. - IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. - IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. - IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. - IMREAD_REDUCED_COLOR_8 = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. - IMREAD_IGNORE_ORIENTATION = 128, //!< If set, do not rotate the image according to EXIF's orientation flag. - IMREAD_COLOR_RGB = 256, //!< If set, always convert image to the 3 channel RGB color image. - }; - -//! Imwrite flags -enum ImwriteFlags { - IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. - IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. - IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. - IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. - IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. - IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. - IMWRITE_JPEG_SAMPLING_FACTOR = 7, //!< For JPEG, set sampling factor. See cv::ImwriteJPEGSamplingFactorParams. - IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. If specified, strategy is changed to IMWRITE_PNG_STRATEGY_DEFAULT (Z_DEFAULT_STRATEGY). Default value is 1 (best speed setting). - IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_RLE. - IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. - IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. - IMWRITE_EXR_TYPE = (3 << 4) + 0 /* 48 */, //!< override EXR storage type (FLOAT (FP32) is default) - IMWRITE_EXR_COMPRESSION = (3 << 4) + 1 /* 49 */, //!< override EXR compression type (ZIP_COMPRESSION = 3 is default) - IMWRITE_EXR_DWA_COMPRESSION_LEVEL = (3 << 4) + 2 /* 50 */, //!< override EXR DWA compression level (45 is default) - IMWRITE_WEBP_QUALITY = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. - IMWRITE_HDR_COMPRESSION = (5 << 4) + 0 /* 80 */, //!< specify HDR compression - IMWRITE_PAM_TUPLETYPE = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format - IMWRITE_TIFF_RESUNIT = 256,//!< For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values - IMWRITE_TIFF_XDPI = 257,//!< For TIFF, use to specify the X direction DPI - IMWRITE_TIFF_YDPI = 258,//!< For TIFF, use to specify the Y direction DPI - IMWRITE_TIFF_COMPRESSION = 259,//!< For TIFF, use to specify the image compression scheme. See cv::ImwriteTiffCompressionFlags. Note, for images whose depth is CV_32F, only libtiff's SGILOG compression scheme is used. For other supported depths, the compression scheme can be specified by this flag; LZW compression is the default. - IMWRITE_TIFF_ROWSPERSTRIP = 278,//!< For TIFF, use to specify the number of rows per strip. - IMWRITE_TIFF_PREDICTOR = 317,//!< For TIFF, use to specify predictor. See cv::ImwriteTiffPredictorFlags. - IMWRITE_JPEG2000_COMPRESSION_X1000 = 272,//!< For JPEG2000, use to specify the target compression rate (multiplied by 1000). The value can be from 0 to 1000. Default is 1000. - IMWRITE_AVIF_QUALITY = 512,//!< For AVIF, it can be a quality between 0 and 100 (the higher the better). Default is 95. - IMWRITE_AVIF_DEPTH = 513,//!< For AVIF, it can be 8, 10 or 12. If >8, it is stored/read as CV_32F. Default is 8. - IMWRITE_AVIF_SPEED = 514,//!< For AVIF, it is between 0 (slowest) and (fastest). Default is 9. - IMWRITE_JPEGXL_QUALITY = 640,//!< For JPEG XL, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. If set, distance parameter is re-calicurated from quality level automatically. This parameter request libjxl v0.10 or later. - IMWRITE_JPEGXL_EFFORT = 641,//!< For JPEG XL, encoder effort/speed level without affecting decoding speed; it is between 1 (fastest) and 10 (slowest). Default is 7. - IMWRITE_JPEGXL_DISTANCE = 642,//!< For JPEG XL, distance level for lossy compression: target max butteraugli distance, lower = higher quality, 0 = lossless; range: 0 .. 25. Default is 1. - IMWRITE_JPEGXL_DECODING_SPEED = 643,//!< For JPEG XL, decoding speed tier for the provided options; minimum is 0 (slowest to decode, best quality/density), and maximum is 4 (fastest to decode, at the cost of some quality/density). Default is 0. - IMWRITE_GIF_LOOP = 1024,//!< For GIF, it can be a loop flag from 0 to 65535. Default is 0 - loop forever. - IMWRITE_GIF_SPEED = 1025,//!< For GIF, it is between 1 (slowest) and 100 (fastest). Default is 96. - IMWRITE_GIF_QUALITY = 1026, //!< For GIF, it can be a quality from 1 to 8. Default is 2. See cv::ImwriteGifCompressionFlags. - IMWRITE_GIF_DITHER = 1027, //!< For GIF, it can be a quality from -1(most dither) to 3(no dither). Default is 0. - IMWRITE_GIF_TRANSPARENCY = 1028, //!< For GIF, the alpha channel lower than this will be set to transparent. Default is 1. - IMWRITE_GIF_COLORTABLE = 1029 //!< For GIF, 0 means global color table is used, 1 means local color table is used. Default is 0. -}; - -enum ImwriteJPEGSamplingFactorParams { - IMWRITE_JPEG_SAMPLING_FACTOR_411 = 0x411111, //!< 4x1,1x1,1x1 - IMWRITE_JPEG_SAMPLING_FACTOR_420 = 0x221111, //!< 2x2,1x1,1x1(Default) - IMWRITE_JPEG_SAMPLING_FACTOR_422 = 0x211111, //!< 2x1,1x1,1x1 - IMWRITE_JPEG_SAMPLING_FACTOR_440 = 0x121111, //!< 1x2,1x1,1x1 - IMWRITE_JPEG_SAMPLING_FACTOR_444 = 0x111111 //!< 1x1,1x1,1x1(No subsampling) - }; - -enum ImwriteTiffCompressionFlags { - IMWRITE_TIFF_COMPRESSION_NONE = 1, //!< dump mode - IMWRITE_TIFF_COMPRESSION_CCITTRLE = 2, //!< CCITT modified Huffman RLE - IMWRITE_TIFF_COMPRESSION_CCITTFAX3 = 3, //!< CCITT Group 3 fax encoding - IMWRITE_TIFF_COMPRESSION_CCITT_T4 = 3, //!< CCITT T.4 (TIFF 6 name) - IMWRITE_TIFF_COMPRESSION_CCITTFAX4 = 4, //!< CCITT Group 4 fax encoding - IMWRITE_TIFF_COMPRESSION_CCITT_T6 = 4, //!< CCITT T.6 (TIFF 6 name) - IMWRITE_TIFF_COMPRESSION_LZW = 5, //!< Lempel-Ziv & Welch - IMWRITE_TIFF_COMPRESSION_OJPEG = 6, //!< !6.0 JPEG - IMWRITE_TIFF_COMPRESSION_JPEG = 7, //!< %JPEG DCT compression - IMWRITE_TIFF_COMPRESSION_T85 = 9, //!< !TIFF/FX T.85 JBIG compression - IMWRITE_TIFF_COMPRESSION_T43 = 10, //!< !TIFF/FX T.43 colour by layered JBIG compression - IMWRITE_TIFF_COMPRESSION_NEXT = 32766, //!< NeXT 2-bit RLE - IMWRITE_TIFF_COMPRESSION_CCITTRLEW = 32771, //!< #1 w/ word alignment - IMWRITE_TIFF_COMPRESSION_PACKBITS = 32773, //!< Macintosh RLE - IMWRITE_TIFF_COMPRESSION_THUNDERSCAN = 32809, //!< ThunderScan RLE - IMWRITE_TIFF_COMPRESSION_IT8CTPAD = 32895, //!< IT8 CT w/padding - IMWRITE_TIFF_COMPRESSION_IT8LW = 32896, //!< IT8 Linework RLE - IMWRITE_TIFF_COMPRESSION_IT8MP = 32897, //!< IT8 Monochrome picture - IMWRITE_TIFF_COMPRESSION_IT8BL = 32898, //!< IT8 Binary line art - IMWRITE_TIFF_COMPRESSION_PIXARFILM = 32908, //!< Pixar companded 10bit LZW - IMWRITE_TIFF_COMPRESSION_PIXARLOG = 32909, //!< Pixar companded 11bit ZIP - IMWRITE_TIFF_COMPRESSION_DEFLATE = 32946, //!< Deflate compression, legacy tag - IMWRITE_TIFF_COMPRESSION_ADOBE_DEFLATE = 8, //!< Deflate compression, as recognized by Adobe - IMWRITE_TIFF_COMPRESSION_DCS = 32947, //!< Kodak DCS encoding - IMWRITE_TIFF_COMPRESSION_JBIG = 34661, //!< ISO JBIG - IMWRITE_TIFF_COMPRESSION_SGILOG = 34676, //!< SGI Log Luminance RLE - IMWRITE_TIFF_COMPRESSION_SGILOG24 = 34677, //!< SGI Log 24-bit packed - IMWRITE_TIFF_COMPRESSION_JP2000 = 34712, //!< Leadtools JPEG2000 - IMWRITE_TIFF_COMPRESSION_LERC = 34887, //!< ESRI Lerc codec: https://github.com/Esri/lerc - IMWRITE_TIFF_COMPRESSION_LZMA = 34925, //!< LZMA2 - IMWRITE_TIFF_COMPRESSION_ZSTD = 50000, //!< ZSTD: WARNING not registered in Adobe-maintained registry - IMWRITE_TIFF_COMPRESSION_WEBP = 50001, //!< WEBP: WARNING not registered in Adobe-maintained registry - IMWRITE_TIFF_COMPRESSION_JXL = 50002 //!< JPEGXL: WARNING not registered in Adobe-maintained registry -}; - -enum ImwriteTiffPredictorFlags { - IMWRITE_TIFF_PREDICTOR_NONE = 1, //!< no prediction scheme used - IMWRITE_TIFF_PREDICTOR_HORIZONTAL = 2, //!< horizontal differencing - IMWRITE_TIFF_PREDICTOR_FLOATINGPOINT = 3 //!< floating point predictor - -}; - -enum ImwriteEXRTypeFlags { - /*IMWRITE_EXR_TYPE_UNIT = 0, //!< not supported */ - IMWRITE_EXR_TYPE_HALF = 1, //!< store as HALF (FP16) - IMWRITE_EXR_TYPE_FLOAT = 2 //!< store as FP32 (default) - }; - -enum ImwriteEXRCompressionFlags { - IMWRITE_EXR_COMPRESSION_NO = 0, //!< no compression - IMWRITE_EXR_COMPRESSION_RLE = 1, //!< run length encoding - IMWRITE_EXR_COMPRESSION_ZIPS = 2, //!< zlib compression, one scan line at a time - IMWRITE_EXR_COMPRESSION_ZIP = 3, //!< zlib compression, in blocks of 16 scan lines - IMWRITE_EXR_COMPRESSION_PIZ = 4, //!< piz-based wavelet compression - IMWRITE_EXR_COMPRESSION_PXR24 = 5, //!< lossy 24-bit float compression - IMWRITE_EXR_COMPRESSION_B44 = 6, //!< lossy 4-by-4 pixel block compression, fixed compression rate - IMWRITE_EXR_COMPRESSION_B44A = 7, //!< lossy 4-by-4 pixel block compression, flat fields are compressed more - IMWRITE_EXR_COMPRESSION_DWAA = 8, //!< lossy DCT based compression, in blocks of 32 scanlines. More efficient for partial buffer access. Supported since OpenEXR 2.2.0. - IMWRITE_EXR_COMPRESSION_DWAB = 9, //!< lossy DCT based compression, in blocks of 256 scanlines. More efficient space wise and faster to decode full frames than DWAA_COMPRESSION. Supported since OpenEXR 2.2.0. - }; - -//! Imwrite PNG specific flags used to tune the compression algorithm. -/** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. - -- The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. -- IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data. -- The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. -- IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. -*/ -enum ImwritePNGFlags { - IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. - IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. - IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). - IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). - IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. - }; - -//! Imwrite PAM specific tupletype flags used to define the 'TUPLETYPE' field of a PAM file. -enum ImwritePAMFlags { - IMWRITE_PAM_FORMAT_NULL = 0, - IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, - IMWRITE_PAM_FORMAT_GRAYSCALE = 2, - IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, - IMWRITE_PAM_FORMAT_RGB = 4, - IMWRITE_PAM_FORMAT_RGB_ALPHA = 5 - }; - -//! Imwrite HDR specific values for IMWRITE_HDR_COMPRESSION parameter key -enum ImwriteHDRCompressionFlags { - IMWRITE_HDR_COMPRESSION_NONE = 0, - IMWRITE_HDR_COMPRESSION_RLE = 1 -}; - -//! Imwrite GIF specific values for IMWRITE_GIF_QUALITY parameter key, if larger than 3, then its related to the size of the color table. -enum ImwriteGIFCompressionFlags { - IMWRITE_GIF_FAST_NO_DITHER = 1, - IMWRITE_GIF_FAST_FLOYD_DITHER = 2, - IMWRITE_GIF_COLORTABLE_SIZE_8 = 3, - IMWRITE_GIF_COLORTABLE_SIZE_16 = 4, - IMWRITE_GIF_COLORTABLE_SIZE_32 = 5, - IMWRITE_GIF_COLORTABLE_SIZE_64 = 6, - IMWRITE_GIF_COLORTABLE_SIZE_128 = 7, - IMWRITE_GIF_COLORTABLE_SIZE_256 = 8 -}; - -//! @} imgcodecs_flags - -/** @brief Represents an animation with multiple frames. -The `Animation` struct is designed to store and manage data for animated sequences such as those from animated formats (e.g., GIF, AVIF, APNG, WebP). -It provides support for looping, background color settings, frame timing, and frame storage. -*/ -struct CV_EXPORTS_W_SIMPLE Animation -{ - //! Number of times the animation should loop. 0 means infinite looping. - CV_PROP_RW int loop_count; - //! Background color of the animation in BGRA format. - CV_PROP_RW Scalar bgcolor; - //! Duration for each frame in milliseconds. - CV_PROP_RW std::vector durations; - //! Vector of frames, where each Mat represents a single frame. - CV_PROP_RW std::vector frames; - - /** @brief Constructs an Animation object with optional loop count and background color. - - @param loopCount An integer representing the number of times the animation should loop: - - `0` (default) indicates infinite looping, meaning the animation will replay continuously. - - Positive values denote finite repeat counts, allowing the animation to play a limited number of times. - - If a negative value or a value beyond the maximum of `0xffff` (65535) is provided, it is reset to `0` - (infinite looping) to maintain valid bounds. - - @param bgColor A `Scalar` object representing the background color in BGRA format: - - Defaults to `Scalar()`, indicating an empty color (usually transparent if supported). - - This background color provides a solid fill behind frames that have transparency, ensuring a consistent display appearance. - */ - Animation(int loopCount = 0, Scalar bgColor = Scalar()); -}; - -/** @brief Loads an image from a file. - -@anchor imread - -The `imread` function loads an image from the specified file and returns OpenCV matrix. If the image cannot be -read (because of a missing file, improper permissions, or unsupported/invalid format), the function -returns an empty matrix. - -Currently, the following file formats are supported: - -- Windows bitmaps - \*.bmp, \*.dib (always supported) -- GIF files - \*.gif (always supported) -- JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Note* section) -- JPEG 2000 files - \*.jp2 (see the *Note* section) -- Portable Network Graphics - \*.png (see the *Note* section) -- WebP - \*.webp (see the *Note* section) -- AVIF - \*.avif (see the *Note* section) -- Portable image format - \*.pbm, \*.pgm, \*.ppm, \*.pxm, \*.pnm (always supported) -- PFM files - \*.pfm (see the *Note* section) -- Sun rasters - \*.sr, \*.ras (always supported) -- TIFF files - \*.tiff, \*.tif (see the *Note* section) -- OpenEXR Image files - \*.exr (see the *Note* section) -- Radiance HDR - \*.hdr, \*.pic (always supported) -- Raster and Vector geospatial data supported by GDAL (see the *Note* section) - -@note -- The function determines the type of an image by its content, not by the file extension. -- In the case of color images, the decoded images will have the channels stored in **B G R** order. -- When using IMREAD_GRAYSCALE, the codec's internal grayscale conversion will be used, if available. - Results may differ from the output of cvtColor(). -- On Microsoft Windows\* and Mac OS\*, the codecs shipped with OpenCV (libjpeg, libpng, libtiff, - and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On Mac OS, - there is also an option to use native Mac OS image readers. However, beware that currently these - native image loaders give images with different pixel values because of the color management embedded - into Mac OS. -- On Linux\*, BSD flavors, and other Unix-like open-source operating systems, OpenCV looks for - codecs supplied with the OS. Ensure the relevant packages are installed (including development - files, such as "libjpeg-dev" in Debian\* and Ubuntu\*) to get codec support, or turn - on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. -- If the *WITH_GDAL* flag is set to true in CMake and @ref IMREAD_LOAD_GDAL is used to load the image, - the [GDAL](http://www.gdal.org) driver will be used to decode the image, supporting - [Raster](http://www.gdal.org/formats_list.html) and [Vector](http://www.gdal.org/ogr_formats.html) formats. -- If EXIF information is embedded in the image file, the EXIF orientation will be taken into account, - and thus the image will be rotated accordingly unless the flags @ref IMREAD_IGNORE_ORIENTATION - or @ref IMREAD_UNCHANGED are passed. -- Use the IMREAD_UNCHANGED flag to preserve the floating-point values from PFM images. -- By default, the number of pixels must be less than 2^30. This limit can be changed by setting - the environment variable `OPENCV_IO_MAX_IMAGE_PIXELS`. See @ref tutorial_env_reference. - -@param filename Name of the file to be loaded. -@param flags Flag that can take values of `cv::ImreadModes`. -*/ -CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR_BGR ); - -/** @brief Loads an image from a file. - -This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts and the return value. -@param filename Name of file to be loaded. -@param dst object in which the image will be loaded. -@param flags Flag that can take values of cv::ImreadModes -@note -The image passing through the img parameter can be pre-allocated. The memory is reused if the shape and the type match with the load image. - */ -CV_EXPORTS_W void imread( const String& filename, OutputArray dst, int flags = IMREAD_COLOR_BGR ); - -/** @brief Loads a multi-page image from a file. - -The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. -@param filename Name of file to be loaded. -@param mats A vector of Mat objects holding each page. -@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. -@sa cv::imread -*/ -CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int flags = IMREAD_ANYCOLOR); - -/** @brief Loads images of a multi-page image from a file. - -The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. -@param filename Name of file to be loaded. -@param mats A vector of Mat objects holding each page. -@param start Start index of the image to load -@param count Count number of images to load -@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. -@sa cv::imread -*/ -CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int start, int count, int flags = IMREAD_ANYCOLOR); - -/** @example samples/cpp/tutorial_code/imgcodecs/animations.cpp -An example to show usage of cv::imreadanimation and cv::imwriteanimation functions. -Check @ref tutorial_animations "the corresponding tutorial" for more details -*/ - -/** @brief Loads frames from an animated image file into an Animation structure. - -The function imreadanimation loads frames from an animated image file (e.g., GIF, AVIF, APNG, WEBP) into the provided Animation struct. - -@param filename A string containing the path to the file. -@param animation A reference to an Animation structure where the loaded frames will be stored. It should be initialized before the function is called. -@param start The index of the first frame to load. This is optional and defaults to 0. -@param count The number of frames to load. This is optional and defaults to 32767. - -@return Returns true if the file was successfully loaded and frames were extracted; returns false otherwise. -*/ -CV_EXPORTS_W bool imreadanimation(const String& filename, CV_OUT Animation& animation, int start = 0, int count = INT16_MAX); - -/** @brief Saves an Animation to a specified file. - -The function imwriteanimation saves the provided Animation data to the specified file in an animated format. -Supported formats depend on the implementation and may include formats like GIF, AVIF, APNG, or WEBP. - -@param filename The name of the file where the animation will be saved. The file extension determines the format. -@param animation A constant reference to an Animation struct containing the frames and metadata to be saved. -@param params Optional format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ...). -These parameters are used to specify additional options for the encoding process. Refer to `cv::ImwriteFlags` for details on possible parameters. - -@return Returns true if the animation was successfully saved; returns false otherwise. -*/ -CV_EXPORTS_W bool imwriteanimation(const String& filename, const Animation& animation, const std::vector& params = std::vector()); - -/** @brief Returns the number of images inside the given file - -The function imcount returns the number of pages in a multi-page image (e.g. TIFF), the number of frames in an animation (e.g. AVIF), and 1 otherwise. -If the image cannot be decoded, 0 is returned. -@param filename Name of file to be loaded. -@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. -@todo when cv::IMREAD_LOAD_GDAL flag used the return value will be 0 or 1 because OpenCV's GDAL decoder doesn't support multi-page reading yet. -*/ -CV_EXPORTS_W size_t imcount(const String& filename, int flags = IMREAD_ANYCOLOR); - -/** @brief Saves an image to a specified file. - -The function imwrite saves the image to the specified file. The image format is chosen based on the -filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) -single-channel or 3-channel (with 'BGR' channel order) images -can be saved using this function, with these exceptions: - -- With OpenEXR encoder, only 32-bit float (CV_32F) images can be saved. - - 8-bit unsigned (CV_8U) images are not supported. -- With Radiance HDR encoder, non 64-bit float (CV_64F) images can be saved. - - All images will be converted to 32-bit float (CV_32F). -- With JPEG 2000 encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. -- With JPEG XL encoder, 8-bit unsigned (CV_8U), 16-bit unsigned (CV_16U) and 32-bit float(CV_32F) images can be saved. - - JPEG XL images with an alpha channel can be saved using this function. - To do this, create 8-bit (or 16-bit, 32-bit float) 4-channel image BGRA, where the alpha channel goes last. - Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535/1.0. -- With PAM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. -- With PNG encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. - - PNG images with an alpha channel can be saved using this function. To do this, create - 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels - should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below). -- With PGM/PPM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. -- With TIFF encoder, 8-bit unsigned (CV_8U), 8-bit signed (CV_8S), - 16-bit unsigned (CV_16U), 16-bit signed (CV_16S), - 32-bit signed (CV_32S), - 32-bit float (CV_32F) and 64-bit float (CV_64F) images can be saved. - - Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below). - - 32-bit float 3-channel (CV_32FC3) TIFF images will be saved - using the LogLuv high dynamic range encoding (4 bytes per pixel) - -If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way. - -If the format, depth or channel order is different, use -Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O -functions to save the image to XML or YAML format. - -The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. -It also demonstrates how to save multiple images in a TIFF file: -@include snippets/imgcodecs_imwrite.cpp -@param filename Name of the file. -@param img (Mat or vector of Mat) Image or Images to be saved. -@param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags -*/ -CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, - const std::vector& params = std::vector()); - -//! @brief multi-image overload for bindings -CV_WRAP static inline -bool imwritemulti(const String& filename, InputArrayOfArrays img, - const std::vector& params = std::vector()) -{ - return imwrite(filename, img, params); -} - -/** @brief Reads an image from a buffer in memory. - -The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or -contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). - -See cv::imread for the list of supported formats and flags description. - -@note In the case of color images, the decoded images will have the channels stored in **B G R** order. -@param buf Input array or vector of bytes. -@param flags The same flags as in cv::imread, see cv::ImreadModes. -*/ -CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); - -/** @overload -@param buf Input array or vector of bytes. -@param flags The same flags as in cv::imread, see cv::ImreadModes. -@param dst The optional output placeholder for the decoded matrix. It can save the image -reallocations when the function is called repeatedly for images of the same size. In case of decoder -failure the function returns empty cv::Mat object, but does not release user-provided dst buffer. -*/ -CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); - -/** @brief Reads a multi-page image from a buffer in memory. - -The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or -contains invalid data, the function returns false. - -See cv::imreadmulti for the list of supported formats and flags description. - -@note In the case of color images, the decoded images will have the channels stored in **B G R** order. -@param buf Input array or vector of bytes. -@param flags The same flags as in cv::imread, see cv::ImreadModes. -@param mats A vector of Mat objects holding each page, if more than one. -@param range A continuous selection of pages. -*/ -CV_EXPORTS_W bool imdecodemulti(InputArray buf, int flags, CV_OUT std::vector& mats, const cv::Range& range = Range::all()); - -/** @brief Encodes an image into a memory buffer. - -The function imencode compresses the image and stores it in the memory buffer that is resized to fit the -result. See cv::imwrite for the list of supported formats and flags description. - -@param ext File extension that defines the output format. Must include a leading period. -@param img Image to be compressed. -@param buf Output buffer resized to fit the compressed image. -@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. -*/ -CV_EXPORTS_W bool imencode( const String& ext, InputArray img, - CV_OUT std::vector& buf, - const std::vector& params = std::vector()); - -/** @brief Encodes array of images into a memory buffer. - -The function is analog to cv::imencode for in-memory multi-page image compression. -See cv::imwrite for the list of supported formats and flags description. - -@param ext File extension that defines the output format. Must include a leading period. -@param imgs Vector of images to be written. -@param buf Output buffer resized to fit the compressed data. -@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. -*/ -CV_EXPORTS_W bool imencodemulti( const String& ext, InputArrayOfArrays imgs, - CV_OUT std::vector& buf, - const std::vector& params = std::vector()); - -/** @brief Checks if the specified image file can be decoded by OpenCV. - -The function haveImageReader checks if OpenCV is capable of reading the specified file. -This can be useful for verifying support for a given image format before attempting to load an image. - -@param filename The name of the file to be checked. -@return true if an image reader for the specified file is available and the file can be opened, false otherwise. - -@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. -It does not check for the actual existence of the file but rather the ability to read the specified file type. -If the file cannot be opened or the format is unsupported, the function will return false. - -@sa cv::haveImageWriter, cv::imread, cv::imdecode -*/ -CV_EXPORTS_W bool haveImageReader( const String& filename ); - -/** @brief Checks if the specified image file or specified file extension can be encoded by OpenCV. - -The function haveImageWriter checks if OpenCV is capable of writing images with the specified file extension. -This can be useful for verifying support for a given image format before attempting to save an image. - -@param filename The name of the file or the file extension (e.g., ".jpg", ".png"). -It is recommended to provide the file extension rather than the full file name. -@return true if an image writer for the specified extension is available, false otherwise. - -@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. -It does not check for the actual existence of the file but rather the ability to write files of the given type. - -@sa cv::haveImageReader, cv::imwrite, cv::imencode -*/ -CV_EXPORTS_W bool haveImageWriter( const String& filename ); - -/** @brief To read multi-page images on demand - -The ImageCollection class provides iterator API to read multi-page images on demand. Create iterator -to the collection of the images and iterate over the collection. Decode the necessary page with operator*. - -The performance of page decoding is O(1) if collection is increment sequentially. If the user wants to access random page, -then the time Complexity is O(n) because the collection has to be reinitialized every time in order to go to the correct page. -However, the intermediate pages are not decoded during the process, so typically it's quite fast. -This is required because multi-page codecs does not support going backwards. -After decoding the one page, it is stored inside the collection cache. Hence, trying to get Mat object from already decoded page is O(1). -If you need memory, you can use .releaseCache() method to release cached index. -The space complexity is O(n) if all pages are decoded into memory. The user is able to decode and release images on demand. -*/ -class CV_EXPORTS ImageCollection { -public: - struct CV_EXPORTS iterator { - iterator(ImageCollection* col); - iterator(ImageCollection* col, int end); - Mat& operator*(); - Mat* operator->(); - iterator& operator++(); - iterator operator++(int); - friend bool operator== (const iterator& a, const iterator& b) { return a.m_curr == b.m_curr; } - friend bool operator!= (const iterator& a, const iterator& b) { return a.m_curr != b.m_curr; } - - private: - ImageCollection* m_pCollection; - int m_curr; - }; - - ImageCollection(); - ImageCollection(const String& filename, int flags); - void init(const String& img, int flags); - size_t size() const; - const Mat& at(int index); - const Mat& operator[](int index); - void releaseCache(int index); - iterator begin(); - iterator end(); - - class Impl; - Ptr getImpl(); -protected: - Ptr pImpl; -}; - -//! @} imgcodecs - -} // cv - -#endif //OPENCV_IMGCODECS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_IMGCODECS_HPP +#define OPENCV_IMGCODECS_HPP + +#include "opencv2/core.hpp" + +/** + @defgroup imgcodecs Image file reading and writing + @{ + @defgroup imgcodecs_flags Flags used for image file reading and writing + @defgroup imgcodecs_ios iOS glue + @defgroup imgcodecs_macosx MacOS(OSX) glue + @} +*/ + +//////////////////////////////// image codec //////////////////////////////// +namespace cv +{ + +//! @addtogroup imgcodecs +//! @{ + +//! @addtogroup imgcodecs_flags +//! @{ + +//! Imread flags +enum ImreadModes { + IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation. + IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion). + IMREAD_COLOR_BGR = 1, //!< If set, always convert image to the 3 channel BGR color image. + IMREAD_COLOR = 1, //!< Same as IMREAD_COLOR_BGR. + IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. + IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. + IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. + IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. + IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. + IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. + IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. + IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. + IMREAD_REDUCED_COLOR_8 = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. + IMREAD_IGNORE_ORIENTATION = 128, //!< If set, do not rotate the image according to EXIF's orientation flag. + IMREAD_COLOR_RGB = 256, //!< If set, always convert image to the 3 channel RGB color image. + }; + +//! Imwrite flags +enum ImwriteFlags { + IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. + IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. + IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. + IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. + IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. + IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is -1 - don't use. If JPEG_LIB_VERSION < 70, Not supported. + IMWRITE_JPEG_SAMPLING_FACTOR = 7, //!< For JPEG, set sampling factor. See cv::ImwriteJPEGSamplingFactorParams. + IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. If specified, strategy is changed to IMWRITE_PNG_STRATEGY_DEFAULT (Z_DEFAULT_STRATEGY). Default value is 1 (best speed setting). + IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_RLE. + IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. + IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. + IMWRITE_EXR_TYPE = (3 << 4) + 0 /* 48 */, //!< override EXR storage type (FLOAT (FP32) is default) + IMWRITE_EXR_COMPRESSION = (3 << 4) + 1 /* 49 */, //!< override EXR compression type (ZIP_COMPRESSION = 3 is default) + IMWRITE_EXR_DWA_COMPRESSION_LEVEL = (3 << 4) + 2 /* 50 */, //!< override EXR DWA compression level (45 is default) + IMWRITE_WEBP_QUALITY = 64, //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. + IMWRITE_HDR_COMPRESSION = (5 << 4) + 0 /* 80 */, //!< specify HDR compression + IMWRITE_PAM_TUPLETYPE = 128,//!< For PAM, sets the TUPLETYPE field to the corresponding string value that is defined for the format + IMWRITE_TIFF_RESUNIT = 256,//!< For TIFF, use to specify which DPI resolution unit to set; see libtiff documentation for valid values + IMWRITE_TIFF_XDPI = 257,//!< For TIFF, use to specify the X direction DPI + IMWRITE_TIFF_YDPI = 258,//!< For TIFF, use to specify the Y direction DPI + IMWRITE_TIFF_COMPRESSION = 259,//!< For TIFF, use to specify the image compression scheme. See cv::ImwriteTiffCompressionFlags. Note, for images whose depth is CV_32F, only libtiff's SGILOG compression scheme is used. For other supported depths, the compression scheme can be specified by this flag; LZW compression is the default. + IMWRITE_TIFF_ROWSPERSTRIP = 278,//!< For TIFF, use to specify the number of rows per strip. + IMWRITE_TIFF_PREDICTOR = 317,//!< For TIFF, use to specify predictor. See cv::ImwriteTiffPredictorFlags. + IMWRITE_JPEG2000_COMPRESSION_X1000 = 272,//!< For JPEG2000, use to specify the target compression rate (multiplied by 1000). The value can be from 0 to 1000. Default is 1000. + IMWRITE_AVIF_QUALITY = 512,//!< For AVIF, it can be a quality between 0 and 100 (the higher the better). Default is 95. + IMWRITE_AVIF_DEPTH = 513,//!< For AVIF, it can be 8, 10 or 12. If >8, it is stored/read as CV_32F. Default is 8. + IMWRITE_AVIF_SPEED = 514,//!< For AVIF, it is between 0 (slowest) and (fastest). Default is 9. + IMWRITE_JPEGXL_QUALITY = 640,//!< For JPEG XL, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. If set, distance parameter is re-calicurated from quality level automatically. This parameter request libjxl v0.10 or later. + IMWRITE_JPEGXL_EFFORT = 641,//!< For JPEG XL, encoder effort/speed level without affecting decoding speed; it is between 1 (fastest) and 10 (slowest). Default is 7. + IMWRITE_JPEGXL_DISTANCE = 642,//!< For JPEG XL, distance level for lossy compression: target max butteraugli distance, lower = higher quality, 0 = lossless; range: 0 .. 25. Default is 1. + IMWRITE_JPEGXL_DECODING_SPEED = 643,//!< For JPEG XL, decoding speed tier for the provided options; minimum is 0 (slowest to decode, best quality/density), and maximum is 4 (fastest to decode, at the cost of some quality/density). Default is 0. + IMWRITE_GIF_LOOP = 1024,//!< For GIF, it can be a loop flag from 0 to 65535. Default is 0 - loop forever. + IMWRITE_GIF_SPEED = 1025,//!< For GIF, it is between 1 (slowest) and 100 (fastest). Default is 96. + IMWRITE_GIF_QUALITY = 1026, //!< For GIF, it can be a quality from 1 to 8. Default is 2. See cv::ImwriteGifCompressionFlags. + IMWRITE_GIF_DITHER = 1027, //!< For GIF, it can be a quality from -1(most dither) to 3(no dither). Default is 0. + IMWRITE_GIF_TRANSPARENCY = 1028, //!< For GIF, the alpha channel lower than this will be set to transparent. Default is 1. + IMWRITE_GIF_COLORTABLE = 1029 //!< For GIF, 0 means global color table is used, 1 means local color table is used. Default is 0. +}; + +enum ImwriteJPEGSamplingFactorParams { + IMWRITE_JPEG_SAMPLING_FACTOR_411 = 0x411111, //!< 4x1,1x1,1x1 + IMWRITE_JPEG_SAMPLING_FACTOR_420 = 0x221111, //!< 2x2,1x1,1x1(Default) + IMWRITE_JPEG_SAMPLING_FACTOR_422 = 0x211111, //!< 2x1,1x1,1x1 + IMWRITE_JPEG_SAMPLING_FACTOR_440 = 0x121111, //!< 1x2,1x1,1x1 + IMWRITE_JPEG_SAMPLING_FACTOR_444 = 0x111111 //!< 1x1,1x1,1x1(No subsampling) + }; + +enum ImwriteTiffCompressionFlags { + IMWRITE_TIFF_COMPRESSION_NONE = 1, //!< dump mode + IMWRITE_TIFF_COMPRESSION_CCITTRLE = 2, //!< CCITT modified Huffman RLE + IMWRITE_TIFF_COMPRESSION_CCITTFAX3 = 3, //!< CCITT Group 3 fax encoding + IMWRITE_TIFF_COMPRESSION_CCITT_T4 = 3, //!< CCITT T.4 (TIFF 6 name) + IMWRITE_TIFF_COMPRESSION_CCITTFAX4 = 4, //!< CCITT Group 4 fax encoding + IMWRITE_TIFF_COMPRESSION_CCITT_T6 = 4, //!< CCITT T.6 (TIFF 6 name) + IMWRITE_TIFF_COMPRESSION_LZW = 5, //!< Lempel-Ziv & Welch + IMWRITE_TIFF_COMPRESSION_OJPEG = 6, //!< !6.0 JPEG + IMWRITE_TIFF_COMPRESSION_JPEG = 7, //!< %JPEG DCT compression + IMWRITE_TIFF_COMPRESSION_T85 = 9, //!< !TIFF/FX T.85 JBIG compression + IMWRITE_TIFF_COMPRESSION_T43 = 10, //!< !TIFF/FX T.43 colour by layered JBIG compression + IMWRITE_TIFF_COMPRESSION_NEXT = 32766, //!< NeXT 2-bit RLE + IMWRITE_TIFF_COMPRESSION_CCITTRLEW = 32771, //!< #1 w/ word alignment + IMWRITE_TIFF_COMPRESSION_PACKBITS = 32773, //!< Macintosh RLE + IMWRITE_TIFF_COMPRESSION_THUNDERSCAN = 32809, //!< ThunderScan RLE + IMWRITE_TIFF_COMPRESSION_IT8CTPAD = 32895, //!< IT8 CT w/padding + IMWRITE_TIFF_COMPRESSION_IT8LW = 32896, //!< IT8 Linework RLE + IMWRITE_TIFF_COMPRESSION_IT8MP = 32897, //!< IT8 Monochrome picture + IMWRITE_TIFF_COMPRESSION_IT8BL = 32898, //!< IT8 Binary line art + IMWRITE_TIFF_COMPRESSION_PIXARFILM = 32908, //!< Pixar companded 10bit LZW + IMWRITE_TIFF_COMPRESSION_PIXARLOG = 32909, //!< Pixar companded 11bit ZIP + IMWRITE_TIFF_COMPRESSION_DEFLATE = 32946, //!< Deflate compression, legacy tag + IMWRITE_TIFF_COMPRESSION_ADOBE_DEFLATE = 8, //!< Deflate compression, as recognized by Adobe + IMWRITE_TIFF_COMPRESSION_DCS = 32947, //!< Kodak DCS encoding + IMWRITE_TIFF_COMPRESSION_JBIG = 34661, //!< ISO JBIG + IMWRITE_TIFF_COMPRESSION_SGILOG = 34676, //!< SGI Log Luminance RLE + IMWRITE_TIFF_COMPRESSION_SGILOG24 = 34677, //!< SGI Log 24-bit packed + IMWRITE_TIFF_COMPRESSION_JP2000 = 34712, //!< Leadtools JPEG2000 + IMWRITE_TIFF_COMPRESSION_LERC = 34887, //!< ESRI Lerc codec: https://github.com/Esri/lerc + IMWRITE_TIFF_COMPRESSION_LZMA = 34925, //!< LZMA2 + IMWRITE_TIFF_COMPRESSION_ZSTD = 50000, //!< ZSTD: WARNING not registered in Adobe-maintained registry + IMWRITE_TIFF_COMPRESSION_WEBP = 50001, //!< WEBP: WARNING not registered in Adobe-maintained registry + IMWRITE_TIFF_COMPRESSION_JXL = 50002 //!< JPEGXL: WARNING not registered in Adobe-maintained registry +}; + +enum ImwriteTiffPredictorFlags { + IMWRITE_TIFF_PREDICTOR_NONE = 1, //!< no prediction scheme used + IMWRITE_TIFF_PREDICTOR_HORIZONTAL = 2, //!< horizontal differencing + IMWRITE_TIFF_PREDICTOR_FLOATINGPOINT = 3 //!< floating point predictor + +}; + +enum ImwriteEXRTypeFlags { + /*IMWRITE_EXR_TYPE_UNIT = 0, //!< not supported */ + IMWRITE_EXR_TYPE_HALF = 1, //!< store as HALF (FP16) + IMWRITE_EXR_TYPE_FLOAT = 2 //!< store as FP32 (default) + }; + +enum ImwriteEXRCompressionFlags { + IMWRITE_EXR_COMPRESSION_NO = 0, //!< no compression + IMWRITE_EXR_COMPRESSION_RLE = 1, //!< run length encoding + IMWRITE_EXR_COMPRESSION_ZIPS = 2, //!< zlib compression, one scan line at a time + IMWRITE_EXR_COMPRESSION_ZIP = 3, //!< zlib compression, in blocks of 16 scan lines + IMWRITE_EXR_COMPRESSION_PIZ = 4, //!< piz-based wavelet compression + IMWRITE_EXR_COMPRESSION_PXR24 = 5, //!< lossy 24-bit float compression + IMWRITE_EXR_COMPRESSION_B44 = 6, //!< lossy 4-by-4 pixel block compression, fixed compression rate + IMWRITE_EXR_COMPRESSION_B44A = 7, //!< lossy 4-by-4 pixel block compression, flat fields are compressed more + IMWRITE_EXR_COMPRESSION_DWAA = 8, //!< lossy DCT based compression, in blocks of 32 scanlines. More efficient for partial buffer access. Supported since OpenEXR 2.2.0. + IMWRITE_EXR_COMPRESSION_DWAB = 9, //!< lossy DCT based compression, in blocks of 256 scanlines. More efficient space wise and faster to decode full frames than DWAA_COMPRESSION. Supported since OpenEXR 2.2.0. + }; + +//! Imwrite PNG specific flags used to tune the compression algorithm. +/** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. + +- The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. +- IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data. +- The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. +- IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. +*/ +enum ImwritePNGFlags { + IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. + IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. + IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). + IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). + IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. + }; + +//! Imwrite PAM specific tupletype flags used to define the 'TUPLETYPE' field of a PAM file. +enum ImwritePAMFlags { + IMWRITE_PAM_FORMAT_NULL = 0, + IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, + IMWRITE_PAM_FORMAT_GRAYSCALE = 2, + IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, + IMWRITE_PAM_FORMAT_RGB = 4, + IMWRITE_PAM_FORMAT_RGB_ALPHA = 5 + }; + +//! Imwrite HDR specific values for IMWRITE_HDR_COMPRESSION parameter key +enum ImwriteHDRCompressionFlags { + IMWRITE_HDR_COMPRESSION_NONE = 0, + IMWRITE_HDR_COMPRESSION_RLE = 1 +}; + +//! Imwrite GIF specific values for IMWRITE_GIF_QUALITY parameter key, if larger than 3, then its related to the size of the color table. +enum ImwriteGIFCompressionFlags { + IMWRITE_GIF_FAST_NO_DITHER = 1, + IMWRITE_GIF_FAST_FLOYD_DITHER = 2, + IMWRITE_GIF_COLORTABLE_SIZE_8 = 3, + IMWRITE_GIF_COLORTABLE_SIZE_16 = 4, + IMWRITE_GIF_COLORTABLE_SIZE_32 = 5, + IMWRITE_GIF_COLORTABLE_SIZE_64 = 6, + IMWRITE_GIF_COLORTABLE_SIZE_128 = 7, + IMWRITE_GIF_COLORTABLE_SIZE_256 = 8 +}; + +//! @} imgcodecs_flags + +/** @brief Represents an animation with multiple frames. +The `Animation` struct is designed to store and manage data for animated sequences such as those from animated formats (e.g., GIF, AVIF, APNG, WebP). +It provides support for looping, background color settings, frame timing, and frame storage. +*/ +struct CV_EXPORTS_W_SIMPLE Animation +{ + //! Number of times the animation should loop. 0 means infinite looping. + CV_PROP_RW int loop_count; + //! Background color of the animation in BGRA format. + CV_PROP_RW Scalar bgcolor; + //! Duration for each frame in milliseconds. + CV_PROP_RW std::vector durations; + //! Vector of frames, where each Mat represents a single frame. + CV_PROP_RW std::vector frames; + + /** @brief Constructs an Animation object with optional loop count and background color. + + @param loopCount An integer representing the number of times the animation should loop: + - `0` (default) indicates infinite looping, meaning the animation will replay continuously. + - Positive values denote finite repeat counts, allowing the animation to play a limited number of times. + - If a negative value or a value beyond the maximum of `0xffff` (65535) is provided, it is reset to `0` + (infinite looping) to maintain valid bounds. + + @param bgColor A `Scalar` object representing the background color in BGRA format: + - Defaults to `Scalar()`, indicating an empty color (usually transparent if supported). + - This background color provides a solid fill behind frames that have transparency, ensuring a consistent display appearance. + */ + Animation(int loopCount = 0, Scalar bgColor = Scalar()); +}; + +/** @brief Loads an image from a file. + +@anchor imread + +The `imread` function loads an image from the specified file and returns OpenCV matrix. If the image cannot be +read (because of a missing file, improper permissions, or unsupported/invalid format), the function +returns an empty matrix. + +Currently, the following file formats are supported: + +- Windows bitmaps - \*.bmp, \*.dib (always supported) +- GIF files - \*.gif (always supported) +- JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Note* section) +- JPEG 2000 files - \*.jp2 (see the *Note* section) +- Portable Network Graphics - \*.png (see the *Note* section) +- WebP - \*.webp (see the *Note* section) +- AVIF - \*.avif (see the *Note* section) +- Portable image format - \*.pbm, \*.pgm, \*.ppm, \*.pxm, \*.pnm (always supported) +- PFM files - \*.pfm (see the *Note* section) +- Sun rasters - \*.sr, \*.ras (always supported) +- TIFF files - \*.tiff, \*.tif (see the *Note* section) +- OpenEXR Image files - \*.exr (see the *Note* section) +- Radiance HDR - \*.hdr, \*.pic (always supported) +- Raster and Vector geospatial data supported by GDAL (see the *Note* section) + +@note +- The function determines the type of an image by its content, not by the file extension. +- In the case of color images, the decoded images will have the channels stored in **B G R** order. +- When using IMREAD_GRAYSCALE, the codec's internal grayscale conversion will be used, if available. + Results may differ from the output of cvtColor(). +- On Microsoft Windows\* and Mac OS\*, the codecs shipped with OpenCV (libjpeg, libpng, libtiff, + and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On Mac OS, + there is also an option to use native Mac OS image readers. However, beware that currently these + native image loaders give images with different pixel values because of the color management embedded + into Mac OS. +- On Linux\*, BSD flavors, and other Unix-like open-source operating systems, OpenCV looks for + codecs supplied with the OS. Ensure the relevant packages are installed (including development + files, such as "libjpeg-dev" in Debian\* and Ubuntu\*) to get codec support, or turn + on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. +- If the *WITH_GDAL* flag is set to true in CMake and @ref IMREAD_LOAD_GDAL is used to load the image, + the [GDAL](http://www.gdal.org) driver will be used to decode the image, supporting + [Raster](http://www.gdal.org/formats_list.html) and [Vector](http://www.gdal.org/ogr_formats.html) formats. +- If EXIF information is embedded in the image file, the EXIF orientation will be taken into account, + and thus the image will be rotated accordingly unless the flags @ref IMREAD_IGNORE_ORIENTATION + or @ref IMREAD_UNCHANGED are passed. +- Use the IMREAD_UNCHANGED flag to preserve the floating-point values from PFM images. +- By default, the number of pixels must be less than 2^30. This limit can be changed by setting + the environment variable `OPENCV_IO_MAX_IMAGE_PIXELS`. See @ref tutorial_env_reference. + +@param filename Name of the file to be loaded. +@param flags Flag that can take values of `cv::ImreadModes`. +*/ +CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR_BGR ); + +/** @brief Loads an image from a file. + +This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts and the return value. +@param filename Name of file to be loaded. +@param dst object in which the image will be loaded. +@param flags Flag that can take values of cv::ImreadModes +@note +The image passing through the img parameter can be pre-allocated. The memory is reused if the shape and the type match with the load image. + */ +CV_EXPORTS_W void imread( const String& filename, OutputArray dst, int flags = IMREAD_COLOR_BGR ); + +/** @brief Loads a multi-page image from a file. + +The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. +@param filename Name of file to be loaded. +@param mats A vector of Mat objects holding each page. +@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. +@sa cv::imread +*/ +CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int flags = IMREAD_ANYCOLOR); + +/** @brief Loads images of a multi-page image from a file. + +The function imreadmulti loads a specified range from a multi-page image from the specified file into a vector of Mat objects. +@param filename Name of file to be loaded. +@param mats A vector of Mat objects holding each page. +@param start Start index of the image to load +@param count Count number of images to load +@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. +@sa cv::imread +*/ +CV_EXPORTS_W bool imreadmulti(const String& filename, CV_OUT std::vector& mats, int start, int count, int flags = IMREAD_ANYCOLOR); + +/** @example samples/cpp/tutorial_code/imgcodecs/animations.cpp +An example to show usage of cv::imreadanimation and cv::imwriteanimation functions. +Check @ref tutorial_animations "the corresponding tutorial" for more details +*/ + +/** @brief Loads frames from an animated image file into an Animation structure. + +The function imreadanimation loads frames from an animated image file (e.g., GIF, AVIF, APNG, WEBP) into the provided Animation struct. + +@param filename A string containing the path to the file. +@param animation A reference to an Animation structure where the loaded frames will be stored. It should be initialized before the function is called. +@param start The index of the first frame to load. This is optional and defaults to 0. +@param count The number of frames to load. This is optional and defaults to 32767. + +@return Returns true if the file was successfully loaded and frames were extracted; returns false otherwise. +*/ +CV_EXPORTS_W bool imreadanimation(const String& filename, CV_OUT Animation& animation, int start = 0, int count = INT16_MAX); + +/** @brief Saves an Animation to a specified file. + +The function imwriteanimation saves the provided Animation data to the specified file in an animated format. +Supported formats depend on the implementation and may include formats like GIF, AVIF, APNG, or WEBP. + +@param filename The name of the file where the animation will be saved. The file extension determines the format. +@param animation A constant reference to an Animation struct containing the frames and metadata to be saved. +@param params Optional format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ...). +These parameters are used to specify additional options for the encoding process. Refer to `cv::ImwriteFlags` for details on possible parameters. + +@return Returns true if the animation was successfully saved; returns false otherwise. +*/ +CV_EXPORTS_W bool imwriteanimation(const String& filename, const Animation& animation, const std::vector& params = std::vector()); + +/** @brief Returns the number of images inside the given file + +The function imcount returns the number of pages in a multi-page image (e.g. TIFF), the number of frames in an animation (e.g. AVIF), and 1 otherwise. +If the image cannot be decoded, 0 is returned. +@param filename Name of file to be loaded. +@param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. +@todo when cv::IMREAD_LOAD_GDAL flag used the return value will be 0 or 1 because OpenCV's GDAL decoder doesn't support multi-page reading yet. +*/ +CV_EXPORTS_W size_t imcount(const String& filename, int flags = IMREAD_ANYCOLOR); + +/** @brief Saves an image to a specified file. + +The function imwrite saves the image to the specified file. The image format is chosen based on the +filename extension (see cv::imread for the list of extensions). In general, only 8-bit unsigned (CV_8U) +single-channel or 3-channel (with 'BGR' channel order) images +can be saved using this function, with these exceptions: + +- With OpenEXR encoder, only 32-bit float (CV_32F) images can be saved. + - 8-bit unsigned (CV_8U) images are not supported. +- With Radiance HDR encoder, non 64-bit float (CV_64F) images can be saved. + - All images will be converted to 32-bit float (CV_32F). +- With JPEG 2000 encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. +- With JPEG XL encoder, 8-bit unsigned (CV_8U), 16-bit unsigned (CV_16U) and 32-bit float(CV_32F) images can be saved. + - JPEG XL images with an alpha channel can be saved using this function. + To do this, create 8-bit (or 16-bit, 32-bit float) 4-channel image BGRA, where the alpha channel goes last. + Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535/1.0. +- With PAM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. +- With PNG encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. + - PNG images with an alpha channel can be saved using this function. To do this, create + 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels + should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535 (see the code sample below). +- With PGM/PPM encoder, 8-bit unsigned (CV_8U) and 16-bit unsigned (CV_16U) images can be saved. +- With TIFF encoder, 8-bit unsigned (CV_8U), 8-bit signed (CV_8S), + 16-bit unsigned (CV_16U), 16-bit signed (CV_16S), + 32-bit signed (CV_32S), + 32-bit float (CV_32F) and 64-bit float (CV_64F) images can be saved. + - Multiple images (vector of Mat) can be saved in TIFF format (see the code sample below). + - 32-bit float 3-channel (CV_32FC3) TIFF images will be saved + using the LogLuv high dynamic range encoding (4 bytes per pixel) + +If the image format is not supported, the image will be converted to 8-bit unsigned (CV_8U) and saved that way. + +If the format, depth or channel order is different, use +Mat::convertTo and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O +functions to save the image to XML or YAML format. + +The sample below shows how to create a BGRA image, how to set custom compression parameters and save it to a PNG file. +It also demonstrates how to save multiple images in a TIFF file: +@include snippets/imgcodecs_imwrite.cpp +@param filename Name of the file. +@param img (Mat or vector of Mat) Image or Images to be saved. +@param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags +*/ +CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, + const std::vector& params = std::vector()); + +//! @brief multi-image overload for bindings +CV_WRAP static inline +bool imwritemulti(const String& filename, InputArrayOfArrays img, + const std::vector& params = std::vector()) +{ + return imwrite(filename, img, params); +} + +/** @brief Reads an image from a buffer in memory. + +The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or +contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). + +See cv::imread for the list of supported formats and flags description. + +@note In the case of color images, the decoded images will have the channels stored in **B G R** order. +@param buf Input array or vector of bytes. +@param flags The same flags as in cv::imread, see cv::ImreadModes. +*/ +CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); + +/** @overload +@param buf Input array or vector of bytes. +@param flags The same flags as in cv::imread, see cv::ImreadModes. +@param dst The optional output placeholder for the decoded matrix. It can save the image +reallocations when the function is called repeatedly for images of the same size. In case of decoder +failure the function returns empty cv::Mat object, but does not release user-provided dst buffer. +*/ +CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); + +/** @brief Reads a multi-page image from a buffer in memory. + +The function imdecodemulti reads a multi-page image from the specified buffer in the memory. If the buffer is too short or +contains invalid data, the function returns false. + +See cv::imreadmulti for the list of supported formats and flags description. + +@note In the case of color images, the decoded images will have the channels stored in **B G R** order. +@param buf Input array or vector of bytes. +@param flags The same flags as in cv::imread, see cv::ImreadModes. +@param mats A vector of Mat objects holding each page, if more than one. +@param range A continuous selection of pages. +*/ +CV_EXPORTS_W bool imdecodemulti(InputArray buf, int flags, CV_OUT std::vector& mats, const cv::Range& range = Range::all()); + +/** @brief Encodes an image into a memory buffer. + +The function imencode compresses the image and stores it in the memory buffer that is resized to fit the +result. See cv::imwrite for the list of supported formats and flags description. + +@param ext File extension that defines the output format. Must include a leading period. +@param img Image to be compressed. +@param buf Output buffer resized to fit the compressed image. +@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. +*/ +CV_EXPORTS_W bool imencode( const String& ext, InputArray img, + CV_OUT std::vector& buf, + const std::vector& params = std::vector()); + +/** @brief Encodes array of images into a memory buffer. + +The function is analog to cv::imencode for in-memory multi-page image compression. +See cv::imwrite for the list of supported formats and flags description. + +@param ext File extension that defines the output format. Must include a leading period. +@param imgs Vector of images to be written. +@param buf Output buffer resized to fit the compressed data. +@param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. +*/ +CV_EXPORTS_W bool imencodemulti( const String& ext, InputArrayOfArrays imgs, + CV_OUT std::vector& buf, + const std::vector& params = std::vector()); + +/** @brief Checks if the specified image file can be decoded by OpenCV. + +The function haveImageReader checks if OpenCV is capable of reading the specified file. +This can be useful for verifying support for a given image format before attempting to load an image. + +@param filename The name of the file to be checked. +@return true if an image reader for the specified file is available and the file can be opened, false otherwise. + +@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. +It does not check for the actual existence of the file but rather the ability to read the specified file type. +If the file cannot be opened or the format is unsupported, the function will return false. + +@sa cv::haveImageWriter, cv::imread, cv::imdecode +*/ +CV_EXPORTS_W bool haveImageReader( const String& filename ); + +/** @brief Checks if the specified image file or specified file extension can be encoded by OpenCV. + +The function haveImageWriter checks if OpenCV is capable of writing images with the specified file extension. +This can be useful for verifying support for a given image format before attempting to save an image. + +@param filename The name of the file or the file extension (e.g., ".jpg", ".png"). +It is recommended to provide the file extension rather than the full file name. +@return true if an image writer for the specified extension is available, false otherwise. + +@note The function checks the availability of image codecs that are either built into OpenCV or dynamically loaded. +It does not check for the actual existence of the file but rather the ability to write files of the given type. + +@sa cv::haveImageReader, cv::imwrite, cv::imencode +*/ +CV_EXPORTS_W bool haveImageWriter( const String& filename ); + +/** @brief To read multi-page images on demand + +The ImageCollection class provides iterator API to read multi-page images on demand. Create iterator +to the collection of the images and iterate over the collection. Decode the necessary page with operator*. + +The performance of page decoding is O(1) if collection is increment sequentially. If the user wants to access random page, +then the time Complexity is O(n) because the collection has to be reinitialized every time in order to go to the correct page. +However, the intermediate pages are not decoded during the process, so typically it's quite fast. +This is required because multi-page codecs does not support going backwards. +After decoding the one page, it is stored inside the collection cache. Hence, trying to get Mat object from already decoded page is O(1). +If you need memory, you can use .releaseCache() method to release cached index. +The space complexity is O(n) if all pages are decoded into memory. The user is able to decode and release images on demand. +*/ +class CV_EXPORTS ImageCollection { +public: + struct CV_EXPORTS iterator { + iterator(ImageCollection* col); + iterator(ImageCollection* col, int end); + Mat& operator*(); + Mat* operator->(); + iterator& operator++(); + iterator operator++(int); + friend bool operator== (const iterator& a, const iterator& b) { return a.m_curr == b.m_curr; } + friend bool operator!= (const iterator& a, const iterator& b) { return a.m_curr != b.m_curr; } + + private: + ImageCollection* m_pCollection; + int m_curr; + }; + + ImageCollection(); + ImageCollection(const String& filename, int flags); + void init(const String& img, int flags); + size_t size() const; + const Mat& at(int index); + const Mat& operator[](int index); + void releaseCache(int index); + iterator begin(); + iterator end(); + + class Impl; + Ptr getImpl(); +protected: + Ptr pImpl; +}; + +//! @} imgcodecs + +} // cv + +#endif //OPENCV_IMGCODECS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp index d2ed9f435b..a3cd232645 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/imgcodecs.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/imgcodecs.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h index e870a3ba24..c78b3f72fa 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/imgcodecs_c.h @@ -1 +1 @@ -#error "This header with legacy C API declarations has been removed from OpenCV. Legacy constants are available from legacy/constants_c.h file." +#error "This header with legacy C API declarations has been removed from OpenCV. Legacy constants are available from legacy/constants_c.h file." diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h index 2bd679a23d..5f17218170 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/ios.h @@ -1,59 +1,59 @@ - -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#import -#import -#import -#import -#include "opencv2/core.hpp" - -//! @addtogroup imgcodecs_ios -//! @{ - -CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; -CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); -CV_EXPORTS UIImage* MatToUIImage(const cv::Mat& image); -CV_EXPORTS void UIImageToMat(const UIImage* image, - cv::Mat& m, bool alphaExist = false); - -//! @} + +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#import +#import +#import +#import +#include "opencv2/core.hpp" + +//! @addtogroup imgcodecs_ios +//! @{ + +CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; +CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); +CV_EXPORTS UIImage* MatToUIImage(const cv::Mat& image); +CV_EXPORTS void UIImageToMat(const UIImage* image, + cv::Mat& m, bool alphaExist = false); + +//! @} diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h index f38c928c9d..de7be4f74d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/legacy/constants_c.h @@ -1,54 +1,54 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_IMGCODECS_LEGACY_CONSTANTS_H -#define OPENCV_IMGCODECS_LEGACY_CONSTANTS_H - -/* duplicate of "ImreadModes" enumeration for better compatibility with OpenCV 3.x */ -enum -{ -/* 8bit, color or not */ - CV_LOAD_IMAGE_UNCHANGED =-1, -/* 8bit, gray */ - CV_LOAD_IMAGE_GRAYSCALE =0, -/* ?, color */ - CV_LOAD_IMAGE_COLOR =1, -/* any depth, ? */ - CV_LOAD_IMAGE_ANYDEPTH =2, -/* ?, any color */ - CV_LOAD_IMAGE_ANYCOLOR =4, -/* ?, no rotate */ - CV_LOAD_IMAGE_IGNORE_ORIENTATION =128 -}; - -/* duplicate of "ImwriteFlags" enumeration for better compatibility with OpenCV 3.x */ -enum -{ - CV_IMWRITE_JPEG_QUALITY =1, - CV_IMWRITE_JPEG_PROGRESSIVE =2, - CV_IMWRITE_JPEG_OPTIMIZE =3, - CV_IMWRITE_JPEG_RST_INTERVAL =4, - CV_IMWRITE_JPEG_LUMA_QUALITY =5, - CV_IMWRITE_JPEG_CHROMA_QUALITY =6, - CV_IMWRITE_PNG_COMPRESSION =16, - CV_IMWRITE_PNG_STRATEGY =17, - CV_IMWRITE_PNG_BILEVEL =18, - CV_IMWRITE_PNG_STRATEGY_DEFAULT =0, - CV_IMWRITE_PNG_STRATEGY_FILTERED =1, - CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, - CV_IMWRITE_PNG_STRATEGY_RLE =3, - CV_IMWRITE_PNG_STRATEGY_FIXED =4, - CV_IMWRITE_PXM_BINARY =32, - CV_IMWRITE_EXR_TYPE = 48, - CV_IMWRITE_WEBP_QUALITY =64, - CV_IMWRITE_PAM_TUPLETYPE = 128, - CV_IMWRITE_PAM_FORMAT_NULL = 0, - CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, - CV_IMWRITE_PAM_FORMAT_GRAYSCALE = 2, - CV_IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, - CV_IMWRITE_PAM_FORMAT_RGB = 4, - CV_IMWRITE_PAM_FORMAT_RGB_ALPHA = 5, -}; - -#endif // OPENCV_IMGCODECS_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_IMGCODECS_LEGACY_CONSTANTS_H +#define OPENCV_IMGCODECS_LEGACY_CONSTANTS_H + +/* duplicate of "ImreadModes" enumeration for better compatibility with OpenCV 3.x */ +enum +{ +/* 8bit, color or not */ + CV_LOAD_IMAGE_UNCHANGED =-1, +/* 8bit, gray */ + CV_LOAD_IMAGE_GRAYSCALE =0, +/* ?, color */ + CV_LOAD_IMAGE_COLOR =1, +/* any depth, ? */ + CV_LOAD_IMAGE_ANYDEPTH =2, +/* ?, any color */ + CV_LOAD_IMAGE_ANYCOLOR =4, +/* ?, no rotate */ + CV_LOAD_IMAGE_IGNORE_ORIENTATION =128 +}; + +/* duplicate of "ImwriteFlags" enumeration for better compatibility with OpenCV 3.x */ +enum +{ + CV_IMWRITE_JPEG_QUALITY =1, + CV_IMWRITE_JPEG_PROGRESSIVE =2, + CV_IMWRITE_JPEG_OPTIMIZE =3, + CV_IMWRITE_JPEG_RST_INTERVAL =4, + CV_IMWRITE_JPEG_LUMA_QUALITY =5, + CV_IMWRITE_JPEG_CHROMA_QUALITY =6, + CV_IMWRITE_PNG_COMPRESSION =16, + CV_IMWRITE_PNG_STRATEGY =17, + CV_IMWRITE_PNG_BILEVEL =18, + CV_IMWRITE_PNG_STRATEGY_DEFAULT =0, + CV_IMWRITE_PNG_STRATEGY_FILTERED =1, + CV_IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY =2, + CV_IMWRITE_PNG_STRATEGY_RLE =3, + CV_IMWRITE_PNG_STRATEGY_FIXED =4, + CV_IMWRITE_PXM_BINARY =32, + CV_IMWRITE_EXR_TYPE = 48, + CV_IMWRITE_WEBP_QUALITY =64, + CV_IMWRITE_PAM_TUPLETYPE = 128, + CV_IMWRITE_PAM_FORMAT_NULL = 0, + CV_IMWRITE_PAM_FORMAT_BLACKANDWHITE = 1, + CV_IMWRITE_PAM_FORMAT_GRAYSCALE = 2, + CV_IMWRITE_PAM_FORMAT_GRAYSCALE_ALPHA = 3, + CV_IMWRITE_PAM_FORMAT_RGB = 4, + CV_IMWRITE_PAM_FORMAT_RGB_ALPHA = 5, +}; + +#endif // OPENCV_IMGCODECS_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h index 5bf4cfb2e3..cfb0770700 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgcodecs/macosx.h @@ -1,20 +1,20 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#if !defined(__APPLE__) || !defined(__MACH__) -#error This header should be used in macOS ObjC/Swift projects. -#endif - -#import -#include "opencv2/core.hpp" - -//! @addtogroup imgcodecs_macosx -//! @{ - -CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; -CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); -CV_EXPORTS NSImage* MatToNSImage(const cv::Mat& image); -CV_EXPORTS void NSImageToMat(const NSImage* image, cv::Mat& m, bool alphaExist = false); - -//! @} +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#if !defined(__APPLE__) || !defined(__MACH__) +#error This header should be used in macOS ObjC/Swift projects. +#endif + +#import +#include "opencv2/core.hpp" + +//! @addtogroup imgcodecs_macosx +//! @{ + +CV_EXPORTS CGImageRef MatToCGImage(const cv::Mat& image) CF_RETURNS_RETAINED; +CV_EXPORTS void CGImageToMat(const CGImageRef image, cv::Mat& m, bool alphaExist = false); +CV_EXPORTS NSImage* MatToNSImage(const cv::Mat& image); +CV_EXPORTS void NSImageToMat(const NSImage* image, cv::Mat& m, bool alphaExist = false); + +//! @} diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp index 4f8fe77d26..3daa6d1a0d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc.hpp @@ -1,5101 +1,5101 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_IMGPROC_HPP -#define OPENCV_IMGPROC_HPP - -#include "opencv2/core.hpp" - -/** -@defgroup imgproc Image Processing - -This module offers a comprehensive suite of image processing functions, enabling tasks such as those listed above. - -@{ - @defgroup imgproc_filter Image Filtering - - Functions and classes described in this section are used to perform various linear or non-linear - filtering operations on 2D images (represented as Mat's). It means that for each pixel location - \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to - compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of - morphological operations, it is the minimum or maximum values, and so on. The computed response is - stored in the destination image at the same location \f$(x,y)\f$. It means that the output image - will be of the same size as the input image. Normally, the functions support multi-channel arrays, - in which case every channel is processed independently. Therefore, the output image will also have - the same number of channels as the input one. - - Another common feature of the functions and classes described in this section is that, unlike - simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For - example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when - processing the left-most pixels in each row, you need pixels to the left of them, that is, outside - of the image. You can let these pixels be the same as the left-most image pixels ("replicated - border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant - border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method. - For details, see #BorderTypes - - @anchor filter_depths - ### Depth combinations - Input depth (src.depth()) | Output depth (ddepth) - --------------------------|---------------------- - CV_8U | -1/CV_16S/CV_32F/CV_64F - CV_16U/CV_16S | -1/CV_32F/CV_64F - CV_32F | -1/CV_32F - CV_64F | -1/CV_64F - - @note when ddepth=-1, the output image will have the same depth as the source. - - @note if you need double floating-point accuracy and using single floating-point input data - (CV_32F input and CV_64F output depth combination), you can use @ref Mat.convertTo to convert - the input data to the desired precision. - - @defgroup imgproc_transform Geometric Image Transformations - - The functions in this section perform various geometrical transformations of 2D images. They do not - change the image content but deform the pixel grid and map this deformed grid to the destination - image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from - destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the - functions compute coordinates of the corresponding "donor" pixel in the source image and copy the - pixel value: - - \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f] - - In case when you specify the forward mapping \f$\left: \texttt{src} \rightarrow - \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping - \f$\left: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula. - - The actual implementations of the geometrical transformations, from the most generic remap and to - the simplest and the fastest resize, need to solve two main problems with the above formula: - - - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the - previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both - of them may fall outside of the image. In this case, an extrapolation method needs to be used. - OpenCV provides the same selection of extrapolation methods as in the filtering functions. In - addition, it provides the method #BORDER_TRANSPARENT. This means that the corresponding pixels in - the destination image will not be modified at all. - - - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point - numbers. This means that \f$\left\f$ can be either an affine or perspective - transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional - coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the - nearest integer coordinates and the corresponding pixel can be used. This is called a - nearest-neighbor interpolation. However, a better result can be achieved by using more - sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) , - where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y), - f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the - interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See - #resize for details. - - @note The geometrical transformations do not work with `CV_8S` or `CV_32S` images. - - @defgroup imgproc_misc Miscellaneous Image Transformations - @defgroup imgproc_draw Drawing Functions - - Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be - rendered with antialiasing (implemented only for 8-bit images for now). All the functions include - the parameter color that uses an RGB value (that may be constructed with the Scalar constructor ) - for color images and brightness for grayscale images. For color images, the channel ordering is - normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a - color using the Scalar constructor, it should look like: - - \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f] - - If you are using your own image rendering and I/O functions, you can use any channel ordering. The - drawing functions process each channel independently and do not depend on the channel order or even - on the used color space. The whole image can be converted from BGR to RGB or to a different color - space using cvtColor . - - If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, - many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means - that the coordinates can be passed as fixed-point numbers encoded as integers. The number of - fractional bits is specified by the shift parameter and the real point coordinates are calculated as - \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is - especially effective when rendering antialiased shapes. - - @note The functions do not support alpha-transparency when the target image is 4-channel. In this - case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint - semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main - image. - - @defgroup imgproc_color_conversions Color Space Conversions - @defgroup imgproc_colormap ColorMaps in OpenCV - - The human perception isn't built for observing fine changes in grayscale images. Human eyes are more - sensitive to observing changes between colors, so you often need to recolor your grayscale images to - get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your - computer vision application. - - In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample - code reads the path to an image from command line, applies a Jet colormap on it and shows the - result: - - @include snippets/imgproc_applyColorMap.cpp - - @see #ColormapTypes - - @defgroup imgproc_subdiv2d Planar Subdivision - - The Subdiv2D class described in this section is used to perform various planar subdivision on - a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles - using the Delaunay's algorithm, which corresponds to the dual graph of the Voronoi diagram. - In the figure below, the Delaunay's triangulation is marked with black lines and the Voronoi - diagram with red lines. - - ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png) - - The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast - location of points on the plane, building special graphs (such as NNG,RNG), and so forth. - - @defgroup imgproc_hist Histograms - @defgroup imgproc_shape Structural Analysis and Shape Descriptors - @defgroup imgproc_motion Motion Analysis and Object Tracking - @defgroup imgproc_feature Feature Detection - @defgroup imgproc_object Object Detection - @defgroup imgproc_segmentation Image Segmentation - @defgroup imgproc_hal Hardware Acceleration Layer - @{ - @defgroup imgproc_hal_functions Functions - @defgroup imgproc_hal_interface Interface - @} - @} -*/ - -namespace cv -{ - -/** @addtogroup imgproc -@{ -*/ - -//! @addtogroup imgproc_filter -//! @{ - -enum SpecialFilter { - FILTER_SCHARR = -1 -}; - -//! type of morphological operation -enum MorphTypes{ - MORPH_ERODE = 0, //!< see #erode - MORPH_DILATE = 1, //!< see #dilate - MORPH_OPEN = 2, //!< an opening operation - //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] - MORPH_CLOSE = 3, //!< a closing operation - //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] - MORPH_GRADIENT = 4, //!< a morphological gradient - //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] - MORPH_TOPHAT = 5, //!< "top hat" - //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] - MORPH_BLACKHAT = 6, //!< "black hat" - //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] - MORPH_HITMISS = 7 //!< "hit or miss" - //!< .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation -}; - -//! shape of the structuring element -enum MorphShapes { - MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f] - MORPH_CROSS = 1, //!< a cross-shaped structuring element: - //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f] - MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed - //!< into the rectangle Rect(0, 0, esize.width, esize.height) -}; - -//! @} imgproc_filter - -//! @addtogroup imgproc_transform -//! @{ - -//! interpolation algorithm -enum InterpolationFlags{ - /** nearest neighbor interpolation */ - INTER_NEAREST = 0, - /** bilinear interpolation */ - INTER_LINEAR = 1, - /** bicubic interpolation */ - INTER_CUBIC = 2, - /** resampling using pixel area relation. It may be a preferred method for image decimation, as - it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST - method. */ - INTER_AREA = 3, - /** Lanczos interpolation over 8x8 neighborhood */ - INTER_LANCZOS4 = 4, - /** Bit exact bilinear interpolation */ - INTER_LINEAR_EXACT = 5, - /** Bit exact nearest neighbor interpolation. This will produce same results as - the nearest neighbor method in PIL, scikit-image or Matlab. */ - INTER_NEAREST_EXACT = 6, - /** mask for interpolation codes */ - INTER_MAX = 7, - /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the - source image, they are set to zero */ - WARP_FILL_OUTLIERS = 8, - /** flag, inverse transformation - - For example, #linearPolar or #logPolar transforms: - - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$ - - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$ - */ - WARP_INVERSE_MAP = 16, - WARP_RELATIVE_MAP = 32 -}; - -/** \brief Specify the polar mapping mode -@sa warpPolar -*/ -enum WarpPolarMode -{ - WARP_POLAR_LINEAR = 0, ///< Remaps an image to/from polar space. - WARP_POLAR_LOG = 256 ///< Remaps an image to/from semilog-polar space. -}; - -enum InterpolationMasks { - INTER_BITS = 5, - INTER_BITS2 = INTER_BITS * 2, - INTER_TAB_SIZE = 1 << INTER_BITS, - INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE - }; - -//! @} imgproc_transform - -//! @addtogroup imgproc_misc -//! @{ - -//! Distance types for Distance Transform and M-estimators -//! @see distanceTransform, fitLine -enum DistanceTypes { - DIST_USER = -1, //!< User defined distance - DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2| - DIST_L2 = 2, //!< the simple euclidean distance - DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|) - DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) - DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 - DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 - DIST_HUBER = 7 //!< distance = |x| \texttt{thresh}\)}{0}{otherwise}\f] - THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] - THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] - THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] - THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] - THRESH_MASK = 7, - THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value - THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value -}; - -//! adaptive threshold algorithm -//! @see adaptiveThreshold -enum AdaptiveThresholdTypes { - /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times - \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */ - ADAPTIVE_THRESH_MEAN_C = 0, - /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian - window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ - minus C . The default sigma (standard deviation) is used for the specified blockSize . See - #getGaussianKernel*/ - ADAPTIVE_THRESH_GAUSSIAN_C = 1 -}; - -//! class of the pixel in GrabCut algorithm -enum GrabCutClasses { - GC_BGD = 0, //!< an obvious background pixels - GC_FGD = 1, //!< an obvious foreground (object) pixel - GC_PR_BGD = 2, //!< a possible background pixel - GC_PR_FGD = 3 //!< a possible foreground pixel -}; - -//! GrabCut algorithm flags -enum GrabCutModes { - /** The function initializes the state and the mask using the provided rectangle. After that it - runs iterCount iterations of the algorithm. */ - GC_INIT_WITH_RECT = 0, - /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT - and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are - automatically initialized with GC_BGD .*/ - GC_INIT_WITH_MASK = 1, - /** The value means that the algorithm should just resume. */ - GC_EVAL = 2, - /** The value means that the algorithm should just run the grabCut algorithm (a single iteration) with the fixed model */ - GC_EVAL_FREEZE_MODEL = 3 -}; - -//! distanceTransform algorithm flags -enum DistanceTransformLabelTypes { - /** each connected component of zeros in src (as well as all the non-zero pixels closest to the - connected component) will be assigned the same label */ - DIST_LABEL_CCOMP = 0, - /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */ - DIST_LABEL_PIXEL = 1 -}; - -//! floodfill algorithm flags -enum FloodFillFlags { - /** If set, the difference between the current pixel and seed pixel is considered. Otherwise, - the difference between neighbor pixels is considered (that is, the range is floating). */ - FLOODFILL_FIXED_RANGE = 1 << 16, - /** If set, the function does not change the image ( newVal is ignored), and only fills the - mask with the value specified in bits 8-16 of flags as described above. This option only make - sense in function variants that have the mask parameter. */ - FLOODFILL_MASK_ONLY = 1 << 17 -}; - -//! @} imgproc_misc - -//! @addtogroup imgproc_shape -//! @{ - -//! connected components statistics -enum ConnectedComponentsTypes { - CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding - //!< box in the horizontal direction. - CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding - //!< box in the vertical direction. - CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box - CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box - CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component -#ifndef CV_DOXYGEN - CC_STAT_MAX = 5 //!< Max enumeration value. Used internally only for memory allocation -#endif -}; - -//! connected components algorithm -enum ConnectedComponentsAlgorithmsTypes { - CCL_DEFAULT = -1, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. - CCL_WU = 0, //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for SAUF. - CCL_GRANA = 1, //!< BBDT @cite Grana2010 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both BBDT and SAUF. - CCL_BOLELLI = 2, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both Spaghetti and Spaghetti4C. - CCL_SAUF = 3, //!< Same as CCL_WU. It is preferable to use the flag with the name of the algorithm (CCL_SAUF) rather than the one with the name of the first author (CCL_WU). - CCL_BBDT = 4, //!< Same as CCL_GRANA. It is preferable to use the flag with the name of the algorithm (CCL_BBDT) rather than the one with the name of the first author (CCL_GRANA). - CCL_SPAGHETTI = 5, //!< Same as CCL_BOLELLI. It is preferable to use the flag with the name of the algorithm (CCL_SPAGHETTI) rather than the one with the name of the first author (CCL_BOLELLI). -}; - -//! mode of the contour retrieval algorithm -enum RetrievalModes { - /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for - all the contours. */ - RETR_EXTERNAL = 0, - /** retrieves all of the contours without establishing any hierarchical relationships. */ - RETR_LIST = 1, - /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top - level, there are external boundaries of the components. At the second level, there are - boundaries of the holes. If there is another contour inside a hole of a connected component, it - is still put at the top level. */ - RETR_CCOMP = 2, - /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/ - RETR_TREE = 3, - RETR_FLOODFILL = 4 //!< -}; - -//! the contour approximation algorithm -enum ContourApproximationModes { - /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and - (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, - max(abs(x1-x2),abs(y2-y1))==1. */ - CHAIN_APPROX_NONE = 1, - /** compresses horizontal, vertical, and diagonal segments and leaves only their end points. - For example, an up-right rectangular contour is encoded with 4 points. */ - CHAIN_APPROX_SIMPLE = 2, - /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ - CHAIN_APPROX_TC89_L1 = 3, - /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ - CHAIN_APPROX_TC89_KCOS = 4 -}; - -/** @brief Shape matching methods - -\f$A\f$ denotes object1,\f$B\f$ denotes object2 - -\f$\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}\f$ - -and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively. -*/ -enum ShapeMatchModes { - CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] - CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] - CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] -}; - -//! @} imgproc_shape - -//! @addtogroup imgproc_feature -//! @{ - -//! Variants of a Hough transform -enum HoughModes { - - /** classical or standard Hough transform. Every line is represented by two floating-point - numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line, - and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must - be (the created sequence will be) of CV_32FC2 type */ - HOUGH_STANDARD = 0, - /** probabilistic Hough transform (more efficient in case if the picture contains a few long - linear segments). It returns line segments rather than the whole line. Each segment is - represented by starting and ending points, and the matrix must be (the created sequence will - be) of the CV_32SC4 type. */ - HOUGH_PROBABILISTIC = 1, - /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as - HOUGH_STANDARD. */ - HOUGH_MULTI_SCALE = 2, - HOUGH_GRADIENT = 3, //!< basically *21HT*, described in @cite Yuen90 - HOUGH_GRADIENT_ALT = 4, //!< variation of HOUGH_GRADIENT to get better accuracy -}; - -//! Variants of Line Segment %Detector -enum LineSegmentDetectorModes { - LSD_REFINE_NONE = 0, //!< No refinement applied - LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations. - LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are - //!< refined through increase of precision, decrement in size, etc. -}; - -//! @} imgproc_feature - -/** Histogram comparison methods - @ingroup imgproc_hist -*/ -enum HistCompMethods { - /** Correlation - \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] - where - \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] - and \f$N\f$ is a total number of histogram bins. */ - HISTCMP_CORREL = 0, - /** Chi-Square - \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */ - HISTCMP_CHISQR = 1, - /** Intersection - \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */ - HISTCMP_INTERSECT = 2, - /** Bhattacharyya distance - (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.) - \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */ - HISTCMP_BHATTACHARYYA = 3, - HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA - /** Alternative Chi-Square - \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] - This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */ - HISTCMP_CHISQR_ALT = 4, - /** Kullback-Leibler divergence - \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */ - HISTCMP_KL_DIV = 5 -}; - -/** the color conversion codes -@see @ref imgproc_color_conversions -@ingroup imgproc_color_conversions - */ -enum ColorConversionCodes { - COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image - COLOR_RGB2RGBA = COLOR_BGR2BGRA, - - COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image - COLOR_RGBA2RGB = COLOR_BGRA2BGR, - - COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) - COLOR_RGB2BGRA = COLOR_BGR2RGBA, - - COLOR_RGBA2BGR = 3, - COLOR_BGRA2RGB = COLOR_RGBA2BGR, - - COLOR_BGR2RGB = 4, - COLOR_RGB2BGR = COLOR_BGR2RGB, - - COLOR_BGRA2RGBA = 5, - COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, - - COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions" - COLOR_RGB2GRAY = 7, - COLOR_GRAY2BGR = 8, - COLOR_GRAY2RGB = COLOR_GRAY2BGR, - COLOR_GRAY2BGRA = 9, - COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, - COLOR_BGRA2GRAY = 10, - COLOR_RGBA2GRAY = 11, - - COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) - COLOR_RGB2BGR565 = 13, - COLOR_BGR5652BGR = 14, - COLOR_BGR5652RGB = 15, - COLOR_BGRA2BGR565 = 16, - COLOR_RGBA2BGR565 = 17, - COLOR_BGR5652BGRA = 18, - COLOR_BGR5652RGBA = 19, - - COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) - COLOR_BGR5652GRAY = 21, - - COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) - COLOR_RGB2BGR555 = 23, - COLOR_BGR5552BGR = 24, - COLOR_BGR5552RGB = 25, - COLOR_BGRA2BGR555 = 26, - COLOR_RGBA2BGR555 = 27, - COLOR_BGR5552BGRA = 28, - COLOR_BGR5552RGBA = 29, - - COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) - COLOR_BGR5552GRAY = 31, - - COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions" - COLOR_RGB2XYZ = 33, - COLOR_XYZ2BGR = 34, - COLOR_XYZ2RGB = 35, - - COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions" - COLOR_RGB2YCrCb = 37, - COLOR_YCrCb2BGR = 38, - COLOR_YCrCb2RGB = 39, - - COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" - COLOR_RGB2HSV = 41, - - COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions" - COLOR_RGB2Lab = 45, - - COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions" - COLOR_RGB2Luv = 51, - COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hls "color conversions" - COLOR_RGB2HLS = 53, - - COLOR_HSV2BGR = 54, //!< backward conversions HSV to RGB/BGR with H range 0..180 if 8 bit image - COLOR_HSV2RGB = 55, - - COLOR_Lab2BGR = 56, - COLOR_Lab2RGB = 57, - COLOR_Luv2BGR = 58, - COLOR_Luv2RGB = 59, - COLOR_HLS2BGR = 60, //!< backward conversions HLS to RGB/BGR with H range 0..180 if 8 bit image - COLOR_HLS2RGB = 61, - - COLOR_BGR2HSV_FULL = 66, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" - COLOR_RGB2HSV_FULL = 67, - COLOR_BGR2HLS_FULL = 68, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hls "color conversions" - COLOR_RGB2HLS_FULL = 69, - - COLOR_HSV2BGR_FULL = 70, //!< backward conversions HSV to RGB/BGR with H range 0..255 if 8 bit image - COLOR_HSV2RGB_FULL = 71, - COLOR_HLS2BGR_FULL = 72, //!< backward conversions HLS to RGB/BGR with H range 0..255 if 8 bit image - COLOR_HLS2RGB_FULL = 73, - - COLOR_LBGR2Lab = 74, - COLOR_LRGB2Lab = 75, - COLOR_LBGR2Luv = 76, - COLOR_LRGB2Luv = 77, - - COLOR_Lab2LBGR = 78, - COLOR_Lab2LRGB = 79, - COLOR_Luv2LBGR = 80, - COLOR_Luv2LRGB = 81, - - COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV - COLOR_RGB2YUV = 83, - COLOR_YUV2BGR = 84, - COLOR_YUV2RGB = 85, - - COLOR_YUV2RGB_NV12 = 90, //!< convert between 4:2:0-subsampled YUV NV12 and RGB, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_NV12 = 91, //!< convert between 4:2:0-subsampled YUV NV12 and BGR, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_NV21 = 92, //!< convert between 4:2:0-subsampled YUV NV21 and RGB, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_NV21 = 93, //!< convert between 4:2:0-subsampled YUV NV21 and BGR, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, //!< synonym to NV21 - COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, //!< synonym to NV21 - - COLOR_YUV2RGBA_NV12 = 94, //!< convert between 4:2:0-subsampled YUV NV12 and RGBA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_NV12 = 95, //!< convert between 4:2:0-subsampled YUV NV12 and BGRA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_NV21 = 96, //!< convert between 4:2:0-subsampled YUV NV21 and RGBA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_NV21 = 97, //!< convert between 4:2:0-subsampled YUV NV21 and BGRA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x - COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, //!< synonym to NV21 - COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, //!< synonym to NV21 - - COLOR_YUV2RGB_YV12 = 98, //!< convert between 4:2:0-subsampled YUV YV12 and RGB, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_YV12 = 99, //!< convert between 4:2:0-subsampled YUV YV12 and BGR, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_IYUV = 100, //!< convert between 4:2:0-subsampled YUV IYUV and RGB, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_IYUV = 101, //!< convert between 4:2:0-subsampled YUV IYUV and BGR, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, //!< synonym to IYUV - COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, //!< synonym to IYUV - COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, //!< synonym to YV12 - COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, //!< synonym to YV12 - - COLOR_YUV2RGBA_YV12 = 102, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_YV12 = 103, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_IYUV = 104, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_IYUV = 105, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, //!< synonym to IYUV - COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, //!< synonym to IYUV - COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, //!< synonym to YV12 - COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, //!< synonym to YV12 - - COLOR_YUV2GRAY_420 = 106, //!< extract Y channel from YUV 4:2:0 image - COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 - - COLOR_YUV2RGB_UYVY = 107, //!< convert between YUV UYVY and RGB, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_UYVY = 108, //!< convert between YUV UYVY and BGR, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2RGB_VYUY = 109, //!< convert between YUV VYUY and RGB, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2BGR_VYUY = 110, //!< convert between YUV VYUY and BGR, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY - COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY - COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY - COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY - - COLOR_YUV2RGBA_UYVY = 111, //!< convert between YUV UYVY and RGBA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_UYVY = 112, //!< convert between YUV UYVY and BGRA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2RGBA_VYUY = 113, //!< convert between YUV VYUY and RGBA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - //COLOR_YUV2BGRA_VYUY = 114, //!< convert between YUV VYUY and BGRA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY - COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY - COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY - COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY - - COLOR_YUV2RGB_YUY2 = 115, //!< convert between YUV YUY2 and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_YUY2 = 116, //!< convert between YUV YUY2 and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_YVYU = 117, //!< convert between YUV YVYU and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGR_YVYU = 118, //!< convert between YUV YVYU and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 - COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 - - COLOR_YUV2RGBA_YUY2 = 119, //!< convert between YUV YUY2 and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_YUY2 = 120, //!< convert between YUV YUY2 and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_YVYU = 121, //!< convert between YUV YVYU and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2BGRA_YVYU = 122, //!< convert between YUV YVYU and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 - COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 - COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 - - COLOR_YUV2GRAY_UYVY = 123, //!< extract Y channel from YUV 4:2:2 image - COLOR_YUV2GRAY_YUY2 = 124, //!< extract Y channel from YUV 4:2:2 image - //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY - COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY - COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY - COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 - COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 - COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 - - //! alpha premultiplication - COLOR_RGBA2mRGBA = 125, - COLOR_mRGBA2RGBA = 126, - - COLOR_RGB2YUV_I420 = 127, //!< convert between RGB and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_I420 = 128, //!< convert between BGR and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, //!< synonym to I420 - COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, //!< synonym to I420 - - COLOR_RGBA2YUV_I420 = 129, //!< convert between RGBA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_I420 = 130, //!< convert between BGRA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, //!< synonym to I420 - COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, //!< synonym to I420 - COLOR_RGB2YUV_YV12 = 131, //!< convert between RGB and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_YV12 = 132, //!< convert between BGR and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_YV12 = 133, //!< convert between RGBA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_YV12 = 134, //!< convert between BGRA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x - - //! Demosaicing, see @ref color_convert_bayer "color conversions" for additional information - COLOR_BayerBG2BGR = 46, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGR = 47, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGR = 48, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGR = 49, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGR = COLOR_BayerBG2BGR, - COLOR_BayerGRBG2BGR = COLOR_BayerGB2BGR, - COLOR_BayerBGGR2BGR = COLOR_BayerRG2BGR, - COLOR_BayerGBRG2BGR = COLOR_BayerGR2BGR, - - COLOR_BayerRGGB2RGB = COLOR_BayerBGGR2BGR, - COLOR_BayerGRBG2RGB = COLOR_BayerGBRG2BGR, - COLOR_BayerBGGR2RGB = COLOR_BayerRGGB2BGR, - COLOR_BayerGBRG2RGB = COLOR_BayerGRBG2BGR, - - COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerBG2GRAY = 86, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2GRAY = 87, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2GRAY = 88, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2GRAY = 89, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2GRAY = COLOR_BayerBG2GRAY, - COLOR_BayerGRBG2GRAY = COLOR_BayerGB2GRAY, - COLOR_BayerBGGR2GRAY = COLOR_BayerRG2GRAY, - COLOR_BayerGBRG2GRAY = COLOR_BayerGR2GRAY, - - //! Demosaicing using Variable Number of Gradients - COLOR_BayerBG2BGR_VNG = 62, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGR_VNG = 63, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGR_VNG = 64, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGR_VNG = 65, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGR_VNG = COLOR_BayerBG2BGR_VNG, - COLOR_BayerGRBG2BGR_VNG = COLOR_BayerGB2BGR_VNG, - COLOR_BayerBGGR2BGR_VNG = COLOR_BayerRG2BGR_VNG, - COLOR_BayerGBRG2BGR_VNG = COLOR_BayerGR2BGR_VNG, - - COLOR_BayerRGGB2RGB_VNG = COLOR_BayerBGGR2BGR_VNG, - COLOR_BayerGRBG2RGB_VNG = COLOR_BayerGBRG2BGR_VNG, - COLOR_BayerBGGR2RGB_VNG = COLOR_BayerRGGB2BGR_VNG, - COLOR_BayerGBRG2RGB_VNG = COLOR_BayerGRBG2BGR_VNG, - - COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //!< equivalent to GBRG Bayer pattern - - //! Edge-Aware Demosaicing - COLOR_BayerBG2BGR_EA = 135, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGR_EA = 136, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGR_EA = 137, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGR_EA = 138, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGR_EA = COLOR_BayerBG2BGR_EA, - COLOR_BayerGRBG2BGR_EA = COLOR_BayerGB2BGR_EA, - COLOR_BayerBGGR2BGR_EA = COLOR_BayerRG2BGR_EA, - COLOR_BayerGBRG2BGR_EA = COLOR_BayerGR2BGR_EA, - - COLOR_BayerRGGB2RGB_EA = COLOR_BayerBGGR2BGR_EA, - COLOR_BayerGRBG2RGB_EA = COLOR_BayerGBRG2BGR_EA, - COLOR_BayerBGGR2RGB_EA = COLOR_BayerRGGB2BGR_EA, - COLOR_BayerGBRG2RGB_EA = COLOR_BayerGRBG2BGR_EA, - - COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, //!< equivalent to GBRG Bayer pattern - - //! Demosaicing with alpha channel - COLOR_BayerBG2BGRA = 139, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2BGRA = 140, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2BGRA = 141, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2BGRA = 142, //!< equivalent to GBRG Bayer pattern - - COLOR_BayerRGGB2BGRA = COLOR_BayerBG2BGRA, - COLOR_BayerGRBG2BGRA = COLOR_BayerGB2BGRA, - COLOR_BayerBGGR2BGRA = COLOR_BayerRG2BGRA, - COLOR_BayerGBRG2BGRA = COLOR_BayerGR2BGRA, - - COLOR_BayerRGGB2RGBA = COLOR_BayerBGGR2BGRA, - COLOR_BayerGRBG2RGBA = COLOR_BayerGBRG2BGRA, - COLOR_BayerBGGR2RGBA = COLOR_BayerRGGB2BGRA, - COLOR_BayerGBRG2RGBA = COLOR_BayerGRBG2BGRA, - - COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA, //!< equivalent to RGGB Bayer pattern - COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, //!< equivalent to GRBG Bayer pattern - COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, //!< equivalent to BGGR Bayer pattern - COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, //!< equivalent to GBRG Bayer pattern - - COLOR_RGB2YUV_UYVY = 143, //!< convert between RGB and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_UYVY = 144, //!< convert between BGR and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_Y422 = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY - COLOR_BGR2YUV_Y422 = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY - COLOR_RGB2YUV_UYNV = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY - COLOR_BGR2YUV_UYNV = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY - - COLOR_RGBA2YUV_UYVY = 145, //!< convert between RGBA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_UYVY = 146, //!< convert between BGRA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_Y422 = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY - COLOR_BGRA2YUV_Y422 = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY - COLOR_RGBA2YUV_UYNV = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY - COLOR_BGRA2YUV_UYNV = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY - - COLOR_RGB2YUV_YUY2 = 147, //!< convert between RGB and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_YUY2 = 148, //!< convert between BGR and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_YVYU = 149, //!< convert between RGB and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_BGR2YUV_YVYU = 150, //!< convert between BGR and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_RGB2YUV_YUYV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGR2YUV_YUYV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 - COLOR_RGB2YUV_YUNV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGR2YUV_YUNV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 - - COLOR_RGBA2YUV_YUY2 = 151, //!< convert between RGBA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_YUY2 = 152, //!< convert between BGRA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_YVYU = 153, //!< convert between RGBA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_BGRA2YUV_YVYU = 154, //!< convert between BGRA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x - COLOR_RGBA2YUV_YUYV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGRA2YUV_YUYV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 - COLOR_RGBA2YUV_YUNV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 - COLOR_BGRA2YUV_YUNV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 - - COLOR_COLORCVT_MAX = 155 -}; - -//! @addtogroup imgproc_shape -//! @{ - -//! types of intersection between rectangles -enum RectanglesIntersectTypes { - INTERSECT_NONE = 0, //!< No intersection - INTERSECT_PARTIAL = 1, //!< There is a partial intersection - INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other -}; - -/** types of line -@ingroup imgproc_draw -*/ -enum LineTypes { - FILLED = -1, - LINE_4 = 4, //!< 4-connected line - LINE_8 = 8, //!< 8-connected line - LINE_AA = 16 //!< antialiased line -}; - -/** Only a subset of Hershey fonts are supported -@ingroup imgproc_draw -*/ -enum HersheyFonts { - FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font - FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font - FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX) - FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font - FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX) - FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX - FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font - FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX - FONT_ITALIC = 16 //!< flag for italic font -}; - -/** Possible set of marker types used for the cv::drawMarker function -@ingroup imgproc_draw -*/ -enum MarkerTypes -{ - MARKER_CROSS = 0, //!< A crosshair marker shape - MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape - MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross - MARKER_DIAMOND = 3, //!< A diamond marker shape - MARKER_SQUARE = 4, //!< A square marker shape - MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape - MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape -}; - -/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform -*/ -class CV_EXPORTS_W GeneralizedHough : public Algorithm -{ -public: - //! set template to search - CV_WRAP virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; - CV_WRAP virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; - - //! find template on image - CV_WRAP virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; - CV_WRAP virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; - - //! Canny low threshold. - CV_WRAP virtual void setCannyLowThresh(int cannyLowThresh) = 0; - CV_WRAP virtual int getCannyLowThresh() const = 0; - - //! Canny high threshold. - CV_WRAP virtual void setCannyHighThresh(int cannyHighThresh) = 0; - CV_WRAP virtual int getCannyHighThresh() const = 0; - - //! Minimum distance between the centers of the detected objects. - CV_WRAP virtual void setMinDist(double minDist) = 0; - CV_WRAP virtual double getMinDist() const = 0; - - //! Inverse ratio of the accumulator resolution to the image resolution. - CV_WRAP virtual void setDp(double dp) = 0; - CV_WRAP virtual double getDp() const = 0; - - //! Maximal size of inner buffers. - CV_WRAP virtual void setMaxBufferSize(int maxBufferSize) = 0; - CV_WRAP virtual int getMaxBufferSize() const = 0; -}; - -/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform - -Detects position only without translation and rotation @cite Ballard1981 . -*/ -class CV_EXPORTS_W GeneralizedHoughBallard : public GeneralizedHough -{ -public: - //! R-Table levels. - CV_WRAP virtual void setLevels(int levels) = 0; - CV_WRAP virtual int getLevels() const = 0; - - //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. - CV_WRAP virtual void setVotesThreshold(int votesThreshold) = 0; - CV_WRAP virtual int getVotesThreshold() const = 0; -}; - -/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform - -Detects position, translation and rotation @cite Guil1999 . -*/ -class CV_EXPORTS_W GeneralizedHoughGuil : public GeneralizedHough -{ -public: - //! Angle difference in degrees between two points in feature. - CV_WRAP virtual void setXi(double xi) = 0; - CV_WRAP virtual double getXi() const = 0; - - //! Feature table levels. - CV_WRAP virtual void setLevels(int levels) = 0; - CV_WRAP virtual int getLevels() const = 0; - - //! Maximal difference between angles that treated as equal. - CV_WRAP virtual void setAngleEpsilon(double angleEpsilon) = 0; - CV_WRAP virtual double getAngleEpsilon() const = 0; - - //! Minimal rotation angle to detect in degrees. - CV_WRAP virtual void setMinAngle(double minAngle) = 0; - CV_WRAP virtual double getMinAngle() const = 0; - - //! Maximal rotation angle to detect in degrees. - CV_WRAP virtual void setMaxAngle(double maxAngle) = 0; - CV_WRAP virtual double getMaxAngle() const = 0; - - //! Angle step in degrees. - CV_WRAP virtual void setAngleStep(double angleStep) = 0; - CV_WRAP virtual double getAngleStep() const = 0; - - //! Angle votes threshold. - CV_WRAP virtual void setAngleThresh(int angleThresh) = 0; - CV_WRAP virtual int getAngleThresh() const = 0; - - //! Minimal scale to detect. - CV_WRAP virtual void setMinScale(double minScale) = 0; - CV_WRAP virtual double getMinScale() const = 0; - - //! Maximal scale to detect. - CV_WRAP virtual void setMaxScale(double maxScale) = 0; - CV_WRAP virtual double getMaxScale() const = 0; - - //! Scale step. - CV_WRAP virtual void setScaleStep(double scaleStep) = 0; - CV_WRAP virtual double getScaleStep() const = 0; - - //! Scale votes threshold. - CV_WRAP virtual void setScaleThresh(int scaleThresh) = 0; - CV_WRAP virtual int getScaleThresh() const = 0; - - //! Position votes threshold. - CV_WRAP virtual void setPosThresh(int posThresh) = 0; - CV_WRAP virtual int getPosThresh() const = 0; -}; - -//! @} imgproc_shape - -//! @addtogroup imgproc_hist -//! @{ - -/** @brief Base class for Contrast Limited Adaptive Histogram Equalization. -*/ -class CV_EXPORTS_W CLAHE : public Algorithm -{ -public: - /** @brief Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization. - - @param src Source image of type CV_8UC1 or CV_16UC1. - @param dst Destination image. - */ - CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; - - /** @brief Sets threshold for contrast limiting. - - @param clipLimit threshold value. - */ - CV_WRAP virtual void setClipLimit(double clipLimit) = 0; - - //! Returns threshold value for contrast limiting. - CV_WRAP virtual double getClipLimit() const = 0; - - /** @brief Sets size of grid for histogram equalization. Input image will be divided into - equally sized rectangular tiles. - - @param tileGridSize defines the number of tiles in row and column. - */ - CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; - - //!@brief Returns Size defines the number of tiles in row and column. - CV_WRAP virtual Size getTilesGridSize() const = 0; - - CV_WRAP virtual void collectGarbage() = 0; -}; - -//! @} imgproc_hist - -//! @addtogroup imgproc_subdiv2d -//! @{ - -class CV_EXPORTS_W Subdiv2D -{ -public: - /** Subdiv2D point location cases */ - enum { PTLOC_ERROR = -2, //!< Point location error - PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect - PTLOC_INSIDE = 0, //!< Point inside some facet - PTLOC_VERTEX = 1, //!< Point coincides with one of the subdivision vertices - PTLOC_ON_EDGE = 2 //!< Point on some edge - }; - - /** Subdiv2D edge type navigation (see: getEdge()) */ - enum { NEXT_AROUND_ORG = 0x00, - NEXT_AROUND_DST = 0x22, - PREV_AROUND_ORG = 0x11, - PREV_AROUND_DST = 0x33, - NEXT_AROUND_LEFT = 0x13, - NEXT_AROUND_RIGHT = 0x31, - PREV_AROUND_LEFT = 0x20, - PREV_AROUND_RIGHT = 0x02 - }; - - /** creates an empty Subdiv2D object. - To create a new empty Delaunay subdivision you need to use the #initDelaunay function. - */ - CV_WRAP Subdiv2D(); - - /** @overload - - @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. - - The function creates an empty Delaunay subdivision where 2D points can be added using the function - insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime - error is raised. - */ - CV_WRAP Subdiv2D(Rect rect); - - /** @brief Creates a new empty Delaunay subdivision - - @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. - - */ - CV_WRAP void initDelaunay(Rect rect); - - /** @brief Insert a single point into a Delaunay triangulation. - - @param pt Point to insert. - - The function inserts a single point into a subdivision and modifies the subdivision topology - appropriately. If a point with the same coordinates exists already, no new point is added. - @returns the ID of the point. - - @note If the point is outside of the triangulation specified rect a runtime error is raised. - */ - CV_WRAP int insert(Point2f pt); - - /** @brief Insert multiple points into a Delaunay triangulation. - - @param ptvec Points to insert. - - The function inserts a vector of points into a subdivision and modifies the subdivision topology - appropriately. - */ - CV_WRAP void insert(const std::vector& ptvec); - - /** @brief Returns the location of a point within a Delaunay triangulation. - - @param pt Point to locate. - @param edge Output edge that the point belongs to or is located to the right of it. - @param vertex Optional output vertex the input point coincides with. - - The function locates the input point within the subdivision and gives one of the triangle edges - or vertices. - - @returns an integer which specify one of the following five cases for point location: - - The point falls into some facet. The function returns #PTLOC_INSIDE and edge will contain one of - edges of the facet. - - The point falls onto the edge. The function returns #PTLOC_ON_EDGE and edge will contain this edge. - - The point coincides with one of the subdivision vertices. The function returns #PTLOC_VERTEX and - vertex will contain a pointer to the vertex. - - The point is outside the subdivision reference rectangle. The function returns #PTLOC_OUTSIDE_RECT - and no pointers are filled. - - One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error - processing mode is selected, #PTLOC_ERROR is returned. - */ - CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); - - /** @brief Finds the subdivision vertex closest to the given point. - - @param pt Input point. - @param nearestPt Output subdivision vertex point. - - The function is another function that locates the input point within the subdivision. It finds the - subdivision vertex that is the closest to the input point. It is not necessarily one of vertices - of the facet containing the input point, though the facet (located using locate() ) is used as a - starting point. - - @returns vertex ID. - */ - CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); - - /** @brief Returns a list of all edges. - - @param edgeList Output vector. - - The function gives each edge as a 4 numbers vector, where each two are one of the edge - vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3]. - */ - CV_WRAP void getEdgeList(CV_OUT std::vector& edgeList) const; - - /** @brief Returns a list of the leading edge ID connected to each triangle. - - @param leadingEdgeList Output vector. - - The function gives one edge ID for each triangle. - */ - CV_WRAP void getLeadingEdgeList(CV_OUT std::vector& leadingEdgeList) const; - - /** @brief Returns a list of all triangles. - - @param triangleList Output vector. - - The function gives each triangle as a 6 numbers vector, where each two are one of the triangle - vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5]. - */ - CV_WRAP void getTriangleList(CV_OUT std::vector& triangleList) const; - - /** @brief Returns a list of all Voronoi facets. - - @param idx Vector of vertices IDs to consider. For all vertices you can pass empty vector. - @param facetList Output vector of the Voronoi facets. - @param facetCenters Output vector of the Voronoi facets center points. - - */ - CV_WRAP void getVoronoiFacetList(const std::vector& idx, CV_OUT std::vector >& facetList, - CV_OUT std::vector& facetCenters); - - /** @brief Returns vertex location from vertex ID. - - @param vertex vertex ID. - @param firstEdge Optional. The first edge ID which is connected to the vertex. - @returns vertex (x,y) - - */ - CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; - - /** @brief Returns one of the edges related to the given edge. - - @param edge Subdivision edge ID. - @param nextEdgeType Parameter specifying which of the related edges to return. - The following values are possible: - - NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge) - - NEXT_AROUND_DST next around the edge vertex ( eDnext ) - - PREV_AROUND_ORG previous around the edge origin (reversed eRnext ) - - PREV_AROUND_DST previous around the edge destination (reversed eLnext ) - - NEXT_AROUND_LEFT next around the left facet ( eLnext ) - - NEXT_AROUND_RIGHT next around the right facet ( eRnext ) - - PREV_AROUND_LEFT previous around the left facet (reversed eOnext ) - - PREV_AROUND_RIGHT previous around the right facet (reversed eDnext ) - - ![sample output](pics/quadedge.png) - - @returns edge ID related to the input edge. - */ - CV_WRAP int getEdge( int edge, int nextEdgeType ) const; - - /** @brief Returns next edge around the edge origin. - - @param edge Subdivision edge ID. - - @returns an integer which is next edge ID around the edge origin: eOnext on the - picture above if e is the input edge). - */ - CV_WRAP int nextEdge(int edge) const; - - /** @brief Returns another edge of the same quad-edge. - - @param edge Subdivision edge ID. - @param rotate Parameter specifying which of the edges of the same quad-edge as the input - one to return. The following values are possible: - - 0 - the input edge ( e on the picture below if e is the input edge) - - 1 - the rotated edge ( eRot ) - - 2 - the reversed edge (reversed e (in green)) - - 3 - the reversed rotated edge (reversed eRot (in green)) - - @returns one of the edges ID of the same quad-edge as the input edge. - */ - CV_WRAP int rotateEdge(int edge, int rotate) const; - CV_WRAP int symEdge(int edge) const; - - /** @brief Returns the edge origin. - - @param edge Subdivision edge ID. - @param orgpt Output vertex location. - - @returns vertex ID. - */ - CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; - - /** @brief Returns the edge destination. - - @param edge Subdivision edge ID. - @param dstpt Output vertex location. - - @returns vertex ID. - */ - CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; - -protected: - int newEdge(); - void deleteEdge(int edge); - int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); - void deletePoint(int vtx); - void setEdgePoints( int edge, int orgPt, int dstPt ); - void splice( int edgeA, int edgeB ); - int connectEdges( int edgeA, int edgeB ); - void swapEdges( int edge ); - int isRightOf(Point2f pt, int edge) const; - void calcVoronoi(); - void clearVoronoi(); - void checkSubdiv() const; - - struct CV_EXPORTS Vertex - { - Vertex(); - Vertex(Point2f pt, bool isvirtual, int firstEdge=0); - bool isvirtual() const; - bool isfree() const; - - int firstEdge; - int type; - Point2f pt; - }; - - struct CV_EXPORTS QuadEdge - { - QuadEdge(); - QuadEdge(int edgeidx); - bool isfree() const; - - int next[4]; - int pt[4]; - }; - - //! All of the vertices - std::vector vtx; - //! All of the edges - std::vector qedges; - int freeQEdge; - int freePoint; - bool validGeometry; - - int recentEdge; - //! Top left corner of the bounding rect - Point2f topLeft; - //! Bottom right corner of the bounding rect - Point2f bottomRight; -}; - -//! @} imgproc_subdiv2d - -//! @addtogroup imgproc_feature -//! @{ - -/** @example samples/cpp/lsd_lines.cpp -An example using the LineSegmentDetector -\image html building_lsd.png "Sample output image" width=434 height=300 -*/ - -/** @brief Line segment detector class - -following the algorithm described at @cite Rafael12 . - -@note Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict. -restored again after [Computation of a NFA](https://github.com/rafael-grompone-von-gioi/binomial_nfa) code published under the MIT license. -*/ -class CV_EXPORTS_W LineSegmentDetector : public Algorithm -{ -public: - - /** @brief Finds lines in the input image. - - This is the output of the default parameters of the algorithm on the above shown image. - - ![image](pics/building_lsd.png) - - @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: - `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);` - @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where - Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly - oriented depending on the gradient. - @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. - @param prec Vector of precisions with which the lines are found. - @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The - bigger the value, logarithmically better the detection. - - -1 corresponds to 10 mean false alarms - - 0 corresponds to 1 mean false alarm - - 1 corresponds to 0.1 mean false alarms - This vector will be calculated only when the objects type is #LSD_REFINE_ADV. - */ - CV_WRAP virtual void detect(InputArray image, OutputArray lines, - OutputArray width = noArray(), OutputArray prec = noArray(), - OutputArray nfa = noArray()) = 0; - - /** @brief Draws the line segments on a given image. - @param image The image, where the lines will be drawn. Should be bigger or equal to the image, - where the lines were found. - @param lines A vector of the lines that needed to be drawn. - */ - CV_WRAP virtual void drawSegments(InputOutputArray image, InputArray lines) = 0; - - /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. - - @param size The size of the image, where lines1 and lines2 were found. - @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. - @param lines2 The second group of lines. They visualized in red color. - @param image Optional image, where the lines will be drawn. The image should be color(3-channel) - in order for lines1 and lines2 to be drawn in the above mentioned colors. - */ - CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray image = noArray()) = 0; - - virtual ~LineSegmentDetector() { } -}; - -/** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it. - -The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want -to edit those, as to tailor it for their own application. - -@param refine The way found lines will be refined, see #LineSegmentDetectorModes -@param scale The scale of the image that will be used to find the lines. Range (0..1]. -@param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. -@param quant Bound to the quantization error on the gradient norm. -@param ang_th Gradient angle tolerance in degrees. -@param log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advance refinement is chosen. -@param density_th Minimal density of aligned region points in the enclosing rectangle. -@param n_bins Number of bins in pseudo-ordering of gradient modulus. - */ -CV_EXPORTS_W Ptr createLineSegmentDetector( - int refine = LSD_REFINE_STD, double scale = 0.8, - double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, - double log_eps = 0, double density_th = 0.7, int n_bins = 1024); - -//! @} imgproc_feature - -//! @addtogroup imgproc_filter -//! @{ - -/** @brief Returns Gaussian filter coefficients. - -The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter -coefficients: - -\f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f] - -where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$. - -Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize -smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. -You may also use the higher-level GaussianBlur. -@param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive. -@param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as -`sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. -@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . -@sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur - */ -CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); - -/** @brief Returns filter coefficients for computing spatial image derivatives. - -The function computes and returns the filter coefficients for spatial image derivatives. When -`ksize=FILTER_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel -kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to - -@param kx Output matrix of row filter coefficients. It has the type ktype . -@param ky Output matrix of column filter coefficients. It has the type ktype . -@param dx Derivative order in respect of x. -@param dy Derivative order in respect of y. -@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. -@param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. -Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are -going to filter floating-point images, you are likely to use the normalized kernels. But if you -compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve -all the fractional bits, you may want to set normalize=false . -@param ktype Type of filter coefficients. It can be CV_32f or CV_64F . - */ -CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, - int dx, int dy, int ksize, - bool normalize = false, int ktype = CV_32F ); - -/** @brief Returns Gabor filter coefficients. - -For more details about gabor filter equations and parameters, see: [Gabor -Filter](http://en.wikipedia.org/wiki/Gabor_filter). - -@param ksize Size of the filter returned. -@param sigma Standard deviation of the gaussian envelope. -@param theta Orientation of the normal to the parallel stripes of a Gabor function. -@param lambd Wavelength of the sinusoidal factor. -@param gamma Spatial aspect ratio. -@param psi Phase offset. -@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . - */ -CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, - double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); - -//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. -static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } - -/** @brief Returns a structuring element of the specified size and shape for morphological operations. - -The function constructs and returns the structuring element that can be further passed to #erode, -#dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as -the structuring element. - -@param shape Element shape that could be one of #MorphShapes -@param ksize Size of the structuring element. -@param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the -anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor -position. In other cases the anchor just regulates how much the result of the morphological -operation is shifted. - */ -CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); - -/** @example samples/cpp/tutorial_code/ImgProc/Smoothing/Smoothing.cpp -Sample code for simple filters -![Sample screenshot](Smoothing_Tutorial_Result_Median_Filter.jpg) -Check @ref tutorial_gausian_median_blur_bilateral_filter "the corresponding tutorial" for more details - */ - -/** @brief Blurs an image using the median filter. - -The function smoothes an image using the median filter with the \f$\texttt{ksize} \times -\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. -In-place operation is supported. - -@note The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes - -@param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be -CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. -@param dst destination array of the same size and type as src. -@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... -@sa bilateralFilter, blur, boxFilter, GaussianBlur - */ -CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); - -/** @brief Blurs an image using a Gaussian filter. - -The function convolves the source image with the specified Gaussian kernel. In-place filtering is -supported. - -@param src input image; the image can have any number of channels, which are processed -independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be -positive and odd. Or, they can be zero's and then they are computed from sigma. -@param sigmaX Gaussian kernel standard deviation in X direction. -@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be -equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, -respectively (see #getGaussianKernel for details); to fully control the result regardless of -possible future modifications of all this semantics, it is recommended to specify all of ksize, -sigmaX, and sigmaY. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param hint Implementation modfication flags. See #AlgorithmHint - -@sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur - */ -CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, - double sigmaX, double sigmaY = 0, - int borderType = BORDER_DEFAULT, - AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); - -/** @brief Applies the bilateral filter to an image. - -The function applies bilateral filtering to the input image, as described in -http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html -bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is -very slow compared to most filters. - -_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< -10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very -strong effect, making the image look "cartoonish". - -_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time -applications, and perhaps d=9 for offline applications that need heavy noise filtering. - -This filter does not work inplace. -@param src Source 8-bit or floating-point, 1-channel or 3-channel image. -@param dst Destination image of the same size and type as src . -@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, -it is computed from sigmaSpace. -@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that -farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting -in larger areas of semi-equal color. -@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that -farther pixels will influence each other as long as their colors are close enough (see sigmaColor -). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is -proportional to sigmaSpace. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes - */ -CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, - double sigmaColor, double sigmaSpace, - int borderType = BORDER_DEFAULT ); - -/** @brief Blurs an image using the box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] - -where - -\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\f] - -Unnormalized box filter is useful for computing various integral characteristics over each pixel -neighborhood, such as covariance matrices of image derivatives (used in dense optical flow -algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. - -@param src input image. -@param dst output image of the same size and type as src. -@param ddepth the output image depth (-1 to use src.depth()). -@param ksize blurring kernel size. -@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel -center. -@param normalize flag, specifying whether the kernel is normalized by its area or not. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. -@sa blur, bilateralFilter, GaussianBlur, medianBlur, integral - */ -CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, - Size ksize, Point anchor = Point(-1,-1), - bool normalize = true, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter. - -For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring -pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$. - -The unnormalized square box filter can be useful in computing local image statistics such as the local -variance and standard deviation around the neighborhood of a pixel. - -@param src input image -@param dst output image of the same size and type as src -@param ddepth the output image depth (-1 to use src.depth()) -@param ksize kernel size -@param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel -center. -@param normalize flag, specifying whether the kernel is to be normalized by it's area or not. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. -@sa boxFilter -*/ -CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth, - Size ksize, Point anchor = Point(-1, -1), - bool normalize = true, - int borderType = BORDER_DEFAULT ); - -/** @brief Blurs an image using the normalized box filter. - -The function smooths an image using the kernel: - -\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] - -The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize, -anchor, true, borderType)`. - -@param src input image; it can have any number of channels, which are processed independently, but -the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param ksize blurring kernel size. -@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel -center. -@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. -@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur - */ -CV_EXPORTS_W void blur( InputArray src, OutputArray dst, - Size ksize, Point anchor = Point(-1,-1), - int borderType = BORDER_DEFAULT ); - -/** @brief Blurs an image using the stackBlur. - -The function applies and stackBlur to an image. -stackBlur can generate similar results as Gaussian blur, and the time consumption does not increase with the increase of kernel size. -It creates a kind of moving stack of colors whilst scanning through the image. Thereby it just has to add one new block of color to the right side -of the stack and remove the leftmost color. The remaining colors on the topmost layer of the stack are either added on or reduced by one, -depending on if they are on the right or on the left side of the stack. The only supported borderType is BORDER_REPLICATE. -Original paper was proposed by Mario Klingemann, which can be found http://underdestruction.com/2004/02/25/stackblur-2004. - -@param src input image. The number of channels can be arbitrary, but the depth should be one of -CV_8U, CV_16U, CV_16S or CV_32F. -@param dst output image of the same size and type as src. -@param ksize stack-blurring kernel size. The ksize.width and ksize.height can differ but they both must be -positive and odd. -*/ -CV_EXPORTS_W void stackBlur(InputArray src, OutputArray dst, Size ksize); - -/** @brief Convolves an image with the kernel. - -The function applies an arbitrary linear filter to an image. In-place operation is supported. When -the aperture is partially outside the image, the function interpolates outlier pixel values -according to the specified border mode. - -The function does actually compute correlation, not the convolution: - -\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] - -That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip -the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - -anchor.y - 1)`. - -The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or -larger) and the direct algorithm for small kernels. - -@param src input image. -@param dst output image of the same size and the same number of channels as src. -@param ddepth desired depth of the destination image, see @ref filter_depths "combinations" -@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point -matrix; if you want to apply different kernels to different channels, split the image into -separate color planes using split and process them individually. -@param anchor anchor of the kernel that indicates the relative position of a filtered point within -the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor -is at the kernel center. -@param delta optional value added to the filtered pixels before storing them in dst. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa sepFilter2D, dft, matchTemplate - */ -CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, - InputArray kernel, Point anchor = Point(-1,-1), - double delta = 0, int borderType = BORDER_DEFAULT ); - -/** @brief Applies a separable linear filter to an image. - -The function applies a separable linear filter to the image. That is, first, every row of src is -filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D -kernel kernelY. The final result shifted by delta is stored in dst . - -@param src Source image. -@param dst Destination image of the same size and the same number of channels as src . -@param ddepth Destination image depth, see @ref filter_depths "combinations" -@param kernelX Coefficients for filtering each row. -@param kernelY Coefficients for filtering each column. -@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor -is at the kernel center. -@param delta Value added to the filtered results before storing them. -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa filter2D, Sobel, GaussianBlur, boxFilter, blur - */ -CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, - InputArray kernelX, InputArray kernelY, - Point anchor = Point(-1,-1), - double delta = 0, int borderType = BORDER_DEFAULT ); - -/** @example samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp -Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector -![Sample screenshot](Sobel_Derivatives_Tutorial_Result.jpg) -Check @ref tutorial_sobel_derivatives "the corresponding tutorial" for more details -*/ - -/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. - -In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to -calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ -kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first -or the second x- or y- derivatives. - -There is also the special value `ksize = #FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr -filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is - -\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] - -for the x-derivative, or transposed for the y-derivative. - -The function calculates an image derivative by convolving the image with the appropriate kernel: - -\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] - -The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less -resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) -or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first -case corresponds to a kernel of: - -\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] - -The second case corresponds to a kernel of: - -\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] - -@param src input image. -@param dst output image of the same size and the same number of channels as src . -@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of - 8-bit input images it will result in truncated derivatives. -@param dx order of the derivative x. -@param dy order of the derivative y. -@param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see #getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar - */ -CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, - int dx, int dy, int ksize = 3, - double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates the first order image derivative in both x and y using a Sobel operator - -Equivalent to calling: - -@code -Sobel( src, dx, CV_16SC1, 1, 0, 3 ); -Sobel( src, dy, CV_16SC1, 0, 1, 3 ); -@endcode - -@param src input image. -@param dx output image with first-order derivative in x. -@param dy output image with first-order derivative in y. -@param ksize size of Sobel kernel. It must be 3. -@param borderType pixel extrapolation method, see #BorderTypes. - Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. - -@sa Sobel - */ - -CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx, - OutputArray dy, int ksize = 3, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates the first x- or y- image derivative using Scharr operator. - -The function computes the first x- or y- spatial image derivative using the Scharr operator. The -call - -\f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f] - -is equivalent to - -\f[\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\f] - -@param src input image. -@param dst output image of the same size and the same number of channels as src. -@param ddepth output image depth, see @ref filter_depths "combinations" -@param dx order of the derivative x. -@param dy order of the derivative y. -@param scale optional scale factor for the computed derivative values; by default, no scaling is -applied (see #getDerivKernels for details). -@param delta optional delta value that is added to the results prior to storing them in dst. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa cartToPolar - */ -CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, - int dx, int dy, double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT ); - -/** @example samples/cpp/laplace.cpp -An example using Laplace transformations for edge detection -*/ - -/** @brief Calculates the Laplacian of an image. - -The function calculates the Laplacian of the source image by adding up the second x and y -derivatives calculated using the Sobel operator: - -\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] - -This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image -with the following \f$3 \times 3\f$ aperture: - -\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] - -@param src Source image. -@param dst Destination image of the same size and the same number of channels as src . -@param ddepth Desired depth of the destination image, see @ref filter_depths "combinations". -@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for -details. The size must be positive and odd. -@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is -applied. See #getDerivKernels for details. -@param delta Optional delta value that is added to the results prior to storing them in dst . -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@sa Sobel, Scharr - */ -CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, - int ksize = 1, double scale = 1, double delta = 0, - int borderType = BORDER_DEFAULT ); - -//! @} imgproc_filter - -//! @addtogroup imgproc_feature -//! @{ - -/** @example samples/cpp/edge.cpp -This program demonstrates usage of the Canny edge detector - -Check @ref tutorial_canny_detector "the corresponding tutorial" for more details -*/ - -/** @brief Finds edges in an image using the Canny algorithm @cite Canny86 . - -The function finds edges in the input image and marks them in the output map edges using the -Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The -largest value is used to find initial segments of strong edges. See - - -@param image 8-bit input image. -@param edges output edge map; single channels 8-bit image, which has the same size as image . -@param threshold1 first threshold for the hysteresis procedure. -@param threshold2 second threshold for the hysteresis procedure. -@param apertureSize aperture size for the Sobel operator. -@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm -\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( -L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( -L2gradient=false ). - */ -CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, - double threshold1, double threshold2, - int apertureSize = 3, bool L2gradient = false ); - -/** \overload - -Finds edges in an image using the Canny algorithm with custom image gradient. - -@param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). -@param dy 16-bit y derivative of input image (same type as dx). -@param edges output edge map; single channels 8-bit image, which has the same size as image . -@param threshold1 first threshold for the hysteresis procedure. -@param threshold2 second threshold for the hysteresis procedure. -@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm -\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( -L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( -L2gradient=false ). - */ -CV_EXPORTS_W void Canny( InputArray dx, InputArray dy, - OutputArray edges, - double threshold1, double threshold2, - bool L2gradient = false ); - -/** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection. - -The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal -eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms -of the formulae in the cornerEigenValsAndVecs description. - -@param src Input single-channel 8-bit or floating-point image. -@param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as -src . -@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). -@param ksize Aperture parameter for the Sobel operator. -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - */ -CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, - int blockSize, int ksize = 3, - int borderType = BORDER_DEFAULT ); - -/** @brief Harris corner detector. - -The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and -cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance -matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it -computes the following characteristic: - -\f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f] - -Corners in the image can be found as the local maxima of this response map. - -@param src Input single-channel 8-bit or floating-point image. -@param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same -size as src . -@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). -@param ksize Aperture parameter for the Sobel operator. -@param k Harris detector free parameter. See the formula above. -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - */ -CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, - int ksize, double k, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection. - -For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize -neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as: - -\f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f] - -where the derivatives are computed using the Sobel operator. - -After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as -\f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where - -- \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$ -- \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$ -- \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$ - -The output of the function can be used for robust edge or corner detection. - -@param src Input single-channel 8-bit or floating-point image. -@param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . -@param blockSize Neighborhood size (see details below). -@param ksize Aperture parameter for the Sobel operator. -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - -@sa cornerMinEigenVal, cornerHarris, preCornerDetect - */ -CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, - int blockSize, int ksize, - int borderType = BORDER_DEFAULT ); - -/** @brief Calculates a feature map for corner detection. - -The function calculates the complex spatial derivative-based function of the source image - -\f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f] - -where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image -derivatives, and \f$D_{xy}\f$ is the mixed derivative. - -The corners can be found as local maximums of the functions, as shown below: -@code - Mat corners, dilated_corners; - preCornerDetect(image, corners, 3); - // dilation with 3x3 rectangular structuring element - dilate(corners, dilated_corners, Mat(), 1); - Mat corner_mask = corners == dilated_corners; -@endcode - -@param src Source single-channel 8-bit of floating-point image. -@param dst Output image that has the type CV_32F and the same size as src . -@param ksize %Aperture size of the Sobel . -@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. - */ -CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, - int borderType = BORDER_DEFAULT ); - -/** @brief Refines the corner locations. - -The function iterates to find the sub-pixel accurate location of corners or radial saddle -points as described in @cite forstner1987fast, and as shown on the figure below. - -![image](pics/cornersubpix.png) - -Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$ -to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$ -subject to image and measurement noise. Consider the expression: - -\f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f] - -where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The -value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up -with \f$\epsilon_i\f$ set to zero: - -\f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) \cdot q - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f] - -where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first -gradient term \f$G\f$ and the second gradient term \f$b\f$ gives: - -\f[q = G^{-1} \cdot b\f] - -The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates -until the center stays within a set threshold. - -@param image Input single-channel, 8-bit or float image. -@param corners Initial coordinates of the input corners and refined coordinates provided for -output. -@param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , -then a \f$(5*2+1) \times (5*2+1) = 11 \times 11\f$ search window is used. -@param zeroZone Half of the size of the dead region in the middle of the search zone over which -the summation in the formula below is not done. It is used sometimes to avoid possible -singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such -a size. -@param criteria Criteria for termination of the iterative process of corner refinement. That is, -the process of corner position refinement stops either after criteria.maxCount iterations or when -the corner position moves by less than criteria.epsilon on some iteration. - */ -CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, - Size winSize, Size zeroZone, - TermCriteria criteria ); - -/** @brief Determines strong corners on an image. - -The function finds the most prominent corners in the image or in the specified image region, as -described in @cite Shi94 - -- Function calculates the corner quality measure at every source image pixel using the - #cornerMinEigenVal or #cornerHarris . -- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are - retained). -- The corners with the minimal eigenvalue less than - \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. -- The remaining corners are sorted by the quality measure in the descending order. -- Function throws away each corner for which there is a stronger corner at a distance less than - maxDistance. - -The function can be used to initialize a point-based tracker of an object. - -@note If the function is called with different values A and B of the parameter qualityLevel , and -A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector -with qualityLevel=B . - -@param image Input 8-bit or floating-point 32-bit, single-channel image. -@param corners Output vector of detected corners. -@param maxCorners Maximum number of corners to return. If there are more corners than are found, -the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set -and all detected corners are returned. -@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The -parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue -(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the -quality measure less than the product are rejected. For example, if the best corner has the -quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure -less than 15 are rejected. -@param minDistance Minimum possible Euclidean distance between the returned corners. -@param mask Optional region of interest. If the image is not empty (it needs to have the type -CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. -@param blockSize Size of an average block for computing a derivative covariation matrix over each -pixel neighborhood. See cornerEigenValsAndVecs . -@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) -or #cornerMinEigenVal. -@param k Free parameter of the Harris detector. - -@sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, - */ - -CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, - int maxCorners, double qualityLevel, double minDistance, - InputArray mask = noArray(), int blockSize = 3, - bool useHarrisDetector = false, double k = 0.04 ); - -CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, - int maxCorners, double qualityLevel, double minDistance, - InputArray mask, int blockSize, - int gradientSize, bool useHarrisDetector = false, - double k = 0.04 ); - -/** @brief Same as above, but returns also quality measure of the detected corners. - -@param image Input 8-bit or floating-point 32-bit, single-channel image. -@param corners Output vector of detected corners. -@param maxCorners Maximum number of corners to return. If there are more corners than are found, -the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set -and all detected corners are returned. -@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The -parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue -(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the -quality measure less than the product are rejected. For example, if the best corner has the -quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure -less than 15 are rejected. -@param minDistance Minimum possible Euclidean distance between the returned corners. -@param mask Region of interest. If the image is not empty (it needs to have the type -CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. -@param cornersQuality Output vector of quality measure of the detected corners. -@param blockSize Size of an average block for computing a derivative covariation matrix over each -pixel neighborhood. See cornerEigenValsAndVecs . -@param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. -See cornerEigenValsAndVecs . -@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) -or #cornerMinEigenVal. -@param k Free parameter of the Harris detector. - */ -CV_EXPORTS CV_WRAP_AS(goodFeaturesToTrackWithQuality) void goodFeaturesToTrack( - InputArray image, OutputArray corners, - int maxCorners, double qualityLevel, double minDistance, - InputArray mask, OutputArray cornersQuality, int blockSize = 3, - int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04); - -/** @example samples/cpp/tutorial_code/ImgTrans/houghlines.cpp -An example using the Hough line detector -![Sample input image](Hough_Lines_Tutorial_Original_Image.jpg) ![Output image](Hough_Lines_Tutorial_Result.jpg) -*/ - -/** @brief Finds lines in a binary image using the standard Hough transform. - -The function implements the standard or standard multi-scale Hough transform algorithm for line -detection. See for a good explanation of Hough -transform. - -@param image 8-bit, single-channel binary source image. The image may be modified by the function. -@param lines Output vector of lines. Each line is represented by a 2 or 3 element vector -\f$(\rho, \theta)\f$ or \f$(\rho, \theta, \textrm{votes})\f$, where \f$\rho\f$ is the distance from -the coordinate origin \f$(0,0)\f$ (top-left corner of the image), \f$\theta\f$ is the line rotation -angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ), and -\f$\textrm{votes}\f$ is the value of accumulator. -@param rho Distance resolution of the accumulator in pixels. -@param theta Angle resolution of the accumulator in radians. -@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough -votes ( \f$>\texttt{threshold}\f$ ). -@param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. -The coarse accumulator distance resolution is rho and the accurate accumulator resolution is -rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these -parameters should be positive. -@param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. -@param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. -Must fall between 0 and max_theta. -@param max_theta For standard and multi-scale Hough transform, an upper bound for the angle. -Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly -less than max_theta, depending on the parameters min_theta and theta. -@param use_edgeval True if you want to use weighted Hough transform. - */ -CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, - double rho, double theta, int threshold, - double srn = 0, double stn = 0, - double min_theta = 0, double max_theta = CV_PI, - bool use_edgeval = false ); - -/** @brief Finds line segments in a binary image using the probabilistic Hough transform. - -The function implements the probabilistic Hough transform algorithm for line detection, described -in @cite Matas00 - -See the line detection example below: -@include snippets/imgproc_HoughLinesP.cpp -This is a sample picture the function parameters have been tuned for: - -![image](pics/building.jpg) - -And this is the output of the above program in case of the probabilistic Hough transform: - -![image](pics/houghp.png) - -@param image 8-bit, single-channel binary source image. The image may be modified by the function. -@param lines Output vector of lines. Each line is represented by a 4-element vector -\f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected -line segment. -@param rho Distance resolution of the accumulator in pixels. -@param theta Angle resolution of the accumulator in radians. -@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough -votes ( \f$>\texttt{threshold}\f$ ). -@param minLineLength Minimum line length. Line segments shorter than that are rejected. -@param maxLineGap Maximum allowed gap between points on the same line to link them. - -@sa LineSegmentDetector - */ -CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, - double rho, double theta, int threshold, - double minLineLength = 0, double maxLineGap = 0 ); - -/** @brief Finds lines in a set of points using the standard Hough transform. - -The function finds lines in a set of points using a modification of the Hough transform. -@include snippets/imgproc_HoughLinesPointSet.cpp -@param point Input vector of points. Each vector must be encoded as a Point vector \f$(x,y)\f$. Type must be CV_32FC2 or CV_32SC2. -@param lines Output vector of found lines. Each vector is encoded as a vector \f$(votes, rho, theta)\f$. -The larger the value of 'votes', the higher the reliability of the Hough line. -@param lines_max Max count of Hough lines. -@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough -votes ( \f$>\texttt{threshold}\f$ ). -@param min_rho Minimum value for \f$\rho\f$ for the accumulator (Note: \f$\rho\f$ can be negative. The absolute value \f$|\rho|\f$ is the distance of a line to the origin.). -@param max_rho Maximum value for \f$\rho\f$ for the accumulator. -@param rho_step Distance resolution of the accumulator. -@param min_theta Minimum angle value of the accumulator in radians. -@param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum -angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step. -@param theta_step Angle resolution of the accumulator in radians. - */ -CV_EXPORTS_W void HoughLinesPointSet( InputArray point, OutputArray lines, int lines_max, int threshold, - double min_rho, double max_rho, double rho_step, - double min_theta, double max_theta, double theta_step ); - -/** @example samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp -An example using the Hough circle detector -*/ - -/** @brief Finds circles in a grayscale image using the Hough transform. - -The function finds circles in a grayscale image using a modification of the Hough transform. - -Example: : -@include snippets/imgproc_HoughLinesCircles.cpp - -@note Usually the function detects the centers of circles well. However, it may fail to find correct -radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if -you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number -to return centers only without radius search, and find the correct radius using an additional procedure. - -It also helps to smooth image a bit unless it's already soft. For example, -GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. - -@param image 8-bit, single-channel, grayscale input image. -@param circles Output vector of found circles. Each vector is encoded as 3 or 4 element -floating-point vector \f$(x, y, radius)\f$ or \f$(x, y, radius, votes)\f$ . -@param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. -@param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if -dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has -half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, -unless some small very circles need to be detected. -@param minDist Minimum distance between the centers of the detected circles. If the parameter is -too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is -too large, some circles may be missed. -@param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, -it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). -Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value -should normally be higher, such as 300 or normally exposed and contrasty images. -@param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the -accumulator threshold for the circle centers at the detection stage. The smaller it is, the more -false circles may be detected. Circles, corresponding to the larger accumulator values, will be -returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. -The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. -If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. -But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. -@param minRadius Minimum circle radius. -@param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, #HOUGH_GRADIENT returns -centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. - -@sa fitEllipse, minEnclosingCircle - */ -CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, - int method, double dp, double minDist, - double param1 = 100, double param2 = 100, - int minRadius = 0, int maxRadius = 0 ); - -//! @} imgproc_feature - -//! @addtogroup imgproc_filter -//! @{ - -/** @example samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp -Advanced morphology Transformations sample code -![Sample screenshot](Morphology_2_Tutorial_Result.jpg) -Check @ref tutorial_opening_closing_hats "the corresponding tutorial" for more details -*/ - -/** @brief Erodes an image by using a specific structuring element. - -The function erodes the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the minimum is taken: - -\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In -case of multi-channel images, each channel is processed independently. - -@param src input image; the number of channels can be arbitrary, but the depth should be one of -CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular -structuring element is used. Kernel can be created using #getStructuringElement. -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times erosion is applied. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param borderValue border value in case of a constant border -@sa dilate, morphologyEx, getStructuringElement - */ -CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, - Point anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue() ); - -/** @example samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp -Erosion and Dilation sample code -![Sample Screenshot-Erosion](Morphology_1_Tutorial_Erosion_Result.jpg)![Sample Screenshot-Dilation](Morphology_1_Tutorial_Dilation_Result.jpg) -Check @ref tutorial_erosion_dilatation "the corresponding tutorial" for more details -*/ - -/** @brief Dilates an image by using a specific structuring element. - -The function dilates the source image using the specified structuring element that determines the -shape of a pixel neighborhood over which the maximum is taken: -\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] - -The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In -case of multi-channel images, each channel is processed independently. - -@param src input image; the number of channels can be arbitrary, but the depth should be one of -CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst output image of the same size and type as src. -@param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular -structuring element is used. Kernel can be created using #getStructuringElement -@param anchor position of the anchor within the element; default value (-1, -1) means that the -anchor is at the element center. -@param iterations number of times dilation is applied. -@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. -@param borderValue border value in case of a constant border -@sa erode, morphologyEx, getStructuringElement - */ -CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, - Point anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue() ); - -/** @brief Performs advanced morphological transformations. - -The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as -basic operations. - -Any of the operations can be done in-place. In case of multi-channel images, each channel is -processed independently. - -@param src Source image. The number of channels can be arbitrary. The depth should be one of -CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. -@param dst Destination image of the same size and type as source image. -@param op Type of a morphological operation, see #MorphTypes -@param kernel Structuring element. It can be created using #getStructuringElement. -@param anchor Anchor position with the kernel. Negative values mean that the anchor is at the -kernel center. -@param iterations Number of times erosion and dilation are applied. -@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. -@param borderValue Border value in case of a constant border. The default value has a special -meaning. -@sa dilate, erode, getStructuringElement -@note The number of iterations is the number of times erosion or dilatation operation will be applied. -For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply -successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). - */ -CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, - int op, InputArray kernel, - Point anchor = Point(-1,-1), int iterations = 1, - int borderType = BORDER_CONSTANT, - const Scalar& borderValue = morphologyDefaultBorderValue() ); - -//! @} imgproc_filter - -//! @addtogroup imgproc_transform -//! @{ - -/** @brief Resizes an image. - -The function resize resizes the image src down to or up to the specified size. Note that the -initial dst type or size are not taken into account. Instead, the size and type are derived from -the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst, -you may call the function as follows: -@code - // explicitly specify dsize=dst.size(); fx and fy will be computed from that. - resize(src, dst, dst.size(), 0, 0, interpolation); -@endcode -If you want to decimate the image by factor of 2 in each direction, you can call the function this -way: -@code - // specify fx and fy and let the function compute the destination image size. - resize(src, dst, Size(), 0.5, 0.5, interpolation); -@endcode -To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to -enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR -(faster but still looks OK). - -@param src input image. -@param dst output image; it has the size dsize (when it is non-zero) or the size computed from -src.size(), fx, and fy; the type of dst is the same as of src. -@param dsize output image size; if it equals zero (`None` in Python), it is computed as: - \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] - Either dsize or both fx and fy must be non-zero. -@param fx scale factor along the horizontal axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.width/src.cols}\f] -@param fy scale factor along the vertical axis; when it equals 0, it is computed as -\f[\texttt{(double)dsize.height/src.rows}\f] -@param interpolation interpolation method, see #InterpolationFlags - -@sa warpAffine, warpPerspective, remap - */ -CV_EXPORTS_W void resize( InputArray src, OutputArray dst, - Size dsize, double fx = 0, double fy = 0, - int interpolation = INTER_LINEAR ); - -/** @brief Applies an affine transformation to an image. - -The function warpAffine transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted -with #invertAffineTransform and then put in the formula above instead of M. The function cannot -operate in-place. - -@param src input image. -@param dst output image that has the size dsize and the same type as src . -@param M \f$2\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (see #InterpolationFlags) and the optional -flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (see #BorderTypes); when -borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to -the "outliers" in the source image are not modified by the function. -@param borderValue value used in case of a constant border; by default, it is 0. - -@sa warpPerspective, resize, remap, getRectSubPix, transform - */ -CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, - InputArray M, Size dsize, - int flags = INTER_LINEAR, - int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @example samples/cpp/warpPerspective_demo.cpp -An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping -*/ - -/** @brief Applies a perspective transformation to an image. - -The function warpPerspective transforms the source image using the specified matrix: - -\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , - \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] - -when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert -and then put in the formula above instead of M. The function cannot operate in-place. - -@param src input image. -@param dst output image that has the size dsize and the same type as src . -@param M \f$3\times 3\f$ transformation matrix. -@param dsize size of the output image. -@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the -optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( -\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). -@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). -@param borderValue value used in case of a constant border; by default, it equals 0. - -@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform - */ -CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, - InputArray M, Size dsize, - int flags = INTER_LINEAR, - int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @brief Applies a generic geometrical transformation to an image. - -The function remap transforms the source image using the specified map: - -\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] - -with the WARP_RELATIVE_MAP flag : - -\f[\texttt{dst} (x,y) = \texttt{src} (x+map_x(x,y),y+map_y(x,y))\f] - -where values of pixels with non-integer coordinates are computed using one of available -interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps -in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in -\f$map_1\f$, or fixed-point maps created by using #convertMaps. The reason you might want to -convert from floating to fixed-point representations of a map is that they can yield much faster -(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), -cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. - -This function cannot operate in-place. - -@param src Source image. -@param dst Destination image. It has the same size as map1 and the same type as src . -@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , -CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point -representation to fixed-point for speed. -@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map -if map1 is (x,y) points), respectively. -@param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA -#INTER_LINEAR_EXACT and #INTER_NEAREST_EXACT are not supported by this function. -The extra flag WARP_RELATIVE_MAP can be ORed to the interpolation method -(e.g. INTER_LINEAR | WARP_RELATIVE_MAP) -@param borderMode Pixel extrapolation method (see #BorderTypes). When -borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that -corresponds to the "outliers" in the source image are not modified by the function. -@param borderValue Value used in case of a constant border. By default, it is 0. -@note -Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - */ -CV_EXPORTS_W void remap( InputArray src, OutputArray dst, - InputArray map1, InputArray map2, - int interpolation, int borderMode = BORDER_CONSTANT, - const Scalar& borderValue = Scalar()); - -/** @brief Converts image transformation maps from one representation to another. - -The function converts a pair of maps for remap from one representation to another. The following -options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are -supported: - -- \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the -most frequently used conversion operation, in which the original floating-point maps (see #remap) -are converted to a more compact and much faster fixed-point representation. The first output array -contains the rounded coordinates and the second array (created only when nninterpolation=false ) -contains indices in the interpolation tables. - -- \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but -the original maps are stored in one 2-channel matrix. - -- Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same -as the originals. - -@param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . -@param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), -respectively. -@param dstmap1 The first output map that has the type dstmap1type and the same size as src . -@param dstmap2 The second output map. -@param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or -CV_32FC2 . -@param nninterpolation Flag indicating whether the fixed-point maps are used for the -nearest-neighbor or for a more complex interpolation. - -@sa remap, undistort, initUndistortRectifyMap - */ -CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, - OutputArray dstmap1, OutputArray dstmap2, - int dstmap1type, bool nninterpolation = false ); - -/** @brief Calculates an affine matrix of 2D rotation. - -The function calculates the following matrix: - -\f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f] - -where - -\f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f] - -The transformation maps the rotation center to itself. If this is not the target, adjust the shift. - -@param center Center of the rotation in the source image. -@param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the -coordinate origin is assumed to be the top-left corner). -@param scale Isotropic scale factor. - -@sa getAffineTransform, warpAffine, transform - */ -CV_EXPORTS_W Mat getRotationMatrix2D(Point2f center, double angle, double scale); - -/** @sa getRotationMatrix2D */ -CV_EXPORTS Matx23d getRotationMatrix2D_(Point2f center, double angle, double scale); - -inline -Mat getRotationMatrix2D(Point2f center, double angle, double scale) -{ - return Mat(getRotationMatrix2D_(center, angle, scale), true); -} - -/** @brief Calculates an affine transform from three pairs of the corresponding points. - -The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that: - -\f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] - -where - -\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f] - -@param src Coordinates of triangle vertices in the source image. -@param dst Coordinates of the corresponding triangle vertices in the destination image. - -@sa warpAffine, transform - */ -CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); - -/** @brief Inverts an affine transformation. - -The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M: - -\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f] - -The result is also a \f$2 \times 3\f$ matrix of the same type as M. - -@param M Original affine transformation. -@param iM Output reverse affine transformation. - */ -CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); - -/** @brief Calculates a perspective transform from four pairs of the corresponding points. - -The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that: - -\f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] - -where - -\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f] - -@param src Coordinates of quadrangle vertices in the source image. -@param dst Coordinates of the corresponding quadrangle vertices in the destination image. -@param solveMethod method passed to cv::solve (#DecompTypes) - -@sa findHomography, warpPerspective, perspectiveTransform - */ -CV_EXPORTS_W Mat getPerspectiveTransform(InputArray src, InputArray dst, int solveMethod = DECOMP_LU); - -/** @overload */ -CV_EXPORTS Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod = DECOMP_LU); - - -CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); - -/** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy. - -The function getRectSubPix extracts pixels from src: - -\f[patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f] - -where the values of the pixels at non-integer coordinates are retrieved using bilinear -interpolation. Every channel of multi-channel images is processed independently. Also -the image should be a single channel or three channel image. While the center of the -rectangle must be inside the image, parts of the rectangle may be outside. - -@param image Source image. -@param patchSize Size of the extracted patch. -@param center Floating point coordinates of the center of the extracted rectangle within the -source image. The center must be inside the image. -@param patch Extracted patch that has the size patchSize and the same number of channels as src . -@param patchType Depth of the extracted pixels. By default, they have the same depth as src . - -@sa warpAffine, warpPerspective - */ -CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, - Point2f center, OutputArray patch, int patchType = -1 ); - -/** @example samples/cpp/polar_transforms.cpp -An example using the cv::linearPolar and cv::logPolar operations -*/ - -/** @brief Remaps an image to semilog-polar coordinates space. - -@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG); - -@internal -Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image d)"): -\f[\begin{array}{l} - dst( \rho , \phi ) = src(x,y) \\ - dst.size() \leftarrow src.size() -\end{array}\f] - -where -\f[\begin{array}{l} - I = (dx,dy) = (x - center.x,y - center.y) \\ - \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ - \phi = Kangle \cdot \texttt{angle} (I) \\ -\end{array}\f] - -and -\f[\begin{array}{l} - M = src.cols / log_e(maxRadius) \\ - Kangle = src.rows / 2\Pi \\ -\end{array}\f] - -The function emulates the human "foveal" vision and can be used for fast scale and -rotation-invariant template matching, for object tracking and so forth. -@param src Source image -@param dst Destination image. It will have same size and type as src. -@param center The transformation center; where the output precision is maximal -@param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. -@param flags A combination of interpolation methods, see #InterpolationFlags - -@note -- The function can not operate in-place. -- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - -@sa cv::linearPolar -@endinternal -*/ -CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, - Point2f center, double M, int flags ); - -/** @brief Remaps an image to polar coordinates space. - -@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags) - -@internal -Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image c)"): -\f[\begin{array}{l} - dst( \rho , \phi ) = src(x,y) \\ - dst.size() \leftarrow src.size() -\end{array}\f] - -where -\f[\begin{array}{l} - I = (dx,dy) = (x - center.x,y - center.y) \\ - \rho = Kmag \cdot \texttt{magnitude} (I) ,\\ - \phi = angle \cdot \texttt{angle} (I) -\end{array}\f] - -and -\f[\begin{array}{l} - Kx = src.cols / maxRadius \\ - Ky = src.rows / 2\Pi -\end{array}\f] - - -@param src Source image -@param dst Destination image. It will have same size and type as src. -@param center The transformation center; -@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. -@param flags A combination of interpolation methods, see #InterpolationFlags - -@note -- The function can not operate in-place. -- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. - -@sa cv::logPolar -@endinternal -*/ -CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, - Point2f center, double maxRadius, int flags ); - - -/** \brief Remaps an image to polar or semilog-polar coordinates space - -@anchor polar_remaps_reference_image -![Polar remaps reference](pics/polar_remap_doc.png) - -Transform the source image using the following transformation: -\f[ -dst(\rho , \phi ) = src(x,y) -\f] - -where -\f[ -\begin{array}{l} -\vec{I} = (x - center.x, \;y - center.y) \\ -\phi = Kangle \cdot \texttt{angle} (\vec{I}) \\ -\rho = \left\{\begin{matrix} -Klin \cdot \texttt{magnitude} (\vec{I}) & default \\ -Klog \cdot log_e(\texttt{magnitude} (\vec{I})) & if \; semilog \\ -\end{matrix}\right. -\end{array} -\f] - -and -\f[ -\begin{array}{l} -Kangle = dsize.height / 2\Pi \\ -Klin = dsize.width / maxRadius \\ -Klog = dsize.width / log_e(maxRadius) \\ -\end{array} -\f] - - -\par Linear vs semilog mapping - -Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to `flags` to specify the polar mapping mode. - -Linear is the default mode. - -The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision) -in contrast to peripheral vision where acuity is minor. - -\par Option on `dsize`: - -- if both values in `dsize <=0 ` (default), -the destination image will have (almost) same area of source bounding circle: -\f[\begin{array}{l} -dsize.area \leftarrow (maxRadius^2 \cdot \Pi) \\ -dsize.width = \texttt{cvRound}(maxRadius) \\ -dsize.height = \texttt{cvRound}(maxRadius \cdot \Pi) \\ -\end{array}\f] - - -- if only `dsize.height <= 0`, -the destination image area will be proportional to the bounding circle area but scaled by `Kx * Kx`: -\f[\begin{array}{l} -dsize.height = \texttt{cvRound}(dsize.width \cdot \Pi) \\ -\end{array} -\f] - -- if both values in `dsize > 0 `, -the destination image will have the given size therefore the area of the bounding circle will be scaled to `dsize`. - - -\par Reverse mapping - -You can get reverse mapping adding #WARP_INVERSE_MAP to `flags` -\snippet polar_transforms.cpp InverseMap - -In addiction, to calculate the original coordinate from a polar mapped coordinate \f$(rho, phi)->(x, y)\f$: -\snippet polar_transforms.cpp InverseCoordinate - -@param src Source image. -@param dst Destination image. It will have same type as src. -@param dsize The destination image size (see description for valid options). -@param center The transformation center. -@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. -@param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode. - - Add #WARP_POLAR_LINEAR to select linear polar mapping (default) - - Add #WARP_POLAR_LOG to select semilog polar mapping - - Add #WARP_INVERSE_MAP for reverse mapping. -@note -- The function can not operate in-place. -- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. -- This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767. - -@sa cv::remap -*/ -CV_EXPORTS_W void warpPolar(InputArray src, OutputArray dst, Size dsize, - Point2f center, double maxRadius, int flags); - - -//! @} imgproc_transform - -//! @addtogroup imgproc_misc -//! @{ - -/** @brief Calculates the integral of an image. - -The function calculates one or more integral images for the source image as follows: - -\f[\texttt{sum} (X,Y) = \sum _{x - -Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed -with getOptimalDFTSize. - -The function performs the following equations: -- First it applies a Hanning window (see ) to each -image to remove possible edge effects. This window is cached until the array size changes to speed -up processing time. -- Next it computes the forward DFTs of each source array: -\f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f] -where \f$\mathcal{F}\f$ is the forward DFT. -- It then computes the cross-power spectrum of each frequency domain array: -\f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f] -- Next the cross-correlation is converted back into the time domain via the inverse DFT: -\f[r = \mathcal{F}^{-1}\{R\}\f] -- Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to -achieve sub-pixel accuracy. -\f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f] -- If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 -centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single -peak) and will be smaller when there are multiple peaks. - -@param src1 Source floating point array (CV_32FC1 or CV_64FC1) -@param src2 Source floating point array (CV_32FC1 or CV_64FC1) -@param window Floating point array with windowing coefficients to reduce edge effects (optional). -@param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). -@returns detected phase shift (sub-pixel) between the two arrays. - -@sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow - */ -CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, - InputArray window = noArray(), CV_OUT double* response = 0); - -/** @brief This function computes a Hanning window coefficients in two dimensions. - -See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) -for more information. - -An example is shown below: -@code - // create hanning window of size 100x100 and type CV_32F - Mat hann; - createHanningWindow(hann, Size(100, 100), CV_32F); -@endcode -@param dst Destination array to place Hann coefficients in -@param winSize The window size specifications (both width and height must be > 1) -@param type Created array type - */ -CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); - -/** @brief Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum. - -The function cv::divSpectrums performs the per-element division of the first array by the second array. -The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform. - -@param a first input array. -@param b second input array of the same size and type as src1 . -@param c output array of the same size and type as src1 . -@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that -each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. -@param conjB optional flag that conjugates the second input array before the multiplication (true) -or not (false). -*/ -CV_EXPORTS_W void divSpectrums(InputArray a, InputArray b, OutputArray c, - int flags, bool conjB = false); - -//! @} imgproc_motion - -//! @addtogroup imgproc_misc -//! @{ - -/** @brief Applies a fixed-level threshold to each array element. - -The function applies fixed-level thresholding to a multiple-channel array. The function is typically -used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for -this purpose) or for removing a noise, that is, filtering out pixels with too small or too large -values. There are several types of thresholding supported by the function. They are determined by -type parameter. - -Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the -above values. In these cases, the function determines the optimal threshold value using the Otsu's -or Triangle algorithm and uses it instead of the specified thresh. - -@note Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images. - -@param src input array (multiple-channel, 8-bit or 32-bit floating point). -@param dst output array of the same size and type and the same number of channels as src. -@param thresh threshold value. -@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding -types. -@param type thresholding type (see #ThresholdTypes). -@return the computed threshold value if Otsu's or Triangle methods used. - -@sa adaptiveThreshold, findContours, compare, min, max - */ -CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, - double thresh, double maxval, int type ); - - -/** @brief Applies an adaptive threshold to an array. - -The function transforms a grayscale image to a binary image according to the formulae: -- **THRESH_BINARY** - \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f] -- **THRESH_BINARY_INV** - \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f] -where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter). - -The function can process the image in-place. - -@param src Source 8-bit single-channel image. -@param dst Destination image of the same size and the same type as src. -@param maxValue Non-zero value assigned to the pixels for which the condition is satisfied -@param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes. -The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries. -@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV, -see #ThresholdTypes. -@param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the -pixel: 3, 5, 7, and so on. -@param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it -is positive but may be zero or negative as well. - -@sa threshold, blur, GaussianBlur - */ -CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, - double maxValue, int adaptiveMethod, - int thresholdType, int blockSize, double C ); - -//! @} imgproc_misc - -//! @addtogroup imgproc_filter -//! @{ - -/** @example samples/cpp/tutorial_code/ImgProc/Pyramids/Pyramids.cpp -An example using pyrDown and pyrUp functions -*/ - -/** @brief Blurs an image and downsamples it. - -By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in -any case, the following conditions should be satisfied: - -\f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f] - -The function performs the downsampling step of the Gaussian pyramid construction. First, it -convolves the source image with the kernel: - -\f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f] - -Then, it downsamples the image by rejecting even rows and columns. - -@param src input image. -@param dst output image; it has the specified size and the same type as src. -@param dstsize size of the output image. -@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) - */ -CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, - const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); - -/** @brief Upsamples an image and then blurs it. - -By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any -case, the following conditions should be satisfied: - -\f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f] - -The function performs the upsampling step of the Gaussian pyramid construction, though it can -actually be used to construct the Laplacian pyramid. First, it upsamples the source image by -injecting even zero rows and columns and then convolves the result with the same kernel as in -pyrDown multiplied by 4. - -@param src input image. -@param dst output image. It has the specified size and the same type as src . -@param dstsize size of the output image. -@param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported) - */ -CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, - const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); - -/** @brief Constructs the Gaussian pyramid for an image. - -The function constructs a vector of images and builds the Gaussian pyramid by recursively applying -pyrDown to the previously built pyramid layers, starting from `dst[0]==src`. - -@param src Source image. Check pyrDown for the list of supported types. -@param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the -same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on. -@param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative. -@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) - */ -CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, - int maxlevel, int borderType = BORDER_DEFAULT ); - -//! @} imgproc_filter - -//! @addtogroup imgproc_hist -//! @{ - -/** @example samples/cpp/demhist.cpp -An example for creating histograms of an image -*/ - -/** @brief Calculates a histogram of a set of arrays. - -The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used -to increment a histogram bin are taken from the corresponding input arrays at the same location. The -sample below shows how to compute a 2D Hue-Saturation histogram for a color image. : -@include snippets/imgproc_calcHist.cpp - -@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same -size. Each of them can have an arbitrary number of channels. -@param nimages Number of source images. -@param channels List of the dims channels used to compute the histogram. The first array channels -are numerated from 0 to images[0].channels()-1 , the second array channels are counted from -images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. -@param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size -as images[i] . The non-zero mask elements mark the array elements counted in the histogram. -@param hist Output histogram, which is a dense or sparse dims -dimensional array. -@param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS -(equal to 32 in the current OpenCV version). -@param histSize Array of histogram sizes in each dimension. -@param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the -histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower -(inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary -\f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a -uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform ( -uniform=false ), then each of ranges[i] contains histSize[i]+1 elements: -\f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$ -. The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not -counted in the histogram. -@param uniform Flag indicating whether the histogram is uniform or not (see above). -@param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning -when it is allocated. This feature enables you to compute a single histogram from several sets of -arrays, or to update the histogram in time. -*/ -CV_EXPORTS void calcHist( const Mat* images, int nimages, - const int* channels, InputArray mask, - OutputArray hist, int dims, const int* histSize, - const float** ranges, bool uniform = true, bool accumulate = false ); - -/** @overload - -this variant uses %SparseMat for output -*/ -CV_EXPORTS void calcHist( const Mat* images, int nimages, - const int* channels, InputArray mask, - SparseMat& hist, int dims, - const int* histSize, const float** ranges, - bool uniform = true, bool accumulate = false ); - -/** @overload - -this variant supports only uniform histograms. - -ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements -(histSize.size() element pairs). The first and second elements of each pair specify the lower and -upper boundaries. -*/ -CV_EXPORTS_W void calcHist( InputArrayOfArrays images, - const std::vector& channels, - InputArray mask, OutputArray hist, - const std::vector& histSize, - const std::vector& ranges, - bool accumulate = false ); - -/** @brief Calculates the back projection of a histogram. - -The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to -#calcHist , at each location (x, y) the function collects the values from the selected channels -in the input images and finds the corresponding histogram bin. But instead of incrementing it, the -function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of -statistics, the function computes probability of each element value in respect with the empirical -probability distribution represented by the histogram. See how, for example, you can find and track -a bright-colored object in a scene: - -- Before tracking, show the object to the camera so that it covers almost the whole frame. -Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant -colors in the object. - -- When tracking, calculate a back projection of a hue plane of each input video frame using that -pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make -sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels. - -- Find connected components in the resulting picture and choose, for example, the largest -component. - -This is an approximate algorithm of the CamShift color object tracker. - -@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same -size. Each of them can have an arbitrary number of channels. -@param nimages Number of source images. -@param channels The list of channels used to compute the back projection. The number of channels -must match the histogram dimensionality. The first array channels are numerated from 0 to -images[0].channels()-1 , the second array channels are counted from images[0].channels() to -images[0].channels() + images[1].channels()-1, and so on. -@param hist Input histogram that can be dense or sparse. -@param backProject Destination back projection array that is a single-channel array of the same -size and depth as images[0] . -@param ranges Array of arrays of the histogram bin boundaries in each dimension. See #calcHist . -@param scale Optional scale factor for the output back projection. -@param uniform Flag indicating whether the histogram is uniform or not (see #calcHist). - -@sa calcHist, compareHist - */ -CV_EXPORTS void calcBackProject( const Mat* images, int nimages, - const int* channels, InputArray hist, - OutputArray backProject, const float** ranges, - double scale = 1, bool uniform = true ); - -/** @overload */ -CV_EXPORTS void calcBackProject( const Mat* images, int nimages, - const int* channels, const SparseMat& hist, - OutputArray backProject, const float** ranges, - double scale = 1, bool uniform = true ); - -/** @overload */ -CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector& channels, - InputArray hist, OutputArray dst, - const std::vector& ranges, - double scale ); - -/** @brief Compares two histograms. - -The function cv::compareHist compares two dense or two sparse histograms using the specified method. - -The function returns \f$d(H_1, H_2)\f$ . - -While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable -for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling -problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms -or more general sparse configurations of weighted points, consider using the #EMD function. - -@param H1 First compared histogram. -@param H2 Second compared histogram of the same size as H1 . -@param method Comparison method, see #HistCompMethods - */ -CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); - -/** @overload */ -CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); - -/** @brief Equalizes the histogram of a grayscale image. - -The function equalizes the histogram of the input image using the following algorithm: - -- Calculate the histogram \f$H\f$ for src . -- Normalize the histogram so that the sum of histogram bins is 255. -- Compute the integral of the histogram: -\f[H'_i = \sum _{0 \le j < i} H(j)\f] -- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ - -The algorithm normalizes the brightness and increases the contrast of the image. - -@param src Source 8-bit single channel image. -@param dst Destination image of the same size and type as src . - */ -CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); - -/** @brief Creates a smart pointer to a cv::CLAHE class and initializes it. - -@param clipLimit Threshold for contrast limiting. -@param tileGridSize Size of grid for histogram equalization. Input image will be divided into -equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. - */ -CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); - -/** @brief Computes the "minimal work" distance between two weighted point configurations. - -The function computes the earth mover distance and/or a lower boundary of the distance between the -two weighted point configurations. One of the applications described in @cite RubnerSept98, -@cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation -problem that is solved using some modification of a simplex algorithm, thus the complexity is -exponential in the worst case, though, on average it is much faster. In the case of a real metric -the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used -to determine roughly whether the two signatures are far enough so that they cannot relate to the -same object. - -@param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix. -Each row stores the point weight followed by the point coordinates. The matrix is allowed to have -a single column (weights only) if the user-defined cost matrix is used. The weights must be -non-negative and have at least one non-zero value. -@param signature2 Second signature of the same format as signature1 , though the number of rows -may be different. The total weights may be different. In this case an extra "dummy" point is added -to either signature1 or signature2. The weights must be non-negative and have at least one non-zero -value. -@param distType Used metric. See #DistanceTypes. -@param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix -is used, lower boundary lowerBound cannot be calculated because it needs a metric function. -@param lowerBound Optional input/output parameter: lower boundary of a distance between the two -signatures that is a distance between mass centers. The lower boundary may not be calculated if -the user-defined cost matrix is used, the total weights of point configurations are not equal, or -if the signatures consist of weights only (the signature matrices have a single column). You -**must** initialize \*lowerBound . If the calculated distance between mass centers is greater or -equal to \*lowerBound (it means that the signatures are far enough), the function does not -calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on -return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound -should be set to 0. -@param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is -a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 . - */ -CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, - int distType, InputArray cost=noArray(), - float* lowerBound = 0, OutputArray flow = noArray() ); - -CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2, - int distType, InputArray cost=noArray(), - CV_IN_OUT Ptr lowerBound = Ptr(), OutputArray flow = noArray() ); - -//! @} imgproc_hist - -//! @addtogroup imgproc_segmentation -//! @{ - -/** @example samples/cpp/watershed.cpp -An example using the watershed algorithm -*/ - -/** @brief Performs a marker-based image segmentation using the watershed algorithm. - -The function implements one of the variants of watershed, non-parametric marker-based segmentation -algorithm, described in @cite Meyer92 . - -Before passing the image to the function, you have to roughly outline the desired regions in the -image markers with positive (\>0) indices. So, every region is represented as one or more connected -components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary -mask using #findContours and #drawContours (see the watershed.cpp demo). The markers are "seeds" of -the future image regions. All the other pixels in markers , whose relation to the outlined regions -is not known and should be defined by the algorithm, should be set to 0's. In the function output, -each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the -regions. - -@note Any two neighbor connected components are not necessarily separated by a watershed boundary -(-1's pixels); for example, they can touch each other in the initial marker image passed to the -function. - -@param image Input 8-bit 3-channel image. -@param markers Input/output 32-bit single-channel image (map) of markers. It should have the same -size as image . - -@sa findContours - */ -CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); - -//! @} imgproc_segmentation - -//! @addtogroup imgproc_filter -//! @{ - -/** @brief Performs initial step of meanshift segmentation of an image. - -The function implements the filtering stage of meanshift segmentation, that is, the output of the -function is the filtered "posterized" image with color gradients and fine-grain texture flattened. -At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes -meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is -considered: - -\f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f] - -where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively -(though, the algorithm does not depend on the color space used, so any 3-component color space can -be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector -(R',G',B') are found and they act as the neighborhood center on the next iteration: - -\f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f] - -After the iterations over, the color components of the initial pixel (that is, the pixel from where -the iterations started) are set to the final value (average color at the last iteration): - -\f[I(X,Y) <- (R*,G*,B*)\f] - -When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is -run on the smallest layer first. After that, the results are propagated to the larger layer and the -iterations are run again only on those pixels where the layer colors differ by more than sr from the -lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the -results will be actually different from the ones obtained by running the meanshift procedure on the -whole original image (i.e. when maxLevel==0). - -@param src The source 8-bit, 3-channel image. -@param dst The destination image of the same format and the same size as the source. -@param sp The spatial window radius. -@param sr The color window radius. -@param maxLevel Maximum level of the pyramid for the segmentation. -@param termcrit Termination criteria: when to stop meanshift iterations. - */ -CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, - double sp, double sr, int maxLevel = 1, - TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); - -//! @} - -//! @addtogroup imgproc_segmentation -//! @{ - -/** @example samples/cpp/grabcut.cpp -An example using the GrabCut algorithm -![Sample Screenshot](grabcut_output1.jpg) -*/ - -/** @brief Runs the GrabCut algorithm. - -The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). - -@param img Input 8-bit 3-channel image. -@param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when -mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. -@param rect ROI containing a segmented object. The pixels outside of the ROI are marked as -"obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . -@param bgdModel Temporary array for the background model. Do not modify it while you are -processing the same image. -@param fgdModel Temporary arrays for the foreground model. Do not modify it while you are -processing the same image. -@param iterCount Number of iterations the algorithm should make before returning the result. Note -that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or -mode==GC_EVAL . -@param mode Operation mode that could be one of the #GrabCutModes - */ -CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, - InputOutputArray bgdModel, InputOutputArray fgdModel, - int iterCount, int mode = GC_EVAL ); - -//! @} imgproc_segmentation - -//! @addtogroup imgproc_misc -//! @{ - -/** @example samples/cpp/distrans.cpp -An example on using the distance transform -*/ - -/** @brief Calculates the distance to the closest zero pixel for each pixel of the source image. - -The function cv::distanceTransform calculates the approximate or precise distance from every binary -image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. - -When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the -algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library. - -In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function -finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, -diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall -distance is calculated as a sum of these basic distances. Since the distance function should be -symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all -the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the -same cost (denoted as `c`). For the #DIST_C and #DIST_L1 types, the distance is calculated -precisely, whereas for #DIST_L2 (Euclidean distance) the distance can be calculated only with a -relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV -uses the values suggested in the original paper: -- DIST_L1: `a = 1, b = 2` -- DIST_L2: - - `3 x 3`: `a=0.955, b=1.3693` - - `5 x 5`: `a=1, b=1.4, c=2.1969` -- DIST_C: `a = 1, b = 1` - -Typically, for a fast, coarse distance estimation #DIST_L2, a \f$3\times 3\f$ mask is used. For a -more accurate distance estimation #DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used. -Note that both the precise and the approximate algorithms are linear on the number of pixels. - -This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$ -but also identifies the nearest connected component consisting of zero pixels -(labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the -component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function -automatically finds connected components of zero pixels in the input image and marks them with -distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and -marks all the zero pixels with distinct labels. - -In this mode, the complexity is still linear. That is, the function provides a very fast way to -compute the Voronoi diagram for a binary image. Currently, the second variant can use only the -approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported -yet. - -@param src 8-bit, single-channel (binary) source image. -@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, -single-channel image of the same size as src. -@param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type -CV_32SC1 and the same size as src. -@param distanceType Type of distance, see #DistanceTypes -@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. -#DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, -the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times -5\f$ or any larger aperture. -@param labelType Type of the label array to build, see #DistanceTransformLabelTypes. - */ -CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, - OutputArray labels, int distanceType, int maskSize, - int labelType = DIST_LABEL_CCOMP ); - -/** @overload -@param src 8-bit, single-channel (binary) source image. -@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, -single-channel image of the same size as src . -@param distanceType Type of distance, see #DistanceTypes -@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the -#DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives -the same result as \f$5\times 5\f$ or any larger aperture. -@param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for -the first variant of the function and distanceType == #DIST_L1. -*/ -CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, - int distanceType, int maskSize, int dstType=CV_32F); - -/** @brief Fills a connected component with the given color. - -The function cv::floodFill fills a connected component starting from the seed point with the specified -color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The -pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if: - -- in case of a grayscale image and floating range -\f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f] - - -- in case of a grayscale image and fixed range -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f] - - -- in case of a color image and floating range -\f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f] -\f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f] -and -\f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f] - - -- in case of a color image and fixed range -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f] -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f] -and -\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f] - - -where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the -component. That is, to be added to the connected component, a color/brightness of the pixel should -be close enough to: -- Color/brightness of one of its neighbors that already belong to the connected component in case -of a floating range. -- Color/brightness of the seed point in case of a fixed range. - -Use these functions to either mark a connected component with the specified color in-place, or build -a mask and then extract the contour, or copy the region to another image, and so on. - -@param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the -function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See -the details below. -@param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels -taller than image. If an empty Mat is passed it will be created automatically. Since this is both an -input and output parameter, you must take responsibility of initializing it. -Flood-filling cannot go across non-zero pixels in the input mask. For example, -an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the -mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags -as described below. Additionally, the function fills the border of the mask with ones to simplify -internal processing. It is therefore possible to use the same mask in multiple calls to the function -to make sure the filled areas do not overlap. -@param seedPoint Starting point. -@param newVal New value of the repainted domain pixels. -@param loDiff Maximal lower brightness/color difference between the currently observed pixel and -one of its neighbors belonging to the component, or a seed pixel being added to the component. -@param upDiff Maximal upper brightness/color difference between the currently observed pixel and -one of its neighbors belonging to the component, or a seed pixel being added to the component. -@param rect Optional output parameter set by the function to the minimum bounding rectangle of the -repainted domain. -@param flags Operation flags. The first 8 bits contain a connectivity value. The default value of -4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A -connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) -will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill -the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest -neighbours and fill the mask with a value of 255. The following additional options occupy higher -bits and therefore may be further combined with the connectivity and mask fill values using -bit-wise or (|), see #FloodFillFlags. - -@note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the -pixel \f$(x+1, y+1)\f$ in the mask . - -@sa findContours - */ -CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, - Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, - Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), - int flags = 4 ); - -/** @example samples/cpp/ffilldemo.cpp -An example using the FloodFill technique -*/ - -/** @overload - -variant without `mask` parameter -*/ -CV_EXPORTS int floodFill( InputOutputArray image, - Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, - Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), - int flags = 4 ); - -//! Performs linear blending of two images: -//! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f] -//! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer. -//! @param src2 It has the same type and size as src1. -//! @param weights1 It has a type of CV_32FC1 and the same size with src1. -//! @param weights2 It has a type of CV_32FC1 and the same size with src1. -//! @param dst It is created if it does not have the same size and type with src1. -CV_EXPORTS_W void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); - -//! @} imgproc_misc - -//! @addtogroup imgproc_color_conversions -//! @{ - -/** @brief Converts an image from one color space to another. - -The function converts an input image from one color space to another. In case of a transformation -to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note -that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the -bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue -component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and -sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. - -The conventional ranges for R, G, and B channel values are: -- 0 to 255 for CV_8U images -- 0 to 65535 for CV_16U images -- 0 to 1 for CV_32F images - -In case of linear transformations, the range does not matter. But in case of a non-linear -transformation, an input RGB image should be normalized to the proper value range to get the correct -results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a -32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will -have the 0..255 value range instead of 0..1 assumed by the function. So, before calling #cvtColor , -you need first to scale the image down: -@code - img *= 1./255; - cvtColor(img, img, COLOR_BGR2Luv); -@endcode -If you use #cvtColor with 8-bit images, the conversion will have some information lost. For many -applications, this will not be noticeable but it is recommended to use 32-bit images in applications -that need the full range of colors or that convert an image before an operation and then convert -back. - -If conversion adds the alpha channel, its value will set to the maximum of corresponding channel -range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. - -@param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision -floating-point. -@param dst output image of the same size and depth as src. -@param code color space conversion code (see #ColorConversionCodes). -@param dstCn number of channels in the destination image; if the parameter is 0, the number of the -channels is derived automatically from src and code. -@param hint Implementation modfication flags. See #AlgorithmHint - -@see @ref imgproc_color_conversions - */ -CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); - -/** @brief Converts an image from one color space to another where the source image is -stored in two planes. - -This function only supports YUV420 to RGB conversion as of now. - -@param src1 8-bit image (#CV_8U) of the Y plane. -@param src2 image containing interleaved U/V plane. -@param dst output image. -@param code Specifies the type of conversion. It can take any of the following values: -- #COLOR_YUV2BGR_NV12 -- #COLOR_YUV2RGB_NV12 -- #COLOR_YUV2BGRA_NV12 -- #COLOR_YUV2RGBA_NV12 -- #COLOR_YUV2BGR_NV21 -- #COLOR_YUV2RGB_NV21 -- #COLOR_YUV2BGRA_NV21 -- #COLOR_YUV2RGBA_NV21 -@param hint Implementation modfication flags. See #AlgorithmHint -*/ -CV_EXPORTS_W void cvtColorTwoPlane( InputArray src1, InputArray src2, OutputArray dst, int code, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); - -/** @brief main function for all demosaicing processes - -@param src input image: 8-bit unsigned or 16-bit unsigned. -@param dst output image of the same size and depth as src. -@param code Color space conversion code (see the description below). -@param dstCn number of channels in the destination image; if the parameter is 0, the number of the -channels is derived automatically from src and code. - -The function can do the following transformations: - -- Demosaicing using bilinear interpolation - - #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR - - #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY - -- Demosaicing using Variable Number of Gradients. - - #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG - -- Edge-Aware Demosaicing. - - #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA - -- Demosaicing with alpha channel - - #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA - -@sa cvtColor -*/ -CV_EXPORTS_W void demosaicing(InputArray src, OutputArray dst, int code, int dstCn = 0); - -//! @} imgproc_color_conversions - -//! @addtogroup imgproc_shape -//! @{ - -/** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape. - -The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The -results are returned in the structure cv::Moments. - -@param array Single chanel raster image (CV_8U, CV_16U, CV_16S, CV_32F, CV_64F) or an array ( -\f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f). -@param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is -used for images only. -@returns moments. - -@note Only applicable to contour moments calculations from Python bindings: Note that the numpy -type for the input array should be either np.int32 or np.float32. - -@sa contourArea, arcLength - */ -CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); - -/** @brief Calculates seven Hu invariants. - -The function calculates seven Hu invariants (introduced in @cite Hu62; see also -) defined as: - -\f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f] - -where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ . - -These values are proved to be invariants to the image scale, rotation, and reflection except the -seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of -infinite image resolution. In case of raster images, the computed Hu invariants for the original and -transformed images are a bit different. - -@param moments Input moments computed with moments . -@param hu Output Hu invariants. - -@sa matchShapes - */ -CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); - -/** @overload */ -CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); - -//! @} imgproc_shape - -//! @addtogroup imgproc_object -//! @{ - -//! type of the template matching operation -enum TemplateMatchModes { - TM_SQDIFF = 0, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] - with mask: - \f[R(x,y)= \sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot - M(x',y') \right)^2\f] */ - TM_SQDIFF_NORMED = 1, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{ - x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] - with mask: - \f[R(x,y)= \frac{\sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot - M(x',y') \right)^2}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot - M(x',y') \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot - M(x',y') \right)^2}}\f] */ - TM_CCORR = 2, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] - with mask: - \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot M(x',y') - ^2)\f] */ - TM_CCORR_NORMED = 3, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{ - \sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] - with mask: - \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot - M(x',y')^2)}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot M(x',y') - \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot M(x',y') - \right)^2}}\f] */ - TM_CCOEFF = 4, /*!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] - where - \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{ - x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) - \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] - with mask: - \f[\begin{array}{l} T'(x',y')=M(x',y') \cdot \left( T(x',y') - - \frac{1}{\sum _{x'',y''} M(x'',y'')} \cdot \sum _{x'',y''} - (T(x'',y'') \cdot M(x'',y'')) \right) \\ I'(x+x',y+y')=M(x',y') - \cdot \left( I(x+x',y+y') - \frac{1}{\sum _{x'',y''} M(x'',y'')} - \cdot \sum _{x'',y''} (I(x+x'',y+y'') \cdot M(x'',y'')) \right) - \end{array} \f] */ - TM_CCOEFF_NORMED = 5 /*!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ - \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} - }\f] */ -}; - -/** @example samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp -An example using Template Matching algorithm -*/ - -/** @brief Compares a template against overlapped image regions. - -The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against -templ using the specified method and stores the comparison results in result . #TemplateMatchModes -describes the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ -template, \f$R\f$ result, \f$M\f$ the optional mask ). The summation is done over template and/or -the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$ - -After the function finishes the comparison, the best matches can be found as global minimums (when -#TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the -#minMaxLoc function. In case of a color image, template summation in the numerator and each sum in -the denominator is done over all of the channels and separate mean values are used for each channel. -That is, the function can take a color template and a color image. The result will still be a -single-channel image, which is easier to analyze. - -@param image Image where the search is running. It must be 8-bit or 32-bit floating-point. -@param templ Searched template. It must be not greater than the source image and have the same -data type. -@param result Map of comparison results. It must be single-channel 32-bit floating-point. If image -is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ . -@param method Parameter specifying the comparison method, see #TemplateMatchModes -@param mask Optional mask. It must have the same size as templ. It must either have the same number - of channels as template or only one channel, which is then used for all template and - image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, - meaning only elements where mask is nonzero are used and are kept unchanged independent - of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are - used as weights. The exact formulas are documented in #TemplateMatchModes. - */ -CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, - OutputArray result, int method, InputArray mask = noArray() ); - -//! @} - -//! @addtogroup imgproc_shape -//! @{ - -/** @example samples/cpp/connected_components.cpp -This program demonstrates connected components and use of the trackbar -*/ - -/** @brief computes the connected components labeled image of boolean image - -image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 -represents the background label. ltype specifies the output label image type, an important -consideration based on the total number of labels or alternatively the total number of pixels in -the source image. ccltype specifies the connected components labeling algorithm to use, currently -Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms -are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces -a row major ordering of labels while Spaghetti and BBDT do not. -This function uses parallel version of the algorithms if at least one allowed -parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. - -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -@param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes). -*/ -CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels, - int connectivity, int ltype, int ccltype); - - -/** @overload - -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -*/ -CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, - int connectivity = 8, int ltype = CV_32S); - - -/** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label - -image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 -represents the background label. ltype specifies the output label image type, an important -consideration based on the total number of labels or alternatively the total number of pixels in -the source image. ccltype specifies the connected components labeling algorithm to use, currently -Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms -are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces -a row major ordering of labels while Spaghetti and BBDT do not. -This function uses parallel version of the algorithms (statistics included) if at least one allowed -parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. - -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param stats statistics output for each label, including the background label. -Statistics are accessed via stats(label, COLUMN) where COLUMN is one of -#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. -@param centroids centroid output for each label, including the background label. Centroids are -accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -@param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes). -*/ -CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels, - OutputArray stats, OutputArray centroids, - int connectivity, int ltype, int ccltype); - -/** @overload -@param image the 8-bit single-channel image to be labeled -@param labels destination labeled image -@param stats statistics output for each label, including the background label. -Statistics are accessed via stats(label, COLUMN) where COLUMN is one of -#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. -@param centroids centroid output for each label, including the background label. Centroids are -accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. -@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively -@param ltype output image label type. Currently CV_32S and CV_16U are supported. -*/ -CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, - OutputArray stats, OutputArray centroids, - int connectivity = 8, int ltype = CV_32S); - - -/** @brief Finds contours in a binary image. - -The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours -are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the -OpenCV sample directory. -@note Since opencv 3.2 source image is not modified by this function. - -@param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero -pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , -#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. -If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). -@param contours Detected contours. Each contour is stored as a vector of points (e.g. -std::vector >). -@param hierarchy Optional output vector (e.g. std::vector), containing information about the image topology. It has -as many elements as the number of contours. For each i-th contour contours[i], the elements -hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices -in contours of the next and previous contours at the same hierarchical level, the first child -contour and the parent contour, respectively. If for the contour i there are no next, previous, -parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. -@note In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. -@param mode Contour retrieval mode, see #RetrievalModes -@param method Contour approximation method, see #ContourApproximationModes -@param offset Optional offset by which every contour point is shifted. This is useful if the -contours are extracted from the image ROI and then they should be analyzed in the whole image -context. - */ -CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours, - OutputArray hierarchy, int mode, - int method, Point offset = Point()); - -/** @overload */ -CV_EXPORTS void findContours( InputArray image, OutputArrayOfArrays contours, - int mode, int method, Point offset = Point()); - -//! @brief Find contours using link runs algorithm -//! -//! This function implements an algorithm different from cv::findContours: -//! - doesn't allocate temporary image internally, thus it has reduced memory consumption -//! - supports CV_8UC1 images only -//! - outputs 2-level hierarhy only (RETR_CCOMP mode) -//! - doesn't support approximation change other than CHAIN_APPROX_SIMPLE -//! In all other aspects this function is compatible with cv::findContours. -CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy); - -//! @overload -CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours); - -/** @brief Approximates a polygonal curve(s) with the specified precision. - -The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less -vertices so that the distance between them is less or equal to the specified precision. It uses the -Douglas-Peucker algorithm - -@param curve Input vector of a 2D point stored in std::vector or Mat -@param approxCurve Result of the approximation. The type should match the type of the input curve. -@param epsilon Parameter specifying the approximation accuracy. This is the maximum distance -between the original curve and its approximation. -@param closed If true, the approximated curve is closed (its first and last vertices are -connected). Otherwise, it is not closed. - */ -CV_EXPORTS_W void approxPolyDP( InputArray curve, - OutputArray approxCurve, - double epsilon, bool closed ); - -/** @brief Approximates a polygon with a convex hull with a specified accuracy and number of sides. - -The cv::approxPolyN function approximates a polygon with a convex hull -so that the difference between the contour area of the original contour and the new polygon is minimal. -It uses a greedy algorithm for contracting two vertices into one in such a way that the additional area is minimal. -Straight lines formed by each edge of the convex contour are drawn and the areas of the resulting triangles are considered. -Each vertex will lie either on the original contour or outside it. - -The algorithm based on the paper @cite LowIlie2003 . - -@param curve Input vector of a 2D points stored in std::vector or Mat, points must be float or integer. -@param approxCurve Result of the approximation. The type is vector of a 2D point (Point2f or Point) in std::vector or Mat. -@param nsides The parameter defines the number of sides of the result polygon. -@param epsilon_percentage defines the percentage of the maximum of additional area. -If it equals -1, it is not used. Otherwise algorighm stops if additional area is greater than contourArea(_curve) * percentage. -If additional area exceeds the limit, algorithm returns as many vertices as there were at the moment the limit was exceeded. -@param ensure_convex If it is true, algorithm creates a convex hull of input contour. Otherwise input vector should be convex. - */ -CV_EXPORTS_W void approxPolyN(InputArray curve, OutputArray approxCurve, - int nsides, float epsilon_percentage = -1.0, - bool ensure_convex = true); - -/** @brief Calculates a contour perimeter or a curve length. - -The function computes a curve length or a closed contour perimeter. - -@param curve Input vector of 2D points, stored in std::vector or Mat. -@param closed Flag indicating whether the curve is closed or not. - */ -CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); - -/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image. - -The function calculates and returns the minimal up-right bounding rectangle for the specified point set or -non-zero pixels of gray-scale image. - -@param array Input gray-scale image or 2D point set, stored in std::vector or Mat. - */ -CV_EXPORTS_W Rect boundingRect( InputArray array ); - -/** @brief Calculates a contour area. - -The function computes a contour area. Similarly to moments , the area is computed using the Green -formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using -#drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong -results for contours with self-intersections. - -Example: -@code - vector contour; - contour.push_back(Point2f(0, 0)); - contour.push_back(Point2f(10, 0)); - contour.push_back(Point2f(10, 10)); - contour.push_back(Point2f(5, 4)); - - double area0 = contourArea(contour); - vector approx; - approxPolyDP(contour, approx, 5, true); - double area1 = contourArea(approx); - - cout << "area0 =" << area0 << endl << - "area1 =" << area1 << endl << - "approx poly vertices" << approx.size() << endl; -@endcode -@param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. -@param oriented Oriented area flag. If it is true, the function returns a signed area value, -depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can -determine orientation of a contour by taking the sign of an area. By default, the parameter is -false, which means that the absolute value is returned. - */ -CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); - -/** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set. - -The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a -specified point set. Developer should keep in mind that the returned RotatedRect can contain negative -indices when data is close to the containing Mat element boundary. - -@param points Input vector of 2D points, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); - -/** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. - -The function finds the four vertices of a rotated rectangle. This function is useful to draw the -rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please -visit the @ref tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses for contours" for more information. - -@param box The input rotated rectangle. It may be the output of @ref minAreaRect. -@param points The output array of four vertices of rectangles. - */ -CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); - -/** @brief Finds a circle of the minimum area enclosing a 2D point set. - -The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. - -@param points Input vector of 2D points, stored in std::vector\<\> or Mat -@param center Output center of the circle. -@param radius Output radius of the circle. - */ -CV_EXPORTS_W void minEnclosingCircle( InputArray points, - CV_OUT Point2f& center, CV_OUT float& radius ); - -/** @example samples/cpp/minarea.cpp -*/ - -/** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area. - -The function finds a triangle of minimum area enclosing the given set of 2D points and returns its -area. The output for a given 2D point set is shown in the image below. 2D points are depicted in -*red* and the enclosing triangle in *yellow*. - -![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) - -The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's -@cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal -enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function -takes a 2D point set as input an additional preprocessing step of computing the convex hull of the -2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which is higher -than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$. - -@param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat -@param triangle Output vector of three 2D points defining the vertices of the triangle. The depth -of the OutputArray must be CV_32F. - */ -CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); - -/** @brief Compares two shapes. - -The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments) - -@param contour1 First contour or grayscale image. -@param contour2 Second contour or grayscale image. -@param method Comparison method, see #ShapeMatchModes -@param parameter Method-specific parameter (not supported now). - */ -CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, - int method, double parameter ); - -/** @example samples/cpp/convexhull.cpp -An example using the convexHull functionality -*/ - -/** @brief Finds the convex hull of a point set. - -The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82 -that has *O(N logN)* complexity in the current implementation. - -@param points Input 2D point set, stored in std::vector or Mat. -@param hull Output convex hull. It is either an integer vector of indices or vector of points. In -the first case, the hull elements are 0-based indices of the convex hull points in the original -array (since the set of convex hull points is a subset of the original point set). In the second -case, hull elements are the convex hull points themselves. -@param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. -Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing -to the right, and its Y axis pointing upwards. -@param returnPoints Operation flag. In case of a matrix, when the flag is true, the function -returns convex hull points. Otherwise, it returns indices of the convex hull points. When the -output array is std::vector, the flag is ignored, and the output depends on the type of the -vector: std::vector\ implies returnPoints=false, std::vector\ implies -returnPoints=true. - -@note `points` and `hull` should be different arrays, inplace processing isn't supported. - -Check @ref tutorial_hull "the corresponding tutorial" for more details. - -useful links: - -https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ - */ -CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, - bool clockwise = false, bool returnPoints = true ); - -/** @brief Finds the convexity defects of a contour. - -The figure below displays convexity defects of a hand contour: - -![image](pics/defects.png) - -@param contour Input contour. -@param convexhull Convex hull obtained using convexHull that should contain indices of the contour -points that make the hull. -@param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java -interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i): -(start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices -in the original contour of the convexity defect beginning, end and the farthest point, and -fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the -farthest contour point and the hull. That is, to get the floating-point value of the depth will be -fixpt_depth/256.0. - */ -CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); - -/** @brief Tests a contour convexity. - -The function tests whether the input contour is convex or not. The contour must be simple, that is, -without self-intersections. Otherwise, the function output is undefined. - -@param contour Input vector of 2D points, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W bool isContourConvex( InputArray contour ); - -/** @example samples/cpp/intersectExample.cpp -Examples of how intersectConvexConvex works -*/ - -/** @brief Finds intersection of two convex polygons - -@param p1 First polygon -@param p2 Second polygon -@param p12 Output polygon describing the intersecting area -@param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other. -When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge -of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. - -@returns Area of intersecting polygon. May be negative, if algorithm has not converged, e.g. non-convex input. - -@note intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't. - */ -CV_EXPORTS_W float intersectConvexConvex( InputArray p1, InputArray p2, - OutputArray p12, bool handleNested = true ); - -/** @example samples/cpp/fitellipse.cpp -An example using the fitEllipse technique -*/ - -/** @brief Fits an ellipse around a set of 2D points. - -The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of -all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95 -is used. Developer should keep in mind that it is possible that the returned -ellipse/rotatedRect data contains negative indices, due to the data points being close to the -border of the containing Mat element. - -@param points Input 2D point set, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); - -/** @brief Fits an ellipse around a set of 2D points. - - The function calculates the ellipse that fits a set of 2D points. - It returns the rotated rectangle in which the ellipse is inscribed. - The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used. - - For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, - which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. - However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, - the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, - quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. - If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used. - The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves - by imposing the condition that \f$ A^T ( D_x^T D_x + D_y^T D_y) A = 1 \f$ where - the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with - respect to x and y. The matrices are formed row by row applying the following to - each of the points in the set: - \f{align*}{ - D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} & - D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} & - D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\} - \f} - The AMS method minimizes the cost function - \f{equation*}{ - \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T } - \f} - - The minimum cost is found by solving the generalized eigenvalue problem. - - \f{equation*}{ - D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A - \f} - - @param points Input 2D point set, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points ); - - -/** @brief Fits an ellipse around a set of 2D points. - - The function calculates the ellipse that fits a set of 2D points. - It returns the rotated rectangle in which the ellipse is inscribed. - The Direct least square (Direct) method by @cite oy1998NumericallySD is used. - - For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, - which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. - However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, - the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, - quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. - The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$. - The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality - and as the coefficients can be arbitrarily scaled is not overly restrictive. - - \f{equation*}{ - \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix} - 0 & 0 & 2 & 0 & 0 & 0 \\ - 0 & -1 & 0 & 0 & 0 & 0 \\ - 2 & 0 & 0 & 0 & 0 & 0 \\ - 0 & 0 & 0 & 0 & 0 & 0 \\ - 0 & 0 & 0 & 0 & 0 & 0 \\ - 0 & 0 & 0 & 0 & 0 & 0 - \end{matrix} \right) - \f} - - The minimum cost is found by solving the generalized eigenvalue problem. - - \f{equation*}{ - D^T D A = \lambda \left( C\right) A - \f} - - The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution - with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients - - \f{equation*}{ - A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u} - \f} - The scaling factor guarantees that \f$A^T C A =1\f$. - - @param points Input 2D point set, stored in std::vector\<\> or Mat - */ -CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points ); - -/** @brief Fits a line to a 2D or 3D point set. - -The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where -\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one -of the following: -- DIST_L2 -\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] -- DIST_L1 -\f[\rho (r) = r\f] -- DIST_L12 -\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] -- DIST_FAIR -\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] -- DIST_WELSCH -\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] -- DIST_HUBER -\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] - -The algorithm is based on the M-estimator ( ) technique -that iteratively fits the line using the weighted least-squares algorithm. After each iteration the -weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . - -@param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat. -@param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements -(like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and -(x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like -Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line -and (x0, y0, z0) is a point on the line. -@param distType Distance used by the M-estimator, see #DistanceTypes -@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value -is chosen. -@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). -@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. - */ -CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, - double param, double reps, double aeps ); - -/** @brief Performs a point-in-contour test. - -The function determines whether the point is inside a contour, outside, or lies on an edge (or -coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) -value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. -Otherwise, the return value is a signed distance between the point and the nearest contour edge. - -See below a sample output of the function where each image pixel is tested against the contour: - -![sample output](pics/pointpolygon.png) - -@param contour Input contour. -@param pt Point tested against the contour. -@param measureDist If true, the function estimates the signed distance from the point to the -nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. - */ -CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); - -/** @brief Finds out if there is any intersection between two rotated rectangles. - -If there is then the vertices of the intersecting region are returned as well. - -Below are some examples of intersection configurations. The hatched pattern indicates the -intersecting region and the red vertices are returned by the function. - -![intersection examples](pics/intersection.png) - -@param rect1 First rectangle -@param rect2 Second rectangle -@param intersectingRegion The output array of the vertices of the intersecting region. It returns -at most 8 vertices. Stored as std::vector\ or cv::Mat as Mx1 of type CV_32FC2. -@returns One of #RectanglesIntersectTypes - */ -CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); - -/** @brief Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it. -*/ -CV_EXPORTS_W Ptr createGeneralizedHoughBallard(); - -/** @brief Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it. -*/ -CV_EXPORTS_W Ptr createGeneralizedHoughGuil(); - -//! @} imgproc_shape - -//! @addtogroup imgproc_colormap -//! @{ - -//! GNU Octave/MATLAB equivalent colormaps -enum ColormapTypes -{ - COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg) - COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg) - COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg) - COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg) - COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg) - COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg) - COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg) - COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg) - COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg) - COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg) - COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg) - COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg) - COLORMAP_PARULA = 12, //!< ![parula](pics/colormaps/colorscale_parula.jpg) - COLORMAP_MAGMA = 13, //!< ![magma](pics/colormaps/colorscale_magma.jpg) - COLORMAP_INFERNO = 14, //!< ![inferno](pics/colormaps/colorscale_inferno.jpg) - COLORMAP_PLASMA = 15, //!< ![plasma](pics/colormaps/colorscale_plasma.jpg) - COLORMAP_VIRIDIS = 16, //!< ![viridis](pics/colormaps/colorscale_viridis.jpg) - COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg) - COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg) - COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg) - COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg) - COLORMAP_DEEPGREEN = 21 //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg) -}; - -/** @example samples/cpp/falsecolor.cpp -An example using applyColorMap function -*/ - -/** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image. - -@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. -@param dst The result is the colormapped source image. Note: Mat::create is called on dst. -@param colormap The colormap to apply, see #ColormapTypes -*/ -CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); - -/** @brief Applies a user colormap on a given image. - -@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. -@param dst The result is the colormapped source image of the same number of channels as userColor. Note: Mat::create is called on dst. -@param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 -*/ -CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor); - -//! @} imgproc_colormap - -//! @addtogroup imgproc_draw -//! @{ - - -/** OpenCV color channel order is BGR[A] */ -#define CV_RGB(r, g, b) cv::Scalar((b), (g), (r), 0) - -/** @brief Draws a line segment connecting two points. - -The function line draws the line segment between pt1 and pt2 points in the image. The line is -clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected -or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased -lines are drawn using Gaussian filtering. - -@param img Image. -@param pt1 First point of the line segment. -@param pt2 Second point of the line segment. -@param color Line color. -@param thickness Line thickness. -@param lineType Type of the line. See #LineTypes. -@param shift Number of fractional bits in the point coordinates. - */ -CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, - int thickness = 1, int lineType = LINE_8, int shift = 0); - -/** @brief Draws an arrow segment pointing from the first point to the second one. - -The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. - -@param img Image. -@param pt1 The point the arrow starts from. -@param pt2 The point the arrow points to. -@param color Line color. -@param thickness Line thickness. -@param line_type Type of the line. See #LineTypes -@param shift Number of fractional bits in the point coordinates. -@param tipLength The length of the arrow tip in relation to the arrow length - */ -CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, - int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); - -/** @brief Draws a simple, thick, or filled up-right rectangle. - -The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners -are pt1 and pt2. - -@param img Image. -@param pt1 Vertex of the rectangle. -@param pt2 Vertex of the rectangle opposite to pt1 . -@param color Rectangle color or brightness (grayscale image). -@param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, -mean that the function has to draw a filled rectangle. -@param lineType Type of the line. See #LineTypes -@param shift Number of fractional bits in the point coordinates. - */ -CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @overload - -use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and -r.br()-Point(1,1)` are opposite corners -*/ -CV_EXPORTS_W void rectangle(InputOutputArray img, Rect rec, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp -An example using drawing functions -*/ - -/** @brief Draws a circle. - -The function cv::circle draws a simple or filled circle with a given center and radius. -@param img Image where the circle is drawn. -@param center Center of the circle. -@param radius Radius of the circle. -@param color Circle color. -@param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, -mean that a filled circle is to be drawn. -@param lineType Type of the circle boundary. See #LineTypes -@param shift Number of fractional bits in the coordinates of the center and in the radius value. - */ -CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @brief Draws a simple or thick elliptic arc or fills an ellipse sector. - -The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic -arc, or a filled ellipse sector. The drawing code uses general parametric form. -A piecewise-linear curve is used to approximate the elliptic arc -boundary. If you need more control of the ellipse rendering, you can retrieve the curve using -#ellipse2Poly and then render it with #polylines or fill it with #fillPoly. If you use the first -variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and -`endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains -the meaning of the parameters to draw the blue arc. - -![Parameters of Elliptic Arc](pics/ellipse.svg) - -@param img Image. -@param center Center of the ellipse. -@param axes Half of the size of the ellipse main axes. -@param angle Ellipse rotation angle in degrees. -@param startAngle Starting angle of the elliptic arc in degrees. -@param endAngle Ending angle of the elliptic arc in degrees. -@param color Ellipse color. -@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that -a filled ellipse sector is to be drawn. -@param lineType Type of the ellipse boundary. See #LineTypes -@param shift Number of fractional bits in the coordinates of the center and values of axes. - */ -CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes, - double angle, double startAngle, double endAngle, - const Scalar& color, int thickness = 1, - int lineType = LINE_8, int shift = 0); - -/** @overload -@param img Image. -@param box Alternative ellipse representation via RotatedRect. This means that the function draws -an ellipse inscribed in the rotated rectangle. -@param color Ellipse color. -@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that -a filled ellipse sector is to be drawn. -@param lineType Type of the ellipse boundary. See #LineTypes -*/ -CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, - int thickness = 1, int lineType = LINE_8); - -/* ----------------------------------------------------------------------------------------- */ -/* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */ -/* ----------------------------------------------------------------------------------------- */ - -/** @brief Draws a marker on a predefined position in an image. - -The function cv::drawMarker draws a marker on a given position in the image. For the moment several -marker types are supported, see #MarkerTypes for more information. - -@param img Image. -@param position The point where the crosshair is positioned. -@param color Line color. -@param markerType The specific type of marker you want to use, see #MarkerTypes -@param thickness Line thickness. -@param line_type Type of the line, See #LineTypes -@param markerSize The length of the marker axis [default = 20 pixels] - */ -CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar& color, - int markerType = MARKER_CROSS, int markerSize=20, int thickness=1, - int line_type=8); - -/* ----------------------------------------------------------------------------------------- */ -/* END OF MARKER SECTION */ -/* ----------------------------------------------------------------------------------------- */ - -/** @brief Fills a convex polygon. - -The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the -function #fillPoly . It can fill not only convex polygons but any monotonic polygon without -self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) -twice at the most (though, its top-most and/or the bottom edge could be horizontal). - -@param img Image. -@param points Polygon vertices. -@param color Polygon color. -@param lineType Type of the polygon boundaries. See #LineTypes -@param shift Number of fractional bits in the vertex coordinates. - */ -CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, - const Scalar& color, int lineType = LINE_8, - int shift = 0); - -/** @overload */ -CV_EXPORTS void fillConvexPoly(InputOutputArray img, const Point* pts, int npts, - const Scalar& color, int lineType = LINE_8, - int shift = 0); - -/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_1.cpp -An example using drawing functions -Check @ref tutorial_random_generator_and_text "the corresponding tutorial" for more details -*/ - -/** @brief Fills the area bounded by one or more polygons. - -The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill -complex areas, for example, areas with holes, contours with self-intersections (some of their -parts), and so forth. - -@param img Image. -@param pts Array of polygons where each polygon is represented as an array of points. -@param color Polygon color. -@param lineType Type of the polygon boundaries. See #LineTypes -@param shift Number of fractional bits in the vertex coordinates. -@param offset Optional offset of all points of the contours. - */ -CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, - const Scalar& color, int lineType = LINE_8, int shift = 0, - Point offset = Point() ); - -/** @overload */ -CV_EXPORTS void fillPoly(InputOutputArray img, const Point** pts, - const int* npts, int ncontours, - const Scalar& color, int lineType = LINE_8, int shift = 0, - Point offset = Point() ); - -/** @brief Draws several polygonal curves. - -@param img Image. -@param pts Array of polygonal curves. -@param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, -the function draws a line from the last vertex of each curve to its first vertex. -@param color Polyline color. -@param thickness Thickness of the polyline edges. -@param lineType Type of the line segments. See #LineTypes -@param shift Number of fractional bits in the vertex coordinates. - -The function cv::polylines draws one or more polygonal curves. - */ -CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, - bool isClosed, const Scalar& color, - int thickness = 1, int lineType = LINE_8, int shift = 0 ); - -/** @overload */ -CV_EXPORTS void polylines(InputOutputArray img, const Point* const* pts, const int* npts, - int ncontours, bool isClosed, const Scalar& color, - int thickness = 1, int lineType = LINE_8, int shift = 0 ); - -/** @example samples/cpp/contours2.cpp -An example program illustrates the use of cv::findContours and cv::drawContours -\image html WindowsQtContoursOutput.png "Screenshot of the program" -*/ - -/** @example samples/cpp/segment_objects.cpp -An example using drawContours to clean up a background segmentation result -*/ - -/** @brief Draws contours outlines or filled contours. - -The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area -bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve -connected components from the binary image and label them: : -@include snippets/imgproc_drawContours.cpp - -@param image Destination image. -@param contours All the input contours. Each contour is stored as a point vector. -@param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. -@param color Color of the contours. -@param thickness Thickness of lines the contours are drawn with. If it is negative (for example, -thickness=#FILLED ), the contour interiors are drawn. -@param lineType Line connectivity. See #LineTypes -@param hierarchy Optional information about hierarchy. It is only needed if you want to draw only -some of the contours (see maxLevel ). -@param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. -If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function -draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This -parameter is only taken into account when there is hierarchy available. -@param offset Optional contour shift parameter. Shift all the drawn contours by the specified -\f$\texttt{offset}=(dx,dy)\f$ . -@note When thickness=#FILLED, the function is designed to handle connected components with holes correctly -even when no hierarchy data is provided. This is done by analyzing all the outlines together -using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved -contours. In order to solve this problem, you need to call #drawContours separately for each sub-group -of contours, or iterate over the collection using contourIdx parameter. - */ -CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours, - int contourIdx, const Scalar& color, - int thickness = 1, int lineType = LINE_8, - InputArray hierarchy = noArray(), - int maxLevel = INT_MAX, Point offset = Point() ); - -/** @brief Clips the line against the image rectangle. - -The function cv::clipLine calculates a part of the line segment that is entirely within the specified -rectangle. It returns false if the line segment is completely outside the rectangle. Otherwise, -it returns true . -@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . -@param pt1 First line point. -@param pt2 Second line point. - */ -CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); - -/** @overload -@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . -@param pt1 First line point. -@param pt2 Second line point. -*/ -CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2); - -/** @overload -@param imgRect Image rectangle. -@param pt1 First line point. -@param pt2 Second line point. -*/ -CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); - -/** @brief Approximates an elliptic arc with a polyline. - -The function ellipse2Poly computes the vertices of a polyline that approximates the specified -elliptic arc. It is used by #ellipse. If `arcStart` is greater than `arcEnd`, they are swapped. - -@param center Center of the arc. -@param axes Half of the size of the ellipse main axes. See #ellipse for details. -@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. -@param arcStart Starting angle of the elliptic arc in degrees. -@param arcEnd Ending angle of the elliptic arc in degrees. -@param delta Angle between the subsequent polyline vertices. It defines the approximation -accuracy. -@param pts Output vector of polyline vertices. - */ -CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, - int arcStart, int arcEnd, int delta, - CV_OUT std::vector& pts ); - -/** @overload -@param center Center of the arc. -@param axes Half of the size of the ellipse main axes. See #ellipse for details. -@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. -@param arcStart Starting angle of the elliptic arc in degrees. -@param arcEnd Ending angle of the elliptic arc in degrees. -@param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. -@param pts Output vector of polyline vertices. -*/ -CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle, - int arcStart, int arcEnd, int delta, - CV_OUT std::vector& pts); - -/** @brief Draws a text string. - -The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered -using the specified font are replaced by question marks. See #getTextSize for a text rendering code -example. - -@param img Image. -@param text Text string to be drawn. -@param org Bottom-left corner of the text string in the image. -@param fontFace Font type, see #HersheyFonts. -@param fontScale Font scale factor that is multiplied by the font-specific base size. -@param color Text color. -@param thickness Thickness of the lines used to draw a text. -@param lineType Line type. See #LineTypes -@param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, -it is at the top-left corner. - */ -CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org, - int fontFace, double fontScale, Scalar color, - int thickness = 1, int lineType = LINE_8, - bool bottomLeftOrigin = false ); - -/** @brief Calculates the width and height of a text string. - -The function cv::getTextSize calculates and returns the size of a box that contains the specified text. -That is, the following code renders some text, the tight box surrounding it, and the baseline: : -@code - String text = "Funny text inside the box"; - int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; - double fontScale = 2; - int thickness = 3; - - Mat img(600, 800, CV_8UC3, Scalar::all(0)); - - int baseline=0; - Size textSize = getTextSize(text, fontFace, - fontScale, thickness, &baseline); - baseline += thickness; - - // center the text - Point textOrg((img.cols - textSize.width)/2, - (img.rows + textSize.height)/2); - - // draw the box - rectangle(img, textOrg + Point(0, baseline), - textOrg + Point(textSize.width, -textSize.height), - Scalar(0,0,255)); - // ... and the baseline first - line(img, textOrg + Point(0, thickness), - textOrg + Point(textSize.width, thickness), - Scalar(0, 0, 255)); - - // then put the text itself - putText(img, text, textOrg, fontFace, fontScale, - Scalar::all(255), thickness, 8); -@endcode - -@param text Input text string. -@param fontFace Font to use, see #HersheyFonts. -@param fontScale Font scale factor that is multiplied by the font-specific base size. -@param thickness Thickness of lines used to render the text. See #putText for details. -@param[out] baseLine y-coordinate of the baseline relative to the bottom-most text -point. -@return The size of a box that contains the specified text. - -@see putText - */ -CV_EXPORTS_W Size getTextSize(const String& text, int fontFace, - double fontScale, int thickness, - CV_OUT int* baseLine); - - -/** @brief Calculates the font-specific size to use to achieve a given height in pixels. - -@param fontFace Font to use, see cv::HersheyFonts. -@param pixelHeight Pixel height to compute the fontScale for -@param thickness Thickness of lines used to render the text.See putText for details. -@return The fontSize to use for cv::putText - -@see cv::putText -*/ -CV_EXPORTS_W double getFontScaleFromHeight(const int fontFace, - const int pixelHeight, - const int thickness = 1); - -/** @brief Class for iterating over all pixels on a raster line segment. - -The class LineIterator is used to get each pixel of a raster line connecting -two specified points. -It can be treated as a versatile implementation of the Bresenham algorithm -where you can stop at each pixel and do some extra processing, for -example, grab pixel values along the line or draw a line with an effect -(for example, with XOR operation). - -The number of pixels along the line is stored in LineIterator::count. -The method LineIterator::pos returns the current position in the image: - -@code{.cpp} -// grabs pixels along the line (pt1, pt2) -// from 8-bit 3-channel image to the buffer -LineIterator it(img, pt1, pt2, 8); -LineIterator it2 = it; -vector buf(it.count); - -for(int i = 0; i < it.count; i++, ++it) - buf[i] = *(const Vec3b*)*it; - -// alternative way of iterating through the line -for(int i = 0; i < it2.count; i++, ++it2) -{ - Vec3b val = img.at(it2.pos()); - CV_Assert(buf[i] == val); -} -@endcode -*/ -class CV_EXPORTS LineIterator -{ -public: - /** @brief Initializes iterator object for the given line and image. - - The returned iterator can be used to traverse all pixels on a line that - connects the given two points. - The line will be clipped on the image boundaries. - - @param img Underlying image. - @param pt1 First endpoint of the line. - @param pt2 The other endpoint of the line. - @param connectivity Pixel connectivity of the iterator. Valid values are 4 (iterator can move - up, down, left and right) and 8 (iterator can also move diagonally). - @param leftToRight If true, the line is traversed from the leftmost endpoint to the rightmost - endpoint. Otherwise, the line is traversed from \p pt1 to \p pt2. - */ - LineIterator( const Mat& img, Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(&img, Rect(0, 0, img.cols, img.rows), pt1, pt2, connectivity, leftToRight); - ptmode = false; - } - LineIterator( Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(0, Rect(std::min(pt1.x, pt2.x), - std::min(pt1.y, pt2.y), - std::max(pt1.x, pt2.x) - std::min(pt1.x, pt2.x) + 1, - std::max(pt1.y, pt2.y) - std::min(pt1.y, pt2.y) + 1), - pt1, pt2, connectivity, leftToRight); - ptmode = true; - } - LineIterator( Size boundingAreaSize, Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(0, Rect(0, 0, boundingAreaSize.width, boundingAreaSize.height), - pt1, pt2, connectivity, leftToRight); - ptmode = true; - } - LineIterator( Rect boundingAreaRect, Point pt1, Point pt2, - int connectivity = 8, bool leftToRight = false ) - { - init(0, boundingAreaRect, pt1, pt2, connectivity, leftToRight); - ptmode = true; - } - void init(const Mat* img, Rect boundingAreaRect, Point pt1, Point pt2, int connectivity, bool leftToRight); - - /** @brief Returns pointer to the current pixel. - */ - uchar* operator *(); - - /** @brief Moves iterator to the next pixel on the line. - - This is the prefix version (++it). - */ - LineIterator& operator ++(); - - /** @brief Moves iterator to the next pixel on the line. - - This is the postfix version (it++). - */ - LineIterator operator ++(int); - - /** @brief Returns coordinates of the current pixel. - */ - Point pos() const; - - uchar* ptr; - const uchar* ptr0; - int step, elemSize; - int err, count; - int minusDelta, plusDelta; - int minusStep, plusStep; - int minusShift, plusShift; - Point p; - bool ptmode; -}; - -//! @cond IGNORED - -// === LineIterator implementation === - -inline -uchar* LineIterator::operator *() -{ - return ptmode ? 0 : ptr; -} - -inline -LineIterator& LineIterator::operator ++() -{ - int mask = err < 0 ? -1 : 0; - err += minusDelta + (plusDelta & mask); - if(!ptmode) - { - ptr += minusStep + (plusStep & mask); - } - else - { - p.x += minusShift + (plusShift & mask); - p.y += minusStep + (plusStep & mask); - } - return *this; -} - -inline -LineIterator LineIterator::operator ++(int) -{ - LineIterator it = *this; - ++(*this); - return it; -} - -inline -Point LineIterator::pos() const -{ - if(!ptmode) - { - size_t offset = (size_t)(ptr - ptr0); - int y = (int)(offset/step); - int x = (int)((offset - (size_t)y*step)/elemSize); - return Point(x, y); - } - return p; -} - -//! @endcond - -//! @} imgproc_draw - -//! @} imgproc - -} // cv - - -#include "./imgproc/segmentation.hpp" - - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_IMGPROC_HPP +#define OPENCV_IMGPROC_HPP + +#include "opencv2/core.hpp" + +/** +@defgroup imgproc Image Processing + +This module offers a comprehensive suite of image processing functions, enabling tasks such as those listed above. + +@{ + @defgroup imgproc_filter Image Filtering + + Functions and classes described in this section are used to perform various linear or non-linear + filtering operations on 2D images (represented as Mat's). It means that for each pixel location + \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to + compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of + morphological operations, it is the minimum or maximum values, and so on. The computed response is + stored in the destination image at the same location \f$(x,y)\f$. It means that the output image + will be of the same size as the input image. Normally, the functions support multi-channel arrays, + in which case every channel is processed independently. Therefore, the output image will also have + the same number of channels as the input one. + + Another common feature of the functions and classes described in this section is that, unlike + simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For + example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when + processing the left-most pixels in each row, you need pixels to the left of them, that is, outside + of the image. You can let these pixels be the same as the left-most image pixels ("replicated + border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant + border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method. + For details, see #BorderTypes + + @anchor filter_depths + ### Depth combinations + Input depth (src.depth()) | Output depth (ddepth) + --------------------------|---------------------- + CV_8U | -1/CV_16S/CV_32F/CV_64F + CV_16U/CV_16S | -1/CV_32F/CV_64F + CV_32F | -1/CV_32F + CV_64F | -1/CV_64F + + @note when ddepth=-1, the output image will have the same depth as the source. + + @note if you need double floating-point accuracy and using single floating-point input data + (CV_32F input and CV_64F output depth combination), you can use @ref Mat.convertTo to convert + the input data to the desired precision. + + @defgroup imgproc_transform Geometric Image Transformations + + The functions in this section perform various geometrical transformations of 2D images. They do not + change the image content but deform the pixel grid and map this deformed grid to the destination + image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from + destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the + functions compute coordinates of the corresponding "donor" pixel in the source image and copy the + pixel value: + + \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f] + + In case when you specify the forward mapping \f$\left: \texttt{src} \rightarrow + \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping + \f$\left: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula. + + The actual implementations of the geometrical transformations, from the most generic remap and to + the simplest and the fastest resize, need to solve two main problems with the above formula: + + - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the + previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both + of them may fall outside of the image. In this case, an extrapolation method needs to be used. + OpenCV provides the same selection of extrapolation methods as in the filtering functions. In + addition, it provides the method #BORDER_TRANSPARENT. This means that the corresponding pixels in + the destination image will not be modified at all. + + - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point + numbers. This means that \f$\left\f$ can be either an affine or perspective + transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional + coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the + nearest integer coordinates and the corresponding pixel can be used. This is called a + nearest-neighbor interpolation. However, a better result can be achieved by using more + sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) , + where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y), + f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the + interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See + #resize for details. + + @note The geometrical transformations do not work with `CV_8S` or `CV_32S` images. + + @defgroup imgproc_misc Miscellaneous Image Transformations + @defgroup imgproc_draw Drawing Functions + + Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be + rendered with antialiasing (implemented only for 8-bit images for now). All the functions include + the parameter color that uses an RGB value (that may be constructed with the Scalar constructor ) + for color images and brightness for grayscale images. For color images, the channel ordering is + normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a + color using the Scalar constructor, it should look like: + + \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f] + + If you are using your own image rendering and I/O functions, you can use any channel ordering. The + drawing functions process each channel independently and do not depend on the channel order or even + on the used color space. The whole image can be converted from BGR to RGB or to a different color + space using cvtColor . + + If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, + many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means + that the coordinates can be passed as fixed-point numbers encoded as integers. The number of + fractional bits is specified by the shift parameter and the real point coordinates are calculated as + \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is + especially effective when rendering antialiased shapes. + + @note The functions do not support alpha-transparency when the target image is 4-channel. In this + case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint + semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main + image. + + @defgroup imgproc_color_conversions Color Space Conversions + @defgroup imgproc_colormap ColorMaps in OpenCV + + The human perception isn't built for observing fine changes in grayscale images. Human eyes are more + sensitive to observing changes between colors, so you often need to recolor your grayscale images to + get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your + computer vision application. + + In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample + code reads the path to an image from command line, applies a Jet colormap on it and shows the + result: + + @include snippets/imgproc_applyColorMap.cpp + + @see #ColormapTypes + + @defgroup imgproc_subdiv2d Planar Subdivision + + The Subdiv2D class described in this section is used to perform various planar subdivision on + a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles + using the Delaunay's algorithm, which corresponds to the dual graph of the Voronoi diagram. + In the figure below, the Delaunay's triangulation is marked with black lines and the Voronoi + diagram with red lines. + + ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png) + + The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast + location of points on the plane, building special graphs (such as NNG,RNG), and so forth. + + @defgroup imgproc_hist Histograms + @defgroup imgproc_shape Structural Analysis and Shape Descriptors + @defgroup imgproc_motion Motion Analysis and Object Tracking + @defgroup imgproc_feature Feature Detection + @defgroup imgproc_object Object Detection + @defgroup imgproc_segmentation Image Segmentation + @defgroup imgproc_hal Hardware Acceleration Layer + @{ + @defgroup imgproc_hal_functions Functions + @defgroup imgproc_hal_interface Interface + @} + @} +*/ + +namespace cv +{ + +/** @addtogroup imgproc +@{ +*/ + +//! @addtogroup imgproc_filter +//! @{ + +enum SpecialFilter { + FILTER_SCHARR = -1 +}; + +//! type of morphological operation +enum MorphTypes{ + MORPH_ERODE = 0, //!< see #erode + MORPH_DILATE = 1, //!< see #dilate + MORPH_OPEN = 2, //!< an opening operation + //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] + MORPH_CLOSE = 3, //!< a closing operation + //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] + MORPH_GRADIENT = 4, //!< a morphological gradient + //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] + MORPH_TOPHAT = 5, //!< "top hat" + //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] + MORPH_BLACKHAT = 6, //!< "black hat" + //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] + MORPH_HITMISS = 7 //!< "hit or miss" + //!< .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation +}; + +//! shape of the structuring element +enum MorphShapes { + MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f] + MORPH_CROSS = 1, //!< a cross-shaped structuring element: + //!< \f[E_{ij} = \begin{cases} 1 & \texttt{if } {i=\texttt{anchor.y } {or } {j=\texttt{anchor.x}}} \\0 & \texttt{otherwise} \end{cases}\f] + MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed + //!< into the rectangle Rect(0, 0, esize.width, esize.height) +}; + +//! @} imgproc_filter + +//! @addtogroup imgproc_transform +//! @{ + +//! interpolation algorithm +enum InterpolationFlags{ + /** nearest neighbor interpolation */ + INTER_NEAREST = 0, + /** bilinear interpolation */ + INTER_LINEAR = 1, + /** bicubic interpolation */ + INTER_CUBIC = 2, + /** resampling using pixel area relation. It may be a preferred method for image decimation, as + it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST + method. */ + INTER_AREA = 3, + /** Lanczos interpolation over 8x8 neighborhood */ + INTER_LANCZOS4 = 4, + /** Bit exact bilinear interpolation */ + INTER_LINEAR_EXACT = 5, + /** Bit exact nearest neighbor interpolation. This will produce same results as + the nearest neighbor method in PIL, scikit-image or Matlab. */ + INTER_NEAREST_EXACT = 6, + /** mask for interpolation codes */ + INTER_MAX = 7, + /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the + source image, they are set to zero */ + WARP_FILL_OUTLIERS = 8, + /** flag, inverse transformation + + For example, #linearPolar or #logPolar transforms: + - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$ + - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$ + */ + WARP_INVERSE_MAP = 16, + WARP_RELATIVE_MAP = 32 +}; + +/** \brief Specify the polar mapping mode +@sa warpPolar +*/ +enum WarpPolarMode +{ + WARP_POLAR_LINEAR = 0, ///< Remaps an image to/from polar space. + WARP_POLAR_LOG = 256 ///< Remaps an image to/from semilog-polar space. +}; + +enum InterpolationMasks { + INTER_BITS = 5, + INTER_BITS2 = INTER_BITS * 2, + INTER_TAB_SIZE = 1 << INTER_BITS, + INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE + }; + +//! @} imgproc_transform + +//! @addtogroup imgproc_misc +//! @{ + +//! Distance types for Distance Transform and M-estimators +//! @see distanceTransform, fitLine +enum DistanceTypes { + DIST_USER = -1, //!< User defined distance + DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2| + DIST_L2 = 2, //!< the simple euclidean distance + DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|) + DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) + DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 + DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 + DIST_HUBER = 7 //!< distance = |x| \texttt{thresh}\)}{0}{otherwise}\f] + THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] + THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] + THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] + THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] + THRESH_MASK = 7, + THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value + THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value +}; + +//! adaptive threshold algorithm +//! @see adaptiveThreshold +enum AdaptiveThresholdTypes { + /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times + \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */ + ADAPTIVE_THRESH_MEAN_C = 0, + /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian + window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ + minus C . The default sigma (standard deviation) is used for the specified blockSize . See + #getGaussianKernel*/ + ADAPTIVE_THRESH_GAUSSIAN_C = 1 +}; + +//! class of the pixel in GrabCut algorithm +enum GrabCutClasses { + GC_BGD = 0, //!< an obvious background pixels + GC_FGD = 1, //!< an obvious foreground (object) pixel + GC_PR_BGD = 2, //!< a possible background pixel + GC_PR_FGD = 3 //!< a possible foreground pixel +}; + +//! GrabCut algorithm flags +enum GrabCutModes { + /** The function initializes the state and the mask using the provided rectangle. After that it + runs iterCount iterations of the algorithm. */ + GC_INIT_WITH_RECT = 0, + /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT + and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are + automatically initialized with GC_BGD .*/ + GC_INIT_WITH_MASK = 1, + /** The value means that the algorithm should just resume. */ + GC_EVAL = 2, + /** The value means that the algorithm should just run the grabCut algorithm (a single iteration) with the fixed model */ + GC_EVAL_FREEZE_MODEL = 3 +}; + +//! distanceTransform algorithm flags +enum DistanceTransformLabelTypes { + /** each connected component of zeros in src (as well as all the non-zero pixels closest to the + connected component) will be assigned the same label */ + DIST_LABEL_CCOMP = 0, + /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */ + DIST_LABEL_PIXEL = 1 +}; + +//! floodfill algorithm flags +enum FloodFillFlags { + /** If set, the difference between the current pixel and seed pixel is considered. Otherwise, + the difference between neighbor pixels is considered (that is, the range is floating). */ + FLOODFILL_FIXED_RANGE = 1 << 16, + /** If set, the function does not change the image ( newVal is ignored), and only fills the + mask with the value specified in bits 8-16 of flags as described above. This option only make + sense in function variants that have the mask parameter. */ + FLOODFILL_MASK_ONLY = 1 << 17 +}; + +//! @} imgproc_misc + +//! @addtogroup imgproc_shape +//! @{ + +//! connected components statistics +enum ConnectedComponentsTypes { + CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding + //!< box in the horizontal direction. + CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding + //!< box in the vertical direction. + CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box + CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box + CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component +#ifndef CV_DOXYGEN + CC_STAT_MAX = 5 //!< Max enumeration value. Used internally only for memory allocation +#endif +}; + +//! connected components algorithm +enum ConnectedComponentsAlgorithmsTypes { + CCL_DEFAULT = -1, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. + CCL_WU = 0, //!< SAUF @cite Wu2009 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for SAUF. + CCL_GRANA = 1, //!< BBDT @cite Grana2010 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both BBDT and SAUF. + CCL_BOLELLI = 2, //!< Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, Spaghetti4C @cite Bolelli2021 algorithm for 4-way connectivity. The parallel implementation described in @cite Bolelli2017 is available for both Spaghetti and Spaghetti4C. + CCL_SAUF = 3, //!< Same as CCL_WU. It is preferable to use the flag with the name of the algorithm (CCL_SAUF) rather than the one with the name of the first author (CCL_WU). + CCL_BBDT = 4, //!< Same as CCL_GRANA. It is preferable to use the flag with the name of the algorithm (CCL_BBDT) rather than the one with the name of the first author (CCL_GRANA). + CCL_SPAGHETTI = 5, //!< Same as CCL_BOLELLI. It is preferable to use the flag with the name of the algorithm (CCL_SPAGHETTI) rather than the one with the name of the first author (CCL_BOLELLI). +}; + +//! mode of the contour retrieval algorithm +enum RetrievalModes { + /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for + all the contours. */ + RETR_EXTERNAL = 0, + /** retrieves all of the contours without establishing any hierarchical relationships. */ + RETR_LIST = 1, + /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top + level, there are external boundaries of the components. At the second level, there are + boundaries of the holes. If there is another contour inside a hole of a connected component, it + is still put at the top level. */ + RETR_CCOMP = 2, + /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/ + RETR_TREE = 3, + RETR_FLOODFILL = 4 //!< +}; + +//! the contour approximation algorithm +enum ContourApproximationModes { + /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and + (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, + max(abs(x1-x2),abs(y2-y1))==1. */ + CHAIN_APPROX_NONE = 1, + /** compresses horizontal, vertical, and diagonal segments and leaves only their end points. + For example, an up-right rectangular contour is encoded with 4 points. */ + CHAIN_APPROX_SIMPLE = 2, + /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ + CHAIN_APPROX_TC89_L1 = 3, + /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ + CHAIN_APPROX_TC89_KCOS = 4 +}; + +/** @brief Shape matching methods + +\f$A\f$ denotes object1,\f$B\f$ denotes object2 + +\f$\begin{array}{l} m^A_i = \mathrm{sign} (h^A_i) \cdot \log{h^A_i} \\ m^B_i = \mathrm{sign} (h^B_i) \cdot \log{h^B_i} \end{array}\f$ + +and \f$h^A_i, h^B_i\f$ are the Hu moments of \f$A\f$ and \f$B\f$ , respectively. +*/ +enum ShapeMatchModes { + CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] + CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] + CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] +}; + +//! @} imgproc_shape + +//! @addtogroup imgproc_feature +//! @{ + +//! Variants of a Hough transform +enum HoughModes { + + /** classical or standard Hough transform. Every line is represented by two floating-point + numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line, + and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must + be (the created sequence will be) of CV_32FC2 type */ + HOUGH_STANDARD = 0, + /** probabilistic Hough transform (more efficient in case if the picture contains a few long + linear segments). It returns line segments rather than the whole line. Each segment is + represented by starting and ending points, and the matrix must be (the created sequence will + be) of the CV_32SC4 type. */ + HOUGH_PROBABILISTIC = 1, + /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as + HOUGH_STANDARD. */ + HOUGH_MULTI_SCALE = 2, + HOUGH_GRADIENT = 3, //!< basically *21HT*, described in @cite Yuen90 + HOUGH_GRADIENT_ALT = 4, //!< variation of HOUGH_GRADIENT to get better accuracy +}; + +//! Variants of Line Segment %Detector +enum LineSegmentDetectorModes { + LSD_REFINE_NONE = 0, //!< No refinement applied + LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations. + LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are + //!< refined through increase of precision, decrement in size, etc. +}; + +//! @} imgproc_feature + +/** Histogram comparison methods + @ingroup imgproc_hist +*/ +enum HistCompMethods { + /** Correlation + \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] + where + \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] + and \f$N\f$ is a total number of histogram bins. */ + HISTCMP_CORREL = 0, + /** Chi-Square + \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */ + HISTCMP_CHISQR = 1, + /** Intersection + \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */ + HISTCMP_INTERSECT = 2, + /** Bhattacharyya distance + (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.) + \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */ + HISTCMP_BHATTACHARYYA = 3, + HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA + /** Alternative Chi-Square + \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] + This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */ + HISTCMP_CHISQR_ALT = 4, + /** Kullback-Leibler divergence + \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */ + HISTCMP_KL_DIV = 5 +}; + +/** the color conversion codes +@see @ref imgproc_color_conversions +@ingroup imgproc_color_conversions + */ +enum ColorConversionCodes { + COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image + COLOR_RGB2RGBA = COLOR_BGR2BGRA, + + COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image + COLOR_RGBA2RGB = COLOR_BGRA2BGR, + + COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) + COLOR_RGB2BGRA = COLOR_BGR2RGBA, + + COLOR_RGBA2BGR = 3, + COLOR_BGRA2RGB = COLOR_RGBA2BGR, + + COLOR_BGR2RGB = 4, + COLOR_RGB2BGR = COLOR_BGR2RGB, + + COLOR_BGRA2RGBA = 5, + COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, + + COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions" + COLOR_RGB2GRAY = 7, + COLOR_GRAY2BGR = 8, + COLOR_GRAY2RGB = COLOR_GRAY2BGR, + COLOR_GRAY2BGRA = 9, + COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, + COLOR_BGRA2GRAY = 10, + COLOR_RGBA2GRAY = 11, + + COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) + COLOR_RGB2BGR565 = 13, + COLOR_BGR5652BGR = 14, + COLOR_BGR5652RGB = 15, + COLOR_BGRA2BGR565 = 16, + COLOR_RGBA2BGR565 = 17, + COLOR_BGR5652BGRA = 18, + COLOR_BGR5652RGBA = 19, + + COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) + COLOR_BGR5652GRAY = 21, + + COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) + COLOR_RGB2BGR555 = 23, + COLOR_BGR5552BGR = 24, + COLOR_BGR5552RGB = 25, + COLOR_BGRA2BGR555 = 26, + COLOR_RGBA2BGR555 = 27, + COLOR_BGR5552BGRA = 28, + COLOR_BGR5552RGBA = 29, + + COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) + COLOR_BGR5552GRAY = 31, + + COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions" + COLOR_RGB2XYZ = 33, + COLOR_XYZ2BGR = 34, + COLOR_XYZ2RGB = 35, + + COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions" + COLOR_RGB2YCrCb = 37, + COLOR_YCrCb2BGR = 38, + COLOR_YCrCb2RGB = 39, + + COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" + COLOR_RGB2HSV = 41, + + COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions" + COLOR_RGB2Lab = 45, + + COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions" + COLOR_RGB2Luv = 51, + COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..180 if 8 bit image, @ref color_convert_rgb_hls "color conversions" + COLOR_RGB2HLS = 53, + + COLOR_HSV2BGR = 54, //!< backward conversions HSV to RGB/BGR with H range 0..180 if 8 bit image + COLOR_HSV2RGB = 55, + + COLOR_Lab2BGR = 56, + COLOR_Lab2RGB = 57, + COLOR_Luv2BGR = 58, + COLOR_Luv2RGB = 59, + COLOR_HLS2BGR = 60, //!< backward conversions HLS to RGB/BGR with H range 0..180 if 8 bit image + COLOR_HLS2RGB = 61, + + COLOR_BGR2HSV_FULL = 66, //!< convert RGB/BGR to HSV (hue saturation value) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hsv "color conversions" + COLOR_RGB2HSV_FULL = 67, + COLOR_BGR2HLS_FULL = 68, //!< convert RGB/BGR to HLS (hue lightness saturation) with H range 0..255 if 8 bit image, @ref color_convert_rgb_hls "color conversions" + COLOR_RGB2HLS_FULL = 69, + + COLOR_HSV2BGR_FULL = 70, //!< backward conversions HSV to RGB/BGR with H range 0..255 if 8 bit image + COLOR_HSV2RGB_FULL = 71, + COLOR_HLS2BGR_FULL = 72, //!< backward conversions HLS to RGB/BGR with H range 0..255 if 8 bit image + COLOR_HLS2RGB_FULL = 73, + + COLOR_LBGR2Lab = 74, + COLOR_LRGB2Lab = 75, + COLOR_LBGR2Luv = 76, + COLOR_LRGB2Luv = 77, + + COLOR_Lab2LBGR = 78, + COLOR_Lab2LRGB = 79, + COLOR_Luv2LBGR = 80, + COLOR_Luv2LRGB = 81, + + COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV + COLOR_RGB2YUV = 83, + COLOR_YUV2BGR = 84, + COLOR_YUV2RGB = 85, + + COLOR_YUV2RGB_NV12 = 90, //!< convert between 4:2:0-subsampled YUV NV12 and RGB, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_NV12 = 91, //!< convert between 4:2:0-subsampled YUV NV12 and BGR, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_NV21 = 92, //!< convert between 4:2:0-subsampled YUV NV21 and RGB, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_NV21 = 93, //!< convert between 4:2:0-subsampled YUV NV21 and BGR, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, //!< synonym to NV21 + COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, //!< synonym to NV21 + + COLOR_YUV2RGBA_NV12 = 94, //!< convert between 4:2:0-subsampled YUV NV12 and RGBA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_NV12 = 95, //!< convert between 4:2:0-subsampled YUV NV12 and BGRA, two planes (in one or separate arrays): Y and U/V interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_NV21 = 96, //!< convert between 4:2:0-subsampled YUV NV21 and RGBA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_NV21 = 97, //!< convert between 4:2:0-subsampled YUV NV21 and BGRA, two planes (in one or separate arrays): Y and V/U interleaved, see @ref color_convert_rgb_yuv_42x + COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, //!< synonym to NV21 + COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, //!< synonym to NV21 + + COLOR_YUV2RGB_YV12 = 98, //!< convert between 4:2:0-subsampled YUV YV12 and RGB, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_YV12 = 99, //!< convert between 4:2:0-subsampled YUV YV12 and BGR, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_IYUV = 100, //!< convert between 4:2:0-subsampled YUV IYUV and RGB, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_IYUV = 101, //!< convert between 4:2:0-subsampled YUV IYUV and BGR, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, //!< synonym to IYUV + COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, //!< synonym to IYUV + COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, //!< synonym to YV12 + COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, //!< synonym to YV12 + + COLOR_YUV2RGBA_YV12 = 102, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_YV12 = 103, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_IYUV = 104, //!< convert between 4:2:0-subsampled YUV YV12 and RGBA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_IYUV = 105, //!< convert between 4:2:0-subsampled YUV YV12 and BGRA, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, //!< synonym to IYUV + COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, //!< synonym to IYUV + COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, //!< synonym to YV12 + COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, //!< synonym to YV12 + + COLOR_YUV2GRAY_420 = 106, //!< extract Y channel from YUV 4:2:0 image + COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, //!< synonym to COLOR_YUV2GRAY_420 + + COLOR_YUV2RGB_UYVY = 107, //!< convert between YUV UYVY and RGB, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_UYVY = 108, //!< convert between YUV UYVY and BGR, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2RGB_VYUY = 109, //!< convert between YUV VYUY and RGB, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2BGR_VYUY = 110, //!< convert between YUV VYUY and BGR, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY + COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY + COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, //!< synonym to UYVY + COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, //!< synonym to UYVY + + COLOR_YUV2RGBA_UYVY = 111, //!< convert between YUV UYVY and RGBA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_UYVY = 112, //!< convert between YUV UYVY and BGRA, YUV is 4:2:2-subsampled and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2RGBA_VYUY = 113, //!< convert between YUV VYUY and RGBA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + //COLOR_YUV2BGRA_VYUY = 114, //!< convert between YUV VYUY and BGRA, YUV is 4:2:2-subsampled and interleaved as V/Y1/U/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY + COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY + COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, //!< synonym to UYVY + COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, //!< synonym to UYVY + + COLOR_YUV2RGB_YUY2 = 115, //!< convert between YUV YUY2 and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_YUY2 = 116, //!< convert between YUV YUY2 and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_YVYU = 117, //!< convert between YUV YVYU and RGB, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGR_YVYU = 118, //!< convert between YUV YVYU and BGR, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 + COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, //!< synonym to YUY2 + + COLOR_YUV2RGBA_YUY2 = 119, //!< convert between YUV YUY2 and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_YUY2 = 120, //!< convert between YUV YUY2 and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_YVYU = 121, //!< convert between YUV YVYU and RGBA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2BGRA_YVYU = 122, //!< convert between YUV YVYU and BGRA, YUV is 4:2:2-subsampled and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 + COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, //!< synonym to YUY2 + COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, //!< synonym to YUY2 + + COLOR_YUV2GRAY_UYVY = 123, //!< extract Y channel from YUV 4:2:2 image + COLOR_YUV2GRAY_YUY2 = 124, //!< extract Y channel from YUV 4:2:2 image + //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY + COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY + COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, //!< synonym to COLOR_YUV2GRAY_UYVY + COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 + COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 + COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //!< synonym to COLOR_YUV2GRAY_YUY2 + + //! alpha premultiplication + COLOR_RGBA2mRGBA = 125, + COLOR_mRGBA2RGBA = 126, + + COLOR_RGB2YUV_I420 = 127, //!< convert between RGB and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_I420 = 128, //!< convert between BGR and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, //!< synonym to I420 + COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, //!< synonym to I420 + + COLOR_RGBA2YUV_I420 = 129, //!< convert between RGBA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_I420 = 130, //!< convert between BGRA and 4:2:0-subsampled YUV I420, three planes in one array: Y, U and V, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, //!< synonym to I420 + COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, //!< synonym to I420 + COLOR_RGB2YUV_YV12 = 131, //!< convert between RGB and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_YV12 = 132, //!< convert between BGR and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_YV12 = 133, //!< convert between RGBA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_YV12 = 134, //!< convert between BGRA and 4:2:0-subsampled YUV YV12, three planes in one array: Y, V and U, see @ref color_convert_rgb_yuv_42x + + //! Demosaicing, see @ref color_convert_bayer "color conversions" for additional information + COLOR_BayerBG2BGR = 46, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGR = 47, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGR = 48, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGR = 49, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGR = COLOR_BayerBG2BGR, + COLOR_BayerGRBG2BGR = COLOR_BayerGB2BGR, + COLOR_BayerBGGR2BGR = COLOR_BayerRG2BGR, + COLOR_BayerGBRG2BGR = COLOR_BayerGR2BGR, + + COLOR_BayerRGGB2RGB = COLOR_BayerBGGR2BGR, + COLOR_BayerGRBG2RGB = COLOR_BayerGBRG2BGR, + COLOR_BayerBGGR2RGB = COLOR_BayerRGGB2BGR, + COLOR_BayerGBRG2RGB = COLOR_BayerGRBG2BGR, + + COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerBG2GRAY = 86, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2GRAY = 87, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2GRAY = 88, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2GRAY = 89, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2GRAY = COLOR_BayerBG2GRAY, + COLOR_BayerGRBG2GRAY = COLOR_BayerGB2GRAY, + COLOR_BayerBGGR2GRAY = COLOR_BayerRG2GRAY, + COLOR_BayerGBRG2GRAY = COLOR_BayerGR2GRAY, + + //! Demosaicing using Variable Number of Gradients + COLOR_BayerBG2BGR_VNG = 62, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGR_VNG = 63, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGR_VNG = 64, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGR_VNG = 65, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGR_VNG = COLOR_BayerBG2BGR_VNG, + COLOR_BayerGRBG2BGR_VNG = COLOR_BayerGB2BGR_VNG, + COLOR_BayerBGGR2BGR_VNG = COLOR_BayerRG2BGR_VNG, + COLOR_BayerGBRG2BGR_VNG = COLOR_BayerGR2BGR_VNG, + + COLOR_BayerRGGB2RGB_VNG = COLOR_BayerBGGR2BGR_VNG, + COLOR_BayerGRBG2RGB_VNG = COLOR_BayerGBRG2BGR_VNG, + COLOR_BayerBGGR2RGB_VNG = COLOR_BayerRGGB2BGR_VNG, + COLOR_BayerGBRG2RGB_VNG = COLOR_BayerGRBG2BGR_VNG, + + COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //!< equivalent to GBRG Bayer pattern + + //! Edge-Aware Demosaicing + COLOR_BayerBG2BGR_EA = 135, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGR_EA = 136, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGR_EA = 137, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGR_EA = 138, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGR_EA = COLOR_BayerBG2BGR_EA, + COLOR_BayerGRBG2BGR_EA = COLOR_BayerGB2BGR_EA, + COLOR_BayerBGGR2BGR_EA = COLOR_BayerRG2BGR_EA, + COLOR_BayerGBRG2BGR_EA = COLOR_BayerGR2BGR_EA, + + COLOR_BayerRGGB2RGB_EA = COLOR_BayerBGGR2BGR_EA, + COLOR_BayerGRBG2RGB_EA = COLOR_BayerGBRG2BGR_EA, + COLOR_BayerBGGR2RGB_EA = COLOR_BayerRGGB2BGR_EA, + COLOR_BayerGBRG2RGB_EA = COLOR_BayerGRBG2BGR_EA, + + COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, //!< equivalent to GBRG Bayer pattern + + //! Demosaicing with alpha channel + COLOR_BayerBG2BGRA = 139, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2BGRA = 140, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2BGRA = 141, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2BGRA = 142, //!< equivalent to GBRG Bayer pattern + + COLOR_BayerRGGB2BGRA = COLOR_BayerBG2BGRA, + COLOR_BayerGRBG2BGRA = COLOR_BayerGB2BGRA, + COLOR_BayerBGGR2BGRA = COLOR_BayerRG2BGRA, + COLOR_BayerGBRG2BGRA = COLOR_BayerGR2BGRA, + + COLOR_BayerRGGB2RGBA = COLOR_BayerBGGR2BGRA, + COLOR_BayerGRBG2RGBA = COLOR_BayerGBRG2BGRA, + COLOR_BayerBGGR2RGBA = COLOR_BayerRGGB2BGRA, + COLOR_BayerGBRG2RGBA = COLOR_BayerGRBG2BGRA, + + COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA, //!< equivalent to RGGB Bayer pattern + COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, //!< equivalent to GRBG Bayer pattern + COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, //!< equivalent to BGGR Bayer pattern + COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, //!< equivalent to GBRG Bayer pattern + + COLOR_RGB2YUV_UYVY = 143, //!< convert between RGB and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_UYVY = 144, //!< convert between BGR and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_Y422 = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY + COLOR_BGR2YUV_Y422 = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY + COLOR_RGB2YUV_UYNV = COLOR_RGB2YUV_UYVY, //!< synonym to UYVY + COLOR_BGR2YUV_UYNV = COLOR_BGR2YUV_UYVY, //!< synonym to UYVY + + COLOR_RGBA2YUV_UYVY = 145, //!< convert between RGBA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_UYVY = 146, //!< convert between BGRA and YUV UYVU, YUV is 4:2:2 and interleaved as U/Y1/V/Y2, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_Y422 = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY + COLOR_BGRA2YUV_Y422 = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY + COLOR_RGBA2YUV_UYNV = COLOR_RGBA2YUV_UYVY, //!< synonym to UYVY + COLOR_BGRA2YUV_UYNV = COLOR_BGRA2YUV_UYVY, //!< synonym to UYVY + + COLOR_RGB2YUV_YUY2 = 147, //!< convert between RGB and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_YUY2 = 148, //!< convert between BGR and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_YVYU = 149, //!< convert between RGB and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_BGR2YUV_YVYU = 150, //!< convert between BGR and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_RGB2YUV_YUYV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGR2YUV_YUYV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 + COLOR_RGB2YUV_YUNV = COLOR_RGB2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGR2YUV_YUNV = COLOR_BGR2YUV_YUY2, //!< synonym to YUY2 + + COLOR_RGBA2YUV_YUY2 = 151, //!< convert between RGBA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_YUY2 = 152, //!< convert between BGRA and YUV YUY2, YUV is 4:2:2 and interleaved as Y1/U/Y2/V, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_YVYU = 153, //!< convert between RGBA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_BGRA2YUV_YVYU = 154, //!< convert between BGRA and YUV YVYU, YUV is 4:2:2 and interleaved as Y1/V/Y2/U, see @ref color_convert_rgb_yuv_42x + COLOR_RGBA2YUV_YUYV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGRA2YUV_YUYV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 + COLOR_RGBA2YUV_YUNV = COLOR_RGBA2YUV_YUY2, //!< synonym to YUY2 + COLOR_BGRA2YUV_YUNV = COLOR_BGRA2YUV_YUY2, //!< synonym to YUY2 + + COLOR_COLORCVT_MAX = 155 +}; + +//! @addtogroup imgproc_shape +//! @{ + +//! types of intersection between rectangles +enum RectanglesIntersectTypes { + INTERSECT_NONE = 0, //!< No intersection + INTERSECT_PARTIAL = 1, //!< There is a partial intersection + INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other +}; + +/** types of line +@ingroup imgproc_draw +*/ +enum LineTypes { + FILLED = -1, + LINE_4 = 4, //!< 4-connected line + LINE_8 = 8, //!< 8-connected line + LINE_AA = 16 //!< antialiased line +}; + +/** Only a subset of Hershey fonts are supported +@ingroup imgproc_draw +*/ +enum HersheyFonts { + FONT_HERSHEY_SIMPLEX = 0, //!< normal size sans-serif font + FONT_HERSHEY_PLAIN = 1, //!< small size sans-serif font + FONT_HERSHEY_DUPLEX = 2, //!< normal size sans-serif font (more complex than FONT_HERSHEY_SIMPLEX) + FONT_HERSHEY_COMPLEX = 3, //!< normal size serif font + FONT_HERSHEY_TRIPLEX = 4, //!< normal size serif font (more complex than FONT_HERSHEY_COMPLEX) + FONT_HERSHEY_COMPLEX_SMALL = 5, //!< smaller version of FONT_HERSHEY_COMPLEX + FONT_HERSHEY_SCRIPT_SIMPLEX = 6, //!< hand-writing style font + FONT_HERSHEY_SCRIPT_COMPLEX = 7, //!< more complex variant of FONT_HERSHEY_SCRIPT_SIMPLEX + FONT_ITALIC = 16 //!< flag for italic font +}; + +/** Possible set of marker types used for the cv::drawMarker function +@ingroup imgproc_draw +*/ +enum MarkerTypes +{ + MARKER_CROSS = 0, //!< A crosshair marker shape + MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape + MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross + MARKER_DIAMOND = 3, //!< A diamond marker shape + MARKER_SQUARE = 4, //!< A square marker shape + MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape + MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape +}; + +/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform +*/ +class CV_EXPORTS_W GeneralizedHough : public Algorithm +{ +public: + //! set template to search + CV_WRAP virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; + CV_WRAP virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; + + //! find template on image + CV_WRAP virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; + CV_WRAP virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; + + //! Canny low threshold. + CV_WRAP virtual void setCannyLowThresh(int cannyLowThresh) = 0; + CV_WRAP virtual int getCannyLowThresh() const = 0; + + //! Canny high threshold. + CV_WRAP virtual void setCannyHighThresh(int cannyHighThresh) = 0; + CV_WRAP virtual int getCannyHighThresh() const = 0; + + //! Minimum distance between the centers of the detected objects. + CV_WRAP virtual void setMinDist(double minDist) = 0; + CV_WRAP virtual double getMinDist() const = 0; + + //! Inverse ratio of the accumulator resolution to the image resolution. + CV_WRAP virtual void setDp(double dp) = 0; + CV_WRAP virtual double getDp() const = 0; + + //! Maximal size of inner buffers. + CV_WRAP virtual void setMaxBufferSize(int maxBufferSize) = 0; + CV_WRAP virtual int getMaxBufferSize() const = 0; +}; + +/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform + +Detects position only without translation and rotation @cite Ballard1981 . +*/ +class CV_EXPORTS_W GeneralizedHoughBallard : public GeneralizedHough +{ +public: + //! R-Table levels. + CV_WRAP virtual void setLevels(int levels) = 0; + CV_WRAP virtual int getLevels() const = 0; + + //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. + CV_WRAP virtual void setVotesThreshold(int votesThreshold) = 0; + CV_WRAP virtual int getVotesThreshold() const = 0; +}; + +/** @brief finds arbitrary template in the grayscale image using Generalized Hough Transform + +Detects position, translation and rotation @cite Guil1999 . +*/ +class CV_EXPORTS_W GeneralizedHoughGuil : public GeneralizedHough +{ +public: + //! Angle difference in degrees between two points in feature. + CV_WRAP virtual void setXi(double xi) = 0; + CV_WRAP virtual double getXi() const = 0; + + //! Feature table levels. + CV_WRAP virtual void setLevels(int levels) = 0; + CV_WRAP virtual int getLevels() const = 0; + + //! Maximal difference between angles that treated as equal. + CV_WRAP virtual void setAngleEpsilon(double angleEpsilon) = 0; + CV_WRAP virtual double getAngleEpsilon() const = 0; + + //! Minimal rotation angle to detect in degrees. + CV_WRAP virtual void setMinAngle(double minAngle) = 0; + CV_WRAP virtual double getMinAngle() const = 0; + + //! Maximal rotation angle to detect in degrees. + CV_WRAP virtual void setMaxAngle(double maxAngle) = 0; + CV_WRAP virtual double getMaxAngle() const = 0; + + //! Angle step in degrees. + CV_WRAP virtual void setAngleStep(double angleStep) = 0; + CV_WRAP virtual double getAngleStep() const = 0; + + //! Angle votes threshold. + CV_WRAP virtual void setAngleThresh(int angleThresh) = 0; + CV_WRAP virtual int getAngleThresh() const = 0; + + //! Minimal scale to detect. + CV_WRAP virtual void setMinScale(double minScale) = 0; + CV_WRAP virtual double getMinScale() const = 0; + + //! Maximal scale to detect. + CV_WRAP virtual void setMaxScale(double maxScale) = 0; + CV_WRAP virtual double getMaxScale() const = 0; + + //! Scale step. + CV_WRAP virtual void setScaleStep(double scaleStep) = 0; + CV_WRAP virtual double getScaleStep() const = 0; + + //! Scale votes threshold. + CV_WRAP virtual void setScaleThresh(int scaleThresh) = 0; + CV_WRAP virtual int getScaleThresh() const = 0; + + //! Position votes threshold. + CV_WRAP virtual void setPosThresh(int posThresh) = 0; + CV_WRAP virtual int getPosThresh() const = 0; +}; + +//! @} imgproc_shape + +//! @addtogroup imgproc_hist +//! @{ + +/** @brief Base class for Contrast Limited Adaptive Histogram Equalization. +*/ +class CV_EXPORTS_W CLAHE : public Algorithm +{ +public: + /** @brief Equalizes the histogram of a grayscale image using Contrast Limited Adaptive Histogram Equalization. + + @param src Source image of type CV_8UC1 or CV_16UC1. + @param dst Destination image. + */ + CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; + + /** @brief Sets threshold for contrast limiting. + + @param clipLimit threshold value. + */ + CV_WRAP virtual void setClipLimit(double clipLimit) = 0; + + //! Returns threshold value for contrast limiting. + CV_WRAP virtual double getClipLimit() const = 0; + + /** @brief Sets size of grid for histogram equalization. Input image will be divided into + equally sized rectangular tiles. + + @param tileGridSize defines the number of tiles in row and column. + */ + CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; + + //!@brief Returns Size defines the number of tiles in row and column. + CV_WRAP virtual Size getTilesGridSize() const = 0; + + CV_WRAP virtual void collectGarbage() = 0; +}; + +//! @} imgproc_hist + +//! @addtogroup imgproc_subdiv2d +//! @{ + +class CV_EXPORTS_W Subdiv2D +{ +public: + /** Subdiv2D point location cases */ + enum { PTLOC_ERROR = -2, //!< Point location error + PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect + PTLOC_INSIDE = 0, //!< Point inside some facet + PTLOC_VERTEX = 1, //!< Point coincides with one of the subdivision vertices + PTLOC_ON_EDGE = 2 //!< Point on some edge + }; + + /** Subdiv2D edge type navigation (see: getEdge()) */ + enum { NEXT_AROUND_ORG = 0x00, + NEXT_AROUND_DST = 0x22, + PREV_AROUND_ORG = 0x11, + PREV_AROUND_DST = 0x33, + NEXT_AROUND_LEFT = 0x13, + NEXT_AROUND_RIGHT = 0x31, + PREV_AROUND_LEFT = 0x20, + PREV_AROUND_RIGHT = 0x02 + }; + + /** creates an empty Subdiv2D object. + To create a new empty Delaunay subdivision you need to use the #initDelaunay function. + */ + CV_WRAP Subdiv2D(); + + /** @overload + + @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. + + The function creates an empty Delaunay subdivision where 2D points can be added using the function + insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime + error is raised. + */ + CV_WRAP Subdiv2D(Rect rect); + + /** @brief Creates a new empty Delaunay subdivision + + @param rect Rectangle that includes all of the 2D points that are to be added to the subdivision. + + */ + CV_WRAP void initDelaunay(Rect rect); + + /** @brief Insert a single point into a Delaunay triangulation. + + @param pt Point to insert. + + The function inserts a single point into a subdivision and modifies the subdivision topology + appropriately. If a point with the same coordinates exists already, no new point is added. + @returns the ID of the point. + + @note If the point is outside of the triangulation specified rect a runtime error is raised. + */ + CV_WRAP int insert(Point2f pt); + + /** @brief Insert multiple points into a Delaunay triangulation. + + @param ptvec Points to insert. + + The function inserts a vector of points into a subdivision and modifies the subdivision topology + appropriately. + */ + CV_WRAP void insert(const std::vector& ptvec); + + /** @brief Returns the location of a point within a Delaunay triangulation. + + @param pt Point to locate. + @param edge Output edge that the point belongs to or is located to the right of it. + @param vertex Optional output vertex the input point coincides with. + + The function locates the input point within the subdivision and gives one of the triangle edges + or vertices. + + @returns an integer which specify one of the following five cases for point location: + - The point falls into some facet. The function returns #PTLOC_INSIDE and edge will contain one of + edges of the facet. + - The point falls onto the edge. The function returns #PTLOC_ON_EDGE and edge will contain this edge. + - The point coincides with one of the subdivision vertices. The function returns #PTLOC_VERTEX and + vertex will contain a pointer to the vertex. + - The point is outside the subdivision reference rectangle. The function returns #PTLOC_OUTSIDE_RECT + and no pointers are filled. + - One of input arguments is invalid. A runtime error is raised or, if silent or "parent" error + processing mode is selected, #PTLOC_ERROR is returned. + */ + CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); + + /** @brief Finds the subdivision vertex closest to the given point. + + @param pt Input point. + @param nearestPt Output subdivision vertex point. + + The function is another function that locates the input point within the subdivision. It finds the + subdivision vertex that is the closest to the input point. It is not necessarily one of vertices + of the facet containing the input point, though the facet (located using locate() ) is used as a + starting point. + + @returns vertex ID. + */ + CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); + + /** @brief Returns a list of all edges. + + @param edgeList Output vector. + + The function gives each edge as a 4 numbers vector, where each two are one of the edge + vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3]. + */ + CV_WRAP void getEdgeList(CV_OUT std::vector& edgeList) const; + + /** @brief Returns a list of the leading edge ID connected to each triangle. + + @param leadingEdgeList Output vector. + + The function gives one edge ID for each triangle. + */ + CV_WRAP void getLeadingEdgeList(CV_OUT std::vector& leadingEdgeList) const; + + /** @brief Returns a list of all triangles. + + @param triangleList Output vector. + + The function gives each triangle as a 6 numbers vector, where each two are one of the triangle + vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5]. + */ + CV_WRAP void getTriangleList(CV_OUT std::vector& triangleList) const; + + /** @brief Returns a list of all Voronoi facets. + + @param idx Vector of vertices IDs to consider. For all vertices you can pass empty vector. + @param facetList Output vector of the Voronoi facets. + @param facetCenters Output vector of the Voronoi facets center points. + + */ + CV_WRAP void getVoronoiFacetList(const std::vector& idx, CV_OUT std::vector >& facetList, + CV_OUT std::vector& facetCenters); + + /** @brief Returns vertex location from vertex ID. + + @param vertex vertex ID. + @param firstEdge Optional. The first edge ID which is connected to the vertex. + @returns vertex (x,y) + + */ + CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; + + /** @brief Returns one of the edges related to the given edge. + + @param edge Subdivision edge ID. + @param nextEdgeType Parameter specifying which of the related edges to return. + The following values are possible: + - NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge) + - NEXT_AROUND_DST next around the edge vertex ( eDnext ) + - PREV_AROUND_ORG previous around the edge origin (reversed eRnext ) + - PREV_AROUND_DST previous around the edge destination (reversed eLnext ) + - NEXT_AROUND_LEFT next around the left facet ( eLnext ) + - NEXT_AROUND_RIGHT next around the right facet ( eRnext ) + - PREV_AROUND_LEFT previous around the left facet (reversed eOnext ) + - PREV_AROUND_RIGHT previous around the right facet (reversed eDnext ) + + ![sample output](pics/quadedge.png) + + @returns edge ID related to the input edge. + */ + CV_WRAP int getEdge( int edge, int nextEdgeType ) const; + + /** @brief Returns next edge around the edge origin. + + @param edge Subdivision edge ID. + + @returns an integer which is next edge ID around the edge origin: eOnext on the + picture above if e is the input edge). + */ + CV_WRAP int nextEdge(int edge) const; + + /** @brief Returns another edge of the same quad-edge. + + @param edge Subdivision edge ID. + @param rotate Parameter specifying which of the edges of the same quad-edge as the input + one to return. The following values are possible: + - 0 - the input edge ( e on the picture below if e is the input edge) + - 1 - the rotated edge ( eRot ) + - 2 - the reversed edge (reversed e (in green)) + - 3 - the reversed rotated edge (reversed eRot (in green)) + + @returns one of the edges ID of the same quad-edge as the input edge. + */ + CV_WRAP int rotateEdge(int edge, int rotate) const; + CV_WRAP int symEdge(int edge) const; + + /** @brief Returns the edge origin. + + @param edge Subdivision edge ID. + @param orgpt Output vertex location. + + @returns vertex ID. + */ + CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; + + /** @brief Returns the edge destination. + + @param edge Subdivision edge ID. + @param dstpt Output vertex location. + + @returns vertex ID. + */ + CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; + +protected: + int newEdge(); + void deleteEdge(int edge); + int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); + void deletePoint(int vtx); + void setEdgePoints( int edge, int orgPt, int dstPt ); + void splice( int edgeA, int edgeB ); + int connectEdges( int edgeA, int edgeB ); + void swapEdges( int edge ); + int isRightOf(Point2f pt, int edge) const; + void calcVoronoi(); + void clearVoronoi(); + void checkSubdiv() const; + + struct CV_EXPORTS Vertex + { + Vertex(); + Vertex(Point2f pt, bool isvirtual, int firstEdge=0); + bool isvirtual() const; + bool isfree() const; + + int firstEdge; + int type; + Point2f pt; + }; + + struct CV_EXPORTS QuadEdge + { + QuadEdge(); + QuadEdge(int edgeidx); + bool isfree() const; + + int next[4]; + int pt[4]; + }; + + //! All of the vertices + std::vector vtx; + //! All of the edges + std::vector qedges; + int freeQEdge; + int freePoint; + bool validGeometry; + + int recentEdge; + //! Top left corner of the bounding rect + Point2f topLeft; + //! Bottom right corner of the bounding rect + Point2f bottomRight; +}; + +//! @} imgproc_subdiv2d + +//! @addtogroup imgproc_feature +//! @{ + +/** @example samples/cpp/lsd_lines.cpp +An example using the LineSegmentDetector +\image html building_lsd.png "Sample output image" width=434 height=300 +*/ + +/** @brief Line segment detector class + +following the algorithm described at @cite Rafael12 . + +@note Implementation has been removed from OpenCV version 3.4.6 to 3.4.15 and version 4.1.0 to 4.5.3 due original code license conflict. +restored again after [Computation of a NFA](https://github.com/rafael-grompone-von-gioi/binomial_nfa) code published under the MIT license. +*/ +class CV_EXPORTS_W LineSegmentDetector : public Algorithm +{ +public: + + /** @brief Finds lines in the input image. + + This is the output of the default parameters of the algorithm on the above shown image. + + ![image](pics/building_lsd.png) + + @param image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: + `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);` + @param lines A vector of Vec4f elements specifying the beginning and ending point of a line. Where + Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly + oriented depending on the gradient. + @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. + @param prec Vector of precisions with which the lines are found. + @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The + bigger the value, logarithmically better the detection. + - -1 corresponds to 10 mean false alarms + - 0 corresponds to 1 mean false alarm + - 1 corresponds to 0.1 mean false alarms + This vector will be calculated only when the objects type is #LSD_REFINE_ADV. + */ + CV_WRAP virtual void detect(InputArray image, OutputArray lines, + OutputArray width = noArray(), OutputArray prec = noArray(), + OutputArray nfa = noArray()) = 0; + + /** @brief Draws the line segments on a given image. + @param image The image, where the lines will be drawn. Should be bigger or equal to the image, + where the lines were found. + @param lines A vector of the lines that needed to be drawn. + */ + CV_WRAP virtual void drawSegments(InputOutputArray image, InputArray lines) = 0; + + /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. + + @param size The size of the image, where lines1 and lines2 were found. + @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. + @param lines2 The second group of lines. They visualized in red color. + @param image Optional image, where the lines will be drawn. The image should be color(3-channel) + in order for lines1 and lines2 to be drawn in the above mentioned colors. + */ + CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray image = noArray()) = 0; + + virtual ~LineSegmentDetector() { } +}; + +/** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it. + +The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want +to edit those, as to tailor it for their own application. + +@param refine The way found lines will be refined, see #LineSegmentDetectorModes +@param scale The scale of the image that will be used to find the lines. Range (0..1]. +@param sigma_scale Sigma for Gaussian filter. It is computed as sigma = sigma_scale/scale. +@param quant Bound to the quantization error on the gradient norm. +@param ang_th Gradient angle tolerance in degrees. +@param log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advance refinement is chosen. +@param density_th Minimal density of aligned region points in the enclosing rectangle. +@param n_bins Number of bins in pseudo-ordering of gradient modulus. + */ +CV_EXPORTS_W Ptr createLineSegmentDetector( + int refine = LSD_REFINE_STD, double scale = 0.8, + double sigma_scale = 0.6, double quant = 2.0, double ang_th = 22.5, + double log_eps = 0, double density_th = 0.7, int n_bins = 1024); + +//! @} imgproc_feature + +//! @addtogroup imgproc_filter +//! @{ + +/** @brief Returns Gaussian filter coefficients. + +The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter +coefficients: + +\f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f] + +where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$. + +Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize +smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. +You may also use the higher-level GaussianBlur. +@param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive. +@param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as +`sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8`. +@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . +@sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur + */ +CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); + +/** @brief Returns filter coefficients for computing spatial image derivatives. + +The function computes and returns the filter coefficients for spatial image derivatives. When +`ksize=FILTER_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see #Scharr). Otherwise, Sobel +kernels are generated (see #Sobel). The filters are normally passed to #sepFilter2D or to + +@param kx Output matrix of row filter coefficients. It has the type ktype . +@param ky Output matrix of column filter coefficients. It has the type ktype . +@param dx Derivative order in respect of x. +@param dy Derivative order in respect of y. +@param ksize Aperture size. It can be FILTER_SCHARR, 1, 3, 5, or 7. +@param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. +Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are +going to filter floating-point images, you are likely to use the normalized kernels. But if you +compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve +all the fractional bits, you may want to set normalize=false . +@param ktype Type of filter coefficients. It can be CV_32f or CV_64F . + */ +CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, + int dx, int dy, int ksize, + bool normalize = false, int ktype = CV_32F ); + +/** @brief Returns Gabor filter coefficients. + +For more details about gabor filter equations and parameters, see: [Gabor +Filter](http://en.wikipedia.org/wiki/Gabor_filter). + +@param ksize Size of the filter returned. +@param sigma Standard deviation of the gaussian envelope. +@param theta Orientation of the normal to the parallel stripes of a Gabor function. +@param lambd Wavelength of the sinusoidal factor. +@param gamma Spatial aspect ratio. +@param psi Phase offset. +@param ktype Type of filter coefficients. It can be CV_32F or CV_64F . + */ +CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, + double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); + +//! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. +static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } + +/** @brief Returns a structuring element of the specified size and shape for morphological operations. + +The function constructs and returns the structuring element that can be further passed to #erode, +#dilate or #morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as +the structuring element. + +@param shape Element shape that could be one of #MorphShapes +@param ksize Size of the structuring element. +@param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the +anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor +position. In other cases the anchor just regulates how much the result of the morphological +operation is shifted. + */ +CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); + +/** @example samples/cpp/tutorial_code/ImgProc/Smoothing/Smoothing.cpp +Sample code for simple filters +![Sample screenshot](Smoothing_Tutorial_Result_Median_Filter.jpg) +Check @ref tutorial_gausian_median_blur_bilateral_filter "the corresponding tutorial" for more details + */ + +/** @brief Blurs an image using the median filter. + +The function smoothes an image using the median filter with the \f$\texttt{ksize} \times +\texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. +In-place operation is supported. + +@note The median filter uses #BORDER_REPLICATE internally to cope with border pixels, see #BorderTypes + +@param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be +CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. +@param dst destination array of the same size and type as src. +@param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... +@sa bilateralFilter, blur, boxFilter, GaussianBlur + */ +CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); + +/** @brief Blurs an image using a Gaussian filter. + +The function convolves the source image with the specified Gaussian kernel. In-place filtering is +supported. + +@param src input image; the image can have any number of channels, which are processed +independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be +positive and odd. Or, they can be zero's and then they are computed from sigma. +@param sigmaX Gaussian kernel standard deviation in X direction. +@param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be +equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, +respectively (see #getGaussianKernel for details); to fully control the result regardless of +possible future modifications of all this semantics, it is recommended to specify all of ksize, +sigmaX, and sigmaY. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param hint Implementation modfication flags. See #AlgorithmHint + +@sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur + */ +CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, + double sigmaX, double sigmaY = 0, + int borderType = BORDER_DEFAULT, + AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); + +/** @brief Applies the bilateral filter to an image. + +The function applies bilateral filtering to the input image, as described in +http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html +bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is +very slow compared to most filters. + +_Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< +10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very +strong effect, making the image look "cartoonish". + +_Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time +applications, and perhaps d=9 for offline applications that need heavy noise filtering. + +This filter does not work inplace. +@param src Source 8-bit or floating-point, 1-channel or 3-channel image. +@param dst Destination image of the same size and type as src . +@param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, +it is computed from sigmaSpace. +@param sigmaColor Filter sigma in the color space. A larger value of the parameter means that +farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting +in larger areas of semi-equal color. +@param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that +farther pixels will influence each other as long as their colors are close enough (see sigmaColor +). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is +proportional to sigmaSpace. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes + */ +CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, + double sigmaColor, double sigmaSpace, + int borderType = BORDER_DEFAULT ); + +/** @brief Blurs an image using the box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] + +where + +\f[\alpha = \begin{cases} \frac{1}{\texttt{ksize.width*ksize.height}} & \texttt{when } \texttt{normalize=true} \\1 & \texttt{otherwise}\end{cases}\f] + +Unnormalized box filter is useful for computing various integral characteristics over each pixel +neighborhood, such as covariance matrices of image derivatives (used in dense optical flow +algorithms, and so on). If you need to compute pixel sums over variable-size windows, use #integral. + +@param src input image. +@param dst output image of the same size and type as src. +@param ddepth the output image depth (-1 to use src.depth()). +@param ksize blurring kernel size. +@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel +center. +@param normalize flag, specifying whether the kernel is normalized by its area or not. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. +@sa blur, bilateralFilter, GaussianBlur, medianBlur, integral + */ +CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, + Size ksize, Point anchor = Point(-1,-1), + bool normalize = true, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter. + +For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring +pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$. + +The unnormalized square box filter can be useful in computing local image statistics such as the local +variance and standard deviation around the neighborhood of a pixel. + +@param src input image +@param dst output image of the same size and type as src +@param ddepth the output image depth (-1 to use src.depth()) +@param ksize kernel size +@param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel +center. +@param normalize flag, specifying whether the kernel is to be normalized by it's area or not. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. +@sa boxFilter +*/ +CV_EXPORTS_W void sqrBoxFilter( InputArray src, OutputArray dst, int ddepth, + Size ksize, Point anchor = Point(-1, -1), + bool normalize = true, + int borderType = BORDER_DEFAULT ); + +/** @brief Blurs an image using the normalized box filter. + +The function smooths an image using the kernel: + +\f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] + +The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), ksize, +anchor, true, borderType)`. + +@param src input image; it can have any number of channels, which are processed independently, but +the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param ksize blurring kernel size. +@param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel +center. +@param borderType border mode used to extrapolate pixels outside of the image, see #BorderTypes. #BORDER_WRAP is not supported. +@sa boxFilter, bilateralFilter, GaussianBlur, medianBlur + */ +CV_EXPORTS_W void blur( InputArray src, OutputArray dst, + Size ksize, Point anchor = Point(-1,-1), + int borderType = BORDER_DEFAULT ); + +/** @brief Blurs an image using the stackBlur. + +The function applies and stackBlur to an image. +stackBlur can generate similar results as Gaussian blur, and the time consumption does not increase with the increase of kernel size. +It creates a kind of moving stack of colors whilst scanning through the image. Thereby it just has to add one new block of color to the right side +of the stack and remove the leftmost color. The remaining colors on the topmost layer of the stack are either added on or reduced by one, +depending on if they are on the right or on the left side of the stack. The only supported borderType is BORDER_REPLICATE. +Original paper was proposed by Mario Klingemann, which can be found http://underdestruction.com/2004/02/25/stackblur-2004. + +@param src input image. The number of channels can be arbitrary, but the depth should be one of +CV_8U, CV_16U, CV_16S or CV_32F. +@param dst output image of the same size and type as src. +@param ksize stack-blurring kernel size. The ksize.width and ksize.height can differ but they both must be +positive and odd. +*/ +CV_EXPORTS_W void stackBlur(InputArray src, OutputArray dst, Size ksize); + +/** @brief Convolves an image with the kernel. + +The function applies an arbitrary linear filter to an image. In-place operation is supported. When +the aperture is partially outside the image, the function interpolates outlier pixel values +according to the specified border mode. + +The function does actually compute correlation, not the convolution: + +\f[\texttt{dst} (x,y) = \sum _{ \substack{0\leq x' < \texttt{kernel.cols}\\{0\leq y' < \texttt{kernel.rows}}}} \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] + +That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip +the kernel using #flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - +anchor.y - 1)`. + +The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or +larger) and the direct algorithm for small kernels. + +@param src input image. +@param dst output image of the same size and the same number of channels as src. +@param ddepth desired depth of the destination image, see @ref filter_depths "combinations" +@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point +matrix; if you want to apply different kernels to different channels, split the image into +separate color planes using split and process them individually. +@param anchor anchor of the kernel that indicates the relative position of a filtered point within +the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor +is at the kernel center. +@param delta optional value added to the filtered pixels before storing them in dst. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa sepFilter2D, dft, matchTemplate + */ +CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, + InputArray kernel, Point anchor = Point(-1,-1), + double delta = 0, int borderType = BORDER_DEFAULT ); + +/** @brief Applies a separable linear filter to an image. + +The function applies a separable linear filter to the image. That is, first, every row of src is +filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D +kernel kernelY. The final result shifted by delta is stored in dst . + +@param src Source image. +@param dst Destination image of the same size and the same number of channels as src . +@param ddepth Destination image depth, see @ref filter_depths "combinations" +@param kernelX Coefficients for filtering each row. +@param kernelY Coefficients for filtering each column. +@param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor +is at the kernel center. +@param delta Value added to the filtered results before storing them. +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa filter2D, Sobel, GaussianBlur, boxFilter, blur + */ +CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, + InputArray kernelX, InputArray kernelY, + Point anchor = Point(-1,-1), + double delta = 0, int borderType = BORDER_DEFAULT ); + +/** @example samples/cpp/tutorial_code/ImgTrans/Sobel_Demo.cpp +Sample code using Sobel and/or Scharr OpenCV functions to make a simple Edge Detector +![Sample screenshot](Sobel_Derivatives_Tutorial_Result.jpg) +Check @ref tutorial_sobel_derivatives "the corresponding tutorial" for more details +*/ + +/** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. + +In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to +calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ +kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first +or the second x- or y- derivatives. + +There is also the special value `ksize = #FILTER_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr +filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is + +\f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] + +for the x-derivative, or transposed for the y-derivative. + +The function calculates an image derivative by convolving the image with the appropriate kernel: + +\f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] + +The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less +resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) +or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first +case corresponds to a kernel of: + +\f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] + +The second case corresponds to a kernel of: + +\f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] + +@param src input image. +@param dst output image of the same size and the same number of channels as src . +@param ddepth output image depth, see @ref filter_depths "combinations"; in the case of + 8-bit input images it will result in truncated derivatives. +@param dx order of the derivative x. +@param dy order of the derivative y. +@param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see #getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar + */ +CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, + int dx, int dy, int ksize = 3, + double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates the first order image derivative in both x and y using a Sobel operator + +Equivalent to calling: + +@code +Sobel( src, dx, CV_16SC1, 1, 0, 3 ); +Sobel( src, dy, CV_16SC1, 0, 1, 3 ); +@endcode + +@param src input image. +@param dx output image with first-order derivative in x. +@param dy output image with first-order derivative in y. +@param ksize size of Sobel kernel. It must be 3. +@param borderType pixel extrapolation method, see #BorderTypes. + Only #BORDER_DEFAULT=#BORDER_REFLECT_101 and #BORDER_REPLICATE are supported. + +@sa Sobel + */ + +CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx, + OutputArray dy, int ksize = 3, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates the first x- or y- image derivative using Scharr operator. + +The function computes the first x- or y- spatial image derivative using the Scharr operator. The +call + +\f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f] + +is equivalent to + +\f[\texttt{Sobel(src, dst, ddepth, dx, dy, FILTER_SCHARR, scale, delta, borderType)} .\f] + +@param src input image. +@param dst output image of the same size and the same number of channels as src. +@param ddepth output image depth, see @ref filter_depths "combinations" +@param dx order of the derivative x. +@param dy order of the derivative y. +@param scale optional scale factor for the computed derivative values; by default, no scaling is +applied (see #getDerivKernels for details). +@param delta optional delta value that is added to the results prior to storing them in dst. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa cartToPolar + */ +CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, + int dx, int dy, double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT ); + +/** @example samples/cpp/laplace.cpp +An example using Laplace transformations for edge detection +*/ + +/** @brief Calculates the Laplacian of an image. + +The function calculates the Laplacian of the source image by adding up the second x and y +derivatives calculated using the Sobel operator: + +\f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] + +This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image +with the following \f$3 \times 3\f$ aperture: + +\f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] + +@param src Source image. +@param dst Destination image of the same size and the same number of channels as src . +@param ddepth Desired depth of the destination image, see @ref filter_depths "combinations". +@param ksize Aperture size used to compute the second-derivative filters. See #getDerivKernels for +details. The size must be positive and odd. +@param scale Optional scale factor for the computed Laplacian values. By default, no scaling is +applied. See #getDerivKernels for details. +@param delta Optional delta value that is added to the results prior to storing them in dst . +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@sa Sobel, Scharr + */ +CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, + int ksize = 1, double scale = 1, double delta = 0, + int borderType = BORDER_DEFAULT ); + +//! @} imgproc_filter + +//! @addtogroup imgproc_feature +//! @{ + +/** @example samples/cpp/edge.cpp +This program demonstrates usage of the Canny edge detector + +Check @ref tutorial_canny_detector "the corresponding tutorial" for more details +*/ + +/** @brief Finds edges in an image using the Canny algorithm @cite Canny86 . + +The function finds edges in the input image and marks them in the output map edges using the +Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The +largest value is used to find initial segments of strong edges. See + + +@param image 8-bit input image. +@param edges output edge map; single channels 8-bit image, which has the same size as image . +@param threshold1 first threshold for the hysteresis procedure. +@param threshold2 second threshold for the hysteresis procedure. +@param apertureSize aperture size for the Sobel operator. +@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm +\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( +L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( +L2gradient=false ). + */ +CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, + double threshold1, double threshold2, + int apertureSize = 3, bool L2gradient = false ); + +/** \overload + +Finds edges in an image using the Canny algorithm with custom image gradient. + +@param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). +@param dy 16-bit y derivative of input image (same type as dx). +@param edges output edge map; single channels 8-bit image, which has the same size as image . +@param threshold1 first threshold for the hysteresis procedure. +@param threshold2 second threshold for the hysteresis procedure. +@param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm +\f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( +L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( +L2gradient=false ). + */ +CV_EXPORTS_W void Canny( InputArray dx, InputArray dy, + OutputArray edges, + double threshold1, double threshold2, + bool L2gradient = false ); + +/** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection. + +The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal +eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms +of the formulae in the cornerEigenValsAndVecs description. + +@param src Input single-channel 8-bit or floating-point image. +@param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as +src . +@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). +@param ksize Aperture parameter for the Sobel operator. +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + */ +CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, + int blockSize, int ksize = 3, + int borderType = BORDER_DEFAULT ); + +/** @brief Harris corner detector. + +The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and +cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance +matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it +computes the following characteristic: + +\f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f] + +Corners in the image can be found as the local maxima of this response map. + +@param src Input single-channel 8-bit or floating-point image. +@param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same +size as src . +@param blockSize Neighborhood size (see the details on #cornerEigenValsAndVecs ). +@param ksize Aperture parameter for the Sobel operator. +@param k Harris detector free parameter. See the formula above. +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + */ +CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, + int ksize, double k, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection. + +For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize +neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as: + +\f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f] + +where the derivatives are computed using the Sobel operator. + +After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as +\f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where + +- \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$ +- \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$ +- \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$ + +The output of the function can be used for robust edge or corner detection. + +@param src Input single-channel 8-bit or floating-point image. +@param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . +@param blockSize Neighborhood size (see details below). +@param ksize Aperture parameter for the Sobel operator. +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + +@sa cornerMinEigenVal, cornerHarris, preCornerDetect + */ +CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, + int blockSize, int ksize, + int borderType = BORDER_DEFAULT ); + +/** @brief Calculates a feature map for corner detection. + +The function calculates the complex spatial derivative-based function of the source image + +\f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f] + +where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image +derivatives, and \f$D_{xy}\f$ is the mixed derivative. + +The corners can be found as local maximums of the functions, as shown below: +@code + Mat corners, dilated_corners; + preCornerDetect(image, corners, 3); + // dilation with 3x3 rectangular structuring element + dilate(corners, dilated_corners, Mat(), 1); + Mat corner_mask = corners == dilated_corners; +@endcode + +@param src Source single-channel 8-bit of floating-point image. +@param dst Output image that has the type CV_32F and the same size as src . +@param ksize %Aperture size of the Sobel . +@param borderType Pixel extrapolation method. See #BorderTypes. #BORDER_WRAP is not supported. + */ +CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, + int borderType = BORDER_DEFAULT ); + +/** @brief Refines the corner locations. + +The function iterates to find the sub-pixel accurate location of corners or radial saddle +points as described in @cite forstner1987fast, and as shown on the figure below. + +![image](pics/cornersubpix.png) + +Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$ +to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$ +subject to image and measurement noise. Consider the expression: + +\f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f] + +where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The +value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up +with \f$\epsilon_i\f$ set to zero: + +\f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) \cdot q - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f] + +where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first +gradient term \f$G\f$ and the second gradient term \f$b\f$ gives: + +\f[q = G^{-1} \cdot b\f] + +The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates +until the center stays within a set threshold. + +@param image Input single-channel, 8-bit or float image. +@param corners Initial coordinates of the input corners and refined coordinates provided for +output. +@param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , +then a \f$(5*2+1) \times (5*2+1) = 11 \times 11\f$ search window is used. +@param zeroZone Half of the size of the dead region in the middle of the search zone over which +the summation in the formula below is not done. It is used sometimes to avoid possible +singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such +a size. +@param criteria Criteria for termination of the iterative process of corner refinement. That is, +the process of corner position refinement stops either after criteria.maxCount iterations or when +the corner position moves by less than criteria.epsilon on some iteration. + */ +CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, + Size winSize, Size zeroZone, + TermCriteria criteria ); + +/** @brief Determines strong corners on an image. + +The function finds the most prominent corners in the image or in the specified image region, as +described in @cite Shi94 + +- Function calculates the corner quality measure at every source image pixel using the + #cornerMinEigenVal or #cornerHarris . +- Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are + retained). +- The corners with the minimal eigenvalue less than + \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. +- The remaining corners are sorted by the quality measure in the descending order. +- Function throws away each corner for which there is a stronger corner at a distance less than + maxDistance. + +The function can be used to initialize a point-based tracker of an object. + +@note If the function is called with different values A and B of the parameter qualityLevel , and +A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector +with qualityLevel=B . + +@param image Input 8-bit or floating-point 32-bit, single-channel image. +@param corners Output vector of detected corners. +@param maxCorners Maximum number of corners to return. If there are more corners than are found, +the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set +and all detected corners are returned. +@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The +parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue +(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the +quality measure less than the product are rejected. For example, if the best corner has the +quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure +less than 15 are rejected. +@param minDistance Minimum possible Euclidean distance between the returned corners. +@param mask Optional region of interest. If the image is not empty (it needs to have the type +CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. +@param blockSize Size of an average block for computing a derivative covariation matrix over each +pixel neighborhood. See cornerEigenValsAndVecs . +@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) +or #cornerMinEigenVal. +@param k Free parameter of the Harris detector. + +@sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, + */ + +CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask = noArray(), int blockSize = 3, + bool useHarrisDetector = false, double k = 0.04 ); + +CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask, int blockSize, + int gradientSize, bool useHarrisDetector = false, + double k = 0.04 ); + +/** @brief Same as above, but returns also quality measure of the detected corners. + +@param image Input 8-bit or floating-point 32-bit, single-channel image. +@param corners Output vector of detected corners. +@param maxCorners Maximum number of corners to return. If there are more corners than are found, +the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set +and all detected corners are returned. +@param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The +parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue +(see #cornerMinEigenVal ) or the Harris function response (see #cornerHarris ). The corners with the +quality measure less than the product are rejected. For example, if the best corner has the +quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure +less than 15 are rejected. +@param minDistance Minimum possible Euclidean distance between the returned corners. +@param mask Region of interest. If the image is not empty (it needs to have the type +CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. +@param cornersQuality Output vector of quality measure of the detected corners. +@param blockSize Size of an average block for computing a derivative covariation matrix over each +pixel neighborhood. See cornerEigenValsAndVecs . +@param gradientSize Aperture parameter for the Sobel operator used for derivatives computation. +See cornerEigenValsAndVecs . +@param useHarrisDetector Parameter indicating whether to use a Harris detector (see #cornerHarris) +or #cornerMinEigenVal. +@param k Free parameter of the Harris detector. + */ +CV_EXPORTS CV_WRAP_AS(goodFeaturesToTrackWithQuality) void goodFeaturesToTrack( + InputArray image, OutputArray corners, + int maxCorners, double qualityLevel, double minDistance, + InputArray mask, OutputArray cornersQuality, int blockSize = 3, + int gradientSize = 3, bool useHarrisDetector = false, double k = 0.04); + +/** @example samples/cpp/tutorial_code/ImgTrans/houghlines.cpp +An example using the Hough line detector +![Sample input image](Hough_Lines_Tutorial_Original_Image.jpg) ![Output image](Hough_Lines_Tutorial_Result.jpg) +*/ + +/** @brief Finds lines in a binary image using the standard Hough transform. + +The function implements the standard or standard multi-scale Hough transform algorithm for line +detection. See for a good explanation of Hough +transform. + +@param image 8-bit, single-channel binary source image. The image may be modified by the function. +@param lines Output vector of lines. Each line is represented by a 2 or 3 element vector +\f$(\rho, \theta)\f$ or \f$(\rho, \theta, \textrm{votes})\f$, where \f$\rho\f$ is the distance from +the coordinate origin \f$(0,0)\f$ (top-left corner of the image), \f$\theta\f$ is the line rotation +angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ), and +\f$\textrm{votes}\f$ is the value of accumulator. +@param rho Distance resolution of the accumulator in pixels. +@param theta Angle resolution of the accumulator in radians. +@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough +votes ( \f$>\texttt{threshold}\f$ ). +@param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho. +The coarse accumulator distance resolution is rho and the accurate accumulator resolution is +rho/srn. If both srn=0 and stn=0, the classical Hough transform is used. Otherwise, both these +parameters should be positive. +@param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. +@param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. +Must fall between 0 and max_theta. +@param max_theta For standard and multi-scale Hough transform, an upper bound for the angle. +Must fall between min_theta and CV_PI. The actual maximum angle in the accumulator may be slightly +less than max_theta, depending on the parameters min_theta and theta. +@param use_edgeval True if you want to use weighted Hough transform. + */ +CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, + double rho, double theta, int threshold, + double srn = 0, double stn = 0, + double min_theta = 0, double max_theta = CV_PI, + bool use_edgeval = false ); + +/** @brief Finds line segments in a binary image using the probabilistic Hough transform. + +The function implements the probabilistic Hough transform algorithm for line detection, described +in @cite Matas00 + +See the line detection example below: +@include snippets/imgproc_HoughLinesP.cpp +This is a sample picture the function parameters have been tuned for: + +![image](pics/building.jpg) + +And this is the output of the above program in case of the probabilistic Hough transform: + +![image](pics/houghp.png) + +@param image 8-bit, single-channel binary source image. The image may be modified by the function. +@param lines Output vector of lines. Each line is represented by a 4-element vector +\f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected +line segment. +@param rho Distance resolution of the accumulator in pixels. +@param theta Angle resolution of the accumulator in radians. +@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough +votes ( \f$>\texttt{threshold}\f$ ). +@param minLineLength Minimum line length. Line segments shorter than that are rejected. +@param maxLineGap Maximum allowed gap between points on the same line to link them. + +@sa LineSegmentDetector + */ +CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, + double rho, double theta, int threshold, + double minLineLength = 0, double maxLineGap = 0 ); + +/** @brief Finds lines in a set of points using the standard Hough transform. + +The function finds lines in a set of points using a modification of the Hough transform. +@include snippets/imgproc_HoughLinesPointSet.cpp +@param point Input vector of points. Each vector must be encoded as a Point vector \f$(x,y)\f$. Type must be CV_32FC2 or CV_32SC2. +@param lines Output vector of found lines. Each vector is encoded as a vector \f$(votes, rho, theta)\f$. +The larger the value of 'votes', the higher the reliability of the Hough line. +@param lines_max Max count of Hough lines. +@param threshold %Accumulator threshold parameter. Only those lines are returned that get enough +votes ( \f$>\texttt{threshold}\f$ ). +@param min_rho Minimum value for \f$\rho\f$ for the accumulator (Note: \f$\rho\f$ can be negative. The absolute value \f$|\rho|\f$ is the distance of a line to the origin.). +@param max_rho Maximum value for \f$\rho\f$ for the accumulator. +@param rho_step Distance resolution of the accumulator. +@param min_theta Minimum angle value of the accumulator in radians. +@param max_theta Upper bound for the angle value of the accumulator in radians. The actual maximum +angle may be slightly less than max_theta, depending on the parameters min_theta and theta_step. +@param theta_step Angle resolution of the accumulator in radians. + */ +CV_EXPORTS_W void HoughLinesPointSet( InputArray point, OutputArray lines, int lines_max, int threshold, + double min_rho, double max_rho, double rho_step, + double min_theta, double max_theta, double theta_step ); + +/** @example samples/cpp/tutorial_code/ImgTrans/houghcircles.cpp +An example using the Hough circle detector +*/ + +/** @brief Finds circles in a grayscale image using the Hough transform. + +The function finds circles in a grayscale image using a modification of the Hough transform. + +Example: : +@include snippets/imgproc_HoughLinesCircles.cpp + +@note Usually the function detects the centers of circles well. However, it may fail to find correct +radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if +you know it. Or, in the case of #HOUGH_GRADIENT method you may set maxRadius to a negative number +to return centers only without radius search, and find the correct radius using an additional procedure. + +It also helps to smooth image a bit unless it's already soft. For example, +GaussianBlur() with 7x7 kernel and 1.5x1.5 sigma or similar blurring may help. + +@param image 8-bit, single-channel, grayscale input image. +@param circles Output vector of found circles. Each vector is encoded as 3 or 4 element +floating-point vector \f$(x, y, radius)\f$ or \f$(x, y, radius, votes)\f$ . +@param method Detection method, see #HoughModes. The available methods are #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT. +@param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if +dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has +half as big width and height. For #HOUGH_GRADIENT_ALT the recommended value is dp=1.5, +unless some small very circles need to be detected. +@param minDist Minimum distance between the centers of the detected circles. If the parameter is +too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is +too large, some circles may be missed. +@param param1 First method-specific parameter. In case of #HOUGH_GRADIENT and #HOUGH_GRADIENT_ALT, +it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). +Note that #HOUGH_GRADIENT_ALT uses #Scharr algorithm to compute image derivatives, so the threshold value +should normally be higher, such as 300 or normally exposed and contrasty images. +@param param2 Second method-specific parameter. In case of #HOUGH_GRADIENT, it is the +accumulator threshold for the circle centers at the detection stage. The smaller it is, the more +false circles may be detected. Circles, corresponding to the larger accumulator values, will be +returned first. In the case of #HOUGH_GRADIENT_ALT algorithm, this is the circle "perfectness" measure. +The closer it to 1, the better shaped circles algorithm selects. In most cases 0.9 should be fine. +If you want get better detection of small circles, you may decrease it to 0.85, 0.8 or even less. +But then also try to limit the search range [minRadius, maxRadius] to avoid many false circles. +@param minRadius Minimum circle radius. +@param maxRadius Maximum circle radius. If <= 0, uses the maximum image dimension. If < 0, #HOUGH_GRADIENT returns +centers without finding the radius. #HOUGH_GRADIENT_ALT always computes circle radiuses. + +@sa fitEllipse, minEnclosingCircle + */ +CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, + int method, double dp, double minDist, + double param1 = 100, double param2 = 100, + int minRadius = 0, int maxRadius = 0 ); + +//! @} imgproc_feature + +//! @addtogroup imgproc_filter +//! @{ + +/** @example samples/cpp/tutorial_code/ImgProc/Morphology_2.cpp +Advanced morphology Transformations sample code +![Sample screenshot](Morphology_2_Tutorial_Result.jpg) +Check @ref tutorial_opening_closing_hats "the corresponding tutorial" for more details +*/ + +/** @brief Erodes an image by using a specific structuring element. + +The function erodes the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the minimum is taken: + +\f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In +case of multi-channel images, each channel is processed independently. + +@param src input image; the number of channels can be arbitrary, but the depth should be one of +CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular +structuring element is used. Kernel can be created using #getStructuringElement. +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times erosion is applied. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param borderValue border value in case of a constant border +@sa dilate, morphologyEx, getStructuringElement + */ +CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, + Point anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue() ); + +/** @example samples/cpp/tutorial_code/ImgProc/Morphology_1.cpp +Erosion and Dilation sample code +![Sample Screenshot-Erosion](Morphology_1_Tutorial_Erosion_Result.jpg)![Sample Screenshot-Dilation](Morphology_1_Tutorial_Dilation_Result.jpg) +Check @ref tutorial_erosion_dilatation "the corresponding tutorial" for more details +*/ + +/** @brief Dilates an image by using a specific structuring element. + +The function dilates the source image using the specified structuring element that determines the +shape of a pixel neighborhood over which the maximum is taken: +\f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] + +The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In +case of multi-channel images, each channel is processed independently. + +@param src input image; the number of channels can be arbitrary, but the depth should be one of +CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst output image of the same size and type as src. +@param kernel structuring element used for dilation; if element=Mat(), a 3 x 3 rectangular +structuring element is used. Kernel can be created using #getStructuringElement +@param anchor position of the anchor within the element; default value (-1, -1) means that the +anchor is at the element center. +@param iterations number of times dilation is applied. +@param borderType pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not suported. +@param borderValue border value in case of a constant border +@sa erode, morphologyEx, getStructuringElement + */ +CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, + Point anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue() ); + +/** @brief Performs advanced morphological transformations. + +The function cv::morphologyEx can perform advanced morphological transformations using an erosion and dilation as +basic operations. + +Any of the operations can be done in-place. In case of multi-channel images, each channel is +processed independently. + +@param src Source image. The number of channels can be arbitrary. The depth should be one of +CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. +@param dst Destination image of the same size and type as source image. +@param op Type of a morphological operation, see #MorphTypes +@param kernel Structuring element. It can be created using #getStructuringElement. +@param anchor Anchor position with the kernel. Negative values mean that the anchor is at the +kernel center. +@param iterations Number of times erosion and dilation are applied. +@param borderType Pixel extrapolation method, see #BorderTypes. #BORDER_WRAP is not supported. +@param borderValue Border value in case of a constant border. The default value has a special +meaning. +@sa dilate, erode, getStructuringElement +@note The number of iterations is the number of times erosion or dilatation operation will be applied. +For instance, an opening operation (#MORPH_OPEN) with two iterations is equivalent to apply +successively: erode -> erode -> dilate -> dilate (and not erode -> dilate -> erode -> dilate). + */ +CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, + int op, InputArray kernel, + Point anchor = Point(-1,-1), int iterations = 1, + int borderType = BORDER_CONSTANT, + const Scalar& borderValue = morphologyDefaultBorderValue() ); + +//! @} imgproc_filter + +//! @addtogroup imgproc_transform +//! @{ + +/** @brief Resizes an image. + +The function resize resizes the image src down to or up to the specified size. Note that the +initial dst type or size are not taken into account. Instead, the size and type are derived from +the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst, +you may call the function as follows: +@code + // explicitly specify dsize=dst.size(); fx and fy will be computed from that. + resize(src, dst, dst.size(), 0, 0, interpolation); +@endcode +If you want to decimate the image by factor of 2 in each direction, you can call the function this +way: +@code + // specify fx and fy and let the function compute the destination image size. + resize(src, dst, Size(), 0.5, 0.5, interpolation); +@endcode +To shrink an image, it will generally look best with #INTER_AREA interpolation, whereas to +enlarge an image, it will generally look best with #INTER_CUBIC (slow) or #INTER_LINEAR +(faster but still looks OK). + +@param src input image. +@param dst output image; it has the size dsize (when it is non-zero) or the size computed from +src.size(), fx, and fy; the type of dst is the same as of src. +@param dsize output image size; if it equals zero (`None` in Python), it is computed as: + \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] + Either dsize or both fx and fy must be non-zero. +@param fx scale factor along the horizontal axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.width/src.cols}\f] +@param fy scale factor along the vertical axis; when it equals 0, it is computed as +\f[\texttt{(double)dsize.height/src.rows}\f] +@param interpolation interpolation method, see #InterpolationFlags + +@sa warpAffine, warpPerspective, remap + */ +CV_EXPORTS_W void resize( InputArray src, OutputArray dst, + Size dsize, double fx = 0, double fy = 0, + int interpolation = INTER_LINEAR ); + +/** @brief Applies an affine transformation to an image. + +The function warpAffine transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted +with #invertAffineTransform and then put in the formula above instead of M. The function cannot +operate in-place. + +@param src input image. +@param dst output image that has the size dsize and the same type as src . +@param M \f$2\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (see #InterpolationFlags) and the optional +flag #WARP_INVERSE_MAP that means that M is the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (see #BorderTypes); when +borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to +the "outliers" in the source image are not modified by the function. +@param borderValue value used in case of a constant border; by default, it is 0. + +@sa warpPerspective, resize, remap, getRectSubPix, transform + */ +CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, + InputArray M, Size dsize, + int flags = INTER_LINEAR, + int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @example samples/cpp/warpPerspective_demo.cpp +An example program shows using cv::getPerspectiveTransform and cv::warpPerspective for image warping +*/ + +/** @brief Applies a perspective transformation to an image. + +The function warpPerspective transforms the source image using the specified matrix: + +\f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , + \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] + +when the flag #WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert +and then put in the formula above instead of M. The function cannot operate in-place. + +@param src input image. +@param dst output image that has the size dsize and the same type as src . +@param M \f$3\times 3\f$ transformation matrix. +@param dsize size of the output image. +@param flags combination of interpolation methods (#INTER_LINEAR or #INTER_NEAREST) and the +optional flag #WARP_INVERSE_MAP, that sets M as the inverse transformation ( +\f$\texttt{dst}\rightarrow\texttt{src}\f$ ). +@param borderMode pixel extrapolation method (#BORDER_CONSTANT or #BORDER_REPLICATE). +@param borderValue value used in case of a constant border; by default, it equals 0. + +@sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform + */ +CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, + InputArray M, Size dsize, + int flags = INTER_LINEAR, + int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @brief Applies a generic geometrical transformation to an image. + +The function remap transforms the source image using the specified map: + +\f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] + +with the WARP_RELATIVE_MAP flag : + +\f[\texttt{dst} (x,y) = \texttt{src} (x+map_x(x,y),y+map_y(x,y))\f] + +where values of pixels with non-integer coordinates are computed using one of available +interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps +in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in +\f$map_1\f$, or fixed-point maps created by using #convertMaps. The reason you might want to +convert from floating to fixed-point representations of a map is that they can yield much faster +(\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), +cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. + +This function cannot operate in-place. + +@param src Source image. +@param dst Destination image. It has the same size as map1 and the same type as src . +@param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , +CV_32FC1, or CV_32FC2. See #convertMaps for details on converting a floating point +representation to fixed-point for speed. +@param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map +if map1 is (x,y) points), respectively. +@param interpolation Interpolation method (see #InterpolationFlags). The methods #INTER_AREA +#INTER_LINEAR_EXACT and #INTER_NEAREST_EXACT are not supported by this function. +The extra flag WARP_RELATIVE_MAP can be ORed to the interpolation method +(e.g. INTER_LINEAR | WARP_RELATIVE_MAP) +@param borderMode Pixel extrapolation method (see #BorderTypes). When +borderMode=#BORDER_TRANSPARENT, it means that the pixels in the destination image that +corresponds to the "outliers" in the source image are not modified by the function. +@param borderValue Value used in case of a constant border. By default, it is 0. +@note +Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + */ +CV_EXPORTS_W void remap( InputArray src, OutputArray dst, + InputArray map1, InputArray map2, + int interpolation, int borderMode = BORDER_CONSTANT, + const Scalar& borderValue = Scalar()); + +/** @brief Converts image transformation maps from one representation to another. + +The function converts a pair of maps for remap from one representation to another. The following +options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are +supported: + +- \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the +most frequently used conversion operation, in which the original floating-point maps (see #remap) +are converted to a more compact and much faster fixed-point representation. The first output array +contains the rounded coordinates and the second array (created only when nninterpolation=false ) +contains indices in the interpolation tables. + +- \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but +the original maps are stored in one 2-channel matrix. + +- Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same +as the originals. + +@param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . +@param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), +respectively. +@param dstmap1 The first output map that has the type dstmap1type and the same size as src . +@param dstmap2 The second output map. +@param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or +CV_32FC2 . +@param nninterpolation Flag indicating whether the fixed-point maps are used for the +nearest-neighbor or for a more complex interpolation. + +@sa remap, undistort, initUndistortRectifyMap + */ +CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, + OutputArray dstmap1, OutputArray dstmap2, + int dstmap1type, bool nninterpolation = false ); + +/** @brief Calculates an affine matrix of 2D rotation. + +The function calculates the following matrix: + +\f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f] + +where + +\f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f] + +The transformation maps the rotation center to itself. If this is not the target, adjust the shift. + +@param center Center of the rotation in the source image. +@param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the +coordinate origin is assumed to be the top-left corner). +@param scale Isotropic scale factor. + +@sa getAffineTransform, warpAffine, transform + */ +CV_EXPORTS_W Mat getRotationMatrix2D(Point2f center, double angle, double scale); + +/** @sa getRotationMatrix2D */ +CV_EXPORTS Matx23d getRotationMatrix2D_(Point2f center, double angle, double scale); + +inline +Mat getRotationMatrix2D(Point2f center, double angle, double scale) +{ + return Mat(getRotationMatrix2D_(center, angle, scale), true); +} + +/** @brief Calculates an affine transform from three pairs of the corresponding points. + +The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that: + +\f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] + +where + +\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f] + +@param src Coordinates of triangle vertices in the source image. +@param dst Coordinates of the corresponding triangle vertices in the destination image. + +@sa warpAffine, transform + */ +CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); + +/** @brief Inverts an affine transformation. + +The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M: + +\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f] + +The result is also a \f$2 \times 3\f$ matrix of the same type as M. + +@param M Original affine transformation. +@param iM Output reverse affine transformation. + */ +CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); + +/** @brief Calculates a perspective transform from four pairs of the corresponding points. + +The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that: + +\f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] + +where + +\f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f] + +@param src Coordinates of quadrangle vertices in the source image. +@param dst Coordinates of the corresponding quadrangle vertices in the destination image. +@param solveMethod method passed to cv::solve (#DecompTypes) + +@sa findHomography, warpPerspective, perspectiveTransform + */ +CV_EXPORTS_W Mat getPerspectiveTransform(InputArray src, InputArray dst, int solveMethod = DECOMP_LU); + +/** @overload */ +CV_EXPORTS Mat getPerspectiveTransform(const Point2f src[], const Point2f dst[], int solveMethod = DECOMP_LU); + + +CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); + +/** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy. + +The function getRectSubPix extracts pixels from src: + +\f[patch(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f] + +where the values of the pixels at non-integer coordinates are retrieved using bilinear +interpolation. Every channel of multi-channel images is processed independently. Also +the image should be a single channel or three channel image. While the center of the +rectangle must be inside the image, parts of the rectangle may be outside. + +@param image Source image. +@param patchSize Size of the extracted patch. +@param center Floating point coordinates of the center of the extracted rectangle within the +source image. The center must be inside the image. +@param patch Extracted patch that has the size patchSize and the same number of channels as src . +@param patchType Depth of the extracted pixels. By default, they have the same depth as src . + +@sa warpAffine, warpPerspective + */ +CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, + Point2f center, OutputArray patch, int patchType = -1 ); + +/** @example samples/cpp/polar_transforms.cpp +An example using the cv::linearPolar and cv::logPolar operations +*/ + +/** @brief Remaps an image to semilog-polar coordinates space. + +@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags+WARP_POLAR_LOG); + +@internal +Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image d)"): +\f[\begin{array}{l} + dst( \rho , \phi ) = src(x,y) \\ + dst.size() \leftarrow src.size() +\end{array}\f] + +where +\f[\begin{array}{l} + I = (dx,dy) = (x - center.x,y - center.y) \\ + \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ + \phi = Kangle \cdot \texttt{angle} (I) \\ +\end{array}\f] + +and +\f[\begin{array}{l} + M = src.cols / log_e(maxRadius) \\ + Kangle = src.rows / 2\Pi \\ +\end{array}\f] + +The function emulates the human "foveal" vision and can be used for fast scale and +rotation-invariant template matching, for object tracking and so forth. +@param src Source image +@param dst Destination image. It will have same size and type as src. +@param center The transformation center; where the output precision is maximal +@param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. +@param flags A combination of interpolation methods, see #InterpolationFlags + +@note +- The function can not operate in-place. +- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + +@sa cv::linearPolar +@endinternal +*/ +CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, + Point2f center, double M, int flags ); + +/** @brief Remaps an image to polar coordinates space. + +@deprecated This function produces same result as cv::warpPolar(src, dst, src.size(), center, maxRadius, flags) + +@internal +Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image c)"): +\f[\begin{array}{l} + dst( \rho , \phi ) = src(x,y) \\ + dst.size() \leftarrow src.size() +\end{array}\f] + +where +\f[\begin{array}{l} + I = (dx,dy) = (x - center.x,y - center.y) \\ + \rho = Kmag \cdot \texttt{magnitude} (I) ,\\ + \phi = angle \cdot \texttt{angle} (I) +\end{array}\f] + +and +\f[\begin{array}{l} + Kx = src.cols / maxRadius \\ + Ky = src.rows / 2\Pi +\end{array}\f] + + +@param src Source image +@param dst Destination image. It will have same size and type as src. +@param center The transformation center; +@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. +@param flags A combination of interpolation methods, see #InterpolationFlags + +@note +- The function can not operate in-place. +- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. + +@sa cv::logPolar +@endinternal +*/ +CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, + Point2f center, double maxRadius, int flags ); + + +/** \brief Remaps an image to polar or semilog-polar coordinates space + +@anchor polar_remaps_reference_image +![Polar remaps reference](pics/polar_remap_doc.png) + +Transform the source image using the following transformation: +\f[ +dst(\rho , \phi ) = src(x,y) +\f] + +where +\f[ +\begin{array}{l} +\vec{I} = (x - center.x, \;y - center.y) \\ +\phi = Kangle \cdot \texttt{angle} (\vec{I}) \\ +\rho = \left\{\begin{matrix} +Klin \cdot \texttt{magnitude} (\vec{I}) & default \\ +Klog \cdot log_e(\texttt{magnitude} (\vec{I})) & if \; semilog \\ +\end{matrix}\right. +\end{array} +\f] + +and +\f[ +\begin{array}{l} +Kangle = dsize.height / 2\Pi \\ +Klin = dsize.width / maxRadius \\ +Klog = dsize.width / log_e(maxRadius) \\ +\end{array} +\f] + + +\par Linear vs semilog mapping + +Polar mapping can be linear or semi-log. Add one of #WarpPolarMode to `flags` to specify the polar mapping mode. + +Linear is the default mode. + +The semilog mapping emulates the human "foveal" vision that permit very high acuity on the line of sight (central vision) +in contrast to peripheral vision where acuity is minor. + +\par Option on `dsize`: + +- if both values in `dsize <=0 ` (default), +the destination image will have (almost) same area of source bounding circle: +\f[\begin{array}{l} +dsize.area \leftarrow (maxRadius^2 \cdot \Pi) \\ +dsize.width = \texttt{cvRound}(maxRadius) \\ +dsize.height = \texttt{cvRound}(maxRadius \cdot \Pi) \\ +\end{array}\f] + + +- if only `dsize.height <= 0`, +the destination image area will be proportional to the bounding circle area but scaled by `Kx * Kx`: +\f[\begin{array}{l} +dsize.height = \texttt{cvRound}(dsize.width \cdot \Pi) \\ +\end{array} +\f] + +- if both values in `dsize > 0 `, +the destination image will have the given size therefore the area of the bounding circle will be scaled to `dsize`. + + +\par Reverse mapping + +You can get reverse mapping adding #WARP_INVERSE_MAP to `flags` +\snippet polar_transforms.cpp InverseMap + +In addiction, to calculate the original coordinate from a polar mapped coordinate \f$(rho, phi)->(x, y)\f$: +\snippet polar_transforms.cpp InverseCoordinate + +@param src Source image. +@param dst Destination image. It will have same type as src. +@param dsize The destination image size (see description for valid options). +@param center The transformation center. +@param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. +@param flags A combination of interpolation methods, #InterpolationFlags + #WarpPolarMode. + - Add #WARP_POLAR_LINEAR to select linear polar mapping (default) + - Add #WARP_POLAR_LOG to select semilog polar mapping + - Add #WARP_INVERSE_MAP for reverse mapping. +@note +- The function can not operate in-place. +- To calculate magnitude and angle in degrees #cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. +- This function uses #remap. Due to current implementation limitations the size of an input and output images should be less than 32767x32767. + +@sa cv::remap +*/ +CV_EXPORTS_W void warpPolar(InputArray src, OutputArray dst, Size dsize, + Point2f center, double maxRadius, int flags); + + +//! @} imgproc_transform + +//! @addtogroup imgproc_misc +//! @{ + +/** @brief Calculates the integral of an image. + +The function calculates one or more integral images for the source image as follows: + +\f[\texttt{sum} (X,Y) = \sum _{x + +Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed +with getOptimalDFTSize. + +The function performs the following equations: +- First it applies a Hanning window (see ) to each +image to remove possible edge effects. This window is cached until the array size changes to speed +up processing time. +- Next it computes the forward DFTs of each source array: +\f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f] +where \f$\mathcal{F}\f$ is the forward DFT. +- It then computes the cross-power spectrum of each frequency domain array: +\f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f] +- Next the cross-correlation is converted back into the time domain via the inverse DFT: +\f[r = \mathcal{F}^{-1}\{R\}\f] +- Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to +achieve sub-pixel accuracy. +\f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f] +- If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 +centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single +peak) and will be smaller when there are multiple peaks. + +@param src1 Source floating point array (CV_32FC1 or CV_64FC1) +@param src2 Source floating point array (CV_32FC1 or CV_64FC1) +@param window Floating point array with windowing coefficients to reduce edge effects (optional). +@param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). +@returns detected phase shift (sub-pixel) between the two arrays. + +@sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow + */ +CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, + InputArray window = noArray(), CV_OUT double* response = 0); + +/** @brief This function computes a Hanning window coefficients in two dimensions. + +See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) +for more information. + +An example is shown below: +@code + // create hanning window of size 100x100 and type CV_32F + Mat hann; + createHanningWindow(hann, Size(100, 100), CV_32F); +@endcode +@param dst Destination array to place Hann coefficients in +@param winSize The window size specifications (both width and height must be > 1) +@param type Created array type + */ +CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); + +/** @brief Performs the per-element division of the first Fourier spectrum by the second Fourier spectrum. + +The function cv::divSpectrums performs the per-element division of the first array by the second array. +The arrays are CCS-packed or complex matrices that are results of a real or complex Fourier transform. + +@param a first input array. +@param b second input array of the same size and type as src1 . +@param c output array of the same size and type as src1 . +@param flags operation flags; currently, the only supported flag is cv::DFT_ROWS, which indicates that +each row of src1 and src2 is an independent 1D Fourier spectrum. If you do not want to use this flag, then simply add a `0` as value. +@param conjB optional flag that conjugates the second input array before the multiplication (true) +or not (false). +*/ +CV_EXPORTS_W void divSpectrums(InputArray a, InputArray b, OutputArray c, + int flags, bool conjB = false); + +//! @} imgproc_motion + +//! @addtogroup imgproc_misc +//! @{ + +/** @brief Applies a fixed-level threshold to each array element. + +The function applies fixed-level thresholding to a multiple-channel array. The function is typically +used to get a bi-level (binary) image out of a grayscale image ( #compare could be also used for +this purpose) or for removing a noise, that is, filtering out pixels with too small or too large +values. There are several types of thresholding supported by the function. They are determined by +type parameter. + +Also, the special values #THRESH_OTSU or #THRESH_TRIANGLE may be combined with one of the +above values. In these cases, the function determines the optimal threshold value using the Otsu's +or Triangle algorithm and uses it instead of the specified thresh. + +@note Currently, the Otsu's and Triangle methods are implemented only for 8-bit single-channel images. + +@param src input array (multiple-channel, 8-bit or 32-bit floating point). +@param dst output array of the same size and type and the same number of channels as src. +@param thresh threshold value. +@param maxval maximum value to use with the #THRESH_BINARY and #THRESH_BINARY_INV thresholding +types. +@param type thresholding type (see #ThresholdTypes). +@return the computed threshold value if Otsu's or Triangle methods used. + +@sa adaptiveThreshold, findContours, compare, min, max + */ +CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, + double thresh, double maxval, int type ); + + +/** @brief Applies an adaptive threshold to an array. + +The function transforms a grayscale image to a binary image according to the formulae: +- **THRESH_BINARY** + \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f] +- **THRESH_BINARY_INV** + \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f] +where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter). + +The function can process the image in-place. + +@param src Source 8-bit single-channel image. +@param dst Destination image of the same size and the same type as src. +@param maxValue Non-zero value assigned to the pixels for which the condition is satisfied +@param adaptiveMethod Adaptive thresholding algorithm to use, see #AdaptiveThresholdTypes. +The #BORDER_REPLICATE | #BORDER_ISOLATED is used to process boundaries. +@param thresholdType Thresholding type that must be either #THRESH_BINARY or #THRESH_BINARY_INV, +see #ThresholdTypes. +@param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the +pixel: 3, 5, 7, and so on. +@param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it +is positive but may be zero or negative as well. + +@sa threshold, blur, GaussianBlur + */ +CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, + double maxValue, int adaptiveMethod, + int thresholdType, int blockSize, double C ); + +//! @} imgproc_misc + +//! @addtogroup imgproc_filter +//! @{ + +/** @example samples/cpp/tutorial_code/ImgProc/Pyramids/Pyramids.cpp +An example using pyrDown and pyrUp functions +*/ + +/** @brief Blurs an image and downsamples it. + +By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in +any case, the following conditions should be satisfied: + +\f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f] + +The function performs the downsampling step of the Gaussian pyramid construction. First, it +convolves the source image with the kernel: + +\f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f] + +Then, it downsamples the image by rejecting even rows and columns. + +@param src input image. +@param dst output image; it has the specified size and the same type as src. +@param dstsize size of the output image. +@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) + */ +CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, + const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); + +/** @brief Upsamples an image and then blurs it. + +By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any +case, the following conditions should be satisfied: + +\f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f] + +The function performs the upsampling step of the Gaussian pyramid construction, though it can +actually be used to construct the Laplacian pyramid. First, it upsamples the source image by +injecting even zero rows and columns and then convolves the result with the same kernel as in +pyrDown multiplied by 4. + +@param src input image. +@param dst output image. It has the specified size and the same type as src . +@param dstsize size of the output image. +@param borderType Pixel extrapolation method, see #BorderTypes (only #BORDER_DEFAULT is supported) + */ +CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, + const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); + +/** @brief Constructs the Gaussian pyramid for an image. + +The function constructs a vector of images and builds the Gaussian pyramid by recursively applying +pyrDown to the previously built pyramid layers, starting from `dst[0]==src`. + +@param src Source image. Check pyrDown for the list of supported types. +@param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the +same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on. +@param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative. +@param borderType Pixel extrapolation method, see #BorderTypes (#BORDER_CONSTANT isn't supported) + */ +CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, + int maxlevel, int borderType = BORDER_DEFAULT ); + +//! @} imgproc_filter + +//! @addtogroup imgproc_hist +//! @{ + +/** @example samples/cpp/demhist.cpp +An example for creating histograms of an image +*/ + +/** @brief Calculates a histogram of a set of arrays. + +The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used +to increment a histogram bin are taken from the corresponding input arrays at the same location. The +sample below shows how to compute a 2D Hue-Saturation histogram for a color image. : +@include snippets/imgproc_calcHist.cpp + +@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same +size. Each of them can have an arbitrary number of channels. +@param nimages Number of source images. +@param channels List of the dims channels used to compute the histogram. The first array channels +are numerated from 0 to images[0].channels()-1 , the second array channels are counted from +images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. +@param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size +as images[i] . The non-zero mask elements mark the array elements counted in the histogram. +@param hist Output histogram, which is a dense or sparse dims -dimensional array. +@param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS +(equal to 32 in the current OpenCV version). +@param histSize Array of histogram sizes in each dimension. +@param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the +histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower +(inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary +\f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a +uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform ( +uniform=false ), then each of ranges[i] contains histSize[i]+1 elements: +\f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$ +. The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not +counted in the histogram. +@param uniform Flag indicating whether the histogram is uniform or not (see above). +@param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning +when it is allocated. This feature enables you to compute a single histogram from several sets of +arrays, or to update the histogram in time. +*/ +CV_EXPORTS void calcHist( const Mat* images, int nimages, + const int* channels, InputArray mask, + OutputArray hist, int dims, const int* histSize, + const float** ranges, bool uniform = true, bool accumulate = false ); + +/** @overload + +this variant uses %SparseMat for output +*/ +CV_EXPORTS void calcHist( const Mat* images, int nimages, + const int* channels, InputArray mask, + SparseMat& hist, int dims, + const int* histSize, const float** ranges, + bool uniform = true, bool accumulate = false ); + +/** @overload + +this variant supports only uniform histograms. + +ranges argument is either empty vector or a flattened vector of histSize.size()*2 elements +(histSize.size() element pairs). The first and second elements of each pair specify the lower and +upper boundaries. +*/ +CV_EXPORTS_W void calcHist( InputArrayOfArrays images, + const std::vector& channels, + InputArray mask, OutputArray hist, + const std::vector& histSize, + const std::vector& ranges, + bool accumulate = false ); + +/** @brief Calculates the back projection of a histogram. + +The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to +#calcHist , at each location (x, y) the function collects the values from the selected channels +in the input images and finds the corresponding histogram bin. But instead of incrementing it, the +function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of +statistics, the function computes probability of each element value in respect with the empirical +probability distribution represented by the histogram. See how, for example, you can find and track +a bright-colored object in a scene: + +- Before tracking, show the object to the camera so that it covers almost the whole frame. +Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant +colors in the object. + +- When tracking, calculate a back projection of a hue plane of each input video frame using that +pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make +sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels. + +- Find connected components in the resulting picture and choose, for example, the largest +component. + +This is an approximate algorithm of the CamShift color object tracker. + +@param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same +size. Each of them can have an arbitrary number of channels. +@param nimages Number of source images. +@param channels The list of channels used to compute the back projection. The number of channels +must match the histogram dimensionality. The first array channels are numerated from 0 to +images[0].channels()-1 , the second array channels are counted from images[0].channels() to +images[0].channels() + images[1].channels()-1, and so on. +@param hist Input histogram that can be dense or sparse. +@param backProject Destination back projection array that is a single-channel array of the same +size and depth as images[0] . +@param ranges Array of arrays of the histogram bin boundaries in each dimension. See #calcHist . +@param scale Optional scale factor for the output back projection. +@param uniform Flag indicating whether the histogram is uniform or not (see #calcHist). + +@sa calcHist, compareHist + */ +CV_EXPORTS void calcBackProject( const Mat* images, int nimages, + const int* channels, InputArray hist, + OutputArray backProject, const float** ranges, + double scale = 1, bool uniform = true ); + +/** @overload */ +CV_EXPORTS void calcBackProject( const Mat* images, int nimages, + const int* channels, const SparseMat& hist, + OutputArray backProject, const float** ranges, + double scale = 1, bool uniform = true ); + +/** @overload */ +CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector& channels, + InputArray hist, OutputArray dst, + const std::vector& ranges, + double scale ); + +/** @brief Compares two histograms. + +The function cv::compareHist compares two dense or two sparse histograms using the specified method. + +The function returns \f$d(H_1, H_2)\f$ . + +While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable +for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling +problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms +or more general sparse configurations of weighted points, consider using the #EMD function. + +@param H1 First compared histogram. +@param H2 Second compared histogram of the same size as H1 . +@param method Comparison method, see #HistCompMethods + */ +CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); + +/** @overload */ +CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); + +/** @brief Equalizes the histogram of a grayscale image. + +The function equalizes the histogram of the input image using the following algorithm: + +- Calculate the histogram \f$H\f$ for src . +- Normalize the histogram so that the sum of histogram bins is 255. +- Compute the integral of the histogram: +\f[H'_i = \sum _{0 \le j < i} H(j)\f] +- Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ + +The algorithm normalizes the brightness and increases the contrast of the image. + +@param src Source 8-bit single channel image. +@param dst Destination image of the same size and type as src . + */ +CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); + +/** @brief Creates a smart pointer to a cv::CLAHE class and initializes it. + +@param clipLimit Threshold for contrast limiting. +@param tileGridSize Size of grid for histogram equalization. Input image will be divided into +equally sized rectangular tiles. tileGridSize defines the number of tiles in row and column. + */ +CV_EXPORTS_W Ptr createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); + +/** @brief Computes the "minimal work" distance between two weighted point configurations. + +The function computes the earth mover distance and/or a lower boundary of the distance between the +two weighted point configurations. One of the applications described in @cite RubnerSept98, +@cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation +problem that is solved using some modification of a simplex algorithm, thus the complexity is +exponential in the worst case, though, on average it is much faster. In the case of a real metric +the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used +to determine roughly whether the two signatures are far enough so that they cannot relate to the +same object. + +@param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix. +Each row stores the point weight followed by the point coordinates. The matrix is allowed to have +a single column (weights only) if the user-defined cost matrix is used. The weights must be +non-negative and have at least one non-zero value. +@param signature2 Second signature of the same format as signature1 , though the number of rows +may be different. The total weights may be different. In this case an extra "dummy" point is added +to either signature1 or signature2. The weights must be non-negative and have at least one non-zero +value. +@param distType Used metric. See #DistanceTypes. +@param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix +is used, lower boundary lowerBound cannot be calculated because it needs a metric function. +@param lowerBound Optional input/output parameter: lower boundary of a distance between the two +signatures that is a distance between mass centers. The lower boundary may not be calculated if +the user-defined cost matrix is used, the total weights of point configurations are not equal, or +if the signatures consist of weights only (the signature matrices have a single column). You +**must** initialize \*lowerBound . If the calculated distance between mass centers is greater or +equal to \*lowerBound (it means that the signatures are far enough), the function does not +calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on +return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound +should be set to 0. +@param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is +a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 . + */ +CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, + int distType, InputArray cost=noArray(), + float* lowerBound = 0, OutputArray flow = noArray() ); + +CV_EXPORTS_AS(EMD) float wrapperEMD( InputArray signature1, InputArray signature2, + int distType, InputArray cost=noArray(), + CV_IN_OUT Ptr lowerBound = Ptr(), OutputArray flow = noArray() ); + +//! @} imgproc_hist + +//! @addtogroup imgproc_segmentation +//! @{ + +/** @example samples/cpp/watershed.cpp +An example using the watershed algorithm +*/ + +/** @brief Performs a marker-based image segmentation using the watershed algorithm. + +The function implements one of the variants of watershed, non-parametric marker-based segmentation +algorithm, described in @cite Meyer92 . + +Before passing the image to the function, you have to roughly outline the desired regions in the +image markers with positive (\>0) indices. So, every region is represented as one or more connected +components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary +mask using #findContours and #drawContours (see the watershed.cpp demo). The markers are "seeds" of +the future image regions. All the other pixels in markers , whose relation to the outlined regions +is not known and should be defined by the algorithm, should be set to 0's. In the function output, +each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the +regions. + +@note Any two neighbor connected components are not necessarily separated by a watershed boundary +(-1's pixels); for example, they can touch each other in the initial marker image passed to the +function. + +@param image Input 8-bit 3-channel image. +@param markers Input/output 32-bit single-channel image (map) of markers. It should have the same +size as image . + +@sa findContours + */ +CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); + +//! @} imgproc_segmentation + +//! @addtogroup imgproc_filter +//! @{ + +/** @brief Performs initial step of meanshift segmentation of an image. + +The function implements the filtering stage of meanshift segmentation, that is, the output of the +function is the filtered "posterized" image with color gradients and fine-grain texture flattened. +At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes +meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is +considered: + +\f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f] + +where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively +(though, the algorithm does not depend on the color space used, so any 3-component color space can +be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector +(R',G',B') are found and they act as the neighborhood center on the next iteration: + +\f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f] + +After the iterations over, the color components of the initial pixel (that is, the pixel from where +the iterations started) are set to the final value (average color at the last iteration): + +\f[I(X,Y) <- (R*,G*,B*)\f] + +When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is +run on the smallest layer first. After that, the results are propagated to the larger layer and the +iterations are run again only on those pixels where the layer colors differ by more than sr from the +lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the +results will be actually different from the ones obtained by running the meanshift procedure on the +whole original image (i.e. when maxLevel==0). + +@param src The source 8-bit, 3-channel image. +@param dst The destination image of the same format and the same size as the source. +@param sp The spatial window radius. +@param sr The color window radius. +@param maxLevel Maximum level of the pyramid for the segmentation. +@param termcrit Termination criteria: when to stop meanshift iterations. + */ +CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, + double sp, double sr, int maxLevel = 1, + TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); + +//! @} + +//! @addtogroup imgproc_segmentation +//! @{ + +/** @example samples/cpp/grabcut.cpp +An example using the GrabCut algorithm +![Sample Screenshot](grabcut_output1.jpg) +*/ + +/** @brief Runs the GrabCut algorithm. + +The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). + +@param img Input 8-bit 3-channel image. +@param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when +mode is set to #GC_INIT_WITH_RECT. Its elements may have one of the #GrabCutClasses. +@param rect ROI containing a segmented object. The pixels outside of the ROI are marked as +"obvious background". The parameter is only used when mode==#GC_INIT_WITH_RECT . +@param bgdModel Temporary array for the background model. Do not modify it while you are +processing the same image. +@param fgdModel Temporary arrays for the foreground model. Do not modify it while you are +processing the same image. +@param iterCount Number of iterations the algorithm should make before returning the result. Note +that the result can be refined with further calls with mode==#GC_INIT_WITH_MASK or +mode==GC_EVAL . +@param mode Operation mode that could be one of the #GrabCutModes + */ +CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, + InputOutputArray bgdModel, InputOutputArray fgdModel, + int iterCount, int mode = GC_EVAL ); + +//! @} imgproc_segmentation + +//! @addtogroup imgproc_misc +//! @{ + +/** @example samples/cpp/distrans.cpp +An example on using the distance transform +*/ + +/** @brief Calculates the distance to the closest zero pixel for each pixel of the source image. + +The function cv::distanceTransform calculates the approximate or precise distance from every binary +image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. + +When maskSize == #DIST_MASK_PRECISE and distanceType == #DIST_L2 , the function runs the +algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library. + +In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function +finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, +diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall +distance is calculated as a sum of these basic distances. Since the distance function should be +symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all +the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the +same cost (denoted as `c`). For the #DIST_C and #DIST_L1 types, the distance is calculated +precisely, whereas for #DIST_L2 (Euclidean distance) the distance can be calculated only with a +relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV +uses the values suggested in the original paper: +- DIST_L1: `a = 1, b = 2` +- DIST_L2: + - `3 x 3`: `a=0.955, b=1.3693` + - `5 x 5`: `a=1, b=1.4, c=2.1969` +- DIST_C: `a = 1, b = 1` + +Typically, for a fast, coarse distance estimation #DIST_L2, a \f$3\times 3\f$ mask is used. For a +more accurate distance estimation #DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used. +Note that both the precise and the approximate algorithms are linear on the number of pixels. + +This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$ +but also identifies the nearest connected component consisting of zero pixels +(labelType==#DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==#DIST_LABEL_PIXEL). Index of the +component/pixel is stored in `labels(x, y)`. When labelType==#DIST_LABEL_CCOMP, the function +automatically finds connected components of zero pixels in the input image and marks them with +distinct labels. When labelType==#DIST_LABEL_PIXEL, the function scans through the input image and +marks all the zero pixels with distinct labels. + +In this mode, the complexity is still linear. That is, the function provides a very fast way to +compute the Voronoi diagram for a binary image. Currently, the second variant can use only the +approximate distance transform algorithm, i.e. maskSize=#DIST_MASK_PRECISE is not supported +yet. + +@param src 8-bit, single-channel (binary) source image. +@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, +single-channel image of the same size as src. +@param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type +CV_32SC1 and the same size as src. +@param distanceType Type of distance, see #DistanceTypes +@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. +#DIST_MASK_PRECISE is not supported by this variant. In case of the #DIST_L1 or #DIST_C distance type, +the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times +5\f$ or any larger aperture. +@param labelType Type of the label array to build, see #DistanceTransformLabelTypes. + */ +CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, + OutputArray labels, int distanceType, int maskSize, + int labelType = DIST_LABEL_CCOMP ); + +/** @overload +@param src 8-bit, single-channel (binary) source image. +@param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, +single-channel image of the same size as src . +@param distanceType Type of distance, see #DistanceTypes +@param maskSize Size of the distance transform mask, see #DistanceTransformMasks. In case of the +#DIST_L1 or #DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives +the same result as \f$5\times 5\f$ or any larger aperture. +@param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for +the first variant of the function and distanceType == #DIST_L1. +*/ +CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, + int distanceType, int maskSize, int dstType=CV_32F); + +/** @brief Fills a connected component with the given color. + +The function cv::floodFill fills a connected component starting from the seed point with the specified +color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The +pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if: + +- in case of a grayscale image and floating range +\f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f] + + +- in case of a grayscale image and fixed range +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f] + + +- in case of a color image and floating range +\f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f] +\f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f] +and +\f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f] + + +- in case of a color image and fixed range +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f] +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f] +and +\f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f] + + +where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the +component. That is, to be added to the connected component, a color/brightness of the pixel should +be close enough to: +- Color/brightness of one of its neighbors that already belong to the connected component in case +of a floating range. +- Color/brightness of the seed point in case of a fixed range. + +Use these functions to either mark a connected component with the specified color in-place, or build +a mask and then extract the contour, or copy the region to another image, and so on. + +@param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the +function unless the #FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See +the details below. +@param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels +taller than image. If an empty Mat is passed it will be created automatically. Since this is both an +input and output parameter, you must take responsibility of initializing it. +Flood-filling cannot go across non-zero pixels in the input mask. For example, +an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the +mask corresponding to filled pixels in the image are set to 1 or to the specified value in flags +as described below. Additionally, the function fills the border of the mask with ones to simplify +internal processing. It is therefore possible to use the same mask in multiple calls to the function +to make sure the filled areas do not overlap. +@param seedPoint Starting point. +@param newVal New value of the repainted domain pixels. +@param loDiff Maximal lower brightness/color difference between the currently observed pixel and +one of its neighbors belonging to the component, or a seed pixel being added to the component. +@param upDiff Maximal upper brightness/color difference between the currently observed pixel and +one of its neighbors belonging to the component, or a seed pixel being added to the component. +@param rect Optional output parameter set by the function to the minimum bounding rectangle of the +repainted domain. +@param flags Operation flags. The first 8 bits contain a connectivity value. The default value of +4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A +connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) +will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill +the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest +neighbours and fill the mask with a value of 255. The following additional options occupy higher +bits and therefore may be further combined with the connectivity and mask fill values using +bit-wise or (|), see #FloodFillFlags. + +@note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the +pixel \f$(x+1, y+1)\f$ in the mask . + +@sa findContours + */ +CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, + Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, + Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), + int flags = 4 ); + +/** @example samples/cpp/ffilldemo.cpp +An example using the FloodFill technique +*/ + +/** @overload + +variant without `mask` parameter +*/ +CV_EXPORTS int floodFill( InputOutputArray image, + Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, + Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), + int flags = 4 ); + +//! Performs linear blending of two images: +//! \f[ \texttt{dst}(i,j) = \texttt{weights1}(i,j)*\texttt{src1}(i,j) + \texttt{weights2}(i,j)*\texttt{src2}(i,j) \f] +//! @param src1 It has a type of CV_8UC(n) or CV_32FC(n), where n is a positive integer. +//! @param src2 It has the same type and size as src1. +//! @param weights1 It has a type of CV_32FC1 and the same size with src1. +//! @param weights2 It has a type of CV_32FC1 and the same size with src1. +//! @param dst It is created if it does not have the same size and type with src1. +CV_EXPORTS_W void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); + +//! @} imgproc_misc + +//! @addtogroup imgproc_color_conversions +//! @{ + +/** @brief Converts an image from one color space to another. + +The function converts an input image from one color space to another. In case of a transformation +to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note +that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the +bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue +component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and +sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. + +The conventional ranges for R, G, and B channel values are: +- 0 to 255 for CV_8U images +- 0 to 65535 for CV_16U images +- 0 to 1 for CV_32F images + +In case of linear transformations, the range does not matter. But in case of a non-linear +transformation, an input RGB image should be normalized to the proper value range to get the correct +results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a +32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will +have the 0..255 value range instead of 0..1 assumed by the function. So, before calling #cvtColor , +you need first to scale the image down: +@code + img *= 1./255; + cvtColor(img, img, COLOR_BGR2Luv); +@endcode +If you use #cvtColor with 8-bit images, the conversion will have some information lost. For many +applications, this will not be noticeable but it is recommended to use 32-bit images in applications +that need the full range of colors or that convert an image before an operation and then convert +back. + +If conversion adds the alpha channel, its value will set to the maximum of corresponding channel +range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. + +@param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision +floating-point. +@param dst output image of the same size and depth as src. +@param code color space conversion code (see #ColorConversionCodes). +@param dstCn number of channels in the destination image; if the parameter is 0, the number of the +channels is derived automatically from src and code. +@param hint Implementation modfication flags. See #AlgorithmHint + +@see @ref imgproc_color_conversions + */ +CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); + +/** @brief Converts an image from one color space to another where the source image is +stored in two planes. + +This function only supports YUV420 to RGB conversion as of now. + +@param src1 8-bit image (#CV_8U) of the Y plane. +@param src2 image containing interleaved U/V plane. +@param dst output image. +@param code Specifies the type of conversion. It can take any of the following values: +- #COLOR_YUV2BGR_NV12 +- #COLOR_YUV2RGB_NV12 +- #COLOR_YUV2BGRA_NV12 +- #COLOR_YUV2RGBA_NV12 +- #COLOR_YUV2BGR_NV21 +- #COLOR_YUV2RGB_NV21 +- #COLOR_YUV2BGRA_NV21 +- #COLOR_YUV2RGBA_NV21 +@param hint Implementation modfication flags. See #AlgorithmHint +*/ +CV_EXPORTS_W void cvtColorTwoPlane( InputArray src1, InputArray src2, OutputArray dst, int code, AlgorithmHint hint = cv::ALGO_HINT_DEFAULT ); + +/** @brief main function for all demosaicing processes + +@param src input image: 8-bit unsigned or 16-bit unsigned. +@param dst output image of the same size and depth as src. +@param code Color space conversion code (see the description below). +@param dstCn number of channels in the destination image; if the parameter is 0, the number of the +channels is derived automatically from src and code. + +The function can do the following transformations: + +- Demosaicing using bilinear interpolation + + #COLOR_BayerBG2BGR , #COLOR_BayerGB2BGR , #COLOR_BayerRG2BGR , #COLOR_BayerGR2BGR + + #COLOR_BayerBG2GRAY , #COLOR_BayerGB2GRAY , #COLOR_BayerRG2GRAY , #COLOR_BayerGR2GRAY + +- Demosaicing using Variable Number of Gradients. + + #COLOR_BayerBG2BGR_VNG , #COLOR_BayerGB2BGR_VNG , #COLOR_BayerRG2BGR_VNG , #COLOR_BayerGR2BGR_VNG + +- Edge-Aware Demosaicing. + + #COLOR_BayerBG2BGR_EA , #COLOR_BayerGB2BGR_EA , #COLOR_BayerRG2BGR_EA , #COLOR_BayerGR2BGR_EA + +- Demosaicing with alpha channel + + #COLOR_BayerBG2BGRA , #COLOR_BayerGB2BGRA , #COLOR_BayerRG2BGRA , #COLOR_BayerGR2BGRA + +@sa cvtColor +*/ +CV_EXPORTS_W void demosaicing(InputArray src, OutputArray dst, int code, int dstCn = 0); + +//! @} imgproc_color_conversions + +//! @addtogroup imgproc_shape +//! @{ + +/** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape. + +The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The +results are returned in the structure cv::Moments. + +@param array Single chanel raster image (CV_8U, CV_16U, CV_16S, CV_32F, CV_64F) or an array ( +\f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f). +@param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is +used for images only. +@returns moments. + +@note Only applicable to contour moments calculations from Python bindings: Note that the numpy +type for the input array should be either np.int32 or np.float32. + +@sa contourArea, arcLength + */ +CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); + +/** @brief Calculates seven Hu invariants. + +The function calculates seven Hu invariants (introduced in @cite Hu62; see also +) defined as: + +\f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f] + +where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ . + +These values are proved to be invariants to the image scale, rotation, and reflection except the +seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of +infinite image resolution. In case of raster images, the computed Hu invariants for the original and +transformed images are a bit different. + +@param moments Input moments computed with moments . +@param hu Output Hu invariants. + +@sa matchShapes + */ +CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); + +/** @overload */ +CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); + +//! @} imgproc_shape + +//! @addtogroup imgproc_object +//! @{ + +//! type of the template matching operation +enum TemplateMatchModes { + TM_SQDIFF = 0, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] + with mask: + \f[R(x,y)= \sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot + M(x',y') \right)^2\f] */ + TM_SQDIFF_NORMED = 1, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{ + x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] + with mask: + \f[R(x,y)= \frac{\sum _{x',y'} \left( (T(x',y')-I(x+x',y+y')) \cdot + M(x',y') \right)^2}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot + M(x',y') \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot + M(x',y') \right)^2}}\f] */ + TM_CCORR = 2, /*!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] + with mask: + \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot M(x',y') + ^2)\f] */ + TM_CCORR_NORMED = 3, /*!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{ + \sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] + with mask: + \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y') \cdot + M(x',y')^2)}{\sqrt{\sum_{x',y'} \left( T(x',y') \cdot M(x',y') + \right)^2 \cdot \sum_{x',y'} \left( I(x+x',y+y') \cdot M(x',y') + \right)^2}}\f] */ + TM_CCOEFF = 4, /*!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] + where + \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{ + x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) + \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] + with mask: + \f[\begin{array}{l} T'(x',y')=M(x',y') \cdot \left( T(x',y') - + \frac{1}{\sum _{x'',y''} M(x'',y'')} \cdot \sum _{x'',y''} + (T(x'',y'') \cdot M(x'',y'')) \right) \\ I'(x+x',y+y')=M(x',y') + \cdot \left( I(x+x',y+y') - \frac{1}{\sum _{x'',y''} M(x'',y'')} + \cdot \sum _{x'',y''} (I(x+x'',y+y'') \cdot M(x'',y'')) \right) + \end{array} \f] */ + TM_CCOEFF_NORMED = 5 /*!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ + \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} + }\f] */ +}; + +/** @example samples/cpp/tutorial_code/Histograms_Matching/MatchTemplate_Demo.cpp +An example using Template Matching algorithm +*/ + +/** @brief Compares a template against overlapped image regions. + +The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against +templ using the specified method and stores the comparison results in result . #TemplateMatchModes +describes the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ +template, \f$R\f$ result, \f$M\f$ the optional mask ). The summation is done over template and/or +the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$ + +After the function finishes the comparison, the best matches can be found as global minimums (when +#TM_SQDIFF was used) or maximums (when #TM_CCORR or #TM_CCOEFF was used) using the +#minMaxLoc function. In case of a color image, template summation in the numerator and each sum in +the denominator is done over all of the channels and separate mean values are used for each channel. +That is, the function can take a color template and a color image. The result will still be a +single-channel image, which is easier to analyze. + +@param image Image where the search is running. It must be 8-bit or 32-bit floating-point. +@param templ Searched template. It must be not greater than the source image and have the same +data type. +@param result Map of comparison results. It must be single-channel 32-bit floating-point. If image +is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ . +@param method Parameter specifying the comparison method, see #TemplateMatchModes +@param mask Optional mask. It must have the same size as templ. It must either have the same number + of channels as template or only one channel, which is then used for all template and + image channels. If the data type is #CV_8U, the mask is interpreted as a binary mask, + meaning only elements where mask is nonzero are used and are kept unchanged independent + of the actual mask value (weight equals 1). For data tpye #CV_32F, the mask values are + used as weights. The exact formulas are documented in #TemplateMatchModes. + */ +CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, + OutputArray result, int method, InputArray mask = noArray() ); + +//! @} + +//! @addtogroup imgproc_shape +//! @{ + +/** @example samples/cpp/connected_components.cpp +This program demonstrates connected components and use of the trackbar +*/ + +/** @brief computes the connected components labeled image of boolean image + +image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 +represents the background label. ltype specifies the output label image type, an important +consideration based on the total number of labels or alternatively the total number of pixels in +the source image. ccltype specifies the connected components labeling algorithm to use, currently +Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms +are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces +a row major ordering of labels while Spaghetti and BBDT do not. +This function uses parallel version of the algorithms if at least one allowed +parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. + +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +@param ccltype connected components algorithm type (see the #ConnectedComponentsAlgorithmsTypes). +*/ +CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels, + int connectivity, int ltype, int ccltype); + + +/** @overload + +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +*/ +CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, + int connectivity = 8, int ltype = CV_32S); + + +/** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label + +image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 +represents the background label. ltype specifies the output label image type, an important +consideration based on the total number of labels or alternatively the total number of pixels in +the source image. ccltype specifies the connected components labeling algorithm to use, currently +Bolelli (Spaghetti) @cite Bolelli2019, Grana (BBDT) @cite Grana2010 and Wu's (SAUF) @cite Wu2009 algorithms +are supported, see the #ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces +a row major ordering of labels while Spaghetti and BBDT do not. +This function uses parallel version of the algorithms (statistics included) if at least one allowed +parallel framework is enabled and if the rows of the image are at least twice the number returned by #getNumberOfCPUs. + +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param stats statistics output for each label, including the background label. +Statistics are accessed via stats(label, COLUMN) where COLUMN is one of +#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. +@param centroids centroid output for each label, including the background label. Centroids are +accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +@param ccltype connected components algorithm type (see #ConnectedComponentsAlgorithmsTypes). +*/ +CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, + int connectivity, int ltype, int ccltype); + +/** @overload +@param image the 8-bit single-channel image to be labeled +@param labels destination labeled image +@param stats statistics output for each label, including the background label. +Statistics are accessed via stats(label, COLUMN) where COLUMN is one of +#ConnectedComponentsTypes, selecting the statistic. The data type is CV_32S. +@param centroids centroid output for each label, including the background label. Centroids are +accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. +@param connectivity 8 or 4 for 8-way or 4-way connectivity respectively +@param ltype output image label type. Currently CV_32S and CV_16U are supported. +*/ +CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, + OutputArray stats, OutputArray centroids, + int connectivity = 8, int ltype = CV_32S); + + +/** @brief Finds contours in a binary image. + +The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours +are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the +OpenCV sample directory. +@note Since opencv 3.2 source image is not modified by this function. + +@param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero +pixels remain 0's, so the image is treated as binary . You can use #compare, #inRange, #threshold , +#adaptiveThreshold, #Canny, and others to create a binary image out of a grayscale or color one. +If mode equals to #RETR_CCOMP or #RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). +@param contours Detected contours. Each contour is stored as a vector of points (e.g. +std::vector >). +@param hierarchy Optional output vector (e.g. std::vector), containing information about the image topology. It has +as many elements as the number of contours. For each i-th contour contours[i], the elements +hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices +in contours of the next and previous contours at the same hierarchical level, the first child +contour and the parent contour, respectively. If for the contour i there are no next, previous, +parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. +@note In Python, hierarchy is nested inside a top level array. Use hierarchy[0][i] to access hierarchical elements of i-th contour. +@param mode Contour retrieval mode, see #RetrievalModes +@param method Contour approximation method, see #ContourApproximationModes +@param offset Optional offset by which every contour point is shifted. This is useful if the +contours are extracted from the image ROI and then they should be analyzed in the whole image +context. + */ +CV_EXPORTS_W void findContours( InputArray image, OutputArrayOfArrays contours, + OutputArray hierarchy, int mode, + int method, Point offset = Point()); + +/** @overload */ +CV_EXPORTS void findContours( InputArray image, OutputArrayOfArrays contours, + int mode, int method, Point offset = Point()); + +//! @brief Find contours using link runs algorithm +//! +//! This function implements an algorithm different from cv::findContours: +//! - doesn't allocate temporary image internally, thus it has reduced memory consumption +//! - supports CV_8UC1 images only +//! - outputs 2-level hierarhy only (RETR_CCOMP mode) +//! - doesn't support approximation change other than CHAIN_APPROX_SIMPLE +//! In all other aspects this function is compatible with cv::findContours. +CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours, OutputArray hierarchy); + +//! @overload +CV_EXPORTS_W void findContoursLinkRuns(InputArray image, OutputArrayOfArrays contours); + +/** @brief Approximates a polygonal curve(s) with the specified precision. + +The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less +vertices so that the distance between them is less or equal to the specified precision. It uses the +Douglas-Peucker algorithm + +@param curve Input vector of a 2D point stored in std::vector or Mat +@param approxCurve Result of the approximation. The type should match the type of the input curve. +@param epsilon Parameter specifying the approximation accuracy. This is the maximum distance +between the original curve and its approximation. +@param closed If true, the approximated curve is closed (its first and last vertices are +connected). Otherwise, it is not closed. + */ +CV_EXPORTS_W void approxPolyDP( InputArray curve, + OutputArray approxCurve, + double epsilon, bool closed ); + +/** @brief Approximates a polygon with a convex hull with a specified accuracy and number of sides. + +The cv::approxPolyN function approximates a polygon with a convex hull +so that the difference between the contour area of the original contour and the new polygon is minimal. +It uses a greedy algorithm for contracting two vertices into one in such a way that the additional area is minimal. +Straight lines formed by each edge of the convex contour are drawn and the areas of the resulting triangles are considered. +Each vertex will lie either on the original contour or outside it. + +The algorithm based on the paper @cite LowIlie2003 . + +@param curve Input vector of a 2D points stored in std::vector or Mat, points must be float or integer. +@param approxCurve Result of the approximation. The type is vector of a 2D point (Point2f or Point) in std::vector or Mat. +@param nsides The parameter defines the number of sides of the result polygon. +@param epsilon_percentage defines the percentage of the maximum of additional area. +If it equals -1, it is not used. Otherwise algorighm stops if additional area is greater than contourArea(_curve) * percentage. +If additional area exceeds the limit, algorithm returns as many vertices as there were at the moment the limit was exceeded. +@param ensure_convex If it is true, algorithm creates a convex hull of input contour. Otherwise input vector should be convex. + */ +CV_EXPORTS_W void approxPolyN(InputArray curve, OutputArray approxCurve, + int nsides, float epsilon_percentage = -1.0, + bool ensure_convex = true); + +/** @brief Calculates a contour perimeter or a curve length. + +The function computes a curve length or a closed contour perimeter. + +@param curve Input vector of 2D points, stored in std::vector or Mat. +@param closed Flag indicating whether the curve is closed or not. + */ +CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); + +/** @brief Calculates the up-right bounding rectangle of a point set or non-zero pixels of gray-scale image. + +The function calculates and returns the minimal up-right bounding rectangle for the specified point set or +non-zero pixels of gray-scale image. + +@param array Input gray-scale image or 2D point set, stored in std::vector or Mat. + */ +CV_EXPORTS_W Rect boundingRect( InputArray array ); + +/** @brief Calculates a contour area. + +The function computes a contour area. Similarly to moments , the area is computed using the Green +formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using +#drawContours or #fillPoly , can be different. Also, the function will most certainly give a wrong +results for contours with self-intersections. + +Example: +@code + vector contour; + contour.push_back(Point2f(0, 0)); + contour.push_back(Point2f(10, 0)); + contour.push_back(Point2f(10, 10)); + contour.push_back(Point2f(5, 4)); + + double area0 = contourArea(contour); + vector approx; + approxPolyDP(contour, approx, 5, true); + double area1 = contourArea(approx); + + cout << "area0 =" << area0 << endl << + "area1 =" << area1 << endl << + "approx poly vertices" << approx.size() << endl; +@endcode +@param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. +@param oriented Oriented area flag. If it is true, the function returns a signed area value, +depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can +determine orientation of a contour by taking the sign of an area. By default, the parameter is +false, which means that the absolute value is returned. + */ +CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); + +/** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set. + +The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a +specified point set. Developer should keep in mind that the returned RotatedRect can contain negative +indices when data is close to the containing Mat element boundary. + +@param points Input vector of 2D points, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); + +/** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. + +The function finds the four vertices of a rotated rectangle. This function is useful to draw the +rectangle. In C++, instead of using this function, you can directly use RotatedRect::points method. Please +visit the @ref tutorial_bounding_rotated_ellipses "tutorial on Creating Bounding rotated boxes and ellipses for contours" for more information. + +@param box The input rotated rectangle. It may be the output of @ref minAreaRect. +@param points The output array of four vertices of rectangles. + */ +CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); + +/** @brief Finds a circle of the minimum area enclosing a 2D point set. + +The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. + +@param points Input vector of 2D points, stored in std::vector\<\> or Mat +@param center Output center of the circle. +@param radius Output radius of the circle. + */ +CV_EXPORTS_W void minEnclosingCircle( InputArray points, + CV_OUT Point2f& center, CV_OUT float& radius ); + +/** @example samples/cpp/minarea.cpp +*/ + +/** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area. + +The function finds a triangle of minimum area enclosing the given set of 2D points and returns its +area. The output for a given 2D point set is shown in the image below. 2D points are depicted in +*red* and the enclosing triangle in *yellow*. + +![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) + +The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's +@cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal +enclosing triangle of a 2D convex polygon with n vertices. Since the #minEnclosingTriangle function +takes a 2D point set as input an additional preprocessing step of computing the convex hull of the +2D point set is required. The complexity of the #convexHull function is \f$O(n log(n))\f$ which is higher +than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$. + +@param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat +@param triangle Output vector of three 2D points defining the vertices of the triangle. The depth +of the OutputArray must be CV_32F. + */ +CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); + +/** @brief Compares two shapes. + +The function compares two shapes. All three implemented methods use the Hu invariants (see #HuMoments) + +@param contour1 First contour or grayscale image. +@param contour2 Second contour or grayscale image. +@param method Comparison method, see #ShapeMatchModes +@param parameter Method-specific parameter (not supported now). + */ +CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, + int method, double parameter ); + +/** @example samples/cpp/convexhull.cpp +An example using the convexHull functionality +*/ + +/** @brief Finds the convex hull of a point set. + +The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82 +that has *O(N logN)* complexity in the current implementation. + +@param points Input 2D point set, stored in std::vector or Mat. +@param hull Output convex hull. It is either an integer vector of indices or vector of points. In +the first case, the hull elements are 0-based indices of the convex hull points in the original +array (since the set of convex hull points is a subset of the original point set). In the second +case, hull elements are the convex hull points themselves. +@param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. +Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing +to the right, and its Y axis pointing upwards. +@param returnPoints Operation flag. In case of a matrix, when the flag is true, the function +returns convex hull points. Otherwise, it returns indices of the convex hull points. When the +output array is std::vector, the flag is ignored, and the output depends on the type of the +vector: std::vector\ implies returnPoints=false, std::vector\ implies +returnPoints=true. + +@note `points` and `hull` should be different arrays, inplace processing isn't supported. + +Check @ref tutorial_hull "the corresponding tutorial" for more details. + +useful links: + +https://www.learnopencv.com/convex-hull-using-opencv-in-python-and-c/ + */ +CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, + bool clockwise = false, bool returnPoints = true ); + +/** @brief Finds the convexity defects of a contour. + +The figure below displays convexity defects of a hand contour: + +![image](pics/defects.png) + +@param contour Input contour. +@param convexhull Convex hull obtained using convexHull that should contain indices of the contour +points that make the hull. +@param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java +interface each convexity defect is represented as 4-element integer vector (a.k.a. #Vec4i): +(start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices +in the original contour of the convexity defect beginning, end and the farthest point, and +fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the +farthest contour point and the hull. That is, to get the floating-point value of the depth will be +fixpt_depth/256.0. + */ +CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); + +/** @brief Tests a contour convexity. + +The function tests whether the input contour is convex or not. The contour must be simple, that is, +without self-intersections. Otherwise, the function output is undefined. + +@param contour Input vector of 2D points, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W bool isContourConvex( InputArray contour ); + +/** @example samples/cpp/intersectExample.cpp +Examples of how intersectConvexConvex works +*/ + +/** @brief Finds intersection of two convex polygons + +@param p1 First polygon +@param p2 Second polygon +@param p12 Output polygon describing the intersecting area +@param handleNested When true, an intersection is found if one of the polygons is fully enclosed in the other. +When false, no intersection is found. If the polygons share a side or the vertex of one polygon lies on an edge +of the other, they are not considered nested and an intersection will be found regardless of the value of handleNested. + +@returns Area of intersecting polygon. May be negative, if algorithm has not converged, e.g. non-convex input. + +@note intersectConvexConvex doesn't confirm that both polygons are convex and will return invalid results if they aren't. + */ +CV_EXPORTS_W float intersectConvexConvex( InputArray p1, InputArray p2, + OutputArray p12, bool handleNested = true ); + +/** @example samples/cpp/fitellipse.cpp +An example using the fitEllipse technique +*/ + +/** @brief Fits an ellipse around a set of 2D points. + +The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of +all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95 +is used. Developer should keep in mind that it is possible that the returned +ellipse/rotatedRect data contains negative indices, due to the data points being close to the +border of the containing Mat element. + +@param points Input 2D point set, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); + +/** @brief Fits an ellipse around a set of 2D points. + + The function calculates the ellipse that fits a set of 2D points. + It returns the rotated rectangle in which the ellipse is inscribed. + The Approximate Mean Square (AMS) proposed by @cite Taubin1991 is used. + + For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, + which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. + However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, + the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, + quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. + If the fit is found to be a parabolic or hyperbolic function then the standard #fitEllipse method is used. + The AMS method restricts the fit to parabolic, hyperbolic and elliptical curves + by imposing the condition that \f$ A^T ( D_x^T D_x + D_y^T D_y) A = 1 \f$ where + the matrices \f$ Dx \f$ and \f$ Dy \f$ are the partial derivatives of the design matrix \f$ D \f$ with + respect to x and y. The matrices are formed row by row applying the following to + each of the points in the set: + \f{align*}{ + D(i,:)&=\left\{x_i^2, x_i y_i, y_i^2, x_i, y_i, 1\right\} & + D_x(i,:)&=\left\{2 x_i,y_i,0,1,0,0\right\} & + D_y(i,:)&=\left\{0,x_i,2 y_i,0,1,0\right\} + \f} + The AMS method minimizes the cost function + \f{equation*}{ + \epsilon ^2=\frac{ A^T D^T D A }{ A^T (D_x^T D_x + D_y^T D_y) A^T } + \f} + + The minimum cost is found by solving the generalized eigenvalue problem. + + \f{equation*}{ + D^T D A = \lambda \left( D_x^T D_x + D_y^T D_y\right) A + \f} + + @param points Input 2D point set, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect fitEllipseAMS( InputArray points ); + + +/** @brief Fits an ellipse around a set of 2D points. + + The function calculates the ellipse that fits a set of 2D points. + It returns the rotated rectangle in which the ellipse is inscribed. + The Direct least square (Direct) method by @cite oy1998NumericallySD is used. + + For an ellipse, this basis set is \f$ \chi= \left(x^2, x y, y^2, x, y, 1\right) \f$, + which is a set of six free coefficients \f$ A^T=\left\{A_{\text{xx}},A_{\text{xy}},A_{\text{yy}},A_x,A_y,A_0\right\} \f$. + However, to specify an ellipse, all that is needed is five numbers; the major and minor axes lengths \f$ (a,b) \f$, + the position \f$ (x_0,y_0) \f$, and the orientation \f$ \theta \f$. This is because the basis set includes lines, + quadratics, parabolic and hyperbolic functions as well as elliptical functions as possible fits. + The Direct method confines the fit to ellipses by ensuring that \f$ 4 A_{xx} A_{yy}- A_{xy}^2 > 0 \f$. + The condition imposed is that \f$ 4 A_{xx} A_{yy}- A_{xy}^2=1 \f$ which satisfies the inequality + and as the coefficients can be arbitrarily scaled is not overly restrictive. + + \f{equation*}{ + \epsilon ^2= A^T D^T D A \quad \text{with} \quad A^T C A =1 \quad \text{and} \quad C=\left(\begin{matrix} + 0 & 0 & 2 & 0 & 0 & 0 \\ + 0 & -1 & 0 & 0 & 0 & 0 \\ + 2 & 0 & 0 & 0 & 0 & 0 \\ + 0 & 0 & 0 & 0 & 0 & 0 \\ + 0 & 0 & 0 & 0 & 0 & 0 \\ + 0 & 0 & 0 & 0 & 0 & 0 + \end{matrix} \right) + \f} + + The minimum cost is found by solving the generalized eigenvalue problem. + + \f{equation*}{ + D^T D A = \lambda \left( C\right) A + \f} + + The system produces only one positive eigenvalue \f$ \lambda\f$ which is chosen as the solution + with its eigenvector \f$\mathbf{u}\f$. These are used to find the coefficients + + \f{equation*}{ + A = \sqrt{\frac{1}{\mathbf{u}^T C \mathbf{u}}} \mathbf{u} + \f} + The scaling factor guarantees that \f$A^T C A =1\f$. + + @param points Input 2D point set, stored in std::vector\<\> or Mat + */ +CV_EXPORTS_W RotatedRect fitEllipseDirect( InputArray points ); + +/** @brief Fits a line to a 2D or 3D point set. + +The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where +\f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one +of the following: +- DIST_L2 +\f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] +- DIST_L1 +\f[\rho (r) = r\f] +- DIST_L12 +\f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] +- DIST_FAIR +\f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] +- DIST_WELSCH +\f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] +- DIST_HUBER +\f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] + +The algorithm is based on the M-estimator ( ) technique +that iteratively fits the line using the weighted least-squares algorithm. After each iteration the +weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . + +@param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat. +@param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements +(like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and +(x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like +Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line +and (x0, y0, z0) is a point on the line. +@param distType Distance used by the M-estimator, see #DistanceTypes +@param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value +is chosen. +@param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). +@param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. + */ +CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, + double param, double reps, double aeps ); + +/** @brief Performs a point-in-contour test. + +The function determines whether the point is inside a contour, outside, or lies on an edge (or +coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) +value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. +Otherwise, the return value is a signed distance between the point and the nearest contour edge. + +See below a sample output of the function where each image pixel is tested against the contour: + +![sample output](pics/pointpolygon.png) + +@param contour Input contour. +@param pt Point tested against the contour. +@param measureDist If true, the function estimates the signed distance from the point to the +nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. + */ +CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); + +/** @brief Finds out if there is any intersection between two rotated rectangles. + +If there is then the vertices of the intersecting region are returned as well. + +Below are some examples of intersection configurations. The hatched pattern indicates the +intersecting region and the red vertices are returned by the function. + +![intersection examples](pics/intersection.png) + +@param rect1 First rectangle +@param rect2 Second rectangle +@param intersectingRegion The output array of the vertices of the intersecting region. It returns +at most 8 vertices. Stored as std::vector\ or cv::Mat as Mx1 of type CV_32FC2. +@returns One of #RectanglesIntersectTypes + */ +CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); + +/** @brief Creates a smart pointer to a cv::GeneralizedHoughBallard class and initializes it. +*/ +CV_EXPORTS_W Ptr createGeneralizedHoughBallard(); + +/** @brief Creates a smart pointer to a cv::GeneralizedHoughGuil class and initializes it. +*/ +CV_EXPORTS_W Ptr createGeneralizedHoughGuil(); + +//! @} imgproc_shape + +//! @addtogroup imgproc_colormap +//! @{ + +//! GNU Octave/MATLAB equivalent colormaps +enum ColormapTypes +{ + COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg) + COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg) + COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg) + COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg) + COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg) + COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg) + COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg) + COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg) + COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg) + COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg) + COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg) + COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg) + COLORMAP_PARULA = 12, //!< ![parula](pics/colormaps/colorscale_parula.jpg) + COLORMAP_MAGMA = 13, //!< ![magma](pics/colormaps/colorscale_magma.jpg) + COLORMAP_INFERNO = 14, //!< ![inferno](pics/colormaps/colorscale_inferno.jpg) + COLORMAP_PLASMA = 15, //!< ![plasma](pics/colormaps/colorscale_plasma.jpg) + COLORMAP_VIRIDIS = 16, //!< ![viridis](pics/colormaps/colorscale_viridis.jpg) + COLORMAP_CIVIDIS = 17, //!< ![cividis](pics/colormaps/colorscale_cividis.jpg) + COLORMAP_TWILIGHT = 18, //!< ![twilight](pics/colormaps/colorscale_twilight.jpg) + COLORMAP_TWILIGHT_SHIFTED = 19, //!< ![twilight shifted](pics/colormaps/colorscale_twilight_shifted.jpg) + COLORMAP_TURBO = 20, //!< ![turbo](pics/colormaps/colorscale_turbo.jpg) + COLORMAP_DEEPGREEN = 21 //!< ![deepgreen](pics/colormaps/colorscale_deepgreen.jpg) +}; + +/** @example samples/cpp/falsecolor.cpp +An example using applyColorMap function +*/ + +/** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image. + +@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. +@param dst The result is the colormapped source image. Note: Mat::create is called on dst. +@param colormap The colormap to apply, see #ColormapTypes +*/ +CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); + +/** @brief Applies a user colormap on a given image. + +@param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. If CV_8UC3, then the CV_8UC1 image is generated internally using cv::COLOR_BGR2GRAY. +@param dst The result is the colormapped source image of the same number of channels as userColor. Note: Mat::create is called on dst. +@param userColor The colormap to apply of type CV_8UC1 or CV_8UC3 and size 256 +*/ +CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, InputArray userColor); + +//! @} imgproc_colormap + +//! @addtogroup imgproc_draw +//! @{ + + +/** OpenCV color channel order is BGR[A] */ +#define CV_RGB(r, g, b) cv::Scalar((b), (g), (r), 0) + +/** @brief Draws a line segment connecting two points. + +The function line draws the line segment between pt1 and pt2 points in the image. The line is +clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected +or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased +lines are drawn using Gaussian filtering. + +@param img Image. +@param pt1 First point of the line segment. +@param pt2 Second point of the line segment. +@param color Line color. +@param thickness Line thickness. +@param lineType Type of the line. See #LineTypes. +@param shift Number of fractional bits in the point coordinates. + */ +CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, + int thickness = 1, int lineType = LINE_8, int shift = 0); + +/** @brief Draws an arrow segment pointing from the first point to the second one. + +The function cv::arrowedLine draws an arrow between pt1 and pt2 points in the image. See also #line. + +@param img Image. +@param pt1 The point the arrow starts from. +@param pt2 The point the arrow points to. +@param color Line color. +@param thickness Line thickness. +@param line_type Type of the line. See #LineTypes +@param shift Number of fractional bits in the point coordinates. +@param tipLength The length of the arrow tip in relation to the arrow length + */ +CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, + int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); + +/** @brief Draws a simple, thick, or filled up-right rectangle. + +The function cv::rectangle draws a rectangle outline or a filled rectangle whose two opposite corners +are pt1 and pt2. + +@param img Image. +@param pt1 Vertex of the rectangle. +@param pt2 Vertex of the rectangle opposite to pt1 . +@param color Rectangle color or brightness (grayscale image). +@param thickness Thickness of lines that make up the rectangle. Negative values, like #FILLED, +mean that the function has to draw a filled rectangle. +@param lineType Type of the line. See #LineTypes +@param shift Number of fractional bits in the point coordinates. + */ +CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @overload + +use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and +r.br()-Point(1,1)` are opposite corners +*/ +CV_EXPORTS_W void rectangle(InputOutputArray img, Rect rec, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_2.cpp +An example using drawing functions +*/ + +/** @brief Draws a circle. + +The function cv::circle draws a simple or filled circle with a given center and radius. +@param img Image where the circle is drawn. +@param center Center of the circle. +@param radius Radius of the circle. +@param color Circle color. +@param thickness Thickness of the circle outline, if positive. Negative values, like #FILLED, +mean that a filled circle is to be drawn. +@param lineType Type of the circle boundary. See #LineTypes +@param shift Number of fractional bits in the coordinates of the center and in the radius value. + */ +CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @brief Draws a simple or thick elliptic arc or fills an ellipse sector. + +The function cv::ellipse with more parameters draws an ellipse outline, a filled ellipse, an elliptic +arc, or a filled ellipse sector. The drawing code uses general parametric form. +A piecewise-linear curve is used to approximate the elliptic arc +boundary. If you need more control of the ellipse rendering, you can retrieve the curve using +#ellipse2Poly and then render it with #polylines or fill it with #fillPoly. If you use the first +variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and +`endAngle=360`. If `startAngle` is greater than `endAngle`, they are swapped. The figure below explains +the meaning of the parameters to draw the blue arc. + +![Parameters of Elliptic Arc](pics/ellipse.svg) + +@param img Image. +@param center Center of the ellipse. +@param axes Half of the size of the ellipse main axes. +@param angle Ellipse rotation angle in degrees. +@param startAngle Starting angle of the elliptic arc in degrees. +@param endAngle Ending angle of the elliptic arc in degrees. +@param color Ellipse color. +@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that +a filled ellipse sector is to be drawn. +@param lineType Type of the ellipse boundary. See #LineTypes +@param shift Number of fractional bits in the coordinates of the center and values of axes. + */ +CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes, + double angle, double startAngle, double endAngle, + const Scalar& color, int thickness = 1, + int lineType = LINE_8, int shift = 0); + +/** @overload +@param img Image. +@param box Alternative ellipse representation via RotatedRect. This means that the function draws +an ellipse inscribed in the rotated rectangle. +@param color Ellipse color. +@param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that +a filled ellipse sector is to be drawn. +@param lineType Type of the ellipse boundary. See #LineTypes +*/ +CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, + int thickness = 1, int lineType = LINE_8); + +/* ----------------------------------------------------------------------------------------- */ +/* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */ +/* ----------------------------------------------------------------------------------------- */ + +/** @brief Draws a marker on a predefined position in an image. + +The function cv::drawMarker draws a marker on a given position in the image. For the moment several +marker types are supported, see #MarkerTypes for more information. + +@param img Image. +@param position The point where the crosshair is positioned. +@param color Line color. +@param markerType The specific type of marker you want to use, see #MarkerTypes +@param thickness Line thickness. +@param line_type Type of the line, See #LineTypes +@param markerSize The length of the marker axis [default = 20 pixels] + */ +CV_EXPORTS_W void drawMarker(InputOutputArray img, Point position, const Scalar& color, + int markerType = MARKER_CROSS, int markerSize=20, int thickness=1, + int line_type=8); + +/* ----------------------------------------------------------------------------------------- */ +/* END OF MARKER SECTION */ +/* ----------------------------------------------------------------------------------------- */ + +/** @brief Fills a convex polygon. + +The function cv::fillConvexPoly draws a filled convex polygon. This function is much faster than the +function #fillPoly . It can fill not only convex polygons but any monotonic polygon without +self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) +twice at the most (though, its top-most and/or the bottom edge could be horizontal). + +@param img Image. +@param points Polygon vertices. +@param color Polygon color. +@param lineType Type of the polygon boundaries. See #LineTypes +@param shift Number of fractional bits in the vertex coordinates. + */ +CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, + const Scalar& color, int lineType = LINE_8, + int shift = 0); + +/** @overload */ +CV_EXPORTS void fillConvexPoly(InputOutputArray img, const Point* pts, int npts, + const Scalar& color, int lineType = LINE_8, + int shift = 0); + +/** @example samples/cpp/tutorial_code/ImgProc/basic_drawing/Drawing_1.cpp +An example using drawing functions +Check @ref tutorial_random_generator_and_text "the corresponding tutorial" for more details +*/ + +/** @brief Fills the area bounded by one or more polygons. + +The function cv::fillPoly fills an area bounded by several polygonal contours. The function can fill +complex areas, for example, areas with holes, contours with self-intersections (some of their +parts), and so forth. + +@param img Image. +@param pts Array of polygons where each polygon is represented as an array of points. +@param color Polygon color. +@param lineType Type of the polygon boundaries. See #LineTypes +@param shift Number of fractional bits in the vertex coordinates. +@param offset Optional offset of all points of the contours. + */ +CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, + const Scalar& color, int lineType = LINE_8, int shift = 0, + Point offset = Point() ); + +/** @overload */ +CV_EXPORTS void fillPoly(InputOutputArray img, const Point** pts, + const int* npts, int ncontours, + const Scalar& color, int lineType = LINE_8, int shift = 0, + Point offset = Point() ); + +/** @brief Draws several polygonal curves. + +@param img Image. +@param pts Array of polygonal curves. +@param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, +the function draws a line from the last vertex of each curve to its first vertex. +@param color Polyline color. +@param thickness Thickness of the polyline edges. +@param lineType Type of the line segments. See #LineTypes +@param shift Number of fractional bits in the vertex coordinates. + +The function cv::polylines draws one or more polygonal curves. + */ +CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, + bool isClosed, const Scalar& color, + int thickness = 1, int lineType = LINE_8, int shift = 0 ); + +/** @overload */ +CV_EXPORTS void polylines(InputOutputArray img, const Point* const* pts, const int* npts, + int ncontours, bool isClosed, const Scalar& color, + int thickness = 1, int lineType = LINE_8, int shift = 0 ); + +/** @example samples/cpp/contours2.cpp +An example program illustrates the use of cv::findContours and cv::drawContours +\image html WindowsQtContoursOutput.png "Screenshot of the program" +*/ + +/** @example samples/cpp/segment_objects.cpp +An example using drawContours to clean up a background segmentation result +*/ + +/** @brief Draws contours outlines or filled contours. + +The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area +bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve +connected components from the binary image and label them: : +@include snippets/imgproc_drawContours.cpp + +@param image Destination image. +@param contours All the input contours. Each contour is stored as a point vector. +@param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. +@param color Color of the contours. +@param thickness Thickness of lines the contours are drawn with. If it is negative (for example, +thickness=#FILLED ), the contour interiors are drawn. +@param lineType Line connectivity. See #LineTypes +@param hierarchy Optional information about hierarchy. It is only needed if you want to draw only +some of the contours (see maxLevel ). +@param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. +If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function +draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This +parameter is only taken into account when there is hierarchy available. +@param offset Optional contour shift parameter. Shift all the drawn contours by the specified +\f$\texttt{offset}=(dx,dy)\f$ . +@note When thickness=#FILLED, the function is designed to handle connected components with holes correctly +even when no hierarchy data is provided. This is done by analyzing all the outlines together +using even-odd rule. This may give incorrect results if you have a joint collection of separately retrieved +contours. In order to solve this problem, you need to call #drawContours separately for each sub-group +of contours, or iterate over the collection using contourIdx parameter. + */ +CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours, + int contourIdx, const Scalar& color, + int thickness = 1, int lineType = LINE_8, + InputArray hierarchy = noArray(), + int maxLevel = INT_MAX, Point offset = Point() ); + +/** @brief Clips the line against the image rectangle. + +The function cv::clipLine calculates a part of the line segment that is entirely within the specified +rectangle. It returns false if the line segment is completely outside the rectangle. Otherwise, +it returns true . +@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . +@param pt1 First line point. +@param pt2 Second line point. + */ +CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); + +/** @overload +@param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . +@param pt1 First line point. +@param pt2 Second line point. +*/ +CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2); + +/** @overload +@param imgRect Image rectangle. +@param pt1 First line point. +@param pt2 Second line point. +*/ +CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); + +/** @brief Approximates an elliptic arc with a polyline. + +The function ellipse2Poly computes the vertices of a polyline that approximates the specified +elliptic arc. It is used by #ellipse. If `arcStart` is greater than `arcEnd`, they are swapped. + +@param center Center of the arc. +@param axes Half of the size of the ellipse main axes. See #ellipse for details. +@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. +@param arcStart Starting angle of the elliptic arc in degrees. +@param arcEnd Ending angle of the elliptic arc in degrees. +@param delta Angle between the subsequent polyline vertices. It defines the approximation +accuracy. +@param pts Output vector of polyline vertices. + */ +CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, + int arcStart, int arcEnd, int delta, + CV_OUT std::vector& pts ); + +/** @overload +@param center Center of the arc. +@param axes Half of the size of the ellipse main axes. See #ellipse for details. +@param angle Rotation angle of the ellipse in degrees. See #ellipse for details. +@param arcStart Starting angle of the elliptic arc in degrees. +@param arcEnd Ending angle of the elliptic arc in degrees. +@param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. +@param pts Output vector of polyline vertices. +*/ +CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle, + int arcStart, int arcEnd, int delta, + CV_OUT std::vector& pts); + +/** @brief Draws a text string. + +The function cv::putText renders the specified text string in the image. Symbols that cannot be rendered +using the specified font are replaced by question marks. See #getTextSize for a text rendering code +example. + +@param img Image. +@param text Text string to be drawn. +@param org Bottom-left corner of the text string in the image. +@param fontFace Font type, see #HersheyFonts. +@param fontScale Font scale factor that is multiplied by the font-specific base size. +@param color Text color. +@param thickness Thickness of the lines used to draw a text. +@param lineType Line type. See #LineTypes +@param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, +it is at the top-left corner. + */ +CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org, + int fontFace, double fontScale, Scalar color, + int thickness = 1, int lineType = LINE_8, + bool bottomLeftOrigin = false ); + +/** @brief Calculates the width and height of a text string. + +The function cv::getTextSize calculates and returns the size of a box that contains the specified text. +That is, the following code renders some text, the tight box surrounding it, and the baseline: : +@code + String text = "Funny text inside the box"; + int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; + double fontScale = 2; + int thickness = 3; + + Mat img(600, 800, CV_8UC3, Scalar::all(0)); + + int baseline=0; + Size textSize = getTextSize(text, fontFace, + fontScale, thickness, &baseline); + baseline += thickness; + + // center the text + Point textOrg((img.cols - textSize.width)/2, + (img.rows + textSize.height)/2); + + // draw the box + rectangle(img, textOrg + Point(0, baseline), + textOrg + Point(textSize.width, -textSize.height), + Scalar(0,0,255)); + // ... and the baseline first + line(img, textOrg + Point(0, thickness), + textOrg + Point(textSize.width, thickness), + Scalar(0, 0, 255)); + + // then put the text itself + putText(img, text, textOrg, fontFace, fontScale, + Scalar::all(255), thickness, 8); +@endcode + +@param text Input text string. +@param fontFace Font to use, see #HersheyFonts. +@param fontScale Font scale factor that is multiplied by the font-specific base size. +@param thickness Thickness of lines used to render the text. See #putText for details. +@param[out] baseLine y-coordinate of the baseline relative to the bottom-most text +point. +@return The size of a box that contains the specified text. + +@see putText + */ +CV_EXPORTS_W Size getTextSize(const String& text, int fontFace, + double fontScale, int thickness, + CV_OUT int* baseLine); + + +/** @brief Calculates the font-specific size to use to achieve a given height in pixels. + +@param fontFace Font to use, see cv::HersheyFonts. +@param pixelHeight Pixel height to compute the fontScale for +@param thickness Thickness of lines used to render the text.See putText for details. +@return The fontSize to use for cv::putText + +@see cv::putText +*/ +CV_EXPORTS_W double getFontScaleFromHeight(const int fontFace, + const int pixelHeight, + const int thickness = 1); + +/** @brief Class for iterating over all pixels on a raster line segment. + +The class LineIterator is used to get each pixel of a raster line connecting +two specified points. +It can be treated as a versatile implementation of the Bresenham algorithm +where you can stop at each pixel and do some extra processing, for +example, grab pixel values along the line or draw a line with an effect +(for example, with XOR operation). + +The number of pixels along the line is stored in LineIterator::count. +The method LineIterator::pos returns the current position in the image: + +@code{.cpp} +// grabs pixels along the line (pt1, pt2) +// from 8-bit 3-channel image to the buffer +LineIterator it(img, pt1, pt2, 8); +LineIterator it2 = it; +vector buf(it.count); + +for(int i = 0; i < it.count; i++, ++it) + buf[i] = *(const Vec3b*)*it; + +// alternative way of iterating through the line +for(int i = 0; i < it2.count; i++, ++it2) +{ + Vec3b val = img.at(it2.pos()); + CV_Assert(buf[i] == val); +} +@endcode +*/ +class CV_EXPORTS LineIterator +{ +public: + /** @brief Initializes iterator object for the given line and image. + + The returned iterator can be used to traverse all pixels on a line that + connects the given two points. + The line will be clipped on the image boundaries. + + @param img Underlying image. + @param pt1 First endpoint of the line. + @param pt2 The other endpoint of the line. + @param connectivity Pixel connectivity of the iterator. Valid values are 4 (iterator can move + up, down, left and right) and 8 (iterator can also move diagonally). + @param leftToRight If true, the line is traversed from the leftmost endpoint to the rightmost + endpoint. Otherwise, the line is traversed from \p pt1 to \p pt2. + */ + LineIterator( const Mat& img, Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(&img, Rect(0, 0, img.cols, img.rows), pt1, pt2, connectivity, leftToRight); + ptmode = false; + } + LineIterator( Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(0, Rect(std::min(pt1.x, pt2.x), + std::min(pt1.y, pt2.y), + std::max(pt1.x, pt2.x) - std::min(pt1.x, pt2.x) + 1, + std::max(pt1.y, pt2.y) - std::min(pt1.y, pt2.y) + 1), + pt1, pt2, connectivity, leftToRight); + ptmode = true; + } + LineIterator( Size boundingAreaSize, Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(0, Rect(0, 0, boundingAreaSize.width, boundingAreaSize.height), + pt1, pt2, connectivity, leftToRight); + ptmode = true; + } + LineIterator( Rect boundingAreaRect, Point pt1, Point pt2, + int connectivity = 8, bool leftToRight = false ) + { + init(0, boundingAreaRect, pt1, pt2, connectivity, leftToRight); + ptmode = true; + } + void init(const Mat* img, Rect boundingAreaRect, Point pt1, Point pt2, int connectivity, bool leftToRight); + + /** @brief Returns pointer to the current pixel. + */ + uchar* operator *(); + + /** @brief Moves iterator to the next pixel on the line. + + This is the prefix version (++it). + */ + LineIterator& operator ++(); + + /** @brief Moves iterator to the next pixel on the line. + + This is the postfix version (it++). + */ + LineIterator operator ++(int); + + /** @brief Returns coordinates of the current pixel. + */ + Point pos() const; + + uchar* ptr; + const uchar* ptr0; + int step, elemSize; + int err, count; + int minusDelta, plusDelta; + int minusStep, plusStep; + int minusShift, plusShift; + Point p; + bool ptmode; +}; + +//! @cond IGNORED + +// === LineIterator implementation === + +inline +uchar* LineIterator::operator *() +{ + return ptmode ? 0 : ptr; +} + +inline +LineIterator& LineIterator::operator ++() +{ + int mask = err < 0 ? -1 : 0; + err += minusDelta + (plusDelta & mask); + if(!ptmode) + { + ptr += minusStep + (plusStep & mask); + } + else + { + p.x += minusShift + (plusShift & mask); + p.y += minusStep + (plusStep & mask); + } + return *this; +} + +inline +LineIterator LineIterator::operator ++(int) +{ + LineIterator it = *this; + ++(*this); + return it; +} + +inline +Point LineIterator::pos() const +{ + if(!ptmode) + { + size_t offset = (size_t)(ptr - ptr0); + int y = (int)(offset/step); + int x = (int)((offset - (size_t)y*step)/elemSize); + return Point(x, y); + } + return p; +} + +//! @endcond + +//! @} imgproc_draw + +//! @} imgproc + +} // cv + + +#include "./imgproc/segmentation.hpp" + + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp index b0dd395112..c69527a779 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/bindings.hpp @@ -1,34 +1,34 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_IMGPROC_BINDINGS_HPP -#define OPENCV_IMGPROC_BINDINGS_HPP - -// This file contains special overloads for OpenCV bindings -// No need to use these functions in C++ code. - -namespace cv { - -/** @brief Finds lines in a binary image using the standard Hough transform and get accumulator. - * - * @note This function is for bindings use only. Use original function in C++ code - * - * @sa HoughLines - */ -CV_WRAP static inline -void HoughLinesWithAccumulator( - InputArray image, OutputArray lines, - double rho, double theta, int threshold, - double srn = 0, double stn = 0, - double min_theta = 0, double max_theta = CV_PI -) -{ - std::vector lines_acc; - HoughLines(image, lines_acc, rho, theta, threshold, srn, stn, min_theta, max_theta); - Mat(lines_acc).copyTo(lines); -} - -} // namespace - -#endif // OPENCV_IMGPROC_BINDINGS_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_IMGPROC_BINDINGS_HPP +#define OPENCV_IMGPROC_BINDINGS_HPP + +// This file contains special overloads for OpenCV bindings +// No need to use these functions in C++ code. + +namespace cv { + +/** @brief Finds lines in a binary image using the standard Hough transform and get accumulator. + * + * @note This function is for bindings use only. Use original function in C++ code + * + * @sa HoughLines + */ +CV_WRAP static inline +void HoughLinesWithAccumulator( + InputArray image, OutputArray lines, + double rho, double theta, int threshold, + double srn = 0, double stn = 0, + double min_theta = 0, double max_theta = CV_PI +) +{ + std::vector lines_acc; + HoughLines(image, lines_acc, rho, theta, threshold, srn, stn, min_theta, max_theta); + Mat(lines_acc).copyTo(lines); +} + +} // namespace + +#endif // OPENCV_IMGPROC_BINDINGS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp index 4c30f37b97..f17c6e7afb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/gcgraph.hpp @@ -1,395 +1,395 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP -#define OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP - -//! @cond IGNORED - -namespace cv { namespace detail { -template class GCGraph -{ -public: - GCGraph(); - GCGraph( unsigned int vtxCount, unsigned int edgeCount ); - ~GCGraph(); - void create( unsigned int vtxCount, unsigned int edgeCount ); - int addVtx(); - void addEdges( int i, int j, TWeight w, TWeight revw ); - void addTermWeights( int i, TWeight sourceW, TWeight sinkW ); - TWeight maxFlow(); - bool inSourceSegment( int i ); -private: - class Vtx - { - public: - Vtx *next; // initialized and used in maxFlow() only - int parent; - int first; - int ts; - int dist; - TWeight weight; - uchar t; - }; - class Edge - { - public: - int dst; - int next; - TWeight weight; - }; - - std::vector vtcs; - std::vector edges; - TWeight flow; -}; - -template -GCGraph::GCGraph() -{ - flow = 0; -} -template -GCGraph::GCGraph( unsigned int vtxCount, unsigned int edgeCount ) -{ - create( vtxCount, edgeCount ); -} -template -GCGraph::~GCGraph() -{ -} -template -void GCGraph::create( unsigned int vtxCount, unsigned int edgeCount ) -{ - vtcs.reserve( vtxCount ); - edges.reserve( edgeCount + 2 ); - flow = 0; -} - -template -int GCGraph::addVtx() -{ - Vtx v; - memset( &v, 0, sizeof(Vtx)); - vtcs.push_back(v); - return (int)vtcs.size() - 1; -} - -template -void GCGraph::addEdges( int i, int j, TWeight w, TWeight revw ) -{ - CV_Assert( i>=0 && i<(int)vtcs.size() ); - CV_Assert( j>=0 && j<(int)vtcs.size() ); - CV_Assert( w>=0 && revw>=0 ); - CV_Assert( i != j ); - - if( !edges.size() ) - edges.resize( 2 ); - - Edge fromI, toI; - fromI.dst = j; - fromI.next = vtcs[i].first; - fromI.weight = w; - vtcs[i].first = (int)edges.size(); - edges.push_back( fromI ); - - toI.dst = i; - toI.next = vtcs[j].first; - toI.weight = revw; - vtcs[j].first = (int)edges.size(); - edges.push_back( toI ); -} - -template -void GCGraph::addTermWeights( int i, TWeight sourceW, TWeight sinkW ) -{ - CV_Assert( i>=0 && i<(int)vtcs.size() ); - - TWeight dw = vtcs[i].weight; - if( dw > 0 ) - sourceW += dw; - else - sinkW -= dw; - flow += (sourceW < sinkW) ? sourceW : sinkW; - vtcs[i].weight = sourceW - sinkW; -} - -template -TWeight GCGraph::maxFlow() -{ - CV_Assert(!vtcs.empty()); - CV_Assert(!edges.empty()); - const int TERMINAL = -1, ORPHAN = -2; - Vtx stub, *nilNode = &stub, *first = nilNode, *last = nilNode; - int curr_ts = 0; - stub.next = nilNode; - Vtx *vtxPtr = &vtcs[0]; - Edge *edgePtr = &edges[0]; - - std::vector orphans; - - // initialize the active queue and the graph vertices - for( int i = 0; i < (int)vtcs.size(); i++ ) - { - Vtx* v = vtxPtr + i; - v->ts = 0; - if( v->weight != 0 ) - { - last = last->next = v; - v->dist = 1; - v->parent = TERMINAL; - v->t = v->weight < 0; - } - else - v->parent = 0; - } - first = first->next; - last->next = nilNode; - nilNode->next = 0; - - // run the search-path -> augment-graph -> restore-trees loop - for(;;) - { - Vtx* v, *u; - int e0 = -1, ei = 0, ej = 0; - TWeight minWeight, weight; - uchar vt; - - // grow S & T search trees, find an edge connecting them - while( first != nilNode ) - { - v = first; - if( v->parent ) - { - vt = v->t; - for( ei = v->first; ei != 0; ei = edgePtr[ei].next ) - { - if( edgePtr[ei^vt].weight == 0 ) - continue; - u = vtxPtr+edgePtr[ei].dst; - if( !u->parent ) - { - u->t = vt; - u->parent = ei ^ 1; - u->ts = v->ts; - u->dist = v->dist + 1; - if( !u->next ) - { - u->next = nilNode; - last = last->next = u; - } - continue; - } - - if( u->t != vt ) - { - e0 = ei ^ vt; - break; - } - - if( u->dist > v->dist+1 && u->ts <= v->ts ) - { - // reassign the parent - u->parent = ei ^ 1; - u->ts = v->ts; - u->dist = v->dist + 1; - } - } - if( e0 > 0 ) - break; - } - // exclude the vertex from the active list - first = first->next; - v->next = 0; - } - - if( e0 <= 0 ) - break; - - // find the minimum edge weight along the path - minWeight = edgePtr[e0].weight; - CV_Assert( minWeight > 0 ); - // k = 1: source tree, k = 0: destination tree - for( int k = 1; k >= 0; k-- ) - { - for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) - { - if( (ei = v->parent) < 0 ) - break; - weight = edgePtr[ei^k].weight; - minWeight = MIN(minWeight, weight); - CV_Assert( minWeight > 0 ); - } - weight = fabs(v->weight); - minWeight = MIN(minWeight, weight); - CV_Assert( minWeight > 0 ); - } - - // modify weights of the edges along the path and collect orphans - edgePtr[e0].weight -= minWeight; - edgePtr[e0^1].weight += minWeight; - flow += minWeight; - - // k = 1: source tree, k = 0: destination tree - for( int k = 1; k >= 0; k-- ) - { - for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) - { - if( (ei = v->parent) < 0 ) - break; - edgePtr[ei^(k^1)].weight += minWeight; - if( (edgePtr[ei^k].weight -= minWeight) == 0 ) - { - orphans.push_back(v); - v->parent = ORPHAN; - } - } - - v->weight = v->weight + minWeight*(1-k*2); - if( v->weight == 0 ) - { - orphans.push_back(v); - v->parent = ORPHAN; - } - } - - // restore the search trees by finding new parents for the orphans - curr_ts++; - while( !orphans.empty() ) - { - Vtx* v2 = orphans.back(); - orphans.pop_back(); - - int d, minDist = INT_MAX; - e0 = 0; - vt = v2->t; - - for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) - { - if( edgePtr[ei^(vt^1)].weight == 0 ) - continue; - u = vtxPtr+edgePtr[ei].dst; - if( u->t != vt || u->parent == 0 ) - continue; - // compute the distance to the tree root - for( d = 0;; ) - { - if( u->ts == curr_ts ) - { - d += u->dist; - break; - } - ej = u->parent; - d++; - if( ej < 0 ) - { - if( ej == ORPHAN ) - d = INT_MAX-1; - else - { - u->ts = curr_ts; - u->dist = 1; - } - break; - } - u = vtxPtr+edgePtr[ej].dst; - } - - // update the distance - if( ++d < INT_MAX ) - { - if( d < minDist ) - { - minDist = d; - e0 = ei; - } - for( u = vtxPtr+edgePtr[ei].dst; u->ts != curr_ts; u = vtxPtr+edgePtr[u->parent].dst ) - { - u->ts = curr_ts; - u->dist = --d; - } - } - } - - if( (v2->parent = e0) > 0 ) - { - v2->ts = curr_ts; - v2->dist = minDist; - continue; - } - - /* no parent is found */ - v2->ts = 0; - for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) - { - u = vtxPtr+edgePtr[ei].dst; - ej = u->parent; - if( u->t != vt || !ej ) - continue; - if( edgePtr[ei^(vt^1)].weight && !u->next ) - { - u->next = nilNode; - last = last->next = u; - } - if( ej > 0 && vtxPtr+edgePtr[ej].dst == v2 ) - { - orphans.push_back(u); - u->parent = ORPHAN; - } - } - } - } - return flow; -} - -template -bool GCGraph::inSourceSegment( int i ) -{ - CV_Assert( i>=0 && i<(int)vtcs.size() ); - return vtcs[i].t == 0; -} - -}} // namespace detail, cv - - -//! @endcond - -#endif // OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// Intel License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of Intel Corporation may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP +#define OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP + +//! @cond IGNORED + +namespace cv { namespace detail { +template class GCGraph +{ +public: + GCGraph(); + GCGraph( unsigned int vtxCount, unsigned int edgeCount ); + ~GCGraph(); + void create( unsigned int vtxCount, unsigned int edgeCount ); + int addVtx(); + void addEdges( int i, int j, TWeight w, TWeight revw ); + void addTermWeights( int i, TWeight sourceW, TWeight sinkW ); + TWeight maxFlow(); + bool inSourceSegment( int i ); +private: + class Vtx + { + public: + Vtx *next; // initialized and used in maxFlow() only + int parent; + int first; + int ts; + int dist; + TWeight weight; + uchar t; + }; + class Edge + { + public: + int dst; + int next; + TWeight weight; + }; + + std::vector vtcs; + std::vector edges; + TWeight flow; +}; + +template +GCGraph::GCGraph() +{ + flow = 0; +} +template +GCGraph::GCGraph( unsigned int vtxCount, unsigned int edgeCount ) +{ + create( vtxCount, edgeCount ); +} +template +GCGraph::~GCGraph() +{ +} +template +void GCGraph::create( unsigned int vtxCount, unsigned int edgeCount ) +{ + vtcs.reserve( vtxCount ); + edges.reserve( edgeCount + 2 ); + flow = 0; +} + +template +int GCGraph::addVtx() +{ + Vtx v; + memset( &v, 0, sizeof(Vtx)); + vtcs.push_back(v); + return (int)vtcs.size() - 1; +} + +template +void GCGraph::addEdges( int i, int j, TWeight w, TWeight revw ) +{ + CV_Assert( i>=0 && i<(int)vtcs.size() ); + CV_Assert( j>=0 && j<(int)vtcs.size() ); + CV_Assert( w>=0 && revw>=0 ); + CV_Assert( i != j ); + + if( !edges.size() ) + edges.resize( 2 ); + + Edge fromI, toI; + fromI.dst = j; + fromI.next = vtcs[i].first; + fromI.weight = w; + vtcs[i].first = (int)edges.size(); + edges.push_back( fromI ); + + toI.dst = i; + toI.next = vtcs[j].first; + toI.weight = revw; + vtcs[j].first = (int)edges.size(); + edges.push_back( toI ); +} + +template +void GCGraph::addTermWeights( int i, TWeight sourceW, TWeight sinkW ) +{ + CV_Assert( i>=0 && i<(int)vtcs.size() ); + + TWeight dw = vtcs[i].weight; + if( dw > 0 ) + sourceW += dw; + else + sinkW -= dw; + flow += (sourceW < sinkW) ? sourceW : sinkW; + vtcs[i].weight = sourceW - sinkW; +} + +template +TWeight GCGraph::maxFlow() +{ + CV_Assert(!vtcs.empty()); + CV_Assert(!edges.empty()); + const int TERMINAL = -1, ORPHAN = -2; + Vtx stub, *nilNode = &stub, *first = nilNode, *last = nilNode; + int curr_ts = 0; + stub.next = nilNode; + Vtx *vtxPtr = &vtcs[0]; + Edge *edgePtr = &edges[0]; + + std::vector orphans; + + // initialize the active queue and the graph vertices + for( int i = 0; i < (int)vtcs.size(); i++ ) + { + Vtx* v = vtxPtr + i; + v->ts = 0; + if( v->weight != 0 ) + { + last = last->next = v; + v->dist = 1; + v->parent = TERMINAL; + v->t = v->weight < 0; + } + else + v->parent = 0; + } + first = first->next; + last->next = nilNode; + nilNode->next = 0; + + // run the search-path -> augment-graph -> restore-trees loop + for(;;) + { + Vtx* v, *u; + int e0 = -1, ei = 0, ej = 0; + TWeight minWeight, weight; + uchar vt; + + // grow S & T search trees, find an edge connecting them + while( first != nilNode ) + { + v = first; + if( v->parent ) + { + vt = v->t; + for( ei = v->first; ei != 0; ei = edgePtr[ei].next ) + { + if( edgePtr[ei^vt].weight == 0 ) + continue; + u = vtxPtr+edgePtr[ei].dst; + if( !u->parent ) + { + u->t = vt; + u->parent = ei ^ 1; + u->ts = v->ts; + u->dist = v->dist + 1; + if( !u->next ) + { + u->next = nilNode; + last = last->next = u; + } + continue; + } + + if( u->t != vt ) + { + e0 = ei ^ vt; + break; + } + + if( u->dist > v->dist+1 && u->ts <= v->ts ) + { + // reassign the parent + u->parent = ei ^ 1; + u->ts = v->ts; + u->dist = v->dist + 1; + } + } + if( e0 > 0 ) + break; + } + // exclude the vertex from the active list + first = first->next; + v->next = 0; + } + + if( e0 <= 0 ) + break; + + // find the minimum edge weight along the path + minWeight = edgePtr[e0].weight; + CV_Assert( minWeight > 0 ); + // k = 1: source tree, k = 0: destination tree + for( int k = 1; k >= 0; k-- ) + { + for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) + { + if( (ei = v->parent) < 0 ) + break; + weight = edgePtr[ei^k].weight; + minWeight = MIN(minWeight, weight); + CV_Assert( minWeight > 0 ); + } + weight = fabs(v->weight); + minWeight = MIN(minWeight, weight); + CV_Assert( minWeight > 0 ); + } + + // modify weights of the edges along the path and collect orphans + edgePtr[e0].weight -= minWeight; + edgePtr[e0^1].weight += minWeight; + flow += minWeight; + + // k = 1: source tree, k = 0: destination tree + for( int k = 1; k >= 0; k-- ) + { + for( v = vtxPtr+edgePtr[e0^k].dst;; v = vtxPtr+edgePtr[ei].dst ) + { + if( (ei = v->parent) < 0 ) + break; + edgePtr[ei^(k^1)].weight += minWeight; + if( (edgePtr[ei^k].weight -= minWeight) == 0 ) + { + orphans.push_back(v); + v->parent = ORPHAN; + } + } + + v->weight = v->weight + minWeight*(1-k*2); + if( v->weight == 0 ) + { + orphans.push_back(v); + v->parent = ORPHAN; + } + } + + // restore the search trees by finding new parents for the orphans + curr_ts++; + while( !orphans.empty() ) + { + Vtx* v2 = orphans.back(); + orphans.pop_back(); + + int d, minDist = INT_MAX; + e0 = 0; + vt = v2->t; + + for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) + { + if( edgePtr[ei^(vt^1)].weight == 0 ) + continue; + u = vtxPtr+edgePtr[ei].dst; + if( u->t != vt || u->parent == 0 ) + continue; + // compute the distance to the tree root + for( d = 0;; ) + { + if( u->ts == curr_ts ) + { + d += u->dist; + break; + } + ej = u->parent; + d++; + if( ej < 0 ) + { + if( ej == ORPHAN ) + d = INT_MAX-1; + else + { + u->ts = curr_ts; + u->dist = 1; + } + break; + } + u = vtxPtr+edgePtr[ej].dst; + } + + // update the distance + if( ++d < INT_MAX ) + { + if( d < minDist ) + { + minDist = d; + e0 = ei; + } + for( u = vtxPtr+edgePtr[ei].dst; u->ts != curr_ts; u = vtxPtr+edgePtr[u->parent].dst ) + { + u->ts = curr_ts; + u->dist = --d; + } + } + } + + if( (v2->parent = e0) > 0 ) + { + v2->ts = curr_ts; + v2->dist = minDist; + continue; + } + + /* no parent is found */ + v2->ts = 0; + for( ei = v2->first; ei != 0; ei = edgePtr[ei].next ) + { + u = vtxPtr+edgePtr[ei].dst; + ej = u->parent; + if( u->t != vt || !ej ) + continue; + if( edgePtr[ei^(vt^1)].weight && !u->next ) + { + u->next = nilNode; + last = last->next = u; + } + if( ej > 0 && vtxPtr+edgePtr[ej].dst == v2 ) + { + orphans.push_back(u); + u->parent = ORPHAN; + } + } + } + } + return flow; +} + +template +bool GCGraph::inSourceSegment( int i ) +{ + CV_Assert( i>=0 && i<(int)vtcs.size() ); + return vtcs[i].t == 0; +} + +}} // namespace detail, cv + + +//! @endcond + +#endif // OPENCV_IMGPROC_DETAIL_GCGRAPH_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp index 9917c8f0f2..029d9c90e8 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/detail/legacy.hpp @@ -1,38 +1,38 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html - -#ifndef OPENCV_IMGPROC_DETAIL_LEGACY_HPP -#define OPENCV_IMGPROC_DETAIL_LEGACY_HPP - -#include "opencv2/imgproc.hpp" - -namespace cv { - -#ifdef __OPENCV_BUILD - -CV_EXPORTS void findContours_legacy(InputArray _image, - OutputArrayOfArrays _contours, - OutputArray _hierarchy, - int mode, - int method, - Point offset = Point()); -CV_EXPORTS void findContours_legacy(InputArray image, - OutputArrayOfArrays contours, - int mode, - int method, - Point offset = Point()); - -CV_EXPORTS float EMD_legacy( InputArray _signature1, InputArray _signature2, - int distType, InputArray _cost, - float* lowerBound, OutputArray _flow ); - -CV_EXPORTS float wrapperEMD_legacy(InputArray _signature1, InputArray _signature2, - int distType, InputArray _cost, - Ptr lowerBound, OutputArray _flow); - -#endif - -} // namespace cv - -#endif // OPENCV_IMGPROC_DETAIL_LEGACY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html + +#ifndef OPENCV_IMGPROC_DETAIL_LEGACY_HPP +#define OPENCV_IMGPROC_DETAIL_LEGACY_HPP + +#include "opencv2/imgproc.hpp" + +namespace cv { + +#ifdef __OPENCV_BUILD + +CV_EXPORTS void findContours_legacy(InputArray _image, + OutputArrayOfArrays _contours, + OutputArray _hierarchy, + int mode, + int method, + Point offset = Point()); +CV_EXPORTS void findContours_legacy(InputArray image, + OutputArrayOfArrays contours, + int mode, + int method, + Point offset = Point()); + +CV_EXPORTS float EMD_legacy( InputArray _signature1, InputArray _signature2, + int distType, InputArray _cost, + float* lowerBound, OutputArray _flow ); + +CV_EXPORTS float wrapperEMD_legacy(InputArray _signature1, InputArray _signature2, + int distType, InputArray _cost, + Ptr lowerBound, OutputArray _flow); + +#endif + +} // namespace cv + +#endif // OPENCV_IMGPROC_DETAIL_LEGACY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp index 814b19ea7e..1d1db5e3a0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/hal.hpp @@ -1,269 +1,269 @@ -#ifndef CV_IMGPROC_HAL_HPP -#define CV_IMGPROC_HAL_HPP - -#include "opencv2/core/cvdef.h" -#include "opencv2/core/cvstd.hpp" -#include "opencv2/core/utility.hpp" -#include "opencv2/core/hal/interface.h" - -namespace cv { namespace hal { - -//! @addtogroup imgproc_hal_functions -//! @{ - -//--------------------------- -//! @cond IGNORED - -struct CV_EXPORTS Filter2D -{ - CV_DEPRECATED static Ptr create(uchar * , size_t , int , - int , int , - int , int , - int , int , - int , double , - int , int , - bool , bool ); - virtual void apply(uchar * , size_t , - uchar * , size_t , - int , int , - int , int , - int , int ) = 0; - virtual ~Filter2D() {} -}; - -struct CV_EXPORTS SepFilter2D -{ - CV_DEPRECATED static Ptr create(int , int , int , - uchar * , int , - uchar * , int , - int , int , - double , int ); - virtual void apply(uchar * , size_t , - uchar * , size_t , - int , int , - int , int , - int , int ) = 0; - virtual ~SepFilter2D() {} -}; - - -struct CV_EXPORTS Morph -{ - CV_DEPRECATED static Ptr create(int , int , int , int , int , - int , uchar * , size_t , - int , int , - int , int , - int , const double *, - int , bool , bool ); - virtual void apply(uchar * , size_t , uchar * , size_t , int , int , - int , int , int , int , - int , int , int , int ) = 0; - virtual ~Morph() {} -}; - -//! @endcond -//--------------------------- - -CV_EXPORTS void filter2D(int stype, int dtype, int kernel_type, - uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int full_width, int full_height, - int offset_x, int offset_y, - uchar * kernel_data, size_t kernel_step, - int kernel_width, int kernel_height, - int anchor_x, int anchor_y, - double delta, int borderType, - bool isSubmatrix); - -CV_EXPORTS void sepFilter2D(int stype, int dtype, int ktype, - uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int full_width, int full_height, - int offset_x, int offset_y, - uchar * kernelx_data, int kernelx_len, - uchar * kernely_data, int kernely_len, - int anchor_x, int anchor_y, - double delta, int borderType); - -CV_EXPORTS void morph(int op, int src_type, int dst_type, - uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int roi_width, int roi_height, int roi_x, int roi_y, - int roi_width2, int roi_height2, int roi_x2, int roi_y2, - int kernel_type, uchar * kernel_data, size_t kernel_step, - int kernel_width, int kernel_height, int anchor_x, int anchor_y, - int borderType, const double borderValue[4], - int iterations, bool isSubmatrix); - - -CV_EXPORTS void resize(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - double inv_scale_x, double inv_scale_y, int interpolation); - -CV_EXPORTS void warpAffine(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - const double M[6], int interpolation, int borderType, const double borderValue[4]); - -CV_EXPORTS void warpAffineBlocklineNN(int *adelta, int *bdelta, short* xy, int X0, int Y0, int bw); - -CV_EXPORTS void warpAffineBlockline(int *adelta, int *bdelta, short* xy, short* alpha, int X0, int Y0, int bw); - -CV_EXPORTS void warpPerspective(int src_type, - const uchar * src_data, size_t src_step, int src_width, int src_height, - uchar * dst_data, size_t dst_step, int dst_width, int dst_height, - const double M[9], int interpolation, int borderType, const double borderValue[4]); - -CV_EXPORTS void warpPerspectiveBlocklineNN(const double *M, short* xy, double X0, double Y0, double W0, int bw); - -CV_EXPORTS void warpPerspectiveBlockline(const double *M, short* xy, short* alpha, double X0, double Y0, double W0, int bw); - -CV_EXPORTS void cvtBGRtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, int dcn, bool swapBlue); - -CV_EXPORTS void cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int greenBits); - -CV_EXPORTS void cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int dcn, bool swapBlue, int greenBits); - -CV_EXPORTS void cvtBGRtoGray(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue); - -CV_EXPORTS void cvtGraytoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn); - -CV_EXPORTS void cvtBGR5x5toGray(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int greenBits); - -CV_EXPORTS void cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int greenBits); -CV_EXPORTS void cvtBGRtoYUV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue, bool isCbCr, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue, bool isCbCr, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtBGRtoXYZ(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue); - -CV_EXPORTS void cvtXYZtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue); - -CV_EXPORTS void cvtBGRtoHSV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV); - -CV_EXPORTS void cvtHSVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV); - -CV_EXPORTS void cvtBGRtoLab(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int scn, bool swapBlue, bool isLab, bool srgb); - -CV_EXPORTS void cvtLabtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int depth, int dcn, bool swapBlue, bool isLab, bool srgb); - -CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -//! Separate Y and UV planes -CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, const uchar * uv_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, size_t y_step, const uchar * uv_data, size_t uv_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int dst_width, int dst_height, - int dcn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int uIdx, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -//! Separate Y and UV planes -CV_EXPORTS void cvtBGRtoTwoPlaneYUV(const uchar * src_data, size_t src_step, - uchar * y_data, uchar * uv_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int uIdx); - -CV_EXPORTS void cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int dcn, bool swapBlue, int uIdx, int ycn, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtOnePlaneBGRtoYUV(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height, - int scn, bool swapBlue, int uIdx, int ycn, - AlgorithmHint hint = ALGO_HINT_DEFAULT); - -CV_EXPORTS void cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height); - -CV_EXPORTS void cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, - uchar * dst_data, size_t dst_step, - int width, int height); - -CV_EXPORTS void integral(int depth, int sdepth, int sqdepth, - const uchar* src, size_t srcstep, - uchar* sum, size_t sumstep, - uchar* sqsum, size_t sqsumstep, - uchar* tilted, size_t tstep, - int width, int height, int cn); - -//! @} - -}} - -#endif // CV_IMGPROC_HAL_HPP +#ifndef CV_IMGPROC_HAL_HPP +#define CV_IMGPROC_HAL_HPP + +#include "opencv2/core/cvdef.h" +#include "opencv2/core/cvstd.hpp" +#include "opencv2/core/utility.hpp" +#include "opencv2/core/hal/interface.h" + +namespace cv { namespace hal { + +//! @addtogroup imgproc_hal_functions +//! @{ + +//--------------------------- +//! @cond IGNORED + +struct CV_EXPORTS Filter2D +{ + CV_DEPRECATED static Ptr create(uchar * , size_t , int , + int , int , + int , int , + int , int , + int , double , + int , int , + bool , bool ); + virtual void apply(uchar * , size_t , + uchar * , size_t , + int , int , + int , int , + int , int ) = 0; + virtual ~Filter2D() {} +}; + +struct CV_EXPORTS SepFilter2D +{ + CV_DEPRECATED static Ptr create(int , int , int , + uchar * , int , + uchar * , int , + int , int , + double , int ); + virtual void apply(uchar * , size_t , + uchar * , size_t , + int , int , + int , int , + int , int ) = 0; + virtual ~SepFilter2D() {} +}; + + +struct CV_EXPORTS Morph +{ + CV_DEPRECATED static Ptr create(int , int , int , int , int , + int , uchar * , size_t , + int , int , + int , int , + int , const double *, + int , bool , bool ); + virtual void apply(uchar * , size_t , uchar * , size_t , int , int , + int , int , int , int , + int , int , int , int ) = 0; + virtual ~Morph() {} +}; + +//! @endcond +//--------------------------- + +CV_EXPORTS void filter2D(int stype, int dtype, int kernel_type, + uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int full_width, int full_height, + int offset_x, int offset_y, + uchar * kernel_data, size_t kernel_step, + int kernel_width, int kernel_height, + int anchor_x, int anchor_y, + double delta, int borderType, + bool isSubmatrix); + +CV_EXPORTS void sepFilter2D(int stype, int dtype, int ktype, + uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int full_width, int full_height, + int offset_x, int offset_y, + uchar * kernelx_data, int kernelx_len, + uchar * kernely_data, int kernely_len, + int anchor_x, int anchor_y, + double delta, int borderType); + +CV_EXPORTS void morph(int op, int src_type, int dst_type, + uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int roi_width, int roi_height, int roi_x, int roi_y, + int roi_width2, int roi_height2, int roi_x2, int roi_y2, + int kernel_type, uchar * kernel_data, size_t kernel_step, + int kernel_width, int kernel_height, int anchor_x, int anchor_y, + int borderType, const double borderValue[4], + int iterations, bool isSubmatrix); + + +CV_EXPORTS void resize(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + double inv_scale_x, double inv_scale_y, int interpolation); + +CV_EXPORTS void warpAffine(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + const double M[6], int interpolation, int borderType, const double borderValue[4]); + +CV_EXPORTS void warpAffineBlocklineNN(int *adelta, int *bdelta, short* xy, int X0, int Y0, int bw); + +CV_EXPORTS void warpAffineBlockline(int *adelta, int *bdelta, short* xy, short* alpha, int X0, int Y0, int bw); + +CV_EXPORTS void warpPerspective(int src_type, + const uchar * src_data, size_t src_step, int src_width, int src_height, + uchar * dst_data, size_t dst_step, int dst_width, int dst_height, + const double M[9], int interpolation, int borderType, const double borderValue[4]); + +CV_EXPORTS void warpPerspectiveBlocklineNN(const double *M, short* xy, double X0, double Y0, double W0, int bw); + +CV_EXPORTS void warpPerspectiveBlockline(const double *M, short* xy, short* alpha, double X0, double Y0, double W0, int bw); + +CV_EXPORTS void cvtBGRtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, int dcn, bool swapBlue); + +CV_EXPORTS void cvtBGRtoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int greenBits); + +CV_EXPORTS void cvtBGR5x5toBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int greenBits); + +CV_EXPORTS void cvtBGRtoGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue); + +CV_EXPORTS void cvtGraytoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn); + +CV_EXPORTS void cvtBGR5x5toGray(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits); + +CV_EXPORTS void cvtGraytoBGR5x5(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int greenBits); +CV_EXPORTS void cvtBGRtoYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isCbCr, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isCbCr, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtBGRtoXYZ(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue); + +CV_EXPORTS void cvtXYZtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue); + +CV_EXPORTS void cvtBGRtoHSV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isFullRange, bool isHSV); + +CV_EXPORTS void cvtHSVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isFullRange, bool isHSV); + +CV_EXPORTS void cvtBGRtoLab(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int scn, bool swapBlue, bool isLab, bool srgb); + +CV_EXPORTS void cvtLabtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int depth, int dcn, bool swapBlue, bool isLab, bool srgb); + +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +//! Separate Y and UV planes +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, const uchar * uv_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtTwoPlaneYUVtoBGR(const uchar * y_data, size_t y_step, const uchar * uv_data, size_t uv_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtThreePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int dst_width, int dst_height, + int dcn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtBGRtoThreePlaneYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +//! Separate Y and UV planes +CV_EXPORTS void cvtBGRtoTwoPlaneYUV(const uchar * src_data, size_t src_step, + uchar * y_data, uchar * uv_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx); + +CV_EXPORTS void cvtOnePlaneYUVtoBGR(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int dcn, bool swapBlue, int uIdx, int ycn, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtOnePlaneBGRtoYUV(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height, + int scn, bool swapBlue, int uIdx, int ycn, + AlgorithmHint hint = ALGO_HINT_DEFAULT); + +CV_EXPORTS void cvtRGBAtoMultipliedRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height); + +CV_EXPORTS void cvtMultipliedRGBAtoRGBA(const uchar * src_data, size_t src_step, + uchar * dst_data, size_t dst_step, + int width, int height); + +CV_EXPORTS void integral(int depth, int sdepth, int sqdepth, + const uchar* src, size_t srcstep, + uchar* sum, size_t sumstep, + uchar* sqsum, size_t sqsumstep, + uchar* tilted, size_t tstep, + int width, int height, int cn); + +//! @} + +}} + +#endif // CV_IMGPROC_HAL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h index 29773aa34d..8e485b9fca 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/hal/interface.h @@ -1,52 +1,52 @@ -#ifndef OPENCV_IMGPROC_HAL_INTERFACE_H -#define OPENCV_IMGPROC_HAL_INTERFACE_H - -//! @addtogroup imgproc_hal_interface -//! @{ - -//! @name Interpolation modes -//! @sa cv::InterpolationFlags -//! @{ -#define CV_HAL_INTER_NEAREST 0 -#define CV_HAL_INTER_LINEAR 1 -#define CV_HAL_INTER_CUBIC 2 -#define CV_HAL_INTER_AREA 3 -#define CV_HAL_INTER_LANCZOS4 4 -#define CV_HAL_INTER_LINEAR_EXACT 5 -#define CV_HAL_INTER_NEAREST_EXACT 6 -#define CV_HAL_INTER_MAX 7 -#define CV_HAL_WARP_FILL_OUTLIERS 8 -#define CV_HAL_WARP_INVERSE_MAP 16 -#define CV_HAL_WARP_RELATIVE_MAP 32 -//! @} - -//! @name Morphology operations -//! @sa cv::MorphTypes -//! @{ -#define CV_HAL_MORPH_ERODE 0 -#define CV_HAL_MORPH_DILATE 1 -//! @} - -//! @name Threshold types -//! @sa cv::ThresholdTypes -//! @{ -#define CV_HAL_THRESH_BINARY 0 -#define CV_HAL_THRESH_BINARY_INV 1 -#define CV_HAL_THRESH_TRUNC 2 -#define CV_HAL_THRESH_TOZERO 3 -#define CV_HAL_THRESH_TOZERO_INV 4 -#define CV_HAL_THRESH_MASK 7 -#define CV_HAL_THRESH_OTSU 8 -#define CV_HAL_THRESH_TRIANGLE 16 -//! @} - -//! @name Adaptive threshold algorithm -//! @sa cv::AdaptiveThresholdTypes -//! @{ -#define CV_HAL_ADAPTIVE_THRESH_MEAN_C 0 -#define CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C 1 -//! @} - -//! @} - -#endif +#ifndef OPENCV_IMGPROC_HAL_INTERFACE_H +#define OPENCV_IMGPROC_HAL_INTERFACE_H + +//! @addtogroup imgproc_hal_interface +//! @{ + +//! @name Interpolation modes +//! @sa cv::InterpolationFlags +//! @{ +#define CV_HAL_INTER_NEAREST 0 +#define CV_HAL_INTER_LINEAR 1 +#define CV_HAL_INTER_CUBIC 2 +#define CV_HAL_INTER_AREA 3 +#define CV_HAL_INTER_LANCZOS4 4 +#define CV_HAL_INTER_LINEAR_EXACT 5 +#define CV_HAL_INTER_NEAREST_EXACT 6 +#define CV_HAL_INTER_MAX 7 +#define CV_HAL_WARP_FILL_OUTLIERS 8 +#define CV_HAL_WARP_INVERSE_MAP 16 +#define CV_HAL_WARP_RELATIVE_MAP 32 +//! @} + +//! @name Morphology operations +//! @sa cv::MorphTypes +//! @{ +#define CV_HAL_MORPH_ERODE 0 +#define CV_HAL_MORPH_DILATE 1 +//! @} + +//! @name Threshold types +//! @sa cv::ThresholdTypes +//! @{ +#define CV_HAL_THRESH_BINARY 0 +#define CV_HAL_THRESH_BINARY_INV 1 +#define CV_HAL_THRESH_TRUNC 2 +#define CV_HAL_THRESH_TOZERO 3 +#define CV_HAL_THRESH_TOZERO_INV 4 +#define CV_HAL_THRESH_MASK 7 +#define CV_HAL_THRESH_OTSU 8 +#define CV_HAL_THRESH_TRIANGLE 16 +//! @} + +//! @name Adaptive threshold algorithm +//! @sa cv::AdaptiveThresholdTypes +//! @{ +#define CV_HAL_ADAPTIVE_THRESH_MEAN_C 0 +#define CV_HAL_ADAPTIVE_THRESH_GAUSSIAN_C 1 +//! @} + +//! @} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp index d661014131..4175bd0bc0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/imgproc.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/imgproc.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h index 1dbb6d7059..9085b0fa74 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/imgproc_c.h @@ -1,1185 +1,1185 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_IMGPROC_IMGPROC_C_H -#define OPENCV_IMGPROC_IMGPROC_C_H - -#include "opencv2/imgproc/types_c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup imgproc_c -@{ -*/ - -/*********************** Background statistics accumulation *****************************/ - -/** @brief Adds image to accumulator -@see cv::accumulate -*/ -CVAPI(void) cvAcc( const CvArr* image, CvArr* sum, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Adds squared image to accumulator -@see cv::accumulateSquare -*/ -CVAPI(void) cvSquareAcc( const CvArr* image, CvArr* sqsum, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Adds a product of two images to accumulator -@see cv::accumulateProduct -*/ -CVAPI(void) cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc, - const CvArr* mask CV_DEFAULT(NULL) ); - -/** @brief Adds image to accumulator with weights: acc = acc*(1-alpha) + image*alpha -@see cv::accumulateWeighted -*/ -CVAPI(void) cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, - const CvArr* mask CV_DEFAULT(NULL) ); - -/****************************************************************************************\ -* Image Processing * -\****************************************************************************************/ - -/** Copies source 2D array inside of the larger destination array and - makes a border of the specified type (IPL_BORDER_*) around the copied area. */ -CVAPI(void) cvCopyMakeBorder( const CvArr* src, CvArr* dst, CvPoint offset, - int bordertype, CvScalar value CV_DEFAULT(cvScalarAll(0))); - -/** @brief Smooths the image in one of several ways. - -@param src The source image -@param dst The destination image -@param smoothtype Type of the smoothing, see SmoothMethod_c -@param size1 The first parameter of the smoothing operation, the aperture width. Must be a -positive odd number (1, 3, 5, ...) -@param size2 The second parameter of the smoothing operation, the aperture height. Ignored by -CV_MEDIAN and CV_BILATERAL methods. In the case of simple scaled/non-scaled and Gaussian blur if -size2 is zero, it is set to size1. Otherwise it must be a positive odd number. -@param sigma1 In the case of a Gaussian parameter this parameter may specify Gaussian \f$\sigma\f$ -(standard deviation). If it is zero, it is calculated from the kernel size: -\f[\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n= \begin{array}{l l} \mbox{\texttt{size1} for horizontal kernel} \\ \mbox{\texttt{size2} for vertical kernel} \end{array}\f] -Using standard sigma for small kernels ( \f$3\times 3\f$ to \f$7\times 7\f$ ) gives better speed. If -sigma1 is not zero, while size1 and size2 are zeros, the kernel size is calculated from the -sigma (to provide accurate enough operation). -@param sigma2 additional parameter for bilateral filtering - -@see cv::GaussianBlur, cv::blur, cv::medianBlur, cv::bilateralFilter. - */ -CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst, - int smoothtype CV_DEFAULT(CV_GAUSSIAN), - int size1 CV_DEFAULT(3), - int size2 CV_DEFAULT(0), - double sigma1 CV_DEFAULT(0), - double sigma2 CV_DEFAULT(0)); - -/** @brief Convolves an image with the kernel. - -@param src input image. -@param dst output image of the same size and the same number of channels as src. -@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point -matrix; if you want to apply different kernels to different channels, split the image into -separate color planes using split and process them individually. -@param anchor anchor of the kernel that indicates the relative position of a filtered point within -the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor -is at the kernel center. - -@see cv::filter2D - */ -CVAPI(void) cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, - CvPoint anchor CV_DEFAULT(cvPoint(-1,-1))); - -/** @brief Finds integral image: SUM(X,Y) = sum(x \texttt{hist1}(I)\)}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if \(\texttt{hist1}(I) \ne 0\) and \(\texttt{hist2}(I) \le \texttt{hist1}(I)\)}\f] - -@param hist1 First histogram (the divisor). -@param hist2 Second histogram. -@param dst_hist Destination histogram. -@param scale Scale factor for the destination histogram. - */ -CVAPI(void) cvCalcProbDensity( const CvHistogram* hist1, const CvHistogram* hist2, - CvHistogram* dst_hist, double scale CV_DEFAULT(255) ); - -/** @brief equalizes histogram of 8-bit single-channel image -@see cv::equalizeHist -*/ -CVAPI(void) cvEqualizeHist( const CvArr* src, CvArr* dst ); - - -/** @brief Applies distance transform to binary image -@see cv::distanceTransform -*/ -CVAPI(void) cvDistTransform( const CvArr* src, CvArr* dst, - int distance_type CV_DEFAULT(CV_DIST_L2), - int mask_size CV_DEFAULT(3), - const float* mask CV_DEFAULT(NULL), - CvArr* labels CV_DEFAULT(NULL), - int labelType CV_DEFAULT(CV_DIST_LABEL_CCOMP)); - - -/** @brief Applies fixed-level threshold to grayscale image. - - This is a basic operation applied before retrieving contours -@see cv::threshold -*/ -CVAPI(double) cvThreshold( const CvArr* src, CvArr* dst, - double threshold, double max_value, - int threshold_type ); - -/** @brief Applies adaptive threshold to grayscale image. - - The two parameters for methods CV_ADAPTIVE_THRESH_MEAN_C and - CV_ADAPTIVE_THRESH_GAUSSIAN_C are: - neighborhood size (3, 5, 7 etc.), - and a constant subtracted from mean (...,-3,-2,-1,0,1,2,3,...) -@see cv::adaptiveThreshold -*/ -CVAPI(void) cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value, - int adaptive_method CV_DEFAULT(CV_ADAPTIVE_THRESH_MEAN_C), - int threshold_type CV_DEFAULT(CV_THRESH_BINARY), - int block_size CV_DEFAULT(3), - double param1 CV_DEFAULT(5)); - -/** @brief Fills the connected component until the color difference gets large enough -@see cv::floodFill -*/ -CVAPI(void) cvFloodFill( CvArr* image, CvPoint seed_point, - CvScalar new_val, CvScalar lo_diff CV_DEFAULT(cvScalarAll(0)), - CvScalar up_diff CV_DEFAULT(cvScalarAll(0)), - CvConnectedComp* comp CV_DEFAULT(NULL), - int flags CV_DEFAULT(4), - CvArr* mask CV_DEFAULT(NULL)); - -/****************************************************************************************\ -* Feature detection * -\****************************************************************************************/ - -/** @brief Runs canny edge detector -@see cv::Canny -*/ -CVAPI(void) cvCanny( const CvArr* image, CvArr* edges, double threshold1, - double threshold2, int aperture_size CV_DEFAULT(3) ); - -/** @brief Calculates constraint image for corner detection - - Dx^2 * Dyy + Dxx * Dy^2 - 2 * Dx * Dy * Dxy. - Applying threshold to the result gives coordinates of corners -@see cv::preCornerDetect -*/ -CVAPI(void) cvPreCornerDetect( const CvArr* image, CvArr* corners, - int aperture_size CV_DEFAULT(3) ); - -/** @brief Calculates eigen values and vectors of 2x2 - gradient covariation matrix at every image pixel -@see cv::cornerEigenValsAndVecs -*/ -CVAPI(void) cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, - int block_size, int aperture_size CV_DEFAULT(3) ); - -/** @brief Calculates minimal eigenvalue for 2x2 gradient covariation matrix at - every image pixel -@see cv::cornerMinEigenVal -*/ -CVAPI(void) cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, - int block_size, int aperture_size CV_DEFAULT(3) ); - -/** @brief Harris corner detector: - - Calculates det(M) - k*(trace(M)^2), where M is 2x2 gradient covariation matrix for each pixel -@see cv::cornerHarris -*/ -CVAPI(void) cvCornerHarris( const CvArr* image, CvArr* harris_response, - int block_size, int aperture_size CV_DEFAULT(3), - double k CV_DEFAULT(0.04) ); - -/** @brief Adjust corner position using some sort of gradient search -@see cv::cornerSubPix -*/ -CVAPI(void) cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, - int count, CvSize win, CvSize zero_zone, - CvTermCriteria criteria ); - -/** @brief Finds a sparse set of points within the selected region - that seem to be easy to track -@see cv::goodFeaturesToTrack -*/ -CVAPI(void) cvGoodFeaturesToTrack( const CvArr* image, CvArr* eig_image, - CvArr* temp_image, CvPoint2D32f* corners, - int* corner_count, double quality_level, - double min_distance, - const CvArr* mask CV_DEFAULT(NULL), - int block_size CV_DEFAULT(3), - int use_harris CV_DEFAULT(0), - double k CV_DEFAULT(0.04) ); - -/** @brief Finds lines on binary image using one of several methods. - - line_storage is either memory storage or 1 x _max number of lines_ CvMat, its - number of columns is changed by the function. - method is one of CV_HOUGH_*; - rho, theta and threshold are used for each of those methods; - param1 ~ line length, param2 ~ line gap - for probabilistic, - param1 ~ srn, param2 ~ stn - for multi-scale -@see cv::HoughLines -*/ -CVAPI(CvSeq*) cvHoughLines2( CvArr* image, void* line_storage, int method, - double rho, double theta, int threshold, - double param1 CV_DEFAULT(0), double param2 CV_DEFAULT(0), - double min_theta CV_DEFAULT(0), double max_theta CV_DEFAULT(CV_PI)); - -/** @brief Finds circles in the image -@see cv::HoughCircles -*/ -CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage, - int method, double dp, double min_dist, - double param1 CV_DEFAULT(100), - double param2 CV_DEFAULT(100), - int min_radius CV_DEFAULT(0), - int max_radius CV_DEFAULT(0)); - -/** @brief Fits a line into set of 2d or 3d points in a robust way (M-estimator technique) -@see cv::fitLine -*/ -CVAPI(void) cvFitLine( const CvArr* points, int dist_type, double param, - double reps, double aeps, float* line ); - -/****************************************************************************************\ -* Drawing * -\****************************************************************************************/ - -/****************************************************************************************\ -* Drawing functions work with images/matrices of arbitrary type. * -* For color images the channel order is BGR[A] * -* Antialiasing is supported only for 8-bit image now. * -* All the functions include parameter color that means rgb value (that may be * -* constructed with CV_RGB macro) for color images and brightness * -* for grayscale images. * -* If a drawn figure is partially or completely outside of the image, it is clipped.* -\****************************************************************************************/ - -#define CV_FILLED -1 - -#define CV_AA 16 - -/** @brief Draws 4-connected, 8-connected or antialiased line segment connecting two points -@see cv::line -*/ -CVAPI(void) cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -/** @brief Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2) - - if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn -@see cv::rectangle -*/ -CVAPI(void) cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - int shift CV_DEFAULT(0)); - -/** @brief Draws a rectangle specified by a CvRect structure -@see cv::rectangle -*/ -CVAPI(void) cvRectangleR( CvArr* img, CvRect r, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - int shift CV_DEFAULT(0)); - - -/** @brief Draws a circle with specified center and radius. - - Thickness works in the same way as with cvRectangle -@see cv::circle -*/ -CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -/** @brief Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector - - depending on _thickness_, _start_angle_ and _end_angle_ parameters. The resultant figure - is rotated by _angle_. All the angles are in degrees -@see cv::ellipse -*/ -CVAPI(void) cvEllipse( CvArr* img, CvPoint center, CvSize axes, - double angle, double start_angle, double end_angle, - CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -CV_INLINE void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ) -{ - CvSize axes = cvSize( - cvRound(box.size.width*0.5), - cvRound(box.size.height*0.5) - ); - - cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle, - 0, 360, color, thickness, line_type, shift ); -} - -/** @brief Fills convex or monotonous polygon. -@see cv::fillConvexPoly -*/ -CVAPI(void) cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); - -/** @brief Fills an area bounded by one or more arbitrary polygons -@see cv::fillPoly -*/ -CVAPI(void) cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, - int contours, CvScalar color, - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -/** @brief Draws one or more polygonal curves -@see cv::polylines -*/ -CVAPI(void) cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, - int is_closed, CvScalar color, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); - -#define cvDrawRect cvRectangle -#define cvDrawLine cvLine -#define cvDrawCircle cvCircle -#define cvDrawEllipse cvEllipse -#define cvDrawPolyLine cvPolyLine - -/** @brief Clips the line segment connecting *pt1 and *pt2 - by the rectangular window - - (0<=xptr will point to pt1 (or pt2, see left_to_right description) location in -the image. Returns the number of pixels on the line between the ending points. -@see cv::LineIterator -*/ -CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, - CvLineIterator* line_iterator, - int connectivity CV_DEFAULT(8), - int left_to_right CV_DEFAULT(0)); - -#define CV_NEXT_LINE_POINT( line_iterator ) \ -{ \ - int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ - (line_iterator).err += (line_iterator).minus_delta + \ - ((line_iterator).plus_delta & _line_iterator_mask); \ - (line_iterator).ptr += (line_iterator).minus_step + \ - ((line_iterator).plus_step & _line_iterator_mask); \ -} - - -#define CV_FONT_HERSHEY_SIMPLEX 0 -#define CV_FONT_HERSHEY_PLAIN 1 -#define CV_FONT_HERSHEY_DUPLEX 2 -#define CV_FONT_HERSHEY_COMPLEX 3 -#define CV_FONT_HERSHEY_TRIPLEX 4 -#define CV_FONT_HERSHEY_COMPLEX_SMALL 5 -#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 -#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 - -#define CV_FONT_ITALIC 16 - -#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX - - -/** Font structure */ -typedef struct CvFont -{ - const char* nameFont; //Qt:nameFont - CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red_component[, alpha_component]) - int font_face; //Qt: bool italic /** =CV_FONT_* */ - const int* ascii; //!< font data and metrics - const int* greek; - const int* cyrillic; - float hscale, vscale; - float shear; //!< slope coefficient: 0 - normal, >0 - italic - int thickness; //!< Qt: weight /** letters thickness */ - float dx; //!< horizontal interval between letters - int line_type; //!< Qt: PointSize -} -CvFont; - -/** @brief Initializes font structure (OpenCV 1.x API). - -The function initializes the font structure that can be passed to text rendering functions. - -@param font Pointer to the font structure initialized by the function -@param font_face Font name identifier. See cv::HersheyFonts and corresponding old CV_* identifiers. -@param hscale Horizontal scale. If equal to 1.0f , the characters have the original width -depending on the font type. If equal to 0.5f , the characters are of half the original width. -@param vscale Vertical scale. If equal to 1.0f , the characters have the original height depending -on the font type. If equal to 0.5f , the characters are of half the original height. -@param shear Approximate tangent of the character slope relative to the vertical line. A zero -value means a non-italic font, 1.0f means about a 45 degree slope, etc. -@param thickness Thickness of the text strokes -@param line_type Type of the strokes, see line description - -@sa cvPutText - */ -CVAPI(void) cvInitFont( CvFont* font, int font_face, - double hscale, double vscale, - double shear CV_DEFAULT(0), - int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8)); - -CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) -{ - CvFont font; - cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); - return font; -} - -/** @brief Renders text stroke with specified font and color at specified location. - CvFont should be initialized with cvInitFont -@see cvInitFont, cvGetTextSize, cvFont, cv::putText -*/ -CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, - const CvFont* font, CvScalar color ); - -/** @brief Calculates bounding box of text stroke (useful for alignment) -@see cv::getTextSize -*/ -CVAPI(void) cvGetTextSize( const char* text_string, const CvFont* font, - CvSize* text_size, int* baseline ); - -/** @brief Unpacks color value - -if arrtype is CV_8UC?, _color_ is treated as packed color value, otherwise the first channels -(depending on arrtype) of destination scalar are set to the same value = _color_ -*/ -CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); - -/** @brief Returns the polygon points which make up the given ellipse. - -The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial -sweep of the ellipse arc can be done by specifying arc_start and arc_end to be something other than -0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total -number of points stored into 'pts' is returned by this function. -@see cv::ellipse2Poly -*/ -CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, - int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); - -/** @brief Draws contour outlines or filled interiors on the image -@see cv::drawContours -*/ -CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, - CvScalar external_color, CvScalar hole_color, - int max_level, int thickness CV_DEFAULT(1), - int line_type CV_DEFAULT(8), - CvPoint offset CV_DEFAULT(cvPoint(0,0))); - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_IMGPROC_IMGPROC_C_H +#define OPENCV_IMGPROC_IMGPROC_C_H + +#include "opencv2/imgproc/types_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup imgproc_c +@{ +*/ + +/*********************** Background statistics accumulation *****************************/ + +/** @brief Adds image to accumulator +@see cv::accumulate +*/ +CVAPI(void) cvAcc( const CvArr* image, CvArr* sum, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Adds squared image to accumulator +@see cv::accumulateSquare +*/ +CVAPI(void) cvSquareAcc( const CvArr* image, CvArr* sqsum, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Adds a product of two images to accumulator +@see cv::accumulateProduct +*/ +CVAPI(void) cvMultiplyAcc( const CvArr* image1, const CvArr* image2, CvArr* acc, + const CvArr* mask CV_DEFAULT(NULL) ); + +/** @brief Adds image to accumulator with weights: acc = acc*(1-alpha) + image*alpha +@see cv::accumulateWeighted +*/ +CVAPI(void) cvRunningAvg( const CvArr* image, CvArr* acc, double alpha, + const CvArr* mask CV_DEFAULT(NULL) ); + +/****************************************************************************************\ +* Image Processing * +\****************************************************************************************/ + +/** Copies source 2D array inside of the larger destination array and + makes a border of the specified type (IPL_BORDER_*) around the copied area. */ +CVAPI(void) cvCopyMakeBorder( const CvArr* src, CvArr* dst, CvPoint offset, + int bordertype, CvScalar value CV_DEFAULT(cvScalarAll(0))); + +/** @brief Smooths the image in one of several ways. + +@param src The source image +@param dst The destination image +@param smoothtype Type of the smoothing, see SmoothMethod_c +@param size1 The first parameter of the smoothing operation, the aperture width. Must be a +positive odd number (1, 3, 5, ...) +@param size2 The second parameter of the smoothing operation, the aperture height. Ignored by +CV_MEDIAN and CV_BILATERAL methods. In the case of simple scaled/non-scaled and Gaussian blur if +size2 is zero, it is set to size1. Otherwise it must be a positive odd number. +@param sigma1 In the case of a Gaussian parameter this parameter may specify Gaussian \f$\sigma\f$ +(standard deviation). If it is zero, it is calculated from the kernel size: +\f[\sigma = 0.3 (n/2 - 1) + 0.8 \quad \text{where} \quad n= \begin{array}{l l} \mbox{\texttt{size1} for horizontal kernel} \\ \mbox{\texttt{size2} for vertical kernel} \end{array}\f] +Using standard sigma for small kernels ( \f$3\times 3\f$ to \f$7\times 7\f$ ) gives better speed. If +sigma1 is not zero, while size1 and size2 are zeros, the kernel size is calculated from the +sigma (to provide accurate enough operation). +@param sigma2 additional parameter for bilateral filtering + +@see cv::GaussianBlur, cv::blur, cv::medianBlur, cv::bilateralFilter. + */ +CVAPI(void) cvSmooth( const CvArr* src, CvArr* dst, + int smoothtype CV_DEFAULT(CV_GAUSSIAN), + int size1 CV_DEFAULT(3), + int size2 CV_DEFAULT(0), + double sigma1 CV_DEFAULT(0), + double sigma2 CV_DEFAULT(0)); + +/** @brief Convolves an image with the kernel. + +@param src input image. +@param dst output image of the same size and the same number of channels as src. +@param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point +matrix; if you want to apply different kernels to different channels, split the image into +separate color planes using split and process them individually. +@param anchor anchor of the kernel that indicates the relative position of a filtered point within +the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor +is at the kernel center. + +@see cv::filter2D + */ +CVAPI(void) cvFilter2D( const CvArr* src, CvArr* dst, const CvMat* kernel, + CvPoint anchor CV_DEFAULT(cvPoint(-1,-1))); + +/** @brief Finds integral image: SUM(X,Y) = sum(x \texttt{hist1}(I)\)}{\frac{\texttt{hist2}(I) \cdot \texttt{scale}}{\texttt{hist1}(I)}}{if \(\texttt{hist1}(I) \ne 0\) and \(\texttt{hist2}(I) \le \texttt{hist1}(I)\)}\f] + +@param hist1 First histogram (the divisor). +@param hist2 Second histogram. +@param dst_hist Destination histogram. +@param scale Scale factor for the destination histogram. + */ +CVAPI(void) cvCalcProbDensity( const CvHistogram* hist1, const CvHistogram* hist2, + CvHistogram* dst_hist, double scale CV_DEFAULT(255) ); + +/** @brief equalizes histogram of 8-bit single-channel image +@see cv::equalizeHist +*/ +CVAPI(void) cvEqualizeHist( const CvArr* src, CvArr* dst ); + + +/** @brief Applies distance transform to binary image +@see cv::distanceTransform +*/ +CVAPI(void) cvDistTransform( const CvArr* src, CvArr* dst, + int distance_type CV_DEFAULT(CV_DIST_L2), + int mask_size CV_DEFAULT(3), + const float* mask CV_DEFAULT(NULL), + CvArr* labels CV_DEFAULT(NULL), + int labelType CV_DEFAULT(CV_DIST_LABEL_CCOMP)); + + +/** @brief Applies fixed-level threshold to grayscale image. + + This is a basic operation applied before retrieving contours +@see cv::threshold +*/ +CVAPI(double) cvThreshold( const CvArr* src, CvArr* dst, + double threshold, double max_value, + int threshold_type ); + +/** @brief Applies adaptive threshold to grayscale image. + + The two parameters for methods CV_ADAPTIVE_THRESH_MEAN_C and + CV_ADAPTIVE_THRESH_GAUSSIAN_C are: + neighborhood size (3, 5, 7 etc.), + and a constant subtracted from mean (...,-3,-2,-1,0,1,2,3,...) +@see cv::adaptiveThreshold +*/ +CVAPI(void) cvAdaptiveThreshold( const CvArr* src, CvArr* dst, double max_value, + int adaptive_method CV_DEFAULT(CV_ADAPTIVE_THRESH_MEAN_C), + int threshold_type CV_DEFAULT(CV_THRESH_BINARY), + int block_size CV_DEFAULT(3), + double param1 CV_DEFAULT(5)); + +/** @brief Fills the connected component until the color difference gets large enough +@see cv::floodFill +*/ +CVAPI(void) cvFloodFill( CvArr* image, CvPoint seed_point, + CvScalar new_val, CvScalar lo_diff CV_DEFAULT(cvScalarAll(0)), + CvScalar up_diff CV_DEFAULT(cvScalarAll(0)), + CvConnectedComp* comp CV_DEFAULT(NULL), + int flags CV_DEFAULT(4), + CvArr* mask CV_DEFAULT(NULL)); + +/****************************************************************************************\ +* Feature detection * +\****************************************************************************************/ + +/** @brief Runs canny edge detector +@see cv::Canny +*/ +CVAPI(void) cvCanny( const CvArr* image, CvArr* edges, double threshold1, + double threshold2, int aperture_size CV_DEFAULT(3) ); + +/** @brief Calculates constraint image for corner detection + + Dx^2 * Dyy + Dxx * Dy^2 - 2 * Dx * Dy * Dxy. + Applying threshold to the result gives coordinates of corners +@see cv::preCornerDetect +*/ +CVAPI(void) cvPreCornerDetect( const CvArr* image, CvArr* corners, + int aperture_size CV_DEFAULT(3) ); + +/** @brief Calculates eigen values and vectors of 2x2 + gradient covariation matrix at every image pixel +@see cv::cornerEigenValsAndVecs +*/ +CVAPI(void) cvCornerEigenValsAndVecs( const CvArr* image, CvArr* eigenvv, + int block_size, int aperture_size CV_DEFAULT(3) ); + +/** @brief Calculates minimal eigenvalue for 2x2 gradient covariation matrix at + every image pixel +@see cv::cornerMinEigenVal +*/ +CVAPI(void) cvCornerMinEigenVal( const CvArr* image, CvArr* eigenval, + int block_size, int aperture_size CV_DEFAULT(3) ); + +/** @brief Harris corner detector: + + Calculates det(M) - k*(trace(M)^2), where M is 2x2 gradient covariation matrix for each pixel +@see cv::cornerHarris +*/ +CVAPI(void) cvCornerHarris( const CvArr* image, CvArr* harris_response, + int block_size, int aperture_size CV_DEFAULT(3), + double k CV_DEFAULT(0.04) ); + +/** @brief Adjust corner position using some sort of gradient search +@see cv::cornerSubPix +*/ +CVAPI(void) cvFindCornerSubPix( const CvArr* image, CvPoint2D32f* corners, + int count, CvSize win, CvSize zero_zone, + CvTermCriteria criteria ); + +/** @brief Finds a sparse set of points within the selected region + that seem to be easy to track +@see cv::goodFeaturesToTrack +*/ +CVAPI(void) cvGoodFeaturesToTrack( const CvArr* image, CvArr* eig_image, + CvArr* temp_image, CvPoint2D32f* corners, + int* corner_count, double quality_level, + double min_distance, + const CvArr* mask CV_DEFAULT(NULL), + int block_size CV_DEFAULT(3), + int use_harris CV_DEFAULT(0), + double k CV_DEFAULT(0.04) ); + +/** @brief Finds lines on binary image using one of several methods. + + line_storage is either memory storage or 1 x _max number of lines_ CvMat, its + number of columns is changed by the function. + method is one of CV_HOUGH_*; + rho, theta and threshold are used for each of those methods; + param1 ~ line length, param2 ~ line gap - for probabilistic, + param1 ~ srn, param2 ~ stn - for multi-scale +@see cv::HoughLines +*/ +CVAPI(CvSeq*) cvHoughLines2( CvArr* image, void* line_storage, int method, + double rho, double theta, int threshold, + double param1 CV_DEFAULT(0), double param2 CV_DEFAULT(0), + double min_theta CV_DEFAULT(0), double max_theta CV_DEFAULT(CV_PI)); + +/** @brief Finds circles in the image +@see cv::HoughCircles +*/ +CVAPI(CvSeq*) cvHoughCircles( CvArr* image, void* circle_storage, + int method, double dp, double min_dist, + double param1 CV_DEFAULT(100), + double param2 CV_DEFAULT(100), + int min_radius CV_DEFAULT(0), + int max_radius CV_DEFAULT(0)); + +/** @brief Fits a line into set of 2d or 3d points in a robust way (M-estimator technique) +@see cv::fitLine +*/ +CVAPI(void) cvFitLine( const CvArr* points, int dist_type, double param, + double reps, double aeps, float* line ); + +/****************************************************************************************\ +* Drawing * +\****************************************************************************************/ + +/****************************************************************************************\ +* Drawing functions work with images/matrices of arbitrary type. * +* For color images the channel order is BGR[A] * +* Antialiasing is supported only for 8-bit image now. * +* All the functions include parameter color that means rgb value (that may be * +* constructed with CV_RGB macro) for color images and brightness * +* for grayscale images. * +* If a drawn figure is partially or completely outside of the image, it is clipped.* +\****************************************************************************************/ + +#define CV_FILLED -1 + +#define CV_AA 16 + +/** @brief Draws 4-connected, 8-connected or antialiased line segment connecting two points +@see cv::line +*/ +CVAPI(void) cvLine( CvArr* img, CvPoint pt1, CvPoint pt2, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); + +/** @brief Draws a rectangle given two opposite corners of the rectangle (pt1 & pt2) + + if thickness<0 (e.g. thickness == CV_FILLED), the filled box is drawn +@see cv::rectangle +*/ +CVAPI(void) cvRectangle( CvArr* img, CvPoint pt1, CvPoint pt2, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), + int shift CV_DEFAULT(0)); + +/** @brief Draws a rectangle specified by a CvRect structure +@see cv::rectangle +*/ +CVAPI(void) cvRectangleR( CvArr* img, CvRect r, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), + int shift CV_DEFAULT(0)); + + +/** @brief Draws a circle with specified center and radius. + + Thickness works in the same way as with cvRectangle +@see cv::circle +*/ +CVAPI(void) cvCircle( CvArr* img, CvPoint center, int radius, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); + +/** @brief Draws ellipse outline, filled ellipse, elliptic arc or filled elliptic sector + + depending on _thickness_, _start_angle_ and _end_angle_ parameters. The resultant figure + is rotated by _angle_. All the angles are in degrees +@see cv::ellipse +*/ +CVAPI(void) cvEllipse( CvArr* img, CvPoint center, CvSize axes, + double angle, double start_angle, double end_angle, + CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); + +CV_INLINE void cvEllipseBox( CvArr* img, CvBox2D box, CvScalar color, + int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ) +{ + CvSize axes = cvSize( + cvRound(box.size.width*0.5), + cvRound(box.size.height*0.5) + ); + + cvEllipse( img, cvPointFrom32f( box.center ), axes, box.angle, + 0, 360, color, thickness, line_type, shift ); +} + +/** @brief Fills convex or monotonous polygon. +@see cv::fillConvexPoly +*/ +CVAPI(void) cvFillConvexPoly( CvArr* img, const CvPoint* pts, int npts, CvScalar color, + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0)); + +/** @brief Fills an area bounded by one or more arbitrary polygons +@see cv::fillPoly +*/ +CVAPI(void) cvFillPoly( CvArr* img, CvPoint** pts, const int* npts, + int contours, CvScalar color, + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); + +/** @brief Draws one or more polygonal curves +@see cv::polylines +*/ +CVAPI(void) cvPolyLine( CvArr* img, CvPoint** pts, const int* npts, int contours, + int is_closed, CvScalar color, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), int shift CV_DEFAULT(0) ); + +#define cvDrawRect cvRectangle +#define cvDrawLine cvLine +#define cvDrawCircle cvCircle +#define cvDrawEllipse cvEllipse +#define cvDrawPolyLine cvPolyLine + +/** @brief Clips the line segment connecting *pt1 and *pt2 + by the rectangular window + + (0<=xptr will point to pt1 (or pt2, see left_to_right description) location in +the image. Returns the number of pixels on the line between the ending points. +@see cv::LineIterator +*/ +CVAPI(int) cvInitLineIterator( const CvArr* image, CvPoint pt1, CvPoint pt2, + CvLineIterator* line_iterator, + int connectivity CV_DEFAULT(8), + int left_to_right CV_DEFAULT(0)); + +#define CV_NEXT_LINE_POINT( line_iterator ) \ +{ \ + int _line_iterator_mask = (line_iterator).err < 0 ? -1 : 0; \ + (line_iterator).err += (line_iterator).minus_delta + \ + ((line_iterator).plus_delta & _line_iterator_mask); \ + (line_iterator).ptr += (line_iterator).minus_step + \ + ((line_iterator).plus_step & _line_iterator_mask); \ +} + + +#define CV_FONT_HERSHEY_SIMPLEX 0 +#define CV_FONT_HERSHEY_PLAIN 1 +#define CV_FONT_HERSHEY_DUPLEX 2 +#define CV_FONT_HERSHEY_COMPLEX 3 +#define CV_FONT_HERSHEY_TRIPLEX 4 +#define CV_FONT_HERSHEY_COMPLEX_SMALL 5 +#define CV_FONT_HERSHEY_SCRIPT_SIMPLEX 6 +#define CV_FONT_HERSHEY_SCRIPT_COMPLEX 7 + +#define CV_FONT_ITALIC 16 + +#define CV_FONT_VECTOR0 CV_FONT_HERSHEY_SIMPLEX + + +/** Font structure */ +typedef struct CvFont +{ + const char* nameFont; //Qt:nameFont + CvScalar color; //Qt:ColorFont -> cvScalar(blue_component, green_component, red_component[, alpha_component]) + int font_face; //Qt: bool italic /** =CV_FONT_* */ + const int* ascii; //!< font data and metrics + const int* greek; + const int* cyrillic; + float hscale, vscale; + float shear; //!< slope coefficient: 0 - normal, >0 - italic + int thickness; //!< Qt: weight /** letters thickness */ + float dx; //!< horizontal interval between letters + int line_type; //!< Qt: PointSize +} +CvFont; + +/** @brief Initializes font structure (OpenCV 1.x API). + +The function initializes the font structure that can be passed to text rendering functions. + +@param font Pointer to the font structure initialized by the function +@param font_face Font name identifier. See cv::HersheyFonts and corresponding old CV_* identifiers. +@param hscale Horizontal scale. If equal to 1.0f , the characters have the original width +depending on the font type. If equal to 0.5f , the characters are of half the original width. +@param vscale Vertical scale. If equal to 1.0f , the characters have the original height depending +on the font type. If equal to 0.5f , the characters are of half the original height. +@param shear Approximate tangent of the character slope relative to the vertical line. A zero +value means a non-italic font, 1.0f means about a 45 degree slope, etc. +@param thickness Thickness of the text strokes +@param line_type Type of the strokes, see line description + +@sa cvPutText + */ +CVAPI(void) cvInitFont( CvFont* font, int font_face, + double hscale, double vscale, + double shear CV_DEFAULT(0), + int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8)); + +CV_INLINE CvFont cvFont( double scale, int thickness CV_DEFAULT(1) ) +{ + CvFont font; + cvInitFont( &font, CV_FONT_HERSHEY_PLAIN, scale, scale, 0, thickness, CV_AA ); + return font; +} + +/** @brief Renders text stroke with specified font and color at specified location. + CvFont should be initialized with cvInitFont +@see cvInitFont, cvGetTextSize, cvFont, cv::putText +*/ +CVAPI(void) cvPutText( CvArr* img, const char* text, CvPoint org, + const CvFont* font, CvScalar color ); + +/** @brief Calculates bounding box of text stroke (useful for alignment) +@see cv::getTextSize +*/ +CVAPI(void) cvGetTextSize( const char* text_string, const CvFont* font, + CvSize* text_size, int* baseline ); + +/** @brief Unpacks color value + +if arrtype is CV_8UC?, _color_ is treated as packed color value, otherwise the first channels +(depending on arrtype) of destination scalar are set to the same value = _color_ +*/ +CVAPI(CvScalar) cvColorToScalar( double packed_color, int arrtype ); + +/** @brief Returns the polygon points which make up the given ellipse. + +The ellipse is define by the box of size 'axes' rotated 'angle' around the 'center'. A partial +sweep of the ellipse arc can be done by specifying arc_start and arc_end to be something other than +0 and 360, respectively. The input array 'pts' must be large enough to hold the result. The total +number of points stored into 'pts' is returned by this function. +@see cv::ellipse2Poly +*/ +CVAPI(int) cvEllipse2Poly( CvPoint center, CvSize axes, + int angle, int arc_start, int arc_end, CvPoint * pts, int delta ); + +/** @brief Draws contour outlines or filled interiors on the image +@see cv::drawContours +*/ +CVAPI(void) cvDrawContours( CvArr *img, CvSeq* contour, + CvScalar external_color, CvScalar hole_color, + int max_level, int thickness CV_DEFAULT(1), + int line_type CV_DEFAULT(8), + CvPoint offset CV_DEFAULT(cvPoint(0,0))); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp b/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp index 916b0e3bbc..b2df4fcaca 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/segmentation.hpp @@ -1,141 +1,141 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_IMGPROC_SEGMENTATION_HPP -#define OPENCV_IMGPROC_SEGMENTATION_HPP - -#include "opencv2/imgproc.hpp" - -namespace cv { - -namespace segmentation { - -//! @addtogroup imgproc_segmentation -//! @{ - - -/** @brief Intelligent Scissors image segmentation - * - * This class is used to find the path (contour) between two points - * which can be used for image segmentation. - * - * Usage example: - * @snippet snippets/imgproc_segmentation.cpp usage_example_intelligent_scissors - * - * Reference: "Intelligent Scissors for Image Composition" - * algorithm designed by Eric N. Mortensen and William A. Barrett, Brigham Young University - * @cite Mortensen95intelligentscissors - */ -class CV_EXPORTS_W_SIMPLE IntelligentScissorsMB -{ -public: - CV_WRAP - IntelligentScissorsMB(); - - /** @brief Specify weights of feature functions - * - * Consider keeping weights normalized (sum of weights equals to 1.0) - * Discrete dynamic programming (DP) goal is minimization of costs between pixels. - * - * @param weight_non_edge Specify cost of non-edge pixels (default: 0.43f) - * @param weight_gradient_direction Specify cost of gradient direction function (default: 0.43f) - * @param weight_gradient_magnitude Specify cost of gradient magnitude function (default: 0.14f) - */ - CV_WRAP - IntelligentScissorsMB& setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude); - - /** @brief Specify gradient magnitude max value threshold - * - * Zero limit value is used to disable gradient magnitude thresholding (default behavior, as described in original article). - * Otherwize pixels with `gradient magnitude >= threshold` have zero cost. - * - * @note Thresholding should be used for images with irregular regions (to avoid stuck on parameters from high-contract areas, like embedded logos). - * - * @param gradient_magnitude_threshold_max Specify gradient magnitude max value threshold (default: 0, disabled) - */ - CV_WRAP - IntelligentScissorsMB& setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f); - - /** @brief Switch to "Laplacian Zero-Crossing" edge feature extractor and specify its parameters - * - * This feature extractor is used by default according to article. - * - * Implementation has additional filtering for regions with low-amplitude noise. - * This filtering is enabled through parameter of minimal gradient amplitude (use some small value 4, 8, 16). - * - * @note Current implementation of this feature extractor is based on processing of grayscale images (color image is converted to grayscale image first). - * - * @note Canny edge detector is a bit slower, but provides better results (especially on color images): use setEdgeFeatureCannyParameters(). - * - * @param gradient_magnitude_min_value Minimal gradient magnitude value for edge pixels (default: 0, check is disabled) - */ - CV_WRAP - IntelligentScissorsMB& setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f); - - /** @brief Switch edge feature extractor to use Canny edge detector - * - * @note "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) - * - * @sa Canny - */ - CV_WRAP - IntelligentScissorsMB& setEdgeFeatureCannyParameters( - double threshold1, double threshold2, - int apertureSize = 3, bool L2gradient = false - ); - - /** @brief Specify input image and extract image features - * - * @param image input image. Type is #CV_8UC1 / #CV_8UC3 - */ - CV_WRAP - IntelligentScissorsMB& applyImage(InputArray image); - - /** @brief Specify custom features of input image - * - * Customized advanced variant of applyImage() call. - * - * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are `{0, 1}`. - * @param gradient_direction Specify gradient direction feature. Type is CV_32FC2. Values are expected to be normalized: `x^2 + y^2 == 1` - * @param gradient_magnitude Specify cost of gradient magnitude function: Type is CV_32FC1. Values should be in range `[0, 1]`. - * @param image **Optional parameter**. Must be specified if subset of features is specified (non-specified features are calculated internally) - */ - CV_WRAP - IntelligentScissorsMB& applyImageFeatures( - InputArray non_edge, InputArray gradient_direction, InputArray gradient_magnitude, - InputArray image = noArray() - ); - - /** @brief Prepares a map of optimal paths for the given source point on the image - * - * @note applyImage() / applyImageFeatures() must be called before this call - * - * @param sourcePt The source point used to find the paths - */ - CV_WRAP void buildMap(const Point& sourcePt); - - /** @brief Extracts optimal contour for the given target point on the image - * - * @note buildMap() must be called before this call - * - * @param targetPt The target point - * @param[out] contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with `std::vector`) - * @param backward Flag to indicate reverse order of retrieved pixels (use "true" value to fetch points from the target to the source point) - */ - CV_WRAP void getContour(const Point& targetPt, OutputArray contour, bool backward = false) const; - -#ifndef CV_DOXYGEN - struct Impl; - inline Impl* getImpl() const { return impl.get(); } -protected: - std::shared_ptr impl; -#endif -}; - -//! @} - -} // namespace segmentation -} // namespace cv - -#endif // OPENCV_IMGPROC_SEGMENTATION_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_IMGPROC_SEGMENTATION_HPP +#define OPENCV_IMGPROC_SEGMENTATION_HPP + +#include "opencv2/imgproc.hpp" + +namespace cv { + +namespace segmentation { + +//! @addtogroup imgproc_segmentation +//! @{ + + +/** @brief Intelligent Scissors image segmentation + * + * This class is used to find the path (contour) between two points + * which can be used for image segmentation. + * + * Usage example: + * @snippet snippets/imgproc_segmentation.cpp usage_example_intelligent_scissors + * + * Reference: "Intelligent Scissors for Image Composition" + * algorithm designed by Eric N. Mortensen and William A. Barrett, Brigham Young University + * @cite Mortensen95intelligentscissors + */ +class CV_EXPORTS_W_SIMPLE IntelligentScissorsMB +{ +public: + CV_WRAP + IntelligentScissorsMB(); + + /** @brief Specify weights of feature functions + * + * Consider keeping weights normalized (sum of weights equals to 1.0) + * Discrete dynamic programming (DP) goal is minimization of costs between pixels. + * + * @param weight_non_edge Specify cost of non-edge pixels (default: 0.43f) + * @param weight_gradient_direction Specify cost of gradient direction function (default: 0.43f) + * @param weight_gradient_magnitude Specify cost of gradient magnitude function (default: 0.14f) + */ + CV_WRAP + IntelligentScissorsMB& setWeights(float weight_non_edge, float weight_gradient_direction, float weight_gradient_magnitude); + + /** @brief Specify gradient magnitude max value threshold + * + * Zero limit value is used to disable gradient magnitude thresholding (default behavior, as described in original article). + * Otherwize pixels with `gradient magnitude >= threshold` have zero cost. + * + * @note Thresholding should be used for images with irregular regions (to avoid stuck on parameters from high-contract areas, like embedded logos). + * + * @param gradient_magnitude_threshold_max Specify gradient magnitude max value threshold (default: 0, disabled) + */ + CV_WRAP + IntelligentScissorsMB& setGradientMagnitudeMaxLimit(float gradient_magnitude_threshold_max = 0.0f); + + /** @brief Switch to "Laplacian Zero-Crossing" edge feature extractor and specify its parameters + * + * This feature extractor is used by default according to article. + * + * Implementation has additional filtering for regions with low-amplitude noise. + * This filtering is enabled through parameter of minimal gradient amplitude (use some small value 4, 8, 16). + * + * @note Current implementation of this feature extractor is based on processing of grayscale images (color image is converted to grayscale image first). + * + * @note Canny edge detector is a bit slower, but provides better results (especially on color images): use setEdgeFeatureCannyParameters(). + * + * @param gradient_magnitude_min_value Minimal gradient magnitude value for edge pixels (default: 0, check is disabled) + */ + CV_WRAP + IntelligentScissorsMB& setEdgeFeatureZeroCrossingParameters(float gradient_magnitude_min_value = 0.0f); + + /** @brief Switch edge feature extractor to use Canny edge detector + * + * @note "Laplacian Zero-Crossing" feature extractor is used by default (following to original article) + * + * @sa Canny + */ + CV_WRAP + IntelligentScissorsMB& setEdgeFeatureCannyParameters( + double threshold1, double threshold2, + int apertureSize = 3, bool L2gradient = false + ); + + /** @brief Specify input image and extract image features + * + * @param image input image. Type is #CV_8UC1 / #CV_8UC3 + */ + CV_WRAP + IntelligentScissorsMB& applyImage(InputArray image); + + /** @brief Specify custom features of input image + * + * Customized advanced variant of applyImage() call. + * + * @param non_edge Specify cost of non-edge pixels. Type is CV_8UC1. Expected values are `{0, 1}`. + * @param gradient_direction Specify gradient direction feature. Type is CV_32FC2. Values are expected to be normalized: `x^2 + y^2 == 1` + * @param gradient_magnitude Specify cost of gradient magnitude function: Type is CV_32FC1. Values should be in range `[0, 1]`. + * @param image **Optional parameter**. Must be specified if subset of features is specified (non-specified features are calculated internally) + */ + CV_WRAP + IntelligentScissorsMB& applyImageFeatures( + InputArray non_edge, InputArray gradient_direction, InputArray gradient_magnitude, + InputArray image = noArray() + ); + + /** @brief Prepares a map of optimal paths for the given source point on the image + * + * @note applyImage() / applyImageFeatures() must be called before this call + * + * @param sourcePt The source point used to find the paths + */ + CV_WRAP void buildMap(const Point& sourcePt); + + /** @brief Extracts optimal contour for the given target point on the image + * + * @note buildMap() must be called before this call + * + * @param targetPt The target point + * @param[out] contour The list of pixels which contains optimal path between the source and the target points of the image. Type is CV_32SC2 (compatible with `std::vector`) + * @param backward Flag to indicate reverse order of retrieved pixels (use "true" value to fetch points from the target to the source point) + */ + CV_WRAP void getContour(const Point& targetPt, OutputArray contour, bool backward = false) const; + +#ifndef CV_DOXYGEN + struct Impl; + inline Impl* getImpl() const { return impl.get(); } +protected: + std::shared_ptr impl; +#endif +}; + +//! @} + +} // namespace segmentation +} // namespace cv + +#endif // OPENCV_IMGPROC_SEGMENTATION_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h b/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h index af25ac1c1b..255ed0c37f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/imgproc/types_c.h @@ -1,660 +1,660 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_IMGPROC_TYPES_C_H -#define OPENCV_IMGPROC_TYPES_C_H - -#include "opencv2/core/core_c.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** @addtogroup imgproc_c - @{ -*/ - -/** Connected component structure */ -typedef struct CvConnectedComp -{ - double area; /** DBL_EPSILON ? 1./std::sqrt(am00) : 0; - } - operator cv::Moments() const - { - return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); - } -#endif -} -CvMoments; - -#ifdef __cplusplus -} // extern "C" - -CV_INLINE CvMoments cvMoments() -{ -#if !defined(CV__ENABLE_C_API_CTORS) - CvMoments self = CV_STRUCT_INITIALIZER; return self; -#else - return CvMoments(); -#endif -} - -CV_INLINE CvMoments cvMoments(const cv::Moments& m) -{ -#if !defined(CV__ENABLE_C_API_CTORS) - double am00 = std::abs(m.m00); - CvMoments self = { - m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03, - m.mu20, m.mu11, m.mu02, m.mu30, m.mu21, m.mu12, m.mu03, - am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0 - }; - return self; -#else - return CvMoments(m); -#endif -} - -extern "C" { -#endif // __cplusplus - -/** Hu invariants */ -typedef struct CvHuMoments -{ - double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */ -} -CvHuMoments; - -/** Template matching methods */ -enum -{ - CV_TM_SQDIFF =0, - CV_TM_SQDIFF_NORMED =1, - CV_TM_CCORR =2, - CV_TM_CCORR_NORMED =3, - CV_TM_CCOEFF =4, - CV_TM_CCOEFF_NORMED =5 -}; - -typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); - -/** Contour retrieval modes */ -enum -{ - CV_RETR_EXTERNAL=0, - CV_RETR_LIST=1, - CV_RETR_CCOMP=2, - CV_RETR_TREE=3, - CV_RETR_FLOODFILL=4 -}; - -/** Contour approximation methods */ -enum -{ - CV_CHAIN_CODE=0, - CV_CHAIN_APPROX_NONE=1, - CV_CHAIN_APPROX_SIMPLE=2, - CV_CHAIN_APPROX_TC89_L1=3, - CV_CHAIN_APPROX_TC89_KCOS=4, - CV_LINK_RUNS=5 -}; - -/* -Internal structure that is used for sequential retrieving contours from the image. -It supports both hierarchical and plane variants of Suzuki algorithm. -*/ -typedef struct _CvContourScanner* CvContourScanner; - -/** Freeman chain reader state */ -typedef struct CvChainPtReader -{ - CV_SEQ_READER_FIELDS() - char code; - CvPoint pt; - schar deltas[8][2]; -} -CvChainPtReader; - -/** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ -#define CV_INIT_3X3_DELTAS( deltas, step, nch ) \ - ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ - (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ - (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ - (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) - - -/** Contour approximation algorithms */ -enum -{ - CV_POLY_APPROX_DP = 0 -}; - -/** Shape matching methods */ -enum -{ - CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] - CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] - CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] -}; - -/** Shape orientation */ -enum -{ - CV_CLOCKWISE =1, - CV_COUNTER_CLOCKWISE =2 -}; - - -/** Convexity defect */ -typedef struct CvConvexityDefect -{ - CvPoint* start; /**< point of the contour where the defect begins */ - CvPoint* end; /**< point of the contour where the defect ends */ - CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */ - float depth; /**< distance between the farthest point and the convex hull */ -} CvConvexityDefect; - - -/** Histogram comparison methods */ -enum -{ - CV_COMP_CORREL =0, - CV_COMP_CHISQR =1, - CV_COMP_INTERSECT =2, - CV_COMP_BHATTACHARYYA =3, - CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA, - CV_COMP_CHISQR_ALT =4, - CV_COMP_KL_DIV =5 -}; - -/** Mask size for distance transform */ -enum -{ - CV_DIST_MASK_3 =3, - CV_DIST_MASK_5 =5, - CV_DIST_MASK_PRECISE =0 -}; - -/** Content of output label array: connected components or pixels */ -enum -{ - CV_DIST_LABEL_CCOMP = 0, - CV_DIST_LABEL_PIXEL = 1 -}; - -/** Distance types for Distance Transform and M-estimators */ -enum -{ - CV_DIST_USER =-1, /**< User defined distance */ - CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */ - CV_DIST_L2 =2, /**< the simple euclidean distance */ - CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */ - CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */ - CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */ - CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */ - CV_DIST_HUBER =7 /**< distance = |x| threshold ? max_value : 0 */ - CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */ - CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */ - CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */ - CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */ - CV_THRESH_MASK =7, - CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value; - combine the flag with one of the above CV_THRESH_* values */ - CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value; - combine the flag with one of the above CV_THRESH_* values, but not - with CV_THRESH_OTSU */ -}; - -/** Adaptive threshold methods */ -enum -{ - CV_ADAPTIVE_THRESH_MEAN_C =0, - CV_ADAPTIVE_THRESH_GAUSSIAN_C =1 -}; - -/** FloodFill flags */ -enum -{ - CV_FLOODFILL_FIXED_RANGE =(1 << 16), - CV_FLOODFILL_MASK_ONLY =(1 << 17) -}; - - -/** Canny edge detector flags */ -enum -{ - CV_CANNY_L2_GRADIENT =(1 << 31) -}; - -/** Variants of a Hough transform */ -enum -{ - CV_HOUGH_STANDARD =0, - CV_HOUGH_PROBABILISTIC =1, - CV_HOUGH_MULTI_SCALE =2, - CV_HOUGH_GRADIENT =3 -}; - - -/* Fast search data structures */ -struct CvFeatureTree; -struct CvLSH; -struct CvLSHOperations; - -/** @} */ - -#ifdef __cplusplus -} -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_IMGPROC_TYPES_C_H +#define OPENCV_IMGPROC_TYPES_C_H + +#include "opencv2/core/core_c.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** @addtogroup imgproc_c + @{ +*/ + +/** Connected component structure */ +typedef struct CvConnectedComp +{ + double area; /** DBL_EPSILON ? 1./std::sqrt(am00) : 0; + } + operator cv::Moments() const + { + return cv::Moments(m00, m10, m01, m20, m11, m02, m30, m21, m12, m03); + } +#endif +} +CvMoments; + +#ifdef __cplusplus +} // extern "C" + +CV_INLINE CvMoments cvMoments() +{ +#if !defined(CV__ENABLE_C_API_CTORS) + CvMoments self = CV_STRUCT_INITIALIZER; return self; +#else + return CvMoments(); +#endif +} + +CV_INLINE CvMoments cvMoments(const cv::Moments& m) +{ +#if !defined(CV__ENABLE_C_API_CTORS) + double am00 = std::abs(m.m00); + CvMoments self = { + m.m00, m.m10, m.m01, m.m20, m.m11, m.m02, m.m30, m.m21, m.m12, m.m03, + m.mu20, m.mu11, m.mu02, m.mu30, m.mu21, m.mu12, m.mu03, + am00 > DBL_EPSILON ? 1./std::sqrt(am00) : 0 + }; + return self; +#else + return CvMoments(m); +#endif +} + +extern "C" { +#endif // __cplusplus + +/** Hu invariants */ +typedef struct CvHuMoments +{ + double hu1, hu2, hu3, hu4, hu5, hu6, hu7; /**< Hu invariants */ +} +CvHuMoments; + +/** Template matching methods */ +enum +{ + CV_TM_SQDIFF =0, + CV_TM_SQDIFF_NORMED =1, + CV_TM_CCORR =2, + CV_TM_CCORR_NORMED =3, + CV_TM_CCOEFF =4, + CV_TM_CCOEFF_NORMED =5 +}; + +typedef float (CV_CDECL * CvDistanceFunction)( const float* a, const float* b, void* user_param ); + +/** Contour retrieval modes */ +enum +{ + CV_RETR_EXTERNAL=0, + CV_RETR_LIST=1, + CV_RETR_CCOMP=2, + CV_RETR_TREE=3, + CV_RETR_FLOODFILL=4 +}; + +/** Contour approximation methods */ +enum +{ + CV_CHAIN_CODE=0, + CV_CHAIN_APPROX_NONE=1, + CV_CHAIN_APPROX_SIMPLE=2, + CV_CHAIN_APPROX_TC89_L1=3, + CV_CHAIN_APPROX_TC89_KCOS=4, + CV_LINK_RUNS=5 +}; + +/* +Internal structure that is used for sequential retrieving contours from the image. +It supports both hierarchical and plane variants of Suzuki algorithm. +*/ +typedef struct _CvContourScanner* CvContourScanner; + +/** Freeman chain reader state */ +typedef struct CvChainPtReader +{ + CV_SEQ_READER_FIELDS() + char code; + CvPoint pt; + schar deltas[8][2]; +} +CvChainPtReader; + +/** initializes 8-element array for fast access to 3x3 neighborhood of a pixel */ +#define CV_INIT_3X3_DELTAS( deltas, step, nch ) \ + ((deltas)[0] = (nch), (deltas)[1] = -(step) + (nch), \ + (deltas)[2] = -(step), (deltas)[3] = -(step) - (nch), \ + (deltas)[4] = -(nch), (deltas)[5] = (step) - (nch), \ + (deltas)[6] = (step), (deltas)[7] = (step) + (nch)) + + +/** Contour approximation algorithms */ +enum +{ + CV_POLY_APPROX_DP = 0 +}; + +/** Shape matching methods */ +enum +{ + CV_CONTOURS_MATCH_I1 =1, //!< \f[I_1(A,B) = \sum _{i=1...7} \left | \frac{1}{m^A_i} - \frac{1}{m^B_i} \right |\f] + CV_CONTOURS_MATCH_I2 =2, //!< \f[I_2(A,B) = \sum _{i=1...7} \left | m^A_i - m^B_i \right |\f] + CV_CONTOURS_MATCH_I3 =3 //!< \f[I_3(A,B) = \max _{i=1...7} \frac{ \left| m^A_i - m^B_i \right| }{ \left| m^A_i \right| }\f] +}; + +/** Shape orientation */ +enum +{ + CV_CLOCKWISE =1, + CV_COUNTER_CLOCKWISE =2 +}; + + +/** Convexity defect */ +typedef struct CvConvexityDefect +{ + CvPoint* start; /**< point of the contour where the defect begins */ + CvPoint* end; /**< point of the contour where the defect ends */ + CvPoint* depth_point; /**< the farthest from the convex hull point within the defect */ + float depth; /**< distance between the farthest point and the convex hull */ +} CvConvexityDefect; + + +/** Histogram comparison methods */ +enum +{ + CV_COMP_CORREL =0, + CV_COMP_CHISQR =1, + CV_COMP_INTERSECT =2, + CV_COMP_BHATTACHARYYA =3, + CV_COMP_HELLINGER =CV_COMP_BHATTACHARYYA, + CV_COMP_CHISQR_ALT =4, + CV_COMP_KL_DIV =5 +}; + +/** Mask size for distance transform */ +enum +{ + CV_DIST_MASK_3 =3, + CV_DIST_MASK_5 =5, + CV_DIST_MASK_PRECISE =0 +}; + +/** Content of output label array: connected components or pixels */ +enum +{ + CV_DIST_LABEL_CCOMP = 0, + CV_DIST_LABEL_PIXEL = 1 +}; + +/** Distance types for Distance Transform and M-estimators */ +enum +{ + CV_DIST_USER =-1, /**< User defined distance */ + CV_DIST_L1 =1, /**< distance = |x1-x2| + |y1-y2| */ + CV_DIST_L2 =2, /**< the simple euclidean distance */ + CV_DIST_C =3, /**< distance = max(|x1-x2|,|y1-y2|) */ + CV_DIST_L12 =4, /**< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) */ + CV_DIST_FAIR =5, /**< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 */ + CV_DIST_WELSCH =6, /**< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 */ + CV_DIST_HUBER =7 /**< distance = |x| threshold ? max_value : 0 */ + CV_THRESH_BINARY_INV =1, /**< value = value > threshold ? 0 : max_value */ + CV_THRESH_TRUNC =2, /**< value = value > threshold ? threshold : value */ + CV_THRESH_TOZERO =3, /**< value = value > threshold ? value : 0 */ + CV_THRESH_TOZERO_INV =4, /**< value = value > threshold ? 0 : value */ + CV_THRESH_MASK =7, + CV_THRESH_OTSU =8, /**< use Otsu algorithm to choose the optimal threshold value; + combine the flag with one of the above CV_THRESH_* values */ + CV_THRESH_TRIANGLE =16 /**< use Triangle algorithm to choose the optimal threshold value; + combine the flag with one of the above CV_THRESH_* values, but not + with CV_THRESH_OTSU */ +}; + +/** Adaptive threshold methods */ +enum +{ + CV_ADAPTIVE_THRESH_MEAN_C =0, + CV_ADAPTIVE_THRESH_GAUSSIAN_C =1 +}; + +/** FloodFill flags */ +enum +{ + CV_FLOODFILL_FIXED_RANGE =(1 << 16), + CV_FLOODFILL_MASK_ONLY =(1 << 17) +}; + + +/** Canny edge detector flags */ +enum +{ + CV_CANNY_L2_GRADIENT =(1 << 31) +}; + +/** Variants of a Hough transform */ +enum +{ + CV_HOUGH_STANDARD =0, + CV_HOUGH_PROBABILISTIC =1, + CV_HOUGH_MULTI_SCALE =2, + CV_HOUGH_GRADIENT =3 +}; + + +/* Fast search data structures */ +struct CvFeatureTree; +struct CvLSH; +struct CvLSHOperations; + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/ml.hpp b/3rdParty/opencv-4.11.0/opencv2/ml.hpp index 4e62c98dcc..d537ab7759 100644 --- a/3rdParty/opencv-4.11.0/opencv2/ml.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/ml.hpp @@ -1,1956 +1,1956 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Copyright (C) 2014, Itseez Inc, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_ML_HPP -#define OPENCV_ML_HPP - -#ifdef __cplusplus -# include "opencv2/core.hpp" -#endif - -#ifdef __cplusplus - -#include -#include -#include - -/** - @defgroup ml Machine Learning - - The Machine Learning Library (MLL) is a set of classes and functions for statistical - classification, regression, and clustering of data. - - Most of the classification and regression algorithms are implemented as C++ classes. As the - algorithms have different sets of features (like an ability to handle missing measurements or - categorical input variables), there is a little common ground between the classes. This common - ground is defined by the class cv::ml::StatModel that all the other ML classes are derived from. - - See detailed overview here: @ref ml_intro. - */ - -namespace cv -{ - -namespace ml -{ - -//! @addtogroup ml -//! @{ - -/** @brief Variable types */ -enum VariableTypes -{ - VAR_NUMERICAL =0, //!< same as VAR_ORDERED - VAR_ORDERED =0, //!< ordered variables - VAR_CATEGORICAL =1 //!< categorical variables -}; - -/** @brief %Error types */ -enum ErrorTypes -{ - TEST_ERROR = 0, - TRAIN_ERROR = 1 -}; - -/** @brief Sample types */ -enum SampleTypes -{ - ROW_SAMPLE = 0, //!< each training sample is a row of samples - COL_SAMPLE = 1 //!< each training sample occupies a column of samples -}; - -/** @brief The structure represents the logarithmic grid range of statmodel parameters. - -It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate -being computed by cross-validation. - */ -class CV_EXPORTS_W ParamGrid -{ -public: - /** @brief Default constructor */ - ParamGrid(); - /** @brief Constructor with parameters */ - ParamGrid(double _minVal, double _maxVal, double _logStep); - - CV_PROP_RW double minVal; //!< Minimum value of the statmodel parameter. Default value is 0. - CV_PROP_RW double maxVal; //!< Maximum value of the statmodel parameter. Default value is 0. - /** @brief Logarithmic step for iterating the statmodel parameter. - - The grid determines the following iteration sequence of the statmodel parameter values: - \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f] - where \f$n\f$ is the maximal index satisfying - \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f] - The grid is logarithmic, so logStep must always be greater than 1. Default value is 1. - */ - CV_PROP_RW double logStep; - - /** @brief Creates a ParamGrid Ptr that can be given to the %SVM::trainAuto method - - @param minVal minimum value of the parameter grid - @param maxVal maximum value of the parameter grid - @param logstep Logarithmic step for iterating the statmodel parameter - */ - CV_WRAP static Ptr create(double minVal=0., double maxVal=0., double logstep=1.); -}; - -/** @brief Class encapsulating training data. - -Please note that the class only specifies the interface of training data, but not implementation. -All the statistical model classes in _ml_ module accepts Ptr\ as parameter. In other -words, you can create your own class derived from TrainData and pass smart pointer to the instance -of this class into StatModel::train. - -@sa @ref ml_intro_data - */ -class CV_EXPORTS_W TrainData -{ -public: - static inline float missingValue() { return FLT_MAX; } - virtual ~TrainData(); - - CV_WRAP virtual int getLayout() const = 0; - CV_WRAP virtual int getNTrainSamples() const = 0; - CV_WRAP virtual int getNTestSamples() const = 0; - CV_WRAP virtual int getNSamples() const = 0; - CV_WRAP virtual int getNVars() const = 0; - CV_WRAP virtual int getNAllVars() const = 0; - - CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0; - CV_WRAP virtual Mat getSamples() const = 0; - CV_WRAP virtual Mat getMissing() const = 0; - - /** @brief Returns matrix of train samples - - @param layout The requested layout. If it's different from the initial one, the matrix is - transposed. See ml::SampleTypes. - @param compressSamples if true, the function returns only the training samples (specified by - sampleIdx) - @param compressVars if true, the function returns the shorter training samples, containing only - the active variables. - - In current implementation the function tries to avoid physical data copying and returns the - matrix stored inside TrainData (unless the transposition or compression is needed). - */ - CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE, - bool compressSamples=true, - bool compressVars=true) const = 0; - - /** @brief Returns the vector of responses - - The function returns ordered or the original categorical responses. Usually it's used in - regression algorithms. - */ - CV_WRAP virtual Mat getTrainResponses() const = 0; - - /** @brief Returns the vector of normalized categorical responses - - The function returns vector of responses. Each response is integer from `0` to `-1`. The actual label value can be retrieved then from the class label vector, see - TrainData::getClassLabels. - */ - CV_WRAP virtual Mat getTrainNormCatResponses() const = 0; - CV_WRAP virtual Mat getTestResponses() const = 0; - CV_WRAP virtual Mat getTestNormCatResponses() const = 0; - CV_WRAP virtual Mat getResponses() const = 0; - CV_WRAP virtual Mat getNormCatResponses() const = 0; - CV_WRAP virtual Mat getSampleWeights() const = 0; - CV_WRAP virtual Mat getTrainSampleWeights() const = 0; - CV_WRAP virtual Mat getTestSampleWeights() const = 0; - CV_WRAP virtual Mat getVarIdx() const = 0; - CV_WRAP virtual Mat getVarType() const = 0; - CV_WRAP virtual Mat getVarSymbolFlags() const = 0; - CV_WRAP virtual int getResponseType() const = 0; - CV_WRAP virtual Mat getTrainSampleIdx() const = 0; - CV_WRAP virtual Mat getTestSampleIdx() const = 0; - CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0; - virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0; - CV_WRAP virtual Mat getDefaultSubstValues() const = 0; - - CV_WRAP virtual int getCatCount(int vi) const = 0; - - /** @brief Returns the vector of class labels - - The function returns vector of unique labels occurred in the responses. - */ - CV_WRAP virtual Mat getClassLabels() const = 0; - - CV_WRAP virtual Mat getCatOfs() const = 0; - CV_WRAP virtual Mat getCatMap() const = 0; - - /** @brief Splits the training data into the training and test parts - @sa TrainData::setTrainTestSplitRatio - */ - CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0; - - /** @brief Splits the training data into the training and test parts - - The function selects a subset of specified relative size and then returns it as the training - set. If the function is not called, all the data is used for training. Please, note that for - each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test - subset can be retrieved and processed as well. - @sa TrainData::setTrainTestSplit - */ - CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0; - CV_WRAP virtual void shuffleTrainTest() = 0; - - /** @brief Returns matrix of test samples */ - CV_WRAP virtual Mat getTestSamples() const = 0; - - /** @brief Returns vector of symbolic names captured in loadFromCSV() */ - CV_WRAP virtual void getNames(std::vector& names) const = 0; - - /** @brief Extract from 1D vector elements specified by passed indexes. - @param vec input vector (supported types: CV_32S, CV_32F, CV_64F) - @param idx 1D index vector - */ - static CV_WRAP Mat getSubVector(const Mat& vec, const Mat& idx); - - /** @brief Extract from matrix rows/cols specified by passed indexes. - @param matrix input matrix (supported types: CV_32S, CV_32F, CV_64F) - @param idx 1D index vector - @param layout specifies to extract rows (cv::ml::ROW_SAMPLES) or to extract columns (cv::ml::COL_SAMPLES) - */ - static CV_WRAP Mat getSubMatrix(const Mat& matrix, const Mat& idx, int layout); - - /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data. - - @param filename The input file name - @param headerLineCount The number of lines in the beginning to skip; besides the header, the - function also skips empty lines and lines staring with `#` - @param responseStartIdx Index of the first output variable. If -1, the function considers the - last variable as the response - @param responseEndIdx Index of the last output variable + 1. If -1, then there is single - response variable at responseStartIdx. - @param varTypeSpec The optional text string that specifies the variables' types. It has the - format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2` - (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are - considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` - should cover all the variables. If varTypeSpec is not specified, then algorithm uses the - following rules: - - all input variables are considered ordered by default. If some column contains has non- - numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding - variable is considered categorical. - - if there are several output variables, they are all considered as ordered. Error is - reported when non-numerical values are used. - - if there is a single output variable, then if its values are non-numerical or are all - integers, then it's considered categorical. Otherwise, it's considered ordered. - @param delimiter The character used to separate values in each line. - @param missch The character used to specify missing measurements. It should not be a digit. - Although it's a non-numerical value, it surely does not affect the decision of whether the - variable ordered or categorical. - @note If the dataset only contains input variables and no responses, use responseStartIdx = -2 - and responseEndIdx = 0. The output variables vector will just contain zeros. - */ - static Ptr loadFromCSV(const String& filename, - int headerLineCount, - int responseStartIdx=-1, - int responseEndIdx=-1, - const String& varTypeSpec=String(), - char delimiter=',', - char missch='?'); - - /** @brief Creates training data from in-memory arrays. - - @param samples matrix of samples. It should have CV_32F type. - @param layout see ml::SampleTypes. - @param responses matrix of responses. If the responses are scalar, they should be stored as a - single row or as a single column. The matrix should have type CV_32F or CV_32S (in the - former case the responses are considered as ordered by default; in the latter case - as - categorical) - @param varIdx vector specifying which variables to use for training. It can be an integer vector - (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of - active variables. - @param sampleIdx vector specifying which samples to use for training. It can be an integer - vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask - of training samples. - @param sampleWeights optional vector with weights for each sample. It should have CV_32F type. - @param varType optional vector of type CV_8U and size ` + - `, containing types of each input and output variable. See - ml::VariableTypes. - */ - CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, - InputArray varIdx=noArray(), InputArray sampleIdx=noArray(), - InputArray sampleWeights=noArray(), InputArray varType=noArray()); -}; - -/** @brief Base class for statistical models in OpenCV ML. - */ -class CV_EXPORTS_W StatModel : public Algorithm -{ -public: - /** Predict options */ - enum Flags { - UPDATE_MODEL = 1, - RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label - COMPRESSED_INPUT=2, - PREPROCESSED_INPUT=4 - }; - - /** @brief Returns the number of variables in training samples */ - CV_WRAP virtual int getVarCount() const = 0; - - CV_WRAP virtual bool empty() const CV_OVERRIDE; - - /** @brief Returns true if the model is trained */ - CV_WRAP virtual bool isTrained() const = 0; - /** @brief Returns true if the model is classifier */ - CV_WRAP virtual bool isClassifier() const = 0; - - /** @brief Trains the statistical model - - @param trainData training data that can be loaded from file using TrainData::loadFromCSV or - created with TrainData::create. - @param flags optional flags, depending on the model. Some of the models can be updated with the - new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). - */ - CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); - - /** @brief Trains the statistical model - - @param samples training samples - @param layout See ml::SampleTypes. - @param responses vector of responses associated with the training samples. - */ - CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses ); - - /** @brief Computes error on the training or test dataset - - @param data the training data - @param test if true, the error is computed over the test subset of the data, otherwise it's - computed over the training subset of the data. Please note that if you loaded a completely - different dataset to evaluate already trained classifier, you will probably want not to set - the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so - that the error is computed for the whole new set. Yes, this sounds a bit confusing. - @param resp the optional output responses. - - The method uses StatModel::predict to compute the error. For regression models the error is - computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%). - */ - CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; - - /** @brief Predicts response(s) for the provided sample(s) - - @param samples The input samples, floating-point matrix - @param results The optional output matrix of results. - @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags. - */ - CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0; - - /** @brief Create and train model with default parameters - - The class must implement static `create()` method with no parameters or with all default parameter values - */ - template static Ptr<_Tp> train(const Ptr& data, int flags=0) - { - Ptr<_Tp> model = _Tp::create(); - return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>(); - } -}; - -/****************************************************************************************\ -* Normal Bayes Classifier * -\****************************************************************************************/ - -/** @brief Bayes classifier for normally distributed data. - -@sa @ref ml_intro_bayes - */ -class CV_EXPORTS_W NormalBayesClassifier : public StatModel -{ -public: - /** @brief Predicts the response for sample(s). - - The method estimates the most probable classes for input vectors. Input vectors (one or more) - are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one - output vector outputs. The predicted class for a single input vector is returned by the method. - The vector outputProbs contains the output probabilities corresponding to each element of - result. - */ - CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs, - OutputArray outputProbs, int flags=0 ) const = 0; - - /** Creates empty model - Use StatModel::train to train the model after creation. */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized NormalBayesClassifier from a file - * - * Use NormalBayesClassifier::save to serialize and store an NormalBayesClassifier to disk. - * Load the NormalBayesClassifier from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized NormalBayesClassifier - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* K-Nearest Neighbour Classifier * -\****************************************************************************************/ - -/** @brief The class implements K-Nearest Neighbors model - -@sa @ref ml_intro_knn - */ -class CV_EXPORTS_W KNearest : public StatModel -{ -public: - - /** Default number of neighbors to use in predict method. */ - /** @see setDefaultK */ - CV_WRAP virtual int getDefaultK() const = 0; - /** @copybrief getDefaultK @see getDefaultK */ - CV_WRAP virtual void setDefaultK(int val) = 0; - - /** Whether classification or regression model should be trained. */ - /** @see setIsClassifier */ - CV_WRAP virtual bool getIsClassifier() const = 0; - /** @copybrief getIsClassifier @see getIsClassifier */ - CV_WRAP virtual void setIsClassifier(bool val) = 0; - - /** Parameter for KDTree implementation. */ - /** @see setEmax */ - CV_WRAP virtual int getEmax() const = 0; - /** @copybrief getEmax @see getEmax */ - CV_WRAP virtual void setEmax(int val) = 0; - - /** %Algorithm type, one of KNearest::Types. */ - /** @see setAlgorithmType */ - CV_WRAP virtual int getAlgorithmType() const = 0; - /** @copybrief getAlgorithmType @see getAlgorithmType */ - CV_WRAP virtual void setAlgorithmType(int val) = 0; - - /** @brief Finds the neighbors and predicts responses for input vectors. - - @param samples Input samples stored by rows. It is a single-precision floating-point matrix of - ` * k` size. - @param k Number of used nearest neighbors. Should be greater than 1. - @param results Vector with results of prediction (regression or classification) for each input - sample. It is a single-precision floating-point vector with `` elements. - @param neighborResponses Optional output values for corresponding neighbors. It is a single- - precision floating-point matrix of ` * k` size. - @param dist Optional output distances from the input vectors to the corresponding neighbors. It - is a single-precision floating-point matrix of ` * k` size. - - For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. - In case of regression, the predicted result is a mean value of the particular vector's neighbor - responses. In case of classification, the class is determined by voting. - - For each input vector, the neighbors are sorted by their distances to the vector. - - In case of C++ interface you can use output pointers to empty matrices and the function will - allocate memory itself. - - If only a single input vector is passed, all output matrices are optional and the predicted - value is returned by the method. - - The function is parallelized with the TBB library. - */ - CV_WRAP virtual float findNearest( InputArray samples, int k, - OutputArray results, - OutputArray neighborResponses=noArray(), - OutputArray dist=noArray() ) const = 0; - - /** @brief Implementations of KNearest algorithm - */ - enum Types - { - BRUTE_FORCE=1, - KDTREE=2 - }; - - /** @brief Creates the empty model - - The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method. - */ - CV_WRAP static Ptr create(); - /** @brief Loads and creates a serialized knearest from a file - * - * Use KNearest::save to serialize and store an KNearest to disk. - * Load the KNearest from this file again, by calling this function with the path to the file. - * - * @param filepath path to serialized KNearest - */ - CV_WRAP static Ptr load(const String& filepath); -}; - -/****************************************************************************************\ -* Support Vector Machines * -\****************************************************************************************/ - -/** @brief Support Vector Machines. - -@sa @ref ml_intro_svm - */ -class CV_EXPORTS_W SVM : public StatModel -{ -public: - - class CV_EXPORTS Kernel : public Algorithm - { - public: - virtual int getType() const = 0; - virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0; - }; - - /** Type of a %SVM formulation. - See SVM::Types. Default value is SVM::C_SVC. */ - /** @see setType */ - CV_WRAP virtual int getType() const = 0; - /** @copybrief getType @see getType */ - CV_WRAP virtual void setType(int val) = 0; - - /** Parameter \f$\gamma\f$ of a kernel function. - For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */ - /** @see setGamma */ - CV_WRAP virtual double getGamma() const = 0; - /** @copybrief getGamma @see getGamma */ - CV_WRAP virtual void setGamma(double val) = 0; - - /** Parameter _coef0_ of a kernel function. - For SVM::POLY or SVM::SIGMOID. Default value is 0.*/ - /** @see setCoef0 */ - CV_WRAP virtual double getCoef0() const = 0; - /** @copybrief getCoef0 @see getCoef0 */ - CV_WRAP virtual void setCoef0(double val) = 0; - - /** Parameter _degree_ of a kernel function. - For SVM::POLY. Default value is 0. */ - /** @see setDegree */ - CV_WRAP virtual double getDegree() const = 0; - /** @copybrief getDegree @see getDegree */ - CV_WRAP virtual void setDegree(double val) = 0; - - /** Parameter _C_ of a %SVM optimization problem. - For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */ - /** @see setC */ - CV_WRAP virtual double getC() const = 0; - /** @copybrief getC @see getC */ - CV_WRAP virtual void setC(double val) = 0; - - /** Parameter \f$\nu\f$ of a %SVM optimization problem. - For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */ - /** @see setNu */ - CV_WRAP virtual double getNu() const = 0; - /** @copybrief getNu @see getNu */ - CV_WRAP virtual void setNu(double val) = 0; - - /** Parameter \f$\epsilon\f$ of a %SVM optimization problem. - For SVM::EPS_SVR. Default value is 0. */ - /** @see setP */ - CV_WRAP virtual double getP() const = 0; - /** @copybrief getP @see getP */ - CV_WRAP virtual void setP(double val) = 0; - - /** Optional weights in the SVM::C_SVC problem, assigned to particular classes. - They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus - these weights affect the misclassification penalty for different classes. The larger weight, - the larger penalty on misclassification of data from the corresponding class. Default value is - empty Mat. */ - /** @see setClassWeights */ - CV_WRAP virtual cv::Mat getClassWeights() const = 0; - /** @copybrief getClassWeights @see getClassWeights */ - CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0; - - /** Termination criteria of the iterative %SVM training procedure which solves a partial - case of constrained quadratic optimization problem. - You can specify tolerance and/or the maximum number of iterations. Default value is - `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */ - /** @see setTermCriteria */ - CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; - - /** Type of a %SVM kernel. - See SVM::KernelTypes. Default value is SVM::RBF. */ - CV_WRAP virtual int getKernelType() const = 0; - - /** Initialize with one of predefined kernels. - See SVM::KernelTypes. */ - CV_WRAP virtual void setKernel(int kernelType) = 0; - - /** Initialize with custom kernel. - See SVM::Kernel class for implementation details */ - virtual void setCustomKernel(const Ptr &_kernel) = 0; - - //! %SVM type - enum Types { - /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows - imperfect separation of classes with penalty multiplier C for outliers. */ - C_SVC=100, - /** \f$\nu\f$-Support Vector Classification. n-class classification with possible - imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother - the decision boundary) is used instead of C. */ - NU_SVC=101, - /** Distribution Estimation (One-class %SVM). All the training data are from - the same class, %SVM builds a boundary that separates the class from the rest of the feature - space. */ - ONE_CLASS=102, - /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors - from the training set and the fitting hyper-plane must be less than p. For outliers the - penalty multiplier C is used. */ - EPS_SVR=103, - /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p. - See @cite LibSVM for details. */ - NU_SVR=104 - }; - - /** @brief %SVM kernel type - - A comparison of different kernels on the following 2D test case with four classes. Four - SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three - different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score. - Bright means max-score \> 0, dark means max-score \< 0. - ![image](pics/SVM_Comparison.png) - */ - enum KernelTypes { - /** Returned by SVM::getKernelType in case when custom kernel has been set */ - CUSTOM=-1, - /** Linear kernel. No mapping is done, linear discrimination (or regression) is - done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */ - LINEAR=0, - /** Polynomial kernel: - \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */ - POLY=1, - /** Radial basis function (RBF), a good choice in most cases. - \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */ - RBF=2, - /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */ - SIGMOID=3, - /** Exponential Chi2 kernel, similar to the RBF kernel: - \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. */ - CHI2=4, - /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */ - INTER=5 - }; - - //! %SVM params type - enum ParamTypes { - C=0, - GAMMA=1, - P=2, - NU=3, - COEF=4, - DEGREE=5 - }; - - /** @brief Trains an %SVM with optimal parameters. - - @param data the training data that can be constructed using TrainData::create or - TrainData::loadFromCSV. - @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One - subset is used to test the model, the others form the train set. So, the %SVM algorithm is - executed kFold times. - @param Cgrid grid for C - @param gammaGrid grid for gamma - @param pGrid grid for p - @param nuGrid grid for nu - @param coeffGrid grid for coeff - @param degreeGrid grid for degree - @param balanced If true and the problem is 2-class classification then the method creates more - balanced cross-validation subsets that is proportions between classes in subsets are close - to such proportion in the whole train dataset. - - The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, - nu, coef0, degree. Parameters are considered optimal when the cross-validation - estimate of the test set error is minimal. - - If there is no need to optimize a parameter, the corresponding grid step should be set to any - value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step - = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value - `Gamma` is taken for gamma. - - And, finally, if the optimization in a parameter is required but the corresponding grid is - unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for - gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`. - - This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the - regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and - the usual %SVM with parameters specified in params is executed. - */ - virtual bool trainAuto( const Ptr& data, int kFold = 10, - ParamGrid Cgrid = getDefaultGrid(C), - ParamGrid gammaGrid = getDefaultGrid(GAMMA), - ParamGrid pGrid = getDefaultGrid(P), - ParamGrid nuGrid = getDefaultGrid(NU), - ParamGrid coeffGrid = getDefaultGrid(COEF), - ParamGrid degreeGrid = getDefaultGrid(DEGREE), - bool balanced=false) = 0; - - /** @brief Trains an %SVM with optimal parameters - - @param samples training samples - @param layout See ml::SampleTypes. - @param responses vector of responses associated with the training samples. - @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One - subset is used to test the model, the others form the train set. So, the %SVM algorithm is - @param Cgrid grid for C - @param gammaGrid grid for gamma - @param pGrid grid for p - @param nuGrid grid for nu - @param coeffGrid grid for coeff - @param degreeGrid grid for degree - @param balanced If true and the problem is 2-class classification then the method creates more - balanced cross-validation subsets that is proportions between classes in subsets are close - to such proportion in the whole train dataset. - - The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, - nu, coef0, degree. Parameters are considered optimal when the cross-validation - estimate of the test set error is minimal. - - This function only makes use of SVM::getDefaultGrid for parameter optimization and thus only - offers rudimentary parameter options. - - This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the - regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and - the usual %SVM with parameters specified in params is executed. - */ - CV_WRAP virtual bool trainAuto(InputArray samples, - int layout, - InputArray responses, - int kFold = 10, - Ptr Cgrid = SVM::getDefaultGridPtr(SVM::C), - Ptr gammaGrid = SVM::getDefaultGridPtr(SVM::GAMMA), - Ptr pGrid = SVM::getDefaultGridPtr(SVM::P), - Ptr nuGrid = SVM::getDefaultGridPtr(SVM::NU), - Ptr coeffGrid = SVM::getDefaultGridPtr(SVM::COEF), - Ptr degreeGrid = SVM::getDefaultGridPtr(SVM::DEGREE), - bool balanced=false) = 0; - - /** @brief Retrieves all the support vectors - - The method returns all the support vectors as a floating-point matrix, where support vectors are - stored as matrix rows. - */ - CV_WRAP virtual Mat getSupportVectors() const = 0; - - /** @brief Retrieves all the uncompressed support vectors of a linear %SVM - - The method returns all the uncompressed support vectors of a linear %SVM that the compressed - support vector, used for prediction, was derived from. They are returned in a floating-point - matrix, where the support vectors are stored as matrix rows. - */ - CV_WRAP virtual Mat getUncompressedSupportVectors() const = 0; - - /** @brief Retrieves the decision function - - @param i the index of the decision function. If the problem solved is regression, 1-class or - 2-class classification, then there will be just one decision function and the index should - always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$ - decision functions. - @param alpha the optional output vector for weights, corresponding to different support vectors. - In the case of linear %SVM all the alpha's will be 1's. - @param svidx the optional output vector of indices of support vectors within the matrix of - support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear - %SVM each decision function consists of a single "compressed" support vector. - - The method returns rho parameter of the decision function, a scalar subtracted from the weighted - sum of kernel responses. - */ - CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0; - - /** @brief Generates a grid for %SVM parameters. - - @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is - generated for the parameter with this ID. - - The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be - passed to the function SVM::trainAuto. - */ - static ParamGrid getDefaultGrid( int param_id ); - - /** @brief Generates a grid for %SVM parameters. - - @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is - generated for the parameter with this ID. - - The function generates a grid pointer for the specified parameter of the %SVM algorithm. - The grid may be passed to the function SVM::trainAuto. - */ - CV_WRAP static Ptr getDefaultGridPtr( int param_id ); - - /** Creates empty model. - Use StatModel::train to train the model. Since %SVM has several parameters, you may want to - find the best parameters for your problem, it can be done with SVM::trainAuto. */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized svm from a file - * - * Use SVM::save to serialize and store an SVM to disk. - * Load the SVM from this file again, by calling this function with the path to the file. - * - * @param filepath path to serialized svm - */ - CV_WRAP static Ptr load(const String& filepath); -}; - -/****************************************************************************************\ -* Expectation - Maximization * -\****************************************************************************************/ - -/** @brief The class implements the Expectation Maximization algorithm. - -@sa @ref ml_intro_em - */ -class CV_EXPORTS_W EM : public StatModel -{ -public: - //! Type of covariation matrices - enum Types { - /** A scaled identity matrix \f$\mu_k * I\f$. There is the only - parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases, - when the constraint is relevant, or as a first step in the optimization (for example in case - when the data is preprocessed with PCA). The results of such preliminary estimation may be - passed again to the optimization procedure, this time with - covMatType=EM::COV_MAT_DIAGONAL. */ - COV_MAT_SPHERICAL=0, - /** A diagonal matrix with positive diagonal elements. The number of - free parameters is d for each matrix. This is most commonly used option yielding good - estimation results. */ - COV_MAT_DIAGONAL=1, - /** A symmetric positively defined matrix. The number of free - parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless - there is pretty accurate initial estimation of the parameters and/or a huge number of - training samples. */ - COV_MAT_GENERIC=2, - COV_MAT_DEFAULT=COV_MAT_DIAGONAL - }; - - //! Default parameters - enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100}; - - //! The initial step - enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0}; - - /** The number of mixture components in the Gaussian mixture model. - Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could - determine the optimal number of mixtures within a specified value range, but that is not the - case in ML yet. */ - /** @see setClustersNumber */ - CV_WRAP virtual int getClustersNumber() const = 0; - /** @copybrief getClustersNumber @see getClustersNumber */ - CV_WRAP virtual void setClustersNumber(int val) = 0; - - /** Constraint on covariance matrices which defines type of matrices. - See EM::Types. */ - /** @see setCovarianceMatrixType */ - CV_WRAP virtual int getCovarianceMatrixType() const = 0; - /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */ - CV_WRAP virtual void setCovarianceMatrixType(int val) = 0; - - /** The termination criteria of the %EM algorithm. - The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of - M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default - maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; - - /** @brief Returns weights of the mixtures - - Returns vector with the number of elements equal to the number of mixtures. - */ - CV_WRAP virtual Mat getWeights() const = 0; - /** @brief Returns the cluster centers (means of the Gaussian mixture) - - Returns matrix with the number of rows equal to the number of mixtures and number of columns - equal to the space dimensionality. - */ - CV_WRAP virtual Mat getMeans() const = 0; - /** @brief Returns covariation matrices - - Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures, - each matrix is a square floating-point matrix NxN, where N is the space dimensionality. - */ - CV_WRAP virtual void getCovs(CV_OUT std::vector& covs) const = 0; - - /** @brief Returns posterior probabilities for the provided samples - - @param samples The input samples, floating-point matrix - @param results The optional output \f$ nSamples \times nClusters\f$ matrix of results. It contains - posterior probabilities for each sample from the input - @param flags This parameter will be ignored - */ - CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; - - /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component - for the given sample. - - @param sample A sample for classification. It should be a one-channel matrix of - \f$1 \times dims\f$ or \f$dims \times 1\f$ size. - @param probs Optional output matrix that contains posterior probabilities of each component - given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. - - The method returns a two-element double vector. Zero element is a likelihood logarithm value for - the sample. First element is an index of the most probable mixture component for the given - sample. - */ - CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0; - - /** @brief Estimate the Gaussian mixture parameters from a samples set. - - This variation starts with Expectation step. Initial values of the model parameters will be - estimated by the k-means algorithm. - - Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take - responses (class labels or function values) as input. Instead, it computes the *Maximum - Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the - parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in - covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each - sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most - probable mixture component for each sample). - - The trained model can be used further for prediction, just like any other classifier. The - trained model is similar to the NormalBayesClassifier. - - @param samples Samples from which the Gaussian mixture model will be estimated. It should be a - one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type - it will be converted to the inner matrix of such type for the further computing. - @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for - each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. - @param labels The optional output "class label" for each sample: - \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable - mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. - @param probs The optional output matrix that contains posterior probabilities of each Gaussian - mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and - CV_64FC1 type. - */ - CV_WRAP virtual bool trainEM(InputArray samples, - OutputArray logLikelihoods=noArray(), - OutputArray labels=noArray(), - OutputArray probs=noArray()) = 0; - - /** @brief Estimate the Gaussian mixture parameters from a samples set. - - This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of - mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices - \f$S_k\f$ of mixture components. - - @param samples Samples from which the Gaussian mixture model will be estimated. It should be a - one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type - it will be converted to the inner matrix of such type for the further computing. - @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of - \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be - converted to the inner matrix of such type for the further computing. - @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of - covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices - do not have CV_64F type they will be converted to the inner matrices of such type for the - further computing. - @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel - floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size. - @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for - each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. - @param labels The optional output "class label" for each sample: - \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable - mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. - @param probs The optional output matrix that contains posterior probabilities of each Gaussian - mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and - CV_64FC1 type. - */ - CV_WRAP virtual bool trainE(InputArray samples, InputArray means0, - InputArray covs0=noArray(), - InputArray weights0=noArray(), - OutputArray logLikelihoods=noArray(), - OutputArray labels=noArray(), - OutputArray probs=noArray()) = 0; - - /** @brief Estimate the Gaussian mixture parameters from a samples set. - - This variation starts with Maximization step. You need to provide initial probabilities - \f$p_{i,k}\f$ to use this option. - - @param samples Samples from which the Gaussian mixture model will be estimated. It should be a - one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type - it will be converted to the inner matrix of such type for the further computing. - @param probs0 the probabilities - @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for - each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. - @param labels The optional output "class label" for each sample: - \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable - mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. - @param probs The optional output matrix that contains posterior probabilities of each Gaussian - mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and - CV_64FC1 type. - */ - CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0, - OutputArray logLikelihoods=noArray(), - OutputArray labels=noArray(), - OutputArray probs=noArray()) = 0; - - /** Creates empty %EM model. - The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you - can use one of the EM::train\* methods or load it from file using Algorithm::load\(filename). - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized EM from a file - * - * Use EM::save to serialize and store an EM to disk. - * Load the EM from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized EM - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Decision Tree * -\****************************************************************************************/ - -/** @brief The class represents a single decision tree or a collection of decision trees. - -The current public interface of the class allows user to train only a single decision tree, however -the class is capable of storing multiple decision trees and using them for prediction (by summing -responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost) -use this capability to implement decision tree ensembles. - -@sa @ref ml_intro_trees -*/ -class CV_EXPORTS_W DTrees : public StatModel -{ -public: - /** Predict options */ - enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) }; - - /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to - find a suboptimal split. - If a discrete variable, on which the training procedure tries to make a split, takes more than - maxCategories values, the precise best subset estimation may take a very long time because the - algorithm is exponential. Instead, many decision trees engines (including our implementation) - try to find sub-optimal split in this case by clustering all the samples into maxCategories - clusters that is some categories are merged together. The clustering is applied only in n \> - 2-class classification problems for categorical variables with N \> max_categories possible - values. In case of regression and 2-class classification the optimal split can be found - efficiently without employing clustering, thus the parameter is not used in these cases. - Default value is 10.*/ - /** @see setMaxCategories */ - CV_WRAP virtual int getMaxCategories() const = 0; - /** @copybrief getMaxCategories @see getMaxCategories */ - CV_WRAP virtual void setMaxCategories(int val) = 0; - - /** The maximum possible depth of the tree. - That is the training algorithms attempts to split a node while its depth is less than maxDepth. - The root node has zero depth. The actual depth may be smaller if the other termination criteria - are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the - tree is pruned. Default value is INT_MAX.*/ - /** @see setMaxDepth */ - CV_WRAP virtual int getMaxDepth() const = 0; - /** @copybrief getMaxDepth @see getMaxDepth */ - CV_WRAP virtual void setMaxDepth(int val) = 0; - - /** If the number of samples in a node is less than this parameter then the node will not be split. - - Default value is 10.*/ - /** @see setMinSampleCount */ - CV_WRAP virtual int getMinSampleCount() const = 0; - /** @copybrief getMinSampleCount @see getMinSampleCount */ - CV_WRAP virtual void setMinSampleCount(int val) = 0; - - /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold - cross-validation procedure where K is equal to CVFolds. - Default value is 10.*/ - /** @see setCVFolds */ - CV_WRAP virtual int getCVFolds() const = 0; - /** @copybrief getCVFolds @see getCVFolds */ - CV_WRAP virtual void setCVFolds(int val) = 0; - - /** If true then surrogate splits will be built. - These splits allow to work with missing data and compute variable importance correctly. - Default value is false. - @note currently it's not implemented.*/ - /** @see setUseSurrogates */ - CV_WRAP virtual bool getUseSurrogates() const = 0; - /** @copybrief getUseSurrogates @see getUseSurrogates */ - CV_WRAP virtual void setUseSurrogates(bool val) = 0; - - /** If true then a pruning will be harsher. - This will make a tree more compact and more resistant to the training data noise but a bit less - accurate. Default value is true.*/ - /** @see setUse1SERule */ - CV_WRAP virtual bool getUse1SERule() const = 0; - /** @copybrief getUse1SERule @see getUse1SERule */ - CV_WRAP virtual void setUse1SERule(bool val) = 0; - - /** If true then pruned branches are physically removed from the tree. - Otherwise they are retained and it is possible to get results from the original unpruned (or - pruned less aggressively) tree. Default value is true.*/ - /** @see setTruncatePrunedTree */ - CV_WRAP virtual bool getTruncatePrunedTree() const = 0; - /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */ - CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0; - - /** Termination criteria for regression trees. - If all absolute differences between an estimated value in a node and values of train samples - in this node are less than this parameter then the node will not be split further. Default - value is 0.01f*/ - /** @see setRegressionAccuracy */ - CV_WRAP virtual float getRegressionAccuracy() const = 0; - /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */ - CV_WRAP virtual void setRegressionAccuracy(float val) = 0; - - /** @brief The array of a priori class probabilities, sorted by the class label value. - - The parameter can be used to tune the decision tree preferences toward a certain class. For - example, if you want to detect some rare anomaly occurrence, the training base will likely - contain much more normal cases than anomalies, so a very good classification performance - will be achieved just by considering every case as normal. To avoid this, the priors can be - specified, where the anomaly probability is artificially increased (up to 0.5 or even - greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is - adjusted properly. - - You can also think about this parameter as weights of prediction categories which determine - relative weights that you give to misclassification. That is, if the weight of the first - category is 1 and the weight of the second category is 10, then each mistake in predicting - the second category is equivalent to making 10 mistakes in predicting the first category. - Default value is empty Mat.*/ - /** @see setPriors */ - CV_WRAP virtual cv::Mat getPriors() const = 0; - /** @copybrief getPriors @see getPriors */ - CV_WRAP virtual void setPriors(const cv::Mat &val) = 0; - - /** @brief The class represents a decision tree node. - */ - class CV_EXPORTS Node - { - public: - Node(); - double value; //!< Value at the node: a class label in case of classification or estimated - //!< function value in case of regression. - int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the - //!< node. It is used internally in classification trees and tree ensembles. - int parent; //!< Index of the parent node - int left; //!< Index of the left child node - int right; //!< Index of right child node - int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the - //!< case of missing values. - int split; //!< Index of the first split - }; - - /** @brief The class represents split in a decision tree. - */ - class CV_EXPORTS Split - { - public: - Split(); - int varIdx; //!< Index of variable on which the split is created. - bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right - //!< branches are exchanged in the rule expressions below). - float quality; //!< The split quality, a positive number. It is used to choose the best split. - int next; //!< Index of the next split in the list of splits for the node - float c; /**< The threshold value in case of split on an ordered variable. - The rule is: - @code{.none} - if var_value < c - then next_node <- left - else next_node <- right - @endcode */ - int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable. - The rule is: - @code{.none} - if bitset[var_value] == 1 - then next_node <- left - else next_node <- right - @endcode */ - }; - - /** @brief Returns indices of root nodes - */ - virtual const std::vector& getRoots() const = 0; - /** @brief Returns all the nodes - - all the node indices are indices in the returned vector - */ - virtual const std::vector& getNodes() const = 0; - /** @brief Returns all the splits - - all the split indices are indices in the returned vector - */ - virtual const std::vector& getSplits() const = 0; - /** @brief Returns all the bitsets for categorical splits - - Split::subsetOfs is an offset in the returned vector - */ - virtual const std::vector& getSubsets() const = 0; - - /** @brief Creates the empty model - - The static method creates empty decision tree with the specified parameters. It should be then - trained using train method (see StatModel::train). Alternatively, you can load the model from - file using Algorithm::load\(filename). - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized DTrees from a file - * - * Use DTree::save to serialize and store an DTree to disk. - * Load the DTree from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized DTree - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Random Trees Classifier * -\****************************************************************************************/ - -/** @brief The class implements the random forest predictor. - -@sa @ref ml_intro_rtrees - */ -class CV_EXPORTS_W RTrees : public DTrees -{ -public: - - /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance. - Default value is false.*/ - /** @see setCalculateVarImportance */ - CV_WRAP virtual bool getCalculateVarImportance() const = 0; - /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */ - CV_WRAP virtual void setCalculateVarImportance(bool val) = 0; - - /** The size of the randomly selected subset of features at each tree node and that are used - to find the best split(s). - If you set it to 0 then the size will be set to the square root of the total number of - features. Default value is 0.*/ - /** @see setActiveVarCount */ - CV_WRAP virtual int getActiveVarCount() const = 0; - /** @copybrief getActiveVarCount @see getActiveVarCount */ - CV_WRAP virtual void setActiveVarCount(int val) = 0; - - /** The termination criteria that specifies when the training algorithm stops. - Either when the specified number of trees is trained and added to the ensemble or when - sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the - better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes - pass a certain number of trees. Also to keep in mind, the number of tree increases the - prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS + - TermCriteria::EPS, 50, 0.1)*/ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; - - /** Returns the variable importance array. - The method returns the variable importance vector, computed at the training stage when - CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is - returned. - */ - CV_WRAP virtual Mat getVarImportance() const = 0; - - /** Returns the result of each individual tree in the forest. - In case the model is a regression problem, the method will return each of the trees' - results for each of the sample cases. If the model is a classifier, it will return - a Mat with samples + 1 rows, where the first row gives the class number and the - following rows return the votes each class had for each sample. - @param samples Array containing the samples for which votes will be calculated. - @param results Array where the result of the calculation will be written. - @param flags Flags for defining the type of RTrees. - */ - CV_WRAP virtual void getVotes(InputArray samples, OutputArray results, int flags) const = 0; - - /** Returns the OOB error value, computed at the training stage when calcOOBError is set to true. - * If this flag was set to false, 0 is returned. The OOB error is also scaled by sample weighting. - */ -#if CV_VERSION_MAJOR == 4 - CV_WRAP virtual double getOOBError() const { return 0; } -#else - /*CV_WRAP*/ virtual double getOOBError() const = 0; -#endif - - /** Creates the empty model. - Use StatModel::train to train the model, StatModel::train to create and train the model, - Algorithm::load to load the pre-trained model. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized RTree from a file - * - * Use RTree::save to serialize and store an RTree to disk. - * Load the RTree from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized RTree - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Boosted tree classifier * -\****************************************************************************************/ - -/** @brief Boosted tree classifier derived from DTrees - -@sa @ref ml_intro_boost - */ -class CV_EXPORTS_W Boost : public DTrees -{ -public: - /** Type of the boosting algorithm. - See Boost::Types. Default value is Boost::REAL. */ - /** @see setBoostType */ - CV_WRAP virtual int getBoostType() const = 0; - /** @copybrief getBoostType @see getBoostType */ - CV_WRAP virtual void setBoostType(int val) = 0; - - /** The number of weak classifiers. - Default value is 100. */ - /** @see setWeakCount */ - CV_WRAP virtual int getWeakCount() const = 0; - /** @copybrief getWeakCount @see getWeakCount */ - CV_WRAP virtual void setWeakCount(int val) = 0; - - /** A threshold between 0 and 1 used to save computational time. - Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next* - iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/ - /** @see setWeightTrimRate */ - CV_WRAP virtual double getWeightTrimRate() const = 0; - /** @copybrief getWeightTrimRate @see getWeightTrimRate */ - CV_WRAP virtual void setWeightTrimRate(double val) = 0; - - /** Boosting type. - Gentle AdaBoost and Real AdaBoost are often the preferable choices. */ - enum Types { - DISCRETE=0, //!< Discrete AdaBoost. - REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions - //!< and works well with categorical data. - LOGIT=2, //!< LogitBoost. It can produce good regression fits. - GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that - //!(filename) to load the pre-trained model. */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized Boost from a file - * - * Use Boost::save to serialize and store an RTree to disk. - * Load the Boost from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized Boost - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - -/****************************************************************************************\ -* Gradient Boosted Trees * -\****************************************************************************************/ - -/*class CV_EXPORTS_W GBTrees : public DTrees -{ -public: - struct CV_EXPORTS_W_MAP Params : public DTrees::Params - { - CV_PROP_RW int weakCount; - CV_PROP_RW int lossFunctionType; - CV_PROP_RW float subsamplePortion; - CV_PROP_RW float shrinkage; - - Params(); - Params( int lossFunctionType, int weakCount, float shrinkage, - float subsamplePortion, int maxDepth, bool useSurrogates ); - }; - - enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS}; - - virtual void setK(int k) = 0; - - virtual float predictSerial( InputArray samples, - OutputArray weakResponses, int flags) const = 0; - - static Ptr create(const Params& p); -};*/ - -/****************************************************************************************\ -* Artificial Neural Networks (ANN) * -\****************************************************************************************/ - -/////////////////////////////////// Multi-Layer Perceptrons ////////////////////////////// - -/** @brief Artificial Neural Networks - Multi-Layer Perceptrons. - -Unlike many other models in ML that are constructed and trained at once, in the MLP model these -steps are separated. First, a network with the specified topology is created using the non-default -constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is -trained using a set of input and output vectors. The training procedure can be repeated more than -once, that is, the weights can be adjusted based on the new training data. - -Additional flags for StatModel::train are available: ANN_MLP::TrainFlags. - -@sa @ref ml_intro_ann - */ -class CV_EXPORTS_W ANN_MLP : public StatModel -{ -public: - /** Available training methods */ - enum TrainingMethods { - BACKPROP=0, //!< The back-propagation algorithm. - RPROP = 1, //!< The RPROP algorithm. See @cite RPROP93 for details. - ANNEAL = 2 //!< The simulated annealing algorithm. See @cite Kirkpatrick83 for details. - }; - - /** Sets training method and common parameters. - @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods. - @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP and to initialT for ANN_MLP::ANNEAL. - @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP and to finalT for ANN_MLP::ANNEAL. - */ - CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0; - - /** Returns current training method */ - CV_WRAP virtual int getTrainMethod() const = 0; - - /** Initialize the activation function for each neuron. - Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM. - @param type The type of activation function. See ANN_MLP::ActivationFunctions. - @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0. - @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0. - */ - CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0; - - /** Integer vector specifying the number of neurons in each layer including the input and output layers. - The very first element specifies the number of elements in the input layer. - The last element - number of elements in the output layer. Default value is empty Mat. - @sa getLayerSizes */ - CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0; - - /** Integer vector specifying the number of neurons in each layer including the input and output layers. - The very first element specifies the number of elements in the input layer. - The last element - number of elements in the output layer. - @sa setLayerSizes */ - CV_WRAP virtual cv::Mat getLayerSizes() const = 0; - - /** Termination criteria of the training algorithm. - You can specify the maximum number of iterations (maxCount) and/or how much the error could - change between the iterations to make the algorithm continue (epsilon). Default value is - TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; - - /** BPROP: Strength of the weight gradient term. - The recommended value is about 0.1. Default value is 0.1.*/ - /** @see setBackpropWeightScale */ - CV_WRAP virtual double getBackpropWeightScale() const = 0; - /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */ - CV_WRAP virtual void setBackpropWeightScale(double val) = 0; - - /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations). - This parameter provides some inertia to smooth the random fluctuations of the weights. It can - vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough. - Default value is 0.1.*/ - /** @see setBackpropMomentumScale */ - CV_WRAP virtual double getBackpropMomentumScale() const = 0; - /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */ - CV_WRAP virtual void setBackpropMomentumScale(double val) = 0; - - /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$. - Default value is 0.1.*/ - /** @see setRpropDW0 */ - CV_WRAP virtual double getRpropDW0() const = 0; - /** @copybrief getRpropDW0 @see getRpropDW0 */ - CV_WRAP virtual void setRpropDW0(double val) = 0; - - /** RPROP: Increase factor \f$\eta^+\f$. - It must be \>1. Default value is 1.2.*/ - /** @see setRpropDWPlus */ - CV_WRAP virtual double getRpropDWPlus() const = 0; - /** @copybrief getRpropDWPlus @see getRpropDWPlus */ - CV_WRAP virtual void setRpropDWPlus(double val) = 0; - - /** RPROP: Decrease factor \f$\eta^-\f$. - It must be \<1. Default value is 0.5.*/ - /** @see setRpropDWMinus */ - CV_WRAP virtual double getRpropDWMinus() const = 0; - /** @copybrief getRpropDWMinus @see getRpropDWMinus */ - CV_WRAP virtual void setRpropDWMinus(double val) = 0; - - /** RPROP: Update-values lower limit \f$\Delta_{min}\f$. - It must be positive. Default value is FLT_EPSILON.*/ - /** @see setRpropDWMin */ - CV_WRAP virtual double getRpropDWMin() const = 0; - /** @copybrief getRpropDWMin @see getRpropDWMin */ - CV_WRAP virtual void setRpropDWMin(double val) = 0; - - /** RPROP: Update-values upper limit \f$\Delta_{max}\f$. - It must be \>1. Default value is 50.*/ - /** @see setRpropDWMax */ - CV_WRAP virtual double getRpropDWMax() const = 0; - /** @copybrief getRpropDWMax @see getRpropDWMax */ - CV_WRAP virtual void setRpropDWMax(double val) = 0; - - /** ANNEAL: Update initial temperature. - It must be \>=0. Default value is 10.*/ - /** @see setAnnealInitialT */ - CV_WRAP virtual double getAnnealInitialT() const = 0; - /** @copybrief getAnnealInitialT @see getAnnealInitialT */ - CV_WRAP virtual void setAnnealInitialT(double val) = 0; - - /** ANNEAL: Update final temperature. - It must be \>=0 and less than initialT. Default value is 0.1.*/ - /** @see setAnnealFinalT */ - CV_WRAP virtual double getAnnealFinalT() const = 0; - /** @copybrief getAnnealFinalT @see getAnnealFinalT */ - CV_WRAP virtual void setAnnealFinalT(double val) = 0; - - /** ANNEAL: Update cooling ratio. - It must be \>0 and less than 1. Default value is 0.95.*/ - /** @see setAnnealCoolingRatio */ - CV_WRAP virtual double getAnnealCoolingRatio() const = 0; - /** @copybrief getAnnealCoolingRatio @see getAnnealCoolingRatio */ - CV_WRAP virtual void setAnnealCoolingRatio(double val) = 0; - - /** ANNEAL: Update iteration per step. - It must be \>0 . Default value is 10.*/ - /** @see setAnnealItePerStep */ - CV_WRAP virtual int getAnnealItePerStep() const = 0; - /** @copybrief getAnnealItePerStep @see getAnnealItePerStep */ - CV_WRAP virtual void setAnnealItePerStep(int val) = 0; - - /** @brief Set/initialize anneal RNG */ - virtual void setAnnealEnergyRNG(const RNG& rng) = 0; - - /** possible activation functions */ - enum ActivationFunctions { - /** Identity function: \f$f(x)=x\f$ */ - IDENTITY = 0, - /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x})\f$ - @note - If you are using the default sigmoid activation function with the default parameter values - fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output - will range from [-1.7159, 1.7159], instead of [0,1].*/ - SIGMOID_SYM = 1, - /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */ - GAUSSIAN = 2, - /** ReLU function: \f$f(x)=max(0,x)\f$ */ - RELU = 3, - /** Leaky ReLU function: for x>0 \f$f(x)=x \f$ and x<=0 \f$f(x)=\alpha x \f$*/ - LEAKYRELU= 4 - }; - - /** Train options */ - enum TrainFlags { - /** Update the network weights, rather than compute them from scratch. In the latter case - the weights are initialized using the Nguyen-Widrow algorithm. */ - UPDATE_WEIGHTS = 1, - /** Do not normalize the input vectors. If this flag is not set, the training algorithm - normalizes each input feature independently, shifting its mean value to 0 and making the - standard deviation equal to 1. If the network is assumed to be updated frequently, the new - training data could be much different from original one. In this case, you should take care - of proper normalization. */ - NO_INPUT_SCALE = 2, - /** Do not normalize the output vectors. If the flag is not set, the training algorithm - normalizes each output feature independently, by transforming it to the certain range - depending on the used activation function. */ - NO_OUTPUT_SCALE = 4 - }; - - CV_WRAP virtual Mat getWeights(int layerIdx) const = 0; - - /** @brief Creates empty model - - Use StatModel::train to train the model, Algorithm::load\(filename) to load the pre-trained model. - Note that the train method has optional flags: ANN_MLP::TrainFlags. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized ANN from a file - * - * Use ANN::save to serialize and store an ANN to disk. - * Load the ANN from this file again, by calling this function with the path to the file. - * - * @param filepath path to serialized ANN - */ - CV_WRAP static Ptr load(const String& filepath); - -}; - -#ifndef DISABLE_OPENCV_3_COMPATIBILITY -typedef ANN_MLP ANN_MLP_ANNEAL; -#endif - -/****************************************************************************************\ -* Logistic Regression * -\****************************************************************************************/ - -/** @brief Implements Logistic Regression classifier. - -@sa @ref ml_intro_lr - */ -class CV_EXPORTS_W LogisticRegression : public StatModel -{ -public: - - /** Learning rate. */ - /** @see setLearningRate */ - CV_WRAP virtual double getLearningRate() const = 0; - /** @copybrief getLearningRate @see getLearningRate */ - CV_WRAP virtual void setLearningRate(double val) = 0; - - /** Number of iterations. */ - /** @see setIterations */ - CV_WRAP virtual int getIterations() const = 0; - /** @copybrief getIterations @see getIterations */ - CV_WRAP virtual void setIterations(int val) = 0; - - /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */ - /** @see setRegularization */ - CV_WRAP virtual int getRegularization() const = 0; - /** @copybrief getRegularization @see getRegularization */ - CV_WRAP virtual void setRegularization(int val) = 0; - - /** Kind of training method used. See LogisticRegression::Methods. */ - /** @see setTrainMethod */ - CV_WRAP virtual int getTrainMethod() const = 0; - /** @copybrief getTrainMethod @see getTrainMethod */ - CV_WRAP virtual void setTrainMethod(int val) = 0; - - /** Specifies the number of training samples taken in each step of Mini-Batch Gradient - Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It - has to take values less than the total number of training samples. */ - /** @see setMiniBatchSize */ - CV_WRAP virtual int getMiniBatchSize() const = 0; - /** @copybrief getMiniBatchSize @see getMiniBatchSize */ - CV_WRAP virtual void setMiniBatchSize(int val) = 0; - - /** Termination criteria of the algorithm. */ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; - - //! Regularization kinds - enum RegKinds { - REG_DISABLE = -1, //!< Regularization disabled - REG_L1 = 0, //!< %L1 norm - REG_L2 = 1 //!< %L2 norm - }; - - //! Training methods - enum Methods { - BATCH = 0, - MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method. - }; - - /** @brief Predicts responses for input samples and returns a float type. - - @param samples The input data for the prediction algorithm. Matrix [m x n], where each row - contains variables (features) of one object being classified. Should have data type CV_32F. - @param results Predicted labels as a column matrix of type CV_32S. - @param flags Not used. - */ - CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; - - /** @brief This function returns the trained parameters arranged across rows. - - For a two class classification problem, it returns a row matrix. It returns learnt parameters of - the Logistic Regression as a matrix of type CV_32F. - */ - CV_WRAP virtual Mat get_learnt_thetas() const = 0; - - /** @brief Creates empty model. - - Creates Logistic Regression model with parameters given. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized LogisticRegression from a file - * - * Use LogisticRegression::save to serialize and store an LogisticRegression to disk. - * Load the LogisticRegression from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized LogisticRegression - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); -}; - - -/****************************************************************************************\ -* Stochastic Gradient Descent SVM Classifier * -\****************************************************************************************/ - -/*! -@brief Stochastic Gradient Descent SVM classifier - -SVMSGD provides a fast and easy-to-use implementation of the SVM classifier using the Stochastic Gradient Descent approach, -as presented in @cite bottou2010large. - -The classifier has following parameters: -- model type, -- margin type, -- margin regularization (\f$\lambda\f$), -- initial step size (\f$\gamma_0\f$), -- step decreasing power (\f$c\f$), -- and termination criteria. - -The model type may have one of the following values: \ref SGD and \ref ASGD. - -- \ref SGD is the classic version of SVMSGD classifier: every next step is calculated by the formula - \f[w_{t+1} = w_t - \gamma(t) \frac{dQ_i}{dw} |_{w = w_t}\f] - where - - \f$w_t\f$ is the weights vector for decision function at step \f$t\f$, - - \f$\gamma(t)\f$ is the step size of model parameters at the iteration \f$t\f$, it is decreased on each step by the formula - \f$\gamma(t) = \gamma_0 (1 + \lambda \gamma_0 t) ^ {-c}\f$ - - \f$Q_i\f$ is the target functional from SVM task for sample with number \f$i\f$, this sample is chosen stochastically on each step of the algorithm. - -- \ref ASGD is Average Stochastic Gradient Descent SVM Classifier. ASGD classifier averages weights vector on each step of algorithm by the formula -\f$\widehat{w}_{t+1} = \frac{t}{1+t}\widehat{w}_{t} + \frac{1}{1+t}w_{t+1}\f$ - -The recommended model type is ASGD (following @cite bottou2010large). - -The margin type may have one of the following values: \ref SOFT_MARGIN or \ref HARD_MARGIN. - -- You should use \ref HARD_MARGIN type, if you have linearly separable sets. -- You should use \ref SOFT_MARGIN type, if you have non-linearly separable sets or sets with outliers. -- In the general case (if you know nothing about linear separability of your sets), use SOFT_MARGIN. - -The other parameters may be described as follows: -- Margin regularization parameter is responsible for weights decreasing at each step and for the strength of restrictions on outliers - (the less the parameter, the less probability that an outlier will be ignored). - Recommended value for SGD model is 0.0001, for ASGD model is 0.00001. - -- Initial step size parameter is the initial value for the step size \f$\gamma(t)\f$. - You will have to find the best initial step for your problem. - -- Step decreasing power is the power parameter for \f$\gamma(t)\f$ decreasing by the formula, mentioned above. - Recommended value for SGD model is 1, for ASGD model is 0.75. - -- Termination criteria can be TermCriteria::COUNT, TermCriteria::EPS or TermCriteria::COUNT + TermCriteria::EPS. - You will have to find the best termination criteria for your problem. - -Note that the parameters margin regularization, initial step size, and step decreasing power should be positive. - -To use SVMSGD algorithm do as follows: - -- first, create the SVMSGD object. The algorithm will set optimal parameters by default, but you can set your own parameters via functions setSvmsgdType(), - setMarginType(), setMarginRegularization(), setInitialStepSize(), and setStepDecreasingPower(). - -- then the SVM model can be trained using the train features and the correspondent labels by the method train(). - -- after that, the label of a new feature vector can be predicted using the method predict(). - -@code -// Create empty object -cv::Ptr svmsgd = SVMSGD::create(); - -// Train the Stochastic Gradient Descent SVM -svmsgd->train(trainData); - -// Predict labels for the new samples -svmsgd->predict(samples, responses); -@endcode - -*/ - -class CV_EXPORTS_W SVMSGD : public cv::ml::StatModel -{ -public: - - /** SVMSGD type. - ASGD is often the preferable choice. */ - enum SvmsgdType - { - SGD, //!< Stochastic Gradient Descent - ASGD //!< Average Stochastic Gradient Descent - }; - - /** Margin type.*/ - enum MarginType - { - SOFT_MARGIN, //!< General case, suits to the case of non-linearly separable sets, allows outliers. - HARD_MARGIN //!< More accurate for the case of linearly separable sets. - }; - - /** - * @return the weights of the trained model (decision function f(x) = weights * x + shift). - */ - CV_WRAP virtual Mat getWeights() = 0; - - /** - * @return the shift of the trained model (decision function f(x) = weights * x + shift). - */ - CV_WRAP virtual float getShift() = 0; - - /** @brief Creates empty model. - * Use StatModel::train to train the model. Since %SVMSGD has several parameters, you may want to - * find the best parameters for your problem or use setOptimalParameters() to set some default parameters. - */ - CV_WRAP static Ptr create(); - - /** @brief Loads and creates a serialized SVMSGD from a file - * - * Use SVMSGD::save to serialize and store an SVMSGD to disk. - * Load the SVMSGD from this file again, by calling this function with the path to the file. - * Optionally specify the node for the file containing the classifier - * - * @param filepath path to serialized SVMSGD - * @param nodeName name of node containing the classifier - */ - CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); - - /** @brief Function sets optimal parameters values for chosen SVM SGD model. - * @param svmsgdType is the type of SVMSGD classifier. - * @param marginType is the type of margin constraint. - */ - CV_WRAP virtual void setOptimalParameters(int svmsgdType = SVMSGD::ASGD, int marginType = SVMSGD::SOFT_MARGIN) = 0; - - /** @brief %Algorithm type, one of SVMSGD::SvmsgdType. */ - /** @see setSvmsgdType */ - CV_WRAP virtual int getSvmsgdType() const = 0; - /** @copybrief getSvmsgdType @see getSvmsgdType */ - CV_WRAP virtual void setSvmsgdType(int svmsgdType) = 0; - - /** @brief %Margin type, one of SVMSGD::MarginType. */ - /** @see setMarginType */ - CV_WRAP virtual int getMarginType() const = 0; - /** @copybrief getMarginType @see getMarginType */ - CV_WRAP virtual void setMarginType(int marginType) = 0; - - /** @brief Parameter marginRegularization of a %SVMSGD optimization problem. */ - /** @see setMarginRegularization */ - CV_WRAP virtual float getMarginRegularization() const = 0; - /** @copybrief getMarginRegularization @see getMarginRegularization */ - CV_WRAP virtual void setMarginRegularization(float marginRegularization) = 0; - - /** @brief Parameter initialStepSize of a %SVMSGD optimization problem. */ - /** @see setInitialStepSize */ - CV_WRAP virtual float getInitialStepSize() const = 0; - /** @copybrief getInitialStepSize @see getInitialStepSize */ - CV_WRAP virtual void setInitialStepSize(float InitialStepSize) = 0; - - /** @brief Parameter stepDecreasingPower of a %SVMSGD optimization problem. */ - /** @see setStepDecreasingPower */ - CV_WRAP virtual float getStepDecreasingPower() const = 0; - /** @copybrief getStepDecreasingPower @see getStepDecreasingPower */ - CV_WRAP virtual void setStepDecreasingPower(float stepDecreasingPower) = 0; - - /** @brief Termination criteria of the training algorithm. - You can specify the maximum number of iterations (maxCount) and/or how much the error could - change between the iterations to make the algorithm continue (epsilon).*/ - /** @see setTermCriteria */ - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - /** @copybrief getTermCriteria @see getTermCriteria */ - CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; -}; - - -/****************************************************************************************\ -* Auxiliary functions declarations * -\****************************************************************************************/ - -/** @brief Generates _sample_ from multivariate normal distribution - -@param mean an average row vector -@param cov symmetric covariation matrix -@param nsamples returned samples count -@param samples returned samples array -*/ -CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples); - -/** @brief Creates test set */ -CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses, - OutputArray samples, OutputArray responses); - - -/****************************************************************************************\ -* Simulated annealing solver * -\****************************************************************************************/ - -#ifdef CV_DOXYGEN -/** @brief This class declares example interface for system state used in simulated annealing optimization algorithm. - -@note This class is not defined in C++ code and can't be use directly - you need your own implementation with the same methods. -*/ -struct SimulatedAnnealingSolverSystem -{ - /** Give energy value for a state of system.*/ - double energy() const; - /** Function which change the state of system (random perturbation).*/ - void changeState(); - /** Function to reverse to the previous state. Can be called once only after changeState(). */ - void reverseState(); -}; -#endif // CV_DOXYGEN - -/** @brief The class implements simulated annealing for optimization. - -@cite Kirkpatrick83 for details - -@param solverSystem optimization system (see SimulatedAnnealingSolverSystem) -@param initialTemperature initial temperature -@param finalTemperature final temperature -@param coolingRatio temperature step multiplies -@param iterationsPerStep number of iterations per temperature changing step -@param lastTemperature optional output for last used temperature -@param rngEnergy specify custom random numbers generator (cv::theRNG() by default) -*/ -template -int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, - double initialTemperature, double finalTemperature, double coolingRatio, - size_t iterationsPerStep, - CV_OUT double* lastTemperature = NULL, - cv::RNG& rngEnergy = cv::theRNG() -); - -//! @} ml - -} -} - -#include - -#endif // __cplusplus -#endif // OPENCV_ML_HPP - -/* End of file. */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Copyright (C) 2014, Itseez Inc, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_ML_HPP +#define OPENCV_ML_HPP + +#ifdef __cplusplus +# include "opencv2/core.hpp" +#endif + +#ifdef __cplusplus + +#include +#include +#include + +/** + @defgroup ml Machine Learning + + The Machine Learning Library (MLL) is a set of classes and functions for statistical + classification, regression, and clustering of data. + + Most of the classification and regression algorithms are implemented as C++ classes. As the + algorithms have different sets of features (like an ability to handle missing measurements or + categorical input variables), there is a little common ground between the classes. This common + ground is defined by the class cv::ml::StatModel that all the other ML classes are derived from. + + See detailed overview here: @ref ml_intro. + */ + +namespace cv +{ + +namespace ml +{ + +//! @addtogroup ml +//! @{ + +/** @brief Variable types */ +enum VariableTypes +{ + VAR_NUMERICAL =0, //!< same as VAR_ORDERED + VAR_ORDERED =0, //!< ordered variables + VAR_CATEGORICAL =1 //!< categorical variables +}; + +/** @brief %Error types */ +enum ErrorTypes +{ + TEST_ERROR = 0, + TRAIN_ERROR = 1 +}; + +/** @brief Sample types */ +enum SampleTypes +{ + ROW_SAMPLE = 0, //!< each training sample is a row of samples + COL_SAMPLE = 1 //!< each training sample occupies a column of samples +}; + +/** @brief The structure represents the logarithmic grid range of statmodel parameters. + +It is used for optimizing statmodel accuracy by varying model parameters, the accuracy estimate +being computed by cross-validation. + */ +class CV_EXPORTS_W ParamGrid +{ +public: + /** @brief Default constructor */ + ParamGrid(); + /** @brief Constructor with parameters */ + ParamGrid(double _minVal, double _maxVal, double _logStep); + + CV_PROP_RW double minVal; //!< Minimum value of the statmodel parameter. Default value is 0. + CV_PROP_RW double maxVal; //!< Maximum value of the statmodel parameter. Default value is 0. + /** @brief Logarithmic step for iterating the statmodel parameter. + + The grid determines the following iteration sequence of the statmodel parameter values: + \f[(minVal, minVal*step, minVal*{step}^2, \dots, minVal*{logStep}^n),\f] + where \f$n\f$ is the maximal index satisfying + \f[\texttt{minVal} * \texttt{logStep} ^n < \texttt{maxVal}\f] + The grid is logarithmic, so logStep must always be greater than 1. Default value is 1. + */ + CV_PROP_RW double logStep; + + /** @brief Creates a ParamGrid Ptr that can be given to the %SVM::trainAuto method + + @param minVal minimum value of the parameter grid + @param maxVal maximum value of the parameter grid + @param logstep Logarithmic step for iterating the statmodel parameter + */ + CV_WRAP static Ptr create(double minVal=0., double maxVal=0., double logstep=1.); +}; + +/** @brief Class encapsulating training data. + +Please note that the class only specifies the interface of training data, but not implementation. +All the statistical model classes in _ml_ module accepts Ptr\ as parameter. In other +words, you can create your own class derived from TrainData and pass smart pointer to the instance +of this class into StatModel::train. + +@sa @ref ml_intro_data + */ +class CV_EXPORTS_W TrainData +{ +public: + static inline float missingValue() { return FLT_MAX; } + virtual ~TrainData(); + + CV_WRAP virtual int getLayout() const = 0; + CV_WRAP virtual int getNTrainSamples() const = 0; + CV_WRAP virtual int getNTestSamples() const = 0; + CV_WRAP virtual int getNSamples() const = 0; + CV_WRAP virtual int getNVars() const = 0; + CV_WRAP virtual int getNAllVars() const = 0; + + CV_WRAP virtual void getSample(InputArray varIdx, int sidx, float* buf) const = 0; + CV_WRAP virtual Mat getSamples() const = 0; + CV_WRAP virtual Mat getMissing() const = 0; + + /** @brief Returns matrix of train samples + + @param layout The requested layout. If it's different from the initial one, the matrix is + transposed. See ml::SampleTypes. + @param compressSamples if true, the function returns only the training samples (specified by + sampleIdx) + @param compressVars if true, the function returns the shorter training samples, containing only + the active variables. + + In current implementation the function tries to avoid physical data copying and returns the + matrix stored inside TrainData (unless the transposition or compression is needed). + */ + CV_WRAP virtual Mat getTrainSamples(int layout=ROW_SAMPLE, + bool compressSamples=true, + bool compressVars=true) const = 0; + + /** @brief Returns the vector of responses + + The function returns ordered or the original categorical responses. Usually it's used in + regression algorithms. + */ + CV_WRAP virtual Mat getTrainResponses() const = 0; + + /** @brief Returns the vector of normalized categorical responses + + The function returns vector of responses. Each response is integer from `0` to `-1`. The actual label value can be retrieved then from the class label vector, see + TrainData::getClassLabels. + */ + CV_WRAP virtual Mat getTrainNormCatResponses() const = 0; + CV_WRAP virtual Mat getTestResponses() const = 0; + CV_WRAP virtual Mat getTestNormCatResponses() const = 0; + CV_WRAP virtual Mat getResponses() const = 0; + CV_WRAP virtual Mat getNormCatResponses() const = 0; + CV_WRAP virtual Mat getSampleWeights() const = 0; + CV_WRAP virtual Mat getTrainSampleWeights() const = 0; + CV_WRAP virtual Mat getTestSampleWeights() const = 0; + CV_WRAP virtual Mat getVarIdx() const = 0; + CV_WRAP virtual Mat getVarType() const = 0; + CV_WRAP virtual Mat getVarSymbolFlags() const = 0; + CV_WRAP virtual int getResponseType() const = 0; + CV_WRAP virtual Mat getTrainSampleIdx() const = 0; + CV_WRAP virtual Mat getTestSampleIdx() const = 0; + CV_WRAP virtual void getValues(int vi, InputArray sidx, float* values) const = 0; + virtual void getNormCatValues(int vi, InputArray sidx, int* values) const = 0; + CV_WRAP virtual Mat getDefaultSubstValues() const = 0; + + CV_WRAP virtual int getCatCount(int vi) const = 0; + + /** @brief Returns the vector of class labels + + The function returns vector of unique labels occurred in the responses. + */ + CV_WRAP virtual Mat getClassLabels() const = 0; + + CV_WRAP virtual Mat getCatOfs() const = 0; + CV_WRAP virtual Mat getCatMap() const = 0; + + /** @brief Splits the training data into the training and test parts + @sa TrainData::setTrainTestSplitRatio + */ + CV_WRAP virtual void setTrainTestSplit(int count, bool shuffle=true) = 0; + + /** @brief Splits the training data into the training and test parts + + The function selects a subset of specified relative size and then returns it as the training + set. If the function is not called, all the data is used for training. Please, note that for + each of TrainData::getTrain\* there is corresponding TrainData::getTest\*, so that the test + subset can be retrieved and processed as well. + @sa TrainData::setTrainTestSplit + */ + CV_WRAP virtual void setTrainTestSplitRatio(double ratio, bool shuffle=true) = 0; + CV_WRAP virtual void shuffleTrainTest() = 0; + + /** @brief Returns matrix of test samples */ + CV_WRAP virtual Mat getTestSamples() const = 0; + + /** @brief Returns vector of symbolic names captured in loadFromCSV() */ + CV_WRAP virtual void getNames(std::vector& names) const = 0; + + /** @brief Extract from 1D vector elements specified by passed indexes. + @param vec input vector (supported types: CV_32S, CV_32F, CV_64F) + @param idx 1D index vector + */ + static CV_WRAP Mat getSubVector(const Mat& vec, const Mat& idx); + + /** @brief Extract from matrix rows/cols specified by passed indexes. + @param matrix input matrix (supported types: CV_32S, CV_32F, CV_64F) + @param idx 1D index vector + @param layout specifies to extract rows (cv::ml::ROW_SAMPLES) or to extract columns (cv::ml::COL_SAMPLES) + */ + static CV_WRAP Mat getSubMatrix(const Mat& matrix, const Mat& idx, int layout); + + /** @brief Reads the dataset from a .csv file and returns the ready-to-use training data. + + @param filename The input file name + @param headerLineCount The number of lines in the beginning to skip; besides the header, the + function also skips empty lines and lines staring with `#` + @param responseStartIdx Index of the first output variable. If -1, the function considers the + last variable as the response + @param responseEndIdx Index of the last output variable + 1. If -1, then there is single + response variable at responseStartIdx. + @param varTypeSpec The optional text string that specifies the variables' types. It has the + format `ord[n1-n2,n3,n4-n5,...]cat[n6,n7-n8,...]`. That is, variables from `n1 to n2` + (inclusive range), `n3`, `n4 to n5` ... are considered ordered and `n6`, `n7 to n8` ... are + considered as categorical. The range `[n1..n2] + [n3] + [n4..n5] + ... + [n6] + [n7..n8]` + should cover all the variables. If varTypeSpec is not specified, then algorithm uses the + following rules: + - all input variables are considered ordered by default. If some column contains has non- + numerical values, e.g. 'apple', 'pear', 'apple', 'apple', 'mango', the corresponding + variable is considered categorical. + - if there are several output variables, they are all considered as ordered. Error is + reported when non-numerical values are used. + - if there is a single output variable, then if its values are non-numerical or are all + integers, then it's considered categorical. Otherwise, it's considered ordered. + @param delimiter The character used to separate values in each line. + @param missch The character used to specify missing measurements. It should not be a digit. + Although it's a non-numerical value, it surely does not affect the decision of whether the + variable ordered or categorical. + @note If the dataset only contains input variables and no responses, use responseStartIdx = -2 + and responseEndIdx = 0. The output variables vector will just contain zeros. + */ + static Ptr loadFromCSV(const String& filename, + int headerLineCount, + int responseStartIdx=-1, + int responseEndIdx=-1, + const String& varTypeSpec=String(), + char delimiter=',', + char missch='?'); + + /** @brief Creates training data from in-memory arrays. + + @param samples matrix of samples. It should have CV_32F type. + @param layout see ml::SampleTypes. + @param responses matrix of responses. If the responses are scalar, they should be stored as a + single row or as a single column. The matrix should have type CV_32F or CV_32S (in the + former case the responses are considered as ordered by default; in the latter case - as + categorical) + @param varIdx vector specifying which variables to use for training. It can be an integer vector + (CV_32S) containing 0-based variable indices or byte vector (CV_8U) containing a mask of + active variables. + @param sampleIdx vector specifying which samples to use for training. It can be an integer + vector (CV_32S) containing 0-based sample indices or byte vector (CV_8U) containing a mask + of training samples. + @param sampleWeights optional vector with weights for each sample. It should have CV_32F type. + @param varType optional vector of type CV_8U and size ` + + `, containing types of each input and output variable. See + ml::VariableTypes. + */ + CV_WRAP static Ptr create(InputArray samples, int layout, InputArray responses, + InputArray varIdx=noArray(), InputArray sampleIdx=noArray(), + InputArray sampleWeights=noArray(), InputArray varType=noArray()); +}; + +/** @brief Base class for statistical models in OpenCV ML. + */ +class CV_EXPORTS_W StatModel : public Algorithm +{ +public: + /** Predict options */ + enum Flags { + UPDATE_MODEL = 1, + RAW_OUTPUT=1, //!< makes the method return the raw results (the sum), not the class label + COMPRESSED_INPUT=2, + PREPROCESSED_INPUT=4 + }; + + /** @brief Returns the number of variables in training samples */ + CV_WRAP virtual int getVarCount() const = 0; + + CV_WRAP virtual bool empty() const CV_OVERRIDE; + + /** @brief Returns true if the model is trained */ + CV_WRAP virtual bool isTrained() const = 0; + /** @brief Returns true if the model is classifier */ + CV_WRAP virtual bool isClassifier() const = 0; + + /** @brief Trains the statistical model + + @param trainData training data that can be loaded from file using TrainData::loadFromCSV or + created with TrainData::create. + @param flags optional flags, depending on the model. Some of the models can be updated with the + new training samples, not completely overwritten (such as NormalBayesClassifier or ANN_MLP). + */ + CV_WRAP virtual bool train( const Ptr& trainData, int flags=0 ); + + /** @brief Trains the statistical model + + @param samples training samples + @param layout See ml::SampleTypes. + @param responses vector of responses associated with the training samples. + */ + CV_WRAP virtual bool train( InputArray samples, int layout, InputArray responses ); + + /** @brief Computes error on the training or test dataset + + @param data the training data + @param test if true, the error is computed over the test subset of the data, otherwise it's + computed over the training subset of the data. Please note that if you loaded a completely + different dataset to evaluate already trained classifier, you will probably want not to set + the test subset at all with TrainData::setTrainTestSplitRatio and specify test=false, so + that the error is computed for the whole new set. Yes, this sounds a bit confusing. + @param resp the optional output responses. + + The method uses StatModel::predict to compute the error. For regression models the error is + computed as RMS, for classifiers - as a percent of missclassified samples (0%-100%). + */ + CV_WRAP virtual float calcError( const Ptr& data, bool test, OutputArray resp ) const; + + /** @brief Predicts response(s) for the provided sample(s) + + @param samples The input samples, floating-point matrix + @param results The optional output matrix of results. + @param flags The optional flags, model-dependent. See cv::ml::StatModel::Flags. + */ + CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const = 0; + + /** @brief Create and train model with default parameters + + The class must implement static `create()` method with no parameters or with all default parameter values + */ + template static Ptr<_Tp> train(const Ptr& data, int flags=0) + { + Ptr<_Tp> model = _Tp::create(); + return !model.empty() && model->train(data, flags) ? model : Ptr<_Tp>(); + } +}; + +/****************************************************************************************\ +* Normal Bayes Classifier * +\****************************************************************************************/ + +/** @brief Bayes classifier for normally distributed data. + +@sa @ref ml_intro_bayes + */ +class CV_EXPORTS_W NormalBayesClassifier : public StatModel +{ +public: + /** @brief Predicts the response for sample(s). + + The method estimates the most probable classes for input vectors. Input vectors (one or more) + are stored as rows of the matrix inputs. In case of multiple input vectors, there should be one + output vector outputs. The predicted class for a single input vector is returned by the method. + The vector outputProbs contains the output probabilities corresponding to each element of + result. + */ + CV_WRAP virtual float predictProb( InputArray inputs, OutputArray outputs, + OutputArray outputProbs, int flags=0 ) const = 0; + + /** Creates empty model + Use StatModel::train to train the model after creation. */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized NormalBayesClassifier from a file + * + * Use NormalBayesClassifier::save to serialize and store an NormalBayesClassifier to disk. + * Load the NormalBayesClassifier from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized NormalBayesClassifier + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* K-Nearest Neighbour Classifier * +\****************************************************************************************/ + +/** @brief The class implements K-Nearest Neighbors model + +@sa @ref ml_intro_knn + */ +class CV_EXPORTS_W KNearest : public StatModel +{ +public: + + /** Default number of neighbors to use in predict method. */ + /** @see setDefaultK */ + CV_WRAP virtual int getDefaultK() const = 0; + /** @copybrief getDefaultK @see getDefaultK */ + CV_WRAP virtual void setDefaultK(int val) = 0; + + /** Whether classification or regression model should be trained. */ + /** @see setIsClassifier */ + CV_WRAP virtual bool getIsClassifier() const = 0; + /** @copybrief getIsClassifier @see getIsClassifier */ + CV_WRAP virtual void setIsClassifier(bool val) = 0; + + /** Parameter for KDTree implementation. */ + /** @see setEmax */ + CV_WRAP virtual int getEmax() const = 0; + /** @copybrief getEmax @see getEmax */ + CV_WRAP virtual void setEmax(int val) = 0; + + /** %Algorithm type, one of KNearest::Types. */ + /** @see setAlgorithmType */ + CV_WRAP virtual int getAlgorithmType() const = 0; + /** @copybrief getAlgorithmType @see getAlgorithmType */ + CV_WRAP virtual void setAlgorithmType(int val) = 0; + + /** @brief Finds the neighbors and predicts responses for input vectors. + + @param samples Input samples stored by rows. It is a single-precision floating-point matrix of + ` * k` size. + @param k Number of used nearest neighbors. Should be greater than 1. + @param results Vector with results of prediction (regression or classification) for each input + sample. It is a single-precision floating-point vector with `` elements. + @param neighborResponses Optional output values for corresponding neighbors. It is a single- + precision floating-point matrix of ` * k` size. + @param dist Optional output distances from the input vectors to the corresponding neighbors. It + is a single-precision floating-point matrix of ` * k` size. + + For each input vector (a row of the matrix samples), the method finds the k nearest neighbors. + In case of regression, the predicted result is a mean value of the particular vector's neighbor + responses. In case of classification, the class is determined by voting. + + For each input vector, the neighbors are sorted by their distances to the vector. + + In case of C++ interface you can use output pointers to empty matrices and the function will + allocate memory itself. + + If only a single input vector is passed, all output matrices are optional and the predicted + value is returned by the method. + + The function is parallelized with the TBB library. + */ + CV_WRAP virtual float findNearest( InputArray samples, int k, + OutputArray results, + OutputArray neighborResponses=noArray(), + OutputArray dist=noArray() ) const = 0; + + /** @brief Implementations of KNearest algorithm + */ + enum Types + { + BRUTE_FORCE=1, + KDTREE=2 + }; + + /** @brief Creates the empty model + + The static method creates empty %KNearest classifier. It should be then trained using StatModel::train method. + */ + CV_WRAP static Ptr create(); + /** @brief Loads and creates a serialized knearest from a file + * + * Use KNearest::save to serialize and store an KNearest to disk. + * Load the KNearest from this file again, by calling this function with the path to the file. + * + * @param filepath path to serialized KNearest + */ + CV_WRAP static Ptr load(const String& filepath); +}; + +/****************************************************************************************\ +* Support Vector Machines * +\****************************************************************************************/ + +/** @brief Support Vector Machines. + +@sa @ref ml_intro_svm + */ +class CV_EXPORTS_W SVM : public StatModel +{ +public: + + class CV_EXPORTS Kernel : public Algorithm + { + public: + virtual int getType() const = 0; + virtual void calc( int vcount, int n, const float* vecs, const float* another, float* results ) = 0; + }; + + /** Type of a %SVM formulation. + See SVM::Types. Default value is SVM::C_SVC. */ + /** @see setType */ + CV_WRAP virtual int getType() const = 0; + /** @copybrief getType @see getType */ + CV_WRAP virtual void setType(int val) = 0; + + /** Parameter \f$\gamma\f$ of a kernel function. + For SVM::POLY, SVM::RBF, SVM::SIGMOID or SVM::CHI2. Default value is 1. */ + /** @see setGamma */ + CV_WRAP virtual double getGamma() const = 0; + /** @copybrief getGamma @see getGamma */ + CV_WRAP virtual void setGamma(double val) = 0; + + /** Parameter _coef0_ of a kernel function. + For SVM::POLY or SVM::SIGMOID. Default value is 0.*/ + /** @see setCoef0 */ + CV_WRAP virtual double getCoef0() const = 0; + /** @copybrief getCoef0 @see getCoef0 */ + CV_WRAP virtual void setCoef0(double val) = 0; + + /** Parameter _degree_ of a kernel function. + For SVM::POLY. Default value is 0. */ + /** @see setDegree */ + CV_WRAP virtual double getDegree() const = 0; + /** @copybrief getDegree @see getDegree */ + CV_WRAP virtual void setDegree(double val) = 0; + + /** Parameter _C_ of a %SVM optimization problem. + For SVM::C_SVC, SVM::EPS_SVR or SVM::NU_SVR. Default value is 0. */ + /** @see setC */ + CV_WRAP virtual double getC() const = 0; + /** @copybrief getC @see getC */ + CV_WRAP virtual void setC(double val) = 0; + + /** Parameter \f$\nu\f$ of a %SVM optimization problem. + For SVM::NU_SVC, SVM::ONE_CLASS or SVM::NU_SVR. Default value is 0. */ + /** @see setNu */ + CV_WRAP virtual double getNu() const = 0; + /** @copybrief getNu @see getNu */ + CV_WRAP virtual void setNu(double val) = 0; + + /** Parameter \f$\epsilon\f$ of a %SVM optimization problem. + For SVM::EPS_SVR. Default value is 0. */ + /** @see setP */ + CV_WRAP virtual double getP() const = 0; + /** @copybrief getP @see getP */ + CV_WRAP virtual void setP(double val) = 0; + + /** Optional weights in the SVM::C_SVC problem, assigned to particular classes. + They are multiplied by _C_ so the parameter _C_ of class _i_ becomes `classWeights(i) * C`. Thus + these weights affect the misclassification penalty for different classes. The larger weight, + the larger penalty on misclassification of data from the corresponding class. Default value is + empty Mat. */ + /** @see setClassWeights */ + CV_WRAP virtual cv::Mat getClassWeights() const = 0; + /** @copybrief getClassWeights @see getClassWeights */ + CV_WRAP virtual void setClassWeights(const cv::Mat &val) = 0; + + /** Termination criteria of the iterative %SVM training procedure which solves a partial + case of constrained quadratic optimization problem. + You can specify tolerance and/or the maximum number of iterations. Default value is + `TermCriteria( TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, FLT_EPSILON )`; */ + /** @see setTermCriteria */ + CV_WRAP virtual cv::TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; + + /** Type of a %SVM kernel. + See SVM::KernelTypes. Default value is SVM::RBF. */ + CV_WRAP virtual int getKernelType() const = 0; + + /** Initialize with one of predefined kernels. + See SVM::KernelTypes. */ + CV_WRAP virtual void setKernel(int kernelType) = 0; + + /** Initialize with custom kernel. + See SVM::Kernel class for implementation details */ + virtual void setCustomKernel(const Ptr &_kernel) = 0; + + //! %SVM type + enum Types { + /** C-Support Vector Classification. n-class classification (n \f$\geq\f$ 2), allows + imperfect separation of classes with penalty multiplier C for outliers. */ + C_SVC=100, + /** \f$\nu\f$-Support Vector Classification. n-class classification with possible + imperfect separation. Parameter \f$\nu\f$ (in the range 0..1, the larger the value, the smoother + the decision boundary) is used instead of C. */ + NU_SVC=101, + /** Distribution Estimation (One-class %SVM). All the training data are from + the same class, %SVM builds a boundary that separates the class from the rest of the feature + space. */ + ONE_CLASS=102, + /** \f$\epsilon\f$-Support Vector Regression. The distance between feature vectors + from the training set and the fitting hyper-plane must be less than p. For outliers the + penalty multiplier C is used. */ + EPS_SVR=103, + /** \f$\nu\f$-Support Vector Regression. \f$\nu\f$ is used instead of p. + See @cite LibSVM for details. */ + NU_SVR=104 + }; + + /** @brief %SVM kernel type + + A comparison of different kernels on the following 2D test case with four classes. Four + SVM::C_SVC SVMs have been trained (one against rest) with auto_train. Evaluation on three + different kernels (SVM::CHI2, SVM::INTER, SVM::RBF). The color depicts the class with max score. + Bright means max-score \> 0, dark means max-score \< 0. + ![image](pics/SVM_Comparison.png) + */ + enum KernelTypes { + /** Returned by SVM::getKernelType in case when custom kernel has been set */ + CUSTOM=-1, + /** Linear kernel. No mapping is done, linear discrimination (or regression) is + done in the original feature space. It is the fastest option. \f$K(x_i, x_j) = x_i^T x_j\f$. */ + LINEAR=0, + /** Polynomial kernel: + \f$K(x_i, x_j) = (\gamma x_i^T x_j + coef0)^{degree}, \gamma > 0\f$. */ + POLY=1, + /** Radial basis function (RBF), a good choice in most cases. + \f$K(x_i, x_j) = e^{-\gamma ||x_i - x_j||^2}, \gamma > 0\f$. */ + RBF=2, + /** Sigmoid kernel: \f$K(x_i, x_j) = \tanh(\gamma x_i^T x_j + coef0)\f$. */ + SIGMOID=3, + /** Exponential Chi2 kernel, similar to the RBF kernel: + \f$K(x_i, x_j) = e^{-\gamma \chi^2(x_i,x_j)}, \chi^2(x_i,x_j) = (x_i-x_j)^2/(x_i+x_j), \gamma > 0\f$. */ + CHI2=4, + /** Histogram intersection kernel. A fast kernel. \f$K(x_i, x_j) = min(x_i,x_j)\f$. */ + INTER=5 + }; + + //! %SVM params type + enum ParamTypes { + C=0, + GAMMA=1, + P=2, + NU=3, + COEF=4, + DEGREE=5 + }; + + /** @brief Trains an %SVM with optimal parameters. + + @param data the training data that can be constructed using TrainData::create or + TrainData::loadFromCSV. + @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One + subset is used to test the model, the others form the train set. So, the %SVM algorithm is + executed kFold times. + @param Cgrid grid for C + @param gammaGrid grid for gamma + @param pGrid grid for p + @param nuGrid grid for nu + @param coeffGrid grid for coeff + @param degreeGrid grid for degree + @param balanced If true and the problem is 2-class classification then the method creates more + balanced cross-validation subsets that is proportions between classes in subsets are close + to such proportion in the whole train dataset. + + The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, + nu, coef0, degree. Parameters are considered optimal when the cross-validation + estimate of the test set error is minimal. + + If there is no need to optimize a parameter, the corresponding grid step should be set to any + value less than or equal to 1. For example, to avoid optimization in gamma, set `gammaGrid.step + = 0`, `gammaGrid.minVal`, `gamma_grid.maxVal` as arbitrary numbers. In this case, the value + `Gamma` is taken for gamma. + + And, finally, if the optimization in a parameter is required but the corresponding grid is + unknown, you may call the function SVM::getDefaultGrid. To generate a grid, for example, for + gamma, call `SVM::getDefaultGrid(SVM::GAMMA)`. + + This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the + regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and + the usual %SVM with parameters specified in params is executed. + */ + virtual bool trainAuto( const Ptr& data, int kFold = 10, + ParamGrid Cgrid = getDefaultGrid(C), + ParamGrid gammaGrid = getDefaultGrid(GAMMA), + ParamGrid pGrid = getDefaultGrid(P), + ParamGrid nuGrid = getDefaultGrid(NU), + ParamGrid coeffGrid = getDefaultGrid(COEF), + ParamGrid degreeGrid = getDefaultGrid(DEGREE), + bool balanced=false) = 0; + + /** @brief Trains an %SVM with optimal parameters + + @param samples training samples + @param layout See ml::SampleTypes. + @param responses vector of responses associated with the training samples. + @param kFold Cross-validation parameter. The training set is divided into kFold subsets. One + subset is used to test the model, the others form the train set. So, the %SVM algorithm is + @param Cgrid grid for C + @param gammaGrid grid for gamma + @param pGrid grid for p + @param nuGrid grid for nu + @param coeffGrid grid for coeff + @param degreeGrid grid for degree + @param balanced If true and the problem is 2-class classification then the method creates more + balanced cross-validation subsets that is proportions between classes in subsets are close + to such proportion in the whole train dataset. + + The method trains the %SVM model automatically by choosing the optimal parameters C, gamma, p, + nu, coef0, degree. Parameters are considered optimal when the cross-validation + estimate of the test set error is minimal. + + This function only makes use of SVM::getDefaultGrid for parameter optimization and thus only + offers rudimentary parameter options. + + This function works for the classification (SVM::C_SVC or SVM::NU_SVC) as well as for the + regression (SVM::EPS_SVR or SVM::NU_SVR). If it is SVM::ONE_CLASS, no optimization is made and + the usual %SVM with parameters specified in params is executed. + */ + CV_WRAP virtual bool trainAuto(InputArray samples, + int layout, + InputArray responses, + int kFold = 10, + Ptr Cgrid = SVM::getDefaultGridPtr(SVM::C), + Ptr gammaGrid = SVM::getDefaultGridPtr(SVM::GAMMA), + Ptr pGrid = SVM::getDefaultGridPtr(SVM::P), + Ptr nuGrid = SVM::getDefaultGridPtr(SVM::NU), + Ptr coeffGrid = SVM::getDefaultGridPtr(SVM::COEF), + Ptr degreeGrid = SVM::getDefaultGridPtr(SVM::DEGREE), + bool balanced=false) = 0; + + /** @brief Retrieves all the support vectors + + The method returns all the support vectors as a floating-point matrix, where support vectors are + stored as matrix rows. + */ + CV_WRAP virtual Mat getSupportVectors() const = 0; + + /** @brief Retrieves all the uncompressed support vectors of a linear %SVM + + The method returns all the uncompressed support vectors of a linear %SVM that the compressed + support vector, used for prediction, was derived from. They are returned in a floating-point + matrix, where the support vectors are stored as matrix rows. + */ + CV_WRAP virtual Mat getUncompressedSupportVectors() const = 0; + + /** @brief Retrieves the decision function + + @param i the index of the decision function. If the problem solved is regression, 1-class or + 2-class classification, then there will be just one decision function and the index should + always be 0. Otherwise, in the case of N-class classification, there will be \f$N(N-1)/2\f$ + decision functions. + @param alpha the optional output vector for weights, corresponding to different support vectors. + In the case of linear %SVM all the alpha's will be 1's. + @param svidx the optional output vector of indices of support vectors within the matrix of + support vectors (which can be retrieved by SVM::getSupportVectors). In the case of linear + %SVM each decision function consists of a single "compressed" support vector. + + The method returns rho parameter of the decision function, a scalar subtracted from the weighted + sum of kernel responses. + */ + CV_WRAP virtual double getDecisionFunction(int i, OutputArray alpha, OutputArray svidx) const = 0; + + /** @brief Generates a grid for %SVM parameters. + + @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is + generated for the parameter with this ID. + + The function generates a grid for the specified parameter of the %SVM algorithm. The grid may be + passed to the function SVM::trainAuto. + */ + static ParamGrid getDefaultGrid( int param_id ); + + /** @brief Generates a grid for %SVM parameters. + + @param param_id %SVM parameters IDs that must be one of the SVM::ParamTypes. The grid is + generated for the parameter with this ID. + + The function generates a grid pointer for the specified parameter of the %SVM algorithm. + The grid may be passed to the function SVM::trainAuto. + */ + CV_WRAP static Ptr getDefaultGridPtr( int param_id ); + + /** Creates empty model. + Use StatModel::train to train the model. Since %SVM has several parameters, you may want to + find the best parameters for your problem, it can be done with SVM::trainAuto. */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized svm from a file + * + * Use SVM::save to serialize and store an SVM to disk. + * Load the SVM from this file again, by calling this function with the path to the file. + * + * @param filepath path to serialized svm + */ + CV_WRAP static Ptr load(const String& filepath); +}; + +/****************************************************************************************\ +* Expectation - Maximization * +\****************************************************************************************/ + +/** @brief The class implements the Expectation Maximization algorithm. + +@sa @ref ml_intro_em + */ +class CV_EXPORTS_W EM : public StatModel +{ +public: + //! Type of covariation matrices + enum Types { + /** A scaled identity matrix \f$\mu_k * I\f$. There is the only + parameter \f$\mu_k\f$ to be estimated for each matrix. The option may be used in special cases, + when the constraint is relevant, or as a first step in the optimization (for example in case + when the data is preprocessed with PCA). The results of such preliminary estimation may be + passed again to the optimization procedure, this time with + covMatType=EM::COV_MAT_DIAGONAL. */ + COV_MAT_SPHERICAL=0, + /** A diagonal matrix with positive diagonal elements. The number of + free parameters is d for each matrix. This is most commonly used option yielding good + estimation results. */ + COV_MAT_DIAGONAL=1, + /** A symmetric positively defined matrix. The number of free + parameters in each matrix is about \f$d^2/2\f$. It is not recommended to use this option, unless + there is pretty accurate initial estimation of the parameters and/or a huge number of + training samples. */ + COV_MAT_GENERIC=2, + COV_MAT_DEFAULT=COV_MAT_DIAGONAL + }; + + //! Default parameters + enum {DEFAULT_NCLUSTERS=5, DEFAULT_MAX_ITERS=100}; + + //! The initial step + enum {START_E_STEP=1, START_M_STEP=2, START_AUTO_STEP=0}; + + /** The number of mixture components in the Gaussian mixture model. + Default value of the parameter is EM::DEFAULT_NCLUSTERS=5. Some of %EM implementation could + determine the optimal number of mixtures within a specified value range, but that is not the + case in ML yet. */ + /** @see setClustersNumber */ + CV_WRAP virtual int getClustersNumber() const = 0; + /** @copybrief getClustersNumber @see getClustersNumber */ + CV_WRAP virtual void setClustersNumber(int val) = 0; + + /** Constraint on covariance matrices which defines type of matrices. + See EM::Types. */ + /** @see setCovarianceMatrixType */ + CV_WRAP virtual int getCovarianceMatrixType() const = 0; + /** @copybrief getCovarianceMatrixType @see getCovarianceMatrixType */ + CV_WRAP virtual void setCovarianceMatrixType(int val) = 0; + + /** The termination criteria of the %EM algorithm. + The %EM algorithm can be terminated by the number of iterations termCrit.maxCount (number of + M-steps) or when relative change of likelihood logarithm is less than termCrit.epsilon. Default + maximum number of iterations is EM::DEFAULT_MAX_ITERS=100. */ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; + + /** @brief Returns weights of the mixtures + + Returns vector with the number of elements equal to the number of mixtures. + */ + CV_WRAP virtual Mat getWeights() const = 0; + /** @brief Returns the cluster centers (means of the Gaussian mixture) + + Returns matrix with the number of rows equal to the number of mixtures and number of columns + equal to the space dimensionality. + */ + CV_WRAP virtual Mat getMeans() const = 0; + /** @brief Returns covariation matrices + + Returns vector of covariation matrices. Number of matrices is the number of gaussian mixtures, + each matrix is a square floating-point matrix NxN, where N is the space dimensionality. + */ + CV_WRAP virtual void getCovs(CV_OUT std::vector& covs) const = 0; + + /** @brief Returns posterior probabilities for the provided samples + + @param samples The input samples, floating-point matrix + @param results The optional output \f$ nSamples \times nClusters\f$ matrix of results. It contains + posterior probabilities for each sample from the input + @param flags This parameter will be ignored + */ + CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; + + /** @brief Returns a likelihood logarithm value and an index of the most probable mixture component + for the given sample. + + @param sample A sample for classification. It should be a one-channel matrix of + \f$1 \times dims\f$ or \f$dims \times 1\f$ size. + @param probs Optional output matrix that contains posterior probabilities of each component + given the sample. It has \f$1 \times nclusters\f$ size and CV_64FC1 type. + + The method returns a two-element double vector. Zero element is a likelihood logarithm value for + the sample. First element is an index of the most probable mixture component for the given + sample. + */ + CV_WRAP virtual Vec2d predict2(InputArray sample, OutputArray probs) const = 0; + + /** @brief Estimate the Gaussian mixture parameters from a samples set. + + This variation starts with Expectation step. Initial values of the model parameters will be + estimated by the k-means algorithm. + + Unlike many of the ML models, %EM is an unsupervised learning algorithm and it does not take + responses (class labels or function values) as input. Instead, it computes the *Maximum + Likelihood Estimate* of the Gaussian mixture parameters from an input sample set, stores all the + parameters inside the structure: \f$p_{i,k}\f$ in probs, \f$a_k\f$ in means , \f$S_k\f$ in + covs[k], \f$\pi_k\f$ in weights , and optionally computes the output "class label" for each + sample: \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most + probable mixture component for each sample). + + The trained model can be used further for prediction, just like any other classifier. The + trained model is similar to the NormalBayesClassifier. + + @param samples Samples from which the Gaussian mixture model will be estimated. It should be a + one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type + it will be converted to the inner matrix of such type for the further computing. + @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for + each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. + @param labels The optional output "class label" for each sample: + \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable + mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. + @param probs The optional output matrix that contains posterior probabilities of each Gaussian + mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and + CV_64FC1 type. + */ + CV_WRAP virtual bool trainEM(InputArray samples, + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()) = 0; + + /** @brief Estimate the Gaussian mixture parameters from a samples set. + + This variation starts with Expectation step. You need to provide initial means \f$a_k\f$ of + mixture components. Optionally you can pass initial weights \f$\pi_k\f$ and covariance matrices + \f$S_k\f$ of mixture components. + + @param samples Samples from which the Gaussian mixture model will be estimated. It should be a + one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type + it will be converted to the inner matrix of such type for the further computing. + @param means0 Initial means \f$a_k\f$ of mixture components. It is a one-channel matrix of + \f$nclusters \times dims\f$ size. If the matrix does not have CV_64F type it will be + converted to the inner matrix of such type for the further computing. + @param covs0 The vector of initial covariance matrices \f$S_k\f$ of mixture components. Each of + covariance matrices is a one-channel matrix of \f$dims \times dims\f$ size. If the matrices + do not have CV_64F type they will be converted to the inner matrices of such type for the + further computing. + @param weights0 Initial weights \f$\pi_k\f$ of mixture components. It should be a one-channel + floating-point matrix with \f$1 \times nclusters\f$ or \f$nclusters \times 1\f$ size. + @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for + each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. + @param labels The optional output "class label" for each sample: + \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable + mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. + @param probs The optional output matrix that contains posterior probabilities of each Gaussian + mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and + CV_64FC1 type. + */ + CV_WRAP virtual bool trainE(InputArray samples, InputArray means0, + InputArray covs0=noArray(), + InputArray weights0=noArray(), + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()) = 0; + + /** @brief Estimate the Gaussian mixture parameters from a samples set. + + This variation starts with Maximization step. You need to provide initial probabilities + \f$p_{i,k}\f$ to use this option. + + @param samples Samples from which the Gaussian mixture model will be estimated. It should be a + one-channel matrix, each row of which is a sample. If the matrix does not have CV_64F type + it will be converted to the inner matrix of such type for the further computing. + @param probs0 the probabilities + @param logLikelihoods The optional output matrix that contains a likelihood logarithm value for + each sample. It has \f$nsamples \times 1\f$ size and CV_64FC1 type. + @param labels The optional output "class label" for each sample: + \f$\texttt{labels}_i=\texttt{arg max}_k(p_{i,k}), i=1..N\f$ (indices of the most probable + mixture component for each sample). It has \f$nsamples \times 1\f$ size and CV_32SC1 type. + @param probs The optional output matrix that contains posterior probabilities of each Gaussian + mixture component given the each sample. It has \f$nsamples \times nclusters\f$ size and + CV_64FC1 type. + */ + CV_WRAP virtual bool trainM(InputArray samples, InputArray probs0, + OutputArray logLikelihoods=noArray(), + OutputArray labels=noArray(), + OutputArray probs=noArray()) = 0; + + /** Creates empty %EM model. + The model should be trained then using StatModel::train(traindata, flags) method. Alternatively, you + can use one of the EM::train\* methods or load it from file using Algorithm::load\(filename). + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized EM from a file + * + * Use EM::save to serialize and store an EM to disk. + * Load the EM from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized EM + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Decision Tree * +\****************************************************************************************/ + +/** @brief The class represents a single decision tree or a collection of decision trees. + +The current public interface of the class allows user to train only a single decision tree, however +the class is capable of storing multiple decision trees and using them for prediction (by summing +responses or using a voting schemes), and the derived from DTrees classes (such as RTrees and Boost) +use this capability to implement decision tree ensembles. + +@sa @ref ml_intro_trees +*/ +class CV_EXPORTS_W DTrees : public StatModel +{ +public: + /** Predict options */ + enum Flags { PREDICT_AUTO=0, PREDICT_SUM=(1<<8), PREDICT_MAX_VOTE=(2<<8), PREDICT_MASK=(3<<8) }; + + /** Cluster possible values of a categorical variable into K\<=maxCategories clusters to + find a suboptimal split. + If a discrete variable, on which the training procedure tries to make a split, takes more than + maxCategories values, the precise best subset estimation may take a very long time because the + algorithm is exponential. Instead, many decision trees engines (including our implementation) + try to find sub-optimal split in this case by clustering all the samples into maxCategories + clusters that is some categories are merged together. The clustering is applied only in n \> + 2-class classification problems for categorical variables with N \> max_categories possible + values. In case of regression and 2-class classification the optimal split can be found + efficiently without employing clustering, thus the parameter is not used in these cases. + Default value is 10.*/ + /** @see setMaxCategories */ + CV_WRAP virtual int getMaxCategories() const = 0; + /** @copybrief getMaxCategories @see getMaxCategories */ + CV_WRAP virtual void setMaxCategories(int val) = 0; + + /** The maximum possible depth of the tree. + That is the training algorithms attempts to split a node while its depth is less than maxDepth. + The root node has zero depth. The actual depth may be smaller if the other termination criteria + are met (see the outline of the training procedure @ref ml_intro_trees "here"), and/or if the + tree is pruned. Default value is INT_MAX.*/ + /** @see setMaxDepth */ + CV_WRAP virtual int getMaxDepth() const = 0; + /** @copybrief getMaxDepth @see getMaxDepth */ + CV_WRAP virtual void setMaxDepth(int val) = 0; + + /** If the number of samples in a node is less than this parameter then the node will not be split. + + Default value is 10.*/ + /** @see setMinSampleCount */ + CV_WRAP virtual int getMinSampleCount() const = 0; + /** @copybrief getMinSampleCount @see getMinSampleCount */ + CV_WRAP virtual void setMinSampleCount(int val) = 0; + + /** If CVFolds \> 1 then algorithms prunes the built decision tree using K-fold + cross-validation procedure where K is equal to CVFolds. + Default value is 10.*/ + /** @see setCVFolds */ + CV_WRAP virtual int getCVFolds() const = 0; + /** @copybrief getCVFolds @see getCVFolds */ + CV_WRAP virtual void setCVFolds(int val) = 0; + + /** If true then surrogate splits will be built. + These splits allow to work with missing data and compute variable importance correctly. + Default value is false. + @note currently it's not implemented.*/ + /** @see setUseSurrogates */ + CV_WRAP virtual bool getUseSurrogates() const = 0; + /** @copybrief getUseSurrogates @see getUseSurrogates */ + CV_WRAP virtual void setUseSurrogates(bool val) = 0; + + /** If true then a pruning will be harsher. + This will make a tree more compact and more resistant to the training data noise but a bit less + accurate. Default value is true.*/ + /** @see setUse1SERule */ + CV_WRAP virtual bool getUse1SERule() const = 0; + /** @copybrief getUse1SERule @see getUse1SERule */ + CV_WRAP virtual void setUse1SERule(bool val) = 0; + + /** If true then pruned branches are physically removed from the tree. + Otherwise they are retained and it is possible to get results from the original unpruned (or + pruned less aggressively) tree. Default value is true.*/ + /** @see setTruncatePrunedTree */ + CV_WRAP virtual bool getTruncatePrunedTree() const = 0; + /** @copybrief getTruncatePrunedTree @see getTruncatePrunedTree */ + CV_WRAP virtual void setTruncatePrunedTree(bool val) = 0; + + /** Termination criteria for regression trees. + If all absolute differences between an estimated value in a node and values of train samples + in this node are less than this parameter then the node will not be split further. Default + value is 0.01f*/ + /** @see setRegressionAccuracy */ + CV_WRAP virtual float getRegressionAccuracy() const = 0; + /** @copybrief getRegressionAccuracy @see getRegressionAccuracy */ + CV_WRAP virtual void setRegressionAccuracy(float val) = 0; + + /** @brief The array of a priori class probabilities, sorted by the class label value. + + The parameter can be used to tune the decision tree preferences toward a certain class. For + example, if you want to detect some rare anomaly occurrence, the training base will likely + contain much more normal cases than anomalies, so a very good classification performance + will be achieved just by considering every case as normal. To avoid this, the priors can be + specified, where the anomaly probability is artificially increased (up to 0.5 or even + greater), so the weight of the misclassified anomalies becomes much bigger, and the tree is + adjusted properly. + + You can also think about this parameter as weights of prediction categories which determine + relative weights that you give to misclassification. That is, if the weight of the first + category is 1 and the weight of the second category is 10, then each mistake in predicting + the second category is equivalent to making 10 mistakes in predicting the first category. + Default value is empty Mat.*/ + /** @see setPriors */ + CV_WRAP virtual cv::Mat getPriors() const = 0; + /** @copybrief getPriors @see getPriors */ + CV_WRAP virtual void setPriors(const cv::Mat &val) = 0; + + /** @brief The class represents a decision tree node. + */ + class CV_EXPORTS Node + { + public: + Node(); + double value; //!< Value at the node: a class label in case of classification or estimated + //!< function value in case of regression. + int classIdx; //!< Class index normalized to 0..class_count-1 range and assigned to the + //!< node. It is used internally in classification trees and tree ensembles. + int parent; //!< Index of the parent node + int left; //!< Index of the left child node + int right; //!< Index of right child node + int defaultDir; //!< Default direction where to go (-1: left or +1: right). It helps in the + //!< case of missing values. + int split; //!< Index of the first split + }; + + /** @brief The class represents split in a decision tree. + */ + class CV_EXPORTS Split + { + public: + Split(); + int varIdx; //!< Index of variable on which the split is created. + bool inversed; //!< If true, then the inverse split rule is used (i.e. left and right + //!< branches are exchanged in the rule expressions below). + float quality; //!< The split quality, a positive number. It is used to choose the best split. + int next; //!< Index of the next split in the list of splits for the node + float c; /**< The threshold value in case of split on an ordered variable. + The rule is: + @code{.none} + if var_value < c + then next_node <- left + else next_node <- right + @endcode */ + int subsetOfs; /**< Offset of the bitset used by the split on a categorical variable. + The rule is: + @code{.none} + if bitset[var_value] == 1 + then next_node <- left + else next_node <- right + @endcode */ + }; + + /** @brief Returns indices of root nodes + */ + virtual const std::vector& getRoots() const = 0; + /** @brief Returns all the nodes + + all the node indices are indices in the returned vector + */ + virtual const std::vector& getNodes() const = 0; + /** @brief Returns all the splits + + all the split indices are indices in the returned vector + */ + virtual const std::vector& getSplits() const = 0; + /** @brief Returns all the bitsets for categorical splits + + Split::subsetOfs is an offset in the returned vector + */ + virtual const std::vector& getSubsets() const = 0; + + /** @brief Creates the empty model + + The static method creates empty decision tree with the specified parameters. It should be then + trained using train method (see StatModel::train). Alternatively, you can load the model from + file using Algorithm::load\(filename). + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized DTrees from a file + * + * Use DTree::save to serialize and store an DTree to disk. + * Load the DTree from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized DTree + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Random Trees Classifier * +\****************************************************************************************/ + +/** @brief The class implements the random forest predictor. + +@sa @ref ml_intro_rtrees + */ +class CV_EXPORTS_W RTrees : public DTrees +{ +public: + + /** If true then variable importance will be calculated and then it can be retrieved by RTrees::getVarImportance. + Default value is false.*/ + /** @see setCalculateVarImportance */ + CV_WRAP virtual bool getCalculateVarImportance() const = 0; + /** @copybrief getCalculateVarImportance @see getCalculateVarImportance */ + CV_WRAP virtual void setCalculateVarImportance(bool val) = 0; + + /** The size of the randomly selected subset of features at each tree node and that are used + to find the best split(s). + If you set it to 0 then the size will be set to the square root of the total number of + features. Default value is 0.*/ + /** @see setActiveVarCount */ + CV_WRAP virtual int getActiveVarCount() const = 0; + /** @copybrief getActiveVarCount @see getActiveVarCount */ + CV_WRAP virtual void setActiveVarCount(int val) = 0; + + /** The termination criteria that specifies when the training algorithm stops. + Either when the specified number of trees is trained and added to the ensemble or when + sufficient accuracy (measured as OOB error) is achieved. Typically the more trees you have the + better the accuracy. However, the improvement in accuracy generally diminishes and asymptotes + pass a certain number of trees. Also to keep in mind, the number of tree increases the + prediction time linearly. Default value is TermCriteria(TermCriteria::MAX_ITERS + + TermCriteria::EPS, 50, 0.1)*/ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const TermCriteria &val) = 0; + + /** Returns the variable importance array. + The method returns the variable importance vector, computed at the training stage when + CalculateVarImportance is set to true. If this flag was set to false, the empty matrix is + returned. + */ + CV_WRAP virtual Mat getVarImportance() const = 0; + + /** Returns the result of each individual tree in the forest. + In case the model is a regression problem, the method will return each of the trees' + results for each of the sample cases. If the model is a classifier, it will return + a Mat with samples + 1 rows, where the first row gives the class number and the + following rows return the votes each class had for each sample. + @param samples Array containing the samples for which votes will be calculated. + @param results Array where the result of the calculation will be written. + @param flags Flags for defining the type of RTrees. + */ + CV_WRAP virtual void getVotes(InputArray samples, OutputArray results, int flags) const = 0; + + /** Returns the OOB error value, computed at the training stage when calcOOBError is set to true. + * If this flag was set to false, 0 is returned. The OOB error is also scaled by sample weighting. + */ +#if CV_VERSION_MAJOR == 4 + CV_WRAP virtual double getOOBError() const { return 0; } +#else + /*CV_WRAP*/ virtual double getOOBError() const = 0; +#endif + + /** Creates the empty model. + Use StatModel::train to train the model, StatModel::train to create and train the model, + Algorithm::load to load the pre-trained model. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized RTree from a file + * + * Use RTree::save to serialize and store an RTree to disk. + * Load the RTree from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized RTree + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Boosted tree classifier * +\****************************************************************************************/ + +/** @brief Boosted tree classifier derived from DTrees + +@sa @ref ml_intro_boost + */ +class CV_EXPORTS_W Boost : public DTrees +{ +public: + /** Type of the boosting algorithm. + See Boost::Types. Default value is Boost::REAL. */ + /** @see setBoostType */ + CV_WRAP virtual int getBoostType() const = 0; + /** @copybrief getBoostType @see getBoostType */ + CV_WRAP virtual void setBoostType(int val) = 0; + + /** The number of weak classifiers. + Default value is 100. */ + /** @see setWeakCount */ + CV_WRAP virtual int getWeakCount() const = 0; + /** @copybrief getWeakCount @see getWeakCount */ + CV_WRAP virtual void setWeakCount(int val) = 0; + + /** A threshold between 0 and 1 used to save computational time. + Samples with summary weight \f$\leq 1 - weight_trim_rate\f$ do not participate in the *next* + iteration of training. Set this parameter to 0 to turn off this functionality. Default value is 0.95.*/ + /** @see setWeightTrimRate */ + CV_WRAP virtual double getWeightTrimRate() const = 0; + /** @copybrief getWeightTrimRate @see getWeightTrimRate */ + CV_WRAP virtual void setWeightTrimRate(double val) = 0; + + /** Boosting type. + Gentle AdaBoost and Real AdaBoost are often the preferable choices. */ + enum Types { + DISCRETE=0, //!< Discrete AdaBoost. + REAL=1, //!< Real AdaBoost. It is a technique that utilizes confidence-rated predictions + //!< and works well with categorical data. + LOGIT=2, //!< LogitBoost. It can produce good regression fits. + GENTLE=3 //!< Gentle AdaBoost. It puts less weight on outlier data points and for that + //!(filename) to load the pre-trained model. */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized Boost from a file + * + * Use Boost::save to serialize and store an RTree to disk. + * Load the Boost from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized Boost + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + +/****************************************************************************************\ +* Gradient Boosted Trees * +\****************************************************************************************/ + +/*class CV_EXPORTS_W GBTrees : public DTrees +{ +public: + struct CV_EXPORTS_W_MAP Params : public DTrees::Params + { + CV_PROP_RW int weakCount; + CV_PROP_RW int lossFunctionType; + CV_PROP_RW float subsamplePortion; + CV_PROP_RW float shrinkage; + + Params(); + Params( int lossFunctionType, int weakCount, float shrinkage, + float subsamplePortion, int maxDepth, bool useSurrogates ); + }; + + enum {SQUARED_LOSS=0, ABSOLUTE_LOSS, HUBER_LOSS=3, DEVIANCE_LOSS}; + + virtual void setK(int k) = 0; + + virtual float predictSerial( InputArray samples, + OutputArray weakResponses, int flags) const = 0; + + static Ptr create(const Params& p); +};*/ + +/****************************************************************************************\ +* Artificial Neural Networks (ANN) * +\****************************************************************************************/ + +/////////////////////////////////// Multi-Layer Perceptrons ////////////////////////////// + +/** @brief Artificial Neural Networks - Multi-Layer Perceptrons. + +Unlike many other models in ML that are constructed and trained at once, in the MLP model these +steps are separated. First, a network with the specified topology is created using the non-default +constructor or the method ANN_MLP::create. All the weights are set to zeros. Then, the network is +trained using a set of input and output vectors. The training procedure can be repeated more than +once, that is, the weights can be adjusted based on the new training data. + +Additional flags for StatModel::train are available: ANN_MLP::TrainFlags. + +@sa @ref ml_intro_ann + */ +class CV_EXPORTS_W ANN_MLP : public StatModel +{ +public: + /** Available training methods */ + enum TrainingMethods { + BACKPROP=0, //!< The back-propagation algorithm. + RPROP = 1, //!< The RPROP algorithm. See @cite RPROP93 for details. + ANNEAL = 2 //!< The simulated annealing algorithm. See @cite Kirkpatrick83 for details. + }; + + /** Sets training method and common parameters. + @param method Default value is ANN_MLP::RPROP. See ANN_MLP::TrainingMethods. + @param param1 passed to setRpropDW0 for ANN_MLP::RPROP and to setBackpropWeightScale for ANN_MLP::BACKPROP and to initialT for ANN_MLP::ANNEAL. + @param param2 passed to setRpropDWMin for ANN_MLP::RPROP and to setBackpropMomentumScale for ANN_MLP::BACKPROP and to finalT for ANN_MLP::ANNEAL. + */ + CV_WRAP virtual void setTrainMethod(int method, double param1 = 0, double param2 = 0) = 0; + + /** Returns current training method */ + CV_WRAP virtual int getTrainMethod() const = 0; + + /** Initialize the activation function for each neuron. + Currently the default and the only fully supported activation function is ANN_MLP::SIGMOID_SYM. + @param type The type of activation function. See ANN_MLP::ActivationFunctions. + @param param1 The first parameter of the activation function, \f$\alpha\f$. Default value is 0. + @param param2 The second parameter of the activation function, \f$\beta\f$. Default value is 0. + */ + CV_WRAP virtual void setActivationFunction(int type, double param1 = 0, double param2 = 0) = 0; + + /** Integer vector specifying the number of neurons in each layer including the input and output layers. + The very first element specifies the number of elements in the input layer. + The last element - number of elements in the output layer. Default value is empty Mat. + @sa getLayerSizes */ + CV_WRAP virtual void setLayerSizes(InputArray _layer_sizes) = 0; + + /** Integer vector specifying the number of neurons in each layer including the input and output layers. + The very first element specifies the number of elements in the input layer. + The last element - number of elements in the output layer. + @sa setLayerSizes */ + CV_WRAP virtual cv::Mat getLayerSizes() const = 0; + + /** Termination criteria of the training algorithm. + You can specify the maximum number of iterations (maxCount) and/or how much the error could + change between the iterations to make the algorithm continue (epsilon). Default value is + TermCriteria(TermCriteria::MAX_ITER + TermCriteria::EPS, 1000, 0.01).*/ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; + + /** BPROP: Strength of the weight gradient term. + The recommended value is about 0.1. Default value is 0.1.*/ + /** @see setBackpropWeightScale */ + CV_WRAP virtual double getBackpropWeightScale() const = 0; + /** @copybrief getBackpropWeightScale @see getBackpropWeightScale */ + CV_WRAP virtual void setBackpropWeightScale(double val) = 0; + + /** BPROP: Strength of the momentum term (the difference between weights on the 2 previous iterations). + This parameter provides some inertia to smooth the random fluctuations of the weights. It can + vary from 0 (the feature is disabled) to 1 and beyond. The value 0.1 or so is good enough. + Default value is 0.1.*/ + /** @see setBackpropMomentumScale */ + CV_WRAP virtual double getBackpropMomentumScale() const = 0; + /** @copybrief getBackpropMomentumScale @see getBackpropMomentumScale */ + CV_WRAP virtual void setBackpropMomentumScale(double val) = 0; + + /** RPROP: Initial value \f$\Delta_0\f$ of update-values \f$\Delta_{ij}\f$. + Default value is 0.1.*/ + /** @see setRpropDW0 */ + CV_WRAP virtual double getRpropDW0() const = 0; + /** @copybrief getRpropDW0 @see getRpropDW0 */ + CV_WRAP virtual void setRpropDW0(double val) = 0; + + /** RPROP: Increase factor \f$\eta^+\f$. + It must be \>1. Default value is 1.2.*/ + /** @see setRpropDWPlus */ + CV_WRAP virtual double getRpropDWPlus() const = 0; + /** @copybrief getRpropDWPlus @see getRpropDWPlus */ + CV_WRAP virtual void setRpropDWPlus(double val) = 0; + + /** RPROP: Decrease factor \f$\eta^-\f$. + It must be \<1. Default value is 0.5.*/ + /** @see setRpropDWMinus */ + CV_WRAP virtual double getRpropDWMinus() const = 0; + /** @copybrief getRpropDWMinus @see getRpropDWMinus */ + CV_WRAP virtual void setRpropDWMinus(double val) = 0; + + /** RPROP: Update-values lower limit \f$\Delta_{min}\f$. + It must be positive. Default value is FLT_EPSILON.*/ + /** @see setRpropDWMin */ + CV_WRAP virtual double getRpropDWMin() const = 0; + /** @copybrief getRpropDWMin @see getRpropDWMin */ + CV_WRAP virtual void setRpropDWMin(double val) = 0; + + /** RPROP: Update-values upper limit \f$\Delta_{max}\f$. + It must be \>1. Default value is 50.*/ + /** @see setRpropDWMax */ + CV_WRAP virtual double getRpropDWMax() const = 0; + /** @copybrief getRpropDWMax @see getRpropDWMax */ + CV_WRAP virtual void setRpropDWMax(double val) = 0; + + /** ANNEAL: Update initial temperature. + It must be \>=0. Default value is 10.*/ + /** @see setAnnealInitialT */ + CV_WRAP virtual double getAnnealInitialT() const = 0; + /** @copybrief getAnnealInitialT @see getAnnealInitialT */ + CV_WRAP virtual void setAnnealInitialT(double val) = 0; + + /** ANNEAL: Update final temperature. + It must be \>=0 and less than initialT. Default value is 0.1.*/ + /** @see setAnnealFinalT */ + CV_WRAP virtual double getAnnealFinalT() const = 0; + /** @copybrief getAnnealFinalT @see getAnnealFinalT */ + CV_WRAP virtual void setAnnealFinalT(double val) = 0; + + /** ANNEAL: Update cooling ratio. + It must be \>0 and less than 1. Default value is 0.95.*/ + /** @see setAnnealCoolingRatio */ + CV_WRAP virtual double getAnnealCoolingRatio() const = 0; + /** @copybrief getAnnealCoolingRatio @see getAnnealCoolingRatio */ + CV_WRAP virtual void setAnnealCoolingRatio(double val) = 0; + + /** ANNEAL: Update iteration per step. + It must be \>0 . Default value is 10.*/ + /** @see setAnnealItePerStep */ + CV_WRAP virtual int getAnnealItePerStep() const = 0; + /** @copybrief getAnnealItePerStep @see getAnnealItePerStep */ + CV_WRAP virtual void setAnnealItePerStep(int val) = 0; + + /** @brief Set/initialize anneal RNG */ + virtual void setAnnealEnergyRNG(const RNG& rng) = 0; + + /** possible activation functions */ + enum ActivationFunctions { + /** Identity function: \f$f(x)=x\f$ */ + IDENTITY = 0, + /** Symmetrical sigmoid: \f$f(x)=\beta*(1-e^{-\alpha x})/(1+e^{-\alpha x})\f$ + @note + If you are using the default sigmoid activation function with the default parameter values + fparam1=0 and fparam2=0 then the function used is y = 1.7159\*tanh(2/3 \* x), so the output + will range from [-1.7159, 1.7159], instead of [0,1].*/ + SIGMOID_SYM = 1, + /** Gaussian function: \f$f(x)=\beta e^{-\alpha x*x}\f$ */ + GAUSSIAN = 2, + /** ReLU function: \f$f(x)=max(0,x)\f$ */ + RELU = 3, + /** Leaky ReLU function: for x>0 \f$f(x)=x \f$ and x<=0 \f$f(x)=\alpha x \f$*/ + LEAKYRELU= 4 + }; + + /** Train options */ + enum TrainFlags { + /** Update the network weights, rather than compute them from scratch. In the latter case + the weights are initialized using the Nguyen-Widrow algorithm. */ + UPDATE_WEIGHTS = 1, + /** Do not normalize the input vectors. If this flag is not set, the training algorithm + normalizes each input feature independently, shifting its mean value to 0 and making the + standard deviation equal to 1. If the network is assumed to be updated frequently, the new + training data could be much different from original one. In this case, you should take care + of proper normalization. */ + NO_INPUT_SCALE = 2, + /** Do not normalize the output vectors. If the flag is not set, the training algorithm + normalizes each output feature independently, by transforming it to the certain range + depending on the used activation function. */ + NO_OUTPUT_SCALE = 4 + }; + + CV_WRAP virtual Mat getWeights(int layerIdx) const = 0; + + /** @brief Creates empty model + + Use StatModel::train to train the model, Algorithm::load\(filename) to load the pre-trained model. + Note that the train method has optional flags: ANN_MLP::TrainFlags. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized ANN from a file + * + * Use ANN::save to serialize and store an ANN to disk. + * Load the ANN from this file again, by calling this function with the path to the file. + * + * @param filepath path to serialized ANN + */ + CV_WRAP static Ptr load(const String& filepath); + +}; + +#ifndef DISABLE_OPENCV_3_COMPATIBILITY +typedef ANN_MLP ANN_MLP_ANNEAL; +#endif + +/****************************************************************************************\ +* Logistic Regression * +\****************************************************************************************/ + +/** @brief Implements Logistic Regression classifier. + +@sa @ref ml_intro_lr + */ +class CV_EXPORTS_W LogisticRegression : public StatModel +{ +public: + + /** Learning rate. */ + /** @see setLearningRate */ + CV_WRAP virtual double getLearningRate() const = 0; + /** @copybrief getLearningRate @see getLearningRate */ + CV_WRAP virtual void setLearningRate(double val) = 0; + + /** Number of iterations. */ + /** @see setIterations */ + CV_WRAP virtual int getIterations() const = 0; + /** @copybrief getIterations @see getIterations */ + CV_WRAP virtual void setIterations(int val) = 0; + + /** Kind of regularization to be applied. See LogisticRegression::RegKinds. */ + /** @see setRegularization */ + CV_WRAP virtual int getRegularization() const = 0; + /** @copybrief getRegularization @see getRegularization */ + CV_WRAP virtual void setRegularization(int val) = 0; + + /** Kind of training method used. See LogisticRegression::Methods. */ + /** @see setTrainMethod */ + CV_WRAP virtual int getTrainMethod() const = 0; + /** @copybrief getTrainMethod @see getTrainMethod */ + CV_WRAP virtual void setTrainMethod(int val) = 0; + + /** Specifies the number of training samples taken in each step of Mini-Batch Gradient + Descent. Will only be used if using LogisticRegression::MINI_BATCH training algorithm. It + has to take values less than the total number of training samples. */ + /** @see setMiniBatchSize */ + CV_WRAP virtual int getMiniBatchSize() const = 0; + /** @copybrief getMiniBatchSize @see getMiniBatchSize */ + CV_WRAP virtual void setMiniBatchSize(int val) = 0; + + /** Termination criteria of the algorithm. */ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(TermCriteria val) = 0; + + //! Regularization kinds + enum RegKinds { + REG_DISABLE = -1, //!< Regularization disabled + REG_L1 = 0, //!< %L1 norm + REG_L2 = 1 //!< %L2 norm + }; + + //! Training methods + enum Methods { + BATCH = 0, + MINI_BATCH = 1 //!< Set MiniBatchSize to a positive integer when using this method. + }; + + /** @brief Predicts responses for input samples and returns a float type. + + @param samples The input data for the prediction algorithm. Matrix [m x n], where each row + contains variables (features) of one object being classified. Should have data type CV_32F. + @param results Predicted labels as a column matrix of type CV_32S. + @param flags Not used. + */ + CV_WRAP virtual float predict( InputArray samples, OutputArray results=noArray(), int flags=0 ) const CV_OVERRIDE = 0; + + /** @brief This function returns the trained parameters arranged across rows. + + For a two class classification problem, it returns a row matrix. It returns learnt parameters of + the Logistic Regression as a matrix of type CV_32F. + */ + CV_WRAP virtual Mat get_learnt_thetas() const = 0; + + /** @brief Creates empty model. + + Creates Logistic Regression model with parameters given. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized LogisticRegression from a file + * + * Use LogisticRegression::save to serialize and store an LogisticRegression to disk. + * Load the LogisticRegression from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized LogisticRegression + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); +}; + + +/****************************************************************************************\ +* Stochastic Gradient Descent SVM Classifier * +\****************************************************************************************/ + +/*! +@brief Stochastic Gradient Descent SVM classifier + +SVMSGD provides a fast and easy-to-use implementation of the SVM classifier using the Stochastic Gradient Descent approach, +as presented in @cite bottou2010large. + +The classifier has following parameters: +- model type, +- margin type, +- margin regularization (\f$\lambda\f$), +- initial step size (\f$\gamma_0\f$), +- step decreasing power (\f$c\f$), +- and termination criteria. + +The model type may have one of the following values: \ref SGD and \ref ASGD. + +- \ref SGD is the classic version of SVMSGD classifier: every next step is calculated by the formula + \f[w_{t+1} = w_t - \gamma(t) \frac{dQ_i}{dw} |_{w = w_t}\f] + where + - \f$w_t\f$ is the weights vector for decision function at step \f$t\f$, + - \f$\gamma(t)\f$ is the step size of model parameters at the iteration \f$t\f$, it is decreased on each step by the formula + \f$\gamma(t) = \gamma_0 (1 + \lambda \gamma_0 t) ^ {-c}\f$ + - \f$Q_i\f$ is the target functional from SVM task for sample with number \f$i\f$, this sample is chosen stochastically on each step of the algorithm. + +- \ref ASGD is Average Stochastic Gradient Descent SVM Classifier. ASGD classifier averages weights vector on each step of algorithm by the formula +\f$\widehat{w}_{t+1} = \frac{t}{1+t}\widehat{w}_{t} + \frac{1}{1+t}w_{t+1}\f$ + +The recommended model type is ASGD (following @cite bottou2010large). + +The margin type may have one of the following values: \ref SOFT_MARGIN or \ref HARD_MARGIN. + +- You should use \ref HARD_MARGIN type, if you have linearly separable sets. +- You should use \ref SOFT_MARGIN type, if you have non-linearly separable sets or sets with outliers. +- In the general case (if you know nothing about linear separability of your sets), use SOFT_MARGIN. + +The other parameters may be described as follows: +- Margin regularization parameter is responsible for weights decreasing at each step and for the strength of restrictions on outliers + (the less the parameter, the less probability that an outlier will be ignored). + Recommended value for SGD model is 0.0001, for ASGD model is 0.00001. + +- Initial step size parameter is the initial value for the step size \f$\gamma(t)\f$. + You will have to find the best initial step for your problem. + +- Step decreasing power is the power parameter for \f$\gamma(t)\f$ decreasing by the formula, mentioned above. + Recommended value for SGD model is 1, for ASGD model is 0.75. + +- Termination criteria can be TermCriteria::COUNT, TermCriteria::EPS or TermCriteria::COUNT + TermCriteria::EPS. + You will have to find the best termination criteria for your problem. + +Note that the parameters margin regularization, initial step size, and step decreasing power should be positive. + +To use SVMSGD algorithm do as follows: + +- first, create the SVMSGD object. The algorithm will set optimal parameters by default, but you can set your own parameters via functions setSvmsgdType(), + setMarginType(), setMarginRegularization(), setInitialStepSize(), and setStepDecreasingPower(). + +- then the SVM model can be trained using the train features and the correspondent labels by the method train(). + +- after that, the label of a new feature vector can be predicted using the method predict(). + +@code +// Create empty object +cv::Ptr svmsgd = SVMSGD::create(); + +// Train the Stochastic Gradient Descent SVM +svmsgd->train(trainData); + +// Predict labels for the new samples +svmsgd->predict(samples, responses); +@endcode + +*/ + +class CV_EXPORTS_W SVMSGD : public cv::ml::StatModel +{ +public: + + /** SVMSGD type. + ASGD is often the preferable choice. */ + enum SvmsgdType + { + SGD, //!< Stochastic Gradient Descent + ASGD //!< Average Stochastic Gradient Descent + }; + + /** Margin type.*/ + enum MarginType + { + SOFT_MARGIN, //!< General case, suits to the case of non-linearly separable sets, allows outliers. + HARD_MARGIN //!< More accurate for the case of linearly separable sets. + }; + + /** + * @return the weights of the trained model (decision function f(x) = weights * x + shift). + */ + CV_WRAP virtual Mat getWeights() = 0; + + /** + * @return the shift of the trained model (decision function f(x) = weights * x + shift). + */ + CV_WRAP virtual float getShift() = 0; + + /** @brief Creates empty model. + * Use StatModel::train to train the model. Since %SVMSGD has several parameters, you may want to + * find the best parameters for your problem or use setOptimalParameters() to set some default parameters. + */ + CV_WRAP static Ptr create(); + + /** @brief Loads and creates a serialized SVMSGD from a file + * + * Use SVMSGD::save to serialize and store an SVMSGD to disk. + * Load the SVMSGD from this file again, by calling this function with the path to the file. + * Optionally specify the node for the file containing the classifier + * + * @param filepath path to serialized SVMSGD + * @param nodeName name of node containing the classifier + */ + CV_WRAP static Ptr load(const String& filepath , const String& nodeName = String()); + + /** @brief Function sets optimal parameters values for chosen SVM SGD model. + * @param svmsgdType is the type of SVMSGD classifier. + * @param marginType is the type of margin constraint. + */ + CV_WRAP virtual void setOptimalParameters(int svmsgdType = SVMSGD::ASGD, int marginType = SVMSGD::SOFT_MARGIN) = 0; + + /** @brief %Algorithm type, one of SVMSGD::SvmsgdType. */ + /** @see setSvmsgdType */ + CV_WRAP virtual int getSvmsgdType() const = 0; + /** @copybrief getSvmsgdType @see getSvmsgdType */ + CV_WRAP virtual void setSvmsgdType(int svmsgdType) = 0; + + /** @brief %Margin type, one of SVMSGD::MarginType. */ + /** @see setMarginType */ + CV_WRAP virtual int getMarginType() const = 0; + /** @copybrief getMarginType @see getMarginType */ + CV_WRAP virtual void setMarginType(int marginType) = 0; + + /** @brief Parameter marginRegularization of a %SVMSGD optimization problem. */ + /** @see setMarginRegularization */ + CV_WRAP virtual float getMarginRegularization() const = 0; + /** @copybrief getMarginRegularization @see getMarginRegularization */ + CV_WRAP virtual void setMarginRegularization(float marginRegularization) = 0; + + /** @brief Parameter initialStepSize of a %SVMSGD optimization problem. */ + /** @see setInitialStepSize */ + CV_WRAP virtual float getInitialStepSize() const = 0; + /** @copybrief getInitialStepSize @see getInitialStepSize */ + CV_WRAP virtual void setInitialStepSize(float InitialStepSize) = 0; + + /** @brief Parameter stepDecreasingPower of a %SVMSGD optimization problem. */ + /** @see setStepDecreasingPower */ + CV_WRAP virtual float getStepDecreasingPower() const = 0; + /** @copybrief getStepDecreasingPower @see getStepDecreasingPower */ + CV_WRAP virtual void setStepDecreasingPower(float stepDecreasingPower) = 0; + + /** @brief Termination criteria of the training algorithm. + You can specify the maximum number of iterations (maxCount) and/or how much the error could + change between the iterations to make the algorithm continue (epsilon).*/ + /** @see setTermCriteria */ + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + /** @copybrief getTermCriteria @see getTermCriteria */ + CV_WRAP virtual void setTermCriteria(const cv::TermCriteria &val) = 0; +}; + + +/****************************************************************************************\ +* Auxiliary functions declarations * +\****************************************************************************************/ + +/** @brief Generates _sample_ from multivariate normal distribution + +@param mean an average row vector +@param cov symmetric covariation matrix +@param nsamples returned samples count +@param samples returned samples array +*/ +CV_EXPORTS void randMVNormal( InputArray mean, InputArray cov, int nsamples, OutputArray samples); + +/** @brief Creates test set */ +CV_EXPORTS void createConcentricSpheresTestSet( int nsamples, int nfeatures, int nclasses, + OutputArray samples, OutputArray responses); + + +/****************************************************************************************\ +* Simulated annealing solver * +\****************************************************************************************/ + +#ifdef CV_DOXYGEN +/** @brief This class declares example interface for system state used in simulated annealing optimization algorithm. + +@note This class is not defined in C++ code and can't be use directly - you need your own implementation with the same methods. +*/ +struct SimulatedAnnealingSolverSystem +{ + /** Give energy value for a state of system.*/ + double energy() const; + /** Function which change the state of system (random perturbation).*/ + void changeState(); + /** Function to reverse to the previous state. Can be called once only after changeState(). */ + void reverseState(); +}; +#endif // CV_DOXYGEN + +/** @brief The class implements simulated annealing for optimization. + +@cite Kirkpatrick83 for details + +@param solverSystem optimization system (see SimulatedAnnealingSolverSystem) +@param initialTemperature initial temperature +@param finalTemperature final temperature +@param coolingRatio temperature step multiplies +@param iterationsPerStep number of iterations per temperature changing step +@param lastTemperature optional output for last used temperature +@param rngEnergy specify custom random numbers generator (cv::theRNG() by default) +*/ +template +int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, + double initialTemperature, double finalTemperature, double coolingRatio, + size_t iterationsPerStep, + CV_OUT double* lastTemperature = NULL, + cv::RNG& rngEnergy = cv::theRNG() +); + +//! @} ml + +} +} + +#include + +#endif // __cplusplus +#endif // OPENCV_ML_HPP + +/* End of file. */ diff --git a/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp b/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp index 7c84aab559..f6f9cd8f89 100644 --- a/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/ml/ml.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/ml.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/ml.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp b/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp index 91bab1f5f5..dc9c78393a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/ml/ml.inl.hpp @@ -1,60 +1,60 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_ML_INL_HPP -#define OPENCV_ML_INL_HPP - -namespace cv { namespace ml { - -// declared in ml.hpp -template -int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, - double initialTemperature, double finalTemperature, double coolingRatio, - size_t iterationsPerStep, - CV_OUT double* lastTemperature, - cv::RNG& rngEnergy -) -{ - CV_Assert(finalTemperature > 0); - CV_Assert(initialTemperature > finalTemperature); - CV_Assert(iterationsPerStep > 0); - CV_Assert(coolingRatio < 1.0f); - double Ti = initialTemperature; - double previousEnergy = solverSystem.energy(); - int exchange = 0; - while (Ti > finalTemperature) - { - for (size_t i = 0; i < iterationsPerStep; i++) - { - solverSystem.changeState(); - double newEnergy = solverSystem.energy(); - if (newEnergy < previousEnergy) - { - previousEnergy = newEnergy; - exchange++; - } - else - { - double r = rngEnergy.uniform(0.0, 1.0); - if (r < std::exp(-(newEnergy - previousEnergy) / Ti)) - { - previousEnergy = newEnergy; - exchange++; - } - else - { - solverSystem.reverseState(); - } - } - } - Ti *= coolingRatio; - } - if (lastTemperature) - *lastTemperature = Ti; - return exchange; -} - -}} //namespace - -#endif // OPENCV_ML_INL_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_ML_INL_HPP +#define OPENCV_ML_INL_HPP + +namespace cv { namespace ml { + +// declared in ml.hpp +template +int simulatedAnnealingSolver(SimulatedAnnealingSolverSystem& solverSystem, + double initialTemperature, double finalTemperature, double coolingRatio, + size_t iterationsPerStep, + CV_OUT double* lastTemperature, + cv::RNG& rngEnergy +) +{ + CV_Assert(finalTemperature > 0); + CV_Assert(initialTemperature > finalTemperature); + CV_Assert(iterationsPerStep > 0); + CV_Assert(coolingRatio < 1.0f); + double Ti = initialTemperature; + double previousEnergy = solverSystem.energy(); + int exchange = 0; + while (Ti > finalTemperature) + { + for (size_t i = 0; i < iterationsPerStep; i++) + { + solverSystem.changeState(); + double newEnergy = solverSystem.energy(); + if (newEnergy < previousEnergy) + { + previousEnergy = newEnergy; + exchange++; + } + else + { + double r = rngEnergy.uniform(0.0, 1.0); + if (r < std::exp(-(newEnergy - previousEnergy) / Ti)) + { + previousEnergy = newEnergy; + exchange++; + } + else + { + solverSystem.reverseState(); + } + } + } + Ti *= coolingRatio; + } + if (lastTemperature) + *lastTemperature = Ti; + return exchange; +} + +}} //namespace + +#endif // OPENCV_ML_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp index 15364fc88b..7f11890608 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect.hpp @@ -1,873 +1,873 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_OBJDETECT_HPP -#define OPENCV_OBJDETECT_HPP - -#include "opencv2/core.hpp" -#include "opencv2/objdetect/aruco_detector.hpp" -#include "opencv2/objdetect/graphical_code_detector.hpp" - -/** -@defgroup objdetect Object Detection - -@{ - @defgroup objdetect_cascade_classifier Cascade Classifier for Object Detection - - The object detector described below has been initially proposed by Paul Viola @cite Viola01 and - improved by Rainer Lienhart @cite Lienhart02 . - - First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is - trained with a few hundred sample views of a particular object (i.e., a face or a car), called - positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary - images of the same size. - - After a classifier is trained, it can be applied to a region of interest (of the same size as used - during the training) in an input image. The classifier outputs a "1" if the region is likely to show - the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can - move the search window across the image and check every location using the classifier. The - classifier is designed so that it can be easily "resized" in order to be able to find the objects of - interest at different sizes, which is more efficient than resizing the image itself. So, to find an - object of an unknown size in the image the scan procedure should be done several times at different - scales. - - The word "cascade" in the classifier name means that the resultant classifier consists of several - simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some - stage the candidate is rejected or all the stages are passed. The word "boosted" means that the - classifiers at every stage of the cascade are complex themselves and they are built out of basic - classifiers using one of four different boosting techniques (weighted voting). Currently Discrete - Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are - decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic - classifiers, and are calculated as described below. The current algorithm uses the following - Haar-like features: - - ![image](pics/haarfeatures.png) - - The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within - the region of interest and the scale (this scale is not the same as the scale used at the detection - stage, though these two scales are multiplied). For example, in the case of the third line feature - (2c) the response is calculated as the difference between the sum of image pixels under the - rectangle covering the whole feature (including the two white stripes and the black stripe in the - middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to - compensate for the differences in the size of areas. The sums of pixel values over a rectangular - regions are calculated rapidly using integral images (see below and the integral description). - - Check @ref tutorial_cascade_classifier "the corresponding tutorial" for more details. - - The following reference is for the detection part only. There is a separate application called - opencv_traincascade that can train a cascade of boosted classifiers from a set of samples. - - @note In the new C++ interface it is also possible to use LBP (local binary pattern) features in - addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection - using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at - - - @defgroup objdetect_hog HOG (Histogram of Oriented Gradients) descriptor and object detector - @defgroup objdetect_barcode Barcode detection and decoding - @defgroup objdetect_qrcode QRCode detection and encoding - @defgroup objdetect_dnn_face DNN-based face detection and recognition - - Check @ref tutorial_dnn_face "the corresponding tutorial" for more details. - - @defgroup objdetect_common Common functions and classes - @defgroup objdetect_aruco ArUco markers and boards detection for robust camera pose estimation - @{ - ArUco Marker Detection - Square fiducial markers (also known as Augmented Reality Markers) are useful for easy, - fast and robust camera pose estimation. - - The main functionality of ArucoDetector class is detection of markers in an image. If the markers are grouped - as a board, then you can try to recover the missing markers with ArucoDetector::refineDetectedMarkers(). - ArUco markers can also be used for advanced chessboard corner finding. To do this, group the markers in the - CharucoBoard and find the corners of the chessboard with the CharucoDetector::detectBoard(). - - The implementation is based on the ArUco Library by R. Muñoz-Salinas and S. Garrido-Jurado @cite Aruco2014. - - Markers can also be detected based on the AprilTag 2 @cite wang2016iros fiducial detection method. - - @sa @cite Aruco2014 - This code has been originally developed by Sergio Garrido-Jurado as a project - for Google Summer of Code 2015 (GSoC 15). - @} - -@} - */ - -typedef struct CvHaarClassifierCascade CvHaarClassifierCascade; - -namespace cv -{ - -//! @addtogroup objdetect_common -//! @{ - -///////////////////////////// Object Detection //////////////////////////// - -/** @brief This class is used for grouping object candidates detected by Cascade Classifier, HOG etc. - -instance of the class is to be passed to cv::partition - */ -class CV_EXPORTS SimilarRects -{ -public: - SimilarRects(double _eps) : eps(_eps) {} - inline bool operator()(const Rect& r1, const Rect& r2) const - { - double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5; - return std::abs(r1.x - r2.x) <= delta && - std::abs(r1.y - r2.y) <= delta && - std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && - std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; - } - double eps; -}; - -/** @brief Groups the object candidate rectangles. - -@param rectList Input/output vector of rectangles. Output vector includes retained and grouped -rectangles. (The Python list is not modified in place.) -@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a -group of rectangles to retain it. -@param eps Relative difference between sides of the rectangles to merge them into a group. - -The function is a wrapper for the generic function partition . It clusters all the input rectangles -using the rectangle equivalence criteria that combines rectangles with similar sizes and similar -locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If -\f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small -clusters containing less than or equal to groupThreshold rectangles are rejected. In each other -cluster, the average rectangle is computed and put into the output rectangle list. - */ -CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, double eps = 0.2); -/** @overload */ -CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector& rectList, CV_OUT std::vector& weights, - int groupThreshold, double eps = 0.2); -/** @overload */ -CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, - double eps, std::vector* weights, std::vector* levelWeights ); -/** @overload */ -CV_EXPORTS void groupRectangles(std::vector& rectList, std::vector& rejectLevels, - std::vector& levelWeights, int groupThreshold, double eps = 0.2); -/** @overload */ -CV_EXPORTS void groupRectangles_meanshift(std::vector& rectList, std::vector& foundWeights, - std::vector& foundScales, - double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); -//! @} - -//! @addtogroup objdetect_cascade_classifier -//! @{ - -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; }; - -enum { CASCADE_DO_CANNY_PRUNING = 1, - CASCADE_SCALE_IMAGE = 2, - CASCADE_FIND_BIGGEST_OBJECT = 4, - CASCADE_DO_ROUGH_SEARCH = 8 - }; - -class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm -{ -public: - virtual ~BaseCascadeClassifier(); - virtual bool empty() const CV_OVERRIDE = 0; - virtual bool load( const String& filename ) = 0; - virtual void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - double scaleFactor, - int minNeighbors, int flags, - Size minSize, Size maxSize ) = 0; - - virtual void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& numDetections, - double scaleFactor, - int minNeighbors, int flags, - Size minSize, Size maxSize ) = 0; - - virtual void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& rejectLevels, - CV_OUT std::vector& levelWeights, - double scaleFactor, - int minNeighbors, int flags, - Size minSize, Size maxSize, - bool outputRejectLevels ) = 0; - - virtual bool isOldFormatCascade() const = 0; - virtual Size getOriginalWindowSize() const = 0; - virtual int getFeatureType() const = 0; - virtual void* getOldCascade() = 0; - - class CV_EXPORTS MaskGenerator - { - public: - virtual ~MaskGenerator() {} - virtual Mat generateMask(const Mat& src)=0; - virtual void initializeMask(const Mat& /*src*/) { } - }; - virtual void setMaskGenerator(const Ptr& maskGenerator) = 0; - virtual Ptr getMaskGenerator() = 0; -}; - -/** @example samples/cpp/facedetect.cpp -This program demonstrates usage of the Cascade classifier class -\image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254 -*/ -/** @brief Cascade classifier class for object detection. - */ -class CV_EXPORTS_W CascadeClassifier -{ -public: - CV_WRAP CascadeClassifier(); - /** @brief Loads a classifier from a file. - - @param filename Name of the file from which the classifier is loaded. - */ - CV_WRAP CascadeClassifier(const String& filename); - ~CascadeClassifier(); - /** @brief Checks whether the classifier has been loaded. - */ - CV_WRAP bool empty() const; - /** @brief Loads a classifier from a file. - - @param filename Name of the file from which the classifier is loaded. The file may contain an old - HAAR classifier trained by the haartraining application or a new cascade classifier trained by the - traincascade application. - */ - CV_WRAP bool load( const String& filename ); - /** @brief Reads a classifier from a FileStorage node. - - @note The file may contain a new cascade classifier (trained by the traincascade application) only. - */ - CV_WRAP bool read( const FileNode& node ); - - /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list - of rectangles. - - @param image Matrix of the type CV_8U containing an image where objects are detected. - @param objects Vector of rectangles where each rectangle contains the detected object, the - rectangles may be partially outside the original image. - @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. - @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have - to retain it. - @param flags Parameter with the same meaning for an old cascade as in the function - cvHaarDetectObjects. It is not used for a new cascade. - @param minSize Minimum possible object size. Objects smaller than that are ignored. - @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. - */ - CV_WRAP void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - double scaleFactor = 1.1, - int minNeighbors = 3, int flags = 0, - Size minSize = Size(), - Size maxSize = Size() ); - - /** @overload - @param image Matrix of the type CV_8U containing an image where objects are detected. - @param objects Vector of rectangles where each rectangle contains the detected object, the - rectangles may be partially outside the original image. - @param numDetections Vector of detection numbers for the corresponding objects. An object's number - of detections is the number of neighboring positively classified rectangles that were joined - together to form the object. - @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. - @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have - to retain it. - @param flags Parameter with the same meaning for an old cascade as in the function - cvHaarDetectObjects. It is not used for a new cascade. - @param minSize Minimum possible object size. Objects smaller than that are ignored. - @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. - */ - CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& numDetections, - double scaleFactor=1.1, - int minNeighbors=3, int flags=0, - Size minSize=Size(), - Size maxSize=Size() ); - - /** @overload - This function allows you to retrieve the final stage decision certainty of classification. - For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter. - For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage. - This value can then be used to separate strong from weaker classifications. - - A code sample on how to use it efficiently can be found below: - @code - Mat img; - vector weights; - vector levels; - vector detections; - CascadeClassifier model("/path/to/your/model.xml"); - model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true); - cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl; - @endcode - */ - CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image, - CV_OUT std::vector& objects, - CV_OUT std::vector& rejectLevels, - CV_OUT std::vector& levelWeights, - double scaleFactor = 1.1, - int minNeighbors = 3, int flags = 0, - Size minSize = Size(), - Size maxSize = Size(), - bool outputRejectLevels = false ); - - CV_WRAP bool isOldFormatCascade() const; - CV_WRAP Size getOriginalWindowSize() const; - CV_WRAP int getFeatureType() const; - void* getOldCascade(); - - CV_WRAP static bool convert(const String& oldcascade, const String& newcascade); - - void setMaskGenerator(const Ptr& maskGenerator); - Ptr getMaskGenerator(); - - Ptr cc; -}; - -CV_EXPORTS Ptr createFaceDetectionMaskGenerator(); -//! @} - -//! @addtogroup objdetect_hog -//! @{ -//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// - -//! struct for detection region of interest (ROI) -struct DetectionROI -{ - //! scale(size) of the bounding box - double scale; - //! set of requested locations to be evaluated - std::vector locations; - //! vector that will contain confidence values for each location - std::vector confidences; -}; - -/**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector. - -the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 . - -useful links: - -https://hal.inria.fr/inria-00548512/document/ - -https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients - -https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor - -http://www.learnopencv.com/histogram-of-oriented-gradients - -http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial - - */ -struct CV_EXPORTS_W HOGDescriptor -{ -public: - enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType - }; - enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value. - }; - enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW }; - - /**@brief Creates the HOG descriptor and detector with default parameters. - - aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 ) - */ - CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8), - cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), - histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), - free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false) - {} - - /** @overload - @param _winSize sets winSize with given value. - @param _blockSize sets blockSize with given value. - @param _blockStride sets blockStride with given value. - @param _cellSize sets cellSize with given value. - @param _nbins sets nbins with given value. - @param _derivAperture sets derivAperture with given value. - @param _winSigma sets winSigma with given value. - @param _histogramNormType sets histogramNormType with given value. - @param _L2HysThreshold sets L2HysThreshold with given value. - @param _gammaCorrection sets gammaCorrection with given value. - @param _nlevels sets nlevels with given value. - @param _signedGradient sets signedGradient with given value. - */ - CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride, - Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1, - HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys, - double _L2HysThreshold=0.2, bool _gammaCorrection=false, - int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false) - : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize), - nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma), - histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold), - gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient) - {} - - /** @overload - - Creates the HOG descriptor and detector and loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file. - @param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier. - */ - CV_WRAP HOGDescriptor(const String& filename) - { - load(filename); - } - - /** @overload - @param d the HOGDescriptor which cloned to create a new one. - */ - HOGDescriptor(const HOGDescriptor& d) - { - d.copyTo(*this); - } - - /**@brief Default destructor. - */ - virtual ~HOGDescriptor() {} - - /**@brief Returns the number of coefficients required for the classification. - */ - CV_WRAP size_t getDescriptorSize() const; - - /** @brief Checks if detector size equal to descriptor size. - */ - CV_WRAP bool checkDetectorSize() const; - - /** @brief Returns winSigma value - */ - CV_WRAP double getWinSigma() const; - - /**@example samples/cpp/peopledetect.cpp - */ - /**@brief Sets coefficients for the linear SVM classifier. - @param svmdetector coefficients for the linear SVM classifier. - */ - CV_WRAP virtual void setSVMDetector(InputArray svmdetector); - - /** @brief Reads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file node. - @param fn File node - */ - virtual bool read(FileNode& fn); - - /** @brief Stores HOGDescriptor parameters and coefficients for the linear SVM classifier in a file storage. - @param fs File storage - @param objname Object name - */ - virtual void write(FileStorage& fs, const String& objname) const; - - /** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file - @param filename Name of the file to read. - @param objname The optional name of the node to read (if empty, the first top-level node will be used). - */ - CV_WRAP virtual bool load(const String& filename, const String& objname = String()); - - /** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file - @param filename File name - @param objname Object name - */ - CV_WRAP virtual void save(const String& filename, const String& objname = String()) const; - - /** @brief clones the HOGDescriptor - @param c cloned HOGDescriptor - */ - virtual void copyTo(HOGDescriptor& c) const; - - /**@example samples/cpp/train_HOG.cpp - */ - /** @brief Computes HOG descriptors of given image. - @param img Matrix of the type CV_8U containing an image where HOG features will be calculated. - @param descriptors Matrix of the type CV_32F - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param locations Vector of Point - */ - CV_WRAP virtual void compute(InputArray img, - CV_OUT std::vector& descriptors, - Size winStride = Size(), Size padding = Size(), - const std::vector& locations = std::vector()) const; - - /** @brief Performs object detection without a multi-scale window. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. - @param weights Vector that will contain confidence values for each detected object. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param searchLocations Vector of Point includes set of requested locations to be evaluated. - */ - CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, - CV_OUT std::vector& weights, - double hitThreshold = 0, Size winStride = Size(), - Size padding = Size(), - const std::vector& searchLocations = std::vector()) const; - - /** @brief Performs object detection without a multi-scale window. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param searchLocations Vector of Point includes locations to search. - */ - virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, - double hitThreshold = 0, Size winStride = Size(), - Size padding = Size(), - const std::vector& searchLocations=std::vector()) const; - - /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list - of rectangles. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of rectangles where each rectangle contains the detected object. - @param foundWeights Vector that will contain confidence values for each detected object. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param scale Coefficient of the detection window increase. - @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered - by many rectangles. 0 means not to perform grouping. - @param useMeanshiftGrouping indicates grouping algorithm - */ - CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, - CV_OUT std::vector& foundWeights, double hitThreshold = 0, - Size winStride = Size(), Size padding = Size(), double scale = 1.05, - double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; - - /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list - of rectangles. - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of rectangles where each rectangle contains the detected object. - @param hitThreshold Threshold for the distance between features and SVM classifying plane. - Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). - But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param winStride Window stride. It must be a multiple of block stride. - @param padding Padding - @param scale Coefficient of the detection window increase. - @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered - by many rectangles. 0 means not to perform grouping. - @param useMeanshiftGrouping indicates grouping algorithm - */ - virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, - double hitThreshold = 0, Size winStride = Size(), - Size padding = Size(), double scale = 1.05, - double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; - - /** @brief Computes gradients and quantized gradient orientations. - @param img Matrix contains the image to be computed - @param grad Matrix of type CV_32FC2 contains computed gradients - @param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations - @param paddingTL Padding from top-left - @param paddingBR Padding from bottom-right - */ - CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs, - Size paddingTL = Size(), Size paddingBR = Size()) const; - - /** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows). - */ - CV_WRAP static std::vector getDefaultPeopleDetector(); - - /**@example samples/tapi/hog.cpp - */ - /** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows). - */ - CV_WRAP static std::vector getDaimlerPeopleDetector(); - - //! Detection window size. Align to block size and block stride. Default value is Size(64,128). - CV_PROP Size winSize; - - //! Block size in pixels. Align to cell size. Default value is Size(16,16). - CV_PROP Size blockSize; - - //! Block stride. It must be a multiple of cell size. Default value is Size(8,8). - CV_PROP Size blockStride; - - //! Cell size. Default value is Size(8,8). - CV_PROP Size cellSize; - - //! Number of bins used in the calculation of histogram of gradients. Default value is 9. - CV_PROP int nbins; - - //! not documented - CV_PROP int derivAperture; - - //! Gaussian smoothing window parameter. - CV_PROP double winSigma; - - //! histogramNormType - CV_PROP HOGDescriptor::HistogramNormType histogramNormType; - - //! L2-Hys normalization method shrinkage. - CV_PROP double L2HysThreshold; - - //! Flag to specify whether the gamma correction preprocessing is required or not. - CV_PROP bool gammaCorrection; - - //! coefficients for the linear SVM classifier. - CV_PROP std::vector svmDetector; - - //! coefficients for the linear SVM classifier used when OpenCL is enabled - UMat oclSvmDetector; - - //! not documented - float free_coef; - - //! Maximum number of detection window increases. Default value is 64 - CV_PROP int nlevels; - - //! Indicates signed gradient will be used or not - CV_PROP bool signedGradient; - - /** @brief evaluate specified ROI and return confidence value for each location - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param locations Vector of Point - @param foundLocations Vector of Point where each Point is detected object's top-left point. - @param confidences confidences - @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually - it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if - the free coefficient is omitted (which is allowed), you can specify it manually here - @param winStride winStride - @param padding padding - */ - virtual void detectROI(InputArray img, const std::vector &locations, - CV_OUT std::vector& foundLocations, CV_OUT std::vector& confidences, - double hitThreshold = 0, cv::Size winStride = Size(), - cv::Size padding = Size()) const; - - /** @brief evaluate specified ROI and return confidence value for each location in multiple scales - @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. - @param foundLocations Vector of rectangles where each rectangle contains the detected object. - @param locations Vector of DetectionROI - @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified - in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here. - @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. - */ - virtual void detectMultiScaleROI(InputArray img, - CV_OUT std::vector& foundLocations, - std::vector& locations, - double hitThreshold = 0, - int groupThreshold = 0) const; - - /** @brief Groups the object candidate rectangles. - @param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.) - @param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.) - @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. - @param eps Relative difference between sides of the rectangles to merge them into a group. - */ - void groupRectangles(std::vector& rectList, std::vector& weights, int groupThreshold, double eps) const; -}; -//! @} - -//! @addtogroup objdetect_qrcode -//! @{ - -class CV_EXPORTS_W QRCodeEncoder { -protected: - QRCodeEncoder(); // use ::create() -public: - virtual ~QRCodeEncoder(); - - enum EncodeMode { - MODE_AUTO = -1, - MODE_NUMERIC = 1, // 0b0001 - MODE_ALPHANUMERIC = 2, // 0b0010 - MODE_BYTE = 4, // 0b0100 - MODE_ECI = 7, // 0b0111 - MODE_KANJI = 8, // 0b1000 - MODE_STRUCTURED_APPEND = 3 // 0b0011 - }; - - enum CorrectionLevel { - CORRECT_LEVEL_L = 0, - CORRECT_LEVEL_M = 1, - CORRECT_LEVEL_Q = 2, - CORRECT_LEVEL_H = 3 - }; - - enum ECIEncodings { - ECI_UTF8 = 26 - }; - - /** @brief QR code encoder parameters. */ - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - - //! The optional version of QR code (by default - maximum possible depending on the length of the string). - CV_PROP_RW int version; - - //! The optional level of error correction (by default - the lowest). - CV_PROP_RW CorrectionLevel correction_level; - - //! The optional encoding mode - Numeric, Alphanumeric, Byte, Kanji, ECI or Structured Append. - CV_PROP_RW EncodeMode mode; - - //! The optional number of QR codes to generate in Structured Append mode. - CV_PROP_RW int structure_number; - }; - - /** @brief Constructor - @param parameters QR code encoder parameters QRCodeEncoder::Params - */ - static CV_WRAP - Ptr create(const QRCodeEncoder::Params& parameters = QRCodeEncoder::Params()); - - /** @brief Generates QR code from input string. - @param encoded_info Input string to encode. - @param qrcode Generated QR code. - */ - CV_WRAP virtual void encode(const String& encoded_info, OutputArray qrcode) = 0; - - /** @brief Generates QR code from input string in Structured Append mode. The encoded message is splitting over a number of QR codes. - @param encoded_info Input string to encode. - @param qrcodes Vector of generated QR codes. - */ - CV_WRAP virtual void encodeStructuredAppend(const String& encoded_info, OutputArrayOfArrays qrcodes) = 0; - -}; -class CV_EXPORTS_W_SIMPLE QRCodeDetector : public GraphicalCodeDetector -{ -public: - CV_WRAP QRCodeDetector(); - - /** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection. - @param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern - of the scheme 1:1:3:1:1 according to QR code standard. - */ - CV_WRAP QRCodeDetector& setEpsX(double epsX); - /** @brief sets the epsilon used during the vertical scan of QR code stop marker detection. - @param epsY Epsilon neighborhood, which allows you to determine the vertical pattern - of the scheme 1:1:3:1:1 according to QR code standard. - */ - CV_WRAP QRCodeDetector& setEpsY(double epsY); - - /** @brief use markers to improve the position of the corners of the QR code - * - * alignmentMarkers using by default - */ - CV_WRAP QRCodeDetector& setUseAlignmentMarkers(bool useAlignmentMarkers); - - /** @brief Decodes QR code on a curved surface in image once it's found by the detect() method. - - Returns UTF8-encoded output string or empty string if the code cannot be decoded. - @param img grayscale or color (BGR) image containing QR code. - @param points Quadrangle vertices found by detect() method (or some other algorithm). - @param straight_qrcode The optional output image containing rectified and binarized QR code - */ - CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray()); - - /** @brief Both detects and decodes QR code on a curved surface - - @param img grayscale or color (BGR) image containing QR code. - @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found. - @param straight_qrcode The optional output image containing rectified and binarized QR code - */ - CV_WRAP std::string detectAndDecodeCurved(InputArray img, OutputArray points=noArray(), - OutputArray straight_qrcode = noArray()); -}; - -class CV_EXPORTS_W_SIMPLE QRCodeDetectorAruco : public GraphicalCodeDetector { -public: - CV_WRAP QRCodeDetectorAruco(); - - struct CV_EXPORTS_W_SIMPLE Params { - CV_WRAP Params(); - - /** @brief The minimum allowed pixel size of a QR module in the smallest image in the image pyramid, default 4.f */ - CV_PROP_RW float minModuleSizeInPyramid; - - /** @brief The maximum allowed relative rotation for finder patterns in the same QR code, default pi/12 */ - CV_PROP_RW float maxRotation; - - /** @brief The maximum allowed relative mismatch in module sizes for finder patterns in the same QR code, default 1.75f */ - CV_PROP_RW float maxModuleSizeMismatch; - - /** @brief The maximum allowed module relative mismatch for timing pattern module, default 2.f - * - * If relative mismatch of timing pattern module more this value, penalty points will be added. - * If a lot of penalty points are added, QR code will be rejected. */ - CV_PROP_RW float maxTimingPatternMismatch; - - /** @brief The maximum allowed percentage of penalty points out of total pins in timing pattern, default 0.4f */ - CV_PROP_RW float maxPenalties; - - /** @brief The maximum allowed relative color mismatch in the timing pattern, default 0.2f*/ - CV_PROP_RW float maxColorsMismatch; - - /** @brief The algorithm find QR codes with almost minimum timing pattern score and minimum size, default 0.9f - * - * The QR code with the minimum "timing pattern score" and minimum "size" is selected as the best QR code. - * If for the current QR code "timing pattern score" * scaleTimingPatternScore < "previous timing pattern score" and "size" < "previous size", then - * current QR code set as the best QR code. */ - CV_PROP_RW float scaleTimingPatternScore; - }; - - /** @brief QR code detector constructor for Aruco-based algorithm. See cv::QRCodeDetectorAruco::Params */ - CV_WRAP explicit QRCodeDetectorAruco(const QRCodeDetectorAruco::Params& params); - - /** @brief Detector parameters getter. See cv::QRCodeDetectorAruco::Params */ - CV_WRAP const QRCodeDetectorAruco::Params& getDetectorParameters() const; - - /** @brief Detector parameters setter. See cv::QRCodeDetectorAruco::Params */ - CV_WRAP QRCodeDetectorAruco& setDetectorParameters(const QRCodeDetectorAruco::Params& params); - - /** @brief Aruco detector parameters are used to search for the finder patterns. */ - CV_WRAP const aruco::DetectorParameters& getArucoParameters() const; - - /** @brief Aruco detector parameters are used to search for the finder patterns. */ - CV_WRAP void setArucoParameters(const aruco::DetectorParameters& params); -}; - -//! @} -} - -#include "opencv2/objdetect/detection_based_tracker.hpp" -#include "opencv2/objdetect/face.hpp" -#include "opencv2/objdetect/charuco_detector.hpp" -#include "opencv2/objdetect/barcode.hpp" - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_OBJDETECT_HPP +#define OPENCV_OBJDETECT_HPP + +#include "opencv2/core.hpp" +#include "opencv2/objdetect/aruco_detector.hpp" +#include "opencv2/objdetect/graphical_code_detector.hpp" + +/** +@defgroup objdetect Object Detection + +@{ + @defgroup objdetect_cascade_classifier Cascade Classifier for Object Detection + + The object detector described below has been initially proposed by Paul Viola @cite Viola01 and + improved by Rainer Lienhart @cite Lienhart02 . + + First, a classifier (namely a *cascade of boosted classifiers working with haar-like features*) is + trained with a few hundred sample views of a particular object (i.e., a face or a car), called + positive examples, that are scaled to the same size (say, 20x20), and negative examples - arbitrary + images of the same size. + + After a classifier is trained, it can be applied to a region of interest (of the same size as used + during the training) in an input image. The classifier outputs a "1" if the region is likely to show + the object (i.e., face/car), and "0" otherwise. To search for the object in the whole image one can + move the search window across the image and check every location using the classifier. The + classifier is designed so that it can be easily "resized" in order to be able to find the objects of + interest at different sizes, which is more efficient than resizing the image itself. So, to find an + object of an unknown size in the image the scan procedure should be done several times at different + scales. + + The word "cascade" in the classifier name means that the resultant classifier consists of several + simpler classifiers (*stages*) that are applied subsequently to a region of interest until at some + stage the candidate is rejected or all the stages are passed. The word "boosted" means that the + classifiers at every stage of the cascade are complex themselves and they are built out of basic + classifiers using one of four different boosting techniques (weighted voting). Currently Discrete + Adaboost, Real Adaboost, Gentle Adaboost and Logitboost are supported. The basic classifiers are + decision-tree classifiers with at least 2 leaves. Haar-like features are the input to the basic + classifiers, and are calculated as described below. The current algorithm uses the following + Haar-like features: + + ![image](pics/haarfeatures.png) + + The feature used in a particular classifier is specified by its shape (1a, 2b etc.), position within + the region of interest and the scale (this scale is not the same as the scale used at the detection + stage, though these two scales are multiplied). For example, in the case of the third line feature + (2c) the response is calculated as the difference between the sum of image pixels under the + rectangle covering the whole feature (including the two white stripes and the black stripe in the + middle) and the sum of the image pixels under the black stripe multiplied by 3 in order to + compensate for the differences in the size of areas. The sums of pixel values over a rectangular + regions are calculated rapidly using integral images (see below and the integral description). + + Check @ref tutorial_cascade_classifier "the corresponding tutorial" for more details. + + The following reference is for the detection part only. There is a separate application called + opencv_traincascade that can train a cascade of boosted classifiers from a set of samples. + + @note In the new C++ interface it is also possible to use LBP (local binary pattern) features in + addition to Haar-like features. .. [Viola01] Paul Viola and Michael J. Jones. Rapid Object Detection + using a Boosted Cascade of Simple Features. IEEE CVPR, 2001. The paper is available online at + + + @defgroup objdetect_hog HOG (Histogram of Oriented Gradients) descriptor and object detector + @defgroup objdetect_barcode Barcode detection and decoding + @defgroup objdetect_qrcode QRCode detection and encoding + @defgroup objdetect_dnn_face DNN-based face detection and recognition + + Check @ref tutorial_dnn_face "the corresponding tutorial" for more details. + + @defgroup objdetect_common Common functions and classes + @defgroup objdetect_aruco ArUco markers and boards detection for robust camera pose estimation + @{ + ArUco Marker Detection + Square fiducial markers (also known as Augmented Reality Markers) are useful for easy, + fast and robust camera pose estimation. + + The main functionality of ArucoDetector class is detection of markers in an image. If the markers are grouped + as a board, then you can try to recover the missing markers with ArucoDetector::refineDetectedMarkers(). + ArUco markers can also be used for advanced chessboard corner finding. To do this, group the markers in the + CharucoBoard and find the corners of the chessboard with the CharucoDetector::detectBoard(). + + The implementation is based on the ArUco Library by R. Muñoz-Salinas and S. Garrido-Jurado @cite Aruco2014. + + Markers can also be detected based on the AprilTag 2 @cite wang2016iros fiducial detection method. + + @sa @cite Aruco2014 + This code has been originally developed by Sergio Garrido-Jurado as a project + for Google Summer of Code 2015 (GSoC 15). + @} + +@} + */ + +typedef struct CvHaarClassifierCascade CvHaarClassifierCascade; + +namespace cv +{ + +//! @addtogroup objdetect_common +//! @{ + +///////////////////////////// Object Detection //////////////////////////// + +/** @brief This class is used for grouping object candidates detected by Cascade Classifier, HOG etc. + +instance of the class is to be passed to cv::partition + */ +class CV_EXPORTS SimilarRects +{ +public: + SimilarRects(double _eps) : eps(_eps) {} + inline bool operator()(const Rect& r1, const Rect& r2) const + { + double delta = eps * ((std::min)(r1.width, r2.width) + (std::min)(r1.height, r2.height)) * 0.5; + return std::abs(r1.x - r2.x) <= delta && + std::abs(r1.y - r2.y) <= delta && + std::abs(r1.x + r1.width - r2.x - r2.width) <= delta && + std::abs(r1.y + r1.height - r2.y - r2.height) <= delta; + } + double eps; +}; + +/** @brief Groups the object candidate rectangles. + +@param rectList Input/output vector of rectangles. Output vector includes retained and grouped +rectangles. (The Python list is not modified in place.) +@param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a +group of rectangles to retain it. +@param eps Relative difference between sides of the rectangles to merge them into a group. + +The function is a wrapper for the generic function partition . It clusters all the input rectangles +using the rectangle equivalence criteria that combines rectangles with similar sizes and similar +locations. The similarity is defined by eps. When eps=0 , no clustering is done at all. If +\f$\texttt{eps}\rightarrow +\inf\f$ , all the rectangles are put in one cluster. Then, the small +clusters containing less than or equal to groupThreshold rectangles are rejected. In each other +cluster, the average rectangle is computed and put into the output rectangle list. + */ +CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, double eps = 0.2); +/** @overload */ +CV_EXPORTS_W void groupRectangles(CV_IN_OUT std::vector& rectList, CV_OUT std::vector& weights, + int groupThreshold, double eps = 0.2); +/** @overload */ +CV_EXPORTS void groupRectangles(std::vector& rectList, int groupThreshold, + double eps, std::vector* weights, std::vector* levelWeights ); +/** @overload */ +CV_EXPORTS void groupRectangles(std::vector& rectList, std::vector& rejectLevels, + std::vector& levelWeights, int groupThreshold, double eps = 0.2); +/** @overload */ +CV_EXPORTS void groupRectangles_meanshift(std::vector& rectList, std::vector& foundWeights, + std::vector& foundScales, + double detectThreshold = 0.0, Size winDetSize = Size(64, 128)); +//! @} + +//! @addtogroup objdetect_cascade_classifier +//! @{ + +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvHaarClassifierCascade* obj) const; }; + +enum { CASCADE_DO_CANNY_PRUNING = 1, + CASCADE_SCALE_IMAGE = 2, + CASCADE_FIND_BIGGEST_OBJECT = 4, + CASCADE_DO_ROUGH_SEARCH = 8 + }; + +class CV_EXPORTS_W BaseCascadeClassifier : public Algorithm +{ +public: + virtual ~BaseCascadeClassifier(); + virtual bool empty() const CV_OVERRIDE = 0; + virtual bool load( const String& filename ) = 0; + virtual void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + double scaleFactor, + int minNeighbors, int flags, + Size minSize, Size maxSize ) = 0; + + virtual void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& numDetections, + double scaleFactor, + int minNeighbors, int flags, + Size minSize, Size maxSize ) = 0; + + virtual void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& rejectLevels, + CV_OUT std::vector& levelWeights, + double scaleFactor, + int minNeighbors, int flags, + Size minSize, Size maxSize, + bool outputRejectLevels ) = 0; + + virtual bool isOldFormatCascade() const = 0; + virtual Size getOriginalWindowSize() const = 0; + virtual int getFeatureType() const = 0; + virtual void* getOldCascade() = 0; + + class CV_EXPORTS MaskGenerator + { + public: + virtual ~MaskGenerator() {} + virtual Mat generateMask(const Mat& src)=0; + virtual void initializeMask(const Mat& /*src*/) { } + }; + virtual void setMaskGenerator(const Ptr& maskGenerator) = 0; + virtual Ptr getMaskGenerator() = 0; +}; + +/** @example samples/cpp/facedetect.cpp +This program demonstrates usage of the Cascade classifier class +\image html Cascade_Classifier_Tutorial_Result_Haar.jpg "Sample screenshot" width=321 height=254 +*/ +/** @brief Cascade classifier class for object detection. + */ +class CV_EXPORTS_W CascadeClassifier +{ +public: + CV_WRAP CascadeClassifier(); + /** @brief Loads a classifier from a file. + + @param filename Name of the file from which the classifier is loaded. + */ + CV_WRAP CascadeClassifier(const String& filename); + ~CascadeClassifier(); + /** @brief Checks whether the classifier has been loaded. + */ + CV_WRAP bool empty() const; + /** @brief Loads a classifier from a file. + + @param filename Name of the file from which the classifier is loaded. The file may contain an old + HAAR classifier trained by the haartraining application or a new cascade classifier trained by the + traincascade application. + */ + CV_WRAP bool load( const String& filename ); + /** @brief Reads a classifier from a FileStorage node. + + @note The file may contain a new cascade classifier (trained by the traincascade application) only. + */ + CV_WRAP bool read( const FileNode& node ); + + /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list + of rectangles. + + @param image Matrix of the type CV_8U containing an image where objects are detected. + @param objects Vector of rectangles where each rectangle contains the detected object, the + rectangles may be partially outside the original image. + @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. + @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have + to retain it. + @param flags Parameter with the same meaning for an old cascade as in the function + cvHaarDetectObjects. It is not used for a new cascade. + @param minSize Minimum possible object size. Objects smaller than that are ignored. + @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. + */ + CV_WRAP void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + double scaleFactor = 1.1, + int minNeighbors = 3, int flags = 0, + Size minSize = Size(), + Size maxSize = Size() ); + + /** @overload + @param image Matrix of the type CV_8U containing an image where objects are detected. + @param objects Vector of rectangles where each rectangle contains the detected object, the + rectangles may be partially outside the original image. + @param numDetections Vector of detection numbers for the corresponding objects. An object's number + of detections is the number of neighboring positively classified rectangles that were joined + together to form the object. + @param scaleFactor Parameter specifying how much the image size is reduced at each image scale. + @param minNeighbors Parameter specifying how many neighbors each candidate rectangle should have + to retain it. + @param flags Parameter with the same meaning for an old cascade as in the function + cvHaarDetectObjects. It is not used for a new cascade. + @param minSize Minimum possible object size. Objects smaller than that are ignored. + @param maxSize Maximum possible object size. Objects larger than that are ignored. If `maxSize == minSize` model is evaluated on single scale. + */ + CV_WRAP_AS(detectMultiScale2) void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& numDetections, + double scaleFactor=1.1, + int minNeighbors=3, int flags=0, + Size minSize=Size(), + Size maxSize=Size() ); + + /** @overload + This function allows you to retrieve the final stage decision certainty of classification. + For this, one needs to set `outputRejectLevels` on true and provide the `rejectLevels` and `levelWeights` parameter. + For each resulting detection, `levelWeights` will then contain the certainty of classification at the final stage. + This value can then be used to separate strong from weaker classifications. + + A code sample on how to use it efficiently can be found below: + @code + Mat img; + vector weights; + vector levels; + vector detections; + CascadeClassifier model("/path/to/your/model.xml"); + model.detectMultiScale(img, detections, levels, weights, 1.1, 3, 0, Size(), Size(), true); + cerr << "Detection " << detections[0] << " with weight " << weights[0] << endl; + @endcode + */ + CV_WRAP_AS(detectMultiScale3) void detectMultiScale( InputArray image, + CV_OUT std::vector& objects, + CV_OUT std::vector& rejectLevels, + CV_OUT std::vector& levelWeights, + double scaleFactor = 1.1, + int minNeighbors = 3, int flags = 0, + Size minSize = Size(), + Size maxSize = Size(), + bool outputRejectLevels = false ); + + CV_WRAP bool isOldFormatCascade() const; + CV_WRAP Size getOriginalWindowSize() const; + CV_WRAP int getFeatureType() const; + void* getOldCascade(); + + CV_WRAP static bool convert(const String& oldcascade, const String& newcascade); + + void setMaskGenerator(const Ptr& maskGenerator); + Ptr getMaskGenerator(); + + Ptr cc; +}; + +CV_EXPORTS Ptr createFaceDetectionMaskGenerator(); +//! @} + +//! @addtogroup objdetect_hog +//! @{ +//////////////// HOG (Histogram-of-Oriented-Gradients) Descriptor and Object Detector ////////////// + +//! struct for detection region of interest (ROI) +struct DetectionROI +{ + //! scale(size) of the bounding box + double scale; + //! set of requested locations to be evaluated + std::vector locations; + //! vector that will contain confidence values for each location + std::vector confidences; +}; + +/**@brief Implementation of HOG (Histogram of Oriented Gradients) descriptor and object detector. + +the HOG descriptor algorithm introduced by Navneet Dalal and Bill Triggs @cite Dalal2005 . + +useful links: + +https://hal.inria.fr/inria-00548512/document/ + +https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients + +https://software.intel.com/en-us/ipp-dev-reference-histogram-of-oriented-gradients-hog-descriptor + +http://www.learnopencv.com/histogram-of-oriented-gradients + +http://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial + + */ +struct CV_EXPORTS_W HOGDescriptor +{ +public: + enum HistogramNormType { L2Hys = 0 //!< Default histogramNormType + }; + enum { DEFAULT_NLEVELS = 64 //!< Default nlevels value. + }; + enum DescriptorStorageFormat { DESCR_FORMAT_COL_BY_COL, DESCR_FORMAT_ROW_BY_ROW }; + + /**@brief Creates the HOG descriptor and detector with default parameters. + + aqual to HOGDescriptor(Size(64,128), Size(16,16), Size(8,8), Size(8,8), 9 ) + */ + CV_WRAP HOGDescriptor() : winSize(64,128), blockSize(16,16), blockStride(8,8), + cellSize(8,8), nbins(9), derivAperture(1), winSigma(-1), + histogramNormType(HOGDescriptor::L2Hys), L2HysThreshold(0.2), gammaCorrection(true), + free_coef(-1.f), nlevels(HOGDescriptor::DEFAULT_NLEVELS), signedGradient(false) + {} + + /** @overload + @param _winSize sets winSize with given value. + @param _blockSize sets blockSize with given value. + @param _blockStride sets blockStride with given value. + @param _cellSize sets cellSize with given value. + @param _nbins sets nbins with given value. + @param _derivAperture sets derivAperture with given value. + @param _winSigma sets winSigma with given value. + @param _histogramNormType sets histogramNormType with given value. + @param _L2HysThreshold sets L2HysThreshold with given value. + @param _gammaCorrection sets gammaCorrection with given value. + @param _nlevels sets nlevels with given value. + @param _signedGradient sets signedGradient with given value. + */ + CV_WRAP HOGDescriptor(Size _winSize, Size _blockSize, Size _blockStride, + Size _cellSize, int _nbins, int _derivAperture=1, double _winSigma=-1, + HOGDescriptor::HistogramNormType _histogramNormType=HOGDescriptor::L2Hys, + double _L2HysThreshold=0.2, bool _gammaCorrection=false, + int _nlevels=HOGDescriptor::DEFAULT_NLEVELS, bool _signedGradient=false) + : winSize(_winSize), blockSize(_blockSize), blockStride(_blockStride), cellSize(_cellSize), + nbins(_nbins), derivAperture(_derivAperture), winSigma(_winSigma), + histogramNormType(_histogramNormType), L2HysThreshold(_L2HysThreshold), + gammaCorrection(_gammaCorrection), free_coef(-1.f), nlevels(_nlevels), signedGradient(_signedGradient) + {} + + /** @overload + + Creates the HOG descriptor and detector and loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file. + @param filename The file name containing HOGDescriptor properties and coefficients for the linear SVM classifier. + */ + CV_WRAP HOGDescriptor(const String& filename) + { + load(filename); + } + + /** @overload + @param d the HOGDescriptor which cloned to create a new one. + */ + HOGDescriptor(const HOGDescriptor& d) + { + d.copyTo(*this); + } + + /**@brief Default destructor. + */ + virtual ~HOGDescriptor() {} + + /**@brief Returns the number of coefficients required for the classification. + */ + CV_WRAP size_t getDescriptorSize() const; + + /** @brief Checks if detector size equal to descriptor size. + */ + CV_WRAP bool checkDetectorSize() const; + + /** @brief Returns winSigma value + */ + CV_WRAP double getWinSigma() const; + + /**@example samples/cpp/peopledetect.cpp + */ + /**@brief Sets coefficients for the linear SVM classifier. + @param svmdetector coefficients for the linear SVM classifier. + */ + CV_WRAP virtual void setSVMDetector(InputArray svmdetector); + + /** @brief Reads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file node. + @param fn File node + */ + virtual bool read(FileNode& fn); + + /** @brief Stores HOGDescriptor parameters and coefficients for the linear SVM classifier in a file storage. + @param fs File storage + @param objname Object name + */ + virtual void write(FileStorage& fs, const String& objname) const; + + /** @brief loads HOGDescriptor parameters and coefficients for the linear SVM classifier from a file + @param filename Name of the file to read. + @param objname The optional name of the node to read (if empty, the first top-level node will be used). + */ + CV_WRAP virtual bool load(const String& filename, const String& objname = String()); + + /** @brief saves HOGDescriptor parameters and coefficients for the linear SVM classifier to a file + @param filename File name + @param objname Object name + */ + CV_WRAP virtual void save(const String& filename, const String& objname = String()) const; + + /** @brief clones the HOGDescriptor + @param c cloned HOGDescriptor + */ + virtual void copyTo(HOGDescriptor& c) const; + + /**@example samples/cpp/train_HOG.cpp + */ + /** @brief Computes HOG descriptors of given image. + @param img Matrix of the type CV_8U containing an image where HOG features will be calculated. + @param descriptors Matrix of the type CV_32F + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param locations Vector of Point + */ + CV_WRAP virtual void compute(InputArray img, + CV_OUT std::vector& descriptors, + Size winStride = Size(), Size padding = Size(), + const std::vector& locations = std::vector()) const; + + /** @brief Performs object detection without a multi-scale window. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. + @param weights Vector that will contain confidence values for each detected object. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param searchLocations Vector of Point includes set of requested locations to be evaluated. + */ + CV_WRAP virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, + CV_OUT std::vector& weights, + double hitThreshold = 0, Size winStride = Size(), + Size padding = Size(), + const std::vector& searchLocations = std::vector()) const; + + /** @brief Performs object detection without a multi-scale window. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of point where each point contains left-top corner point of detected object boundaries. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param searchLocations Vector of Point includes locations to search. + */ + virtual void detect(InputArray img, CV_OUT std::vector& foundLocations, + double hitThreshold = 0, Size winStride = Size(), + Size padding = Size(), + const std::vector& searchLocations=std::vector()) const; + + /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list + of rectangles. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of rectangles where each rectangle contains the detected object. + @param foundWeights Vector that will contain confidence values for each detected object. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param scale Coefficient of the detection window increase. + @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered + by many rectangles. 0 means not to perform grouping. + @param useMeanshiftGrouping indicates grouping algorithm + */ + CV_WRAP virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, + CV_OUT std::vector& foundWeights, double hitThreshold = 0, + Size winStride = Size(), Size padding = Size(), double scale = 1.05, + double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; + + /** @brief Detects objects of different sizes in the input image. The detected objects are returned as a list + of rectangles. + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of rectangles where each rectangle contains the detected object. + @param hitThreshold Threshold for the distance between features and SVM classifying plane. + Usually it is 0 and should be specified in the detector coefficients (as the last free coefficient). + But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param winStride Window stride. It must be a multiple of block stride. + @param padding Padding + @param scale Coefficient of the detection window increase. + @param groupThreshold Coefficient to regulate the similarity threshold. When detected, some objects can be covered + by many rectangles. 0 means not to perform grouping. + @param useMeanshiftGrouping indicates grouping algorithm + */ + virtual void detectMultiScale(InputArray img, CV_OUT std::vector& foundLocations, + double hitThreshold = 0, Size winStride = Size(), + Size padding = Size(), double scale = 1.05, + double groupThreshold = 2.0, bool useMeanshiftGrouping = false) const; + + /** @brief Computes gradients and quantized gradient orientations. + @param img Matrix contains the image to be computed + @param grad Matrix of type CV_32FC2 contains computed gradients + @param angleOfs Matrix of type CV_8UC2 contains quantized gradient orientations + @param paddingTL Padding from top-left + @param paddingBR Padding from bottom-right + */ + CV_WRAP virtual void computeGradient(InputArray img, InputOutputArray grad, InputOutputArray angleOfs, + Size paddingTL = Size(), Size paddingBR = Size()) const; + + /** @brief Returns coefficients of the classifier trained for people detection (for 64x128 windows). + */ + CV_WRAP static std::vector getDefaultPeopleDetector(); + + /**@example samples/tapi/hog.cpp + */ + /** @brief Returns coefficients of the classifier trained for people detection (for 48x96 windows). + */ + CV_WRAP static std::vector getDaimlerPeopleDetector(); + + //! Detection window size. Align to block size and block stride. Default value is Size(64,128). + CV_PROP Size winSize; + + //! Block size in pixels. Align to cell size. Default value is Size(16,16). + CV_PROP Size blockSize; + + //! Block stride. It must be a multiple of cell size. Default value is Size(8,8). + CV_PROP Size blockStride; + + //! Cell size. Default value is Size(8,8). + CV_PROP Size cellSize; + + //! Number of bins used in the calculation of histogram of gradients. Default value is 9. + CV_PROP int nbins; + + //! not documented + CV_PROP int derivAperture; + + //! Gaussian smoothing window parameter. + CV_PROP double winSigma; + + //! histogramNormType + CV_PROP HOGDescriptor::HistogramNormType histogramNormType; + + //! L2-Hys normalization method shrinkage. + CV_PROP double L2HysThreshold; + + //! Flag to specify whether the gamma correction preprocessing is required or not. + CV_PROP bool gammaCorrection; + + //! coefficients for the linear SVM classifier. + CV_PROP std::vector svmDetector; + + //! coefficients for the linear SVM classifier used when OpenCL is enabled + UMat oclSvmDetector; + + //! not documented + float free_coef; + + //! Maximum number of detection window increases. Default value is 64 + CV_PROP int nlevels; + + //! Indicates signed gradient will be used or not + CV_PROP bool signedGradient; + + /** @brief evaluate specified ROI and return confidence value for each location + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param locations Vector of Point + @param foundLocations Vector of Point where each Point is detected object's top-left point. + @param confidences confidences + @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually + it is 0 and should be specified in the detector coefficients (as the last free coefficient). But if + the free coefficient is omitted (which is allowed), you can specify it manually here + @param winStride winStride + @param padding padding + */ + virtual void detectROI(InputArray img, const std::vector &locations, + CV_OUT std::vector& foundLocations, CV_OUT std::vector& confidences, + double hitThreshold = 0, cv::Size winStride = Size(), + cv::Size padding = Size()) const; + + /** @brief evaluate specified ROI and return confidence value for each location in multiple scales + @param img Matrix of the type CV_8U or CV_8UC3 containing an image where objects are detected. + @param foundLocations Vector of rectangles where each rectangle contains the detected object. + @param locations Vector of DetectionROI + @param hitThreshold Threshold for the distance between features and SVM classifying plane. Usually it is 0 and should be specified + in the detector coefficients (as the last free coefficient). But if the free coefficient is omitted (which is allowed), you can specify it manually here. + @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. + */ + virtual void detectMultiScaleROI(InputArray img, + CV_OUT std::vector& foundLocations, + std::vector& locations, + double hitThreshold = 0, + int groupThreshold = 0) const; + + /** @brief Groups the object candidate rectangles. + @param rectList Input/output vector of rectangles. Output vector includes retained and grouped rectangles. (The Python list is not modified in place.) + @param weights Input/output vector of weights of rectangles. Output vector includes weights of retained and grouped rectangles. (The Python list is not modified in place.) + @param groupThreshold Minimum possible number of rectangles minus 1. The threshold is used in a group of rectangles to retain it. + @param eps Relative difference between sides of the rectangles to merge them into a group. + */ + void groupRectangles(std::vector& rectList, std::vector& weights, int groupThreshold, double eps) const; +}; +//! @} + +//! @addtogroup objdetect_qrcode +//! @{ + +class CV_EXPORTS_W QRCodeEncoder { +protected: + QRCodeEncoder(); // use ::create() +public: + virtual ~QRCodeEncoder(); + + enum EncodeMode { + MODE_AUTO = -1, + MODE_NUMERIC = 1, // 0b0001 + MODE_ALPHANUMERIC = 2, // 0b0010 + MODE_BYTE = 4, // 0b0100 + MODE_ECI = 7, // 0b0111 + MODE_KANJI = 8, // 0b1000 + MODE_STRUCTURED_APPEND = 3 // 0b0011 + }; + + enum CorrectionLevel { + CORRECT_LEVEL_L = 0, + CORRECT_LEVEL_M = 1, + CORRECT_LEVEL_Q = 2, + CORRECT_LEVEL_H = 3 + }; + + enum ECIEncodings { + ECI_UTF8 = 26 + }; + + /** @brief QR code encoder parameters. */ + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + + //! The optional version of QR code (by default - maximum possible depending on the length of the string). + CV_PROP_RW int version; + + //! The optional level of error correction (by default - the lowest). + CV_PROP_RW CorrectionLevel correction_level; + + //! The optional encoding mode - Numeric, Alphanumeric, Byte, Kanji, ECI or Structured Append. + CV_PROP_RW EncodeMode mode; + + //! The optional number of QR codes to generate in Structured Append mode. + CV_PROP_RW int structure_number; + }; + + /** @brief Constructor + @param parameters QR code encoder parameters QRCodeEncoder::Params + */ + static CV_WRAP + Ptr create(const QRCodeEncoder::Params& parameters = QRCodeEncoder::Params()); + + /** @brief Generates QR code from input string. + @param encoded_info Input string to encode. + @param qrcode Generated QR code. + */ + CV_WRAP virtual void encode(const String& encoded_info, OutputArray qrcode) = 0; + + /** @brief Generates QR code from input string in Structured Append mode. The encoded message is splitting over a number of QR codes. + @param encoded_info Input string to encode. + @param qrcodes Vector of generated QR codes. + */ + CV_WRAP virtual void encodeStructuredAppend(const String& encoded_info, OutputArrayOfArrays qrcodes) = 0; + +}; +class CV_EXPORTS_W_SIMPLE QRCodeDetector : public GraphicalCodeDetector +{ +public: + CV_WRAP QRCodeDetector(); + + /** @brief sets the epsilon used during the horizontal scan of QR code stop marker detection. + @param epsX Epsilon neighborhood, which allows you to determine the horizontal pattern + of the scheme 1:1:3:1:1 according to QR code standard. + */ + CV_WRAP QRCodeDetector& setEpsX(double epsX); + /** @brief sets the epsilon used during the vertical scan of QR code stop marker detection. + @param epsY Epsilon neighborhood, which allows you to determine the vertical pattern + of the scheme 1:1:3:1:1 according to QR code standard. + */ + CV_WRAP QRCodeDetector& setEpsY(double epsY); + + /** @brief use markers to improve the position of the corners of the QR code + * + * alignmentMarkers using by default + */ + CV_WRAP QRCodeDetector& setUseAlignmentMarkers(bool useAlignmentMarkers); + + /** @brief Decodes QR code on a curved surface in image once it's found by the detect() method. + + Returns UTF8-encoded output string or empty string if the code cannot be decoded. + @param img grayscale or color (BGR) image containing QR code. + @param points Quadrangle vertices found by detect() method (or some other algorithm). + @param straight_qrcode The optional output image containing rectified and binarized QR code + */ + CV_WRAP cv::String decodeCurved(InputArray img, InputArray points, OutputArray straight_qrcode = noArray()); + + /** @brief Both detects and decodes QR code on a curved surface + + @param img grayscale or color (BGR) image containing QR code. + @param points optional output array of vertices of the found QR code quadrangle. Will be empty if not found. + @param straight_qrcode The optional output image containing rectified and binarized QR code + */ + CV_WRAP std::string detectAndDecodeCurved(InputArray img, OutputArray points=noArray(), + OutputArray straight_qrcode = noArray()); +}; + +class CV_EXPORTS_W_SIMPLE QRCodeDetectorAruco : public GraphicalCodeDetector { +public: + CV_WRAP QRCodeDetectorAruco(); + + struct CV_EXPORTS_W_SIMPLE Params { + CV_WRAP Params(); + + /** @brief The minimum allowed pixel size of a QR module in the smallest image in the image pyramid, default 4.f */ + CV_PROP_RW float minModuleSizeInPyramid; + + /** @brief The maximum allowed relative rotation for finder patterns in the same QR code, default pi/12 */ + CV_PROP_RW float maxRotation; + + /** @brief The maximum allowed relative mismatch in module sizes for finder patterns in the same QR code, default 1.75f */ + CV_PROP_RW float maxModuleSizeMismatch; + + /** @brief The maximum allowed module relative mismatch for timing pattern module, default 2.f + * + * If relative mismatch of timing pattern module more this value, penalty points will be added. + * If a lot of penalty points are added, QR code will be rejected. */ + CV_PROP_RW float maxTimingPatternMismatch; + + /** @brief The maximum allowed percentage of penalty points out of total pins in timing pattern, default 0.4f */ + CV_PROP_RW float maxPenalties; + + /** @brief The maximum allowed relative color mismatch in the timing pattern, default 0.2f*/ + CV_PROP_RW float maxColorsMismatch; + + /** @brief The algorithm find QR codes with almost minimum timing pattern score and minimum size, default 0.9f + * + * The QR code with the minimum "timing pattern score" and minimum "size" is selected as the best QR code. + * If for the current QR code "timing pattern score" * scaleTimingPatternScore < "previous timing pattern score" and "size" < "previous size", then + * current QR code set as the best QR code. */ + CV_PROP_RW float scaleTimingPatternScore; + }; + + /** @brief QR code detector constructor for Aruco-based algorithm. See cv::QRCodeDetectorAruco::Params */ + CV_WRAP explicit QRCodeDetectorAruco(const QRCodeDetectorAruco::Params& params); + + /** @brief Detector parameters getter. See cv::QRCodeDetectorAruco::Params */ + CV_WRAP const QRCodeDetectorAruco::Params& getDetectorParameters() const; + + /** @brief Detector parameters setter. See cv::QRCodeDetectorAruco::Params */ + CV_WRAP QRCodeDetectorAruco& setDetectorParameters(const QRCodeDetectorAruco::Params& params); + + /** @brief Aruco detector parameters are used to search for the finder patterns. */ + CV_WRAP const aruco::DetectorParameters& getArucoParameters() const; + + /** @brief Aruco detector parameters are used to search for the finder patterns. */ + CV_WRAP void setArucoParameters(const aruco::DetectorParameters& params); +}; + +//! @} +} + +#include "opencv2/objdetect/detection_based_tracker.hpp" +#include "opencv2/objdetect/face.hpp" +#include "opencv2/objdetect/charuco_detector.hpp" +#include "opencv2/objdetect/barcode.hpp" + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp index 526a55e06c..e8300c82bf 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_board.hpp @@ -1,199 +1,199 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_ARUCO_BOARD_HPP -#define OPENCV_OBJDETECT_ARUCO_BOARD_HPP - -#include - -namespace cv { -namespace aruco { -//! @addtogroup objdetect_aruco -//! @{ - -class Dictionary; - -/** @brief Board of ArUco markers - * - * A board is a set of markers in the 3D space with a common coordinate system. - * The common form of a board of marker is a planar (2D) board, however any 3D layout can be used. - * A Board object is composed by: - * - The object points of the marker corners, i.e. their coordinates respect to the board system. - * - The dictionary which indicates the type of markers of the board - * - The identifier of all the markers in the board. - */ -class CV_EXPORTS_W_SIMPLE Board { -public: - /** @brief Common Board constructor - * - * @param objPoints array of object points of all the marker corners in the board - * @param dictionary the dictionary of markers employed for this board - * @param ids vector of the identifiers of the markers in the board - */ - CV_WRAP Board(InputArrayOfArrays objPoints, const Dictionary& dictionary, InputArray ids); - - /** @brief return the Dictionary of markers employed for this board - */ - CV_WRAP const Dictionary& getDictionary() const; - - /** @brief return array of object points of all the marker corners in the board. - * - * Each marker include its 4 corners in this order: - * - objPoints[i][0] - left-top point of i-th marker - * - objPoints[i][1] - right-top point of i-th marker - * - objPoints[i][2] - right-bottom point of i-th marker - * - objPoints[i][3] - left-bottom point of i-th marker - * - * Markers are placed in a certain order - row by row, left to right in every row. For M markers, the size is Mx4. - */ - CV_WRAP const std::vector >& getObjPoints() const; - - /** @brief vector of the identifiers of the markers in the board (should be the same size as objPoints) - * @return vector of the identifiers of the markers - */ - CV_WRAP const std::vector& getIds() const; - - /** @brief get coordinate of the bottom right corner of the board, is set when calling the function create() - */ - CV_WRAP const Point3f& getRightBottomCorner() const; - - /** @brief Given a board configuration and a set of detected markers, returns the corresponding - * image points and object points, can be used in solvePnP() - * - * @param detectedCorners List of detected marker corners of the board. - * For cv::Board and cv::GridBoard the method expects std::vector> or std::vector with Aruco marker corners. - * For cv::CharucoBoard the method expects std::vector or Mat with ChAruco corners (chess board corners matched with Aruco markers). - * - * @param detectedIds List of identifiers for each marker or charuco corner. - * For any Board class the method expects std::vector or Mat. - * - * @param objPoints Vector of marker points in the board coordinate space. - * For any Board class the method expects std::vector objectPoints or cv::Mat - * - * @param imgPoints Vector of marker points in the image coordinate space. - * For any Board class the method expects std::vector objectPoints or cv::Mat - * - * @sa solvePnP - */ - CV_WRAP void matchImagePoints(InputArrayOfArrays detectedCorners, InputArray detectedIds, - OutputArray objPoints, OutputArray imgPoints) const; - - /** @brief Draw a planar board - * - * @param outSize size of the output image in pixels. - * @param img output image with the board. The size of this image will be outSize - * and the board will be on the center, keeping the board proportions. - * @param marginSize minimum margins (in pixels) of the board in the output image - * @param borderBits width of the marker borders. - * - * This function return the image of the board, ready to be printed. - */ - CV_WRAP void generateImage(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1) const; - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - Board(); - - struct Impl; -protected: - Board(const Ptr& impl); - Ptr impl; -}; - -/** @brief Planar board with grid arrangement of markers - * - * More common type of board. All markers are placed in the same plane in a grid arrangement. - * The board image can be drawn using generateImage() method. - */ -class CV_EXPORTS_W_SIMPLE GridBoard : public Board { -public: - /** - * @brief GridBoard constructor - * - * @param size number of markers in x and y directions - * @param markerLength marker side length (normally in meters) - * @param markerSeparation separation between two markers (same unit as markerLength) - * @param dictionary dictionary of markers indicating the type of markers - * @param ids set of marker ids in dictionary to use on board. - */ - CV_WRAP GridBoard(const Size& size, float markerLength, float markerSeparation, - const Dictionary &dictionary, InputArray ids = noArray()); - - CV_WRAP Size getGridSize() const; - CV_WRAP float getMarkerLength() const; - CV_WRAP float getMarkerSeparation() const; - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - GridBoard(); -}; - -/** - * @brief ChArUco board is a planar chessboard where the markers are placed inside the white squares of a chessboard. - * - * The benefits of ChArUco boards is that they provide both, ArUco markers versatility and chessboard corner precision, - * which is important for calibration and pose estimation. The board image can be drawn using generateImage() method. - */ -class CV_EXPORTS_W_SIMPLE CharucoBoard : public Board { -public: - /** @brief CharucoBoard constructor - * - * @param size number of chessboard squares in x and y directions - * @param squareLength squareLength chessboard square side length (normally in meters) - * @param markerLength marker side length (same unit than squareLength) - * @param dictionary dictionary of markers indicating the type of markers - * @param ids array of id used markers - * The first markers in the dictionary are used to fill the white chessboard squares. - */ - CV_WRAP CharucoBoard(const Size& size, float squareLength, float markerLength, - const Dictionary &dictionary, InputArray ids = noArray()); - - /** @brief set legacy chessboard pattern. - * - * Legacy setting creates chessboard patterns starting with a white box in the upper left corner - * if there is an even row count of chessboard boxes, otherwise it starts with a black box. - * This setting ensures compatibility to patterns created with OpenCV versions prior OpenCV 4.6.0. - * See https://github.com/opencv/opencv/issues/23152. - * - * Default value: false. - */ - CV_WRAP void setLegacyPattern(bool legacyPattern); - CV_WRAP bool getLegacyPattern() const; - - CV_WRAP Size getChessboardSize() const; - CV_WRAP float getSquareLength() const; - CV_WRAP float getMarkerLength() const; - - /** @brief get CharucoBoard::chessboardCorners - */ - CV_WRAP std::vector getChessboardCorners() const; - - /** @brief get CharucoBoard::nearestMarkerIdx, for each charuco corner, nearest marker index in ids array - */ - CV_PROP std::vector > getNearestMarkerIdx() const; - - /** @brief get CharucoBoard::nearestMarkerCorners, for each charuco corner, nearest marker corner id of each marker - */ - CV_PROP std::vector > getNearestMarkerCorners() const; - - /** @brief check whether the ChArUco markers are collinear - * - * @param charucoIds list of identifiers for each corner in charucoCorners per frame. - * @return bool value, 1 (true) if detected corners form a line, 0 (false) if they do not. - * solvePnP, calibration functions will fail if the corners are collinear (true). - * - * The number of ids in charucoIDs should be <= the number of chessboard corners in the board. - * This functions checks whether the charuco corners are on a straight line (returns true, if so), or not (false). - * Axis parallel, as well as diagonal and other straight lines detected. Degenerate cases: - * for number of charucoIDs <= 2,the function returns true. - */ - CV_WRAP bool checkCharucoCornersCollinear(InputArray charucoIds) const; - - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - CharucoBoard(); -}; - -//! @} - -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_ARUCO_BOARD_HPP +#define OPENCV_OBJDETECT_ARUCO_BOARD_HPP + +#include + +namespace cv { +namespace aruco { +//! @addtogroup objdetect_aruco +//! @{ + +class Dictionary; + +/** @brief Board of ArUco markers + * + * A board is a set of markers in the 3D space with a common coordinate system. + * The common form of a board of marker is a planar (2D) board, however any 3D layout can be used. + * A Board object is composed by: + * - The object points of the marker corners, i.e. their coordinates respect to the board system. + * - The dictionary which indicates the type of markers of the board + * - The identifier of all the markers in the board. + */ +class CV_EXPORTS_W_SIMPLE Board { +public: + /** @brief Common Board constructor + * + * @param objPoints array of object points of all the marker corners in the board + * @param dictionary the dictionary of markers employed for this board + * @param ids vector of the identifiers of the markers in the board + */ + CV_WRAP Board(InputArrayOfArrays objPoints, const Dictionary& dictionary, InputArray ids); + + /** @brief return the Dictionary of markers employed for this board + */ + CV_WRAP const Dictionary& getDictionary() const; + + /** @brief return array of object points of all the marker corners in the board. + * + * Each marker include its 4 corners in this order: + * - objPoints[i][0] - left-top point of i-th marker + * - objPoints[i][1] - right-top point of i-th marker + * - objPoints[i][2] - right-bottom point of i-th marker + * - objPoints[i][3] - left-bottom point of i-th marker + * + * Markers are placed in a certain order - row by row, left to right in every row. For M markers, the size is Mx4. + */ + CV_WRAP const std::vector >& getObjPoints() const; + + /** @brief vector of the identifiers of the markers in the board (should be the same size as objPoints) + * @return vector of the identifiers of the markers + */ + CV_WRAP const std::vector& getIds() const; + + /** @brief get coordinate of the bottom right corner of the board, is set when calling the function create() + */ + CV_WRAP const Point3f& getRightBottomCorner() const; + + /** @brief Given a board configuration and a set of detected markers, returns the corresponding + * image points and object points, can be used in solvePnP() + * + * @param detectedCorners List of detected marker corners of the board. + * For cv::Board and cv::GridBoard the method expects std::vector> or std::vector with Aruco marker corners. + * For cv::CharucoBoard the method expects std::vector or Mat with ChAruco corners (chess board corners matched with Aruco markers). + * + * @param detectedIds List of identifiers for each marker or charuco corner. + * For any Board class the method expects std::vector or Mat. + * + * @param objPoints Vector of marker points in the board coordinate space. + * For any Board class the method expects std::vector objectPoints or cv::Mat + * + * @param imgPoints Vector of marker points in the image coordinate space. + * For any Board class the method expects std::vector objectPoints or cv::Mat + * + * @sa solvePnP + */ + CV_WRAP void matchImagePoints(InputArrayOfArrays detectedCorners, InputArray detectedIds, + OutputArray objPoints, OutputArray imgPoints) const; + + /** @brief Draw a planar board + * + * @param outSize size of the output image in pixels. + * @param img output image with the board. The size of this image will be outSize + * and the board will be on the center, keeping the board proportions. + * @param marginSize minimum margins (in pixels) of the board in the output image + * @param borderBits width of the marker borders. + * + * This function return the image of the board, ready to be printed. + */ + CV_WRAP void generateImage(Size outSize, OutputArray img, int marginSize = 0, int borderBits = 1) const; + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + Board(); + + struct Impl; +protected: + Board(const Ptr& impl); + Ptr impl; +}; + +/** @brief Planar board with grid arrangement of markers + * + * More common type of board. All markers are placed in the same plane in a grid arrangement. + * The board image can be drawn using generateImage() method. + */ +class CV_EXPORTS_W_SIMPLE GridBoard : public Board { +public: + /** + * @brief GridBoard constructor + * + * @param size number of markers in x and y directions + * @param markerLength marker side length (normally in meters) + * @param markerSeparation separation between two markers (same unit as markerLength) + * @param dictionary dictionary of markers indicating the type of markers + * @param ids set of marker ids in dictionary to use on board. + */ + CV_WRAP GridBoard(const Size& size, float markerLength, float markerSeparation, + const Dictionary &dictionary, InputArray ids = noArray()); + + CV_WRAP Size getGridSize() const; + CV_WRAP float getMarkerLength() const; + CV_WRAP float getMarkerSeparation() const; + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + GridBoard(); +}; + +/** + * @brief ChArUco board is a planar chessboard where the markers are placed inside the white squares of a chessboard. + * + * The benefits of ChArUco boards is that they provide both, ArUco markers versatility and chessboard corner precision, + * which is important for calibration and pose estimation. The board image can be drawn using generateImage() method. + */ +class CV_EXPORTS_W_SIMPLE CharucoBoard : public Board { +public: + /** @brief CharucoBoard constructor + * + * @param size number of chessboard squares in x and y directions + * @param squareLength squareLength chessboard square side length (normally in meters) + * @param markerLength marker side length (same unit than squareLength) + * @param dictionary dictionary of markers indicating the type of markers + * @param ids array of id used markers + * The first markers in the dictionary are used to fill the white chessboard squares. + */ + CV_WRAP CharucoBoard(const Size& size, float squareLength, float markerLength, + const Dictionary &dictionary, InputArray ids = noArray()); + + /** @brief set legacy chessboard pattern. + * + * Legacy setting creates chessboard patterns starting with a white box in the upper left corner + * if there is an even row count of chessboard boxes, otherwise it starts with a black box. + * This setting ensures compatibility to patterns created with OpenCV versions prior OpenCV 4.6.0. + * See https://github.com/opencv/opencv/issues/23152. + * + * Default value: false. + */ + CV_WRAP void setLegacyPattern(bool legacyPattern); + CV_WRAP bool getLegacyPattern() const; + + CV_WRAP Size getChessboardSize() const; + CV_WRAP float getSquareLength() const; + CV_WRAP float getMarkerLength() const; + + /** @brief get CharucoBoard::chessboardCorners + */ + CV_WRAP std::vector getChessboardCorners() const; + + /** @brief get CharucoBoard::nearestMarkerIdx, for each charuco corner, nearest marker index in ids array + */ + CV_PROP std::vector > getNearestMarkerIdx() const; + + /** @brief get CharucoBoard::nearestMarkerCorners, for each charuco corner, nearest marker corner id of each marker + */ + CV_PROP std::vector > getNearestMarkerCorners() const; + + /** @brief check whether the ChArUco markers are collinear + * + * @param charucoIds list of identifiers for each corner in charucoCorners per frame. + * @return bool value, 1 (true) if detected corners form a line, 0 (false) if they do not. + * solvePnP, calibration functions will fail if the corners are collinear (true). + * + * The number of ids in charucoIDs should be <= the number of chessboard corners in the board. + * This functions checks whether the charuco corners are on a straight line (returns true, if so), or not (false). + * Axis parallel, as well as diagonal and other straight lines detected. Degenerate cases: + * for number of charucoIDs <= 2,the function returns true. + */ + CV_WRAP bool checkCharucoCornersCollinear(InputArray charucoIds) const; + + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + CharucoBoard(); +}; + +//! @} + +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp index 2eac6e419d..9d30d55d17 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_detector.hpp @@ -1,400 +1,400 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP -#define OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP - -#include -#include - -namespace cv { -namespace aruco { - -//! @addtogroup objdetect_aruco -//! @{ - -enum CornerRefineMethod{ - CORNER_REFINE_NONE, ///< Tag and corners detection based on the ArUco approach - CORNER_REFINE_SUBPIX, ///< ArUco approach and refine the corners locations using corner subpixel accuracy - CORNER_REFINE_CONTOUR, ///< ArUco approach and refine the corners locations using the contour-points line fitting - CORNER_REFINE_APRILTAG, ///< Tag and corners detection based on the AprilTag 2 approach @cite wang2016iros -}; - -/** @brief struct DetectorParameters is used by ArucoDetector - */ -struct CV_EXPORTS_W_SIMPLE DetectorParameters { - CV_WRAP DetectorParameters() { - adaptiveThreshWinSizeMin = 3; - adaptiveThreshWinSizeMax = 23; - adaptiveThreshWinSizeStep = 10; - adaptiveThreshConstant = 7; - minMarkerPerimeterRate = 0.03; - maxMarkerPerimeterRate = 4.; - polygonalApproxAccuracyRate = 0.03; - minCornerDistanceRate = 0.05; - minDistanceToBorder = 3; - minMarkerDistanceRate = 0.125; - cornerRefinementMethod = (int)CORNER_REFINE_NONE; - cornerRefinementWinSize = 5; - relativeCornerRefinmentWinSize = 0.3f; - cornerRefinementMaxIterations = 30; - cornerRefinementMinAccuracy = 0.1; - markerBorderBits = 1; - perspectiveRemovePixelPerCell = 4; - perspectiveRemoveIgnoredMarginPerCell = 0.13; - maxErroneousBitsInBorderRate = 0.35; - minOtsuStdDev = 5.0; - errorCorrectionRate = 0.6; - aprilTagQuadDecimate = 0.0; - aprilTagQuadSigma = 0.0; - aprilTagMinClusterPixels = 5; - aprilTagMaxNmaxima = 10; - aprilTagCriticalRad = (float)(10* CV_PI /180); - aprilTagMaxLineFitMse = 10.0; - aprilTagMinWhiteBlackDiff = 5; - aprilTagDeglitch = 0; - detectInvertedMarker = false; - useAruco3Detection = false; - minSideLengthCanonicalImg = 32; - minMarkerLengthRatioOriginalImg = 0.0; - } - - /** @brief Read a new set of DetectorParameters from FileNode (use FileStorage.root()). - */ - CV_WRAP bool readDetectorParameters(const FileNode& fn); - - /** @brief Write a set of DetectorParameters to FileStorage - */ - CV_WRAP bool writeDetectorParameters(FileStorage& fs, const String& name = String()); - - /// minimum window size for adaptive thresholding before finding contours (default 3). - CV_PROP_RW int adaptiveThreshWinSizeMin; - - /// maximum window size for adaptive thresholding before finding contours (default 23). - CV_PROP_RW int adaptiveThreshWinSizeMax; - - /// increments from adaptiveThreshWinSizeMin to adaptiveThreshWinSizeMax during the thresholding (default 10). - CV_PROP_RW int adaptiveThreshWinSizeStep; - - /// constant for adaptive thresholding before finding contours (default 7) - CV_PROP_RW double adaptiveThreshConstant; - - /** @brief determine minimum perimeter for marker contour to be detected. - * - * This is defined as a rate respect to the maximum dimension of the input image (default 0.03). - */ - CV_PROP_RW double minMarkerPerimeterRate; - - /** @brief determine maximum perimeter for marker contour to be detected. - * - * This is defined as a rate respect to the maximum dimension of the input image (default 4.0). - */ - CV_PROP_RW double maxMarkerPerimeterRate; - - /// minimum accuracy during the polygonal approximation process to determine which contours are squares. (default 0.03) - CV_PROP_RW double polygonalApproxAccuracyRate; - - /// minimum distance between corners for detected markers relative to its perimeter (default 0.05) - CV_PROP_RW double minCornerDistanceRate; - - /// minimum distance of any corner to the image border for detected markers (in pixels) (default 3) - CV_PROP_RW int minDistanceToBorder; - - /** @brief minimum average distance between the corners of the two markers to be grouped (default 0.125). - * - * The rate is relative to the smaller perimeter of the two markers. - * Two markers are grouped if average distance between the corners of the two markers is less than - * min(MarkerPerimeter1, MarkerPerimeter2)*minMarkerDistanceRate. - * - * default value is 0.125 because 0.125*MarkerPerimeter = (MarkerPerimeter / 4) * 0.5 = half the side of the marker. - * - * @note default value was changed from 0.05 after 4.8.1 release, because the filtering algorithm has been changed. - * Now a few candidates from the same group can be added to the list of candidates if they are far from each other. - * @sa minGroupDistance. - */ - CV_PROP_RW double minMarkerDistanceRate; - - /** @brief minimum average distance between the corners of the two markers in group to add them to the list of candidates - * - * The average distance between the corners of the two markers is calculated relative to its module size (default 0.21). - */ - CV_PROP_RW float minGroupDistance = 0.21f; - - /** @brief default value CORNER_REFINE_NONE */ - CV_PROP_RW int cornerRefinementMethod; - - /** @brief maximum window size for the corner refinement process (in pixels) (default 5). - * - * The window size may decrease if the ArUco marker is too small, check relativeCornerRefinmentWinSize. - * The final window size is calculated as: - * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), - * where averageArucoModuleSize is average module size of ArUco marker in pixels. - * (ArUco marker is composed of black and white modules) - */ - CV_PROP_RW int cornerRefinementWinSize; - - /** @brief Dynamic window size for corner refinement relative to Aruco module size (default 0.3). - * - * The final window size is calculated as: - * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), - * where averageArucoModuleSize is average module size of ArUco marker in pixels. - * (ArUco marker is composed of black and white modules) - * In the case of markers located far from each other, it may be useful to increase the value of the parameter to 0.4-0.5. - * In the case of markers located close to each other, it may be useful to decrease the parameter value to 0.1-0.2. - */ - CV_PROP_RW float relativeCornerRefinmentWinSize; - - /// maximum number of iterations for stop criteria of the corner refinement process (default 30). - CV_PROP_RW int cornerRefinementMaxIterations; - - /// minimum error for the stop cristeria of the corner refinement process (default: 0.1) - CV_PROP_RW double cornerRefinementMinAccuracy; - - /// number of bits of the marker border, i.e. marker border width (default 1). - CV_PROP_RW int markerBorderBits; - - /// number of bits (per dimension) for each cell of the marker when removing the perspective (default 4). - CV_PROP_RW int perspectiveRemovePixelPerCell; - - /** @brief width of the margin of pixels on each cell not considered for the determination of the cell bit. - * - * Represents the rate respect to the total size of the cell, i.e. perspectiveRemovePixelPerCell (default 0.13) - */ - CV_PROP_RW double perspectiveRemoveIgnoredMarginPerCell; - - /** @brief maximum number of accepted erroneous bits in the border (i.e. number of allowed white bits in the border). - * - * Represented as a rate respect to the total number of bits per marker (default 0.35). - */ - CV_PROP_RW double maxErroneousBitsInBorderRate; - - /** @brief minimun standard deviation in pixels values during the decodification step to apply Otsu - * thresholding (otherwise, all the bits are set to 0 or 1 depending on mean higher than 128 or not) (default 5.0) - */ - CV_PROP_RW double minOtsuStdDev; - - /// error correction rate respect to the maximun error correction capability for each dictionary (default 0.6). - CV_PROP_RW double errorCorrectionRate; - - /** @brief April :: User-configurable parameters. - * - * Detection of quads can be done on a lower-resolution image, improving speed at a cost of - * pose accuracy and a slight decrease in detection rate. Decoding the binary payload is still - */ - CV_PROP_RW float aprilTagQuadDecimate; - - /// what Gaussian blur should be applied to the segmented image (used for quad detection?) - CV_PROP_RW float aprilTagQuadSigma; - - // April :: Internal variables - /// reject quads containing too few pixels (default 5). - CV_PROP_RW int aprilTagMinClusterPixels; - - /// how many corner candidates to consider when segmenting a group of pixels into a quad (default 10). - CV_PROP_RW int aprilTagMaxNmaxima; - - /** @brief reject quads where pairs of edges have angles that are close to straight or close to 180 degrees. - * - * Zero means that no quads are rejected. (In radians) (default 10*PI/180) - */ - CV_PROP_RW float aprilTagCriticalRad; - - /// when fitting lines to the contours, what is the maximum mean squared error - CV_PROP_RW float aprilTagMaxLineFitMse; - - /** @brief add an extra check that the white model must be (overall) brighter than the black model. - * - * When we build our model of black & white pixels, we add an extra check that the white model must be (overall) - * brighter than the black model. How much brighter? (in pixel values, [0,255]), (default 5) - */ - CV_PROP_RW int aprilTagMinWhiteBlackDiff; - - /// should the thresholded image be deglitched? Only useful for very noisy images (default 0). - CV_PROP_RW int aprilTagDeglitch; - - /** @brief to check if there is a white marker. - * - * In order to generate a "white" marker just invert a normal marker by using a tilde, ~markerImage. (default false) - */ - CV_PROP_RW bool detectInvertedMarker; - - /** @brief enable the new and faster Aruco detection strategy. - * - * Proposed in the paper: - * Romero-Ramirez et al: Speeded up detection of squared fiducial markers (2018) - * https://www.researchgate.net/publication/325787310_Speeded_Up_Detection_of_Squared_Fiducial_Markers - */ - CV_PROP_RW bool useAruco3Detection; - - /// minimum side length of a marker in the canonical image. Latter is the binarized image in which contours are searched. - CV_PROP_RW int minSideLengthCanonicalImg; - - /// range [0,1], eq (2) from paper. The parameter tau_i has a direct influence on the processing speed. - CV_PROP_RW float minMarkerLengthRatioOriginalImg; -}; - -/** @brief struct RefineParameters is used by ArucoDetector - */ -struct CV_EXPORTS_W_SIMPLE RefineParameters { - CV_WRAP RefineParameters(float minRepDistance = 10.f, float errorCorrectionRate = 3.f, bool checkAllOrders = true); - - - /** @brief Read a new set of RefineParameters from FileNode (use FileStorage.root()). - */ - CV_WRAP bool readRefineParameters(const FileNode& fn); - - /** @brief Write a set of RefineParameters to FileStorage - */ - CV_WRAP bool writeRefineParameters(FileStorage& fs, const String& name = String()); - - /** @brief minRepDistance minimum distance between the corners of the rejected candidate and the reprojected marker - in order to consider it as a correspondence. - */ - CV_PROP_RW float minRepDistance; - - /** @brief errorCorrectionRate rate of allowed erroneous bits respect to the error correction capability of the used dictionary. - * - * -1 ignores the error correction step. - */ - CV_PROP_RW float errorCorrectionRate; - - /** @brief checkAllOrders consider the four posible corner orders in the rejectedCorners array. - * - * If it set to false, only the provided corner order is considered (default true). - */ - CV_PROP_RW bool checkAllOrders; -}; - -/** @brief The main functionality of ArucoDetector class is detection of markers in an image with detectMarkers() method. - * - * After detecting some markers in the image, you can try to find undetected markers from this dictionary with - * refineDetectedMarkers() method. - * - * @see DetectorParameters, RefineParameters - */ -class CV_EXPORTS_W ArucoDetector : public Algorithm -{ -public: - /** @brief Basic ArucoDetector constructor - * - * @param dictionary indicates the type of markers that will be searched - * @param detectorParams marker detection parameters - * @param refineParams marker refine detection parameters - */ - CV_WRAP ArucoDetector(const Dictionary &dictionary = getPredefinedDictionary(cv::aruco::DICT_4X4_50), - const DetectorParameters &detectorParams = DetectorParameters(), - const RefineParameters& refineParams = RefineParameters()); - - /** @brief Basic marker detection - * - * @param image input image - * @param corners vector of detected marker corners. For each marker, its four corners - * are provided, (e.g std::vector > ). For N detected markers, - * the dimensions of this array is Nx4. The order of the corners is clockwise. - * @param ids vector of identifiers of the detected markers. The identifier is of type int - * (e.g. std::vector). For N detected markers, the size of ids is also N. - * The identifiers have the same order than the markers in the imgPoints array. - * @param rejectedImgPoints contains the imgPoints of those squares whose inner code has not a - * correct codification. Useful for debugging purposes. - * - * Performs marker detection in the input image. Only markers included in the specific dictionary - * are searched. For each detected marker, it returns the 2D position of its corner in the image - * and its corresponding identifier. - * Note that this function does not perform pose estimation. - * @note The function does not correct lens distortion or takes it into account. It's recommended to undistort - * input image with corresponding camera model, if camera parameters are known - * @sa undistort, estimatePoseSingleMarkers, estimatePoseBoard - */ - CV_WRAP void detectMarkers(InputArray image, OutputArrayOfArrays corners, OutputArray ids, - OutputArrayOfArrays rejectedImgPoints = noArray()) const; - - /** @brief Refine not detected markers based on the already detected and the board layout - * - * @param image input image - * @param board layout of markers in the board. - * @param detectedCorners vector of already detected marker corners. - * @param detectedIds vector of already detected marker identifiers. - * @param rejectedCorners vector of rejected candidates during the marker detection process. - * @param cameraMatrix optional input 3x3 floating-point camera matrix - * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ - * @param distCoeffs optional vector of distortion coefficients - * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements - * @param recoveredIdxs Optional array to returns the indexes of the recovered candidates in the - * original rejectedCorners array. - * - * This function tries to find markers that were not detected in the basic detecMarkers function. - * First, based on the current detected marker and the board layout, the function interpolates - * the position of the missing markers. Then it tries to find correspondence between the reprojected - * markers and the rejected candidates based on the minRepDistance and errorCorrectionRate parameters. - * If camera parameters and distortion coefficients are provided, missing markers are reprojected - * using projectPoint function. If not, missing marker projections are interpolated using global - * homography, and all the marker corners in the board must have the same Z coordinate. - */ - CV_WRAP void refineDetectedMarkers(InputArray image, const Board &board, - InputOutputArrayOfArrays detectedCorners, - InputOutputArray detectedIds, InputOutputArrayOfArrays rejectedCorners, - InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray(), - OutputArray recoveredIdxs = noArray()) const; - - CV_WRAP const Dictionary& getDictionary() const; - CV_WRAP void setDictionary(const Dictionary& dictionary); - - CV_WRAP const DetectorParameters& getDetectorParameters() const; - CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); - - CV_WRAP const RefineParameters& getRefineParameters() const; - CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); - - /** @brief Stores algorithm parameters in a file storage - */ - virtual void write(FileStorage& fs) const override; - - /** @brief simplified API for language bindings - */ - CV_WRAP inline void write(FileStorage& fs, const String& name) { Algorithm::write(fs, name); } - - /** @brief Reads algorithm parameters from a file storage - */ - CV_WRAP virtual void read(const FileNode& fn) override; -protected: - struct ArucoDetectorImpl; - Ptr arucoDetectorImpl; -}; - -/** @brief Draw detected markers in image - * - * @param image input/output image. It must have 1 or 3 channels. The number of channels is not altered. - * @param corners positions of marker corners on input image. - * (e.g std::vector > ). For N detected markers, the dimensions of - * this array should be Nx4. The order of the corners should be clockwise. - * @param ids vector of identifiers for markers in markersCorners . - * Optional, if not provided, ids are not painted. - * @param borderColor color of marker borders. Rest of colors (text color and first corner color) - * are calculated based on this one to improve visualization. - * - * Given an array of detected marker corners and its corresponding ids, this functions draws - * the markers in the image. The marker borders are painted and the markers identifiers if provided. - * Useful for debugging purposes. - */ -CV_EXPORTS_W void drawDetectedMarkers(InputOutputArray image, InputArrayOfArrays corners, - InputArray ids = noArray(), Scalar borderColor = Scalar(0, 255, 0)); - -/** @brief Generate a canonical marker image - * - * @param dictionary dictionary of markers indicating the type of markers - * @param id identifier of the marker that will be returned. It has to be a valid id in the specified dictionary. - * @param sidePixels size of the image in pixels - * @param img output image with the marker - * @param borderBits width of the marker border. - * - * This function returns a marker image in its canonical form (i.e. ready to be printed) - */ -CV_EXPORTS_W void generateImageMarker(const Dictionary &dictionary, int id, int sidePixels, OutputArray img, - int borderBits = 1); - -//! @} - -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP +#define OPENCV_OBJDETECT_ARUCO_DETECTOR_HPP + +#include +#include + +namespace cv { +namespace aruco { + +//! @addtogroup objdetect_aruco +//! @{ + +enum CornerRefineMethod{ + CORNER_REFINE_NONE, ///< Tag and corners detection based on the ArUco approach + CORNER_REFINE_SUBPIX, ///< ArUco approach and refine the corners locations using corner subpixel accuracy + CORNER_REFINE_CONTOUR, ///< ArUco approach and refine the corners locations using the contour-points line fitting + CORNER_REFINE_APRILTAG, ///< Tag and corners detection based on the AprilTag 2 approach @cite wang2016iros +}; + +/** @brief struct DetectorParameters is used by ArucoDetector + */ +struct CV_EXPORTS_W_SIMPLE DetectorParameters { + CV_WRAP DetectorParameters() { + adaptiveThreshWinSizeMin = 3; + adaptiveThreshWinSizeMax = 23; + adaptiveThreshWinSizeStep = 10; + adaptiveThreshConstant = 7; + minMarkerPerimeterRate = 0.03; + maxMarkerPerimeterRate = 4.; + polygonalApproxAccuracyRate = 0.03; + minCornerDistanceRate = 0.05; + minDistanceToBorder = 3; + minMarkerDistanceRate = 0.125; + cornerRefinementMethod = (int)CORNER_REFINE_NONE; + cornerRefinementWinSize = 5; + relativeCornerRefinmentWinSize = 0.3f; + cornerRefinementMaxIterations = 30; + cornerRefinementMinAccuracy = 0.1; + markerBorderBits = 1; + perspectiveRemovePixelPerCell = 4; + perspectiveRemoveIgnoredMarginPerCell = 0.13; + maxErroneousBitsInBorderRate = 0.35; + minOtsuStdDev = 5.0; + errorCorrectionRate = 0.6; + aprilTagQuadDecimate = 0.0; + aprilTagQuadSigma = 0.0; + aprilTagMinClusterPixels = 5; + aprilTagMaxNmaxima = 10; + aprilTagCriticalRad = (float)(10* CV_PI /180); + aprilTagMaxLineFitMse = 10.0; + aprilTagMinWhiteBlackDiff = 5; + aprilTagDeglitch = 0; + detectInvertedMarker = false; + useAruco3Detection = false; + minSideLengthCanonicalImg = 32; + minMarkerLengthRatioOriginalImg = 0.0; + } + + /** @brief Read a new set of DetectorParameters from FileNode (use FileStorage.root()). + */ + CV_WRAP bool readDetectorParameters(const FileNode& fn); + + /** @brief Write a set of DetectorParameters to FileStorage + */ + CV_WRAP bool writeDetectorParameters(FileStorage& fs, const String& name = String()); + + /// minimum window size for adaptive thresholding before finding contours (default 3). + CV_PROP_RW int adaptiveThreshWinSizeMin; + + /// maximum window size for adaptive thresholding before finding contours (default 23). + CV_PROP_RW int adaptiveThreshWinSizeMax; + + /// increments from adaptiveThreshWinSizeMin to adaptiveThreshWinSizeMax during the thresholding (default 10). + CV_PROP_RW int adaptiveThreshWinSizeStep; + + /// constant for adaptive thresholding before finding contours (default 7) + CV_PROP_RW double adaptiveThreshConstant; + + /** @brief determine minimum perimeter for marker contour to be detected. + * + * This is defined as a rate respect to the maximum dimension of the input image (default 0.03). + */ + CV_PROP_RW double minMarkerPerimeterRate; + + /** @brief determine maximum perimeter for marker contour to be detected. + * + * This is defined as a rate respect to the maximum dimension of the input image (default 4.0). + */ + CV_PROP_RW double maxMarkerPerimeterRate; + + /// minimum accuracy during the polygonal approximation process to determine which contours are squares. (default 0.03) + CV_PROP_RW double polygonalApproxAccuracyRate; + + /// minimum distance between corners for detected markers relative to its perimeter (default 0.05) + CV_PROP_RW double minCornerDistanceRate; + + /// minimum distance of any corner to the image border for detected markers (in pixels) (default 3) + CV_PROP_RW int minDistanceToBorder; + + /** @brief minimum average distance between the corners of the two markers to be grouped (default 0.125). + * + * The rate is relative to the smaller perimeter of the two markers. + * Two markers are grouped if average distance between the corners of the two markers is less than + * min(MarkerPerimeter1, MarkerPerimeter2)*minMarkerDistanceRate. + * + * default value is 0.125 because 0.125*MarkerPerimeter = (MarkerPerimeter / 4) * 0.5 = half the side of the marker. + * + * @note default value was changed from 0.05 after 4.8.1 release, because the filtering algorithm has been changed. + * Now a few candidates from the same group can be added to the list of candidates if they are far from each other. + * @sa minGroupDistance. + */ + CV_PROP_RW double minMarkerDistanceRate; + + /** @brief minimum average distance between the corners of the two markers in group to add them to the list of candidates + * + * The average distance between the corners of the two markers is calculated relative to its module size (default 0.21). + */ + CV_PROP_RW float minGroupDistance = 0.21f; + + /** @brief default value CORNER_REFINE_NONE */ + CV_PROP_RW int cornerRefinementMethod; + + /** @brief maximum window size for the corner refinement process (in pixels) (default 5). + * + * The window size may decrease if the ArUco marker is too small, check relativeCornerRefinmentWinSize. + * The final window size is calculated as: + * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), + * where averageArucoModuleSize is average module size of ArUco marker in pixels. + * (ArUco marker is composed of black and white modules) + */ + CV_PROP_RW int cornerRefinementWinSize; + + /** @brief Dynamic window size for corner refinement relative to Aruco module size (default 0.3). + * + * The final window size is calculated as: + * min(cornerRefinementWinSize, averageArucoModuleSize*relativeCornerRefinmentWinSize), + * where averageArucoModuleSize is average module size of ArUco marker in pixels. + * (ArUco marker is composed of black and white modules) + * In the case of markers located far from each other, it may be useful to increase the value of the parameter to 0.4-0.5. + * In the case of markers located close to each other, it may be useful to decrease the parameter value to 0.1-0.2. + */ + CV_PROP_RW float relativeCornerRefinmentWinSize; + + /// maximum number of iterations for stop criteria of the corner refinement process (default 30). + CV_PROP_RW int cornerRefinementMaxIterations; + + /// minimum error for the stop cristeria of the corner refinement process (default: 0.1) + CV_PROP_RW double cornerRefinementMinAccuracy; + + /// number of bits of the marker border, i.e. marker border width (default 1). + CV_PROP_RW int markerBorderBits; + + /// number of bits (per dimension) for each cell of the marker when removing the perspective (default 4). + CV_PROP_RW int perspectiveRemovePixelPerCell; + + /** @brief width of the margin of pixels on each cell not considered for the determination of the cell bit. + * + * Represents the rate respect to the total size of the cell, i.e. perspectiveRemovePixelPerCell (default 0.13) + */ + CV_PROP_RW double perspectiveRemoveIgnoredMarginPerCell; + + /** @brief maximum number of accepted erroneous bits in the border (i.e. number of allowed white bits in the border). + * + * Represented as a rate respect to the total number of bits per marker (default 0.35). + */ + CV_PROP_RW double maxErroneousBitsInBorderRate; + + /** @brief minimun standard deviation in pixels values during the decodification step to apply Otsu + * thresholding (otherwise, all the bits are set to 0 or 1 depending on mean higher than 128 or not) (default 5.0) + */ + CV_PROP_RW double minOtsuStdDev; + + /// error correction rate respect to the maximun error correction capability for each dictionary (default 0.6). + CV_PROP_RW double errorCorrectionRate; + + /** @brief April :: User-configurable parameters. + * + * Detection of quads can be done on a lower-resolution image, improving speed at a cost of + * pose accuracy and a slight decrease in detection rate. Decoding the binary payload is still + */ + CV_PROP_RW float aprilTagQuadDecimate; + + /// what Gaussian blur should be applied to the segmented image (used for quad detection?) + CV_PROP_RW float aprilTagQuadSigma; + + // April :: Internal variables + /// reject quads containing too few pixels (default 5). + CV_PROP_RW int aprilTagMinClusterPixels; + + /// how many corner candidates to consider when segmenting a group of pixels into a quad (default 10). + CV_PROP_RW int aprilTagMaxNmaxima; + + /** @brief reject quads where pairs of edges have angles that are close to straight or close to 180 degrees. + * + * Zero means that no quads are rejected. (In radians) (default 10*PI/180) + */ + CV_PROP_RW float aprilTagCriticalRad; + + /// when fitting lines to the contours, what is the maximum mean squared error + CV_PROP_RW float aprilTagMaxLineFitMse; + + /** @brief add an extra check that the white model must be (overall) brighter than the black model. + * + * When we build our model of black & white pixels, we add an extra check that the white model must be (overall) + * brighter than the black model. How much brighter? (in pixel values, [0,255]), (default 5) + */ + CV_PROP_RW int aprilTagMinWhiteBlackDiff; + + /// should the thresholded image be deglitched? Only useful for very noisy images (default 0). + CV_PROP_RW int aprilTagDeglitch; + + /** @brief to check if there is a white marker. + * + * In order to generate a "white" marker just invert a normal marker by using a tilde, ~markerImage. (default false) + */ + CV_PROP_RW bool detectInvertedMarker; + + /** @brief enable the new and faster Aruco detection strategy. + * + * Proposed in the paper: + * Romero-Ramirez et al: Speeded up detection of squared fiducial markers (2018) + * https://www.researchgate.net/publication/325787310_Speeded_Up_Detection_of_Squared_Fiducial_Markers + */ + CV_PROP_RW bool useAruco3Detection; + + /// minimum side length of a marker in the canonical image. Latter is the binarized image in which contours are searched. + CV_PROP_RW int minSideLengthCanonicalImg; + + /// range [0,1], eq (2) from paper. The parameter tau_i has a direct influence on the processing speed. + CV_PROP_RW float minMarkerLengthRatioOriginalImg; +}; + +/** @brief struct RefineParameters is used by ArucoDetector + */ +struct CV_EXPORTS_W_SIMPLE RefineParameters { + CV_WRAP RefineParameters(float minRepDistance = 10.f, float errorCorrectionRate = 3.f, bool checkAllOrders = true); + + + /** @brief Read a new set of RefineParameters from FileNode (use FileStorage.root()). + */ + CV_WRAP bool readRefineParameters(const FileNode& fn); + + /** @brief Write a set of RefineParameters to FileStorage + */ + CV_WRAP bool writeRefineParameters(FileStorage& fs, const String& name = String()); + + /** @brief minRepDistance minimum distance between the corners of the rejected candidate and the reprojected marker + in order to consider it as a correspondence. + */ + CV_PROP_RW float minRepDistance; + + /** @brief errorCorrectionRate rate of allowed erroneous bits respect to the error correction capability of the used dictionary. + * + * -1 ignores the error correction step. + */ + CV_PROP_RW float errorCorrectionRate; + + /** @brief checkAllOrders consider the four posible corner orders in the rejectedCorners array. + * + * If it set to false, only the provided corner order is considered (default true). + */ + CV_PROP_RW bool checkAllOrders; +}; + +/** @brief The main functionality of ArucoDetector class is detection of markers in an image with detectMarkers() method. + * + * After detecting some markers in the image, you can try to find undetected markers from this dictionary with + * refineDetectedMarkers() method. + * + * @see DetectorParameters, RefineParameters + */ +class CV_EXPORTS_W ArucoDetector : public Algorithm +{ +public: + /** @brief Basic ArucoDetector constructor + * + * @param dictionary indicates the type of markers that will be searched + * @param detectorParams marker detection parameters + * @param refineParams marker refine detection parameters + */ + CV_WRAP ArucoDetector(const Dictionary &dictionary = getPredefinedDictionary(cv::aruco::DICT_4X4_50), + const DetectorParameters &detectorParams = DetectorParameters(), + const RefineParameters& refineParams = RefineParameters()); + + /** @brief Basic marker detection + * + * @param image input image + * @param corners vector of detected marker corners. For each marker, its four corners + * are provided, (e.g std::vector > ). For N detected markers, + * the dimensions of this array is Nx4. The order of the corners is clockwise. + * @param ids vector of identifiers of the detected markers. The identifier is of type int + * (e.g. std::vector). For N detected markers, the size of ids is also N. + * The identifiers have the same order than the markers in the imgPoints array. + * @param rejectedImgPoints contains the imgPoints of those squares whose inner code has not a + * correct codification. Useful for debugging purposes. + * + * Performs marker detection in the input image. Only markers included in the specific dictionary + * are searched. For each detected marker, it returns the 2D position of its corner in the image + * and its corresponding identifier. + * Note that this function does not perform pose estimation. + * @note The function does not correct lens distortion or takes it into account. It's recommended to undistort + * input image with corresponding camera model, if camera parameters are known + * @sa undistort, estimatePoseSingleMarkers, estimatePoseBoard + */ + CV_WRAP void detectMarkers(InputArray image, OutputArrayOfArrays corners, OutputArray ids, + OutputArrayOfArrays rejectedImgPoints = noArray()) const; + + /** @brief Refine not detected markers based on the already detected and the board layout + * + * @param image input image + * @param board layout of markers in the board. + * @param detectedCorners vector of already detected marker corners. + * @param detectedIds vector of already detected marker identifiers. + * @param rejectedCorners vector of rejected candidates during the marker detection process. + * @param cameraMatrix optional input 3x3 floating-point camera matrix + * \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ + * @param distCoeffs optional vector of distortion coefficients + * \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6],[s_1, s_2, s_3, s_4]])\f$ of 4, 5, 8 or 12 elements + * @param recoveredIdxs Optional array to returns the indexes of the recovered candidates in the + * original rejectedCorners array. + * + * This function tries to find markers that were not detected in the basic detecMarkers function. + * First, based on the current detected marker and the board layout, the function interpolates + * the position of the missing markers. Then it tries to find correspondence between the reprojected + * markers and the rejected candidates based on the minRepDistance and errorCorrectionRate parameters. + * If camera parameters and distortion coefficients are provided, missing markers are reprojected + * using projectPoint function. If not, missing marker projections are interpolated using global + * homography, and all the marker corners in the board must have the same Z coordinate. + */ + CV_WRAP void refineDetectedMarkers(InputArray image, const Board &board, + InputOutputArrayOfArrays detectedCorners, + InputOutputArray detectedIds, InputOutputArrayOfArrays rejectedCorners, + InputArray cameraMatrix = noArray(), InputArray distCoeffs = noArray(), + OutputArray recoveredIdxs = noArray()) const; + + CV_WRAP const Dictionary& getDictionary() const; + CV_WRAP void setDictionary(const Dictionary& dictionary); + + CV_WRAP const DetectorParameters& getDetectorParameters() const; + CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); + + CV_WRAP const RefineParameters& getRefineParameters() const; + CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); + + /** @brief Stores algorithm parameters in a file storage + */ + virtual void write(FileStorage& fs) const override; + + /** @brief simplified API for language bindings + */ + CV_WRAP inline void write(FileStorage& fs, const String& name) { Algorithm::write(fs, name); } + + /** @brief Reads algorithm parameters from a file storage + */ + CV_WRAP virtual void read(const FileNode& fn) override; +protected: + struct ArucoDetectorImpl; + Ptr arucoDetectorImpl; +}; + +/** @brief Draw detected markers in image + * + * @param image input/output image. It must have 1 or 3 channels. The number of channels is not altered. + * @param corners positions of marker corners on input image. + * (e.g std::vector > ). For N detected markers, the dimensions of + * this array should be Nx4. The order of the corners should be clockwise. + * @param ids vector of identifiers for markers in markersCorners . + * Optional, if not provided, ids are not painted. + * @param borderColor color of marker borders. Rest of colors (text color and first corner color) + * are calculated based on this one to improve visualization. + * + * Given an array of detected marker corners and its corresponding ids, this functions draws + * the markers in the image. The marker borders are painted and the markers identifiers if provided. + * Useful for debugging purposes. + */ +CV_EXPORTS_W void drawDetectedMarkers(InputOutputArray image, InputArrayOfArrays corners, + InputArray ids = noArray(), Scalar borderColor = Scalar(0, 255, 0)); + +/** @brief Generate a canonical marker image + * + * @param dictionary dictionary of markers indicating the type of markers + * @param id identifier of the marker that will be returned. It has to be a valid id in the specified dictionary. + * @param sidePixels size of the image in pixels + * @param img output image with the marker + * @param borderBits width of the marker border. + * + * This function returns a marker image in its canonical form (i.e. ready to be printed) + */ +CV_EXPORTS_W void generateImageMarker(const Dictionary &dictionary, int id, int sidePixels, OutputArray img, + int borderBits = 1); + +//! @} + +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp index e6d0fb5f21..bc7b934b2a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/aruco_dictionary.hpp @@ -1,155 +1,155 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_DICTIONARY_HPP -#define OPENCV_OBJDETECT_DICTIONARY_HPP - -#include - -namespace cv { -namespace aruco { - -//! @addtogroup objdetect_aruco -//! @{ - - -/** @brief Dictionary is a set of unique ArUco markers of the same size - * - * `bytesList` storing as 2-dimensions Mat with 4-th channels (CV_8UC4 type was used) and contains the marker codewords where: - * - bytesList.rows is the dictionary size - * - each marker is encoded using `nbytes = ceil(markerSize*markerSize/8.)` bytes - * - each row contains all 4 rotations of the marker, so its length is `4*nbytes` - * - the byte order in the bytesList[i] row: - * `//bytes without rotation/bytes with rotation 1/bytes with rotation 2/bytes with rotation 3//` - * So `bytesList.ptr(i)[k*nbytes + j]` is the j-th byte of i-th marker, in its k-th rotation. - * @note Python bindings generate matrix with shape of bytesList `dictionary_size x nbytes x 4`, - * but it should be indexed like C++ version. Python example for j-th byte of i-th marker, in its k-th rotation: - * `aruco_dict.bytesList[id].ravel()[k*nbytes + j]` - */ -class CV_EXPORTS_W_SIMPLE Dictionary { - - public: - CV_PROP_RW Mat bytesList; ///< marker code information. See class description for more details - CV_PROP_RW int markerSize; ///< number of bits per dimension - CV_PROP_RW int maxCorrectionBits; ///< maximum number of bits that can be corrected - - CV_WRAP Dictionary(); - - /** @brief Basic ArUco dictionary constructor - * - * @param bytesList bits for all ArUco markers in dictionary see memory layout in the class description - * @param _markerSize ArUco marker size in units - * @param maxcorr maximum number of bits that can be corrected - */ - CV_WRAP Dictionary(const Mat &bytesList, int _markerSize, int maxcorr = 0); - - /** @brief Read a new dictionary from FileNode. - * - * Dictionary example in YAML format:\n - * nmarkers: 35\n - * markersize: 6\n - * maxCorrectionBits: 5\n - * marker_0: "101011111011111001001001101100000000"\n - * ...\n - * marker_34: "011111010000111011111110110101100101" - */ - CV_WRAP bool readDictionary(const cv::FileNode& fn); - - /** @brief Write a dictionary to FileStorage, format is the same as in readDictionary(). - */ - CV_WRAP void writeDictionary(FileStorage& fs, const String& name = String()); - - /** @brief Given a matrix of bits. Returns whether if marker is identified or not. - * - * Returns reference to the marker id in the dictionary (if any) and its rotation. - */ - CV_WRAP bool identify(const Mat &onlyBits, CV_OUT int &idx, CV_OUT int &rotation, double maxCorrectionRate) const; - - /** @brief Returns Hamming distance of the input bits to the specific id. - * - * If `allRotations` flag is set, the four posible marker rotations are considered - */ - CV_WRAP int getDistanceToId(InputArray bits, int id, bool allRotations = true) const; - - - /** @brief Generate a canonical marker image - */ - CV_WRAP void generateImageMarker(int id, int sidePixels, OutputArray _img, int borderBits = 1) const; - - - /** @brief Transform matrix of bits to list of bytes with 4 marker rotations - */ - CV_WRAP static Mat getByteListFromBits(const Mat &bits); - - - /** @brief Transform list of bytes to matrix of bits - */ - CV_WRAP static Mat getBitsFromByteList(const Mat &byteList, int markerSize); -}; - - - - -/** @brief Predefined markers dictionaries/sets - * - * Each dictionary indicates the number of bits and the number of markers contained - * - DICT_ARUCO_ORIGINAL: standard ArUco Library Markers. 1024 markers, 5x5 bits, 0 minimum - distance - */ -enum PredefinedDictionaryType { - DICT_4X4_50 = 0, ///< 4x4 bits, minimum hamming distance between any two codes = 4, 50 codes - DICT_4X4_100, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 100 codes - DICT_4X4_250, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 250 codes - DICT_4X4_1000, ///< 4x4 bits, minimum hamming distance between any two codes = 2, 1000 codes - DICT_5X5_50, ///< 5x5 bits, minimum hamming distance between any two codes = 8, 50 codes - DICT_5X5_100, ///< 5x5 bits, minimum hamming distance between any two codes = 7, 100 codes - DICT_5X5_250, ///< 5x5 bits, minimum hamming distance between any two codes = 6, 250 codes - DICT_5X5_1000, ///< 5x5 bits, minimum hamming distance between any two codes = 5, 1000 codes - DICT_6X6_50, ///< 6x6 bits, minimum hamming distance between any two codes = 13, 50 codes - DICT_6X6_100, ///< 6x6 bits, minimum hamming distance between any two codes = 12, 100 codes - DICT_6X6_250, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 250 codes - DICT_6X6_1000, ///< 6x6 bits, minimum hamming distance between any two codes = 9, 1000 codes - DICT_7X7_50, ///< 7x7 bits, minimum hamming distance between any two codes = 19, 50 codes - DICT_7X7_100, ///< 7x7 bits, minimum hamming distance between any two codes = 18, 100 codes - DICT_7X7_250, ///< 7x7 bits, minimum hamming distance between any two codes = 17, 250 codes - DICT_7X7_1000, ///< 7x7 bits, minimum hamming distance between any two codes = 14, 1000 codes - DICT_ARUCO_ORIGINAL, ///< 6x6 bits, minimum hamming distance between any two codes = 3, 1024 codes - DICT_APRILTAG_16h5, ///< 4x4 bits, minimum hamming distance between any two codes = 5, 30 codes - DICT_APRILTAG_25h9, ///< 5x5 bits, minimum hamming distance between any two codes = 9, 35 codes - DICT_APRILTAG_36h10, ///< 6x6 bits, minimum hamming distance between any two codes = 10, 2320 codes - DICT_APRILTAG_36h11, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 587 codes - DICT_ARUCO_MIP_36h12 ///< 6x6 bits, minimum hamming distance between any two codes = 12, 250 codes -}; - - -/** @brief Returns one of the predefined dictionaries defined in PredefinedDictionaryType - */ -CV_EXPORTS Dictionary getPredefinedDictionary(PredefinedDictionaryType name); - - -/** @brief Returns one of the predefined dictionaries referenced by DICT_*. - */ -CV_EXPORTS_W Dictionary getPredefinedDictionary(int dict); - -/** @brief Extend base dictionary by new nMarkers - * - * @param nMarkers number of markers in the dictionary - * @param markerSize number of bits per dimension of each markers - * @param baseDictionary Include the markers in this dictionary at the beginning (optional) - * @param randomSeed a user supplied seed for theRNG() - * - * This function creates a new dictionary composed by nMarkers markers and each markers composed - * by markerSize x markerSize bits. If baseDictionary is provided, its markers are directly - * included and the rest are generated based on them. If the size of baseDictionary is higher - * than nMarkers, only the first nMarkers in baseDictionary are taken and no new marker is added. - */ -CV_EXPORTS_W Dictionary extendDictionary(int nMarkers, int markerSize, const Dictionary &baseDictionary = Dictionary(), - int randomSeed=0); - - - -//! @} -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_DICTIONARY_HPP +#define OPENCV_OBJDETECT_DICTIONARY_HPP + +#include + +namespace cv { +namespace aruco { + +//! @addtogroup objdetect_aruco +//! @{ + + +/** @brief Dictionary is a set of unique ArUco markers of the same size + * + * `bytesList` storing as 2-dimensions Mat with 4-th channels (CV_8UC4 type was used) and contains the marker codewords where: + * - bytesList.rows is the dictionary size + * - each marker is encoded using `nbytes = ceil(markerSize*markerSize/8.)` bytes + * - each row contains all 4 rotations of the marker, so its length is `4*nbytes` + * - the byte order in the bytesList[i] row: + * `//bytes without rotation/bytes with rotation 1/bytes with rotation 2/bytes with rotation 3//` + * So `bytesList.ptr(i)[k*nbytes + j]` is the j-th byte of i-th marker, in its k-th rotation. + * @note Python bindings generate matrix with shape of bytesList `dictionary_size x nbytes x 4`, + * but it should be indexed like C++ version. Python example for j-th byte of i-th marker, in its k-th rotation: + * `aruco_dict.bytesList[id].ravel()[k*nbytes + j]` + */ +class CV_EXPORTS_W_SIMPLE Dictionary { + + public: + CV_PROP_RW Mat bytesList; ///< marker code information. See class description for more details + CV_PROP_RW int markerSize; ///< number of bits per dimension + CV_PROP_RW int maxCorrectionBits; ///< maximum number of bits that can be corrected + + CV_WRAP Dictionary(); + + /** @brief Basic ArUco dictionary constructor + * + * @param bytesList bits for all ArUco markers in dictionary see memory layout in the class description + * @param _markerSize ArUco marker size in units + * @param maxcorr maximum number of bits that can be corrected + */ + CV_WRAP Dictionary(const Mat &bytesList, int _markerSize, int maxcorr = 0); + + /** @brief Read a new dictionary from FileNode. + * + * Dictionary example in YAML format:\n + * nmarkers: 35\n + * markersize: 6\n + * maxCorrectionBits: 5\n + * marker_0: "101011111011111001001001101100000000"\n + * ...\n + * marker_34: "011111010000111011111110110101100101" + */ + CV_WRAP bool readDictionary(const cv::FileNode& fn); + + /** @brief Write a dictionary to FileStorage, format is the same as in readDictionary(). + */ + CV_WRAP void writeDictionary(FileStorage& fs, const String& name = String()); + + /** @brief Given a matrix of bits. Returns whether if marker is identified or not. + * + * Returns reference to the marker id in the dictionary (if any) and its rotation. + */ + CV_WRAP bool identify(const Mat &onlyBits, CV_OUT int &idx, CV_OUT int &rotation, double maxCorrectionRate) const; + + /** @brief Returns Hamming distance of the input bits to the specific id. + * + * If `allRotations` flag is set, the four posible marker rotations are considered + */ + CV_WRAP int getDistanceToId(InputArray bits, int id, bool allRotations = true) const; + + + /** @brief Generate a canonical marker image + */ + CV_WRAP void generateImageMarker(int id, int sidePixels, OutputArray _img, int borderBits = 1) const; + + + /** @brief Transform matrix of bits to list of bytes with 4 marker rotations + */ + CV_WRAP static Mat getByteListFromBits(const Mat &bits); + + + /** @brief Transform list of bytes to matrix of bits + */ + CV_WRAP static Mat getBitsFromByteList(const Mat &byteList, int markerSize); +}; + + + + +/** @brief Predefined markers dictionaries/sets + * + * Each dictionary indicates the number of bits and the number of markers contained + * - DICT_ARUCO_ORIGINAL: standard ArUco Library Markers. 1024 markers, 5x5 bits, 0 minimum + distance + */ +enum PredefinedDictionaryType { + DICT_4X4_50 = 0, ///< 4x4 bits, minimum hamming distance between any two codes = 4, 50 codes + DICT_4X4_100, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 100 codes + DICT_4X4_250, ///< 4x4 bits, minimum hamming distance between any two codes = 3, 250 codes + DICT_4X4_1000, ///< 4x4 bits, minimum hamming distance between any two codes = 2, 1000 codes + DICT_5X5_50, ///< 5x5 bits, minimum hamming distance between any two codes = 8, 50 codes + DICT_5X5_100, ///< 5x5 bits, minimum hamming distance between any two codes = 7, 100 codes + DICT_5X5_250, ///< 5x5 bits, minimum hamming distance between any two codes = 6, 250 codes + DICT_5X5_1000, ///< 5x5 bits, minimum hamming distance between any two codes = 5, 1000 codes + DICT_6X6_50, ///< 6x6 bits, minimum hamming distance between any two codes = 13, 50 codes + DICT_6X6_100, ///< 6x6 bits, minimum hamming distance between any two codes = 12, 100 codes + DICT_6X6_250, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 250 codes + DICT_6X6_1000, ///< 6x6 bits, minimum hamming distance between any two codes = 9, 1000 codes + DICT_7X7_50, ///< 7x7 bits, minimum hamming distance between any two codes = 19, 50 codes + DICT_7X7_100, ///< 7x7 bits, minimum hamming distance between any two codes = 18, 100 codes + DICT_7X7_250, ///< 7x7 bits, minimum hamming distance between any two codes = 17, 250 codes + DICT_7X7_1000, ///< 7x7 bits, minimum hamming distance between any two codes = 14, 1000 codes + DICT_ARUCO_ORIGINAL, ///< 6x6 bits, minimum hamming distance between any two codes = 3, 1024 codes + DICT_APRILTAG_16h5, ///< 4x4 bits, minimum hamming distance between any two codes = 5, 30 codes + DICT_APRILTAG_25h9, ///< 5x5 bits, minimum hamming distance between any two codes = 9, 35 codes + DICT_APRILTAG_36h10, ///< 6x6 bits, minimum hamming distance between any two codes = 10, 2320 codes + DICT_APRILTAG_36h11, ///< 6x6 bits, minimum hamming distance between any two codes = 11, 587 codes + DICT_ARUCO_MIP_36h12 ///< 6x6 bits, minimum hamming distance between any two codes = 12, 250 codes +}; + + +/** @brief Returns one of the predefined dictionaries defined in PredefinedDictionaryType + */ +CV_EXPORTS Dictionary getPredefinedDictionary(PredefinedDictionaryType name); + + +/** @brief Returns one of the predefined dictionaries referenced by DICT_*. + */ +CV_EXPORTS_W Dictionary getPredefinedDictionary(int dict); + +/** @brief Extend base dictionary by new nMarkers + * + * @param nMarkers number of markers in the dictionary + * @param markerSize number of bits per dimension of each markers + * @param baseDictionary Include the markers in this dictionary at the beginning (optional) + * @param randomSeed a user supplied seed for theRNG() + * + * This function creates a new dictionary composed by nMarkers markers and each markers composed + * by markerSize x markerSize bits. If baseDictionary is provided, its markers are directly + * included and the rest are generated based on them. If the size of baseDictionary is higher + * than nMarkers, only the first nMarkers in baseDictionary are taken and no new marker is added. + */ +CV_EXPORTS_W Dictionary extendDictionary(int nMarkers, int markerSize, const Dictionary &baseDictionary = Dictionary(), + int randomSeed=0); + + + +//! @} +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp index e36259f286..c20b67c0b2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/barcode.hpp @@ -1,111 +1,111 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. -// Copyright (c) 2020-2021 darkliang wangberlinT Certseeds - -#ifndef OPENCV_OBJDETECT_BARCODE_HPP -#define OPENCV_OBJDETECT_BARCODE_HPP - -#include -#include - -namespace cv { -namespace barcode { - -//! @addtogroup objdetect_barcode -//! @{ - -class CV_EXPORTS_W_SIMPLE BarcodeDetector : public cv::GraphicalCodeDetector -{ -public: - /** @brief Initialize the BarcodeDetector. - */ - CV_WRAP BarcodeDetector(); - /** @brief Initialize the BarcodeDetector. - * - * Parameters allow to load _optional_ Super Resolution DNN model for better quality. - * @param prototxt_path prototxt file path for the super resolution model - * @param model_path model file path for the super resolution model - */ - CV_WRAP BarcodeDetector(CV_WRAP_FILE_PATH const std::string &prototxt_path, CV_WRAP_FILE_PATH const std::string &model_path); - ~BarcodeDetector(); - - /** @brief Decodes barcode in image once it's found by the detect() method. - * - * @param img grayscale or color (BGR) image containing bar code. - * @param points vector of rotated rectangle vertices found by detect() method (or some other algorithm). - * For N detected barcodes, the dimensions of this array should be [N][4]. - * Order of four points in vector is bottomLeft, topLeft, topRight, bottomRight. - * @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. - * @param decoded_type vector strings, specifies the type of these barcodes - * @return true if at least one valid barcode have been found - */ - CV_WRAP bool decodeWithType(InputArray img, - InputArray points, - CV_OUT std::vector &decoded_info, - CV_OUT std::vector &decoded_type) const; - - /** @brief Both detects and decodes barcode - - * @param img grayscale or color (BGR) image containing barcode. - * @param decoded_info UTF8-encoded output vector of string(s) or empty vector of string if the codes cannot be decoded. - * @param decoded_type vector of strings, specifies the type of these barcodes - * @param points optional output vector of vertices of the found barcode rectangle. Will be empty if not found. - * @return true if at least one valid barcode have been found - */ - CV_WRAP bool detectAndDecodeWithType(InputArray img, - CV_OUT std::vector &decoded_info, - CV_OUT std::vector &decoded_type, - OutputArray points = noArray()) const; - - /** @brief Get detector downsampling threshold. - * - * @return detector downsampling threshold - */ - CV_WRAP double getDownsamplingThreshold() const; - - /** @brief Set detector downsampling threshold. - * - * By default, the detect method resizes the input image to this limit if the smallest image size is is greater than the threshold. - * Increasing this value can improve detection accuracy and the number of results at the expense of performance. - * Correlates with detector scales. Setting this to a large value will disable downsampling. - * @param thresh downsampling limit to apply (default 512) - * @see setDetectorScales - */ - CV_WRAP BarcodeDetector& setDownsamplingThreshold(double thresh); - - /** @brief Returns detector box filter sizes. - * - * @param sizes output parameter for returning the sizes. - */ - CV_WRAP void getDetectorScales(CV_OUT std::vector& sizes) const; - - /** @brief Set detector box filter sizes. - * - * Adjusts the value and the number of box filters used in the detect step. - * The filter sizes directly correlate with the expected line widths for a barcode. Corresponds to expected barcode distance. - * If the downsampling limit is increased, filter sizes need to be adjusted in an inversely proportional way. - * @param sizes box filter sizes, relative to minimum dimension of the image (default [0.01, 0.03, 0.06, 0.08]) - */ - CV_WRAP BarcodeDetector& setDetectorScales(const std::vector& sizes); - - /** @brief Get detector gradient magnitude threshold. - * - * @return detector gradient magnitude threshold. - */ - CV_WRAP double getGradientThreshold() const; - - /** @brief Set detector gradient magnitude threshold. - * - * Sets the coherence threshold for detected bounding boxes. - * Increasing this value will generate a closer fitted bounding box width and can reduce false-positives. - * Values between 16 and 1024 generally work, while too high of a value will remove valid detections. - * @param thresh gradient magnitude threshold (default 64). - */ - CV_WRAP BarcodeDetector& setGradientThreshold(double thresh); -}; -//! @} - -}} // cv::barcode:: - -#endif // OPENCV_OBJDETECT_BARCODE_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. +// Copyright (c) 2020-2021 darkliang wangberlinT Certseeds + +#ifndef OPENCV_OBJDETECT_BARCODE_HPP +#define OPENCV_OBJDETECT_BARCODE_HPP + +#include +#include + +namespace cv { +namespace barcode { + +//! @addtogroup objdetect_barcode +//! @{ + +class CV_EXPORTS_W_SIMPLE BarcodeDetector : public cv::GraphicalCodeDetector +{ +public: + /** @brief Initialize the BarcodeDetector. + */ + CV_WRAP BarcodeDetector(); + /** @brief Initialize the BarcodeDetector. + * + * Parameters allow to load _optional_ Super Resolution DNN model for better quality. + * @param prototxt_path prototxt file path for the super resolution model + * @param model_path model file path for the super resolution model + */ + CV_WRAP BarcodeDetector(CV_WRAP_FILE_PATH const std::string &prototxt_path, CV_WRAP_FILE_PATH const std::string &model_path); + ~BarcodeDetector(); + + /** @brief Decodes barcode in image once it's found by the detect() method. + * + * @param img grayscale or color (BGR) image containing bar code. + * @param points vector of rotated rectangle vertices found by detect() method (or some other algorithm). + * For N detected barcodes, the dimensions of this array should be [N][4]. + * Order of four points in vector is bottomLeft, topLeft, topRight, bottomRight. + * @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. + * @param decoded_type vector strings, specifies the type of these barcodes + * @return true if at least one valid barcode have been found + */ + CV_WRAP bool decodeWithType(InputArray img, + InputArray points, + CV_OUT std::vector &decoded_info, + CV_OUT std::vector &decoded_type) const; + + /** @brief Both detects and decodes barcode + + * @param img grayscale or color (BGR) image containing barcode. + * @param decoded_info UTF8-encoded output vector of string(s) or empty vector of string if the codes cannot be decoded. + * @param decoded_type vector of strings, specifies the type of these barcodes + * @param points optional output vector of vertices of the found barcode rectangle. Will be empty if not found. + * @return true if at least one valid barcode have been found + */ + CV_WRAP bool detectAndDecodeWithType(InputArray img, + CV_OUT std::vector &decoded_info, + CV_OUT std::vector &decoded_type, + OutputArray points = noArray()) const; + + /** @brief Get detector downsampling threshold. + * + * @return detector downsampling threshold + */ + CV_WRAP double getDownsamplingThreshold() const; + + /** @brief Set detector downsampling threshold. + * + * By default, the detect method resizes the input image to this limit if the smallest image size is is greater than the threshold. + * Increasing this value can improve detection accuracy and the number of results at the expense of performance. + * Correlates with detector scales. Setting this to a large value will disable downsampling. + * @param thresh downsampling limit to apply (default 512) + * @see setDetectorScales + */ + CV_WRAP BarcodeDetector& setDownsamplingThreshold(double thresh); + + /** @brief Returns detector box filter sizes. + * + * @param sizes output parameter for returning the sizes. + */ + CV_WRAP void getDetectorScales(CV_OUT std::vector& sizes) const; + + /** @brief Set detector box filter sizes. + * + * Adjusts the value and the number of box filters used in the detect step. + * The filter sizes directly correlate with the expected line widths for a barcode. Corresponds to expected barcode distance. + * If the downsampling limit is increased, filter sizes need to be adjusted in an inversely proportional way. + * @param sizes box filter sizes, relative to minimum dimension of the image (default [0.01, 0.03, 0.06, 0.08]) + */ + CV_WRAP BarcodeDetector& setDetectorScales(const std::vector& sizes); + + /** @brief Get detector gradient magnitude threshold. + * + * @return detector gradient magnitude threshold. + */ + CV_WRAP double getGradientThreshold() const; + + /** @brief Set detector gradient magnitude threshold. + * + * Sets the coherence threshold for detected bounding boxes. + * Increasing this value will generate a closer fitted bounding box width and can reduce false-positives. + * Values between 16 and 1024 generally work, while too high of a value will remove valid detections. + * @param thresh gradient magnitude threshold (default 64). + */ + CV_WRAP BarcodeDetector& setGradientThreshold(double thresh); +}; +//! @} + +}} // cv::barcode:: + +#endif // OPENCV_OBJDETECT_BARCODE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp index 5adfe2931c..e10cb3f025 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/charuco_detector.hpp @@ -1,157 +1,157 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP -#define OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP - -#include "opencv2/objdetect/aruco_detector.hpp" - -namespace cv { -namespace aruco { - -//! @addtogroup objdetect_aruco -//! @{ - -struct CV_EXPORTS_W_SIMPLE CharucoParameters { - CV_WRAP CharucoParameters() { - minMarkers = 2; - tryRefineMarkers = false; - } - /// cameraMatrix optional 3x3 floating-point camera matrix - CV_PROP_RW Mat cameraMatrix; - - /// distCoeffs optional vector of distortion coefficients - CV_PROP_RW Mat distCoeffs; - - /// minMarkers number of adjacent markers that must be detected to return a charuco corner, default = 2 - CV_PROP_RW int minMarkers; - - /// try to use refine board, default false - CV_PROP_RW bool tryRefineMarkers; -}; - -class CV_EXPORTS_W CharucoDetector : public Algorithm { -public: - /** @brief Basic CharucoDetector constructor - * - * @param board ChAruco board - * @param charucoParams charuco detection parameters - * @param detectorParams marker detection parameters - * @param refineParams marker refine detection parameters - */ - CV_WRAP CharucoDetector(const CharucoBoard& board, - const CharucoParameters& charucoParams = CharucoParameters(), - const DetectorParameters &detectorParams = DetectorParameters(), - const RefineParameters& refineParams = RefineParameters()); - - CV_WRAP const CharucoBoard& getBoard() const; - CV_WRAP void setBoard(const CharucoBoard& board); - - CV_WRAP const CharucoParameters& getCharucoParameters() const; - CV_WRAP void setCharucoParameters(CharucoParameters& charucoParameters); - - CV_WRAP const DetectorParameters& getDetectorParameters() const; - CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); - - CV_WRAP const RefineParameters& getRefineParameters() const; - CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); - - /** - * @brief detect aruco markers and interpolate position of ChArUco board corners - * @param image input image necesary for corner refinement. Note that markers are not detected and - * should be sent in corners and ids parameters. - * @param charucoCorners interpolated chessboard corners. - * @param charucoIds interpolated chessboard corners identifiers. - * @param markerCorners vector of already detected markers corners. For each marker, its four - * corners are provided, (e.g std::vector > ). For N detected markers, the - * dimensions of this array should be Nx4. The order of the corners should be clockwise. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * @param markerIds list of identifiers for each marker in corners. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * - * This function receives the detected markers and returns the 2D position of the chessboard corners - * from a ChArUco board using the detected Aruco markers. - * - * If markerCorners and markerCorners are empty, the detectMarkers() will run and detect aruco markers and ids. - * - * If camera parameters are provided, the process is based in an approximated pose estimation, else it is based on local homography. - * Only visible corners are returned. For each corner, its corresponding identifier is also returned in charucoIds. - * @sa findChessboardCorners - * @note After OpenCV 4.6.0, there was an incompatible change in the ChArUco pattern generation algorithm for even row counts. - * Use cv::aruco::CharucoBoard::setLegacyPattern() to ensure compatibility with patterns created using OpenCV versions prior to 4.6.0. - * For more information, see the issue: https://github.com/opencv/opencv/issues/23152 - */ - CV_WRAP void detectBoard(InputArray image, OutputArray charucoCorners, OutputArray charucoIds, - InputOutputArrayOfArrays markerCorners = noArray(), - InputOutputArray markerIds = noArray()) const; - - /** - * @brief Detect ChArUco Diamond markers - * - * @param image input image necessary for corner subpixel. - * @param diamondCorners output list of detected diamond corners (4 corners per diamond). The order - * is the same than in marker corners: top left, top right, bottom right and bottom left. Similar - * format than the corners returned by detectMarkers (e.g std::vector > ). - * @param diamondIds ids of the diamonds in diamondCorners. The id of each diamond is in fact of - * type Vec4i, so each diamond has 4 ids, which are the ids of the aruco markers composing the - * diamond. - * @param markerCorners list of detected marker corners from detectMarkers function. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * @param markerIds list of marker ids in markerCorners. - * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. - * - * This function detects Diamond markers from the previous detected ArUco markers. The diamonds - * are returned in the diamondCorners and diamondIds parameters. If camera calibration parameters - * are provided, the diamond search is based on reprojection. If not, diamond search is based on - * homography. Homography is faster than reprojection, but less accurate. - */ - CV_WRAP void detectDiamonds(InputArray image, OutputArrayOfArrays diamondCorners, OutputArray diamondIds, - InputOutputArrayOfArrays markerCorners = noArray(), - InputOutputArray markerIds = noArray()) const; -protected: - struct CharucoDetectorImpl; - Ptr charucoDetectorImpl; -}; - -/** - * @brief Draws a set of Charuco corners - * @param image input/output image. It must have 1 or 3 channels. The number of channels is not - * altered. - * @param charucoCorners vector of detected charuco corners - * @param charucoIds list of identifiers for each corner in charucoCorners - * @param cornerColor color of the square surrounding each corner - * - * This function draws a set of detected Charuco corners. If identifiers vector is provided, it also - * draws the id of each corner. - */ -CV_EXPORTS_W void drawDetectedCornersCharuco(InputOutputArray image, InputArray charucoCorners, - InputArray charucoIds = noArray(), Scalar cornerColor = Scalar(255, 0, 0)); - -/** - * @brief Draw a set of detected ChArUco Diamond markers - * - * @param image input/output image. It must have 1 or 3 channels. The number of channels is not - * altered. - * @param diamondCorners positions of diamond corners in the same format returned by - * detectCharucoDiamond(). (e.g std::vector > ). For N detected markers, - * the dimensions of this array should be Nx4. The order of the corners should be clockwise. - * @param diamondIds vector of identifiers for diamonds in diamondCorners, in the same format - * returned by detectCharucoDiamond() (e.g. std::vector). - * Optional, if not provided, ids are not painted. - * @param borderColor color of marker borders. Rest of colors (text color and first corner color) - * are calculated based on this one. - * - * Given an array of detected diamonds, this functions draws them in the image. The marker borders - * are painted and the markers identifiers if provided. - * Useful for debugging purposes. - */ -CV_EXPORTS_W void drawDetectedDiamonds(InputOutputArray image, InputArrayOfArrays diamondCorners, - InputArray diamondIds = noArray(), - Scalar borderColor = Scalar(0, 0, 255)); - -//! @} - -} -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP +#define OPENCV_OBJDETECT_CHARUCO_DETECTOR_HPP + +#include "opencv2/objdetect/aruco_detector.hpp" + +namespace cv { +namespace aruco { + +//! @addtogroup objdetect_aruco +//! @{ + +struct CV_EXPORTS_W_SIMPLE CharucoParameters { + CV_WRAP CharucoParameters() { + minMarkers = 2; + tryRefineMarkers = false; + } + /// cameraMatrix optional 3x3 floating-point camera matrix + CV_PROP_RW Mat cameraMatrix; + + /// distCoeffs optional vector of distortion coefficients + CV_PROP_RW Mat distCoeffs; + + /// minMarkers number of adjacent markers that must be detected to return a charuco corner, default = 2 + CV_PROP_RW int minMarkers; + + /// try to use refine board, default false + CV_PROP_RW bool tryRefineMarkers; +}; + +class CV_EXPORTS_W CharucoDetector : public Algorithm { +public: + /** @brief Basic CharucoDetector constructor + * + * @param board ChAruco board + * @param charucoParams charuco detection parameters + * @param detectorParams marker detection parameters + * @param refineParams marker refine detection parameters + */ + CV_WRAP CharucoDetector(const CharucoBoard& board, + const CharucoParameters& charucoParams = CharucoParameters(), + const DetectorParameters &detectorParams = DetectorParameters(), + const RefineParameters& refineParams = RefineParameters()); + + CV_WRAP const CharucoBoard& getBoard() const; + CV_WRAP void setBoard(const CharucoBoard& board); + + CV_WRAP const CharucoParameters& getCharucoParameters() const; + CV_WRAP void setCharucoParameters(CharucoParameters& charucoParameters); + + CV_WRAP const DetectorParameters& getDetectorParameters() const; + CV_WRAP void setDetectorParameters(const DetectorParameters& detectorParameters); + + CV_WRAP const RefineParameters& getRefineParameters() const; + CV_WRAP void setRefineParameters(const RefineParameters& refineParameters); + + /** + * @brief detect aruco markers and interpolate position of ChArUco board corners + * @param image input image necesary for corner refinement. Note that markers are not detected and + * should be sent in corners and ids parameters. + * @param charucoCorners interpolated chessboard corners. + * @param charucoIds interpolated chessboard corners identifiers. + * @param markerCorners vector of already detected markers corners. For each marker, its four + * corners are provided, (e.g std::vector > ). For N detected markers, the + * dimensions of this array should be Nx4. The order of the corners should be clockwise. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * @param markerIds list of identifiers for each marker in corners. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * + * This function receives the detected markers and returns the 2D position of the chessboard corners + * from a ChArUco board using the detected Aruco markers. + * + * If markerCorners and markerCorners are empty, the detectMarkers() will run and detect aruco markers and ids. + * + * If camera parameters are provided, the process is based in an approximated pose estimation, else it is based on local homography. + * Only visible corners are returned. For each corner, its corresponding identifier is also returned in charucoIds. + * @sa findChessboardCorners + * @note After OpenCV 4.6.0, there was an incompatible change in the ChArUco pattern generation algorithm for even row counts. + * Use cv::aruco::CharucoBoard::setLegacyPattern() to ensure compatibility with patterns created using OpenCV versions prior to 4.6.0. + * For more information, see the issue: https://github.com/opencv/opencv/issues/23152 + */ + CV_WRAP void detectBoard(InputArray image, OutputArray charucoCorners, OutputArray charucoIds, + InputOutputArrayOfArrays markerCorners = noArray(), + InputOutputArray markerIds = noArray()) const; + + /** + * @brief Detect ChArUco Diamond markers + * + * @param image input image necessary for corner subpixel. + * @param diamondCorners output list of detected diamond corners (4 corners per diamond). The order + * is the same than in marker corners: top left, top right, bottom right and bottom left. Similar + * format than the corners returned by detectMarkers (e.g std::vector > ). + * @param diamondIds ids of the diamonds in diamondCorners. The id of each diamond is in fact of + * type Vec4i, so each diamond has 4 ids, which are the ids of the aruco markers composing the + * diamond. + * @param markerCorners list of detected marker corners from detectMarkers function. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * @param markerIds list of marker ids in markerCorners. + * If markerCorners and markerCorners are empty, the function detect aruco markers and ids. + * + * This function detects Diamond markers from the previous detected ArUco markers. The diamonds + * are returned in the diamondCorners and diamondIds parameters. If camera calibration parameters + * are provided, the diamond search is based on reprojection. If not, diamond search is based on + * homography. Homography is faster than reprojection, but less accurate. + */ + CV_WRAP void detectDiamonds(InputArray image, OutputArrayOfArrays diamondCorners, OutputArray diamondIds, + InputOutputArrayOfArrays markerCorners = noArray(), + InputOutputArray markerIds = noArray()) const; +protected: + struct CharucoDetectorImpl; + Ptr charucoDetectorImpl; +}; + +/** + * @brief Draws a set of Charuco corners + * @param image input/output image. It must have 1 or 3 channels. The number of channels is not + * altered. + * @param charucoCorners vector of detected charuco corners + * @param charucoIds list of identifiers for each corner in charucoCorners + * @param cornerColor color of the square surrounding each corner + * + * This function draws a set of detected Charuco corners. If identifiers vector is provided, it also + * draws the id of each corner. + */ +CV_EXPORTS_W void drawDetectedCornersCharuco(InputOutputArray image, InputArray charucoCorners, + InputArray charucoIds = noArray(), Scalar cornerColor = Scalar(255, 0, 0)); + +/** + * @brief Draw a set of detected ChArUco Diamond markers + * + * @param image input/output image. It must have 1 or 3 channels. The number of channels is not + * altered. + * @param diamondCorners positions of diamond corners in the same format returned by + * detectCharucoDiamond(). (e.g std::vector > ). For N detected markers, + * the dimensions of this array should be Nx4. The order of the corners should be clockwise. + * @param diamondIds vector of identifiers for diamonds in diamondCorners, in the same format + * returned by detectCharucoDiamond() (e.g. std::vector). + * Optional, if not provided, ids are not painted. + * @param borderColor color of marker borders. Rest of colors (text color and first corner color) + * are calculated based on this one. + * + * Given an array of detected diamonds, this functions draws them in the image. The marker borders + * are painted and the markers identifiers if provided. + * Useful for debugging purposes. + */ +CV_EXPORTS_W void drawDetectedDiamonds(InputOutputArray image, InputArrayOfArrays diamondCorners, + InputArray diamondIds = noArray(), + Scalar borderColor = Scalar(0, 0, 255)); + +//! @} + +} +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp index 8fe43c2c6b..8050278b42 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/detection_based_tracker.hpp @@ -1,222 +1,222 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_OBJDETECT_DBT_HPP -#define OPENCV_OBJDETECT_DBT_HPP - -#include - -#include - -namespace cv -{ - -//! @addtogroup objdetect_cascade_classifier -//! @{ - -class CV_EXPORTS DetectionBasedTracker -{ - public: - struct CV_EXPORTS Parameters - { - int maxTrackLifetime; - int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 - - Parameters(); - }; - - class IDetector - { - public: - IDetector(): - minObjSize(96, 96), - maxObjSize(INT_MAX, INT_MAX), - minNeighbours(2), - scaleFactor(1.1f) - {} - - virtual void detect(const cv::Mat& image, std::vector& objects) = 0; - - void setMinObjectSize(const cv::Size& min) - { - minObjSize = min; - } - void setMaxObjectSize(const cv::Size& max) - { - maxObjSize = max; - } - cv::Size getMinObjectSize() const - { - return minObjSize; - } - cv::Size getMaxObjectSize() const - { - return maxObjSize; - } - float getScaleFactor() - { - return scaleFactor; - } - void setScaleFactor(float value) - { - scaleFactor = value; - } - int getMinNeighbours() - { - return minNeighbours; - } - void setMinNeighbours(int value) - { - minNeighbours = value; - } - virtual ~IDetector() {} - - protected: - cv::Size minObjSize; - cv::Size maxObjSize; - int minNeighbours; - float scaleFactor; - }; - - DetectionBasedTracker(cv::Ptr mainDetector, cv::Ptr trackingDetector, const Parameters& params); - virtual ~DetectionBasedTracker(); - - virtual bool run(); - virtual void stop(); - virtual void resetTracking(); - - virtual void process(const cv::Mat& imageGray); - - bool setParameters(const Parameters& params); - const Parameters& getParameters() const; - - - typedef std::pair Object; - virtual void getObjects(std::vector& result) const; - virtual void getObjects(std::vector& result) const; - - enum ObjectStatus - { - DETECTED_NOT_SHOWN_YET, - DETECTED, - DETECTED_TEMPORARY_LOST, - WRONG_OBJECT - }; - struct ExtObject - { - int id; - cv::Rect location; - ObjectStatus status; - ExtObject(int _id, cv::Rect _location, ObjectStatus _status) - :id(_id), location(_location), status(_status) - { - } - }; - virtual void getObjects(std::vector& result) const; - - - virtual int addObject(const cv::Rect& location); //returns id of the new object - - protected: - class SeparateDetectionWork; - cv::Ptr separateDetectionWork; - friend void* workcycleObjectDetectorFunction(void* p); - - struct InnerParameters - { - int numLastPositionsToTrack; - int numStepsToWaitBeforeFirstShow; - int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; - int numStepsToShowWithoutDetecting; - - float coeffTrackingWindowSize; - float coeffObjectSizeToTrack; - float coeffObjectSpeedUsingInPrediction; - - InnerParameters(); - }; - Parameters parameters; - InnerParameters innerParameters; - - struct TrackedObject - { - typedef std::vector PositionsVector; - - PositionsVector lastPositions; - - int numDetectedFrames; - int numFramesNotDetected; - int id; - - TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) - { - lastPositions.push_back(rect); - id=getNextId(); - } - - static int getNextId() - { - static int _id=0; - return _id++; - } - }; - - int numTrackedSteps; - std::vector trackedObjects; - - std::vector weightsPositionsSmoothing; - std::vector weightsSizesSmoothing; - - cv::Ptr cascadeForTracking; - - void updateTrackedObjects(const std::vector& detectedObjects); - cv::Rect calcTrackedObjectPositionToShow(int i) const; - cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const; - void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector& detectedObjectsInRegions); -}; - -//! @} - -} //end of cv namespace - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_OBJDETECT_DBT_HPP +#define OPENCV_OBJDETECT_DBT_HPP + +#include + +#include + +namespace cv +{ + +//! @addtogroup objdetect_cascade_classifier +//! @{ + +class CV_EXPORTS DetectionBasedTracker +{ + public: + struct CV_EXPORTS Parameters + { + int maxTrackLifetime; + int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 + + Parameters(); + }; + + class IDetector + { + public: + IDetector(): + minObjSize(96, 96), + maxObjSize(INT_MAX, INT_MAX), + minNeighbours(2), + scaleFactor(1.1f) + {} + + virtual void detect(const cv::Mat& image, std::vector& objects) = 0; + + void setMinObjectSize(const cv::Size& min) + { + minObjSize = min; + } + void setMaxObjectSize(const cv::Size& max) + { + maxObjSize = max; + } + cv::Size getMinObjectSize() const + { + return minObjSize; + } + cv::Size getMaxObjectSize() const + { + return maxObjSize; + } + float getScaleFactor() + { + return scaleFactor; + } + void setScaleFactor(float value) + { + scaleFactor = value; + } + int getMinNeighbours() + { + return minNeighbours; + } + void setMinNeighbours(int value) + { + minNeighbours = value; + } + virtual ~IDetector() {} + + protected: + cv::Size minObjSize; + cv::Size maxObjSize; + int minNeighbours; + float scaleFactor; + }; + + DetectionBasedTracker(cv::Ptr mainDetector, cv::Ptr trackingDetector, const Parameters& params); + virtual ~DetectionBasedTracker(); + + virtual bool run(); + virtual void stop(); + virtual void resetTracking(); + + virtual void process(const cv::Mat& imageGray); + + bool setParameters(const Parameters& params); + const Parameters& getParameters() const; + + + typedef std::pair Object; + virtual void getObjects(std::vector& result) const; + virtual void getObjects(std::vector& result) const; + + enum ObjectStatus + { + DETECTED_NOT_SHOWN_YET, + DETECTED, + DETECTED_TEMPORARY_LOST, + WRONG_OBJECT + }; + struct ExtObject + { + int id; + cv::Rect location; + ObjectStatus status; + ExtObject(int _id, cv::Rect _location, ObjectStatus _status) + :id(_id), location(_location), status(_status) + { + } + }; + virtual void getObjects(std::vector& result) const; + + + virtual int addObject(const cv::Rect& location); //returns id of the new object + + protected: + class SeparateDetectionWork; + cv::Ptr separateDetectionWork; + friend void* workcycleObjectDetectorFunction(void* p); + + struct InnerParameters + { + int numLastPositionsToTrack; + int numStepsToWaitBeforeFirstShow; + int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; + int numStepsToShowWithoutDetecting; + + float coeffTrackingWindowSize; + float coeffObjectSizeToTrack; + float coeffObjectSpeedUsingInPrediction; + + InnerParameters(); + }; + Parameters parameters; + InnerParameters innerParameters; + + struct TrackedObject + { + typedef std::vector PositionsVector; + + PositionsVector lastPositions; + + int numDetectedFrames; + int numFramesNotDetected; + int id; + + TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) + { + lastPositions.push_back(rect); + id=getNextId(); + } + + static int getNextId() + { + static int _id=0; + return _id++; + } + }; + + int numTrackedSteps; + std::vector trackedObjects; + + std::vector weightsPositionsSmoothing; + std::vector weightsSizesSmoothing; + + cv::Ptr cascadeForTracking; + + void updateTrackedObjects(const std::vector& detectedObjects); + cv::Rect calcTrackedObjectPositionToShow(int i) const; + cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const; + void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector& detectedObjectsInRegions); +}; + +//! @} + +} //end of cv namespace + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp index 3528d73bc6..566204f7f9 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/face.hpp @@ -1,179 +1,179 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_OBJDETECT_FACE_HPP -#define OPENCV_OBJDETECT_FACE_HPP - -#include - -namespace cv -{ - -//! @addtogroup objdetect_dnn_face -//! @{ - -/** @brief DNN-based face detector - -model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet - */ -class CV_EXPORTS_W FaceDetectorYN -{ -public: - virtual ~FaceDetectorYN() {} - - /** @brief Set the size for the network input, which overwrites the input size of creating model. Call this method when the size of input image does not match the input size when creating model - * - * @param input_size the size of the input image - */ - CV_WRAP virtual void setInputSize(const Size& input_size) = 0; - - CV_WRAP virtual Size getInputSize() = 0; - - /** @brief Set the score threshold to filter out bounding boxes of score less than the given value - * - * @param score_threshold threshold for filtering out bounding boxes - */ - CV_WRAP virtual void setScoreThreshold(float score_threshold) = 0; - - CV_WRAP virtual float getScoreThreshold() = 0; - - /** @brief Set the Non-maximum-suppression threshold to suppress bounding boxes that have IoU greater than the given value - * - * @param nms_threshold threshold for NMS operation - */ - CV_WRAP virtual void setNMSThreshold(float nms_threshold) = 0; - - CV_WRAP virtual float getNMSThreshold() = 0; - - /** @brief Set the number of bounding boxes preserved before NMS - * - * @param top_k the number of bounding boxes to preserve from top rank based on score - */ - CV_WRAP virtual void setTopK(int top_k) = 0; - - CV_WRAP virtual int getTopK() = 0; - - /** @brief Detects faces in the input image. Following is an example output. - - * ![image](pics/lena-face-detection.jpg) - - * @param image an image to detect - * @param faces detection results stored in a 2D cv::Mat of shape [num_faces, 15] - * - 0-1: x, y of bbox top left corner - * - 2-3: width, height of bbox - * - 4-5: x, y of right eye (blue point in the example image) - * - 6-7: x, y of left eye (red point in the example image) - * - 8-9: x, y of nose tip (green point in the example image) - * - 10-11: x, y of right corner of mouth (pink point in the example image) - * - 12-13: x, y of left corner of mouth (yellow point in the example image) - * - 14: face score - */ - CV_WRAP virtual int detect(InputArray image, OutputArray faces) = 0; - - /** @brief Creates an instance of face detector class with given parameters - * - * @param model the path to the requested model - * @param config the path to the config file for compability, which is not requested for ONNX models - * @param input_size the size of the input image - * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value - * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value - * @param top_k keep top K bboxes before NMS - * @param backend_id the id of backend - * @param target_id the id of target device - */ - CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, - CV_WRAP_FILE_PATH const String& config, - const Size& input_size, - float score_threshold = 0.9f, - float nms_threshold = 0.3f, - int top_k = 5000, - int backend_id = 0, - int target_id = 0); - - /** @overload - * - * @param framework Name of origin framework - * @param bufferModel A buffer with a content of binary file with weights - * @param bufferConfig A buffer with a content of text file contains network configuration - * @param input_size the size of the input image - * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value - * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value - * @param top_k keep top K bboxes before NMS - * @param backend_id the id of backend - * @param target_id the id of target device - */ - CV_WRAP static Ptr create(const String& framework, - const std::vector& bufferModel, - const std::vector& bufferConfig, - const Size& input_size, - float score_threshold = 0.9f, - float nms_threshold = 0.3f, - int top_k = 5000, - int backend_id = 0, - int target_id = 0); - -}; - -/** @brief DNN-based face recognizer - -model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_recognition_sface - */ -class CV_EXPORTS_W FaceRecognizerSF -{ -public: - virtual ~FaceRecognizerSF() {} - - /** @brief Definition of distance used for calculating the distance between two face features - */ - enum DisType { FR_COSINE=0, FR_NORM_L2=1 }; - - /** @brief Aligns detected face with the source input image and crops it - * @param src_img input image - * @param face_box the detected face result from the input image - * @param aligned_img output aligned image - */ - CV_WRAP virtual void alignCrop(InputArray src_img, InputArray face_box, OutputArray aligned_img) const = 0; - - /** @brief Extracts face feature from aligned image - * @param aligned_img input aligned image - * @param face_feature output face feature - */ - CV_WRAP virtual void feature(InputArray aligned_img, OutputArray face_feature) = 0; - - /** @brief Calculates the distance between two face features - * @param face_feature1 the first input feature - * @param face_feature2 the second input feature of the same size and the same type as face_feature1 - * @param dis_type defines how to calculate the distance between two face features with optional values "FR_COSINE" or "FR_NORM_L2" - */ - CV_WRAP virtual double match(InputArray face_feature1, InputArray face_feature2, int dis_type = FaceRecognizerSF::FR_COSINE) const = 0; - - /** @brief Creates an instance of this class with given parameters - * @param model the path of the onnx model used for face recognition - * @param config the path to the config file for compability, which is not requested for ONNX models - * @param backend_id the id of backend - * @param target_id the id of target device - */ - CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config, int backend_id = 0, int target_id = 0); - - /** - * @brief Creates an instance of this class from a buffer containing the model weights and configuration. - * @param framework Name of the framework (ONNX, etc.) - * @param bufferModel A buffer containing the binary model weights. - * @param bufferConfig A buffer containing the network configuration. - * @param backend_id The id of the backend. - * @param target_id The id of the target device. - * - * @return A pointer to the created instance of FaceRecognizerSF. - */ - CV_WRAP static Ptr create(const String& framework, - const std::vector& bufferModel, - const std::vector& bufferConfig, - int backend_id = 0, - int target_id = 0); -}; - -//! @} -} // namespace cv - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_OBJDETECT_FACE_HPP +#define OPENCV_OBJDETECT_FACE_HPP + +#include + +namespace cv +{ + +//! @addtogroup objdetect_dnn_face +//! @{ + +/** @brief DNN-based face detector + +model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet + */ +class CV_EXPORTS_W FaceDetectorYN +{ +public: + virtual ~FaceDetectorYN() {} + + /** @brief Set the size for the network input, which overwrites the input size of creating model. Call this method when the size of input image does not match the input size when creating model + * + * @param input_size the size of the input image + */ + CV_WRAP virtual void setInputSize(const Size& input_size) = 0; + + CV_WRAP virtual Size getInputSize() = 0; + + /** @brief Set the score threshold to filter out bounding boxes of score less than the given value + * + * @param score_threshold threshold for filtering out bounding boxes + */ + CV_WRAP virtual void setScoreThreshold(float score_threshold) = 0; + + CV_WRAP virtual float getScoreThreshold() = 0; + + /** @brief Set the Non-maximum-suppression threshold to suppress bounding boxes that have IoU greater than the given value + * + * @param nms_threshold threshold for NMS operation + */ + CV_WRAP virtual void setNMSThreshold(float nms_threshold) = 0; + + CV_WRAP virtual float getNMSThreshold() = 0; + + /** @brief Set the number of bounding boxes preserved before NMS + * + * @param top_k the number of bounding boxes to preserve from top rank based on score + */ + CV_WRAP virtual void setTopK(int top_k) = 0; + + CV_WRAP virtual int getTopK() = 0; + + /** @brief Detects faces in the input image. Following is an example output. + + * ![image](pics/lena-face-detection.jpg) + + * @param image an image to detect + * @param faces detection results stored in a 2D cv::Mat of shape [num_faces, 15] + * - 0-1: x, y of bbox top left corner + * - 2-3: width, height of bbox + * - 4-5: x, y of right eye (blue point in the example image) + * - 6-7: x, y of left eye (red point in the example image) + * - 8-9: x, y of nose tip (green point in the example image) + * - 10-11: x, y of right corner of mouth (pink point in the example image) + * - 12-13: x, y of left corner of mouth (yellow point in the example image) + * - 14: face score + */ + CV_WRAP virtual int detect(InputArray image, OutputArray faces) = 0; + + /** @brief Creates an instance of face detector class with given parameters + * + * @param model the path to the requested model + * @param config the path to the config file for compability, which is not requested for ONNX models + * @param input_size the size of the input image + * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value + * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value + * @param top_k keep top K bboxes before NMS + * @param backend_id the id of backend + * @param target_id the id of target device + */ + CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, + CV_WRAP_FILE_PATH const String& config, + const Size& input_size, + float score_threshold = 0.9f, + float nms_threshold = 0.3f, + int top_k = 5000, + int backend_id = 0, + int target_id = 0); + + /** @overload + * + * @param framework Name of origin framework + * @param bufferModel A buffer with a content of binary file with weights + * @param bufferConfig A buffer with a content of text file contains network configuration + * @param input_size the size of the input image + * @param score_threshold the threshold to filter out bounding boxes of score smaller than the given value + * @param nms_threshold the threshold to suppress bounding boxes of IoU bigger than the given value + * @param top_k keep top K bboxes before NMS + * @param backend_id the id of backend + * @param target_id the id of target device + */ + CV_WRAP static Ptr create(const String& framework, + const std::vector& bufferModel, + const std::vector& bufferConfig, + const Size& input_size, + float score_threshold = 0.9f, + float nms_threshold = 0.3f, + int top_k = 5000, + int backend_id = 0, + int target_id = 0); + +}; + +/** @brief DNN-based face recognizer + +model download link: https://github.com/opencv/opencv_zoo/tree/master/models/face_recognition_sface + */ +class CV_EXPORTS_W FaceRecognizerSF +{ +public: + virtual ~FaceRecognizerSF() {} + + /** @brief Definition of distance used for calculating the distance between two face features + */ + enum DisType { FR_COSINE=0, FR_NORM_L2=1 }; + + /** @brief Aligns detected face with the source input image and crops it + * @param src_img input image + * @param face_box the detected face result from the input image + * @param aligned_img output aligned image + */ + CV_WRAP virtual void alignCrop(InputArray src_img, InputArray face_box, OutputArray aligned_img) const = 0; + + /** @brief Extracts face feature from aligned image + * @param aligned_img input aligned image + * @param face_feature output face feature + */ + CV_WRAP virtual void feature(InputArray aligned_img, OutputArray face_feature) = 0; + + /** @brief Calculates the distance between two face features + * @param face_feature1 the first input feature + * @param face_feature2 the second input feature of the same size and the same type as face_feature1 + * @param dis_type defines how to calculate the distance between two face features with optional values "FR_COSINE" or "FR_NORM_L2" + */ + CV_WRAP virtual double match(InputArray face_feature1, InputArray face_feature2, int dis_type = FaceRecognizerSF::FR_COSINE) const = 0; + + /** @brief Creates an instance of this class with given parameters + * @param model the path of the onnx model used for face recognition + * @param config the path to the config file for compability, which is not requested for ONNX models + * @param backend_id the id of backend + * @param target_id the id of target device + */ + CV_WRAP static Ptr create(CV_WRAP_FILE_PATH const String& model, CV_WRAP_FILE_PATH const String& config, int backend_id = 0, int target_id = 0); + + /** + * @brief Creates an instance of this class from a buffer containing the model weights and configuration. + * @param framework Name of the framework (ONNX, etc.) + * @param bufferModel A buffer containing the binary model weights. + * @param bufferConfig A buffer containing the network configuration. + * @param backend_id The id of the backend. + * @param target_id The id of the target device. + * + * @return A pointer to the created instance of FaceRecognizerSF. + */ + CV_WRAP static Ptr create(const String& framework, + const std::vector& bufferModel, + const std::vector& bufferConfig, + int backend_id = 0, + int target_id = 0); +}; + +//! @} +} // namespace cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp index e4200a4204..ed697c50c0 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/graphical_code_detector.hpp @@ -1,85 +1,85 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html -#ifndef OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP -#define OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP - -#include - -namespace cv { - -//! @addtogroup objdetect_common -//! @{ - -class CV_EXPORTS_W_SIMPLE GraphicalCodeDetector { -public: - CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) - GraphicalCodeDetector(); - - GraphicalCodeDetector(const GraphicalCodeDetector&) = default; - GraphicalCodeDetector(GraphicalCodeDetector&&) = default; - GraphicalCodeDetector& operator=(const GraphicalCodeDetector&) = default; - GraphicalCodeDetector& operator=(GraphicalCodeDetector&&) = default; - - /** @brief Detects graphical code in image and returns the quadrangle containing the code. - @param img grayscale or color (BGR) image containing (or not) graphical code. - @param points Output vector of vertices of the minimum-area quadrangle containing the code. - */ - CV_WRAP bool detect(InputArray img, OutputArray points) const; - - /** @brief Decodes graphical code in image once it's found by the detect() method. - - Returns UTF8-encoded output string or empty string if the code cannot be decoded. - @param img grayscale or color (BGR) image containing graphical code. - @param points Quadrangle vertices found by detect() method (or some other algorithm). - @param straight_code The optional output image containing binarized code, will be empty if not found. - */ - CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_code = noArray()) const; - - /** @brief Both detects and decodes graphical code - - @param img grayscale or color (BGR) image containing graphical code. - @param points optional output array of vertices of the found graphical code quadrangle, will be empty if not found. - @param straight_code The optional output image containing binarized code - */ - CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points = noArray(), - OutputArray straight_code = noArray()) const; - - - /** @brief Detects graphical codes in image and returns the vector of the quadrangles containing the codes. - @param img grayscale or color (BGR) image containing (or not) graphical codes. - @param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes. - */ - CV_WRAP bool detectMulti(InputArray img, OutputArray points) const; - - /** @brief Decodes graphical codes in image once it's found by the detect() method. - @param img grayscale or color (BGR) image containing graphical codes. - @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. - @param points vector of Quadrangle vertices found by detect() method (or some other algorithm). - @param straight_code The optional output vector of images containing binarized codes - */ - CV_WRAP bool decodeMulti(InputArray img, InputArray points, CV_OUT std::vector& decoded_info, - OutputArrayOfArrays straight_code = noArray()) const; - - /** @brief Both detects and decodes graphical codes - @param img grayscale or color (BGR) image containing graphical codes. - @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. - @param points optional output vector of vertices of the found graphical code quadrangles. Will be empty if not found. - @param straight_code The optional vector of images containing binarized codes - - - If there are QR codes encoded with a Structured Append mode on the image and all of them detected and decoded correctly, - method writes a full message to position corresponds to 0-th code in a sequence. The rest of QR codes from the same sequence - have empty string. - */ - CV_WRAP bool detectAndDecodeMulti(InputArray img, CV_OUT std::vector& decoded_info, OutputArray points = noArray(), - OutputArrayOfArrays straight_code = noArray()) const; - struct Impl; -protected: - Ptr p; -}; - -//! @} - -} - -#endif +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html +#ifndef OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP +#define OPENCV_OBJDETECT_GRAPHICAL_CODE_DETECTOR_HPP + +#include + +namespace cv { + +//! @addtogroup objdetect_common +//! @{ + +class CV_EXPORTS_W_SIMPLE GraphicalCodeDetector { +public: + CV_DEPRECATED_EXTERNAL // avoid using in C++ code, will be moved to "protected" (need to fix bindings first) + GraphicalCodeDetector(); + + GraphicalCodeDetector(const GraphicalCodeDetector&) = default; + GraphicalCodeDetector(GraphicalCodeDetector&&) = default; + GraphicalCodeDetector& operator=(const GraphicalCodeDetector&) = default; + GraphicalCodeDetector& operator=(GraphicalCodeDetector&&) = default; + + /** @brief Detects graphical code in image and returns the quadrangle containing the code. + @param img grayscale or color (BGR) image containing (or not) graphical code. + @param points Output vector of vertices of the minimum-area quadrangle containing the code. + */ + CV_WRAP bool detect(InputArray img, OutputArray points) const; + + /** @brief Decodes graphical code in image once it's found by the detect() method. + + Returns UTF8-encoded output string or empty string if the code cannot be decoded. + @param img grayscale or color (BGR) image containing graphical code. + @param points Quadrangle vertices found by detect() method (or some other algorithm). + @param straight_code The optional output image containing binarized code, will be empty if not found. + */ + CV_WRAP std::string decode(InputArray img, InputArray points, OutputArray straight_code = noArray()) const; + + /** @brief Both detects and decodes graphical code + + @param img grayscale or color (BGR) image containing graphical code. + @param points optional output array of vertices of the found graphical code quadrangle, will be empty if not found. + @param straight_code The optional output image containing binarized code + */ + CV_WRAP std::string detectAndDecode(InputArray img, OutputArray points = noArray(), + OutputArray straight_code = noArray()) const; + + + /** @brief Detects graphical codes in image and returns the vector of the quadrangles containing the codes. + @param img grayscale or color (BGR) image containing (or not) graphical codes. + @param points Output vector of vector of vertices of the minimum-area quadrangle containing the codes. + */ + CV_WRAP bool detectMulti(InputArray img, OutputArray points) const; + + /** @brief Decodes graphical codes in image once it's found by the detect() method. + @param img grayscale or color (BGR) image containing graphical codes. + @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. + @param points vector of Quadrangle vertices found by detect() method (or some other algorithm). + @param straight_code The optional output vector of images containing binarized codes + */ + CV_WRAP bool decodeMulti(InputArray img, InputArray points, CV_OUT std::vector& decoded_info, + OutputArrayOfArrays straight_code = noArray()) const; + + /** @brief Both detects and decodes graphical codes + @param img grayscale or color (BGR) image containing graphical codes. + @param decoded_info UTF8-encoded output vector of string or empty vector of string if the codes cannot be decoded. + @param points optional output vector of vertices of the found graphical code quadrangles. Will be empty if not found. + @param straight_code The optional vector of images containing binarized codes + + - If there are QR codes encoded with a Structured Append mode on the image and all of them detected and decoded correctly, + method writes a full message to position corresponds to 0-th code in a sequence. The rest of QR codes from the same sequence + have empty string. + */ + CV_WRAP bool detectAndDecodeMulti(InputArray img, CV_OUT std::vector& decoded_info, OutputArray points = noArray(), + OutputArrayOfArrays straight_code = noArray()) const; + struct Impl; +protected: + Ptr p; +}; + +//! @} + +} + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp b/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp index 2a0dfdd42b..3ee284f427 100644 --- a/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/objdetect/objdetect.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/objdetect.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/objdetect.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/opencv.hpp b/3rdParty/opencv-4.11.0/opencv2/opencv.hpp index 801d6a6aa4..d17b94a4ea 100644 --- a/3rdParty/opencv-4.11.0/opencv2/opencv.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/opencv.hpp @@ -1,95 +1,95 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_ALL_HPP -#define OPENCV_ALL_HPP - -// File that defines what modules where included during the build of OpenCV -// These are purely the defines of the correct HAVE_OPENCV_modulename values -#include "opencv2/opencv_modules.hpp" - -// Then the list of defines is checked to include the correct headers -// Core library is always included --> without no OpenCV functionality available -#include "opencv2/core.hpp" - -// Then the optional modules are checked -#ifdef HAVE_OPENCV_CALIB3D -#include "opencv2/calib3d.hpp" -#endif -#ifdef HAVE_OPENCV_FEATURES2D -#include "opencv2/features2d.hpp" -#endif -#ifdef HAVE_OPENCV_DNN -#include "opencv2/dnn.hpp" -#endif -#ifdef HAVE_OPENCV_FLANN -#include "opencv2/flann.hpp" -#endif -#ifdef HAVE_OPENCV_HIGHGUI -#include "opencv2/highgui.hpp" -#endif -#ifdef HAVE_OPENCV_IMGCODECS -#include "opencv2/imgcodecs.hpp" -#endif -#ifdef HAVE_OPENCV_IMGPROC -#include "opencv2/imgproc.hpp" -#endif -#ifdef HAVE_OPENCV_ML -#include "opencv2/ml.hpp" -#endif -#ifdef HAVE_OPENCV_OBJDETECT -#include "opencv2/objdetect.hpp" -#endif -#ifdef HAVE_OPENCV_PHOTO -#include "opencv2/photo.hpp" -#endif -#ifdef HAVE_OPENCV_STITCHING -#include "opencv2/stitching.hpp" -#endif -#ifdef HAVE_OPENCV_VIDEO -#include "opencv2/video.hpp" -#endif -#ifdef HAVE_OPENCV_VIDEOIO -#include "opencv2/videoio.hpp" -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_ALL_HPP +#define OPENCV_ALL_HPP + +// File that defines what modules where included during the build of OpenCV +// These are purely the defines of the correct HAVE_OPENCV_modulename values +#include "opencv2/opencv_modules.hpp" + +// Then the list of defines is checked to include the correct headers +// Core library is always included --> without no OpenCV functionality available +#include "opencv2/core.hpp" + +// Then the optional modules are checked +#ifdef HAVE_OPENCV_CALIB3D +#include "opencv2/calib3d.hpp" +#endif +#ifdef HAVE_OPENCV_FEATURES2D +#include "opencv2/features2d.hpp" +#endif +#ifdef HAVE_OPENCV_DNN +#include "opencv2/dnn.hpp" +#endif +#ifdef HAVE_OPENCV_FLANN +#include "opencv2/flann.hpp" +#endif +#ifdef HAVE_OPENCV_HIGHGUI +#include "opencv2/highgui.hpp" +#endif +#ifdef HAVE_OPENCV_IMGCODECS +#include "opencv2/imgcodecs.hpp" +#endif +#ifdef HAVE_OPENCV_IMGPROC +#include "opencv2/imgproc.hpp" +#endif +#ifdef HAVE_OPENCV_ML +#include "opencv2/ml.hpp" +#endif +#ifdef HAVE_OPENCV_OBJDETECT +#include "opencv2/objdetect.hpp" +#endif +#ifdef HAVE_OPENCV_PHOTO +#include "opencv2/photo.hpp" +#endif +#ifdef HAVE_OPENCV_STITCHING +#include "opencv2/stitching.hpp" +#endif +#ifdef HAVE_OPENCV_VIDEO +#include "opencv2/video.hpp" +#endif +#ifdef HAVE_OPENCV_VIDEOIO +#include "opencv2/videoio.hpp" +#endif + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp b/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp index eb15e4abff..c9e24d845f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/opencv_modules.hpp @@ -1,30 +1,30 @@ -/* - * ** File generated automatically, do not modify ** - * - * This file defines the list of modules available in current build configuration - * - * -*/ - -// This definition means that OpenCV is built with enabled non-free code. -// For example, patented algorithms for non-profit/non-commercial use only. -/* #undef OPENCV_ENABLE_NONFREE */ - -#define HAVE_OPENCV_CALIB3D -#define HAVE_OPENCV_CORE -#define HAVE_OPENCV_DNN -#define HAVE_OPENCV_FEATURES2D -#define HAVE_OPENCV_FLANN -#define HAVE_OPENCV_GAPI -#define HAVE_OPENCV_HIGHGUI -#define HAVE_OPENCV_IMGCODECS -#define HAVE_OPENCV_IMGPROC -#define HAVE_OPENCV_ML -#define HAVE_OPENCV_OBJDETECT -#define HAVE_OPENCV_PHOTO -#define HAVE_OPENCV_STITCHING -#define HAVE_OPENCV_VIDEO -#define HAVE_OPENCV_VIDEOIO -#define HAVE_OPENCV_WORLD - - +/* + * ** File generated automatically, do not modify ** + * + * This file defines the list of modules available in current build configuration + * + * +*/ + +// This definition means that OpenCV is built with enabled non-free code. +// For example, patented algorithms for non-profit/non-commercial use only. +/* #undef OPENCV_ENABLE_NONFREE */ + +#define HAVE_OPENCV_CALIB3D +#define HAVE_OPENCV_CORE +#define HAVE_OPENCV_DNN +#define HAVE_OPENCV_FEATURES2D +#define HAVE_OPENCV_FLANN +#define HAVE_OPENCV_GAPI +#define HAVE_OPENCV_HIGHGUI +#define HAVE_OPENCV_IMGCODECS +#define HAVE_OPENCV_IMGPROC +#define HAVE_OPENCV_ML +#define HAVE_OPENCV_OBJDETECT +#define HAVE_OPENCV_PHOTO +#define HAVE_OPENCV_STITCHING +#define HAVE_OPENCV_VIDEO +#define HAVE_OPENCV_VIDEOIO +#define HAVE_OPENCV_WORLD + + diff --git a/3rdParty/opencv-4.11.0/opencv2/photo.hpp b/3rdParty/opencv-4.11.0/opencv2/photo.hpp index 66f00b7e90..a8b7c6049a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/photo.hpp @@ -1,898 +1,898 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_PHOTO_HPP -#define OPENCV_PHOTO_HPP - -#include "opencv2/core.hpp" -#include "opencv2/imgproc.hpp" - -/** -@defgroup photo Computational Photography - -This module includes photo processing algorithms -@{ - @defgroup photo_inpaint Inpainting - @defgroup photo_denoise Denoising - @defgroup photo_hdr HDR imaging - - This section describes high dynamic range imaging algorithms namely tonemapping, exposure alignment, - camera calibration with multiple exposures and exposure fusion. - - @defgroup photo_decolor Contrast Preserving Decolorization - - Useful links: - - http://www.cse.cuhk.edu.hk/leojia/projects/color2gray/index.html - - @defgroup photo_clone Seamless Cloning - - Useful links: - - https://www.learnopencv.com/seamless-cloning-using-opencv-python-cpp - - @defgroup photo_render Non-Photorealistic Rendering - - Useful links: - - http://www.inf.ufrgs.br/~eslgastal/DomainTransform - - https://www.learnopencv.com/non-photorealistic-rendering-using-opencv-python-c/ - -@} - */ - -namespace cv -{ - -//! @addtogroup photo -//! @{ - -//! @addtogroup photo_inpaint -//! @{ -//! the inpainting algorithm -enum -{ - INPAINT_NS = 0, //!< Use Navier-Stokes based method - INPAINT_TELEA = 1 //!< Use the algorithm proposed by Alexandru Telea @cite Telea04 -}; - -/** @brief Restores the selected region in an image using the region neighborhood. - -@param src Input 8-bit, 16-bit unsigned or 32-bit float 1-channel or 8-bit 3-channel image. -@param inpaintMask Inpainting mask, 8-bit 1-channel image. Non-zero pixels indicate the area that -needs to be inpainted. -@param dst Output image with the same size and type as src . -@param inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered -by the algorithm. -@param flags Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA - -The function reconstructs the selected image area from the pixel near the area boundary. The -function may be used to remove dust and scratches from a scanned photo, or to remove undesirable -objects from still images or video. See for more details. - -@note - - An example using the inpainting technique can be found at - opencv_source_code/samples/cpp/inpaint.cpp - - (Python) An example using the inpainting technique can be found at - opencv_source_code/samples/python/inpaint.py - */ -CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask, - OutputArray dst, double inpaintRadius, int flags ); - -//! @} photo_inpaint - -//! @addtogroup photo_denoise -//! @{ - -/** @brief Perform image denoising using Non-local Means Denoising algorithm - with several computational -optimizations. Noise expected to be a gaussian white noise - -@param src Input 8-bit 1-channel, 2-channel, 3-channel or 4-channel image. -@param dst Output image with the same size and type as src . -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength. Big h value perfectly removes noise but also -removes image details, smaller h value preserves details but also preserves some noise - -This function expected to be applied to grayscale images. For colored images look at -fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored -image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting -image to CIELAB colorspace and then separately denoise L and AB components with different h -parameter. - */ -CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, float h = 3, - int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Perform image denoising using Non-local Means Denoising algorithm - with several computational -optimizations. Noise expected to be a gaussian white noise - -@param src Input 8-bit or 16-bit (only with NORM_L1) 1-channel, -2-channel, 3-channel or 4-channel image. -@param dst Output image with the same size and type as src . -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Array of parameters regulating filter strength, either one -parameter applied to all channels or one per channel in dst. Big h value -perfectly removes noise but also removes image details, smaller h -value preserves details but also preserves some noise -@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 - -This function expected to be applied to grayscale images. For colored images look at -fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored -image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting -image to CIELAB colorspace and then separately denoise L and AB components with different h -parameter. - */ -CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, - const std::vector& h, - int templateWindowSize = 7, int searchWindowSize = 21, - int normType = NORM_L2); - -/** @brief Modification of fastNlMeansDenoising function for colored images - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src . -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly -removes noise but also removes image details, smaller h value preserves details but also preserves -some noise -@param hColor The same as h but for color components. For most images value equals 10 -will be enough to remove colored noise and do not distort colors - -The function converts image to CIELAB colorspace and then separately denoise L and AB components -with given h parameters using fastNlMeansDenoising function. - */ -CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst, - float h = 3, float hColor = 3, - int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been -captured in small period of time. For example video. This version of the function is for grayscale -images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details -(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). - -@param srcImgs Input 8-bit 1-channel, 2-channel, 3-channel or -4-channel images sequence. All images should have the same type and -size. -@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence -@param temporalWindowSize Number of surrounding images to use for target image denoising. Should -be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to -imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise -srcImgs[imgToDenoiseIndex] image. -@param dst Output image with the same size and type as srcImgs images. -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength. Bigger h value -perfectly removes noise but also removes image details, smaller h -value preserves details but also preserves some noise - */ -CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, - int imgToDenoiseIndex, int temporalWindowSize, - float h = 3, int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been -captured in small period of time. For example video. This version of the function is for grayscale -images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details -(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). - -@param srcImgs Input 8-bit or 16-bit (only with NORM_L1) 1-channel, -2-channel, 3-channel or 4-channel images sequence. All images should -have the same type and size. -@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence -@param temporalWindowSize Number of surrounding images to use for target image denoising. Should -be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to -imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise -srcImgs[imgToDenoiseIndex] image. -@param dst Output image with the same size and type as srcImgs images. -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Array of parameters regulating filter strength, either one -parameter applied to all channels or one per channel in dst. Big h value -perfectly removes noise but also removes image details, smaller h -value preserves details but also preserves some noise -@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 - */ -CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, - int imgToDenoiseIndex, int temporalWindowSize, - const std::vector& h, - int templateWindowSize = 7, int searchWindowSize = 21, - int normType = NORM_L2); - -/** @brief Modification of fastNlMeansDenoisingMulti function for colored images sequences - -@param srcImgs Input 8-bit 3-channel images sequence. All images should have the same type and -size. -@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence -@param temporalWindowSize Number of surrounding images to use for target image denoising. Should -be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to -imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise -srcImgs[imgToDenoiseIndex] image. -@param dst Output image with the same size and type as srcImgs images. -@param templateWindowSize Size in pixels of the template patch that is used to compute weights. -Should be odd. Recommended value 7 pixels -@param searchWindowSize Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater -denoising time. Recommended value 21 pixels -@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly -removes noise but also removes image details, smaller h value preserves details but also preserves -some noise. -@param hColor The same as h but for color components. - -The function converts images to CIELAB colorspace and then separately denoise L and AB components -with given h parameters using fastNlMeansDenoisingMulti function. - */ -CV_EXPORTS_W void fastNlMeansDenoisingColoredMulti( InputArrayOfArrays srcImgs, OutputArray dst, - int imgToDenoiseIndex, int temporalWindowSize, - float h = 3, float hColor = 3, - int templateWindowSize = 7, int searchWindowSize = 21); - -/** @brief Primal-dual algorithm is an algorithm for solving special types of variational problems (that is, -finding a function to minimize some functional). As the image denoising, in particular, may be seen -as the variational problem, primal-dual algorithm then can be used to perform denoising and this is -exactly what is implemented. - -It should be noted, that this implementation was taken from the July 2013 blog entry -@cite MA13 , which also contained (slightly more general) ready-to-use source code on Python. -Subsequently, that code was rewritten on C++ with the usage of openCV by Vadim Pisarevsky at the end -of July 2013 and finally it was slightly adapted by later authors. - -Although the thorough discussion and justification of the algorithm involved may be found in -@cite ChambolleEtAl, it might make sense to skim over it here, following @cite MA13 . To begin -with, we consider the 1-byte gray-level images as the functions from the rectangular domain of -pixels (it may be seen as set -\f$\left\{(x,y)\in\mathbb{N}\times\mathbb{N}\mid 1\leq x\leq n,\;1\leq y\leq m\right\}\f$ for some -\f$m,\;n\in\mathbb{N}\f$) into \f$\{0,1,\dots,255\}\f$. We shall denote the noised images as \f$f_i\f$ and with -this view, given some image \f$x\f$ of the same size, we may measure how bad it is by the formula - -\f[\left\|\left\|\nabla x\right\|\right\| + \lambda\sum_i\left\|\left\|x-f_i\right\|\right\|\f] - -\f$\|\|\cdot\|\|\f$ here denotes \f$L_2\f$-norm and as you see, the first addend states that we want our -image to be smooth (ideally, having zero gradient, thus being constant) and the second states that -we want our result to be close to the observations we've got. If we treat \f$x\f$ as a function, this is -exactly the functional what we seek to minimize and here the Primal-Dual algorithm comes into play. - -@param observations This array should contain one or more noised versions of the image that is to -be restored. -@param result Here the denoised image will be stored. There is no need to do pre-allocation of -storage space, as it will be automatically allocated, if necessary. -@param lambda Corresponds to \f$\lambda\f$ in the formulas above. As it is enlarged, the smooth -(blurred) images are treated more favorably than detailed (but maybe more noised) ones. Roughly -speaking, as it becomes smaller, the result will be more blur but more sever outliers will be -removed. -@param niters Number of iterations that the algorithm will run. Of course, as more iterations as -better, but it is hard to quantitatively refine this statement, so just use the default and -increase it if the results are poor. - */ -CV_EXPORTS_W void denoise_TVL1(const std::vector& observations,Mat& result, double lambda=1.0, int niters=30); - -//! @} photo_denoise - -//! @addtogroup photo_hdr -//! @{ - -enum { LDR_SIZE = 256 }; - -/** @brief Base class for tonemapping algorithms - tools that are used to map HDR image to 8-bit range. - */ -class CV_EXPORTS_W Tonemap : public Algorithm -{ -public: - /** @brief Tonemaps image - - @param src source image - CV_32FC3 Mat (float 32 bits 3 channels) - @param dst destination image - CV_32FC3 Mat with values in [0, 1] range - */ - CV_WRAP virtual void process(InputArray src, OutputArray dst) = 0; - - CV_WRAP virtual float getGamma() const = 0; - CV_WRAP virtual void setGamma(float gamma) = 0; -}; - -/** @brief Creates simple linear mapper with gamma correction - -@param gamma positive value for gamma correction. Gamma value of 1.0 implies no correction, gamma -equal to 2.2f is suitable for most displays. -Generally gamma \> 1 brightens the image and gamma \< 1 darkens it. - */ -CV_EXPORTS_W Ptr createTonemap(float gamma = 1.0f); - -/** @brief Adaptive logarithmic mapping is a fast global tonemapping algorithm that scales the image in -logarithmic domain. - -Since it's a global operator the same function is applied to all the pixels, it is controlled by the -bias parameter. - -Optional saturation enhancement is possible as described in @cite FL02 . - -For more information see @cite DM03 . - */ -class CV_EXPORTS_W TonemapDrago : public Tonemap -{ -public: - - CV_WRAP virtual float getSaturation() const = 0; - CV_WRAP virtual void setSaturation(float saturation) = 0; - - CV_WRAP virtual float getBias() const = 0; - CV_WRAP virtual void setBias(float bias) = 0; -}; - -/** @brief Creates TonemapDrago object - -@param gamma gamma value for gamma correction. See createTonemap -@param saturation positive saturation enhancement value. 1.0 preserves saturation, values greater -than 1 increase saturation and values less than 1 decrease it. -@param bias value for bias function in [0, 1] range. Values from 0.7 to 0.9 usually give best -results, default value is 0.85. - */ -CV_EXPORTS_W Ptr createTonemapDrago(float gamma = 1.0f, float saturation = 1.0f, float bias = 0.85f); - - -/** @brief This is a global tonemapping operator that models human visual system. - -Mapping function is controlled by adaptation parameter, that is computed using light adaptation and -color adaptation. - -For more information see @cite RD05 . - */ -class CV_EXPORTS_W TonemapReinhard : public Tonemap -{ -public: - CV_WRAP virtual float getIntensity() const = 0; - CV_WRAP virtual void setIntensity(float intensity) = 0; - - CV_WRAP virtual float getLightAdaptation() const = 0; - CV_WRAP virtual void setLightAdaptation(float light_adapt) = 0; - - CV_WRAP virtual float getColorAdaptation() const = 0; - CV_WRAP virtual void setColorAdaptation(float color_adapt) = 0; -}; - -/** @brief Creates TonemapReinhard object - -@param gamma gamma value for gamma correction. See createTonemap -@param intensity result intensity in [-8, 8] range. Greater intensity produces brighter results. -@param light_adapt light adaptation in [0, 1] range. If 1 adaptation is based only on pixel -value, if 0 it's global, otherwise it's a weighted mean of this two cases. -@param color_adapt chromatic adaptation in [0, 1] range. If 1 channels are treated independently, -if 0 adaptation level is the same for each channel. - */ -CV_EXPORTS_W Ptr -createTonemapReinhard(float gamma = 1.0f, float intensity = 0.0f, float light_adapt = 1.0f, float color_adapt = 0.0f); - -/** @brief This algorithm transforms image to contrast using gradients on all levels of gaussian pyramid, -transforms contrast values to HVS response and scales the response. After this the image is -reconstructed from new contrast values. - -For more information see @cite MM06 . - */ -class CV_EXPORTS_W TonemapMantiuk : public Tonemap -{ -public: - CV_WRAP virtual float getScale() const = 0; - CV_WRAP virtual void setScale(float scale) = 0; - - CV_WRAP virtual float getSaturation() const = 0; - CV_WRAP virtual void setSaturation(float saturation) = 0; -}; - -/** @brief Creates TonemapMantiuk object - -@param gamma gamma value for gamma correction. See createTonemap -@param scale contrast scale factor. HVS response is multiplied by this parameter, thus compressing -dynamic range. Values from 0.6 to 0.9 produce best results. -@param saturation saturation enhancement value. See createTonemapDrago - */ -CV_EXPORTS_W Ptr -createTonemapMantiuk(float gamma = 1.0f, float scale = 0.7f, float saturation = 1.0f); - -/** @brief The base class for algorithms that align images of the same scene with different exposures - */ -class CV_EXPORTS_W AlignExposures : public Algorithm -{ -public: - /** @brief Aligns images - - @param src vector of input images - @param dst vector of aligned images - @param times vector of exposure time values for each image - @param response 256x1 matrix with inverse camera response function for each pixel value, it should - have the same number of channels as images. - */ - CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, - InputArray times, InputArray response) = 0; -}; - -/** @brief This algorithm converts images to median threshold bitmaps (1 for pixels brighter than median -luminance and 0 otherwise) and than aligns the resulting bitmaps using bit operations. - -It is invariant to exposure, so exposure values and camera response are not necessary. - -In this implementation new image regions are filled with zeros. - -For more information see @cite GW03 . - */ -class CV_EXPORTS_W AlignMTB : public AlignExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - - /** @brief Short version of process, that doesn't take extra arguments. - - @param src vector of input images - @param dst vector of aligned images - */ - CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst) = 0; - - /** @brief Calculates shift between two images, i. e. how to shift the second image to correspond it with the - first. - - @param img0 first image - @param img1 second image - */ - CV_WRAP virtual Point calculateShift(InputArray img0, InputArray img1) = 0; - /** @brief Helper function, that shift Mat filling new regions with zeros. - - @param src input image - @param dst result image - @param shift shift value - */ - CV_WRAP virtual void shiftMat(InputArray src, OutputArray dst, const Point shift) = 0; - /** @brief Computes median threshold and exclude bitmaps of given image. - - @param img input image - @param tb median threshold bitmap - @param eb exclude bitmap - */ - CV_WRAP virtual void computeBitmaps(InputArray img, OutputArray tb, OutputArray eb) = 0; - - CV_WRAP virtual int getMaxBits() const = 0; - CV_WRAP virtual void setMaxBits(int max_bits) = 0; - - CV_WRAP virtual int getExcludeRange() const = 0; - CV_WRAP virtual void setExcludeRange(int exclude_range) = 0; - - CV_WRAP virtual bool getCut() const = 0; - CV_WRAP virtual void setCut(bool value) = 0; -}; - -/** @brief Creates AlignMTB object - -@param max_bits logarithm to the base 2 of maximal shift in each dimension. Values of 5 and 6 are -usually good enough (31 and 63 pixels shift respectively). -@param exclude_range range for exclusion bitmap that is constructed to suppress noise around the -median value. -@param cut if true cuts images, otherwise fills the new regions with zeros. - */ -CV_EXPORTS_W Ptr createAlignMTB(int max_bits = 6, int exclude_range = 4, bool cut = true); - -/** @brief The base class for camera response calibration algorithms. - */ -class CV_EXPORTS_W CalibrateCRF : public Algorithm -{ -public: - /** @brief Recovers inverse camera response. - - @param src vector of input images - @param dst 256x1 matrix with inverse camera response function - @param times vector of exposure time values for each image - */ - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; -}; - -/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective -function as linear system. Objective function is constructed using pixel values on the same position -in all images, extra term is added to make the result smoother. - -For more information see @cite DM97 . - */ -class CV_EXPORTS_W CalibrateDebevec : public CalibrateCRF -{ -public: - CV_WRAP virtual float getLambda() const = 0; - CV_WRAP virtual void setLambda(float lambda) = 0; - - CV_WRAP virtual int getSamples() const = 0; - CV_WRAP virtual void setSamples(int samples) = 0; - - CV_WRAP virtual bool getRandom() const = 0; - CV_WRAP virtual void setRandom(bool random) = 0; -}; - -/** @brief Creates CalibrateDebevec object - -@param samples number of pixel locations to use -@param lambda smoothness term weight. Greater values produce smoother results, but can alter the -response. -@param random if true sample pixel locations are chosen at random, otherwise they form a -rectangular grid. - */ -CV_EXPORTS_W Ptr createCalibrateDebevec(int samples = 70, float lambda = 10.0f, bool random = false); - -/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective -function as linear system. This algorithm uses all image pixels. - -For more information see @cite RB99 . - */ -class CV_EXPORTS_W CalibrateRobertson : public CalibrateCRF -{ -public: - CV_WRAP virtual int getMaxIter() const = 0; - CV_WRAP virtual void setMaxIter(int max_iter) = 0; - - CV_WRAP virtual float getThreshold() const = 0; - CV_WRAP virtual void setThreshold(float threshold) = 0; - - CV_WRAP virtual Mat getRadiance() const = 0; -}; - -/** @brief Creates CalibrateRobertson object - -@param max_iter maximal number of Gauss-Seidel solver iterations. -@param threshold target difference between results of two successive steps of the minimization. - */ -CV_EXPORTS_W Ptr createCalibrateRobertson(int max_iter = 30, float threshold = 0.01f); - -/** @brief The base class algorithms that can merge exposure sequence to a single image. - */ -class CV_EXPORTS_W MergeExposures : public Algorithm -{ -public: - /** @brief Merges images. - - @param src vector of input images - @param dst result image - @param times vector of exposure time values for each image - @param response 256x1 matrix with inverse camera response function for each pixel value, it should - have the same number of channels as images. - */ - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) = 0; -}; - -/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure -values and camera response. - -For more information see @cite DM97 . - */ -class CV_EXPORTS_W MergeDebevec : public MergeExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; -}; - -/** @brief Creates MergeDebevec object - */ -CV_EXPORTS_W Ptr createMergeDebevec(); - -/** @brief Pixels are weighted using contrast, saturation and well-exposedness measures, than images are -combined using laplacian pyramids. - -The resulting image weight is constructed as weighted average of contrast, saturation and -well-exposedness measures. - -The resulting image doesn't require tonemapping and can be converted to 8-bit image by multiplying -by 255, but it's recommended to apply gamma correction and/or linear tonemapping. - -For more information see @cite MK07 . - */ -class CV_EXPORTS_W MergeMertens : public MergeExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - /** @brief Short version of process, that doesn't take extra arguments. - - @param src vector of input images - @param dst result image - */ - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst) = 0; - - CV_WRAP virtual float getContrastWeight() const = 0; - CV_WRAP virtual void setContrastWeight(float contrast_weiht) = 0; - - CV_WRAP virtual float getSaturationWeight() const = 0; - CV_WRAP virtual void setSaturationWeight(float saturation_weight) = 0; - - CV_WRAP virtual float getExposureWeight() const = 0; - CV_WRAP virtual void setExposureWeight(float exposure_weight) = 0; -}; - -/** @brief Creates MergeMertens object - -@param contrast_weight contrast measure weight. See MergeMertens. -@param saturation_weight saturation measure weight -@param exposure_weight well-exposedness measure weight - */ -CV_EXPORTS_W Ptr -createMergeMertens(float contrast_weight = 1.0f, float saturation_weight = 1.0f, float exposure_weight = 0.0f); - -/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure -values and camera response. - -For more information see @cite RB99 . - */ -class CV_EXPORTS_W MergeRobertson : public MergeExposures -{ -public: - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, - InputArray times, InputArray response) CV_OVERRIDE = 0; - CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; -}; - -/** @brief Creates MergeRobertson object - */ -CV_EXPORTS_W Ptr createMergeRobertson(); - -//! @} photo_hdr - -//! @addtogroup photo_decolor -//! @{ - -/** @brief Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized -black-and-white photograph rendering, and in many single channel image processing applications -@cite CL12 . - -@param src Input 8-bit 3-channel image. -@param grayscale Output 8-bit 1-channel image. -@param color_boost Output 8-bit 3-channel image. - -This function is to be applied on color images. - */ -CV_EXPORTS_W void decolor( InputArray src, OutputArray grayscale, OutputArray color_boost); - -//! @} photo_decolor - -//! @addtogroup photo_clone -//! @{ - - -//! Flags for the seamlessClone algorithm -enum SeamlessCloneFlags -{ - /** - @brief Normal seamless cloning. - This method is ideal for inserting objects with complex outlines into a new background. - It preserves the original appearance and lighting of the inserted object, ensuring a natural blend. - */ - NORMAL_CLONE = 1, - - /** - @brief Mixed seamless cloning. - This method addresses cases where simple color-based selection or alpha masking is time-consuming - and may result in undesirable halos. By combining structure from the source and texture from the - destination, mixed seamless cloning is highly effective, even with loosely defined selections. - */ - MIXED_CLONE = 2, - - /** - @brief Monochrome transfer cloning. - This method allows users to replace specific features of an object, such as grayscale textures - or patterns, with alternative features. It is particularly useful for artistic effects or - targeted object modifications. - */ - MONOCHROME_TRANSFER = 3, - - /** - @brief Enhanced normal seamless cloning. - Similar to `NORMAL_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. - This mode processes a larger source region by considering the entire mask area instead of only - the bounding rectangle of non-zero pixels. - */ - NORMAL_CLONE_WIDE = 9, - - /** - @brief Enhanced mixed seamless cloning. - Similar to `MIXED_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. - This mode processes a larger source region by considering the entire mask area instead of only - the bounding rectangle of non-zero pixels. - */ - MIXED_CLONE_WIDE = 10, - - /** - @brief Enhanced monochrome transfer cloning. - Similar to `MONOCHROME_TRANSFER`, but with an advanced approach to ROI (Region of Interest) calculation. - This mode processes a larger source region by considering the entire mask area instead of only - the bounding rectangle of non-zero pixels. - */ - MONOCHROME_TRANSFER_WIDE = 11 -}; - - -/** @example samples/cpp/tutorial_code/photo/seamless_cloning/cloning_demo.cpp -An example using seamlessClone function -*/ -/** @brief Performs seamless cloning to blend a region from a source image into a destination image. -This function is designed for local image editing, allowing changes restricted to a region -(manually selected as the ROI) to be applied effortlessly and seamlessly. These changes can -range from slight distortions to complete replacement by novel content @cite PM03. - -@param src The source image (8-bit 3-channel), from which a region will be blended into the destination. -@param dst The destination image (8-bit 3-channel), where the src image will be blended. -@param mask A binary mask (8-bit, 1, 3, or 4-channel) specifying the region in the source image to blend. -Non-zero pixels indicate the region to be blended. If an empty Mat is provided, a mask with -all non-zero pixels is created internally. -@param p The point where the center of the src image is placed in the dst image. -@param blend The output image that stores the result of the seamless cloning. It has the same size and type as `dst`. -@param flags Flags that control the type of cloning method, can take values of `cv::SeamlessCloneFlags`. - */ -CV_EXPORTS_W void seamlessClone( InputArray src, InputArray dst, InputArray mask, Point p, - OutputArray blend, int flags); - -/** @brief Given an original color image, two differently colored versions of this image can be mixed -seamlessly. - -@param src Input 8-bit 3-channel image. -@param mask Input 8-bit 1 or 3-channel image. -@param dst Output image with the same size and type as src . -@param red_mul R-channel multiply factor. -@param green_mul G-channel multiply factor. -@param blue_mul B-channel multiply factor. - -Multiplication factor is between .5 to 2.5. - */ -CV_EXPORTS_W void colorChange(InputArray src, InputArray mask, OutputArray dst, float red_mul = 1.0f, - float green_mul = 1.0f, float blue_mul = 1.0f); - -/** @brief Applying an appropriate non-linear transformation to the gradient field inside the selection and -then integrating back with a Poisson solver, modifies locally the apparent illumination of an image. - -@param src Input 8-bit 3-channel image. -@param mask Input 8-bit 1 or 3-channel image. -@param dst Output image with the same size and type as src. -@param alpha Value ranges between 0-2. -@param beta Value ranges between 0-2. - -This is useful to highlight under-exposed foreground objects or to reduce specular reflections. - */ -CV_EXPORTS_W void illuminationChange(InputArray src, InputArray mask, OutputArray dst, - float alpha = 0.2f, float beta = 0.4f); - -/** @brief By retaining only the gradients at edge locations, before integrating with the Poisson solver, one -washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge %Detector is used. - -@param src Input 8-bit 3-channel image. -@param mask Input 8-bit 1 or 3-channel image. -@param dst Output image with the same size and type as src. -@param low_threshold %Range from 0 to 100. -@param high_threshold Value \> 100. -@param kernel_size The size of the Sobel kernel to be used. - -@note -The algorithm assumes that the color of the source image is close to that of the destination. This -assumption means that when the colors don't match, the source image color gets tinted toward the -color of the destination image. - */ -CV_EXPORTS_W void textureFlattening(InputArray src, InputArray mask, OutputArray dst, - float low_threshold = 30, float high_threshold = 45, - int kernel_size = 3); - -//! @} photo_clone - -//! @addtogroup photo_render -//! @{ - -//! Edge preserving filters -enum -{ - RECURS_FILTER = 1, //!< Recursive Filtering - NORMCONV_FILTER = 2 //!< Normalized Convolution Filtering -}; - -/** @brief Filtering is the fundamental operation in image and video processing. Edge-preserving smoothing -filters are used in many different applications @cite EM11 . - -@param src Input 8-bit 3-channel image. -@param dst Output 8-bit 3-channel image. -@param flags Edge preserving filters: cv::RECURS_FILTER or cv::NORMCONV_FILTER -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. - */ -CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flags = 1, - float sigma_s = 60, float sigma_r = 0.4f); - -/** @brief This filter enhances the details of a particular image. - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src. -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. - */ -CV_EXPORTS_W void detailEnhance(InputArray src, OutputArray dst, float sigma_s = 10, - float sigma_r = 0.15f); - -/** @example samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp -An example using non-photorealistic line drawing functions -*/ -/** @brief Pencil-like non-photorealistic line drawing - -@param src Input 8-bit 3-channel image. -@param dst1 Output 8-bit 1-channel image. -@param dst2 Output image with the same size and type as src. -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. -@param shade_factor %Range between 0 to 0.1. - */ -CV_EXPORTS_W void pencilSketch(InputArray src, OutputArray dst1, OutputArray dst2, - float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f); - -/** @brief Stylization aims to produce digital imagery with a wide variety of effects not focused on -photorealism. Edge-aware filters are ideal for stylization, as they can abstract regions of low -contrast while preserving, or enhancing, high-contrast features. - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src. -@param sigma_s %Range between 0 to 200. -@param sigma_r %Range between 0 to 1. - */ -CV_EXPORTS_W void stylization(InputArray src, OutputArray dst, float sigma_s = 60, - float sigma_r = 0.45f); - -//! @} photo_render - -//! @} photo - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_PHOTO_HPP +#define OPENCV_PHOTO_HPP + +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" + +/** +@defgroup photo Computational Photography + +This module includes photo processing algorithms +@{ + @defgroup photo_inpaint Inpainting + @defgroup photo_denoise Denoising + @defgroup photo_hdr HDR imaging + + This section describes high dynamic range imaging algorithms namely tonemapping, exposure alignment, + camera calibration with multiple exposures and exposure fusion. + + @defgroup photo_decolor Contrast Preserving Decolorization + + Useful links: + + http://www.cse.cuhk.edu.hk/leojia/projects/color2gray/index.html + + @defgroup photo_clone Seamless Cloning + + Useful links: + + https://www.learnopencv.com/seamless-cloning-using-opencv-python-cpp + + @defgroup photo_render Non-Photorealistic Rendering + + Useful links: + + http://www.inf.ufrgs.br/~eslgastal/DomainTransform + + https://www.learnopencv.com/non-photorealistic-rendering-using-opencv-python-c/ + +@} + */ + +namespace cv +{ + +//! @addtogroup photo +//! @{ + +//! @addtogroup photo_inpaint +//! @{ +//! the inpainting algorithm +enum +{ + INPAINT_NS = 0, //!< Use Navier-Stokes based method + INPAINT_TELEA = 1 //!< Use the algorithm proposed by Alexandru Telea @cite Telea04 +}; + +/** @brief Restores the selected region in an image using the region neighborhood. + +@param src Input 8-bit, 16-bit unsigned or 32-bit float 1-channel or 8-bit 3-channel image. +@param inpaintMask Inpainting mask, 8-bit 1-channel image. Non-zero pixels indicate the area that +needs to be inpainted. +@param dst Output image with the same size and type as src . +@param inpaintRadius Radius of a circular neighborhood of each point inpainted that is considered +by the algorithm. +@param flags Inpainting method that could be cv::INPAINT_NS or cv::INPAINT_TELEA + +The function reconstructs the selected image area from the pixel near the area boundary. The +function may be used to remove dust and scratches from a scanned photo, or to remove undesirable +objects from still images or video. See for more details. + +@note + - An example using the inpainting technique can be found at + opencv_source_code/samples/cpp/inpaint.cpp + - (Python) An example using the inpainting technique can be found at + opencv_source_code/samples/python/inpaint.py + */ +CV_EXPORTS_W void inpaint( InputArray src, InputArray inpaintMask, + OutputArray dst, double inpaintRadius, int flags ); + +//! @} photo_inpaint + +//! @addtogroup photo_denoise +//! @{ + +/** @brief Perform image denoising using Non-local Means Denoising algorithm + with several computational +optimizations. Noise expected to be a gaussian white noise + +@param src Input 8-bit 1-channel, 2-channel, 3-channel or 4-channel image. +@param dst Output image with the same size and type as src . +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength. Big h value perfectly removes noise but also +removes image details, smaller h value preserves details but also preserves some noise + +This function expected to be applied to grayscale images. For colored images look at +fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored +image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting +image to CIELAB colorspace and then separately denoise L and AB components with different h +parameter. + */ +CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, float h = 3, + int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Perform image denoising using Non-local Means Denoising algorithm + with several computational +optimizations. Noise expected to be a gaussian white noise + +@param src Input 8-bit or 16-bit (only with NORM_L1) 1-channel, +2-channel, 3-channel or 4-channel image. +@param dst Output image with the same size and type as src . +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Array of parameters regulating filter strength, either one +parameter applied to all channels or one per channel in dst. Big h value +perfectly removes noise but also removes image details, smaller h +value preserves details but also preserves some noise +@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 + +This function expected to be applied to grayscale images. For colored images look at +fastNlMeansDenoisingColored. Advanced usage of this functions can be manual denoising of colored +image in different colorspaces. Such approach is used in fastNlMeansDenoisingColored by converting +image to CIELAB colorspace and then separately denoise L and AB components with different h +parameter. + */ +CV_EXPORTS_W void fastNlMeansDenoising( InputArray src, OutputArray dst, + const std::vector& h, + int templateWindowSize = 7, int searchWindowSize = 21, + int normType = NORM_L2); + +/** @brief Modification of fastNlMeansDenoising function for colored images + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src . +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly +removes noise but also removes image details, smaller h value preserves details but also preserves +some noise +@param hColor The same as h but for color components. For most images value equals 10 +will be enough to remove colored noise and do not distort colors + +The function converts image to CIELAB colorspace and then separately denoise L and AB components +with given h parameters using fastNlMeansDenoising function. + */ +CV_EXPORTS_W void fastNlMeansDenoisingColored( InputArray src, OutputArray dst, + float h = 3, float hColor = 3, + int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been +captured in small period of time. For example video. This version of the function is for grayscale +images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details +(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). + +@param srcImgs Input 8-bit 1-channel, 2-channel, 3-channel or +4-channel images sequence. All images should have the same type and +size. +@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence +@param temporalWindowSize Number of surrounding images to use for target image denoising. Should +be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to +imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise +srcImgs[imgToDenoiseIndex] image. +@param dst Output image with the same size and type as srcImgs images. +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength. Bigger h value +perfectly removes noise but also removes image details, smaller h +value preserves details but also preserves some noise + */ +CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, + int imgToDenoiseIndex, int temporalWindowSize, + float h = 3, int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Modification of fastNlMeansDenoising function for images sequence where consecutive images have been +captured in small period of time. For example video. This version of the function is for grayscale +images or for manual manipulation with colorspaces. See @cite Buades2005DenoisingIS for more details +(open access [here](https://static.aminer.org/pdf/PDF/000/317/196/spatio_temporal_wiener_filtering_of_image_sequences_using_a_parametric.pdf)). + +@param srcImgs Input 8-bit or 16-bit (only with NORM_L1) 1-channel, +2-channel, 3-channel or 4-channel images sequence. All images should +have the same type and size. +@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence +@param temporalWindowSize Number of surrounding images to use for target image denoising. Should +be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to +imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise +srcImgs[imgToDenoiseIndex] image. +@param dst Output image with the same size and type as srcImgs images. +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Array of parameters regulating filter strength, either one +parameter applied to all channels or one per channel in dst. Big h value +perfectly removes noise but also removes image details, smaller h +value preserves details but also preserves some noise +@param normType Type of norm used for weight calculation. Can be either NORM_L2 or NORM_L1 + */ +CV_EXPORTS_W void fastNlMeansDenoisingMulti( InputArrayOfArrays srcImgs, OutputArray dst, + int imgToDenoiseIndex, int temporalWindowSize, + const std::vector& h, + int templateWindowSize = 7, int searchWindowSize = 21, + int normType = NORM_L2); + +/** @brief Modification of fastNlMeansDenoisingMulti function for colored images sequences + +@param srcImgs Input 8-bit 3-channel images sequence. All images should have the same type and +size. +@param imgToDenoiseIndex Target image to denoise index in srcImgs sequence +@param temporalWindowSize Number of surrounding images to use for target image denoising. Should +be odd. Images from imgToDenoiseIndex - temporalWindowSize / 2 to +imgToDenoiseIndex + temporalWindowSize / 2 from srcImgs will be used to denoise +srcImgs[imgToDenoiseIndex] image. +@param dst Output image with the same size and type as srcImgs images. +@param templateWindowSize Size in pixels of the template patch that is used to compute weights. +Should be odd. Recommended value 7 pixels +@param searchWindowSize Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater searchWindowsSize - greater +denoising time. Recommended value 21 pixels +@param h Parameter regulating filter strength for luminance component. Bigger h value perfectly +removes noise but also removes image details, smaller h value preserves details but also preserves +some noise. +@param hColor The same as h but for color components. + +The function converts images to CIELAB colorspace and then separately denoise L and AB components +with given h parameters using fastNlMeansDenoisingMulti function. + */ +CV_EXPORTS_W void fastNlMeansDenoisingColoredMulti( InputArrayOfArrays srcImgs, OutputArray dst, + int imgToDenoiseIndex, int temporalWindowSize, + float h = 3, float hColor = 3, + int templateWindowSize = 7, int searchWindowSize = 21); + +/** @brief Primal-dual algorithm is an algorithm for solving special types of variational problems (that is, +finding a function to minimize some functional). As the image denoising, in particular, may be seen +as the variational problem, primal-dual algorithm then can be used to perform denoising and this is +exactly what is implemented. + +It should be noted, that this implementation was taken from the July 2013 blog entry +@cite MA13 , which also contained (slightly more general) ready-to-use source code on Python. +Subsequently, that code was rewritten on C++ with the usage of openCV by Vadim Pisarevsky at the end +of July 2013 and finally it was slightly adapted by later authors. + +Although the thorough discussion and justification of the algorithm involved may be found in +@cite ChambolleEtAl, it might make sense to skim over it here, following @cite MA13 . To begin +with, we consider the 1-byte gray-level images as the functions from the rectangular domain of +pixels (it may be seen as set +\f$\left\{(x,y)\in\mathbb{N}\times\mathbb{N}\mid 1\leq x\leq n,\;1\leq y\leq m\right\}\f$ for some +\f$m,\;n\in\mathbb{N}\f$) into \f$\{0,1,\dots,255\}\f$. We shall denote the noised images as \f$f_i\f$ and with +this view, given some image \f$x\f$ of the same size, we may measure how bad it is by the formula + +\f[\left\|\left\|\nabla x\right\|\right\| + \lambda\sum_i\left\|\left\|x-f_i\right\|\right\|\f] + +\f$\|\|\cdot\|\|\f$ here denotes \f$L_2\f$-norm and as you see, the first addend states that we want our +image to be smooth (ideally, having zero gradient, thus being constant) and the second states that +we want our result to be close to the observations we've got. If we treat \f$x\f$ as a function, this is +exactly the functional what we seek to minimize and here the Primal-Dual algorithm comes into play. + +@param observations This array should contain one or more noised versions of the image that is to +be restored. +@param result Here the denoised image will be stored. There is no need to do pre-allocation of +storage space, as it will be automatically allocated, if necessary. +@param lambda Corresponds to \f$\lambda\f$ in the formulas above. As it is enlarged, the smooth +(blurred) images are treated more favorably than detailed (but maybe more noised) ones. Roughly +speaking, as it becomes smaller, the result will be more blur but more sever outliers will be +removed. +@param niters Number of iterations that the algorithm will run. Of course, as more iterations as +better, but it is hard to quantitatively refine this statement, so just use the default and +increase it if the results are poor. + */ +CV_EXPORTS_W void denoise_TVL1(const std::vector& observations,Mat& result, double lambda=1.0, int niters=30); + +//! @} photo_denoise + +//! @addtogroup photo_hdr +//! @{ + +enum { LDR_SIZE = 256 }; + +/** @brief Base class for tonemapping algorithms - tools that are used to map HDR image to 8-bit range. + */ +class CV_EXPORTS_W Tonemap : public Algorithm +{ +public: + /** @brief Tonemaps image + + @param src source image - CV_32FC3 Mat (float 32 bits 3 channels) + @param dst destination image - CV_32FC3 Mat with values in [0, 1] range + */ + CV_WRAP virtual void process(InputArray src, OutputArray dst) = 0; + + CV_WRAP virtual float getGamma() const = 0; + CV_WRAP virtual void setGamma(float gamma) = 0; +}; + +/** @brief Creates simple linear mapper with gamma correction + +@param gamma positive value for gamma correction. Gamma value of 1.0 implies no correction, gamma +equal to 2.2f is suitable for most displays. +Generally gamma \> 1 brightens the image and gamma \< 1 darkens it. + */ +CV_EXPORTS_W Ptr createTonemap(float gamma = 1.0f); + +/** @brief Adaptive logarithmic mapping is a fast global tonemapping algorithm that scales the image in +logarithmic domain. + +Since it's a global operator the same function is applied to all the pixels, it is controlled by the +bias parameter. + +Optional saturation enhancement is possible as described in @cite FL02 . + +For more information see @cite DM03 . + */ +class CV_EXPORTS_W TonemapDrago : public Tonemap +{ +public: + + CV_WRAP virtual float getSaturation() const = 0; + CV_WRAP virtual void setSaturation(float saturation) = 0; + + CV_WRAP virtual float getBias() const = 0; + CV_WRAP virtual void setBias(float bias) = 0; +}; + +/** @brief Creates TonemapDrago object + +@param gamma gamma value for gamma correction. See createTonemap +@param saturation positive saturation enhancement value. 1.0 preserves saturation, values greater +than 1 increase saturation and values less than 1 decrease it. +@param bias value for bias function in [0, 1] range. Values from 0.7 to 0.9 usually give best +results, default value is 0.85. + */ +CV_EXPORTS_W Ptr createTonemapDrago(float gamma = 1.0f, float saturation = 1.0f, float bias = 0.85f); + + +/** @brief This is a global tonemapping operator that models human visual system. + +Mapping function is controlled by adaptation parameter, that is computed using light adaptation and +color adaptation. + +For more information see @cite RD05 . + */ +class CV_EXPORTS_W TonemapReinhard : public Tonemap +{ +public: + CV_WRAP virtual float getIntensity() const = 0; + CV_WRAP virtual void setIntensity(float intensity) = 0; + + CV_WRAP virtual float getLightAdaptation() const = 0; + CV_WRAP virtual void setLightAdaptation(float light_adapt) = 0; + + CV_WRAP virtual float getColorAdaptation() const = 0; + CV_WRAP virtual void setColorAdaptation(float color_adapt) = 0; +}; + +/** @brief Creates TonemapReinhard object + +@param gamma gamma value for gamma correction. See createTonemap +@param intensity result intensity in [-8, 8] range. Greater intensity produces brighter results. +@param light_adapt light adaptation in [0, 1] range. If 1 adaptation is based only on pixel +value, if 0 it's global, otherwise it's a weighted mean of this two cases. +@param color_adapt chromatic adaptation in [0, 1] range. If 1 channels are treated independently, +if 0 adaptation level is the same for each channel. + */ +CV_EXPORTS_W Ptr +createTonemapReinhard(float gamma = 1.0f, float intensity = 0.0f, float light_adapt = 1.0f, float color_adapt = 0.0f); + +/** @brief This algorithm transforms image to contrast using gradients on all levels of gaussian pyramid, +transforms contrast values to HVS response and scales the response. After this the image is +reconstructed from new contrast values. + +For more information see @cite MM06 . + */ +class CV_EXPORTS_W TonemapMantiuk : public Tonemap +{ +public: + CV_WRAP virtual float getScale() const = 0; + CV_WRAP virtual void setScale(float scale) = 0; + + CV_WRAP virtual float getSaturation() const = 0; + CV_WRAP virtual void setSaturation(float saturation) = 0; +}; + +/** @brief Creates TonemapMantiuk object + +@param gamma gamma value for gamma correction. See createTonemap +@param scale contrast scale factor. HVS response is multiplied by this parameter, thus compressing +dynamic range. Values from 0.6 to 0.9 produce best results. +@param saturation saturation enhancement value. See createTonemapDrago + */ +CV_EXPORTS_W Ptr +createTonemapMantiuk(float gamma = 1.0f, float scale = 0.7f, float saturation = 1.0f); + +/** @brief The base class for algorithms that align images of the same scene with different exposures + */ +class CV_EXPORTS_W AlignExposures : public Algorithm +{ +public: + /** @brief Aligns images + + @param src vector of input images + @param dst vector of aligned images + @param times vector of exposure time values for each image + @param response 256x1 matrix with inverse camera response function for each pixel value, it should + have the same number of channels as images. + */ + CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, + InputArray times, InputArray response) = 0; +}; + +/** @brief This algorithm converts images to median threshold bitmaps (1 for pixels brighter than median +luminance and 0 otherwise) and than aligns the resulting bitmaps using bit operations. + +It is invariant to exposure, so exposure values and camera response are not necessary. + +In this implementation new image regions are filled with zeros. + +For more information see @cite GW03 . + */ +class CV_EXPORTS_W AlignMTB : public AlignExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + + /** @brief Short version of process, that doesn't take extra arguments. + + @param src vector of input images + @param dst vector of aligned images + */ + CV_WRAP virtual void process(InputArrayOfArrays src, std::vector& dst) = 0; + + /** @brief Calculates shift between two images, i. e. how to shift the second image to correspond it with the + first. + + @param img0 first image + @param img1 second image + */ + CV_WRAP virtual Point calculateShift(InputArray img0, InputArray img1) = 0; + /** @brief Helper function, that shift Mat filling new regions with zeros. + + @param src input image + @param dst result image + @param shift shift value + */ + CV_WRAP virtual void shiftMat(InputArray src, OutputArray dst, const Point shift) = 0; + /** @brief Computes median threshold and exclude bitmaps of given image. + + @param img input image + @param tb median threshold bitmap + @param eb exclude bitmap + */ + CV_WRAP virtual void computeBitmaps(InputArray img, OutputArray tb, OutputArray eb) = 0; + + CV_WRAP virtual int getMaxBits() const = 0; + CV_WRAP virtual void setMaxBits(int max_bits) = 0; + + CV_WRAP virtual int getExcludeRange() const = 0; + CV_WRAP virtual void setExcludeRange(int exclude_range) = 0; + + CV_WRAP virtual bool getCut() const = 0; + CV_WRAP virtual void setCut(bool value) = 0; +}; + +/** @brief Creates AlignMTB object + +@param max_bits logarithm to the base 2 of maximal shift in each dimension. Values of 5 and 6 are +usually good enough (31 and 63 pixels shift respectively). +@param exclude_range range for exclusion bitmap that is constructed to suppress noise around the +median value. +@param cut if true cuts images, otherwise fills the new regions with zeros. + */ +CV_EXPORTS_W Ptr createAlignMTB(int max_bits = 6, int exclude_range = 4, bool cut = true); + +/** @brief The base class for camera response calibration algorithms. + */ +class CV_EXPORTS_W CalibrateCRF : public Algorithm +{ +public: + /** @brief Recovers inverse camera response. + + @param src vector of input images + @param dst 256x1 matrix with inverse camera response function + @param times vector of exposure time values for each image + */ + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; +}; + +/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective +function as linear system. Objective function is constructed using pixel values on the same position +in all images, extra term is added to make the result smoother. + +For more information see @cite DM97 . + */ +class CV_EXPORTS_W CalibrateDebevec : public CalibrateCRF +{ +public: + CV_WRAP virtual float getLambda() const = 0; + CV_WRAP virtual void setLambda(float lambda) = 0; + + CV_WRAP virtual int getSamples() const = 0; + CV_WRAP virtual void setSamples(int samples) = 0; + + CV_WRAP virtual bool getRandom() const = 0; + CV_WRAP virtual void setRandom(bool random) = 0; +}; + +/** @brief Creates CalibrateDebevec object + +@param samples number of pixel locations to use +@param lambda smoothness term weight. Greater values produce smoother results, but can alter the +response. +@param random if true sample pixel locations are chosen at random, otherwise they form a +rectangular grid. + */ +CV_EXPORTS_W Ptr createCalibrateDebevec(int samples = 70, float lambda = 10.0f, bool random = false); + +/** @brief Inverse camera response function is extracted for each brightness value by minimizing an objective +function as linear system. This algorithm uses all image pixels. + +For more information see @cite RB99 . + */ +class CV_EXPORTS_W CalibrateRobertson : public CalibrateCRF +{ +public: + CV_WRAP virtual int getMaxIter() const = 0; + CV_WRAP virtual void setMaxIter(int max_iter) = 0; + + CV_WRAP virtual float getThreshold() const = 0; + CV_WRAP virtual void setThreshold(float threshold) = 0; + + CV_WRAP virtual Mat getRadiance() const = 0; +}; + +/** @brief Creates CalibrateRobertson object + +@param max_iter maximal number of Gauss-Seidel solver iterations. +@param threshold target difference between results of two successive steps of the minimization. + */ +CV_EXPORTS_W Ptr createCalibrateRobertson(int max_iter = 30, float threshold = 0.01f); + +/** @brief The base class algorithms that can merge exposure sequence to a single image. + */ +class CV_EXPORTS_W MergeExposures : public Algorithm +{ +public: + /** @brief Merges images. + + @param src vector of input images + @param dst result image + @param times vector of exposure time values for each image + @param response 256x1 matrix with inverse camera response function for each pixel value, it should + have the same number of channels as images. + */ + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) = 0; +}; + +/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure +values and camera response. + +For more information see @cite DM97 . + */ +class CV_EXPORTS_W MergeDebevec : public MergeExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; +}; + +/** @brief Creates MergeDebevec object + */ +CV_EXPORTS_W Ptr createMergeDebevec(); + +/** @brief Pixels are weighted using contrast, saturation and well-exposedness measures, than images are +combined using laplacian pyramids. + +The resulting image weight is constructed as weighted average of contrast, saturation and +well-exposedness measures. + +The resulting image doesn't require tonemapping and can be converted to 8-bit image by multiplying +by 255, but it's recommended to apply gamma correction and/or linear tonemapping. + +For more information see @cite MK07 . + */ +class CV_EXPORTS_W MergeMertens : public MergeExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + /** @brief Short version of process, that doesn't take extra arguments. + + @param src vector of input images + @param dst result image + */ + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst) = 0; + + CV_WRAP virtual float getContrastWeight() const = 0; + CV_WRAP virtual void setContrastWeight(float contrast_weiht) = 0; + + CV_WRAP virtual float getSaturationWeight() const = 0; + CV_WRAP virtual void setSaturationWeight(float saturation_weight) = 0; + + CV_WRAP virtual float getExposureWeight() const = 0; + CV_WRAP virtual void setExposureWeight(float exposure_weight) = 0; +}; + +/** @brief Creates MergeMertens object + +@param contrast_weight contrast measure weight. See MergeMertens. +@param saturation_weight saturation measure weight +@param exposure_weight well-exposedness measure weight + */ +CV_EXPORTS_W Ptr +createMergeMertens(float contrast_weight = 1.0f, float saturation_weight = 1.0f, float exposure_weight = 0.0f); + +/** @brief The resulting HDR image is calculated as weighted average of the exposures considering exposure +values and camera response. + +For more information see @cite RB99 . + */ +class CV_EXPORTS_W MergeRobertson : public MergeExposures +{ +public: + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, + InputArray times, InputArray response) CV_OVERRIDE = 0; + CV_WRAP virtual void process(InputArrayOfArrays src, OutputArray dst, InputArray times) = 0; +}; + +/** @brief Creates MergeRobertson object + */ +CV_EXPORTS_W Ptr createMergeRobertson(); + +//! @} photo_hdr + +//! @addtogroup photo_decolor +//! @{ + +/** @brief Transforms a color image to a grayscale image. It is a basic tool in digital printing, stylized +black-and-white photograph rendering, and in many single channel image processing applications +@cite CL12 . + +@param src Input 8-bit 3-channel image. +@param grayscale Output 8-bit 1-channel image. +@param color_boost Output 8-bit 3-channel image. + +This function is to be applied on color images. + */ +CV_EXPORTS_W void decolor( InputArray src, OutputArray grayscale, OutputArray color_boost); + +//! @} photo_decolor + +//! @addtogroup photo_clone +//! @{ + + +//! Flags for the seamlessClone algorithm +enum SeamlessCloneFlags +{ + /** + @brief Normal seamless cloning. + This method is ideal for inserting objects with complex outlines into a new background. + It preserves the original appearance and lighting of the inserted object, ensuring a natural blend. + */ + NORMAL_CLONE = 1, + + /** + @brief Mixed seamless cloning. + This method addresses cases where simple color-based selection or alpha masking is time-consuming + and may result in undesirable halos. By combining structure from the source and texture from the + destination, mixed seamless cloning is highly effective, even with loosely defined selections. + */ + MIXED_CLONE = 2, + + /** + @brief Monochrome transfer cloning. + This method allows users to replace specific features of an object, such as grayscale textures + or patterns, with alternative features. It is particularly useful for artistic effects or + targeted object modifications. + */ + MONOCHROME_TRANSFER = 3, + + /** + @brief Enhanced normal seamless cloning. + Similar to `NORMAL_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. + This mode processes a larger source region by considering the entire mask area instead of only + the bounding rectangle of non-zero pixels. + */ + NORMAL_CLONE_WIDE = 9, + + /** + @brief Enhanced mixed seamless cloning. + Similar to `MIXED_CLONE`, but with an advanced approach to ROI (Region of Interest) calculation. + This mode processes a larger source region by considering the entire mask area instead of only + the bounding rectangle of non-zero pixels. + */ + MIXED_CLONE_WIDE = 10, + + /** + @brief Enhanced monochrome transfer cloning. + Similar to `MONOCHROME_TRANSFER`, but with an advanced approach to ROI (Region of Interest) calculation. + This mode processes a larger source region by considering the entire mask area instead of only + the bounding rectangle of non-zero pixels. + */ + MONOCHROME_TRANSFER_WIDE = 11 +}; + + +/** @example samples/cpp/tutorial_code/photo/seamless_cloning/cloning_demo.cpp +An example using seamlessClone function +*/ +/** @brief Performs seamless cloning to blend a region from a source image into a destination image. +This function is designed for local image editing, allowing changes restricted to a region +(manually selected as the ROI) to be applied effortlessly and seamlessly. These changes can +range from slight distortions to complete replacement by novel content @cite PM03. + +@param src The source image (8-bit 3-channel), from which a region will be blended into the destination. +@param dst The destination image (8-bit 3-channel), where the src image will be blended. +@param mask A binary mask (8-bit, 1, 3, or 4-channel) specifying the region in the source image to blend. +Non-zero pixels indicate the region to be blended. If an empty Mat is provided, a mask with +all non-zero pixels is created internally. +@param p The point where the center of the src image is placed in the dst image. +@param blend The output image that stores the result of the seamless cloning. It has the same size and type as `dst`. +@param flags Flags that control the type of cloning method, can take values of `cv::SeamlessCloneFlags`. + */ +CV_EXPORTS_W void seamlessClone( InputArray src, InputArray dst, InputArray mask, Point p, + OutputArray blend, int flags); + +/** @brief Given an original color image, two differently colored versions of this image can be mixed +seamlessly. + +@param src Input 8-bit 3-channel image. +@param mask Input 8-bit 1 or 3-channel image. +@param dst Output image with the same size and type as src . +@param red_mul R-channel multiply factor. +@param green_mul G-channel multiply factor. +@param blue_mul B-channel multiply factor. + +Multiplication factor is between .5 to 2.5. + */ +CV_EXPORTS_W void colorChange(InputArray src, InputArray mask, OutputArray dst, float red_mul = 1.0f, + float green_mul = 1.0f, float blue_mul = 1.0f); + +/** @brief Applying an appropriate non-linear transformation to the gradient field inside the selection and +then integrating back with a Poisson solver, modifies locally the apparent illumination of an image. + +@param src Input 8-bit 3-channel image. +@param mask Input 8-bit 1 or 3-channel image. +@param dst Output image with the same size and type as src. +@param alpha Value ranges between 0-2. +@param beta Value ranges between 0-2. + +This is useful to highlight under-exposed foreground objects or to reduce specular reflections. + */ +CV_EXPORTS_W void illuminationChange(InputArray src, InputArray mask, OutputArray dst, + float alpha = 0.2f, float beta = 0.4f); + +/** @brief By retaining only the gradients at edge locations, before integrating with the Poisson solver, one +washes out the texture of the selected region, giving its contents a flat aspect. Here Canny Edge %Detector is used. + +@param src Input 8-bit 3-channel image. +@param mask Input 8-bit 1 or 3-channel image. +@param dst Output image with the same size and type as src. +@param low_threshold %Range from 0 to 100. +@param high_threshold Value \> 100. +@param kernel_size The size of the Sobel kernel to be used. + +@note +The algorithm assumes that the color of the source image is close to that of the destination. This +assumption means that when the colors don't match, the source image color gets tinted toward the +color of the destination image. + */ +CV_EXPORTS_W void textureFlattening(InputArray src, InputArray mask, OutputArray dst, + float low_threshold = 30, float high_threshold = 45, + int kernel_size = 3); + +//! @} photo_clone + +//! @addtogroup photo_render +//! @{ + +//! Edge preserving filters +enum +{ + RECURS_FILTER = 1, //!< Recursive Filtering + NORMCONV_FILTER = 2 //!< Normalized Convolution Filtering +}; + +/** @brief Filtering is the fundamental operation in image and video processing. Edge-preserving smoothing +filters are used in many different applications @cite EM11 . + +@param src Input 8-bit 3-channel image. +@param dst Output 8-bit 3-channel image. +@param flags Edge preserving filters: cv::RECURS_FILTER or cv::NORMCONV_FILTER +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. + */ +CV_EXPORTS_W void edgePreservingFilter(InputArray src, OutputArray dst, int flags = 1, + float sigma_s = 60, float sigma_r = 0.4f); + +/** @brief This filter enhances the details of a particular image. + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src. +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. + */ +CV_EXPORTS_W void detailEnhance(InputArray src, OutputArray dst, float sigma_s = 10, + float sigma_r = 0.15f); + +/** @example samples/cpp/tutorial_code/photo/non_photorealistic_rendering/npr_demo.cpp +An example using non-photorealistic line drawing functions +*/ +/** @brief Pencil-like non-photorealistic line drawing + +@param src Input 8-bit 3-channel image. +@param dst1 Output 8-bit 1-channel image. +@param dst2 Output image with the same size and type as src. +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. +@param shade_factor %Range between 0 to 0.1. + */ +CV_EXPORTS_W void pencilSketch(InputArray src, OutputArray dst1, OutputArray dst2, + float sigma_s = 60, float sigma_r = 0.07f, float shade_factor = 0.02f); + +/** @brief Stylization aims to produce digital imagery with a wide variety of effects not focused on +photorealism. Edge-aware filters are ideal for stylization, as they can abstract regions of low +contrast while preserving, or enhancing, high-contrast features. + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src. +@param sigma_s %Range between 0 to 200. +@param sigma_r %Range between 0 to 1. + */ +CV_EXPORTS_W void stylization(InputArray src, OutputArray dst, float sigma_s = 60, + float sigma_r = 0.45f); + +//! @} photo_render + +//! @} photo + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp b/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp index cb1dd9caff..709ad2d26f 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/photo/cuda.hpp @@ -1,157 +1,157 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_PHOTO_CUDA_HPP -#define OPENCV_PHOTO_CUDA_HPP - -#include "opencv2/core/cuda.hpp" - -namespace cv { namespace cuda { - -//! @addtogroup photo_denoise -//! @{ - -/** @brief Performs pure non local means denoising without any simplification, and thus it is not fast. - -@param src Source image. Supports only CV_8UC1, CV_8UC2 and CV_8UC3. -@param dst Destination image. -@param h Filter sigma regulating filter strength for color. -@param search_window Size of search window. -@param block_size Size of block used for computing weights. -@param borderMode Border type. See borderInterpolate for details. BORDER_REFLECT101 , -BORDER_REPLICATE , BORDER_CONSTANT , BORDER_REFLECT and BORDER_WRAP are supported for now. -@param stream Stream for the asynchronous version. - -@sa - fastNlMeansDenoising - */ -CV_EXPORTS void nonLocalMeans(InputArray src, OutputArray dst, - float h, - int search_window = 21, - int block_size = 7, - int borderMode = BORDER_DEFAULT, - Stream& stream = Stream::Null()); -CV_WRAP inline void nonLocalMeans(const GpuMat& src, CV_OUT GpuMat& dst, - float h, - int search_window = 21, - int block_size = 7, - int borderMode = BORDER_DEFAULT, - Stream& stream = Stream::Null()) -{ - nonLocalMeans(InputArray(src), OutputArray(dst), h, search_window, block_size, borderMode, stream); -} - -/** @brief Perform image denoising using Non-local Means Denoising algorithm - with several computational -optimizations. Noise expected to be a gaussian white noise - -@param src Input 8-bit 1-channel, 2-channel or 3-channel image. -@param dst Output image with the same size and type as src . -@param h Parameter regulating filter strength. Big h value perfectly removes noise but also -removes image details, smaller h value preserves details but also preserves some noise -@param search_window Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater search_window - greater -denoising time. Recommended value 21 pixels -@param block_size Size in pixels of the template patch that is used to compute weights. Should be -odd. Recommended value 7 pixels -@param stream Stream for the asynchronous invocations. - -This function expected to be applied to grayscale images. For colored images look at -FastNonLocalMeansDenoising::labMethod. - -@sa - fastNlMeansDenoising - */ -CV_EXPORTS void fastNlMeansDenoising(InputArray src, OutputArray dst, - float h, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()); -CV_WRAP inline void fastNlMeansDenoising(const GpuMat& src, CV_OUT GpuMat& dst, - float h, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()) -{ - fastNlMeansDenoising(InputArray(src), OutputArray(dst), h, search_window, block_size, stream); -} - -/** @brief Modification of fastNlMeansDenoising function for colored images - -@param src Input 8-bit 3-channel image. -@param dst Output image with the same size and type as src . -@param h_luminance Parameter regulating filter strength. Big h value perfectly removes noise but -also removes image details, smaller h value preserves details but also preserves some noise -@param photo_render float The same as h but for color components. For most images value equals 10 will be -enough to remove colored noise and do not distort colors -@param search_window Size in pixels of the window that is used to compute weighted average for -given pixel. Should be odd. Affect performance linearly: greater search_window - greater -denoising time. Recommended value 21 pixels -@param block_size Size in pixels of the template patch that is used to compute weights. Should be -odd. Recommended value 7 pixels -@param stream Stream for the asynchronous invocations. - -The function converts image to CIELAB colorspace and then separately denoise L and AB components -with given h parameters using FastNonLocalMeansDenoising::simpleMethod function. - -@sa - fastNlMeansDenoisingColored - */ -CV_EXPORTS void fastNlMeansDenoisingColored(InputArray src, OutputArray dst, - float h_luminance, float photo_render, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()); -CV_WRAP inline void fastNlMeansDenoisingColored(const GpuMat& src, CV_OUT GpuMat& dst, - float h_luminance, float photo_render, - int search_window = 21, - int block_size = 7, - Stream& stream = Stream::Null()) -{ - fastNlMeansDenoisingColored(InputArray(src), OutputArray(dst), h_luminance, photo_render, search_window, block_size, stream); -} - -//! @} photo - -}} // namespace cv { namespace cuda { - -#endif /* OPENCV_PHOTO_CUDA_HPP */ +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2008-2012, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_PHOTO_CUDA_HPP +#define OPENCV_PHOTO_CUDA_HPP + +#include "opencv2/core/cuda.hpp" + +namespace cv { namespace cuda { + +//! @addtogroup photo_denoise +//! @{ + +/** @brief Performs pure non local means denoising without any simplification, and thus it is not fast. + +@param src Source image. Supports only CV_8UC1, CV_8UC2 and CV_8UC3. +@param dst Destination image. +@param h Filter sigma regulating filter strength for color. +@param search_window Size of search window. +@param block_size Size of block used for computing weights. +@param borderMode Border type. See borderInterpolate for details. BORDER_REFLECT101 , +BORDER_REPLICATE , BORDER_CONSTANT , BORDER_REFLECT and BORDER_WRAP are supported for now. +@param stream Stream for the asynchronous version. + +@sa + fastNlMeansDenoising + */ +CV_EXPORTS void nonLocalMeans(InputArray src, OutputArray dst, + float h, + int search_window = 21, + int block_size = 7, + int borderMode = BORDER_DEFAULT, + Stream& stream = Stream::Null()); +CV_WRAP inline void nonLocalMeans(const GpuMat& src, CV_OUT GpuMat& dst, + float h, + int search_window = 21, + int block_size = 7, + int borderMode = BORDER_DEFAULT, + Stream& stream = Stream::Null()) +{ + nonLocalMeans(InputArray(src), OutputArray(dst), h, search_window, block_size, borderMode, stream); +} + +/** @brief Perform image denoising using Non-local Means Denoising algorithm + with several computational +optimizations. Noise expected to be a gaussian white noise + +@param src Input 8-bit 1-channel, 2-channel or 3-channel image. +@param dst Output image with the same size and type as src . +@param h Parameter regulating filter strength. Big h value perfectly removes noise but also +removes image details, smaller h value preserves details but also preserves some noise +@param search_window Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater search_window - greater +denoising time. Recommended value 21 pixels +@param block_size Size in pixels of the template patch that is used to compute weights. Should be +odd. Recommended value 7 pixels +@param stream Stream for the asynchronous invocations. + +This function expected to be applied to grayscale images. For colored images look at +FastNonLocalMeansDenoising::labMethod. + +@sa + fastNlMeansDenoising + */ +CV_EXPORTS void fastNlMeansDenoising(InputArray src, OutputArray dst, + float h, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()); +CV_WRAP inline void fastNlMeansDenoising(const GpuMat& src, CV_OUT GpuMat& dst, + float h, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()) +{ + fastNlMeansDenoising(InputArray(src), OutputArray(dst), h, search_window, block_size, stream); +} + +/** @brief Modification of fastNlMeansDenoising function for colored images + +@param src Input 8-bit 3-channel image. +@param dst Output image with the same size and type as src . +@param h_luminance Parameter regulating filter strength. Big h value perfectly removes noise but +also removes image details, smaller h value preserves details but also preserves some noise +@param photo_render float The same as h but for color components. For most images value equals 10 will be +enough to remove colored noise and do not distort colors +@param search_window Size in pixels of the window that is used to compute weighted average for +given pixel. Should be odd. Affect performance linearly: greater search_window - greater +denoising time. Recommended value 21 pixels +@param block_size Size in pixels of the template patch that is used to compute weights. Should be +odd. Recommended value 7 pixels +@param stream Stream for the asynchronous invocations. + +The function converts image to CIELAB colorspace and then separately denoise L and AB components +with given h parameters using FastNonLocalMeansDenoising::simpleMethod function. + +@sa + fastNlMeansDenoisingColored + */ +CV_EXPORTS void fastNlMeansDenoisingColored(InputArray src, OutputArray dst, + float h_luminance, float photo_render, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()); +CV_WRAP inline void fastNlMeansDenoisingColored(const GpuMat& src, CV_OUT GpuMat& dst, + float h_luminance, float photo_render, + int search_window = 21, + int block_size = 7, + Stream& stream = Stream::Null()) +{ + fastNlMeansDenoisingColored(InputArray(src), OutputArray(dst), h_luminance, photo_render, search_window, block_size, stream); +} + +//! @} photo + +}} // namespace cv { namespace cuda { + +#endif /* OPENCV_PHOTO_CUDA_HPP */ diff --git a/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h index 84515ca3b4..ec1d4403fd 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/photo/legacy/constants_c.h @@ -1,14 +1,14 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_PHOTO_LEGACY_CONSTANTS_H -#define OPENCV_PHOTO_LEGACY_CONSTANTS_H - -enum InpaintingModes -{ - CV_INPAINT_NS =0, - CV_INPAINT_TELEA =1 -}; - -#endif // OPENCV_PHOTO_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_PHOTO_LEGACY_CONSTANTS_H +#define OPENCV_PHOTO_LEGACY_CONSTANTS_H + +enum InpaintingModes +{ + CV_INPAINT_NS =0, + CV_INPAINT_TELEA =1 +}; + +#endif // OPENCV_PHOTO_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp b/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp index 96d4b3bfa9..8af5e9f0fa 100644 --- a/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/photo/photo.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/photo.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/photo.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching.hpp index b38210d9d4..41f0550618 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching.hpp @@ -1,370 +1,370 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_STITCHER_HPP -#define OPENCV_STITCHING_STITCHER_HPP - -#include "opencv2/core.hpp" -#include "opencv2/features2d.hpp" -#include "opencv2/stitching/warpers.hpp" -#include "opencv2/stitching/detail/matchers.hpp" -#include "opencv2/stitching/detail/motion_estimators.hpp" -#include "opencv2/stitching/detail/exposure_compensate.hpp" -#include "opencv2/stitching/detail/seam_finders.hpp" -#include "opencv2/stitching/detail/blenders.hpp" -#include "opencv2/stitching/detail/camera.hpp" - - -#if defined(Status) -# warning Detected X11 'Status' macro definition, it can cause build conflicts. Please, include this header before any X11 headers. -#endif - - -/** -@defgroup stitching Images stitching - -This figure illustrates the stitching module pipeline implemented in the Stitcher class. Using that -class it's possible to configure/remove some steps, i.e. adjust the stitching pipeline according to -the particular needs. All building blocks from the pipeline are available in the detail namespace, -one can combine and use them separately. - -The implemented stitching pipeline is very similar to the one proposed in @cite BL07 . - -![stitching pipeline](StitchingPipeline.jpg) - -Camera models -------------- - -There are currently 2 camera models implemented in stitching pipeline. - -- _Homography model_ expecting perspective transformations between images - implemented in @ref cv::detail::BestOf2NearestMatcher cv::detail::HomographyBasedEstimator - cv::detail::BundleAdjusterReproj cv::detail::BundleAdjusterRay -- _Affine model_ expecting affine transformation with 6 DOF or 4 DOF implemented in - @ref cv::detail::AffineBestOf2NearestMatcher cv::detail::AffineBasedEstimator - cv::detail::BundleAdjusterAffine cv::detail::BundleAdjusterAffinePartial cv::AffineWarper - -Homography model is useful for creating photo panoramas captured by camera, -while affine-based model can be used to stitch scans and object captured by -specialized devices. Use @ref cv::Stitcher::create to get preconfigured pipeline for one -of those models. - -@note -Certain detailed settings of @ref cv::Stitcher might not make sense. Especially -you should not mix classes implementing affine model and classes implementing -Homography model, as they work with different transformations. - -@{ - @defgroup stitching_match Features Finding and Images Matching - @defgroup stitching_rotation Rotation Estimation - @defgroup stitching_autocalib Autocalibration - @defgroup stitching_warp Images Warping - @defgroup stitching_seam Seam Estimation - @defgroup stitching_exposure Exposure Compensation - @defgroup stitching_blend Image Blenders -@} - */ - -namespace cv { - -//! @addtogroup stitching -//! @{ - -/** @example samples/cpp/stitching.cpp -A basic example on image stitching -*/ - -/** @example samples/python/stitching.py -A basic example on image stitching in Python. -*/ - -/** @example samples/cpp/stitching_detailed.cpp -A detailed example on image stitching -*/ - -/** @brief High level image stitcher. - -It's possible to use this class without being aware of the entire stitching pipeline. However, to -be able to achieve higher stitching stability and quality of the final images at least being -familiar with the theory is recommended. - -@note -- A basic example on image stitching can be found at - opencv_source_code/samples/cpp/stitching.cpp -- A basic example on image stitching in Python can be found at - opencv_source_code/samples/python/stitching.py -- A detailed example on image stitching can be found at - opencv_source_code/samples/cpp/stitching_detailed.cpp - */ -class CV_EXPORTS_W Stitcher -{ -public: - /** - * When setting a resolution for stitching, this values is a placeholder - * for preserving the original resolution. - */ -#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) - static constexpr double ORIG_RESOL = -1.0; -#else - // support MSVS 2013 - static const double ORIG_RESOL; // Initialized in stitcher.cpp -#endif - - enum Status - { - OK = 0, - ERR_NEED_MORE_IMGS = 1, - ERR_HOMOGRAPHY_EST_FAIL = 2, - ERR_CAMERA_PARAMS_ADJUST_FAIL = 3 - }; - - enum Mode - { - /** Mode for creating photo panoramas. Expects images under perspective - transformation and projects resulting pano to sphere. - - @sa detail::BestOf2NearestMatcher SphericalWarper - */ - PANORAMA = 0, - /** Mode for composing scans. Expects images under affine transformation does - not compensate exposure by default. - - @sa detail::AffineBestOf2NearestMatcher AffineWarper - */ - SCANS = 1, - - }; - - /** @brief Creates a Stitcher configured in one of the stitching modes. - - @param mode Scenario for stitcher operation. This is usually determined by source of images - to stitch and their transformation. Default parameters will be chosen for operation in given - scenario. - @return Stitcher class instance. - */ - CV_WRAP static Ptr create(Mode mode = Stitcher::PANORAMA); - - CV_WRAP double registrationResol() const { return registr_resol_; } - CV_WRAP void setRegistrationResol(double resol_mpx) { registr_resol_ = resol_mpx; } - - CV_WRAP double seamEstimationResol() const { return seam_est_resol_; } - CV_WRAP void setSeamEstimationResol(double resol_mpx) { seam_est_resol_ = resol_mpx; } - - CV_WRAP double compositingResol() const { return compose_resol_; } - CV_WRAP void setCompositingResol(double resol_mpx) { compose_resol_ = resol_mpx; } - - CV_WRAP double panoConfidenceThresh() const { return conf_thresh_; } - CV_WRAP void setPanoConfidenceThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } - - CV_WRAP bool waveCorrection() const { return do_wave_correct_; } - CV_WRAP void setWaveCorrection(bool flag) { do_wave_correct_ = flag; } - - CV_WRAP InterpolationFlags interpolationFlags() const { return interp_flags_; } - CV_WRAP void setInterpolationFlags(InterpolationFlags interp_flags) { interp_flags_ = interp_flags; } - - detail::WaveCorrectKind waveCorrectKind() const { return wave_correct_kind_; } - void setWaveCorrectKind(detail::WaveCorrectKind kind) { wave_correct_kind_ = kind; } - - Ptr featuresFinder() { return features_finder_; } - Ptr featuresFinder() const { return features_finder_; } - void setFeaturesFinder(Ptr features_finder) - { features_finder_ = features_finder; } - - Ptr featuresMatcher() { return features_matcher_; } - Ptr featuresMatcher() const { return features_matcher_; } - void setFeaturesMatcher(Ptr features_matcher) - { features_matcher_ = features_matcher; } - - const cv::UMat& matchingMask() const { return matching_mask_; } - void setMatchingMask(const cv::UMat &mask) - { - CV_Assert(mask.type() == CV_8U && mask.cols == mask.rows); - matching_mask_ = mask.clone(); - } - - Ptr bundleAdjuster() { return bundle_adjuster_; } - const Ptr bundleAdjuster() const { return bundle_adjuster_; } - void setBundleAdjuster(Ptr bundle_adjuster) - { bundle_adjuster_ = bundle_adjuster; } - - Ptr estimator() { return estimator_; } - const Ptr estimator() const { return estimator_; } - void setEstimator(Ptr estimator) - { estimator_ = estimator; } - - Ptr warper() { return warper_; } - const Ptr warper() const { return warper_; } - void setWarper(Ptr creator) { warper_ = creator; } - - Ptr exposureCompensator() { return exposure_comp_; } - const Ptr exposureCompensator() const { return exposure_comp_; } - void setExposureCompensator(Ptr exposure_comp) - { exposure_comp_ = exposure_comp; } - - Ptr seamFinder() { return seam_finder_; } - const Ptr seamFinder() const { return seam_finder_; } - void setSeamFinder(Ptr seam_finder) { seam_finder_ = seam_finder; } - - Ptr blender() { return blender_; } - const Ptr blender() const { return blender_; } - void setBlender(Ptr b) { blender_ = b; } - - /** @brief These functions try to match the given images and to estimate rotations of each camera. - - @note Use the functions only if you're aware of the stitching pipeline, otherwise use - Stitcher::stitch. - - @param images Input images. - @param masks Masks for each input image specifying where to look for keypoints (optional). - @return Status code. - */ - CV_WRAP Status estimateTransform(InputArrayOfArrays images, InputArrayOfArrays masks = noArray()); - - /** @brief These function restors camera rotation and camera intrinsics of each camera - * that can be got with @ref Stitcher::cameras call - - @param images Input images. - @param cameras Estimated rotation of cameras for each of the input images. - @param component Indices (0-based) of images constituting the final panorama (optional). - @return Status code. - */ - Status setTransform(InputArrayOfArrays images, - const std::vector &cameras, - const std::vector &component); - /** @overload */ - Status setTransform(InputArrayOfArrays images, const std::vector &cameras); - - /** @overload */ - CV_WRAP Status composePanorama(OutputArray pano); - /** @brief These functions try to compose the given images (or images stored internally from the other function - calls) into the final pano under the assumption that the image transformations were estimated - before. - - @note Use the functions only if you're aware of the stitching pipeline, otherwise use - Stitcher::stitch. - - @param images Input images. - @param pano Final pano. - @return Status code. - */ - CV_WRAP Status composePanorama(InputArrayOfArrays images, OutputArray pano); - - /** @overload */ - CV_WRAP Status stitch(InputArrayOfArrays images, OutputArray pano); - /** @brief These functions try to stitch the given images. - - @param images Input images. - @param masks Masks for each input image specifying where to look for keypoints (optional). - @param pano Final pano. - @return Status code. - */ - CV_WRAP Status stitch(InputArrayOfArrays images, InputArrayOfArrays masks, OutputArray pano); - - /** @brief Returns indeces of input images used in panorama stitching - */ - CV_WRAP std::vector component() const { return indices_; } - - /** Returns estimated camera parameters for all stitched images - */ - CV_WRAP std::vector cameras() const { return cameras_; } - CV_WRAP double workScale() const { return work_scale_; } - - /** @brief Return the mask of the panorama. - - The mask is a 8U UMat with the values: 0xFF (white) for pixels filled by the input images, - 0 (black) for unused pixels. It can be used as the mask for inpaint. - - @return The mask. - */ - UMat resultMask() const { return result_mask_; } - -private: - Status matchImages(); - Status estimateCameraParams(); - - double registr_resol_; - double seam_est_resol_; - double compose_resol_; - double conf_thresh_; - InterpolationFlags interp_flags_; - Ptr features_finder_; - Ptr features_matcher_; - cv::UMat matching_mask_; - Ptr bundle_adjuster_; - Ptr estimator_; - bool do_wave_correct_; - detail::WaveCorrectKind wave_correct_kind_; - Ptr warper_; - Ptr exposure_comp_; - Ptr seam_finder_; - Ptr blender_; - - std::vector imgs_; - std::vector masks_; - std::vector full_img_sizes_; - std::vector features_; - std::vector pairwise_matches_; - std::vector seam_est_imgs_; - std::vector indices_; - std::vector cameras_; - UMat result_mask_; - double work_scale_; - double seam_scale_; - double seam_work_aspect_; - double warped_image_scale_; -}; - -/** - * @deprecated use Stitcher::create - */ -CV_DEPRECATED Ptr createStitcher(bool try_use_gpu = false); - -/** - * @deprecated use Stitcher::create - */ -CV_DEPRECATED Ptr createStitcherScans(bool try_use_gpu = false); - -//! @} stitching - -} // namespace cv - -#endif // OPENCV_STITCHING_STITCHER_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_STITCHER_HPP +#define OPENCV_STITCHING_STITCHER_HPP + +#include "opencv2/core.hpp" +#include "opencv2/features2d.hpp" +#include "opencv2/stitching/warpers.hpp" +#include "opencv2/stitching/detail/matchers.hpp" +#include "opencv2/stitching/detail/motion_estimators.hpp" +#include "opencv2/stitching/detail/exposure_compensate.hpp" +#include "opencv2/stitching/detail/seam_finders.hpp" +#include "opencv2/stitching/detail/blenders.hpp" +#include "opencv2/stitching/detail/camera.hpp" + + +#if defined(Status) +# warning Detected X11 'Status' macro definition, it can cause build conflicts. Please, include this header before any X11 headers. +#endif + + +/** +@defgroup stitching Images stitching + +This figure illustrates the stitching module pipeline implemented in the Stitcher class. Using that +class it's possible to configure/remove some steps, i.e. adjust the stitching pipeline according to +the particular needs. All building blocks from the pipeline are available in the detail namespace, +one can combine and use them separately. + +The implemented stitching pipeline is very similar to the one proposed in @cite BL07 . + +![stitching pipeline](StitchingPipeline.jpg) + +Camera models +------------- + +There are currently 2 camera models implemented in stitching pipeline. + +- _Homography model_ expecting perspective transformations between images + implemented in @ref cv::detail::BestOf2NearestMatcher cv::detail::HomographyBasedEstimator + cv::detail::BundleAdjusterReproj cv::detail::BundleAdjusterRay +- _Affine model_ expecting affine transformation with 6 DOF or 4 DOF implemented in + @ref cv::detail::AffineBestOf2NearestMatcher cv::detail::AffineBasedEstimator + cv::detail::BundleAdjusterAffine cv::detail::BundleAdjusterAffinePartial cv::AffineWarper + +Homography model is useful for creating photo panoramas captured by camera, +while affine-based model can be used to stitch scans and object captured by +specialized devices. Use @ref cv::Stitcher::create to get preconfigured pipeline for one +of those models. + +@note +Certain detailed settings of @ref cv::Stitcher might not make sense. Especially +you should not mix classes implementing affine model and classes implementing +Homography model, as they work with different transformations. + +@{ + @defgroup stitching_match Features Finding and Images Matching + @defgroup stitching_rotation Rotation Estimation + @defgroup stitching_autocalib Autocalibration + @defgroup stitching_warp Images Warping + @defgroup stitching_seam Seam Estimation + @defgroup stitching_exposure Exposure Compensation + @defgroup stitching_blend Image Blenders +@} + */ + +namespace cv { + +//! @addtogroup stitching +//! @{ + +/** @example samples/cpp/stitching.cpp +A basic example on image stitching +*/ + +/** @example samples/python/stitching.py +A basic example on image stitching in Python. +*/ + +/** @example samples/cpp/stitching_detailed.cpp +A detailed example on image stitching +*/ + +/** @brief High level image stitcher. + +It's possible to use this class without being aware of the entire stitching pipeline. However, to +be able to achieve higher stitching stability and quality of the final images at least being +familiar with the theory is recommended. + +@note +- A basic example on image stitching can be found at + opencv_source_code/samples/cpp/stitching.cpp +- A basic example on image stitching in Python can be found at + opencv_source_code/samples/python/stitching.py +- A detailed example on image stitching can be found at + opencv_source_code/samples/cpp/stitching_detailed.cpp + */ +class CV_EXPORTS_W Stitcher +{ +public: + /** + * When setting a resolution for stitching, this values is a placeholder + * for preserving the original resolution. + */ +#if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/) + static constexpr double ORIG_RESOL = -1.0; +#else + // support MSVS 2013 + static const double ORIG_RESOL; // Initialized in stitcher.cpp +#endif + + enum Status + { + OK = 0, + ERR_NEED_MORE_IMGS = 1, + ERR_HOMOGRAPHY_EST_FAIL = 2, + ERR_CAMERA_PARAMS_ADJUST_FAIL = 3 + }; + + enum Mode + { + /** Mode for creating photo panoramas. Expects images under perspective + transformation and projects resulting pano to sphere. + + @sa detail::BestOf2NearestMatcher SphericalWarper + */ + PANORAMA = 0, + /** Mode for composing scans. Expects images under affine transformation does + not compensate exposure by default. + + @sa detail::AffineBestOf2NearestMatcher AffineWarper + */ + SCANS = 1, + + }; + + /** @brief Creates a Stitcher configured in one of the stitching modes. + + @param mode Scenario for stitcher operation. This is usually determined by source of images + to stitch and their transformation. Default parameters will be chosen for operation in given + scenario. + @return Stitcher class instance. + */ + CV_WRAP static Ptr create(Mode mode = Stitcher::PANORAMA); + + CV_WRAP double registrationResol() const { return registr_resol_; } + CV_WRAP void setRegistrationResol(double resol_mpx) { registr_resol_ = resol_mpx; } + + CV_WRAP double seamEstimationResol() const { return seam_est_resol_; } + CV_WRAP void setSeamEstimationResol(double resol_mpx) { seam_est_resol_ = resol_mpx; } + + CV_WRAP double compositingResol() const { return compose_resol_; } + CV_WRAP void setCompositingResol(double resol_mpx) { compose_resol_ = resol_mpx; } + + CV_WRAP double panoConfidenceThresh() const { return conf_thresh_; } + CV_WRAP void setPanoConfidenceThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } + + CV_WRAP bool waveCorrection() const { return do_wave_correct_; } + CV_WRAP void setWaveCorrection(bool flag) { do_wave_correct_ = flag; } + + CV_WRAP InterpolationFlags interpolationFlags() const { return interp_flags_; } + CV_WRAP void setInterpolationFlags(InterpolationFlags interp_flags) { interp_flags_ = interp_flags; } + + detail::WaveCorrectKind waveCorrectKind() const { return wave_correct_kind_; } + void setWaveCorrectKind(detail::WaveCorrectKind kind) { wave_correct_kind_ = kind; } + + Ptr featuresFinder() { return features_finder_; } + Ptr featuresFinder() const { return features_finder_; } + void setFeaturesFinder(Ptr features_finder) + { features_finder_ = features_finder; } + + Ptr featuresMatcher() { return features_matcher_; } + Ptr featuresMatcher() const { return features_matcher_; } + void setFeaturesMatcher(Ptr features_matcher) + { features_matcher_ = features_matcher; } + + const cv::UMat& matchingMask() const { return matching_mask_; } + void setMatchingMask(const cv::UMat &mask) + { + CV_Assert(mask.type() == CV_8U && mask.cols == mask.rows); + matching_mask_ = mask.clone(); + } + + Ptr bundleAdjuster() { return bundle_adjuster_; } + const Ptr bundleAdjuster() const { return bundle_adjuster_; } + void setBundleAdjuster(Ptr bundle_adjuster) + { bundle_adjuster_ = bundle_adjuster; } + + Ptr estimator() { return estimator_; } + const Ptr estimator() const { return estimator_; } + void setEstimator(Ptr estimator) + { estimator_ = estimator; } + + Ptr warper() { return warper_; } + const Ptr warper() const { return warper_; } + void setWarper(Ptr creator) { warper_ = creator; } + + Ptr exposureCompensator() { return exposure_comp_; } + const Ptr exposureCompensator() const { return exposure_comp_; } + void setExposureCompensator(Ptr exposure_comp) + { exposure_comp_ = exposure_comp; } + + Ptr seamFinder() { return seam_finder_; } + const Ptr seamFinder() const { return seam_finder_; } + void setSeamFinder(Ptr seam_finder) { seam_finder_ = seam_finder; } + + Ptr blender() { return blender_; } + const Ptr blender() const { return blender_; } + void setBlender(Ptr b) { blender_ = b; } + + /** @brief These functions try to match the given images and to estimate rotations of each camera. + + @note Use the functions only if you're aware of the stitching pipeline, otherwise use + Stitcher::stitch. + + @param images Input images. + @param masks Masks for each input image specifying where to look for keypoints (optional). + @return Status code. + */ + CV_WRAP Status estimateTransform(InputArrayOfArrays images, InputArrayOfArrays masks = noArray()); + + /** @brief These function restors camera rotation and camera intrinsics of each camera + * that can be got with @ref Stitcher::cameras call + + @param images Input images. + @param cameras Estimated rotation of cameras for each of the input images. + @param component Indices (0-based) of images constituting the final panorama (optional). + @return Status code. + */ + Status setTransform(InputArrayOfArrays images, + const std::vector &cameras, + const std::vector &component); + /** @overload */ + Status setTransform(InputArrayOfArrays images, const std::vector &cameras); + + /** @overload */ + CV_WRAP Status composePanorama(OutputArray pano); + /** @brief These functions try to compose the given images (or images stored internally from the other function + calls) into the final pano under the assumption that the image transformations were estimated + before. + + @note Use the functions only if you're aware of the stitching pipeline, otherwise use + Stitcher::stitch. + + @param images Input images. + @param pano Final pano. + @return Status code. + */ + CV_WRAP Status composePanorama(InputArrayOfArrays images, OutputArray pano); + + /** @overload */ + CV_WRAP Status stitch(InputArrayOfArrays images, OutputArray pano); + /** @brief These functions try to stitch the given images. + + @param images Input images. + @param masks Masks for each input image specifying where to look for keypoints (optional). + @param pano Final pano. + @return Status code. + */ + CV_WRAP Status stitch(InputArrayOfArrays images, InputArrayOfArrays masks, OutputArray pano); + + /** @brief Returns indeces of input images used in panorama stitching + */ + CV_WRAP std::vector component() const { return indices_; } + + /** Returns estimated camera parameters for all stitched images + */ + CV_WRAP std::vector cameras() const { return cameras_; } + CV_WRAP double workScale() const { return work_scale_; } + + /** @brief Return the mask of the panorama. + + The mask is a 8U UMat with the values: 0xFF (white) for pixels filled by the input images, + 0 (black) for unused pixels. It can be used as the mask for inpaint. + + @return The mask. + */ + UMat resultMask() const { return result_mask_; } + +private: + Status matchImages(); + Status estimateCameraParams(); + + double registr_resol_; + double seam_est_resol_; + double compose_resol_; + double conf_thresh_; + InterpolationFlags interp_flags_; + Ptr features_finder_; + Ptr features_matcher_; + cv::UMat matching_mask_; + Ptr bundle_adjuster_; + Ptr estimator_; + bool do_wave_correct_; + detail::WaveCorrectKind wave_correct_kind_; + Ptr warper_; + Ptr exposure_comp_; + Ptr seam_finder_; + Ptr blender_; + + std::vector imgs_; + std::vector masks_; + std::vector full_img_sizes_; + std::vector features_; + std::vector pairwise_matches_; + std::vector seam_est_imgs_; + std::vector indices_; + std::vector cameras_; + UMat result_mask_; + double work_scale_; + double seam_scale_; + double seam_work_aspect_; + double warped_image_scale_; +}; + +/** + * @deprecated use Stitcher::create + */ +CV_DEPRECATED Ptr createStitcher(bool try_use_gpu = false); + +/** + * @deprecated use Stitcher::create + */ +CV_DEPRECATED Ptr createStitcherScans(bool try_use_gpu = false); + +//! @} stitching + +} // namespace cv + +#endif // OPENCV_STITCHING_STITCHER_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp index 7487560f82..8eb6212c65 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/autocalib.hpp @@ -1,86 +1,86 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_AUTOCALIB_HPP -#define OPENCV_STITCHING_AUTOCALIB_HPP - -#include "opencv2/core.hpp" -#include "matchers.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_autocalib -//! @{ - -/** @brief Tries to estimate focal lengths from the given homography under the assumption that the camera -undergoes rotations around its centre only. - -@param H Homography. -@param f0 Estimated focal length along X axis. -@param f1 Estimated focal length along Y axis. -@param f0_ok True, if f0 was estimated successfully, false otherwise. -@param f1_ok True, if f1 was estimated successfully, false otherwise. - -See "Construction of Panoramic Image Mosaics with Global and Local Alignment" -by Heung-Yeung Shum and Richard Szeliski. - */ -void CV_EXPORTS_W focalsFromHomography(const Mat &H, double &f0, double &f1, bool &f0_ok, bool &f1_ok); - -/** @brief Estimates focal lengths for each given camera. - -@param features Features of images. -@param pairwise_matches Matches between all image pairs. -@param focals Estimated focal lengths for each camera. - */ -void CV_EXPORTS estimateFocal(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &focals); - -bool CV_EXPORTS_W calibrateRotatingCamera(const std::vector &Hs,CV_OUT Mat &K); - -//! @} stitching_autocalib - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_AUTOCALIB_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_AUTOCALIB_HPP +#define OPENCV_STITCHING_AUTOCALIB_HPP + +#include "opencv2/core.hpp" +#include "matchers.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_autocalib +//! @{ + +/** @brief Tries to estimate focal lengths from the given homography under the assumption that the camera +undergoes rotations around its centre only. + +@param H Homography. +@param f0 Estimated focal length along X axis. +@param f1 Estimated focal length along Y axis. +@param f0_ok True, if f0 was estimated successfully, false otherwise. +@param f1_ok True, if f1 was estimated successfully, false otherwise. + +See "Construction of Panoramic Image Mosaics with Global and Local Alignment" +by Heung-Yeung Shum and Richard Szeliski. + */ +void CV_EXPORTS_W focalsFromHomography(const Mat &H, double &f0, double &f1, bool &f0_ok, bool &f1_ok); + +/** @brief Estimates focal lengths for each given camera. + +@param features Features of images. +@param pairwise_matches Matches between all image pairs. +@param focals Estimated focal lengths for each camera. + */ +void CV_EXPORTS estimateFocal(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &focals); + +bool CV_EXPORTS_W calibrateRotatingCamera(const std::vector &Hs,CV_OUT Mat &K); + +//! @} stitching_autocalib + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_AUTOCALIB_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp index 79e1af43e3..ec35aa7cbb 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/blenders.hpp @@ -1,184 +1,184 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_BLENDERS_HPP -#define OPENCV_STITCHING_BLENDERS_HPP - -#if defined(NO) -# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. -#endif - -#include "opencv2/core.hpp" -#include "opencv2/core/cuda.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_blend -//! @{ - -/** @brief Base class for all blenders. - -Simple blender which puts one image over another -*/ -class CV_EXPORTS_W Blender -{ -public: - virtual ~Blender() {} - - enum { NO, FEATHER, MULTI_BAND }; - CV_WRAP static Ptr createDefault(int type, bool try_gpu = false); - - /** @brief Prepares the blender for blending. - - @param corners Source images top-left corners - @param sizes Source image sizes - */ - CV_WRAP virtual void prepare(const std::vector &corners, const std::vector &sizes); - /** @overload */ - CV_WRAP virtual void prepare(Rect dst_roi); - /** @brief Processes the image. - - @param img Source image - @param mask Source image mask - @param tl Source image top-left corners - */ - CV_WRAP virtual void feed(InputArray img, InputArray mask, Point tl); - /** @brief Blends and returns the final pano. - - @param dst Final pano - @param dst_mask Final pano mask - */ - CV_WRAP virtual void blend(CV_IN_OUT InputOutputArray dst,CV_IN_OUT InputOutputArray dst_mask); - -protected: - UMat dst_, dst_mask_; - Rect dst_roi_; -}; - -/** @brief Simple blender which mixes images at its borders. - */ -class CV_EXPORTS_W FeatherBlender : public Blender -{ -public: - CV_WRAP FeatherBlender(float sharpness = 0.02f); - - CV_WRAP float sharpness() const { return sharpness_; } - CV_WRAP void setSharpness(float val) { sharpness_ = val; } - - CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; - CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; - CV_WRAP void blend(InputOutputArray dst, InputOutputArray dst_mask) CV_OVERRIDE; - - //! Creates weight maps for fixed set of source images by their masks and top-left corners. - //! Final image can be obtained by simple weighting of the source images. - CV_WRAP Rect createWeightMaps(const std::vector &masks, const std::vector &corners, - CV_IN_OUT std::vector &weight_maps); - -private: - float sharpness_; - UMat weight_map_; - UMat dst_weight_map_; -}; - -inline FeatherBlender::FeatherBlender(float _sharpness) { setSharpness(_sharpness); } - -/** @brief Blender which uses multi-band blending algorithm (see @cite BA83). - */ -class CV_EXPORTS_W MultiBandBlender : public Blender -{ -public: - CV_WRAP MultiBandBlender(int try_gpu = false, int num_bands = 5, int weight_type = CV_32F); - - CV_WRAP int numBands() const { return actual_num_bands_; } - CV_WRAP void setNumBands(int val) { actual_num_bands_ = val; } - - CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; - CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; - CV_WRAP void blend(CV_IN_OUT InputOutputArray dst, CV_IN_OUT InputOutputArray dst_mask) CV_OVERRIDE; - -private: - int actual_num_bands_, num_bands_; - std::vector dst_pyr_laplace_; - std::vector dst_band_weights_; - Rect dst_roi_final_; - bool can_use_gpu_; - int weight_type_; //CV_32F or CV_16S -#if defined(HAVE_OPENCV_CUDAARITHM) && defined(HAVE_OPENCV_CUDAWARPING) - std::vector gpu_dst_pyr_laplace_; - std::vector gpu_dst_band_weights_; - std::vector gpu_tl_points_; - std::vector gpu_imgs_with_border_; - std::vector > gpu_weight_pyr_gauss_vec_; - std::vector > gpu_src_pyr_laplace_vec_; - std::vector > gpu_ups_; - cuda::GpuMat gpu_dst_mask_; - cuda::GpuMat gpu_mask_; - cuda::GpuMat gpu_img_; - cuda::GpuMat gpu_weight_map_; - cuda::GpuMat gpu_add_mask_; - int gpu_feed_idx_; - bool gpu_initialized_; -#endif -}; - - -////////////////////////////////////////////////////////////////////////////// -// Auxiliary functions - -void CV_EXPORTS_W normalizeUsingWeightMap(InputArray weight, CV_IN_OUT InputOutputArray src); - -void CV_EXPORTS_W createWeightMap(InputArray mask, float sharpness, CV_IN_OUT InputOutputArray weight); - -void CV_EXPORTS_W createLaplacePyr(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); -void CV_EXPORTS_W createLaplacePyrGpu(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); - -// Restores source image -void CV_EXPORTS_W restoreImageFromLaplacePyr(CV_IN_OUT std::vector& pyr); -void CV_EXPORTS_W restoreImageFromLaplacePyrGpu(CV_IN_OUT std::vector& pyr); - -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_BLENDERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_BLENDERS_HPP +#define OPENCV_STITCHING_BLENDERS_HPP + +#if defined(NO) +# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. +#endif + +#include "opencv2/core.hpp" +#include "opencv2/core/cuda.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_blend +//! @{ + +/** @brief Base class for all blenders. + +Simple blender which puts one image over another +*/ +class CV_EXPORTS_W Blender +{ +public: + virtual ~Blender() {} + + enum { NO, FEATHER, MULTI_BAND }; + CV_WRAP static Ptr createDefault(int type, bool try_gpu = false); + + /** @brief Prepares the blender for blending. + + @param corners Source images top-left corners + @param sizes Source image sizes + */ + CV_WRAP virtual void prepare(const std::vector &corners, const std::vector &sizes); + /** @overload */ + CV_WRAP virtual void prepare(Rect dst_roi); + /** @brief Processes the image. + + @param img Source image + @param mask Source image mask + @param tl Source image top-left corners + */ + CV_WRAP virtual void feed(InputArray img, InputArray mask, Point tl); + /** @brief Blends and returns the final pano. + + @param dst Final pano + @param dst_mask Final pano mask + */ + CV_WRAP virtual void blend(CV_IN_OUT InputOutputArray dst,CV_IN_OUT InputOutputArray dst_mask); + +protected: + UMat dst_, dst_mask_; + Rect dst_roi_; +}; + +/** @brief Simple blender which mixes images at its borders. + */ +class CV_EXPORTS_W FeatherBlender : public Blender +{ +public: + CV_WRAP FeatherBlender(float sharpness = 0.02f); + + CV_WRAP float sharpness() const { return sharpness_; } + CV_WRAP void setSharpness(float val) { sharpness_ = val; } + + CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; + CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; + CV_WRAP void blend(InputOutputArray dst, InputOutputArray dst_mask) CV_OVERRIDE; + + //! Creates weight maps for fixed set of source images by their masks and top-left corners. + //! Final image can be obtained by simple weighting of the source images. + CV_WRAP Rect createWeightMaps(const std::vector &masks, const std::vector &corners, + CV_IN_OUT std::vector &weight_maps); + +private: + float sharpness_; + UMat weight_map_; + UMat dst_weight_map_; +}; + +inline FeatherBlender::FeatherBlender(float _sharpness) { setSharpness(_sharpness); } + +/** @brief Blender which uses multi-band blending algorithm (see @cite BA83). + */ +class CV_EXPORTS_W MultiBandBlender : public Blender +{ +public: + CV_WRAP MultiBandBlender(int try_gpu = false, int num_bands = 5, int weight_type = CV_32F); + + CV_WRAP int numBands() const { return actual_num_bands_; } + CV_WRAP void setNumBands(int val) { actual_num_bands_ = val; } + + CV_WRAP void prepare(Rect dst_roi) CV_OVERRIDE; + CV_WRAP void feed(InputArray img, InputArray mask, Point tl) CV_OVERRIDE; + CV_WRAP void blend(CV_IN_OUT InputOutputArray dst, CV_IN_OUT InputOutputArray dst_mask) CV_OVERRIDE; + +private: + int actual_num_bands_, num_bands_; + std::vector dst_pyr_laplace_; + std::vector dst_band_weights_; + Rect dst_roi_final_; + bool can_use_gpu_; + int weight_type_; //CV_32F or CV_16S +#if defined(HAVE_OPENCV_CUDAARITHM) && defined(HAVE_OPENCV_CUDAWARPING) + std::vector gpu_dst_pyr_laplace_; + std::vector gpu_dst_band_weights_; + std::vector gpu_tl_points_; + std::vector gpu_imgs_with_border_; + std::vector > gpu_weight_pyr_gauss_vec_; + std::vector > gpu_src_pyr_laplace_vec_; + std::vector > gpu_ups_; + cuda::GpuMat gpu_dst_mask_; + cuda::GpuMat gpu_mask_; + cuda::GpuMat gpu_img_; + cuda::GpuMat gpu_weight_map_; + cuda::GpuMat gpu_add_mask_; + int gpu_feed_idx_; + bool gpu_initialized_; +#endif +}; + + +////////////////////////////////////////////////////////////////////////////// +// Auxiliary functions + +void CV_EXPORTS_W normalizeUsingWeightMap(InputArray weight, CV_IN_OUT InputOutputArray src); + +void CV_EXPORTS_W createWeightMap(InputArray mask, float sharpness, CV_IN_OUT InputOutputArray weight); + +void CV_EXPORTS_W createLaplacePyr(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); +void CV_EXPORTS_W createLaplacePyrGpu(InputArray img, int num_levels, CV_IN_OUT std::vector& pyr); + +// Restores source image +void CV_EXPORTS_W restoreImageFromLaplacePyr(CV_IN_OUT std::vector& pyr); +void CV_EXPORTS_W restoreImageFromLaplacePyrGpu(CV_IN_OUT std::vector& pyr); + +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_BLENDERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp index 3ae7fd29b5..14ecf60f30 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/camera.hpp @@ -1,78 +1,78 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_CAMERA_HPP -#define OPENCV_STITCHING_CAMERA_HPP - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching -//! @{ - -/** @brief Describes camera parameters. - -@note Translation is assumed to be zero during the whole stitching pipeline. : - */ -struct CV_EXPORTS_W_SIMPLE CameraParams -{ - CameraParams(); - CameraParams(const CameraParams& other); - CameraParams& operator =(const CameraParams& other); - CV_WRAP Mat K() const; - - CV_PROP_RW double focal; // Focal length - CV_PROP_RW double aspect; // Aspect ratio - CV_PROP_RW double ppx; // Principal point X - CV_PROP_RW double ppy; // Principal point Y - CV_PROP_RW Mat R; // Rotation - CV_PROP_RW Mat t; // Translation -}; - -//! @} - -} // namespace detail -} // namespace cv - -#endif // #ifndef OPENCV_STITCHING_CAMERA_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_CAMERA_HPP +#define OPENCV_STITCHING_CAMERA_HPP + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching +//! @{ + +/** @brief Describes camera parameters. + +@note Translation is assumed to be zero during the whole stitching pipeline. : + */ +struct CV_EXPORTS_W_SIMPLE CameraParams +{ + CameraParams(); + CameraParams(const CameraParams& other); + CameraParams& operator =(const CameraParams& other); + CV_WRAP Mat K() const; + + CV_PROP_RW double focal; // Focal length + CV_PROP_RW double aspect; // Aspect ratio + CV_PROP_RW double ppx; // Principal point X + CV_PROP_RW double ppy; // Principal point Y + CV_PROP_RW Mat R; // Rotation + CV_PROP_RW Mat t; // Translation +}; + +//! @} + +} // namespace detail +} // namespace cv + +#endif // #ifndef OPENCV_STITCHING_CAMERA_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp index fb4eb71eb4..dea76c957b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/exposure_compensate.hpp @@ -1,245 +1,245 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP -#define OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP - -#if defined(NO) -# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. -#endif - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_exposure -//! @{ - -/** @brief Base class for all exposure compensators. - */ -class CV_EXPORTS_W ExposureCompensator -{ -public: - ExposureCompensator(): updateGain(true) {} - virtual ~ExposureCompensator() {} - - enum { NO, GAIN, GAIN_BLOCKS, CHANNELS, CHANNELS_BLOCKS }; - CV_WRAP static Ptr createDefault(int type); - - /** - @param corners Source image top-left corners - @param images Source images - @param masks Image masks to update (second value in pair specifies the value which should be used - to detect where image is) - */ - CV_WRAP void feed(const std::vector &corners, const std::vector &images, - const std::vector &masks); - /** @overload */ - virtual void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) = 0; - /** @brief Compensate exposure in the specified image. - - @param index Image index - @param corner Image top-left corner - @param image Image to process - @param mask Image mask - */ - CV_WRAP virtual void apply(int index, Point corner, InputOutputArray image, InputArray mask) = 0; - CV_WRAP virtual void getMatGains(CV_OUT std::vector& ) {CV_Error(Error::StsInternal, "");} - CV_WRAP virtual void setMatGains(std::vector& ) { CV_Error(Error::StsInternal, ""); } - CV_WRAP void setUpdateGain(bool b) { updateGain = b; } - CV_WRAP bool getUpdateGain() { return updateGain; } -protected : - bool updateGain; -}; - -/** @brief Stub exposure compensator which does nothing. - */ -class CV_EXPORTS_W NoExposureCompensator : public ExposureCompensator -{ -public: - void feed(const std::vector &/*corners*/, const std::vector &/*images*/, - const std::vector > &/*masks*/) CV_OVERRIDE { } - CV_WRAP void apply(int /*index*/, Point /*corner*/, InputOutputArray /*image*/, InputArray /*mask*/) CV_OVERRIDE { } - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { umv.clear(); return; } - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { umv.clear(); return; } -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image -intensities, see @cite BL07 and @cite WJ10 for details. - */ -class CV_EXPORTS_W GainCompensator : public ExposureCompensator -{ -public: - // This Constructor only exists to make source level compatibility detector happy - CV_WRAP GainCompensator() - : GainCompensator(1) {} - CV_WRAP GainCompensator(int nr_feeds) - : nr_feeds_(nr_feeds), similarity_threshold_(1) {} - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; - void singleFeed(const std::vector &corners, const std::vector &images, - const std::vector > &masks); - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE ; - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE ; - CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } - CV_WRAP int getNrFeeds() { return nr_feeds_; } - CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } - CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } - void prepareSimilarityMask(const std::vector &corners, const std::vector &images); - std::vector gains() const; - -private: - UMat buildSimilarityMask(InputArray src_array1, InputArray src_array2); - - Mat_ gains_; - int nr_feeds_; - double similarity_threshold_; - std::vector similarities_; -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image -intensities on each channel independently. - */ -class CV_EXPORTS_W ChannelsCompensator : public ExposureCompensator -{ -public: - CV_WRAP ChannelsCompensator(int nr_feeds=1) - : nr_feeds_(nr_feeds), similarity_threshold_(1) {} - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; - CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } - CV_WRAP int getNrFeeds() { return nr_feeds_; } - CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } - CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } - std::vector gains() const { return gains_; } - -private: - std::vector gains_; - int nr_feeds_; - double similarity_threshold_; -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image blocks. - */ -class CV_EXPORTS_W BlocksCompensator : public ExposureCompensator -{ -public: - BlocksCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) - : bl_width_(bl_width), bl_height_(bl_height), nr_feeds_(nr_feeds), nr_gain_filtering_iterations_(2), - similarity_threshold_(1) {} - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; - CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } - CV_WRAP int getNrFeeds() { return nr_feeds_; } - CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } - CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } - CV_WRAP void setBlockSize(int width, int height) { bl_width_ = width; bl_height_ = height; } - CV_WRAP void setBlockSize(Size size) { setBlockSize(size.width, size.height); } - CV_WRAP Size getBlockSize() const { return Size(bl_width_, bl_height_); } - CV_WRAP void setNrGainsFilteringIterations(int nr_iterations) { nr_gain_filtering_iterations_ = nr_iterations; } - CV_WRAP int getNrGainsFilteringIterations() const { return nr_gain_filtering_iterations_; } - -protected: - template - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks); - -private: - UMat getGainMap(const GainCompensator& compensator, int bl_idx, Size bl_per_img); - UMat getGainMap(const ChannelsCompensator& compensator, int bl_idx, Size bl_per_img); - - int bl_width_, bl_height_; - std::vector gain_maps_; - int nr_feeds_; - int nr_gain_filtering_iterations_; - double similarity_threshold_; -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block -intensities, see @cite UES01 for details. - */ -class CV_EXPORTS_W BlocksGainCompensator : public BlocksCompensator -{ -public: - // This Constructor only exists to make source level compatibility detector happy - CV_WRAP BlocksGainCompensator(int bl_width = 32, int bl_height = 32) - : BlocksGainCompensator(bl_width, bl_height, 1) {} - CV_WRAP BlocksGainCompensator(int bl_width, int bl_height, int nr_feeds) - : BlocksCompensator(bl_width, bl_height, nr_feeds) {} - - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; - - // This function only exists to make source level compatibility detector happy - CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE { - BlocksCompensator::apply(index, corner, image, mask); } - // This function only exists to make source level compatibility detector happy - CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { BlocksCompensator::getMatGains(umv); } - // This function only exists to make source level compatibility detector happy - CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { BlocksCompensator::setMatGains(umv); } -}; - -/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block -on each channel. - */ -class CV_EXPORTS_W BlocksChannelsCompensator : public BlocksCompensator -{ -public: - CV_WRAP BlocksChannelsCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) - : BlocksCompensator(bl_width, bl_height, nr_feeds) {} - - void feed(const std::vector &corners, const std::vector &images, - const std::vector > &masks) CV_OVERRIDE; -}; -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP +#define OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP + +#if defined(NO) +# warning Detected Apple 'NO' macro definition, it can cause build conflicts. Please, include this header before any Apple headers. +#endif + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_exposure +//! @{ + +/** @brief Base class for all exposure compensators. + */ +class CV_EXPORTS_W ExposureCompensator +{ +public: + ExposureCompensator(): updateGain(true) {} + virtual ~ExposureCompensator() {} + + enum { NO, GAIN, GAIN_BLOCKS, CHANNELS, CHANNELS_BLOCKS }; + CV_WRAP static Ptr createDefault(int type); + + /** + @param corners Source image top-left corners + @param images Source images + @param masks Image masks to update (second value in pair specifies the value which should be used + to detect where image is) + */ + CV_WRAP void feed(const std::vector &corners, const std::vector &images, + const std::vector &masks); + /** @overload */ + virtual void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) = 0; + /** @brief Compensate exposure in the specified image. + + @param index Image index + @param corner Image top-left corner + @param image Image to process + @param mask Image mask + */ + CV_WRAP virtual void apply(int index, Point corner, InputOutputArray image, InputArray mask) = 0; + CV_WRAP virtual void getMatGains(CV_OUT std::vector& ) {CV_Error(Error::StsInternal, "");} + CV_WRAP virtual void setMatGains(std::vector& ) { CV_Error(Error::StsInternal, ""); } + CV_WRAP void setUpdateGain(bool b) { updateGain = b; } + CV_WRAP bool getUpdateGain() { return updateGain; } +protected : + bool updateGain; +}; + +/** @brief Stub exposure compensator which does nothing. + */ +class CV_EXPORTS_W NoExposureCompensator : public ExposureCompensator +{ +public: + void feed(const std::vector &/*corners*/, const std::vector &/*images*/, + const std::vector > &/*masks*/) CV_OVERRIDE { } + CV_WRAP void apply(int /*index*/, Point /*corner*/, InputOutputArray /*image*/, InputArray /*mask*/) CV_OVERRIDE { } + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { umv.clear(); return; } + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { umv.clear(); return; } +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image +intensities, see @cite BL07 and @cite WJ10 for details. + */ +class CV_EXPORTS_W GainCompensator : public ExposureCompensator +{ +public: + // This Constructor only exists to make source level compatibility detector happy + CV_WRAP GainCompensator() + : GainCompensator(1) {} + CV_WRAP GainCompensator(int nr_feeds) + : nr_feeds_(nr_feeds), similarity_threshold_(1) {} + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; + void singleFeed(const std::vector &corners, const std::vector &images, + const std::vector > &masks); + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE ; + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE ; + CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } + CV_WRAP int getNrFeeds() { return nr_feeds_; } + CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } + CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } + void prepareSimilarityMask(const std::vector &corners, const std::vector &images); + std::vector gains() const; + +private: + UMat buildSimilarityMask(InputArray src_array1, InputArray src_array2); + + Mat_ gains_; + int nr_feeds_; + double similarity_threshold_; + std::vector similarities_; +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image +intensities on each channel independently. + */ +class CV_EXPORTS_W ChannelsCompensator : public ExposureCompensator +{ +public: + CV_WRAP ChannelsCompensator(int nr_feeds=1) + : nr_feeds_(nr_feeds), similarity_threshold_(1) {} + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; + CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } + CV_WRAP int getNrFeeds() { return nr_feeds_; } + CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } + CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } + std::vector gains() const { return gains_; } + +private: + std::vector gains_; + int nr_feeds_; + double similarity_threshold_; +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image blocks. + */ +class CV_EXPORTS_W BlocksCompensator : public ExposureCompensator +{ +public: + BlocksCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) + : bl_width_(bl_width), bl_height_(bl_height), nr_feeds_(nr_feeds), nr_gain_filtering_iterations_(2), + similarity_threshold_(1) {} + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE; + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE; + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE; + CV_WRAP void setNrFeeds(int nr_feeds) { nr_feeds_ = nr_feeds; } + CV_WRAP int getNrFeeds() { return nr_feeds_; } + CV_WRAP void setSimilarityThreshold(double similarity_threshold) { similarity_threshold_ = similarity_threshold; } + CV_WRAP double getSimilarityThreshold() const { return similarity_threshold_; } + CV_WRAP void setBlockSize(int width, int height) { bl_width_ = width; bl_height_ = height; } + CV_WRAP void setBlockSize(Size size) { setBlockSize(size.width, size.height); } + CV_WRAP Size getBlockSize() const { return Size(bl_width_, bl_height_); } + CV_WRAP void setNrGainsFilteringIterations(int nr_iterations) { nr_gain_filtering_iterations_ = nr_iterations; } + CV_WRAP int getNrGainsFilteringIterations() const { return nr_gain_filtering_iterations_; } + +protected: + template + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks); + +private: + UMat getGainMap(const GainCompensator& compensator, int bl_idx, Size bl_per_img); + UMat getGainMap(const ChannelsCompensator& compensator, int bl_idx, Size bl_per_img); + + int bl_width_, bl_height_; + std::vector gain_maps_; + int nr_feeds_; + int nr_gain_filtering_iterations_; + double similarity_threshold_; +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block +intensities, see @cite UES01 for details. + */ +class CV_EXPORTS_W BlocksGainCompensator : public BlocksCompensator +{ +public: + // This Constructor only exists to make source level compatibility detector happy + CV_WRAP BlocksGainCompensator(int bl_width = 32, int bl_height = 32) + : BlocksGainCompensator(bl_width, bl_height, 1) {} + CV_WRAP BlocksGainCompensator(int bl_width, int bl_height, int nr_feeds) + : BlocksCompensator(bl_width, bl_height, nr_feeds) {} + + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; + + // This function only exists to make source level compatibility detector happy + CV_WRAP void apply(int index, Point corner, InputOutputArray image, InputArray mask) CV_OVERRIDE { + BlocksCompensator::apply(index, corner, image, mask); } + // This function only exists to make source level compatibility detector happy + CV_WRAP void getMatGains(CV_OUT std::vector& umv) CV_OVERRIDE { BlocksCompensator::getMatGains(umv); } + // This function only exists to make source level compatibility detector happy + CV_WRAP void setMatGains(std::vector& umv) CV_OVERRIDE { BlocksCompensator::setMatGains(umv); } +}; + +/** @brief Exposure compensator which tries to remove exposure related artifacts by adjusting image block +on each channel. + */ +class CV_EXPORTS_W BlocksChannelsCompensator : public BlocksCompensator +{ +public: + CV_WRAP BlocksChannelsCompensator(int bl_width=32, int bl_height=32, int nr_feeds=1) + : BlocksCompensator(bl_width, bl_height, nr_feeds) {} + + void feed(const std::vector &corners, const std::vector &images, + const std::vector > &masks) CV_OVERRIDE; +}; +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_EXPOSURE_COMPENSATE_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp index 44a623ae6c..e25668308e 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/matchers.hpp @@ -1,267 +1,267 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_MATCHERS_HPP -#define OPENCV_STITCHING_MATCHERS_HPP - -#include "opencv2/core.hpp" -#include "opencv2/features2d.hpp" - -#include "opencv2/opencv_modules.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_match -//! @{ - -/** @brief Structure containing image keypoints and descriptors. */ -struct CV_EXPORTS_W_SIMPLE ImageFeatures -{ - CV_PROP_RW int img_idx; - CV_PROP_RW Size img_size; - CV_PROP_RW std::vector keypoints; - CV_PROP_RW UMat descriptors; - CV_WRAP std::vector getKeypoints() { return keypoints; } -}; -/** @brief - -@param featuresFinder -@param images -@param features -@param masks -*/ -CV_EXPORTS_W void computeImageFeatures( - const Ptr &featuresFinder, - InputArrayOfArrays images, - CV_OUT std::vector &features, - InputArrayOfArrays masks = noArray()); - -/** @brief - -@param featuresFinder -@param image -@param features -@param mask -*/ -CV_EXPORTS_AS(computeImageFeatures2) void computeImageFeatures( - const Ptr &featuresFinder, - InputArray image, - CV_OUT ImageFeatures &features, - InputArray mask = noArray()); - -/** @brief Structure containing information about matches between two images. - -It's assumed that there is a transformation between those images. Transformation may be -homography or affine transformation based on selected matcher. - -@sa detail::FeaturesMatcher -*/ -struct CV_EXPORTS_W_SIMPLE MatchesInfo -{ - MatchesInfo(); - MatchesInfo(const MatchesInfo &other); - MatchesInfo& operator =(const MatchesInfo &other); - - CV_PROP_RW int src_img_idx; - CV_PROP_RW int dst_img_idx; //!< Images indices (optional) - CV_PROP_RW std::vector matches; - CV_PROP_RW std::vector inliers_mask; //!< Geometrically consistent matches mask - CV_PROP_RW int num_inliers; //!< Number of geometrically consistent matches - CV_PROP_RW Mat H; //!< Estimated transformation - CV_PROP_RW double confidence; //!< Confidence two images are from the same panorama - CV_WRAP std::vector getMatches() { return matches; } - CV_WRAP std::vector getInliers() { return inliers_mask; } -}; - -/** @brief Feature matchers base class. */ -class CV_EXPORTS_W FeaturesMatcher -{ -public: - CV_WRAP virtual ~FeaturesMatcher() {} - - /** @overload - @param features1 First image features - @param features2 Second image features - @param matches_info Found matches - */ - CV_WRAP_AS(apply) void operator ()(const ImageFeatures &features1, const ImageFeatures &features2, - CV_OUT MatchesInfo& matches_info) { match(features1, features2, matches_info); } - - /** @brief Performs images matching. - - @param features Features of the source images - @param pairwise_matches Found pairwise matches - @param mask Mask indicating which image pairs must be matched - - The function is parallelized with the TBB library. - - @sa detail::MatchesInfo - */ - CV_WRAP_AS(apply2) void operator ()(const std::vector &features, CV_OUT std::vector &pairwise_matches, - const cv::UMat &mask = cv::UMat()) { match(features, pairwise_matches, mask); } - - /** @return True, if it's possible to use the same matcher instance in parallel, false otherwise - */ - CV_WRAP bool isThreadSafe() const { return is_thread_safe_; } - - /** @brief Frees unused memory allocated before if there is any. - */ - CV_WRAP virtual void collectGarbage() {} - -protected: - FeaturesMatcher(bool is_thread_safe = false) : is_thread_safe_(is_thread_safe) {} - - /** @brief This method must implement matching logic in order to make the wrappers - detail::FeaturesMatcher::operator()_ work. - - @param features1 first image features - @param features2 second image features - @param matches_info found matches - */ - virtual void match(const ImageFeatures &features1, const ImageFeatures &features2, - MatchesInfo& matches_info) = 0; - - /** @brief This method implements logic to match features between arbitrary number of features. - By default this checks every pair of inputs in the input, but the behaviour can be changed by subclasses. - - @param features vector of image features - @param pairwise_matches found matches - @param mask (optional) mask indicating which image pairs should be matched - */ - virtual void match(const std::vector &features, std::vector &pairwise_matches, - const cv::UMat &mask = cv::UMat()); - - bool is_thread_safe_; -}; - -/** @brief Features matcher which finds two best matches for each feature and leaves the best one only if the -ratio between descriptor distances is greater than the threshold match_conf - -@sa detail::FeaturesMatcher - */ -class CV_EXPORTS_W BestOf2NearestMatcher : public FeaturesMatcher -{ -public: - /** @brief Constructs a "best of 2 nearest" matcher. - - @param try_use_gpu Should try to use GPU or not - @param match_conf Match distances ration threshold - @param num_matches_thresh1 Minimum number of matches required for the 2D projective transform - estimation used in the inliers classification step - @param num_matches_thresh2 Minimum number of matches required for the 2D projective transform - re-estimation on inliers - @param matches_confindece_thresh Matching confidence threshold to take the match into account. - The threshold was determined experimentally and set to 3 by default. - */ - CV_WRAP BestOf2NearestMatcher(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, - int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); - - CV_WRAP void collectGarbage() CV_OVERRIDE; - CV_WRAP static Ptr create(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, - int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); - -protected: - - void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; - int num_matches_thresh1_; - int num_matches_thresh2_; - double matches_confindece_thresh_; - Ptr impl_; -}; - -class CV_EXPORTS_W BestOf2NearestRangeMatcher : public BestOf2NearestMatcher -{ -public: - CV_WRAP BestOf2NearestRangeMatcher(int range_width = 5, bool try_use_gpu = false, float match_conf = 0.3f, - int num_matches_thresh1 = 6, int num_matches_thresh2 = 6); - -protected: - // indicate that we do not want to hide the base class match method with a different signature - using BestOf2NearestMatcher::match; - void match(const std::vector &features, std::vector &pairwise_matches, - const cv::UMat &mask = cv::UMat()) CV_OVERRIDE; - - int range_width_; -}; - -/** @brief Features matcher similar to cv::detail::BestOf2NearestMatcher which -finds two best matches for each feature and leaves the best one only if the -ratio between descriptor distances is greater than the threshold match_conf. - -Unlike cv::detail::BestOf2NearestMatcher this matcher uses affine -transformation (affine transformation estimate will be placed in matches_info). - -@sa cv::detail::FeaturesMatcher cv::detail::BestOf2NearestMatcher - */ -class CV_EXPORTS_W AffineBestOf2NearestMatcher : public BestOf2NearestMatcher -{ -public: - /** @brief Constructs a "best of 2 nearest" matcher that expects affine transformation - between images - - @param full_affine whether to use full affine transformation with 6 degress of freedom or reduced - transformation with 4 degrees of freedom using only rotation, translation and uniform scaling - @param try_use_gpu Should try to use GPU or not - @param match_conf Match distances ration threshold - @param num_matches_thresh1 Minimum number of matches required for the 2D affine transform - estimation used in the inliers classification step - - @sa cv::estimateAffine2D cv::estimateAffinePartial2D - */ - CV_WRAP AffineBestOf2NearestMatcher(bool full_affine = false, bool try_use_gpu = false, - float match_conf = 0.3f, int num_matches_thresh1 = 6) : - BestOf2NearestMatcher(try_use_gpu, match_conf, num_matches_thresh1, num_matches_thresh1), - full_affine_(full_affine) {} - -protected: - void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; - - bool full_affine_; -}; - -//! @} stitching_match - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_MATCHERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_MATCHERS_HPP +#define OPENCV_STITCHING_MATCHERS_HPP + +#include "opencv2/core.hpp" +#include "opencv2/features2d.hpp" + +#include "opencv2/opencv_modules.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_match +//! @{ + +/** @brief Structure containing image keypoints and descriptors. */ +struct CV_EXPORTS_W_SIMPLE ImageFeatures +{ + CV_PROP_RW int img_idx; + CV_PROP_RW Size img_size; + CV_PROP_RW std::vector keypoints; + CV_PROP_RW UMat descriptors; + CV_WRAP std::vector getKeypoints() { return keypoints; } +}; +/** @brief + +@param featuresFinder +@param images +@param features +@param masks +*/ +CV_EXPORTS_W void computeImageFeatures( + const Ptr &featuresFinder, + InputArrayOfArrays images, + CV_OUT std::vector &features, + InputArrayOfArrays masks = noArray()); + +/** @brief + +@param featuresFinder +@param image +@param features +@param mask +*/ +CV_EXPORTS_AS(computeImageFeatures2) void computeImageFeatures( + const Ptr &featuresFinder, + InputArray image, + CV_OUT ImageFeatures &features, + InputArray mask = noArray()); + +/** @brief Structure containing information about matches between two images. + +It's assumed that there is a transformation between those images. Transformation may be +homography or affine transformation based on selected matcher. + +@sa detail::FeaturesMatcher +*/ +struct CV_EXPORTS_W_SIMPLE MatchesInfo +{ + MatchesInfo(); + MatchesInfo(const MatchesInfo &other); + MatchesInfo& operator =(const MatchesInfo &other); + + CV_PROP_RW int src_img_idx; + CV_PROP_RW int dst_img_idx; //!< Images indices (optional) + CV_PROP_RW std::vector matches; + CV_PROP_RW std::vector inliers_mask; //!< Geometrically consistent matches mask + CV_PROP_RW int num_inliers; //!< Number of geometrically consistent matches + CV_PROP_RW Mat H; //!< Estimated transformation + CV_PROP_RW double confidence; //!< Confidence two images are from the same panorama + CV_WRAP std::vector getMatches() { return matches; } + CV_WRAP std::vector getInliers() { return inliers_mask; } +}; + +/** @brief Feature matchers base class. */ +class CV_EXPORTS_W FeaturesMatcher +{ +public: + CV_WRAP virtual ~FeaturesMatcher() {} + + /** @overload + @param features1 First image features + @param features2 Second image features + @param matches_info Found matches + */ + CV_WRAP_AS(apply) void operator ()(const ImageFeatures &features1, const ImageFeatures &features2, + CV_OUT MatchesInfo& matches_info) { match(features1, features2, matches_info); } + + /** @brief Performs images matching. + + @param features Features of the source images + @param pairwise_matches Found pairwise matches + @param mask Mask indicating which image pairs must be matched + + The function is parallelized with the TBB library. + + @sa detail::MatchesInfo + */ + CV_WRAP_AS(apply2) void operator ()(const std::vector &features, CV_OUT std::vector &pairwise_matches, + const cv::UMat &mask = cv::UMat()) { match(features, pairwise_matches, mask); } + + /** @return True, if it's possible to use the same matcher instance in parallel, false otherwise + */ + CV_WRAP bool isThreadSafe() const { return is_thread_safe_; } + + /** @brief Frees unused memory allocated before if there is any. + */ + CV_WRAP virtual void collectGarbage() {} + +protected: + FeaturesMatcher(bool is_thread_safe = false) : is_thread_safe_(is_thread_safe) {} + + /** @brief This method must implement matching logic in order to make the wrappers + detail::FeaturesMatcher::operator()_ work. + + @param features1 first image features + @param features2 second image features + @param matches_info found matches + */ + virtual void match(const ImageFeatures &features1, const ImageFeatures &features2, + MatchesInfo& matches_info) = 0; + + /** @brief This method implements logic to match features between arbitrary number of features. + By default this checks every pair of inputs in the input, but the behaviour can be changed by subclasses. + + @param features vector of image features + @param pairwise_matches found matches + @param mask (optional) mask indicating which image pairs should be matched + */ + virtual void match(const std::vector &features, std::vector &pairwise_matches, + const cv::UMat &mask = cv::UMat()); + + bool is_thread_safe_; +}; + +/** @brief Features matcher which finds two best matches for each feature and leaves the best one only if the +ratio between descriptor distances is greater than the threshold match_conf + +@sa detail::FeaturesMatcher + */ +class CV_EXPORTS_W BestOf2NearestMatcher : public FeaturesMatcher +{ +public: + /** @brief Constructs a "best of 2 nearest" matcher. + + @param try_use_gpu Should try to use GPU or not + @param match_conf Match distances ration threshold + @param num_matches_thresh1 Minimum number of matches required for the 2D projective transform + estimation used in the inliers classification step + @param num_matches_thresh2 Minimum number of matches required for the 2D projective transform + re-estimation on inliers + @param matches_confindece_thresh Matching confidence threshold to take the match into account. + The threshold was determined experimentally and set to 3 by default. + */ + CV_WRAP BestOf2NearestMatcher(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, + int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); + + CV_WRAP void collectGarbage() CV_OVERRIDE; + CV_WRAP static Ptr create(bool try_use_gpu = false, float match_conf = 0.3f, int num_matches_thresh1 = 6, + int num_matches_thresh2 = 6, double matches_confindece_thresh = 3.); + +protected: + + void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; + int num_matches_thresh1_; + int num_matches_thresh2_; + double matches_confindece_thresh_; + Ptr impl_; +}; + +class CV_EXPORTS_W BestOf2NearestRangeMatcher : public BestOf2NearestMatcher +{ +public: + CV_WRAP BestOf2NearestRangeMatcher(int range_width = 5, bool try_use_gpu = false, float match_conf = 0.3f, + int num_matches_thresh1 = 6, int num_matches_thresh2 = 6); + +protected: + // indicate that we do not want to hide the base class match method with a different signature + using BestOf2NearestMatcher::match; + void match(const std::vector &features, std::vector &pairwise_matches, + const cv::UMat &mask = cv::UMat()) CV_OVERRIDE; + + int range_width_; +}; + +/** @brief Features matcher similar to cv::detail::BestOf2NearestMatcher which +finds two best matches for each feature and leaves the best one only if the +ratio between descriptor distances is greater than the threshold match_conf. + +Unlike cv::detail::BestOf2NearestMatcher this matcher uses affine +transformation (affine transformation estimate will be placed in matches_info). + +@sa cv::detail::FeaturesMatcher cv::detail::BestOf2NearestMatcher + */ +class CV_EXPORTS_W AffineBestOf2NearestMatcher : public BestOf2NearestMatcher +{ +public: + /** @brief Constructs a "best of 2 nearest" matcher that expects affine transformation + between images + + @param full_affine whether to use full affine transformation with 6 degress of freedom or reduced + transformation with 4 degrees of freedom using only rotation, translation and uniform scaling + @param try_use_gpu Should try to use GPU or not + @param match_conf Match distances ration threshold + @param num_matches_thresh1 Minimum number of matches required for the 2D affine transform + estimation used in the inliers classification step + + @sa cv::estimateAffine2D cv::estimateAffinePartial2D + */ + CV_WRAP AffineBestOf2NearestMatcher(bool full_affine = false, bool try_use_gpu = false, + float match_conf = 0.3f, int num_matches_thresh1 = 6) : + BestOf2NearestMatcher(try_use_gpu, match_conf, num_matches_thresh1, num_matches_thresh1), + full_affine_(full_affine) {} + +protected: + void match(const ImageFeatures &features1, const ImageFeatures &features2, MatchesInfo &matches_info) CV_OVERRIDE; + + bool full_affine_; +}; + +//! @} stitching_match + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_MATCHERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp index 00c61343a2..c03aa52090 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/motion_estimators.hpp @@ -1,373 +1,373 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_MOTION_ESTIMATORS_HPP -#define OPENCV_STITCHING_MOTION_ESTIMATORS_HPP - -#include "opencv2/core.hpp" -#include "matchers.hpp" -#include "util.hpp" -#include "camera.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_rotation -//! @{ - -/** @brief Rotation estimator base class. - -It takes features of all images, pairwise matches between all images and estimates rotations of all -cameras. - -@note The coordinate system origin is implementation-dependent, but you can always normalize the -rotations in respect to the first camera, for instance. : - */ -class CV_EXPORTS_W Estimator -{ -public: - virtual ~Estimator() {} - - /** @brief Estimates camera parameters. - - @param features Features of images - @param pairwise_matches Pairwise matches of images - @param cameras Estimated camera parameters - @return True in case of success, false otherwise - */ - CV_WRAP_AS(apply) bool operator ()(const std::vector &features, - const std::vector &pairwise_matches, - CV_OUT CV_IN_OUT std::vector &cameras) - { - return estimate(features, pairwise_matches, cameras); - } - -protected: - /** @brief This method must implement camera parameters estimation logic in order to make the wrapper - detail::Estimator::operator()_ work. - - @param features Features of images - @param pairwise_matches Pairwise matches of images - @param cameras Estimated camera parameters - @return True in case of success, false otherwise - */ - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - CV_OUT std::vector &cameras) = 0; -}; - -/** @brief Homography based rotation estimator. - */ -class CV_EXPORTS_W HomographyBasedEstimator : public Estimator -{ -public: - CV_WRAP HomographyBasedEstimator(bool is_focals_estimated = false) - : is_focals_estimated_(is_focals_estimated) {} - -private: - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &cameras) CV_OVERRIDE; - - bool is_focals_estimated_; -}; - -/** @brief Affine transformation based estimator. - -This estimator uses pairwise transformations estimated by matcher to estimate -final transformation for each camera. - -@sa cv::detail::HomographyBasedEstimator - */ -class CV_EXPORTS_W AffineBasedEstimator : public Estimator -{ -public: - CV_WRAP AffineBasedEstimator(){} -private: - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &cameras) CV_OVERRIDE; -}; - -/** @brief Base class for all camera parameters refinement methods. - */ -class CV_EXPORTS_W BundleAdjusterBase : public Estimator -{ -public: - CV_WRAP Mat refinementMask() const { return refinement_mask_.clone(); } - CV_WRAP void setRefinementMask(const Mat &mask) - { - CV_Assert(mask.type() == CV_8U && mask.size() == Size(3, 3)); - refinement_mask_ = mask.clone(); - } - - CV_WRAP double confThresh() const { return conf_thresh_; } - CV_WRAP void setConfThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } - - CV_WRAP TermCriteria termCriteria() { return term_criteria_; } - CV_WRAP void setTermCriteria(const TermCriteria& term_criteria) { term_criteria_ = term_criteria; } - -protected: - /** @brief Construct a bundle adjuster base instance. - - @param num_params_per_cam Number of parameters per camera - @param num_errs_per_measurement Number of error terms (components) per match - */ - BundleAdjusterBase(int num_params_per_cam, int num_errs_per_measurement) - : num_images_(0), total_num_matches_(0), - num_params_per_cam_(num_params_per_cam), - num_errs_per_measurement_(num_errs_per_measurement), - features_(0), pairwise_matches_(0), conf_thresh_(0) - { - setRefinementMask(Mat::ones(3, 3, CV_8U)); - setConfThresh(1.); - setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 1000, DBL_EPSILON)); - } - - // Runs bundle adjustment - virtual bool estimate(const std::vector &features, - const std::vector &pairwise_matches, - std::vector &cameras) CV_OVERRIDE; - - /** @brief Sets initial camera parameter to refine. - - @param cameras Camera parameters - */ - virtual void setUpInitialCameraParams(const std::vector &cameras) = 0; - /** @brief Gets the refined camera parameters. - - @param cameras Refined camera parameters - */ - virtual void obtainRefinedCameraParams(std::vector &cameras) const = 0; - /** @brief Calculates error vector. - - @param err Error column-vector of length total_num_matches \* num_errs_per_measurement - */ - virtual void calcError(Mat &err) = 0; - /** @brief Calculates the cost function jacobian. - - @param jac Jacobian matrix of dimensions - (total_num_matches \* num_errs_per_measurement) x (num_images \* num_params_per_cam) - */ - virtual void calcJacobian(Mat &jac) = 0; - - // 3x3 8U mask, where 0 means don't refine respective parameter, != 0 means refine - Mat refinement_mask_; - - int num_images_; - int total_num_matches_; - - int num_params_per_cam_; - int num_errs_per_measurement_; - - const ImageFeatures *features_; - const MatchesInfo *pairwise_matches_; - - // Threshold to filter out poorly matched image pairs - double conf_thresh_; - - //Levenberg-Marquardt algorithm termination criteria - TermCriteria term_criteria_; - - // Camera parameters matrix (CV_64F) - Mat cam_params_; - - // Connected images pairs - std::vector > edges_; -}; - - -/** @brief Stub bundle adjuster that does nothing. - */ -class CV_EXPORTS_W NoBundleAdjuster : public BundleAdjusterBase -{ -public: - CV_WRAP NoBundleAdjuster() : BundleAdjusterBase(0, 0) {} - -private: - bool estimate(const std::vector &, const std::vector &, - std::vector &) CV_OVERRIDE - { - return true; - } - void setUpInitialCameraParams(const std::vector &) CV_OVERRIDE {} - void obtainRefinedCameraParams(std::vector &) const CV_OVERRIDE {} - void calcError(Mat &) CV_OVERRIDE {} - void calcJacobian(Mat &) CV_OVERRIDE {} -}; - - -/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the reprojection -error squares - -It can estimate focal length, aspect ratio, principal point. -You can affect only on them via the refinement mask. - */ -class CV_EXPORTS_W BundleAdjusterReproj : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterReproj() : BundleAdjusterBase(7, 2) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the distances -between the rays passing through the camera center and a feature. : - -It can estimate focal length. It ignores the refinement mask for now. - */ -class CV_EXPORTS_W BundleAdjusterRay : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterRay() : BundleAdjusterBase(4, 3) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -/** @brief Bundle adjuster that expects affine transformation -represented in homogeneous coordinates in R for each camera param. Implements -camera parameters refinement algorithm which minimizes sum of the reprojection -error squares - -It estimates all transformation parameters. Refinement mask is ignored. - -@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffinePartial - */ -class CV_EXPORTS_W BundleAdjusterAffine : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterAffine() : BundleAdjusterBase(6, 2) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -/** @brief Bundle adjuster that expects affine transformation with 4 DOF -represented in homogeneous coordinates in R for each camera param. Implements -camera parameters refinement algorithm which minimizes sum of the reprojection -error squares - -It estimates all transformation parameters. Refinement mask is ignored. - -@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffine - */ -class CV_EXPORTS_W BundleAdjusterAffinePartial : public BundleAdjusterBase -{ -public: - CV_WRAP BundleAdjusterAffinePartial() : BundleAdjusterBase(4, 2) {} - -private: - void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; - void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; - void calcError(Mat &err) CV_OVERRIDE; - void calcJacobian(Mat &jac) CV_OVERRIDE; - - Mat err1_, err2_; -}; - - -enum WaveCorrectKind -{ - WAVE_CORRECT_HORIZ, - WAVE_CORRECT_VERT, - WAVE_CORRECT_AUTO -}; - -/** @brief Tries to detect the wave correction kind depending -on whether a panorama spans horizontally or vertically - -@param rmats Camera rotation matrices. -@return The correction kind to use for this panorama - */ -CV_EXPORTS -WaveCorrectKind autoDetectWaveCorrectKind(const std::vector &rmats); - -/** @brief Tries to make panorama more horizontal (or vertical). - -@param rmats Camera rotation matrices. -@param kind Correction kind, see detail::WaveCorrectKind. - */ -void CV_EXPORTS_W waveCorrect(CV_IN_OUT std::vector &rmats, WaveCorrectKind kind); - - -////////////////////////////////////////////////////////////////////////////// -// Auxiliary functions - -// Returns matches graph representation in DOT language -String CV_EXPORTS_W matchesGraphAsString(std::vector &paths, std::vector &pairwise_matches, - float conf_threshold); - -CV_EXPORTS_W std::vector leaveBiggestComponent( - std::vector &features, - std::vector &pairwise_matches, - float conf_threshold); - -void CV_EXPORTS findMaxSpanningTree( - int num_images, const std::vector &pairwise_matches, - Graph &span_tree, std::vector ¢ers); - -//! @} stitching_rotation - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_MOTION_ESTIMATORS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_MOTION_ESTIMATORS_HPP +#define OPENCV_STITCHING_MOTION_ESTIMATORS_HPP + +#include "opencv2/core.hpp" +#include "matchers.hpp" +#include "util.hpp" +#include "camera.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_rotation +//! @{ + +/** @brief Rotation estimator base class. + +It takes features of all images, pairwise matches between all images and estimates rotations of all +cameras. + +@note The coordinate system origin is implementation-dependent, but you can always normalize the +rotations in respect to the first camera, for instance. : + */ +class CV_EXPORTS_W Estimator +{ +public: + virtual ~Estimator() {} + + /** @brief Estimates camera parameters. + + @param features Features of images + @param pairwise_matches Pairwise matches of images + @param cameras Estimated camera parameters + @return True in case of success, false otherwise + */ + CV_WRAP_AS(apply) bool operator ()(const std::vector &features, + const std::vector &pairwise_matches, + CV_OUT CV_IN_OUT std::vector &cameras) + { + return estimate(features, pairwise_matches, cameras); + } + +protected: + /** @brief This method must implement camera parameters estimation logic in order to make the wrapper + detail::Estimator::operator()_ work. + + @param features Features of images + @param pairwise_matches Pairwise matches of images + @param cameras Estimated camera parameters + @return True in case of success, false otherwise + */ + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + CV_OUT std::vector &cameras) = 0; +}; + +/** @brief Homography based rotation estimator. + */ +class CV_EXPORTS_W HomographyBasedEstimator : public Estimator +{ +public: + CV_WRAP HomographyBasedEstimator(bool is_focals_estimated = false) + : is_focals_estimated_(is_focals_estimated) {} + +private: + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &cameras) CV_OVERRIDE; + + bool is_focals_estimated_; +}; + +/** @brief Affine transformation based estimator. + +This estimator uses pairwise transformations estimated by matcher to estimate +final transformation for each camera. + +@sa cv::detail::HomographyBasedEstimator + */ +class CV_EXPORTS_W AffineBasedEstimator : public Estimator +{ +public: + CV_WRAP AffineBasedEstimator(){} +private: + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &cameras) CV_OVERRIDE; +}; + +/** @brief Base class for all camera parameters refinement methods. + */ +class CV_EXPORTS_W BundleAdjusterBase : public Estimator +{ +public: + CV_WRAP Mat refinementMask() const { return refinement_mask_.clone(); } + CV_WRAP void setRefinementMask(const Mat &mask) + { + CV_Assert(mask.type() == CV_8U && mask.size() == Size(3, 3)); + refinement_mask_ = mask.clone(); + } + + CV_WRAP double confThresh() const { return conf_thresh_; } + CV_WRAP void setConfThresh(double conf_thresh) { conf_thresh_ = conf_thresh; } + + CV_WRAP TermCriteria termCriteria() { return term_criteria_; } + CV_WRAP void setTermCriteria(const TermCriteria& term_criteria) { term_criteria_ = term_criteria; } + +protected: + /** @brief Construct a bundle adjuster base instance. + + @param num_params_per_cam Number of parameters per camera + @param num_errs_per_measurement Number of error terms (components) per match + */ + BundleAdjusterBase(int num_params_per_cam, int num_errs_per_measurement) + : num_images_(0), total_num_matches_(0), + num_params_per_cam_(num_params_per_cam), + num_errs_per_measurement_(num_errs_per_measurement), + features_(0), pairwise_matches_(0), conf_thresh_(0) + { + setRefinementMask(Mat::ones(3, 3, CV_8U)); + setConfThresh(1.); + setTermCriteria(TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 1000, DBL_EPSILON)); + } + + // Runs bundle adjustment + virtual bool estimate(const std::vector &features, + const std::vector &pairwise_matches, + std::vector &cameras) CV_OVERRIDE; + + /** @brief Sets initial camera parameter to refine. + + @param cameras Camera parameters + */ + virtual void setUpInitialCameraParams(const std::vector &cameras) = 0; + /** @brief Gets the refined camera parameters. + + @param cameras Refined camera parameters + */ + virtual void obtainRefinedCameraParams(std::vector &cameras) const = 0; + /** @brief Calculates error vector. + + @param err Error column-vector of length total_num_matches \* num_errs_per_measurement + */ + virtual void calcError(Mat &err) = 0; + /** @brief Calculates the cost function jacobian. + + @param jac Jacobian matrix of dimensions + (total_num_matches \* num_errs_per_measurement) x (num_images \* num_params_per_cam) + */ + virtual void calcJacobian(Mat &jac) = 0; + + // 3x3 8U mask, where 0 means don't refine respective parameter, != 0 means refine + Mat refinement_mask_; + + int num_images_; + int total_num_matches_; + + int num_params_per_cam_; + int num_errs_per_measurement_; + + const ImageFeatures *features_; + const MatchesInfo *pairwise_matches_; + + // Threshold to filter out poorly matched image pairs + double conf_thresh_; + + //Levenberg-Marquardt algorithm termination criteria + TermCriteria term_criteria_; + + // Camera parameters matrix (CV_64F) + Mat cam_params_; + + // Connected images pairs + std::vector > edges_; +}; + + +/** @brief Stub bundle adjuster that does nothing. + */ +class CV_EXPORTS_W NoBundleAdjuster : public BundleAdjusterBase +{ +public: + CV_WRAP NoBundleAdjuster() : BundleAdjusterBase(0, 0) {} + +private: + bool estimate(const std::vector &, const std::vector &, + std::vector &) CV_OVERRIDE + { + return true; + } + void setUpInitialCameraParams(const std::vector &) CV_OVERRIDE {} + void obtainRefinedCameraParams(std::vector &) const CV_OVERRIDE {} + void calcError(Mat &) CV_OVERRIDE {} + void calcJacobian(Mat &) CV_OVERRIDE {} +}; + + +/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the reprojection +error squares + +It can estimate focal length, aspect ratio, principal point. +You can affect only on them via the refinement mask. + */ +class CV_EXPORTS_W BundleAdjusterReproj : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterReproj() : BundleAdjusterBase(7, 2) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +/** @brief Implementation of the camera parameters refinement algorithm which minimizes sum of the distances +between the rays passing through the camera center and a feature. : + +It can estimate focal length. It ignores the refinement mask for now. + */ +class CV_EXPORTS_W BundleAdjusterRay : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterRay() : BundleAdjusterBase(4, 3) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +/** @brief Bundle adjuster that expects affine transformation +represented in homogeneous coordinates in R for each camera param. Implements +camera parameters refinement algorithm which minimizes sum of the reprojection +error squares + +It estimates all transformation parameters. Refinement mask is ignored. + +@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffinePartial + */ +class CV_EXPORTS_W BundleAdjusterAffine : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterAffine() : BundleAdjusterBase(6, 2) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +/** @brief Bundle adjuster that expects affine transformation with 4 DOF +represented in homogeneous coordinates in R for each camera param. Implements +camera parameters refinement algorithm which minimizes sum of the reprojection +error squares + +It estimates all transformation parameters. Refinement mask is ignored. + +@sa AffineBasedEstimator AffineBestOf2NearestMatcher BundleAdjusterAffine + */ +class CV_EXPORTS_W BundleAdjusterAffinePartial : public BundleAdjusterBase +{ +public: + CV_WRAP BundleAdjusterAffinePartial() : BundleAdjusterBase(4, 2) {} + +private: + void setUpInitialCameraParams(const std::vector &cameras) CV_OVERRIDE; + void obtainRefinedCameraParams(std::vector &cameras) const CV_OVERRIDE; + void calcError(Mat &err) CV_OVERRIDE; + void calcJacobian(Mat &jac) CV_OVERRIDE; + + Mat err1_, err2_; +}; + + +enum WaveCorrectKind +{ + WAVE_CORRECT_HORIZ, + WAVE_CORRECT_VERT, + WAVE_CORRECT_AUTO +}; + +/** @brief Tries to detect the wave correction kind depending +on whether a panorama spans horizontally or vertically + +@param rmats Camera rotation matrices. +@return The correction kind to use for this panorama + */ +CV_EXPORTS +WaveCorrectKind autoDetectWaveCorrectKind(const std::vector &rmats); + +/** @brief Tries to make panorama more horizontal (or vertical). + +@param rmats Camera rotation matrices. +@param kind Correction kind, see detail::WaveCorrectKind. + */ +void CV_EXPORTS_W waveCorrect(CV_IN_OUT std::vector &rmats, WaveCorrectKind kind); + + +////////////////////////////////////////////////////////////////////////////// +// Auxiliary functions + +// Returns matches graph representation in DOT language +String CV_EXPORTS_W matchesGraphAsString(std::vector &paths, std::vector &pairwise_matches, + float conf_threshold); + +CV_EXPORTS_W std::vector leaveBiggestComponent( + std::vector &features, + std::vector &pairwise_matches, + float conf_threshold); + +void CV_EXPORTS findMaxSpanningTree( + int num_images, const std::vector &pairwise_matches, + Graph &span_tree, std::vector ¢ers); + +//! @} stitching_rotation + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_MOTION_ESTIMATORS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp index 1c13cce101..9ccfd14424 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/seam_finders.hpp @@ -1,291 +1,291 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_SEAM_FINDERS_HPP -#define OPENCV_STITCHING_SEAM_FINDERS_HPP - -#include -#include "opencv2/core.hpp" -#include "opencv2/opencv_modules.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_seam -//! @{ - -/** @brief Base class for a seam estimator. - */ -class CV_EXPORTS_W SeamFinder -{ -public: - CV_WRAP virtual ~SeamFinder() {} - enum { NO, VORONOI_SEAM, DP_SEAM }; - /** @brief Estimates seams. - - @param src Source images - @param corners Source image top-left corners - @param masks Source image masks to update - */ - CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) = 0; - CV_WRAP static Ptr createDefault(int type); -}; - -/** @brief Stub seam estimator which does nothing. - */ -class CV_EXPORTS_W NoSeamFinder : public SeamFinder -{ -public: - CV_WRAP void find(const std::vector&, const std::vector&, CV_IN_OUT std::vector&) CV_OVERRIDE {} -}; - -/** @brief Base class for all pairwise seam estimators. - */ -class CV_EXPORTS_W PairwiseSeamFinder : public SeamFinder -{ -public: - CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) CV_OVERRIDE; - -protected: - void run(); - /** @brief Resolves masks intersection of two specified images in the given ROI. - - @param first First image index - @param second Second image index - @param roi Region of interest - */ - virtual void findInPair(size_t first, size_t second, Rect roi) = 0; - - std::vector images_; - std::vector sizes_; - std::vector corners_; - std::vector masks_; -}; - -/** @brief Voronoi diagram-based seam estimator. - */ -class CV_EXPORTS_W VoronoiSeamFinder : public PairwiseSeamFinder -{ -public: - CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) CV_OVERRIDE; - virtual void find(const std::vector &size, const std::vector &corners, - std::vector &masks); -private: - void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; -}; - - -class CV_EXPORTS_W DpSeamFinder : public SeamFinder -{ -public: - enum CostFunction { COLOR, COLOR_GRAD }; - - DpSeamFinder(CostFunction costFunc = COLOR); - CV_WRAP DpSeamFinder(String costFunc ); - - CostFunction costFunction() const { return costFunc_; } - void setCostFunction(CostFunction val) { costFunc_ = val; } - CV_WRAP void setCostFunction(String val); - - virtual void find(const std::vector &src, const std::vector &corners, - std::vector &masks) CV_OVERRIDE; - -private: - enum ComponentState - { - FIRST = 1, SECOND = 2, INTERS = 4, - INTERS_FIRST = INTERS | FIRST, - INTERS_SECOND = INTERS | SECOND - }; - - class ImagePairLess - { - public: - ImagePairLess(const std::vector &images, const std::vector &corners) - : src_(&images[0]), corners_(&corners[0]) {} - - bool operator() (const std::pair &l, const std::pair &r) const - { - Point c1 = corners_[l.first] + Point(src_[l.first].cols / 2, src_[l.first].rows / 2); - Point c2 = corners_[l.second] + Point(src_[l.second].cols / 2, src_[l.second].rows / 2); - int d1 = (c1 - c2).dot(c1 - c2); - - c1 = corners_[r.first] + Point(src_[r.first].cols / 2, src_[r.first].rows / 2); - c2 = corners_[r.second] + Point(src_[r.second].cols / 2, src_[r.second].rows / 2); - int d2 = (c1 - c2).dot(c1 - c2); - - return d1 < d2; - } - - private: - const Mat *src_; - const Point *corners_; - }; - - class ClosePoints - { - public: - ClosePoints(int minDist) : minDist_(minDist) {} - - bool operator() (const Point &p1, const Point &p2) const - { - int dist2 = (p1.x-p2.x) * (p1.x-p2.x) + (p1.y-p2.y) * (p1.y-p2.y); - return dist2 < minDist_ * minDist_; - } - - private: - int minDist_; - }; - - void process( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); - - void findComponents(); - - void findEdges(); - - void resolveConflicts( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); - - void computeGradients(const Mat &image1, const Mat &image2); - - bool hasOnlyOneNeighbor(int comp); - - bool closeToContour(int y, int x, const Mat_ &contourMask); - - bool getSeamTips(int comp1, int comp2, Point &p1, Point &p2); - - void computeCosts( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, - int comp, Mat_ &costV, Mat_ &costH); - - bool estimateSeam( - const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp, - Point p1, Point p2, std::vector &seam, bool &isHorizontal); - - void updateLabelsUsingSeam( - int comp1, int comp2, const std::vector &seam, bool isHorizontalSeam); - - CostFunction costFunc_; - - // processing images pair data - Point unionTl_, unionBr_; - Size unionSize_; - Mat_ mask1_, mask2_; - Mat_ contour1mask_, contour2mask_; - Mat_ gradx1_, grady1_; - Mat_ gradx2_, grady2_; - - // components data - int ncomps_; - Mat_ labels_; - std::vector states_; - std::vector tls_, brs_; - std::vector > contours_; - std::set > edges_; -}; - -/** @brief Base class for all minimum graph-cut-based seam estimators. - */ -class CV_EXPORTS GraphCutSeamFinderBase -{ -public: - enum CostType { COST_COLOR, COST_COLOR_GRAD }; -}; - -/** @brief Minimum graph cut-based seam estimator. See details in @cite V03 . - */ -class CV_EXPORTS_W GraphCutSeamFinder : public GraphCutSeamFinderBase, public SeamFinder -{ -public: - GraphCutSeamFinder(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, - float bad_region_penalty = 1000.f); - CV_WRAP GraphCutSeamFinder(String cost_type,float terminal_cost = 10000.f, - float bad_region_penalty = 1000.f); - - ~GraphCutSeamFinder(); - - CV_WRAP void find(const std::vector &src, const std::vector &corners, - CV_IN_OUT std::vector &masks) CV_OVERRIDE; - -private: - // To avoid GCGraph dependency - class Impl; - Ptr impl_; -}; - - -#ifdef HAVE_OPENCV_CUDALEGACY -class CV_EXPORTS GraphCutSeamFinderGpu : public GraphCutSeamFinderBase, public PairwiseSeamFinder -{ -public: - GraphCutSeamFinderGpu(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, - float bad_region_penalty = 1000.f) - : cost_type_(cost_type), terminal_cost_(terminal_cost), - bad_region_penalty_(bad_region_penalty) {} - - void find(const std::vector &src, const std::vector &corners, - std::vector &masks) CV_OVERRIDE; - void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; - -private: - void setGraphWeightsColor(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &mask1, const cv::Mat &mask2, - cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); - void setGraphWeightsColorGrad(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &dx1, const cv::Mat &dx2, - const cv::Mat &dy1, const cv::Mat &dy2, const cv::Mat &mask1, const cv::Mat &mask2, - cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); - std::vector dx_, dy_; - int cost_type_; - float terminal_cost_; - float bad_region_penalty_; -}; -#endif - -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_SEAM_FINDERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_SEAM_FINDERS_HPP +#define OPENCV_STITCHING_SEAM_FINDERS_HPP + +#include +#include "opencv2/core.hpp" +#include "opencv2/opencv_modules.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_seam +//! @{ + +/** @brief Base class for a seam estimator. + */ +class CV_EXPORTS_W SeamFinder +{ +public: + CV_WRAP virtual ~SeamFinder() {} + enum { NO, VORONOI_SEAM, DP_SEAM }; + /** @brief Estimates seams. + + @param src Source images + @param corners Source image top-left corners + @param masks Source image masks to update + */ + CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) = 0; + CV_WRAP static Ptr createDefault(int type); +}; + +/** @brief Stub seam estimator which does nothing. + */ +class CV_EXPORTS_W NoSeamFinder : public SeamFinder +{ +public: + CV_WRAP void find(const std::vector&, const std::vector&, CV_IN_OUT std::vector&) CV_OVERRIDE {} +}; + +/** @brief Base class for all pairwise seam estimators. + */ +class CV_EXPORTS_W PairwiseSeamFinder : public SeamFinder +{ +public: + CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) CV_OVERRIDE; + +protected: + void run(); + /** @brief Resolves masks intersection of two specified images in the given ROI. + + @param first First image index + @param second Second image index + @param roi Region of interest + */ + virtual void findInPair(size_t first, size_t second, Rect roi) = 0; + + std::vector images_; + std::vector sizes_; + std::vector corners_; + std::vector masks_; +}; + +/** @brief Voronoi diagram-based seam estimator. + */ +class CV_EXPORTS_W VoronoiSeamFinder : public PairwiseSeamFinder +{ +public: + CV_WRAP virtual void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) CV_OVERRIDE; + virtual void find(const std::vector &size, const std::vector &corners, + std::vector &masks); +private: + void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; +}; + + +class CV_EXPORTS_W DpSeamFinder : public SeamFinder +{ +public: + enum CostFunction { COLOR, COLOR_GRAD }; + + DpSeamFinder(CostFunction costFunc = COLOR); + CV_WRAP DpSeamFinder(String costFunc ); + + CostFunction costFunction() const { return costFunc_; } + void setCostFunction(CostFunction val) { costFunc_ = val; } + CV_WRAP void setCostFunction(String val); + + virtual void find(const std::vector &src, const std::vector &corners, + std::vector &masks) CV_OVERRIDE; + +private: + enum ComponentState + { + FIRST = 1, SECOND = 2, INTERS = 4, + INTERS_FIRST = INTERS | FIRST, + INTERS_SECOND = INTERS | SECOND + }; + + class ImagePairLess + { + public: + ImagePairLess(const std::vector &images, const std::vector &corners) + : src_(&images[0]), corners_(&corners[0]) {} + + bool operator() (const std::pair &l, const std::pair &r) const + { + Point c1 = corners_[l.first] + Point(src_[l.first].cols / 2, src_[l.first].rows / 2); + Point c2 = corners_[l.second] + Point(src_[l.second].cols / 2, src_[l.second].rows / 2); + int d1 = (c1 - c2).dot(c1 - c2); + + c1 = corners_[r.first] + Point(src_[r.first].cols / 2, src_[r.first].rows / 2); + c2 = corners_[r.second] + Point(src_[r.second].cols / 2, src_[r.second].rows / 2); + int d2 = (c1 - c2).dot(c1 - c2); + + return d1 < d2; + } + + private: + const Mat *src_; + const Point *corners_; + }; + + class ClosePoints + { + public: + ClosePoints(int minDist) : minDist_(minDist) {} + + bool operator() (const Point &p1, const Point &p2) const + { + int dist2 = (p1.x-p2.x) * (p1.x-p2.x) + (p1.y-p2.y) * (p1.y-p2.y); + return dist2 < minDist_ * minDist_; + } + + private: + int minDist_; + }; + + void process( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); + + void findComponents(); + + void findEdges(); + + void resolveConflicts( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, Mat &mask1, Mat &mask2); + + void computeGradients(const Mat &image1, const Mat &image2); + + bool hasOnlyOneNeighbor(int comp); + + bool closeToContour(int y, int x, const Mat_ &contourMask); + + bool getSeamTips(int comp1, int comp2, Point &p1, Point &p2); + + void computeCosts( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, + int comp, Mat_ &costV, Mat_ &costH); + + bool estimateSeam( + const Mat &image1, const Mat &image2, Point tl1, Point tl2, int comp, + Point p1, Point p2, std::vector &seam, bool &isHorizontal); + + void updateLabelsUsingSeam( + int comp1, int comp2, const std::vector &seam, bool isHorizontalSeam); + + CostFunction costFunc_; + + // processing images pair data + Point unionTl_, unionBr_; + Size unionSize_; + Mat_ mask1_, mask2_; + Mat_ contour1mask_, contour2mask_; + Mat_ gradx1_, grady1_; + Mat_ gradx2_, grady2_; + + // components data + int ncomps_; + Mat_ labels_; + std::vector states_; + std::vector tls_, brs_; + std::vector > contours_; + std::set > edges_; +}; + +/** @brief Base class for all minimum graph-cut-based seam estimators. + */ +class CV_EXPORTS GraphCutSeamFinderBase +{ +public: + enum CostType { COST_COLOR, COST_COLOR_GRAD }; +}; + +/** @brief Minimum graph cut-based seam estimator. See details in @cite V03 . + */ +class CV_EXPORTS_W GraphCutSeamFinder : public GraphCutSeamFinderBase, public SeamFinder +{ +public: + GraphCutSeamFinder(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, + float bad_region_penalty = 1000.f); + CV_WRAP GraphCutSeamFinder(String cost_type,float terminal_cost = 10000.f, + float bad_region_penalty = 1000.f); + + ~GraphCutSeamFinder(); + + CV_WRAP void find(const std::vector &src, const std::vector &corners, + CV_IN_OUT std::vector &masks) CV_OVERRIDE; + +private: + // To avoid GCGraph dependency + class Impl; + Ptr impl_; +}; + + +#ifdef HAVE_OPENCV_CUDALEGACY +class CV_EXPORTS GraphCutSeamFinderGpu : public GraphCutSeamFinderBase, public PairwiseSeamFinder +{ +public: + GraphCutSeamFinderGpu(int cost_type = COST_COLOR_GRAD, float terminal_cost = 10000.f, + float bad_region_penalty = 1000.f) + : cost_type_(cost_type), terminal_cost_(terminal_cost), + bad_region_penalty_(bad_region_penalty) {} + + void find(const std::vector &src, const std::vector &corners, + std::vector &masks) CV_OVERRIDE; + void findInPair(size_t first, size_t second, Rect roi) CV_OVERRIDE; + +private: + void setGraphWeightsColor(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &mask1, const cv::Mat &mask2, + cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); + void setGraphWeightsColorGrad(const cv::Mat &img1, const cv::Mat &img2, const cv::Mat &dx1, const cv::Mat &dx2, + const cv::Mat &dy1, const cv::Mat &dy2, const cv::Mat &mask1, const cv::Mat &mask2, + cv::Mat &terminals, cv::Mat &leftT, cv::Mat &rightT, cv::Mat &top, cv::Mat &bottom); + std::vector dx_, dy_; + int cost_type_; + float terminal_cost_; + float bad_region_penalty_; +}; +#endif + +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_SEAM_FINDERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp index 479fe14802..f6f3da8a8d 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/timelapsers.hpp @@ -1,91 +1,91 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - - -#ifndef OPENCV_STITCHING_TIMELAPSERS_HPP -#define OPENCV_STITCHING_TIMELAPSERS_HPP - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching -//! @{ - -// Base Timelapser class, takes a sequence of images, applies appropriate shift, stores result in dst_. - -class CV_EXPORTS_W Timelapser -{ -public: - - enum {AS_IS, CROP}; - - virtual ~Timelapser() {} - - CV_WRAP static Ptr createDefault(int type); - - CV_WRAP virtual void initialize(const std::vector &corners, const std::vector &sizes); - CV_WRAP virtual void process(InputArray img, InputArray mask, Point tl); - CV_WRAP virtual const UMat& getDst() {return dst_;} - -protected: - - virtual bool test_point(Point pt); - - UMat dst_; - Rect dst_roi_; -}; - - -class CV_EXPORTS_W TimelapserCrop : public Timelapser -{ -public: - virtual void initialize(const std::vector &corners, const std::vector &sizes) CV_OVERRIDE; -}; - -//! @} - -} // namespace detail -} // namespace cv - -#endif // OPENCV_STITCHING_TIMELAPSERS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + + +#ifndef OPENCV_STITCHING_TIMELAPSERS_HPP +#define OPENCV_STITCHING_TIMELAPSERS_HPP + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching +//! @{ + +// Base Timelapser class, takes a sequence of images, applies appropriate shift, stores result in dst_. + +class CV_EXPORTS_W Timelapser +{ +public: + + enum {AS_IS, CROP}; + + virtual ~Timelapser() {} + + CV_WRAP static Ptr createDefault(int type); + + CV_WRAP virtual void initialize(const std::vector &corners, const std::vector &sizes); + CV_WRAP virtual void process(InputArray img, InputArray mask, Point tl); + CV_WRAP virtual const UMat& getDst() {return dst_;} + +protected: + + virtual bool test_point(Point pt); + + UMat dst_; + Rect dst_roi_; +}; + + +class CV_EXPORTS_W TimelapserCrop : public Timelapser +{ +public: + virtual void initialize(const std::vector &corners, const std::vector &sizes) CV_OVERRIDE; +}; + +//! @} + +} // namespace detail +} // namespace cv + +#endif // OPENCV_STITCHING_TIMELAPSERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp index 44b29d8513..bf7a39098c 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util.hpp @@ -1,121 +1,121 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_UTIL_HPP -#define OPENCV_STITCHING_UTIL_HPP - -#include -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching -//! @{ - -class CV_EXPORTS DisjointSets -{ -public: - DisjointSets(int elem_count = 0) { createOneElemSets(elem_count); } - - void createOneElemSets(int elem_count); - int findSetByElem(int elem); - int mergeSets(int set1, int set2); - - std::vector parent; - std::vector size; - -private: - std::vector rank_; -}; - - -struct CV_EXPORTS GraphEdge -{ - GraphEdge(int from, int to, float weight); - bool operator <(const GraphEdge& other) const { return weight < other.weight; } - bool operator >(const GraphEdge& other) const { return weight > other.weight; } - - int from, to; - float weight; -}; - -inline GraphEdge::GraphEdge(int _from, int _to, float _weight) : from(_from), to(_to), weight(_weight) {} - - -class CV_EXPORTS Graph -{ -public: - Graph(int num_vertices = 0) { create(num_vertices); } - void create(int num_vertices) { edges_.assign(num_vertices, std::list()); } - int numVertices() const { return static_cast(edges_.size()); } - void addEdge(int from, int to, float weight); - template B forEach(B body) const; - template B walkBreadthFirst(int from, B body) const; - -private: - std::vector< std::list > edges_; -}; - - -////////////////////////////////////////////////////////////////////////////// -// Auxiliary functions - -CV_EXPORTS_W bool overlapRoi(Point tl1, Point tl2, Size sz1, Size sz2, Rect &roi); -CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &images); -CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &sizes); -CV_EXPORTS_W Rect resultRoiIntersection(const std::vector &corners, const std::vector &sizes); -CV_EXPORTS_W Point resultTl(const std::vector &corners); - -// Returns random 'count' element subset of the {0,1,...,size-1} set -CV_EXPORTS_W void selectRandomSubset(int count, int size, std::vector &subset); - -CV_EXPORTS_W int& stitchingLogLevel(); - -//! @} - -} // namespace detail -} // namespace cv - -#include "util_inl.hpp" - -#endif // OPENCV_STITCHING_UTIL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_UTIL_HPP +#define OPENCV_STITCHING_UTIL_HPP + +#include +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching +//! @{ + +class CV_EXPORTS DisjointSets +{ +public: + DisjointSets(int elem_count = 0) { createOneElemSets(elem_count); } + + void createOneElemSets(int elem_count); + int findSetByElem(int elem); + int mergeSets(int set1, int set2); + + std::vector parent; + std::vector size; + +private: + std::vector rank_; +}; + + +struct CV_EXPORTS GraphEdge +{ + GraphEdge(int from, int to, float weight); + bool operator <(const GraphEdge& other) const { return weight < other.weight; } + bool operator >(const GraphEdge& other) const { return weight > other.weight; } + + int from, to; + float weight; +}; + +inline GraphEdge::GraphEdge(int _from, int _to, float _weight) : from(_from), to(_to), weight(_weight) {} + + +class CV_EXPORTS Graph +{ +public: + Graph(int num_vertices = 0) { create(num_vertices); } + void create(int num_vertices) { edges_.assign(num_vertices, std::list()); } + int numVertices() const { return static_cast(edges_.size()); } + void addEdge(int from, int to, float weight); + template B forEach(B body) const; + template B walkBreadthFirst(int from, B body) const; + +private: + std::vector< std::list > edges_; +}; + + +////////////////////////////////////////////////////////////////////////////// +// Auxiliary functions + +CV_EXPORTS_W bool overlapRoi(Point tl1, Point tl2, Size sz1, Size sz2, Rect &roi); +CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &images); +CV_EXPORTS_W Rect resultRoi(const std::vector &corners, const std::vector &sizes); +CV_EXPORTS_W Rect resultRoiIntersection(const std::vector &corners, const std::vector &sizes); +CV_EXPORTS_W Point resultTl(const std::vector &corners); + +// Returns random 'count' element subset of the {0,1,...,size-1} set +CV_EXPORTS_W void selectRandomSubset(int count, int size, std::vector &subset); + +CV_EXPORTS_W int& stitchingLogLevel(); + +//! @} + +} // namespace detail +} // namespace cv + +#include "util_inl.hpp" + +#endif // OPENCV_STITCHING_UTIL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp index a70bf1ad5e..dafab8b811 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/util_inl.hpp @@ -1,131 +1,131 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_UTIL_INL_HPP -#define OPENCV_STITCHING_UTIL_INL_HPP - -#include -#include "opencv2/core.hpp" -#include "util.hpp" // Make your IDE see declarations - -//! @cond IGNORED - -namespace cv { -namespace detail { - -template -B Graph::forEach(B body) const -{ - for (int i = 0; i < numVertices(); ++i) - { - std::list::const_iterator edge = edges_[i].begin(); - for (; edge != edges_[i].end(); ++edge) - body(*edge); - } - return body; -} - - -template -B Graph::walkBreadthFirst(int from, B body) const -{ - std::vector was(numVertices(), false); - std::queue vertices; - - was[from] = true; - vertices.push(from); - - while (!vertices.empty()) - { - int vertex = vertices.front(); - vertices.pop(); - - std::list::const_iterator edge = edges_[vertex].begin(); - for (; edge != edges_[vertex].end(); ++edge) - { - if (!was[edge->to]) - { - body(*edge); - was[edge->to] = true; - vertices.push(edge->to); - } - } - } - - return body; -} - - -////////////////////////////////////////////////////////////////////////////// -// Some auxiliary math functions - -static inline -float normL2(const Point3f& a) -{ - return a.x * a.x + a.y * a.y + a.z * a.z; -} - - -static inline -float normL2(const Point3f& a, const Point3f& b) -{ - return normL2(a - b); -} - - -static inline -double normL2sq(const Mat &r) -{ - return r.dot(r); -} - - -static inline int sqr(int x) { return x * x; } -static inline float sqr(float x) { return x * x; } -static inline double sqr(double x) { return x * x; } - -} // namespace detail -} // namespace cv - -//! @endcond - -#endif // OPENCV_STITCHING_UTIL_INL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_UTIL_INL_HPP +#define OPENCV_STITCHING_UTIL_INL_HPP + +#include +#include "opencv2/core.hpp" +#include "util.hpp" // Make your IDE see declarations + +//! @cond IGNORED + +namespace cv { +namespace detail { + +template +B Graph::forEach(B body) const +{ + for (int i = 0; i < numVertices(); ++i) + { + std::list::const_iterator edge = edges_[i].begin(); + for (; edge != edges_[i].end(); ++edge) + body(*edge); + } + return body; +} + + +template +B Graph::walkBreadthFirst(int from, B body) const +{ + std::vector was(numVertices(), false); + std::queue vertices; + + was[from] = true; + vertices.push(from); + + while (!vertices.empty()) + { + int vertex = vertices.front(); + vertices.pop(); + + std::list::const_iterator edge = edges_[vertex].begin(); + for (; edge != edges_[vertex].end(); ++edge) + { + if (!was[edge->to]) + { + body(*edge); + was[edge->to] = true; + vertices.push(edge->to); + } + } + } + + return body; +} + + +////////////////////////////////////////////////////////////////////////////// +// Some auxiliary math functions + +static inline +float normL2(const Point3f& a) +{ + return a.x * a.x + a.y * a.y + a.z * a.z; +} + + +static inline +float normL2(const Point3f& a, const Point3f& b) +{ + return normL2(a - b); +} + + +static inline +double normL2sq(const Mat &r) +{ + return r.dot(r); +} + + +static inline int sqr(int x) { return x * x; } +static inline float sqr(float x) { return x * x; } +static inline double sqr(double x) { return x * x; } + +} // namespace detail +} // namespace cv + +//! @endcond + +#endif // OPENCV_STITCHING_UTIL_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp index 7dd16871e7..d0d7869d45 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers.hpp @@ -1,706 +1,706 @@ - /*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_WARPERS_HPP -#define OPENCV_STITCHING_WARPERS_HPP - -#include "opencv2/core.hpp" -#include "opencv2/core/cuda.hpp" -#include "opencv2/imgproc.hpp" -#include "opencv2/opencv_modules.hpp" - -namespace cv { -namespace detail { - -//! @addtogroup stitching_warp -//! @{ - -/** @brief Rotation-only model image warper interface. - */ -class CV_EXPORTS RotationWarper -{ -public: - virtual ~RotationWarper() {} - - /** @brief Projects the image point. - - @param pt Source point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected point - */ - virtual Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) = 0; - - /** @brief Projects the image point backward. - - @param pt Projected point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Backward-projected point - */ -#if CV_VERSION_MAJOR == 4 - virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) - { - CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); - CV_Error(Error::StsNotImplemented, ""); - } -#else - virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) = 0; -#endif - - /** @brief Builds the projection maps according to the given camera data. - - @param src_size Source image size - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param xmap Projection map for the x axis - @param ymap Projection map for the y axis - @return Projected image minimum bounding box - */ - virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) = 0; - - /** @brief Projects the image. - - @param src Source image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst Projected image - @return Project image top-left corner - */ - virtual Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - CV_OUT OutputArray dst) = 0; - - /** @brief Projects the image backward. - - @param src Projected image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst_size Backward-projected image size - @param dst Backward-projected image - */ - virtual void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, CV_OUT OutputArray dst) = 0; - - /** - @param src_size Source image bounding box - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected image minimum bounding box - */ - virtual Rect warpRoi(Size src_size, InputArray K, InputArray R) = 0; - - virtual float getScale() const { return 1.f; } - virtual void setScale(float) {} -}; - -/** @brief Base class for warping logic implementation. - */ -struct CV_EXPORTS_W_SIMPLE ProjectorBase -{ - void setCameraParams(InputArray K = Mat::eye(3, 3, CV_32F), - InputArray R = Mat::eye(3, 3, CV_32F), - InputArray T = Mat::zeros(3, 1, CV_32F)); - - float scale; - float k[9]; - float rinv[9]; - float r_kinv[9]; - float k_rinv[9]; - float t[3]; -}; - -/** @brief Base class for rotation-based warper using a detail::ProjectorBase_ derived class. - */ -template -class CV_EXPORTS_TEMPLATE RotationWarperBase : public RotationWarper -{ -public: - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; - - Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; - - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE; - - void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, OutputArray dst) CV_OVERRIDE; - - Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; - - float getScale() const CV_OVERRIDE{ return projector_.scale; } - void setScale(float val) CV_OVERRIDE { projector_.scale = val; } - -protected: - - // Detects ROI of the destination image. It's correct for any projection. - virtual void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br); - - // Detects ROI of the destination image by walking over image border. - // Correctness for any projection isn't guaranteed. - void detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br); - - P projector_; -}; - - -struct CV_EXPORTS PlaneProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - -/** @brief Warper that maps an image onto the z = 1 plane. - */ -class CV_EXPORTS PlaneWarper : public RotationWarperBase -{ -public: - /** @brief Construct an instance of the plane warper class. - - @param scale Projected image scale multiplier - */ - PlaneWarper(float scale = 1.f) { projector_.scale = scale; } - - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R, InputArray T); - - Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) CV_OVERRIDE; - Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R, InputArray T); - - virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap); - Rect buildMaps(Size src_size, InputArray K, InputArray R, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap) CV_OVERRIDE; - - Point warp(InputArray src, InputArray K, InputArray R, - int interp_mode, int border_mode, CV_OUT OutputArray dst) CV_OVERRIDE; - virtual Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, - CV_OUT OutputArray dst); - - Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; - Rect warpRoi(Size src_size, InputArray K, InputArray R, InputArray T); - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; -}; - - -/** @brief Affine warper that uses rotations and translations - - Uses affine transformation in homogeneous coordinates to represent both rotation and - translation in camera rotation matrix. - */ -class CV_EXPORTS AffineWarper : public PlaneWarper -{ -public: - /** @brief Construct an instance of the affine warper class. - - @param scale Projected image scale multiplier - */ - AffineWarper(float scale = 1.f) : PlaneWarper(scale) {} - - /** @brief Projects the image point. - - @param pt Source point - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @return Projected point - */ - Point2f warpPoint(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; - - /** @brief Projects the image point backward. - - @param pt Projected point - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @return Backward-projected point - */ - Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; - - /** @brief Builds the projection maps according to the given camera data. - - @param src_size Source image size - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @param xmap Projection map for the x axis - @param ymap Projection map for the y axis - @return Projected image minimum bounding box - */ - Rect buildMaps(Size src_size, InputArray K, InputArray H, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - - /** @brief Projects the image. - - @param src Source image - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst Projected image - @return Project image top-left corner - */ - Point warp(InputArray src, InputArray K, InputArray H, - int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; - - /** - @param src_size Source image bounding box - @param K Camera intrinsic parameters - @param H Camera extrinsic parameters - @return Projected image minimum bounding box - */ - Rect warpRoi(Size src_size, InputArray K, InputArray H) CV_OVERRIDE; - -protected: - /** @brief Extracts rotation and translation matrices from matrix H representing - affine transformation in homogeneous coordinates - */ - void getRTfromHomogeneous(InputArray H, Mat &R, Mat &T); -}; - - -struct CV_EXPORTS_W_SIMPLE SphericalProjector : ProjectorBase -{ - CV_WRAP void mapForward(float x, float y, float &u, float &v); - CV_WRAP void mapBackward(float u, float v, float &x, float &y); -}; - - -/** @brief Warper that maps an image onto the unit sphere located at the origin. - - Projects image onto unit sphere with origin at (0, 0, 0) and radius scale, measured in pixels. - A 360 panorama would therefore have a resulting width of 2 * scale * PI pixels. - Poles are located at (0, -1, 0) and (0, 1, 0) points. -*/ -class CV_EXPORTS SphericalWarper : public RotationWarperBase -{ -public: - /** @brief Construct an instance of the spherical warper class. - - @param scale Radius of the projected sphere, in pixels. An image spanning the - whole sphere will have a width of 2 * scale * PI pixels. - */ - SphericalWarper(float scale) { projector_.scale = scale; } - - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; -}; - - -struct CV_EXPORTS CylindricalProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -/** @brief Warper that maps an image onto the x\*x + z\*z = 1 cylinder. - */ -class CV_EXPORTS CylindricalWarper : public RotationWarperBase -{ -public: - /** @brief Construct an instance of the cylindrical warper class. - - @param scale Projected image scale multiplier - */ - CylindricalWarper(float scale) { projector_.scale = scale; } - - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE - { - RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); - } -}; - - -struct CV_EXPORTS FisheyeProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS FisheyeWarper : public RotationWarperBase -{ -public: - FisheyeWarper(float scale) { projector_.scale = scale; } -}; - - -struct CV_EXPORTS StereographicProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS StereographicWarper : public RotationWarperBase -{ -public: - StereographicWarper(float scale) { projector_.scale = scale; } -}; - - -struct CV_EXPORTS CompressedRectilinearProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS CompressedRectilinearWarper : public RotationWarperBase -{ -public: - CompressedRectilinearWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } -}; - - -struct CV_EXPORTS CompressedRectilinearPortraitProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS CompressedRectilinearPortraitWarper : public RotationWarperBase -{ -public: - CompressedRectilinearPortraitWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } -}; - - -struct CV_EXPORTS PaniniProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS PaniniWarper : public RotationWarperBase -{ -public: - PaniniWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } -}; - - -struct CV_EXPORTS PaniniPortraitProjector : ProjectorBase -{ - float a, b; - - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS PaniniPortraitWarper : public RotationWarperBase -{ -public: - PaniniPortraitWarper(float scale, float A = 1, float B = 1) - { - projector_.a = A; - projector_.b = B; - projector_.scale = scale; - } - -}; - - -struct CV_EXPORTS MercatorProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS MercatorWarper : public RotationWarperBase -{ -public: - MercatorWarper(float scale) { projector_.scale = scale; } -}; - - -struct CV_EXPORTS TransverseMercatorProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS TransverseMercatorWarper : public RotationWarperBase -{ -public: - TransverseMercatorWarper(float scale) { projector_.scale = scale; } -}; - - -class CV_EXPORTS PlaneWarperGpu : public PlaneWarper -{ -public: - PlaneWarperGpu(float scale = 1.f) : PlaneWarper(scale) {} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, T, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, T, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, - cuda::GpuMat & dst); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, - cuda::GpuMat & dst); - -private: - cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; -}; - - -class CV_EXPORTS SphericalWarperGpu : public SphericalWarper -{ -public: - SphericalWarperGpu(float scale) : SphericalWarper(scale) {} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, - cuda::GpuMat & dst); - -private: - cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; -}; - - -class CV_EXPORTS CylindricalWarperGpu : public CylindricalWarper -{ -public: - CylindricalWarperGpu(float scale) : CylindricalWarper(scale) {} - -// WARNING: unreachable code using Ninja -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(push) -#pragma warning(disable: 4702) -#endif - Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE - { - Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); - d_xmap_.download(xmap); - d_ymap_.download(ymap); - return result; - } - - Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) CV_OVERRIDE - { - d_src_.upload(src); - Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); - d_dst_.download(dst); - return result; - } -#if defined _MSC_VER && _MSC_VER >= 1920 -#pragma warning(pop) -#endif - - Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); - - Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, - cuda::GpuMat & dst); - -private: - cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; -}; - - -struct CV_EXPORTS SphericalPortraitProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -// Projects image onto unit sphere with origin at (0, 0, 0). -// Poles are located NOT at (0, -1, 0) and (0, 1, 0) points, BUT at (1, 0, 0) and (-1, 0, 0) points. -class CV_EXPORTS SphericalPortraitWarper : public RotationWarperBase -{ -public: - SphericalPortraitWarper(float scale) { projector_.scale = scale; } - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; -}; - -struct CV_EXPORTS CylindricalPortraitProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS CylindricalPortraitWarper : public RotationWarperBase -{ -public: - CylindricalPortraitWarper(float scale) { projector_.scale = scale; } - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE - { - RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); - } -}; - -struct CV_EXPORTS PlanePortraitProjector : ProjectorBase -{ - void mapForward(float x, float y, float &u, float &v); - void mapBackward(float u, float v, float &x, float &y); -}; - - -class CV_EXPORTS PlanePortraitWarper : public RotationWarperBase -{ -public: - PlanePortraitWarper(float scale) { projector_.scale = scale; } - -protected: - void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE - { - RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); - } -}; - -//! @} stitching_warp - -} // namespace detail -} // namespace cv - -#include "warpers_inl.hpp" - -#endif // OPENCV_STITCHING_WARPERS_HPP + /*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_WARPERS_HPP +#define OPENCV_STITCHING_WARPERS_HPP + +#include "opencv2/core.hpp" +#include "opencv2/core/cuda.hpp" +#include "opencv2/imgproc.hpp" +#include "opencv2/opencv_modules.hpp" + +namespace cv { +namespace detail { + +//! @addtogroup stitching_warp +//! @{ + +/** @brief Rotation-only model image warper interface. + */ +class CV_EXPORTS RotationWarper +{ +public: + virtual ~RotationWarper() {} + + /** @brief Projects the image point. + + @param pt Source point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected point + */ + virtual Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) = 0; + + /** @brief Projects the image point backward. + + @param pt Projected point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Backward-projected point + */ +#if CV_VERSION_MAJOR == 4 + virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) + { + CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); + CV_Error(Error::StsNotImplemented, ""); + } +#else + virtual Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) = 0; +#endif + + /** @brief Builds the projection maps according to the given camera data. + + @param src_size Source image size + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param xmap Projection map for the x axis + @param ymap Projection map for the y axis + @return Projected image minimum bounding box + */ + virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) = 0; + + /** @brief Projects the image. + + @param src Source image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst Projected image + @return Project image top-left corner + */ + virtual Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + CV_OUT OutputArray dst) = 0; + + /** @brief Projects the image backward. + + @param src Projected image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst_size Backward-projected image size + @param dst Backward-projected image + */ + virtual void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, CV_OUT OutputArray dst) = 0; + + /** + @param src_size Source image bounding box + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected image minimum bounding box + */ + virtual Rect warpRoi(Size src_size, InputArray K, InputArray R) = 0; + + virtual float getScale() const { return 1.f; } + virtual void setScale(float) {} +}; + +/** @brief Base class for warping logic implementation. + */ +struct CV_EXPORTS_W_SIMPLE ProjectorBase +{ + void setCameraParams(InputArray K = Mat::eye(3, 3, CV_32F), + InputArray R = Mat::eye(3, 3, CV_32F), + InputArray T = Mat::zeros(3, 1, CV_32F)); + + float scale; + float k[9]; + float rinv[9]; + float r_kinv[9]; + float k_rinv[9]; + float t[3]; +}; + +/** @brief Base class for rotation-based warper using a detail::ProjectorBase_ derived class. + */ +template +class CV_EXPORTS_TEMPLATE RotationWarperBase : public RotationWarper +{ +public: + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; + + Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; + + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE; + + void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, OutputArray dst) CV_OVERRIDE; + + Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; + + float getScale() const CV_OVERRIDE{ return projector_.scale; } + void setScale(float val) CV_OVERRIDE { projector_.scale = val; } + +protected: + + // Detects ROI of the destination image. It's correct for any projection. + virtual void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br); + + // Detects ROI of the destination image by walking over image border. + // Correctness for any projection isn't guaranteed. + void detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br); + + P projector_; +}; + + +struct CV_EXPORTS PlaneProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + +/** @brief Warper that maps an image onto the z = 1 plane. + */ +class CV_EXPORTS PlaneWarper : public RotationWarperBase +{ +public: + /** @brief Construct an instance of the plane warper class. + + @param scale Projected image scale multiplier + */ + PlaneWarper(float scale = 1.f) { projector_.scale = scale; } + + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R) CV_OVERRIDE; + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R, InputArray T); + + Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) CV_OVERRIDE; + Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R, InputArray T); + + virtual Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap); + Rect buildMaps(Size src_size, InputArray K, InputArray R, CV_OUT OutputArray xmap, CV_OUT OutputArray ymap) CV_OVERRIDE; + + Point warp(InputArray src, InputArray K, InputArray R, + int interp_mode, int border_mode, CV_OUT OutputArray dst) CV_OVERRIDE; + virtual Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, + CV_OUT OutputArray dst); + + Rect warpRoi(Size src_size, InputArray K, InputArray R) CV_OVERRIDE; + Rect warpRoi(Size src_size, InputArray K, InputArray R, InputArray T); + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; +}; + + +/** @brief Affine warper that uses rotations and translations + + Uses affine transformation in homogeneous coordinates to represent both rotation and + translation in camera rotation matrix. + */ +class CV_EXPORTS AffineWarper : public PlaneWarper +{ +public: + /** @brief Construct an instance of the affine warper class. + + @param scale Projected image scale multiplier + */ + AffineWarper(float scale = 1.f) : PlaneWarper(scale) {} + + /** @brief Projects the image point. + + @param pt Source point + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @return Projected point + */ + Point2f warpPoint(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; + + /** @brief Projects the image point backward. + + @param pt Projected point + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @return Backward-projected point + */ + Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray H) CV_OVERRIDE; + + /** @brief Builds the projection maps according to the given camera data. + + @param src_size Source image size + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @param xmap Projection map for the x axis + @param ymap Projection map for the y axis + @return Projected image minimum bounding box + */ + Rect buildMaps(Size src_size, InputArray K, InputArray H, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + + /** @brief Projects the image. + + @param src Source image + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst Projected image + @return Project image top-left corner + */ + Point warp(InputArray src, InputArray K, InputArray H, + int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; + + /** + @param src_size Source image bounding box + @param K Camera intrinsic parameters + @param H Camera extrinsic parameters + @return Projected image minimum bounding box + */ + Rect warpRoi(Size src_size, InputArray K, InputArray H) CV_OVERRIDE; + +protected: + /** @brief Extracts rotation and translation matrices from matrix H representing + affine transformation in homogeneous coordinates + */ + void getRTfromHomogeneous(InputArray H, Mat &R, Mat &T); +}; + + +struct CV_EXPORTS_W_SIMPLE SphericalProjector : ProjectorBase +{ + CV_WRAP void mapForward(float x, float y, float &u, float &v); + CV_WRAP void mapBackward(float u, float v, float &x, float &y); +}; + + +/** @brief Warper that maps an image onto the unit sphere located at the origin. + + Projects image onto unit sphere with origin at (0, 0, 0) and radius scale, measured in pixels. + A 360 panorama would therefore have a resulting width of 2 * scale * PI pixels. + Poles are located at (0, -1, 0) and (0, 1, 0) points. +*/ +class CV_EXPORTS SphericalWarper : public RotationWarperBase +{ +public: + /** @brief Construct an instance of the spherical warper class. + + @param scale Radius of the projected sphere, in pixels. An image spanning the + whole sphere will have a width of 2 * scale * PI pixels. + */ + SphericalWarper(float scale) { projector_.scale = scale; } + + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; +}; + + +struct CV_EXPORTS CylindricalProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +/** @brief Warper that maps an image onto the x\*x + z\*z = 1 cylinder. + */ +class CV_EXPORTS CylindricalWarper : public RotationWarperBase +{ +public: + /** @brief Construct an instance of the cylindrical warper class. + + @param scale Projected image scale multiplier + */ + CylindricalWarper(float scale) { projector_.scale = scale; } + + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE; + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, OutputArray dst) CV_OVERRIDE; +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE + { + RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); + } +}; + + +struct CV_EXPORTS FisheyeProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS FisheyeWarper : public RotationWarperBase +{ +public: + FisheyeWarper(float scale) { projector_.scale = scale; } +}; + + +struct CV_EXPORTS StereographicProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS StereographicWarper : public RotationWarperBase +{ +public: + StereographicWarper(float scale) { projector_.scale = scale; } +}; + + +struct CV_EXPORTS CompressedRectilinearProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS CompressedRectilinearWarper : public RotationWarperBase +{ +public: + CompressedRectilinearWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } +}; + + +struct CV_EXPORTS CompressedRectilinearPortraitProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS CompressedRectilinearPortraitWarper : public RotationWarperBase +{ +public: + CompressedRectilinearPortraitWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } +}; + + +struct CV_EXPORTS PaniniProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS PaniniWarper : public RotationWarperBase +{ +public: + PaniniWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } +}; + + +struct CV_EXPORTS PaniniPortraitProjector : ProjectorBase +{ + float a, b; + + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS PaniniPortraitWarper : public RotationWarperBase +{ +public: + PaniniPortraitWarper(float scale, float A = 1, float B = 1) + { + projector_.a = A; + projector_.b = B; + projector_.scale = scale; + } + +}; + + +struct CV_EXPORTS MercatorProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS MercatorWarper : public RotationWarperBase +{ +public: + MercatorWarper(float scale) { projector_.scale = scale; } +}; + + +struct CV_EXPORTS TransverseMercatorProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS TransverseMercatorWarper : public RotationWarperBase +{ +public: + TransverseMercatorWarper(float scale) { projector_.scale = scale; } +}; + + +class CV_EXPORTS PlaneWarperGpu : public PlaneWarper +{ +public: + PlaneWarperGpu(float scale = 1.f) : PlaneWarper(scale) {} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, T, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, T, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Rect buildMaps(Size src_size, InputArray K, InputArray R, InputArray T, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, + cuda::GpuMat & dst); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, InputArray T, int interp_mode, int border_mode, + cuda::GpuMat & dst); + +private: + cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; +}; + + +class CV_EXPORTS SphericalWarperGpu : public SphericalWarper +{ +public: + SphericalWarperGpu(float scale) : SphericalWarper(scale) {} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, + cuda::GpuMat & dst); + +private: + cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; +}; + + +class CV_EXPORTS CylindricalWarperGpu : public CylindricalWarper +{ +public: + CylindricalWarperGpu(float scale) : CylindricalWarper(scale) {} + +// WARNING: unreachable code using Ninja +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(push) +#pragma warning(disable: 4702) +#endif + Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap) CV_OVERRIDE + { + Rect result = buildMaps(src_size, K, R, d_xmap_, d_ymap_); + d_xmap_.download(xmap); + d_ymap_.download(ymap); + return result; + } + + Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) CV_OVERRIDE + { + d_src_.upload(src); + Point result = warp(d_src_, K, R, interp_mode, border_mode, d_dst_); + d_dst_.download(dst); + return result; + } +#if defined _MSC_VER && _MSC_VER >= 1920 +#pragma warning(pop) +#endif + + Rect buildMaps(Size src_size, InputArray K, InputArray R, cuda::GpuMat & xmap, cuda::GpuMat & ymap); + + Point warp(const cuda::GpuMat & src, InputArray K, InputArray R, int interp_mode, int border_mode, + cuda::GpuMat & dst); + +private: + cuda::GpuMat d_xmap_, d_ymap_, d_src_, d_dst_; +}; + + +struct CV_EXPORTS SphericalPortraitProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +// Projects image onto unit sphere with origin at (0, 0, 0). +// Poles are located NOT at (0, -1, 0) and (0, 1, 0) points, BUT at (1, 0, 0) and (-1, 0, 0) points. +class CV_EXPORTS SphericalPortraitWarper : public RotationWarperBase +{ +public: + SphericalPortraitWarper(float scale) { projector_.scale = scale; } + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE; +}; + +struct CV_EXPORTS CylindricalPortraitProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS CylindricalPortraitWarper : public RotationWarperBase +{ +public: + CylindricalPortraitWarper(float scale) { projector_.scale = scale; } + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE + { + RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); + } +}; + +struct CV_EXPORTS PlanePortraitProjector : ProjectorBase +{ + void mapForward(float x, float y, float &u, float &v); + void mapBackward(float u, float v, float &x, float &y); +}; + + +class CV_EXPORTS PlanePortraitWarper : public RotationWarperBase +{ +public: + PlanePortraitWarper(float scale) { projector_.scale = scale; } + +protected: + void detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) CV_OVERRIDE + { + RotationWarperBase::detectResultRoiByBorder(src_size, dst_tl, dst_br); + } +}; + +//! @} stitching_warp + +} // namespace detail +} // namespace cv + +#include "warpers_inl.hpp" + +#endif // OPENCV_STITCHING_WARPERS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp index 00c122c6d5..72b5c08672 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/detail/warpers_inl.hpp @@ -1,782 +1,782 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_WARPERS_INL_HPP -#define OPENCV_STITCHING_WARPERS_INL_HPP - -#include "opencv2/core.hpp" -#include "warpers.hpp" // Make your IDE see declarations -#include - -//! @cond IGNORED - -namespace cv { -namespace detail { - -template -Point2f RotationWarperBase

::warpPoint(const Point2f &pt, InputArray K, InputArray R) -{ - projector_.setCameraParams(K, R); - Point2f uv; - projector_.mapForward(pt.x, pt.y, uv.x, uv.y); - return uv; -} - -template -Point2f RotationWarperBase

::warpPointBackward(const Point2f& pt, InputArray K, InputArray R) -{ - projector_.setCameraParams(K, R); - Point2f xy; - projector_.mapBackward(pt.x, pt.y, xy.x, xy.y); - return xy; -} - -template -Rect RotationWarperBase

::buildMaps(Size src_size, InputArray K, InputArray R, OutputArray _xmap, OutputArray _ymap) -{ - projector_.setCameraParams(K, R); - - Point dst_tl, dst_br; - detectResultRoi(src_size, dst_tl, dst_br); - - _xmap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); - _ymap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); - - Mat xmap = _xmap.getMat(), ymap = _ymap.getMat(); - - float x, y; - for (int v = dst_tl.y; v <= dst_br.y; ++v) - { - for (int u = dst_tl.x; u <= dst_br.x; ++u) - { - projector_.mapBackward(static_cast(u), static_cast(v), x, y); - xmap.at(v - dst_tl.y, u - dst_tl.x) = x; - ymap.at(v - dst_tl.y, u - dst_tl.x) = y; - } - } - - return Rect(dst_tl, dst_br); -} - - -template -Point RotationWarperBase

::warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - OutputArray dst) -{ - UMat xmap, ymap; - Rect dst_roi = buildMaps(src.size(), K, R, xmap, ymap); - - dst.create(dst_roi.height + 1, dst_roi.width + 1, src.type()); - remap(src, dst, xmap, ymap, interp_mode, border_mode); - - return dst_roi.tl(); -} - - -template -void RotationWarperBase

::warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, OutputArray dst) -{ - projector_.setCameraParams(K, R); - - Point src_tl, src_br; - detectResultRoi(dst_size, src_tl, src_br); - - Size size = src.size(); - CV_Assert(src_br.x - src_tl.x + 1 == size.width && src_br.y - src_tl.y + 1 == size.height); - - Mat xmap(dst_size, CV_32F); - Mat ymap(dst_size, CV_32F); - - float u, v; - for (int y = 0; y < dst_size.height; ++y) - { - for (int x = 0; x < dst_size.width; ++x) - { - projector_.mapForward(static_cast(x), static_cast(y), u, v); - xmap.at(y, x) = u - src_tl.x; - ymap.at(y, x) = v - src_tl.y; - } - } - - dst.create(dst_size, src.type()); - remap(src, dst, xmap, ymap, interp_mode, border_mode); -} - - -template -Rect RotationWarperBase

::warpRoi(Size src_size, InputArray K, InputArray R) -{ - projector_.setCameraParams(K, R); - - Point dst_tl, dst_br; - detectResultRoi(src_size, dst_tl, dst_br); - - return Rect(dst_tl, Point(dst_br.x + 1, dst_br.y + 1)); -} - - -template -void RotationWarperBase

::detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) -{ - float tl_uf = (std::numeric_limits::max)(); - float tl_vf = (std::numeric_limits::max)(); - float br_uf = -(std::numeric_limits::max)(); - float br_vf = -(std::numeric_limits::max)(); - - float u, v; - for (int y = 0; y < src_size.height; ++y) - { - for (int x = 0; x < src_size.width; ++x) - { - projector_.mapForward(static_cast(x), static_cast(y), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - } - } - - dst_tl.x = static_cast(tl_uf); - dst_tl.y = static_cast(tl_vf); - dst_br.x = static_cast(br_uf); - dst_br.y = static_cast(br_vf); -} - - -template -void RotationWarperBase

::detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br) -{ - float tl_uf = (std::numeric_limits::max)(); - float tl_vf = (std::numeric_limits::max)(); - float br_uf = -(std::numeric_limits::max)(); - float br_vf = -(std::numeric_limits::max)(); - - float u, v; - for (float x = 0; x < src_size.width; ++x) - { - projector_.mapForward(static_cast(x), 0, u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - - projector_.mapForward(static_cast(x), static_cast(src_size.height - 1), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - } - for (int y = 0; y < src_size.height; ++y) - { - projector_.mapForward(0, static_cast(y), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - - projector_.mapForward(static_cast(src_size.width - 1), static_cast(y), u, v); - tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); - br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); - } - - dst_tl.x = static_cast(tl_uf); - dst_tl.y = static_cast(tl_vf); - dst_br.x = static_cast(br_uf); - dst_br.y = static_cast(br_vf); -} - - -inline -void PlaneProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - x_ = t[0] + x_ / z_ * (1 - t[2]); - y_ = t[1] + y_ / z_ * (1 - t[2]); - - u = scale * x_; - v = scale * y_; -} - - -inline -void PlaneProjector::mapBackward(float u, float v, float &x, float &y) -{ - u = u / scale - t[0]; - v = v / scale - t[1]; - - float z; - x = k_rinv[0] * u + k_rinv[1] * v + k_rinv[2] * (1 - t[2]); - y = k_rinv[3] * u + k_rinv[4] * v + k_rinv[5] * (1 - t[2]); - z = k_rinv[6] * u + k_rinv[7] * v + k_rinv[8] * (1 - t[2]); - - x /= z; - y /= z; -} - - -inline -void SphericalProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - u = scale * atan2f(x_, z_); - float w = y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_); - v = scale * (static_cast(CV_PI) - acosf(w == w ? w : 0)); -} - - -inline -void SphericalProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float sinv = sinf(static_cast(CV_PI) - v); - float x_ = sinv * sinf(u); - float y_ = cosf(static_cast(CV_PI) - v); - float z_ = sinv * cosf(u); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - - -inline -void CylindricalProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - u = scale * atan2f(x_, z_); - v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); -} - - -inline -void CylindricalProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float x_ = sinf(u); - float y_ = v; - float z_ = cosf(u); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void FisheyeProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = scale * v_ * cosf(u_); - v = scale * v_ * sinf(u_); -} - -inline -void FisheyeProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float u_ = atan2f(v, u); - float v_ = sqrtf(u*u + v*v); - - float sinv = sinf((float)CV_PI - v_); - float x_ = sinv * sinf(u_); - float y_ = cosf((float)CV_PI - v_); - float z_ = sinv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void StereographicProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float r = sinf(v_) / (1 - cosf(v_)); - - u = scale * r * std::cos(u_); - v = scale * r * std::sin(u_); -} - -inline -void StereographicProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float u_ = atan2f(v, u); - float r = sqrtf(u*u + v*v); - float v_ = 2 * atanf(1.f / r); - - float sinv = sinf((float)CV_PI - v_); - float x_ = sinv * sinf(u_); - float y_ = cosf((float)CV_PI - v_); - float z_ = sinv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void CompressedRectilinearProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = scale * a * tanf(u_ / a); - v = scale * b * tanf(v_) / cosf(u_); -} - -inline -void CompressedRectilinearProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float aatg = a * atanf(u / a); - float u_ = aatg; - float v_ = atanf(v * cosf(aatg) / b); - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void CompressedRectilinearPortraitProjector::mapForward(float x, float y, float &u, float &v) -{ - float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = - scale * a * tanf(u_ / a); - v = scale * b * tanf(v_) / cosf(u_); -} - -inline -void CompressedRectilinearPortraitProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= - scale; - v /= scale; - - float aatg = a * atanf(u / a); - float u_ = aatg; - float v_ = atanf(v * cosf( aatg ) / b); - - float cosv = cosf(v_); - float y_ = cosv * sinf(u_); - float x_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void PaniniProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float tg = a * tanf(u_ / a); - u = scale * tg; - - float sinu = sinf(u_); - if ( fabs(sinu) < 1E-7 ) - v = scale * b * tanf(v_); - else - v = scale * b * tg * tanf(v_) / sinu; -} - -inline -void PaniniProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float lamda = a * atanf(u / a); - float u_ = lamda; - - float v_; - if ( fabs(lamda) > 1E-7) - v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda / a))); - else - v_ = atanf(v / b); - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void PaniniPortraitProjector::mapForward(float x, float y, float &u, float &v) -{ - float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float tg = a * tanf(u_ / a); - u = - scale * tg; - - float sinu = sinf( u_ ); - if ( fabs(sinu) < 1E-7 ) - v = scale * b * tanf(v_); - else - v = scale * b * tg * tanf(v_) / sinu; -} - -inline -void PaniniPortraitProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= - scale; - v /= scale; - - float lamda = a * atanf(u / a); - float u_ = lamda; - - float v_; - if ( fabs(lamda) > 1E-7) - v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda/a))); - else - v_ = atanf(v / b); - - float cosv = cosf(v_); - float y_ = cosv * sinf(u_); - float x_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void MercatorProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - u = scale * u_; - v = scale * logf( tanf( (float)(CV_PI/4) + v_/2 ) ); -} - -inline -void MercatorProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float v_ = atanf( sinhf(v) ); - float u_ = u; - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void TransverseMercatorProjector::mapForward(float x, float y, float &u, float &v) -{ - float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float u_ = atan2f(x_, z_); - float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); - - float B = cosf(v_) * sinf(u_); - - u = scale / 2 * logf( (1+B) / (1-B) ); - v = scale * atan2f(tanf(v_), cosf(u_)); -} - -inline -void TransverseMercatorProjector::mapBackward(float u, float v, float &x, float &y) -{ - u /= scale; - v /= scale; - - float v_ = asinf( sinf(v) / coshf(u) ); - float u_ = atan2f( sinhf(u), std::cos(v) ); - - float cosv = cosf(v_); - float x_ = cosv * sinf(u_); - float y_ = sinf(v_); - float z_ = cosv * cosf(u_); - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void SphericalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) -{ - float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float x_ = y0_; - float y_ = x0_; - float u, v; - - u = scale * atan2f(x_, z_); - v = scale * (static_cast(CV_PI) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))); - - u0 = -u;//v; - v0 = v;//u; -} - - -inline -void SphericalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) -{ - float u, v; - u = -u0;//v0; - v = v0;//u0; - - u /= scale; - v /= scale; - - float sinv = sinf(static_cast(CV_PI) - v); - float x0_ = sinv * sinf(u); - float y0_ = cosf(static_cast(CV_PI) - v); - float z_ = sinv * cosf(u); - - float x_ = y0_; - float y_ = x0_; - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void CylindricalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) -{ - float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float x_ = y0_; - float y_ = x0_; - float u, v; - - u = scale * atan2f(x_, z_); - v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); - - u0 = -u;//v; - v0 = v;//u; -} - - -inline -void CylindricalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) -{ - float u, v; - u = -u0;//v0; - v = v0;//u0; - - u /= scale; - v /= scale; - - float x0_ = sinf(u); - float y0_ = v; - float z_ = cosf(u); - - float x_ = y0_; - float y_ = x0_; - - float z; - x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; - y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; - z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; - - if (z > 0) { x /= z; y /= z; } - else x = y = -1; -} - -inline -void PlanePortraitProjector::mapForward(float x, float y, float &u0, float &v0) -{ - float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; - float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; - float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; - - float x_ = y0_; - float y_ = x0_; - - x_ = t[0] + x_ / z_ * (1 - t[2]); - y_ = t[1] + y_ / z_ * (1 - t[2]); - - float u,v; - u = scale * x_; - v = scale * y_; - - u0 = -u; - v0 = v; -} - - -inline -void PlanePortraitProjector::mapBackward(float u0, float v0, float &x, float &y) -{ - float u, v; - u = -u0; - v = v0; - - u = u / scale - t[0]; - v = v / scale - t[1]; - - float z; - x = k_rinv[0] * v + k_rinv[1] * u + k_rinv[2] * (1 - t[2]); - y = k_rinv[3] * v + k_rinv[4] * u + k_rinv[5] * (1 - t[2]); - z = k_rinv[6] * v + k_rinv[7] * u + k_rinv[8] * (1 - t[2]); - - x /= z; - y /= z; -} - - -} // namespace detail -} // namespace cv - -//! @endcond - -#endif // OPENCV_STITCHING_WARPERS_INL_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_WARPERS_INL_HPP +#define OPENCV_STITCHING_WARPERS_INL_HPP + +#include "opencv2/core.hpp" +#include "warpers.hpp" // Make your IDE see declarations +#include + +//! @cond IGNORED + +namespace cv { +namespace detail { + +template +Point2f RotationWarperBase

::warpPoint(const Point2f &pt, InputArray K, InputArray R) +{ + projector_.setCameraParams(K, R); + Point2f uv; + projector_.mapForward(pt.x, pt.y, uv.x, uv.y); + return uv; +} + +template +Point2f RotationWarperBase

::warpPointBackward(const Point2f& pt, InputArray K, InputArray R) +{ + projector_.setCameraParams(K, R); + Point2f xy; + projector_.mapBackward(pt.x, pt.y, xy.x, xy.y); + return xy; +} + +template +Rect RotationWarperBase

::buildMaps(Size src_size, InputArray K, InputArray R, OutputArray _xmap, OutputArray _ymap) +{ + projector_.setCameraParams(K, R); + + Point dst_tl, dst_br; + detectResultRoi(src_size, dst_tl, dst_br); + + _xmap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); + _ymap.create(dst_br.y - dst_tl.y + 1, dst_br.x - dst_tl.x + 1, CV_32F); + + Mat xmap = _xmap.getMat(), ymap = _ymap.getMat(); + + float x, y; + for (int v = dst_tl.y; v <= dst_br.y; ++v) + { + for (int u = dst_tl.x; u <= dst_br.x; ++u) + { + projector_.mapBackward(static_cast(u), static_cast(v), x, y); + xmap.at(v - dst_tl.y, u - dst_tl.x) = x; + ymap.at(v - dst_tl.y, u - dst_tl.x) = y; + } + } + + return Rect(dst_tl, dst_br); +} + + +template +Point RotationWarperBase

::warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + OutputArray dst) +{ + UMat xmap, ymap; + Rect dst_roi = buildMaps(src.size(), K, R, xmap, ymap); + + dst.create(dst_roi.height + 1, dst_roi.width + 1, src.type()); + remap(src, dst, xmap, ymap, interp_mode, border_mode); + + return dst_roi.tl(); +} + + +template +void RotationWarperBase

::warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, OutputArray dst) +{ + projector_.setCameraParams(K, R); + + Point src_tl, src_br; + detectResultRoi(dst_size, src_tl, src_br); + + Size size = src.size(); + CV_Assert(src_br.x - src_tl.x + 1 == size.width && src_br.y - src_tl.y + 1 == size.height); + + Mat xmap(dst_size, CV_32F); + Mat ymap(dst_size, CV_32F); + + float u, v; + for (int y = 0; y < dst_size.height; ++y) + { + for (int x = 0; x < dst_size.width; ++x) + { + projector_.mapForward(static_cast(x), static_cast(y), u, v); + xmap.at(y, x) = u - src_tl.x; + ymap.at(y, x) = v - src_tl.y; + } + } + + dst.create(dst_size, src.type()); + remap(src, dst, xmap, ymap, interp_mode, border_mode); +} + + +template +Rect RotationWarperBase

::warpRoi(Size src_size, InputArray K, InputArray R) +{ + projector_.setCameraParams(K, R); + + Point dst_tl, dst_br; + detectResultRoi(src_size, dst_tl, dst_br); + + return Rect(dst_tl, Point(dst_br.x + 1, dst_br.y + 1)); +} + + +template +void RotationWarperBase

::detectResultRoi(Size src_size, Point &dst_tl, Point &dst_br) +{ + float tl_uf = (std::numeric_limits::max)(); + float tl_vf = (std::numeric_limits::max)(); + float br_uf = -(std::numeric_limits::max)(); + float br_vf = -(std::numeric_limits::max)(); + + float u, v; + for (int y = 0; y < src_size.height; ++y) + { + for (int x = 0; x < src_size.width; ++x) + { + projector_.mapForward(static_cast(x), static_cast(y), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + } + } + + dst_tl.x = static_cast(tl_uf); + dst_tl.y = static_cast(tl_vf); + dst_br.x = static_cast(br_uf); + dst_br.y = static_cast(br_vf); +} + + +template +void RotationWarperBase

::detectResultRoiByBorder(Size src_size, Point &dst_tl, Point &dst_br) +{ + float tl_uf = (std::numeric_limits::max)(); + float tl_vf = (std::numeric_limits::max)(); + float br_uf = -(std::numeric_limits::max)(); + float br_vf = -(std::numeric_limits::max)(); + + float u, v; + for (float x = 0; x < src_size.width; ++x) + { + projector_.mapForward(static_cast(x), 0, u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + + projector_.mapForward(static_cast(x), static_cast(src_size.height - 1), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + } + for (int y = 0; y < src_size.height; ++y) + { + projector_.mapForward(0, static_cast(y), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + + projector_.mapForward(static_cast(src_size.width - 1), static_cast(y), u, v); + tl_uf = (std::min)(tl_uf, u); tl_vf = (std::min)(tl_vf, v); + br_uf = (std::max)(br_uf, u); br_vf = (std::max)(br_vf, v); + } + + dst_tl.x = static_cast(tl_uf); + dst_tl.y = static_cast(tl_vf); + dst_br.x = static_cast(br_uf); + dst_br.y = static_cast(br_vf); +} + + +inline +void PlaneProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + x_ = t[0] + x_ / z_ * (1 - t[2]); + y_ = t[1] + y_ / z_ * (1 - t[2]); + + u = scale * x_; + v = scale * y_; +} + + +inline +void PlaneProjector::mapBackward(float u, float v, float &x, float &y) +{ + u = u / scale - t[0]; + v = v / scale - t[1]; + + float z; + x = k_rinv[0] * u + k_rinv[1] * v + k_rinv[2] * (1 - t[2]); + y = k_rinv[3] * u + k_rinv[4] * v + k_rinv[5] * (1 - t[2]); + z = k_rinv[6] * u + k_rinv[7] * v + k_rinv[8] * (1 - t[2]); + + x /= z; + y /= z; +} + + +inline +void SphericalProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + u = scale * atan2f(x_, z_); + float w = y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_); + v = scale * (static_cast(CV_PI) - acosf(w == w ? w : 0)); +} + + +inline +void SphericalProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float sinv = sinf(static_cast(CV_PI) - v); + float x_ = sinv * sinf(u); + float y_ = cosf(static_cast(CV_PI) - v); + float z_ = sinv * cosf(u); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + + +inline +void CylindricalProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + u = scale * atan2f(x_, z_); + v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); +} + + +inline +void CylindricalProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float x_ = sinf(u); + float y_ = v; + float z_ = cosf(u); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void FisheyeProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = scale * v_ * cosf(u_); + v = scale * v_ * sinf(u_); +} + +inline +void FisheyeProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float u_ = atan2f(v, u); + float v_ = sqrtf(u*u + v*v); + + float sinv = sinf((float)CV_PI - v_); + float x_ = sinv * sinf(u_); + float y_ = cosf((float)CV_PI - v_); + float z_ = sinv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void StereographicProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = (float)CV_PI - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float r = sinf(v_) / (1 - cosf(v_)); + + u = scale * r * std::cos(u_); + v = scale * r * std::sin(u_); +} + +inline +void StereographicProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float u_ = atan2f(v, u); + float r = sqrtf(u*u + v*v); + float v_ = 2 * atanf(1.f / r); + + float sinv = sinf((float)CV_PI - v_); + float x_ = sinv * sinf(u_); + float y_ = cosf((float)CV_PI - v_); + float z_ = sinv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void CompressedRectilinearProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = scale * a * tanf(u_ / a); + v = scale * b * tanf(v_) / cosf(u_); +} + +inline +void CompressedRectilinearProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float aatg = a * atanf(u / a); + float u_ = aatg; + float v_ = atanf(v * cosf(aatg) / b); + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void CompressedRectilinearPortraitProjector::mapForward(float x, float y, float &u, float &v) +{ + float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = - scale * a * tanf(u_ / a); + v = scale * b * tanf(v_) / cosf(u_); +} + +inline +void CompressedRectilinearPortraitProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= - scale; + v /= scale; + + float aatg = a * atanf(u / a); + float u_ = aatg; + float v_ = atanf(v * cosf( aatg ) / b); + + float cosv = cosf(v_); + float y_ = cosv * sinf(u_); + float x_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void PaniniProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float tg = a * tanf(u_ / a); + u = scale * tg; + + float sinu = sinf(u_); + if ( fabs(sinu) < 1E-7 ) + v = scale * b * tanf(v_); + else + v = scale * b * tg * tanf(v_) / sinu; +} + +inline +void PaniniProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float lamda = a * atanf(u / a); + float u_ = lamda; + + float v_; + if ( fabs(lamda) > 1E-7) + v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda / a))); + else + v_ = atanf(v / b); + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void PaniniPortraitProjector::mapForward(float x, float y, float &u, float &v) +{ + float y_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float x_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float tg = a * tanf(u_ / a); + u = - scale * tg; + + float sinu = sinf( u_ ); + if ( fabs(sinu) < 1E-7 ) + v = scale * b * tanf(v_); + else + v = scale * b * tg * tanf(v_) / sinu; +} + +inline +void PaniniPortraitProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= - scale; + v /= scale; + + float lamda = a * atanf(u / a); + float u_ = lamda; + + float v_; + if ( fabs(lamda) > 1E-7) + v_ = atanf(v * sinf(lamda) / (b * a * tanf(lamda/a))); + else + v_ = atanf(v / b); + + float cosv = cosf(v_); + float y_ = cosv * sinf(u_); + float x_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void MercatorProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + u = scale * u_; + v = scale * logf( tanf( (float)(CV_PI/4) + v_/2 ) ); +} + +inline +void MercatorProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float v_ = atanf( sinhf(v) ); + float u_ = u; + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void TransverseMercatorProjector::mapForward(float x, float y, float &u, float &v) +{ + float x_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float u_ = atan2f(x_, z_); + float v_ = asinf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_)); + + float B = cosf(v_) * sinf(u_); + + u = scale / 2 * logf( (1+B) / (1-B) ); + v = scale * atan2f(tanf(v_), cosf(u_)); +} + +inline +void TransverseMercatorProjector::mapBackward(float u, float v, float &x, float &y) +{ + u /= scale; + v /= scale; + + float v_ = asinf( sinf(v) / coshf(u) ); + float u_ = atan2f( sinhf(u), std::cos(v) ); + + float cosv = cosf(v_); + float x_ = cosv * sinf(u_); + float y_ = sinf(v_); + float z_ = cosv * cosf(u_); + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void SphericalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) +{ + float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float x_ = y0_; + float y_ = x0_; + float u, v; + + u = scale * atan2f(x_, z_); + v = scale * (static_cast(CV_PI) - acosf(y_ / sqrtf(x_ * x_ + y_ * y_ + z_ * z_))); + + u0 = -u;//v; + v0 = v;//u; +} + + +inline +void SphericalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) +{ + float u, v; + u = -u0;//v0; + v = v0;//u0; + + u /= scale; + v /= scale; + + float sinv = sinf(static_cast(CV_PI) - v); + float x0_ = sinv * sinf(u); + float y0_ = cosf(static_cast(CV_PI) - v); + float z_ = sinv * cosf(u); + + float x_ = y0_; + float y_ = x0_; + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void CylindricalPortraitProjector::mapForward(float x, float y, float &u0, float &v0) +{ + float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float x_ = y0_; + float y_ = x0_; + float u, v; + + u = scale * atan2f(x_, z_); + v = scale * y_ / sqrtf(x_ * x_ + z_ * z_); + + u0 = -u;//v; + v0 = v;//u; +} + + +inline +void CylindricalPortraitProjector::mapBackward(float u0, float v0, float &x, float &y) +{ + float u, v; + u = -u0;//v0; + v = v0;//u0; + + u /= scale; + v /= scale; + + float x0_ = sinf(u); + float y0_ = v; + float z_ = cosf(u); + + float x_ = y0_; + float y_ = x0_; + + float z; + x = k_rinv[0] * x_ + k_rinv[1] * y_ + k_rinv[2] * z_; + y = k_rinv[3] * x_ + k_rinv[4] * y_ + k_rinv[5] * z_; + z = k_rinv[6] * x_ + k_rinv[7] * y_ + k_rinv[8] * z_; + + if (z > 0) { x /= z; y /= z; } + else x = y = -1; +} + +inline +void PlanePortraitProjector::mapForward(float x, float y, float &u0, float &v0) +{ + float x0_ = r_kinv[0] * x + r_kinv[1] * y + r_kinv[2]; + float y0_ = r_kinv[3] * x + r_kinv[4] * y + r_kinv[5]; + float z_ = r_kinv[6] * x + r_kinv[7] * y + r_kinv[8]; + + float x_ = y0_; + float y_ = x0_; + + x_ = t[0] + x_ / z_ * (1 - t[2]); + y_ = t[1] + y_ / z_ * (1 - t[2]); + + float u,v; + u = scale * x_; + v = scale * y_; + + u0 = -u; + v0 = v; +} + + +inline +void PlanePortraitProjector::mapBackward(float u0, float v0, float &x, float &y) +{ + float u, v; + u = -u0; + v = v0; + + u = u / scale - t[0]; + v = v / scale - t[1]; + + float z; + x = k_rinv[0] * v + k_rinv[1] * u + k_rinv[2] * (1 - t[2]); + y = k_rinv[3] * v + k_rinv[4] * u + k_rinv[5] * (1 - t[2]); + z = k_rinv[6] * v + k_rinv[7] * u + k_rinv[8] * (1 - t[2]); + + x /= z; + y /= z; +} + + +} // namespace detail +} // namespace cv + +//! @endcond + +#endif // OPENCV_STITCHING_WARPERS_INL_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp b/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp index 34ef44e8f1..0a5bf63de2 100644 --- a/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/stitching/warpers.hpp @@ -1,277 +1,277 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_STITCHING_WARPER_CREATORS_HPP -#define OPENCV_STITCHING_WARPER_CREATORS_HPP - -#include "opencv2/stitching/detail/warpers.hpp" -#include - -namespace cv { - class CV_EXPORTS_W PyRotationWarper - { - Ptr rw; - - public: - CV_WRAP PyRotationWarper(String type, float scale); - CV_WRAP PyRotationWarper() {} - ~PyRotationWarper() {} - - /** @brief Projects the image point. - - @param pt Source point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected point - */ - CV_WRAP Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R); - - /** @brief Projects the image point backward. - - @param pt Projected point - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Backward-projected point - */ -#if CV_VERSION_MAJOR == 4 - CV_WRAP Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) - { - CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); - CV_Error(Error::StsNotImplemented, ""); - } -#else - CV_WRAP Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R); -#endif - /** @brief Builds the projection maps according to the given camera data. - - @param src_size Source image size - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param xmap Projection map for the x axis - @param ymap Projection map for the y axis - @return Projected image minimum bounding box - */ - CV_WRAP Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap); - - /** @brief Projects the image. - - @param src Source image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst Projected image - @return Project image top-left corner - */ - CV_WRAP Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - CV_OUT OutputArray dst); - - /** @brief Projects the image backward. - - @param src Projected image - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @param interp_mode Interpolation mode - @param border_mode Border extrapolation mode - @param dst_size Backward-projected image size - @param dst Backward-projected image - */ - CV_WRAP void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, - Size dst_size, CV_OUT OutputArray dst); - - /** - @param src_size Source image bounding box - @param K Camera intrinsic parameters - @param R Camera rotation matrix - @return Projected image minimum bounding box - */ - CV_WRAP Rect warpRoi(Size src_size, InputArray K, InputArray R); - - CV_WRAP float getScale() const { return 1.f; } - CV_WRAP void setScale(float) {} - }; - -//! @addtogroup stitching_warp -//! @{ - -/** @brief Image warper factories base class. - */ - -class CV_EXPORTS_W WarperCreator -{ -public: - CV_WRAP virtual ~WarperCreator() {} - virtual Ptr create(float scale) const = 0; -}; - - -/** @brief Plane warper factory class. - @sa detail::PlaneWarper - */ -class CV_EXPORTS PlaneWarper : public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -/** @brief Affine warper factory class. - @sa detail::AffineWarper - */ -class CV_EXPORTS AffineWarper : public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -/** @brief Cylindrical warper factory class. -@sa detail::CylindricalWarper -*/ -class CV_EXPORTS CylindricalWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -/** @brief Spherical warper factory class */ -class CV_EXPORTS SphericalWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS FisheyeWarper : public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS StereographicWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS CompressedRectilinearWarper: public WarperCreator -{ - float a, b; -public: - CompressedRectilinearWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS CompressedRectilinearPortraitWarper: public WarperCreator -{ - float a, b; -public: - CompressedRectilinearPortraitWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS PaniniWarper: public WarperCreator -{ - float a, b; -public: - PaniniWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS PaniniPortraitWarper: public WarperCreator -{ - float a, b; -public: - PaniniPortraitWarper(float A = 1, float B = 1) - { - a = A; b = B; - } - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } -}; - -class CV_EXPORTS MercatorWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - -class CV_EXPORTS TransverseMercatorWarper: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - - - -#ifdef HAVE_OPENCV_CUDAWARPING -class PlaneWarperGpu: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - - -class CylindricalWarperGpu: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; - - -class SphericalWarperGpu: public WarperCreator -{ -public: - Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } -}; -#endif - -//! @} stitching_warp - -} // namespace cv - -#endif // OPENCV_STITCHING_WARPER_CREATORS_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_STITCHING_WARPER_CREATORS_HPP +#define OPENCV_STITCHING_WARPER_CREATORS_HPP + +#include "opencv2/stitching/detail/warpers.hpp" +#include + +namespace cv { + class CV_EXPORTS_W PyRotationWarper + { + Ptr rw; + + public: + CV_WRAP PyRotationWarper(String type, float scale); + CV_WRAP PyRotationWarper() {} + ~PyRotationWarper() {} + + /** @brief Projects the image point. + + @param pt Source point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected point + */ + CV_WRAP Point2f warpPoint(const Point2f &pt, InputArray K, InputArray R); + + /** @brief Projects the image point backward. + + @param pt Projected point + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Backward-projected point + */ +#if CV_VERSION_MAJOR == 4 + CV_WRAP Point2f warpPointBackward(const Point2f& pt, InputArray K, InputArray R) + { + CV_UNUSED(pt); CV_UNUSED(K); CV_UNUSED(R); + CV_Error(Error::StsNotImplemented, ""); + } +#else + CV_WRAP Point2f warpPointBackward(const Point2f &pt, InputArray K, InputArray R); +#endif + /** @brief Builds the projection maps according to the given camera data. + + @param src_size Source image size + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param xmap Projection map for the x axis + @param ymap Projection map for the y axis + @return Projected image minimum bounding box + */ + CV_WRAP Rect buildMaps(Size src_size, InputArray K, InputArray R, OutputArray xmap, OutputArray ymap); + + /** @brief Projects the image. + + @param src Source image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst Projected image + @return Project image top-left corner + */ + CV_WRAP Point warp(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + CV_OUT OutputArray dst); + + /** @brief Projects the image backward. + + @param src Projected image + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @param interp_mode Interpolation mode + @param border_mode Border extrapolation mode + @param dst_size Backward-projected image size + @param dst Backward-projected image + */ + CV_WRAP void warpBackward(InputArray src, InputArray K, InputArray R, int interp_mode, int border_mode, + Size dst_size, CV_OUT OutputArray dst); + + /** + @param src_size Source image bounding box + @param K Camera intrinsic parameters + @param R Camera rotation matrix + @return Projected image minimum bounding box + */ + CV_WRAP Rect warpRoi(Size src_size, InputArray K, InputArray R); + + CV_WRAP float getScale() const { return 1.f; } + CV_WRAP void setScale(float) {} + }; + +//! @addtogroup stitching_warp +//! @{ + +/** @brief Image warper factories base class. + */ + +class CV_EXPORTS_W WarperCreator +{ +public: + CV_WRAP virtual ~WarperCreator() {} + virtual Ptr create(float scale) const = 0; +}; + + +/** @brief Plane warper factory class. + @sa detail::PlaneWarper + */ +class CV_EXPORTS PlaneWarper : public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +/** @brief Affine warper factory class. + @sa detail::AffineWarper + */ +class CV_EXPORTS AffineWarper : public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +/** @brief Cylindrical warper factory class. +@sa detail::CylindricalWarper +*/ +class CV_EXPORTS CylindricalWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +/** @brief Spherical warper factory class */ +class CV_EXPORTS SphericalWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS FisheyeWarper : public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS StereographicWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS CompressedRectilinearWarper: public WarperCreator +{ + float a, b; +public: + CompressedRectilinearWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS CompressedRectilinearPortraitWarper: public WarperCreator +{ + float a, b; +public: + CompressedRectilinearPortraitWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS PaniniWarper: public WarperCreator +{ + float a, b; +public: + PaniniWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS PaniniPortraitWarper: public WarperCreator +{ + float a, b; +public: + PaniniPortraitWarper(float A = 1, float B = 1) + { + a = A; b = B; + } + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale, a, b); } +}; + +class CV_EXPORTS MercatorWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + +class CV_EXPORTS TransverseMercatorWarper: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + + + +#ifdef HAVE_OPENCV_CUDAWARPING +class PlaneWarperGpu: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + + +class CylindricalWarperGpu: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; + + +class SphericalWarperGpu: public WarperCreator +{ +public: + Ptr create(float scale) const CV_OVERRIDE { return makePtr(scale); } +}; +#endif + +//! @} stitching_warp + +} // namespace cv + +#endif // OPENCV_STITCHING_WARPER_CREATORS_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/video.hpp b/3rdParty/opencv-4.11.0/opencv2/video.hpp index 8ce49bc284..b1c19196d4 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video.hpp @@ -1,58 +1,58 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_VIDEO_HPP -#define OPENCV_VIDEO_HPP - -/** - @defgroup video Video Analysis - @{ - @defgroup video_motion Motion Analysis - @defgroup video_track Object Tracking - @} -*/ - -#include "opencv2/video/tracking.hpp" -#include "opencv2/video/background_segm.hpp" - -#endif //OPENCV_VIDEO_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_VIDEO_HPP +#define OPENCV_VIDEO_HPP + +/** + @defgroup video Video Analysis + @{ + @defgroup video_motion Motion Analysis + @defgroup video_track Object Tracking + @} +*/ + +#include "opencv2/video/tracking.hpp" +#include "opencv2/video/background_segm.hpp" + +#endif //OPENCV_VIDEO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp b/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp index 7433cd8b08..e1dfa15a9a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/background_segm.hpp @@ -1,317 +1,317 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_BACKGROUND_SEGM_HPP -#define OPENCV_BACKGROUND_SEGM_HPP - -#include "opencv2/core.hpp" - -namespace cv -{ - -//! @addtogroup video_motion -//! @{ - -/** @brief Base class for background/foreground segmentation. : - -The class is only used to define the common interface for the whole family of background/foreground -segmentation algorithms. - */ -class CV_EXPORTS_W BackgroundSubtractor : public Algorithm -{ -public: - /** @brief Computes a foreground mask. - - @param image Next video frame. - @param fgmask The output foreground mask as an 8-bit binary image. - @param learningRate The value between 0 and 1 that indicates how fast the background model is - learnt. Negative parameter value makes the algorithm to use some automatically chosen learning - rate. 0 means that the background model is not updated at all, 1 means that the background model - is completely reinitialized from the last frame. - */ - CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; - - /** @brief Computes a background image. - - @param backgroundImage The output background image. - - @note Sometimes the background image can be very blurry, as it contain the average background - statistics. - */ - CV_WRAP virtual void getBackgroundImage(OutputArray backgroundImage) const = 0; -}; - - -/** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. - -The class implements the Gaussian mixture model background subtraction described in @cite Zivkovic2004 -and @cite Zivkovic2006 . - */ -class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor -{ -public: - /** @brief Returns the number of last frames that affect the background model - */ - CV_WRAP virtual int getHistory() const = 0; - /** @brief Sets the number of last frames that affect the background model - */ - CV_WRAP virtual void setHistory(int history) = 0; - - /** @brief Returns the number of gaussian components in the background model - */ - CV_WRAP virtual int getNMixtures() const = 0; - /** @brief Sets the number of gaussian components in the background model. - - The model needs to be reinitalized to reserve memory. - */ - CV_WRAP virtual void setNMixtures(int nmixtures) = 0;//needs reinitialization! - - /** @brief Returns the "background ratio" parameter of the algorithm - - If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's - considered background and added to the model as a center of a new component. It corresponds to TB - parameter in the paper. - */ - CV_WRAP virtual double getBackgroundRatio() const = 0; - /** @brief Sets the "background ratio" parameter of the algorithm - */ - CV_WRAP virtual void setBackgroundRatio(double ratio) = 0; - - /** @brief Returns the variance threshold for the pixel-model match - - The main threshold on the squared Mahalanobis distance to decide if the sample is well described by - the background model or not. Related to Cthr from the paper. - */ - CV_WRAP virtual double getVarThreshold() const = 0; - /** @brief Sets the variance threshold for the pixel-model match - */ - CV_WRAP virtual void setVarThreshold(double varThreshold) = 0; - - /** @brief Returns the variance threshold for the pixel-model match used for new mixture component generation - - Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the - existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it - is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg - value generates more components. A higher Tg value may result in a small number of components but - they can grow too large. - */ - CV_WRAP virtual double getVarThresholdGen() const = 0; - /** @brief Sets the variance threshold for the pixel-model match used for new mixture component generation - */ - CV_WRAP virtual void setVarThresholdGen(double varThresholdGen) = 0; - - /** @brief Returns the initial variance of each gaussian component - */ - CV_WRAP virtual double getVarInit() const = 0; - /** @brief Sets the initial variance of each gaussian component - */ - CV_WRAP virtual void setVarInit(double varInit) = 0; - - CV_WRAP virtual double getVarMin() const = 0; - CV_WRAP virtual void setVarMin(double varMin) = 0; - - CV_WRAP virtual double getVarMax() const = 0; - CV_WRAP virtual void setVarMax(double varMax) = 0; - - /** @brief Returns the complexity reduction threshold - - This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05 - is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the - standard Stauffer&Grimson algorithm. - */ - CV_WRAP virtual double getComplexityReductionThreshold() const = 0; - /** @brief Sets the complexity reduction threshold - */ - CV_WRAP virtual void setComplexityReductionThreshold(double ct) = 0; - - /** @brief Returns the shadow detection flag - - If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorMOG2 for - details. - */ - CV_WRAP virtual bool getDetectShadows() const = 0; - /** @brief Enables or disables shadow detection - */ - CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; - - /** @brief Returns the shadow value - - Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 - in the mask always means background, 255 means foreground. - */ - CV_WRAP virtual int getShadowValue() const = 0; - /** @brief Sets the shadow value - */ - CV_WRAP virtual void setShadowValue(int value) = 0; - - /** @brief Returns the shadow threshold - - A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in - the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel - is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, - *Detecting Moving Shadows...*, IEEE PAMI,2003. - */ - CV_WRAP virtual double getShadowThreshold() const = 0; - /** @brief Sets the shadow threshold - */ - CV_WRAP virtual void setShadowThreshold(double threshold) = 0; - - /** @brief Computes a foreground mask. - - @param image Next video frame. Floating point frame will be used without scaling and should be in range \f$[0,255]\f$. - @param fgmask The output foreground mask as an 8-bit binary image. - @param learningRate The value between 0 and 1 that indicates how fast the background model is - learnt. Negative parameter value makes the algorithm to use some automatically chosen learning - rate. 0 means that the background model is not updated at all, 1 means that the background model - is completely reinitialized from the last frame. - */ - CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) CV_OVERRIDE = 0; -}; - -/** @brief Creates MOG2 Background Subtractor - -@param history Length of the history. -@param varThreshold Threshold on the squared Mahalanobis distance between the pixel and the model -to decide whether a pixel is well described by the background model. This parameter does not -affect the background update. -@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the -speed a bit, so if you do not need this feature, set the parameter to false. - */ -CV_EXPORTS_W Ptr - createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, - bool detectShadows=true); - -/** @brief K-nearest neighbours - based Background/Foreground Segmentation Algorithm. - -The class implements the K-nearest neighbours background subtraction described in @cite Zivkovic2006 . -Very efficient if number of foreground pixels is low. - */ -class CV_EXPORTS_W BackgroundSubtractorKNN : public BackgroundSubtractor -{ -public: - /** @brief Returns the number of last frames that affect the background model - */ - CV_WRAP virtual int getHistory() const = 0; - /** @brief Sets the number of last frames that affect the background model - */ - CV_WRAP virtual void setHistory(int history) = 0; - - /** @brief Returns the number of data samples in the background model - */ - CV_WRAP virtual int getNSamples() const = 0; - /** @brief Sets the number of data samples in the background model. - - The model needs to be reinitalized to reserve memory. - */ - CV_WRAP virtual void setNSamples(int _nN) = 0;//needs reinitialization! - - /** @brief Returns the threshold on the squared distance between the pixel and the sample - - The threshold on the squared distance between the pixel and the sample to decide whether a pixel is - close to a data sample. - */ - CV_WRAP virtual double getDist2Threshold() const = 0; - /** @brief Sets the threshold on the squared distance - */ - CV_WRAP virtual void setDist2Threshold(double _dist2Threshold) = 0; - - /** @brief Returns the number of neighbours, the k in the kNN. - - K is the number of samples that need to be within dist2Threshold in order to decide that that - pixel is matching the kNN background model. - */ - CV_WRAP virtual int getkNNSamples() const = 0; - /** @brief Sets the k in the kNN. How many nearest neighbours need to match. - */ - CV_WRAP virtual void setkNNSamples(int _nkNN) = 0; - - /** @brief Returns the shadow detection flag - - If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for - details. - */ - CV_WRAP virtual bool getDetectShadows() const = 0; - /** @brief Enables or disables shadow detection - */ - CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; - - /** @brief Returns the shadow value - - Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 - in the mask always means background, 255 means foreground. - */ - CV_WRAP virtual int getShadowValue() const = 0; - /** @brief Sets the shadow value - */ - CV_WRAP virtual void setShadowValue(int value) = 0; - - /** @brief Returns the shadow threshold - - A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in - the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel - is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, - *Detecting Moving Shadows...*, IEEE PAMI,2003. - */ - CV_WRAP virtual double getShadowThreshold() const = 0; - /** @brief Sets the shadow threshold - */ - CV_WRAP virtual void setShadowThreshold(double threshold) = 0; -}; - -/** @brief Creates KNN Background Subtractor - -@param history Length of the history. -@param dist2Threshold Threshold on the squared distance between the pixel and the sample to decide -whether a pixel is close to that sample. This parameter does not affect the background update. -@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the -speed a bit, so if you do not need this feature, set the parameter to false. - */ -CV_EXPORTS_W Ptr - createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, - bool detectShadows=true); - -//! @} video_motion - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_BACKGROUND_SEGM_HPP +#define OPENCV_BACKGROUND_SEGM_HPP + +#include "opencv2/core.hpp" + +namespace cv +{ + +//! @addtogroup video_motion +//! @{ + +/** @brief Base class for background/foreground segmentation. : + +The class is only used to define the common interface for the whole family of background/foreground +segmentation algorithms. + */ +class CV_EXPORTS_W BackgroundSubtractor : public Algorithm +{ +public: + /** @brief Computes a foreground mask. + + @param image Next video frame. + @param fgmask The output foreground mask as an 8-bit binary image. + @param learningRate The value between 0 and 1 that indicates how fast the background model is + learnt. Negative parameter value makes the algorithm to use some automatically chosen learning + rate. 0 means that the background model is not updated at all, 1 means that the background model + is completely reinitialized from the last frame. + */ + CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) = 0; + + /** @brief Computes a background image. + + @param backgroundImage The output background image. + + @note Sometimes the background image can be very blurry, as it contain the average background + statistics. + */ + CV_WRAP virtual void getBackgroundImage(OutputArray backgroundImage) const = 0; +}; + + +/** @brief Gaussian Mixture-based Background/Foreground Segmentation Algorithm. + +The class implements the Gaussian mixture model background subtraction described in @cite Zivkovic2004 +and @cite Zivkovic2006 . + */ +class CV_EXPORTS_W BackgroundSubtractorMOG2 : public BackgroundSubtractor +{ +public: + /** @brief Returns the number of last frames that affect the background model + */ + CV_WRAP virtual int getHistory() const = 0; + /** @brief Sets the number of last frames that affect the background model + */ + CV_WRAP virtual void setHistory(int history) = 0; + + /** @brief Returns the number of gaussian components in the background model + */ + CV_WRAP virtual int getNMixtures() const = 0; + /** @brief Sets the number of gaussian components in the background model. + + The model needs to be reinitalized to reserve memory. + */ + CV_WRAP virtual void setNMixtures(int nmixtures) = 0;//needs reinitialization! + + /** @brief Returns the "background ratio" parameter of the algorithm + + If a foreground pixel keeps semi-constant value for about backgroundRatio\*history frames, it's + considered background and added to the model as a center of a new component. It corresponds to TB + parameter in the paper. + */ + CV_WRAP virtual double getBackgroundRatio() const = 0; + /** @brief Sets the "background ratio" parameter of the algorithm + */ + CV_WRAP virtual void setBackgroundRatio(double ratio) = 0; + + /** @brief Returns the variance threshold for the pixel-model match + + The main threshold on the squared Mahalanobis distance to decide if the sample is well described by + the background model or not. Related to Cthr from the paper. + */ + CV_WRAP virtual double getVarThreshold() const = 0; + /** @brief Sets the variance threshold for the pixel-model match + */ + CV_WRAP virtual void setVarThreshold(double varThreshold) = 0; + + /** @brief Returns the variance threshold for the pixel-model match used for new mixture component generation + + Threshold for the squared Mahalanobis distance that helps decide when a sample is close to the + existing components (corresponds to Tg in the paper). If a pixel is not close to any component, it + is considered foreground or added as a new component. 3 sigma =\> Tg=3\*3=9 is default. A smaller Tg + value generates more components. A higher Tg value may result in a small number of components but + they can grow too large. + */ + CV_WRAP virtual double getVarThresholdGen() const = 0; + /** @brief Sets the variance threshold for the pixel-model match used for new mixture component generation + */ + CV_WRAP virtual void setVarThresholdGen(double varThresholdGen) = 0; + + /** @brief Returns the initial variance of each gaussian component + */ + CV_WRAP virtual double getVarInit() const = 0; + /** @brief Sets the initial variance of each gaussian component + */ + CV_WRAP virtual void setVarInit(double varInit) = 0; + + CV_WRAP virtual double getVarMin() const = 0; + CV_WRAP virtual void setVarMin(double varMin) = 0; + + CV_WRAP virtual double getVarMax() const = 0; + CV_WRAP virtual void setVarMax(double varMax) = 0; + + /** @brief Returns the complexity reduction threshold + + This parameter defines the number of samples needed to accept to prove the component exists. CT=0.05 + is a default value for all the samples. By setting CT=0 you get an algorithm very similar to the + standard Stauffer&Grimson algorithm. + */ + CV_WRAP virtual double getComplexityReductionThreshold() const = 0; + /** @brief Sets the complexity reduction threshold + */ + CV_WRAP virtual void setComplexityReductionThreshold(double ct) = 0; + + /** @brief Returns the shadow detection flag + + If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorMOG2 for + details. + */ + CV_WRAP virtual bool getDetectShadows() const = 0; + /** @brief Enables or disables shadow detection + */ + CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; + + /** @brief Returns the shadow value + + Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 + in the mask always means background, 255 means foreground. + */ + CV_WRAP virtual int getShadowValue() const = 0; + /** @brief Sets the shadow value + */ + CV_WRAP virtual void setShadowValue(int value) = 0; + + /** @brief Returns the shadow threshold + + A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in + the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel + is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, + *Detecting Moving Shadows...*, IEEE PAMI,2003. + */ + CV_WRAP virtual double getShadowThreshold() const = 0; + /** @brief Sets the shadow threshold + */ + CV_WRAP virtual void setShadowThreshold(double threshold) = 0; + + /** @brief Computes a foreground mask. + + @param image Next video frame. Floating point frame will be used without scaling and should be in range \f$[0,255]\f$. + @param fgmask The output foreground mask as an 8-bit binary image. + @param learningRate The value between 0 and 1 that indicates how fast the background model is + learnt. Negative parameter value makes the algorithm to use some automatically chosen learning + rate. 0 means that the background model is not updated at all, 1 means that the background model + is completely reinitialized from the last frame. + */ + CV_WRAP virtual void apply(InputArray image, OutputArray fgmask, double learningRate=-1) CV_OVERRIDE = 0; +}; + +/** @brief Creates MOG2 Background Subtractor + +@param history Length of the history. +@param varThreshold Threshold on the squared Mahalanobis distance between the pixel and the model +to decide whether a pixel is well described by the background model. This parameter does not +affect the background update. +@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the +speed a bit, so if you do not need this feature, set the parameter to false. + */ +CV_EXPORTS_W Ptr + createBackgroundSubtractorMOG2(int history=500, double varThreshold=16, + bool detectShadows=true); + +/** @brief K-nearest neighbours - based Background/Foreground Segmentation Algorithm. + +The class implements the K-nearest neighbours background subtraction described in @cite Zivkovic2006 . +Very efficient if number of foreground pixels is low. + */ +class CV_EXPORTS_W BackgroundSubtractorKNN : public BackgroundSubtractor +{ +public: + /** @brief Returns the number of last frames that affect the background model + */ + CV_WRAP virtual int getHistory() const = 0; + /** @brief Sets the number of last frames that affect the background model + */ + CV_WRAP virtual void setHistory(int history) = 0; + + /** @brief Returns the number of data samples in the background model + */ + CV_WRAP virtual int getNSamples() const = 0; + /** @brief Sets the number of data samples in the background model. + + The model needs to be reinitalized to reserve memory. + */ + CV_WRAP virtual void setNSamples(int _nN) = 0;//needs reinitialization! + + /** @brief Returns the threshold on the squared distance between the pixel and the sample + + The threshold on the squared distance between the pixel and the sample to decide whether a pixel is + close to a data sample. + */ + CV_WRAP virtual double getDist2Threshold() const = 0; + /** @brief Sets the threshold on the squared distance + */ + CV_WRAP virtual void setDist2Threshold(double _dist2Threshold) = 0; + + /** @brief Returns the number of neighbours, the k in the kNN. + + K is the number of samples that need to be within dist2Threshold in order to decide that that + pixel is matching the kNN background model. + */ + CV_WRAP virtual int getkNNSamples() const = 0; + /** @brief Sets the k in the kNN. How many nearest neighbours need to match. + */ + CV_WRAP virtual void setkNNSamples(int _nkNN) = 0; + + /** @brief Returns the shadow detection flag + + If true, the algorithm detects shadows and marks them. See createBackgroundSubtractorKNN for + details. + */ + CV_WRAP virtual bool getDetectShadows() const = 0; + /** @brief Enables or disables shadow detection + */ + CV_WRAP virtual void setDetectShadows(bool detectShadows) = 0; + + /** @brief Returns the shadow value + + Shadow value is the value used to mark shadows in the foreground mask. Default value is 127. Value 0 + in the mask always means background, 255 means foreground. + */ + CV_WRAP virtual int getShadowValue() const = 0; + /** @brief Sets the shadow value + */ + CV_WRAP virtual void setShadowValue(int value) = 0; + + /** @brief Returns the shadow threshold + + A shadow is detected if pixel is a darker version of the background. The shadow threshold (Tau in + the paper) is a threshold defining how much darker the shadow can be. Tau= 0.5 means that if a pixel + is more than twice darker then it is not shadow. See Prati, Mikic, Trivedi and Cucchiara, + *Detecting Moving Shadows...*, IEEE PAMI,2003. + */ + CV_WRAP virtual double getShadowThreshold() const = 0; + /** @brief Sets the shadow threshold + */ + CV_WRAP virtual void setShadowThreshold(double threshold) = 0; +}; + +/** @brief Creates KNN Background Subtractor + +@param history Length of the history. +@param dist2Threshold Threshold on the squared distance between the pixel and the sample to decide +whether a pixel is close to that sample. This parameter does not affect the background update. +@param detectShadows If true, the algorithm will detect shadows and mark them. It decreases the +speed a bit, so if you do not need this feature, set the parameter to false. + */ +CV_EXPORTS_W Ptr + createBackgroundSubtractorKNN(int history=500, double dist2Threshold=400.0, + bool detectShadows=true); + +//! @} video_motion + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp b/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp index eb954d6a16..3c7823b7dc 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/detail/tracking.detail.hpp @@ -1,406 +1,406 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEO_DETAIL_TRACKING_HPP -#define OPENCV_VIDEO_DETAIL_TRACKING_HPP - -/* - * Partially based on: - * ==================================================================================================================== - * - [AAM] S. Salti, A. Cavallaro, L. Di Stefano, Adaptive Appearance Modeling for Video Tracking: Survey and Evaluation - * - [AMVOT] X. Li, W. Hu, C. Shen, Z. Zhang, A. Dick, A. van den Hengel, A Survey of Appearance Models in Visual Object Tracking - * - * This Tracking API has been designed with PlantUML. If you modify this API please change UML files under modules/tracking/doc/uml - * - */ - -#include "opencv2/core.hpp" - -namespace cv { -namespace detail { -inline namespace tracking { - -/** @addtogroup tracking_detail -@{ -*/ - -/************************************ TrackerFeature Base Classes ************************************/ - -/** @brief Abstract base class for TrackerFeature that represents the feature. -*/ -class CV_EXPORTS TrackerFeature -{ -public: - virtual ~TrackerFeature(); - - /** @brief Compute the features in the images collection - @param images The images - @param response The output response - */ - void compute(const std::vector& images, Mat& response); - -protected: - virtual bool computeImpl(const std::vector& images, Mat& response) = 0; -}; - -/** @brief Class that manages the extraction and selection of features - -@cite AAM Feature Extraction and Feature Set Refinement (Feature Processing and Feature Selection). -See table I and section III C @cite AMVOT Appearance modelling -\> Visual representation (Table II, -section 3.1 - 3.2) - -TrackerFeatureSet is an aggregation of TrackerFeature - -@sa - TrackerFeature - -*/ -class CV_EXPORTS TrackerFeatureSet -{ -public: - TrackerFeatureSet(); - - ~TrackerFeatureSet(); - - /** @brief Extract features from the images collection - @param images The input images - */ - void extraction(const std::vector& images); - - /** @brief Add TrackerFeature in the collection. Return true if TrackerFeature is added, false otherwise - @param feature The TrackerFeature class - */ - bool addTrackerFeature(const Ptr& feature); - - /** @brief Get the TrackerFeature collection (TrackerFeature name, TrackerFeature pointer) - */ - const std::vector>& getTrackerFeatures() const; - - /** @brief Get the responses - @note Be sure to call extraction before getResponses Example TrackerFeatureSet::getResponses - */ - const std::vector& getResponses() const; - -private: - void clearResponses(); - bool blockAddTrackerFeature; - - std::vector> features; // list of features - std::vector responses; // list of response after compute -}; - -/************************************ TrackerSampler Base Classes ************************************/ - -/** @brief Abstract base class for TrackerSamplerAlgorithm that represents the algorithm for the specific -sampler. -*/ -class CV_EXPORTS TrackerSamplerAlgorithm -{ -public: - virtual ~TrackerSamplerAlgorithm(); - - /** @brief Computes the regions starting from a position in an image. - - Return true if samples are computed, false otherwise - - @param image The current frame - @param boundingBox The bounding box from which regions can be calculated - - @param sample The computed samples @cite AAM Fig. 1 variable Sk - */ - virtual bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) = 0; -}; - -/** - * \brief Class that manages the sampler in order to select regions for the update the model of the tracker - * [AAM] Sampling e Labeling. See table I and section III B - */ - -/** @brief Class that manages the sampler in order to select regions for the update the model of the tracker - -@cite AAM Sampling e Labeling. See table I and section III B - -TrackerSampler is an aggregation of TrackerSamplerAlgorithm -@sa - TrackerSamplerAlgorithm - */ -class CV_EXPORTS TrackerSampler -{ -public: - TrackerSampler(); - - ~TrackerSampler(); - - /** @brief Computes the regions starting from a position in an image - @param image The current frame - @param boundingBox The bounding box from which regions can be calculated - */ - void sampling(const Mat& image, Rect boundingBox); - - /** @brief Return the collection of the TrackerSamplerAlgorithm - */ - const std::vector>& getSamplers() const; - - /** @brief Return the samples from all TrackerSamplerAlgorithm, @cite AAM Fig. 1 variable Sk - */ - const std::vector& getSamples() const; - - /** @brief Add TrackerSamplerAlgorithm in the collection. Return true if sampler is added, false otherwise - @param sampler The TrackerSamplerAlgorithm - */ - bool addTrackerSamplerAlgorithm(const Ptr& sampler); - -private: - std::vector> samplers; - std::vector samples; - bool blockAddTrackerSampler; - - void clearSamples(); -}; - -/************************************ TrackerModel Base Classes ************************************/ - -/** @brief Abstract base class for TrackerTargetState that represents a possible state of the target. - -See @cite AAM \f$\hat{x}^{i}_{k}\f$ all the states candidates. - -Inherits this class with your Target state, In own implementation you can add scale variation, -width, height, orientation, etc. -*/ -class CV_EXPORTS TrackerTargetState -{ -public: - virtual ~TrackerTargetState() {} - /** @brief Get the position - * @return The position - */ - Point2f getTargetPosition() const; - - /** @brief Set the position - * @param position The position - */ - void setTargetPosition(const Point2f& position); - /** @brief Get the width of the target - * @return The width of the target - */ - int getTargetWidth() const; - - /** @brief Set the width of the target - * @param width The width of the target - */ - void setTargetWidth(int width); - /** @brief Get the height of the target - * @return The height of the target - */ - int getTargetHeight() const; - - /** @brief Set the height of the target - * @param height The height of the target - */ - void setTargetHeight(int height); - -protected: - Point2f targetPosition; - int targetWidth; - int targetHeight; -}; - -/** @brief Represents the model of the target at frame \f$k\f$ (all states and scores) - -See @cite AAM The set of the pair \f$\langle \hat{x}^{i}_{k}, C^{i}_{k} \rangle\f$ -@sa TrackerTargetState -*/ -typedef std::vector, float>> ConfidenceMap; - -/** @brief Represents the estimate states for all frames - -@cite AAM \f$x_{k}\f$ is the trajectory of the target up to time \f$k\f$ - -@sa TrackerTargetState -*/ -typedef std::vector> Trajectory; - -/** @brief Abstract base class for TrackerStateEstimator that estimates the most likely target state. - -See @cite AAM State estimator - -See @cite AMVOT Statistical modeling (Fig. 3), Table III (generative) - IV (discriminative) - V (hybrid) -*/ -class CV_EXPORTS TrackerStateEstimator -{ -public: - virtual ~TrackerStateEstimator(); - - /** @brief Estimate the most likely target state, return the estimated state - @param confidenceMaps The overall appearance model as a list of :cConfidenceMap - */ - Ptr estimate(const std::vector& confidenceMaps); - - /** @brief Update the ConfidenceMap with the scores - @param confidenceMaps The overall appearance model as a list of :cConfidenceMap - */ - void update(std::vector& confidenceMaps); - - /** @brief Create TrackerStateEstimator by tracker state estimator type - @param trackeStateEstimatorType The TrackerStateEstimator name - - The modes available now: - - - "BOOSTING" -- Boosting-based discriminative appearance models. See @cite AMVOT section 4.4 - - The modes available soon: - - - "SVM" -- SVM-based discriminative appearance models. See @cite AMVOT section 4.5 - */ - static Ptr create(const String& trackeStateEstimatorType); - - /** @brief Get the name of the specific TrackerStateEstimator - */ - String getClassName() const; - -protected: - virtual Ptr estimateImpl(const std::vector& confidenceMaps) = 0; - virtual void updateImpl(std::vector& confidenceMaps) = 0; - String className; -}; - -/** @brief Abstract class that represents the model of the target. - -It must be instantiated by specialized tracker - -See @cite AAM Ak - -Inherits this with your TrackerModel -*/ -class CV_EXPORTS TrackerModel -{ -public: - TrackerModel(); - - virtual ~TrackerModel(); - - /** @brief Set TrackerEstimator, return true if the tracker state estimator is added, false otherwise - @param trackerStateEstimator The TrackerStateEstimator - @note You can add only one TrackerStateEstimator - */ - bool setTrackerStateEstimator(Ptr trackerStateEstimator); - - /** @brief Estimate the most likely target location - - @cite AAM ME, Model Estimation table I - @param responses Features extracted from TrackerFeatureSet - */ - void modelEstimation(const std::vector& responses); - - /** @brief Update the model - - @cite AAM MU, Model Update table I - */ - void modelUpdate(); - - /** @brief Run the TrackerStateEstimator, return true if is possible to estimate a new state, false otherwise - */ - bool runStateEstimator(); - - /** @brief Set the current TrackerTargetState in the Trajectory - @param lastTargetState The current TrackerTargetState - */ - void setLastTargetState(const Ptr& lastTargetState); - - /** @brief Get the last TrackerTargetState from Trajectory - */ - Ptr getLastTargetState() const; - - /** @brief Get the list of the ConfidenceMap - */ - const std::vector& getConfidenceMaps() const; - - /** @brief Get the last ConfidenceMap for the current frame - */ - const ConfidenceMap& getLastConfidenceMap() const; - - /** @brief Get the TrackerStateEstimator - */ - Ptr getTrackerStateEstimator() const; - -private: - void clearCurrentConfidenceMap(); - -protected: - std::vector confidenceMaps; - Ptr stateEstimator; - ConfidenceMap currentConfidenceMap; - Trajectory trajectory; - int maxCMLength; - - virtual void modelEstimationImpl(const std::vector& responses) = 0; - virtual void modelUpdateImpl() = 0; -}; - -/************************************ Specific TrackerStateEstimator Classes ************************************/ - -// None - -/************************************ Specific TrackerSamplerAlgorithm Classes ************************************/ - -/** @brief TrackerSampler based on CSC (current state centered), used by MIL algorithm TrackerMIL - */ -class CV_EXPORTS TrackerSamplerCSC : public TrackerSamplerAlgorithm -{ -public: - ~TrackerSamplerCSC(); - - enum MODE - { - MODE_INIT_POS = 1, //!< mode for init positive samples - MODE_INIT_NEG = 2, //!< mode for init negative samples - MODE_TRACK_POS = 3, //!< mode for update positive samples - MODE_TRACK_NEG = 4, //!< mode for update negative samples - MODE_DETECT = 5 //!< mode for detect samples - }; - - struct CV_EXPORTS Params - { - Params(); - float initInRad; //!< radius for gathering positive instances during init - float trackInPosRad; //!< radius for gathering positive instances during tracking - float searchWinSize; //!< size of search window - int initMaxNegNum; //!< # negative samples to use during init - int trackMaxPosNum; //!< # positive samples to use during training - int trackMaxNegNum; //!< # negative samples to use during training - }; - - /** @brief Constructor - @param parameters TrackerSamplerCSC parameters TrackerSamplerCSC::Params - */ - TrackerSamplerCSC(const TrackerSamplerCSC::Params& parameters = TrackerSamplerCSC::Params()); - - /** @brief Set the sampling mode of TrackerSamplerCSC - @param samplingMode The sampling mode - - The modes are: - - - "MODE_INIT_POS = 1" -- for the positive sampling in initialization step - - "MODE_INIT_NEG = 2" -- for the negative sampling in initialization step - - "MODE_TRACK_POS = 3" -- for the positive sampling in update step - - "MODE_TRACK_NEG = 4" -- for the negative sampling in update step - - "MODE_DETECT = 5" -- for the sampling in detection step - */ - void setMode(int samplingMode); - - bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) CV_OVERRIDE; - -private: - Params params; - int mode; - RNG rng; - - std::vector sampleImage(const Mat& img, int x, int y, int w, int h, float inrad, float outrad = 0, int maxnum = 1000000); -}; - -//! @} - -}}} // namespace cv::detail::tracking - -#endif // OPENCV_VIDEO_DETAIL_TRACKING_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEO_DETAIL_TRACKING_HPP +#define OPENCV_VIDEO_DETAIL_TRACKING_HPP + +/* + * Partially based on: + * ==================================================================================================================== + * - [AAM] S. Salti, A. Cavallaro, L. Di Stefano, Adaptive Appearance Modeling for Video Tracking: Survey and Evaluation + * - [AMVOT] X. Li, W. Hu, C. Shen, Z. Zhang, A. Dick, A. van den Hengel, A Survey of Appearance Models in Visual Object Tracking + * + * This Tracking API has been designed with PlantUML. If you modify this API please change UML files under modules/tracking/doc/uml + * + */ + +#include "opencv2/core.hpp" + +namespace cv { +namespace detail { +inline namespace tracking { + +/** @addtogroup tracking_detail +@{ +*/ + +/************************************ TrackerFeature Base Classes ************************************/ + +/** @brief Abstract base class for TrackerFeature that represents the feature. +*/ +class CV_EXPORTS TrackerFeature +{ +public: + virtual ~TrackerFeature(); + + /** @brief Compute the features in the images collection + @param images The images + @param response The output response + */ + void compute(const std::vector& images, Mat& response); + +protected: + virtual bool computeImpl(const std::vector& images, Mat& response) = 0; +}; + +/** @brief Class that manages the extraction and selection of features + +@cite AAM Feature Extraction and Feature Set Refinement (Feature Processing and Feature Selection). +See table I and section III C @cite AMVOT Appearance modelling -\> Visual representation (Table II, +section 3.1 - 3.2) + +TrackerFeatureSet is an aggregation of TrackerFeature + +@sa + TrackerFeature + +*/ +class CV_EXPORTS TrackerFeatureSet +{ +public: + TrackerFeatureSet(); + + ~TrackerFeatureSet(); + + /** @brief Extract features from the images collection + @param images The input images + */ + void extraction(const std::vector& images); + + /** @brief Add TrackerFeature in the collection. Return true if TrackerFeature is added, false otherwise + @param feature The TrackerFeature class + */ + bool addTrackerFeature(const Ptr& feature); + + /** @brief Get the TrackerFeature collection (TrackerFeature name, TrackerFeature pointer) + */ + const std::vector>& getTrackerFeatures() const; + + /** @brief Get the responses + @note Be sure to call extraction before getResponses Example TrackerFeatureSet::getResponses + */ + const std::vector& getResponses() const; + +private: + void clearResponses(); + bool blockAddTrackerFeature; + + std::vector> features; // list of features + std::vector responses; // list of response after compute +}; + +/************************************ TrackerSampler Base Classes ************************************/ + +/** @brief Abstract base class for TrackerSamplerAlgorithm that represents the algorithm for the specific +sampler. +*/ +class CV_EXPORTS TrackerSamplerAlgorithm +{ +public: + virtual ~TrackerSamplerAlgorithm(); + + /** @brief Computes the regions starting from a position in an image. + + Return true if samples are computed, false otherwise + + @param image The current frame + @param boundingBox The bounding box from which regions can be calculated + + @param sample The computed samples @cite AAM Fig. 1 variable Sk + */ + virtual bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) = 0; +}; + +/** + * \brief Class that manages the sampler in order to select regions for the update the model of the tracker + * [AAM] Sampling e Labeling. See table I and section III B + */ + +/** @brief Class that manages the sampler in order to select regions for the update the model of the tracker + +@cite AAM Sampling e Labeling. See table I and section III B + +TrackerSampler is an aggregation of TrackerSamplerAlgorithm +@sa + TrackerSamplerAlgorithm + */ +class CV_EXPORTS TrackerSampler +{ +public: + TrackerSampler(); + + ~TrackerSampler(); + + /** @brief Computes the regions starting from a position in an image + @param image The current frame + @param boundingBox The bounding box from which regions can be calculated + */ + void sampling(const Mat& image, Rect boundingBox); + + /** @brief Return the collection of the TrackerSamplerAlgorithm + */ + const std::vector>& getSamplers() const; + + /** @brief Return the samples from all TrackerSamplerAlgorithm, @cite AAM Fig. 1 variable Sk + */ + const std::vector& getSamples() const; + + /** @brief Add TrackerSamplerAlgorithm in the collection. Return true if sampler is added, false otherwise + @param sampler The TrackerSamplerAlgorithm + */ + bool addTrackerSamplerAlgorithm(const Ptr& sampler); + +private: + std::vector> samplers; + std::vector samples; + bool blockAddTrackerSampler; + + void clearSamples(); +}; + +/************************************ TrackerModel Base Classes ************************************/ + +/** @brief Abstract base class for TrackerTargetState that represents a possible state of the target. + +See @cite AAM \f$\hat{x}^{i}_{k}\f$ all the states candidates. + +Inherits this class with your Target state, In own implementation you can add scale variation, +width, height, orientation, etc. +*/ +class CV_EXPORTS TrackerTargetState +{ +public: + virtual ~TrackerTargetState() {} + /** @brief Get the position + * @return The position + */ + Point2f getTargetPosition() const; + + /** @brief Set the position + * @param position The position + */ + void setTargetPosition(const Point2f& position); + /** @brief Get the width of the target + * @return The width of the target + */ + int getTargetWidth() const; + + /** @brief Set the width of the target + * @param width The width of the target + */ + void setTargetWidth(int width); + /** @brief Get the height of the target + * @return The height of the target + */ + int getTargetHeight() const; + + /** @brief Set the height of the target + * @param height The height of the target + */ + void setTargetHeight(int height); + +protected: + Point2f targetPosition; + int targetWidth; + int targetHeight; +}; + +/** @brief Represents the model of the target at frame \f$k\f$ (all states and scores) + +See @cite AAM The set of the pair \f$\langle \hat{x}^{i}_{k}, C^{i}_{k} \rangle\f$ +@sa TrackerTargetState +*/ +typedef std::vector, float>> ConfidenceMap; + +/** @brief Represents the estimate states for all frames + +@cite AAM \f$x_{k}\f$ is the trajectory of the target up to time \f$k\f$ + +@sa TrackerTargetState +*/ +typedef std::vector> Trajectory; + +/** @brief Abstract base class for TrackerStateEstimator that estimates the most likely target state. + +See @cite AAM State estimator + +See @cite AMVOT Statistical modeling (Fig. 3), Table III (generative) - IV (discriminative) - V (hybrid) +*/ +class CV_EXPORTS TrackerStateEstimator +{ +public: + virtual ~TrackerStateEstimator(); + + /** @brief Estimate the most likely target state, return the estimated state + @param confidenceMaps The overall appearance model as a list of :cConfidenceMap + */ + Ptr estimate(const std::vector& confidenceMaps); + + /** @brief Update the ConfidenceMap with the scores + @param confidenceMaps The overall appearance model as a list of :cConfidenceMap + */ + void update(std::vector& confidenceMaps); + + /** @brief Create TrackerStateEstimator by tracker state estimator type + @param trackeStateEstimatorType The TrackerStateEstimator name + + The modes available now: + + - "BOOSTING" -- Boosting-based discriminative appearance models. See @cite AMVOT section 4.4 + + The modes available soon: + + - "SVM" -- SVM-based discriminative appearance models. See @cite AMVOT section 4.5 + */ + static Ptr create(const String& trackeStateEstimatorType); + + /** @brief Get the name of the specific TrackerStateEstimator + */ + String getClassName() const; + +protected: + virtual Ptr estimateImpl(const std::vector& confidenceMaps) = 0; + virtual void updateImpl(std::vector& confidenceMaps) = 0; + String className; +}; + +/** @brief Abstract class that represents the model of the target. + +It must be instantiated by specialized tracker + +See @cite AAM Ak + +Inherits this with your TrackerModel +*/ +class CV_EXPORTS TrackerModel +{ +public: + TrackerModel(); + + virtual ~TrackerModel(); + + /** @brief Set TrackerEstimator, return true if the tracker state estimator is added, false otherwise + @param trackerStateEstimator The TrackerStateEstimator + @note You can add only one TrackerStateEstimator + */ + bool setTrackerStateEstimator(Ptr trackerStateEstimator); + + /** @brief Estimate the most likely target location + + @cite AAM ME, Model Estimation table I + @param responses Features extracted from TrackerFeatureSet + */ + void modelEstimation(const std::vector& responses); + + /** @brief Update the model + + @cite AAM MU, Model Update table I + */ + void modelUpdate(); + + /** @brief Run the TrackerStateEstimator, return true if is possible to estimate a new state, false otherwise + */ + bool runStateEstimator(); + + /** @brief Set the current TrackerTargetState in the Trajectory + @param lastTargetState The current TrackerTargetState + */ + void setLastTargetState(const Ptr& lastTargetState); + + /** @brief Get the last TrackerTargetState from Trajectory + */ + Ptr getLastTargetState() const; + + /** @brief Get the list of the ConfidenceMap + */ + const std::vector& getConfidenceMaps() const; + + /** @brief Get the last ConfidenceMap for the current frame + */ + const ConfidenceMap& getLastConfidenceMap() const; + + /** @brief Get the TrackerStateEstimator + */ + Ptr getTrackerStateEstimator() const; + +private: + void clearCurrentConfidenceMap(); + +protected: + std::vector confidenceMaps; + Ptr stateEstimator; + ConfidenceMap currentConfidenceMap; + Trajectory trajectory; + int maxCMLength; + + virtual void modelEstimationImpl(const std::vector& responses) = 0; + virtual void modelUpdateImpl() = 0; +}; + +/************************************ Specific TrackerStateEstimator Classes ************************************/ + +// None + +/************************************ Specific TrackerSamplerAlgorithm Classes ************************************/ + +/** @brief TrackerSampler based on CSC (current state centered), used by MIL algorithm TrackerMIL + */ +class CV_EXPORTS TrackerSamplerCSC : public TrackerSamplerAlgorithm +{ +public: + ~TrackerSamplerCSC(); + + enum MODE + { + MODE_INIT_POS = 1, //!< mode for init positive samples + MODE_INIT_NEG = 2, //!< mode for init negative samples + MODE_TRACK_POS = 3, //!< mode for update positive samples + MODE_TRACK_NEG = 4, //!< mode for update negative samples + MODE_DETECT = 5 //!< mode for detect samples + }; + + struct CV_EXPORTS Params + { + Params(); + float initInRad; //!< radius for gathering positive instances during init + float trackInPosRad; //!< radius for gathering positive instances during tracking + float searchWinSize; //!< size of search window + int initMaxNegNum; //!< # negative samples to use during init + int trackMaxPosNum; //!< # positive samples to use during training + int trackMaxNegNum; //!< # negative samples to use during training + }; + + /** @brief Constructor + @param parameters TrackerSamplerCSC parameters TrackerSamplerCSC::Params + */ + TrackerSamplerCSC(const TrackerSamplerCSC::Params& parameters = TrackerSamplerCSC::Params()); + + /** @brief Set the sampling mode of TrackerSamplerCSC + @param samplingMode The sampling mode + + The modes are: + + - "MODE_INIT_POS = 1" -- for the positive sampling in initialization step + - "MODE_INIT_NEG = 2" -- for the negative sampling in initialization step + - "MODE_TRACK_POS = 3" -- for the positive sampling in update step + - "MODE_TRACK_NEG = 4" -- for the negative sampling in update step + - "MODE_DETECT = 5" -- for the sampling in detection step + */ + void setMode(int samplingMode); + + bool sampling(const Mat& image, const Rect& boundingBox, std::vector& sample) CV_OVERRIDE; + +private: + Params params; + int mode; + RNG rng; + + std::vector sampleImage(const Mat& img, int x, int y, int w, int h, float inrad, float outrad = 0, int maxnum = 1000000); +}; + +//! @} + +}}} // namespace cv::detail::tracking + +#endif // OPENCV_VIDEO_DETAIL_TRACKING_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h index 5bdd4a1906..1a98f52961 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/video/legacy/constants_c.h @@ -1,16 +1,16 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEO_LEGACY_CONSTANTS_H -#define OPENCV_VIDEO_LEGACY_CONSTANTS_H - -enum -{ - CV_LKFLOW_PYR_A_READY = 1, - CV_LKFLOW_PYR_B_READY = 2, - CV_LKFLOW_INITIAL_GUESSES = 4, - CV_LKFLOW_GET_MIN_EIGENVALS = 8 -}; - -#endif // OPENCV_VIDEO_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEO_LEGACY_CONSTANTS_H +#define OPENCV_VIDEO_LEGACY_CONSTANTS_H + +enum +{ + CV_LKFLOW_PYR_A_READY = 1, + CV_LKFLOW_PYR_B_READY = 2, + CV_LKFLOW_INITIAL_GUESSES = 4, + CV_LKFLOW_GET_MIN_EIGENVALS = 8 +}; + +#endif // OPENCV_VIDEO_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp b/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp index 130bf1bcc0..ac3788772a 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/tracking.hpp @@ -1,944 +1,944 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_TRACKING_HPP -#define OPENCV_TRACKING_HPP - -#include "opencv2/core.hpp" -#include "opencv2/imgproc.hpp" - -namespace cv -{ - -//! @addtogroup video_track -//! @{ - -enum { OPTFLOW_USE_INITIAL_FLOW = 4, - OPTFLOW_LK_GET_MIN_EIGENVALS = 8, - OPTFLOW_FARNEBACK_GAUSSIAN = 256 - }; - -/** @brief Finds an object center, size, and orientation. - -@param probImage Back projection of the object histogram. See calcBackProject. -@param window Initial search window. -@param criteria Stop criteria for the underlying meanShift. -returns -(in old interfaces) Number of iterations CAMSHIFT took to converge -The function implements the CAMSHIFT object tracking algorithm @cite Bradski98 . First, it finds an -object center using meanShift and then adjusts the window size and finds the optimal rotation. The -function returns the rotated rectangle structure that includes the object position, size, and -orientation. The next position of the search window can be obtained with RotatedRect::boundingRect() - -See the OpenCV sample camshiftdemo.c that tracks colored objects. - -@note -- (Python) A sample explaining the camshift tracking algorithm can be found at - opencv_source_code/samples/python/camshift.py - */ -CV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_IN_OUT Rect& window, - TermCriteria criteria ); -/** @example samples/cpp/camshiftdemo.cpp -An example using the mean-shift tracking algorithm -*/ - -/** @brief Finds an object on a back projection image. - -@param probImage Back projection of the object histogram. See calcBackProject for details. -@param window Initial search window. -@param criteria Stop criteria for the iterative search algorithm. -returns -: Number of iterations CAMSHIFT took to converge. -The function implements the iterative object search algorithm. It takes the input back projection of -an object and the initial position. The mass center in window of the back projection image is -computed and the search window center shifts to the mass center. The procedure is repeated until the -specified number of iterations criteria.maxCount is done or until the window center shifts by less -than criteria.epsilon. The algorithm is used inside CamShift and, unlike CamShift , the search -window size or orientation do not change during the search. You can simply pass the output of -calcBackProject to this function. But better results can be obtained if you pre-filter the back -projection and remove the noise. For example, you can do this by retrieving connected components -with findContours , throwing away contours with small area ( contourArea ), and rendering the -remaining contours with drawContours. - - */ -CV_EXPORTS_W int meanShift( InputArray probImage, CV_IN_OUT Rect& window, TermCriteria criteria ); - -/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. - -@param img 8-bit input image. -@param pyramid output pyramid. -@param winSize window size of optical flow algorithm. Must be not less than winSize argument of -calcOpticalFlowPyrLK. It is needed to calculate required padding for pyramid levels. -@param maxLevel 0-based maximal pyramid level number. -@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is -constructed without the gradients then calcOpticalFlowPyrLK will calculate them internally. -@param pyrBorder the border mode for pyramid layers. -@param derivBorder the border mode for gradients. -@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false -to force data copying. -@return number of levels in constructed pyramid. Can be less than maxLevel. - */ -CV_EXPORTS_W int buildOpticalFlowPyramid( InputArray img, OutputArrayOfArrays pyramid, - Size winSize, int maxLevel, bool withDerivatives = true, - int pyrBorder = BORDER_REFLECT_101, - int derivBorder = BORDER_CONSTANT, - bool tryReuseInputImage = true ); - -/** @example samples/cpp/lkdemo.cpp -An example using the Lucas-Kanade optical flow algorithm -*/ - -/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with -pyramids. - -@param prevImg first 8-bit input image or pyramid constructed by buildOpticalFlowPyramid. -@param nextImg second input image or pyramid of the same size and the same type as prevImg. -@param prevPts vector of 2D points for which the flow needs to be found; point coordinates must be -single-precision floating-point numbers. -@param nextPts output vector of 2D points (with single-precision floating-point coordinates) -containing the calculated new positions of input features in the second image; when -OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input. -@param status output status vector (of unsigned chars); each element of the vector is set to 1 if -the flow for the corresponding features has been found, otherwise, it is set to 0. -@param err output vector of errors; each element of the vector is set to an error for the -corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't -found then the error is not defined (use the status parameter to find such cases). -@param winSize size of the search window at each pyramid level. -@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single -level), if set to 1, two levels are used, and so on; if pyramids are passed to input then -algorithm will use as many levels as pyramids have but no more than maxLevel. -@param criteria parameter, specifying the termination criteria of the iterative search algorithm -(after the specified maximum number of iterations criteria.maxCount or when the search window -moves by less than criteria.epsilon. -@param flags operation flags: - - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is - not set, then prevPts is copied to nextPts and is considered the initial estimate. - - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see - minEigThreshold description); if the flag is not set, then L1 distance between patches - around the original and a moved point, divided by number of pixels in a window, is used as a - error measure. -@param minEigThreshold the algorithm calculates the minimum eigen value of a 2x2 normal matrix of -optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided -by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding -feature is filtered out and its flow is not processed, so it allows to remove bad points and get a -performance boost. - -The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See -@cite Bouguet00 . The function is parallelized with the TBB library. - -@note Some examples: - -- An example using the Lucas-Kanade optical flow algorithm can be found at - opencv_source_code/samples/cpp/lkdemo.cpp -- (Python) An example using the Lucas-Kanade optical flow algorithm can be found at - opencv_source_code/samples/python/lk_track.py -- (Python) An example using the Lucas-Kanade tracker for homography matching can be found at - opencv_source_code/samples/python/lk_homography.py - */ -CV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg, - InputArray prevPts, InputOutputArray nextPts, - OutputArray status, OutputArray err, - Size winSize = Size(21,21), int maxLevel = 3, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), - int flags = 0, double minEigThreshold = 1e-4 ); - -/** @brief Computes a dense optical flow using the Gunnar Farneback's algorithm. - -@param prev first 8-bit single-channel input image. -@param next second input image of the same size and the same type as prev. -@param flow computed flow image that has the same size as prev and type CV_32FC2. -@param pyr_scale parameter, specifying the image scale (\<1) to build pyramids for each image; -pyr_scale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous -one. -@param levels number of pyramid layers including the initial image; levels=1 means that no extra -layers are created and only the original images are used. -@param winsize averaging window size; larger values increase the algorithm robustness to image -noise and give more chances for fast motion detection, but yield more blurred motion field. -@param iterations number of iterations the algorithm does at each pyramid level. -@param poly_n size of the pixel neighborhood used to find polynomial expansion in each pixel; -larger values mean that the image will be approximated with smoother surfaces, yielding more -robust algorithm and more blurred motion field, typically poly_n =5 or 7. -@param poly_sigma standard deviation of the Gaussian that is used to smooth derivatives used as a -basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a -good value would be poly_sigma=1.5. -@param flags operation flags that can be a combination of the following: - - **OPTFLOW_USE_INITIAL_FLOW** uses the input flow as an initial flow approximation. - - **OPTFLOW_FARNEBACK_GAUSSIAN** uses the Gaussian \f$\texttt{winsize}\times\texttt{winsize}\f$ - filter instead of a box filter of the same size for optical flow estimation; usually, this - option gives z more accurate flow than with a box filter, at the cost of lower speed; - normally, winsize for a Gaussian window should be set to a larger value to achieve the same - level of robustness. - -The function finds an optical flow for each prev pixel using the @cite Farneback2003 algorithm so that - -\f[\texttt{prev} (y,x) \sim \texttt{next} ( y + \texttt{flow} (y,x)[1], x + \texttt{flow} (y,x)[0])\f] - -@note Some examples: - -- An example using the optical flow algorithm described by Gunnar Farneback can be found at - opencv_source_code/samples/cpp/fback.cpp -- (Python) An example using the optical flow algorithm described by Gunnar Farneback can be - found at opencv_source_code/samples/python/opt_flow.py - */ -CV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next, InputOutputArray flow, - double pyr_scale, int levels, int winsize, - int iterations, int poly_n, double poly_sigma, - int flags ); - -/** @brief Computes an optimal affine transformation between two 2D point sets. - -@param src First input 2D point set stored in std::vector or Mat, or an image stored in Mat. -@param dst Second input 2D point set of the same size and the same type as A, or another image. -@param fullAffine If true, the function finds an optimal affine transformation with no additional -restrictions (6 degrees of freedom). Otherwise, the class of transformations to choose from is -limited to combinations of translation, rotation, and uniform scaling (4 degrees of freedom). - -The function finds an optimal affine transform *[A|b]* (a 2 x 3 floating-point matrix) that -approximates best the affine transformation between: - -* Two point sets -* Two raster images. In this case, the function first finds some features in the src image and - finds the corresponding features in dst image. After that, the problem is reduced to the first - case. -In case of point sets, the problem is formulated as follows: you need to find a 2x2 matrix *A* and -2x1 vector *b* so that: - -\f[[A^*|b^*] = arg \min _{[A|b]} \sum _i \| \texttt{dst}[i] - A { \texttt{src}[i]}^T - b \| ^2\f] -where src[i] and dst[i] are the i-th points in src and dst, respectively -\f$[A|b]\f$ can be either arbitrary (when fullAffine=true ) or have a form of -\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\f] -when fullAffine=false. - -@deprecated Use cv::estimateAffine2D, cv::estimateAffinePartial2D instead. If you are using this function -with images, extract points using cv::calcOpticalFlowPyrLK and then use the estimation functions. - -@sa -estimateAffine2D, estimateAffinePartial2D, getAffineTransform, getPerspectiveTransform, findHomography - */ -CV_DEPRECATED CV_EXPORTS Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine ); - -enum -{ - MOTION_TRANSLATION = 0, - MOTION_EUCLIDEAN = 1, - MOTION_AFFINE = 2, - MOTION_HOMOGRAPHY = 3 -}; - -/** @brief Computes the Enhanced Correlation Coefficient value between two images @cite EP08 . - -@param templateImage single-channel template image; CV_8U or CV_32F array. -@param inputImage single-channel input image to be warped to provide an image similar to - templateImage, same type as templateImage. -@param inputMask An optional mask to indicate valid values of inputImage. - -@sa -findTransformECC - */ - -CV_EXPORTS_W double computeECC(InputArray templateImage, InputArray inputImage, InputArray inputMask = noArray()); - -/** @example samples/cpp/image_alignment.cpp -An example using the image alignment ECC algorithm -*/ - -/** @brief Finds the geometric transform (warp) between two images in terms of the ECC criterion @cite EP08 . - -@param templateImage single-channel template image; CV_8U or CV_32F array. -@param inputImage single-channel input image which should be warped with the final warpMatrix in -order to provide an image similar to templateImage, same type as templateImage. -@param warpMatrix floating-point \f$2\times 3\f$ or \f$3\times 3\f$ mapping matrix (warp). -@param motionType parameter, specifying the type of motion: - - **MOTION_TRANSLATION** sets a translational motion model; warpMatrix is \f$2\times 3\f$ with - the first \f$2\times 2\f$ part being the unity matrix and the rest two parameters being - estimated. - - **MOTION_EUCLIDEAN** sets a Euclidean (rigid) transformation as motion model; three - parameters are estimated; warpMatrix is \f$2\times 3\f$. - - **MOTION_AFFINE** sets an affine motion model (DEFAULT); six parameters are estimated; - warpMatrix is \f$2\times 3\f$. - - **MOTION_HOMOGRAPHY** sets a homography as a motion model; eight parameters are - estimated;\`warpMatrix\` is \f$3\times 3\f$. -@param criteria parameter, specifying the termination criteria of the ECC algorithm; -criteria.epsilon defines the threshold of the increment in the correlation coefficient between two -iterations (a negative criteria.epsilon makes criteria.maxcount the only termination criterion). -Default values are shown in the declaration above. -@param inputMask An optional mask to indicate valid values of inputImage. -@param gaussFiltSize An optional value indicating size of gaussian blur filter; (DEFAULT: 5) - -The function estimates the optimum transformation (warpMatrix) with respect to ECC criterion -(@cite EP08), that is - -\f[\texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f] - -where - -\f[\begin{bmatrix} x' \\ y' \end{bmatrix} = W \cdot \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}\f] - -(the equation holds with homogeneous coordinates for homography). It returns the final enhanced -correlation coefficient, that is the correlation coefficient between the template image and the -final warped input image. When a \f$3\times 3\f$ matrix is given with motionType =0, 1 or 2, the third -row is ignored. - -Unlike findHomography and estimateRigidTransform, the function findTransformECC implements an -area-based alignment that builds on intensity similarities. In essence, the function updates the -initial transformation that roughly aligns the images. If this information is missing, the identity -warp (unity matrix) is used as an initialization. Note that if images undergo strong -displacements/rotations, an initial transformation that roughly aligns the images is necessary -(e.g., a simple euclidean/similarity transform that allows for the images showing the same image -content approximately). Use inverse warping in the second image to take an image close to the first -one, i.e. use the flag WARP_INVERSE_MAP with warpAffine or warpPerspective. See also the OpenCV -sample image_alignment.cpp that demonstrates the use of the function. Note that the function throws -an exception if algorithm does not converges. - -@sa -computeECC, estimateAffine2D, estimateAffinePartial2D, findHomography - */ -CV_EXPORTS_W double findTransformECC( InputArray templateImage, InputArray inputImage, - InputOutputArray warpMatrix, int motionType, - TermCriteria criteria, - InputArray inputMask, int gaussFiltSize); - -/** @overload */ -CV_EXPORTS_W -double findTransformECC(InputArray templateImage, InputArray inputImage, - InputOutputArray warpMatrix, int motionType = MOTION_AFFINE, - TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), - InputArray inputMask = noArray()); - -/** @example samples/cpp/kalman.cpp -An example using the standard Kalman filter -*/ - -/** @brief Kalman filter class. - -The class implements a standard Kalman filter , -@cite Welch95 . However, you can modify transitionMatrix, controlMatrix, and measurementMatrix to get -an extended Kalman filter functionality. -@note In C API when CvKalman\* kalmanFilter structure is not needed anymore, it should be released -with cvReleaseKalman(&kalmanFilter) - */ -class CV_EXPORTS_W KalmanFilter -{ -public: - CV_WRAP KalmanFilter(); - /** @overload - @param dynamParams Dimensionality of the state. - @param measureParams Dimensionality of the measurement. - @param controlParams Dimensionality of the control vector. - @param type Type of the created matrices that should be CV_32F or CV_64F. - */ - CV_WRAP KalmanFilter( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); - - /** @brief Re-initializes Kalman filter. The previous content is destroyed. - - @param dynamParams Dimensionality of the state. - @param measureParams Dimensionality of the measurement. - @param controlParams Dimensionality of the control vector. - @param type Type of the created matrices that should be CV_32F or CV_64F. - */ - void init( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); - - /** @brief Computes a predicted state. - - @param control The optional input control - */ - CV_WRAP const Mat& predict( const Mat& control = Mat() ); - - /** @brief Updates the predicted state from the measurement. - - @param measurement The measured system parameters - */ - CV_WRAP const Mat& correct( const Mat& measurement ); - - CV_PROP_RW Mat statePre; //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k) - CV_PROP_RW Mat statePost; //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) - CV_PROP_RW Mat transitionMatrix; //!< state transition matrix (A) - CV_PROP_RW Mat controlMatrix; //!< control matrix (B) (not used if there is no control) - CV_PROP_RW Mat measurementMatrix; //!< measurement matrix (H) - CV_PROP_RW Mat processNoiseCov; //!< process noise covariance matrix (Q) - CV_PROP_RW Mat measurementNoiseCov;//!< measurement noise covariance matrix (R) - CV_PROP_RW Mat errorCovPre; //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/ - CV_PROP_RW Mat gain; //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R) - CV_PROP_RW Mat errorCovPost; //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) - - // temporary matrices - Mat temp1; - Mat temp2; - Mat temp3; - Mat temp4; - Mat temp5; -}; - - -/** @brief Read a .flo file - - @param path Path to the file to be loaded - - The function readOpticalFlow loads a flow field from a file and returns it as a single matrix. - Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the - flow in the horizontal direction (u), second - vertical (v). - */ -CV_EXPORTS_W Mat readOpticalFlow( const String& path ); -/** @brief Write a .flo to disk - - @param path Path to the file to be written - @param flow Flow field to be stored - - The function stores a flow field in a file, returns true on success, false otherwise. - The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds - to the flow in the horizontal direction (u), second - vertical (v). - */ -CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow ); - -/** - Base class for dense optical flow algorithms -*/ -class CV_EXPORTS_W DenseOpticalFlow : public Algorithm -{ -public: - /** @brief Calculates an optical flow. - - @param I0 first 8-bit single-channel input image. - @param I1 second input image of the same size and the same type as prev. - @param flow computed flow image that has the same size as prev and type CV_32FC2. - */ - CV_WRAP virtual void calc( InputArray I0, InputArray I1, InputOutputArray flow ) = 0; - /** @brief Releases all inner buffers. - */ - CV_WRAP virtual void collectGarbage() = 0; -}; - -/** @brief Base interface for sparse optical flow algorithms. - */ -class CV_EXPORTS_W SparseOpticalFlow : public Algorithm -{ -public: - /** @brief Calculates a sparse optical flow. - - @param prevImg First input image. - @param nextImg Second input image of the same size and the same type as prevImg. - @param prevPts Vector of 2D points for which the flow needs to be found. - @param nextPts Output vector of 2D points containing the calculated new positions of input features in the second image. - @param status Output status vector. Each element of the vector is set to 1 if the - flow for the corresponding features has been found. Otherwise, it is set to 0. - @param err Optional output vector that contains error response for each point (inverse confidence). - */ - CV_WRAP virtual void calc(InputArray prevImg, InputArray nextImg, - InputArray prevPts, InputOutputArray nextPts, - OutputArray status, - OutputArray err = cv::noArray()) = 0; -}; - - -/** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm. - */ -class CV_EXPORTS_W FarnebackOpticalFlow : public DenseOpticalFlow -{ -public: - CV_WRAP virtual int getNumLevels() const = 0; - CV_WRAP virtual void setNumLevels(int numLevels) = 0; - - CV_WRAP virtual double getPyrScale() const = 0; - CV_WRAP virtual void setPyrScale(double pyrScale) = 0; - - CV_WRAP virtual bool getFastPyramids() const = 0; - CV_WRAP virtual void setFastPyramids(bool fastPyramids) = 0; - - CV_WRAP virtual int getWinSize() const = 0; - CV_WRAP virtual void setWinSize(int winSize) = 0; - - CV_WRAP virtual int getNumIters() const = 0; - CV_WRAP virtual void setNumIters(int numIters) = 0; - - CV_WRAP virtual int getPolyN() const = 0; - CV_WRAP virtual void setPolyN(int polyN) = 0; - - CV_WRAP virtual double getPolySigma() const = 0; - CV_WRAP virtual void setPolySigma(double polySigma) = 0; - - CV_WRAP virtual int getFlags() const = 0; - CV_WRAP virtual void setFlags(int flags) = 0; - - CV_WRAP static Ptr create( - int numLevels = 5, - double pyrScale = 0.5, - bool fastPyramids = false, - int winSize = 13, - int numIters = 10, - int polyN = 5, - double polySigma = 1.1, - int flags = 0); -}; - -/** @brief Variational optical flow refinement - -This class implements variational refinement of the input flow field, i.e. -it uses input flow to initialize the minimization of the following functional: -\f$E(U) = \int_{\Omega} \delta \Psi(E_I) + \gamma \Psi(E_G) + \alpha \Psi(E_S) \f$, -where \f$E_I,E_G,E_S\f$ are color constancy, gradient constancy and smoothness terms -respectively. \f$\Psi(s^2)=\sqrt{s^2+\epsilon^2}\f$ is a robust penalizer to limit the -influence of outliers. A complete formulation and a description of the minimization -procedure can be found in @cite Brox2004 -*/ -class CV_EXPORTS_W VariationalRefinement : public DenseOpticalFlow -{ -public: - /** @brief @ref calc function overload to handle separate horizontal (u) and vertical (v) flow components - (to avoid extra splits/merges) */ - CV_WRAP virtual void calcUV(InputArray I0, InputArray I1, InputOutputArray flow_u, InputOutputArray flow_v) = 0; - - /** @brief Number of outer (fixed-point) iterations in the minimization procedure. - @see setFixedPointIterations */ - CV_WRAP virtual int getFixedPointIterations() const = 0; - /** @copybrief getFixedPointIterations @see getFixedPointIterations */ - CV_WRAP virtual void setFixedPointIterations(int val) = 0; - - /** @brief Number of inner successive over-relaxation (SOR) iterations - in the minimization procedure to solve the respective linear system. - @see setSorIterations */ - CV_WRAP virtual int getSorIterations() const = 0; - /** @copybrief getSorIterations @see getSorIterations */ - CV_WRAP virtual void setSorIterations(int val) = 0; - - /** @brief Relaxation factor in SOR - @see setOmega */ - CV_WRAP virtual float getOmega() const = 0; - /** @copybrief getOmega @see getOmega */ - CV_WRAP virtual void setOmega(float val) = 0; - - /** @brief Weight of the smoothness term - @see setAlpha */ - CV_WRAP virtual float getAlpha() const = 0; - /** @copybrief getAlpha @see getAlpha */ - CV_WRAP virtual void setAlpha(float val) = 0; - - /** @brief Weight of the color constancy term - @see setDelta */ - CV_WRAP virtual float getDelta() const = 0; - /** @copybrief getDelta @see getDelta */ - CV_WRAP virtual void setDelta(float val) = 0; - - /** @brief Weight of the gradient constancy term - @see setGamma */ - CV_WRAP virtual float getGamma() const = 0; - /** @copybrief getGamma @see getGamma */ - CV_WRAP virtual void setGamma(float val) = 0; - - /** @brief Norm value shift for robust penalizer - @see setEpsilon */ - CV_WRAP virtual float getEpsilon() const = 0; - /** @copybrief getEpsilon @see getEpsilon */ - CV_WRAP virtual void setEpsilon(float val) = 0; - - /** @brief Creates an instance of VariationalRefinement - */ - CV_WRAP static Ptr create(); -}; - -/** @brief DIS optical flow algorithm. - -This class implements the Dense Inverse Search (DIS) optical flow algorithm. More -details about the algorithm can be found at @cite Kroeger2016 . Includes three presets with preselected -parameters to provide reasonable trade-off between speed and quality. However, even the slowest preset is -still relatively fast, use DeepFlow if you need better quality and don't care about speed. - -This implementation includes several additional features compared to the algorithm described in the paper, -including spatial propagation of flow vectors (@ref getUseSpatialPropagation), as well as an option to -utilize an initial flow approximation passed to @ref calc (which is, essentially, temporal propagation, -if the previous frame's flow field is passed). -*/ -class CV_EXPORTS_W DISOpticalFlow : public DenseOpticalFlow -{ -public: - enum - { - PRESET_ULTRAFAST = 0, - PRESET_FAST = 1, - PRESET_MEDIUM = 2 - }; - - /** @brief Finest level of the Gaussian pyramid on which the flow is computed (zero level - corresponds to the original image resolution). The final flow is obtained by bilinear upscaling. - @see setFinestScale */ - CV_WRAP virtual int getFinestScale() const = 0; - /** @copybrief getFinestScale @see getFinestScale */ - CV_WRAP virtual void setFinestScale(int val) = 0; - - /** @brief Size of an image patch for matching (in pixels). Normally, default 8x8 patches work well - enough in most cases. - @see setPatchSize */ - CV_WRAP virtual int getPatchSize() const = 0; - /** @copybrief getPatchSize @see getPatchSize */ - CV_WRAP virtual void setPatchSize(int val) = 0; - - /** @brief Stride between neighbor patches. Must be less than patch size. Lower values correspond - to higher flow quality. - @see setPatchStride */ - CV_WRAP virtual int getPatchStride() const = 0; - /** @copybrief getPatchStride @see getPatchStride */ - CV_WRAP virtual void setPatchStride(int val) = 0; - - /** @brief Maximum number of gradient descent iterations in the patch inverse search stage. Higher values - may improve quality in some cases. - @see setGradientDescentIterations */ - CV_WRAP virtual int getGradientDescentIterations() const = 0; - /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ - CV_WRAP virtual void setGradientDescentIterations(int val) = 0; - - /** @brief Number of fixed point iterations of variational refinement per scale. Set to zero to - disable variational refinement completely. Higher values will typically result in more smooth and - high-quality flow. - @see setGradientDescentIterations */ - CV_WRAP virtual int getVariationalRefinementIterations() const = 0; - /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ - CV_WRAP virtual void setVariationalRefinementIterations(int val) = 0; - - /** @brief Weight of the smoothness term - @see setVariationalRefinementAlpha */ - CV_WRAP virtual float getVariationalRefinementAlpha() const = 0; - /** @copybrief getVariationalRefinementAlpha @see getVariationalRefinementAlpha */ - CV_WRAP virtual void setVariationalRefinementAlpha(float val) = 0; - - /** @brief Weight of the color constancy term - @see setVariationalRefinementDelta */ - CV_WRAP virtual float getVariationalRefinementDelta() const = 0; - /** @copybrief getVariationalRefinementDelta @see getVariationalRefinementDelta */ - CV_WRAP virtual void setVariationalRefinementDelta(float val) = 0; - - /** @brief Weight of the gradient constancy term - @see setVariationalRefinementGamma */ - CV_WRAP virtual float getVariationalRefinementGamma() const = 0; - /** @copybrief getVariationalRefinementGamma @see getVariationalRefinementGamma */ - CV_WRAP virtual void setVariationalRefinementGamma(float val) = 0; - - /** @brief Norm value shift for robust penalizer - @see setVariationalRefinementEpsilon */ - CV_WRAP virtual float getVariationalRefinementEpsilon() const = 0; - /** @copybrief getVariationalRefinementEpsilon @see getVariationalRefinementEpsilon */ - CV_WRAP virtual void setVariationalRefinementEpsilon(float val) = 0; - - - /** @brief Whether to use mean-normalization of patches when computing patch distance. It is turned on - by default as it typically provides a noticeable quality boost because of increased robustness to - illumination variations. Turn it off if you are certain that your sequence doesn't contain any changes - in illumination. - @see setUseMeanNormalization */ - CV_WRAP virtual bool getUseMeanNormalization() const = 0; - /** @copybrief getUseMeanNormalization @see getUseMeanNormalization */ - CV_WRAP virtual void setUseMeanNormalization(bool val) = 0; - - /** @brief Whether to use spatial propagation of good optical flow vectors. This option is turned on by - default, as it tends to work better on average and can sometimes help recover from major errors - introduced by the coarse-to-fine scheme employed by the DIS optical flow algorithm. Turning this - option off can make the output flow field a bit smoother, however. - @see setUseSpatialPropagation */ - CV_WRAP virtual bool getUseSpatialPropagation() const = 0; - /** @copybrief getUseSpatialPropagation @see getUseSpatialPropagation */ - CV_WRAP virtual void setUseSpatialPropagation(bool val) = 0; - - /** @brief Creates an instance of DISOpticalFlow - - @param preset one of PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM - */ - CV_WRAP static Ptr create(int preset = DISOpticalFlow::PRESET_FAST); -}; - -/** @brief Class used for calculating a sparse optical flow. - -The class can calculate an optical flow for a sparse feature set using the -iterative Lucas-Kanade method with pyramids. - -@sa calcOpticalFlowPyrLK - -*/ -class CV_EXPORTS_W SparsePyrLKOpticalFlow : public SparseOpticalFlow -{ -public: - CV_WRAP virtual Size getWinSize() const = 0; - CV_WRAP virtual void setWinSize(Size winSize) = 0; - - CV_WRAP virtual int getMaxLevel() const = 0; - CV_WRAP virtual void setMaxLevel(int maxLevel) = 0; - - CV_WRAP virtual TermCriteria getTermCriteria() const = 0; - CV_WRAP virtual void setTermCriteria(TermCriteria& crit) = 0; - - CV_WRAP virtual int getFlags() const = 0; - CV_WRAP virtual void setFlags(int flags) = 0; - - CV_WRAP virtual double getMinEigThreshold() const = 0; - CV_WRAP virtual void setMinEigThreshold(double minEigThreshold) = 0; - - CV_WRAP static Ptr create( - Size winSize = Size(21, 21), - int maxLevel = 3, TermCriteria crit = - TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), - int flags = 0, - double minEigThreshold = 1e-4); -}; - - - - -/** @brief Base abstract class for the long-term tracker - */ -class CV_EXPORTS_W Tracker -{ -protected: - Tracker(); -public: - virtual ~Tracker(); - - /** @brief Initialize the tracker with a known bounding box that surrounded the target - @param image The initial frame - @param boundingBox The initial bounding box - */ - CV_WRAP virtual - void init(InputArray image, const Rect& boundingBox) = 0; - - /** @brief Update the tracker, find the new most likely bounding box for the target - @param image The current frame - @param boundingBox The bounding box that represent the new target location, if true was returned, not - modified otherwise - - @return True means that target was located and false means that tracker cannot locate target in - current frame. Note, that latter *does not* imply that tracker has failed, maybe target is indeed - missing from the frame (say, out of sight) - */ - CV_WRAP virtual - bool update(InputArray image, CV_OUT Rect& boundingBox) = 0; -}; - - - -/** @brief The MIL algorithm trains a classifier in an online manner to separate the object from the -background. - -Multiple Instance Learning avoids the drift problem for a robust tracking. The implementation is -based on @cite MIL . - -Original code can be found here - */ -class CV_EXPORTS_W TrackerMIL : public Tracker -{ -protected: - TrackerMIL(); // use ::create() -public: - virtual ~TrackerMIL() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - //parameters for sampler - CV_PROP_RW float samplerInitInRadius; //!< radius for gathering positive instances during init - CV_PROP_RW int samplerInitMaxNegNum; //!< # negative samples to use during init - CV_PROP_RW float samplerSearchWinSize; //!< size of search window - CV_PROP_RW float samplerTrackInRadius; //!< radius for gathering positive instances during tracking - CV_PROP_RW int samplerTrackMaxPosNum; //!< # positive samples to use during tracking - CV_PROP_RW int samplerTrackMaxNegNum; //!< # negative samples to use during tracking - CV_PROP_RW int featureSetNumFeatures; //!< # features - }; - - /** @brief Create MIL tracker instance - * @param parameters MIL parameters TrackerMIL::Params - */ - static CV_WRAP - Ptr create(const TrackerMIL::Params ¶meters = TrackerMIL::Params()); - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - - - -/** @brief the GOTURN (Generic Object Tracking Using Regression Networks) tracker - * - * GOTURN (@cite GOTURN) is kind of trackers based on Convolutional Neural Networks (CNN). While taking all advantages of CNN trackers, - * GOTURN is much faster due to offline training without online fine-tuning nature. - * GOTURN tracker addresses the problem of single target tracking: given a bounding box label of an object in the first frame of the video, - * we track that object through the rest of the video. NOTE: Current method of GOTURN does not handle occlusions; however, it is fairly - * robust to viewpoint changes, lighting changes, and deformations. - * Inputs of GOTURN are two RGB patches representing Target and Search patches resized to 227x227. - * Outputs of GOTURN are predicted bounding box coordinates, relative to Search patch coordinate system, in format X1,Y1,X2,Y2. - * Original paper is here: - * As long as original authors implementation: - * Implementation of training algorithm is placed in separately here due to 3d-party dependencies: - * - * GOTURN architecture goturn.prototxt and trained model goturn.caffemodel are accessible on opencv_extra GitHub repository. - */ -class CV_EXPORTS_W TrackerGOTURN : public Tracker -{ -protected: - TrackerGOTURN(); // use ::create() -public: - virtual ~TrackerGOTURN() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string modelTxt; - CV_PROP_RW std::string modelBin; - }; - - /** @brief Constructor - @param parameters GOTURN parameters TrackerGOTURN::Params - */ - static CV_WRAP - Ptr create(const TrackerGOTURN::Params& parameters = TrackerGOTURN::Params()); - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -class CV_EXPORTS_W TrackerDaSiamRPN : public Tracker -{ -protected: - TrackerDaSiamRPN(); // use ::create() -public: - virtual ~TrackerDaSiamRPN() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string model; - CV_PROP_RW std::string kernel_cls1; - CV_PROP_RW std::string kernel_r1; - CV_PROP_RW int backend; - CV_PROP_RW int target; - }; - - /** @brief Constructor - @param parameters DaSiamRPN parameters TrackerDaSiamRPN::Params - */ - static CV_WRAP - Ptr create(const TrackerDaSiamRPN::Params& parameters = TrackerDaSiamRPN::Params()); - - /** @brief Return tracking score - */ - CV_WRAP virtual float getTrackingScore() = 0; - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -/** @brief the Nano tracker is a super lightweight dnn-based general object tracking. - * - * Nano tracker is much faster and extremely lightweight due to special model structure, the whole model size is about 1.9 MB. - * Nano tracker needs two models: one for feature extraction (backbone) and the another for localization (neckhead). - * Model download link: https://github.com/HonglinChu/SiamTrackers/tree/master/NanoTrack/models/nanotrackv2 - * Original repo is here: https://github.com/HonglinChu/NanoTrack - * Author: HongLinChu, 1628464345@qq.com - */ -class CV_EXPORTS_W TrackerNano : public Tracker -{ -protected: - TrackerNano(); // use ::create() -public: - virtual ~TrackerNano() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string backbone; - CV_PROP_RW std::string neckhead; - CV_PROP_RW int backend; - CV_PROP_RW int target; - }; - - /** @brief Constructor - @param parameters NanoTrack parameters TrackerNano::Params - */ - static CV_WRAP - Ptr create(const TrackerNano::Params& parameters = TrackerNano::Params()); - - /** @brief Return tracking score - */ - CV_WRAP virtual float getTrackingScore() = 0; - - //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -/** @brief the VIT tracker is a super lightweight dnn-based general object tracking. - * - * VIT tracker is much faster and extremely lightweight due to special model structure, the model file is about 767KB. - * Model download link: https://github.com/opencv/opencv_zoo/tree/main/models/object_tracking_vittrack - * Author: PengyuLiu, 1872918507@qq.com - */ -class CV_EXPORTS_W TrackerVit : public Tracker -{ -protected: - TrackerVit(); // use ::create() -public: - virtual ~TrackerVit() CV_OVERRIDE; - - struct CV_EXPORTS_W_SIMPLE Params - { - CV_WRAP Params(); - CV_PROP_RW std::string net; - CV_PROP_RW int backend; - CV_PROP_RW int target; - CV_PROP_RW Scalar meanvalue; - CV_PROP_RW Scalar stdvalue; - CV_PROP_RW float tracking_score_threshold; - }; - - /** @brief Constructor - @param parameters vit tracker parameters TrackerVit::Params - */ - static CV_WRAP - Ptr create(const TrackerVit::Params& parameters = TrackerVit::Params()); - - /** @brief Return tracking score - */ - CV_WRAP virtual float getTrackingScore() = 0; - - // void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; - // bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; -}; - -//! @} video_track - -} // cv - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_TRACKING_HPP +#define OPENCV_TRACKING_HPP + +#include "opencv2/core.hpp" +#include "opencv2/imgproc.hpp" + +namespace cv +{ + +//! @addtogroup video_track +//! @{ + +enum { OPTFLOW_USE_INITIAL_FLOW = 4, + OPTFLOW_LK_GET_MIN_EIGENVALS = 8, + OPTFLOW_FARNEBACK_GAUSSIAN = 256 + }; + +/** @brief Finds an object center, size, and orientation. + +@param probImage Back projection of the object histogram. See calcBackProject. +@param window Initial search window. +@param criteria Stop criteria for the underlying meanShift. +returns +(in old interfaces) Number of iterations CAMSHIFT took to converge +The function implements the CAMSHIFT object tracking algorithm @cite Bradski98 . First, it finds an +object center using meanShift and then adjusts the window size and finds the optimal rotation. The +function returns the rotated rectangle structure that includes the object position, size, and +orientation. The next position of the search window can be obtained with RotatedRect::boundingRect() + +See the OpenCV sample camshiftdemo.c that tracks colored objects. + +@note +- (Python) A sample explaining the camshift tracking algorithm can be found at + opencv_source_code/samples/python/camshift.py + */ +CV_EXPORTS_W RotatedRect CamShift( InputArray probImage, CV_IN_OUT Rect& window, + TermCriteria criteria ); +/** @example samples/cpp/camshiftdemo.cpp +An example using the mean-shift tracking algorithm +*/ + +/** @brief Finds an object on a back projection image. + +@param probImage Back projection of the object histogram. See calcBackProject for details. +@param window Initial search window. +@param criteria Stop criteria for the iterative search algorithm. +returns +: Number of iterations CAMSHIFT took to converge. +The function implements the iterative object search algorithm. It takes the input back projection of +an object and the initial position. The mass center in window of the back projection image is +computed and the search window center shifts to the mass center. The procedure is repeated until the +specified number of iterations criteria.maxCount is done or until the window center shifts by less +than criteria.epsilon. The algorithm is used inside CamShift and, unlike CamShift , the search +window size or orientation do not change during the search. You can simply pass the output of +calcBackProject to this function. But better results can be obtained if you pre-filter the back +projection and remove the noise. For example, you can do this by retrieving connected components +with findContours , throwing away contours with small area ( contourArea ), and rendering the +remaining contours with drawContours. + + */ +CV_EXPORTS_W int meanShift( InputArray probImage, CV_IN_OUT Rect& window, TermCriteria criteria ); + +/** @brief Constructs the image pyramid which can be passed to calcOpticalFlowPyrLK. + +@param img 8-bit input image. +@param pyramid output pyramid. +@param winSize window size of optical flow algorithm. Must be not less than winSize argument of +calcOpticalFlowPyrLK. It is needed to calculate required padding for pyramid levels. +@param maxLevel 0-based maximal pyramid level number. +@param withDerivatives set to precompute gradients for the every pyramid level. If pyramid is +constructed without the gradients then calcOpticalFlowPyrLK will calculate them internally. +@param pyrBorder the border mode for pyramid layers. +@param derivBorder the border mode for gradients. +@param tryReuseInputImage put ROI of input image into the pyramid if possible. You can pass false +to force data copying. +@return number of levels in constructed pyramid. Can be less than maxLevel. + */ +CV_EXPORTS_W int buildOpticalFlowPyramid( InputArray img, OutputArrayOfArrays pyramid, + Size winSize, int maxLevel, bool withDerivatives = true, + int pyrBorder = BORDER_REFLECT_101, + int derivBorder = BORDER_CONSTANT, + bool tryReuseInputImage = true ); + +/** @example samples/cpp/lkdemo.cpp +An example using the Lucas-Kanade optical flow algorithm +*/ + +/** @brief Calculates an optical flow for a sparse feature set using the iterative Lucas-Kanade method with +pyramids. + +@param prevImg first 8-bit input image or pyramid constructed by buildOpticalFlowPyramid. +@param nextImg second input image or pyramid of the same size and the same type as prevImg. +@param prevPts vector of 2D points for which the flow needs to be found; point coordinates must be +single-precision floating-point numbers. +@param nextPts output vector of 2D points (with single-precision floating-point coordinates) +containing the calculated new positions of input features in the second image; when +OPTFLOW_USE_INITIAL_FLOW flag is passed, the vector must have the same size as in the input. +@param status output status vector (of unsigned chars); each element of the vector is set to 1 if +the flow for the corresponding features has been found, otherwise, it is set to 0. +@param err output vector of errors; each element of the vector is set to an error for the +corresponding feature, type of the error measure can be set in flags parameter; if the flow wasn't +found then the error is not defined (use the status parameter to find such cases). +@param winSize size of the search window at each pyramid level. +@param maxLevel 0-based maximal pyramid level number; if set to 0, pyramids are not used (single +level), if set to 1, two levels are used, and so on; if pyramids are passed to input then +algorithm will use as many levels as pyramids have but no more than maxLevel. +@param criteria parameter, specifying the termination criteria of the iterative search algorithm +(after the specified maximum number of iterations criteria.maxCount or when the search window +moves by less than criteria.epsilon. +@param flags operation flags: + - **OPTFLOW_USE_INITIAL_FLOW** uses initial estimations, stored in nextPts; if the flag is + not set, then prevPts is copied to nextPts and is considered the initial estimate. + - **OPTFLOW_LK_GET_MIN_EIGENVALS** use minimum eigen values as an error measure (see + minEigThreshold description); if the flag is not set, then L1 distance between patches + around the original and a moved point, divided by number of pixels in a window, is used as a + error measure. +@param minEigThreshold the algorithm calculates the minimum eigen value of a 2x2 normal matrix of +optical flow equations (this matrix is called a spatial gradient matrix in @cite Bouguet00), divided +by number of pixels in a window; if this value is less than minEigThreshold, then a corresponding +feature is filtered out and its flow is not processed, so it allows to remove bad points and get a +performance boost. + +The function implements a sparse iterative version of the Lucas-Kanade optical flow in pyramids. See +@cite Bouguet00 . The function is parallelized with the TBB library. + +@note Some examples: + +- An example using the Lucas-Kanade optical flow algorithm can be found at + opencv_source_code/samples/cpp/lkdemo.cpp +- (Python) An example using the Lucas-Kanade optical flow algorithm can be found at + opencv_source_code/samples/python/lk_track.py +- (Python) An example using the Lucas-Kanade tracker for homography matching can be found at + opencv_source_code/samples/python/lk_homography.py + */ +CV_EXPORTS_W void calcOpticalFlowPyrLK( InputArray prevImg, InputArray nextImg, + InputArray prevPts, InputOutputArray nextPts, + OutputArray status, OutputArray err, + Size winSize = Size(21,21), int maxLevel = 3, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), + int flags = 0, double minEigThreshold = 1e-4 ); + +/** @brief Computes a dense optical flow using the Gunnar Farneback's algorithm. + +@param prev first 8-bit single-channel input image. +@param next second input image of the same size and the same type as prev. +@param flow computed flow image that has the same size as prev and type CV_32FC2. +@param pyr_scale parameter, specifying the image scale (\<1) to build pyramids for each image; +pyr_scale=0.5 means a classical pyramid, where each next layer is twice smaller than the previous +one. +@param levels number of pyramid layers including the initial image; levels=1 means that no extra +layers are created and only the original images are used. +@param winsize averaging window size; larger values increase the algorithm robustness to image +noise and give more chances for fast motion detection, but yield more blurred motion field. +@param iterations number of iterations the algorithm does at each pyramid level. +@param poly_n size of the pixel neighborhood used to find polynomial expansion in each pixel; +larger values mean that the image will be approximated with smoother surfaces, yielding more +robust algorithm and more blurred motion field, typically poly_n =5 or 7. +@param poly_sigma standard deviation of the Gaussian that is used to smooth derivatives used as a +basis for the polynomial expansion; for poly_n=5, you can set poly_sigma=1.1, for poly_n=7, a +good value would be poly_sigma=1.5. +@param flags operation flags that can be a combination of the following: + - **OPTFLOW_USE_INITIAL_FLOW** uses the input flow as an initial flow approximation. + - **OPTFLOW_FARNEBACK_GAUSSIAN** uses the Gaussian \f$\texttt{winsize}\times\texttt{winsize}\f$ + filter instead of a box filter of the same size for optical flow estimation; usually, this + option gives z more accurate flow than with a box filter, at the cost of lower speed; + normally, winsize for a Gaussian window should be set to a larger value to achieve the same + level of robustness. + +The function finds an optical flow for each prev pixel using the @cite Farneback2003 algorithm so that + +\f[\texttt{prev} (y,x) \sim \texttt{next} ( y + \texttt{flow} (y,x)[1], x + \texttt{flow} (y,x)[0])\f] + +@note Some examples: + +- An example using the optical flow algorithm described by Gunnar Farneback can be found at + opencv_source_code/samples/cpp/fback.cpp +- (Python) An example using the optical flow algorithm described by Gunnar Farneback can be + found at opencv_source_code/samples/python/opt_flow.py + */ +CV_EXPORTS_W void calcOpticalFlowFarneback( InputArray prev, InputArray next, InputOutputArray flow, + double pyr_scale, int levels, int winsize, + int iterations, int poly_n, double poly_sigma, + int flags ); + +/** @brief Computes an optimal affine transformation between two 2D point sets. + +@param src First input 2D point set stored in std::vector or Mat, or an image stored in Mat. +@param dst Second input 2D point set of the same size and the same type as A, or another image. +@param fullAffine If true, the function finds an optimal affine transformation with no additional +restrictions (6 degrees of freedom). Otherwise, the class of transformations to choose from is +limited to combinations of translation, rotation, and uniform scaling (4 degrees of freedom). + +The function finds an optimal affine transform *[A|b]* (a 2 x 3 floating-point matrix) that +approximates best the affine transformation between: + +* Two point sets +* Two raster images. In this case, the function first finds some features in the src image and + finds the corresponding features in dst image. After that, the problem is reduced to the first + case. +In case of point sets, the problem is formulated as follows: you need to find a 2x2 matrix *A* and +2x1 vector *b* so that: + +\f[[A^*|b^*] = arg \min _{[A|b]} \sum _i \| \texttt{dst}[i] - A { \texttt{src}[i]}^T - b \| ^2\f] +where src[i] and dst[i] are the i-th points in src and dst, respectively +\f$[A|b]\f$ can be either arbitrary (when fullAffine=true ) or have a form of +\f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ -a_{12} & a_{11} & b_2 \end{bmatrix}\f] +when fullAffine=false. + +@deprecated Use cv::estimateAffine2D, cv::estimateAffinePartial2D instead. If you are using this function +with images, extract points using cv::calcOpticalFlowPyrLK and then use the estimation functions. + +@sa +estimateAffine2D, estimateAffinePartial2D, getAffineTransform, getPerspectiveTransform, findHomography + */ +CV_DEPRECATED CV_EXPORTS Mat estimateRigidTransform( InputArray src, InputArray dst, bool fullAffine ); + +enum +{ + MOTION_TRANSLATION = 0, + MOTION_EUCLIDEAN = 1, + MOTION_AFFINE = 2, + MOTION_HOMOGRAPHY = 3 +}; + +/** @brief Computes the Enhanced Correlation Coefficient value between two images @cite EP08 . + +@param templateImage single-channel template image; CV_8U or CV_32F array. +@param inputImage single-channel input image to be warped to provide an image similar to + templateImage, same type as templateImage. +@param inputMask An optional mask to indicate valid values of inputImage. + +@sa +findTransformECC + */ + +CV_EXPORTS_W double computeECC(InputArray templateImage, InputArray inputImage, InputArray inputMask = noArray()); + +/** @example samples/cpp/image_alignment.cpp +An example using the image alignment ECC algorithm +*/ + +/** @brief Finds the geometric transform (warp) between two images in terms of the ECC criterion @cite EP08 . + +@param templateImage single-channel template image; CV_8U or CV_32F array. +@param inputImage single-channel input image which should be warped with the final warpMatrix in +order to provide an image similar to templateImage, same type as templateImage. +@param warpMatrix floating-point \f$2\times 3\f$ or \f$3\times 3\f$ mapping matrix (warp). +@param motionType parameter, specifying the type of motion: + - **MOTION_TRANSLATION** sets a translational motion model; warpMatrix is \f$2\times 3\f$ with + the first \f$2\times 2\f$ part being the unity matrix and the rest two parameters being + estimated. + - **MOTION_EUCLIDEAN** sets a Euclidean (rigid) transformation as motion model; three + parameters are estimated; warpMatrix is \f$2\times 3\f$. + - **MOTION_AFFINE** sets an affine motion model (DEFAULT); six parameters are estimated; + warpMatrix is \f$2\times 3\f$. + - **MOTION_HOMOGRAPHY** sets a homography as a motion model; eight parameters are + estimated;\`warpMatrix\` is \f$3\times 3\f$. +@param criteria parameter, specifying the termination criteria of the ECC algorithm; +criteria.epsilon defines the threshold of the increment in the correlation coefficient between two +iterations (a negative criteria.epsilon makes criteria.maxcount the only termination criterion). +Default values are shown in the declaration above. +@param inputMask An optional mask to indicate valid values of inputImage. +@param gaussFiltSize An optional value indicating size of gaussian blur filter; (DEFAULT: 5) + +The function estimates the optimum transformation (warpMatrix) with respect to ECC criterion +(@cite EP08), that is + +\f[\texttt{warpMatrix} = \arg\max_{W} \texttt{ECC}(\texttt{templateImage}(x,y),\texttt{inputImage}(x',y'))\f] + +where + +\f[\begin{bmatrix} x' \\ y' \end{bmatrix} = W \cdot \begin{bmatrix} x \\ y \\ 1 \end{bmatrix}\f] + +(the equation holds with homogeneous coordinates for homography). It returns the final enhanced +correlation coefficient, that is the correlation coefficient between the template image and the +final warped input image. When a \f$3\times 3\f$ matrix is given with motionType =0, 1 or 2, the third +row is ignored. + +Unlike findHomography and estimateRigidTransform, the function findTransformECC implements an +area-based alignment that builds on intensity similarities. In essence, the function updates the +initial transformation that roughly aligns the images. If this information is missing, the identity +warp (unity matrix) is used as an initialization. Note that if images undergo strong +displacements/rotations, an initial transformation that roughly aligns the images is necessary +(e.g., a simple euclidean/similarity transform that allows for the images showing the same image +content approximately). Use inverse warping in the second image to take an image close to the first +one, i.e. use the flag WARP_INVERSE_MAP with warpAffine or warpPerspective. See also the OpenCV +sample image_alignment.cpp that demonstrates the use of the function. Note that the function throws +an exception if algorithm does not converges. + +@sa +computeECC, estimateAffine2D, estimateAffinePartial2D, findHomography + */ +CV_EXPORTS_W double findTransformECC( InputArray templateImage, InputArray inputImage, + InputOutputArray warpMatrix, int motionType, + TermCriteria criteria, + InputArray inputMask, int gaussFiltSize); + +/** @overload */ +CV_EXPORTS_W +double findTransformECC(InputArray templateImage, InputArray inputImage, + InputOutputArray warpMatrix, int motionType = MOTION_AFFINE, + TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), + InputArray inputMask = noArray()); + +/** @example samples/cpp/kalman.cpp +An example using the standard Kalman filter +*/ + +/** @brief Kalman filter class. + +The class implements a standard Kalman filter , +@cite Welch95 . However, you can modify transitionMatrix, controlMatrix, and measurementMatrix to get +an extended Kalman filter functionality. +@note In C API when CvKalman\* kalmanFilter structure is not needed anymore, it should be released +with cvReleaseKalman(&kalmanFilter) + */ +class CV_EXPORTS_W KalmanFilter +{ +public: + CV_WRAP KalmanFilter(); + /** @overload + @param dynamParams Dimensionality of the state. + @param measureParams Dimensionality of the measurement. + @param controlParams Dimensionality of the control vector. + @param type Type of the created matrices that should be CV_32F or CV_64F. + */ + CV_WRAP KalmanFilter( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); + + /** @brief Re-initializes Kalman filter. The previous content is destroyed. + + @param dynamParams Dimensionality of the state. + @param measureParams Dimensionality of the measurement. + @param controlParams Dimensionality of the control vector. + @param type Type of the created matrices that should be CV_32F or CV_64F. + */ + void init( int dynamParams, int measureParams, int controlParams = 0, int type = CV_32F ); + + /** @brief Computes a predicted state. + + @param control The optional input control + */ + CV_WRAP const Mat& predict( const Mat& control = Mat() ); + + /** @brief Updates the predicted state from the measurement. + + @param measurement The measured system parameters + */ + CV_WRAP const Mat& correct( const Mat& measurement ); + + CV_PROP_RW Mat statePre; //!< predicted state (x'(k)): x(k)=A*x(k-1)+B*u(k) + CV_PROP_RW Mat statePost; //!< corrected state (x(k)): x(k)=x'(k)+K(k)*(z(k)-H*x'(k)) + CV_PROP_RW Mat transitionMatrix; //!< state transition matrix (A) + CV_PROP_RW Mat controlMatrix; //!< control matrix (B) (not used if there is no control) + CV_PROP_RW Mat measurementMatrix; //!< measurement matrix (H) + CV_PROP_RW Mat processNoiseCov; //!< process noise covariance matrix (Q) + CV_PROP_RW Mat measurementNoiseCov;//!< measurement noise covariance matrix (R) + CV_PROP_RW Mat errorCovPre; //!< priori error estimate covariance matrix (P'(k)): P'(k)=A*P(k-1)*At + Q)*/ + CV_PROP_RW Mat gain; //!< Kalman gain matrix (K(k)): K(k)=P'(k)*Ht*inv(H*P'(k)*Ht+R) + CV_PROP_RW Mat errorCovPost; //!< posteriori error estimate covariance matrix (P(k)): P(k)=(I-K(k)*H)*P'(k) + + // temporary matrices + Mat temp1; + Mat temp2; + Mat temp3; + Mat temp4; + Mat temp5; +}; + + +/** @brief Read a .flo file + + @param path Path to the file to be loaded + + The function readOpticalFlow loads a flow field from a file and returns it as a single matrix. + Resulting Mat has a type CV_32FC2 - floating-point, 2-channel. First channel corresponds to the + flow in the horizontal direction (u), second - vertical (v). + */ +CV_EXPORTS_W Mat readOpticalFlow( const String& path ); +/** @brief Write a .flo to disk + + @param path Path to the file to be written + @param flow Flow field to be stored + + The function stores a flow field in a file, returns true on success, false otherwise. + The flow field must be a 2-channel, floating-point matrix (CV_32FC2). First channel corresponds + to the flow in the horizontal direction (u), second - vertical (v). + */ +CV_EXPORTS_W bool writeOpticalFlow( const String& path, InputArray flow ); + +/** + Base class for dense optical flow algorithms +*/ +class CV_EXPORTS_W DenseOpticalFlow : public Algorithm +{ +public: + /** @brief Calculates an optical flow. + + @param I0 first 8-bit single-channel input image. + @param I1 second input image of the same size and the same type as prev. + @param flow computed flow image that has the same size as prev and type CV_32FC2. + */ + CV_WRAP virtual void calc( InputArray I0, InputArray I1, InputOutputArray flow ) = 0; + /** @brief Releases all inner buffers. + */ + CV_WRAP virtual void collectGarbage() = 0; +}; + +/** @brief Base interface for sparse optical flow algorithms. + */ +class CV_EXPORTS_W SparseOpticalFlow : public Algorithm +{ +public: + /** @brief Calculates a sparse optical flow. + + @param prevImg First input image. + @param nextImg Second input image of the same size and the same type as prevImg. + @param prevPts Vector of 2D points for which the flow needs to be found. + @param nextPts Output vector of 2D points containing the calculated new positions of input features in the second image. + @param status Output status vector. Each element of the vector is set to 1 if the + flow for the corresponding features has been found. Otherwise, it is set to 0. + @param err Optional output vector that contains error response for each point (inverse confidence). + */ + CV_WRAP virtual void calc(InputArray prevImg, InputArray nextImg, + InputArray prevPts, InputOutputArray nextPts, + OutputArray status, + OutputArray err = cv::noArray()) = 0; +}; + + +/** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm. + */ +class CV_EXPORTS_W FarnebackOpticalFlow : public DenseOpticalFlow +{ +public: + CV_WRAP virtual int getNumLevels() const = 0; + CV_WRAP virtual void setNumLevels(int numLevels) = 0; + + CV_WRAP virtual double getPyrScale() const = 0; + CV_WRAP virtual void setPyrScale(double pyrScale) = 0; + + CV_WRAP virtual bool getFastPyramids() const = 0; + CV_WRAP virtual void setFastPyramids(bool fastPyramids) = 0; + + CV_WRAP virtual int getWinSize() const = 0; + CV_WRAP virtual void setWinSize(int winSize) = 0; + + CV_WRAP virtual int getNumIters() const = 0; + CV_WRAP virtual void setNumIters(int numIters) = 0; + + CV_WRAP virtual int getPolyN() const = 0; + CV_WRAP virtual void setPolyN(int polyN) = 0; + + CV_WRAP virtual double getPolySigma() const = 0; + CV_WRAP virtual void setPolySigma(double polySigma) = 0; + + CV_WRAP virtual int getFlags() const = 0; + CV_WRAP virtual void setFlags(int flags) = 0; + + CV_WRAP static Ptr create( + int numLevels = 5, + double pyrScale = 0.5, + bool fastPyramids = false, + int winSize = 13, + int numIters = 10, + int polyN = 5, + double polySigma = 1.1, + int flags = 0); +}; + +/** @brief Variational optical flow refinement + +This class implements variational refinement of the input flow field, i.e. +it uses input flow to initialize the minimization of the following functional: +\f$E(U) = \int_{\Omega} \delta \Psi(E_I) + \gamma \Psi(E_G) + \alpha \Psi(E_S) \f$, +where \f$E_I,E_G,E_S\f$ are color constancy, gradient constancy and smoothness terms +respectively. \f$\Psi(s^2)=\sqrt{s^2+\epsilon^2}\f$ is a robust penalizer to limit the +influence of outliers. A complete formulation and a description of the minimization +procedure can be found in @cite Brox2004 +*/ +class CV_EXPORTS_W VariationalRefinement : public DenseOpticalFlow +{ +public: + /** @brief @ref calc function overload to handle separate horizontal (u) and vertical (v) flow components + (to avoid extra splits/merges) */ + CV_WRAP virtual void calcUV(InputArray I0, InputArray I1, InputOutputArray flow_u, InputOutputArray flow_v) = 0; + + /** @brief Number of outer (fixed-point) iterations in the minimization procedure. + @see setFixedPointIterations */ + CV_WRAP virtual int getFixedPointIterations() const = 0; + /** @copybrief getFixedPointIterations @see getFixedPointIterations */ + CV_WRAP virtual void setFixedPointIterations(int val) = 0; + + /** @brief Number of inner successive over-relaxation (SOR) iterations + in the minimization procedure to solve the respective linear system. + @see setSorIterations */ + CV_WRAP virtual int getSorIterations() const = 0; + /** @copybrief getSorIterations @see getSorIterations */ + CV_WRAP virtual void setSorIterations(int val) = 0; + + /** @brief Relaxation factor in SOR + @see setOmega */ + CV_WRAP virtual float getOmega() const = 0; + /** @copybrief getOmega @see getOmega */ + CV_WRAP virtual void setOmega(float val) = 0; + + /** @brief Weight of the smoothness term + @see setAlpha */ + CV_WRAP virtual float getAlpha() const = 0; + /** @copybrief getAlpha @see getAlpha */ + CV_WRAP virtual void setAlpha(float val) = 0; + + /** @brief Weight of the color constancy term + @see setDelta */ + CV_WRAP virtual float getDelta() const = 0; + /** @copybrief getDelta @see getDelta */ + CV_WRAP virtual void setDelta(float val) = 0; + + /** @brief Weight of the gradient constancy term + @see setGamma */ + CV_WRAP virtual float getGamma() const = 0; + /** @copybrief getGamma @see getGamma */ + CV_WRAP virtual void setGamma(float val) = 0; + + /** @brief Norm value shift for robust penalizer + @see setEpsilon */ + CV_WRAP virtual float getEpsilon() const = 0; + /** @copybrief getEpsilon @see getEpsilon */ + CV_WRAP virtual void setEpsilon(float val) = 0; + + /** @brief Creates an instance of VariationalRefinement + */ + CV_WRAP static Ptr create(); +}; + +/** @brief DIS optical flow algorithm. + +This class implements the Dense Inverse Search (DIS) optical flow algorithm. More +details about the algorithm can be found at @cite Kroeger2016 . Includes three presets with preselected +parameters to provide reasonable trade-off between speed and quality. However, even the slowest preset is +still relatively fast, use DeepFlow if you need better quality and don't care about speed. + +This implementation includes several additional features compared to the algorithm described in the paper, +including spatial propagation of flow vectors (@ref getUseSpatialPropagation), as well as an option to +utilize an initial flow approximation passed to @ref calc (which is, essentially, temporal propagation, +if the previous frame's flow field is passed). +*/ +class CV_EXPORTS_W DISOpticalFlow : public DenseOpticalFlow +{ +public: + enum + { + PRESET_ULTRAFAST = 0, + PRESET_FAST = 1, + PRESET_MEDIUM = 2 + }; + + /** @brief Finest level of the Gaussian pyramid on which the flow is computed (zero level + corresponds to the original image resolution). The final flow is obtained by bilinear upscaling. + @see setFinestScale */ + CV_WRAP virtual int getFinestScale() const = 0; + /** @copybrief getFinestScale @see getFinestScale */ + CV_WRAP virtual void setFinestScale(int val) = 0; + + /** @brief Size of an image patch for matching (in pixels). Normally, default 8x8 patches work well + enough in most cases. + @see setPatchSize */ + CV_WRAP virtual int getPatchSize() const = 0; + /** @copybrief getPatchSize @see getPatchSize */ + CV_WRAP virtual void setPatchSize(int val) = 0; + + /** @brief Stride between neighbor patches. Must be less than patch size. Lower values correspond + to higher flow quality. + @see setPatchStride */ + CV_WRAP virtual int getPatchStride() const = 0; + /** @copybrief getPatchStride @see getPatchStride */ + CV_WRAP virtual void setPatchStride(int val) = 0; + + /** @brief Maximum number of gradient descent iterations in the patch inverse search stage. Higher values + may improve quality in some cases. + @see setGradientDescentIterations */ + CV_WRAP virtual int getGradientDescentIterations() const = 0; + /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ + CV_WRAP virtual void setGradientDescentIterations(int val) = 0; + + /** @brief Number of fixed point iterations of variational refinement per scale. Set to zero to + disable variational refinement completely. Higher values will typically result in more smooth and + high-quality flow. + @see setGradientDescentIterations */ + CV_WRAP virtual int getVariationalRefinementIterations() const = 0; + /** @copybrief getGradientDescentIterations @see getGradientDescentIterations */ + CV_WRAP virtual void setVariationalRefinementIterations(int val) = 0; + + /** @brief Weight of the smoothness term + @see setVariationalRefinementAlpha */ + CV_WRAP virtual float getVariationalRefinementAlpha() const = 0; + /** @copybrief getVariationalRefinementAlpha @see getVariationalRefinementAlpha */ + CV_WRAP virtual void setVariationalRefinementAlpha(float val) = 0; + + /** @brief Weight of the color constancy term + @see setVariationalRefinementDelta */ + CV_WRAP virtual float getVariationalRefinementDelta() const = 0; + /** @copybrief getVariationalRefinementDelta @see getVariationalRefinementDelta */ + CV_WRAP virtual void setVariationalRefinementDelta(float val) = 0; + + /** @brief Weight of the gradient constancy term + @see setVariationalRefinementGamma */ + CV_WRAP virtual float getVariationalRefinementGamma() const = 0; + /** @copybrief getVariationalRefinementGamma @see getVariationalRefinementGamma */ + CV_WRAP virtual void setVariationalRefinementGamma(float val) = 0; + + /** @brief Norm value shift for robust penalizer + @see setVariationalRefinementEpsilon */ + CV_WRAP virtual float getVariationalRefinementEpsilon() const = 0; + /** @copybrief getVariationalRefinementEpsilon @see getVariationalRefinementEpsilon */ + CV_WRAP virtual void setVariationalRefinementEpsilon(float val) = 0; + + + /** @brief Whether to use mean-normalization of patches when computing patch distance. It is turned on + by default as it typically provides a noticeable quality boost because of increased robustness to + illumination variations. Turn it off if you are certain that your sequence doesn't contain any changes + in illumination. + @see setUseMeanNormalization */ + CV_WRAP virtual bool getUseMeanNormalization() const = 0; + /** @copybrief getUseMeanNormalization @see getUseMeanNormalization */ + CV_WRAP virtual void setUseMeanNormalization(bool val) = 0; + + /** @brief Whether to use spatial propagation of good optical flow vectors. This option is turned on by + default, as it tends to work better on average and can sometimes help recover from major errors + introduced by the coarse-to-fine scheme employed by the DIS optical flow algorithm. Turning this + option off can make the output flow field a bit smoother, however. + @see setUseSpatialPropagation */ + CV_WRAP virtual bool getUseSpatialPropagation() const = 0; + /** @copybrief getUseSpatialPropagation @see getUseSpatialPropagation */ + CV_WRAP virtual void setUseSpatialPropagation(bool val) = 0; + + /** @brief Creates an instance of DISOpticalFlow + + @param preset one of PRESET_ULTRAFAST, PRESET_FAST and PRESET_MEDIUM + */ + CV_WRAP static Ptr create(int preset = DISOpticalFlow::PRESET_FAST); +}; + +/** @brief Class used for calculating a sparse optical flow. + +The class can calculate an optical flow for a sparse feature set using the +iterative Lucas-Kanade method with pyramids. + +@sa calcOpticalFlowPyrLK + +*/ +class CV_EXPORTS_W SparsePyrLKOpticalFlow : public SparseOpticalFlow +{ +public: + CV_WRAP virtual Size getWinSize() const = 0; + CV_WRAP virtual void setWinSize(Size winSize) = 0; + + CV_WRAP virtual int getMaxLevel() const = 0; + CV_WRAP virtual void setMaxLevel(int maxLevel) = 0; + + CV_WRAP virtual TermCriteria getTermCriteria() const = 0; + CV_WRAP virtual void setTermCriteria(TermCriteria& crit) = 0; + + CV_WRAP virtual int getFlags() const = 0; + CV_WRAP virtual void setFlags(int flags) = 0; + + CV_WRAP virtual double getMinEigThreshold() const = 0; + CV_WRAP virtual void setMinEigThreshold(double minEigThreshold) = 0; + + CV_WRAP static Ptr create( + Size winSize = Size(21, 21), + int maxLevel = 3, TermCriteria crit = + TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), + int flags = 0, + double minEigThreshold = 1e-4); +}; + + + + +/** @brief Base abstract class for the long-term tracker + */ +class CV_EXPORTS_W Tracker +{ +protected: + Tracker(); +public: + virtual ~Tracker(); + + /** @brief Initialize the tracker with a known bounding box that surrounded the target + @param image The initial frame + @param boundingBox The initial bounding box + */ + CV_WRAP virtual + void init(InputArray image, const Rect& boundingBox) = 0; + + /** @brief Update the tracker, find the new most likely bounding box for the target + @param image The current frame + @param boundingBox The bounding box that represent the new target location, if true was returned, not + modified otherwise + + @return True means that target was located and false means that tracker cannot locate target in + current frame. Note, that latter *does not* imply that tracker has failed, maybe target is indeed + missing from the frame (say, out of sight) + */ + CV_WRAP virtual + bool update(InputArray image, CV_OUT Rect& boundingBox) = 0; +}; + + + +/** @brief The MIL algorithm trains a classifier in an online manner to separate the object from the +background. + +Multiple Instance Learning avoids the drift problem for a robust tracking. The implementation is +based on @cite MIL . + +Original code can be found here + */ +class CV_EXPORTS_W TrackerMIL : public Tracker +{ +protected: + TrackerMIL(); // use ::create() +public: + virtual ~TrackerMIL() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + //parameters for sampler + CV_PROP_RW float samplerInitInRadius; //!< radius for gathering positive instances during init + CV_PROP_RW int samplerInitMaxNegNum; //!< # negative samples to use during init + CV_PROP_RW float samplerSearchWinSize; //!< size of search window + CV_PROP_RW float samplerTrackInRadius; //!< radius for gathering positive instances during tracking + CV_PROP_RW int samplerTrackMaxPosNum; //!< # positive samples to use during tracking + CV_PROP_RW int samplerTrackMaxNegNum; //!< # negative samples to use during tracking + CV_PROP_RW int featureSetNumFeatures; //!< # features + }; + + /** @brief Create MIL tracker instance + * @param parameters MIL parameters TrackerMIL::Params + */ + static CV_WRAP + Ptr create(const TrackerMIL::Params ¶meters = TrackerMIL::Params()); + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + + + +/** @brief the GOTURN (Generic Object Tracking Using Regression Networks) tracker + * + * GOTURN (@cite GOTURN) is kind of trackers based on Convolutional Neural Networks (CNN). While taking all advantages of CNN trackers, + * GOTURN is much faster due to offline training without online fine-tuning nature. + * GOTURN tracker addresses the problem of single target tracking: given a bounding box label of an object in the first frame of the video, + * we track that object through the rest of the video. NOTE: Current method of GOTURN does not handle occlusions; however, it is fairly + * robust to viewpoint changes, lighting changes, and deformations. + * Inputs of GOTURN are two RGB patches representing Target and Search patches resized to 227x227. + * Outputs of GOTURN are predicted bounding box coordinates, relative to Search patch coordinate system, in format X1,Y1,X2,Y2. + * Original paper is here: + * As long as original authors implementation: + * Implementation of training algorithm is placed in separately here due to 3d-party dependencies: + * + * GOTURN architecture goturn.prototxt and trained model goturn.caffemodel are accessible on opencv_extra GitHub repository. + */ +class CV_EXPORTS_W TrackerGOTURN : public Tracker +{ +protected: + TrackerGOTURN(); // use ::create() +public: + virtual ~TrackerGOTURN() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string modelTxt; + CV_PROP_RW std::string modelBin; + }; + + /** @brief Constructor + @param parameters GOTURN parameters TrackerGOTURN::Params + */ + static CV_WRAP + Ptr create(const TrackerGOTURN::Params& parameters = TrackerGOTURN::Params()); + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +class CV_EXPORTS_W TrackerDaSiamRPN : public Tracker +{ +protected: + TrackerDaSiamRPN(); // use ::create() +public: + virtual ~TrackerDaSiamRPN() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string model; + CV_PROP_RW std::string kernel_cls1; + CV_PROP_RW std::string kernel_r1; + CV_PROP_RW int backend; + CV_PROP_RW int target; + }; + + /** @brief Constructor + @param parameters DaSiamRPN parameters TrackerDaSiamRPN::Params + */ + static CV_WRAP + Ptr create(const TrackerDaSiamRPN::Params& parameters = TrackerDaSiamRPN::Params()); + + /** @brief Return tracking score + */ + CV_WRAP virtual float getTrackingScore() = 0; + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +/** @brief the Nano tracker is a super lightweight dnn-based general object tracking. + * + * Nano tracker is much faster and extremely lightweight due to special model structure, the whole model size is about 1.9 MB. + * Nano tracker needs two models: one for feature extraction (backbone) and the another for localization (neckhead). + * Model download link: https://github.com/HonglinChu/SiamTrackers/tree/master/NanoTrack/models/nanotrackv2 + * Original repo is here: https://github.com/HonglinChu/NanoTrack + * Author: HongLinChu, 1628464345@qq.com + */ +class CV_EXPORTS_W TrackerNano : public Tracker +{ +protected: + TrackerNano(); // use ::create() +public: + virtual ~TrackerNano() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string backbone; + CV_PROP_RW std::string neckhead; + CV_PROP_RW int backend; + CV_PROP_RW int target; + }; + + /** @brief Constructor + @param parameters NanoTrack parameters TrackerNano::Params + */ + static CV_WRAP + Ptr create(const TrackerNano::Params& parameters = TrackerNano::Params()); + + /** @brief Return tracking score + */ + CV_WRAP virtual float getTrackingScore() = 0; + + //void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + //bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +/** @brief the VIT tracker is a super lightweight dnn-based general object tracking. + * + * VIT tracker is much faster and extremely lightweight due to special model structure, the model file is about 767KB. + * Model download link: https://github.com/opencv/opencv_zoo/tree/main/models/object_tracking_vittrack + * Author: PengyuLiu, 1872918507@qq.com + */ +class CV_EXPORTS_W TrackerVit : public Tracker +{ +protected: + TrackerVit(); // use ::create() +public: + virtual ~TrackerVit() CV_OVERRIDE; + + struct CV_EXPORTS_W_SIMPLE Params + { + CV_WRAP Params(); + CV_PROP_RW std::string net; + CV_PROP_RW int backend; + CV_PROP_RW int target; + CV_PROP_RW Scalar meanvalue; + CV_PROP_RW Scalar stdvalue; + CV_PROP_RW float tracking_score_threshold; + }; + + /** @brief Constructor + @param parameters vit tracker parameters TrackerVit::Params + */ + static CV_WRAP + Ptr create(const TrackerVit::Params& parameters = TrackerVit::Params()); + + /** @brief Return tracking score + */ + CV_WRAP virtual float getTrackingScore() = 0; + + // void init(InputArray image, const Rect& boundingBox) CV_OVERRIDE; + // bool update(InputArray image, CV_OUT Rect& boundingBox) CV_OVERRIDE; +}; + +//! @} video_track + +} // cv + +#endif diff --git a/3rdParty/opencv-4.11.0/opencv2/video/video.hpp b/3rdParty/opencv-4.11.0/opencv2/video/video.hpp index 2d7a38be57..8267b85d59 100644 --- a/3rdParty/opencv-4.11.0/opencv2/video/video.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/video/video.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/video.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/video.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio.hpp b/3rdParty/opencv-4.11.0/opencv2/videoio.hpp index 9fc080c4cf..6e50f87e44 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/videoio.hpp @@ -1,1238 +1,1238 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_VIDEOIO_HPP -#define OPENCV_VIDEOIO_HPP - -#include "opencv2/core.hpp" - -/** - @defgroup videoio Video I/O - - @brief Read and write video or images sequence with OpenCV - - ### See also: - - @ref videoio_overview - - Tutorials: @ref tutorial_table_of_content_app - @{ - @defgroup videoio_flags_base Flags for video I/O - @defgroup videoio_flags_others Additional flags for video I/O API backends - @defgroup videoio_hwaccel Hardware-accelerated video decoding and encoding - @defgroup videoio_c C API for video I/O - @defgroup videoio_ios iOS glue for video I/O - @defgroup videoio_winrt WinRT glue for video I/O - @defgroup videoio_registry Query I/O API backends registry - @} -*/ - -////////////////////////////////// video io ///////////////////////////////// - -typedef struct CvCapture CvCapture; -typedef struct CvVideoWriter CvVideoWriter; - -namespace cv -{ - -//! @addtogroup videoio -//! @{ - -//! @addtogroup videoio_flags_base -//! @{ - - -/** @brief cv::VideoCapture API backends identifier. - -Select preferred API for a capture object. -To be used in the VideoCapture::VideoCapture() constructor or VideoCapture::open() - -@note -- Backends are available only if they have been built with your OpenCV binaries. -See @ref videoio_overview for more information. -- Microsoft Media Foundation backend tries to use hardware accelerated transformations -if possible. Environment flag "OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS" set to 0 -disables it and may improve initialization time. More details: -https://learn.microsoft.com/en-us/windows/win32/medfound/mf-readwrite-enable-hardware-transforms -*/ -enum VideoCaptureAPIs { - CAP_ANY = 0, //!< Auto detect == 0 - CAP_VFW = 200, //!< Video For Windows (obsolete, removed) - CAP_V4L = 200, //!< V4L/V4L2 capturing support - CAP_V4L2 = CAP_V4L, //!< Same as CAP_V4L - CAP_FIREWIRE = 300, //!< IEEE 1394 drivers - CAP_FIREWARE = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_IEEE1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_DC1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_CMU1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE - CAP_QT = 500, //!< QuickTime (obsolete, removed) - CAP_UNICAP = 600, //!< Unicap drivers (obsolete, removed) - CAP_DSHOW = 700, //!< DirectShow (via videoInput) - CAP_PVAPI = 800, //!< PvAPI, Prosilica GigE SDK - CAP_OPENNI = 900, //!< OpenNI (for Kinect) - CAP_OPENNI_ASUS = 910, //!< OpenNI (for Asus Xtion) - CAP_ANDROID = 1000, //!< MediaNDK (API Level 21+) and NDK Camera (API level 24+) for Android - CAP_XIAPI = 1100, //!< XIMEA Camera API - CAP_AVFOUNDATION = 1200, //!< AVFoundation framework for iOS (OS X Lion will have the same API) - CAP_GIGANETIX = 1300, //!< Smartek Giganetix GigEVisionSDK - CAP_MSMF = 1400, //!< Microsoft Media Foundation (via videoInput). See platform specific notes above. - CAP_WINRT = 1410, //!< Microsoft Windows Runtime using Media Foundation - CAP_INTELPERC = 1500, //!< RealSense (former Intel Perceptual Computing SDK) - CAP_REALSENSE = 1500, //!< Synonym for CAP_INTELPERC - CAP_OPENNI2 = 1600, //!< OpenNI2 (for Kinect) - CAP_OPENNI2_ASUS = 1610, //!< OpenNI2 (for Asus Xtion and Occipital Structure sensors) - CAP_OPENNI2_ASTRA= 1620, //!< OpenNI2 (for Orbbec Astra) - CAP_GPHOTO2 = 1700, //!< gPhoto2 connection - CAP_GSTREAMER = 1800, //!< GStreamer - CAP_FFMPEG = 1900, //!< Open and record video file or stream using the FFMPEG library - CAP_IMAGES = 2000, //!< OpenCV Image Sequence (e.g. img_%02d.jpg) - CAP_ARAVIS = 2100, //!< Aravis SDK - CAP_OPENCV_MJPEG = 2200, //!< Built-in OpenCV MotionJPEG codec - CAP_INTEL_MFX = 2300, //!< Intel MediaSDK - CAP_XINE = 2400, //!< XINE engine (Linux) - CAP_UEYE = 2500, //!< uEye Camera API - CAP_OBSENSOR = 2600, //!< For Orbbec 3D-Sensor device/module (Astra+, Femto, Astra2, Gemini2, Gemini2L, Gemini2XL, Femto Mega) attention: Astra2 cameras currently only support Windows and Linux kernel versions no higher than 4.15, and higher versions of Linux kernel may have exceptions. - }; - - -/** @brief cv::VideoCapture generic properties identifier. - - Reading / writing properties involves many layers. Some unexpected result might happens along this chain. - Effective behaviour depends from device hardware, driver and API Backend. - @sa videoio_flags_others, VideoCapture::get(), VideoCapture::set() -*/ -enum VideoCaptureProperties { - CAP_PROP_POS_MSEC =0, //!< Current position of the video file in milliseconds. - CAP_PROP_POS_FRAMES =1, //!< 0-based index of the frame to be decoded/captured next. When the index i is set in RAW mode (CAP_PROP_FORMAT == -1) this will seek to the key frame k, where k <= i. - CAP_PROP_POS_AVI_RATIO =2, //!< Relative position of the video file: 0=start of the film, 1=end of the film. - CAP_PROP_FRAME_WIDTH =3, //!< Width of the frames in the video stream. - CAP_PROP_FRAME_HEIGHT =4, //!< Height of the frames in the video stream. - CAP_PROP_FPS =5, //!< Frame rate. - CAP_PROP_FOURCC =6, //!< 4-character code of codec. see VideoWriter::fourcc . - CAP_PROP_FRAME_COUNT =7, //!< Number of frames in the video file. - CAP_PROP_FORMAT =8, //!< Format of the %Mat objects (see Mat::type()) returned by VideoCapture::retrieve(). - //!< Set value -1 to fetch undecoded RAW video streams (as Mat 8UC1). - CAP_PROP_MODE =9, //!< Backend-specific value indicating the current capture mode. - CAP_PROP_BRIGHTNESS =10, //!< Brightness of the image (only for those cameras that support). - CAP_PROP_CONTRAST =11, //!< Contrast of the image (only for cameras). - CAP_PROP_SATURATION =12, //!< Saturation of the image (only for cameras). - CAP_PROP_HUE =13, //!< Hue of the image (only for cameras). - CAP_PROP_GAIN =14, //!< Gain of the image (only for those cameras that support). - CAP_PROP_EXPOSURE =15, //!< Exposure (only for those cameras that support). - CAP_PROP_CONVERT_RGB =16, //!< Boolean flags indicating whether images should be converted to RGB.
- //!< *GStreamer note*: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output. - CAP_PROP_WHITE_BALANCE_BLUE_U =17, //!< Currently unsupported. - CAP_PROP_RECTIFICATION =18, //!< Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently). - CAP_PROP_MONOCHROME =19, - CAP_PROP_SHARPNESS =20, - CAP_PROP_AUTO_EXPOSURE =21, //!< DC1394: exposure control done by camera, user can adjust reference level using this feature. - CAP_PROP_GAMMA =22, - CAP_PROP_TEMPERATURE =23, - CAP_PROP_TRIGGER =24, - CAP_PROP_TRIGGER_DELAY =25, - CAP_PROP_WHITE_BALANCE_RED_V =26, - CAP_PROP_ZOOM =27, - CAP_PROP_FOCUS =28, - CAP_PROP_GUID =29, - CAP_PROP_ISO_SPEED =30, - CAP_PROP_BACKLIGHT =32, - CAP_PROP_PAN =33, - CAP_PROP_TILT =34, - CAP_PROP_ROLL =35, - CAP_PROP_IRIS =36, - CAP_PROP_SETTINGS =37, //!< Pop up video/camera filter dialog (note: only supported by DSHOW backend currently. The property value is ignored) - CAP_PROP_BUFFERSIZE =38, - CAP_PROP_AUTOFOCUS =39, - CAP_PROP_SAR_NUM =40, //!< Sample aspect ratio: num/den (num) - CAP_PROP_SAR_DEN =41, //!< Sample aspect ratio: num/den (den) - CAP_PROP_BACKEND =42, //!< Current backend (enum VideoCaptureAPIs). Read-only property - CAP_PROP_CHANNEL =43, //!< Video input or Channel Number (only for those cameras that support) - CAP_PROP_AUTO_WB =44, //!< enable/ disable auto white-balance - CAP_PROP_WB_TEMPERATURE=45, //!< white-balance color temperature - CAP_PROP_CODEC_PIXEL_FORMAT =46, //!< (read-only) codec's pixel format. 4-character code - see VideoWriter::fourcc . Subset of [AV_PIX_FMT_*](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/raw.c) or -1 if unknown - CAP_PROP_BITRATE =47, //!< (read-only) Video bitrate in kbits/s - CAP_PROP_ORIENTATION_META=48, //!< (read-only) Frame rotation defined by stream meta (applicable for FFmpeg and AVFoundation back-ends only) - CAP_PROP_ORIENTATION_AUTO=49, //!< if true - rotates output frames of CvCapture considering video file's metadata (applicable for FFmpeg and AVFoundation back-ends only) (https://github.com/opencv/opencv/issues/15499) - CAP_PROP_HW_ACCELERATION=50, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in cv::VideoCapture constructor / .open() method. Default value is backend-specific. - CAP_PROP_HW_DEVICE =51, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. - CAP_PROP_HW_ACCELERATION_USE_OPENCL=52, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between HW accelerated decoder and cv::UMat. - CAP_PROP_OPEN_TIMEOUT_MSEC=53, //!< (**open-only**) timeout in milliseconds for opening a video capture (applicable for FFmpeg and GStreamer back-ends only) - CAP_PROP_READ_TIMEOUT_MSEC=54, //!< (**open-only**) timeout in milliseconds for reading from a video capture (applicable for FFmpeg and GStreamer back-ends only) - CAP_PROP_STREAM_OPEN_TIME_USEC =55, //!< (read-only) time in microseconds since Jan 1 1970 when stream was opened. Applicable for FFmpeg backend only. Useful for RTSP and other live streams - CAP_PROP_VIDEO_TOTAL_CHANNELS = 56, //!< (read-only) Number of video channels - CAP_PROP_VIDEO_STREAM = 57, //!< (**open-only**) Specify video stream, 0-based index. Use -1 to disable video stream from file or IP cameras. Default value is 0. - CAP_PROP_AUDIO_STREAM = 58, //!< (**open-only**) Specify stream in multi-language media files, -1 - disable audio processing or microphone. Default value is -1. - CAP_PROP_AUDIO_POS = 59, //!< (read-only) Audio position is measured in samples. Accurate audio sample timestamp of previous grabbed fragment. See CAP_PROP_AUDIO_SAMPLES_PER_SECOND and CAP_PROP_AUDIO_SHIFT_NSEC. - CAP_PROP_AUDIO_SHIFT_NSEC = 60, //!< (read only) Contains the time difference between the start of the audio stream and the video stream in nanoseconds. Positive value means that audio is started after the first video frame. Negative value means that audio is started before the first video frame. - CAP_PROP_AUDIO_DATA_DEPTH = 61, //!< (open, read) Alternative definition to bits-per-sample, but with clear handling of 32F / 32S - CAP_PROP_AUDIO_SAMPLES_PER_SECOND = 62, //!< (open, read) determined from file/codec input. If not specified, then selected audio sample rate is 44100 - CAP_PROP_AUDIO_BASE_INDEX = 63, //!< (read-only) Index of the first audio channel for .retrieve() calls. That audio channel number continues enumeration after video channels. - CAP_PROP_AUDIO_TOTAL_CHANNELS = 64, //!< (read-only) Number of audio channels in the selected audio stream (mono, stereo, etc) - CAP_PROP_AUDIO_TOTAL_STREAMS = 65, //!< (read-only) Number of audio streams. - CAP_PROP_AUDIO_SYNCHRONIZE = 66, //!< (open, read) Enables audio synchronization. - CAP_PROP_LRF_HAS_KEY_FRAME = 67, //!< FFmpeg back-end only - Indicates whether the Last Raw Frame (LRF), output from VideoCapture::read() when VideoCapture is initialized with VideoCapture::open(CAP_FFMPEG, {CAP_PROP_FORMAT, -1}) or VideoCapture::set(CAP_PROP_FORMAT,-1) is called before the first call to VideoCapture::read(), contains encoded data for a key frame. - CAP_PROP_CODEC_EXTRADATA_INDEX = 68, //!< Positive index indicates that returning extra data is supported by the video back end. This can be retrieved as cap.retrieve(data, ). E.g. When reading from a h264 encoded RTSP stream, the FFmpeg backend could return the SPS and/or PPS if available (if sent in reply to a DESCRIBE request), from calls to cap.retrieve(data, ). - CAP_PROP_FRAME_TYPE = 69, //!< (read-only) FFmpeg back-end only - Frame type ascii code (73 = 'I', 80 = 'P', 66 = 'B' or 63 = '?' if unknown) of the most recently read frame. - CAP_PROP_N_THREADS = 70, //!< (**open-only**) Set the maximum number of threads to use. Use 0 to use as many threads as CPU cores (applicable for FFmpeg back-end only). - CAP_PROP_PTS = 71, //!< (read-only) FFmpeg back-end only - presentation timestamp of the most recently read frame using the FPS time base. e.g. fps = 25, VideoCapture::get(\ref CAP_PROP_PTS) = 3, presentation time = 3/25 seconds. - CAP_PROP_DTS_DELAY = 72, //!< (read-only) FFmpeg back-end only - maximum difference between presentation (pts) and decompression timestamps (dts) using FPS time base. e.g. delay is maximum when frame_num = 0, if true, VideoCapture::get(\ref CAP_PROP_PTS) = 0 and VideoCapture::get(\ref CAP_PROP_DTS_DELAY) = 2, dts = -2. Non zero values usually imply the stream is encoded using B-frames which are not decoded in presentation order. -#ifndef CV_DOXYGEN - CV__CAP_PROP_LATEST -#endif - }; - -/** @brief cv::VideoWriter generic properties identifier. - @sa VideoWriter::get(), VideoWriter::set() -*/ -enum VideoWriterProperties { - VIDEOWRITER_PROP_QUALITY = 1, //!< Current quality (0..100%) of the encoded videostream. Can be adjusted dynamically in some codecs. - VIDEOWRITER_PROP_FRAMEBYTES = 2, //!< (Read-only): Size of just encoded video frame. Note that the encoding order may be different from representation order. - VIDEOWRITER_PROP_NSTRIPES = 3, //!< Number of stripes for parallel encoding. -1 for auto detection. - VIDEOWRITER_PROP_IS_COLOR = 4, //!< If it is not zero, the encoder will expect and encode color frames, otherwise it - //!< will work with grayscale frames. - VIDEOWRITER_PROP_DEPTH = 5, //!< Defaults to \ref CV_8U. - VIDEOWRITER_PROP_HW_ACCELERATION = 6, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in VideoWriter constructor / .open() method. Default value is backend-specific. - VIDEOWRITER_PROP_HW_DEVICE = 7, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. - VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL= 8, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between cv::UMat and HW accelerated encoder. - VIDEOWRITER_PROP_RAW_VIDEO = 9, //!< (**open-only**) Set to non-zero to enable encapsulation of an encoded raw video stream. Each raw encoded video frame should be passed to VideoWriter::write() as single row or column of a \ref CV_8UC1 Mat. \note If the key frame interval is not 1 then it must be manually specified by the user. This can either be performed during initialization passing \ref VIDEOWRITER_PROP_KEY_INTERVAL as one of the extra encoder params to \ref VideoWriter::VideoWriter(const String &, int, double, const Size &, const std::vector< int > ¶ms) or afterwards by setting the \ref VIDEOWRITER_PROP_KEY_FLAG with \ref VideoWriter::set() before writing each frame. FFMpeg backend only. - VIDEOWRITER_PROP_KEY_INTERVAL = 10, //!< (**open-only**) Set the key frame interval using raw video encapsulation (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). Defaults to 1 when not set. FFmpeg back-end only. - VIDEOWRITER_PROP_KEY_FLAG = 11, //!< Set to non-zero to signal that the following frames are key frames or zero if not, when encapsulating raw video (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). FFmpeg back-end only. - VIDEOWRITER_PROP_PTS = 12, //!< Specifies the frame presentation timestamp for each frame using the FPS time base. This property is **only** necessary when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be provided by your external encoder and for video sources with fixed frame rates it is equivalent to dividing the current frame's presentation time (\ref CAP_PROP_POS_MSEC) by the frame duration (1000.0 / VideoCapture::get(\ref CAP_PROP_FPS)). It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_PTS). FFmpeg back-end only. - VIDEOWRITER_PROP_DTS_DELAY = 13, //!< Specifies the maximum difference between presentation (pts) and decompression timestamps (dts) using the FPS time base. This property is necessary **only** when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be calculated based on the specific GOP pattern used during encoding. For example, in a GOP with presentation order IBP and decoding order IPB, this value would be 1, as the B-frame is the second frame presented but the third to be decoded. It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_DTS_DELAY). Non-zero values usually imply the stream is encoded using B-frames. FFmpeg back-end only. -#ifndef CV_DOXYGEN - CV__VIDEOWRITER_PROP_LATEST -#endif -}; - -//! @} videoio_flags_base - -//! @addtogroup videoio_flags_others -//! @{ - -/** @name Hardware acceleration support - @{ -*/ - -/** @brief Video Acceleration type - * - * Used as value in #CAP_PROP_HW_ACCELERATION and #VIDEOWRITER_PROP_HW_ACCELERATION - * - * @note In case of FFmpeg backend, it translated to enum AVHWDeviceType (https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/hwcontext.h) - */ -enum VideoAccelerationType -{ - VIDEO_ACCELERATION_NONE = 0, //!< Do not require any specific H/W acceleration, prefer software processing. - //!< Reading of this value means that special H/W accelerated handling is not added or not detected by OpenCV. - - VIDEO_ACCELERATION_ANY = 1, //!< Prefer to use H/W acceleration. If no one supported, then fallback to software processing. - //!< @note H/W acceleration may require special configuration of used environment. - //!< @note Results in encoding scenario may differ between software and hardware accelerated encoders. - - VIDEO_ACCELERATION_D3D11 = 2, //!< DirectX 11 - VIDEO_ACCELERATION_VAAPI = 3, //!< VAAPI - VIDEO_ACCELERATION_MFX = 4, //!< libmfx (Intel MediaSDK/oneVPL) -}; - -//! @} Hardware acceleration support - -/** @name IEEE 1394 drivers - @{ -*/ - -/** @brief Modes of the IEEE 1394 controlling registers -(can be: auto, manual, auto single push, absolute Latter allowed with any other mode) -every feature can have only one mode turned on at a time -*/ -enum { CAP_PROP_DC1394_OFF = -4, //!< turn the feature off (not controlled manually nor automatically). - CAP_PROP_DC1394_MODE_MANUAL = -3, //!< set automatically when a value of the feature is set by the user. - CAP_PROP_DC1394_MODE_AUTO = -2, - CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, - CAP_PROP_DC1394_MAX = 31 - }; - -//! @} IEEE 1394 drivers - -/** @name OpenNI (for Kinect) - @{ -*/ - -//! OpenNI map generators -enum { CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, - CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, - CAP_OPENNI_IR_GENERATOR = 1 << 29, - CAP_OPENNI_GENERATORS_MASK = CAP_OPENNI_DEPTH_GENERATOR + CAP_OPENNI_IMAGE_GENERATOR + CAP_OPENNI_IR_GENERATOR - }; - -//! Properties of cameras available through OpenNI backend -enum { CAP_PROP_OPENNI_OUTPUT_MODE = 100, - CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, //!< In mm - CAP_PROP_OPENNI_BASELINE = 102, //!< In mm - CAP_PROP_OPENNI_FOCAL_LENGTH = 103, //!< In pixels - CAP_PROP_OPENNI_REGISTRATION = 104, //!< Flag that synchronizes the remapping depth map to image map - //!< by changing depth generator's view point (if the flag is "on") or - //!< sets this view point to its normal one (if the flag is "off"). - CAP_PROP_OPENNI_REGISTRATION_ON = CAP_PROP_OPENNI_REGISTRATION, - CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, - CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, - CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, - CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, - CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, - CAP_PROP_OPENNI2_SYNC = 110, - CAP_PROP_OPENNI2_MIRROR = 111 - }; - -#ifdef _MSC_VER -#pragma warning( push ) -#pragma warning( disable: 5054 ) -#endif -//! OpenNI shortcuts -enum { CAP_OPENNI_IMAGE_GENERATOR_PRESENT = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, - CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_OUTPUT_MODE, - CAP_OPENNI_DEPTH_GENERATOR_PRESENT = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, - CAP_OPENNI_DEPTH_GENERATOR_BASELINE = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_BASELINE, - CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_FOCAL_LENGTH, - CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_REGISTRATION, - CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, - CAP_OPENNI_IR_GENERATOR_PRESENT = +CAP_OPENNI_IR_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT - }; -#ifdef _MSC_VER -#pragma warning( pop ) -#endif - -//! OpenNI data given from depth generator -enum { CAP_OPENNI_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) - CAP_OPENNI_POINT_CLOUD_MAP = 1, //!< XYZ in meters (CV_32FC3) - CAP_OPENNI_DISPARITY_MAP = 2, //!< Disparity in pixels (CV_8UC1) - CAP_OPENNI_DISPARITY_MAP_32F = 3, //!< Disparity in pixels (CV_32FC1) - CAP_OPENNI_VALID_DEPTH_MASK = 4, //!< CV_8UC1 - - CAP_OPENNI_BGR_IMAGE = 5, //!< Data given from RGB image generator - CAP_OPENNI_GRAY_IMAGE = 6, //!< Data given from RGB image generator - - CAP_OPENNI_IR_IMAGE = 7 //!< Data given from IR image generator - }; - -//! Supported output modes of OpenNI image generator -enum { CAP_OPENNI_VGA_30HZ = 0, - CAP_OPENNI_SXGA_15HZ = 1, - CAP_OPENNI_SXGA_30HZ = 2, - CAP_OPENNI_QVGA_30HZ = 3, - CAP_OPENNI_QVGA_60HZ = 4 - }; - -//! @} OpenNI - -/** @name GStreamer - @{ -*/ - -enum { CAP_PROP_GSTREAMER_QUEUE_LENGTH = 200 //!< Default is 1 - }; - -//! @} GStreamer - -/** @name PvAPI, Prosilica GigE SDK - @{ -*/ - -//! PVAPI -enum { CAP_PROP_PVAPI_MULTICASTIP = 300, //!< IP for enable multicast master mode. 0 for disable multicast. - CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, //!< FrameStartTriggerMode: Determines how a frame is initiated. - CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, //!< Horizontal sub-sampling of the image. - CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, //!< Vertical sub-sampling of the image. - CAP_PROP_PVAPI_BINNINGX = 304, //!< Horizontal binning factor. - CAP_PROP_PVAPI_BINNINGY = 305, //!< Vertical binning factor. - CAP_PROP_PVAPI_PIXELFORMAT = 306 //!< Pixel format. - }; - -//! PVAPI: FrameStartTriggerMode -enum { CAP_PVAPI_FSTRIGMODE_FREERUN = 0, //!< Freerun - CAP_PVAPI_FSTRIGMODE_SYNCIN1 = 1, //!< SyncIn1 - CAP_PVAPI_FSTRIGMODE_SYNCIN2 = 2, //!< SyncIn2 - CAP_PVAPI_FSTRIGMODE_FIXEDRATE = 3, //!< FixedRate - CAP_PVAPI_FSTRIGMODE_SOFTWARE = 4 //!< Software - }; - -//! PVAPI: DecimationHorizontal, DecimationVertical -enum { CAP_PVAPI_DECIMATION_OFF = 1, //!< Off - CAP_PVAPI_DECIMATION_2OUTOF4 = 2, //!< 2 out of 4 decimation - CAP_PVAPI_DECIMATION_2OUTOF8 = 4, //!< 2 out of 8 decimation - CAP_PVAPI_DECIMATION_2OUTOF16 = 8 //!< 2 out of 16 decimation - }; - -//! PVAPI: PixelFormat -enum { CAP_PVAPI_PIXELFORMAT_MONO8 = 1, //!< Mono8 - CAP_PVAPI_PIXELFORMAT_MONO16 = 2, //!< Mono16 - CAP_PVAPI_PIXELFORMAT_BAYER8 = 3, //!< Bayer8 - CAP_PVAPI_PIXELFORMAT_BAYER16 = 4, //!< Bayer16 - CAP_PVAPI_PIXELFORMAT_RGB24 = 5, //!< Rgb24 - CAP_PVAPI_PIXELFORMAT_BGR24 = 6, //!< Bgr24 - CAP_PVAPI_PIXELFORMAT_RGBA32 = 7, //!< Rgba32 - CAP_PVAPI_PIXELFORMAT_BGRA32 = 8, //!< Bgra32 - }; - -//! @} PvAPI - -/** @name XIMEA Camera API - @{ -*/ - -//! Properties of cameras available through XIMEA SDK backend -enum { CAP_PROP_XI_DOWNSAMPLING = 400, //!< Change image resolution by binning or skipping. - CAP_PROP_XI_DATA_FORMAT = 401, //!< Output data format. - CAP_PROP_XI_OFFSET_X = 402, //!< Horizontal offset from the origin to the area of interest (in pixels). - CAP_PROP_XI_OFFSET_Y = 403, //!< Vertical offset from the origin to the area of interest (in pixels). - CAP_PROP_XI_TRG_SOURCE = 404, //!< Defines source of trigger. - CAP_PROP_XI_TRG_SOFTWARE = 405, //!< Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. - CAP_PROP_XI_GPI_SELECTOR = 406, //!< Selects general purpose input. - CAP_PROP_XI_GPI_MODE = 407, //!< Set general purpose input mode. - CAP_PROP_XI_GPI_LEVEL = 408, //!< Get general purpose level. - CAP_PROP_XI_GPO_SELECTOR = 409, //!< Selects general purpose output. - CAP_PROP_XI_GPO_MODE = 410, //!< Set general purpose output mode. - CAP_PROP_XI_LED_SELECTOR = 411, //!< Selects camera signalling LED. - CAP_PROP_XI_LED_MODE = 412, //!< Define camera signalling LED functionality. - CAP_PROP_XI_MANUAL_WB = 413, //!< Calculates White Balance(must be called during acquisition). - CAP_PROP_XI_AUTO_WB = 414, //!< Automatic white balance. - CAP_PROP_XI_AEAG = 415, //!< Automatic exposure/gain. - CAP_PROP_XI_EXP_PRIORITY = 416, //!< Exposure priority (0.5 - exposure 50%, gain 50%). - CAP_PROP_XI_AE_MAX_LIMIT = 417, //!< Maximum limit of exposure in AEAG procedure. - CAP_PROP_XI_AG_MAX_LIMIT = 418, //!< Maximum limit of gain in AEAG procedure. - CAP_PROP_XI_AEAG_LEVEL = 419, //!< Average intensity of output signal AEAG should achieve(in %). - CAP_PROP_XI_TIMEOUT = 420, //!< Image capture timeout in milliseconds. - CAP_PROP_XI_EXPOSURE = 421, //!< Exposure time in microseconds. - CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, //!< Sets the number of times of exposure in one frame. - CAP_PROP_XI_GAIN_SELECTOR = 423, //!< Gain selector for parameter Gain allows to select different type of gains. - CAP_PROP_XI_GAIN = 424, //!< Gain in dB. - CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, //!< Change image downsampling type. - CAP_PROP_XI_BINNING_SELECTOR = 427, //!< Binning engine selector. - CAP_PROP_XI_BINNING_VERTICAL = 428, //!< Vertical Binning - number of vertical photo-sensitive cells to combine together. - CAP_PROP_XI_BINNING_HORIZONTAL = 429, //!< Horizontal Binning - number of horizontal photo-sensitive cells to combine together. - CAP_PROP_XI_BINNING_PATTERN = 430, //!< Binning pattern type. - CAP_PROP_XI_DECIMATION_SELECTOR = 431, //!< Decimation engine selector. - CAP_PROP_XI_DECIMATION_VERTICAL = 432, //!< Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. - CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, //!< Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. - CAP_PROP_XI_DECIMATION_PATTERN = 434, //!< Decimation pattern type. - CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, //!< Selects which test pattern generator is controlled by the TestPattern feature. - CAP_PROP_XI_TEST_PATTERN = 588, //!< Selects which test pattern type is generated by the selected generator. - CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, //!< Output data format. - CAP_PROP_XI_SHUTTER_TYPE = 436, //!< Change sensor shutter type(CMOS sensor). - CAP_PROP_XI_SENSOR_TAPS = 437, //!< Number of taps. - CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, //!< Automatic exposure/gain ROI offset X. - CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, //!< Automatic exposure/gain ROI offset Y. - CAP_PROP_XI_AEAG_ROI_WIDTH = 441, //!< Automatic exposure/gain ROI Width. - CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, //!< Automatic exposure/gain ROI Height. - CAP_PROP_XI_BPC = 445, //!< Correction of bad pixels. - CAP_PROP_XI_WB_KR = 448, //!< White balance red coefficient. - CAP_PROP_XI_WB_KG = 449, //!< White balance green coefficient. - CAP_PROP_XI_WB_KB = 450, //!< White balance blue coefficient. - CAP_PROP_XI_WIDTH = 451, //!< Width of the Image provided by the device (in pixels). - CAP_PROP_XI_HEIGHT = 452, //!< Height of the Image provided by the device (in pixels). - CAP_PROP_XI_REGION_SELECTOR = 589, //!< Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode. - CAP_PROP_XI_REGION_MODE = 595, //!< Activates/deactivates Region selected by Region Selector. - CAP_PROP_XI_LIMIT_BANDWIDTH = 459, //!< Set/get bandwidth(datarate)(in Megabits). - CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, //!< Sensor output data bit depth. - CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, //!< Device output data bit depth. - CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, //!< bitdepth of data returned by function xiGetImage. - CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, //!< Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. - CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, //!< Data packing type. Some cameras supports only specific packing type. - CAP_PROP_XI_IS_COOLED = 465, //!< Returns 1 for cameras that support cooling. - CAP_PROP_XI_COOLING = 466, //!< Start camera cooling. - CAP_PROP_XI_TARGET_TEMP = 467, //!< Set sensor target temperature for cooling. - CAP_PROP_XI_CHIP_TEMP = 468, //!< Camera sensor temperature. - CAP_PROP_XI_HOUS_TEMP = 469, //!< Camera housing temperature. - CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, //!< Camera housing back side temperature. - CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, //!< Camera sensor board temperature. - CAP_PROP_XI_CMS = 470, //!< Mode of color management system. - CAP_PROP_XI_APPLY_CMS = 471, //!< Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). - CAP_PROP_XI_IMAGE_IS_COLOR = 474, //!< Returns 1 for color cameras. - CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, //!< Returns color filter array type of RAW data. - CAP_PROP_XI_GAMMAY = 476, //!< Luminosity gamma. - CAP_PROP_XI_GAMMAC = 477, //!< Chromaticity gamma. - CAP_PROP_XI_SHARPNESS = 478, //!< Sharpness Strength. - CAP_PROP_XI_CC_MATRIX_00 = 479, //!< Color Correction Matrix element [0][0]. - CAP_PROP_XI_CC_MATRIX_01 = 480, //!< Color Correction Matrix element [0][1]. - CAP_PROP_XI_CC_MATRIX_02 = 481, //!< Color Correction Matrix element [0][2]. - CAP_PROP_XI_CC_MATRIX_03 = 482, //!< Color Correction Matrix element [0][3]. - CAP_PROP_XI_CC_MATRIX_10 = 483, //!< Color Correction Matrix element [1][0]. - CAP_PROP_XI_CC_MATRIX_11 = 484, //!< Color Correction Matrix element [1][1]. - CAP_PROP_XI_CC_MATRIX_12 = 485, //!< Color Correction Matrix element [1][2]. - CAP_PROP_XI_CC_MATRIX_13 = 486, //!< Color Correction Matrix element [1][3]. - CAP_PROP_XI_CC_MATRIX_20 = 487, //!< Color Correction Matrix element [2][0]. - CAP_PROP_XI_CC_MATRIX_21 = 488, //!< Color Correction Matrix element [2][1]. - CAP_PROP_XI_CC_MATRIX_22 = 489, //!< Color Correction Matrix element [2][2]. - CAP_PROP_XI_CC_MATRIX_23 = 490, //!< Color Correction Matrix element [2][3]. - CAP_PROP_XI_CC_MATRIX_30 = 491, //!< Color Correction Matrix element [3][0]. - CAP_PROP_XI_CC_MATRIX_31 = 492, //!< Color Correction Matrix element [3][1]. - CAP_PROP_XI_CC_MATRIX_32 = 493, //!< Color Correction Matrix element [3][2]. - CAP_PROP_XI_CC_MATRIX_33 = 494, //!< Color Correction Matrix element [3][3]. - CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, //!< Set default Color Correction Matrix. - CAP_PROP_XI_TRG_SELECTOR = 498, //!< Selects the type of trigger. - CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, //!< Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart. - CAP_PROP_XI_DEBOUNCE_EN = 507, //!< Enable/Disable debounce to selected GPI. - CAP_PROP_XI_DEBOUNCE_T0 = 508, //!< Debounce time (x * 10us). - CAP_PROP_XI_DEBOUNCE_T1 = 509, //!< Debounce time (x * 10us). - CAP_PROP_XI_DEBOUNCE_POL = 510, //!< Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge). - CAP_PROP_XI_LENS_MODE = 511, //!< Status of lens control interface. This shall be set to XI_ON before any Lens operations. - CAP_PROP_XI_LENS_APERTURE_VALUE = 512, //!< Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11. - CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, //!< Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. - CAP_PROP_XI_LENS_FOCUS_MOVE = 514, //!< Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. - CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, //!< Lens focus distance in cm. - CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, //!< Lens focal distance in mm. - CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, //!< Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. - CAP_PROP_XI_LENS_FEATURE = 518, //!< Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. - CAP_PROP_XI_DEVICE_MODEL_ID = 521, //!< Returns device model id. - CAP_PROP_XI_DEVICE_SN = 522, //!< Returns device serial number. - CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, //!< The alpha channel of RGB32 output image format. - CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, //!< Buffer size in bytes sufficient for output image returned by xiGetImage. - CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, //!< Current format of pixels on transport layer. - CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, //!< Sensor clock frequency in Hz. - CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, //!< Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. - CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, //!< Number of output channels from sensor used for data transfer. - CAP_PROP_XI_FRAMERATE = 535, //!< Define framerate in Hz. - CAP_PROP_XI_COUNTER_SELECTOR = 536, //!< Select counter. - CAP_PROP_XI_COUNTER_VALUE = 537, //!< Counter status. - CAP_PROP_XI_ACQ_TIMING_MODE = 538, //!< Type of sensor frames timing. - CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, //!< Calculate and returns available interface bandwidth(int Megabits). - CAP_PROP_XI_BUFFER_POLICY = 540, //!< Data move policy. - CAP_PROP_XI_LUT_EN = 541, //!< Activates LUT. - CAP_PROP_XI_LUT_INDEX = 542, //!< Control the index (offset) of the coefficient to access in the LUT. - CAP_PROP_XI_LUT_VALUE = 543, //!< Value at entry LUTIndex of the LUT. - CAP_PROP_XI_TRG_DELAY = 544, //!< Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. - CAP_PROP_XI_TS_RST_MODE = 545, //!< Defines how time stamp reset engine will be armed. - CAP_PROP_XI_TS_RST_SOURCE = 546, //!< Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming). - CAP_PROP_XI_IS_DEVICE_EXIST = 547, //!< Returns 1 if camera connected and works properly. - CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, //!< Acquisition buffer size in buffer_size_unit. Default bytes. - CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, //!< Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes. - CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, //!< Acquisition transport buffer size in bytes. - CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, //!< Queue of field/frame buffers. - CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, //!< Number of buffers to commit to low level. - CAP_PROP_XI_RECENT_FRAME = 553, //!< GetImage returns most recent frame. - CAP_PROP_XI_DEVICE_RESET = 554, //!< Resets the camera to default state. - CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, //!< Correction of column FPN. - CAP_PROP_XI_ROW_FPN_CORRECTION = 591, //!< Correction of row FPN. - CAP_PROP_XI_SENSOR_MODE = 558, //!< Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. - CAP_PROP_XI_HDR = 559, //!< Enable High Dynamic Range feature. - CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, //!< The number of kneepoints in the PWLR. - CAP_PROP_XI_HDR_T1 = 561, //!< Position of first kneepoint(in % of XI_PRM_EXPOSURE). - CAP_PROP_XI_HDR_T2 = 562, //!< Position of second kneepoint (in % of XI_PRM_EXPOSURE). - CAP_PROP_XI_KNEEPOINT1 = 563, //!< Value of first kneepoint (% of sensor saturation). - CAP_PROP_XI_KNEEPOINT2 = 564, //!< Value of second kneepoint (% of sensor saturation). - CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, //!< Last image black level counts. Can be used for Offline processing to recall it. - CAP_PROP_XI_HW_REVISION = 571, //!< Returns hardware revision number. - CAP_PROP_XI_DEBUG_LEVEL = 572, //!< Set debug level. - CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, //!< Automatic bandwidth calculation. - CAP_PROP_XI_FFS_FILE_ID = 594, //!< File number. - CAP_PROP_XI_FFS_FILE_SIZE = 580, //!< Size of file. - CAP_PROP_XI_FREE_FFS_SIZE = 581, //!< Size of free camera FFS. - CAP_PROP_XI_USED_FFS_SIZE = 582, //!< Size of used camera FFS. - CAP_PROP_XI_FFS_ACCESS_KEY = 583, //!< Setting of key enables file operations on some cameras. - CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, //!< Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. - CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, //!< Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. - }; - -//! @} XIMEA - - -/** @name ARAVIS Camera API - @{ -*/ - -//! Properties of cameras available through ARAVIS backend -enum { CAP_PROP_ARAVIS_AUTOTRIGGER = 600 //!< Automatically trigger frame capture if camera is configured with software trigger -}; - -//! @} ARAVIS - - -/** @name Android - @{ -*/ - -//! Properties of cameras available through NDK Camera API backend -enum { CAP_PROP_ANDROID_DEVICE_TORCH = 8001, - }; - -//! @} Android - - -/** @name AVFoundation framework for iOS - @{ -*/ - -//! Properties of cameras available through AVFOUNDATION backend -enum { CAP_PROP_IOS_DEVICE_FOCUS = 9001, - CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, - CAP_PROP_IOS_DEVICE_FLASH = 9003, - CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, - CAP_PROP_IOS_DEVICE_TORCH = 9005 - }; - -//! @} AVFoundation framework for iOS - - -/** @name Smartek Giganetix GigEVisionSDK - @{ -*/ - -//! Properties of cameras available through Smartek Giganetix Ethernet Vision backend -/* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ -enum { CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, - CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, - CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, - CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, - CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, - CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006 - }; - -//! @} Smartek - -/** @name Intel Perceptual Computing SDK - @{ -*/ -enum { CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, - CAP_PROP_INTELPERC_PROFILE_IDX = 11002, - CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, - CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, - CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, - CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, - CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007 - }; - -//! Intel Perceptual Streams -enum { CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, - CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, - CAP_INTELPERC_IR_GENERATOR = 1 << 27, - CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR + CAP_INTELPERC_IR_GENERATOR - }; - -enum { CAP_INTELPERC_DEPTH_MAP = 0, //!< Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. - CAP_INTELPERC_UVDEPTH_MAP = 1, //!< Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. - CAP_INTELPERC_IR_MAP = 2, //!< Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. - CAP_INTELPERC_IMAGE = 3 - }; - -//! @} Intel Perceptual - -/** @name gPhoto2 connection - @{ -*/ - -/** @brief gPhoto2 properties - -If `propertyId` is less than 0 then work on widget with that __additive inversed__ camera setting ID -Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. -@see CvCaptureCAM_GPHOTO2 for more info -*/ -enum { CAP_PROP_GPHOTO2_PREVIEW = 17001, //!< Capture only preview from liveview mode. - CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, //!< Readonly, returns (const char *). - CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, //!< Trigger, only by set. Reload camera settings. - CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, //!< Reload all settings on set. - CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, //!< Collect messages with details. - CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, //!< Readonly, returns (const char *). - CAP_PROP_SPEED = 17007, //!< Exposure speed. Can be readonly, depends on camera program. - CAP_PROP_APERTURE = 17008, //!< Aperture. Can be readonly, depends on camera program. - CAP_PROP_EXPOSUREPROGRAM = 17009, //!< Camera exposure program. - CAP_PROP_VIEWFINDER = 17010 //!< Enter liveview mode. - }; - -//! @} gPhoto2 - - -/** @name Images backend - @{ -*/ - -/** @brief Images backend properties - -*/ -enum { CAP_PROP_IMAGES_BASE = 18000, - CAP_PROP_IMAGES_LAST = 19000 // excluding - }; - -//! @} Images - -/** @name OBSENSOR (for Orbbec 3D-Sensor device/module ) - @{ -*/ -//! OBSENSOR data given from image generator -enum VideoCaptureOBSensorDataType{ - CAP_OBSENSOR_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) - CAP_OBSENSOR_BGR_IMAGE = 1, //!< Data given from BGR stream generator - CAP_OBSENSOR_IR_IMAGE = 2 //!< Data given from IR stream generator(CV_16UC1) -}; - -//! OBSENSOR stream generator -enum VideoCaptureOBSensorGenerators{ - CAP_OBSENSOR_DEPTH_GENERATOR = 1 << 29, - CAP_OBSENSOR_IMAGE_GENERATOR = 1 << 28, - CAP_OBSENSOR_IR_GENERATOR = 1 << 27, - CAP_OBSENSOR_GENERATORS_MASK = CAP_OBSENSOR_DEPTH_GENERATOR + CAP_OBSENSOR_IMAGE_GENERATOR + CAP_OBSENSOR_IR_GENERATOR -}; - -//!OBSENSOR properties -enum VideoCaptureOBSensorProperties{ - // INTRINSIC - CAP_PROP_OBSENSOR_INTRINSIC_FX=26001, - CAP_PROP_OBSENSOR_INTRINSIC_FY=26002, - CAP_PROP_OBSENSOR_INTRINSIC_CX=26003, - CAP_PROP_OBSENSOR_INTRINSIC_CY=26004, -}; - -//! @} OBSENSOR - -//! @} videoio_flags_others - -/** @brief Read data stream interface - */ -class CV_EXPORTS_W IStreamReader -{ -public: - virtual ~IStreamReader(); - - /** @brief Read bytes from stream */ - virtual long long read(char* buffer, long long size) = 0; - - /** @brief Sets the stream position - * - * @param offset Seek offset - * @param origin SEEK_SET / SEEK_END / SEEK_CUR - * - * @see fseek - */ - virtual long long seek(long long offset, int origin) = 0; -}; - -class IVideoCapture; -//! @cond IGNORED -namespace internal { class VideoCapturePrivateAccessor; } -//! @endcond IGNORED - -/** @brief Class for video capturing from video files, image sequences or cameras. - -The class provides C++ API for capturing video from cameras or for reading video files and image sequences. - -Here is how the class can be used: -@include samples/cpp/videocapture_basic.cpp - -@note In @ref videoio_c "C API" the black-box structure `CvCapture` is used instead of %VideoCapture. -@note -- (C++) A basic sample on using the %VideoCapture interface can be found at - `OPENCV_SOURCE_CODE/samples/cpp/videocapture_starter.cpp` -- (Python) A basic sample on using the %VideoCapture interface can be found at - `OPENCV_SOURCE_CODE/samples/python/video.py` -- (Python) A multi threaded video processing sample can be found at - `OPENCV_SOURCE_CODE/samples/python/video_threaded.py` -- (Python) %VideoCapture sample showcasing some features of the Video4Linux2 backend - `OPENCV_SOURCE_CODE/samples/python/video_v4l2.py` - */ -class CV_EXPORTS_W VideoCapture -{ -public: - /** @brief Default constructor - @note In @ref videoio_c "C API", when you finished working with video, release CvCapture structure with - cvReleaseCapture(), or use Ptr\ that calls cvReleaseCapture() automatically in the - destructor. - */ - CV_WRAP VideoCapture(); - - /** @overload - @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference - - @param filename it can be: - - name of video file (eg. `video.avi`) - - or image sequence (eg. `img_%02d.jpg`, which will read samples like `img_00.jpg, img_01.jpg, img_02.jpg, ...`) - - or URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`) - - or GStreamer pipeline string in gst-launch tool format in case if GStreamer is used as backend - Note that each video stream or IP camera feed has its own URL scheme. Please refer to the - documentation of source stream to know the right URL. - @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader - implementation if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW. - - @sa cv::VideoCaptureAPIs - */ - CV_WRAP explicit VideoCapture(const String& filename, int apiPreference = CAP_ANY); - - /** @overload - @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - */ - CV_WRAP explicit VideoCapture(const String& filename, int apiPreference, const std::vector& params); - - /** @overload - @brief Opens a camera for video capturing - - @param index id of the video capturing device to open. To open default camera using default backend just pass 0. - (to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY) - @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader - implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L. - - @sa cv::VideoCaptureAPIs - */ - CV_WRAP explicit VideoCapture(int index, int apiPreference = CAP_ANY); - - /** @overload - @brief Opens a camera for video capturing with API Preference and parameters - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - */ - CV_WRAP explicit VideoCapture(int index, int apiPreference, const std::vector& params); - - /** @overload - @brief Opens a video using data stream. - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - */ - CV_WRAP VideoCapture(const Ptr& source, int apiPreference, const std::vector& params); - - /** @brief Default destructor - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - virtual ~VideoCapture(); - - /** @brief Opens a video file or a capturing device or an IP video stream for video capturing. - - @overload - - Parameters are same as the constructor VideoCapture(const String& filename, int apiPreference = CAP_ANY) - @return `true` if the file has been successfully opened - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(const String& filename, int apiPreference = CAP_ANY); - - /** @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters - - @overload - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - - @return `true` if the file has been successfully opened - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(const String& filename, int apiPreference, const std::vector& params); - - /** @brief Opens a camera for video capturing - - @overload - - Parameters are same as the constructor VideoCapture(int index, int apiPreference = CAP_ANY) - @return `true` if the camera has been successfully opened. - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(int index, int apiPreference = CAP_ANY); - - /** @brief Opens a camera for video capturing with API Preference and parameters - - @overload - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - - @return `true` if the camera has been successfully opened. - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(int index, int apiPreference, const std::vector& params); - - /** @brief Opens a video using data stream. - - @overload - - The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. - See cv::VideoCaptureProperties - - @return `true` if the file has been successfully opened - - The method first calls VideoCapture::release to close the already opened file or camera. - */ - CV_WRAP virtual bool open(const Ptr& source, int apiPreference, const std::vector& params); - - /** @brief Returns true if video capturing has been initialized already. - - If the previous call to VideoCapture constructor or VideoCapture::open() succeeded, the method returns - true. - */ - CV_WRAP virtual bool isOpened() const; - - /** @brief Closes video file or capturing device. - - The method is automatically called by subsequent VideoCapture::open and by VideoCapture - destructor. - - The C function also deallocates memory and clears \*capture pointer. - */ - CV_WRAP virtual void release(); - - /** @brief Grabs the next frame from video file or capturing device. - - @return `true` (non-zero) in the case of success. - - The method/function grabs the next frame from video file or camera and returns true (non-zero) in - the case of success. - - The primary use of the function is in multi-camera environments, especially when the cameras do not - have hardware synchronization. That is, you call VideoCapture::grab() for each camera and after that - call the slower method VideoCapture::retrieve() to decode and get frame from each camera. This way - the overhead on demosaicing or motion jpeg decompression etc. is eliminated and the retrieved frames - from different cameras will be closer in time. - - Also, when a connected camera is multi-head (for example, a stereo camera or a Kinect device), the - correct way of retrieving data from it is to call VideoCapture::grab() first and then call - VideoCapture::retrieve() one or more times with different values of the channel parameter. - - @ref tutorial_kinect_openni - */ - CV_WRAP virtual bool grab(); - - /** @brief Decodes and returns the grabbed video frame. - - @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. - @param flag it could be a frame index or a driver specific flag - @return `false` if no frames has been grabbed - - The method decodes and returns the just grabbed frame. If no frames has been grabbed - (camera has been disconnected, or there are no more frames in video file), the method returns false - and the function returns an empty image (with %cv::Mat, test it with Mat::empty()). - - @sa read() - - @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video - capturing structure. It is not allowed to modify or release the image! You can copy the frame using - cvCloneImage and then do whatever you want with the copy. - */ - CV_WRAP virtual bool retrieve(OutputArray image, int flag = 0); - - /** @brief Stream operator to read the next video frame. - @sa read() - */ - virtual VideoCapture& operator >> (CV_OUT Mat& image); - - /** @overload - @sa read() - */ - virtual VideoCapture& operator >> (CV_OUT UMat& image); - - /** @brief Grabs, decodes and returns the next video frame. - - @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. - @return `false` if no frames has been grabbed - - The method/function combines VideoCapture::grab() and VideoCapture::retrieve() in one call. This is the - most convenient method for reading video files or capturing data from decode and returns the just - grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more - frames in video file), the method returns false and the function returns empty image (with %cv::Mat, test it with Mat::empty()). - - @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video - capturing structure. It is not allowed to modify or release the image! You can copy the frame using - cvCloneImage and then do whatever you want with the copy. - */ - CV_WRAP virtual bool read(OutputArray image); - - /** @brief Sets a property in the VideoCapture. - - @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) - or one from @ref videoio_flags_others - @param value Value of the property. - @return `true` if the property is supported by backend used by the VideoCapture instance. - @note Even if it returns `true` this doesn't ensure that the property - value has been accepted by the capture device. See note in VideoCapture::get() - */ - CV_WRAP virtual bool set(int propId, double value); - - /** @brief Returns the specified VideoCapture property - - @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) - or one from @ref videoio_flags_others - @return Value for the specified property. Value 0 is returned when querying a property that is - not supported by the backend used by the VideoCapture instance. - - @note Reading / writing properties involves many layers. Some unexpected result might happens - along this chain. - @code{.txt} - VideoCapture -> API Backend -> Operating System -> Device Driver -> Device Hardware - @endcode - The returned value might be different from what really used by the device or it could be encoded - using device dependent rules (eg. steps or percentage). Effective behaviour depends from device - driver and API Backend - - */ - CV_WRAP virtual double get(int propId) const; - - /** @brief Returns used backend API name - - @note Stream should be opened. - */ - CV_WRAP String getBackendName() const; - - /** Switches exceptions mode - * - * methods raise exceptions if not successful instead of returning an error code - */ - CV_WRAP void setExceptionMode(bool enable) { throwOnFail = enable; } - - /// query if exception mode is active - CV_WRAP bool getExceptionMode() const { return throwOnFail; } - - - /** @brief Wait for ready frames from VideoCapture. - - @param streams input video streams - @param readyIndex stream indexes with grabbed frames (ready to use .retrieve() to fetch actual frame) - @param timeoutNs number of nanoseconds (0 - infinite) - @return `true` if streamReady is not empty - - @throws Exception %Exception on stream errors (check .isOpened() to filter out malformed streams) or VideoCapture type is not supported - - The primary use of the function is in multi-camera environments. - The method fills the ready state vector, grabs video frame, if camera is ready. - - After this call use VideoCapture::retrieve() to decode and fetch frame data. - */ - CV_WRAP static - bool waitAny( - const std::vector& streams, - CV_OUT std::vector& readyIndex, - int64 timeoutNs = 0); - -protected: - Ptr cap; - Ptr icap; - bool throwOnFail; - - friend class internal::VideoCapturePrivateAccessor; -}; - -class IVideoWriter; - -/** @example samples/cpp/tutorial_code/videoio/video-write/video-write.cpp -Check @ref tutorial_video_write "the corresponding tutorial" for more details -*/ - -/** @example samples/cpp/videowriter_basic.cpp -An example using VideoCapture and VideoWriter class -*/ - -/** @brief Video writer class. - -The class provides C++ API for writing video files or image sequences. -*/ -class CV_EXPORTS_W VideoWriter -{ -public: - /** @brief Default constructors - - The constructors/functions initialize video writers. - - On Linux FFMPEG is used to write videos; - - On Windows FFMPEG or MSWF or DSHOW is used; - - On MacOSX AVFoundation is used. - */ - CV_WRAP VideoWriter(); - - /** @overload - @param filename Name of the output video file. - @param fourcc 4-character code of codec used to compress the frames. For example, - VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec, VideoWriter::fourcc('M','J','P','G') - is a motion-jpeg codec etc. List of codes can be obtained at - [MSDN](https://docs.microsoft.com/en-us/windows/win32/medfound/video-fourccs) page - or with this [page](https://fourcc.org/codecs.php) - of the fourcc site for a more complete list). FFMPEG backend with MP4 container natively uses - other values as fourcc code: see [ObjectType](http://mp4ra.org/#/codecs), - so you may receive a warning message from OpenCV about fourcc code conversion. - @param fps Framerate of the created video stream. - @param frameSize Size of the video frames. - @param isColor If it is not zero, the encoder will expect and encode color frames, otherwise it - will work with grayscale frames. - - @b Tips: - - With some backends `fourcc=-1` pops up the codec selection dialog from the system. - - To save image sequence use a proper filename (eg. `img_%02d.jpg`) and `fourcc=0` - OR `fps=0`. Use uncompressed image format (eg. `img_%02d.BMP`) to save raw frames. - - Most codecs are lossy. If you want lossless video file you need to use a lossless codecs - (eg. FFMPEG FFV1, Huffman HFYU, Lagarith LAGS, etc...) - - If FFMPEG is enabled, using `codec=0; fps=0;` you can create an uncompressed (raw) video file. - - If FFMPEG is used, we allow frames of odd width or height, but in this case we truncate - the rightmost column/the bottom row. Probably, this should be handled more elegantly, - but some internal functions inside FFMPEG swscale require even width/height. - */ - CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - The `apiPreference` parameter allows to specify API backends to use. Can be used to enforce a specific reader implementation - if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_GSTREAMER. - */ - CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - * The `params` parameter allows to specify extra encoder parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) - * see cv::VideoWriterProperties - */ - CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, const Size& frameSize, - const std::vector& params); - - /** @overload - */ - CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, - const Size& frameSize, const std::vector& params); - - /** @brief Default destructor - - The method first calls VideoWriter::release to close the already opened file. - */ - virtual ~VideoWriter(); - - /** @brief Initializes or reinitializes video writer. - - The method opens video writer. Parameters are the same as in the constructor - VideoWriter::VideoWriter. - @return `true` if video writer has been successfully initialized - - The method first calls VideoWriter::release to close the already opened file. - */ - CV_WRAP virtual bool open(const String& filename, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - */ - CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, - Size frameSize, bool isColor = true); - - /** @overload - */ - CV_WRAP bool open(const String& filename, int fourcc, double fps, const Size& frameSize, - const std::vector& params); - - /** @overload - */ - CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, - const Size& frameSize, const std::vector& params); - - /** @brief Returns true if video writer has been successfully initialized. - */ - CV_WRAP virtual bool isOpened() const; - - /** @brief Closes the video writer. - - The method is automatically called by subsequent VideoWriter::open and by the VideoWriter - destructor. - */ - CV_WRAP virtual void release(); - - /** @brief Stream operator to write the next video frame. - @sa write - */ - virtual VideoWriter& operator << (const Mat& image); - - /** @overload - @sa write - */ - virtual VideoWriter& operator << (const UMat& image); - - /** @brief Writes the next video frame - - @param image The written frame. In general, color images are expected in BGR format. - - The function/method writes the specified image to video file. It must have the same size as has - been specified when opening the video writer. - */ - CV_WRAP virtual void write(InputArray image); - - /** @brief Sets a property in the VideoWriter. - - @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) - or one of @ref videoio_flags_others - - @param value Value of the property. - @return `true` if the property is supported by the backend used by the VideoWriter instance. - */ - CV_WRAP virtual bool set(int propId, double value); - - /** @brief Returns the specified VideoWriter property - - @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) - or one of @ref videoio_flags_others - - @return Value for the specified property. Value 0 is returned when querying a property that is - not supported by the backend used by the VideoWriter instance. - */ - CV_WRAP virtual double get(int propId) const; - - /** @brief Concatenates 4 chars to a fourcc code - - @return a fourcc code - - This static method constructs the fourcc code of the codec to be used in the constructor - VideoWriter::VideoWriter or VideoWriter::open. - */ - CV_WRAP static int fourcc(char c1, char c2, char c3, char c4); - - /** @brief Returns used backend API name - - @note Stream should be opened. - */ - CV_WRAP String getBackendName() const; - -protected: - Ptr writer; - Ptr iwriter; - - static Ptr create(const String& filename, int fourcc, double fps, - Size frameSize, bool isColor = true); -}; - -//! @cond IGNORED -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvCapture* obj) const; }; -template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvVideoWriter* obj) const; }; -//! @endcond IGNORED - -//! @} videoio - -} // cv - -#endif //OPENCV_VIDEOIO_HPP +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_VIDEOIO_HPP +#define OPENCV_VIDEOIO_HPP + +#include "opencv2/core.hpp" + +/** + @defgroup videoio Video I/O + + @brief Read and write video or images sequence with OpenCV + + ### See also: + - @ref videoio_overview + - Tutorials: @ref tutorial_table_of_content_app + @{ + @defgroup videoio_flags_base Flags for video I/O + @defgroup videoio_flags_others Additional flags for video I/O API backends + @defgroup videoio_hwaccel Hardware-accelerated video decoding and encoding + @defgroup videoio_c C API for video I/O + @defgroup videoio_ios iOS glue for video I/O + @defgroup videoio_winrt WinRT glue for video I/O + @defgroup videoio_registry Query I/O API backends registry + @} +*/ + +////////////////////////////////// video io ///////////////////////////////// + +typedef struct CvCapture CvCapture; +typedef struct CvVideoWriter CvVideoWriter; + +namespace cv +{ + +//! @addtogroup videoio +//! @{ + +//! @addtogroup videoio_flags_base +//! @{ + + +/** @brief cv::VideoCapture API backends identifier. + +Select preferred API for a capture object. +To be used in the VideoCapture::VideoCapture() constructor or VideoCapture::open() + +@note +- Backends are available only if they have been built with your OpenCV binaries. +See @ref videoio_overview for more information. +- Microsoft Media Foundation backend tries to use hardware accelerated transformations +if possible. Environment flag "OPENCV_VIDEOIO_MSMF_ENABLE_HW_TRANSFORMS" set to 0 +disables it and may improve initialization time. More details: +https://learn.microsoft.com/en-us/windows/win32/medfound/mf-readwrite-enable-hardware-transforms +*/ +enum VideoCaptureAPIs { + CAP_ANY = 0, //!< Auto detect == 0 + CAP_VFW = 200, //!< Video For Windows (obsolete, removed) + CAP_V4L = 200, //!< V4L/V4L2 capturing support + CAP_V4L2 = CAP_V4L, //!< Same as CAP_V4L + CAP_FIREWIRE = 300, //!< IEEE 1394 drivers + CAP_FIREWARE = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_IEEE1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_DC1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_CMU1394 = CAP_FIREWIRE, //!< Same value as CAP_FIREWIRE + CAP_QT = 500, //!< QuickTime (obsolete, removed) + CAP_UNICAP = 600, //!< Unicap drivers (obsolete, removed) + CAP_DSHOW = 700, //!< DirectShow (via videoInput) + CAP_PVAPI = 800, //!< PvAPI, Prosilica GigE SDK + CAP_OPENNI = 900, //!< OpenNI (for Kinect) + CAP_OPENNI_ASUS = 910, //!< OpenNI (for Asus Xtion) + CAP_ANDROID = 1000, //!< MediaNDK (API Level 21+) and NDK Camera (API level 24+) for Android + CAP_XIAPI = 1100, //!< XIMEA Camera API + CAP_AVFOUNDATION = 1200, //!< AVFoundation framework for iOS (OS X Lion will have the same API) + CAP_GIGANETIX = 1300, //!< Smartek Giganetix GigEVisionSDK + CAP_MSMF = 1400, //!< Microsoft Media Foundation (via videoInput). See platform specific notes above. + CAP_WINRT = 1410, //!< Microsoft Windows Runtime using Media Foundation + CAP_INTELPERC = 1500, //!< RealSense (former Intel Perceptual Computing SDK) + CAP_REALSENSE = 1500, //!< Synonym for CAP_INTELPERC + CAP_OPENNI2 = 1600, //!< OpenNI2 (for Kinect) + CAP_OPENNI2_ASUS = 1610, //!< OpenNI2 (for Asus Xtion and Occipital Structure sensors) + CAP_OPENNI2_ASTRA= 1620, //!< OpenNI2 (for Orbbec Astra) + CAP_GPHOTO2 = 1700, //!< gPhoto2 connection + CAP_GSTREAMER = 1800, //!< GStreamer + CAP_FFMPEG = 1900, //!< Open and record video file or stream using the FFMPEG library + CAP_IMAGES = 2000, //!< OpenCV Image Sequence (e.g. img_%02d.jpg) + CAP_ARAVIS = 2100, //!< Aravis SDK + CAP_OPENCV_MJPEG = 2200, //!< Built-in OpenCV MotionJPEG codec + CAP_INTEL_MFX = 2300, //!< Intel MediaSDK + CAP_XINE = 2400, //!< XINE engine (Linux) + CAP_UEYE = 2500, //!< uEye Camera API + CAP_OBSENSOR = 2600, //!< For Orbbec 3D-Sensor device/module (Astra+, Femto, Astra2, Gemini2, Gemini2L, Gemini2XL, Femto Mega) attention: Astra2 cameras currently only support Windows and Linux kernel versions no higher than 4.15, and higher versions of Linux kernel may have exceptions. + }; + + +/** @brief cv::VideoCapture generic properties identifier. + + Reading / writing properties involves many layers. Some unexpected result might happens along this chain. + Effective behaviour depends from device hardware, driver and API Backend. + @sa videoio_flags_others, VideoCapture::get(), VideoCapture::set() +*/ +enum VideoCaptureProperties { + CAP_PROP_POS_MSEC =0, //!< Current position of the video file in milliseconds. + CAP_PROP_POS_FRAMES =1, //!< 0-based index of the frame to be decoded/captured next. When the index i is set in RAW mode (CAP_PROP_FORMAT == -1) this will seek to the key frame k, where k <= i. + CAP_PROP_POS_AVI_RATIO =2, //!< Relative position of the video file: 0=start of the film, 1=end of the film. + CAP_PROP_FRAME_WIDTH =3, //!< Width of the frames in the video stream. + CAP_PROP_FRAME_HEIGHT =4, //!< Height of the frames in the video stream. + CAP_PROP_FPS =5, //!< Frame rate. + CAP_PROP_FOURCC =6, //!< 4-character code of codec. see VideoWriter::fourcc . + CAP_PROP_FRAME_COUNT =7, //!< Number of frames in the video file. + CAP_PROP_FORMAT =8, //!< Format of the %Mat objects (see Mat::type()) returned by VideoCapture::retrieve(). + //!< Set value -1 to fetch undecoded RAW video streams (as Mat 8UC1). + CAP_PROP_MODE =9, //!< Backend-specific value indicating the current capture mode. + CAP_PROP_BRIGHTNESS =10, //!< Brightness of the image (only for those cameras that support). + CAP_PROP_CONTRAST =11, //!< Contrast of the image (only for cameras). + CAP_PROP_SATURATION =12, //!< Saturation of the image (only for cameras). + CAP_PROP_HUE =13, //!< Hue of the image (only for cameras). + CAP_PROP_GAIN =14, //!< Gain of the image (only for those cameras that support). + CAP_PROP_EXPOSURE =15, //!< Exposure (only for those cameras that support). + CAP_PROP_CONVERT_RGB =16, //!< Boolean flags indicating whether images should be converted to RGB.
+ //!< *GStreamer note*: The flag is ignored in case if custom pipeline is used. It's user responsibility to interpret pipeline output. + CAP_PROP_WHITE_BALANCE_BLUE_U =17, //!< Currently unsupported. + CAP_PROP_RECTIFICATION =18, //!< Rectification flag for stereo cameras (note: only supported by DC1394 v 2.x backend currently). + CAP_PROP_MONOCHROME =19, + CAP_PROP_SHARPNESS =20, + CAP_PROP_AUTO_EXPOSURE =21, //!< DC1394: exposure control done by camera, user can adjust reference level using this feature. + CAP_PROP_GAMMA =22, + CAP_PROP_TEMPERATURE =23, + CAP_PROP_TRIGGER =24, + CAP_PROP_TRIGGER_DELAY =25, + CAP_PROP_WHITE_BALANCE_RED_V =26, + CAP_PROP_ZOOM =27, + CAP_PROP_FOCUS =28, + CAP_PROP_GUID =29, + CAP_PROP_ISO_SPEED =30, + CAP_PROP_BACKLIGHT =32, + CAP_PROP_PAN =33, + CAP_PROP_TILT =34, + CAP_PROP_ROLL =35, + CAP_PROP_IRIS =36, + CAP_PROP_SETTINGS =37, //!< Pop up video/camera filter dialog (note: only supported by DSHOW backend currently. The property value is ignored) + CAP_PROP_BUFFERSIZE =38, + CAP_PROP_AUTOFOCUS =39, + CAP_PROP_SAR_NUM =40, //!< Sample aspect ratio: num/den (num) + CAP_PROP_SAR_DEN =41, //!< Sample aspect ratio: num/den (den) + CAP_PROP_BACKEND =42, //!< Current backend (enum VideoCaptureAPIs). Read-only property + CAP_PROP_CHANNEL =43, //!< Video input or Channel Number (only for those cameras that support) + CAP_PROP_AUTO_WB =44, //!< enable/ disable auto white-balance + CAP_PROP_WB_TEMPERATURE=45, //!< white-balance color temperature + CAP_PROP_CODEC_PIXEL_FORMAT =46, //!< (read-only) codec's pixel format. 4-character code - see VideoWriter::fourcc . Subset of [AV_PIX_FMT_*](https://github.com/FFmpeg/FFmpeg/blob/master/libavcodec/raw.c) or -1 if unknown + CAP_PROP_BITRATE =47, //!< (read-only) Video bitrate in kbits/s + CAP_PROP_ORIENTATION_META=48, //!< (read-only) Frame rotation defined by stream meta (applicable for FFmpeg and AVFoundation back-ends only) + CAP_PROP_ORIENTATION_AUTO=49, //!< if true - rotates output frames of CvCapture considering video file's metadata (applicable for FFmpeg and AVFoundation back-ends only) (https://github.com/opencv/opencv/issues/15499) + CAP_PROP_HW_ACCELERATION=50, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in cv::VideoCapture constructor / .open() method. Default value is backend-specific. + CAP_PROP_HW_DEVICE =51, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. + CAP_PROP_HW_ACCELERATION_USE_OPENCL=52, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between HW accelerated decoder and cv::UMat. + CAP_PROP_OPEN_TIMEOUT_MSEC=53, //!< (**open-only**) timeout in milliseconds for opening a video capture (applicable for FFmpeg and GStreamer back-ends only) + CAP_PROP_READ_TIMEOUT_MSEC=54, //!< (**open-only**) timeout in milliseconds for reading from a video capture (applicable for FFmpeg and GStreamer back-ends only) + CAP_PROP_STREAM_OPEN_TIME_USEC =55, //!< (read-only) time in microseconds since Jan 1 1970 when stream was opened. Applicable for FFmpeg backend only. Useful for RTSP and other live streams + CAP_PROP_VIDEO_TOTAL_CHANNELS = 56, //!< (read-only) Number of video channels + CAP_PROP_VIDEO_STREAM = 57, //!< (**open-only**) Specify video stream, 0-based index. Use -1 to disable video stream from file or IP cameras. Default value is 0. + CAP_PROP_AUDIO_STREAM = 58, //!< (**open-only**) Specify stream in multi-language media files, -1 - disable audio processing or microphone. Default value is -1. + CAP_PROP_AUDIO_POS = 59, //!< (read-only) Audio position is measured in samples. Accurate audio sample timestamp of previous grabbed fragment. See CAP_PROP_AUDIO_SAMPLES_PER_SECOND and CAP_PROP_AUDIO_SHIFT_NSEC. + CAP_PROP_AUDIO_SHIFT_NSEC = 60, //!< (read only) Contains the time difference between the start of the audio stream and the video stream in nanoseconds. Positive value means that audio is started after the first video frame. Negative value means that audio is started before the first video frame. + CAP_PROP_AUDIO_DATA_DEPTH = 61, //!< (open, read) Alternative definition to bits-per-sample, but with clear handling of 32F / 32S + CAP_PROP_AUDIO_SAMPLES_PER_SECOND = 62, //!< (open, read) determined from file/codec input. If not specified, then selected audio sample rate is 44100 + CAP_PROP_AUDIO_BASE_INDEX = 63, //!< (read-only) Index of the first audio channel for .retrieve() calls. That audio channel number continues enumeration after video channels. + CAP_PROP_AUDIO_TOTAL_CHANNELS = 64, //!< (read-only) Number of audio channels in the selected audio stream (mono, stereo, etc) + CAP_PROP_AUDIO_TOTAL_STREAMS = 65, //!< (read-only) Number of audio streams. + CAP_PROP_AUDIO_SYNCHRONIZE = 66, //!< (open, read) Enables audio synchronization. + CAP_PROP_LRF_HAS_KEY_FRAME = 67, //!< FFmpeg back-end only - Indicates whether the Last Raw Frame (LRF), output from VideoCapture::read() when VideoCapture is initialized with VideoCapture::open(CAP_FFMPEG, {CAP_PROP_FORMAT, -1}) or VideoCapture::set(CAP_PROP_FORMAT,-1) is called before the first call to VideoCapture::read(), contains encoded data for a key frame. + CAP_PROP_CODEC_EXTRADATA_INDEX = 68, //!< Positive index indicates that returning extra data is supported by the video back end. This can be retrieved as cap.retrieve(data, ). E.g. When reading from a h264 encoded RTSP stream, the FFmpeg backend could return the SPS and/or PPS if available (if sent in reply to a DESCRIBE request), from calls to cap.retrieve(data, ). + CAP_PROP_FRAME_TYPE = 69, //!< (read-only) FFmpeg back-end only - Frame type ascii code (73 = 'I', 80 = 'P', 66 = 'B' or 63 = '?' if unknown) of the most recently read frame. + CAP_PROP_N_THREADS = 70, //!< (**open-only**) Set the maximum number of threads to use. Use 0 to use as many threads as CPU cores (applicable for FFmpeg back-end only). + CAP_PROP_PTS = 71, //!< (read-only) FFmpeg back-end only - presentation timestamp of the most recently read frame using the FPS time base. e.g. fps = 25, VideoCapture::get(\ref CAP_PROP_PTS) = 3, presentation time = 3/25 seconds. + CAP_PROP_DTS_DELAY = 72, //!< (read-only) FFmpeg back-end only - maximum difference between presentation (pts) and decompression timestamps (dts) using FPS time base. e.g. delay is maximum when frame_num = 0, if true, VideoCapture::get(\ref CAP_PROP_PTS) = 0 and VideoCapture::get(\ref CAP_PROP_DTS_DELAY) = 2, dts = -2. Non zero values usually imply the stream is encoded using B-frames which are not decoded in presentation order. +#ifndef CV_DOXYGEN + CV__CAP_PROP_LATEST +#endif + }; + +/** @brief cv::VideoWriter generic properties identifier. + @sa VideoWriter::get(), VideoWriter::set() +*/ +enum VideoWriterProperties { + VIDEOWRITER_PROP_QUALITY = 1, //!< Current quality (0..100%) of the encoded videostream. Can be adjusted dynamically in some codecs. + VIDEOWRITER_PROP_FRAMEBYTES = 2, //!< (Read-only): Size of just encoded video frame. Note that the encoding order may be different from representation order. + VIDEOWRITER_PROP_NSTRIPES = 3, //!< Number of stripes for parallel encoding. -1 for auto detection. + VIDEOWRITER_PROP_IS_COLOR = 4, //!< If it is not zero, the encoder will expect and encode color frames, otherwise it + //!< will work with grayscale frames. + VIDEOWRITER_PROP_DEPTH = 5, //!< Defaults to \ref CV_8U. + VIDEOWRITER_PROP_HW_ACCELERATION = 6, //!< (**open-only**) Hardware acceleration type (see #VideoAccelerationType). Setting supported only via `params` parameter in VideoWriter constructor / .open() method. Default value is backend-specific. + VIDEOWRITER_PROP_HW_DEVICE = 7, //!< (**open-only**) Hardware device index (select GPU if multiple available). Device enumeration is acceleration type specific. + VIDEOWRITER_PROP_HW_ACCELERATION_USE_OPENCL= 8, //!< (**open-only**) If non-zero, create new OpenCL context and bind it to current thread. The OpenCL context created with Video Acceleration context attached it (if not attached yet) for optimized GPU data copy between cv::UMat and HW accelerated encoder. + VIDEOWRITER_PROP_RAW_VIDEO = 9, //!< (**open-only**) Set to non-zero to enable encapsulation of an encoded raw video stream. Each raw encoded video frame should be passed to VideoWriter::write() as single row or column of a \ref CV_8UC1 Mat. \note If the key frame interval is not 1 then it must be manually specified by the user. This can either be performed during initialization passing \ref VIDEOWRITER_PROP_KEY_INTERVAL as one of the extra encoder params to \ref VideoWriter::VideoWriter(const String &, int, double, const Size &, const std::vector< int > ¶ms) or afterwards by setting the \ref VIDEOWRITER_PROP_KEY_FLAG with \ref VideoWriter::set() before writing each frame. FFMpeg backend only. + VIDEOWRITER_PROP_KEY_INTERVAL = 10, //!< (**open-only**) Set the key frame interval using raw video encapsulation (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). Defaults to 1 when not set. FFmpeg back-end only. + VIDEOWRITER_PROP_KEY_FLAG = 11, //!< Set to non-zero to signal that the following frames are key frames or zero if not, when encapsulating raw video (\ref VIDEOWRITER_PROP_RAW_VIDEO != 0). FFmpeg back-end only. + VIDEOWRITER_PROP_PTS = 12, //!< Specifies the frame presentation timestamp for each frame using the FPS time base. This property is **only** necessary when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be provided by your external encoder and for video sources with fixed frame rates it is equivalent to dividing the current frame's presentation time (\ref CAP_PROP_POS_MSEC) by the frame duration (1000.0 / VideoCapture::get(\ref CAP_PROP_FPS)). It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_PTS). FFmpeg back-end only. + VIDEOWRITER_PROP_DTS_DELAY = 13, //!< Specifies the maximum difference between presentation (pts) and decompression timestamps (dts) using the FPS time base. This property is necessary **only** when encapsulating **externally** encoded video where the decoding order differs from the presentation order, such as in GOP patterns with bi-directional B-frames. The value should be calculated based on the specific GOP pattern used during encoding. For example, in a GOP with presentation order IBP and decoding order IPB, this value would be 1, as the B-frame is the second frame presented but the third to be decoded. It can be queried from the resulting encapsulated video file using VideoCapture::get(\ref CAP_PROP_DTS_DELAY). Non-zero values usually imply the stream is encoded using B-frames. FFmpeg back-end only. +#ifndef CV_DOXYGEN + CV__VIDEOWRITER_PROP_LATEST +#endif +}; + +//! @} videoio_flags_base + +//! @addtogroup videoio_flags_others +//! @{ + +/** @name Hardware acceleration support + @{ +*/ + +/** @brief Video Acceleration type + * + * Used as value in #CAP_PROP_HW_ACCELERATION and #VIDEOWRITER_PROP_HW_ACCELERATION + * + * @note In case of FFmpeg backend, it translated to enum AVHWDeviceType (https://github.com/FFmpeg/FFmpeg/blob/master/libavutil/hwcontext.h) + */ +enum VideoAccelerationType +{ + VIDEO_ACCELERATION_NONE = 0, //!< Do not require any specific H/W acceleration, prefer software processing. + //!< Reading of this value means that special H/W accelerated handling is not added or not detected by OpenCV. + + VIDEO_ACCELERATION_ANY = 1, //!< Prefer to use H/W acceleration. If no one supported, then fallback to software processing. + //!< @note H/W acceleration may require special configuration of used environment. + //!< @note Results in encoding scenario may differ between software and hardware accelerated encoders. + + VIDEO_ACCELERATION_D3D11 = 2, //!< DirectX 11 + VIDEO_ACCELERATION_VAAPI = 3, //!< VAAPI + VIDEO_ACCELERATION_MFX = 4, //!< libmfx (Intel MediaSDK/oneVPL) +}; + +//! @} Hardware acceleration support + +/** @name IEEE 1394 drivers + @{ +*/ + +/** @brief Modes of the IEEE 1394 controlling registers +(can be: auto, manual, auto single push, absolute Latter allowed with any other mode) +every feature can have only one mode turned on at a time +*/ +enum { CAP_PROP_DC1394_OFF = -4, //!< turn the feature off (not controlled manually nor automatically). + CAP_PROP_DC1394_MODE_MANUAL = -3, //!< set automatically when a value of the feature is set by the user. + CAP_PROP_DC1394_MODE_AUTO = -2, + CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, + CAP_PROP_DC1394_MAX = 31 + }; + +//! @} IEEE 1394 drivers + +/** @name OpenNI (for Kinect) + @{ +*/ + +//! OpenNI map generators +enum { CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, + CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, + CAP_OPENNI_IR_GENERATOR = 1 << 29, + CAP_OPENNI_GENERATORS_MASK = CAP_OPENNI_DEPTH_GENERATOR + CAP_OPENNI_IMAGE_GENERATOR + CAP_OPENNI_IR_GENERATOR + }; + +//! Properties of cameras available through OpenNI backend +enum { CAP_PROP_OPENNI_OUTPUT_MODE = 100, + CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, //!< In mm + CAP_PROP_OPENNI_BASELINE = 102, //!< In mm + CAP_PROP_OPENNI_FOCAL_LENGTH = 103, //!< In pixels + CAP_PROP_OPENNI_REGISTRATION = 104, //!< Flag that synchronizes the remapping depth map to image map + //!< by changing depth generator's view point (if the flag is "on") or + //!< sets this view point to its normal one (if the flag is "off"). + CAP_PROP_OPENNI_REGISTRATION_ON = CAP_PROP_OPENNI_REGISTRATION, + CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, + CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, + CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, + CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, + CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, + CAP_PROP_OPENNI2_SYNC = 110, + CAP_PROP_OPENNI2_MIRROR = 111 + }; + +#ifdef _MSC_VER +#pragma warning( push ) +#pragma warning( disable: 5054 ) +#endif +//! OpenNI shortcuts +enum { CAP_OPENNI_IMAGE_GENERATOR_PRESENT = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, + CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = +CAP_OPENNI_IMAGE_GENERATOR + CAP_PROP_OPENNI_OUTPUT_MODE, + CAP_OPENNI_DEPTH_GENERATOR_PRESENT = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT, + CAP_OPENNI_DEPTH_GENERATOR_BASELINE = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_BASELINE, + CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_FOCAL_LENGTH, + CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = +CAP_OPENNI_DEPTH_GENERATOR + CAP_PROP_OPENNI_REGISTRATION, + CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, + CAP_OPENNI_IR_GENERATOR_PRESENT = +CAP_OPENNI_IR_GENERATOR + CAP_PROP_OPENNI_GENERATOR_PRESENT + }; +#ifdef _MSC_VER +#pragma warning( pop ) +#endif + +//! OpenNI data given from depth generator +enum { CAP_OPENNI_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) + CAP_OPENNI_POINT_CLOUD_MAP = 1, //!< XYZ in meters (CV_32FC3) + CAP_OPENNI_DISPARITY_MAP = 2, //!< Disparity in pixels (CV_8UC1) + CAP_OPENNI_DISPARITY_MAP_32F = 3, //!< Disparity in pixels (CV_32FC1) + CAP_OPENNI_VALID_DEPTH_MASK = 4, //!< CV_8UC1 + + CAP_OPENNI_BGR_IMAGE = 5, //!< Data given from RGB image generator + CAP_OPENNI_GRAY_IMAGE = 6, //!< Data given from RGB image generator + + CAP_OPENNI_IR_IMAGE = 7 //!< Data given from IR image generator + }; + +//! Supported output modes of OpenNI image generator +enum { CAP_OPENNI_VGA_30HZ = 0, + CAP_OPENNI_SXGA_15HZ = 1, + CAP_OPENNI_SXGA_30HZ = 2, + CAP_OPENNI_QVGA_30HZ = 3, + CAP_OPENNI_QVGA_60HZ = 4 + }; + +//! @} OpenNI + +/** @name GStreamer + @{ +*/ + +enum { CAP_PROP_GSTREAMER_QUEUE_LENGTH = 200 //!< Default is 1 + }; + +//! @} GStreamer + +/** @name PvAPI, Prosilica GigE SDK + @{ +*/ + +//! PVAPI +enum { CAP_PROP_PVAPI_MULTICASTIP = 300, //!< IP for enable multicast master mode. 0 for disable multicast. + CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, //!< FrameStartTriggerMode: Determines how a frame is initiated. + CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, //!< Horizontal sub-sampling of the image. + CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, //!< Vertical sub-sampling of the image. + CAP_PROP_PVAPI_BINNINGX = 304, //!< Horizontal binning factor. + CAP_PROP_PVAPI_BINNINGY = 305, //!< Vertical binning factor. + CAP_PROP_PVAPI_PIXELFORMAT = 306 //!< Pixel format. + }; + +//! PVAPI: FrameStartTriggerMode +enum { CAP_PVAPI_FSTRIGMODE_FREERUN = 0, //!< Freerun + CAP_PVAPI_FSTRIGMODE_SYNCIN1 = 1, //!< SyncIn1 + CAP_PVAPI_FSTRIGMODE_SYNCIN2 = 2, //!< SyncIn2 + CAP_PVAPI_FSTRIGMODE_FIXEDRATE = 3, //!< FixedRate + CAP_PVAPI_FSTRIGMODE_SOFTWARE = 4 //!< Software + }; + +//! PVAPI: DecimationHorizontal, DecimationVertical +enum { CAP_PVAPI_DECIMATION_OFF = 1, //!< Off + CAP_PVAPI_DECIMATION_2OUTOF4 = 2, //!< 2 out of 4 decimation + CAP_PVAPI_DECIMATION_2OUTOF8 = 4, //!< 2 out of 8 decimation + CAP_PVAPI_DECIMATION_2OUTOF16 = 8 //!< 2 out of 16 decimation + }; + +//! PVAPI: PixelFormat +enum { CAP_PVAPI_PIXELFORMAT_MONO8 = 1, //!< Mono8 + CAP_PVAPI_PIXELFORMAT_MONO16 = 2, //!< Mono16 + CAP_PVAPI_PIXELFORMAT_BAYER8 = 3, //!< Bayer8 + CAP_PVAPI_PIXELFORMAT_BAYER16 = 4, //!< Bayer16 + CAP_PVAPI_PIXELFORMAT_RGB24 = 5, //!< Rgb24 + CAP_PVAPI_PIXELFORMAT_BGR24 = 6, //!< Bgr24 + CAP_PVAPI_PIXELFORMAT_RGBA32 = 7, //!< Rgba32 + CAP_PVAPI_PIXELFORMAT_BGRA32 = 8, //!< Bgra32 + }; + +//! @} PvAPI + +/** @name XIMEA Camera API + @{ +*/ + +//! Properties of cameras available through XIMEA SDK backend +enum { CAP_PROP_XI_DOWNSAMPLING = 400, //!< Change image resolution by binning or skipping. + CAP_PROP_XI_DATA_FORMAT = 401, //!< Output data format. + CAP_PROP_XI_OFFSET_X = 402, //!< Horizontal offset from the origin to the area of interest (in pixels). + CAP_PROP_XI_OFFSET_Y = 403, //!< Vertical offset from the origin to the area of interest (in pixels). + CAP_PROP_XI_TRG_SOURCE = 404, //!< Defines source of trigger. + CAP_PROP_XI_TRG_SOFTWARE = 405, //!< Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. + CAP_PROP_XI_GPI_SELECTOR = 406, //!< Selects general purpose input. + CAP_PROP_XI_GPI_MODE = 407, //!< Set general purpose input mode. + CAP_PROP_XI_GPI_LEVEL = 408, //!< Get general purpose level. + CAP_PROP_XI_GPO_SELECTOR = 409, //!< Selects general purpose output. + CAP_PROP_XI_GPO_MODE = 410, //!< Set general purpose output mode. + CAP_PROP_XI_LED_SELECTOR = 411, //!< Selects camera signalling LED. + CAP_PROP_XI_LED_MODE = 412, //!< Define camera signalling LED functionality. + CAP_PROP_XI_MANUAL_WB = 413, //!< Calculates White Balance(must be called during acquisition). + CAP_PROP_XI_AUTO_WB = 414, //!< Automatic white balance. + CAP_PROP_XI_AEAG = 415, //!< Automatic exposure/gain. + CAP_PROP_XI_EXP_PRIORITY = 416, //!< Exposure priority (0.5 - exposure 50%, gain 50%). + CAP_PROP_XI_AE_MAX_LIMIT = 417, //!< Maximum limit of exposure in AEAG procedure. + CAP_PROP_XI_AG_MAX_LIMIT = 418, //!< Maximum limit of gain in AEAG procedure. + CAP_PROP_XI_AEAG_LEVEL = 419, //!< Average intensity of output signal AEAG should achieve(in %). + CAP_PROP_XI_TIMEOUT = 420, //!< Image capture timeout in milliseconds. + CAP_PROP_XI_EXPOSURE = 421, //!< Exposure time in microseconds. + CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, //!< Sets the number of times of exposure in one frame. + CAP_PROP_XI_GAIN_SELECTOR = 423, //!< Gain selector for parameter Gain allows to select different type of gains. + CAP_PROP_XI_GAIN = 424, //!< Gain in dB. + CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, //!< Change image downsampling type. + CAP_PROP_XI_BINNING_SELECTOR = 427, //!< Binning engine selector. + CAP_PROP_XI_BINNING_VERTICAL = 428, //!< Vertical Binning - number of vertical photo-sensitive cells to combine together. + CAP_PROP_XI_BINNING_HORIZONTAL = 429, //!< Horizontal Binning - number of horizontal photo-sensitive cells to combine together. + CAP_PROP_XI_BINNING_PATTERN = 430, //!< Binning pattern type. + CAP_PROP_XI_DECIMATION_SELECTOR = 431, //!< Decimation engine selector. + CAP_PROP_XI_DECIMATION_VERTICAL = 432, //!< Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. + CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, //!< Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. + CAP_PROP_XI_DECIMATION_PATTERN = 434, //!< Decimation pattern type. + CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, //!< Selects which test pattern generator is controlled by the TestPattern feature. + CAP_PROP_XI_TEST_PATTERN = 588, //!< Selects which test pattern type is generated by the selected generator. + CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, //!< Output data format. + CAP_PROP_XI_SHUTTER_TYPE = 436, //!< Change sensor shutter type(CMOS sensor). + CAP_PROP_XI_SENSOR_TAPS = 437, //!< Number of taps. + CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, //!< Automatic exposure/gain ROI offset X. + CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, //!< Automatic exposure/gain ROI offset Y. + CAP_PROP_XI_AEAG_ROI_WIDTH = 441, //!< Automatic exposure/gain ROI Width. + CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, //!< Automatic exposure/gain ROI Height. + CAP_PROP_XI_BPC = 445, //!< Correction of bad pixels. + CAP_PROP_XI_WB_KR = 448, //!< White balance red coefficient. + CAP_PROP_XI_WB_KG = 449, //!< White balance green coefficient. + CAP_PROP_XI_WB_KB = 450, //!< White balance blue coefficient. + CAP_PROP_XI_WIDTH = 451, //!< Width of the Image provided by the device (in pixels). + CAP_PROP_XI_HEIGHT = 452, //!< Height of the Image provided by the device (in pixels). + CAP_PROP_XI_REGION_SELECTOR = 589, //!< Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode. + CAP_PROP_XI_REGION_MODE = 595, //!< Activates/deactivates Region selected by Region Selector. + CAP_PROP_XI_LIMIT_BANDWIDTH = 459, //!< Set/get bandwidth(datarate)(in Megabits). + CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, //!< Sensor output data bit depth. + CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, //!< Device output data bit depth. + CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, //!< bitdepth of data returned by function xiGetImage. + CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, //!< Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. + CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, //!< Data packing type. Some cameras supports only specific packing type. + CAP_PROP_XI_IS_COOLED = 465, //!< Returns 1 for cameras that support cooling. + CAP_PROP_XI_COOLING = 466, //!< Start camera cooling. + CAP_PROP_XI_TARGET_TEMP = 467, //!< Set sensor target temperature for cooling. + CAP_PROP_XI_CHIP_TEMP = 468, //!< Camera sensor temperature. + CAP_PROP_XI_HOUS_TEMP = 469, //!< Camera housing temperature. + CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, //!< Camera housing back side temperature. + CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, //!< Camera sensor board temperature. + CAP_PROP_XI_CMS = 470, //!< Mode of color management system. + CAP_PROP_XI_APPLY_CMS = 471, //!< Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). + CAP_PROP_XI_IMAGE_IS_COLOR = 474, //!< Returns 1 for color cameras. + CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, //!< Returns color filter array type of RAW data. + CAP_PROP_XI_GAMMAY = 476, //!< Luminosity gamma. + CAP_PROP_XI_GAMMAC = 477, //!< Chromaticity gamma. + CAP_PROP_XI_SHARPNESS = 478, //!< Sharpness Strength. + CAP_PROP_XI_CC_MATRIX_00 = 479, //!< Color Correction Matrix element [0][0]. + CAP_PROP_XI_CC_MATRIX_01 = 480, //!< Color Correction Matrix element [0][1]. + CAP_PROP_XI_CC_MATRIX_02 = 481, //!< Color Correction Matrix element [0][2]. + CAP_PROP_XI_CC_MATRIX_03 = 482, //!< Color Correction Matrix element [0][3]. + CAP_PROP_XI_CC_MATRIX_10 = 483, //!< Color Correction Matrix element [1][0]. + CAP_PROP_XI_CC_MATRIX_11 = 484, //!< Color Correction Matrix element [1][1]. + CAP_PROP_XI_CC_MATRIX_12 = 485, //!< Color Correction Matrix element [1][2]. + CAP_PROP_XI_CC_MATRIX_13 = 486, //!< Color Correction Matrix element [1][3]. + CAP_PROP_XI_CC_MATRIX_20 = 487, //!< Color Correction Matrix element [2][0]. + CAP_PROP_XI_CC_MATRIX_21 = 488, //!< Color Correction Matrix element [2][1]. + CAP_PROP_XI_CC_MATRIX_22 = 489, //!< Color Correction Matrix element [2][2]. + CAP_PROP_XI_CC_MATRIX_23 = 490, //!< Color Correction Matrix element [2][3]. + CAP_PROP_XI_CC_MATRIX_30 = 491, //!< Color Correction Matrix element [3][0]. + CAP_PROP_XI_CC_MATRIX_31 = 492, //!< Color Correction Matrix element [3][1]. + CAP_PROP_XI_CC_MATRIX_32 = 493, //!< Color Correction Matrix element [3][2]. + CAP_PROP_XI_CC_MATRIX_33 = 494, //!< Color Correction Matrix element [3][3]. + CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, //!< Set default Color Correction Matrix. + CAP_PROP_XI_TRG_SELECTOR = 498, //!< Selects the type of trigger. + CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, //!< Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart. + CAP_PROP_XI_DEBOUNCE_EN = 507, //!< Enable/Disable debounce to selected GPI. + CAP_PROP_XI_DEBOUNCE_T0 = 508, //!< Debounce time (x * 10us). + CAP_PROP_XI_DEBOUNCE_T1 = 509, //!< Debounce time (x * 10us). + CAP_PROP_XI_DEBOUNCE_POL = 510, //!< Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge). + CAP_PROP_XI_LENS_MODE = 511, //!< Status of lens control interface. This shall be set to XI_ON before any Lens operations. + CAP_PROP_XI_LENS_APERTURE_VALUE = 512, //!< Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11. + CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, //!< Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. + CAP_PROP_XI_LENS_FOCUS_MOVE = 514, //!< Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. + CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, //!< Lens focus distance in cm. + CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, //!< Lens focal distance in mm. + CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, //!< Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. + CAP_PROP_XI_LENS_FEATURE = 518, //!< Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. + CAP_PROP_XI_DEVICE_MODEL_ID = 521, //!< Returns device model id. + CAP_PROP_XI_DEVICE_SN = 522, //!< Returns device serial number. + CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, //!< The alpha channel of RGB32 output image format. + CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, //!< Buffer size in bytes sufficient for output image returned by xiGetImage. + CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, //!< Current format of pixels on transport layer. + CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, //!< Sensor clock frequency in Hz. + CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, //!< Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. + CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, //!< Number of output channels from sensor used for data transfer. + CAP_PROP_XI_FRAMERATE = 535, //!< Define framerate in Hz. + CAP_PROP_XI_COUNTER_SELECTOR = 536, //!< Select counter. + CAP_PROP_XI_COUNTER_VALUE = 537, //!< Counter status. + CAP_PROP_XI_ACQ_TIMING_MODE = 538, //!< Type of sensor frames timing. + CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, //!< Calculate and returns available interface bandwidth(int Megabits). + CAP_PROP_XI_BUFFER_POLICY = 540, //!< Data move policy. + CAP_PROP_XI_LUT_EN = 541, //!< Activates LUT. + CAP_PROP_XI_LUT_INDEX = 542, //!< Control the index (offset) of the coefficient to access in the LUT. + CAP_PROP_XI_LUT_VALUE = 543, //!< Value at entry LUTIndex of the LUT. + CAP_PROP_XI_TRG_DELAY = 544, //!< Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. + CAP_PROP_XI_TS_RST_MODE = 545, //!< Defines how time stamp reset engine will be armed. + CAP_PROP_XI_TS_RST_SOURCE = 546, //!< Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming). + CAP_PROP_XI_IS_DEVICE_EXIST = 547, //!< Returns 1 if camera connected and works properly. + CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, //!< Acquisition buffer size in buffer_size_unit. Default bytes. + CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, //!< Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes. + CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, //!< Acquisition transport buffer size in bytes. + CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, //!< Queue of field/frame buffers. + CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, //!< Number of buffers to commit to low level. + CAP_PROP_XI_RECENT_FRAME = 553, //!< GetImage returns most recent frame. + CAP_PROP_XI_DEVICE_RESET = 554, //!< Resets the camera to default state. + CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, //!< Correction of column FPN. + CAP_PROP_XI_ROW_FPN_CORRECTION = 591, //!< Correction of row FPN. + CAP_PROP_XI_SENSOR_MODE = 558, //!< Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. + CAP_PROP_XI_HDR = 559, //!< Enable High Dynamic Range feature. + CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, //!< The number of kneepoints in the PWLR. + CAP_PROP_XI_HDR_T1 = 561, //!< Position of first kneepoint(in % of XI_PRM_EXPOSURE). + CAP_PROP_XI_HDR_T2 = 562, //!< Position of second kneepoint (in % of XI_PRM_EXPOSURE). + CAP_PROP_XI_KNEEPOINT1 = 563, //!< Value of first kneepoint (% of sensor saturation). + CAP_PROP_XI_KNEEPOINT2 = 564, //!< Value of second kneepoint (% of sensor saturation). + CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, //!< Last image black level counts. Can be used for Offline processing to recall it. + CAP_PROP_XI_HW_REVISION = 571, //!< Returns hardware revision number. + CAP_PROP_XI_DEBUG_LEVEL = 572, //!< Set debug level. + CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, //!< Automatic bandwidth calculation. + CAP_PROP_XI_FFS_FILE_ID = 594, //!< File number. + CAP_PROP_XI_FFS_FILE_SIZE = 580, //!< Size of file. + CAP_PROP_XI_FREE_FFS_SIZE = 581, //!< Size of free camera FFS. + CAP_PROP_XI_USED_FFS_SIZE = 582, //!< Size of used camera FFS. + CAP_PROP_XI_FFS_ACCESS_KEY = 583, //!< Setting of key enables file operations on some cameras. + CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, //!< Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. + CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, //!< Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. + }; + +//! @} XIMEA + + +/** @name ARAVIS Camera API + @{ +*/ + +//! Properties of cameras available through ARAVIS backend +enum { CAP_PROP_ARAVIS_AUTOTRIGGER = 600 //!< Automatically trigger frame capture if camera is configured with software trigger +}; + +//! @} ARAVIS + + +/** @name Android + @{ +*/ + +//! Properties of cameras available through NDK Camera API backend +enum { CAP_PROP_ANDROID_DEVICE_TORCH = 8001, + }; + +//! @} Android + + +/** @name AVFoundation framework for iOS + @{ +*/ + +//! Properties of cameras available through AVFOUNDATION backend +enum { CAP_PROP_IOS_DEVICE_FOCUS = 9001, + CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, + CAP_PROP_IOS_DEVICE_FLASH = 9003, + CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, + CAP_PROP_IOS_DEVICE_TORCH = 9005 + }; + +//! @} AVFoundation framework for iOS + + +/** @name Smartek Giganetix GigEVisionSDK + @{ +*/ + +//! Properties of cameras available through Smartek Giganetix Ethernet Vision backend +/* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ +enum { CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, + CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, + CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, + CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, + CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, + CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006 + }; + +//! @} Smartek + +/** @name Intel Perceptual Computing SDK + @{ +*/ +enum { CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, + CAP_PROP_INTELPERC_PROFILE_IDX = 11002, + CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, + CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, + CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, + CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, + CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007 + }; + +//! Intel Perceptual Streams +enum { CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, + CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, + CAP_INTELPERC_IR_GENERATOR = 1 << 27, + CAP_INTELPERC_GENERATORS_MASK = CAP_INTELPERC_DEPTH_GENERATOR + CAP_INTELPERC_IMAGE_GENERATOR + CAP_INTELPERC_IR_GENERATOR + }; + +enum { CAP_INTELPERC_DEPTH_MAP = 0, //!< Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. + CAP_INTELPERC_UVDEPTH_MAP = 1, //!< Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. + CAP_INTELPERC_IR_MAP = 2, //!< Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. + CAP_INTELPERC_IMAGE = 3 + }; + +//! @} Intel Perceptual + +/** @name gPhoto2 connection + @{ +*/ + +/** @brief gPhoto2 properties + +If `propertyId` is less than 0 then work on widget with that __additive inversed__ camera setting ID +Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. +@see CvCaptureCAM_GPHOTO2 for more info +*/ +enum { CAP_PROP_GPHOTO2_PREVIEW = 17001, //!< Capture only preview from liveview mode. + CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, //!< Readonly, returns (const char *). + CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, //!< Trigger, only by set. Reload camera settings. + CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, //!< Reload all settings on set. + CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, //!< Collect messages with details. + CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, //!< Readonly, returns (const char *). + CAP_PROP_SPEED = 17007, //!< Exposure speed. Can be readonly, depends on camera program. + CAP_PROP_APERTURE = 17008, //!< Aperture. Can be readonly, depends on camera program. + CAP_PROP_EXPOSUREPROGRAM = 17009, //!< Camera exposure program. + CAP_PROP_VIEWFINDER = 17010 //!< Enter liveview mode. + }; + +//! @} gPhoto2 + + +/** @name Images backend + @{ +*/ + +/** @brief Images backend properties + +*/ +enum { CAP_PROP_IMAGES_BASE = 18000, + CAP_PROP_IMAGES_LAST = 19000 // excluding + }; + +//! @} Images + +/** @name OBSENSOR (for Orbbec 3D-Sensor device/module ) + @{ +*/ +//! OBSENSOR data given from image generator +enum VideoCaptureOBSensorDataType{ + CAP_OBSENSOR_DEPTH_MAP = 0, //!< Depth values in mm (CV_16UC1) + CAP_OBSENSOR_BGR_IMAGE = 1, //!< Data given from BGR stream generator + CAP_OBSENSOR_IR_IMAGE = 2 //!< Data given from IR stream generator(CV_16UC1) +}; + +//! OBSENSOR stream generator +enum VideoCaptureOBSensorGenerators{ + CAP_OBSENSOR_DEPTH_GENERATOR = 1 << 29, + CAP_OBSENSOR_IMAGE_GENERATOR = 1 << 28, + CAP_OBSENSOR_IR_GENERATOR = 1 << 27, + CAP_OBSENSOR_GENERATORS_MASK = CAP_OBSENSOR_DEPTH_GENERATOR + CAP_OBSENSOR_IMAGE_GENERATOR + CAP_OBSENSOR_IR_GENERATOR +}; + +//!OBSENSOR properties +enum VideoCaptureOBSensorProperties{ + // INTRINSIC + CAP_PROP_OBSENSOR_INTRINSIC_FX=26001, + CAP_PROP_OBSENSOR_INTRINSIC_FY=26002, + CAP_PROP_OBSENSOR_INTRINSIC_CX=26003, + CAP_PROP_OBSENSOR_INTRINSIC_CY=26004, +}; + +//! @} OBSENSOR + +//! @} videoio_flags_others + +/** @brief Read data stream interface + */ +class CV_EXPORTS_W IStreamReader +{ +public: + virtual ~IStreamReader(); + + /** @brief Read bytes from stream */ + virtual long long read(char* buffer, long long size) = 0; + + /** @brief Sets the stream position + * + * @param offset Seek offset + * @param origin SEEK_SET / SEEK_END / SEEK_CUR + * + * @see fseek + */ + virtual long long seek(long long offset, int origin) = 0; +}; + +class IVideoCapture; +//! @cond IGNORED +namespace internal { class VideoCapturePrivateAccessor; } +//! @endcond IGNORED + +/** @brief Class for video capturing from video files, image sequences or cameras. + +The class provides C++ API for capturing video from cameras or for reading video files and image sequences. + +Here is how the class can be used: +@include samples/cpp/videocapture_basic.cpp + +@note In @ref videoio_c "C API" the black-box structure `CvCapture` is used instead of %VideoCapture. +@note +- (C++) A basic sample on using the %VideoCapture interface can be found at + `OPENCV_SOURCE_CODE/samples/cpp/videocapture_starter.cpp` +- (Python) A basic sample on using the %VideoCapture interface can be found at + `OPENCV_SOURCE_CODE/samples/python/video.py` +- (Python) A multi threaded video processing sample can be found at + `OPENCV_SOURCE_CODE/samples/python/video_threaded.py` +- (Python) %VideoCapture sample showcasing some features of the Video4Linux2 backend + `OPENCV_SOURCE_CODE/samples/python/video_v4l2.py` + */ +class CV_EXPORTS_W VideoCapture +{ +public: + /** @brief Default constructor + @note In @ref videoio_c "C API", when you finished working with video, release CvCapture structure with + cvReleaseCapture(), or use Ptr\ that calls cvReleaseCapture() automatically in the + destructor. + */ + CV_WRAP VideoCapture(); + + /** @overload + @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference + + @param filename it can be: + - name of video file (eg. `video.avi`) + - or image sequence (eg. `img_%02d.jpg`, which will read samples like `img_00.jpg, img_01.jpg, img_02.jpg, ...`) + - or URL of video stream (eg. `protocol://host:port/script_name?script_params|auth`) + - or GStreamer pipeline string in gst-launch tool format in case if GStreamer is used as backend + Note that each video stream or IP camera feed has its own URL scheme. Please refer to the + documentation of source stream to know the right URL. + @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader + implementation if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_IMAGES or cv::CAP_DSHOW. + + @sa cv::VideoCaptureAPIs + */ + CV_WRAP explicit VideoCapture(const String& filename, int apiPreference = CAP_ANY); + + /** @overload + @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + */ + CV_WRAP explicit VideoCapture(const String& filename, int apiPreference, const std::vector& params); + + /** @overload + @brief Opens a camera for video capturing + + @param index id of the video capturing device to open. To open default camera using default backend just pass 0. + (to backward compatibility usage of camera_id + domain_offset (CAP_*) is valid when apiPreference is CAP_ANY) + @param apiPreference preferred Capture API backends to use. Can be used to enforce a specific reader + implementation if multiple are available: e.g. cv::CAP_DSHOW or cv::CAP_MSMF or cv::CAP_V4L. + + @sa cv::VideoCaptureAPIs + */ + CV_WRAP explicit VideoCapture(int index, int apiPreference = CAP_ANY); + + /** @overload + @brief Opens a camera for video capturing with API Preference and parameters + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + */ + CV_WRAP explicit VideoCapture(int index, int apiPreference, const std::vector& params); + + /** @overload + @brief Opens a video using data stream. + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + */ + CV_WRAP VideoCapture(const Ptr& source, int apiPreference, const std::vector& params); + + /** @brief Default destructor + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + virtual ~VideoCapture(); + + /** @brief Opens a video file or a capturing device or an IP video stream for video capturing. + + @overload + + Parameters are same as the constructor VideoCapture(const String& filename, int apiPreference = CAP_ANY) + @return `true` if the file has been successfully opened + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(const String& filename, int apiPreference = CAP_ANY); + + /** @brief Opens a video file or a capturing device or an IP video stream for video capturing with API Preference and parameters + + @overload + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + + @return `true` if the file has been successfully opened + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(const String& filename, int apiPreference, const std::vector& params); + + /** @brief Opens a camera for video capturing + + @overload + + Parameters are same as the constructor VideoCapture(int index, int apiPreference = CAP_ANY) + @return `true` if the camera has been successfully opened. + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(int index, int apiPreference = CAP_ANY); + + /** @brief Opens a camera for video capturing with API Preference and parameters + + @overload + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + + @return `true` if the camera has been successfully opened. + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(int index, int apiPreference, const std::vector& params); + + /** @brief Opens a video using data stream. + + @overload + + The `params` parameter allows to specify extra parameters encoded as pairs `(paramId_1, paramValue_1, paramId_2, paramValue_2, ...)`. + See cv::VideoCaptureProperties + + @return `true` if the file has been successfully opened + + The method first calls VideoCapture::release to close the already opened file or camera. + */ + CV_WRAP virtual bool open(const Ptr& source, int apiPreference, const std::vector& params); + + /** @brief Returns true if video capturing has been initialized already. + + If the previous call to VideoCapture constructor or VideoCapture::open() succeeded, the method returns + true. + */ + CV_WRAP virtual bool isOpened() const; + + /** @brief Closes video file or capturing device. + + The method is automatically called by subsequent VideoCapture::open and by VideoCapture + destructor. + + The C function also deallocates memory and clears \*capture pointer. + */ + CV_WRAP virtual void release(); + + /** @brief Grabs the next frame from video file or capturing device. + + @return `true` (non-zero) in the case of success. + + The method/function grabs the next frame from video file or camera and returns true (non-zero) in + the case of success. + + The primary use of the function is in multi-camera environments, especially when the cameras do not + have hardware synchronization. That is, you call VideoCapture::grab() for each camera and after that + call the slower method VideoCapture::retrieve() to decode and get frame from each camera. This way + the overhead on demosaicing or motion jpeg decompression etc. is eliminated and the retrieved frames + from different cameras will be closer in time. + + Also, when a connected camera is multi-head (for example, a stereo camera or a Kinect device), the + correct way of retrieving data from it is to call VideoCapture::grab() first and then call + VideoCapture::retrieve() one or more times with different values of the channel parameter. + + @ref tutorial_kinect_openni + */ + CV_WRAP virtual bool grab(); + + /** @brief Decodes and returns the grabbed video frame. + + @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. + @param flag it could be a frame index or a driver specific flag + @return `false` if no frames has been grabbed + + The method decodes and returns the just grabbed frame. If no frames has been grabbed + (camera has been disconnected, or there are no more frames in video file), the method returns false + and the function returns an empty image (with %cv::Mat, test it with Mat::empty()). + + @sa read() + + @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video + capturing structure. It is not allowed to modify or release the image! You can copy the frame using + cvCloneImage and then do whatever you want with the copy. + */ + CV_WRAP virtual bool retrieve(OutputArray image, int flag = 0); + + /** @brief Stream operator to read the next video frame. + @sa read() + */ + virtual VideoCapture& operator >> (CV_OUT Mat& image); + + /** @overload + @sa read() + */ + virtual VideoCapture& operator >> (CV_OUT UMat& image); + + /** @brief Grabs, decodes and returns the next video frame. + + @param [out] image the video frame is returned here. If no frames has been grabbed the image will be empty. + @return `false` if no frames has been grabbed + + The method/function combines VideoCapture::grab() and VideoCapture::retrieve() in one call. This is the + most convenient method for reading video files or capturing data from decode and returns the just + grabbed frame. If no frames has been grabbed (camera has been disconnected, or there are no more + frames in video file), the method returns false and the function returns empty image (with %cv::Mat, test it with Mat::empty()). + + @note In @ref videoio_c "C API", functions cvRetrieveFrame() and cv.RetrieveFrame() return image stored inside the video + capturing structure. It is not allowed to modify or release the image! You can copy the frame using + cvCloneImage and then do whatever you want with the copy. + */ + CV_WRAP virtual bool read(OutputArray image); + + /** @brief Sets a property in the VideoCapture. + + @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) + or one from @ref videoio_flags_others + @param value Value of the property. + @return `true` if the property is supported by backend used by the VideoCapture instance. + @note Even if it returns `true` this doesn't ensure that the property + value has been accepted by the capture device. See note in VideoCapture::get() + */ + CV_WRAP virtual bool set(int propId, double value); + + /** @brief Returns the specified VideoCapture property + + @param propId Property identifier from cv::VideoCaptureProperties (eg. cv::CAP_PROP_POS_MSEC, cv::CAP_PROP_POS_FRAMES, ...) + or one from @ref videoio_flags_others + @return Value for the specified property. Value 0 is returned when querying a property that is + not supported by the backend used by the VideoCapture instance. + + @note Reading / writing properties involves many layers. Some unexpected result might happens + along this chain. + @code{.txt} + VideoCapture -> API Backend -> Operating System -> Device Driver -> Device Hardware + @endcode + The returned value might be different from what really used by the device or it could be encoded + using device dependent rules (eg. steps or percentage). Effective behaviour depends from device + driver and API Backend + + */ + CV_WRAP virtual double get(int propId) const; + + /** @brief Returns used backend API name + + @note Stream should be opened. + */ + CV_WRAP String getBackendName() const; + + /** Switches exceptions mode + * + * methods raise exceptions if not successful instead of returning an error code + */ + CV_WRAP void setExceptionMode(bool enable) { throwOnFail = enable; } + + /// query if exception mode is active + CV_WRAP bool getExceptionMode() const { return throwOnFail; } + + + /** @brief Wait for ready frames from VideoCapture. + + @param streams input video streams + @param readyIndex stream indexes with grabbed frames (ready to use .retrieve() to fetch actual frame) + @param timeoutNs number of nanoseconds (0 - infinite) + @return `true` if streamReady is not empty + + @throws Exception %Exception on stream errors (check .isOpened() to filter out malformed streams) or VideoCapture type is not supported + + The primary use of the function is in multi-camera environments. + The method fills the ready state vector, grabs video frame, if camera is ready. + + After this call use VideoCapture::retrieve() to decode and fetch frame data. + */ + CV_WRAP static + bool waitAny( + const std::vector& streams, + CV_OUT std::vector& readyIndex, + int64 timeoutNs = 0); + +protected: + Ptr cap; + Ptr icap; + bool throwOnFail; + + friend class internal::VideoCapturePrivateAccessor; +}; + +class IVideoWriter; + +/** @example samples/cpp/tutorial_code/videoio/video-write/video-write.cpp +Check @ref tutorial_video_write "the corresponding tutorial" for more details +*/ + +/** @example samples/cpp/videowriter_basic.cpp +An example using VideoCapture and VideoWriter class +*/ + +/** @brief Video writer class. + +The class provides C++ API for writing video files or image sequences. +*/ +class CV_EXPORTS_W VideoWriter +{ +public: + /** @brief Default constructors + + The constructors/functions initialize video writers. + - On Linux FFMPEG is used to write videos; + - On Windows FFMPEG or MSWF or DSHOW is used; + - On MacOSX AVFoundation is used. + */ + CV_WRAP VideoWriter(); + + /** @overload + @param filename Name of the output video file. + @param fourcc 4-character code of codec used to compress the frames. For example, + VideoWriter::fourcc('P','I','M','1') is a MPEG-1 codec, VideoWriter::fourcc('M','J','P','G') + is a motion-jpeg codec etc. List of codes can be obtained at + [MSDN](https://docs.microsoft.com/en-us/windows/win32/medfound/video-fourccs) page + or with this [page](https://fourcc.org/codecs.php) + of the fourcc site for a more complete list). FFMPEG backend with MP4 container natively uses + other values as fourcc code: see [ObjectType](http://mp4ra.org/#/codecs), + so you may receive a warning message from OpenCV about fourcc code conversion. + @param fps Framerate of the created video stream. + @param frameSize Size of the video frames. + @param isColor If it is not zero, the encoder will expect and encode color frames, otherwise it + will work with grayscale frames. + + @b Tips: + - With some backends `fourcc=-1` pops up the codec selection dialog from the system. + - To save image sequence use a proper filename (eg. `img_%02d.jpg`) and `fourcc=0` + OR `fps=0`. Use uncompressed image format (eg. `img_%02d.BMP`) to save raw frames. + - Most codecs are lossy. If you want lossless video file you need to use a lossless codecs + (eg. FFMPEG FFV1, Huffman HFYU, Lagarith LAGS, etc...) + - If FFMPEG is enabled, using `codec=0; fps=0;` you can create an uncompressed (raw) video file. + - If FFMPEG is used, we allow frames of odd width or height, but in this case we truncate + the rightmost column/the bottom row. Probably, this should be handled more elegantly, + but some internal functions inside FFMPEG swscale require even width/height. + */ + CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + The `apiPreference` parameter allows to specify API backends to use. Can be used to enforce a specific reader implementation + if multiple are available: e.g. cv::CAP_FFMPEG or cv::CAP_GSTREAMER. + */ + CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + * The `params` parameter allows to specify extra encoder parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) + * see cv::VideoWriterProperties + */ + CV_WRAP VideoWriter(const String& filename, int fourcc, double fps, const Size& frameSize, + const std::vector& params); + + /** @overload + */ + CV_WRAP VideoWriter(const String& filename, int apiPreference, int fourcc, double fps, + const Size& frameSize, const std::vector& params); + + /** @brief Default destructor + + The method first calls VideoWriter::release to close the already opened file. + */ + virtual ~VideoWriter(); + + /** @brief Initializes or reinitializes video writer. + + The method opens video writer. Parameters are the same as in the constructor + VideoWriter::VideoWriter. + @return `true` if video writer has been successfully initialized + + The method first calls VideoWriter::release to close the already opened file. + */ + CV_WRAP virtual bool open(const String& filename, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + */ + CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, + Size frameSize, bool isColor = true); + + /** @overload + */ + CV_WRAP bool open(const String& filename, int fourcc, double fps, const Size& frameSize, + const std::vector& params); + + /** @overload + */ + CV_WRAP bool open(const String& filename, int apiPreference, int fourcc, double fps, + const Size& frameSize, const std::vector& params); + + /** @brief Returns true if video writer has been successfully initialized. + */ + CV_WRAP virtual bool isOpened() const; + + /** @brief Closes the video writer. + + The method is automatically called by subsequent VideoWriter::open and by the VideoWriter + destructor. + */ + CV_WRAP virtual void release(); + + /** @brief Stream operator to write the next video frame. + @sa write + */ + virtual VideoWriter& operator << (const Mat& image); + + /** @overload + @sa write + */ + virtual VideoWriter& operator << (const UMat& image); + + /** @brief Writes the next video frame + + @param image The written frame. In general, color images are expected in BGR format. + + The function/method writes the specified image to video file. It must have the same size as has + been specified when opening the video writer. + */ + CV_WRAP virtual void write(InputArray image); + + /** @brief Sets a property in the VideoWriter. + + @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) + or one of @ref videoio_flags_others + + @param value Value of the property. + @return `true` if the property is supported by the backend used by the VideoWriter instance. + */ + CV_WRAP virtual bool set(int propId, double value); + + /** @brief Returns the specified VideoWriter property + + @param propId Property identifier from cv::VideoWriterProperties (eg. cv::VIDEOWRITER_PROP_QUALITY) + or one of @ref videoio_flags_others + + @return Value for the specified property. Value 0 is returned when querying a property that is + not supported by the backend used by the VideoWriter instance. + */ + CV_WRAP virtual double get(int propId) const; + + /** @brief Concatenates 4 chars to a fourcc code + + @return a fourcc code + + This static method constructs the fourcc code of the codec to be used in the constructor + VideoWriter::VideoWriter or VideoWriter::open. + */ + CV_WRAP static int fourcc(char c1, char c2, char c3, char c4); + + /** @brief Returns used backend API name + + @note Stream should be opened. + */ + CV_WRAP String getBackendName() const; + +protected: + Ptr writer; + Ptr iwriter; + + static Ptr create(const String& filename, int fourcc, double fps, + Size frameSize, bool isColor = true); +}; + +//! @cond IGNORED +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvCapture* obj) const; }; +template<> struct DefaultDeleter{ CV_EXPORTS void operator ()(CvVideoWriter* obj) const; }; +//! @endcond IGNORED + +//! @} videoio + +} // cv + +#endif //OPENCV_VIDEOIO_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h b/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h index 191cfed7d9..6bdcc2690b 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/legacy/constants_c.h @@ -1,420 +1,420 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEOIO_LEGACY_CONSTANTS_H -#define OPENCV_VIDEOIO_LEGACY_CONSTANTS_H - -#include "opencv2/core/cvdef.h" - -enum -{ - CV_CAP_ANY =0, // autodetect - - CV_CAP_MIL =100, // MIL proprietary drivers - - CV_CAP_VFW =200, // platform native - CV_CAP_V4L =200, - CV_CAP_V4L2 =200, - - CV_CAP_FIREWARE =300, // IEEE 1394 drivers - CV_CAP_FIREWIRE =300, - CV_CAP_IEEE1394 =300, - CV_CAP_DC1394 =300, - CV_CAP_CMU1394 =300, - - CV_CAP_STEREO =400, // TYZX proprietary drivers - CV_CAP_TYZX =400, - CV_TYZX_LEFT =400, - CV_TYZX_RIGHT =401, - CV_TYZX_COLOR =402, - CV_TYZX_Z =403, - - CV_CAP_QT =500, // QuickTime - - CV_CAP_UNICAP =600, // Unicap drivers - - CV_CAP_DSHOW =700, // DirectShow (via videoInput) - CV_CAP_MSMF =1400, // Microsoft Media Foundation (via videoInput) - - CV_CAP_PVAPI =800, // PvAPI, Prosilica GigE SDK - - CV_CAP_OPENNI =900, // OpenNI (for Kinect) - CV_CAP_OPENNI_ASUS =910, // OpenNI (for Asus Xtion) - - CV_CAP_ANDROID =1000, // Android - not used - CV_CAP_ANDROID_BACK =CV_CAP_ANDROID+99, // Android back camera - not used - CV_CAP_ANDROID_FRONT =CV_CAP_ANDROID+98, // Android front camera - not used - - CV_CAP_XIAPI =1100, // XIMEA Camera API - - CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) - - CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK - - CV_CAP_INTELPERC = 1500, // Intel Perceptual Computing - - CV_CAP_OPENNI2 = 1600, // OpenNI2 (for Kinect) - CV_CAP_GPHOTO2 = 1700, - CV_CAP_GSTREAMER = 1800, // GStreamer - CV_CAP_FFMPEG = 1900, // FFMPEG - CV_CAP_IMAGES = 2000, // OpenCV Image Sequence (e.g. img_%02d.jpg) - - CV_CAP_ARAVIS = 2100 // Aravis GigE SDK -}; - -enum -{ - // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) - // every feature can have only one mode turned on at a time - CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) - CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user - CV_CAP_PROP_DC1394_MODE_AUTO = -2, - CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, - CV_CAP_PROP_POS_MSEC =0, - CV_CAP_PROP_POS_FRAMES =1, - CV_CAP_PROP_POS_AVI_RATIO =2, - CV_CAP_PROP_FRAME_WIDTH =3, - CV_CAP_PROP_FRAME_HEIGHT =4, - CV_CAP_PROP_FPS =5, - CV_CAP_PROP_FOURCC =6, - CV_CAP_PROP_FRAME_COUNT =7, - CV_CAP_PROP_FORMAT =8, - CV_CAP_PROP_MODE =9, - CV_CAP_PROP_BRIGHTNESS =10, - CV_CAP_PROP_CONTRAST =11, - CV_CAP_PROP_SATURATION =12, - CV_CAP_PROP_HUE =13, - CV_CAP_PROP_GAIN =14, - CV_CAP_PROP_EXPOSURE =15, - CV_CAP_PROP_CONVERT_RGB =16, - CV_CAP_PROP_WHITE_BALANCE_BLUE_U =17, - CV_CAP_PROP_RECTIFICATION =18, - CV_CAP_PROP_MONOCHROME =19, - CV_CAP_PROP_SHARPNESS =20, - CV_CAP_PROP_AUTO_EXPOSURE =21, // exposure control done by camera, - // user can adjust reference level - // using this feature - CV_CAP_PROP_GAMMA =22, - CV_CAP_PROP_TEMPERATURE =23, - CV_CAP_PROP_TRIGGER =24, - CV_CAP_PROP_TRIGGER_DELAY =25, - CV_CAP_PROP_WHITE_BALANCE_RED_V =26, - CV_CAP_PROP_ZOOM =27, - CV_CAP_PROP_FOCUS =28, - CV_CAP_PROP_GUID =29, - CV_CAP_PROP_ISO_SPEED =30, - CV_CAP_PROP_MAX_DC1394 =31, - CV_CAP_PROP_BACKLIGHT =32, - CV_CAP_PROP_PAN =33, - CV_CAP_PROP_TILT =34, - CV_CAP_PROP_ROLL =35, - CV_CAP_PROP_IRIS =36, - CV_CAP_PROP_SETTINGS =37, - CV_CAP_PROP_BUFFERSIZE =38, - CV_CAP_PROP_AUTOFOCUS =39, - CV_CAP_PROP_SAR_NUM =40, - CV_CAP_PROP_SAR_DEN =41, - - CV_CAP_PROP_AUTOGRAB =1024, // property for videoio class CvCapture_Android only - CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING=1025, // readonly, tricky property, returns cpnst char* indeed - CV_CAP_PROP_PREVIEW_FORMAT=1026, // readonly, tricky property, returns cpnst char* indeed - - // OpenNI map generators - CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, - CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, - CV_CAP_OPENNI_IR_GENERATOR = 1 << 29, - CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_OPENNI_IR_GENERATOR, - - // Properties of cameras available through OpenNI interfaces - CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, - CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm - CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm - CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels - CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag - CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map - // by changing depth generator's view point (if the flag is "on") or - // sets this view point to its normal one (if the flag is "off"). - CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, - CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, - CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, - CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, - - CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, - CV_CAP_PROP_OPENNI2_SYNC = 110, - CV_CAP_PROP_OPENNI2_MIRROR = 111, - - CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, - CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, - CV_CAP_OPENNI_DEPTH_GENERATOR_PRESENT = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, - CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, - CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, - CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, - CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, - CV_CAP_OPENNI_IR_GENERATOR_PRESENT = CV_CAP_OPENNI_IR_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, - - // Properties of cameras available through GStreamer interface - CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 - - // PVAPI - CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast - CV_CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, // FrameStartTriggerMode: Determines how a frame is initiated - CV_CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, // Horizontal sub-sampling of the image - CV_CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, // Vertical sub-sampling of the image - CV_CAP_PROP_PVAPI_BINNINGX = 304, // Horizontal binning factor - CV_CAP_PROP_PVAPI_BINNINGY = 305, // Vertical binning factor - CV_CAP_PROP_PVAPI_PIXELFORMAT = 306, // Pixel format - - // Properties of cameras available through XIMEA SDK interface - CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. - CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. - CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). - CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). - CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. - CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. - CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input - CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode - CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level - CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output - CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode - CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED - CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality - CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) - CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance - CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain - CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). - CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure - CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure - CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) - CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds - CV_CAP_PROP_XI_EXPOSURE = 421, // Exposure time in microseconds - CV_CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, // Sets the number of times of exposure in one frame. - CV_CAP_PROP_XI_GAIN_SELECTOR = 423, // Gain selector for parameter Gain allows to select different type of gains. - CV_CAP_PROP_XI_GAIN = 424, // Gain in dB - CV_CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, // Change image downsampling type. - CV_CAP_PROP_XI_BINNING_SELECTOR = 427, // Binning engine selector. - CV_CAP_PROP_XI_BINNING_VERTICAL = 428, // Vertical Binning - number of vertical photo-sensitive cells to combine together. - CV_CAP_PROP_XI_BINNING_HORIZONTAL = 429, // Horizontal Binning - number of horizontal photo-sensitive cells to combine together. - CV_CAP_PROP_XI_BINNING_PATTERN = 430, // Binning pattern type. - CV_CAP_PROP_XI_DECIMATION_SELECTOR = 431, // Decimation engine selector. - CV_CAP_PROP_XI_DECIMATION_VERTICAL = 432, // Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. - CV_CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, // Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. - CV_CAP_PROP_XI_DECIMATION_PATTERN = 434, // Decimation pattern type. - CV_CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, // Selects which test pattern generator is controlled by the TestPattern feature. - CV_CAP_PROP_XI_TEST_PATTERN = 588, // Selects which test pattern type is generated by the selected generator. - CV_CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, // Output data format. - CV_CAP_PROP_XI_SHUTTER_TYPE = 436, // Change sensor shutter type(CMOS sensor). - CV_CAP_PROP_XI_SENSOR_TAPS = 437, // Number of taps - CV_CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, // Automatic exposure/gain ROI offset X - CV_CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, // Automatic exposure/gain ROI offset Y - CV_CAP_PROP_XI_AEAG_ROI_WIDTH = 441, // Automatic exposure/gain ROI Width - CV_CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, // Automatic exposure/gain ROI Height - CV_CAP_PROP_XI_BPC = 445, // Correction of bad pixels - CV_CAP_PROP_XI_WB_KR = 448, // White balance red coefficient - CV_CAP_PROP_XI_WB_KG = 449, // White balance green coefficient - CV_CAP_PROP_XI_WB_KB = 450, // White balance blue coefficient - CV_CAP_PROP_XI_WIDTH = 451, // Width of the Image provided by the device (in pixels). - CV_CAP_PROP_XI_HEIGHT = 452, // Height of the Image provided by the device (in pixels). - CV_CAP_PROP_XI_REGION_SELECTOR = 589, // Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode - CV_CAP_PROP_XI_REGION_MODE = 595, // Activates/deactivates Region selected by Region Selector - CV_CAP_PROP_XI_LIMIT_BANDWIDTH = 459, // Set/get bandwidth(datarate)(in Megabits) - CV_CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, // Sensor output data bit depth. - CV_CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, // Device output data bit depth. - CV_CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, // bitdepth of data returned by function xiGetImage - CV_CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, // Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. - CV_CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, // Data packing type. Some cameras supports only specific packing type. - CV_CAP_PROP_XI_IS_COOLED = 465, // Returns 1 for cameras that support cooling. - CV_CAP_PROP_XI_COOLING = 466, // Start camera cooling. - CV_CAP_PROP_XI_TARGET_TEMP = 467, // Set sensor target temperature for cooling. - CV_CAP_PROP_XI_CHIP_TEMP = 468, // Camera sensor temperature - CV_CAP_PROP_XI_HOUS_TEMP = 469, // Camera housing temperature - CV_CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, // Camera housing back side temperature - CV_CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, // Camera sensor board temperature - CV_CAP_PROP_XI_CMS = 470, // Mode of color management system. - CV_CAP_PROP_XI_APPLY_CMS = 471, // Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). - CV_CAP_PROP_XI_IMAGE_IS_COLOR = 474, // Returns 1 for color cameras. - CV_CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, // Returns color filter array type of RAW data. - CV_CAP_PROP_XI_GAMMAY = 476, // Luminosity gamma - CV_CAP_PROP_XI_GAMMAC = 477, // Chromaticity gamma - CV_CAP_PROP_XI_SHARPNESS = 478, // Sharpness Strength - CV_CAP_PROP_XI_CC_MATRIX_00 = 479, // Color Correction Matrix element [0][0] - CV_CAP_PROP_XI_CC_MATRIX_01 = 480, // Color Correction Matrix element [0][1] - CV_CAP_PROP_XI_CC_MATRIX_02 = 481, // Color Correction Matrix element [0][2] - CV_CAP_PROP_XI_CC_MATRIX_03 = 482, // Color Correction Matrix element [0][3] - CV_CAP_PROP_XI_CC_MATRIX_10 = 483, // Color Correction Matrix element [1][0] - CV_CAP_PROP_XI_CC_MATRIX_11 = 484, // Color Correction Matrix element [1][1] - CV_CAP_PROP_XI_CC_MATRIX_12 = 485, // Color Correction Matrix element [1][2] - CV_CAP_PROP_XI_CC_MATRIX_13 = 486, // Color Correction Matrix element [1][3] - CV_CAP_PROP_XI_CC_MATRIX_20 = 487, // Color Correction Matrix element [2][0] - CV_CAP_PROP_XI_CC_MATRIX_21 = 488, // Color Correction Matrix element [2][1] - CV_CAP_PROP_XI_CC_MATRIX_22 = 489, // Color Correction Matrix element [2][2] - CV_CAP_PROP_XI_CC_MATRIX_23 = 490, // Color Correction Matrix element [2][3] - CV_CAP_PROP_XI_CC_MATRIX_30 = 491, // Color Correction Matrix element [3][0] - CV_CAP_PROP_XI_CC_MATRIX_31 = 492, // Color Correction Matrix element [3][1] - CV_CAP_PROP_XI_CC_MATRIX_32 = 493, // Color Correction Matrix element [3][2] - CV_CAP_PROP_XI_CC_MATRIX_33 = 494, // Color Correction Matrix element [3][3] - CV_CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, // Set default Color Correction Matrix - CV_CAP_PROP_XI_TRG_SELECTOR = 498, // Selects the type of trigger. - CV_CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, // Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart - CV_CAP_PROP_XI_DEBOUNCE_EN = 507, // Enable/Disable debounce to selected GPI - CV_CAP_PROP_XI_DEBOUNCE_T0 = 508, // Debounce time (x * 10us) - CV_CAP_PROP_XI_DEBOUNCE_T1 = 509, // Debounce time (x * 10us) - CV_CAP_PROP_XI_DEBOUNCE_POL = 510, // Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge) - CV_CAP_PROP_XI_LENS_MODE = 511, // Status of lens control interface. This shall be set to XI_ON before any Lens operations. - CV_CAP_PROP_XI_LENS_APERTURE_VALUE = 512, // Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11 - CV_CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, // Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. - CV_CAP_PROP_XI_LENS_FOCUS_MOVE = 514, // Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. - CV_CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, // Lens focus distance in cm. - CV_CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, // Lens focal distance in mm. - CV_CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, // Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. - CV_CAP_PROP_XI_LENS_FEATURE = 518, // Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. - CV_CAP_PROP_XI_DEVICE_MODEL_ID = 521, // Return device model id - CV_CAP_PROP_XI_DEVICE_SN = 522, // Return device serial number - CV_CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, // The alpha channel of RGB32 output image format. - CV_CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, // Buffer size in bytes sufficient for output image returned by xiGetImage - CV_CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, // Current format of pixels on transport layer. - CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, // Sensor clock frequency in Hz. - CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, // Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. - CV_CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, // Number of output channels from sensor used for data transfer. - CV_CAP_PROP_XI_FRAMERATE = 535, // Define framerate in Hz - CV_CAP_PROP_XI_COUNTER_SELECTOR = 536, // Select counter - CV_CAP_PROP_XI_COUNTER_VALUE = 537, // Counter status - CV_CAP_PROP_XI_ACQ_TIMING_MODE = 538, // Type of sensor frames timing. - CV_CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, // Calculate and return available interface bandwidth(int Megabits) - CV_CAP_PROP_XI_BUFFER_POLICY = 540, // Data move policy - CV_CAP_PROP_XI_LUT_EN = 541, // Activates LUT. - CV_CAP_PROP_XI_LUT_INDEX = 542, // Control the index (offset) of the coefficient to access in the LUT. - CV_CAP_PROP_XI_LUT_VALUE = 543, // Value at entry LUTIndex of the LUT - CV_CAP_PROP_XI_TRG_DELAY = 544, // Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. - CV_CAP_PROP_XI_TS_RST_MODE = 545, // Defines how time stamp reset engine will be armed - CV_CAP_PROP_XI_TS_RST_SOURCE = 546, // Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming) - CV_CAP_PROP_XI_IS_DEVICE_EXIST = 547, // Returns 1 if camera connected and works properly. - CV_CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, // Acquisition buffer size in buffer_size_unit. Default bytes. - CV_CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, // Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes - CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, // Acquisition transport buffer size in bytes - CV_CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, // Queue of field/frame buffers - CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, // Number of buffers to commit to low level - CV_CAP_PROP_XI_RECENT_FRAME = 553, // GetImage returns most recent frame - CV_CAP_PROP_XI_DEVICE_RESET = 554, // Resets the camera to default state. - CV_CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, // Correction of column FPN - CV_CAP_PROP_XI_ROW_FPN_CORRECTION = 591, // Correction of row FPN - CV_CAP_PROP_XI_SENSOR_MODE = 558, // Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. - CV_CAP_PROP_XI_HDR = 559, // Enable High Dynamic Range feature. - CV_CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, // The number of kneepoints in the PWLR. - CV_CAP_PROP_XI_HDR_T1 = 561, // position of first kneepoint(in % of XI_PRM_EXPOSURE) - CV_CAP_PROP_XI_HDR_T2 = 562, // position of second kneepoint (in % of XI_PRM_EXPOSURE) - CV_CAP_PROP_XI_KNEEPOINT1 = 563, // value of first kneepoint (% of sensor saturation) - CV_CAP_PROP_XI_KNEEPOINT2 = 564, // value of second kneepoint (% of sensor saturation) - CV_CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, // Last image black level counts. Can be used for Offline processing to recall it. - CV_CAP_PROP_XI_HW_REVISION = 571, // Returns hardware revision number. - CV_CAP_PROP_XI_DEBUG_LEVEL = 572, // Set debug level - CV_CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, // Automatic bandwidth calculation, - CV_CAP_PROP_XI_FFS_FILE_ID = 594, // File number. - CV_CAP_PROP_XI_FFS_FILE_SIZE = 580, // Size of file. - CV_CAP_PROP_XI_FREE_FFS_SIZE = 581, // Size of free camera FFS. - CV_CAP_PROP_XI_USED_FFS_SIZE = 582, // Size of used camera FFS. - CV_CAP_PROP_XI_FFS_ACCESS_KEY = 583, // Setting of key enables file operations on some cameras. - CV_CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, // Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. - CV_CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, // Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. - - - // Properties for Android cameras - CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, - CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, - CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, - CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, - CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, - CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, - CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, - CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, - CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009, - CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010, - - // Properties of cameras available through AVFOUNDATION interface - CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, - CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, - CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, - CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, - CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, - - // Properties of cameras available through Smartek Giganetix Ethernet Vision interface - /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ - CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, - CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, - CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, - CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, - CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, - CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, - - CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, - CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, - CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, - CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, - CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, - CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, - CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, - - // Intel PerC streams - CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, - CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, - CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR -}; - -enum -{ - // Data given from depth generator. - CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) - CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) - CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) - CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) - CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 - - // Data given from RGB image generator. - CV_CAP_OPENNI_BGR_IMAGE = 5, - CV_CAP_OPENNI_GRAY_IMAGE = 6, - - // Data given from IR image generator. - CV_CAP_OPENNI_IR_IMAGE = 7 -}; - -// Supported output modes of OpenNI image generator -enum -{ - CV_CAP_OPENNI_VGA_30HZ = 0, - CV_CAP_OPENNI_SXGA_15HZ = 1, - CV_CAP_OPENNI_SXGA_30HZ = 2, - CV_CAP_OPENNI_QVGA_30HZ = 3, - CV_CAP_OPENNI_QVGA_60HZ = 4 -}; - -enum -{ - CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. - CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. - CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. - CV_CAP_INTELPERC_IMAGE = 3 -}; - -// gPhoto2 properties, if propertyId is less than 0 then work on widget with that __additive inversed__ camera setting ID -// Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. -// @see CvCaptureCAM_GPHOTO2 for more info -enum -{ - CV_CAP_PROP_GPHOTO2_PREVIEW = 17001, // Capture only preview from liveview mode. - CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, // Readonly, returns (const char *). - CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, // Trigger, only by set. Reload camera settings. - CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, // Reload all settings on set. - CV_CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, // Collect messages with details. - CV_CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, // Readonly, returns (const char *). - CV_CAP_PROP_SPEED = 17007, // Exposure speed. Can be readonly, depends on camera program. - CV_CAP_PROP_APERTURE = 17008, // Aperture. Can be readonly, depends on camera program. - CV_CAP_PROP_EXPOSUREPROGRAM = 17009, // Camera exposure program. - CV_CAP_PROP_VIEWFINDER = 17010 // Enter liveview mode. -}; - -//! (Windows only) Open Codec Selection Dialog -#define CV_FOURCC_PROMPT -1 -//! (Linux only) Use default codec for specified filename -#define CV_FOURCC_DEFAULT CV_FOURCC('I', 'Y', 'U', 'V') - -#endif // OPENCV_VIDEOIO_LEGACY_CONSTANTS_H +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEOIO_LEGACY_CONSTANTS_H +#define OPENCV_VIDEOIO_LEGACY_CONSTANTS_H + +#include "opencv2/core/cvdef.h" + +enum +{ + CV_CAP_ANY =0, // autodetect + + CV_CAP_MIL =100, // MIL proprietary drivers + + CV_CAP_VFW =200, // platform native + CV_CAP_V4L =200, + CV_CAP_V4L2 =200, + + CV_CAP_FIREWARE =300, // IEEE 1394 drivers + CV_CAP_FIREWIRE =300, + CV_CAP_IEEE1394 =300, + CV_CAP_DC1394 =300, + CV_CAP_CMU1394 =300, + + CV_CAP_STEREO =400, // TYZX proprietary drivers + CV_CAP_TYZX =400, + CV_TYZX_LEFT =400, + CV_TYZX_RIGHT =401, + CV_TYZX_COLOR =402, + CV_TYZX_Z =403, + + CV_CAP_QT =500, // QuickTime + + CV_CAP_UNICAP =600, // Unicap drivers + + CV_CAP_DSHOW =700, // DirectShow (via videoInput) + CV_CAP_MSMF =1400, // Microsoft Media Foundation (via videoInput) + + CV_CAP_PVAPI =800, // PvAPI, Prosilica GigE SDK + + CV_CAP_OPENNI =900, // OpenNI (for Kinect) + CV_CAP_OPENNI_ASUS =910, // OpenNI (for Asus Xtion) + + CV_CAP_ANDROID =1000, // Android - not used + CV_CAP_ANDROID_BACK =CV_CAP_ANDROID+99, // Android back camera - not used + CV_CAP_ANDROID_FRONT =CV_CAP_ANDROID+98, // Android front camera - not used + + CV_CAP_XIAPI =1100, // XIMEA Camera API + + CV_CAP_AVFOUNDATION = 1200, // AVFoundation framework for iOS (OS X Lion will have the same API) + + CV_CAP_GIGANETIX = 1300, // Smartek Giganetix GigEVisionSDK + + CV_CAP_INTELPERC = 1500, // Intel Perceptual Computing + + CV_CAP_OPENNI2 = 1600, // OpenNI2 (for Kinect) + CV_CAP_GPHOTO2 = 1700, + CV_CAP_GSTREAMER = 1800, // GStreamer + CV_CAP_FFMPEG = 1900, // FFMPEG + CV_CAP_IMAGES = 2000, // OpenCV Image Sequence (e.g. img_%02d.jpg) + + CV_CAP_ARAVIS = 2100 // Aravis GigE SDK +}; + +enum +{ + // modes of the controlling registers (can be: auto, manual, auto single push, absolute Latter allowed with any other mode) + // every feature can have only one mode turned on at a time + CV_CAP_PROP_DC1394_OFF = -4, //turn the feature off (not controlled manually nor automatically) + CV_CAP_PROP_DC1394_MODE_MANUAL = -3, //set automatically when a value of the feature is set by the user + CV_CAP_PROP_DC1394_MODE_AUTO = -2, + CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO = -1, + CV_CAP_PROP_POS_MSEC =0, + CV_CAP_PROP_POS_FRAMES =1, + CV_CAP_PROP_POS_AVI_RATIO =2, + CV_CAP_PROP_FRAME_WIDTH =3, + CV_CAP_PROP_FRAME_HEIGHT =4, + CV_CAP_PROP_FPS =5, + CV_CAP_PROP_FOURCC =6, + CV_CAP_PROP_FRAME_COUNT =7, + CV_CAP_PROP_FORMAT =8, + CV_CAP_PROP_MODE =9, + CV_CAP_PROP_BRIGHTNESS =10, + CV_CAP_PROP_CONTRAST =11, + CV_CAP_PROP_SATURATION =12, + CV_CAP_PROP_HUE =13, + CV_CAP_PROP_GAIN =14, + CV_CAP_PROP_EXPOSURE =15, + CV_CAP_PROP_CONVERT_RGB =16, + CV_CAP_PROP_WHITE_BALANCE_BLUE_U =17, + CV_CAP_PROP_RECTIFICATION =18, + CV_CAP_PROP_MONOCHROME =19, + CV_CAP_PROP_SHARPNESS =20, + CV_CAP_PROP_AUTO_EXPOSURE =21, // exposure control done by camera, + // user can adjust reference level + // using this feature + CV_CAP_PROP_GAMMA =22, + CV_CAP_PROP_TEMPERATURE =23, + CV_CAP_PROP_TRIGGER =24, + CV_CAP_PROP_TRIGGER_DELAY =25, + CV_CAP_PROP_WHITE_BALANCE_RED_V =26, + CV_CAP_PROP_ZOOM =27, + CV_CAP_PROP_FOCUS =28, + CV_CAP_PROP_GUID =29, + CV_CAP_PROP_ISO_SPEED =30, + CV_CAP_PROP_MAX_DC1394 =31, + CV_CAP_PROP_BACKLIGHT =32, + CV_CAP_PROP_PAN =33, + CV_CAP_PROP_TILT =34, + CV_CAP_PROP_ROLL =35, + CV_CAP_PROP_IRIS =36, + CV_CAP_PROP_SETTINGS =37, + CV_CAP_PROP_BUFFERSIZE =38, + CV_CAP_PROP_AUTOFOCUS =39, + CV_CAP_PROP_SAR_NUM =40, + CV_CAP_PROP_SAR_DEN =41, + + CV_CAP_PROP_AUTOGRAB =1024, // property for videoio class CvCapture_Android only + CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING=1025, // readonly, tricky property, returns cpnst char* indeed + CV_CAP_PROP_PREVIEW_FORMAT=1026, // readonly, tricky property, returns cpnst char* indeed + + // OpenNI map generators + CV_CAP_OPENNI_DEPTH_GENERATOR = 1 << 31, + CV_CAP_OPENNI_IMAGE_GENERATOR = 1 << 30, + CV_CAP_OPENNI_IR_GENERATOR = 1 << 29, + CV_CAP_OPENNI_GENERATORS_MASK = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_OPENNI_IR_GENERATOR, + + // Properties of cameras available through OpenNI interfaces + CV_CAP_PROP_OPENNI_OUTPUT_MODE = 100, + CV_CAP_PROP_OPENNI_FRAME_MAX_DEPTH = 101, // in mm + CV_CAP_PROP_OPENNI_BASELINE = 102, // in mm + CV_CAP_PROP_OPENNI_FOCAL_LENGTH = 103, // in pixels + CV_CAP_PROP_OPENNI_REGISTRATION = 104, // flag + CV_CAP_PROP_OPENNI_REGISTRATION_ON = CV_CAP_PROP_OPENNI_REGISTRATION, // flag that synchronizes the remapping depth map to image map + // by changing depth generator's view point (if the flag is "on") or + // sets this view point to its normal one (if the flag is "off"). + CV_CAP_PROP_OPENNI_APPROX_FRAME_SYNC = 105, + CV_CAP_PROP_OPENNI_MAX_BUFFER_SIZE = 106, + CV_CAP_PROP_OPENNI_CIRCLE_BUFFER = 107, + CV_CAP_PROP_OPENNI_MAX_TIME_DURATION = 108, + + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT = 109, + CV_CAP_PROP_OPENNI2_SYNC = 110, + CV_CAP_PROP_OPENNI2_MIRROR = 111, + + CV_CAP_OPENNI_IMAGE_GENERATOR_PRESENT = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + CV_CAP_OPENNI_IMAGE_GENERATOR_OUTPUT_MODE = CV_CAP_OPENNI_IMAGE_GENERATOR + CV_CAP_PROP_OPENNI_OUTPUT_MODE, + CV_CAP_OPENNI_DEPTH_GENERATOR_PRESENT = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + CV_CAP_OPENNI_DEPTH_GENERATOR_BASELINE = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_BASELINE, + CV_CAP_OPENNI_DEPTH_GENERATOR_FOCAL_LENGTH = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_FOCAL_LENGTH, + CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION = CV_CAP_OPENNI_DEPTH_GENERATOR + CV_CAP_PROP_OPENNI_REGISTRATION, + CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION_ON = CV_CAP_OPENNI_DEPTH_GENERATOR_REGISTRATION, + CV_CAP_OPENNI_IR_GENERATOR_PRESENT = CV_CAP_OPENNI_IR_GENERATOR + CV_CAP_PROP_OPENNI_GENERATOR_PRESENT, + + // Properties of cameras available through GStreamer interface + CV_CAP_GSTREAMER_QUEUE_LENGTH = 200, // default is 1 + + // PVAPI + CV_CAP_PROP_PVAPI_MULTICASTIP = 300, // ip for anable multicast master mode. 0 for disable multicast + CV_CAP_PROP_PVAPI_FRAMESTARTTRIGGERMODE = 301, // FrameStartTriggerMode: Determines how a frame is initiated + CV_CAP_PROP_PVAPI_DECIMATIONHORIZONTAL = 302, // Horizontal sub-sampling of the image + CV_CAP_PROP_PVAPI_DECIMATIONVERTICAL = 303, // Vertical sub-sampling of the image + CV_CAP_PROP_PVAPI_BINNINGX = 304, // Horizontal binning factor + CV_CAP_PROP_PVAPI_BINNINGY = 305, // Vertical binning factor + CV_CAP_PROP_PVAPI_PIXELFORMAT = 306, // Pixel format + + // Properties of cameras available through XIMEA SDK interface + CV_CAP_PROP_XI_DOWNSAMPLING = 400, // Change image resolution by binning or skipping. + CV_CAP_PROP_XI_DATA_FORMAT = 401, // Output data format. + CV_CAP_PROP_XI_OFFSET_X = 402, // Horizontal offset from the origin to the area of interest (in pixels). + CV_CAP_PROP_XI_OFFSET_Y = 403, // Vertical offset from the origin to the area of interest (in pixels). + CV_CAP_PROP_XI_TRG_SOURCE = 404, // Defines source of trigger. + CV_CAP_PROP_XI_TRG_SOFTWARE = 405, // Generates an internal trigger. PRM_TRG_SOURCE must be set to TRG_SOFTWARE. + CV_CAP_PROP_XI_GPI_SELECTOR = 406, // Selects general purpose input + CV_CAP_PROP_XI_GPI_MODE = 407, // Set general purpose input mode + CV_CAP_PROP_XI_GPI_LEVEL = 408, // Get general purpose level + CV_CAP_PROP_XI_GPO_SELECTOR = 409, // Selects general purpose output + CV_CAP_PROP_XI_GPO_MODE = 410, // Set general purpose output mode + CV_CAP_PROP_XI_LED_SELECTOR = 411, // Selects camera signalling LED + CV_CAP_PROP_XI_LED_MODE = 412, // Define camera signalling LED functionality + CV_CAP_PROP_XI_MANUAL_WB = 413, // Calculates White Balance(must be called during acquisition) + CV_CAP_PROP_XI_AUTO_WB = 414, // Automatic white balance + CV_CAP_PROP_XI_AEAG = 415, // Automatic exposure/gain + CV_CAP_PROP_XI_EXP_PRIORITY = 416, // Exposure priority (0.5 - exposure 50%, gain 50%). + CV_CAP_PROP_XI_AE_MAX_LIMIT = 417, // Maximum limit of exposure in AEAG procedure + CV_CAP_PROP_XI_AG_MAX_LIMIT = 418, // Maximum limit of gain in AEAG procedure + CV_CAP_PROP_XI_AEAG_LEVEL = 419, // Average intensity of output signal AEAG should achieve(in %) + CV_CAP_PROP_XI_TIMEOUT = 420, // Image capture timeout in milliseconds + CV_CAP_PROP_XI_EXPOSURE = 421, // Exposure time in microseconds + CV_CAP_PROP_XI_EXPOSURE_BURST_COUNT = 422, // Sets the number of times of exposure in one frame. + CV_CAP_PROP_XI_GAIN_SELECTOR = 423, // Gain selector for parameter Gain allows to select different type of gains. + CV_CAP_PROP_XI_GAIN = 424, // Gain in dB + CV_CAP_PROP_XI_DOWNSAMPLING_TYPE = 426, // Change image downsampling type. + CV_CAP_PROP_XI_BINNING_SELECTOR = 427, // Binning engine selector. + CV_CAP_PROP_XI_BINNING_VERTICAL = 428, // Vertical Binning - number of vertical photo-sensitive cells to combine together. + CV_CAP_PROP_XI_BINNING_HORIZONTAL = 429, // Horizontal Binning - number of horizontal photo-sensitive cells to combine together. + CV_CAP_PROP_XI_BINNING_PATTERN = 430, // Binning pattern type. + CV_CAP_PROP_XI_DECIMATION_SELECTOR = 431, // Decimation engine selector. + CV_CAP_PROP_XI_DECIMATION_VERTICAL = 432, // Vertical Decimation - vertical sub-sampling of the image - reduces the vertical resolution of the image by the specified vertical decimation factor. + CV_CAP_PROP_XI_DECIMATION_HORIZONTAL = 433, // Horizontal Decimation - horizontal sub-sampling of the image - reduces the horizontal resolution of the image by the specified vertical decimation factor. + CV_CAP_PROP_XI_DECIMATION_PATTERN = 434, // Decimation pattern type. + CV_CAP_PROP_XI_TEST_PATTERN_GENERATOR_SELECTOR = 587, // Selects which test pattern generator is controlled by the TestPattern feature. + CV_CAP_PROP_XI_TEST_PATTERN = 588, // Selects which test pattern type is generated by the selected generator. + CV_CAP_PROP_XI_IMAGE_DATA_FORMAT = 435, // Output data format. + CV_CAP_PROP_XI_SHUTTER_TYPE = 436, // Change sensor shutter type(CMOS sensor). + CV_CAP_PROP_XI_SENSOR_TAPS = 437, // Number of taps + CV_CAP_PROP_XI_AEAG_ROI_OFFSET_X = 439, // Automatic exposure/gain ROI offset X + CV_CAP_PROP_XI_AEAG_ROI_OFFSET_Y = 440, // Automatic exposure/gain ROI offset Y + CV_CAP_PROP_XI_AEAG_ROI_WIDTH = 441, // Automatic exposure/gain ROI Width + CV_CAP_PROP_XI_AEAG_ROI_HEIGHT = 442, // Automatic exposure/gain ROI Height + CV_CAP_PROP_XI_BPC = 445, // Correction of bad pixels + CV_CAP_PROP_XI_WB_KR = 448, // White balance red coefficient + CV_CAP_PROP_XI_WB_KG = 449, // White balance green coefficient + CV_CAP_PROP_XI_WB_KB = 450, // White balance blue coefficient + CV_CAP_PROP_XI_WIDTH = 451, // Width of the Image provided by the device (in pixels). + CV_CAP_PROP_XI_HEIGHT = 452, // Height of the Image provided by the device (in pixels). + CV_CAP_PROP_XI_REGION_SELECTOR = 589, // Selects Region in Multiple ROI which parameters are set by width, height, ... ,region mode + CV_CAP_PROP_XI_REGION_MODE = 595, // Activates/deactivates Region selected by Region Selector + CV_CAP_PROP_XI_LIMIT_BANDWIDTH = 459, // Set/get bandwidth(datarate)(in Megabits) + CV_CAP_PROP_XI_SENSOR_DATA_BIT_DEPTH = 460, // Sensor output data bit depth. + CV_CAP_PROP_XI_OUTPUT_DATA_BIT_DEPTH = 461, // Device output data bit depth. + CV_CAP_PROP_XI_IMAGE_DATA_BIT_DEPTH = 462, // bitdepth of data returned by function xiGetImage + CV_CAP_PROP_XI_OUTPUT_DATA_PACKING = 463, // Device output data packing (or grouping) enabled. Packing could be enabled if output_data_bit_depth > 8 and packing capability is available. + CV_CAP_PROP_XI_OUTPUT_DATA_PACKING_TYPE = 464, // Data packing type. Some cameras supports only specific packing type. + CV_CAP_PROP_XI_IS_COOLED = 465, // Returns 1 for cameras that support cooling. + CV_CAP_PROP_XI_COOLING = 466, // Start camera cooling. + CV_CAP_PROP_XI_TARGET_TEMP = 467, // Set sensor target temperature for cooling. + CV_CAP_PROP_XI_CHIP_TEMP = 468, // Camera sensor temperature + CV_CAP_PROP_XI_HOUS_TEMP = 469, // Camera housing temperature + CV_CAP_PROP_XI_HOUS_BACK_SIDE_TEMP = 590, // Camera housing back side temperature + CV_CAP_PROP_XI_SENSOR_BOARD_TEMP = 596, // Camera sensor board temperature + CV_CAP_PROP_XI_CMS = 470, // Mode of color management system. + CV_CAP_PROP_XI_APPLY_CMS = 471, // Enable applying of CMS profiles to xiGetImage (see XI_PRM_INPUT_CMS_PROFILE, XI_PRM_OUTPUT_CMS_PROFILE). + CV_CAP_PROP_XI_IMAGE_IS_COLOR = 474, // Returns 1 for color cameras. + CV_CAP_PROP_XI_COLOR_FILTER_ARRAY = 475, // Returns color filter array type of RAW data. + CV_CAP_PROP_XI_GAMMAY = 476, // Luminosity gamma + CV_CAP_PROP_XI_GAMMAC = 477, // Chromaticity gamma + CV_CAP_PROP_XI_SHARPNESS = 478, // Sharpness Strength + CV_CAP_PROP_XI_CC_MATRIX_00 = 479, // Color Correction Matrix element [0][0] + CV_CAP_PROP_XI_CC_MATRIX_01 = 480, // Color Correction Matrix element [0][1] + CV_CAP_PROP_XI_CC_MATRIX_02 = 481, // Color Correction Matrix element [0][2] + CV_CAP_PROP_XI_CC_MATRIX_03 = 482, // Color Correction Matrix element [0][3] + CV_CAP_PROP_XI_CC_MATRIX_10 = 483, // Color Correction Matrix element [1][0] + CV_CAP_PROP_XI_CC_MATRIX_11 = 484, // Color Correction Matrix element [1][1] + CV_CAP_PROP_XI_CC_MATRIX_12 = 485, // Color Correction Matrix element [1][2] + CV_CAP_PROP_XI_CC_MATRIX_13 = 486, // Color Correction Matrix element [1][3] + CV_CAP_PROP_XI_CC_MATRIX_20 = 487, // Color Correction Matrix element [2][0] + CV_CAP_PROP_XI_CC_MATRIX_21 = 488, // Color Correction Matrix element [2][1] + CV_CAP_PROP_XI_CC_MATRIX_22 = 489, // Color Correction Matrix element [2][2] + CV_CAP_PROP_XI_CC_MATRIX_23 = 490, // Color Correction Matrix element [2][3] + CV_CAP_PROP_XI_CC_MATRIX_30 = 491, // Color Correction Matrix element [3][0] + CV_CAP_PROP_XI_CC_MATRIX_31 = 492, // Color Correction Matrix element [3][1] + CV_CAP_PROP_XI_CC_MATRIX_32 = 493, // Color Correction Matrix element [3][2] + CV_CAP_PROP_XI_CC_MATRIX_33 = 494, // Color Correction Matrix element [3][3] + CV_CAP_PROP_XI_DEFAULT_CC_MATRIX = 495, // Set default Color Correction Matrix + CV_CAP_PROP_XI_TRG_SELECTOR = 498, // Selects the type of trigger. + CV_CAP_PROP_XI_ACQ_FRAME_BURST_COUNT = 499, // Sets number of frames acquired by burst. This burst is used only if trigger is set to FrameBurstStart + CV_CAP_PROP_XI_DEBOUNCE_EN = 507, // Enable/Disable debounce to selected GPI + CV_CAP_PROP_XI_DEBOUNCE_T0 = 508, // Debounce time (x * 10us) + CV_CAP_PROP_XI_DEBOUNCE_T1 = 509, // Debounce time (x * 10us) + CV_CAP_PROP_XI_DEBOUNCE_POL = 510, // Debounce polarity (pol = 1 t0 - falling edge, t1 - rising edge) + CV_CAP_PROP_XI_LENS_MODE = 511, // Status of lens control interface. This shall be set to XI_ON before any Lens operations. + CV_CAP_PROP_XI_LENS_APERTURE_VALUE = 512, // Current lens aperture value in stops. Examples: 2.8, 4, 5.6, 8, 11 + CV_CAP_PROP_XI_LENS_FOCUS_MOVEMENT_VALUE = 513, // Lens current focus movement value to be used by XI_PRM_LENS_FOCUS_MOVE in motor steps. + CV_CAP_PROP_XI_LENS_FOCUS_MOVE = 514, // Moves lens focus motor by steps set in XI_PRM_LENS_FOCUS_MOVEMENT_VALUE. + CV_CAP_PROP_XI_LENS_FOCUS_DISTANCE = 515, // Lens focus distance in cm. + CV_CAP_PROP_XI_LENS_FOCAL_LENGTH = 516, // Lens focal distance in mm. + CV_CAP_PROP_XI_LENS_FEATURE_SELECTOR = 517, // Selects the current feature which is accessible by XI_PRM_LENS_FEATURE. + CV_CAP_PROP_XI_LENS_FEATURE = 518, // Allows access to lens feature value currently selected by XI_PRM_LENS_FEATURE_SELECTOR. + CV_CAP_PROP_XI_DEVICE_MODEL_ID = 521, // Return device model id + CV_CAP_PROP_XI_DEVICE_SN = 522, // Return device serial number + CV_CAP_PROP_XI_IMAGE_DATA_FORMAT_RGB32_ALPHA = 529, // The alpha channel of RGB32 output image format. + CV_CAP_PROP_XI_IMAGE_PAYLOAD_SIZE = 530, // Buffer size in bytes sufficient for output image returned by xiGetImage + CV_CAP_PROP_XI_TRANSPORT_PIXEL_FORMAT = 531, // Current format of pixels on transport layer. + CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_HZ = 532, // Sensor clock frequency in Hz. + CV_CAP_PROP_XI_SENSOR_CLOCK_FREQ_INDEX = 533, // Sensor clock frequency index. Sensor with selected frequencies have possibility to set the frequency only by this index. + CV_CAP_PROP_XI_SENSOR_OUTPUT_CHANNEL_COUNT = 534, // Number of output channels from sensor used for data transfer. + CV_CAP_PROP_XI_FRAMERATE = 535, // Define framerate in Hz + CV_CAP_PROP_XI_COUNTER_SELECTOR = 536, // Select counter + CV_CAP_PROP_XI_COUNTER_VALUE = 537, // Counter status + CV_CAP_PROP_XI_ACQ_TIMING_MODE = 538, // Type of sensor frames timing. + CV_CAP_PROP_XI_AVAILABLE_BANDWIDTH = 539, // Calculate and return available interface bandwidth(int Megabits) + CV_CAP_PROP_XI_BUFFER_POLICY = 540, // Data move policy + CV_CAP_PROP_XI_LUT_EN = 541, // Activates LUT. + CV_CAP_PROP_XI_LUT_INDEX = 542, // Control the index (offset) of the coefficient to access in the LUT. + CV_CAP_PROP_XI_LUT_VALUE = 543, // Value at entry LUTIndex of the LUT + CV_CAP_PROP_XI_TRG_DELAY = 544, // Specifies the delay in microseconds (us) to apply after the trigger reception before activating it. + CV_CAP_PROP_XI_TS_RST_MODE = 545, // Defines how time stamp reset engine will be armed + CV_CAP_PROP_XI_TS_RST_SOURCE = 546, // Defines which source will be used for timestamp reset. Writing this parameter will trigger settings of engine (arming) + CV_CAP_PROP_XI_IS_DEVICE_EXIST = 547, // Returns 1 if camera connected and works properly. + CV_CAP_PROP_XI_ACQ_BUFFER_SIZE = 548, // Acquisition buffer size in buffer_size_unit. Default bytes. + CV_CAP_PROP_XI_ACQ_BUFFER_SIZE_UNIT = 549, // Acquisition buffer size unit in bytes. Default 1. E.g. Value 1024 means that buffer_size is in KiBytes + CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_SIZE = 550, // Acquisition transport buffer size in bytes + CV_CAP_PROP_XI_BUFFERS_QUEUE_SIZE = 551, // Queue of field/frame buffers + CV_CAP_PROP_XI_ACQ_TRANSPORT_BUFFER_COMMIT = 552, // Number of buffers to commit to low level + CV_CAP_PROP_XI_RECENT_FRAME = 553, // GetImage returns most recent frame + CV_CAP_PROP_XI_DEVICE_RESET = 554, // Resets the camera to default state. + CV_CAP_PROP_XI_COLUMN_FPN_CORRECTION = 555, // Correction of column FPN + CV_CAP_PROP_XI_ROW_FPN_CORRECTION = 591, // Correction of row FPN + CV_CAP_PROP_XI_SENSOR_MODE = 558, // Current sensor mode. Allows to select sensor mode by one integer. Setting of this parameter affects: image dimensions and downsampling. + CV_CAP_PROP_XI_HDR = 559, // Enable High Dynamic Range feature. + CV_CAP_PROP_XI_HDR_KNEEPOINT_COUNT = 560, // The number of kneepoints in the PWLR. + CV_CAP_PROP_XI_HDR_T1 = 561, // position of first kneepoint(in % of XI_PRM_EXPOSURE) + CV_CAP_PROP_XI_HDR_T2 = 562, // position of second kneepoint (in % of XI_PRM_EXPOSURE) + CV_CAP_PROP_XI_KNEEPOINT1 = 563, // value of first kneepoint (% of sensor saturation) + CV_CAP_PROP_XI_KNEEPOINT2 = 564, // value of second kneepoint (% of sensor saturation) + CV_CAP_PROP_XI_IMAGE_BLACK_LEVEL = 565, // Last image black level counts. Can be used for Offline processing to recall it. + CV_CAP_PROP_XI_HW_REVISION = 571, // Returns hardware revision number. + CV_CAP_PROP_XI_DEBUG_LEVEL = 572, // Set debug level + CV_CAP_PROP_XI_AUTO_BANDWIDTH_CALCULATION = 573, // Automatic bandwidth calculation, + CV_CAP_PROP_XI_FFS_FILE_ID = 594, // File number. + CV_CAP_PROP_XI_FFS_FILE_SIZE = 580, // Size of file. + CV_CAP_PROP_XI_FREE_FFS_SIZE = 581, // Size of free camera FFS. + CV_CAP_PROP_XI_USED_FFS_SIZE = 582, // Size of used camera FFS. + CV_CAP_PROP_XI_FFS_ACCESS_KEY = 583, // Setting of key enables file operations on some cameras. + CV_CAP_PROP_XI_SENSOR_FEATURE_SELECTOR = 585, // Selects the current feature which is accessible by XI_PRM_SENSOR_FEATURE_VALUE. + CV_CAP_PROP_XI_SENSOR_FEATURE_VALUE = 586, // Allows access to sensor feature value currently selected by XI_PRM_SENSOR_FEATURE_SELECTOR. + + + // Properties for Android cameras + CV_CAP_PROP_ANDROID_FLASH_MODE = 8001, + CV_CAP_PROP_ANDROID_FOCUS_MODE = 8002, + CV_CAP_PROP_ANDROID_WHITE_BALANCE = 8003, + CV_CAP_PROP_ANDROID_ANTIBANDING = 8004, + CV_CAP_PROP_ANDROID_FOCAL_LENGTH = 8005, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_NEAR = 8006, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_OPTIMAL = 8007, + CV_CAP_PROP_ANDROID_FOCUS_DISTANCE_FAR = 8008, + CV_CAP_PROP_ANDROID_EXPOSE_LOCK = 8009, + CV_CAP_PROP_ANDROID_WHITEBALANCE_LOCK = 8010, + + // Properties of cameras available through AVFOUNDATION interface + CV_CAP_PROP_IOS_DEVICE_FOCUS = 9001, + CV_CAP_PROP_IOS_DEVICE_EXPOSURE = 9002, + CV_CAP_PROP_IOS_DEVICE_FLASH = 9003, + CV_CAP_PROP_IOS_DEVICE_WHITEBALANCE = 9004, + CV_CAP_PROP_IOS_DEVICE_TORCH = 9005, + + // Properties of cameras available through Smartek Giganetix Ethernet Vision interface + /* --- Vladimir Litvinenko (litvinenko.vladimir@gmail.com) --- */ + CV_CAP_PROP_GIGA_FRAME_OFFSET_X = 10001, + CV_CAP_PROP_GIGA_FRAME_OFFSET_Y = 10002, + CV_CAP_PROP_GIGA_FRAME_WIDTH_MAX = 10003, + CV_CAP_PROP_GIGA_FRAME_HEIGH_MAX = 10004, + CV_CAP_PROP_GIGA_FRAME_SENS_WIDTH = 10005, + CV_CAP_PROP_GIGA_FRAME_SENS_HEIGH = 10006, + + CV_CAP_PROP_INTELPERC_PROFILE_COUNT = 11001, + CV_CAP_PROP_INTELPERC_PROFILE_IDX = 11002, + CV_CAP_PROP_INTELPERC_DEPTH_LOW_CONFIDENCE_VALUE = 11003, + CV_CAP_PROP_INTELPERC_DEPTH_SATURATION_VALUE = 11004, + CV_CAP_PROP_INTELPERC_DEPTH_CONFIDENCE_THRESHOLD = 11005, + CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_HORZ = 11006, + CV_CAP_PROP_INTELPERC_DEPTH_FOCAL_LENGTH_VERT = 11007, + + // Intel PerC streams + CV_CAP_INTELPERC_DEPTH_GENERATOR = 1 << 29, + CV_CAP_INTELPERC_IMAGE_GENERATOR = 1 << 28, + CV_CAP_INTELPERC_GENERATORS_MASK = CV_CAP_INTELPERC_DEPTH_GENERATOR + CV_CAP_INTELPERC_IMAGE_GENERATOR +}; + +enum +{ + // Data given from depth generator. + CV_CAP_OPENNI_DEPTH_MAP = 0, // Depth values in mm (CV_16UC1) + CV_CAP_OPENNI_POINT_CLOUD_MAP = 1, // XYZ in meters (CV_32FC3) + CV_CAP_OPENNI_DISPARITY_MAP = 2, // Disparity in pixels (CV_8UC1) + CV_CAP_OPENNI_DISPARITY_MAP_32F = 3, // Disparity in pixels (CV_32FC1) + CV_CAP_OPENNI_VALID_DEPTH_MASK = 4, // CV_8UC1 + + // Data given from RGB image generator. + CV_CAP_OPENNI_BGR_IMAGE = 5, + CV_CAP_OPENNI_GRAY_IMAGE = 6, + + // Data given from IR image generator. + CV_CAP_OPENNI_IR_IMAGE = 7 +}; + +// Supported output modes of OpenNI image generator +enum +{ + CV_CAP_OPENNI_VGA_30HZ = 0, + CV_CAP_OPENNI_SXGA_15HZ = 1, + CV_CAP_OPENNI_SXGA_30HZ = 2, + CV_CAP_OPENNI_QVGA_30HZ = 3, + CV_CAP_OPENNI_QVGA_60HZ = 4 +}; + +enum +{ + CV_CAP_INTELPERC_DEPTH_MAP = 0, // Each pixel is a 16-bit integer. The value indicates the distance from an object to the camera's XY plane or the Cartesian depth. + CV_CAP_INTELPERC_UVDEPTH_MAP = 1, // Each pixel contains two 32-bit floating point values in the range of 0-1, representing the mapping of depth coordinates to the color coordinates. + CV_CAP_INTELPERC_IR_MAP = 2, // Each pixel is a 16-bit integer. The value indicates the intensity of the reflected laser beam. + CV_CAP_INTELPERC_IMAGE = 3 +}; + +// gPhoto2 properties, if propertyId is less than 0 then work on widget with that __additive inversed__ camera setting ID +// Get IDs by using CAP_PROP_GPHOTO2_WIDGET_ENUMERATE. +// @see CvCaptureCAM_GPHOTO2 for more info +enum +{ + CV_CAP_PROP_GPHOTO2_PREVIEW = 17001, // Capture only preview from liveview mode. + CV_CAP_PROP_GPHOTO2_WIDGET_ENUMERATE = 17002, // Readonly, returns (const char *). + CV_CAP_PROP_GPHOTO2_RELOAD_CONFIG = 17003, // Trigger, only by set. Reload camera settings. + CV_CAP_PROP_GPHOTO2_RELOAD_ON_CHANGE = 17004, // Reload all settings on set. + CV_CAP_PROP_GPHOTO2_COLLECT_MSGS = 17005, // Collect messages with details. + CV_CAP_PROP_GPHOTO2_FLUSH_MSGS = 17006, // Readonly, returns (const char *). + CV_CAP_PROP_SPEED = 17007, // Exposure speed. Can be readonly, depends on camera program. + CV_CAP_PROP_APERTURE = 17008, // Aperture. Can be readonly, depends on camera program. + CV_CAP_PROP_EXPOSUREPROGRAM = 17009, // Camera exposure program. + CV_CAP_PROP_VIEWFINDER = 17010 // Enter liveview mode. +}; + +//! (Windows only) Open Codec Selection Dialog +#define CV_FOURCC_PROMPT -1 +//! (Linux only) Use default codec for specified filename +#define CV_FOURCC_DEFAULT CV_FOURCC('I', 'Y', 'U', 'V') + +#endif // OPENCV_VIDEOIO_LEGACY_CONSTANTS_H diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp b/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp index a60d0e87bc..47e94b1909 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/registry.hpp @@ -1,82 +1,82 @@ -// This file is part of OpenCV project. -// It is subject to the license terms in the LICENSE file found in the top-level directory -// of this distribution and at http://opencv.org/license.html. - -#ifndef OPENCV_VIDEOIO_REGISTRY_HPP -#define OPENCV_VIDEOIO_REGISTRY_HPP - -#include - -namespace cv { namespace videoio_registry { -/** @addtogroup videoio_registry -This section contains API description how to query/configure available Video I/O backends. - -Runtime configuration options: -- enable debug mode: `OPENCV_VIDEOIO_DEBUG=1` -- change backend priority: `OPENCV_VIDEOIO_PRIORITY_=9999` -- disable backend: `OPENCV_VIDEOIO_PRIORITY_=0` -- specify list of backends with high priority (>100000): `OPENCV_VIDEOIO_PRIORITY_LIST=FFMPEG,GSTREAMER` - -@{ - */ - - -/** @brief Returns backend API name or "UnknownVideoAPI(xxx)" -@param api backend ID (#VideoCaptureAPIs) -*/ -CV_EXPORTS_W cv::String getBackendName(VideoCaptureAPIs api); - -/** @brief Returns list of all available backends */ -CV_EXPORTS_W std::vector getBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoCapture(int index)` */ -CV_EXPORTS_W std::vector getCameraBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoCapture(filename)` */ -CV_EXPORTS_W std::vector getStreamBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoCapture(buffer)` */ -CV_EXPORTS_W std::vector getStreamBufferedBackends(); - -/** @brief Returns list of available backends which works via `cv::VideoWriter()` */ -CV_EXPORTS_W std::vector getWriterBackends(); - -/** @brief Returns true if backend is available */ -CV_EXPORTS_W bool hasBackend(VideoCaptureAPIs api); - -/** @brief Returns true if backend is built in (false if backend is used as plugin) */ -CV_EXPORTS_W bool isBackendBuiltIn(VideoCaptureAPIs api); - -/** @brief Returns description and ABI/API version of videoio plugin's camera interface */ -CV_EXPORTS_W std::string getCameraBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - -/** @brief Returns description and ABI/API version of videoio plugin's stream capture interface */ -CV_EXPORTS_W std::string getStreamBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - -/** @brief Returns description and ABI/API version of videoio plugin's buffer capture interface */ -CV_EXPORTS_W std::string getStreamBufferedBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - -/** @brief Returns description and ABI/API version of videoio plugin's writer interface */ -CV_EXPORTS_W std::string getWriterBackendPluginVersion( - VideoCaptureAPIs api, - CV_OUT int& version_ABI, - CV_OUT int& version_API -); - - -//! @} -}} // namespace - -#endif // OPENCV_VIDEOIO_REGISTRY_HPP +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#ifndef OPENCV_VIDEOIO_REGISTRY_HPP +#define OPENCV_VIDEOIO_REGISTRY_HPP + +#include + +namespace cv { namespace videoio_registry { +/** @addtogroup videoio_registry +This section contains API description how to query/configure available Video I/O backends. + +Runtime configuration options: +- enable debug mode: `OPENCV_VIDEOIO_DEBUG=1` +- change backend priority: `OPENCV_VIDEOIO_PRIORITY_=9999` +- disable backend: `OPENCV_VIDEOIO_PRIORITY_=0` +- specify list of backends with high priority (>100000): `OPENCV_VIDEOIO_PRIORITY_LIST=FFMPEG,GSTREAMER` + +@{ + */ + + +/** @brief Returns backend API name or "UnknownVideoAPI(xxx)" +@param api backend ID (#VideoCaptureAPIs) +*/ +CV_EXPORTS_W cv::String getBackendName(VideoCaptureAPIs api); + +/** @brief Returns list of all available backends */ +CV_EXPORTS_W std::vector getBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoCapture(int index)` */ +CV_EXPORTS_W std::vector getCameraBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoCapture(filename)` */ +CV_EXPORTS_W std::vector getStreamBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoCapture(buffer)` */ +CV_EXPORTS_W std::vector getStreamBufferedBackends(); + +/** @brief Returns list of available backends which works via `cv::VideoWriter()` */ +CV_EXPORTS_W std::vector getWriterBackends(); + +/** @brief Returns true if backend is available */ +CV_EXPORTS_W bool hasBackend(VideoCaptureAPIs api); + +/** @brief Returns true if backend is built in (false if backend is used as plugin) */ +CV_EXPORTS_W bool isBackendBuiltIn(VideoCaptureAPIs api); + +/** @brief Returns description and ABI/API version of videoio plugin's camera interface */ +CV_EXPORTS_W std::string getCameraBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + +/** @brief Returns description and ABI/API version of videoio plugin's stream capture interface */ +CV_EXPORTS_W std::string getStreamBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + +/** @brief Returns description and ABI/API version of videoio plugin's buffer capture interface */ +CV_EXPORTS_W std::string getStreamBufferedBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + +/** @brief Returns description and ABI/API version of videoio plugin's writer interface */ +CV_EXPORTS_W std::string getWriterBackendPluginVersion( + VideoCaptureAPIs api, + CV_OUT int& version_ABI, + CV_OUT int& version_API +); + + +//! @} +}} // namespace + +#endif // OPENCV_VIDEOIO_REGISTRY_HPP diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp index 00593547ac..ec84cf7a68 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio.hpp @@ -1,48 +1,48 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009, Willow Garage Inc., all rights reserved. -// Copyright (C) 2013, OpenCV Foundation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifdef __OPENCV_BUILD -#error this is a compatibility header which should not be used inside the OpenCV library -#endif - -#include "opencv2/videoio.hpp" +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009, Willow Garage Inc., all rights reserved. +// Copyright (C) 2013, OpenCV Foundation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifdef __OPENCV_BUILD +#error this is a compatibility header which should not be used inside the OpenCV library +#endif + +#include "opencv2/videoio.hpp" diff --git a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h index 3f6efd9d54..cf1a6d0411 100644 --- a/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h +++ b/3rdParty/opencv-4.11.0/opencv2/videoio/videoio_c.h @@ -1,153 +1,153 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// Intel License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000, Intel Corporation, all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of Intel Corporation may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_VIDEOIO_H -#define OPENCV_VIDEOIO_H - -#include "opencv2/core/core_c.h" - -#include "opencv2/videoio/legacy/constants_c.h" - -#ifdef __cplusplus -extern "C" { -#endif /* __cplusplus */ - -/** - @addtogroup videoio_c - @{ -*/ - -/****************************************************************************************\ -* Working with Video Files and Cameras * -\****************************************************************************************/ - -/** @brief "black box" capture structure - -In C++ use cv::VideoCapture -*/ -typedef struct CvCapture CvCapture; - -/** @brief start capturing frames from video file -*/ -CVAPI(CvCapture*) cvCreateFileCapture( const char* filename ); - -/** @brief start capturing frames from video file. allows specifying a preferred API to use -*/ -CVAPI(CvCapture*) cvCreateFileCaptureWithPreference( const char* filename , int apiPreference); - -/** @brief start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) -*/ -CVAPI(CvCapture*) cvCreateCameraCapture( int index ); - -/** @brief grab a frame, return 1 on success, 0 on fail. - - this function is thought to be fast -*/ -CVAPI(int) cvGrabFrame( CvCapture* capture ); - -/** @brief get the frame grabbed with cvGrabFrame(..) - - This function may apply some frame processing like - frame decompression, flipping etc. - @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! -*/ -CVAPI(IplImage*) cvRetrieveFrame( CvCapture* capture, int streamIdx CV_DEFAULT(0) ); - -/** @brief Just a combination of cvGrabFrame and cvRetrieveFrame - - @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! -*/ -CVAPI(IplImage*) cvQueryFrame( CvCapture* capture ); - -/** @brief stop capturing/reading and free resources -*/ -CVAPI(void) cvReleaseCapture( CvCapture** capture ); - -/** @brief retrieve capture properties -*/ -CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id ); -/** @brief set capture properties -*/ -CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value ); - -/** @brief Return the type of the capturer (eg, ::CV_CAP_VFW, ::CV_CAP_UNICAP) - -It is unknown if created with ::CV_CAP_ANY -*/ -CVAPI(int) cvGetCaptureDomain( CvCapture* capture); - -/** @brief "black box" video file writer structure - -In C++ use cv::VideoWriter -*/ -typedef struct CvVideoWriter CvVideoWriter; - -/** @brief initialize video file writer -*/ -CVAPI(CvVideoWriter*) cvCreateVideoWriter( const char* filename, int fourcc, - double fps, CvSize frame_size, - int is_color CV_DEFAULT(1)); - -/** @brief write frame to video file -*/ -CVAPI(int) cvWriteFrame( CvVideoWriter* writer, const IplImage* image ); - -/** @brief close video file writer -*/ -CVAPI(void) cvReleaseVideoWriter( CvVideoWriter** writer ); - -// *************************************************************************************** -//! @name Obsolete functions/synonyms -//! @{ -#define cvCaptureFromCAM cvCreateCameraCapture //!< @deprecated use cvCreateCameraCapture() instead -#define cvCaptureFromFile cvCreateFileCapture //!< @deprecated use cvCreateFileCapture() instead -#define cvCaptureFromAVI cvCaptureFromFile //!< @deprecated use cvCreateFileCapture() instead -#define cvCreateAVIWriter cvCreateVideoWriter //!< @deprecated use cvCreateVideoWriter() instead -#define cvWriteToAVI cvWriteFrame //!< @deprecated use cvWriteFrame() instead -//! @} Obsolete... - -//! @} videoio_c - -#ifdef __cplusplus -} -#endif - -#endif //OPENCV_VIDEOIO_H +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// Intel License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000, Intel Corporation, all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of Intel Corporation may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_VIDEOIO_H +#define OPENCV_VIDEOIO_H + +#include "opencv2/core/core_c.h" + +#include "opencv2/videoio/legacy/constants_c.h" + +#ifdef __cplusplus +extern "C" { +#endif /* __cplusplus */ + +/** + @addtogroup videoio_c + @{ +*/ + +/****************************************************************************************\ +* Working with Video Files and Cameras * +\****************************************************************************************/ + +/** @brief "black box" capture structure + +In C++ use cv::VideoCapture +*/ +typedef struct CvCapture CvCapture; + +/** @brief start capturing frames from video file +*/ +CVAPI(CvCapture*) cvCreateFileCapture( const char* filename ); + +/** @brief start capturing frames from video file. allows specifying a preferred API to use +*/ +CVAPI(CvCapture*) cvCreateFileCaptureWithPreference( const char* filename , int apiPreference); + +/** @brief start capturing frames from camera: index = camera_index + domain_offset (CV_CAP_*) +*/ +CVAPI(CvCapture*) cvCreateCameraCapture( int index ); + +/** @brief grab a frame, return 1 on success, 0 on fail. + + this function is thought to be fast +*/ +CVAPI(int) cvGrabFrame( CvCapture* capture ); + +/** @brief get the frame grabbed with cvGrabFrame(..) + + This function may apply some frame processing like + frame decompression, flipping etc. + @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! +*/ +CVAPI(IplImage*) cvRetrieveFrame( CvCapture* capture, int streamIdx CV_DEFAULT(0) ); + +/** @brief Just a combination of cvGrabFrame and cvRetrieveFrame + + @warning !!!DO NOT RELEASE or MODIFY the retrieved frame!!! +*/ +CVAPI(IplImage*) cvQueryFrame( CvCapture* capture ); + +/** @brief stop capturing/reading and free resources +*/ +CVAPI(void) cvReleaseCapture( CvCapture** capture ); + +/** @brief retrieve capture properties +*/ +CVAPI(double) cvGetCaptureProperty( CvCapture* capture, int property_id ); +/** @brief set capture properties +*/ +CVAPI(int) cvSetCaptureProperty( CvCapture* capture, int property_id, double value ); + +/** @brief Return the type of the capturer (eg, ::CV_CAP_VFW, ::CV_CAP_UNICAP) + +It is unknown if created with ::CV_CAP_ANY +*/ +CVAPI(int) cvGetCaptureDomain( CvCapture* capture); + +/** @brief "black box" video file writer structure + +In C++ use cv::VideoWriter +*/ +typedef struct CvVideoWriter CvVideoWriter; + +/** @brief initialize video file writer +*/ +CVAPI(CvVideoWriter*) cvCreateVideoWriter( const char* filename, int fourcc, + double fps, CvSize frame_size, + int is_color CV_DEFAULT(1)); + +/** @brief write frame to video file +*/ +CVAPI(int) cvWriteFrame( CvVideoWriter* writer, const IplImage* image ); + +/** @brief close video file writer +*/ +CVAPI(void) cvReleaseVideoWriter( CvVideoWriter** writer ); + +// *************************************************************************************** +//! @name Obsolete functions/synonyms +//! @{ +#define cvCaptureFromCAM cvCreateCameraCapture //!< @deprecated use cvCreateCameraCapture() instead +#define cvCaptureFromFile cvCreateFileCapture //!< @deprecated use cvCreateFileCapture() instead +#define cvCaptureFromAVI cvCaptureFromFile //!< @deprecated use cvCreateFileCapture() instead +#define cvCreateAVIWriter cvCreateVideoWriter //!< @deprecated use cvCreateVideoWriter() instead +#define cvWriteToAVI cvWriteFrame //!< @deprecated use cvWriteFrame() instead +//! @} Obsolete... + +//! @} videoio_c + +#ifdef __cplusplus +} +#endif + +#endif //OPENCV_VIDEOIO_H diff --git a/3rdParty/opencv-4.11.0/opencv2/world.hpp b/3rdParty/opencv-4.11.0/opencv2/world.hpp index 8ee6068939..4902c2f2a6 100644 --- a/3rdParty/opencv-4.11.0/opencv2/world.hpp +++ b/3rdParty/opencv-4.11.0/opencv2/world.hpp @@ -1,58 +1,58 @@ -/*M/////////////////////////////////////////////////////////////////////////////////////// -// -// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. -// -// By downloading, copying, installing or using the software you agree to this license. -// If you do not agree to this license, do not download, install, -// copy or use the software. -// -// -// License Agreement -// For Open Source Computer Vision Library -// -// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. -// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. -// Third party copyrights are property of their respective owners. -// -// Redistribution and use in source and binary forms, with or without modification, -// are permitted provided that the following conditions are met: -// -// * Redistribution's of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistribution's in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * The name of the copyright holders may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// -// This software is provided by the copyright holders and contributors "as is" and -// any express or implied warranties, including, but not limited to, the implied -// warranties of merchantability and fitness for a particular purpose are disclaimed. -// In no event shall the Intel Corporation or contributors be liable for any direct, -// indirect, incidental, special, exemplary, or consequential damages -// (including, but not limited to, procurement of substitute goods or services; -// loss of use, data, or profits; or business interruption) however caused -// and on any theory of liability, whether in contract, strict liability, -// or tort (including negligence or otherwise) arising in any way out of -// the use of this software, even if advised of the possibility of such damage. -// -//M*/ - -#ifndef OPENCV_WORLD_HPP -#define OPENCV_WORLD_HPP - -#include "opencv2/core.hpp" - -#ifdef __cplusplus -namespace cv -{ - -CV_EXPORTS_W bool initAll(); - -} - -#endif - -#endif +/*M/////////////////////////////////////////////////////////////////////////////////////// +// +// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. +// +// By downloading, copying, installing or using the software you agree to this license. +// If you do not agree to this license, do not download, install, +// copy or use the software. +// +// +// License Agreement +// For Open Source Computer Vision Library +// +// Copyright (C) 2000-2008, Intel Corporation, all rights reserved. +// Copyright (C) 2009-2010, Willow Garage Inc., all rights reserved. +// Third party copyrights are property of their respective owners. +// +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistribution's of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistribution's in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * The name of the copyright holders may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// This software is provided by the copyright holders and contributors "as is" and +// any express or implied warranties, including, but not limited to, the implied +// warranties of merchantability and fitness for a particular purpose are disclaimed. +// In no event shall the Intel Corporation or contributors be liable for any direct, +// indirect, incidental, special, exemplary, or consequential damages +// (including, but not limited to, procurement of substitute goods or services; +// loss of use, data, or profits; or business interruption) however caused +// and on any theory of liability, whether in contract, strict liability, +// or tort (including negligence or otherwise) arising in any way out of +// the use of this software, even if advised of the possibility of such damage. +// +//M*/ + +#ifndef OPENCV_WORLD_HPP +#define OPENCV_WORLD_HPP + +#include "opencv2/core.hpp" + +#ifdef __cplusplus +namespace cv +{ + +CV_EXPORTS_W bool initAll(); + +} + +#endif + +#endif diff --git a/3rdParty/qdarkstyle/README.md b/3rdParty/qdarkstyle/README.md index dcaf8ddaac..002325bd66 100644 --- a/3rdParty/qdarkstyle/README.md +++ b/3rdParty/qdarkstyle/README.md @@ -1,3 +1,3 @@ -# QDarkStyleSheet - -Taken from [QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet/tree/6ff5fdfd7b1e2a538b6f22bd85dd05a817d24c45/qdarkstyle/dark) with minor modifications. +# QDarkStyleSheet + +Taken from [QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet/tree/6ff5fdfd7b1e2a538b6f22bd85dd05a817d24c45/qdarkstyle/dark) with minor modifications. diff --git a/3rdParty/qdarkstyle/dark/__init__.py b/3rdParty/qdarkstyle/dark/__init__.py index 0bd233716d..faaaf799c7 100644 --- a/3rdParty/qdarkstyle/dark/__init__.py +++ b/3rdParty/qdarkstyle/dark/__init__.py @@ -1,3 +1,3 @@ -# -*- coding: utf-8 -*- - - +# -*- coding: utf-8 -*- + + diff --git a/3rdParty/qdarkstyle/dark/_variables.scss b/3rdParty/qdarkstyle/dark/_variables.scss index 438b8e5a0f..d8f1bbedc8 100644 --- a/3rdParty/qdarkstyle/dark/_variables.scss +++ b/3rdParty/qdarkstyle/dark/_variables.scss @@ -1,33 +1,33 @@ -// --------------------------------------------------------------------------- -// -// WARNING! File created programmatically. All changes made in this file will be lost! -// -// Created by the qtsass compiler v0.3.0 -// -// The definitions are in the "qdarkstyle.palette" module -// -//---------------------------------------------------------------------------- -$ID: 'dark'; -$COLOR_BACKGROUND_6: #60798B; -$COLOR_BACKGROUND_5: #54687A; -$COLOR_BACKGROUND_4: #455364; -$COLOR_BACKGROUND_2: #293544; -$COLOR_BACKGROUND_3: #37414F; -$COLOR_BACKGROUND_1: #19232D; -$COLOR_TEXT_1: #E0E1E3; -$COLOR_TEXT_2: #C9CDD0; -$COLOR_TEXT_3: #ACB1B6; -$COLOR_TEXT_4: #9DA9B5; -$COLOR_ACCENT_1: #26486B; -$COLOR_ACCENT_2: #346792; -$COLOR_ACCENT_3: #1A72BB; -$COLOR_ACCENT_4: #259AE9; -$OPACITY_TOOLTIP: 230; -$SIZE_BORDER_RADIUS: 4px; -$BORDER_1: 1px solid $COLOR_BACKGROUND_1; -$BORDER_2: 1px solid $COLOR_BACKGROUND_4; -$BORDER_3: 1px solid $COLOR_BACKGROUND_6; -$BORDER_SELECTION_3: 1px solid $COLOR_ACCENT_3; -$BORDER_SELECTION_2: 1px solid $COLOR_ACCENT_2; -$BORDER_SELECTION_1: 1px solid $COLOR_ACCENT_1; -$PATH_RESOURCES: ':/qss_icons'; +// --------------------------------------------------------------------------- +// +// WARNING! File created programmatically. All changes made in this file will be lost! +// +// Created by the qtsass compiler v0.3.0 +// +// The definitions are in the "qdarkstyle.palette" module +// +//---------------------------------------------------------------------------- +$ID: 'dark'; +$COLOR_BACKGROUND_6: #60798B; +$COLOR_BACKGROUND_5: #54687A; +$COLOR_BACKGROUND_4: #455364; +$COLOR_BACKGROUND_2: #293544; +$COLOR_BACKGROUND_3: #37414F; +$COLOR_BACKGROUND_1: #19232D; +$COLOR_TEXT_1: #E0E1E3; +$COLOR_TEXT_2: #C9CDD0; +$COLOR_TEXT_3: #ACB1B6; +$COLOR_TEXT_4: #9DA9B5; +$COLOR_ACCENT_1: #26486B; +$COLOR_ACCENT_2: #346792; +$COLOR_ACCENT_3: #1A72BB; +$COLOR_ACCENT_4: #259AE9; +$OPACITY_TOOLTIP: 230; +$SIZE_BORDER_RADIUS: 4px; +$BORDER_1: 1px solid $COLOR_BACKGROUND_1; +$BORDER_2: 1px solid $COLOR_BACKGROUND_4; +$BORDER_3: 1px solid $COLOR_BACKGROUND_6; +$BORDER_SELECTION_3: 1px solid $COLOR_ACCENT_3; +$BORDER_SELECTION_2: 1px solid $COLOR_ACCENT_2; +$BORDER_SELECTION_1: 1px solid $COLOR_ACCENT_1; +$PATH_RESOURCES: ':/qss_icons'; diff --git a/3rdParty/qdarkstyle/dark/darkstyle.qrc b/3rdParty/qdarkstyle/dark/darkstyle.qrc index 61664aacc2..ce0d85be60 100644 --- a/3rdParty/qdarkstyle/dark/darkstyle.qrc +++ b/3rdParty/qdarkstyle/dark/darkstyle.qrc @@ -1,216 +1,216 @@ - - - - rc/arrow_down.png - rc/arrow_down@2x.png - rc/arrow_down_disabled.png - rc/arrow_down_disabled@2x.png - rc/arrow_down_focus.png - rc/arrow_down_focus@2x.png - rc/arrow_down_pressed.png - rc/arrow_down_pressed@2x.png - rc/arrow_left.png - rc/arrow_left@2x.png - rc/arrow_left_disabled.png - rc/arrow_left_disabled@2x.png - rc/arrow_left_focus.png - rc/arrow_left_focus@2x.png - rc/arrow_left_pressed.png - rc/arrow_left_pressed@2x.png - rc/arrow_right.png - rc/arrow_right@2x.png - rc/arrow_right_disabled.png - rc/arrow_right_disabled@2x.png - rc/arrow_right_focus.png - rc/arrow_right_focus@2x.png - rc/arrow_right_pressed.png - rc/arrow_right_pressed@2x.png - rc/arrow_up.png - rc/arrow_up@2x.png - rc/arrow_up_disabled.png - rc/arrow_up_disabled@2x.png - rc/arrow_up_focus.png - rc/arrow_up_focus@2x.png - rc/arrow_up_pressed.png - rc/arrow_up_pressed@2x.png - rc/base_icon.png - rc/base_icon@2x.png - rc/base_icon_disabled.png - rc/base_icon_disabled@2x.png - rc/base_icon_focus.png - rc/base_icon_focus@2x.png - rc/base_icon_pressed.png - rc/base_icon_pressed@2x.png - rc/branch_closed.png - rc/branch_closed@2x.png - rc/branch_closed_disabled.png - rc/branch_closed_disabled@2x.png - rc/branch_closed_focus.png - rc/branch_closed_focus@2x.png - rc/branch_closed_pressed.png - rc/branch_closed_pressed@2x.png - rc/branch_end.png - rc/branch_end@2x.png - rc/branch_end_disabled.png - rc/branch_end_disabled@2x.png - rc/branch_end_focus.png - rc/branch_end_focus@2x.png - rc/branch_end_pressed.png - rc/branch_end_pressed@2x.png - rc/branch_line.png - rc/branch_line@2x.png - rc/branch_line_disabled.png - rc/branch_line_disabled@2x.png - rc/branch_line_focus.png - rc/branch_line_focus@2x.png - rc/branch_line_pressed.png - rc/branch_line_pressed@2x.png - rc/branch_more.png - rc/branch_more@2x.png - rc/branch_more_disabled.png - rc/branch_more_disabled@2x.png - rc/branch_more_focus.png - rc/branch_more_focus@2x.png - rc/branch_more_pressed.png - rc/branch_more_pressed@2x.png - rc/branch_open.png - rc/branch_open@2x.png - rc/branch_open_disabled.png - rc/branch_open_disabled@2x.png - rc/branch_open_focus.png - rc/branch_open_focus@2x.png - rc/branch_open_pressed.png - rc/branch_open_pressed@2x.png - rc/checkbox_checked.png - rc/checkbox_checked@2x.png - rc/checkbox_checked_disabled.png - rc/checkbox_checked_disabled@2x.png - rc/checkbox_checked_focus.png - rc/checkbox_checked_focus@2x.png - rc/checkbox_checked_pressed.png - rc/checkbox_checked_pressed@2x.png - rc/checkbox_indeterminate.png - rc/checkbox_indeterminate@2x.png - rc/checkbox_indeterminate_disabled.png - rc/checkbox_indeterminate_disabled@2x.png - rc/checkbox_indeterminate_focus.png - rc/checkbox_indeterminate_focus@2x.png - rc/checkbox_indeterminate_pressed.png - rc/checkbox_indeterminate_pressed@2x.png - rc/checkbox_unchecked.png - rc/checkbox_unchecked@2x.png - rc/checkbox_unchecked_disabled.png - rc/checkbox_unchecked_disabled@2x.png - rc/checkbox_unchecked_focus.png - rc/checkbox_unchecked_focus@2x.png - rc/checkbox_unchecked_pressed.png - rc/checkbox_unchecked_pressed@2x.png - rc/line_horizontal.png - rc/line_horizontal@2x.png - rc/line_horizontal_disabled.png - rc/line_horizontal_disabled@2x.png - rc/line_horizontal_focus.png - rc/line_horizontal_focus@2x.png - rc/line_horizontal_pressed.png - rc/line_horizontal_pressed@2x.png - rc/line_vertical.png - rc/line_vertical@2x.png - rc/line_vertical_disabled.png - rc/line_vertical_disabled@2x.png - rc/line_vertical_focus.png - rc/line_vertical_focus@2x.png - rc/line_vertical_pressed.png - rc/line_vertical_pressed@2x.png - rc/radio_checked.png - rc/radio_checked@2x.png - rc/radio_checked_disabled.png - rc/radio_checked_disabled@2x.png - rc/radio_checked_focus.png - rc/radio_checked_focus@2x.png - rc/radio_checked_pressed.png - rc/radio_checked_pressed@2x.png - rc/radio_unchecked.png - rc/radio_unchecked@2x.png - rc/radio_unchecked_disabled.png - rc/radio_unchecked_disabled@2x.png - rc/radio_unchecked_focus.png - rc/radio_unchecked_focus@2x.png - rc/radio_unchecked_pressed.png - rc/radio_unchecked_pressed@2x.png - rc/toolbar_move_horizontal.png - rc/toolbar_move_horizontal@2x.png - rc/toolbar_move_horizontal_disabled.png - rc/toolbar_move_horizontal_disabled@2x.png - rc/toolbar_move_horizontal_focus.png - rc/toolbar_move_horizontal_focus@2x.png - rc/toolbar_move_horizontal_pressed.png - rc/toolbar_move_horizontal_pressed@2x.png - rc/toolbar_move_vertical.png - rc/toolbar_move_vertical@2x.png - rc/toolbar_move_vertical_disabled.png - rc/toolbar_move_vertical_disabled@2x.png - rc/toolbar_move_vertical_focus.png - rc/toolbar_move_vertical_focus@2x.png - rc/toolbar_move_vertical_pressed.png - rc/toolbar_move_vertical_pressed@2x.png - rc/toolbar_separator_horizontal.png - rc/toolbar_separator_horizontal@2x.png - rc/toolbar_separator_horizontal_disabled.png - rc/toolbar_separator_horizontal_disabled@2x.png - rc/toolbar_separator_horizontal_focus.png - rc/toolbar_separator_horizontal_focus@2x.png - rc/toolbar_separator_horizontal_pressed.png - rc/toolbar_separator_horizontal_pressed@2x.png - rc/toolbar_separator_vertical.png - rc/toolbar_separator_vertical@2x.png - rc/toolbar_separator_vertical_disabled.png - rc/toolbar_separator_vertical_disabled@2x.png - rc/toolbar_separator_vertical_focus.png - rc/toolbar_separator_vertical_focus@2x.png - rc/toolbar_separator_vertical_pressed.png - rc/toolbar_separator_vertical_pressed@2x.png - rc/transparent.png - rc/transparent@2x.png - rc/transparent_disabled.png - rc/transparent_disabled@2x.png - rc/transparent_focus.png - rc/transparent_focus@2x.png - rc/transparent_pressed.png - rc/transparent_pressed@2x.png - rc/window_close.png - rc/window_close@2x.png - rc/window_close_disabled.png - rc/window_close_disabled@2x.png - rc/window_close_focus.png - rc/window_close_focus@2x.png - rc/window_close_pressed.png - rc/window_close_pressed@2x.png - rc/window_grip.png - rc/window_grip@2x.png - rc/window_grip_disabled.png - rc/window_grip_disabled@2x.png - rc/window_grip_focus.png - rc/window_grip_focus@2x.png - rc/window_grip_pressed.png - rc/window_grip_pressed@2x.png - rc/window_minimize.png - rc/window_minimize@2x.png - rc/window_minimize_disabled.png - rc/window_minimize_disabled@2x.png - rc/window_minimize_focus.png - rc/window_minimize_focus@2x.png - rc/window_minimize_pressed.png - rc/window_minimize_pressed@2x.png - rc/window_undock.png - rc/window_undock@2x.png - rc/window_undock_disabled.png - rc/window_undock_disabled@2x.png - rc/window_undock_focus.png - rc/window_undock_focus@2x.png - rc/window_undock_pressed.png - rc/window_undock_pressed@2x.png - - - darkstyle.qss - - + + + + rc/arrow_down.png + rc/arrow_down@2x.png + rc/arrow_down_disabled.png + rc/arrow_down_disabled@2x.png + rc/arrow_down_focus.png + rc/arrow_down_focus@2x.png + rc/arrow_down_pressed.png + rc/arrow_down_pressed@2x.png + rc/arrow_left.png + rc/arrow_left@2x.png + rc/arrow_left_disabled.png + rc/arrow_left_disabled@2x.png + rc/arrow_left_focus.png + rc/arrow_left_focus@2x.png + rc/arrow_left_pressed.png + rc/arrow_left_pressed@2x.png + rc/arrow_right.png + rc/arrow_right@2x.png + rc/arrow_right_disabled.png + rc/arrow_right_disabled@2x.png + rc/arrow_right_focus.png + rc/arrow_right_focus@2x.png + rc/arrow_right_pressed.png + rc/arrow_right_pressed@2x.png + rc/arrow_up.png + rc/arrow_up@2x.png + rc/arrow_up_disabled.png + rc/arrow_up_disabled@2x.png + rc/arrow_up_focus.png + rc/arrow_up_focus@2x.png + rc/arrow_up_pressed.png + rc/arrow_up_pressed@2x.png + rc/base_icon.png + rc/base_icon@2x.png + rc/base_icon_disabled.png + rc/base_icon_disabled@2x.png + rc/base_icon_focus.png + rc/base_icon_focus@2x.png + rc/base_icon_pressed.png + rc/base_icon_pressed@2x.png + rc/branch_closed.png + rc/branch_closed@2x.png + rc/branch_closed_disabled.png + rc/branch_closed_disabled@2x.png + rc/branch_closed_focus.png + rc/branch_closed_focus@2x.png + rc/branch_closed_pressed.png + rc/branch_closed_pressed@2x.png + rc/branch_end.png + rc/branch_end@2x.png + rc/branch_end_disabled.png + rc/branch_end_disabled@2x.png + rc/branch_end_focus.png + rc/branch_end_focus@2x.png + rc/branch_end_pressed.png + rc/branch_end_pressed@2x.png + rc/branch_line.png + rc/branch_line@2x.png + rc/branch_line_disabled.png + rc/branch_line_disabled@2x.png + rc/branch_line_focus.png + rc/branch_line_focus@2x.png + rc/branch_line_pressed.png + rc/branch_line_pressed@2x.png + rc/branch_more.png + rc/branch_more@2x.png + rc/branch_more_disabled.png + rc/branch_more_disabled@2x.png + rc/branch_more_focus.png + rc/branch_more_focus@2x.png + rc/branch_more_pressed.png + rc/branch_more_pressed@2x.png + rc/branch_open.png + rc/branch_open@2x.png + rc/branch_open_disabled.png + rc/branch_open_disabled@2x.png + rc/branch_open_focus.png + rc/branch_open_focus@2x.png + rc/branch_open_pressed.png + rc/branch_open_pressed@2x.png + rc/checkbox_checked.png + rc/checkbox_checked@2x.png + rc/checkbox_checked_disabled.png + rc/checkbox_checked_disabled@2x.png + rc/checkbox_checked_focus.png + rc/checkbox_checked_focus@2x.png + rc/checkbox_checked_pressed.png + rc/checkbox_checked_pressed@2x.png + rc/checkbox_indeterminate.png + rc/checkbox_indeterminate@2x.png + rc/checkbox_indeterminate_disabled.png + rc/checkbox_indeterminate_disabled@2x.png + rc/checkbox_indeterminate_focus.png + rc/checkbox_indeterminate_focus@2x.png + rc/checkbox_indeterminate_pressed.png + rc/checkbox_indeterminate_pressed@2x.png + rc/checkbox_unchecked.png + rc/checkbox_unchecked@2x.png + rc/checkbox_unchecked_disabled.png + rc/checkbox_unchecked_disabled@2x.png + rc/checkbox_unchecked_focus.png + rc/checkbox_unchecked_focus@2x.png + rc/checkbox_unchecked_pressed.png + rc/checkbox_unchecked_pressed@2x.png + rc/line_horizontal.png + rc/line_horizontal@2x.png + rc/line_horizontal_disabled.png + rc/line_horizontal_disabled@2x.png + rc/line_horizontal_focus.png + rc/line_horizontal_focus@2x.png + rc/line_horizontal_pressed.png + rc/line_horizontal_pressed@2x.png + rc/line_vertical.png + rc/line_vertical@2x.png + rc/line_vertical_disabled.png + rc/line_vertical_disabled@2x.png + rc/line_vertical_focus.png + rc/line_vertical_focus@2x.png + rc/line_vertical_pressed.png + rc/line_vertical_pressed@2x.png + rc/radio_checked.png + rc/radio_checked@2x.png + rc/radio_checked_disabled.png + rc/radio_checked_disabled@2x.png + rc/radio_checked_focus.png + rc/radio_checked_focus@2x.png + rc/radio_checked_pressed.png + rc/radio_checked_pressed@2x.png + rc/radio_unchecked.png + rc/radio_unchecked@2x.png + rc/radio_unchecked_disabled.png + rc/radio_unchecked_disabled@2x.png + rc/radio_unchecked_focus.png + rc/radio_unchecked_focus@2x.png + rc/radio_unchecked_pressed.png + rc/radio_unchecked_pressed@2x.png + rc/toolbar_move_horizontal.png + rc/toolbar_move_horizontal@2x.png + rc/toolbar_move_horizontal_disabled.png + rc/toolbar_move_horizontal_disabled@2x.png + rc/toolbar_move_horizontal_focus.png + rc/toolbar_move_horizontal_focus@2x.png + rc/toolbar_move_horizontal_pressed.png + rc/toolbar_move_horizontal_pressed@2x.png + rc/toolbar_move_vertical.png + rc/toolbar_move_vertical@2x.png + rc/toolbar_move_vertical_disabled.png + rc/toolbar_move_vertical_disabled@2x.png + rc/toolbar_move_vertical_focus.png + rc/toolbar_move_vertical_focus@2x.png + rc/toolbar_move_vertical_pressed.png + rc/toolbar_move_vertical_pressed@2x.png + rc/toolbar_separator_horizontal.png + rc/toolbar_separator_horizontal@2x.png + rc/toolbar_separator_horizontal_disabled.png + rc/toolbar_separator_horizontal_disabled@2x.png + rc/toolbar_separator_horizontal_focus.png + rc/toolbar_separator_horizontal_focus@2x.png + rc/toolbar_separator_horizontal_pressed.png + rc/toolbar_separator_horizontal_pressed@2x.png + rc/toolbar_separator_vertical.png + rc/toolbar_separator_vertical@2x.png + rc/toolbar_separator_vertical_disabled.png + rc/toolbar_separator_vertical_disabled@2x.png + rc/toolbar_separator_vertical_focus.png + rc/toolbar_separator_vertical_focus@2x.png + rc/toolbar_separator_vertical_pressed.png + rc/toolbar_separator_vertical_pressed@2x.png + rc/transparent.png + rc/transparent@2x.png + rc/transparent_disabled.png + rc/transparent_disabled@2x.png + rc/transparent_focus.png + rc/transparent_focus@2x.png + rc/transparent_pressed.png + rc/transparent_pressed@2x.png + rc/window_close.png + rc/window_close@2x.png + rc/window_close_disabled.png + rc/window_close_disabled@2x.png + rc/window_close_focus.png + rc/window_close_focus@2x.png + rc/window_close_pressed.png + rc/window_close_pressed@2x.png + rc/window_grip.png + rc/window_grip@2x.png + rc/window_grip_disabled.png + rc/window_grip_disabled@2x.png + rc/window_grip_focus.png + rc/window_grip_focus@2x.png + rc/window_grip_pressed.png + rc/window_grip_pressed@2x.png + rc/window_minimize.png + rc/window_minimize@2x.png + rc/window_minimize_disabled.png + rc/window_minimize_disabled@2x.png + rc/window_minimize_focus.png + rc/window_minimize_focus@2x.png + rc/window_minimize_pressed.png + rc/window_minimize_pressed@2x.png + rc/window_undock.png + rc/window_undock@2x.png + rc/window_undock_disabled.png + rc/window_undock_disabled@2x.png + rc/window_undock_focus.png + rc/window_undock_focus@2x.png + rc/window_undock_pressed.png + rc/window_undock_pressed@2x.png + + + darkstyle.qss + + diff --git a/3rdParty/qdarkstyle/dark/darkstyle.qss b/3rdParty/qdarkstyle/dark/darkstyle.qss index 1fc6099f2b..5fe3464fa1 100644 --- a/3rdParty/qdarkstyle/dark/darkstyle.qss +++ b/3rdParty/qdarkstyle/dark/darkstyle.qss @@ -1,2217 +1,2217 @@ -/* --------------------------------------------------------------------------- - - WARNING! File created programmatically. All changes made in this file will be lost! - - Created by the qtsass compiler v0.3.0 - - The definitions are in the "qdarkstyle.qss._styles.scss" module - ---------------------------------------------------------------------------- */ -/* Light Style - QDarkStyleSheet ------------------------------------------ */ -/* - -See Qt documentation: - - - https://doc.qt.io/qt-5/stylesheet.html - - https://doc.qt.io/qt-5/stylesheet-reference.html - - https://doc.qt.io/qt-5/stylesheet-examples.html - ---------------------------------------------------------------------------- */ -/* Reset elements ------------------------------------------------------------ - -Resetting everything helps to unify styles across different operating systems - ---------------------------------------------------------------------------- */ -* { - padding: 0px; - margin: 0px; - border: 0px; - border-style: none; - border-image: none; - outline: 0; -} - -/* specific reset for elements inside QToolBar */ -QToolBar * { - margin: 0px; - padding: 0px; -} - -/* QWidget ---------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QWidget { - background-color: #19232D; - border: 0px solid #455364; - padding: 0px; - color: #E0E1E3; - selection-background-color: #346792; - selection-color: #E0E1E3; -} - -QWidget:disabled { - background-color: #19232D; - color: #9DA9B5; - selection-background-color: #26486B; - selection-color: #9DA9B5; -} - -QWidget::item:selected { - background-color: #346792; -} - -QWidget::item:hover:!selected { - background-color: #1A72BB; -} - -/* QMainWindow ------------------------------------------------------------ - -This adjusts the splitter in the dock widget, not qsplitter -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow - ---------------------------------------------------------------------------- */ -QMainWindow::separator { - background-color: #455364; - border: 0px solid #19232D; - spacing: 0px; - padding: 2px; -} - -QMainWindow::separator:hover { - background-color: #60798B; - border: 0px solid #1A72BB; -} - -QMainWindow::separator:horizontal { - width: 5px; - margin-top: 2px; - margin-bottom: 2px; - image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); -} - -QMainWindow::separator:vertical { - height: 5px; - margin-left: 2px; - margin-right: 2px; - image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); -} - -/* QToolTip --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip - ---------------------------------------------------------------------------- */ -QToolTip { - background-color: #346792; - color: #E0E1E3; - /* If you remove the border property, background stops working on Windows */ - border: none; - /* Remove padding, for fix combo box tooltip */ - padding: 0px; - /* Remove opacity, fix #174 - may need to use RGBA */ -} - -/* QStatusBar ------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar - ---------------------------------------------------------------------------- */ -QStatusBar { - border: 1px solid #455364; - /* Fixes Spyder #9120, #9121 */ - background: #455364; - /* Fixes #205, white vertical borders separating items */ -} - -QStatusBar::item { - border: none; -} - -QStatusBar QToolTip { - background-color: #1A72BB; - border: 1px solid #19232D; - color: #19232D; - /* Remove padding, for fix combo box tooltip */ - padding: 0px; - /* Reducing transparency to read better */ - opacity: 230; -} - -QStatusBar QLabel { - /* Fixes Spyder #9120, #9121 */ - background: transparent; -} - -/* QCheckBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox - ---------------------------------------------------------------------------- */ -QCheckBox { - background-color: #19232D; - color: #E0E1E3; - spacing: 4px; - outline: none; - padding-top: 4px; - padding-bottom: 4px; -} - -QCheckBox:focus { - border: none; -} - -QCheckBox QWidget:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QCheckBox::indicator { - margin-left: 2px; - height: 14px; - width: 14px; -} - -QCheckBox::indicator:unchecked { - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QCheckBox::indicator:unchecked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); -} - -QCheckBox::indicator:checked { - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QCheckBox::indicator:checked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); -} - -QCheckBox::indicator:indeterminate { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); -} - -QCheckBox::indicator:indeterminate:disabled { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); -} - -QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); -} - -/* QGroupBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox - ---------------------------------------------------------------------------- */ -QGroupBox { - font-weight: bold; - border: 1px solid #455364; - border-radius: 4px; - padding: 2px; - padding-top: 4px; - margin-top: 6px; - margin-bottom: 4px; -} - -QGroupBox::title { - subcontrol-origin: margin; - subcontrol-position: top left; - left: 4px; - padding-left: 2px; - padding-right: 4px; - padding-top: -4px; -} - -QGroupBox::indicator { - margin-left: 2px; - margin-top: 2px; - padding: 0; - height: 14px; - width: 14px; -} - -QGroupBox::indicator:unchecked { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QGroupBox::indicator:unchecked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); -} - -QGroupBox::indicator:checked { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QGroupBox::indicator:checked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); -} - -/* QRadioButton ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton - ---------------------------------------------------------------------------- */ -QRadioButton { - background-color: #19232D; - color: #E0E1E3; - spacing: 4px; - padding-top: 4px; - padding-bottom: 4px; - border: none; - outline: none; -} - -QRadioButton:focus { - border: none; -} - -QRadioButton:disabled { - background-color: #19232D; - color: #9DA9B5; - border: none; - outline: none; -} - -QRadioButton QWidget { - background-color: #19232D; - color: #E0E1E3; - spacing: 0px; - padding: 0px; - outline: none; - border: none; -} - -QRadioButton::indicator { - border: none; - outline: none; - margin-left: 2px; - height: 14px; - width: 14px; -} - -QRadioButton::indicator:unchecked { - image: url(":/qss_icons/dark/rc/radio_unchecked.png"); -} - -QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); -} - -QRadioButton::indicator:unchecked:disabled { - image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); -} - -QRadioButton::indicator:checked { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked.png"); -} - -QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); -} - -QRadioButton::indicator:checked:disabled { - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); -} - -/* QMenuBar --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar - ---------------------------------------------------------------------------- */ -QMenuBar { - background-color: #455364; - padding: 2px; - border: 1px solid #19232D; - color: #E0E1E3; - selection-background-color: #1A72BB; -} - -QMenuBar:focus { - border: 1px solid #346792; -} - -QMenuBar::item { - background: transparent; - padding: 4px; -} - -QMenuBar::item:selected { - padding: 4px; - background: transparent; - border: 0px solid #455364; - background-color: #1A72BB; -} - -QMenuBar::item:pressed { - padding: 4px; - border: 0px solid #455364; - background-color: #1A72BB; - color: #E0E1E3; - margin-bottom: 0px; - padding-bottom: 0px; -} - -/* QMenu ------------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu - ---------------------------------------------------------------------------- */ -QMenu { - border: 0px solid #455364; - color: #E0E1E3; - margin: 0px; - background-color: #37414F; - selection-background-color: #1A72BB; -} - -QMenu::separator { - height: 1px; - background-color: #60798B; - color: #E0E1E3; -} - -QMenu::item { - background-color: #37414F; - padding: 4px 24px 4px 28px; - /* Reserve space for selection border */ - border: 1px transparent #455364; -} - -QMenu::item:selected { - color: #E0E1E3; - background-color: #1A72BB; -} - -QMenu::item:pressed { - background-color: #1A72BB; -} - -QMenu::icon { - padding-left: 10px; - width: 14px; - height: 14px; -} - -QMenu::indicator { - padding-left: 8px; - width: 12px; - height: 12px; - /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */ - /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */ -} - -QMenu::indicator:non-exclusive:unchecked { - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QMenu::indicator:non-exclusive:unchecked:hover, QMenu::indicator:non-exclusive:unchecked:focus, QMenu::indicator:non-exclusive:unchecked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QMenu::indicator:non-exclusive:unchecked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); -} - -QMenu::indicator:non-exclusive:checked { - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QMenu::indicator:non-exclusive:checked:hover, QMenu::indicator:non-exclusive:checked:focus, QMenu::indicator:non-exclusive:checked:pressed { - border: none; - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QMenu::indicator:non-exclusive:checked:disabled { - image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); -} - -QMenu::indicator:non-exclusive:indeterminate { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); -} - -QMenu::indicator:non-exclusive:indeterminate:disabled { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); -} - -QMenu::indicator:non-exclusive:indeterminate:focus, QMenu::indicator:non-exclusive:indeterminate:hover, QMenu::indicator:non-exclusive:indeterminate:pressed { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); -} - -QMenu::indicator:exclusive:unchecked { - image: url(":/qss_icons/dark/rc/radio_unchecked.png"); -} - -QMenu::indicator:exclusive:unchecked:hover, QMenu::indicator:exclusive:unchecked:focus, QMenu::indicator:exclusive:unchecked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); -} - -QMenu::indicator:exclusive:unchecked:disabled { - image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); -} - -QMenu::indicator:exclusive:checked { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked.png"); -} - -QMenu::indicator:exclusive:checked:hover, QMenu::indicator:exclusive:checked:focus, QMenu::indicator:exclusive:checked:pressed { - border: none; - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); -} - -QMenu::indicator:exclusive:checked:disabled { - outline: none; - image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); -} - -QMenu::right-arrow { - margin: 5px; - padding-left: 12px; - image: url(":/qss_icons/dark/rc/arrow_right.png"); - height: 12px; - width: 12px; -} - -/* QAbstractItemView ------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox - ---------------------------------------------------------------------------- */ -QAbstractItemView { - alternate-background-color: #19232D; - color: #E0E1E3; - border: 1px solid #455364; - border-radius: 4px; -} - -QAbstractItemView QLineEdit { - padding: 2px; -} - -/* QAbstractScrollArea ---------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea - ---------------------------------------------------------------------------- */ -QAbstractScrollArea { - background-color: #19232D; - border: 1px solid #455364; - border-radius: 4px; - /* fix #159 */ - padding: 2px; - /* remove min-height to fix #244 */ - color: #E0E1E3; -} - -QAbstractScrollArea:disabled { - color: #9DA9B5; -} - -/* QScrollArea ------------------------------------------------------------ - ---------------------------------------------------------------------------- */ -QScrollArea QWidget QWidget:disabled { - background-color: #19232D; -} - -/* QScrollBar ------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar - ---------------------------------------------------------------------------- */ -QScrollBar:horizontal { - height: 16px; - margin: 2px 16px 2px 16px; - border: 1px solid #455364; - border-radius: 4px; - background-color: #19232D; -} - -QScrollBar:vertical { - background-color: #19232D; - width: 16px; - margin: 16px 2px 16px 2px; - border: 1px solid #455364; - border-radius: 4px; -} - -QScrollBar::handle:horizontal { - background-color: #60798B; - border: 1px solid #455364; - border-radius: 4px; - min-width: 8px; -} - -QScrollBar::handle:horizontal:hover { - background-color: #346792; - border: #346792; - border-radius: 4px; - min-width: 8px; -} - -QScrollBar::handle:horizontal:focus { - border: 1px solid #1A72BB; -} - -QScrollBar::handle:vertical { - background-color: #60798B; - border: 1px solid #455364; - min-height: 8px; - border-radius: 4px; -} - -QScrollBar::handle:vertical:hover { - background-color: #346792; - border: #346792; - border-radius: 4px; - min-height: 8px; -} - -QScrollBar::handle:vertical:focus { - border: 1px solid #1A72BB; -} - -QScrollBar::add-line:horizontal { - margin: 0px 0px 0px 0px; - border-image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on { - border-image: url(":/qss_icons/dark/rc/arrow_right.png"); - height: 12px; - width: 12px; - subcontrol-position: right; - subcontrol-origin: margin; -} - -QScrollBar::add-line:vertical { - margin: 3px 0px 3px 0px; - border-image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: bottom; - subcontrol-origin: margin; -} - -QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on { - border-image: url(":/qss_icons/dark/rc/arrow_down.png"); - height: 12px; - width: 12px; - subcontrol-position: bottom; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal { - margin: 0px 3px 0px 3px; - border-image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on { - border-image: url(":/qss_icons/dark/rc/arrow_left.png"); - height: 12px; - width: 12px; - subcontrol-position: left; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:vertical { - margin: 3px 0px 3px 0px; - border-image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); - height: 12px; - width: 12px; - subcontrol-position: top; - subcontrol-origin: margin; -} - -QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on { - border-image: url(":/qss_icons/dark/rc/arrow_up.png"); - height: 12px; - width: 12px; - subcontrol-position: top; - subcontrol-origin: margin; -} - -QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal { - background: none; -} - -QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { - background: none; -} - -QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { - background: none; -} - -QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { - background: none; -} - -/* QTextEdit -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets - ---------------------------------------------------------------------------- */ -QTextEdit { - background-color: #19232D; - color: #E0E1E3; - border-radius: 4px; - border: 1px solid #455364; -} - -QTextEdit:focus { - border: 1px solid #1A72BB; -} - -QTextEdit:selected { - background: #346792; - color: #455364; -} - -/* QPlainTextEdit --------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QPlainTextEdit { - background-color: #19232D; - color: #E0E1E3; - border-radius: 4px; - border: 1px solid #455364; -} - -QPlainTextEdit:focus { - border: 1px solid #1A72BB; -} - -QPlainTextEdit:selected { - background: #346792; - color: #455364; -} - -/* QSizeGrip -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip - ---------------------------------------------------------------------------- */ -QSizeGrip { - background: transparent; - width: 12px; - height: 12px; - image: url(":/qss_icons/dark/rc/window_grip.png"); -} - -/* QStackedWidget --------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QStackedWidget { - padding: 2px; - border: 1px solid #455364; - border: 1px solid #19232D; -} - -/* QToolBar --------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar - ---------------------------------------------------------------------------- */ -QToolBar { - background-color: #455364; - border-bottom: 1px solid #19232D; - padding: 1px; - font-weight: bold; - spacing: 2px; -} - -QToolBar:disabled { - /* Fixes #272 */ - background-color: #455364; -} - -QToolBar::handle:horizontal { - width: 16px; - image: url(":/qss_icons/dark/rc/toolbar_move_horizontal.png"); -} - -QToolBar::handle:vertical { - height: 16px; - image: url(":/qss_icons/dark/rc/toolbar_move_vertical.png"); -} - -QToolBar::separator:horizontal { - width: 16px; - image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); -} - -QToolBar::separator:vertical { - height: 16px; - image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); -} - -QToolButton#qt_toolbar_ext_button { - background: #455364; - border: 0px; - color: #E0E1E3; - image: url(":/qss_icons/dark/rc/arrow_right.png"); -} - -/* QAbstractSpinBox ------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QAbstractSpinBox { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - /* This fixes 103, 111 */ - padding-top: 2px; - /* This fixes 103, 111 */ - padding-bottom: 2px; - padding-left: 4px; - padding-right: 4px; - border-radius: 4px; - /* min-width: 5px; removed to fix 109 */ -} - -QAbstractSpinBox:up-button { - background-color: transparent #19232D; - subcontrol-origin: border; - subcontrol-position: top right; - border-left: 1px solid #455364; - border-bottom: 1px solid #455364; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - margin: 1px; - width: 12px; - margin-bottom: -1px; -} - -QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off { - image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); - height: 8px; - width: 8px; -} - -QAbstractSpinBox::up-arrow:hover { - image: url(":/qss_icons/dark/rc/arrow_up.png"); -} - -QAbstractSpinBox:down-button { - background-color: transparent #19232D; - subcontrol-origin: border; - subcontrol-position: bottom right; - border-left: 1px solid #455364; - border-top: 1px solid #455364; - border-top-left-radius: 0; - border-bottom-left-radius: 0; - margin: 1px; - width: 12px; - margin-top: -1px; -} - -QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off { - image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QAbstractSpinBox::down-arrow:hover { - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -QAbstractSpinBox:hover { - border: 1px solid #346792; - color: #E0E1E3; -} - -QAbstractSpinBox:focus { - border: 1px solid #1A72BB; -} - -QAbstractSpinBox:selected { - background: #346792; - color: #455364; -} - -/* ------------------------------------------------------------------------ */ -/* DISPLAYS --------------------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QLabel ----------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe - ---------------------------------------------------------------------------- */ -QLabel { - background-color: #19232D; - border: 0px solid #455364; - padding: 0px; - margin: 0px; - color: #E0E1E3; -} - -QLabel:disabled { - background-color: #19232D; - border: 0px solid #455364; - color: #9DA9B5; -} - -/* QTextBrowser ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea - ---------------------------------------------------------------------------- */ -QTextBrowser { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; -} - -QTextBrowser:disabled { - background-color: #19232D; - border: 1px solid #455364; - color: #9DA9B5; - border-radius: 4px; -} - -QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed { - border: 1px solid #455364; -} - -/* QGraphicsView ---------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QGraphicsView { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; -} - -QGraphicsView:disabled { - background-color: #19232D; - border: 1px solid #455364; - color: #9DA9B5; - border-radius: 4px; -} - -QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed { - border: 1px solid #455364; -} - -/* QCalendarWidget -------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QCalendarWidget { - border: 1px solid #455364; - border-radius: 4px; -} - -QCalendarWidget:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -/* QLCDNumber ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QLCDNumber { - background-color: #19232D; - color: #E0E1E3; -} - -QLCDNumber:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -/* QProgressBar ----------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar - ---------------------------------------------------------------------------- */ -QProgressBar { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; - text-align: center; -} - -QProgressBar:disabled { - background-color: #19232D; - border: 1px solid #455364; - color: #9DA9B5; - border-radius: 4px; - text-align: center; -} - -QProgressBar::chunk { - background-color: #346792; - color: #19232D; - border-radius: 4px; -} - -QProgressBar::chunk:disabled { - background-color: #26486B; - color: #9DA9B5; - border-radius: 4px; -} - -/* ------------------------------------------------------------------------ */ -/* BUTTONS ---------------------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QPushButton ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton - ---------------------------------------------------------------------------- */ -QPushButton { - background-color: #455364; - color: #E0E1E3; - border-radius: 4px; - padding: 2px; - outline: none; - border: none; -} - -QPushButton:disabled { - background-color: #455364; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; -} - -QPushButton:checked { - background-color: #60798B; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QPushButton:checked:disabled { - background-color: #60798B; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QPushButton:checked:selected { - background: #60798B; -} - -QPushButton:hover { - background-color: #54687A; - color: #E0E1E3; -} - -QPushButton:pressed { - background-color: #60798B; -} - -QPushButton:selected { - background: #60798B; - color: #E0E1E3; -} - -QPushButton::menu-indicator { - subcontrol-origin: padding; - subcontrol-position: bottom right; - bottom: 4px; -} - -QDialogButtonBox QPushButton { - /* Issue #194 #248 - Special case of QPushButton inside dialogs, for better UI */ - min-width: 80px; -} - -/* QToolButton ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton - ---------------------------------------------------------------------------- */ -QToolButton { - background-color: #455364; - color: #E0E1E3; - border-radius: 4px; - padding: 2px; - outline: none; - border: none; - /* The subcontrols below are used only in the DelayedPopup mode */ - /* The subcontrols below are used only in the MenuButtonPopup mode */ - /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */ -} - -QToolButton:disabled { - background-color: #455364; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; -} - -QToolButton:checked { - background-color: #60798B; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QToolButton:checked:disabled { - background-color: #60798B; - color: #9DA9B5; - border-radius: 4px; - padding: 2px; - outline: none; -} - -QToolButton:checked:hover { - background-color: #54687A; - color: #E0E1E3; -} - -QToolButton:checked:pressed { - background-color: #60798B; -} - -QToolButton:checked:selected { - background: #60798B; - color: #E0E1E3; -} - -QToolButton:hover { - background-color: #54687A; - color: #E0E1E3; -} - -QToolButton:pressed { - background-color: #60798B; -} - -QToolButton:selected { - background: #60798B; - color: #E0E1E3; -} - -QToolButton[popupMode="0"] { - /* Only for DelayedPopup */ - padding-right: 2px; -} - -QToolButton[popupMode="1"] { - /* Only for MenuButtonPopup */ - padding-right: 20px; -} - -QToolButton[popupMode="1"]::menu-button { - border: none; -} - -QToolButton[popupMode="1"]::menu-button:hover { - border: none; - border-left: 1px solid #455364; - border-radius: 0; -} - -QToolButton[popupMode="2"] { - /* Only for InstantPopup */ - padding-right: 2px; -} - -QToolButton::menu-button { - padding: 2px; - border-radius: 4px; - width: 12px; - border: none; - outline: none; -} - -QToolButton::menu-button:hover { - border: 1px solid #346792; -} - -QToolButton::menu-button:checked:hover { - border: 1px solid #346792; -} - -QToolButton::menu-indicator { - image: url(":/qss_icons/dark/rc/arrow_down.png"); - height: 8px; - width: 8px; - top: 0; - /* Exclude a shift for better image */ - left: -2px; - /* Shift it a bit */ -} - -QToolButton::menu-arrow { - image: url(":/qss_icons/dark/rc/arrow_down.png"); - height: 8px; - width: 8px; -} - -QToolButton::menu-arrow:hover { - image: url(":/qss_icons/dark/rc/arrow_down_focus.png"); -} - -/* QCommandLinkButton ----------------------------------------------------- - ---------------------------------------------------------------------------- */ -QCommandLinkButton { - background-color: transparent; - border: 1px solid #455364; - color: #E0E1E3; - border-radius: 4px; - padding: 0px; - margin: 0px; -} - -QCommandLinkButton:disabled { - background-color: transparent; - color: #9DA9B5; -} - -/* ------------------------------------------------------------------------ */ -/* INPUTS - NO FIELDS ----------------------------------------------------- */ -/* ------------------------------------------------------------------------ */ -/* QComboBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox - ---------------------------------------------------------------------------- */ -QComboBox { - border: 1px solid #455364; - border-radius: 4px; - selection-background-color: #346792; - padding-left: 4px; - padding-right: 4px; - /* padding-right = 36; 4 + 16*2 See scrollbar size */ - /* changed to 4px to fix #239 */ - /* Fixes #103, #111 */ - min-height: 1.5em; - /* padding-top: 2px; removed to fix #132 */ - /* padding-bottom: 2px; removed to fix #132 */ - /* min-width: 75px; removed to fix #109 */ - /* Needed to remove indicator - fix #132 */ -} - -QComboBox QAbstractItemView { - border: 1px solid #455364; - border-radius: 0; - background-color: #19232D; - selection-background-color: #346792; -} - -QComboBox QAbstractItemView:hover { - background-color: #19232D; - color: #E0E1E3; -} - -QComboBox QAbstractItemView:selected { - background: #346792; - color: #455364; -} - -QComboBox QAbstractItemView:alternate { - background: #19232D; -} - -QComboBox:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QComboBox:hover { - border: 1px solid #346792; -} - -QComboBox:focus { - border: 1px solid #1A72BB; -} - -QComboBox:on { - selection-background-color: #346792; -} - -QComboBox::indicator { - border: none; - border-radius: 0; - background-color: transparent; - selection-background-color: transparent; - color: transparent; - selection-color: transparent; - /* Needed to remove indicator - fix #132 */ -} - -QComboBox::indicator:alternate { - background: #19232D; -} - -QComboBox::item { - /* Remove to fix #282, #285 and MR #288*/ - /*&:checked { - font-weight: bold; - } - - &:selected { - border: 0px solid transparent; - } - */ -} - -QComboBox::item:alternate { - background: #19232D; -} - -QComboBox::drop-down { - subcontrol-origin: padding; - subcontrol-position: top right; - width: 12px; - border-left: 1px solid #455364; -} - -QComboBox::down-arrow { - image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus { - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -/* QSlider ---------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider - ---------------------------------------------------------------------------- */ -QSlider:disabled { - background: #19232D; -} - -QSlider:focus { - border: none; -} - -QSlider::groove:horizontal { - background: #455364; - border: 1px solid #455364; - height: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::groove:vertical { - background: #455364; - border: 1px solid #455364; - width: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::add-page:vertical { - background: #346792; - border: 1px solid #455364; - width: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::add-page:vertical :disabled { - background: #26486B; -} - -QSlider::sub-page:horizontal { - background: #346792; - border: 1px solid #455364; - height: 4px; - margin: 0px; - border-radius: 4px; -} - -QSlider::sub-page:horizontal:disabled { - background: #26486B; -} - -QSlider::handle:horizontal { - background: #9DA9B5; - border: 1px solid #455364; - width: 8px; - height: 8px; - margin: -8px 0px; - border-radius: 4px; -} - -QSlider::handle:horizontal:hover { - background: #346792; - border: 1px solid #346792; -} - -QSlider::handle:horizontal:focus { - border: 1px solid #1A72BB; -} - -QSlider::handle:vertical { - background: #9DA9B5; - border: 1px solid #455364; - width: 8px; - height: 8px; - margin: 0 -8px; - border-radius: 4px; -} - -QSlider::handle:vertical:hover { - background: #346792; - border: 1px solid #346792; -} - -QSlider::handle:vertical:focus { - border: 1px solid #1A72BB; -} - -/* QLineEdit -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit - ---------------------------------------------------------------------------- */ -QLineEdit { - background-color: #19232D; - padding-top: 2px; - /* This QLineEdit fix 103, 111 */ - padding-bottom: 2px; - /* This QLineEdit fix 103, 111 */ - padding-left: 4px; - padding-right: 4px; - border-style: solid; - border: 1px solid #455364; - border-radius: 4px; - color: #E0E1E3; -} - -QLineEdit:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QLineEdit:hover { - border: 1px solid #346792; - color: #E0E1E3; -} - -QLineEdit:focus { - border: 1px solid #1A72BB; -} - -QLineEdit:selected { - background-color: #346792; - color: #455364; -} - -/* QTabWiget -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabWidget { - padding: 2px; - selection-background-color: #455364; -} - -QTabWidget QWidget { - /* Fixes #189 */ - border-radius: 4px; -} - -QTabWidget::pane { - border: 1px solid #455364; - border-radius: 4px; - margin: 0px; - /* Fixes double border inside pane with pyqt5 */ - padding: 0px; -} - -QTabWidget::pane:selected { - background-color: #455364; - border: 1px solid #346792; -} - -/* QTabBar ---------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar - ---------------------------------------------------------------------------- */ -QTabBar, QDockWidget QTabBar { - qproperty-drawBase: 0; - border-radius: 4px; - margin: 0px; - padding: 2px; - border: 0; - /* left: 5px; move to the right by 5px - removed for fix */ -} - -QTabBar::close-button, QDockWidget QTabBar::close-button { - border: 0; - margin: 0; - padding: 4px; - image: url(":/qss_icons/dark/rc/window_close.png"); -} - -QTabBar::close-button:hover, QDockWidget QTabBar::close-button:hover { - image: url(":/qss_icons/dark/rc/window_close_focus.png"); -} - -QTabBar::close-button:pressed, QDockWidget QTabBar::close-button:pressed { - image: url(":/qss_icons/dark/rc/window_close_pressed.png"); -} - -QTabBar::tab, QDockWidget QTabBar::tab { - /* !selected and disabled ----------------------------------------- */ - /* selected ------------------------------------------------------- */ -} - -QTabBar::tab:top:selected:disabled, QDockWidget QTabBar::tab:top:selected:disabled { - border-bottom: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:bottom:selected:disabled, QDockWidget QTabBar::tab:bottom:selected:disabled { - border-top: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:left:selected:disabled, QDockWidget QTabBar::tab:left:selected:disabled { - border-right: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:right:selected:disabled, QDockWidget QTabBar::tab:right:selected:disabled { - border-left: 3px solid #26486B; - color: #9DA9B5; - background-color: #455364; -} - -QTabBar::tab:top:!selected:disabled, QDockWidget QTabBar::tab:top:!selected:disabled { - border-bottom: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:bottom:!selected:disabled, QDockWidget QTabBar::tab:bottom:!selected:disabled { - border-top: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:left:!selected:disabled, QDockWidget QTabBar::tab:left:!selected:disabled { - border-right: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:right:!selected:disabled, QDockWidget QTabBar::tab:right:!selected:disabled { - border-left: 3px solid #19232D; - color: #9DA9B5; - background-color: #19232D; -} - -QTabBar::tab:top:!selected, QDockWidget QTabBar::tab:top:!selected { - border-bottom: 2px solid #19232D; - margin-top: 2px; -} - -QTabBar::tab:bottom:!selected, QDockWidget QTabBar::tab:bottom:!selected { - border-top: 2px solid #19232D; - margin-bottom: 2px; -} - -QTabBar::tab:left:!selected, QDockWidget QTabBar::tab:left:!selected { - border-left: 2px solid #19232D; - margin-right: 2px; -} - -QTabBar::tab:right:!selected, QDockWidget QTabBar::tab:right:!selected { - border-right: 2px solid #19232D; - margin-left: 2px; -} - -QTabBar::tab:top, QDockWidget QTabBar::tab:top { - background-color: #455364; - margin-left: 2px; - padding-left: 4px; - padding-right: 4px; - padding-top: 2px; - padding-bottom: 2px; - min-width: 5px; - border-bottom: 3px solid #455364; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QTabBar::tab:top:selected, QDockWidget QTabBar::tab:top:selected { - background-color: #54687A; - border-bottom: 3px solid #259AE9; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QTabBar::tab:top:!selected:hover, QDockWidget QTabBar::tab:top:!selected:hover { - border: 1px solid #1A72BB; - border-bottom: 3px solid #1A72BB; - /* Fixes spyder-ide/spyder#9766 and #243 */ - padding-left: 3px; - padding-right: 3px; -} - -QTabBar::tab:bottom, QDockWidget QTabBar::tab:bottom { - border-top: 3px solid #455364; - background-color: #455364; - margin-left: 2px; - padding-left: 4px; - padding-right: 4px; - padding-top: 2px; - padding-bottom: 2px; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - min-width: 5px; -} - -QTabBar::tab:bottom:selected, QDockWidget QTabBar::tab:bottom:selected { - background-color: #54687A; - border-top: 3px solid #259AE9; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; -} - -QTabBar::tab:bottom:!selected:hover, QDockWidget QTabBar::tab:bottom:!selected:hover { - border: 1px solid #1A72BB; - border-top: 3px solid #1A72BB; - /* Fixes spyder-ide/spyder#9766 and #243 */ - padding-left: 3px; - padding-right: 3px; -} - -QTabBar::tab:left, QDockWidget QTabBar::tab:left { - background-color: #455364; - margin-top: 2px; - padding-left: 2px; - padding-right: 2px; - padding-top: 4px; - padding-bottom: 4px; - border-top-left-radius: 4px; - border-bottom-left-radius: 4px; - min-height: 5px; -} - -QTabBar::tab:left:selected, QDockWidget QTabBar::tab:left:selected { - background-color: #54687A; - border-right: 3px solid #259AE9; -} - -QTabBar::tab:left:!selected:hover, QDockWidget QTabBar::tab:left:!selected:hover { - border: 1px solid #1A72BB; - border-right: 3px solid #1A72BB; - /* Fixes different behavior #271 */ - margin-right: 0px; - padding-right: -1px; -} - -QTabBar::tab:right, QDockWidget QTabBar::tab:right { - background-color: #455364; - margin-top: 2px; - padding-left: 2px; - padding-right: 2px; - padding-top: 4px; - padding-bottom: 4px; - border-top-right-radius: 4px; - border-bottom-right-radius: 4px; - min-height: 5px; -} - -QTabBar::tab:right:selected, QDockWidget QTabBar::tab:right:selected { - background-color: #54687A; - border-left: 3px solid #259AE9; -} - -QTabBar::tab:right:!selected:hover, QDockWidget QTabBar::tab:right:!selected:hover { - border: 1px solid #1A72BB; - border-left: 3px solid #1A72BB; - /* Fixes different behavior #271 */ - margin-left: 0px; - padding-left: 0px; -} - -QTabBar QToolButton, QDockWidget QTabBar QToolButton { - /* Fixes #136 */ - background-color: #455364; - height: 12px; - width: 12px; -} - -QTabBar QToolButton:pressed, QDockWidget QTabBar QToolButton:pressed { - background-color: #455364; -} - -QTabBar QToolButton:pressed:hover, QDockWidget QTabBar QToolButton:pressed:hover { - border: 1px solid #346792; -} - -QTabBar QToolButton::left-arrow:enabled, QDockWidget QTabBar QToolButton::left-arrow:enabled { - image: url(":/qss_icons/dark/rc/arrow_left.png"); -} - -QTabBar QToolButton::left-arrow:disabled, QDockWidget QTabBar QToolButton::left-arrow:disabled { - image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); -} - -QTabBar QToolButton::right-arrow:enabled, QDockWidget QTabBar QToolButton::right-arrow:enabled { - image: url(":/qss_icons/dark/rc/arrow_right.png"); -} - -QTabBar QToolButton::right-arrow:disabled, QDockWidget QTabBar QToolButton::right-arrow:disabled { - image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); -} - -/* QDockWiget ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QDockWidget { - outline: 1px solid #455364; - background-color: #19232D; - border: 1px solid #455364; - border-radius: 4px; - titlebar-close-icon: url(":/qss_icons/dark/rc/transparent.png"); - titlebar-normal-icon: url(":/qss_icons/dark/rc/transparent.png"); -} - -QDockWidget::title { - /* Better size for title bar */ - padding: 3px; - spacing: 4px; - border: none; - background-color: #455364; -} - -QDockWidget::close-button { - icon-size: 12px; - border: none; - background: transparent; - background-image: transparent; - border: 0; - margin: 0; - padding: 0; - image: url(":/qss_icons/dark/rc/window_close.png"); -} - -QDockWidget::close-button:hover { - image: url(":/qss_icons/dark/rc/window_close_focus.png"); -} - -QDockWidget::close-button:pressed { - image: url(":/qss_icons/dark/rc/window_close_pressed.png"); -} - -QDockWidget::float-button { - icon-size: 12px; - border: none; - background: transparent; - background-image: transparent; - border: 0; - margin: 0; - padding: 0; - image: url(":/qss_icons/dark/rc/window_undock.png"); -} - -QDockWidget::float-button:hover { - image: url(":/qss_icons/dark/rc/window_undock_focus.png"); -} - -QDockWidget::float-button:pressed { - image: url(":/qss_icons/dark/rc/window_undock_pressed.png"); -} - -/* QTreeView QListView QTableView ----------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview - ---------------------------------------------------------------------------- */ -QTreeView:branch:selected, QTreeView:branch:hover { - background: url(":/qss_icons/dark/rc/transparent.png"); -} - -QTreeView:branch:has-siblings:!adjoins-item { - border-image: url(":/qss_icons/dark/rc/branch_line.png") 0; -} - -QTreeView:branch:has-siblings:adjoins-item { - border-image: url(":/qss_icons/dark/rc/branch_more.png") 0; -} - -QTreeView:branch:!has-children:!has-siblings:adjoins-item { - border-image: url(":/qss_icons/dark/rc/branch_end.png") 0; -} - -QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings { - border-image: none; - image: url(":/qss_icons/dark/rc/branch_closed.png"); -} - -QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings { - border-image: none; - image: url(":/qss_icons/dark/rc/branch_open.png"); -} - -QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover { - image: url(":/qss_icons/dark/rc/branch_closed_focus.png"); -} - -QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover { - image: url(":/qss_icons/dark/rc/branch_open_focus.png"); -} - -QTreeView::indicator:checked, -QListView::indicator:checked, -QTableView::indicator:checked, -QColumnView::indicator:checked { - image: url(":/qss_icons/dark/rc/checkbox_checked.png"); -} - -QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed, -QListView::indicator:checked:hover, -QListView::indicator:checked:focus, -QListView::indicator:checked:pressed, -QTableView::indicator:checked:hover, -QTableView::indicator:checked:focus, -QTableView::indicator:checked:pressed, -QColumnView::indicator:checked:hover, -QColumnView::indicator:checked:focus, -QColumnView::indicator:checked:pressed { - image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); -} - -QTreeView::indicator:unchecked, -QListView::indicator:unchecked, -QTableView::indicator:unchecked, -QColumnView::indicator:unchecked { - image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); -} - -QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed, -QListView::indicator:unchecked:hover, -QListView::indicator:unchecked:focus, -QListView::indicator:unchecked:pressed, -QTableView::indicator:unchecked:hover, -QTableView::indicator:unchecked:focus, -QTableView::indicator:unchecked:pressed, -QColumnView::indicator:unchecked:hover, -QColumnView::indicator:unchecked:focus, -QColumnView::indicator:unchecked:pressed { - image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); -} - -QTreeView::indicator:indeterminate, -QListView::indicator:indeterminate, -QTableView::indicator:indeterminate, -QColumnView::indicator:indeterminate { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); -} - -QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed, -QListView::indicator:indeterminate:hover, -QListView::indicator:indeterminate:focus, -QListView::indicator:indeterminate:pressed, -QTableView::indicator:indeterminate:hover, -QTableView::indicator:indeterminate:focus, -QTableView::indicator:indeterminate:pressed, -QColumnView::indicator:indeterminate:hover, -QColumnView::indicator:indeterminate:focus, -QColumnView::indicator:indeterminate:pressed { - image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); -} - -QTreeView, -QListView, -QTableView, -QColumnView { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - gridline-color: #455364; - border-radius: 4px; -} - -QTreeView:disabled, -QListView:disabled, -QTableView:disabled, -QColumnView:disabled { - background-color: #19232D; - color: #9DA9B5; -} - -QTreeView:selected, -QListView:selected, -QTableView:selected, -QColumnView:selected { - background-color: #346792; - color: #455364; -} - -QTreeView:focus, -QListView:focus, -QTableView:focus, -QColumnView:focus { - border: 1px solid #1A72BB; -} - -QTreeView::item:pressed, -QListView::item:pressed, -QTableView::item:pressed, -QColumnView::item:pressed { - background-color: #346792; -} - -QTreeView::item:selected:active, -QListView::item:selected:active, -QTableView::item:selected:active, -QColumnView::item:selected:active { - background-color: #346792; -} - -QTreeView::item:selected:!active, -QListView::item:selected:!active, -QTableView::item:selected:!active, -QColumnView::item:selected:!active { - color: #E0E1E3; - background-color: #37414F; -} - -QTreeView::item:!selected:hover, -QListView::item:!selected:hover, -QTableView::item:!selected:hover, -QColumnView::item:!selected:hover { - outline: 0; - color: #E0E1E3; - background-color: #37414F; -} - -QTableCornerButton::section { - background-color: #19232D; - border: 1px transparent #455364; - border-radius: 0px; -} - -/* QHeaderView ------------------------------------------------------------ - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview - ---------------------------------------------------------------------------- */ -QHeaderView { - background-color: #455364; - border: 0px transparent #455364; - padding: 0; - margin: 0; - border-radius: 0; -} - -QHeaderView:disabled { - background-color: #455364; - border: 1px transparent #455364; -} - -QHeaderView::section { - background-color: #455364; - color: #E0E1E3; - border-radius: 0; - text-align: left; - font-size: 13px; -} - -QHeaderView::section::horizontal { - padding-top: 0; - padding-bottom: 0; - padding-left: 4px; - padding-right: 4px; - border-left: 1px solid #19232D; -} - -QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one { - border-left: 1px solid #455364; -} - -QHeaderView::section::horizontal:disabled { - color: #9DA9B5; -} - -QHeaderView::section::vertical { - padding-top: 0; - padding-bottom: 0; - padding-left: 4px; - padding-right: 4px; - border-top: 1px solid #19232D; -} - -QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one { - border-top: 1px solid #455364; -} - -QHeaderView::section::vertical:disabled { - color: #9DA9B5; -} - -QHeaderView::down-arrow { - /* Those settings (border/width/height/background-color) solve bug */ - /* transparent arrow background and size */ - background-color: #455364; - border: none; - height: 12px; - width: 12px; - padding-left: 2px; - padding-right: 2px; - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -QHeaderView::up-arrow { - background-color: #455364; - border: none; - height: 12px; - width: 12px; - padding-left: 2px; - padding-right: 2px; - image: url(":/qss_icons/dark/rc/arrow_up.png"); -} - -/* QToolBox -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox - ---------------------------------------------------------------------------- */ -QToolBox { - padding: 0px; - border: 0px; - border: 1px solid #455364; -} - -QToolBox:selected { - padding: 0px; - border: 2px solid #346792; -} - -QToolBox::tab { - background-color: #19232D; - border: 1px solid #455364; - color: #E0E1E3; - border-top-left-radius: 4px; - border-top-right-radius: 4px; -} - -QToolBox::tab:disabled { - color: #9DA9B5; -} - -QToolBox::tab:selected { - background-color: #60798B; - border-bottom: 2px solid #346792; -} - -QToolBox::tab:selected:disabled { - background-color: #455364; - border-bottom: 2px solid #26486B; -} - -QToolBox::tab:!selected { - background-color: #455364; - border-bottom: 2px solid #455364; -} - -QToolBox::tab:!selected:disabled { - background-color: #19232D; -} - -QToolBox::tab:hover { - border-color: #1A72BB; - border-bottom: 2px solid #1A72BB; -} - -QToolBox QScrollArea QWidget QWidget { - padding: 0px; - border: 0px; - background-color: #19232D; -} - -/* QFrame ----------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe -https://doc.qt.io/qt-5/qframe.html#-prop -https://doc.qt.io/qt-5/qframe.html#details -https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color - ---------------------------------------------------------------------------- */ -/* (dot) .QFrame fix #141, #126, #123 */ -.QFrame { - border-radius: 4px; - border: 1px solid #455364; - /* No frame */ - /* HLine */ - /* HLine */ -} - -.QFrame[frameShape="0"] { - border-radius: 4px; - border: 1px transparent #455364; -} - -.QFrame[frameShape="4"] { - max-height: 2px; - border: none; - background-color: #455364; -} - -.QFrame[frameShape="5"] { - max-width: 2px; - border: none; - background-color: #455364; -} - -/* QSplitter -------------------------------------------------------------- - -https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter - ---------------------------------------------------------------------------- */ -QSplitter { - background-color: #455364; - spacing: 0px; - padding: 0px; - margin: 0px; -} - -QSplitter::handle { - background-color: #455364; - border: 0px solid #19232D; - spacing: 0px; - padding: 1px; - margin: 0px; -} - -QSplitter::handle:hover { - background-color: #9DA9B5; -} - -QSplitter::handle:horizontal { - width: 5px; - image: url(":/qss_icons/dark/rc/line_vertical.png"); -} - -QSplitter::handle:vertical { - height: 5px; - image: url(":/qss_icons/dark/rc/line_horizontal.png"); -} - -/* QDateEdit, QDateTimeEdit ----------------------------------------------- - ---------------------------------------------------------------------------- */ -QDateEdit, QDateTimeEdit { - selection-background-color: #346792; - border-style: solid; - border: 1px solid #455364; - border-radius: 4px; - /* This fixes 103, 111 */ - padding-top: 2px; - /* This fixes 103, 111 */ - padding-bottom: 2px; - padding-left: 4px; - padding-right: 4px; - min-width: 10px; -} - -QDateEdit:on, QDateTimeEdit:on { - selection-background-color: #346792; -} - -QDateEdit::drop-down, QDateTimeEdit::drop-down { - subcontrol-origin: padding; - subcontrol-position: top right; - width: 12px; - border-left: 1px solid #455364; -} - -QDateEdit::down-arrow, QDateTimeEdit::down-arrow { - image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); - height: 8px; - width: 8px; -} - -QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus, QDateTimeEdit::down-arrow:on, QDateTimeEdit::down-arrow:hover, QDateTimeEdit::down-arrow:focus { - image: url(":/qss_icons/dark/rc/arrow_down.png"); -} - -QDateEdit QAbstractItemView, QDateTimeEdit QAbstractItemView { - background-color: #19232D; - border-radius: 4px; - border: 1px solid #455364; - selection-background-color: #346792; -} - -/* QAbstractView ---------------------------------------------------------- - ---------------------------------------------------------------------------- */ -QAbstractView:hover { - border: 1px solid #346792; - color: #E0E1E3; -} - -QAbstractView:selected { - background: #346792; - color: #455364; -} - -/* PlotWidget ------------------------------------------------------------- - ---------------------------------------------------------------------------- */ -PlotWidget { - /* Fix cut labels in plots #134 */ - padding: 0px; -} +/* --------------------------------------------------------------------------- + + WARNING! File created programmatically. All changes made in this file will be lost! + + Created by the qtsass compiler v0.3.0 + + The definitions are in the "qdarkstyle.qss._styles.scss" module + +--------------------------------------------------------------------------- */ +/* Light Style - QDarkStyleSheet ------------------------------------------ */ +/* + +See Qt documentation: + + - https://doc.qt.io/qt-5/stylesheet.html + - https://doc.qt.io/qt-5/stylesheet-reference.html + - https://doc.qt.io/qt-5/stylesheet-examples.html + +--------------------------------------------------------------------------- */ +/* Reset elements ------------------------------------------------------------ + +Resetting everything helps to unify styles across different operating systems + +--------------------------------------------------------------------------- */ +* { + padding: 0px; + margin: 0px; + border: 0px; + border-style: none; + border-image: none; + outline: 0; +} + +/* specific reset for elements inside QToolBar */ +QToolBar * { + margin: 0px; + padding: 0px; +} + +/* QWidget ---------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QWidget { + background-color: #19232D; + border: 0px solid #455364; + padding: 0px; + color: #E0E1E3; + selection-background-color: #346792; + selection-color: #E0E1E3; +} + +QWidget:disabled { + background-color: #19232D; + color: #9DA9B5; + selection-background-color: #26486B; + selection-color: #9DA9B5; +} + +QWidget::item:selected { + background-color: #346792; +} + +QWidget::item:hover:!selected { + background-color: #1A72BB; +} + +/* QMainWindow ------------------------------------------------------------ + +This adjusts the splitter in the dock widget, not qsplitter +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmainwindow + +--------------------------------------------------------------------------- */ +QMainWindow::separator { + background-color: #455364; + border: 0px solid #19232D; + spacing: 0px; + padding: 2px; +} + +QMainWindow::separator:hover { + background-color: #60798B; + border: 0px solid #1A72BB; +} + +QMainWindow::separator:horizontal { + width: 5px; + margin-top: 2px; + margin-bottom: 2px; + image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); +} + +QMainWindow::separator:vertical { + height: 5px; + margin-left: 2px; + margin-right: 2px; + image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); +} + +/* QToolTip --------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtooltip + +--------------------------------------------------------------------------- */ +QToolTip { + background-color: #346792; + color: #E0E1E3; + /* If you remove the border property, background stops working on Windows */ + border: none; + /* Remove padding, for fix combo box tooltip */ + padding: 0px; + /* Remove opacity, fix #174 - may need to use RGBA */ +} + +/* QStatusBar ------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qstatusbar + +--------------------------------------------------------------------------- */ +QStatusBar { + border: 1px solid #455364; + /* Fixes Spyder #9120, #9121 */ + background: #455364; + /* Fixes #205, white vertical borders separating items */ +} + +QStatusBar::item { + border: none; +} + +QStatusBar QToolTip { + background-color: #1A72BB; + border: 1px solid #19232D; + color: #19232D; + /* Remove padding, for fix combo box tooltip */ + padding: 0px; + /* Reducing transparency to read better */ + opacity: 230; +} + +QStatusBar QLabel { + /* Fixes Spyder #9120, #9121 */ + background: transparent; +} + +/* QCheckBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcheckbox + +--------------------------------------------------------------------------- */ +QCheckBox { + background-color: #19232D; + color: #E0E1E3; + spacing: 4px; + outline: none; + padding-top: 4px; + padding-bottom: 4px; +} + +QCheckBox:focus { + border: none; +} + +QCheckBox QWidget:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QCheckBox::indicator { + margin-left: 2px; + height: 14px; + width: 14px; +} + +QCheckBox::indicator:unchecked { + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QCheckBox::indicator:unchecked:hover, QCheckBox::indicator:unchecked:focus, QCheckBox::indicator:unchecked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QCheckBox::indicator:unchecked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); +} + +QCheckBox::indicator:checked { + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QCheckBox::indicator:checked:hover, QCheckBox::indicator:checked:focus, QCheckBox::indicator:checked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QCheckBox::indicator:checked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); +} + +QCheckBox::indicator:indeterminate { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); +} + +QCheckBox::indicator:indeterminate:disabled { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); +} + +QCheckBox::indicator:indeterminate:focus, QCheckBox::indicator:indeterminate:hover, QCheckBox::indicator:indeterminate:pressed { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); +} + +/* QGroupBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qgroupbox + +--------------------------------------------------------------------------- */ +QGroupBox { + font-weight: bold; + border: 1px solid #455364; + border-radius: 4px; + padding: 2px; + padding-top: 4px; + margin-top: 6px; + margin-bottom: 4px; +} + +QGroupBox::title { + subcontrol-origin: margin; + subcontrol-position: top left; + left: 4px; + padding-left: 2px; + padding-right: 4px; + padding-top: -4px; +} + +QGroupBox::indicator { + margin-left: 2px; + margin-top: 2px; + padding: 0; + height: 14px; + width: 14px; +} + +QGroupBox::indicator:unchecked { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QGroupBox::indicator:unchecked:hover, QGroupBox::indicator:unchecked:focus, QGroupBox::indicator:unchecked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QGroupBox::indicator:unchecked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); +} + +QGroupBox::indicator:checked { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QGroupBox::indicator:checked:hover, QGroupBox::indicator:checked:focus, QGroupBox::indicator:checked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QGroupBox::indicator:checked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); +} + +/* QRadioButton ----------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qradiobutton + +--------------------------------------------------------------------------- */ +QRadioButton { + background-color: #19232D; + color: #E0E1E3; + spacing: 4px; + padding-top: 4px; + padding-bottom: 4px; + border: none; + outline: none; +} + +QRadioButton:focus { + border: none; +} + +QRadioButton:disabled { + background-color: #19232D; + color: #9DA9B5; + border: none; + outline: none; +} + +QRadioButton QWidget { + background-color: #19232D; + color: #E0E1E3; + spacing: 0px; + padding: 0px; + outline: none; + border: none; +} + +QRadioButton::indicator { + border: none; + outline: none; + margin-left: 2px; + height: 14px; + width: 14px; +} + +QRadioButton::indicator:unchecked { + image: url(":/qss_icons/dark/rc/radio_unchecked.png"); +} + +QRadioButton::indicator:unchecked:hover, QRadioButton::indicator:unchecked:focus, QRadioButton::indicator:unchecked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); +} + +QRadioButton::indicator:unchecked:disabled { + image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); +} + +QRadioButton::indicator:checked { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked.png"); +} + +QRadioButton::indicator:checked:hover, QRadioButton::indicator:checked:focus, QRadioButton::indicator:checked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); +} + +QRadioButton::indicator:checked:disabled { + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); +} + +/* QMenuBar --------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenubar + +--------------------------------------------------------------------------- */ +QMenuBar { + background-color: #455364; + padding: 2px; + border: 1px solid #19232D; + color: #E0E1E3; + selection-background-color: #1A72BB; +} + +QMenuBar:focus { + border: 1px solid #346792; +} + +QMenuBar::item { + background: transparent; + padding: 4px; +} + +QMenuBar::item:selected { + padding: 4px; + background: transparent; + border: 0px solid #455364; + background-color: #1A72BB; +} + +QMenuBar::item:pressed { + padding: 4px; + border: 0px solid #455364; + background-color: #1A72BB; + color: #E0E1E3; + margin-bottom: 0px; + padding-bottom: 0px; +} + +/* QMenu ------------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qmenu + +--------------------------------------------------------------------------- */ +QMenu { + border: 0px solid #455364; + color: #E0E1E3; + margin: 0px; + background-color: #37414F; + selection-background-color: #1A72BB; +} + +QMenu::separator { + height: 1px; + background-color: #60798B; + color: #E0E1E3; +} + +QMenu::item { + background-color: #37414F; + padding: 4px 24px 4px 28px; + /* Reserve space for selection border */ + border: 1px transparent #455364; +} + +QMenu::item:selected { + color: #E0E1E3; + background-color: #1A72BB; +} + +QMenu::item:pressed { + background-color: #1A72BB; +} + +QMenu::icon { + padding-left: 10px; + width: 14px; + height: 14px; +} + +QMenu::indicator { + padding-left: 8px; + width: 12px; + height: 12px; + /* non-exclusive indicator = check box style indicator (see QActionGroup::setExclusive) */ + /* exclusive indicator = radio button style indicator (see QActionGroup::setExclusive) */ +} + +QMenu::indicator:non-exclusive:unchecked { + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QMenu::indicator:non-exclusive:unchecked:hover, QMenu::indicator:non-exclusive:unchecked:focus, QMenu::indicator:non-exclusive:unchecked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QMenu::indicator:non-exclusive:unchecked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_disabled.png"); +} + +QMenu::indicator:non-exclusive:checked { + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QMenu::indicator:non-exclusive:checked:hover, QMenu::indicator:non-exclusive:checked:focus, QMenu::indicator:non-exclusive:checked:pressed { + border: none; + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QMenu::indicator:non-exclusive:checked:disabled { + image: url(":/qss_icons/dark/rc/checkbox_checked_disabled.png"); +} + +QMenu::indicator:non-exclusive:indeterminate { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); +} + +QMenu::indicator:non-exclusive:indeterminate:disabled { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_disabled.png"); +} + +QMenu::indicator:non-exclusive:indeterminate:focus, QMenu::indicator:non-exclusive:indeterminate:hover, QMenu::indicator:non-exclusive:indeterminate:pressed { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); +} + +QMenu::indicator:exclusive:unchecked { + image: url(":/qss_icons/dark/rc/radio_unchecked.png"); +} + +QMenu::indicator:exclusive:unchecked:hover, QMenu::indicator:exclusive:unchecked:focus, QMenu::indicator:exclusive:unchecked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_unchecked_focus.png"); +} + +QMenu::indicator:exclusive:unchecked:disabled { + image: url(":/qss_icons/dark/rc/radio_unchecked_disabled.png"); +} + +QMenu::indicator:exclusive:checked { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked.png"); +} + +QMenu::indicator:exclusive:checked:hover, QMenu::indicator:exclusive:checked:focus, QMenu::indicator:exclusive:checked:pressed { + border: none; + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_focus.png"); +} + +QMenu::indicator:exclusive:checked:disabled { + outline: none; + image: url(":/qss_icons/dark/rc/radio_checked_disabled.png"); +} + +QMenu::right-arrow { + margin: 5px; + padding-left: 12px; + image: url(":/qss_icons/dark/rc/arrow_right.png"); + height: 12px; + width: 12px; +} + +/* QAbstractItemView ------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox + +--------------------------------------------------------------------------- */ +QAbstractItemView { + alternate-background-color: #19232D; + color: #E0E1E3; + border: 1px solid #455364; + border-radius: 4px; +} + +QAbstractItemView QLineEdit { + padding: 2px; +} + +/* QAbstractScrollArea ---------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea + +--------------------------------------------------------------------------- */ +QAbstractScrollArea { + background-color: #19232D; + border: 1px solid #455364; + border-radius: 4px; + /* fix #159 */ + padding: 2px; + /* remove min-height to fix #244 */ + color: #E0E1E3; +} + +QAbstractScrollArea:disabled { + color: #9DA9B5; +} + +/* QScrollArea ------------------------------------------------------------ + +--------------------------------------------------------------------------- */ +QScrollArea QWidget QWidget:disabled { + background-color: #19232D; +} + +/* QScrollBar ------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qscrollbar + +--------------------------------------------------------------------------- */ +QScrollBar:horizontal { + height: 16px; + margin: 2px 16px 2px 16px; + border: 1px solid #455364; + border-radius: 4px; + background-color: #19232D; +} + +QScrollBar:vertical { + background-color: #19232D; + width: 16px; + margin: 16px 2px 16px 2px; + border: 1px solid #455364; + border-radius: 4px; +} + +QScrollBar::handle:horizontal { + background-color: #60798B; + border: 1px solid #455364; + border-radius: 4px; + min-width: 8px; +} + +QScrollBar::handle:horizontal:hover { + background-color: #346792; + border: #346792; + border-radius: 4px; + min-width: 8px; +} + +QScrollBar::handle:horizontal:focus { + border: 1px solid #1A72BB; +} + +QScrollBar::handle:vertical { + background-color: #60798B; + border: 1px solid #455364; + min-height: 8px; + border-radius: 4px; +} + +QScrollBar::handle:vertical:hover { + background-color: #346792; + border: #346792; + border-radius: 4px; + min-height: 8px; +} + +QScrollBar::handle:vertical:focus { + border: 1px solid #1A72BB; +} + +QScrollBar::add-line:horizontal { + margin: 0px 0px 0px 0px; + border-image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::add-line:horizontal:hover, QScrollBar::add-line:horizontal:on { + border-image: url(":/qss_icons/dark/rc/arrow_right.png"); + height: 12px; + width: 12px; + subcontrol-position: right; + subcontrol-origin: margin; +} + +QScrollBar::add-line:vertical { + margin: 3px 0px 3px 0px; + border-image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: bottom; + subcontrol-origin: margin; +} + +QScrollBar::add-line:vertical:hover, QScrollBar::add-line:vertical:on { + border-image: url(":/qss_icons/dark/rc/arrow_down.png"); + height: 12px; + width: 12px; + subcontrol-position: bottom; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal { + margin: 0px 3px 0px 3px; + border-image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: left; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:horizontal:hover, QScrollBar::sub-line:horizontal:on { + border-image: url(":/qss_icons/dark/rc/arrow_left.png"); + height: 12px; + width: 12px; + subcontrol-position: left; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:vertical { + margin: 3px 0px 3px 0px; + border-image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); + height: 12px; + width: 12px; + subcontrol-position: top; + subcontrol-origin: margin; +} + +QScrollBar::sub-line:vertical:hover, QScrollBar::sub-line:vertical:on { + border-image: url(":/qss_icons/dark/rc/arrow_up.png"); + height: 12px; + width: 12px; + subcontrol-position: top; + subcontrol-origin: margin; +} + +QScrollBar::up-arrow:horizontal, QScrollBar::down-arrow:horizontal { + background: none; +} + +QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { + background: none; +} + +QScrollBar::add-page:horizontal, QScrollBar::sub-page:horizontal { + background: none; +} + +QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { + background: none; +} + +/* QTextEdit -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-specific-widgets + +--------------------------------------------------------------------------- */ +QTextEdit { + background-color: #19232D; + color: #E0E1E3; + border-radius: 4px; + border: 1px solid #455364; +} + +QTextEdit:focus { + border: 1px solid #1A72BB; +} + +QTextEdit:selected { + background: #346792; + color: #455364; +} + +/* QPlainTextEdit --------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QPlainTextEdit { + background-color: #19232D; + color: #E0E1E3; + border-radius: 4px; + border: 1px solid #455364; +} + +QPlainTextEdit:focus { + border: 1px solid #1A72BB; +} + +QPlainTextEdit:selected { + background: #346792; + color: #455364; +} + +/* QSizeGrip -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsizegrip + +--------------------------------------------------------------------------- */ +QSizeGrip { + background: transparent; + width: 12px; + height: 12px; + image: url(":/qss_icons/dark/rc/window_grip.png"); +} + +/* QStackedWidget --------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QStackedWidget { + padding: 2px; + border: 1px solid #455364; + border: 1px solid #19232D; +} + +/* QToolBar --------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbar + +--------------------------------------------------------------------------- */ +QToolBar { + background-color: #455364; + border-bottom: 1px solid #19232D; + padding: 1px; + font-weight: bold; + spacing: 2px; +} + +QToolBar:disabled { + /* Fixes #272 */ + background-color: #455364; +} + +QToolBar::handle:horizontal { + width: 16px; + image: url(":/qss_icons/dark/rc/toolbar_move_horizontal.png"); +} + +QToolBar::handle:vertical { + height: 16px; + image: url(":/qss_icons/dark/rc/toolbar_move_vertical.png"); +} + +QToolBar::separator:horizontal { + width: 16px; + image: url(":/qss_icons/dark/rc/toolbar_separator_horizontal.png"); +} + +QToolBar::separator:vertical { + height: 16px; + image: url(":/qss_icons/dark/rc/toolbar_separator_vertical.png"); +} + +QToolButton#qt_toolbar_ext_button { + background: #455364; + border: 0px; + color: #E0E1E3; + image: url(":/qss_icons/dark/rc/arrow_right.png"); +} + +/* QAbstractSpinBox ------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QAbstractSpinBox { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + /* This fixes 103, 111 */ + padding-top: 2px; + /* This fixes 103, 111 */ + padding-bottom: 2px; + padding-left: 4px; + padding-right: 4px; + border-radius: 4px; + /* min-width: 5px; removed to fix 109 */ +} + +QAbstractSpinBox:up-button { + background-color: transparent #19232D; + subcontrol-origin: border; + subcontrol-position: top right; + border-left: 1px solid #455364; + border-bottom: 1px solid #455364; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + margin: 1px; + width: 12px; + margin-bottom: -1px; +} + +QAbstractSpinBox::up-arrow, QAbstractSpinBox::up-arrow:disabled, QAbstractSpinBox::up-arrow:off { + image: url(":/qss_icons/dark/rc/arrow_up_disabled.png"); + height: 8px; + width: 8px; +} + +QAbstractSpinBox::up-arrow:hover { + image: url(":/qss_icons/dark/rc/arrow_up.png"); +} + +QAbstractSpinBox:down-button { + background-color: transparent #19232D; + subcontrol-origin: border; + subcontrol-position: bottom right; + border-left: 1px solid #455364; + border-top: 1px solid #455364; + border-top-left-radius: 0; + border-bottom-left-radius: 0; + margin: 1px; + width: 12px; + margin-top: -1px; +} + +QAbstractSpinBox::down-arrow, QAbstractSpinBox::down-arrow:disabled, QAbstractSpinBox::down-arrow:off { + image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 8px; + width: 8px; +} + +QAbstractSpinBox::down-arrow:hover { + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +QAbstractSpinBox:hover { + border: 1px solid #346792; + color: #E0E1E3; +} + +QAbstractSpinBox:focus { + border: 1px solid #1A72BB; +} + +QAbstractSpinBox:selected { + background: #346792; + color: #455364; +} + +/* ------------------------------------------------------------------------ */ +/* DISPLAYS --------------------------------------------------------------- */ +/* ------------------------------------------------------------------------ */ +/* QLabel ----------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe + +--------------------------------------------------------------------------- */ +QLabel { + background-color: #19232D; + border: 0px solid #455364; + padding: 0px; + margin: 0px; + color: #E0E1E3; +} + +QLabel:disabled { + background-color: #19232D; + border: 0px solid #455364; + color: #9DA9B5; +} + +/* QTextBrowser ----------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qabstractscrollarea + +--------------------------------------------------------------------------- */ +QTextBrowser { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; +} + +QTextBrowser:disabled { + background-color: #19232D; + border: 1px solid #455364; + color: #9DA9B5; + border-radius: 4px; +} + +QTextBrowser:hover, QTextBrowser:!hover, QTextBrowser:selected, QTextBrowser:pressed { + border: 1px solid #455364; +} + +/* QGraphicsView ---------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QGraphicsView { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; +} + +QGraphicsView:disabled { + background-color: #19232D; + border: 1px solid #455364; + color: #9DA9B5; + border-radius: 4px; +} + +QGraphicsView:hover, QGraphicsView:!hover, QGraphicsView:selected, QGraphicsView:pressed { + border: 1px solid #455364; +} + +/* QCalendarWidget -------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QCalendarWidget { + border: 1px solid #455364; + border-radius: 4px; +} + +QCalendarWidget:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +/* QLCDNumber ------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QLCDNumber { + background-color: #19232D; + color: #E0E1E3; +} + +QLCDNumber:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +/* QProgressBar ----------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qprogressbar + +--------------------------------------------------------------------------- */ +QProgressBar { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; + text-align: center; +} + +QProgressBar:disabled { + background-color: #19232D; + border: 1px solid #455364; + color: #9DA9B5; + border-radius: 4px; + text-align: center; +} + +QProgressBar::chunk { + background-color: #346792; + color: #19232D; + border-radius: 4px; +} + +QProgressBar::chunk:disabled { + background-color: #26486B; + color: #9DA9B5; + border-radius: 4px; +} + +/* ------------------------------------------------------------------------ */ +/* BUTTONS ---------------------------------------------------------------- */ +/* ------------------------------------------------------------------------ */ +/* QPushButton ------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qpushbutton + +--------------------------------------------------------------------------- */ +QPushButton { + background-color: #455364; + color: #E0E1E3; + border-radius: 4px; + padding: 2px; + outline: none; + border: none; +} + +QPushButton:disabled { + background-color: #455364; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; +} + +QPushButton:checked { + background-color: #60798B; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QPushButton:checked:disabled { + background-color: #60798B; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QPushButton:checked:selected { + background: #60798B; +} + +QPushButton:hover { + background-color: #54687A; + color: #E0E1E3; +} + +QPushButton:pressed { + background-color: #60798B; +} + +QPushButton:selected { + background: #60798B; + color: #E0E1E3; +} + +QPushButton::menu-indicator { + subcontrol-origin: padding; + subcontrol-position: bottom right; + bottom: 4px; +} + +QDialogButtonBox QPushButton { + /* Issue #194 #248 - Special case of QPushButton inside dialogs, for better UI */ + min-width: 80px; +} + +/* QToolButton ------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbutton + +--------------------------------------------------------------------------- */ +QToolButton { + background-color: #455364; + color: #E0E1E3; + border-radius: 4px; + padding: 2px; + outline: none; + border: none; + /* The subcontrols below are used only in the DelayedPopup mode */ + /* The subcontrols below are used only in the MenuButtonPopup mode */ + /* The subcontrol below is used only in the InstantPopup or DelayedPopup mode */ +} + +QToolButton:disabled { + background-color: #455364; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; +} + +QToolButton:checked { + background-color: #60798B; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QToolButton:checked:disabled { + background-color: #60798B; + color: #9DA9B5; + border-radius: 4px; + padding: 2px; + outline: none; +} + +QToolButton:checked:hover { + background-color: #54687A; + color: #E0E1E3; +} + +QToolButton:checked:pressed { + background-color: #60798B; +} + +QToolButton:checked:selected { + background: #60798B; + color: #E0E1E3; +} + +QToolButton:hover { + background-color: #54687A; + color: #E0E1E3; +} + +QToolButton:pressed { + background-color: #60798B; +} + +QToolButton:selected { + background: #60798B; + color: #E0E1E3; +} + +QToolButton[popupMode="0"] { + /* Only for DelayedPopup */ + padding-right: 2px; +} + +QToolButton[popupMode="1"] { + /* Only for MenuButtonPopup */ + padding-right: 20px; +} + +QToolButton[popupMode="1"]::menu-button { + border: none; +} + +QToolButton[popupMode="1"]::menu-button:hover { + border: none; + border-left: 1px solid #455364; + border-radius: 0; +} + +QToolButton[popupMode="2"] { + /* Only for InstantPopup */ + padding-right: 2px; +} + +QToolButton::menu-button { + padding: 2px; + border-radius: 4px; + width: 12px; + border: none; + outline: none; +} + +QToolButton::menu-button:hover { + border: 1px solid #346792; +} + +QToolButton::menu-button:checked:hover { + border: 1px solid #346792; +} + +QToolButton::menu-indicator { + image: url(":/qss_icons/dark/rc/arrow_down.png"); + height: 8px; + width: 8px; + top: 0; + /* Exclude a shift for better image */ + left: -2px; + /* Shift it a bit */ +} + +QToolButton::menu-arrow { + image: url(":/qss_icons/dark/rc/arrow_down.png"); + height: 8px; + width: 8px; +} + +QToolButton::menu-arrow:hover { + image: url(":/qss_icons/dark/rc/arrow_down_focus.png"); +} + +/* QCommandLinkButton ----------------------------------------------------- + +--------------------------------------------------------------------------- */ +QCommandLinkButton { + background-color: transparent; + border: 1px solid #455364; + color: #E0E1E3; + border-radius: 4px; + padding: 0px; + margin: 0px; +} + +QCommandLinkButton:disabled { + background-color: transparent; + color: #9DA9B5; +} + +/* ------------------------------------------------------------------------ */ +/* INPUTS - NO FIELDS ----------------------------------------------------- */ +/* ------------------------------------------------------------------------ */ +/* QComboBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qcombobox + +--------------------------------------------------------------------------- */ +QComboBox { + border: 1px solid #455364; + border-radius: 4px; + selection-background-color: #346792; + padding-left: 4px; + padding-right: 4px; + /* padding-right = 36; 4 + 16*2 See scrollbar size */ + /* changed to 4px to fix #239 */ + /* Fixes #103, #111 */ + min-height: 1.5em; + /* padding-top: 2px; removed to fix #132 */ + /* padding-bottom: 2px; removed to fix #132 */ + /* min-width: 75px; removed to fix #109 */ + /* Needed to remove indicator - fix #132 */ +} + +QComboBox QAbstractItemView { + border: 1px solid #455364; + border-radius: 0; + background-color: #19232D; + selection-background-color: #346792; +} + +QComboBox QAbstractItemView:hover { + background-color: #19232D; + color: #E0E1E3; +} + +QComboBox QAbstractItemView:selected { + background: #346792; + color: #455364; +} + +QComboBox QAbstractItemView:alternate { + background: #19232D; +} + +QComboBox:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QComboBox:hover { + border: 1px solid #346792; +} + +QComboBox:focus { + border: 1px solid #1A72BB; +} + +QComboBox:on { + selection-background-color: #346792; +} + +QComboBox::indicator { + border: none; + border-radius: 0; + background-color: transparent; + selection-background-color: transparent; + color: transparent; + selection-color: transparent; + /* Needed to remove indicator - fix #132 */ +} + +QComboBox::indicator:alternate { + background: #19232D; +} + +QComboBox::item { + /* Remove to fix #282, #285 and MR #288*/ + /*&:checked { + font-weight: bold; + } + + &:selected { + border: 0px solid transparent; + } + */ +} + +QComboBox::item:alternate { + background: #19232D; +} + +QComboBox::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 12px; + border-left: 1px solid #455364; +} + +QComboBox::down-arrow { + image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 8px; + width: 8px; +} + +QComboBox::down-arrow:on, QComboBox::down-arrow:hover, QComboBox::down-arrow:focus { + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +/* QSlider ---------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qslider + +--------------------------------------------------------------------------- */ +QSlider:disabled { + background: #19232D; +} + +QSlider:focus { + border: none; +} + +QSlider::groove:horizontal { + background: #455364; + border: 1px solid #455364; + height: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::groove:vertical { + background: #455364; + border: 1px solid #455364; + width: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::add-page:vertical { + background: #346792; + border: 1px solid #455364; + width: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::add-page:vertical :disabled { + background: #26486B; +} + +QSlider::sub-page:horizontal { + background: #346792; + border: 1px solid #455364; + height: 4px; + margin: 0px; + border-radius: 4px; +} + +QSlider::sub-page:horizontal:disabled { + background: #26486B; +} + +QSlider::handle:horizontal { + background: #9DA9B5; + border: 1px solid #455364; + width: 8px; + height: 8px; + margin: -8px 0px; + border-radius: 4px; +} + +QSlider::handle:horizontal:hover { + background: #346792; + border: 1px solid #346792; +} + +QSlider::handle:horizontal:focus { + border: 1px solid #1A72BB; +} + +QSlider::handle:vertical { + background: #9DA9B5; + border: 1px solid #455364; + width: 8px; + height: 8px; + margin: 0 -8px; + border-radius: 4px; +} + +QSlider::handle:vertical:hover { + background: #346792; + border: 1px solid #346792; +} + +QSlider::handle:vertical:focus { + border: 1px solid #1A72BB; +} + +/* QLineEdit -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlineedit + +--------------------------------------------------------------------------- */ +QLineEdit { + background-color: #19232D; + padding-top: 2px; + /* This QLineEdit fix 103, 111 */ + padding-bottom: 2px; + /* This QLineEdit fix 103, 111 */ + padding-left: 4px; + padding-right: 4px; + border-style: solid; + border: 1px solid #455364; + border-radius: 4px; + color: #E0E1E3; +} + +QLineEdit:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QLineEdit:hover { + border: 1px solid #346792; + color: #E0E1E3; +} + +QLineEdit:focus { + border: 1px solid #1A72BB; +} + +QLineEdit:selected { + background-color: #346792; + color: #455364; +} + +/* QTabWiget -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar + +--------------------------------------------------------------------------- */ +QTabWidget { + padding: 2px; + selection-background-color: #455364; +} + +QTabWidget QWidget { + /* Fixes #189 */ + border-radius: 4px; +} + +QTabWidget::pane { + border: 1px solid #455364; + border-radius: 4px; + margin: 0px; + /* Fixes double border inside pane with pyqt5 */ + padding: 0px; +} + +QTabWidget::pane:selected { + background-color: #455364; + border: 1px solid #346792; +} + +/* QTabBar ---------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtabwidget-and-qtabbar + +--------------------------------------------------------------------------- */ +QTabBar, QDockWidget QTabBar { + qproperty-drawBase: 0; + border-radius: 4px; + margin: 0px; + padding: 2px; + border: 0; + /* left: 5px; move to the right by 5px - removed for fix */ +} + +QTabBar::close-button, QDockWidget QTabBar::close-button { + border: 0; + margin: 0; + padding: 4px; + image: url(":/qss_icons/dark/rc/window_close.png"); +} + +QTabBar::close-button:hover, QDockWidget QTabBar::close-button:hover { + image: url(":/qss_icons/dark/rc/window_close_focus.png"); +} + +QTabBar::close-button:pressed, QDockWidget QTabBar::close-button:pressed { + image: url(":/qss_icons/dark/rc/window_close_pressed.png"); +} + +QTabBar::tab, QDockWidget QTabBar::tab { + /* !selected and disabled ----------------------------------------- */ + /* selected ------------------------------------------------------- */ +} + +QTabBar::tab:top:selected:disabled, QDockWidget QTabBar::tab:top:selected:disabled { + border-bottom: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:bottom:selected:disabled, QDockWidget QTabBar::tab:bottom:selected:disabled { + border-top: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:left:selected:disabled, QDockWidget QTabBar::tab:left:selected:disabled { + border-right: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:right:selected:disabled, QDockWidget QTabBar::tab:right:selected:disabled { + border-left: 3px solid #26486B; + color: #9DA9B5; + background-color: #455364; +} + +QTabBar::tab:top:!selected:disabled, QDockWidget QTabBar::tab:top:!selected:disabled { + border-bottom: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:bottom:!selected:disabled, QDockWidget QTabBar::tab:bottom:!selected:disabled { + border-top: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:left:!selected:disabled, QDockWidget QTabBar::tab:left:!selected:disabled { + border-right: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:right:!selected:disabled, QDockWidget QTabBar::tab:right:!selected:disabled { + border-left: 3px solid #19232D; + color: #9DA9B5; + background-color: #19232D; +} + +QTabBar::tab:top:!selected, QDockWidget QTabBar::tab:top:!selected { + border-bottom: 2px solid #19232D; + margin-top: 2px; +} + +QTabBar::tab:bottom:!selected, QDockWidget QTabBar::tab:bottom:!selected { + border-top: 2px solid #19232D; + margin-bottom: 2px; +} + +QTabBar::tab:left:!selected, QDockWidget QTabBar::tab:left:!selected { + border-left: 2px solid #19232D; + margin-right: 2px; +} + +QTabBar::tab:right:!selected, QDockWidget QTabBar::tab:right:!selected { + border-right: 2px solid #19232D; + margin-left: 2px; +} + +QTabBar::tab:top, QDockWidget QTabBar::tab:top { + background-color: #455364; + margin-left: 2px; + padding-left: 4px; + padding-right: 4px; + padding-top: 2px; + padding-bottom: 2px; + min-width: 5px; + border-bottom: 3px solid #455364; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +QTabBar::tab:top:selected, QDockWidget QTabBar::tab:top:selected { + background-color: #54687A; + border-bottom: 3px solid #259AE9; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +QTabBar::tab:top:!selected:hover, QDockWidget QTabBar::tab:top:!selected:hover { + border: 1px solid #1A72BB; + border-bottom: 3px solid #1A72BB; + /* Fixes spyder-ide/spyder#9766 and #243 */ + padding-left: 3px; + padding-right: 3px; +} + +QTabBar::tab:bottom, QDockWidget QTabBar::tab:bottom { + border-top: 3px solid #455364; + background-color: #455364; + margin-left: 2px; + padding-left: 4px; + padding-right: 4px; + padding-top: 2px; + padding-bottom: 2px; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; + min-width: 5px; +} + +QTabBar::tab:bottom:selected, QDockWidget QTabBar::tab:bottom:selected { + background-color: #54687A; + border-top: 3px solid #259AE9; + border-bottom-left-radius: 4px; + border-bottom-right-radius: 4px; +} + +QTabBar::tab:bottom:!selected:hover, QDockWidget QTabBar::tab:bottom:!selected:hover { + border: 1px solid #1A72BB; + border-top: 3px solid #1A72BB; + /* Fixes spyder-ide/spyder#9766 and #243 */ + padding-left: 3px; + padding-right: 3px; +} + +QTabBar::tab:left, QDockWidget QTabBar::tab:left { + background-color: #455364; + margin-top: 2px; + padding-left: 2px; + padding-right: 2px; + padding-top: 4px; + padding-bottom: 4px; + border-top-left-radius: 4px; + border-bottom-left-radius: 4px; + min-height: 5px; +} + +QTabBar::tab:left:selected, QDockWidget QTabBar::tab:left:selected { + background-color: #54687A; + border-right: 3px solid #259AE9; +} + +QTabBar::tab:left:!selected:hover, QDockWidget QTabBar::tab:left:!selected:hover { + border: 1px solid #1A72BB; + border-right: 3px solid #1A72BB; + /* Fixes different behavior #271 */ + margin-right: 0px; + padding-right: -1px; +} + +QTabBar::tab:right, QDockWidget QTabBar::tab:right { + background-color: #455364; + margin-top: 2px; + padding-left: 2px; + padding-right: 2px; + padding-top: 4px; + padding-bottom: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + min-height: 5px; +} + +QTabBar::tab:right:selected, QDockWidget QTabBar::tab:right:selected { + background-color: #54687A; + border-left: 3px solid #259AE9; +} + +QTabBar::tab:right:!selected:hover, QDockWidget QTabBar::tab:right:!selected:hover { + border: 1px solid #1A72BB; + border-left: 3px solid #1A72BB; + /* Fixes different behavior #271 */ + margin-left: 0px; + padding-left: 0px; +} + +QTabBar QToolButton, QDockWidget QTabBar QToolButton { + /* Fixes #136 */ + background-color: #455364; + height: 12px; + width: 12px; +} + +QTabBar QToolButton:pressed, QDockWidget QTabBar QToolButton:pressed { + background-color: #455364; +} + +QTabBar QToolButton:pressed:hover, QDockWidget QTabBar QToolButton:pressed:hover { + border: 1px solid #346792; +} + +QTabBar QToolButton::left-arrow:enabled, QDockWidget QTabBar QToolButton::left-arrow:enabled { + image: url(":/qss_icons/dark/rc/arrow_left.png"); +} + +QTabBar QToolButton::left-arrow:disabled, QDockWidget QTabBar QToolButton::left-arrow:disabled { + image: url(":/qss_icons/dark/rc/arrow_left_disabled.png"); +} + +QTabBar QToolButton::right-arrow:enabled, QDockWidget QTabBar QToolButton::right-arrow:enabled { + image: url(":/qss_icons/dark/rc/arrow_right.png"); +} + +QTabBar QToolButton::right-arrow:disabled, QDockWidget QTabBar QToolButton::right-arrow:disabled { + image: url(":/qss_icons/dark/rc/arrow_right_disabled.png"); +} + +/* QDockWiget ------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QDockWidget { + outline: 1px solid #455364; + background-color: #19232D; + border: 1px solid #455364; + border-radius: 4px; + titlebar-close-icon: url(":/qss_icons/dark/rc/transparent.png"); + titlebar-normal-icon: url(":/qss_icons/dark/rc/transparent.png"); +} + +QDockWidget::title { + /* Better size for title bar */ + padding: 3px; + spacing: 4px; + border: none; + background-color: #455364; +} + +QDockWidget::close-button { + icon-size: 12px; + border: none; + background: transparent; + background-image: transparent; + border: 0; + margin: 0; + padding: 0; + image: url(":/qss_icons/dark/rc/window_close.png"); +} + +QDockWidget::close-button:hover { + image: url(":/qss_icons/dark/rc/window_close_focus.png"); +} + +QDockWidget::close-button:pressed { + image: url(":/qss_icons/dark/rc/window_close_pressed.png"); +} + +QDockWidget::float-button { + icon-size: 12px; + border: none; + background: transparent; + background-image: transparent; + border: 0; + margin: 0; + padding: 0; + image: url(":/qss_icons/dark/rc/window_undock.png"); +} + +QDockWidget::float-button:hover { + image: url(":/qss_icons/dark/rc/window_undock_focus.png"); +} + +QDockWidget::float-button:pressed { + image: url(":/qss_icons/dark/rc/window_undock_pressed.png"); +} + +/* QTreeView QListView QTableView ----------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtreeview +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qlistview +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtableview + +--------------------------------------------------------------------------- */ +QTreeView:branch:selected, QTreeView:branch:hover { + background: url(":/qss_icons/dark/rc/transparent.png"); +} + +QTreeView:branch:has-siblings:!adjoins-item { + border-image: url(":/qss_icons/dark/rc/branch_line.png") 0; +} + +QTreeView:branch:has-siblings:adjoins-item { + border-image: url(":/qss_icons/dark/rc/branch_more.png") 0; +} + +QTreeView:branch:!has-children:!has-siblings:adjoins-item { + border-image: url(":/qss_icons/dark/rc/branch_end.png") 0; +} + +QTreeView:branch:has-children:!has-siblings:closed, QTreeView:branch:closed:has-children:has-siblings { + border-image: none; + image: url(":/qss_icons/dark/rc/branch_closed.png"); +} + +QTreeView:branch:open:has-children:!has-siblings, QTreeView:branch:open:has-children:has-siblings { + border-image: none; + image: url(":/qss_icons/dark/rc/branch_open.png"); +} + +QTreeView:branch:has-children:!has-siblings:closed:hover, QTreeView:branch:closed:has-children:has-siblings:hover { + image: url(":/qss_icons/dark/rc/branch_closed_focus.png"); +} + +QTreeView:branch:open:has-children:!has-siblings:hover, QTreeView:branch:open:has-children:has-siblings:hover { + image: url(":/qss_icons/dark/rc/branch_open_focus.png"); +} + +QTreeView::indicator:checked, +QListView::indicator:checked, +QTableView::indicator:checked, +QColumnView::indicator:checked { + image: url(":/qss_icons/dark/rc/checkbox_checked.png"); +} + +QTreeView::indicator:checked:hover, QTreeView::indicator:checked:focus, QTreeView::indicator:checked:pressed, +QListView::indicator:checked:hover, +QListView::indicator:checked:focus, +QListView::indicator:checked:pressed, +QTableView::indicator:checked:hover, +QTableView::indicator:checked:focus, +QTableView::indicator:checked:pressed, +QColumnView::indicator:checked:hover, +QColumnView::indicator:checked:focus, +QColumnView::indicator:checked:pressed { + image: url(":/qss_icons/dark/rc/checkbox_checked_focus.png"); +} + +QTreeView::indicator:unchecked, +QListView::indicator:unchecked, +QTableView::indicator:unchecked, +QColumnView::indicator:unchecked { + image: url(":/qss_icons/dark/rc/checkbox_unchecked.png"); +} + +QTreeView::indicator:unchecked:hover, QTreeView::indicator:unchecked:focus, QTreeView::indicator:unchecked:pressed, +QListView::indicator:unchecked:hover, +QListView::indicator:unchecked:focus, +QListView::indicator:unchecked:pressed, +QTableView::indicator:unchecked:hover, +QTableView::indicator:unchecked:focus, +QTableView::indicator:unchecked:pressed, +QColumnView::indicator:unchecked:hover, +QColumnView::indicator:unchecked:focus, +QColumnView::indicator:unchecked:pressed { + image: url(":/qss_icons/dark/rc/checkbox_unchecked_focus.png"); +} + +QTreeView::indicator:indeterminate, +QListView::indicator:indeterminate, +QTableView::indicator:indeterminate, +QColumnView::indicator:indeterminate { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate.png"); +} + +QTreeView::indicator:indeterminate:hover, QTreeView::indicator:indeterminate:focus, QTreeView::indicator:indeterminate:pressed, +QListView::indicator:indeterminate:hover, +QListView::indicator:indeterminate:focus, +QListView::indicator:indeterminate:pressed, +QTableView::indicator:indeterminate:hover, +QTableView::indicator:indeterminate:focus, +QTableView::indicator:indeterminate:pressed, +QColumnView::indicator:indeterminate:hover, +QColumnView::indicator:indeterminate:focus, +QColumnView::indicator:indeterminate:pressed { + image: url(":/qss_icons/dark/rc/checkbox_indeterminate_focus.png"); +} + +QTreeView, +QListView, +QTableView, +QColumnView { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + gridline-color: #455364; + border-radius: 4px; +} + +QTreeView:disabled, +QListView:disabled, +QTableView:disabled, +QColumnView:disabled { + background-color: #19232D; + color: #9DA9B5; +} + +QTreeView:selected, +QListView:selected, +QTableView:selected, +QColumnView:selected { + background-color: #346792; + color: #455364; +} + +QTreeView:focus, +QListView:focus, +QTableView:focus, +QColumnView:focus { + border: 1px solid #1A72BB; +} + +QTreeView::item:pressed, +QListView::item:pressed, +QTableView::item:pressed, +QColumnView::item:pressed { + background-color: #346792; +} + +QTreeView::item:selected:active, +QListView::item:selected:active, +QTableView::item:selected:active, +QColumnView::item:selected:active { + background-color: #346792; +} + +QTreeView::item:selected:!active, +QListView::item:selected:!active, +QTableView::item:selected:!active, +QColumnView::item:selected:!active { + color: #E0E1E3; + background-color: #37414F; +} + +QTreeView::item:!selected:hover, +QListView::item:!selected:hover, +QTableView::item:!selected:hover, +QColumnView::item:!selected:hover { + outline: 0; + color: #E0E1E3; + background-color: #37414F; +} + +QTableCornerButton::section { + background-color: #19232D; + border: 1px transparent #455364; + border-radius: 0px; +} + +/* QHeaderView ------------------------------------------------------------ + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qheaderview + +--------------------------------------------------------------------------- */ +QHeaderView { + background-color: #455364; + border: 0px transparent #455364; + padding: 0; + margin: 0; + border-radius: 0; +} + +QHeaderView:disabled { + background-color: #455364; + border: 1px transparent #455364; +} + +QHeaderView::section { + background-color: #455364; + color: #E0E1E3; + border-radius: 0; + text-align: left; + font-size: 13px; +} + +QHeaderView::section::horizontal { + padding-top: 0; + padding-bottom: 0; + padding-left: 4px; + padding-right: 4px; + border-left: 1px solid #19232D; +} + +QHeaderView::section::horizontal::first, QHeaderView::section::horizontal::only-one { + border-left: 1px solid #455364; +} + +QHeaderView::section::horizontal:disabled { + color: #9DA9B5; +} + +QHeaderView::section::vertical { + padding-top: 0; + padding-bottom: 0; + padding-left: 4px; + padding-right: 4px; + border-top: 1px solid #19232D; +} + +QHeaderView::section::vertical::first, QHeaderView::section::vertical::only-one { + border-top: 1px solid #455364; +} + +QHeaderView::section::vertical:disabled { + color: #9DA9B5; +} + +QHeaderView::down-arrow { + /* Those settings (border/width/height/background-color) solve bug */ + /* transparent arrow background and size */ + background-color: #455364; + border: none; + height: 12px; + width: 12px; + padding-left: 2px; + padding-right: 2px; + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +QHeaderView::up-arrow { + background-color: #455364; + border: none; + height: 12px; + width: 12px; + padding-left: 2px; + padding-right: 2px; + image: url(":/qss_icons/dark/rc/arrow_up.png"); +} + +/* QToolBox -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qtoolbox + +--------------------------------------------------------------------------- */ +QToolBox { + padding: 0px; + border: 0px; + border: 1px solid #455364; +} + +QToolBox:selected { + padding: 0px; + border: 2px solid #346792; +} + +QToolBox::tab { + background-color: #19232D; + border: 1px solid #455364; + color: #E0E1E3; + border-top-left-radius: 4px; + border-top-right-radius: 4px; +} + +QToolBox::tab:disabled { + color: #9DA9B5; +} + +QToolBox::tab:selected { + background-color: #60798B; + border-bottom: 2px solid #346792; +} + +QToolBox::tab:selected:disabled { + background-color: #455364; + border-bottom: 2px solid #26486B; +} + +QToolBox::tab:!selected { + background-color: #455364; + border-bottom: 2px solid #455364; +} + +QToolBox::tab:!selected:disabled { + background-color: #19232D; +} + +QToolBox::tab:hover { + border-color: #1A72BB; + border-bottom: 2px solid #1A72BB; +} + +QToolBox QScrollArea QWidget QWidget { + padding: 0px; + border: 0px; + background-color: #19232D; +} + +/* QFrame ----------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qframe +https://doc.qt.io/qt-5/qframe.html#-prop +https://doc.qt.io/qt-5/qframe.html#details +https://stackoverflow.com/questions/14581498/qt-stylesheet-for-hline-vline-color + +--------------------------------------------------------------------------- */ +/* (dot) .QFrame fix #141, #126, #123 */ +.QFrame { + border-radius: 4px; + border: 1px solid #455364; + /* No frame */ + /* HLine */ + /* HLine */ +} + +.QFrame[frameShape="0"] { + border-radius: 4px; + border: 1px transparent #455364; +} + +.QFrame[frameShape="4"] { + max-height: 2px; + border: none; + background-color: #455364; +} + +.QFrame[frameShape="5"] { + max-width: 2px; + border: none; + background-color: #455364; +} + +/* QSplitter -------------------------------------------------------------- + +https://doc.qt.io/qt-5/stylesheet-examples.html#customizing-qsplitter + +--------------------------------------------------------------------------- */ +QSplitter { + background-color: #455364; + spacing: 0px; + padding: 0px; + margin: 0px; +} + +QSplitter::handle { + background-color: #455364; + border: 0px solid #19232D; + spacing: 0px; + padding: 1px; + margin: 0px; +} + +QSplitter::handle:hover { + background-color: #9DA9B5; +} + +QSplitter::handle:horizontal { + width: 5px; + image: url(":/qss_icons/dark/rc/line_vertical.png"); +} + +QSplitter::handle:vertical { + height: 5px; + image: url(":/qss_icons/dark/rc/line_horizontal.png"); +} + +/* QDateEdit, QDateTimeEdit ----------------------------------------------- + +--------------------------------------------------------------------------- */ +QDateEdit, QDateTimeEdit { + selection-background-color: #346792; + border-style: solid; + border: 1px solid #455364; + border-radius: 4px; + /* This fixes 103, 111 */ + padding-top: 2px; + /* This fixes 103, 111 */ + padding-bottom: 2px; + padding-left: 4px; + padding-right: 4px; + min-width: 10px; +} + +QDateEdit:on, QDateTimeEdit:on { + selection-background-color: #346792; +} + +QDateEdit::drop-down, QDateTimeEdit::drop-down { + subcontrol-origin: padding; + subcontrol-position: top right; + width: 12px; + border-left: 1px solid #455364; +} + +QDateEdit::down-arrow, QDateTimeEdit::down-arrow { + image: url(":/qss_icons/dark/rc/arrow_down_disabled.png"); + height: 8px; + width: 8px; +} + +QDateEdit::down-arrow:on, QDateEdit::down-arrow:hover, QDateEdit::down-arrow:focus, QDateTimeEdit::down-arrow:on, QDateTimeEdit::down-arrow:hover, QDateTimeEdit::down-arrow:focus { + image: url(":/qss_icons/dark/rc/arrow_down.png"); +} + +QDateEdit QAbstractItemView, QDateTimeEdit QAbstractItemView { + background-color: #19232D; + border-radius: 4px; + border: 1px solid #455364; + selection-background-color: #346792; +} + +/* QAbstractView ---------------------------------------------------------- + +--------------------------------------------------------------------------- */ +QAbstractView:hover { + border: 1px solid #346792; + color: #E0E1E3; +} + +QAbstractView:selected { + background: #346792; + color: #455364; +} + +/* PlotWidget ------------------------------------------------------------- + +--------------------------------------------------------------------------- */ +PlotWidget { + /* Fix cut labels in plots #134 */ + padding: 0px; +} diff --git a/3rdParty/qdarkstyle/dark/darkstyle_rc.py b/3rdParty/qdarkstyle/dark/darkstyle_rc.py index 8b382a74a8..7eaf96d61f 100644 --- a/3rdParty/qdarkstyle/dark/darkstyle_rc.py +++ b/3rdParty/qdarkstyle/dark/darkstyle_rc.py @@ -1,11382 +1,11382 @@ -# -*- coding: utf-8 -*- - -# Resource object code -# -# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2) -# -# WARNING! All changes made in this file will be lost! - -from qtpy import QtCore - -qt_resource_data = b"\ -\x00\x00\x1a\xa6\ -\x00\ -\x00\xdc\x92\x78\x9c\xd5\x3d\x6b\x6f\xdb\x46\xb6\xdf\x0b\xf4\x3f\ -\xd0\x31\xb0\x68\xbb\x96\x6d\xc9\xb2\x63\xab\xe8\x07\x3b\x8f\x6e\ -\x80\x34\x4d\x6a\x77\x8b\x8b\xc5\x85\x41\x49\x94\xc5\x0d\x45\x2a\ -\x24\x15\xc7\x2d\xee\x7f\xbf\x33\x43\xce\x70\x1e\x67\x5e\x7c\xd8\ -\xa9\x81\xa6\xb6\x34\x73\xde\x73\xce\x3c\xce\x9c\x39\xfa\x21\x18\ -\xf5\xf7\xf3\xed\x37\xdf\x7e\x13\xa0\x9f\x3f\x2e\x7f\x7b\xf7\xe6\ -\xdd\xcf\x7b\xc1\xeb\x38\x89\x82\x45\x1e\x85\x65\xb4\x0c\xb6\x79\ -\x76\x97\x87\x9b\x4d\x58\xc6\x8b\x30\x49\x1e\x0e\x83\xcb\x24\x09\ -\x16\xeb\x30\xbd\x8b\x8a\x60\x13\x2e\xa3\x20\x4e\x83\x72\x1d\x17\ -\xc1\x0a\xf7\xbb\x8f\xd1\xd7\xf3\x28\x48\xb2\xa2\xdc\xa3\xa0\x5f\ -\xd4\xc0\xe6\x0f\xa8\x65\x14\x7c\x2a\x8b\xb0\x28\x82\x45\xb6\xd9\ -\xa2\x2e\x79\xf0\xf9\xf8\xf0\xe4\xf0\x98\x36\xbe\x41\x2d\x96\xd1\ -\x2a\x4e\xe3\x32\xce\xd2\x22\x08\xf3\x1a\x45\x14\x3c\xfb\xb4\x0c\ -\xf3\x8f\x45\xf9\x90\x44\x87\x9f\x8a\xe2\xf0\x96\xfc\x5a\x1c\x16\ -\x8b\xa2\x78\x16\x6c\xb2\xe5\x2e\x89\x30\x98\x1e\xa5\x13\xfc\x70\ -\xf4\xed\x37\x47\x3f\x04\x6f\xe3\xbb\x75\x19\x5c\x63\x7c\xc1\x28\ -\xf8\xf0\x12\xd1\x41\xfe\xb8\x5e\x47\x51\xe9\xa1\x8e\x1a\x1e\xa6\ -\xf2\x3a\x8a\x82\x0f\x65\xb0\xcc\x16\xbb\x4d\x94\x96\x21\x66\x77\ -\x56\x49\x61\x14\xac\xcb\x72\x5b\xcc\x8e\x8e\xd0\xb7\x87\x9f\xca\ -\xc3\x38\x3b\xfa\x54\x8e\x4e\x8f\x2a\x86\x31\xce\xc3\x75\xb9\x49\ -\x1c\xdb\x8e\xf2\x68\x15\xe5\x51\xba\x88\xbc\x7a\x45\x5f\xc2\xcd\ -\x16\xcb\xb7\xea\x34\x88\x5c\x7f\x8b\x0a\x24\xbf\x28\x89\xb0\x08\ -\x8a\x4e\x76\x8d\x29\x24\xe0\xca\x38\xbd\x0b\xa2\xcf\x51\xfe\x80\ -\xec\x12\xfd\xba\x8e\x92\x6d\x11\x94\x59\xb0\x4b\xe3\xd5\x43\x50\ -\x71\x18\x84\x8b\x3c\x43\x56\xb8\x8c\x57\x44\x36\x65\x90\x6d\xa3\ -\x3c\x24\x7d\x8b\x87\xa2\x8c\x36\xc5\x10\x2c\xff\x10\xfc\x85\xc5\ -\xbf\x0d\x97\x4b\x84\x69\x16\x1c\x6f\xbf\xfc\x88\x3f\xd8\x84\xf9\ -\x5d\x9c\x36\x7f\xcf\xb3\x7c\x19\xe5\xf2\xdf\x23\x42\xfb\x2c\x48\ -\xb3\x34\xe2\x3f\x8e\x37\xe1\x1d\xff\x71\xb6\x2b\x93\x38\x45\x9f\ -\x1c\xa3\x3f\xff\x0f\xf3\x81\x44\x5d\x6c\xa3\x45\xbc\x8a\x17\x41\ -\x4e\x64\xbe\xca\xf2\x46\xee\x71\x5a\xc4\x68\x28\x7f\xb8\xc9\xb2\ -\xe4\x2a\xcc\x09\xa9\xcd\x1f\x15\xcd\x32\x89\x12\x0f\x14\xcd\x87\ -\x3f\xe2\xe5\x9d\xd7\x98\x80\x7f\x86\x90\x3e\xa5\x8d\xf0\x33\x0f\ -\x17\x1f\xef\xf2\x6c\x97\x2e\x47\x8b\x2c\xc9\x90\xb0\xf7\xc7\x17\ -\x93\x93\xc9\x4b\x59\x01\x41\x91\x25\xf1\x32\xd8\x9f\x9e\x9e\x9e\ -\x9c\x4d\x21\xde\x83\x80\x42\x78\x75\xfc\x6a\xfc\xea\x84\x7c\x54\ -\x20\xe9\x2e\xf0\xa0\x1e\x01\x98\x4e\xa6\x67\xcf\x2f\x26\x52\x3b\ -\x05\x08\x91\x69\x4d\xf4\x6c\x19\x17\xe1\x3c\x41\x6e\xd4\x81\x7a\ -\xfa\xd1\xc5\xcb\xcb\x8b\xab\x53\x3b\x39\x93\xb3\xe9\xf9\xd9\x95\ -\x86\x1c\x06\x44\x20\x67\x16\xa3\x31\x32\xab\x5a\x1b\x88\x62\x8c\ -\x02\x9d\xd7\x19\x1a\xa4\xb3\x3d\x2b\x8c\xf1\xe5\xf3\xc9\xd5\x15\ -\x6f\x63\xbf\x84\x71\xfa\x47\x9c\x2e\xb3\xfb\xce\x2e\xe3\x06\xc7\ -\xae\x70\xf9\xdf\x5d\x81\xc6\x01\x8e\x32\xc5\x36\x89\xcb\x12\xc5\ -\xa5\x3a\xea\x20\x07\xf9\x11\xc5\x35\x4c\xf7\x01\x1a\x62\x65\xf0\ -\x89\xb6\xf8\xf6\x1b\x4f\x27\xba\xbf\x40\x58\xb2\x4d\xfc\x27\xb2\ -\x9d\xd1\xa7\x0d\x62\xe2\x9e\x30\x31\x88\xad\x37\x32\x9a\x21\x35\ -\x6d\x43\xe4\xdc\xd0\x90\xd7\xc9\x98\x33\x6e\xc0\xf4\x39\xd3\x2a\ -\xb6\xe1\x42\x30\x7d\x36\x16\x26\x8d\x1f\x80\x91\x57\x0a\xd7\x92\ -\x70\x76\xfc\xfc\xe2\xfc\x4a\x4b\x82\x60\x04\x5a\x04\x79\xfc\x67\ -\x86\x82\x69\x52\x61\x41\x6a\x2b\xd7\xb3\xe0\x54\xf0\xb2\xa3\x32\ -\xdb\x52\x6a\xd9\x67\xf3\xac\x44\x9a\x69\x3e\xae\x5d\xea\x2e\x4f\ -\xbe\x7b\x36\x3b\x42\xb3\x8d\xdb\x78\x81\xa6\x23\x47\x78\x06\x72\ -\x94\x2f\x8e\x4a\xe4\x1c\xe7\x61\x7e\xcb\x70\xdf\x22\xd6\xc8\x24\ -\xe9\x70\x9b\xde\x3d\xfb\xde\x42\x28\x6d\x5c\x91\xb9\x8e\xf0\xf4\ -\x42\xa1\x33\x89\x56\xa5\x42\x68\x5e\x35\x6d\x4f\x67\x23\x23\x91\ -\x52\x3c\xae\xb0\xcb\xbf\x89\xb7\x5d\x9d\x37\x06\xd7\x69\x68\x60\ -\xaa\xcb\x78\x3b\xc8\xb8\xa0\x3c\x5a\x3d\x16\xe8\xd5\x91\x94\xde\ -\xac\x82\x87\x6c\x87\xc2\xe8\x06\x99\x33\x71\x11\x95\xb9\xe2\xc9\ -\x32\x9a\x43\x94\x0f\x07\x1c\x58\x34\xdd\xc8\xd0\xec\xe3\x3e\xcb\ -\x3f\xe2\xa9\x45\x96\x06\x95\x31\x14\x84\x98\xc6\xd2\x59\xec\x26\ -\x93\x22\x02\xb9\x1e\x58\x07\x24\x54\xaf\xe2\x2f\x78\xc6\x3c\xcf\ -\x50\x8f\x2f\x41\x2d\x9f\x1a\x86\x12\x8d\x1a\x18\x19\x1e\xad\x98\ -\x22\xdc\x7f\x7f\xfc\x7c\x8a\x66\x7e\x9b\xf0\x21\x48\x23\xe4\x6f\ -\xf1\x94\xa8\x88\x82\xdf\x7e\xbe\xba\x24\x90\x98\x19\x5c\xa3\xd9\ -\xe8\xae\xc0\xb1\xbf\x93\xbc\x3b\x9b\x41\x41\xe8\x40\xe6\x3b\x88\ -\x21\x34\x5c\xfe\xc5\x6b\x62\x0c\x46\x7c\x24\x96\xd7\xf1\x17\x34\ -\x6f\xbc\xde\x3e\x60\x5d\xef\x5f\x8c\x27\xc7\x07\xe4\x7f\x63\xaa\ -\x4a\xa6\xf4\x19\xdc\x75\x7f\x72\x7c\x7a\x10\xdc\xaf\x51\xf0\x0b\ -\x98\x03\xa8\xd0\x16\x41\x3d\x40\xb1\x91\xe0\xe0\x58\x34\x1a\x69\ -\x08\xad\xe2\xa6\x48\x6e\x6d\x38\x52\xcb\xc0\x6a\xe6\xcc\x9f\x82\ -\x9c\x03\x73\x09\xee\xa3\xde\x6c\x74\xb9\xc3\xb1\x24\x28\xf3\x30\ -\x45\x71\x05\x2f\x51\x1e\xb0\x55\xa2\xf5\x22\x5a\x2d\x46\x24\x0a\ -\x57\xdd\x6b\x3b\x46\x7e\xef\xe4\x18\xe2\xf6\x6d\x38\x8f\x6a\x67\ -\xea\xa9\xa9\x06\x77\xc9\x7b\xc2\x17\xeb\x68\xf1\xf1\x0a\xb1\xd1\ -\xcd\xd2\x3a\x0f\x81\x05\xa6\x03\x89\x73\x90\x11\xc0\x98\xf4\x98\ -\x52\xf2\x33\x5c\x3a\x15\x98\xd6\x3a\x65\xeb\x0e\xe6\xcd\x6a\xb5\ -\x57\x21\x77\x2a\xce\x18\x58\xcc\x9d\x72\x13\x07\x4a\xd2\x6c\x85\ -\xd6\xc5\x85\xc1\xd4\x19\xed\xbd\xcc\x8f\x25\xe4\x33\xe4\xa3\xd1\ -\xe8\x64\x13\x26\x30\x20\xd3\xa8\x3d\xa6\x7c\xd5\xb3\x8d\x31\xc8\ -\x4f\x03\x72\xb6\x4b\x89\x56\x29\xa9\xb6\x10\x4e\x4d\xe0\x96\xf5\ -\x93\xa6\x18\x46\x1c\xd5\xa4\xeb\x20\xb0\xb4\x22\xe2\xb6\xb6\xda\ -\xa2\xb5\x63\xc1\x44\x2c\x87\x2e\x7f\x46\x6e\x09\x5a\x2f\x76\x44\ -\x35\xb7\x40\x49\x01\x38\x60\x6d\xa7\x26\x77\x25\xb9\xa8\xc8\x45\ -\x41\x3d\xab\xc7\x57\x39\x1d\x55\xd3\x42\x31\xe8\xb7\x08\x05\x87\ -\x4d\x9c\x86\x28\x96\xfa\xa1\x13\xfa\xfa\xe2\x6a\xcb\xa3\x00\xa4\ -\x35\xa7\x46\x23\x10\x5b\x9a\x4c\x4a\x6c\x29\x18\x4d\x4b\x86\x00\ -\x4b\xc1\x41\xf4\x67\xe4\x80\xb7\x5f\x41\x10\xc5\x81\x60\x3b\x54\ -\x10\x65\x4c\x12\x01\xae\xd0\xca\x6a\x74\x5f\x47\x86\x79\x96\x2c\ -\x75\x33\x2c\x65\xc1\x3d\xca\xc3\x65\xbc\x2b\x94\x30\xa9\xac\x00\ -\x49\x2c\x3d\x83\x97\xaf\x7c\xe8\xa1\x84\xcd\x66\x65\x5c\x26\xf5\ -\x30\x29\x76\x73\xa4\xd0\x32\xcf\x92\x11\x5a\x07\x92\x0d\xbd\x0a\ -\xc4\x8f\xd2\xb7\xdb\xac\x20\x3b\xf0\x68\x86\x94\x6d\x03\x1c\xf9\ -\x48\x8b\x2a\x04\xca\x91\x5c\x0c\x8c\xf4\xd3\x7a\xa9\x2a\x37\x26\ -\xf4\x8f\x60\x4a\x5d\xe2\x2e\xb4\x8a\x6f\xa6\x97\xee\xa1\x19\xc0\ -\x2a\x87\xe6\x1e\x42\x9c\x34\xc6\x8d\x48\xd9\xa8\x35\xb7\xa2\x5e\ -\xc0\xdc\xea\x51\x62\xb5\x99\x84\xa1\x62\x35\x84\xb5\x27\xbd\xb9\ -\x6b\xcd\x45\x67\x2e\x1a\x7b\xc4\xe0\x6d\x42\x3f\x48\xf0\xc6\x41\ -\xe0\x37\xe4\xd6\xb2\xab\x1d\xf2\x4f\x69\x97\x38\xd0\x39\x08\x60\ -\xf7\x9a\xcd\x09\x1d\x83\xc4\x01\x9e\xcf\x9e\xd6\x53\x1e\xab\x27\ -\xc0\x64\xe4\xd5\x58\x65\x03\x1c\x99\xd6\x35\x16\xdf\xb6\xe3\xf1\ -\x83\x3f\x75\x81\xc7\x69\x8d\x49\x98\x9a\xf3\x2a\x68\xb5\x6a\x15\ -\x82\x1c\x9f\xac\x5c\x75\x59\x3a\xc2\x88\x7d\x57\x8f\xc4\xec\xb5\ -\xe1\xc8\x86\x83\x79\x37\x6b\x43\xea\xe2\xac\x0d\xcd\x7e\x4e\x15\ -\xa0\x27\x83\xa0\xe3\xb3\x12\xe5\xe7\xfd\x64\x94\x9a\x30\xa5\xc1\ -\x6a\x8e\x54\x6d\x05\xe0\xa5\x5f\x47\xed\x3a\xea\x76\x58\xcd\xb6\ -\xd0\x2b\xac\xd5\xae\x04\xe8\x43\xdc\x2f\x51\xba\xeb\xbc\x5b\xde\ -\x43\x88\xdb\x20\x3a\x86\xda\x2d\xa7\x3c\xea\xbc\x31\x74\x3a\x3e\ -\x91\x42\x93\x79\x83\xd9\xf5\xec\x5c\x3e\x09\xac\x08\x83\x82\x19\ -\x87\x4f\x3a\x87\xa6\x9d\xf8\x0d\x75\xed\xa6\x30\xc7\x11\xef\x9f\ -\x05\x18\xd2\x49\xb8\xd4\xc1\x0c\xdd\x9c\x6b\xe0\x2e\x81\x8a\x10\ -\x61\x14\xaa\x74\xb4\xc6\x05\x2a\x4a\x5a\x7e\x1e\x6b\xe6\x28\x52\ -\x8a\x08\x26\xb8\x87\x1c\xb6\x5e\xc6\xcb\x60\x83\x45\x34\x45\x58\ -\xde\x5a\x89\x72\x99\x3f\xc0\x09\xe5\xf3\xe9\x78\xfa\xba\xd5\x40\ -\x51\x52\x01\xd8\x4c\x44\x8f\x8e\x3b\x97\xd7\x64\xa8\x54\x90\xa1\ -\xa1\x04\xd1\xcc\xdb\x64\x30\xc1\xff\x90\x5f\xce\xf9\x83\xa1\x22\ -\xca\x3f\x47\x64\x0e\x17\x91\xa3\x25\xc6\x27\x3d\x6b\x15\x4f\x4f\ -\xf1\x40\xe7\x46\x15\x27\x63\x99\x40\x69\x9c\x02\x0a\x70\x15\xa4\ -\x3a\xd8\x9c\x7b\x2e\xe8\x12\x41\xdc\x3f\x19\x1f\x83\xb3\x41\x65\ -\xba\x28\xc0\x12\x27\xa4\x22\xc0\x73\x09\x9e\x32\xfd\x9c\x34\x32\ -\x47\x41\x11\x0d\x95\x45\xb2\x2b\xe2\xcf\x38\xe3\x92\x82\xfd\x29\ -\x20\xf1\x8f\x1c\xe9\x91\x51\xc5\x7d\xf7\x5d\x81\x73\x18\x2f\x89\ -\x62\xc8\xda\x12\x9b\x57\xf9\x8a\x42\xf9\xbe\xd6\x12\x82\x0e\x43\ -\x26\xf1\x35\xa8\xd6\x64\xed\x80\x83\xa2\x98\x09\xbc\xf4\x7e\xdc\ -\xe2\x88\x8d\x4d\xae\x5c\xdb\xd3\x59\x96\x6b\xfb\x47\xd9\xe0\x71\ -\x25\x66\xa8\xad\x1e\x33\xfe\x3e\x0f\x68\x9c\x30\x39\x2a\xd5\x4f\ -\xa5\x8f\xb8\x03\xe4\x46\xc8\x30\x07\x39\x66\xdc\x43\x1d\xe9\x78\ -\x60\x1d\xf4\x70\xc7\x87\x0e\x37\xb3\x81\x0f\x7c\x7c\xfa\x0c\x74\ -\xf4\xa3\xd0\xd0\xda\x17\x9b\x37\x2f\x1c\xd0\x68\xc5\xe2\xe3\x80\ -\xfd\x9d\xef\x30\xbb\x18\x2e\x74\x0d\xb2\x91\xa1\x47\xfc\x98\x7b\ -\x19\x56\x2a\x1c\x94\xed\xae\xea\xa7\xdb\xd4\xb0\xd3\xf4\x18\xfb\ -\x1a\x35\x19\xe4\x0c\x6f\x14\xe6\x79\x76\x2f\x5e\x03\x38\x05\x8f\ -\x00\xc7\xae\x79\xa9\x04\xe2\x2d\x81\xce\xf0\x02\x13\x53\x71\xe6\ -\xca\x16\x90\x97\xf3\x02\x4d\xf7\x17\xe5\x1b\x34\x07\xff\x77\x1c\ -\xb5\xcd\x02\xef\x9e\x9d\x85\xb3\xdd\x86\x3a\x58\x56\x98\x24\xf2\ -\x0f\x13\xe4\x7b\xb1\xe7\x05\x57\x7c\xc6\x5d\x95\x16\xa7\xd0\x95\ -\x29\x28\x94\x7c\x78\x8b\x0c\xee\xd5\x32\x2e\xa5\x5d\x06\x8d\x9a\ -\xae\x17\x79\x96\x24\x97\x79\x14\xb6\x52\x54\x67\x35\x85\x35\x1d\ -\x05\xa1\x03\x2d\x11\xc3\x41\x15\xc6\xb1\xab\x5d\x17\xaa\x37\x4d\ -\xbc\x72\x03\x90\x74\xab\x8c\xde\xd3\x0b\x39\xc1\x92\x5b\xd3\xd5\ -\x29\xca\x28\x52\x8f\xaa\x91\x85\x93\x2b\x49\xbf\xc9\x74\x5a\xf7\ -\xd3\x2c\xe9\x55\x5e\x24\xaf\x03\xa7\xd0\x91\xec\xe1\x6e\xda\xa6\ -\x3f\xc3\xe4\xfc\x36\xb4\xd1\xe3\x25\xff\xfc\x41\x89\xd3\xaf\x20\ -\x4f\x9a\xd0\x31\x58\x9e\x34\xe5\x52\xb9\x5e\xc1\xdc\xb5\x98\x8d\ -\x42\x6c\x90\x7c\xc8\x7e\x69\x6f\xe9\x56\x45\x70\xf4\x89\xb7\x2a\ -\xcc\xc3\x8e\x46\x16\x99\x74\x81\x6c\xd3\x0e\xb6\x9b\xeb\x6c\x88\ -\x9b\xad\xc3\x74\x99\x44\x8a\x10\xdd\x6e\xc2\x78\xc9\x0c\x0f\xf8\ -\x9a\xbf\x73\x47\x5a\x2c\x77\x73\xb8\x4b\x11\x94\x22\xf5\xb3\x5e\ -\xe8\x30\x6f\xe3\x4b\xfb\x69\x2a\x24\xab\x09\x38\xcb\xb6\xf1\x9a\ -\xcd\x46\x9a\x97\xa2\x29\x29\x83\x89\x56\xa4\xce\x4a\x46\x5b\xc9\ -\xa2\xc0\x32\x22\x13\x4c\xd9\x72\xb9\xad\x6a\xfe\x3f\x9e\x6c\x8f\ -\x69\xa0\x3a\x0f\xb5\xce\x07\x35\x09\x6b\x04\x9c\xfc\xb5\x92\xed\ -\xe6\xc2\x27\x5b\x51\x58\x9a\xb1\x94\x0f\x6f\xae\x9f\x9c\x59\x71\ -\xc0\x50\x95\x9e\xd4\xea\x3c\x69\xab\xd2\x65\x76\x9f\xf6\xa7\xd1\ -\xea\x1c\xa9\x07\x2e\x8d\x0a\x65\x8d\x5a\xa9\x13\x73\xfc\x64\x8c\ -\xa2\xc6\xf6\x31\xca\x29\xd5\x5f\xa1\x78\x7d\xd7\x9f\x42\x59\x3e\ -\x69\x57\x2e\x21\x85\x42\xcd\x5a\xa9\x14\x53\xf9\xd4\xac\x0e\x34\ -\x3e\x77\xdb\xfe\x94\x59\x66\xdb\x1e\x18\x34\x6a\xb2\xdb\xd0\xdc\ -\x6d\x9f\x86\xc7\xdd\xb6\xda\x39\xe1\x0c\x51\xe4\x0f\xfb\x0c\xa5\ -\x89\x9a\x8e\x20\xde\xf1\x03\xe0\x53\xf1\x68\xa1\xeb\xa6\x45\x7a\ -\xd8\xd8\x2b\x6e\xb1\x70\x75\xb4\x63\xdd\x48\x0d\x5a\x40\x87\x29\ -\x67\xb0\xdd\xe8\x26\x57\x97\xa3\x2f\x25\xd9\x91\xe8\xb6\xe4\xe9\ -\xba\x16\xa3\x55\x36\x46\x55\xc5\x80\x41\x8a\x88\x34\xbc\x3a\xac\ -\x73\xb4\xfb\x40\xea\x4a\xcb\x30\x1d\xae\x14\x48\xf1\xfa\x4d\x25\ -\x59\x2f\x5d\xa1\x07\xf8\xd2\xb5\x88\x1b\xab\xf8\x7d\x12\xc6\x69\ -\x77\x3d\x0f\xa2\x12\x91\xb6\x47\xd6\x8b\x80\xdc\x4f\x39\x62\xd7\ -\xae\x1a\xba\x8e\xff\x8c\x7e\xce\x3b\x17\x10\xe8\xbe\x21\x82\xe8\ -\xb8\xcb\x07\x2a\x20\xc0\x98\x54\x84\x24\x27\x76\x59\xf3\x2e\x6c\ -\xe1\xab\x2a\x0f\x72\x8b\x59\x51\xb3\x0e\xaf\xcb\x10\xef\xdf\x77\ -\xad\xb7\x33\xd4\xdd\x7a\x8e\xb6\xbf\xc0\x0d\x4a\x97\xad\x0d\x38\ -\x67\x50\xa8\x57\xf1\x35\x24\x5e\xd6\x55\x36\x06\xab\x57\xe1\x98\ -\x78\x59\x3b\x10\x9a\x75\x07\xa7\x5b\x32\x3d\xd0\x94\x2f\xf8\xca\ -\x1a\xcb\x9f\xe7\xcb\xba\xd4\xb4\x48\x7b\xa5\x5c\x81\x83\xe7\x13\ -\xe5\x8a\xbd\x4a\xa8\x08\x4b\xb7\x2f\x26\x6f\xd0\xb9\x56\x3a\xc1\ -\x5b\xde\xda\x22\x27\x0a\x56\xb8\x10\x4b\x3b\xa4\x9a\x0a\x30\x0c\ -\xa5\xb5\x4e\x8d\x37\x5a\x7b\x55\x17\x08\x7b\x4f\x3c\x5b\x4b\xdf\ -\x10\xd4\x24\xb9\x6b\xff\x53\x79\x4b\xbb\xa1\x58\x73\x3b\x07\xaf\ -\xc9\x68\xcb\x10\xe9\x02\x66\x9b\x7d\x16\xf5\x70\x6a\x1b\xa7\x1d\ -\xee\xa8\x0e\x7b\x92\x54\xd3\xe6\x30\x9f\x30\x7b\x53\xb8\x92\xcd\ -\x4d\x55\xb7\x11\x0f\xdd\xf1\xf1\xc9\x41\x30\x1e\x8f\xc5\xd3\x24\ -\xf1\x92\xa5\x53\x0f\xb9\x90\x92\x78\x3e\x2c\x5f\x62\x92\xae\x88\ -\xea\x4f\xbb\xb8\xad\x64\x7c\xf2\x5c\x1f\x6d\x2d\xe9\x81\xd6\xf8\ -\xf8\x82\xcb\x07\x94\xc4\x87\xd7\x49\xb0\xc5\x51\x41\x0a\xb9\xa3\ -\x7c\xb1\x2b\x75\xb5\x57\x91\x68\x5c\x28\x72\x7b\x72\x35\x43\xf5\ -\xe1\xb8\x69\x0f\x1f\x70\xda\x6a\x23\x04\x9c\xc0\x62\x12\x3a\x56\ -\x41\x40\x0d\xd8\xe1\x86\x66\xc9\x2b\xa5\x71\x8f\xc6\xc0\xe1\x2f\ -\x15\x26\x5b\x75\x1e\x28\x63\x88\x5b\x91\xd2\x08\x61\x6c\x94\xad\ -\x56\x6e\x79\x2a\x2e\x7b\x16\x52\xb2\xeb\xb9\x0b\x0b\xfc\xd6\xbc\ -\xf7\x56\x02\x0c\x9b\x2c\xba\x1f\xcd\xda\x2a\x8d\xb5\x32\x38\x32\ -\xb4\x9f\xd2\xda\xaa\x7b\xe0\x46\x53\x6b\x76\x30\x20\x3b\xe2\xf6\ -\x37\x4c\xe6\xc6\x35\xf3\x34\x38\xdb\x26\xb6\x8f\xc9\x09\x5b\x3d\ -\x9e\x46\x27\x6c\x2d\xc3\xf0\xf9\x33\x26\xc3\xed\x17\xfb\x79\x7f\ -\x0d\xcf\x6b\x11\x29\x77\xee\xb8\x8c\xec\x35\x96\x22\x78\x2f\xdf\ -\x5c\xbf\x7f\x7b\xf9\x3f\xd7\x5d\x01\x53\x78\xbd\x10\xc7\xc1\xab\ -\xab\x57\x75\x86\xd7\x79\x19\xb3\xca\xc3\xcd\x20\x15\x94\xf9\xfa\ -\x5c\xbd\xd4\x5d\x15\x5d\x89\x61\x92\x58\x19\x28\x41\xef\x75\x85\ -\xd9\xed\xde\x8e\x9a\xfc\x82\xb7\x52\xae\xd0\x98\x2d\xa2\x4e\xab\ -\xd2\xbf\x4b\xca\x13\xcf\xee\x10\x93\x54\xc3\x81\x3b\x87\xba\x95\ -\x66\xcd\x34\x28\x57\xd7\xad\x34\xd0\xe3\x0b\xfe\xb3\x3d\xe8\x43\ -\xea\x1d\xa5\x8f\xc1\x44\x53\xed\x9e\x5f\x55\x5e\x27\xdc\xae\xe3\ -\x45\xd1\x21\x03\x12\xff\x0c\x62\x18\x02\x6d\x8f\x6c\x19\x3c\xee\ -\x27\x33\x0d\x81\x88\xa6\x46\x08\xf7\xe1\x1e\xf8\x29\x67\x1d\xc2\ -\xe7\xfe\xe6\xf1\x22\x4c\xa2\x14\x4d\x24\x3a\x6e\x10\x0e\x62\x1e\ -\x12\x6d\x56\xa6\x8c\xa2\x16\x81\xf5\x50\x08\x90\xc4\xe4\x17\x2f\ -\xdf\xed\x36\xf3\x6e\x6e\x7c\x20\xe9\x35\xb4\x79\xb0\x28\x87\x44\ -\x0a\xa3\x27\x79\xbd\xc7\x2f\x45\x20\x13\xed\xb8\x1d\xdb\x39\xf0\ -\x6d\x6b\x3a\x86\xda\x8e\xe5\xf9\x7c\x34\xbf\x16\x04\x25\x8a\x14\ -\xa3\x30\x89\xef\xd0\x64\x67\x81\x16\x8e\x64\x51\x58\x1f\xe1\x34\ -\x14\x3d\x81\xb7\x73\x26\x6d\xb6\x58\xef\xd2\x8f\x2e\x69\x70\x5a\ -\x5a\xc1\xd1\xaf\xe2\xb0\x4b\x81\xab\x77\xef\xe5\xd5\x07\x98\xfc\ -\x5f\xfd\x7e\x73\xf3\xeb\xbb\xce\x6b\x93\xe1\x16\x27\xef\x77\xc5\ -\xba\x7b\xf9\xa6\x1e\x06\x36\xa2\x63\xc0\xf2\x4d\x1c\x9b\x3a\xab\ -\x69\x35\x70\x95\x25\x8b\x63\xd9\xa1\x86\x1e\xbb\x39\xb7\x1a\xb6\ -\x60\xdd\x7e\x0e\xab\x78\xb5\xcb\x21\x91\xd6\x9f\x75\x1d\x4e\x3b\ -\xc7\x40\x4d\x02\x6f\x8e\x3d\xe8\x31\x6c\x68\x30\x4a\x94\xce\xe6\ -\xb4\xdf\xd3\xe9\xd9\xf9\xf3\x4b\x53\x84\xe6\x40\xd9\xca\x0c\xe8\ -\x89\x70\xa1\xdc\x85\x82\x19\xae\x95\x31\x92\xaa\x0d\x00\x1b\x96\ -\xb5\x8c\xbd\x76\x2c\xd5\xd2\x95\x2f\xe3\x30\xc9\xee\x2a\xd4\xa4\ -\xc6\xb3\x3c\x3a\x71\x19\xfe\xa2\xd8\x45\x38\x48\x4c\xf1\x75\x96\ -\xf3\x60\x14\x5c\xe3\xdc\x9b\x30\x09\x16\x61\x11\x05\xd9\x4a\xe8\ -\x55\xbf\x70\xb3\x24\x80\x8b\xaa\x5e\x79\x5d\x61\xfc\xf7\x37\xf5\ -\x11\x06\x9f\xae\x2e\x55\x2c\x69\x8e\xb2\x9e\xd6\x09\x92\x43\xb4\ -\xe1\x9c\x20\xc7\xe6\x13\x3b\xc1\xfa\xb4\x29\xe2\x8c\xa8\x40\x0a\ -\x4b\xb2\x7b\xf2\x22\xd8\x0e\x8f\x86\x2c\x4d\x1e\xe8\x2b\x2d\x2f\ -\xa3\x24\x7c\x88\x96\xef\xb3\xed\x6e\x8b\x9f\x02\x8b\x9a\xda\x13\ -\x1e\x50\x48\x25\x1d\xc2\xbf\x1d\x50\x0d\x27\x2e\x54\x30\x6f\xd2\ -\xa2\x0c\xd3\xb2\x82\x81\x0c\x0d\x26\x4e\x3e\x24\x7d\x4c\x3f\xcf\ -\x61\x7d\x34\x3f\xaf\xe2\x7c\x5a\x3f\x0f\xd0\xd3\xd5\x65\x03\x20\ -\x3d\x5d\x37\x00\xa1\x93\x0b\xe7\xe0\xf5\xc8\x5c\x7b\xa6\x7a\x62\ -\xe6\x3f\x5b\x3c\x96\x7e\x41\x43\xe9\xa7\x67\xc7\xcf\xfe\x97\x05\ -\x85\x5f\xf1\x28\x5c\xc9\x43\x4e\x3c\xa1\x16\x5e\xd0\x31\x01\x1e\ -\x43\x80\x65\x17\x01\xc3\x3e\x76\x01\x5e\x07\x55\xe1\xb0\x10\x9a\ -\x0a\xba\x01\x80\x8e\x80\xe4\x87\xe2\x1c\x8e\x05\xf9\xa3\x3c\x13\ -\xfa\x09\x24\x1c\xc1\xf1\x79\x48\x1d\x90\x84\x26\x5d\x4c\x19\xec\ -\xf2\xe1\xa2\x63\xa1\x51\x0d\x6e\xd7\x73\x34\x33\x10\xc8\x9d\xf8\ -\x03\x93\x26\x5b\x9d\x6e\xa1\x80\x27\x95\x41\x40\x8e\x60\x8f\x69\ -\xb8\x25\xb5\x95\x50\x70\x0a\x83\x62\x1d\xaf\x4a\x7e\x8e\x44\x90\ -\xd7\x1a\xad\x8c\x68\xc4\x65\x85\x5c\x93\xe6\x71\x89\x7a\xce\xd1\ -\xbf\x60\x70\xab\x78\xe2\x0a\x09\xf4\xcf\x8f\x09\x67\xbb\x43\x57\ -\x5d\x61\xfb\x17\xd9\x66\x13\xa6\xcb\xb7\x71\xfa\xb1\xcb\xac\x70\ -\x98\xad\x55\x85\x36\x8d\x97\xd6\x95\x21\xec\xba\x55\x65\x79\xdc\ -\xb2\xde\xb3\x95\xa9\xb4\xce\x05\x64\x72\xb5\x5b\x91\xbd\x8a\x13\ -\x2f\x34\xde\xbd\xff\xfd\xe6\x1a\xad\x2f\xde\xfd\x1a\xbc\x7e\xf3\ -\xea\xed\xcb\x96\x9b\x35\x83\xed\xd0\xbc\xc0\x55\x28\xbe\x82\x67\ -\x16\x06\xad\x86\xc1\x98\xd4\xb9\x53\xfb\xb5\x68\xd7\x17\x39\xbd\ -\x52\xd6\x90\x02\x84\x6f\x82\x9f\x82\x93\xb3\x1f\x83\x69\xf0\xcf\ -\x60\x7c\xf6\xc3\x24\xc0\xcf\xfc\xb2\xfb\xf9\x01\x4e\x4c\x6f\x16\ -\x14\xd5\x3b\xca\x24\x89\x0d\x97\x40\x64\xc5\x19\x4e\x2e\x9a\x36\ -\x75\x66\x2d\xc9\xb6\xdb\x6f\xd2\xed\xf8\xfb\xbf\xe3\xc3\xd3\x68\ -\x23\x13\xc3\x32\xf7\xf0\xa3\xca\x72\xba\xdc\xfe\xf8\x64\xd2\xa0\ -\x80\x52\xf7\x2c\x5d\xb8\xa5\xf2\xf3\x53\x8a\x44\xed\x72\xcc\x31\ -\xf2\x2e\x8a\x96\xd5\x77\x75\x59\x8a\x26\xbe\x8d\x44\x0c\xcc\x43\ -\x54\x0a\xd7\x14\x42\xf1\x32\x81\x3a\x73\xc9\xb8\x1f\xee\x66\x1e\ -\x36\xe2\x2c\xd3\x6c\xfb\xc1\x8c\x01\x74\x97\xbc\x1a\x13\x5c\x56\ -\x53\x06\x00\x2c\x15\x5b\xa0\x50\x7a\x79\x6e\x8b\xc2\xf2\x9a\x27\ -\xb1\x5e\x5e\x29\x4a\xac\x17\x8d\x87\x6d\xb4\x6d\xaf\xff\xee\x68\ -\x76\x72\x2c\x33\x11\xa3\x89\x7b\x7a\x10\x9a\x06\x1d\x86\x20\x5f\ -\x8d\xaa\x8d\xad\x70\xa5\x61\x9b\xa7\x03\x99\xb7\x3b\x9f\x1c\xe0\ -\x7f\x4f\x03\x34\x1f\x08\x7e\xf9\x0d\xff\x7e\x4e\xbd\xc6\x3f\xc4\ -\xed\x89\xe6\x07\xbe\xb4\x50\xfd\x10\xec\xf4\x8f\x7f\x48\xa3\xa6\ -\xf9\x51\x53\x7c\x64\x91\x31\x70\xf4\x57\x50\x34\xb8\x0e\x6c\x2b\ -\xa9\x2c\xf3\x6c\x3b\xc2\xd3\xcc\xf6\xbb\xa9\x62\xb6\x31\xbc\x16\ -\x32\xac\xfa\x14\x8a\x58\x92\xe2\x23\xa5\x49\x42\xa8\xd1\x10\x3d\ -\x08\xe0\x6f\xd8\xab\x56\xd0\x97\x9c\x3f\x68\x9b\x56\x49\xae\x55\ -\x21\x11\x75\x3d\xf5\x1f\xf5\x71\x87\x8d\xd0\x31\xcc\xed\x2c\x02\ -\x5a\xeb\xc2\x81\x12\x3b\x55\x07\xdb\x7b\x21\x75\xb3\x19\x02\x83\ -\x14\x65\xbc\x18\x6c\xb9\xea\xc5\x7d\x4b\xad\x68\x0a\xae\x26\x8c\ -\x47\xc3\x12\x3d\xfa\xcb\xc4\xee\xd4\xd4\x36\xdc\x81\x18\xe5\xea\ -\xb3\x39\x9a\x3f\x3e\x39\x26\xbb\x60\x07\xe7\x22\x10\xa7\xbb\xe0\ -\xee\x5c\xf5\xa0\x72\x80\xa2\x16\x7c\x59\x4b\x36\xc1\x8f\xdc\x18\ -\x75\x45\xbd\xa1\xec\x1d\x29\x93\xa3\x73\xb5\xa6\x83\x89\x53\xc7\ -\x52\x4e\x56\xf9\x4b\x73\x1e\x3d\x78\xbf\x3a\x42\x22\x18\x83\xcd\ -\xf7\x2d\xc7\x63\x22\x49\x4f\x29\x9a\x6b\x36\x75\x94\x61\xab\x4a\ -\x4c\x24\x17\x8d\x56\x5b\xec\xe6\xfc\x3b\x87\x24\xbc\x8f\x1a\x21\ -\x3a\x86\x49\x6a\x13\x4a\x4a\x9a\x17\x14\xc6\xeb\x69\x0d\x24\x3c\ -\xbf\x74\xbd\xa7\xe6\xd7\xdb\xe7\x36\x1b\x91\xed\xac\xd2\xae\x83\ -\x79\x6b\x36\x2f\x74\x69\x7c\x35\xb5\x7d\xac\xc7\x18\xac\xae\x97\ -\x49\x18\x20\x2f\x57\xc1\x7a\xe9\x96\xb9\xa6\x5c\x31\x35\xfd\xf5\ -\x26\x9c\xff\x11\x77\xba\x19\x4f\x7e\xba\x1f\xd9\x87\xf3\xaa\x16\ -\xc8\x08\x79\x01\xf2\xe7\x60\x37\xc5\x31\xc7\x86\x0b\xf7\xc6\x25\ -\xaf\x7c\x3b\x9b\xc1\x12\x9e\x61\xe3\x36\xa4\xce\xe9\xde\x8e\x29\ -\x3f\x9e\x42\x99\xcd\xb6\x61\x1a\x69\x2d\xc1\xa1\xa4\xa1\x34\x05\ -\x60\x84\x2c\xb3\x1d\x32\xfb\xba\x1b\x4d\xf3\x20\xc8\xee\xe3\x72\ -\x1d\x6c\x1f\x3e\x95\xa7\xf0\x1b\xf4\x20\x89\x76\xe3\x33\x4f\x15\ -\xc5\x08\x50\xdb\x61\x0f\x25\x0a\xfe\x66\x76\x88\x38\x46\xcb\xb4\ -\x97\xd9\xe2\x23\xb5\xa2\x5a\x0c\x44\xaa\x38\x49\x77\x8b\x82\xe1\ -\xc3\x68\x99\x87\xf7\x57\x61\x11\x49\x77\x0b\x6d\xda\xd7\xd6\x92\ -\x60\x67\x59\x95\x83\x26\x5b\x93\x74\xb7\x01\x67\x66\x54\x5b\xb4\ -\xf3\x07\xfc\x4d\x30\x62\x1b\x96\xf8\xa4\x0b\xbb\x7b\xee\xe4\x8a\ -\x90\x3b\x9b\x2d\x92\xac\x88\xea\x73\x3d\x90\x23\xb1\x89\x68\xe1\ -\xe2\x75\xc8\x63\x91\x74\xca\x9b\x63\x0d\x10\x82\x45\xbe\x60\x0f\ -\x50\xc0\xd6\xc8\x36\x52\x7d\x4e\xc4\x78\x1a\xc0\x9a\xe5\x20\x82\ -\x3a\x4b\xc0\x85\x16\xaf\x97\x08\x04\x6a\xea\x9e\x1a\x7a\x90\x95\ -\x6b\xd0\xa3\x6f\x98\x4b\xdb\x63\x83\x1e\x6f\x41\xb1\x48\xea\x67\ -\xf6\x04\x12\x03\xd4\x65\x00\x29\x2c\xcc\xf0\x3c\x87\x82\xe6\xef\ -\xba\x6a\x18\x83\xdb\xf3\xb6\xc9\xa6\x3f\x27\x8d\xeb\xb2\x24\x45\ -\xbb\x84\x0c\x46\x40\x0d\xde\x87\x66\x5d\x17\x81\x6c\x32\xe1\x1b\ -\x88\x66\xe2\x32\x7c\x28\x86\x3b\x08\xf4\xd6\x33\xc2\x81\x28\xae\ -\xa0\xfb\x90\xac\xe9\x21\xd0\x5c\xb9\xce\x81\x48\xc6\x0a\xdc\xf3\ -\x35\x65\xb5\x83\xcd\x96\x2d\x8f\xd1\x5a\x6b\x4a\x03\x86\xe9\x45\ -\xb5\xb6\x8f\xd1\x9a\xfb\xa4\x9a\x68\xd1\x8b\x66\x4d\x0f\x8b\x3d\ -\xf7\x49\x73\x05\xdd\x8b\x68\x5d\x17\xb3\x45\xf7\x49\xb4\x60\xa0\ -\xae\x86\x0c\xda\xef\x04\x24\x50\x7d\xee\xde\x6e\xa2\x1e\x96\xa9\ -\x1a\xa4\x91\x0c\x71\xd9\x6c\x33\x3b\x67\x6b\x03\xd4\x65\x24\x03\ -\xca\x26\xd3\x5b\x85\xbb\xfd\x40\xc6\x6e\x24\x84\x7f\xd7\x19\xb4\ -\x0d\xb3\x45\xb8\xac\x32\xc0\x17\xa4\xbd\x36\x22\xc0\xed\x12\xdd\ -\x46\x88\x54\x69\xc7\xec\x67\x1d\x8a\x86\x48\xbb\x21\xf8\xfb\xea\ -\x51\x19\xcd\x82\x11\x9c\xc4\x38\xce\x75\x5c\xb2\x5b\x0d\x13\xa0\ -\xd3\x8b\xcb\x57\x17\xc3\x31\xd3\x78\x29\xd3\x1c\x5d\xd3\xda\xbe\ -\x8b\x62\x8c\x87\x4d\x23\xb6\x72\x2e\xb6\x0f\xb8\x35\x5a\x2f\x1f\ -\x55\xbf\xee\x5f\x3c\x3f\x3b\x23\x53\xe0\xfd\xc9\xf4\x04\xdc\xf1\ -\x3a\x81\x0d\xed\xc4\xe8\x97\xac\xde\xc8\x18\x14\xcd\xcf\xd3\x3e\ -\xdd\x38\x31\x94\xc1\x99\x82\x4d\x20\x43\x01\x86\x9b\x75\x32\xed\ -\x3e\x87\xf6\x18\x0e\xca\xc4\x5a\x19\x0b\xdd\x18\x75\x98\x56\xd9\ -\x06\x05\xdc\xc1\x63\x5c\x28\xd3\xad\xa7\x19\x14\xb8\x93\x25\x30\ -\x7a\x84\x05\xd0\x56\xe1\x31\x20\x04\x4d\xc9\xda\xe5\x21\x20\xde\ -\xca\x72\x76\x88\x26\x23\xe1\x53\xd6\x74\xa6\x2e\x2c\xa9\x5c\x97\ -\x5e\x1e\x66\x0e\xac\xc7\xa8\xa1\x5b\xa7\xd0\x36\xfb\x84\x9a\x7b\ -\x58\x27\x30\xb5\x06\xec\x73\x19\xaf\x56\x11\xa9\x1c\x36\x8f\xd6\ -\xe1\xe7\x38\xcb\x71\xd5\x4d\x96\x15\x28\xcc\x8e\xe4\xd7\xb8\xeb\ -\x8f\x85\x92\x5b\xca\x5c\xc8\x36\x57\xfa\xaa\x4d\x13\x76\xb1\xae\ -\x6e\xd8\x66\x9c\xe2\xe2\xd9\x79\x95\xed\x61\x9e\xea\xd2\x5b\x6f\ -\x9d\xf2\xca\xc7\x66\x9e\x60\x7b\x0f\xfb\x54\x17\x51\x6d\xcd\xb3\ -\x82\x24\x5b\x27\xff\x29\xcf\x2d\x7f\xf9\x12\xde\x53\x56\xae\x2d\ -\x72\xa7\x14\x27\x67\x0e\x05\x69\xdd\x1e\x1e\x04\xd0\x19\xb7\x38\ -\xa1\x86\xf6\xd1\x63\x43\x65\xd0\xb3\xbe\xb9\xf3\x1d\x14\x15\x0e\ -\x71\x6b\x75\x86\x55\x94\xea\x97\xe3\xb6\x4e\x3e\x89\x59\xc2\xbb\ -\x1b\x4e\x94\x19\x77\x0a\xac\xbd\x7c\x69\xd3\x3d\x99\x09\xa1\xe3\ -\x1e\xd0\xf4\x90\x1f\xd0\xcb\x87\x48\xa0\xe4\xad\x15\x8d\x87\x08\ -\xa1\x6e\xde\xe4\x69\x84\x88\x8f\xcc\x2a\xfc\x9d\xcf\x6e\x07\x39\ -\xdc\xe2\x64\x43\x38\x66\xd7\xcb\x34\xc7\x99\xfd\xbf\xfd\x58\xc6\ -\x65\x12\xcd\xc3\x7c\x54\x9d\xa0\x60\x01\x9b\xaa\x35\x37\x39\xad\ -\x5c\x6a\x26\x83\x91\x66\xf9\x26\x4c\xda\x00\xa9\x6f\xea\x33\x71\ -\xa0\x28\x83\x81\x32\x0f\x7c\x55\xdd\x1c\x23\x37\x1e\xf0\xf9\x5a\ -\xf5\x2d\xbe\x04\x21\x9d\xc6\xd2\xe9\x33\xab\x38\x2e\x3f\x7c\xd0\ -\x64\x57\x5b\xfd\x26\x4f\x8e\x7a\x2e\x87\x99\x1a\x61\x82\x4c\xf7\ -\x05\x4d\x05\xfd\x39\x02\x6a\x4b\xd7\x5d\xa2\x32\x1e\xfd\x55\x7f\ -\x76\x38\xf8\xd3\xb1\xd9\xeb\x99\x9e\x16\x49\xdf\x87\x75\x3c\xa2\ -\x55\x92\x85\xe5\xdf\x5f\x69\x08\x19\x62\xca\x91\xcf\x16\x5a\xab\ -\xe0\x5b\xd5\x26\x60\x69\xa3\xb6\x1a\x0f\xa8\x37\x92\xdc\x90\x47\ -\x11\x7d\x11\xb8\x28\xab\xdf\x6e\xb0\x57\xf7\xab\x49\xd8\x3d\xb9\ -\x01\xd1\xf1\x19\xa1\xec\x9c\xe0\x56\x94\x3d\x80\x29\xb1\x04\x2a\ -\x38\x43\xa4\x57\xd4\x32\x9f\xcd\x91\x19\x2f\xd6\x42\x3d\x49\xe9\ -\x2b\x4d\x16\x63\x0b\x3f\xaf\x40\x0e\x0b\x34\x28\xe7\x28\xf4\xdd\ -\x15\xb3\xbd\x70\xf9\xdf\x2c\x4e\x8b\x51\x73\xcf\xa3\x8e\x5d\x36\ -\x33\xab\xa0\xdd\xe2\x08\x5a\x21\xe4\xef\x9d\x9b\x50\x76\xc5\xb8\ -\xc9\x72\x3b\xc6\x3d\x8c\x72\xb1\x8e\x93\x25\x92\x48\xf5\x57\x6f\ -\x04\x44\xe9\xd2\x89\x63\x0d\x7a\xe2\x4f\x21\x95\x57\x5f\x88\x5d\ -\xf9\x9e\x10\xad\xce\x0f\xc7\xd7\xb4\x57\x38\x2c\x16\x92\x6d\x6b\ -\xcc\x30\x07\x00\xe9\x6a\x8f\xbe\x09\xc7\x18\x1c\x0c\xdb\x28\xf3\ -\xa6\xd0\xab\xa7\xe4\x7d\xdc\xbc\x20\x68\x38\xe3\xc6\x4f\xdc\x5a\ -\xaa\xcd\x42\x6f\x41\x33\x06\x68\xa6\x98\xbb\x4d\x56\xdf\xee\x3a\ -\x20\xe9\x9f\x55\x00\xd1\x7c\xcd\xa2\x8a\xe6\xfb\x17\x59\xb2\xdb\ -\xa4\x9a\x06\x6e\x0c\x90\xc6\xf3\xec\xcb\x6d\xdd\xcb\x9d\x7e\x55\ -\xba\x40\x1b\x22\x13\x4b\x1b\xba\x9f\x60\x96\x47\x8d\xce\xd2\xa8\ -\xc2\x67\x69\xc4\x21\x34\x49\xb8\xc1\x68\x6c\xc5\x50\x1a\x5b\x71\ -\x38\x8d\x5a\x6b\x90\x9a\x9b\x31\xac\xe6\x66\x5e\xf3\x1f\xd9\x16\ -\x9c\x2d\x7a\x97\x5a\x6c\x5a\x68\x00\xca\x49\x68\x01\xf3\xc4\x9a\ -\x78\x72\xc3\xfa\xf9\x70\x62\xb4\xee\xa6\x95\xc9\xbe\x9b\x56\x16\ -\x0b\x97\x91\x5a\x9b\x19\xad\x1c\x44\x6b\x96\xb9\xc5\xd2\x01\xc4\ -\x96\x76\x56\x6b\x07\x50\xdb\x1a\x5a\x2c\x5e\x41\xde\xd6\x4a\x9c\ -\xad\x1e\xfd\x16\xa1\xd5\xfe\x26\xc6\x77\x60\x75\xda\x50\x1a\x81\ -\x92\x53\x5a\xc1\x3c\x0a\xcd\x3c\xf9\x13\xfa\xfa\x72\x67\x1c\x0d\ -\x62\x4b\xd3\x88\x10\x5b\x5a\x46\x05\x44\x80\x53\x53\xe3\xe8\xd0\ -\x92\x60\xd7\x8b\x65\x94\x68\x88\x70\x68\x6b\x1d\x2d\x1a\x32\x5c\ -\x1a\x5b\x46\x0d\x48\x48\x17\xcb\x32\x8e\x1e\x5e\x29\x82\x6c\x44\ -\x02\x5d\xae\xf3\x78\x17\xee\xb9\xcb\xe3\x25\x5e\x72\x19\xde\x10\ -\x04\x4f\xef\xa9\x19\xb3\xad\x62\xde\xb0\xf8\x0f\x1b\x45\xf3\x9f\ -\x72\x62\xef\xe1\xb6\x12\xa3\x86\xad\x7f\x79\x6a\xf8\x0f\x1b\x6a\ -\xf8\x4f\x39\x6a\xba\x5f\x38\x6a\xa8\x51\x47\x1c\x60\xfe\x90\x25\ -\xfa\xbd\xa9\xdb\x78\x14\x5c\x7e\x00\x76\x1f\xd2\x37\xfc\xe8\x93\ -\xbe\x12\x06\x04\xf7\x9d\x5d\x20\x20\x39\xec\x8c\x31\x5c\x94\xf1\ -\x67\x39\x1e\x68\x5a\xc8\xe4\x01\x4d\x14\x32\xa5\x36\x5d\xc9\xdd\ -\xb3\xd3\xbb\xe7\x40\xf0\x9e\x0b\xc5\x7b\x3c\xc9\x50\x71\x2d\x80\ -\x8b\xe7\xd3\xf1\xf4\xb5\x8e\x0b\xf9\x24\x58\x65\x02\x68\x21\xf3\ -\x00\x34\x51\x58\x00\x8f\x90\xd9\x31\xc8\xb1\xce\xe9\x38\x30\x84\ -\x89\x79\x91\xe5\x69\x94\xd3\x93\xa6\xa2\xba\xb0\xe6\xeb\x05\x85\ -\x17\xd6\x0c\x55\x81\xc4\x22\xbf\xff\x8a\x42\xf4\x6d\xc7\xd7\x54\ -\x7a\xd8\xcc\x5c\x13\x3a\x06\xdb\x3f\xe4\xd8\xb4\x9e\x46\x73\x7b\ -\xe3\x06\xb1\x4a\x7b\xe4\xe2\x06\xba\xb6\xae\x64\x43\x87\x57\xe5\ -\x5b\xbb\x9e\x15\xf0\x56\x33\xf2\xaa\x73\x57\xb1\xc5\xbf\x7a\x80\ -\xcf\x84\xc9\x87\xa4\x2a\x4d\x7d\x56\xc1\xa7\x7f\x01\xb4\xcc\x94\ -\xaa\x02\x42\xd2\x8b\x70\xf8\xc0\x52\x5e\xc4\x4f\x7d\x2e\x21\x2b\ -\x35\x60\xa4\x8c\x76\x0b\x85\xb3\xd9\x2a\xce\x0b\x9c\x1c\x64\x6d\ -\x88\x0b\x21\x8f\x32\xf1\xb2\xa7\xb5\x04\x8d\x0d\xaa\x68\x20\x9a\ -\x19\x01\x08\x44\xac\x38\x30\xa8\x8c\xe5\x17\x15\x5d\x44\xcc\x6a\ -\x02\x98\x05\xdc\x34\x03\xc5\xab\x7d\xcb\xd1\x05\xb3\xb7\x6c\xe5\ -\x2a\x41\xe4\xea\x7c\x56\x44\x41\x11\x95\x25\xd9\xaa\xfd\xae\xa2\ -\xeb\x88\x64\xd1\x1c\x55\xc9\x35\x47\xf2\xb8\xfb\x1e\x53\x8b\x22\ -\xe0\x7c\x77\xd7\x5c\xa0\xe3\x47\x74\x85\xa2\xe9\x46\xb2\x30\xb9\ -\x0a\x7a\x6e\x7e\x82\xed\x11\x5b\x72\x7c\x3c\x53\xd4\x5a\xbf\xdc\ -\xc8\x4b\x92\xbe\x43\xea\xe3\xf7\x9e\x94\x1f\xf9\xf9\x53\x56\x1b\ -\xff\xe9\xab\x4f\x92\xd2\xf8\x03\x15\x9f\xa4\x2c\xf2\x3e\x44\x2e\ -\x47\xa3\xfe\xad\x1f\x90\x35\x3c\x69\xe1\xa1\x05\x3c\xd1\x27\x6c\ -\xd5\x80\x9a\xeb\xac\xc3\x3c\x47\xd4\xf1\x22\x04\x47\xa5\x9b\xbb\ -\x11\x7a\x58\x97\x67\x6a\x89\x7a\xe0\x4a\x95\x41\x72\xda\x0b\x91\ -\x0e\x03\x12\x42\x25\x55\x13\x12\x50\xc9\x57\x8d\x5a\xa2\xd0\x18\ -\x94\x88\xc2\x63\x99\x0d\x80\x51\x32\x07\x9b\x5e\xda\x2b\x27\x13\ -\xfd\x8a\xb5\x1e\x42\x1f\xae\x49\x31\xd4\xcb\x3c\x0a\x59\x69\x09\ -\xa1\xc4\x84\x7d\x78\xd9\xd8\xc0\x4e\xe9\x35\x7e\xca\xf4\xeb\x79\ -\x52\x55\x03\xa3\xfa\xba\xea\x36\xc2\x45\x11\x9c\x5a\x2e\xa3\x32\ -\x8c\x93\xa2\x69\x5b\x94\x48\x24\x58\x5b\xab\x24\xbb\x3f\x5c\x64\ -\x9b\xa3\x4f\xbb\xa8\xc0\x61\xbe\x38\x1a\x4f\x4f\xcf\xc7\xd3\x8b\ -\x73\x0c\x86\x23\x79\x95\xe5\xa3\x35\xd9\x03\xfa\xdc\xec\x04\x0d\ -\xe1\x3b\x91\x32\xbe\x5b\x66\xe5\xf7\xc1\x61\xad\x93\xba\xd0\xe4\ -\x74\x8c\xeb\xd9\x4e\xce\xc8\xbf\xd5\xbd\x0a\xda\x82\x37\x39\xd8\ -\xdf\xe8\x1c\x18\xae\x71\x99\x05\x44\x54\xcd\x94\xe2\x5f\xb8\xb0\ -\x0c\xf4\x27\x31\x96\x1a\xe9\x7f\x48\xa7\xeb\x75\xb8\xe5\x5f\x14\ -\x70\x20\xc2\xb0\x04\x81\x40\x4f\x29\xe8\x4d\xf8\x85\x25\x9c\x3b\ -\xa4\x35\x69\x12\xde\x20\x14\xa7\x3c\x8a\x7a\x4e\xd0\x1e\x03\x29\ -\x89\xb8\x4d\x62\x92\xcc\xd7\xcd\x1e\x3a\x0f\xa6\xa2\xa6\x63\x90\ -\x18\xcf\x98\x74\xf0\xcb\x2c\x55\x51\x29\x48\x62\xaa\x79\x4e\x31\ -\xd0\x82\x60\xbe\xcb\x6f\xf5\x12\xaa\x9e\x8e\xb1\x07\x1d\x96\x92\ -\xc5\x52\x68\x06\x7a\x8b\xeb\x58\xe9\xf2\xa8\x6d\x62\x89\xdd\xcf\ -\x2d\x5d\x8c\x48\x73\x65\x05\x97\xb8\x9a\x13\x2f\x6c\x38\xa2\x6a\ -\xc8\x05\x12\x8f\xc3\x92\x94\xa0\x3a\xa8\x7e\xbd\x89\x37\xad\xea\ -\xae\x0d\x93\x78\xac\xa1\x8d\x48\xc2\xb5\xb4\x79\xaf\x25\xc9\x68\ -\xc9\xb4\x15\xb9\x6b\xa1\xa9\x94\x06\x96\x68\x33\xf6\x90\x2f\x5a\ -\x7a\x2d\xc5\xb9\xeb\x94\x63\xde\xe6\xa9\xf4\xaa\xe2\xb2\xbc\x00\ -\x5b\x55\x84\x66\xe0\x9a\x22\xbe\x32\xd8\xaf\xa6\xbc\x2f\x47\x2b\ -\x5b\xb8\xab\xc4\x3e\x76\xe5\x5f\x88\xaa\x46\x39\xca\x37\xec\xd6\ -\x0b\xf4\x25\x3d\x67\xd5\xb1\x04\x28\x5d\x07\x1b\x6c\xd0\x43\x65\ -\x61\x46\xb8\x5a\x7e\x5d\x1e\xd0\xba\x7a\xf7\x0e\x0b\x3b\xcf\xe9\ -\x92\x87\xc5\x63\xef\x48\xe9\xfa\x1a\xdf\x1b\xe7\x69\xeb\x5c\xbf\ -\x50\x00\xd6\xa5\xe8\x3e\x92\xda\xfb\x24\x2b\x3b\xbe\xc0\x4d\x7e\ -\x86\x90\x1a\x47\x1b\xdd\xc8\x7b\x8d\x26\xe7\x8b\x5d\x19\x24\xe1\ -\x3c\x4a\x0a\xfc\xa0\xdd\x16\x35\x22\x37\xe9\xa6\xda\x32\x7a\xff\ -\x0f\x59\xf9\x35\x4a\ -\x00\x00\x04\x5f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x11\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x68\x1d\x55\x1c\xc5\x7f\x67\xf2\x90\x14\x95\xa2\xa8\x1b\ -\x51\x57\xa2\xb8\x11\x69\xc9\x47\x45\x49\x45\xab\x55\x0c\xcd\x7b\ -\xa5\xae\x44\x2a\x8a\x76\x21\x2a\x28\x82\x0a\xb1\xb4\x62\x05\xc1\ -\x85\x88\x16\x04\x71\x61\xd1\x90\x2f\x03\x5a\x8d\x4a\x2b\x48\x9b\ -\x3c\x6d\x69\x41\x5c\x14\x44\x5c\x28\xa2\x60\x54\xb0\x46\x9b\x37\ -\xc7\xc5\x6b\x64\x66\x5e\xc1\x44\xe6\xe3\x5a\xdf\x59\x9e\x03\x73\ -\xff\xf7\x77\xef\xdc\xb9\x77\xe6\x3d\xe8\xaa\xab\xae\xfe\xcf\x52\ -\xd5\x05\xac\x54\x7d\x13\x1e\x55\xe4\xa7\x65\x2b\x76\xb4\xbb\xd9\ -\xd0\x33\x79\x5c\xf7\x3f\x01\xa0\x7f\xc2\x1b\x89\xfc\x31\x3e\x5d\ -\xaf\x1d\xcf\x37\x7a\x7a\xf2\xb8\x76\x94\xc7\x45\x8a\x54\xdf\xb8\ -\xd7\x23\xcf\xfc\xdd\x79\x00\x29\xb7\xba\x83\x06\x30\x38\xee\xab\ -\x15\x79\x3f\x70\x5e\xd2\x37\xc4\x79\xb5\x11\x2c\x80\x75\x63\xbe\ -\x3c\x8e\x3c\x0b\x5c\x94\xcd\x04\xce\xab\x9d\x20\x01\xdc\x30\xe6\ -\x8b\x6b\x35\xcf\x02\x97\x15\xdd\x56\xad\xe8\x06\x56\xab\xeb\xdf\ -\xf1\xf9\x7f\xc6\x7e\x0f\x73\x55\x19\xed\x05\x35\x03\x86\x5e\x77\ -\xef\x52\xcb\xd3\x98\xf5\x49\xdf\x39\x4e\xf9\xac\x82\x01\x30\x74\ -\xc0\xb5\xc5\xb5\xde\x07\xdc\x94\x0a\x84\x95\xe3\xa2\x97\x55\x18\ -\x00\x6c\xfd\xbe\x10\xef\x35\x8c\x64\x13\x5c\x5c\xe7\x21\x10\x00\ -\xfd\x53\xf1\xf3\xa0\x7b\x53\xa6\x30\x05\x8e\xfc\xb2\x2a\x07\x30\ -\x30\xe9\x27\x40\x8f\x27\x3d\xb7\xef\xfa\xc2\x3b\x0f\x15\x03\x18\ -\x98\xf4\xfd\xc6\x7b\xb2\xbe\x14\xb5\xca\xaa\xa1\x32\x00\xfd\x53\ -\x6e\x18\xbf\x9a\x32\x0d\x36\x31\x2e\x6c\xd1\xef\x50\x25\x00\x06\ -\xc6\x7d\x33\xf6\xbe\x6c\xfb\x16\xb1\x54\xdc\x23\xef\x4c\x2a\x1d\ -\xc0\xe0\x94\xfb\x2c\x4f\x03\xe7\x24\x7d\x9b\x38\xcf\x2d\xee\x4a\ -\x55\x2a\x80\xfe\x69\x5f\x13\xdb\xfb\x11\xe7\xa6\x02\x97\x3f\xf2\ -\xcb\x2a\x0d\xc0\x86\x09\x5f\x41\xec\x59\xe0\xc2\x74\xa2\x98\x8a\ -\x3a\x0f\x25\x9d\x05\x36\x4c\xfa\x92\x16\xfe\x10\xb8\x34\x9d\x28\ -\xa6\xcc\x15\xef\x0c\x2a\x7c\x06\xac\x1b\xf3\xda\x25\xf9\x7d\xe0\ -\xca\x54\x20\xbb\xea\xce\x43\xc1\x33\x60\x70\xcc\x6b\xe2\x9a\x67\ -\x30\xd7\xa5\x02\x61\xac\x52\x36\x3a\xff\xa4\xc2\x66\xc0\xd0\x01\ -\xd7\xe2\x9a\xdf\x02\x6e\x4c\xfa\x2e\x61\x7f\xbf\x1a\x15\x03\x60\ -\xd4\xd1\xe2\x42\xfc\x1a\x30\x9c\xf2\x0b\x3e\xd9\xfd\x1b\xe5\x0f\ -\xc0\xd6\xc0\xb5\xf1\x0b\x46\xf7\x64\x93\x90\x46\x7e\x59\xb9\x03\ -\x18\x98\xe2\x49\xa3\x47\x53\x66\x7b\xad\x0b\xae\xf3\x90\x33\x80\ -\xbe\x49\x3f\x68\xbc\xbb\x23\x90\x4a\x3b\xdc\xac\x56\xb9\x01\xe8\ -\x9b\x6c\xed\x11\x7e\x25\xeb\x3b\xc0\x69\x9f\x54\x8e\x33\x20\xf3\ -\x42\x83\xf6\xfb\xfb\xaa\xb6\xb8\x2b\x55\x6e\x00\x04\x9d\xd3\x3c\ -\xe8\xae\xb7\x95\x1f\x00\xe9\x61\x32\x5d\x96\x88\x42\xff\xfc\x98\ -\x1b\x80\xb9\x11\x8d\x81\x1e\xea\x4c\x9c\xcb\x47\xcc\xa2\x94\xeb\ -\x53\x60\xbe\xae\x97\x41\xa3\x9d\x49\xb8\x10\x72\xdf\x07\xcc\x8f\ -\xb0\xcb\xf2\x4b\x69\x57\x20\xa2\x10\xef\x86\xfc\x77\x82\x92\x9b\ -\xc7\xa2\x47\x8c\xdf\x4c\xf9\x46\xb8\xfa\xb7\xd0\x59\x15\x53\xd0\ -\x4e\xc5\xad\x1f\xa3\xed\xc0\xbb\x99\x44\x28\x2c\x08\x85\x15\x73\ -\xe4\x01\x9d\x5a\xaa\x69\x1b\xf0\x69\x2a\x68\xff\xd0\x21\x18\x08\ -\x85\x16\x72\x64\x58\x27\xff\x90\xee\x04\x8e\x67\x22\x19\x07\x01\ -\xa1\xf0\x22\x8e\x8d\xe8\xe7\x78\x49\xb7\x19\xbe\x4a\xfa\x42\x32\ -\xaa\x7c\x59\x2c\x65\x14\x3e\xdb\xa6\xef\xa9\xe9\x16\xe0\xbb\xa4\ -\x2f\x1c\x55\x0d\xa1\xb4\x69\xd8\x1c\xd6\xd7\x2d\x74\x2b\xb0\x90\ -\xf4\xd5\xbe\x15\x2a\x83\x50\xea\x7d\xf8\x79\x5d\x5f\x18\xdd\x01\ -\x9c\xcc\xd6\xe1\x8a\x20\x94\xbe\x10\x35\xeb\x3a\xec\x58\x75\xe0\ -\x54\xd2\x17\x44\x76\xf9\x10\x2a\x59\x89\x9b\x5b\xf5\x81\xac\xbb\ -\xc9\x1e\x9e\x2a\x80\x50\xd9\xa3\x68\xae\xa1\xb7\x6d\xed\x48\x99\ -\x5a\x3e\x41\x96\xa7\x4a\x9f\xc5\xcd\x86\xf6\xda\x7a\xaa\x23\x70\ -\x79\x87\xa7\xca\x37\x23\xcd\x3a\xcf\x09\xbf\x98\x32\x75\xfa\xf0\ -\x54\x82\x2a\x07\x80\xe4\xb9\xe3\xd1\x63\xc2\x6f\xa4\xfc\x92\xb6\ -\xcc\xd5\x03\x00\xd8\xa9\xb8\xf7\x82\xe8\x3e\x60\x26\x93\x14\x7e\ -\x78\x0a\x03\x00\x70\x70\xa3\x96\xd6\xfc\xa2\xbb\x0c\x9f\xa4\x02\ -\x23\x17\x58\x67\x30\x00\x00\x0e\x6e\xd7\xa2\x7a\x35\x0c\x1c\x4d\ -\xfa\x2a\x70\x93\x14\x14\x00\x80\xf9\xdb\xf5\x6b\x0f\xda\x0c\x9c\ -\x28\xa3\xbd\xe0\x00\x00\x1c\xaa\xeb\x87\x1e\x6b\x13\xf0\x6d\xd1\ -\x6d\x05\x09\x00\xe0\x50\x43\xdf\x10\x69\x13\xf0\x53\x36\xcb\xf3\ -\xdc\x10\x2c\x00\x80\xf9\x2d\xfa\x32\x92\x36\x63\x7e\x4b\xfa\xca\ -\xb1\xee\xa0\x01\x00\x1c\x1e\x51\x53\xd6\x96\xcc\x0f\xa9\xce\xfe\ -\xbf\xcc\x24\x35\xb7\x55\x1f\x61\xed\xa2\xfd\xf9\xad\x85\xf4\x6c\ -\xd5\x35\x75\xd5\x55\x57\x67\x87\xfe\x02\x8f\xb0\x51\x56\xec\xcd\ -\x17\x8d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x88\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3a\x49\x44\x41\x54\x58\x85\xed\ -\xcd\xb1\x11\x00\x10\x00\xc0\xc0\x30\x99\xc6\x04\x56\x30\x96\x15\ -\x2c\xe0\xdc\x59\x4d\xa5\x55\x6a\xe4\xab\x74\x01\x49\x92\x7e\x17\ -\x4e\xe4\x52\x17\x90\x1e\x4d\xe7\xe8\x2d\x03\xc4\x17\x43\x49\x92\ -\xa4\x9b\x0d\x00\xac\x05\x04\x1d\x7e\x88\x63\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\xbb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x6d\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x6f\x13\x31\x18\xc6\x9f\xf7\x2e\x15\x13\x08\xa6\x22\x35\ -\xc4\xbd\x88\x05\x06\x40\x82\x85\x1d\xca\x00\x62\x80\xa1\x0b\x12\ -\x7f\x01\x1f\x1b\xb4\x03\x08\x24\x3e\xc4\xc4\xc7\x5f\x80\xc4\xd2\ -\x01\x06\x04\x03\x85\x9d\x05\x24\xca\xd0\x6e\x77\xe7\x24\x1d\x60\ -\x00\xc4\x56\x91\xe4\x61\x48\x24\x2e\x77\x17\x68\xe3\xbb\xb8\xa5\ -\xfe\x6d\x7e\xfd\xc6\x79\xfc\xc4\x67\x5b\x39\x1b\x70\x38\x1c\xdb\ -\x19\x59\x4f\x12\xc9\x8a\xd6\xad\xb3\x14\xce\x0a\xe4\x18\x80\x29\ -\x00\x3b\xca\x95\xb6\x61\xd6\x00\xac\x12\xfc\x20\x94\x05\xa5\xaa\ -\x2f\x45\xa4\xfd\xaf\x0f\xfd\xd3\x00\xad\xf5\x49\x42\x1e\x01\x72\ -\xa0\x10\x99\xe3\x63\x59\xd0\xbd\xaa\x94\x7a\xfb\xb7\x24\x6f\x58\ -\x05\x49\x89\x1b\xad\x79\xc2\x5b\xdc\x82\x9d\x07\x80\x83\x84\xb7\ -\x18\xe9\xd6\x1c\xc9\xa1\x3f\xf4\x50\x03\x74\x73\x75\x0e\xe4\x9d\ -\x72\xb4\x8d\x0f\x01\xef\xc6\x8d\xd5\xeb\xc3\xeb\x73\xe8\x0d\x7b\ -\x6f\x31\x15\xfe\x0e\xe2\x06\xd0\x79\xad\x94\x6a\x88\x48\xa7\x50\ -\xa5\x86\x90\xf4\xb5\xd6\x35\xc0\x3f\x0d\xc1\x6d\x00\x7b\x92\xf5\ -\x82\xee\x4c\xde\xe3\x90\x31\x80\x64\x45\x37\x9a\x9f\x07\x87\x3d\ -\xdf\x75\x3b\xed\x0b\xf5\x7a\xfd\x4b\x09\xda\x0b\x27\x0c\xc3\x49\ -\xcf\xaf\x3c\x03\xe4\x44\x22\xbc\xac\x6a\xd5\xc3\xe9\x89\x31\x63\ -\x40\x1c\x37\xcf\x41\xf0\x3c\x11\xfa\xd6\xfe\x35\x71\x60\xff\xfe\ -\xbd\x5f\xcb\x12\x5c\x06\x3d\x13\x26\x56\x90\x1c\x09\xc4\xf9\xe9\ -\xe9\x7d\x2f\x92\x79\x99\x39\x80\xc2\xd9\xc1\x00\x6e\x6e\xb5\xce\ -\x03\x40\xbd\x5e\xff\x22\xc0\xcd\x64\x2c\xd3\x37\xe4\x18\xd0\x5f\ -\xe7\x13\x74\x5e\x17\x2d\x6e\x5c\x90\x9d\x57\xc9\xb2\x40\x8e\xa6\ -\x73\xf2\x56\x81\xa9\x64\x41\x29\xd5\x28\x58\xd7\xd8\xc8\xd1\x5e\ -\x4d\xe7\xe4\x19\x30\xb0\xc3\xdb\x6c\xb3\xfd\x46\xc8\xd1\x9e\xd9\ -\xbd\x0e\xdd\x07\x6c\x17\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\ -\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\ -\xd8\xc6\x19\x60\x5b\x80\x6d\x2a\x45\x34\x12\x36\x1a\x33\x1e\xe4\ -\x01\x88\x43\x58\xe7\xbb\x06\x03\x08\x60\xa9\x2b\xbc\x56\xaf\xd5\ -\xd2\xff\x5b\x6e\x18\xe3\x11\x10\xe9\xd6\x45\x8f\xf2\x06\xc4\x61\ -\x94\xdf\x79\xf4\xbf\xe3\x88\x47\x79\x13\xe9\xd6\x45\xd3\xc6\x8c\ -\x0c\x88\xa2\x68\xb7\x80\x4f\x4c\x45\x8c\x8a\x80\x8f\xa3\x28\xda\ -\x6d\xd2\x86\x91\x01\x22\x95\xe3\x00\x76\x9a\xb4\x61\xc8\xae\xbe\ -\x86\x91\xd9\xf6\x93\xa0\x91\x01\x64\xfb\x3d\x80\x9f\x05\x69\x19\ -\x85\x9f\x7d\x0d\x23\x63\x64\x40\x10\x04\x3f\x08\xb9\x6c\xd2\x86\ -\x09\x84\x5c\x0e\x82\xe0\x87\x49\x1b\xc6\x8f\x40\xa0\xaa\x4f\xbb\ -\xc2\x53\x00\x3e\xa1\xb7\x44\x95\x0d\x21\x58\xea\x0a\x4f\x05\xaa\ -\xfa\xd4\xb4\xb1\x42\xf6\x01\xfd\xf5\xd8\x78\x4d\xb6\x81\x9b\x04\ -\x6d\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\ -\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\ -\x03\x72\x62\x6b\xc9\x02\x49\x7f\x4c\x5a\x0a\x27\x47\xfb\x5a\x3a\ -\x27\xcf\x80\xd5\x64\xa1\x77\xfc\x74\x6b\x92\xa3\xbd\x95\xce\xc9\ -\x1e\x94\x04\x3f\x0c\x46\xfc\xd3\x85\xaa\x1a\x23\x22\xfe\x99\x64\ -\x99\xe0\xc7\x74\x4e\xf6\xa0\x24\x65\x61\x30\x80\xdb\x61\x18\x4e\ -\x16\xae\xae\x64\xc2\x30\x9c\x24\x70\x2b\x19\xcb\xf4\x0d\x39\x06\ -\x28\x55\x7d\x09\x70\x25\x11\xda\xe3\xf9\x95\x67\x5b\xc9\x84\x3f\ -\x87\xa5\x07\x4e\x8c\x2f\xf7\xfa\x36\x48\x76\x04\x88\xb4\x05\xbc\ -\x92\x8a\x9e\xf0\xfc\x89\x15\xad\x9b\x97\xe2\x38\x0e\x36\xe3\xc4\ -\x48\xd2\x8f\xe3\x38\xd0\xba\x79\xa9\x77\x48\x7a\xe0\xa4\x38\x04\ -\xdd\xab\x79\x57\x68\x86\xbe\xca\x8a\x1b\xad\xf9\xff\xe1\xc2\x04\ -\x00\x10\x32\x1f\xa8\xea\xbd\xbc\xba\xa1\xfb\x00\xb5\x6f\xea\x1e\ -\x21\xf3\xe5\xc9\x1a\x0b\x24\x30\x37\x5d\x9b\xba\x3f\x2c\x61\x9d\ -\x97\xa6\xbc\x87\x00\x0e\x16\x2a\xad\x7c\xd6\x75\x69\x6a\x94\x6b\ -\x73\x47\xd1\x3b\x75\xbd\x19\xaf\xcd\xb5\x08\x7e\xdc\xc8\xb5\x39\ -\x87\xc3\xb1\xbd\xf9\x0d\x9c\xbe\x20\xb7\xf5\xf6\x9b\x02\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xdc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x8e\x49\x44\x41\x54\x58\x85\xed\ -\x97\x41\x4a\xc3\x50\x10\x86\xbf\x79\x71\xab\x0b\x45\x5d\xd8\xd6\ -\x92\x4b\x28\x28\x5e\xa0\x5e\x41\x0f\x20\xe8\x4a\xd4\x23\x58\xc1\ -\x85\x15\x3c\x88\xd0\x0b\x08\x82\x5e\x22\xe6\x25\xcf\x85\x8a\x82\ -\x74\x9d\x8c\x0b\x1b\x91\x36\x46\xac\xa9\x0a\xe6\x5f\x0d\xf3\x86\ -\x37\x1f\x33\xc3\xe3\x0d\xfc\x77\xc9\xa0\xc3\xda\xdb\x95\x94\x64\ -\x5f\x54\x96\x11\x66\x4b\xc9\xa2\x3c\xa8\xe8\x95\xc1\x6b\x2f\x2e\ -\x2e\x5c\x7e\x08\x10\x86\xd1\x2e\x22\x47\x79\x60\x25\x29\x45\x75\ -\xaf\xd9\x6c\x1c\x0f\x01\x58\x6b\x57\x15\x73\x01\x3c\x0b\xb2\x63\ -\x8c\x76\xeb\xf5\xfa\x53\x19\x59\xe3\x38\x9e\x4e\x53\x69\x29\xda\ -\x01\xa6\x04\xb3\x36\x58\x09\x6e\x6c\x74\x1e\xda\x58\xad\x75\x1b\ -\x65\x24\xcd\x93\xb5\x6e\x33\xb4\xb1\xde\xd8\xe8\x3c\xf3\x99\xcc\ -\x10\x95\x65\x00\x63\xb4\x3b\x2e\x00\xcf\xa3\x0b\x20\xc8\xd2\x10\ -\x40\x36\x70\x65\x95\x3d\x4f\xb5\x5a\xed\xb1\x6f\xce\x0d\x03\xfc\ -\x92\x2a\x80\x0a\xe0\xd7\x01\x26\x3e\x0b\x08\xa3\x68\x0b\x95\x43\ -\x60\xf2\x8b\x77\xf7\x10\x3d\x68\x36\x1a\x67\x45\x41\x85\x15\x08\ -\x82\x60\x1e\x95\xd3\x11\x92\x03\x4c\xa2\xd2\x09\x82\x60\x7e\x64\ -\x80\x9f\x50\x21\x80\xef\xfb\x77\x88\x6e\x03\xbd\x11\xee\xee\x21\ -\xba\xe3\xfb\xfe\x5d\x51\xd0\xa7\x33\xd0\xef\x61\x61\x1f\xbf\xa3\ -\xbf\xdd\x82\x0a\xa0\x02\xf8\x59\x00\xe5\x01\x5e\x3f\x90\xe3\x4a\ -\xe6\x9c\x9b\xe9\x9b\xf7\x43\x00\x2a\x7a\x05\x90\xa6\xd2\x1a\x17\ -\x40\x92\xd0\x02\x50\xf4\x3a\xf3\xbd\x3d\x44\x06\xaf\xad\xa4\xeb\ -\x8a\x76\xac\x75\xe2\x79\x74\xdf\xfd\xe1\xbe\x25\xe7\xdc\x4c\x92\ -\xd0\x52\xf4\x04\x48\x0d\x5e\x3b\x3b\xcb\x5b\x4c\xda\x8c\x6f\x36\ -\x3e\x5e\x4c\x32\xbd\xad\x66\xaf\x5f\xe7\xb9\xc1\xf3\x11\x75\xaf\ -\xe8\x75\xde\x6a\x56\xe9\x05\x72\xdf\x93\xde\xaf\x9f\x93\x4c\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x05\x36\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xe8\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x4c\x1c\x55\x1c\xc7\xbf\xbf\x99\x59\x4c\x7a\x21\x55\x1a\ -\x52\x69\x7a\x71\x9b\x88\x21\xa9\x48\x6f\xbd\x6c\x5c\x81\x43\x2b\ -\x91\xc0\x46\x8d\xd0\x34\xd9\x8d\xbd\x7a\xb1\x07\x12\x59\x20\x31\ -\xa6\xf5\xe4\xcd\xe8\x12\x1a\x25\x9a\x66\x5b\x30\x84\xc6\x00\x62\ -\x36\x2d\x7a\xa2\x92\x18\x5d\x2e\xc5\x03\x61\x0f\x18\x6c\xc3\xa9\ -\x59\xd8\x99\x9f\x07\xf6\xc9\xec\xec\xec\xce\x2c\xf3\x67\x07\xd9\ -\xcf\xed\xcd\xfc\x66\xde\x6f\xbe\xf9\xfe\xde\x7b\x33\x79\x03\x34\ -\x68\xd0\xe0\x24\x43\x76\x82\x22\x91\xa4\xa2\xb4\xe4\xfa\x88\xf1\ -\x2e\x80\x4b\x00\xda\x00\xbc\xe0\x69\x66\xb5\x93\x07\x90\x03\xb0\ -\xca\x84\xbb\x85\x9d\xb6\xb9\x4c\x66\xbc\x60\x75\x91\xa5\x00\x3d\ -\xfd\x89\x6e\x96\xf0\x05\x80\x76\x17\x92\xf4\x11\xca\x92\xc6\x1f\ -\x2d\xce\xa6\x96\xaa\x45\xc9\xd5\xee\xd0\x3d\x98\x18\x01\xe1\x0e\ -\x80\x33\xae\xe6\xe6\x0f\x67\x40\x18\x0e\xb7\x77\xee\x6d\xac\xaf\ -\xfd\x52\x29\xa8\xa2\x00\xdd\x83\x89\x11\x30\x3e\xf5\x26\x37\x1f\ -\x21\x8a\x86\xdb\x3b\xf3\x1b\xeb\x6b\x2b\xa6\xa7\xcd\x0e\x16\x6d\ -\xbf\x58\x72\x90\xf1\x8c\x89\x47\x25\x89\x1e\x34\x63\x77\x33\x9d\ -\x4e\xab\x1e\xa4\x7b\x64\x62\xb1\x98\xbc\x8b\xe6\xf3\x9a\xc6\x57\ -\x88\x69\x02\x84\xd3\xfa\xf3\xa4\xa1\xc7\xac\x1c\xca\x04\x88\x44\ -\x92\x4a\xe8\xa5\xdc\xef\xd0\xd5\x3c\x01\x3f\xa9\xfb\x18\x5a\x9e\ -\x4b\x6d\x7b\x92\xbd\xcb\x44\xfb\x12\xad\x72\x08\xd3\x0c\xbc\x75\ -\x78\x94\xb2\xfb\xff\xbc\x7c\xd1\x38\x30\x4a\xc6\x8b\x95\x96\x5c\ -\x1f\x4a\x07\xbc\xa7\xd0\x94\x0f\x8e\xcb\xc3\x03\xc0\xf2\x5c\x6a\ -\x5b\xdd\xc7\x10\x18\xcf\x0e\x8f\xf2\x6b\xc5\x67\x2b\xa1\x4c\x80\ -\xe2\x54\x77\x78\x19\x38\xb9\x38\xfb\xe5\xdf\x5e\x24\xea\x25\xcb\ -\x73\xa9\x6d\x06\x25\xf5\xc7\x8c\xcf\x06\x98\x08\x80\x83\x79\xfe\ -\x30\x40\xa2\x07\x2e\xe7\xe6\x1b\x92\xcc\xf3\xfa\x36\x01\x5d\x65\ -\x31\x26\xd7\xb5\xe9\x1b\xcd\xd8\xdd\x74\x39\x2f\xdf\x30\xe6\xce\ -\xc0\x39\x63\x8c\x99\x00\x25\x2b\xbc\xa0\x8d\xf6\xb5\x60\x92\x7b\ -\xd9\xea\xd5\x4c\x80\x13\x85\x52\xef\x04\xec\xd0\x1b\x8b\x87\x35\ -\x4d\x1a\x05\x78\x00\x00\x88\x71\xaf\xa0\x49\x13\x3f\xff\xf0\xd5\ -\x86\xd3\x7b\x07\xde\x01\xdd\x03\x37\x2e\x68\x1a\x3d\x04\x78\x18\ -\xc0\x29\x00\xa7\x98\x70\x4d\x96\xb5\x47\xbd\xb1\x78\xd8\xe9\xfd\ -\x03\x2d\x40\x24\x92\x54\xc0\xea\xf7\x00\xce\x9a\x9c\x3e\xcb\x2a\ -\x7d\xe2\xb4\x8f\x40\x0b\x10\x6a\xc9\xdd\x04\x95\x4f\x5d\x02\x26\ -\x0c\x3a\xed\x23\xb0\x02\xf4\xf4\xc7\x3b\xc0\x18\xf3\xba\x9f\x40\ -\x0a\x10\x89\x24\x15\x26\xba\x03\x20\x64\x11\x9a\x76\xda\x57\x20\ -\x05\xb0\xb2\x7e\x91\x3d\x4d\x52\x6f\x3b\xed\x2b\x70\x02\xd8\xb5\ -\x3e\x31\x8f\x2d\xa7\xa7\xb2\x4e\xfb\x0b\x94\x00\x35\x58\x7f\x75\ -\xef\xe9\xb9\xcf\xdd\xe8\x33\x50\x02\xd8\xb5\xbe\x04\xba\x6e\xe7\ -\x83\xa7\x1d\x02\xb3\x12\xec\xe9\x8f\x77\xb0\x4d\xeb\x2f\xcc\xa4\ -\xfe\x74\xab\xdf\x40\x38\xa0\x1e\xd6\x17\xb8\xe2\x80\x37\xdf\xf9\ -\xf0\x15\x45\xd2\x46\x0f\x17\x26\x74\x5f\x92\xb4\x89\x85\xf4\xe4\ -\x13\x3b\xd7\x87\x5a\x72\x37\xc1\xfe\x5a\x5f\xe0\xd8\x01\xbd\xb1\ -\x78\x58\x96\xb5\x47\x4c\xb8\x86\xe2\x5a\x1d\xe0\x61\x4d\xa3\x87\ -\xdd\x03\x37\x2e\x58\x5d\x5f\xcb\xa8\xbf\x70\xff\x6b\xd7\xac\x2f\ -\x70\x2c\xc0\xc1\x5b\x9a\xf9\x5a\x1d\x50\xbf\x8b\x44\x92\x15\x5d\ -\x56\x4f\xeb\x0b\x5c\x18\x03\x0e\x5e\x51\x2b\x70\xa9\xe9\xc5\xad\ -\x8f\x2b\x9d\xac\xc7\xa8\x6f\xc4\xf3\x41\x90\x89\xc6\x7a\xfa\xe3\ -\x1d\xc6\xe3\xf5\xb6\xbe\xc0\xb1\x00\xc4\xb8\x67\x11\xd2\xc4\x12\ -\x4d\xe9\x4b\x21\x08\xd6\x17\x38\x16\x40\x95\xd5\x5b\x00\xf6\x2c\ -\xc2\x4a\x4a\x21\x08\xd6\x17\x38\x16\x60\x39\x3d\x95\x05\x61\xdc\ -\x2a\x4e\x94\x42\x50\xac\x2f\x70\x65\x0c\xd8\xdf\x69\xbb\x0d\xc6\ -\x63\x8b\xb0\x26\x96\xe8\x5b\x96\xa4\x69\x04\xc0\xfa\x02\x57\x04\ -\xc8\x64\xc6\x0b\xc4\x7c\x1d\xd6\xa5\xf0\x3a\xc0\x17\x2d\x62\x7c\ -\xb1\xbe\xc0\xb5\x59\x60\x71\x76\xf2\x0f\x3b\xa5\x60\x85\x5f\xd6\ -\x17\xb8\x3a\x0d\xda\x2c\x85\x6a\xf8\x66\x7d\x81\xab\x02\xd4\x50\ -\x0a\x66\xf8\x6a\x7d\x81\xeb\x0b\xa1\xa3\x96\x82\xdf\xd6\x17\x78\ -\xb2\x12\x3c\x42\x29\xf8\x6e\x7d\x81\x27\x02\xd4\x58\x0a\x75\xb1\ -\xbe\xc0\xb3\x77\x01\xbb\xa5\x50\x2f\xeb\x0b\x3c\x7d\x19\xb2\x51\ -\x0a\x75\xb3\xbe\xc0\x53\x01\x32\x99\xf1\x82\x24\xf3\x7b\x00\xcc\ -\x36\x59\x6c\x4a\x12\xbf\x5f\x2f\xeb\x0b\x3c\x7f\x1d\x5e\x48\x4f\ -\x3e\x51\x18\x97\x19\x98\x07\xf0\x1c\xc0\x73\x06\xe6\x15\xc6\x65\ -\xbb\x9f\xcc\xbc\xc4\x97\xaf\xc2\x3f\xce\xa4\xb6\x00\xbc\xed\x47\ -\x5f\xb5\x12\x88\xaf\xc2\xf5\xc4\x4c\x80\xbc\xbe\x11\x8b\xc5\xaa\ -\xed\x27\x0e\x34\x26\xb9\xe7\x8d\x31\x66\x02\xe4\xf4\x8d\x5d\x34\ -\x9f\x77\x33\x29\x3f\x31\xe6\x4e\xc0\x96\x31\xc6\x4c\x80\x55\x7d\ -\x43\xd3\xf8\x8a\xcb\x79\xf9\x86\xa6\xd2\x55\x7d\x9b\x51\x3e\x25\ -\x97\x09\xc0\x84\xbb\xfa\x36\x31\x4d\x44\xfb\x12\xad\xee\xa7\xe7\ -\x2d\xd1\xbe\x44\x2b\x81\x4b\x16\x62\xc6\x67\x03\x4c\x04\x28\xec\ -\xb4\xcd\x01\x58\xff\xef\x00\xe1\xb4\x1c\xc2\xf4\x71\x12\x41\x6c\ -\x96\x2e\xdd\x31\x4e\xd9\xe2\xb3\x95\x50\xdb\x76\x79\x50\x52\x92\ -\x79\x3e\xd0\xdb\xe5\x55\xba\x4a\xe0\xf1\x23\x6f\x97\x17\xfc\x6f\ -\x7e\x98\x00\x40\xcc\x23\x8b\x33\x93\x9f\x99\x9d\xab\x38\xc5\xfd\ -\x95\xfd\x6d\x25\xdc\xde\x99\x07\x51\xd4\xbb\xd4\x3c\x87\x19\x18\ -\x59\x9a\x99\xbc\x55\x29\xa0\xea\x1c\xbf\xb1\xbe\xb6\x12\x7e\xf5\ -\x8d\x5f\x41\xd4\x85\x63\xf7\xdf\x10\x65\x49\xc3\xd0\xd2\x4c\xea\ -\x9b\xaa\x51\x76\x6e\xa5\xff\x6d\x8e\x80\xae\xe2\xae\xeb\xc0\xfd\ -\x36\x47\xc0\x16\x03\x8f\x6b\xf9\x6d\xae\x41\x83\x06\x27\x9b\x7f\ -\x01\x0f\x15\x0b\x99\x9e\x82\xdf\x92\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x05\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb7\x49\x44\x41\x54\x58\x85\xed\ -\x96\xbd\x4a\xc3\x50\x14\xc7\xff\x27\x1f\x53\xc1\x07\xf0\xda\x34\ -\x43\xf7\x82\x93\x08\xe2\x2b\x88\x0e\xd2\xc5\x17\xd0\x45\x10\x71\ -\xe9\xd4\xc1\x41\x74\x29\x3e\x81\x93\x43\x9f\xc0\x45\x90\x82\xa3\ -\x7d\x80\x62\x3e\x50\x33\xb8\xe8\x20\xa1\x69\x7b\x1c\x6c\x42\x13\ -\x9b\x34\xe9\xe7\xd0\xfe\xa7\xfb\x71\xee\xfd\xff\x72\xee\xb9\x97\ -\x00\xcb\x2e\x4a\x9a\x74\x1c\x27\xe7\xba\xed\x2a\x88\xf6\x01\x14\ -\x26\xf4\x32\xc1\x54\x57\x55\xaa\x08\x21\x7e\x46\x02\x38\x8e\x93\ -\x73\xdb\x5e\x03\x8c\xd2\x84\xc6\x61\x11\x9a\xaa\x2c\x6d\xfb\x10\ -\x52\x5c\x9c\xeb\xb6\xab\x53\x37\x07\x00\x46\xc9\xf3\xb8\xea\x77\ -\x63\x01\xfa\x69\x9f\x8d\x88\x0f\xfc\xa6\x92\x10\x16\x3a\x73\xbd\ -\x90\x4f\xac\x97\x51\x32\x4c\x9b\x87\xed\x1d\x9f\x81\x39\x69\x05\ -\xf0\xaf\x06\x5a\xad\x37\x4d\x51\x78\x97\xc1\xa1\x71\xc3\xb0\x4f\ -\x62\x77\x91\xb8\x47\x2c\x37\x35\x6d\xfd\x99\x88\xba\x59\x00\x42\ -\x85\x65\x18\xd6\x19\x88\x2e\x87\x81\xa5\x11\x03\x4f\xc4\xdd\x43\ -\x5d\xd7\x3f\xa2\x73\x91\x22\x0c\x8a\x3a\x38\x82\x57\xcb\x2a\x83\ -\xe8\x6a\x5c\x73\x00\x20\x60\x87\x49\xbe\x67\x66\x39\xed\x9a\x00\ -\x80\x98\xce\xc7\x35\x8e\x42\x58\xd6\xfb\x56\xda\xf8\xc1\xaf\x0d\ -\xbf\x7a\x84\xdb\xd4\xae\x8c\x3d\x00\x22\xe8\x52\xb7\x04\xa0\x91\ -\x15\x20\x54\x0f\xba\x96\x8f\x2f\xba\x88\x0c\xcb\x06\x18\xc7\xc1\ -\x40\x8f\x52\xdf\xae\x85\x5f\xc3\x15\xc0\x0a\x60\xe1\x00\x63\xbf\ -\x7a\x89\x22\xd4\x0c\xd3\xae\x25\x44\x98\x7e\x63\x31\x19\x60\xaa\ -\xfb\xcd\xd9\x64\x20\x49\x84\xa6\xaa\x50\xc5\xef\xce\x33\x03\x26\ -\x98\x6e\x06\xff\x88\xff\x78\xfa\x32\x4c\xfb\x0b\xc0\xda\x34\x9c\ -\x08\x74\x54\x28\x6c\xdc\xa5\x89\x1d\xcc\xc0\xc3\x34\xcc\x01\x74\ -\x3c\x85\x1e\xd3\x06\x07\x00\x1d\x45\x3a\x05\xf0\x39\xb1\x3d\xf3\ -\x45\x51\x08\x3b\x33\x40\x51\x08\xbb\xa3\x48\x9b\x00\xea\x00\xbe\ -\xb3\xda\x02\x78\x61\xe2\xb2\xae\x6b\xd7\x19\xd7\x2e\xb9\x7e\x01\ -\xf9\xaa\x7b\xc5\x23\x95\x73\x7f\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\xa6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x58\x49\x44\x41\x54\x58\x85\xed\ -\xd2\x31\x2f\x43\x51\x18\xc6\xf1\xff\x39\x15\x03\x89\x10\x42\xba\ -\x11\x9b\x89\xb0\x89\x45\xb4\x69\xd0\x44\xb5\xb5\xd5\xc0\x15\x12\ -\x1f\xc0\x66\x12\x1f\xc0\xac\xb5\x34\x62\x68\x99\x08\xad\x44\x42\ -\x48\x37\x11\xc2\xd6\x45\x27\x83\x44\xca\xe4\xde\xfb\x5a\x19\x38\ -\xda\x2e\x12\xe7\x37\x3f\x79\xce\xf3\x26\x07\x2c\xcb\xb2\xac\xff\ -\x4e\x99\x02\xa1\xb8\xb3\x0d\x0c\x2b\x5f\x52\x85\x83\xf4\xdd\x6f\ -\x4a\x23\x33\x2b\xbd\x5e\xc0\xcd\x02\x2f\xc5\xfc\xf6\x34\x20\xdf\ -\x65\xb5\x79\xa1\xb4\x03\x83\xa2\xf5\x65\x38\xe6\x8c\x9b\xf2\xe1\ -\xa4\x33\xec\x35\xb9\x25\x60\x14\xa4\xd3\x94\x37\x0e\xa8\xea\xb6\ -\x14\x8a\x1c\x48\x9b\x68\x8e\x27\x12\xce\xfc\x77\xd9\x89\xd9\xc5\ -\x29\xf1\x39\x47\xe8\x11\xd4\xd9\xbb\xe7\x45\xf8\xe1\x7a\x80\x80\ -\x69\x40\xe5\xbe\xe4\xa6\x92\xd1\x7c\xe5\xe9\xb5\x15\x18\x53\x10\ -\xeb\x1f\x18\x92\xf2\xc3\xf5\xf9\xe7\x5c\x28\xbe\xb4\xa2\x14\x59\ -\xa0\x19\xc8\x76\xe8\x97\xb9\xa3\xfd\xdd\x37\x53\xbf\xf1\x0f\x7c\ -\x7d\xc4\x59\x05\xb6\x00\x8d\xb0\xf3\xdc\xa5\x97\xa7\x83\x41\xef\ -\xea\xb6\xb2\x89\x52\x6b\x00\xa2\x64\xe3\x34\x97\x5e\xc7\x70\x79\ -\x5d\x03\x00\xc2\xf1\xc5\xa8\xa0\xf6\x80\x16\x81\x0b\x05\x55\x60\ -\x12\x70\x15\xb2\x5c\xc8\xa7\x33\xb5\xf4\xd5\x3c\x00\x20\x14\x5f\ -\x18\x01\x7d\x08\x74\x03\x08\x54\x95\xf2\x13\xc5\x5c\xa6\x50\x6b\ -\x57\x5d\x03\x00\xc2\x49\xa7\x4f\x7c\xca\xc0\xa3\xf6\xfd\xe8\xc9\ -\x41\xe6\xa6\xde\xae\x46\x28\x1a\x38\xc2\xb2\x2c\xcb\xfa\x13\x3e\ -\x00\x77\x85\x6b\x30\xd4\xa0\xe5\x67\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\xa5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x57\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xcd\x2b\x44\x51\x1c\xc6\xf1\xef\xb9\x93\xd2\x28\x29\xe5\x65\ -\xc7\x7f\x20\xf7\x92\xb2\xb3\x9a\x30\x3b\x65\x35\x56\x9a\x3b\xc2\ -\x88\x8d\xdd\xac\x64\xa5\xa6\xb9\x77\x33\x23\x79\xa9\x59\x58\x58\ -\x29\x25\x1b\x45\x22\xae\xa2\xac\x6d\x94\x6c\x88\x14\xa9\x3b\xf3\ -\xb3\x30\x0b\xd4\xb8\x33\x63\x25\xe7\xb3\x3c\x3d\x3d\x3d\xa7\x73\ -\x40\xd3\x34\x4d\xfb\xef\x54\x50\xc0\xb2\x33\x2b\x60\x98\xa8\x62\ -\xcc\xcb\xce\x5c\x55\x52\xda\x97\x48\x77\xf8\x12\xca\x83\x7a\xf2\ -\x72\x53\xc3\xa0\xa4\x5c\xd6\x08\x6c\x13\x9a\x40\xba\x10\x75\xd4\ -\x9d\x70\x07\x82\xe2\xdd\x13\x19\xd3\x97\xd0\x09\xd0\x0f\x34\x07\ -\xe5\x03\x07\xd4\x35\x14\x62\xc0\x16\xd0\x68\x88\xec\x5a\xb6\x33\ -\x56\x2e\x6b\xc6\x9d\x21\xa3\xa8\x0e\x80\x56\x60\xdf\x7f\xf3\x23\ -\x3f\xdd\xbe\xa2\x01\xc7\xe9\xb9\x57\xaf\xed\x7e\x54\x50\x4b\x40\ -\x1d\xb0\xd1\x63\x3b\x29\x90\x2f\xcf\x67\xda\x6e\x42\x29\xb6\x81\ -\x30\x48\xfe\xe5\xe1\x3e\x72\xb1\x3e\xfb\x18\xd4\x1f\xf8\x07\x3e\ -\xb3\xe2\x99\x49\x94\x72\x3e\x86\xcb\x9a\x48\xbd\x7d\xde\x7e\x5b\ -\xb0\xee\x9a\x17\x81\xf9\x52\xe1\xc2\x59\x6e\x3a\x15\x74\xf3\x9a\ -\x06\x00\xf4\xd8\x4e\x54\x60\x13\x08\x2b\x38\x14\xd4\x33\xc8\x20\ -\xe0\xa3\xb0\xbd\x6c\x72\xb5\x9a\xbe\xaa\x07\x00\xf4\xda\xae\x25\ -\xc8\x8e\x40\x4b\xe9\xe8\x59\x84\x91\xf3\xe5\xe4\x5e\xb5\x5d\x35\ -\x0d\x00\xe8\x1d\x77\x3b\x8b\x21\xb9\x06\x6e\x0c\x88\x9e\xe6\x92\ -\x97\xb5\x76\xfd\x82\xa8\xef\x9f\x51\xd3\x34\x4d\xfb\x73\xde\x01\ -\x57\x2b\x69\x45\xc4\x74\x4c\x85\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x02\xdb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8d\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x4f\x48\x54\x51\x14\xc6\x7f\xe7\x8d\xb8\x11\x82\x12\x03\x75\ -\x35\xb8\x10\xc9\x4d\x6d\x32\x8c\x28\x9c\xa6\x85\x12\x18\x6f\xb6\ -\x12\xcc\x64\xad\x5c\xa9\x2d\x87\xc1\xd5\x04\x2d\x12\x92\x2c\x27\ -\x28\x17\x19\xc6\xb8\x49\x28\x07\x13\x02\xff\xb4\xa9\x8d\xd5\x4e\ -\xdd\xd8\x42\x29\x68\xe1\x46\x98\x7b\x5a\xf8\xde\xf4\x1c\x9a\x3f\ -\x6f\x7c\xb6\xa8\x6f\xf5\xde\xb9\xe7\x9e\xef\x7b\xdf\xb9\x97\x77\ -\x2f\xfc\xef\x90\xe2\xc0\xd5\x1b\xf1\x6e\x44\xee\x02\x5d\x40\x53\ -\x40\x3c\xbb\xc0\x1a\xaa\xe9\x5c\x36\xb3\xec\x1d\x08\x79\x5f\x22\ -\x76\x7c\x58\x90\x17\x40\x3b\xd0\x10\x10\x39\x4e\xad\x76\x44\x6e\ -\xb6\x75\x9c\xdb\xdb\xf8\xfa\x71\xd5\x1d\x28\x38\x10\x89\x0d\x5e\ -\x14\x63\xde\x03\x3f\x51\x1d\xb2\x42\xcc\xbf\x9d\xcd\xfc\x08\x82\ -\xfd\x5a\x2c\x7e\xca\xe4\xe9\x45\x64\x1c\x38\x81\xea\x25\xd7\x89\ -\xba\x82\x12\x63\x46\x01\x41\x75\x28\x97\xcd\x4c\x07\x41\xec\xc2\ -\xf9\x90\xe9\x88\x9d\x10\x51\x9e\x39\x2d\xbe\x0e\x60\x79\xf2\xba\ -\x00\xac\x10\xf3\x41\x92\x7b\xa1\xf9\x7d\xb7\xf6\x79\x37\xe6\x15\ -\xd0\xe4\x51\x7b\x2c\x58\x9c\x7b\xfe\xdd\x79\x3c\xed\xc6\xea\x4a\ -\xe4\xd6\x8c\xa8\x7d\xab\x4f\x55\x1f\x03\x88\xc8\xe0\xc2\xab\x27\ -\xaf\xcb\xe5\x07\x2a\x20\x1a\x4b\x84\xd5\xe8\x0c\xce\x0e\x72\x84\ -\xb4\x94\x9b\x63\x95\x1b\xf4\x83\x64\x32\x69\xa9\xe1\x29\x3e\xb7\ -\x6f\x60\x02\x56\x3f\x7f\xbb\x03\x5c\xf6\xc6\x14\xc6\xfe\x8a\x80\ -\x68\x2c\x11\x56\xd5\x7b\x87\xc9\x65\xa9\xbb\xb3\x75\xf2\xd8\x05\ -\x94\xb0\x7e\xcf\xb2\x34\x9e\x4a\xa5\x4c\xa5\xf9\x15\x17\x61\xa5\ -\x55\x5d\xc2\xfa\x91\xdc\xec\xd4\x66\x35\x1f\x50\xd1\x01\x87\xbc\ -\x19\x68\x56\xd5\x99\x68\x2c\x11\x2e\x88\x3b\x82\xf5\x2e\xfc\x6e\ -\xc3\x06\x63\x24\x93\x4c\x26\x23\x00\x2b\xeb\xdb\x35\x5b\x5f\xb5\ -\x00\x85\x31\x81\x09\xf7\x5d\xd0\x2b\xcb\xeb\xdb\xb7\x2d\x11\xe1\ -\x08\xd6\xbb\xa8\xd8\x82\xee\xce\xd6\x49\x45\x96\xbc\x31\x81\x09\ -\x55\x7d\x78\x98\xdc\x9f\xf5\x55\x0b\x48\xa5\x52\xc6\xb2\x34\x0e\ -\xec\x95\x49\xf3\x6d\x7d\xd5\x02\x00\x16\x66\xa7\x36\x45\x64\xb4\ -\xd4\xb8\xc2\xc8\x82\x4f\xeb\x7d\x09\x00\xb8\x70\xa6\xe5\x51\x71\ -\x2b\x0e\xc8\x6b\xb3\xde\xb7\x80\x12\xad\xa8\xd9\x7a\xdf\x02\xe0\ -\xa0\x15\xc6\xa8\x0d\xba\x05\xba\x65\x8c\xda\xb5\x5a\xef\xc2\xf7\ -\xef\x78\x71\x2e\xf3\x06\x08\x57\x4c\xac\x12\x5e\x07\x76\xe1\xe0\ -\x00\x19\x54\xf1\x62\xf4\xf4\x0f\x34\x3a\x8f\x3b\x7f\x12\xb0\x06\ -\x60\xf2\xf4\x1e\x97\x00\x09\xd5\xbb\xb5\x3f\xb8\xb1\xdf\x2d\x50\ -\x4d\x23\xd2\x87\xc8\x78\xc4\x4e\x88\xe6\xf7\xe7\x3d\x67\xb8\x23\ -\xa1\xa7\x7f\xa0\x51\x42\xf5\xbd\xa2\x3c\x00\x0c\xaa\xe9\x82\x28\ -\x6f\x62\xc4\x8e\x0f\x8b\x4a\x9a\x00\x0f\x2a\x45\x30\x28\xa3\xb9\ -\xec\xd4\x7d\x37\x70\xe8\x66\xb4\xf1\xe5\xd3\x4a\x5b\xc7\xd9\x45\ -\x44\x9a\x80\x93\x04\x77\x3b\xda\x01\xde\xa1\x9a\xc8\x65\x33\x2f\ -\x03\xaa\xf9\x8f\xe0\x17\xaf\x0f\x09\xa8\xe3\xe3\x70\xe1\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x07\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb9\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x51\x0d\x83\x50\x10\x05\xd1\xa5\xc1\x1a\x0a\xb0\x80\xac\x5a\ -\xa8\x02\xc4\x81\x8c\xd3\xe4\xcd\x18\xd8\xc9\xe4\xfe\xed\x0c\xe4\ -\x38\xaf\xe7\x38\xaf\x47\x3a\x7c\xe4\xf1\x7f\xa0\x00\x5a\x40\x53\ -\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ -\x02\x9a\xe5\x03\x6c\xf2\xb8\x7e\x8d\xcf\xb4\x80\xd9\xb5\xc0\xcc\ -\xcc\xfd\xfb\xb2\x25\x2e\xbf\x80\x02\x68\x01\x4d\x01\xb4\x80\xa6\ -\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ -\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ -\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x96\x0f\ -\xf0\x02\x2e\x56\x08\x76\x9d\x62\x12\xf1\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x86\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\xf0\x84\x1f\x0c\x13\x11\ -\x50\xee\xf5\xff\xb3\x11\x8b\xb2\x7a\xb2\x7a\x36\x1f\x6f\x33\xbe\ -\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\ -\x03\xf8\x62\x04\x97\x5f\x3b\xc3\x6b\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7d\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\xc1\x0d\x80\x20\x14\x05\x41\xb4\x29\xba\xa6\x10\x8b\x12\xcb\ -\x58\x13\x66\x1a\xf8\x2f\x1b\x6e\x8c\x11\x9a\xeb\xdd\x73\xbd\xbb\ -\xdc\x70\x97\xc7\xff\x40\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ -\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ -\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ -\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\xed\xf8\x00\ -\x57\x79\xbc\xfe\x1a\x1f\xa3\x7f\x01\x4f\x7c\x1f\x00\x00\x00\x00\ -\x00\x00\x00\x4e\xf0\x01\xb9\x04\x09\xb0\x92\x01\xea\x01\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x1b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcd\x49\x44\x41\x54\x58\x85\xed\ -\x96\xb1\x4a\x23\x51\x14\x86\xbf\x93\x64\x13\x54\xb0\x70\x8b\x2d\ -\x04\xc5\x17\x30\xa0\x23\x2c\x82\xec\x2b\x2c\x8a\x8a\x85\x96\x8e\ -\x10\x89\x08\x22\x36\x56\x29\xb6\x08\xbb\xab\x23\x2b\x9b\xb4\x56\ -\x2a\x79\x02\x1b\x41\x04\xc1\x04\xf4\x09\x54\x2c\x54\xd0\x42\x0b\ -\x41\x50\x8f\x85\x4e\x4c\xa2\x33\xce\x24\xd1\x14\xe6\xaf\xee\x9d\ -\x39\x73\xff\x6f\xce\x3d\x73\xe6\xc2\x67\x97\xb8\xdd\xec\x1c\x4d\ -\x36\x85\x1b\xc2\x09\x90\x7e\x84\xf6\x8a\x9c\x94\x23\x84\x8c\x6a\ -\x64\x3e\x97\x36\xaf\xdf\x04\xe8\x1c\x4d\x36\x7d\x69\x8c\x6c\x0b\ -\x44\x2b\x32\x7e\xc1\xc1\x3e\x1a\xe9\xb5\x21\x02\x4e\x81\xe1\x86\ -\x70\xa2\xda\xe6\x00\x02\x51\x91\x9b\x84\x3d\x77\x04\x00\xe9\xaf\ -\xb6\x79\x5e\xca\x80\x3d\x0c\x39\xfb\x17\xef\x79\x36\x15\x77\xad\ -\x97\xb7\x64\x98\x96\xbe\xb6\xb6\x4b\x06\x3e\x46\x75\x80\x17\x35\ -\xd0\x3d\xbe\xd0\x26\x01\xf9\x81\x16\x5f\x37\x26\xac\x49\xa7\x45\ -\x44\xe5\x5e\x85\xfd\x8e\x8b\x6f\x3b\xeb\xeb\x43\x77\x65\x03\xf4\ -\x98\x8b\x33\x8a\xfc\x42\x5f\x29\x4e\x65\xc9\x69\x11\x45\x41\xe1\ -\xb0\xe5\x74\xab\x7b\xfc\xef\x70\x2e\x3d\x7d\xe2\x15\x20\xbf\x05\ -\x86\x69\x8d\x28\x92\x2c\x85\xf2\x23\x85\xbe\x80\x04\x57\x07\x07\ -\xd7\x82\xbe\x01\x40\x66\xcb\x35\x2e\x85\x38\xf8\x7a\xf6\xdd\x6b\ -\x7c\xc1\xdb\x6a\x69\xd7\xfb\xe7\xdd\x54\x7e\x0a\xda\x6a\xcf\x45\ -\x89\x02\xdb\x3e\x01\x8a\xff\x0b\xd9\x54\xdc\xb1\xe8\x4a\x65\x98\ -\x16\x40\x2c\x0f\x24\xea\xf9\xeb\xaa\xf9\x67\x58\x07\xa8\x03\xd4\ -\x1c\xa0\xec\xae\xe7\x2a\x65\xc9\x30\x2d\xc7\xd6\x8d\x72\x64\x0f\ -\x6b\x93\x01\x21\x63\x0f\xdf\x27\x03\x2e\x7a\x3a\x94\xce\xdb\xf3\ -\x8f\xcb\xc0\x63\xda\xff\x14\x9e\x88\xa1\xa0\xfd\x1a\xa6\x75\x09\ -\x34\x57\xc5\x4c\x74\x2c\xfb\x7f\x6a\xc5\x4b\xe8\x73\x06\x54\x37\ -\xaa\x62\x0e\xb7\x12\x08\x6d\x7a\x0d\xce\x03\x48\x28\x34\x0d\x9c\ -\x57\xea\xae\xca\xdc\xee\x72\xec\xd8\x37\xc0\xee\x72\xec\x58\x82\ -\xc1\x2e\x54\x33\xc0\x95\x5f\x5f\x90\x3d\x44\x47\x72\xe9\xf8\x6f\ -\x9f\xcf\x7e\x72\x3d\x00\x27\x99\x79\x91\xf6\x77\x59\xd9\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x95\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\xd8\x29\x2d\x13\x67\x02\xa4\ -\x6c\x16\x31\x84\xe9\xf8\xef\x63\x5d\x1b\x89\x8c\x22\xbb\x22\xbb\ -\x9c\x8d\x65\x1a\xb6\x79\xaf\xe9\x0e\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x80\x9b\xf7\x19\x0d\x9d\x47\x8e\x8f\xbb\ -\xb2\xd3\x06\x7c\x18\x63\x85\x7e\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\x35\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe7\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xb1\x11\xc2\x30\x14\xc5\x9e\x19\x22\x13\x31\x01\xc7\x06\xd0\ -\x30\x11\x0d\x23\x70\x4c\xc0\x34\xa9\xb2\x85\x29\x08\x5d\x3a\xdb\ -\x88\x3b\xa4\xea\x17\xff\x12\x7d\xf5\x4e\x44\xe4\x9f\x29\xa3\x7f\ -\xb0\x3f\x9e\x0f\xa5\xe6\x9a\x24\xb5\xe4\xf2\xbc\xdf\x1e\x3d\xf7\ -\x5b\xd9\x8d\xfc\x78\x92\xac\xc7\x4c\x49\xa6\xcf\x61\x3d\xf7\x5b\ -\x19\x1e\x20\xef\x63\xb6\xe6\x5e\xfb\x4d\x7c\x23\xc0\x4f\x63\x00\ -\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\x06\ -\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\x63\ -\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\ -\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\ -\x63\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\ -\x34\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\ -\x40\x63\x00\x5a\x80\x66\xfc\xa3\xa9\x64\xd9\x9a\x7b\xed\xb7\x32\ -\x3c\x40\x4d\x4e\x49\xe6\x24\xf3\x3a\x77\xdd\x17\x11\x69\xe1\x05\ -\x2c\x27\x22\x30\x10\x9e\x42\xf3\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\x51\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x03\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\xfb\x9a\x0a\x04\x0a\x3c\x1b\ -\x20\x21\x81\x04\x8b\x83\x05\xb0\x06\xdc\x4c\x48\x58\xc0\x50\xcf\ -\x18\x40\xa2\xf0\x48\x12\x70\xd8\x51\x84\x1d\xa0\x48\xc8\x38\x04\ -\x99\x4c\xda\x5e\x2c\x79\x0f\x70\x7d\x93\xd0\xff\x93\xe7\x56\x9c\ -\x1e\xd3\x4a\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\x20\xd8\xdf\ -\x67\xb7\x83\xc9\x79\xc8\x53\xa5\x1f\x4f\x52\xa7\xba\xee\x7e\xbb\ -\xff\x38\xc0\xee\xc9\xc5\x86\x59\x35\x95\x74\x2c\x69\xad\xa7\x6e\ -\xb9\x2c\xe4\x7e\xdf\x56\xc5\xf8\xf9\x7a\xf4\x16\x1f\x93\x01\xf6\ -\x47\x97\xeb\xcd\x52\x2f\x26\x6d\x65\xa9\x97\x8b\x69\x1e\x9a\x6e\ -\x7b\x76\x73\xfa\xfe\x3d\x2e\xe2\xe7\xda\xa5\xea\x7f\xf7\xf2\x92\ -\xe4\xda\x6c\x42\x31\x8d\xe3\x64\x00\xb9\x1d\x66\x29\xb4\x02\x26\ -\x1d\xc5\x59\x3a\xc0\xc0\xa4\x03\x98\x3f\xae\xa0\x47\x16\x2e\x3d\ -\xc4\x59\x32\x40\xa8\x34\x71\xe9\x35\x4b\xa3\x9c\x4c\xf3\xb2\xed\ -\xce\xe2\x38\x19\x60\x76\x35\xfe\x08\x65\xb1\x27\xe9\x56\xd2\x67\ -\x8e\x6e\x3d\x5b\xc8\xfd\xae\x2d\x6d\x27\xfe\x02\x48\xfc\x08\x01\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x43\xf1\x05\xad\xf1\x3c\x35\ -\x36\x50\x8e\x69\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x01\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3d\x49\x44\x41\x54\x58\x85\xed\ -\x93\x3f\x2f\x43\x61\x14\x87\x9f\x73\x5b\xc1\xd0\x88\x6f\xd0\x5d\ -\x62\xbb\xda\xc9\x62\x34\x48\x2b\x6c\xc2\x66\xf0\x09\x24\x12\x3a\ -\x58\x7c\x01\x7f\xd2\xc1\xaa\xf4\x76\x31\x4b\x2c\xa2\x9d\xd4\x07\ -\x10\x2c\xc2\xa2\x93\x84\xd4\xfb\x33\x50\x4d\x6c\xf7\xbd\xc9\x5d\ -\xdc\x67\x3b\xc9\x7b\x7e\xe7\xc9\xc9\x79\x21\x23\x23\xe3\xbf\x63\ -\xb1\x5e\x4b\x56\x6a\xc9\x01\xbc\x9b\x4d\xde\x54\xac\x97\x54\x20\ -\x88\xf5\x7a\x67\x28\x3c\x2a\xbd\x2e\x35\x94\x4b\x57\xa0\x66\x4e\ -\xd8\xf2\xa0\x7c\xcc\xab\x9f\xae\x00\xd0\xa9\xda\xa9\xd0\xee\xa0\ -\x2e\x45\xae\x9b\xaa\xc0\xb7\x44\x6e\x0b\xb8\xf8\x29\xa7\xcb\xd1\ -\xe7\xbe\xaf\x40\xbc\x23\xfc\x43\x29\x72\x1a\x26\xd9\x7a\xbb\x62\ -\x47\x71\x33\xbc\x36\x30\xa0\xdd\xb5\xe1\x11\x4a\x87\x61\x53\xb3\ -\xa9\x0a\x50\x33\x37\xde\xb7\xc2\x6f\x98\xe9\x32\x5d\x01\xe0\x05\ -\x3e\x80\x7b\xdf\xfe\x64\x02\x92\x15\x46\x5c\x1d\x28\x02\xcf\x39\ -\x59\x31\x55\x81\x72\xe4\xb6\x91\xad\x00\x6f\x98\xcd\x5f\x2d\xda\ -\x43\xdc\x0c\xef\x5f\x30\x13\x69\xd5\xd0\x31\xe0\x84\x2d\x74\xaa\ -\x76\xee\x93\xe3\xb5\x81\xb0\xa5\x39\x43\x75\x00\x61\x1b\xbe\xc3\ -\xbd\x04\xc2\x33\x4d\x05\x52\x13\xc8\x9b\xb4\xd7\xa9\xda\x81\xef\ -\xf0\xf8\x02\x92\x05\x81\x1a\xc0\x04\xa6\x93\xeb\xdb\x60\x33\xc9\ -\x70\x80\x7c\xdc\x06\x83\x27\xe0\x6e\xac\x17\xac\x51\x33\x97\x54\ -\x20\x23\x23\x23\xe3\x0b\x46\x70\x62\xa1\x9b\x7f\x53\x6a\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xb2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\x73\x93\x72\x03\x3a\x70\x82\ -\x96\x89\x89\xb9\x8d\xc4\x58\x04\x5c\xa1\x03\xb7\xf0\x35\x90\xe8\ -\x15\x2a\x04\x2c\x88\x42\x7b\x08\xa0\x9c\x80\x01\x26\xf6\xd2\x98\ -\x81\x86\xa2\xa6\x21\x76\xe2\x84\x01\x8f\xf6\x93\x7f\x9f\x6c\xe7\ -\x29\xf0\xdf\x87\xd4\x89\x45\xfd\x41\x4b\x85\xe6\x12\xe4\x65\x3c\ -\x1a\x9e\x00\xa8\x7a\x71\xa6\x20\xfb\x60\x76\x92\xf9\x5a\x02\xac\ -\x70\xda\xc0\x73\x3c\x97\xc3\x64\xad\xf2\x2b\x48\xe3\x74\xef\xaf\ -\x86\xaf\xb5\x04\xc8\xc3\x2b\x0d\x60\x83\x57\x16\xc0\x16\xaf\x24\ -\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\x11\xdc\x5b\x00\x5b\xfc\xe0\ -\xe8\x74\xdb\xa8\x8f\x1b\x83\xbc\xdf\x8d\xce\x7b\xe0\xa1\x11\x39\ -\xe2\x13\x60\x4f\x30\xcd\x64\xbe\x54\x80\x02\xf8\x2e\xf0\x28\x71\ -\x70\x9c\xac\x15\xbe\x82\x12\x78\x74\x7b\x71\xf6\x56\x2a\x80\x2f\ -\xbc\x50\x00\x37\x7c\x31\x05\xd3\x01\x9e\x24\x0e\x7a\xeb\xb8\x73\ -\x00\xdf\xb8\x53\x80\x2a\x70\xb0\xfc\x0a\x6c\xf1\xa8\x3f\x68\xb9\ -\xe0\x60\x71\x02\x2e\xb8\x0a\x65\xe2\x82\xe7\x06\x28\x86\xcb\x4c\ -\xe2\x46\x77\x13\xee\xd4\x09\x2b\xc2\x53\x9d\x30\xa8\x0f\x5f\x4c\ -\x81\x0e\x6b\x9d\xb0\x51\x0e\x67\xb9\x69\x36\x1e\xf5\x07\x2d\x09\ -\xcc\xcf\x87\x99\xdd\x09\x0b\xe0\x6d\x90\x59\x3c\x37\xbd\xa2\x0f\ -\x53\x36\x6f\xea\x0b\x5f\xd5\x65\x9d\x90\x02\xd0\x5a\x2b\x15\x32\ -\xce\xc3\x01\x51\x21\xd7\x79\xf8\x7a\x5d\x16\xfe\x1d\x60\x39\xb6\ -\x80\x87\xdf\xfe\x64\xb4\xd6\x02\xd2\xfc\xaa\xcb\xc4\x53\x75\x36\ -\xfd\x00\xad\xb5\xc2\xae\x35\x8b\xe7\xba\xbf\x1d\x9f\xf9\xbe\xa6\ -\x95\x85\xff\xbc\x8e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\xe0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x92\x49\x44\x41\x54\x78\x9c\xed\ -\x98\x4d\x68\x5c\x55\x18\x86\x9f\xf7\xde\x50\x12\x45\xa1\xda\x9d\ -\xe8\x56\x5c\xb7\x64\x22\xa9\x68\x54\x4a\x9b\x42\xd2\x49\x20\xe0\ -\x4a\xb4\xfe\x81\x6b\x7f\x41\x44\xac\x60\xba\xd0\xad\x8a\x05\x57\ -\xae\x9a\x8c\xc9\xa2\x15\x4a\x35\x9b\xca\x4c\xd2\x14\x74\xd3\x9f\ -\x9d\xc5\x65\x44\xd2\xb8\x88\x3a\x73\x5f\x17\xa1\x32\xb9\xf7\x26\ -\x99\x99\xdc\x99\x44\x7a\x9e\xe5\xf9\xee\x39\xe7\x7d\xbf\xf3\x73\ -\xcf\x39\x10\x08\x04\x02\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\ -\x10\xb8\xb7\x50\xba\x60\x70\xc6\x1f\x4a\xfe\x00\x88\x0d\x89\xc0\ -\x7b\xa0\xab\x30\x0c\x12\x44\x40\xc3\xd6\xc7\x8b\x93\xfa\xa8\x39\ -\x9e\x49\x40\x69\x36\xa9\x03\x71\xaf\x04\xf6\x98\x46\x6d\x22\xea\ -\x6b\x2e\x88\xf6\x4a\xc9\x7e\x21\x93\x00\x5b\x67\xd0\xff\x7b\xda\ -\xe7\x22\x6c\xeb\x4c\xb6\x38\x87\xd2\x8c\x47\x90\xe7\x80\x07\x52\ -\x21\x03\x49\x17\xe4\x15\x49\x44\xd6\xd7\x9a\xa4\xb1\x6a\x59\x0b\ -\xe9\x8f\x73\x13\x00\x50\xaa\xf8\x30\xf6\xf7\xc0\xa1\x54\x0d\xe3\ -\xfd\x99\x04\x43\xa4\xac\xa7\x15\xa4\xe3\xb5\xb2\x96\xf3\xea\x6c\ -\x99\x00\x80\x23\x73\x7e\x3c\x6e\xf8\x12\xf0\x68\xaa\x23\x6b\xbf\ -\xcd\x04\x11\xe1\xcd\x7e\x24\x6e\xd7\x23\x1d\xbb\x3a\xae\x9b\x5b\ -\x55\xdb\x76\x13\xbc\x3a\xae\x9b\x49\xa4\x61\xe0\xc6\xe6\xbe\x90\ -\xb5\x7f\x36\x50\xe7\x98\x07\x6e\x34\xa4\xa3\xdb\x99\x87\x1d\x66\ -\xc0\x5d\x0e\xcf\xfb\x50\x5f\xc3\x17\x31\x47\x52\x5d\x03\x6a\xb4\ -\x23\xb6\x78\x1c\xa7\x6d\x08\x96\xfe\xe9\xd3\xe8\xf2\x98\x56\x76\ -\xaa\xdd\xd2\x28\x2e\x8f\x69\xa5\x2f\xd2\xb3\xc0\x0f\x9b\x23\x02\ -\x88\x51\x4b\x79\x2c\x14\x6f\x8c\x78\x9e\xf9\xcb\x71\xac\xe7\x5a\ -\x31\x0f\x6d\x9c\x03\xae\x8c\x6b\x6d\x60\x55\x27\x05\x95\x1c\x35\ -\xb1\x5b\x9c\x4d\x45\x60\x90\xf2\x97\xe0\xec\xc1\x7e\x9d\xbc\x32\ -\xae\xb5\x56\xdb\x6a\x6b\x1d\x2f\xbc\xa4\xf5\xfe\x83\x9a\x92\x7d\ -\x2e\x1d\x93\x89\x9c\x5d\x87\x85\x63\x23\x39\xab\x5b\xf6\xb9\xc7\ -\xea\x9a\xba\x38\xaa\xbf\xda\x69\xaf\x33\xc1\xb6\x4a\x95\x64\x1a\ -\xf4\x56\x8e\xc0\x44\x5d\x3a\x48\x35\x9d\xeb\x37\x21\xfb\x6c\x75\ -\x22\x7a\x17\xa9\xed\x7e\x77\x35\x62\x83\x15\xbf\x2d\x7b\x3a\xa7\ -\xd9\x04\x5c\x68\x12\x8c\x24\x9c\x3d\xb9\x4a\xef\x2c\x96\x75\xb6\ -\xd3\x76\x77\x3d\x65\x87\x66\xfc\x8a\xe5\x2f\xc9\x8c\x4c\x71\x49\ -\xd8\xc2\x7c\x62\xe9\xb5\xc5\xb2\x32\xcb\xb1\x1d\x0a\x59\xb3\xa5\ -\x8a\x27\xb1\xbf\x05\x0e\x34\x97\x5b\xb6\xac\x5d\x1d\x98\x8c\x23\ -\x65\x7f\x33\x7f\x0b\xbd\x50\x9d\xd0\xec\x6e\xda\x86\x02\x77\xee\ -\xa1\xf3\x7e\xde\xf2\x77\x88\xfb\x9b\xcb\x8d\x2d\x3a\x4e\x42\xde\ -\xb9\xfe\xcf\x44\x3a\xb5\x54\xd6\xe5\x0e\xdb\xdc\x44\xa1\xbb\xf6\ -\x93\x15\x0f\x26\xf6\x05\xe0\xe1\x54\xa8\x93\x4b\x54\x9e\xf9\xdf\ -\x13\xeb\xc4\xd2\xa4\x96\x3a\xd5\x98\xa6\xf0\xdf\xd6\xd0\xac\x9f\ -\x30\xbe\x04\x3c\x92\x0a\x19\x91\xec\xf8\x7f\x10\xd8\xb9\x97\x9a\ -\xdf\x84\x8e\x55\x27\x74\xbd\x38\xb5\x5d\x78\x10\xa9\x4e\xe8\x7a\ -\x6c\x0d\x03\xb7\x52\x21\xb1\x61\x6c\x47\x4d\x39\xe6\x6f\xd5\xeb\ -\x1a\x2e\xda\x3c\x74\xe9\x45\xe8\xa7\x49\xfd\x1a\xa3\xa7\x80\x6b\ -\xa9\x90\x8c\xb7\x79\x6e\x73\x9c\x73\xa9\xb9\x76\xa0\xae\xa3\xcb\ -\x53\xba\x5d\xb0\xcc\x0d\x41\xdd\x68\xf4\x2e\xa5\x0b\x7e\xd0\xeb\ -\x9e\x17\x3c\x9d\xd3\x75\xe3\xbf\xf7\x56\x09\x9c\x9b\x98\x05\xfa\ -\x35\x5e\x1b\xd5\x9d\x6e\x69\xec\xea\x95\xb6\x36\xaa\x3b\xf7\xad\ -\xea\x38\x30\x9f\x8d\x3a\x66\x63\x00\xb4\x85\xf9\xb9\x81\x55\x9d\ -\xe8\xa6\x79\xe8\xd1\x05\xe6\x99\x1f\xdd\xb7\xfe\x47\xf2\xb5\xd1\ -\x8b\x2d\x55\xb0\xbf\x19\x78\x28\x7a\x75\x61\x44\xf5\x2e\x4b\xeb\ -\xcd\xa3\xc6\xc2\x88\xea\xd5\x9f\xa3\x97\x85\x3f\xdf\xe9\x5b\xe3\ -\xcf\x6a\xbf\x44\xa7\x7b\x61\x1e\x7a\x78\x85\x05\xc0\xd6\xe0\x2c\ -\xef\x49\xfe\x24\x5f\x8d\xde\xaf\x9d\xe2\xd3\x4e\x2e\x35\x9d\xd2\ -\xfb\x97\x0c\x60\x70\xc6\xaf\x4b\xfe\xa2\xa9\xc8\x48\x6f\xd4\xca\ -\xfa\xaa\xd7\x5a\xf6\x24\x01\x00\x43\x33\x8d\x69\x4b\xa7\x81\x06\ -\xd6\x9b\xb5\x49\x9d\xdf\x2b\x2d\x81\x40\x20\x10\x08\x04\x02\x81\ -\x40\x20\x10\x08\x04\x02\x81\x7b\x89\x7f\x01\x9b\xd6\x34\x0b\xef\ -\xec\xcc\xa6\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x1d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xcf\x49\x44\x41\x54\x78\x9c\xed\ -\x98\x4f\x6c\x54\x55\x18\xc5\xcf\x79\x4f\x06\x89\x85\x05\xd4\x44\ -\xaa\x25\xee\xc0\xa5\x7d\x6f\xea\xc2\xc4\x14\x0d\x0d\x74\xa1\x94\ -\x85\x0b\x56\x16\xc2\xcc\x88\xb1\xba\xc0\xb0\xc2\xb1\x31\x21\x21\ -\x90\xc8\xcc\x0b\x8a\x48\xc0\x98\x18\x17\x35\xca\xaa\x25\x8d\x50\ -\x12\xa8\x89\x69\x47\x97\x86\xc4\x95\x7f\xaa\x89\x92\x98\x00\xa9\ -\x14\xdf\xfd\x5c\x30\x95\x79\x7f\x3a\x9d\x7f\x6f\xa6\xe2\xf7\x5b\ -\xbe\x6f\xee\xbd\xe7\x9c\xb9\xf7\xce\xf7\x06\x50\x14\x45\x51\x14\ -\x45\x51\x14\x45\x51\x14\x45\x51\xfe\x5f\xb0\x53\x0b\xf7\xe7\x0a\ -\xc3\x46\x78\x0a\x80\x45\xe0\xa3\xd9\x0f\x47\x8f\x74\x42\x87\xdd\ -\x89\x45\xd3\xb9\xe2\x01\x11\x7e\x02\x60\x03\x80\x2e\x00\xcf\x6d\ -\x76\x76\xfe\xf2\x6b\xe9\xe2\xb7\xed\xd6\xd2\xf6\x00\x9c\x6c\xf1\ -\x30\x80\x02\x42\xbb\x8f\xe4\x8b\x3d\xe9\xa1\x85\xf9\xb9\xc9\x99\ -\x76\xea\x69\x63\x00\x42\x27\xdb\x7d\x9c\xc0\xdb\x55\x3e\xb4\xa3\ -\xc7\xdd\xf5\xc8\x7c\x69\xe2\x2b\x60\xac\x2d\xaa\xda\x72\x07\x0c\ -\xe4\xf3\x0f\xdd\xfa\x6d\xe3\x19\x80\x23\x35\x0d\x10\x9c\xeb\xda\ -\x7c\x23\x7b\x65\x6c\xec\xef\x84\xa5\x25\x1f\xc0\xc0\x2b\xe7\x1f\ -\xbe\xb5\xf6\xe6\x67\x00\x76\x87\x6b\x02\x31\x00\x41\xc0\x8a\xd6\ -\xf8\xe5\xfa\x3b\x5d\x7b\xaf\x7c\x3c\xf2\x57\x92\xfa\x12\x0d\xe0\ -\x99\xd7\x8b\x1b\xfc\x45\x5c\x00\xb0\x3d\x66\x65\x1f\x72\x5f\x85\ -\x08\xec\xb0\x18\x02\x97\x53\x77\x17\x76\xcf\x9c\x3b\x7c\x33\x29\ -\x8d\x89\x05\xf0\xf4\x48\xf1\x51\x7b\x0d\x26\x41\x38\xc1\x8a\x00\ -\xa0\x1f\xab\x44\xc4\x8e\x91\x34\xe7\x2f\x62\xe8\xbb\xf3\xa3\xbf\ -\x27\xa1\x33\x91\x00\x9c\xcc\xc9\x2d\xa4\x35\x05\x60\x6b\xa8\x24\ -\x00\x4c\x75\x39\x62\xc5\xe8\xba\x4e\xdb\xde\x31\xfb\xfe\x6b\x3f\ -\xb5\x52\x27\x10\x73\xf6\x9a\xa5\xef\xe0\x7b\x4f\x91\xd6\x0c\xea\ -\x36\xbf\xf4\x11\x18\x80\x12\x2a\x6c\x15\xdf\x9f\x71\x32\xde\xb6\ -\x56\xe9\x5c\xa2\xa5\x01\xa4\x0f\x9c\x4c\x5b\xbe\x7d\x15\xc0\x13\ -\xc1\x0a\x6b\x30\x5f\x89\x18\x08\xc2\x21\xf4\x92\x72\xad\x3f\xeb\ -\xb9\x4d\xca\x0c\xd0\xb2\x00\xd2\xd9\xc2\x0b\x62\x59\x97\x01\x6c\ -\xaa\x7c\x2e\x02\x01\xa4\x0e\xf3\x65\x18\xbb\x13\x36\x19\xc8\x74\ -\x5f\xce\x7b\xbe\x09\xa9\x01\x5a\x12\x40\x3a\x5b\xdc\x23\xe0\x04\ -\xee\xb5\xb5\x95\x08\x59\xcf\x37\x1f\x26\x76\x27\x74\x59\x22\x93\ -\xfd\xb9\xc2\x70\xe3\xf3\xde\xa7\xe9\x00\xdc\xac\xb7\x5f\x80\x71\ -\x00\xa9\x40\xe1\x9e\xf1\x26\xcc\x57\x9d\x27\x65\x84\x9f\xbb\xb9\ -\xe2\xbe\x66\xa7\x6f\xaa\x15\x76\x33\xc5\xb7\x40\x78\x88\xdc\xda\ -\x12\xb7\x7d\x9b\x42\x08\x30\xb8\x0e\x01\xbc\xf4\xb8\xbb\xf3\xf6\ -\x7c\xe9\xe2\xd7\x8d\xce\xdb\x60\x00\x42\x37\xb3\xf1\x18\xc8\x77\ -\x22\x15\xc0\xb0\xc5\xe6\x81\xb2\x73\x0a\x00\x86\xc2\xe6\x60\x8f\ -\xbb\x6b\xdd\x7c\x69\xe2\x52\x23\xef\x0f\x75\xf7\x01\xe5\xbe\xfe\ -\x34\xc0\xfd\xe1\x9a\x40\x12\x31\x1f\x58\x83\x20\x25\x7a\x74\x49\ -\x9c\x7d\xf2\xc6\x63\xb9\xf1\xf1\x97\xa3\x4d\x56\x15\xea\x0a\xa0\ -\xdc\xd7\x7f\x0a\x60\x4f\x54\x98\x18\x4a\xb2\xe6\x2b\xd6\x22\x85\ -\x71\xf7\xd7\x17\x7f\xa6\xb0\xf7\x07\x6f\xf4\x4e\xad\x73\xd5\x1c\ -\xc0\xb3\xfb\x8e\xad\x5f\x5c\xb3\xee\x82\x00\xc1\x9f\x20\x01\x84\ -\x30\x44\xe4\xb6\x4e\x14\x81\x90\x88\x0d\xe1\xd2\xda\xbb\x0b\xc3\ -\xb5\xbe\x3f\xd4\x14\x80\x93\x39\xd1\x4d\xa6\x26\x01\x04\x9b\x10\ -\x11\x90\xf4\xdb\xea\x3c\x8c\x88\x1d\xbd\x16\x30\x2b\x66\x71\xa8\ -\x74\xe6\xd0\x1f\x2b\x0d\x5f\x31\x80\xf4\xc1\x53\xbd\xe2\xfb\x53\ -\x00\x42\x6d\x28\x1b\x6b\x70\x12\x40\x40\x8b\x90\xa0\x17\xe1\xf7\ -\xb6\x91\xc1\x6f\xce\x8e\xfe\x5c\x6d\x6c\xd5\x00\x9c\x8c\xb7\x8d\ -\x94\x29\x00\xbd\xa1\x15\x05\xa4\x69\xf3\xae\x5f\x01\x5a\x08\x87\ -\x00\xfc\x08\xcb\x0c\xce\x7d\xf0\xe6\xf5\xe5\x46\x2d\xdb\x08\xf5\ -\x67\x3d\x97\x94\xab\x88\x35\x8f\x55\x66\x1e\x28\xef\xc6\xb0\xa8\ -\x2d\x30\xd6\xb5\xbe\x57\x0b\x4e\xdc\x08\x60\x99\x00\x9c\x4c\x61\ -\xbb\x81\x4c\x03\xe8\x0e\x2c\x81\x25\xf3\xab\x16\x23\xd1\x10\xba\ -\x2d\xc3\x69\x37\xe7\x0d\xc4\x0d\x88\x1c\x81\x74\xae\x70\x44\xc4\ -\x1a\x8b\xd9\x4e\xff\x71\x28\xa4\xc9\xcf\x9e\x7e\xe3\xdd\xca\xa7\ -\xd1\xff\xe2\x0c\xf3\x0f\x9e\x79\xa0\xdc\xa9\xe4\xc3\x4f\xa3\x47\ -\xe0\x01\xb4\xfe\x2f\x31\xde\xa2\x3b\x80\x3c\x2a\xad\x78\x8b\x5b\ -\x65\x08\x60\x84\x3c\xda\x69\x1d\x8a\xa2\x28\x8a\xa2\x28\x8a\xa2\ -\x28\x8a\xa2\x28\x4a\xa7\xf9\x07\xee\x73\x3f\xf5\xa2\x1e\x57\x1f\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xc0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x72\x49\x44\x41\x54\x58\x85\xe5\ -\x97\xcf\x4e\x13\x61\x14\xc5\x7f\xf7\x6b\xbb\x22\x31\x51\xc0\x08\ -\xbb\xbe\x82\xd0\x8a\xd1\x18\x4c\x5c\x09\x71\xc5\x1b\xd0\xd0\x26\ -\x40\x49\x8c\xc2\xb2\x69\x58\x95\x44\x23\x2d\x90\x42\xc0\xc4\xb0\ -\xc1\xbd\x4d\xd8\x28\x89\x89\x8a\x40\x7d\x05\x58\x29\x11\x31\x71\ -\xc1\xaa\x76\xae\x8b\xce\xd4\xb1\xd0\x3f\x53\x06\x17\x7a\x96\xe7\ -\xde\x99\x73\xe6\xdc\x6f\x32\x77\xe0\x7f\x87\xd4\x12\xfd\x89\xdc\ -\x2d\x54\x67\x10\x06\x50\xba\x7d\x52\x39\x42\xd9\x46\x24\xb3\x97\ -\x9f\x7c\x57\xd7\x40\x24\x3e\xff\x48\x91\xb9\xb3\x8c\xf9\x04\x4b\ -\x95\xe9\xe2\x4a\xf2\xc9\x29\x03\x7d\x63\xcf\x6e\x8b\x98\xb7\xc0\ -\x0f\x44\x93\xa1\x52\xb9\xf0\x61\xed\xe1\x77\x3f\x54\x6f\x8e\x3e\ -\xbd\x52\x0a\x05\x86\x50\xc9\x02\x97\x10\xb9\xe3\x24\x11\xac\x3a\ -\x11\x33\x0d\x08\xa2\xc9\xbd\xfc\xd4\xba\x1f\xc2\x0e\xec\x07\x59\ -\xef\x8f\x67\x05\x78\x81\xea\x0c\xf0\x00\xc0\x54\xbb\x84\x01\x80\ -\x50\xa9\x5c\xf0\x53\xdc\x0d\x13\x34\x85\x8a\x14\x37\xaa\x5c\xb5\ -\x6a\x1f\x38\xbf\x62\x3f\x0b\x3b\x8b\x13\xc7\x15\x29\xae\x3a\x5c\ -\xb0\x7e\x7b\x7b\xb8\x9e\x58\x18\x36\x6a\xad\x00\x58\x62\xc6\x3e\ -\xe5\x27\x5e\x35\xea\xf7\xd5\x40\x34\x96\x0b\x5b\x6a\x6d\x00\x1d\ -\x00\xb6\x91\xde\x46\xd7\x98\x46\x45\x4f\x48\xa5\x8c\x15\xd0\xe7\ -\x8e\x78\xab\xf0\xcd\x40\xe4\xb0\x2b\x01\x0c\xba\x39\x55\x66\xff\ -\x8a\x81\x68\x2c\x17\x56\x74\xae\x86\xde\x2a\xf6\x1c\x2f\x5f\xbc\ -\x81\xb3\xa3\x3f\x31\x65\x19\x25\x9d\xb6\x9a\x5d\xde\xf4\x10\x36\ -\x3b\xd5\x91\xc3\xae\x84\xa2\x83\x6e\x4e\x95\xc7\x3b\xab\x93\xfb\ -\xad\xf8\x6f\x9a\x80\x2d\xde\x03\xf4\x18\xb5\x36\xa2\xb1\x5c\xd8\ -\xa9\x9d\x27\x7a\x07\x5e\x5f\xc3\x0e\x2b\xa0\x6b\xa4\x52\xf7\x00\ -\xac\xc3\xf6\xa3\x6f\xd9\x80\x2a\xb3\x22\x2c\xb9\xa8\xbb\x7d\x5f\ -\x3a\xe3\x46\x44\xce\x13\xbd\x83\xa6\x23\xb0\xe3\xdc\x72\x73\x22\ -\x2c\x29\xba\x58\xd3\xea\x29\xfa\x96\x0d\x90\x4e\x5b\xa6\x2c\xa3\ -\xc0\x49\x83\x2e\xcf\xd1\xb7\x6e\x00\xd8\x59\x9d\xdc\x17\x64\xba\ -\x5e\xbd\x9d\xe8\x3d\x19\x00\xd8\xbd\xf6\x2d\x4f\xcd\x28\x6c\xb4\ -\x15\xbd\x67\x03\x75\x46\xd1\x76\xf4\xde\x0d\xe0\x8c\x42\x47\x14\ -\x0e\x14\x0e\x04\x1d\x69\x37\x7a\x07\x9e\x3f\xc7\xbb\xcb\x53\x9b\ -\x40\xb8\x69\x63\x8b\x70\xaf\x64\x47\x50\x59\x20\xfd\xba\x79\x2d\ -\xa2\xe3\x0b\x9d\x15\x29\xbe\x9e\x36\xa0\x6c\x03\x94\x42\x81\xa1\ -\x8b\x32\x60\xfd\xb4\x86\x2a\x52\x7c\x74\xb8\xdf\x23\x10\xc9\xa0\ -\x3a\x8c\x4a\xb6\x3f\x9e\x15\x13\x34\x05\x67\x87\x3b\x2f\xa2\xe3\ -\x0b\x9d\xb6\xf8\x3c\x60\x21\x92\xa9\xca\xba\x1b\xed\x1f\x93\x0c\ -\x7e\x6e\x4a\x7f\xe2\xd4\x8f\x49\xc0\x5d\xfd\x5c\xdc\x7c\xdf\x1b\ -\xb9\xff\x1a\xe8\x16\xb8\x8c\xc7\xf5\xaa\x1e\xec\x99\xbf\x41\x24\ -\x56\x5c\x4e\xbe\xf4\xe3\x9e\xff\x0e\x7e\x01\x29\x72\x01\x2f\x4e\ -\xc0\xa2\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xc0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x72\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x09\x83\x60\x14\x04\xe0\xd3\x21\xc4\x26\xe0\x4c\x59\xc1\ -\xca\x89\xdc\x24\xf3\x08\x69\xc4\x21\x34\xad\xf8\xd7\x2a\xc4\xef\ -\x2b\x8f\x57\xdc\xbb\x04\x00\x00\x00\x00\x00\x00\x78\x82\xea\x18\ -\x4c\xd3\xf7\x9d\x2a\x63\x92\xe6\x86\x3e\x67\x9a\xb3\xa5\xef\xba\ -\xd7\x67\x1f\xd6\xc5\xd9\x7f\x3e\x9f\x24\x6d\xea\x8c\xc7\xb0\x1c\ -\xe0\x61\xca\x01\xb6\x0c\x49\x96\xeb\xab\x9c\x6e\xce\x9a\xe1\xee\ -\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xf5\x7e\x5a\x95\x0d\x08\xf2\ -\x12\x5b\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xa7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x59\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\xb8\x85\xa4\x34\xb8\x85\xa4\x34\x50\x62\x06\x13\x25\ -\x9a\xa9\x01\x46\x1d\x30\xea\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\ -\x0e\x18\x70\x07\xb0\x50\x6a\xc0\x7f\x06\x06\x07\x4a\xaa\xe4\xa1\ -\x1f\x02\x8c\x0c\x0c\x07\x76\xad\x99\xd3\x40\xae\xfe\x01\x0f\x81\ -\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x06\xdc\ -\x01\x00\x05\x9e\x09\x3f\xb6\x6d\xc4\xbd\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\x80\x30\x00\xc4\x40\xc2\x1e\x11\xec\x3f\x15\x88\x41\ -\x42\xcb\x06\x47\x61\x77\x5f\xbd\xe5\xb1\x21\xae\xfb\x59\xdf\x7d\ -\x1e\x73\x08\x8f\x5d\x9c\xfe\x89\x02\x68\x01\x4d\x01\xb4\x80\xa6\ -\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ -\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ -\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ -\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ -\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ -\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ -\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ -\x2f\x70\x51\x04\x80\x66\x61\x99\xa8\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\xf4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa6\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x4f\x68\x1c\x55\x18\xc0\x7f\xdf\x9b\xec\x26\x5a\x93\x88\x96\ -\x98\x9a\xdd\xc9\xee\xc6\x80\x86\x3d\x78\x90\x42\x0f\xf5\x4f\x29\ -\x2d\x22\x6d\xaa\xa0\x22\x52\x0b\x55\xf1\xd0\x9b\x20\xa4\x78\xe8\ -\x41\xd1\x80\x27\xa5\x28\x88\x20\x88\x5e\x0d\x36\x6a\xb5\x60\x69\ -\x4f\x52\x1a\x28\xc2\x2a\x91\x6d\xb2\x7f\x66\xb6\xab\x78\x90\xd8\ -\x58\x35\x99\x79\x9f\x87\x9d\x5d\x93\x6c\xd2\x64\xd9\x8d\x97\x7e\ -\x97\xf9\xf8\xe6\x9b\xf7\xfb\xbd\x61\xde\xcc\x1b\xb8\xd5\x43\x5a\ -\x69\xbe\x5a\xa9\x24\x63\x81\x3d\x62\x91\xfd\x82\x26\x51\x12\x08\ -\x06\xa5\x82\xe0\x0b\x5c\x34\x86\xa9\x64\x32\x99\xef\xa8\xc0\xbc\ -\xe7\xed\x36\x96\x49\xe0\xb1\xad\xf4\x2b\x5c\x36\xc8\xc9\xe1\xe1\ -\xc4\x77\x6d\x09\xcc\xcd\xcd\xf5\x3b\x4e\xfc\x03\x84\xe7\xa2\x52\ -\x55\x61\x1a\xd1\xb3\x2a\x32\x1f\x76\x75\x55\x6f\x0b\x43\x1b\x86\ -\xe1\xa0\xaa\x93\x52\xd1\x03\x02\xe3\xc0\x70\xd4\xff\xb5\x0d\x97\ -\x8f\x67\x32\x99\x5f\x5b\x16\xf0\x3c\xef\xbe\xd0\xea\x19\x90\x07\ -\x80\xaa\xc0\x29\xd7\x4d\x7c\x2c\x22\xc1\xcd\xa4\x55\xd5\x14\x3d\ -\xef\x59\x51\x79\x13\xc8\x20\x94\x6d\x20\x87\x33\x99\xc4\x0f\x5b\ -\x16\x28\x95\x4a\x19\xc5\x5c\x02\x76\x0a\x7c\xb1\xb4\xf4\xf7\x0b\ -\xa3\xa3\xa3\x7f\xdc\x0c\xbc\x36\xf2\xf9\x7c\x77\xac\xbb\xe7\x7d\ -\x94\xe3\xc0\x9f\xa8\xd9\x9b\x4a\x0d\x5d\xd9\x54\x20\x9f\xcf\xf7\ -\xc5\xe2\x3d\xdf\x03\x63\x0a\xef\xa6\xdc\xc4\xab\x22\x62\x5b\x81\ -\xd7\x43\x55\xa5\x58\xae\x4c\x08\xfa\x16\xe0\xa3\xe1\xee\x54\x2a\ -\x55\x5d\xd9\x63\xd6\x5e\x14\x8b\xf7\x9c\xae\xc1\x75\xba\x1d\x38\ -\x80\x88\x68\xca\x1d\x9a\x04\x3e\x02\x12\x88\xf3\xa9\xaa\xae\x9a\ -\xf4\x2a\x81\x72\xb9\xfc\x10\x70\x14\xe5\x37\x1b\x2c\x1f\x6d\x07\ -\xbe\x52\x62\xf1\xfa\xc2\x09\x60\x16\xd8\x57\x2a\xf9\x8f\x6f\x28\ -\x60\x95\xb7\x6b\x17\xf1\xc6\xc8\xc8\xc8\x42\xbb\xf0\x7a\x64\xb3\ -\xd9\x25\x94\xd7\x01\x54\x98\x5c\x79\x17\x1a\x49\xb1\x58\xdc\x85\ -\x38\x15\xe0\xf7\xc5\xeb\x0b\xbb\xb2\xd9\xec\x52\xa7\x04\xa0\xf6\ -\x3c\x94\xca\xfe\x4f\xc0\xfd\x36\x94\x07\xeb\xab\xa2\x71\x07\x44\ -\x9c\x43\x91\xd0\x57\x9d\x86\xd7\xc6\x17\x55\x38\x03\x20\x8e\x3e\ -\x59\xaf\x37\x04\x54\x79\xb4\x96\xf0\x4d\xa7\xe1\x0d\x09\x95\x6f\ -\xa3\x74\x5f\x93\x00\x22\xc9\x28\x29\x6c\x97\x80\xea\xf2\x3c\x80\ -\x40\xa2\x59\x20\x2a\xaa\x2e\x57\xd9\xa6\x08\x82\xa0\x3e\xf6\x50\ -\xfd\x41\x6c\x7a\x0f\xfc\x8f\xb1\x56\xc0\x56\x6a\xc7\xd8\xe0\x76\ -\x11\x1d\x67\x47\x34\xb6\x5c\xab\xbf\x63\xfe\x13\x50\xe3\xd5\xba\ -\x6c\x7a\xbb\x04\x8c\xb1\x99\x28\xf5\x1b\xb5\x06\x5f\xb8\x00\x60\ -\x94\x83\xdb\x25\x20\xa2\x07\x00\x14\x3d\xdf\x24\xe0\x88\x9d\xae\ -\x9d\x94\x27\x66\x66\x66\x62\x9d\x86\xab\xaa\x28\x1c\x06\xc0\xca\ -\x54\x93\x80\xeb\xba\xd7\x80\xf3\xc0\xce\xbb\x07\x06\x5e\xea\xb4\ -\x80\xe7\x79\x87\x80\x31\xe0\xc7\x54\x6a\xa8\xb1\x37\x58\xb5\x0a\ -\x8c\xe8\x04\x80\xa8\x39\x95\xcf\xe7\xfb\x3a\x05\xcf\xe5\x72\x71\ -\xab\x52\xfb\xce\x60\x4e\x8a\x88\xae\x2b\xe0\xba\xee\x65\xe0\x33\ -\xd0\x7b\xe2\xf1\x9e\x4f\x54\xb5\xed\x65\xaa\xaa\xd2\xdb\xdb\xf7\ -\x1e\x30\x86\x70\xc1\x75\xef\xfd\x72\xe5\xf9\x26\x40\x18\x2c\x9d\ -\x00\x66\x15\xc6\x4b\xa5\xca\x3b\xed\x48\xa8\xaa\x94\xcb\xfe\x6b\ -\x8a\xbc\x02\x5c\x33\xe8\xf3\x2b\x67\x0f\x1b\x6c\xc9\x6a\xfb\x41\ -\x2e\x01\x77\x21\x7c\x7e\x7b\x4f\xf7\xb1\x81\x81\x81\xc5\x56\xe0\ -\xb9\x5c\x2e\x7e\x47\x6f\xff\x69\xe0\x65\xe0\x86\x11\x7d\xc4\x75\ -\xdd\x99\xb5\x7d\xeb\xce\x2e\x99\x4c\x5e\x0d\x1d\xd9\x03\xfc\x8c\ -\xf2\xd4\x8d\xbf\xfe\x99\x2d\x16\xbd\x17\x55\xb5\x6b\x33\xb0\xaa\ -\x9a\x52\xc9\x7f\x66\x47\x6f\x7f\x2e\x82\xfb\xa8\xb3\x77\x3d\x38\ -\x6c\xb2\x2d\x2f\x14\x0a\x77\x62\x9c\x0f\x05\x79\x3a\x2a\xf9\xa8\ -\x4c\x8b\xc8\x59\x08\xe6\x8d\x31\xd5\x20\x08\x2c\xc4\x07\x71\xc2\ -\x61\xb1\x1c\x44\x64\x1c\xc8\x44\x83\x9f\xb3\x36\x38\x96\x4e\xa7\ -\x7f\xd9\x88\xb1\xa5\x1f\x93\x62\xd1\xdf\x23\xa2\x93\x0a\x0f\x6f\ -\xa5\x1f\xb8\x62\x45\x27\x32\xae\x7b\x6e\xb3\xc6\x96\x7e\xcd\x0a\ -\x85\x42\x0a\x13\x3b\x22\xe8\x7e\x94\x24\x42\x02\x70\x00\x5f\xc0\ -\xb7\xc8\x45\xac\x4c\xa5\xd3\x43\xb3\xad\x8c\x7b\x6b\xc7\xbf\xc1\ -\x7f\x6c\x10\x0e\xdc\xa9\xdc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x02\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x3c\x49\x44\x41\x54\x58\x85\xed\ -\x97\x3d\x6b\x14\x51\x14\x86\x9f\x73\xc7\x2e\x60\x61\x30\xa0\x66\ -\xdc\xd9\x5f\x61\x40\x91\x58\x6f\xca\xb4\xda\x04\xd4\xca\xca\xc4\ -\x1f\x90\x6a\x03\x16\x06\x0c\x2a\x68\x9d\x3a\xb8\x60\x17\x10\x84\ -\xe4\x57\xec\xbd\x99\xb1\x49\x50\xb0\x48\xb9\xf3\x5a\xec\x4e\x4c\ -\x26\xfb\xbd\x13\x1b\x7d\xab\xcb\x39\x77\xe6\x3c\xf3\x9e\x0b\x73\ -\x0f\xfc\xeb\xb2\x72\x20\x84\xef\xf7\x73\x3a\xaf\x4c\xb6\x84\x71\ -\xb3\x92\x2a\xe2\x44\xa6\x03\x47\xd4\xac\xd5\xee\x7c\x1b\x08\xe0\ -\xfd\xd1\x4b\xcc\xb6\xfa\x81\x55\xa4\x1c\x69\x23\x49\xee\xbe\xbe\ -\x04\x10\x42\x78\x20\xdc\x57\xe0\x97\x61\x2f\x9c\x53\x2b\x8e\xe3\ -\x9f\x55\x54\x4d\xd3\xf4\x46\x9e\x5b\x43\x68\x1b\xb8\x6e\xb8\x87\ -\x65\x27\x68\x87\xa3\x3d\x1f\x52\x85\x90\x3d\xae\xa2\x68\x3f\x85\ -\x90\x3d\xf1\x21\x55\x3b\x1c\xed\x15\x31\x57\x2c\x4c\xb6\x04\xe0\ -\x9c\x5a\x57\x05\x10\x45\xb4\x00\x0c\xbb\x77\x09\xa0\x38\x70\x55\ -\xd9\xde\x4f\x8b\x8b\x8b\x3f\x7a\xcb\x85\x22\x76\xad\xea\x22\x21\ -\x64\x2b\x42\x1f\x00\x0c\x7b\x5a\xab\x2d\x7e\x1e\xb6\xbf\x52\x00\ -\xef\x7d\x5d\x68\x17\x98\x03\xe8\x81\xdc\x1e\xf6\x8c\x1b\x96\x9c\ -\x44\x92\x1c\x2e\xfa\x54\x14\x1f\x57\x95\x01\x84\x34\x7d\x8e\x58\ -\xbe\x00\x65\xda\xfc\x2b\x00\xde\xfb\x3a\xb2\xad\x52\x78\x3f\x89\ -\xe3\xf7\x57\x0e\x30\xc0\xfa\x53\xd4\x59\x33\xb3\x7c\xd4\xf3\x23\ -\x0f\xe1\xa8\x53\xdd\xb5\xde\x96\x2f\x40\x99\xd6\xeb\xb5\xa4\x3d\ -\xce\x07\x8c\x74\xa0\x57\xfc\x16\x70\x4b\x68\xd7\x7b\x5f\x2f\x72\ -\xb3\x58\x3f\x36\x40\x49\x73\x58\xf4\x51\x92\x9b\xd5\xfa\x42\x23\ -\x5b\x20\xd3\xa6\xc9\x76\xce\x85\x1e\xf9\x34\x7d\x66\x60\xb3\x58\ -\x5f\x68\xa4\x03\x3d\x3b\xf7\xcf\xc7\x4c\xb6\x83\xec\x6d\x69\xeb\ -\x44\xd6\x8f\x0d\x60\x66\x39\xea\xac\x01\xa7\x43\xb6\x4d\x6c\xfd\ -\xd8\x00\x00\x49\x92\xb4\x31\x6d\x0c\xca\xcb\xb4\x9e\x24\x93\x59\ -\x3f\x11\x00\x40\x2d\x8e\xdf\x51\x6a\x45\x4f\x53\x59\x3f\x31\xc0\ -\x80\x56\x4c\x6d\xfd\xc4\x00\xd0\x6d\x85\x1c\xab\x60\x1e\xcc\xcb\ -\xb1\x3a\xad\xf5\x85\x26\xfe\x1d\xd7\xe3\xf8\x0b\x50\x1f\xb9\x71\ -\x4c\xfd\x71\x40\x9c\x40\xf7\x02\x59\xd5\xcb\xcb\xca\xb2\x6c\xbe\ -\xb7\x3c\xbe\x04\x20\xd3\x01\x40\x9e\x5b\xe3\xaa\x00\x3a\x1d\x1a\ -\x00\x42\x87\x45\xec\xac\x05\x8e\xa8\x29\xf2\x15\xa1\xed\x10\x32\ -\x8b\x22\x5a\xe7\xee\x70\x33\x29\xcb\xb2\xf9\x4e\x87\x86\xd0\x1b\ -\x20\x77\x44\xcd\x22\xd7\x6f\x30\x69\x52\xe1\x45\xa5\xa4\xc1\x83\ -\x49\xa1\xb3\xd1\xac\x7b\x75\x5e\x28\xe7\xa7\xd4\xb1\xd0\x61\xbf\ -\xd1\xec\xbf\x7e\x03\x1f\xb0\x01\x10\x54\x88\x8f\x55\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\xfe\x21\x15\x83\xf8\x29\xe4\ -\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\xc6\xda\ -\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\x00\x00\ -\x00\x00\xbc\xd7\x42\xd4\x03\xab\xc4\x79\xcd\x85\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x20\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x15\x82\x50\x10\x44\xd1\x5d\x8b\xa0\x16\xeb\xa0\x05\x22\ -\x2b\xb2\x0b\xea\xb0\x0e\x22\xab\x00\x03\x34\xd3\x94\xeb\x39\xcc\ -\x8d\x7e\xf6\x67\x5f\x55\x44\x9c\x59\xab\x8f\xaf\xf3\x36\x6e\xb5\ -\xdd\xf7\x11\x7d\x7b\x8c\x3d\x8b\x1d\x17\xf1\x69\x55\xd5\xfb\xf8\ -\xa1\xaa\x86\x4f\x08\x81\x05\xa8\xfd\xf8\x6f\xef\x43\xc9\x00\x7f\ -\x21\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ -\x2d\x01\xf4\x00\x4d\x06\x78\xfe\x78\x1f\xca\x05\x58\x7b\xea\xae\ -\xa5\xbb\x96\x5a\x7b\x62\x3b\x22\xe2\xd4\x5e\x68\x08\x13\x4e\x3b\ -\x46\xe4\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x01\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb3\x49\x44\x41\x54\x78\x9c\xed\ -\x99\x4f\x68\x5c\x45\x1c\xc7\xbf\xdf\xd9\x4d\x08\x88\x27\x5b\xb1\ -\xbc\xbc\x9d\x8d\x8d\xb2\x67\x15\x4f\xed\x21\xfe\xa3\x5a\x28\x82\ -\x17\x3d\x09\xc6\x58\xc1\xa3\xa2\xa0\x88\x94\x7a\x69\x05\xbd\x56\ -\xb1\xe0\x49\x10\xa4\xda\x8b\x95\x42\xa5\x5e\x2d\xf5\x2c\x12\x92\ -\x7d\x79\x59\x11\x8d\xa7\x08\x4d\x36\xfb\xe6\xeb\x61\x37\x74\xf7\ -\xbd\xb7\x64\x93\x7d\xbb\x1b\xe9\x7c\x4e\xcb\xfc\x66\xe6\xf7\xfd\ -\xce\x9b\x79\x6f\x66\x16\xf0\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ -\x1e\x8f\xc7\xe3\xf1\xdc\x5b\x30\x5d\x10\x45\x8d\x8f\x44\x7d\x28\ -\xe7\x4a\x24\x1d\x00\x4d\x40\x57\x91\x50\x92\xa1\x31\x09\xc5\xf3\ -\xd6\x06\xe7\x7a\x82\xe9\xda\xf5\x28\x6e\x01\x28\x8d\x4d\xde\x78\ -\x49\xaa\x36\x2c\x77\x17\x98\x49\x29\x39\x2c\x64\x06\x80\xc0\xc7\ -\xf8\xff\x4f\xfb\x3c\xd4\xf1\xd6\x43\x66\x09\x00\x40\xbd\xbe\xbe\ -\x00\xea\x2a\x80\xfb\x53\x7d\x88\xa4\xd3\x21\x1e\x1e\x01\x86\x59\ -\x5f\x9b\x72\x38\x33\x37\x17\xde\x4c\xd7\xcf\x1d\x00\x00\x88\xa2\ -\xe8\x71\xc1\xfc\x08\xe0\x48\xaa\x89\x00\xb9\x02\xb4\x8e\x02\x83\ -\xac\xa7\x0d\xc2\x9d\xb2\xd6\xde\xee\xd7\x20\x17\x6b\xed\x6d\x97\ -\x98\x13\x04\xe2\xde\x88\xc8\x43\xf8\xee\x60\x9e\x79\x62\xcd\x25\ -\xe6\x44\x3f\xf3\xc8\x34\xc8\x61\xb9\xd1\x08\xcb\x2d\x77\x1d\x40\ -\x2d\xd5\x52\x10\xdd\xe4\x5f\x17\x04\x28\x03\x65\xbc\xfc\xd6\x2a\ -\x9b\xe7\xe6\x83\x20\xce\x6d\x76\xb7\xf5\xde\x34\x1a\x8d\x23\x3b\ -\x2d\x77\x0d\xc0\x13\xdd\xe5\x12\x40\x32\x99\xe4\x20\x48\x28\x31\ -\xe5\x42\xc0\xad\xe9\xb2\x79\x21\x08\x82\x8d\xbd\xda\x0f\x34\x95\ -\x83\x20\xd8\xd8\xba\x33\xf3\x14\x80\x9f\xba\xcb\x49\x40\x50\x69\ -\xa0\x51\x2c\x1c\x51\xc8\x9a\x07\x70\x63\xfb\xce\xcc\xd3\x83\x98\ -\x07\xf6\xb1\x96\x6b\xb5\xa3\x9b\x72\xad\xd3\x20\xbe\xeb\x2e\x27\ -\x00\x01\x25\x0d\x38\x9b\x8a\xa0\x9d\x8b\x26\x93\x90\xb8\xb2\xd3\ -\xdc\x3a\x5d\xab\x1d\xdd\x1c\xb4\xaf\x7d\x8b\x96\x54\x8e\xe2\xf5\ -\x4b\x10\x16\x73\xa2\xae\xfd\x95\x18\x25\x22\xc0\xec\x83\x23\x2e\ -\xdb\x70\xf6\x6c\x7b\x49\x0e\xce\xbe\xdf\xe6\x24\x5b\x36\x9c\x5d\ -\x02\xf0\x49\x4e\x34\xef\x33\x54\x24\xb9\xe6\x05\x5c\xb4\xe1\xec\ -\xd2\x7e\xcd\x77\x3a\x3c\x38\x51\x14\xbf\x2b\xe0\x42\x4e\xa8\xf0\ -\x43\x14\xdb\x53\x2b\x6f\xe7\xfa\x9e\xb5\xe1\xc5\x21\xfa\x1d\x8e\ -\x7a\x3d\x7e\x1d\xc4\xe7\x48\x8b\x23\x1d\x54\xd0\x9e\x91\x24\xa4\ -\xb4\x79\x07\xe1\x8d\x6a\x35\xbc\x3c\x54\xd7\xc3\x34\xde\xa5\x5e\ -\x8f\x5f\x02\xf1\x35\x80\xe9\x54\x48\x68\xcf\x86\x83\x23\x18\x30\ -\xa3\xb3\x09\xe1\x95\x6a\x35\xbc\x32\x54\xdf\x28\x70\xbd\x46\x51\ -\xe3\x19\xc1\x7d\x0f\xe0\xbe\x54\x48\x24\xf6\x7d\x7e\x20\x01\x49\ -\xa6\xfd\xab\x87\x7f\x09\xbe\x68\xed\xec\x8d\x21\xe4\xde\xcd\x53\ -\x44\x27\xbb\xac\xc4\xf1\x93\xc6\xe1\x07\x00\x0f\xa4\x42\x07\x99\ -\x09\x79\x2f\xd4\x7f\x0c\xf5\x7c\xa5\x52\xb9\x75\x50\x8d\x79\x49\ -\x0a\xe3\xe1\x30\xfc\x05\x4a\x4e\x02\x68\xa4\x42\x04\x07\xcf\x95\ -\xbb\xaf\x07\xd6\xa1\xe4\x64\x91\xe6\x91\x93\xa4\x10\x56\x56\xfe\ -\xb0\xc6\x24\xd7\x41\x3c\x9a\x4a\x27\x10\x0e\x7d\xd7\x43\x9f\x7d\ -\xbd\xf0\x7b\x92\x98\x67\x8f\x1f\x0f\xd6\x8a\xd6\x3a\xb2\x6f\xf6\ -\xf2\xf2\x9f\x0f\x96\xa7\x9a\xd7\x00\x3e\xd6\x13\x90\x00\x9a\x9c\ -\xf3\x03\x01\xb9\x52\x76\xc9\xeb\xd7\x9d\xe9\xa9\x53\x8f\x1c\x3b\ -\xf6\xf7\x28\x74\x8e\xec\x58\x3b\x3f\xff\xd0\x5f\x3b\xcd\xed\x05\ -\x08\x3f\xf7\x04\x48\x48\xea\xb9\x73\x6c\x6f\xa7\x95\x35\x4f\xdc\ -\xdc\x69\x6e\x2f\x8c\xca\xfc\x6e\xee\x91\xb2\xba\xba\x3a\x03\x33\ -\xf5\x0d\xa1\x33\xdd\xe5\x9d\xe7\xef\x3a\x22\xf2\x36\x38\x57\x9d\ -\x6b\xbd\x3c\x37\x37\xb7\x35\x4a\x7d\x63\x39\xc0\x48\x2a\xaf\xad\ -\xc5\x5f\x0a\x7c\x75\x90\xfa\x04\xbf\xaa\x54\x82\x25\x92\xad\x51\ -\x6b\x1b\xcb\xcd\x0e\xc9\x56\xa5\x12\xbe\x06\xe9\xb3\x3d\x2b\x8b\ -\x9f\x56\x2a\xc1\xe2\x38\xcc\x03\x63\xbc\xda\x22\xe9\xac\x0d\xdf\ -\x06\xf9\x41\xbf\x3a\x02\xdf\xb7\x36\x78\xa7\xf3\x87\xcc\x78\x74\ -\x8d\x2b\x51\x37\xab\xd1\xfa\x59\x42\x97\xba\x8a\x44\xe0\x4d\x6b\ -\xc3\x2f\xc6\xad\x65\x32\x97\x39\x00\x56\xa3\xf8\x02\x81\x45\x00\ -\x09\xc1\xb7\xac\x9d\xfd\x76\x52\x5a\x3c\x1e\x8f\xc7\xe3\xf1\x78\ -\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\xf7\x12\xff\x01\x83\xc1\x2a\x8b\ -\xb6\x49\x04\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x5e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ -\x99\xd1\x4b\x53\x51\x1c\xc7\xbf\xe7\x6c\x3a\x37\xca\xa2\x88\x1e\ -\xaa\x87\x46\x11\x24\x3d\x54\x90\x91\x09\xd1\x9c\x31\x91\x32\x2f\ -\x23\x7a\x4a\xe9\x6a\x10\x48\x7f\x40\xd0\x1e\xea\x2d\xa2\xde\x8a\ -\xb9\x2d\x1f\xd2\x82\xb5\x19\x8b\x2c\xb7\x52\x1f\xc2\x20\xb0\xa8\ -\xcc\x12\xb4\x1e\xca\x82\xc8\x32\x57\x8e\x9c\x3b\xa7\x27\x69\x5e\ -\xaf\x0d\xc1\x73\xae\xd0\xf9\x3c\x7e\x7f\xb0\xef\xf7\x7e\xef\xd9\ -\xce\xb9\x77\x80\x42\xa1\x50\x28\x14\x0a\x85\x42\xa1\x50\x28\x14\ -\x8a\xff\x0d\x22\xda\xc0\xab\xe9\x1d\x00\x8e\x03\x00\x38\x69\x4c\ -\xc5\x5b\xdb\x44\x7b\x2e\x06\xa1\x05\x1c\x68\x68\x28\x29\x4a\xdb\ -\x33\xf9\x1a\xe5\xec\x60\x77\x3c\xd2\x2b\xd2\x77\x31\x50\xa1\x9f\ -\xfe\xcb\x65\x37\x4a\x8c\xd0\x1e\x4f\x7d\xa3\x5b\xa8\xef\x22\x90\ -\xf1\x15\xe0\x66\xba\x33\xcb\x4a\x13\x89\x48\x5a\xb4\x7f\x21\xc4\ -\xae\x00\x00\xab\xe9\x8f\x79\xab\x00\x00\x32\x45\x74\x32\x10\x08\ -\x08\xf7\x2f\x84\xf0\x00\xd1\x68\x34\x67\x2f\xc9\xac\x32\x9b\xf5\ -\x0f\x8e\xe5\x44\xfb\x17\x42\xca\x1d\xb8\xdf\xde\x3e\x49\x29\xdf\ -\x6a\x36\xf3\x6a\xfa\x63\x19\x19\x16\x42\xda\x12\xec\x8e\x86\x47\ -\x40\x78\x95\xc9\xa8\xa2\x5a\x6b\xba\x28\x2b\x87\x11\x9b\x4c\xb3\ -\x77\x43\xcf\xdf\xbb\xb7\xef\x1c\x27\x20\x35\x86\xd1\xbe\x2d\x65\ -\xbb\x47\x46\x87\x9e\xbd\x92\x99\x07\x90\xb0\x0b\x98\xe1\xd5\xf4\ -\x36\x00\x27\x8c\x3a\xa5\xbc\xbc\x3b\x1a\x7e\x2a\x33\x8b\x25\x05\ -\x00\x80\x57\xd3\x47\x01\xcc\x3f\x0f\x64\xd9\x86\x54\x22\xf2\x49\ -\x56\x0e\xcb\x0a\x00\x16\x3e\x23\xfc\xa4\x2b\x5d\x4f\xa2\x97\x33\ -\x66\xb3\xa5\xc6\xd2\x7d\xf8\xdb\x5a\x5a\x6c\xa6\xaf\x60\xe9\x29\ -\x48\xba\x39\x96\x16\x30\x10\x0c\x66\xb3\xc5\x74\x9d\xd9\xcc\xab\ -\xe9\xdf\x65\x64\xb0\xfc\x24\xd6\x77\x33\xf8\x95\x30\xbe\xc3\x64\ -\xb4\xaa\x4a\xd3\x6f\x89\xf6\xb7\xbc\x00\x00\x48\x76\x86\x07\x39\ -\x41\x9d\x51\x27\xc0\x31\xd1\xde\xcb\xa2\x00\x00\xa0\x9c\x0e\x5b\ -\xe2\x6b\x85\xa9\x11\xcf\x61\x7d\x3d\x07\xeb\x32\x19\xf5\x8b\xf6\ -\xb6\xbc\x80\xda\xda\x66\x17\xb5\x23\x01\x60\xf3\x9c\x01\xc7\xf9\ -\x54\x2c\x54\x21\xda\xdf\xd2\x02\xfc\x7e\xbf\x6d\xda\xc1\x3a\x40\ -\xb0\x27\x5f\x27\xe0\xad\xa9\x78\x28\x20\x23\x83\xa5\x05\x4c\xb0\ -\xd2\x4b\x1c\x38\x92\xaf\x11\x82\x07\xd3\xe3\x1b\x4f\x03\x30\x3d\ -\x24\x2d\x35\x16\x1e\x85\x9b\xce\x00\xfc\xca\x5c\x95\xbc\x70\x66\ -\x73\x95\x32\xdf\x14\x59\xf3\x30\x54\xdf\x74\x14\x84\xc7\x0c\xfe\ -\x1f\x73\xd4\xbe\xb7\x27\x7a\x6d\x4c\x66\x16\xe9\x05\x54\x6b\xcd\ -\xe5\x1c\xac\x17\x80\x73\x56\xe3\x40\x9a\x03\xfb\x1f\xc5\x42\x2f\ -\x65\xe7\x91\xfa\x1b\xe0\xa9\x6f\x74\x73\xb0\xbb\xc8\xbb\x78\x00\ -\x33\x94\x41\xb3\xe2\xe2\x01\x89\x05\x1c\xf2\x9f\x5c\x43\x88\xad\ -\x0b\xc0\x9c\xb3\x3f\x01\x3f\x95\xec\x0c\xa5\x64\xe5\x30\x22\xa5\ -\x00\x9f\xaf\xc5\x91\x63\xe4\x0e\x01\xb6\xe5\xeb\x9c\xf0\x0b\xc9\ -\x58\x38\x22\x23\xc3\x42\x08\x2f\x20\x10\x08\xd0\x19\x57\xe6\x3a\ -\x01\x2a\x0d\xa3\x1b\x0f\x6f\x87\xcf\x89\xf6\x2f\x84\xf0\x02\xfa\ -\x5f\x8f\x9d\xc5\xec\x7f\x83\x7f\xe9\xb3\x4f\x39\x75\x48\xda\xeb\ -\xff\x85\xd0\x5d\xc0\xe7\x6b\x71\xcc\xb8\x32\x13\x00\x4a\xf2\xe4\ -\x37\xc5\x8e\xa2\x8a\x7b\x1d\x57\xa5\x3c\xef\x17\x42\xe8\x0a\xf8\ -\xb2\xe9\x37\xe3\x40\x36\x5f\xb2\xe5\xec\x35\xcb\xe5\xe2\x01\xc1\ -\xaf\xc5\x3f\x0f\x0c\x30\x77\xd9\xae\x61\xc2\xe1\xe1\x04\x1f\x08\ -\x25\x75\xc9\x78\xf0\xad\x48\x4f\x85\x42\xa1\x50\x28\x14\x0a\x85\ -\x42\xa1\x50\x28\x14\x8a\x42\xfc\x01\xea\x12\xdd\x53\xe7\x12\x49\ -\xf2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x06\xb5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\x67\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x70\x5b\x57\x15\xc7\x7f\xe7\x2a\x85\x94\xd0\xa4\x4d\x3f\ -\x67\x18\x16\x0c\xbb\x34\x49\x93\x36\xb4\x14\x18\x68\xac\x2f\xa7\ -\x8d\xed\xda\x8a\x76\x6d\x67\x62\xd9\x1e\xd6\xac\xca\x02\x16\x4c\ -\x16\x6c\xd8\x32\x53\x5b\x76\x57\xed\x46\xb6\x34\x0c\x4d\x1b\x3f\ -\xe9\xc9\xe5\xa3\x84\x0e\xe5\xa3\x2d\x30\xcc\x74\x4a\x17\xdd\x51\ -\x0a\xc4\x69\x6a\x3b\x13\xdd\xc3\xc2\x92\x31\xfa\xbc\x4f\x7a\xcf\ -\x36\x83\xff\xcb\x7b\xcf\x3b\xe7\xfc\x7f\xbe\xf7\x3e\x3d\xe9\x19\ -\xf6\xb5\xaf\x7d\xfd\x3f\x4b\xda\x0d\xa6\x9e\x7d\xf6\x90\xae\x7d\ -\xf6\x3b\x28\x23\xc0\x41\x85\xab\xc6\xf0\x43\xaf\x90\xff\x60\x87\ -\xfb\xeb\x4b\xa9\xec\xd4\x97\xac\xe5\x79\x81\xc7\x81\x75\x55\x2e\ -\xdf\x8a\x7d\xe6\x47\xaf\x17\x7e\xfc\x49\x73\x6c\x0b\x80\xd1\xd1\ -\xc9\x3b\xd6\x6e\x33\x3f\x03\x4e\x37\x4d\x5d\x13\x4c\xda\x5b\x9a\ -\x7d\x33\xa2\xbe\x43\x51\x7c\x62\xfa\x2b\x46\xb4\x0c\x1c\xf9\xef\ -\x19\x79\xfb\xc0\xc1\x4f\xbf\xf9\xda\x4b\x2f\xad\x6e\x1f\x35\xcd\ -\x09\xd6\x0e\x98\xe7\x69\x35\x0f\x70\x44\x51\x2f\x95\x99\x79\x2c\ -\xc4\x7e\x43\x55\x67\xf3\x00\xfa\x50\x6d\xfd\xf6\xef\x36\x8f\xb6\ -\x00\x40\x18\xed\x5c\x42\x0f\xef\x55\x08\xdd\xcd\x6f\x4a\x61\xac\ -\x79\xac\x05\x80\xc0\xed\xdd\x4b\x6d\x42\x48\x67\x73\x8f\xf6\xd1\ -\x67\x24\x4a\x66\x26\xcf\xf4\x32\x5f\xd7\xc1\xe6\x81\xd6\x15\xa0\ -\xbc\xd1\xbb\xa4\x1e\xb6\xd6\x94\xf7\x02\x84\x64\x66\xf2\x0c\x98\ -\x0a\xbd\xcd\x03\xad\xde\x5a\x00\xa8\xc4\x2e\x01\xd7\x7a\xe7\xda\ -\x7d\x08\xc1\xcc\xcb\x2a\xc4\x7e\xd0\x3c\xda\x02\xa0\xbc\xf4\xc2\ -\x7b\xc6\x68\x0a\x67\x08\xb2\x2b\xdb\xa1\x6e\xde\x65\xd9\x03\xb2\ -\xaa\xaa\xe9\xf2\xd2\x0b\xef\xb5\xcc\x74\xba\x24\x9d\xcd\x3d\x6a\ -\xad\x29\x83\x1e\x76\xe8\xe7\x9a\x55\x49\xfa\xc5\xb9\xdf\x38\xc4\ -\x0e\xac\x54\x76\xea\x11\xb5\x54\x80\x3b\x7b\xc5\x2a\x5c\x47\x49\ -\x55\x8a\xf9\x5f\xb7\x9b\xef\x08\x00\xf6\x26\x84\x30\xcd\x43\x0f\ -\x00\xb0\xb7\x20\x84\x6d\x1e\x1c\x00\x00\xa4\x32\x33\x8f\x29\xea\ -\xb9\x42\x00\x9b\x28\x2f\x2d\xbc\xe5\x92\xdb\x55\xe9\x89\x99\x87\ -\x2d\xb6\x82\x70\x57\xaf\x58\x85\xeb\x6a\x6c\xda\x2f\x2c\x5c\xed\ -\x15\xeb\x04\x00\x76\x17\x42\x54\xe6\xa1\xdd\xe7\x80\x0e\xf2\x96\ -\x66\xdf\x54\xd5\xf4\xe6\xed\xa4\xa7\x8e\x80\xa9\x6c\x9e\xd4\x83\ -\x29\xa8\x79\x23\x32\xec\x6a\x1e\x02\xac\x80\x86\x12\x13\x53\x5f\ -\x45\xf0\x04\xee\x70\x08\xff\x17\xd8\x64\xbf\x2b\x21\x88\x79\xe0\ -\x13\x11\x49\x7b\x8b\x73\xbf\x0a\x52\x23\x30\x00\x08\x0e\x41\x0c\ -\x09\xaf\x90\xff\x6d\x90\x1a\x3b\x61\x1e\xfa\x04\x00\xd1\x42\x48\ -\x64\x72\xa7\x45\xc5\x8f\xda\x3c\x0c\x00\x00\x20\x9e\x9d\x7c\x5c\ -\xac\x59\x0e\x13\x42\x50\xf3\xa8\x0e\x97\x8b\xf3\x0e\xcf\x2f\xed\ -\x35\x10\x00\x08\x17\xc2\x4e\x9b\x87\x00\x77\x81\x4e\xf2\x0b\x0b\ -\x57\x8d\xc8\xb0\xc2\x75\x87\xf0\x3b\xb5\x46\x39\x3d\x31\xf3\x70\ -\xf3\x44\x22\x93\x3b\x2d\x88\xf3\x9e\x57\x63\xce\x0d\x6a\x1e\x42\ -\x58\x01\x0d\xa5\x2e\x4c\x7f\x4d\x55\x97\x81\xcf\xf7\x0c\x56\xfe\ -\x69\x30\x89\xe5\xe2\xec\xef\x00\x92\xd9\xe9\x53\x58\xf5\x81\xa3\ -\x0e\xa5\x6e\xa8\x31\xc3\x95\xc2\xec\x2f\x07\xeb\x78\x53\xa1\x01\ -\x80\xfe\x20\xd8\x98\xda\xdd\x32\x0f\x21\x03\x80\x80\x10\x44\x57\ -\x51\x00\x71\xf9\x74\x19\xba\x79\x88\x00\x00\x40\x72\x22\xf7\x75\ -\x44\xae\xe0\x02\xc1\x4d\x37\x8c\x70\x6e\x79\x31\xff\x8b\x90\xf2\ -\x6d\x29\x12\x00\x10\x2a\x84\xc8\xcc\x43\x08\x77\x81\x4e\x2a\x17\ -\xe7\xdf\x50\x63\xce\x01\x2d\x3f\x46\x04\xd0\x0d\x51\x7d\x32\x2a\ -\xf3\x10\xe1\x0a\x68\x28\x91\x9d\xf9\x86\x58\x7b\x05\x38\x14\xf0\ -\xd2\x1b\xa2\xfa\xa4\x57\x9c\xff\x79\x14\x7d\x35\x14\x39\x00\xa8\ -\x43\xa8\x59\x0f\xe9\xf5\x95\x7b\x5d\xc2\xba\x58\x4d\x47\x6d\x1e\ -\x22\xdc\x02\xdb\xa5\xd6\xae\x22\x72\xd3\xfd\x02\xbd\xa9\x31\xe3\ -\xf2\xd8\x3d\xb0\x22\x07\x10\xcf\x4c\x9d\x34\x50\x05\x75\xf9\xde\ -\xbe\x2e\x39\x8c\x55\x3f\x99\x9d\x3e\x15\x5d\x67\xf5\x4a\x51\x26\ -\xff\x8f\x79\xee\xee\x33\xc5\x3f\x30\x12\x2f\x17\xe6\xfe\x10\x66\ -\x5f\xdb\x15\xd9\x0a\x88\x67\xa6\x4e\x1a\xc5\xa7\x7f\xf3\x00\x47\ -\xb1\xea\xa7\xc7\x27\x1f\x0a\xab\xaf\x66\x45\x02\x20\x91\x9d\x39\ -\x61\x14\x1f\xe1\x9e\x10\xd2\x1d\xb5\xc6\x54\xa3\x82\x10\x3a\x80\ -\x44\x76\xe6\x84\xd4\x6c\xd5\xc5\xbc\xc0\x86\xc2\x86\x43\xda\xa3\ -\xd6\x98\x48\x56\x42\xa8\x00\x82\x98\x07\xd6\xac\x30\x6c\x54\x53\ -\xc0\xa7\x0e\xf1\x77\x47\x01\x21\xbc\xc7\xe1\xf1\xdc\x71\x15\x59\ -\x71\x35\x6f\xd4\x3e\xb5\x5c\x5c\x58\x01\x48\x66\xa7\xbf\x85\xd5\ -\x57\x81\xcf\x39\x5c\xfb\xb1\x85\x21\x7f\x29\xff\xce\x40\x0d\xd7\ -\x15\x0a\x80\x41\xcc\x37\xb4\x5b\x10\x06\x06\x10\xd4\xbc\x58\xce\ -\x7b\xa5\x7c\xb5\xdd\x64\xe2\xc2\xd4\x13\xa2\x5c\x66\x07\x21\x0c\ -\x74\x06\xa4\xc6\x73\xc7\xd5\x88\xf3\x9e\xef\x66\x1e\xa0\xb2\x98\ -\x7f\x5d\x85\xa7\x70\x3c\x13\x8c\xe2\xc7\x33\x53\x27\x9d\x1b\x6e\ -\xa3\xbe\x01\x6c\x99\x87\x7b\x1d\xc2\xd7\x10\x1d\xe9\x66\xbe\xa1\ -\x6d\x10\xd6\x7a\x66\x15\xee\x31\x8a\x9f\xc8\xce\x9c\x70\xe8\xa1\ -\x43\x8a\x3e\x94\xce\x4c\x3f\x68\xd1\x15\xdc\xcc\xaf\x23\x7a\xbe\ -\xbc\x38\xef\x07\xa9\x51\xdf\x0e\xaf\xd2\xf3\x9d\x25\x40\xf9\xbb\ -\xc6\xcc\x50\xa5\x30\xfb\x6e\x90\x1a\xd0\x07\x80\x9d\x30\xbf\x55\ -\x6b\x62\xf2\xac\x15\x73\x99\x08\x21\x04\x02\x50\x37\x5f\x05\xee\ -\x73\x08\x1f\xc8\xfc\x56\xcd\x80\x10\x44\xf5\xac\x57\x9a\xff\xa3\ -\x6b\x7e\x67\x00\x41\xcd\x5b\x95\x11\xbf\x38\x57\x71\xcd\xdf\x4d\ -\xa9\xf1\xa9\x21\x35\xbc\x42\x04\x10\x9c\x0e\xc1\x78\xf6\xe2\xb1\ -\xdd\x32\x0f\xe0\x95\xf2\x55\xb1\x9c\xc7\xf1\x60\x54\x91\x95\xd4\ -\x78\xee\xb8\x4b\xee\x9e\x00\xe2\xd9\x8b\xc7\x8c\x8d\xad\xe0\x68\ -\x5e\x2c\xa3\x61\x9a\x6f\xc8\x2b\xe5\xab\x88\x8e\xe0\x0a\xc1\x48\ -\xd5\x05\x42\xd7\x2d\xd0\x8f\x79\xaf\x94\x2f\x3b\xc4\xf6\xad\xe4\ -\x85\x5c\x1c\x95\x57\x68\xf3\xd6\x67\x1b\x7d\x24\x56\x87\xba\x6d\ -\x87\x8e\x2b\x20\x9e\xbd\x78\xcc\x68\x2c\xc0\x81\x67\xc7\xa2\x36\ -\x0f\x50\x5e\x9c\xf7\x11\x3d\x0f\xac\x3b\x84\xdf\xab\x46\xaa\xe9\ -\xcc\xf4\x83\x9d\x02\xda\xae\x80\x2d\xf3\xca\xfd\x0e\x45\x36\x10\ -\x3b\x5a\x5e\x5c\xf0\x1c\x62\x43\x53\xd0\x95\x60\x90\xb3\xcb\x4b\ -\x73\x7f\x6a\x9e\x68\x01\x30\x94\xfd\xf6\x17\x0e\xd8\x5b\x6f\x29\ -\x3c\xe0\x90\x78\x57\xcc\x37\x14\x9f\x98\x4e\x18\xd1\x9f\xe2\x06\ -\xe1\x6f\x72\xab\x76\xc6\xfb\xc9\x8b\x1f\x6e\x1f\x6c\xd9\x02\xb1\ -\x5a\xed\x7b\xff\x0b\xe6\x01\xfc\xe2\x5c\xc5\xaa\x8c\xe0\xb6\x1d\ -\xee\xd3\x58\xec\xfb\xcd\x83\x6d\x5e\x96\xd6\x27\x1c\x92\x6d\x28\ -\x32\xb6\x9b\xe6\x1b\xf2\x8b\x73\x15\xb1\x8c\xe2\x00\x41\x84\xb3\ -\xcd\x63\x6d\xfe\x5f\x40\x6a\x3d\xf2\x6c\x28\x32\x56\x59\x9a\x5b\ -\x76\x6f\x33\x5a\x79\xa5\x7c\xd9\x05\x82\x42\x8b\xb7\x56\x00\xa2\ -\xdd\xfe\xaa\x1b\xd6\xea\xd3\x7b\xc9\x7c\x43\x5e\x29\x5f\x46\xec\ -\x18\xdd\x21\x5c\x69\x1e\x68\x01\x50\xab\xdd\xbc\x24\xf0\x7e\x9b\ -\x8b\x37\xac\xd5\xa7\xfd\xd2\x7c\x4b\x92\xbd\xa2\xf2\xe2\x82\xd7\ -\x05\xc2\x07\x07\x4c\xed\x52\xf3\x60\xac\x25\xea\x2f\x6f\xaf\x7d\ -\xf1\xd4\x99\x97\x63\x35\x3d\x04\xdc\x0f\xdc\x44\xd4\x37\x1a\x7b\ -\xae\x5c\x8a\xee\x57\xda\xb0\xf4\xd7\x3f\xff\xfe\xfd\x2f\x1f\x7f\ -\xe4\xb2\xaa\x3c\x20\x9b\xef\x1b\x7d\xac\xaa\x2f\xdf\x16\xb3\xcf\ -\xbc\x56\x78\xf1\xa3\xdd\xee\x6f\x5f\xfb\xda\xd7\xde\xd2\xbf\x01\ -\xee\x83\x44\x52\xf4\x9c\x9a\x3b\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x03\x62\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x14\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3b\x68\x14\x51\x18\x85\xcf\x99\x5d\x30\x62\xb0\x11\x11\x31\ -\x85\xc1\x58\x08\x01\x0b\x61\x77\xed\x02\xbe\x30\x85\x8f\x0d\x31\ -\x60\x97\x80\xa8\xa4\xb3\x09\x29\xad\x8c\xa5\x90\x20\x5a\x58\x5a\ -\x24\xee\x86\x20\x24\x82\x0a\x16\x82\xd9\x80\x45\x24\x85\x85\xa2\ -\xc5\x82\x88\x58\x28\x3e\x12\xdc\x9d\x63\x13\x44\x77\x66\x77\x33\ -\x33\x7b\xf7\x26\xce\x7c\xe5\x9d\x9b\xf3\x9f\x39\x99\xc7\xbf\x77\ -\x2e\x90\x90\x90\x10\x67\x18\x55\xa0\x6f\x5a\x9d\xab\x69\x8c\x0a\ -\x1a\x14\xd0\x4b\x60\x5b\x2b\x8c\x85\x45\xc0\x1a\x81\x15\x82\x33\ -\x1d\x15\x4c\x3d\xbb\xc0\x6f\x8d\xe6\x47\x0a\x20\x5b\xd4\x09\x40\ -\xf7\x00\x74\x45\xd1\x31\x48\x19\xe0\x48\x29\xcf\xc7\xf5\x26\x38\ -\x61\x95\xb3\x45\x8d\x00\x7a\x84\xcd\x7b\xf2\x00\xd0\x05\x68\x21\ -\x5b\xd4\x70\xbd\x09\xa1\xae\x80\xec\xac\x4e\x42\x5a\x40\x84\x00\ -\xdb\x4c\x15\xe0\x69\xbf\x2b\x21\x70\x00\x7d\xd3\xea\xfc\x99\xd6\ -\x6b\x00\xfb\x5a\x62\xad\x7d\x94\xb7\x57\x78\xa8\xf6\x99\x10\xf8\ -\x3f\xb8\x9a\xc6\x28\xb6\xde\xc9\x03\x40\xd7\xba\xf7\x7f\x08\x1c\ -\x80\xa0\xc1\xd6\xf8\x69\x3f\x7e\xde\x43\x04\x80\xde\xd6\xd8\x69\ -\x3f\x7e\xde\xd3\x41\x45\x9a\xbd\xe7\x4b\x79\x27\x72\x6f\x11\x85\ -\x6c\xd1\x55\xbd\x63\x7e\xde\xb7\xca\x53\xdc\x18\x49\x00\xb6\x0d\ -\xd8\x26\x09\xc0\xb6\x01\xdb\x24\x01\xd8\x36\x60\x9b\xd8\x07\xd0\ -\xb4\x11\x3a\x52\xd0\xde\xb4\xe3\x5e\x95\xcb\x63\x20\xf6\x34\x9b\ -\x9f\x29\xba\x6f\xc2\x9a\xa1\x20\x10\x65\x81\xf3\xec\xc0\x9d\x52\ -\x3f\xbf\x86\xd5\xda\x70\xcd\x46\x07\x73\x05\x9d\x11\x75\x0f\xc0\ -\x2e\xd3\x46\x3c\x08\xef\x00\x5e\x2c\x0d\x70\x31\xc8\x9f\x35\xea\ -\x04\x01\x6f\xa7\x5a\xf7\x16\xc8\x14\xab\x13\xa2\xe6\x60\xe3\xe4\ -\x01\x80\xe8\x06\xf5\x3c\x53\xd4\x15\x93\x65\x7c\x03\xc8\x15\x34\ -\x44\x70\xcc\x64\xe1\x0d\x92\x22\x34\x99\x2d\x28\x67\xaa\x80\x27\ -\x80\xdc\xac\xf6\x8b\xba\x6b\xaa\x60\x08\x52\x80\xee\x67\xe7\xb5\ -\xd3\x84\xb8\x27\x00\xb9\xee\x38\x00\x23\xc5\x42\x43\x74\x6b\x15\ -\x97\x4d\x48\x7b\x6f\x01\xb2\xdf\x44\xa1\xa8\x10\x32\xe2\xcb\xef\ -\x19\xb0\x39\x57\x79\x65\xc6\x57\xe0\x05\x11\x27\xc5\x83\x26\x8c\ -\xa0\x8a\x1e\x17\x5a\xa8\x77\x58\x8c\xfe\x11\xc7\x8f\xc0\x01\xbc\ -\x38\xcb\xd0\x8d\x4e\x23\x8e\xce\x09\xa8\x9a\x50\x6e\x4c\xec\x5b\ -\xe1\x24\x00\xdb\x06\x6c\x93\x04\x60\xdb\x80\x6d\x92\x00\x6c\x1b\ -\xb0\x4d\x12\x80\x6d\x03\xb6\x49\x02\xb0\x6d\xc0\x36\x49\x00\xb6\ -\x0d\xd8\x26\xf0\xaf\x41\x5b\x10\x38\xd0\x6c\xc5\xb7\x19\x02\xd6\ -\x6a\xc7\x62\x75\x05\x10\x58\xa9\x1d\x8b\x59\x00\x9c\xa9\x1d\x8b\ -\x53\x00\xe5\x8e\x0a\xa6\x6a\x07\xe3\x12\x40\x15\xe0\x88\xdf\xbe\ -\xe1\x38\x04\x50\x05\x78\xa9\xde\x7e\xe1\x2d\xf3\x16\x08\x49\xd3\ -\xcd\xd2\xff\x5d\x00\x7f\x6f\x97\xff\xb1\x03\x93\xaf\x4e\xf1\x7b\ -\xa3\xf9\x9e\xa5\xe6\xa8\xef\x5a\x53\x08\x78\xbb\x94\x77\x7a\x5a\ -\xad\xeb\xfd\x34\x06\x7c\x6a\x75\x91\x96\x20\x7c\x34\x21\xeb\x09\ -\x80\xd0\x13\x13\x85\xa2\x42\x47\x4f\x4d\xe8\xfa\x5c\x01\xce\x4d\ -\x00\xbf\x4c\x14\x8b\xc0\xe7\x8a\xeb\xdc\x36\x21\xec\x09\x60\x29\ -\xcf\x65\x6d\x8e\xbd\x01\x7f\xa0\xc3\xe1\x97\x03\xfc\x60\x42\xdb\ -\xb7\x0f\x58\x5a\xc6\x2d\x00\x0f\x4c\x14\x0c\x8e\x26\x16\xcf\xf1\ -\xa1\x29\x75\xff\x46\xe8\x3a\xdd\xd2\x32\x87\x04\x5e\x83\xbd\xdb\ -\xe1\x0b\xc9\xa1\x52\x3e\x35\x6e\xb2\x48\xd3\x2f\xae\x99\xa2\x0e\ -\x13\xee\x98\xc0\xe3\x04\x76\x9b\x34\xb3\x4e\x19\xd2\x3c\x1d\xe7\ -\xc6\xe2\x79\xbe\x6f\x43\xbd\x84\x84\x84\x18\xf3\x1b\xe9\x0c\xd1\ -\x12\xec\xcb\x09\x01\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\x79\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2b\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x6f\x28\x98\x05\xfc\x5b\x00\ -\x19\xc7\x23\x31\xd0\x56\x01\x00\x61\xbd\xe7\xdc\xe4\xc0\x4a\xc6\ -\x01\x80\x2f\x3c\x1a\xe8\x01\xff\xf7\xcd\x6b\x25\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x4a\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\x3f\x4a\xc4\x40\x14\xc7\xf1\xef\x4b\x16\xbd\x81\x5b\x78\x02\ -\xd7\xca\x2a\x60\xb7\xf1\x00\x0b\xf1\x40\x7a\x22\x21\xd8\x08\xc2\ -\x6e\x27\xa4\x5e\xff\x9c\xc0\x42\x2b\x0f\xb0\xe1\x59\x84\x28\xc4\ -\xc4\x99\x97\x9d\x89\x85\x53\xce\x3c\xf8\xfc\x98\x79\x3c\x06\xfe\ -\xfb\x92\x29\xb1\xac\xd4\x39\x3b\x2d\x11\x5e\xab\x22\xb9\x04\x48\ -\x26\xc5\x6b\xdd\x20\x64\x28\xc7\xed\xfe\x24\x01\xbe\x70\x38\x01\ -\x5e\x98\xc9\xaa\x3d\x8b\xfe\x04\x3f\xf0\x54\x96\xd5\x4a\xde\x26\ -\x09\xe0\xc2\xa3\x06\xf0\xc1\xa3\x05\xf0\xc5\xa3\x04\xb0\xe0\xc1\ -\x03\x58\xf1\xa0\x01\xc6\xe0\xc1\x02\xf8\xe2\xe7\x37\x7a\xb4\x13\ -\xbd\x13\xe5\xa3\x2a\x92\x1c\x02\x0c\x22\x0b\x5e\xa3\x6b\x51\xce\ -\x80\x83\x76\x7f\x36\x25\x0e\x9c\x0a\x3c\x26\x48\xd1\x9e\x8d\x7e\ -\x82\x3d\xf0\x8b\x87\x42\xde\xf7\x0a\x10\x0a\x1f\x15\xc0\x88\x6f\ -\x80\x05\xf0\x94\x22\x79\x17\x37\x07\x08\x8d\x9b\x02\xc4\xc0\x01\ -\xd2\x90\x78\x56\xea\x5c\xd5\x1f\x07\x8f\x1b\xb0\xe0\xd4\xba\xb6\ -\xe0\xce\x00\x23\xf1\xe7\x14\x59\xf6\xe1\xa6\x49\x18\x03\xf7\x9e\ -\x84\x91\xf0\x0d\xb0\x70\x4e\x42\x23\xde\xd6\x0d\xe2\xae\xde\x90\ -\x9e\x62\x33\x4e\x2a\xf9\xd8\xc6\x94\x4e\x71\x68\xdc\x79\x43\x4d\ -\x13\x5e\x69\x42\xad\xf7\x2e\x1c\x55\x91\x5a\x6f\x5d\x78\xb7\x6e\ -\x08\xff\x0e\xd0\xac\x43\x60\xfb\xeb\x4f\xe6\x1a\xd1\xa6\x83\xb7\ -\x83\x78\x4f\x9d\xcf\x3c\x68\x6e\x41\xd5\x3d\x9a\x55\x25\x68\xdd\ -\x5f\xaf\x4f\xda\x1b\xa3\x91\x9e\x7b\xef\x4a\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xa6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x58\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\xdc\x7f\xf8\xb8\xe1\xfe\xc3\xc7\x0d\x94\x98\xc1\x44\ -\x89\x66\x6a\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\ -\xa8\x03\x06\xdc\x01\x2c\x14\x9b\xf0\x9f\xc1\x81\x92\x2a\x79\x18\ -\x84\x00\x23\xc3\x01\x45\x79\xd9\x06\x72\xb5\x0f\x78\x08\x8c\x3a\ -\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\xe0\x0e\x00\ -\x00\xe6\xf7\x0c\x89\x70\x77\x76\x17\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\x50\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x02\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x2d\x4e\x03\x51\x14\xc5\xf1\x73\x29\xe1\x4b\xa0\xc0\xb3\x01\ -\x92\x0a\x7c\xc7\x15\x3c\x86\xd4\x23\x31\x2c\xa0\x99\x05\x74\x07\ -\x4d\x05\x49\x25\xa6\x09\x81\x86\xb0\x08\x76\x80\x22\x21\x75\x08\ -\x98\x66\xca\xbb\x58\xf2\x1e\x04\x35\x8f\x84\xf9\xff\xe4\xb9\x23\ -\xce\x1c\x33\x23\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xad\x60\ -\xbf\xdd\x8b\x62\xd8\xc9\xd2\xa4\x21\xbd\x9e\x42\x59\x96\xe1\xa7\ -\xfb\xb7\x03\x14\x67\xe7\x7b\x1b\xcb\x30\x72\xd3\xa9\xa4\x9d\xc6\ -\xda\xe5\x51\x99\xfc\xc6\x6b\xbf\xb8\x9f\x4d\x9e\xe3\x63\x32\xc0\ -\xc9\x60\xb0\xbb\xaa\xb6\x1e\x25\x3b\xc8\x50\x2e\xa7\x45\xa8\x75\ -\xf8\x30\x1b\xbf\x7c\x0d\xd7\xe2\xa7\x3e\x96\xdb\xe5\x3f\x7c\x79\ -\x49\xda\xb7\x75\x8d\xe2\x30\x19\xc0\x5d\xfd\x3c\x7d\xf2\x33\xd3\ -\x71\x9c\x25\x03\xb4\x4d\x32\x80\x99\xe6\x7f\x51\x24\x07\x77\xdd\ -\xc5\x59\x32\x40\x67\xf3\x7d\x28\xf9\x53\x96\x46\x79\x2d\x7c\xa5\ -\xcb\x38\x4c\x06\xb8\x9d\x4e\x5f\x43\xa8\x8f\xcc\x75\x25\xe9\x2d\ -\x4b\xb5\x66\x55\x26\xbf\x56\x1d\xba\xf1\x17\x40\xe2\x47\x08\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x68\x8b\x4f\xc6\xe5\x42\x89\xb1\ -\xed\x97\x86\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x27\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x68\x5c\x55\x14\xc6\x7f\xe7\xcd\xb4\x5a\x8c\x08\xb6\xba\ -\x30\xa8\x2b\x51\xd4\x8d\x50\x84\x22\x48\x6c\x27\x89\x41\x0c\x76\ -\xc6\xd1\x95\xd8\xfc\x99\x50\x17\xa2\x05\x45\xf0\x0f\xe3\xd0\x8a\ -\x15\x04\x17\x22\xb6\x49\xa6\xc6\x45\x8a\x9a\x26\x0d\xa1\x1a\x3b\ -\x49\x64\x0a\x8a\x20\x28\x08\xc5\x85\x20\xe2\xa2\x41\x04\xad\x14\ -\x6d\x0b\x93\xb9\xc7\x45\x1c\x79\xf3\x66\xc0\x14\xdf\xbd\xef\x62\ -\xe6\x5b\x7e\x1f\xdc\x73\xee\x77\xce\xfd\xf7\x98\x81\x0e\x3a\xe8\ -\x60\x33\x43\x92\x4e\x60\xa3\xc8\x64\x47\x8b\x22\xf2\x32\x18\x51\ -\xd5\x43\xcb\x73\xc7\x5e\x8d\x63\xdc\x20\x8e\x41\x6c\xa3\x3f\x3b\ -\xfc\x00\x42\x11\x34\x0d\x92\x12\x09\x5e\x89\x6b\xec\x74\x5c\x03\ -\xd9\x42\x6f\x6e\x78\xa7\x21\x58\x90\xe6\x6e\x8d\xad\x70\x5e\x77\ -\x40\x5f\x6e\xec\x0e\x34\x58\x04\xba\x22\x92\x89\x2b\x86\xb7\x06\ -\x64\xf2\x63\xb7\x28\xa6\x82\xb0\xa3\x8d\xac\x71\xc5\xf1\xd2\x80\ -\x81\xfc\xd0\x0d\x18\x53\x01\x6e\xb6\x1d\xcb\x3b\x03\x06\x07\x87\ -\xaf\x5d\x33\xa9\x4f\x04\x6e\x77\x11\xcf\x2b\x03\x7a\xf6\xed\xbb\ -\xfa\xd2\xd6\x60\x1e\xd8\x19\x91\x62\x6b\xf9\x28\xbc\x31\xa0\xa7\ -\xa7\x98\xde\xf2\x47\xfa\x38\xca\xee\x88\xa4\xc4\xb8\xe9\x45\xe1\ -\x8b\x01\x92\xde\xbe\x7a\x14\x65\x6f\x13\xab\x6a\x75\xf2\xe0\x89\ -\x01\x99\xdc\xe8\x1b\x82\x0e\x47\x68\x45\xc4\xea\xe4\xc1\x03\x03\ -\x7a\x1f\x2d\xbc\x20\xf0\x7c\x1b\xc9\xfa\xe4\x21\x61\x03\x32\xb9\ -\x42\x01\xd5\xc3\x6d\xa4\xba\xab\x1c\x12\x33\x20\x93\x2b\xe4\x04\ -\x3d\xd2\x44\xae\xef\xf5\x4e\x2a\xdf\x40\x22\x06\xec\xc9\x16\x32\ -\x82\x1e\x6f\x89\x1f\x60\xb0\x78\xe4\xb5\x83\x73\x03\xfa\xf3\x23\ -\xf7\x06\xa2\xf3\xc0\xd6\x88\x64\x50\xb7\x93\x07\xc7\x06\xec\xc9\ -\x0f\xdd\x69\x8c\x2c\x02\xd7\x84\x79\xc1\x7d\xe5\x1b\x70\xf6\x1c\ -\xde\x9d\x1d\xb9\x35\x30\x52\x01\xae\x8f\x48\x46\x13\x9a\x3c\x38\ -\xea\x80\xbe\xbd\xfb\x6f\x4c\x09\x4b\x40\x77\x98\x17\x24\xb1\xca\ -\x37\x60\xbd\x03\x32\xf9\xb1\xeb\xd4\xac\x7d\x0a\x72\x5b\xb3\xa2\ -\x9a\x64\xe5\x1b\xb0\xda\x01\xbb\xf2\x07\xb6\x89\x31\x0b\xc0\x3d\ -\x11\x49\xc1\xfe\x2d\x6f\x23\xb0\x66\x40\x4f\x4f\x31\xdd\xa5\x17\ -\x3e\x00\xee\x8f\x48\xd6\xef\xf7\x57\x02\x2b\x06\x14\x8b\xc5\x60\ -\xcb\xf6\x73\x93\xa8\x0c\x46\x24\x6f\x2a\xdf\x80\x0d\x03\xe4\x8b\ -\xb3\xab\x6f\x02\x4f\x36\xb1\xda\xa8\x7c\xe2\xcb\xbe\x09\xb1\x1b\ -\x90\xc9\x8d\xbe\x28\xe8\x81\x16\x41\xfc\x69\xfb\x30\x62\x35\xa0\ -\x37\x57\xd8\x2f\x70\xa8\x55\x11\x67\x8f\x9b\x2b\x45\x6c\x06\xf4\ -\x66\x47\x0e\x83\xbe\x1b\xe5\xc5\xc3\xb6\x0f\x23\xbe\x0e\x10\x89\ -\x7e\xd0\x00\x24\xd1\x5b\xde\x46\x10\x9b\x01\xd2\xf6\x0d\xef\xf5\ -\xdc\x81\x18\x0d\x30\xc8\x33\xb4\xce\x38\xf1\x2f\x4e\xff\x86\xd8\ -\x12\x5c\x9e\x9d\xf8\x08\x78\xba\x55\xd1\x54\x5c\x31\x6c\x20\xd6\ -\x0a\x2d\xcd\x4e\xbe\x03\x5a\x6c\x66\x05\xc0\x5b\x13\x62\x6f\xd1\ -\xa5\xd9\xf2\x41\x11\xde\x8e\xf2\x8a\x7a\xb9\x1c\x6c\x24\xa5\xbb\ -\xee\xea\x7e\x56\x95\xe9\x30\x29\x88\x58\x8a\xf7\x9f\x60\x25\xa1\ -\x52\xa9\x64\xce\xef\x08\x86\x10\xf9\x38\x22\x09\x9e\x75\x82\xb5\ -\x64\xbe\x1e\x1f\xaf\x5d\x75\x59\x1e\x43\xf5\xf3\x66\x45\x44\x3d\ -\xea\x04\xab\x89\x9c\x3a\x35\x7e\xb1\x66\xea\x0f\x83\x7c\x1b\xe6\ -\x05\xc4\x97\x3d\xc1\x7a\x12\xd5\xf9\xa9\xdf\x6b\x41\xed\x41\x81\ -\x1f\xc2\xbc\x20\x22\x1e\xfc\x48\xcb\x49\x15\xaa\x33\x53\x3f\x13\ -\xd0\x8b\xb0\x1a\xe6\x15\x02\x91\x64\x4d\x70\xd6\x86\x95\x99\xc9\ -\x1f\xa5\xae\xfd\x28\xe7\xc3\xbc\x2a\x01\xeb\x27\x44\x22\x70\xba\ -\x0e\x2b\x27\xcb\x67\x4d\xca\x3c\x04\x5c\x6c\x56\x34\x20\xa1\xe5\ -\xe0\x7c\x23\x5a\x99\x39\xf6\xa5\x22\x59\xa0\xd6\x26\x17\xe7\x26\ -\x24\xb2\x13\x2f\xcf\x4e\x9c\x16\xe5\x09\xa2\x8f\x27\x25\x70\xbd\ -\x31\x26\x76\x14\x55\xe6\x26\x3f\x44\xf4\xa9\x26\x52\xd6\x37\x46\ -\x97\x1e\x24\x7a\x16\x2f\x9d\x28\x1f\x45\x78\xa9\x55\x71\xf7\x82\ -\x4c\xfc\x32\xb2\x74\x62\xf2\x75\x45\xde\x6a\x23\x39\xc9\x2d\x71\ -\x03\x00\xbd\xef\xee\x9b\x9e\x03\xde\x8f\xf0\x4e\xae\xcc\x3e\x18\ -\x40\xa9\x54\x32\xb5\x5f\xbb\x47\x11\x5d\x08\xf3\x7f\x6f\x88\x56\ -\x73\xf4\xc2\x00\x80\x6a\xb5\xb4\x56\xeb\xaa\x3f\x8e\x72\x26\x22\ -\x59\x35\xc1\x1b\x03\x00\xaa\x53\x53\x97\xd3\xdb\x2e\x0d\x2a\x7c\ -\x13\x91\xac\x1d\x0b\x5e\x19\x00\xb0\x38\x3d\x7d\x21\x30\xe9\x01\ -\xe0\x7b\x17\xf1\xbc\x33\x00\xa0\x72\xf2\xc8\x2f\x75\xd5\x3e\xe0\ -\x9c\xed\x58\x5e\x1a\x00\xf0\xd9\x5c\xf9\x27\x13\xd4\xfb\x80\xdf\ -\xda\xc8\xb1\x2d\x09\x6f\x0d\x00\x58\x99\x79\xef\xbb\x20\xd0\x01\ -\xe0\xcf\x88\xb4\x39\xfe\x32\x03\x70\x7a\xa6\xfc\x95\x51\x79\x04\ -\xf4\x9f\x77\x83\x6c\x86\xbf\xcc\x84\xb1\x32\x37\xb1\x0c\x1c\x04\ -\xad\x23\xd4\x45\x78\x2d\xe9\x9c\x3a\xe8\xa0\x83\xff\x07\xfe\x02\ -\xec\x35\x2d\x8c\x9b\x14\xe3\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x6e\x26\xb0\x82\xfd\x2b\xf8\ -\x29\xe4\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\ -\xc6\xda\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\ -\x00\x00\x00\x00\xbc\xd7\xba\x61\x02\x03\x59\xaf\x8c\x6f\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x85\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ -\xce\xb1\x11\x00\x30\x08\x03\x31\x2e\x4b\xb1\x35\x23\x42\x86\x80\ -\x52\xdf\xdb\xa7\x88\x45\x59\x3d\x59\x3d\x9b\x8f\xb7\x19\x5f\x04\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0\x01\ -\x8b\x69\x06\x03\x87\x7c\xe1\xcd\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x04\x32\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe4\x49\x44\x41\x54\x78\x9c\xed\ -\x99\xcb\x6f\x5b\x55\x10\xc6\xbf\x39\xb6\x4b\x02\xa1\x42\x24\x6c\ -\x10\xa9\xa0\x41\x6a\xd3\x76\xe3\xb4\xac\x90\x90\x4b\xec\x8b\xda\ -\x45\x5a\x3f\xb2\x80\x2c\xc8\xc3\x0e\xfc\x03\x88\x55\x1b\xd8\x54\ -\x42\xac\x10\x42\x42\xa1\x24\x15\x2c\xb2\x30\x8f\xb6\x0b\x8c\xac\ -\xb6\x89\x68\x61\x01\x28\xde\xd5\x54\x2a\x46\xa2\xcd\x0a\x58\x54\ -\x55\xd5\xa8\xb1\xcf\xb0\x48\x08\xd7\xf7\x1e\x3b\x7e\xdc\x6b\x17\ -\x31\x3f\xc9\x9b\x99\xf3\x98\xf9\x3c\x67\xee\xb9\x36\x20\x08\x82\ -\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\xfc\xbf\xa0\x6e\x6d\x1c\ -\x4b\x64\xe2\x20\xfe\x08\x04\xc5\xe0\x4f\x2e\x7d\xf1\xe9\xa9\x6e\ -\xc4\x11\xe8\xc6\xa6\xd1\x64\x26\x43\xc4\x9f\x01\xd8\x0d\xa0\x8f\ -\x40\x2f\x0d\x1d\x0c\xaf\x95\xae\x17\x56\x3b\x1d\x4b\xc7\x05\x88\ -\xa5\x32\x6f\x13\xf8\x03\xb8\xaa\x8f\xc6\x86\x86\xc3\xf7\x4b\xc5\ -\xc2\xf7\x9d\x8c\xa7\x93\x02\x90\x95\xcc\xbc\x0f\xf0\xe9\xda\x23\ -\x28\xb6\xf7\xc0\xc8\x63\xa5\xe2\xea\xa5\x8e\x05\xd5\x89\x4d\x22\ -\x91\xb9\x60\xe8\xc9\xb5\x79\x10\xa6\x1a\x19\xcf\xa0\x85\xf2\x5f\ -\x4f\xbf\xb1\xb2\xf2\x6e\xd9\xef\xd8\x7c\x17\x20\x32\x39\xd9\x13\ -\xbc\x1b\x5a\x22\xf0\x49\x83\x5b\x13\x01\xcc\x50\x86\xc8\xbe\xde\ -\xe8\x2b\xbf\xb6\x72\xee\xdc\xba\x9f\xf1\xf9\x2a\xc0\xb1\x89\x89\ -\xdd\x1b\xeb\x8f\x9e\x27\xf0\x51\xbb\x9d\x37\x37\xae\x54\x8f\xe6\ -\x80\xbb\x2d\xe0\x4a\xef\x03\x7d\xf2\xe2\xc5\x85\xbb\x7e\xc5\xe8\ -\x9b\x00\xc7\xc6\xa7\x9e\x2a\x57\x02\x39\x10\x0e\x1b\xdc\x15\x83\ -\x0d\x30\xf7\xa4\x9f\x83\xaa\x72\x3c\x97\x5d\xfc\xc3\xc3\xf0\xb6\ -\xf1\x45\x80\xe8\xf8\xec\x1e\x68\x9d\x27\x60\x9f\xdd\xce\x60\x26\ -\x90\xae\x37\x97\xc1\x8a\x40\x54\x6d\xc3\x0d\x55\xae\xc4\xf2\x17\ -\x16\x6f\x79\x1d\xab\xe7\x02\x44\xe3\xe9\x61\x52\xc8\x03\x78\xc6\ -\xe1\x62\x00\x75\x93\xff\x77\x24\x2b\x10\x39\x63\xbb\x45\x50\x56\ -\xfe\xcb\xf9\x5f\x3c\x08\x73\x1b\x77\xf3\x69\x83\xd1\x44\xe6\x05\ -\x52\xb8\x0a\x67\xf2\xdc\x44\xf2\x00\x40\xa4\x01\x66\x87\x75\x90\ -\xa1\xaf\xc5\x92\xd3\x47\xda\x0e\xd4\x86\x67\x02\xc4\x52\x33\xa3\ -\x8a\xf8\x0a\x80\xfe\x6a\x0f\x33\xa8\x89\xe4\xb7\x21\xcd\x9b\x55\ -\x63\xa7\x1f\x50\xcb\x56\x3c\xfd\x72\xab\x71\x3a\xf1\x44\x80\x68\ -\x2a\x9d\x00\xd3\x37\x00\xfa\xec\x76\x06\x33\x76\x38\xf3\xf5\x20\ -\x40\x33\xbb\x44\xe8\x63\x85\x5c\x2c\x91\x89\xb7\xba\xae\x9d\xb6\ -\x6f\x82\x56\x22\x3d\x03\xe0\x73\x00\x41\xbb\x9d\x00\x0d\x90\x33\ -\xf8\xa6\x21\x02\x6f\xf5\x44\x7b\x4f\x08\x80\x30\xfe\xfc\x81\xf0\ -\xed\x5f\x8b\x85\x42\x3b\xeb\xb7\x25\x80\x95\x4c\xbf\xc5\x84\x0f\ -\x1d\xc1\x6d\x7e\x73\xee\xf2\x6d\x8b\xad\x96\x68\xdf\x87\x00\x3a\ -\xb1\xf7\x60\xf8\x5e\xe9\x7a\xe1\x87\x56\xd7\x6d\x55\x00\x8a\xa5\ -\x32\xef\x01\x78\xc7\xed\x81\x86\xc7\xc9\xdb\x17\x87\x4b\x6c\xb2\ -\x86\x86\xc3\xbd\xa5\x62\xe1\x72\xcb\x2b\x36\x43\x24\x32\x17\x0c\ -\xf5\xaf\x7d\x0c\x60\xc6\xe0\xf6\x31\xf9\x6d\x08\xa6\xde\xc5\x38\ -\xfb\x44\xe0\xce\x9b\xd9\x6c\xb6\xd6\x25\xcb\x48\x53\x15\x10\x99\ -\x9c\xec\x09\x05\xee\x2d\x01\x98\x70\x6c\xee\xf3\x37\x6f\x80\x41\ -\x8e\x03\x31\xb2\xce\x3d\x87\xf6\x3d\xfb\xe2\x85\x9b\x37\x7f\x6c\ -\x58\x84\x86\x2b\x60\x6c\x6c\xfa\xf1\xfb\xbb\xd4\x79\x30\x5c\x8f\ -\x20\x3f\xce\x7c\x03\x98\x2b\x01\xb8\xdc\xbb\xa1\xe3\x8d\xbe\x3f\ -\x34\x24\x40\xe4\xd5\xd9\x81\xd0\x03\x9d\x03\x60\xb8\x84\x50\xa5\ -\xf3\xb9\x57\x61\xaa\xe2\x9f\x36\x76\xa9\xe3\x2b\x4b\xf3\x7f\xee\ -\x34\x79\x47\x01\xac\x13\x53\x83\x1c\x0c\xe4\x01\xec\xaf\x72\x30\ -\x5a\xbc\xe0\xf8\x82\x82\x3b\x97\x62\x90\x61\xe5\xbe\x3a\x7b\xbb\ -\xde\xc4\xba\x02\x58\xc9\xd9\xfd\x0c\x9d\x07\x30\x68\xb7\x33\xc0\ -\xd4\xcc\xd5\xb6\x13\x98\xdf\x1f\x7e\x0f\x28\x6d\x7d\x9b\x5d\xb8\ -\x51\x6b\x5a\xcd\x9b\x60\x2c\x39\x7d\x84\x59\x5f\x85\x33\x79\xc6\ -\x8e\x6f\x74\x5d\x81\xc8\xd4\x84\xf7\x54\x2a\xea\x9a\x35\x9e\x36\ -\xbd\x92\x03\xa8\x21\xc0\x2b\x89\xe9\xa3\x80\x5a\x06\x61\xc0\xe1\ -\x62\x22\xe8\x2e\x9f\xf9\x7a\xb8\x45\x20\x0c\x68\x8d\xe5\x68\x2a\ -\x1d\x31\x4d\x70\x35\x90\xd1\x44\xfa\x14\x13\x2d\x12\xf0\x88\x61\ -\xfc\x3f\x9d\xf7\x61\xfe\xb8\x8e\xf5\x56\x2e\xaf\x3f\x37\x3c\xa2\ -\x7f\x2b\xae\x7e\x67\xf7\xb9\x2a\x40\x11\xe6\xa8\x8b\x7f\x98\xf8\ -\x05\x01\xa4\x08\x73\x4e\xbb\xa7\xbf\x07\xfc\x17\x31\x55\xc0\x19\ -\x7a\x78\x1e\x6f\x9e\x41\x04\xad\x08\x67\xba\x1d\x87\x20\x08\x82\ -\x20\x08\x82\x20\x08\x82\x20\x08\x82\xd0\x6d\xfe\x06\xf7\x21\x1d\ -\x03\xf2\x02\xba\x61\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\xe3\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x95\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x3d\x48\x5b\x51\x14\xc7\xff\xe7\xe5\x49\x07\xb1\x2a\x16\x22\ -\x58\x74\xae\x43\x15\x92\x22\xdd\x84\x56\x1d\x14\x37\xeb\x50\x41\ -\x07\x89\x14\x5a\x3f\xa6\x52\x87\x06\x85\x62\xe9\xe2\x47\x1d\xaa\ -\x38\x28\xb8\xa8\x9b\x28\x54\xdb\xa1\x43\xa1\x88\x06\xd4\xc1\xce\ -\x8a\xb6\xa6\x90\xfa\x41\x1d\x6c\x93\x77\x3a\xa8\xe5\xe5\xe5\x45\ -\x93\xdc\x97\x5c\xad\xf7\xb7\xdd\xf3\x4e\x4e\xfe\xf7\xff\xde\xbb\ -\xf7\x92\xdc\x0b\x28\x14\x8a\xeb\x0c\x25\x92\x54\xe9\xf7\xeb\x47\ -\xbb\x05\xf5\x06\xd0\x48\x20\x2f\xc0\x45\x00\x6e\xa4\x59\x5b\xb2\ -\x1c\x03\xb4\xc3\xe0\x15\x0d\x98\xca\x2e\x0c\xcd\x7e\xea\xe9\x09\ -\x5f\xf4\xa1\x0b\x0d\xf0\xb6\x0d\x57\x81\x79\x10\xc4\x77\x9c\xd1\ -\x99\x19\x18\xd8\x20\x68\x9d\x2b\x23\x4f\x3f\x9c\x97\xa7\x9d\x53\ -\x82\xbc\xbe\xa1\x6e\xc0\x58\xbc\x6a\x9d\x07\x00\x02\x4a\x01\x63\ -\xf1\x5e\xdb\xe0\x0b\x80\xe3\xde\x68\x57\xbc\x0b\x5e\x5f\x41\x37\ -\x08\xaf\xd2\x23\x2f\x93\xd0\x83\x22\xef\xd2\xf1\xb7\xc0\xfb\xcf\ -\xb6\x57\xed\x82\xde\xb6\xe1\x2a\xc0\x58\xb4\x84\xf7\x40\x78\xa9\ -\x85\x69\xbe\xe4\xc0\xbd\x35\x33\xf3\x28\xe2\xb8\x56\x01\x1a\x1a\ -\xa6\x5d\x9b\xb9\xc1\x62\x43\xe7\x5a\x30\x7a\x01\xe4\x47\x67\x68\ -\xd5\x76\xaf\x43\x8c\x01\x95\x7e\xbf\xfe\xeb\xfb\xad\xf5\xa8\xc7\ -\x9e\xf0\xd1\x15\x36\x9a\x96\xc6\x3a\x83\xce\x4b\x77\x9e\x8a\xd6\ -\x01\x77\x44\xd7\x26\xc1\x78\x78\x16\x63\x60\x23\xa7\x30\x54\x66\ -\x1d\x18\x63\xc6\x80\xa3\xdd\x82\x7a\xcb\x3b\xff\xf3\x37\xb2\x1e\ -\x5f\x95\xce\x03\xc0\xd2\x58\x67\xd0\x15\x36\x9a\x00\xec\x9d\xc5\ -\x08\x28\x3d\xda\x2d\xa8\xb7\xe6\xc6\x18\x60\x00\x8d\x51\x01\x82\ -\x7f\xfd\xdd\x93\x1f\xe9\x10\x9a\x4e\x96\xc6\x3a\x83\x0c\xf6\x9b\ -\x63\x31\x7d\x83\x8d\x01\x27\xf3\xbc\x29\x21\x4c\xf3\xce\xcb\xcb\ -\x0c\xae\x88\x36\x67\x6e\x13\xe0\xb1\xe6\xd8\x4c\x83\x5c\x64\x6e\ -\x95\x1c\xb8\xb7\x9c\x16\x96\x29\x6c\xb4\xdf\xb6\xe6\xd8\xad\x03\ -\xa2\x56\x78\x97\x6d\xb4\x4f\x06\x1b\xed\x31\xab\xd7\x73\x16\x42\ -\xd7\x03\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\ -\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\ -\x16\x20\x1b\xdd\x89\x22\x1e\xdf\x50\x35\x08\x6f\x08\xb8\x8b\x04\ -\xff\x6b\x10\x80\x01\x5a\x63\xe6\xe7\x81\xd1\x76\xeb\xef\x96\x49\ -\x23\xfc\x04\x78\x7c\x83\xcd\x44\x58\x20\xa0\x0c\xe9\xef\x3c\x4e\ -\xbe\x83\xcb\x89\xb0\xe0\xf1\x0d\x36\x8b\x16\x13\x32\xa0\xbc\xa5\ -\x3f\x8f\x88\xde\x8a\x8a\x48\x15\x22\x1a\x2a\x6f\xe9\xcf\x13\xa9\ -\x21\x64\x80\x9e\xa5\xdf\x07\x90\x23\x52\x43\x90\x9b\xa7\x1a\x52\ -\xe6\xda\x0f\x82\x42\x06\x84\xff\x84\xbf\x00\x38\x74\x48\x4b\x2a\ -\x1c\x9e\x6a\x48\x19\x21\x03\x56\xc7\xbb\xf6\x99\xb9\x5d\xa4\x86\ -\x08\xcc\xdc\xbe\x3a\xde\xb5\x2f\x52\x43\xf8\x15\x08\x8c\x76\x4c\ -\x30\xa3\x06\xa0\x55\x00\x2c\x5a\x2f\x01\x98\x81\x35\x66\xd4\x04\ -\x46\x3b\x26\x44\x8b\x39\xb2\x0e\x38\x9d\x8f\x85\xe7\x64\x19\xa8\ -\x41\x50\xb6\x00\xd9\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\ -\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\x28\x03\x64\x0b\x90\ -\x8d\x32\xc0\x26\x76\x6c\x6e\x34\x34\x4c\xc7\xdd\x4e\x7b\xd9\xb1\ -\xd1\x7e\x6c\xcd\xb1\x31\x80\x76\xcc\xad\xcd\xdc\x60\xb1\xa3\xaa\ -\x32\x88\x8d\xf6\x6d\x6b\x4e\x8c\x01\x0c\x5e\x31\xb7\x0d\x9d\x6b\ -\x1d\xd6\x95\x31\x22\x2e\xa3\xce\xdc\x66\x20\x60\xcd\x89\x31\x40\ -\x03\xa6\xa2\x02\x8c\xde\x8a\xd6\x01\xb7\xe3\xea\xd2\x4c\x45\xeb\ -\x80\x9b\x40\x3d\xe6\x58\x4c\xdf\x60\x63\x40\x76\x61\x68\x16\x4c\ -\x5f\x4d\xa1\xfc\x88\xae\x4d\x5e\x25\x13\xfe\x6d\x96\x36\xed\x18\ -\x67\x60\x23\xbb\x30\x34\x6b\xcd\x4d\x6a\xbb\x3c\x83\xfd\xae\x88\ -\x36\x77\x99\xb7\xcb\x47\x5c\x46\xdd\xe9\x9d\x4f\x6d\xbb\xfc\x19\ -\x5e\xdf\xd0\x7f\x72\x60\x02\x20\x70\xf7\xf2\x48\x47\x9f\xdd\xb5\ -\xb8\xeb\x80\x95\xd1\x67\x7d\x04\xee\x4e\x9f\xac\x8c\xc0\xcc\xf4\ -\x62\x79\xa4\xfd\x75\xbc\x84\x84\x0e\x4d\x31\x8c\x81\x93\x33\x38\ -\x57\x87\x44\x0f\x4d\xa5\x70\x6c\x0e\x1e\x9c\xec\xba\xbe\x84\xc7\ -\xe6\xb0\xcd\x40\x20\x99\x63\x73\x0a\x85\xe2\x7a\xf3\x17\x37\xaf\ -\x1e\xac\x94\x31\x9b\x08\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x05\x08\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xba\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5b\x6c\x94\x45\x14\xc7\x7f\x67\xbe\xd2\x2a\x78\x21\x2d\x89\ -\x8b\x72\x6d\x40\xb1\x51\xa3\x74\xb7\xe8\x83\x37\x24\x90\x80\x5c\ -\x34\x56\x43\x34\x62\x08\x74\x4b\x61\x0b\x9a\xa0\xa0\xc4\xb5\x01\ -\xb1\xbe\x40\xba\x5d\x5a\x76\x6d\x62\x48\x78\xb2\x89\x0d\x54\x40\ -\x49\x34\xf0\xa4\xa5\xbb\x36\x3c\xd8\x60\x4c\x20\x60\x69\x4b\x84\ -\x26\x1a\x01\xbb\xec\xce\xf1\x61\xbb\xcb\xd7\xfb\x45\xdf\xf8\xbf\ -\x7d\x67\xce\x39\xff\xff\xcc\x37\x33\xe7\x0c\xdc\xe9\x90\xf1\x38\ -\xfb\x2a\x0e\xcc\xb4\xa9\xe4\x1a\x51\x59\x82\x30\x13\x61\x06\x8a\ -\x41\xb9\x8c\x48\x07\xc2\x69\x47\x6d\x53\x4b\x64\xeb\x6f\xff\xab\ -\x00\x6f\x79\xa8\x04\xa5\x1a\x78\x71\x8c\x59\x5b\x45\x75\x67\x6b\ -\x64\xeb\xf7\xff\x49\x40\x71\x59\xe4\x7e\x91\xde\x7a\x60\x6d\x9f\ -\xa9\x0b\xa4\x59\x95\x13\xea\xa4\xce\xeb\x3f\xa6\x6b\xd2\x64\x63\ -\x35\x81\xc7\x8a\x9d\x63\x0c\x4b\xd5\xb2\x1a\x61\x76\x5f\xfa\xe3\ -\x4e\x2a\xb5\xbe\xa5\x61\xdb\x95\x71\x0b\x58\x58\x71\x60\x9e\x49\ -\xda\xa3\x88\x3e\x0a\x74\x89\x10\x9c\xf2\xc0\xb5\x2f\x4f\x55\x55\ -\x25\x47\x9c\x52\x30\x68\xbc\xdd\x05\x6f\x80\xec\x01\x2d\x04\x2e\ -\x19\x58\x75\x26\x52\x79\x76\xcc\x02\xbc\x9b\xf6\x15\x62\x73\x5a\ -\x80\x69\xc0\x11\x27\x97\xb7\x5b\x6a\x2b\xff\x1a\x91\x78\x00\xe6\ -\x05\x42\x79\x53\x7b\xa9\x43\x58\x0f\x5c\x47\x78\x36\x76\xb0\xb2\ -\x6d\x54\x01\x8b\x02\xa1\xfb\x92\x09\x7e\x14\x28\x52\xb4\x26\xee\ -\xe9\x79\x8f\xaa\x2a\x3b\x1e\xf2\xdb\x50\xf1\xf9\x43\x3b\x14\xd9\ -\x0b\x74\xa8\xa6\x4a\xe2\xd1\x77\xbb\xdc\x1e\x39\x03\x43\x52\xbd\ -\x84\x45\x28\x02\x9a\x87\x22\x4f\x9f\x84\xd4\x06\x81\xe5\x02\xb3\ -\x14\x2c\xc8\x45\x55\x8e\x41\xb2\xa1\x3f\x81\x68\x6b\x44\xab\x7d\ -\xe5\xb5\x85\xaa\x6c\x30\xe2\x1c\x06\x5d\x02\xa2\x43\xae\x40\x89\ -\xbf\xd6\x6b\xd1\x56\x84\x3f\xd4\xe6\xcd\x8f\x47\xfd\x7f\x66\x07\ -\x83\x41\xe3\xeb\xce\xff\x40\x91\x8f\x81\xbb\x86\x99\xf2\x75\x55\ -\x3e\x8c\x47\x03\xb5\x6e\x92\xa2\xd2\x60\xee\xe4\xfc\x82\xb3\xc0\ -\x02\xd0\x15\xb1\xc8\xd6\xe3\x99\x31\xe3\x8e\xb6\xa2\x9f\x01\xa8\ -\xea\xee\x81\xe4\xde\xee\xfc\x43\x7d\x4b\x39\x1c\x39\xc0\x14\x11\ -\x6a\xbc\xfe\x50\x1d\x68\x76\x72\xed\x8d\x55\x09\x81\x8f\xfa\xe6\ -\x5c\xed\x1e\xcb\x0a\x28\x2e\xdb\x3f\x1d\xe5\x25\xa0\xe7\x66\x4f\ -\x4f\xc4\x9d\xd5\xd7\x5d\xb0\x0b\xe4\xad\x11\x88\x5d\x50\x40\xca\ -\x7d\xfe\x70\xa5\xdb\xda\x1a\x09\x34\x01\xe7\x80\xc7\x4b\xfc\xb5\ -\x4f\x0c\x12\x20\x98\x95\x80\xa0\x1c\x6b\x6f\xac\x4a\x64\xec\xde\ -\x4d\xfb\x0a\x15\x76\x8d\x8d\x3c\x9d\x29\x2d\x43\x3f\x7d\x6a\x4b\ -\xed\x83\x2e\xbb\xa2\x7a\x14\xc0\x8a\xbe\x32\x48\x00\x22\x2f\xa4\ -\x03\xe5\xdb\x7e\xe9\x34\xa7\x02\x98\x34\x76\x01\x59\x4c\x71\x12\ -\x6c\x74\x1b\xac\x31\xdf\xa5\x73\xca\xe2\xc1\x02\x60\x26\x80\x23\ -\x72\xc1\x1d\xa4\xca\x8a\x09\x90\xa7\x21\xfa\xb2\xfb\x33\x97\xe4\ -\x79\x00\x85\x19\x83\x04\x64\x8c\x46\x6e\xb9\x8e\x91\x0a\x50\x38\ -\x71\x01\x99\x2b\x39\x8d\xab\x93\x9c\x4c\xee\x87\x32\x1b\xd1\x0c\ -\x0a\x72\x23\xf8\x89\x8c\xea\x33\x12\x14\x67\x94\xdc\xee\x4d\xc8\ -\x65\x80\x84\x38\x9e\xac\x53\xfa\x12\xba\x38\x61\x01\xc8\x25\xf7\ -\xd7\xbd\xd6\x78\xd2\xba\xe8\xcc\x5c\x70\xb7\x67\xa7\xf2\x3b\x80\ -\xb1\xcc\x1d\x90\xe4\x38\x13\x85\x68\xbf\x58\x73\x2b\x55\x08\x20\ -\xd0\x91\xb5\xdd\x1e\xd5\x53\x00\x22\xb2\xcc\x1d\xe4\xa0\x07\x81\ -\x89\xd4\x82\x84\x49\x4a\x43\x3f\x01\x86\xa5\x00\x0a\x3f\x0c\x12\ -\x90\xca\x91\x66\x00\x55\x5d\x51\x5c\x16\xc9\x1e\xbb\x96\x48\x65\ -\x3b\x10\x1a\x37\xbd\xca\xde\x33\x0d\x81\x0b\x6e\x83\x55\x59\x05\ -\x60\x6c\xaa\x69\x90\x80\xb6\x70\xa0\x53\xd2\xca\xa6\x41\xef\x86\ -\x7e\xb9\x34\xef\xfd\xf1\xfd\x0a\x6d\x8c\x4d\xbf\xba\xdb\x6d\xf1\ -\x6e\x0a\xaf\x14\x28\x02\x7e\x69\xfd\x62\x5b\xb6\x37\xe8\xbf\xc3\ -\xad\xdd\x01\x20\x42\x70\x51\x20\x74\x5f\xc6\x1c\x8f\xfa\x6f\xa9\ -\xe6\xae\x51\xb4\x86\x91\x7f\x47\x12\x61\xef\xdc\x9e\xe9\x6b\xdd\ -\x55\xb4\xa8\x34\x98\xab\x36\x5d\x67\x04\x76\x0e\x5b\x0d\x01\x8a\ -\xfd\xa1\xc3\x02\x6f\x02\x47\x62\x9e\x6b\xaf\x0e\x2c\xc7\xde\xf2\ -\x9a\xc7\x50\x29\x07\x96\x03\xb3\x48\x5f\xfe\x17\x15\xfd\x46\x8c\ -\xd6\xc7\xea\xb7\xfd\x3a\x60\x35\xc4\x5b\x56\x5b\x8f\xe0\x07\x4e\ -\xc5\x22\x81\xc5\x23\x0b\x48\xf7\x81\x3f\x01\x0b\x80\x7d\x31\xcf\ -\xb5\xed\xc3\x35\x24\xa5\xa5\x5f\x39\x00\x8d\x8d\xaf\xa7\x86\x5e\ -\x10\x15\x6f\x79\x78\x3b\xaa\x9f\xa3\x74\xa6\x72\xc5\xd7\x16\x0e\ -\x74\xba\x3d\x86\x6c\xc9\x16\x56\x1c\x98\x67\x52\xa9\x16\x20\x1f\ -\xf8\xfa\x86\xe3\xac\x6b\xaf\xdb\xfc\xf7\xd0\x24\x43\xa3\xa8\x34\ -\x98\x7b\x77\x7e\x41\x58\x60\x23\x70\xc3\x20\xcf\x9f\x89\x04\x62\ -\x03\xfd\x86\x6d\x4a\x4b\x36\x86\x1f\xb6\xc6\x1e\x05\x1e\x51\xe4\ -\xb2\x40\xf0\x1e\xcf\xd5\x43\x63\x69\x4a\x7d\x57\xf2\x5f\xb3\x2a\ -\x7b\x04\xe6\x03\x1d\xaa\x66\x75\x3c\xba\xe5\xe7\xa1\xdc\x47\x6c\ -\xcb\x9f\x7c\x67\xff\xd4\x9c\x3c\x13\x05\x29\xed\x33\x75\x88\xd0\ -\x8c\x72\x02\x6b\xce\xe7\xd8\x44\xd7\xcd\x94\x58\x27\x37\xc7\xa3\ -\x86\xd9\xc6\xda\x65\x88\x59\xdd\xd7\x0d\x03\x9c\x14\xc7\x59\xd7\ -\x5a\xb7\xb9\x7b\x38\x8e\x31\x3d\x4c\x4a\xfc\xe1\x67\x2c\x5a\x0d\ -\xfa\xdc\x58\xfc\x81\x36\x55\x76\xc4\xa3\x95\x27\x47\x73\x1c\xd7\ -\xd3\xec\xe9\xf2\xfd\x73\x92\xd6\x59\x83\xb0\x04\xed\x7b\x9a\x81\ -\x03\x74\xa4\xaf\x57\x3d\x6d\xd5\x34\xc5\xa3\x81\x73\xe3\xc9\x7b\ -\x67\xe3\x5f\x5e\xef\xd7\x3d\x0b\xb2\x5f\x42\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x31\x15\x80\x30\x00\xc4\x50\x5a\x53\xf5\x81\x50\x7c\x60\x0a\ -\xba\xe2\xe0\x33\x24\xdb\x4d\x97\x97\x71\x20\xd6\xf5\xbc\xdf\x7d\ -\x9f\x73\x08\x8f\x29\x4e\xff\x44\x01\xb4\x80\xa6\x00\x5a\x40\x53\ -\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ -\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ -\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ -\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ -\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ -\x0d\x64\x41\x04\x80\xc9\xe4\x92\xad\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\xe2\x50\x80\x04\x84\x20\x3d\ -\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ -\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xc0\x07\x65\x23\x03\x3b\x58\x7b\xaf\x09\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x0a\x60\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x12\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x6b\x90\x14\xd5\x19\x3d\xe7\xce\xcc\xae\x83\x2c\x88\xf8\x48\ -\x4a\x28\x83\x31\x96\xae\x01\x4c\x70\x99\x5d\x82\x2b\x98\xa4\x54\ -\x82\x2c\xbb\x8b\x1b\x1f\xa5\xe2\x23\x2a\x26\xc6\xc4\x24\x26\x5a\ -\xa5\x8b\x46\x8d\xc6\x08\x96\x55\x06\xb5\x82\xa5\x22\x95\x64\x60\ -\x77\x00\x2d\x51\xab\xc4\xb5\x10\xd9\x5d\x5e\x6a\xf9\xc0\x32\x51\ -\x11\x42\x34\x2a\xca\x43\x79\xcc\xf4\x3d\xf9\xb1\xa0\xdd\x3d\x33\ -\xdd\x33\x3b\x33\x94\x95\x70\xaa\xe6\x47\x7f\xf7\xdc\xef\x9e\xfb\ -\x4d\xf7\xed\xfb\xf8\x1a\x38\x80\x03\x38\x80\xff\x67\x70\x7f\x34\ -\x72\x4a\x52\x87\xef\x89\xa1\x91\xd6\x8e\x94\xc1\xf1\x14\x8f\x11\ -\x70\x08\x80\x41\x00\x22\x00\xb6\xed\xfd\xbd\x27\xe8\x0d\xc0\xbc\ -\x8e\x28\x96\xf7\x4e\xe1\x3b\x95\xd6\x56\xb1\x00\x8c\x4b\xe9\x9b\ -\x8e\xb5\xd3\x41\x4e\x01\x30\xaa\x5f\x4e\x84\x77\x60\xb4\xd4\x5a\ -\xf3\xf0\xaa\x16\xac\x06\xa9\xf2\xaa\x2c\x77\x00\x24\x36\xa4\x70\ -\xba\x85\xae\x03\x30\xb1\x9c\xae\x09\xbc\x2a\x70\x56\xe6\x43\x3c\ -\xb6\xe6\x0a\xa6\xcb\xe8\xb7\x3c\x48\x74\x68\x22\x8c\xfe\x08\xe1\ -\xe4\x72\xf9\xcc\x83\x77\x05\xce\xec\x6d\xc6\xa3\xe5\xb8\x23\x4a\ -\x0e\x40\x62\xb1\x8e\x94\x63\xef\x26\x78\x7e\x00\xcd\x02\x58\x01\ -\xaa\x4b\xd6\xac\x37\x11\xfc\x53\x19\x6c\xb1\x16\xdb\x0f\x02\x9c\ -\x9d\x06\x35\x31\x60\xb0\x0c\x46\x08\x38\x0e\x50\x03\x80\x1f\x02\ -\x88\x07\xf8\x5c\x6e\x2d\x67\xac\x9a\xc6\xd7\x4a\xd1\x5f\x52\x00\ -\x1a\x52\x1a\x6b\xa5\x45\x00\xbe\x9e\xa3\x78\x3b\xa8\x27\x29\xf3\ -\xb8\x05\x9e\xea\x6d\xe1\xc7\x45\xf9\x4e\x2a\xee\x44\x70\x1a\x69\ -\xcf\x02\x38\x25\x4f\x1b\xbb\x44\x5e\xd2\xdb\xcc\xbf\xf6\x47\x3f\ -\x50\x42\x00\xc6\x76\xe8\x3c\x50\x0f\x11\xa8\xf6\x8b\xa2\x74\x6f\ -\xb4\xda\xdc\xf1\xc2\x64\x7e\xd2\x5f\xff\x6e\xd4\x26\x55\x55\x13\ -\xc5\x4f\x00\xdd\x04\xe0\x08\x7f\xb9\xa0\xdb\x7a\x5f\x36\x37\xe1\ -\x66\xda\x62\x7d\x17\x1f\x80\x76\x99\xc4\x28\x7b\x2b\xc8\xeb\x7d\ -\x25\x56\xd0\x43\x94\xb9\xb9\xa7\x95\x9b\x8a\xf6\x5b\x00\xbe\xb7\ -\x58\x35\x69\x8b\x6b\x29\xfd\x1a\xc0\x40\x4f\xa1\xb0\x28\xee\xf0\ -\x82\xae\x36\xee\x28\xc6\x67\x71\x01\x68\x97\x49\x8c\xb6\xf3\x01\ -\x9e\xe3\x2b\xd9\x6c\xc8\xe6\x95\xcd\xec\x2d\xca\x5f\x3f\x91\xe8\ -\xd0\x30\x18\xa5\xfc\x03\xae\x88\x75\xac\xe6\x84\x9e\x49\xdc\x56\ -\xa8\x2f\x53\x54\xc3\x27\xd9\x99\x39\x3a\xdf\x9d\x11\x4f\xde\x5f\ -\x9d\x07\x80\x9e\x56\x6e\x32\x69\x36\x0a\x9a\xef\xb6\x53\xf8\x0e\ -\x77\x69\xfe\xd9\x49\x45\x0a\xf5\x55\x70\x00\xea\x3b\xf4\x63\x88\ -\x37\x7a\x1a\x84\x1e\x89\x6f\xe5\xc4\x35\xad\xfc\x77\xa1\x7e\xca\ -\x85\x95\x6d\xdc\xd9\xdb\x6c\x2e\x10\xf9\x5b\x00\x5f\xbc\x0e\x05\ -\x4c\xde\x18\xb1\xb7\x17\xea\xa7\xa0\x47\x60\xec\x42\x9d\x4c\xa3\ -\xe5\x00\x0e\xfa\xd2\xaa\xc7\x7a\x9a\xcd\x85\x95\x98\x9d\x15\x8b\ -\x44\x87\x7e\x01\x6a\xb6\xdb\x26\xf0\xa2\xde\x16\x3e\x1a\x56\x37\ -\x34\x00\x63\x3b\x35\x94\xd0\xcb\x00\x8e\x72\x99\x7b\xe3\x5b\x79\ -\x6a\xd7\xc5\xdc\x55\x8c\xd0\xfa\x4e\x9d\x60\x85\x66\x1a\x3b\x0a\ -\xe2\x30\x00\xc3\x00\x38\x00\x36\x91\xda\x24\x6b\xd6\x2a\x86\xce\ -\xa2\xd7\x00\x12\x13\x29\x3b\x17\xe0\xc5\x2e\xeb\x1e\x8a\x0d\xdd\ -\xad\x5c\x1b\x54\x35\x34\x00\x89\x4e\x67\x2e\xc0\x4b\x5c\xa6\xcd\ -\xd1\x08\xeb\x56\x34\x71\x73\x21\xda\x6a\x93\xaa\xaa\x89\x61\x06\ -\xa4\x2b\x01\x1c\x5f\x48\x1d\x11\xeb\x0c\x78\xef\xf0\x34\xe6\x2d\ -\x68\xa3\x53\x48\x9d\x33\x9f\x54\xf5\xc7\x3b\xb5\x8c\xc4\x38\x97\ -\x79\x6d\x7c\x08\x13\x5d\x13\x99\xc9\x57\x2f\x30\x00\x89\x4e\x8d\ -\x07\xb4\xdc\xad\x0d\xe2\xb8\x9e\x56\x76\x17\x22\x6a\x6c\x4a\x53\ -\x69\x75\x17\x88\x63\x0b\xe1\xe7\xc0\x4b\x02\x7f\xd5\xdb\xc2\x65\ -\x85\x90\x13\x8b\x75\x24\x1c\xbd\x0a\xe0\xb0\x7d\x36\x82\xd7\x74\ -\xb7\xf0\xde\x7c\x75\xf2\x0f\x82\x12\x01\xfd\xc1\x67\x9c\x5f\x48\ -\xe7\xc7\x3c\xa0\x58\x22\xe5\xdc\x47\x29\x55\x42\xe7\x01\xe0\x24\ -\x42\xcf\xd6\x77\x38\x33\xd1\xae\xd0\x01\xbb\xa7\x89\x1f\x40\xbc\ -\xcd\xa3\x18\xba\x71\xd4\xd3\x3a\x38\x5f\x9d\xbc\x4e\x1b\x52\x68\ -\x04\x30\xde\x65\x4a\x3b\xd6\xb4\x87\x89\x18\xff\x84\x86\xc4\x0e\ -\xd7\x52\x88\x57\x85\x71\x0b\x85\xc8\xf6\xc4\x68\xfd\x7d\xcc\x12\ -\x0d\x08\xe3\xc6\xb7\xe1\x7e\x12\xef\xb9\x4c\x87\x0d\xf8\x0c\x57\ -\xe4\xe3\xe7\x0d\x80\x85\x7e\xe3\xbe\xa6\xf4\xc0\xea\x69\x7c\x3b\ -\xa8\xf1\xda\xa4\xaa\xd2\x7b\xb4\x48\xc0\xf7\xc3\x84\xf6\x03\xd3\ -\xa2\x69\x3d\x1a\x76\x27\xf4\x0d\xcc\xf4\xfc\x51\x82\xae\xcd\x37\ -\x37\xc8\xe9\xac\x2e\xa9\xaf\x01\x38\xc3\x65\x4a\x2b\x6a\x6e\x0d\ -\x94\x27\x71\x60\xd4\xde\x07\xa0\x31\x90\x57\x0a\x88\xd6\xc4\x68\ -\x1b\x7a\x17\x0e\x4f\x63\x1e\x80\xb7\x5c\xa6\xa3\x36\x18\xfc\x20\ -\x17\x37\x67\x00\x22\x51\x9c\x87\xbe\xad\xaa\x7d\x0d\x2f\xeb\x69\ -\xe2\x07\x41\x8d\x26\x16\xe1\x7c\x82\x97\x85\x89\x2b\x1d\xbc\xa9\ -\x7e\xa1\x72\x76\x66\x1f\x16\xb4\xd1\x21\xb4\xc0\x53\xcb\xd8\x8b\ -\x72\x71\x73\x06\x40\xd0\x59\x1e\x83\xe5\x92\xa0\x06\xc7\x2c\xd1\ -\x00\x48\x77\x04\x71\xca\x09\x19\xcd\x0a\x9d\xee\x1a\xe3\xd3\xcc\ -\x49\xb9\xea\x64\x05\x60\xef\x88\xe9\x7e\x97\x22\xe3\xe0\x89\xa0\ -\xb6\x62\x0e\xae\x85\x77\xa2\x54\x69\x8c\xdc\x10\xc3\xf4\x20\x42\ -\xf7\x3a\xac\x02\xe0\xbe\x6b\x07\x6f\x8a\x61\x8c\x9f\x97\x15\x80\ -\xea\xcf\x51\x0f\xa0\xca\x65\x7a\x69\x4d\x1b\xdf\xf3\xf3\xf6\xe1\ -\xec\xa4\x22\x56\xfa\x79\xa8\xe4\x32\x83\xd2\x35\x81\x84\x9b\x69\ -\x29\x79\xfe\x38\x29\x7b\x9f\x32\x2b\x00\x06\xf8\xb6\xa7\x12\x3d\ -\x13\xa1\x2c\x6c\x8c\xe1\x14\x02\x87\x07\x8a\xa9\x0c\x46\x26\x16\ -\xea\x5b\x41\x04\x4b\xe3\xd1\x2e\xda\x13\xfd\x9c\xec\x31\x40\xf6\ -\x04\x0f\xc1\x9a\xb7\xb2\x38\x6e\xba\xec\xb4\x40\x99\x95\x84\x41\ -\x6b\x50\x71\xc4\xc0\xa7\x9d\x27\xf8\x39\xd9\x01\x20\xbf\xe1\xbe\ -\xb4\x40\xe0\xbb\x1f\x62\xa5\x77\x81\x83\x1a\xcf\x7a\xa6\xdd\xc8\ -\xec\xf1\x69\x17\x46\xf8\x39\x59\x01\x90\x45\x8d\x8f\xf0\x69\xa0\ -\x06\xee\xd7\xc1\xcf\x8f\x61\x41\x85\x07\x7f\x96\xa5\xbd\xc6\xcf\ -\xc9\x0a\x00\xe9\x25\x59\x22\xff\x1e\x5b\xdf\xac\x2c\xd7\x6e\xed\ -\xfe\x42\x60\x00\xba\xa6\x63\x37\x00\xf7\x4a\xb0\xaa\x36\x29\xf7\ -\x00\x9f\x23\x00\xbe\x15\x22\x2d\xf2\x6e\x78\x4c\x98\x00\x93\xcb\ -\xc7\x7e\x44\xac\x54\x07\xd9\x8f\x00\xb0\xdd\x7d\xed\xbf\x23\xdc\ -\xd8\xbb\xce\x0e\x9c\x21\x56\x18\x81\xbb\xcf\x13\x1e\x46\x35\x80\ -\xa8\xcb\xb4\xe7\xf5\x36\xee\x71\x73\x72\x0c\x82\xf0\xec\xa8\xda\ -\xbe\x53\xdc\x20\xfc\x2b\xa4\xbc\x92\x08\x0c\xc0\xce\x43\x31\xd8\ -\x67\xda\xee\xe7\x64\x07\xc0\x6a\x83\x8f\x91\x35\x72\xba\x41\xe8\ -\xd5\xa0\xf2\x4a\x42\x21\x6d\xcb\xc1\x31\x3e\xd3\xbb\x7e\x4e\x8e\ -\xe7\xd7\xbc\xe1\xbe\xa2\x6c\xe0\x64\x03\x32\x9d\x81\xe5\x15\x84\ -\x09\x6f\xdb\xa3\x5d\xd0\xfa\x2c\x1f\x59\x55\x08\xdf\x61\x23\xc7\ -\x67\x71\x5c\x38\x68\x1b\x9e\x01\x02\xde\x14\x95\xc3\x86\xee\x16\ -\xac\x0b\x22\x10\x76\xbc\xf7\xda\x64\xdd\x31\x59\x01\x88\x67\xb0\ -\x12\x80\xfb\xfc\xfd\xbb\x89\x0e\xe5\x7d\xdd\x74\x5d\xcc\x5d\x94\ -\x1e\x0e\x95\x5b\x66\x48\x7c\x30\x70\x4b\xbe\x5d\x06\xe0\x64\x6f\ -\x25\x74\xf9\x69\x59\x01\xd8\x7b\xb6\xb6\xd2\x53\x8f\x98\xec\xe7\ -\xb9\x11\x73\xcc\x2d\x00\xb6\x06\x2a\x2e\x2f\x36\x46\x1c\xcc\x0e\ -\x22\xd4\x8d\xc2\x18\x78\xe7\x28\xdb\xe2\x87\x62\xb5\x9f\x97\x67\ -\x3f\x80\x9e\x55\x14\xa1\x29\x41\x8d\x2d\x6f\xe3\x87\x00\x83\x77\ -\x8c\xca\x09\xf2\x86\x95\x6d\xdc\x19\x44\x31\xb0\x1e\xcd\x82\x9e\ -\xca\xb5\x3d\x9e\x33\x00\xb1\x08\xe6\xa3\x2f\xa9\x61\x6f\x65\x9c\ -\x76\x4a\x52\x81\x2b\xbe\xf8\x10\xdc\x03\xe2\xe9\x40\xe1\xe5\x00\ -\x35\xaf\x67\x2a\xe6\x07\x72\xda\x65\x40\x7a\x16\x69\xb4\xe6\x91\ -\x5c\xd4\x9c\x01\x58\xd1\xc4\xcd\x02\x9e\xf9\xa2\x32\x50\x9d\x8e\ -\x5a\xff\x71\xb8\x07\x5d\x13\x99\xd9\xdd\x77\x70\xfa\x66\xa0\xb8\ -\xd2\xd0\x1d\xff\xd4\x5c\x1e\x76\x1c\x57\x3f\x1a\xe7\xc2\x7b\x08\ -\xf3\x7e\x7c\xe8\x97\xfd\x71\x23\xef\x34\x56\xe4\x9f\x3c\xd7\xe0\ -\x4f\xc7\x75\xe8\xe8\xa0\x86\x5f\x6a\xe6\xa7\x8e\xe5\x24\x54\x22\ -\x08\xc4\x6a\x44\x38\x35\xec\x38\xae\x36\xa9\x2a\x49\xbf\x77\xdb\ -\x44\xce\xce\x77\x3a\x94\x37\x00\xab\xa6\x62\x19\xbc\x83\x61\x95\ -\x03\x3b\x33\x4c\xe7\xea\x69\x7c\x7b\x37\x59\x0f\xe4\x8e\x78\xff\ -\xa0\xbf\x99\x34\x1b\xc3\x36\x66\x01\x60\x60\x0c\x97\x83\x9e\xc9\ -\xdb\x96\x98\xc1\x9c\x7c\xfc\xfc\x0b\x19\x52\x24\x6f\xf0\xd9\x2e\ -\x4c\xa4\x82\xd7\xe0\x40\xdf\x9d\x10\x1f\xc2\x1f\x11\xfc\x1d\x72\ -\x4c\x3f\x8b\xc0\x47\x02\x67\xf4\x34\x9b\xf3\xc2\x06\x3d\x00\x18\ -\xb3\x44\x87\x51\xf2\x1c\xe1\x43\xbc\x7d\x45\x13\xf3\x6a\x08\x5c\ -\xc9\x75\x37\xb3\x0b\xd4\x3c\x0f\x5f\x4a\x25\x16\xeb\xc8\x30\x31\ -\x5d\x13\x99\xe9\x6e\xe1\x9d\x11\xf0\x58\x49\x73\x00\x7c\x1e\x56\ -\xc7\x85\xad\x80\xee\xc8\x64\x78\x6c\x6f\x0b\xef\x2f\xe4\x08\xbe\ -\x36\xa9\xaa\x48\x46\x0b\xe1\xcd\x21\x7a\x25\xf3\x11\xf2\x9e\x0b\ -\x02\x05\x9c\x0e\x8f\xeb\xd4\x11\x0e\xf4\x0a\x80\x2f\x3a\x2d\xe1\ -\xc5\xa1\x71\x9e\xb6\x74\x12\x77\x87\xd5\xdf\x87\x31\x4b\x34\x20\ -\x96\xc1\x19\xa0\x6d\x95\x38\x12\x7d\xbb\xc8\x87\x02\x80\x80\x0f\ -\x09\x6c\x06\xb4\x96\x34\x0b\xb6\xa5\xf1\xac\x7f\xd5\x16\x86\xfa\ -\x4e\x67\x8e\xc0\x2b\x5d\xa6\xb4\x21\xc7\x87\x65\xae\x14\x94\x20\ -\x91\xe8\x50\xbd\xa8\x2e\x6f\x46\x98\x1e\xea\x69\x36\x97\x95\x92\ -\x20\xd1\x90\x54\xfc\x90\x81\xb0\xc5\x04\x32\x8f\xbe\xab\x40\xdd\ -\xe7\xb6\x89\xbc\xac\xb7\x99\x73\xc3\xea\x16\x9c\x24\x95\xe8\xd0\ -\x05\xa0\xbc\x19\x17\xd2\x83\xdb\x1d\x73\x75\xb1\xff\x56\xd9\x20\ -\xb1\x3e\x85\xab\x05\xcd\x86\xfb\x71\xa6\xee\xe9\x69\x8e\xfc\xb2\ -\x10\x17\x45\x65\x89\xd5\x77\x38\x77\x8a\xbc\xce\xa3\x01\x78\xde\ -\x89\x72\xda\x9a\x29\xfc\xa8\x18\x5f\xa5\xa2\x36\xa9\xaa\x41\x11\ -\xfb\x67\x91\x97\x7a\x0a\x88\xa7\xe3\x87\x70\x72\x50\x52\x84\x1b\ -\x45\x6d\x67\x0d\x77\xcc\x0d\x04\x52\xde\xf6\x70\x6a\x34\xa3\x55\ -\x0d\x8b\x34\xb2\x18\x5f\xa5\x60\x5c\xa7\x8e\xa8\x89\xea\xd9\xac\ -\xce\x03\xaf\xed\x06\xcf\x29\xb4\xf3\x40\x3f\x12\x25\xcf\x4e\x2a\ -\xb2\x31\x6a\xef\x12\xe8\xbf\xc5\xd2\x80\xe6\x44\x60\x6e\x7b\xb1\ -\x85\xff\x29\xd6\x6f\x21\x68\x48\x2a\xee\x44\xf1\x33\x42\xd7\x03\ -\x18\xe2\x2b\x5e\x9a\xc9\xf0\xdc\x35\x6d\x2c\x6a\x51\xd6\xff\x54\ -\xd9\x94\x2e\x65\xdf\xeb\xcd\xbf\x31\xb9\x83\xd2\xdd\x8a\x9b\x59\ -\xc5\x24\x2c\x06\x61\xc2\x73\x8a\xee\xda\x82\xe9\xa2\x66\x22\xc7\ -\x19\xa4\xa0\x59\x47\x67\xcc\x75\x85\xe6\x13\xb9\x51\x52\xb2\x74\ -\x5d\x87\x1a\x0d\xd5\x09\x60\x68\x8e\xe2\x4f\x00\x3d\x0e\x99\xc7\ -\x11\xc7\x33\xc5\x06\xa3\x36\xa9\xaa\x41\x06\x8d\x32\xf6\x2c\x80\ -\x4d\x00\x72\x4d\xc3\xd3\x22\x67\x14\x32\xda\xe7\x43\xc9\xe9\xf2\ -\x75\x8b\x34\xdc\x58\xdd\x03\xa0\x25\x80\x96\x06\xf1\xbc\x2c\x9f\ -\xa3\xc1\x9b\x12\xfe\x21\x83\x2d\xd5\x51\xec\x48\x1b\x38\x66\x07\ -\x6a\x6c\x15\x06\xcb\xc1\x08\x10\xc7\x11\xb6\x01\xe0\xe9\xe8\xfb\ -\xa4\x26\x9f\xf0\x55\x22\x67\xf4\x34\x73\x4d\x29\xfa\xcb\xf6\xc1\ -\x44\x7d\x4a\x67\x4a\xba\x13\x40\xa5\x07\xc3\xcd\x12\x6f\x39\xda\ -\xc1\x5f\xfa\x73\xcb\xfb\x51\xde\x4f\x66\xda\x65\xc6\x8e\x42\x93\ -\xa1\xae\x17\x50\x57\x56\xdf\xc0\xdb\x00\x67\xc5\xb7\x62\x6e\xb1\ -\x09\x9a\x41\xa8\xd8\x47\x53\x75\x0b\x75\xa2\x31\x76\xfa\xde\x8f\ -\x1d\x8e\xeb\xa7\x9b\xf7\x01\x3d\x69\x65\x1e\x59\xf5\x0a\x5e\xe8\ -\xcf\xf7\x00\x61\xd8\x2f\x9f\xcd\xd5\x2d\xd2\x70\x5a\x4c\x34\xb2\ -\x27\x8a\x3c\x1e\xc0\x08\x12\x83\x25\x0c\x42\xdf\xc9\xcd\x56\xf4\ -\x7d\x36\xb7\x11\xd0\x7a\xd2\xac\x17\xf1\x7c\x4f\x13\xde\xf8\x2a\ -\xe4\x22\x1f\xc0\x01\x1c\xc0\xff\x2e\xfe\x0b\x91\x5a\xc0\x8b\x79\ -\xe5\x16\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x01\x23\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd5\x49\x44\x41\x54\x78\x9c\xed\ -\xdb\x31\x11\xc2\x40\x00\x05\xd1\x0d\x22\xa2\x08\x05\x0c\x0e\xa0\ -\x41\x11\x0d\x12\x18\x14\xa0\x26\x15\x2e\x42\x41\xe8\x52\x67\x99\ -\x61\x5f\x75\xdd\xfd\xdb\xfe\x20\xc9\x3f\x1b\xac\x8b\xf7\xc7\xf3\ -\x61\x98\xb9\x02\xcc\x03\x97\xe7\xfd\xf6\x30\x76\xec\x8c\x4b\x01\ -\x96\xc7\x8f\xc0\xf8\x0d\x61\xd0\x02\xf0\x79\xfc\xda\x79\x53\x66\ -\x80\x9f\x50\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\x02\ -\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\x2b\ -\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\ -\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\ -\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\ -\xb6\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\ -\x60\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xcd\xfb\x34\x05\xaf\xb5\xf3\ -\xd6\xb4\x00\x33\x9c\x80\x09\x98\x96\x73\x92\x6c\xee\x0d\xbb\x93\ -\x11\x50\xe7\xe7\xb7\x79\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xcd\xa1\x15\x00\x10\x00\x00\xd1\x63\x29\x55\x31\x80\x45\x4d\xe0\ -\x3d\xd9\x52\x9e\xa4\x8a\x8a\xfb\xe9\xda\x81\x24\x49\xbf\x0b\x27\ -\x52\x5b\x03\xc8\x8f\xae\x7d\xd6\x58\x00\xe2\x93\xa1\x24\x49\xd2\ -\xc5\x06\x65\xbc\x05\x04\xc9\x39\x8e\xf8\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xd0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x82\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5d\x88\xd4\x65\x18\xc5\x7f\xe7\x9d\xf1\x2b\xa9\x34\x24\xac\ -\x5c\xab\x25\xfb\x58\x2a\x05\x75\x56\x89\x3e\x34\x51\xd2\x74\x77\ -\x6b\xdb\x88\x22\x41\x14\xa5\x8b\x2e\x82\x4a\x4b\xda\xa2\x32\xbb\ -\x09\xac\xd0\x8a\x20\x04\xaf\xcc\x76\x56\xcd\xed\x03\x0a\xbd\x08\ -\x9d\x5d\xcd\x36\x48\x8a\xc0\xd0\x56\xb7\x0c\x04\x25\xd3\x6c\xe6\ -\x3d\x5d\xcc\xec\x38\xe3\xce\xae\x3b\xd6\x9d\xe7\x66\xf8\x3f\xff\ -\xe7\x3d\xe7\xbc\x5f\xff\xe7\x19\xb8\xd4\xa1\x6a\x92\xa7\xb7\xbb\ -\x26\x91\xa3\xd1\xf2\x1c\x8b\x1a\xcc\x04\x41\x00\x8e\x20\x7a\x8c\ -\x76\x29\x47\x3a\xd3\xac\x9f\xff\x57\x03\x33\xd3\x4e\x45\x7b\x2d\ -\x30\x6b\x88\xa4\x5d\x39\x69\x55\x57\x93\xbe\xfa\x4f\x06\xa6\x6e\ -\xf6\x95\xc9\x64\xdc\x00\x7a\xac\x10\xea\xc5\xde\xee\x10\x3e\x53\ -\x8e\x83\xc3\x23\xbd\x7f\x27\x89\x8e\x8c\x97\xb8\x41\x8a\x73\x41\ -\x0d\xc0\xf5\x05\xf6\x0e\x82\x96\x64\x1a\xf4\x7b\xd5\x06\x66\x6e\ -\xf5\x4d\x31\xe7\x6d\xc0\x6d\x40\xaf\x50\xeb\xc8\xb1\x7c\xb4\x73\ -\x96\xb2\x83\x4e\xa9\xd5\x21\x35\x85\x47\x65\xbf\x06\xd4\x4a\x1c\ -\x8e\xd6\xa2\xce\x87\xd4\x3d\x64\x03\xd3\xb6\xb8\x36\x11\x9c\x01\ -\xc6\x01\x5b\x19\xa9\x27\x33\xf3\x75\x72\x50\xe1\xf3\xf0\x40\x87\ -\x47\x1c\x3f\x13\xd7\x83\x96\x60\x4e\x05\xeb\xee\xdd\xcd\xda\x7f\ -\x41\x03\xf5\x1d\xbe\x82\x33\xde\x0d\xd4\x81\xd7\x65\xba\xc3\x33\ -\xbc\xa2\x58\x8d\x78\x11\xb6\xea\xdb\x59\x89\xbd\x06\xe8\xc9\x5a\ -\xa9\x7d\x0f\xab\xb7\x34\x25\xd9\x6f\xd0\xdf\xf1\x5d\x50\x9d\xcd\ -\xf6\xce\xef\xfb\x8b\x4f\x6f\x77\x4d\x88\x71\x29\xd2\x7c\xcc\x44\ -\x20\x62\x0e\x81\x76\x64\xe1\xc3\x32\x01\xc9\x19\x7b\x6d\x2a\xed\ -\x5a\xa1\xa5\x49\x79\x13\xf6\x1c\x24\x57\x5c\x81\xd4\x16\x4f\x53\ -\x70\x97\xe1\x8f\x5c\x56\x93\xf6\xb5\xe8\x44\xf1\x65\xab\x43\xfd\ -\x14\x9e\xc7\x7e\x09\x18\x59\x79\xc6\x9c\x92\xf4\xc2\x9e\x26\xde\ -\x29\x15\xa9\xdb\xec\xe1\x97\x27\xdd\x0d\xdc\x4a\xd4\x82\x4c\xb3\ -\x3a\xfa\xde\x85\xd2\xf1\x4a\xf8\x0d\x80\x60\xbd\xda\x4f\x7c\x72\ -\xdc\x58\x58\xca\xca\xe2\xf9\xe9\x8c\x36\x5e\x37\x23\x1d\xd7\x63\ -\x17\x27\x77\xa0\x45\x67\x85\x5e\xcc\x2b\x7a\x6d\xe9\xbb\xa2\x81\ -\xa9\x9f\xf8\x1a\xcc\xfd\xc0\xf1\x93\x39\xde\x2f\xe5\xad\x9f\xcc\ -\x6a\xd0\x13\x98\x21\xc1\x68\x45\x7d\x3b\x4f\x97\xc6\xf6\x34\x91\ -\x06\x7e\x04\xee\x48\xa5\xb9\xb3\x9f\x81\x64\x60\x21\x20\xe4\x1d\ -\x07\x5a\x74\xb6\x2f\x3e\x6d\x8b\x6b\xc1\xab\x0b\x33\x1c\x3a\xa2\ -\x5f\xbf\x6b\xab\xaf\x2d\x3e\x4b\x96\xbd\x0d\x20\x38\x36\xf5\x33\ -\x80\xe3\x7d\xf9\x9f\xf0\x79\x29\x4f\x22\x11\x9f\x02\x86\x55\x21\ -\x5d\x10\x64\xf4\x3f\x91\x65\x65\x9e\x14\xbe\x00\xb0\x34\xbb\xbf\ -\x01\x54\x53\x18\xf8\x4b\x19\x91\xb5\xa0\x6a\xf1\xa2\x07\x3f\x58\ -\xfa\x1c\xc4\xc1\x3c\x27\x13\x2a\x18\xc8\x07\x83\x38\x77\x8d\xf2\ -\x87\xa5\xf6\x62\x0d\xd8\x85\x4f\x72\x01\x63\x47\x14\xb8\xc5\x75\ -\x7d\x07\x31\x54\x18\x77\x0e\x2f\xa3\x0b\xe6\x0c\x02\x41\xe2\x02\ -\xdc\x65\xe4\x47\x00\x1c\x19\x5f\x8c\xbc\xa2\x68\x38\x74\xb1\x06\ -\x80\xc3\xa5\x0f\x27\x4e\x17\xb9\x8f\xf6\x7d\xe0\x4a\x0c\xf8\x57\ -\x00\x07\x6e\x2c\xa3\x90\x3b\xb8\x48\x88\xf2\xb1\xb9\x73\xdb\xd9\ -\xd3\x17\x2b\x1a\xb0\xc3\x4e\x80\xe0\x38\xaf\x8c\x44\xe1\x3d\xe0\ -\x62\x6a\xc1\xd9\x98\x0c\x1f\x96\x3b\x8a\x73\x0b\x6a\x5f\xf7\x33\ -\x30\x2c\xc9\x76\x00\xa3\x05\x53\xdf\x77\xf1\xda\x65\x1a\x75\x00\ -\xf9\xed\x6a\xd5\x2d\xad\xe9\x5c\xa4\x73\x37\xca\x16\x68\x11\x40\ -\x54\x48\xf7\x33\xf0\x4d\x83\x8e\x02\x5f\x03\xe3\x86\x5d\xcd\xd2\ -\x52\xb2\xec\xb1\xf0\x1c\xa2\x8a\xad\xf0\xc7\x9d\xdf\xf1\x6a\x69\ -\x64\x46\x1b\x0b\x81\x3a\xe0\x87\xae\x46\x8a\xbd\x41\xd9\x09\x8f\ -\xd6\xca\xbc\x59\xb7\xd6\x77\xf8\x8a\xbe\xf8\xbe\xe5\xfa\x27\x7b\ -\x4c\x8d\xe0\x75\x0c\xbe\x1d\x59\xe1\x35\x13\xb3\xe1\xb1\xd2\x2a\ -\x5a\xb7\xd9\xc3\xad\x7c\x9d\x51\xd0\xaa\x01\xab\x21\x40\xaa\x2d\ -\xb7\x49\xe8\x71\x60\x6b\xa6\x5b\x0f\x9d\x5f\x8e\xa7\xb5\xf9\xf6\ -\x04\x71\x05\xd6\x7c\xc4\x44\xc0\x86\x43\xc2\x9f\xe6\x12\x61\xc3\ -\xde\x06\xfd\x54\xbe\x18\x56\x7d\x3a\x6e\x00\x2d\x07\x76\x66\x9a\ -\x34\x7b\x50\x03\xf9\x3e\xd0\x7b\x80\x5b\x8d\xdf\xea\xec\x0e\xcf\ -\x0e\xd4\x90\x3c\xb2\xd9\x09\x80\x8f\x5b\x94\xab\xb8\x1e\xb6\x52\ -\xed\x3c\x2b\xfb\x4d\xe0\x68\x32\xa1\xe9\x85\xad\x2e\xa2\x62\x79\ -\x29\xf4\x83\x19\xe0\x2a\xa0\x6d\x54\x56\x8b\x77\xb6\xe8\xcf\x8a\ -\x22\x03\x20\xdf\x03\xc4\x77\x41\xcb\x80\xbf\x1c\x75\x6f\x67\xb3\ -\xf6\x9e\x9f\x37\x60\x7d\x4b\xb5\xf9\x66\xe1\x6d\xc0\x2d\xc0\x11\ -\x4b\xad\x97\x8d\x61\xe3\x50\x9a\xd2\x19\x53\x68\x76\xbe\x29\x9d\ -\x04\xf4\xc8\x6a\xd8\xf3\xb0\xbe\xad\x94\x3e\x68\x81\x9d\x92\xf6\ -\x98\x11\x8e\x1f\x80\x1e\x29\x84\x7a\x6c\x6f\x0f\x89\xf0\x59\x2e\ -\xcb\xc1\x64\xa4\xf7\xf4\x30\xe2\xa8\x1c\xe3\x73\x70\x7d\x08\x71\ -\x9e\xf3\x6d\x79\xdf\x07\xe7\xcb\x98\xd5\xe2\xae\x16\xfd\x36\x90\ -\xc6\x90\x2a\x7c\xaa\xcd\x33\x85\xd7\x02\xf7\x0c\x25\xdf\x62\xbf\ -\xd0\xca\x4c\x93\xbe\xbc\x50\x6e\x55\x7f\xcd\x66\xa4\x7d\x83\x23\ -\x8d\xc8\x73\x80\x1a\xf2\x15\x34\x01\xf4\x20\x7a\x40\xbb\x42\x8e\ -\xf4\xee\x66\xfd\x58\x0d\xef\xa5\x8d\x7f\x01\x53\xeb\xdb\x78\xb8\ -\xf8\xe0\x36\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3e\x49\x44\x41\x54\x58\x85\xed\ -\xd3\xb1\x11\x00\x10\x00\x04\xc1\xa3\x32\x89\x0a\xb4\xa0\x2c\x2d\ -\x68\xc0\x98\xd1\x9a\x48\x2a\x24\xb9\x8d\x3e\xbb\xe8\x41\x92\xf4\ -\x59\x38\x23\x97\xba\x80\xf4\x28\x3a\x47\x6f\x19\x20\xbe\x08\x4a\ -\x37\xbe\x40\x92\xa4\xef\x36\xf1\x29\x0a\x07\x7b\xbe\x69\xcc\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0a\x8e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x40\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x8c\x1c\x65\x19\xff\x3d\xb3\xb7\xd7\xbb\x72\xd7\x03\x29\ -\x07\xf5\x76\x76\x76\xaf\x3d\x02\xa1\x25\x2a\x05\x81\xd4\x13\x50\ -\x03\x12\x28\x20\x24\xf2\x11\xa4\x02\x22\xa0\x88\xf2\x65\xd0\x00\ -\x15\x21\xf2\x21\x85\x90\xd4\x02\xb1\x0d\x50\x1a\x31\x28\x10\x31\ -\x7c\x34\xa1\x94\x54\x85\x40\x2d\x88\x8b\x94\x5c\xbd\xdd\xf9\xd8\ -\xeb\x51\xca\x47\x3f\xb4\xd7\xdd\xd9\xf7\xe7\x1f\x77\x6d\x67\x66\ -\x67\x67\x76\xef\xf6\x2e\x46\xfb\xfb\x6f\x9e\xf7\xf7\x7c\xcc\x33\ -\xef\xce\xbc\xef\xf3\xbc\x0b\xec\xc7\x7e\xec\xc7\xff\x33\x64\x2a\ -\x9c\x0c\x6c\xde\x7c\x48\x72\xb7\xdb\x4f\xc1\x3c\x0d\x72\x84\x02\ -\x7b\x01\x1c\x28\x90\x19\x00\x13\x00\xb6\x03\xd8\x4e\x88\x05\xf0\ -\x3d\x0d\xf2\x0f\xd2\x5d\x97\xc9\x64\xf2\x93\x1d\xdb\xa4\x25\xc0\ -\xb2\xac\xd9\x0a\xda\x22\x28\x2e\x84\xe0\xe8\x71\x9a\xc9\x83\xf2\ -\x82\xa6\xa9\x47\x75\x5d\x5f\x2f\x22\x6c\x6a\x90\x68\x72\x02\x48\ -\x4a\xc1\x71\x4e\x15\x85\x9b\x00\x9c\xdc\x4c\xdb\x00\x72\x14\x2e\ -\xf9\x68\xcb\x96\x27\xe6\xcf\x9f\x5f\x6e\x96\xd1\xa6\x25\xa0\x50\ -\x70\x4e\x86\xf0\x1e\x00\xf3\x9b\x65\x33\x1c\x52\x20\xb0\x38\x93\ -\xee\x79\xbc\x19\x33\x62\xc2\x09\x18\x1c\x1c\x3c\x54\x4b\x24\xef\ -\x03\x70\x51\x04\x4d\x11\xf8\xb3\x88\xac\x85\xe2\x46\x26\xf0\xcf\ -\x16\xe0\x63\xd7\x75\x77\xb8\x6d\x6d\x95\xd6\x52\xa9\x93\x6c\xe9\ -\x02\x54\x96\x82\xc3\x01\x39\x41\xc0\xaf\x01\x68\xaf\x65\x90\xc0\ -\x3a\x0d\xea\x2a\xc3\x30\xde\x9d\x48\xfc\x13\x4a\xc0\xa0\x6d\x1f\ -\xa7\x29\x3c\x0b\x60\x56\xc8\xf0\x0e\x81\x3c\x4f\xf2\xb9\x96\x16\ -\x79\x31\x95\x4a\x7d\xd4\x88\x6d\xdb\xb6\xdb\x2b\x15\x39\x45\x44\ -\x9d\x49\xc8\xc2\x1a\x3e\x46\x28\xbc\x34\x9b\x4e\xff\x66\x3c\xf1\ -\x03\x13\x48\x40\xa1\x60\x5f\x08\xc1\x0a\x00\xd3\xaa\x82\x02\x1e\ -\xd4\xa0\xee\x32\x0c\xe3\x93\xf1\xda\xf7\x22\x97\xcb\xb5\x76\x74\ -\xcc\xf8\x0e\x44\x6e\x05\xd0\x5d\x45\xa0\xdc\x69\x18\x3d\xb7\x8a\ -\x88\x6a\xd4\x76\xc3\x09\x20\xa9\x59\x96\x7d\x07\x21\x37\x07\x86\ -\x14\x80\x15\x2d\x09\xf9\x59\x2a\x95\x72\x1a\xb5\x5b\x0f\x36\x6e\ -\xfc\xb0\xb3\xbd\x7d\xe4\x3a\x02\x37\x00\xe8\xf0\x07\x86\x67\xa7\ -\x4f\x9f\x76\x71\x77\x77\xf7\xce\x46\x6c\x36\x94\x00\x92\x9a\x69\ -\x16\x57\x41\x78\x7e\x60\x68\x48\x69\x38\xa7\x57\xd7\xdf\x68\xc4\ -\xde\x78\xe1\x38\x4e\xca\xad\xf0\x19\x54\xbf\x70\xdf\x2a\x97\x46\ -\x4e\xea\xeb\xeb\xdb\x5e\xaf\x2d\xad\x11\xc7\xa6\x5d\x5c\x5c\x75\ -\xf3\x82\xd7\xc1\xca\xfc\xa9\xba\x79\x00\x48\xa5\x52\x4e\x42\x43\ -\x3f\x80\x55\x81\xa1\xcf\x27\x5b\xdb\x56\x91\x4c\xd4\x6b\xab\xee\ -\x19\x90\xb7\xac\x6f\x0a\xe5\x49\xbf\x32\x1f\x53\xaa\x72\x65\x36\ -\x9b\x1d\xa9\xd7\x4e\x33\x41\x52\x2c\xcb\xb9\x91\xc0\x5d\xf0\xdc\ -\x0b\x81\x7b\xb2\x86\xfe\xe3\x7a\x6c\xd4\x95\x00\xcb\xb2\xe6\x2b\ -\xca\x3a\x00\x6d\x1e\xf1\x13\x46\x3a\xf5\xad\xc9\x58\x9d\x35\x8a\ -\xbc\xe9\xfc\x50\xc0\xfb\xbd\x32\x81\x5c\x62\x18\xa9\xc7\xe3\x74\ -\x63\x13\xe0\x38\xce\xc1\x6e\x85\x7f\x03\xd0\xe3\x51\x7a\x43\x29\ -\xf7\xcb\x8d\x3e\xf9\x42\xa1\x70\x24\xb4\x96\x73\x84\x38\x9a\x50\ -\x29\x40\x52\x00\x2a\x02\x38\x14\x38\x50\xdc\x00\xa8\xa7\x1b\xdd\ -\x03\x90\x14\xd3\x2c\x2e\x87\xf0\xdb\x1e\x71\x09\x4c\x9c\x90\xc9\ -\x7c\x76\x43\x94\x6e\x6c\x02\x0a\x96\xbd\x1c\xc4\xa5\x1e\xd1\x90\ -\x26\x3c\x36\x9d\x4e\x0f\xd5\x13\x5c\x2e\x97\x6b\xed\xec\xec\xba\ -\x8a\xc0\x95\x00\x8e\xa8\x47\x07\xc0\x5b\x14\x3e\x98\xd1\xf5\x95\ -\x22\x52\xa9\x47\x61\x60\x60\x60\x5a\xb2\xb5\x6d\x0d\x80\x13\xf7\ -\x49\xb9\xc1\x48\xeb\x5f\x14\x11\xb7\x96\x5e\x64\x02\x4c\xd3\x5c\ -\x40\x68\xeb\x3c\x22\x52\xc9\x89\xd9\x6c\xea\xf5\x7a\x82\xca\x5b\ -\xd6\xd9\x42\xb9\x17\xc0\x9c\x7a\xf8\x21\x78\x1b\x94\xeb\x33\x99\ -\xd4\x9a\x7a\xc8\x63\xab\xd2\x1c\x80\x99\x7b\x64\x02\x5c\x6b\x18\ -\xfa\x83\xb5\x74\x6a\x7e\x05\x48\x0a\x91\xf8\x45\x40\xbc\xaa\x9e\ -\x9b\x5f\xbf\x7e\x7d\xb2\x50\x70\x96\x0a\xe5\x19\x8c\xff\xe6\x01\ -\xe0\x73\x10\xbe\x9c\x37\xed\xc5\x24\x63\xbf\x58\xbd\xbd\xbd\x1f\ -\x10\x72\xa7\x57\x46\xe0\x96\xe1\xe1\xe1\x03\x6a\xe9\xd4\x34\x5a\ -\x70\x9c\x7e\x80\x0b\x3c\xa2\xb2\x40\xdd\x16\x17\x84\x69\x9a\x07\ -\xcd\x3c\xe4\xd0\x17\x20\xbc\x3a\x8e\x5b\x2f\x04\xb8\xcd\xb4\x9c\ -\xdf\x16\x8b\xc5\xe9\xb1\x64\x55\x7e\x08\x02\xcb\x23\x99\x39\x52\ -\x2a\x7d\xb7\x16\xbd\x66\x02\x44\xe1\xc6\x40\x14\x0f\x1b\x86\x31\ -\x18\xe5\x3b\x97\xcb\xb5\x02\xda\xb3\x00\xbe\x12\x1b\x68\xe3\x38\ -\xaf\xec\xaa\xc7\xe3\x66\x42\x36\x9b\x1d\x21\xe8\x7f\x50\x94\xeb\ -\x6a\xad\x0d\x42\x8d\xe5\xf3\xf9\xc3\x00\x9c\xe6\x11\x95\x95\x5b\ -\xbe\x23\xca\x31\x49\xe9\xe8\xec\x5a\x4a\xa0\x3f\x8a\x37\x41\x9c\ -\x5b\xb0\x9c\xd8\x59\x98\xd1\xf5\x95\x04\x06\x3c\xa2\x9e\x82\x6d\ -\x7f\x35\x8c\x1b\x9a\x00\x49\x24\x2e\x04\xb0\x37\x63\x02\xac\xe9\ -\xed\xed\xfd\x20\xca\xa9\x65\x39\x17\x01\xb8\x3c\x2e\xb8\x89\x42\ -\x80\x5b\x4d\xb3\x18\x7a\x33\x7b\x39\x22\x15\x21\x9f\xf2\xc9\x94\ -\x5c\x12\xc6\xad\x31\x9d\xe4\x4c\xef\x15\x85\x7f\x88\x72\x58\x2c\ -\x16\xa7\x8f\xad\xc6\xa6\x04\x0a\x6a\x49\xdc\x72\x97\x09\xf1\xc7\ -\x2c\x38\x3d\x4c\xa7\x2a\x01\xc3\xc3\xc3\x07\x80\xde\x6f\x29\x50\ -\x29\x27\xfe\x18\xe5\xac\x5c\xae\x5c\x07\xcf\x42\x69\xb2\x21\xc0\ -\x3c\xd3\x74\x16\x45\x71\x32\xa9\xd4\x9b\x80\x78\x67\x6d\x57\xde\ -\x71\x8e\x09\xf2\xaa\x12\xb0\x7b\xb7\x7b\x3c\x80\x56\x8f\xe8\xed\ -\xd9\xb3\x7b\xac\x20\x6f\x0f\x46\xb3\x2a\x3f\x88\x0f\xbb\xb9\xa0\ -\xe0\xda\xa8\x71\x11\x51\x10\xfa\x1e\x5c\x42\x55\xd7\x29\x43\x7e\ -\x02\x9c\x1b\x10\xac\xab\xe6\xec\x43\xa1\xe0\x7c\x09\x82\x43\xa2\ -\x38\x93\x01\x01\xe6\xd9\xb6\xdd\x17\xc5\xe1\xe8\xfe\x65\xdf\x35\ -\x70\x54\x90\x13\x96\x80\x23\x03\x8e\x06\xaa\x39\x9e\xf1\x04\xce\ -\x0b\xe8\x47\xd1\x9b\x0a\x57\xe1\xdc\xa8\x71\xa1\x04\x63\x3f\x32\ -\xc8\x09\x49\x80\x64\xbc\x57\xa4\x44\x7e\xfb\xa1\x82\x45\x89\x29\ -\xe9\xb5\xec\xf1\x54\xf5\x9b\xf6\x82\x2c\x05\x63\xcf\x06\x39\x55\ -\x09\x20\xd0\xe9\x73\x22\xf2\x69\x4c\x14\x53\xf6\xf2\x0b\xf1\x9d\ -\x8a\x61\x04\x63\xef\x0c\x12\x62\x13\x50\xa9\xb0\x66\x8d\x6d\x6c\ -\x55\x16\x56\xad\x9d\x1a\x30\x3a\x01\x99\x4c\x66\x37\x00\xef\x4e\ -\xb0\x75\x74\xb5\xba\x0f\x55\x09\x90\xe0\x1c\x4e\x32\xea\x47\xad\ -\x85\xd9\x98\x3a\x48\x72\xa2\x16\xc2\x82\xdf\xe1\xbd\x48\x28\xad\ -\x6a\xda\xec\x75\x3f\xba\xcf\x8e\x5c\x21\x4e\x2e\x18\x59\x7d\x2e\ -\x14\x0a\xd3\x00\xb4\x78\x44\xa5\xb9\x73\xe7\x96\xbc\x9c\xb0\x19\ -\xe0\xab\xa8\x92\x3c\x30\x26\x8a\x62\xcc\xf8\xa4\x41\x80\xc8\x04\ -\x90\xec\x0a\x88\x76\x04\x39\x55\x09\x50\x80\x19\x30\x53\xf5\xe6\ -\xf4\x07\xc1\x5c\xd4\xf8\x64\x82\x94\x48\xdf\x9a\xd6\xda\x1b\x10\ -\x15\xaa\x38\xd5\x6a\xf2\x9e\xcf\x89\x20\x72\xb1\x21\x82\xa7\xa3\ -\xc6\x27\x17\x5a\xa4\x6f\xa9\x8e\x7d\x63\x95\x85\x6a\x41\xc5\xd7\ -\x6c\x14\x7f\x51\xa4\x0a\x95\x4a\x65\x35\x80\x86\xba\x31\x4d\x82\ -\x69\x18\xb3\xde\x8a\x22\x30\x10\x3b\x81\xaa\x19\x53\x95\x80\xf6\ -\xf6\xf6\xd7\x00\x78\xfa\xef\xf2\x05\xc7\x71\x6a\x7e\x6e\xb2\xd9\ -\xec\x08\x04\x8f\xc6\xc7\xdb\x64\x88\x3c\x12\x55\x92\x1f\xfb\x44\ -\x9f\xe1\x13\x2a\x59\x1b\xe4\x55\x25\xa0\xbb\xbb\x7b\xa7\x00\xaf\ -\x79\x65\x65\x15\x30\x14\x40\x39\xd9\x72\x3b\x80\x6d\xd1\x11\x37\ -\x0f\x02\xd8\x09\xf1\xf7\x01\x82\xb0\x6d\xfb\x18\xf8\xd7\x28\xdb\ -\x33\x99\x9e\xf5\x41\x5e\xe8\x37\x9c\x84\x6f\x17\x25\xe0\xc2\x28\ -\x67\x7d\xb3\x66\x7d\x08\x32\xb2\x62\xd4\x64\xfc\x44\xd7\xf5\x5d\ -\x51\x04\x05\xcd\x17\x33\xc1\x17\xc3\xca\xe3\xa1\x09\xd0\x34\xae\ -\xc2\x68\xb7\x77\x8f\xf6\x29\x03\x9b\x37\x47\xee\xf8\x0c\x43\x7f\ -\x40\x80\x97\xa2\x38\x8d\x23\x74\x86\xaf\x4c\xa7\x53\xc1\x9e\xa0\ -\x5f\x8b\xd4\x40\xfa\x36\x69\x42\x79\x2c\x8c\x1b\x9a\x80\x74\x3a\ -\x3d\x04\x62\xb5\x47\x34\x2d\xb9\xbb\x1c\x6c\x87\xfb\x20\x22\xae\ -\x52\xee\xf9\x00\xde\x8f\xe2\x35\x06\x09\x5e\xbe\x4e\xe5\x5e\x11\ -\xd7\x8e\x33\x4d\xe7\x02\xf8\x9b\x30\xc3\x86\x91\x5a\x1d\xc6\xad\ -\x5d\x15\x16\xf9\x65\x40\xf0\xbd\xc1\xc1\x21\x23\xca\x71\x36\x9b\ -\xfd\x54\xa0\x4e\x47\x53\x93\xb0\x17\xeb\x95\x5b\x3e\x3b\xae\x1d\ -\x97\xcb\xe5\x5a\x21\xf8\xb9\x57\x26\xc0\xfd\xb5\xba\x43\x35\x13\ -\x90\x4e\xf7\xac\x81\xff\x65\xd8\x9a\x48\xa8\xc5\x71\x51\x1a\x86\ -\x31\x48\xe5\x1e\x2f\x40\x68\xc6\xc7\x05\xca\x93\x09\x0d\xfd\x71\ -\x85\x59\x00\xe8\xe8\xe8\xba\x02\xfe\x6d\xef\xc7\xbb\x76\xb5\x2d\ -\xab\xc5\x8f\xdc\xbc\xe7\xf3\xf6\x49\xa2\xe1\x15\x8f\x48\x09\xd4\ -\x71\x86\x61\xfc\x35\x36\x66\xb2\xc5\xb2\x9c\xeb\x09\xfc\x14\x21\ -\xdb\xd0\x3a\xb1\x95\x22\xb7\x64\xf4\x9e\x87\xeb\xe9\x42\x17\x8b\ -\xc5\x99\x65\x57\xbd\x0b\xef\x31\x1a\xf2\x86\x4c\x26\x7d\x5f\x2d\ -\x9d\x98\x26\x83\xbe\x16\xc0\x4a\x3f\x5f\x7b\x66\x70\x70\xf0\xd0\ -\xb8\x60\x44\xc4\x35\x0c\xfd\x6e\xb7\x9c\x9c\x03\xca\x32\x00\xff\ -\x8e\xd3\xf1\x60\x9b\x00\x77\x55\xdc\xd2\x9c\x6c\x3a\xf5\x50\x3d\ -\x37\x9f\xcb\xe5\x5a\xcb\x65\xf5\x3b\xf8\x6e\x1e\xef\x6c\xdd\xba\ -\xa5\x66\x5f\x10\xa8\xa3\x7c\xb3\x69\xd3\x70\x77\x4b\xd2\x7d\x07\ -\xa0\xf7\xa6\xff\x52\x2e\x8d\x9c\xd2\xd7\xd7\xb7\x3b\x4e\x7f\x0f\ -\x8a\xc5\xe2\xf4\x72\x59\x9d\x06\x0d\xe7\x92\x98\x27\xa3\x55\xe4\ -\xcf\x8c\x05\xfa\x21\x34\x0c\x41\xc9\x06\x80\x4f\xed\xdc\xb9\xed\ -\xe5\xe0\xae\x2d\x0e\xa6\x69\x2d\x23\xe4\x4a\x8f\xa8\xac\x34\x2c\ -\x88\x3b\xb9\x52\x57\xfd\x2a\x9f\x77\x8e\x17\x8d\x6b\xe1\x3d\x11\ -\x26\x58\x61\xe8\xa9\xcb\x27\x72\x40\xc2\xb6\xed\xf6\x91\x91\x11\ -\xd5\x48\x22\xc3\x50\xb0\xac\xab\x41\x59\xea\x13\x12\x97\x67\x32\ -\xfa\xf2\x38\xdd\xba\x0b\x78\xa6\xe9\x5c\x4c\xd0\x77\xe2\x82\xc0\ -\x23\xff\xda\xb1\xed\x9a\x46\x9f\x56\xb3\x30\x76\x44\xe6\x1a\x02\ -\xf7\xc3\xf3\x73\x16\xf0\x01\xc3\x48\xff\xa8\x1e\x1b\x0d\x55\x30\ -\xf3\xa6\x7d\xb7\x00\x37\xf9\xa3\xc0\xab\xc9\xa4\x76\x5e\x4f\x4f\ -\xcf\xd6\x46\x6c\x4d\x14\xb9\x5c\xae\xb5\x63\x46\xd7\xaf\x40\x5c\ -\xe6\x95\x0b\xf0\x52\x3a\x9d\x3a\x23\xea\x50\x44\x80\x5f\x3f\x48\ -\x26\x4c\xdb\x79\x0a\xc4\x39\x01\x33\x85\x84\xc6\x85\xba\xae\xff\ -\xbd\x11\x7b\xe3\xc5\xd8\x7b\xe9\xf7\xa8\xde\xa9\xbe\x4b\xe5\x2e\ -\xc8\x66\xb3\xd1\x85\x5c\x0f\xc6\x73\x50\x32\x61\x9a\xf6\xbd\x10\ -\x09\x4e\xb1\x32\x81\x65\x95\x72\xf2\xce\x39\x73\x0e\xdb\xd2\xa8\ -\xdd\x7a\x30\x7a\x7c\x16\xdf\x87\xe0\x66\x00\x07\xf9\x06\x05\x2f\ -\x54\xca\xa5\x0b\x66\xcf\x9e\xdd\xd0\xa6\x6c\x22\x47\x65\x2f\x83\ -\x60\x19\x80\x60\x61\x72\x27\x81\xfb\xdc\xd2\xc8\x92\x46\x0e\x2c\ -\x46\x81\x64\x8b\x69\x3a\x8b\x20\x58\x8c\xb0\x1e\x24\x65\x89\x61\ -\xf4\xdc\x54\xef\x79\x22\x2f\x26\x76\x58\xda\xb2\xfa\x35\xca\xd3\ -\x00\x0e\x0e\x19\xfe\x84\xe0\x73\x1a\xb4\xe7\x4a\xa5\x5d\xab\x1b\ -\x4d\xc6\xe8\xe1\xaa\x83\xfa\x15\xd4\x99\x02\x9c\x05\x20\x6c\x19\ -\x5e\x06\x71\x55\x3d\x6f\xfb\x5a\x98\x70\x1b\x67\x53\xb1\xa8\xb7\ -\x54\xd4\x03\x20\xbe\x11\x41\x2b\x03\x7c\x15\xa2\xbd\x02\xc5\xf7\ -\x95\x92\x4d\x6a\x9a\x7c\x9c\x74\xdd\x9d\xa5\x52\xa9\xd2\xd6\xd6\ -\xd6\xa9\x94\xea\x22\x13\x59\x6a\x38\x1c\x54\x27\x08\xe4\x54\x00\ -\x33\x6a\x19\x24\xf0\xe6\xd8\x71\xf9\xd8\x55\x69\x14\x9a\xf8\x87\ -\x09\xfb\xeb\x14\xdc\x2d\xc0\xbc\x66\xd9\xac\x81\x21\x42\x6e\xcf\ -\xa4\x7b\x7e\x3d\x9e\x29\x1f\x44\xb3\xff\x32\xa3\x99\xa6\x73\x16\ -\x05\x37\x0b\x70\x6c\x33\x6d\x03\x18\x04\xb9\x84\xac\x2c\x6f\xe6\ -\xd1\xdc\x49\xeb\x64\x9a\xa6\x79\x14\x45\x5b\x04\x85\x85\x10\x1c\ -\x3e\x4e\x33\xc3\x10\x3c\xaf\xc0\xc7\xb2\xba\xfe\xa7\xf1\xfc\x1f\ -\x20\x0e\x53\xd2\xca\xdd\x54\x2c\xea\x49\x97\x27\x2b\xf0\x28\x40\ -\x8e\x00\x98\x15\x41\x17\x88\x19\x18\xed\xdc\x6c\x03\xb8\x5d\x20\ -\xb6\x02\x36\x42\xb8\x51\x23\x5f\x4d\xa7\xd3\xef\xfd\x37\x9c\x45\ -\xde\x8f\xfd\xd8\x8f\xff\x5d\xfc\x07\xbb\x1b\xfe\xd4\xc4\x32\xd9\ -\x11\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x3e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xed\ -\xd6\x3f\x68\x13\x61\x18\xc7\xf1\xef\xf3\x5e\x62\xa5\x82\x8a\x1d\ -\x14\x5d\x44\x9c\x1c\xfc\x13\xcc\xe0\xe0\x28\x5d\xea\x24\xc1\x45\ -\xd1\x45\xd2\xda\x34\x05\xc1\x51\x4a\x70\x74\x50\x92\x5a\x6b\x40\ -\x10\x75\x10\x8b\x5b\x10\xc5\xd1\xa1\xa0\x6d\xc4\xc5\xc9\xa1\x93\ -\x28\x48\x4b\x87\x8a\x35\xc9\xfd\x1c\xee\xb2\x38\xdd\x5d\x8e\xcb\ -\xa0\x0f\xdc\x76\xcf\xfb\xfb\xf0\xdc\xfb\xde\x1d\xfc\xeb\x65\x51\ -\x6e\x3a\x5d\xae\x6f\x80\x59\xbe\xdb\x39\xb2\xfc\xe8\xc6\x7a\x9a\ -\x00\x17\xf1\xbe\xbd\xa0\x3d\x9d\x5c\xae\x75\xfc\xf2\x9d\x5d\xc3\ -\x00\xf4\xeb\xcc\xc8\xe8\xc8\xcb\x63\xa5\xb9\x1d\xc3\x02\x20\x18\ -\x1f\xdd\x37\xf6\xa4\x54\x7a\xe1\x65\x0e\x10\xf8\x60\x02\x2e\xae\ -\x8d\x7d\x6b\x80\x22\xed\xa1\xd4\x00\x06\x12\xbe\x00\x24\xa6\x8a\ -\x93\xf5\x5a\xa6\x80\x00\x61\x92\xe1\x07\x08\xbb\x55\x2c\x37\x66\ -\x33\x05\x00\x98\x90\x50\x80\x40\xf7\x8a\xe5\xc6\xa5\x4c\x01\xf0\ -\xd7\x24\xd0\xe3\xc2\xe4\xfc\x44\xa6\x00\x08\x26\x81\x10\xe0\x39\ -\xf9\x4b\x85\xa9\xfa\xd9\x4c\x01\x81\x02\x3f\x44\xec\x74\x3e\xad\ -\xe2\xb5\xbb\x27\xb3\x05\x84\x08\xc9\x04\xec\x96\xf3\x5e\x17\xae\ -\xdf\x3f\x9a\x2d\x00\x30\x53\xff\x1d\xb1\xdf\x7a\xbd\xb7\xa7\x2a\ -\x8d\x83\x99\x02\x82\x0a\x4e\x86\xc1\x61\xd7\xd1\xab\x21\x00\x00\ -\x44\x88\x38\x31\x04\x80\x39\x30\x04\x6b\xbd\xbc\x1d\x8a\xd2\x91\ -\x4b\x2b\x5a\xe0\x2c\xf8\x36\x7c\x97\xe7\x9d\xfb\x38\x3f\xfd\x35\ -\x4a\x5f\x5a\x13\x70\x16\xfc\xdc\x6c\x3a\x18\x6f\x2f\x4c\x7f\x89\ -\xdc\x98\x46\x38\x41\xf8\x2f\xdf\x71\xfe\xfd\xc3\xea\xa7\x38\xcd\ -\x83\x3e\x02\x0b\xaf\x9e\x6f\xae\xd4\x7e\x50\x79\x17\x77\x81\xc4\ -\x13\x90\xc9\xfa\xfd\x86\x5d\x6d\x2f\x56\x5a\x49\xd6\x49\x3a\x01\ -\x33\x99\x03\x90\x98\x5d\x69\xce\x3c\x4b\xb8\x4e\x92\x09\xc8\x40\ -\x2e\x54\xdc\x5e\x6d\x56\xeb\x49\xc3\x63\x03\x84\x0c\xf5\xcf\xba\ -\x16\x3e\x2c\x56\xe7\x06\x09\x8f\x0d\x30\x70\x18\x20\x7b\xbe\x7a\ -\x60\x7d\x26\x7c\xf7\x0f\x54\x31\xf7\x80\x61\xf0\x66\x6b\xe3\xc7\ -\x15\x9a\x35\x7f\xd0\x70\x88\xbf\x07\x96\xb7\x7f\x6e\x5f\xf8\xbc\ -\x54\xfb\x9d\x46\x38\x44\x9c\x80\x60\xd3\xc0\xf2\xdd\xee\xc4\xca\ -\xd3\x9b\x5b\x69\x85\xff\x2f\x80\x3f\x94\x18\xa2\x63\x8f\xc5\xfb\ -\x89\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ -\xce\x49\x0d\x00\x31\x0c\x04\xc1\x5c\x90\x0c\xca\x2c\x36\x14\x4c\ -\x25\xfc\x72\x80\x98\x95\xfc\xe9\xfa\xcf\xa8\x4b\x11\x98\xc7\x34\ -\x8f\xa9\x7c\x34\x65\xfc\x07\x02\x08\x20\x80\x00\x02\x08\x48\x0f\ -\x18\xf2\xc3\xad\x9f\x79\xe4\x04\xdc\xd3\x57\x6d\x5b\xb9\x00\x00\ -\x00\xf9\x1e\xf2\x23\x09\xdd\x64\x85\x0e\x0a\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xd0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x82\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\x31\x0e\x82\x50\x10\x04\xd0\x81\x43\x10\x1b\x13\xce\xe4\x15\ -\xa8\x38\x11\x37\xf1\x3c\x24\x36\xc4\x43\x88\xad\xe1\xdb\x22\x86\ -\xff\x5e\x39\xd9\x62\x76\xbb\x4d\x00\x00\x00\x00\x00\xa8\x47\xb3\ -\x0d\xe6\xf9\x71\x4b\x93\x29\x49\x77\x40\x9f\x3d\x2d\x59\x33\xf4\ -\xfd\xf5\xfe\x19\xb6\xc5\xd8\x39\x97\x4f\x92\x4b\xda\x4c\xdb\xb0\ -\x3c\x40\x65\xca\x03\xac\x19\x93\x3c\x7f\x5f\x65\x77\x4b\x5e\x19\ -\x8f\x2e\x01\x00\xfc\x0f\xbf\x40\x31\x76\xce\xe5\x13\xbf\xc0\x77\ -\x7e\x01\x00\x00\x00\x00\x00\x00\x2a\xf1\x06\x74\xea\x1a\x0f\x1a\ -\xcd\x17\x42\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x2e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe0\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xbd\x6b\x14\x51\x14\xc5\x7f\x67\x46\x8d\x20\xf1\xab\x90\x85\ -\xcd\xec\x18\xc1\x2e\x85\xa5\x95\x65\x04\x25\x8d\x85\x56\x0a\x76\ -\x36\x42\xfe\x00\xb1\x10\x7b\x11\x04\x4b\x41\x2b\x2d\x6c\x82\x85\ -\xa6\xb3\xb2\x14\xd9\x4e\xc8\x3a\x3b\xbb\xb0\x58\x69\x82\x90\x0f\ -\x76\x8e\xc5\xac\xb5\xfb\x66\x1e\x0a\x7a\xab\x79\xc3\xbc\x73\x7e\ -\xf7\xbe\xfb\xde\x1b\xf8\xdf\x43\xb1\x05\xcb\xb2\x3c\x3d\xad\xd8\ -\x02\xfb\x6c\xde\x3b\xf5\xbb\xef\x0f\xc5\x34\x9f\x4c\x26\xc7\x76\ -\xf7\x0f\xde\x00\x27\xe6\xcd\x2d\x1a\x40\xbf\xdf\x3f\xb2\xb7\x77\ -\xf0\x1a\xb8\x18\x32\x2f\x89\x61\x6e\x3b\x5d\x5c\x3c\xf9\xdc\xb0\ -\x8a\x1d\x34\xb7\x35\x80\x6d\x0d\x87\xe5\x13\xe3\x1b\xf5\x1b\x55\ -\x7f\x14\xa0\x28\xc7\x0f\x8c\xee\x00\x18\x2a\x44\x50\x09\x5a\x01\ -\x0c\x8a\xd1\x3a\xf6\x3d\xdb\x80\x2b\x11\x66\xde\x0a\xa0\x28\x46\ -\x37\x85\x1f\x01\x24\x52\x05\x0a\x36\x6f\x0c\x50\x14\xe3\x35\xe3\ -\x67\xf5\x48\x95\x1b\x64\xde\x18\x60\x6b\x38\xbc\x64\xaa\x57\x40\ -\x5a\x1b\x07\xb6\x7d\x1b\x80\xc1\x60\x74\x21\xb1\x36\x80\xa3\x60\ -\x0b\x82\x3a\xbe\x15\x40\x59\x96\xe7\x95\xf8\x2d\x70\x1c\x70\xe8\ -\x76\x6b\x05\x50\x96\x65\x77\x5a\xb1\x09\x9c\x99\x75\x7a\x14\x73\ -\x98\xf3\x28\x9e\x56\x8c\xea\x27\xe3\x48\x99\xff\x8a\xf9\x96\xc0\ -\x7c\x8a\x69\x1a\x0c\x90\xa6\x5c\x01\x7d\x01\xa1\x48\xf7\x47\x10\ -\x40\x96\x65\xe3\x34\xf1\x2a\xf0\xd5\xf5\x3d\x1b\x0d\x62\x6e\xa1\ -\x2c\xcb\x3e\xbb\xd2\x65\x60\x1b\x10\x8e\x03\x11\x24\xb2\xbc\xbc\ -\xf4\xb1\x92\xd7\x80\x5d\x84\x1c\xa1\x12\xc1\x02\xe7\x7a\xbd\xf7\ -\x22\xb9\x0e\x4c\x05\x52\xcb\xdf\xba\x46\x19\xe4\x79\x77\x43\xe8\ -\x36\xc0\xac\x0a\x8d\x21\x1a\x97\x30\xcf\x97\x5e\x08\xd6\x01\x6c\ -\x37\x86\x68\xb5\x86\x79\x9e\x3d\x46\x7a\x28\x69\xa6\xe5\x60\x88\ -\xd6\x4d\x94\x67\xdd\xfb\x58\x4f\xeb\x91\x12\x3b\xac\x12\xad\x01\ -\x24\x39\xcf\xbb\x77\x85\x5e\xd6\xe3\x30\xcd\x28\x7b\x59\xd2\x74\ -\x67\xe7\xdb\x2d\xc1\xbb\xd0\xb9\xd1\x4e\xb4\x95\x95\x95\xfd\x85\ -\x85\xc3\xd7\x10\x1f\xfe\x0a\x00\x40\xa7\xd3\xf9\x91\x8a\xab\xb6\ -\xb7\xc1\xdf\x63\x6a\xff\xbb\xf1\x13\xb6\x0b\xa1\x01\x61\x9e\xcd\ -\x4b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x98\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x0d\xc0\x30\x08\x04\x41\x82\x5c\x1b\x15\x50\x02\x7d\x98\ -\x9a\x52\xa0\x9d\x22\x2e\x12\x9f\x9d\xff\x9d\xd6\x4c\x10\x59\x1d\ -\x59\xad\x7c\xb8\x32\xfe\x03\x01\x04\x10\x40\x00\x01\x04\x8c\x07\ -\x2c\xf5\xe0\x5e\xdb\x91\x35\x13\xf0\x1c\x7f\xcd\x8f\x72\x01\x00\ -\x00\xe6\x7d\x0c\xb6\x09\x4f\xb2\x71\xd6\x0c\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\x77\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x29\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x53\xb8\x9e\x44\x40\xc6\xf1\ -\x48\x0c\xb4\x55\x00\x40\x58\xef\x39\x37\x39\xb0\x92\x71\x00\xe0\ -\x0b\x0f\xd3\xb2\x02\xe6\x6a\x84\x46\x98\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x9a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x76\xf2\xda\xc4\x4d\x10\xb8\ -\x99\xb4\x41\xa6\x74\x7c\xef\xf8\x83\xf0\x5d\x15\xa1\x64\xba\xdc\ -\x74\xb9\xbd\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf2\x9f\x51\x93\ -\x9d\xda\x29\xe8\x00\x81\xd7\x0c\xbd\xf7\x79\x8f\x39\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xee\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x53\xb8\x46\x22\x20\x23\x3c\ -\x1a\x03\xeb\x6d\x0c\x68\xed\x73\xd7\x3e\x57\x36\x4c\x39\xfe\x83\ -\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\ -\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\ -\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\ -\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\ -\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\ -\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\ -\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\ -\x75\x80\x0e\xd0\x3a\x40\x07\x68\x0f\xaf\xe7\x06\x43\x97\x92\x59\ -\xbc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xea\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9c\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5d\x6c\x14\x55\x14\xc7\x7f\x67\xa6\x5b\xaa\x15\x6a\x94\x34\ -\x68\x77\x66\xa7\x8b\x4d\x90\x54\x9f\x2a\x09\x0f\xf8\x81\x04\x12\ -\x91\x0f\x49\xd4\x10\x8d\x24\x08\x91\xf8\xe0\x83\x09\x0a\x4a\xe4\ -\x01\xc5\xfa\x62\x82\x12\x50\x43\x62\x4c\x78\x33\xb1\x81\x0a\x28\ -\x89\x04\x9e\x90\xd0\x84\x90\x54\x03\x59\xda\xdd\x9d\xd9\xa5\x62\ -\x8d\x09\x22\xa8\xed\xce\x3d\x3e\xec\x07\xb3\xdd\x6e\xbb\xad\xbe\ -\x71\x5e\x76\xe6\xdc\xff\x39\xff\xff\xbd\x77\xee\x3d\x67\xe1\x4e\ -\x37\x99\x09\xf8\x4a\x3e\xef\xc4\x0a\x66\xbd\x41\x56\x08\xea\xa0\ -\xc4\x11\x2c\x94\x3c\x42\x4e\xe0\x8c\x65\xd1\xe7\x38\x4e\xea\x7f\ -\x15\x30\x1c\x04\x4b\x2c\x43\x2f\xf0\x54\x23\x78\x85\xf3\x16\xb2\ -\x33\x91\x88\xff\xf0\x9f\x04\x0c\x0d\x0d\xb5\xd9\x76\xf3\x41\x84\ -\x8d\x25\xd7\x88\x42\x3f\xa2\x27\x54\x64\x38\x6c\x6a\x1a\xb9\x2b\ -\x0c\x4d\x18\x86\x0b\x54\x6d\x4f\x45\x57\x0a\xac\x03\x12\x25\xfc\ -\x71\x13\x8e\x6f\x4e\x26\x93\xd7\x66\x2c\x20\x08\x82\x87\x42\xa3\ -\x47\x41\x1e\x06\x46\x04\x76\xbb\x6e\xfc\x4b\x11\x29\x4c\x25\x5a\ -\x55\xad\x4c\x10\xbc\x28\x2a\xef\x03\x49\x04\xdf\x14\x64\x6d\x32\ -\x19\xbf\xd8\xb0\x80\x6c\x36\x9b\x54\xac\x73\xc0\x7c\x81\x23\x63\ -\x63\x7f\xbf\xd2\xd5\xd5\xf5\xc7\x54\xc4\x13\x2d\x95\x4a\xcd\x89\ -\xcd\x69\x39\x80\xb2\x19\xb8\x89\x5a\xcb\x3c\xaf\xe3\xc2\xb4\x02\ -\x52\xa9\xd4\xbc\x58\x73\xcb\x59\x60\xb1\xc2\x3e\xcf\x8d\xbf\x29\ -\x22\x66\x26\xe4\x65\x53\x55\xc9\xf8\xf9\x1d\x82\xee\x05\x72\x68\ -\xb8\xc4\xf3\xbc\x91\x28\xa6\x69\x62\x50\xac\xb9\x65\x7f\x91\x5c\ -\xfb\x3d\xd7\xa9\x21\xbf\x92\xcf\x3b\x76\xc1\x6c\x11\x78\x06\x70\ -\x01\x83\x92\x05\x3d\x06\xe6\x50\x94\x40\x44\x54\x55\x7b\xb3\x7e\ -\x2e\x09\x6c\x41\xec\xc3\xaa\xba\x42\x44\x74\xd2\x15\xf0\x7d\xbf\ -\xc7\xa8\x9c\x47\x19\x0d\xc3\xb1\xae\x85\x0b\x17\x5e\x8f\xcc\xc6\ -\xca\xf8\xf9\xb7\x05\x7d\x0f\x68\xa9\x33\xe9\x9b\x02\xef\xb8\x6e\ -\xfc\xd3\x28\xc9\xe0\xe0\x60\xf3\x3d\x73\xdb\x2e\x02\x8b\x50\x56\ -\x7b\x9e\x73\xbc\x3c\x66\x45\xa3\x8d\xf2\x61\x51\x39\x7b\x26\x92\ -\x67\xfd\xdc\x57\xa5\xa5\xac\x47\x0e\xd0\xaa\xb0\xcf\xf7\x83\x03\ -\xaa\x5a\x99\x5c\x77\x77\xf7\x18\xca\xbb\x00\x2a\xf4\x46\xc7\x2a\ -\x02\x32\x99\xcc\x03\x20\x4f\x03\xbf\xdf\xb8\x71\xfd\xf3\xea\x95\ -\xc9\xed\x02\x5e\x56\xa5\x21\x53\x64\x9b\xef\xe7\xde\x88\xfa\x12\ -\x89\x78\x1f\x70\x49\xe0\x91\x74\x3a\xff\x68\x8d\x00\x11\x7b\x0d\ -\xc5\x2d\x39\xd6\xdd\xdd\x3d\x56\xf6\x17\x4f\x04\xbb\x8a\x98\xc6\ -\x04\x14\x45\xf0\x81\xef\xfb\x0f\xde\xce\x2f\xaa\x70\x14\x40\x6c\ -\x7d\xae\x46\x80\x2a\x4f\x96\x22\xbf\xab\x4a\x24\xf6\xeb\x40\xac\ -\x71\xea\x8a\xb5\xaa\xca\xd6\xa8\x43\x54\xbe\x2f\x3d\x2e\xaf\x11\ -\x80\x88\x53\x7a\x48\x57\x4f\x45\x57\xcf\x82\xbc\x18\x0a\xcf\x56\ -\xa7\x1a\x1f\x06\x10\x88\xd7\x0a\x28\x39\x55\xc7\x47\x6e\x07\xa8\ -\x00\xc9\xd9\x0a\x40\x2b\x57\x32\x00\x85\x42\xa1\x9c\xbb\xa3\xfc\ -\x21\x5a\x35\x41\xd5\x26\x0d\x60\xa6\x8a\xb6\xa7\xc9\x1d\x4d\x6e\ -\xf2\xc5\xdf\xd8\x82\x0a\xa2\x78\x09\x65\x67\x2d\x00\xfc\xe8\x8b\ -\x6d\xb7\x96\x72\xcb\xd5\xf2\x05\x77\x5b\x80\x5a\x41\x11\x65\x3a\ -\x27\x24\x39\xce\x6c\x4d\xb5\x2a\xd6\xb2\x4c\x79\x3b\x73\x15\x5f\ -\x05\x2b\x9c\x06\xb0\x94\x55\xd1\x20\xc1\x7c\x06\xcc\xa6\x16\x8c\ -\x81\x39\x54\x95\x4b\x74\x25\x80\xa2\xa7\x6a\x04\xd8\x62\xfa\x8b\ -\x83\xb2\x7a\x60\x60\xa0\x72\xec\x12\x89\xc4\xcf\x82\x7e\xd2\x38\ -\xaf\x96\x84\xb3\xd7\xf3\xbc\xca\x89\x52\x55\x51\x58\x0b\x80\x91\ -\xbe\x1a\x01\xae\xeb\x5e\x05\x4e\x01\xf3\xef\x6f\x6f\xdf\x12\x4d\ -\x39\x3a\xfa\xeb\x5b\x34\xbc\x15\x82\xa2\x5f\xbb\x6e\x7c\x4f\xd4\ -\x1b\x04\xc1\x1a\x60\x31\xf0\x93\xe7\x75\x54\x7a\x83\xaa\x2f\xdc\ -\x12\xdd\x01\x20\x6a\xed\x4e\xa5\x52\xf3\xca\xfe\x9e\x9e\x9e\xf1\ -\xdf\x46\xaf\xad\x57\xd8\xc7\xd4\xdb\x51\x40\x75\xaf\xe7\x3a\x1b\ -\xa3\x55\x74\x70\x70\xb0\xd9\xa8\x14\xeb\x0c\xd6\xce\xba\xd5\x10\ -\x20\x93\x0d\x0e\x03\x2f\x09\x1c\x71\xdd\xf8\x86\x89\xe5\xd8\xf7\ -\xfd\x6e\x83\x6c\x43\x2b\xe5\x58\x81\xac\xc2\xb7\x1a\x5a\x07\x93\ -\xc9\x8e\xcb\x51\xbc\xaa\x8a\xef\x07\x07\x15\x79\x0d\xe1\x74\xc2\ -\x89\x2f\x9f\x52\xc0\xd0\xd0\x50\x9b\xdd\xd4\xfc\x23\xb0\x08\x95\ -\x8f\x13\x89\x8e\xed\xf5\x1a\x12\x55\xb5\x01\x44\x24\xac\x33\x2e\ -\xbe\x9f\xdb\xae\xf0\x11\x70\xd5\x12\x7d\xac\xb4\xd5\x15\x9b\xb4\ -\xbc\x14\xfb\x41\xce\x01\xf7\x21\x7c\x73\x77\xcb\x9c\x4d\xed\xed\ -\xed\x7f\x4e\x86\xad\x67\xa5\x1e\x60\x3f\xb0\x15\xb8\x65\x89\x3e\ -\xe1\xba\xee\xc0\x44\xdc\xa4\xb7\x9c\xe3\x38\x57\x42\x5b\x96\x02\ -\x97\x51\x36\xdc\xfa\xeb\x9f\x4b\x99\x4c\xf0\xaa\xaa\xd6\x74\x50\ -\x13\x4d\x55\xad\x6c\x36\xf7\x42\xeb\xdc\xb6\xc1\x12\x79\x0e\xb5\ -\x97\x4d\x46\x0e\xd3\xb4\xe5\xe9\x74\xfa\x5e\x2c\xfb\x0b\x41\x9e\ -\x2f\xb9\x72\xa8\xf4\x8b\xc8\x09\x28\x0c\x5b\x96\x35\x52\x28\x14\ -\x0c\x34\x2f\xc0\x0e\x13\x62\x58\x85\xc8\x3a\x4a\xf5\x43\xe0\xa4\ -\x31\x85\x4d\x9d\x9d\x9d\xbf\xd4\xe3\x68\xa8\xc2\x67\x32\xb9\xa5\ -\x22\xda\xab\xf0\x78\x23\x78\xe0\x82\x11\xdd\x91\x74\xdd\x93\xd3\ -\x01\x67\xf4\xd7\x2c\x9d\x4e\x7b\x58\xb1\xf5\x82\xae\x40\x71\x10\ -\xe2\x80\x0d\xe4\x04\x72\x06\x39\x83\x91\xbe\xce\xce\x8e\x4b\x33\ -\xc9\x7b\x67\xdb\xbf\x21\xb9\xe6\xce\xae\xea\xf6\xd6\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x18\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xca\x49\x44\x41\x54\x58\x85\xed\ -\x96\x3f\x48\xc3\x40\x14\xc6\xbf\x97\x0a\x29\x08\xd5\x5d\xa9\x8b\ -\xb8\x76\x15\x41\x5c\x8c\xae\xd2\x58\xc4\x21\x2e\xad\x2e\xba\x14\ -\x44\x5c\x9c\x3a\x38\x08\x2e\xc5\xa5\x56\x1c\x5c\x94\x92\x82\xd0\ -\x45\xb3\x08\x22\x38\xda\xd1\xc1\xa1\x38\xb8\x08\xfe\x19\x0a\x85\ -\xe6\x9e\x8b\xa9\x35\x35\x69\xd2\xbf\x83\xfd\xa6\x77\xc9\xcb\x7d\ -\xbf\xbc\xbb\x7b\x1c\xf0\xdf\x45\x6e\x2f\x17\x34\x6d\x58\x94\x83\ -\x29\x02\x47\x01\x4c\xb4\xe9\x55\x02\x58\x97\x2b\x81\xbd\x42\x21\ -\x53\x6e\x0a\xb0\xa0\x69\xc3\x5c\x0e\xde\x01\x1c\x69\xd3\xd8\x26\ -\x2a\xca\x15\x9a\xb1\x20\x24\xa7\x34\x51\x0e\xa6\x3a\x6f\x0e\x00\ -\x1c\xa9\xc8\x66\xca\x1a\x39\x02\x7c\x97\xbd\x4b\x22\xd5\x8a\x86\ -\x5c\xb2\x7e\xad\xb9\xa1\x67\x5d\xf7\x4b\x33\x29\x6a\x82\xff\x9a\ -\xdb\xb1\x02\xbd\xd2\x00\xa0\x61\x0f\xcc\xc7\x36\xc2\x64\x9a\x73\ -\x0d\xcf\xd5\xf8\x96\xd3\x24\x12\x49\x82\x85\x28\x8e\x06\x3e\xef\ -\x73\xb9\x9c\xd9\x32\xc0\xfc\x72\x7c\x9b\x84\xd8\x07\x51\x03\x18\ -\x81\xd2\x4e\x93\x30\x33\x40\x84\x37\x31\x72\xbb\x18\xdd\x58\xb9\ -\xca\x67\x5e\xbc\x02\xd4\x96\x40\x51\x13\xab\xc4\x74\x60\x87\xf2\ -\x23\x02\x66\x4d\x12\x17\xb1\x58\x2c\xe0\x1b\x00\xc0\x4e\xab\xc6\ -\x76\x88\x77\x33\x34\xed\x35\xbf\xfe\x6f\xed\x5d\xef\xc8\x87\xef\ -\x12\x80\xb1\x1a\x84\x24\x45\x00\xdc\xf9\x05\xf8\xd5\x68\x0c\x3d\ -\xeb\xb8\xe9\xec\x52\xd4\x04\x00\x6c\x5a\x63\xc1\xc2\xf3\xe9\xea\ -\xfb\x31\x1c\x00\x0c\x00\xfa\x0e\xd0\x72\xd7\x73\x13\x81\xd2\x8a\ -\x9a\x70\x6c\xdd\x00\x4a\x56\xd0\xa7\x0a\xb0\x6e\x45\x5d\xa9\x80\ -\xbb\xa8\x28\x57\xa4\x3d\x6b\xd4\xcb\x0a\x94\x00\x3e\xac\xbf\x11\ -\x03\x75\xed\x57\x51\xd7\x3f\x00\x0e\x75\xc4\x8a\x79\xcd\xc8\x9f\ -\x9c\x79\x49\xad\x55\x80\x20\x8c\x8e\x98\x03\x55\x32\xc5\x8d\xd7\ -\xe4\x9f\x25\xa8\x8a\x24\x18\xaf\x6d\xdb\x33\x76\xaf\x2f\x4f\x9f\ -\xbd\xa6\xd7\x2e\x0e\x4f\x8f\x0f\x9f\x93\x53\x91\x73\x92\x28\x0c\ -\x48\xe3\x00\x64\x5f\xb6\x40\x91\x88\x92\x86\x9e\x3d\xf6\xf1\xdd\ -\x40\xf8\x02\x67\xdb\x80\xa5\xc9\x72\x5a\xc9\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x34\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xe6\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xcb\x6e\xd3\x40\x14\x40\xcf\x0d\x2c\x80\xcf\x48\xb3\x69\x0a\ -\x8b\x24\x3b\xd6\x69\x36\x48\xb4\xb5\xc3\x4b\x42\x2d\x10\x5b\xf0\ -\x01\x48\x7c\x03\x4b\x76\x48\x24\x40\x05\xe5\xd5\x26\x1f\xd0\x76\ -\xcb\x36\x29\x8f\xda\xbc\x62\x5e\x12\xfc\x01\xb0\x69\x2e\x8b\xd4\ -\xc1\x8e\xed\xc4\x29\xd9\x20\xee\x6a\x6c\xcf\xdc\x73\xe6\xce\xe8\ -\xca\xf0\xbf\x87\xf8\x83\x4a\xd5\x3e\xa9\xaa\xb7\x81\xa3\x2a\xdc\ -\xd8\xde\xa8\xb7\xa6\x09\x2a\x57\x2d\x43\x94\x9b\xc0\x2f\x54\xaf\ -\x6d\xb5\x1a\xcf\x01\x32\xfe\x04\x55\x6d\x00\x27\x80\x9c\x28\xeb\ -\x15\xc3\x3a\x37\x2d\x78\xa5\x6a\x9f\x17\x65\x1d\xc8\x01\xc7\x11\ -\xa9\xfb\xdf\x32\x7f\xa6\xe9\x91\xc0\x9a\x8c\x0a\x8f\xa6\x21\x51\ -\xa9\xda\xe7\x55\x75\x2d\xcc\xe2\x58\x44\x40\xc9\x5c\x07\x7a\xd3\ -\x94\xa8\x18\xd6\xb9\x18\x78\x0f\xd1\xeb\xfe\xc3\x21\x7f\xe0\xb9\ -\x6d\x77\x26\x5f\x7c\x0f\x2c\xf1\xe7\x6e\x08\xc2\x52\x6e\xb6\xf8\ -\xb6\xeb\xb6\x77\x27\x86\x0b\x8f\x22\x70\x58\xd9\x6a\x36\x9e\x44\ -\x04\xf6\x25\x5e\xc7\x48\x64\x26\x95\xd8\x87\xaf\x0d\xe5\xdf\x87\ -\xd7\x1f\x06\xe7\x86\x04\x7c\x89\xec\x6c\xe1\x83\x88\x44\x24\xb2\ -\xf9\xd2\x1b\x6f\x8c\x44\xd9\xb4\xcf\xd2\xdf\xf9\x58\x78\xac\x40\ -\x5f\xa2\xf3\x2a\x4e\x42\xc0\x18\x25\x51\x36\xed\xb3\x82\x0e\xc3\ -\x35\x09\x9e\x28\xe0\x4b\xe4\xe6\x4a\x5d\x60\x31\x8d\xc4\x7c\xb5\ -\x76\x46\xe0\x71\x0c\x7c\x39\x09\x3e\x52\x00\xa0\xeb\xb4\x13\x25\ -\x66\xe6\x0a\xae\xe7\x74\x1c\x1f\x8e\xca\xc4\x70\x02\x49\x47\xc6\ -\xbc\x69\x5d\x04\x56\x09\xdf\xe8\x3d\x44\x2f\xf4\x51\x31\x70\xd5\ -\x95\xad\x56\xe3\xc1\xb8\xdc\xa9\x04\x92\x24\x04\x7a\xda\x1f\x06\ -\xc5\x52\xc3\x61\xcc\x11\x04\xc3\x73\xdb\x2f\x67\xf2\x45\x8f\xe1\ -\x3e\x11\xde\xc4\x44\xf0\x89\x04\x02\x12\xdd\x21\x89\x01\x5c\x85\ -\x4b\xdb\xcd\xf4\x70\x08\x97\x2e\x55\x28\xf2\x93\xfe\x05\x0b\x87\ -\x88\x66\x7a\xfc\x98\x34\xdf\x44\x15\x28\x9b\xb6\x29\xe8\x93\x84\ -\x75\x82\x60\xe6\x66\x8b\x4e\xd7\x6d\x3b\x53\x17\x28\x57\x2d\x43\ -\xe0\x29\x70\x38\xf0\xda\xaf\x44\xb0\x63\x9a\xd9\x7c\x69\xd7\x73\ -\xdb\x6e\x9a\xbc\xa9\x8e\x60\xff\x67\x22\x02\x17\xf4\xb2\x0a\x97\ -\x08\x1f\xc9\x21\x41\x9f\x96\x4d\xdb\x4c\x93\x7b\x6c\x05\xe6\x0d\ -\x7b\x49\xe0\x59\x1c\x7c\xb3\xd9\x58\xf5\x9c\xf6\x8b\x5c\xbe\xf0\ -\x09\x64\x81\x70\xb3\x4a\x55\x89\x91\x02\xf3\x86\xbd\x84\x68\x04\ -\x8e\xca\x95\xad\x56\x7d\xd5\x7f\xd1\x75\x3b\x49\x12\x46\x36\x5f\ -\x72\x46\x49\x24\x0a\x8c\x86\xdf\xb9\x3f\x3c\xbf\xeb\x76\x5e\xcc\ -\xcc\x96\x3e\x23\x4c\x24\x11\x2b\x50\x31\x6b\x8b\x08\xeb\x69\xe1\ -\x7e\x78\x6e\x7b\x27\x51\x62\xae\xb8\xeb\x39\x51\x89\x88\x40\xc5\ -\xac\x2d\x2a\x12\x81\xab\x50\xdb\x6e\xd6\x13\xe1\x41\x89\xec\x5c\ -\xf1\x8b\xc0\x69\x86\xef\x44\x8c\x44\x48\xa0\x5c\xb5\x16\x40\x36\ -\x62\xe1\x1b\xf5\x7b\xe3\xe0\x03\x09\x27\xbd\xc4\x40\xa0\x6c\xd4\ -\x4e\x09\xd2\xfa\x5b\x78\x50\x22\x97\x2f\x7c\x05\x89\x48\xe4\xf2\ -\x85\x9d\xae\xdb\x79\x07\x81\x3e\x90\x11\xb9\x35\x0c\x17\xd4\x3a\ -\x08\xdc\x8f\xcd\x66\xe3\xae\xa0\x16\xe1\x3e\x71\x58\x91\x5b\x03\ -\xee\x80\x86\x06\x7f\xc9\x55\x50\x6b\xb3\xd9\xb8\x7b\x50\xf8\x18\ -\x89\xbd\x88\x40\x46\xf5\x2a\xe0\x01\xdf\x51\x5d\x99\x06\x3c\x28\ -\x01\x2c\x23\x7c\x03\x3e\x4a\x8f\xab\xd3\xca\xfd\xef\xc7\x6f\xcf\ -\x0b\x86\xc1\xfd\xdf\x90\xb9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x02\x25\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd7\x49\x44\x41\x54\x58\x85\xed\ -\x95\x3d\x68\x13\x51\x1c\xc0\x7f\xff\x77\xfd\xc2\xc1\x28\x2d\x3a\ -\x74\x29\xda\x0e\xea\x10\xb1\x9b\xa5\x50\xc4\x24\x94\xc6\xc1\xe6\ -\x4e\xf0\x0b\xc1\x26\xd6\x2e\xdd\x9c\x83\x9b\x7b\xb7\x0c\xd2\xcd\ -\xc5\xa1\x4a\x44\xac\x8b\x07\xe9\x22\xd8\x51\x27\x3f\x26\xc7\xd2\ -\x49\x38\xcf\x7b\x7f\x87\x5c\x6c\x42\xaa\x4d\x0f\xab\x14\xee\xb7\ -\x1c\x77\xf7\xff\xf8\xbd\x7b\xef\xde\x83\x94\x94\x94\x94\xff\x8c\ -\x24\x4d\xbc\xe4\xdd\x1f\x75\x6c\xf4\x02\x34\x4b\x68\x47\x5f\x3f\ -\x7f\xfc\x35\x49\x1d\x93\x24\x29\x57\x5a\x9c\x70\x6c\xd8\x00\xcd\ -\x02\xd0\x2f\x1b\x05\x6f\x61\xfc\x9f\x08\xe4\xbc\xca\x79\x88\x1a\ -\x20\x63\x0a\x28\x00\x32\x66\x55\x1a\x85\xab\x77\xb3\x07\x2a\x50\ -\x70\xcb\xd3\x58\x7c\xe0\x04\xa0\x02\x91\x40\x04\x28\xca\x49\x6b\ -\x8c\x5f\x70\xcb\xd3\x07\x22\x90\x77\x2b\x45\xab\xac\x83\x1e\xd5\ -\xe6\xc0\x6d\xdb\x6b\x0b\xaa\x40\xc6\x2a\xeb\x97\xe7\x17\xe6\xfe\ -\xaa\x40\xae\x54\xbe\xa5\xaa\x6b\xc0\x10\xaa\x2a\x9d\xcd\x63\xc4\ -\xaa\xa2\xc0\x90\x88\x3c\xcb\xbb\x95\x9b\xbd\xd4\x76\xf6\x0a\xc8\ -\x97\xca\xcb\x40\x0d\x30\x8a\xaa\x88\xec\xd2\x3c\x56\x10\x94\xe6\ -\x9f\x65\x80\xf9\x53\x67\x26\xb7\x3e\x7d\xd8\x7c\x9b\x54\x40\x72\ -\xa5\xca\x43\xe0\x51\x7c\x6b\xa5\xb5\xe6\xfe\x8c\x8a\xc4\x3e\xc2\ -\xec\xf8\xb9\x0b\xf2\xf1\xfd\xa6\xbf\x2f\x81\x6a\xb5\x6a\x06\x46\ -\x26\x56\x80\x07\x71\xa9\xd6\x1c\xf7\x8c\xec\x5c\x66\x4e\x9f\x9d\ -\x1c\xbe\x7d\xed\xca\x2b\xdf\xf7\xbb\x6a\x74\x6d\x44\x9e\xe7\x0d\ -\x6c\xdb\xcc\x2a\x70\x3d\x0e\xd9\x77\xf3\xb6\xf2\x02\xda\x5a\x67\ -\x4f\xb6\x86\xcd\x9d\x77\xb5\x5a\xf8\x5b\x81\x62\xf1\xde\x91\x60\ -\x30\x7a\x0a\x32\x8b\x02\x46\x2c\x9a\xb4\xf9\x2f\x07\x51\x55\xd3\ -\x6c\xa4\x2f\x07\x03\xc7\xad\xd7\x6b\xdf\xba\x04\xe6\x6e\x2c\x1d\ -\xff\x1e\x84\x75\xe0\x62\xfc\xc8\xd2\xdb\x9c\xef\xed\x80\x88\xee\ -\x7c\x89\x8d\x30\xfa\x51\x7c\xb3\xb6\xba\x0d\xd0\xd7\x0a\x0a\x82\ -\xf0\xb3\x40\xa6\x2d\x2f\xd1\x36\xbd\x1b\xda\x39\x8e\xa9\x7e\xa7\ -\xef\x0b\x70\xac\xa3\x49\xe2\x53\x29\x25\x25\x25\xe5\xb0\xf3\x13\ -\x19\xff\x9a\x58\xf0\x37\x9f\x0a\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x03\xd3\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x85\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x4d\x68\x9c\x55\x14\x86\x9f\xf7\x66\xd2\x1f\xa1\xb5\x95\xa2\ -\x29\x36\xb4\x06\xad\x9a\x8d\x81\xd4\x49\xb2\xf0\xa7\xa5\xb4\x54\ -\x69\x93\x9a\x18\x11\xa9\x85\xa2\xb8\x70\x27\x08\x29\x2e\xa2\x28\ -\x1a\x70\xa5\x14\x45\x11\x44\xd1\x4d\x68\x33\x69\xa2\xa9\x16\x2c\ -\xe9\x42\xda\x69\xac\xa5\x0b\x43\x41\x88\xa0\x93\x46\x11\x94\x6a\ -\xb5\x3f\xcc\x77\x5f\x17\x33\x49\x93\x4e\x92\x26\x64\xe2\xa6\x67\ -\x73\x3f\xce\x77\xbe\xf3\x3e\xf7\x7e\xf7\xe7\x5c\xb8\xd9\x4d\xf3\ -\x09\x7e\xb0\xd7\xd5\x15\x09\x2d\x96\xb7\x5a\x54\x63\xd6\x09\x02\ -\x30\x8a\xc8\x19\x1d\x57\x42\x26\xdb\xa6\x1f\xcb\x0a\xd0\x94\x71\ -\x3a\xda\x5d\xc0\xe6\x39\x26\x1d\x4a\xa4\xfd\x43\xbb\xf5\xcd\x82\ -\x00\xea\xbb\x7d\x6b\x2a\x15\xdf\x07\x3d\x5d\x74\x8d\x61\xf7\x3b\ -\x84\x23\x4a\x18\x59\x12\x19\xbb\x92\x22\x3a\x52\x25\xb1\x41\x8a\ -\xdb\x40\xcd\xc0\xfa\x62\xf6\x01\x82\xf6\x65\x9b\xf5\xdb\xbc\x01\ -\x9a\x0e\xfb\xee\x98\xb8\x0f\xb8\x1f\x18\x13\xea\x5c\xb6\x9a\x8f\ -\x07\x37\x2b\x3f\x6b\x97\x3a\x1d\xd2\x75\x3c\x25\xfb\x0d\xa0\x46\ -\xe2\xe7\x68\xed\x3a\xf5\x84\xce\xce\x19\x60\xd3\x41\xd7\x54\x04\ -\x67\x81\x35\xc0\x61\x96\xe9\xd9\xec\x63\xfa\x6b\x56\xe1\xeb\x6c\ -\xc7\x80\x97\xfe\x71\x39\xbe\x07\xda\x87\xf9\x27\x58\x0f\x9d\x68\ -\xd3\x99\x1b\x02\x34\x0c\x78\x25\x97\x7d\x02\xa8\x05\xbf\x93\x3d\ -\x1b\x5e\xe2\x35\xc5\xf9\x88\x4f\x98\xad\x86\x5e\x3a\xb0\xdf\x04\ -\x72\x79\x2b\x7d\xba\x55\x63\x93\x43\x42\xc9\x47\x57\xe2\x01\xa0\ -\xd6\xa6\x7f\x41\xe2\x00\x92\xb3\x2d\x74\x19\x7f\x04\xac\x4b\xc9\ -\x9f\x61\x4f\xe9\xf4\x14\x80\xf4\x41\x6f\xc2\xda\x63\xf8\x3d\x49\ -\xb4\x67\x41\xe2\x93\x20\x2e\xe6\xc3\x8b\xc0\x39\x60\x4b\xc3\x21\ -\x76\xcc\x08\xa0\x0a\xbf\x05\x10\xac\xd7\x4f\xb7\xeb\xc2\x82\xc5\ -\x8b\x36\xdc\xae\xab\x42\xaf\x14\x14\xdd\x35\x79\x14\x26\x1e\xea\ -\x0f\x79\x6d\x4a\x1e\x05\xfe\xfc\x3b\xaf\xb5\xc3\xed\xba\x5a\x2e\ -\x00\xa0\x30\x1f\x32\x1e\x06\xee\x33\xaa\x1b\x5f\x15\x13\x23\x90\ -\x0a\xec\x04\x84\xfc\x65\xd9\xc5\x01\x24\xcb\xee\x03\x08\x8e\xbb\ -\xc7\xdd\xd7\x7e\x81\xe3\xa3\x85\x26\x7c\x55\x76\xf1\xa2\x45\x85\ -\xaf\x01\x2c\x6d\x29\x05\x40\xd5\x85\x86\x9f\x16\x0b\x20\x88\x11\ -\x00\xcc\xba\x69\x00\x0a\xce\x20\xc6\x58\x24\x5b\xbd\xb4\x98\x5b\ -\xdc\x39\x3e\x11\x4b\xf7\x81\xff\xcb\x5e\xa5\x04\x60\x14\xc0\x91\ -\xaa\xc5\xd2\xbc\x70\x69\x22\xf7\xf9\xf1\x3d\x66\x12\x80\x7f\x01\ -\x70\xe0\xae\xc5\x02\x48\xa0\xa6\xf8\x98\x1b\xf7\x4d\x00\xd8\x61\ -\x10\x20\x38\x6e\x5f\x2c\x00\x14\xb7\x15\xd5\x8e\x95\x00\x54\xa6\ -\xe8\x07\x30\x7a\xbc\xfe\x03\x57\x96\x5d\xdc\x16\x68\x17\x40\x54\ -\xc8\x94\x00\x7c\xdb\xac\xf3\xc0\x31\x60\x4d\xe5\xed\x3c\x57\x6e\ -\xfd\xc6\x1e\x76\x02\xb5\xc0\x0f\x43\x2d\x4c\xd4\x06\x53\x56\x41\ -\xb4\x3a\x0a\xb0\xee\x6c\x18\xf0\xca\x72\x89\xd7\x76\x7b\x89\x55\ -\x38\x67\x14\xb4\x1f\xc9\xd3\x02\x0c\xb5\x6a\xc8\xf8\x73\xe0\x0e\ -\x2e\xfb\x53\x3a\xbd\xf0\x65\x6a\x6b\x45\x2a\xbe\x4b\xa1\xf7\x83\ -\x27\x9b\xf9\x62\xf2\xeb\x12\x81\xe4\xda\xd1\xd9\x9c\x7e\x20\xbe\ -\xbd\x20\x08\x5b\xe9\x5e\x5e\x06\xbd\x00\x9c\x4f\x55\xe8\x99\xc9\ -\xbd\x87\x19\x4a\xb2\x62\x3d\x98\x05\x6e\x03\x7a\x96\xe7\xb5\x77\ -\xb0\x5d\x17\xe7\xa3\x5d\xdb\xed\x25\x2b\x52\xf1\x00\xe8\x79\xe0\ -\x5f\x47\x3d\x72\xaa\x4d\xdf\x5d\x1f\x37\x63\x51\x9a\xee\xf1\x46\ -\xe1\x3e\xe0\x5e\x60\xd4\x52\xe7\x2d\xab\xf8\x64\x2e\x45\x69\x63\ -\x1d\x6d\x2e\x14\xa5\xf7\x00\x39\x59\xcd\x27\x5b\xf5\xfd\x74\xe1\ -\xb3\x96\xe5\x75\x19\xaf\x5a\xea\xf8\x21\xe8\xc9\xa2\x2b\x67\xbb\ -\x3f\x54\x84\x23\x49\x9e\x91\x54\x64\xec\x52\x25\x71\x79\x42\x55\ -\x02\xeb\x43\x88\xdb\x5d\x28\xcb\xc7\x37\x9c\xa3\x31\xaf\xbd\x43\ -\xed\xfa\x75\x26\x8d\x39\x5d\x4c\xd2\x3d\x6e\x12\xee\x02\x1e\x9e\ -\x4b\xbc\xc5\x19\xa1\x8e\xec\x6e\x1d\xbd\x51\xec\xbc\xae\x66\x8d\ -\x19\x6f\x70\xa4\x05\x79\x2b\x50\x4d\xe1\x04\xad\x00\x72\x88\x1c\ -\xe8\x78\x48\xc8\x9c\x68\xd3\xb9\xf9\xe4\xbd\xb9\xed\x3f\x89\x47\ -\x63\xa6\x91\x26\x12\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\xf0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x6f\x28\xc0\x02\xfe\x2d\x80\ -\x8c\xf0\x68\x0c\xac\xb7\x31\xa0\xb5\xcf\x5d\xfb\x5c\xd9\x30\xe5\ -\xf8\x0f\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ -\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ -\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ -\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\ -\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\ -\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\ -\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\ -\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x3d\x9d\xfa\x04\x75\x0c\ -\x2b\x93\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x41\x49\x44\x41\x54\x58\x85\xed\ -\xd3\xa1\x11\xc0\x20\x14\x04\xd1\x85\x9a\x28\x00\x93\x5a\x70\x14\ -\x83\x4a\x31\x99\xa1\x81\x14\x85\xc2\x22\xf9\x66\x9f\x3a\xb7\xea\ -\x40\x92\x14\x2c\xed\x51\xda\x98\x40\xbd\x54\xfd\xfe\xb7\x3f\x00\ -\xf9\x4a\x50\x3a\xf0\x05\x92\x24\x85\x5b\x1c\x18\x0a\x07\xd4\x09\ -\xe9\x09\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xd2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x84\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xb1\x0d\x82\x50\x18\xc4\xf1\xff\xf7\xdc\x81\xc4\x3d\x18\x80\ -\x4d\x2c\x6c\xe8\x1c\x41\x98\x81\x06\x13\x6b\x67\xb0\xb4\x77\x10\ -\x13\x76\xd0\xb3\x52\x21\x24\x76\x0f\x9a\xfb\x75\x97\xf7\x25\x77\ -\xc5\x03\x33\x33\xb3\x95\xc5\x34\x2a\xaa\x63\xb3\xc9\x59\x78\x6b\ -\x9b\x27\x84\x66\x03\xca\xba\xab\x90\x2e\xc0\x36\xe7\x80\x80\x01\ -\xb4\xbb\x9f\x0e\x57\x80\xf4\x7d\x91\xfa\xdc\xe5\x00\x82\xe2\x45\ -\x3a\x7f\x72\xfa\x77\xbc\x84\xdf\x80\x88\x1a\x78\xe4\x2e\x0c\x18\ -\x14\xec\x47\x79\x6c\xf9\x4f\x68\x66\x66\xb6\xba\x37\x95\x79\x1e\ -\x09\xc0\xb2\x67\x2f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\x85\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xfd\x87\x04\x31\x08\x1d\x02\ -\x9e\xbe\x7f\x22\x47\x2c\xca\xea\xc9\xea\xd9\x7c\xbc\xcd\xf8\x22\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x0f\ -\x7e\x19\x07\x85\xa1\xbf\xac\xe9\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\xd2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x84\x49\x44\x41\x54\x58\x85\xed\ -\x97\xcd\x4a\x23\x41\x14\x85\xbf\xd3\xba\xd5\x85\x32\xfa\x26\xe9\ -\x0c\x8a\x2f\x90\x61\x04\x03\x3e\x84\x60\x56\x62\xe6\x11\x26\x82\ -\x0b\x23\xb8\x1f\xdc\x0d\xd8\xe0\x22\x2f\x30\x20\xa6\x7d\x13\x15\ -\x07\x24\x6b\xfb\xcc\xc2\xae\x20\x49\x6c\x31\x76\x74\xc0\x3e\xab\ -\xe2\xd6\xa5\xce\x57\x3f\x14\xf7\xc2\x67\x97\x46\x03\xf5\x33\xaf\ -\x65\xb8\x8d\xa8\x0b\xbe\x94\x61\x62\xb8\xc5\xf4\x23\xd4\xe9\x37\ -\x75\xf1\x2c\x40\x9c\x78\x0f\x7c\x30\x09\xac\x24\x65\x58\xfb\x69\ -\x53\x87\x63\x00\x71\xe2\x75\xf0\x1f\xe0\x1e\xab\x15\x3d\xd0\xbb\ -\xdc\xd6\xdf\x32\x5c\xbf\xfe\xf6\x52\x36\x47\x03\xb9\x0b\x2c\xca\ -\xda\x08\x27\x31\x1f\x92\x6c\xef\x4b\x08\xab\x95\x36\x75\x5a\x86\ -\x71\x50\xbe\x91\xd3\x5a\x62\x09\xff\xca\x70\x1b\xf8\x0e\x10\x0d\ -\xb3\x44\x1d\x20\x7a\xa0\x57\xa6\xf9\x88\x7a\x00\x12\x71\x08\x0c\ -\x01\xc2\x83\x2b\xeb\xd8\x27\xe9\x6a\x4b\x77\xf9\x70\x65\x0c\xe0\ -\xa3\x54\x01\x54\x00\x1f\x0e\x30\xff\x52\x42\x7c\xe6\x1d\xe4\x9f\ -\xc0\xc2\x2b\xd7\x1e\x60\xfd\x48\x9b\x3a\x29\x4a\x2a\x3c\x81\xf8\ -\xdc\xab\xc8\xc7\x53\x98\x03\x2c\x20\x77\xe3\x73\xaf\x4e\x0d\xf0\ -\x1e\x2a\x04\x48\x37\x75\x8d\xb5\x0b\x0c\xa6\x58\x7b\x80\xd5\x4a\ -\x37\x75\x5d\x94\xf4\xe2\x1b\xc8\xef\xb0\xf0\x1e\xdf\xa2\xff\xfb\ -\x0a\x2a\x80\x0a\xe0\x5d\x01\x0c\xb7\xf0\x58\x40\xce\xca\xac\x96\ -\x78\x39\x1f\xde\x8c\x01\x60\xfa\x00\xd9\x1c\x8d\x59\x01\xc0\xe3\ -\xda\x36\x69\x08\x0c\x3f\xa2\x08\x75\x8c\xbf\x21\x77\x6b\x89\x05\ -\xf4\x9e\xd4\x70\x6f\x52\xbe\xf3\x86\xf0\x11\x90\x45\xa8\x13\xe6\ -\x26\x35\x26\x1d\x66\xf7\x36\x9e\x6f\x4c\x82\x42\x6b\x96\x97\xce\ -\x2b\xa3\xf3\x53\xea\xc6\x26\x9d\xd4\x9a\x55\xfa\x07\xf1\xe4\x84\ -\x86\xea\x09\x57\xf9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x04\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x3c\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x88\x1c\x45\x14\xc6\xbf\xd7\x33\x99\xc4\x3f\x2b\x62\x16\ -\x15\x24\x78\x11\xff\x5c\x04\x77\x3b\x7a\xf0\xe0\x22\x26\x12\xc1\ -\x3f\x2c\x22\x1e\x04\x35\x9a\x99\xd9\x24\x33\xbb\x11\x09\x28\xea\ -\xb8\x98\x80\x41\x31\x6e\x8f\xba\x99\x4e\xc4\x1c\x44\xd1\x53\x0c\ -\x62\x64\x83\xb0\x90\x83\x91\xd9\x59\x30\x20\x82\x78\x10\x11\x49\ -\x84\x28\xea\x06\x75\x37\x5d\x9f\x87\x5d\x35\xe9\xea\x68\x26\xa9\ -\xaa\x2e\x70\x7e\xc7\x3a\xd4\xf7\xea\xab\x57\xaf\x5f\x75\xcf\x00\ -\x3d\x7a\xf4\xf8\x3f\x23\xa6\x26\x0a\xcb\x13\xcf\x43\xe4\x19\x01\ -\x48\xca\xb6\x99\xb8\x36\x6e\x6a\x6e\x9b\x04\xc6\x66\x12\x79\x16\ -\x40\x81\x40\x11\x82\x46\x58\x6d\x0e\x19\x9b\xdb\x22\xe6\x0c\x38\ -\x6d\x2e\x0a\xc8\xfd\x03\x23\x13\x83\x06\xe7\xb7\x82\x31\x03\x08\ -\xa8\xd4\x50\x5f\xa0\xe4\xe3\x70\xe4\xd5\xeb\x4c\x69\xd8\xc0\x98\ -\x01\x02\x30\x63\xb8\x1f\x2a\x38\xb8\x7a\xe3\xeb\xab\x4c\xe9\x98\ -\xc6\xe4\x11\x38\x13\xab\x98\x24\x53\x83\xe5\x97\xfb\x1d\x68\x75\ -\x8d\x0b\x03\x00\xe0\x7a\x91\xd2\x81\x5b\xd7\xef\xe8\x73\xa4\x77\ -\xd6\x58\x33\x80\xd4\x8e\x44\x38\xbf\xec\x82\x7d\xd7\xd4\xa2\xe5\ -\xb6\x34\xcf\x05\x6b\x06\x88\x40\x21\x55\x17\x08\xdc\x7e\xe9\x3c\ -\xde\x19\x6a\x34\x8a\xb6\x74\xbb\xc5\xf6\x11\x50\x80\xa4\x33\x61\ -\x78\xee\xe8\x65\xbb\x00\x1a\x6b\xc2\xce\x07\x07\x35\x80\x0a\x4c\ -\x9b\x20\x8f\x85\xe5\xe8\x45\xfb\xda\xff\x8d\x9b\x22\x28\x4c\xf7\ -\x08\x80\xc8\xd6\xb0\xda\xdc\xea\x44\xff\x5f\x70\xf5\x14\x00\x80\ -\x44\x1b\x21\x77\x0c\x96\x27\x1e\x77\x18\x83\x86\x4b\x03\xb2\xba\ -\x45\x88\x48\x6b\x75\x25\x1a\x76\x19\xc7\xa9\x38\x35\x60\xa9\x5b\ -\x4c\x9b\x10\x10\x78\x37\xdc\x10\xdd\xe1\x32\x96\xbf\xc5\x73\xd0\ -\x24\xa0\xd5\x84\x12\x02\xec\x0b\xab\xd1\xcd\xae\x83\xc9\xc3\x00\ -\x00\x42\xea\x85\xf1\x22\x10\x1f\x0d\x6c\xdc\x79\x83\xcb\x48\x72\ -\x32\x00\x10\x0a\x33\x6a\xc2\x4a\x49\x8a\x07\x6f\xda\xf4\xda\xd5\ -\xae\xe2\xc8\xcd\x00\x60\xb1\x26\xa4\x4d\x10\xf0\xaa\xc2\x49\x35\ -\x75\x63\x75\xf2\x72\x17\x31\xe4\x6a\x00\xb0\x64\x82\x7e\x6f\xb8\ -\xb6\xc4\x85\x03\xb7\xd4\xa2\x4b\x6c\xeb\xe7\x6e\x00\xb0\x78\x6f\ -\xa0\xfe\x3e\x61\x20\x59\xc0\xfe\xa1\x47\xde\x5a\x61\x53\xdb\x0b\ -\x03\x00\x40\x00\x85\x74\x26\x10\xb7\xcd\x95\x7e\x7d\xcf\xe6\xe5\ -\xc9\x1b\x03\x00\x00\x92\x61\x82\xe0\x9e\x13\xc7\xfa\xf7\xa0\xd1\ -\xb0\x12\xab\x5f\x06\x00\x80\x88\x62\xea\x06\x49\xf2\xe1\xf0\xe8\ -\xca\x97\x6c\xdc\x20\xfd\x33\x00\x84\x80\x0a\xd4\x5e\x31\x3e\x11\ -\x96\x9b\x4f\x99\x56\xf3\xd0\x80\x45\x44\x24\xd1\xca\xa2\x60\x7b\ -\x58\x8d\x2a\x26\x75\xbc\x35\x80\x00\x32\xba\x45\x80\x98\x0c\x2b\ -\xd1\xfd\xa6\x74\xbc\x35\x00\x00\x24\xbb\x65\x16\x00\x4d\x53\x1a\ -\x5e\x1b\x00\xe0\x4c\x75\xcf\xd8\x63\xd1\x9b\x97\x93\x59\x2c\x2d\ -\x3d\x6b\x93\xde\x34\xa5\xe1\xaf\x01\x02\x28\xa2\x90\xde\x7f\x81\ -\x6c\x6a\xb7\x6a\x6f\x98\x92\xf1\xd4\x00\x01\x49\x6d\xf1\xa4\x3c\ -\x37\x13\x9b\x5b\x3c\xe0\x6f\x0d\x08\xb4\x9d\x17\x44\x9d\x78\xf3\ -\x36\xd3\x42\x1e\x66\x80\x04\x7a\xe5\xe3\xdb\xed\x2b\x7e\xdc\x92\ -\xf1\x8d\xe1\xbc\xf1\x2b\x03\x08\x6d\xf1\x02\x7e\x48\xae\x58\x8f\ -\xf1\x71\xbd\x27\x30\x80\x47\x06\x48\x00\x41\x6a\xf1\x38\x54\xbc\ -\x30\x79\xa0\x13\x57\x16\x6c\xa9\xfa\x71\x04\x88\x00\x72\xfa\xce\ -\x13\xf8\x9c\x5c\x7e\xf7\xa7\x3b\xeb\xbf\xd9\x94\xf6\x21\x03\x24\ -\xbd\xf3\x20\xbe\x2e\x26\xea\xce\x4e\x5c\xf9\xd9\xb6\x78\xae\x06\ -\x70\xb1\xd7\x09\x52\x83\xdf\x17\x83\x64\xcd\x67\x7b\xc6\x8e\xb9\ -\x88\x21\xcf\x23\x20\xa2\x6f\xc0\x4f\xc2\x60\xed\xe1\x5d\xf5\x6f\ -\x5c\x05\x91\x4b\x06\x50\x32\x76\x1e\x38\xa1\x02\xdc\xd5\xde\xbd\ -\xf9\x0b\x97\xb1\xe4\x61\x80\x08\x35\xdd\x05\x12\xc3\xb3\x93\xf5\ -\xc3\xae\x83\x71\xfc\x71\x94\x59\x3b\x4f\x11\x3e\xd4\x89\xeb\x53\ -\x2e\x63\xf9\x0b\xa7\x35\x40\x20\xba\xe1\x64\xb5\xdd\x1a\x7d\xdf\ -\x65\x1c\xa7\xe2\x32\x03\x0a\xe9\x01\x01\x9f\x9e\x89\x47\x63\x87\ -\x31\x68\x38\x31\x80\x59\x3b\x0f\xbc\xd2\x6e\xd5\x73\xff\x99\x8c\ -\x83\x23\x20\x81\x40\xeb\xf2\xf6\x76\x5a\xb5\x27\x6d\x5c\x6e\xba\ -\xc5\x76\x06\x64\xdc\xec\xf0\x41\xdf\x95\xc7\x37\xf8\xb0\x78\xc0\ -\x62\x06\x90\x08\x24\xdd\xe2\x02\xd3\x17\xff\xd1\xf7\xe0\xf4\x78\ -\xfd\xa4\x2d\xdd\x6e\xb1\xf9\x43\xc9\xf4\xe2\x67\x0b\x25\xdc\x3b\ -\xbd\xf7\xd1\xdf\x6d\x69\x9e\x0b\xae\x1e\x83\x5f\xcd\xcb\xb2\x75\ -\x47\x9a\x23\xbf\x38\xd2\x3b\x6b\x5c\x18\xf0\x1d\xa9\xd6\x1c\x69\ -\x8d\xfc\xe0\x40\xab\x6b\x4c\xfe\x61\x22\xeb\x05\xfe\x71\x55\x48\ -\xd6\x76\xe2\xb1\x6f\x4d\xe9\x98\xc6\x58\x06\x64\xdc\xec\xe6\x44\ -\xa9\x75\xb3\xad\x2d\x5f\x9a\xd2\xb0\x81\xc1\x0c\xf8\xe7\x13\x16\ -\x21\x14\xf0\xbe\xf6\xee\xb1\xb6\xa9\xf9\x6d\x61\xf0\x5f\x63\xc1\ -\x76\x21\x12\x40\x12\x80\x2f\xb4\x5b\xa3\x9f\x18\x9b\xbb\x47\x8f\ -\x1e\x3d\x2c\xf1\x27\x17\xaf\x43\xaf\x5e\x06\xce\xc3\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x08\xd7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x89\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x6d\x70\x54\xd5\x19\x7e\xde\x73\x77\x37\xb0\x24\x7c\x64\x11\ -\x13\xd4\xd1\xa0\x65\x30\x54\x66\x60\xb3\x50\xd4\x46\xb0\x76\xa4\ -\x1d\xc1\x62\xbb\x56\xed\xa8\x80\x24\x21\x40\x56\x60\xac\x1d\x9c\ -\xd1\x4b\x5a\xa9\xf5\x2b\x26\xbb\x60\x08\x04\x0a\x2a\xd3\x19\xd3\ -\x11\xa6\x38\x80\x4c\x6b\xc3\x50\x0b\x21\x1b\xed\x50\x05\x3a\x7e\ -\x80\x94\x49\x88\x95\xcf\x60\x24\xd9\xdd\xf3\xf6\x47\x10\xee\xc7\ -\xee\x66\x6f\x72\x37\x86\x36\xcf\xbf\xfb\x9c\xe7\xbc\xfb\xdc\x77\ -\xcf\x3d\x7b\xee\x39\xef\x02\x03\x18\xc0\x00\xfe\x9f\x41\x7d\xf1\ -\x21\x13\xe7\x06\xaf\x52\x32\xa8\x10\x90\xb7\x80\x69\x1c\x08\x63\ -\x98\x31\x9c\x80\xa1\x00\x14\x80\xce\x01\x38\x07\xe6\x63\x20\x1c\ -\x02\x70\x50\xc4\x68\xcf\xfe\xda\xb2\x23\xe9\xf6\x96\xb6\x04\x78\ -\x8b\x83\x37\x0a\xc2\x1c\x66\xcc\x02\x61\x42\x0f\xc3\x1c\x61\xf0\ -\x0e\x21\x79\x63\xe3\xba\xc7\xc3\x00\xb1\xad\x26\x61\x7b\x02\x98\ -\x7c\x25\xc1\xbb\x19\xf4\x24\x80\xe9\xf6\xc6\xc6\x87\x04\xaa\x90\ -\xec\x7a\xa3\x69\x6d\x49\xc4\xae\xa0\xb6\x25\xc0\x5b\x5c\x35\x9d\ -\x88\x5e\x00\x50\x60\x57\xcc\x78\x60\xe0\x28\x98\x57\x34\xad\x0d\ -\xbc\x66\xc7\x88\xe8\x75\x02\xa6\xcc\xaf\xbc\x3a\xaa\x88\x97\x09\ -\xf8\x45\x12\x99\x24\xe0\x3d\x10\xd7\x4b\x29\x0e\x03\xb1\x4f\x1d\ -\x44\xa7\xa4\xe2\x68\x8b\x7e\x1d\x8b\x29\x83\xa2\x59\x60\xc7\x30\ -\x62\xe4\x49\xa6\xb1\x04\x9e\x0a\xc2\x0f\x01\x0c\x4e\x62\x7c\x0f\ -\xa4\x28\x6d\x5c\xb7\xf8\xa3\xde\xf8\xef\x55\x02\x0a\x16\x04\x27\ -\x83\xb1\x15\x40\x6e\x9c\xe6\x36\x00\xdb\x89\xb0\x8d\x14\xb1\x73\ -\xff\xea\xc5\x27\xad\xc4\x9e\xba\xb4\x62\x70\xe7\x57\x8e\x3b\x09\ -\x98\x09\xc2\xac\x04\x9f\x71\x01\xc0\xbc\x70\x4d\xe0\x0f\xd6\xdd\ -\x77\xa1\xc7\x09\xf0\x16\x87\x1e\x22\xe2\x0d\x00\x32\x4c\xa6\x98\ -\x83\x1d\x8a\xf3\x77\xff\xac\x5e\x78\xba\xa7\xf1\xb5\xc8\xf7\xab\ -\x2e\xf7\x88\xec\x22\x22\x7a\x86\x81\x51\x26\x01\xd3\xca\x70\xee\ -\x97\xcf\xa0\xbc\x5c\x5a\x8d\x6d\x3d\x01\xaa\x2a\xbc\x27\x46\x3e\ -\x4b\xe0\xe5\x86\x16\x49\x84\x0d\x22\x8a\xf2\x86\xda\xc0\x71\xcb\ -\x71\x53\xc0\x6d\xf3\x9e\xcf\xea\x70\xb8\x97\x81\xf8\x09\x00\x99\ -\x86\xe6\xad\xed\x8a\xf2\xf0\xc1\x57\x17\x9d\xb7\x12\xd3\x5a\x02\ -\x54\x55\x14\xb4\x8c\xdc\x0c\xe2\x07\x74\x3c\xa3\x19\x02\xb3\xc3\ -\x6b\x02\xfb\x2d\xc5\xeb\x21\xa6\xcc\x0f\x5e\x1b\x53\xb0\x05\xe6\ -\x09\xf7\x03\xc5\x85\x69\x0d\xa1\xc0\xb9\x54\x63\x09\x2b\x1f\xec\ -\x6b\xcd\x5e\x61\xbc\x79\x02\xf6\x31\x62\x05\x7d\x75\xf3\x00\xd0\ -\x50\x1b\x38\xee\x74\x47\x0b\x19\xd8\x6c\x68\x9a\x28\x3b\x79\xb3\ -\xdf\xff\xa6\x92\x6a\xac\x94\x85\xbe\x92\xd0\xcf\x19\x08\x69\x39\ -\x22\xda\x34\xa4\x23\xcb\xbf\x77\x7d\xe9\x99\x54\xe3\xd8\x85\xe3\ -\xfb\xde\x89\xb6\x34\x6d\xdf\x32\xda\xd7\xd8\x0e\xe0\x2e\x5c\x1a\ -\xcd\x34\xf6\xcc\xa0\xb6\x41\xcd\x4d\x3b\xff\x9c\x4a\x9c\x94\x1e\ -\x81\xc9\x25\xa1\x02\x09\xde\x03\x60\xd0\x65\x96\xdf\x08\xd7\x04\ -\x1e\x49\xc7\xea\xcc\x2a\x0a\x8a\x83\x4b\x40\x78\xc5\x40\x3f\x1a\ -\xae\x09\xbc\xd6\x5d\xdf\x6e\x1f\x81\xc9\x8b\x56\x79\x62\xc0\x56\ -\xe8\x6e\x1e\xfb\x33\x3b\x86\x16\xf5\x87\x9b\x07\x80\xf0\xda\xb2\ -\x2a\x80\x7f\x6f\xa0\xd7\x79\x8b\x57\x4d\xea\xae\x6f\xb7\x09\x90\ -\x11\xf9\x02\x81\xaf\xb9\x44\x30\x9a\x63\x4e\x9a\x5d\xbf\x71\xee\ -\x05\xeb\x56\xd3\x05\xe2\x33\x2e\x2a\x05\xe1\xef\x1a\xd2\x45\x24\ -\xd7\x4d\x53\x55\x47\xb2\x9e\x49\x13\xe0\x2d\xae\xbc\x1d\x84\x79\ -\x1a\x8a\xa5\x82\x9f\x7e\xb0\xaa\xac\xb9\x37\x76\xd3\x81\x4f\x42\ -\x81\x0e\x25\x2a\xef\x03\xf0\xa5\x86\x9e\xd4\xd6\xe2\x59\x98\xac\ -\x5f\x92\x04\x30\x11\x89\xe7\x0c\xdc\xe6\xf7\xab\x03\xfb\x7a\x6e\ -\x33\xbd\x68\xa8\x5d\xd2\x0a\xc6\x4a\x2d\x47\x84\xa7\x27\x3c\xfc\ -\xe2\x90\x44\x7d\x12\x26\xc0\x57\x14\x2a\x04\x70\xbb\x86\x8a\x40\ -\xc4\xd4\xde\xdb\x4c\x2f\x32\x3b\xb3\xd6\x00\x38\xa6\xa1\x46\x3a\ -\xdd\xae\x92\x44\xfa\x84\x09\x60\x81\x5f\xea\x09\xd4\x84\xab\x97\ -\x7d\xd6\x6b\x87\x69\x46\xfd\xc6\xb9\x17\x88\x60\xf8\xa2\xc4\xb2\ -\x44\x6b\x83\xb8\x09\xf0\x2d\x5c\x9d\x03\x60\x86\x86\x8a\x28\x52\ -\x3e\x6b\x97\xc9\x74\xe3\x86\x93\x39\xaf\x33\xf0\xf1\x37\xd7\x04\ -\xbe\xe6\x53\x4f\xeb\x5d\xf1\xb4\x71\x13\x20\x63\xd1\x87\xa0\x59\ -\x24\x11\xf0\x6e\x43\xed\x92\x56\xdb\x9d\xa6\x09\x75\x75\xf7\xc7\ -\x88\x50\xa7\xe5\x04\xf3\xa3\xf1\xb4\x71\x13\x40\xa0\x99\x06\xe6\ -\x4f\x76\x99\xeb\x2b\xb0\x94\x46\xcf\x3f\x8e\xf7\x18\x98\x12\x70\ -\x71\xc6\xbc\x55\xcb\x49\x8e\xbd\x6d\xaf\xbd\xf4\xa3\x29\xf7\x74\ -\x23\x00\xed\xa8\x1d\x76\xc4\x73\xc2\x6b\xd4\x99\x12\x90\xe1\x76\ -\x7d\x0f\x80\xeb\x32\x43\xff\x68\x5a\xbb\xe4\x98\x51\xd7\xef\x51\ -\x5e\x2e\x01\xd6\x7d\x71\xcc\xe6\x7d\xca\x38\x8f\x80\xf8\xae\x81\ -\xd8\x63\xab\xb1\x3e\x04\xb3\xde\x3b\x31\xc6\x1b\x35\xa6\x04\x30\ -\xf3\xcd\xba\x6b\xc8\x8f\x8d\x9a\x2b\x05\x82\xa1\xf7\x4e\xb8\xd9\ -\xa4\x31\x12\x44\xb8\x41\x47\x30\xf5\xfb\xdf\xfe\x84\x70\x3a\x8c\ -\xde\xf3\x8c\x12\xf3\x08\x20\x64\x69\xaf\x49\x50\x9f\xbf\xeb\xdb\ -\x85\x21\xed\x6e\xa3\xf7\x2c\xa3\xc6\x3c\x07\xb0\x5e\x24\x98\x2d\ -\xed\xb1\xf5\x27\xd4\x6f\x9c\xd3\x01\x20\xaa\xa1\x5c\xf9\x7e\xd5\ -\xa5\xd5\xc4\x5b\x07\xe8\x36\x49\xa2\x42\xf6\x8b\x77\xfe\x74\x21\ -\x5e\x02\xda\x74\x02\x56\x4c\xc3\xe6\x4a\xc1\xb4\x39\x1b\x33\x00\ -\x68\xf7\x03\x3a\x0f\xd6\x95\x77\x6a\x35\xe6\x49\x10\xd0\xed\xa8\ -\xb2\xe4\xe1\xe9\xb1\x97\x7e\x7c\xed\x38\x3b\xcc\x40\xb5\x19\x35\ -\xe6\x49\x10\xf4\xb9\xf6\x9a\x84\x79\xe6\xbc\x52\xc0\x8a\x63\x8c\ -\x9e\xc0\x51\xa3\x26\xce\x24\xc8\x87\xb4\x97\x04\x7c\xc7\x66\x5f\ -\x7d\x06\x09\xa9\xf3\xce\x84\xc3\x46\x8d\x39\x01\x24\x74\x87\x8d\ -\xcc\xba\x4d\x91\x2b\x0a\x0c\x83\x77\xa6\x0f\x8d\x1a\x53\x02\xda\ -\x15\xda\x0b\x40\x7b\xfe\x3e\x69\xca\xfc\xe0\xb5\xb6\xbb\x4b\x37\ -\x54\x55\x10\x70\x8f\x96\x62\x85\xeb\x8d\x32\x53\x02\xba\xce\xd6\ -\x68\xaf\x96\x8b\x2a\x74\x8f\x51\xd7\xdf\xe1\x6b\x1e\xe1\x85\xfe\ -\x44\xf9\xdc\xd0\x51\x27\xc3\x46\x5d\xfc\x2d\x31\xd6\xbf\x45\x11\ -\xf1\x2c\x5b\xdd\xf5\x05\x84\xd0\x79\x66\x60\x67\x7d\x79\x79\xd4\ -\x24\x8b\xd7\x37\xe6\xa2\xcd\x00\x2e\x1f\x35\x33\xee\x9c\x38\x37\ -\x78\x95\xdd\x1e\xd3\x06\x55\x15\x0c\xfc\x4c\x4b\x11\x78\x53\x3c\ -\x69\xdc\x04\x5c\xdc\xf7\xdf\xa5\xa1\x32\x14\xa7\xe9\x38\xbc\xdf\ -\xc2\xd7\xea\x79\x10\xc0\x38\x0d\x75\x22\x33\xe7\xd4\xae\x78\xda\ -\x84\xbb\xc2\x04\x7e\x49\x4f\xd0\xa2\x89\x8b\x56\x5d\x6f\x8b\xc3\ -\x34\x22\xdf\xaf\xba\x98\xf1\x1b\x1d\x49\xf4\x4a\xbc\xe1\x0f\x24\ -\x49\x40\x63\x4d\xe0\x5d\x00\xda\xc9\xd0\x25\xa2\x72\x85\x1d\x26\ -\xd3\x09\xb7\xc7\x53\x0c\xfd\x6b\xef\xa9\x8c\xce\xf6\xea\x44\xfa\ -\x24\x27\x43\xc4\x20\x7a\x4a\xc7\x00\x8f\x4c\x2a\xad\x32\xed\xab\ -\xf5\x17\x78\x8b\x5f\x1a\x49\x8c\xa7\xb5\x1c\x33\x7e\xfb\xde\x86\ -\x5f\x99\x96\xc0\xdf\x20\xe9\xd9\x60\x78\x4d\x59\x3d\x18\xaf\x6b\ -\xf5\x42\xd2\x96\x29\xf3\x2b\xaf\xee\xa5\x57\xdb\x91\xef\x57\x5d\ -\x24\x5c\x7f\xd4\xd5\x10\x31\x0e\x00\x19\xc1\x64\xfd\xba\x3d\x1d\ -\xee\x14\xce\x27\xa0\xdf\x5d\xbd\x2e\xe6\x10\x6f\xdd\x54\x16\x34\ -\x16\x47\x7d\xab\x70\x67\x67\x57\x81\x71\x87\x86\x8a\x40\xa0\xa8\ -\xbb\xa2\xca\x6e\x13\x70\x60\x4d\xe9\x17\x52\xe0\x27\x00\x3a\x2e\ -\x91\x8c\x5b\x87\x77\xe0\x55\x80\xfb\xa4\xd6\xb8\x3b\xf8\x4a\x42\ -\x0b\x01\x5a\xa0\x67\xa9\x34\x95\xb2\x9d\x94\x4a\x64\x5a\xc2\x3b\ -\x8e\x8f\xf6\xcd\xf8\x1c\xa0\xd9\x97\xe3\x63\xe2\xe8\x82\xc6\xdc\ -\xe1\x63\x26\xef\xfa\xcf\xc1\xdd\x31\x8b\x9e\x6d\x02\x93\xb7\xd8\ -\x13\x00\xa1\x0a\xfa\x8d\x9c\xca\x70\x4d\xe0\xb9\x44\xbd\xb4\x48\ -\xb9\x46\xa8\x39\xbc\xf3\xc0\x68\xef\x0c\x37\x88\x6e\xd3\xd0\x5e\ -\xa7\xdb\x5d\x98\x3b\xe9\x07\x6f\xb7\x34\xed\x6a\x4f\x35\x96\x1d\ -\xc8\xf7\xab\xae\xeb\xbf\x7f\xa0\x86\xba\x26\xea\x4b\x37\x4f\xc0\ -\x3b\x99\x39\x27\xe7\x1e\xdd\xbd\x3b\xa5\x9a\x41\x4b\x55\x62\x79\ -\xa7\x73\x9f\x62\xd0\x16\x1d\xc9\xb8\x03\xe4\x6a\xf4\x16\x87\x6e\ -\xb1\x12\xab\x37\x98\xb0\xa0\x7a\x94\x3b\xdb\xf3\x17\x80\x1e\x33\ -\x34\x7d\x14\xe9\x88\x3d\x90\xe8\x37\x3f\x1e\x2c\x3f\xc3\x7e\xff\ -\x9b\xca\x91\x11\x2d\x2f\x82\x68\xa9\xa1\x29\x42\x84\xea\x0e\x38\ -\x57\x1e\x58\x53\xfa\x85\xd5\xb8\xa9\x60\xea\xd2\x8a\xc1\x91\xaf\ -\x1c\x8b\x41\x58\x0e\x60\x84\xae\x91\xb0\x83\x65\xc6\x83\x4d\x6b\ -\x4b\xce\x5a\x89\xd9\xe3\x49\xac\xa0\x24\xf4\x18\xc0\xd5\x00\x9c\ -\x86\xa6\xf3\x20\x7e\x59\x71\x52\x85\x95\x82\xc5\x64\x98\xa6\xaa\ -\x8e\xb6\x96\xec\x39\x20\xb1\x42\x57\xaf\x74\x19\x15\x79\xa7\x72\ -\x9e\xac\xab\xbb\xdf\xf2\x5c\xd4\xab\x59\xdc\x57\x52\x59\xc8\x10\ -\x6f\x01\xf0\xc4\x69\x3e\x0d\x60\x1b\x80\x6d\x8a\x0b\xbb\xac\x26\ -\x23\xdf\xaf\xba\xdc\xc3\x3d\x85\xa4\x60\x26\x4b\xdc\x0b\x42\xbc\ -\x65\x78\x04\xa0\xd2\x70\x4d\xd9\xfa\x1e\xd8\x07\x60\x43\xb9\xbc\ -\x6f\xe1\xea\xeb\x38\x16\xab\x04\x70\x5f\x12\x59\x04\x84\xdd\x90\ -\xf8\x2b\x04\xfd\x4b\x30\x7f\xc2\x8a\x72\xea\x02\xd3\x79\xb7\x23\ -\x1a\x13\x91\x68\x96\x64\xc7\xb0\x28\x23\x8f\x04\x8d\x05\xcb\xa9\ -\x00\xdd\x8d\xae\xbf\xd4\x24\x72\xde\x28\x89\x4b\xdf\xaf\x7e\xbc\ -\xa9\x37\xfe\x6d\xfb\x1d\x2f\x28\x0a\xfd\x08\x82\x9f\x07\x90\xde\ -\xc9\xb0\xab\x2e\xf9\xd7\x79\x27\x73\x6a\x7b\x32\xe4\x8d\xb0\x77\ -\x21\xa3\xaa\x62\x72\x6b\xf6\xbd\x12\xb4\x1c\x0c\x9f\xad\xb1\x41\ -\x9f\x81\x65\x45\x66\xe7\xd0\xf5\x76\xd6\x28\xa6\x6d\x25\xe7\x2b\ -\x5a\x35\x5e\x0a\x9e\x43\xe0\x59\x00\xc6\xf6\x30\xcc\x09\x30\xb6\ -\x13\xc9\x4d\x8d\x39\xa7\xff\xd6\x93\xff\x03\x74\x87\x3e\x59\xca\ -\x5e\x9c\x27\xa6\x83\x79\x3c\x40\xe3\x40\xc8\x03\x30\x0c\x5d\xcf\ -\xb8\x83\x41\x67\x89\x71\x0e\xc4\xff\x26\xc2\x61\x29\x71\xd8\x41\ -\xd8\xdd\x50\x53\x76\xa8\xbf\x94\xe3\x0e\x60\x00\x03\xf8\xdf\xc4\ -\x7f\x01\x33\x41\xc7\xce\x61\x76\x81\xea\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x77\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x29\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x88\xdb\x45\x14\xc7\xbf\x6f\x92\xad\x55\xd9\x5e\xb6\x78\ -\xa9\xc5\x9b\x7f\xc0\x93\x95\x1e\xbc\x18\x6a\x92\x1a\xa1\x5b\x1b\ -\xb2\xa2\x54\xb0\xdd\x64\xb5\x20\x1e\x14\x29\x28\x6a\x0c\xb6\xa0\ -\x08\x16\x2a\xe8\xba\x49\x64\x0f\x56\x51\x37\xe9\xba\x88\x5b\x93\ -\x2c\x2c\x08\x2a\x88\x82\xd0\x22\x88\x07\x91\x56\x50\x28\x45\x69\ -\x89\x74\x93\x79\x1e\xb2\x5b\xd2\xdf\xfc\x0a\x9b\xee\xcc\xfb\x0d\ -\x34\x9f\xdb\xce\xe1\x7d\xdf\x7c\x99\x79\x33\x6f\x33\x3f\x60\xc8\ -\x90\x21\x37\x32\x64\x2b\x50\x32\x3b\xf9\x3a\x11\xbd\x02\x28\x66\ -\xe6\x23\xad\x7a\xa5\x64\x2b\xb6\x4b\x94\xad\x40\x44\xea\x55\x80\ -\x62\x00\xc7\x41\x28\x26\x73\x85\x84\xad\xd8\x2e\xb1\x66\x40\x7f\ -\x2c\x02\x08\x8c\x85\xf4\x44\x61\x87\xc5\xf8\x4e\xb0\x69\x80\xee\ -\xff\x83\x80\x51\xee\xe2\xd4\xc3\x13\x93\x77\x59\xd4\xb0\x8e\x4d\ -\x03\xd8\x18\x21\x6c\xed\x6a\xd5\x4c\xef\x3d\xb8\xdd\xa2\x8e\x55\ -\x6c\x1a\x70\x2d\xb6\x73\x3c\xd6\x48\x3c\xf1\xf4\x56\x01\xad\x81\ -\x91\x30\x00\x00\xee\x1e\xb9\xac\x17\xc7\xc7\x27\x47\x85\xf4\xd6\ -\x8d\x33\x03\x98\x39\xb8\x25\xee\x6f\x6f\x52\xf3\x99\xcc\x73\x37\ -\xb9\xd2\xbc\x1e\x9c\x19\x40\x44\x1a\xc1\xba\xc0\xd8\xd5\xb9\xa5\ -\xfd\x71\x22\x51\x8c\xbb\xd2\x1d\x14\xd7\x5b\x40\xc3\x5c\x09\xd9\ -\x91\xb1\x73\xd3\xb0\x78\x09\xdb\x08\xee\x6b\x40\xd8\x4a\x00\xf2\ -\xa9\xdc\xd4\x9b\xce\xb5\xd7\x81\x54\x11\xd4\xc6\x08\xf3\xe1\x54\ -\x36\x7f\x58\x48\xff\x9a\x48\x19\x00\x00\x5d\x63\x84\xe8\xad\x54\ -\x2e\x5f\x10\xcc\xc1\x40\xd2\x80\xb5\xed\x70\x35\x4c\x1f\x24\x73\ -\x85\xac\x68\x1e\x7d\xc8\x1a\xc0\xcc\x20\x63\x3b\x28\x62\x7c\xf2\ -\x50\x76\x2a\x29\x9a\xcb\x9a\xb8\xb8\x22\x83\x61\xd6\x84\x4d\x8a\ -\x78\x7e\xf7\x44\x7e\xa7\x74\x3a\xf2\x06\xf4\x60\x32\xb7\xc3\xad\ -\x5a\xd3\x57\xc9\x7d\x85\x7b\x24\x13\x89\xca\x80\xb5\x9b\x62\xd0\ -\x84\x31\x52\x68\xee\xca\xe6\xef\x90\xca\x23\x32\x03\x56\x61\x32\ -\x6b\xc2\xb6\x18\x51\x23\xbd\xef\xd0\x6d\x12\x09\x44\x6d\x00\x98\ -\xc1\x80\x71\x5b\xbc\x53\xab\xce\x62\x66\xff\xfe\x2d\xae\xf5\x23\ -\x37\xa0\x87\x79\x5b\x24\xe0\xbe\x4e\xfb\xe6\x85\xc4\x81\x03\x9b\ -\x5d\x2a\x7b\x62\x00\x00\x40\xf7\x56\x43\x1f\x84\x07\x47\x2e\xc6\ -\x3e\x75\xd9\x3c\xf9\x64\x00\x88\x48\xb3\xd1\x41\xd2\xf8\xc8\xd8\ -\xb9\x4a\xb1\x58\x74\x92\xab\x57\x06\x00\x0c\xea\x9d\x0c\xc1\x9a\ -\xf0\xd4\xb7\xa7\xcf\xbe\x0d\x07\x1d\xa4\x67\x06\x5c\xc1\xbc\x32\ -\x83\x5e\x48\xe5\x0a\x2f\xd9\x16\xf2\xd5\x00\x00\x64\x36\x4f\x8c\ -\xa3\xa9\x5c\xfe\x19\x9b\x2a\x1e\x1b\xc0\x00\xa0\x8d\xcd\xc0\xf4\ -\x7e\x3a\x5b\xc8\xd9\x52\xf1\xd8\x00\x00\xbd\xa2\x10\xdc\x0e\x04\ -\xc2\xbb\xb6\x04\x7c\x37\x00\x14\x52\xf6\x98\x61\xed\x58\xf4\xde\ -\x00\xe6\xb0\x1c\xb9\x6a\x2b\xbe\x37\xff\x9d\x0d\x87\x63\xc1\x93\ -\x8f\x88\x9e\x6d\xd4\x2a\xef\xd9\x52\xf0\x78\x05\x98\x93\x07\xe1\ -\xb5\xc6\x5c\xd9\xda\xe4\x01\x7f\x0d\x50\x21\x77\x9e\xe3\xcd\xb9\ -\xca\x11\x07\x42\x3e\x41\x00\xb3\x82\x39\xfb\x8f\x1e\xb8\x77\xdb\ -\xf3\x08\xfb\x01\x76\x83\x78\x56\x03\xb4\x02\x5d\x5d\xf7\x19\xf8\ -\xf2\xc2\x98\x9a\x2c\x95\x4a\x21\xb7\xc3\x8d\xe3\xcd\x0a\xe0\xde\ -\xb2\x0f\x4e\xfe\x9b\x4b\x6a\xf4\xb1\x1f\x67\x66\x56\x5c\xe9\x7a\ -\x61\x00\x33\x14\x99\x15\xef\x67\x28\xb5\xe7\xbb\xcf\x8f\xb5\x5d\ -\x6a\x47\xbf\x05\x88\x88\xc0\xc1\x3d\xff\x9b\x5e\xe1\xdd\x4b\x0b\ -\xe5\x7f\x5c\xcb\x47\xbb\x02\x88\x68\xb5\xe8\xf5\x8d\xe1\xcf\x58\ -\x37\x9e\x5a\x5a\xa8\xfc\x25\x91\x42\x64\x06\xf4\x1e\x52\x05\x26\ -\xcf\xb8\xa0\x98\xd2\xa7\xe6\xa7\x7f\x97\xca\x23\x2a\x03\x88\x4d\ -\xed\x4b\x0c\x3c\xf2\x75\xad\x7c\x46\x32\x11\x79\x03\x08\x14\xa2\ -\xbb\x02\xd2\xd9\x56\xbd\xf2\xbd\x74\x3a\xd2\x06\x10\xb4\xa1\xc9\ -\x0c\x7a\xb2\x39\xf7\x61\x43\x38\x17\x00\xf2\x06\x28\xe3\xb0\x63\ -\x1c\x6a\xd5\xca\x9f\x09\xe7\x71\x05\xc9\x63\x30\x16\x1c\x20\xe6\ -\x97\x1b\xf5\xea\x8c\x60\x0e\x06\x52\x2b\x20\xac\xa7\x7f\xa7\x51\ -\xaf\x46\xfe\x4c\xc6\xbd\x01\xa1\xcd\x0d\xcf\x36\x6b\xd5\x17\xe1\ -\xa0\xb9\x19\x14\xd7\x06\x18\xcd\x0d\x01\x5f\xac\x9c\xbf\x7d\x0a\ -\x1e\x4c\x1e\x70\xfb\x50\x32\xac\xad\x5d\xbe\x3c\xda\x79\x7c\x79\ -\xb9\xd4\x71\xa5\x3b\x28\x2e\x1f\x4a\x06\x3b\xbb\x9f\xe2\x9b\xdb\ -\x7b\x97\x67\x67\xff\x73\xa5\x79\x3d\x48\x15\xc1\x5f\x95\x8e\x67\ -\x16\x4f\x9c\xf8\x57\x48\x6f\xdd\x48\x18\x70\x96\x95\x4a\x35\x4e\ -\x4e\xff\x2d\xa0\x35\x30\x36\xef\x01\x61\x3f\x5c\x9e\x67\x8d\x74\ -\xab\x36\xf3\x87\x45\x1d\xab\x38\xf9\x64\x66\x95\x8b\x9a\x29\xd3\ -\x3a\x59\xf9\xc5\xa2\x86\x75\xec\x7d\x34\x85\xfe\x57\x5f\xcc\x20\ -\x7e\x74\xa9\x5e\xfe\xc1\x56\x7c\x57\x58\xfc\x6a\x8c\x8f\x82\xd0\ -\x05\xb8\x0b\xe0\x8d\xe6\x5c\x75\xc9\x56\xec\x21\x43\x86\x0c\x71\ -\xc5\xff\x03\xa1\x32\xbd\x29\x9d\x1e\xd2\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x17\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xc9\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x4d\x48\x54\x51\x18\x06\xe0\xf7\xbd\x5e\x4b\xb2\x20\x82\xa0\ -\x08\x8c\x56\x41\x41\x54\xd2\x38\x1a\x84\x45\x04\x26\x29\x26\xcc\ -\x22\xca\x12\xa2\x9f\x45\x8b\x08\xa2\x82\x90\xa0\x45\x60\x05\x6e\ -\x82\x28\x88\x6a\x11\xf8\x33\x57\xa4\xbf\x4d\xf4\x03\xe6\x38\x30\ -\x81\x9b\x16\x19\x05\xad\xa2\xac\xb0\x20\x35\xaf\xf7\x6d\x23\xe4\ -\x5c\x2b\xcc\xb9\x33\x41\x7d\xcf\xf2\x7c\xe7\xbc\x7c\xe7\xbb\x1c\ -\x66\x00\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\ -\xfc\x2f\x98\x6b\x40\x45\xb7\x56\x21\xd0\x0d\x00\xcb\x04\x5e\x4c\ -\x37\xe0\x3c\x48\x45\xd0\xdb\x4f\xc5\xba\xd4\x00\xaa\x15\x00\x1c\ -\xf2\x48\xaa\x81\xf7\x72\xc9\xcb\x7d\x00\xc9\xe0\x31\x80\x4d\x3f\ -\x12\x75\xf3\xcb\xb8\xb3\xff\x79\x82\xdf\x72\xcd\xce\x22\x31\xee\ -\xe1\xb8\xa0\x73\x53\x56\x87\xfd\xf7\x5c\x9c\x39\xc8\xf1\xd9\xc6\ -\x3a\x11\xb4\x96\x9d\x21\xee\x59\xe0\xea\xfe\x5a\x4f\x0b\x23\xc8\ -\x06\x00\x54\x3f\x94\x1b\xf7\x82\x4b\xa1\xcb\x03\x11\x7c\xc0\x9c\ -\x07\x30\x01\x1e\x06\xf0\x2e\xb4\xbc\x79\xae\xd4\x5b\xd5\xa5\xe5\ -\xb9\xe6\x57\xb7\x6b\xfe\xc8\x27\x75\x0b\x3c\x34\x75\x5d\xc0\x18\ -\x1d\xee\xce\xe5\xeb\x03\x11\x4c\x10\x00\x62\x3d\x5a\x41\x5f\xf7\ -\x00\xac\x0c\x95\xde\x52\xac\x4d\x35\xf2\xd9\x6c\x72\xcb\xbb\xb4\ -\xd4\xa5\x6e\x03\x58\x1f\x2a\x7d\xa4\x58\x97\x6a\x64\xef\x6c\x72\ -\xa7\x8a\xe2\x09\x20\x5d\xc7\xd7\x8e\xcf\x2a\x00\x4f\x42\xa5\x25\ -\x82\x9e\xc4\xba\x54\xfb\xa7\x99\x1b\x3a\xb5\xba\xd8\x51\x0a\xd3\ -\x2f\xff\x4a\x60\x65\x14\x97\x07\x22\x1a\x00\x00\xf4\x25\xf8\x71\ -\x51\x09\xb7\x01\xba\x95\x55\x20\x4a\x49\xf5\xc4\x3d\x1d\x9e\x69\ -\x56\x2c\xa9\x2d\x8e\xa3\x5e\x09\x65\x59\x05\xa1\x7f\x8e\xcf\x78\ -\x7a\x27\x5f\x44\xd3\x75\x44\x4f\x20\x4b\x8b\x9c\x8a\x35\xc1\x59\ -\x90\x27\xa7\x17\xd5\xda\x3f\xe0\x9c\xc0\x19\x06\xbf\x3a\x1e\x4b\ -\xaa\x89\xd0\x55\x00\xc5\xa1\x46\xbd\x71\x97\xbb\x33\x75\xfc\x1a\ -\x65\xbb\xd1\x0f\x60\x52\x85\xa7\x03\x90\x2e\x01\x28\x9a\xba\x2e\ -\xa8\x7d\xde\xb0\xb3\xf7\x51\x33\x47\xb3\x0e\x48\xac\xf0\x70\x1a\ -\xd0\x99\xe9\x69\x6a\x2b\xf3\x9d\x63\x1d\x09\x4e\x44\xdd\x67\xde\ -\x06\x00\x00\x71\x4f\x35\x0a\xd4\x01\xa2\x34\x54\xea\x15\x58\x9f\ -\xde\xc9\x0f\x00\xb0\xaa\x5d\x73\x16\x14\x05\x97\x41\xee\x0b\xed\ -\x13\xc8\xa3\xfd\x0d\x6c\xcb\x57\x8f\x79\x1d\x00\x00\x54\x76\x6a\ -\x5d\xe0\xe8\x0e\x80\xa5\xa1\xd2\x60\x11\x59\x33\x36\x8e\x21\xb7\ -\x58\x9d\x10\xb6\x86\xea\xa3\x12\x77\xa5\x1b\xe9\xe5\xb3\xbf\xbc\ -\x0f\x00\x00\xca\xdb\x55\xe6\xba\xba\x0b\x60\xf5\x0c\x8f\x0c\x41\ -\xdc\xd1\xdf\xc8\x54\x3e\xfb\x02\x22\xfc\x15\xf8\x9d\x4c\x82\x6f\ -\x7c\x9f\x1b\x09\x3c\x98\xc1\xf6\x41\xa7\x88\x95\x85\xb8\x3c\x50\ -\xa0\x01\x00\x40\x26\xc1\xe1\xcf\x3e\xb7\x13\xba\xfe\xab\x3d\x12\ -\x9e\xfa\x2e\xab\xfa\xea\xf9\xb2\x50\x7d\x15\xe4\x09\x64\x91\x18\ -\x4f\x06\x2d\x22\x5b\x42\x95\x4e\xc7\x67\x53\x5f\x82\x23\x85\x6c\ -\xa7\xf0\x03\x98\x14\x4b\x4e\x5c\x21\xd8\x0c\x40\x82\x2e\xa4\x07\ -\x9c\x53\xbf\xfb\x7f\xf0\x4f\xaa\x7e\x28\xb7\xfa\x9a\x4a\xfe\x76\ -\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\xcc\x7f\ -\xe2\x3b\x5f\x7a\xf2\xea\xb1\x6e\xd0\x9c\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x08\x6c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x1e\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x8c\x1c\x65\x1d\x7e\x7e\x33\xb7\x7b\x77\x70\x1f\x10\xe8\ -\x51\xb3\x1f\xb3\x7b\xd7\x6b\x4a\x5a\x4c\x2c\xa7\x11\xd2\x54\x4b\ -\x34\xa8\xa1\x87\x45\x12\x05\x03\x34\x90\x2a\x45\x49\x94\x40\x4d\ -\x4d\xc0\xaa\x54\xa1\x4a\x0b\xfc\x41\x55\x04\x2d\xd0\x48\x02\x42\ -\x63\x0d\x60\xff\xc0\x36\x55\x21\x80\xd1\xe8\x62\xcf\x5c\xdd\xdb\ -\xd9\x9d\xbb\x1e\xb5\x14\xfb\x61\x7a\xb7\xb3\xfb\x3e\xfe\xd1\x22\ -\xf3\xb5\x77\xbb\xb7\x33\xc7\x55\xef\xf9\x6f\x9e\xf7\xf7\xfe\xe6\ -\x99\x67\xde\x99\x7d\xe7\x7d\x7f\x0b\xcc\x63\x1e\xf3\xf8\x7f\x86\ -\xcc\xc6\x49\x86\x0f\x1d\x5a\x10\x9b\xac\xac\xa4\xe0\x12\x0d\xb2\ -\x44\x81\xbd\x00\xce\x13\x48\x17\x40\x1d\xc0\x71\x00\xc7\x09\x29\ -\x02\x3c\xa0\x41\xfe\x46\x56\xf6\x67\x32\x99\x91\xa8\xb5\x45\x66\ -\x40\xb1\x58\xec\x53\xd0\xd6\x42\x71\x10\x82\x0f\xce\x30\xcd\x08\ -\x28\x2f\x6a\x9a\xfa\x79\x2a\x95\x7a\x43\x44\x18\xaa\x48\x84\x6c\ -\x00\x49\x29\x58\xd6\x95\xa2\xb0\x01\xc0\xaa\x30\x73\x03\xc8\x51\ -\xb8\xf5\xed\xc3\x87\x9f\x1a\x18\x18\xb0\xc3\x4a\x1a\x9a\x01\x85\ -\x82\xb5\x0a\xc2\x2d\x00\x06\xc2\xca\x19\x0c\x29\x10\xd8\x94\x49\ -\x27\x9e\x08\x63\x44\x34\x6d\x40\x3e\x9f\xbf\x48\xd3\x63\x0f\x00\ -\xf8\xe2\x14\x61\x8a\xc0\xef\x45\x64\x2f\x14\x87\xa8\xe3\x1f\x2d\ -\xc0\xd1\x4a\xa5\x72\xa2\xd2\xd6\x56\x8d\x97\xcb\x9d\x64\x4b\x37\ -\xa0\xb2\x14\x2c\x06\xe4\x32\x01\x3f\x09\xa0\xbd\x56\x42\x02\xfb\ -\x35\xa8\xf5\x86\x61\xbc\xd9\x8c\xfe\xa6\x0c\xc8\x97\x4a\x1f\xd1\ -\x14\x76\x01\xf8\x40\x40\xf3\x09\x81\xbc\x40\x72\x77\x4b\x8b\xbc\ -\x94\x4c\x26\xdf\x6e\x24\x77\xa9\x54\x6a\xaf\x56\xe5\x0a\x11\xb5\ -\x9a\x90\xc1\x1a\xe7\x98\xa0\xf0\xe6\x6c\x3a\xfd\x8b\x99\xe8\x07\ -\x9a\x30\xa0\x50\x28\x5d\x0f\xc1\xe3\x00\x5a\x7d\xa2\x80\x87\x35\ -\xa8\xfb\x0c\xc3\x78\x67\xa6\xf9\x9d\xc8\xe5\x72\xf1\x8e\x8e\xae\ -\x75\x10\xb9\x07\x40\x8f\x2f\x80\xb2\xd9\x30\x12\xf7\x88\x88\x6a\ -\x34\x77\xc3\x06\x90\xd4\x8a\xc5\xd2\xbd\x84\x6c\xf4\x34\x29\x00\ -\x8f\xb7\xe8\xf2\xed\x64\x32\x69\x35\x9a\xb7\x1e\x0c\x0d\xfd\xb3\ -\xb3\xbd\x7d\xe2\x0e\x02\x77\x02\xe8\x70\x0b\xc3\xae\x73\xce\x69\ -\xbd\xa1\xa7\xa7\xe7\x64\x23\x39\x1b\x32\x80\xa4\x66\x9a\xa3\x3b\ -\x21\xfc\x82\xa7\x69\x4c\x69\x58\xd3\x9b\x4a\xbd\xd6\x48\xbe\x99\ -\xc2\xb2\xac\x64\xa5\xca\xe7\xe1\x7f\xe1\xfe\xc9\x2e\x4f\x7c\xbc\ -\xbf\xbf\xff\x78\xbd\xb9\xb4\x46\x4e\x6c\x96\x46\x37\xf9\x2e\x5e\ -\xf0\x2a\x58\x1d\x98\xad\x8b\x07\x80\x64\x32\x69\xe9\x1a\x56\x02\ -\xd8\xe9\x69\xfa\x50\x2c\xde\xb6\x93\xa4\x5e\x6f\xae\xba\x47\xc0\ -\x48\xb1\xf8\x79\xa1\x3c\xed\xee\xcc\x1d\x4a\x55\x6f\xcd\x66\xb3\ -\x13\xf5\xe6\x09\x13\x24\xa5\x58\xb4\xee\x22\x70\x1f\x1c\xd7\x42\ -\x60\x4b\xd6\x48\x7d\xa3\x9e\x1c\x75\x19\x50\x2c\x16\x07\x14\x65\ -\x3f\x80\x36\x07\xfd\x94\x91\x4e\xde\x18\xc5\xec\xac\x51\x8c\x98\ -\xd6\xd7\x04\xdc\xe6\xe4\x04\x72\x93\x61\x24\x9f\x98\xae\xef\xb4\ -\x8f\x80\x65\x59\x17\x28\xca\x2e\x38\x2e\x5e\x80\xd7\xa8\x2a\xeb\ -\xe6\xc2\xc5\x03\x40\x26\x9d\x78\x08\x94\x9f\x39\x39\x82\x8f\x16\ -\x0a\x63\xcb\xa7\xeb\x3b\xad\x01\x15\xc5\x2d\x00\x12\x0e\x6a\x4c\ -\x84\x6b\xde\xaf\x61\x1f\x04\x11\xa1\x6d\x9f\x5a\x0f\xe0\x0f\x0e\ -\x3a\x0e\xa9\x3c\x4a\xb2\x65\xaa\xbe\x53\x1a\x60\x9a\xe6\x0a\x10\ -\x37\x3b\x28\x52\xc9\xe7\xd2\xe9\xf4\x58\x13\x7a\x23\x41\x7f\x7f\ -\xff\xa4\xaa\xda\xd7\x00\x38\xf2\x1e\x2b\xcb\x8b\x45\xeb\xb6\xa9\ -\xfa\xd5\x34\x80\xa4\x10\xfa\xf7\x3d\xf4\xce\x6c\x36\xf9\x6a\x33\ -\x42\xa3\x44\x6f\x6f\xef\x5b\x84\x6c\x76\x72\x04\xee\x1e\x1f\x1f\ -\x3f\xb7\x56\x9f\x9a\x06\x14\x2c\x6b\x25\xc0\x15\x0e\xca\x16\xa8\ -\x6f\x85\xa0\x33\x5a\x28\xfb\x47\x10\x14\x1d\xcc\x85\x13\xe5\xf2\ -\x97\x6b\x85\xd7\x34\x40\x14\xee\x72\x13\xf8\xb1\x61\x18\xf9\xe6\ -\x15\x46\x8b\x6c\x36\x3b\x41\xd0\x7d\xa3\x28\x77\xd4\x9a\x1b\x04\ -\x1a\x30\x32\x32\xb2\x10\xc0\xa7\x1c\x94\xad\x2a\xf6\xbd\xa1\xa9\ -\x8c\x18\x99\x54\xea\x49\x02\xc3\x0e\x2a\x51\x28\x95\x3e\x11\x14\ -\x1b\x68\x80\xe8\xfa\xf5\x00\xfe\xeb\x98\x00\x2f\xf7\xf6\xf6\xbe\ -\x15\xae\xcc\xe8\x20\x22\x55\x21\x9f\x71\x71\x4a\x6e\x0a\x8a\xad\ -\xf1\x08\xc8\x6a\xe7\x11\x85\xbf\x0a\x4b\xdc\x6c\x81\xba\xb8\x35\ -\x0b\x3e\x13\xf4\x18\xf8\x0c\x18\x1f\x1f\x3f\x17\xc4\xe5\x4e\xae\ -\x6a\xeb\xbf\x0e\x5d\x61\xc4\xc8\x24\x93\xaf\x03\xe2\x1c\xb5\xdd\ -\x23\x96\x75\xa9\x37\xce\x67\xc0\xe4\x64\xe5\xa3\x00\xe2\x0e\xea\ -\xcf\x7d\x7d\x89\xa2\x37\x6e\xae\x43\x44\x14\x84\xae\x1b\xa7\x2b\ -\xff\x3a\x65\xc0\x23\xc0\x65\x1e\x62\x7f\xa8\xca\x66\x11\x3c\xfd\ -\xfd\xf2\xde\x31\xb0\xd4\x1b\x13\x64\xc0\xc5\xce\x23\x71\xbf\x4d\ -\xcf\x2a\x08\xc5\xab\xfd\x62\x6f\x4c\x80\x01\x92\x71\x1e\x91\x32\ -\xe7\x7f\xfb\x6b\x81\x2c\x7b\xb5\x67\xbd\x31\x3e\x03\x08\x74\x3a\ -\x8f\x45\xe4\x5f\x21\xeb\x9a\x4d\x78\xb5\x77\x7a\x03\xa6\x35\xa0\ -\x5a\x65\x43\x6b\x6c\x73\x09\x99\x4c\x66\x12\x40\xc5\x41\xc5\x73\ -\xb9\x9c\xf3\x05\xef\x37\x40\xbc\x8b\x24\x31\xce\x89\x6f\xfe\xa8\ -\x10\x34\x11\x3a\xe1\x3c\xd0\x95\xe6\x1b\x36\x67\x0b\x0a\x85\x42\ -\x2b\x00\xe7\x7a\x40\x79\xd9\xb2\x65\x65\x67\x4c\xd0\x08\x70\xad\ -\xa8\x92\x3c\x2f\x1a\x79\xd1\x83\x64\xb7\x87\x3a\xe1\x8d\xf1\x19\ -\xa0\x00\xd3\x93\xc6\xf7\xe6\x3c\x5b\xa0\x69\xf1\x5e\x0f\x55\xf0\ -\xc5\xf8\xbb\xc9\x01\xe7\x11\x05\xfd\x61\x8a\x9a\x4d\x88\x5f\xfb\ -\x90\x37\xc6\x67\x80\x86\xaa\x6b\xb3\x51\xdc\x8b\x22\x67\x15\xe8\ -\xd1\x4e\x20\xe7\x8d\xf1\x19\xd0\xde\xde\xfe\x0a\x00\xc7\xfe\xbb\ -\x2c\xb7\x2c\x2b\x19\x81\xbe\x48\x41\x52\x03\x70\x95\x8b\x54\xb2\ -\xd7\x1b\xe7\x33\xa0\xa7\xa7\xe7\xa4\x00\xaf\x38\x39\x5b\x79\x12\ -\x9d\x05\x28\x95\x4a\x97\xc2\xbd\xa3\x7c\x3c\x93\x49\xbc\xe1\x8d\ -\x0b\x5c\x0f\x20\xe1\xfa\x8a\x12\x70\x30\x5c\x79\xd1\x43\x41\x73\ -\x69\x26\xf8\x92\x88\x54\xbc\x71\x81\x06\x68\x1a\x77\xe2\xf4\x6e\ -\xef\xbb\xbd\xaf\x18\x3e\x74\x68\x41\xd8\x22\xa3\x02\x49\x0d\xe4\ -\xb5\x4e\x4e\x28\x3b\x82\x62\x03\x0d\x48\xa7\xd3\x63\x20\xf6\x38\ -\xa8\xd6\xd8\xa4\xed\xdd\x0e\x9f\xb3\x30\x4d\xeb\x3a\x00\x4b\x1c\ -\xd4\xb8\x61\x24\xf7\x04\xc5\xd6\x5e\x15\x16\xf9\xa1\x87\xf8\x4a\ -\x3e\x3f\x66\x84\xa2\x30\x42\xe4\x72\xb9\x38\x04\xdf\x75\x72\x02\ -\x6c\x0b\x1a\xfe\xc0\x14\x06\xa4\xd3\x89\x97\xe1\x7e\x19\xc6\x75\ -\x5d\x6d\x0a\x45\x65\x84\xe8\xe8\xe8\xfe\x12\xdc\x9f\xbd\x47\x4f\ -\x9d\x6a\xdb\x5e\x2b\x7e\xaa\x11\x40\x2a\x7c\xd3\xc9\x11\xbc\xd1\ -\x34\x4d\xdf\xba\xda\x5c\xc1\xe8\xe8\xe8\x85\x10\xdc\xed\x22\xc9\ -\xef\x2d\x59\xb2\xc0\x37\x05\x7e\x17\x53\xee\x0d\x66\xb3\xa9\xbd\ -\x00\x9e\x74\xc7\x6b\xcf\xe7\xf3\xf9\x8b\x9a\x11\x1a\x05\x72\xb9\ -\x5c\xdc\xb6\xd5\xb3\x70\xd6\x10\x11\x7f\x39\x72\xe4\xf0\xc3\x53\ -\xf5\x9b\x7e\x77\xd8\x8e\xdd\xe9\x5c\x5d\x25\x90\xd2\xf4\xd8\x73\ -\xc3\xc3\xc3\xde\xe2\xa8\xf7\x15\x9d\x9d\x5d\x0f\x41\xf0\x31\x07\ -\x65\x2b\x1d\xeb\xa6\x2b\xaa\x9c\xd6\x80\x45\x8b\x16\x1e\xa6\xc2\ -\x67\x01\x4c\x3a\xe8\xcb\x63\xad\x6d\x8f\x90\x9c\x95\x5a\xe3\xe9\ -\x50\x28\x16\x6f\x23\xe4\x56\x17\x49\xac\xaf\xa7\x6c\xa7\xee\x0b\ -\x30\x4d\xeb\x06\x82\xae\x8a\x0b\x02\x3f\xf9\xf7\x89\x63\xb7\x7b\ -\xbf\xb1\x67\x0b\x67\x4a\x64\x6e\x27\xb0\x0d\x8e\x9b\x29\xe0\x83\ -\x86\x91\xfe\x7a\x3d\x39\x1a\xba\x83\x23\x66\xe9\x7e\x01\x36\xb8\ -\x55\x60\x5f\x2c\xa6\x5d\x9b\x48\x24\x8e\xd4\xe8\x16\x09\x72\xb9\ -\x5c\xbc\xa3\xab\xfb\x11\x10\xb7\x38\x79\x01\x7e\x93\x4e\x27\xaf\ -\xaa\xf5\xb3\xe7\x45\xa3\x65\x72\xba\x59\xb2\x9e\x01\xb1\xc6\x93\ -\xa6\xa0\x6b\x1c\x4c\xa5\x52\x7f\x6d\x24\xdf\x4c\x71\xf0\xe0\x78\ -\x4f\x4b\xac\xf2\x4b\xf8\xbf\x54\xdf\xa4\xaa\xac\xc8\x66\xb3\x75\ -\x2f\xe4\xce\xa4\x50\x52\x37\xcd\xd2\x0f\x20\xe2\x1d\x62\x36\x81\ -\xed\x55\x3b\xb6\x79\xd1\xa2\x85\x87\x1b\xcd\x5b\x0f\x4e\x97\xcf\ -\xe2\xab\x10\x6c\x04\x70\xbe\xab\x51\xf0\x62\xd5\x2e\x5f\xd7\xd7\ -\xd7\x77\xac\x91\x9c\xcd\x94\xca\xde\x02\xc1\x76\x00\x31\x4f\xd3\ -\x49\x02\x0f\x54\xca\x13\x5b\x1b\x29\x58\x9c\x0a\x24\x5b\x4c\xd3\ -\x5a\x0b\xc1\x26\xb8\xeb\x95\xce\x04\xc8\x56\xc3\x48\x6c\x10\x91\ -\x6a\xa3\xb9\x9b\x2b\x96\x2e\x16\x57\x6a\x94\xe7\x00\x5c\x10\xd0\ -\xfc\x0e\xc1\xdd\x1a\xb4\xdd\xe5\xf2\xa9\x3d\x8d\x9a\x91\xcb\xe5\ -\xe2\x9d\x9d\xe7\xaf\x54\x50\xab\x05\xb8\x1a\x40\xd0\x34\xdc\x06\ -\xb1\x3e\x93\x49\x3d\x36\x13\xfd\x40\x08\xe5\xf2\x07\x47\x47\x53\ -\x2d\x55\xf5\x20\x88\x6b\xa6\x08\xb3\x01\xee\x83\x68\xbf\x85\xe2\ -\xdf\x95\x92\x83\xaa\x55\x8e\xc6\x2a\x95\x93\xe5\x72\xb9\xda\xd6\ -\xd6\xd6\xa9\x94\xea\x26\xf5\x2c\x35\x2c\x06\xd5\x65\x02\xb9\x12\ -\x40\x57\xad\x84\x04\x5e\x3f\x53\x2e\xff\xc7\x66\xf4\x87\xf8\x87\ -\x89\xd2\xa7\x29\xb8\x5f\x80\x4b\xc2\xca\x59\x03\x63\x84\x7c\x27\ -\x93\x4e\xfc\x74\x26\x43\xde\x8b\xb0\xff\x32\xa3\x99\xa6\x75\x35\ -\x05\x1b\x05\xf8\x70\x98\xb9\x01\xe4\x41\x6e\x25\xab\x8f\x85\x59\ -\xa3\x18\xd9\x4c\xce\x34\xcd\xa5\x14\x6d\x2d\x14\x06\x21\x58\x3c\ -\xc3\x34\xe3\x10\xbc\xa0\xc0\x1d\xd9\x54\xea\x77\x33\xf9\x3f\xc0\ -\x74\x98\x95\xa9\xec\xc1\xd1\xd1\x54\xac\xc2\x55\x0a\x5c\x0a\xc8\ -\x12\x80\x59\x11\x74\x83\xe8\xc2\xe9\x9d\x9b\x63\x00\x8f\x0b\xa4\ -\xa4\x80\x21\x08\x87\x34\x72\x5f\x3a\x9d\x3e\x30\x57\xca\x71\xe7\ -\x31\x8f\x79\xfc\x6f\xe2\x3f\x21\x7b\x09\x29\x0d\x19\xbe\x1d\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3f\x49\x44\x41\x54\x58\x85\xed\ -\xd3\xb1\x11\x00\x10\x10\x44\xd1\xa5\x10\x94\x22\xd1\xb5\x19\xad\ -\x18\x0a\x39\x91\x50\xea\x92\xff\xa2\xcd\x7e\xb4\x12\x00\xc0\x59\ -\xb8\x63\xae\x3d\x64\xaa\x7f\xb2\xd6\x4b\x4e\x4d\x92\xe2\x9f\x20\ -\xf0\xc6\x0b\x00\x00\x70\x77\x00\xa4\x4c\x0e\x07\xff\x04\x59\xb9\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x3e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xe5\ -\x96\x31\x68\x53\x51\x14\x86\xbf\x3f\x7d\xad\x52\x41\x31\x82\x08\ -\x2e\x2e\x2e\x0e\xe2\xd0\xa0\x5d\x1c\x2b\x54\xba\x08\xa9\x53\x05\ -\x11\x4d\x96\xb4\xa9\xe0\x26\x8a\xe2\x26\xb4\x4d\x2b\xd8\x87\x83\ -\x60\x27\x1b\x70\x29\x0e\xea\xe6\xa2\xf2\x3a\x48\x07\x17\x41\x1d\ -\x14\x41\xa8\x60\xa1\x45\xdb\xe4\x1d\x87\xa4\x4e\x82\xef\xde\x5c\ -\x22\xe8\xd9\x1e\xdc\xf3\xff\xdf\x3d\xef\xdc\x73\x2f\xfc\xef\xa1\ -\xd0\x82\x83\x17\xa6\xf2\x5b\x51\xef\x3b\x30\x5b\x8e\xc7\xf7\xfe\ -\x69\x7d\x14\xd2\xfc\xe8\xd8\xed\x5d\x8d\x28\x7a\x0c\xb6\x27\x6b\ -\x4e\x2e\x94\xf9\x91\xe2\xf5\xbe\xbe\xfe\x1d\x8f\x0c\x4e\xb8\xe4\ -\x05\x01\x28\x16\x17\x7b\xfa\xf3\xfb\x1e\x00\x43\xae\xb9\x01\x00\ -\x4c\xef\xf3\x9f\xef\x00\x67\x31\x30\x2c\xed\x2a\x40\xa1\x34\x77\ -\x13\x54\x06\xc3\x64\xa9\x90\x75\x0d\x60\xe0\xd2\x6c\xd5\xe0\x2a\ -\x80\x49\xce\xe6\x1d\x01\x0c\x94\x6b\x63\x88\x69\x00\x83\x54\x86\ -\xb3\xb9\x37\x40\xa1\x34\x3b\x82\xe9\x7e\xfb\x33\x15\x7e\xe6\x5e\ -\x00\x85\xd2\xcc\x49\x83\x45\xa0\x87\x96\xb1\xb7\xb9\x33\x40\xe1\ -\xe2\xf4\x31\x23\xb7\x04\xec\x6c\x1b\x3b\x75\xfc\xef\x22\xf3\x24\ -\x3c\x5e\xaa\x1d\x4e\xd1\x13\x60\xb7\x81\x29\x80\x39\x64\xac\xc0\ -\x60\x79\xea\x60\xd3\xf4\xcc\x60\x3f\x16\xce\x1c\x32\x56\x60\xcb\ -\xa2\x8f\xbf\xae\x2d\x85\x33\x87\xac\x3d\x60\xac\x84\x34\x75\x06\ -\xe8\xcd\x35\x86\x0d\x3e\xb4\x61\x82\x5d\x60\x99\x01\x5e\xcc\x5f\ -\xfe\x14\x61\x43\x82\x2f\xb4\xc6\x5d\x30\x88\xcc\x42\xaf\xe2\x89\ -\xb7\xa4\xcd\x53\xc0\x9a\x5a\x0f\x99\x20\x10\x4e\x22\xc9\xbd\xc9\ -\xd7\x22\x1d\x01\xbe\x13\x08\xc2\x59\x20\x89\xab\xcf\x05\xa3\x40\ -\x13\x10\xea\xec\x59\xe7\xb5\x83\x24\x1e\x5f\x42\x76\x1e\xd8\x6e\ -\x4a\x6f\x08\xef\x12\x2e\xcf\x4f\x2c\x08\x55\xb7\x75\xcc\xb3\x12\ -\x1d\xfd\xc3\x24\xae\xd4\x04\xb7\x00\x64\xe6\x05\xd1\x71\x13\x25\ -\x71\xe5\x9a\xc4\x5d\x10\x4a\xc9\xb5\x26\x75\x17\x01\x40\x76\x68\ -\xf5\x40\x05\x78\x88\x40\xc8\x49\x33\xc8\x59\xae\xd7\x47\x9b\x1b\ -\x5f\x57\xcf\x01\x4f\x5d\x73\x83\x4d\xb4\x37\xf5\x1b\x9b\x9b\x1b\ -\x3f\xce\x08\x5e\xfe\x15\x00\x80\x95\x85\x2b\xeb\x51\xa3\x71\x1a\ -\x58\x03\x7d\x0b\xa9\xfd\xef\xc6\x4f\x11\x32\x94\x0c\x6f\x6b\x20\ -\xde\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x95\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ -\xce\xb1\x0d\x00\x20\x0c\x03\x41\x82\x18\x2a\xdb\xc1\x42\x69\xd8\ -\x2f\xc0\x10\x46\x4a\xf3\xd7\xdb\xfa\xd6\x04\x1e\xb9\x3c\x72\x29\ -\x1f\x5d\x19\xff\x40\x00\x01\x04\x10\x40\x00\x01\xe5\x01\x43\x3d\ -\xb8\x66\xd3\x23\xab\x02\xfa\xb6\x7b\xb4\x0b\x00\x00\x50\xed\x01\ -\x74\x44\x0a\xfd\x41\x7d\x20\x9d\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x02\x21\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ -\xd5\x3b\x8b\x13\x51\x18\xc6\xf1\xff\x33\xf1\x86\x82\xd9\x4e\x50\ -\x0b\x11\x5b\xd1\x56\xc4\x72\x36\xcd\x6a\x61\x76\xb0\x71\x51\x34\ -\x29\x2c\x64\x3f\x81\x48\xf0\x0b\x88\x82\x8d\xd9\x20\xee\x16\x42\ -\x36\x2e\xc8\x22\xce\xc6\xce\xc2\xda\xde\xc2\x4a\xb0\x71\x89\xa0\ -\x78\x21\xe7\xb1\x98\x09\xd8\x99\xcb\x30\x29\xf4\xad\x4e\xf1\x5e\ -\x7e\x9c\x73\xe6\x0c\xfc\xeb\xa1\x71\x92\xe2\x7a\x63\x17\x50\x14\ -\xf9\x64\xda\x5d\xfb\x5c\x24\x20\x1a\x33\x6f\x01\xa8\x7a\xa8\xed\ -\xc5\x95\x95\x43\xf3\x00\x00\x60\x71\xce\xdf\xf6\xf7\x92\x24\xd9\ -\x37\x17\x40\x1e\xb5\xdd\x50\x7d\x9a\x24\x49\xa5\x74\x80\x50\x30\ -\x58\x70\x65\x10\xaa\x0f\x19\xf3\x0e\x15\x06\x30\xb6\x24\x67\x6b\ -\x6e\xc5\x97\x1b\xad\x52\x01\x99\xc2\x06\x05\x00\xc4\x9d\xb8\xde\ -\x5c\x2d\x17\x90\x2b\x04\x21\x5f\xdf\x8f\xeb\x8d\xab\x25\x03\xc0\ -\x60\x69\x84\xe0\xc9\xe2\x72\x73\xa9\x54\x00\x80\x8d\x33\x0b\x15\ -\xdb\xdd\xda\x72\xe3\x42\xa9\x80\x3c\x42\x0e\x39\x10\xac\xed\x38\ -\x69\x9e\x2d\x1b\x40\x76\x14\x36\xf8\x30\xf6\xab\x5a\x72\xf3\x54\ -\xa9\x80\x9c\x11\x00\x63\x8e\x84\x40\x3f\xbe\x74\xe3\x68\xc9\x00\ -\x00\x82\x33\xcc\x09\xf6\x56\x5e\xce\x03\xf0\xc7\xd3\xe8\x33\xf3\ -\x00\xe4\xfd\xfc\x81\x5f\xe1\x58\xa9\x00\x67\xbd\x84\xf8\x14\x45\ -\xc4\xfd\x17\x9d\x8f\xe3\xd4\xed\x29\x66\xba\x23\x49\x02\x06\xd1\ -\x30\xd4\xd2\xad\xce\xfb\x71\x4b\x67\xde\x01\xe3\x88\x6c\xf8\xf7\ -\x48\x5c\x4c\xb7\x3a\xef\x26\xa9\x9f\x11\x20\x09\x09\x18\x4a\x4a\ -\xd2\xcd\xf6\x9b\x49\x3b\xcc\x02\x10\x78\x54\x7f\x7d\x67\xf3\xf1\ -\xf6\x34\x4d\xa6\x05\x68\x54\x2b\x58\xed\xf7\xda\x1b\x53\xf6\x99\ -\x0a\x20\x9c\xd7\x99\x7b\x3b\xbd\xf6\x83\x69\x87\xc3\xa4\x5f\x81\ -\x10\x81\x08\x81\xed\x47\xaf\x9f\xaf\xdd\x9d\x65\x38\x4c\xba\x03\ -\x76\x84\x00\xfb\xd9\xf9\xd3\xc7\x6f\x93\xfd\x8a\x4b\x04\x64\x0f\ -\x6d\xba\x50\xf9\x72\xad\xd5\x6a\x85\xbf\x65\x17\x0e\x90\x79\xab\ -\x83\x3f\xea\xdd\x6e\xf7\x67\x11\xc3\x61\xec\x3b\xa0\x01\x42\x8a\ -\xc2\x52\xba\xbe\xfe\xb5\xa8\xe1\xff\x03\xe0\x37\xff\xea\x99\x56\ -\xb6\x04\x03\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x03\x2a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdc\x49\x44\x41\x54\x78\x9c\xed\ -\x99\x4f\x48\x54\x51\x18\xc5\xcf\x79\xf3\xd2\xd1\x20\x49\x88\x16\ -\x41\x50\x10\xad\xaa\x45\xe1\x9b\x30\x21\x22\x08\x25\x1a\x67\x2c\ -\x23\x5a\x54\x10\x08\x41\xb4\x69\x17\xe4\xa2\x76\x11\xb4\x0f\xd2\ -\x45\x48\x58\x8e\xe6\x62\x08\x22\x6d\xa1\x8d\xcf\x72\x51\x04\x21\ -\x14\x44\xff\x16\x25\x16\x0a\x29\xf8\xde\xfd\x5a\x84\x31\x7f\x9e\ -\x0d\x82\xf7\xbe\xa0\xfb\x5b\x7e\x07\xe6\x9c\x39\xef\x3e\xee\x9d\ -\x3b\x80\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x96\xff\ -\x0d\xea\x36\xf0\x72\x61\x1f\xc0\x53\x00\x40\xf2\xdc\x44\x86\xbd\ -\xba\x3d\x57\x83\xd6\x02\x0e\xf6\x48\x72\xa1\x41\x16\x4a\x86\xc2\ -\x43\x7e\x07\x47\x75\xfa\xae\x06\x47\xeb\xa7\xaf\x87\x5b\x31\xa3\ -\x8c\xec\x7b\x20\xdb\xb5\xfa\xae\x02\x03\xaf\x80\x92\xa8\xb9\x9b\ -\xe0\x86\xf1\x34\xe7\x75\xfb\x57\x43\xef\x0a\x00\xb0\x35\x60\xe5\ -\x2a\x00\x10\x84\x32\x87\x6e\xd1\xee\x5f\x0d\xed\x01\xee\x77\x32\ -\x44\x92\x0d\x51\x9a\xb7\x47\x42\xdd\xfe\xd5\x30\xf2\x04\xfc\x36\ -\xce\x39\x09\xee\x88\xd2\xbc\x9c\x1a\x33\x91\x61\x25\x8c\x2d\xc1\ -\x42\x9a\x6f\x15\x79\x38\x42\x6a\xf6\x72\xe1\x0d\x53\x39\xca\x31\ -\xfa\x0e\x3e\xcf\xf0\x89\x90\x17\x2b\x15\x5e\x4e\xe5\xe4\xb4\xc9\ -\x2c\x7f\x9c\xe3\x30\x4d\xe5\xc2\x5e\x01\xcf\x94\xcf\x1d\xd2\x2b\ -\x64\x38\x69\x32\x4b\x2c\x05\x00\x80\x97\x53\xef\x00\x54\x9c\x07\ -\xdc\x04\xb7\x8c\xa7\xf9\xc5\x54\x8e\xd8\x0a\x00\x56\x3e\x23\x38\ -\x01\xeb\x0b\x9d\x5c\x88\xd2\xd6\x9a\x58\xf7\xe1\xe0\x1b\x6b\xa2\ -\xe6\xca\x95\x9f\x10\x31\xf2\x70\x62\x2d\x60\xaa\x8b\x4b\x81\xcb\ -\x4d\x51\x9a\x37\x28\xdf\x4d\x64\x88\xfd\x24\x36\x75\x8c\x33\x21\ -\xb8\x2b\x42\x6a\xf0\x06\xc3\x7b\xba\xfd\x63\x2f\x00\x00\x5e\x64\ -\xf9\x1a\x60\x7b\x85\x20\x3c\xa9\xdb\xfb\x9f\x28\x00\x00\x1c\x85\ -\xe9\x58\x7c\xe3\x30\x2d\xc7\x7b\x28\x9b\x15\x25\x5f\x3e\x17\xc1\ -\x33\xdd\xde\xb1\x17\xb0\x77\x58\xea\x11\xca\x30\x88\x6d\x25\x02\ -\xe5\xda\x64\x87\xd3\xac\xdb\x3f\xd6\x02\x4e\xf4\x4b\xc2\x0d\xa4\ -\x0f\x40\x53\xa9\x22\xb7\xfd\x76\xa7\xdb\x44\x86\x58\x0b\xf8\xe0\ -\xaa\x9b\x00\xd2\xc5\x33\x01\x1e\xd5\x6d\x74\x2e\x80\x8c\x3c\x24\ -\xad\x35\xf1\x1d\x85\x07\xe5\x12\x44\x6e\x95\x8d\x5f\xba\x09\xb6\ -\x98\xbc\x29\x8a\xa5\x80\xa6\x01\xc9\x90\x32\x50\xe6\xff\xc9\x09\ -\x98\x2a\x74\xf2\xb3\xc9\x2c\xc6\x0b\x48\x0d\x89\x27\x4a\x46\x01\ -\xd4\x15\x8d\xe7\xa1\x78\xc0\x3f\xce\x57\xa6\xf3\x24\x4c\x9a\xfd\ -\xbe\x0d\x96\x11\x02\xc5\x57\x64\x01\xc0\xb4\xdf\xc1\x82\xc9\x2c\ -\xcb\x44\x5e\x58\xea\x60\x7f\xbf\x34\x2a\x47\xf2\x00\xca\xce\xfe\ -\xec\xf2\xb3\x7c\x6c\x2a\x47\x39\x46\x76\x81\xd6\xbc\xd4\x2a\x57\ -\x86\x00\xec\x2c\x11\x44\xae\xfb\x59\xde\x31\x91\x61\x25\xf4\x17\ -\xd0\x2d\xce\xec\xa2\xea\x01\xd0\x52\x2a\xc8\x5d\x3f\xeb\x5c\xd5\ -\xee\x5f\x05\xed\x05\x78\xbb\x71\x65\xf9\xbf\xc1\x22\x9e\x36\x26\ -\x9d\xf3\xa6\xf6\xfa\xbf\xa1\x75\x17\x68\xcd\x4b\xed\xec\xa2\xfc\ -\x00\x90\x2c\x1a\xbf\x59\x57\xc3\xe6\xb1\xa3\x34\xf2\x7b\xbf\x1a\ -\x5a\x57\xc0\xd7\x8f\x50\x00\x96\x8a\x47\x24\xdb\xfe\x95\x2f\x0f\ -\x68\x2e\x60\xaa\x8b\x4b\x04\xcf\x02\x98\x01\x30\xad\xc8\x23\x13\ -\x19\xbe\xd7\xe9\x69\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\ -\x8b\xc5\x52\x8d\x5f\x44\x94\xcc\xbe\xc4\xf9\xa0\xab\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x9b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x08\x05\x51\x34\x0e\x66\xc3\x04\xae\xc0\x98\ -\x26\xac\xe6\x06\x22\xc4\xf2\xae\xfc\x09\xc9\x6b\x11\xa1\x64\xba\ -\xcc\x75\x99\xbf\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd2\x9f\x51\ -\x13\xd9\x99\x9d\xa2\x0e\xd8\x07\x09\x21\x90\x7b\x88\xd1\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf9\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xab\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xb7\x2a\xc0\x02\xb2\xb0\x80\ -\x02\xc4\x95\x15\x07\x9f\x21\xd9\x6e\xba\xbc\x8c\x0d\x31\x8f\x73\ -\x7d\xf7\x73\x5f\x43\x78\xec\xe2\xf4\x4f\x14\x40\x0b\x68\x0a\xa0\ -\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ -\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ -\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ -\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ -\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\ -\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x79\x01\x55\xd1\x04\x80\x1e\x3b\xba\xea\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x27\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd9\x49\x44\x41\x54\x58\x85\xe5\ -\x96\x31\x6b\x54\x41\x14\x85\xbf\x33\x59\x45\x09\x2a\x5a\xd8\x58\ -\x58\xd9\x58\x88\x4d\xd8\xa4\xb1\x4c\x40\x09\xb8\x89\xae\x95\x01\ -\x3b\x1b\x21\x3f\x40\x2c\x42\x7a\x11\x04\x4b\x21\xa9\x7c\xba\x89\ -\x10\x2c\xa2\x9d\x8d\x59\xd3\x48\x0a\x1b\x41\x04\x4d\x63\x67\x64\ -\x51\x92\xec\x1c\x8b\x65\xc1\x4a\xdf\xbc\x37\x28\xe8\xa9\xe7\x9e\ -\xfb\xdd\x3b\xf7\xce\x7b\xf0\xbf\x4b\xb9\x0d\x27\x0a\x9f\x88\x0d\ -\xbf\xb7\xf0\xeb\x56\x38\xfe\xbb\xf3\x8d\x9c\xc9\xcf\xad\x7b\x34\ -\xf6\xfc\x0c\x38\x26\x97\x8b\x09\xb9\x92\x9f\x2d\x7c\xf0\x70\xcf\ -\x2b\xc0\x78\x4a\x5c\x16\x80\xab\x85\x47\x8e\x1c\x88\x4b\xc0\x64\ -\xc9\xc2\x33\x02\xd8\xfa\xd8\x88\xf7\xb1\xae\x61\x23\x13\xff\x28\ -\x40\x73\x25\x2e\x18\xdd\x04\x83\x14\x11\x49\x4d\xa8\x05\xd0\xec\ -\x78\x1e\xe9\x36\x80\xad\x08\x69\xc9\x6b\x01\x34\x3b\xbe\x8e\x7c\ -\x97\x41\xd6\xa8\xc4\xca\x6b\x01\x8c\x3f\xf5\x34\xf2\x43\x18\x54\ -\xae\x0a\x95\x0f\x95\xfc\x0e\x8c\x75\x7c\xc1\xd1\x05\x30\x62\xec\ -\xaa\x95\x0f\x95\xd4\x81\xb1\x55\x9f\x0f\xf2\x1a\x70\x08\x6c\xa1\ -\xa4\x89\xaf\x05\xd0\x7c\xe2\x33\xc1\x5e\x07\x8e\x5a\x98\x0c\xc9\ -\x4b\x03\x4c\x14\x3e\x45\xf0\x0b\xe0\x24\xc2\xa9\xbb\xfe\x2b\x95\ -\x9a\x81\xd8\xf0\x27\x00\x63\x72\xb4\xfd\x67\x95\xbd\x82\x2d\x80\ -\xb2\x1f\x98\xec\x00\x61\x5f\x17\x81\x0f\x48\xa5\x63\xb2\x02\xbc\ -\x6a\x6b\x9b\xa8\x49\xe0\x33\x46\x56\x3e\x88\xd2\x46\xdd\x2b\x7a\ -\x17\xa5\x29\x60\x47\x46\xc6\x59\x20\x92\x4c\x36\x5b\x7a\x13\xad\ -\x69\xe0\xbb\x50\x16\x88\x64\x83\xcd\x59\xbd\x54\x50\x1b\xe8\x0f\ -\x20\x54\xeb\xb7\xae\x52\x05\x1b\x97\xb5\x86\x75\x03\x40\x83\x2e\ -\x54\x86\xa8\xdc\xc2\xee\xac\x96\x91\xe6\x87\x3e\xae\x08\x51\xeb\ -\x0e\xbb\x2d\xdd\xc3\x5e\x04\x50\x45\x88\xda\x43\xd4\x9d\x09\x77\ -\x6c\x3f\x00\x90\x9d\x0c\x51\x7f\x95\x24\x9f\xee\x87\x5b\xc8\x8f\ -\x90\x90\xd3\x36\x23\xcb\x2e\x3f\x6e\xab\xff\x75\x2f\xcc\x01\xcf\ -\x53\x97\x22\xdb\x8b\xf6\xb6\xad\xdd\x6f\xa3\x9a\x01\x36\xfe\x0a\ -\x00\xc0\xd6\x94\x7a\x61\x5f\x97\x90\x77\x6c\xbe\xe4\xf4\xfe\x77\ -\xf5\x03\x8b\xca\xad\x03\x49\x73\x42\xef\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xd8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8a\x49\x44\x41\x54\x58\x85\xe5\ -\x96\x3d\x72\xd3\x40\x18\x86\xdf\xd7\x49\x01\x9c\x83\x12\x5a\x4b\ -\x70\x05\x0a\xa2\x35\xc4\x21\x24\x71\xfe\x66\xc2\x01\x32\xc3\x19\ -\x28\xd3\x51\x24\x01\x3b\xe4\xd7\x48\xce\x0c\x67\x60\xc6\xd6\x21\ -\xa0\x83\x1b\x00\x05\xd6\x4b\xe1\x28\xc8\x2b\xc9\x92\x3c\x6a\x18\ -\xbe\x4a\x5a\x7d\xfb\x3e\x8f\x77\x25\xcf\x02\xff\x7b\x31\xbe\x78\ -\x74\xad\xc7\x51\xa4\xb7\x10\xee\x92\x7c\x3d\x34\x0c\xea\x04\xb9\ -\x81\x8c\xa4\x37\x24\x7e\x41\x7c\x35\x6c\xf1\x33\x00\x34\xe2\x86\ -\x28\xd2\x11\x80\x87\x20\xee\x0b\xea\xbb\xbe\xda\x75\xc1\x9d\x40\ -\x2b\x82\xfa\x93\x6c\x3c\x10\x75\x18\x3f\x6b\x24\xfa\xee\x24\xae\ -\x1b\xa2\xce\xea\x90\x70\x02\xad\x00\x3a\x4d\xb2\x48\xdc\x4b\x0b\ -\x90\xfb\x00\xa2\x3a\x25\x26\x73\xa7\xe1\x00\xa2\x48\xdc\x4f\x09\ -\x8c\x3c\xfa\x22\xd7\x32\x24\x4e\xe7\x91\x70\x7d\xb5\x45\x9d\xd9\ -\x70\x90\x9d\xd0\xb0\x9f\x12\x00\x80\xd0\xe3\x79\x86\xc4\x42\x55\ -\x89\x1b\x78\xea\x97\x83\xec\x8c\x3c\x7e\x48\xf6\x36\x60\x55\xe8\ -\xf1\x5c\xe2\x7a\xa6\xc4\x40\xcb\x85\xf0\x81\x96\x6f\xe0\x0b\x45\ -\x70\x20\xf1\x19\xda\xd5\xf4\xb5\x4a\xea\xc4\x92\x1c\x93\x5c\x1d\ -\x7a\xbc\xca\x85\x4b\x67\x16\x5c\x20\x37\xb2\xe0\x33\x05\x00\xc0\ -\x0d\xf4\x52\x50\xaf\x8c\x44\x33\xd0\x73\x42\xe7\x55\xe0\x85\x02\ -\xb3\x24\x04\xbe\x88\x5f\xa6\x79\xe1\xa5\x04\x00\xc0\x19\x68\x0d\ -\x52\x37\x4b\x62\x12\x92\x01\x17\x3b\xa3\x16\x4f\x8a\xb2\x4b\x09\ -\xe4\x49\x48\x88\x40\x80\xd3\x62\xa5\xe1\x95\x04\x12\x12\xbd\x19\ -\xf3\x2a\xc1\x2b\x0b\xdc\x4a\x00\x3d\x48\xf6\x5c\x09\xdc\x0c\x0d\ -\x7b\x55\xf2\x52\xff\x03\x25\xea\xa7\x24\xd9\x83\x02\x44\xe1\x47\ -\xd5\xb0\x4a\x02\xce\x40\x2d\x48\x17\xcc\x98\x47\xa0\x01\xea\xc2\ -\xf1\xf5\xac\x4a\x66\xe9\x2d\x70\x03\x19\x41\x97\x00\x16\x13\xc3\ -\x02\x09\x6b\x3b\xc6\x20\xdb\x23\x8f\x7e\x99\xdc\x52\x2b\x90\x07\ -\x17\xb8\x25\x61\x13\x40\x72\x4b\x16\x20\x5d\x3a\x03\xb5\x6a\x11\ -\x68\xfa\xf2\xf2\xe0\xa1\x61\x37\x34\xec\x09\xdc\x9a\x57\x62\xa6\ -\x40\xd3\x97\x47\xea\xca\x86\x93\xdc\x0e\x0d\xbb\xf1\x40\x68\xd8\ -\xcd\x91\xb8\x28\x92\xc8\x15\x98\x05\x1f\x7a\x7c\x6f\xf7\x87\x86\ -\x5d\x92\xdb\x96\xc4\x62\x91\x44\xe6\x4b\xd8\x1c\x68\x89\x52\xbf\ -\x2c\x3c\x59\xee\x40\x9b\x92\x8e\xad\xec\xdf\x04\xdb\x59\x07\xdd\ -\xd4\x0a\xe4\xc1\x01\xee\x14\xc1\x01\x60\xd2\xc3\x1d\x58\x2b\x21\ -\xe8\xd2\x0d\x64\xec\xfe\xa9\x15\x70\x02\x3d\x05\xf4\x31\x0b\x3e\ -\x32\x7c\x57\x04\xb7\xb2\xb6\x00\x1d\xa1\x60\x25\x6e\x1f\x36\x7d\ -\x3d\x21\x75\x5d\x07\x3c\x21\xb1\x0d\xe8\x30\x25\xd1\xa0\x19\x2e\ -\xf1\x13\x30\x75\x2a\xd6\x41\x06\x7c\x77\x5e\x38\x00\x8c\x0c\x8f\ -\x01\xee\xc2\xde\x8e\xb1\x0e\xe2\x9b\xbf\x67\xf5\xe9\x33\x60\x0c\ -\x3f\x9e\x17\x5e\x20\x31\x4e\x09\x40\xdc\x03\xf0\x05\xc0\x77\x88\ -\x9d\x3a\xe0\x53\x12\xe4\x06\x80\x6f\x10\xbe\x8a\xdc\xab\x2b\xfb\ -\xdf\xaf\x3f\xf0\x88\x83\xb8\x80\x8e\x5a\x2b\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xa4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x56\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\x58\xac\xfd\xdb\x60\xb1\xf6\x6f\x03\x25\x66\x30\x51\ -\xa2\x99\x1a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\ -\xea\x80\x01\x77\x00\x0b\xe5\x46\xfc\x77\xa0\xa4\x4a\x1e\x0e\x21\ -\xc0\x78\xe0\x44\x30\x73\x03\xb9\xba\x07\x3c\x04\x46\x1d\x30\xea\ -\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x70\x07\x00\x00\x30\ -\xcb\x0b\x07\x89\x28\x47\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x03\xf0\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa2\x49\x44\x41\x54\x78\x9c\xed\ -\x97\xbd\x6f\x1c\x45\x18\xc6\x9f\x67\x6e\xb1\x8c\x94\xd0\xc4\x29\ -\xa2\xfb\x8e\xb0\x30\x35\xa1\x87\x20\x2c\x94\x0a\xa7\x4c\x07\x51\ -\x04\x7f\x00\x10\x51\x44\x08\x21\x21\x3e\x6a\xa4\x28\x31\xe9\x10\ -\x05\x08\x68\x88\x25\x4b\xe0\x02\x3a\xa0\xc6\x91\x89\x76\x76\xf7\ -\x4e\x29\x9c\x8e\x02\x07\xdf\xcd\x43\x71\x32\xba\xdb\xdd\xf3\x7d\ -\xf8\xf6\x9c\x8f\xf9\x95\xf3\xee\x3b\xf3\xbc\xcf\xbe\xbb\x33\x03\ -\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x9e\ -\x2c\x78\x5c\x0b\x5b\x9b\xac\x81\xf8\x02\xa0\x01\x71\xb3\x51\xab\ -\x5c\x3b\x0e\x1d\xc7\x62\x40\x14\x25\x57\x04\x5c\x07\x60\xfe\x1f\ -\x14\xae\x34\x1a\xd5\xf5\x79\x6b\x31\xa3\x1f\x99\x2d\x51\x94\x5c\ -\x15\x70\x23\xb3\x36\x71\x33\x8a\x92\xf7\xe6\xad\x67\x6e\x1d\x20\ -\x89\x51\xd2\xfa\x0c\xc2\x3b\x23\x1e\xfd\xbc\x5e\xab\x5c\x25\xa9\ -\x79\xe8\x9a\x8b\x01\x92\x82\x28\x6a\xdf\x00\xf5\xc6\x58\x09\xc4\ -\xad\x7a\xb5\xf2\x16\xc9\x4e\xc1\xd2\x8a\x37\x20\x0c\xc3\x45\x32\ -\xf8\x1a\xc4\xeb\xfd\xe3\x02\x40\xc8\xa9\x27\xc1\x64\x84\x10\xdf\ -\xab\xdb\xb9\xd4\x6c\x36\xf7\x8a\xd4\x57\xe8\x3f\x60\x67\x67\xe7\ -\x19\x9a\xe0\x76\xa6\x78\x01\x04\xba\x00\x45\x40\x04\xba\x99\x7e\ -\x17\xd6\x68\x82\x1f\xb7\xb7\x77\x4f\x16\xa9\xb1\xb0\x0e\xd8\xb9\ -\x77\xef\xf4\x53\xff\x76\x36\x00\xbc\x30\x10\x90\x00\x9a\x6e\xaf\ -\x07\x52\x52\xe4\x4a\x60\x46\xd2\xef\xfb\x0b\xc1\x85\xe5\x33\x67\ -\x76\x8b\xd0\x59\x88\x01\x77\xef\xb6\x6b\xa5\xc0\x6d\x02\x78\x2e\ -\xb5\x9a\x00\x3a\x68\xd8\xff\x8d\x00\x65\xa0\x8c\xae\x3b\x9d\xc0\ -\xbc\xfa\x6c\xb9\x9c\xcc\x5a\xeb\xcc\x0d\xb0\xd6\x3e\x0f\x96\x36\ -\x01\x54\x52\x2b\x09\x82\x1b\x53\x94\x51\x4a\x1b\x81\xc4\x39\xb3\ -\xda\x6c\x96\xb7\x67\xa7\x76\xc6\xff\x80\x38\x8e\x5f\x04\x4b\xbf\ -\x20\x5d\x3c\xc6\x2f\xbe\xf7\x30\x1c\x30\xb8\x0d\x0a\xa8\xd2\xb8\ -\x5f\xe3\x38\x3e\x37\x0b\xad\x07\xcc\xcc\x80\x28\x6a\xbd\xe2\xc4\ -\x9f\x01\x9c\x4a\x85\x44\x8e\x5f\xfc\x01\xa4\x1c\xb2\xdf\xca\x29\ -\x27\x6e\x59\xdb\x3a\x3f\xb5\xd0\x14\x33\x31\xc0\xda\xe4\xa2\xa0\ -\xdb\x00\x4e\x0c\x04\x04\x01\x70\x43\x3f\xf9\x43\xe8\xe5\xd0\x41\ -\x99\xec\x13\xa0\x36\xac\x4d\xd6\xa6\x53\x3b\xc8\x91\x0d\xb0\x36\ -\xb9\x0c\xe2\x1b\x00\x0b\x03\x01\xd2\x61\x8a\x37\x9f\x81\x74\x20\ -\xd3\xf3\x2c\x80\xf8\xd6\xda\xf8\xcd\xa3\x4e\x7f\x24\x03\xac\x4d\ -\xde\x05\xb1\x9e\x9e\x87\x40\xde\x9b\x9b\x1e\xa9\xb7\x7b\x0c\x62\ -\x40\x7e\x69\x6d\x3c\xea\x68\x7d\x28\x53\xed\x02\x92\x68\xe3\xd6\ -\x27\x04\xf2\x2e\x2f\x0e\xd9\x4d\x7e\x56\x10\x39\x2f\x4d\xc0\xa7\ -\x8d\x5a\xe5\xfd\x69\xee\x0f\x13\x1b\x20\x29\x88\x92\xd6\x75\x08\ -\x97\x73\x84\x38\x16\x57\xfc\xc1\x1a\x64\x7e\xe7\xae\xd7\x6b\x95\ -\xb7\x49\x76\x27\x99\x6f\x22\x03\xc2\x30\x5c\x64\x29\xf8\x0a\xc2\ -\xc5\x8c\x30\xc1\x91\xc5\x16\xdf\xb7\x16\xc9\x1c\x13\x88\xef\xf6\ -\x1f\xec\x5d\x5a\x5e\x5e\x7e\x30\xee\x5c\x63\x1b\xb0\xbd\xbd\x7b\ -\x72\xf1\xe9\xbd\x1f\x00\xe4\x6c\x41\xca\xec\xdb\xc5\x23\x02\xcc\ -\xeb\x84\x9f\xf6\xfe\x59\x5c\x5b\x59\x39\xfd\xf7\x38\xb3\x8c\x65\ -\x40\xbb\xdd\x5e\xda\xef\xb8\x0d\x00\x03\x87\x10\xf5\xfa\x71\xa2\ -\x96\x9b\x35\x12\x4a\xe9\xeb\x83\x80\xdf\x16\x02\x73\xa1\x5c\x2e\ -\xdf\x1f\x95\x3f\xd2\x80\xbf\xda\xed\x6a\xd0\x71\x9b\x00\x56\x06\ -\x12\x09\x69\x82\xd3\x5d\x91\x90\x30\xca\xdc\x1f\xf4\x67\x50\x32\ -\xab\x95\x4a\xa5\x75\x68\xee\x61\xc1\x30\x6c\xaf\x18\xe3\x36\x05\ -\x54\x53\x69\xea\xb5\xfd\xc3\x04\x4d\xef\xb3\xe8\x1f\x42\xec\x3a\ -\x66\xf5\xec\xd9\xf2\x9d\xa1\x59\xc3\x02\x71\x1c\x9f\x73\xe2\x06\ -\x80\xa5\x54\x48\xc0\xc3\xf1\xe6\x73\x30\xc8\xd6\x74\x9f\x70\xaf\ -\xd5\xeb\xf5\x3f\x86\x25\x64\xb0\xb6\xf5\xb2\x13\xb7\xf0\x68\x15\ -\x0f\xe4\x9f\x41\x96\x04\xb3\x15\x86\xc9\x4b\x79\x09\x99\x0e\xb0\ -\x71\x7c\x0d\xe2\x87\x79\xb1\x47\x1c\x81\xfa\xa0\x51\xab\x7d\xd4\ -\x3f\x98\x29\x32\x8a\x92\x8e\x80\xd2\xfc\x74\xcd\x0f\x02\xdd\x7a\ -\xbd\x1a\xf4\x8f\xe5\x1d\x2b\x1f\x5b\xf2\x6a\xcb\x18\x60\xc8\x8f\ -\x73\x2e\x1e\x8f\x01\x74\xbd\xda\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ -\x1e\x8f\xc7\xe3\xf1\x78\x3c\x4f\x36\xff\x01\x8b\x04\x4e\x83\xb0\ -\x2f\x88\xa2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x2d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdf\x49\x44\x41\x54\x78\x9c\xed\ -\xd5\x3f\x88\x14\x67\x18\xc7\xf1\xef\x33\xb3\x77\x08\x7a\x68\x93\ -\x10\xdd\x99\x9b\x59\xb7\x10\xe2\x35\x91\x2b\xa2\x42\x8a\x20\x01\ -\x95\x24\x58\xd8\x48\x34\x29\x44\xb0\xb0\x08\x81\x60\x0a\x91\x40\ -\x0a\xc1\x10\xb0\x11\x42\x6c\xa2\x45\x24\x11\x84\xc4\xc4\x34\x16\ -\x11\x2e\x68\x63\x75\x58\x68\x74\xde\x99\x59\x41\xcf\x53\x38\x14\ -\x3d\x6f\xdd\x7d\x52\x48\xc2\xde\x70\xfe\xe1\x66\x76\x15\x7c\x3e\ -\xe5\xfb\xcc\xfb\xdb\xe7\x7d\x66\x5f\x06\x8c\x31\xc6\x18\x63\x8c\ -\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xba\x90\xb2\x01\x69\x9a\xbe\ -\xad\x78\xc7\x81\x3a\xca\x77\x51\x14\x7c\x2b\x22\x5a\x41\x6f\x0b\ -\x72\x2e\xdf\x86\x70\x18\x00\x65\x5f\x1c\x87\x67\xcb\xe4\x55\x30\ -\x80\xfc\x2f\x85\xf7\x7a\x96\x4e\xdc\xbf\x37\xb3\x7b\x6c\x6c\x6c\ -\xae\x6c\x76\x2f\x55\x95\x2c\x6b\x7d\xa9\x70\xa8\x67\x79\x66\xfa\ -\xf6\xad\x37\xc6\xc7\xc7\xdb\x8b\xcd\xf5\x4a\x37\x86\x14\x33\x76\ -\x2e\x1b\x59\xfe\x67\x92\x24\x2b\xca\x66\xff\xff\x1b\xaa\xb5\x2c\ -\xcb\x8f\x16\x0e\x0f\x15\xbc\xc0\xd2\x01\x59\x96\x8d\x75\x55\xce\ -\x01\x6f\x16\x4a\x97\xbb\x1d\x7f\xcb\xea\xd5\xab\xd2\x32\xf9\x53\ -\x53\x53\xcb\x1e\x3c\x7c\x74\x12\xd8\x5a\x28\x3d\x12\xbc\xed\x51\ -\x54\xff\xad\x4c\x7e\xe9\x01\x00\x38\xe7\x1a\x88\x7f\x16\x58\x53\ -\x28\xdd\x44\xfd\xad\x71\xbc\xea\xd2\x22\x73\x57\x22\xde\x19\x90\ -\x75\x85\xd2\x5d\xc1\xfb\x28\x8a\xea\x13\x8b\x6a\xb8\x47\xe9\x2b\ -\x00\x10\xc7\x71\xe2\x7b\x6c\x10\x38\x5f\x28\xbd\x85\x74\xce\x3b\ -\xd7\x2a\xbe\xbd\xe7\x4a\xd3\x74\x2d\x9e\x7f\x61\x81\xc3\x5f\xef\ -\xf8\xb2\xbe\x8a\xc3\x43\x45\x03\x00\x08\xc3\xf0\xee\xdc\xdc\xec\ -\x07\x28\x3f\x15\x4a\x4b\x11\xfd\x35\xc9\xb2\xbd\x2f\x9a\xe5\x5c\ -\xeb\x7d\xc5\x9b\x40\x19\x9d\x57\x50\x2e\xb6\x87\x6b\xef\x36\x83\ -\xe0\x4a\x15\x3d\x43\x45\x57\xa0\x97\xaa\x7a\x59\x96\x7f\xa3\xc8\ -\x57\x0b\x94\x0f\x47\xa3\xc1\x7e\x11\xe9\x3e\x6d\x7f\x9a\xb6\x76\ -\x29\x7a\x0c\x18\x9a\x57\x10\x4e\x0f\xf9\xde\x27\xf5\x7a\xfd\x41\ -\x95\xfd\x56\x3e\x80\xff\xa4\x69\xbe\x47\xe1\x28\xe0\xf7\xae\x2b\ -\xfa\x33\xdd\xce\xa7\x8d\x46\x63\x76\xde\xfa\x93\xcf\xdc\x01\x85\ -\xaf\x8b\x59\x0a\x47\xe2\xd1\xe0\x0b\x11\xe9\x54\xdd\x67\xdf\x06\ -\x00\xe0\x5c\xbe\x19\xe1\x17\x60\xe9\xfc\x8a\x4e\xd4\x7c\xef\xe3\ -\x20\x08\xee\x00\x4c\x4e\x4e\x0e\x8f\x8c\xac\xf8\x5e\xd1\xcf\x0a\ -\x11\x2a\xf0\x79\x14\x85\x47\xfa\xd5\x63\x5f\x07\x00\xe0\xdc\x8d\ -\x77\x90\xee\xef\xc0\xca\xde\x75\x85\xab\xbe\xe8\xe6\x76\xbb\x3d\ -\xed\xd7\x86\x4e\x81\x6c\x2a\x6c\x9d\x45\xd9\x11\xc7\xe1\xe9\x7e\ -\xf6\xd7\xf7\x01\x00\x5c\xbb\x76\x63\xd4\xaf\x75\xff\x00\xd6\xbe\ -\xe0\x96\x69\xed\xca\x87\x8d\x46\x70\xa1\x9f\x7d\x41\x85\x5f\x81\ -\x67\x69\x36\xeb\x59\xe7\xf1\xdc\x46\xe0\xdc\xf3\x9e\x55\xb8\xea\ -\x7b\xac\x1f\xc4\xe1\x61\x40\x03\x00\x68\x36\x9b\x33\xf7\xef\xcd\ -\x6c\x11\xf4\xc7\x67\x3c\xf6\xf7\x70\xcd\xdb\x10\x86\xe1\x3f\x83\ -\xea\x6b\x20\x57\xa0\x97\xaa\x8a\xcb\x5a\x07\x05\x0e\x16\x4a\xa7\ -\x7c\x8f\x5d\x61\x18\x3e\x1c\x74\x4f\x2f\x85\x4b\xf3\x1f\x5c\x9a\ -\x3f\x76\x69\xde\x4e\xd2\xfc\x90\xaa\x0e\xec\xdf\xf8\xca\x50\xd5\ -\x5a\x92\x24\x4b\x5e\x76\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ -\x31\xc6\x18\x63\xcc\x6b\xe2\x5f\xd1\x80\xf4\xd2\x90\x91\xe7\x38\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x2d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdf\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xb1\x6b\x14\x51\x10\x87\xbf\xdf\xbb\x43\x82\x82\x47\x2c\x6c\ -\xac\xed\x2d\xad\x2c\x24\xb7\x01\x25\xcd\xc5\x8d\xd5\x05\x64\x15\ -\xd3\x08\xf9\x03\xc4\x42\xec\x45\x10\x54\xe2\x21\x78\x95\xae\x77\ -\x4d\xb0\xf0\x36\x58\x58\x59\x8a\xad\x20\x16\xda\xd8\xe8\x05\x0c\ -\x41\x72\x6f\x2c\x56\xc5\x4a\xf7\xed\x3e\x22\xe8\x74\x03\x3b\x33\ -\xdf\xfc\x76\xe6\x31\xf0\xbf\x9b\x62\x27\x5c\x4c\xb3\x23\xde\xeb\ -\x2d\x60\xc5\xe8\xfe\xfc\x9f\xbe\x6f\xc7\x2c\x9e\xf4\xfb\x87\xfc\ -\x8e\x9e\x02\x9d\xaa\x31\x2e\x56\xf1\x34\x4d\x0f\xd8\xce\xdc\x18\ -\x38\x19\x12\x17\x05\x20\x4d\xd3\xd6\x27\xdf\x79\x08\x96\x84\xc6\ -\xc6\x00\xd0\x67\xdf\xb9\x2d\x38\x8f\x01\xe0\xf7\x15\x60\xe1\x5c\ -\x76\x1d\x58\xc3\x00\x27\x0f\xdf\x31\x2a\x5a\xa3\x21\x5c\xe8\x5d\ -\x5c\x97\x71\x15\x00\xc9\x63\x16\x54\x1c\x1a\x28\xd0\xed\x65\x7d\ -\x89\x9b\x3f\x8b\x13\x5e\xbc\x36\x40\xb2\x9c\x2d\x21\x3d\x28\xbd\ -\x7a\x9d\xd7\x06\x48\x7a\xd9\x29\x43\x8f\x81\x96\x61\x56\xb7\xf3\ -\x5a\x00\xdd\xf4\xd2\x09\x93\xdb\x04\xe6\x30\x33\xa1\xa0\x89\x6f\ -\x04\xd0\x5d\xbe\x7c\x1c\x6f\xcf\xc0\x0e\x1b\x58\xf9\xdf\x9b\x5b\ -\x25\x80\xd3\xe9\xda\x31\x98\x15\xc0\x51\xc0\x14\xb8\xeb\xbf\xb3\ -\x4a\x6b\xd8\xf2\x7b\xef\x7f\x71\xa3\x15\x87\x8a\x0a\x08\x5e\x43\ -\xe0\x0b\x13\x13\x60\xcf\xb5\xcf\x80\xbd\x53\x40\x4c\x54\x80\xe7\ -\xf9\xdd\x0f\xd0\x4e\x80\x8f\x80\x2c\x22\x44\xe5\x44\xc5\xe8\xde\ -\x1b\x9c\x16\x41\xdb\x2a\x0f\x99\x28\x10\x41\x49\x8a\x7c\xe3\x95\ -\xcc\x2f\x01\xbb\x80\xcc\x9a\x43\x04\x27\x98\x8c\x07\x2f\x84\xad\ -\x00\x33\x09\x81\x1a\x9d\x75\xb5\x3a\x98\x8c\x06\x9b\x98\x5d\x28\ -\x3d\x73\x34\xb8\x2d\x6b\x4b\x58\x8c\x07\x43\xd0\xfa\x8f\x3c\xa5\ -\x1a\xfb\x08\x00\x50\x8c\x36\x6e\x99\xec\x06\x80\x79\x9c\x6a\x28\ -\xd1\x78\x88\xb6\x9e\x0c\xae\x09\xee\x20\x30\xc3\x11\xa8\x44\x8c\ -\x55\xb2\x8e\x9b\x5e\x31\x78\x84\x80\xc0\xcd\x88\xb2\xcb\x79\x9e\ -\xcf\xe6\xdd\x74\x15\x34\x09\x8d\x8d\xf6\xa2\xe5\x79\xfe\x55\x07\ -\x77\x7b\xc0\xcb\xbf\x02\x00\x30\x19\x0e\xbf\x38\x67\x67\x91\xb6\ -\x81\x69\xcc\xdc\xff\xae\x7d\x03\x68\x47\x95\x0a\x88\x7f\x49\xe0\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x38\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xea\x49\x44\x41\x54\x78\x9c\xed\ -\x98\xc1\x6b\x13\x41\x18\xc5\xdf\xb7\x69\xda\xb4\x45\x2a\xa2\xf5\ -\x90\x4c\x36\x09\x04\x4f\xde\x8a\x15\xaa\x17\x11\x04\x2f\x2a\x82\ -\x22\x1e\xec\x41\x10\x04\xe9\xc5\x9b\xa0\x07\xbd\x89\x7f\x81\xa0\ -\x1e\xa4\x78\x11\x44\xa1\x08\xa2\xf5\x20\x1e\xbc\x29\x82\x2d\xb1\ -\xcd\x4e\x36\x11\xb4\x05\x4d\x15\x1b\x9a\x64\x3f\x4f\x62\x93\x6c\ -\x4d\x0b\x99\xd9\x1e\xbe\xdf\xf1\x7d\xb0\xef\xcd\xdb\x59\x66\x58\ -\x40\x10\x04\x41\x10\x04\x41\x10\x04\x41\x10\x04\xa1\xc7\x78\x9e\ -\x3f\xed\x69\x9f\x3d\xed\x73\xb1\x54\x9a\x8c\x3a\x4f\x3b\x64\xf2\ -\xe1\xc5\x62\x31\x41\x4e\xdf\x6a\x8b\xc8\x74\x24\x93\x49\xcd\x9a\ -\xf4\xdd\x0a\x8e\xc9\x87\x0f\x0f\x0f\xf7\x75\x88\xc4\xaf\xb4\xd6\ -\x39\x93\xbe\x5b\xc1\x68\x01\xa3\xa3\xa3\xbf\xc2\x74\x86\xb3\x30\ -\x37\xb7\xb4\xc3\xa4\xf7\x66\x31\x5a\x00\x00\xb8\xe9\x54\xe7\x2e\ -\x00\x90\x18\xac\xad\x30\xb3\x71\xff\x6e\x18\x0f\x40\x44\xcd\xfa\ -\x5a\x6d\x24\x6c\xa6\x4b\xe5\xa6\x69\xff\x6e\x58\x79\x03\xf9\x7c\ -\x7e\x25\xe6\x20\x1f\x36\xf3\x74\xe9\x8d\x8d\x0c\x1b\x61\x6d\x0b\ -\x2a\xa5\x3e\x13\xe8\x68\xe7\x84\x26\xbc\x92\x7f\xdb\x56\x8e\x76\ -\xac\x7e\x83\xae\x9b\x7a\x09\xc6\x95\x8e\x01\xe3\xaa\xe7\xf9\xe7\ -\x6d\x66\xf9\x8b\xd1\x7b\xc0\x46\x68\x5d\x7a\xc0\xa0\x0b\xed\x7a\ -\xe0\x60\x3c\xa7\xd4\x3b\x9b\x59\x22\x29\x00\x00\x3c\xed\x2f\x00\ -\xe8\xb8\x0f\x38\xc4\xc9\x74\x3a\xfd\xc5\x56\x8e\xc8\x0a\x00\x00\ -\x4f\xfb\x1c\xa6\xc7\x1c\x0c\x29\xa5\x56\xc3\x66\xbd\x26\xd2\x73\ -\x78\x79\xe9\x6b\x7f\x98\xde\x0c\xf0\x9b\x99\xad\xbc\x9c\x48\x77\ -\x00\x00\x54\x2a\x95\xdd\xf5\x46\xb0\x14\x32\xaa\x66\x5c\xb5\xd3\ -\xb4\x7f\xe4\x37\xb1\x64\x32\xb9\xec\x10\xef\x0f\x19\x8d\x68\x5d\ -\x7e\x64\xda\x3f\xf2\x02\x00\x20\x9d\x4e\x7f\x64\xe2\x93\xed\x3a\ -\x83\xcf\x9a\xf6\xde\x16\x05\x00\x00\x9a\xb1\xf9\x28\x6c\xb7\x45\ -\x01\x8b\x8b\x8b\x7b\xc9\x09\x66\x42\x46\x6f\x4d\x7b\x47\x5e\x40\ -\xa5\x52\x19\x8a\xc5\xe2\x4f\x01\x64\x5b\x06\x44\x37\x33\xae\x9a\ -\x30\xed\x1f\x69\x01\xcc\x1c\x6b\x34\x82\x69\x06\x0e\xb4\x8d\xee\ -\xba\x2a\x79\xc3\x46\x86\x48\x0b\xf0\x4a\xe5\x3b\x0c\x9c\x68\x11\ -\x19\xcf\xdd\x74\xea\x32\x11\x85\x5e\x92\x7a\x4d\x64\x05\x68\xed\ -\x4f\x11\x30\xd5\x22\x12\xde\xd7\x6a\x89\x33\x44\xd4\xb0\x95\x23\ -\x92\x8b\x90\xe7\xf9\xa7\x40\x78\xdc\xe6\x5f\x8e\x39\x38\xa8\x94\ -\xaa\xd8\xcc\x62\xbd\x80\xa2\xef\x8f\x53\x80\x59\x00\x83\xeb\xe4\ -\x9f\x81\x83\x43\x39\xa5\x3e\xd8\xce\x63\xf5\x13\xd0\x5a\xe7\xa8\ -\x89\x67\x68\x5d\x7c\x83\x10\x9c\x8e\x62\xf1\x80\xc5\x02\x7c\xdf\ -\xdf\xc5\x70\x66\x40\xd8\xd3\x32\x60\xbe\xe4\xba\xee\x0b\x5b\x39\ -\xda\x09\xfd\x63\xdb\x6b\x0a\x85\xc2\x40\x23\xc0\x13\x02\xf6\xb5\ -\x0c\x88\x6e\x65\x5c\x75\xcf\x46\x86\x8d\x30\xbe\x03\x98\xd9\x89\ -\xc7\x13\xf7\x09\x38\xdc\x36\x7a\xe8\xaa\xe4\x75\xd3\xfe\xdd\x30\ -\x5e\x80\xd6\xfe\x35\x10\xce\xb5\x88\x84\xd7\xf5\xb5\xda\x45\x5b\ -\x67\xfd\xff\x30\x7a\x0a\x14\x0a\x85\x81\x78\x7f\xe2\x07\x80\xc4\ -\x3f\x95\x3f\x11\x78\xc2\x75\xdd\xef\x26\xbd\x37\x8b\xd1\x1d\x50\ -\xad\x56\x03\x00\xf5\x75\xd2\x37\x0e\x9a\xc7\xb7\xcb\xe2\x01\xc3\ -\x05\x8c\x8d\x8d\xd5\xc1\x98\x04\xb0\x0c\x60\x9e\x03\x3a\x96\xcd\ -\x66\x3d\x93\x9e\x82\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\x08\ -\xdd\xf8\x03\x6a\x65\xdc\x45\x31\x50\xc4\x7d\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x9a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xc1\x09\x00\x20\x0c\x04\xc1\x20\x16\x66\xe1\x82\xad\x48\x52\ -\x48\xec\x40\x3d\xf1\xb9\xfb\x3c\x08\xcc\x37\x66\x24\x36\x3d\xc6\ -\xf4\x18\xb7\xfb\xa9\x2a\x0b\xd2\x9a\xb4\x1f\x2a\x2f\x47\x3f\x03\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfd\x33\xb2\ -\xec\xda\x4e\xfb\x16\xbe\x7b\x13\xbf\x30\xe2\x93\xe7\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\xf1\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\xa3\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xcd\x73\x5b\x67\x15\x87\x9f\xf3\xca\xed\x24\x84\x3a\x4d\xbf\ -\x99\xae\xd8\x36\x6d\xda\xea\xc3\x21\x94\x81\xc6\x49\x6d\x27\x8d\ -\xe3\xfe\x01\x85\x45\x07\xf9\x63\x6a\x4b\x86\x55\x59\xc0\x82\xc9\ -\x02\x86\x81\xda\x96\xa7\xb6\x6c\x66\xd8\xf5\x1f\xa0\x09\x89\xbf\ -\x42\x81\x36\xb1\x25\xab\x1f\x40\x37\x9d\x4e\x17\x1d\x86\x19\x4a\ -\x0b\x71\x9a\x26\x4a\xf0\x7b\x58\xc8\x37\x88\x2b\xd9\x7a\xaf\x74\ -\x6f\x6d\x06\x3f\xcb\xf7\x9e\x7b\xde\xf3\xfb\xe9\x9c\x57\xd2\x95\ -\x60\x97\x5d\x76\xf9\x7f\x46\xea\x2d\x1e\xfa\xf6\xcf\xf6\xdd\xb1\ -\x77\xcf\xf7\xc5\x68\x2f\xca\x1e\x90\x4b\x66\x9d\x9f\xac\xfc\x72\ -\xe4\xc3\x2f\xba\xc0\x66\xe8\xf8\x6e\xee\xab\x36\xc6\x4b\xa0\x47\ -\x10\x6e\x60\xe5\xec\xe7\x6d\xe6\xe7\xef\xbd\xf2\xe2\x67\xfe\xd8\ -\x1a\x03\x9e\x7a\xe1\xa7\x77\x95\xef\xd8\xfb\x3a\xf0\xa4\xef\xd2\ -\x15\x55\xdb\xbd\x3a\x33\xba\x1c\x55\xe1\x61\x90\x4a\x8f\xa5\xd4\ -\x98\x79\x60\x7f\xf5\xba\xc2\x3b\x6d\x77\xf2\xcd\xe5\x5c\x66\xad\ -\x7a\xdd\xf8\x13\x94\xef\xdc\xfb\x12\xb5\xe2\x01\xf6\x8b\x98\xb9\ -\x44\xff\xd8\xe1\x50\x2b\x0e\x91\xcd\xc4\x03\x08\x3c\x6e\x6f\xe9\ -\x0f\xfc\xeb\x35\x06\xa0\x9c\xde\x62\x8f\xf6\x9d\x6a\xc2\x56\xe2\ -\x3d\xd4\x9a\x3e\xff\x5a\xad\x01\xb0\xb7\xc1\x5e\xed\x22\x66\x2e\ -\x39\x38\xd1\x11\xb0\xc6\xc8\xe8\x18\xc8\x25\x1b\x89\x07\x40\x74\ -\x8f\x7f\xa9\x9e\x01\x6f\x38\xec\xd9\x8e\x32\xbf\x13\x4c\xe8\x18\ -\xc8\x25\x2d\xba\x40\x23\xf1\x00\x68\x8d\xb6\x1a\x03\x62\xe8\x19\ -\xe0\x8a\xc3\xde\xdb\x6e\x42\x30\xf1\xac\xc5\xe0\xc7\xfe\xc5\x1a\ -\x03\x96\xf3\xd9\xf7\x11\xba\x70\x37\x61\x5b\xc6\x61\x43\x7c\xe3\ -\xb6\xaf\xb0\x66\x0d\xdd\xcb\xf9\xec\xfb\xfe\x0b\xf5\x46\x80\xe2\ -\x74\x66\x65\xc3\x84\xb5\x7a\xd7\x7d\xec\x47\x99\x4b\xa5\xc7\x52\ -\x0e\xb1\xa1\x10\x1f\x1a\x4f\x6c\x88\xbf\xdb\x21\xfc\xaa\x35\x74\ -\x97\xa6\x32\x97\xeb\x5d\xac\xfb\x41\xc8\x23\x39\x38\xd1\x81\x32\ -\x0f\xb4\x3b\x6c\x74\x45\xac\x7d\xa6\x30\x3b\x5a\x70\x88\x6d\x9a\ -\xf8\xd0\x78\xc2\x58\x59\xc0\x5d\x7c\xd7\x66\xe2\xa1\x81\x01\xb0\ -\xb3\x4c\x08\x5b\x3c\x38\x18\x00\x90\xe8\x1f\x3b\x2c\x62\xe6\x70\ -\x34\xc1\x20\xc7\x57\xf2\x23\x45\x97\xdc\xae\x24\xfa\x27\xe3\x22\ -\x76\x01\x38\xe0\x10\x7e\xd5\x60\xba\x57\xf2\xc3\x97\x1a\x05\x3a\ -\x19\x50\x29\x60\xfb\x4c\x88\x4a\x3c\x6c\x72\x08\xd6\x63\x75\x66\ -\x74\xd9\x1a\xba\x71\x3c\x18\x2d\xba\xd0\x31\x90\x4b\xba\xe6\xdf\ -\x8c\xa0\xe2\xc5\x6a\x8f\xab\x78\x08\xd0\x01\x1e\xf1\xa1\x89\xaf\ -\x19\xcb\x1c\x70\x97\x43\xf8\x3f\x0d\xf2\x4c\xb3\x9d\x10\x50\xfc\ -\x67\x62\xb5\xbb\x30\x9b\x7d\x33\xc8\x1e\xce\x1d\xe0\x51\x9a\xca\ -\x5c\xb6\x86\x2e\xe0\xaa\x43\xf8\xdd\x16\x9d\x8f\x0f\x8d\x27\x82\ -\xee\xf3\x45\x88\x87\x26\x3a\xc0\x23\x68\x27\x58\xa3\xc7\x4b\x53\ -\xd9\x55\x97\xdc\xc9\xc1\x89\x27\x51\x16\x89\x58\x3c\x34\xd1\x01\ -\x1e\xa5\xa9\xcc\x65\x83\xe9\xc6\xb1\x13\x8c\x95\x05\x97\x4e\x08\ -\x2a\x1e\x91\x9e\x66\xc5\x43\x0b\x1d\xe0\xd1\x31\x30\x79\xc4\x62\ -\x2f\x10\x42\x27\x34\x23\xbe\x38\x3d\xe2\xf2\xe5\x6d\x53\x9a\xee\ -\x00\x8f\x95\xfc\xf0\x25\xb1\xda\x83\x7b\x27\xcc\x27\xfa\x27\xe3\ -\xfe\x0b\x1b\xe2\x9d\x67\x5e\xd5\x9e\x68\x55\x3c\x84\x60\x00\x40\ -\x61\x36\xfb\xe6\x86\x09\x35\xcf\xdc\xea\x70\x40\xc4\x2e\x54\x9b\ -\x90\x4a\xbf\xfc\xc4\x86\xf8\x7b\x1c\xee\xbf\xa6\x6a\x4f\xac\xce\ -\x8c\xfe\xa1\xd9\x7a\xab\x69\x79\x04\xaa\x49\xa5\xc7\xbf\xae\x46\ -\x2e\x00\x5f\x76\x08\xff\x87\xaa\x39\x6e\xf4\x96\x55\x13\x5b\xc4\ -\x5d\x7c\x4f\x58\xe2\x21\x64\x03\x20\x98\x09\x82\xae\x69\xa5\x04\ -\x97\x4f\x97\xa1\x8b\xaf\xd4\x10\x01\xc9\xc1\xdc\x53\xa8\x9e\xc7\ -\xad\x13\x5c\xb8\x66\x0d\x27\x4a\x53\x99\xdf\x87\x94\xef\x36\x91\ -\x18\x00\xa1\x9a\x10\x99\x78\x08\xe9\x10\xac\x47\x71\x7a\xe4\x0d\ -\x55\x7b\x02\xb7\x83\x71\x33\xae\x09\xf6\x64\x54\xe2\x21\xc2\x0e\ -\xf0\x48\xf4\x8f\x7d\x43\xc4\x9c\x07\xf6\x05\xbc\xf5\x9a\x60\x4f\ -\x16\xf2\xa3\xbf\x8b\xa2\x2e\x8f\xc8\x0d\x80\x8a\x09\xc6\x98\x39\ -\xd5\x86\x8f\xdc\x3d\x6e\x08\xb6\x3b\x6a\xf1\x10\xe1\x08\x54\xa3\ -\x31\xd6\x54\xe5\xa6\xf3\x0d\xc2\x4d\xac\xba\x7c\xed\x6e\x99\xc8\ -\x0d\x88\x0f\x8d\x1d\x32\xd6\x2c\x81\xba\x3c\xbd\xad\xa0\xb4\xab\ -\x89\x2d\xa6\xd2\x2f\x3f\x11\x61\x69\x40\xc4\x23\xf0\x1f\xf1\xdc\ -\xdb\x64\x8a\x4f\xc5\xae\x1f\x2b\xcc\x7e\xef\xed\x30\xeb\xaa\x26\ -\x32\x03\x36\xc4\x2f\x02\xf7\xb5\x98\xea\x53\x03\x9d\x2b\xf9\xcc\ -\x3b\x61\xd4\xe5\x27\x12\x03\x12\xfd\xb9\xc7\x44\x74\x89\xd6\xc5\ -\x7b\x44\x66\x42\xe8\x67\x40\x10\xf1\x0a\x65\x85\xb2\x43\xda\x7b\ -\x2c\x2c\x76\x0c\x4c\x3c\xde\x7a\x85\xff\x4d\xa8\x06\x04\x7c\xe5\ -\xaf\x8b\x48\x8f\xc1\x76\x01\x9f\x3b\xc4\xdf\x1b\x85\x09\xa1\x8d\ -\x40\x72\x70\xfc\x51\x54\x2e\xe2\x28\x5e\x55\x9f\x5d\x9d\xc9\x5e\ -\x04\x48\xa5\x27\xbe\xa5\x86\x73\xc0\x97\x1c\xee\xfd\xc4\x1a\xdb\ -\x59\x9a\x1a\x7d\xb7\x95\x7a\x3d\x42\x31\xa0\x15\xf1\x1e\xdb\x65\ -\x42\xcb\x23\x10\x54\xbc\x15\x39\xe5\x17\x0f\x50\x98\xcd\xbc\x8e\ -\xc8\xb3\x38\x8e\x83\xb1\x66\x29\x3e\x34\x76\x28\x68\xbd\x7e\x5a\ -\x32\x20\x39\x38\xfe\x28\x88\xf3\xcc\x5b\x91\x53\xa5\xe9\x91\xa5\ -\xcd\x02\x8a\xd3\x23\xbf\x0d\x68\xc2\x62\xab\x26\x34\x3d\x02\xb7\ -\xc5\x2b\xf7\x3b\x84\x5f\x17\xb4\xb7\x90\xcf\x2e\xba\xe5\xce\x3d\ -\x8d\xea\x39\x1a\xff\x5d\x07\xe0\xef\xaa\xd2\xb9\x3a\x33\xf2\x47\ -\x97\xdc\x7e\x9a\xea\x80\x54\x7a\xf2\x60\x00\xf1\x37\x82\x88\x87\ -\xdb\x9d\x70\x12\xb8\xee\x10\x7e\x9f\x88\x2e\x25\xfa\x73\x8f\xb9\ -\xe6\xaf\x26\x70\x07\xa4\xd2\x93\x07\x35\x66\x2f\x06\x10\x7f\x2a\ -\x88\xf8\x6a\x12\xfd\xe3\x47\x45\xe4\x2c\x11\x76\x42\x20\x03\x52\ -\xe9\xc9\x83\x18\xbb\xa4\xf0\x80\x43\x78\x4b\xe2\x3d\x82\x9a\x80\ -\xe8\xd1\xe2\x74\xf6\x4f\xae\xf9\x9d\x0d\x08\x2a\x1e\x4b\x6f\x71\ -\x36\xb3\xe0\x9a\x7f\x2b\xe2\x83\xb9\x4e\xa3\xfa\x1a\x11\x98\xe0\ -\x64\xc0\xe1\x81\x89\x47\x2c\x5c\xdc\x0e\xf1\x1e\x51\x99\xd0\xf0\ -\x10\x0c\x2c\x1e\x73\x3a\x6c\xf1\x00\xa5\xe9\x91\x25\x41\x7b\x71\ -\x3c\x18\x41\x96\x2a\xef\x54\x5b\xb3\x65\x07\x34\x25\x3e\x3f\x3c\ -\xef\x10\xdb\x34\xa9\x81\xf1\x63\x8a\xbc\x06\xd4\xfc\xeb\xb3\x06\ -\xe1\x63\xd0\xce\xad\x3a\x61\xd3\x0e\x38\x3c\x30\xf1\xc8\x3a\x38\ -\xcf\xbc\x2a\x7d\x51\x8b\x07\x28\xe4\xb3\x8b\x82\x9e\x02\x6e\x34\ -\x0c\x56\xee\x07\x59\xaa\xbc\x6d\xd7\xa7\x6e\x07\x78\xe2\x81\x07\ -\x1d\x6a\x2a\xab\x72\x7a\x75\x26\x33\xe7\x10\x1b\x1a\x41\x3b\x41\ -\xd6\xcd\xd1\xc2\xec\xf0\x9f\x6b\x2f\xf9\x38\x32\xf8\x8b\x87\x6f\ -\x69\x5b\x11\x78\xc8\xa1\x8e\x6d\x11\xef\x91\x4c\x4f\x1c\xc7\xf0\ -\x6b\x1c\x4c\x10\xf8\x1b\xb1\x58\xb2\xf0\xca\x8b\x1f\x55\xaf\xd7\ -\x8c\xc0\x2d\xdb\xf6\x43\xfe\x07\xc4\x03\x14\x67\x33\x0b\x58\x7a\ -\x71\x18\x07\x85\x07\xb0\xeb\x3f\xf2\xaf\xd7\x9e\x01\xc2\xd3\x0e\ -\x7b\x97\xad\x48\xdf\x76\x8a\xf7\xa8\xbc\xe3\x98\xd3\xb8\x98\xa0\ -\x1c\xf5\xaf\xd5\x18\xa0\xb0\xde\x20\x4f\xd9\x8a\xf4\x95\xa6\x47\ -\x2e\xb8\x97\x19\x2d\x95\xc3\xd7\xc9\x84\x1a\x6d\x35\x06\x08\x6c\ -\xf5\xaa\x96\x05\x7d\x6e\x27\x89\xf7\x28\xe6\x87\xe7\x55\xe9\x63\ -\x0b\x13\x44\x38\xef\x5f\xab\x31\xc0\xb4\x99\x33\xc0\x07\x75\xee\ -\x2f\x0b\xfa\x5c\x21\x9f\xad\x49\xb2\x53\x58\x9d\xc9\xcc\x6d\x61\ -\xc2\x87\xff\x2a\x73\xc6\xbf\x18\xf3\x2f\xfc\xa5\x70\xee\xfa\x57\ -\x12\xc7\x5e\x15\x89\xed\x43\x79\x50\x84\x9b\x28\x8b\x8a\xf9\x4e\ -\x71\x26\xba\x5f\x69\xc3\xe2\xaf\xab\xbf\xf9\xe0\xe1\x78\xd7\x59\ -\xc4\x3c\x04\x1c\x40\xf9\x44\x45\x5f\xb5\x37\xe5\xf9\xb7\x7e\x95\ -\xf9\x78\xbb\xeb\xdb\x65\x97\x5d\x76\x16\xff\x06\x5e\xec\x1f\xa0\ -\xf6\x5e\x26\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x02\x06\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb8\x49\x44\x41\x54\x58\x85\xed\ -\x97\xcf\x4a\x1b\x51\x14\x87\xbf\x33\x49\x56\x25\x42\x2b\xa9\xe0\ -\x6b\x34\xff\x8a\xc5\x07\x68\x4a\x5f\xa2\xc1\x94\x6a\x46\x29\x25\ -\xf6\x11\x1a\xa1\x25\x99\xd8\xa2\x45\x17\x92\x95\x0f\x10\x70\xd3\ -\x2e\x04\xab\x69\x93\xd7\x10\x34\x28\x94\x2c\x63\x72\x5c\xcc\x64\ -\x0c\xc6\x8e\x98\x4c\x62\x69\xf3\x5b\xde\x7b\xb8\xdf\x37\xf7\x5c\ -\x86\x7b\xe1\x7f\x8f\x5c\x1f\x88\xbe\x2e\xcd\xa1\xba\x8a\x90\x44\ -\x89\xf8\x44\x69\xa0\x1c\x21\x92\xaf\x6d\x64\x0f\xfe\x28\x10\xcb\ -\x14\xdf\x29\xb2\x76\x93\x98\x4f\xe9\xa8\x92\xab\x7f\x35\x3f\xf6\ -\x09\x3c\x59\x28\x3c\x13\x31\xf6\x81\xdf\x88\x9a\xa1\x56\xbb\x72\ -\xb8\xfd\xf6\xdc\x0f\xea\xd3\x57\x9f\x1e\xb5\x42\x81\x14\x2a\x16\ -\x30\x85\xc8\x7c\x77\x27\x82\xae\x89\x18\x39\x40\x10\x35\x6b\x1b\ -\xcb\x65\x3f\xc0\xdd\x38\x1f\x52\x8e\x66\x2c\x01\x76\x50\x5d\x05\ -\x5e\x02\x18\x6e\x95\x90\x04\x08\xb5\xda\x15\x3f\xe1\xbd\x31\x82\ -\x46\xc5\x46\x91\x70\xc7\xdc\x59\xe7\xc0\xf9\xb5\xed\x37\xe5\xe7\ -\xe7\xa5\x33\x1b\xc5\xe3\x7e\x81\x7b\xca\x44\x60\x22\x70\xef\x02\ -\xc1\xdb\x0a\x62\x99\xd2\x1b\x45\x3f\x00\xe1\x3b\xae\xdd\x14\xe4\ -\xfd\xaf\xcd\xec\x17\xaf\x22\xcf\x1d\x48\xa4\x0b\x33\x8a\x96\x06\ -\x80\x03\x84\x15\xb5\x12\xe9\xc2\xcc\xc0\x02\xe3\x88\xa7\x40\x75\ -\x6b\xe5\x44\x90\x2c\xd0\x1c\x60\xed\xa6\x20\x66\x75\x6b\xe5\xc4\ -\xab\xe8\xd6\x33\xe0\xf4\xd0\xb3\x8f\xc3\xe4\xef\x6e\xc1\x44\x60\ -\x22\x30\x5e\x01\xa1\x01\xf6\x05\x72\x54\xb0\xf8\xe2\xfa\xb4\x8d\ -\xe2\xb4\x5f\x40\x39\x02\x68\x85\x02\xa9\x51\x09\x74\x2e\x3a\x29\ -\x1b\x45\xb5\x3b\x76\xf5\x23\x12\xc9\xa3\xfa\x02\x15\x2b\x9a\xb1\ -\xc4\x08\x1a\x95\xee\x1d\x6e\xd8\xc4\x17\xd7\xa7\x1d\x78\x11\xe8\ -\x20\x92\x77\xb1\xbd\x85\xce\xc3\x24\xcf\xe8\xce\x46\xdf\xc3\x24\ -\xd0\x3b\x7b\x5c\xdf\xfb\x31\x1b\x7b\xfe\x0d\x88\x08\x3c\x04\x1e\ -\xf8\x41\x75\x7a\xfe\x1d\x91\x74\x7d\xd3\xdc\xf5\x63\xcd\x7f\x27\ -\x97\x00\x43\x86\x87\x3f\x9c\xa0\xff\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x37\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe9\x49\x44\x41\x54\x58\x85\xed\ -\x94\x31\x68\x13\x61\x14\xc7\x7f\xef\x8e\x50\x8d\x20\x75\x50\x8a\ -\x93\x29\xe2\x24\xa2\xa5\x71\x11\xdc\x44\x91\x8e\x8a\x53\x41\x87\ -\xda\xa0\x49\x8a\x83\x93\x08\xea\xea\x60\x4d\x5b\x6b\xeb\xe0\xa0\ -\xa0\x58\xc4\x41\x07\xa5\x53\x71\x50\xa8\x8d\x5a\xc4\xc9\xc1\x45\ -\xa1\x88\x56\x45\x4b\xb5\xb9\xfb\x3b\x24\x67\xcf\x60\x9b\xbb\x58\ -\xec\x72\x3f\x38\xf8\x8e\x7b\xef\xff\xfe\xef\xde\xf7\x7d\x90\x90\ -\x90\x90\xb0\xca\x58\xb0\xe8\x3c\x5e\x9a\xc5\x68\xfd\x2f\x55\xc5\ -\xe7\x67\xa3\xc5\x0d\x00\x4e\xc8\x8a\xb3\x64\xc2\x4a\x13\xaa\xf5\ -\x7b\x91\xaa\x54\x32\x06\x4f\x83\x77\x21\x1f\xf0\x56\xe2\x11\xf8\ -\xa1\xf2\x4f\x52\x95\x4a\x66\xd1\x4b\x88\x1d\xdd\x17\xd7\xb5\xa4\ -\x5b\xee\x0a\xf6\x23\xc0\xe4\x83\xe9\x5f\x9a\x15\x32\xc3\x82\x46\ -\x1f\xfe\x9c\xfb\x71\x68\xfa\xc6\xe9\xef\xc1\x77\x37\x1c\x3c\x33\ -\x3d\xbe\xd0\xda\xbe\xfb\x4e\x6a\x6d\x7a\x1b\xc6\xf6\xaa\xc1\x3f\ -\x3c\xc6\x2b\x6e\x2c\x16\x97\xdd\x9e\x9b\xfd\x78\xe4\xd5\xad\x33\ -\xf3\xe1\x18\xb7\x3e\xe9\xc3\xeb\x09\x6f\x4f\xfb\xb1\x7b\x5f\xd2\ -\xdf\x36\x82\x65\x01\x93\x09\x8b\x69\x44\x60\x56\x1b\xb1\x19\xc3\ -\x99\x4f\x6d\x3d\x13\x63\xf9\x4a\x7d\xdc\x32\xaa\xb2\x6c\xae\x74\ -\x5e\xb2\xb3\xb5\x48\x1f\x11\x6d\x1c\x86\xa1\x6a\x71\xc1\x85\xa9\ -\x91\xc2\xb9\xa5\x46\xd9\xb0\xad\x6c\xef\x40\x9f\x50\x3f\x80\xaa\ -\x03\xf5\x1b\xa4\x38\x81\xae\x44\xdf\xd4\x68\xb1\xb4\xbc\xd7\x08\ -\x74\xe6\x2e\x77\x23\xbb\x0e\xb8\x02\x19\x7f\x37\x21\xe1\x58\x75\ -\x56\x9e\x61\x47\x27\x47\x0a\x37\x1b\x69\x47\x1e\x6c\x47\x6e\xb0\ -\xcb\x91\x3f\x06\xac\x01\x44\xbd\x09\x99\x83\xc9\x80\x79\xdf\x9c\ -\xc3\xe5\xab\xf9\x07\x51\x74\x63\xed\xac\x6c\x6f\xff\x5e\xe1\xdc\ -\x07\xd6\xd7\x99\x08\x7e\xfb\x57\xdf\xa1\xab\x3c\x5c\x7c\x1c\x55\ -\x33\xf6\x19\xcb\xf6\x5c\xda\x89\xe3\x3e\x12\x6c\x02\x54\xdb\xed\ -\x00\x33\xe6\x7b\x07\x26\xaf\x9d\x7a\x11\x47\xaf\xa9\x43\xde\x71\ -\x62\x68\xab\x79\xde\xb8\xc1\x16\x00\xc1\x5b\xb9\xee\xbe\xf2\x95\ -\x93\x6f\xe2\x6a\x35\x7d\xcb\xec\xca\x0f\x6c\x76\x17\xf4\x4e\xf0\ -\xd2\x4f\xd9\xc1\xe7\x83\x85\xf7\xcd\x6a\x25\x24\x24\x24\xac\x2a\ -\xbf\x00\xaf\x38\xac\x82\xe2\x51\x10\x13\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x04\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\xd1\x0d\x83\x50\x0c\xc5\xd0\x14\x75\x8d\x0a\xf6\x9f\x0a\xc4\ -\x20\x74\x8c\x83\xf4\xec\x05\x62\x59\xf7\x2f\x33\x90\xf3\xba\x9f\ -\xf3\xba\x1f\xe9\xb0\xc9\xe3\x6f\xa0\x00\x5a\x40\x53\x00\x2d\xa0\ -\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ -\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\ -\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\xe5\ -\x03\x7c\xe4\x71\xfd\x1a\x9f\x69\x01\xf3\xd5\x02\x33\x33\xc7\xfe\ -\x63\x4b\x5c\x7e\x01\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\ -\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\ -\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\ -\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x2c\x1f\xe0\x0f\xc7\ -\xa8\x0b\xc6\x03\x24\x5a\xc7\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x4c\x76\xb2\x8f\x85\xfd\x14\ -\x72\x20\x33\x09\x96\xad\x02\x00\x00\x00\x00\x00\x00\xe0\x7f\x63\ -\xed\x73\xd3\x11\x49\x33\x1d\x90\x66\x40\x3a\x00\x00\x00\x00\x00\ -\x00\x00\x00\xde\x6b\x42\xab\x02\x34\xd3\x03\x1d\x60\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x1a\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x4f\x6c\x14\x65\x18\xc7\xf1\xef\x33\xdb\xad\x44\xc4\x34\x01\ -\xa3\x04\x82\x4a\x0f\xc4\x02\x51\xeb\x09\x88\x64\x85\xdd\x25\xa4\ -\xa9\xc8\x6e\x97\x10\x62\xb1\xa6\xdb\x46\x4c\x3c\x18\x13\x6f\xa6\ -\xf1\x46\x82\x91\x70\x69\x42\xff\x24\x04\x4d\x54\xa6\x7f\x38\x28\ -\xe8\x96\x26\x94\xa4\x88\x46\xca\xad\x1e\x80\x9a\x08\x21\x46\x10\ -\xc1\x90\xd0\x52\xf6\x7d\xbc\x70\xd8\x0e\x45\xb0\x33\xbb\x84\xf0\ -\x7c\x8e\xf3\xcc\xfc\xf6\xf7\xbe\xb3\xb3\xb3\x60\x8c\x31\xc6\x18\ -\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x98\xc7\x85\x84\x0d\xd8\x98\ -\x7b\xb7\xce\x2b\xc6\x0e\x8a\xb0\x04\xf8\xbc\xd0\xdf\xf3\x19\xa0\ -\xe1\xab\xcd\x2e\x95\x69\xdb\x2a\xa2\x7b\x00\x10\xf9\xa0\xd0\xd7\ -\x7d\x34\x4c\x5e\xe8\x0d\x48\x65\xf3\x23\xc0\xfa\x92\xc8\x2f\x6a\ -\xbc\x6b\x79\xdf\xf7\x6f\x85\xcd\x0e\x90\x54\x53\xdb\xc7\xa8\xee\ -\x2e\x39\x76\xfd\xea\x42\xef\x99\xd3\x5d\x5d\xd3\x73\x0d\xf5\x42\ -\xd7\x52\x0d\x64\x68\xf3\xdf\xae\xe6\xfb\xc4\x5b\x2d\x35\xa1\xb3\ -\xef\x48\x24\x3a\xaa\x52\xd9\x7c\x67\x60\xf1\x80\x84\xbe\x81\xa1\ -\x37\x40\x94\x5d\xc0\x9f\x33\x8e\xa1\x6f\xc4\x63\xf1\xd1\x0d\x99\ -\xd6\xe7\xc3\xe6\x27\x72\xef\x3f\x15\x5f\x74\xe9\x30\xf0\x5e\x60\ -\x34\x25\xb8\xb7\xc3\xdc\x7d\x88\xe0\x11\x00\x48\xe7\xf2\x2f\x3a\ -\xc7\x51\x81\x15\x81\xf0\x3f\x44\xbd\x86\x1f\x06\xba\xc6\xe6\x92\ -\xbb\x29\xd3\xbe\xb8\x28\xee\x5b\x81\xfa\xc0\xe8\x2a\xaa\x6f\x0e\ -\x0d\xf4\x8e\xce\xb9\xf4\x1d\xe1\x1f\x01\xa0\xe0\xf7\xfc\x16\xf3\ -\x74\x2d\x70\xa2\xf4\xb8\xc2\x73\x4e\xdc\x89\x64\xa6\xb5\xe1\xff\ -\x66\x6e\xca\xb6\xad\x74\xe2\x4e\xcd\xb2\xf8\x09\xe7\x64\x4d\x14\ -\x8b\x07\x88\x45\x11\x02\x70\x7e\xfc\xcc\xcd\x15\x2f\xac\xfb\xca\ -\xc5\x6f\xd7\x02\xab\x4b\x46\xd5\x22\xb2\x7d\x79\x5d\xfd\xe5\x89\ -\x5f\xc7\x7e\x79\x90\xac\xf4\xd6\xfc\x06\x15\x0a\xc0\xb3\x33\x27\ -\xfa\x53\x95\xe7\x36\x16\xfa\x7b\x2f\x44\xd5\x3b\xb2\x0d\x00\x38\ -\x77\xee\xe7\x62\xf3\xb6\xc6\xc1\x0b\x97\x6f\x54\x03\xaf\x97\x8c\ -\x44\xa0\x61\x79\x5d\xfd\xfc\xe6\x6d\x8d\xc3\x23\x23\x23\xf7\x7c\ -\x4d\x26\x9b\xf2\x3b\x11\x0e\x01\x4f\xce\x18\x08\x83\x4f\x4c\xc5\ -\xb6\x1c\x39\xdc\x7b\x3d\xca\xce\x91\xfc\x06\xcc\x26\x9d\xc9\xb7\ -\xab\xd0\xc9\xdd\x9b\x7c\x68\x7a\xc1\xed\x77\x8e\x1f\x38\x30\x19\ -\xec\x92\xca\xb6\x7e\x02\xf2\xe9\xdd\x69\xba\xaf\xc6\xfb\xe7\x23\ -\xdf\xf7\x8b\x51\xf7\x2c\xdb\x06\x00\xa4\x9b\xda\x36\xab\xaa\x0f\ -\xcc\x0f\x8c\x46\x9d\xbb\xb5\x65\x78\xf0\xe0\x5f\x00\xb9\x5c\xae\ -\xfa\x9a\x7b\x7a\x3f\x48\x4b\xe0\x3c\x05\xf9\x70\xa8\xbf\x7b\x5f\ -\xb9\x3a\x96\x75\x03\x00\x92\xd9\xd6\x57\x05\xf9\x0e\x58\x3c\x73\ -\xa2\x67\x8b\xc5\xd8\x66\x2f\xce\x15\xcf\xb9\x3e\x85\x64\xe0\xd2\ -\x49\x54\x76\x0c\x0d\x74\x0f\x96\xb3\x5f\xd9\x37\x00\x20\x99\x6b\ -\x5f\x26\xce\x1d\x01\x56\x3e\xd0\x05\xca\x15\x85\xc6\x63\x03\x3d\ -\xa7\xca\xdb\x2c\xa2\xd7\xe0\xfd\x1c\xf3\xbb\x7e\x57\xcf\x5b\x07\ -\x0c\xdf\xff\x6c\x3d\xeb\xc5\x74\x4d\x25\x16\x0f\x11\xbf\x05\xfe\ -\xcb\xc4\xf8\xe9\xa9\xd7\x56\xd5\x7e\x3d\xa9\xf3\x96\x01\xaf\xdc\ -\xe3\xb4\x93\xd3\xd5\xb1\xd4\xf0\x37\x3d\x17\x2b\xd5\xab\x22\x8f\ -\x40\xf0\x33\xd3\x4d\xf9\x0e\x55\x3a\x02\x4d\xfa\x6e\xc8\x82\x9d\ -\x3f\xfa\x7b\x6f\x56\xb2\x4c\xc5\xbe\x01\xa5\xce\x8f\x8f\x1d\xaf\ -\x7d\xa9\x7e\x29\xc2\xcb\x80\x43\x75\xcf\xda\x55\x4b\x77\x7d\xd9\ -\xb9\x3b\xd4\xff\xfa\x47\x4e\x22\xd1\x51\x95\x68\x69\x99\xf7\xb0\ -\x7b\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\x8f\ -\x89\x7f\x01\x76\x43\xf4\x3d\x50\xc3\x70\x12\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9a\x49\x44\x41\x54\x58\x85\xe5\ -\x96\xbb\x72\xd3\x40\x14\x86\xbf\xe3\xa4\x00\x9e\x23\x25\x54\xb1\ -\x52\xf0\x0a\x14\x90\x84\xc4\x21\x64\x72\x23\x44\x6a\x2c\x37\x99\ -\xe1\x19\x28\x65\x35\x92\x27\x09\xd8\x21\xce\xc5\xc0\x30\xc3\x33\ -\x50\x59\x7e\x05\xe8\xe0\x0d\x80\x02\xfb\x50\xc4\x4a\x64\x5d\x6c\ -\xcb\x71\xc3\x70\x2a\x69\xb5\xfb\x7f\x9f\x56\xab\xd9\x85\xff\xbd\ -\x24\xbc\x30\x5e\x3a\x0f\xb5\x20\x1e\xca\x5d\x11\x5e\xb5\x7d\xfb\ -\xe3\x34\x41\x86\x59\x5d\x52\xe5\x35\xc2\x6f\x44\xac\xc0\x2b\x7f\ -\x01\x28\x84\x1d\xb4\x20\x47\xc0\x03\x84\x39\x85\x96\x61\xba\xa5\ -\x69\xc1\x8b\x96\xb3\xa6\xd0\x42\x98\x03\xee\xa3\x7a\x18\x3e\xbb\ -\x11\x80\x3b\x91\x31\x05\x45\x9b\xd3\x90\x28\x5a\xce\x1a\x2a\xa7\ -\x51\x16\x70\x2f\x21\x20\x22\x07\x40\x6f\x9a\x12\x86\xe9\x96\x52\ -\xe0\x3d\x55\x39\x48\x08\x04\x5e\xf9\x03\xb0\x91\x22\x71\x3a\x89\ -\x84\x61\xba\x25\x45\x9b\x71\xb8\x20\x5b\x9d\x5a\xb9\x95\x10\x00\ -\x08\x7c\xfb\x2c\x45\x62\x26\xaf\x44\x1f\x9e\x78\x73\x41\xb6\xda\ -\x7e\xf9\x5d\xb4\xaf\x90\x52\xf3\xfb\xee\xba\x88\x9e\xc4\x02\xba\ -\x22\xba\xde\xf6\x2a\x97\x43\xe1\x96\xb3\xaa\x2a\x4d\x60\x66\x14\ -\x3c\x53\x60\x52\x89\x0c\xb8\x0a\xb2\x99\x06\x27\x16\x3e\x50\x9d\ -\x5a\xb9\x29\xc2\x26\xf1\xcf\xa1\xd2\x34\x2c\x67\x35\x45\x78\x25\ -\x2f\x1c\x86\xcc\x40\x58\x86\x55\x7d\xae\x4a\x23\x26\xdb\x55\x95\ -\x67\xe1\x62\x9a\xdf\x77\x57\x44\xf4\x2c\x2f\x7c\x2c\x01\x00\xc3\ -\x74\x37\x14\xad\xa7\x49\x00\xa4\xc1\x11\xdd\x0a\xbc\xca\xc9\xa8\ -\xec\xb1\x04\xb2\x24\xb4\xff\x79\x64\x50\x6c\x6c\x78\x2e\x81\x88\ -\x44\x63\xc8\xb8\x5c\xf0\xdc\x02\x37\x12\x34\x40\xe3\x63\x15\xd8\ -\x0e\x7c\xbb\x91\x27\x2f\xf3\x2f\xc8\x2a\x15\x7e\x29\xaa\x89\xf6\ -\x2b\x81\x9f\x79\xf3\x72\x09\x14\x2d\x77\x19\xd5\x73\x49\x19\xd7\ -\x6f\x3b\x2f\x9a\xd5\xa7\x79\x32\x73\x2c\xc2\xea\x92\xc2\x05\x30\ -\x1b\x69\x0e\x67\x22\x9a\xd3\x45\xa4\xd4\xdf\x5b\x46\xd6\x58\x33\ -\x90\x05\x57\xd5\x1d\x60\x3b\x22\x02\x30\x83\xea\x45\xd1\x72\x97\ -\xa7\x22\xb0\x60\x39\x8b\x59\xf0\x4e\xad\x52\x0f\x7c\xbb\xd1\x17\ -\x99\x48\x62\xa8\xc0\x82\xe5\x2c\xf6\x54\x2e\xe3\x70\x11\x76\x3b\ -\xb5\x4a\x3d\x6c\xe8\xd4\x2a\xf5\x0c\x89\xf3\x51\x12\x99\x02\xc3\ -\xe0\x6d\xcf\x7e\x1b\xef\xdf\xa9\x55\xea\x22\xec\xc6\x24\x66\x47\ -\x49\x64\x6d\xc7\x4f\x44\xb4\x35\x2e\x3c\x5a\x86\x55\xdd\x56\xe5\ -\x38\x96\xfd\x47\xa0\x94\x76\xd0\x4d\x08\x64\xc2\x91\x17\x6d\xbf\ -\xfc\x66\x18\xfc\x5a\xc2\x74\x77\x14\x3d\x1a\x47\x62\x40\xa0\x68\ -\x3a\x8f\x41\xde\xdf\x06\x9e\x57\xe2\xfa\xe1\xfc\x7e\xf5\x91\x08\ -\x9f\xa6\x01\x0f\xab\x68\x55\x77\x51\x0e\x53\x24\x96\xda\xbe\xfd\ -\x19\x06\x4e\xc5\x38\x71\x38\xc2\xde\xa4\x70\x80\xc0\xb3\x8f\x11\ -\xf6\x88\x2d\x4c\x05\x27\xbc\x49\x6c\xad\x51\x78\xe0\xd9\xc7\x93\ -\xc2\x87\x4a\x28\xdd\x84\x00\xaa\x26\xc8\x57\xe0\xc7\xd5\x96\x7a\ -\x7b\x78\x54\x42\x90\x4d\x94\xef\xc0\xb7\x5e\x41\xcc\x69\x65\xff\ -\xfb\xf5\x17\x4b\x00\x72\xf1\x7d\xf9\x90\x28\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x3b\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xbd\x6b\x14\x41\x18\xc6\x9f\xd9\x0d\x84\xa0\xd8\x88\x04\x63\ -\x0a\x43\x62\xa1\x08\x42\x72\xd1\x94\xe2\x27\x06\xb1\x0b\x8a\x8d\ -\x78\x60\x36\x97\xd3\x53\x0b\x09\xfe\x05\xc6\x2a\xb8\x97\x4b\x72\ -\x29\xd2\x08\x36\xd1\x42\x84\x9c\xa0\x16\x01\x8b\x48\x2e\x29\x24\ -\x88\x85\x82\xc5\x29\x04\xb5\x88\xe4\x83\x33\x99\x7d\x2d\x22\x16\ -\xb7\x7b\x7b\xb7\x1f\x73\x93\x73\xe7\x57\xce\x0d\xcf\xfb\xec\x73\ -\xf3\xc5\xee\x00\x0a\x85\x22\xca\xb0\xa0\x02\x47\x06\x33\xbb\x9b\ -\x38\x4f\x32\x42\x1f\x18\x8e\x02\x68\x0c\xc1\x57\x10\x8a\x20\x2c\ -\x11\xc3\xf4\x86\xae\x67\x3e\x8c\x25\x57\xdd\x3a\x07\x0a\x20\x66\ -\x8c\x9e\x05\xac\x29\x00\xad\x41\x74\x04\x52\x00\xb4\x78\x3e\x7b\ -\xf3\x55\xb9\x0e\x9a\x5f\xe5\xd8\x80\x19\x07\xac\x97\xd8\xb9\x0f\ -\x0f\x00\xad\x80\x95\xeb\x36\xd2\xd7\xcb\x75\xf0\x35\x02\xba\xfa\ -\xcd\x73\x8c\x21\x87\x00\x01\xd6\x18\x0e\x68\x17\x9c\x46\x82\xe7\ -\x00\xb6\xe7\xbc\xf5\x91\x81\x0e\x84\xe3\xad\x66\x14\xd6\x75\xfd\ -\x70\xe9\x9a\xe0\xf9\x1f\x6c\xe2\x3c\x59\x87\x0f\x0f\x00\xad\x4d\ -\x9c\x27\x4b\x1b\x3d\x07\xc0\x08\x7d\xe1\xf8\xa9\x3d\x4e\xde\xbd\ -\xcf\xe1\xed\xad\xae\x3e\x71\xf0\xde\xe0\x43\xc6\x75\x9f\xcf\x67\ -\x53\x81\xcf\x16\x41\x88\x19\x26\xb9\xfc\x6c\xf3\x5e\x2f\xab\xb8\ -\x30\x54\x00\xb2\x0d\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\ -\xc8\x26\xf2\x01\x54\x3c\x08\x75\xf5\x8f\xec\xd7\x34\x2d\x41\x60\ -\xa7\x41\x68\xae\xd4\x3f\x66\x98\x9f\x7c\xbb\x21\x10\x18\x0a\x20\ -\xcc\xe8\x8d\xc8\xbe\x4b\xa7\x7e\xf9\xd6\xaa\x12\xd7\x00\x62\x89\ -\xf4\x25\x58\x34\x45\x84\xbd\x1e\x34\xdb\x7d\xbb\xd9\x3e\x43\x76\ -\x80\xe1\x24\xff\x8d\x44\x67\xc2\xbc\xba\x38\x9e\x9a\xf3\xad\x57\ -\x05\x65\xa7\x40\xcc\x30\x87\x61\xd1\x73\xc0\xd3\xc3\x87\x49\x9b\ -\x66\xe1\x6d\x97\x91\x1e\x10\x59\xc4\x31\x80\x6e\x23\x7d\x19\xc0\ -\x90\xc8\xc2\x55\xa2\x33\xd0\x68\x67\xc2\xec\x11\x55\xc0\x16\x40\ -\xcf\xc0\xc8\x41\x02\x4d\x8a\x2a\xe8\x03\x5d\xb3\xf0\xe4\xc4\x2d\ -\x73\x8f\x08\x71\x5b\x00\x5b\xd4\x70\x1f\x80\x90\x62\x01\x68\xe3\ -\x45\x18\x22\x84\x1d\xa6\x00\xf5\x8a\x28\x14\x18\x06\x21\xbe\x9c\ -\xd6\x80\x9d\xf9\x96\x97\xc4\xf8\xf2\xfc\x42\xc4\xd2\xf5\x43\x22\ -\x8c\xe8\x7c\xab\x83\xc0\x72\x65\x3b\xb0\xe0\x1f\x71\x9c\xf0\x1c\ -\xc0\xe2\x58\xd2\xff\x41\xc7\x85\xce\xc1\x0c\x34\xce\x45\x48\xbb\ -\x12\xf9\xa3\xb0\x0a\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\ -\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\x40\xb6\x01\xd9\xa8\ -\x00\x64\x1b\x90\x8d\x9f\xfb\x01\xb2\x68\xaf\xf0\xed\xbf\x1a\x8a\ -\xa5\x0d\xd1\x1a\x01\x84\xa5\xd2\xa6\x48\x05\x40\x0c\xd3\xa5\x6d\ -\x51\x0a\xa0\xb0\xa1\xeb\x99\xd2\xc6\xa8\x04\xc0\x01\x2d\xee\x74\ -\x6f\x38\x0a\x01\x70\x06\x76\xa3\xdc\x7d\xe1\x7a\xda\x05\xfc\x50\ -\x00\xb4\xf8\xbc\xcb\x65\xe9\xff\x31\x80\x7f\xd7\xe5\x37\xd7\x8b\ -\xa3\xef\x1f\xdf\x5b\x73\xeb\x6c\x7b\xd5\x1c\xc2\x5e\x2b\x8a\xcf\ -\xf9\x6c\xaa\x23\x6c\x51\xfb\x1a\xc0\xf0\x3d\xec\x22\xa1\xc0\xb0\ -\x2c\x42\xd6\x1e\x00\xe1\xb5\x88\x42\x41\x61\xa0\x37\x22\x74\x6d\ -\x01\x68\xc0\x43\x00\x9b\x22\x8a\x05\xe0\xa7\x65\x59\xe3\x22\x84\ -\xf5\xd2\x86\xaf\x0b\xb9\xe5\x96\xee\xde\x55\x00\xe7\x45\x14\xf4\ -\x03\x03\xae\xe4\x27\xef\x2c\x88\xd0\x76\x3c\x07\xe4\x9b\x7f\x3c\ -\x02\xf0\x54\x44\x41\xaf\x30\x46\xc3\xf3\xd9\xd4\x0b\x51\xfa\xb6\ -\x11\x00\x00\x98\x9d\xa5\x6f\x17\x8f\x3f\x6b\x59\xdb\xb5\x02\xe0\ -\x54\xd9\x7e\x62\x59\x61\x8c\xae\xcd\x4f\xdc\x36\x45\x16\xa9\xf8\ -\xc5\xf5\xb8\x61\x1e\xb3\x80\x21\x30\x9c\x01\x61\x9f\x48\x33\x7f\ -\x29\x00\x6c\xa6\x81\x6d\x3d\x98\x9b\xb8\xfb\xa5\x06\xf5\x14\x0a\ -\x45\x84\xf9\x03\x3a\xde\xd0\x31\x4b\x14\x34\x6a\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x52\xb6\x36\xa2\x7e\x0a\x39\ -\x90\x99\x04\xcb\x56\x01\x00\x00\x00\x00\x00\x00\xf0\xbf\xb1\xf6\ -\xb9\xe9\x88\xa4\x99\x0e\x48\x33\x20\x1d\x00\x00\x00\x00\x00\x00\ -\x00\x00\xef\x35\x86\x6a\x02\xea\xd1\x43\x33\x62\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x08\x4f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x01\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x70\x54\xd5\x1d\x3d\xe7\xee\x26\x61\xab\x01\x0b\x7e\xb4\ -\xa3\x19\x8a\x4e\x19\x0c\x15\x5b\x20\x6c\x42\x11\xc1\x69\xc7\xca\ -\x00\x71\x13\x4c\xd5\x0e\x4a\x75\xa8\xc5\xd6\x99\xd6\xb1\x74\x70\ -\x46\x03\xad\xd8\x6a\x2b\xa8\x7f\x48\x5b\x3f\x2a\x2a\xd3\x99\x85\ -\xcd\x06\xe9\x80\x3a\x53\x09\x83\x7c\x6c\x42\xc6\xd6\x51\xa1\x63\ -\xeb\x07\x30\xa9\x5a\x0a\xe5\xc3\x12\xd8\xdd\x7b\xfa\x47\x50\xdf\ -\x7b\xbb\x9b\xec\x66\xdf\xc6\xa4\xcd\x99\xd9\x3f\xde\xef\x9e\xfb\ -\x7b\xe7\x9e\xf7\xf6\xbe\xfb\xee\xbd\x0f\x18\xc6\x30\x86\xf1\xff\ -\x0c\x0e\xc4\x49\xae\x88\xea\xbc\xd3\x65\x98\x49\x6b\x2f\x93\xc1\ -\x04\x8a\x17\x0b\x38\x07\xc0\x48\x00\x01\x00\xc7\xce\xfc\xf6\x0b\ -\xda\x0b\x98\x37\x11\xc4\xf6\xf6\xf9\x7c\xa7\xd4\xda\x4a\x66\xc0\ -\xf4\xb8\x2e\x49\x5b\xbb\x08\xe4\x7c\x00\x93\xfa\x95\x44\x78\x07\ -\x46\x5b\xac\x35\x4f\x77\x34\x60\x0f\x48\xf9\xab\xd2\x6f\x03\x24\ -\xd6\xc5\x71\xb5\x85\x96\x02\x98\xed\x67\x6a\x02\xaf\x0b\x5c\x95\ -\xfa\x27\x9e\xeb\xbc\x8d\x49\x1f\xf3\xfa\x83\x70\x4c\xb3\x61\xf4\ -\x20\x84\xa9\x7e\xe5\xcc\x81\x77\x05\x2e\x6f\x8f\xe0\x19\x3f\xee\ -\x88\xa2\x0d\x08\x6f\xd4\x05\x4a\xdb\x87\x08\x7e\xa7\x17\x9a\x05\ -\xb0\x03\x54\x9b\xac\xd9\x67\x02\xf8\xbb\x52\x38\x6c\x2d\x8e\x8f\ -\x00\xd2\x27\x0d\x2a\xcb\x80\x51\x32\x18\x27\x60\x3c\xa0\x3a\x00\ -\xdf\x04\x10\xea\x25\xe7\x76\x6b\xb9\xa4\x63\x01\xdf\x28\x46\x7f\ -\x51\x06\xd4\xc5\x35\xcd\x4a\xad\x00\xbe\x98\xa5\xf8\x38\xa8\xcd\ -\x94\xd9\x64\x81\x17\xda\x1b\xf8\xaf\x82\x72\x47\x15\x4a\x07\x70\ -\x15\x69\xe7\x01\x9c\x9f\xe3\x1c\xdd\x22\x6f\x69\x8f\xf0\x0f\xfd\ -\xd1\x0f\x14\x61\xc0\xb4\x98\x6e\x04\xf5\x14\x81\x0a\xaf\x28\x4a\ -\x8f\x06\x2b\xcc\x2f\x5f\x99\xcb\x23\xfd\xcd\xef\x44\x75\x54\xe5\ -\x95\x41\x2c\x06\x74\x2f\x80\xf3\xbd\xe5\x82\x56\xb6\xff\xc5\xdc\ -\x8b\x15\xb4\x85\xe6\x2e\xdc\x80\x66\x99\xf0\x24\x7b\x1f\xc8\x65\ -\x9e\x12\x2b\xe8\x29\xca\xac\x48\x34\xf2\x60\xc1\x79\xf3\xc0\xd7\ -\x37\xaa\x32\x69\x71\x27\xa5\xbb\x00\x9c\xed\x2a\x14\x5a\x43\x69\ -\x2e\x6c\x6b\xe2\x89\x42\x72\x16\x66\x40\xb3\x4c\xf8\x72\xbb\x0e\ -\xe0\xf5\x9e\x92\x2e\x43\x46\x76\x45\xd8\x5e\x50\xbe\x7e\x22\x1c\ -\xd3\x45\x30\x8a\x7b\x3b\x5c\x11\xaf\xb2\x82\xb3\x12\x73\x78\x2c\ -\xdf\x5c\xa6\xa0\x13\x7f\xd5\x2e\xcf\xd2\xf8\xdd\x29\x71\xea\x40\ -\x35\x1e\x00\x12\x8d\x3c\x68\x92\x9c\x29\x68\x9d\x33\x4e\xe1\x6b\ -\xec\xd6\xba\xeb\xa2\x0a\xe4\x9b\x2b\x6f\x03\x6a\x63\xfa\x36\xc4\ -\x7b\x5c\x27\x84\xd6\x86\x8e\x72\x76\x67\x23\xff\x91\x6f\x1e\xbf\ -\xb0\xab\x89\x27\xdb\x23\x66\xa1\xc8\x9f\x02\xf8\xe4\x71\x28\x60\ -\xee\x81\x80\xbd\x3f\xdf\x3c\x79\xfd\x05\xa6\x6d\xd0\x54\x1a\x6d\ -\x07\x30\xe2\xd3\xa8\x9e\x4b\x44\xcc\x4d\xa5\x18\x9d\x15\x8a\x70\ -\x4c\x3f\x02\xb5\xda\x19\x13\x78\x73\x7b\x03\x9f\xe9\xab\x6e\x9f\ -\x77\xc0\xb4\x16\x8d\xa1\x51\x2b\x5c\x8d\x47\x7b\xe8\xa8\x59\x3c\ -\x18\x1a\x0f\x00\x89\x06\x3c\x02\xe8\xf7\xce\x18\xa1\xc7\x6b\x63\ -\x9a\xdc\x57\xdd\x3e\x0d\x20\xec\x83\x00\x2e\x74\x84\xba\x82\x01\ -\x46\xda\xbe\xcb\xee\xc2\xa5\x96\x08\xa4\x46\x8f\x30\x4b\x24\xec\ -\x74\x44\xcb\x45\x3d\x3e\x6b\xab\x82\xbd\x55\xed\xd5\x80\x70\x8b\ -\x66\x00\xbc\xc5\x11\x12\xc4\xc6\x1d\xf5\xec\x2a\x46\x6f\x29\xb0\ -\x65\x0e\x4f\x31\xc8\x06\x00\x87\x1c\xe1\xc9\xdd\x47\x70\x7b\x6f\ -\xf5\x72\x1b\x20\x11\xd0\x2f\x3c\xc1\x75\x89\x46\xee\x2e\x42\x67\ -\x49\x91\xa8\xe7\x07\x10\x57\x3a\x63\x82\xee\x99\xf4\xa2\xce\xca\ -\x55\x27\xa7\x01\x75\x71\xcc\x04\x30\xc3\x11\x4a\xa6\xad\x69\x2e\ -\x5e\x66\x69\x11\x3a\x86\xdf\x90\xd8\xef\x08\x9d\xfb\xb9\x8f\x70\ -\x5b\x2e\x7e\x4e\x03\x2c\xf4\x13\xe7\x31\xa5\xdf\xee\x59\xc0\xb7\ -\x7d\xd0\x58\x52\xf4\xf4\x4d\x74\x5d\x28\x41\x77\xe6\x1a\x1b\x64\ -\x35\xa0\x26\xaa\x2f\x00\xf8\x96\x23\x94\x54\xd0\xdc\xe7\x9f\xcc\ -\xd2\xa2\x2a\x89\x67\x01\xbc\xe5\x08\x5d\xf8\x9e\xc1\x37\xb2\x71\ -\xb3\x1a\x10\x08\xe2\x46\xf4\x4c\x55\xf5\x80\x78\x39\x51\xcf\x0f\ -\xfc\x14\x59\x4a\xac\x6f\x62\x9a\xd0\x7a\x67\x8c\xc6\xde\x9c\x8d\ -\x9b\xd5\x00\x41\xf3\x5c\x01\xcb\xe7\x7d\x53\x37\x50\x30\xc6\xa3\ -\x99\x73\xb2\xfd\x0d\x32\x0c\x38\xd3\x63\x4e\x77\xc6\x52\x69\xfc\ -\xd1\x67\x79\x25\xc7\xee\x57\xd1\x01\xc0\x79\xd7\x8e\x3a\x58\x86\ -\x29\x5e\x5e\x86\x01\x15\xff\x41\x2d\x80\x72\x47\xe8\xcf\x9d\x4d\ -\xdc\xef\xe5\x0d\x7a\xac\xa0\xa5\xe4\xba\x70\x52\xe6\x3c\x65\x86\ -\x01\x06\xf8\x8a\xab\x12\xb5\xdd\x7f\x75\x03\x03\x4b\xe3\xd2\x2e\ -\xda\x89\x5e\x4e\x66\x1f\x20\x7b\xa9\x8b\x60\xcd\x5b\x19\x9c\x21\ -\x82\x80\x81\x47\x3b\x2f\xf5\x72\x32\x0d\x20\xbf\xe4\x3c\xb4\xc0\ -\xa0\x7f\xf6\xe7\x42\xea\xb4\x47\xbb\x30\xce\xcb\xc9\x30\x40\x16\ -\x95\x1e\xc2\xbf\x7d\x57\x36\x40\x38\xeb\xa3\x0c\xed\x95\x5e\x4e\ -\x86\x01\xa4\x9b\x64\x89\x82\xe6\xd8\x06\x13\xda\x16\xe1\x14\x80\ -\x94\x23\x54\x5e\x1d\x95\xb3\x83\xcf\x62\x80\x67\x92\x84\x16\x83\ -\xe2\x9d\xbf\x54\xc8\xfc\x0b\x00\xc7\x9d\xc7\xde\x3b\x62\x28\x61\ -\xd6\xd3\xa8\x00\xe0\x9c\x0f\x38\xfd\x66\x13\x4f\x3b\x39\x59\x3a\ -\x41\xb8\x66\x54\x6d\xcf\x2a\xee\x90\xc4\xc9\xd1\x18\xe5\x09\x1d\ -\xf7\x72\x32\x0d\xb0\x7a\xcf\xc3\xc8\xe8\x39\x87\x0a\x94\xc6\xc5\ -\x9e\xd0\xbb\x5e\x4e\x96\x77\x01\xb3\xd7\x79\x44\xd9\x2f\xfb\x29\ -\x6a\x80\xe1\xd2\x2e\x68\x9f\x97\x90\xed\x2f\xe0\x59\x6c\xe4\x8c\ -\x0c\xce\x10\x01\x61\x67\xb8\x8f\xcd\xeb\x5e\x4e\x86\x01\xa1\x14\ -\x76\x01\x70\xae\xbf\x4f\x0e\xc7\x74\x91\xff\xf2\x4a\x8c\x66\x19\ -\x80\x73\x5d\x31\xa1\xcd\x4b\xcb\x30\xe0\xcc\xda\xda\x2e\x57\x3d\ -\x62\xae\x97\x37\xd8\x51\x33\x09\x53\xe0\x5e\x51\x3e\x16\x1a\x8d\ -\x3d\x5e\x5e\x8e\xf9\x00\xba\xde\xa2\x08\xcd\xf7\x57\x5e\xe9\x61\ -\x60\x5d\x9a\x05\xbd\xd0\x36\x9b\xa9\x4c\x5e\x16\x94\x05\xb0\x0e\ -\x3d\x9b\x1a\xce\x54\xc6\x55\x57\x44\x75\x9e\xef\x2a\x4b\x85\x66\ -\x19\x90\x0b\x9c\x21\x5a\xb3\x36\x1b\x35\xab\x01\x3b\xea\xd9\x25\ -\xe0\xa5\x4f\x2a\x03\x15\xc9\xa0\xf5\x2e\x87\x0f\x5a\xd4\x5e\x8e\ -\x1b\x00\x4c\x70\x84\xde\x0f\x8d\xf9\xb4\x3d\x4e\xe4\x9c\x15\x16\ -\xf9\x6b\xd7\x31\xf8\x83\xe9\x31\x8d\xf5\x47\x62\xe9\x50\x1d\x55\ -\xb9\xa4\x9f\x3b\x63\x22\x57\x67\xbb\xfd\x81\x5e\x0c\xe8\xb8\x16\ -\x2f\xc3\xdd\x19\x96\xa7\x61\x97\xfb\xa2\xb2\x84\x38\xbb\x0c\xdf\ -\x03\x5d\x83\xb7\xc3\x65\x06\x6b\x72\xf1\x73\xaf\x0c\x91\x22\x79\ -\xb7\x27\x76\x53\x38\xae\x8c\x79\xb5\xc1\x82\x29\xcf\xeb\x5c\x4a\ -\xae\x25\x7c\x88\xf7\xef\xa8\x67\xc6\x10\xf8\x63\xf4\xba\x36\xb8\ -\x3b\xc2\x36\x50\xcf\xba\xf8\x52\x3c\xbc\x51\x17\x14\x27\xd5\x7f\ -\x54\x47\x55\x1e\x48\x69\x03\xdc\x7b\x88\x5e\x4b\x1d\xc2\xa3\xbd\ -\xd5\xeb\x73\x75\x38\x20\x73\x17\xdc\xb3\xab\x55\x4a\xa9\xe5\x9a\ -\xcd\xf2\x6e\x8e\xfa\x4c\x31\x32\x68\x1f\x21\x70\xa5\x23\x94\x34\ -\xe4\xe2\xbe\x36\x55\xf6\x69\xc0\xce\x06\x7e\x08\xf1\x5a\x01\xa7\ -\x3e\x8e\x91\x98\x7e\xb8\xdb\x3e\xd6\xb3\x80\xfa\xd9\x23\x1c\xd3\ -\xed\x02\xbf\xef\x8c\x89\x5c\x92\xcf\xb6\x9d\xbc\x1b\x10\x8e\x69\ -\x21\x28\xf7\x8e\x0b\xe9\x77\xc7\xd3\xe6\x0e\xef\x3b\xf6\x80\x41\ -\x62\x6d\x1c\x77\x08\x5a\x0d\xe7\xc5\xa4\x1e\x4e\x44\x02\x3f\xce\ -\x27\x45\x41\x57\xb0\x36\x96\x7e\x40\xe4\x52\x97\x06\x60\x5b\x3a\ -\xc8\x05\x9d\xf3\x79\x28\x57\xbd\x52\xa0\x3a\xaa\xf2\x91\x01\xfb\ -\x98\xc8\x5b\x5d\x05\xc4\x8b\xa1\x73\x38\x37\xd7\x63\xcf\x8b\x82\ -\x76\x89\x55\xa5\xcd\xdd\x04\xe2\xee\xf3\xe1\xca\x60\x4a\x1d\x75\ -\xad\xba\xac\x90\x5c\xc5\x60\x7a\x8b\xce\xaf\x0c\xea\x4f\x19\x8d\ -\x07\xde\x38\x05\x5e\x9f\x6f\xe3\x81\x7e\x6c\x94\xbc\x2e\xaa\xc0\ -\x81\xa0\xfd\x95\x40\xef\x2d\x96\x04\xb4\x26\x00\xb3\x72\x67\x03\ -\x3f\x2c\x34\x6f\x3e\xa8\x8b\x2a\x94\x0e\xe2\x87\x84\x96\x01\xf8\ -\xbc\xa7\x78\x4b\x2a\xc5\x1b\x3a\x9b\x78\xb4\x90\x9c\xfd\xdf\x2a\ -\x1b\xd7\xad\x94\xd6\x00\x28\xf3\x14\x9d\xa0\xf4\x90\x42\x66\x55\ -\x21\x1b\x16\x7b\xc3\xac\xad\x0a\x76\x1f\xc6\x22\x51\xcb\xe1\xde\ -\xaf\x04\x00\x10\xb4\x6a\x6c\xca\x2c\x5d\xdf\xc4\x74\xa1\xb9\x8b\ -\xea\xc5\x6b\x62\x9a\x69\xa8\x16\x00\x63\xb2\x14\x1f\x01\xb4\x09\ -\x32\x9b\x10\xc2\x4b\x85\x9a\x51\x1d\x55\xf9\x48\x83\x99\x32\x76\ -\x1e\xc0\x7a\x00\xd9\x86\xe1\x49\x91\x4b\xda\x23\x7c\xb2\x3f\xfa\ -\x01\x1f\xb6\xcb\xd7\xb4\xaa\xca\x58\x3d\x0c\xa0\xa1\x17\x5a\x12\ -\xc4\x36\x59\x6e\xa5\xc1\x5f\x25\xfc\x4d\x06\x87\x2b\x82\x38\x91\ -\x34\x48\x9b\x13\xa8\xb4\xe5\x18\xa5\x34\xc6\x81\x18\x4f\xd8\x3a\ -\x80\x57\xa3\xe7\x93\x9a\x5c\xc2\x3b\x44\x2e\x49\x44\xd8\x59\x8c\ -\x7e\xdf\x9e\xe3\xb5\x71\x5d\x23\xe9\x01\x00\xa5\xee\x0c\xbb\x24\ -\xfe\x6c\x6c\x1a\x4f\xf4\xe7\x96\xf7\xc2\xdf\x81\x4c\xb3\xcc\xb4\ -\x49\xa8\x37\xd4\x32\x01\x35\xbe\xe6\x06\xde\x06\xb8\x2a\x74\x14\ -\x4f\xfa\xb9\x47\xb1\x64\x23\xb9\x9a\x0d\x9a\x68\x8c\x5d\x74\xe6\ -\x63\x87\xf1\xfd\x4c\xf3\x3e\xa0\xcd\x56\x66\x6d\xc7\x6b\x78\xa5\ -\x3f\xdf\x03\xf4\x85\x01\x19\xca\xd6\xb4\xaa\x8a\x16\xb3\x8d\xec\ -\x44\x91\x13\x00\x8c\x23\x31\x4a\xc2\x48\xf4\xac\xdc\x1c\x45\xcf\ -\x67\x73\x07\x00\xed\x23\xcd\x3e\x11\xdb\x12\xf5\xd8\x3b\x58\xb6\ -\xe3\x0e\x63\x18\xc3\xf8\xdf\xc4\x7f\x01\x16\x1d\xd4\x53\x92\x2f\ -\x1f\x88\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xeb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9d\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xbd\x6e\x13\x41\x14\x46\xcf\x75\x08\xa1\x09\x5d\xde\x80\x37\ -\xb0\x5d\xd1\xf0\x08\x34\x58\x36\x09\x08\x1a\x7b\x0b\x6c\x57\x74\ -\xb4\x3c\x80\x6d\x90\x6c\x37\xfc\xe6\x47\x50\x20\xde\x80\x1a\x70\ -\xc5\x73\x20\x21\xd1\x40\x24\x7c\x29\x22\x24\x33\x5e\xc7\xb1\x77\ -\x66\x76\x66\xe3\x5b\xee\xde\xfd\x34\xe7\x68\x76\x76\x35\x1a\xd8\ -\xd4\xa6\x36\x75\x99\x4b\xf2\x1e\x80\xeb\x2a\x37\x07\xb7\x11\x7d\ -\x2a\xc2\x0f\x9d\x4a\x32\x19\xb7\xbf\xcd\xde\xbf\x92\xd7\xc0\x7c\ -\x54\x25\xe9\xd5\x51\x3d\x04\x4a\x28\x48\x49\x87\xc0\xcd\xd9\x9e\ -\x52\x3e\x43\x73\x5f\x67\xf0\x72\x06\xff\xaf\x94\xeb\x66\x5f\x21\ -\x05\xa4\xc2\xc3\x1f\xd0\x27\x66\x6f\xe1\x5e\x81\x45\xf0\xaa\xd2\ -\x98\x8c\x3b\x1f\xcd\xfe\x42\x2d\x82\xe7\xc3\xb7\xdf\xa7\x3d\x53\ -\x18\x01\xeb\xc0\x43\x41\x04\xac\x0b\x0f\x05\x10\x90\x05\x1e\x22\ -\x17\x90\x15\x1e\x22\x16\x60\x03\x1e\x22\x15\x60\x0b\x1e\x22\x14\ -\x60\x13\x1e\x22\x13\x60\x1b\x1e\x22\x12\xe0\x02\x1e\x22\x11\xe0\ -\x0a\x1e\x22\x10\xe0\x12\x1e\x02\x17\xe0\x1a\x1e\x02\x16\xe0\x03\ -\x1e\x02\x15\xe0\x0b\x1e\x02\x14\x60\x1b\xbe\xdc\x1c\xdc\x91\x92\ -\x3e\x07\x28\xa1\xad\xcf\xc3\xee\x87\xd9\xfb\x41\xed\x08\xd9\x86\ -\xaf\x24\xbd\xba\x88\x9e\xa0\xec\xa1\xec\x4d\x91\x91\xd9\x13\x8c\ -\x00\x17\xf0\x29\x79\x73\x15\x84\x00\x4f\xf0\x53\x41\x1f\x99\xbd\ -\xb9\x0b\xf0\x06\x2f\xdc\xff\x32\xec\xbe\x33\xfb\x73\x5d\x04\xfd\ -\xc2\x77\x0e\xd3\x9e\xc9\x4d\x40\x08\xf0\x90\x93\x80\x50\xe0\x21\ -\x07\x01\x21\xc1\x83\x67\x01\xa1\xc1\x83\x47\x01\x21\xc2\x83\x27\ -\x01\xbe\xe0\x55\xe5\xde\x64\xdc\x3e\x5a\x25\xcb\xb9\x80\x90\xe1\ -\xc1\xb1\x80\xd0\xe1\xc1\xa1\x80\x18\xe0\xc1\x91\x80\x58\xe0\xc1\ -\x81\x80\x98\xe0\xc1\xb2\x80\xd8\xe0\xc1\xa2\x80\x18\xe1\xc1\x92\ -\x80\x58\xe1\xc1\xc2\x19\x21\x5f\xf0\xc0\xc1\x64\xdc\x3e\x5e\x35\ -\xaf\x9a\xf4\x6a\x8a\x3c\x03\x07\x7b\x82\x3e\xe1\xbf\x8e\x3a\xab\ -\xc3\xb7\x06\x07\xaa\x72\xec\x64\x4f\x30\x0a\x78\xf4\x15\x4b\x18\ -\xd7\x12\x10\x3c\x7c\xd2\xdf\x4f\x81\xb7\xb3\x27\x18\x05\xbc\xf2\ -\xda\xcc\xb3\xb2\x27\x18\x37\x7c\xc6\x3d\xc1\xd0\xe1\xcb\xcd\xc1\ -\x5d\x11\x7d\x63\xe6\x2d\xfb\x74\x5e\x48\x40\x51\xe1\xe1\x02\x6b\ -\x80\x37\x78\xd1\x7d\xdf\xf0\xb0\x64\x06\x78\x85\x1f\x76\x4f\x56\ -\xcd\xcb\x0a\x0f\xe7\xfc\x09\x86\x0e\x5f\x69\xf5\x1b\x30\x0f\xcf\ -\x8a\x7f\x8c\xa9\x33\x20\x0e\x78\xde\xce\xe5\xad\xb1\x86\x6c\x99\ -\x17\xaa\x49\xaf\x86\xca\x11\x96\xe0\x17\xe4\xad\x0d\x5f\x4d\x7a\ -\x35\x48\xc9\x5b\x73\x01\xfd\x6f\x06\x94\x9b\xa3\x6d\x91\xdf\xdf\ -\x81\xdd\x99\xcb\x19\x0e\x27\xa4\xe6\x65\x78\xe7\xed\xe6\x81\xf1\ -\x15\xd8\x3d\xbd\xba\x05\xec\xcc\x5c\xca\x74\x2c\x25\x25\x2f\xd3\ -\x60\x6d\xe7\x81\x21\xe0\xd3\xcb\x87\xbf\x54\x79\x0c\x9c\x02\x3f\ -\x81\x7a\x96\x33\x39\x66\x9e\x88\x36\xb2\x0c\xd6\x76\xde\xc2\xba\ -\xd1\xee\xef\x94\x9b\xa3\xed\x50\xf3\x6e\x3d\x78\x71\xcd\x66\xde\ -\xa6\x36\x75\x89\xeb\x2f\x57\x3e\x7f\x9e\x34\x61\xbc\xb4\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\xde\x50\x80\x05\xfc\x5b\x20\ -\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ -\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xc0\x07\xe4\xc6\x04\x35\x1a\x89\x95\x2e\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x86\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x0d\x00\x40\x08\x03\x41\x72\xaa\x90\x87\x21\x24\x92\x9c\ -\x08\x78\xce\xfe\xdb\x4c\xc4\xa2\xec\xa9\xec\xa9\xcd\xc7\xdb\x8c\ -\x2f\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xf8\xac\x79\x05\x03\xdf\x56\x31\xc9\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\xa2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x54\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x4f\x53\x51\x18\x87\x9f\xb7\x85\x58\x07\x8d\x9d\x18\x24\ -\x3a\xcb\xa0\x24\x92\x36\x6e\x98\x28\x0c\x1a\x91\x26\xc8\x20\x09\ -\xff\x81\x71\x53\x18\x24\x9a\xf8\x11\x27\x3f\xfe\x02\x12\x17\x31\ -\x82\x18\x1d\x44\x13\x9c\x34\x25\x98\xa0\x03\xce\x12\x1c\x70\xb0\ -\xc4\xc5\x1a\xa4\xaf\x83\x17\x73\xef\xed\xad\xd2\x9e\x7b\x7b\x40\ -\xce\xb3\x9d\xf7\x9e\x9e\xfe\xde\xdf\x3d\x5f\x69\xcf\x01\x87\xc3\ -\xb1\x93\x91\xcd\x54\xea\x9e\xd5\x96\x72\x89\x33\x15\x2a\x83\x82\ -\x74\x29\xec\x17\xd8\x95\xb4\xb8\x7a\x50\xf8\x21\xf0\x59\xd1\xf9\ -\x14\xa9\x87\x99\x2c\x4f\x5f\x1f\x97\x9f\xff\xfa\xdc\x3f\x0d\xc8\ -\x4f\xea\x49\xd0\xbb\xc0\xa1\x58\x94\x36\x8f\x45\x90\x8b\xc5\x82\ -\xbc\xfc\x5b\xa5\x54\xcd\x27\xaa\x92\x7b\xac\xa3\xa0\x33\x6c\xbf\ -\xe4\x01\x3a\x40\x67\xf2\x53\x3a\x82\x6a\xcd\x17\x5d\xd3\x80\xdc\ -\x24\x23\x22\x7a\x3d\x19\x6d\x4d\x44\xf5\x46\xfe\x09\x97\x6b\x3d\ -\x8e\x74\xc6\xeb\xf6\x33\xa1\x70\x49\x45\xae\x90\xe6\xf9\xc1\x32\ -\x4b\x8f\xce\xc9\x7a\xac\x42\x0d\x19\x98\xd0\xf4\xa7\x0c\x07\x58\ -\xe7\x94\xa8\x5e\x03\xb2\xc1\x1a\xd2\x13\x35\x1c\xaa\x0c\xe8\x9e\ -\xd5\x96\xef\x25\xfd\x80\xbf\xdb\x0b\xaf\x48\xc9\x50\xb1\x4f\x56\ -\x62\x57\x9e\x00\xf9\x69\x6d\xa3\xa2\x0f\x50\x4e\xf8\xc2\x8b\xbb\ -\xb3\x72\x24\x3c\x31\x56\x0d\x81\x72\x89\x33\x04\xc7\xfc\xd7\xb4\ -\xca\xf9\xed\x92\x3c\x40\xb1\x4f\x56\x48\xc9\x10\x50\xf2\x85\x3b\ -\xbc\xdc\x02\x54\x19\x50\xa1\x32\xe8\x2f\xab\xc8\xd8\x9b\x82\x7c\ -\x89\x5f\x66\xb2\x14\xfb\x64\x45\x54\xc6\xfc\xb1\x70\x6e\x10\x61\ -\x80\x20\x5d\x81\x40\x9a\xe7\xb1\xab\x6b\x12\x95\x56\x9e\x05\x23\ -\x72\x34\x5c\xa7\xca\x00\x85\xfd\xfe\xf2\xc1\x32\x4b\x71\x0b\x6b\ -\x16\x11\xda\xdb\xc3\x75\x22\x7a\x40\x70\x87\xb7\xd5\x66\xfb\x7a\ -\x08\x6b\x8f\xda\xbd\xd6\xde\x08\xed\x10\x9c\x01\xb6\x05\xd8\xc6\ -\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\ -\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x5a\xe2\x68\x24\x3f\ -\xa5\x3d\xa8\xde\x06\x0e\xb3\xc9\xff\x1a\x0c\x50\xe0\x3d\x22\x97\ -\x8a\xfd\x12\xfe\xdd\xb2\x6e\x8c\x7b\x40\x6e\x52\x87\x51\x7d\x01\ -\x1c\x21\xf9\xe4\xf1\xbe\xa3\x13\xd5\x17\xb9\x49\x1d\x36\x6d\xcc\ -\xc8\x80\xce\x29\xdd\x27\xe8\x7d\x53\x11\x8d\x22\xe8\xbd\xce\x29\ -\xdd\x67\xd2\x86\x91\x01\x19\x38\x06\xec\x31\x69\xc3\x90\xbd\x9e\ -\x86\x86\xd9\xf1\x93\xa0\x91\x01\x65\x78\x0b\x7c\x8b\x49\x4b\x23\ -\x7c\xf3\x34\x34\x8c\x91\x01\x0b\xfd\xb2\xaa\xc8\x05\x93\x36\x4c\ -\x50\xe4\xc2\x42\xbf\xac\x9a\xb4\x61\x3c\x04\xe6\x0a\x32\x8e\x48\ -\x2f\xb0\xc0\xef\x25\x2a\x69\x36\x96\xc1\xde\xb9\x82\x8c\x9b\x36\ -\x16\xcb\x3e\xc0\x5b\x8f\x8d\xd7\x64\x1b\xb8\x49\xd0\xb6\x00\xdb\ -\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\ -\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\x20\x1c\x50\ -\xf8\xe1\x2f\x0f\x4c\x68\xba\x79\x72\xe2\x25\xac\x3d\x9c\x1b\x44\ -\x1f\x92\xfa\xec\x2f\x7f\xca\x70\x20\x7e\x69\xcd\x21\x42\xfb\x72\ -\xb8\x4e\x44\x0f\xd0\xf9\x40\x60\x9d\x53\xf1\xca\x6a\x1e\xa9\x35\ -\x4e\x07\x23\xfa\xae\xaa\x4e\x75\x20\xf5\xd0\x5f\x16\xd5\x6b\xf9\ -\x69\x6d\x8b\x5b\x5c\xd2\xe4\xa7\xb5\x4d\x45\xaf\xfa\x63\xe1\xdc\ -\x7e\xc7\x42\x64\xb2\x3c\x05\x3e\xfa\x42\x59\x2a\xfa\x60\x3b\x99\ -\xf0\xe7\xb0\x74\xf0\xc4\xf8\xa2\x97\x5b\x80\xba\x8e\xcb\x8b\xca\ -\x58\xa5\x95\x67\x5b\xf9\xb8\x7c\x6a\x8d\xd3\xde\x9b\x6f\xec\xb8\ -\xfc\x06\xb9\xc7\x3a\xfa\x5f\x5c\x98\x00\x10\x19\x2d\xf6\xcb\xcd\ -\xa8\x47\x35\xf7\x01\x73\x05\x6e\x22\x32\x9a\x9c\xaa\xa6\xa0\x20\ -\x23\xc5\xb3\xdc\xaa\x55\x61\xb3\x97\xa6\xee\x00\x1d\xb1\x4a\x4b\ -\x9e\x4d\x5d\x9a\xaa\xfb\xda\x9c\x77\xe4\xbc\x7d\x2b\x5e\x9b\x03\ -\x96\x41\xdf\xd5\x73\x6d\xce\xe1\x70\xec\x6c\x7e\x01\x43\x8d\x07\ -\x87\xbb\xe6\x3f\x9a\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x08\xe5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x08\x97\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x6d\x6c\x14\xc7\x19\x7e\xde\xb9\x0f\xdb\xa1\xfe\x68\x21\xa1\ -\xc8\xd0\x06\xac\x20\x28\xa6\x2a\x98\x56\x35\x45\x60\xc0\x9c\xeb\ -\xaa\x98\xf8\x60\xd5\x90\x0a\x62\xe3\x8f\x86\xa4\xad\x4a\x94\x46\ -\x02\x29\x39\xdc\x86\x7e\xa4\x0d\x09\x89\x14\x08\x9c\x8d\x21\xd0\ -\x48\x3d\x6c\x23\x93\xc6\xe1\x6c\xa7\x46\xa4\x80\x42\x20\x55\x02\ -\x36\x51\x52\x87\x50\x6a\x25\x51\xb1\x9d\x03\x81\xed\xbb\x9b\xb7\ -\x3f\xf8\xda\xdd\x5b\x9f\xef\x7c\xbb\xae\x69\xfd\xfc\x9b\x67\xde\ -\x7d\xf7\xd9\xe7\x66\x67\x66\x67\xe6\x80\x31\x8c\x61\x0c\xff\xcf\ -\xa0\x91\xb8\x49\xa1\x52\x7a\x77\x50\xda\x17\x0a\xe2\xd9\x92\x31\ -\x83\x80\x69\x00\x67\x80\x28\x0d\x12\x36\x10\x02\x00\x02\x20\xbe\ -\x00\x89\x0e\x16\xd4\x2e\x08\x47\xfd\x3e\xef\xc7\x56\x6b\xb3\xcc\ -\x80\x25\xf7\x57\x66\x09\x7b\xb8\x44\x30\x15\x31\xf0\xcd\x61\xa6\ -\xf9\x98\x99\x9b\x18\xa2\xb6\xb5\x7e\xd7\x3b\x00\xd8\x4c\x8d\x80\ -\xf9\x06\xd0\xd2\xe2\xb2\x02\x12\xe2\x09\x02\x2f\x36\x39\xf7\x19\ -\x26\x6c\xed\xf9\x8a\xd8\x77\x6a\xe7\xce\xa0\x59\x49\x4d\x33\xa0\ -\xc0\xbd\x6e\xb1\x24\xf1\x0c\x80\x79\x66\xe5\x34\x06\x9f\x27\x60\ -\xb3\xbf\xae\x7a\x2f\x4c\x68\x11\x09\x1b\xb0\xb4\xa8\x7c\x22\xd9\ -\xf1\x2c\x11\x7e\x1c\x25\x4c\x32\xf0\x37\x62\xb4\x31\xf8\x9c\x20\ -\xdb\x3f\x18\xd4\x1d\x14\xfd\x97\x53\x40\xe1\x81\x30\x52\x89\x44\ -\x3a\x88\xa6\x82\x31\x9d\x88\x73\xc1\xb4\x0c\x40\xca\x60\x09\x19\ -\x38\x6a\x03\xad\x3f\x5c\xb7\xeb\x6c\x22\xfa\x13\x32\xa0\x40\x29\ -\xfb\x8e\x94\x74\x10\xc0\x24\x7d\x1d\x03\x97\x01\xbc\x2e\x88\x0e\ -\x85\xc3\xfd\x6f\xb4\x36\xec\xbd\x14\x4f\xee\x5c\x65\x43\xca\xb8\ -\x70\x60\x09\x41\x2c\x07\x71\x91\xd1\x3d\x00\xf4\x01\x58\xd7\x5c\ -\xe7\x7d\x75\x58\x0f\x80\x04\x0c\xc8\x77\x97\x3d\x48\x44\x35\x00\ -\x92\x22\x44\x11\xbd\xe0\x74\xda\x7f\xf7\x97\x3f\x6d\xef\x19\x6e\ -\x7e\x35\x14\x45\x71\xf6\xca\xf4\x0a\x00\x4f\x01\xb8\x47\x5f\x4f\ -\xc0\x96\xdc\xec\xcc\xa7\xaa\xaa\xaa\x64\xbc\xb9\xe3\x36\xc0\xe3\ -\xf1\x88\x63\x67\xbb\x9e\x06\xf3\x46\x5d\x95\x04\xa3\xc6\x0e\x54\ -\x35\xd5\x7b\x2f\xc6\x9b\x37\x16\x14\x15\xad\x4b\xbd\x6a\x17\x8f\ -\x11\xe1\x71\x00\x5f\x52\xd7\x31\xe8\x60\x48\x38\xd6\xb4\xf9\x5e\ -\xba\x12\x4f\xce\xb8\x0c\xf0\x78\x3c\xe2\xd8\xfb\x17\xf7\x83\xe8\ -\x01\x5d\x96\x2e\x41\x5c\x7c\xd8\x57\xfd\x76\x3c\xf9\x86\x8b\x42\ -\x77\xf9\xe4\x10\xa1\x01\x91\x1d\xee\xbb\xf6\xe4\x6b\x79\x4d\xfb\ -\xf7\x07\x62\xcd\x65\x8b\xe7\xc6\xce\xf1\xf7\x55\x81\xe8\x51\x1d\ -\x7d\x42\xb0\x58\x7a\xb8\xce\xfb\x41\x3c\xb9\x12\xc1\x47\x1d\xa7\ -\x03\x13\xb3\x17\xed\x73\xc8\x81\x7b\x89\x34\x73\x8c\x49\xe1\x90\ -\x63\x76\x4e\x76\xd6\x9f\xdb\xdb\xdb\x63\x1a\x21\x62\x36\xc0\xe5\ -\x2e\xff\x11\x08\x2f\xea\xe8\x3d\xc1\xd4\x90\xd2\xfa\x6a\x75\x6f\ -\xac\x79\xcc\xc2\xc5\xf6\x13\xa1\xce\x8e\xd3\x0d\x59\x33\xe7\x5c\ -\x05\x51\x3e\x6e\xb4\x66\x02\xa6\xf7\x21\x25\xb9\xb3\xfd\x74\x4b\ -\x2c\x79\x62\x7a\x05\x96\xad\x5c\x37\x0f\x10\x47\x01\x24\xab\xe8\ -\x7d\xcd\x75\xde\xb5\xb0\x60\x76\x16\x2f\xf2\xdd\xe5\xbf\x20\xc2\ -\x73\x6a\x8e\x09\x0f\xb5\x1c\xf0\xee\x1d\xea\x5a\x31\x54\xc0\xd2\ -\xe2\xb5\xe3\x01\x71\x10\xea\x87\x67\xbc\x1d\x4c\x0d\x55\x60\x14\ -\x3c\x3c\x00\xb4\xd4\x7b\xb7\x81\xb1\x5b\xcd\x11\x63\x57\x81\xbb\ -\x72\xee\x50\xd7\x0e\x69\x00\x89\xa4\x67\x00\x64\xde\x26\xd0\x85\ -\x90\x2c\x6e\xab\xad\xed\x1b\x8e\x58\x8b\xc0\xf6\x6b\x29\xeb\x01\ -\x1c\x53\x71\xce\x30\xc9\x5d\x79\x79\x1e\x7b\xb4\x0b\xa3\x1a\x90\ -\xaf\x54\x2e\x20\xf0\x3a\xf5\x8d\x58\x62\x65\x73\x63\x4d\x57\x02\ -\x62\x2d\x41\x53\xd3\x8b\xfd\x32\x08\x37\x18\xff\xbe\xc9\x11\x30\ -\xd7\x39\xfe\x5f\x8f\x44\xbb\x2e\x9a\x01\x44\xe1\xf0\x6f\x75\xdc\ -\xfe\x96\x7a\xef\x89\x44\x84\x5a\x89\xd6\x46\xef\x67\x0c\x6c\x51\ -\x73\xcc\x78\xd2\xb5\x66\xcd\xb8\xc1\xae\x19\xd4\x80\x65\x4a\xc5\ -\x42\x10\x2d\x50\x51\x41\xc9\x61\x8f\x09\x3a\x2d\x45\x28\x2d\xb4\ -\x03\xc0\x85\x5b\x04\x61\x02\x5f\x4d\xfe\xc9\x60\xf1\x83\xb7\x00\ -\xc6\x2f\xb5\x04\xbd\xdc\x5a\xbf\xbb\x33\x61\x85\x16\xa3\xad\xb6\ -\xb6\x0f\x4c\xba\x1f\x8a\x1f\x53\x14\xc5\x70\xc8\x37\x34\x20\x4f\ -\x29\xf9\x2a\x98\xbf\xaf\xa2\x82\x32\xc8\x4f\x9b\xa6\xd2\x62\x64\ -\xd8\x7a\x5f\x01\xf8\x43\x15\x95\xd9\x23\x33\xf2\x8d\x62\x0d\x0d\ -\x70\x48\xc7\x83\xd0\x4e\x92\xde\x6c\x6d\xf4\x7e\x66\xa2\x46\x4b\ -\xe1\xf3\xf9\xc2\x60\xf2\xa9\x39\x02\x3f\x64\x14\x3b\xc8\x2b\xc0\ -\xcb\x35\x17\x13\x35\x9a\x25\x6e\xa4\x40\x24\xf4\x9a\x7f\x60\xf4\ -\x1a\x44\x18\x70\xa3\xc7\x9c\xaf\xe6\x24\xd1\x6b\xe6\xca\xb3\x1e\ -\xb9\xd9\x93\x4e\x82\xa0\x6e\xb5\xe9\x01\xa4\xe5\xe8\xe3\x22\x0c\ -\xe0\x6b\xce\xef\x02\x70\xaa\xa8\xbf\xb7\xf8\x76\x5e\xd0\xc7\x8d\ -\x76\x54\x55\x55\x49\x30\x34\x3f\x9c\x64\x11\xb1\x4e\x19\xf9\x0a\ -\xb0\xc8\x56\x17\x89\x70\xd4\x74\x75\x23\x04\x02\x6b\xb5\x33\x66\ -\xe9\x63\x0c\x0c\xc0\x4c\x75\x51\x4a\xfa\x30\x22\xe6\x4e\x01\x09\ -\x9d\x76\x9e\xa9\x0f\x89\x34\x80\xf8\x5e\x2d\x21\x47\xfd\xd8\x3f\ -\x18\x06\x28\xa8\xd7\x3e\x55\x1f\x63\x34\x0a\xa4\xaa\x0b\x04\x8c\ -\xf8\xb7\xbe\x69\x18\x17\xa1\x3d\x55\x1f\x32\xa4\x01\x82\x39\xae\ -\x35\xb6\xd1\x84\xb6\xda\xda\x7e\x00\x21\x15\xe5\x54\x14\x45\xdd\ -\xc1\x1b\x1a\xa0\x59\x24\x09\x09\x31\x2a\xbe\xf9\xad\x42\x84\x01\ -\xc4\xb8\xac\x09\x60\x8e\x68\x36\x77\x0a\xf2\x4a\x4a\x92\x00\xa8\ -\xd7\x03\x06\x7c\x3e\xdf\x80\x3a\x26\x72\x1e\x70\x7d\xa7\xf6\x76\ -\x19\xc8\xb0\x46\x9e\xf5\xb0\x75\xdb\xd3\x75\xd4\x65\x7d\x4c\xa4\ -\x01\xc0\x27\x1a\x82\x22\x7b\xce\x3b\x06\x49\x72\x9a\xa6\xcc\x38\ -\xaf\x0f\x31\x9a\x07\x74\xa8\x8b\x04\xba\xcf\x64\x59\x23\x06\x62\ -\xa1\xd1\xce\xc0\x39\x7d\x4c\x84\x01\x82\xa1\xd9\x6c\x64\x60\x81\ -\x3e\xe6\x4e\x81\x60\xd6\x6a\x27\x9c\x89\x88\xd1\x13\x03\x76\xe7\ -\x71\x00\xb7\xf6\xdf\x09\x98\x5b\xe8\x2e\x9f\x6c\x85\x40\x2b\xe1\ -\xf1\x78\x04\x83\x7e\xa8\x21\x19\x6d\xfa\xb8\x08\x03\x6e\xec\xad\ -\x1d\x57\x73\x21\xd2\x25\xba\x03\xf0\xd6\xfb\x5d\x39\xd0\xec\x28\ -\x53\x20\xd4\x9d\xf9\x8e\x3e\xce\x70\x3d\x80\x00\xdd\xe7\xaf\x2c\ -\x32\x55\xdd\x08\x80\x84\x5e\x33\xbf\xd1\xd6\x56\x15\xd2\xc7\x19\ -\x1a\xc0\x41\xb9\x1f\x80\x6a\xab\x99\x96\x14\x2a\xa5\x77\x9b\xaa\ -\xd0\x42\x78\x3c\x1e\x41\x4c\xab\x74\xf4\x1e\xa3\x58\x43\x03\x9a\ -\x1b\x6b\xba\x88\xe0\x57\x51\x49\x41\x69\xd7\x6f\x87\x8f\x5a\x1c\ -\x3f\xdb\xb5\x1a\xc0\x8c\x9b\x65\x02\x3e\x0d\x5e\xca\xf4\x1b\xc5\ -\x0e\xba\x2a\xcc\xe0\x3f\xaa\xcb\x04\x7e\x74\x89\xbb\xec\xeb\xa6\ -\xa9\xb4\x08\x8a\xa2\x38\x99\xf9\xd7\x6a\x8e\x99\x9f\x33\x6a\xfe\ -\x40\x14\x03\x9a\x0f\x54\xbf\x49\xac\xe9\x0c\x9d\x36\xc2\x66\x73\ -\x64\x5a\x87\x1e\x99\x56\x09\xed\x67\x6f\x77\x4a\x88\xb7\x0f\x16\ -\x1f\x6d\x67\x88\xa5\xc0\x26\x2d\x45\x6b\x5d\x4a\x79\xc4\xba\xda\ -\x68\x41\xde\xea\xca\x09\x04\x7a\x52\x43\x32\x7e\xd3\xd8\x58\x13\ -\x31\x05\xbe\x89\xa8\x7b\x83\x2d\x07\xbc\x6d\x00\xbd\xa2\x8e\x67\ -\x89\x86\xa5\x45\xe5\x13\x13\x52\x6a\x01\x14\x45\x71\x3a\xfa\xe5\ -\x01\xa8\xce\x10\x11\xf0\x5e\xf7\x04\xf1\x42\xb4\xeb\x86\xde\x1d\ -\x96\xb6\xc7\x75\xab\xab\x53\x84\x03\xf5\x85\x85\x3f\xd3\x1f\x8e\ -\xfa\xaf\xa2\x57\xa6\x6f\x03\x61\x91\x8a\x0a\x92\xe0\x8a\xa1\x0e\ -\x55\x0e\x69\x80\xbf\x61\xc7\xe7\x2c\x71\x3f\x80\x7e\x15\x3d\x3f\ -\x78\x57\xdf\x4b\x18\xa1\xb3\xc6\x43\xc1\xb5\xaa\xe2\x11\x00\x0f\ -\xab\x39\x62\xac\x8f\xe5\xcc\x52\x4c\x47\x64\x3a\x3b\x4e\x5f\xcc\ -\x9a\x39\xe7\x13\x10\x15\xdf\xba\x01\x30\x67\xda\x37\xe6\x4e\xca\ -\xc9\xce\xf2\xb7\xb7\xb7\x87\xe3\x56\x6d\x0e\xc8\xb5\xb2\xfc\xe7\ -\x0c\x6c\x83\xea\xc7\x20\xc2\xf3\xfe\x3a\xaf\x7e\x67\xdb\x10\x31\ -\x9f\x11\xea\xec\x78\xf7\xbd\xac\x59\x39\x77\x01\xf8\xde\xad\x1b\ -\x01\x39\x7d\x32\x79\xe1\xd7\xbe\x35\xef\xb5\xf3\x67\x4e\x5d\x8d\ -\x47\x79\xa2\x50\x14\xc5\x99\x39\x73\xfe\xcb\x00\x36\x41\xdb\x12\ -\x0f\x07\x2f\x65\x96\x9e\x3f\x7f\x24\xa6\x33\x83\x43\xbe\x02\x6a\ -\x64\x50\xef\x26\x5c\x3f\x9e\x76\x1b\x84\x45\x8e\x81\xf0\xc9\x7c\ -\xa5\x72\x76\x3c\xb9\x12\x81\xab\xf8\xe1\x7b\x7a\xc3\x69\xad\x00\ -\xca\x74\x55\x67\x83\xe1\xd0\x03\x83\x8d\xf9\x46\x88\xfb\x1d\x56\ -\x14\xc5\xd6\x23\x33\xfe\x40\xe0\x0d\xba\xaa\x20\x80\xed\x24\xed\ -\x5b\xfc\x0d\x3b\x3e\x8f\x37\x6f\x2c\xc8\x55\x36\xa4\xa4\xca\xcb\ -\x3f\x65\xc6\x46\x10\xbe\xac\xad\xe5\x26\x16\xb6\xd5\x2d\xbe\x9d\ -\x5f\xc4\x93\x73\xd8\x9d\x98\xcb\x5d\x5e\xc6\x84\xed\x00\x1c\xba\ -\xaa\x2b\x44\x78\xd6\x96\x74\x6d\x6b\x3c\x07\x16\xa3\x21\x2f\xcf\ -\x63\x77\x4c\xb8\x58\x02\xa6\xcd\x50\x9f\x57\xba\x05\xde\x9a\x21\ -\x02\x4f\xf8\x7c\xbe\xb8\xfb\xa2\x84\x7a\x71\x97\xbb\x6c\x21\x13\ -\xd5\x03\x18\x1f\xa9\x09\x3d\x04\x1c\x02\x70\xc8\x96\x72\xcd\x1f\ -\xaf\x19\x8a\xa2\x38\xbb\xc3\x19\x0b\x05\xf1\x72\x00\x2b\x00\x18\ -\x4d\xc3\x83\xc4\x58\xef\xaf\xf7\x56\x0f\x47\x3f\x60\xc2\x30\xe6\ -\x5a\x51\x3a\x85\xed\xb6\xe7\x01\xb8\xa3\x84\x05\x09\x38\xc2\x84\ -\xbf\x32\xd3\x07\x36\x19\xfe\x88\x25\x77\x3b\xc6\x25\x5f\x91\x14\ -\x08\xf7\x0f\xa4\xa6\x12\xfa\xd3\x29\x2c\xa6\x0a\xc2\x74\x66\xca\ -\x05\x51\x01\xc0\x69\x51\x72\x9e\x24\x81\xf5\x7e\x9f\xf7\x54\x22\ -\xfa\x4d\x1b\xc7\x5d\xab\x2a\x0a\x99\xf9\xf7\x00\xac\xed\x0c\x09\ -\x5d\x00\xff\x2a\x83\x02\xde\xe1\x34\xf9\xc8\x74\x26\xe2\xfa\x61\ -\xea\xae\x15\x20\xde\x08\xe0\xdb\x66\xe6\x06\xd0\x09\x60\x6b\x30\ -\x35\x54\x6d\xe6\x19\x45\xcb\x66\x72\x05\x2b\x2b\x66\x31\x50\xc2\ -\xe0\x22\x00\xd3\x87\x93\x83\x80\x4f\x25\xe8\x75\xc1\x72\x4f\xee\ -\xec\xc9\x6f\x0d\xe7\xff\x00\x31\xdc\xc3\x7a\xb8\x56\x94\x4e\x91\ -\x0e\xdb\x62\x02\xcd\x02\xe4\x0c\x30\x4d\x05\x90\x0e\x20\x0d\xd7\ -\x77\x6e\xbe\x00\x10\x00\xe8\x9f\x00\x9f\x63\xe0\x1c\x8b\xf0\x91\ -\x56\xdf\xee\x0e\x8c\x92\xe3\xb8\x63\x18\xc3\x18\xfe\x37\xf1\x1f\ -\x38\xf1\xe0\xe7\x81\x02\x5e\x62\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\xcd\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\xff\xca\x50\x41\x83\x10\x90\ -\xb1\x24\x9d\x31\x70\x2f\x9b\xfe\x75\x26\x74\xaf\xe7\xbd\xd7\xf3\ -\x96\x1b\xce\xf2\xf8\x1f\x08\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ -\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ -\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ -\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x6d\x1f\ -\xe0\x28\x8f\xd7\x5f\xe3\x33\xf1\x0b\x38\x66\xae\xf2\x3e\x00\x00\ -\x00\x00\x00\x00\x00\x6c\xe2\x03\x9c\x6d\x0b\xf4\x94\x3b\x8d\x4b\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x30\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\xc2\x30\x18\x05\xe1\x67\x86\x48\x87\x94\x99\x58\x21\ -\x15\x13\xb1\x05\x33\x45\xa1\x61\x0b\x53\x80\xa8\xa0\xb2\x9d\x43\ -\xe2\xbe\x2a\xc5\x2f\x78\xbe\x44\xd2\x3f\x2b\xa3\xff\x60\x5d\x6f\ -\xa7\x94\x5c\x92\x24\x35\xe7\x79\x3e\x5e\x7b\xde\xb7\x3a\x8c\xfc\ -\xf1\x24\x79\x3d\x66\x4a\x32\xbd\x1f\xd6\xf3\xbe\xd1\xf8\x00\xcf\ -\xc7\x7c\xfa\xee\x75\xdf\x64\x8f\x00\x3f\xcd\x00\xf4\x00\x9a\x01\ -\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\ -\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\ -\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\ -\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ -\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ -\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ -\x00\xda\x1e\x01\xee\x5f\xbe\x7b\xdd\x37\x19\x1f\xa0\x66\x49\xc9\ -\x96\x92\x2d\x35\x4b\xf7\x7b\x49\x6a\xf0\x00\xc5\x3d\x1c\x34\xe1\ -\xa3\xf7\x6f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x2c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xde\x49\x44\x41\x54\x78\x9c\xed\ -\x98\xcf\x6b\x5c\x55\x14\xc7\x3f\xe7\xbe\x34\x34\x91\x8a\x60\x71\ -\x93\xb6\x2e\xb2\xd0\x90\x22\xc6\x42\x17\xad\x59\xc4\xa6\x69\x0a\ -\x5a\x35\x31\x0b\x17\x22\x4d\x13\xf0\x1f\x10\x7f\x40\x91\xa0\x82\ -\xba\x50\x0a\x2e\x34\x9d\x69\x04\x89\x05\x33\x9d\x74\x84\x9a\x32\ -\x33\x29\x23\xe2\xaa\x36\xe9\xaa\x31\x5d\x04\x6d\x2b\x88\xa6\x0b\ -\x9b\xd2\x40\x66\xe6\x1d\x17\x49\x63\xdf\x9b\x37\xc9\x64\x66\xde\ -\x34\xda\xfb\x59\xbe\xf3\xee\x79\xdf\x73\xef\xb9\xe7\xbe\x7b\xc0\ -\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\xf2\x60\ -\x21\xfe\x07\x9d\x3d\xfd\xef\x89\x31\xc7\x51\x1c\xc0\x05\xb4\xf6\ -\xb2\xaa\x8a\x00\x06\x21\xaf\xae\xfb\x7e\x3a\x7e\x6a\xe8\x5e\x63\ -\x5d\xc1\xdb\xb2\x1a\x3c\x80\xa9\x85\xc2\x9a\xa0\x38\x22\xe6\x38\ -\xe0\x99\x80\xff\x4f\x80\x65\x52\x30\x01\xaa\xee\x07\xa0\xff\xf5\ -\xb4\x0f\x40\x75\x39\x36\x2f\x05\x35\x00\xe0\x50\x4f\x7f\x47\x5e\ -\x4c\x42\x60\x9b\xc7\x05\xa8\x2c\xd7\x85\xcd\x8b\xaa\x41\xc4\x13\ -\x97\xc2\x02\xc2\x91\x74\x2c\x92\xf1\xbf\x1e\x38\x01\x00\x5d\x7d\ -\x03\x7b\x34\xcf\x79\x84\xed\xfe\x2f\x80\x71\x37\x5f\x6d\x14\x40\ -\x0d\xfe\x98\x94\x79\x71\xe8\x4e\x8e\x45\x2e\x15\x1b\x55\x94\xee\ -\xbe\xfe\x27\xf2\xae\x49\x01\x3b\xbd\x4e\x55\x11\xd9\x6c\x99\x50\ -\x18\x3c\x5c\x73\x8c\xdb\x75\x7e\xec\xd4\x6c\xb1\x41\x6b\x4e\x00\ -\x40\xd7\x8b\x47\x77\x6a\x9d\x93\x04\x9e\xf4\x99\x94\xcd\xb3\x1d\ -\x82\x82\xff\x45\x72\xf9\xae\x64\x62\xe4\xfa\x7a\x03\xd7\x24\x99\ -\x18\xb9\x9e\xad\x37\xed\xc0\xcf\x3e\x93\x80\x3a\x41\x63\x6a\x87\ -\xb0\xa2\xc1\x1f\xfc\xc5\x6c\xbd\x69\x5f\x2f\x78\x28\xf1\x18\xcc\ -\x9c\x1e\x9e\x6f\xc8\xba\xcf\x21\x5c\x28\x22\xa0\xe6\x08\x08\xb8\ -\x4e\x40\x12\x4f\x36\x64\xdd\x03\x99\xd3\xc3\xf3\xa5\xf8\x29\x59\ -\xfc\xec\xec\xf4\xd2\xae\xbd\x4f\x7d\xeb\x64\x4d\x2b\xd0\xe2\x91\ -\x02\xa6\x84\xdd\x54\x45\x44\x8a\x7c\x33\x5e\x77\xa7\xa1\xf7\xdc\ -\xb9\x2f\xef\x94\xea\x69\x43\xab\xf7\xeb\xe5\xcb\xb9\x5d\x8f\xbd\ -\x70\xc6\x69\x5c\x68\x02\x9e\x09\x52\x15\x36\x72\xf7\xd7\xb6\x90\ -\xe8\x23\xe6\xef\xd7\x13\x89\x91\xec\x06\xfd\x95\xa7\xa3\xb3\x77\ -\xe0\x63\x81\x37\x03\x1c\xba\x1a\xd6\x19\x29\x08\x1a\x10\xbc\xc8\ -\x27\xa9\xd8\xc9\xb7\x29\xe3\xbb\x65\xef\xdf\xb9\x99\xa9\x54\x73\ -\x4b\xdb\x22\x22\x07\xfd\x72\xc2\xc8\x85\xa2\x2b\xaf\xfa\x56\xea\ -\x4c\x64\xa8\x70\x44\x69\x54\x54\xc0\xe6\x66\xa6\x7f\x6a\x6e\x6d\ -\xfb\x1d\xe4\x79\xbc\xd9\x54\xd5\x19\x10\x10\x2d\x0c\xde\x15\x65\ -\x30\x15\x8f\x7e\x5e\xa1\xef\xca\xe9\xec\x1d\xec\x15\xf4\x1b\xa0\ -\xde\x67\xaa\xf8\x5f\x41\x51\x13\x90\x52\x4b\x2a\xbc\x9a\x8e\x45\ -\xe2\x95\xf8\x86\x2a\xae\xd4\x81\x9e\xc1\x4e\x23\x7a\x16\x78\xc8\ -\x6b\x51\x85\xf2\xfe\x1a\x15\x8c\x14\x6a\xbc\x8d\xe8\x4b\xa9\x58\ -\x74\xb2\x3c\xa5\x5e\xaa\x9a\xaa\x87\xfa\x8e\xed\x75\x5d\xf9\x1e\ -\x78\xd4\x63\x50\x14\xd9\x60\x26\x28\x06\x29\xd0\x77\xd3\x55\x39\ -\x3c\x19\x3f\x79\xb1\x32\xa5\xff\x52\xf5\x6a\xd5\xf9\xf2\x40\x8b\ -\x18\x52\x40\x93\xcf\x54\xfa\x76\x08\xb8\xd1\x01\x37\xd4\xa5\x2b\ -\x3d\x1e\x99\xa9\x82\xcc\x55\xaa\xde\x10\x49\x8f\x47\x66\xf2\xaa\ -\xfb\x81\xab\x3e\x53\xf0\x11\xe6\x43\x09\x0c\xfe\xaa\x1a\xb3\xbf\ -\xda\xc1\x43\x48\x1d\xa1\x0b\xf1\xe8\x6f\xe2\xd6\xb5\x2b\x4c\x79\ -\x0c\xcb\x29\xbd\xd6\xc9\xe3\xf8\x0b\x9e\xc2\x54\x9d\xc9\x3f\x9b\ -\x1e\x1b\xbe\x16\x82\xd4\xf0\x5a\x62\xc9\xf1\x2f\xfe\xdc\xb2\x75\ -\xb1\x03\xe5\x07\xbf\x4d\x03\x27\x21\xf0\x4e\x91\xd9\xb2\x75\xb1\ -\x63\x62\x6c\xe4\xaf\x10\x24\x02\x21\xf7\x04\x27\x46\x47\x6f\x65\ -\x1f\xce\x75\x23\xfa\xdd\xbd\xcf\x57\x96\xd8\x11\x41\x64\x35\x2b\ -\xbc\x59\x2f\x90\xc8\x6e\xcb\x1d\x9e\x18\x1d\xbd\x15\xa6\xc6\xd0\ -\x6f\x72\xcb\xf7\x87\x23\x31\xa7\x71\xe1\x71\xe0\x69\x9f\x59\x08\ -\x2c\xc4\xfa\x55\xf6\xe6\x8e\xd7\x32\x67\x4f\x2c\x85\xad\xaf\x26\ -\x5d\xe1\x4c\x66\x28\xb7\x6f\x77\x53\xbf\x22\x9f\xad\xff\xb6\x7e\ -\xba\x6f\xf7\x8e\x63\x99\xcc\x50\x2e\x7c\x65\xb5\xbd\xc3\x02\xc8\ -\xc1\x57\x06\xde\x41\xf9\x30\xd0\xa8\xfa\x6e\x32\x1e\xfd\x88\x1a\ -\x36\x1c\x6b\xde\xcc\x98\xbb\x32\xf5\x63\x73\x6b\xdb\x1f\x2b\xf7\ -\x87\xbb\xa8\x28\x6f\x24\xe3\xd1\x13\xb5\xd6\x73\x5f\xba\x39\x73\ -\x57\xa6\x2f\x35\xb7\xee\x69\x64\xb9\xcf\x78\x5b\x94\xa3\xc9\x78\ -\xe4\xeb\xfb\xa1\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\ -\x16\x8b\xc5\xf2\xa0\xf1\x0f\x64\x76\x37\x12\x6f\xd4\x61\x03\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xc8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xb1\x0d\x83\x40\x10\x44\xd1\xbf\x4b\x0f\x96\x08\x08\xdc\x09\ -\x9d\x10\x90\xb8\x24\x02\xc7\xae\x81\x6e\x08\x1c\x20\xd1\x03\xb7\ -\x8e\x0e\x59\x42\x22\xe3\x2e\x99\x97\x8d\xb4\xd2\x4c\xb0\x20\x22\ -\x22\x52\x99\xfd\x87\x88\x30\xa0\xb9\xb9\x73\x37\xb3\x38\x0d\x58\ -\x96\x6f\x6f\xce\x07\x68\x6f\x1e\xb0\x85\x33\x3c\xbb\x6e\x06\xf0\ -\x63\x89\x33\x15\x28\x07\x78\x58\xe2\x9d\x83\x5f\x5d\x96\x70\x0c\ -\x88\xc4\x0b\x58\x0b\x74\x6e\x61\x31\xe6\x50\xfd\x09\x45\x44\x44\ -\xaa\xfb\x01\x02\x66\x1a\x07\xaf\xc1\xa8\xac\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x63\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x15\x49\x44\x41\x54\x78\x9c\xed\ -\x99\x5f\x48\x53\x61\x18\xc6\x9f\xef\x9c\xcd\xe9\xa0\x14\x2b\x92\ -\xbc\x52\x8c\xae\xba\xda\x99\x56\x26\x44\x04\xa1\x37\x15\x61\xd1\ -\x55\x46\xe2\x51\x6b\xb3\x24\xe8\x22\x68\x17\x75\x17\x99\x6d\x91\ -\x73\x81\x7a\x11\x12\x49\x10\x05\x26\x04\xd9\x45\x65\xe5\x66\x94\ -\x41\x08\xf6\xe7\xa2\x34\x44\x4b\x34\x1c\xfb\xfb\x76\x63\x31\xb7\ -\x63\x43\xf0\xfb\x8e\xd0\xf7\xbb\xdb\xfb\xc2\x9e\xe7\x7b\xce\xbb\ -\x9d\x77\x67\x80\x44\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\ -\x92\xff\x0d\xc6\x5b\x40\xd3\xbd\xbd\x00\x8e\x01\x00\x63\x38\x31\ -\xec\x77\xf7\xf0\xd6\x5c\x09\x5c\x03\xd8\x53\xd7\x9d\xfb\xcb\x36\ -\x1f\x4e\xad\x11\xd1\xde\x50\xa0\x65\x90\xa7\xee\x4a\x50\x78\xbe\ -\xf9\x94\x7d\xc1\x92\x5e\x63\x8c\x3d\xd1\x9a\xda\x4a\x79\xea\xae\ -\x04\x11\x1f\x01\x32\xaa\xdb\x62\xe1\xf5\xcf\xbb\xce\xcf\xf3\xd6\ -\xcf\x06\xd7\x09\x00\x80\x92\x1f\x45\x19\x53\x00\x00\x11\x6b\xde\ -\x1c\x3c\x1e\xee\xfa\xd9\xe0\x6e\xa0\xaf\xef\x48\x42\xcd\x41\xbe\ -\x51\x4f\xfb\xbe\x21\xc1\x5b\x3f\x1b\x42\xae\xc0\x2b\x9f\x7b\x2e\ -\xa9\xaa\x5b\x8d\x7a\x9a\xee\x7d\x26\xc2\xc3\x72\x08\x1b\xc1\x91\ -\x9b\xa7\xc6\x19\x68\x9f\x41\xab\xd2\xa1\xfb\xae\x88\xf2\x91\x8e\ -\x2a\x52\x6c\x22\x34\xf0\x79\x8b\xb3\x7a\x06\x40\x4d\x6a\x9d\x01\ -\xbb\x8a\x9d\xd5\xe3\x13\xc1\x47\xa3\x22\xfd\x2c\x6a\x8b\xc7\xd9\ -\xe8\xeb\x21\xa2\xe3\x19\x0d\x86\x8a\xa0\xdf\xfd\x5a\xa4\x17\x53\ -\x02\x00\x00\x4d\xf7\x7d\x04\x28\x63\x1f\x48\x58\x59\xf1\x9b\x1b\ -\xae\x09\x51\x3e\x4c\x0b\x00\x58\x7e\x47\xb0\xda\xe3\xf6\xa1\x6b\ -\xad\x61\xa3\xde\x6a\x63\xea\x7d\x98\xc8\x96\x63\x54\x8f\x2d\x58\ -\x16\x00\x12\x72\x71\x4c\x0d\x20\x14\xd0\x63\x44\xd1\x4d\x46\x3d\ -\x4d\xf7\xfd\x14\xe1\xc1\xf4\x4d\x2c\x14\x38\x37\x0d\x46\xdb\x0d\ -\x5a\xf9\x9a\xee\xbd\xc3\x5b\xdf\xf4\x00\x00\x20\xe8\x6f\x79\x0f\ -\xd0\x41\x83\xd6\x51\xde\xda\x6b\x22\x00\x00\x20\x52\xc6\xcc\xd0\ -\x5d\x13\x01\x54\xd4\xb7\x6f\x66\x8c\xfa\x33\x1a\x0c\x2f\x78\x6b\ -\x9b\x1e\x80\xa3\xa1\xd3\x9e\x50\x95\x07\x00\x4a\x52\xeb\x8c\xd1\ -\xa5\xa0\xdf\x5d\xc9\x5b\xdf\xd4\x00\x6a\x6b\xef\xaa\x8c\x45\x7a\ -\x01\x94\xa7\xd6\x09\xb8\x35\xec\x77\x7b\x44\x78\x30\x35\x80\x4f\ -\x85\x93\x57\x01\x1c\x48\x2b\x0f\xac\x2b\x9a\x69\x06\x98\xe1\x92\ -\xb4\xda\x98\xb6\x09\x3a\x75\x5f\x0b\x81\xda\x53\x6b\x04\xbc\xcd\ -\x8d\x85\xab\x44\x3e\x29\x32\x25\x80\xf2\xc6\xeb\x87\x92\xc4\xee\ -\xa5\xe9\x7f\xb5\xb2\xf8\x8e\x21\x7f\xeb\x37\x91\x5e\x84\x07\xe0\ -\x68\x68\xaf\x60\x4c\x19\x04\x90\x97\x52\x9e\x4f\x2a\xc9\xdd\x23\ -\x1d\x67\xde\x89\xf6\x63\xf8\xbc\x8e\x17\x5a\x53\x5b\x29\x48\x79\ -\x08\x5a\x72\xf8\x38\xa0\x1c\x1e\xe9\x70\x0b\x3f\x3c\x20\xf0\x4b\ -\x70\xe7\xc9\xb6\x42\x24\x2d\xfd\x20\x2c\xdd\xfd\x19\xf4\x60\xe7\ -\xe9\xc7\xa2\x7c\xa4\x23\x64\x02\xca\x5c\x5e\x5b\x3c\x8a\xfb\x00\ -\xb6\xa5\xd6\x19\x70\x79\xd8\xef\xee\x12\xe1\x61\x39\xf8\x4f\x80\ -\xc7\xa3\x14\x44\xd1\x4d\x40\xd5\xd2\x06\xdd\x1e\xee\x74\x5d\xe4\ -\xae\x9f\x05\xee\x01\x38\x26\x37\x5e\xc0\xe2\x7f\x83\x29\x3c\x9d\ -\xcd\x61\xf5\xa2\xee\xf5\xff\x82\xeb\x5d\xa0\xcc\xe5\xb5\x15\x44\ -\x31\x0b\x20\xf7\x6f\x91\xd8\x87\x88\xaa\x56\x8e\x76\x34\x0b\xf9\ -\xbd\x9f\x0d\xae\x13\x90\x1f\xb1\x25\x01\xc4\xfe\xbc\x66\xc0\x94\ -\x45\x89\xd7\xac\x95\xc3\x03\x9c\x03\x08\x05\xf4\x18\x03\xea\x00\ -\x4c\x03\x18\x43\x32\xb1\xff\xa5\xff\xec\x17\x9e\x9a\x12\x89\x44\ -\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\xd9\xf8\x0d\x59\x9b\ -\xda\x0c\x1f\xf1\x22\x4f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x01\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3b\x49\x44\x41\x54\x58\x85\xed\ -\x97\x31\x4e\x02\x41\x14\x86\xbf\xb7\x81\xa5\x74\x69\x56\x0a\x43\ -\x34\xd9\x66\x2f\xe0\x09\x4c\xe4\x0e\x9c\x02\x6b\xb5\x90\x1e\x4e\ -\xc1\x19\x8c\x89\x27\xe0\x02\xdb\x6c\xc0\x80\xc5\x86\x06\x2c\x59\ -\xc8\x3e\x0b\x67\x0d\x2c\x62\xa1\xbb\xb1\x70\xfe\x6a\x32\x33\xc9\ -\xf7\x65\xa6\x79\x3f\xfc\xf7\x48\x71\x63\x3a\x9b\x5d\x3b\x2a\x37\ -\x0a\x97\x80\x57\x12\x67\x25\x30\xce\x44\x07\x17\xed\xf6\xd3\x51\ -\x81\x97\xd9\x6b\x1f\xd5\x5b\x60\x0d\x44\x28\x6f\xa5\xe0\x85\x13\ -\x20\x04\x1a\x88\xf4\xcf\xdb\x67\xf7\x07\x02\xd3\xf9\xbc\x23\x19\ -\x8f\xa0\xcf\xdb\x8d\xdb\x0d\x82\xd6\xa2\x14\xb8\x49\x1c\x27\x7e\ -\xad\x9e\x8e\x40\xae\x54\xb4\x93\xbf\x84\x93\x5f\x70\x32\x7a\xc0\ -\xba\x0a\x38\x40\x10\xb4\x16\xdb\x8d\xdb\x05\x52\x47\xa5\xf7\xc9\ -\xcd\x17\xe6\xcf\xa3\x2a\xe0\xbb\x12\x08\x91\x61\xed\x0b\x00\x5e\ -\x69\x7f\xfe\x5d\x32\x56\x40\xf3\x2b\x81\x3f\x89\x15\xb0\x02\x56\ -\xc0\x0a\x58\x01\x2b\x60\x05\xac\xc0\xae\xc0\xca\x4c\xaf\x55\x13\ -\x3d\x60\x79\x20\x20\x30\x06\xc2\x38\x4e\xfc\xaa\xd8\x71\x9c\xf8\ -\x28\xa1\x61\xed\x0b\x64\xa2\x03\xa0\x51\xab\xa7\xa3\x2a\x24\x26\ -\x93\xc9\xe9\xc7\x58\x8e\x9b\x89\x0e\xf3\xfd\x62\x31\x79\x40\xf5\ -\x0e\x48\x11\x22\x33\x40\xfe\x3e\x0e\x1e\x4a\x08\xb8\x47\x8b\x49\ -\x1e\x53\xcd\x7a\x66\x74\x6e\x16\xcf\x7f\x98\xa5\xa9\x66\xc3\x62\ -\x35\xb3\x79\x07\x25\xbf\x6e\x2c\x3a\x0b\x42\xe7\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xd3\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x85\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\xe8\x01\x51\x0a\x75\x20\x3a\ -\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x26\xb5\ -\x1e\xd9\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\x60\x3b\ -\x4a\x1b\x9c\x6e\xf5\x5c\x53\xc7\x24\x87\x0e\x7d\x96\x34\xe5\x5d\ -\xae\x8f\x4b\xb9\x7f\x87\xbb\x76\x6a\xa5\xcb\x27\xc9\xb1\xec\xeb\ -\xd8\x86\xb3\x03\x6c\xcd\xec\x00\x25\x65\x48\xf2\xec\xd0\x65\x69\ -\x53\x7d\x95\xa1\x77\x09\x00\xe0\x7f\xf8\x05\xda\xa9\x95\x2e\x9f\ -\xf8\x05\x7e\xf3\x0b\x00\x00\x00\x00\x00\x00\xb0\x11\x1f\x5d\xbc\ -\x24\x0f\x6c\x9f\x83\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x01\x8c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3e\x49\x44\x41\x54\x58\x85\xed\ -\xd2\xbf\x2b\x85\x51\x00\xc6\xf1\xef\xf3\xca\x62\x90\x52\xac\xfc\ -\x05\x14\xbd\xf7\x96\xcd\x24\x3f\x8a\x9b\x98\x58\x29\x7f\x80\xcd\ -\x24\x93\xc9\x2c\x52\x06\x03\x2f\x29\x25\x8b\x22\xf1\x8a\xa2\xcc\ -\x16\x65\xb1\xd0\x1d\xa4\xee\xbd\x8f\x81\x01\xc5\xeb\xde\x4d\xce\ -\x67\x3c\x3d\x3d\x3d\xa7\x73\x20\x08\x82\x20\xf8\xef\x94\x15\xc8\ -\x6f\x95\x97\x2d\x75\x95\xd1\xc4\x45\x41\x37\xbf\x29\xcd\x6f\xbb\ -\xcd\xf6\x3a\xe2\x29\x1d\xd6\x20\x92\xbf\xcb\x46\x59\x65\x46\x4d\ -\x40\x67\x1d\x3e\x89\x13\xf7\x66\xe5\x73\xdb\xee\xb2\x7d\x06\xf4\ -\x50\xa1\x39\x2b\x9f\x39\x20\x2a\x6b\x02\xd8\x04\x1a\x85\xf7\xe3\ -\xc4\x93\xdf\x65\xe3\x2d\x0f\x60\x1f\x01\xad\xc0\xe1\x4b\xa4\xbe\ -\x9f\x6e\xff\xab\x01\xa7\x63\x7a\x4e\xaf\x35\x0e\x5e\x04\xea\x85\ -\xd7\x72\x89\xe7\xb0\x3f\x3d\x5f\x9c\x78\x5a\xf2\x2e\xd0\x00\x5e\ -\x2f\x96\xd4\x77\x35\xa2\xc7\xac\xfe\xcc\x3f\xf0\x51\x2e\xf1\x0c\ -\x78\xe9\x6d\xb8\x57\x4b\x0f\xd1\xd4\xe5\x3d\xe5\xb8\xa3\xb2\x20\ -\x34\x0b\x80\x3d\x9f\x16\xa2\xb9\xac\x9b\xd7\x34\x00\x20\xbf\xe3\ -\x21\x57\xbc\x01\x34\x00\xc7\x88\x22\xa6\x1f\x28\x81\xa6\xd2\x82\ -\x56\xaa\xe9\xab\x7a\x00\x40\xbc\xe9\x6e\x45\xde\x03\x5a\xde\x8f\ -\x8a\x48\xa3\xe9\x88\x0e\xaa\xed\xaa\x69\x00\x40\xbc\xeb\x76\x95\ -\x7c\x0b\xdc\x19\x0d\x9d\x17\x74\x5d\x6b\x57\xed\x6c\x7d\xfd\x8c\ -\x41\x10\x04\xc1\x9f\xf3\x0a\x0d\x2b\x72\x05\x90\xf4\xef\x82\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x21\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ -\x97\xb1\x6b\x53\x51\x14\xc6\x7f\x5f\x5e\xe9\x22\x15\xb4\xc4\xfe\ -\x01\x1d\x4a\x47\x5d\x2c\x28\x2e\x79\xea\x10\x09\x54\x5e\xd7\x22\ -\xe4\xe9\x20\x98\xa9\x54\xff\x04\x33\x38\x18\xc1\xc5\x64\xd0\x0e\ -\x45\x94\x08\x85\x0c\x1a\xe2\x20\xa8\x75\xd1\x4d\xb7\xee\x6d\x51\ -\x90\xe0\x52\xc8\x3d\x0e\xbe\x17\x9f\x52\x5e\x89\x7d\x69\x45\xf3\ -\x4d\xf7\x9d\x7b\x38\xdf\xef\xde\x73\x79\xdc\x0b\xff\xbb\xf4\x7b\ -\xe0\xfc\xe5\xf2\x19\xa4\x9b\xc0\x1c\x90\xcf\xc8\x67\x1b\x58\xc7\ -\xac\xda\x6e\x36\x5e\x27\x27\xbc\xe4\x87\x1f\x94\x97\x84\x56\x81\ -\x19\xe0\x48\x46\xe6\x44\xb5\x66\x90\xae\x4c\xcf\x9e\xfa\xb6\xf1\ -\xe9\xfd\xdb\x78\xa2\xbf\x03\xfe\xc2\xb5\xb3\x72\xee\x15\xf0\x15\ -\xb3\x4a\xce\xa3\xf5\xfc\x49\xe3\x4b\x16\xee\x17\x17\xca\xc7\x5d\ -\x8f\x22\x52\x0d\x38\x8a\xd9\xb9\x78\x27\xc6\xfa\x24\xce\x2d\x03\ -\xc2\xac\xd2\x6e\x36\x56\xb2\x30\x8e\x15\x2d\x64\xc5\x0f\x42\xc9\ -\x78\x18\xb5\xb8\x04\x90\x4b\xe4\xcd\x01\xe4\x3c\x5a\x59\x9a\x27\ -\x65\xbd\x9d\xb8\xf6\xe9\x38\x96\x04\xc8\x27\x68\x87\xa2\xce\xb3\ -\x47\x9f\xa3\xe1\x89\xdd\x00\x0e\x45\x23\x80\x11\xc0\xa1\x03\x8c\ -\xed\x95\x70\x21\xb8\x7a\xdd\x99\xdd\x16\x4c\x0c\x52\xd8\xa0\x9b\ -\x93\x6e\xbd\x78\xfa\xe0\x7e\x5a\x5e\xea\x0e\x14\x4a\xe1\x94\x99\ -\xdd\x1b\xd4\x1c\x40\x30\x61\x66\xb5\x42\x29\x9c\xfa\x63\x80\x83\ -\x50\x2a\x40\x67\xad\xbe\x29\xe9\x86\x41\x77\xd0\xc2\x06\x5d\x49\ -\x95\xce\x5a\x7d\x33\x2d\x6f\xcf\x33\x10\xf5\x30\xb5\x8f\xfb\xd1\ -\xdf\xdd\x82\x11\xc0\x08\xe0\xa0\x01\xb6\xe1\xc7\x05\x72\x58\x66\ -\x85\xf9\xc5\xc9\x68\xb8\xb5\x1b\xc0\x3a\x80\xeb\x51\x1c\x16\x80\ -\xbc\xf1\xb8\xf6\xbb\x38\xf6\xf3\x47\x64\x56\x45\xba\x84\x54\xf3\ -\x83\x50\xd6\xdb\x69\x25\xee\x70\xfb\x52\x61\x7e\x71\x52\xde\x78\ -\x51\xc6\x5d\xc0\x61\x56\xed\x43\x25\x13\xfd\xa0\xbc\x24\x53\x95\ -\xe1\x9d\x0d\x87\xb1\xdc\x6e\xd6\xef\xc4\x81\x5f\x5e\x46\x1b\x1f\ -\x3f\xbc\x99\x9e\x3d\xd9\x41\xca\x03\xc7\xc8\xee\x75\xb4\x05\xbc\ -\xc4\x2c\x6c\x37\x1b\x8f\x33\xaa\xf9\x8f\xe8\x3b\xaa\x2b\x8c\x73\ -\x1f\xb4\x18\x18\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x01\xaa\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x5c\x49\x44\x41\x54\x58\x85\xed\ -\x94\x3f\x4b\x42\x51\x18\x87\x9f\x57\xad\x4d\xac\x21\x8a\x5a\x0c\ -\xb7\x6c\x72\x74\x70\x09\x6d\x68\x08\xba\xda\x16\x05\x1a\x41\xdf\ -\xa0\x49\xce\xd0\xd2\x27\xa8\x54\x70\x0a\x32\x8d\x86\x5a\x14\xa4\ -\xbe\x80\xd0\xe4\x94\xd4\x14\xd1\x90\x53\x43\xea\x3d\x4d\x5a\x8d\ -\xf7\x5c\xb8\x4b\xf7\xd9\x5e\x38\xe7\xf7\x3e\xbc\xe7\x0f\xf8\xf8\ -\xf8\xfc\x77\xc4\xe9\xfa\xb4\x55\xb0\x01\x06\xa3\xe1\xec\xfd\x4d\ -\xb5\xef\x56\x20\xe0\x64\x71\xb1\x58\x9c\x08\x4f\x05\x43\x1f\xb9\ -\x5c\x2e\xe8\xa9\x80\x52\xca\x46\xf4\xf6\xb8\xee\xdb\x91\xa1\xa7\ -\x02\x00\xad\x7a\xe5\x4a\xe0\x78\x5c\x67\xac\xc2\xa3\x1b\x01\xa3\ -\x11\x3e\x75\x3b\xed\x58\x3c\x91\x02\x96\x81\xf9\xd8\x4a\x62\xa1\ -\xd7\xed\xdc\x99\x64\x39\xbd\x84\x7f\x48\x5b\x05\x3d\x09\xd2\x1c\ -\x34\xaf\xcb\xe7\x4e\x33\x1c\x1f\xc1\x6f\x92\xab\x4b\x93\x09\x6a\ -\xe1\x2c\xb3\x95\x4f\x79\x2a\xa0\x94\xb2\x07\x81\xe9\xf0\x8f\x84\ -\x3c\x78\x2a\x00\x30\xc7\xfb\x17\xe8\x67\xd3\xfd\x6e\x05\xa4\x6f\ -\xcf\x94\x41\xa2\x08\x6f\x23\xad\xa3\x9e\x0a\x64\xb2\x85\x22\xe8\ -\x1d\xe0\x53\x84\x8d\xf6\x75\xe5\xc5\x69\x86\xf1\x2b\xc8\x58\xf9\ -\x5d\x8d\x54\x01\x5b\x44\x36\x9b\xf5\xd2\xad\x49\x8e\xd1\x3f\x90\ -\xce\xe6\xd7\x40\x6a\x40\x00\xe4\xb0\xd5\x28\x5d\x98\xe4\x80\xc1\ -\x11\xac\x5b\xfb\x71\xb4\x34\x80\x10\x22\x27\xad\x46\xe9\xd4\xb4\ -\xb9\x89\x80\xd8\x50\x03\x22\x1a\x2e\x93\xf1\xc5\x23\x37\xcd\x01\ -\x42\xce\xb7\xe8\x57\x0d\xbd\x61\x78\xb8\xa7\x94\xb2\xdd\x0a\xf8\ -\xf8\xf8\xf8\x7c\x03\xa5\xd7\x5e\xc1\x97\x2b\x14\xb6\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x31\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe3\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x11\x82\x40\x18\x05\xe1\xf7\x5b\x04\xb5\x58\x07\x2d\x18\ -\x59\x91\x5d\x50\x87\x75\x10\x59\x05\x18\xa0\x99\x46\x77\xb0\xce\ -\xb8\x5f\x74\xc1\x0d\xbc\xdb\x44\xd2\x3f\xab\xbd\x7f\x70\x9e\xd6\ -\x71\xcd\x7a\xdb\x7e\x56\xd7\xfb\x58\x53\xcf\xfb\xad\x4e\x7b\x7e\ -\x3c\x49\x5e\x8f\x19\x92\x0c\xef\x87\xf5\xbc\xdf\x6a\xf7\x00\xd9\ -\x1e\xf3\xe9\xdc\xeb\x7e\x93\x23\x02\xfc\x34\x03\xd0\x03\x68\x06\ -\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\ -\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\ -\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\ -\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\ -\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\ -\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\ -\x03\x68\x47\x04\x78\x7c\x39\xf7\xba\xdf\x64\xff\x00\x4b\x5d\xaa\ -\x32\x57\x65\xce\x52\x97\xee\xf7\x25\xa9\xc1\x13\x85\x02\x26\x2c\ -\x67\x7d\xc5\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x02\xda\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8c\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3b\x6f\x13\x41\x14\x46\xcf\xb5\x13\x42\x13\xba\xfc\x92\x48\ -\xb6\x25\x1a\x5a\xba\x3c\x44\xe4\x90\x80\x44\x05\x05\x2d\x1d\x2d\ -\xff\x00\x24\x5c\x21\x1e\x79\x08\x84\x57\x34\xd4\x74\x80\x5b\x7e\ -\x07\x12\x12\x0d\x42\x72\x3e\x0a\x84\x64\x36\xeb\x38\xde\x9d\x99\ -\x9d\x59\xfb\x96\xb3\x77\x3f\xcd\x39\xda\x5d\x5b\x57\x03\xcb\x5a\ -\xd6\xb2\x16\xb9\xac\xee\x0d\xf8\xae\x4e\xa6\x2d\x93\x9e\x48\xfc\ -\x68\xb7\xed\xc1\xe7\x2d\xfb\x36\x79\x7d\xa5\xae\x8d\x85\xa8\xee\ -\x50\x7d\xa4\x23\xa0\x65\x06\xe3\xb1\x9e\x03\xd7\x27\x7b\x5a\xf5\ -\x6c\xcd\x7f\x75\x87\xea\xc3\x5f\xf8\x7f\x6b\x2d\xe3\x5a\xbe\xaf\ -\x91\x02\x8a\xe0\x81\xb1\xb0\xc7\xf9\xde\xc6\xbd\x02\x17\xc0\xef\ -\x8f\x76\xec\x43\xbe\xbf\x51\x1f\xc1\x19\xf0\xef\x8a\xee\x69\x8c\ -\x80\x32\xf0\xd0\x10\x01\x65\xe1\xa1\x01\x02\xaa\xc0\x43\xe2\x02\ -\xaa\xc2\x43\xc2\x02\x5c\xc0\x43\xa2\x02\x5c\xc1\x43\x82\x02\x5c\ -\xc2\x43\x62\x02\x5c\xc3\x43\x42\x02\x7c\xc0\x43\x22\x02\x7c\xc1\ -\x43\x02\x02\x7c\xc2\x43\xe4\x02\x7c\xc3\x43\xc4\x02\x42\xc0\x43\ -\xa4\x02\x42\xc1\x43\x84\x02\x5c\xc3\x77\x86\xba\x05\x7a\x06\x80\ -\xec\xfe\x68\xd7\xb2\xc9\xeb\x51\x4d\x84\x5c\xc3\x77\x87\xea\x1b\ -\x3a\x35\xd8\x30\xd8\xc0\x34\xc8\xf7\x44\x23\xc0\x07\x7c\x41\xde\ -\xb9\x8a\x42\x40\x20\xf8\xb3\x96\xd9\xc3\x7c\x6f\xed\x02\x42\xc1\ -\x1b\x76\xf7\xcb\xb6\xbd\xcd\xf7\xd7\xfa\x11\x0c\x0a\xbf\x63\x47\ -\x45\xf7\xd4\x26\x20\x06\x78\xa8\x49\x40\x2c\xf0\x50\x83\x80\x98\ -\xe0\x21\xb0\x80\xd8\xe0\x21\xa0\x80\x18\xe1\x21\x90\x80\x50\xf0\ -\x92\xdd\x19\xed\xda\xf1\x3c\x59\xde\x05\xc4\x0c\x0f\x9e\x05\xc4\ -\x0e\x0f\x1e\x05\xa4\x00\x0f\x9e\x04\xa4\x02\x0f\x1e\x04\xa4\x04\ -\x0f\x8e\x05\xa4\x06\x0f\x0e\x05\xa4\x08\x0f\x8e\x04\xa4\x0a\x0f\ -\x0e\x04\x04\x83\x37\x3b\x1c\x6d\xdb\xc9\xbc\x79\xbd\x4c\x7b\x67\ -\xd2\x53\xc0\xfd\x4c\x30\x76\xf8\x6e\xa6\x43\x49\x27\x5e\x66\x82\ -\x29\xc0\x23\xbd\x64\x06\x63\x29\x01\xb1\xc3\xf7\x86\x3a\x28\x80\ -\x77\x33\x13\x4c\x01\x5e\xe8\x55\x3e\xcf\xc9\x4c\x30\x69\xf8\xaa\ -\x33\xc1\xd8\xe1\x3b\xef\x75\xdb\x4c\xaf\xcf\xe5\xcd\xf8\xe9\xbc\ -\x94\x80\xa6\xc2\xc3\x25\xce\x0a\x87\x82\x07\x3b\x18\x6d\xdb\xe9\ -\xbc\x79\x55\xe0\x61\xc6\x13\x10\x12\xfe\xeb\x4e\x78\x78\xb8\x40\ -\x40\xf4\xf0\x99\xf6\x4d\x7a\x93\xcf\x9b\xf7\x35\x2a\x14\xb0\x28\ -\xf0\x00\xed\xfc\x42\x2f\xd3\x1e\xe8\x18\x47\xf0\x53\xf2\x4a\xc3\ -\xf7\x32\xed\xa1\xf3\x79\x65\x3f\xa0\xff\x3d\x01\x9b\x03\xad\xae\ -\x6c\xe8\x3b\xb0\x3e\xb1\x5c\x1a\x7e\x4a\x5e\x69\x78\xd7\x79\x90\ -\xfb\x27\xb8\x7e\x85\x36\xb0\x36\xb1\x54\xe9\x58\x4a\x41\x5e\xa5\ -\xcd\xba\xce\x83\x9c\x80\x4f\xf7\xec\x97\x61\x8f\x80\xdf\xc0\x4f\ -\x64\xfd\x2a\x67\x72\xf2\x79\x66\xb6\x5f\x65\xb3\xae\xf3\xa6\xd6\ -\xcd\x8f\x5a\xdb\x1c\x68\x35\xd6\xbc\x1b\x2f\x74\xd5\x65\xde\xb2\ -\x96\xb5\xc0\xf5\x07\xd6\x41\x4c\x2b\x6c\xde\x0f\x7f\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xee\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x0d\x00\x20\x00\x03\x31\x82\x7f\x91\x10\x84\x80\x8c\xf2\ -\xb8\x1a\xd8\x65\x63\x40\x6b\x9f\xbb\xf6\xb9\xb2\x61\xca\xf1\x1f\ -\x74\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\ -\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\ -\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\ -\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\ -\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ -\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ -\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ -\xad\x03\x74\x80\xd6\x01\x3a\x40\x7b\xd6\x8f\x07\xc5\x02\xeb\xa3\ -\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x0a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbc\x49\x44\x41\x54\x58\x85\xed\ -\x94\x3d\x6b\x14\x61\x14\x85\x9f\xf3\x6e\x84\x85\x80\x68\x23\x83\ -\x9b\x9d\x37\x0b\xfe\x00\x7f\x81\x9d\x28\x12\xb4\xd1\x52\x48\x2b\ -\x41\xf2\x1f\xf4\x0f\x88\x16\x96\x36\x16\x8a\x58\x69\xa1\x58\x5a\ -\x68\xa9\xbd\x98\xcc\xec\x46\xd6\x4a\x63\x12\x30\xc8\xce\xb1\xd8\ -\x0f\x96\x7c\xed\xce\xfa\x91\x66\x1e\x18\xb8\x33\x5c\xce\x39\xdc\ -\x79\xef\x0b\x15\x15\x15\x15\xc7\x8c\x86\xc5\x7a\x96\x7f\x03\x9d\ -\xfa\x3f\xb6\xfe\xbe\x18\xd3\xd3\x00\x61\xf4\x69\xac\xfe\xe7\xf6\ -\x63\x5e\xa3\x62\x2e\xa8\x85\x78\xdf\xef\x30\x98\x02\xe8\xfd\x95\ -\xc7\x14\xd8\x43\xab\x77\x73\x41\xad\xe1\xcb\xe8\x17\x00\x74\xbb\ -\xdd\xf9\xdd\xdd\x5f\xcf\x0d\x97\x06\x49\x0b\x81\xf9\x03\x0c\x12\ -\x0e\x20\x30\xaf\xea\xf5\x13\xd7\x93\x24\xd9\xd9\x37\x01\x80\x24\ -\x49\x76\xb6\xb6\x36\xaf\x0a\x3d\x1d\xa4\x0b\x7b\x43\x96\xb4\x57\ -\x5f\x43\x60\x3d\xd9\xde\xde\xbc\x36\x6e\xce\x61\xe2\xb6\x6b\x59\ -\xb6\xf1\x00\xf9\x96\x6d\x24\x15\x94\x9c\x84\x40\x85\x1d\x24\x81\ -\xf5\x30\xc6\xc6\x6d\x49\xbd\xbd\x7d\x07\x1e\x3c\x49\xbd\x18\x1b\ -\x2b\x48\x77\x25\x01\x04\x95\x98\x84\x40\x86\x20\x09\xc3\x9d\x18\ -\x1b\x2b\x07\x99\x0f\x7a\x8f\x26\xcb\xda\xab\x86\x7b\x00\x06\x0b\ -\x8a\xa3\xfa\x3d\x16\x56\xb0\x1a\x63\xf3\xfe\x84\xb0\x93\xc9\xb2\ -\xce\x4d\xe3\x47\x40\xad\xef\x71\x48\x08\x13\x10\x02\x7a\x82\xe5\ -\x18\x9b\x8f\x27\x69\x4f\x3d\xd6\x2c\xeb\x2c\x19\x3f\x03\xea\x18\ -\xa3\x7d\x21\x86\x07\xf6\xa7\xd0\x8d\x18\x17\x5e\x4e\xa3\x5b\xea\ -\x84\x7f\xce\xf3\x0b\xc1\x7a\x01\x9c\x44\x78\x70\x57\x80\x08\x18\ -\x01\x3f\x82\xbc\x94\xa6\xe9\xdb\x69\x35\x4b\xaf\xd8\xda\x5a\xe7\ -\xbc\x82\x5f\x03\x67\x40\x76\x7f\xd5\x00\x7d\x75\xc1\xe5\x56\x6b\ -\xe1\x43\x19\xbd\x99\x76\xbc\xdd\x6e\x9f\xeb\x15\x7a\x03\x5e\x1c\ -\xc8\xac\xd7\x82\x2f\x36\x9b\xcd\x4f\x65\xb5\x66\xbe\x64\xf2\x3c\ -\x3f\x5b\x58\x1b\x88\x8f\x01\x5f\x49\xd3\xf4\xcb\xac\x5a\x15\x15\ -\x15\x15\xc7\xca\x6f\xbc\xd7\xa4\x72\xc7\xdc\xd0\xf5\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x78\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x4d\x78\x9a\x1f\x0c\x83\x8c\ -\xe3\x91\x18\x68\xab\x00\x80\xb0\xde\x73\x6e\x72\x60\x25\xe3\x00\ -\xc0\x17\x1e\xbe\x17\x02\x30\xed\xb9\x5b\x96\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x20\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\xc2\x40\x14\x44\xc1\x35\x45\x38\x43\x72\x4d\xb4\xe0\ -\x88\x8a\xe8\x82\x9a\x2c\x93\xd0\x85\x09\x40\x44\x90\x7a\x90\xd8\ -\x89\x2e\xbb\xfd\x2f\xa9\xaa\x7f\x36\xa8\x8f\x97\xe5\x76\xca\x90\ -\x4b\x92\x64\xcb\x79\x9a\x8e\x57\xb1\xe3\x20\x3e\x4d\x92\xd7\xf1\ -\x63\x92\xf1\x1d\x02\x70\x01\x9e\xc7\x7f\x7a\xef\x4a\x06\xf8\x09\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ -\x0d\xa0\x07\x68\x32\xc0\xfd\xcb\x7b\x57\x2e\xc0\x96\x39\x43\xd6\ -\x0c\x59\xb3\x65\x66\x3b\xaa\xea\xaf\x3d\x00\x08\x2d\x0e\x52\x29\ -\x6c\xf3\x60\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x03\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb5\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5d\x68\x9b\x55\x18\xc7\x7f\xcf\x79\xfb\x81\x53\xe7\x6c\x07\ -\x8b\xd8\xb2\x59\xaa\x62\x41\x91\x35\xcd\xf4\xc2\xaf\x39\x36\x44\ -\xb6\x4e\xb0\x88\xc8\x9c\x0c\xd7\x74\xad\xe9\xaa\x20\x74\x78\x11\ -\x83\x43\x0b\x82\xc5\x34\xad\x26\x1b\x88\xa2\x57\x03\x8b\xed\x74\ -\x3a\x50\xba\x2b\xe9\xb2\x58\xbc\xb0\x14\x84\x0a\x9a\x36\x1d\xae\ -\x05\xc5\x6d\x36\xcb\x7b\x1e\x2f\x92\x7e\x66\xed\x5a\x9a\x7a\xb3\ -\xff\xe5\xf3\x3e\xe7\xfc\x7f\xcf\xe1\x3d\xe7\x3c\x07\x6e\x76\xc9\ -\x6a\x92\xeb\x9a\xbb\x2b\xad\x9b\xd9\x2f\x2a\xbb\x10\x2a\x11\x2a\ -\x50\x0c\xca\x18\x22\x49\x84\x73\x8e\xda\xde\xc1\xe8\xd1\x5f\x0b\ -\x0a\xe0\x6d\x0a\xfb\x50\x3a\x80\xa7\x56\x38\x6b\x5c\x54\x8f\xc5\ -\xa3\x47\xbf\x5f\x13\x40\x6d\x63\xf4\x0e\x91\xe9\x8f\x80\x17\x73\ -\xa1\x14\x48\xbf\x2a\x67\xd4\x71\x47\xf5\x5f\x93\x2a\xde\x60\xac\ -\xa6\xf1\x58\xb1\xdb\x8c\x61\xb7\x5a\xea\x11\xb6\xe6\xa6\xff\xc6\ -\x71\xdd\x43\x83\x27\xdb\x2e\xae\x1a\x60\x7b\x73\x77\xb5\xc9\xd8\ -\x3e\x44\x1f\x00\x52\x22\x04\x6f\xdd\x32\xf9\xc9\x40\x28\x94\x59\ -\xb6\xa4\x60\xd0\x78\x27\xca\x5f\x00\x39\x0e\x5a\x05\xfc\x6e\x60\ -\xdf\xf9\x68\xeb\xcf\x2b\x06\xf0\x1e\xf9\xa0\x0a\x5b\x34\x08\x6c\ -\x06\xbe\x72\x4a\x78\x79\xb0\xab\xf5\xef\x65\x8d\x17\xa9\x3a\x10\ -\x2e\xdd\x34\x4d\x0f\xc2\x21\xe0\x32\xc2\x63\x17\x3e\x6e\x1d\xba\ -\x21\xc0\x8e\x40\x78\x63\x26\xcd\x8f\x02\x35\x8a\x7e\x98\xf0\x4c\ -\xbd\x41\x28\x64\x57\x63\x3e\x27\x95\x3a\x7f\xb8\x5d\x91\x77\x81\ -\xa4\xaa\xeb\x4b\xc4\x5e\x4f\xcd\xcf\x30\x8b\x87\xb8\xd3\x44\x04\ -\x6a\x80\xfe\xb5\x99\x03\x88\xc6\xa3\xad\x1d\x22\x9c\x04\x2a\x8c\ -\x38\x9f\x83\x2e\x28\x7a\x01\x80\xcf\xdf\xe5\x45\x38\x80\xf0\xa7\ -\x6a\xe9\x81\xb5\x99\xcf\x41\x5c\x9e\x9c\x6c\x01\x46\x14\x76\x7a\ -\xfd\xe1\x67\x96\x04\xb0\xa2\xef\x01\xa8\xea\x3b\x89\x98\xff\xaf\ -\xb5\x9b\x67\x35\x7c\x2a\x94\x16\x78\x2b\x07\xd4\x31\x7f\x15\x66\ -\x01\x6a\x1b\x3b\xef\x42\x79\x1a\x98\xba\x3a\x35\x15\x2d\x94\xf9\ -\x8c\xe2\xd1\x40\x2f\x30\x02\x3c\xe8\xf3\x77\x3d\x94\x07\x20\x98\ -\xbd\x80\xa0\x7c\x3d\x7c\x2a\x94\x2e\x34\x00\x88\xa2\xda\x07\x60\ -\x45\x9f\xcb\x03\x40\xe4\x49\x00\x45\xbe\x2d\xbc\x79\x56\xd6\x98\ -\xef\xb2\x28\xb2\x33\x1f\x00\x2a\x01\x1c\x91\xdf\xd6\x0b\xa0\x84\ -\xcc\x28\x80\x42\x45\x1e\xc0\x4c\xd0\xc8\xb5\x54\xfe\xd0\xc2\xe8\ -\x52\xb1\x33\x33\xf7\xdd\x33\x3f\x62\xde\x39\xf0\xbf\x29\xf8\xf6\ -\x42\x00\x81\x31\x80\xb4\x38\x9e\xf5\xf2\xbc\xdd\x1a\x0f\x80\xc2\ -\xf8\xcc\x19\x33\xb7\x02\x2a\x7f\x00\x18\xcb\x3d\xeb\x05\x60\xae\ -\xb9\x55\x00\x02\xc9\xd9\xd8\xdc\x57\x1d\x00\x10\x91\x3d\xeb\x06\ -\x60\xd8\x0d\xa0\xf0\x43\x1e\x80\x5b\x24\xfd\x00\xaa\xfa\x6c\x6d\ -\x63\xb4\xb8\xf0\xf6\x2a\x56\x65\x1f\x80\xb1\x6e\x6f\x1e\xc0\x50\ -\x24\x30\x2e\x59\xb2\xcd\x30\xfd\x6a\xa1\xed\xbd\x47\x22\x7b\x73\ -\x97\xdc\x2f\xf1\x13\x6d\xb3\xbd\xc1\xc2\x5d\x60\x6d\x3b\x80\x08\ -\xc1\x1d\x81\xf0\xc6\x42\x99\xd7\x34\x04\x4b\xd4\x66\xef\x19\x81\ -\x63\x20\x7a\x5d\x80\xf8\x89\xb6\xb8\xc2\x17\xc0\x16\x37\xcd\x67\ -\x04\x83\x05\xd8\xa6\x2a\x1b\xee\x2c\x0f\xe7\xaa\x1f\x88\x47\x03\ -\xa7\xe7\x7f\xcd\x37\xd0\xd2\x16\xb2\x97\x46\xbd\x77\xa2\xfc\xfd\ -\xb5\x41\xa8\x78\x9b\x22\x6f\x22\xf8\x51\xc6\xdd\x62\x79\x69\x7e\ -\xf5\xb0\x44\x4b\xb6\xbd\xb9\xbb\xda\xb8\xee\x20\x50\x06\x7c\x79\ -\xc5\x71\x0e\x0e\xf7\xb4\xfc\xb3\x1a\xeb\x9a\x86\x60\xc9\x2d\x65\ -\xe5\x11\x81\xc3\xc0\x15\x83\x3c\x71\x3e\x1a\xb8\xb0\x38\x6f\xc9\ -\xa6\xd4\x77\x38\x72\x9f\x35\xb6\x0f\xb8\x5f\x91\x31\x81\xe0\x6d\ -\x9e\x4b\x9f\xae\xa4\x29\xad\xbb\x58\xf6\xbc\x55\x39\x2e\x70\x2f\ -\x90\x54\x35\xf5\x89\xd8\x6b\x3f\x5d\x2f\x7d\xd9\xb6\xfc\xe1\x57\ -\x3a\x37\x15\x95\x9a\x18\x48\x43\x2e\x94\x14\xa1\x1f\xe5\x0c\xd6\ -\x8c\x16\xd9\x74\xea\xaa\x2b\xd6\x29\x29\xf2\xa8\x61\xab\xb1\x76\ -\x0f\x62\xea\x73\xdd\x30\xc0\x59\x71\x9c\x83\xf1\x9e\x96\x89\xa5\ -\x3c\x56\xf4\x30\xf1\xf9\x23\x8f\x5a\xb4\x03\xf4\xf1\x95\xe4\x03\ -\x43\xaa\xb4\x27\x62\xad\x67\x6f\x94\xb8\xaa\xa7\xd9\x23\x4d\x9d\ -\xdb\x32\xd6\xd9\x8f\xb0\x0b\xcd\x3d\xcd\xc0\x01\x92\xd9\xe3\x55\ -\xcf\x59\x35\xbd\x89\x58\x60\x64\x35\xf3\xde\xdc\xfa\x0f\x80\xbd\ -\x5b\x45\x41\xb4\xc0\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x04\xe8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ -\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ -\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ -\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ -\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ -\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ -\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ -\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ -\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ -\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ -\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ -\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ -\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ -\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ -\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ -\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ -\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ -\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ -\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ -\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ -\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ -\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ -\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ -\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ -\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ -\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ -\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ -\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ -\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ -\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ -\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ -\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ -\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ -\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ -\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ -\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ -\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ -\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ -\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ -\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ -\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ -\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ -\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ -\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ -\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ -\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ -\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ -\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ -\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ -\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ -\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ -\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ -\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ -\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ -\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ -\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ -\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ -\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ -\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ -\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ -\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ -\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ -\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ -\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ -\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ -\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ -\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ -\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ -\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ -\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ -\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ -\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ -\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ -\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ -\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\x7b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\x2d\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xc9\x73\x5c\x57\x15\xc6\x7f\xdf\xb5\x49\x39\x09\x91\x83\x33\ -\x40\x15\x2b\xb6\x78\x48\x9c\x48\x3d\x24\x14\xc4\x8a\x63\xc9\x93\ -\x2c\x75\xab\xf2\x87\xb0\x0a\x0b\x58\x50\x5e\xb0\xc9\x12\xfe\x88\ -\x54\xab\x25\x92\x38\x65\x6b\x34\x09\xa0\x1e\x0c\x45\x18\x56\x29\ -\x2a\x95\x62\x45\x26\xb0\x6c\x63\x29\x46\xf7\xb0\xe8\x6e\xe8\x74\ -\xb7\xf4\xee\xeb\x7e\x4f\xea\x14\xfa\x96\xf7\x9e\x3e\xf7\x7c\xbf\ -\x3a\xe7\xf5\xeb\xa7\x27\x38\xd0\x81\x0e\xf4\xff\x2c\xf5\x5a\x3c\ -\x75\xc3\x1e\x7d\xf8\x2e\x3f\x94\xec\xb2\xc1\x11\xcc\xd6\xed\x6b\ -\xee\x67\xb5\x29\x7d\xb8\xd7\x05\xf6\xa3\xcc\x9b\xf6\x1d\x3d\xf0\ -\xaf\x21\xe5\x05\x9b\x5e\xba\xf6\xc8\x03\x5e\xbf\xf9\xaa\xee\x76\ -\xc6\x76\x01\x78\xf1\x97\xf6\xd8\x03\x6f\xbf\x92\x71\xba\x63\xeb\ -\xb6\x9c\x26\x2a\xd3\xaa\xa6\x56\x79\x02\x1a\x9b\xb3\x31\x27\x5b\ -\x02\x8e\x76\x6c\xbd\xcf\x11\x7d\xbf\x7a\x41\x1b\xed\x8b\xae\x33\ -\xc1\xf6\xb6\x7f\xad\x87\x79\x80\xa3\xe6\x6d\x31\xb7\x60\xd9\x04\ -\xeb\x4d\x54\xbb\x98\x07\x78\x86\x4d\xff\xa3\xce\xc5\x2e\x00\xa0\ -\xa9\x5d\xce\x18\x19\x56\x08\x11\xe6\x9b\xd2\x95\xce\x95\x2e\x00\ -\x1e\x1e\x8e\x38\x6b\xc4\xbc\x2d\xe6\xe7\x2d\x13\xb7\xc8\xb4\x94\ -\x29\xd9\x68\xb4\x79\xc0\x38\xd2\xb9\xd4\x05\x40\xd8\x6f\x02\xce\ -\x1c\xf1\x66\x4b\xc3\x00\x21\x53\xb2\x51\x39\x5b\x26\xca\x3c\x80\ -\xba\xbd\x75\x8f\x80\x77\x57\x81\xdb\x01\x67\xef\x3b\x84\x58\xe6\ -\x61\x03\xef\x7e\xda\xb9\xd8\x05\xa0\x3a\xab\x0f\x9c\x74\x8e\x70\ -\x08\xfb\x32\x0e\x4d\xf3\xd1\x6d\xdf\xd0\x06\xa6\x89\xea\xac\x3e\ -\xe8\xdc\xe8\x79\x1f\x00\x90\x9f\xb7\x8c\x37\x5b\x02\x46\x02\x0e\ -\xb8\xed\x4d\xaf\xd4\x8b\xaa\x07\xc4\x0e\xac\xec\xbc\x3d\x8f\xd9\ -\x32\xf0\x78\x40\xf8\x1d\x4c\xe7\xaa\x45\x55\x7a\x6d\xee\x08\x00\ -\x86\x13\x42\x92\xe6\x21\x02\x00\x0c\x17\x84\xa4\xcd\x43\x00\x00\ -\x80\xdc\x82\x65\xcd\xdb\x22\x81\x10\xcc\xeb\x6c\x6d\x56\xb7\x42\ -\x72\x87\x2a\x37\x67\xcf\x99\x6c\x19\xf8\x46\x40\xf8\x1d\x43\x13\ -\xb5\x82\xd6\xa3\x02\x83\x00\xc0\xfe\x42\x48\xcb\x3c\xf4\xbc\x13\ -\xec\xad\xca\xb4\xaa\x98\x26\x80\x8d\xc8\x60\x38\x2a\x67\xcb\x99\ -\x92\x8d\x86\xe6\xdf\x49\x71\xcd\x3b\xa7\xc9\x50\xf3\x10\xa3\x03\ -\x5a\xca\xce\x59\x0e\xd9\x22\xf0\x58\x40\xf8\x3f\xcd\xeb\x95\x7e\ -\x3b\x21\xa6\xf9\xbb\xce\x69\x62\x7d\x5a\xbf\x8d\x73\x46\x6c\x00\ -\x10\x1f\x02\xd2\xd9\xea\x8c\x7e\x17\xe7\x8c\xbd\x30\x0f\x31\x46\ -\xa0\x5d\xd5\xa2\x2a\x98\xce\x01\x77\x02\xc2\x1f\xc7\x6c\x39\x3b\ -\x6f\xcf\x87\xe6\xcf\x97\xec\xf4\x5e\x98\x87\x3e\x01\x40\x03\x82\ -\xa1\x09\x12\x86\x90\x2f\xd9\x69\xef\x6c\x85\x40\xf3\x32\x4d\xf6\ -\x6b\x1e\xfa\x1c\x81\x76\x65\xca\x96\x17\x76\x83\x04\xc6\xa1\x1f\ -\xf3\x95\xa2\x42\x7e\xbc\xed\xa8\xbe\x3b\xa0\xa5\x5a\x41\xeb\xce\ -\x69\x92\xf0\x4e\x58\xca\xcd\xd9\x73\x9d\x1b\x4d\xf3\xc1\x6d\x0f\ -\x3a\x3f\xa8\x79\x48\xa0\x03\x5a\xca\x2f\xd8\x0b\xde\xdb\x0d\xe0\ -\xeb\x01\xe1\xff\x90\xe9\x6c\xa5\xa8\xdf\x03\x8c\xcd\xdb\xb3\xce\ -\x6c\x05\x38\x16\xf9\x49\xe3\x1e\xd2\x64\xb5\xa0\x5f\x0f\x56\x71\ -\x43\x89\x01\x80\xfe\x20\x6c\x3b\xfc\x7e\x99\x87\x84\x01\x40\x3c\ -\x08\x26\x36\x64\x40\xc8\xdd\x65\x0a\xe6\x21\x05\x00\x00\xb9\x39\ -\x7b\xd1\x64\xd7\x09\xeb\x84\x68\x19\xf7\xec\x90\xce\xd7\xa6\xf5\ -\x5e\x22\xf9\xda\x94\x0a\x00\x48\x10\x42\x8a\xe6\x21\x81\x6f\x81\ -\x9d\xd4\xb8\x42\xeb\x3c\xd0\xf5\xc7\x88\x60\x19\xf7\x3c\xba\x90\ -\x96\x79\x48\xb1\x03\x5a\xca\x96\xed\x7b\x98\x5d\x47\x3c\x1a\xeb\ -\x83\x4d\xf3\xf5\xa2\xde\x4d\xa9\x34\x60\x0f\x00\xc0\x7f\x21\x2c\ -\xa2\xc8\x47\xee\x0d\x19\x9b\x1e\x4d\xa4\x6d\x1e\x52\x1c\x81\x2f\ -\xc9\xb3\x81\xf8\x22\x38\xde\xe9\x0b\x5c\xd0\xcf\xee\x81\x95\x3a\ -\x80\x6c\xc9\x4e\xe1\x6c\x95\xb0\xa7\xb7\x0d\x99\x8d\x38\xb3\x95\ -\xb1\x79\x7b\x36\xbd\xca\x1a\x4a\x75\x04\xda\xcc\x3f\xd1\x67\x8a\ -\xcf\xbd\xf4\x72\x7d\x46\x7f\x48\xb2\xae\x76\xa5\x06\xa0\x69\x7e\ -\x05\x78\x72\xc0\x54\x9f\x1b\x1a\xaf\x15\xf4\x7e\x12\x75\x75\x2a\ -\x95\x11\xc8\x2f\xd8\xc9\x84\xcc\x03\x1c\x13\xb6\x9a\x29\xdb\x33\ -\x09\xe4\xea\x52\xe2\x00\xf2\x0b\x76\xd2\x7b\x5b\x25\xc0\xbc\xc1\ -\x96\x60\x2b\x20\xed\x31\x61\x2b\x69\x40\x48\x14\x40\x1c\xf3\xc0\ -\x7d\x27\x4d\x6e\x37\x9e\x2c\xfd\x2b\x20\xfe\x89\x34\x20\x24\x06\ -\x60\xb4\x6c\x27\xe2\x98\xc7\x74\xb1\x32\xa3\x9b\xf5\xa2\xde\x75\ -\xe8\x02\x31\x20\x64\x4b\x76\x6a\xb0\x6a\xff\xa7\x44\x2e\x82\xa3\ -\x65\x3b\x71\x08\x5b\x23\x86\xf9\x6a\x51\x6b\xed\x8b\xf9\xb2\xfd\ -\xc0\x63\xef\x00\x8f\x04\xe4\xf8\x0c\xaf\xf1\xea\xac\xfe\xd8\x4f\ -\xbd\xed\x1a\x18\x40\x5c\xf3\x86\x2e\xd5\x0a\x5a\xed\xb5\x99\x9b\ -\xb7\x97\xcc\xec\x1a\x7b\x08\x61\xa0\x11\x18\x2d\xdb\x09\x47\x78\ -\xdb\xef\x66\x1e\xa0\x32\xa3\x9b\x92\x2e\x12\x38\x0e\xb8\xc1\xc7\ -\xa1\xef\x0e\x68\x99\x17\x3c\x15\x10\x7e\xdf\x4b\x97\xeb\x33\x5a\ -\x09\xc9\xdd\xec\x84\x77\x88\x7e\x5d\x07\xe0\x53\xe7\x34\xbe\x3e\ -\xad\x3f\x85\xe4\xee\x54\x5f\x00\xc6\x4a\x76\x5c\xce\xd6\x02\xcd\ -\x6f\x7a\xe9\x52\xa8\xf9\x96\xf6\x0a\x42\xec\x11\xd8\x0b\xf3\xd0\ -\x18\x07\x4c\x17\x81\xfb\x01\xe1\x4f\x7a\x6f\xab\xf9\x05\x3b\x19\ -\xf7\x9c\x58\x1d\x30\x56\xb2\xe3\xae\x71\x6f\xff\x74\x40\x78\xdf\ -\xe6\xdb\x95\x9d\xb3\x33\xc8\xae\x11\xd8\x09\xdb\xe8\xcc\xad\x82\ -\xfe\x1c\x9a\x3f\xb8\x03\xe2\x9a\x97\x0f\x9f\xf9\xdd\x54\x2d\x6a\ -\xcd\xd0\x25\x02\x3b\xe1\x10\xb6\x36\x5a\xb6\x13\xa1\xf9\x83\x3a\ -\x20\xbb\x60\xdf\xc5\xdb\x1a\x31\xcc\x57\x66\xb5\x1c\x5a\x44\x88\ -\x32\x65\x1b\x17\xf6\x36\x09\x77\x42\x24\x80\xb8\xe6\x41\x53\xd5\ -\x82\x96\x02\x62\x63\x6b\x6c\xde\x5e\x76\x66\x6f\x11\x00\xc1\xe0\ -\x13\x8f\xc6\xa3\x20\xec\x0a\x60\x98\xcc\xb7\xd4\x84\xf0\x36\x74\ -\xbf\xf5\xd9\xa9\x10\x08\x3b\x5e\x03\x9a\xe6\x83\x67\x1e\xe9\x4a\ -\xda\xe6\x01\xea\x33\x5a\xf1\xd2\x25\x60\x33\x2a\x56\xf0\x94\xc3\ -\x56\xc7\x4a\x76\x7c\x97\x98\x6e\xb5\x99\xff\x66\xd4\x21\x06\x5b\ -\x92\xa6\xaa\x33\x5a\x8c\x8a\x4d\x52\x71\x3b\xc1\xbc\xce\xd4\x67\ -\xf5\x97\xce\xbd\x2e\x00\xf9\x37\xec\xdb\xfe\xb0\xdd\x02\xbe\x15\ -\x90\x78\x5f\xcc\xb7\x94\x2b\xd9\x59\x73\xf6\x16\x01\x10\x80\x8f\ -\xbd\xd3\x68\x7d\x5a\x7f\x6b\x5f\xec\x7e\x5b\xfc\xb0\xff\x31\x5f\ -\x01\xf3\x00\x95\x59\x2d\xcb\xeb\x32\x01\xe3\x00\x3c\x2d\xef\x7f\ -\xd2\xb9\xd8\xeb\xff\x05\x5e\x8a\xca\x64\xb0\x85\xd7\x95\xfd\x34\ -\xdf\x52\xe3\xeb\x56\x53\x04\x41\xd0\x99\xce\x95\x5e\x17\xc1\xed\ -\xdd\x52\xb4\xcc\xd7\x66\x75\x23\xb4\xc8\xb4\xd5\xb8\xf8\x46\x43\ -\x50\x0f\x6f\xdd\x00\x1a\x6f\x7f\xf5\x94\xc1\xd6\x21\x34\x3d\x4c\ -\xe6\x5b\xaa\x16\xb4\x84\x74\x85\x5d\x21\xd8\xf5\xce\x95\x2e\x00\ -\x66\xee\xaa\xc1\x5f\xbb\xd6\x9b\xe6\xd7\x0b\xea\x4a\x32\x2c\xaa\ -\xce\x68\x71\x47\x08\xc6\x87\x0f\xfd\xdb\x5d\xed\x5c\xee\x02\x50\ -\x2b\xe8\xb3\xed\xc3\xca\x81\xfd\x1c\xf8\x08\xf8\x18\x78\xd3\x99\ -\x5e\x18\x66\xf3\x2d\x55\x67\xb4\xe8\xa5\x3c\xc6\x02\xf0\x77\xe0\ -\x23\x64\xbf\x78\x68\x5b\xd9\xf7\x5e\xd5\x27\xfb\x5d\xdf\x81\x0e\ -\x74\xa0\xe1\xd2\x7f\x00\x72\xd2\x49\x30\x2e\xe9\xad\x3a\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x58\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x0a\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4b\x88\x5c\x45\x18\x85\xcf\xa9\x19\x34\x41\xa2\xa0\x21\x1b\ -\x09\xee\x7c\xac\x04\x13\x7b\xda\xb8\x30\x06\x13\x99\x80\x26\xdd\ -\x1d\x06\x17\x82\xe0\x83\x08\xae\x14\x09\x24\x88\x1a\x4c\x40\x11\ -\x5c\x28\xf8\x42\xd1\x85\x28\x8a\xdd\xf3\x40\x26\x32\x41\x1c\x10\ -\x64\x7a\x9a\x11\xb2\x10\x41\x5c\x04\x11\x41\x83\x09\x11\x25\x0d\ -\xe9\x5b\xc7\x45\xcf\xa8\xdc\x2a\x35\x9d\x54\x55\x17\xd8\xdf\xf2\ -\x2e\xea\xfc\xff\xb9\x55\x7f\xd5\x7f\x1f\xc0\x88\x11\x23\xfe\xcf\ -\x30\xd4\x40\x95\xa6\x9e\x35\xb4\x4f\x89\x94\x2c\x8f\x2c\x37\x78\ -\x38\xd4\xd8\x31\x09\x66\xc0\x44\xb3\x28\x40\x9a\xd5\x51\x45\x70\ -\xc7\x52\x8d\x8b\xa1\xc6\x8f\x85\x09\x36\xd2\x5a\xf2\x00\x20\x50\ -\xd2\xdc\xc4\xb4\xb6\x04\x1b\x3f\x12\xc1\x0c\x10\x60\x4b\x97\x36\ -\x40\xfa\x74\xeb\xac\x6e\x08\xa5\x11\x83\x60\x06\x10\x90\xe7\xf2\ -\xc6\xb1\x42\xc7\x6f\x9d\xd1\xe6\x50\x3a\xa1\x09\xb7\x04\xfe\x99\ -\xcd\xc6\x6a\x61\xcb\x9c\x36\x26\xd0\x1a\x98\x14\x06\x00\xc0\x8d\ -\xe3\x85\x8e\xdd\x3e\xab\x0d\x89\xf4\x2e\x98\x68\x06\xa8\xbc\x24\ -\x84\xad\xbd\x42\x33\x93\xf3\xba\x3c\x96\xe6\xc5\x10\xcd\x00\x02\ -\x16\x74\xea\xc2\x8e\xd3\x5d\xbd\xbf\xfd\x73\x8d\xc7\xd2\x1d\x94\ -\xb8\x4b\x40\xb0\x70\x8b\x63\xbd\x7b\xda\xbe\x0e\x29\xd8\x19\xe4\ -\x52\x48\x51\x03\x9c\x99\x20\xf2\xa1\x6a\xcb\x3e\x9f\x40\xfb\x3f\ -\x49\x53\x04\x05\xab\x72\x49\x20\x0f\x54\xa6\x75\x20\x89\xfe\xbf\ -\x90\x6a\x17\x00\x69\x0a\xe7\x9a\xf4\x42\xb5\xa9\x87\x53\xc5\xe0\ -\x23\x99\x01\x90\x7c\xa7\x45\x88\x7a\xa3\xda\x52\x3d\x59\x1c\x25\ -\xd2\x19\x80\xfe\x69\xd1\x63\x82\x11\xf4\x41\xf5\x63\xdd\x95\x32\ -\x96\x3f\xc5\x53\x0b\x12\xd0\xea\xee\xf0\x77\x2e\x13\x35\x73\xdb\ -\xb4\x2a\xa9\xe3\x49\x6e\x00\x00\x80\x9e\x99\x40\x5c\x61\xa5\xf9\ -\x6a\x4b\x37\xa5\x0c\x65\x38\x06\x60\xad\x79\x62\x79\x26\x5c\x23\ -\xe8\xf8\xb6\xa6\xae\x4b\x15\xc7\xd0\x0c\xe8\x23\x9f\x09\xd7\x16\ -\xd4\xc2\xb6\x96\x36\xa5\x88\x60\xc8\x06\x00\x7d\x13\x54\x3e\x2d\ -\x5e\x5f\x40\xc7\x26\xe6\x75\x65\x6c\xf5\x0c\x0c\x00\x00\x5a\xa7\ -\x79\x02\x6e\x51\x57\x73\xdb\xdf\xd1\xba\x98\xca\x99\x18\xb0\xda\ -\x3c\x95\x4c\x20\x70\xc7\xb9\xab\xf4\x61\xcc\xe6\x29\x1b\x03\x56\ -\xf1\x35\x4f\xf7\x76\xcf\xd8\xb7\xf0\x8c\xa2\xc4\x9a\x9b\x01\x80\ -\xaf\x79\x02\x1f\xa8\xdc\x6c\x5f\x8c\xd1\x41\xe6\x68\x40\xbf\x8d\ -\x2e\xd5\x45\x82\x4f\x54\x5a\x38\x18\x5a\x2a\x4f\x03\x00\x80\x74\ -\x9b\x27\xea\x68\xa5\xa9\xfd\x21\x65\xf2\x35\x00\x80\x04\x5b\xae\ -\x08\xa4\x5e\x9b\x68\x6a\x5f\x28\x8d\xac\x0d\xa0\xef\xc8\x0c\x10\ -\xd4\x2b\xa1\x34\xb2\x36\x00\x00\xe8\x2f\x7b\xc1\xb6\xc5\xbc\x0d\ -\xe8\x67\xef\xc4\x28\xe8\xed\x50\x12\xd9\x3c\x9d\xf5\x22\x8d\xb9\ -\xd7\xf8\xd8\x72\xc3\xbc\x1a\x4a\x22\xe3\x19\xe0\x4d\xfe\xe9\x76\ -\x83\xc1\x92\x07\x72\x34\x80\x80\x08\xe3\xbe\xb9\xd7\xcb\xed\x3a\ -\x8e\x84\x96\xcb\xce\x00\x09\x86\x2a\x67\xaf\xf7\xda\x27\xcc\xe3\ -\x20\x7d\x2f\x60\x2f\x89\xbc\x0c\x20\x0c\x4b\xb7\x9e\xc0\x27\xbd\ -\x53\xe6\x41\x1c\x76\x9e\x1b\x04\x21\x27\x03\x0c\x9c\x3b\x8f\x2f\ -\xd8\xe3\xd4\xca\x7e\x9e\x8f\x25\x9a\xc9\x2e\x20\xe3\xd9\xf1\x4f\ -\xf4\x7a\xbc\x67\x65\x8a\xe7\x62\x2a\x0f\xdd\x00\x81\x2c\x4f\x7b\ -\x08\xdf\x61\x9c\x77\xaf\xd4\x79\x36\xb6\xfe\x50\x97\x40\x3f\x79\ -\xa7\xcf\xff\x91\x86\x3b\xdb\x7b\xf8\x53\x8a\x18\x86\x67\x80\xe0\ -\x4b\xfe\x8c\xb5\xdc\xb5\x54\xe3\xc9\x54\x61\x0c\xc5\x00\x09\x04\ -\x4b\xda\xc2\xef\x10\x77\x77\xf6\xf1\xeb\x94\xb1\x24\xaf\x01\x02\ -\xc8\x72\xf2\xc0\x79\x18\xd6\xdb\x35\x2e\xa5\x8e\x27\xe9\x0c\x90\ -\x40\xca\xd1\x14\xc9\xfb\xdb\x35\x2e\xa4\x8c\x65\x8d\x74\x33\x80\ -\x84\x67\xcd\x03\xe4\xa3\x4b\x35\x7e\x94\x2c\x8e\x12\xc9\x66\x80\ -\x64\xdd\xe6\x86\x3c\xd4\xae\xf1\xcd\x54\x31\xf8\x48\x63\x00\x61\ -\xe8\x6c\xf5\x7a\xa9\xbd\x17\x43\xff\x4c\x26\x85\x01\xee\x11\x57\ -\x7a\x77\xb9\x66\x9e\x8c\xd1\xdc\x0c\x4a\x5c\x03\xfa\xd5\xbe\x7c\ -\xc4\x9d\x5d\x7f\xb5\x79\x24\x87\xe4\x81\xb8\x1f\x4a\xfa\x9a\x9b\ -\xc5\xf5\x67\x79\xdf\xe2\x9d\xec\xc5\xd2\x1d\x94\x68\xbb\x80\x73\ -\xbe\x07\xbe\xc2\x3a\xee\x59\xac\xb3\x1b\x4b\xf3\x62\x48\xb5\x0b\ -\x7c\x3b\x06\x4e\xb6\x77\xf3\xd7\x44\x7a\x17\x4c\x0a\x03\x7e\xe8\ -\xf5\xb8\xf3\xcb\x3a\x7f\x4e\xa0\x35\x30\x21\x7f\x98\xf0\x3d\xc1\ -\xff\x85\xe0\xae\x95\x29\x7e\x1f\x4a\x27\x34\xc1\x6a\x00\x5d\x33\ -\x7f\xb3\xe2\x64\xa7\xc1\x6f\x42\x69\xc4\x20\xe4\x12\xf8\xeb\x99\ -\x1d\x21\x4b\xee\xed\x34\xd8\x09\x38\x7e\x14\x42\xfe\x34\x75\x14\ -\x40\x01\xa0\x80\xf8\x5c\xa7\xc6\xcf\x82\x8d\x3d\x62\xc4\x88\x11\ -\x91\xf8\x03\x6e\xfe\x4e\x7e\xe0\xc6\x25\x53\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcd\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\x6f\x55\x80\x05\xd4\x62\xaa\ -\xc8\x58\x12\x66\x0c\xdc\xcb\xa6\x7f\x9d\x09\xad\xeb\xde\xeb\xba\ -\x77\xb9\xe1\x2c\x8f\x7f\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xef\ -\x03\x1c\xe5\xf1\xfa\x6b\x7c\xa6\x7e\x01\x7b\x9e\xf4\x3e\x00\x00\ -\x00\x00\x00\x00\x00\xfc\xc3\x0b\xb7\x26\x07\xfa\x17\x1e\x2a\x64\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x8f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x41\x49\x44\x41\x54\x58\x85\xed\ -\x97\x31\x6b\x14\x51\x14\x85\xbf\x33\x59\xab\x80\x85\x62\x20\x76\ -\xf9\x03\x62\xb5\xbb\xa2\x88\x82\x5d\x42\x8a\x24\xf8\x07\x02\x6a\ -\x95\xca\x24\x65\x08\xa9\x56\xb0\x30\x60\x50\x41\x41\xd2\x04\xc1\ -\x2d\x82\x0b\x76\x01\x41\xb2\xbb\x95\xf8\x07\x92\x3a\x41\xc1\x22\ -\x95\xc9\x1c\x8b\x9d\xb7\xac\x9b\xd9\xec\x4e\x76\xb4\xd1\xaf\x7a\ -\xdc\x77\x67\xee\x99\x73\xdf\xcc\xbc\x07\xff\x3a\xea\x0e\x94\xdf\ -\xfb\x66\x8c\x97\x11\x65\xc1\x95\x3c\x8a\x18\x0e\x31\xf5\x08\x55\ -\xea\xb3\xfa\xdc\x53\x40\xa9\xea\xc7\xe0\x27\x69\xc2\x72\x22\xc6\ -\x5a\x6a\xcc\xea\xe9\x29\x01\xa5\xaa\x6f\x81\x3f\x01\x3f\xb0\x16\ -\xa2\x13\x6a\xbb\xf7\xf5\x3d\x8f\xaa\x37\xde\xf9\x52\x3c\xc2\x24\ -\xf2\x3a\x70\x51\xd6\xed\xe0\x44\x21\x24\xd9\x5e\x92\x10\xd6\x42\ -\x63\x56\x9b\x79\x14\x0e\x24\x0f\xb2\x59\xac\x5a\xc2\x6f\x63\xbc\ -\x0c\x4c\x03\x44\xed\x2c\x51\x06\x88\x4e\xa8\xe5\x59\xbc\x8b\x1a\ -\x80\x44\x29\x04\xda\x02\xc2\x82\xcb\xcb\xf6\x34\x9a\x33\xfa\x96\ -\x0c\xc7\x42\xac\xd0\x23\xf7\xdc\x14\xab\x9e\x12\x7e\x05\x60\xf4\ -\xa0\x39\xa3\x0f\x67\xe5\xe7\x2a\xa0\xb8\xed\x09\xfd\xf4\x16\x62\ -\x14\x20\x11\x72\xf5\xac\x6b\xa2\xb3\x26\x33\xb1\xe2\x48\xc7\x7e\ -\x13\x8a\x0f\x4a\x6e\x02\x4a\xd7\x78\x04\xdc\xe9\x8c\x49\x5a\xfb\ -\x2b\x02\x8a\xdb\x9e\x48\x3e\x60\x9d\xec\xd4\xbf\xf0\xf2\xcf\x0b\ -\x48\xb3\xde\x1c\xb9\xa0\x79\x56\x15\xf7\xbb\xbc\xef\x22\xec\xb7\ -\xaa\x53\xad\x8f\xb4\xd8\x98\xd6\xde\x20\xfa\xfb\x3a\x90\x14\x1f\ -\x07\xc6\x65\x6f\xb5\xec\x4e\xc4\x0d\x61\x7d\x20\xdb\x6b\x28\x46\ -\x75\xec\xd7\xac\xf8\x1e\x40\xaa\xf5\x17\x06\xb3\x7e\x60\x01\x92\ -\xd6\x6c\x6f\x74\x84\xee\x96\xaf\xf3\xd0\x31\x62\x08\xeb\x03\x7d\ -\x5b\x90\xd8\xb9\xd3\x19\xb3\xbd\x81\xfc\xbc\x2b\x35\x93\xf5\x03\ -\x0b\x60\x55\xb1\x0b\x9a\xc7\x1c\xf5\xcc\xc9\xb0\xea\xb3\x0b\x00\ -\x9a\xd3\xda\x03\x2d\xf5\x9a\x57\xa4\xc5\x66\x46\xeb\x33\x09\x00\ -\x68\x7c\xe5\x05\x5d\xad\x48\x38\x97\xf5\x99\x05\xa4\xb6\x62\x08\ -\xeb\xb3\x0b\xa0\xd5\x8a\x48\x9a\x03\xf6\x81\xfd\x48\x9a\x3b\xaf\ -\xf5\x81\xcc\xbf\xe3\xdd\x19\x7d\x04\x26\xfa\x26\x0e\x48\xdb\x01\ -\xc3\x21\xb4\x36\x90\x79\xdd\xbc\x9b\x62\xd5\x97\x93\xe1\xc1\x29\ -\x01\x98\x3a\x40\x3c\xc2\xe4\x9f\x12\x00\xad\x7b\xdb\x34\x42\xa0\ -\xdd\x82\x08\x55\x8c\xa7\x90\xd7\x8b\x55\x0b\xa8\x75\xec\xe1\x86\ -\x22\x79\xf2\x49\xe1\x67\x40\x1c\xa1\x4a\x98\x4b\x3b\x98\x54\xc8\ -\x73\xa7\xf4\x3b\xbd\x0f\x26\x81\x70\x34\x4b\xb6\xce\x63\xdd\xf3\ -\xe7\xe4\xc0\xa6\x91\x76\x34\xfb\xcf\x2f\xa6\x4e\xeb\xad\xb9\x6d\ -\xcb\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x8b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x58\x85\xed\ -\xd3\x21\x12\x00\x10\x00\x05\xd1\xe5\x52\xaa\xe2\x00\x2e\xea\x04\ -\x66\x64\x97\x32\x92\x2a\x52\xf6\xa5\xdf\x36\x7d\x90\x24\x7d\x16\ -\xce\x48\x6d\x0d\x20\x3f\xaa\xf6\x59\x63\x01\x88\x4f\x82\xd2\x85\ -\x2f\x90\x24\xe9\xbb\x0d\xbb\x58\x0a\x07\x83\x32\x65\x0f\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x26\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd8\x49\x44\x41\x54\x78\x9c\xed\ -\xd2\xb1\x4d\xc3\x50\x18\x46\xd1\x1f\x86\xf0\x26\x2c\x92\x15\x52\ -\x20\x1a\x86\xa1\x89\xb2\x44\x16\x61\x8b\x54\x6c\x61\x0a\x2c\xa5\ -\x88\x68\x7d\x22\xe5\x1e\xc9\xd2\x73\xf5\x3e\x5f\x79\x26\xc9\x33\ -\x7b\x51\x17\xbf\xbd\x7f\x1d\x66\xe6\xb4\xbd\x7e\x7c\x9f\x3f\x2f\ -\x62\xc7\xab\xb8\x74\x73\x5a\x67\x96\x75\x66\x99\x5b\x88\xdd\xb1\ -\x00\xdb\x87\xdf\x9d\xf7\x26\xff\x80\x87\x50\x00\x3d\x40\x2b\x80\ -\x1e\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\ -\x01\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\ -\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\ -\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\xa0\ -\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\x5a\ -\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x93\x01\x7e\xfe\x39\ -\xef\x0a\x06\x58\x8f\x33\x73\xfd\x7b\xd6\xa3\xdb\x91\xe4\x99\xfd\ -\x02\xc9\x6e\x11\x4a\x9d\x22\x1c\x0a\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x03\x5c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x0e\x49\x44\x41\x54\x78\x9c\xed\ -\xd5\x4b\x6c\x54\x75\x14\xc7\xf1\xef\xb9\x53\xa6\xda\x81\xd0\xd0\ -\x98\x50\x4d\x4a\x64\x63\x52\x36\xc0\x4c\xc7\x47\xa2\xa9\xcf\xa4\ -\x16\x24\x2c\x70\x41\x04\x4b\x02\x33\x03\xed\x80\x62\xe2\xc2\xc4\ -\x4c\xba\x33\xf1\x51\x3b\x03\xa5\x0f\x89\x04\x16\x18\x0a\x29\x31\ -\x60\xdd\x98\x58\x92\x52\x18\xda\x59\xb2\x00\xa2\x1b\x83\x84\xd0\ -\x0a\x49\x83\x9d\xda\xce\x71\x51\xa3\xd3\x6b\x25\xd8\x7b\x67\xba\ -\xe0\x7c\x96\xff\x73\xef\x6f\x7e\xf7\xcc\x0b\x8c\x31\xc6\x18\x63\ -\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xa8\x10\xaf\x01\xcf\xc6\ -\xd3\xf5\xb3\xca\x71\x84\xa7\x50\xbe\x18\xed\x4d\x7e\x06\xa2\x7e\ -\x94\x5b\x48\x34\xd1\xb9\xb5\xa0\xf2\x29\x00\x05\x49\x8e\xf6\x25\ -\x07\xbd\xe4\x79\x5e\x40\x24\x9e\x19\x02\x7d\xe9\xef\x03\xe5\xc4\ -\xfd\xdf\xc6\x77\x5f\xed\x6f\x9f\xf6\x9a\x3d\x9f\x4a\x38\x9e\xf9\ -\x50\xe0\x93\xa2\xc3\x7b\xaa\x95\x4f\x8c\xf5\xc6\xff\x58\x6c\xaa\ -\xe3\x43\xb1\xf9\x19\xc2\x8e\xaa\x55\x35\xdf\xaf\x6f\xe9\xa8\xf6\ -\x9e\x3d\xa7\x31\x95\xaa\x88\xc4\xd3\x5d\xae\x87\x9f\x7b\x35\x8f\ -\xbc\x2f\x40\x74\xaf\xc0\x6d\xd7\xe9\xcb\x81\xca\xc0\xf0\x86\xd6\ -\x43\x6b\xbc\xc6\xd7\xef\x3b\xbc\x7c\xf2\x56\xcd\x59\x90\x84\x6b\ -\x94\x17\x78\xc7\xcb\xbb\x0f\x3e\x6c\x10\x20\xba\x3b\xf3\x74\x21\ -\xa0\x83\xc0\x33\xae\xd1\x2d\x55\xa7\x79\xac\xb7\x2d\xb7\x98\xdc\ -\x70\xac\xa3\x56\x24\x70\x0e\xd8\xe8\x1a\x4d\x20\xf2\xd6\x68\x77\ -\x72\x78\x31\xb9\xc5\x7c\xf8\x0a\x40\xf6\xab\xe4\xcf\xcb\x66\x66\ -\x5e\x00\xb9\xe0\x1a\xad\x16\x29\x5c\x08\xc7\xd2\xcd\xff\x37\xb3\ -\x61\xcf\xa1\x75\x22\x81\x4b\xfc\xeb\xe1\xe5\x27\xa7\xe0\x3c\xef\ -\xc7\xc3\x83\x4f\x0b\x00\x18\x39\x7a\x70\xe2\x6e\x50\xdf\x00\x4e\ -\xba\x46\x21\x11\xbe\x0d\xc7\xd2\x7b\x1f\x36\x6b\x63\x22\xf3\x8a\ -\x3a\x85\x61\xa0\x6e\xfe\x44\x2e\xcf\x4e\xeb\x73\xd9\xbe\xb6\x6b\ -\x9e\x0b\xff\x25\xe0\x57\x10\xc0\x44\x76\x70\xf6\xe6\xa6\xe8\x40\ -\xed\x64\x28\x28\xf0\x62\xd1\x48\x44\x68\x7e\x32\xd2\x14\xba\xb9\ -\x29\xfa\x03\x43\x43\xff\xf9\x37\x19\x89\xa7\x77\x0a\x9c\x02\xaa\ -\x8a\xcf\x15\x19\x40\x83\x5b\x72\x47\x5b\xef\xf9\xd9\xd9\x97\xdf\ -\x80\x85\x44\x62\x9d\x31\x44\xba\x70\x2d\x59\xe1\xd4\x8a\xfc\x8a\ -\x77\x7f\x3c\xb6\x6b\x6a\xfe\x1d\x2a\x0d\xf1\xcc\xc7\x0a\xed\xee\ -\x2c\x45\x3b\xd7\x4e\xd4\x7e\xd0\xdf\xff\xf6\xac\xdf\x3d\x4b\xb6\ -\x00\x80\xc8\x9e\x4c\x13\x8e\xf6\x03\x21\xd7\x68\xd8\xa9\x70\xb6\ -\x64\x0f\xb7\x8d\x03\xd4\x6f\x4b\x05\x1f\x5f\x55\xd3\x23\xd0\xe2\ -\xba\x4e\x05\x79\xff\x4a\x4f\xb2\xb3\x54\x1d\x4b\xba\x00\x80\x48\ -\x22\xbd\x01\xe5\x3c\x50\x5b\x7c\xae\x70\x1d\xa5\x09\x2a\xef\x88\ -\x93\x3f\x8d\xf2\x9a\xeb\xd6\x29\x47\x74\x7b\xb6\xfb\xc0\x40\x29\ -\xfb\x95\x7c\x01\x00\xe1\xd8\x97\x75\x22\xce\x77\xc0\xba\x87\xbc\ -\xe5\x4e\xc1\x61\x73\xee\xc8\xfe\x4b\xa5\xec\x05\x65\x5a\x00\x40\ -\x38\xd6\xb3\x52\x24\x7f\x06\x78\xf5\x41\xd7\x29\x5c\xd7\x40\xe0\ -\xcd\x5c\x57\xeb\x8d\x72\xf4\xf2\xf5\x5f\xe0\x41\x7e\x1d\x3b\x97\ -\xaf\x5e\x1b\xfd\x26\x58\x15\xaa\x03\xd6\x2f\x78\x91\x70\x11\x9d\ -\x7e\x3d\xd7\xfd\xde\x2f\xe5\xea\x55\xb6\x4f\xc0\x3f\x54\x22\x89\ -\x74\x0a\x95\x94\x6b\x70\x7a\x59\xd5\xcc\xce\x91\x8e\x83\xbf\x97\ -\xb3\xcd\x12\x2c\x60\x4e\x43\x22\xdd\xa7\xca\x2e\x40\x81\xcf\x47\ -\x57\x8f\x7f\x44\x7b\x7b\x61\xa9\xfa\x2c\x89\xc6\x54\xaa\xa2\xb1\ -\xe5\xeb\xc7\x96\xba\x87\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ -\x31\xc6\x18\xf3\x88\xf8\x13\xba\x50\xdf\xc1\x6b\x55\xb9\xde\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xc4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x76\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xc1\x0d\x82\x40\x14\x04\xd0\x59\x8b\x30\x36\x62\x23\xb6\xc0\ -\xc1\x70\xb2\x17\x2f\x84\x46\xa8\x82\x42\x88\x4d\xac\x57\x43\xf6\ -\x0a\x24\xf2\xde\x71\xf2\x0f\xf3\x27\x01\x00\x00\x00\x00\x00\x00\ -\xce\xa0\xac\x83\xfb\xf3\xfd\x48\x32\xd4\xe4\x7a\x40\x9f\x2d\x2d\ -\x49\xed\xe6\xf1\x35\xfd\x86\x97\xc6\xe1\x3f\x3e\x9f\x24\xb7\xa4\ -\x0c\xeb\xb0\x35\xc0\xa9\xb4\x06\xe8\x4b\xf2\xd9\xbd\xc9\xf6\x96\ -\xa4\xf6\x47\x97\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xf7\x05\x16\ -\xa6\x0e\x08\x70\x11\x84\x99\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x88\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x14\x44\x05\x88\x0e\ -\x20\x71\x45\x4e\x68\x81\x94\xc4\x0d\x59\x34\xf1\xa4\xc8\x2f\x42\ -\xeb\x91\x3d\x13\xae\x2e\xd8\xbb\xec\x12\x00\x00\x00\x00\x00\xf6\ -\xa3\x2c\x83\xf3\xf5\x7e\x29\x35\x63\x92\x63\x87\x3e\xab\x29\xc9\ -\x5c\x93\xdb\xf4\x7c\xbc\xbe\xf3\x43\x33\xb8\xc1\xe5\x93\xa4\x26\ -\xa7\x24\xe3\x32\x6f\x0e\xb0\x37\xcd\x01\x6a\xc9\x90\xe4\xdd\xa1\ -\xcb\xaa\x4a\x32\x27\x19\x7a\xf7\x00\x00\xfe\x87\x5f\xa0\x19\xdc\ -\xe0\xf2\x89\x5f\xe0\x27\xbf\x00\x00\x00\x00\x00\x00\x00\x3b\xf1\ -\x01\xd7\x53\x1e\x0f\x14\xfc\xaf\x10\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\xc4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x76\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3d\x6f\xd3\x40\x1c\x87\x9f\x4b\xa8\xca\x02\x4b\x78\x59\x6a\ -\xe7\xfc\x39\xf8\x12\x2c\x54\x0d\x2d\xac\x74\x60\x65\x63\xe5\x1b\ -\x80\xc4\xca\x4b\x0b\x82\x01\xf1\x3d\xbc\x31\x66\x70\xed\x66\x43\ -\x48\x48\x2c\xa8\x52\x7b\x2c\x11\x32\x87\x9d\x36\xf6\xdd\xf9\xce\ -\xf1\x6f\xb3\xfd\xcf\x4f\xf7\x3c\x8a\x9d\xe8\x64\x18\x32\x64\xc8\ -\x26\x47\x74\xbd\x00\xdb\xc9\x8a\xe2\xbe\x50\xe2\x05\xf0\x73\x3c\ -\xe2\x30\x8a\xa2\x6f\xe5\xeb\xd7\x3a\x5a\x97\x93\x64\x45\xb1\x27\ -\x94\x38\x02\x46\x00\xe7\x17\xbc\x06\xee\x95\x67\x46\x5d\x2c\xcc\ -\x45\x74\xf8\x65\x6e\xea\x73\xbd\x14\x50\x03\x7f\xae\x84\x7a\xae\ -\xcf\xf6\xee\x16\xa8\x83\x17\x88\x99\x8c\xa3\xaf\xfa\x7c\xaf\x1e\ -\x82\xab\xe0\xa7\xd3\x9d\xcf\x55\x9f\xe9\x8d\x80\x26\xf0\xd0\x13\ -\x01\x4d\xe1\xa1\x07\x02\xda\xc0\x43\xe0\x02\xda\xc2\x43\xc0\x02\ -\x4c\xc0\x43\xa0\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\ -\xc3\x43\x40\x02\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\ -\x83\xe7\x02\x6c\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\ -\x87\x02\x4c\xc3\xe7\xf9\xe2\x81\x52\xea\xd5\xf2\xf0\x89\x94\xd1\ -\x97\xf2\x75\xaf\x04\x98\x86\xff\xaf\x4f\xf1\x5d\xca\xe8\x4e\x79\ -\xc6\x9b\x2d\x31\xeb\xf0\x35\xf1\x42\x80\x23\xf8\x0b\x21\xc4\x53\ -\x7d\xb6\x73\x01\xae\xe0\x51\x3c\x9e\x4e\x77\x3e\xe9\xf3\x9d\x3e\ -\x03\x5c\xc2\x4b\x19\x1d\x55\x7d\xa6\x33\x01\x3e\xc0\x43\x47\x02\ -\x7c\x81\x87\x0e\x04\xf8\x04\x0f\x8e\x05\xf8\x06\x0f\x0e\x05\xf8\ -\x08\x0f\x8e\x04\x38\x84\x7f\x24\x65\x74\xbc\x4e\x97\x75\x01\x3e\ -\xc3\x83\x65\x01\xbe\xc3\x83\x45\x01\x21\xc0\x83\x25\x01\xa1\xc0\ -\x83\x05\x01\x21\xc1\x83\x61\x01\xa1\xc1\x83\x41\x01\x21\xc2\x83\ -\x21\x01\xa1\xc2\x83\x01\x01\xae\xe0\x95\x50\x07\x49\x1c\x7f\x58\ -\xb7\x2f\xcf\x17\xbb\x4a\xa9\x97\xcb\x43\xb3\x7b\x82\xfe\xc3\x9f\ -\x1e\x28\x78\xf3\xb7\xcf\xe4\x9e\x60\x70\xf0\x35\x69\x24\xc0\x77\ -\xf8\x93\x93\xd3\xfd\x0a\x78\x33\x7b\x82\x21\xc0\x23\x78\xab\xf7\ -\x19\xd9\x13\x0c\x19\xbe\xf5\x9e\x60\x00\xf0\x0f\x11\xbc\xd3\xfb\ -\x2e\xfb\xe9\xbc\x92\x80\xbe\xc2\xc3\x15\x04\x38\x84\xdf\x4f\xe2\ -\xf8\xe3\xba\x7d\x6d\xe0\xe1\x12\x01\x7d\x87\x87\x15\x02\x7c\x87\ -\xcf\x8a\x62\x26\x94\x78\x5f\xd1\xb7\xd6\x6d\x54\x29\x60\x53\xe0\ -\x01\xc6\xfa\x89\x3c\x5f\xec\x02\xc7\x18\x82\xaf\xe9\x6b\x0c\xbf\ -\xa2\xaf\xd1\x03\xf4\x9f\x6f\x40\x9a\xa6\x5b\xb7\x6e\xdf\xfd\x01\ -\xdc\x28\x9d\x6e\x0c\x5f\xd3\xd7\x18\xde\x74\x1f\x68\xff\x04\x27\ -\x93\xc9\x18\xd8\x2e\x9d\x6a\xf5\x5a\x4a\x45\x5f\xab\xc5\x9a\xee\ -\x03\x4d\x40\x92\x24\xbf\x05\x3c\x03\xce\x80\x5f\x02\xb1\xd7\xe6\ -\x9d\x9c\x8a\xbe\x59\x9b\xc5\x9a\xee\xab\xcd\x7c\x3e\xdf\x4e\xd3\ -\x74\xcb\xd7\xbe\x2c\xcb\xae\x9b\xec\x1b\x32\x64\x83\xf3\x07\x17\ -\xa8\x1d\x6f\x59\x60\x0c\x9b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x0a\xf4\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xa6\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7b\x70\x54\xd5\x19\xff\x7d\xf7\xee\x6e\x60\x93\x08\x64\x11\ -\x83\xd2\x91\xd8\x96\xd1\x58\x98\x21\xbb\x0b\x52\x35\x22\xda\xd1\ -\x5a\xc5\x07\xae\xf5\x31\x28\x51\xd8\x4d\x80\x2c\xc2\x54\x5b\x9d\ -\xa9\x4b\xac\x76\xb4\x6a\x08\xbb\x60\xdc\x08\x18\x41\xa6\xad\x99\ -\x51\xa7\x3a\x8a\x4c\xb5\xa1\xd4\x22\x64\x03\x96\xfa\xc0\xf1\x11\ -\x1f\x34\x90\x4a\xc2\x23\x12\xb2\xd9\xdd\xf3\xf5\x8f\x20\xdc\x7b\ -\xf7\xee\xbd\x77\x93\x5d\xa6\xd3\xf2\xfb\x6f\xbf\xf3\x3b\xdf\xf9\ -\x9d\xef\x9e\x3d\xf7\x3c\xbe\x0b\x9c\xc6\x69\x9c\xc6\xff\x33\xe8\ -\x54\x34\x32\xb5\x2a\x7c\xa6\x5c\x40\x95\x80\x98\x0c\xa6\xf3\x41\ -\x38\x8f\x19\xa3\x09\x38\x03\x80\x0c\xd0\x11\x00\x47\xc0\xfc\x15\ -\x08\x1f\x01\xf8\x50\x4a\xd1\xd6\x1d\x6b\x6a\x3b\xf2\xad\x2d\x6f\ -\x01\x70\xfb\xc3\xdf\x97\x08\xf3\x98\x31\x1b\x84\x29\x43\x74\xd3\ -\xc1\xe0\x37\x24\xc1\xcd\x6d\xcf\x2e\x89\x01\xc4\x39\x15\x89\x9c\ -\x07\x80\xc9\x1b\x08\x5f\xc5\xa0\xfb\x01\x5c\x9e\x5b\xdf\x78\x9f\ -\x40\xf5\x82\x1d\x2f\xb4\x37\x05\x12\xb9\x72\x9a\xb3\x00\xb8\xfd\ -\x2b\x2f\x27\xa2\xdf\x01\xf0\xe4\xca\xa7\x1e\x18\xf8\x02\xcc\xcb\ -\xdb\x9b\x82\xeb\x73\x31\x22\x86\x1d\x80\xe9\xf3\x1b\xce\x4a\xca\ -\xd2\x53\x04\xdc\x61\x40\x13\x04\xbc\x03\xe2\x56\x21\xa4\x3d\x40\ -\xea\x33\x1b\x51\x8f\x90\x6d\xbd\xc9\x63\xa9\x94\x3c\x22\x59\x0c\ -\xb6\x8d\x22\x46\x99\x60\x9a\x44\xe0\x19\x20\xfc\x04\xc0\x48\x03\ -\xe1\x5b\x21\xa4\x9a\xb6\x67\x17\x7f\x30\x1c\xfd\xc3\x0a\x80\xa7\ -\x3a\x3c\x0d\x8c\x57\x00\x8c\xd7\x29\xee\x05\xf0\x3a\x11\x5e\x25\ -\x59\xda\xb4\x63\xf5\xe2\xee\x6c\x7c\xcf\x58\x5a\x3f\x72\xe0\xa8\ -\x6d\x16\x01\xd7\x81\x30\x3b\x43\x1b\xfd\x00\xee\x8e\x45\x83\xbf\ -\xcf\x5e\xfd\x20\x86\x1c\x00\xb7\x3f\x72\x3b\x11\xaf\x03\x50\x90\ -\x26\x8a\x39\x1c\x97\xed\x8f\xfd\xb3\x71\xe1\xc1\xa1\xfa\x57\xa2\ -\xdc\x17\x72\x38\xc7\x94\x2c\x20\xa2\x87\x18\x18\x97\x46\x60\x7a\ -\x34\x36\xfe\xc0\x43\xa8\xab\x13\xd9\xfa\xce\x3e\x00\xa1\x90\xe4\ -\xde\x3f\xf6\x11\x02\x3f\xa0\x29\x11\x44\x58\x27\x25\x51\xb7\x7d\ -\x4d\x70\x6f\xd6\x7e\x2d\xe0\xe2\xbb\x1f\x2f\x8e\xdb\x9c\xcb\x40\ -\xfc\x0b\x00\x45\x9a\xe2\x57\xfa\x64\x79\xee\x87\x4f\x2f\xfa\x36\ -\x1b\x9f\xd9\x05\x20\x14\x92\x3c\xfb\xc6\x6e\x04\xf1\xad\x2a\x3b\ -\xa3\x13\x12\x6e\x8c\x3d\x13\xdc\x91\x95\xbf\x21\x62\xfa\xfc\xf0\ -\x84\x94\x8c\x97\x91\x3e\xe1\xee\x92\x1d\x98\xb9\x3d\x12\x3c\x62\ -\xd5\x97\x94\x4d\xc3\xde\xae\x92\xe5\xda\xce\x13\xf0\x2e\x23\xe5\ -\x39\x55\x9d\x07\x80\xed\x6b\x82\x7b\xed\xce\x64\x25\x03\x1b\x35\ -\x45\x53\xc5\x00\x6f\xf4\xf9\x5e\x94\xad\xfa\xb2\x4c\xf4\x06\x22\ -\x3f\x67\x20\xa2\xb4\x11\xd1\xf3\x85\xf1\x62\xdf\xb6\xb5\x35\x87\ -\xac\xfa\xc9\x15\xf6\xbe\xfb\x66\x72\x5f\xfb\xeb\x2f\x9f\xed\x6d\ -\xeb\x03\x70\x25\x4e\x8c\x66\x9a\x74\x68\x44\xef\x88\xce\xf6\x4d\ -\x7f\xb6\xe2\xc7\xd2\x5f\x60\x5a\x20\xe2\x11\xe0\xad\x00\x46\x9c\ -\xb4\xf2\x0b\xb1\x68\xf0\xce\x7c\xac\xce\xb2\x85\xc7\x1f\xbe\x17\ -\x84\x15\x1a\xf3\x5d\xb1\x68\x70\xbd\x59\x5d\xd3\x00\x4c\x5b\xb4\ -\xca\x95\x4a\xf2\x3f\x08\x7c\x8e\xc2\xbc\xa3\x28\x5e\x7c\x59\x6b\ -\x73\x55\x7f\x36\x42\x2b\x16\xae\xb8\x40\x4a\xca\x37\x1e\x5f\x1a\ -\x4f\x00\x63\x02\x88\x52\x00\xf6\x12\x89\xbd\x42\xd0\x4e\x59\xd0\ -\x4b\xd9\xef\x01\x98\x3c\x81\xf0\x5a\x80\xaa\x14\xc6\x01\x66\x69\ -\x46\x7b\xd3\xe2\x9d\x46\x35\x4d\x03\xe0\xf1\x87\xd7\x82\x70\xf7\ -\xc9\xb6\xd0\x99\x72\x90\x77\xd7\xaa\xda\x4e\x2b\xd2\xca\x7d\x21\ -\x47\x61\xc9\xd8\x1a\x06\x57\x03\x38\xdf\x4a\x1d\x00\xbb\x88\x10\ -\x9e\xd8\x5d\xba\xa1\xa5\xe5\x96\x94\x95\x0a\x3f\xa8\x0d\x17\x8c\ -\x4e\xe0\x6d\x30\x7e\xac\x30\xef\x2c\x2a\xed\x9e\xde\x5a\x57\x97\ -\xcc\x54\xcf\x70\x12\x74\xfb\x1b\x2e\x51\x75\x1e\x60\x21\x63\x8e\ -\xd5\xce\xbb\xfd\x91\x1b\x9c\x63\x5c\x1f\x30\xb8\x01\xd6\x3b\x0f\ -\x00\x53\x99\xf1\x5c\x47\x49\x57\xac\xa2\x3a\x32\xcb\x4a\x85\x4f\ -\x23\xc1\xb8\x9c\x14\x37\x01\x38\xa0\x30\x57\xf4\xee\x73\x2d\x34\ -\xaa\x67\x30\x02\x98\x3c\x81\xc8\x5f\x01\x5c\xa2\xb0\xbd\x10\x8b\ -\x2e\x99\x6b\x26\xc6\xed\x8f\xda\x41\xfd\x0d\x04\x32\x6c\xdc\x32\ -\x88\xeb\x62\x67\xf5\x3c\x6c\x65\xa1\xa3\x33\x1f\x1c\x18\xe8\x8b\ -\x4f\xdc\xbd\xe1\xbe\xa3\x7a\xfc\x8c\x23\xc0\xbb\x20\x52\x09\x55\ -\xe7\x91\x80\x94\x0a\x99\x09\x98\x5c\xf3\xf4\x18\xa2\xf8\x1b\x39\ -\xeb\x3c\x00\x30\x85\x3c\xfb\x5d\x7f\x74\xfb\xa3\x4e\x33\x6a\xd1\ -\x40\xf1\x33\x00\xbe\x52\x98\xc6\xda\x9d\x8e\x40\x26\x7e\xc6\x00\ -\xb0\x84\xfb\xd4\x06\x44\x63\x8d\xcb\x3e\x37\x6a\xbc\xdc\x17\x72\ -\x14\x88\xd4\x2b\x00\xae\x30\x13\x3a\x04\xdc\x4c\xe8\x5f\x8f\x50\ -\xc8\xf0\x6f\xdb\xda\x5c\xd5\x4f\x04\xcd\x83\x92\x96\x65\x5a\x1b\ -\xe8\x3a\xf3\x2e\x5c\x5d\x0a\xe0\x6a\x85\x29\x21\x0b\xf1\x88\xb1\ -\x3e\xa6\x42\x97\x6b\x35\xc0\x95\xc6\xbc\x61\x80\x68\x8e\x7b\xbf\ -\xcb\x74\x14\x4e\xec\x2e\xdd\xc0\xc0\x27\x27\xaa\x81\xcf\xf9\xcc\ -\xd5\x75\xa5\x1e\x57\x37\x00\x22\x95\xbc\x1d\x8a\x45\x12\x01\x6f\ -\x6f\x5f\x73\x6f\x97\x51\xa3\xde\xc0\xaa\x3b\x98\x31\xdf\x4c\xdc\ -\x70\x41\xc0\x43\x9e\x05\x61\xdd\xce\x7c\x87\x96\x96\x5b\x52\x44\ -\x68\x51\xda\x24\xe6\xbb\xf4\xb8\xba\x01\x20\xd0\x75\x1a\xcb\x9f\ -\x8c\x1a\x74\xfb\xa3\x4e\x01\x3c\x66\xc4\xc9\x29\x24\xd4\x9b\x2d\ -\x77\x59\x08\xad\xe6\x6b\xf4\xea\xa4\x05\x60\xca\xdc\x27\x0a\x01\ -\xd5\xbb\x14\x82\x53\xaf\x19\x0a\xa2\xf8\x32\xcd\x42\x29\xdf\x98\ -\xdc\x51\xd2\x35\xcf\x88\xd0\x3e\xfe\x60\x1b\x00\xe5\xa8\x1d\xd5\ -\xe1\xda\xef\xd6\xf2\xd2\x02\x50\xe0\x74\x5c\x04\xc0\x71\xd2\x42\ -\xef\xb5\x37\xdd\xfb\x95\x96\xf7\x1d\x7c\xbe\x17\x65\x22\x04\xcd\ -\x35\xe7\x1a\xbc\xc4\xb0\xb8\xae\x4e\x00\xac\x7a\x70\xcc\xe9\xe7\ -\x94\x3a\x7f\x01\xe9\x47\x1a\xc3\x56\xa3\x76\x3a\x5c\x5d\x97\x82\ -\x71\xa6\xa1\x98\xfc\x60\xf2\xf4\xc0\xca\x1f\x1a\x11\x98\xd5\xda\ -\x89\x71\xa1\x96\x93\x16\x00\x66\xbe\x40\xf5\x1b\xe2\x13\x2d\x47\ -\x53\xe1\x66\xc3\xf2\x3c\x22\xc9\xd2\x1c\xa3\x72\x89\xa1\xd6\x4e\ -\xb8\x20\x8d\xa3\x35\x10\x61\xa2\xca\xc0\x64\xf8\xee\x07\x28\xaf\ -\xa7\xc0\x86\x2d\x13\xa7\xfd\xa7\x55\xb0\xdb\xb4\xda\xcb\xb4\x94\ -\xf4\x11\x40\x28\x56\x35\x22\x91\xc9\x5e\xff\x94\x4e\x7e\x2a\x10\ -\x30\xc1\xa8\xbc\xb0\xcf\xa9\xd5\x5e\xac\xe5\xa4\xcf\x01\xac\x26\ -\x49\xcc\x99\xcf\xd8\x06\x57\x65\x7a\xa7\xb5\xa7\x04\x6c\x12\x80\ -\xd6\xe6\x79\x71\x00\xca\x9d\xa0\xa3\xdc\x17\x72\x28\x39\x7a\xeb\ -\x00\xd5\x06\x29\x29\x89\x8c\x07\x1e\x33\x07\xeb\x67\x75\xac\x96\ -\x63\xd8\x87\xeb\x40\x4f\x7c\xaf\x8a\xc0\x72\xda\xb0\xf9\x0e\xc7\ -\xf7\xd9\x86\x2b\xc4\xbc\x82\x61\x78\xfa\x3c\x73\x5e\x73\x01\x00\ -\x9b\xc2\x34\xf0\x61\x4b\xdd\x80\x92\x93\x3e\x09\x02\xaa\x13\x55\ -\x16\x3c\xda\x44\xc4\xbf\x4c\x85\xe6\x0b\x64\x1c\x80\x63\xb6\xc3\ -\xa3\x34\xa6\x5e\x2d\x27\x7d\x12\x04\x7d\xa9\x6a\x43\x4a\x9f\x39\ -\xd5\xe5\xf4\xbe\x51\x79\x5e\xc1\xc6\x6d\xb3\x6c\x3b\x4f\x6d\xc0\ -\x17\x5a\x8e\xce\x24\xc8\x1f\x29\x7f\x12\x60\xbc\xd8\x20\xbc\x64\ -\x54\x9e\x4f\x30\xc8\xb0\x6d\x01\xa1\xd2\xce\x84\x3d\x5a\x4e\x7a\ -\x00\x48\x52\x5d\x36\x32\xab\x0e\x45\xd2\x50\x74\xac\x68\x33\x80\ -\xac\x6e\x63\x72\x02\xc6\x97\xed\x4d\x8b\x76\x19\x53\x34\xda\x75\ -\x46\x4c\x5a\x00\xfa\x64\xda\x06\x40\x79\xff\x5e\x31\x7d\x7e\x38\ -\xe3\xeb\xa6\xb5\xb9\xaa\x1f\x8c\x66\x33\xbd\x79\x40\x93\xe1\x91\ -\x7c\x28\x24\x11\x70\xad\xd2\xc4\x32\xb7\x6a\x69\x69\x01\x18\xbc\ -\x5b\xa3\x6d\x4a\x5b\x52\xa6\x6b\xb5\x3c\x25\x52\x09\x3c\x0c\xe0\ -\xb0\x89\xe0\x5c\xe2\x6b\x7b\x61\x52\x7b\x0f\xa0\x82\xb7\x73\x8c\ -\x1b\xea\x35\xca\x91\x33\xc6\x75\xc7\xb4\x3c\xfd\x77\x38\xab\x77\ -\x51\x44\x3c\xdb\xa8\xb1\x5d\xcf\x05\xbf\x21\xb0\xc9\x89\x51\xee\ -\x40\xa0\x07\xb7\xad\x58\x76\xcc\x90\x24\x49\x2a\xcd\x0c\x6c\xd2\ -\x3b\x1e\xd7\x0d\x40\xca\x41\x1b\x01\x9c\x3c\x81\x65\xcc\x9a\x5a\ -\x15\x36\xdc\xf1\x15\x96\xf6\x34\x10\xf0\xa6\xa1\xa8\x5c\x80\xb1\ -\xa1\x2d\xba\x58\x7b\x27\xa8\x46\x28\x24\x31\xa0\xda\xa4\x11\xf8\ -\x79\x3d\xaa\x6e\x00\x8e\x9f\xfb\x6f\x56\x98\x0a\x64\x7b\xda\x75\ -\xb8\x0a\xad\x75\x75\xc9\x44\x3c\x75\x2b\x80\x8f\x0d\xc5\x0d\x03\ -\x04\xbc\x5b\x34\x50\xec\x37\xbb\x8e\xf3\x76\xb9\x6e\x83\xfa\x1e\ -\x62\x7f\x51\x69\xcf\x66\x3d\x6e\xc6\x65\x2c\x81\x9f\x54\x1b\x68\ -\xd1\xd4\x45\xab\xce\x35\x6a\xf8\xbd\xe6\xa5\x87\x20\x25\xaf\x41\ -\x7e\x82\x10\x93\x52\xe2\x06\xb3\xeb\xb8\x72\x5f\xc8\xc1\x8c\xdf\ -\xa8\x8c\x44\x2b\x32\xdd\x0e\x65\x0c\x40\x5b\x34\xf8\x36\x00\xe5\ -\x64\xe8\x90\x92\x62\xb9\xa9\xca\xc6\x65\x9f\x27\xe3\xa9\x8b\xa0\ -\x1e\x41\xc3\x03\xd3\x1f\xec\xce\x64\xa5\xd9\xc1\x2c\x00\x38\x5d\ -\x2e\x3f\xd4\xdb\xde\x9e\x82\x81\xbe\xc6\x4c\x7c\x83\x8d\x0c\x31\ -\x88\x1e\x54\x59\x80\x3b\x2b\x6a\x56\x1a\xef\xc1\x31\x38\x12\x8a\ -\x4a\xbb\x7f\xc6\xc0\xaf\xa0\xb3\xfc\xcc\x02\x07\x18\x54\x13\x6b\ -\x5a\x7c\xbb\xe9\xa4\x07\xc0\xed\x7f\x72\x2c\x31\x7e\xad\xb4\x31\ -\xe3\xb7\xef\xac\xfb\x65\x46\x0d\x56\x2e\x47\xd7\x83\xa0\xbc\x0e\ -\xfb\x5a\x4e\x09\xaf\x95\xa7\x01\x00\x53\xaa\x1b\xc7\x15\x20\xb1\ -\x9c\x19\x77\x01\x30\xbd\xd9\x39\x8e\xc3\x44\xdc\x28\xc4\x88\xc7\ -\xda\x9b\x02\x96\x5e\xaf\xe5\xbe\x90\xc3\xe9\x72\x6d\x06\xe3\xb2\ -\x13\x46\xc6\x6e\x46\x81\xc7\x28\xaf\xd0\x34\x00\x53\xaa\x1b\xc7\ -\x39\x38\xb1\x1b\xc0\x59\x8a\x5a\x7f\x3f\x64\xc7\xac\x4f\x23\xc1\ -\xb8\x15\x71\xc0\xe0\xd1\xb9\x44\xf1\xab\x41\x3c\x87\x99\x26\x03\ -\x38\x07\x40\xc9\x71\x7f\xdf\x30\xa3\x93\xc0\x3b\x21\xa4\x96\xbe\ -\x43\x07\xde\xd2\xee\xda\xcc\xe0\x09\xac\x6c\x04\xa8\x5a\x61\x4a\ -\x80\x70\x89\x59\xe6\x8a\xa5\x04\x89\x8a\x9a\xf0\x45\x92\x40\x2b\ -\x94\x19\x61\x8c\x75\xb1\xa6\xda\xf9\xc3\x49\x90\x98\xb1\xb4\x7e\ -\xe4\x37\x49\x9b\xc8\x26\x90\x7a\xf0\x06\x22\x0b\x19\xbc\x5a\x6d\ -\xa5\xf9\xb1\x68\xed\x5a\xb3\xba\x96\x93\xa4\x3c\xd5\x2b\xe7\x82\ -\x49\x93\x71\x41\x4d\x7d\x3d\x07\x6a\xb3\x7d\x5a\xb9\x03\x93\xdb\ -\x1f\xa9\xa5\xc1\xdb\x60\xe5\x7c\xd6\x10\x8b\x06\x97\x5a\xf1\x60\ -\x39\x47\xa8\x33\xb6\x69\xf7\xd9\xee\xab\x9d\x20\xba\x58\x61\x76\ -\xdb\x9d\xce\xca\xf1\x15\x57\xbc\xb6\xaf\x7d\x73\x9f\x55\x5f\xb9\ -\x40\xb9\x2f\xe4\x38\xf7\xd2\xdd\x51\x1a\x9c\xa8\x4f\x3c\x48\x02\ -\xde\x2c\x2a\xed\xae\xfa\x62\xcb\x16\x4b\x39\x83\x59\x1d\x67\x95\ -\x1d\x1c\xff\x20\x83\x5e\x56\x19\x19\x97\x81\x1c\x6d\x6e\x7f\x64\ -\x72\x36\xbe\x86\x83\x29\xd5\x8d\xe3\x9c\x25\xae\xb7\x00\xba\x47\ -\x53\xf4\x41\x22\x9e\xba\xd5\x28\x23\x44\x8b\xac\x13\x25\x7d\xbe\ -\x17\xe5\x8e\x31\xfb\x9e\x00\x91\x76\x88\x25\x88\xd0\x18\x87\xfd\ -\xd1\xdd\xcf\xd4\xfc\x3b\x5b\xbf\x56\x30\x63\x69\xfd\xc8\xc4\x51\ -\xdb\x62\x10\x1e\x00\x30\x46\x55\x48\x78\x83\x45\xc1\x6d\x56\xdf\ -\x1a\x27\xab\x0d\x11\x9e\x40\xe4\x1e\x80\x1b\x91\x7e\x30\xf9\x2d\ -\x88\x9f\x92\xed\x54\x9f\x4d\xc2\xa2\x11\x66\x86\x42\xb6\xde\x7d\ -\x25\xf3\x40\xd2\xf2\x0c\x77\x90\xf5\x65\x3d\xa5\xf7\x5b\xcd\x27\ -\x52\x62\x58\xc9\xd2\xde\x40\x43\x25\x43\x7a\x09\x80\x4b\xa7\xf8\ -\x20\x80\x57\x01\xbc\x2a\x3b\xb0\x39\xdb\x60\x94\xfb\x42\x0e\xe7\ -\x68\x57\x25\xc9\xb8\x8e\x05\xae\x07\x41\x6f\x19\x9e\x00\xa8\xc6\ -\xca\x6c\x9f\x09\xc3\x4e\x97\xf7\x2e\x5c\xfd\x3d\x4e\xa5\x1a\x00\ -\xdc\x64\x40\x4b\x80\xb0\x05\x02\x7f\x81\x44\x1f\x4b\xcc\x9f\xb2\ -\x2c\xf7\xf4\x33\x7d\xeb\xb4\x25\x53\x52\x22\x59\x2c\xd8\x36\x2a\ -\xc9\x28\x23\x89\x26\x81\xc5\x0c\x80\xae\xc2\xe0\x27\x35\x99\x94\ -\xb7\x09\xe2\x9a\x9d\x8d\x4b\xda\x87\xa3\x3f\x67\x1f\x4c\x78\x16\ -\x44\x7e\x0a\x89\x1f\x07\x90\xdf\xc9\x70\x30\x2f\xf9\xe1\xb2\xee\ -\xd2\x35\x43\x19\xf2\x5a\xe4\xf6\x93\x99\x50\x48\x9a\xd6\x55\x72\ -\xbd\x00\x3d\x00\x86\x37\xa7\xbe\x41\x9f\x83\x45\x7d\xd1\xc0\x19\ -\x6b\xb3\x4d\xd0\x34\xf4\x9a\x2b\x47\x5a\x78\x17\xac\xba\x50\x48\ -\x3c\x8f\xc0\xb3\x01\x4c\x1a\xa2\x9b\xfd\x60\xbc\x4e\x24\x9e\x6f\ -\x2b\x3d\xf8\xb7\xa1\x7c\x0f\x60\x86\x53\xf2\xd9\xdc\xf1\x79\xe2\ -\x72\x30\x5f\x08\xd0\xf9\x20\x94\x01\x18\x85\xc1\xff\xb8\x8d\x41\ -\x87\x89\x71\x04\xc4\x5f\x13\x61\x8f\x10\xd8\x63\x23\x6c\xd9\x1e\ -\xad\xfd\xe8\xbf\x21\x17\xf9\x34\x4e\xe3\x34\xfe\x77\xf1\x1f\x1c\ -\x6b\xc6\x54\xc2\x9c\x88\xf8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\x9b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x46\x72\x80\xb6\x71\x9f\xe6\ -\x09\x5c\xad\x0d\x32\xa5\xe3\x7b\xc7\x1f\x84\xef\xaa\x08\x25\x53\ -\x5b\xae\xb6\xfc\x75\x8f\x1a\x05\xc3\x4c\xee\xd7\x7a\xe5\xe8\x67\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\xff\x8c\ -\x9a\xec\xd4\x4e\x41\x07\x39\xb5\x09\xe5\x39\xad\x0d\x4e\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xc7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x79\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\xb3\x9b\x72\x03\x3a\x70\x82\ -\x82\x84\xc4\xd4\xb9\xe5\x00\x48\x70\x85\x0e\xb0\x54\xdc\x20\x1c\ -\xa1\x1b\x54\xe2\x12\x88\x05\x09\xa9\x99\x91\x3a\x51\x28\x27\x60\ -\x80\x89\xb9\x21\x35\x43\x15\xa1\xb6\x69\x63\xa7\x4e\x18\xf0\x68\ -\x3f\xf9\xf7\xc9\xb6\x9e\x0c\xff\x7d\x48\x95\x58\xab\xdb\x6f\x24\ -\x5a\xdf\x81\x79\x1f\x0d\x7a\x67\x00\xaa\x52\x5c\xe9\x08\x4c\x0b\ -\x64\x2f\x9d\xaf\x55\x8a\x8b\x69\x62\xe4\x4d\xcf\x92\x93\x74\xad\ -\xf4\x2b\xc8\xc0\xdb\x4f\xb7\x97\x1f\x95\x04\xc8\xc3\x4b\x0d\x60\ -\x83\x97\x16\xc0\x16\x2f\x25\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\ -\x11\xdc\x5b\x00\x5b\xfc\xf0\xfc\x7a\xb7\x6e\xe2\x07\xe0\x6b\x34\ -\xe8\x75\xc0\x43\x27\x74\xc4\x87\xc0\x11\x50\x4f\xe7\xb7\x0a\x50\ -\x00\x3f\x00\x5e\xa6\x12\x9c\xa6\x6b\x85\xaf\x60\x0b\xfc\xf8\xf9\ -\xe6\xe2\x73\xab\x00\xbe\xf0\x42\x01\x5c\xf0\xc0\xc4\x91\xc0\x3e\ -\xf0\x3a\x95\xa0\xb3\x8c\x3b\x07\xf0\x8d\x3b\x05\x28\x03\x07\xd0\ -\x3e\xf1\x56\xb7\xdf\x10\x31\xd6\x38\x58\x9c\x80\x0b\xfe\xad\xd5\ -\xd0\x05\xcf\x0d\x50\x04\x37\x30\x89\x25\x68\x67\xe1\x4e\x9d\xb0\ -\x24\x7c\xa5\x13\x66\xfe\x09\xcb\xc0\x03\x13\x47\xcc\xaf\x67\xa1\ -\x13\xae\x3c\x42\x17\x3c\x51\x3a\x12\xd9\x8c\x67\x3c\xcc\x85\x66\ -\xa4\xb2\x36\xb5\xc5\x11\xd3\x34\x30\xa9\x25\xb3\xcc\x07\x67\xf3\ -\x30\x25\x6b\x53\x57\xdc\xa6\x6e\xdd\x09\xcd\x4f\x20\x0c\x55\xa2\ -\xd5\x63\xfe\x67\xc2\x48\x52\x53\xf7\x79\xf8\x72\xdd\x3a\xfc\x37\ -\xc0\x7c\xec\x00\xe3\x8d\x3f\x99\xf0\x4a\x8c\xa1\x0e\x8c\xd7\xe3\ -\xab\x75\x36\xfd\x00\xc2\x50\x81\xb1\x68\xcd\x46\xfc\xd6\xfd\xf1\ -\xf8\x01\x9a\x8b\x01\xab\xe8\x4a\xa0\x68\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x2a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdc\x49\x44\x41\x54\x58\x85\xed\ -\x95\xbf\x6b\x53\x51\x14\xc7\x3f\xdf\x9b\x68\x4a\x07\xab\x06\x2a\ -\xb5\xab\x2e\x82\x54\x92\x06\x51\xe9\x6c\x8b\x9d\x44\x07\x51\x70\ -\x32\x3f\x14\x2b\xfe\x05\x21\x9b\x93\xc5\x18\x85\x66\xea\xe6\xe2\ -\xa0\xa0\x54\xbb\x05\xec\x52\x1a\xd4\xbf\x40\xa7\xaa\x83\xe2\x24\ -\xb4\x4d\xee\x71\xc8\xb3\xa9\x69\xaa\xcd\x6b\xc4\xe5\x7d\xe0\x0d\ -\xef\xde\x7b\xce\xf9\x70\xee\xbb\xef\x42\x44\x44\x44\xc4\x7f\x46\ -\x61\x03\xcf\xe4\xef\x8f\xae\x5b\xfc\xa5\x60\xac\xb9\x4f\xa3\x6f\ -\x2b\xb7\x57\xc3\xe4\x71\x61\x82\x4e\xe7\x1e\x1c\x5f\xb7\xf8\x1b\ -\xc1\x18\x80\xdb\xb0\xa5\xd4\xcd\x47\xc7\xc2\xe4\xea\xb9\x03\x99\ -\x1b\xb3\xa7\x70\xb1\xd7\x06\xc3\x1d\x53\x5f\x1c\x9c\x5f\x9e\x9b\ -\x79\xdf\x4b\xbe\x9e\x3a\x90\x2a\x94\x27\xcc\xc5\x6a\x06\xc3\x18\ -\x06\x34\x5b\x8f\x0c\x38\xe2\xa1\x96\x2a\x94\x27\xfe\x89\x40\x2a\ -\x5f\x99\x76\x9e\x45\xe0\x80\x81\x21\x7c\x7b\xd6\xbc\x99\x0c\x18\ -\x72\x9e\xc5\x74\xb6\x7c\xa1\xaf\x02\x99\xdc\xc3\x6b\xce\xfc\x33\ -\x60\x00\x30\xb1\xb5\x78\x0b\xc9\x7c\xd0\x95\x01\x89\xe7\x99\x7c\ -\xf9\xea\x6e\x72\xc7\xfe\xb6\x20\x9d\x2d\xcf\x20\xaa\x81\xac\xd1\ -\xa5\x78\xdb\x02\xc3\x10\xc2\x01\x17\x47\xc6\x27\xbf\x7d\xaa\xbf\ -\x5a\x0e\x29\x60\x4a\xe7\x92\x25\x89\x7b\xc1\x80\x0f\x04\xfe\x8c\ -\x30\x13\x08\x24\x34\x75\x34\x33\xa9\xd5\x95\x85\x1a\x94\x76\x58\ -\xde\x8d\x62\xd1\x8d\x7f\x4e\x96\x81\x5b\xb4\xaa\x7a\xed\xa6\xf8\ -\x56\x7d\x4c\x42\x2e\x78\xa9\xac\x8c\x7c\xbd\x43\xa9\xb4\x7d\xeb\ -\x3a\x07\x4e\x5c\x2e\xee\x1f\x3c\x9c\x9c\x07\xae\x00\x98\xf0\xb2\ -\xde\x8a\x6f\x4a\x08\xc9\x36\xbf\xb3\x27\x66\x89\xeb\xf5\x6a\x6e\ -\x63\x47\x81\x74\x76\x6e\x50\x6e\xed\x29\xc6\x14\x06\x26\xf3\x6a\ -\x1d\xb1\xd0\xfc\xd6\x09\xb1\x60\x3e\x71\xa9\x5e\xcd\xfd\xd8\x26\ -\x70\xb2\xf0\xf8\x50\xc2\x1a\x2f\x30\xce\x06\x81\x7b\x2e\xde\x96\ -\x40\x6a\x9f\xb8\xa5\xc6\x5a\x73\xfa\xdd\xfc\xdd\xef\x00\xf1\x5f\ -\x8b\x12\xbe\xf1\x01\x18\x6a\x9b\x29\xd4\x6f\xba\x1b\x1d\xfb\x7c\ -\x2e\x9e\x88\x7f\x04\x0e\x42\xc8\xbb\x60\xef\xf4\xa5\xb1\x11\x11\ -\x11\x11\xfd\xe1\x27\x68\xea\x98\xa0\x5e\x6e\x43\xde\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x47\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xf9\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\x5b\xa6\x04\x04\x0a\x6c\x43\ -\x9a\x54\x92\x20\xd8\x03\x2c\x80\x75\x60\x58\x00\x61\x01\xb3\x09\ -\x3c\x92\x64\x58\x06\xba\x06\x53\x12\x32\x0e\x41\x86\x0e\xf3\x2e\ -\x96\xbc\x07\xb8\xbe\x49\xe8\xff\xc9\x73\x2b\x4e\x8f\x69\x25\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x60\x12\xec\xaf\xa3\xbb\x9b\xa4\ -\x32\x53\x97\xb1\x04\x33\x0b\xbf\x1d\x7f\x1c\xa0\xef\xfb\xc3\xe1\ -\x73\x33\x37\xd9\xa5\xa4\xfd\xd1\xaa\xe5\xb1\x92\xf4\x50\x98\x5f\ -\xd5\x75\xfd\x12\x1f\x93\x01\xba\xae\x3b\x98\x55\x7b\x4f\x92\x1f\ -\xe7\x68\x97\x8d\x6b\x19\xc2\xfa\xa4\x69\x9a\xd7\xef\x71\x11\x3f\ -\x57\x55\xbb\xb7\xff\xee\xe5\x25\xc9\x74\x54\x94\xb3\x79\x1c\x27\ -\x03\xb8\x74\x9e\xa7\xd1\x56\x5c\xc4\x41\x32\xc0\xd4\x24\x03\x98\ -\xf4\xb8\x8d\x22\x99\x2c\xe2\x20\x19\x60\x18\x3e\x6e\x24\x7b\xce\ -\x52\x27\x27\xd7\x32\x6c\xd6\xd7\x71\x9c\x0c\xd0\xb6\xed\xdb\x4e\ -\xa9\x33\x97\xdf\x49\x7a\xcf\x52\x6e\x5c\x2b\x49\xf7\x45\xe1\xa7\ -\xf1\x17\x40\xe2\x47\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x98\ -\x8a\x2f\xe6\x4f\x38\x6a\x74\xad\x97\x2f\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xef\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa1\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x4d\x78\xc2\x0f\x86\x41\x46\ -\x78\x34\x06\xd6\xdb\x18\xd0\xda\xe7\xae\x7d\xae\x6c\x98\x72\xfc\ -\x07\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\ -\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\ -\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\ -\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\ -\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\ -\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\ -\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\ -\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x1e\x06\x73\x04\xd7\x28\x98\ -\xcd\x67\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x52\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x04\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x4f\x14\x51\x14\xc5\xcf\x99\xac\x05\x6c\xa9\x1b\xbe\x7a\ -\x1b\x59\x1a\xe2\x62\x21\x35\x35\x9f\x46\x12\xb1\x93\x68\x02\x5a\ -\xc2\x5f\xa0\x35\x98\x08\xa5\x9a\x48\xc2\x67\x2c\xa9\xb1\x20\x24\ -\x34\x2c\x54\xd6\x2c\x12\xb4\xdc\xa5\x60\x9d\x63\xe1\xb2\x3b\xcc\ -\x0c\x1f\x22\xbb\x77\x37\xbc\x5f\xb5\xf7\xdd\x3b\xc9\x79\x27\xef\ -\xcd\x6c\x71\x2f\xe0\x70\x38\x6e\x33\xbc\x4a\x51\xd7\xba\x92\x4d\ -\x79\x8c\x80\x1a\x22\xd0\x29\xa1\x1d\x40\xa2\xca\xda\xfe\x95\x22\ -\x89\x9c\x80\x5d\x88\xcb\xc7\x49\x2c\xee\xf4\x31\x7f\xd9\x43\x17\ -\x1b\x20\x31\xb3\x86\x31\x42\x6f\x01\xb4\xdd\x94\xd2\x1a\x71\x20\ -\x70\x6a\xab\x1f\x9f\x41\xea\xbc\xa2\x73\x0d\xe8\x9e\xd7\x9d\x44\ -\xca\x9f\x05\x38\x5e\x1d\x7d\xb5\x42\xf3\xc5\x23\x6f\x62\x7b\x9c\ -\x27\x71\xd9\xf8\x63\x2c\x31\xb1\xea\xbf\x07\xf8\x22\x94\xc9\x4a\ -\xfa\x46\x7a\x3f\x48\xf8\x37\x2d\xf5\x7f\x90\xe0\x49\x7e\x2b\xc9\ -\xc7\x00\xd2\x95\x0c\xc7\x13\x29\x1f\x90\x5e\xc6\x9d\x84\xd8\x13\ -\x90\x59\xd5\x18\xa1\x8f\x81\xa5\x5f\x12\x27\xb7\x06\xb0\x70\xd1\ -\x71\xaa\x0b\x24\x66\x56\xf1\x94\xd4\x0c\x80\xbb\xe5\x65\xf0\xf9\ -\xd6\x00\x3f\x85\xcb\x23\x06\xfc\x7d\xe1\xe9\x3b\x2a\x77\xfe\x67\ -\x51\xec\xda\x1e\xe4\x41\xd5\x44\x57\x81\xee\x15\xb5\x25\xa8\x1d\ -\x00\xf7\x4a\x4b\xb9\xe3\x24\xef\x87\x5f\x8c\x5e\xf8\xc1\xa6\x3c\ -\x46\x10\x78\xe1\x49\x7c\xdd\x68\x9b\x07\x80\xed\x41\x1e\x10\x7c\ -\x13\x58\x6a\x6f\x2e\x60\x38\x5c\x17\x31\x00\xd4\x50\x20\xca\x6e\ -\x0d\x60\xa1\x0a\xfa\x6a\xc2\x66\x3f\xbe\x00\xc8\x9e\xc6\x82\x2e\ -\x37\x80\x40\x67\x25\xd0\x46\xdd\xdf\xf9\x8b\x20\x05\x6a\xa3\x1c\ -\x0b\x0f\xc2\x25\x11\x03\x4a\x7f\x72\x4a\x81\x77\x58\x2d\x6d\x35\ -\xe3\xec\x1e\x3a\xc2\xe9\xe8\x15\x08\x7c\x1a\xeb\xed\x53\x77\x1d\ -\x42\x7b\x88\x7c\xf6\xe3\x0c\xb8\x55\x38\x03\xac\x05\x58\xe3\x0c\ -\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\ -\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\ -\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\ -\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\ -\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\ -\x05\x58\x13\x67\x40\xf1\xf4\x87\xd4\xf8\x06\x85\xf6\x50\x0c\xe7\ -\xa3\x6d\x72\x44\xae\x12\xf8\x2d\xd5\x91\x55\x43\xce\xee\x61\x3f\ -\x9c\x8e\xb6\xc9\x01\xbb\x95\x80\xbd\x90\xae\x34\x53\x50\x97\x48\ -\x84\xd8\x5b\x8e\x89\xbd\x70\x49\xf4\x88\x8b\xcb\x81\x28\xfd\x68\ -\x15\x23\x55\x11\x57\x03\x7a\xd6\xf0\x04\x81\xce\x71\x82\x4b\xe1\ -\x9a\x88\x01\xc7\x49\x2c\x02\x28\xf7\x06\xfb\xd4\x6c\xcf\x57\x35\ -\xdc\x55\x78\xb8\xa8\x56\x41\x33\x81\xa5\x5c\xa1\x19\x97\x1b\xb0\ -\xd3\xc7\xbc\xc0\xa9\xd3\x98\x40\x4a\xbf\x95\xcd\xac\x68\xb4\x21\ -\xae\x83\xc4\xcc\x8a\x46\x99\xd0\x0e\x81\x54\x79\x19\x9c\x8e\x1b\ -\xa1\x89\xdf\x90\xc4\x9e\x35\xff\x43\xcc\xb4\x48\x16\xd4\x06\xe4\ -\x1d\xd6\x5b\x17\xa9\x04\x0f\xf4\x5b\x4a\x77\x3e\x1d\xcc\x11\x9a\ -\xdb\xec\xf7\x5e\xc5\xf5\x3d\xc7\x4f\x8c\x90\x2a\xce\x6b\x22\x91\ -\xf2\x11\x32\x21\x0d\x31\x0d\x08\xaa\xc7\x16\xea\x98\x03\x4a\x68\ -\xee\xe4\xc8\x9b\x3c\xaf\xe9\xfb\x2a\x43\x53\xcf\x08\xbd\x43\xe3\ -\x0d\x4d\xe5\x04\x4e\x5f\x7b\x68\x2a\x48\xd7\xba\x92\xcd\x05\x0c\ -\x0b\x1a\x2e\xb5\x9c\x77\xa0\x0e\xc7\xe6\x00\xec\x83\xd8\x23\xb8\ -\x54\x68\xc6\xd2\x55\xc6\xe6\x1c\x0e\xc7\xed\xe6\x0f\xfd\x5b\xf6\ -\x1a\x3c\xff\xda\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\xc5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x77\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x0d\xc2\x40\x10\x04\xc0\x3d\xe8\x01\x51\x0a\x75\x20\x3a\ -\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x8e\x8d\ -\x25\x3c\x13\xae\x2e\xd8\xdb\x04\x00\x00\x00\x00\x00\x00\xd8\x82\ -\xea\x83\xd3\xad\x9d\x5b\xda\x98\xe4\xb0\x42\x9f\x25\x4d\x79\xd7\ -\xf5\x71\xa9\xfb\x77\xb8\xeb\xaf\xfe\xf4\xf9\x24\x39\xd6\xbe\x8d\ -\x7d\x38\x1b\x60\x6b\x66\x03\x54\x6a\x48\xf2\x5c\xa1\xcb\xd2\xa6\ -\xf6\xaa\x61\xed\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xef\x7d\x00\ -\x4e\xfe\x12\x08\x2a\x3f\xe7\x81\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x05\x27\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xd9\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x68\x14\x57\x1c\xc7\xbf\xbf\x99\xd1\x42\xd3\x22\x76\x85\ -\xdd\x90\xa2\x87\xc6\x43\x45\xb0\x24\x5b\xf6\xe0\x65\xa1\xb5\x17\ -\x6d\x2e\x6d\x6a\x4b\x55\x3c\x84\xac\x8d\x36\xe6\xd2\x82\x81\x66\ -\xb2\x81\x62\x6b\x2f\xd9\x60\xc4\xb5\x81\x16\x1a\x5a\x34\xf6\x12\ -\x22\x94\xb4\x87\xa0\xbd\x2c\xd9\x78\x90\xba\xbd\xd8\x83\x21\xd6\ -\xac\x10\x45\x30\x48\xc2\xce\xfc\x7a\x48\x5e\x3b\xbb\x3b\xbb\x3b\ -\x9b\xf9\x9b\x66\x3f\xb0\x87\x79\xf3\x9b\x79\xbf\xf9\xee\xf7\x37\ -\xf3\x66\x78\x0f\x68\xd0\xa0\xc1\x56\x86\xac\x04\xc5\x55\x55\x59\ -\x5e\x0c\x75\xe8\xc0\x51\x02\x45\x01\x6e\x01\xf0\x82\xcb\xb9\xd5\ -\xcb\x0a\x40\x0f\x18\x9c\x95\x80\xab\x4d\x91\xa5\xc9\x99\x64\xb2\ -\x50\xeb\xa0\x9a\x02\x44\x13\x17\x0f\x81\x39\x05\xe2\xd7\x9d\xc9\ -\xd3\x1b\x18\xc8\x11\xa4\xbe\x6c\xfa\xcc\xaf\xd5\xe2\xa4\x2a\xa7\ -\xa0\x68\xf7\x48\x3f\xa0\x4f\x6f\xb6\x8b\x07\x00\x02\xf6\x01\xfa\ -\xf4\x9b\x89\xd4\x39\x80\x2b\xfe\xd1\x72\xa5\x1d\xd1\xee\x50\x3f\ -\x08\x5f\xba\x93\x9e\x97\xd0\x5b\x2d\xd1\xcc\xca\xdf\x73\xbf\xfc\ -\x6e\xba\xd7\xac\x31\x9a\xb8\x78\x08\xd0\xa7\x4b\x9a\x9f\x80\x30\ -\x20\x15\xe8\xc6\x9e\xa7\xe1\xf9\x89\x89\x0f\x34\xc7\x73\xb5\x41\ -\x67\xe7\x35\xf9\xfe\x8e\xfc\x6e\x5d\xe1\xc3\x60\x0c\x01\xd8\x59\ -\x1c\x21\xbd\x63\x56\x0e\x65\x02\xc4\x55\x55\x79\xf6\x70\xd7\x9d\ -\x22\xdb\x13\x7e\x93\x0b\xfa\xb1\xcc\x58\x5f\xde\xf9\xd4\x9d\x27\ -\xd6\x35\x1c\xd6\x14\x69\x1c\x8c\xb7\x45\x1b\x03\xb9\x97\x23\x4b\ -\x07\x4a\x6f\x8c\x65\xf7\x80\xe5\xc5\x50\x47\x49\xcd\x3f\x5e\xc5\ -\xb6\x8f\x37\xcb\xc5\x03\x40\x66\xac\x2f\x2f\x17\xf4\x63\x00\x9e\ -\x88\x36\x02\xf6\x2d\x2f\x86\x3a\x4a\x63\xcb\x04\xd0\x81\xa3\x45\ -\x0d\x04\xf5\xce\xe5\x4f\x1e\xb9\x91\xa8\x9b\x64\xc6\xfa\xf2\x0c\ -\x56\x8d\x6d\x65\xd7\x06\x13\x01\xd6\x9e\xf3\x86\x80\x02\xdd\x70\ -\x3e\x3d\x6f\x90\x35\x69\xca\xb8\x4d\x40\x7b\x69\x8c\xc9\x63\x90\ -\x5b\x8c\x5b\x7b\x9e\x86\xe7\x9d\x4e\xcc\x2b\x4c\x72\x7f\xb5\x34\ -\xc6\x6c\x1c\x50\x34\xc2\x0b\xda\xdd\xbe\x1e\x4c\x72\x2f\x1b\xbd\ -\x56\x19\x08\x6d\x0d\x14\xbf\x13\xb0\x42\x5b\xcf\x68\xab\x54\xd0\ -\x06\x40\x78\x6f\xbd\xe9\x3a\x33\x86\xe6\xae\xf4\xfe\x65\xf7\xdc\ -\x81\x77\x40\x2c\x91\xda\x2b\x69\xda\x4d\x10\x8e\x03\x78\x71\xfd\ -\x77\x82\x08\xb7\xda\x7a\x46\x5b\xed\x9e\x3f\xd0\x02\xc4\x55\x55\ -\xd1\x98\x7e\x02\xd0\x6c\xb2\xbb\x59\xd2\xb4\x2f\xec\xf6\x11\x68\ -\x01\x9e\x3d\x0c\x7d\x0e\x2a\x7f\x74\x19\x78\xdf\x6e\x1f\x81\x15\ -\x20\x7a\x2a\xb5\x1f\x84\x41\xb7\xfb\x09\xa4\x00\x71\x55\x55\xa0\ -\xd3\xf7\x00\xb6\x55\x8b\x23\xa2\x09\xbb\x7d\x05\x52\x00\x0b\xd6\ -\x07\x80\x55\x89\xf9\x82\xdd\xbe\x02\x27\x80\x55\xeb\x13\x78\x30\ -\x93\xee\xcd\xd9\xed\x2f\x50\x02\x58\xb5\x3e\x80\x6c\x53\xe4\xf1\ -\x37\x4e\xf4\x19\x28\x01\xac\x5a\x9f\x74\xe9\xa4\x95\x0f\x9e\x56\ -\x08\x8c\x00\xf5\x58\x7f\xf6\xdb\x33\x77\x9d\xea\x37\x10\x02\xf8\ -\x61\x7d\x81\x23\xef\x02\xed\xdd\x23\xaf\x11\x61\x00\x62\x60\xc2\ -\xf8\x59\x57\xe4\xa1\xdb\x97\x4e\xdf\xb3\x72\xbc\x1f\xd6\x17\xd8\ -\x76\x40\x5b\xcf\x68\x2b\x11\x6e\x01\x38\x01\x31\x56\x27\x1c\x97\ -\x34\xed\x66\x2c\x91\xda\x5b\xeb\x78\xbf\xac\x2f\xb0\x2d\x80\x54\ -\xd0\x06\x50\x61\xac\xae\x81\x7e\x8c\xab\x6a\x45\x97\xf9\x69\x7d\ -\x81\xfd\x7b\xc0\x7f\xaf\xa8\x66\x44\x97\x17\x5f\xf9\xac\xd2\x4e\ -\x3f\xad\x2f\x70\xfd\x26\xc8\xa0\xc1\xe8\xa9\xd4\xfe\xd2\x76\xbf\ -\xad\x2f\x70\x42\x80\xeb\x35\xf6\x6f\x07\xd3\x77\xc6\x52\x08\x82\ -\xf5\x05\xb6\x05\x90\x81\xaf\x01\xac\xd6\x08\x2b\x2a\x85\x20\x58\ -\x5f\x60\x5b\x80\x4c\xba\x37\x07\x46\xb2\x56\x9c\x28\x85\xa0\x58\ -\x5f\xe0\xc8\x3d\xe0\xa5\xe6\xa5\x0b\x60\xcc\xd5\x08\xdb\x0e\x96\ -\x7e\x60\xa6\x71\x04\xc0\xfa\x02\x47\x04\x98\x49\x26\x0b\x90\xf8\ -\x24\x6a\x96\x02\xbf\x41\xc0\x81\x1a\xa7\xf3\xc4\xfa\x02\xc7\x9e\ -\x02\xd9\xcb\x67\xff\xb0\x52\x0a\xb5\xf0\xca\xfa\x02\x47\x1f\x83\ -\x16\x4b\xa1\x1a\x9e\x59\x5f\xe0\xa8\x00\xd6\x4b\xc1\x14\x4f\xad\ -\x2f\x70\x7c\x20\xb4\xd1\x52\xf0\xda\xfa\x02\x57\x46\x82\x1b\x28\ -\x05\xcf\xad\x2f\x70\x45\x80\x3a\x4b\xc1\x17\xeb\x0b\x5c\x7b\x17\ -\xb0\x5a\x0a\x7e\x59\x5f\xe0\xea\xcb\x90\x85\x52\xf0\xcd\xfa\x02\ -\x57\x05\x98\x49\x26\x0b\xba\x22\x7f\x08\xc0\x6c\x92\xc5\xbc\x2e\ -\xcb\x1f\xf9\x65\x7d\x81\xeb\xaf\xc3\xb7\x2f\x9d\xbe\x27\x6b\x38\ -\x48\xe0\x29\x00\xcf\x01\x3c\x27\xf0\x94\xac\xe1\xa0\xd5\x4f\x66\ -\x6e\xe2\xc9\xfc\x80\xcc\x58\xef\x02\x80\x77\xbd\xe8\xab\x5e\x02\ -\xf1\x55\xd8\x4f\xcc\x04\x58\x31\x6e\x74\x76\x5e\xab\x38\x9d\x36\ -\xe8\x98\xe4\xbe\x52\x1a\x63\x22\x00\x3d\x30\x6e\xdd\xdf\x91\xdf\ -\xed\x68\x56\x1e\x62\x92\xfb\x42\x69\x4c\x99\x00\x0c\xce\x1a\xb7\ -\x75\x85\x0f\x3b\x9c\x97\x67\x68\xb2\x7e\xc4\xb8\xcd\x28\x7f\x24\ -\x97\x09\x20\x01\x57\x8b\x1a\x18\x43\xb1\xae\xe1\xb0\xe3\xd9\xb9\ -\x4c\xac\x6b\x38\x4c\xa0\xa2\x81\x58\xd9\xb5\xc1\x44\x80\xa6\xc8\ -\xd2\x24\x98\xfe\x34\x34\xed\xd4\x14\x69\x7c\x33\x89\xf0\xef\x64\ -\x69\xc3\x8c\x71\x06\x72\x4d\x91\xa5\xc9\xd2\xd8\xba\xa6\xcb\x33\ -\x58\x95\x35\x69\x2a\xc8\xd3\xe5\x35\x59\x3f\xb2\xfe\xcf\x6f\x6c\ -\xba\xbc\x20\xda\x3d\xf2\x3f\x59\x30\x01\x10\xb8\x7f\x36\x7d\xf6\ -\xbc\xd9\xbe\x8a\xe3\x80\xec\x95\x4f\xcf\x13\xb8\xdf\xbd\xb4\x3c\ -\x81\x99\xe9\xdc\x6c\xba\xf7\xab\x4a\x01\x96\x16\x4d\x31\xf4\xe1\ -\xb5\x35\x38\x9b\x07\xab\x8b\xa6\x36\xb0\x6c\x0e\xed\x58\x9b\x75\ -\x1d\xc0\x65\x73\x58\x60\x60\xae\x9e\x65\x73\x0d\x1a\x34\xd8\xda\ -\xfc\x03\xf8\xad\xf2\xfb\x1a\x49\x36\xd6\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x39\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xbf\x4e\xc2\x50\x14\xc7\xf1\xef\xb9\x21\x30\x5a\x17\x7c\x86\ -\xbe\x40\x5f\x80\x8a\x4c\x26\xa8\x1b\x23\x98\xb0\xd6\x59\x1d\x64\ -\x87\x95\x44\x57\x46\x65\x34\x22\x4f\xd0\x17\xe8\x3b\xb0\x50\x47\ -\x08\xe1\x38\x94\x2a\x7f\x5d\x6c\xe3\xe0\xfd\x8d\x37\x37\xfd\x7d\ -\xd2\xbb\x9c\x03\xff\x3d\xb2\x7d\xe0\x5f\x5e\x9f\x09\xdc\x80\x7a\ -\x80\x93\x51\x4f\x0c\x12\x2a\x74\xc7\xcf\x8f\x6f\x07\x01\xfe\x55\ -\xb3\x23\x2a\xb7\xc0\x0c\x88\x50\x3e\x32\xa9\x17\x8e\x00\x17\x28\ -\xa1\x74\xde\x5f\x9e\xee\x77\x00\x95\x7a\xb3\x66\x8c\xbc\x0a\x8c\ -\x59\x16\x1a\xa3\x61\x7f\x92\x49\xf9\x2a\xd5\x7a\xbb\x8c\x59\x0c\ -\x14\x7c\x45\x6a\xe9\x9f\x30\xe9\x05\x63\x4c\x00\xcc\xf2\x28\x07\ -\x18\x0d\xfb\x13\x96\x85\x06\x30\x17\x34\xf8\xea\xfd\xbe\xa2\x1e\ -\x10\xe5\x51\xbe\x81\x40\x22\x14\x6f\x0f\x00\x27\xb3\x37\xff\x29\ -\xaa\x31\xc2\xf1\x3e\xc0\x9f\xc4\x02\x2c\xc0\x02\x2c\xc0\x02\x2c\ -\xc0\x02\x2c\x60\x1d\x10\xaf\xa6\xd7\x7c\x23\xe2\xa0\x4c\xf7\x00\ -\x24\x04\xdc\x6a\xbd\x5d\xce\xab\x3b\xf9\xb6\xba\x08\xe1\x0e\x40\ -\xa1\x0b\x94\x30\x8b\x41\x1e\x88\xca\x79\xeb\x04\xb3\x18\x00\x45\ -\x45\x7a\xe9\xf9\xc6\x62\x72\x7a\xd1\x7a\x40\xb8\x03\xe6\xc9\xf4\ -\xaa\x71\x26\xed\x22\x0e\xa8\x0b\x14\x0f\x2e\x26\x69\x92\xd5\x4c\ -\x03\x14\x6f\x7d\x7a\xfd\x55\x94\x29\x42\xa8\x48\x6f\x7b\x35\xb3\ -\xf9\x04\xc3\x25\x66\x2f\xe5\x8f\x2b\x3d\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\x4e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x00\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4f\x4f\x13\x51\x14\xc5\xcf\x41\x40\x09\x4b\xad\x94\x3f\xb6\ -\x0d\x0b\x37\x80\x2b\x96\xf2\x2d\x00\x23\x89\xb8\x93\x68\x22\xba\ -\x84\x4f\xa0\x6b\x35\x11\x97\x6a\x22\x89\xf0\x2d\x70\xc9\x8a\xc2\ -\xca\x05\x43\x0b\xa5\x50\x5d\x12\xb4\x20\xc7\x05\x2d\x0e\xd3\x81\ -\x56\xe2\xf4\xb6\xf2\x7e\xab\xd7\xfb\xde\x34\xe7\x9e\xbe\x37\xaf\ -\x8b\x7b\x01\x87\xc3\x71\x99\x61\x2d\x8b\xf2\xf9\x7c\xe7\x7e\xb1\ -\x38\x4e\x71\x14\xc4\x20\x84\x1e\x00\xad\x11\x6b\xfb\x5b\x0e\x41\ -\xe4\x20\xac\x8a\x5a\xec\x68\x6f\xff\x1c\x8f\xc7\xf7\xaa\x3d\x74\ -\xae\x01\x92\xe8\x65\xb6\x26\x09\xbd\x00\xd0\xfd\xcf\xa4\xd6\x87\ -\x6d\x82\x33\x89\x44\xef\x47\x92\x3a\x6b\xd1\x99\x06\x2c\x2f\x2f\ -\xb7\xc5\x62\x37\x5f\x0b\x9c\x8a\x46\x5f\x7d\x20\xf4\xae\x50\xd8\ -\x7d\x3a\x3c\x3c\x7c\x10\x36\x1f\xba\x8d\x8f\x7f\xf9\xcd\x37\x02\ -\x1e\x9d\x8a\x03\x69\x8a\x5f\x48\xe5\x25\x1d\x45\x21\xf8\xa2\x90\ -\x6c\x91\x18\x17\x75\x97\xc0\x50\x39\x2e\x70\x2a\x16\xbb\x09\x49\ -\x8f\xc3\x76\x42\xe8\x0e\xd8\xd8\xd8\x9c\x14\xf4\xde\x17\xfa\x0e\ -\x61\x3a\x99\xec\x9b\x3f\x6f\x3b\x35\x02\x92\xb8\xb1\xb1\x79\x1f\ -\xc4\x2b\x00\xd7\xcb\x71\x82\x0f\x93\xc9\xbe\x0f\xc1\xf5\x15\x06\ -\xe4\xf3\xf9\xce\x1f\x3f\x0f\xbe\xe2\xcf\x99\xff\x06\xfd\xba\x93\ -\x4a\xa5\xb6\x23\x53\x1d\x01\x9e\xe7\x75\x83\x57\x56\x00\xdc\x28\ -\x85\x72\xd7\xae\xb6\xdd\x0e\xbe\x18\x5b\x82\x0f\xee\x17\x8b\xe3\ -\xf0\xbf\xf0\x84\x67\xcd\x96\x3c\x00\xa4\x52\xa9\x6d\x08\xcf\x7d\ -\xa1\x9e\xfd\x62\x71\x2c\xb8\xae\xc2\x00\x8a\xa3\xe5\xb1\x80\x74\ -\x32\xd9\x37\x1f\x91\xc6\xc8\x49\x26\xfb\x3e\x09\x48\x97\x3f\x53\ -\xac\x6e\x00\x88\x41\xdf\x03\x4b\x8d\x7e\xe6\xcf\x83\xa4\x28\x2e\ -\xf9\x42\x03\xc1\x35\x95\x06\x1c\xff\xc9\x29\x7d\x81\x76\xa2\x91\ -\x56\x3f\x02\x39\xf4\x06\xe7\x2b\x0d\xf0\x5d\x8d\x8d\x76\xd5\x5d\ -\x84\x40\x0e\x15\xd7\x7e\x98\x01\x97\x0a\x67\x80\xb5\x00\x6b\x9c\ -\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\ -\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\ -\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\ -\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\ -\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\ -\xb5\x00\x6b\xc2\x0c\x38\x2c\x0f\x48\x36\xbd\x41\x81\x1c\x0e\x83\ -\xf3\x61\x65\x72\xb9\xf2\x50\x62\x57\x34\xb2\xea\x47\x20\x87\xad\ -\xe0\x7c\x58\x99\xdc\xea\xc9\x90\x1a\x91\x54\x53\x4f\x41\x23\x22\ -\x89\xa2\x46\x7c\xa1\xb5\xe0\x9a\x0a\x03\x44\x2d\x96\xc7\x04\x86\ -\xbc\x6c\x76\x3c\x22\x7d\x91\xe3\x65\xb3\xf7\x4e\x55\x8e\x53\x0b\ -\xc1\x35\xd5\x8b\xa5\x85\xc2\xd1\xd1\xc1\x50\x7f\x7f\x7f\x53\x15\ -\x4d\xae\xaf\xaf\xc7\xc9\xd6\x15\x10\xb1\x52\xa8\xb6\x62\xe9\x78\ -\x3c\xbe\x47\x70\xe6\x24\x40\xc4\x5a\x5a\xda\xd2\x9e\x97\x9d\x68\ -\x86\xe3\x20\x89\x9e\x97\x9d\x08\x24\x0f\x82\xb3\x61\x2d\x34\xa1\ -\x09\x49\x62\x26\x93\x7d\x1b\xec\x16\x29\x35\x4c\x2c\x91\xda\x69\ -\xb4\x2a\xd2\x52\xc3\x44\x97\xa8\x11\xff\xb6\x07\x00\x42\x73\x89\ -\xc4\xad\x27\x35\x37\x4c\x00\xff\x55\xcb\xcc\x5c\xa1\xb0\x3b\x7d\ -\x56\xcb\x4c\xd5\xa6\xa9\x4c\x66\xeb\x81\xa0\x97\x68\xbe\xa6\xa9\ -\x1c\xc1\xd9\x0b\x37\x4d\xf9\x29\xb5\xcd\x8d\x95\xea\xed\x07\x70\ -\x5c\x75\xdd\x78\x6d\x73\xc7\xf7\xfc\x9a\xa8\x85\x8e\xf6\xf6\x85\ -\x5a\xda\xe6\x1c\x0e\xc7\xe5\xe6\x37\x49\x9a\x11\x82\x28\x6e\xc8\ -\x6e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x78\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ -\xce\x41\x11\x00\x20\x0c\x04\xb1\x16\xff\x22\xe9\x20\x04\x64\x1c\ -\x8f\xc4\xc0\x6e\x15\x00\x10\xd6\x7b\xce\x4d\x0e\xac\x64\x1c\x00\ -\xf8\xc2\x03\x48\xae\x03\xa7\xd4\xed\xa0\x47\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x06\x65\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x06\x17\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xc9\x73\x5c\xd5\x15\x87\xbf\x73\x5b\x31\x32\x83\x4c\x6c\x50\ -\x00\xf5\x1b\x5a\x15\x6f\xb0\x31\x93\xc1\x98\xa4\x12\x2c\x1c\x24\ -\x83\x6d\xe5\x6f\x61\x05\x8b\x64\x91\xf2\x82\x0d\xcb\xe4\xef\xa0\ -\x98\xca\xd6\x18\x46\x43\x85\xa4\x42\x80\x2a\xaa\x28\xd4\x6f\x90\ -\x29\x07\xc7\x0e\x96\x71\x2c\x19\xeb\x1e\x16\x52\x3b\xe2\x75\xab\ -\xfb\xbe\xee\xf7\x24\x51\xe8\x5b\xde\x77\xfa\xbe\xf3\xfb\xfa\xdc\ -\x1e\xa4\x86\x6d\xb6\xd9\xe6\xa7\x8c\xb4\x5a\x3c\x7f\xfe\xfc\x6d\ -\x8b\x8b\xd7\x9f\x57\x91\x13\x40\x3f\x70\x56\x74\xf9\xa5\x30\x0c\ -\xeb\x1b\xdb\x5e\x77\x44\x51\x54\x53\xa9\xbc\x00\x1c\x06\x16\x0d\ -\xbc\xb1\x73\xe7\x2d\x2f\x0f\x0e\x0e\x7e\x9b\xad\x6d\x12\xf0\xf9\ -\xe7\x17\xee\xe8\xdf\xb9\xf8\x16\xf0\x70\xe6\xd2\x65\x35\x8c\xd6\ -\x3c\xef\xc3\x72\xda\x2e\x86\x24\x49\x1e\xb3\x2a\x93\xc0\xae\x1f\ -\x5c\x10\x3e\xfe\x6e\x69\xf1\x37\x7b\xf7\xee\x5d\x58\xbb\x6c\xb2\ -\x1b\xf4\xf7\x5f\x7b\x81\xe6\xf0\x00\xbb\xc4\x32\x51\x4f\xd3\x43\ -\x45\x36\x5c\x24\xeb\x86\x07\x50\x1e\xdc\xb1\xa3\xff\xc5\xec\x72\ -\x93\x00\x44\x4e\xb6\xb9\xc7\xc0\x56\x95\xd0\x36\xfc\x2a\x8a\x8e\ -\x67\xd7\x9a\x05\xc0\xce\x0e\xf7\x1a\x10\xcb\xc4\x5c\x9a\x3e\x9e\ -\xb3\xc7\xd2\x48\x92\xe4\x60\xa7\xf0\x2b\x48\x7f\x76\xa5\x49\x80\ -\xa2\xef\x39\xdc\x73\xc0\x58\x26\xb7\x82\x84\xd5\xf0\x53\x74\x0c\ -\x0f\x40\x53\xb6\x26\x01\x7d\x46\x4e\x01\x97\x1d\x36\xdb\x74\x09\ -\x39\xc3\x2f\x54\x0c\x7f\xca\x2e\x36\x09\xf0\x3c\xef\x0b\x6b\x78\ -\x06\x77\x09\x9b\x72\x1c\xdc\xc7\x1e\x80\x05\xb5\x32\xea\x79\xde\ -\x17\xd9\x0b\x2d\x3f\x07\x00\xcc\xa5\xe9\xe3\xc6\x32\x09\x0c\x38\ -\xdc\xe0\xb2\x11\xfd\x9d\xef\xfb\x7f\x73\xa8\xed\x99\x38\x8e\x1f\ -\x55\xcc\x14\x70\xa7\x43\xf9\x15\xb5\xf2\x4c\xad\x56\xfd\xa0\xd5\ -\xc5\x75\x05\xc0\xd6\x94\x50\x64\x78\xe8\x20\x00\xb6\x96\x84\xa2\ -\xc3\x83\x83\x00\x80\x7a\x9a\x1e\x12\xcb\x04\xee\x12\x8e\xfa\xbe\ -\xff\x91\xcb\xde\xae\x44\xd1\x57\x8f\x20\xcb\x53\xc0\xcf\x1d\xca\ -\xaf\xa0\x32\x1a\x86\xd5\xb3\x9d\x0a\x9d\x04\xc0\xe6\x4a\x28\x2b\ -\x3c\xb4\xfe\x20\xd4\x92\x9a\xe7\x7d\xa8\x56\x46\x81\x85\x8e\xc5\ -\xb0\xcb\xaa\x4c\x25\x49\x72\xd0\x75\xff\xf5\xc8\x1f\xde\x8c\xb9\ -\x86\x87\x1c\x13\xd0\xa0\x5e\x9f\x7f\x42\x8c\x4e\x00\x77\x38\x94\ -\x7f\xb3\xfa\x9a\xd0\xd5\x24\xe4\x0c\xff\x2d\x6a\x46\xc3\x70\xe8\ -\xfd\x3c\xf7\xc8\x2d\x00\xf2\x4b\x10\xec\xd1\x20\x08\xfe\x9e\xe7\ -\x1e\x1b\x11\x1e\xba\x14\x00\xe5\x4a\x88\xa2\x73\x0f\x23\x76\x9a\ -\x92\xc3\x43\x0f\x02\x00\xa2\x68\xfe\x30\xa2\x67\x28\x50\x42\xde\ -\xf0\x82\x19\x0b\x82\x21\x97\xef\x2f\x2d\xe9\x49\x00\x14\x2b\x61\ -\xa3\xc3\x43\x8e\x77\x81\xf5\x08\xc3\xea\x59\xd4\x8c\x01\x57\x1c\ -\xca\xef\x54\xcc\x64\x14\x7d\xf5\x48\xf6\xc2\x6a\x78\xe7\x33\x2f\ -\xd8\x63\xbd\x86\x87\x02\x26\xa0\x41\x14\x9d\x7b\x12\xb1\x67\x80\ -\xdb\x1d\xca\xff\x8b\x56\x8e\x86\xe1\x7d\xff\x00\xa8\xd7\xe7\x1f\ -\x12\xa3\xd3\xc0\x6e\x87\xc7\x5e\x15\xec\x58\x10\x04\xef\xf6\xd2\ -\x6f\x83\xc2\x04\x40\x77\x12\x54\xad\xdd\xac\xf0\x50\xb0\x00\xc8\ -\x29\x41\x59\x50\x14\x11\x71\xf9\x74\x59\x78\x78\x28\x41\x00\x40\ -\x1c\x9f\xfb\x95\x62\x4f\xe3\x36\x09\x2e\x5c\x35\xa2\xc7\x7c\xdf\ -\x7f\xa7\xa0\xfd\x6e\x52\x8a\x00\x28\x54\x42\x69\xe1\xa1\x80\x77\ -\x81\xf5\x08\x82\xa1\xf7\x04\x7b\x0c\x68\xfa\x67\x44\x0e\xae\x5a\ -\xd1\x67\xcb\x0a\x0f\x25\x4e\x40\x83\x38\x8e\x7f\xad\x98\xd3\xc0\ -\x6d\x39\x1f\x7a\xd5\x8a\x3e\x3b\xec\xfb\x6f\x97\xd1\x57\x83\xd2\ -\x05\xc0\xaa\x04\x35\x13\x48\xc7\x3f\xb9\x37\x58\xb4\xa2\xa3\x65\ -\x87\x87\x12\x8f\xc0\x5a\x96\x8d\x59\x40\xb8\xee\x5a\xaf\x70\x5d\ -\x96\x8d\xcb\xd7\xee\x9e\x29\x5d\xc0\x5c\x9a\x1e\x30\x96\x19\xdc\ -\xfe\x7a\x0b\x80\xc0\x80\x18\x9d\xae\xd7\xe7\x1f\x2a\xb1\xb5\xc6\ -\xbd\xca\x63\x4d\xf8\x3d\x5d\x6e\x71\x49\xad\x3c\x5d\xab\x55\xff\ -\x59\x64\x5f\x6b\x29\x6d\x02\x56\xc3\x4f\xd3\x7d\x78\x80\xdd\x62\ -\x74\x7a\x6e\x6e\xfe\xc1\xa2\xfa\xca\x52\xca\x04\xa4\x69\xfa\xc0\ -\xf2\xca\x33\x7f\x57\x41\x5b\x5e\xb2\xcb\x32\x32\x3c\x5c\xfd\xb8\ -\xa0\xfd\x6e\x52\xf8\x04\xe4\x0c\xbf\xa4\xaa\x4b\x0e\x75\xbb\x4d\ -\xa5\x9c\x49\x28\x54\x40\xce\xf0\xd7\xd4\x32\xa6\x2b\xff\x86\xfb\ -\x9f\x43\xfd\x9e\x32\x24\x14\x76\x04\x92\x24\xd9\x6f\x55\x66\x71\ -\x0c\x8f\xca\x73\x61\x58\x9d\x05\xa8\xa7\xe9\x6f\xc5\xf2\x26\x70\ -\xab\xc3\x63\x2f\x5a\xc3\xc8\xb0\xe7\xfd\xab\x97\x7e\x1b\x14\x22\ -\xa0\x97\xf0\x0d\x36\x4b\x42\xcf\x47\xa0\x8b\xf0\xc7\xb3\xe1\x01\ -\x6a\x9e\xf7\x96\x5a\x9e\xc3\xf5\x38\x58\x66\xe6\xd2\xf4\x40\xde\ -\x7e\xb3\xf4\x24\x20\x49\x92\xfd\xd6\x8a\xf3\x99\x5f\x0d\x3f\xb3\ -\x5e\x41\xad\xe6\xfd\x35\xa7\x84\xe9\x5e\x25\x74\x7d\x04\x6e\x86\ -\x17\xee\x76\x28\xbf\x26\xc8\x89\x20\xa8\x4e\xbb\xec\x5d\xaf\xa7\ -\x4f\x89\xe1\x4d\x3a\xff\x5c\x07\xe0\x3f\x15\xc3\x88\xe7\x79\x9f\ -\xb8\xec\x9d\xa5\x2b\x01\x71\x1c\xef\x53\x35\xb3\x8e\xe1\x17\x05\ -\x39\xee\x1a\xbe\xc1\x46\x49\xc8\x2d\x60\x23\xc2\x37\x88\xa2\xf9\ -\x23\x88\xbe\x41\x89\x12\x72\x09\x88\xe3\x78\x9f\x62\x66\x80\x41\ -\x87\xf2\x9e\xc2\x37\xc8\x2b\xc1\x88\x1e\xf1\x7d\xff\x53\xd7\xfd\ -\x9d\x5f\x04\xf3\x87\x37\xce\x67\xbe\x1d\x61\x58\x9d\x45\xe5\x38\ -\x70\xcd\xa1\xfc\x2e\xab\x32\x9b\x24\xc9\x7e\xd7\xfd\x9d\x26\x20\ -\x8e\xe3\xfb\x15\x33\x4b\xae\xf0\x43\x53\xae\x4d\xb8\x10\x45\xf3\ -\x23\x88\xbe\x4e\xc1\x93\xd0\x71\x02\xf2\x87\xb7\x27\x8b\x0e\x0f\ -\x10\x86\xd5\x19\x41\x4e\xe0\x3a\x09\x56\x66\x5c\x26\xa1\xed\x04\ -\x74\x17\x3e\x98\x74\xa8\xed\x9a\x38\x9e\x7f\x5a\xd1\xd7\x59\xf9\ -\x15\x7b\x7b\x94\x0b\xc6\xe8\x48\xbb\x49\x58\x77\x02\x56\xc2\x57\ -\x9c\xcf\xbc\x15\x1d\x2f\x3b\x3c\x40\x10\x54\xa7\x05\x39\x0e\x2c\ -\x76\x2c\x16\xee\xb6\x56\x66\xe2\x38\xde\xb7\x7e\x49\x0b\xfe\x1f\ -\x5e\x7f\xe1\xd0\xd3\x92\x15\x3d\x39\xec\xfb\x13\x0e\xb5\x85\x91\ -\x77\x12\x44\xec\x91\x20\x08\x3e\xcb\x5e\x6a\x12\x90\xa6\xe9\xd0\ -\xb2\xe5\x23\xe0\x1e\x87\x3e\x36\x25\x7c\x83\x38\x3e\x77\x54\xb1\ -\xaf\xe1\x22\x01\xbe\xbe\xd1\x67\x0e\xfe\x72\x68\x28\x5d\xbb\xd8\ -\x74\x04\xac\xd5\x3f\xf0\x23\x08\x0f\x10\x04\x43\x53\x82\x39\x81\ -\xcb\x71\x80\xc1\xbe\x1b\xf6\x8f\xd9\xc5\x16\xbf\x16\x97\xa7\x1c\ -\x36\x5b\x52\xd1\xf1\xcd\x0c\xdf\x60\x45\x82\x3d\x89\x9b\x84\x23\ -\xd9\x85\x56\x2f\x82\xcb\x1d\x36\x59\x52\xd1\xf1\x9a\xef\x9f\x71\ -\x69\x70\x23\x08\x82\x60\xd2\x49\x82\x36\x67\x6b\x12\x20\x68\xbb\ -\x67\x75\x49\x0d\xbf\xdf\x4a\xe1\x1b\x04\x41\x30\x69\x45\xc7\x69\ -\x23\x41\x85\xd3\xd9\xb5\x26\x01\x95\x8a\x39\x05\x7c\xd9\xe2\xf1\ -\x2b\xe1\x3d\xaf\x69\x93\xad\xc2\xb0\xef\x4f\xb4\x91\x50\xbf\xb1\ -\xa3\xef\x54\x76\xb1\x49\x40\xb5\x5a\xbd\xf8\xb3\x3e\xf3\x04\xc2\ -\x9f\x81\x18\xf8\x5a\x91\x57\xd1\xca\x93\x5b\x39\x7c\x83\x61\xdf\ -\x9f\x50\x2b\x87\x51\x5e\x01\xf9\x37\x10\xa3\xf2\x97\xef\x76\xf4\ -\x1d\xda\x7b\xef\xbd\x17\x36\xbb\xbf\x6d\xb6\xd9\x66\x6b\xf1\x3d\ -\x64\x29\x23\xc7\x02\xc7\xba\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x01\x06\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb8\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\xc1\x0d\x83\x50\x10\xc4\xd0\x0d\xa2\x24\x7a\xe2\x46\x31\xdc\ -\xe8\x29\x3d\x91\x32\x5e\xa4\x6f\x37\xb0\x96\x35\xb7\x9d\x81\x1c\ -\xe7\xfd\x1e\xe7\xfd\x4a\x87\x4d\x1e\xff\x07\x0a\xa0\x05\x34\x05\ -\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ -\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ -\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ -\xa0\x59\x3e\xc0\x47\x1e\xd7\xaf\xf1\x99\x16\x30\xbb\x16\x98\x99\ -\xf9\x3e\x17\x5b\xe2\xf2\x0b\x28\x80\x16\xd0\x14\x40\x0b\x68\x0a\ -\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ -\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ -\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\x66\xf9\x00\ -\x3f\xfa\xaa\x08\xd8\xe7\x6a\x2c\xe4\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x04\x72\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x24\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x88\x1c\x55\x14\x85\xbf\x5b\xdd\x09\x8a\x8a\x20\x2a\x62\ -\x4f\x57\x75\x0d\x19\x14\x77\xc2\xe0\x52\x50\x34\x1a\xc4\xe0\x0f\ -\xe8\x4a\x44\x51\xd0\x85\x18\x41\x11\x74\x11\x21\x8a\x11\x04\x17\ -\x22\x1a\x70\xe3\xc2\xa0\xae\xc2\x80\x46\x47\x5d\x08\x82\xe0\x42\ -\x10\x44\x82\x66\xa6\xe7\x75\xcd\x24\xd1\x88\x8a\x60\x18\xec\xee\ -\x77\x5d\xcc\x88\x55\x35\x43\x98\x21\xef\xbd\x7a\x9a\x3e\xcb\x73\ -\xa0\xee\x7d\xa7\xee\x7d\x3f\xf5\x03\x13\x4c\x30\xc1\x04\xff\x01\ -\x18\xb3\xb2\xdf\x0c\x8a\xe1\x92\x29\x46\xc6\x14\x2f\xb8\xba\xae\ -\xb8\xba\x90\x4f\x2c\x2d\x2d\xdf\x84\xe8\xe7\xfc\x9b\xaf\xed\x65\ -\xdd\x96\x8b\x6b\x27\x2e\x2e\xe2\x13\x83\xc1\x60\x16\xd1\x39\x4a\ -\x37\x4b\x55\x9d\xe5\x1d\xb5\x01\xfd\xfe\xca\xb5\x56\xe5\x28\x70\ -\x71\x99\x17\x11\xeb\x2a\x46\xb4\x06\x2c\x2c\xac\xa4\x49\x62\xe7\ -\x81\xcb\x37\x91\xd5\x55\x9c\x28\x0d\xf8\xf1\xe4\xc9\x2b\x5a\x6d\ -\x3b\xaf\xd0\xf5\x1d\x2b\x3a\x03\x8e\x1d\x3b\x7d\xc9\x8e\xbf\x46\ -\x1f\x01\xd7\x84\x88\xd7\x0e\x11\x64\xab\xe8\xf7\xfb\x17\x48\xb2\ -\x7a\x04\x98\xad\x49\x8a\xa7\x15\x2b\x9a\x0a\x50\xd5\xb6\xb4\xda\ -\x87\x81\x9b\xeb\x12\xe0\x6c\xd2\xab\x23\x0a\x03\x54\x55\x4c\xb1\ -\x7c\x08\xe5\xee\xaa\x22\x5e\x07\x0f\x91\x18\x60\x06\xcb\xaf\xa0\ -\x3c\x5c\xe6\x44\x50\x50\xaf\x83\x87\x08\xe6\x00\x63\x8a\x67\x15\ -\x9e\x29\x73\xba\xb6\xc8\x79\x1f\x3c\x34\x5c\x01\xc6\x14\x8f\x2a\ -\x1c\xac\xf3\x22\x8c\x43\xe5\xd0\x98\x01\x4b\x4b\xc5\xbd\x0a\x6f\ -\x6d\x54\xfc\x97\x7d\x19\x8d\x18\x60\xcc\xca\x2d\x08\x87\x37\xc4\ -\x57\xec\xfa\xc4\x17\x0c\xc1\x0d\x58\x2c\x8a\x1b\x14\x7b\x04\xd8\ -\x59\xe6\x15\x2c\xe2\x6e\x8b\xbb\x55\x04\x9d\x04\x8d\x31\xd7\xa9\ -\xe5\x28\x70\x51\x4d\xb2\xe2\x70\x7f\xbf\x1d\x04\xab\x80\xc5\xc5\ -\x13\x99\x92\xcc\x03\x97\x55\x04\xc1\xd2\xd0\xe0\x21\x90\x01\xc7\ -\x8f\x9f\xba\x52\x5a\xe3\x4f\x81\x4e\x99\x17\xb0\x68\x73\x83\x87\ -\x00\x2d\xb0\xb0\xb0\x70\x69\xab\x3d\xfc\x18\x98\xa9\x2a\xaa\x1a\ -\x78\xc2\xdb\x0c\x5e\x0d\x28\x8a\xe2\x42\x6b\x99\x53\xb8\xbe\x26\ -\x29\xb8\x7b\xa8\x71\x2e\xf0\xd6\x02\xaa\xda\x1e\x59\x79\x4f\xe1\ -\xc6\xba\x44\xa0\x5d\xde\x56\xe0\xc5\x00\x55\x4d\x06\x83\xe2\x6d\ -\x41\xf7\x96\x79\x89\x6c\xf0\xe0\xc1\x00\x55\x15\x63\x8a\x57\x15\ -\x79\xb0\xcc\x8b\xa0\x1a\xd9\xe0\xc1\xc3\x1c\x60\x8a\xe2\x39\x44\ -\x9e\x2a\x73\x21\x0f\x37\xdb\x85\xd3\x0a\xe8\x0f\x96\x1f\x43\xe5\ -\xc5\x3a\x1f\xf2\x70\xb3\x5d\x38\x33\xa0\x6f\x8a\x83\xa2\xfa\xe6\ -\x46\x25\xec\xe1\x66\xbb\x70\x66\x80\xd4\x1e\x68\xc0\xfa\xfe\x3e\ -\x82\xb5\xfe\x6c\x70\xd7\x02\x9b\x94\x79\x03\x67\x9b\x6d\xc3\x5d\ -\x05\x20\x4f\x52\xdb\xd3\x2b\x12\xc5\x23\xb7\xb3\xc1\x59\x82\x59\ -\x36\xf5\x01\xaa\x4f\x94\x39\x01\x14\x5a\x31\xbf\x83\x75\x7a\x87\ -\x7a\xbd\xf4\x0d\x81\xfd\x65\x4e\x00\xd4\x46\x6b\x82\xf3\x12\x4d\ -\xd3\xa9\x03\xc0\xeb\x15\x52\x04\xc4\xdd\x1b\x5d\x97\x70\x9e\x94\ -\x88\x68\x96\x4e\xed\x03\xde\xad\x08\x8a\x20\x71\x3c\x86\x2f\xc3\ -\x4b\x42\x22\x62\x7f\x39\xfd\xd3\x43\xc0\x87\x15\x41\x11\x90\x44\ -\x22\xea\x06\x6f\x77\x64\x76\x76\x76\xb8\xa3\x9d\xdc\x07\xf2\x65\ -\x55\x51\x71\xf9\x81\xc3\xb9\xc2\x6b\x22\x9d\x4e\xe7\x8c\xda\xe1\ -\x9d\x08\xdf\x56\x15\x11\x34\x8e\x76\xf0\x9e\x44\x9e\xe7\xbf\xeb\ -\x78\x74\x3b\xb0\x50\x11\x04\x41\x9a\x6f\x86\x20\x77\x21\xcf\xf3\ -\x53\xe8\xf8\x56\xe0\x44\x45\x50\x4d\xd6\x96\x88\xe6\x10\xac\x0c\ -\x7b\xbd\x5e\x3f\x11\xbd\x0d\xf8\xad\xaa\x68\x42\x83\x9b\x84\xa0\ -\x7d\x98\xa6\xe9\x77\xa8\xdc\x01\x9c\xa9\xe7\xa1\x0d\x99\x10\x7c\ -\x22\xea\xf5\xa6\xbe\x52\xd1\x7b\x80\x61\x99\x17\x48\x54\xc3\x9b\ -\xd0\xc8\x4c\x9c\xa7\xe9\x27\x2a\xfa\x00\xb5\xc3\x93\x08\x09\x68\ -\x50\x13\x1a\x5b\x8a\xf2\x34\x7d\x5f\x91\xc7\x37\x2a\x61\x4f\x90\ -\x8d\xae\xc5\x79\x36\x75\x08\x91\xe7\xeb\xbc\x2a\x4e\x3e\x83\xdd\ -\x0a\x1a\xdf\x8c\x64\xdd\xce\xcb\xa8\xbe\x56\xe6\x44\xfe\x69\x07\ -\xff\x68\xdc\x00\x11\xd1\x2c\xeb\x3e\x2d\xe8\x3b\x65\x5e\xd7\xcf\ -\x0d\xbe\xe3\x37\x6e\x00\xac\x1d\x9e\xd2\xb4\xfb\x88\x22\x73\x55\ -\x45\x05\xcf\x39\x46\x61\x00\x80\x88\x8c\xb0\xc3\xfb\x51\xbe\xa8\ -\x4b\x78\xcc\x33\x1a\x03\x00\xf2\x3c\x5f\x1d\x0e\x57\xf7\x82\x7e\ -\x53\x93\xbc\x2d\x8d\x51\x19\x00\x30\x33\x33\xf3\xc7\x68\xb8\x73\ -\x0f\xca\x0f\x21\xe2\x45\x67\x00\xc0\xae\x5d\x57\xfd\x6c\x6d\x6b\ -\x37\xb0\xe2\x3b\x56\x94\x06\x00\x4c\x4f\x5f\x6d\x04\xbb\x1b\xf8\ -\x75\x13\xd9\x59\x4b\x44\x6b\x00\x40\x96\x65\xdf\xdb\x84\x3d\xc0\ -\x9f\x65\xfe\xbc\xf9\x65\x06\x60\xba\xdb\xfd\x5a\x48\xee\x2a\xbf\ -\x62\x3b\x2f\x7e\x99\x29\x23\xcb\x3a\x9f\x09\x72\x00\x18\x83\x8c\ -\x13\x91\x97\x9a\xce\x69\x82\x09\x26\xf8\x7f\xe0\x6f\x3e\x50\x4e\ -\x18\x86\xf9\x70\xa3\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\x61\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x13\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\xbf\x6b\x14\x41\x14\xc7\xbf\x6f\x93\x70\x9e\x04\x1b\x31\x46\ -\x72\x9b\xdd\x8d\xb9\x42\x08\xd8\xda\xfb\x03\xb4\xb0\x93\x80\x5d\ -\x0e\x44\x25\x9d\x4d\xc8\x5f\x60\x2c\x85\x04\xd1\x22\xa5\x4d\x6c\ -\x44\x48\x04\xb5\xb3\xb0\x15\x52\x08\xd1\xec\xde\xde\x82\x78\x62\ -\xa1\xa8\xe7\x91\xdc\x8c\x4d\x08\x78\xbb\x77\x97\xdd\xb9\x97\xc9\ -\xb9\xf3\x29\xe7\xe6\xbe\xef\xbb\xdf\xdb\x9d\x7d\xcc\x0d\x60\x30\ -\x18\xf2\x0c\xa9\x0a\xd4\xeb\xf5\xd1\x46\xa3\x39\x2f\x81\x1b\x00\ -\x66\x00\x14\xd4\x6d\x29\xd1\x04\xb0\x49\xc0\x5a\xb1\x58\x58\x19\ -\x1b\x1b\xfb\xd9\x6d\xb2\x52\x00\xd5\x6a\xf5\xb2\x84\xb5\x0a\xa0\ -\xa4\xa2\xc3\x48\x44\x10\x15\xc7\x71\x5e\x75\x9a\x60\x65\x55\x0e\ -\x82\xb0\x22\x61\xbd\xc4\xd1\xbd\x78\x00\x28\x49\x58\x1b\x7e\x18\ -\xce\x75\x9a\x90\xe9\x0e\xd8\x0e\xc3\x2b\x96\xa4\x0d\x28\x04\x78\ -\xc8\xb4\x08\xe2\x6a\xd2\x9d\x90\x3a\x80\x7a\xbd\x3e\xfa\xbb\xd1\ -\xfc\x00\x60\xa2\x2f\xd6\x0e\x8f\xe8\x78\xb1\x70\xae\x7d\x4d\x48\ -\xfd\x0b\x36\x1a\xcd\x79\x0c\xde\xc5\x03\x40\x69\xcf\xfb\x3f\xa4\ -\x0e\x60\x6f\xb5\x1f\x48\x92\xbc\x67\x79\x86\x67\xfa\xe0\x45\x17\ -\x31\xef\xc3\x19\x44\xba\xbe\xe7\x5d\xc7\x56\xee\x2d\x54\x08\xaa\ -\x35\xd9\xe5\xe3\x98\xf7\x41\x59\xc5\xd9\x30\x01\xe8\x36\xa0\x1b\ -\x13\x80\x6e\x03\xba\x31\x01\xe8\x36\xa0\x9b\xdc\x07\xd0\xb3\x11\ -\x0a\x82\xe0\x0c\xac\xe1\xbb\x90\xf2\x22\x80\xd3\x3d\xe7\x57\x6b\ -\x1f\x15\xfc\x48\x10\x22\x08\xac\xef\xec\xfc\x79\x5c\x2e\x97\x7f\ -\x28\x68\x1d\x88\xae\x5d\x5b\x18\x86\xd7\x85\xa4\x55\x00\x27\xb9\ -\x8d\x24\xe0\x4b\x41\x37\x3d\xaf\xf4\x2e\xcd\x97\x7a\x74\x82\xb1\ -\x4e\xb5\xe3\x23\xe0\x57\x6b\x4b\x42\xd2\x73\xe8\xb9\x78\x00\xf0\ -\xc8\x92\x6f\xfd\x30\xba\xc3\x59\x24\x31\x00\x3f\x0c\x67\x09\x58\ -\xe0\x2c\x7c\x40\x86\x48\xca\x65\xdf\x8f\x2e\x70\x15\x88\x05\xe0\ -\xfb\xbe\x4b\x92\x9e\x70\x15\xcc\xc0\x10\x59\xf2\xe9\xd6\xd6\xd6\ -\x09\x0e\xf1\xf8\x1d\x60\x0d\x2f\x02\x60\x29\xa6\x80\x37\x32\x72\ -\xec\x36\x87\x70\x2c\x00\x02\xae\x71\x14\x52\xc6\xe2\xf1\x95\xb4\ -\x06\x1c\xcd\x5d\x5e\xc9\xe3\x2b\xf5\x86\xc8\x90\x85\x32\x87\x91\ -\x5d\x60\x9a\x04\x36\xba\x4c\x61\xd9\x68\x49\x1d\x80\x6d\xdb\x2a\ -\x8d\x4e\x47\x6a\xb5\x1a\x5a\x1c\xc2\x3d\xc8\x7d\x2b\x6c\x02\xd0\ -\x6d\x40\x37\x26\x00\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\ -\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\xdd\x06\x74\x93\xe5\ -\x7c\x80\x2e\xce\xf6\xda\xf1\x3d\x00\xcd\xf6\x81\xbc\xdd\x01\x9b\ -\xed\x03\xb9\x0a\x80\x80\xb5\xf6\xb1\x3c\x05\x10\x15\x8b\x85\x95\ -\xf6\xc1\xbc\x04\xd0\x22\x88\x4a\xd2\xb9\xe1\x3c\x04\xd0\x92\x24\ -\x6f\x75\x3a\x2f\x3c\x48\x6f\x81\x2c\x44\x04\x51\x71\x27\x3b\x1f\ -\x96\xfe\x1f\x03\xd8\x3f\x2e\x5f\x28\x8c\x2c\x8f\x8f\x8f\xff\xea\ -\x36\x39\xb6\xd5\xdc\x87\x77\x2d\x17\x9f\x5c\xc7\x9e\xee\xb7\x68\ -\x7c\x0d\x90\xf8\xda\xef\x22\x7d\xe2\x0b\x87\x68\xd2\x22\xf8\x9a\ -\xa3\x90\x32\x44\x6f\x38\x64\x63\x01\x08\x41\x0f\x00\xec\x70\x14\ -\x53\xe0\x1b\xc4\xee\x23\x0e\xe1\x58\x00\x53\x53\xa5\xf7\x92\xe8\ -\x28\x9c\x0d\xd8\x87\x60\xcd\xb9\xae\xfb\x99\x43\x3b\xb1\x0f\x70\ -\xed\x89\x87\x00\x9e\x71\x14\x4c\x0b\x01\x4b\x8e\x33\xf1\x82\x4b\ -\x3f\x31\x00\x22\x12\xce\x64\x69\x56\x12\xdd\x83\xbe\xc7\xe1\x3b\ -\x81\x66\x1d\xc7\x5e\xe4\x2c\xd2\xf3\x1f\xd7\xed\xed\xe8\xbc\x65\ -\xc9\x05\x00\x97\x40\x38\xc5\x69\x66\x8f\x48\x02\xeb\x10\xbb\xf7\ -\x3d\xcf\x0b\x0e\xa1\x9e\xc1\x60\xc8\x31\x7f\x01\x50\x46\xc4\x66\ -\xcc\x07\x14\xea\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x09\xc0\x30\x0c\x04\x41\xc9\x49\xdf\x71\x4d\x6e\x48\x08\ -\xd5\x11\xec\x22\xce\xa0\xcf\xce\xff\x8e\x35\x13\x44\xd6\x8c\xac\ -\xa9\x7c\x0c\x65\x7c\x03\x01\x04\x10\x40\x00\x01\x04\xb4\x07\xbc\ -\xea\x81\x9b\x7d\x91\xd5\x13\xe0\xfb\x59\xdb\x7f\xe5\x02\x00\x00\ -\xf4\x3b\x2b\x9a\x0d\x40\x4d\xe0\x05\x89\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x85\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ -\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xc9\xd9\x14\x21\x16\xe9\x10\ -\xf0\xf4\xfd\x13\x39\x62\x51\xf5\x64\xf5\xe4\xe6\xe3\x6d\xc6\x17\ -\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7c\ -\x9f\x23\x06\x85\x22\x0f\x12\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x05\x38\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xea\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x5b\x6c\x54\x55\x14\x86\xbf\xb5\x67\x3a\x20\x24\xe5\x22\x46\ -\x04\x2a\xd0\x80\x29\x04\x4c\x04\x25\x01\x82\xa2\xd0\xd6\x8a\x40\ -\x29\x39\x1a\x52\x22\xf6\x02\x21\x26\xfa\x60\x82\x82\x10\x27\x0d\ -\x0a\xf5\xc5\x04\x45\x94\xda\x16\x8d\xf2\xc2\xf4\xa2\x6d\x28\xd0\ -\x01\xd2\xbe\x80\x04\x6b\x43\xc0\x42\x62\x2c\x17\x4b\xab\x31\x10\ -\x30\x8a\xb4\x9d\xd9\xcb\x87\x99\x29\x67\x7a\x6f\xf1\x8d\xf5\x74\ -\xf6\xda\xeb\xfc\xff\xbf\xd7\xd9\x6b\xaf\x7d\xe0\x41\x37\x19\x4a\ -\x70\xda\xea\x9c\x24\xeb\xf1\x66\x8a\xb1\xcb\x51\x49\x02\xa6\x00\ -\x46\xe0\xba\x42\x0b\xaa\xf5\x88\xb7\x32\x58\xbe\xff\x97\xff\x55\ -\x40\xba\x93\xb7\x20\x6c\x4d\xa1\xa0\xcf\x0f\x12\xf7\x2c\xa2\xdb\ -\x82\x65\x25\x27\xee\x4b\xc0\x72\x67\xd3\x18\xb1\xf6\x73\x60\x5d\ -\xd4\xd5\xa6\x50\x6d\xd0\x23\x61\xa4\xd9\x67\xc2\x6d\x1d\xa1\xb0\ -\xf5\x9a\x11\x13\xc3\x6a\xa7\x89\x48\x1a\xb0\x1a\x98\x1a\x8d\xaf\ -\xb1\x9d\xe4\x9e\xa8\x2a\xfe\x63\xc8\x02\xd2\x9d\xbc\x19\xd6\x4a\ -\x15\x30\x2b\x42\x2c\xfe\xd0\x8d\x49\x07\xea\xea\x0a\x42\xfd\x89\ -\xf6\xfb\xfd\xe6\xd4\x85\xeb\xaf\x02\x1f\x00\xc9\xc0\x35\x63\xed\ -\xaa\x63\x95\xa5\xe7\x06\x2d\x60\x59\x56\x4e\xb2\xc1\x73\x06\x61\ -\x82\xc0\xf7\x9e\x91\xff\xbe\x76\xe4\xe0\xc1\xbf\xfa\x23\xee\x6e\ -\x19\x19\x6f\x8e\xe8\x1c\x75\x77\x9f\xa0\xb9\xc0\x3f\x8a\x2e\x39\ -\x5e\x5e\xd2\x38\xa0\x80\x8c\xec\xec\xc4\xd0\xdd\x51\xa7\x41\x67\ -\x83\xee\x59\x34\x67\xca\xdb\x05\x05\x05\x76\x28\xe4\x6e\xfc\xb4\ -\xac\xbc\xad\x2a\xb2\x0b\x68\x31\x6a\x16\x1c\xab\x28\x6a\x73\x07\ -\x78\xbb\xbf\x11\xba\x3b\x6a\x6f\x84\x9c\xea\xde\xc8\xd3\x56\xe7\ -\x24\xa9\xd7\x9b\x0f\xfa\x12\xf0\xb8\x80\x55\xf4\x2a\x22\x87\x8d\ -\x35\xc5\xdd\x08\xb4\xb6\xa2\xa4\x30\x35\x2b\x3f\x19\x21\xdf\x1a\ -\xfb\x2d\xb0\x1c\xd0\x5e\x33\x90\xba\x36\xf7\x69\x30\x67\x81\x3f\ -\xd5\x98\x99\xc7\x03\x45\xb7\x63\x73\x7e\xbf\xdf\x9c\x3e\xdf\xf2\ -\xae\x8a\xbc\x0f\x8c\xec\x63\xc5\xff\x08\xbc\x57\x5b\x5e\xfc\xa9\ -\x9b\xc4\x71\x1c\xdf\x2d\x3b\xe6\x1c\x90\x02\xac\x08\x96\x17\xd7\ -\xc4\xe6\x4c\x5c\xbe\x30\xbb\x01\x54\x65\x67\x77\xf2\x53\x17\xae\ -\x7f\x1d\x4d\x65\x5f\xe4\x00\xa3\x15\xf6\xa4\xae\xcd\xdf\xe7\x5e\ -\x5c\x20\x10\xe8\x50\x61\x7b\x74\x58\xe8\x9e\xeb\x12\x90\x9e\xb5\ -\xe9\x31\x85\x65\xc0\xcd\x71\x9e\x5b\xfb\xdd\xa8\xa7\x2e\xb4\xec\ -\x00\xd6\xdf\x5b\x53\x3f\x16\x89\xd9\x9c\xba\x76\xe3\x5b\x6e\xf7\ -\xf1\xb2\xe2\x4a\xe0\x12\x30\x37\x7d\x4d\xee\x93\x3d\x04\x28\x76\ -\x65\x44\x99\x1c\x0e\x04\x02\x1d\x31\xff\xb2\xac\x9c\x64\x90\x1d\ -\xc0\xe0\x8e\xad\xae\x18\xfd\x30\x75\x55\xee\xa4\x38\x69\x22\x55\ -\x00\xea\x31\x6b\x7a\x0a\x10\x96\x02\xa8\xda\xa3\x6e\x3c\x63\x3c\ -\x6f\x00\x09\x83\xa0\xee\x6e\xa3\xd5\x6b\x36\xc6\x69\x0b\xeb\x31\ -\x00\xab\xbc\xd0\x43\x00\xaa\x49\x11\x75\x7a\x39\x0e\x46\x59\x31\ -\x0c\xf2\x08\xa1\xf0\xb2\x7b\x6c\xd4\xdb\x0c\x20\x91\x1e\xd2\x4d\ -\x80\x44\x9c\x09\x9d\x3e\x77\x19\x09\x91\xd3\x6c\xb8\x36\xd5\x3d\ -\x90\xf6\x84\x18\xf6\xe4\x28\x76\x7c\x15\x74\x37\xbf\xdf\x2f\x03\ -\xc5\x0c\x60\x9e\x01\xb0\xdd\xe0\x72\x1d\x20\x64\x42\x13\x63\x9e\ -\x82\x82\x02\x2b\x70\xf5\x3e\x04\x5c\x73\x0f\xda\x1f\xba\x13\xc5\ -\xd6\xd6\xd8\x01\xe7\xde\x03\xbf\x01\x88\x30\x3d\x0e\x42\xa8\x61\ -\xb8\xa6\xf1\xef\x26\xa0\xc9\x51\x7f\x4b\xcc\x77\x4f\x80\xa1\x2e\ -\xfa\x94\xee\x7e\x29\x2c\xe1\x2f\x80\xe1\xf4\x82\x0e\xf1\x50\x1c\ -\xa7\x47\x4c\x1a\x00\x62\x4e\xf6\x14\xd0\xa1\xd5\x51\x75\x2b\xe6\ -\x6f\xda\xd4\x55\x76\x27\x02\x07\x9a\x44\xf8\x24\x3a\x37\xa0\xc5\ -\x42\x54\xd9\x55\x1b\x28\x76\x57\x94\x28\xb2\x2a\xca\x5a\xd9\x43\ -\x40\xb0\xaa\xb4\x15\xe1\x24\xc2\x84\x71\x37\x6c\xbe\x1b\xf4\xc6\ -\x78\xf3\x0e\x50\x33\x98\x83\x48\x22\x2a\x02\x8b\xe7\x4e\xde\xe9\ -\xf6\xa7\x66\x6d\x5c\x19\x6d\x72\x3f\x07\x03\x5f\x76\xdd\x0d\xe2\ -\x76\xb8\xb5\xb2\x15\x40\x04\x7f\x46\x76\x76\x62\xcc\xdf\x50\x54\ -\xd4\x79\xf3\x61\x93\x09\xba\x87\xfe\x3f\x47\x08\x65\xd7\x58\xcf\ -\xed\x75\xee\x2e\xea\x38\x8e\x0f\x61\x77\x44\xa0\x6e\xc3\x95\xcb\ -\xb8\x32\xb9\x7c\xf1\xa7\xd6\xe4\x59\xf3\x66\x0a\x2c\xd4\x50\xc2\ -\xec\xf5\xaf\xac\x3c\x54\x5f\x5f\xaf\x00\x6d\x0d\x0d\xb6\xf9\x62\ -\xe3\xd1\x19\x29\x4f\x55\x20\xa2\xc0\x23\x40\x22\x60\x05\x2e\x83\ -\x7e\xe3\x31\x9a\x5b\x5b\x5e\x72\xa8\xa9\xa9\xc9\xfd\xb1\x64\x72\ -\xca\xe2\xcf\x10\xcd\x00\xea\x82\xe5\x25\xdb\xdd\x9c\x3d\x92\x1a\ -\xbd\x07\xfe\x00\xa4\x80\x7e\xbc\x68\xce\x94\x2d\x7d\x5d\x48\x1c\ -\xc7\xf1\x00\x04\x02\x81\x70\x1f\x19\x91\xd4\xac\xbc\x2d\x88\x7c\ -\x84\xd0\x4a\x87\x7d\x26\x58\x55\xda\xda\xaf\x00\xe8\xba\x0f\x9e\ -\x01\xc6\x03\x15\x9d\xc6\xb7\xa1\x2e\xb0\xef\xef\x3e\x48\x7a\x35\ -\xc7\x71\x7c\xb7\x6d\xe2\x5e\x45\x36\x02\x77\xc0\x3e\x17\x2c\x2f\ -\xfd\xb1\x7b\x5c\xaf\x27\xd5\xaf\x4d\x8d\x37\xa7\xa7\xcc\xff\x0e\ -\x21\x4d\x60\x89\x47\xc3\x1b\x66\xcc\x9a\x77\x3b\xe9\xd1\x95\xe7\ -\xaf\x5c\xa9\xef\xb7\x24\xfd\x7e\xbf\x49\x98\xf0\x84\xd3\xae\xbe\ -\x32\x90\x54\x22\x57\xb1\xb4\xda\x8a\xe2\x86\xde\xe2\xfb\xdd\xd7\ -\x4b\x33\x5f\x1f\x9b\x60\xbc\x45\x08\x4e\xd4\xd5\x22\x50\x0d\x7a\ -\x44\x30\xcd\x18\xdb\xd6\xde\x19\xb6\x3e\x8f\x6f\xa2\x45\xa7\x02\ -\xe9\x82\xae\xa6\xab\x7f\x48\x6d\xa7\xe9\xdc\x50\x17\xf8\xea\xf7\ -\xbe\x38\x06\xf5\x63\xb2\xcc\xc9\x5d\x68\xac\x29\x04\x9e\x1d\x4c\ -\x3c\xd0\x88\xd8\xad\xc1\xb2\xd2\xda\x81\x02\x87\xf4\x6b\xf6\x62\ -\xe6\xe6\x69\x21\x13\xca\x14\x23\xcb\x45\x35\x49\x23\x6d\xd5\x03\ -\xb4\x00\x2d\xa2\x5a\x8f\x78\x2a\x6b\xcb\x8b\x2e\x0d\x05\xf7\xc1\ -\xb6\xff\x00\xf7\x80\xda\xb0\x80\x19\xdd\x42\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7e\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x41\x0d\xc0\x20\x14\x05\x41\x5a\x4d\x78\xc2\x4f\x65\xd5\x14\ -\x95\xb1\x4d\x98\x31\xf0\x5f\x36\xdc\x18\x23\x34\xd7\xb3\xe7\x7a\ -\x76\xb9\xe1\x2e\x8f\xff\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ -\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xf1\ -\x01\xae\xf2\x78\xfd\x35\x3e\x46\xff\x02\xde\xf8\x3e\x00\x00\x00\ -\x00\x00\x00\x00\x9c\xe0\x03\xda\xaf\x07\x8e\xa0\xaf\x15\x04\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x68\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ -\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ -\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xf7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xa9\x49\x44\x41\x54\x58\x85\xed\ -\x96\xb1\x4a\xc3\x50\x14\x86\xff\x93\x64\xb1\x05\x5f\x40\xd4\x37\ -\xa8\x60\xa1\x11\x41\x7c\x03\x29\x0d\x2a\x5d\x7c\x01\x5d\x04\x11\ -\x97\x4e\x1d\x1c\x44\x97\xe2\x13\x38\x59\x49\x3a\x17\x17\x41\x0a\ -\x86\x52\xb0\x8f\x50\x3b\xb8\xb8\x28\xd4\xa9\xb9\xc7\xa1\x26\x36\ -\xb5\xb7\x4d\x4c\x6b\x86\xf6\x9f\x6e\x92\x73\xcf\xff\xe5\xdc\x7b\ -\x0f\x17\x98\x75\xd1\xa8\x8f\xa9\x2a\x27\x13\x1d\x51\x64\x50\x0e\ -\xc0\x6a\x44\xaf\x16\x83\x4d\x47\x53\x0a\x8d\x1d\xfa\x1c\x0b\x90\ -\xaa\x72\x72\xa1\xc3\x35\x00\x6b\x11\x8d\x07\xd5\xec\x6a\xb4\xe9\ -\x42\x28\xb2\xa8\x44\x47\x14\xa7\x60\x0e\x00\x6b\x6a\x57\x14\xdd\ -\x07\x29\xc0\x77\xd9\xa7\x22\x02\x19\xee\x58\x1b\x11\xe7\x5b\x73\ -\x3b\xa7\x8c\xdc\x2f\xe3\xa4\x5b\x82\x87\xe5\x96\x56\xe0\xbf\x34\ -\x07\xf8\xb5\x07\xd2\x65\x5e\xd1\x54\x6c\x03\xec\x7b\x9f\xa9\xf0\ -\x91\x2c\x09\x09\x08\x02\x9a\xcb\x0e\x9e\xee\xf6\xc8\xf9\x33\x80\ -\x6e\xf1\x09\xc0\xe7\xc3\xc0\x88\xb9\x24\xcd\x42\x3d\xdc\x17\x0d\ -\x8f\x69\x93\xf7\x1b\x06\xbd\x06\x05\xf0\x96\x20\x53\xe1\x3c\xc0\ -\x17\xc3\xcc\x43\x68\x4b\x23\xbe\xdd\x2d\xb3\x1a\x1a\x80\x98\x4f\ -\x23\x18\xfb\x20\xda\x2a\x36\x82\x06\xf7\xff\xed\x40\xd7\xe3\xeb\ -\xe0\x9e\x94\x05\xb0\xe4\xcd\xec\xe5\xaa\x85\x05\xf0\x35\x1a\x3b\ -\xa7\x4a\x37\xdd\xa0\x74\xcb\x01\x40\x87\x1e\x80\x12\xfc\x74\xc5\ -\x7e\x0c\xe7\x00\x73\x80\xd8\x01\xa2\x74\x3d\xa9\x88\xb9\xa4\x5b\ -\x42\xde\xba\x81\x96\x3b\x88\xa5\x02\x0c\x36\xe3\x04\x68\x3a\x9a\ -\x52\x88\x03\xa0\xc5\xe0\xab\xfe\x1b\x31\xd0\xd7\x7e\x75\x4b\xbc\ -\x03\x58\x9c\x88\x15\xd3\x81\x6d\xd0\x4d\x90\xd0\x9f\x0a\x30\xee\ -\x27\x62\x0e\x74\x85\x8a\x87\xa0\xc1\x1e\x80\x50\xe9\x18\xc0\x5b\ -\x64\x7b\xa6\xb3\x7a\x96\xda\xa1\x01\xea\x59\x6a\x0b\x85\xd6\xc1\ -\x30\x01\x7c\x84\xb5\x05\xf0\x0c\x50\xde\x36\xe8\x32\xe4\xdc\x19\ -\xd7\x17\x91\x1d\x7b\x32\x62\xe5\x6b\x14\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x94\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x46\x49\x44\x41\x54\x58\x85\xed\ -\xd1\x21\x4b\x43\x51\x18\xc6\xf1\xff\x7b\xc7\x8a\x41\x04\x41\xcb\ -\x76\xdd\xf6\x09\x04\x6d\x36\x93\xa8\x6b\x82\x49\xab\x82\xdf\xc1\ -\x62\x31\xf8\x11\x64\x20\x18\x0c\x26\x41\x10\x8b\xa0\x08\x86\x15\ -\xc1\xec\x7d\xcf\x3d\xd7\xee\x98\x60\x71\x7b\x2d\x1a\x14\xb6\xbb\ -\xbb\x24\x78\x7e\xf1\xf0\xf0\xf0\x1c\x5e\x08\x82\x20\x08\xfe\x3b\ -\xc9\x0b\x68\xea\x8f\x31\x16\x22\xb1\xad\x38\x8e\x9f\x46\x29\x4d\ -\x92\xa4\x26\x51\xe9\x14\xa4\x33\x17\x57\xd6\x45\xc4\x06\x65\xa3\ -\xdc\x36\x63\x0a\x98\xef\x9b\xdc\xab\x66\xcb\x79\x71\xe7\xdc\x82\ -\x44\xe5\x07\x90\x25\x8c\xe9\xbc\x7c\xee\x80\x52\xc4\x16\x70\x0e\ -\x4c\x22\x76\xe5\x5c\xb6\x3d\x28\xab\x9a\xad\x19\xd1\x2d\xd8\x2c\ -\x70\x63\xf6\xb1\x32\xec\xf7\x23\x0d\xa8\x56\xab\xef\x73\x71\x65\ -\x13\xe1\x08\x28\x1b\x76\xe2\x9c\xdf\x37\xb3\x1f\xe7\x4b\xd2\x6c\ -\x17\xb1\x0b\x60\x02\x38\x7d\xeb\x76\x56\xea\xf5\xfa\x6b\x5e\x7f\ -\x21\xaa\xe9\x9e\x3a\xdf\x53\xe7\x4d\x35\x6b\xb5\xdb\xed\xb2\x99\ -\x45\x89\xf3\x87\xea\xbc\xa9\xf3\xa6\x69\x76\xf0\x7b\xdc\x30\x23\ -\x07\xbf\x39\xf7\xd2\x34\xfa\x67\xc0\x84\xc1\x9d\x40\x17\x58\x05\ -\x3e\x30\xdb\xa9\xd5\xe2\x56\x91\xbe\xc2\x03\x00\xd2\x34\x5d\xec\ -\x9b\x5c\x02\x33\x5f\x4f\xdd\xbe\xd8\x46\x23\x8e\xaf\x8b\x76\x8d\ -\x35\x00\x40\x55\xeb\x48\xe9\x59\xc0\xf7\x7a\xd2\x6c\x34\x2a\x8f\ -\xe3\x76\x8d\xcd\xcc\xa4\xc8\xbd\x83\x20\x08\x82\x3f\xe9\x13\xfa\ -\xca\x87\x49\xdf\x83\x3a\x35\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x04\x83\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x35\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4b\x88\x1c\x55\x14\x86\xbf\x53\xdd\x93\x31\x24\x41\x88\xf1\ -\x85\xa8\x2b\x51\x5c\x08\x43\xb7\x11\x11\x64\x14\x8d\x06\x31\xf8\ -\x00\x5d\x89\x4e\x30\xd3\x1d\x92\x9e\x76\x40\x11\x7c\xd0\x36\x89\ -\x98\x80\xf8\xe8\x36\xa6\x7b\x0c\x18\x17\x06\x75\x15\x06\x34\x3a\ -\xba\x48\x40\x90\xcc\x74\xe2\x03\x71\x21\x88\xb8\xd0\xa8\x84\x28\ -\x9a\x09\x66\x66\xba\x7e\x17\x6d\xa0\xaa\x18\x83\xd1\x7a\x5c\x4c\ -\xff\xcb\xff\x40\xdd\x73\xbf\x3a\x7d\xef\x3d\x55\xd5\xd0\x57\x5f\ -\x7d\x9d\xcd\xb2\xac\x13\xf8\xa7\x2a\x8e\x36\x6b\x66\x7a\x4a\x60\ -\x48\x5b\x3b\x13\xd5\x67\xe2\xb8\xae\x17\xc7\x45\x92\x56\x61\xf4\ -\xe5\x9b\x30\x6a\x82\x3c\x90\xc3\xec\xe9\xb8\xae\xed\x3c\x80\xd5\ -\xa5\x66\xd1\xcc\x26\x41\xc1\x6a\x8d\x2d\x6f\xa7\x01\x14\x46\x9b\ -\x57\xf9\x68\x1f\xb0\x3c\xe8\x0b\xfc\xb8\xc6\x70\x16\x40\x61\xf4\ -\xa5\xcb\xcc\x34\x05\xac\x8a\xc6\x0c\x14\xd7\x38\xf9\xb8\x2e\x14\ -\xa7\x86\x46\x1a\xe7\x9b\x31\x05\x5c\x9a\xf4\x58\xce\x55\xc0\x0d\ -\xeb\xb7\xaf\xc8\x2d\xe1\x3d\xe0\xca\x34\xc6\x73\x0a\xc0\xf0\x43\ -\xaf\x9f\x33\x37\xb0\x74\x2f\x50\x0c\xfa\x8a\xb1\xe4\xa3\x72\x06\ -\xc0\x70\xad\x96\xff\x7d\xf0\xf8\x1e\xc1\xcd\x91\x90\x2c\xc6\x45\ -\x2f\x2a\x47\x00\xc8\x8e\x1f\x39\xaf\x6d\xe8\xee\xb0\x6f\x22\xc1\ -\xc9\x83\x23\x00\x8a\xa5\xe6\x76\x8c\xf5\x41\x4f\x98\x40\x89\x4e\ -\x1e\x1c\x00\x50\x28\x35\x1e\x07\x1e\x8b\xfa\x96\xc2\xe4\x21\x63\ -\x00\xd7\x96\x1b\x1b\x0c\xb6\x2d\x12\xea\xa6\x95\x43\x66\x00\x8a\ -\xe5\xe6\xbd\x12\xad\xa8\xaf\x94\xee\xfc\x29\x65\x02\xa0\xb8\xa1\ -\x71\x0b\xd2\x9e\x45\xc6\xf7\xad\xb7\xf0\xa5\xa6\xd4\x01\x14\xcb\ -\x8d\xd5\x78\xec\x05\x96\x04\x7d\x19\x3e\x09\xee\xf7\x7f\xa7\x54\ -\x01\x5c\x57\x6a\x5c\x8d\xd8\x07\x2c\x8b\x84\x7c\x53\xfa\x93\x87\ -\x14\x01\x0c\x6d\x7a\xe5\xf2\x05\x6c\x0a\x58\x19\xf4\xff\xea\xec\ -\x32\x99\x3c\xa4\x04\xe0\x9a\xf2\xce\x0b\xbc\x05\xff\x43\x43\x97\ -\x04\x7d\x81\x1f\x67\x67\xf7\x6f\x94\x78\x37\x58\x18\x6d\x9f\x6b\ -\x3a\xf9\x3e\x70\x45\xd0\x57\xef\x88\x9b\xe9\xe4\x21\xe1\x0a\xb8\ -\x7e\xfc\x85\xa5\x66\x73\x93\xc0\x50\x28\x20\x4b\xf4\x7c\x7f\x26\ -\x4a\x0c\xc0\x70\xad\x96\x9f\x9f\xcd\xbf\x05\xba\x31\xe8\xab\x77\ -\xca\x75\x62\xf2\x90\x14\x80\x5a\xcd\x9b\xfd\x69\xd5\x2e\x8c\x75\ -\x41\x5b\xb8\x73\xe7\x4f\x29\x01\x00\xb2\xe2\x91\x95\xcf\x4b\x7a\ -\x30\xec\xbb\x37\x79\x48\x60\x11\x2c\x96\x1b\x4f\x20\x1b\x0f\x99\ -\x12\x98\x7b\x93\x87\x98\x2b\xa0\x50\x6a\x96\x91\x6d\x0d\x99\x02\ -\x33\x4b\xad\xb9\x39\x53\xc5\x06\xa0\x58\x6a\x6c\x33\xb4\x33\xea\ -\xcb\xf0\x33\xdf\xeb\x4e\xa3\xf8\x2a\x20\xf2\x40\x03\x7a\x9d\x9d\ -\x0b\x7b\xfd\xe9\x14\x1f\x00\xa5\xd7\xc3\xc7\xa9\xd8\x00\x98\xa9\ -\x4a\xe4\x6e\x1b\xe6\xb9\xfe\xfa\x35\x36\x00\x33\xad\xea\x3b\x48\ -\x95\xa8\x2f\x91\x73\x19\x42\xac\xbb\x40\x67\xa2\xba\xc3\xa0\x16\ -\xf4\x0c\x40\xca\xb9\xfa\x26\x3e\xf6\x83\xd0\x4c\xbb\xb2\x05\xac\ -\x19\x76\x0d\x50\xe6\x0f\x60\x17\x53\x02\x49\x99\x3a\x17\x1d\x7d\ -\x44\xf0\x66\x34\x90\xcc\x78\xff\x4d\xc9\x24\x54\xaf\xfb\x68\x70\ -\x04\x78\x37\x12\x31\xe4\x16\x84\xc4\x92\x39\x34\x51\x9a\x97\x06\ -\xef\x03\x3e\x0e\x05\x0c\x03\x73\x06\x42\xa2\x89\x1c\x9a\x28\x9d\ -\x58\x38\xd9\xbd\x53\xf0\x79\x38\x22\x67\x7e\x0e\x89\x27\xf1\xd9\ -\xee\xf1\x5f\xbd\x5c\xee\x76\xe0\x9b\x48\xc8\x7a\xd5\x90\xad\x52\ -\xb9\x0b\x33\xaf\x6e\xfa\xd1\xeb\xda\xad\x88\x1f\x42\x01\xe1\x29\ -\x63\x08\xa9\x95\xe1\xf4\xae\xca\xb7\x78\xba\x0d\xf8\x25\xe8\x9b\ -\xf0\x7a\x8f\x0a\xb2\x51\xaa\xbf\xc3\x4e\xab\xfa\xa5\x87\x77\x07\ -\x70\x22\x14\x90\x79\x22\x1b\x08\xa9\x2f\x44\xd3\xed\xcd\x9f\xf8\ -\x66\xf7\x00\xf3\x41\xdf\x30\x4f\x19\x54\x42\x26\x2b\xf1\xe1\x56\ -\xe5\x03\xc3\x1e\x20\xda\x3c\xc9\x3c\xa5\x7c\x66\xce\x6c\x2b\x9a\ -\x69\x57\xde\xc6\xd8\x18\xf5\x4d\x78\x69\x12\xc8\x74\x2f\xee\xb4\ -\xc6\xda\x88\x27\x43\xa6\x81\xa4\x5c\x5a\x39\x64\x7e\x18\xe9\x4c\ -\x54\x9e\x43\x7a\x31\x64\x9a\xa1\x94\x4e\x8b\x99\x03\x00\x53\xe7\ -\xe2\x63\x8f\x9a\xd9\x1b\x21\x17\xa5\xd2\x37\x38\x00\x00\xa8\xd7\ -\xfd\x65\x17\x1e\x7d\x18\x31\x19\xf2\x2d\xf9\x0e\xd2\x0d\x00\xc0\ -\xfe\x7a\x7d\x61\xf9\xdc\x8a\xfb\x31\x0e\x44\x42\xa6\x04\xf3\x74\ -\x06\x00\xc0\xfe\xdd\x23\x7f\xe4\x06\x58\x07\x1c\x0e\xfa\x96\xe0\ -\xd6\xe8\x14\x00\x80\x83\xcd\xb1\xdf\xe6\x6c\x60\x2d\xf0\x75\x1a\ -\xe3\x39\x07\x00\xe0\x8b\xd6\xc6\x9f\xbb\x79\x6f\x8d\xb0\xef\x93\ -\x1e\xcb\x49\x00\x00\x9f\xee\xd8\xfc\x5d\x1e\xad\x01\x8e\x45\x63\ -\x71\x9e\x16\x9d\x05\x00\x70\xb0\x3d\xf6\x15\xc6\x5a\x60\x36\xe8\ -\xdb\xd9\xf2\x97\x19\x80\x4e\x6b\x6c\x1a\x9f\xbb\x14\xf8\x7e\x30\ -\xce\x8f\x29\x9d\x07\x00\xd0\x79\x6d\xec\x23\xd0\x16\xb0\xae\x89\ -\x2e\xe6\x3d\x9b\x75\x4e\x7d\xf5\xd5\xd7\xff\x43\x7f\x02\x97\x76\ -\x3e\x83\x62\x89\x8e\x83\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\x89\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x58\x85\xed\ -\xcd\xb1\x11\x00\x10\x10\x05\xd1\x4f\x21\x28\x45\xa2\x6b\x33\x5a\ -\x31\x14\x72\x22\xa1\xf4\x12\xfb\xa2\xcd\x56\x02\x00\xe0\x77\xe1\ -\xc6\x5c\x7b\xc8\x54\x7d\xb6\xd6\x4b\x4e\x4d\x92\xa2\xcf\x10\x00\ -\x00\xe0\xed\x00\x5a\x36\x07\x04\x97\xc1\x22\x16\x00\x00\x00\x00\ -\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xca\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\x7c\x49\x44\x41\x54\x58\x85\xed\ -\x97\x4b\x72\xd3\x40\x14\x45\xcf\x73\x32\x00\xb6\x10\x59\x2d\xcd\ -\x60\x0b\x6c\x81\x01\x90\x00\x81\x90\x8a\xf3\x71\x15\x2c\x20\x55\ -\xac\x81\x61\x66\x0c\x20\xc4\xf9\x3b\x21\x14\x55\xac\x81\x35\xc0\ -\x08\xb7\x24\x03\x3b\x00\x06\xc4\x8f\x41\xe4\x20\xeb\x63\x49\x2e\ -\x33\x82\x1e\x59\xaf\xba\xef\x39\x7e\x6a\x5b\x2d\xf8\xd7\x87\x0c\ -\x3f\x58\xfb\xe5\xa6\xca\xe0\x85\xc0\x55\x94\x67\x9e\xd7\x7c\x3b\ -\x4d\x90\xb5\xd1\x3c\xc2\x73\xe0\xa7\xd0\x78\x6a\xcc\xdc\x87\x51\ -\x81\x20\xfa\x08\x5c\x8f\x2f\x07\x2a\xba\xe4\xbb\x6e\x77\x1a\xf0\ -\x5e\x18\x3e\x14\x95\x03\xa0\x11\x97\x3e\x79\xa6\x79\x83\x44\x01\ -\x90\x2b\x89\x35\x0d\x51\x39\xec\x85\xe1\xe2\x5f\x80\x83\x70\xed\ -\x12\x74\x59\x54\xdd\x04\x06\xd3\x94\xe8\x85\xe1\x62\x06\x0e\x03\ -\x51\xd9\xcc\x08\x78\x5e\xf3\x4c\x45\x97\x73\x24\x0e\x26\x91\x88\ -\xe1\x87\x19\x38\xb4\x8c\x71\x4e\x33\x02\x00\xbe\xeb\x1e\xe5\x48\ -\xcc\xd4\x95\x28\xfc\xe6\xd0\x32\xa6\xb9\x9f\x9c\x2b\xe4\x0c\x6b\ -\xa3\x25\x84\xbd\x54\xc0\xb9\x20\x4b\xc6\x38\x27\xe3\xe0\x41\xd0\ -\x7f\xa0\xe8\x21\x30\x53\x06\x2f\x14\x98\x54\xa2\x00\xae\x02\x2b\ -\x79\xf0\xb1\x02\xb1\xc4\x63\x84\xdd\x2a\x12\x41\xd0\xbf\xaf\xe8\ -\x51\x1d\x78\xa9\x40\x89\xc4\xa3\xe1\x66\x9a\x14\x5e\x49\xe0\x02\ -\x10\x2d\x2b\x74\xf2\x24\x00\xf2\xe1\xd2\x32\xc6\xd9\x2b\xcb\xae\ -\x24\x30\x46\x62\xf8\x6b\x49\xd6\x2a\xc3\x6b\x09\x24\x24\x76\xc7\ -\xac\xab\x05\x87\xd4\xff\x40\xd9\x30\xa6\xb9\x2f\xb0\x02\x68\x01\ -\x7c\xb5\x0e\xbc\xb6\x00\x80\x2a\x3f\xf2\x04\xe4\xa2\xf6\xbd\x6e\ -\x5e\x2d\x01\x6b\xa3\x05\x84\xe3\xbc\x75\x0a\x0d\x45\x8f\x83\xa0\ -\x7f\xaf\x4e\x66\xe5\x3d\x10\x3f\xcf\xbb\xc0\xec\x08\x57\x04\x54\ -\x93\x39\xe7\x28\x8b\x9e\xd7\x3c\xab\x92\x5b\xa9\x03\x45\x70\x45\ -\xd6\x44\x59\x65\xf4\x96\xcc\x20\x74\xad\x8d\x16\xa6\x22\x60\x6d\ -\x74\xb7\x08\xee\x1b\xa7\x63\x8c\xb3\xab\xc8\xda\xa4\x12\x63\x05\ -\x62\xf8\x49\x06\x2e\xba\xee\x1b\xa7\x33\x2c\xf8\xc6\xe9\x14\x48\ -\x1c\x97\x49\x14\x0a\x8c\x85\xbb\xee\x4e\x7a\xbe\x6f\x9c\x8e\x8a\ -\xae\xa7\x24\x66\xcb\x24\x72\x37\x61\x2f\x0c\xef\x88\xca\x69\x55\ -\x78\x6a\xed\xaa\xa8\x6c\xa7\xb2\x7f\xc5\x1b\x33\x73\xd0\xcd\x74\ -\x60\x0c\x7c\xa3\x0c\x0e\xe0\xbb\xee\x8e\x8a\x6e\x90\xed\x44\xd7\ -\xda\x68\x3e\x3d\x7f\xa4\x03\xbd\x30\xbc\x2d\x2a\x6f\x0a\xe0\xaf\ -\xcb\xe0\xa9\xac\x35\x51\x79\x45\x49\x27\x12\xef\x05\xfd\x5b\x88\ -\xbe\x9b\x06\xfc\x4f\x66\xb8\x8e\xc8\xcb\xb4\x84\xd0\x98\x37\x66\ -\xee\x3d\x8c\x1c\x95\x75\x2b\x0d\x47\xb5\x3d\x29\x1c\xc0\xf3\xdc\ -\x6d\x54\xdb\xa4\x6e\x87\x32\xd8\x1a\x5e\x5c\x0a\xe8\xe8\x41\x54\ -\x51\x6d\x7b\x9e\xbb\x3d\x29\xbc\x44\xe2\x3c\x23\x20\x2a\x4f\x80\ -\xcf\xc0\x37\x41\x5a\xd3\x80\x27\x25\xe2\xa7\xe8\x57\xa0\xc7\x05\ -\xeb\xff\x00\xe0\x37\x93\x02\x62\x58\xa2\x39\x4a\x39\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xce\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x80\x49\x44\x41\x54\x58\x85\xed\ -\xd2\x21\x0e\xc2\x40\x14\x84\xe1\x7f\x96\x3b\x90\x70\x13\xe4\x9e\ -\x81\x0b\x20\x30\x1c\x09\x81\xc6\xd6\x22\xeb\x38\x0a\x49\xef\x40\ -\x07\xd5\x26\x0d\x09\xae\x5b\x33\x9f\x7b\x6f\x37\x99\x11\x0f\x22\ -\x22\x22\x36\xa6\xc5\x64\xab\xf6\xec\xd6\x0c\xec\x2b\x1f\x24\xff\ -\x14\x38\x76\xae\xb6\x1f\xc0\x61\xcd\x02\xc0\x50\xd0\xf9\x75\xd2\ -\x13\xa0\x4c\x5b\xdb\xb7\x06\xe1\x00\xfb\x11\xdf\xa7\xa1\xfc\xfb\ -\xd9\xc2\x5c\x40\xd2\x15\x78\x37\xc8\x1c\x3c\xea\x32\xe7\x2e\x9e\ -\x36\x38\xc2\x88\x88\x88\xcd\x7d\x01\x5e\x93\x20\x04\x37\xe4\x99\ -\xec\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0b\x37\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xe9\x49\x44\x41\x54\x78\x9c\xed\ -\x5b\x7d\x70\x54\xd5\x15\xff\x9d\xbb\x9b\x4d\x22\xe6\x43\xc1\xaf\ -\x06\x3f\x30\xc8\x40\x43\xac\x12\xb4\xc6\xd2\xc8\x47\xb2\x18\x85\ -\x60\x36\xbc\x56\xb1\x68\x20\x9b\x08\x5a\xdb\xe2\xb4\x4e\x65\xa6\ -\xae\xb1\xda\xb1\x1f\x02\x23\xa3\x68\xd8\x40\x44\xa3\x6d\x97\x04\ -\x06\xac\x31\x5f\x76\x53\x14\x1c\x85\xd0\x22\x04\x18\x35\x44\xc5\ -\xd4\x56\x49\x42\x40\x20\xfb\x76\xdf\xe9\x1f\x21\xf0\xf6\xed\xdb\ -\xb7\x6f\x93\x5d\xa6\xd3\xf2\x9b\xd9\x3f\xde\xb9\xbf\x7b\xce\x79\ -\xe7\xdd\x77\xdf\xbd\xe7\x9e\x05\xce\xe3\x3c\xce\xe3\xff\x19\x74\ -\x2e\x8c\x14\x4a\x8b\x2e\x91\x15\x6b\x9e\x20\xce\x56\x18\x13\x09\ -\xb8\x16\xe0\x74\x10\xa5\x42\x81\x05\x84\x7e\x00\xfd\x20\xfe\x0c\ -\x0a\xf6\xb3\xa0\x0e\x41\xd8\xd6\xe4\x71\x1f\x8a\xb7\x6f\x71\x0b\ -\xc0\xcc\xbb\x2a\x32\x85\x35\x50\x2a\x98\x8a\x18\xb8\x7e\x98\x6a\ -\x0e\x31\x73\x03\x43\xd4\xb4\xd6\xaf\xdd\x09\x80\x63\xe9\x23\x10\ -\xfb\x00\xd0\xac\xe2\xb2\xd9\x24\xc4\xa3\x04\x9e\x11\x63\xdd\x7b\ -\x99\xb0\xa2\xf7\x62\xf1\xea\xae\xaa\x2a\x39\x56\x4a\x63\x16\x80\ -\xd9\x8e\xc5\x33\x14\x12\xbf\x03\x30\x35\x56\x3a\xf5\xc1\x5d\x04\ -\x3c\xd1\x54\x57\xbd\x01\x31\x18\x11\x23\x0e\xc0\xac\x22\xe7\x65\ -\x64\xc5\xb3\x44\xb8\xd7\x80\xa6\x30\xf0\x2e\x31\xbc\x0c\x3e\x20\ -\xc8\xf2\x09\x83\x7a\x64\x31\x70\x2c\x19\x14\xf0\x05\x90\x42\x24\ -\xd2\x40\x34\x0e\x8c\x09\x44\x9c\x0b\xa6\x02\x00\xc9\xe1\x14\x32\ -\xb0\xcd\x02\x5a\xda\x58\xb7\x76\xdf\x48\xfc\x1f\x51\x00\x66\x4b\ -\x65\x37\x2b\x0a\x6d\x06\x70\x85\xb6\x8d\x81\x63\x00\xde\x14\x44\ -\x5b\x03\x81\x81\xb7\x5a\x37\x6d\x38\x12\x8d\xee\x5c\x69\x59\xf2\ -\xa8\x40\xff\x4c\x82\x98\x0b\xe2\x22\x3d\x1b\x00\x4e\x01\x58\xdc\ -\x5c\xe7\x7e\x7d\x58\x37\x80\x11\x04\x20\xdf\x51\xb6\x80\x88\xd6\ -\x01\x48\x0c\x71\x8a\xe8\x39\x9b\xcd\xfa\xcc\x5f\x5e\x5b\xd3\x3b\ -\x5c\xfd\x6a\x48\x92\x64\xeb\x53\xd2\xca\x01\x3c\x0e\xe0\x52\x6d\ -\x3b\x01\x4f\xe7\x4e\xce\x78\xbc\xb2\xb2\x52\x89\x56\x77\xd4\x01\ -\x70\xb9\x5c\x62\xfb\xbe\xee\xa7\xc0\xfc\x98\xa6\x49\x01\x63\x9d\ -\x15\xa8\x6c\xa8\x77\x1f\x8e\x56\xaf\x19\x14\x15\x2d\x4e\x39\x61\ -\x15\x8f\x10\xe1\xe7\x00\x2e\x54\xb7\x31\x68\xb3\x5f\x24\x2c\xf4\ -\x7a\x5e\x38\x1e\x8d\xce\xa8\x02\xe0\x72\xb9\xc4\xf6\x0f\x0f\xd7\ -\x82\xe8\x6e\x8d\x96\x6e\x41\x5c\xdc\xe8\xa9\x7e\x3f\x1a\x7d\xc3\ -\x45\xa1\xc3\x39\xd6\x4f\xd8\x84\xd0\x09\x77\xb7\x35\xe9\xe4\xf4\ -\x86\xda\xda\x7e\xb3\xba\x2c\xd1\x18\xb6\x8d\xbe\xae\x12\x44\x0f\ -\x69\xc4\xef\x09\x16\xb3\x1a\xeb\xdc\x07\xa3\xd1\x35\x12\x7c\xbc\ -\xbf\xbd\xff\xb2\xc9\xb7\xbd\x9a\xa0\xf8\xae\x21\x0a\x5a\x63\x5c\ -\x11\xf0\x27\x64\xe7\x4c\xce\xfc\x73\x47\x47\x87\xa9\x2f\x84\xe9\ -\x00\xd8\x1d\xce\x1f\x82\xb0\x5a\x23\x7e\x59\x4e\xf1\x4b\xad\xaf\ -\x57\xf7\x99\xd5\x13\x2b\x1c\xee\x78\xcf\xdf\xb9\xbf\x7d\x53\xe6\ -\xa4\x1b\x4f\x80\x28\x1f\xa7\x47\x33\x01\x13\x4e\x21\x39\xa9\xb3\ -\xa3\xbd\xc5\x8c\x1e\x53\xaf\x40\x41\xc9\xe2\xa9\x80\xd8\x06\x20\ -\x49\x25\x7e\xb5\xb9\xce\x7d\x1f\xe2\xb0\x3a\x8b\x16\xf9\x0e\xe7\ -\xcf\x88\xb0\x52\x2d\x63\xc2\xfd\x2d\x1b\xdd\x1b\x22\xf5\x8d\x18\ -\x80\x59\xc5\xf7\x8d\x16\xc2\xf6\x0f\x00\x19\x67\xb5\xe3\x7d\x39\ -\xd5\x7f\x9b\xb7\xa6\xe6\x54\x54\x8e\x16\x3b\x27\x91\x05\xc5\xcc\ -\xb8\x9e\x80\xb1\x18\xfc\x05\x00\x1c\x26\xe0\x30\x33\xda\xc9\x82\ -\xfa\x61\xec\x01\xa8\xc0\xe1\xac\x06\x61\x91\x4a\xe6\x13\x2c\x72\ -\x1b\xeb\xab\xda\x0d\x3b\x46\x74\xba\xa4\xbc\x9a\xc0\x8b\x55\x3d\ -\xba\xe1\x53\x6e\x6a\xde\xb2\xae\xdb\x8c\x67\x83\x9f\xb0\xf4\xa5\ -\x00\x2f\x01\x30\xd1\x4c\x1f\x00\xbb\xc1\xf4\x5c\xba\xa5\xef\x15\ -\x8f\xc7\x13\x30\xd3\xa1\xb0\xf0\xe1\x44\xff\x05\x27\xdf\x06\x70\ -\xeb\x90\x8c\x81\x76\xff\x91\x8c\xef\x7a\xbd\x95\xfe\x70\xfd\x84\ -\x91\xd2\x7c\xa9\x62\x5a\xd0\xcd\x03\xcc\x0a\x4a\xcc\xde\xbc\xbd\ -\xa4\xec\xae\x3e\x25\x6d\x1f\xc0\xab\x60\xfe\xe6\x01\xe0\x46\x10\ -\xaf\xef\x53\xd2\x76\xda\x8b\x9d\x33\xcd\x74\x68\x68\x58\x3d\xa0\ -\xc8\x70\x80\xf1\xf5\x90\x8c\x80\x29\xb6\xd1\x5f\x3c\x68\xd4\xcf\ -\x68\x12\xa4\xcc\x89\x37\xd4\x82\xe8\x2a\x95\xac\xb6\xa5\xde\xad\ -\x9d\x08\x43\x90\x53\x51\x91\x90\x75\xf5\x0d\xab\x41\xf4\x2c\x80\ -\x8b\x23\x7a\x1f\x1e\x97\x83\x70\xff\xf8\xac\x29\xf4\x23\x69\xee\ -\xdf\xda\xda\xda\x0c\xe7\x9b\x43\x07\xdb\xbf\xb9\x76\xd2\x14\x99\ -\x08\xb7\x9f\x11\x32\x6e\x1a\x3f\x35\xeb\x85\x4f\xf6\xec\xd1\xdd\ -\x40\x85\x1d\x01\x05\x52\x79\x1e\x88\xa6\xa9\x44\xb2\xc2\x01\x57\ -\x24\x8f\xef\x5c\xb0\xf4\xa2\x8b\x8f\x28\x0d\x44\x64\x18\xf9\x68\ -\xc0\x0c\xd7\xf6\x7d\x5f\xfc\x69\xce\x9c\x8a\x0b\x22\x71\xfd\xa9\ -\xfe\x17\x01\x7c\x76\x46\x40\x18\xc3\x27\x92\x1e\x08\xc7\x0f\xff\ -\x0a\x30\x7e\x11\x2c\xa0\x97\x5a\xeb\xd7\x77\x1a\x19\x97\x24\xc9\ -\xe6\x1b\x90\x37\x03\x98\x15\xc9\xd1\xa8\xc1\x98\xef\x4b\x0c\x6c\ -\x70\xb9\x5c\x86\xaf\xad\xb7\xa6\xe6\x14\x98\x34\x0f\x8a\x1f\x91\ -\x24\x49\x77\xb4\xeb\x2a\x9b\x2e\x95\x5e\x0e\xe6\xdb\x55\x22\x59\ -\x91\xf9\xa9\x08\x2e\x52\x5f\x20\xed\x79\x00\x79\x11\x78\xc3\x06\ -\x83\x4a\xb6\xef\xed\x8e\x38\x0a\xd3\x2d\x7d\xaf\x00\xfc\x91\x4a\ -\x94\xd1\xab\xa4\xe7\xeb\x71\x75\x03\x90\xa0\x24\x2c\x40\xf0\xfc\ -\xf0\x76\xeb\x16\xf7\xbf\x8c\x8c\x16\x94\x38\xef\x05\xc1\x19\xc9\ -\xb9\x91\x83\x1f\x9f\xe5\x28\xd7\xbd\x99\x21\x78\x3c\x9e\x00\x98\ -\x3c\x6a\x19\x81\xef\xd7\xe3\x86\x19\x4e\x3c\x37\xa8\x33\xd1\x16\ -\x23\x83\xa7\xdf\xcd\x67\x8c\x38\xb1\x84\x20\x5e\x11\x6e\x48\x0f\ -\x81\x48\x68\x7d\xbe\x43\xaf\x4f\x48\x00\xec\x0b\x17\x8e\x82\xea\ -\x5b\x0a\x00\x0a\xd1\x1b\x46\xc6\x7c\x36\x7e\x04\xea\x85\x52\xfc\ -\x91\x7d\x34\x90\x56\x6a\x44\xc8\x9d\x7c\xc5\x07\x20\xa8\x47\x6d\ -\x5a\x3f\x52\x73\xb4\xbc\x90\x00\xf0\x49\xdb\x2d\x00\x6c\x2a\xd1\ -\xdf\x5b\x3c\x55\x9f\x69\x79\x43\x90\x24\xc9\xc2\xc4\x3f\x89\xec\ -\x73\x6c\xc1\x84\x9f\x1a\xb5\x57\x56\x56\x2a\x60\x04\x3d\x38\x85\ -\x45\x48\x9e\x32\xf4\x15\x60\x31\x59\x7d\x49\x84\x6d\x46\x86\x7a\ -\x39\xed\xfb\x00\x2e\x31\xe2\xc4\x09\xd9\x05\x25\x0f\x5c\x67\x44\ -\x20\x70\xb0\xef\x8c\x2c\x2d\x47\x27\x00\x98\xa4\xbe\x54\x14\xfa\ -\x28\x84\xa3\x36\xc2\x98\x6f\xd4\x1e\x4f\x30\x02\x25\x86\x04\x12\ -\x1a\xdf\x79\x92\x96\x12\x1a\x00\xe2\x6b\x82\x05\x8a\xe1\xb7\x1f\ -\xe0\x38\x67\x81\xc3\x83\x08\x21\xef\xb4\x1a\x3e\x92\xb5\xbe\x8f\ -\xd3\x72\xf4\xbe\x02\x29\x41\x46\x80\x08\x7b\x7d\x3a\x97\x93\x5f\ -\x30\x18\x63\x0d\xdb\x47\x85\xf8\x9e\xa2\xa5\x44\x0c\x80\x60\x0e\ -\x9b\x63\x3b\xbd\x2a\xd3\xcb\xd6\x9e\x2b\x18\x06\xc0\x5b\x53\x33\ -\x00\x40\xbd\x13\xb4\x49\x92\xa4\x9e\xe0\x75\x03\x10\xb4\x45\xf6\ -\x0b\x11\x76\x03\xd2\xd6\x06\x11\x46\xc7\xb9\x01\x21\x61\xa4\x2a\ -\x42\x9c\x27\xc6\xb1\x20\x02\x73\xc8\xb0\x19\x82\xd7\x5b\xe9\x27\ -\xc0\x70\x85\x18\x57\x28\x30\xcc\x3e\x4f\x2f\x2d\x4d\x04\x60\x55\ -\x89\x7c\x1e\x8f\xc7\xa7\xe6\x84\xae\x03\x06\x4f\x6a\xcf\x5e\x03\ -\xe9\x46\x46\x98\xf1\x45\x64\x4f\xe3\x03\x22\xe3\x00\x58\x7a\xac\ -\x69\x1a\xd1\x31\x2d\x27\x34\x00\xc0\xa7\xc1\x56\x42\x67\x4e\x4d\ -\xfb\x5e\xc3\xf6\xf8\xc2\xd8\x76\xa2\x72\x6d\xd0\x35\xa3\x4b\x4b\ -\xd1\x5b\x07\xec\x57\x5f\x12\xc8\x70\xb1\x01\xa6\x7a\xc3\xf6\x38\ -\x82\x58\x18\xda\x26\x16\x41\xbe\x33\x70\x40\xcb\x09\x09\x80\x60\ -\x04\x1d\x36\x32\x30\x4d\xcb\x51\x43\x4e\x95\x9b\x00\x44\x75\x1a\ -\x13\x23\x7c\xda\x58\x5f\xb5\xdb\x88\x20\x98\x83\x7d\xd7\x19\xad\ -\x21\x01\xf0\x59\x6d\x3b\x00\x9c\x49\x1f\x11\x30\xa5\xd0\xe1\x0c\ -\xfb\xb9\x19\xcc\x0c\x53\x8d\x09\x87\x63\x0b\x42\x15\x0c\x52\xf2\ -\x2e\x97\x4b\x30\x68\x4e\x90\x90\xe1\xd5\xf2\x42\x02\x70\xfa\x6c\ -\x6d\x87\x5a\xe6\x27\x8d\x22\x0d\xac\xc2\xff\x24\x80\xa3\x86\x0e\ -\xc7\x16\x9f\x1f\xa7\x94\x95\x46\x84\x77\x3e\xec\xce\x41\xd0\x1a\ -\x85\xfa\xfd\x3d\x19\x3b\xb5\x3c\xdd\x6f\x38\x01\x9a\xed\xaf\x52\ -\x64\x64\xac\xc1\xb3\xfe\x2b\xa6\x88\x19\xa3\x58\x62\xf9\x0e\xcf\ -\xca\x93\x46\x04\x12\x5a\x9f\xf9\x2d\xbd\xf4\xb8\x6e\x00\x58\x56\ -\x6a\x01\xa8\x8e\x9a\x69\x66\xa1\xb4\xc8\x70\xc7\xe7\xff\x7a\xec\ -\x2a\x00\x8d\x46\x9c\xd8\x80\x5e\x69\xae\x73\xd7\x1a\x31\x5c\x2e\ -\x97\x20\x26\xed\x26\xed\x65\x3d\xae\x6e\x00\x9a\xb7\xac\xeb\x26\ -\x42\x93\x4a\x94\x28\x2b\x56\xed\x71\x78\x10\xbc\xde\x4a\xbf\x1c\ -\xf0\xdf\xcd\x40\x3c\x0f\x49\xdf\x93\x53\xe4\x0a\x44\x38\x8e\xdb\ -\xb1\xaf\xfb\x1e\xa8\xce\x21\x08\xf8\x52\x3e\x92\xd1\xa4\xc7\x0d\ -\xbb\x8c\x65\xf0\x1f\xd4\xd7\x04\x7e\x68\xa6\xa3\xec\x6a\x23\xc3\ -\xde\xcd\x35\x7d\xcc\x81\x3b\xe2\x14\x84\x9d\x8a\x8c\xbb\x22\x1d\ -\xc7\x49\x92\x64\x63\xe6\x5f\xab\x65\xcc\xbc\x32\xdc\xe9\x50\xd8\ -\x00\x34\x6f\xac\x7e\x9b\x38\x68\x32\xb4\x59\x08\x4f\x44\xf2\xb2\ -\xb5\x7e\x7d\xa7\x3f\xe0\xbf\x05\x20\xdd\x88\x0f\x0b\xcc\x7f\x3c\ -\x2e\x52\xf2\x22\x25\x66\x01\xa0\x57\x49\xad\x40\xf0\xb6\xb7\x27\ -\xd9\xcf\x6b\xc2\xf1\x8d\x36\x32\xac\x08\x2c\x0f\x16\xd1\x7d\x76\ -\xc9\x69\xb8\x07\x07\x06\x47\x82\x7c\xe4\x5b\x77\x82\xe8\x97\xac\ -\xb3\xfc\x34\x0d\xc6\xd7\x00\x2d\x6d\xae\xaf\x5e\x10\x69\xd2\x03\ -\x80\xe9\xf7\x54\x8c\x21\xd0\xaf\x34\x3a\x7e\xb3\x65\xcb\xba\xb0\ -\x3e\x18\x66\x56\x3b\x3b\xda\xbb\x32\xbf\x9d\x93\x09\xe0\x3b\xa7\ -\x45\x04\x46\xe1\xb8\xeb\xa6\xbc\x76\xe8\x60\xfb\x37\x46\x7d\xbb\ -\xba\xda\x94\xce\x8e\xf6\x77\xc7\x4f\xbc\xb9\x9a\x48\xb9\x10\x40\ -\x16\x60\x7a\xf7\x76\x94\x80\x55\x6c\x11\x3f\x68\xd9\xb8\xf6\x5d\ -\x33\x1d\x24\x49\xb2\xc9\x72\xe2\x56\xd0\xd9\xb4\x17\x01\x7b\x7a\ -\xc6\x88\xb2\x7f\xee\xda\x15\xb6\x76\x28\xe2\xe9\xb0\xbd\x78\xc9\ -\xa5\x6c\xf1\xef\x01\xe3\x32\x95\x78\xbb\xf5\x44\xf2\xcc\x86\x86\ -\xd5\x03\x66\x9c\x03\x06\x53\xe7\xa7\x92\x94\xdb\x05\xa3\x84\x81\ -\x6c\x0c\x66\x91\x87\xce\x0d\xbf\x02\xa8\x1b\xcc\xed\x24\xc8\x93\ -\x46\x7d\xad\xda\x5d\x5b\x24\x14\x94\x38\xd7\x00\x58\xa2\x12\xc9\ -\x42\xf0\xb4\x48\x65\x3b\xa6\x0a\x24\xf2\x1d\xce\x5b\x88\xe0\x85\ -\xaa\x22\x8c\x41\xeb\x5a\xea\xd6\x3a\x31\x82\x02\x89\x5c\x69\x59\ -\x72\xfa\x71\xbf\x12\x4d\x20\xf5\x60\x9f\x5f\xfe\x20\x33\x3f\xaf\ -\x96\x11\xc3\xd9\x54\xef\xae\x8e\xd4\xd7\x74\x91\x54\x81\xa3\x6c\ -\x21\x88\x82\x2a\x2e\x18\xa8\xba\x48\x1c\x7d\x38\xda\xa7\x15\x43\ -\x90\xbd\xc4\xf9\x30\x03\x2b\xa1\x9a\xcf\x88\xb0\xaa\x69\xa3\x7b\ -\x99\x19\x05\xa6\x6b\x84\x3a\xf7\xef\xde\x93\x99\x95\x73\x01\x80\ -\xef\x9d\x31\x04\xe4\x9c\x52\x92\xf2\xae\xba\x61\xea\x1b\x5d\x7b\ -\x77\x9d\x88\xc6\xf3\x91\x42\x92\x24\x5b\xc6\xa4\x5b\x5f\x02\xb0\ -\x1c\xc1\x0f\xb2\x51\x3e\x92\xb1\xa8\xab\xab\xcd\x54\xcd\x60\x54\ -\xe9\xac\x74\xea\x5b\x8e\xc1\xf2\xb4\xb3\x20\xdc\x96\xe0\x0b\x7c\ -\x90\x2f\x55\x64\x47\xa3\x6b\x24\xb0\x17\x2f\xb9\xb4\x2f\x90\xda\ -\x0a\xa0\x4c\xd3\xb4\x4f\x0e\xf8\xef\x36\xaa\x08\xd1\x22\xea\x42\ -\x49\x49\x92\x2c\xbd\x4a\xfa\xef\x09\xac\x1d\x62\x32\x80\x35\xa4\ -\x58\x9f\x6e\xda\xf4\xe2\xbf\xa3\xd5\x6b\x06\xb9\xd2\xb2\xe4\x14\ -\xe5\xd8\x8f\x99\xf1\x18\x08\x17\x05\xb7\x72\x03\x0b\xcb\x3d\x2d\ -\x9e\xaa\xa8\x36\x65\xc3\x2e\x95\xb5\x3b\x9c\x65\x4c\x58\x83\xd0\ -\x4f\xdb\x71\x22\x3c\x6b\x49\x3c\xb9\x22\x9a\x82\x45\x23\x4c\x9f\ -\xee\xb2\x26\x8c\x39\x5c\x0a\xa6\x27\xa0\x7b\x06\xc9\x2b\xd2\x45\ -\xff\xa3\x66\xeb\x89\xd4\x18\x51\xb1\xb4\xdd\x51\x96\xc7\x44\xf5\ -\x00\x46\x87\xfa\x84\x5e\x02\xb6\x02\xd8\x6a\x49\x3e\xd9\x14\x6d\ -\x30\x24\x49\xb2\xf5\x04\xd2\xf3\x04\xf1\x5c\x00\xf3\x00\xe8\x2d\ -\xc3\x65\x62\x2c\x35\x33\xdb\x87\xc3\x88\xcb\xe5\xed\xf3\x16\x5d\ -\xc9\x56\xcb\x2a\x00\x0e\x03\x9a\x4c\x40\x1b\x13\xfe\xca\x4c\x07\ -\x2d\x4a\xe0\x63\x56\xb8\x27\x61\x54\xd2\x71\x85\xfa\x03\x03\xbe\ -\x94\x14\xc2\x40\x1a\x05\xc4\x38\x41\x98\xc0\x4c\xb9\x20\x9a\x0d\ -\x70\xaa\x81\xce\x0f\x48\x60\x69\x93\xc7\xbd\x6b\x24\xfe\xc7\xec\ -\x0f\x13\xf6\xf9\xe5\x85\xcc\xfc\x5b\x0c\x2e\x72\xe2\x07\x42\x37\ -\xc0\x4f\xa6\x53\xbf\x7b\x38\x43\x3e\x54\x5d\x0c\x31\x58\x4c\xdd\ -\x3d\x0f\xc4\x8f\x01\xb8\x29\x96\xba\x01\x74\x02\x58\x21\xa7\xf8\ -\xab\xa3\x2d\xd0\x34\x42\xdc\xfe\x34\x35\xbb\xa4\x3c\x8b\x81\x52\ -\x06\x17\x01\x98\x30\x1c\x1d\x04\x7c\xa9\x80\xde\x14\xac\xbc\x9c\ -\x9b\x3d\xf6\x9d\xe1\xfc\x1f\xc0\x84\x8d\xf8\xc3\x3e\x6f\xd1\x95\ -\x4a\x82\x65\x06\x81\xb2\x00\x65\x22\x98\xc6\x01\x48\x03\x90\x8a\ -\xc1\x93\x9b\xa3\x00\xfa\x01\xfa\x1c\xe0\x03\x0c\x1c\x60\x11\x68\ -\x6b\xf5\xac\xdf\x8f\xff\x82\x5a\xe4\xf3\x38\x8f\xf3\xf8\xdf\xc5\ -\x7f\x00\x80\x02\xea\x80\xb2\xb7\x05\xfa\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\xb2\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ -\xd6\xb1\x4a\x03\x31\x1c\xc7\xf1\x6f\x72\x97\xfa\x06\x56\x90\x6a\ -\x29\x5d\xaa\x93\x93\x73\xeb\x03\x08\xfa\xa4\xe2\x52\x10\xda\x87\ -\x50\xeb\x52\x6e\x13\xd4\xc9\xfd\xae\xf7\x77\x90\x13\xda\x5e\xbd\ -\x24\x4d\xce\xc1\x8c\xc9\x1f\x3e\x3f\x92\x3f\x7f\x02\xff\x7d\xa9\ -\x36\xb1\x2c\xcb\xba\x5a\x9b\x3b\x34\xaf\xfd\x93\xde\x2d\x80\x6e\ -\x15\x4f\xd2\x39\x8a\x4b\x4a\x8e\xab\xfd\xb4\x55\x1c\x35\x02\x79\ -\x29\xcb\xe2\xba\x3a\x8b\xfe\x04\x5b\xf8\xaa\x18\x0f\x06\x83\xf7\ -\x56\x02\x34\xe1\x51\x03\xd8\xe0\xd1\x02\xd8\xe2\x51\x02\xb8\xe0\ -\xc1\x03\xb8\xe2\x41\x03\xf8\xe0\xc1\x02\xd8\xe2\xcb\xe5\xdb\x61\ -\x6a\xf2\x29\xf0\xd9\x3f\xed\x4d\x20\xc0\x24\x74\xc4\x67\xc0\x05\ -\x48\xa7\xda\xdf\x2b\x80\x07\x7e\x0e\x3c\x15\x79\xe7\xa6\x3a\xf3\ -\x7e\x02\x7f\xdc\x5c\x0d\x87\x47\x1f\x7b\x05\x08\x85\x7b\x05\x70\ -\xc4\xe7\xc0\x19\xf0\x5c\xe4\x66\xb2\x89\x3b\x07\x08\x8d\x3b\x05\ -\x88\x81\x03\x24\x21\xf1\x2c\xcb\xba\x49\x8a\x35\x0e\x16\x37\xe0\ -\x82\xeb\xc4\xcc\x5c\xf0\xc6\x00\x9e\xf8\xa2\xc8\xcd\xb8\x0e\x77\ -\x9a\x84\x91\xf0\xad\x49\x58\xfb\x27\x8c\x84\x57\xbd\xb1\x36\x09\ -\xb7\x9a\xd0\x0d\x4f\xe7\xa0\x7e\xc5\x6b\x1a\x73\x6d\x18\xe9\xcd\ -\x62\x47\x7c\x04\x2c\xca\x55\x5e\xdb\x70\x36\x8d\xa9\xd6\x8b\xfd\ -\x70\x9b\xba\x5d\x37\xa4\x01\x44\x44\xab\xc4\x3c\x34\xe1\x22\xa2\ -\x54\x62\xee\x9b\xf0\xcd\xba\x5d\xf8\x4f\x00\x00\x25\x1c\x08\x3c\ -\x36\xfc\x64\x94\x52\x74\xbe\xeb\xea\xf1\xba\x3a\x9b\x79\x80\x88\ -\x68\x11\x69\x1c\x4c\x22\xa2\x42\xd6\xfd\xf9\xfa\x02\x53\x42\xe8\ -\x88\x61\x1a\x4e\x81\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x03\x5e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x4f\x13\x51\x14\x86\xdf\x53\xd1\x21\x74\xa9\x84\x0f\xf7\ -\x6e\xb0\xdd\xb4\xc4\x8d\xfe\x0b\xc1\x48\x52\xdc\x98\x56\x89\xad\ -\xb2\x30\x81\x5f\xa0\x09\x0b\x4d\x5b\x23\xed\x4e\x49\x34\x01\xfe\ -\x05\xee\xa4\x1b\x0a\x2b\xd7\x14\x49\x74\x09\x32\x0a\x7d\x5d\xb4\ -\x94\x61\x66\x4a\x2b\x32\x3d\x6d\xb8\xcf\x6a\x3a\xe7\x4e\xf2\xde\ -\x27\xf7\xf6\x6e\xee\x01\x0c\x06\xc3\x65\x46\xda\x19\x14\x4d\x2c\ -\x84\xad\x81\xfe\x49\x02\xf7\x01\xde\x06\x30\x0a\xa0\x2f\xd8\x68\ -\xff\xcc\x21\x80\x0a\x20\x9b\x02\xac\xda\xfb\x07\xcb\x1b\x4b\x2f\ -\xf7\x5a\x7d\xd4\x42\x00\x25\x96\xcc\x4e\x8b\xc8\x2b\x00\x23\x17\ -\x93\xb3\x63\xec\x00\x98\x5b\x2f\xa4\x97\x00\x61\xb3\x41\x4d\x05\ -\xc4\x92\x85\xab\x02\x3b\x07\x41\x2a\x90\x78\x9d\x82\x28\x10\x56\ -\xba\x54\x4c\xfd\xf1\x2b\x37\x59\xc6\x14\x91\x7c\x1e\x40\xd2\x55\ -\x28\x8b\xe0\x0b\x88\xef\x55\xa0\x7a\xb1\x49\xff\x8f\x10\x10\x82\ -\x60\x98\xc4\x5d\x00\x91\x46\x41\x90\x12\xda\x00\xf8\xd4\x6f\x25\ -\xf8\xae\x80\x78\x2a\x3b\x0d\xe0\x83\xe3\xd5\x4f\x52\x32\xa5\xe2\ -\xb3\xcf\x67\x2d\xa7\xee\x80\x12\x4b\xe6\x1f\x8a\x30\x0b\xe0\xba\ -\xa3\xf0\x68\xbd\x90\xf9\xe8\x1e\xed\x11\x10\x4d\x2c\x84\xaf\x0d\ -\x58\xdf\x70\xb2\xe7\x7f\x90\x47\xd1\x52\x71\x76\x27\x98\xc0\xc1\ -\x10\x4b\xbe\x19\x11\xb9\xb2\x01\xe0\x06\x00\x80\xa8\xfc\xfe\x65\ -\xdf\x72\xff\x31\x86\xdc\x1f\x5a\x03\xfd\x93\x70\xfc\xe1\x91\xf2\ -\xbc\xd7\x26\x0f\x00\xa5\xe2\xec\x8e\x08\x5e\x34\x5e\x08\x46\xad\ -\xb0\x35\xe1\x1e\xe7\x11\x50\x3b\xea\x1a\x94\x6b\xcb\xbe\x37\xf9\ -\xba\x98\xfe\x04\xa0\x7c\xfc\x9b\x94\xd6\x02\xea\xe7\x7c\xed\x09\ -\x5c\xeb\xfe\x3d\x7f\x16\xc2\xda\x1c\xea\x90\x63\xee\x11\x3e\x02\ -\x30\x7a\x52\x94\xdd\x60\x82\x75\x8e\x53\x73\x10\xdc\xf4\xd6\xbd\ -\x34\x8e\xc6\x6e\x3b\xea\xce\x83\x6b\x0e\x9e\x63\xdf\x4f\xc0\xa5\ -\xc2\x08\xd0\x0e\xa0\x8d\x11\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\ -\x46\x80\x76\x00\x6d\x8c\x00\xed\x00\xda\x18\x01\xda\x01\xb4\x31\ -\x02\xb4\x03\x68\x63\x04\x68\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x11\ -\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\x46\x80\x76\x00\x6d\x8c\x00\ -\xed\x00\xda\x18\x01\xda\x01\xb4\x31\x02\xb4\x03\x68\x63\x04\x68\ -\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x9f\x80\x43\x47\xb1\xe7\x05\xb9\ -\xe6\x70\xe8\x53\xf7\x50\x39\x7e\xa8\x82\x43\x41\x84\xea\x24\xa7\ -\xe6\x40\x6c\xbb\xeb\x3e\x02\x64\xb3\xf1\x04\xb9\x07\xb0\xad\x9e\ -\x82\xee\x84\x52\x9b\x43\x1d\x91\x2d\xf7\x08\x8f\x00\x01\x56\x1d\ -\x3f\x23\xe3\xa9\xfc\x64\x30\xe1\x82\x27\xfe\x24\xfb\x00\x8e\x9b\ -\xe3\x22\x5c\x71\x8f\xf1\x08\xb0\xf7\x0f\x96\x51\x6b\x36\x00\x00\ -\x50\x98\xbb\xf3\xf8\x6d\xcf\x6d\x85\xf1\x99\x77\xc3\x80\x64\x1b\ -\x2f\x88\x8a\xbd\x67\xb7\x16\x50\xbf\x4d\x3d\xe7\xf8\x70\xf0\xa8\ -\x2f\x54\x8e\x25\x73\x53\xbd\xb1\x1d\x28\xb1\x64\x6e\x8a\xd5\xa3\ -\x0d\x10\x83\x8d\xd7\x82\x79\xbf\x16\x9a\x26\x13\xa2\xc4\x93\xb9\ -\xf7\x3e\xdd\x22\x65\x82\x6b\x21\xc8\x6e\xb7\xdd\x22\x0d\x01\xa1\ -\x2a\x38\x54\xdf\xf3\x91\xd3\x55\x2e\xae\x17\x32\x33\x7e\xf7\x9e\ -\x9b\x74\x8c\x08\x89\x42\x5a\x68\xc3\x25\x21\x22\x90\x08\xd1\x66\ -\xb7\x55\x07\xa9\x65\xf2\x4b\xc5\x45\xb2\x3f\xd3\xec\xd2\x77\xcb\ -\xa6\xa9\x78\x2a\x97\x00\xf0\x1a\xbd\xd6\x34\x45\x54\x20\x98\x3f\ -\x77\xd3\x94\x93\x68\x62\x21\x6c\x85\xad\x09\x52\x26\x40\x8e\xd5\ -\x6f\x5d\x77\x5f\xdb\x1c\xb1\x0d\x91\x2d\x11\xae\xd8\x7b\xf6\x4a\ -\x3b\x6d\x73\x06\x83\xe1\x72\xf3\x17\xf4\xb0\xe5\x26\x61\x1e\x11\ -\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x8d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3f\x49\x44\x41\x54\x58\x85\xed\ -\x92\xb1\x4a\x03\x51\x10\x45\xcf\x4d\x02\xa2\x18\x82\xad\xac\xd9\ -\x4d\x5a\xc1\x5f\xb0\xb0\xb4\xb0\xb3\x13\xed\x2c\xfc\x02\x41\xb0\ -\xb2\xf1\x07\x14\x49\x61\xab\x62\x67\x2d\xe8\x1f\xf8\x03\xba\x6f\ -\xb3\x20\xa6\xd1\xca\x42\x93\x37\x56\x09\x62\xb7\x6f\x61\x1b\xf7\ -\x74\x03\x33\x77\x0e\xef\x0d\xd4\xd4\xd4\xfc\x77\x54\xa4\xd9\xcc\ -\xe4\xb2\xdc\x03\x98\x1f\x2f\xf5\x7a\xbd\x8f\xb2\x02\x8d\x82\xfd\ -\x33\x61\x35\x5a\xef\x66\xd6\xac\x54\x40\x92\x17\xda\x9e\xd6\x2e\ -\xcb\xc7\x95\x0a\x00\xc4\x71\x74\x83\xe9\x64\x5a\xa7\xe9\xf0\xa9\ -\x52\x01\x80\x24\x89\x8e\x80\x7b\x00\xc4\x9a\x73\xd9\x59\xa8\x40\ -\xa1\x23\xfc\x4b\xea\x86\xf6\x2b\x68\x3f\x8e\x57\x2e\x2a\x15\x30\ -\xb3\x86\xcb\xf2\xc9\xb4\xf6\xb2\xf5\x7e\xb7\xfb\x58\x24\x23\xe8\ -\x0b\xa6\x48\xf2\x0b\xf3\x73\xed\x59\x98\xe9\xa1\x68\x46\x29\x01\ -\x80\xd1\x68\xf4\x05\x4a\x43\xe7\x4b\x09\x98\x99\x16\xdb\x9d\x01\ -\x58\x02\x7a\xf3\x93\x66\x52\xa9\x40\x9a\xe5\xc7\xc0\x0e\xf0\x29\ -\x26\x9b\xfd\xfe\xb2\x2b\x9a\x11\x7c\x84\x2f\x2e\xdf\x15\x76\x09\ -\x78\xa1\xad\x38\x8e\xee\x42\x72\x82\x5e\xc0\xb9\x7c\x43\xd8\x00\ -\xc0\xa4\x83\xd0\xe5\x41\x02\xce\xb9\x55\xc3\x6e\x81\x96\xc1\x69\ -\xaf\x1b\x9d\x87\x2e\x2f\x2c\x60\x66\x32\x1a\xd7\x40\x47\xe8\x2a\ -\xe9\x46\x87\x65\x96\x03\xb4\x02\x66\x5e\x81\x67\xef\xbf\xf7\x24\ -\xf9\xb2\x02\x35\x35\x35\x35\x3f\x6e\x39\x66\xc8\x1a\xa6\xbc\x56\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x83\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x35\x49\x44\x41\x54\x58\x85\xed\ -\x97\x31\x4e\x02\x51\x14\x45\xcf\x65\x12\x28\x91\x06\xd7\x30\x1b\ -\x18\x22\xb5\x09\xb4\x1a\x3b\x56\x81\xb5\x5a\x48\x2f\xab\xa0\x53\ -\x8c\x95\x31\xb1\x36\x71\x36\xc0\x1e\x68\xc0\x52\x93\x99\x6b\x01\ -\x93\x20\x82\x85\x99\x89\x85\xff\x96\xef\xbf\xfc\x7b\xf2\xfe\x2f\ -\xde\x85\xff\x2e\x6d\x17\x92\x5b\xf7\x54\xf3\x39\x90\x00\x07\x25\ -\xf9\x2c\x81\xd4\xb9\x6e\xd2\x33\x3d\xed\x05\xe8\xdc\x65\x23\xa4\ -\x0b\xc3\xbb\x60\x66\x78\x2b\xc3\x5d\xd0\x34\xc4\x82\x06\xf2\xe8\ -\xf5\x24\xba\xfa\x06\x70\x34\x75\x3f\xc7\x8f\x88\xe7\xc8\x1a\xbc\ -\x9c\x6a\x5e\x86\x79\xa1\xee\xd4\xed\x4c\x9e\x60\x8e\x9d\xab\x5f\ -\x4c\xa2\x56\x34\xe4\x78\x68\x78\xaf\xc2\x1c\xe0\xe5\x54\xf3\xc8\ -\x1a\x00\x1f\x8a\x3c\x2c\xea\xb5\x8d\x9e\x44\x30\xab\xc2\x7c\x13\ -\x02\x98\x61\x92\x5d\x00\x07\x65\xbd\xf9\x4f\xf2\xea\x43\xb6\x76\ -\x01\xfc\x89\x02\x40\x00\x08\x00\x01\x20\x00\x04\x80\x00\x10\x00\ -\x36\x01\x96\x82\x66\xd5\x86\x5a\xad\xfa\x8b\x5d\x00\xa9\x21\xee\ -\x4e\xdd\xae\xca\x7c\x7d\x77\x8c\x48\xbf\x01\x38\xd7\x8d\xa0\x91\ -\xc9\x93\x2a\x20\x3a\x0f\x3e\xcc\xe4\x09\x50\x77\xa6\x71\x51\xff\ -\x1a\x4c\xee\xb3\x6b\xac\x4b\xe0\x83\x55\x30\x59\x96\x61\xbe\x1e\ -\x7b\x0c\xd4\xf7\x06\x93\x42\xc9\xad\x7b\x8a\x3c\x5c\xaf\xce\xad\ -\xed\xf3\x5f\x6a\x81\x48\x9d\x69\xbc\x1d\xcd\x82\x3e\x01\x68\xb1\ -\x6f\x2f\x7c\x41\x27\x3e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x03\xeb\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x9d\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x3f\x6c\x52\x51\x14\xc6\xbf\xf3\x78\xe8\xa4\xd8\xa8\x69\x22\ -\xc6\xa9\x83\x75\x50\x6b\x5d\xdc\x48\x10\x1c\x34\xa4\xa6\x25\x0e\ -\xd6\xd8\x28\xb3\x71\x33\x61\x90\xd4\xc4\x18\xdd\xd4\xc5\x01\x4c\ -\x35\x2e\xa6\xf6\x4f\x88\x0e\x52\x9b\x30\x54\x5d\xaa\x55\x07\x98\ -\xea\x60\x64\xa8\xf1\x1f\x6e\xd8\xf2\x8e\x43\xd1\x3e\x1e\x0f\x5a\ -\x7a\xdf\xe3\xb6\x72\x7f\xdb\x3d\xef\xdc\xc3\x77\xbf\xbc\x77\xef\ -\x4d\xb8\x17\x50\x28\x14\xed\x0c\xad\x25\x29\x10\x48\xe8\xfa\xae\ -\x42\x84\x18\x67\x00\x1c\x05\xe0\x07\xb0\xd5\x55\x65\xcd\x53\x02\ -\x50\x00\x30\xcb\x84\xc7\x4b\x5f\xfd\xe9\x6c\x76\x78\x69\xb5\x4e\ -\xab\x1a\x10\x3e\x1d\x0b\xb1\x86\xdb\x00\xba\x1d\x10\xd9\x42\x28\ -\x47\x06\x5f\xce\x4c\x24\xa7\x1a\x65\x79\x1a\x55\x08\x0d\xc4\xe2\ -\x20\x8c\x00\xd8\xed\xa8\xb6\xd6\xb0\x1b\x84\x73\x5d\xdd\x3d\xbf\ -\xe7\xf3\x73\x2f\xeb\x25\xd5\x35\x20\x34\x10\x8b\x83\x71\xdd\x1d\ -\x6d\x2d\x84\x28\xd8\xd5\xdd\x53\x9a\xcf\xcf\xcd\xd8\x3e\xb6\x0b\ -\x56\x5e\xfb\x4c\x55\x90\xf1\x83\x89\xaf\x6a\x1a\x3d\xf3\xa1\xf8\ -\x69\x74\x74\xb4\xec\x82\xdc\x75\x13\x8d\x46\x3d\x45\xf8\xf6\x19\ -\x06\x9f\x24\xa6\x6b\x20\x74\x98\x9f\x93\x81\xb0\xdd\xe7\x50\x63\ -\x40\x20\x90\xd0\xbd\x3b\x0b\x1f\x60\xfa\xe6\x09\x78\x51\x5e\xc4\ -\xe0\x74\x3a\xb9\xe0\x8a\x7a\x87\x09\x46\x62\x9d\x1e\x2f\x1e\x31\ -\x70\x7c\x25\x4a\xb9\xc5\x6f\x7b\x0e\x59\x27\x46\xcd\xda\x59\xdf\ -\x55\x88\xa0\x7a\xc2\xfb\x0e\x43\x3f\xbb\x59\x06\x0f\x00\xd3\xe9\ -\xe4\x42\x79\x11\x83\x60\xfc\x58\x89\xf2\x81\xca\xd8\xaa\xa8\x31\ -\xa0\xb2\xd4\xad\x74\x03\x27\x32\x13\xf7\xbe\xb8\x21\xd4\x4d\xa6\ -\xd3\xc9\x05\x06\x25\xcc\x31\xeb\xd8\x00\x1b\x03\xb0\xbc\xce\xaf\ -\x24\x68\xf4\xcc\x61\x6d\x2d\x43\xf3\xf0\x53\x73\x9b\x80\xde\x9a\ -\x1c\x9b\x7e\x7e\x73\xc3\x87\xe2\x27\x87\x75\xb5\x0c\xab\x76\x06\ -\xf6\x5a\x73\xec\x0c\xa8\xda\xe1\x6d\xb4\xd9\xbe\x19\x6c\xb4\xd7\ -\xec\x5e\xed\x0c\x68\x2b\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\ -\x6c\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\x6c\x94\x01\xb2\x05\ -\xc8\x46\x19\x20\x5b\x80\x6c\x74\x27\x8a\x84\x06\x2e\x84\xc1\x9e\ -\x5b\x00\x1f\xc4\x1a\xff\x6b\x10\x80\x01\xbc\x07\x19\x57\xa6\x9e\ -\xdc\xcf\xac\x9a\xbd\x0a\xc2\x6f\x40\xb8\xff\xe2\x79\xb0\xf6\x1c\ -\xe0\x43\x70\x7f\xf0\xa8\xfc\xc6\x61\xb0\xf6\x3c\xdc\x7f\xf1\xbc\ -\x68\x31\x21\x03\x02\x7d\x43\x3b\x0c\xd0\x5d\x51\x11\xeb\x85\xa1\ -\xdd\x09\xf4\x0d\xed\x10\xa9\x21\x64\xc0\x16\xdd\x7b\x8c\x80\x6d\ -\x22\x35\xc4\xe0\xed\x5b\x74\xef\x31\x91\x0a\x6d\x3f\x09\x0a\x19\ -\xf0\x7b\x69\xf1\x35\x40\xbf\x9c\x12\xd3\x3c\xf4\x6b\x59\xc3\xfa\ -\x11\x32\x20\x3b\x39\xf2\x93\x60\x5c\x12\xa9\x21\x02\xc1\xb8\x94\ -\x9d\x1c\xf9\x29\x52\x43\xf8\x13\xc8\x8c\xa5\x1e\x80\x8c\x13\x00\ -\xde\x61\x79\x89\x72\x1b\x06\xe8\x3d\xc8\x38\x91\x19\x4b\x3d\x10\ -\x2d\xe6\xc8\x3e\xa0\xb2\x1e\x0b\xaf\xc9\x32\x50\x93\xa0\x6c\x01\ -\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\ -\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x4d\ -\xac\x64\x6e\x44\xa3\xd1\x46\xe7\x89\x37\x34\x36\xda\x4b\xd6\x1c\ -\x3b\x03\x0a\xe6\x46\x11\xbe\x7d\x4e\x8a\x6a\x25\x56\xed\x04\x7c\ -\xb6\xe6\xd8\x19\x30\x6b\x6e\x18\x06\x9f\x74\x58\x57\xcb\x30\xca\ -\x74\xca\xdc\x66\xe0\x8d\x35\xa7\xc6\x00\x26\x3c\x36\xb7\x89\xe9\ -\x5a\x30\x12\xeb\x74\x5e\x9e\xbb\x04\x23\xb1\x4e\x02\x0f\x9b\x63\ -\xd6\xb1\x01\x36\x06\x2c\x7d\xf5\xa7\x01\xe4\xff\x05\x08\x1d\x1e\ -\x2f\x1e\x6d\x26\x13\xfe\x1e\x96\xae\x3e\x31\x4e\xb9\xca\xd8\xaa\ -\x68\xee\xb8\x3c\x28\xa1\x79\xf8\xe9\x86\x3e\x2e\x5f\xa6\x53\x04\ -\x1e\x5e\xf7\x71\xf9\xbf\xfc\x37\x17\x26\x00\x10\x73\x3c\x33\x9e\ -\xba\x61\xf7\xac\xee\x12\xf7\x31\xf7\x76\xa6\xab\xbb\xa7\x04\xa2\ -\xa0\x7b\xd2\x5c\x87\x19\x88\x4f\x8d\xa7\x6e\xd6\x4b\x68\xb8\xc6\ -\xcf\xe7\xe7\x66\xba\xf6\x1f\x79\x05\xa2\x5e\x6c\xba\x7b\x43\x94\ -\x23\x03\x83\x53\xe3\xc9\x87\x0d\xb3\xd6\x52\xca\x7c\x6d\x8e\x80\ -\xde\xca\xa9\xeb\x0d\x77\x6d\x8e\x80\xcf\x0c\xbc\x69\xe6\xda\x9c\ -\x42\xa1\x68\x6f\xfe\x00\x06\x14\x1b\x10\x41\x9d\x58\x08\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\x15\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xc7\x49\x44\x41\x54\x58\x85\xe5\ -\x97\x51\x48\x5d\x65\x1c\xc0\x7f\xff\xef\xea\x5d\xf3\xc1\x6d\x21\ -\xcc\x4a\xd9\x26\x2b\xb6\xa8\x1e\x5a\x0c\x0a\x56\x2b\xf5\x9a\x0c\ -\xa7\x33\x0e\x11\x42\x36\x6d\x16\x44\x2f\x41\xe0\xe8\xe1\x20\x45\ -\x13\x7a\x2a\xc6\x62\x4e\x2d\x22\x9f\xae\x57\x4b\x6b\xb6\x7b\x75\ -\x5c\x5f\x16\xc3\x42\x46\x2b\x84\xc8\x46\x5d\xb5\x88\x0d\x8d\x5a\ -\xea\xbd\xf7\xfb\xf7\x70\xaf\x76\xbd\xd7\x39\x2f\x5e\x7b\xd9\xff\ -\xe9\x9c\xef\xfc\xbf\xff\xef\xf7\x1d\xce\x39\xdf\xff\xc0\x9d\x1e\ -\x92\x4d\xb2\xaf\xf6\x78\xa9\xf5\xe4\xd5\x89\xb1\x15\xa8\x94\x02\ -\x25\x80\x11\x98\x52\x88\xa0\x3a\x8a\xe4\xf5\x87\x02\x67\x7f\xcc\ -\xa9\x40\x95\xd3\x7c\x30\x6e\x4d\xbb\xa0\x4f\xaf\xb3\xee\x18\xa2\ -\x27\x43\xbd\x5d\x23\x1b\x12\xa8\x70\x5a\xb6\x89\xb5\x1f\x02\x2f\ -\x24\x87\x66\x14\x06\x0d\x3a\x14\x47\x26\xbd\x26\x3e\xb3\x18\x8b\ -\xdb\x3c\xb3\xa5\x38\xae\x76\xb7\x88\xf8\x80\x5a\x60\x57\x32\xff\ -\xbc\x8d\xd2\x34\x32\xd0\xf9\x7b\xd6\x02\x55\x4e\xf3\x5e\x6b\x65\ -\x00\xd8\x9f\x00\x8b\x1b\xbb\x7e\xef\x47\xe1\x70\x5b\x6c\x2d\x69\ -\xd7\x75\xcd\xa5\xab\x53\xcf\x03\xef\x00\x65\xc0\x2f\xc6\xda\xa3\ -\x17\xfa\xbb\xaf\xac\x5b\xa0\xbc\xfe\x78\x99\xc1\x73\x19\xa1\x48\ -\xe0\x73\xcf\x5d\xff\xbc\x38\xd4\xd3\xf3\xe7\x5a\xe0\xf4\xa8\xae\ -\x7e\x7d\x4b\xb4\x60\xfe\x8c\xa0\x4d\xc0\xdf\x8a\x1e\x1a\x0e\x74\ -\x8d\xdf\x56\xa0\xba\xa1\xa1\x30\x36\x5f\xf0\x35\xe8\x83\xa0\xef\ -\x3f\xf1\x50\xc9\x1b\x6d\x6d\x6d\x36\x1b\x78\x6a\x7d\x5f\x7d\x73\ -\xab\x8a\xbc\x0b\x44\x8c\x9a\x83\x17\xfa\x3a\x66\x52\x13\x4c\xfa\ -\x8c\xd8\x7c\xc1\xe9\x04\x9c\xc1\x0d\xc2\x01\x34\xd8\xd7\xd5\x8e\ -\xd2\x09\x94\x58\x63\x3f\x25\x6d\xd1\x2b\x4e\x2a\x9f\x6b\x7a\x0c\ -\xcc\x18\xf0\x87\x1a\x73\xff\xb0\xbf\x63\x6e\x03\xf0\xe5\x70\x1c\ -\xc7\x3b\x6b\xb7\x5d\x01\xf6\x01\x47\x42\x81\xce\xf3\x4b\xd7\x56\ -\xdc\x01\xc1\x9c\x02\x50\x95\xb7\x73\x05\x07\xf0\xfb\xfd\x8b\x2a\ -\xbc\x95\x3c\x6d\x27\x65\xe1\xcb\x02\x55\xf5\x2d\xf7\x28\x94\x03\ -\x37\x76\x78\x66\xcf\xe6\x0a\xbe\x14\xc3\xbd\x9d\xfd\xc0\x04\xf0\ -\x70\xd5\xb1\xa6\x47\x32\x04\x14\x5b\x93\x30\x93\x2f\xfd\x7e\xff\ -\x62\xae\x05\x00\x45\x64\x00\x40\x3d\xe6\x58\xa6\x80\x70\x18\x40\ -\xd5\x7e\xb5\x09\x70\x00\x24\xae\x17\x00\xac\xf2\x4c\x86\x00\xaa\ -\xa5\x09\x3b\xfd\x79\xb3\x04\x8c\xe6\x4d\x02\x48\x62\x0f\x49\x13\ -\x90\xc4\x60\x7e\xd4\x3b\x93\x31\x33\x47\x21\x0b\xf9\x4b\xb5\xef\ -\x23\xf9\x20\x66\x7c\x07\xfe\xaf\x70\x5d\x37\x5d\x40\xa6\x00\x62\ -\x26\x56\xbc\x59\xd0\x85\xad\x37\x93\xb5\x75\x7a\xe9\x03\x97\xfa\ -\x0c\xfc\x0a\x20\xc2\x9e\xcd\x12\xc8\x47\xcb\x12\x2c\x22\x4b\x63\ -\xff\x09\x18\xc2\xc9\xa3\xaa\xcd\x12\x50\x31\x3e\x00\xc4\x5c\xcc\ -\x14\x58\xd4\xc1\xa4\xdd\x91\x03\x2d\x2d\xf9\x9b\xc0\x17\x45\x8e\ -\x26\xa9\xfd\x19\x02\xa1\x81\xee\x69\x84\x8b\x08\x45\x3b\xae\xdb\ -\x97\x73\x4d\xaf\xac\x3f\x51\x93\xdc\xe4\xbe\x0f\xf9\xcf\x2d\xf7\ -\x06\x2b\xde\x02\x6b\xa5\x15\x40\x04\xb7\xba\xa1\xa1\x30\x57\x70\ -\xc7\x71\xbc\x08\xa7\x00\x04\x3d\x09\xe8\xaa\x02\x23\x7d\xe7\xc6\ -\x54\xe9\x41\xd9\x19\x9f\xdf\xfa\x89\xeb\xba\xb9\x78\x4d\x65\x36\ -\xbe\xfd\x83\xe4\xea\xc3\xc1\x40\xd7\x17\xa9\x17\x33\x01\x1e\xf3\ -\x1a\x30\xa1\x50\x7b\xe9\x6a\xe4\xbd\x0d\x4a\x48\x65\x7d\xf3\x9b\ -\x88\xbe\x82\x30\x4d\xd4\x36\x90\xb2\x7a\xb8\x45\x4b\x96\xec\x07\ -\x2f\x03\x77\x03\x7d\x51\xe3\x6d\x0c\xfb\xcf\xfc\x95\x0d\xd9\x71\ -\x1c\xef\x9c\x2d\x3c\xad\xc8\x09\xe0\x26\xd8\xa7\x42\x81\xee\x6f\ -\xd2\xf3\x3c\xab\x4d\xfe\xe9\x87\xf1\x1b\x7b\xf6\x1d\xf8\x0c\xc1\ -\x27\x70\xc8\xa3\xf1\xc6\xbd\xfb\x1f\x9d\x2b\xdd\x59\xf3\xdd\xb5\ -\x6b\xa3\x6b\x76\x48\xae\xeb\x9a\xfc\xa2\x07\x9c\x05\xf5\xf6\x82\ -\x54\x92\x68\xc5\x7c\xc1\xbe\xce\x6f\x57\xcb\x5f\xb3\x2d\x3f\x5c\ -\xf7\xd2\xf6\x7c\x93\xd7\x81\xe0\x24\x87\x22\x02\x83\xa0\x43\x82\ -\x99\xc4\xd8\x99\x85\x68\xdc\x7a\x3d\xde\x62\x8b\xee\x02\xaa\x04\ -\xad\x25\xd1\x0d\x03\x12\x8c\x9a\x68\x63\xd8\xff\xf1\x6f\xb7\x62\ -\xac\xeb\xc7\xa4\xdc\x69\x7a\xdc\x58\xd3\x0e\x3c\xb9\x9e\x7c\x60\ -\x1c\xb1\xad\xa1\xde\xee\xe0\xed\x12\xb3\xfa\x35\x7b\xb6\xee\xd5\ -\xdd\x31\x13\xab\x13\x23\x15\xa2\x5a\xaa\x89\x6d\xd5\x03\x44\x80\ -\x88\xa8\x8e\x22\x9e\xfe\x60\xa0\x63\x22\x9b\xba\x77\x76\xfc\x0b\ -\xeb\x32\x64\xd4\x54\xc2\x43\x07\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x03\x64\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x16\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbf\x4f\x53\x51\x14\xc7\xbf\xdf\x17\x08\x90\x4e\xf2\x23\x02\ -\xee\x2e\x58\x17\x57\x4d\x4c\xac\x75\x73\xa8\x05\x23\x49\xd1\xa4\ -\xa5\x44\x13\xd0\x11\xfe\x02\x9d\xc1\x44\xac\x38\x68\x13\x4d\xa0\ -\xb2\x83\x6c\xb8\xba\x50\x98\x9c\x29\x92\x14\xb6\x0a\x44\xf2\x8e\ -\x03\x7d\x4d\x73\xfb\x6a\x11\x69\x4f\x1b\xee\x67\xba\x3d\xf7\xbe\ -\xf6\x7b\xbe\xbd\xf7\xdd\xe5\x1c\xc0\x62\xb1\x5c\x64\x78\x9a\x45\ -\xe1\x58\x2c\xe0\x1e\x74\x8c\x50\x10\x05\x70\x0d\xc0\x20\x80\xb6\ -\xba\x2a\xfb\x77\x8e\x01\xe4\x00\x6c\x0a\x91\x71\xba\x8e\x16\x57\ -\xd3\xe9\x42\xad\x87\x6a\x19\xc0\xf0\x83\xf8\x98\x80\x2f\x01\x0c\ -\x9c\x87\xca\x06\xb2\x23\xc4\xf4\x5a\x66\x21\x0d\x40\xaa\x2d\xaa\ -\x6a\xc0\x8d\x64\xb2\xbd\x3b\x2f\x73\xa0\x4c\xd4\x45\x5e\xa3\x10\ -\xbe\xdd\xef\xe5\xe4\xf7\x54\xea\xb7\xdf\x74\xb5\x6d\xcc\x4b\x7b\ -\xee\x6b\x10\x49\x23\x9e\x25\xf0\x4d\x20\x3f\x29\x8e\x7b\xbe\x4a\ -\xff\x0f\xa1\xeb\x10\xec\x17\xe0\x26\x80\x60\x69\x82\x32\xd1\x9d\ -\x07\x00\x3c\x85\xcf\x4e\xf0\xdd\x01\xa1\x68\x62\x8c\x82\x0f\x65\ -\xa1\x3d\x11\x99\x5a\x5b\x7e\xff\xd9\xef\x4b\x9a\x0c\x86\x22\xf1\ -\x47\x24\x67\x01\xf4\x78\x41\x21\x1e\xaf\x65\x16\x3e\x56\x2c\x36\ -\x03\xe1\x58\x2c\x20\xbf\x3a\x7e\xc0\x3b\xf3\x82\xbc\x03\xe7\xfa\ -\xca\x72\x6a\xa7\x8e\xa2\xcf\x9d\x7b\x91\xe4\x80\x0b\x77\x03\x44\ -\x2f\x00\x80\xc8\xb1\xeb\xe8\xaa\xf9\x62\x74\xcc\x07\xdd\x83\x8e\ -\x11\x94\xbd\xf0\x04\xf2\xbc\xd5\x92\x07\x80\x95\xe5\xd4\x0e\x1d\ -\xbe\x28\x05\x04\x83\x52\xe8\x1c\x36\xd7\x55\x18\x50\xbc\xea\x3c\ -\xb2\xc5\x6d\xdf\x92\xac\x66\xde\x7d\x02\x90\x2d\x05\x28\xb5\x0d\ -\xc0\xc9\x3d\x0f\x00\x10\x91\x75\x34\xff\x99\xff\x1b\x52\xcc\xc1\ -\x63\xc8\x5c\xe0\x67\xc0\xa0\x37\x20\xb1\x5b\x0f\x55\x8d\xc4\xc8\ -\xe1\x8a\x39\xef\x67\x40\xe9\x6a\x6c\xb6\xab\xee\x2c\x18\x39\x54\ -\x5c\xfb\x7e\x06\x5c\x28\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\ -\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\ -\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\ -\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\ -\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\ -\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xf1\ -\x33\xe0\xd8\x1b\x08\xdd\x96\x37\xc8\xc8\xe1\xd8\x9c\xf7\x4b\x30\ -\x57\x7a\x58\x70\xb9\x1e\xa2\x1a\x89\x91\xc3\xb6\x39\xef\x67\xc0\ -\xa6\x37\x20\x79\x0b\xa7\xec\x29\x68\x52\x58\xcc\xc1\x63\xcb\x5c\ -\x50\x61\x80\x10\x99\xb2\x8f\xc1\x70\x24\x31\x52\x0f\x65\x8d\x20\ -\x1c\x1d\x7f\x88\xf2\xca\x71\xe1\x92\xb9\xa6\xc2\x00\xa7\xeb\x68\ -\x11\x40\xa9\x36\x58\x88\xb9\x3b\xf7\x13\x2d\x77\x14\x6e\x0f\x3f\ -\xe9\x17\x91\xd9\x52\x80\xc8\x31\x70\x58\xdb\x80\xd5\x74\xba\x20\ -\xc4\x74\x59\xa8\xcf\x69\x47\x36\x14\x89\x8f\xa2\x35\x8e\x03\x43\ -\x91\xf8\x68\xbb\xdb\xb6\x01\xa0\xcf\x0b\x0a\x30\xe3\xd7\x42\x53\ -\x2d\x21\xde\x8d\x8c\xbf\xf1\xe9\x16\xc9\x8a\xc8\x3a\x89\xdd\x66\ -\xab\x22\x15\xba\x8e\x08\x2e\x17\xcf\x7c\xd0\x98\x9e\xff\xfa\x65\ -\xe1\x19\x7c\xea\x9e\xab\x75\x8c\xc8\x7e\x2f\x27\xbb\xf3\x80\x61\ -\x42\x90\x64\xf0\xe4\x07\x9b\xad\x86\x9a\xa0\xff\xdf\x39\xbf\xdf\ -\xe3\x4c\xa1\x4a\xd1\x77\xcd\xa6\xa9\x50\x34\x11\xa3\xe0\x15\x5a\ -\xad\x69\x8a\xc8\x09\x30\x73\xe6\xa6\xa9\x72\xc2\xb1\x58\x40\x0a\ -\x9d\xc3\xc5\x7a\xfb\x21\x9c\x54\x5d\x37\x63\xdb\xdc\x36\x80\x2d\ -\x08\x97\x18\x38\x5c\x3a\x4d\xdb\x9c\xc5\x62\xb9\xd8\xfc\x01\xdf\ -\x73\xe1\xb5\xcf\x33\xa6\xd1\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\xc8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\xb1\x6d\xc2\x60\x14\x85\xd1\xef\x67\x88\x88\x81\x32\x01\x62\ -\x83\xd0\x78\x22\x9a\xac\x90\x36\x0d\x0b\x59\x2c\xe1\xb4\x91\x5d\ -\x83\x25\x38\xa7\xbc\x7a\xc5\x7d\xb7\x00\x00\x00\x00\x00\x00\x80\ -\x77\x30\xd6\xc1\xe7\xf9\x72\x1a\x4b\xd7\xea\x63\x87\x3e\x0f\x33\ -\x6a\x5e\xea\xeb\xf6\xf3\xfd\xfb\x3f\x3f\x6c\x0e\x5f\xf0\xf9\xaa\ -\xa5\x8e\xd5\x75\x9d\x6f\x06\x78\x37\x9b\x01\x96\xd1\x54\xdd\x77\ -\xe8\xf2\x50\xa3\xe6\x6a\xda\xbb\x07\x00\x00\x00\x00\x00\x00\x00\ -\xf0\x7c\x7f\x0b\xd1\x0f\x08\x20\x9f\x5b\xc7\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x04\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ -\xd9\x41\x0d\xc3\x40\x10\xc5\xd0\x69\x14\x4e\xe1\x51\xa0\xe1\x11\ -\x52\x9b\xc2\x78\x95\xd6\x26\x30\x96\xf5\x6f\x33\x03\xb9\xee\xf5\ -\x5e\xf7\x7a\xa5\xc3\x21\x8f\xff\x03\x05\xd0\x02\x9a\x02\x68\x01\ -\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ -\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ -\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x6c\ -\x1f\xe0\x23\x8f\xeb\xd7\xf8\x4c\x0b\x98\x53\x0b\xcc\xcc\x3c\xdf\ -\x83\x2d\x71\xfb\x05\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ -\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ -\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ -\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\xb3\x7d\x80\x1f\x17\ -\x67\x0a\x44\xf8\xee\xeb\x4c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x02\x1d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcf\x49\x44\x41\x54\x58\x85\xed\ -\xd6\x3d\x8b\x53\x41\x18\xc5\xf1\xff\x99\x44\xf1\x05\x5f\x3a\x41\ -\x1b\x11\x2b\x0b\xb5\x31\x61\x11\x4b\x49\xb3\xb2\x59\x65\xd7\x46\ -\xd0\xd6\x42\xf6\x13\x88\x2c\x7e\x01\x51\xb0\x16\xb1\x90\x15\xcd\ -\x2e\x04\x71\xb1\x14\x89\x49\xa5\x16\x56\x16\x6b\x23\xd8\x28\x8b\ -\xf8\x82\x26\x73\x2c\xe6\x46\x2c\x73\x93\x30\x16\xfa\x14\x97\x5b\ -\xcc\xcc\xf9\xcd\xdc\x67\xe0\xc2\xbf\x5e\x1a\x65\x50\xad\x15\x3f\ -\xc9\x28\xf4\x75\xa8\xb3\xa8\x8f\xd3\x04\x84\x51\x06\xc9\xec\x05\ -\xf6\xc4\xaa\xdb\x47\xd7\xbd\x33\x3b\xe0\x8f\x9a\xd9\xfe\xd5\x0f\ -\x8f\xac\x78\xeb\x5f\x01\x38\x3d\x1a\xbb\xb6\xc4\xbb\x0b\x2b\xae\ -\x64\x07\x60\x22\xc2\x58\xe7\xdf\x55\xe2\x2d\xec\x91\x7a\x68\x6a\ -\x00\x09\x63\x6c\x83\xa4\xcb\xf5\xd5\xb8\x9c\x15\x50\x94\x81\x98\ -\xde\x74\xb5\xde\xf2\x52\x6e\x00\x12\xf6\x6f\x84\x6f\xd4\x5b\xbe\ -\x90\x15\x00\x20\xb0\xd1\x10\x71\xa7\xf6\xc8\xb3\x59\x01\x09\x61\ -\x1b\x1b\xa8\x08\x3f\xa8\xad\xfa\x54\x56\x40\x42\x28\x92\x10\xdb\ -\x14\xdd\x3e\xd1\xf2\xf1\xac\x80\x82\x11\x9d\x9a\x73\x77\xb0\x9f\ -\xcc\xac\xf9\x70\x66\x00\x28\x35\xa5\x81\x7d\x71\xe0\xa7\x27\xd7\ -\xbc\x3f\x2b\xa0\x50\xc4\xf4\x35\x38\xd8\x1f\xf8\x71\x7e\x40\x42\ -\x0c\xeb\x58\x7e\x80\x09\x85\x60\xa3\x5a\xd1\x81\xac\x00\x8b\x40\ -\x4a\xff\x10\x2a\x3a\xfd\x7c\x4e\xef\x33\x02\x1c\x64\x04\x6c\x1a\ -\x35\x3a\x73\x7a\x3b\xea\xcc\xea\xc4\xd1\x38\x08\x09\xf8\xee\xa0\ -\x33\xbd\xa6\x5e\x95\x99\x3f\xd1\x09\xd8\x52\x11\x3e\x30\x5a\xe8\ -\x35\xf5\xac\xec\x1a\x63\x9f\x80\x8d\x24\xa7\x0d\x48\x97\x7a\xf3\ -\x6a\x8f\xb3\xce\xb8\x27\x20\xa5\xa6\x43\x68\xa9\x3b\xaf\x7b\x63\ -\xae\x53\x1e\x60\x23\x18\xee\xdc\xd7\x5f\x9c\xd5\xcd\x71\xc3\x4b\ -\x03\x9c\x7e\x05\xd2\x5d\x97\x6f\x77\x9b\xe1\xda\x24\xe1\xa5\x01\ -\xc2\x21\xf5\x9c\xef\x77\x5f\x86\x2b\x48\xce\x0a\x48\x3b\x67\xfd\ -\x73\x3f\x5c\x64\xb9\xf8\x19\x99\xb0\xca\xde\x82\xce\xb7\x1d\x3a\ -\xf7\xa6\xa1\x1f\xd3\x08\x2f\x03\xd8\x44\x56\xf8\x19\x66\x5f\x37\ -\xf4\x65\x5a\xe1\xff\x0b\xe0\x17\x0f\x9e\xa4\x40\x97\xf1\x9c\xea\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xf8\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xaa\x49\x44\x41\x54\x78\x9c\xed\ -\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xa6\x7a\x62\x43\x0c\x1b\x9e\ -\xf0\x54\x56\x1c\x7c\x86\x64\xbb\xe9\xf2\x32\x36\xc4\x3c\xae\xf5\ -\xdd\xcf\x7d\x0e\xe1\xb1\x8b\xd3\x3f\x51\x00\x2d\xa0\x29\x80\x16\ -\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\ -\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ -\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ -\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\ -\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\ -\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\ -\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\ -\x80\xe6\x05\x58\xe1\x04\x80\x5c\x86\x43\xbc\x00\x00\x00\x00\x49\ -\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x4d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xff\x49\x44\x41\x54\x78\x9c\xed\ -\xd6\xa1\x4a\x04\x51\x14\xc6\xf1\xef\xcc\x8c\x08\x06\xd3\xda\x7d\ -\x01\x41\x50\xb0\xda\x5c\xb6\x6c\xf1\x39\x2c\x3e\x80\xec\x03\xec\ -\x4b\xd8\x2d\xc2\x8a\xb6\x29\x86\x8d\xbe\x81\x69\x41\x6c\x06\x19\ -\x41\xef\x31\x58\xe4\x5e\xb5\xcd\x59\x70\xfe\xbf\x78\xce\x84\xef\ -\x7e\xe1\xce\x95\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x41\xb0\ -\x3f\xb7\xee\x76\xdc\xaa\x0e\xca\xd2\x8b\xb6\x55\xd2\xcc\xd2\x6f\ -\xfb\x1f\x0b\x38\xb8\xf6\x51\xf3\x9e\xe6\x92\x9d\x4a\xda\xea\x2d\ -\x5d\x8c\x4e\xae\x45\xd3\xd8\xd9\xfd\xd4\x56\xf9\xb2\x28\xe0\xe8\ -\xc6\xb7\xd5\xf9\x83\xa4\xdd\x88\x74\x51\x5c\x7a\xb6\xda\xf6\x96\ -\x53\x7b\xfa\x3e\xaf\x8a\x2f\xdf\xd2\x4c\xff\xec\xf0\x92\x64\xd2\ -\x8e\x7f\xa4\x79\x3e\x2f\x0b\x70\x3b\x09\x49\xb4\x06\x26\x1b\xe7\ -\xb3\xb2\x80\x81\x29\x0b\x30\xbf\x5b\x43\x8e\x10\x2e\xbf\xcd\x67\ -\x65\x01\x9b\xd5\x85\xa4\xc7\x80\x3c\xa1\xbe\x2e\xc1\xea\x3c\x9f\ -\x17\x05\x2c\x27\xf6\xe2\xb2\x43\xc9\x2f\x25\xbd\x86\xa4\xeb\x57\ -\x27\xd7\xd5\x46\x6d\xfb\xf9\x1f\x40\xe2\x21\x04\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x0c\xc5\x27\x17\xb6\x3b\xc1\x0d\x7c\x50\x9f\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x22\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ -\xd6\x31\x6b\x14\x41\x18\xc6\xf1\xff\x33\x17\x8d\x20\xd1\x74\x1e\ -\xde\xed\xad\x1c\x96\x82\xb6\x16\x96\x92\x26\x56\x22\x36\x82\xb6\ -\x16\x92\x4f\x20\x22\x7e\x01\x51\xb0\x16\xb1\x10\xc4\xee\x10\xc5\ -\xd2\xc2\x5a\xb8\x52\x48\x76\x37\x91\xb3\x51\x03\x11\x8c\x72\xf3\ -\x58\xec\x5d\x5a\x6f\xef\x96\x4d\xa1\xd3\xec\x2e\xcc\x3b\xcf\x6f\ -\xdf\x9d\x81\x85\x7f\x7d\x68\x96\x49\x5b\x59\xfe\x0d\xa4\x56\xa0\ -\x9f\x24\xc9\xd7\x3a\x01\x61\xb6\x69\x5a\x05\x4e\x8e\x23\x83\xd1\ -\x68\x74\xfc\x10\x00\x07\xe3\xe2\xfe\xfe\xef\x57\xc3\xe1\xf0\xe8\ -\xe1\x00\x6c\x0c\x6b\x2b\x2b\xab\xcf\x6c\xb7\x9a\x07\xa0\x28\x61\ -\xe3\xeb\x59\xb6\xf3\xd8\xf6\x4c\x7b\xa8\x3e\x80\x70\x34\x2e\xef\ -\x7d\x3b\x2b\x76\xee\x37\x0b\x00\x04\x06\x47\xdb\x60\xdf\xcd\xb2\ -\x62\xa3\x51\xc0\x84\x61\x29\x44\x00\xc3\xc3\x2c\x2b\x6e\x34\x0c\ -\x00\xb0\x91\xa6\x88\xa7\x59\xb6\xbd\xde\x30\x00\xb0\x4d\xb9\x27\ -\x5a\xc6\x2f\xf3\x3c\xbf\xd4\x2c\x00\x40\x44\xb0\x81\x63\xd1\x1a\ -\x6c\x6e\x6e\x5f\x68\x16\x50\x2a\x22\x60\xe0\x84\x02\x6f\x8a\xa2\ -\x38\xdb\x30\x00\x80\x38\x39\x21\xa7\xc6\x51\xef\xf2\x3c\x3f\xdd\ -\x34\x00\x43\x2c\x1b\xe1\x33\x11\xbd\x6e\x1c\x30\x55\x4c\xae\xe7\ -\x1b\x07\x08\x02\x12\xa0\xad\x20\x77\x66\xa9\x59\xaa\x31\x3f\x18\ -\x04\xfa\xd2\x0a\xbe\x9c\x24\xbd\xcf\x33\x15\xd5\x93\xed\x40\xf9\ -\x73\xb3\x1b\xc7\xac\x25\x49\xf2\x69\xd6\xca\x85\x01\x86\x40\xd9\ -\xf7\x9f\x41\xbe\xd2\xef\x77\x3f\x56\xa9\x5f\x10\x20\xa9\x7c\xf3\ -\xb1\xd0\xb5\x5e\xaf\xf7\xbe\xea\x0a\x8b\x00\x34\x69\x3d\x82\x5b\ -\x69\xda\x1d\xcc\xb3\xc8\xbc\x00\xd9\x07\xe1\x1b\x69\x9a\x3c\x9f\ -\x73\x9d\xea\xa7\xc0\xe5\x07\x0f\x65\xf3\xf5\x20\xed\x75\x1f\xcd\ -\x1b\x0e\x15\x3b\x60\x97\xe1\xe5\x83\x9e\xa4\x49\xe7\xde\x22\xe1\ -\x95\x01\x92\xa7\xe1\x2f\xd2\xb4\x73\x47\x92\xff\x52\x52\x2f\x00\ -\x84\xe0\xed\xde\xde\xf7\x9b\x9a\xfc\x8c\x2c\x3a\xaa\xee\x81\x0f\ -\xcb\xcb\x47\xae\xa6\xe9\xb9\x5f\x75\x84\x57\x00\x78\xd7\x46\x4b\ -\x2d\xad\xb7\xdb\xed\x1f\x75\x85\xff\x1f\x00\x7f\x00\x61\x3f\xa0\ -\x35\x7d\x81\xed\xd8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x04\xe7\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x99\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xbd\x6f\x1c\x45\x18\xc6\x9f\x77\xf7\x1c\xa4\x74\xa9\x4c\x74\ -\x1f\x63\x1f\x4e\x91\x28\x52\x90\x92\x2e\x6d\xa0\x09\x50\x60\xa4\ -\x80\x44\xa2\xfc\x03\x11\x69\x40\xd8\x12\x4e\xb0\x14\x02\xa1\x81\ -\xbf\x00\x24\x2c\x50\x44\x42\x11\x39\x8d\xa1\x4a\x5a\xa7\x41\x60\ -\x37\xe1\xd8\x8f\xbb\x22\x14\x50\x22\x87\xdb\x7d\x28\xce\x23\xf6\ -\x6e\xf7\xbc\x7b\xde\x4f\xe3\xfb\x49\x2e\x76\xe6\xbd\x9b\x77\x1f\ -\x3f\xef\xec\xec\x69\x06\x98\x32\x65\xca\x61\x46\x92\x04\x91\xac\ -\xd9\x76\xf7\x0d\x0a\x2f\x09\xe4\x1c\x80\x3a\x80\x17\xf2\x4d\x6d\ -\x62\x76\x00\xf4\x08\x6e\x0a\xe5\xae\x52\x8d\x07\x22\xd2\x8f\xfb\ -\x50\xac\x00\xb6\x6d\xbf\x42\xc8\x97\x80\x9c\xcc\x24\xcd\xe2\xd8\ -\x12\xf8\xd7\x95\x52\x3f\xee\x15\x64\x8c\xeb\x20\x29\x96\xd3\x5d\ -\x26\x8c\x8d\x03\x78\xf3\x00\x70\x8a\x30\x36\x7e\xb7\xbb\x4b\x24\ -\xc7\xfe\xa3\xc7\x0a\x60\xbb\xbd\x25\x90\xb7\xf2\xc9\xad\x38\x04\ -\xfc\xc4\x72\x7a\x1f\x8e\xef\x8f\x60\x60\x7b\x63\x63\xa4\xf9\x2f\ -\x10\x2b\x80\xf7\x50\x29\xe5\x88\x88\x97\x69\xa6\x29\x21\x69\xda\ -\xb6\xdd\x02\xcc\x8b\x10\xac\x02\x38\x16\xec\x17\xf8\xaf\x46\x95\ -\x43\x48\x00\x92\x35\xdb\x71\x7f\x1e\xb6\x3d\x7f\xf2\xbd\xfe\xbb\ -\xed\x76\xfb\x59\x0e\xb9\x67\x4e\xa7\xd3\x99\x35\xcc\xda\x1a\x20\ -\x17\x02\xcd\x5b\xaa\xd5\x38\x33\x3a\x31\x86\x04\xb0\x2c\xf7\x4d\ -\x08\xee\x07\x9a\xfe\xec\xff\x33\x73\x72\x61\xe1\xc5\x3f\xf2\x4a\ -\x38\x0f\x06\x22\xcc\x6c\x23\xe8\x04\x62\x71\x6e\xae\xf9\x43\x30\ -\x2e\x34\x07\x50\x78\x69\xb8\x01\x37\x0e\xda\xcd\x03\x40\xbb\xdd\ -\x7e\x26\xc0\x8d\x60\x5b\xe8\xde\x10\x21\xc0\xee\x73\x3e\x80\xf7\ -\x30\xeb\xe4\x8a\x82\xf4\xd6\x83\xd7\x02\x39\x3b\x1a\x13\xf5\x14\ -\xa8\x07\x2f\x94\x52\x4e\xc6\x79\x15\x46\x44\xee\x8d\xd1\x98\x28\ -\x01\x86\x56\x78\x55\x9b\xed\x27\x21\x22\xf7\xd0\xea\x75\xec\x3a\ -\xe0\xb0\x50\x2b\x3b\x81\x24\xb8\xae\xbb\xe0\xf9\x58\x01\xb0\x08\ -\x00\x04\xef\x99\x82\xd5\x56\xab\xf5\x5b\xda\xef\xae\xbc\x03\x5c\ -\xd7\x3d\xe1\xf9\x78\x04\xe0\x32\x80\xa3\x00\x8e\x0a\xe4\x8a\x4f\ -\x79\xec\xba\xee\x42\xda\xef\xaf\xb4\x00\x24\x6b\x9e\x8f\xef\x00\ -\x1c\x8f\xe8\x3e\xde\xf7\xf9\x51\xda\x31\x2a\x2d\x80\xed\xf6\x3e\ -\x00\x10\x7a\x74\x69\x04\xf2\x56\xda\x31\x2a\x2b\x80\xe3\x38\xa7\ -\x41\xde\xcc\x7b\x9c\x4a\x0a\x40\xb2\xe6\x53\xbe\x06\x30\xb3\x57\ -\x9c\x80\xdf\xa7\x1d\xab\x92\x02\xc4\x59\x7f\x97\xe7\x00\xef\xa4\ -\x1d\xab\x72\x02\x24\xb5\x3e\x21\x37\x95\x52\x5b\x69\xc7\xab\x94\ -\x00\x49\xad\x0f\x60\x73\xae\x55\xff\x3c\x8b\x31\x2b\x25\x40\x52\ -\xeb\x0b\xfc\xab\x49\x7e\xf0\x4c\x42\x65\x04\x98\xd0\xfa\xbf\x66\ -\x35\x6e\x25\x04\x28\xc3\xfa\x9a\x4c\xde\x05\x1c\xc7\x79\xc9\x23\ -\x56\x02\x0b\x93\xfb\xa6\x81\xd5\x66\xb3\xf9\x34\xc9\xe7\xcb\xb0\ -\xbe\x26\xb5\x03\x5c\xd7\x5d\xf0\x29\x8f\x05\x72\x05\xbb\x6b\x75\ -\x00\x97\x3d\x1f\x8f\x5c\xd7\x3d\x11\xf7\xf9\xb2\xac\xaf\x49\x2d\ -\xc0\xee\x5b\x5a\xe4\x5a\xdd\xf3\xf1\x2d\xc9\xb1\x2e\x2b\xd3\xfa\ -\x9a\x2c\xe6\x80\xc5\x3d\xfa\xce\x59\x4e\xef\xfd\x71\x9d\x65\x5a\ -\x5f\x93\xfb\x24\x28\xe0\x4d\xc7\x71\x4e\x8f\xb6\x97\x6d\x7d\x4d\ -\x6a\x01\x08\xde\x8b\x09\x39\xe2\x53\xbe\x0a\x96\x42\x15\xac\xaf\ -\x49\x2d\x80\x01\x7e\x06\xe0\x79\x4c\xd8\x50\x29\x54\xc1\xfa\x9a\ -\xd4\x02\x28\xa5\xb6\x20\xf2\x71\x5c\x9c\x2e\x85\xaa\x58\x5f\x93\ -\xc9\x1c\xa0\x9a\xf5\x3b\x00\x9e\xc4\x84\x1d\xf1\x29\xdf\xf8\x90\ -\x35\x54\xc0\xfa\x9a\x4c\x04\x10\x91\xbe\x21\xbc\x8a\xf8\x52\x78\ -\x19\xc4\x99\x98\x98\x42\xac\xaf\xc9\xec\x29\xd0\x6a\xb5\x7e\x49\ -\x52\x0a\x71\x14\x65\x7d\x4d\xa6\x8f\xc1\x84\xa5\xb0\x17\x85\x59\ -\x5f\x93\xa9\x00\x13\x94\x42\x14\x85\x5a\x5f\x93\xf9\x42\x68\xbf\ -\xa5\x50\xb4\xf5\x35\xb9\xac\x04\xf7\x51\x0a\x85\x5b\x5f\x93\x8b\ -\x00\x13\x96\x42\x29\xd6\xd7\xe4\xf6\x2e\x90\xb4\x14\xca\xb2\xbe\ -\x26\xd7\x97\xa1\x04\xa5\x50\x9a\xf5\x35\xb9\x0a\x20\x22\x7d\xd3\ -\xc0\xdb\x10\x84\x37\x59\x08\x1c\xd3\xc0\x3b\x65\x59\x5f\x93\xfb\ -\xeb\x70\xb3\xd9\x7c\x5a\x33\xe4\x3c\x80\x75\x00\x7f\xef\xfe\xad\ -\xd7\x0c\x39\x9f\xf4\x27\xb3\x3c\x29\x64\x7f\x40\xa3\xd1\xe8\x02\ -\x78\xbd\x88\xb1\x26\xa5\x12\xbf\x0a\x97\x49\x94\x00\x3b\xc1\x0b\ -\x92\x66\x41\xb9\x64\x4e\x44\xee\x3b\xa3\x31\x51\x02\xf4\x82\x17\ -\x83\xed\xa7\x07\x93\x88\xdc\xbb\xa3\x31\xe1\x8d\x92\xe0\xe6\x70\ -\x8b\x79\x31\xd3\xac\x0a\x44\xc4\x7c\x2d\x78\x4d\x30\xf4\x48\x0e\ -\x6f\x94\xa4\xdc\x1d\x6e\xc0\x6a\xa7\xd3\x99\xcd\x3c\xbb\x9c\xe9\ -\x74\x3a\xb3\x04\x86\x16\x62\xa1\x7b\x43\x84\x00\x4a\x35\x1e\x00\ -\xdc\x0e\x34\x1d\x33\xcc\xda\xda\x41\x12\xe1\xbf\xcd\xd2\x43\x3b\ -\xc6\xb7\x06\xf7\x36\x4c\xd8\x01\x22\x7d\x01\xdf\x1b\x69\xbd\x60\ -\x98\x33\xdb\xb6\xed\x5e\xb3\x2c\x6b\xbe\x8a\x13\x23\x49\xd3\xb2\ -\xac\x79\xdb\x76\xaf\x0d\x36\x49\x0f\xed\x14\x87\xc0\xbf\x1e\xb5\ -\xe8\x1a\x7b\x92\xc2\x72\xba\xcb\xff\x87\x03\x13\x00\x40\xc8\xf2\ -\xbc\x6a\xdc\x8e\xea\x1b\xbb\x0e\x50\xcd\xfa\x6d\x42\x96\xf3\x4b\ -\xab\x10\x48\x60\x69\xae\x55\xff\x74\x5c\x40\xc2\x43\x53\xc6\x17\ -\x00\x4e\x65\x9a\x5a\xfe\x24\x3a\x34\xb5\x9f\x63\x73\x67\x31\xd8\ -\x75\x5d\xc5\x63\x73\x5d\x82\x4f\x26\x39\x36\x37\x65\xca\x94\xc3\ -\xcd\xbf\x5b\x3f\xf6\x3c\xa0\xff\x9c\x5c\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x04\xf5\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\xa7\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xcf\x6f\x15\x55\x14\xc7\xbf\x67\xa6\x85\xc2\xca\xe7\xa6\x21\ -\x10\x58\x58\x16\x36\x4d\x30\xf1\xa5\x2f\x95\x4d\x9b\xa8\x1b\x90\ -\x96\x02\xa2\x11\x08\x7f\x82\x1b\x89\x6d\x62\x5b\x9b\x28\x8a\x1b\ -\xfd\x0b\x34\xb1\xd1\x00\x6d\xf1\x91\xb2\xa9\x26\x6d\x20\x81\x3c\ -\x2d\x1b\xa3\x75\x83\x0b\x9a\xb2\xa8\x8b\xd6\x15\x2d\xd0\xb9\x5f\ -\x17\x7d\x53\x66\xe6\xcd\x74\xe6\x31\x77\x7e\xd4\xbe\x4f\xf2\x16\ -\x73\xee\x79\xef\x9e\x7b\xde\xf7\xdc\xb9\x33\xb9\x17\x68\xd0\xa0\ -\xc1\x4e\x46\xa2\x38\x75\xcf\xb0\x69\x6d\x05\x27\x14\xd4\x59\x81\ -\x14\x09\xec\x17\x60\x77\xd2\xc1\xd5\x03\x81\x27\x02\x3c\x22\x38\ -\x67\xc0\xb8\xda\x52\xc0\xcd\xd9\x1e\x59\x0f\xfb\x5e\x68\x02\x4a\ -\x93\x7c\x0b\xe0\x37\x00\x5e\xd5\x12\x69\x7a\xcc\x03\xf2\x61\xa5\ -\x5f\x7e\xde\xca\xc9\x08\x6c\x21\xa5\x73\x82\x83\x00\xa7\xb1\xfd\ -\x06\x0f\x00\xed\x00\xa7\x4b\x37\x38\x00\x32\xf0\x8f\x0e\x4c\x40\ -\xe7\x24\x06\x44\xf8\x59\x32\xb1\xa5\x08\xf9\x79\xe9\x27\x7c\x1c\ -\xd4\xec\x9b\x99\xaa\xec\xa7\x3d\xe6\x15\x8a\x0c\xc1\xc4\xad\x43\ -\x6b\x58\xb8\xfe\xae\x58\x5a\x03\x8d\xc9\x99\x6b\x34\x1f\xb6\xe0\ -\x20\x2c\x1c\x13\x72\x14\x40\xc1\xed\x21\x6f\xfb\x95\x43\x4d\x02\ -\xba\x67\xd8\xb4\xba\xc2\xdf\xe1\x94\xbd\xe0\x17\x18\x72\xae\xd2\ -\x2b\x4b\xda\x23\x4f\x80\x52\x99\xad\x50\x1c\x03\xf1\xa6\xc3\x3c\ -\xbf\xa7\x20\x47\xbc\x13\x63\x4d\x09\xac\xad\xe0\x04\xdc\x35\xbf\ -\x6c\x52\x3e\xd8\x2e\x83\x07\x80\x4a\xaf\x2c\xc1\x90\x73\x00\x56\ -\x1c\xe6\xf6\xea\xd8\x5c\xd4\x24\x40\x41\x9d\x75\x5e\x53\x64\xf8\ -\x6e\xbf\xfc\xa3\x3f\xcc\x64\xa9\xf4\xca\x92\x50\x86\x9d\x36\xef\ -\xd8\x00\x9f\x04\x08\xa4\xe8\x32\x98\xb8\xa5\x3d\xba\x94\x50\xcd\ -\x98\x72\x5b\xe4\x75\xaf\x4f\x4d\x02\x08\xec\x77\x5e\x1f\x5a\xc3\ -\x82\xee\xc0\xd2\xc2\x27\xf6\x03\x5e\x1f\x1f\x05\xb8\x57\x78\x79\ -\x9b\xed\xeb\xc1\x1b\xbb\xdf\xea\x35\x78\x21\xb4\x43\x68\xca\x3a\ -\x80\x28\x74\x95\xd9\xa6\x94\x1a\x02\xe5\xd4\x86\x85\xe3\xa6\x18\ -\xa3\x77\x4f\xca\xdf\x71\x7f\x3b\xf7\x0a\x28\x8d\xf3\xb0\xb2\x78\ -\x1b\x94\xf3\x00\xf6\x6e\x7c\xe4\x82\x45\xde\xe9\x2a\xb3\x2d\xee\ -\xef\xe7\x3a\x01\xdd\x33\x6c\x82\xc1\x1f\x01\xec\xf3\x69\xde\xa7\ -\x2c\xf5\x49\xdc\x3e\x72\x9d\x80\xc7\xcb\xb8\x04\xa0\xe6\xd6\xf5\ -\x1c\x39\x1d\xb7\x8f\xdc\xce\x01\xc5\x49\x76\x08\x38\x92\x74\x3f\ -\xb9\x54\x40\xf7\x0c\x9b\x4c\xf0\x3b\x00\xcd\x5b\xf9\x09\x78\x3d\ -\x6e\x5f\xb9\x4c\x40\xb8\xf4\x01\x00\x4f\x69\x18\x57\xe2\xf6\x95\ -\xbb\x12\x88\x2c\x7d\x91\x91\x4a\x9f\xcc\xc7\xed\x2f\x57\x0a\x88\ -\x2a\x7d\x08\xe6\xf6\xbc\x84\xaf\x74\xf4\x99\xab\x04\x44\x95\xbe\ -\xb2\xe4\x62\x94\x17\x9e\x51\xc8\x4d\x09\xd4\x23\xfd\xdf\x4e\xcb\ -\x9f\xba\xfa\xcd\x85\x02\xb2\x90\xbe\x8d\x16\x05\xbc\x71\x83\xaf\ -\x58\x54\x43\x9b\x0b\x13\xe1\x84\x61\x18\xa3\xf7\x7a\xe5\x41\x94\ -\xef\x3f\x5e\xc6\x25\x91\x74\xa5\x6f\x13\x5b\x01\x5d\x65\xb6\x59\ -\xe4\x1d\x40\x2e\xc0\x5e\xab\x53\xce\x2b\x8b\xb7\x4b\xe3\x3c\x1c\ -\xf6\xfd\xe2\x24\x3b\x44\xd2\x97\xbe\x4d\xec\x04\x28\xa5\x86\x10\ -\xb0\x56\x87\xc9\x1f\xba\x67\x18\xa8\xb2\x2c\xa5\x6f\x13\x7f\x0e\ -\xd8\x7c\x44\xf5\x6b\x43\x71\xf5\x5f\x7c\x14\xd4\x9c\xc5\xac\xef\ -\x25\xf9\x49\x90\x1c\x29\x4e\xb2\xc3\x6b\xce\x5a\xfa\x36\x1a\x12\ -\xc0\xf1\x10\x87\x5d\xa6\xf0\x5b\x67\x29\xe4\x41\xfa\x36\xf1\x13\ -\x60\x18\x5f\x02\x78\xba\xa5\x8f\xa7\x14\xf2\x20\x7d\x9b\xd8\x09\ -\xa8\xf4\xc9\x3c\x29\x9f\x86\x3a\x56\x4b\x21\x2f\xd2\xb7\xd1\x32\ -\x07\xec\x7d\x19\x57\x00\xdc\x0f\x71\xdb\x65\x82\xdf\x9b\xe0\x18\ -\x72\x20\x7d\x1b\x2d\x09\x98\xed\x91\x75\x0b\x72\x11\x61\xa5\x00\ -\xbc\x06\xe0\x48\x88\x4f\x2a\xd2\xb7\xd1\x76\x17\x98\xeb\x97\x3f\ -\x22\x95\x42\x18\x29\x49\xdf\x46\xeb\x6d\x30\x62\x29\x04\x93\xa2\ -\xf4\x6d\xb4\x26\xa0\x8e\x52\xf0\x23\x55\xe9\xdb\x68\x5f\x08\xbd\ -\x70\x29\xa4\x2c\x7d\x9b\x44\x56\x82\x75\x97\x42\x06\xd2\xb7\x49\ -\x24\x01\x75\x96\x42\x26\xd2\xb7\x49\xec\x59\x20\x72\x29\x64\x24\ -\x7d\x9b\x44\x1f\x86\x42\x4b\x21\x43\xe9\xdb\x24\x9a\x80\xd9\x1e\ -\x59\x37\x4c\x79\x4f\xa4\x76\x93\x85\x08\x16\x0c\x43\xde\xcf\x4a\ -\xfa\x36\x89\x3f\x0e\xdf\xeb\x95\x07\x54\x72\x54\x80\x29\x00\xab\ -\x00\x56\x05\x98\xa2\x92\xa3\x51\x5f\x99\x25\x49\x2a\x6f\x85\x2b\ -\xa7\x64\x11\xc0\x3b\x69\xf4\x55\x2f\xb9\x78\x2b\x9c\x25\x7e\x9b\ -\xa4\x9e\x38\xaf\xcf\x5c\xa3\x99\x5e\x38\x7a\xf1\xc6\xee\x1d\x1b\ -\xe0\xbf\x49\xea\x91\xf3\xfa\x61\x0b\x0e\xea\x0f\x2d\x1d\x7c\x62\ -\x5f\xf4\xfa\xf8\x28\x80\x73\x2e\x83\x85\x63\x7a\xc3\x4a\x0f\xe3\ -\x19\x8e\xbb\x2d\xac\xb9\x25\xd7\x24\xc0\x80\x71\xd5\x79\x2d\xe4\ -\x68\xa9\xcc\x56\xdd\xc1\x25\x4d\xa9\xcc\x56\x0a\x5d\x0b\x31\xef\ -\xd8\x36\x6c\x1e\x5a\x0a\xb8\x09\xe0\x2f\x87\xa9\x00\xc5\xb1\xed\ -\x94\x84\xcd\xcd\xd2\xee\x1d\xe3\xf3\xd5\xb1\xb9\xa8\x6b\xbb\xbc\ -\x50\x86\x55\x33\xa6\xf2\xbc\x5d\xde\x78\x86\xe3\xd5\x7f\xfe\xc5\ -\xb6\xcb\xdb\x74\x4e\x70\xf0\x7f\x71\x60\x02\x00\x44\x06\x2b\x27\ -\xe5\xb2\x5f\x53\xe0\x3a\xe0\xd7\x7e\x5c\x86\xc8\x60\x72\x51\xa5\ -\x02\x01\x19\xa8\xf4\xe1\x8b\x20\x87\xa8\x87\xa6\xbe\x06\xd0\xae\ -\x35\xb4\xe4\x89\x74\x68\xaa\xee\x63\x73\xd5\x2d\xe7\x07\xf2\x78\ -\x6c\x0e\xc0\x22\xc0\xfb\xf5\x1c\x9b\x6b\xd0\xa0\xc1\xce\xe6\x3f\ -\xb7\x37\xe9\x8b\xf9\x5d\x56\x0e\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xd7\x41\x0d\x00\x20\x0c\x04\xc1\x83\x20\xa9\x02\x70\x53\x3f\xd5\ -\x43\x52\x6b\x88\x38\x7e\xec\xfe\x7b\x99\x6f\x25\x32\x8a\xac\x8e\ -\xac\x76\x36\x96\x69\xd8\xe6\xbd\xa6\x3b\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x6e\xde\x67\x34\x74\x1e\x39\x3e\ -\xee\x02\x8e\xc2\x05\x10\x61\x1a\xbe\x91\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x03\xde\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x90\x49\x44\x41\x54\x78\x9c\xed\ -\x98\xcf\x6f\x54\x55\x1c\xc5\xcf\xb9\xf3\xd2\xd4\x04\x31\x4a\xdd\ -\x89\x2e\x81\x75\xdb\x99\x31\xc6\x64\xaa\x81\x98\x2e\xb4\xd3\x1a\ -\x16\xec\x90\x10\xfd\x03\x54\xe2\x82\x18\x62\x42\xfc\xb1\x36\x21\ -\x50\x60\x45\x4c\xa0\xf3\xa6\xb8\x60\x92\x26\x32\x24\xd8\xc8\x88\ -\xac\xd5\x35\xee\x24\x1a\xe3\xa2\x55\xda\x7b\x5c\xcc\x80\xd3\x77\ -\x6f\x3b\xbf\xde\x9b\xa9\x78\x3f\xcb\xfb\xee\xfd\x7e\xcf\xf7\xbc\ -\xef\xdc\x77\xef\x00\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\x10\ -\x08\x04\x02\x81\xff\x17\x1c\x55\xe2\x7c\x45\x65\x52\x5f\x02\x30\ -\x90\x2e\x34\x16\x72\xa7\x47\xa1\x63\x24\x06\x14\x63\x9d\x14\x74\ -\x0e\x80\x79\x2c\x44\x3c\x79\x67\x81\x8b\xc3\xd6\x62\x3a\x4f\x49\ -\x97\x62\xac\x53\x82\xce\x27\x73\x8b\xba\x90\xaf\xea\xc3\x61\xeb\ -\x19\x5e\x07\x48\x2c\x54\xed\xe7\x00\xdf\xef\x30\xf1\x8b\x46\xd9\ -\x9c\x02\xa9\x61\xc8\x1a\x8a\x01\xa5\xba\xa2\xb5\xdf\xed\x79\x80\ -\xc7\xbb\x5b\xa1\x4b\x4f\x3d\x6b\xde\xbd\x35\xc3\x8d\x6c\x95\x0d\ -\xc1\x80\xd2\x65\x8d\xaf\xed\xd5\x57\x20\xe6\x92\xcf\x24\x58\x36\ -\x15\x38\x3f\x45\x02\xd5\xf1\x3f\x78\xec\xd6\x71\xae\x67\xa9\x2f\ -\x53\x03\x0a\x37\xb4\x17\xeb\x5a\x06\x30\xe3\x49\xbd\x09\x3c\xea\ -\x72\x02\x50\xce\x13\xe2\x66\x94\xe3\xdc\xea\x5b\xfc\x33\x2b\x8d\ -\x99\x19\xf0\xea\x55\x3d\xff\x77\xa4\x1a\x80\xc9\xad\x4f\x84\x66\ -\xf1\x3e\x94\x73\x24\x11\x3f\x8c\x3d\xe4\xec\xed\xa3\xfc\x35\x0b\ -\x9d\x99\x18\x30\x79\x55\x2f\x46\x91\x56\x00\x1c\x48\x64\x13\x05\ -\xbb\xe3\xee\x46\x18\xc8\xd1\xf5\xb3\x35\x3c\x7c\x77\x8e\xf7\x53\ -\x96\x9a\xbe\x01\xc5\x58\x87\x04\xad\x00\x78\x21\xf1\x48\x20\x2c\ -\x3a\xed\xed\x04\x24\x18\xba\xda\xee\x1b\xcb\x23\xdf\xbd\xcd\x9f\ -\xd2\x53\x9b\xf2\x39\x60\xba\xa2\x69\x41\xb7\xe1\x2b\x1e\x5d\x14\ -\xdf\x9a\x49\xc0\x82\xce\xec\xfd\xd6\xe8\xdb\xfc\x92\xa6\x52\x11\ -\xdb\x22\x35\x03\xa6\xab\x7a\xdd\x50\x37\x01\xec\x6b\x1f\x17\xd4\ -\x2c\xbe\x57\x04\x0b\x38\x26\xec\xa3\x51\x3d\x1f\xeb\xb5\xbe\x85\ -\x26\x48\xc5\x80\x62\xac\x79\x23\xdd\x00\xb0\xa7\x7d\x5c\x90\x08\ -\xf6\x5e\xfc\xbf\x58\x34\x0d\x6c\x67\x0f\xa1\x5a\xbe\xa2\xf2\x00\ -\x71\x1f\x33\xb0\x01\xf9\xaa\x4e\x08\xba\x06\x60\xac\x7d\x5c\xa0\ -\x1d\xb0\xf8\x16\xb4\x72\xe3\x8c\x91\x5a\x2a\xc4\x7a\x67\xd0\xe8\ -\x03\x19\x90\x8f\xf5\x01\xa5\xc5\x64\x9c\x66\xf1\xce\x9b\xeb\x1b\ -\x42\xf2\x98\x60\x00\x5d\x2c\xc4\xea\x70\xb4\xee\x14\xbb\x1f\x24\ -\x16\x63\xfb\xa9\x48\xe7\xf2\x22\xc0\xd2\xfd\xed\xa6\x05\xe1\x79\ -\x69\x82\x3e\xfb\xbe\x6c\x3e\xea\xe7\xfe\xd0\xb3\x01\xa5\xba\xa2\ -\xf5\xdf\xec\x39\x91\x27\x5c\x21\x99\x16\xdf\xcc\x21\x90\xf4\x9a\ -\xb0\xf8\xd2\x86\x79\xef\xda\xd1\xed\x0e\x59\x7e\x7a\x32\xa0\x74\ -\x59\xe3\x6b\xcf\xe8\x0a\x80\xf9\x44\xf6\x66\xf1\xee\xa7\x2b\x13\ -\x24\x90\x80\xf1\xa8\x8f\x9f\x1b\xe7\xb1\xda\x2c\xff\xea\x36\x56\ -\xd7\x06\xbc\x72\x5d\x4f\x6f\x6c\x6a\x19\x80\xf3\x09\x6a\x5d\x6a\ -\x86\x52\x7c\x5b\x4e\x6f\x27\x10\xf8\x26\x97\x63\xb9\xdb\xfb\x43\ -\x57\x06\x4c\x7e\xad\x89\x68\x53\x35\x08\x5b\x0f\x21\x12\xc0\xde\ -\x5a\x2e\x55\x48\xc0\xda\x1c\xb8\xb5\x0c\x02\x77\x1f\x46\x9c\xbd\ -\xf7\x26\x1f\x74\x0c\xd1\x69\xc2\xf4\xb2\xf6\x1b\xab\x15\x00\x07\ -\x13\x8f\xfa\x3b\xe0\x64\x81\xff\xfe\xf0\x23\xc4\x23\x8d\x05\xfe\ -\xb2\xd3\xd2\x1d\x3f\x83\x2f\x2f\xe9\xa0\xb1\x5a\xc5\x6e\x2e\x1e\ -\xd8\xee\xd4\x78\x88\x46\xab\x53\xd7\x75\xc0\xb7\xe4\x11\xdb\x76\ -\x40\x7e\x49\x53\x34\xaa\x01\x98\x70\xd2\xed\xa6\xe2\xdb\xf1\x77\ -\xc2\x03\x90\x6f\x34\xca\xbc\xe7\x5b\xe2\xed\x80\x42\x45\x33\x34\ -\xaa\x23\x51\xbc\x76\x73\xf1\x00\xd0\xbc\x6a\x27\x3b\x61\x02\x52\ -\xbd\x58\x55\xc9\xb7\xc4\xe9\x80\x42\x45\xa7\x61\x74\xc6\xe3\xe4\ -\x70\xb7\xf9\x01\x71\xc4\x13\x82\xe5\xc7\x8d\x05\x7e\xb2\xe3\xbc\ -\x62\x6c\x37\x04\xf8\xfe\x9e\xfa\xcf\x43\x60\xf3\xce\xbc\x89\xda\ -\xc7\x3c\x27\xaa\x27\x17\x5f\x6d\xee\x1e\x40\x9e\x6d\xed\xaa\x4f\ -\x16\x82\x05\x79\x76\xd4\x32\x02\x81\x40\x20\x10\x08\x04\x02\x81\ -\x40\x20\x10\x08\x04\x02\xa3\xe6\x1f\x3c\x8f\x50\x7d\x3b\xd7\xa3\ -\xf5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\xfc\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x02\xae\x49\x44\x41\x54\x78\x9c\xed\ -\x9a\x3f\x6e\x13\x41\x14\x87\xbf\xd9\x10\x85\x26\x48\x14\xb9\x01\ -\x15\x25\x29\x69\x90\x88\x2d\xa5\x43\xd8\xa0\x84\x24\x10\xc9\xb1\ -\xa1\x80\x1b\xd0\x72\x03\x90\x00\xc7\x05\x7f\x82\x03\xb1\x8d\x68\ -\xb3\x3e\x44\x24\x2e\xc0\x05\x22\x21\x0a\x8a\x08\xfc\x68\x90\x70\ -\xc6\xde\x18\xef\xce\xcc\xce\x6c\xfc\xca\xf5\xdb\x9f\xe6\xfb\xb4\ -\x9e\x1d\x3d\x2d\xcc\x6a\x56\xb3\x3a\xcf\xa5\xf2\x5e\x80\xed\x2a\ -\x57\x6a\xb7\x84\xe8\x19\xc8\x77\x89\xa2\x47\xfd\x83\xd7\x5f\x87\ -\x7f\xbf\x90\xd7\xc2\x5c\x54\xb9\x5a\x5f\x13\x91\x3d\x90\x08\x40\ -\x0d\x06\x2f\x81\xeb\xc3\x3d\x51\x2e\x2b\x73\x50\xff\xe0\x4f\x31\ -\x5e\xd2\xfb\x0a\x29\x20\x01\xfe\xb7\x28\x9e\xea\xbd\x85\xfb\x0b\ -\x24\xc1\xa3\x64\xbd\xdf\x69\x7d\xd1\xfb\x0b\xb5\x09\x9e\x05\x1f\ -\x77\x5a\x07\xe3\xee\x29\x8c\x80\x34\xf0\x50\x10\x01\x69\xe1\xa1\ -\x00\x02\xb2\xc0\x43\xe0\x02\xb2\xc2\x43\xc0\x02\x4c\xc0\x43\xa0\ -\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\xc3\x43\x40\x02\ -\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\x83\xe7\x02\x6c\ -\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\x87\x02\x4c\xc3\ -\x97\xaa\xb5\x3b\x88\x7a\x01\x80\xa8\x87\x71\xaf\xf9\x79\xf8\x77\ -\xaf\x26\x42\xa6\xe1\xcb\xd5\xfa\x1a\xa2\xf6\x81\x25\x60\x09\x25\ -\xaf\xf4\x1e\x6f\x04\xd8\x80\x1f\x93\x37\x52\x5e\x08\x70\x04\x3f\ -\x10\xd4\x63\xbd\x37\x77\x01\xae\xe0\x95\x52\xf7\xfb\xdd\xe6\x27\ -\xbd\x3f\xd7\x4d\xd0\x25\xfc\x61\xa7\xb9\x37\xee\x9e\xdc\x04\xf8\ -\x00\x0f\x39\x09\xf0\x05\x1e\x72\x10\xe0\x13\x3c\x38\x16\xe0\x1b\ -\x3c\x38\x14\xe0\x23\x3c\x38\x12\xe0\xec\x3d\x2f\xb2\xd5\xef\xb5\ -\x3e\x4c\x93\x65\x5d\x80\xcf\xf0\x60\x59\x80\xef\xf0\x60\x51\x40\ -\x08\xf0\x60\x49\x40\x28\xf0\x60\x41\x40\x48\xf0\x60\x58\x40\x68\ -\xf0\x60\x50\x40\x88\xf0\x60\x48\x40\xa8\xf0\x60\xe0\x1b\x21\x57\ -\xf0\xc0\x66\xbf\xd7\x6a\x4f\x9b\xb7\x52\xa9\xdf\x55\xc8\x73\xc0\ -\xfc\x4c\xd0\x25\x7c\xdc\xdd\x9d\x1a\xbe\x54\xd9\xd9\x54\x48\x1b\ -\x1b\x33\xc1\x10\xe0\x81\x37\x4c\x60\x4c\x25\xc0\x77\xf8\x72\xb5\ -\xbe\xc1\x28\xbc\x99\x99\x60\x08\xf0\x22\xf2\x56\xcf\x33\x32\x13\ -\x0c\x19\x3e\xf3\x4c\xd0\x77\xf8\x95\xdb\xb5\x7b\x4a\xa9\x77\x7a\ -\xde\xa4\x57\xe7\x7f\x09\x28\x2a\x3c\xc0\x5c\xca\xc5\xda\x98\xe4\ -\x6c\xc4\xdd\xdd\xfd\x69\xf3\xb2\xc0\xc3\x84\x27\xc0\x25\xfc\x61\ -\xa7\xe9\x1c\x1e\xce\x38\x09\xfa\x0e\x5f\xaa\xec\xac\x03\x23\xf0\ -\x4c\x79\x62\x1c\xfb\x04\x04\x02\xff\x5e\xcf\x23\xc5\x1e\x32\x22\ -\xe0\xef\xd9\xb9\x8d\x21\xf8\x84\xbc\xf4\x8f\x7d\x42\x1e\x29\x37\ -\xd0\x53\x02\x96\x1b\x8d\xf9\xcb\xc7\x83\x63\x05\x8b\x43\x97\x53\ -\xc3\x27\xe4\xa5\x86\x37\x9d\x07\xda\x49\x70\xf1\xe4\x64\x4e\xc1\ -\xc2\xd0\xa5\x4c\x9f\xa5\x8c\xc9\xcb\xb4\x58\xd3\x79\xa0\xbd\x06\ -\xbf\x1d\x1d\xfd\xba\x72\xf5\xda\x0f\xe0\xa6\xc0\xcf\x48\xd8\x8a\ -\xbb\xad\x4e\xda\x70\x3d\x0f\xd4\x83\xb8\xdb\xfc\xe8\x4b\x5e\x62\ -\xad\xae\x3e\x59\x58\x6e\x34\xe6\x7d\xcd\xbb\xb1\xbd\x7d\xd1\x64\ -\xde\xac\x66\x75\x8e\xeb\x0f\x00\x7d\xea\x19\xbf\xa0\x8f\x59\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x14\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xc6\x49\x44\x41\x54\x58\x85\xed\ -\x94\xb1\x6a\x14\x51\x14\x86\xbf\xff\xee\xa0\x41\xd0\x68\x13\x8b\ -\xb4\xda\xd8\xac\x20\xee\x6e\xd4\xd4\x22\x06\x45\xb1\x11\x05\x4b\ -\x0b\x51\x1f\x41\xf3\x08\x06\x1f\x40\x50\x10\x42\x76\xb3\x91\x88\ -\x98\x2e\xe0\x82\x08\x01\xf5\x05\xb4\x12\xc4\xc6\x4a\x58\xb3\x73\ -\x7f\x8b\x99\x84\x24\xbb\xd1\xec\xb0\x6a\x33\x5f\x75\x87\x7b\xee\ -\xf9\xff\x73\xce\xbd\x03\x25\x25\x25\x25\xff\x19\x15\x3d\x38\x35\ -\xef\xc9\x98\xf8\x25\x50\x4d\x2a\x9a\xec\x5c\xd6\x97\x22\x79\x42\ -\x91\x43\xf5\x05\x1f\x8f\x89\xdf\x00\x55\x80\x5e\xea\xce\xd4\x92\ -\x8f\x15\xc9\x35\x74\x07\x4e\x2f\xfa\x64\xb0\x5f\x03\x13\xd8\x79\ -\x16\x01\x7c\x35\x3a\xff\xee\xaa\x3e\x0c\x93\x6f\xa8\x0e\xd4\xda\ -\x9e\x0e\xf6\x2a\x30\x81\x30\x41\x29\x41\x29\x60\xe0\xa8\xf0\x6a\ -\xad\xed\xe9\xbf\x62\xa0\xd6\xf2\x8c\xa2\x57\x80\x43\x16\xc6\x44\ -\x9c\x4b\x43\x74\xb6\x1a\x57\xf4\x4a\xad\xe9\x8b\x23\x35\x50\x5f\ -\xf4\x4d\xe1\x36\x30\x06\xb6\x4c\xdc\x19\x23\x88\x64\x33\x19\x93\ -\xbc\xd4\x68\xf9\xc6\x48\x0c\x34\x5a\xbe\x87\xfd\x14\xa8\x18\x1b\ -\xd4\x27\xbe\xc5\x46\xcc\x62\xa8\x18\x3f\x6b\x34\x7d\xb7\xb8\x01\ -\x5b\xf5\x56\x3a\x6b\xfc\x28\xff\x8c\xfa\xad\x78\x6e\x01\x45\xe7\ -\x71\x96\xe7\x1a\xcd\xf4\x21\xf6\xae\x97\x7d\xf0\xc6\x03\x87\x7a\ -\x35\xce\x81\xee\x00\x18\xa2\x36\xa6\xbd\x47\x9c\xbd\x8d\x00\x20\ -\xfb\xf1\xdb\x8f\xe1\x3e\xb3\xfd\x05\xf4\x19\x38\x31\xef\x7d\x07\ -\x93\xf8\x04\x74\xdd\x59\xa6\x28\x0d\x27\xbe\x69\xc2\x08\x11\x32\ -\x11\x3f\xef\x7d\x0b\xb7\xd6\x6e\x6b\x7d\x57\x03\xa7\x5e\xf8\x40\ -\xd2\xf3\x02\x70\x21\x1b\xb7\x22\x43\x56\x3e\x00\x81\x43\x2e\xf5\ -\xaa\x97\xe8\xda\xda\x25\xfd\xe8\x33\x70\x6e\xd9\x47\x7e\x76\xbd\ -\x2c\x71\xc6\x80\x4c\xa4\x60\xe5\x3b\xd9\xde\x09\x3a\x5d\x69\xe6\ -\xfd\x15\x7d\x07\x48\x36\x82\xd6\xbb\xfe\x24\x31\xbe\xe9\x4a\xc5\ -\x7e\xd3\x83\xd0\xf6\x41\x9f\xdd\x6f\x7f\x06\x0e\xc3\x96\x57\xe0\ -\xd1\x14\xbb\x27\xec\x7f\xa7\x55\x52\x52\x52\xf2\x47\x7e\x01\x51\ -\xe3\xba\x72\x94\x2f\x72\xc5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x00\xd1\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x83\x49\x44\x41\x54\x78\x9c\xed\ -\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x34\x42\x23\xb4\x40\ -\x80\x1c\xd1\x0b\x89\x45\x23\x54\xe1\x42\x2c\x9a\x78\x52\x64\x7d\ -\x6a\x8c\xfc\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\xa0\ -\x1f\x65\x19\x9c\x6f\x8f\x4b\x92\xb1\x26\xc7\x0d\xfa\xac\x69\x4e\ -\xea\x75\x7a\xde\x5f\xdf\xe1\xa1\x31\xb8\xc7\xe5\x93\xe4\x94\x94\ -\x71\x19\xb6\x0e\xd0\x95\xd6\x01\x86\x92\xbc\x7f\xde\x64\x7d\x73\ -\x52\x87\xad\x4b\x00\x00\xff\xc3\x2f\xd0\x18\xdc\xe3\xf2\x89\x5f\ -\xa0\xcd\x2f\x00\x00\x00\x00\x00\x00\x40\x27\x3e\xec\xfd\x1c\x0f\ -\x3a\x57\x98\xc9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x01\x34\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe6\x49\x44\x41\x54\x78\x9c\xed\ -\xd2\xb1\x09\xc2\x40\x00\x46\xe1\x5f\x87\xc8\x26\x2e\xe2\x0a\x29\ -\xc4\xc6\x61\x6c\x82\x4b\xb8\x88\x5b\xa4\x72\x8b\xb3\x30\x60\x21\ -\x36\xde\x5d\x9e\xe0\xfb\x20\x90\xc0\xa1\x7f\x1e\x49\x24\xfd\xb3\ -\x4d\xef\x3f\xd8\x1d\xce\xfb\x24\xd3\xf2\x78\xbc\x5d\x4e\xd7\x96\ -\xe7\x6b\x6d\x7b\xfe\xf8\x62\x2a\xc9\x50\x92\x21\xaf\x17\x6b\x79\ -\xbe\x4a\xf7\x00\xcb\x8b\xbc\xdd\xb7\x3a\x5f\x6b\x8d\x2f\xe0\xa7\ -\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ -\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ -\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ -\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\ -\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\ -\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\ -\x40\x0f\xa0\x19\x80\x1e\x40\x5b\x23\xc0\xfd\xc3\x7d\xab\xf3\x55\ -\x56\x08\x50\xc6\x24\xf3\xf3\x2a\x63\xfb\xf3\x92\xf4\xbd\x07\x47\ -\xdd\x22\x24\x17\x57\x09\xda\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ -\x42\x60\x82\ -\x00\x00\x04\x2e\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe0\x49\x44\x41\x54\x78\x9c\xed\ -\x98\x4d\x68\x5c\x55\x14\xc7\x7f\xe7\xbd\x32\xa9\x9a\xb8\xb1\x94\ -\xb4\x52\xc4\x8d\xd6\x8d\x60\x32\x16\xba\x28\x34\x7e\x84\x88\x52\ -\x94\x4a\x51\x57\xcd\xa2\xe9\xa4\x69\x26\x11\xea\x27\x04\x09\x56\ -\xb0\x5d\xa8\xcd\xd4\x7c\x8c\x94\x44\x84\x82\x9b\x62\x5d\x18\x69\ -\xa9\x4c\x16\xae\xe6\x4d\x0a\x6e\xfc\xc0\x45\x69\x35\x0b\x9b\x48\ -\x21\x81\xa6\x53\xe7\x1d\x17\xc9\x68\xe6\xbd\x97\x4e\x66\xe6\xbd\ -\x49\x4a\xef\x6f\x79\xcf\xbb\xe7\xfe\xcf\xb9\xef\xde\x7b\xee\x05\ -\x83\xc1\x60\x30\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\xc3\xbd\ -\x85\x78\x1b\xe2\x5d\xa9\x0f\x04\x1d\x50\xc1\x56\x70\x05\x74\x3d\ -\x84\x85\x85\x82\x08\x58\xa2\x14\x14\xf9\xd0\x49\xf7\x0e\xae\xb4\ -\x6f\xf2\xf5\x10\x1d\x50\xb0\x01\x04\xac\x3a\xe9\x8c\x8c\xe2\x0c\ -\xab\x60\x83\x0e\x00\x25\x09\xb8\xeb\x03\xac\x15\x7f\x02\x54\x8f\ -\x2b\x72\x57\xff\xf6\x41\x28\xa2\xa8\x1e\xf7\xb6\xfb\xf6\x00\x80\ -\xd6\xae\x53\x6d\x22\x72\x1e\x68\xf2\x7c\xae\xa0\x6e\x24\x0a\xc3\ -\xc3\xc2\x1f\xd7\x3c\x22\xfb\x9c\xd1\xde\x8c\xf7\xe3\xc0\x04\x00\ -\xb4\x74\x9f\x6a\xb5\x5c\xf9\x1e\xd8\x52\x62\x50\x14\x61\x43\x26\ -\x41\xc1\x12\x7f\x4c\xb3\xae\xa5\x1d\xd3\x23\x7d\xb9\xa0\x3e\xab\ -\x26\x00\x20\xde\xfd\xd9\xe3\xb8\xd6\x45\x60\x87\xa7\x9b\x02\xee\ -\xc6\x39\x20\x64\x39\x78\xf5\xc6\x73\x15\xcb\x6d\x77\x46\xfa\x7f\ -\x5d\xbd\x67\x19\x9e\x3e\xf2\xf9\x0e\x2d\x14\x2e\x00\x3b\x3d\x5d\ -\x37\x48\x12\x04\xc0\xc2\x1f\xfc\x2f\x62\xdb\xed\xd9\xe1\x9e\x6b\ -\x77\xea\x5d\xf6\x14\xc8\x0e\xf7\x5c\x53\xcd\xef\x01\x9c\x52\x8b\ -\x8a\xa2\x76\xf9\x14\x46\x87\x00\x8a\xda\xbe\xe0\x85\xac\x6a\x7e\ -\x4f\xb9\xe0\x61\x8d\xc7\x60\x2e\x7d\x6c\xb6\xe1\xf6\xcd\x67\x04\ -\x7e\xf0\x09\x50\xec\xf5\xc8\x81\x82\xb8\x04\x8e\x7d\xa9\x21\x7f\ -\xf3\xd9\x5c\xfa\xd8\xec\x5a\xfc\x54\xa4\x7d\xef\xc1\xf1\xcd\xf3\ -\x0d\x0b\x67\x05\x7d\xc5\x2f\x48\x5d\xa9\xd3\xf1\xa9\xa8\x08\x12\ -\x34\x79\xe7\x6e\xc4\x78\xe3\xf7\x54\xf2\xd6\x5a\x7d\x55\x54\x08\ -\x65\x26\x3a\x17\x9b\x9a\x67\x0f\x80\x9e\xf1\xda\x04\xb1\xb4\xc2\ -\x84\x56\xc3\x52\x69\x1b\x14\xbc\x9e\x79\xf4\xef\xe6\x03\x95\x04\ -\x0f\x55\x0b\x56\x89\x1f\x4e\x9d\x00\xde\x0a\x10\x18\xd9\xfd\xa1\ -\x58\xd7\xfb\x0d\x7a\xd2\x49\x27\xdf\xa5\x8a\x3f\xb0\xa6\x19\x8b\ -\x27\x52\x6f\xa3\x7a\x22\xc0\xab\x8b\x86\x9d\x04\x15\x82\x66\x5e\ -\xe4\x1d\x67\xb4\xf7\x64\xb5\x5e\xed\x5a\x24\xcd\x38\x93\x3f\x6e\ -\x6b\xed\xf8\x53\x44\x5e\xa2\x34\x99\xa2\x84\xb8\x1e\x84\xa0\xe0\ -\x5d\x90\x43\xce\x58\xef\xe9\xda\x5c\x87\x40\x3c\x91\xda\x8f\xea\ -\x59\x20\xe6\x31\x2d\xd7\x0a\x35\x11\x54\xda\xe6\x05\x5e\xcf\x8e\ -\x25\xcf\xd5\xe8\x3b\xbc\x49\x8a\x1f\x1a\x7a\x0e\x8b\x6f\x80\x07\ -\x56\xb6\xeb\xd2\x96\x5d\x65\x12\x24\xa8\xc0\x59\x10\xf4\xe5\xec\ -\x58\xdf\xa5\xea\x7c\x7a\x46\x08\xc3\x49\x91\x78\x62\x68\x17\xca\ -\x77\xc0\x43\x9e\x61\xaa\xb8\x44\x05\x06\x3f\x27\xae\xfb\x42\xf6\ -\x8b\xfe\x6c\x2d\x3a\x4b\x46\x09\xcb\x51\x91\x96\x23\x9f\x3e\x21\ -\x85\x4d\x17\x05\x7d\xd8\x63\xaa\x60\x39\x04\x06\xff\x87\x6b\x17\ -\xda\xa7\x87\xdf\xfc\x39\x04\x99\xff\x8f\x14\xa6\xb3\x22\x4f\xf5\ -\x9c\x7e\xc4\xfe\xc7\xbd\x00\x3c\x56\x62\x50\x51\xe4\x4e\x7f\x82\ -\x00\x1a\xb4\xe6\x7f\x53\x75\x9f\xcf\xa5\xfb\xaf\x86\x2c\x35\xba\ -\xc2\xe5\xc9\xc4\xc8\xd6\x98\xde\x9e\x04\x5a\x4a\x2d\x0a\x48\x21\ -\x50\x89\xaa\x1d\x20\x69\xba\x90\xa7\xe3\xf2\x78\xf2\x7a\x14\x3a\ -\x23\x7b\x12\xfb\x69\xb4\xfb\x2f\x3b\x46\x1b\xc2\x54\xa9\x45\x00\ -\x4a\x2e\x51\xc5\x3b\x45\x40\xf0\x19\x3b\x46\x5b\x54\xc1\xff\xa7\ -\x26\x4a\xf6\x1e\x1c\xdf\xbc\x10\x9b\xff\x1a\x61\x9f\xd7\xa6\xcb\ -\x7b\xc2\x2a\x8f\xaf\xe7\x1b\x6f\x35\xbd\x96\x99\xe8\x5c\x8c\x52\ -\x5f\xe4\x8f\xa2\x99\x89\xce\xc5\xc6\x6d\x73\xfb\x45\xe4\x4b\xaf\ -\x4d\x96\x5e\x70\x7c\x1a\x14\x26\x1a\x9b\xe7\x5e\x8d\x3a\x78\xa8\ -\xb1\x12\x5c\x2b\x57\xa6\xa6\xdc\x99\x17\x77\x7d\xbb\x7d\xfe\xbe\ -\x07\x11\xd9\x5d\xe6\xf3\x4f\x72\xcd\x73\x47\xaf\x0c\x0e\xfa\xf7\ -\x89\x08\xa8\xf3\x55\x5e\x25\xde\x95\x7a\x0f\xe1\xa3\x60\x31\xfa\ -\x7e\x76\x2c\xf9\x71\x35\x97\x9a\x6a\x59\x97\xf7\x9c\x78\x62\xe8\ -\x30\xca\xe8\x8a\x26\x45\x35\xe1\xa4\xfb\xd2\xf5\xd6\x52\x97\x25\ -\xe0\x65\xc6\x99\xcc\x6d\x6f\xed\xb8\x1f\x91\x9d\x02\x0b\x40\xa7\ -\x93\xee\xfb\x6a\x3d\xb4\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\ -\x83\xc1\x60\x30\x18\xee\x35\xfe\x05\x2f\xee\x41\x9b\x3f\x6f\x48\ -\xfe\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x22\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ -\x94\xb1\x6b\x13\x51\x1c\xc7\x3f\xdf\x17\x84\xa0\x20\x71\xd0\xc1\ -\x49\x89\x08\x4a\x06\x25\xb8\x3a\x79\xb5\x48\xe9\x50\x0d\x8e\x82\ -\x6d\x66\xff\x02\x41\xdd\xfc\x0b\x1c\x92\xb8\x56\xbc\x06\xa1\x75\ -\xf0\x7a\x43\x07\x07\x75\x11\xed\x10\x17\x2d\x2e\x0a\x2e\xb5\x64\ -\xb1\xa1\xe6\x7e\x0e\x97\x33\xa7\x6d\x63\x92\x16\xbb\xdc\x17\x0e\ -\xde\xdd\xfb\xbe\xef\xf7\xfb\x7e\xef\xf7\x0e\x32\x64\xc8\x90\xe1\ -\x80\xa1\x64\xe0\x5d\x9f\xfb\x0e\x14\xfe\x93\xef\x46\xd8\xac\x1f\ -\x03\x70\xfd\x28\x72\xbb\xd2\xf7\x1b\x29\xaf\xfe\x40\xd1\x69\xe0\ -\x75\x8a\x16\x01\xdd\xfd\x78\x84\xa2\xdf\xde\xc6\xab\x9e\xd7\x9f\ -\x01\x02\xbf\xb1\xae\xc3\x9d\x2b\x40\x00\x80\xe1\x48\x1d\xd1\x1e\ -\x76\xab\x08\x73\xf1\x90\x17\x1c\xe9\x78\x81\xdf\x58\x4f\xa6\x73\ -\x69\xee\xa7\xd5\xd5\xad\x72\xa9\xf8\xf4\x87\xe5\xcf\x4a\x94\x30\ -\xb4\xb7\x08\x12\x98\x13\x80\xd9\x93\x82\x6b\xdf\x5c\x9a\x9f\xdf\ -\x4c\x33\x72\x7f\x2f\x69\xb5\x5a\xdd\x72\xa9\xf8\xac\x63\xf9\xe3\ -\x88\x4b\x8c\x5b\x05\xc5\xe6\xc4\x02\x8f\x0a\xb9\x76\xd5\xf7\xfd\ -\x9f\xdb\x68\x83\x24\xbc\x99\xb9\xfb\x88\xbb\xbd\xd7\x08\xcc\x86\ -\x75\x4f\xcc\x41\x0f\xc2\x66\xed\x1e\xb0\xe3\xda\x6d\x15\x48\x63\ -\xed\xc3\xdb\x95\xe2\xf9\xf2\x06\x30\xd9\x0b\xab\xdd\x84\x12\x98\ -\xe1\x24\x92\x9d\xdf\x09\x9b\xf5\x87\x83\xf8\x03\x03\xf4\x42\xbc\ -\x29\x9e\xbb\xb8\x86\x34\x0d\xb8\x5e\x5f\xec\x18\xc2\xcc\x9c\x24\ -\x11\x77\xff\xad\xb0\x59\xaf\xfd\x4b\x7f\xe8\xf3\x9d\xb8\x51\x9d\ -\x32\x33\x1f\xc8\x13\x57\x21\x4a\xcf\xa7\xcc\x37\x25\x55\x96\x17\ -\x6a\xcf\x87\xd1\x1d\xa9\xc1\x26\x66\x66\x2f\x9b\xdc\x12\xd8\x51\ -\x33\x33\x29\xbe\xdf\x7d\x73\xb5\x9d\x6c\x2a\x58\xa8\xbf\x1c\x56\ -\x73\xe4\x0e\xf7\x2a\xd5\x0b\x44\x16\x00\x27\x0c\x4c\x89\x86\xf8\ -\x86\x34\x19\xfa\xb5\x77\xa3\xe8\x8d\x75\xc5\xae\x56\x66\xcf\x44\ -\x11\x21\xe8\x54\xfc\xc5\x3e\x3b\x87\x17\xf8\x8d\x8f\xa3\x6a\x8d\ -\xfd\x9b\xf1\xa6\x6f\x9f\xe4\x90\xfb\x02\x7a\xcf\x56\xf7\x5a\xb8\ -\xf8\xf8\xeb\xb8\x5a\x19\x32\x64\xc8\x70\xa0\xf8\x05\xa4\xf1\xa4\ -\x8e\x44\xc6\x51\x5e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ -\x82\ -\x00\x00\x00\x8a\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x58\x85\xed\ -\xcd\x21\x15\x00\x21\x00\xc0\xd0\x41\x26\x02\x60\xc8\x82\xbb\x30\ -\xa7\x08\xc3\x7b\x14\x20\x14\x0a\x8b\xc4\xb0\xaf\xe6\x06\x92\x24\ -\xbd\x2e\xec\x48\xf5\x1f\x40\xbe\x74\xed\xb3\x7d\x05\x20\x5e\x19\ -\x4a\x92\x24\x1d\x2c\x16\x1c\x05\x04\xcb\x08\x93\xc5\x00\x00\x00\ -\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x93\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x45\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x4e\xc2\x50\x14\xc6\xf1\xff\x29\xa1\x8c\x96\x05\x9f\xa1\ -\x0b\x03\x09\xf8\x02\x26\xf0\x0e\xac\x26\x94\xc1\x18\x9c\xd5\x41\ -\x76\x10\x19\xe8\x0b\xf0\x0c\xc6\xc4\x27\xa8\x89\x03\x4b\xdf\x81\ -\x05\x1c\x29\x81\xe3\x00\x35\x58\xc0\x41\xdb\x38\x78\xbf\xf1\xb4\ -\xc9\xf7\x4b\x6f\x87\x7b\xe0\xbf\x47\x92\x83\x8a\x37\xac\x5b\xaa\ -\xd7\x40\x0d\x70\x52\xea\x99\x03\xc1\x5a\xa4\xf7\xe6\x5f\x3e\x1f\ -\x05\x54\x5b\x8f\x5d\x85\x1b\x60\x01\x12\x22\xfa\x9e\x4a\xbd\xca\ -\x09\xa8\x0b\x14\x44\xb4\xfb\xea\x5f\xdd\xed\x01\xaa\xad\x41\x43\ -\x91\x27\x84\x97\x88\x7c\x73\xe2\xb7\xa7\xa9\x94\x6f\x53\xf6\x46\ -\x25\x9b\xe5\x18\xe5\x7c\x2d\xd2\x88\xbf\x84\xf5\x89\x44\x3a\xc0\ -\x22\x8b\x72\x80\x89\xdf\x9e\x46\xe4\x9b\x40\x94\x53\xed\xc4\x73\ -\x6b\xe7\x9d\x1a\x48\x98\x45\xf9\x2e\x42\x21\xd4\xcd\xff\xb5\x07\ -\x70\x52\x3b\xf3\x6f\x22\xc2\x1c\x28\x1e\x02\xfc\x49\x0c\xc0\x00\ -\x0c\xc0\x00\x0c\xc0\x00\x0c\xc0\x00\x76\x01\xf3\xcd\xed\x35\xdb\ -\xa8\xe2\x00\xb3\x43\x80\x00\xd4\x2d\x7b\xa3\x52\x56\xe5\x65\x6f\ -\x54\x12\x70\x05\x82\x3d\xc0\x5a\xa4\x07\x14\x6c\x96\xe3\x2c\x10\ -\x67\x17\x0f\xa7\x36\xcb\x31\x60\xaf\x44\xfa\xf1\xfc\xeb\x62\xe2\ -\x0d\xee\x55\xe5\x16\x88\x14\xc2\xed\x05\xf2\xd7\x51\xc5\x11\x70\ -\x01\xfb\xe8\x62\x12\xa7\xe2\x0d\xeb\x39\xd5\xce\xf6\xea\x5c\x4c\ -\x3e\xff\x61\x66\x02\xc1\x4a\xa4\x9f\x5c\xcd\x4c\x3e\x00\xa7\x7c\ -\x6e\x32\xdb\xbd\x64\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ -\x60\x82\ -\x00\x00\x00\xa1\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x53\x49\x44\x41\x54\x58\x85\x63\ -\x60\xa0\x00\x98\x64\x4c\x6c\x30\xc9\x98\xd8\x40\x89\x19\x4c\x94\ -\x68\xa6\x06\x18\x75\xc0\xa8\x03\x46\x1d\x30\xea\x80\x51\x07\x8c\ -\x3a\x60\xc0\x1d\xc0\x42\x05\x33\x1c\x28\xa9\x92\x87\x45\x08\x1c\ -\x38\x33\x23\xbf\x81\x5c\xcd\x03\x1e\x02\xa3\x0e\x18\x75\xc0\xa8\ -\x03\x46\x1d\x30\xea\x80\x51\x07\x0c\xb8\x03\x00\xb9\x93\x08\x9d\ -\x47\x2d\xcd\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\ -\x00\x00\x03\x9c\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x03\x4e\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\xcd\x6b\x13\x41\x18\xc6\x9f\x77\xd3\xa8\x85\x52\x0f\x22\x22\ -\xf6\x60\x6d\x3c\xa8\x05\xd1\x93\xde\x8a\x36\x89\x15\x14\x9b\x18\ -\x94\x16\x11\xd2\x54\xfb\xf1\x07\x14\xff\x02\xeb\x51\x69\xfd\x22\ -\xed\xa5\xd4\x83\x31\x55\x11\x5a\x4d\x2a\xb4\xe0\xc1\x8b\x1f\x87\ -\x22\x3d\x58\x11\xcc\xa5\x8a\x87\x96\x8a\xa9\x49\x66\x3c\x18\x04\ -\xb3\x9b\x4d\xb3\xbb\x93\x31\xcd\xfc\x8e\xb3\xc3\xf3\x3e\xfb\x64\ -\x32\x33\xec\xce\x02\x0a\x85\xa2\x96\x21\xbb\x02\x6d\xa1\x81\x06\ -\x37\xcf\x0c\x82\xf1\x10\x08\xad\x00\xb6\x3a\xe0\xcb\x0e\xeb\xe0\ -\x58\x80\x46\xb1\x0c\xb9\x47\xe7\x62\xb7\xd7\xcc\x3a\xdb\x0a\xc0\ -\xd7\x19\xf1\x72\x0d\xe3\x00\x9a\xec\xe8\x08\x24\x45\x0c\xe1\xc4\ -\xe3\x68\xb2\x58\x07\x97\x55\x65\x5f\xb0\x27\xcc\x89\x1e\x02\xd8\ -\x6e\x55\xa3\x02\x34\x82\xd0\xb5\xef\xd0\xd1\x2f\x9f\x3e\xbc\x7d\ -\x6f\xd4\xc1\xd2\x08\xf0\x9e\x0f\xfb\xc0\xb5\x19\x00\x9a\x2d\x7b\ -\x95\x23\x47\x0c\x1d\x46\x23\xa1\xec\x00\xda\x42\x03\x0d\x6e\xf6\ -\x6b\x11\xc0\x1e\x47\xac\x55\x8e\x54\x46\xdb\x72\xa0\x70\x4e\x28\ -\xfb\x17\x74\xf3\xcc\x20\xaa\xef\xe6\x01\xa0\x29\xef\xfd\x1f\xca\ -\x1f\xc2\x8c\x87\x1c\xb1\x23\x03\x03\xef\xe5\x07\xf0\x67\xa9\xab\ -\x4e\x0c\xbc\xd7\x59\x90\x31\x5d\xe7\x93\xf1\xa8\xed\xbd\x85\x1d\ -\xbc\xc1\x08\x37\xb9\xac\xf3\x5e\x2d\xb3\xb8\x30\x54\x00\xb2\x0d\ -\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\xc8\xa6\xe6\x03\x28\ -\xb9\x11\xf2\x07\xae\xec\x66\x60\xfd\x20\x9c\x24\x60\x97\xd9\x2e\ -\x03\x00\x7c\xc1\xc8\x47\xab\x66\x38\xc0\x01\xa4\x08\x98\x76\x6d\ -\xfb\x79\x6f\x66\x72\x72\xd5\xaa\xd6\x46\x31\x0d\xc0\x1b\xe8\x3d\ -\xcb\x88\x8d\x03\xd8\x91\x37\x58\x12\x0e\xb4\xd8\xf4\xe4\xe1\x40\ -\x5b\x36\x5d\xdf\xdf\x1e\x88\x74\xcd\x4e\x45\x5f\xdb\xd4\x33\xa5\ -\xe8\x5f\xc0\x1b\xe8\x19\x06\xf1\xa7\xc8\xdf\xbc\x04\x9a\x89\xf0\ -\xca\x1b\xec\xed\x13\x59\xc4\x30\x00\x5f\x20\x72\x01\x44\x43\x22\ -\x0b\x6f\x10\x17\xc0\x47\xda\x03\x91\x63\xa2\x0a\xe8\x02\x38\x75\ -\xae\x6f\x2f\x27\xba\x2f\xaa\xa0\x05\x5c\x44\x78\xd0\xd1\xdd\xdd\ -\x28\x42\x5c\x17\x40\xd6\x95\xbd\x06\x70\x21\xc5\x6c\xd0\x9c\x4b\ -\xd7\x5f\x15\x21\xac\x0b\x80\x80\xd3\x22\x0a\xd9\x85\x0b\xf2\x65\ -\x34\x07\xfc\xaf\x8f\xb8\x85\xf8\x2a\xfb\x81\x88\xa6\xf1\xfd\x22\ -\x8c\x64\xb3\xf0\x68\x1a\xcd\x14\xbb\x4e\x0e\xbc\xc4\x31\xa2\xec\ -\x00\x5e\xc4\xc6\x2c\x6f\x74\xcc\xf0\x87\x7a\xc0\x98\x08\x65\x73\ -\x6a\x7e\x2b\xac\x02\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\ -\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\x90\x6d\x40\x36\x2a\ -\x00\xd9\x06\x64\x63\xe5\x7c\x80\x14\x38\xd0\x52\xe2\xdd\xff\x46\ -\x58\x2f\x6c\xa8\xad\x11\xc0\xb1\x50\xd8\x54\x5b\x01\x68\x14\xd3\ -\x35\xc9\xf0\x21\x89\x54\x86\xdc\xa3\x85\x8d\x55\x33\x07\xd8\x24\ -\x47\x0c\xe1\xb9\xb8\xfe\xdc\x70\x2d\x04\x90\xe3\x84\xde\x64\x91\ -\xf3\xc2\x9b\x3d\x80\x14\x31\x84\x8b\xdd\x3c\xb0\x39\x03\xf8\x7b\ -\x5c\x9e\xea\xd3\x23\x89\x89\x89\x1f\x66\x9d\x75\x8f\x9a\x1d\x58\ -\x6b\x85\x40\xc0\x52\x22\x1e\xf5\x38\xad\x6b\xb4\x0a\x7c\x73\xba\ -\x88\x13\x70\x60\x59\x84\xae\x51\x00\xb3\x22\x0a\xd9\x86\xe3\xa5\ -\x08\x59\x5d\x00\x1a\x63\x37\x00\x64\x44\x14\xb3\xc1\x77\x0d\xda\ -\x1d\x11\xc2\xba\x2f\x46\x96\x16\xdf\x2d\x7b\x0e\x1e\x59\x03\xc8\ -\x2f\xa2\xa0\x15\x08\xfc\x62\x62\x2a\xfa\x46\x84\xb6\xe1\x4e\xf0\ -\x78\x6b\xd3\x4d\x10\x1e\x89\x28\x58\x2e\x04\x0c\x27\xe2\x63\xcf\ -\x44\xe9\x1b\x7e\x33\x34\x3f\x3f\xcf\x2f\x85\xce\xc4\x53\x5f\x57\ -\x57\x00\x3a\x51\xac\x9f\x60\x56\x38\xe8\x72\x32\x1e\xbd\x25\xb2\ -\x48\xc9\x37\xae\xfe\xce\xf0\x61\xa6\x69\x43\x00\xda\x01\xec\x14\ -\x69\x26\x4f\x8a\x03\xd3\x75\xb9\xba\xeb\xcf\x9f\xdc\xfd\x5c\x81\ -\x7a\x0a\x85\xa2\x86\xf9\x0d\x29\x0e\xd0\xf4\xc6\x6c\xeb\x8f\x00\ -\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x01\x9f\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\x51\x49\x44\x41\x54\x58\x85\xed\ -\x94\x2d\x48\x43\x51\x14\x80\xbf\xf3\x36\x10\x14\x15\x67\xd1\x66\ -\x17\x2c\xbe\x55\x8b\x98\x4d\xb3\x6a\x71\x4f\xd0\x4d\x8c\x82\xe0\ -\x5e\xb0\x98\xdc\x14\xdd\xc6\xc2\xaa\x13\x9b\x59\xb0\xcf\xbf\x64\ -\x53\x9b\x7f\xf8\x93\x06\x8a\xbb\xc7\xb4\x89\xf1\xdd\x07\xaf\xf8\ -\xbe\x76\xe0\xfc\x7c\xdc\x7b\xee\x85\x98\x98\x98\xff\x8e\x04\x4b\ -\x57\x71\xbd\x5d\x03\xf0\xfd\xd9\x1e\xba\xaa\xaf\x7d\x84\x15\x70\ -\x02\x65\x6f\x16\xba\xc2\xc9\x9e\xc4\x7b\x26\xd3\x48\x44\x2b\xe0\ -\xfb\x46\x55\xe6\x3a\xe1\x5d\xea\xf1\x3b\x5a\x01\xe0\xbc\x9a\x3b\ -\x42\x65\xab\x13\xbb\xd9\xd2\x75\xa4\x02\x00\xcd\x6a\x6e\x43\xe0\ -\x14\x00\x61\xc2\xf5\x8a\x07\xb6\x02\x01\x97\xf0\x2f\xae\x57\xd2\ -\x6e\xa0\xea\x35\xab\xab\xd5\xa0\x3d\xac\x4e\xa0\x43\x73\xe4\xf5\ -\x77\x09\x45\x2a\x69\x6f\x67\x2a\x52\x01\x7c\xdf\xb4\x12\x89\xfe\ -\x4e\xa8\x38\x67\xd1\x0a\x00\xbc\x3c\x7f\x29\xdc\xdb\x96\x87\x14\ -\x50\xe9\x1d\x1a\xae\x09\x8c\x01\x4f\xed\xa4\x33\x16\xb4\x43\xa8\ -\x8f\xc4\x5d\x4a\x15\x40\xf2\x40\xcb\x38\x3a\x73\xb9\x9f\xbf\x09\ -\xda\xc3\xfa\x15\x4c\x66\x8b\xf3\x22\x52\x07\x8c\x11\x67\xf6\xa2\ -\xbc\x72\x62\xd3\x27\x69\x53\x94\xf6\x8a\xd3\x8a\xd4\x00\x14\x59\ -\xb6\x1d\x0e\x16\x3b\x90\x5e\xdc\x1b\x57\xe4\x18\x48\xa2\xba\x7d\ -\x5e\xc9\x95\x6d\x87\x5b\x08\xa8\x18\xc7\x34\x80\x41\xe0\xb0\x39\ -\xfa\xb6\x1e\x66\x38\x58\x5c\x81\xc0\x83\xa0\xb7\x7d\x9f\x03\x0b\ -\xf8\x79\x13\x56\x20\x26\x26\x26\xe6\x07\x9e\x35\x61\x37\x0a\x6d\ -\x65\xe5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x0b\x31\x18\x83\x23\x65\x15\x94\ -\x0c\x12\x86\x30\x1d\xff\x7d\xac\x6b\x23\x91\xd1\xc9\x8a\x93\x15\ -\xce\xc6\xb4\x04\xad\x65\xdd\x4b\x1a\xee\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\xb8\x79\x9f\x91\x7a\xbf\x61\xfc\ -\xdc\x05\xd1\x25\x09\xfd\x18\x55\xe2\x51\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x87\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ -\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\x10\x85\x0c\x2c\xe0\x38\ -\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\x4d\x67\x4d\x6f\x3e\xde\x66\ -\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ -\xc0\x07\x39\x3f\x03\x99\x39\x3b\x26\x1f\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x02\x0d\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbf\x49\x44\x41\x54\x58\x85\xed\ -\x94\xb1\x6a\x54\x41\x14\x86\xbf\x7f\x36\x4a\x90\xe0\x6a\x13\x8b\ -\x8d\x91\x04\xad\x63\x91\x4a\x49\x2d\x62\x4a\x1b\x51\xf0\x01\x44\ -\x7d\x05\x7d\x04\x83\x0f\x20\x28\xd8\x58\x28\x28\x62\xba\x80\x79\ -\x00\x61\xfb\xdd\xd9\xd9\x15\x02\x29\xac\x6c\xc2\x9d\xdf\xe2\xee\ -\x26\x31\xbb\x01\xf7\xba\x62\x73\xbf\xe2\x32\x70\xee\x9c\xff\x9b\ -\x73\x87\x0b\x35\x35\x35\x35\xff\x19\x55\xdd\x98\x52\x6a\x15\xe6\ -\x13\x66\x2d\xc8\xad\xe5\xe5\xe5\xef\x55\xfa\x84\x8a\xe1\xd7\x8a\ -\xac\xaf\x98\x35\x80\xec\xb0\x9b\x52\xba\x5a\xa5\xd7\xd4\x13\xe8\ -\x74\xfa\xd7\x15\xfc\x05\x58\x04\x1f\x6b\xa3\xbd\x5c\x70\x6b\x75\ -\x75\xe9\xdb\x34\xfd\xa6\x9a\x40\xaf\xd7\xdb\x50\xf0\x0e\xb0\x28\ -\x30\xa8\x00\x15\xe5\xda\x97\x42\xc3\x3b\xbd\x5e\x6f\xe3\x9f\x08\ -\xc4\xd8\xdf\xcc\xd6\x36\x70\x1e\xb0\x21\x8f\x6a\xc3\xb5\x81\x66\ -\xb6\xb6\xbb\xdd\xfe\x9d\x99\x0a\xc4\x98\x1e\x18\xbf\x07\xe6\xcb\ -\xec\xa3\xf0\x63\xe4\x61\x6d\x1e\xf9\x43\xb7\x9b\xee\xcf\x44\x20\ -\xc6\xf4\xc4\xf0\x1a\x68\xb8\x1c\xfb\xa4\xf0\x21\xca\x18\x03\x0d\ -\xc4\x9b\x18\xd3\xe3\xca\x02\xb6\xd5\x89\xe9\xb9\xe1\xc5\xa8\xb9\ -\x26\x9f\xfc\x84\x03\x19\x95\x92\x86\xad\x4e\x4c\xcf\x6c\x9f\x7a\ -\xd9\x27\x16\x6c\x87\x98\xfa\x5b\x98\x47\xb6\x09\x52\xf6\xd1\x95\ -\xff\x43\x24\x3b\x07\x49\x20\x5e\x5e\xb9\xbc\xf4\x54\x1a\x9f\xde\ -\x98\x40\xbb\xdd\x3e\xbb\xb0\xd0\x7c\x85\xb8\x37\xd4\xc9\xa0\x29\ -\xc3\x0f\x8f\x22\x50\x39\x65\xf3\x76\x7f\x7f\xef\xe1\xfa\xfa\xfa\ -\xc1\xa9\x02\x83\xc1\xe0\xdc\x41\x91\xdf\x61\x6e\x97\x7b\xc8\x9a\ -\xfa\xe4\x27\x14\x40\xc2\x01\x04\xe2\xf3\x99\x46\xb8\xdb\x6a\xb5\ -\x7e\x8e\x09\xc4\x18\x2f\x9a\xf0\x11\xb8\x51\x5e\x66\x65\xf4\x77\ -\xe1\xc7\x2c\x04\x0e\x48\x80\x77\x9d\x8b\xcd\x95\x95\x95\x1f\x00\ -\x73\xa3\x77\xb2\x43\x47\xa2\x59\x6a\x09\x2a\xfe\xa6\x27\xa2\xc3\ -\x07\xa0\x9b\x0a\x73\x5d\xe0\xc2\xef\x21\x55\x3f\x73\x05\x3c\xa3\ -\xc1\xd6\xd4\xd4\xd4\xcc\x84\x5f\x30\x7d\xb9\x9b\x4b\x8f\xb2\x18\ -\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x75\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ -\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ -\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ -\xae\x42\x60\x82\ -\x00\x00\x04\x67\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x04\x19\x49\x44\x41\x54\x78\x9c\xed\ -\x9b\x4d\x88\x1c\x45\x18\x86\xdf\xb7\x67\x27\x59\x91\x78\x31\x88\ -\x30\x3b\xdd\xd3\x3b\x89\x3f\x57\x5d\xbc\x0a\xc1\x44\x22\xf8\xc3\ -\x22\xe2\x41\x10\xfc\x41\xc1\x93\x22\x01\x3d\xa8\xa0\x01\x45\xf0\ -\xa0\xe0\x1f\x0a\x1e\x44\xd1\x53\x0c\x62\x64\x83\x10\xf0\x22\x08\ -\x82\x07\x31\x38\xcb\x6c\xd7\xf4\x74\x30\x46\x11\x45\x71\xcd\xf4\ -\xd4\xe7\x61\x26\xc6\xed\x6a\xcd\x8e\xa9\xaa\xee\xc3\x3c\xb7\x6d\ -\x96\x7a\xbf\x7a\xa6\xba\xbb\xbe\xee\x19\x60\xce\x9c\x39\x73\x2c\ -\xa0\x54\xfa\x4c\xa2\xd2\x5c\x0d\xd2\x91\x52\xd9\xd3\x55\xd7\xb3\ -\x5d\x68\x6b\xa0\x44\xa5\x63\x00\xc1\xf4\x4f\x11\x8d\x7d\x71\xdc\ -\x3e\x61\x6b\x7c\x57\x04\x17\xfe\x97\xed\x21\x22\xff\x1c\x8b\x0c\ -\x70\x54\x29\x75\xbd\xad\xf1\x5d\x61\x4d\x00\x49\x5d\x38\xb4\x4b\ -\x10\x7c\xda\xef\x67\x57\xdb\xca\x70\x81\x35\x01\x00\xa4\xe4\xd8\ -\xee\x46\x43\x1f\x5f\xcf\xb2\xb6\xc5\x1c\xab\xd8\x14\x50\x8a\x00\ -\xed\x85\x5c\xaf\x65\x59\xb6\xdb\x75\xd6\xff\xc1\xb9\x80\x29\xd7\ -\x8c\x72\x7d\xec\xe4\xc9\x33\xbb\x3c\xe5\x6d\x1b\x97\x02\x8a\xa7\ -\xc4\xca\xe2\x25\x9b\x47\x7a\xbd\xde\x4e\x87\x99\x33\xe3\x52\x80\ -\x86\x29\x61\x5f\x73\xe7\xe2\x7b\x22\xb2\xe0\x30\x77\x26\x5c\x9f\ -\x02\x1a\xe0\x56\x09\x82\x55\x95\x0e\x5f\x17\x11\x6b\x7b\x90\x8b\ -\xc1\xc3\x35\x40\x34\x8b\x2b\x41\x70\x7f\x32\x18\x3e\xef\x3e\xfb\ -\xc2\x78\xb9\x08\x0a\xa0\xa5\x70\x32\x10\x38\xa4\x54\x7a\xc8\x47\ -\xfe\x7f\xe1\xeb\x2e\x00\x12\xe3\xe2\x31\x01\x5e\x48\x92\xf4\x01\ -\x5f\x35\x94\xe1\x4d\xc0\x04\x29\xee\x16\x01\xe2\x8d\x24\x49\x57\ -\xfd\xd6\x71\x1e\xcf\x02\x28\x10\x14\x25\x04\x20\xde\x57\x2a\xbb\ -\xc9\x6f\x2d\xe7\xc2\x7d\x43\x08\x60\x48\xd8\x21\xd0\x47\xfa\x69\ -\x7a\x83\xef\x72\xfc\x0b\x98\x50\x26\xe1\xd2\x40\xe3\x93\x24\x49\ -\xae\xf5\x59\x48\x55\x02\x00\x40\x40\x43\xc2\xe5\x60\xe3\x78\xbf\ -\x7f\x2a\xf2\x55\x44\x95\x02\x00\x81\xd0\x5c\x09\xad\x20\x18\xaf\ -\xad\xaf\x7f\x7f\x85\x8f\x12\xaa\x15\x00\x40\x00\x91\xe2\x46\x89\ -\xb8\x6a\xa1\x79\xf6\x58\xaf\xd7\xbb\xcc\x75\x7e\xe5\x02\x00\x80\ -\xa5\x7d\x03\xaf\x6b\x36\x17\x8f\x6e\x6c\x6c\x2c\xba\xcc\xae\x85\ -\x80\x29\xa6\x04\xe2\x46\x04\xcd\x0f\x5c\x36\x4f\x75\x12\x00\x94\ -\x34\x4f\x84\xdc\x36\x18\xa4\x6f\x15\x9e\x39\x5a\xa3\x6e\x02\x00\ -\x88\x26\xb7\xae\x04\x01\xef\x55\x2a\x7b\xd1\x45\x07\x59\x43\x01\ -\x80\x88\xd9\x3c\x81\xf2\x98\x4a\xb3\x27\x6c\x67\xd5\x52\x00\x50\ -\xde\x3c\x41\xe4\xf0\x86\x1a\x3e\x64\x33\xa7\xb6\x02\x26\x98\xcd\ -\x13\x21\xaf\x29\x35\xbc\xd3\x56\x42\xcd\x05\x50\xc4\x6c\x9e\x28\ -\x90\x57\x6c\x25\xd4\x5c\x00\xfe\xed\xe5\x9d\xb5\xdb\x62\x6d\x1e\ -\x4e\x96\x31\x9d\xbb\xf1\x21\x09\xf0\xb6\xad\x8c\x1a\x0b\x20\x34\ -\xa4\x61\x2c\x00\xca\x23\x71\x18\xbe\x6a\x2b\xa5\xa6\xa7\x00\x21\ -\x52\x32\x79\x91\xa7\x3a\x16\x27\x0f\xd4\x55\x00\x25\x60\x61\xf6\ -\x02\xbc\x1c\x45\xed\xe7\x6c\x47\xd5\x4e\x00\x81\x00\x62\x5c\xfa\ -\xde\xed\x84\x4b\x8f\x92\x2c\x7b\x01\x7b\x51\xd4\x46\xc0\xe4\x13\ -\x67\x20\xe6\x75\xff\xe3\x1f\xcf\x9c\xbe\xaf\xe4\xf5\xbb\x15\x6a\ -\x23\x60\xd2\xec\x6c\xdd\xeb\x0b\xf0\x79\x23\xc0\x5d\x2b\x2b\x2b\ -\x23\x57\xb9\xf5\x10\x20\x12\x9c\x5b\x03\x7f\x43\x7c\xad\xf3\xb3\ -\xb7\xb6\xdb\xed\x3f\x5c\x46\x57\x7f\x1b\x24\x09\x73\xd9\xaf\xeb\ -\x7c\x74\x73\xb7\xdb\xfd\xc5\x75\x7c\xc5\x2b\x80\x84\xd9\xe7\x9f\ -\x12\x9d\xef\x5f\x5e\x5e\x3e\xed\xa3\x82\x2a\x57\x00\x01\x63\xf2\ -\x3f\x13\xfa\x40\x27\x8e\x13\x5f\x45\x54\xb2\x02\xa6\x57\xfa\x62\ -\xf6\xef\xa2\x79\x4b\x14\x45\xdf\xf8\xac\xc5\xbf\x00\x01\x69\xe6\ -\x8e\x34\x65\x35\x8e\x97\xbe\xf0\x5d\x8e\xef\x97\xa3\x04\x8d\x4c\ -\x21\x78\xcf\x72\x18\xae\xf9\xad\x65\x82\xef\x97\xa3\x46\x1e\x81\ -\x87\xa3\x68\xe9\x43\xbf\x75\x9c\xc7\x9b\x00\x11\x34\x8c\x63\xe0\ -\x93\x51\xd4\x7e\xd3\x57\x0d\x65\x78\xb9\x0b\xd0\x5c\xf6\x80\xf0\ -\xa5\x4e\xd4\xaa\xfc\x6b\x32\x1e\x56\x00\x03\x29\x34\x37\x04\xdf\ -\x89\xa2\xd6\xe3\x2e\x9a\x9b\x59\x71\x2d\xc0\xd8\xdf\x13\xf8\x28\ -\x0c\x5b\x0f\xd6\x61\xf2\x80\x5b\x01\x01\x8a\x5b\x5c\xe2\x84\xd6\ -\xf9\xdd\x24\x73\x87\xb9\x33\xe1\x52\x40\xf1\x91\xc6\x57\xa3\x3f\ -\x37\x6f\x8f\xe3\x78\xd3\x61\xe6\xcc\xf8\xd9\x0a\x0b\xbe\xcb\xf3\ -\x1d\x07\xf7\xee\x0d\x7f\xf5\x92\x37\x03\x3e\x6e\x83\xc3\xf1\x38\ -\xd8\xbf\x67\xcf\x95\x3f\x78\xc8\x9a\x19\x9b\x02\xca\x9e\xe0\xff\ -\x04\x19\x1f\xe8\x76\x5b\x03\x8b\x39\x56\x71\xf5\x93\x19\x00\xf8\ -\x2d\xa0\x1c\xec\x74\x3a\xdf\xda\xca\x70\x81\xa3\x9f\xcc\x50\x08\ -\xde\x11\x86\xe1\x97\xb6\xc6\x77\x85\x35\x01\x01\x79\x18\xe0\x18\ -\xc0\x98\xe0\xb3\x51\xb4\xf4\x99\xad\xb1\xe7\xcc\x99\x33\xc7\x15\ -\x7f\x01\x49\x16\x4b\x51\x69\x18\xd5\x52\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\x97\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ -\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\x18\x8c\x26\x13\x64\x85\x8c\ -\x89\x94\xd5\x18\xc2\x74\xfc\xf7\xb1\xae\x8d\x44\x46\x91\xd5\x91\ -\xd5\xce\xc6\x32\x0d\xdb\xbc\xd7\x74\x07\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x00\x00\xc0\xcd\xfa\x8c\x86\x74\x5e\x41\xfe\ -\xed\x02\xdd\xeb\x04\xae\xa2\x49\x76\xdf\x00\x00\x00\x00\x49\x45\ -\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x0c\xd6\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ -\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ -\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ -\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ -\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ -\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ -\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ -\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ -\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ -\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ -\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ -\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ -\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ -\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ -\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ -\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ -\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ -\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ -\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ -\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ -\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ -\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ -\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ -\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ -\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ -\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ -\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ -\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ -\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ -\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ -\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ -\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ -\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ -\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ -\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ -\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ -\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ -\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ -\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ -\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ -\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ -\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ -\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ -\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ -\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ -\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ -\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ -\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ -\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ -\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ -\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ -\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ -\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ -\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ -\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ -\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ -\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ -\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ -\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ -\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ -\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ -\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ -\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ -\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ -\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ -\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ -\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ -\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ -\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ -\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ -\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ -\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ -\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ -\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ -\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ -\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ -\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ -\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ -\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ -\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ -\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ -\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ -\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ -\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ -\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ -\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ -\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ -\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ -\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ -\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ -\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ -\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ -\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ -\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ -\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ -\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ -\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ -\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ -\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ -\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ -\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ -\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ -\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ -\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ -\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ -\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ -\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ -\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ -\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ -\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ -\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ -\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ -\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ -\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ -\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ -\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ -\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ -\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ -\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ -\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ -\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ -\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ -\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ -\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ -\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ -\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ -\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ -\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ -\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ -\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ -\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ -\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ -\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ -\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ -\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ -\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ -\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ -\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ -\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ -\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ -\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ -\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ -\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ -\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ -\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ -\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ -\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ -\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ -\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ -\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ -\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ -\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ -\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ -\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ -\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ -\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ -\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ -\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ -\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ -\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ -\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ -\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ -\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ -\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ -\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ -\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ -\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ -\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ -\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ -\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ -\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ -\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ -\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ -\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ -\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ -\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ -\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ -\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ -\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ -\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ -\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ -\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ -\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ -\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ -\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ -\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ -\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ -\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ -\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ -\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ -\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ -\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ -\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ -\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ -\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ -\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ -\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ -\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ -\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ -\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ -\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ -\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ -\x44\xae\x42\x60\x82\ -\x00\x00\x02\x0b\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbd\x49\x44\x41\x54\x58\x85\xed\ -\x94\x3d\x6b\x14\x51\x18\x85\x9f\x73\xd7\x42\x09\x88\x36\x16\x16\ -\x41\xc1\x5a\x6c\x92\x45\x04\x3b\x59\x91\xe0\xba\x8b\xa6\x51\xc1\ -\x7f\x90\x5f\x20\xa8\xbf\x40\x6c\x52\xda\x58\x28\xb2\x89\x41\x0b\ -\x43\x4a\x91\x24\x6b\xa3\x29\x52\x59\xd8\x28\x58\x25\xa8\x91\x90\ -\xdd\xbd\xc7\x62\x66\xdd\x65\xa3\x9b\x99\xf5\x23\xcd\x3c\x30\xf0\ -\x32\xdc\x39\xe7\xdc\xfb\xbe\x77\xa0\xa0\xa0\xa0\x60\x9f\x51\xb7\ -\x98\x9c\x8b\x1b\x82\x23\xff\xc3\xd4\xb0\xd9\xac\x87\xa3\x00\xe1\ -\x67\x12\xf5\xea\x7f\x4d\xbf\x57\xaf\x68\xe9\x24\xb0\x92\x26\x04\ -\x13\x81\xce\xdf\x78\x6c\xa2\x7b\xfe\xcb\xa9\x57\x12\xa6\x3f\xd9\ -\xe9\x45\x8f\x1d\xfa\xee\x06\xa6\x82\x8d\x51\x94\x30\x7f\x86\xc0\ -\x01\x84\xe1\xe5\xf6\x98\xae\xae\x55\xb4\xb5\xeb\x04\x00\xd6\x2a\ -\xda\xfa\xda\xd2\x65\xe4\x27\x48\x48\x0e\x83\x21\xf3\x60\x23\x43\ -\x48\x24\xfc\xf8\x5b\x5b\xd5\x7e\xf3\x5d\x01\x00\xd6\xa7\xb5\x33\ -\xde\x0a\xd7\x6d\xcf\xa6\xde\xc1\xce\x1f\xc2\x20\x89\x20\xc0\xf6\ -\xec\x78\x3b\xdc\x58\x9f\xd6\xce\xe0\xba\xdf\x0b\xdb\x2a\x3f\x8b\ -\x77\xb1\x6e\x27\x82\x8a\xc2\x99\xda\x61\x24\xe1\x74\x73\xbe\xb7\ -\x5a\x0b\x77\x90\x7e\xf9\xed\x9e\x3b\x2b\xcf\x7b\x06\xfb\x7e\x37\ -\x15\x28\x0e\x37\x77\x10\x52\x22\xae\x99\x95\xba\x1e\x0c\x5b\x9f\ -\xe9\x68\xcb\x0d\xdf\x44\x7e\x08\x94\x86\x85\xe8\x33\xef\x20\xdd\ -\x5a\xad\xe9\xd1\x5e\xda\x99\x7b\x3b\x39\xe7\x29\xe1\xa7\xc0\x41\ -\x92\x9b\x3a\x18\xa2\x3b\xb0\xdb\x46\xd7\x9a\x75\xbd\xc8\xa2\x9b\ -\x6b\xb8\x26\x1a\x3e\x1f\xe4\xe7\xc0\x61\x83\x95\x86\x30\x04\x25\ -\x5a\x5f\x1c\x34\xd5\xbc\xa2\x57\x59\x35\x73\x4f\xf7\xc4\xbc\xcf\ -\x04\x7b\x11\x38\x86\x30\xd1\xdd\x96\x7f\x8e\xd2\xc5\x37\x35\xbd\ -\xcd\xa3\x37\xd2\x1d\x3f\xbb\xe0\x53\xb1\xe3\x25\xe0\x44\xfa\xea\ -\x43\x28\xe9\xc2\x72\x55\xef\xf3\x6a\x8d\xfc\x93\x39\xb7\xe0\xe3\ -\xed\x8e\x3f\x02\xef\x0e\x94\x74\xe9\x75\x55\x9f\x46\xd5\x2a\x28\ -\x28\x28\xd8\x57\x7e\x00\xa4\xf8\xb1\x06\x78\x8b\xc7\xb8\x00\x00\ -\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -\x00\x00\x00\xcf\ -\x89\ -\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ -\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ -\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ -\x01\x95\x2b\x0e\x1b\x00\x00\x00\x81\x49\x44\x41\x54\x58\x85\xed\ -\xd2\x31\x0e\x82\x50\x10\x84\xe1\x7f\x9f\x77\x20\xe1\x36\xaf\xe0\ -\x08\xf6\x16\x5a\x70\x0b\xc2\x2d\x28\xb0\xb5\xb5\xb5\x31\xe1\x36\ -\x26\xdc\x01\x96\x0a\x88\x98\xd8\xf1\x68\xe6\xeb\x76\xb3\xc9\x4c\ -\xb1\x20\x22\x22\x72\x30\xdb\xce\x31\x56\xa7\x3d\x03\xbb\xae\x1e\ -\x00\xff\x29\x50\x9c\x6f\xd1\x9c\x07\x90\xef\x59\x00\xe8\xc7\xd1\ -\x2f\xef\xe7\xfd\x05\x10\x96\xb5\xd3\x24\x08\x07\xc8\x42\xb0\x76\ -\x1e\xc2\xbf\xcb\x14\xd6\x02\x46\x09\x7c\x12\x64\xf6\x8e\x5d\xd7\ -\xd8\x6f\xc9\x9f\x50\x44\x44\xe4\x70\x13\x6a\x59\x1a\x0e\xce\xfb\ -\x3e\xfc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ -" - -qt_resource_name = b"\ -\x00\x09\ -\x09\x5f\x97\x13\ -\x00\x71\ -\x00\x73\x00\x73\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x73\ -\x00\x0a\ -\x09\x24\x4d\x25\ -\x00\x71\ -\x00\x64\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\ -\x00\x04\ -\x00\x06\xa8\x8b\ -\x00\x64\ -\x00\x61\x00\x72\x00\x6b\ -\x00\x0d\ -\x0d\x36\x0c\x63\ -\x00\x64\ -\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\x00\x2e\x00\x71\x00\x73\x00\x73\ -\x00\x02\ -\x00\x00\x07\x83\ -\x00\x72\ -\x00\x63\ -\x00\x17\ -\x0e\xfe\x32\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x27\ -\x0d\x0d\x92\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x0c\x09\x66\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x01\x87\xae\x67\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x20\ -\x0e\xfe\x76\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x09\xcb\xcc\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x18\ -\x07\x8b\xec\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\x9d\x97\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x09\x07\x81\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x09\x0d\xa6\xc7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x07\x36\x1b\x47\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0c\xeb\x5f\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x10\ -\x05\x3e\x39\x67\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x00\x4f\x29\xc7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x04\x24\xf6\xe7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x27\ -\x0e\x3d\xd7\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x07\x50\x2b\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\x6c\x22\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x03\xae\x62\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0e\x19\x8b\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x04\xf8\x32\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x02\x75\x51\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x21\ -\x01\xf6\xa2\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x18\ -\x07\x83\xfe\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x01\xe9\xfd\xe7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x08\xc8\x96\xe7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x14\ -\x07\xec\xd1\xc7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x03\x94\x39\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x29\ -\x09\x81\xd3\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x08\x8f\x96\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x17\ -\x07\x06\x3d\xa7\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x0e\x35\xf3\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x05\x35\xb6\x67\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x00\x10\xb9\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0b\x46\x72\x87\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x09\xc8\xa4\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0c\xa5\xc5\x27\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0a\x12\x4a\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x06\x16\x25\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x04\x8d\x48\xc7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x02\xb6\xb5\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x0c\xa4\x6f\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x00\x6c\xa3\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x0e\x0c\xda\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x25\ -\x06\x6c\x47\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x01\x0e\xe5\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0c\xd5\x5a\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x07\x86\x4e\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x00\x68\xca\xe7\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x1a\ -\x0f\x5a\xb4\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x05\x7a\xd3\x67\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x2c\ -\x0c\xa4\x5a\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x24\ -\x05\x94\xa0\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0f\x1e\x9b\x47\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x01\x41\xee\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x14\ -\x00\x2e\x0a\x07\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x03\x9f\x72\x87\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x0f\x35\xfb\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x0f\xd0\x9c\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x08\xfa\xe1\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\x0d\x28\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x0f\xd7\x34\x67\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0c\x24\xec\x07\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x21\ -\x05\x70\x30\x27\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x18\ -\x06\x60\x39\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x0a\xe5\x6c\x07\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1a\ -\x0a\xa0\x05\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0f\x7e\x6f\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0c\x60\x8e\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0b\x59\x6e\x87\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x02\x0d\xa6\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x0e\x31\x43\xa7\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x0c\x24\x39\x47\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x21\ -\x0e\xf1\x37\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1b\ -\x0b\xea\x1b\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x05\x2a\x70\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x20\ -\x09\xd7\x1f\xa7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x01\xc7\x25\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x04\x3c\x09\xc7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x0d\xfd\xa2\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x0c\xe2\x68\x67\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x06\x6d\x9b\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x0f\x80\x4f\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0e\x26\x93\xe7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x06\x14\xad\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x00\x44\xa0\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x07\xa5\xb1\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x04\xce\xfa\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x24\ -\x04\x0b\x8d\x27\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x04\x34\xf0\xc7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0f\xac\xe3\xc7\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x0b\x2d\x81\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x0a\x7a\x87\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x06\xf8\x08\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x01\x40\x2d\xa7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xb5\x9d\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x17\ -\x0f\x18\x45\x87\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x05\xe4\x2d\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x07\xac\x39\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x0a\x19\xf4\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x08\x8a\x08\x27\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x16\ -\x0a\x1a\xd6\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xb1\x94\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x1e\ -\x0c\xd2\xb9\x87\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x08\x21\xa7\xc7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x05\x12\xcf\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x04\x73\x5f\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x08\x2e\xd3\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x00\x06\x3d\xc7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0a\x14\xed\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0d\x33\x2d\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0b\x78\x08\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x07\x14\x6d\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1f\ -\x02\x4f\x6a\xa7\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x01\xf6\xff\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1e\ -\x05\x75\xad\x27\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x09\x2e\xa9\x47\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x05\x76\x1e\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1c\ -\x0c\xfb\xa0\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x01\x75\xcc\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x00\xa7\x99\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x15\ -\x06\x62\x08\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x06\xf2\x1a\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1a\ -\x05\x28\x8d\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x24\ -\x05\xed\xfa\xe7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x02\x48\x15\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0d\ -\x0b\x72\x3d\x07\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xb3\x4c\x27\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x0e\ -\x06\x0c\xe6\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x0f\x79\xa3\xc7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x03\x43\xb9\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1b\ -\x0a\xfb\x2d\x27\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ -\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x04\x9c\xa4\xa7\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0e\x98\x18\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ -\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x06\x43\xc6\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x04\x64\xf7\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x05\x11\xe0\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x06\x75\x64\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x2b\ -\x03\xd2\xba\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0f\x9a\xe5\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x29\ -\x09\xe4\xb0\x07\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x25\ -\x08\x07\x7e\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x06\xa7\x5a\x47\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x1c\ -\x08\xb5\x77\x67\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x23\ -\x03\xa5\x91\x47\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x17\ -\x0d\xdf\xcf\xa7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x0b\x23\x21\x67\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x16\ -\x07\x09\xf8\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x02\x38\x25\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x0b\x48\x50\x87\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x27\ -\x0c\xeb\xe5\x67\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x03\xf7\x18\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1f\ -\x0a\xae\x27\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0a\x27\x78\x07\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x13\ -\x0b\x4e\x57\xa7\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x13\ -\x00\xcf\x5c\xc7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ -\x00\x6e\x00\x67\ -\x00\x1a\ -\x07\x88\x25\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x11\ -\x08\xfc\x49\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x14\ -\x0a\x20\x6e\x07\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x0e\ -\x0d\x4e\x71\x87\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x00\xd6\x25\xc7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1a\ -\x0e\xbc\xc3\x67\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x09\x5e\xb0\x07\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x03\x1c\x93\x87\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x09\x2f\xda\x87\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ -\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x06\x53\x25\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0c\x33\x94\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x0f\x96\x71\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x10\ -\x00\x55\x62\x07\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x00\x38\x7f\xa7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x0a\xd8\x81\x27\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x00\x6f\x04\x87\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x21\ -\x0a\x51\x5f\x47\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x11\ -\x0b\xda\x30\xa7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\ -\x00\x1c\ -\x08\x3f\xda\x67\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x07\x4b\x88\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ -\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x01\xe0\x4a\x07\ -\x00\x72\ -\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x22\ -\x04\x9a\x03\x67\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x2a\ -\x0f\xc4\xf7\x07\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x06\x65\x89\xe7\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x04\x90\x0a\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x07\x5b\xb0\x67\ -\x00\x6c\ -\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x01\x15\x51\xe7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ -\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0f\ -\x0f\x2c\x24\xc7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0b\xf3\xab\x27\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\ -\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x08\xe1\xf6\xc7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ -\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x28\ -\x0f\x63\x53\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ -\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x15\ -\x0d\x86\xf9\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\ -\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x00\xc1\x23\x67\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x0d\x78\xb6\x87\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x24\ -\x05\x98\x88\x87\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ -\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x0f\xfb\x22\x07\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ -\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\ -\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x0b\x8a\x15\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0f\xff\xfc\x07\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x26\ -\x0f\x35\xf0\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ -\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1e\ -\x00\x4f\xcb\xe7\ -\x00\x63\ -\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ -\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0b\x9d\x16\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1d\ -\x06\xba\x02\xa7\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ -\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x19\ -\x07\xb7\xa1\x47\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ -\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x20\ -\x07\x4e\x5a\xc7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x17\ -\x0b\x9d\x4d\x67\ -\x00\x62\ -\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ -\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x0c\ -\x0b\xd0\x7a\xe7\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x1b\ -\x02\xd4\x90\x87\ -\x00\x74\ -\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ -\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x12\ -\x04\xa2\xb3\x27\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ -\x00\x67\ -\x00\x29\ -\x08\x67\xa4\xa7\ -\x00\x74\ -\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ -\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ -\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x18\ -\x08\xd2\xa3\x27\ -\x00\x62\ -\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ -\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ -\x00\x14\ -\x06\xe9\x8f\x67\ -\x00\x61\ -\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ -\x00\x70\x00\x6e\x00\x67\ -\x00\x1c\ -\x00\xf3\x26\x27\ -\x00\x77\ -\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ -\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ -" - -qt_resource_struct_v1 = b"\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ -\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ -\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ -\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ -\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ -\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ -\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ -\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ -\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ -\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ -\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ -\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ -\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ -\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ -\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ -\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ -\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ -\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ -\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ -\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ -\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ -\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ -\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ -\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ -\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ -\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ -\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ -\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ -\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ -\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ -\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ -\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ -\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ -\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ -\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ -\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ -\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ -\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ -\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ -\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ -\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ -\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ -\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ -\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ -\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ -\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ -\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ -\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ -\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ -\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ -\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ -\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ -\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ -\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ -\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ -\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ -\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ -\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ -\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ -\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ -\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ -\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ -\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ -\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ -\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ -\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ -\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ -\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ -\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ -\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ -\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ -\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ -\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ -\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ -\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ -\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ -\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ -\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ -\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ -\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ -\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ -\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ -\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ -\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ -\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ -\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ -\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ -\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ -\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ -\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ -\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ -\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ -\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ -\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ -\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ -\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ -\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ -\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ -\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ -\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ -\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ -\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ -\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ -\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ -\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ -\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ -\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ -\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ -\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ -\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ -\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ -\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ -\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ -\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ -\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ -\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ -\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ -\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ -\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ -\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ -\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ -\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ -\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ -\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ -\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ -\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ -\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ -\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ -\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ -\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ -\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ -\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ -\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ -\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ -\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ -\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ -\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ -\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ -\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ -\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ -\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ -\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ -\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ -\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ -\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ -\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ -\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ -\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ -\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ -\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ -\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ -\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ -\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ -\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ -\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ -\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ -\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ -\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ -\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ -\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ -\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ -\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ -\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ -\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ -\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ -\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ -\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ -\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ -\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ -\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ -\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ -\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ -\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ -\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ -\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ -\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ -\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ -\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ -\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ -\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ -\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ -\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ -\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ -\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ -\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ -\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ -\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ -\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ -\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ -\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ -\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ -\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ -\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ -\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ -\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ -\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ -\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ -\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ -\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ -\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ -\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ -\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ -\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ -\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ -\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ -\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ -\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ -\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ -\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ -\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ -\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ -\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ -" - -qt_resource_struct_v2 = b"\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ -\x00\x00\x01\x81\x15\x91\x87\xb0\ -\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ -\x00\x00\x01\x81\x15\x91\x88\x41\ -\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ -\x00\x00\x01\x81\x15\x91\x87\x94\ -\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ -\x00\x00\x01\x81\x15\x91\x86\x7f\ -\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ -\x00\x00\x01\x81\x15\x91\x84\xf5\ -\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ -\x00\x00\x01\x81\x15\x91\x85\x87\ -\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ -\x00\x00\x01\x81\x15\x91\x86\x4c\ -\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ -\x00\x00\x01\x81\x15\x91\x88\x2e\ -\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ -\x00\x00\x01\x81\x15\x91\x85\xba\ -\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ -\x00\x00\x01\x81\x15\x91\x87\xe7\ -\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ -\x00\x00\x01\x81\x15\x91\x88\x51\ -\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ -\x00\x00\x01\x81\x15\x91\x88\x3d\ -\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ -\x00\x00\x01\x81\x15\x91\x85\x07\ -\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ -\x00\x00\x01\x81\x15\x91\x86\x7c\ -\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ -\x00\x00\x01\x81\x15\x91\x85\xd5\ -\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ -\x00\x00\x01\x81\x15\x91\x88\x67\ -\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ -\x00\x00\x01\x81\x15\x91\x86\x10\ -\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ -\x00\x00\x01\x81\x15\x91\x85\x6a\ -\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ -\x00\x00\x01\x81\x15\x91\x85\xda\ -\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ -\x00\x00\x01\x81\x15\x91\x87\x84\ -\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ -\x00\x00\x01\x81\x15\x91\x88\x17\ -\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ -\x00\x00\x01\x81\x15\x91\x88\x57\ -\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ -\x00\x00\x01\x81\x15\x91\x87\xaa\ -\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ -\x00\x00\x01\x81\x15\x91\x88\x33\ -\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ -\x00\x00\x01\x81\x15\x91\x86\x4c\ -\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ -\x00\x00\x01\x81\x15\x91\x87\xfb\ -\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ -\x00\x00\x01\x81\x15\x91\x87\x75\ -\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ -\x00\x00\x01\x81\x15\x91\x85\xf9\ -\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ -\x00\x00\x01\x81\x15\x91\x88\x13\ -\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ -\x00\x00\x01\x81\x15\x91\x87\x4e\ -\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ -\x00\x00\x01\x81\x15\x91\x85\xf9\ -\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ -\x00\x00\x01\x81\x15\x91\x86\x2b\ -\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ -\x00\x00\x01\x81\x15\x91\x87\x88\ -\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ -\x00\x00\x01\x81\x15\x91\x87\xb5\ -\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ -\x00\x00\x01\x81\x15\x91\x88\x7c\ -\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ -\x00\x00\x01\x81\x15\x91\x88\x62\ -\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ -\x00\x00\x01\x81\x15\x91\x87\x69\ -\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ -\x00\x00\x01\x81\x15\x91\x84\xbb\ -\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ -\x00\x00\x01\x81\x15\x91\x85\x52\ -\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ -\x00\x00\x01\x81\x15\x91\x84\xcb\ -\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ -\x00\x00\x01\x81\x15\x91\x85\xa9\ -\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ -\x00\x00\x01\x81\x15\x91\x88\x39\ -\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ -\x00\x00\x01\x81\x15\x91\x85\xf9\ -\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ -\x00\x00\x01\x81\x15\x91\x87\xc3\ -\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ -\x00\x00\x01\x81\x15\x91\x86\x6b\ -\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ -\x00\x00\x01\x81\x15\x91\x86\xdd\ -\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ -\x00\x00\x01\x81\x15\x91\x87\xec\ -\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ -\x00\x00\x01\x81\x15\x91\x86\xdd\ -\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ -\x00\x00\x01\x81\x15\x91\x87\xd5\ -\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ -\x00\x00\x01\x81\x15\x91\x84\x48\ -\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ -\x00\x00\x01\x81\x15\x91\x84\x87\ -\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ -\x00\x00\x01\x81\x15\x91\x85\x1a\ -\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ -\x00\x00\x01\x81\x15\x91\x85\x2e\ -\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ -\x00\x00\x01\x81\x15\x91\x85\x34\ -\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ -\x00\x00\x01\x81\x15\x91\x87\x61\ -\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ -\x00\x00\x01\x81\x15\x91\x87\x23\ -\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ -\x00\x00\x01\x81\x15\x91\x86\x13\ -\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ -\x00\x00\x01\x81\x15\x91\x88\x4e\ -\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ -\x00\x00\x01\x81\x15\x91\x88\x75\ -\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ -\x00\x00\x01\x81\x15\x91\x84\x65\ -\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ -\x00\x00\x01\x81\x15\x91\x85\x27\ -\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ -\x00\x00\x01\x81\x15\x91\x86\x4c\ -\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ -\x00\x00\x01\x81\x15\x91\x88\x5e\ -\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ -\x00\x00\x01\x81\x15\x91\x87\x5d\ -\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ -\x00\x00\x01\x81\x15\x91\x85\xbd\ -\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ -\x00\x00\x01\x81\x15\x91\x87\x58\ -\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ -\x00\x00\x01\x81\x15\x91\x86\x1f\ -\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ -\x00\x00\x01\x81\x15\x91\x88\x6b\ -\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ -\x00\x00\x01\x81\x15\x91\x87\x90\ -\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ -\x00\x00\x01\x81\x15\x91\x85\x1d\ -\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ -\x00\x00\x01\x81\x15\x91\x85\x0a\ -\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ -\x00\x00\x01\x81\x15\x91\x85\x31\ -\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ -\x00\x00\x01\x81\x15\x91\x84\x8c\ -\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ -\x00\x00\x01\x81\x15\x91\x85\xe9\ -\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ -\x00\x00\x01\x81\x15\x91\x84\xdb\ -\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ -\x00\x00\x01\x81\x15\x91\x85\x46\ -\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ -\x00\x00\x01\x81\x15\x91\x87\xe3\ -\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ -\x00\x00\x01\x81\x15\x91\x87\x1b\ -\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ -\x00\x00\x01\x81\x15\x91\x87\x7d\ -\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ -\x00\x00\x01\x81\x15\x91\x85\x7d\ -\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ -\x00\x00\x01\x81\x15\x91\x86\x28\ -\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ -\x00\x00\x01\x81\x15\x91\x87\xa3\ -\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ -\x00\x00\x01\x81\x15\x91\x85\xda\ -\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ -\x00\x00\x01\x81\x15\x91\x86\xdd\ -\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ -\x00\x00\x01\x81\x15\x91\x87\x48\ -\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ -\x00\x00\x01\x81\x15\x91\x84\x7c\ -\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ -\x00\x00\x01\x81\x15\x91\x85\x4f\ -\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ -\x00\x00\x01\x81\x15\x91\x87\x0c\ -\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ -\x00\x00\x01\x81\x15\x91\x86\x8f\ -\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ -\x00\x00\x01\x81\x15\x91\x88\x0d\ -\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ -\x00\x00\x01\x81\x15\x91\x85\x93\ -\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ -\x00\x00\x01\x81\x15\x91\x86\x7f\ -\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ -\x00\x00\x01\x81\x15\x91\x85\x54\ -\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ -\x00\x00\x01\x81\x15\x91\x88\x2b\ -\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ -\x00\x00\x01\x81\x15\x91\x86\x6b\ -\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ -\x00\x00\x01\x81\x15\x91\x88\x5b\ -\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ -\x00\x00\x01\x81\x15\x91\x88\x4a\ -\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ -\x00\x00\x01\x81\x15\x91\x84\x72\ -\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ -\x00\x00\x01\x81\x15\x91\x88\x70\ -\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ -\x00\x00\x01\x81\x15\x91\x87\x66\ -\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ -\x00\x00\x01\x81\x15\x91\x87\x72\ -\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ -\x00\x00\x01\x81\x15\x91\x86\x8f\ -\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ -\x00\x00\x01\x81\x15\x91\x85\x74\ -\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ -\x00\x00\x01\x81\x15\x91\x87\x99\ -\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ -\x00\x00\x01\x81\x15\x91\x85\xc6\ -\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ -\x00\x00\x01\x81\x15\x91\x85\xe9\ -\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ -\x00\x00\x01\x81\x15\x91\x84\xac\ -\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ -\x00\x00\x01\x81\x15\x91\x84\x84\ -\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ -\x00\x00\x01\x81\x15\x91\x88\x79\ -\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ -\x00\x00\x01\x81\x15\x91\x87\x6e\ -\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ -\x00\x00\x01\x81\x15\x91\x85\x8b\ -\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ -\x00\x00\x01\x81\x15\x91\x85\xda\ -\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ -\x00\x00\x01\x81\x15\x91\x84\xac\ -\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ -\x00\x00\x01\x81\x15\x91\x85\x0d\ -\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ -\x00\x00\x01\x81\x15\x91\x85\x2a\ -\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ -\x00\x00\x01\x81\x15\x91\x85\x17\ -\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ -\x00\x00\x01\x81\x15\x91\x84\xcb\ -\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ -\x00\x00\x01\x81\x15\x91\x86\x7f\ -\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ -\x00\x00\x01\x81\x15\x91\x87\x3e\ -\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ -\x00\x00\x01\x81\x15\x91\x87\x53\ -\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ -\x00\x00\x01\x81\x15\x91\x84\xbb\ -\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ -\x00\x00\x01\x81\x15\x91\x85\x9c\ -\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ -\x00\x00\x01\x81\x15\x91\x84\x9c\ -\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ -\x00\x00\x01\x81\x15\x91\x88\x09\ -\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ -\x00\x00\x01\x81\x15\x91\x87\x79\ -\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ -\x00\x00\x01\x81\x15\x91\x87\x80\ -\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ -\x00\x00\x01\x81\x15\x91\x87\x8c\ -\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ -\x00\x00\x01\x81\x15\x91\x86\xfc\ -\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ -\x00\x00\x01\x81\x15\x91\x88\x1f\ -\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ -\x00\x00\x01\x81\x15\x91\x84\xea\ -\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ -\x00\x00\x01\x81\x15\x91\x86\x2d\ -\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ -\x00\x00\x01\x81\x15\x91\x85\xb1\ -\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ -\x00\x00\x01\x81\x15\x91\x84\xdb\ -\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ -\x00\x00\x01\x81\x15\x91\x84\xdb\ -\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ -\x00\x00\x01\x81\x15\x91\x84\xac\ -\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ -\x00\x00\x01\x81\x15\x91\x86\xcd\ -\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ -\x00\x00\x01\x81\x15\x91\x85\x3e\ -\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ -\x00\x00\x01\x81\x15\x91\x86\x6b\ -\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ -\x00\x00\x01\x81\x15\x91\x86\xbe\ -\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ -\x00\x00\x01\x81\x15\x91\x86\x9e\ -\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ -\x00\x00\x01\x81\x15\x91\x86\x0d\ -\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ -\x00\x00\x01\x81\x15\x91\x86\xec\ -\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ -\x00\x00\x01\x81\x15\x91\x87\xd0\ -\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ -\x00\x00\x01\x81\x15\x91\x88\x46\ -\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ -\x00\x00\x01\x81\x15\x91\x85\xc9\ -\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ -\x00\x00\x01\x81\x15\x91\x86\x16\ -\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ -\x00\x00\x01\x81\x15\x91\x86\xae\ -\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ -\x00\x00\x01\x81\x15\x91\x87\x43\ -\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ -\x00\x00\x01\x81\x15\x91\x84\x81\ -\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ -\x00\x00\x01\x81\x15\x91\x85\xcd\ -\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ -\x00\x00\x01\x81\x15\x91\x84\x8c\ -\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ -\x00\x00\x01\x81\x15\x91\x86\x3d\ -\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ -\x00\x00\x01\x81\x15\x91\x84\xfd\ -\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ -\x00\x00\x01\x81\x15\x91\x87\x9f\ -\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ -\x00\x00\x01\x81\x15\x91\x86\x2d\ -\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ -\x00\x00\x01\x81\x15\x91\x85\x9f\ -\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ -\x00\x00\x01\x81\x15\x91\x86\x5c\ -\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ -\x00\x00\x01\x81\x15\x91\x87\xa7\ -\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ -\x00\x00\x01\x81\x15\x91\x86\x2d\ -\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ -\x00\x00\x01\x81\x15\x91\x87\x32\ -\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ -\x00\x00\x01\x81\x15\x91\x84\xbb\ -\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ -\x00\x00\x01\x81\x15\x91\x88\x1b\ -\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ -\x00\x00\x01\x81\x15\x91\x87\xdd\ -\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ -\x00\x00\x01\x81\x15\x91\x88\x36\ -\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ -\x00\x00\x01\x81\x15\x91\x87\xd9\ -\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ -\x00\x00\x01\x81\x15\x91\x84\x53\ -\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ -\x00\x00\x00\x00\x00\x00\x00\x00\ -\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ -\x00\x00\x01\x81\x15\x91\x89\x29\ -" - -qt_version = [int(v) for v in QtCore.qVersion().split('.')] -if qt_version < [5, 8, 0]: - rcc_version = 1 - qt_resource_struct = qt_resource_struct_v1 -else: - rcc_version = 2 - qt_resource_struct = qt_resource_struct_v2 - -def qInitResources(): - QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) - -def qCleanupResources(): - QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) - -qInitResources() +# -*- coding: utf-8 -*- + +# Resource object code +# +# Created by: The Resource Compiler for PyQt5 (Qt v5.15.2) +# +# WARNING! All changes made in this file will be lost! + +from qtpy import QtCore + +qt_resource_data = b"\ +\x00\x00\x1a\xa6\ +\x00\ +\x00\xdc\x92\x78\x9c\xd5\x3d\x6b\x6f\xdb\x46\xb6\xdf\x0b\xf4\x3f\ +\xd0\x31\xb0\x68\xbb\x96\x6d\xc9\xb2\x63\xab\xe8\x07\x3b\x8f\x6e\ +\x80\x34\x4d\x6a\x77\x8b\x8b\xc5\x85\x41\x49\x94\xc5\x0d\x45\x2a\ +\x24\x15\xc7\x2d\xee\x7f\xbf\x33\x43\xce\x70\x1e\x67\x5e\x7c\xd8\ +\xa9\x81\xa6\xb6\x34\x73\xde\x73\xce\x3c\xce\x9c\x39\xfa\x21\x18\ +\xf5\xf7\xf3\xed\x37\xdf\x7e\x13\xa0\x9f\x3f\x2e\x7f\x7b\xf7\xe6\ +\xdd\xcf\x7b\xc1\xeb\x38\x89\x82\x45\x1e\x85\x65\xb4\x0c\xb6\x79\ +\x76\x97\x87\x9b\x4d\x58\xc6\x8b\x30\x49\x1e\x0e\x83\xcb\x24\x09\ +\x16\xeb\x30\xbd\x8b\x8a\x60\x13\x2e\xa3\x20\x4e\x83\x72\x1d\x17\ +\xc1\x0a\xf7\xbb\x8f\xd1\xd7\xf3\x28\x48\xb2\xa2\xdc\xa3\xa0\x5f\ +\xd4\xc0\xe6\x0f\xa8\x65\x14\x7c\x2a\x8b\xb0\x28\x82\x45\xb6\xd9\ +\xa2\x2e\x79\xf0\xf9\xf8\xf0\xe4\xf0\x98\x36\xbe\x41\x2d\x96\xd1\ +\x2a\x4e\xe3\x32\xce\xd2\x22\x08\xf3\x1a\x45\x14\x3c\xfb\xb4\x0c\ +\xf3\x8f\x45\xf9\x90\x44\x87\x9f\x8a\xe2\xf0\x96\xfc\x5a\x1c\x16\ +\x8b\xa2\x78\x16\x6c\xb2\xe5\x2e\x89\x30\x98\x1e\xa5\x13\xfc\x70\ +\xf4\xed\x37\x47\x3f\x04\x6f\xe3\xbb\x75\x19\x5c\x63\x7c\xc1\x28\ +\xf8\xf0\x12\xd1\x41\xfe\xb8\x5e\x47\x51\xe9\xa1\x8e\x1a\x1e\xa6\ +\xf2\x3a\x8a\x82\x0f\x65\xb0\xcc\x16\xbb\x4d\x94\x96\x21\x66\x77\ +\x56\x49\x61\x14\xac\xcb\x72\x5b\xcc\x8e\x8e\xd0\xb7\x87\x9f\xca\ +\xc3\x38\x3b\xfa\x54\x8e\x4e\x8f\x2a\x86\x31\xce\xc3\x75\xb9\x49\ +\x1c\xdb\x8e\xf2\x68\x15\xe5\x51\xba\x88\xbc\x7a\x45\x5f\xc2\xcd\ +\x16\xcb\xb7\xea\x34\x88\x5c\x7f\x8b\x0a\x24\xbf\x28\x89\xb0\x08\ +\x8a\x4e\x76\x8d\x29\x24\xe0\xca\x38\xbd\x0b\xa2\xcf\x51\xfe\x80\ +\xec\x12\xfd\xba\x8e\x92\x6d\x11\x94\x59\xb0\x4b\xe3\xd5\x43\x50\ +\x71\x18\x84\x8b\x3c\x43\x56\xb8\x8c\x57\x44\x36\x65\x90\x6d\xa3\ +\x3c\x24\x7d\x8b\x87\xa2\x8c\x36\xc5\x10\x2c\xff\x10\xfc\x85\xc5\ +\xbf\x0d\x97\x4b\x84\x69\x16\x1c\x6f\xbf\xfc\x88\x3f\xd8\x84\xf9\ +\x5d\x9c\x36\x7f\xcf\xb3\x7c\x19\xe5\xf2\xdf\x23\x42\xfb\x2c\x48\ +\xb3\x34\xe2\x3f\x8e\x37\xe1\x1d\xff\x71\xb6\x2b\x93\x38\x45\x9f\ +\x1c\xa3\x3f\xff\x0f\xf3\x81\x44\x5d\x6c\xa3\x45\xbc\x8a\x17\x41\ +\x4e\x64\xbe\xca\xf2\x46\xee\x71\x5a\xc4\x68\x28\x7f\xb8\xc9\xb2\ +\xe4\x2a\xcc\x09\xa9\xcd\x1f\x15\xcd\x32\x89\x12\x0f\x14\xcd\x87\ +\x3f\xe2\xe5\x9d\xd7\x98\x80\x7f\x86\x90\x3e\xa5\x8d\xf0\x33\x0f\ +\x17\x1f\xef\xf2\x6c\x97\x2e\x47\x8b\x2c\xc9\x90\xb0\xf7\xc7\x17\ +\x93\x93\xc9\x4b\x59\x01\x41\x91\x25\xf1\x32\xd8\x9f\x9e\x9e\x9e\ +\x9c\x4d\x21\xde\x83\x80\x42\x78\x75\xfc\x6a\xfc\xea\x84\x7c\x54\ +\x20\xe9\x2e\xf0\xa0\x1e\x01\x98\x4e\xa6\x67\xcf\x2f\x26\x52\x3b\ +\x05\x08\x91\x69\x4d\xf4\x6c\x19\x17\xe1\x3c\x41\x6e\xd4\x81\x7a\ +\xfa\xd1\xc5\xcb\xcb\x8b\xab\x53\x3b\x39\x93\xb3\xe9\xf9\xd9\x95\ +\x86\x1c\x06\x44\x20\x67\x16\xa3\x31\x32\xab\x5a\x1b\x88\x62\x8c\ +\x02\x9d\xd7\x19\x1a\xa4\xb3\x3d\x2b\x8c\xf1\xe5\xf3\xc9\xd5\x15\ +\x6f\x63\xbf\x84\x71\xfa\x47\x9c\x2e\xb3\xfb\xce\x2e\xe3\x06\xc7\ +\xae\x70\xf9\xdf\x5d\x81\xc6\x01\x8e\x32\xc5\x36\x89\xcb\x12\xc5\ +\xa5\x3a\xea\x20\x07\xf9\x11\xc5\x35\x4c\xf7\x01\x1a\x62\x65\xf0\ +\x89\xb6\xf8\xf6\x1b\x4f\x27\xba\xbf\x40\x58\xb2\x4d\xfc\x27\xb2\ +\x9d\xd1\xa7\x0d\x62\xe2\x9e\x30\x31\x88\xad\x37\x32\x9a\x21\x35\ +\x6d\x43\xe4\xdc\xd0\x90\xd7\xc9\x98\x33\x6e\xc0\xf4\x39\xd3\x2a\ +\xb6\xe1\x42\x30\x7d\x36\x16\x26\x8d\x1f\x80\x91\x57\x0a\xd7\x92\ +\x70\x76\xfc\xfc\xe2\xfc\x4a\x4b\x82\x60\x04\x5a\x04\x79\xfc\x67\ +\x86\x82\x69\x52\x61\x41\x6a\x2b\xd7\xb3\xe0\x54\xf0\xb2\xa3\x32\ +\xdb\x52\x6a\xd9\x67\xf3\xac\x44\x9a\x69\x3e\xae\x5d\xea\x2e\x4f\ +\xbe\x7b\x36\x3b\x42\xb3\x8d\xdb\x78\x81\xa6\x23\x47\x78\x06\x72\ +\x94\x2f\x8e\x4a\xe4\x1c\xe7\x61\x7e\xcb\x70\xdf\x22\xd6\xc8\x24\ +\xe9\x70\x9b\xde\x3d\xfb\xde\x42\x28\x6d\x5c\x91\xb9\x8e\xf0\xf4\ +\x42\xa1\x33\x89\x56\xa5\x42\x68\x5e\x35\x6d\x4f\x67\x23\x23\x91\ +\x52\x3c\xae\xb0\xcb\xbf\x89\xb7\x5d\x9d\x37\x06\xd7\x69\x68\x60\ +\xaa\xcb\x78\x3b\xc8\xb8\xa0\x3c\x5a\x3d\x16\xe8\xd5\x91\x94\xde\ +\xac\x82\x87\x6c\x87\xc2\xe8\x06\x99\x33\x71\x11\x95\xb9\xe2\xc9\ +\x32\x9a\x43\x94\x0f\x07\x1c\x58\x34\xdd\xc8\xd0\xec\xe3\x3e\xcb\ +\x3f\xe2\xa9\x45\x96\x06\x95\x31\x14\x84\x98\xc6\xd2\x59\xec\x26\ +\x93\x22\x02\xb9\x1e\x58\x07\x24\x54\xaf\xe2\x2f\x78\xc6\x3c\xcf\ +\x50\x8f\x2f\x41\x2d\x9f\x1a\x86\x12\x8d\x1a\x18\x19\x1e\xad\x98\ +\x22\xdc\x7f\x7f\xfc\x7c\x8a\x66\x7e\x9b\xf0\x21\x48\x23\xe4\x6f\ +\xf1\x94\xa8\x88\x82\xdf\x7e\xbe\xba\x24\x90\x98\x19\x5c\xa3\xd9\ +\xe8\xae\xc0\xb1\xbf\x93\xbc\x3b\x9b\x41\x41\xe8\x40\xe6\x3b\x88\ +\x21\x34\x5c\xfe\xc5\x6b\x62\x0c\x46\x7c\x24\x96\xd7\xf1\x17\x34\ +\x6f\xbc\xde\x3e\x60\x5d\xef\x5f\x8c\x27\xc7\x07\xe4\x7f\x63\xaa\ +\x4a\xa6\xf4\x19\xdc\x75\x7f\x72\x7c\x7a\x10\xdc\xaf\x51\xf0\x0b\ +\x98\x03\xa8\xd0\x16\x41\x3d\x40\xb1\x91\xe0\xe0\x58\x34\x1a\x69\ +\x08\xad\xe2\xa6\x48\x6e\x6d\x38\x52\xcb\xc0\x6a\xe6\xcc\x9f\x82\ +\x9c\x03\x73\x09\xee\xa3\xde\x6c\x74\xb9\xc3\xb1\x24\x28\xf3\x30\ +\x45\x71\x05\x2f\x51\x1e\xb0\x55\xa2\xf5\x22\x5a\x2d\x46\x24\x0a\ +\x57\xdd\x6b\x3b\x46\x7e\xef\xe4\x18\xe2\xf6\x6d\x38\x8f\x6a\x67\ +\xea\xa9\xa9\x06\x77\xc9\x7b\xc2\x17\xeb\x68\xf1\xf1\x0a\xb1\xd1\ +\xcd\xd2\x3a\x0f\x81\x05\xa6\x03\x89\x73\x90\x11\xc0\x98\xf4\x98\ +\x52\xf2\x33\x5c\x3a\x15\x98\xd6\x3a\x65\xeb\x0e\xe6\xcd\x6a\xb5\ +\x57\x21\x77\x2a\xce\x18\x58\xcc\x9d\x72\x13\x07\x4a\xd2\x6c\x85\ +\xd6\xc5\x85\xc1\xd4\x19\xed\xbd\xcc\x8f\x25\xe4\x33\xe4\xa3\xd1\ +\xe8\x64\x13\x26\x30\x20\xd3\xa8\x3d\xa6\x7c\xd5\xb3\x8d\x31\xc8\ +\x4f\x03\x72\xb6\x4b\x89\x56\x29\xa9\xb6\x10\x4e\x4d\xe0\x96\xf5\ +\x93\xa6\x18\x46\x1c\xd5\xa4\xeb\x20\xb0\xb4\x22\xe2\xb6\xb6\xda\ +\xa2\xb5\x63\xc1\x44\x2c\x87\x2e\x7f\x46\x6e\x09\x5a\x2f\x76\x44\ +\x35\xb7\x40\x49\x01\x38\x60\x6d\xa7\x26\x77\x25\xb9\xa8\xc8\x45\ +\x41\x3d\xab\xc7\x57\x39\x1d\x55\xd3\x42\x31\xe8\xb7\x08\x05\x87\ +\x4d\x9c\x86\x28\x96\xfa\xa1\x13\xfa\xfa\xe2\x6a\xcb\xa3\x00\xa4\ +\x35\xa7\x46\x23\x10\x5b\x9a\x4c\x4a\x6c\x29\x18\x4d\x4b\x86\x00\ +\x4b\xc1\x41\xf4\x67\xe4\x80\xb7\x5f\x41\x10\xc5\x81\x60\x3b\x54\ +\x10\x65\x4c\x12\x01\xae\xd0\xca\x6a\x74\x5f\x47\x86\x79\x96\x2c\ +\x75\x33\x2c\x65\xc1\x3d\xca\xc3\x65\xbc\x2b\x94\x30\xa9\xac\x00\ +\x49\x2c\x3d\x83\x97\xaf\x7c\xe8\xa1\x84\xcd\x66\x65\x5c\x26\xf5\ +\x30\x29\x76\x73\xa4\xd0\x32\xcf\x92\x11\x5a\x07\x92\x0d\xbd\x0a\ +\xc4\x8f\xd2\xb7\xdb\xac\x20\x3b\xf0\x68\x86\x94\x6d\x03\x1c\xf9\ +\x48\x8b\x2a\x04\xca\x91\x5c\x0c\x8c\xf4\xd3\x7a\xa9\x2a\x37\x26\ +\xf4\x8f\x60\x4a\x5d\xe2\x2e\xb4\x8a\x6f\xa6\x97\xee\xa1\x19\xc0\ +\x2a\x87\xe6\x1e\x42\x9c\x34\xc6\x8d\x48\xd9\xa8\x35\xb7\xa2\x5e\ +\xc0\xdc\xea\x51\x62\xb5\x99\x84\xa1\x62\x35\x84\xb5\x27\xbd\xb9\ +\x6b\xcd\x45\x67\x2e\x1a\x7b\xc4\xe0\x6d\x42\x3f\x48\xf0\xc6\x41\ +\xe0\x37\xe4\xd6\xb2\xab\x1d\xf2\x4f\x69\x97\x38\xd0\x39\x08\x60\ +\xf7\x9a\xcd\x09\x1d\x83\xc4\x01\x9e\xcf\x9e\xd6\x53\x1e\xab\x27\ +\xc0\x64\xe4\xd5\x58\x65\x03\x1c\x99\xd6\x35\x16\xdf\xb6\xe3\xf1\ +\x83\x3f\x75\x81\xc7\x69\x8d\x49\x98\x9a\xf3\x2a\x68\xb5\x6a\x15\ +\x82\x1c\x9f\xac\x5c\x75\x59\x3a\xc2\x88\x7d\x57\x8f\xc4\xec\xb5\ +\xe1\xc8\x86\x83\x79\x37\x6b\x43\xea\xe2\xac\x0d\xcd\x7e\x4e\x15\ +\xa0\x27\x83\xa0\xe3\xb3\x12\xe5\xe7\xfd\x64\x94\x9a\x30\xa5\xc1\ +\x6a\x8e\x54\x6d\x05\xe0\xa5\x5f\x47\xed\x3a\xea\x76\x58\xcd\xb6\ +\xd0\x2b\xac\xd5\xae\x04\xe8\x43\xdc\x2f\x51\xba\xeb\xbc\x5b\xde\ +\x43\x88\xdb\x20\x3a\x86\xda\x2d\xa7\x3c\xea\xbc\x31\x74\x3a\x3e\ +\x91\x42\x93\x79\x83\xd9\xf5\xec\x5c\x3e\x09\xac\x08\x83\x82\x19\ +\x87\x4f\x3a\x87\xa6\x9d\xf8\x0d\x75\xed\xa6\x30\xc7\x11\xef\x9f\ +\x05\x18\xd2\x49\xb8\xd4\xc1\x0c\xdd\x9c\x6b\xe0\x2e\x81\x8a\x10\ +\x61\x14\xaa\x74\xb4\xc6\x05\x2a\x4a\x5a\x7e\x1e\x6b\xe6\x28\x52\ +\x8a\x08\x26\xb8\x87\x1c\xb6\x5e\xc6\xcb\x60\x83\x45\x34\x45\x58\ +\xde\x5a\x89\x72\x99\x3f\xc0\x09\xe5\xf3\xe9\x78\xfa\xba\xd5\x40\ +\x51\x52\x01\xd8\x4c\x44\x8f\x8e\x3b\x97\xd7\x64\xa8\x54\x90\xa1\ +\xa1\x04\xd1\xcc\xdb\x64\x30\xc1\xff\x90\x5f\xce\xf9\x83\xa1\x22\ +\xca\x3f\x47\x64\x0e\x17\x91\xa3\x25\xc6\x27\x3d\x6b\x15\x4f\x4f\ +\xf1\x40\xe7\x46\x15\x27\x63\x99\x40\x69\x9c\x02\x0a\x70\x15\xa4\ +\x3a\xd8\x9c\x7b\x2e\xe8\x12\x41\xdc\x3f\x19\x1f\x83\xb3\x41\x65\ +\xba\x28\xc0\x12\x27\xa4\x22\xc0\x73\x09\x9e\x32\xfd\x9c\x34\x32\ +\x47\x41\x11\x0d\x95\x45\xb2\x2b\xe2\xcf\x38\xe3\x92\x82\xfd\x29\ +\x20\xf1\x8f\x1c\xe9\x91\x51\xc5\x7d\xf7\x5d\x81\x73\x18\x2f\x89\ +\x62\xc8\xda\x12\x9b\x57\xf9\x8a\x42\xf9\xbe\xd6\x12\x82\x0e\x43\ +\x26\xf1\x35\xa8\xd6\x64\xed\x80\x83\xa2\x98\x09\xbc\xf4\x7e\xdc\ +\xe2\x88\x8d\x4d\xae\x5c\xdb\xd3\x59\x96\x6b\xfb\x47\xd9\xe0\x71\ +\x25\x66\xa8\xad\x1e\x33\xfe\x3e\x0f\x68\x9c\x30\x39\x2a\xd5\x4f\ +\xa5\x8f\xb8\x03\xe4\x46\xc8\x30\x07\x39\x66\xdc\x43\x1d\xe9\x78\ +\x60\x1d\xf4\x70\xc7\x87\x0e\x37\xb3\x81\x0f\x7c\x7c\xfa\x0c\x74\ +\xf4\xa3\xd0\xd0\xda\x17\x9b\x37\x2f\x1c\xd0\x68\xc5\xe2\xe3\x80\ +\xfd\x9d\xef\x30\xbb\x18\x2e\x74\x0d\xb2\x91\xa1\x47\xfc\x98\x7b\ +\x19\x56\x2a\x1c\x94\xed\xae\xea\xa7\xdb\xd4\xb0\xd3\xf4\x18\xfb\ +\x1a\x35\x19\xe4\x0c\x6f\x14\xe6\x79\x76\x2f\x5e\x03\x38\x05\x8f\ +\x00\xc7\xae\x79\xa9\x04\xe2\x2d\x81\xce\xf0\x02\x13\x53\x71\xe6\ +\xca\x16\x90\x97\xf3\x02\x4d\xf7\x17\xe5\x1b\x34\x07\xff\x77\x1c\ +\xb5\xcd\x02\xef\x9e\x9d\x85\xb3\xdd\x86\x3a\x58\x56\x98\x24\xf2\ +\x0f\x13\xe4\x7b\xb1\xe7\x05\x57\x7c\xc6\x5d\x95\x16\xa7\xd0\x95\ +\x29\x28\x94\x7c\x78\x8b\x0c\xee\xd5\x32\x2e\xa5\x5d\x06\x8d\x9a\ +\xae\x17\x79\x96\x24\x97\x79\x14\xb6\x52\x54\x67\x35\x85\x35\x1d\ +\x05\xa1\x03\x2d\x11\xc3\x41\x15\xc6\xb1\xab\x5d\x17\xaa\x37\x4d\ +\xbc\x72\x03\x90\x74\xab\x8c\xde\xd3\x0b\x39\xc1\x92\x5b\xd3\xd5\ +\x29\xca\x28\x52\x8f\xaa\x91\x85\x93\x2b\x49\xbf\xc9\x74\x5a\xf7\ +\xd3\x2c\xe9\x55\x5e\x24\xaf\x03\xa7\xd0\x91\xec\xe1\x6e\xda\xa6\ +\x3f\xc3\xe4\xfc\x36\xb4\xd1\xe3\x25\xff\xfc\x41\x89\xd3\xaf\x20\ +\x4f\x9a\xd0\x31\x58\x9e\x34\xe5\x52\xb9\x5e\xc1\xdc\xb5\x98\x8d\ +\x42\x6c\x90\x7c\xc8\x7e\x69\x6f\xe9\x56\x45\x70\xf4\x89\xb7\x2a\ +\xcc\xc3\x8e\x46\x16\x99\x74\x81\x6c\xd3\x0e\xb6\x9b\xeb\x6c\x88\ +\x9b\xad\xc3\x74\x99\x44\x8a\x10\xdd\x6e\xc2\x78\xc9\x0c\x0f\xf8\ +\x9a\xbf\x73\x47\x5a\x2c\x77\x73\xb8\x4b\x11\x94\x22\xf5\xb3\x5e\ +\xe8\x30\x6f\xe3\x4b\xfb\x69\x2a\x24\xab\x09\x38\xcb\xb6\xf1\x9a\ +\xcd\x46\x9a\x97\xa2\x29\x29\x83\x89\x56\xa4\xce\x4a\x46\x5b\xc9\ +\xa2\xc0\x32\x22\x13\x4c\xd9\x72\xb9\xad\x6a\xfe\x3f\x9e\x6c\x8f\ +\x69\xa0\x3a\x0f\xb5\xce\x07\x35\x09\x6b\x04\x9c\xfc\xb5\x92\xed\ +\xe6\xc2\x27\x5b\x51\x58\x9a\xb1\x94\x0f\x6f\xae\x9f\x9c\x59\x71\ +\xc0\x50\x95\x9e\xd4\xea\x3c\x69\xab\xd2\x65\x76\x9f\xf6\xa7\xd1\ +\xea\x1c\xa9\x07\x2e\x8d\x0a\x65\x8d\x5a\xa9\x13\x73\xfc\x64\x8c\ +\xa2\xc6\xf6\x31\xca\x29\xd5\x5f\xa1\x78\x7d\xd7\x9f\x42\x59\x3e\ +\x69\x57\x2e\x21\x85\x42\xcd\x5a\xa9\x14\x53\xf9\xd4\xac\x0e\x34\ +\x3e\x77\xdb\xfe\x94\x59\x66\xdb\x1e\x18\x34\x6a\xb2\xdb\xd0\xdc\ +\x6d\x9f\x86\xc7\xdd\xb6\xda\x39\xe1\x0c\x51\xe4\x0f\xfb\x0c\xa5\ +\x89\x9a\x8e\x20\xde\xf1\x03\xe0\x53\xf1\x68\xa1\xeb\xa6\x45\x7a\ +\xd8\xd8\x2b\x6e\xb1\x70\x75\xb4\x63\xdd\x48\x0d\x5a\x40\x87\x29\ +\x67\xb0\xdd\xe8\x26\x57\x97\xa3\x2f\x25\xd9\x91\xe8\xb6\xe4\xe9\ +\xba\x16\xa3\x55\x36\x46\x55\xc5\x80\x41\x8a\x88\x34\xbc\x3a\xac\ +\x73\xb4\xfb\x40\xea\x4a\xcb\x30\x1d\xae\x14\x48\xf1\xfa\x4d\x25\ +\x59\x2f\x5d\xa1\x07\xf8\xd2\xb5\x88\x1b\xab\xf8\x7d\x12\xc6\x69\ +\x77\x3d\x0f\xa2\x12\x91\xb6\x47\xd6\x8b\x80\xdc\x4f\x39\x62\xd7\ +\xae\x1a\xba\x8e\xff\x8c\x7e\xce\x3b\x17\x10\xe8\xbe\x21\x82\xe8\ +\xb8\xcb\x07\x2a\x20\xc0\x98\x54\x84\x24\x27\x76\x59\xf3\x2e\x6c\ +\xe1\xab\x2a\x0f\x72\x8b\x59\x51\xb3\x0e\xaf\xcb\x10\xef\xdf\x77\ +\xad\xb7\x33\xd4\xdd\x7a\x8e\xb6\xbf\xc0\x0d\x4a\x97\xad\x0d\x38\ +\x67\x50\xa8\x57\xf1\x35\x24\x5e\xd6\x55\x36\x06\xab\x57\xe1\x98\ +\x78\x59\x3b\x10\x9a\x75\x07\xa7\x5b\x32\x3d\xd0\x94\x2f\xf8\xca\ +\x1a\xcb\x9f\xe7\xcb\xba\xd4\xb4\x48\x7b\xa5\x5c\x81\x83\xe7\x13\ +\xe5\x8a\xbd\x4a\xa8\x08\x4b\xb7\x2f\x26\x6f\xd0\xb9\x56\x3a\xc1\ +\x5b\xde\xda\x22\x27\x0a\x56\xb8\x10\x4b\x3b\xa4\x9a\x0a\x30\x0c\ +\xa5\xb5\x4e\x8d\x37\x5a\x7b\x55\x17\x08\x7b\x4f\x3c\x5b\x4b\xdf\ +\x10\xd4\x24\xb9\x6b\xff\x53\x79\x4b\xbb\xa1\x58\x73\x3b\x07\xaf\ +\xc9\x68\xcb\x10\xe9\x02\x66\x9b\x7d\x16\xf5\x70\x6a\x1b\xa7\x1d\ +\xee\xa8\x0e\x7b\x92\x54\xd3\xe6\x30\x9f\x30\x7b\x53\xb8\x92\xcd\ +\x4d\x55\xb7\x11\x0f\xdd\xf1\xf1\xc9\x41\x30\x1e\x8f\xc5\xd3\x24\ +\xf1\x92\xa5\x53\x0f\xb9\x90\x92\x78\x3e\x2c\x5f\x62\x92\xae\x88\ +\xea\x4f\xbb\xb8\xad\x64\x7c\xf2\x5c\x1f\x6d\x2d\xe9\x81\xd6\xf8\ +\xf8\x82\xcb\x07\x94\xc4\x87\xd7\x49\xb0\xc5\x51\x41\x0a\xb9\xa3\ +\x7c\xb1\x2b\x75\xb5\x57\x91\x68\x5c\x28\x72\x7b\x72\x35\x43\xf5\ +\xe1\xb8\x69\x0f\x1f\x70\xda\x6a\x23\x04\x9c\xc0\x62\x12\x3a\x56\ +\x41\x40\x0d\xd8\xe1\x86\x66\xc9\x2b\xa5\x71\x8f\xc6\xc0\xe1\x2f\ +\x15\x26\x5b\x75\x1e\x28\x63\x88\x5b\x91\xd2\x08\x61\x6c\x94\xad\ +\x56\x6e\x79\x2a\x2e\x7b\x16\x52\xb2\xeb\xb9\x0b\x0b\xfc\xd6\xbc\ +\xf7\x56\x02\x0c\x9b\x2c\xba\x1f\xcd\xda\x2a\x8d\xb5\x32\x38\x32\ +\xb4\x9f\xd2\xda\xaa\x7b\xe0\x46\x53\x6b\x76\x30\x20\x3b\xe2\xf6\ +\x37\x4c\xe6\xc6\x35\xf3\x34\x38\xdb\x26\xb6\x8f\xc9\x09\x5b\x3d\ +\x9e\x46\x27\x6c\x2d\xc3\xf0\xf9\x33\x26\xc3\xed\x17\xfb\x79\x7f\ +\x0d\xcf\x6b\x11\x29\x77\xee\xb8\x8c\xec\x35\x96\x22\x78\x2f\xdf\ +\x5c\xbf\x7f\x7b\xf9\x3f\xd7\x5d\x01\x53\x78\xbd\x10\xc7\xc1\xab\ +\xab\x57\x75\x86\xd7\x79\x19\xb3\xca\xc3\xcd\x20\x15\x94\xf9\xfa\ +\x5c\xbd\xd4\x5d\x15\x5d\x89\x61\x92\x58\x19\x28\x41\xef\x75\x85\ +\xd9\xed\xde\x8e\x9a\xfc\x82\xb7\x52\xae\xd0\x98\x2d\xa2\x4e\xab\ +\xd2\xbf\x4b\xca\x13\xcf\xee\x10\x93\x54\xc3\x81\x3b\x87\xba\x95\ +\x66\xcd\x34\x28\x57\xd7\xad\x34\xd0\xe3\x0b\xfe\xb3\x3d\xe8\x43\ +\xea\x1d\xa5\x8f\xc1\x44\x53\xed\x9e\x5f\x55\x5e\x27\xdc\xae\xe3\ +\x45\xd1\x21\x03\x12\xff\x0c\x62\x18\x02\x6d\x8f\x6c\x19\x3c\xee\ +\x27\x33\x0d\x81\x88\xa6\x46\x08\xf7\xe1\x1e\xf8\x29\x67\x1d\xc2\ +\xe7\xfe\xe6\xf1\x22\x4c\xa2\x14\x4d\x24\x3a\x6e\x10\x0e\x62\x1e\ +\x12\x6d\x56\xa6\x8c\xa2\x16\x81\xf5\x50\x08\x90\xc4\xe4\x17\x2f\ +\xdf\xed\x36\xf3\x6e\x6e\x7c\x20\xe9\x35\xb4\x79\xb0\x28\x87\x44\ +\x0a\xa3\x27\x79\xbd\xc7\x2f\x45\x20\x13\xed\xb8\x1d\xdb\x39\xf0\ +\x6d\x6b\x3a\x86\xda\x8e\xe5\xf9\x7c\x34\xbf\x16\x04\x25\x8a\x14\ +\xa3\x30\x89\xef\xd0\x64\x67\x81\x16\x8e\x64\x51\x58\x1f\xe1\x34\ +\x14\x3d\x81\xb7\x73\x26\x6d\xb6\x58\xef\xd2\x8f\x2e\x69\x70\x5a\ +\x5a\xc1\xd1\xaf\xe2\xb0\x4b\x81\xab\x77\xef\xe5\xd5\x07\x98\xfc\ +\x5f\xfd\x7e\x73\xf3\xeb\xbb\xce\x6b\x93\xe1\x16\x27\xef\x77\xc5\ +\xba\x7b\xf9\xa6\x1e\x06\x36\xa2\x63\xc0\xf2\x4d\x1c\x9b\x3a\xab\ +\x69\x35\x70\x95\x25\x8b\x63\xd9\xa1\x86\x1e\xbb\x39\xb7\x1a\xb6\ +\x60\xdd\x7e\x0e\xab\x78\xb5\xcb\x21\x91\xd6\x9f\x75\x1d\x4e\x3b\ +\xc7\x40\x4d\x02\x6f\x8e\x3d\xe8\x31\x6c\x68\x30\x4a\x94\xce\xe6\ +\xb4\xdf\xd3\xe9\xd9\xf9\xf3\x4b\x53\x84\xe6\x40\xd9\xca\x0c\xe8\ +\x89\x70\xa1\xdc\x85\x82\x19\xae\x95\x31\x92\xaa\x0d\x00\x1b\x96\ +\xb5\x8c\xbd\x76\x2c\xd5\xd2\x95\x2f\xe3\x30\xc9\xee\x2a\xd4\xa4\ +\xc6\xb3\x3c\x3a\x71\x19\xfe\xa2\xd8\x45\x38\x48\x4c\xf1\x75\x96\ +\xf3\x60\x14\x5c\xe3\xdc\x9b\x30\x09\x16\x61\x11\x05\xd9\x4a\xe8\ +\x55\xbf\x70\xb3\x24\x80\x8b\xaa\x5e\x79\x5d\x61\xfc\xf7\x37\xf5\ +\x11\x06\x9f\xae\x2e\x55\x2c\x69\x8e\xb2\x9e\xd6\x09\x92\x43\xb4\ +\xe1\x9c\x20\xc7\xe6\x13\x3b\xc1\xfa\xb4\x29\xe2\x8c\xa8\x40\x0a\ +\x4b\xb2\x7b\xf2\x22\xd8\x0e\x8f\x86\x2c\x4d\x1e\xe8\x2b\x2d\x2f\ +\xa3\x24\x7c\x88\x96\xef\xb3\xed\x6e\x8b\x9f\x02\x8b\x9a\xda\x13\ +\x1e\x50\x48\x25\x1d\xc2\xbf\x1d\x50\x0d\x27\x2e\x54\x30\x6f\xd2\ +\xa2\x0c\xd3\xb2\x82\x81\x0c\x0d\x26\x4e\x3e\x24\x7d\x4c\x3f\xcf\ +\x61\x7d\x34\x3f\xaf\xe2\x7c\x5a\x3f\x0f\xd0\xd3\xd5\x65\x03\x20\ +\x3d\x5d\x37\x00\xa1\x93\x0b\xe7\xe0\xf5\xc8\x5c\x7b\xa6\x7a\x62\ +\xe6\x3f\x5b\x3c\x96\x7e\x41\x43\xe9\xa7\x67\xc7\xcf\xfe\x97\x05\ +\x85\x5f\xf1\x28\x5c\xc9\x43\x4e\x3c\xa1\x16\x5e\xd0\x31\x01\x1e\ +\x43\x80\x65\x17\x01\xc3\x3e\x76\x01\x5e\x07\x55\xe1\xb0\x10\x9a\ +\x0a\xba\x01\x80\x8e\x80\xe4\x87\xe2\x1c\x8e\x05\xf9\xa3\x3c\x13\ +\xfa\x09\x24\x1c\xc1\xf1\x79\x48\x1d\x90\x84\x26\x5d\x4c\x19\xec\ +\xf2\xe1\xa2\x63\xa1\x51\x0d\x6e\xd7\x73\x34\x33\x10\xc8\x9d\xf8\ +\x03\x93\x26\x5b\x9d\x6e\xa1\x80\x27\x95\x41\x40\x8e\x60\x8f\x69\ +\xb8\x25\xb5\x95\x50\x70\x0a\x83\x62\x1d\xaf\x4a\x7e\x8e\x44\x90\ +\xd7\x1a\xad\x8c\x68\xc4\x65\x85\x5c\x93\xe6\x71\x89\x7a\xce\xd1\ +\xbf\x60\x70\xab\x78\xe2\x0a\x09\xf4\xcf\x8f\x09\x67\xbb\x43\x57\ +\x5d\x61\xfb\x17\xd9\x66\x13\xa6\xcb\xb7\x71\xfa\xb1\xcb\xac\x70\ +\x98\xad\x55\x85\x36\x8d\x97\xd6\x95\x21\xec\xba\x55\x65\x79\xdc\ +\xb2\xde\xb3\x95\xa9\xb4\xce\x05\x64\x72\xb5\x5b\x91\xbd\x8a\x13\ +\x2f\x34\xde\xbd\xff\xfd\xe6\x1a\xad\x2f\xde\xfd\x1a\xbc\x7e\xf3\ +\xea\xed\xcb\x96\x9b\x35\x83\xed\xd0\xbc\xc0\x55\x28\xbe\x82\x67\ +\x16\x06\xad\x86\xc1\x98\xd4\xb9\x53\xfb\xb5\x68\xd7\x17\x39\xbd\ +\x52\xd6\x90\x02\x84\x6f\x82\x9f\x82\x93\xb3\x1f\x83\x69\xf0\xcf\ +\x60\x7c\xf6\xc3\x24\xc0\xcf\xfc\xb2\xfb\xf9\x01\x4e\x4c\x6f\x16\ +\x14\xd5\x3b\xca\x24\x89\x0d\x97\x40\x64\xc5\x19\x4e\x2e\x9a\x36\ +\x75\x66\x2d\xc9\xb6\xdb\x6f\xd2\xed\xf8\xfb\xbf\xe3\xc3\xd3\x68\ +\x23\x13\xc3\x32\xf7\xf0\xa3\xca\x72\xba\xdc\xfe\xf8\x64\xd2\xa0\ +\x80\x52\xf7\x2c\x5d\xb8\xa5\xf2\xf3\x53\x8a\x44\xed\x72\xcc\x31\ +\xf2\x2e\x8a\x96\xd5\x77\x75\x59\x8a\x26\xbe\x8d\x44\x0c\xcc\x43\ +\x54\x0a\xd7\x14\x42\xf1\x32\x81\x3a\x73\xc9\xb8\x1f\xee\x66\x1e\ +\x36\xe2\x2c\xd3\x6c\xfb\xc1\x8c\x01\x74\x97\xbc\x1a\x13\x5c\x56\ +\x53\x06\x00\x2c\x15\x5b\xa0\x50\x7a\x79\x6e\x8b\xc2\xf2\x9a\x27\ +\xb1\x5e\x5e\x29\x4a\xac\x17\x8d\x87\x6d\xb4\x6d\xaf\xff\xee\x68\ +\x76\x72\x2c\x33\x11\xa3\x89\x7b\x7a\x10\x9a\x06\x1d\x86\x20\x5f\ +\x8d\xaa\x8d\xad\x70\xa5\x61\x9b\xa7\x03\x99\xb7\x3b\x9f\x1c\xe0\ +\x7f\x4f\x03\x34\x1f\x08\x7e\xf9\x0d\xff\x7e\x4e\xbd\xc6\x3f\xc4\ +\xed\x89\xe6\x07\xbe\xb4\x50\xfd\x10\xec\xf4\x8f\x7f\x48\xa3\xa6\ +\xf9\x51\x53\x7c\x64\x91\x31\x70\xf4\x57\x50\x34\xb8\x0e\x6c\x2b\ +\xa9\x2c\xf3\x6c\x3b\xc2\xd3\xcc\xf6\xbb\xa9\x62\xb6\x31\xbc\x16\ +\x32\xac\xfa\x14\x8a\x58\x92\xe2\x23\xa5\x49\x42\xa8\xd1\x10\x3d\ +\x08\xe0\x6f\xd8\xab\x56\xd0\x97\x9c\x3f\x68\x9b\x56\x49\xae\x55\ +\x21\x11\x75\x3d\xf5\x1f\xf5\x71\x87\x8d\xd0\x31\xcc\xed\x2c\x02\ +\x5a\xeb\xc2\x81\x12\x3b\x55\x07\xdb\x7b\x21\x75\xb3\x19\x02\x83\ +\x14\x65\xbc\x18\x6c\xb9\xea\xc5\x7d\x4b\xad\x68\x0a\xae\x26\x8c\ +\x47\xc3\x12\x3d\xfa\xcb\xc4\xee\xd4\xd4\x36\xdc\x81\x18\xe5\xea\ +\xb3\x39\x9a\x3f\x3e\x39\x26\xbb\x60\x07\xe7\x22\x10\xa7\xbb\xe0\ +\xee\x5c\xf5\xa0\x72\x80\xa2\x16\x7c\x59\x4b\x36\xc1\x8f\xdc\x18\ +\x75\x45\xbd\xa1\xec\x1d\x29\x93\xa3\x73\xb5\xa6\x83\x89\x53\xc7\ +\x52\x4e\x56\xf9\x4b\x73\x1e\x3d\x78\xbf\x3a\x42\x22\x18\x83\xcd\ +\xf7\x2d\xc7\x63\x22\x49\x4f\x29\x9a\x6b\x36\x75\x94\x61\xab\x4a\ +\x4c\x24\x17\x8d\x56\x5b\xec\xe6\xfc\x3b\x87\x24\xbc\x8f\x1a\x21\ +\x3a\x86\x49\x6a\x13\x4a\x4a\x9a\x17\x14\xc6\xeb\x69\x0d\x24\x3c\ +\xbf\x74\xbd\xa7\xe6\xd7\xdb\xe7\x36\x1b\x91\xed\xac\xd2\xae\x83\ +\x79\x6b\x36\x2f\x74\x69\x7c\x35\xb5\x7d\xac\xc7\x18\xac\xae\x97\ +\x49\x18\x20\x2f\x57\xc1\x7a\xe9\x96\xb9\xa6\x5c\x31\x35\xfd\xf5\ +\x26\x9c\xff\x11\x77\xba\x19\x4f\x7e\xba\x1f\xd9\x87\xf3\xaa\x16\ +\xc8\x08\x79\x01\xf2\xe7\x60\x37\xc5\x31\xc7\x86\x0b\xf7\xc6\x25\ +\xaf\x7c\x3b\x9b\xc1\x12\x9e\x61\xe3\x36\xa4\xce\xe9\xde\x8e\x29\ +\x3f\x9e\x42\x99\xcd\xb6\x61\x1a\x69\x2d\xc1\xa1\xa4\xa1\x34\x05\ +\x60\x84\x2c\xb3\x1d\x32\xfb\xba\x1b\x4d\xf3\x20\xc8\xee\xe3\x72\ +\x1d\x6c\x1f\x3e\x95\xa7\xf0\x1b\xf4\x20\x89\x76\xe3\x33\x4f\x15\ +\xc5\x08\x50\xdb\x61\x0f\x25\x0a\xfe\x66\x76\x88\x38\x46\xcb\xb4\ +\x97\xd9\xe2\x23\xb5\xa2\x5a\x0c\x44\xaa\x38\x49\x77\x8b\x82\xe1\ +\xc3\x68\x99\x87\xf7\x57\x61\x11\x49\x77\x0b\x6d\xda\xd7\xd6\x92\ +\x60\x67\x59\x95\x83\x26\x5b\x93\x74\xb7\x01\x67\x66\x54\x5b\xb4\ +\xf3\x07\xfc\x4d\x30\x62\x1b\x96\xf8\xa4\x0b\xbb\x7b\xee\xe4\x8a\ +\x90\x3b\x9b\x2d\x92\xac\x88\xea\x73\x3d\x90\x23\xb1\x89\x68\xe1\ +\xe2\x75\xc8\x63\x91\x74\xca\x9b\x63\x0d\x10\x82\x45\xbe\x60\x0f\ +\x50\xc0\xd6\xc8\x36\x52\x7d\x4e\xc4\x78\x1a\xc0\x9a\xe5\x20\x82\ +\x3a\x4b\xc0\x85\x16\xaf\x97\x08\x04\x6a\xea\x9e\x1a\x7a\x90\x95\ +\x6b\xd0\xa3\x6f\x98\x4b\xdb\x63\x83\x1e\x6f\x41\xb1\x48\xea\x67\ +\xf6\x04\x12\x03\xd4\x65\x00\x29\x2c\xcc\xf0\x3c\x87\x82\xe6\xef\ +\xba\x6a\x18\x83\xdb\xf3\xb6\xc9\xa6\x3f\x27\x8d\xeb\xb2\x24\x45\ +\xbb\x84\x0c\x46\x40\x0d\xde\x87\x66\x5d\x17\x81\x6c\x32\xe1\x1b\ +\x88\x66\xe2\x32\x7c\x28\x86\x3b\x08\xf4\xd6\x33\xc2\x81\x28\xae\ +\xa0\xfb\x90\xac\xe9\x21\xd0\x5c\xb9\xce\x81\x48\xc6\x0a\xdc\xf3\ +\x35\x65\xb5\x83\xcd\x96\x2d\x8f\xd1\x5a\x6b\x4a\x03\x86\xe9\x45\ +\xb5\xb6\x8f\xd1\x9a\xfb\xa4\x9a\x68\xd1\x8b\x66\x4d\x0f\x8b\x3d\ +\xf7\x49\x73\x05\xdd\x8b\x68\x5d\x17\xb3\x45\xf7\x49\xb4\x60\xa0\ +\xae\x86\x0c\xda\xef\x04\x24\x50\x7d\xee\xde\x6e\xa2\x1e\x96\xa9\ +\x1a\xa4\x91\x0c\x71\xd9\x6c\x33\x3b\x67\x6b\x03\xd4\x65\x24\x03\ +\xca\x26\xd3\x5b\x85\xbb\xfd\x40\xc6\x6e\x24\x84\x7f\xd7\x19\xb4\ +\x0d\xb3\x45\xb8\xac\x32\xc0\x17\xa4\xbd\x36\x22\xc0\xed\x12\xdd\ +\x46\x88\x54\x69\xc7\xec\x67\x1d\x8a\x86\x48\xbb\x21\xf8\xfb\xea\ +\x51\x19\xcd\x82\x11\x9c\xc4\x38\xce\x75\x5c\xb2\x5b\x0d\x13\xa0\ +\xd3\x8b\xcb\x57\x17\xc3\x31\xd3\x78\x29\xd3\x1c\x5d\xd3\xda\xbe\ +\x8b\x62\x8c\x87\x4d\x23\xb6\x72\x2e\xb6\x0f\xb8\x35\x5a\x2f\x1f\ +\x55\xbf\xee\x5f\x3c\x3f\x3b\x23\x53\xe0\xfd\xc9\xf4\x04\xdc\xf1\ +\x3a\x81\x0d\xed\xc4\xe8\x97\xac\xde\xc8\x18\x14\xcd\xcf\xd3\x3e\ +\xdd\x38\x31\x94\xc1\x99\x82\x4d\x20\x43\x01\x86\x9b\x75\x32\xed\ +\x3e\x87\xf6\x18\x0e\xca\xc4\x5a\x19\x0b\xdd\x18\x75\x98\x56\xd9\ +\x06\x05\xdc\xc1\x63\x5c\x28\xd3\xad\xa7\x19\x14\xb8\x93\x25\x30\ +\x7a\x84\x05\xd0\x56\xe1\x31\x20\x04\x4d\xc9\xda\xe5\x21\x20\xde\ +\xca\x72\x76\x88\x26\x23\xe1\x53\xd6\x74\xa6\x2e\x2c\xa9\x5c\x97\ +\x5e\x1e\x66\x0e\xac\xc7\xa8\xa1\x5b\xa7\xd0\x36\xfb\x84\x9a\x7b\ +\x58\x27\x30\xb5\x06\xec\x73\x19\xaf\x56\x11\xa9\x1c\x36\x8f\xd6\ +\xe1\xe7\x38\xcb\x71\xd5\x4d\x96\x15\x28\xcc\x8e\xe4\xd7\xb8\xeb\ +\x8f\x85\x92\x5b\xca\x5c\xc8\x36\x57\xfa\xaa\x4d\x13\x76\xb1\xae\ +\x6e\xd8\x66\x9c\xe2\xe2\xd9\x79\x95\xed\x61\x9e\xea\xd2\x5b\x6f\ +\x9d\xf2\xca\xc7\x66\x9e\x60\x7b\x0f\xfb\x54\x17\x51\x6d\xcd\xb3\ +\x82\x24\x5b\x27\xff\x29\xcf\x2d\x7f\xf9\x12\xde\x53\x56\xae\x2d\ +\x72\xa7\x14\x27\x67\x0e\x05\x69\xdd\x1e\x1e\x04\xd0\x19\xb7\x38\ +\xa1\x86\xf6\xd1\x63\x43\x65\xd0\xb3\xbe\xb9\xf3\x1d\x14\x15\x0e\ +\x71\x6b\x75\x86\x55\x94\xea\x97\xe3\xb6\x4e\x3e\x89\x59\xc2\xbb\ +\x1b\x4e\x94\x19\x77\x0a\xac\xbd\x7c\x69\xd3\x3d\x99\x09\xa1\xe3\ +\x1e\xd0\xf4\x90\x1f\xd0\xcb\x87\x48\xa0\xe4\xad\x15\x8d\x87\x08\ +\xa1\x6e\xde\xe4\x69\x84\x88\x8f\xcc\x2a\xfc\x9d\xcf\x6e\x07\x39\ +\xdc\xe2\x64\x43\x38\x66\xd7\xcb\x34\xc7\x99\xfd\xbf\xfd\x58\xc6\ +\x65\x12\xcd\xc3\x7c\x54\x9d\xa0\x60\x01\x9b\xaa\x35\x37\x39\xad\ +\x5c\x6a\x26\x83\x91\x66\xf9\x26\x4c\xda\x00\xa9\x6f\xea\x33\x71\ +\xa0\x28\x83\x81\x32\x0f\x7c\x55\xdd\x1c\x23\x37\x1e\xf0\xf9\x5a\ +\xf5\x2d\xbe\x04\x21\x9d\xc6\xd2\xe9\x33\xab\x38\x2e\x3f\x7c\xd0\ +\x64\x57\x5b\xfd\x26\x4f\x8e\x7a\x2e\x87\x99\x1a\x61\x82\x4c\xf7\ +\x05\x4d\x05\xfd\x39\x02\x6a\x4b\xd7\x5d\xa2\x32\x1e\xfd\x55\x7f\ +\x76\x38\xf8\xd3\xb1\xd9\xeb\x99\x9e\x16\x49\xdf\x87\x75\x3c\xa2\ +\x55\x92\x85\xe5\xdf\x5f\x69\x08\x19\x62\xca\x91\xcf\x16\x5a\xab\ +\xe0\x5b\xd5\x26\x60\x69\xa3\xb6\x1a\x0f\xa8\x37\x92\xdc\x90\x47\ +\x11\x7d\x11\xb8\x28\xab\xdf\x6e\xb0\x57\xf7\xab\x49\xd8\x3d\xb9\ +\x01\xd1\xf1\x19\xa1\xec\x9c\xe0\x56\x94\x3d\x80\x29\xb1\x04\x2a\ +\x38\x43\xa4\x57\xd4\x32\x9f\xcd\x91\x19\x2f\xd6\x42\x3d\x49\xe9\ +\x2b\x4d\x16\x63\x0b\x3f\xaf\x40\x0e\x0b\x34\x28\xe7\x28\xf4\xdd\ +\x15\xb3\xbd\x70\xf9\xdf\x2c\x4e\x8b\x51\x73\xcf\xa3\x8e\x5d\x36\ +\x33\xab\xa0\xdd\xe2\x08\x5a\x21\xe4\xef\x9d\x9b\x50\x76\xc5\xb8\ +\xc9\x72\x3b\xc6\x3d\x8c\x72\xb1\x8e\x93\x25\x92\x48\xf5\x57\x6f\ +\x04\x44\xe9\xd2\x89\x63\x0d\x7a\xe2\x4f\x21\x95\x57\x5f\x88\x5d\ +\xf9\x9e\x10\xad\xce\x0f\xc7\xd7\xb4\x57\x38\x2c\x16\x92\x6d\x6b\ +\xcc\x30\x07\x00\xe9\x6a\x8f\xbe\x09\xc7\x18\x1c\x0c\xdb\x28\xf3\ +\xa6\xd0\xab\xa7\xe4\x7d\xdc\xbc\x20\x68\x38\xe3\xc6\x4f\xdc\x5a\ +\xaa\xcd\x42\x6f\x41\x33\x06\x68\xa6\x98\xbb\x4d\x56\xdf\xee\x3a\ +\x20\xe9\x9f\x55\x00\xd1\x7c\xcd\xa2\x8a\xe6\xfb\x17\x59\xb2\xdb\ +\xa4\x9a\x06\x6e\x0c\x90\xc6\xf3\xec\xcb\x6d\xdd\xcb\x9d\x7e\x55\ +\xba\x40\x1b\x22\x13\x4b\x1b\xba\x9f\x60\x96\x47\x8d\xce\xd2\xa8\ +\xc2\x67\x69\xc4\x21\x34\x49\xb8\xc1\x68\x6c\xc5\x50\x1a\x5b\x71\ +\x38\x8d\x5a\x6b\x90\x9a\x9b\x31\xac\xe6\x66\x5e\xf3\x1f\xd9\x16\ +\x9c\x2d\x7a\x97\x5a\x6c\x5a\x68\x00\xca\x49\x68\x01\xf3\xc4\x9a\ +\x78\x72\xc3\xfa\xf9\x70\x62\xb4\xee\xa6\x95\xc9\xbe\x9b\x56\x16\ +\x0b\x97\x91\x5a\x9b\x19\xad\x1c\x44\x6b\x96\xb9\xc5\xd2\x01\xc4\ +\x96\x76\x56\x6b\x07\x50\xdb\x1a\x5a\x2c\x5e\x41\xde\xd6\x4a\x9c\ +\xad\x1e\xfd\x16\xa1\xd5\xfe\x26\xc6\x77\x60\x75\xda\x50\x1a\x81\ +\x92\x53\x5a\xc1\x3c\x0a\xcd\x3c\xf9\x13\xfa\xfa\x72\x67\x1c\x0d\ +\x62\x4b\xd3\x88\x10\x5b\x5a\x46\x05\x44\x80\x53\x53\xe3\xe8\xd0\ +\x92\x60\xd7\x8b\x65\x94\x68\x88\x70\x68\x6b\x1d\x2d\x1a\x32\x5c\ +\x1a\x5b\x46\x0d\x48\x48\x17\xcb\x32\x8e\x1e\x5e\x29\x82\x6c\x44\ +\x02\x5d\xae\xf3\x78\x17\xee\xb9\xcb\xe3\x25\x5e\x72\x19\xde\x10\ +\x04\x4f\xef\xa9\x19\xb3\xad\x62\xde\xb0\xf8\x0f\x1b\x45\xf3\x9f\ +\x72\x62\xef\xe1\xb6\x12\xa3\x86\xad\x7f\x79\x6a\xf8\x0f\x1b\x6a\ +\xf8\x4f\x39\x6a\xba\x5f\x38\x6a\xa8\x51\x47\x1c\x60\xfe\x90\x25\ +\xfa\xbd\xa9\xdb\x78\x14\x5c\x7e\x00\x76\x1f\xd2\x37\xfc\xe8\x93\ +\xbe\x12\x06\x04\xf7\x9d\x5d\x20\x20\x39\xec\x8c\x31\x5c\x94\xf1\ +\x67\x39\x1e\x68\x5a\xc8\xe4\x01\x4d\x14\x32\xa5\x36\x5d\xc9\xdd\ +\xb3\xd3\xbb\xe7\x40\xf0\x9e\x0b\xc5\x7b\x3c\xc9\x50\x71\x2d\x80\ +\x8b\xe7\xd3\xf1\xf4\xb5\x8e\x0b\xf9\x24\x58\x65\x02\x68\x21\xf3\ +\x00\x34\x51\x58\x00\x8f\x90\xd9\x31\xc8\xb1\xce\xe9\x38\x30\x84\ +\x89\x79\x91\xe5\x69\x94\xd3\x93\xa6\xa2\xba\xb0\xe6\xeb\x05\x85\ +\x17\xd6\x0c\x55\x81\xc4\x22\xbf\xff\x8a\x42\xf4\x6d\xc7\xd7\x54\ +\x7a\xd8\xcc\x5c\x13\x3a\x06\xdb\x3f\xe4\xd8\xb4\x9e\x46\x73\x7b\ +\xe3\x06\xb1\x4a\x7b\xe4\xe2\x06\xba\xb6\xae\x64\x43\x87\x57\xe5\ +\x5b\xbb\x9e\x15\xf0\x56\x33\xf2\xaa\x73\x57\xb1\xc5\xbf\x7a\x80\ +\xcf\x84\xc9\x87\xa4\x2a\x4d\x7d\x56\xc1\xa7\x7f\x01\xb4\xcc\x94\ +\xaa\x02\x42\xd2\x8b\x70\xf8\xc0\x52\x5e\xc4\x4f\x7d\x2e\x21\x2b\ +\x35\x60\xa4\x8c\x76\x0b\x85\xb3\xd9\x2a\xce\x0b\x9c\x1c\x64\x6d\ +\x88\x0b\x21\x8f\x32\xf1\xb2\xa7\xb5\x04\x8d\x0d\xaa\x68\x20\x9a\ +\x19\x01\x08\x44\xac\x38\x30\xa8\x8c\xe5\x17\x15\x5d\x44\xcc\x6a\ +\x02\x98\x05\xdc\x34\x03\xc5\xab\x7d\xcb\xd1\x05\xb3\xb7\x6c\xe5\ +\x2a\x41\xe4\xea\x7c\x56\x44\x41\x11\x95\x25\xd9\xaa\xfd\xae\xa2\ +\xeb\x88\x64\xd1\x1c\x55\xc9\x35\x47\xf2\xb8\xfb\x1e\x53\x8b\x22\ +\xe0\x7c\x77\xd7\x5c\xa0\xe3\x47\x74\x85\xa2\xe9\x46\xb2\x30\xb9\ +\x0a\x7a\x6e\x7e\x82\xed\x11\x5b\x72\x7c\x3c\x53\xd4\x5a\xbf\xdc\ +\xc8\x4b\x92\xbe\x43\xea\xe3\xf7\x9e\x94\x1f\xf9\xf9\x53\x56\x1b\ +\xff\xe9\xab\x4f\x92\xd2\xf8\x03\x15\x9f\xa4\x2c\xf2\x3e\x44\x2e\ +\x47\xa3\xfe\xad\x1f\x90\x35\x3c\x69\xe1\xa1\x05\x3c\xd1\x27\x6c\ +\xd5\x80\x9a\xeb\xac\xc3\x3c\x47\xd4\xf1\x22\x04\x47\xa5\x9b\xbb\ +\x11\x7a\x58\x97\x67\x6a\x89\x7a\xe0\x4a\x95\x41\x72\xda\x0b\x91\ +\x0e\x03\x12\x42\x25\x55\x13\x12\x50\xc9\x57\x8d\x5a\xa2\xd0\x18\ +\x94\x88\xc2\x63\x99\x0d\x80\x51\x32\x07\x9b\x5e\xda\x2b\x27\x13\ +\xfd\x8a\xb5\x1e\x42\x1f\xae\x49\x31\xd4\xcb\x3c\x0a\x59\x69\x09\ +\xa1\xc4\x84\x7d\x78\xd9\xd8\xc0\x4e\xe9\x35\x7e\xca\xf4\xeb\x79\ +\x52\x55\x03\xa3\xfa\xba\xea\x36\xc2\x45\x11\x9c\x5a\x2e\xa3\x32\ +\x8c\x93\xa2\x69\x5b\x94\x48\x24\x58\x5b\xab\x24\xbb\x3f\x5c\x64\ +\x9b\xa3\x4f\xbb\xa8\xc0\x61\xbe\x38\x1a\x4f\x4f\xcf\xc7\xd3\x8b\ +\x73\x0c\x86\x23\x79\x95\xe5\xa3\x35\xd9\x03\xfa\xdc\xec\x04\x0d\ +\xe1\x3b\x91\x32\xbe\x5b\x66\xe5\xf7\xc1\x61\xad\x93\xba\xd0\xe4\ +\x74\x8c\xeb\xd9\x4e\xce\xc8\xbf\xd5\xbd\x0a\xda\x82\x37\x39\xd8\ +\xdf\xe8\x1c\x18\xae\x71\x99\x05\x44\x54\xcd\x94\xe2\x5f\xb8\xb0\ +\x0c\xf4\x27\x31\x96\x1a\xe9\x7f\x48\xa7\xeb\x75\xb8\xe5\x5f\x14\ +\x70\x20\xc2\xb0\x04\x81\x40\x4f\x29\xe8\x4d\xf8\x85\x25\x9c\x3b\ +\xa4\x35\x69\x12\xde\x20\x14\xa7\x3c\x8a\x7a\x4e\xd0\x1e\x03\x29\ +\x89\xb8\x4d\x62\x92\xcc\xd7\xcd\x1e\x3a\x0f\xa6\xa2\xa6\x63\x90\ +\x18\xcf\x98\x74\xf0\xcb\x2c\x55\x51\x29\x48\x62\xaa\x79\x4e\x31\ +\xd0\x82\x60\xbe\xcb\x6f\xf5\x12\xaa\x9e\x8e\xb1\x07\x1d\x96\x92\ +\xc5\x52\x68\x06\x7a\x8b\xeb\x58\xe9\xf2\xa8\x6d\x62\x89\xdd\xcf\ +\x2d\x5d\x8c\x48\x73\x65\x05\x97\xb8\x9a\x13\x2f\x6c\x38\xa2\x6a\ +\xc8\x05\x12\x8f\xc3\x92\x94\xa0\x3a\xa8\x7e\xbd\x89\x37\xad\xea\ +\xae\x0d\x93\x78\xac\xa1\x8d\x48\xc2\xb5\xb4\x79\xaf\x25\xc9\x68\ +\xc9\xb4\x15\xb9\x6b\xa1\xa9\x94\x06\x96\x68\x33\xf6\x90\x2f\x5a\ +\x7a\x2d\xc5\xb9\xeb\x94\x63\xde\xe6\xa9\xf4\xaa\xe2\xb2\xbc\x00\ +\x5b\x55\x84\x66\xe0\x9a\x22\xbe\x32\xd8\xaf\xa6\xbc\x2f\x47\x2b\ +\x5b\xb8\xab\xc4\x3e\x76\xe5\x5f\x88\xaa\x46\x39\xca\x37\xec\xd6\ +\x0b\xf4\x25\x3d\x67\xd5\xb1\x04\x28\x5d\x07\x1b\x6c\xd0\x43\x65\ +\x61\x46\xb8\x5a\x7e\x5d\x1e\xd0\xba\x7a\xf7\x0e\x0b\x3b\xcf\xe9\ +\x92\x87\xc5\x63\xef\x48\xe9\xfa\x1a\xdf\x1b\xe7\x69\xeb\x5c\xbf\ +\x50\x00\xd6\xa5\xe8\x3e\x92\xda\xfb\x24\x2b\x3b\xbe\xc0\x4d\x7e\ +\x86\x90\x1a\x47\x1b\xdd\xc8\x7b\x8d\x26\xe7\x8b\x5d\x19\x24\xe1\ +\x3c\x4a\x0a\xfc\xa0\xdd\x16\x35\x22\x37\xe9\xa6\xda\x32\x7a\xff\ +\x0f\x59\xf9\x35\x4a\ +\x00\x00\x04\x5f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x11\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x68\x1d\x55\x1c\xc5\x7f\x67\xf2\x90\x14\x95\xa2\xa8\x1b\ +\x51\x57\xa2\xb8\x11\x69\xc9\x47\x45\x49\x45\xab\x55\x0c\xcd\x7b\ +\xa5\xae\x44\x2a\x8a\x76\x21\x2a\x28\x82\x0a\xb1\xb4\x62\x05\xc1\ +\x85\x88\x16\x04\x71\x61\xd1\x90\x2f\x03\x5a\x8d\x4a\x2b\x48\x9b\ +\x3c\x6d\x69\x41\x5c\x14\x44\x5c\x28\xa2\x60\x54\xb0\x46\x9b\x37\ +\xc7\xc5\x6b\x64\x66\x5e\xc1\x44\xe6\xe3\x5a\xdf\x59\x9e\x03\x73\ +\xff\xf7\x77\xef\xdc\xb9\x77\xe6\x3d\xe8\xaa\xab\xae\xfe\xcf\x52\ +\xd5\x05\xac\x54\x7d\x13\x1e\x55\xe4\xa7\x65\x2b\x76\xb4\xbb\xd9\ +\xd0\x33\x79\x5c\xf7\x3f\x01\xa0\x7f\xc2\x1b\x89\xfc\x31\x3e\x5d\ +\xaf\x1d\xcf\x37\x7a\x7a\xf2\xb8\x76\x94\xc7\x45\x8a\x54\xdf\xb8\ +\xd7\x23\xcf\xfc\xdd\x79\x00\x29\xb7\xba\x83\x06\x30\x38\xee\xab\ +\x15\x79\x3f\x70\x5e\xd2\x37\xc4\x79\xb5\x11\x2c\x80\x75\x63\xbe\ +\x3c\x8e\x3c\x0b\x5c\x94\xcd\x04\xce\xab\x9d\x20\x01\xdc\x30\xe6\ +\x8b\x6b\x35\xcf\x02\x97\x15\xdd\x56\xad\xe8\x06\x56\xab\xeb\xdf\ +\xf1\xf9\x7f\xc6\x7e\x0f\x73\x55\x19\xed\x05\x35\x03\x86\x5e\x77\ +\xef\x52\xcb\xd3\x98\xf5\x49\xdf\x39\x4e\xf9\xac\x82\x01\x30\x74\ +\xc0\xb5\xc5\xb5\xde\x07\xdc\x94\x0a\x84\x95\xe3\xa2\x97\x55\x18\ +\x00\x6c\xfd\xbe\x10\xef\x35\x8c\x64\x13\x5c\x5c\xe7\x21\x10\x00\ +\xfd\x53\xf1\xf3\xa0\x7b\x53\xa6\x30\x05\x8e\xfc\xb2\x2a\x07\x30\ +\x30\xe9\x27\x40\x8f\x27\x3d\xb7\xef\xfa\xc2\x3b\x0f\x15\x03\x18\ +\x98\xf4\xfd\xc6\x7b\xb2\xbe\x14\xb5\xca\xaa\xa1\x32\x00\xfd\x53\ +\x6e\x18\xbf\x9a\x32\x0d\x36\x31\x2e\x6c\xd1\xef\x50\x25\x00\x06\ +\xc6\x7d\x33\xf6\xbe\x6c\xfb\x16\xb1\x54\xdc\x23\xef\x4c\x2a\x1d\ +\xc0\xe0\x94\xfb\x2c\x4f\x03\xe7\x24\x7d\x9b\x38\xcf\x2d\xee\x4a\ +\x55\x2a\x80\xfe\x69\x5f\x13\xdb\xfb\x11\xe7\xa6\x02\x97\x3f\xf2\ +\xcb\x2a\x0d\xc0\x86\x09\x5f\x41\xec\x59\xe0\xc2\x74\xa2\x98\x8a\ +\x3a\x0f\x25\x9d\x05\x36\x4c\xfa\x92\x16\xfe\x10\xb8\x34\x9d\x28\ +\xa6\xcc\x15\xef\x0c\x2a\x7c\x06\xac\x1b\xf3\xda\x25\xf9\x7d\xe0\ +\xca\x54\x20\xbb\xea\xce\x43\xc1\x33\x60\x70\xcc\x6b\xe2\x9a\x67\ +\x30\xd7\xa5\x02\x61\xac\x52\x36\x3a\xff\xa4\xc2\x66\xc0\xd0\x01\ +\xd7\xe2\x9a\xdf\x02\x6e\x4c\xfa\x2e\x61\x7f\xbf\x1a\x15\x03\x60\ +\xd4\xd1\xe2\x42\xfc\x1a\x30\x9c\xf2\x0b\x3e\xd9\xfd\x1b\xe5\x0f\ +\xc0\xd6\xc0\xb5\xf1\x0b\x46\xf7\x64\x93\x90\x46\x7e\x59\xb9\x03\ +\x18\x98\xe2\x49\xa3\x47\x53\x66\x7b\xad\x0b\xae\xf3\x90\x33\x80\ +\xbe\x49\x3f\x68\xbc\xbb\x23\x90\x4a\x3b\xdc\xac\x56\xb9\x01\xe8\ +\x9b\x6c\xed\x11\x7e\x25\xeb\x3b\xc0\x69\x9f\x54\x8e\x33\x20\xf3\ +\x42\x83\xf6\xfb\xfb\xaa\xb6\xb8\x2b\x55\x6e\x00\x04\x9d\xd3\x3c\ +\xe8\xae\xb7\x95\x1f\x00\xe9\x61\x32\x5d\x96\x88\x42\xff\xfc\x98\ +\x1b\x80\xb9\x11\x8d\x81\x1e\xea\x4c\x9c\xcb\x47\xcc\xa2\x94\xeb\ +\x53\x60\xbe\xae\x97\x41\xa3\x9d\x49\xb8\x10\x72\xdf\x07\xcc\x8f\ +\xb0\xcb\xf2\x4b\x69\x57\x20\xa2\x10\xef\x86\xfc\x77\x82\x92\x9b\ +\xc7\xa2\x47\x8c\xdf\x4c\xf9\x46\xb8\xfa\xb7\xd0\x59\x15\x53\xd0\ +\x4e\xc5\xad\x1f\xa3\xed\xc0\xbb\x99\x44\x28\x2c\x08\x85\x15\x73\ +\xe4\x01\x9d\x5a\xaa\x69\x1b\xf0\x69\x2a\x68\xff\xd0\x21\x18\x08\ +\x85\x16\x72\x64\x58\x27\xff\x90\xee\x04\x8e\x67\x22\x19\x07\x01\ +\xa1\xf0\x22\x8e\x8d\xe8\xe7\x78\x49\xb7\x19\xbe\x4a\xfa\x42\x32\ +\xaa\x7c\x59\x2c\x65\x14\x3e\xdb\xa6\xef\xa9\xe9\x16\xe0\xbb\xa4\ +\x2f\x1c\x55\x0d\xa1\xb4\x69\xd8\x1c\xd6\xd7\x2d\x74\x2b\xb0\x90\ +\xf4\xd5\xbe\x15\x2a\x83\x50\xea\x7d\xf8\x79\x5d\x5f\x18\xdd\x01\ +\x9c\xcc\xd6\xe1\x8a\x20\x94\xbe\x10\x35\xeb\x3a\xec\x58\x75\xe0\ +\x54\xd2\x17\x44\x76\xf9\x10\x2a\x59\x89\x9b\x5b\xf5\x81\xac\xbb\ +\xc9\x1e\x9e\x2a\x80\x50\xd9\xa3\x68\xae\xa1\xb7\x6d\xed\x48\x99\ +\x5a\x3e\x41\x96\xa7\x4a\x9f\xc5\xcd\x86\xf6\xda\x7a\xaa\x23\x70\ +\x79\x87\xa7\xca\x37\x23\xcd\x3a\xcf\x09\xbf\x98\x32\x75\xfa\xf0\ +\x54\x82\x2a\x07\x80\xe4\xb9\xe3\xd1\x63\xc2\x6f\xa4\xfc\x92\xb6\ +\xcc\xd5\x03\x00\xd8\xa9\xb8\xf7\x82\xe8\x3e\x60\x26\x93\x14\x7e\ +\x78\x0a\x03\x00\x70\x70\xa3\x96\xd6\xfc\xa2\xbb\x0c\x9f\xa4\x02\ +\x23\x17\x58\x67\x30\x00\x00\x0e\x6e\xd7\xa2\x7a\x35\x0c\x1c\x4d\ +\xfa\x2a\x70\x93\x14\x14\x00\x80\xf9\xdb\xf5\x6b\x0f\xda\x0c\x9c\ +\x28\xa3\xbd\xe0\x00\x00\x1c\xaa\xeb\x87\x1e\x6b\x13\xf0\x6d\xd1\ +\x6d\x05\x09\x00\xe0\x50\x43\xdf\x10\x69\x13\xf0\x53\x36\xcb\xf3\ +\xdc\x10\x2c\x00\x80\xf9\x2d\xfa\x32\x92\x36\x63\x7e\x4b\xfa\xca\ +\xb1\xee\xa0\x01\x00\x1c\x1e\x51\x53\xd6\x96\xcc\x0f\xa9\xce\xfe\ +\xbf\xcc\x24\x35\xb7\x55\x1f\x61\xed\xa2\xfd\xf9\xad\x85\xf4\x6c\ +\xd5\x35\x75\xd5\x55\x57\x67\x87\xfe\x02\x8f\xb0\x51\x56\xec\xcd\ +\x17\x8d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x88\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3a\x49\x44\x41\x54\x58\x85\xed\ +\xcd\xb1\x11\x00\x10\x00\xc0\xc0\x30\x99\xc6\x04\x56\x30\x96\x15\ +\x2c\xe0\xdc\x59\x4d\xa5\x55\x6a\xe4\xab\x74\x01\x49\x92\x7e\x17\ +\x4e\xe4\x52\x17\x90\x1e\x4d\xe7\xe8\x2d\x03\xc4\x17\x43\x49\x92\ +\xa4\x9b\x0d\x00\xac\x05\x04\x1d\x7e\x88\x63\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\xbb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x6d\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x6f\x13\x31\x18\xc6\x9f\xf7\x2e\x15\x13\x08\xa6\x22\x35\ +\xc4\xbd\x88\x05\x06\x40\x82\x85\x1d\xca\x00\x62\x80\xa1\x0b\x12\ +\x7f\x01\x1f\x1b\xb4\x03\x08\x24\x3e\xc4\xc4\xc7\x5f\x80\xc4\xd2\ +\x01\x06\x04\x03\x85\x9d\x05\x24\xca\xd0\x6e\x77\xe7\x24\x1d\x60\ +\x00\xc4\x56\x91\xe4\x61\x48\x24\x2e\x77\x17\x68\xe3\xbb\xb8\xa5\ +\xfe\x6d\x7e\xfd\xc6\x79\xfc\xc4\x67\x5b\x39\x1b\x70\x38\x1c\xdb\ +\x19\x59\x4f\x12\xc9\x8a\xd6\xad\xb3\x14\xce\x0a\xe4\x18\x80\x29\ +\x00\x3b\xca\x95\xb6\x61\xd6\x00\xac\x12\xfc\x20\x94\x05\xa5\xaa\ +\x2f\x45\xa4\xfd\xaf\x0f\xfd\xd3\x00\xad\xf5\x49\x42\x1e\x01\x72\ +\xa0\x10\x99\xe3\x63\x59\xd0\xbd\xaa\x94\x7a\xfb\xb7\x24\x6f\x58\ +\x05\x49\x89\x1b\xad\x79\xc2\x5b\xdc\x82\x9d\x07\x80\x83\x84\xb7\ +\x18\xe9\xd6\x1c\xc9\xa1\x3f\xf4\x50\x03\x74\x73\x75\x0e\xe4\x9d\ +\x72\xb4\x8d\x0f\x01\xef\xc6\x8d\xd5\xeb\xc3\xeb\x73\xe8\x0d\x7b\ +\x6f\x31\x15\xfe\x0e\xe2\x06\xd0\x79\xad\x94\x6a\x88\x48\xa7\x50\ +\xa5\x86\x90\xf4\xb5\xd6\x35\xc0\x3f\x0d\xc1\x6d\x00\x7b\x92\xf5\ +\x82\xee\x4c\xde\xe3\x90\x31\x80\x64\x45\x37\x9a\x9f\x07\x87\x3d\ +\xdf\x75\x3b\xed\x0b\xf5\x7a\xfd\x4b\x09\xda\x0b\x27\x0c\xc3\x49\ +\xcf\xaf\x3c\x03\xe4\x44\x22\xbc\xac\x6a\xd5\xc3\xe9\x89\x31\x63\ +\x40\x1c\x37\xcf\x41\xf0\x3c\x11\xfa\xd6\xfe\x35\x71\x60\xff\xfe\ +\xbd\x5f\xcb\x12\x5c\x06\x3d\x13\x26\x56\x90\x1c\x09\xc4\xf9\xe9\ +\xe9\x7d\x2f\x92\x79\x99\x39\x80\xc2\xd9\xc1\x00\x6e\x6e\xb5\xce\ +\x03\x40\xbd\x5e\xff\x22\xc0\xcd\x64\x2c\xd3\x37\xe4\x18\xd0\x5f\ +\xe7\x13\x74\x5e\x17\x2d\x6e\x5c\x90\x9d\x57\xc9\xb2\x40\x8e\xa6\ +\x73\xf2\x56\x81\xa9\x64\x41\x29\xd5\x28\x58\xd7\xd8\xc8\xd1\x5e\ +\x4d\xe7\xe4\x19\x30\xb0\xc3\xdb\x6c\xb3\xfd\x46\xc8\xd1\x9e\xd9\ +\xbd\x0e\xdd\x07\x6c\x17\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\ +\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\ +\xd8\xc6\x19\x60\x5b\x80\x6d\x2a\x45\x34\x12\x36\x1a\x33\x1e\xe4\ +\x01\x88\x43\x58\xe7\xbb\x06\x03\x08\x60\xa9\x2b\xbc\x56\xaf\xd5\ +\xd2\xff\x5b\x6e\x18\xe3\x11\x10\xe9\xd6\x45\x8f\xf2\x06\xc4\x61\ +\x94\xdf\x79\xf4\xbf\xe3\x88\x47\x79\x13\xe9\xd6\x45\xd3\xc6\x8c\ +\x0c\x88\xa2\x68\xb7\x80\x4f\x4c\x45\x8c\x8a\x80\x8f\xa3\x28\xda\ +\x6d\xd2\x86\x91\x01\x22\x95\xe3\x00\x76\x9a\xb4\x61\xc8\xae\xbe\ +\x86\x91\xd9\xf6\x93\xa0\x91\x01\x64\xfb\x3d\x80\x9f\x05\x69\x19\ +\x85\x9f\x7d\x0d\x23\x63\x64\x40\x10\x04\x3f\x08\xb9\x6c\xd2\x86\ +\x09\x84\x5c\x0e\x82\xe0\x87\x49\x1b\xc6\x8f\x40\xa0\xaa\x4f\xbb\ +\xc2\x53\x00\x3e\xa1\xb7\x44\x95\x0d\x21\x58\xea\x0a\x4f\x05\xaa\ +\xfa\xd4\xb4\xb1\x42\xf6\x01\xfd\xf5\xd8\x78\x4d\xb6\x81\x9b\x04\ +\x6d\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\ +\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\ +\x03\x72\x62\x6b\xc9\x02\x49\x7f\x4c\x5a\x0a\x27\x47\xfb\x5a\x3a\ +\x27\xcf\x80\xd5\x64\xa1\x77\xfc\x74\x6b\x92\xa3\xbd\x95\xce\xc9\ +\x1e\x94\x04\x3f\x0c\x46\xfc\xd3\x85\xaa\x1a\x23\x22\xfe\x99\x64\ +\x99\xe0\xc7\x74\x4e\xf6\xa0\x24\x65\x61\x30\x80\xdb\x61\x18\x4e\ +\x16\xae\xae\x64\xc2\x30\x9c\x24\x70\x2b\x19\xcb\xf4\x0d\x39\x06\ +\x28\x55\x7d\x09\x70\x25\x11\xda\xe3\xf9\x95\x67\x5b\xc9\x84\x3f\ +\x87\xa5\x07\x4e\x8c\x2f\xf7\xfa\x36\x48\x76\x04\x88\xb4\x05\xbc\ +\x92\x8a\x9e\xf0\xfc\x89\x15\xad\x9b\x97\xe2\x38\x0e\x36\xe3\xc4\ +\x48\xd2\x8f\xe3\x38\xd0\xba\x79\xa9\x77\x48\x7a\xe0\xa4\x38\x04\ +\xdd\xab\x79\x57\x68\x86\xbe\xca\x8a\x1b\xad\xf9\xff\xe1\xc2\x04\ +\x00\x10\x32\x1f\xa8\xea\xbd\xbc\xba\xa1\xfb\x00\xb5\x6f\xea\x1e\ +\x21\xf3\xe5\xc9\x1a\x0b\x24\x30\x37\x5d\x9b\xba\x3f\x2c\x61\x9d\ +\x97\xa6\xbc\x87\x00\x0e\x16\x2a\xad\x7c\xd6\x75\x69\x6a\x94\x6b\ +\x73\x47\xd1\x3b\x75\xbd\x19\xaf\xcd\xb5\x08\x7e\xdc\xc8\xb5\x39\ +\x87\xc3\xb1\xbd\xf9\x0d\x9c\xbe\x20\xb7\xf5\xf6\x9b\x02\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xdc\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x8e\x49\x44\x41\x54\x58\x85\xed\ +\x97\x41\x4a\xc3\x50\x10\x86\xbf\x79\x71\xab\x0b\x45\x5d\xd8\xd6\ +\x92\x4b\x28\x28\x5e\xa0\x5e\x41\x0f\x20\xe8\x4a\xd4\x23\x58\xc1\ +\x85\x15\x3c\x88\xd0\x0b\x08\x82\x5e\x22\xe6\x25\xcf\x85\x8a\x82\ +\x74\x9d\x8c\x0b\x1b\x91\x36\x46\xac\xa9\x0a\xe6\x5f\x0d\xf3\x86\ +\x37\x1f\x33\xc3\xe3\x0d\xfc\x77\xc9\xa0\xc3\xda\xdb\x95\x94\x64\ +\x5f\x54\x96\x11\x66\x4b\xc9\xa2\x3c\xa8\xe8\x95\xc1\x6b\x2f\x2e\ +\x2e\x5c\x7e\x08\x10\x86\xd1\x2e\x22\x47\x79\x60\x25\x29\x45\x75\ +\xaf\xd9\x6c\x1c\x0f\x01\x58\x6b\x57\x15\x73\x01\x3c\x0b\xb2\x63\ +\x8c\x76\xeb\xf5\xfa\x53\x19\x59\xe3\x38\x9e\x4e\x53\x69\x29\xda\ +\x01\xa6\x04\xb3\x36\x58\x09\x6e\x6c\x74\x1e\xda\x58\xad\x75\x1b\ +\x65\x24\xcd\x93\xb5\x6e\x33\xb4\xb1\xde\xd8\xe8\x3c\xf3\x99\xcc\ +\x10\x95\x65\x00\x63\xb4\x3b\x2e\x00\xcf\xa3\x0b\x20\xc8\xd2\x10\ +\x40\x36\x70\x65\x95\x3d\x4f\xb5\x5a\xed\xb1\x6f\xce\x0d\x03\xfc\ +\x92\x2a\x80\x0a\xe0\xd7\x01\x26\x3e\x0b\x08\xa3\x68\x0b\x95\x43\ +\x60\xf2\x8b\x77\xf7\x10\x3d\x68\x36\x1a\x67\x45\x41\x85\x15\x08\ +\x82\x60\x1e\x95\xd3\x11\x92\x03\x4c\xa2\xd2\x09\x82\x60\x7e\x64\ +\x80\x9f\x50\x21\x80\xef\xfb\x77\x88\x6e\x03\xbd\x11\xee\xee\x21\ +\xba\xe3\xfb\xfe\x5d\x51\xd0\xa7\x33\xd0\xef\x61\x61\x1f\xbf\xa3\ +\xbf\xdd\x82\x0a\xa0\x02\xf8\x59\x00\xe5\x01\x5e\x3f\x90\xe3\x4a\ +\xe6\x9c\x9b\xe9\x9b\xf7\x43\x00\x2a\x7a\x05\x90\xa6\xd2\x1a\x17\ +\x40\x92\xd0\x02\x50\xf4\x3a\xf3\xbd\x3d\x44\x06\xaf\xad\xa4\xeb\ +\x8a\x76\xac\x75\xe2\x79\x74\xdf\xfd\xe1\xbe\x25\xe7\xdc\x4c\x92\ +\xd0\x52\xf4\x04\x48\x0d\x5e\x3b\x3b\xcb\x5b\x4c\xda\x8c\x6f\x36\ +\x3e\x5e\x4c\x32\xbd\xad\x66\xaf\x5f\xe7\xb9\xc1\xf3\x11\x75\xaf\ +\xe8\x75\xde\x6a\x56\xe9\x05\x72\xdf\x93\xde\xaf\x9f\x93\x4c\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x05\x36\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xe8\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x4c\x1c\x55\x1c\xc7\xbf\xbf\x99\x59\x4c\x7a\x21\x55\x1a\ +\x52\x69\x7a\x71\x9b\x88\x21\xa9\x48\x6f\xbd\x6c\x5c\x81\x43\x2b\ +\x91\xc0\x46\x8d\xd0\x34\xd9\x8d\xbd\x7a\xb1\x07\x12\x59\x20\x31\ +\xa6\xf5\xe4\xcd\xe8\x12\x1a\x25\x9a\x66\x5b\x30\x84\xc6\x00\x62\ +\x36\x2d\x7a\xa2\x92\x18\x5d\x2e\xc5\x03\x61\x0f\x18\x6c\xc3\xa9\ +\x59\xd8\x99\x9f\x07\xf6\xc9\xec\xec\xec\xce\x2c\xf3\x67\x07\xd9\ +\xcf\xed\xcd\xfc\x66\xde\x6f\xbe\xf9\xfe\xde\x7b\x33\x79\x03\x34\ +\x68\xd0\xe0\x24\x43\x76\x82\x22\x91\xa4\xa2\xb4\xe4\xfa\x88\xf1\ +\x2e\x80\x4b\x00\xda\x00\xbc\xe0\x69\x66\xb5\x93\x07\x90\x03\xb0\ +\xca\x84\xbb\x85\x9d\xb6\xb9\x4c\x66\xbc\x60\x75\x91\xa5\x00\x3d\ +\xfd\x89\x6e\x96\xf0\x05\x80\x76\x17\x92\xf4\x11\xca\x92\xc6\x1f\ +\x2d\xce\xa6\x96\xaa\x45\xc9\xd5\xee\xd0\x3d\x98\x18\x01\xe1\x0e\ +\x80\x33\xae\xe6\xe6\x0f\x67\x40\x18\x0e\xb7\x77\xee\x6d\xac\xaf\ +\xfd\x52\x29\xa8\xa2\x00\xdd\x83\x89\x11\x30\x3e\xf5\x26\x37\x1f\ +\x21\x8a\x86\xdb\x3b\xf3\x1b\xeb\x6b\x2b\xa6\xa7\xcd\x0e\x16\x6d\ +\xbf\x58\x72\x90\xf1\x8c\x89\x47\x25\x89\x1e\x34\x63\x77\x33\x9d\ +\x4e\xab\x1e\xa4\x7b\x64\x62\xb1\x98\xbc\x8b\xe6\xf3\x9a\xc6\x57\ +\x88\x69\x02\x84\xd3\xfa\xf3\xa4\xa1\xc7\xac\x1c\xca\x04\x88\x44\ +\x92\x4a\xe8\xa5\xdc\xef\xd0\xd5\x3c\x01\x3f\xa9\xfb\x18\x5a\x9e\ +\x4b\x6d\x7b\x92\xbd\xcb\x44\xfb\x12\xad\x72\x08\xd3\x0c\xbc\x75\ +\x78\x94\xb2\xfb\xff\xbc\x7c\xd1\x38\x30\x4a\xc6\x8b\x95\x96\x5c\ +\x1f\x4a\x07\xbc\xa7\xd0\x94\x0f\x8e\xcb\xc3\x03\xc0\xf2\x5c\x6a\ +\x5b\xdd\xc7\x10\x18\xcf\x0e\x8f\xf2\x6b\xc5\x67\x2b\xa1\x4c\x80\ +\xe2\x54\x77\x78\x19\x38\xb9\x38\xfb\xe5\xdf\x5e\x24\xea\x25\xcb\ +\x73\xa9\x6d\x06\x25\xf5\xc7\x8c\xcf\x06\x98\x08\x80\x83\x79\xfe\ +\x30\x40\xa2\x07\x2e\xe7\xe6\x1b\x92\xcc\xf3\xfa\x36\x01\x5d\x65\ +\x31\x26\xd7\xb5\xe9\x1b\xcd\xd8\xdd\x74\x39\x2f\xdf\x30\xe6\xce\ +\xc0\x39\x63\x8c\x99\x00\x25\x2b\xbc\xa0\x8d\xf6\xb5\x60\x92\x7b\ +\xd9\xea\xd5\x4c\x80\x13\x85\x52\xef\x04\xec\xd0\x1b\x8b\x87\x35\ +\x4d\x1a\x05\x78\x00\x00\x88\x71\xaf\xa0\x49\x13\x3f\xff\xf0\xd5\ +\x86\xd3\x7b\x07\xde\x01\xdd\x03\x37\x2e\x68\x1a\x3d\x04\x78\x18\ +\xc0\x29\x00\xa7\x98\x70\x4d\x96\xb5\x47\xbd\xb1\x78\xd8\xe9\xfd\ +\x03\x2d\x40\x24\x92\x54\xc0\xea\xf7\x00\xce\x9a\x9c\x3e\xcb\x2a\ +\x7d\xe2\xb4\x8f\x40\x0b\x10\x6a\xc9\xdd\x04\x95\x4f\x5d\x02\x26\ +\x0c\x3a\xed\x23\xb0\x02\xf4\xf4\xc7\x3b\xc0\x18\xf3\xba\x9f\x40\ +\x0a\x10\x89\x24\x15\x26\xba\x03\x20\x64\x11\x9a\x76\xda\x57\x20\ +\x05\xb0\xb2\x7e\x91\x3d\x4d\x52\x6f\x3b\xed\x2b\x70\x02\xd8\xb5\ +\x3e\x31\x8f\x2d\xa7\xa7\xb2\x4e\xfb\x0b\x94\x00\x35\x58\x7f\x75\ +\xef\xe9\xb9\xcf\xdd\xe8\x33\x50\x02\xd8\xb5\xbe\x04\xba\x6e\xe7\ +\x83\xa7\x1d\x02\xb3\x12\xec\xe9\x8f\x77\xb0\x4d\xeb\x2f\xcc\xa4\ +\xfe\x74\xab\xdf\x40\x38\xa0\x1e\xd6\x17\xb8\xe2\x80\x37\xdf\xf9\ +\xf0\x15\x45\xd2\x46\x0f\x17\x26\x74\x5f\x92\xb4\x89\x85\xf4\xe4\ +\x13\x3b\xd7\x87\x5a\x72\x37\xc1\xfe\x5a\x5f\xe0\xd8\x01\xbd\xb1\ +\x78\x58\x96\xb5\x47\x4c\xb8\x86\xe2\x5a\x1d\xe0\x61\x4d\xa3\x87\ +\xdd\x03\x37\x2e\x58\x5d\x5f\xcb\xa8\xbf\x70\xff\x6b\xd7\xac\x2f\ +\x70\x2c\xc0\xc1\x5b\x9a\xf9\x5a\x1d\x50\xbf\x8b\x44\x92\x15\x5d\ +\x56\x4f\xeb\x0b\x5c\x18\x03\x0e\x5e\x51\x2b\x70\xa9\xe9\xc5\xad\ +\x8f\x2b\x9d\xac\xc7\xa8\x6f\xc4\xf3\x41\x90\x89\xc6\x7a\xfa\xe3\ +\x1d\xc6\xe3\xf5\xb6\xbe\xc0\xb1\x00\xc4\xb8\x67\x11\xd2\xc4\x12\ +\x4d\xe9\x4b\x21\x08\xd6\x17\x38\x16\x40\x95\xd5\x5b\x00\xf6\x2c\ +\xc2\x4a\x4a\x21\x08\xd6\x17\x38\x16\x60\x39\x3d\x95\x05\x61\xdc\ +\x2a\x4e\x94\x42\x50\xac\x2f\x70\x65\x0c\xd8\xdf\x69\xbb\x0d\xc6\ +\x63\x8b\xb0\x26\x96\xe8\x5b\x96\xa4\x69\x04\xc0\xfa\x02\x57\x04\ +\xc8\x64\xc6\x0b\xc4\x7c\x1d\xd6\xa5\xf0\x3a\xc0\x17\x2d\x62\x7c\ +\xb1\xbe\xc0\xb5\x59\x60\x71\x76\xf2\x0f\x3b\xa5\x60\x85\x5f\xd6\ +\x17\xb8\x3a\x0d\xda\x2c\x85\x6a\xf8\x66\x7d\x81\xab\x02\xd4\x50\ +\x0a\x66\xf8\x6a\x7d\x81\xeb\x0b\xa1\xa3\x96\x82\xdf\xd6\x17\x78\ +\xb2\x12\x3c\x42\x29\xf8\x6e\x7d\x81\x27\x02\xd4\x58\x0a\x75\xb1\ +\xbe\xc0\xb3\x77\x01\xbb\xa5\x50\x2f\xeb\x0b\x3c\x7d\x19\xb2\x51\ +\x0a\x75\xb3\xbe\xc0\x53\x01\x32\x99\xf1\x82\x24\xf3\x7b\x00\xcc\ +\x36\x59\x6c\x4a\x12\xbf\x5f\x2f\xeb\x0b\x3c\x7f\x1d\x5e\x48\x4f\ +\x3e\x51\x18\x97\x19\x98\x07\xf0\x1c\xc0\x73\x06\xe6\x15\xc6\x65\ +\xbb\x9f\xcc\xbc\xc4\x97\xaf\xc2\x3f\xce\xa4\xb6\x00\xbc\xed\x47\ +\x5f\xb5\x12\x88\xaf\xc2\xf5\xc4\x4c\x80\xbc\xbe\x11\x8b\xc5\xaa\ +\xed\x27\x0e\x34\x26\xb9\xe7\x8d\x31\x66\x02\xe4\xf4\x8d\x5d\x34\ +\x9f\x77\x33\x29\x3f\x31\xe6\x4e\xc0\x96\x31\xc6\x4c\x80\x55\x7d\ +\x43\xd3\xf8\x8a\xcb\x79\xf9\x86\xa6\xd2\x55\x7d\x9b\x51\x3e\x25\ +\x97\x09\xc0\x84\xbb\xfa\x36\x31\x4d\x44\xfb\x12\xad\xee\xa7\xe7\ +\x2d\xd1\xbe\x44\x2b\x81\x4b\x16\x62\xc6\x67\x03\x4c\x04\x28\xec\ +\xb4\xcd\x01\x58\xff\xef\x00\xe1\xb4\x1c\xc2\xf4\x71\x12\x41\x6c\ +\x96\x2e\xdd\x31\x4e\xd9\xe2\xb3\x95\x50\xdb\x76\x79\x50\x52\x92\ +\x79\x3e\xd0\xdb\xe5\x55\xba\x4a\xe0\xf1\x23\x6f\x97\x17\xfc\x6f\ +\x7e\x98\x00\x40\xcc\x23\x8b\x33\x93\x9f\x99\x9d\xab\x38\xc5\xfd\ +\x95\xfd\x6d\x25\xdc\xde\x99\x07\x51\xd4\xbb\xd4\x3c\x87\x19\x18\ +\x59\x9a\x99\xbc\x55\x29\xa0\xea\x1c\xbf\xb1\xbe\xb6\x12\x7e\xf5\ +\x8d\x5f\x41\xd4\x85\x63\xf7\xdf\x10\x65\x49\xc3\xd0\xd2\x4c\xea\ +\x9b\xaa\x51\x76\x6e\xa5\xff\x6d\x8e\x80\xae\xe2\xae\xeb\xc0\xfd\ +\x36\x47\xc0\x16\x03\x8f\x6b\xf9\x6d\xae\x41\x83\x06\x27\x9b\x7f\ +\x01\x0f\x15\x0b\x99\x9e\x82\xdf\x92\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x05\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb7\x49\x44\x41\x54\x58\x85\xed\ +\x96\xbd\x4a\xc3\x50\x14\xc7\xff\x27\x1f\x53\xc1\x07\xf0\xda\x34\ +\x43\xf7\x82\x93\x08\xe2\x2b\x88\x0e\xd2\xc5\x17\xd0\x45\x10\x71\ +\xe9\xd4\xc1\x41\x74\x29\x3e\x81\x93\x43\x9f\xc0\x45\x90\x82\xa3\ +\x7d\x80\x62\x3e\x50\x33\xb8\xe8\x20\xa1\x69\x7b\x1c\x6c\x42\x13\ +\x9b\x34\xe9\xe7\xd0\xfe\xa7\xfb\x71\xee\xfd\xff\x72\xee\xb9\x97\ +\x00\xcb\x2e\x4a\x9a\x74\x1c\x27\xe7\xba\xed\x2a\x88\xf6\x01\x14\ +\x26\xf4\x32\xc1\x54\x57\x55\xaa\x08\x21\x7e\x46\x02\x38\x8e\x93\ +\x73\xdb\x5e\x03\x8c\xd2\x84\xc6\x61\x11\x9a\xaa\x2c\x6d\xfb\x10\ +\x52\x5c\x9c\xeb\xb6\xab\x53\x37\x07\x00\x46\xc9\xf3\xb8\xea\x77\ +\x63\x01\xfa\x69\x9f\x8d\x88\x0f\xfc\xa6\x92\x10\x16\x3a\x73\xbd\ +\x90\x4f\xac\x97\x51\x32\x4c\x9b\x87\xed\x1d\x9f\x81\x39\x69\x05\ +\xf0\xaf\x06\x5a\xad\x37\x4d\x51\x78\x97\xc1\xa1\x71\xc3\xb0\x4f\ +\x62\x77\x91\xb8\x47\x2c\x37\x35\x6d\xfd\x99\x88\xba\x59\x00\x42\ +\x85\x65\x18\xd6\x19\x88\x2e\x87\x81\xa5\x11\x03\x4f\xc4\xdd\x43\ +\x5d\xd7\x3f\xa2\x73\x91\x22\x0c\x8a\x3a\x38\x82\x57\xcb\x2a\x83\ +\xe8\x6a\x5c\x73\x00\x20\x60\x87\x49\xbe\x67\x66\x39\xed\x9a\x00\ +\x80\x98\xce\xc7\x35\x8e\x42\x58\xd6\xfb\x56\xda\xf8\xc1\xaf\x0d\ +\xbf\x7a\x84\xdb\xd4\xae\x8c\x3d\x00\x22\xe8\x52\xb7\x04\xa0\x91\ +\x15\x20\x54\x0f\xba\x96\x8f\x2f\xba\x88\x0c\xcb\x06\x18\xc7\xc1\ +\x40\x8f\x52\xdf\xae\x85\x5f\xc3\x15\xc0\x0a\x60\xe1\x00\x63\xbf\ +\x7a\x89\x22\xd4\x0c\xd3\xae\x25\x44\x98\x7e\x63\x31\x19\x60\xaa\ +\xfb\xcd\xd9\x64\x20\x49\x84\xa6\xaa\x50\xc5\xef\xce\x33\x03\x26\ +\x98\x6e\x06\xff\x88\xff\x78\xfa\x32\x4c\xfb\x0b\xc0\xda\x34\x9c\ +\x08\x74\x54\x28\x6c\xdc\xa5\x89\x1d\xcc\xc0\xc3\x34\xcc\x01\x74\ +\x3c\x85\x1e\xd3\x06\x07\x00\x1d\x45\x3a\x05\xf0\x39\xb1\x3d\xf3\ +\x45\x51\x08\x3b\x33\x40\x51\x08\xbb\xa3\x48\x9b\x00\xea\x00\xbe\ +\xb3\xda\x02\x78\x61\xe2\xb2\xae\x6b\xd7\x19\xd7\x2e\xb9\x7e\x01\ +\xf9\xaa\x7b\xc5\x23\x95\x73\x7f\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\xa6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x58\x49\x44\x41\x54\x58\x85\xed\ +\xd2\x31\x2f\x43\x51\x18\xc6\xf1\xff\x39\x15\x03\x89\x10\x42\xba\ +\x11\x9b\x89\xb0\x89\x45\xb4\x69\xd0\x44\xb5\xb5\xd5\xc0\x15\x12\ +\x1f\xc0\x66\x12\x1f\xc0\xac\xb5\x34\x62\x68\x99\x08\xad\x44\x42\ +\x48\x37\x11\xc2\xd6\x45\x27\x83\x44\xca\xe4\xde\xfb\x5a\x19\x38\ +\xda\x2e\x12\xe7\x37\x3f\x79\xce\xf3\x26\x07\x2c\xcb\xb2\xac\xff\ +\x4e\x99\x02\xa1\xb8\xb3\x0d\x0c\x2b\x5f\x52\x85\x83\xf4\xdd\x6f\ +\x4a\x23\x33\x2b\xbd\x5e\xc0\xcd\x02\x2f\xc5\xfc\xf6\x34\x20\xdf\ +\x65\xb5\x79\xa1\xb4\x03\x83\xa2\xf5\x65\x38\xe6\x8c\x9b\xf2\xe1\ +\xa4\x33\xec\x35\xb9\x25\x60\x14\xa4\xd3\x94\x37\x0e\xa8\xea\xb6\ +\x14\x8a\x1c\x48\x9b\x68\x8e\x27\x12\xce\xfc\x77\xd9\x89\xd9\xc5\ +\x29\xf1\x39\x47\xe8\x11\xd4\xd9\xbb\xe7\x45\xf8\xe1\x7a\x80\x80\ +\x69\x40\xe5\xbe\xe4\xa6\x92\xd1\x7c\xe5\xe9\xb5\x15\x18\x53\x10\ +\xeb\x1f\x18\x92\xf2\xc3\xf5\xf9\xe7\x5c\x28\xbe\xb4\xa2\x14\x59\ +\xa0\x19\xc8\x76\xe8\x97\xb9\xa3\xfd\xdd\x37\x53\xbf\xf1\x0f\x7c\ +\x7d\xc4\x59\x05\xb6\x00\x8d\xb0\xf3\xdc\xa5\x97\xa7\x83\x41\xef\ +\xea\xb6\xb2\x89\x52\x6b\x00\xa2\x64\xe3\x34\x97\x5e\xc7\x70\x79\ +\x5d\x03\x00\xc2\xf1\xc5\xa8\xa0\xf6\x80\x16\x81\x0b\x05\x55\x60\ +\x12\x70\x15\xb2\x5c\xc8\xa7\x33\xb5\xf4\xd5\x3c\x00\x20\x14\x5f\ +\x18\x01\x7d\x08\x74\x03\x08\x54\x95\xf2\x13\xc5\x5c\xa6\x50\x6b\ +\x57\x5d\x03\x00\xc2\x49\xa7\x4f\x7c\xca\xc0\xa3\xf6\xfd\xe8\xc9\ +\x41\xe6\xa6\xde\xae\x46\x28\x1a\x38\xc2\xb2\x2c\xcb\xfa\x13\x3e\ +\x00\x77\x85\x6b\x30\xd4\xa0\xe5\x67\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\xa5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x57\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xcd\x2b\x44\x51\x1c\xc6\xf1\xef\xb9\x93\xd2\x28\x29\xe5\x65\ +\xc7\x7f\x20\xf7\x92\xb2\xb3\x9a\x30\x3b\x65\x35\x56\x9a\x3b\xc2\ +\x88\x8d\xdd\xac\x64\xa5\xa6\xb9\x77\x33\x23\x79\xa9\x59\x58\x58\ +\x29\x25\x1b\x45\x22\xae\xa2\xac\x6d\x94\x6c\x88\x14\xa9\x3b\xf3\ +\xb3\x30\x0b\xd4\xb8\x33\x63\x25\xe7\xb3\x3c\x3d\x3d\x3d\xa7\x73\ +\x40\xd3\x34\x4d\xfb\xef\x54\x50\xc0\xb2\x33\x2b\x60\x98\xa8\x62\ +\xcc\xcb\xce\x5c\x55\x52\xda\x97\x48\x77\xf8\x12\xca\x83\x7a\xf2\ +\x72\x53\xc3\xa0\xa4\x5c\xd6\x08\x6c\x13\x9a\x40\xba\x10\x75\xd4\ +\x9d\x70\x07\x82\xe2\xdd\x13\x19\xd3\x97\xd0\x09\xd0\x0f\x34\x07\ +\xe5\x03\x07\xd4\x35\x14\x62\xc0\x16\xd0\x68\x88\xec\x5a\xb6\x33\ +\x56\x2e\x6b\xc6\x9d\x21\xa3\xa8\x0e\x80\x56\x60\xdf\x7f\xf3\x23\ +\x3f\xdd\xbe\xa2\x01\xc7\xe9\xb9\x57\xaf\xed\x7e\x54\x50\x4b\x40\ +\x1d\xb0\xd1\x63\x3b\x29\x90\x2f\xcf\x67\xda\x6e\x42\x29\xb6\x81\ +\x30\x48\xfe\xe5\xe1\x3e\x72\xb1\x3e\xfb\x18\xd4\x1f\xf8\x07\x3e\ +\xb3\xe2\x99\x49\x94\x72\x3e\x86\xcb\x9a\x48\xbd\x7d\xde\x7e\x5b\ +\xb0\xee\x9a\x17\x81\xf9\x52\xe1\xc2\x59\x6e\x3a\x15\x74\xf3\x9a\ +\x06\x00\xf4\xd8\x4e\x54\x60\x13\x08\x2b\x38\x14\xd4\x33\xc8\x20\ +\xe0\xa3\xb0\xbd\x6c\x72\xb5\x9a\xbe\xaa\x07\x00\xf4\xda\xae\x25\ +\xc8\x8e\x40\x4b\xe9\xe8\x59\x84\x91\xf3\xe5\xe4\x5e\xb5\x5d\x35\ +\x0d\x00\xe8\x1d\x77\x3b\x8b\x21\xb9\x06\x6e\x0c\x88\x9e\xe6\x92\ +\x97\xb5\x76\xfd\x82\xa8\xef\x9f\x51\xd3\x34\x4d\xfb\x73\xde\x01\ +\x57\x2b\x69\x45\xc4\x74\x4c\x85\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x02\xdb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8d\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x4f\x48\x54\x51\x14\xc6\x7f\xe7\x8d\xb8\x11\x82\x12\x03\x75\ +\x35\xb8\x10\xc9\x4d\x6d\x32\x8c\x28\x9c\xa6\x85\x12\x18\x6f\xb6\ +\x12\xcc\x64\xad\x5c\xa9\x2d\x87\xc1\xd5\x04\x2d\x12\x92\x2c\x27\ +\x28\x17\x19\xc6\xb8\x49\x28\x07\x13\x02\xff\xb4\xa9\x8d\xd5\x4e\ +\xdd\xd8\x42\x29\x68\xe1\x46\x98\x7b\x5a\xf8\xde\xf4\x1c\x9a\x3f\ +\x6f\x7c\xb6\xa8\x6f\xf5\xde\xb9\xe7\x9e\xef\x7b\xdf\xb9\x97\x77\ +\x2f\xfc\xef\x90\xe2\xc0\xd5\x1b\xf1\x6e\x44\xee\x02\x5d\x40\x53\ +\x40\x3c\xbb\xc0\x1a\xaa\xe9\x5c\x36\xb3\xec\x1d\x08\x79\x5f\x22\ +\x76\x7c\x58\x90\x17\x40\x3b\xd0\x10\x10\x39\x4e\xad\x76\x44\x6e\ +\xb6\x75\x9c\xdb\xdb\xf8\xfa\x71\xd5\x1d\x28\x38\x10\x89\x0d\x5e\ +\x14\x63\xde\x03\x3f\x51\x1d\xb2\x42\xcc\xbf\x9d\xcd\xfc\x08\x82\ +\xfd\x5a\x2c\x7e\xca\xe4\xe9\x45\x64\x1c\x38\x81\xea\x25\xd7\x89\ +\xba\x82\x12\x63\x46\x01\x41\x75\x28\x97\xcd\x4c\x07\x41\xec\xc2\ +\xf9\x90\xe9\x88\x9d\x10\x51\x9e\x39\x2d\xbe\x0e\x60\x79\xf2\xba\ +\x00\xac\x10\xf3\x41\x92\x7b\xa1\xf9\x7d\xb7\xf6\x79\x37\xe6\x15\ +\xd0\xe4\x51\x7b\x2c\x58\x9c\x7b\xfe\xdd\x79\x3c\xed\xc6\xea\x4a\ +\xe4\xd6\x8c\xa8\x7d\xab\x4f\x55\x1f\x03\x88\xc8\xe0\xc2\xab\x27\ +\xaf\xcb\xe5\x07\x2a\x20\x1a\x4b\x84\xd5\xe8\x0c\xce\x0e\x72\x84\ +\xb4\x94\x9b\x63\x95\x1b\xf4\x83\x64\x32\x69\xa9\xe1\x29\x3e\xb7\ +\x6f\x60\x02\x56\x3f\x7f\xbb\x03\x5c\xf6\xc6\x14\xc6\xfe\x8a\x80\ +\x68\x2c\x11\x56\xd5\x7b\x87\xc9\x65\xa9\xbb\xb3\x75\xf2\xd8\x05\ +\x94\xb0\x7e\xcf\xb2\x34\x9e\x4a\xa5\x4c\xa5\xf9\x15\x17\x61\xa5\ +\x55\x5d\xc2\xfa\x91\xdc\xec\xd4\x66\x35\x1f\x50\xd1\x01\x87\xbc\ +\x19\x68\x56\xd5\x99\x68\x2c\x11\x2e\x88\x3b\x82\xf5\x2e\xfc\x6e\ +\xc3\x06\x63\x24\x93\x4c\x26\x23\x00\x2b\xeb\xdb\x35\x5b\x5f\xb5\ +\x00\x85\x31\x81\x09\xf7\x5d\xd0\x2b\xcb\xeb\xdb\xb7\x2d\x11\xe1\ +\x08\xd6\xbb\xa8\xd8\x82\xee\xce\xd6\x49\x45\x96\xbc\x31\x81\x09\ +\x55\x7d\x78\x98\xdc\x9f\xf5\x55\x0b\x48\xa5\x52\xc6\xb2\x34\x0e\ +\xec\x95\x49\xf3\x6d\x7d\xd5\x02\x00\x16\x66\xa7\x36\x45\x64\xb4\ +\xd4\xb8\xc2\xc8\x82\x4f\xeb\x7d\x09\x00\xb8\x70\xa6\xe5\x51\x71\ +\x2b\x0e\xc8\x6b\xb3\xde\xb7\x80\x12\xad\xa8\xd9\x7a\xdf\x02\xe0\ +\xa0\x15\xc6\xa8\x0d\xba\x05\xba\x65\x8c\xda\xb5\x5a\xef\xc2\xf7\ +\xef\x78\x71\x2e\xf3\x06\x08\x57\x4c\xac\x12\x5e\x07\x76\xe1\xe0\ +\x00\x19\x54\xf1\x62\xf4\xf4\x0f\x34\x3a\x8f\x3b\x7f\x12\xb0\x06\ +\x60\xf2\xf4\x1e\x97\x00\x09\xd5\xbb\xb5\x3f\xb8\xb1\xdf\x2d\x50\ +\x4d\x23\xd2\x87\xc8\x78\xc4\x4e\x88\xe6\xf7\xe7\x3d\x67\xb8\x23\ +\xa1\xa7\x7f\xa0\x51\x42\xf5\xbd\xa2\x3c\x00\x0c\xaa\xe9\x82\x28\ +\x6f\x62\xc4\x8e\x0f\x8b\x4a\x9a\x00\x0f\x2a\x45\x30\x28\xa3\xb9\ +\xec\xd4\x7d\x37\x70\xe8\x66\xb4\xf1\xe5\xd3\x4a\x5b\xc7\xd9\x45\ +\x44\x9a\x80\x93\x04\x77\x3b\xda\x01\xde\xa1\x9a\xc8\x65\x33\x2f\ +\x03\xaa\xf9\x8f\xe0\x17\xaf\x0f\x09\xa8\xe3\xe3\x70\xe1\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x07\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb9\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x51\x0d\x83\x50\x10\x05\xd1\xa5\xc1\x1a\x0a\xb0\x80\xac\x5a\ +\xa8\x02\xc4\x81\x8c\xd3\xe4\xcd\x18\xd8\xc9\xe4\xfe\xed\x0c\xe4\ +\x38\xaf\xe7\x38\xaf\x47\x3a\x7c\xe4\xf1\x7f\xa0\x00\x5a\x40\x53\ +\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ +\x02\x9a\xe5\x03\x6c\xf2\xb8\x7e\x8d\xcf\xb4\x80\xd9\xb5\xc0\xcc\ +\xcc\xfd\xfb\xb2\x25\x2e\xbf\x80\x02\x68\x01\x4d\x01\xb4\x80\xa6\ +\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ +\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ +\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x96\x0f\ +\xf0\x02\x2e\x56\x08\x76\x9d\x62\x12\xf1\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x86\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\xf0\x84\x1f\x0c\x13\x11\ +\x50\xee\xf5\xff\xb3\x11\x8b\xb2\x7a\xb2\x7a\x36\x1f\x6f\x33\xbe\ +\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\ +\x03\xf8\x62\x04\x97\x5f\x3b\xc3\x6b\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7d\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\xc1\x0d\x80\x20\x14\x05\x41\xb4\x29\xba\xa6\x10\x8b\x12\xcb\ +\x58\x13\x66\x1a\xf8\x2f\x1b\x6e\x8c\x11\x9a\xeb\xdd\x73\xbd\xbb\ +\xdc\x70\x97\xc7\xff\x40\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ +\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ +\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\ +\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\x4d\x80\x7a\x40\xed\xf8\x00\ +\x57\x79\xbc\xfe\x1a\x1f\xa3\x7f\x01\x4f\x7c\x1f\x00\x00\x00\x00\ +\x00\x00\x00\x4e\xf0\x01\xb9\x04\x09\xb0\x92\x01\xea\x01\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x1b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcd\x49\x44\x41\x54\x58\x85\xed\ +\x96\xb1\x4a\x23\x51\x14\x86\xbf\x93\x64\x13\x54\xb0\x70\x8b\x2d\ +\x04\xc5\x17\x30\xa0\x23\x2c\x82\xec\x2b\x2c\x8a\x8a\x85\x96\x8e\ +\x10\x89\x08\x22\x36\x56\x29\xb6\x08\xbb\xab\x23\x2b\x9b\xb4\x56\ +\x2a\x79\x02\x1b\x41\x04\xc1\x04\xf4\x09\x54\x2c\x54\xd0\x42\x0b\ +\x41\x50\x8f\x85\x4e\x4c\xa2\x33\xce\x24\xd1\x14\xe6\xaf\xee\x9d\ +\x39\x73\xff\x6f\xce\x3d\x73\xe6\xc2\x67\x97\xb8\xdd\xec\x1c\x4d\ +\x36\x85\x1b\xc2\x09\x90\x7e\x84\xf6\x8a\x9c\x94\x23\x84\x8c\x6a\ +\x64\x3e\x97\x36\xaf\xdf\x04\xe8\x1c\x4d\x36\x7d\x69\x8c\x6c\x0b\ +\x44\x2b\x32\x7e\xc1\xc1\x3e\x1a\xe9\xb5\x21\x02\x4e\x81\xe1\x86\ +\x70\xa2\xda\xe6\x00\x02\x51\x91\x9b\x84\x3d\x77\x04\x00\xe9\xaf\ +\xb6\x79\x5e\xca\x80\x3d\x0c\x39\xfb\x17\xef\x79\x36\x15\x77\xad\ +\x97\xb7\x64\x98\x96\xbe\xb6\xb6\x4b\x06\x3e\x46\x75\x80\x17\x35\ +\xd0\x3d\xbe\xd0\x26\x01\xf9\x81\x16\x5f\x37\x26\xac\x49\xa7\x45\ +\x44\xe5\x5e\x85\xfd\x8e\x8b\x6f\x3b\xeb\xeb\x43\x77\x65\x03\xf4\ +\x98\x8b\x33\x8a\xfc\x42\x5f\x29\x4e\x65\xc9\x69\x11\x45\x41\xe1\ +\xb0\xe5\x74\xab\x7b\xfc\xef\x70\x2e\x3d\x7d\xe2\x15\x20\xbf\x05\ +\x86\x69\x8d\x28\x92\x2c\x85\xf2\x23\x85\xbe\x80\x04\x57\x07\x07\ +\xd7\x82\xbe\x01\x40\x66\xcb\x35\x2e\x85\x38\xf8\x7a\xf6\xdd\x6b\ +\x7c\xc1\xdb\x6a\x69\xd7\xfb\xe7\xdd\x54\x7e\x0a\xda\x6a\xcf\x45\ +\x89\x02\xdb\x3e\x01\x8a\xff\x0b\xd9\x54\xdc\xb1\xe8\x4a\x65\x98\ +\x16\x40\x2c\x0f\x24\xea\xf9\xeb\xaa\xf9\x67\x58\x07\xa8\x03\xd4\ +\x1c\xa0\xec\xae\xe7\x2a\x65\xc9\x30\x2d\xc7\xd6\x8d\x72\x64\x0f\ +\x6b\x93\x01\x21\x63\x0f\xdf\x27\x03\x2e\x7a\x3a\x94\xce\xdb\xf3\ +\x8f\xcb\xc0\x63\xda\xff\x14\x9e\x88\xa1\xa0\xfd\x1a\xa6\x75\x09\ +\x34\x57\xc5\x4c\x74\x2c\xfb\x7f\x6a\xc5\x4b\xe8\x73\x06\x54\x37\ +\xaa\x62\x0e\xb7\x12\x08\x6d\x7a\x0d\xce\x03\x48\x28\x34\x0d\x9c\ +\x57\xea\xae\xca\xdc\xee\x72\xec\xd8\x37\xc0\xee\x72\xec\x58\x82\ +\xc1\x2e\x54\x33\xc0\x95\x5f\x5f\x90\x3d\x44\x47\x72\xe9\xf8\x6f\ +\x9f\xcf\x7e\x72\x3d\x00\x27\x99\x79\x91\xf6\x77\x59\xd9\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x95\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\xd8\x29\x2d\x13\x67\x02\xa4\ +\x6c\x16\x31\x84\xe9\xf8\xef\x63\x5d\x1b\x89\x8c\x22\xbb\x22\xbb\ +\x9c\x8d\x65\x1a\xb6\x79\xaf\xe9\x0e\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x80\x9b\xf7\x19\x0d\x9d\x47\x8e\x8f\xbb\ +\xb2\xd3\x06\x7c\x18\x63\x85\x7e\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\x35\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe7\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xb1\x11\xc2\x30\x14\xc5\x9e\x19\x22\x13\x31\x01\xc7\x06\xd0\ +\x30\x11\x0d\x23\x70\x4c\xc0\x34\xa9\xb2\x85\x29\x08\x5d\x3a\xdb\ +\x88\x3b\xa4\xea\x17\xff\x12\x7d\xf5\x4e\x44\xe4\x9f\x29\xa3\x7f\ +\xb0\x3f\x9e\x0f\xa5\xe6\x9a\x24\xb5\xe4\xf2\xbc\xdf\x1e\x3d\xf7\ +\x5b\xd9\x8d\xfc\x78\x92\xac\xc7\x4c\x49\xa6\xcf\x61\x3d\xf7\x5b\ +\x19\x1e\x20\xef\x63\xb6\xe6\x5e\xfb\x4d\x7c\x23\xc0\x4f\x63\x00\ +\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\x06\ +\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\x63\ +\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\x34\ +\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\x40\ +\x63\x00\x5a\x80\xc6\x00\xb4\x00\x8d\x01\x68\x01\x1a\x03\xd0\x02\ +\x34\x06\xa0\x05\x68\x0c\x40\x0b\xd0\x18\x80\x16\xa0\x31\x00\x2d\ +\x40\x63\x00\x5a\x80\x66\xfc\xa3\xa9\x64\xd9\x9a\x7b\xed\xb7\x32\ +\x3c\x40\x4d\x4e\x49\xe6\x24\xf3\x3a\x77\xdd\x17\x11\x69\xe1\x05\ +\x2c\x27\x22\x30\x10\x9e\x42\xf3\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\x51\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x03\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\xfb\x9a\x0a\x04\x0a\x3c\x1b\ +\x20\x21\x81\x04\x8b\x83\x05\xb0\x06\xdc\x4c\x48\x58\xc0\x50\xcf\ +\x18\x40\xa2\xf0\x48\x12\x70\xd8\x51\x84\x1d\xa0\x48\xc8\x38\x04\ +\x99\x4c\xda\x5e\x2c\x79\x0f\x70\x7d\x93\xd0\xff\x93\xe7\x56\x9c\ +\x1e\xd3\x4a\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc0\x20\xd8\xdf\ +\x67\xb7\x83\xc9\x79\xc8\x53\xa5\x1f\x4f\x52\xa7\xba\xee\x7e\xbb\ +\xff\x38\xc0\xee\xc9\xc5\x86\x59\x35\x95\x74\x2c\x69\xad\xa7\x6e\ +\xb9\x2c\xe4\x7e\xdf\x56\xc5\xf8\xf9\x7a\xf4\x16\x1f\x93\x01\xf6\ +\x47\x97\xeb\xcd\x52\x2f\x26\x6d\x65\xa9\x97\x8b\x69\x1e\x9a\x6e\ +\x7b\x76\x73\xfa\xfe\x3d\x2e\xe2\xe7\xda\xa5\xea\x7f\xf7\xf2\x92\ +\xe4\xda\x6c\x42\x31\x8d\xe3\x64\x00\xb9\x1d\x66\x29\xb4\x02\x26\ +\x1d\xc5\x59\x3a\xc0\xc0\xa4\x03\x98\x3f\xae\xa0\x47\x16\x2e\x3d\ +\xc4\x59\x32\x40\xa8\x34\x71\xe9\x35\x4b\xa3\x9c\x4c\xf3\xb2\xed\ +\xce\xe2\x38\x19\x60\x76\x35\xfe\x08\x65\xb1\x27\xe9\x56\xd2\x67\ +\x8e\x6e\x3d\x5b\xc8\xfd\xae\x2d\x6d\x27\xfe\x02\x48\xfc\x08\x01\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x43\xf1\x05\xad\xf1\x3c\x35\ +\x36\x50\x8e\x69\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x01\x8b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3d\x49\x44\x41\x54\x58\x85\xed\ +\x93\x3f\x2f\x43\x61\x14\x87\x9f\x73\x5b\xc1\xd0\x88\x6f\xd0\x5d\ +\x62\xbb\xda\xc9\x62\x34\x48\x2b\x6c\xc2\x66\xf0\x09\x24\x12\x3a\ +\x58\x7c\x01\x7f\xd2\xc1\xaa\xf4\x76\x31\x4b\x2c\xa2\x9d\xd4\x07\ +\x10\x2c\xc2\xa2\x93\x84\xd4\xfb\x33\x50\x4d\x6c\xf7\xbd\xc9\x5d\ +\xdc\x67\x3b\xc9\x7b\x7e\xe7\xc9\xc9\x79\x21\x23\x23\xe3\xbf\x63\ +\xb1\x5e\x4b\x56\x6a\xc9\x01\xbc\x9b\x4d\xde\x54\xac\x97\x54\x20\ +\x88\xf5\x7a\x67\x28\x3c\x2a\xbd\x2e\x35\x94\x4b\x57\xa0\x66\x4e\ +\xd8\xf2\xa0\x7c\xcc\xab\x9f\xae\x00\xd0\xa9\xda\xa9\xd0\xee\xa0\ +\x2e\x45\xae\x9b\xaa\xc0\xb7\x44\x6e\x0b\xb8\xf8\x29\xa7\xcb\xd1\ +\xe7\xbe\xaf\x40\xbc\x23\xfc\x43\x29\x72\x1a\x26\xd9\x7a\xbb\x62\ +\x47\x71\x33\xbc\x36\x30\xa0\xdd\xb5\xe1\x11\x4a\x87\x61\x53\xb3\ +\xa9\x0a\x50\x33\x37\xde\xb7\xc2\x6f\x98\xe9\x32\x5d\x01\xe0\x05\ +\x3e\x80\x7b\xdf\xfe\x64\x02\x92\x15\x46\x5c\x1d\x28\x02\xcf\x39\ +\x59\x31\x55\x81\x72\xe4\xb6\x91\xad\x00\x6f\x98\xcd\x5f\x2d\xda\ +\x43\xdc\x0c\xef\x5f\x30\x13\x69\xd5\xd0\x31\xe0\x84\x2d\x74\xaa\ +\x76\xee\x93\xe3\xb5\x81\xb0\xa5\x39\x43\x75\x00\x61\x1b\xbe\xc3\ +\xbd\x04\xc2\x33\x4d\x05\x52\x13\xc8\x9b\xb4\xd7\xa9\xda\x81\xef\ +\xf0\xf8\x02\x92\x05\x81\x1a\xc0\x04\xa6\x93\xeb\xdb\x60\x33\xc9\ +\x70\x80\x7c\xdc\x06\x83\x27\xe0\x6e\xac\x17\xac\x51\x33\x97\x54\ +\x20\x23\x23\x23\xe3\x0b\x46\x70\x62\xa1\x9b\x7f\x53\x6a\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xb2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\x73\x93\x72\x03\x3a\x70\x82\ +\x96\x89\x89\xb9\x8d\xc4\x58\x04\x5c\xa1\x03\xb7\xf0\x35\x90\xe8\ +\x15\x2a\x04\x2c\x88\x42\x7b\x08\xa0\x9c\x80\x01\x26\xf6\xd2\x98\ +\x81\x86\xa2\xa6\x21\x76\xe2\x84\x01\x8f\xf6\x93\x7f\x9f\x6c\xe7\ +\x29\xf0\xdf\x87\xd4\x89\x45\xfd\x41\x4b\x85\xe6\x12\xe4\x65\x3c\ +\x1a\x9e\x00\xa8\x7a\x71\xa6\x20\xfb\x60\x76\x92\xf9\x5a\x02\xac\ +\x70\xda\xc0\x73\x3c\x97\xc3\x64\xad\xf2\x2b\x48\xe3\x74\xef\xaf\ +\x86\xaf\xb5\x04\xc8\xc3\x2b\x0d\x60\x83\x57\x16\xc0\x16\xaf\x24\ +\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\x11\xdc\x5b\x00\x5b\xfc\xe0\ +\xe8\x74\xdb\xa8\x8f\x1b\x83\xbc\xdf\x8d\xce\x7b\xe0\xa1\x11\x39\ +\xe2\x13\x60\x4f\x30\xcd\x64\xbe\x54\x80\x02\xf8\x2e\xf0\x28\x71\ +\x70\x9c\xac\x15\xbe\x82\x12\x78\x74\x7b\x71\xf6\x56\x2a\x80\x2f\ +\xbc\x50\x00\x37\x7c\x31\x05\xd3\x01\x9e\x24\x0e\x7a\xeb\xb8\x73\ +\x00\xdf\xb8\x53\x80\x2a\x70\xb0\xfc\x0a\x6c\xf1\xa8\x3f\x68\xb9\ +\xe0\x60\x71\x02\x2e\xb8\x0a\x65\xe2\x82\xe7\x06\x28\x86\xcb\x4c\ +\xe2\x46\x77\x13\xee\xd4\x09\x2b\xc2\x53\x9d\x30\xa8\x0f\x5f\x4c\ +\x81\x0e\x6b\x9d\xb0\x51\x0e\x67\xb9\x69\x36\x1e\xf5\x07\x2d\x09\ +\xcc\xcf\x87\x99\xdd\x09\x0b\xe0\x6d\x90\x59\x3c\x37\xbd\xa2\x0f\ +\x53\x36\x6f\xea\x0b\x5f\xd5\x65\x9d\x90\x02\xd0\x5a\x2b\x15\x32\ +\xce\xc3\x01\x51\x21\xd7\x79\xf8\x7a\x5d\x16\xfe\x1d\x60\x39\xb6\ +\x80\x87\xdf\xfe\x64\xb4\xd6\x02\xd2\xfc\xaa\xcb\xc4\x53\x75\x36\ +\xfd\x00\xad\xb5\xc2\xae\x35\x8b\xe7\xba\xbf\x1d\x9f\xf9\xbe\xa6\ +\x95\x85\xff\xbc\x8e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\xe0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x92\x49\x44\x41\x54\x78\x9c\xed\ +\x98\x4d\x68\x5c\x55\x18\x86\x9f\xf7\xde\x50\x12\x45\xa1\xda\x9d\ +\xe8\x56\x5c\xb7\x64\x22\xa9\x68\x54\x4a\x9b\x42\xd2\x49\x20\xe0\ +\x4a\xb4\xfe\x81\x6b\x7f\x41\x44\xac\x60\xba\xd0\xad\x8a\x05\x57\ +\xae\x9a\x8c\xc9\xa2\x15\x4a\x35\x9b\xca\x4c\xd2\x14\x74\xd3\x9f\ +\x9d\xc5\x65\x44\xd2\xb8\x88\x3a\x73\x5f\x17\xa1\x32\xb9\xf7\x26\ +\x99\x99\xdc\x99\x44\x7a\x9e\xe5\xf9\xee\x39\xe7\x7d\xbf\xf3\x73\ +\xcf\x39\x10\x08\x04\x02\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\ +\x10\xb8\xb7\x50\xba\x60\x70\xc6\x1f\x4a\xfe\x00\x88\x0d\x89\xc0\ +\x7b\xa0\xab\x30\x0c\x12\x44\x40\xc3\xd6\xc7\x8b\x93\xfa\xa8\x39\ +\x9e\x49\x40\x69\x36\xa9\x03\x71\xaf\x04\xf6\x98\x46\x6d\x22\xea\ +\x6b\x2e\x88\xf6\x4a\xc9\x7e\x21\x93\x00\x5b\x67\xd0\xff\x7b\xda\ +\xe7\x22\x6c\xeb\x4c\xb6\x38\x87\xd2\x8c\x47\x90\xe7\x80\x07\x52\ +\x21\x03\x49\x17\xe4\x15\x49\x44\xd6\xd7\x9a\xa4\xb1\x6a\x59\x0b\ +\xe9\x8f\x73\x13\x00\x50\xaa\xf8\x30\xf6\xf7\xc0\xa1\x54\x0d\xe3\ +\xfd\x99\x04\x43\xa4\xac\xa7\x15\xa4\xe3\xb5\xb2\x96\xf3\xea\x6c\ +\x99\x00\x80\x23\x73\x7e\x3c\x6e\xf8\x12\xf0\x68\xaa\x23\x6b\xbf\ +\xcd\x04\x11\xe1\xcd\x7e\x24\x6e\xd7\x23\x1d\xbb\x3a\xae\x9b\x5b\ +\x55\xdb\x76\x13\xbc\x3a\xae\x9b\x49\xa4\x61\xe0\xc6\xe6\xbe\x90\ +\xb5\x7f\x36\x50\xe7\x98\x07\x6e\x34\xa4\xa3\xdb\x99\x87\x1d\x66\ +\xc0\x5d\x0e\xcf\xfb\x50\x5f\xc3\x17\x31\x47\x52\x5d\x03\x6a\xb4\ +\x23\xb6\x78\x1c\xa7\x6d\x08\x96\xfe\xe9\xd3\xe8\xf2\x98\x56\x76\ +\xaa\xdd\xd2\x28\x2e\x8f\x69\xa5\x2f\xd2\xb3\xc0\x0f\x9b\x23\x02\ +\x88\x51\x4b\x79\x2c\x14\x6f\x8c\x78\x9e\xf9\xcb\x71\xac\xe7\x5a\ +\x31\x0f\x6d\x9c\x03\xae\x8c\x6b\x6d\x60\x55\x27\x05\x95\x1c\x35\ +\xb1\x5b\x9c\x4d\x45\x60\x90\xf2\x97\xe0\xec\xc1\x7e\x9d\xbc\x32\ +\xae\xb5\x56\xdb\x6a\x6b\x1d\x2f\xbc\xa4\xf5\xfe\x83\x9a\x92\x7d\ +\x2e\x1d\x93\x89\x9c\x5d\x87\x85\x63\x23\x39\xab\x5b\xf6\xb9\xc7\ +\xea\x9a\xba\x38\xaa\xbf\xda\x69\xaf\x33\xc1\xb6\x4a\x95\x64\x1a\ +\xf4\x56\x8e\xc0\x44\x5d\x3a\x48\x35\x9d\xeb\x37\x21\xfb\x6c\x75\ +\x22\x7a\x17\xa9\xed\x7e\x77\x35\x62\x83\x15\xbf\x2d\x7b\x3a\xa7\ +\xd9\x04\x5c\x68\x12\x8c\x24\x9c\x3d\xb9\x4a\xef\x2c\x96\x75\xb6\ +\xd3\x76\x77\x3d\x65\x87\x66\xfc\x8a\xe5\x2f\xc9\x8c\x4c\x71\x49\ +\xd8\xc2\x7c\x62\xe9\xb5\xc5\xb2\x32\xcb\xb1\x1d\x0a\x59\xb3\xa5\ +\x8a\x27\xb1\xbf\x05\x0e\x34\x97\x5b\xb6\xac\x5d\x1d\x98\x8c\x23\ +\x65\x7f\x33\x7f\x0b\xbd\x50\x9d\xd0\xec\x6e\xda\x86\x02\x77\xee\ +\xa1\xf3\x7e\xde\xf2\x77\x88\xfb\x9b\xcb\x8d\x2d\x3a\x4e\x42\xde\ +\xb9\xfe\xcf\x44\x3a\xb5\x54\xd6\xe5\x0e\xdb\xdc\x44\xa1\xbb\xf6\ +\x93\x15\x0f\x26\xf6\x05\xe0\xe1\x54\xa8\x93\x4b\x54\x9e\xf9\xdf\ +\x13\xeb\xc4\xd2\xa4\x96\x3a\xd5\x98\xa6\xf0\xdf\xd6\xd0\xac\x9f\ +\x30\xbe\x04\x3c\x92\x0a\x19\x91\xec\xf8\x7f\x10\xd8\xb9\x97\x9a\ +\xdf\x84\x8e\x55\x27\x74\xbd\x38\xb5\x5d\x78\x10\xa9\x4e\xe8\x7a\ +\x6c\x0d\x03\xb7\x52\x21\xb1\x61\x6c\x47\x4d\x39\xe6\x6f\xd5\xeb\ +\x1a\x2e\xda\x3c\x74\xe9\x45\xe8\xa7\x49\xfd\x1a\xa3\xa7\x80\x6b\ +\xa9\x90\x8c\xb7\x79\x6e\x73\x9c\x73\xa9\xb9\x76\xa0\xae\xa3\xcb\ +\x53\xba\x5d\xb0\xcc\x0d\x41\xdd\x68\xf4\x2e\xa5\x0b\x7e\xd0\xeb\ +\x9e\x17\x3c\x9d\xd3\x75\xe3\xbf\xf7\x56\x09\x9c\x9b\x98\x05\xfa\ +\x35\x5e\x1b\xd5\x9d\x6e\x69\xec\xea\x95\xb6\x36\xaa\x3b\xf7\xad\ +\xea\x38\x30\x9f\x8d\x3a\x66\x63\x00\xb4\x85\xf9\xb9\x81\x55\x9d\ +\xe8\xa6\x79\xe8\xd1\x05\xe6\x99\x1f\xdd\xb7\xfe\x47\xf2\xb5\xd1\ +\x8b\x2d\x55\xb0\xbf\x19\x78\x28\x7a\x75\x61\x44\xf5\x2e\x4b\xeb\ +\xcd\xa3\xc6\xc2\x88\xea\xd5\x9f\xa3\x97\x85\x3f\xdf\xe9\x5b\xe3\ +\xcf\x6a\xbf\x44\xa7\x7b\x61\x1e\x7a\x78\x85\x05\xc0\xd6\xe0\x2c\ +\xef\x49\xfe\x24\x5f\x8d\xde\xaf\x9d\xe2\xd3\x4e\x2e\x35\x9d\xd2\ +\xfb\x97\x0c\x60\x70\xc6\xaf\x4b\xfe\xa2\xa9\xc8\x48\x6f\xd4\xca\ +\xfa\xaa\xd7\x5a\xf6\x24\x01\x00\x43\x33\x8d\x69\x4b\xa7\x81\x06\ +\xd6\x9b\xb5\x49\x9d\xdf\x2b\x2d\x81\x40\x20\x10\x08\x04\x02\x81\ +\x40\x20\x10\x08\x04\x02\x81\x7b\x89\x7f\x01\x9b\xd6\x34\x0b\xef\ +\xec\xcc\xa6\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x1d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xcf\x49\x44\x41\x54\x78\x9c\xed\ +\x98\x4f\x6c\x54\x55\x18\xc5\xcf\x79\x4f\x06\x89\x85\x05\xd4\x44\ +\xaa\x25\xee\xc0\xa5\x7d\x6f\xea\xc2\xc4\x14\x0d\x0d\x74\xa1\x94\ +\x85\x0b\x56\x16\xc2\xcc\x88\xb1\xba\xc0\xb0\xc2\xb1\x31\x21\x21\ +\x90\xc8\xcc\x0b\x8a\x48\xc0\x98\x18\x17\x35\xca\xaa\x25\x8d\x50\ +\x12\xa8\x89\x69\x47\x97\x86\xc4\x95\x7f\xaa\x89\x92\x98\x00\xa9\ +\x14\xdf\xfd\x5c\x30\x95\x79\x7f\x3a\x9d\x7f\x6f\xa6\xe2\xf7\x5b\ +\xbe\x6f\xee\xbd\xe7\x9c\xb9\xf7\xce\xf7\x06\x50\x14\x45\x51\x14\ +\x45\x51\x14\x45\x51\x14\x45\x51\xfe\x5f\xb0\x53\x0b\xf7\xe7\x0a\ +\xc3\x46\x78\x0a\x80\x45\xe0\xa3\xd9\x0f\x47\x8f\x74\x42\x87\xdd\ +\x89\x45\xd3\xb9\xe2\x01\x11\x7e\x02\x60\x03\x80\x2e\x00\xcf\x6d\ +\x76\x76\xfe\xf2\x6b\xe9\xe2\xb7\xed\xd6\xd2\xf6\x00\x9c\x6c\xf1\ +\x30\x80\x02\x42\xbb\x8f\xe4\x8b\x3d\xe9\xa1\x85\xf9\xb9\xc9\x99\ +\x76\xea\x69\x63\x00\x42\x27\xdb\x7d\x9c\xc0\xdb\x55\x3e\xb4\xa3\ +\xc7\xdd\xf5\xc8\x7c\x69\xe2\x2b\x60\xac\x2d\xaa\xda\x72\x07\x0c\ +\xe4\xf3\x0f\xdd\xfa\x6d\xe3\x19\x80\x23\x35\x0d\x10\x9c\xeb\xda\ +\x7c\x23\x7b\x65\x6c\xec\xef\x84\xa5\x25\x1f\xc0\xc0\x2b\xe7\x1f\ +\xbe\xb5\xf6\xe6\x67\x00\x76\x87\x6b\x02\x31\x00\x41\xc0\x8a\xd6\ +\xf8\xe5\xfa\x3b\x5d\x7b\xaf\x7c\x3c\xf2\x57\x92\xfa\x12\x0d\xe0\ +\x99\xd7\x8b\x1b\xfc\x45\x5c\x00\xb0\x3d\x66\x65\x1f\x72\x5f\x85\ +\x08\xec\xb0\x18\x02\x97\x53\x77\x17\x76\xcf\x9c\x3b\x7c\x33\x29\ +\x8d\x89\x05\xf0\xf4\x48\xf1\x51\x7b\x0d\x26\x41\x38\xc1\x8a\x00\ +\xa0\x1f\xab\x44\xc4\x8e\x91\x34\xe7\x2f\x62\xe8\xbb\xf3\xa3\xbf\ +\x27\xa1\x33\x91\x00\x9c\xcc\xc9\x2d\xa4\x35\x05\x60\x6b\xa8\x24\ +\x00\x4c\x75\x39\x62\xc5\xe8\xba\x4e\xdb\xde\x31\xfb\xfe\x6b\x3f\ +\xb5\x52\x27\x10\x73\xf6\x9a\xa5\xef\xe0\x7b\x4f\x91\xd6\x0c\xea\ +\x36\xbf\xf4\x11\x18\x80\x12\x2a\x6c\x15\xdf\x9f\x71\x32\xde\xb6\ +\x56\xe9\x5c\xa2\xa5\x01\xa4\x0f\x9c\x4c\x5b\xbe\x7d\x15\xc0\x13\ +\xc1\x0a\x6b\x30\x5f\x89\x18\x08\xc2\x21\xf4\x92\x72\xad\x3f\xeb\ +\xb9\x4d\xca\x0c\xd0\xb2\x00\xd2\xd9\xc2\x0b\x62\x59\x97\x01\x6c\ +\xaa\x7c\x2e\x02\x01\xa4\x0e\xf3\x65\x18\xbb\x13\x36\x19\xc8\x74\ +\x5f\xce\x7b\xbe\x09\xa9\x01\x5a\x12\x40\x3a\x5b\xdc\x23\xe0\x04\ +\xee\xb5\xb5\x95\x08\x59\xcf\x37\x1f\x26\x76\x27\x74\x59\x22\x93\ +\xfd\xb9\xc2\x70\xe3\xf3\xde\xa7\xe9\x00\xdc\xac\xb7\x5f\x80\x71\ +\x00\xa9\x40\xe1\x9e\xf1\x26\xcc\x57\x9d\x27\x65\x84\x9f\xbb\xb9\ +\xe2\xbe\x66\xa7\x6f\xaa\x15\x76\x33\xc5\xb7\x40\x78\x88\xdc\xda\ +\x12\xb7\x7d\x9b\x42\x08\x30\xb8\x0e\x01\xbc\xf4\xb8\xbb\xf3\xf6\ +\x7c\xe9\xe2\xd7\x8d\xce\xdb\x60\x00\x42\x37\xb3\xf1\x18\xc8\x77\ +\x22\x15\xc0\xb0\xc5\xe6\x81\xb2\x73\x0a\x00\x86\xc2\xe6\x60\x8f\ +\xbb\x6b\xdd\x7c\x69\xe2\x52\x23\xef\x0f\x75\xf7\x01\xe5\xbe\xfe\ +\x34\xc0\xfd\xe1\x9a\x40\x12\x31\x1f\x58\x83\x20\x25\x7a\x74\x49\ +\x9c\x7d\xf2\xc6\x63\xb9\xf1\xf1\x97\xa3\x4d\x56\x15\xea\x0a\xa0\ +\xdc\xd7\x7f\x0a\x60\x4f\x54\x98\x18\x4a\xb2\xe6\x2b\xd6\x22\x85\ +\x71\xf7\xd7\x17\x7f\xa6\xb0\xf7\x07\x6f\xf4\x4e\xad\x73\xd5\x1c\ +\xc0\xb3\xfb\x8e\xad\x5f\x5c\xb3\xee\x82\x00\xc1\x9f\x20\x01\x84\ +\x30\x44\xe4\xb6\x4e\x14\x81\x90\x88\x0d\xe1\xd2\xda\xbb\x0b\xc3\ +\xb5\xbe\x3f\xd4\x14\x80\x93\x39\xd1\x4d\xa6\x26\x01\x04\x9b\x10\ +\x11\x90\xf4\xdb\xea\x3c\x8c\x88\x1d\xbd\x16\x30\x2b\x66\x71\xa8\ +\x74\xe6\xd0\x1f\x2b\x0d\x5f\x31\x80\xf4\xc1\x53\xbd\xe2\xfb\x53\ +\x00\x42\x6d\x28\x1b\x6b\x70\x12\x40\x40\x8b\x90\xa0\x17\xe1\xf7\ +\xb6\x91\xc1\x6f\xce\x8e\xfe\x5c\x6d\x6c\xd5\x00\x9c\x8c\xb7\x8d\ +\x94\x29\x00\xbd\xa1\x15\x05\xa4\x69\xf3\xae\x5f\x01\x5a\x08\x87\ +\x00\xfc\x08\xcb\x0c\xce\x7d\xf0\xe6\xf5\xe5\x46\x2d\xdb\x08\xf5\ +\x67\x3d\x97\x94\xab\x88\x35\x8f\x55\x66\x1e\x28\xef\xc6\xb0\xa8\ +\x2d\x30\xd6\xb5\xbe\x57\x0b\x4e\xdc\x08\x60\x99\x00\x9c\x4c\x61\ +\xbb\x81\x4c\x03\xe8\x0e\x2c\x81\x25\xf3\xab\x16\x23\xd1\x10\xba\ +\x2d\xc3\x69\x37\xe7\x0d\xc4\x0d\x88\x1c\x81\x74\xae\x70\x44\xc4\ +\x1a\x8b\xd9\x4e\xff\x71\x28\xa4\xc9\xcf\x9e\x7e\xe3\xdd\xca\xa7\ +\xd1\xff\xe2\x0c\xf3\x0f\x9e\x79\xa0\xdc\xa9\xe4\xc3\x4f\xa3\x47\ +\xe0\x01\xb4\xfe\x2f\x31\xde\xa2\x3b\x80\x3c\x2a\xad\x78\x8b\x5b\ +\x65\x08\x60\x84\x3c\xda\x69\x1d\x8a\xa2\x28\x8a\xa2\x28\x8a\xa2\ +\x28\x8a\xa2\x28\x4a\xa7\xf9\x07\xee\x73\x3f\xf5\xa2\x1e\x57\x1f\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xc0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x72\x49\x44\x41\x54\x58\x85\xe5\ +\x97\xcf\x4e\x13\x61\x14\xc5\x7f\xf7\x6b\xbb\x22\x31\x51\xc0\x08\ +\xbb\xbe\x82\xd0\x8a\xd1\x18\x4c\x5c\x09\x71\xc5\x1b\xd0\xd0\x26\ +\x40\x49\x8c\xc2\xb2\x69\x58\x95\x44\x23\x2d\x90\x42\xc0\xc4\xb0\ +\xc1\xbd\x4d\xd8\x28\x89\x89\x8a\x40\x7d\x05\x58\x29\x11\x31\x71\ +\xc1\xaa\x76\xae\x8b\xce\xd4\xb1\xd0\x3f\x53\x06\x17\x7a\x96\xe7\ +\xde\x99\x73\xe6\xdc\x6f\x32\x77\xe0\x7f\x87\xd4\x12\xfd\x89\xdc\ +\x2d\x54\x67\x10\x06\x50\xba\x7d\x52\x39\x42\xd9\x46\x24\xb3\x97\ +\x9f\x7c\x57\xd7\x40\x24\x3e\xff\x48\x91\xb9\xb3\x8c\xf9\x04\x4b\ +\x95\xe9\xe2\x4a\xf2\xc9\x29\x03\x7d\x63\xcf\x6e\x8b\x98\xb7\xc0\ +\x0f\x44\x93\xa1\x52\xb9\xf0\x61\xed\xe1\x77\x3f\x54\x6f\x8e\x3e\ +\xbd\x52\x0a\x05\x86\x50\xc9\x02\x97\x10\xb9\xe3\x24\x11\xac\x3a\ +\x11\x33\x0d\x08\xa2\xc9\xbd\xfc\xd4\xba\x1f\xc2\x0e\xec\x07\x59\ +\xef\x8f\x67\x05\x78\x81\xea\x0c\xf0\x00\xc0\x54\xbb\x84\x01\x80\ +\x50\xa9\x5c\xf0\x53\xdc\x0d\x13\x34\x85\x8a\x14\x37\xaa\x5c\xb5\ +\x6a\x1f\x38\xbf\x62\x3f\x0b\x3b\x8b\x13\xc7\x15\x29\xae\x3a\x5c\ +\xb0\x7e\x7b\x7b\xb8\x9e\x58\x18\x36\x6a\xad\x00\x58\x62\xc6\x3e\ +\xe5\x27\x5e\x35\xea\xf7\xd5\x40\x34\x96\x0b\x5b\x6a\x6d\x00\x1d\ +\x00\xb6\x91\xde\x46\xd7\x98\x46\x45\x4f\x48\xa5\x8c\x15\xd0\xe7\ +\x8e\x78\xab\xf0\xcd\x40\xe4\xb0\x2b\x01\x0c\xba\x39\x55\x66\xff\ +\x8a\x81\x68\x2c\x17\x56\x74\xae\x86\xde\x2a\xf6\x1c\x2f\x5f\xbc\ +\x81\xb3\xa3\x3f\x31\x65\x19\x25\x9d\xb6\x9a\x5d\xde\xf4\x10\x36\ +\x3b\xd5\x91\xc3\xae\x84\xa2\x83\x6e\x4e\x95\xc7\x3b\xab\x93\xfb\ +\xad\xf8\x6f\x9a\x80\x2d\xde\x03\xf4\x18\xb5\x36\xa2\xb1\x5c\xd8\ +\xa9\x9d\x27\x7a\x07\x5e\x5f\xc3\x0e\x2b\xa0\x6b\xa4\x52\xf7\x00\ +\xac\xc3\xf6\xa3\x6f\xd9\x80\x2a\xb3\x22\x2c\xb9\xa8\xbb\x7d\x5f\ +\x3a\xe3\x46\x44\xce\x13\xbd\x83\xa6\x23\xb0\xe3\xdc\x72\x73\x22\ +\x2c\x29\xba\x58\xd3\xea\x29\xfa\x96\x0d\x90\x4e\x5b\xa6\x2c\xa3\ +\xc0\x49\x83\x2e\xcf\xd1\xb7\x6e\x00\xd8\x59\x9d\xdc\x17\x64\xba\ +\x5e\xbd\x9d\xe8\x3d\x19\x00\xd8\xbd\xf6\x2d\x4f\xcd\x28\x6c\xb4\ +\x15\xbd\x67\x03\x75\x46\xd1\x76\xf4\xde\x0d\xe0\x8c\x42\x47\x14\ +\x0e\x14\x0e\x04\x1d\x69\x37\x7a\x07\x9e\x3f\xc7\xbb\xcb\x53\x9b\ +\x40\xb8\x69\x63\x8b\x70\xaf\x64\x47\x50\x59\x20\xfd\xba\x79\x2d\ +\xa2\xe3\x0b\x9d\x15\x29\xbe\x9e\x36\xa0\x6c\x03\x94\x42\x81\xa1\ +\x8b\x32\x60\xfd\xb4\x86\x2a\x52\x7c\x74\xb8\xdf\x23\x10\xc9\xa0\ +\x3a\x8c\x4a\xb6\x3f\x9e\x15\x13\x34\x05\x67\x87\x3b\x2f\xa2\xe3\ +\x0b\x9d\xb6\xf8\x3c\x60\x21\x92\xa9\xca\xba\x1b\xed\x1f\x93\x0c\ +\x7e\x6e\x4a\x7f\xe2\xd4\x8f\x49\xc0\x5d\xfd\x5c\xdc\x7c\xdf\x1b\ +\xb9\xff\x1a\xe8\x16\xb8\x8c\xc7\xf5\xaa\x1e\xec\x99\xbf\x41\x24\ +\x56\x5c\x4e\xbe\xf4\xe3\x9e\xff\x0e\x7e\x01\x29\x72\x01\x2f\x4e\ +\xc0\xa2\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xc0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x72\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x09\x83\x60\x14\x04\xe0\xd3\x21\xc4\x26\xe0\x4c\x59\xc1\ +\xca\x89\xdc\x24\xf3\x08\x69\xc4\x21\x34\xad\xf8\xd7\x2a\xc4\xef\ +\x2b\x8f\x57\xdc\xbb\x04\x00\x00\x00\x00\x00\x00\x78\x82\xea\x18\ +\x4c\xd3\xf7\x9d\x2a\x63\x92\xe6\x86\x3e\x67\x9a\xb3\xa5\xef\xba\ +\xd7\x67\x1f\xd6\xc5\xd9\x7f\x3e\x9f\x24\x6d\xea\x8c\xc7\xb0\x1c\ +\xe0\x61\xca\x01\xb6\x0c\x49\x96\xeb\xab\x9c\x6e\xce\x9a\xe1\xee\ +\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xf5\x7e\x5a\x95\x0d\x08\xf2\ +\x12\x5b\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xa7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x59\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\xb8\x85\xa4\x34\xb8\x85\xa4\x34\x50\x62\x06\x13\x25\ +\x9a\xa9\x01\x46\x1d\x30\xea\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\ +\x0e\x18\x70\x07\xb0\x50\x6a\xc0\x7f\x06\x06\x07\x4a\xaa\xe4\xa1\ +\x1f\x02\x8c\x0c\x0c\x07\x76\xad\x99\xd3\x40\xae\xfe\x01\x0f\x81\ +\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x06\xdc\ +\x01\x00\x05\x9e\x09\x3f\xb6\x6d\xc4\xbd\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\x80\x30\x00\xc4\x40\xc2\x1e\x11\xec\x3f\x15\x88\x41\ +\x42\xcb\x06\x47\x61\x77\x5f\xbd\xe5\xb1\x21\xae\xfb\x59\xdf\x7d\ +\x1e\x73\x08\x8f\x5d\x9c\xfe\x89\x02\x68\x01\x4d\x01\xb4\x80\xa6\ +\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\ +\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ +\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ +\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ +\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ +\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ +\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ +\x2f\x70\x51\x04\x80\x66\x61\x99\xa8\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x03\xf4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa6\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x4f\x68\x1c\x55\x18\xc0\x7f\xdf\x9b\xec\x26\x5a\x93\x88\x96\ +\x98\x9a\xdd\xc9\xee\xc6\x80\x86\x3d\x78\x90\x42\x0f\xf5\x4f\x29\ +\x2d\x22\x6d\xaa\xa0\x22\x52\x0b\x55\xf1\xd0\x9b\x20\xa4\x78\xe8\ +\x41\xd1\x80\x27\xa5\x28\x88\x20\x88\x5e\x0d\x36\x6a\xb5\x60\x69\ +\x4f\x52\x1a\x28\xc2\x2a\x91\x6d\xb2\x7f\x66\xb6\xab\x78\x90\xd8\ +\x58\x35\x99\x79\x9f\x87\x9d\x5d\x93\x6c\xd2\x64\xd9\x8d\x97\x7e\ +\x97\xf9\xf8\xe6\x9b\xf7\xfb\xbd\x61\xde\xcc\x1b\xb8\xd5\x43\x5a\ +\x69\xbe\x5a\xa9\x24\x63\x81\x3d\x62\x91\xfd\x82\x26\x51\x12\x08\ +\x06\xa5\x82\xe0\x0b\x5c\x34\x86\xa9\x64\x32\x99\xef\xa8\xc0\xbc\ +\xe7\xed\x36\x96\x49\xe0\xb1\xad\xf4\x2b\x5c\x36\xc8\xc9\xe1\xe1\ +\xc4\x77\x6d\x09\xcc\xcd\xcd\xf5\x3b\x4e\xfc\x03\x84\xe7\xa2\x52\ +\x55\x61\x1a\xd1\xb3\x2a\x32\x1f\x76\x75\x55\x6f\x0b\x43\x1b\x86\ +\xe1\xa0\xaa\x93\x52\xd1\x03\x02\xe3\xc0\x70\xd4\xff\xb5\x0d\x97\ +\x8f\x67\x32\x99\x5f\x5b\x16\xf0\x3c\xef\xbe\xd0\xea\x19\x90\x07\ +\x80\xaa\xc0\x29\xd7\x4d\x7c\x2c\x22\xc1\xcd\xa4\x55\xd5\x14\x3d\ +\xef\x59\x51\x79\x13\xc8\x20\x94\x6d\x20\x87\x33\x99\xc4\x0f\x5b\ +\x16\x28\x95\x4a\x19\xc5\x5c\x02\x76\x0a\x7c\xb1\xb4\xf4\xf7\x0b\ +\xa3\xa3\xa3\x7f\xdc\x0c\xbc\x36\xf2\xf9\x7c\x77\xac\xbb\xe7\x7d\ +\x94\xe3\xc0\x9f\xa8\xd9\x9b\x4a\x0d\x5d\xd9\x54\x20\x9f\xcf\xf7\ +\xc5\xe2\x3d\xdf\x03\x63\x0a\xef\xa6\xdc\xc4\xab\x22\x62\x5b\x81\ +\xd7\x43\x55\xa5\x58\xae\x4c\x08\xfa\x16\xe0\xa3\xe1\xee\x54\x2a\ +\x55\x5d\xd9\x63\xd6\x5e\x14\x8b\xf7\x9c\xae\xc1\x75\xba\x1d\x38\ +\x80\x88\x68\xca\x1d\x9a\x04\x3e\x02\x12\x88\xf3\xa9\xaa\xae\x9a\ +\xf4\x2a\x81\x72\xb9\xfc\x10\x70\x14\xe5\x37\x1b\x2c\x1f\x6d\x07\ +\xbe\x52\x62\xf1\xfa\xc2\x09\x60\x16\xd8\x57\x2a\xf9\x8f\x6f\x28\ +\x60\x95\xb7\x6b\x17\xf1\xc6\xc8\xc8\xc8\x42\xbb\xf0\x7a\x64\xb3\ +\xd9\x25\x94\xd7\x01\x54\x98\x5c\x79\x17\x1a\x49\xb1\x58\xdc\x85\ +\x38\x15\xe0\xf7\xc5\xeb\x0b\xbb\xb2\xd9\xec\x52\xa7\x04\xa0\xf6\ +\x3c\x94\xca\xfe\x4f\xc0\xfd\x36\x94\x07\xeb\xab\xa2\x71\x07\x44\ +\x9c\x43\x91\xd0\x57\x9d\x86\xd7\xc6\x17\x55\x38\x03\x20\x8e\x3e\ +\x59\xaf\x37\x04\x54\x79\xb4\x96\xf0\x4d\xa7\xe1\x0d\x09\x95\x6f\ +\xa3\x74\x5f\x93\x00\x22\xc9\x28\x29\x6c\x97\x80\xea\xf2\x3c\x80\ +\x40\xa2\x59\x20\x2a\xaa\x2e\x57\xd9\xa6\x08\x82\xa0\x3e\xf6\x50\ +\xfd\x41\x6c\x7a\x0f\xfc\x8f\xb1\x56\xc0\x56\x6a\xc7\xd8\xe0\x76\ +\x11\x1d\x67\x47\x34\xb6\x5c\xab\xbf\x63\xfe\x13\x50\xe3\xd5\xba\ +\x6c\x7a\xbb\x04\x8c\xb1\x99\x28\xf5\x1b\xb5\x06\x5f\xb8\x00\x60\ +\x94\x83\xdb\x25\x20\xa2\x07\x00\x14\x3d\xdf\x24\xe0\x88\x9d\xae\ +\x9d\x94\x27\x66\x66\x66\x62\x9d\x86\xab\xaa\x28\x1c\x06\xc0\xca\ +\x54\x93\x80\xeb\xba\xd7\x80\xf3\xc0\xce\xbb\x07\x06\x5e\xea\xb4\ +\x80\xe7\x79\x87\x80\x31\xe0\xc7\x54\x6a\xa8\xb1\x37\x58\xb5\x0a\ +\x8c\xe8\x04\x80\xa8\x39\x95\xcf\xe7\xfb\x3a\x05\xcf\xe5\x72\x71\ +\xab\x52\xfb\xce\x60\x4e\x8a\x88\xae\x2b\xe0\xba\xee\x65\xe0\x33\ +\xd0\x7b\xe2\xf1\x9e\x4f\x54\xb5\xed\x65\xaa\xaa\xd2\xdb\xdb\xf7\ +\x1e\x30\x86\x70\xc1\x75\xef\xfd\x72\xe5\xf9\x26\x40\x18\x2c\x9d\ +\x00\x66\x15\xc6\x4b\xa5\xca\x3b\xed\x48\xa8\xaa\x94\xcb\xfe\x6b\ +\x8a\xbc\x02\x5c\x33\xe8\xf3\x2b\x67\x0f\x1b\x6c\xc9\x6a\xfb\x41\ +\x2e\x01\x77\x21\x7c\x7e\x7b\x4f\xf7\xb1\x81\x81\x81\xc5\x56\xe0\ +\xb9\x5c\x2e\x7e\x47\x6f\xff\x69\xe0\x65\xe0\x86\x11\x7d\xc4\x75\ +\xdd\x99\xb5\x7d\xeb\xce\x2e\x99\x4c\x5e\x0d\x1d\xd9\x03\xfc\x8c\ +\xf2\xd4\x8d\xbf\xfe\x99\x2d\x16\xbd\x17\x55\xb5\x6b\x33\xb0\xaa\ +\x9a\x52\xc9\x7f\x66\x47\x6f\x7f\x2e\x82\xfb\xa8\xb3\x77\x3d\x38\ +\x6c\xb2\x2d\x2f\x14\x0a\x77\x62\x9c\x0f\x05\x79\x3a\x2a\xf9\xa8\ +\x4c\x8b\xc8\x59\x08\xe6\x8d\x31\xd5\x20\x08\x2c\xc4\x07\x71\xc2\ +\x61\xb1\x1c\x44\x64\x1c\xc8\x44\x83\x9f\xb3\x36\x38\x96\x4e\xa7\ +\x7f\xd9\x88\xb1\xa5\x1f\x93\x62\xd1\xdf\x23\xa2\x93\x0a\x0f\x6f\ +\xa5\x1f\xb8\x62\x45\x27\x32\xae\x7b\x6e\xb3\xc6\x96\x7e\xcd\x0a\ +\x85\x42\x0a\x13\x3b\x22\xe8\x7e\x94\x24\x42\x02\x70\x00\x5f\xc0\ +\xb7\xc8\x45\xac\x4c\xa5\xd3\x43\xb3\xad\x8c\x7b\x6b\xc7\xbf\xc1\ +\x7f\x6c\x10\x0e\xdc\xa9\xdc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x02\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x3c\x49\x44\x41\x54\x58\x85\xed\ +\x97\x3d\x6b\x14\x51\x14\x86\x9f\x73\xc7\x2e\x60\x61\x30\xa0\x66\ +\xdc\xd9\x5f\x61\x40\x91\x58\x6f\xca\xb4\xda\x04\xd4\xca\xca\xc4\ +\x1f\x90\x6a\x03\x16\x06\x0c\x2a\x68\x9d\x3a\xb8\x60\x17\x10\x84\ +\xe4\x57\xec\xbd\x99\xb1\x49\x50\xb0\x48\xb9\xf3\x5a\xec\x4e\x4c\ +\x26\xfb\xbd\x13\x1b\x7d\xab\xcb\x39\x77\xe6\x3c\xf3\x9e\x0b\x73\ +\x0f\xfc\xeb\xb2\x72\x20\x84\xef\xf7\x73\x3a\xaf\x4c\xb6\x84\x71\ +\xb3\x92\x2a\xe2\x44\xa6\x03\x47\xd4\xac\xd5\xee\x7c\x1b\x08\xe0\ +\xfd\xd1\x4b\xcc\xb6\xfa\x81\x55\xa4\x1c\x69\x23\x49\xee\xbe\xbe\ +\x04\x10\x42\x78\x20\xdc\x57\xe0\x97\x61\x2f\x9c\x53\x2b\x8e\xe3\ +\x9f\x55\x54\x4d\xd3\xf4\x46\x9e\x5b\x43\x68\x1b\xb8\x6e\xb8\x87\ +\x65\x27\x68\x87\xa3\x3d\x1f\x52\x85\x90\x3d\xae\xa2\x68\x3f\x85\ +\x90\x3d\xf1\x21\x55\x3b\x1c\xed\x15\x31\x57\x2c\x4c\xb6\x04\xe0\ +\x9c\x5a\x57\x05\x10\x45\xb4\x00\x0c\xbb\x77\x09\xa0\x38\x70\x55\ +\xd9\xde\x4f\x8b\x8b\x8b\x3f\x7a\xcb\x85\x22\x76\xad\xea\x22\x21\ +\x64\x2b\x42\x1f\x00\x0c\x7b\x5a\xab\x2d\x7e\x1e\xb6\xbf\x52\x00\ +\xef\x7d\x5d\x68\x17\x98\x03\xe8\x81\xdc\x1e\xf6\x8c\x1b\x96\x9c\ +\x44\x92\x1c\x2e\xfa\x54\x14\x1f\x57\x95\x01\x84\x34\x7d\x8e\x58\ +\xbe\x00\x65\xda\xfc\x2b\x00\xde\xfb\x3a\xb2\xad\x52\x78\x3f\x89\ +\xe3\xf7\x57\x0e\x30\xc0\xfa\x53\xd4\x59\x33\xb3\x7c\xd4\xf3\x23\ +\x0f\xe1\xa8\x53\xdd\xb5\xde\x96\x2f\x40\x99\xd6\xeb\xb5\xa4\x3d\ +\xce\x07\x8c\x74\xa0\x57\xfc\x16\x70\x4b\x68\xd7\x7b\x5f\x2f\x72\ +\xb3\x58\x3f\x36\x40\x49\x73\x58\xf4\x51\x92\x9b\xd5\xfa\x42\x23\ +\x5b\x20\xd3\xa6\xc9\x76\xce\x85\x1e\xf9\x34\x7d\x66\x60\xb3\x58\ +\x5f\x68\xa4\x03\x3d\x3b\xf7\xcf\xc7\x4c\xb6\x83\xec\x6d\x69\xeb\ +\x44\xd6\x8f\x0d\x60\x66\x39\xea\xac\x01\xa7\x43\xb6\x4d\x6c\xfd\ +\xd8\x00\x00\x49\x92\xb4\x31\x6d\x0c\xca\xcb\xb4\x9e\x24\x93\x59\ +\x3f\x11\x00\x40\x2d\x8e\xdf\x51\x6a\x45\x4f\x53\x59\x3f\x31\xc0\ +\x80\x56\x4c\x6d\xfd\xc4\x00\xd0\x6d\x85\x1c\xab\x60\x1e\xcc\xcb\ +\xb1\x3a\xad\xf5\x85\x26\xfe\x1d\xd7\xe3\xf8\x0b\x50\x1f\xb9\x71\ +\x4c\xfd\x71\x40\x9c\x40\xf7\x02\x59\xd5\xcb\xcb\xca\xb2\x6c\xbe\ +\xb7\x3c\xbe\x04\x20\xd3\x01\x40\x9e\x5b\xe3\xaa\x00\x3a\x1d\x1a\ +\x00\x42\x87\x45\xec\xac\x05\x8e\xa8\x29\xf2\x15\xa1\xed\x10\x32\ +\x8b\x22\x5a\xe7\xee\x70\x33\x29\xcb\xb2\xf9\x4e\x87\x86\xd0\x1b\ +\x20\x77\x44\xcd\x22\xd7\x6f\x30\x69\x52\xe1\x45\xa5\xa4\xc1\x83\ +\x49\xa1\xb3\xd1\xac\x7b\x75\x5e\x28\xe7\xa7\xd4\xb1\xd0\x61\xbf\ +\xd1\xec\xbf\x7e\x03\x1f\xb0\x01\x10\x54\x88\x8f\x55\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\xfe\x21\x15\x83\xf8\x29\xe4\ +\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\xc6\xda\ +\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\x00\x00\ +\x00\x00\xbc\xd7\x42\xd4\x03\xab\xc4\x79\xcd\x85\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x20\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x15\x82\x50\x10\x44\xd1\x5d\x8b\xa0\x16\xeb\xa0\x05\x22\ +\x2b\xb2\x0b\xea\xb0\x0e\x22\xab\x00\x03\x34\xd3\x94\xeb\x39\xcc\ +\x8d\x7e\xf6\x67\x5f\x55\x44\x9c\x59\xab\x8f\xaf\xf3\x36\x6e\xb5\ +\xdd\xf7\x11\x7d\x7b\x8c\x3d\x8b\x1d\x17\xf1\x69\x55\xd5\xfb\xf8\ +\xa1\xaa\x86\x4f\x08\x81\x05\xa8\xfd\xf8\x6f\xef\x43\xc9\x00\x7f\ +\x21\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\x2d\x01\xf4\x00\ +\x2d\x01\xf4\x00\x4d\x06\x78\xfe\x78\x1f\xca\x05\x58\x7b\xea\xae\ +\xa5\xbb\x96\x5a\x7b\x62\x3b\x22\xe2\xd4\x5e\x68\x08\x13\x4e\x3b\ +\x46\xe4\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x01\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb3\x49\x44\x41\x54\x78\x9c\xed\ +\x99\x4f\x68\x5c\x45\x1c\xc7\xbf\xdf\xd9\x4d\x08\x88\x27\x5b\xb1\ +\xbc\xbc\x9d\x8d\x8d\xb2\x67\x15\x4f\xed\x21\xfe\xa3\x5a\x28\x82\ +\x17\x3d\x09\xc6\x58\xc1\xa3\xa2\xa0\x88\x94\x7a\x69\x05\xbd\x56\ +\xb1\xe0\x49\x10\xa4\xda\x8b\x95\x42\xa5\x5e\x2d\xf5\x2c\x12\x92\ +\x7d\x79\x59\x11\x8d\xa7\x08\x4d\x36\xfb\xe6\xeb\x61\x37\x74\xf7\ +\xbd\xb7\x64\x93\x7d\xbb\x1b\xe9\x7c\x4e\xcb\xfc\x66\xe6\xf7\xfd\ +\xce\x9b\x79\x6f\x66\x16\xf0\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ +\x1e\x8f\xc7\xe3\xf1\xdc\x5b\x30\x5d\x10\x45\x8d\x8f\x44\x7d\x28\ +\xe7\x4a\x24\x1d\x00\x4d\x40\x57\x91\x50\x92\xa1\x31\x09\xc5\xf3\ +\xd6\x06\xe7\x7a\x82\xe9\xda\xf5\x28\x6e\x01\x28\x8d\x4d\xde\x78\ +\x49\xaa\x36\x2c\x77\x17\x98\x49\x29\x39\x2c\x64\x06\x80\xc0\xc7\ +\xf8\xff\x4f\xfb\x3c\xd4\xf1\xd6\x43\x66\x09\x00\x40\xbd\xbe\xbe\ +\x00\xea\x2a\x80\xfb\x53\x7d\x88\xa4\xd3\x21\x1e\x1e\x01\x86\x59\ +\x5f\x9b\x72\x38\x33\x37\x17\xde\x4c\xd7\xcf\x1d\x00\x00\x88\xa2\ +\xe8\x71\xc1\xfc\x08\xe0\x48\xaa\x89\x00\xb9\x02\xb4\x8e\x02\x83\ +\xac\xa7\x0d\xc2\x9d\xb2\xd6\xde\xee\xd7\x20\x17\x6b\xed\x6d\x97\ +\x98\x13\x04\xe2\xde\x88\xc8\x43\xf8\xee\x60\x9e\x79\x62\xcd\x25\ +\xe6\x44\x3f\xf3\xc8\x34\xc8\x61\xb9\xd1\x08\xcb\x2d\x77\x1d\x40\ +\x2d\xd5\x52\x10\xdd\xe4\x5f\x17\x04\x28\x03\x65\xbc\xfc\xd6\x2a\ +\x9b\xe7\xe6\x83\x20\xce\x6d\x76\xb7\xf5\xde\x34\x1a\x8d\x23\x3b\ +\x2d\x77\x0d\xc0\x13\xdd\xe5\x12\x40\x32\x99\xe4\x20\x48\x28\x31\ +\xe5\x42\xc0\xad\xe9\xb2\x79\x21\x08\x82\x8d\xbd\xda\x0f\x34\x95\ +\x83\x20\xd8\xd8\xba\x33\xf3\x14\x80\x9f\xba\xcb\x49\x40\x50\x69\ +\xa0\x51\x2c\x1c\x51\xc8\x9a\x07\x70\x63\xfb\xce\xcc\xd3\x83\x98\ +\x07\xf6\xb1\x96\x6b\xb5\xa3\x9b\x72\xad\xd3\x20\xbe\xeb\x2e\x27\ +\x00\x01\x25\x0d\x38\x9b\x8a\xa0\x9d\x8b\x26\x93\x90\xb8\xb2\xd3\ +\xdc\x3a\x5d\xab\x1d\xdd\x1c\xb4\xaf\x7d\x8b\x96\x54\x8e\xe2\xf5\ +\x4b\x10\x16\x73\xa2\xae\xfd\x95\x18\x25\x22\xc0\xec\x83\x23\x2e\ +\xdb\x70\xf6\x6c\x7b\x49\x0e\xce\xbe\xdf\xe6\x24\x5b\x36\x9c\x5d\ +\x02\xf0\x49\x4e\x34\xef\x33\x54\x24\xb9\xe6\x05\x5c\xb4\xe1\xec\ +\xd2\x7e\xcd\x77\x3a\x3c\x38\x51\x14\xbf\x2b\xe0\x42\x4e\xa8\xf0\ +\x43\x14\xdb\x53\x2b\x6f\xe7\xfa\x9e\xb5\xe1\xc5\x21\xfa\x1d\x8e\ +\x7a\x3d\x7e\x1d\xc4\xe7\x48\x8b\x23\x1d\x54\xd0\x9e\x91\x24\xa4\ +\xb4\x79\x07\xe1\x8d\x6a\x35\xbc\x3c\x54\xd7\xc3\x34\xde\xa5\x5e\ +\x8f\x5f\x02\xf1\x35\x80\xe9\x54\x48\x68\xcf\x86\x83\x23\x18\x30\ +\xa3\xb3\x09\xe1\x95\x6a\x35\xbc\x32\x54\xdf\x28\x70\xbd\x46\x51\ +\xe3\x19\xc1\x7d\x0f\xe0\xbe\x54\x48\x24\xf6\x7d\x7e\x20\x01\x49\ +\xa6\xfd\xab\x87\x7f\x09\xbe\x68\xed\xec\x8d\x21\xe4\xde\xcd\x53\ +\x44\x27\xbb\xac\xc4\xf1\x93\xc6\xe1\x07\x00\x0f\xa4\x42\x07\x99\ +\x09\x79\x2f\xd4\x7f\x0c\xf5\x7c\xa5\x52\xb9\x75\x50\x8d\x79\x49\ +\x0a\xe3\xe1\x30\xfc\x05\x4a\x4e\x02\x68\xa4\x42\x04\x07\xcf\x95\ +\xbb\xaf\x07\xd6\xa1\xe4\x64\x91\xe6\x91\x93\xa4\x10\x56\x56\xfe\ +\xb0\xc6\x24\xd7\x41\x3c\x9a\x4a\x27\x10\x0e\x7d\xd7\x43\x9f\x7d\ +\xbd\xf0\x7b\x92\x98\x67\x8f\x1f\x0f\xd6\x8a\xd6\x3a\xb2\x6f\xf6\ +\xf2\xf2\x9f\x0f\x96\xa7\x9a\xd7\x00\x3e\xd6\x13\x90\x00\x9a\x9c\ +\xf3\x03\x01\xb9\x52\x76\xc9\xeb\xd7\x9d\xe9\xa9\x53\x8f\x1c\x3b\ +\xf6\xf7\x28\x74\x8e\xec\x58\x3b\x3f\xff\xd0\x5f\x3b\xcd\xed\x05\ +\x08\x3f\xf7\x04\x48\x48\xea\xb9\x73\x6c\x6f\xa7\x95\x35\x4f\xdc\ +\xdc\x69\x6e\x2f\x8c\xca\xfc\x6e\xee\x91\xb2\xba\xba\x3a\x03\x33\ +\xf5\x0d\xa1\x33\xdd\xe5\x9d\xe7\xef\x3a\x22\xf2\x36\x38\x57\x9d\ +\x6b\xbd\x3c\x37\x37\xb7\x35\x4a\x7d\x63\x39\xc0\x48\x2a\xaf\xad\ +\xc5\x5f\x0a\x7c\x75\x90\xfa\x04\xbf\xaa\x54\x82\x25\x92\xad\x51\ +\x6b\x1b\xcb\xcd\x0e\xc9\x56\xa5\x12\xbe\x06\xe9\xb3\x3d\x2b\x8b\ +\x9f\x56\x2a\xc1\xe2\x38\xcc\x03\x63\xbc\xda\x22\xe9\xac\x0d\xdf\ +\x06\xf9\x41\xbf\x3a\x02\xdf\xb7\x36\x78\xa7\xf3\x87\xcc\x78\x74\ +\x8d\x2b\x51\x37\xab\xd1\xfa\x59\x42\x97\xba\x8a\x44\xe0\x4d\x6b\ +\xc3\x2f\xc6\xad\x65\x32\x97\x39\x00\x56\xa3\xf8\x02\x81\x45\x00\ +\x09\xc1\xb7\xac\x9d\xfd\x76\x52\x5a\x3c\x1e\x8f\xc7\xe3\xf1\x78\ +\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\xf7\x12\xff\x01\x83\xc1\x2a\x8b\ +\xb6\x49\x04\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x5e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ +\x99\xd1\x4b\x53\x51\x1c\xc7\xbf\xe7\x6c\x3a\x37\xca\xa2\x88\x1e\ +\xaa\x87\x46\x11\x24\x3d\x54\x90\x91\x09\xd1\x9c\x31\x91\x32\x2f\ +\x23\x7a\x4a\xe9\x6a\x10\x48\x7f\x40\xd0\x1e\xea\x2d\xa2\xde\x8a\ +\xb9\x2d\x1f\xd2\x82\xb5\x19\x8b\x2c\xb7\x52\x1f\xc2\x20\xb0\xa8\ +\xcc\x12\xb4\x1e\xca\x82\xc8\x32\x57\x8e\x9c\x3b\xa7\x27\x69\x5e\ +\xaf\x0d\xc1\x73\xae\xd0\xf9\x3c\x7e\x7f\xb0\xef\xf7\x7e\xef\xd9\ +\xce\xb9\x77\x80\x42\xa1\x50\x28\x14\x0a\x85\x42\xa1\x50\x28\x14\ +\x8a\xff\x0d\x22\xda\xc0\xab\xe9\x1d\x00\x8e\x03\x00\x38\x69\x4c\ +\xc5\x5b\xdb\x44\x7b\x2e\x06\xa1\x05\x1c\x68\x68\x28\x29\x4a\xdb\ +\x33\xf9\x1a\xe5\xec\x60\x77\x3c\xd2\x2b\xd2\x77\x31\x50\xa1\x9f\ +\xfe\xcb\x65\x37\x4a\x8c\xd0\x1e\x4f\x7d\xa3\x5b\xa8\xef\x22\x90\ +\xf1\x15\xe0\x66\xba\x33\xcb\x4a\x13\x89\x48\x5a\xb4\x7f\x21\xc4\ +\xae\x00\x00\xab\xe9\x8f\x79\xab\x00\x00\x32\x45\x74\x32\x10\x08\ +\x08\xf7\x2f\x84\xf0\x00\xd1\x68\x34\x67\x2f\xc9\xac\x32\x9b\xf5\ +\x0f\x8e\xe5\x44\xfb\x17\x42\xca\x1d\xb8\xdf\xde\x3e\x49\x29\xdf\ +\x6a\x36\xf3\x6a\xfa\x63\x19\x19\x16\x42\xda\x12\xec\x8e\x86\x47\ +\x40\x78\x95\xc9\xa8\xa2\x5a\x6b\xba\x28\x2b\x87\x11\x9b\x4c\xb3\ +\x77\x43\xcf\xdf\xbb\xb7\xef\x1c\x27\x20\x35\x86\xd1\xbe\x2d\x65\ +\xbb\x47\x46\x87\x9e\xbd\x92\x99\x07\x90\xb0\x0b\x98\xe1\xd5\xf4\ +\x36\x00\x27\x8c\x3a\xa5\xbc\xbc\x3b\x1a\x7e\x2a\x33\x8b\x25\x05\ +\x00\x80\x57\xd3\x47\x01\xcc\x3f\x0f\x64\xd9\x86\x54\x22\xf2\x49\ +\x56\x0e\xcb\x0a\x00\x16\x3e\x23\xfc\xa4\x2b\x5d\x4f\xa2\x97\x33\ +\x66\xb3\xa5\xc6\xd2\x7d\xf8\xdb\x5a\x5a\x6c\xa6\xaf\x60\xe9\x29\ +\x48\xba\x39\x96\x16\x30\x10\x0c\x66\xb3\xc5\x74\x9d\xd9\xcc\xab\ +\xe9\xdf\x65\x64\xb0\xfc\x24\xd6\x77\x33\xf8\x95\x30\xbe\xc3\x64\ +\xb4\xaa\x4a\xd3\x6f\x89\xf6\xb7\xbc\x00\x00\x48\x76\x86\x07\x39\ +\x41\x9d\x51\x27\xc0\x31\xd1\xde\xcb\xa2\x00\x00\xa0\x9c\x0e\x5b\ +\xe2\x6b\x85\xa9\x11\xcf\x61\x7d\x3d\x07\xeb\x32\x19\xf5\x8b\xf6\ +\xb6\xbc\x80\xda\xda\x66\x17\xb5\x23\x01\x60\xf3\x9c\x01\xc7\xf9\ +\x54\x2c\x54\x21\xda\xdf\xd2\x02\xfc\x7e\xbf\x6d\xda\xc1\x3a\x40\ +\xb0\x27\x5f\x27\xe0\xad\xa9\x78\x28\x20\x23\x83\xa5\x05\x4c\xb0\ +\xd2\x4b\x1c\x38\x92\xaf\x11\x82\x07\xd3\xe3\x1b\x4f\x03\x30\x3d\ +\x24\x2d\x35\x16\x1e\x85\x9b\xce\x00\xfc\xca\x5c\x95\xbc\x70\x66\ +\x73\x95\x32\xdf\x14\x59\xf3\x30\x54\xdf\x74\x14\x84\xc7\x0c\xfe\ +\x1f\x73\xd4\xbe\xb7\x27\x7a\x6d\x4c\x66\x16\xe9\x05\x54\x6b\xcd\ +\xe5\x1c\xac\x17\x80\x73\x56\xe3\x40\x9a\x03\xfb\x1f\xc5\x42\x2f\ +\x65\xe7\x91\xfa\x1b\xe0\xa9\x6f\x74\x73\xb0\xbb\xc8\xbb\x78\x00\ +\x33\x94\x41\xb3\xe2\xe2\x01\x89\x05\x1c\xf2\x9f\x5c\x43\x88\xad\ +\x0b\xc0\x9c\xb3\x3f\x01\x3f\x95\xec\x0c\xa5\x64\xe5\x30\x22\xa5\ +\x00\x9f\xaf\xc5\x91\x63\xe4\x0e\x01\xb6\xe5\xeb\x9c\xf0\x0b\xc9\ +\x58\x38\x22\x23\xc3\x42\x08\x2f\x20\x10\x08\xd0\x19\x57\xe6\x3a\ +\x01\x2a\x0d\xa3\x1b\x0f\x6f\x87\xcf\x89\xf6\x2f\x84\xf0\x02\xfa\ +\x5f\x8f\x9d\xc5\xec\x7f\x83\x7f\xe9\xb3\x4f\x39\x75\x48\xda\xeb\ +\xff\x85\xd0\x5d\xc0\xe7\x6b\x71\xcc\xb8\x32\x13\x00\x4a\xf2\xe4\ +\x37\xc5\x8e\xa2\x8a\x7b\x1d\x57\xa5\x3c\xef\x17\x42\xe8\x0a\xf8\ +\xb2\xe9\x37\xe3\x40\x36\x5f\xb2\xe5\xec\x35\xcb\xe5\xe2\x01\xc1\ +\xaf\xc5\x3f\x0f\x0c\x30\x77\xd9\xae\x61\xc2\xe1\xe1\x04\x1f\x08\ +\x25\x75\xc9\x78\xf0\xad\x48\x4f\x85\x42\xa1\x50\x28\x14\x0a\x85\ +\x42\xa1\x50\x28\x14\x8a\x42\xfc\x01\xea\x12\xdd\x53\xe7\x12\x49\ +\xf2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x06\xb5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\x67\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x70\x5b\x57\x15\xc7\x7f\xe7\x2a\x85\x94\xd0\xa4\x4d\x3f\ +\x67\x18\x16\x0c\xbb\x34\x49\x93\x36\xb4\x14\x18\x68\xac\x2f\xa7\ +\x8d\xed\xda\x8a\x76\x6d\x67\x62\xd9\x1e\xd6\xac\xca\x02\x16\x4c\ +\x16\x6c\xd8\x32\x53\x5b\x76\x57\xed\x46\xb6\x34\x0c\x4d\x1b\x3f\ +\xe9\xc9\xe5\xa3\x84\x0e\xe5\xa3\x2d\x30\xcc\x74\x4a\x17\xdd\x51\ +\x0a\xc4\x69\x6a\x3b\x13\xdd\xc3\xc2\x92\x31\xfa\xbc\x4f\x7a\xcf\ +\x36\x83\xff\xcb\x7b\xcf\x3b\xe7\xfc\x7f\xbe\xf7\x3e\x3d\xe9\x19\ +\xf6\xb5\xaf\x7d\xfd\x3f\x4b\xda\x0d\xa6\x9e\x7d\xf6\x90\xae\x7d\ +\xf6\x3b\x28\x23\xc0\x41\x85\xab\xc6\xf0\x43\xaf\x90\xff\x60\x87\ +\xfb\xeb\x4b\xa9\xec\xd4\x97\xac\xe5\x79\x81\xc7\x81\x75\x55\x2e\ +\xdf\x8a\x7d\xe6\x47\xaf\x17\x7e\xfc\x49\x73\x6c\x0b\x80\xd1\xd1\ +\xc9\x3b\xd6\x6e\x33\x3f\x03\x4e\x37\x4d\x5d\x13\x4c\xda\x5b\x9a\ +\x7d\x33\xa2\xbe\x43\x51\x7c\x62\xfa\x2b\x46\xb4\x0c\x1c\xf9\xef\ +\x19\x79\xfb\xc0\xc1\x4f\xbf\xf9\xda\x4b\x2f\xad\x6e\x1f\x35\xcd\ +\x09\xd6\x0e\x98\xe7\x69\x35\x0f\x70\x44\x51\x2f\x95\x99\x79\x2c\ +\xc4\x7e\x43\x55\x67\xf3\x00\xfa\x50\x6d\xfd\xf6\xef\x36\x8f\xb6\ +\x00\x40\x18\xed\x5c\x42\x0f\xef\x55\x08\xdd\xcd\x6f\x4a\x61\xac\ +\x79\xac\x05\x80\xc0\xed\xdd\x4b\x6d\x42\x48\x67\x73\x8f\xf6\xd1\ +\x67\x24\x4a\x66\x26\xcf\xf4\x32\x5f\xd7\xc1\xe6\x81\xd6\x15\xa0\ +\xbc\xd1\xbb\xa4\x1e\xb6\xd6\x94\xf7\x02\x84\x64\x66\xf2\x0c\x98\ +\x0a\xbd\xcd\x03\xad\xde\x5a\x00\xa8\xc4\x2e\x01\xd7\x7a\xe7\xda\ +\x7d\x08\xc1\xcc\xcb\x2a\xc4\x7e\xd0\x3c\xda\x02\xa0\xbc\xf4\xc2\ +\x7b\xc6\x68\x0a\x67\x08\xb2\x2b\xdb\xa1\x6e\xde\x65\xd9\x03\xb2\ +\xaa\xaa\xe9\xf2\xd2\x0b\xef\xb5\xcc\x74\xba\x24\x9d\xcd\x3d\x6a\ +\xad\x29\x83\x1e\x76\xe8\xe7\x9a\x55\x49\xfa\xc5\xb9\xdf\x38\xc4\ +\x0e\xac\x54\x76\xea\x11\xb5\x54\x80\x3b\x7b\xc5\x2a\x5c\x47\x49\ +\x55\x8a\xf9\x5f\xb7\x9b\xef\x08\x00\xf6\x26\x84\x30\xcd\x43\x0f\ +\x00\xb0\xb7\x20\x84\x6d\x1e\x1c\x00\x00\xa4\x32\x33\x8f\x29\xea\ +\xb9\x42\x00\x9b\x28\x2f\x2d\xbc\xe5\x92\xdb\x55\xe9\x89\x99\x87\ +\x2d\xb6\x82\x70\x57\xaf\x58\x85\xeb\x6a\x6c\xda\x2f\x2c\x5c\xed\ +\x15\xeb\x04\x00\x76\x17\x42\x54\xe6\xa1\xdd\xe7\x80\x0e\xf2\x96\ +\x66\xdf\x54\xd5\xf4\xe6\xed\xa4\xa7\x8e\x80\xa9\x6c\x9e\xd4\x83\ +\x29\xa8\x79\x23\x32\xec\x6a\x1e\x02\xac\x80\x86\x12\x13\x53\x5f\ +\x45\xf0\x04\xee\x70\x08\xff\x17\xd8\x64\xbf\x2b\x21\x88\x79\xe0\ +\x13\x11\x49\x7b\x8b\x73\xbf\x0a\x52\x23\x30\x00\x08\x0e\x41\x0c\ +\x09\xaf\x90\xff\x6d\x90\x1a\x3b\x61\x1e\xfa\x04\x00\xd1\x42\x48\ +\x64\x72\xa7\x45\xc5\x8f\xda\x3c\x0c\x00\x00\x20\x9e\x9d\x7c\x5c\ +\xac\x59\x0e\x13\x42\x50\xf3\xa8\x0e\x97\x8b\xf3\x0e\xcf\x2f\xed\ +\x35\x10\x00\x08\x17\xc2\x4e\x9b\x87\x00\x77\x81\x4e\xf2\x0b\x0b\ +\x57\x8d\xc8\xb0\xc2\x75\x87\xf0\x3b\xb5\x46\x39\x3d\x31\xf3\x70\ +\xf3\x44\x22\x93\x3b\x2d\x88\xf3\x9e\x57\x63\xce\x0d\x6a\x1e\x42\ +\x58\x01\x0d\xa5\x2e\x4c\x7f\x4d\x55\x97\x81\xcf\xf7\x0c\x56\xfe\ +\x69\x30\x89\xe5\xe2\xec\xef\x00\x92\xd9\xe9\x53\x58\xf5\x81\xa3\ +\x0e\xa5\x6e\xa8\x31\xc3\x95\xc2\xec\x2f\x07\xeb\x78\x53\xa1\x01\ +\x80\xfe\x20\xd8\x98\xda\xdd\x32\x0f\x21\x03\x80\x80\x10\x44\x57\ +\x51\x00\x71\xf9\x74\x19\xba\x79\x88\x00\x00\x40\x72\x22\xf7\x75\ +\x44\xae\xe0\x02\xc1\x4d\x37\x8c\x70\x6e\x79\x31\xff\x8b\x90\xf2\ +\x6d\x29\x12\x00\x10\x2a\x84\xc8\xcc\x43\x08\x77\x81\x4e\x2a\x17\ +\xe7\xdf\x50\x63\xce\x01\x2d\x3f\x46\x04\xd0\x0d\x51\x7d\x32\x2a\ +\xf3\x10\xe1\x0a\x68\x28\x91\x9d\xf9\x86\x58\x7b\x05\x38\x14\xf0\ +\xd2\x1b\xa2\xfa\xa4\x57\x9c\xff\x79\x14\x7d\x35\x14\x39\x00\xa8\ +\x43\xa8\x59\x0f\xe9\xf5\x95\x7b\x5d\xc2\xba\x58\x4d\x47\x6d\x1e\ +\x22\xdc\x02\xdb\xa5\xd6\xae\x22\x72\xd3\xfd\x02\xbd\xa9\x31\xe3\ +\xf2\xd8\x3d\xb0\x22\x07\x10\xcf\x4c\x9d\x34\x50\x05\x75\xf9\xde\ +\xbe\x2e\x39\x8c\x55\x3f\x99\x9d\x3e\x15\x5d\x67\xf5\x4a\x51\x26\ +\xff\x8f\x79\xee\xee\x33\xc5\x3f\x30\x12\x2f\x17\xe6\xfe\x10\x66\ +\x5f\xdb\x15\xd9\x0a\x88\x67\xa6\x4e\x1a\xc5\xa7\x7f\xf3\x00\x47\ +\xb1\xea\xa7\xc7\x27\x1f\x0a\xab\xaf\x66\x45\x02\x20\x91\x9d\x39\ +\x61\x14\x1f\xe1\x9e\x10\xd2\x1d\xb5\xc6\x54\xa3\x82\x10\x3a\x80\ +\x44\x76\xe6\x84\xd4\x6c\xd5\xc5\xbc\xc0\x86\xc2\x86\x43\xda\xa3\ +\xd6\x98\x48\x56\x42\xa8\x00\x82\x98\x07\xd6\xac\x30\x6c\x54\x53\ +\xc0\xa7\x0e\xf1\x77\x47\x01\x21\xbc\xc7\xe1\xf1\xdc\x71\x15\x59\ +\x71\x35\x6f\xd4\x3e\xb5\x5c\x5c\x58\x01\x48\x66\xa7\xbf\x85\xd5\ +\x57\x81\xcf\x39\x5c\xfb\xb1\x85\x21\x7f\x29\xff\xce\x40\x0d\xd7\ +\x15\x0a\x80\x41\xcc\x37\xb4\x5b\x10\x06\x06\x10\xd4\xbc\x58\xce\ +\x7b\xa5\x7c\xb5\xdd\x64\xe2\xc2\xd4\x13\xa2\x5c\x66\x07\x21\x0c\ +\x74\x06\xa4\xc6\x73\xc7\xd5\x88\xf3\x9e\xef\x66\x1e\xa0\xb2\x98\ +\x7f\x5d\x85\xa7\x70\x3c\x13\x8c\xe2\xc7\x33\x53\x27\x9d\x1b\x6e\ +\xa3\xbe\x01\x6c\x99\x87\x7b\x1d\xc2\xd7\x10\x1d\xe9\x66\xbe\xa1\ +\x6d\x10\xd6\x7a\x66\x15\xee\x31\x8a\x9f\xc8\xce\x9c\x70\xe8\xa1\ +\x43\x8a\x3e\x94\xce\x4c\x3f\x68\xd1\x15\xdc\xcc\xaf\x23\x7a\xbe\ +\xbc\x38\xef\x07\xa9\x51\xdf\x0e\xaf\xd2\xf3\x9d\x25\x40\xf9\xbb\ +\xc6\xcc\x50\xa5\x30\xfb\x6e\x90\x1a\xd0\x07\x80\x9d\x30\xbf\x55\ +\x6b\x62\xf2\xac\x15\x73\x99\x08\x21\x04\x02\x50\x37\x5f\x05\xee\ +\x73\x08\x1f\xc8\xfc\x56\xcd\x80\x10\x44\xf5\xac\x57\x9a\xff\xa3\ +\x6b\x7e\x67\x00\x41\xcd\x5b\x95\x11\xbf\x38\x57\x71\xcd\xdf\x4d\ +\xa9\xf1\xa9\x21\x35\xbc\x42\x04\x10\x9c\x0e\xc1\x78\xf6\xe2\xb1\ +\xdd\x32\x0f\xe0\x95\xf2\x55\xb1\x9c\xc7\xf1\x60\x54\x91\x95\xd4\ +\x78\xee\xb8\x4b\xee\x9e\x00\xe2\xd9\x8b\xc7\x8c\x8d\xad\xe0\x68\ +\x5e\x2c\xa3\x61\x9a\x6f\xc8\x2b\xe5\xab\x88\x8e\xe0\x0a\xc1\x48\ +\xd5\x05\x42\xd7\x2d\xd0\x8f\x79\xaf\x94\x2f\x3b\xc4\xf6\xad\xe4\ +\x85\x5c\x1c\x95\x57\x68\xf3\xd6\x67\x1b\x7d\x24\x56\x87\xba\x6d\ +\x87\x8e\x2b\x20\x9e\xbd\x78\xcc\x68\x2c\xc0\x81\x67\xc7\xa2\x36\ +\x0f\x50\x5e\x9c\xf7\x11\x3d\x0f\xac\x3b\x84\xdf\xab\x46\xaa\xe9\ +\xcc\xf4\x83\x9d\x02\xda\xae\x80\x2d\xf3\xca\xfd\x0e\x45\x36\x10\ +\x3b\x5a\x5e\x5c\xf0\x1c\x62\x43\x53\xd0\x95\x60\x90\xb3\xcb\x4b\ +\x73\x7f\x6a\x9e\x68\x01\x30\x94\xfd\xf6\x17\x0e\xd8\x5b\x6f\x29\ +\x3c\xe0\x90\x78\x57\xcc\x37\x14\x9f\x98\x4e\x18\xd1\x9f\xe2\x06\ +\xe1\x6f\x72\xab\x76\xc6\xfb\xc9\x8b\x1f\x6e\x1f\x6c\xd9\x02\xb1\ +\x5a\xed\x7b\xff\x0b\xe6\x01\xfc\xe2\x5c\xc5\xaa\x8c\xe0\xb6\x1d\ +\xee\xd3\x58\xec\xfb\xcd\x83\x6d\x5e\x96\xd6\x27\x1c\x92\x6d\x28\ +\x32\xb6\x9b\xe6\x1b\xf2\x8b\x73\x15\xb1\x8c\xe2\x00\x41\x84\xb3\ +\xcd\x63\x6d\xfe\x5f\x40\x6a\x3d\xf2\x6c\x28\x32\x56\x59\x9a\x5b\ +\x76\x6f\x33\x5a\x79\xa5\x7c\xd9\x05\x82\x42\x8b\xb7\x56\x00\xa2\ +\xdd\xfe\xaa\x1b\xd6\xea\xd3\x7b\xc9\x7c\x43\x5e\x29\x5f\x46\xec\ +\x18\xdd\x21\x5c\x69\x1e\x68\x01\x50\xab\xdd\xbc\x24\xf0\x7e\x9b\ +\x8b\x37\xac\xd5\xa7\xfd\xd2\x7c\x4b\x92\xbd\xa2\xf2\xe2\x82\xd7\ +\x05\xc2\x07\x07\x4c\xed\x52\xf3\x60\xac\x25\xea\x2f\x6f\xaf\x7d\ +\xf1\xd4\x99\x97\x63\x35\x3d\x04\xdc\x0f\xdc\x44\xd4\x37\x1a\x7b\ +\xae\x5c\x8a\xee\x57\xda\xb0\xf4\xd7\x3f\xff\xfe\xfd\x2f\x1f\x7f\ +\xe4\xb2\xaa\x3c\x20\x9b\xef\x1b\x7d\xac\xaa\x2f\xdf\x16\xb3\xcf\ +\xbc\x56\x78\xf1\xa3\xdd\xee\x6f\x5f\xfb\xda\xd7\xde\xd2\xbf\x01\ +\xee\x83\x44\x52\xf4\x9c\x9a\x3b\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x03\x62\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x14\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3b\x68\x14\x51\x18\x85\xcf\x99\x5d\x30\x62\xb0\x11\x11\x31\ +\x85\xc1\x58\x08\x01\x0b\x61\x77\xed\x02\xbe\x30\x85\x8f\x0d\x31\ +\x60\x97\x80\xa8\xa4\xb3\x09\x29\xad\x8c\xa5\x90\x20\x5a\x58\x5a\ +\x24\xee\x86\x20\x24\x82\x0a\x16\x82\xd9\x80\x45\x24\x85\x85\xa2\ +\xc5\x82\x88\x58\x28\x3e\x12\xdc\x9d\x63\x13\x44\x77\x66\x77\x33\ +\x33\x7b\xf7\x26\xce\x7c\xe5\x9d\x9b\xf3\x9f\x39\x99\xc7\xbf\x77\ +\x2e\x90\x90\x90\x10\x67\x18\x55\xa0\x6f\x5a\x9d\xab\x69\x8c\x0a\ +\x1a\x14\xd0\x4b\x60\x5b\x2b\x8c\x85\x45\xc0\x1a\x81\x15\x82\x33\ +\x1d\x15\x4c\x3d\xbb\xc0\x6f\x8d\xe6\x47\x0a\x20\x5b\xd4\x09\x40\ +\xf7\x00\x74\x45\xd1\x31\x48\x19\xe0\x48\x29\xcf\xc7\xf5\x26\x38\ +\x61\x95\xb3\x45\x8d\x00\x7a\x84\xcd\x7b\xf2\x00\xd0\x05\x68\x21\ +\x5b\xd4\x70\xbd\x09\xa1\xae\x80\xec\xac\x4e\x42\x5a\x40\x84\x00\ +\xdb\x4c\x15\xe0\x69\xbf\x2b\x21\x70\x00\x7d\xd3\xea\xfc\x99\xd6\ +\x6b\x00\xfb\x5a\x62\xad\x7d\x94\xb7\x57\x78\xa8\xf6\x99\x10\xf8\ +\x3f\xb8\x9a\xc6\x28\xb6\xde\xc9\x03\x40\xd7\xba\xf7\x7f\x08\x1c\ +\x80\xa0\xc1\xd6\xf8\x69\x3f\x7e\xde\x43\x04\x80\xde\xd6\xd8\x69\ +\x3f\x7e\xde\xd3\x41\x45\x9a\xbd\xe7\x4b\x79\x27\x72\x6f\x11\x85\ +\x6c\xd1\x55\xbd\x63\x7e\xde\xb7\xca\x53\xdc\x18\x49\x00\xb6\x0d\ +\xd8\x26\x09\xc0\xb6\x01\xdb\x24\x01\xd8\x36\x60\x9b\xd8\x07\xd0\ +\xb4\x11\x3a\x52\xd0\xde\xb4\xe3\x5e\x95\xcb\x63\x20\xf6\x34\x9b\ +\x9f\x29\xba\x6f\xc2\x9a\xa1\x20\x10\x65\x81\xf3\xec\xc0\x9d\x52\ +\x3f\xbf\x86\xd5\xda\x70\xcd\x46\x07\x73\x05\x9d\x11\x75\x0f\xc0\ +\x2e\xd3\x46\x3c\x08\xef\x00\x5e\x2c\x0d\x70\x31\xc8\x9f\x35\xea\ +\x04\x01\x6f\xa7\x5a\xf7\x16\xc8\x14\xab\x13\xa2\xe6\x60\xe3\xe4\ +\x01\x80\xe8\x06\xf5\x3c\x53\xd4\x15\x93\x65\x7c\x03\xc8\x15\x34\ +\x44\x70\xcc\x64\xe1\x0d\x92\x22\x34\x99\x2d\x28\x67\xaa\x80\x27\ +\x80\xdc\xac\xf6\x8b\xba\x6b\xaa\x60\x08\x52\x80\xee\x67\xe7\xb5\ +\xd3\x84\xb8\x27\x00\xb9\xee\x38\x00\x23\xc5\x42\x43\x74\x6b\x15\ +\x97\x4d\x48\x7b\x6f\x01\xb2\xdf\x44\xa1\xa8\x10\x32\xe2\xcb\xef\ +\x19\xb0\x39\x57\x79\x65\xc6\x57\xe0\x05\x11\x27\xc5\x83\x26\x8c\ +\xa0\x8a\x1e\x17\x5a\xa8\x77\x58\x8c\xfe\x11\xc7\x8f\xc0\x01\xbc\ +\x38\xcb\xd0\x8d\x4e\x23\x8e\xce\x09\xa8\x9a\x50\x6e\x4c\xec\x5b\ +\xe1\x24\x00\xdb\x06\x6c\x93\x04\x60\xdb\x80\x6d\x92\x00\x6c\x1b\ +\xb0\x4d\x12\x80\x6d\x03\xb6\x49\x02\xb0\x6d\xc0\x36\x49\x00\xb6\ +\x0d\xd8\x26\xf0\xaf\x41\x5b\x10\x38\xd0\x6c\xc5\xb7\x19\x02\xd6\ +\x6a\xc7\x62\x75\x05\x10\x58\xa9\x1d\x8b\x59\x00\x9c\xa9\x1d\x8b\ +\x53\x00\xe5\x8e\x0a\xa6\x6a\x07\xe3\x12\x40\x15\xe0\x88\xdf\xbe\ +\xe1\x38\x04\x50\x05\x78\xa9\xde\x7e\xe1\x2d\xf3\x16\x08\x49\xd3\ +\xcd\xd2\xff\x5d\x00\x7f\x6f\x97\xff\xb1\x03\x93\xaf\x4e\xf1\x7b\ +\xa3\xf9\x9e\xa5\xe6\xa8\xef\x5a\x53\x08\x78\xbb\x94\x77\x7a\x5a\ +\xad\xeb\xfd\x34\x06\x7c\x6a\x75\x91\x96\x20\x7c\x34\x21\xeb\x09\ +\x80\xd0\x13\x13\x85\xa2\x42\x47\x4f\x4d\xe8\xfa\x5c\x01\xce\x4d\ +\x00\xbf\x4c\x14\x8b\xc0\xe7\x8a\xeb\xdc\x36\x21\xec\x09\x60\x29\ +\xcf\x65\x6d\x8e\xbd\x01\x7f\xa0\xc3\xe1\x97\x03\xfc\x60\x42\xdb\ +\xb7\x0f\x58\x5a\xc6\x2d\x00\x0f\x4c\x14\x0c\x8e\x26\x16\xcf\xf1\ +\xa1\x29\x75\xff\x46\xe8\x3a\xdd\xd2\x32\x87\x04\x5e\x83\xbd\xdb\ +\xe1\x0b\xc9\xa1\x52\x3e\x35\x6e\xb2\x48\xd3\x2f\xae\x99\xa2\x0e\ +\x13\xee\x98\xc0\xe3\x04\x76\x9b\x34\xb3\x4e\x19\xd2\x3c\x1d\xe7\ +\xc6\xe2\x79\xbe\x6f\x43\xbd\x84\x84\x84\x18\xf3\x1b\xe9\x0c\xd1\ +\x12\xec\xcb\x09\x01\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\x79\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2b\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x6f\x28\x98\x05\xfc\x5b\x00\ +\x19\xc7\x23\x31\xd0\x56\x01\x00\x61\xbd\xe7\xdc\xe4\xc0\x4a\xc6\ +\x01\x80\x2f\x3c\x1a\xe8\x01\xff\xf7\xcd\x6b\x25\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\x98\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x4a\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\x3f\x4a\xc4\x40\x14\xc7\xf1\xef\x4b\x16\xbd\x81\x5b\x78\x02\ +\xd7\xca\x2a\x60\xb7\xf1\x00\x0b\xf1\x40\x7a\x22\x21\xd8\x08\xc2\ +\x6e\x27\xa4\x5e\xff\x9c\xc0\x42\x2b\x0f\xb0\xe1\x59\x84\x28\xc4\ +\xc4\x99\x97\x9d\x89\x85\x53\xce\x3c\xf8\xfc\x98\x79\x3c\x06\xfe\ +\xfb\x92\x29\xb1\xac\xd4\x39\x3b\x2d\x11\x5e\xab\x22\xb9\x04\x48\ +\x26\xc5\x6b\xdd\x20\x64\x28\xc7\xed\xfe\x24\x01\xbe\x70\x38\x01\ +\x5e\x98\xc9\xaa\x3d\x8b\xfe\x04\x3f\xf0\x54\x96\xd5\x4a\xde\x26\ +\x09\xe0\xc2\xa3\x06\xf0\xc1\xa3\x05\xf0\xc5\xa3\x04\xb0\xe0\xc1\ +\x03\x58\xf1\xa0\x01\xc6\xe0\xc1\x02\xf8\xe2\xe7\x37\x7a\xb4\x13\ +\xbd\x13\xe5\xa3\x2a\x92\x1c\x02\x0c\x22\x0b\x5e\xa3\x6b\x51\xce\ +\x80\x83\x76\x7f\x36\x25\x0e\x9c\x0a\x3c\x26\x48\xd1\x9e\x8d\x7e\ +\x82\x3d\xf0\x8b\x87\x42\xde\xf7\x0a\x10\x0a\x1f\x15\xc0\x88\x6f\ +\x80\x05\xf0\x94\x22\x79\x17\x37\x07\x08\x8d\x9b\x02\xc4\xc0\x01\ +\xd2\x90\x78\x56\xea\x5c\xd5\x1f\x07\x8f\x1b\xb0\xe0\xd4\xba\xb6\ +\xe0\xce\x00\x23\xf1\xe7\x14\x59\xf6\xe1\xa6\x49\x18\x03\xf7\x9e\ +\x84\x91\xf0\x0d\xb0\x70\x4e\x42\x23\xde\xd6\x0d\xe2\xae\xde\x90\ +\x9e\x62\x33\x4e\x2a\xf9\xd8\xc6\x94\x4e\x71\x68\xdc\x79\x43\x4d\ +\x13\x5e\x69\x42\xad\xf7\x2e\x1c\x55\x91\x5a\x6f\x5d\x78\xb7\x6e\ +\x08\xff\x0e\xd0\xac\x43\x60\xfb\xeb\x4f\xe6\x1a\xd1\xa6\x83\xb7\ +\x83\x78\x4f\x9d\xcf\x3c\x68\x6e\x41\xd5\x3d\x9a\x55\x25\x68\xdd\ +\x5f\xaf\x4f\xda\x1b\xa3\x91\x9e\x7b\xef\x4a\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xa6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x58\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\xdc\x7f\xf8\xb8\xe1\xfe\xc3\xc7\x0d\x94\x98\xc1\x44\ +\x89\x66\x6a\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\ +\xa8\x03\x06\xdc\x01\x2c\x14\x9b\xf0\x9f\xc1\x81\x92\x2a\x79\x18\ +\x84\x00\x23\xc3\x01\x45\x79\xd9\x06\x72\xb5\x0f\x78\x08\x8c\x3a\ +\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\xe0\x0e\x00\ +\x00\xe6\xf7\x0c\x89\x70\x77\x76\x17\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\x50\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x02\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x2d\x4e\x03\x51\x14\xc5\xf1\x73\x29\xe1\x4b\xa0\xc0\xb3\x01\ +\x92\x0a\x7c\xc7\x15\x3c\x86\xd4\x23\x31\x2c\xa0\x99\x05\x74\x07\ +\x4d\x05\x49\x25\xa6\x09\x81\x86\xb0\x08\x76\x80\x22\x21\x75\x08\ +\x98\x66\xca\xbb\x58\xf2\x1e\x04\x35\x8f\x84\xf9\xff\xe4\xb9\x23\ +\xce\x1c\x33\x23\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\xad\x60\ +\xbf\xdd\x8b\x62\xd8\xc9\xd2\xa4\x21\xbd\x9e\x42\x59\x96\xe1\xa7\ +\xfb\xb7\x03\x14\x67\xe7\x7b\x1b\xcb\x30\x72\xd3\xa9\xa4\x9d\xc6\ +\xda\xe5\x51\x99\xfc\xc6\x6b\xbf\xb8\x9f\x4d\x9e\xe3\x63\x32\xc0\ +\xc9\x60\xb0\xbb\xaa\xb6\x1e\x25\x3b\xc8\x50\x2e\xa7\x45\xa8\x75\ +\xf8\x30\x1b\xbf\x7c\x0d\xd7\xe2\xa7\x3e\x96\xdb\xe5\x3f\x7c\x79\ +\x49\xda\xb7\x75\x8d\xe2\x30\x19\xc0\x5d\xfd\x3c\x7d\xf2\x33\xd3\ +\x71\x9c\x25\x03\xb4\x4d\x32\x80\x99\xe6\x7f\x51\x24\x07\x77\xdd\ +\xc5\x59\x32\x40\x67\xf3\x7d\x28\xf9\x53\x96\x46\x79\x2d\x7c\xa5\ +\xcb\x38\x4c\x06\xb8\x9d\x4e\x5f\x43\xa8\x8f\xcc\x75\x25\xe9\x2d\ +\x4b\xb5\x66\x55\x26\xbf\x56\x1d\xba\xf1\x17\x40\xe2\x47\x08\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x68\x8b\x4f\xc6\xe5\x42\x89\xb1\ +\xed\x97\x86\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x27\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x68\x5c\x55\x14\xc6\x7f\xe7\xcd\xb4\x5a\x8c\x08\xb6\xba\ +\x30\xa8\x2b\x51\xd4\x8d\x50\x84\x22\x48\x6c\x27\x89\x41\x0c\x76\ +\xc6\xd1\x95\xd8\xfc\x99\x50\x17\xa2\x05\x45\xf0\x0f\xe3\xd0\x8a\ +\x15\x04\x17\x22\xb6\x49\xa6\xc6\x45\x8a\x9a\x26\x0d\xa1\x1a\x3b\ +\x49\x64\x0a\x8a\x20\x28\x08\xc5\x85\x20\xe2\xa2\x41\x04\xad\x14\ +\x6d\x0b\x93\xb9\xc7\x45\x1c\x79\xf3\x66\xc0\x14\xdf\xbd\xef\x62\ +\xe6\x5b\x7e\x1f\xdc\x73\xee\x77\xce\xfd\xf7\x98\x81\x0e\x3a\xe8\ +\x60\x33\x43\x92\x4e\x60\xa3\xc8\x64\x47\x8b\x22\xf2\x32\x18\x51\ +\xd5\x43\xcb\x73\xc7\x5e\x8d\x63\xdc\x20\x8e\x41\x6c\xa3\x3f\x3b\ +\xfc\x00\x42\x11\x34\x0d\x92\x12\x09\x5e\x89\x6b\xec\x74\x5c\x03\ +\xd9\x42\x6f\x6e\x78\xa7\x21\x58\x90\xe6\x6e\x8d\xad\x70\x5e\x77\ +\x40\x5f\x6e\xec\x0e\x34\x58\x04\xba\x22\x92\x89\x2b\x86\xb7\x06\ +\x64\xf2\x63\xb7\x28\xa6\x82\xb0\xa3\x8d\xac\x71\xc5\xf1\xd2\x80\ +\x81\xfc\xd0\x0d\x18\x53\x01\x6e\xb6\x1d\xcb\x3b\x03\x06\x07\x87\ +\xaf\x5d\x33\xa9\x4f\x04\x6e\x77\x11\xcf\x2b\x03\x7a\xf6\xed\xbb\ +\xfa\xd2\xd6\x60\x1e\xd8\x19\x91\x62\x6b\xf9\x28\xbc\x31\xa0\xa7\ +\xa7\x98\xde\xf2\x47\xfa\x38\xca\xee\x88\xa4\xc4\xb8\xe9\x45\xe1\ +\x8b\x01\x92\xde\xbe\x7a\x14\x65\x6f\x13\xab\x6a\x75\xf2\xe0\x89\ +\x01\x99\xdc\xe8\x1b\x82\x0e\x47\x68\x45\xc4\xea\xe4\xc1\x03\x03\ +\x7a\x1f\x2d\xbc\x20\xf0\x7c\x1b\xc9\xfa\xe4\x21\x61\x03\x32\xb9\ +\x42\x01\xd5\xc3\x6d\xa4\xba\xab\x1c\x12\x33\x20\x93\x2b\xe4\x04\ +\x3d\xd2\x44\xae\xef\xf5\x4e\x2a\xdf\x40\x22\x06\xec\xc9\x16\x32\ +\x82\x1e\x6f\x89\x1f\x60\xb0\x78\xe4\xb5\x83\x73\x03\xfa\xf3\x23\ +\xf7\x06\xa2\xf3\xc0\xd6\x88\x64\x50\xb7\x93\x07\xc7\x06\xec\xc9\ +\x0f\xdd\x69\x8c\x2c\x02\xd7\x84\x79\xc1\x7d\xe5\x1b\x70\xf6\x1c\ +\xde\x9d\x1d\xb9\x35\x30\x52\x01\xae\x8f\x48\x46\x13\x9a\x3c\x38\ +\xea\x80\xbe\xbd\xfb\x6f\x4c\x09\x4b\x40\x77\x98\x17\x24\xb1\xca\ +\x37\x60\xbd\x03\x32\xf9\xb1\xeb\xd4\xac\x7d\x0a\x72\x5b\xb3\xa2\ +\x9a\x64\xe5\x1b\xb0\xda\x01\xbb\xf2\x07\xb6\x89\x31\x0b\xc0\x3d\ +\x11\x49\xc1\xfe\x2d\x6f\x23\xb0\x66\x40\x4f\x4f\x31\xdd\xa5\x17\ +\x3e\x00\xee\x8f\x48\xd6\xef\xf7\x57\x02\x2b\x06\x14\x8b\xc5\x60\ +\xcb\xf6\x73\x93\xa8\x0c\x46\x24\x6f\x2a\xdf\x80\x0d\x03\xe4\x8b\ +\xb3\xab\x6f\x02\x4f\x36\xb1\xda\xa8\x7c\xe2\xcb\xbe\x09\xb1\x1b\ +\x90\xc9\x8d\xbe\x28\xe8\x81\x16\x41\xfc\x69\xfb\x30\x62\x35\xa0\ +\x37\x57\xd8\x2f\x70\xa8\x55\x11\x67\x8f\x9b\x2b\x45\x6c\x06\xf4\ +\x66\x47\x0e\x83\xbe\x1b\xe5\xc5\xc3\xb6\x0f\x23\xbe\x0e\x10\x89\ +\x7e\xd0\x00\x24\xd1\x5b\xde\x46\x10\x9b\x01\xd2\xf6\x0d\xef\xf5\ +\xdc\x81\x18\x0d\x30\xc8\x33\xb4\xce\x38\xf1\x2f\x4e\xff\x86\xd8\ +\x12\x5c\x9e\x9d\xf8\x08\x78\xba\x55\xd1\x54\x5c\x31\x6c\x20\xd6\ +\x0a\x2d\xcd\x4e\xbe\x03\x5a\x6c\x66\x05\xc0\x5b\x13\x62\x6f\xd1\ +\xa5\xd9\xf2\x41\x11\xde\x8e\xf2\x8a\x7a\xb9\x1c\x6c\x24\xa5\xbb\ +\xee\xea\x7e\x56\x95\xe9\x30\x29\x88\x58\x8a\xf7\x9f\x60\x25\xa1\ +\x52\xa9\x64\xce\xef\x08\x86\x10\xf9\x38\x22\x09\x9e\x75\x82\xb5\ +\x64\xbe\x1e\x1f\xaf\x5d\x75\x59\x1e\x43\xf5\xf3\x66\x45\x44\x3d\ +\xea\x04\xab\x89\x9c\x3a\x35\x7e\xb1\x66\xea\x0f\x83\x7c\x1b\xe6\ +\x05\xc4\x97\x3d\xc1\x7a\x12\xd5\xf9\xa9\xdf\x6b\x41\xed\x41\x81\ +\x1f\xc2\xbc\x20\x22\x1e\xfc\x48\xcb\x49\x15\xaa\x33\x53\x3f\x13\ +\xd0\x8b\xb0\x1a\xe6\x15\x02\x91\x64\x4d\x70\xd6\x86\x95\x99\xc9\ +\x1f\xa5\xae\xfd\x28\xe7\xc3\xbc\x2a\x01\xeb\x27\x44\x22\x70\xba\ +\x0e\x2b\x27\xcb\x67\x4d\xca\x3c\x04\x5c\x6c\x56\x34\x20\xa1\xe5\ +\xe0\x7c\x23\x5a\x99\x39\xf6\xa5\x22\x59\xa0\xd6\x26\x17\xe7\x26\ +\x24\xb2\x13\x2f\xcf\x4e\x9c\x16\xe5\x09\xa2\x8f\x27\x25\x70\xbd\ +\x31\x26\x76\x14\x55\xe6\x26\x3f\x44\xf4\xa9\x26\x52\xd6\x37\x46\ +\x97\x1e\x24\x7a\x16\x2f\x9d\x28\x1f\x45\x78\xa9\x55\x71\xf7\x82\ +\x4c\xfc\x32\xb2\x74\x62\xf2\x75\x45\xde\x6a\x23\x39\xc9\x2d\x71\ +\x03\x00\xbd\xef\xee\x9b\x9e\x03\xde\x8f\xf0\x4e\xae\xcc\x3e\x18\ +\x40\xa9\x54\x32\xb5\x5f\xbb\x47\x11\x5d\x08\xf3\x7f\x6f\x88\x56\ +\x73\xf4\xc2\x00\x80\x6a\xb5\xb4\x56\xeb\xaa\x3f\x8e\x72\x26\x22\ +\x59\x35\xc1\x1b\x03\x00\xaa\x53\x53\x97\xd3\xdb\x2e\x0d\x2a\x7c\ +\x13\x91\xac\x1d\x0b\x5e\x19\x00\xb0\x38\x3d\x7d\x21\x30\xe9\x01\ +\xe0\x7b\x17\xf1\xbc\x33\x00\xa0\x72\xf2\xc8\x2f\x75\xd5\x3e\xe0\ +\x9c\xed\x58\x5e\x1a\x00\xf0\xd9\x5c\xf9\x27\x13\xd4\xfb\x80\xdf\ +\xda\xc8\xb1\x2d\x09\x6f\x0d\x00\x58\x99\x79\xef\xbb\x20\xd0\x01\ +\xe0\xcf\x88\xb4\x39\xfe\x32\x03\x70\x7a\xa6\xfc\x95\x51\x79\x04\ +\xf4\x9f\x77\x83\x6c\x86\xbf\xcc\x84\xb1\x32\x37\xb1\x0c\x1c\x04\ +\xad\x23\xd4\x45\x78\x2d\xe9\x9c\x3a\xe8\xa0\x83\xff\x07\xfe\x02\ +\xec\x35\x2d\x8c\x9b\x14\xe3\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\x8b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x6e\x26\xb0\x82\xfd\x2b\xf8\ +\x29\xe4\x40\x66\x12\x2c\x5b\x05\x00\x00\x00\x00\x00\x00\xc0\xff\ +\xc6\xda\xe7\xa6\x23\x92\x66\x3a\x20\xcd\x80\x74\x00\x00\x00\x00\ +\x00\x00\x00\x00\xbc\xd7\xba\x61\x02\x03\x59\xaf\x8c\x6f\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x85\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ +\xce\xb1\x11\x00\x30\x08\x03\x31\x2e\x4b\xb1\x35\x23\x42\x86\x80\ +\x52\xdf\xdb\xa7\x88\x45\x59\x3d\x59\x3d\x9b\x8f\xb7\x19\x5f\x04\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf0\x01\ +\x8b\x69\x06\x03\x87\x7c\xe1\xcd\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x04\x32\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe4\x49\x44\x41\x54\x78\x9c\xed\ +\x99\xcb\x6f\x5b\x55\x10\xc6\xbf\x39\xb6\x4b\x02\xa1\x42\x24\x6c\ +\x10\xa9\xa0\x41\x6a\xd3\x76\xe3\xb4\xac\x90\x90\x4b\xec\x8b\xda\ +\x45\x5a\x3f\xb2\x80\x2c\xc8\xc3\x0e\xfc\x03\x88\x55\x1b\xd8\x54\ +\x42\xac\x10\x42\x42\xa1\x24\x15\x2c\xb2\x30\x8f\xb6\x0b\x8c\xac\ +\xb6\x89\x68\x61\x01\x28\xde\xd5\x54\x2a\x46\xa2\xcd\x0a\x58\x54\ +\x55\xd5\xa8\xb1\xcf\xb0\x48\x08\xd7\xf7\x1e\x3b\x7e\xdc\x6b\x17\ +\x31\x3f\xc9\x9b\x99\xf3\x98\xf9\x3c\x67\xee\xb9\x36\x20\x08\x82\ +\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\xfc\xbf\xa0\x6e\x6d\x1c\ +\x4b\x64\xe2\x20\xfe\x08\x04\xc5\xe0\x4f\x2e\x7d\xf1\xe9\xa9\x6e\ +\xc4\x11\xe8\xc6\xa6\xd1\x64\x26\x43\xc4\x9f\x01\xd8\x0d\xa0\x8f\ +\x40\x2f\x0d\x1d\x0c\xaf\x95\xae\x17\x56\x3b\x1d\x4b\xc7\x05\x88\ +\xa5\x32\x6f\x13\xf8\x03\xb8\xaa\x8f\xc6\x86\x86\xc3\xf7\x4b\xc5\ +\xc2\xf7\x9d\x8c\xa7\x93\x02\x90\x95\xcc\xbc\x0f\xf0\xe9\xda\x23\ +\x28\xb6\xf7\xc0\xc8\x63\xa5\xe2\xea\xa5\x8e\x05\xd5\x89\x4d\x22\ +\x91\xb9\x60\xe8\xc9\xb5\x79\x10\xa6\x1a\x19\xcf\xa0\x85\xf2\x5f\ +\x4f\xbf\xb1\xb2\xf2\x6e\xd9\xef\xd8\x7c\x17\x20\x32\x39\xd9\x13\ +\xbc\x1b\x5a\x22\xf0\x49\x83\x5b\x13\x01\xcc\x50\x86\xc8\xbe\xde\ +\xe8\x2b\xbf\xb6\x72\xee\xdc\xba\x9f\xf1\xf9\x2a\xc0\xb1\x89\x89\ +\xdd\x1b\xeb\x8f\x9e\x27\xf0\x51\xbb\x9d\x37\x37\xae\x54\x8f\xe6\ +\x80\xbb\x2d\xe0\x4a\xef\x03\x7d\xf2\xe2\xc5\x85\xbb\x7e\xc5\xe8\ +\x9b\x00\xc7\xc6\xa7\x9e\x2a\x57\x02\x39\x10\x0e\x1b\xdc\x15\x83\ +\x0d\x30\xf7\xa4\x9f\x83\xaa\x72\x3c\x97\x5d\xfc\xc3\xc3\xf0\xb6\ +\xf1\x45\x80\xe8\xf8\xec\x1e\x68\x9d\x27\x60\x9f\xdd\xce\x60\x26\ +\x90\xae\x37\x97\xc1\x8a\x40\x54\x6d\xc3\x0d\x55\xae\xc4\xf2\x17\ +\x16\x6f\x79\x1d\xab\xe7\x02\x44\xe3\xe9\x61\x52\xc8\x03\x78\xc6\ +\xe1\x62\x00\x75\x93\xff\x77\x24\x2b\x10\x39\x63\xbb\x45\x50\x56\ +\xfe\xcb\xf9\x5f\x3c\x08\x73\x1b\x77\xf3\x69\x83\xd1\x44\xe6\x05\ +\x52\xb8\x0a\x67\xf2\xdc\x44\xf2\x00\x40\xa4\x01\x66\x87\x75\x90\ +\xa1\xaf\xc5\x92\xd3\x47\xda\x0e\xd4\x86\x67\x02\xc4\x52\x33\xa3\ +\x8a\xf8\x0a\x80\xfe\x6a\x0f\x33\xa8\x89\xe4\xb7\x21\xcd\x9b\x55\ +\x63\xa7\x1f\x50\xcb\x56\x3c\xfd\x72\xab\x71\x3a\xf1\x44\x80\x68\ +\x2a\x9d\x00\xd3\x37\x00\xfa\xec\x76\x06\x33\x76\x38\xf3\xf5\x20\ +\x40\x33\xbb\x44\xe8\x63\x85\x5c\x2c\x91\x89\xb7\xba\xae\x9d\xb6\ +\x6f\x82\x56\x22\x3d\x03\xe0\x73\x00\x41\xbb\x9d\x00\x0d\x90\x33\ +\xf8\xa6\x21\x02\x6f\xf5\x44\x7b\x4f\x08\x80\x30\xfe\xfc\x81\xf0\ +\xed\x5f\x8b\x85\x42\x3b\xeb\xb7\x25\x80\x95\x4c\xbf\xc5\x84\x0f\ +\x1d\xc1\x6d\x7e\x73\xee\xf2\x6d\x8b\xad\x96\x68\xdf\x87\x00\x3a\ +\xb1\xf7\x60\xf8\x5e\xe9\x7a\xe1\x87\x56\xd7\x6d\x55\x00\x8a\xa5\ +\x32\xef\x01\x78\xc7\xed\x81\x86\xc7\xc9\xdb\x17\x87\x4b\x6c\xb2\ +\x86\x86\xc3\xbd\xa5\x62\xe1\x72\xcb\x2b\x36\x43\x24\x32\x17\x0c\ +\xf5\xaf\x7d\x0c\x60\xc6\xe0\xf6\x31\xf9\x6d\x08\xa6\xde\xc5\x38\ +\xfb\x44\xe0\xce\x9b\xd9\x6c\xb6\xd6\x25\xcb\x48\x53\x15\x10\x99\ +\x9c\xec\x09\x05\xee\x2d\x01\x98\x70\x6c\xee\xf3\x37\x6f\x80\x41\ +\x8e\x03\x31\xb2\xce\x3d\x87\xf6\x3d\xfb\xe2\x85\x9b\x37\x7f\x6c\ +\x58\x84\x86\x2b\x60\x6c\x6c\xfa\xf1\xfb\xbb\xd4\x79\x30\x5c\x8f\ +\x20\x3f\xce\x7c\x03\x98\x2b\x01\xb8\xdc\xbb\xa1\xe3\x8d\xbe\x3f\ +\x34\x24\x40\xe4\xd5\xd9\x81\xd0\x03\x9d\x03\x60\xb8\x84\x50\xa5\ +\xf3\xb9\x57\x61\xaa\xe2\x9f\x36\x76\xa9\xe3\x2b\x4b\xf3\x7f\xee\ +\x34\x79\x47\x01\xac\x13\x53\x83\x1c\x0c\xe4\x01\xec\xaf\x72\x30\ +\x5a\xbc\xe0\xf8\x82\x82\x3b\x97\x62\x90\x61\xe5\xbe\x3a\x7b\xbb\ +\xde\xc4\xba\x02\x58\xc9\xd9\xfd\x0c\x9d\x07\x30\x68\xb7\x33\xc0\ +\xd4\xcc\xd5\xb6\x13\x98\xdf\x1f\x7e\x0f\x28\x6d\x7d\x9b\x5d\xb8\ +\x51\x6b\x5a\xcd\x9b\x60\x2c\x39\x7d\x84\x59\x5f\x85\x33\x79\xc6\ +\x8e\x6f\x74\x5d\x81\xc8\xd4\x84\xf7\x54\x2a\xea\x9a\x35\x9e\x36\ +\xbd\x92\x03\xa8\x21\xc0\x2b\x89\xe9\xa3\x80\x5a\x06\x61\xc0\xe1\ +\x62\x22\xe8\x2e\x9f\xf9\x7a\xb8\x45\x20\x0c\x68\x8d\xe5\x68\x2a\ +\x1d\x31\x4d\x70\x35\x90\xd1\x44\xfa\x14\x13\x2d\x12\xf0\x88\x61\ +\xfc\x3f\x9d\xf7\x61\xfe\xb8\x8e\xf5\x56\x2e\xaf\x3f\x37\x3c\xa2\ +\x7f\x2b\xae\x7e\x67\xf7\xb9\x2a\x40\x11\xe6\xa8\x8b\x7f\x98\xf8\ +\x05\x01\xa4\x08\x73\x4e\xbb\xa7\xbf\x07\xfc\x17\x31\x55\xc0\x19\ +\x7a\x78\x1e\x6f\x9e\x41\x04\xad\x08\x67\xba\x1d\x87\x20\x08\x82\ +\x20\x08\x82\x20\x08\x82\x20\x08\x82\xd0\x6d\xfe\x06\xf7\x21\x1d\ +\x03\xf2\x02\xba\x61\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\xe3\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x95\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x3d\x48\x5b\x51\x14\xc7\xff\xe7\xe5\x49\x07\xb1\x2a\x16\x22\ +\x58\x74\xae\x43\x15\x92\x22\xdd\x84\x56\x1d\x14\x37\xeb\x50\x41\ +\x07\x89\x14\x5a\x3f\xa6\x52\x87\x06\x85\x62\xe9\xe2\x47\x1d\xaa\ +\x38\x28\xb8\xa8\x9b\x28\x54\xdb\xa1\x43\xa1\x88\x06\xd4\xc1\xce\ +\x8a\xb6\xa6\x90\xfa\x41\x1d\x6c\x93\x77\x3a\xa8\xe5\xe5\xe5\x45\ +\x93\xdc\x97\x5c\xad\xf7\xb7\xdd\xf3\x4e\x4e\xfe\xf7\xff\xde\xbb\ +\xf7\x92\xdc\x0b\x28\x14\x8a\xeb\x0c\x25\x92\x54\xe9\xf7\xeb\x47\ +\xbb\x05\xf5\x06\xd0\x48\x20\x2f\xc0\x45\x00\x6e\xa4\x59\x5b\xb2\ +\x1c\x03\xb4\xc3\xe0\x15\x0d\x98\xca\x2e\x0c\xcd\x7e\xea\xe9\x09\ +\x5f\xf4\xa1\x0b\x0d\xf0\xb6\x0d\x57\x81\x79\x10\xc4\x77\x9c\xd1\ +\x99\x19\x18\xd8\x20\x68\x9d\x2b\x23\x4f\x3f\x9c\x97\xa7\x9d\x53\ +\x82\xbc\xbe\xa1\x6e\xc0\x58\xbc\x6a\x9d\x07\x00\x02\x4a\x01\x63\ +\xf1\x5e\xdb\xe0\x0b\x80\xe3\xde\x68\x57\xbc\x0b\x5e\x5f\x41\x37\ +\x08\xaf\xd2\x23\x2f\x93\xd0\x83\x22\xef\xd2\xf1\xb7\xc0\xfb\xcf\ +\xb6\x57\xed\x82\xde\xb6\xe1\x2a\xc0\x58\xb4\x84\xf7\x40\x78\xa9\ +\x85\x69\xbe\xe4\xc0\xbd\x35\x33\xf3\x28\xe2\xb8\x56\x01\x1a\x1a\ +\xa6\x5d\x9b\xb9\xc1\x62\x43\xe7\x5a\x30\x7a\x01\xe4\x47\x67\x68\ +\xd5\x76\xaf\x43\x8c\x01\x95\x7e\xbf\xfe\xeb\xfb\xad\xf5\xa8\xc7\ +\x9e\xf0\xd1\x15\x36\x9a\x96\xc6\x3a\x83\xce\x4b\x77\x9e\x8a\xd6\ +\x01\x77\x44\xd7\x26\xc1\x78\x78\x16\x63\x60\x23\xa7\x30\x54\x66\ +\x1d\x18\x63\xc6\x80\xa3\xdd\x82\x7a\xcb\x3b\xff\xf3\x37\xb2\x1e\ +\x5f\x95\xce\x03\xc0\xd2\x58\x67\xd0\x15\x36\x9a\x00\xec\x9d\xc5\ +\x08\x28\x3d\xda\x2d\xa8\xb7\xe6\xc6\x18\x60\x00\x8d\x51\x01\x82\ +\x7f\xfd\xdd\x93\x1f\xe9\x10\x9a\x4e\x96\xc6\x3a\x83\x0c\xf6\x9b\ +\x63\x31\x7d\x83\x8d\x01\x27\xf3\xbc\x29\x21\x4c\xf3\xce\xcb\xcb\ +\x0c\xae\x88\x36\x67\x6e\x13\xe0\xb1\xe6\xd8\x4c\x83\x5c\x64\x6e\ +\x95\x1c\xb8\xb7\x9c\x16\x96\x29\x6c\xb4\xdf\xb6\xe6\xd8\xad\x03\ +\xa2\x56\x78\x97\x6d\xb4\x4f\x06\x1b\xed\x31\xab\xd7\x73\x16\x42\ +\xd7\x03\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\ +\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\ +\x16\x20\x1b\xdd\x89\x22\x1e\xdf\x50\x35\x08\x6f\x08\xb8\x8b\x04\ +\xff\x6b\x10\x80\x01\x5a\x63\xe6\xe7\x81\xd1\x76\xeb\xef\x96\x49\ +\x23\xfc\x04\x78\x7c\x83\xcd\x44\x58\x20\xa0\x0c\xe9\xef\x3c\x4e\ +\xbe\x83\xcb\x89\xb0\xe0\xf1\x0d\x36\x8b\x16\x13\x32\xa0\xbc\xa5\ +\x3f\x8f\x88\xde\x8a\x8a\x48\x15\x22\x1a\x2a\x6f\xe9\xcf\x13\xa9\ +\x21\x64\x80\x9e\xa5\xdf\x07\x90\x23\x52\x43\x90\x9b\xa7\x1a\x52\ +\xe6\xda\x0f\x82\x42\x06\x84\xff\x84\xbf\x00\x38\x74\x48\x4b\x2a\ +\x1c\x9e\x6a\x48\x19\x21\x03\x56\xc7\xbb\xf6\x99\xb9\x5d\xa4\x86\ +\x08\xcc\xdc\xbe\x3a\xde\xb5\x2f\x52\x43\xf8\x15\x08\x8c\x76\x4c\ +\x30\xa3\x06\xa0\x55\x00\x2c\x5a\x2f\x01\x98\x81\x35\x66\xd4\x04\ +\x46\x3b\x26\x44\x8b\x39\xb2\x0e\x38\x9d\x8f\x85\xe7\x64\x19\xa8\ +\x41\x50\xb6\x00\xd9\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\ +\x28\x03\x64\x0b\x90\x8d\x32\x40\xb6\x00\xd9\x28\x03\x64\x0b\x90\ +\x8d\x32\xc0\x26\x76\x6c\x6e\x34\x34\x4c\xc7\xdd\x4e\x7b\xd9\xb1\ +\xd1\x7e\x6c\xcd\xb1\x31\x80\x76\xcc\xad\xcd\xdc\x60\xb1\xa3\xaa\ +\x32\x88\x8d\xf6\x6d\x6b\x4e\x8c\x01\x0c\x5e\x31\xb7\x0d\x9d\x6b\ +\x1d\xd6\x95\x31\x22\x2e\xa3\xce\xdc\x66\x20\x60\xcd\x89\x31\x40\ +\x03\xa6\xa2\x02\x8c\xde\x8a\xd6\x01\xb7\xe3\xea\xd2\x4c\x45\xeb\ +\x80\x9b\x40\x3d\xe6\x58\x4c\xdf\x60\x63\x40\x76\x61\x68\x16\x4c\ +\x5f\x4d\xa1\xfc\x88\xae\x4d\x5e\x25\x13\xfe\x6d\x96\x36\xed\x18\ +\x67\x60\x23\xbb\x30\x34\x6b\xcd\x4d\x6a\xbb\x3c\x83\xfd\xae\x88\ +\x36\x77\x99\xb7\xcb\x47\x5c\x46\xdd\xe9\x9d\x4f\x6d\xbb\xfc\x19\ +\x5e\xdf\xd0\x7f\x72\x60\x02\x20\x70\xf7\xf2\x48\x47\x9f\xdd\xb5\ +\xb8\xeb\x80\x95\xd1\x67\x7d\x04\xee\x4e\x9f\xac\x8c\xc0\xcc\xf4\ +\x62\x79\xa4\xfd\x75\xbc\x84\x84\x0e\x4d\x31\x8c\x81\x93\x33\x38\ +\x57\x87\x44\x0f\x4d\xa5\x70\x6c\x0e\x1e\x9c\xec\xba\xbe\x84\xc7\ +\xe6\xb0\xcd\x40\x20\x99\x63\x73\x0a\x85\xe2\x7a\xf3\x17\x37\xaf\ +\x1e\xac\x94\x31\x9b\x08\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x05\x08\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xba\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5b\x6c\x94\x45\x14\xc7\x7f\x67\xbe\xd2\x2a\x78\x21\x2d\x89\ +\x8b\x72\x6d\x40\xb1\x51\xa3\x74\xb7\xe8\x83\x37\x24\x90\x80\x5c\ +\x34\x56\x43\x34\x62\x08\x74\x4b\x61\x0b\x9a\xa0\xa0\xc4\xb5\x01\ +\xb1\xbe\x40\xba\x5d\x5a\x76\x6d\x62\x48\x78\xb2\x89\x0d\x54\x40\ +\x49\x34\xf0\xa4\xa5\xbb\x36\x3c\xd8\x60\x4c\x20\x60\x69\x4b\x84\ +\x26\x1a\x01\xbb\xec\xce\xf1\x61\xbb\xcb\xd7\xfb\x45\xdf\xf8\xbf\ +\x7d\x67\xce\x39\xff\xff\xcc\x37\x33\xe7\x0c\xdc\xe9\x90\xf1\x38\ +\xfb\x2a\x0e\xcc\xb4\xa9\xe4\x1a\x51\x59\x82\x30\x13\x61\x06\x8a\ +\x41\xb9\x8c\x48\x07\xc2\x69\x47\x6d\x53\x4b\x64\xeb\x6f\xff\xab\ +\x00\x6f\x79\xa8\x04\xa5\x1a\x78\x71\x8c\x59\x5b\x45\x75\x67\x6b\ +\x64\xeb\xf7\xff\x49\x40\x71\x59\xe4\x7e\x91\xde\x7a\x60\x6d\x9f\ +\xa9\x0b\xa4\x59\x95\x13\xea\xa4\xce\xeb\x3f\xa6\x6b\xd2\x64\x63\ +\x35\x81\xc7\x8a\x9d\x63\x0c\x4b\xd5\xb2\x1a\x61\x76\x5f\xfa\xe3\ +\x4e\x2a\xb5\xbe\xa5\x61\xdb\x95\x71\x0b\x58\x58\x71\x60\x9e\x49\ +\xda\xa3\x88\x3e\x0a\x74\x89\x10\x9c\xf2\xc0\xb5\x2f\x4f\x55\x55\ +\x25\x47\x9c\x52\x30\x68\xbc\xdd\x05\x6f\x80\xec\x01\x2d\x04\x2e\ +\x19\x58\x75\x26\x52\x79\x76\xcc\x02\xbc\x9b\xf6\x15\x62\x73\x5a\ +\x80\x69\xc0\x11\x27\x97\xb7\x5b\x6a\x2b\xff\x1a\x91\x78\x00\xe6\ +\x05\x42\x79\x53\x7b\xa9\x43\x58\x0f\x5c\x47\x78\x36\x76\xb0\xb2\ +\x6d\x54\x01\x8b\x02\xa1\xfb\x92\x09\x7e\x14\x28\x52\xb4\x26\xee\ +\xe9\x79\x8f\xaa\x2a\x3b\x1e\xf2\xdb\x50\xf1\xf9\x43\x3b\x14\xd9\ +\x0b\x74\xa8\xa6\x4a\xe2\xd1\x77\xbb\xdc\x1e\x39\x03\x43\x52\xbd\ +\x84\x45\x28\x02\x9a\x87\x22\x4f\x9f\x84\xd4\x06\x81\xe5\x02\xb3\ +\x14\x2c\xc8\x45\x55\x8e\x41\xb2\xa1\x3f\x81\x68\x6b\x44\xab\x7d\ +\xe5\xb5\x85\xaa\x6c\x30\xe2\x1c\x06\x5d\x02\xa2\x43\xae\x40\x89\ +\xbf\xd6\x6b\xd1\x56\x84\x3f\xd4\xe6\xcd\x8f\x47\xfd\x7f\x66\x07\ +\x83\x41\xe3\xeb\xce\xff\x40\x91\x8f\x81\xbb\x86\x99\xf2\x75\x55\ +\x3e\x8c\x47\x03\xb5\x6e\x92\xa2\xd2\x60\xee\xe4\xfc\x82\xb3\xc0\ +\x02\xd0\x15\xb1\xc8\xd6\xe3\x99\x31\xe3\x8e\xb6\xa2\x9f\x01\xa8\ +\xea\xee\x81\xe4\xde\xee\xfc\x43\x7d\x4b\x39\x1c\x39\xc0\x14\x11\ +\x6a\xbc\xfe\x50\x1d\x68\x76\x72\xed\x8d\x55\x09\x81\x8f\xfa\xe6\ +\x5c\xed\x1e\xcb\x0a\x28\x2e\xdb\x3f\x1d\xe5\x25\xa0\xe7\x66\x4f\ +\x4f\xc4\x9d\xd5\xd7\x5d\xb0\x0b\xe4\xad\x11\x88\x5d\x50\x40\xca\ +\x7d\xfe\x70\xa5\xdb\xda\x1a\x09\x34\x01\xe7\x80\xc7\x4b\xfc\xb5\ +\x4f\x0c\x12\x20\x98\x95\x80\xa0\x1c\x6b\x6f\xac\x4a\x64\xec\xde\ +\x4d\xfb\x0a\x15\x76\x8d\x8d\x3c\x9d\x29\x2d\x43\x3f\x7d\x6a\x4b\ +\xed\x83\x2e\xbb\xa2\x7a\x14\xc0\x8a\xbe\x32\x48\x00\x22\x2f\xa4\ +\x03\xe5\xdb\x7e\xe9\x34\xa7\x02\x98\x34\x76\x01\x59\x4c\x71\x12\ +\x6c\x74\x1b\xac\x31\xdf\xa5\x73\xca\xe2\xc1\x02\x60\x26\x80\x23\ +\x72\xc1\x1d\xa4\xca\x8a\x09\x90\xa7\x21\xfa\xb2\xfb\x33\x97\xe4\ +\x79\x00\x85\x19\x83\x04\x64\x8c\x46\x6e\xb9\x8e\x91\x0a\x50\x38\ +\x71\x01\x99\x2b\x39\x8d\xab\x93\x9c\x4c\xee\x87\x32\x1b\xd1\x0c\ +\x0a\x72\x23\xf8\x89\x8c\xea\x33\x12\x14\x67\x94\xdc\xee\x4d\xc8\ +\x65\x80\x84\x38\x9e\xac\x53\xfa\x12\xba\x38\x61\x01\xc8\x25\xf7\ +\xd7\xbd\xd6\x78\xd2\xba\xe8\xcc\x5c\x70\xb7\x67\xa7\xf2\x3b\x80\ +\xb1\xcc\x1d\x90\xe4\x38\x13\x85\x68\xbf\x58\x73\x2b\x55\x08\x20\ +\xd0\x91\xb5\xdd\x1e\xd5\x53\x00\x22\xb2\xcc\x1d\xe4\xa0\x07\x81\ +\x89\xd4\x82\x84\x49\x4a\x43\x3f\x01\x86\xa5\x00\x0a\x3f\x0c\x12\ +\x90\xca\x91\x66\x00\x55\x5d\x51\x5c\x16\xc9\x1e\xbb\x96\x48\x65\ +\x3b\x10\x1a\x37\xbd\xca\xde\x33\x0d\x81\x0b\x6e\x83\x55\x59\x05\ +\x60\x6c\xaa\x69\x90\x80\xb6\x70\xa0\x53\xd2\xca\xa6\x41\xef\x86\ +\x7e\xb9\x34\xef\xfd\xf1\xfd\x0a\x6d\x8c\x4d\xbf\xba\xdb\x6d\xf1\ +\x6e\x0a\xaf\x14\x28\x02\x7e\x69\xfd\x62\x5b\xb6\x37\xe8\xbf\xc3\ +\xad\xdd\x01\x20\x42\x70\x51\x20\x74\x5f\xc6\x1c\x8f\xfa\x6f\xa9\ +\xe6\xae\x51\xb4\x86\x91\x7f\x47\x12\x61\xef\xdc\x9e\xe9\x6b\xdd\ +\x55\xb4\xa8\x34\x98\xab\x36\x5d\x67\x04\x76\x0e\x5b\x0d\x01\x8a\ +\xfd\xa1\xc3\x02\x6f\x02\x47\x62\x9e\x6b\xaf\x0e\x2c\xc7\xde\xf2\ +\x9a\xc7\x50\x29\x07\x96\x03\xb3\x48\x5f\xfe\x17\x15\xfd\x46\x8c\ +\xd6\xc7\xea\xb7\xfd\x3a\x60\x35\xc4\x5b\x56\x5b\x8f\xe0\x07\x4e\ +\xc5\x22\x81\xc5\x23\x0b\x48\xf7\x81\x3f\x01\x0b\x80\x7d\x31\xcf\ +\xb5\xed\xc3\x35\x24\xa5\xa5\x5f\x39\x00\x8d\x8d\xaf\xa7\x86\x5e\ +\x10\x15\x6f\x79\x78\x3b\xaa\x9f\xa3\x74\xa6\x72\xc5\xd7\x16\x0e\ +\x74\xba\x3d\x86\x6c\xc9\x16\x56\x1c\x98\x67\x52\xa9\x16\x20\x1f\ +\xf8\xfa\x86\xe3\xac\x6b\xaf\xdb\xfc\xf7\xd0\x24\x43\xa3\xa8\x34\ +\x98\x7b\x77\x7e\x41\x58\x60\x23\x70\xc3\x20\xcf\x9f\x89\x04\x62\ +\x03\xfd\x86\x6d\x4a\x4b\x36\x86\x1f\xb6\xc6\x1e\x05\x1e\x51\xe4\ +\xb2\x40\xf0\x1e\xcf\xd5\x43\x63\x69\x4a\x7d\x57\xf2\x5f\xb3\x2a\ +\x7b\x04\xe6\x03\x1d\xaa\x66\x75\x3c\xba\xe5\xe7\xa1\xdc\x47\x6c\ +\xcb\x9f\x7c\x67\xff\xd4\x9c\x3c\x13\x05\x29\xed\x33\x75\x88\xd0\ +\x8c\x72\x02\x6b\xce\xe7\xd8\x44\xd7\xcd\x94\x58\x27\x37\xc7\xa3\ +\x86\xd9\xc6\xda\x65\x88\x59\xdd\xd7\x0d\x03\x9c\x14\xc7\x59\xd7\ +\x5a\xb7\xb9\x7b\x38\x8e\x31\x3d\x4c\x4a\xfc\xe1\x67\x2c\x5a\x0d\ +\xfa\xdc\x58\xfc\x81\x36\x55\x76\xc4\xa3\x95\x27\x47\x73\x1c\xd7\ +\xd3\xec\xe9\xf2\xfd\x73\x92\xd6\x59\x83\xb0\x04\xed\x7b\x9a\x81\ +\x03\x74\xa4\xaf\x57\x3d\x6d\xd5\x34\xc5\xa3\x81\x73\xe3\xc9\x7b\ +\x67\xe3\x5f\x5e\xef\xd7\x3d\x0b\xb2\x5f\x42\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa8\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x31\x15\x80\x30\x00\xc4\x50\x5a\x53\xf5\x81\x50\x7c\x60\x0a\ +\xba\xe2\xe0\x33\x24\xdb\x4d\x97\x97\x71\x20\xd6\xf5\xbc\xdf\x7d\ +\x9f\x73\x08\x8f\x29\x4e\xff\x44\x01\xb4\x80\xa6\x00\x5a\x40\x53\ +\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ +\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ +\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ +\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ +\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ +\x0d\x64\x41\x04\x80\xc9\xe4\x92\xad\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\xe2\x50\x80\x04\x84\x20\x3d\ +\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ +\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xc0\x07\x65\x23\x03\x3b\x58\x7b\xaf\x09\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x0a\x60\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x12\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x6b\x90\x14\xd5\x19\x3d\xe7\xce\xcc\xae\x83\x2c\x88\xf8\x48\ +\x4a\x28\x83\x31\x96\xae\x01\x4c\x70\x99\x5d\x82\x2b\x98\xa4\x54\ +\x82\x2c\xbb\x8b\x1b\x1f\xa5\xe2\x23\x2a\x26\xc6\xc4\x24\x26\x5a\ +\xa5\x8b\x46\x8d\xc6\x08\x96\x55\x06\xb5\x82\xa5\x22\x95\x64\x60\ +\x77\x00\x2d\x51\xab\xc4\xb5\x10\xd9\x5d\x5e\x6a\xf9\xc0\x32\x51\ +\x11\x42\x34\x2a\xca\x43\x79\xcc\xf4\x3d\xf9\xb1\xa0\xdd\x3d\x33\ +\xdd\x33\x3b\x33\x94\x95\x70\xaa\xe6\x47\x7f\xf7\xdc\xef\x9e\xfb\ +\x4d\xf7\xed\xfb\xf8\x1a\x38\x80\x03\x38\x80\xff\x67\x70\x7f\x34\ +\x72\x4a\x52\x87\xef\x89\xa1\x91\xd6\x8e\x94\xc1\xf1\x14\x8f\x11\ +\x70\x08\x80\x41\x00\x22\x00\xb6\xed\xfd\xbd\x27\xe8\x0d\xc0\xbc\ +\x8e\x28\x96\xf7\x4e\xe1\x3b\x95\xd6\x56\xb1\x00\x8c\x4b\xe9\x9b\ +\x8e\xb5\xd3\x41\x4e\x01\x30\xaa\x5f\x4e\x84\x77\x60\xb4\xd4\x5a\ +\xf3\xf0\xaa\x16\xac\x06\xa9\xf2\xaa\x2c\x77\x00\x24\x36\xa4\x70\ +\xba\x85\xae\x03\x30\xb1\x9c\xae\x09\xbc\x2a\x70\x56\xe6\x43\x3c\ +\xb6\xe6\x0a\xa6\xcb\xe8\xb7\x3c\x48\x74\x68\x22\x8c\xfe\x08\xe1\ +\xe4\x72\xf9\xcc\x83\x77\x05\xce\xec\x6d\xc6\xa3\xe5\xb8\x23\x4a\ +\x0e\x40\x62\xb1\x8e\x94\x63\xef\x26\x78\x7e\x00\xcd\x02\x58\x01\ +\xaa\x4b\xd6\xac\x37\x11\xfc\x53\x19\x6c\xb1\x16\xdb\x0f\x02\x9c\ +\x9d\x06\x35\x31\x60\xb0\x0c\x46\x08\x38\x0e\x50\x03\x80\x1f\x02\ +\x88\x07\xf8\x5c\x6e\x2d\x67\xac\x9a\xc6\xd7\x4a\xd1\x5f\x52\x00\ +\x1a\x52\x1a\x6b\xa5\x45\x00\xbe\x9e\xa3\x78\x3b\xa8\x27\x29\xf3\ +\xb8\x05\x9e\xea\x6d\xe1\xc7\x45\xf9\x4e\x2a\xee\x44\x70\x1a\x69\ +\xcf\x02\x38\x25\x4f\x1b\xbb\x44\x5e\xd2\xdb\xcc\xbf\xf6\x47\x3f\ +\x50\x42\x00\xc6\x76\xe8\x3c\x50\x0f\x11\xa8\xf6\x8b\xa2\x74\x6f\ +\xb4\xda\xdc\xf1\xc2\x64\x7e\xd2\x5f\xff\x6e\xd4\x26\x55\x55\x13\ +\xc5\x4f\x00\xdd\x04\xe0\x08\x7f\xb9\xa0\xdb\x7a\x5f\x36\x37\xe1\ +\x66\xda\x62\x7d\x17\x1f\x80\x76\x99\xc4\x28\x7b\x2b\xc8\xeb\x7d\ +\x25\x56\xd0\x43\x94\xb9\xb9\xa7\x95\x9b\x8a\xf6\x5b\x00\xbe\xb7\ +\x58\x35\x69\x8b\x6b\x29\xfd\x1a\xc0\x40\x4f\xa1\xb0\x28\xee\xf0\ +\x82\xae\x36\xee\x28\xc6\x67\x71\x01\x68\x97\x49\x8c\xb6\xf3\x01\ +\x9e\xe3\x2b\xd9\x6c\xc8\xe6\x95\xcd\xec\x2d\xca\x5f\x3f\x91\xe8\ +\xd0\x30\x18\xa5\xfc\x03\xae\x88\x75\xac\xe6\x84\x9e\x49\xdc\x56\ +\xa8\x2f\x53\x54\xc3\x27\xd9\x99\x39\x3a\xdf\x9d\x11\x4f\xde\x5f\ +\x9d\x07\x80\x9e\x56\x6e\x32\x69\x36\x0a\x9a\xef\xb6\x53\xf8\x0e\ +\x77\x69\xfe\xd9\x49\x45\x0a\xf5\x55\x70\x00\xea\x3b\xf4\x63\x88\ +\x37\x7a\x1a\x84\x1e\x89\x6f\xe5\xc4\x35\xad\xfc\x77\xa1\x7e\xca\ +\x85\x95\x6d\xdc\xd9\xdb\x6c\x2e\x10\xf9\x5b\x00\x5f\xbc\x0e\x05\ +\x4c\xde\x18\xb1\xb7\x17\xea\xa7\xa0\x47\x60\xec\x42\x9d\x4c\xa3\ +\xe5\x00\x0e\xfa\xd2\xaa\xc7\x7a\x9a\xcd\x85\x95\x98\x9d\x15\x8b\ +\x44\x87\x7e\x01\x6a\xb6\xdb\x26\xf0\xa2\xde\x16\x3e\x1a\x56\x37\ +\x34\x00\x63\x3b\x35\x94\xd0\xcb\x00\x8e\x72\x99\x7b\xe3\x5b\x79\ +\x6a\xd7\xc5\xdc\x55\x8c\xd0\xfa\x4e\x9d\x60\x85\x66\x1a\x3b\x0a\ +\xe2\x30\x00\xc3\x00\x38\x00\x36\x91\xda\x24\x6b\xd6\x2a\x86\xce\ +\xa2\xd7\x00\x12\x13\x29\x3b\x17\xe0\xc5\x2e\xeb\x1e\x8a\x0d\xdd\ +\xad\x5c\x1b\x54\x35\x34\x00\x89\x4e\x67\x2e\xc0\x4b\x5c\xa6\xcd\ +\xd1\x08\xeb\x56\x34\x71\x73\x21\xda\x6a\x93\xaa\xaa\x89\x61\x06\ +\xa4\x2b\x01\x1c\x5f\x48\x1d\x11\xeb\x0c\x78\xef\xf0\x34\xe6\x2d\ +\x68\xa3\x53\x48\x9d\x33\x9f\x54\xf5\xc7\x3b\xb5\x8c\xc4\x38\x97\ +\x79\x6d\x7c\x08\x13\x5d\x13\x99\xc9\x57\x2f\x30\x00\x89\x4e\x8d\ +\x07\xb4\xdc\xad\x0d\xe2\xb8\x9e\x56\x76\x17\x22\x6a\x6c\x4a\x53\ +\x69\x75\x17\x88\x63\x0b\xe1\xe7\xc0\x4b\x02\x7f\xd5\xdb\xc2\x65\ +\x85\x90\x13\x8b\x75\x24\x1c\xbd\x0a\xe0\xb0\x7d\x36\x82\xd7\x74\ +\xb7\xf0\xde\x7c\x75\xf2\x0f\x82\x12\x01\xfd\xc1\x67\x9c\x5f\x48\ +\xe7\xc7\x3c\xa0\x58\x22\xe5\xdc\x47\x29\x55\x42\xe7\x01\xe0\x24\ +\x42\xcf\xd6\x77\x38\x33\xd1\xae\xd0\x01\xbb\xa7\x89\x1f\x40\xbc\ +\xcd\xa3\x18\xba\x71\xd4\xd3\x3a\x38\x5f\x9d\xbc\x4e\x1b\x52\x68\ +\x04\x30\xde\x65\x4a\x3b\xd6\xb4\x87\x89\x18\xff\x84\x86\xc4\x0e\ +\xd7\x52\x88\x57\x85\x71\x0b\x85\xc8\xf6\xc4\x68\xfd\x7d\xcc\x12\ +\x0d\x08\xe3\xc6\xb7\xe1\x7e\x12\xef\xb9\x4c\x87\x0d\xf8\x0c\x57\ +\xe4\xe3\xe7\x0d\x80\x85\x7e\xe3\xbe\xa6\xf4\xc0\xea\x69\x7c\x3b\ +\xa8\xf1\xda\xa4\xaa\xd2\x7b\xb4\x48\xc0\xf7\xc3\x84\xf6\x03\xd3\ +\xa2\x69\x3d\x1a\x76\x27\xf4\x0d\xcc\xf4\xfc\x51\x82\xae\xcd\x37\ +\x37\xc8\xe9\xac\x2e\xa9\xaf\x01\x38\xc3\x65\x4a\x2b\x6a\x6e\x0d\ +\x94\x27\x71\x60\xd4\xde\x07\xa0\x31\x90\x57\x0a\x88\xd6\xc4\x68\ +\x1b\x7a\x17\x0e\x4f\x63\x1e\x80\xb7\x5c\xa6\xa3\x36\x18\xfc\x20\ +\x17\x37\x67\x00\x22\x51\x9c\x87\xbe\xad\xaa\x7d\x0d\x2f\xeb\x69\ +\xe2\x07\x41\x8d\x26\x16\xe1\x7c\x82\x97\x85\x89\x2b\x1d\xbc\xa9\ +\x7e\xa1\x72\x76\x66\x1f\x16\xb4\xd1\x21\xb4\xc0\x53\xcb\xd8\x8b\ +\x72\x71\x73\x06\x40\xd0\x59\x1e\x83\xe5\x92\xa0\x06\xc7\x2c\xd1\ +\x00\x48\x77\x04\x71\xca\x09\x19\xcd\x0a\x9d\xee\x1a\xe3\xd3\xcc\ +\x49\xb9\xea\x64\x05\x60\xef\x88\xe9\x7e\x97\x22\xe3\xe0\x89\xa0\ +\xb6\x62\x0e\xae\x85\x77\xa2\x54\x69\x8c\xdc\x10\xc3\xf4\x20\x42\ +\xf7\x3a\xac\x02\xe0\xbe\x6b\x07\x6f\x8a\x61\x8c\x9f\x97\x15\x80\ +\xea\xcf\x51\x0f\xa0\xca\x65\x7a\x69\x4d\x1b\xdf\xf3\xf3\xf6\xe1\ +\xec\xa4\x22\x56\xfa\x79\xa8\xe4\x32\x83\xd2\x35\x81\x84\x9b\x69\ +\x29\x79\xfe\x38\x29\x7b\x9f\x32\x2b\x00\x06\xf8\xb6\xa7\x12\x3d\ +\x13\xa1\x2c\x6c\x8c\xe1\x14\x02\x87\x07\x8a\xa9\x0c\x46\x26\x16\ +\xea\x5b\x41\x04\x4b\xe3\xd1\x2e\xda\x13\xfd\x9c\xec\x31\x40\xf6\ +\x04\x0f\xc1\x9a\xb7\xb2\x38\x6e\xba\xec\xb4\x40\x99\x95\x84\x41\ +\x6b\x50\x71\xc4\xc0\xa7\x9d\x27\xf8\x39\xd9\x01\x20\xbf\xe1\xbe\ +\xb4\x40\xe0\xbb\x1f\x62\xa5\x77\x81\x83\x1a\xcf\x7a\xa6\xdd\xc8\ +\xec\xf1\x69\x17\x46\xf8\x39\x59\x01\x90\x45\x8d\x8f\xf0\x69\xa0\ +\x06\xee\xd7\xc1\xcf\x8f\x61\x41\x85\x07\x7f\x96\xa5\xbd\xc6\xcf\ +\xc9\x0a\x00\xe9\x25\x59\x22\xff\x1e\x5b\xdf\xac\x2c\xd7\x6e\xed\ +\xfe\x42\x60\x00\xba\xa6\x63\x37\x00\xf7\x4a\xb0\xaa\x36\x29\xf7\ +\x00\x9f\x23\x00\xbe\x15\x22\x2d\xf2\x6e\x78\x4c\x98\x00\x93\xcb\ +\xc7\x7e\x44\xac\x54\x07\xd9\x8f\x00\xb0\xdd\x7d\xed\xbf\x23\xdc\ +\xd8\xbb\xce\x0e\x9c\x21\x56\x18\x81\xbb\xcf\x13\x1e\x46\x35\x80\ +\xa8\xcb\xb4\xe7\xf5\x36\xee\x71\x73\x72\x0c\x82\xf0\xec\xa8\xda\ +\xbe\x53\xdc\x20\xfc\x2b\xa4\xbc\x92\x08\x0c\xc0\xce\x43\x31\xd8\ +\x67\xda\xee\xe7\x64\x07\xc0\x6a\x83\x8f\x91\x35\x72\xba\x41\xe8\ +\xd5\xa0\xf2\x4a\x42\x21\x6d\xcb\xc1\x31\x3e\xd3\xbb\x7e\x4e\x8e\ +\xe7\xd7\xbc\xe1\xbe\xa2\x6c\xe0\x64\x03\x32\x9d\x81\xe5\x15\x84\ +\x09\x6f\xdb\xa3\x5d\xd0\xfa\x2c\x1f\x59\x55\x08\xdf\x61\x23\xc7\ +\x67\x71\x5c\x38\x68\x1b\x9e\x01\x02\xde\x14\x95\xc3\x86\xee\x16\ +\xac\x0b\x22\x10\x76\xbc\xf7\xda\x64\xdd\x31\x59\x01\x88\x67\xb0\ +\x12\x80\xfb\xfc\xfd\xbb\x89\x0e\xe5\x7d\xdd\x74\x5d\xcc\x5d\x94\ +\x1e\x0e\x95\x5b\x66\x48\x7c\x30\x70\x4b\xbe\x5d\x06\xe0\x64\x6f\ +\x25\x74\xf9\x69\x59\x01\xd8\x7b\xb6\xb6\xd2\x53\x8f\x98\xec\xe7\ +\xb9\x11\x73\xcc\x2d\x00\xb6\x06\x2a\x2e\x2f\x36\x46\x1c\xcc\x0e\ +\x22\xd4\x8d\xc2\x18\x78\xe7\x28\xdb\xe2\x87\x62\xb5\x9f\x97\x67\ +\x3f\x80\x9e\x55\x14\xa1\x29\x41\x8d\x2d\x6f\xe3\x87\x00\x83\x77\ +\x8c\xca\x09\xf2\x86\x95\x6d\xdc\x19\x44\x31\xb0\x1e\xcd\x82\x9e\ +\xca\xb5\x3d\x9e\x33\x00\xb1\x08\xe6\xa3\x2f\xa9\x61\x6f\x65\x9c\ +\x76\x4a\x52\x81\x2b\xbe\xf8\x10\xdc\x03\xe2\xe9\x40\xe1\xe5\x00\ +\x35\xaf\x67\x2a\xe6\x07\x72\xda\x65\x40\x7a\x16\x69\xb4\xe6\x91\ +\x5c\xd4\x9c\x01\x58\xd1\xc4\xcd\x02\x9e\xf9\xa2\x32\x50\x9d\x8e\ +\x5a\xff\x71\xb8\x07\x5d\x13\x99\xd9\xdd\x77\x70\xfa\x66\xa0\xb8\ +\xd2\xd0\x1d\xff\xd4\x5c\x1e\x76\x1c\x57\x3f\x1a\xe7\xc2\x7b\x08\ +\xf3\x7e\x7c\xe8\x97\xfd\x71\x23\xef\x34\x56\xe4\x9f\x3c\xd7\xe0\ +\x4f\xc7\x75\xe8\xe8\xa0\x86\x5f\x6a\xe6\xa7\x8e\xe5\x24\x54\x22\ +\x08\xc4\x6a\x44\x38\x35\xec\x38\xae\x36\xa9\x2a\x49\xbf\x77\xdb\ +\x44\xce\xce\x77\x3a\x94\x37\x00\xab\xa6\x62\x19\xbc\x83\x61\x95\ +\x03\x3b\x33\x4c\xe7\xea\x69\x7c\x7b\x37\x59\x0f\xe4\x8e\x78\xff\ +\xa0\xbf\x99\x34\x1b\xc3\x36\x66\x01\x60\x60\x0c\x97\x83\x9e\xc9\ +\xdb\x96\x98\xc1\x9c\x7c\xfc\xfc\x0b\x19\x52\x24\x6f\xf0\xd9\x2e\ +\x4c\xa4\x82\xd7\xe0\x40\xdf\x9d\x10\x1f\xc2\x1f\x11\xfc\x1d\x72\ +\x4c\x3f\x8b\xc0\x47\x02\x67\xf4\x34\x9b\xf3\xc2\x06\x3d\x00\x18\ +\xb3\x44\x87\x51\xf2\x1c\xe1\x43\xbc\x7d\x45\x13\xf3\x6a\x08\x5c\ +\xc9\x75\x37\xb3\x0b\xd4\x3c\x0f\x5f\x4a\x25\x16\xeb\xc8\x30\x31\ +\x5d\x13\x99\xe9\x6e\xe1\x9d\x11\xf0\x58\x49\x73\x00\x7c\x1e\x56\ +\xc7\x85\xad\x80\xee\xc8\x64\x78\x6c\x6f\x0b\xef\x2f\xe4\x08\xbe\ +\x36\xa9\xaa\x48\x46\x0b\xe1\xcd\x21\x7a\x25\xf3\x11\xf2\x9e\x0b\ +\x02\x05\x9c\x0e\x8f\xeb\xd4\x11\x0e\xf4\x0a\x80\x2f\x3a\x2d\xe1\ +\xc5\xa1\x71\x9e\xb6\x74\x12\x77\x87\xd5\xdf\x87\x31\x4b\x34\x20\ +\x96\xc1\x19\xa0\x6d\x95\x38\x12\x7d\xbb\xc8\x87\x02\x80\x80\x0f\ +\x09\x6c\x06\xb4\x96\x34\x0b\xb6\xa5\xf1\xac\x7f\xd5\x16\x86\xfa\ +\x4e\x67\x8e\xc0\x2b\x5d\xa6\xb4\x21\xc7\x87\x65\xae\x14\x94\x20\ +\x91\xe8\x50\xbd\xa8\x2e\x6f\x46\x98\x1e\xea\x69\x36\x97\x95\x92\ +\x20\xd1\x90\x54\xfc\x90\x81\xb0\xc5\x04\x32\x8f\xbe\xab\x40\xdd\ +\xe7\xb6\x89\xbc\xac\xb7\x99\x73\xc3\xea\x16\x9c\x24\x95\xe8\xd0\ +\x05\xa0\xbc\x19\x17\xd2\x83\xdb\x1d\x73\x75\xb1\xff\x56\xd9\x20\ +\xb1\x3e\x85\xab\x05\xcd\x86\xfb\x71\xa6\xee\xe9\x69\x8e\xfc\xb2\ +\x10\x17\x45\x65\x89\xd5\x77\x38\x77\x8a\xbc\xce\xa3\x01\x78\xde\ +\x89\x72\xda\x9a\x29\xfc\xa8\x18\x5f\xa5\xa2\x36\xa9\xaa\x41\x11\ +\xfb\x67\x91\x97\x7a\x0a\x88\xa7\xe3\x87\x70\x72\x50\x52\x84\x1b\ +\x45\x6d\x67\x0d\x77\xcc\x0d\x04\x52\xde\xf6\x70\x6a\x34\xa3\x55\ +\x0d\x8b\x34\xb2\x18\x5f\xa5\x60\x5c\xa7\x8e\xa8\x89\xea\xd9\xac\ +\xce\x03\xaf\xed\x06\xcf\x29\xb4\xf3\x40\x3f\x12\x25\xcf\x4e\x2a\ +\xb2\x31\x6a\xef\x12\xe8\xbf\xc5\xd2\x80\xe6\x44\x60\x6e\x7b\xb1\ +\x85\xff\x29\xd6\x6f\x21\x68\x48\x2a\xee\x44\xf1\x33\x42\xd7\x03\ +\x18\xe2\x2b\x5e\x9a\xc9\xf0\xdc\x35\x6d\x2c\x6a\x51\xd6\xff\x54\ +\xd9\x94\x2e\x65\xdf\xeb\xcd\xbf\x31\xb9\x83\xd2\xdd\x8a\x9b\x59\ +\xc5\x24\x2c\x06\x61\xc2\x73\x8a\xee\xda\x82\xe9\xa2\x66\x22\xc7\ +\x19\xa4\xa0\x59\x47\x67\xcc\x75\x85\xe6\x13\xb9\x51\x52\xb2\x74\ +\x5d\x87\x1a\x0d\xd5\x09\x60\x68\x8e\xe2\x4f\x00\x3d\x0e\x99\xc7\ +\x11\xc7\x33\xc5\x06\xa3\x36\xa9\xaa\x41\x06\x8d\x32\xf6\x2c\x80\ +\x4d\x00\x72\x4d\xc3\xd3\x22\x67\x14\x32\xda\xe7\x43\xc9\xe9\xf2\ +\x75\x8b\x34\xdc\x58\xdd\x03\xa0\x25\x80\x96\x06\xf1\xbc\x2c\x9f\ +\xa3\xc1\x9b\x12\xfe\x21\x83\x2d\xd5\x51\xec\x48\x1b\x38\x66\x07\ +\x6a\x6c\x15\x06\xcb\xc1\x08\x10\xc7\x11\xb6\x01\xe0\xe9\xe8\xfb\ +\xa4\x26\x9f\xf0\x55\x22\x67\xf4\x34\x73\x4d\x29\xfa\xcb\xf6\xc1\ +\x44\x7d\x4a\x67\x4a\xba\x13\x40\xa5\x07\xc3\xcd\x12\x6f\x39\xda\ +\xc1\x5f\xfa\x73\xcb\xfb\x51\xde\x4f\x66\xda\x65\xc6\x8e\x42\x93\ +\xa1\xae\x17\x50\x57\x56\xdf\xc0\xdb\x00\x67\xc5\xb7\x62\x6e\xb1\ +\x09\x9a\x41\xa8\xd8\x47\x53\x75\x0b\x75\xa2\x31\x76\xfa\xde\x8f\ +\x1d\x8e\xeb\xa7\x9b\xf7\x01\x3d\x69\x65\x1e\x59\xf5\x0a\x5e\xe8\ +\xcf\xf7\x00\x61\xd8\x2f\x9f\xcd\xd5\x2d\xd2\x70\x5a\x4c\x34\xb2\ +\x27\x8a\x3c\x1e\xc0\x08\x12\x83\x25\x0c\x42\xdf\xc9\xcd\x56\xf4\ +\x7d\x36\xb7\x11\xd0\x7a\xd2\xac\x17\xf1\x7c\x4f\x13\xde\xf8\x2a\ +\xe4\x22\x1f\xc0\x01\x1c\xc0\xff\x2e\xfe\x0b\x91\x5a\xc0\x8b\x79\ +\xe5\x16\x6d\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x01\x23\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd5\x49\x44\x41\x54\x78\x9c\xed\ +\xdb\x31\x11\xc2\x40\x00\x05\xd1\x0d\x22\xa2\x08\x05\x0c\x0e\xa0\ +\x41\x11\x0d\x12\x18\x14\xa0\x26\x15\x2e\x42\x41\xe8\x52\x67\x99\ +\x61\x5f\x75\xdd\xfd\xdb\xfe\x20\xc9\x3f\x1b\xac\x8b\xf7\xc7\xf3\ +\x61\x98\xb9\x02\xcc\x03\x97\xe7\xfd\xf6\x30\x76\xec\x8c\x4b\x01\ +\x96\xc7\x8f\xc0\xf8\x0d\x61\xd0\x02\xf0\x79\xfc\xda\x79\x53\x66\ +\x80\x9f\x50\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\x02\ +\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\x2b\ +\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\xb6\ +\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\x60\ +\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xad\x00\xf6\x00\x5b\x01\xec\x01\ +\xb6\x02\xd8\x03\x6c\x05\xb0\x07\xd8\x0a\x60\x0f\xb0\x15\xc0\x1e\ +\x60\x2b\x80\x3d\xc0\x56\x00\x7b\x80\xcd\xfb\x34\x05\xaf\xb5\xf3\ +\xd6\xb4\x00\x33\x9c\x80\x09\x98\x96\x73\x92\x6c\xee\x0d\xbb\x93\ +\x11\x50\xe7\xe7\xb7\x79\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xcd\xa1\x15\x00\x10\x00\x00\xd1\x63\x29\x55\x31\x80\x45\x4d\xe0\ +\x3d\xd9\x52\x9e\xa4\x8a\x8a\xfb\xe9\xda\x81\x24\x49\xbf\x0b\x27\ +\x52\x5b\x03\xc8\x8f\xae\x7d\xd6\x58\x00\xe2\x93\xa1\x24\x49\xd2\ +\xc5\x06\x65\xbc\x05\x04\xc9\x39\x8e\xf8\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xd0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x82\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5d\x88\xd4\x65\x18\xc5\x7f\xe7\x9d\xf1\x2b\xa9\x34\x24\xac\ +\x5c\xab\x25\xfb\x58\x2a\x05\x75\x56\x89\x3e\x34\x51\xd2\x74\x77\ +\x6b\xdb\x88\x22\x41\x14\xa5\x8b\x2e\x82\x4a\x4b\xda\xa2\x32\xbb\ +\x09\xac\xd0\x8a\x20\x04\xaf\xcc\x76\x56\xcd\xed\x03\x0a\xbd\x08\ +\x9d\x5d\xcd\x36\x48\x8a\xc0\xd0\x56\xb7\x0c\x04\x25\xd3\x6c\xe6\ +\x3d\x5d\xcc\xec\x38\xe3\xce\xae\x3b\xd6\x9d\xe7\x66\xf8\x3f\xff\ +\xe7\x3d\xe7\xbc\x5f\xff\xe7\x19\xb8\xd4\xa1\x6a\x92\xa7\xb7\xbb\ +\x26\x91\xa3\xd1\xf2\x1c\x8b\x1a\xcc\x04\x41\x00\x8e\x20\x7a\x8c\ +\x76\x29\x47\x3a\xd3\xac\x9f\xff\x57\x03\x33\xd3\x4e\x45\x7b\x2d\ +\x30\x6b\x88\xa4\x5d\x39\x69\x55\x57\x93\xbe\xfa\x4f\x06\xa6\x6e\ +\xf6\x95\xc9\x64\xdc\x00\x7a\xac\x10\xea\xc5\xde\xee\x10\x3e\x53\ +\x8e\x83\xc3\x23\xbd\x7f\x27\x89\x8e\x8c\x97\xb8\x41\x8a\x73\x41\ +\x0d\xc0\xf5\x05\xf6\x0e\x82\x96\x64\x1a\xf4\x7b\xd5\x06\x66\x6e\ +\xf5\x4d\x31\xe7\x6d\xc0\x6d\x40\xaf\x50\xeb\xc8\xb1\x7c\xb4\x73\ +\x96\xb2\x83\x4e\xa9\xd5\x21\x35\x85\x47\x65\xbf\x06\xd4\x4a\x1c\ +\x8e\xd6\xa2\xce\x87\xd4\x3d\x64\x03\xd3\xb6\xb8\x36\x11\x9c\x01\ +\xc6\x01\x5b\x19\xa9\x27\x33\xf3\x75\x72\x50\xe1\xf3\xf0\x40\x87\ +\x47\x1c\x3f\x13\xd7\x83\x96\x60\x4e\x05\xeb\xee\xdd\xcd\xda\x7f\ +\x41\x03\xf5\x1d\xbe\x82\x33\xde\x0d\xd4\x81\xd7\x65\xba\xc3\x33\ +\xbc\xa2\x58\x8d\x78\x11\xb6\xea\xdb\x59\x89\xbd\x06\xe8\xc9\x5a\ +\xa9\x7d\x0f\xab\xb7\x34\x25\xd9\x6f\xd0\xdf\xf1\x5d\x50\x9d\xcd\ +\xf6\xce\xef\xfb\x8b\x4f\x6f\x77\x4d\x88\x71\x29\xd2\x7c\xcc\x44\ +\x20\x62\x0e\x81\x76\x64\xe1\xc3\x32\x01\xc9\x19\x7b\x6d\x2a\xed\ +\x5a\xa1\xa5\x49\x79\x13\xf6\x1c\x24\x57\x5c\x81\xd4\x16\x4f\x53\ +\x70\x97\xe1\x8f\x5c\x56\x93\xf6\xb5\xe8\x44\xf1\x65\xab\x43\xfd\ +\x14\x9e\xc7\x7e\x09\x18\x59\x79\xc6\x9c\x92\xf4\xc2\x9e\x26\xde\ +\x29\x15\xa9\xdb\xec\xe1\x97\x27\xdd\x0d\xdc\x4a\xd4\x82\x4c\xb3\ +\x3a\xfa\xde\x85\xd2\xf1\x4a\xf8\x0d\x80\x60\xbd\xda\x4f\x7c\x72\ +\xdc\x58\x58\xca\xca\xe2\xf9\xe9\x8c\x36\x5e\x37\x23\x1d\xd7\x63\ +\x17\x27\x77\xa0\x45\x67\x85\x5e\xcc\x2b\x7a\x6d\xe9\xbb\xa2\x81\ +\xa9\x9f\xf8\x1a\xcc\xfd\xc0\xf1\x93\x39\xde\x2f\xe5\xad\x9f\xcc\ +\x6a\xd0\x13\x98\x21\xc1\x68\x45\x7d\x3b\x4f\x97\xc6\xf6\x34\x91\ +\x06\x7e\x04\xee\x48\xa5\xb9\xb3\x9f\x81\x64\x60\x21\x20\xe4\x1d\ +\x07\x5a\x74\xb6\x2f\x3e\x6d\x8b\x6b\xc1\xab\x0b\x33\x1c\x3a\xa2\ +\x5f\xbf\x6b\xab\xaf\x2d\x3e\x4b\x96\xbd\x0d\x20\x38\x36\xf5\x33\ +\x80\xe3\x7d\xf9\x9f\xf0\x79\x29\x4f\x22\x11\x9f\x02\x86\x55\x21\ +\x5d\x10\x64\xf4\x3f\x91\x65\x65\x9e\x14\xbe\x00\xb0\x34\xbb\xbf\ +\x01\x54\x53\x18\xf8\x4b\x19\x91\xb5\xa0\x6a\xf1\xa2\x07\x3f\x58\ +\xfa\x1c\xc4\xc1\x3c\x27\x13\x2a\x18\xc8\x07\x83\x38\x77\x8d\xf2\ +\x87\xa5\xf6\x62\x0d\xd8\x85\x4f\x72\x01\x63\x47\x14\xb8\xc5\x75\ +\x7d\x07\x31\x54\x18\x77\x0e\x2f\xa3\x0b\xe6\x0c\x02\x41\xe2\x02\ +\xdc\x65\xe4\x47\x00\x1c\x19\x5f\x8c\xbc\xa2\x68\x38\x74\xb1\x06\ +\x80\xc3\xa5\x0f\x27\x4e\x17\xb9\x8f\xf6\x7d\xe0\x4a\x0c\xf8\x57\ +\x00\x07\x6e\x2c\xa3\x90\x3b\xb8\x48\x88\xf2\xb1\xb9\x73\xdb\xd9\ +\xd3\x17\x2b\x1a\xb0\xc3\x4e\x80\xe0\x38\xaf\x8c\x44\xe1\x3d\xe0\ +\x62\x6a\xc1\xd9\x98\x0c\x1f\x96\x3b\x8a\x73\x0b\x6a\x5f\xf7\x33\ +\x30\x2c\xc9\x76\x00\xa3\x05\x53\xdf\x77\xf1\xda\x65\x1a\x75\x00\ +\xf9\xed\x6a\xd5\x2d\xad\xe9\x5c\xa4\x73\x37\xca\x16\x68\x11\x40\ +\x54\x48\xf7\x33\xf0\x4d\x83\x8e\x02\x5f\x03\xe3\x86\x5d\xcd\xd2\ +\x52\xb2\xec\xb1\xf0\x1c\xa2\x8a\xad\xf0\xc7\x9d\xdf\xf1\x6a\x69\ +\x64\x46\x1b\x0b\x81\x3a\xe0\x87\xae\x46\x8a\xbd\x41\xd9\x09\x8f\ +\xd6\xca\xbc\x59\xb7\xd6\x77\xf8\x8a\xbe\xf8\xbe\xe5\xfa\x27\x7b\ +\x4c\x8d\xe0\x75\x0c\xbe\x1d\x59\xe1\x35\x13\xb3\xe1\xb1\xd2\x2a\ +\x5a\xb7\xd9\xc3\xad\x7c\x9d\x51\xd0\xaa\x01\xab\x21\x40\xaa\x2d\ +\xb7\x49\xe8\x71\x60\x6b\xa6\x5b\x0f\x9d\x5f\x8e\xa7\xb5\xf9\xf6\ +\x04\x71\x05\xd6\x7c\xc4\x44\xc0\x86\x43\xc2\x9f\xe6\x12\x61\xc3\ +\xde\x06\xfd\x54\xbe\x18\x56\x7d\x3a\x6e\x00\x2d\x07\x76\x66\x9a\ +\x34\x7b\x50\x03\xf9\x3e\xd0\x7b\x80\x5b\x8d\xdf\xea\xec\x0e\xcf\ +\x0e\xd4\x90\x3c\xb2\xd9\x09\x80\x8f\x5b\x94\xab\xb8\x1e\xb6\x52\ +\xed\x3c\x2b\xfb\x4d\xe0\x68\x32\xa1\xe9\x85\xad\x2e\xa2\x62\x79\ +\x29\xf4\x83\x19\xe0\x2a\xa0\x6d\x54\x56\x8b\x77\xb6\xe8\xcf\x8a\ +\x22\x03\x20\xdf\x03\xc4\x77\x41\xcb\x80\xbf\x1c\x75\x6f\x67\xb3\ +\xf6\x9e\x9f\x37\x60\x7d\x4b\xb5\xf9\x66\xe1\x6d\xc0\x2d\xc0\x11\ +\x4b\xad\x97\x8d\x61\xe3\x50\x9a\xd2\x19\x53\x68\x76\xbe\x29\x9d\ +\x04\xf4\xc8\x6a\xd8\xf3\xb0\xbe\xad\x94\x3e\x68\x81\x9d\x92\xf6\ +\x98\x11\x8e\x1f\x80\x1e\x29\x84\x7a\x6c\x6f\x0f\x89\xf0\x59\x2e\ +\xcb\xc1\x64\xa4\xf7\xf4\x30\xe2\xa8\x1c\xe3\x73\x70\x7d\x08\x71\ +\x9e\xf3\x6d\x79\xdf\x07\xe7\xcb\x98\xd5\xe2\xae\x16\xfd\x36\x90\ +\xc6\x90\x2a\x7c\xaa\xcd\x33\x85\xd7\x02\xf7\x0c\x25\xdf\x62\xbf\ +\xd0\xca\x4c\x93\xbe\xbc\x50\x6e\x55\x7f\xcd\x66\xa4\x7d\x83\x23\ +\x8d\xc8\x73\x80\x1a\xf2\x15\x34\x01\xf4\x20\x7a\x40\xbb\x42\x8e\ +\xf4\xee\x66\xfd\x58\x0d\xef\xa5\x8d\x7f\x01\x53\xeb\xdb\x78\xb8\ +\xf8\xe0\x36\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3e\x49\x44\x41\x54\x58\x85\xed\ +\xd3\xb1\x11\x00\x10\x00\x04\xc1\xa3\x32\x89\x0a\xb4\xa0\x2c\x2d\ +\x68\xc0\x98\xd1\x9a\x48\x2a\x24\xb9\x8d\x3e\xbb\xe8\x41\x92\xf4\ +\x59\x38\x23\x97\xba\x80\xf4\x28\x3a\x47\x6f\x19\x20\xbe\x08\x4a\ +\x37\xbe\x40\x92\xa4\xef\x36\xf1\x29\x0a\x07\x7b\xbe\x69\xcc\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0a\x8e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\x40\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x8c\x1c\x65\x19\xff\x3d\xb3\xb7\xd7\xbb\x72\xd7\x03\x29\ +\x07\xf5\x76\x76\x76\xaf\x3d\x02\xa1\x25\x2a\x05\x81\xd4\x13\x50\ +\x03\x12\x28\x20\x24\xf2\x11\xa4\x02\x22\xa0\x88\xf2\x65\xd0\x00\ +\x15\x21\xf2\x21\x85\x90\xd4\x02\xb1\x0d\x50\x1a\x31\x28\x10\x31\ +\x7c\x34\xa1\x94\x54\x85\x40\x2d\x88\x8b\x94\x5c\xbd\xdd\xf9\xd8\ +\xeb\x51\xca\x47\x3f\xb4\xd7\xdd\xd9\xf7\xe7\x1f\x77\x6d\x67\x66\ +\x67\x67\x76\xef\xf6\x2e\x46\xfb\xfb\x6f\x9e\xf7\xf7\x7c\xcc\x33\ +\xef\xce\xbc\xef\xf3\xbc\x0b\xec\xc7\x7e\xec\xc7\xff\x33\x64\x2a\ +\x9c\x0c\x6c\xde\x7c\x48\x72\xb7\xdb\x4f\xc1\x3c\x0d\x72\x84\x02\ +\x7b\x01\x1c\x28\x90\x19\x00\x13\x00\xb6\x03\xd8\x4e\x88\x05\xf0\ +\x3d\x0d\xf2\x0f\xd2\x5d\x97\xc9\x64\xf2\x93\x1d\xdb\xa4\x25\xc0\ +\xb2\xac\xd9\x0a\xda\x22\x28\x2e\x84\xe0\xe8\x71\x9a\xc9\x83\xf2\ +\x82\xa6\xa9\x47\x75\x5d\x5f\x2f\x22\x6c\x6a\x90\x68\x72\x02\x48\ +\x4a\xc1\x71\x4e\x15\x85\x9b\x00\x9c\xdc\x4c\xdb\x00\x72\x14\x2e\ +\xf9\x68\xcb\x96\x27\xe6\xcf\x9f\x5f\x6e\x96\xd1\xa6\x25\xa0\x50\ +\x70\x4e\x86\xf0\x1e\x00\xf3\x9b\x65\x33\x1c\x52\x20\xb0\x38\x93\ +\xee\x79\xbc\x19\x33\x62\xc2\x09\x18\x1c\x1c\x3c\x54\x4b\x24\xef\ +\x03\x70\x51\x04\x4d\x11\xf8\xb3\x88\xac\x85\xe2\x46\x26\xf0\xcf\ +\x16\xe0\x63\xd7\x75\x77\xb8\x6d\x6d\x95\xd6\x52\xa9\x93\x6c\xe9\ +\x02\x54\x96\x82\xc3\x01\x39\x41\xc0\xaf\x01\x68\xaf\x65\x90\xc0\ +\x3a\x0d\xea\x2a\xc3\x30\xde\x9d\x48\xfc\x13\x4a\xc0\xa0\x6d\x1f\ +\xa7\x29\x3c\x0b\x60\x56\xc8\xf0\x0e\x81\x3c\x4f\xf2\xb9\x96\x16\ +\x79\x31\x95\x4a\x7d\xd4\x88\x6d\xdb\xb6\xdb\x2b\x15\x39\x45\x44\ +\x9d\x49\xc8\xc2\x1a\x3e\x46\x28\xbc\x34\x9b\x4e\xff\x66\x3c\xf1\ +\x03\x13\x48\x40\xa1\x60\x5f\x08\xc1\x0a\x00\xd3\xaa\x82\x02\x1e\ +\xd4\xa0\xee\x32\x0c\xe3\x93\xf1\xda\xf7\x22\x97\xcb\xb5\x76\x74\ +\xcc\xf8\x0e\x44\x6e\x05\xd0\x5d\x45\xa0\xdc\x69\x18\x3d\xb7\x8a\ +\x88\x6a\xd4\x76\xc3\x09\x20\xa9\x59\x96\x7d\x07\x21\x37\x07\x86\ +\x14\x80\x15\x2d\x09\xf9\x59\x2a\x95\x72\x1a\xb5\x5b\x0f\x36\x6e\ +\xfc\xb0\xb3\xbd\x7d\xe4\x3a\x02\x37\x00\xe8\xf0\x07\x86\x67\xa7\ +\x4f\x9f\x76\x71\x77\x77\xf7\xce\x46\x6c\x36\x94\x00\x92\x9a\x69\ +\x16\x57\x41\x78\x7e\x60\x68\x48\x69\x38\xa7\x57\xd7\xdf\x68\xc4\ +\xde\x78\xe1\x38\x4e\xca\xad\xf0\x19\x54\xbf\x70\xdf\x2a\x97\x46\ +\x4e\xea\xeb\xeb\xdb\x5e\xaf\x2d\xad\x11\xc7\xa6\x5d\x5c\x5c\x75\ +\xf3\x82\xd7\xc1\xca\xfc\xa9\xba\x79\x00\x48\xa5\x52\x4e\x42\x43\ +\x3f\x80\x55\x81\xa1\xcf\x27\x5b\xdb\x56\x91\x4c\xd4\x6b\xab\xee\ +\x19\x90\xb7\xac\x6f\x0a\xe5\x49\xbf\x32\x1f\x53\xaa\x72\x65\x36\ +\x9b\x1d\xa9\xd7\x4e\x33\x41\x52\x2c\xcb\xb9\x91\xc0\x5d\xf0\xdc\ +\x0b\x81\x7b\xb2\x86\xfe\xe3\x7a\x6c\xd4\x95\x00\xcb\xb2\xe6\x2b\ +\xca\x3a\x00\x6d\x1e\xf1\x13\x46\x3a\xf5\xad\xc9\x58\x9d\x35\x8a\ +\xbc\xe9\xfc\x50\xc0\xfb\xbd\x32\x81\x5c\x62\x18\xa9\xc7\xe3\x74\ +\x63\x13\xe0\x38\xce\xc1\x6e\x85\x7f\x03\xd0\xe3\x51\x7a\x43\x29\ +\xf7\xcb\x8d\x3e\xf9\x42\xa1\x70\x24\xb4\x96\x73\x84\x38\x9a\x50\ +\x29\x40\x52\x00\x2a\x02\x38\x14\x38\x50\xdc\x00\xa8\xa7\x1b\xdd\ +\x03\x90\x14\xd3\x2c\x2e\x87\xf0\xdb\x1e\x71\x09\x4c\x9c\x90\xc9\ +\x7c\x76\x43\x94\x6e\x6c\x02\x0a\x96\xbd\x1c\xc4\xa5\x1e\xd1\x90\ +\x26\x3c\x36\x9d\x4e\x0f\xd5\x13\x5c\x2e\x97\x6b\xed\xec\xec\xba\ +\x8a\xc0\x95\x00\x8e\xa8\x47\x07\xc0\x5b\x14\x3e\x98\xd1\xf5\x95\ +\x22\x52\xa9\x47\x61\x60\x60\x60\x5a\xb2\xb5\x6d\x0d\x80\x13\xf7\ +\x49\xb9\xc1\x48\xeb\x5f\x14\x11\xb7\x96\x5e\x64\x02\x4c\xd3\x5c\ +\x40\x68\xeb\x3c\x22\x52\xc9\x89\xd9\x6c\xea\xf5\x7a\x82\xca\x5b\ +\xd6\xd9\x42\xb9\x17\xc0\x9c\x7a\xf8\x21\x78\x1b\x94\xeb\x33\x99\ +\xd4\x9a\x7a\xc8\x63\xab\xd2\x1c\x80\x99\x7b\x64\x02\x5c\x6b\x18\ +\xfa\x83\xb5\x74\x6a\x7e\x05\x48\x0a\x91\xf8\x45\x40\xbc\xaa\x9e\ +\x9b\x5f\xbf\x7e\x7d\xb2\x50\x70\x96\x0a\xe5\x19\x8c\xff\xe6\x01\ +\xe0\x73\x10\xbe\x9c\x37\xed\xc5\x24\x63\xbf\x58\xbd\xbd\xbd\x1f\ +\x10\x72\xa7\x57\x46\xe0\x96\xe1\xe1\xe1\x03\x6a\xe9\xd4\x34\x5a\ +\x70\x9c\x7e\x80\x0b\x3c\xa2\xb2\x40\xdd\x16\x17\x84\x69\x9a\x07\ +\xcd\x3c\xe4\xd0\x17\x20\xbc\x3a\x8e\x5b\x2f\x04\xb8\xcd\xb4\x9c\ +\xdf\x16\x8b\xc5\xe9\xb1\x64\x55\x7e\x08\x02\xcb\x23\x99\x39\x52\ +\x2a\x7d\xb7\x16\xbd\x66\x02\x44\xe1\xc6\x40\x14\x0f\x1b\x86\x31\ +\x18\xe5\x3b\x97\xcb\xb5\x02\xda\xb3\x00\xbe\x12\x1b\x68\xe3\x38\ +\xaf\xec\xaa\xc7\xe3\x66\x42\x36\x9b\x1d\x21\xe8\x7f\x50\x94\xeb\ +\x6a\xad\x0d\x42\x8d\xe5\xf3\xf9\xc3\x00\x9c\xe6\x11\x95\x95\x5b\ +\xbe\x23\xca\x31\x49\xe9\xe8\xec\x5a\x4a\xa0\x3f\x8a\x37\x41\x9c\ +\x5b\xb0\x9c\xd8\x59\x98\xd1\xf5\x95\x04\x06\x3c\xa2\x9e\x82\x6d\ +\x7f\x35\x8c\x1b\x9a\x00\x49\x24\x2e\x04\xb0\x37\x63\x02\xac\xe9\ +\xed\xed\xfd\x20\xca\xa9\x65\x39\x17\x01\xb8\x3c\x2e\xb8\x89\x42\ +\x80\x5b\x4d\xb3\x18\x7a\x33\x7b\x39\x22\x15\x21\x9f\xf2\xc9\x94\ +\x5c\x12\xc6\xad\x31\x9d\xe4\x4c\xef\x15\x85\x7f\x88\x72\x58\x2c\ +\x16\xa7\x8f\xad\xc6\xa6\x04\x0a\x6a\x49\xdc\x72\x97\x09\xf1\xc7\ +\x2c\x38\x3d\x4c\xa7\x2a\x01\xc3\xc3\xc3\x07\x80\xde\x6f\x29\x50\ +\x29\x27\xfe\x18\xe5\xac\x5c\xae\x5c\x07\xcf\x42\x69\xb2\x21\xc0\ +\x3c\xd3\x74\x16\x45\x71\x32\xa9\xd4\x9b\x80\x78\x67\x6d\x57\xde\ +\x71\x8e\x09\xf2\xaa\x12\xb0\x7b\xb7\x7b\x3c\x80\x56\x8f\xe8\xed\ +\xd9\xb3\x7b\xac\x20\x6f\x0f\x46\xb3\x2a\x3f\x88\x0f\xbb\xb9\xa0\ +\xe0\xda\xa8\x71\x11\x51\x10\xfa\x1e\x5c\x42\x55\xd7\x29\x43\x7e\ +\x02\x9c\x1b\x10\xac\xab\xe6\xec\x43\xa1\xe0\x7c\x09\x82\x43\xa2\ +\x38\x93\x01\x01\xe6\xd9\xb6\xdd\x17\xc5\xe1\xe8\xfe\x65\xdf\x35\ +\x70\x54\x90\x13\x96\x80\x23\x03\x8e\x06\xaa\x39\x9e\xf1\x04\xce\ +\x0b\xe8\x47\xd1\x9b\x0a\x57\xe1\xdc\xa8\x71\xa1\x04\x63\x3f\x32\ +\xc8\x09\x49\x80\x64\xbc\x57\xa4\x44\x7e\xfb\xa1\x82\x45\x89\x29\ +\xe9\xb5\xec\xf1\x54\xf5\x9b\xf6\x82\x2c\x05\x63\xcf\x06\x39\x55\ +\x09\x20\xd0\xe9\x73\x22\xf2\x69\x4c\x14\x53\xf6\xf2\x0b\xf1\x9d\ +\x8a\x61\x04\x63\xef\x0c\x12\x62\x13\x50\xa9\xb0\x66\x8d\x6d\x6c\ +\x55\x16\x56\xad\x9d\x1a\x30\x3a\x01\x99\x4c\x66\x37\x00\xef\x4e\ +\xb0\x75\x74\xb5\xba\x0f\x55\x09\x90\xe0\x1c\x4e\x32\xea\x47\xad\ +\x85\xd9\x98\x3a\x48\x72\xa2\x16\xc2\x82\xdf\xe1\xbd\x48\x28\xad\ +\x6a\xda\xec\x75\x3f\xba\xcf\x8e\x5c\x21\x4e\x2e\x18\x59\x7d\x2e\ +\x14\x0a\xd3\x00\xb4\x78\x44\xa5\xb9\x73\xe7\x96\xbc\x9c\xb0\x19\ +\xe0\xab\xa8\x92\x3c\x30\x26\x8a\x62\xcc\xf8\xa4\x41\x80\xc8\x04\ +\x90\xec\x0a\x88\x76\x04\x39\x55\x09\x50\x80\x19\x30\x53\xf5\xe6\ +\xf4\x07\xc1\x5c\xd4\xf8\x64\x82\x94\x48\xdf\x9a\xd6\xda\x1b\x10\ +\x15\xaa\x38\xd5\x6a\xf2\x9e\xcf\x89\x20\x72\xb1\x21\x82\xa7\xa3\ +\xc6\x27\x17\x5a\xa4\x6f\xa9\x8e\x7d\x63\x95\x85\x6a\x41\xc5\xd7\ +\x6c\x14\x7f\x51\xa4\x0a\x95\x4a\x65\x35\x80\x86\xba\x31\x4d\x82\ +\x69\x18\xb3\xde\x8a\x22\x30\x10\x3b\x81\xaa\x19\x53\x95\x80\xf6\ +\xf6\xf6\xd7\x00\x78\xfa\xef\xf2\x05\xc7\x71\x6a\x7e\x6e\xb2\xd9\ +\xec\x08\x04\x8f\xc6\xc7\xdb\x64\x88\x3c\x12\x55\x92\x1f\xfb\x44\ +\x9f\xe1\x13\x2a\x59\x1b\xe4\x55\x25\xa0\xbb\xbb\x7b\xa7\x00\xaf\ +\x79\x65\x65\x15\x30\x14\x40\x39\xd9\x72\x3b\x80\x6d\xd1\x11\x37\ +\x0f\x02\xd8\x09\xf1\xf7\x01\x82\xb0\x6d\xfb\x18\xf8\xd7\x28\xdb\ +\x33\x99\x9e\xf5\x41\x5e\xe8\x37\x9c\x84\x6f\x17\x25\xe0\xc2\x28\ +\x67\x7d\xb3\x66\x7d\x08\x32\xb2\x62\xd4\x64\xfc\x44\xd7\xf5\x5d\ +\x51\x04\x05\xcd\x17\x33\xc1\x17\xc3\xca\xe3\xa1\x09\xd0\x34\xae\ +\xc2\x68\xb7\x77\x8f\xf6\x29\x03\x9b\x37\x47\xee\xf8\x0c\x43\x7f\ +\x40\x80\x97\xa2\x38\x8d\x23\x74\x86\xaf\x4c\xa7\x53\xc1\x9e\xa0\ +\x5f\x8b\xd4\x40\xfa\x36\x69\x42\x79\x2c\x8c\x1b\x9a\x80\x74\x3a\ +\x3d\x04\x62\xb5\x47\x34\x2d\xb9\xbb\x1c\x6c\x87\xfb\x20\x22\xae\ +\x52\xee\xf9\x00\xde\x8f\xe2\x35\x06\x09\x5e\xbe\x4e\xe5\x5e\x11\ +\xd7\x8e\x33\x4d\xe7\x02\xf8\x9b\x30\xc3\x86\x91\x5a\x1d\xc6\xad\ +\x5d\x15\x16\xf9\x65\x40\xf0\xbd\xc1\xc1\x21\x23\xca\x71\x36\x9b\ +\xfd\x54\xa0\x4e\x47\x53\x93\xb0\x17\xeb\x95\x5b\x3e\x3b\xae\x1d\ +\x97\xcb\xe5\x5a\x21\xf8\xb9\x57\x26\xc0\xfd\xb5\xba\x43\x35\x13\ +\x90\x4e\xf7\xac\x81\xff\x65\xd8\x9a\x48\xa8\xc5\x71\x51\x1a\x86\ +\x31\x48\xe5\x1e\x2f\x40\x68\xc6\xc7\x05\xca\x93\x09\x0d\xfd\x71\ +\x85\x59\x00\xe8\xe8\xe8\xba\x02\xfe\x6d\xef\xc7\xbb\x76\xb5\x2d\ +\xab\xc5\x8f\xdc\xbc\xe7\xf3\xf6\x49\xa2\xe1\x15\x8f\x48\x09\xd4\ +\x71\x86\x61\xfc\x35\x36\x66\xb2\xc5\xb2\x9c\xeb\x09\xfc\x14\x21\ +\xdb\xd0\x3a\xb1\x95\x22\xb7\x64\xf4\x9e\x87\xeb\xe9\x42\x17\x8b\ +\xc5\x99\x65\x57\xbd\x0b\xef\x31\x1a\xf2\x86\x4c\x26\x7d\x5f\x2d\ +\x9d\x98\x26\x83\xbe\x16\xc0\x4a\x3f\x5f\x7b\x66\x70\x70\xf0\xd0\ +\xb8\x60\x44\xc4\x35\x0c\xfd\x6e\xb7\x9c\x9c\x03\xca\x32\x00\xff\ +\x8e\xd3\xf1\x60\x9b\x00\x77\x55\xdc\xd2\x9c\x6c\x3a\xf5\x50\x3d\ +\x37\x9f\xcb\xe5\x5a\xcb\x65\xf5\x3b\xf8\x6e\x1e\xef\x6c\xdd\xba\ +\xa5\x66\x5f\x10\xa8\xa3\x7c\xb3\x69\xd3\x70\x77\x4b\xd2\x7d\x07\ +\xa0\xf7\xa6\xff\x52\x2e\x8d\x9c\xd2\xd7\xd7\xb7\x3b\x4e\x7f\x0f\ +\x8a\xc5\xe2\xf4\x72\x59\x9d\x06\x0d\xe7\x92\x98\x27\xa3\x55\xe4\ +\xcf\x8c\x05\xfa\x21\x34\x0c\x41\xc9\x06\x80\x4f\xed\xdc\xb9\xed\ +\xe5\xe0\xae\x2d\x0e\xa6\x69\x2d\x23\xe4\x4a\x8f\xa8\xac\x34\x2c\ +\x88\x3b\xb9\x52\x57\xfd\x2a\x9f\x77\x8e\x17\x8d\x6b\xe1\x3d\x11\ +\x26\x58\x61\xe8\xa9\xcb\x27\x72\x40\xc2\xb6\xed\xf6\x91\x91\x11\ +\xd5\x48\x22\xc3\x50\xb0\xac\xab\x41\x59\xea\x13\x12\x97\x67\x32\ +\xfa\xf2\x38\xdd\xba\x0b\x78\xa6\xe9\x5c\x4c\xd0\x77\xe2\x82\xc0\ +\x23\xff\xda\xb1\xed\x9a\x46\x9f\x56\xb3\x30\x76\x44\xe6\x1a\x02\ +\xf7\xc3\xf3\x73\x16\xf0\x01\xc3\x48\xff\xa8\x1e\x1b\x0d\x55\x30\ +\xf3\xa6\x7d\xb7\x00\x37\xf9\xa3\xc0\xab\xc9\xa4\x76\x5e\x4f\x4f\ +\xcf\xd6\x46\x6c\x4d\x14\xb9\x5c\xae\xb5\x63\x46\xd7\xaf\x40\x5c\ +\xe6\x95\x0b\xf0\x52\x3a\x9d\x3a\x23\xea\x50\x44\x80\x5f\x3f\x48\ +\x26\x4c\xdb\x79\x0a\xc4\x39\x01\x33\x85\x84\xc6\x85\xba\xae\xff\ +\xbd\x11\x7b\xe3\xc5\xd8\x7b\xe9\xf7\xa8\xde\xa9\xbe\x4b\xe5\x2e\ +\xc8\x66\xb3\xd1\x85\x5c\x0f\xc6\x73\x50\x32\x61\x9a\xf6\xbd\x10\ +\x09\x4e\xb1\x32\x81\x65\x95\x72\xf2\xce\x39\x73\x0e\xdb\xd2\xa8\ +\xdd\x7a\x30\x7a\x7c\x16\xdf\x87\xe0\x66\x00\x07\xf9\x06\x05\x2f\ +\x54\xca\xa5\x0b\x66\xcf\x9e\xdd\xd0\xa6\x6c\x22\x47\x65\x2f\x83\ +\x60\x19\x80\x60\x61\x72\x27\x81\xfb\xdc\xd2\xc8\x92\x46\x0e\x2c\ +\x46\x81\x64\x8b\x69\x3a\x8b\x20\x58\x8c\xb0\x1e\x24\x65\x89\x61\ +\xf4\xdc\x54\xef\x79\x22\x2f\x26\x76\x58\xda\xb2\xfa\x35\xca\xd3\ +\x00\x0e\x0e\x19\xfe\x84\xe0\x73\x1a\xb4\xe7\x4a\xa5\x5d\xab\x1b\ +\x4d\xc6\xe8\xe1\xaa\x83\xfa\x15\xd4\x99\x02\x9c\x05\x20\x6c\x19\ +\x5e\x06\x71\x55\x3d\x6f\xfb\x5a\x98\x70\x1b\x67\x53\xb1\xa8\xb7\ +\x54\xd4\x03\x20\xbe\x11\x41\x2b\x03\x7c\x15\xa2\xbd\x02\xc5\xf7\ +\x95\x92\x4d\x6a\x9a\x7c\x9c\x74\xdd\x9d\xa5\x52\xa9\xd2\xd6\xd6\ +\xd6\xa9\x94\xea\x22\x13\x59\x6a\x38\x1c\x54\x27\x08\xe4\x54\x00\ +\x33\x6a\x19\x24\xf0\xe6\xd8\x71\xf9\xd8\x55\x69\x14\x9a\xf8\x87\ +\x09\xfb\xeb\x14\xdc\x2d\xc0\xbc\x66\xd9\xac\x81\x21\x42\x6e\xcf\ +\xa4\x7b\x7e\x3d\x9e\x29\x1f\x44\xb3\xff\x32\xa3\x99\xa6\x73\x16\ +\x05\x37\x0b\x70\x6c\x33\x6d\x03\x18\x04\xb9\x84\xac\x2c\x6f\xe6\ +\xd1\xdc\x49\xeb\x64\x9a\xa6\x79\x14\x45\x5b\x04\x85\x85\x10\x1c\ +\x3e\x4e\x33\xc3\x10\x3c\xaf\xc0\xc7\xb2\xba\xfe\xa7\xf1\xfc\x1f\ +\x20\x0e\x53\xd2\xca\xdd\x54\x2c\xea\x49\x97\x27\x2b\xf0\x28\x40\ +\x8e\x00\x98\x15\x41\x17\x88\x19\x18\xed\xdc\x6c\x03\xb8\x5d\x20\ +\xb6\x02\x36\x42\xb8\x51\x23\x5f\x4d\xa7\xd3\xef\xfd\x37\x9c\x45\ +\xde\x8f\xfd\xd8\x8f\xff\x5d\xfc\x07\xbb\x1b\xfe\xd4\xc4\x32\xd9\ +\x11\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x3e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xed\ +\xd6\x3f\x68\x13\x61\x18\xc7\xf1\xef\xf3\x5e\x62\xa5\x82\x8a\x1d\ +\x14\x5d\x44\x9c\x1c\xfc\x13\xcc\xe0\xe0\x28\x5d\xea\x24\xc1\x45\ +\xd1\x45\xd2\xda\x34\x05\xc1\x51\x4a\x70\x74\x50\x92\x5a\x6b\x40\ +\x10\x75\x10\x8b\x5b\x10\xc5\xd1\xa1\xa0\x6d\xc4\xc5\xc9\xa1\x93\ +\x28\x48\x4b\x87\x8a\x35\xc9\xfd\x1c\xee\xb2\x38\xdd\x5d\x8e\xcb\ +\xa0\x0f\xdc\x76\xcf\xfb\xfb\xf0\xdc\xfb\xde\x1d\xfc\xeb\x65\x51\ +\x6e\x3a\x5d\xae\x6f\x80\x59\xbe\xdb\x39\xb2\xfc\xe8\xc6\x7a\x9a\ +\x00\x17\xf1\xbe\xbd\xa0\x3d\x9d\x5c\xae\x75\xfc\xf2\x9d\x5d\xc3\ +\x00\xf4\xeb\xcc\xc8\xe8\xc8\xcb\x63\xa5\xb9\x1d\xc3\x02\x20\x18\ +\x1f\xdd\x37\xf6\xa4\x54\x7a\xe1\x65\x0e\x10\xf8\x60\x02\x2e\xae\ +\x8d\x7d\x6b\x80\x22\xed\xa1\xd4\x00\x06\x12\xbe\x00\x24\xa6\x8a\ +\x93\xf5\x5a\xa6\x80\x00\x61\x92\xe1\x07\x08\xbb\x55\x2c\x37\x66\ +\x33\x05\x00\x98\x90\x50\x80\x40\xf7\x8a\xe5\xc6\xa5\x4c\x01\xf0\ +\xd7\x24\xd0\xe3\xc2\xe4\xfc\x44\xa6\x00\x08\x26\x81\x10\xe0\x39\ +\xf9\x4b\x85\xa9\xfa\xd9\x4c\x01\x81\x02\x3f\x44\xec\x74\x3e\xad\ +\xe2\xb5\xbb\x27\xb3\x05\x84\x08\xc9\x04\xec\x96\xf3\x5e\x17\xae\ +\xdf\x3f\x9a\x2d\x00\x30\x53\xff\x1d\xb1\xdf\x7a\xbd\xb7\xa7\x2a\ +\x8d\x83\x99\x02\x82\x0a\x4e\x86\xc1\x61\xd7\xd1\xab\x21\x00\x00\ +\x44\x88\x38\x31\x04\x80\x39\x30\x04\x6b\xbd\xbc\x1d\x8a\xd2\x91\ +\x4b\x2b\x5a\xe0\x2c\xf8\x36\x7c\x97\xe7\x9d\xfb\x38\x3f\xfd\x35\ +\x4a\x5f\x5a\x13\x70\x16\xfc\xdc\x6c\x3a\x18\x6f\x2f\x4c\x7f\x89\ +\xdc\x98\x46\x38\x41\xf8\x2f\xdf\x71\xfe\xfd\xc3\xea\xa7\x38\xcd\ +\x83\x3e\x02\x0b\xaf\x9e\x6f\xae\xd4\x7e\x50\x79\x17\x77\x81\xc4\ +\x13\x90\xc9\xfa\xfd\x86\x5d\x6d\x2f\x56\x5a\x49\xd6\x49\x3a\x01\ +\x33\x99\x03\x90\x98\x5d\x69\xce\x3c\x4b\xb8\x4e\x92\x09\xc8\x40\ +\x2e\x54\xdc\x5e\x6d\x56\xeb\x49\xc3\x63\x03\x84\x0c\xf5\xcf\xba\ +\x16\x3e\x2c\x56\xe7\x06\x09\x8f\x0d\x30\x70\x18\x20\x7b\xbe\x7a\ +\x60\x7d\x26\x7c\xf7\x0f\x54\x31\xf7\x80\x61\xf0\x66\x6b\xe3\xc7\ +\x15\x9a\x35\x7f\xd0\x70\x88\xbf\x07\x96\xb7\x7f\x6e\x5f\xf8\xbc\ +\x54\xfb\x9d\x46\x38\x44\x9c\x80\x60\xd3\xc0\xf2\xdd\xee\xc4\xca\ +\xd3\x9b\x5b\x69\x85\xff\x2f\x80\x3f\x94\x18\xa2\x63\x8f\xc5\xfb\ +\x89\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x98\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ +\xce\x49\x0d\x00\x31\x0c\x04\xc1\x5c\x90\x0c\xca\x2c\x36\x14\x4c\ +\x25\xfc\x72\x80\x98\x95\xfc\xe9\xfa\xcf\xa8\x4b\x11\x98\xc7\x34\ +\x8f\xa9\x7c\x34\x65\xfc\x07\x02\x08\x20\x80\x00\x02\x08\x48\x0f\ +\x18\xf2\xc3\xad\x9f\x79\xe4\x04\xdc\xd3\x57\x6d\x5b\xb9\x00\x00\ +\x00\xf9\x1e\xf2\x23\x09\xdd\x64\x85\x0e\x0a\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xd0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x82\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\x31\x0e\x82\x50\x10\x04\xd0\x81\x43\x10\x1b\x13\xce\xe4\x15\ +\xa8\x38\x11\x37\xf1\x3c\x24\x36\xc4\x43\x88\xad\xe1\xdb\x22\x86\ +\xff\x5e\x39\xd9\x62\x76\xbb\x4d\x00\x00\x00\x00\x00\xa8\x47\xb3\ +\x0d\xe6\xf9\x71\x4b\x93\x29\x49\x77\x40\x9f\x3d\x2d\x59\x33\xf4\ +\xfd\xf5\xfe\x19\xb6\xc5\xd8\x39\x97\x4f\x92\x4b\xda\x4c\xdb\xb0\ +\x3c\x40\x65\xca\x03\xac\x19\x93\x3c\x7f\x5f\x65\x77\x4b\x5e\x19\ +\x8f\x2e\x01\x00\xfc\x0f\xbf\x40\x31\x76\xce\xe5\x13\xbf\xc0\x77\ +\x7e\x01\x00\x00\x00\x00\x00\x00\x2a\xf1\x06\x74\xea\x1a\x0f\x1a\ +\xcd\x17\x42\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x2e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe0\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xbd\x6b\x14\x51\x14\xc5\x7f\x67\x46\x8d\x20\xf1\xab\x90\x85\ +\xcd\xec\x18\xc1\x2e\x85\xa5\x95\x65\x04\x25\x8d\x85\x56\x0a\x76\ +\x36\x42\xfe\x00\xb1\x10\x7b\x11\x04\x4b\x41\x2b\x2d\x6c\x82\x85\ +\xa6\xb3\xb2\x14\xd9\x4e\xc8\x3a\x3b\xbb\xb0\x58\x69\x82\x90\x0f\ +\x76\x8e\xc5\xac\xb5\xfb\x66\x1e\x0a\x7a\xab\x79\xc3\xbc\x73\x7e\ +\xf7\xbe\xfb\xde\x1b\xf8\xdf\x43\xb1\x05\xcb\xb2\x3c\x3d\xad\xd8\ +\x02\xfb\x6c\xde\x3b\xf5\xbb\xef\x0f\xc5\x34\x9f\x4c\x26\xc7\x76\ +\xf7\x0f\xde\x00\x27\xe6\xcd\x2d\x1a\x40\xbf\xdf\x3f\xb2\xb7\x77\ +\xf0\x1a\xb8\x18\x32\x2f\x89\x61\x6e\x3b\x5d\x5c\x3c\xf9\xdc\xb0\ +\x8a\x1d\x34\xb7\x35\x80\x6d\x0d\x87\xe5\x13\xe3\x1b\xf5\x1b\x55\ +\x7f\x14\xa0\x28\xc7\x0f\x8c\xee\x00\x18\x2a\x44\x50\x09\x5a\x01\ +\x0c\x8a\xd1\x3a\xf6\x3d\xdb\x80\x2b\x11\x66\xde\x0a\xa0\x28\x46\ +\x37\x85\x1f\x01\x24\x52\x05\x0a\x36\x6f\x0c\x50\x14\xe3\x35\xe3\ +\x67\xf5\x48\x95\x1b\x64\xde\x18\x60\x6b\x38\xbc\x64\xaa\x57\x40\ +\x5a\x1b\x07\xb6\x7d\x1b\x80\xc1\x60\x74\x21\xb1\x36\x80\xa3\x60\ +\x0b\x82\x3a\xbe\x15\x40\x59\x96\xe7\x95\xf8\x2d\x70\x1c\x70\xe8\ +\x76\x6b\x05\x50\x96\x65\x77\x5a\xb1\x09\x9c\x99\x75\x7a\x14\x73\ +\x98\xf3\x28\x9e\x56\x8c\xea\x27\xe3\x48\x99\xff\x8a\xf9\x96\xc0\ +\x7c\x8a\x69\x1a\x0c\x90\xa6\x5c\x01\x7d\x01\xa1\x48\xf7\x47\x10\ +\x40\x96\x65\xe3\x34\xf1\x2a\xf0\xd5\xf5\x3d\x1b\x0d\x62\x6e\xa1\ +\x2c\xcb\x3e\xbb\xd2\x65\x60\x1b\x10\x8e\x03\x11\x24\xb2\xbc\xbc\ +\xf4\xb1\x92\xd7\x80\x5d\x84\x1c\xa1\x12\xc1\x02\xe7\x7a\xbd\xf7\ +\x22\xb9\x0e\x4c\x05\x52\xcb\xdf\xba\x46\x19\xe4\x79\x77\x43\xe8\ +\x36\xc0\xac\x0a\x8d\x21\x1a\x97\x30\xcf\x97\x5e\x08\xd6\x01\x6c\ +\x37\x86\x68\xb5\x86\x79\x9e\x3d\x46\x7a\x28\x69\xa6\xe5\x60\x88\ +\xd6\x4d\x94\x67\xdd\xfb\x58\x4f\xeb\x91\x12\x3b\xac\x12\xad\x01\ +\x24\x39\xcf\xbb\x77\x85\x5e\xd6\xe3\x30\xcd\x28\x7b\x59\xd2\x74\ +\x67\xe7\xdb\x2d\xc1\xbb\xd0\xb9\xd1\x4e\xb4\x95\x95\x95\xfd\x85\ +\x85\xc3\xd7\x10\x1f\xfe\x0a\x00\x40\xa7\xd3\xf9\x91\x8a\xab\xb6\ +\xb7\xc1\xdf\x63\x6a\xff\xbb\xf1\x13\xb6\x0b\xa1\x01\x61\x9e\xcd\ +\x4b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x98\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4a\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x0d\xc0\x30\x08\x04\x41\x82\x5c\x1b\x15\x50\x02\x7d\x98\ +\x9a\x52\xa0\x9d\x22\x2e\x12\x9f\x9d\xff\x9d\xd6\x4c\x10\x59\x1d\ +\x59\xad\x7c\xb8\x32\xfe\x03\x01\x04\x10\x40\x00\x01\x04\x8c\x07\ +\x2c\xf5\xe0\x5e\xdb\x91\x35\x13\xf0\x1c\x7f\xcd\x8f\x72\x01\x00\ +\x00\xe6\x7d\x0c\xb6\x09\x4f\xb2\x71\xd6\x0c\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\x77\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x29\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x53\xb8\x9e\x44\x40\xc6\xf1\ +\x48\x0c\xb4\x55\x00\x40\x58\xef\x39\x37\x39\xb0\x92\x71\x00\xe0\ +\x0b\x0f\xd3\xb2\x02\xe6\x6a\x84\x46\x98\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x9a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x76\xf2\xda\xc4\x4d\x10\xb8\ +\x99\xb4\x41\xa6\x74\x7c\xef\xf8\x83\xf0\x5d\x15\xa1\x64\xba\xdc\ +\x74\xb9\xbd\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xf2\x9f\x51\x93\ +\x9d\xda\x29\xe8\x00\x81\xd7\x0c\xbd\xf7\x79\x8f\x39\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xee\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x53\xb8\x46\x22\x20\x23\x3c\ +\x1a\x03\xeb\x6d\x0c\x68\xed\x73\xd7\x3e\x57\x36\x4c\x39\xfe\x83\ +\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\ +\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\ +\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\ +\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\ +\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\ +\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\ +\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\ +\x75\x80\x0e\xd0\x3a\x40\x07\x68\x0f\xaf\xe7\x06\x43\x97\x92\x59\ +\xbc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xea\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9c\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5d\x6c\x14\x55\x14\xc7\x7f\x67\xa6\x5b\xaa\x15\x6a\x94\x34\ +\x68\x77\x66\xa7\x8b\x4d\x90\x54\x9f\x2a\x09\x0f\xf8\x81\x04\x12\ +\x91\x0f\x49\xd4\x10\x8d\x24\x08\x91\xf8\xe0\x83\x09\x0a\x4a\xe4\ +\x01\xc5\xfa\x62\x82\x12\x50\x43\x62\x4c\x78\x33\xb1\x81\x0a\x28\ +\x89\x04\x9e\x90\xd0\x84\x90\x54\x03\x59\xda\xdd\x9d\xd9\xa5\x62\ +\x8d\x09\x22\xa8\xed\xce\x3d\x3e\xec\x07\xb3\xdd\x6e\xbb\xad\xbe\ +\x71\x5e\x76\xe6\xdc\xff\x39\xff\xff\xbd\x77\xee\x3d\x67\xe1\x4e\ +\x37\x99\x09\xf8\x4a\x3e\xef\xc4\x0a\x66\xbd\x41\x56\x08\xea\xa0\ +\xc4\x11\x2c\x94\x3c\x42\x4e\xe0\x8c\x65\xd1\xe7\x38\x4e\xea\x7f\ +\x15\x30\x1c\x04\x4b\x2c\x43\x2f\xf0\x54\x23\x78\x85\xf3\x16\xb2\ +\x33\x91\x88\xff\xf0\x9f\x04\x0c\x0d\x0d\xb5\xd9\x76\xf3\x41\x84\ +\x8d\x25\xd7\x88\x42\x3f\xa2\x27\x54\x64\x38\x6c\x6a\x1a\xb9\x2b\ +\x0c\x4d\x18\x86\x0b\x54\x6d\x4f\x45\x57\x0a\xac\x03\x12\x25\xfc\ +\x71\x13\x8e\x6f\x4e\x26\x93\xd7\x66\x2c\x20\x08\x82\x87\x42\xa3\ +\x47\x41\x1e\x06\x46\x04\x76\xbb\x6e\xfc\x4b\x11\x29\x4c\x25\x5a\ +\x55\xad\x4c\x10\xbc\x28\x2a\xef\x03\x49\x04\xdf\x14\x64\x6d\x32\ +\x19\xbf\xd8\xb0\x80\x6c\x36\x9b\x54\xac\x73\xc0\x7c\x81\x23\x63\ +\x63\x7f\xbf\xd2\xd5\xd5\xf5\xc7\x54\xc4\x13\x2d\x95\x4a\xcd\x89\ +\xcd\x69\x39\x80\xb2\x19\xb8\x89\x5a\xcb\x3c\xaf\xe3\xc2\xb4\x02\ +\x52\xa9\xd4\xbc\x58\x73\xcb\x59\x60\xb1\xc2\x3e\xcf\x8d\xbf\x29\ +\x22\x66\x26\xe4\x65\x53\x55\xc9\xf8\xf9\x1d\x82\xee\x05\x72\x68\ +\xb8\xc4\xf3\xbc\x91\x28\xa6\x69\x62\x50\xac\xb9\x65\x7f\x91\x5c\ +\xfb\x3d\xd7\xa9\x21\xbf\x92\xcf\x3b\x76\xc1\x6c\x11\x78\x06\x70\ +\x01\x83\x92\x05\x3d\x06\xe6\x50\x94\x40\x44\x54\x55\x7b\xb3\x7e\ +\x2e\x09\x6c\x41\xec\xc3\xaa\xba\x42\x44\x74\xd2\x15\xf0\x7d\xbf\ +\xc7\xa8\x9c\x47\x19\x0d\xc3\xb1\xae\x85\x0b\x17\x5e\x8f\xcc\xc6\ +\xca\xf8\xf9\xb7\x05\x7d\x0f\x68\xa9\x33\xe9\x9b\x02\xef\xb8\x6e\ +\xfc\xd3\x28\xc9\xe0\xe0\x60\xf3\x3d\x73\xdb\x2e\x02\x8b\x50\x56\ +\x7b\x9e\x73\xbc\x3c\x66\x45\xa3\x8d\xf2\x61\x51\x39\x7b\x26\x92\ +\x67\xfd\xdc\x57\xa5\xa5\xac\x47\x0e\xd0\xaa\xb0\xcf\xf7\x83\x03\ +\xaa\x5a\x99\x5c\x77\x77\xf7\x18\xca\xbb\x00\x2a\xf4\x46\xc7\x2a\ +\x02\x32\x99\xcc\x03\x20\x4f\x03\xbf\xdf\xb8\x71\xfd\xf3\xea\x95\ +\xc9\xed\x02\x5e\x56\xa5\x21\x53\x64\x9b\xef\xe7\xde\x88\xfa\x12\ +\x89\x78\x1f\x70\x49\xe0\x91\x74\x3a\xff\x68\x8d\x00\x11\x7b\x0d\ +\xc5\x2d\x39\xd6\xdd\xdd\x3d\x56\xf6\x17\x4f\x04\xbb\x8a\x98\xc6\ +\x04\x14\x45\xf0\x81\xef\xfb\x0f\xde\xce\x2f\xaa\x70\x14\x40\x6c\ +\x7d\xae\x46\x80\x2a\x4f\x96\x22\xbf\xab\x4a\x24\xf6\xeb\x40\xac\ +\x71\xea\x8a\xb5\xaa\xca\xd6\xa8\x43\x54\xbe\x2f\x3d\x2e\xaf\x11\ +\x80\x88\x53\x7a\x48\x57\x4f\x45\x57\xcf\x82\xbc\x18\x0a\xcf\x56\ +\xa7\x1a\x1f\x06\x10\x88\xd7\x0a\x28\x39\x55\xc7\x47\x6e\x07\xa8\ +\x00\xc9\xd9\x0a\x40\x2b\x57\x32\x00\x85\x42\xa1\x9c\xbb\xa3\xfc\ +\x21\x5a\x35\x41\xd5\x26\x0d\x60\xa6\x8a\xb6\xa7\xc9\x1d\x4d\x6e\ +\xf2\xc5\xdf\xd8\x82\x0a\xa2\x78\x09\x65\x67\x2d\x00\xfc\xe8\x8b\ +\x6d\xb7\x96\x72\xcb\xd5\xf2\x05\x77\x5b\x80\x5a\x41\x11\x65\x3a\ +\x27\x24\x39\xce\x6c\x4d\xb5\x2a\xd6\xb2\x4c\x79\x3b\x73\x15\x5f\ +\x05\x2b\x9c\x06\xb0\x94\x55\xd1\x20\xc1\x7c\x06\xcc\xa6\x16\x8c\ +\x81\x39\x54\x95\x4b\x74\x25\x80\xa2\xa7\x6a\x04\xd8\x62\xfa\x8b\ +\x83\xb2\x7a\x60\x60\xa0\x72\xec\x12\x89\xc4\xcf\x82\x7e\xd2\x38\ +\xaf\x96\x84\xb3\xd7\xf3\xbc\xca\x89\x52\x55\x51\x58\x0b\x80\x91\ +\xbe\x1a\x01\xae\xeb\x5e\x05\x4e\x01\xf3\xef\x6f\x6f\xdf\x12\x4d\ +\x39\x3a\xfa\xeb\x5b\x34\xbc\x15\x82\xa2\x5f\xbb\x6e\x7c\x4f\xd4\ +\x1b\x04\xc1\x1a\x60\x31\xf0\x93\xe7\x75\x54\x7a\x83\xaa\x2f\xdc\ +\x12\xdd\x01\x20\x6a\xed\x4e\xa5\x52\xf3\xca\xfe\x9e\x9e\x9e\xf1\ +\xdf\x46\xaf\xad\x57\xd8\xc7\xd4\xdb\x51\x40\x75\xaf\xe7\x3a\x1b\ +\xa3\x55\x74\x70\x70\xb0\xd9\xa8\x14\xeb\x0c\xd6\xce\xba\xd5\x10\ +\x20\x93\x0d\x0e\x03\x2f\x09\x1c\x71\xdd\xf8\x86\x89\xe5\xd8\xf7\ +\xfd\x6e\x83\x6c\x43\x2b\xe5\x58\x81\xac\xc2\xb7\x1a\x5a\x07\x93\ +\xc9\x8e\xcb\x51\xbc\xaa\x8a\xef\x07\x07\x15\x79\x0d\xe1\x74\xc2\ +\x89\x2f\x9f\x52\xc0\xd0\xd0\x50\x9b\xdd\xd4\xfc\x23\xb0\x08\x95\ +\x8f\x13\x89\x8e\xed\xf5\x1a\x12\x55\xb5\x01\x44\x24\xac\x33\x2e\ +\xbe\x9f\xdb\xae\xf0\x11\x70\xd5\x12\x7d\xac\xb4\xd5\x15\x9b\xb4\ +\xbc\x14\xfb\x41\xce\x01\xf7\x21\x7c\x73\x77\xcb\x9c\x4d\xed\xed\ +\xed\x7f\x4e\x86\xad\x67\xa5\x1e\x60\x3f\xb0\x15\xb8\x65\x89\x3e\ +\xe1\xba\xee\xc0\x44\xdc\xa4\xb7\x9c\xe3\x38\x57\x42\x5b\x96\x02\ +\x97\x51\x36\xdc\xfa\xeb\x9f\x4b\x99\x4c\xf0\xaa\xaa\xd6\x74\x50\ +\x13\x4d\x55\xad\x6c\x36\xf7\x42\xeb\xdc\xb6\xc1\x12\x79\x0e\xb5\ +\x97\x4d\x46\x0e\xd3\xb4\xe5\xe9\x74\xfa\x5e\x2c\xfb\x0b\x41\x9e\ +\x2f\xb9\x72\xa8\xf4\x8b\xc8\x09\x28\x0c\x5b\x96\x35\x52\x28\x14\ +\x0c\x34\x2f\xc0\x0e\x13\x62\x58\x85\xc8\x3a\x4a\xf5\x43\xe0\xa4\ +\x31\x85\x4d\x9d\x9d\x9d\xbf\xd4\xe3\x68\xa8\xc2\x67\x32\xb9\xa5\ +\x22\xda\xab\xf0\x78\x23\x78\xe0\x82\x11\xdd\x91\x74\xdd\x93\xd3\ +\x01\x67\xf4\xd7\x2c\x9d\x4e\x7b\x58\xb1\xf5\x82\xae\x40\x71\x10\ +\xe2\x80\x0d\xe4\x04\x72\x06\x39\x83\x91\xbe\xce\xce\x8e\x4b\x33\ +\xc9\x7b\x67\xdb\xbf\x21\xb9\xe6\xce\xae\xea\xf6\xd6\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x18\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xca\x49\x44\x41\x54\x58\x85\xed\ +\x96\x3f\x48\xc3\x40\x14\xc6\xbf\x97\x0a\x29\x08\xd5\x5d\xa9\x8b\ +\xb8\x76\x15\x41\x5c\x8c\xae\xd2\x58\xc4\x21\x2e\xad\x2e\xba\x14\ +\x44\x5c\x9c\x3a\x38\x08\x2e\xc5\xa5\x56\x1c\x5c\x94\x92\x82\xd0\ +\x45\xb3\x08\x22\x38\xda\xd1\xc1\xa1\x38\xb8\x08\xfe\x19\x0a\x85\ +\xe6\x9e\x8b\xa9\x35\x35\x69\xd2\xbf\x83\xfd\xa6\x77\xc9\xcb\x7d\ +\xbf\xbc\xbb\x7b\x1c\xf0\xdf\x45\x6e\x2f\x17\x34\x6d\x58\x94\x83\ +\x29\x02\x47\x01\x4c\xb4\xe9\x55\x02\x58\x97\x2b\x81\xbd\x42\x21\ +\x53\x6e\x0a\xb0\xa0\x69\xc3\x5c\x0e\xde\x01\x1c\x69\xd3\xd8\x26\ +\x2a\xca\x15\x9a\xb1\x20\x24\xa7\x34\x51\x0e\xa6\x3a\x6f\x0e\x00\ +\x1c\xa9\xc8\x66\xca\x1a\x39\x02\x7c\x97\xbd\x4b\x22\xd5\x8a\x86\ +\x5c\xb2\x7e\xad\xb9\xa1\x67\x5d\xf7\x4b\x33\x29\x6a\x82\xff\x9a\ +\xdb\xb1\x02\xbd\xd2\x00\xa0\x61\x0f\xcc\xc7\x36\xc2\x64\x9a\x73\ +\x0d\xcf\xd5\xf8\x96\xd3\x24\x12\x49\x82\x85\x28\x8e\x06\x3e\xef\ +\x73\xb9\x9c\xd9\x32\xc0\xfc\x72\x7c\x9b\x84\xd8\x07\x51\x03\x18\ +\x81\xd2\x4e\x93\x30\x33\x40\x84\x37\x31\x72\xbb\x18\xdd\x58\xb9\ +\xca\x67\x5e\xbc\x02\xd4\x96\x40\x51\x13\xab\xc4\x74\x60\x87\xf2\ +\x23\x02\x66\x4d\x12\x17\xb1\x58\x2c\xe0\x1b\x00\xc0\x4e\xab\xc6\ +\x76\x88\x77\x33\x34\xed\x35\xbf\xfe\x6f\xed\x5d\xef\xc8\x87\xef\ +\x12\x80\xb1\x1a\x84\x24\x45\x00\xdc\xf9\x05\xf8\xd5\x68\x0c\x3d\ +\xeb\xb8\xe9\xec\x52\xd4\x04\x00\x6c\x5a\x63\xc1\xc2\xf3\xe9\xea\ +\xfb\x31\x1c\x00\x0c\x00\xfa\x0e\xd0\x72\xd7\x73\x13\x81\xd2\x8a\ +\x9a\x70\x6c\xdd\x00\x4a\x56\xd0\xa7\x0a\xb0\x6e\x45\x5d\xa9\x80\ +\xbb\xa8\x28\x57\xa4\x3d\x6b\xd4\xcb\x0a\x94\x00\x3e\xac\xbf\x11\ +\x03\x75\xed\x57\x51\xd7\x3f\x00\x0e\x75\xc4\x8a\x79\xcd\xc8\x9f\ +\x9c\x79\x49\xad\x55\x80\x20\x8c\x8e\x98\x03\x55\x32\xc5\x8d\xd7\ +\xe4\x9f\x25\xa8\x8a\x24\x18\xaf\x6d\xdb\x33\x76\xaf\x2f\x4f\x9f\ +\xbd\xa6\xd7\x2e\x0e\x4f\x8f\x0f\x9f\x93\x53\x91\x73\x92\x28\x0c\ +\x48\xe3\x00\x64\x5f\xb6\x40\x91\x88\x92\x86\x9e\x3d\xf6\xf1\xdd\ +\x40\xf8\x02\x67\xdb\x80\xa5\xc9\x72\x5a\xc9\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x34\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xe6\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xcb\x6e\xd3\x40\x14\x40\xcf\x0d\x2c\x80\xcf\x48\xb3\x69\x0a\ +\x8b\x24\x3b\xd6\x69\x36\x48\xb4\xb5\xc3\x4b\x42\x2d\x10\x5b\xf0\ +\x01\x48\x7c\x03\x4b\x76\x48\x24\x40\x05\xe5\xd5\x26\x1f\xd0\x76\ +\xcb\x36\x29\x8f\xda\xbc\x62\x5e\x12\xfc\x01\xb0\x69\x2e\x8b\xd4\ +\xc1\x8e\xed\xc4\x29\xd9\x20\xee\x6a\x6c\xcf\xdc\x73\xe6\xce\xe8\ +\xca\xf0\xbf\x87\xf8\x83\x4a\xd5\x3e\xa9\xaa\xb7\x81\xa3\x2a\xdc\ +\xd8\xde\xa8\xb7\xa6\x09\x2a\x57\x2d\x43\x94\x9b\xc0\x2f\x54\xaf\ +\x6d\xb5\x1a\xcf\x01\x32\xfe\x04\x55\x6d\x00\x27\x80\x9c\x28\xeb\ +\x15\xc3\x3a\x37\x2d\x78\xa5\x6a\x9f\x17\x65\x1d\xc8\x01\xc7\x11\ +\xa9\xfb\xdf\x32\x7f\xa6\xe9\x91\xc0\x9a\x8c\x0a\x8f\xa6\x21\x51\ +\xa9\xda\xe7\x55\x75\x2d\xcc\xe2\x58\x44\x40\xc9\x5c\x07\x7a\xd3\ +\x94\xa8\x18\xd6\xb9\x18\x78\x0f\xd1\xeb\xfe\xc3\x21\x7f\xe0\xb9\ +\x6d\x77\x26\x5f\x7c\x0f\x2c\xf1\xe7\x6e\x08\xc2\x52\x6e\xb6\xf8\ +\xb6\xeb\xb6\x77\x27\x86\x0b\x8f\x22\x70\x58\xd9\x6a\x36\x9e\x44\ +\x04\xf6\x25\x5e\xc7\x48\x64\x26\x95\xd8\x87\xaf\x0d\xe5\xdf\x87\ +\xd7\x1f\x06\xe7\x86\x04\x7c\x89\xec\x6c\xe1\x83\x88\x44\x24\xb2\ +\xf9\xd2\x1b\x6f\x8c\x44\xd9\xb4\xcf\xd2\xdf\xf9\x58\x78\xac\x40\ +\x5f\xa2\xf3\x2a\x4e\x42\xc0\x18\x25\x51\x36\xed\xb3\x82\x0e\xc3\ +\x35\x09\x9e\x28\xe0\x4b\xe4\xe6\x4a\x5d\x60\x31\x8d\xc4\x7c\xb5\ +\x76\x46\xe0\x71\x0c\x7c\x39\x09\x3e\x52\x00\xa0\xeb\xb4\x13\x25\ +\x66\xe6\x0a\xae\xe7\x74\x1c\x1f\x8e\xca\xc4\x70\x02\x49\x47\xc6\ +\xbc\x69\x5d\x04\x56\x09\xdf\xe8\x3d\x44\x2f\xf4\x51\x31\x70\xd5\ +\x95\xad\x56\xe3\xc1\xb8\xdc\xa9\x04\x92\x24\x04\x7a\xda\x1f\x06\ +\xc5\x52\xc3\x61\xcc\x11\x04\xc3\x73\xdb\x2f\x67\xf2\x45\x8f\xe1\ +\x3e\x11\xde\xc4\x44\xf0\x89\x04\x02\x12\xdd\x21\x89\x01\x5c\x85\ +\x4b\xdb\xcd\xf4\x70\x08\x97\x2e\x55\x28\xf2\x93\xfe\x05\x0b\x87\ +\x88\x66\x7a\xfc\x98\x34\xdf\x44\x15\x28\x9b\xb6\x29\xe8\x93\x84\ +\x75\x82\x60\xe6\x66\x8b\x4e\xd7\x6d\x3b\x53\x17\x28\x57\x2d\x43\ +\xe0\x29\x70\x38\xf0\xda\xaf\x44\xb0\x63\x9a\xd9\x7c\x69\xd7\x73\ +\xdb\x6e\x9a\xbc\xa9\x8e\x60\xff\x67\x22\x02\x17\xf4\xb2\x0a\x97\ +\x08\x1f\xc9\x21\x41\x9f\x96\x4d\xdb\x4c\x93\x7b\x6c\x05\xe6\x0d\ +\x7b\x49\xe0\x59\x1c\x7c\xb3\xd9\x58\xf5\x9c\xf6\x8b\x5c\xbe\xf0\ +\x09\x64\x81\x70\xb3\x4a\x55\x89\x91\x02\xf3\x86\xbd\x84\x68\x04\ +\x8e\xca\x95\xad\x56\x7d\xd5\x7f\xd1\x75\x3b\x49\x12\x46\x36\x5f\ +\x72\x46\x49\x24\x0a\x8c\x86\xdf\xb9\x3f\x3c\xbf\xeb\x76\x5e\xcc\ +\xcc\x96\x3e\x23\x4c\x24\x11\x2b\x50\x31\x6b\x8b\x08\xeb\x69\xe1\ +\x7e\x78\x6e\x7b\x27\x51\x62\xae\xb8\xeb\x39\x51\x89\x88\x40\xc5\ +\xac\x2d\x2a\x12\x81\xab\x50\xdb\x6e\xd6\x13\xe1\x41\x89\xec\x5c\ +\xf1\x8b\xc0\x69\x86\xef\x44\x8c\x44\x48\xa0\x5c\xb5\x16\x40\x36\ +\x62\xe1\x1b\xf5\x7b\xe3\xe0\x03\x09\x27\xbd\xc4\x40\xa0\x6c\xd4\ +\x4e\x09\xd2\xfa\x5b\x78\x50\x22\x97\x2f\x7c\x05\x89\x48\xe4\xf2\ +\x85\x9d\xae\xdb\x79\x07\x81\x3e\x90\x11\xb9\x35\x0c\x17\xd4\x3a\ +\x08\xdc\x8f\xcd\x66\xe3\xae\xa0\x16\xe1\x3e\x71\x58\x91\x5b\x03\ +\xee\x80\x86\x06\x7f\xc9\x55\x50\x6b\xb3\xd9\xb8\x7b\x50\xf8\x18\ +\x89\xbd\x88\x40\x46\xf5\x2a\xe0\x01\xdf\x51\x5d\x99\x06\x3c\x28\ +\x01\x2c\x23\x7c\x03\x3e\x4a\x8f\xab\xd3\xca\xfd\xef\xc7\x6f\xcf\ +\x0b\x86\xc1\xfd\xdf\x90\xb9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x02\x25\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd7\x49\x44\x41\x54\x58\x85\xed\ +\x95\x3d\x68\x13\x51\x1c\xc0\x7f\xff\x77\xfd\xc2\xc1\x28\x2d\x3a\ +\x74\x29\xda\x0e\xea\x10\xb1\x9b\xa5\x50\xc4\x24\x94\xc6\xc1\xe6\ +\x4e\xf0\x0b\xc1\x26\xd6\x2e\xdd\x9c\x83\x9b\x7b\xb7\x0c\xd2\xcd\ +\xc5\xa1\x4a\x44\xac\x8b\x07\xe9\x22\xd8\x51\x27\x3f\x26\xc7\xd2\ +\x49\x38\xcf\x7b\x7f\x87\x5c\x6c\x42\xaa\x4d\x0f\xab\x14\xee\xb7\ +\x1c\x77\xf7\xff\xf8\xbd\x7b\xef\xde\x83\x94\x94\x94\x94\xff\x8c\ +\x24\x4d\xbc\xe4\xdd\x1f\x75\x6c\xf4\x02\x34\x4b\x68\x47\x5f\x3f\ +\x7f\xfc\x35\x49\x1d\x93\x24\x29\x57\x5a\x9c\x70\x6c\xd8\x00\xcd\ +\x02\xd0\x2f\x1b\x05\x6f\x61\xfc\x9f\x08\xe4\xbc\xca\x79\x88\x1a\ +\x20\x63\x0a\x28\x00\x32\x66\x55\x1a\x85\xab\x77\xb3\x07\x2a\x50\ +\x70\xcb\xd3\x58\x7c\xe0\x04\xa0\x02\x91\x40\x04\x28\xca\x49\x6b\ +\x8c\x5f\x70\xcb\xd3\x07\x22\x90\x77\x2b\x45\xab\xac\x83\x1e\xd5\ +\xe6\xc0\x6d\xdb\x6b\x0b\xaa\x40\xc6\x2a\xeb\x97\xe7\x17\xe6\xfe\ +\xaa\x40\xae\x54\xbe\xa5\xaa\x6b\xc0\x10\xaa\x2a\x9d\xcd\x63\xc4\ +\xaa\xa2\xc0\x90\x88\x3c\xcb\xbb\x95\x9b\xbd\xd4\x76\xf6\x0a\xc8\ +\x97\xca\xcb\x40\x0d\x30\x8a\xaa\x88\xec\xd2\x3c\x56\x10\x94\xe6\ +\x9f\x65\x80\xf9\x53\x67\x26\xb7\x3e\x7d\xd8\x7c\x9b\x54\x40\x72\ +\xa5\xca\x43\xe0\x51\x7c\x6b\xa5\xb5\xe6\xfe\x8c\x8a\xc4\x3e\xc2\ +\xec\xf8\xb9\x0b\xf2\xf1\xfd\xa6\xbf\x2f\x81\x6a\xb5\x6a\x06\x46\ +\x26\x56\x80\x07\x71\xa9\xd6\x1c\xf7\x8c\xec\x5c\x66\x4e\x9f\x9d\ +\x1c\xbe\x7d\xed\xca\x2b\xdf\xf7\xbb\x6a\x74\x6d\x44\x9e\xe7\x0d\ +\x6c\xdb\xcc\x2a\x70\x3d\x0e\xd9\x77\xf3\xb6\xf2\x02\xda\x5a\x67\ +\x4f\xb6\x86\xcd\x9d\x77\xb5\x5a\xf8\x5b\x81\x62\xf1\xde\x91\x60\ +\x30\x7a\x0a\x32\x8b\x02\x46\x2c\x9a\xb4\xf9\x2f\x07\x51\x55\xd3\ +\x6c\xa4\x2f\x07\x03\xc7\xad\xd7\x6b\xdf\xba\x04\xe6\x6e\x2c\x1d\ +\xff\x1e\x84\x75\xe0\x62\xfc\xc8\xd2\xdb\x9c\xef\xed\x80\x88\xee\ +\x7c\x89\x8d\x30\xfa\x51\x7c\xb3\xb6\xba\x0d\xd0\xd7\x0a\x0a\x82\ +\xf0\xb3\x40\xa6\x2d\x2f\xd1\x36\xbd\x1b\xda\x39\x8e\xa9\x7e\xa7\ +\xef\x0b\x70\xac\xa3\x49\xe2\x53\x29\x25\x25\x25\xe5\xb0\xf3\x13\ +\x19\xff\x9a\x58\xf0\x37\x9f\x0a\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x03\xd3\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x85\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x4d\x68\x9c\x55\x14\x86\x9f\xf7\x66\xd2\x1f\xa1\xb5\x95\xa2\ +\x29\x36\xb4\x06\xad\x9a\x8d\x81\xd4\x49\xb2\xf0\xa7\xa5\xb4\x54\ +\x69\x93\x9a\x18\x11\xa9\x85\xa2\xb8\x70\x27\x08\x29\x2e\xa2\x28\ +\x1a\x70\xa5\x14\x45\x11\x44\xd1\x4d\x68\x33\x69\xa2\xa9\x16\x2c\ +\xe9\x42\xda\x69\xac\xa5\x0b\x43\x41\x88\xa0\x93\x46\x11\x94\x6a\ +\xb5\x3f\xcc\x77\x5f\x17\x33\x49\x93\x4e\x92\x26\x64\xe2\xa6\x67\ +\x73\x3f\xce\x77\xbe\xf3\x3e\xf7\x7e\xf7\xe7\x5c\xb8\xd9\x4d\xf3\ +\x09\x7e\xb0\xd7\xd5\x15\x09\x2d\x96\xb7\x5a\x54\x63\xd6\x09\x02\ +\x30\x8a\xc8\x19\x1d\x57\x42\x26\xdb\xa6\x1f\xcb\x0a\xd0\x94\x71\ +\x3a\xda\x5d\xc0\xe6\x39\x26\x1d\x4a\xa4\xfd\x43\xbb\xf5\xcd\x82\ +\x00\xea\xbb\x7d\x6b\x2a\x15\xdf\x07\x3d\x5d\x74\x8d\x61\xf7\x3b\ +\x84\x23\x4a\x18\x59\x12\x19\xbb\x92\x22\x3a\x52\x25\xb1\x41\x8a\ +\xdb\x40\xcd\xc0\xfa\x62\xf6\x01\x82\xf6\x65\x9b\xf5\xdb\xbc\x01\ +\x9a\x0e\xfb\xee\x98\xb8\x0f\xb8\x1f\x18\x13\xea\x5c\xb6\x9a\x8f\ +\x07\x37\x2b\x3f\x6b\x97\x3a\x1d\xd2\x75\x3c\x25\xfb\x0d\xa0\x46\ +\xe2\xe7\x68\xed\x3a\xf5\x84\xce\xce\x19\x60\xd3\x41\xd7\x54\x04\ +\x67\x81\x35\xc0\x61\x96\xe9\xd9\xec\x63\xfa\x6b\x56\xe1\xeb\x6c\ +\xc7\x80\x97\xfe\x71\x39\xbe\x07\xda\x87\xf9\x27\x58\x0f\x9d\x68\ +\xd3\x99\x1b\x02\x34\x0c\x78\x25\x97\x7d\x02\xa8\x05\xbf\x93\x3d\ +\x1b\x5e\xe2\x35\xc5\xf9\x88\x4f\x98\xad\x86\x5e\x3a\xb0\xdf\x04\ +\x72\x79\x2b\x7d\xba\x55\x63\x93\x43\x42\xc9\x47\x57\xe2\x01\xa0\ +\xd6\xa6\x7f\x41\xe2\x00\x92\xb3\x2d\x74\x19\x7f\x04\xac\x4b\xc9\ +\x9f\x61\x4f\xe9\xf4\x14\x80\xf4\x41\x6f\xc2\xda\x63\xf8\x3d\x49\ +\xb4\x67\x41\xe2\x93\x20\x2e\xe6\xc3\x8b\xc0\x39\x60\x4b\xc3\x21\ +\x76\xcc\x08\xa0\x0a\xbf\x05\x10\xac\xd7\x4f\xb7\xeb\xc2\x82\xc5\ +\x8b\x36\xdc\xae\xab\x42\xaf\x14\x14\xdd\x35\x79\x14\x26\x1e\xea\ +\x0f\x79\x6d\x4a\x1e\x05\xfe\xfc\x3b\xaf\xb5\xc3\xed\xba\x5a\x2e\ +\x00\xa0\x30\x1f\x32\x1e\x06\xee\x33\xaa\x1b\x5f\x15\x13\x23\x90\ +\x0a\xec\x04\x84\xfc\x65\xd9\xc5\x01\x24\xcb\xee\x03\x08\x8e\xbb\ +\xc7\xdd\xd7\x7e\x81\xe3\xa3\x85\x26\x7c\x55\x76\xf1\xa2\x45\x85\ +\xaf\x01\x2c\x6d\x29\x05\x40\xd5\x85\x86\x9f\x16\x0b\x20\x88\x11\ +\x00\xcc\xba\x69\x00\x0a\xce\x20\xc6\x58\x24\x5b\xbd\xb4\x98\x5b\ +\xdc\x39\x3e\x11\x4b\xf7\x81\xff\xcb\x5e\xa5\x04\x60\x14\xc0\x91\ +\xaa\xc5\xd2\xbc\x70\x69\x22\xf7\xf9\xf1\x3d\x66\x12\x80\x7f\x01\ +\x70\xe0\xae\xc5\x02\x48\xa0\xa6\xf8\x98\x1b\xf7\x4d\x00\xd8\x61\ +\x10\x20\x38\x6e\x5f\x2c\x00\x14\xb7\x15\xd5\x8e\x95\x00\x54\xa6\ +\xe8\x07\x30\x7a\xbc\xfe\x03\x57\x96\x5d\xdc\x16\x68\x17\x40\x54\ +\xc8\x94\x00\x7c\xdb\xac\xf3\xc0\x31\x60\x4d\xe5\xed\x3c\x57\x6e\ +\xfd\xc6\x1e\x76\x02\xb5\xc0\x0f\x43\x2d\x4c\xd4\x06\x53\x56\x41\ +\xb4\x3a\x0a\xb0\xee\x6c\x18\xf0\xca\x72\x89\xd7\x76\x7b\x89\x55\ +\x38\x67\x14\xb4\x1f\xc9\xd3\x02\x0c\xb5\x6a\xc8\xf8\x73\xe0\x0e\ +\x2e\xfb\x53\x3a\xbd\xf0\x65\x6a\x6b\x45\x2a\xbe\x4b\xa1\xf7\x83\ +\x27\x9b\xf9\x62\xf2\xeb\x12\x81\xe4\xda\xd1\xd9\x9c\x7e\x20\xbe\ +\xbd\x20\x08\x5b\xe9\x5e\x5e\x06\xbd\x00\x9c\x4f\x55\xe8\x99\xc9\ +\xbd\x87\x19\x4a\xb2\x62\x3d\x98\x05\x6e\x03\x7a\x96\xe7\xb5\x77\ +\xb0\x5d\x17\xe7\xa3\x5d\xdb\xed\x25\x2b\x52\xf1\x00\xe8\x79\xe0\ +\x5f\x47\x3d\x72\xaa\x4d\xdf\x5d\x1f\x37\x63\x51\x9a\xee\xf1\x46\ +\xe1\x3e\xe0\x5e\x60\xd4\x52\xe7\x2d\xab\xf8\x64\x2e\x45\x69\x63\ +\x1d\x6d\x2e\x14\xa5\xf7\x00\x39\x59\xcd\x27\x5b\xf5\xfd\x74\xe1\ +\xb3\x96\xe5\x75\x19\xaf\x5a\xea\xf8\x21\xe8\xc9\xa2\x2b\x67\xbb\ +\x3f\x54\x84\x23\x49\x9e\x91\x54\x64\xec\x52\x25\x71\x79\x42\x55\ +\x02\xeb\x43\x88\xdb\x5d\x28\xcb\xc7\x37\x9c\xa3\x31\xaf\xbd\x43\ +\xed\xfa\x75\x26\x8d\x39\x5d\x4c\xd2\x3d\x6e\x12\xee\x02\x1e\x9e\ +\x4b\xbc\xc5\x19\xa1\x8e\xec\x6e\x1d\xbd\x51\xec\xbc\xae\x66\x8d\ +\x19\x6f\x70\xa4\x05\x79\x2b\x50\x4d\xe1\x04\xad\x00\x72\x88\x1c\ +\xe8\x78\x48\xc8\x9c\x68\xd3\xb9\xf9\xe4\xbd\xb9\xed\x3f\x89\x47\ +\x63\xa6\x91\x26\x12\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\xf0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x6f\x28\xc0\x02\xfe\x2d\x80\ +\x8c\xf0\x68\x0c\xac\xb7\x31\xa0\xb5\xcf\x5d\xfb\x5c\xd9\x30\xe5\ +\xf8\x0f\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ +\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ +\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ +\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\ +\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\ +\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\ +\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\ +\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x3d\x9d\xfa\x04\x75\x0c\ +\x2b\x93\xd0\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x41\x49\x44\x41\x54\x58\x85\xed\ +\xd3\xa1\x11\xc0\x20\x14\x04\xd1\x85\x9a\x28\x00\x93\x5a\x70\x14\ +\x83\x4a\x31\x99\xa1\x81\x14\x85\xc2\x22\xf9\x66\x9f\x3a\xb7\xea\ +\x40\x92\x14\x2c\xed\x51\xda\x98\x40\xbd\x54\xfd\xfe\xb7\x3f\x00\ +\xf9\x4a\x50\x3a\xf0\x05\x92\x24\x85\x5b\x1c\x18\x0a\x07\xd4\x09\ +\xe9\x09\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xd2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x84\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xb1\x0d\x82\x50\x18\xc4\xf1\xff\xf7\xdc\x81\xc4\x3d\x18\x80\ +\x4d\x2c\x6c\xe8\x1c\x41\x98\x81\x06\x13\x6b\x67\xb0\xb4\x77\x10\ +\x13\x76\xd0\xb3\x52\x21\x24\x76\x0f\x9a\xfb\x75\x97\xf7\x25\x77\ +\xc5\x03\x33\x33\xb3\x95\xc5\x34\x2a\xaa\x63\xb3\xc9\x59\x78\x6b\ +\x9b\x27\x84\x66\x03\xca\xba\xab\x90\x2e\xc0\x36\xe7\x80\x80\x01\ +\xb4\xbb\x9f\x0e\x57\x80\xf4\x7d\x91\xfa\xdc\xe5\x00\x82\xe2\x45\ +\x3a\x7f\x72\xfa\x77\xbc\x84\xdf\x80\x88\x1a\x78\xe4\x2e\x0c\x18\ +\x14\xec\x47\x79\x6c\xf9\x4f\x68\x66\x66\xb6\xba\x37\x95\x79\x1e\ +\x09\xc0\xb2\x67\x2f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\x85\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xfd\x87\x04\x31\x08\x1d\x02\ +\x9e\xbe\x7f\x22\x47\x2c\xca\xea\xc9\xea\xd9\x7c\xbc\xcd\xf8\x22\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x0f\ +\x7e\x19\x07\x85\xa1\xbf\xac\xe9\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\xd2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x84\x49\x44\x41\x54\x58\x85\xed\ +\x97\xcd\x4a\x23\x41\x14\x85\xbf\xd3\xba\xd5\x85\x32\xfa\x26\xe9\ +\x0c\x8a\x2f\x90\x61\x04\x03\x3e\x84\x60\x56\x62\xe6\x11\x26\x82\ +\x0b\x23\xb8\x1f\xdc\x0d\xd8\xe0\x22\x2f\x30\x20\xa6\x7d\x13\x15\ +\x07\x24\x6b\xfb\xcc\xc2\xae\x20\x49\x6c\x31\x76\x74\xc0\x3e\xab\ +\xe2\xd6\xa5\xce\x57\x3f\x14\xf7\xc2\x67\x97\x46\x03\xf5\x33\xaf\ +\x65\xb8\x8d\xa8\x0b\xbe\x94\x61\x62\xb8\xc5\xf4\x23\xd4\xe9\x37\ +\x75\xf1\x2c\x40\x9c\x78\x0f\x7c\x30\x09\xac\x24\x65\x58\xfb\x69\ +\x53\x87\x63\x00\x71\xe2\x75\xf0\x1f\xe0\x1e\xab\x15\x3d\xd0\xbb\ +\xdc\xd6\xdf\x32\x5c\xbf\xfe\xf6\x52\x36\x47\x03\xb9\x0b\x2c\xca\ +\xda\x08\x27\x31\x1f\x92\x6c\xef\x4b\x08\xab\x95\x36\x75\x5a\x86\ +\x71\x50\xbe\x91\xd3\x5a\x62\x09\xff\xca\x70\x1b\xf8\x0e\x10\x0d\ +\xb3\x44\x1d\x20\x7a\xa0\x57\xa6\xf9\x88\x7a\x00\x12\x71\x08\x0c\ +\x01\xc2\x83\x2b\xeb\xd8\x27\xe9\x6a\x4b\x77\xf9\x70\x65\x0c\xe0\ +\xa3\x54\x01\x54\x00\x1f\x0e\x30\xff\x52\x42\x7c\xe6\x1d\xe4\x9f\ +\xc0\xc2\x2b\xd7\x1e\x60\xfd\x48\x9b\x3a\x29\x4a\x2a\x3c\x81\xf8\ +\xdc\xab\xc8\xc7\x53\x98\x03\x2c\x20\x77\xe3\x73\xaf\x4e\x0d\xf0\ +\x1e\x2a\x04\x48\x37\x75\x8d\xb5\x0b\x0c\xa6\x58\x7b\x80\xd5\x4a\ +\x37\x75\x5d\x94\xf4\xe2\x1b\xc8\xef\xb0\xf0\x1e\xdf\xa2\xff\xfb\ +\x0a\x2a\x80\x0a\xe0\x5d\x01\x0c\xb7\xf0\x58\x40\xce\xca\xac\x96\ +\x78\x39\x1f\xde\x8c\x01\x60\xfa\x00\xd9\x1c\x8d\x59\x01\xc0\xe3\ +\xda\x36\x69\x08\x0c\x3f\xa2\x08\x75\x8c\xbf\x21\x77\x6b\x89\x05\ +\xf4\x9e\xd4\x70\x6f\x52\xbe\xf3\x86\xf0\x11\x90\x45\xa8\x13\xe6\ +\x26\x35\x26\x1d\x66\xf7\x36\x9e\x6f\x4c\x82\x42\x6b\x96\x97\xce\ +\x2b\xa3\xf3\x53\xea\xc6\x26\x9d\xd4\x9a\x55\xfa\x07\xf1\xe4\x84\ +\x86\xea\x09\x57\xf9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x04\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x3c\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x88\x1c\x45\x14\xc6\xbf\xd7\x33\x99\xc4\x3f\x2b\x62\x16\ +\x15\x24\x78\x11\xff\x5c\x04\x77\x3b\x7a\xf0\xe0\x22\x26\x12\xc1\ +\x3f\x2c\x22\x1e\x04\x35\x9a\x99\xd9\x24\x33\xbb\x11\x09\x28\xea\ +\xb8\x98\x80\x41\x31\x6e\x8f\xba\x99\x4e\xc4\x1c\x44\xd1\x53\x0c\ +\x62\x64\x83\xb0\x90\x83\x91\xd9\x59\x30\x20\x82\x78\x10\x11\x49\ +\x84\x28\xea\x06\x75\x37\x5d\x9f\x87\x5d\x35\xe9\xea\x68\x26\xa9\ +\xaa\x2e\x70\x7e\xc7\x3a\xd4\xf7\xea\xab\x57\xaf\x5f\x75\xcf\x00\ +\x3d\x7a\xf4\xf8\x3f\x23\xa6\x26\x0a\xcb\x13\xcf\x43\xe4\x19\x01\ +\x48\xca\xb6\x99\xb8\x36\x6e\x6a\x6e\x9b\x04\xc6\x66\x12\x79\x16\ +\x40\x81\x40\x11\x82\x46\x58\x6d\x0e\x19\x9b\xdb\x22\xe6\x0c\x38\ +\x6d\x2e\x0a\xc8\xfd\x03\x23\x13\x83\x06\xe7\xb7\x82\x31\x03\x08\ +\xa8\xd4\x50\x5f\xa0\xe4\xe3\x70\xe4\xd5\xeb\x4c\x69\xd8\xc0\x98\ +\x01\x02\x30\x63\xb8\x1f\x2a\x38\xb8\x7a\xe3\xeb\xab\x4c\xe9\x98\ +\xc6\xe4\x11\x38\x13\xab\x98\x24\x53\x83\xe5\x97\xfb\x1d\x68\x75\ +\x8d\x0b\x03\x00\xe0\x7a\x91\xd2\x81\x5b\xd7\xef\xe8\x73\xa4\x77\ +\xd6\x58\x33\x80\xd4\x8e\x44\x38\xbf\xec\x82\x7d\xd7\xd4\xa2\xe5\ +\xb6\x34\xcf\x05\x6b\x06\x88\x40\x21\x55\x17\x08\xdc\x7e\xe9\x3c\ +\xde\x19\x6a\x34\x8a\xb6\x74\xbb\xc5\xf6\x11\x50\x80\xa4\x33\x61\ +\x78\xee\xe8\x65\xbb\x00\x1a\x6b\xc2\xce\x07\x07\x35\x80\x0a\x4c\ +\x9b\x20\x8f\x85\xe5\xe8\x45\xfb\xda\xff\x8d\x9b\x22\x28\x4c\xf7\ +\x08\x80\xc8\xd6\xb0\xda\xdc\xea\x44\xff\x5f\x70\xf5\x14\x00\x80\ +\x44\x1b\x21\x77\x0c\x96\x27\x1e\x77\x18\x83\x86\x4b\x03\xb2\xba\ +\x45\x88\x48\x6b\x75\x25\x1a\x76\x19\xc7\xa9\x38\x35\x60\xa9\x5b\ +\x4c\x9b\x10\x10\x78\x37\xdc\x10\xdd\xe1\x32\x96\xbf\xc5\x73\xd0\ +\x24\xa0\xd5\x84\x12\x02\xec\x0b\xab\xd1\xcd\xae\x83\xc9\xc3\x00\ +\x00\x42\xea\x85\xf1\x22\x10\x1f\x0d\x6c\xdc\x79\x83\xcb\x48\x72\ +\x32\x00\x10\x0a\x33\x6a\xc2\x4a\x49\x8a\x07\x6f\xda\xf4\xda\xd5\ +\xae\xe2\xc8\xcd\x00\x60\xb1\x26\xa4\x4d\x10\xf0\xaa\xc2\x49\x35\ +\x75\x63\x75\xf2\x72\x17\x31\xe4\x6a\x00\xb0\x64\x82\x7e\x6f\xb8\ +\xb6\xc4\x85\x03\xb7\xd4\xa2\x4b\x6c\xeb\xe7\x6e\x00\xb0\x78\x6f\ +\xa0\xfe\x3e\x61\x20\x59\xc0\xfe\xa1\x47\xde\x5a\x61\x53\xdb\x0b\ +\x03\x00\x40\x00\x85\x74\x26\x10\xb7\xcd\x95\x7e\x7d\xcf\xe6\xe5\ +\xc9\x1b\x03\x00\x00\x92\x61\x82\xe0\x9e\x13\xc7\xfa\xf7\xa0\xd1\ +\xb0\x12\xab\x5f\x06\x00\x80\x88\x62\xea\x06\x49\xf2\xe1\xf0\xe8\ +\xca\x97\x6c\xdc\x20\xfd\x33\x00\x84\x80\x0a\xd4\x5e\x31\x3e\x11\ +\x96\x9b\x4f\x99\x56\xf3\xd0\x80\x45\x44\x24\xd1\xca\xa2\x60\x7b\ +\x58\x8d\x2a\x26\x75\xbc\x35\x80\x00\x32\xba\x45\x80\x98\x0c\x2b\ +\xd1\xfd\xa6\x74\xbc\x35\x00\x00\x24\xbb\x65\x16\x00\x4d\x53\x1a\ +\x5e\x1b\x00\xe0\x4c\x75\xcf\xd8\x63\xd1\x9b\x97\x93\x59\x2c\x2d\ +\x3d\x6b\x93\xde\x34\xa5\xe1\xaf\x01\x02\x28\xa2\x90\xde\x7f\x81\ +\x6c\x6a\xb7\x6a\x6f\x98\x92\xf1\xd4\x00\x01\x49\x6d\xf1\xa4\x3c\ +\x37\x13\x9b\x5b\x3c\xe0\x6f\x0d\x08\xb4\x9d\x17\x44\x9d\x78\xf3\ +\x36\xd3\x42\x1e\x66\x80\x04\x7a\xe5\xe3\xdb\xed\x2b\x7e\xdc\x92\ +\xf1\x8d\xe1\xbc\xf1\x2b\x03\x08\x6d\xf1\x02\x7e\x48\xae\x58\x8f\ +\xf1\x71\xbd\x27\x30\x80\x47\x06\x48\x00\x41\x6a\xf1\x38\x54\xbc\ +\x30\x79\xa0\x13\x57\x16\x6c\xa9\xfa\x71\x04\x88\x00\x72\xfa\xce\ +\x13\xf8\x9c\x5c\x7e\xf7\xa7\x3b\xeb\xbf\xd9\x94\xf6\x21\x03\x24\ +\xbd\xf3\x20\xbe\x2e\x26\xea\xce\x4e\x5c\xf9\xd9\xb6\x78\xae\x06\ +\x70\xb1\xd7\x09\x52\x83\xdf\x17\x83\x64\xcd\x67\x7b\xc6\x8e\xb9\ +\x88\x21\xcf\x23\x20\xa2\x6f\xc0\x4f\xc2\x60\xed\xe1\x5d\xf5\x6f\ +\x5c\x05\x91\x4b\x06\x50\x32\x76\x1e\x38\xa1\x02\xdc\xd5\xde\xbd\ +\xf9\x0b\x97\xb1\xe4\x61\x80\x08\x35\xdd\x05\x12\xc3\xb3\x93\xf5\ +\xc3\xae\x83\x71\xfc\x71\x94\x59\x3b\x4f\x11\x3e\xd4\x89\xeb\x53\ +\x2e\x63\xf9\x0b\xa7\x35\x40\x20\xba\xe1\x64\xb5\xdd\x1a\x7d\xdf\ +\x65\x1c\xa7\xe2\x32\x03\x0a\xe9\x01\x01\x9f\x9e\x89\x47\x63\x87\ +\x31\x68\x38\x31\x80\x59\x3b\x0f\xbc\xd2\x6e\xd5\x73\xff\x99\x8c\ +\x83\x23\x20\x81\x40\xeb\xf2\xf6\x76\x5a\xb5\x27\x6d\x5c\x6e\xba\ +\xc5\x76\x06\x64\xdc\xec\xf0\x41\xdf\x95\xc7\x37\xf8\xb0\x78\xc0\ +\x62\x06\x90\x08\x24\xdd\xe2\x02\xd3\x17\xff\xd1\xf7\xe0\xf4\x78\ +\xfd\xa4\x2d\xdd\x6e\xb1\xf9\x43\xc9\xf4\xe2\x67\x0b\x25\xdc\x3b\ +\xbd\xf7\xd1\xdf\x6d\x69\x9e\x0b\xae\x1e\x83\x5f\xcd\xcb\xb2\x75\ +\x47\x9a\x23\xbf\x38\xd2\x3b\x6b\x5c\x18\xf0\x1d\xa9\xd6\x1c\x69\ +\x8d\xfc\xe0\x40\xab\x6b\x4c\xfe\x61\x22\xeb\x05\xfe\x71\x55\x48\ +\xd6\x76\xe2\xb1\x6f\x4d\xe9\x98\xc6\x58\x06\x64\xdc\xec\xe6\x44\ +\xa9\x75\xb3\xad\x2d\x5f\x9a\xd2\xb0\x81\xc1\x0c\xf8\xe7\x13\x16\ +\x21\x14\xf0\xbe\xf6\xee\xb1\xb6\xa9\xf9\x6d\x61\xf0\x5f\x63\xc1\ +\x76\x21\x12\x40\x12\x80\x2f\xb4\x5b\xa3\x9f\x18\x9b\xbb\x47\x8f\ +\x1e\x3d\x2c\xf1\x27\x17\xaf\x43\xaf\x5e\x06\xce\xc3\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x08\xd7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x89\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x6d\x70\x54\xd5\x19\x7e\xde\x73\x77\x37\xb0\x24\x7c\x64\x11\ +\x13\xd4\xd1\xa0\x65\x30\x54\x66\x60\xb3\x50\xd4\x46\xb0\x76\xa4\ +\x1d\xc1\x62\xbb\x56\xed\xa8\x80\x24\x21\x40\x56\x60\xac\x1d\x9c\ +\xd1\x4b\x5a\xa9\xf5\x2b\x26\xbb\x60\x08\x04\x0a\x2a\xd3\x19\xd3\ +\x11\xa6\x38\x80\x4c\x6b\xc3\x50\x0b\x21\x1b\xed\x50\x05\x3a\x7e\ +\x80\x94\x49\x88\x95\xcf\x60\x24\xd9\xdd\xf3\xf6\x47\x10\xee\xc7\ +\xee\x66\x6f\x72\x37\x86\x36\xcf\xbf\xfb\x9c\xe7\xbc\xfb\xdc\x77\ +\xcf\x3d\x7b\xee\x39\xef\x02\x03\x18\xc0\x00\xfe\x9f\x41\x7d\xf1\ +\x21\x13\xe7\x06\xaf\x52\x32\xa8\x10\x90\xb7\x80\x69\x1c\x08\x63\ +\x98\x31\x9c\x80\xa1\x00\x14\x80\xce\x01\x38\x07\xe6\x63\x20\x1c\ +\x02\x70\x50\xc4\x68\xcf\xfe\xda\xb2\x23\xe9\xf6\x96\xb6\x04\x78\ +\x8b\x83\x37\x0a\xc2\x1c\x66\xcc\x02\x61\x42\x0f\xc3\x1c\x61\xf0\ +\x0e\x21\x79\x63\xe3\xba\xc7\xc3\x00\xb1\xad\x26\x61\x7b\x02\x98\ +\x7c\x25\xc1\xbb\x19\xf4\x24\x80\xe9\xf6\xc6\xc6\x87\x04\xaa\x90\ +\xec\x7a\xa3\x69\x6d\x49\xc4\xae\xa0\xb6\x25\xc0\x5b\x5c\x35\x9d\ +\x88\x5e\x00\x50\x60\x57\xcc\x78\x60\xe0\x28\x98\x57\x34\xad\x0d\ +\xbc\x66\xc7\x88\xe8\x75\x02\xa6\xcc\xaf\xbc\x3a\xaa\x88\x97\x09\ +\xf8\x45\x12\x99\x24\xe0\x3d\x10\xd7\x4b\x29\x0e\x03\xb1\x4f\x1d\ +\x44\xa7\xa4\xe2\x68\x8b\x7e\x1d\x8b\x29\x83\xa2\x59\x60\xc7\x30\ +\x62\xe4\x49\xa6\xb1\x04\x9e\x0a\xc2\x0f\x01\x0c\x4e\x62\x7c\x0f\ +\xa4\x28\x6d\x5c\xb7\xf8\xa3\xde\xf8\xef\x55\x02\x0a\x16\x04\x27\ +\x83\xb1\x15\x40\x6e\x9c\xe6\x36\x00\xdb\x89\xb0\x8d\x14\xb1\x73\ +\xff\xea\xc5\x27\xad\xc4\x9e\xba\xb4\x62\x70\xe7\x57\x8e\x3b\x09\ +\x98\x09\xc2\xac\x04\x9f\x71\x01\xc0\xbc\x70\x4d\xe0\x0f\xd6\xdd\ +\x77\xa1\xc7\x09\xf0\x16\x87\x1e\x22\xe2\x0d\x00\x32\x4c\xa6\x98\ +\x83\x1d\x8a\xf3\x77\xff\xac\x5e\x78\xba\xa7\xf1\xb5\xc8\xf7\xab\ +\x2e\xf7\x88\xec\x22\x22\x7a\x86\x81\x51\x26\x01\xd3\xca\x70\xee\ +\x97\xcf\xa0\xbc\x5c\x5a\x8d\x6d\x3d\x01\xaa\x2a\xbc\x27\x46\x3e\ +\x4b\xe0\xe5\x86\x16\x49\x84\x0d\x22\x8a\xf2\x86\xda\xc0\x71\xcb\ +\x71\x53\xc0\x6d\xf3\x9e\xcf\xea\x70\xb8\x97\x81\xf8\x09\x00\x99\ +\x86\xe6\xad\xed\x8a\xf2\xf0\xc1\x57\x17\x9d\xb7\x12\xd3\x5a\x02\ +\x54\x55\x14\xb4\x8c\xdc\x0c\xe2\x07\x74\x3c\xa3\x19\x02\xb3\xc3\ +\x6b\x02\xfb\x2d\xc5\xeb\x21\xa6\xcc\x0f\x5e\x1b\x53\xb0\x05\xe6\ +\x09\xf7\x03\xc5\x85\x69\x0d\xa1\xc0\xb9\x54\x63\x09\x2b\x1f\xec\ +\x6b\xcd\x5e\x61\xbc\x79\x02\xf6\x31\x62\x05\x7d\x75\xf3\x00\xd0\ +\x50\x1b\x38\xee\x74\x47\x0b\x19\xd8\x6c\x68\x9a\x28\x3b\x79\xb3\ +\xdf\xff\xa6\x92\x6a\xac\x94\x85\xbe\x92\xd0\xcf\x19\x08\x69\x39\ +\x22\xda\x34\xa4\x23\xcb\xbf\x77\x7d\xe9\x99\x54\xe3\xd8\x85\xe3\ +\xfb\xde\x89\xb6\x34\x6d\xdf\x32\xda\xd7\xd8\x0e\xe0\x2e\x5c\x1a\ +\xcd\x34\xf6\xcc\xa0\xb6\x41\xcd\x4d\x3b\xff\x9c\x4a\x9c\x94\x1e\ +\x81\xc9\x25\xa1\x02\x09\xde\x03\x60\xd0\x65\x96\xdf\x08\xd7\x04\ +\x1e\x49\xc7\xea\xcc\x2a\x0a\x8a\x83\x4b\x40\x78\xc5\x40\x3f\x1a\ +\xae\x09\xbc\xd6\x5d\xdf\x6e\x1f\x81\xc9\x8b\x56\x79\x62\xc0\x56\ +\xe8\x6e\x1e\xfb\x33\x3b\x86\x16\xf5\x87\x9b\x07\x80\xf0\xda\xb2\ +\x2a\x80\x7f\x6f\xa0\xd7\x79\x8b\x57\x4d\xea\xae\x6f\xb7\x09\x90\ +\x11\xf9\x02\x81\xaf\xb9\x44\x30\x9a\x63\x4e\x9a\x5d\xbf\x71\xee\ +\x05\xeb\x56\xd3\x05\xe2\x33\x2e\x2a\x05\xe1\xef\x1a\xd2\x45\x24\ +\xd7\x4d\x53\x55\x47\xb2\x9e\x49\x13\xe0\x2d\xae\xbc\x1d\x84\x79\ +\x1a\x8a\xa5\x82\x9f\x7e\xb0\xaa\xac\xb9\x37\x76\xd3\x81\x4f\x42\ +\x81\x0e\x25\x2a\xef\x03\xf0\xa5\x86\x9e\xd4\xd6\xe2\x59\x98\xac\ +\x5f\x92\x04\x30\x11\x89\xe7\x0c\xdc\xe6\xf7\xab\x03\xfb\x7a\x6e\ +\x33\xbd\x68\xa8\x5d\xd2\x0a\xc6\x4a\x2d\x47\x84\xa7\x27\x3c\xfc\ +\xe2\x90\x44\x7d\x12\x26\xc0\x57\x14\x2a\x04\x70\xbb\x86\x8a\x40\ +\xc4\xd4\xde\xdb\x4c\x2f\x32\x3b\xb3\xd6\x00\x38\xa6\xa1\x46\x3a\ +\xdd\xae\x92\x44\xfa\x84\x09\x60\x81\x5f\xea\x09\xd4\x84\xab\x97\ +\x7d\xd6\x6b\x87\x69\x46\xfd\xc6\xb9\x17\x88\x60\xf8\xa2\xc4\xb2\ +\x44\x6b\x83\xb8\x09\xf0\x2d\x5c\x9d\x03\x60\x86\x86\x8a\x28\x52\ +\x3e\x6b\x97\xc9\x74\xe3\x86\x93\x39\xaf\x33\xf0\xf1\x37\xd7\x04\ +\xbe\xe6\x53\x4f\xeb\x5d\xf1\xb4\x71\x13\x20\x63\xd1\x87\xa0\x59\ +\x24\x11\xf0\x6e\x43\xed\x92\x56\xdb\x9d\xa6\x09\x75\x75\xf7\xc7\ +\x88\x50\xa7\xe5\x04\xf3\xa3\xf1\xb4\x71\x13\x40\xa0\x99\x06\xe6\ +\x4f\x76\x99\xeb\x2b\xb0\x94\x46\xcf\x3f\x8e\xf7\x18\x98\x12\x70\ +\x71\xc6\xbc\x55\xcb\x49\x8e\xbd\x6d\xaf\xbd\xf4\xa3\x29\xf7\x74\ +\x23\x00\xed\xa8\x1d\x76\xc4\x73\xc2\x6b\xd4\x99\x12\x90\xe1\x76\ +\x7d\x0f\x80\xeb\x32\x43\xff\x68\x5a\xbb\xe4\x98\x51\xd7\xef\x51\ +\x5e\x2e\x01\xd6\x7d\x71\xcc\xe6\x7d\xca\x38\x8f\x80\xf8\xae\x81\ +\xd8\x63\xab\xb1\x3e\x04\xb3\xde\x3b\x31\xc6\x1b\x35\xa6\x04\x30\ +\xf3\xcd\xba\x6b\xc8\x8f\x8d\x9a\x2b\x05\x82\xa1\xf7\x4e\xb8\xd9\ +\xa4\x31\x12\x44\xb8\x41\x47\x30\xf5\xfb\xdf\xfe\x84\x70\x3a\x8c\ +\xde\xf3\x8c\x12\xf3\x08\x20\x64\x69\xaf\x49\x50\x9f\xbf\xeb\xdb\ +\x85\x21\xed\x6e\xa3\xf7\x2c\xa3\xc6\x3c\x07\xb0\x5e\x24\x98\x2d\ +\xed\xb1\xf5\x27\xd4\x6f\x9c\xd3\x01\x20\xaa\xa1\x5c\xf9\x7e\xd5\ +\xa5\xd5\xc4\x5b\x07\xe8\x36\x49\xa2\x42\xf6\x8b\x77\xfe\x74\x21\ +\x5e\x02\xda\x74\x02\x56\x4c\xc3\xe6\x4a\xc1\xb4\x39\x1b\x33\x00\ +\x68\xf7\x03\x3a\x0f\xd6\x95\x77\x6a\x35\xe6\x49\x10\xd0\xed\xa8\ +\xb2\xe4\xe1\xe9\xb1\x97\x7e\x7c\xed\x38\x3b\xcc\x40\xb5\x19\x35\ +\xe6\x49\x10\xf4\xb9\xf6\x9a\x84\x79\xe6\xbc\x52\xc0\x8a\x63\x8c\ +\x9e\xc0\x51\xa3\x26\xce\x24\xc8\x87\xb4\x97\x04\x7c\xc7\x66\x5f\ +\x7d\x06\x09\xa9\xf3\xce\x84\xc3\x46\x8d\x39\x01\x24\x74\x87\x8d\ +\xcc\xba\x4d\x91\x2b\x0a\x0c\x83\x77\xa6\x0f\x8d\x1a\x53\x02\xda\ +\x15\xda\x0b\x40\x7b\xfe\x3e\x69\xca\xfc\xe0\xb5\xb6\xbb\x4b\x37\ +\x54\x55\x10\x70\x8f\x96\x62\x85\xeb\x8d\x32\x53\x02\xba\xce\xd6\ +\x68\xaf\x96\x8b\x2a\x74\x8f\x51\xd7\xdf\xe1\x6b\x1e\xe1\x85\xfe\ +\x44\xf9\xdc\xd0\x51\x27\xc3\x46\x5d\xfc\x2d\x31\xd6\xbf\x45\x11\ +\xf1\x2c\x5b\xdd\xf5\x05\x84\xd0\x79\x66\x60\x67\x7d\x79\x79\xd4\ +\x24\x8b\xd7\x37\xe6\xa2\xcd\x00\x2e\x1f\x35\x33\xee\x9c\x38\x37\ +\x78\x95\xdd\x1e\xd3\x06\x55\x15\x0c\xfc\x4c\x4b\x11\x78\x53\x3c\ +\x69\xdc\x04\x5c\xdc\xf7\xdf\xa5\xa1\x32\x14\xa7\xe9\x38\xbc\xdf\ +\xc2\xd7\xea\x79\x10\xc0\x38\x0d\x75\x22\x33\xe7\xd4\xae\x78\xda\ +\x84\xbb\xc2\x04\x7e\x49\x4f\xd0\xa2\x89\x8b\x56\x5d\x6f\x8b\xc3\ +\x34\x22\xdf\xaf\xba\x98\xf1\x1b\x1d\x49\xf4\x4a\xbc\xe1\x0f\x24\ +\x49\x40\x63\x4d\xe0\x5d\x00\xda\xc9\xd0\x25\xa2\x72\x85\x1d\x26\ +\xd3\x09\xb7\xc7\x53\x0c\xfd\x6b\xef\xa9\x8c\xce\xf6\xea\x44\xfa\ +\x24\x27\x43\xc4\x20\x7a\x4a\xc7\x00\x8f\x4c\x2a\xad\x32\xed\xab\ +\xf5\x17\x78\x8b\x5f\x1a\x49\x8c\xa7\xb5\x1c\x33\x7e\xfb\xde\x86\ +\x5f\x99\x96\xc0\xdf\x20\xe9\xd9\x60\x78\x4d\x59\x3d\x18\xaf\x6b\ +\xf5\x42\xd2\x96\x29\xf3\x2b\xaf\xee\xa5\x57\xdb\x91\xef\x57\x5d\ +\x24\x5c\x7f\xd4\xd5\x10\x31\x0e\x00\x19\xc1\x64\xfd\xba\x3d\x1d\ +\xee\x14\xce\x27\xa0\xdf\x5d\xbd\x2e\xe6\x10\x6f\xdd\x54\x16\x34\ +\x16\x47\x7d\xab\x70\x67\x67\x57\x81\x71\x87\x86\x8a\x40\xa0\xa8\ +\xbb\xa2\xca\x6e\x13\x70\x60\x4d\xe9\x17\x52\xe0\x27\x00\x3a\x2e\ +\x91\x8c\x5b\x87\x77\xe0\x55\x80\xfb\xa4\xd6\xb8\x3b\xf8\x4a\x42\ +\x0b\x01\x5a\xa0\x67\xa9\x34\x95\xb2\x9d\x94\x4a\x64\x5a\xc2\x3b\ +\x8e\x8f\xf6\xcd\xf8\x1c\xa0\xd9\x97\xe3\x63\xe2\xe8\x82\xc6\xdc\ +\xe1\x63\x26\xef\xfa\xcf\xc1\xdd\x31\x8b\x9e\x6d\x02\x93\xb7\xd8\ +\x13\x00\xa1\x0a\xfa\x8d\x9c\xca\x70\x4d\xe0\xb9\x44\xbd\xb4\x48\ +\xb9\x46\xa8\x39\xbc\xf3\xc0\x68\xef\x0c\x37\x88\x6e\xd3\xd0\x5e\ +\xa7\xdb\x5d\x98\x3b\xe9\x07\x6f\xb7\x34\xed\x6a\x4f\x35\x96\x1d\ +\xc8\xf7\xab\xae\xeb\xbf\x7f\xa0\x86\xba\x26\xea\x4b\x37\x4f\xc0\ +\x3b\x99\x39\x27\xe7\x1e\xdd\xbd\x3b\xa5\x9a\x41\x4b\x55\x62\x79\ +\xa7\x73\x9f\x62\xd0\x16\x1d\xc9\xb8\x03\xe4\x6a\xf4\x16\x87\x6e\ +\xb1\x12\xab\x37\x98\xb0\xa0\x7a\x94\x3b\xdb\xf3\x17\x80\x1e\x33\ +\x34\x7d\x14\xe9\x88\x3d\x90\xe8\x37\x3f\x1e\x2c\x3f\xc3\x7e\xff\ +\x9b\xca\x91\x11\x2d\x2f\x82\x68\xa9\xa1\x29\x42\x84\xea\x0e\x38\ +\x57\x1e\x58\x53\xfa\x85\xd5\xb8\xa9\x60\xea\xd2\x8a\xc1\x91\xaf\ +\x1c\x8b\x41\x58\x0e\x60\x84\xae\x91\xb0\x83\x65\xc6\x83\x4d\x6b\ +\x4b\xce\x5a\x89\xd9\xe3\x49\xac\xa0\x24\xf4\x18\xc0\xd5\x00\x9c\ +\x86\xa6\xf3\x20\x7e\x59\x71\x52\x85\x95\x82\xc5\x64\x98\xa6\xaa\ +\x8e\xb6\x96\xec\x39\x20\xb1\x42\x57\xaf\x74\x19\x15\x79\xa7\x72\ +\x9e\xac\xab\xbb\xdf\xf2\x5c\xd4\xab\x59\xdc\x57\x52\x59\xc8\x10\ +\x6f\x01\xf0\xc4\x69\x3e\x0d\x60\x1b\x80\x6d\x8a\x0b\xbb\xac\x26\ +\x23\xdf\xaf\xba\xdc\xc3\x3d\x85\xa4\x60\x26\x4b\xdc\x0b\x42\xbc\ +\x65\x78\x04\xa0\xd2\x70\x4d\xd9\xfa\x1e\xd8\x07\x60\x43\xb9\xbc\ +\x6f\xe1\xea\xeb\x38\x16\xab\x04\x70\x5f\x12\x59\x04\x84\xdd\x90\ +\xf8\x2b\x04\xfd\x4b\x30\x7f\xc2\x8a\x72\xea\x02\xd3\x79\xb7\x23\ +\x1a\x13\x91\x68\x96\x64\xc7\xb0\x28\x23\x8f\x04\x8d\x05\xcb\xa9\ +\x00\xdd\x8d\xae\xbf\xd4\x24\x72\xde\x28\x89\x4b\xdf\xaf\x7e\xbc\ +\xa9\x37\xfe\x6d\xfb\x1d\x2f\x28\x0a\xfd\x08\x82\x9f\x07\x90\xde\ +\xc9\xb0\xab\x2e\xf9\xd7\x79\x27\x73\x6a\x7b\x32\xe4\x8d\xb0\x77\ +\x21\xa3\xaa\x62\x72\x6b\xf6\xbd\x12\xb4\x1c\x0c\x9f\xad\xb1\x41\ +\x9f\x81\x65\x45\x66\xe7\xd0\xf5\x76\xd6\x28\xa6\x6d\x25\xe7\x2b\ +\x5a\x35\x5e\x0a\x9e\x43\xe0\x59\x00\xc6\xf6\x30\xcc\x09\x30\xb6\ +\x13\xc9\x4d\x8d\x39\xa7\xff\xd6\x93\xff\x03\x74\x87\x3e\x59\xca\ +\x5e\x9c\x27\xa6\x83\x79\x3c\x40\xe3\x40\xc8\x03\x30\x0c\x5d\xcf\ +\xb8\x83\x41\x67\x89\x71\x0e\xc4\xff\x26\xc2\x61\x29\x71\xd8\x41\ +\xd8\xdd\x50\x53\x76\xa8\xbf\x94\xe3\x0e\x60\x00\x03\xf8\xdf\xc4\ +\x7f\x01\x33\x41\xc7\xce\x61\x76\x81\xea\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x77\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x29\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x88\xdb\x45\x14\xc7\xbf\x6f\x92\xad\x55\xd9\x5e\xb6\x78\ +\xa9\xc5\x9b\x7f\xc0\x93\x95\x1e\xbc\x18\x6a\x92\x1a\xa1\x5b\x1b\ +\xb2\xa2\x54\xb0\xdd\x64\xb5\x20\x1e\x14\x29\x28\x6a\x0c\xb6\xa0\ +\x08\x16\x2a\xe8\xba\x49\x64\x0f\x56\x51\x37\xe9\xba\x88\x5b\x93\ +\x2c\x2c\x08\x2a\x88\x82\xd0\x22\x88\x07\x91\x56\x50\x28\x45\x69\ +\x89\x74\x93\x79\x1e\xb2\x5b\xd2\xdf\xfc\x0a\x9b\xee\xcc\xfb\x0d\ +\x34\x9f\xdb\xce\xe1\x7d\xdf\x7c\x99\x79\x33\x6f\x33\x3f\x60\xc8\ +\x90\x21\x37\x32\x64\x2b\x50\x32\x3b\xf9\x3a\x11\xbd\x02\x28\x66\ +\xe6\x23\xad\x7a\xa5\x64\x2b\xb6\x4b\x94\xad\x40\x44\xea\x55\x80\ +\x62\x00\xc7\x41\x28\x26\x73\x85\x84\xad\xd8\x2e\xb1\x66\x40\x7f\ +\x2c\x02\x08\x8c\x85\xf4\x44\x61\x87\xc5\xf8\x4e\xb0\x69\x80\xee\ +\xff\x83\x80\x51\xee\xe2\xd4\xc3\x13\x93\x77\x59\xd4\xb0\x8e\x4d\ +\x03\xd8\x18\x21\x6c\xed\x6a\xd5\x4c\xef\x3d\xb8\xdd\xa2\x8e\x55\ +\x6c\x1a\x70\x2d\xb6\x73\x3c\xd6\x48\x3c\xf1\xf4\x56\x01\xad\x81\ +\x91\x30\x00\x00\xee\x1e\xb9\xac\x17\xc7\xc7\x27\x47\x85\xf4\xd6\ +\x8d\x33\x03\x98\x39\xb8\x25\xee\x6f\x6f\x52\xf3\x99\xcc\x73\x37\ +\xb9\xd2\xbc\x1e\x9c\x19\x40\x44\x1a\xc1\xba\xc0\xd8\xd5\xb9\xa5\ +\xfd\x71\x22\x51\x8c\xbb\xd2\x1d\x14\xd7\x5b\x40\xc3\x5c\x09\xd9\ +\x91\xb1\x73\xd3\xb0\x78\x09\xdb\x08\xee\x6b\x40\xd8\x4a\x00\xf2\ +\xa9\xdc\xd4\x9b\xce\xb5\xd7\x81\x54\x11\xd4\xc6\x08\xf3\xe1\x54\ +\x36\x7f\x58\x48\xff\x9a\x48\x19\x00\x00\x5d\x63\x84\xe8\xad\x54\ +\x2e\x5f\x10\xcc\xc1\x40\xd2\x80\xb5\xed\x70\x35\x4c\x1f\x24\x73\ +\x85\xac\x68\x1e\x7d\xc8\x1a\xc0\xcc\x20\x63\x3b\x28\x62\x7c\xf2\ +\x50\x76\x2a\x29\x9a\xcb\x9a\xb8\xb8\x22\x83\x61\xd6\x84\x4d\x8a\ +\x78\x7e\xf7\x44\x7e\xa7\x74\x3a\xf2\x06\xf4\x60\x32\xb7\xc3\xad\ +\x5a\xd3\x57\xc9\x7d\x85\x7b\x24\x13\x89\xca\x80\xb5\x9b\x62\xd0\ +\x84\x31\x52\x68\xee\xca\xe6\xef\x90\xca\x23\x32\x03\x56\x61\x32\ +\x6b\xc2\xb6\x18\x51\x23\xbd\xef\xd0\x6d\x12\x09\x44\x6d\x00\x98\ +\xc1\x80\x71\x5b\xbc\x53\xab\xce\x62\x66\xff\xfe\x2d\xae\xf5\x23\ +\x37\xa0\x87\x79\x5b\x24\xe0\xbe\x4e\xfb\xe6\x85\xc4\x81\x03\x9b\ +\x5d\x2a\x7b\x62\x00\x00\x40\xf7\x56\x43\x1f\x84\x07\x47\x2e\xc6\ +\x3e\x75\xd9\x3c\xf9\x64\x00\x88\x48\xb3\xd1\x41\xd2\xf8\xc8\xd8\ +\xb9\x4a\xb1\x58\x74\x92\xab\x57\x06\x00\x0c\xea\x9d\x0c\xc1\x9a\ +\xf0\xd4\xb7\xa7\xcf\xbe\x0d\x07\x1d\xa4\x67\x06\x5c\xc1\xbc\x32\ +\x83\x5e\x48\xe5\x0a\x2f\xd9\x16\xf2\xd5\x00\x00\x64\x36\x4f\x8c\ +\xa3\xa9\x5c\xfe\x19\x9b\x2a\x1e\x1b\xc0\x00\xa0\x8d\xcd\xc0\xf4\ +\x7e\x3a\x5b\xc8\xd9\x52\xf1\xd8\x00\x00\xbd\xa2\x10\xdc\x0e\x04\ +\xc2\xbb\xb6\x04\x7c\x37\x00\x14\x52\xf6\x98\x61\xed\x58\xf4\xde\ +\x00\xe6\xb0\x1c\xb9\x6a\x2b\xbe\x37\xff\x9d\x0d\x87\x63\xc1\x93\ +\x8f\x88\x9e\x6d\xd4\x2a\xef\xd9\x52\xf0\x78\x05\x98\x93\x07\xe1\ +\xb5\xc6\x5c\xd9\xda\xe4\x01\x7f\x0d\x50\x21\x77\x9e\xe3\xcd\xb9\ +\xca\x11\x07\x42\x3e\x41\x00\xb3\x82\x39\xfb\x8f\x1e\xb8\x77\xdb\ +\xf3\x08\xfb\x01\x76\x83\x78\x56\x03\xb4\x02\x5d\x5d\xf7\x19\xf8\ +\xf2\xc2\x98\x9a\x2c\x95\x4a\x21\xb7\xc3\x8d\xe3\xcd\x0a\xe0\xde\ +\xb2\x0f\x4e\xfe\x9b\x4b\x6a\xf4\xb1\x1f\x67\x66\x56\x5c\xe9\x7a\ +\x61\x00\x33\x14\x99\x15\xef\x67\x28\xb5\xe7\xbb\xcf\x8f\xb5\x5d\ +\x6a\x47\xbf\x05\x88\x88\xc0\xc1\x3d\xff\x9b\x5e\xe1\xdd\x4b\x0b\ +\xe5\x7f\x5c\xcb\x47\xbb\x02\x88\x68\xb5\xe8\xf5\x8d\xe1\xcf\x58\ +\x37\x9e\x5a\x5a\xa8\xfc\x25\x91\x42\x64\x06\xf4\x1e\x52\x05\x26\ +\xcf\xb8\xa0\x98\xd2\xa7\xe6\xa7\x7f\x97\xca\x23\x2a\x03\x88\x4d\ +\xed\x4b\x0c\x3c\xf2\x75\xad\x7c\x46\x32\x11\x79\x03\x08\x14\xa2\ +\xbb\x02\xd2\xd9\x56\xbd\xf2\xbd\x74\x3a\xd2\x06\x10\xb4\xa1\xc9\ +\x0c\x7a\xb2\x39\xf7\x61\x43\x38\x17\x00\xf2\x06\x28\xe3\xb0\x63\ +\x1c\x6a\xd5\xca\x9f\x09\xe7\x71\x05\xc9\x63\x30\x16\x1c\x20\xe6\ +\x97\x1b\xf5\xea\x8c\x60\x0e\x06\x52\x2b\x20\xac\xa7\x7f\xa7\x51\ +\xaf\x46\xfe\x4c\xc6\xbd\x01\xa1\xcd\x0d\xcf\x36\x6b\xd5\x17\xe1\ +\xa0\xb9\x19\x14\xd7\x06\x18\xcd\x0d\x01\x5f\xac\x9c\xbf\x7d\x0a\ +\x1e\x4c\x1e\x70\xfb\x50\x32\xac\xad\x5d\xbe\x3c\xda\x79\x7c\x79\ +\xb9\xd4\x71\xa5\x3b\x28\x2e\x1f\x4a\x06\x3b\xbb\x9f\xe2\x9b\xdb\ +\x7b\x97\x67\x67\xff\x73\xa5\x79\x3d\x48\x15\xc1\x5f\x95\x8e\x67\ +\x16\x4f\x9c\xf8\x57\x48\x6f\xdd\x48\x18\x70\x96\x95\x4a\x35\x4e\ +\x4e\xff\x2d\xa0\x35\x30\x36\xef\x01\x61\x3f\x5c\x9e\x67\x8d\x74\ +\xab\x36\xf3\x87\x45\x1d\xab\x38\xf9\x64\x66\x95\x8b\x9a\x29\xd3\ +\x3a\x59\xf9\xc5\xa2\x86\x75\xec\x7d\x34\x85\xfe\x57\x5f\xcc\x20\ +\x7e\x74\xa9\x5e\xfe\xc1\x56\x7c\x57\x58\xfc\x6a\x8c\x8f\x82\xd0\ +\x05\xb8\x0b\xe0\x8d\xe6\x5c\x75\xc9\x56\xec\x21\x43\x86\x0c\x71\ +\xc5\xff\x03\xa1\x32\xbd\x29\x9d\x1e\xd2\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x17\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xc9\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x4d\x48\x54\x51\x18\x06\xe0\xf7\xbd\x5e\x4b\xb2\x20\x82\xa0\ +\x08\x8c\x56\x41\x41\x54\xd2\x38\x1a\x84\x45\x04\x26\x29\x26\xcc\ +\x22\xca\x12\xa2\x9f\x45\x8b\x08\xa2\x82\x90\xa0\x45\x60\x05\x6e\ +\x82\x28\x88\x6a\x11\xf8\x33\x57\xa4\xbf\x4d\xf4\x03\xe6\x38\x30\ +\x81\x9b\x16\x19\x05\xad\xa2\xac\xb0\x20\x35\xaf\xf7\x6d\x23\xe4\ +\x5c\x2b\xcc\xb9\x33\x41\x7d\xcf\xf2\x7c\xe7\xbc\x7c\xe7\xbb\x1c\ +\x66\x00\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\ +\xfc\x2f\x98\x6b\x40\x45\xb7\x56\x21\xd0\x0d\x00\xcb\x04\x5e\x4c\ +\x37\xe0\x3c\x48\x45\xd0\xdb\x4f\xc5\xba\xd4\x00\xaa\x15\x00\x1c\ +\xf2\x48\xaa\x81\xf7\x72\xc9\xcb\x7d\x00\xc9\xe0\x31\x80\x4d\x3f\ +\x12\x75\xf3\xcb\xb8\xb3\xff\x79\x82\xdf\x72\xcd\xce\x22\x31\xee\ +\xe1\xb8\xa0\x73\x53\x56\x87\xfd\xf7\x5c\x9c\x39\xc8\xf1\xd9\xc6\ +\x3a\x11\xb4\x96\x9d\x21\xee\x59\xe0\xea\xfe\x5a\x4f\x0b\x23\xc8\ +\x06\x00\x54\x3f\x94\x1b\xf7\x82\x4b\xa1\xcb\x03\x11\x7c\xc0\x9c\ +\x07\x30\x01\x1e\x06\xf0\x2e\xb4\xbc\x79\xae\xd4\x5b\xd5\xa5\xe5\ +\xb9\xe6\x57\xb7\x6b\xfe\xc8\x27\x75\x0b\x3c\x34\x75\x5d\xc0\x18\ +\x1d\xee\xce\xe5\xeb\x03\x11\x4c\x10\x00\x62\x3d\x5a\x41\x5f\xf7\ +\x00\xac\x0c\x95\xde\x52\xac\x4d\x35\xf2\xd9\x6c\x72\xcb\xbb\xb4\ +\xd4\xa5\x6e\x03\x58\x1f\x2a\x7d\xa4\x58\x97\x6a\x64\xef\x6c\x72\ +\xa7\x8a\xe2\x09\x20\x5d\xc7\xd7\x8e\xcf\x2a\x00\x4f\x42\xa5\x25\ +\x82\x9e\xc4\xba\x54\xfb\xa7\x99\x1b\x3a\xb5\xba\xd8\x51\x0a\xd3\ +\x2f\xff\x4a\x60\x65\x14\x97\x07\x22\x1a\x00\x00\xf4\x25\xf8\x71\ +\x51\x09\xb7\x01\xba\x95\x55\x20\x4a\x49\xf5\xc4\x3d\x1d\x9e\x69\ +\x56\x2c\xa9\x2d\x8e\xa3\x5e\x09\x65\x59\x05\xa1\x7f\x8e\xcf\x78\ +\x7a\x27\x5f\x44\xd3\x75\x44\x4f\x20\x4b\x8b\x9c\x8a\x35\xc1\x59\ +\x90\x27\xa7\x17\xd5\xda\x3f\xe0\x9c\xc0\x19\x06\xbf\x3a\x1e\x4b\ +\xaa\x89\xd0\x55\x00\xc5\xa1\x46\xbd\x71\x97\xbb\x33\x75\xfc\x1a\ +\x65\xbb\xd1\x0f\x60\x52\x85\xa7\x03\x90\x2e\x01\x28\x9a\xba\x2e\ +\xa8\x7d\xde\xb0\xb3\xf7\x51\x33\x47\xb3\x0e\x48\xac\xf0\x70\x1a\ +\xd0\x99\xe9\x69\x6a\x2b\xf3\x9d\x63\x1d\x09\x4e\x44\xdd\x67\xde\ +\x06\x00\x00\x71\x4f\x35\x0a\xd4\x01\xa2\x34\x54\xea\x15\x58\x9f\ +\xde\xc9\x0f\x00\xb0\xaa\x5d\x73\x16\x14\x05\x97\x41\xee\x0b\xed\ +\x13\xc8\xa3\xfd\x0d\x6c\xcb\x57\x8f\x79\x1d\x00\x00\x54\x76\x6a\ +\x5d\xe0\xe8\x0e\x80\xa5\xa1\xd2\x60\x11\x59\x33\x36\x8e\x21\xb7\ +\x58\x9d\x10\xb6\x86\xea\xa3\x12\x77\xa5\x1b\xe9\xe5\xb3\xbf\xbc\ +\x0f\x00\x00\xca\xdb\x55\xe6\xba\xba\x0b\x60\xf5\x0c\x8f\x0c\x41\ +\xdc\xd1\xdf\xc8\x54\x3e\xfb\x02\x22\xfc\x15\xf8\x9d\x4c\x82\x6f\ +\x7c\x9f\x1b\x09\x3c\x98\xc1\xf6\x41\xa7\x88\x95\x85\xb8\x3c\x50\ +\xa0\x01\x00\x40\x26\xc1\xe1\xcf\x3e\xb7\x13\xba\xfe\xab\x3d\x12\ +\x9e\xfa\x2e\xab\xfa\xea\xf9\xb2\x50\x7d\x15\xe4\x09\x64\x91\x18\ +\x4f\x06\x2d\x22\x5b\x42\x95\x4e\xc7\x67\x53\x5f\x82\x23\x85\x6c\ +\xa7\xf0\x03\x98\x14\x4b\x4e\x5c\x21\xd8\x0c\x40\x82\x2e\xa4\x07\ +\x9c\x53\xbf\xfb\x7f\xf0\x4f\xaa\x7e\x28\xb7\xfa\x9a\x4a\xfe\x76\ +\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\xcc\x7f\ +\xe2\x3b\x5f\x7a\xf2\xea\xb1\x6e\xd0\x9c\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x08\x6c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x1e\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x8c\x1c\x65\x1d\x7e\x7e\x33\xb7\x7b\x77\x70\x1f\x10\xe8\ +\x51\xb3\x1f\xb3\x7b\xd7\x6b\x4a\x5a\x4c\x2c\xa7\x11\xd2\x54\x4b\ +\x34\xa8\xa1\x87\x45\x12\x05\x03\x34\x90\x2a\x45\x49\x94\x40\x4d\ +\x4d\xc0\xaa\x54\xa1\x4a\x0b\xfc\x41\x55\x04\x2d\xd0\x48\x02\x42\ +\x63\x0d\x60\xff\xc0\x36\x55\x21\x80\xd1\xe8\x62\xcf\x5c\xdd\xdb\ +\xd9\x9d\xbb\x1e\xb5\x14\xfb\x61\x7a\xb7\xb3\xfb\x3e\xfe\xd1\x22\ +\xf3\xb5\x77\xbb\xb7\x33\xc7\x55\xef\xf9\x6f\x9e\xf7\xf7\xfe\xe6\ +\x99\x67\xde\x99\x7d\xe7\x7d\x7f\x0b\xcc\x63\x1e\xf3\xf8\x7f\x86\ +\xcc\xc6\x49\x86\x0f\x1d\x5a\x10\x9b\xac\xac\xa4\xe0\x12\x0d\xb2\ +\x44\x81\xbd\x00\xce\x13\x48\x17\x40\x1d\xc0\x71\x00\xc7\x09\x29\ +\x02\x3c\xa0\x41\xfe\x46\x56\xf6\x67\x32\x99\x91\xa8\xb5\x45\x66\ +\x40\xb1\x58\xec\x53\xd0\xd6\x42\x71\x10\x82\x0f\xce\x30\xcd\x08\ +\x28\x2f\x6a\x9a\xfa\x79\x2a\x95\x7a\x43\x44\x18\xaa\x48\x84\x6c\ +\x00\x49\x29\x58\xd6\x95\xa2\xb0\x01\xc0\xaa\x30\x73\x03\xc8\x51\ +\xb8\xf5\xed\xc3\x87\x9f\x1a\x18\x18\xb0\xc3\x4a\x1a\x9a\x01\x85\ +\x82\xb5\x0a\xc2\x2d\x00\x06\xc2\xca\x19\x0c\x29\x10\xd8\x94\x49\ +\x27\x9e\x08\x63\x44\x34\x6d\x40\x3e\x9f\xbf\x48\xd3\x63\x0f\x00\ +\xf8\xe2\x14\x61\x8a\xc0\xef\x45\x64\x2f\x14\x87\xa8\xe3\x1f\x2d\ +\xc0\xd1\x4a\xa5\x72\xa2\xd2\xd6\x56\x8d\x97\xcb\x9d\x64\x4b\x37\ +\xa0\xb2\x14\x2c\x06\xe4\x32\x01\x3f\x09\xa0\xbd\x56\x42\x02\xfb\ +\x35\xa8\xf5\x86\x61\xbc\xd9\x8c\xfe\xa6\x0c\xc8\x97\x4a\x1f\xd1\ +\x14\x76\x01\xf8\x40\x40\xf3\x09\x81\xbc\x40\x72\x77\x4b\x8b\xbc\ +\x94\x4c\x26\xdf\x6e\x24\x77\xa9\x54\x6a\xaf\x56\xe5\x0a\x11\xb5\ +\x9a\x90\xc1\x1a\xe7\x98\xa0\xf0\xe6\x6c\x3a\xfd\x8b\x99\xe8\x07\ +\x9a\x30\xa0\x50\x28\x5d\x0f\xc1\xe3\x00\x5a\x7d\xa2\x80\x87\x35\ +\xa8\xfb\x0c\xc3\x78\x67\xa6\xf9\x9d\xc8\xe5\x72\xf1\x8e\x8e\xae\ +\x75\x10\xb9\x07\x40\x8f\x2f\x80\xb2\xd9\x30\x12\xf7\x88\x88\x6a\ +\x34\x77\xc3\x06\x90\xd4\x8a\xc5\xd2\xbd\x84\x6c\xf4\x34\x29\x00\ +\x8f\xb7\xe8\xf2\xed\x64\x32\x69\x35\x9a\xb7\x1e\x0c\x0d\xfd\xb3\ +\xb3\xbd\x7d\xe2\x0e\x02\x77\x02\xe8\x70\x0b\xc3\xae\x73\xce\x69\ +\xbd\xa1\xa7\xa7\xe7\x64\x23\x39\x1b\x32\x80\xa4\x66\x9a\xa3\x3b\ +\x21\xfc\x82\xa7\x69\x4c\x69\x58\xd3\x9b\x4a\xbd\xd6\x48\xbe\x99\ +\xc2\xb2\xac\x64\xa5\xca\xe7\xe1\x7f\xe1\xfe\xc9\x2e\x4f\x7c\xbc\ +\xbf\xbf\xff\x78\xbd\xb9\xb4\x46\x4e\x6c\x96\x46\x37\xf9\x2e\x5e\ +\xf0\x2a\x58\x1d\x98\xad\x8b\x07\x80\x64\x32\x69\xe9\x1a\x56\x02\ +\xd8\xe9\x69\xfa\x50\x2c\xde\xb6\x93\xa4\x5e\x6f\xae\xba\x47\xc0\ +\x48\xb1\xf8\x79\xa1\x3c\xed\xee\xcc\x1d\x4a\x55\x6f\xcd\x66\xb3\ +\x13\xf5\xe6\x09\x13\x24\xa5\x58\xb4\xee\x22\x70\x1f\x1c\xd7\x42\ +\x60\x4b\xd6\x48\x7d\xa3\x9e\x1c\x75\x19\x50\x2c\x16\x07\x14\x65\ +\x3f\x80\x36\x07\xfd\x94\x91\x4e\xde\x18\xc5\xec\xac\x51\x8c\x98\ +\xd6\xd7\x04\xdc\xe6\xe4\x04\x72\x93\x61\x24\x9f\x98\xae\xef\xb4\ +\x8f\x80\x65\x59\x17\x28\xca\x2e\x38\x2e\x5e\x80\xd7\xa8\x2a\xeb\ +\xe6\xc2\xc5\x03\x40\x26\x9d\x78\x08\x94\x9f\x39\x39\x82\x8f\x16\ +\x0a\x63\xcb\xa7\xeb\x3b\xad\x01\x15\xc5\x2d\x00\x12\x0e\x6a\x4c\ +\x84\x6b\xde\xaf\x61\x1f\x04\x11\xa1\x6d\x9f\x5a\x0f\xe0\x0f\x0e\ +\x3a\x0e\xa9\x3c\x4a\xb2\x65\xaa\xbe\x53\x1a\x60\x9a\xe6\x0a\x10\ +\x37\x3b\x28\x52\xc9\xe7\xd2\xe9\xf4\x58\x13\x7a\x23\x41\x7f\x7f\ +\xff\xa4\xaa\xda\xd7\x00\x38\xf2\x1e\x2b\xcb\x8b\x45\xeb\xb6\xa9\ +\xfa\xd5\x34\x80\xa4\x10\xfa\xf7\x3d\xf4\xce\x6c\x36\xf9\x6a\x33\ +\x42\xa3\x44\x6f\x6f\xef\x5b\x84\x6c\x76\x72\x04\xee\x1e\x1f\x1f\ +\x3f\xb7\x56\x9f\x9a\x06\x14\x2c\x6b\x25\xc0\x15\x0e\xca\x16\xa8\ +\x6f\x85\xa0\x33\x5a\x28\xfb\x47\x10\x14\x1d\xcc\x85\x13\xe5\xf2\ +\x97\x6b\x85\xd7\x34\x40\x14\xee\x72\x13\xf8\xb1\x61\x18\xf9\xe6\ +\x15\x46\x8b\x6c\x36\x3b\x41\xd0\x7d\xa3\x28\x77\xd4\x9a\x1b\x04\ +\x1a\x30\x32\x32\xb2\x10\xc0\xa7\x1c\x94\xad\x2a\xf6\xbd\xa1\xa9\ +\x8c\x18\x99\x54\xea\x49\x02\xc3\x0e\x2a\x51\x28\x95\x3e\x11\x14\ +\x1b\x68\x80\xe8\xfa\xf5\x00\xfe\xeb\x98\x00\x2f\xf7\xf6\xf6\xbe\ +\x15\xae\xcc\xe8\x20\x22\x55\x21\x9f\x71\x71\x4a\x6e\x0a\x8a\xad\ +\xf1\x08\xc8\x6a\xe7\x11\x85\xbf\x0a\x4b\xdc\x6c\x81\xba\xb8\x35\ +\x0b\x3e\x13\xf4\x18\xf8\x0c\x18\x1f\x1f\x3f\x17\xc4\xe5\x4e\xae\ +\x6a\xeb\xbf\x0e\x5d\x61\xc4\xc8\x24\x93\xaf\x03\xe2\x1c\xb5\xdd\ +\x23\x96\x75\xa9\x37\xce\x67\xc0\xe4\x64\xe5\xa3\x00\xe2\x0e\xea\ +\xcf\x7d\x7d\x89\xa2\x37\x6e\xae\x43\x44\x14\x84\xae\x1b\xa7\x2b\ +\xff\x3a\x65\xc0\x23\xc0\x65\x1e\x62\x7f\xa8\xca\x66\x11\x3c\xfd\ +\xfd\xf2\xde\x31\xb0\xd4\x1b\x13\x64\xc0\xc5\xce\x23\x71\xbf\x4d\ +\xcf\x2a\x08\xc5\xab\xfd\x62\x6f\x4c\x80\x01\x92\x71\x1e\x91\x32\ +\xe7\x7f\xfb\x6b\x81\x2c\x7b\xb5\x67\xbd\x31\x3e\x03\x08\x74\x3a\ +\x8f\x45\xe4\x5f\x21\xeb\x9a\x4d\x78\xb5\x77\x7a\x03\xa6\x35\xa0\ +\x5a\x65\x43\x6b\x6c\x73\x09\x99\x4c\x66\x12\x40\xc5\x41\xc5\x73\ +\xb9\x9c\xf3\x05\xef\x37\x40\xbc\x8b\x24\x31\xce\x89\x6f\xfe\xa8\ +\x10\x34\x11\x3a\xe1\x3c\xd0\x95\xe6\x1b\x36\x67\x0b\x0a\x85\x42\ +\x2b\x00\xe7\x7a\x40\x79\xd9\xb2\x65\x65\x67\x4c\xd0\x08\x70\xad\ +\xa8\x92\x3c\x2f\x1a\x79\xd1\x83\x64\xb7\x87\x3a\xe1\x8d\xf1\x19\ +\xa0\x00\xd3\x93\xc6\xf7\xe6\x3c\x5b\xa0\x69\xf1\x5e\x0f\x55\xf0\ +\xc5\xf8\xbb\xc9\x01\xe7\x11\x05\xfd\x61\x8a\x9a\x4d\x88\x5f\xfb\ +\x90\x37\xc6\x67\x80\x86\xaa\x6b\xb3\x51\xdc\x8b\x22\x67\x15\xe8\ +\xd1\x4e\x20\xe7\x8d\xf1\x19\xd0\xde\xde\xfe\x0a\x00\xc7\xfe\xbb\ +\x2c\xb7\x2c\x2b\x19\x81\xbe\x48\x41\x52\x03\x70\x95\x8b\x54\xb2\ +\xd7\x1b\xe7\x33\xa0\xa7\xa7\xe7\xa4\x00\xaf\x38\x39\x5b\x79\x12\ +\x9d\x05\x28\x95\x4a\x97\xc2\xbd\xa3\x7c\x3c\x93\x49\xbc\xe1\x8d\ +\x0b\x5c\x0f\x20\xe1\xfa\x8a\x12\x70\x30\x5c\x79\xd1\x43\x41\x73\ +\x69\x26\xf8\x92\x88\x54\xbc\x71\x81\x06\x68\x1a\x77\xe2\xf4\x6e\ +\xef\xbb\xbd\xaf\x18\x3e\x74\x68\x41\xd8\x22\xa3\x02\x49\x0d\xe4\ +\xb5\x4e\x4e\x28\x3b\x82\x62\x03\x0d\x48\xa7\xd3\x63\x20\xf6\x38\ +\xa8\xd6\xd8\xa4\xed\xdd\x0e\x9f\xb3\x30\x4d\xeb\x3a\x00\x4b\x1c\ +\xd4\xb8\x61\x24\xf7\x04\xc5\xd6\x5e\x15\x16\xf9\xa1\x87\xf8\x4a\ +\x3e\x3f\x66\x84\xa2\x30\x42\xe4\x72\xb9\x38\x04\xdf\x75\x72\x02\ +\x6c\x0b\x1a\xfe\xc0\x14\x06\xa4\xd3\x89\x97\xe1\x7e\x19\xc6\x75\ +\x5d\x6d\x0a\x45\x65\x84\xe8\xe8\xe8\xfe\x12\xdc\x9f\xbd\x47\x4f\ +\x9d\x6a\xdb\x5e\x2b\x7e\xaa\x11\x40\x2a\x7c\xd3\xc9\x11\xbc\xd1\ +\x34\x4d\xdf\xba\xda\x5c\xc1\xe8\xe8\xe8\x85\x10\xdc\xed\x22\xc9\ +\xef\x2d\x59\xb2\xc0\x37\x05\x7e\x17\x53\xee\x0d\x66\xb3\xa9\xbd\ +\x00\x9e\x74\xc7\x6b\xcf\xe7\xf3\xf9\x8b\x9a\x11\x1a\x05\x72\xb9\ +\x5c\xdc\xb6\xd5\xb3\x70\xd6\x10\x11\x7f\x39\x72\xe4\xf0\xc3\x53\ +\xf5\x9b\x7e\x77\xd8\x8e\xdd\xe9\x5c\x5d\x25\x90\xd2\xf4\xd8\x73\ +\xc3\xc3\xc3\xde\xe2\xa8\xf7\x15\x9d\x9d\x5d\x0f\x41\xf0\x31\x07\ +\x65\x2b\x1d\xeb\xa6\x2b\xaa\x9c\xd6\x80\x45\x8b\x16\x1e\xa6\xc2\ +\x67\x01\x4c\x3a\xe8\xcb\x63\xad\x6d\x8f\x90\x9c\x95\x5a\xe3\xe9\ +\x50\x28\x16\x6f\x23\xe4\x56\x17\x49\xac\xaf\xa7\x6c\xa7\xee\x0b\ +\x30\x4d\xeb\x06\x82\xae\x8a\x0b\x02\x3f\xf9\xf7\x89\x63\xb7\x7b\ +\xbf\xb1\x67\x0b\x67\x4a\x64\x6e\x27\xb0\x0d\x8e\x9b\x29\xe0\x83\ +\x86\x91\xfe\x7a\x3d\x39\x1a\xba\x83\x23\x66\xe9\x7e\x01\x36\xb8\ +\x55\x60\x5f\x2c\xa6\x5d\x9b\x48\x24\x8e\xd4\xe8\x16\x09\x72\xb9\ +\x5c\xbc\xa3\xab\xfb\x11\x10\xb7\x38\x79\x01\x7e\x93\x4e\x27\xaf\ +\xaa\xf5\xb3\xe7\x45\xa3\x65\x72\xba\x59\xb2\x9e\x01\xb1\xc6\x93\ +\xa6\xa0\x6b\x1c\x4c\xa5\x52\x7f\x6d\x24\xdf\x4c\x71\xf0\xe0\x78\ +\x4f\x4b\xac\xf2\x4b\xf8\xbf\x54\xdf\xa4\xaa\xac\xc8\x66\xb3\x75\ +\x2f\xe4\xce\xa4\x50\x52\x37\xcd\xd2\x0f\x20\xe2\x1d\x62\x36\x81\ +\xed\x55\x3b\xb6\x79\xd1\xa2\x85\x87\x1b\xcd\x5b\x0f\x4e\x97\xcf\ +\xe2\xab\x10\x6c\x04\x70\xbe\xab\x51\xf0\x62\xd5\x2e\x5f\xd7\xd7\ +\xd7\x77\xac\x91\x9c\xcd\x94\xca\xde\x02\xc1\x76\x00\x31\x4f\xd3\ +\x49\x02\x0f\x54\xca\x13\x5b\x1b\x29\x58\x9c\x0a\x24\x5b\x4c\xd3\ +\x5a\x0b\xc1\x26\xb8\xeb\x95\xce\x04\xc8\x56\xc3\x48\x6c\x10\x91\ +\x6a\xa3\xb9\x9b\x2b\x96\x2e\x16\x57\x6a\x94\xe7\x00\x5c\x10\xd0\ +\xfc\x0e\xc1\xdd\x1a\xb4\xdd\xe5\xf2\xa9\x3d\x8d\x9a\x91\xcb\xe5\ +\xe2\x9d\x9d\xe7\xaf\x54\x50\xab\x05\xb8\x1a\x40\xd0\x34\xdc\x06\ +\xb1\x3e\x93\x49\x3d\x36\x13\xfd\x40\x08\xe5\xf2\x07\x47\x47\x53\ +\x2d\x55\xf5\x20\x88\x6b\xa6\x08\xb3\x01\xee\x83\x68\xbf\x85\xe2\ +\xdf\x95\x92\x83\xaa\x55\x8e\xc6\x2a\x95\x93\xe5\x72\xb9\xda\xd6\ +\xd6\xd6\xa9\x94\xea\x26\xf5\x2c\x35\x2c\x06\xd5\x65\x02\xb9\x12\ +\x40\x57\xad\x84\x04\x5e\x3f\x53\x2e\xff\xc7\x66\xf4\x87\xf8\x87\ +\x89\xd2\xa7\x29\xb8\x5f\x80\x4b\xc2\xca\x59\x03\x63\x84\x7c\x27\ +\x93\x4e\xfc\x74\x26\x43\xde\x8b\xb0\xff\x32\xa3\x99\xa6\x75\x35\ +\x05\x1b\x05\xf8\x70\x98\xb9\x01\xe4\x41\x6e\x25\xab\x8f\x85\x59\ +\xa3\x18\xd9\x4c\xce\x34\xcd\xa5\x14\x6d\x2d\x14\x06\x21\x58\x3c\ +\xc3\x34\xe3\x10\xbc\xa0\xc0\x1d\xd9\x54\xea\x77\x33\xf9\x3f\xc0\ +\x74\x98\x95\xa9\xec\xc1\xd1\xd1\x54\xac\xc2\x55\x0a\x5c\x0a\xc8\ +\x12\x80\x59\x11\x74\x83\xe8\xc2\xe9\x9d\x9b\x63\x00\x8f\x0b\xa4\ +\xa4\x80\x21\x08\x87\x34\x72\x5f\x3a\x9d\x3e\x30\x57\xca\x71\xe7\ +\x31\x8f\x79\xfc\x6f\xe2\x3f\x21\x7b\x09\x29\x0d\x19\xbe\x1d\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3f\x49\x44\x41\x54\x58\x85\xed\ +\xd3\xb1\x11\x00\x10\x10\x44\xd1\xa5\x10\x94\x22\xd1\xb5\x19\xad\ +\x18\x0a\x39\x91\x50\xea\x92\xff\xa2\xcd\x7e\xb4\x12\x00\xc0\x59\ +\xb8\x63\xae\x3d\x64\xaa\x7f\xb2\xd6\x4b\x4e\x4d\x92\xe2\x9f\x20\ +\xf0\xc6\x0b\x00\x00\x70\x77\x00\xa4\x4c\x0e\x07\xff\x04\x59\xb9\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x3e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xf0\x49\x44\x41\x54\x58\x85\xe5\ +\x96\x31\x68\x53\x51\x14\x86\xbf\x3f\x7d\xad\x52\x41\x31\x82\x08\ +\x2e\x2e\x2e\x0e\xe2\xd0\xa0\x5d\x1c\x2b\x54\xba\x08\xa9\x53\x05\ +\x11\x4d\x96\xb4\xa9\xe0\x26\x8a\xe2\x26\xb4\x4d\x2b\xd8\x87\x83\ +\x60\x27\x1b\x70\x29\x0e\xea\xe6\xa2\xf2\x3a\x48\x07\x17\x41\x1d\ +\x14\x41\xa8\x60\xa1\x45\xdb\xe4\x1d\x87\xa4\x4e\x82\xef\xde\x5c\ +\x22\xe8\xd9\x1e\xdc\xf3\xff\xdf\x3d\xef\xdc\x73\x2f\xfc\xef\xa1\ +\xd0\x82\x83\x17\xa6\xf2\x5b\x51\xef\x3b\x30\x5b\x8e\xc7\xf7\xfe\ +\x69\x7d\x14\xd2\xfc\xe8\xd8\xed\x5d\x8d\x28\x7a\x0c\xb6\x27\x6b\ +\x4e\x2e\x94\xf9\x91\xe2\xf5\xbe\xbe\xfe\x1d\x8f\x0c\x4e\xb8\xe4\ +\x05\x01\x28\x16\x17\x7b\xfa\xf3\xfb\x1e\x00\x43\xae\xb9\x01\x00\ +\x4c\xef\xf3\x9f\xef\x00\x67\x31\x30\x2c\xed\x2a\x40\xa1\x34\x77\ +\x13\x54\x06\xc3\x64\xa9\x90\x75\x0d\x60\xe0\xd2\x6c\xd5\xe0\x2a\ +\x80\x49\xce\xe6\x1d\x01\x0c\x94\x6b\x63\x88\x69\x00\x83\x54\x86\ +\xb3\xb9\x37\x40\xa1\x34\x3b\x82\xe9\x7e\xfb\x33\x15\x7e\xe6\x5e\ +\x00\x85\xd2\xcc\x49\x83\x45\xa0\x87\x96\xb1\xb7\xb9\x33\x40\xe1\ +\xe2\xf4\x31\x23\xb7\x04\xec\x6c\x1b\x3b\x75\xfc\xef\x22\xf3\x24\ +\x3c\x5e\xaa\x1d\x4e\xd1\x13\x60\xb7\x81\x29\x80\x39\x64\xac\xc0\ +\x60\x79\xea\x60\xd3\xf4\xcc\x60\x3f\x16\xce\x1c\x32\x56\x60\xcb\ +\xa2\x8f\xbf\xae\x2d\x85\x33\x87\xac\x3d\x60\xac\x84\x34\x75\x06\ +\xe8\xcd\x35\x86\x0d\x3e\xb4\x61\x82\x5d\x60\x99\x01\x5e\xcc\x5f\ +\xfe\x14\x61\x43\x82\x2f\xb4\xc6\x5d\x30\x88\xcc\x42\xaf\xe2\x89\ +\xb7\xa4\xcd\x53\xc0\x9a\x5a\x0f\x99\x20\x10\x4e\x22\xc9\xbd\xc9\ +\xd7\x22\x1d\x01\xbe\x13\x08\xc2\x59\x20\x89\xab\xcf\x05\xa3\x40\ +\x13\x10\xea\xec\x59\xe7\xb5\x83\x24\x1e\x5f\x42\x76\x1e\xd8\x6e\ +\x4a\x6f\x08\xef\x12\x2e\xcf\x4f\x2c\x08\x55\xb7\x75\xcc\xb3\x12\ +\x1d\xfd\xc3\x24\xae\xd4\x04\xb7\x00\x64\xe6\x05\xd1\x71\x13\x25\ +\x71\xe5\x9a\xc4\x5d\x10\x4a\xc9\xb5\x26\x75\x17\x01\x40\x76\x68\ +\xf5\x40\x05\x78\x88\x40\xc8\x49\x33\xc8\x59\xae\xd7\x47\x9b\x1b\ +\x5f\x57\xcf\x01\x4f\x5d\x73\x83\x4d\xb4\x37\xf5\x1b\x9b\x9b\x1b\ +\x3f\xce\x08\x5e\xfe\x15\x00\x80\x95\x85\x2b\xeb\x51\xa3\x71\x1a\ +\x58\x03\x7d\x0b\xa9\xfd\xef\xc6\x4f\x11\x32\x94\x0c\x6f\x6b\x20\ +\xde\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x95\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x47\x49\x44\x41\x54\x58\x85\xed\ +\xce\xb1\x0d\x00\x20\x0c\x03\x41\x82\x18\x2a\xdb\xc1\x42\x69\xd8\ +\x2f\xc0\x10\x46\x4a\xf3\xd7\xdb\xfa\xd6\x04\x1e\xb9\x3c\x72\x29\ +\x1f\x5d\x19\xff\x40\x00\x01\x04\x10\x40\x00\x01\xe5\x01\x43\x3d\ +\xb8\x66\xd3\x23\xab\x02\xfa\xb6\x7b\xb4\x0b\x00\x00\x50\xed\x01\ +\x74\x44\x0a\xfd\x41\x7d\x20\x9d\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x02\x21\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ +\xd5\x3b\x8b\x13\x51\x18\xc6\xf1\xff\x33\xf1\x86\x82\xd9\x4e\x50\ +\x0b\x11\x5b\xd1\x56\xc4\x72\x36\xcd\x6a\x61\x76\xb0\x71\x51\x34\ +\x29\x2c\x64\x3f\x81\x48\xf0\x0b\x88\x82\x8d\xd9\x20\xee\x16\x42\ +\x36\x2e\xc8\x22\xce\xc6\xce\xc2\xda\xde\xc2\x4a\xb0\x71\x89\xa0\ +\x78\x21\xe7\xb1\x98\x09\xd8\x99\xcb\x30\x29\xf4\xad\x4e\xf1\x5e\ +\x7e\x9c\x73\xe6\x0c\xfc\xeb\xa1\x71\x92\xe2\x7a\x63\x17\x50\x14\ +\xf9\x64\xda\x5d\xfb\x5c\x24\x20\x1a\x33\x6f\x01\xa8\x7a\xa8\xed\ +\xc5\x95\x95\x43\xf3\x00\x00\x60\x71\xce\xdf\xf6\xf7\x92\x24\xd9\ +\x37\x17\x40\x1e\xb5\xdd\x50\x7d\x9a\x24\x49\xa5\x74\x80\x50\x30\ +\x58\x70\x65\x10\xaa\x0f\x19\xf3\x0e\x15\x06\x30\xb6\x24\x67\x6b\ +\x6e\xc5\x97\x1b\xad\x52\x01\x99\xc2\x06\x05\x00\xc4\x9d\xb8\xde\ +\x5c\x2d\x17\x90\x2b\x04\x21\x5f\xdf\x8f\xeb\x8d\xab\x25\x03\xc0\ +\x60\x69\x84\xe0\xc9\xe2\x72\x73\xa9\x54\x00\x80\x8d\x33\x0b\x15\ +\xdb\xdd\xda\x72\xe3\x42\xa9\x80\x3c\x42\x0e\x39\x10\xac\xed\x38\ +\x69\x9e\x2d\x1b\x40\x76\x14\x36\xf8\x30\xf6\xab\x5a\x72\xf3\x54\ +\xa9\x80\x9c\x11\x00\x63\x8e\x84\x40\x3f\xbe\x74\xe3\x68\xc9\x00\ +\x00\x82\x33\xcc\x09\xf6\x56\x5e\xce\x03\xf0\xc7\xd3\xe8\x33\xf3\ +\x00\xe4\xfd\xfc\x81\x5f\xe1\x58\xa9\x00\x67\xbd\x84\xf8\x14\x45\ +\xc4\xfd\x17\x9d\x8f\xe3\xd4\xed\x29\x66\xba\x23\x49\x02\x06\xd1\ +\x30\xd4\xd2\xad\xce\xfb\x71\x4b\x67\xde\x01\xe3\x88\x6c\xf8\xf7\ +\x48\x5c\x4c\xb7\x3a\xef\x26\xa9\x9f\x11\x20\x09\x09\x18\x4a\x4a\ +\xd2\xcd\xf6\x9b\x49\x3b\xcc\x02\x10\x78\x54\x7f\x7d\x67\xf3\xf1\ +\xf6\x34\x4d\xa6\x05\x68\x54\x2b\x58\xed\xf7\xda\x1b\x53\xf6\x99\ +\x0a\x20\x9c\xd7\x99\x7b\x3b\xbd\xf6\x83\x69\x87\xc3\xa4\x5f\x81\ +\x10\x81\x08\x81\xed\x47\xaf\x9f\xaf\xdd\x9d\x65\x38\x4c\xba\x03\ +\x76\x84\x00\xfb\xd9\xf9\xd3\xc7\x6f\x93\xfd\x8a\x4b\x04\x64\x0f\ +\x6d\xba\x50\xf9\x72\xad\xd5\x6a\x85\xbf\x65\x17\x0e\x90\x79\xab\ +\x83\x3f\xea\xdd\x6e\xf7\x67\x11\xc3\x61\xec\x3b\xa0\x01\x42\x8a\ +\xc2\x52\xba\xbe\xfe\xb5\xa8\xe1\xff\x03\xe0\x37\xff\xea\x99\x56\ +\xb6\x04\x03\xd2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x03\x2a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdc\x49\x44\x41\x54\x78\x9c\xed\ +\x99\x4f\x48\x54\x51\x18\xc5\xcf\x79\xf3\xd2\xd1\x20\x49\x88\x16\ +\x41\x50\x10\xad\xaa\x45\xe1\x9b\x30\x21\x22\x08\x25\x1a\x67\x2c\ +\x23\x5a\x54\x10\x08\x41\xb4\x69\x17\xe4\xa2\x76\x11\xb4\x0f\xd2\ +\x45\x48\x58\x8e\xe6\x62\x08\x22\x6d\xa1\x8d\xcf\x72\x51\x04\x21\ +\x14\x44\xff\x16\x25\x16\x0a\x29\xf8\xde\xfd\x5a\x84\x31\x7f\x9e\ +\x0d\x82\xf7\xbe\xa0\xfb\x5b\x7e\x07\xe6\x9c\x39\xef\x3e\xee\x9d\ +\x3b\x80\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x96\xff\ +\x0d\xea\x36\xf0\x72\x61\x1f\xc0\x53\x00\x40\xf2\xdc\x44\x86\xbd\ +\xba\x3d\x57\x83\xd6\x02\x0e\xf6\x48\x72\xa1\x41\x16\x4a\x86\xc2\ +\x43\x7e\x07\x47\x75\xfa\xae\x06\x47\xeb\xa7\xaf\x87\x5b\x31\xa3\ +\x8c\xec\x7b\x20\xdb\xb5\xfa\xae\x02\x03\xaf\x80\x92\xa8\xb9\x9b\ +\xe0\x86\xf1\x34\xe7\x75\xfb\x57\x43\xef\x0a\x00\xb0\x35\x60\xe5\ +\x2a\x00\x10\x84\x32\x87\x6e\xd1\xee\x5f\x0d\xed\x01\xee\x77\x32\ +\x44\x92\x0d\x51\x9a\xb7\x47\x42\xdd\xfe\xd5\x30\xf2\x04\xfc\x36\ +\xce\x39\x09\xee\x88\xd2\xbc\x9c\x1a\x33\x91\x61\x25\x8c\x2d\xc1\ +\x42\x9a\x6f\x15\x79\x38\x42\x6a\xf6\x72\xe1\x0d\x53\x39\xca\x31\ +\xfa\x0e\x3e\xcf\xf0\x89\x90\x17\x2b\x15\x5e\x4e\xe5\xe4\xb4\xc9\ +\x2c\x7f\x9c\xe3\x30\x4d\xe5\xc2\x5e\x01\xcf\x94\xcf\x1d\xd2\x2b\ +\x64\x38\x69\x32\x4b\x2c\x05\x00\x80\x97\x53\xef\x00\x54\x9c\x07\ +\xdc\x04\xb7\x8c\xa7\xf9\xc5\x54\x8e\xd8\x0a\x00\x56\x3e\x23\x38\ +\x01\xeb\x0b\x9d\x5c\x88\xd2\xd6\x9a\x58\xf7\xe1\xe0\x1b\x6b\xa2\ +\xe6\xca\x95\x9f\x10\x31\xf2\x70\x62\x2d\x60\xaa\x8b\x4b\x81\xcb\ +\x4d\x51\x9a\x37\x28\xdf\x4d\x64\x88\xfd\x24\x36\x75\x8c\x33\x21\ +\xb8\x2b\x42\x6a\xf0\x06\xc3\x7b\xba\xfd\x63\x2f\x00\x00\x5e\x64\ +\xf9\x1a\x60\x7b\x85\x20\x3c\xa9\xdb\xfb\x9f\x28\x00\x00\x1c\x85\ +\xe9\x58\x7c\xe3\x30\x2d\xc7\x7b\x28\x9b\x15\x25\x5f\x3e\x17\xc1\ +\x33\xdd\xde\xb1\x17\xb0\x77\x58\xea\x11\xca\x30\x88\x6d\x25\x02\ +\xe5\xda\x64\x87\xd3\xac\xdb\x3f\xd6\x02\x4e\xf4\x4b\xc2\x0d\xa4\ +\x0f\x40\x53\xa9\x22\xb7\xfd\x76\xa7\xdb\x44\x86\x58\x0b\xf8\xe0\ +\xaa\x9b\x00\xd2\xc5\x33\x01\x1e\xd5\x6d\x74\x2e\x80\x8c\x3c\x24\ +\xad\x35\xf1\x1d\x85\x07\xe5\x12\x44\x6e\x95\x8d\x5f\xba\x09\xb6\ +\x98\xbc\x29\x8a\xa5\x80\xa6\x01\xc9\x90\x32\x50\xe6\xff\xc9\x09\ +\x98\x2a\x74\xf2\xb3\xc9\x2c\xc6\x0b\x48\x0d\x89\x27\x4a\x46\x01\ +\xd4\x15\x8d\xe7\xa1\x78\xc0\x3f\xce\x57\xa6\xf3\x24\x4c\x9a\xfd\ +\xbe\x0d\x96\x11\x02\xc5\x57\x64\x01\xc0\xb4\xdf\xc1\x82\xc9\x2c\ +\xcb\x44\x5e\x58\xea\x60\x7f\xbf\x34\x2a\x47\xf2\x00\xca\xce\xfe\ +\xec\xf2\xb3\x7c\x6c\x2a\x47\x39\x46\x76\x81\xd6\xbc\xd4\x2a\x57\ +\x86\x00\xec\x2c\x11\x44\xae\xfb\x59\xde\x31\x91\x61\x25\xf4\x17\ +\xd0\x2d\xce\xec\xa2\xea\x01\xd0\x52\x2a\xc8\x5d\x3f\xeb\x5c\xd5\ +\xee\x5f\x05\xed\x05\x78\xbb\x71\x65\xf9\xbf\xc1\x22\x9e\x36\x26\ +\x9d\xf3\xa6\xf6\xfa\xbf\xa1\x75\x17\x68\xcd\x4b\xed\xec\xa2\xfc\ +\x00\x90\x2c\x1a\xbf\x59\x57\xc3\xe6\xb1\xa3\x34\xf2\x7b\xbf\x1a\ +\x5a\x57\xc0\xd7\x8f\x50\x00\x96\x8a\x47\x24\xdb\xfe\x95\x2f\x0f\ +\x68\x2e\x60\xaa\x8b\x4b\x04\xcf\x02\x98\x01\x30\xad\xc8\x23\x13\ +\x19\xbe\xd7\xe9\x69\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\ +\x8b\xc5\x52\x8d\x5f\x44\x94\xcc\xbe\xc4\xf9\xa0\xab\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x9b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x08\x05\x51\x34\x0e\x66\xc3\x04\xae\xc0\x98\ +\x26\xac\xe6\x06\x22\xc4\xf2\xae\xfc\x09\xc9\x6b\x11\xa1\x64\xba\ +\xcc\x75\x99\xbf\xee\x51\xa3\x60\x98\xc9\xfd\x5a\xaf\x1c\xfd\x0c\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd2\x9f\x51\ +\x13\xd9\x99\x9d\xa2\x0e\xd8\x07\x09\x21\x90\x7b\x88\xd1\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf9\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xab\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xb7\x2a\xc0\x02\xb2\xb0\x80\ +\x02\xc4\x95\x15\x07\x9f\x21\xd9\x6e\xba\xbc\x8c\x0d\x31\x8f\x73\ +\x7d\xf7\x73\x5f\x43\x78\xec\xe2\xf4\x4f\x14\x40\x0b\x68\x0a\xa0\ +\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\ +\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\ +\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\ +\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\ +\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\ +\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x79\x01\x55\xd1\x04\x80\x1e\x3b\xba\xea\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x27\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd9\x49\x44\x41\x54\x58\x85\xe5\ +\x96\x31\x6b\x54\x41\x14\x85\xbf\x33\x59\x45\x09\x2a\x5a\xd8\x58\ +\x58\xd9\x58\x88\x4d\xd8\xa4\xb1\x4c\x40\x09\xb8\x89\xae\x95\x01\ +\x3b\x1b\x21\x3f\x40\x2c\x42\x7a\x11\x04\x4b\x21\xa9\x7c\xba\x89\ +\x10\x2c\xa2\x9d\x8d\x59\xd3\x48\x0a\x1b\x41\x04\x4d\x63\x67\x64\ +\x51\x92\xec\x1c\x8b\x65\xc1\x4a\xdf\xbc\x37\x28\xe8\xa9\xe7\x9e\ +\xfb\xdd\x3b\xf7\xce\x7b\xf0\xbf\x4b\xb9\x0d\x27\x0a\x9f\x88\x0d\ +\xbf\xb7\xf0\xeb\x56\x38\xfe\xbb\xf3\x8d\x9c\xc9\xcf\xad\x7b\x34\ +\xf6\xfc\x0c\x38\x26\x97\x8b\x09\xb9\x92\x9f\x2d\x7c\xf0\x70\xcf\ +\x2b\xc0\x78\x4a\x5c\x16\x80\xab\x85\x47\x8e\x1c\x88\x4b\xc0\x64\ +\xc9\xc2\x33\x02\xd8\xfa\xd8\x88\xf7\xb1\xae\x61\x23\x13\xff\x28\ +\x40\x73\x25\x2e\x18\xdd\x04\x83\x14\x11\x49\x4d\xa8\x05\xd0\xec\ +\x78\x1e\xe9\x36\x80\xad\x08\x69\xc9\x6b\x01\x34\x3b\xbe\x8e\x7c\ +\x97\x41\xd6\xa8\xc4\xca\x6b\x01\x8c\x3f\xf5\x34\xf2\x43\x18\x54\ +\xae\x0a\x95\x0f\x95\xfc\x0e\x8c\x75\x7c\xc1\xd1\x05\x30\x62\xec\ +\xaa\x95\x0f\x95\xd4\x81\xb1\x55\x9f\x0f\xf2\x1a\x70\x08\x6c\xa1\ +\xa4\x89\xaf\x05\xd0\x7c\xe2\x33\xc1\x5e\x07\x8e\x5a\x98\x0c\xc9\ +\x4b\x03\x4c\x14\x3e\x45\xf0\x0b\xe0\x24\xc2\xa9\xbb\xfe\x2b\x95\ +\x9a\x81\xd8\xf0\x27\x00\x63\x72\xb4\xfd\x67\x95\xbd\x82\x2d\x80\ +\xb2\x1f\x98\xec\x00\x61\x5f\x17\x81\x0f\x48\xa5\x63\xb2\x02\xbc\ +\x6a\x6b\x9b\xa8\x49\xe0\x33\x46\x56\x3e\x88\xd2\x46\xdd\x2b\x7a\ +\x17\xa5\x29\x60\x47\x46\xc6\x59\x20\x92\x4c\x36\x5b\x7a\x13\xad\ +\x69\xe0\xbb\x50\x16\x88\x64\x83\xcd\x59\xbd\x54\x50\x1b\xe8\x0f\ +\x20\x54\xeb\xb7\xae\x52\x05\x1b\x97\xb5\x86\x75\x03\x40\x83\x2e\ +\x54\x86\xa8\xdc\xc2\xee\xac\x96\x91\xe6\x87\x3e\xae\x08\x51\xeb\ +\x0e\xbb\x2d\xdd\xc3\x5e\x04\x50\x45\x88\xda\x43\xd4\x9d\x09\x77\ +\x6c\x3f\x00\x90\x9d\x0c\x51\x7f\x95\x24\x9f\xee\x87\x5b\xc8\x8f\ +\x90\x90\xd3\x36\x23\xcb\x2e\x3f\x6e\xab\xff\x75\x2f\xcc\x01\xcf\ +\x53\x97\x22\xdb\x8b\xf6\xb6\xad\xdd\x6f\xa3\x9a\x01\x36\xfe\x0a\ +\x00\xc0\xd6\x94\x7a\x61\x5f\x97\x90\x77\x6c\xbe\xe4\xf4\xfe\x77\ +\xf5\x03\x8b\xca\xad\x03\x49\x73\x42\xef\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xd8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8a\x49\x44\x41\x54\x58\x85\xe5\ +\x96\x3d\x72\xd3\x40\x18\x86\xdf\xd7\x49\x01\x9c\x83\x12\x5a\x4b\ +\x70\x05\x0a\xa2\x35\xc4\x21\x24\x71\xfe\x66\xc2\x01\x32\xc3\x19\ +\x28\xd3\x51\x24\x01\x3b\xe4\xd7\x48\xce\x0c\x67\x60\xc6\xd6\x21\ +\xa0\x83\x1b\x00\x05\xd6\x4b\xe1\x28\xc8\x2b\xc9\x92\x3c\x6a\x18\ +\xbe\x4a\x5a\x7d\xfb\x3e\x8f\x77\x25\xcf\x02\xff\x7b\x31\xbe\x78\ +\x74\xad\xc7\x51\xa4\xb7\x10\xee\x92\x7c\x3d\x34\x0c\xea\x04\xb9\ +\x81\x8c\xa4\x37\x24\x7e\x41\x7c\x35\x6c\xf1\x33\x00\x34\xe2\x86\ +\x28\xd2\x11\x80\x87\x20\xee\x0b\xea\xbb\xbe\xda\x75\xc1\x9d\x40\ +\x2b\x82\xfa\x93\x6c\x3c\x10\x75\x18\x3f\x6b\x24\xfa\xee\x24\xae\ +\x1b\xa2\xce\xea\x90\x70\x02\xad\x00\x3a\x4d\xb2\x48\xdc\x4b\x0b\ +\x90\xfb\x00\xa2\x3a\x25\x26\x73\xa7\xe1\x00\xa2\x48\xdc\x4f\x09\ +\x8c\x3c\xfa\x22\xd7\x32\x24\x4e\xe7\x91\x70\x7d\xb5\x45\x9d\xd9\ +\x70\x90\x9d\xd0\xb0\x9f\x12\x00\x80\xd0\xe3\x79\x86\xc4\x42\x55\ +\x89\x1b\x78\xea\x97\x83\xec\x8c\x3c\x7e\x48\xf6\x36\x60\x55\xe8\ +\xf1\x5c\xe2\x7a\xa6\xc4\x40\xcb\x85\xf0\x81\x96\x6f\xe0\x0b\x45\ +\x70\x20\xf1\x19\xda\xd5\xf4\xb5\x4a\xea\xc4\x92\x1c\x93\x5c\x1d\ +\x7a\xbc\xca\x85\x4b\x67\x16\x5c\x20\x37\xb2\xe0\x33\x05\x00\xc0\ +\x0d\xf4\x52\x50\xaf\x8c\x44\x33\xd0\x73\x42\xe7\x55\xe0\x85\x02\ +\xb3\x24\x04\xbe\x88\x5f\xa6\x79\xe1\xa5\x04\x00\xc0\x19\x68\x0d\ +\x52\x37\x4b\x62\x12\x92\x01\x17\x3b\xa3\x16\x4f\x8a\xb2\x4b\x09\ +\xe4\x49\x48\x88\x40\x80\xd3\x62\xa5\xe1\x95\x04\x12\x12\xbd\x19\ +\xf3\x2a\xc1\x2b\x0b\xdc\x4a\x00\x3d\x48\xf6\x5c\x09\xdc\x0c\x0d\ +\x7b\x55\xf2\x52\xff\x03\x25\xea\xa7\x24\xd9\x83\x02\x44\xe1\x47\ +\xd5\xb0\x4a\x02\xce\x40\x2d\x48\x17\xcc\x98\x47\xa0\x01\xea\xc2\ +\xf1\xf5\xac\x4a\x66\xe9\x2d\x70\x03\x19\x41\x97\x00\x16\x13\xc3\ +\x02\x09\x6b\x3b\xc6\x20\xdb\x23\x8f\x7e\x99\xdc\x52\x2b\x90\x07\ +\x17\xb8\x25\x61\x13\x40\x72\x4b\x16\x20\x5d\x3a\x03\xb5\x6a\x11\ +\x68\xfa\xf2\xf2\xe0\xa1\x61\x37\x34\xec\x09\xdc\x9a\x57\x62\xa6\ +\x40\xd3\x97\x47\xea\xca\x86\x93\xdc\x0e\x0d\xbb\xf1\x40\x68\xd8\ +\xcd\x91\xb8\x28\x92\xc8\x15\x98\x05\x1f\x7a\x7c\x6f\xf7\x87\x86\ +\x5d\x92\xdb\x96\xc4\x62\x91\x44\xe6\x4b\xd8\x1c\x68\x89\x52\xbf\ +\x2c\x3c\x59\xee\x40\x9b\x92\x8e\xad\xec\xdf\x04\xdb\x59\x07\xdd\ +\xd4\x0a\xe4\xc1\x01\xee\x14\xc1\x01\x60\xd2\xc3\x1d\x58\x2b\x21\ +\xe8\xd2\x0d\x64\xec\xfe\xa9\x15\x70\x02\x3d\x05\xf4\x31\x0b\x3e\ +\x32\x7c\x57\x04\xb7\xb2\xb6\x00\x1d\xa1\x60\x25\x6e\x1f\x36\x7d\ +\x3d\x21\x75\x5d\x07\x3c\x21\xb1\x0d\xe8\x30\x25\xd1\xa0\x19\x2e\ +\xf1\x13\x30\x75\x2a\xd6\x41\x06\x7c\x77\x5e\x38\x00\x8c\x0c\x8f\ +\x01\xee\xc2\xde\x8e\xb1\x0e\xe2\x9b\xbf\x67\xf5\xe9\x33\x60\x0c\ +\x3f\x9e\x17\x5e\x20\x31\x4e\x09\x40\xdc\x03\xf0\x05\xc0\x77\x88\ +\x9d\x3a\xe0\x53\x12\xe4\x06\x80\x6f\x10\xbe\x8a\xdc\xab\x2b\xfb\ +\xdf\xaf\x3f\xf0\x88\x83\xb8\x80\x8e\x5a\x2b\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xa4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x56\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\x58\xac\xfd\xdb\x60\xb1\xf6\x6f\x03\x25\x66\x30\x51\ +\xa2\x99\x1a\x60\xd4\x01\xa3\x0e\x18\x75\xc0\xa8\x03\x46\x1d\x30\ +\xea\x80\x01\x77\x00\x0b\xe5\x46\xfc\x77\xa0\xa4\x4a\x1e\x0e\x21\ +\xc0\x78\xe0\x44\x30\x73\x03\xb9\xba\x07\x3c\x04\x46\x1d\x30\xea\ +\x80\x51\x07\x8c\x3a\x60\xd4\x01\xa3\x0e\x18\x70\x07\x00\x00\x30\ +\xcb\x0b\x07\x89\x28\x47\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x03\xf0\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xa2\x49\x44\x41\x54\x78\x9c\xed\ +\x97\xbd\x6f\x1c\x45\x18\xc6\x9f\x67\x6e\xb1\x8c\x94\xd0\xc4\x29\ +\xa2\xfb\x8e\xb0\x30\x35\xa1\x87\x20\x2c\x94\x0a\xa7\x4c\x07\x51\ +\x04\x7f\x00\x10\x51\x44\x08\x21\x21\x3e\x6a\xa4\x28\x31\xe9\x10\ +\x05\x08\x68\x88\x25\x4b\xe0\x02\x3a\xa0\xc6\x91\x89\x76\x76\xf7\ +\x4e\x29\x9c\x8e\x02\x07\xdf\xcd\x43\x71\x32\xba\xdb\xdd\xf3\x7d\ +\xf8\xf6\x9c\x8f\xf9\x95\xf3\xee\x3b\xf3\xbc\xcf\xbe\xbb\x33\x03\ +\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\x1e\x8f\xc7\xe3\xf1\x78\x9e\ +\x2c\x78\x5c\x0b\x5b\x9b\xac\x81\xf8\x02\xa0\x01\x71\xb3\x51\xab\ +\x5c\x3b\x0e\x1d\xc7\x62\x40\x14\x25\x57\x04\x5c\x07\x60\xfe\x1f\ +\x14\xae\x34\x1a\xd5\xf5\x79\x6b\x31\xa3\x1f\x99\x2d\x51\x94\x5c\ +\x15\x70\x23\xb3\x36\x71\x33\x8a\x92\xf7\xe6\xad\x67\x6e\x1d\x20\ +\x89\x51\xd2\xfa\x0c\xc2\x3b\x23\x1e\xfd\xbc\x5e\xab\x5c\x25\xa9\ +\x79\xe8\x9a\x8b\x01\x92\x82\x28\x6a\xdf\x00\xf5\xc6\x58\x09\xc4\ +\xad\x7a\xb5\xf2\x16\xc9\x4e\xc1\xd2\x8a\x37\x20\x0c\xc3\x45\x32\ +\xf8\x1a\xc4\xeb\xfd\xe3\x02\x40\xc8\xa9\x27\xc1\x64\x84\x10\xdf\ +\xab\xdb\xb9\xd4\x6c\x36\xf7\x8a\xd4\x57\xe8\x3f\x60\x67\x67\xe7\ +\x19\x9a\xe0\x76\xa6\x78\x01\x04\xba\x00\x45\x40\x04\xba\x99\x7e\ +\x17\xd6\x68\x82\x1f\xb7\xb7\x77\x4f\x16\xa9\xb1\xb0\x0e\xd8\xb9\ +\x77\xef\xf4\x53\xff\x76\x36\x00\xbc\x30\x10\x90\x00\x9a\x6e\xaf\ +\x07\x52\x52\xe4\x4a\x60\x46\xd2\xef\xfb\x0b\xc1\x85\xe5\x33\x67\ +\x76\x8b\xd0\x59\x88\x01\x77\xef\xb6\x6b\xa5\xc0\x6d\x02\x78\x2e\ +\xb5\x9a\x00\x3a\x68\xd8\xff\x8d\x00\x65\xa0\x8c\xae\x3b\x9d\xc0\ +\xbc\xfa\x6c\xb9\x9c\xcc\x5a\xeb\xcc\x0d\xb0\xd6\x3e\x0f\x96\x36\ +\x01\x54\x52\x2b\x09\x82\x1b\x53\x94\x51\x4a\x1b\x81\xc4\x39\xb3\ +\xda\x6c\x96\xb7\x67\xa7\x76\xc6\xff\x80\x38\x8e\x5f\x04\x4b\xbf\ +\x20\x5d\x3c\xc6\x2f\xbe\xf7\x30\x1c\x30\xb8\x0d\x0a\xa8\xd2\xb8\ +\x5f\xe3\x38\x3e\x37\x0b\xad\x07\xcc\xcc\x80\x28\x6a\xbd\xe2\xc4\ +\x9f\x01\x9c\x4a\x85\x44\x8e\x5f\xfc\x01\xa4\x1c\xb2\xdf\xca\x29\ +\x27\x6e\x59\xdb\x3a\x3f\xb5\xd0\x14\x33\x31\xc0\xda\xe4\xa2\xa0\ +\xdb\x00\x4e\x0c\x04\x04\x01\x70\x43\x3f\xf9\x43\xe8\xe5\xd0\x41\ +\x99\xec\x13\xa0\x36\xac\x4d\xd6\xa6\x53\x3b\xc8\x91\x0d\xb0\x36\ +\xb9\x0c\xe2\x1b\x00\x0b\x03\x01\xd2\x61\x8a\x37\x9f\x81\x74\x20\ +\xd3\xf3\x2c\x80\xf8\xd6\xda\xf8\xcd\xa3\x4e\x7f\x24\x03\xac\x4d\ +\xde\x05\xb1\x9e\x9e\x87\x40\xde\x9b\x9b\x1e\xa9\xb7\x7b\x0c\x62\ +\x40\x7e\x69\x6d\x3c\xea\x68\x7d\x28\x53\xed\x02\x92\x68\xe3\xd6\ +\x27\x04\xf2\x2e\x2f\x0e\xd9\x4d\x7e\x56\x10\x39\x2f\x4d\xc0\xa7\ +\x8d\x5a\xe5\xfd\x69\xee\x0f\x13\x1b\x20\x29\x88\x92\xd6\x75\x08\ +\x97\x73\x84\x38\x16\x57\xfc\xc1\x1a\x64\x7e\xe7\xae\xd7\x6b\x95\ +\xb7\x49\x76\x27\x99\x6f\x22\x03\xc2\x30\x5c\x64\x29\xf8\x0a\xc2\ +\xc5\x8c\x30\xc1\x91\xc5\x16\xdf\xb7\x16\xc9\x1c\x13\x88\xef\xf6\ +\x1f\xec\x5d\x5a\x5e\x5e\x7e\x30\xee\x5c\x63\x1b\xb0\xbd\xbd\x7b\ +\x72\xf1\xe9\xbd\x1f\x00\xe4\x6c\x41\xca\xec\xdb\xc5\x23\x02\xcc\ +\xeb\x84\x9f\xf6\xfe\x59\x5c\x5b\x59\x39\xfd\xf7\x38\xb3\x8c\x65\ +\x40\xbb\xdd\x5e\xda\xef\xb8\x0d\x00\x03\x87\x10\xf5\xfa\x71\xa2\ +\x96\x9b\x35\x12\x4a\xe9\xeb\x83\x80\xdf\x16\x02\x73\xa1\x5c\x2e\ +\xdf\x1f\x95\x3f\xd2\x80\xbf\xda\xed\x6a\xd0\x71\x9b\x00\x56\x06\ +\x12\x09\x69\x82\xd3\x5d\x91\x90\x30\xca\xdc\x1f\xf4\x67\x50\x32\ +\xab\x95\x4a\xa5\x75\x68\xee\x61\xc1\x30\x6c\xaf\x18\xe3\x36\x05\ +\x54\x53\x69\xea\xb5\xfd\xc3\x04\x4d\xef\xb3\xe8\x1f\x42\xec\x3a\ +\x66\xf5\xec\xd9\xf2\x9d\xa1\x59\xc3\x02\x71\x1c\x9f\x73\xe2\x06\ +\x80\xa5\x54\x48\xc0\xc3\xf1\xe6\x73\x30\xc8\xd6\x74\x9f\x70\xaf\ +\xd5\xeb\xf5\x3f\x86\x25\x64\xb0\xb6\xf5\xb2\x13\xb7\xf0\x68\x15\ +\x0f\xe4\x9f\x41\x96\x04\xb3\x15\x86\xc9\x4b\x79\x09\x99\x0e\xb0\ +\x71\x7c\x0d\xe2\x87\x79\xb1\x47\x1c\x81\xfa\xa0\x51\xab\x7d\xd4\ +\x3f\x98\x29\x32\x8a\x92\x8e\x80\xd2\xfc\x74\xcd\x0f\x02\xdd\x7a\ +\xbd\x1a\xf4\x8f\xe5\x1d\x2b\x1f\x5b\xf2\x6a\xcb\x18\x60\xc8\x8f\ +\x73\x2e\x1e\x8f\x01\x74\xbd\xda\x3c\x1e\x8f\xc7\xe3\xf1\x78\x3c\ +\x1e\x8f\xc7\xe3\xf1\x78\x3c\x4f\x36\xff\x01\x8b\x04\x4e\x83\xb0\ +\x2f\x88\xa2\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x2d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xdf\x49\x44\x41\x54\x78\x9c\xed\ +\xd5\x3f\x88\x14\x67\x18\xc7\xf1\xef\x33\xb3\x77\x08\x7a\x68\x93\ +\x10\xdd\x99\x9b\x59\xb7\x10\xe2\x35\x91\x2b\xa2\x42\x8a\x20\x01\ +\x95\x24\x58\xd8\x48\x34\x29\x44\xb0\xb0\x08\x81\x60\x0a\x91\x40\ +\x0a\xc1\x10\xb0\x11\x42\x6c\xa2\x45\x24\x11\x84\xc4\xc4\x34\x16\ +\x11\x2e\x68\x63\x75\x58\x68\x74\xde\x99\x59\x41\xcf\x53\x38\x14\ +\x3d\x6f\xdd\x7d\x52\x48\xc2\xde\x70\xfe\xe1\x66\x76\x15\x7c\x3e\ +\xe5\xfb\xcc\xfb\xdb\xe7\x7d\x66\x5f\x06\x8c\x31\xc6\x18\x63\x8c\ +\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xba\x90\xb2\x01\x69\x9a\xbe\ +\xad\x78\xc7\x81\x3a\xca\x77\x51\x14\x7c\x2b\x22\x5a\x41\x6f\x0b\ +\x72\x2e\xdf\x86\x70\x18\x00\x65\x5f\x1c\x87\x67\xcb\xe4\x55\x30\ +\x80\xfc\x2f\x85\xf7\x7a\x96\x4e\xdc\xbf\x37\xb3\x7b\x6c\x6c\x6c\ +\xae\x6c\x76\x2f\x55\x95\x2c\x6b\x7d\xa9\x70\xa8\x67\x79\x66\xfa\ +\xf6\xad\x37\xc6\xc7\xc7\xdb\x8b\xcd\xf5\x4a\x37\x86\x14\x33\x76\ +\x2e\x1b\x59\xfe\x67\x92\x24\x2b\xca\x66\xff\xff\x1b\xaa\xb5\x2c\ +\xcb\x8f\x16\x0e\x0f\x15\xbc\xc0\xd2\x01\x59\x96\x8d\x75\x55\xce\ +\x01\x6f\x16\x4a\x97\xbb\x1d\x7f\xcb\xea\xd5\xab\xd2\x32\xf9\x53\ +\x53\x53\xcb\x1e\x3c\x7c\x74\x12\xd8\x5a\x28\x3d\x12\xbc\xed\x51\ +\x54\xff\xad\x4c\x7e\xe9\x01\x00\x38\xe7\x1a\x88\x7f\x16\x58\x53\ +\x28\xdd\x44\xfd\xad\x71\xbc\xea\xd2\x22\x73\x57\x22\xde\x19\x90\ +\x75\x85\xd2\x5d\xc1\xfb\x28\x8a\xea\x13\x8b\x6a\xb8\x47\xe9\x2b\ +\x00\x10\xc7\x71\xe2\x7b\x6c\x10\x38\x5f\x28\xbd\x85\x74\xce\x3b\ +\xd7\x2a\xbe\xbd\xe7\x4a\xd3\x74\x2d\x9e\x7f\x61\x81\xc3\x5f\xef\ +\xf8\xb2\xbe\x8a\xc3\x43\x45\x03\x00\x08\xc3\xf0\xee\xdc\xdc\xec\ +\x07\x28\x3f\x15\x4a\x4b\x11\xfd\x35\xc9\xb2\xbd\x2f\x9a\xe5\x5c\ +\xeb\x7d\xc5\x9b\x40\x19\x9d\x57\x50\x2e\xb6\x87\x6b\xef\x36\x83\ +\xe0\x4a\x15\x3d\x43\x45\x57\xa0\x97\xaa\x7a\x59\x96\x7f\xa3\xc8\ +\x57\x0b\x94\x0f\x47\xa3\xc1\x7e\x11\xe9\x3e\x6d\x7f\x9a\xb6\x76\ +\x29\x7a\x0c\x18\x9a\x57\x10\x4e\x0f\xf9\xde\x27\xf5\x7a\xfd\x41\ +\x95\xfd\x56\x3e\x80\xff\xa4\x69\xbe\x47\xe1\x28\xe0\xf7\xae\x2b\ +\xfa\x33\xdd\xce\xa7\x8d\x46\x63\x76\xde\xfa\x93\xcf\xdc\x01\x85\ +\xaf\x8b\x59\x0a\x47\xe2\xd1\xe0\x0b\x11\xe9\x54\xdd\x67\xdf\x06\ +\x00\xe0\x5c\xbe\x19\xe1\x17\x60\xe9\xfc\x8a\x4e\xd4\x7c\xef\xe3\ +\x20\x08\xee\x00\x4c\x4e\x4e\x0e\x8f\x8c\xac\xf8\x5e\xd1\xcf\x0a\ +\x11\x2a\xf0\x79\x14\x85\x47\xfa\xd5\x63\x5f\x07\x00\xe0\xdc\x8d\ +\x77\x90\xee\xef\xc0\xca\xde\x75\x85\xab\xbe\xe8\xe6\x76\xbb\x3d\ +\xed\xd7\x86\x4e\x81\x6c\x2a\x6c\x9d\x45\xd9\x11\xc7\xe1\xe9\x7e\ +\xf6\xd7\xf7\x01\x00\x5c\xbb\x76\x63\xd4\xaf\x75\xff\x00\xd6\xbe\ +\xe0\x96\x69\xed\xca\x87\x8d\x46\x70\xa1\x9f\x7d\x41\x85\x5f\x81\ +\x67\x69\x36\xeb\x59\xe7\xf1\xdc\x46\xe0\xdc\xf3\x9e\x55\xb8\xea\ +\x7b\xac\x1f\xc4\xe1\x61\x40\x03\x00\x68\x36\x9b\x33\xf7\xef\xcd\ +\x6c\x11\xf4\xc7\x67\x3c\xf6\xf7\x70\xcd\xdb\x10\x86\xe1\x3f\x83\ +\xea\x6b\x20\x57\xa0\x97\xaa\x8a\xcb\x5a\x07\x05\x0e\x16\x4a\xa7\ +\x7c\x8f\x5d\x61\x18\x3e\x1c\x74\x4f\x2f\x85\x4b\xf3\x1f\x5c\x9a\ +\x3f\x76\x69\xde\x4e\xd2\xfc\x90\xaa\x0e\xec\xdf\xf8\xca\x50\xd5\ +\x5a\x92\x24\x4b\x5e\x76\x1f\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ +\x31\xc6\x18\x63\xcc\x6b\xe2\x5f\xd1\x80\xf4\xd2\x90\x91\xe7\x38\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x2d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdf\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xb1\x6b\x14\x51\x10\x87\xbf\xdf\xbb\x43\x82\x82\x47\x2c\x6c\ +\xac\xed\x2d\xad\x2c\x24\xb7\x01\x25\xcd\xc5\x8d\xd5\x05\x64\x15\ +\xd3\x08\xf9\x03\xc4\x42\xec\x45\x10\x54\xe2\x21\x78\x95\xae\x77\ +\x4d\xb0\xf0\x36\x58\x58\x59\x8a\xad\x20\x16\xda\xd8\xe8\x05\x0c\ +\x41\x72\x6f\x2c\x56\xc5\x4a\xf7\xed\x3e\x22\xe8\x74\x03\x3b\x33\ +\xdf\xfc\x76\xe6\x31\xf0\xbf\x9b\x62\x27\x5c\x4c\xb3\x23\xde\xeb\ +\x2d\x60\xc5\xe8\xfe\xfc\x9f\xbe\x6f\xc7\x2c\x9e\xf4\xfb\x87\xfc\ +\x8e\x9e\x02\x9d\xaa\x31\x2e\x56\xf1\x34\x4d\x0f\xd8\xce\xdc\x18\ +\x38\x19\x12\x17\x05\x20\x4d\xd3\xd6\x27\xdf\x79\x08\x96\x84\xc6\ +\xc6\x00\xd0\x67\xdf\xb9\x2d\x38\x8f\x01\xe0\xf7\x15\x60\xe1\x5c\ +\x76\x1d\x58\xc3\x00\x27\x0f\xdf\x31\x2a\x5a\xa3\x21\x5c\xe8\x5d\ +\x5c\x97\x71\x15\x00\xc9\x63\x16\x54\x1c\x1a\x28\xd0\xed\x65\x7d\ +\x89\x9b\x3f\x8b\x13\x5e\xbc\x36\x40\xb2\x9c\x2d\x21\x3d\x28\xbd\ +\x7a\x9d\xd7\x06\x48\x7a\xd9\x29\x43\x8f\x81\x96\x61\x56\xb7\xf3\ +\x5a\x00\xdd\xf4\xd2\x09\x93\xdb\x04\xe6\x30\x33\xa1\xa0\x89\x6f\ +\x04\xd0\x5d\xbe\x7c\x1c\x6f\xcf\xc0\x0e\x1b\x58\xf9\xdf\x9b\x5b\ +\x25\x80\xd3\xe9\xda\x31\x98\x15\xc0\x51\xc0\x14\xb8\xeb\xbf\xb3\ +\x4a\x6b\xd8\xf2\x7b\xef\x7f\x71\xa3\x15\x87\x8a\x0a\x08\x5e\x43\ +\xe0\x0b\x13\x13\x60\xcf\xb5\xcf\x80\xbd\x53\x40\x4c\x54\x80\xe7\ +\xf9\xdd\x0f\xd0\x4e\x80\x8f\x80\x2c\x22\x44\xe5\x44\xc5\xe8\xde\ +\x1b\x9c\x16\x41\xdb\x2a\x0f\x99\x28\x10\x41\x49\x8a\x7c\xe3\x95\ +\xcc\x2f\x01\xbb\x80\xcc\x9a\x43\x04\x27\x98\x8c\x07\x2f\x84\xad\ +\x00\x33\x09\x81\x1a\x9d\x75\xb5\x3a\x98\x8c\x06\x9b\x98\x5d\x28\ +\x3d\x73\x34\xb8\x2d\x6b\x4b\x58\x8c\x07\x43\xd0\xfa\x8f\x3c\xa5\ +\x1a\xfb\x08\x00\x50\x8c\x36\x6e\x99\xec\x06\x80\x79\x9c\x6a\x28\ +\xd1\x78\x88\xb6\x9e\x0c\xae\x09\xee\x20\x30\xc3\x11\xa8\x44\x8c\ +\x55\xb2\x8e\x9b\x5e\x31\x78\x84\x80\xc0\xcd\x88\xb2\xcb\x79\x9e\ +\xcf\xe6\xdd\x74\x15\x34\x09\x8d\x8d\xf6\xa2\xe5\x79\xfe\x55\x07\ +\x77\x7b\xc0\xcb\xbf\x02\x00\x30\x19\x0e\xbf\x38\x67\x67\x91\xb6\ +\x81\x69\xcc\xdc\xff\xae\x7d\x03\x68\x47\x95\x0a\x88\x7f\x49\xe0\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x38\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xea\x49\x44\x41\x54\x78\x9c\xed\ +\x98\xc1\x6b\x13\x41\x18\xc5\xdf\xb7\x69\xda\xb4\x45\x2a\xa2\xf5\ +\x90\x4c\x36\x09\x04\x4f\xde\x8a\x15\xaa\x17\x11\x04\x2f\x2a\x82\ +\x22\x1e\xec\x41\x10\x04\xe9\xc5\x9b\xa0\x07\xbd\x89\x7f\x81\xa0\ +\x1e\xa4\x78\x11\x44\xa1\x08\xa2\xf5\x20\x1e\xbc\x29\x82\x2d\xb1\ +\xcd\x4e\x36\x11\xb4\x05\x4d\x15\x1b\x9a\x64\x3f\x4f\x62\x93\x6c\ +\x4d\x0b\x99\xd9\x1e\xbe\xdf\xf1\x7d\xb0\xef\xcd\xdb\x59\x66\x58\ +\x40\x10\x04\x41\x10\x04\x41\x10\x04\x41\x10\x04\xa1\xc7\x78\x9e\ +\x3f\xed\x69\x9f\x3d\xed\x73\xb1\x54\x9a\x8c\x3a\x4f\x3b\x64\xf2\ +\xe1\xc5\x62\x31\x41\x4e\xdf\x6a\x8b\xc8\x74\x24\x93\x49\xcd\x9a\ +\xf4\xdd\x0a\x8e\xc9\x87\x0f\x0f\x0f\xf7\x75\x88\xc4\xaf\xb4\xd6\ +\x39\x93\xbe\x5b\xc1\x68\x01\xa3\xa3\xa3\xbf\xc2\x74\x86\xb3\x30\ +\x37\xb7\xb4\xc3\xa4\xf7\x66\x31\x5a\x00\x00\xb8\xe9\x54\xe7\x2e\ +\x00\x90\x18\xac\xad\x30\xb3\x71\xff\x6e\x18\x0f\x40\x44\xcd\xfa\ +\x5a\x6d\x24\x6c\xa6\x4b\xe5\xa6\x69\xff\x6e\x58\x79\x03\xf9\x7c\ +\x7e\x25\xe6\x20\x1f\x36\xf3\x74\xe9\x8d\x8d\x0c\x1b\x61\x6d\x0b\ +\x2a\xa5\x3e\x13\xe8\x68\xe7\x84\x26\xbc\x92\x7f\xdb\x56\x8e\x76\ +\xac\x7e\x83\xae\x9b\x7a\x09\xc6\x95\x8e\x01\xe3\xaa\xe7\xf9\xe7\ +\x6d\x66\xf9\x8b\xd1\x7b\xc0\x46\x68\x5d\x7a\xc0\xa0\x0b\xed\x7a\ +\xe0\x60\x3c\xa7\xd4\x3b\x9b\x59\x22\x29\x00\x00\x3c\xed\x2f\x00\ +\xe8\xb8\x0f\x38\xc4\xc9\x74\x3a\xfd\xc5\x56\x8e\xc8\x0a\x00\x00\ +\x4f\xfb\x1c\xa6\xc7\x1c\x0c\x29\xa5\x56\xc3\x66\xbd\x26\xd2\x73\ +\x78\x79\xe9\x6b\x7f\x98\xde\x0c\xf0\x9b\x99\xad\xbc\x9c\x48\x77\ +\x00\x00\x54\x2a\x95\xdd\xf5\x46\xb0\x14\x32\xaa\x66\x5c\xb5\xd3\ +\xb4\x7f\xe4\x37\xb1\x64\x32\xb9\xec\x10\xef\x0f\x19\x8d\x68\x5d\ +\x7e\x64\xda\x3f\xf2\x02\x00\x20\x9d\x4e\x7f\x64\xe2\x93\xed\x3a\ +\x83\xcf\x9a\xf6\xde\x16\x05\x00\x00\x9a\xb1\xf9\x28\x6c\xb7\x45\ +\x01\x8b\x8b\x8b\x7b\xc9\x09\x66\x42\x46\x6f\x4d\x7b\x47\x5e\x40\ +\xa5\x52\x19\x8a\xc5\xe2\x4f\x01\x64\x5b\x06\x44\x37\x33\xae\x9a\ +\x30\xed\x1f\x69\x01\xcc\x1c\x6b\x34\x82\x69\x06\x0e\xb4\x8d\xee\ +\xba\x2a\x79\xc3\x46\x86\x48\x0b\xf0\x4a\xe5\x3b\x0c\x9c\x68\x11\ +\x19\xcf\xdd\x74\xea\x32\x11\x85\x5e\x92\x7a\x4d\x64\x05\x68\xed\ +\x4f\x11\x30\xd5\x22\x12\xde\xd7\x6a\x89\x33\x44\xd4\xb0\x95\x23\ +\x92\x8b\x90\xe7\xf9\xa7\x40\x78\xdc\xe6\x5f\x8e\x39\x38\xa8\x94\ +\xaa\xd8\xcc\x62\xbd\x80\xa2\xef\x8f\x53\x80\x59\x00\x83\xeb\xe4\ +\x9f\x81\x83\x43\x39\xa5\x3e\xd8\xce\x63\xf5\x13\xd0\x5a\xe7\xa8\ +\x89\x67\x68\x5d\x7c\x83\x10\x9c\x8e\x62\xf1\x80\xc5\x02\x7c\xdf\ +\xdf\xc5\x70\x66\x40\xd8\xd3\x32\x60\xbe\xe4\xba\xee\x0b\x5b\x39\ +\xda\x09\xfd\x63\xdb\x6b\x0a\x85\xc2\x40\x23\xc0\x13\x02\xf6\xb5\ +\x0c\x88\x6e\x65\x5c\x75\xcf\x46\x86\x8d\x30\xbe\x03\x98\xd9\x89\ +\xc7\x13\xf7\x09\x38\xdc\x36\x7a\xe8\xaa\xe4\x75\xd3\xfe\xdd\x30\ +\x5e\x80\xd6\xfe\x35\x10\xce\xb5\x88\x84\xd7\xf5\xb5\xda\x45\x5b\ +\x67\xfd\xff\x30\x7a\x0a\x14\x0a\x85\x81\x78\x7f\xe2\x07\x80\xc4\ +\x3f\x95\x3f\x11\x78\xc2\x75\xdd\xef\x26\xbd\x37\x8b\xd1\x1d\x50\ +\xad\x56\x03\x00\xf5\x75\xd2\x37\x0e\x9a\xc7\xb7\xcb\xe2\x01\xc3\ +\x05\x8c\x8d\x8d\xd5\xc1\x98\x04\xb0\x0c\x60\x9e\x03\x3a\x96\xcd\ +\x66\x3d\x93\x9e\x82\x20\x08\x82\x20\x08\x82\x20\x08\x82\x20\x08\ +\xdd\xf8\x03\x6a\x65\xdc\x45\x31\x50\xc4\x7d\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x9a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4c\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xc1\x09\x00\x20\x0c\x04\xc1\x20\x16\x66\xe1\x82\xad\x48\x52\ +\x48\xec\x40\x3d\xf1\xb9\xfb\x3c\x08\xcc\x37\x66\x24\x36\x3d\xc6\ +\xf4\x18\xb7\xfb\xa9\x2a\x0b\xd2\x9a\xb4\x1f\x2a\x2f\x47\x3f\x03\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfd\x33\xb2\ +\xec\xda\x4e\xfb\x16\xbe\x7b\x13\xbf\x30\xe2\x93\xe7\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x06\xf1\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\xa3\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xcd\x73\x5b\x67\x15\x87\x9f\xf3\xca\xed\x24\x84\x3a\x4d\xbf\ +\x99\xae\xd8\x36\x6d\xda\xea\xc3\x21\x94\x81\xc6\x49\x6d\x27\x8d\ +\xe3\xfe\x01\x85\x45\x07\xf9\x63\x6a\x4b\x86\x55\x59\xc0\x82\xc9\ +\x02\x86\x81\xda\x96\xa7\xb6\x6c\x66\xd8\xf5\x1f\xa0\x09\x89\xbf\ +\x42\x81\x36\xb1\x25\xab\x1f\x40\x37\x9d\x4e\x17\x1d\x86\x19\x4a\ +\x0b\x71\x9a\x26\x4a\xf0\x7b\x58\xc8\x37\x88\x2b\xd9\x7a\xaf\x74\ +\x6f\x6d\x06\x3f\xcb\xf7\x9e\x7b\xde\xf3\xfb\xe9\x9c\x57\xd2\x95\ +\x60\x97\x5d\x76\xf9\x7f\x46\xea\x2d\x1e\xfa\xf6\xcf\xf6\xdd\xb1\ +\x77\xcf\xf7\xc5\x68\x2f\xca\x1e\x90\x4b\x66\x9d\x9f\xac\xfc\x72\ +\xe4\xc3\x2f\xba\xc0\x66\xe8\xf8\x6e\xee\xab\x36\xc6\x4b\xa0\x47\ +\x10\x6e\x60\xe5\xec\xe7\x6d\xe6\xe7\xef\xbd\xf2\xe2\x67\xfe\xd8\ +\x1a\x03\x9e\x7a\xe1\xa7\x77\x95\xef\xd8\xfb\x3a\xf0\xa4\xef\xd2\ +\x15\x55\xdb\xbd\x3a\x33\xba\x1c\x55\xe1\x61\x90\x4a\x8f\xa5\xd4\ +\x98\x79\x60\x7f\xf5\xba\xc2\x3b\x6d\x77\xf2\xcd\xe5\x5c\x66\xad\ +\x7a\xdd\xf8\x13\x94\xef\xdc\xfb\x12\xb5\xe2\x01\xf6\x8b\x98\xb9\ +\x44\xff\xd8\xe1\x50\x2b\x0e\x91\xcd\xc4\x03\x08\x3c\x6e\x6f\xe9\ +\x0f\xfc\xeb\x35\x06\xa0\x9c\xde\x62\x8f\xf6\x9d\x6a\xc2\x56\xe2\ +\x3d\xd4\x9a\x3e\xff\x5a\xad\x01\xb0\xb7\xc1\x5e\xed\x22\x66\x2e\ +\x39\x38\xd1\x11\xb0\xc6\xc8\xe8\x18\xc8\x25\x1b\x89\x07\x40\x74\ +\x8f\x7f\xa9\x9e\x01\x6f\x38\xec\xd9\x8e\x32\xbf\x13\x4c\xe8\x18\ +\xc8\x25\x2d\xba\x40\x23\xf1\x00\x68\x8d\xb6\x1a\x03\x62\xe8\x19\ +\xe0\x8a\xc3\xde\xdb\x6e\x42\x30\xf1\xac\xc5\xe0\xc7\xfe\xc5\x1a\ +\x03\x96\xf3\xd9\xf7\x11\xba\x70\x37\x61\x5b\xc6\x61\x43\x7c\xe3\ +\xb6\xaf\xb0\x66\x0d\xdd\xcb\xf9\xec\xfb\xfe\x0b\xf5\x46\x80\xe2\ +\x74\x66\x65\xc3\x84\xb5\x7a\xd7\x7d\xec\x47\x99\x4b\xa5\xc7\x52\ +\x0e\xb1\xa1\x10\x1f\x1a\x4f\x6c\x88\xbf\xdb\x21\xfc\xaa\x35\x74\ +\x97\xa6\x32\x97\xeb\x5d\xac\xfb\x41\xc8\x23\x39\x38\xd1\x81\x32\ +\x0f\xb4\x3b\x6c\x74\x45\xac\x7d\xa6\x30\x3b\x5a\x70\x88\x6d\x9a\ +\xf8\xd0\x78\xc2\x58\x59\xc0\x5d\x7c\xd7\x66\xe2\xa1\x81\x01\xb0\ +\xb3\x4c\x08\x5b\x3c\x38\x18\x00\x90\xe8\x1f\x3b\x2c\x62\xe6\x70\ +\x34\xc1\x20\xc7\x57\xf2\x23\x45\x97\xdc\xae\x24\xfa\x27\xe3\x22\ +\x76\x01\x38\xe0\x10\x7e\xd5\x60\xba\x57\xf2\xc3\x97\x1a\x05\x3a\ +\x19\x50\x29\x60\xfb\x4c\x88\x4a\x3c\x6c\x72\x08\xd6\x63\x75\x66\ +\x74\xd9\x1a\xba\x71\x3c\x18\x2d\xba\xd0\x31\x90\x4b\xba\xe6\xdf\ +\x8c\xa0\xe2\xc5\x6a\x8f\xab\x78\x08\xd0\x01\x1e\xf1\xa1\x89\xaf\ +\x19\xcb\x1c\x70\x97\x43\xf8\x3f\x0d\xf2\x4c\xb3\x9d\x10\x50\xfc\ +\x67\x62\xb5\xbb\x30\x9b\x7d\x33\xc8\x1e\xce\x1d\xe0\x51\x9a\xca\ +\x5c\xb6\x86\x2e\xe0\xaa\x43\xf8\xdd\x16\x9d\x8f\x0f\x8d\x27\x82\ +\xee\xf3\x45\x88\x87\x26\x3a\xc0\x23\x68\x27\x58\xa3\xc7\x4b\x53\ +\xd9\x55\x97\xdc\xc9\xc1\x89\x27\x51\x16\x89\x58\x3c\x34\xd1\x01\ +\x1e\xa5\xa9\xcc\x65\x83\xe9\xc6\xb1\x13\x8c\x95\x05\x97\x4e\x08\ +\x2a\x1e\x91\x9e\x66\xc5\x43\x0b\x1d\xe0\xd1\x31\x30\x79\xc4\x62\ +\x2f\x10\x42\x27\x34\x23\xbe\x38\x3d\xe2\xf2\xe5\x6d\x53\x9a\xee\ +\x00\x8f\x95\xfc\xf0\x25\xb1\xda\x83\x7b\x27\xcc\x27\xfa\x27\xe3\ +\xfe\x0b\x1b\xe2\x9d\x67\x5e\xd5\x9e\x68\x55\x3c\x84\x60\x00\x40\ +\x61\x36\xfb\xe6\x86\x09\x35\xcf\xdc\xea\x70\x40\xc4\x2e\x54\x9b\ +\x90\x4a\xbf\xfc\xc4\x86\xf8\x7b\x1c\xee\xbf\xa6\x6a\x4f\xac\xce\ +\x8c\xfe\xa1\xd9\x7a\xab\x69\x79\x04\xaa\x49\xa5\xc7\xbf\xae\x46\ +\x2e\x00\x5f\x76\x08\xff\x87\xaa\x39\x6e\xf4\x96\x55\x13\x5b\xc4\ +\x5d\x7c\x4f\x58\xe2\x21\x64\x03\x20\x98\x09\x82\xae\x69\xa5\x04\ +\x97\x4f\x97\xa1\x8b\xaf\xd4\x10\x01\xc9\xc1\xdc\x53\xa8\x9e\xc7\ +\xad\x13\x5c\xb8\x66\x0d\x27\x4a\x53\x99\xdf\x87\x94\xef\x36\x91\ +\x18\x00\xa1\x9a\x10\x99\x78\x08\xe9\x10\xac\x47\x71\x7a\xe4\x0d\ +\x55\x7b\x02\xb7\x83\x71\x33\xae\x09\xf6\x64\x54\xe2\x21\xc2\x0e\ +\xf0\x48\xf4\x8f\x7d\x43\xc4\x9c\x07\xf6\x05\xbc\xf5\x9a\x60\x4f\ +\x16\xf2\xa3\xbf\x8b\xa2\x2e\x8f\xc8\x0d\x80\x8a\x09\xc6\x98\x39\ +\xd5\x86\x8f\xdc\x3d\x6e\x08\xb6\x3b\x6a\xf1\x10\xe1\x08\x54\xa3\ +\x31\xd6\x54\xe5\xa6\xf3\x0d\xc2\x4d\xac\xba\x7c\xed\x6e\x99\xc8\ +\x0d\x88\x0f\x8d\x1d\x32\xd6\x2c\x81\xba\x3c\xbd\xad\xa0\xb4\xab\ +\x89\x2d\xa6\xd2\x2f\x3f\x11\x61\x69\x40\xc4\x23\xf0\x1f\xf1\xdc\ +\xdb\x64\x8a\x4f\xc5\xae\x1f\x2b\xcc\x7e\xef\xed\x30\xeb\xaa\x26\ +\x32\x03\x36\xc4\x2f\x02\xf7\xb5\x98\xea\x53\x03\x9d\x2b\xf9\xcc\ +\x3b\x61\xd4\xe5\x27\x12\x03\x12\xfd\xb9\xc7\x44\x74\x89\xd6\xc5\ +\x7b\x44\x66\x42\xe8\x67\x40\x10\xf1\x0a\x65\x85\xb2\x43\xda\x7b\ +\x2c\x2c\x76\x0c\x4c\x3c\xde\x7a\x85\xff\x4d\xa8\x06\x04\x7c\xe5\ +\xaf\x8b\x48\x8f\xc1\x76\x01\x9f\x3b\xc4\xdf\x1b\x85\x09\xa1\x8d\ +\x40\x72\x70\xfc\x51\x54\x2e\xe2\x28\x5e\x55\x9f\x5d\x9d\xc9\x5e\ +\x04\x48\xa5\x27\xbe\xa5\x86\x73\xc0\x97\x1c\xee\xfd\xc4\x1a\xdb\ +\x59\x9a\x1a\x7d\xb7\x95\x7a\x3d\x42\x31\xa0\x15\xf1\x1e\xdb\x65\ +\x42\xcb\x23\x10\x54\xbc\x15\x39\xe5\x17\x0f\x50\x98\xcd\xbc\x8e\ +\xc8\xb3\x38\x8e\x83\xb1\x66\x29\x3e\x34\x76\x28\x68\xbd\x7e\x5a\ +\x32\x20\x39\x38\xfe\x28\x88\xf3\xcc\x5b\x91\x53\xa5\xe9\x91\xa5\ +\xcd\x02\x8a\xd3\x23\xbf\x0d\x68\xc2\x62\xab\x26\x34\x3d\x02\xb7\ +\xc5\x2b\xf7\x3b\x84\x5f\x17\xb4\xb7\x90\xcf\x2e\xba\xe5\xce\x3d\ +\x8d\xea\x39\x1a\xff\x5d\x07\xe0\xef\xaa\xd2\xb9\x3a\x33\xf2\x47\ +\x97\xdc\x7e\x9a\xea\x80\x54\x7a\xf2\x60\x00\xf1\x37\x82\x88\x87\ +\xdb\x9d\x70\x12\xb8\xee\x10\x7e\x9f\x88\x2e\x25\xfa\x73\x8f\xb9\ +\xe6\xaf\x26\x70\x07\xa4\xd2\x93\x07\x35\x66\x2f\x06\x10\x7f\x2a\ +\x88\xf8\x6a\x12\xfd\xe3\x47\x45\xe4\x2c\x11\x76\x42\x20\x03\x52\ +\xe9\xc9\x83\x18\xbb\xa4\xf0\x80\x43\x78\x4b\xe2\x3d\x82\x9a\x80\ +\xe8\xd1\xe2\x74\xf6\x4f\xae\xf9\x9d\x0d\x08\x2a\x1e\x4b\x6f\x71\ +\x36\xb3\xe0\x9a\x7f\x2b\xe2\x83\xb9\x4e\xa3\xfa\x1a\x11\x98\xe0\ +\x64\xc0\xe1\x81\x89\x47\x2c\x5c\xdc\x0e\xf1\x1e\x51\x99\xd0\xf0\ +\x10\x0c\x2c\x1e\x73\x3a\x6c\xf1\x00\xa5\xe9\x91\x25\x41\x7b\x71\ +\x3c\x18\x41\x96\x2a\xef\x54\x5b\xb3\x65\x07\x34\x25\x3e\x3f\x3c\ +\xef\x10\xdb\x34\xa9\x81\xf1\x63\x8a\xbc\x06\xd4\xfc\xeb\xb3\x06\ +\xe1\x63\xd0\xce\xad\x3a\x61\xd3\x0e\x38\x3c\x30\xf1\xc8\x3a\x38\ +\xcf\xbc\x2a\x7d\x51\x8b\x07\x28\xe4\xb3\x8b\x82\x9e\x02\x6e\x34\ +\x0c\x56\xee\x07\x59\xaa\xbc\x6d\xd7\xa7\x6e\x07\x78\xe2\x81\x07\ +\x1d\x6a\x2a\xab\x72\x7a\x75\x26\x33\xe7\x10\x1b\x1a\x41\x3b\x41\ +\xd6\xcd\xd1\xc2\xec\xf0\x9f\x6b\x2f\xf9\x38\x32\xf8\x8b\x87\x6f\ +\x69\x5b\x11\x78\xc8\xa1\x8e\x6d\x11\xef\x91\x4c\x4f\x1c\xc7\xf0\ +\x6b\x1c\x4c\x10\xf8\x1b\xb1\x58\xb2\xf0\xca\x8b\x1f\x55\xaf\xd7\ +\x8c\xc0\x2d\xdb\xf6\x43\xfe\x07\xc4\x03\x14\x67\x33\x0b\x58\x7a\ +\x71\x18\x07\x85\x07\xb0\xeb\x3f\xf2\xaf\xd7\x9e\x01\xc2\xd3\x0e\ +\x7b\x97\xad\x48\xdf\x76\x8a\xf7\xa8\xbc\xe3\x98\xd3\xb8\x98\xa0\ +\x1c\xf5\xaf\xd5\x18\xa0\xb0\xde\x20\x4f\xd9\x8a\xf4\x95\xa6\x47\ +\x2e\xb8\x97\x19\x2d\x95\xc3\xd7\xc9\x84\x1a\x6d\x35\x06\x08\x6c\ +\xf5\xaa\x96\x05\x7d\x6e\x27\x89\xf7\x28\xe6\x87\xe7\x55\xe9\x63\ +\x0b\x13\x44\x38\xef\x5f\xab\x31\xc0\xb4\x99\x33\xc0\x07\x75\xee\ +\x2f\x0b\xfa\x5c\x21\x9f\xad\x49\xb2\x53\x58\x9d\xc9\xcc\x6d\x61\ +\xc2\x87\xff\x2a\x73\xc6\xbf\x18\xf3\x2f\xfc\xa5\x70\xee\xfa\x57\ +\x12\xc7\x5e\x15\x89\xed\x43\x79\x50\x84\x9b\x28\x8b\x8a\xf9\x4e\ +\x71\x26\xba\x5f\x69\xc3\xe2\xaf\xab\xbf\xf9\xe0\xe1\x78\xd7\x59\ +\xc4\x3c\x04\x1c\x40\xf9\x44\x45\x5f\xb5\x37\xe5\xf9\xb7\x7e\x95\ +\xf9\x78\xbb\xeb\xdb\x65\x97\x5d\x76\x16\xff\x06\x5e\xec\x1f\xa0\ +\xf6\x5e\x26\xad\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x02\x06\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xb8\x49\x44\x41\x54\x58\x85\xed\ +\x97\xcf\x4a\x1b\x51\x14\x87\xbf\x33\x49\x56\x25\x42\x2b\xa9\xe0\ +\x6b\x34\xff\x8a\xc5\x07\x68\x4a\x5f\xa2\xc1\x94\x6a\x46\x29\x25\ +\xf6\x11\x1a\xa1\x25\x99\xd8\xa2\x45\x17\x92\x95\x0f\x10\x70\xd3\ +\x2e\x04\xab\x69\x93\xd7\x10\x34\x28\x94\x2c\x63\x72\x5c\xcc\x64\ +\x0c\xc6\x8e\x98\x4c\x62\x69\xf3\x5b\xde\x7b\xb8\xdf\x37\xf7\x5c\ +\x86\x7b\xe1\x7f\x8f\x5c\x1f\x88\xbe\x2e\xcd\xa1\xba\x8a\x90\x44\ +\x89\xf8\x44\x69\xa0\x1c\x21\x92\xaf\x6d\x64\x0f\xfe\x28\x10\xcb\ +\x14\xdf\x29\xb2\x76\x93\x98\x4f\xe9\xa8\x92\xab\x7f\x35\x3f\xf6\ +\x09\x3c\x59\x28\x3c\x13\x31\xf6\x81\xdf\x88\x9a\xa1\x56\xbb\x72\ +\xb8\xfd\xf6\xdc\x0f\xea\xd3\x57\x9f\x1e\xb5\x42\x81\x14\x2a\x16\ +\x30\x85\xc8\x7c\x77\x27\x82\xae\x89\x18\x39\x40\x10\x35\x6b\x1b\ +\xcb\x65\x3f\xc0\xdd\x38\x1f\x52\x8e\x66\x2c\x01\x76\x50\x5d\x05\ +\x5e\x02\x18\x6e\x95\x90\x04\x08\xb5\xda\x15\x3f\xe1\xbd\x31\x82\ +\x46\xc5\x46\x91\x70\xc7\xdc\x59\xe7\xc0\xf9\xb5\xed\x37\xe5\xe7\ +\xe7\xa5\x33\x1b\xc5\xe3\x7e\x81\x7b\xca\x44\x60\x22\x70\xef\x02\ +\xc1\xdb\x0a\x62\x99\xd2\x1b\x45\x3f\x00\xe1\x3b\xae\xdd\x14\xe4\ +\xfd\xaf\xcd\xec\x17\xaf\x22\xcf\x1d\x48\xa4\x0b\x33\x8a\x96\x06\ +\x80\x03\x84\x15\xb5\x12\xe9\xc2\xcc\xc0\x02\xe3\x88\xa7\x40\x75\ +\x6b\xe5\x44\x90\x2c\xd0\x1c\x60\xed\xa6\x20\x66\x75\x6b\xe5\xc4\ +\xab\xe8\xd6\x33\xe0\xf4\xd0\xb3\x8f\xc3\xe4\xef\x6e\xc1\x44\x60\ +\x22\x30\x5e\x01\xa1\x01\xf6\x05\x72\x54\xb0\xf8\xe2\xfa\xb4\x8d\ +\xe2\xb4\x5f\x40\x39\x02\x68\x85\x02\xa9\x51\x09\x74\x2e\x3a\x29\ +\x1b\x45\xb5\x3b\x76\xf5\x23\x12\xc9\xa3\xfa\x02\x15\x2b\x9a\xb1\ +\xc4\x08\x1a\x95\xee\x1d\x6e\xd8\xc4\x17\xd7\xa7\x1d\x78\x11\xe8\ +\x20\x92\x77\xb1\xbd\x85\xce\xc3\x24\xcf\xe8\xce\x46\xdf\xc3\x24\ +\xd0\x3b\x7b\x5c\xdf\xfb\x31\x1b\x7b\xfe\x0d\x88\x08\x3c\x04\x1e\ +\xf8\x41\x75\x7a\xfe\x1d\x91\x74\x7d\xd3\xdc\xf5\x63\xcd\x7f\x27\ +\x97\x00\x43\x86\x87\x3f\x9c\xa0\xff\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x37\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xe9\x49\x44\x41\x54\x58\x85\xed\ +\x94\x31\x68\x13\x61\x14\xc7\x7f\xef\x8e\x50\x8d\x20\x75\x50\x8a\ +\x93\x29\xe2\x24\xa2\xa5\x71\x11\xdc\x44\x91\x8e\x8a\x53\x41\x87\ +\xda\xa0\x49\x8a\x83\x93\x08\xea\xea\x60\x4d\x5b\x6b\xeb\xe0\xa0\ +\xa0\x58\xc4\x41\x07\xa5\x53\x71\x50\xa8\x8d\x5a\xc4\xc9\xc1\x45\ +\xa1\x88\x56\x45\x4b\xb5\xb9\xfb\x3b\x24\x67\xcf\x60\x9b\xbb\x58\ +\xec\x72\x3f\x38\xf8\x8e\x7b\xef\xff\xfe\xef\xde\xf7\x7d\x90\x90\ +\x90\x90\xb0\xca\x58\xb0\xe8\x3c\x5e\x9a\xc5\x68\xfd\x2f\x55\xc5\ +\xe7\x67\xa3\xc5\x0d\x00\x4e\xc8\x8a\xb3\x64\xc2\x4a\x13\xaa\xf5\ +\x7b\x91\xaa\x54\x32\x06\x4f\x83\x77\x21\x1f\xf0\x56\xe2\x11\xf8\ +\xa1\xf2\x4f\x52\x95\x4a\x66\xd1\x4b\x88\x1d\xdd\x17\xd7\xb5\xa4\ +\x5b\xee\x0a\xf6\x23\xc0\xe4\x83\xe9\x5f\x9a\x15\x32\xc3\x82\x46\ +\x1f\xfe\x9c\xfb\x71\x68\xfa\xc6\xe9\xef\xc1\x77\x37\x1c\x3c\x33\ +\x3d\xbe\xd0\xda\xbe\xfb\x4e\x6a\x6d\x7a\x1b\xc6\xf6\xaa\xc1\x3f\ +\x3c\xc6\x2b\x6e\x2c\x16\x97\xdd\x9e\x9b\xfd\x78\xe4\xd5\xad\x33\ +\xf3\xe1\x18\xb7\x3e\xe9\xc3\xeb\x09\x6f\x4f\xfb\xb1\x7b\x5f\xd2\ +\xdf\x36\x82\x65\x01\x93\x09\x8b\x69\x44\x60\x56\x1b\xb1\x19\xc3\ +\x99\x4f\x6d\x3d\x13\x63\xf9\x4a\x7d\xdc\x32\xaa\xb2\x6c\xae\x74\ +\x5e\xb2\xb3\xb5\x48\x1f\x11\x6d\x1c\x86\xa1\x6a\x71\xc1\x85\xa9\ +\x91\xc2\xb9\xa5\x46\xd9\xb0\xad\x6c\xef\x40\x9f\x50\x3f\x80\xaa\ +\x03\xf5\x1b\xa4\x38\x81\xae\x44\xdf\xd4\x68\xb1\xb4\xbc\xd7\x08\ +\x74\xe6\x2e\x77\x23\xbb\x0e\xb8\x02\x19\x7f\x37\x21\xe1\x58\x75\ +\x56\x9e\x61\x47\x27\x47\x0a\x37\x1b\x69\x47\x1e\x6c\x47\x6e\xb0\ +\xcb\x91\x3f\x06\xac\x01\x44\xbd\x09\x99\x83\xc9\x80\x79\xdf\x9c\ +\xc3\xe5\xab\xf9\x07\x51\x74\x63\xed\xac\x6c\x6f\xff\x5e\xe1\xdc\ +\x07\xd6\xd7\x99\x08\x7e\xfb\x57\xdf\xa1\xab\x3c\x5c\x7c\x1c\x55\ +\x33\xf6\x19\xcb\xf6\x5c\xda\x89\xe3\x3e\x12\x6c\x02\x54\xdb\xed\ +\x00\x33\xe6\x7b\x07\x26\xaf\x9d\x7a\x11\x47\xaf\xa9\x43\xde\x71\ +\x62\x68\xab\x79\xde\xb8\xc1\x16\x00\xc1\x5b\xb9\xee\xbe\xf2\x95\ +\x93\x6f\xe2\x6a\x35\x7d\xcb\xec\xca\x0f\x6c\x76\x17\xf4\x4e\xf0\ +\xd2\x4f\xd9\xc1\xe7\x83\x85\xf7\xcd\x6a\x25\x24\x24\x24\xac\x2a\ +\xbf\x00\xaf\x38\xac\x82\xe2\x51\x10\x13\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x04\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\xd1\x0d\x83\x50\x0c\xc5\xd0\x14\x75\x8d\x0a\xf6\x9f\x0a\xc4\ +\x20\x74\x8c\x83\xf4\xec\x05\x62\x59\xf7\x2f\x33\x90\xf3\xba\x9f\ +\xf3\xba\x1f\xe9\xb0\xc9\xe3\x6f\xa0\x00\x5a\x40\x53\x00\x2d\xa0\ +\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ +\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\ +\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\xe5\ +\x03\x7c\xe4\x71\xfd\x1a\x9f\x69\x01\xf3\xd5\x02\x33\x33\xc7\xfe\ +\x63\x4b\x5c\x7e\x01\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\ +\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\ +\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\ +\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x2c\x1f\xe0\x0f\xc7\ +\xa8\x0b\xc6\x03\x24\x5a\xc7\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x4c\x76\xb2\x8f\x85\xfd\x14\ +\x72\x20\x33\x09\x96\xad\x02\x00\x00\x00\x00\x00\x00\xe0\x7f\x63\ +\xed\x73\xd3\x11\x49\x33\x1d\x90\x66\x40\x3a\x00\x00\x00\x00\x00\ +\x00\x00\x00\xde\x6b\x42\xab\x02\x34\xd3\x03\x1d\x60\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x1a\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x4f\x6c\x14\x65\x18\xc7\xf1\xef\x33\xdb\xad\x44\xc4\x34\x01\ +\xa3\x04\x82\x4a\x0f\xc4\x02\x51\xeb\x09\x88\x64\x85\xdd\x25\xa4\ +\xa9\xc8\x6e\x97\x10\x62\xb1\xa6\xdb\x46\x4c\x3c\x18\x13\x6f\xa6\ +\xf1\x46\x82\x91\x70\x69\x42\xff\x24\x04\x4d\x54\xa6\x7f\x38\x28\ +\xe8\x96\x26\x94\xa4\x88\x46\xca\xad\x1e\x80\x9a\x08\x21\x46\x10\ +\xc1\x90\xd0\x52\xf6\x7d\xbc\x70\xd8\x0e\x45\xb0\x33\xbb\x84\xf0\ +\x7c\x8e\xf3\xcc\xfc\xf6\xf7\xbe\xb3\xb3\xb3\x60\x8c\x31\xc6\x18\ +\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x98\xc7\x85\x84\x0d\xd8\x98\ +\x7b\xb7\xce\x2b\xc6\x0e\x8a\xb0\x04\xf8\xbc\xd0\xdf\xf3\x19\xa0\ +\xe1\xab\xcd\x2e\x95\x69\xdb\x2a\xa2\x7b\x00\x10\xf9\xa0\xd0\xd7\ +\x7d\x34\x4c\x5e\xe8\x0d\x48\x65\xf3\x23\xc0\xfa\x92\xc8\x2f\x6a\ +\xbc\x6b\x79\xdf\xf7\x6f\x85\xcd\x0e\x90\x54\x53\xdb\xc7\xa8\xee\ +\x2e\x39\x76\xfd\xea\x42\xef\x99\xd3\x5d\x5d\xd3\x73\x0d\xf5\x42\ +\xd7\x52\x0d\x64\x68\xf3\xdf\xae\xe6\xfb\xc4\x5b\x2d\x35\xa1\xb3\ +\xef\x48\x24\x3a\xaa\x52\xd9\x7c\x67\x60\xf1\x80\x84\xbe\x81\xa1\ +\x37\x40\x94\x5d\xc0\x9f\x33\x8e\xa1\x6f\xc4\x63\xf1\xd1\x0d\x99\ +\xd6\xe7\xc3\xe6\x27\x72\xef\x3f\x15\x5f\x74\xe9\x30\xf0\x5e\x60\ +\x34\x25\xb8\xb7\xc3\xdc\x7d\x88\xe0\x11\x00\x48\xe7\xf2\x2f\x3a\ +\xc7\x51\x81\x15\x81\xf0\x3f\x44\xbd\x86\x1f\x06\xba\xc6\xe6\x92\ +\xbb\x29\xd3\xbe\xb8\x28\xee\x5b\x81\xfa\xc0\xe8\x2a\xaa\x6f\x0e\ +\x0d\xf4\x8e\xce\xb9\xf4\x1d\xe1\x1f\x01\xa0\xe0\xf7\xfc\x16\xf3\ +\x74\x2d\x70\xa2\xf4\xb8\xc2\x73\x4e\xdc\x89\x64\xa6\xb5\xe1\xff\ +\x66\x6e\xca\xb6\xad\x74\xe2\x4e\xcd\xb2\xf8\x09\xe7\x64\x4d\x14\ +\x8b\x07\x88\x45\x11\x02\x70\x7e\xfc\xcc\xcd\x15\x2f\xac\xfb\xca\ +\xc5\x6f\xd7\x02\xab\x4b\x46\xd5\x22\xb2\x7d\x79\x5d\xfd\xe5\x89\ +\x5f\xc7\x7e\x79\x90\xac\xf4\xd6\xfc\x06\x15\x0a\xc0\xb3\x33\x27\ +\xfa\x53\x95\xe7\x36\x16\xfa\x7b\x2f\x44\xd5\x3b\xb2\x0d\x00\x38\ +\x77\xee\xe7\x62\xf3\xb6\xc6\xc1\x0b\x97\x6f\x54\x03\xaf\x97\x8c\ +\x44\xa0\x61\x79\x5d\xfd\xfc\xe6\x6d\x8d\xc3\x23\x23\x23\xf7\x7c\ +\x4d\x26\x9b\xf2\x3b\x11\x0e\x01\x4f\xce\x18\x08\x83\x4f\x4c\xc5\ +\xb6\x1c\x39\xdc\x7b\x3d\xca\xce\x91\xfc\x06\xcc\x26\x9d\xc9\xb7\ +\xab\xd0\xc9\xdd\x9b\x7c\x68\x7a\xc1\xed\x77\x8e\x1f\x38\x30\x19\ +\xec\x92\xca\xb6\x7e\x02\xf2\xe9\xdd\x69\xba\xaf\xc6\xfb\xe7\x23\ +\xdf\xf7\x8b\x51\xf7\x2c\xdb\x06\x00\xa4\x9b\xda\x36\xab\xaa\x0f\ +\xcc\x0f\x8c\x46\x9d\xbb\xb5\x65\x78\xf0\xe0\x5f\x00\xb9\x5c\xae\ +\xfa\x9a\x7b\x7a\x3f\x48\x4b\xe0\x3c\x05\xf9\x70\xa8\xbf\x7b\x5f\ +\xb9\x3a\x96\x75\x03\x00\x92\xd9\xd6\x57\x05\xf9\x0e\x58\x3c\x73\ +\xa2\x67\x8b\xc5\xd8\x66\x2f\xce\x15\xcf\xb9\x3e\x85\x64\xe0\xd2\ +\x49\x54\x76\x0c\x0d\x74\x0f\x96\xb3\x5f\xd9\x37\x00\x20\x99\x6b\ +\x5f\x26\xce\x1d\x01\x56\x3e\xd0\x05\xca\x15\x85\xc6\x63\x03\x3d\ +\xa7\xca\xdb\x2c\xa2\xd7\xe0\xfd\x1c\xf3\xbb\x7e\x57\xcf\x5b\x07\ +\x0c\xdf\xff\x6c\x3d\xeb\xc5\x74\x4d\x25\x16\x0f\x11\xbf\x05\xfe\ +\xcb\xc4\xf8\xe9\xa9\xd7\x56\xd5\x7e\x3d\xa9\xf3\x96\x01\xaf\xdc\ +\xe3\xb4\x93\xd3\xd5\xb1\xd4\xf0\x37\x3d\x17\x2b\xd5\xab\x22\x8f\ +\x40\xf0\x33\xd3\x4d\xf9\x0e\x55\x3a\x02\x4d\xfa\x6e\xc8\x82\x9d\ +\x3f\xfa\x7b\x6f\x56\xb2\x4c\xc5\xbe\x01\xa5\xce\x8f\x8f\x1d\xaf\ +\x7d\xa9\x7e\x29\xc2\xcb\x80\x43\x75\xcf\xda\x55\x4b\x77\x7d\xd9\ +\xb9\x3b\xd4\xff\xfa\x47\x4e\x22\xd1\x51\x95\x68\x69\x99\xf7\xb0\ +\x7b\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\x31\x8f\ +\x89\x7f\x01\x76\x43\xf4\x3d\x50\xc3\x70\x12\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9a\x49\x44\x41\x54\x58\x85\xe5\ +\x96\xbb\x72\xd3\x40\x14\x86\xbf\xe3\xa4\x00\x9e\x23\x25\x54\xb1\ +\x52\xf0\x0a\x14\x90\x84\xc4\x21\x64\x72\x23\x44\x6a\x2c\x37\x99\ +\xe1\x19\x28\x65\x35\x92\x27\x09\xd8\x21\xce\xc5\xc0\x30\xc3\x33\ +\x50\x59\x7e\x05\xe8\xe0\x0d\x80\x02\xfb\x50\xc4\x4a\x64\x5d\x6c\ +\xcb\x71\xc3\x70\x2a\x69\xb5\xfb\x7f\x9f\x56\xab\xd9\x85\xff\xbd\ +\x24\xbc\x30\x5e\x3a\x0f\xb5\x20\x1e\xca\x5d\x11\x5e\xb5\x7d\xfb\ +\xe3\x34\x41\x86\x59\x5d\x52\xe5\x35\xc2\x6f\x44\xac\xc0\x2b\x7f\ +\x01\x28\x84\x1d\xb4\x20\x47\xc0\x03\x84\x39\x85\x96\x61\xba\xa5\ +\x69\xc1\x8b\x96\xb3\xa6\xd0\x42\x98\x03\xee\xa3\x7a\x18\x3e\xbb\ +\x11\x80\x3b\x91\x31\x05\x45\x9b\xd3\x90\x28\x5a\xce\x1a\x2a\xa7\ +\x51\x16\x70\x2f\x21\x20\x22\x07\x40\x6f\x9a\x12\x86\xe9\x96\x52\ +\xe0\x3d\x55\x39\x48\x08\x04\x5e\xf9\x03\xb0\x91\x22\x71\x3a\x89\ +\x84\x61\xba\x25\x45\x9b\x71\xb8\x20\x5b\x9d\x5a\xb9\x95\x10\x00\ +\x08\x7c\xfb\x2c\x45\x62\x26\xaf\x44\x1f\x9e\x78\x73\x41\xb6\xda\ +\x7e\xf9\x5d\xb4\xaf\x90\x52\xf3\xfb\xee\xba\x88\x9e\xc4\x02\xba\ +\x22\xba\xde\xf6\x2a\x97\x43\xe1\x96\xb3\xaa\x2a\x4d\x60\x66\x14\ +\x3c\x53\x60\x52\x89\x0c\xb8\x0a\xb2\x99\x06\x27\x16\x3e\x50\x9d\ +\x5a\xb9\x29\xc2\x26\xf1\xcf\xa1\xd2\x34\x2c\x67\x35\x45\x78\x25\ +\x2f\x1c\x86\xcc\x40\x58\x86\x55\x7d\xae\x4a\x23\x26\xdb\x55\x95\ +\x67\xe1\x62\x9a\xdf\x77\x57\x44\xf4\x2c\x2f\x7c\x2c\x01\x00\xc3\ +\x74\x37\x14\xad\xa7\x49\x00\xa4\xc1\x11\xdd\x0a\xbc\xca\xc9\xa8\ +\xec\xb1\x04\xb2\x24\xb4\xff\x79\x64\x50\x6c\x6c\x78\x2e\x81\x88\ +\x44\x63\xc8\xb8\x5c\xf0\xdc\x02\x37\x12\x34\x40\xe3\x63\x15\xd8\ +\x0e\x7c\xbb\x91\x27\x2f\xf3\x2f\xc8\x2a\x15\x7e\x29\xaa\x89\xf6\ +\x2b\x81\x9f\x79\xf3\x72\x09\x14\x2d\x77\x19\xd5\x73\x49\x19\xd7\ +\x6f\x3b\x2f\x9a\xd5\xa7\x79\x32\x73\x2c\xc2\xea\x92\xc2\x05\x30\ +\x1b\x69\x0e\x67\x22\x9a\xd3\x45\xa4\xd4\xdf\x5b\x46\xd6\x58\x33\ +\x90\x05\x57\xd5\x1d\x60\x3b\x22\x02\x30\x83\xea\x45\xd1\x72\x97\ +\xa7\x22\xb0\x60\x39\x8b\x59\xf0\x4e\xad\x52\x0f\x7c\xbb\xd1\x17\ +\x99\x48\x62\xa8\xc0\x82\xe5\x2c\xf6\x54\x2e\xe3\x70\x11\x76\x3b\ +\xb5\x4a\x3d\x6c\xe8\xd4\x2a\xf5\x0c\x89\xf3\x51\x12\x99\x02\xc3\ +\xe0\x6d\xcf\x7e\x1b\xef\xdf\xa9\x55\xea\x22\xec\xc6\x24\x66\x47\ +\x49\x64\x6d\xc7\x4f\x44\xb4\x35\x2e\x3c\x5a\x86\x55\xdd\x56\xe5\ +\x38\x96\xfd\x47\xa0\x94\x76\xd0\x4d\x08\x64\xc2\x91\x17\x6d\xbf\ +\xfc\x66\x18\xfc\x5a\xc2\x74\x77\x14\x3d\x1a\x47\x62\x40\xa0\x68\ +\x3a\x8f\x41\xde\xdf\x06\x9e\x57\xe2\xfa\xe1\xfc\x7e\xf5\x91\x08\ +\x9f\xa6\x01\x0f\xab\x68\x55\x77\x51\x0e\x53\x24\x96\xda\xbe\xfd\ +\x19\x06\x4e\xc5\x38\x71\x38\xc2\xde\xa4\x70\x80\xc0\xb3\x8f\x11\ +\xf6\x88\x2d\x4c\x05\x27\xbc\x49\x6c\xad\x51\x78\xe0\xd9\xc7\x93\ +\xc2\x87\x4a\x28\xdd\x84\x00\xaa\x26\xc8\x57\xe0\xc7\xd5\x96\x7a\ +\x7b\x78\x54\x42\x90\x4d\x94\xef\xc0\xb7\x5e\x41\xcc\x69\x65\xff\ +\xfb\xf5\x17\x4b\x00\x72\xf1\x7d\xf9\x90\x28\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x3b\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xbd\x6b\x14\x41\x18\xc6\x9f\xd9\x0d\x84\xa0\xd8\x88\x04\x63\ +\x0a\x43\x62\xa1\x08\x42\x72\xd1\x94\xe2\x27\x06\xb1\x0b\x8a\x8d\ +\x78\x60\x36\x97\xd3\x53\x0b\x09\xfe\x05\xc6\x2a\xb8\x97\x4b\x72\ +\x29\xd2\x08\x36\xd1\x42\x84\x9c\xa0\x16\x01\x8b\x48\x2e\x29\x24\ +\x88\x85\x82\xc5\x29\x04\xb5\x88\xe4\x83\x33\x99\x7d\x2d\x22\x16\ +\xb7\x7b\x7b\xb7\x1f\x73\x93\x73\xe7\x57\xce\x0d\xcf\xfb\xec\x73\ +\xf3\xc5\xee\x00\x0a\x85\x22\xca\xb0\xa0\x02\x47\x06\x33\xbb\x9b\ +\x38\x4f\x32\x42\x1f\x18\x8e\x02\x68\x0c\xc1\x57\x10\x8a\x20\x2c\ +\x11\xc3\xf4\x86\xae\x67\x3e\x8c\x25\x57\xdd\x3a\x07\x0a\x20\x66\ +\x8c\x9e\x05\xac\x29\x00\xad\x41\x74\x04\x52\x00\xb4\x78\x3e\x7b\ +\xf3\x55\xb9\x0e\x9a\x5f\xe5\xd8\x80\x19\x07\xac\x97\xd8\xb9\x0f\ +\x0f\x00\xad\x80\x95\xeb\x36\xd2\xd7\xcb\x75\xf0\x35\x02\xba\xfa\ +\xcd\x73\x8c\x21\x87\x00\x01\xd6\x18\x0e\x68\x17\x9c\x46\x82\xe7\ +\x00\xb6\xe7\xbc\xf5\x91\x81\x0e\x84\xe3\xad\x66\x14\xd6\x75\xfd\ +\x70\xe9\x9a\xe0\xf9\x1f\x6c\xe2\x3c\x59\x87\x0f\x0f\x00\xad\x4d\ +\x9c\x27\x4b\x1b\x3d\x07\xc0\x08\x7d\xe1\xf8\xa9\x3d\x4e\xde\xbd\ +\xcf\xe1\xed\xad\xae\x3e\x71\xf0\xde\xe0\x43\xc6\x75\x9f\xcf\x67\ +\x53\x81\xcf\x16\x41\x88\x19\x26\xb9\xfc\x6c\xf3\x5e\x2f\xab\xb8\ +\x30\x54\x00\xb2\x0d\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\ +\xc8\x26\xf2\x01\x54\x3c\x08\x75\xf5\x8f\xec\xd7\x34\x2d\x41\x60\ +\xa7\x41\x68\xae\xd4\x3f\x66\x98\x9f\x7c\xbb\x21\x10\x18\x0a\x20\ +\xcc\xe8\x8d\xc8\xbe\x4b\xa7\x7e\xf9\xd6\xaa\x12\xd7\x00\x62\x89\ +\xf4\x25\x58\x34\x45\x84\xbd\x1e\x34\xdb\x7d\xbb\xd9\x3e\x43\x76\ +\x80\xe1\x24\xff\x8d\x44\x67\xc2\xbc\xba\x38\x9e\x9a\xf3\xad\x57\ +\x05\x65\xa7\x40\xcc\x30\x87\x61\xd1\x73\xc0\xd3\xc3\x87\x49\x9b\ +\x66\xe1\x6d\x97\x91\x1e\x10\x59\xc4\x31\x80\x6e\x23\x7d\x19\xc0\ +\x90\xc8\xc2\x55\xa2\x33\xd0\x68\x67\xc2\xec\x11\x55\xc0\x16\x40\ +\xcf\xc0\xc8\x41\x02\x4d\x8a\x2a\xe8\x03\x5d\xb3\xf0\xe4\xc4\x2d\ +\x73\x8f\x08\x71\x5b\x00\x5b\xd4\x70\x1f\x80\x90\x62\x01\x68\xe3\ +\x45\x18\x22\x84\x1d\xa6\x00\xf5\x8a\x28\x14\x18\x06\x21\xbe\x9c\ +\xd6\x80\x9d\xf9\x96\x97\xc4\xf8\xf2\xfc\x42\xc4\xd2\xf5\x43\x22\ +\x8c\xe8\x7c\xab\x83\xc0\x72\x65\x3b\xb0\xe0\x1f\x71\x9c\xf0\x1c\ +\xc0\xe2\x58\xd2\xff\x41\xc7\x85\xce\xc1\x0c\x34\xce\x45\x48\xbb\ +\x12\xf9\xa3\xb0\x0a\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\ +\x40\xb6\x01\xd9\xa8\x00\x64\x1b\x90\x8d\x0a\x40\xb6\x01\xd9\xa8\ +\x00\x64\x1b\x90\x8d\x9f\xfb\x01\xb2\x68\xaf\xf0\xed\xbf\x1a\x8a\ +\xa5\x0d\xd1\x1a\x01\x84\xa5\xd2\xa6\x48\x05\x40\x0c\xd3\xa5\x6d\ +\x51\x0a\xa0\xb0\xa1\xeb\x99\xd2\xc6\xa8\x04\xc0\x01\x2d\xee\x74\ +\x6f\x38\x0a\x01\x70\x06\x76\xa3\xdc\x7d\xe1\x7a\xda\x05\xfc\x50\ +\x00\xb4\xf8\xbc\xcb\x65\xe9\xff\x31\x80\x7f\xd7\xe5\x37\xd7\x8b\ +\xa3\xef\x1f\xdf\x5b\x73\xeb\x6c\x7b\xd5\x1c\xc2\x5e\x2b\x8a\xcf\ +\xf9\x6c\xaa\x23\x6c\x51\xfb\x1a\xc0\xf0\x3d\xec\x22\xa1\xc0\xb0\ +\x2c\x42\xd6\x1e\x00\xe1\xb5\x88\x42\x41\x61\xa0\x37\x22\x74\x6d\ +\x01\x68\xc0\x43\x00\x9b\x22\x8a\x05\xe0\xa7\x65\x59\xe3\x22\x84\ +\xf5\xd2\x86\xaf\x0b\xb9\xe5\x96\xee\xde\x55\x00\xe7\x45\x14\xf4\ +\x03\x03\xae\xe4\x27\xef\x2c\x88\xd0\x76\x3c\x07\xe4\x9b\x7f\x3c\ +\x02\xf0\x54\x44\x41\xaf\x30\x46\xc3\xf3\xd9\xd4\x0b\x51\xfa\xb6\ +\x11\x00\x00\x98\x9d\xa5\x6f\x17\x8f\x3f\x6b\x59\xdb\xb5\x02\xe0\ +\x54\xd9\x7e\x62\x59\x61\x8c\xae\xcd\x4f\xdc\x36\x45\x16\xa9\xf8\ +\xc5\xf5\xb8\x61\x1e\xb3\x80\x21\x30\x9c\x01\x61\x9f\x48\x33\x7f\ +\x29\x00\x6c\xa6\x81\x6d\x3d\x98\x9b\xb8\xfb\xa5\x06\xf5\x14\x0a\ +\x45\x84\xf9\x03\x3a\xde\xd0\x31\x4b\x14\x34\x6a\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x01\x09\x00\x20\x10\x04\xc1\xd7\x52\xb6\x36\xa2\x7e\x0a\x39\ +\x90\x99\x04\xcb\x56\x01\x00\x00\x00\x00\x00\x00\xf0\xbf\xb1\xf6\ +\xb9\xe9\x88\xa4\x99\x0e\x48\x33\x20\x1d\x00\x00\x00\x00\x00\x00\ +\x00\x00\xef\x35\x86\x6a\x02\xea\xd1\x43\x33\x62\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x08\x4f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x01\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x70\x54\xd5\x1d\x3d\xe7\xee\x26\x61\xab\x01\x0b\x7e\xb4\ +\xa3\x19\x8a\x4e\x19\x0c\x15\x5b\x20\x6c\x42\x11\xc1\x69\xc7\xca\ +\x00\x71\x13\x4c\xd5\x0e\x4a\x75\xa8\xc5\xd6\x99\xd6\xb1\x74\x70\ +\x46\x03\xad\xd8\x6a\x2b\xa8\x7f\x48\x5b\x3f\x2a\x2a\xd3\x99\x85\ +\xcd\x06\xe9\x80\x3a\x53\x09\x83\x7c\x6c\x42\xc6\xd6\x51\xa1\x63\ +\xeb\x07\x30\xa9\x5a\x0a\xe5\xc3\x12\xd8\xdd\x7b\xfa\x47\x50\xdf\ +\x7b\xbb\x9b\xec\x66\xdf\xc6\xa4\xcd\x99\xd9\x3f\xde\xef\x9e\xfb\ +\x7b\xe7\x9e\xf7\xf6\xbe\xfb\xee\xbd\x0f\x18\xc6\x30\x86\xf1\xff\ +\x0c\x0e\xc4\x49\xae\x88\xea\xbc\xd3\x65\x98\x49\x6b\x2f\x93\xc1\ +\x04\x8a\x17\x0b\x38\x07\xc0\x48\x00\x01\x00\xc7\xce\xfc\xf6\x0b\ +\xda\x0b\x98\x37\x11\xc4\xf6\xf6\xf9\x7c\xa7\xd4\xda\x4a\x66\xc0\ +\xf4\xb8\x2e\x49\x5b\xbb\x08\xe4\x7c\x00\x93\xfa\x95\x44\x78\x07\ +\x46\x5b\xac\x35\x4f\x77\x34\x60\x0f\x48\xf9\xab\xd2\x6f\x03\x24\ +\xd6\xc5\x71\xb5\x85\x96\x02\x98\xed\x67\x6a\x02\xaf\x0b\x5c\x95\ +\xfa\x27\x9e\xeb\xbc\x8d\x49\x1f\xf3\xfa\x83\x70\x4c\xb3\x61\xf4\ +\x20\x84\xa9\x7e\xe5\xcc\x81\x77\x05\x2e\x6f\x8f\xe0\x19\x3f\xee\ +\x88\xa2\x0d\x08\x6f\xd4\x05\x4a\xdb\x87\x08\x7e\xa7\x17\x9a\x05\ +\xb0\x03\x54\x9b\xac\xd9\x67\x02\xf8\xbb\x52\x38\x6c\x2d\x8e\x8f\ +\x00\xd2\x27\x0d\x2a\xcb\x80\x51\x32\x18\x27\x60\x3c\xa0\x3a\x00\ +\xdf\x04\x10\xea\x25\xe7\x76\x6b\xb9\xa4\x63\x01\xdf\x28\x46\x7f\ +\x51\x06\xd4\xc5\x35\xcd\x4a\xad\x00\xbe\x98\xa5\xf8\x38\xa8\xcd\ +\x94\xd9\x64\x81\x17\xda\x1b\xf8\xaf\x82\x72\x47\x15\x4a\x07\x70\ +\x15\x69\xe7\x01\x9c\x9f\xe3\x1c\xdd\x22\x6f\x69\x8f\xf0\x0f\xfd\ +\xd1\x0f\x14\x61\xc0\xb4\x98\x6e\x04\xf5\x14\x81\x0a\xaf\x28\x4a\ +\x8f\x06\x2b\xcc\x2f\x5f\x99\xcb\x23\xfd\xcd\xef\x44\x75\x54\xe5\ +\x95\x41\x2c\x06\x74\x2f\x80\xf3\xbd\xe5\x82\x56\xb6\xff\xc5\xdc\ +\x8b\x15\xb4\x85\xe6\x2e\xdc\x80\x66\x99\xf0\x24\x7b\x1f\xc8\x65\ +\x9e\x12\x2b\xe8\x29\xca\xac\x48\x34\xf2\x60\xc1\x79\xf3\xc0\xd7\ +\x37\xaa\x32\x69\x71\x27\xa5\xbb\x00\x9c\xed\x2a\x14\x5a\x43\x69\ +\x2e\x6c\x6b\xe2\x89\x42\x72\x16\x66\x40\xb3\x4c\xf8\x72\xbb\x0e\ +\xe0\xf5\x9e\x92\x2e\x43\x46\x76\x45\xd8\x5e\x50\xbe\x7e\x22\x1c\ +\xd3\x45\x30\x8a\x7b\x3b\x5c\x11\xaf\xb2\x82\xb3\x12\x73\x78\x2c\ +\xdf\x5c\xa6\xa0\x13\x7f\xd5\x2e\xcf\xd2\xf8\xdd\x29\x71\xea\x40\ +\x35\x1e\x00\x12\x8d\x3c\x68\x92\x9c\x29\x68\x9d\x33\x4e\xe1\x6b\ +\xec\xd6\xba\xeb\xa2\x0a\xe4\x9b\x2b\x6f\x03\x6a\x63\xfa\x36\xc4\ +\x7b\x5c\x27\x84\xd6\x86\x8e\x72\x76\x67\x23\xff\x91\x6f\x1e\xbf\ +\xb0\xab\x89\x27\xdb\x23\x66\xa1\xc8\x9f\x02\xf8\xe4\x71\x28\x60\ +\xee\x81\x80\xbd\x3f\xdf\x3c\x79\xfd\x05\xa6\x6d\xd0\x54\x1a\x6d\ +\x07\x30\xe2\xd3\xa8\x9e\x4b\x44\xcc\x4d\xa5\x18\x9d\x15\x8a\x70\ +\x4c\x3f\x02\xb5\xda\x19\x13\x78\x73\x7b\x03\x9f\xe9\xab\x6e\x9f\ +\x77\xc0\xb4\x16\x8d\xa1\x51\x2b\x5c\x8d\x47\x7b\xe8\xa8\x59\x3c\ +\x18\x1a\x0f\x00\x89\x06\x3c\x02\xe8\xf7\xce\x18\xa1\xc7\x6b\x63\ +\x9a\xdc\x57\xdd\x3e\x0d\x20\xec\x83\x00\x2e\x74\x84\xba\x82\x01\ +\x46\xda\xbe\xcb\xee\xc2\xa5\x96\x08\xa4\x46\x8f\x30\x4b\x24\xec\ +\x74\x44\xcb\x45\x3d\x3e\x6b\xab\x82\xbd\x55\xed\xd5\x80\x70\x8b\ +\x66\x00\xbc\xc5\x11\x12\xc4\xc6\x1d\xf5\xec\x2a\x46\x6f\x29\xb0\ +\x65\x0e\x4f\x31\xc8\x06\x00\x87\x1c\xe1\xc9\xdd\x47\x70\x7b\x6f\ +\xf5\x72\x1b\x20\x11\xd0\x2f\x3c\xc1\x75\x89\x46\xee\x2e\x42\x67\ +\x49\x91\xa8\xe7\x07\x10\x57\x3a\x63\x82\xee\x99\xf4\xa2\xce\xca\ +\x55\x27\xa7\x01\x75\x71\xcc\x04\x30\xc3\x11\x4a\xa6\xad\x69\x2e\ +\x5e\x66\x69\x11\x3a\x86\xdf\x90\xd8\xef\x08\x9d\xfb\xb9\x8f\x70\ +\x5b\x2e\x7e\x4e\x03\x2c\xf4\x13\xe7\x31\xa5\xdf\xee\x59\xc0\xb7\ +\x7d\xd0\x58\x52\xf4\xf4\x4d\x74\x5d\x28\x41\x77\xe6\x1a\x1b\x64\ +\x35\xa0\x26\xaa\x2f\x00\xf8\x96\x23\x94\x54\xd0\xdc\xe7\x9f\xcc\ +\xd2\xa2\x2a\x89\x67\x01\xbc\xe5\x08\x5d\xf8\x9e\xc1\x37\xb2\x71\ +\xb3\x1a\x10\x08\xe2\x46\xf4\x4c\x55\xf5\x80\x78\x39\x51\xcf\x0f\ +\xfc\x14\x59\x4a\xac\x6f\x62\x9a\xd0\x7a\x67\x8c\xc6\xde\x9c\x8d\ +\x9b\xd5\x00\x41\xf3\x5c\x01\xcb\xe7\x7d\x53\x37\x50\x30\xc6\xa3\ +\x99\x73\xb2\xfd\x0d\x32\x0c\x38\xd3\x63\x4e\x77\xc6\x52\x69\xfc\ +\xd1\x67\x79\x25\xc7\xee\x57\xd1\x01\xc0\x79\xd7\x8e\x3a\x58\x86\ +\x29\x5e\x5e\x86\x01\x15\xff\x41\x2d\x80\x72\x47\xe8\xcf\x9d\x4d\ +\xdc\xef\xe5\x0d\x7a\xac\xa0\xa5\xe4\xba\x70\x52\xe6\x3c\x65\x86\ +\x01\x06\xf8\x8a\xab\x12\xb5\xdd\x7f\x75\x03\x03\x4b\xe3\xd2\x2e\ +\xda\x89\x5e\x4e\x66\x1f\x20\x7b\xa9\x8b\x60\xcd\x5b\x19\x9c\x21\ +\x82\x80\x81\x47\x3b\x2f\xf5\x72\x32\x0d\x20\xbf\xe4\x3c\xb4\xc0\ +\xa0\x7f\xf6\xe7\x42\xea\xb4\x47\xbb\x30\xce\xcb\xc9\x30\x40\x16\ +\x95\x1e\xc2\xbf\x7d\x57\x36\x40\x38\xeb\xa3\x0c\xed\x95\x5e\x4e\ +\x86\x01\xa4\x9b\x64\x89\x82\xe6\xd8\x06\x13\xda\x16\xe1\x14\x80\ +\x94\x23\x54\x5e\x1d\x95\xb3\x83\xcf\x62\x80\x67\x92\x84\x16\x83\ +\xe2\x9d\xbf\x54\xc8\xfc\x0b\x00\xc7\x9d\xc7\xde\x3b\x62\x28\x61\ +\xd6\xd3\xa8\x00\xe0\x9c\x0f\x38\xfd\x66\x13\x4f\x3b\x39\x59\x3a\ +\x41\xb8\x66\x54\x6d\xcf\x2a\xee\x90\xc4\xc9\xd1\x18\xe5\x09\x1d\ +\xf7\x72\x32\x0d\xb0\x7a\xcf\xc3\xc8\xe8\x39\x87\x0a\x94\xc6\xc5\ +\x9e\xd0\xbb\x5e\x4e\x96\x77\x01\xb3\xd7\x79\x44\xd9\x2f\xfb\x29\ +\x6a\x80\xe1\xd2\x2e\x68\x9f\x97\x90\xed\x2f\xe0\x59\x6c\xe4\x8c\ +\x0c\xce\x10\x01\x61\x67\xb8\x8f\xcd\xeb\x5e\x4e\x86\x01\xa1\x14\ +\x76\x01\x70\xae\xbf\x4f\x0e\xc7\x74\x91\xff\xf2\x4a\x8c\x66\x19\ +\x80\x73\x5d\x31\xa1\xcd\x4b\xcb\x30\xe0\xcc\xda\xda\x2e\x57\x3d\ +\x62\xae\x97\x37\xd8\x51\x33\x09\x53\xe0\x5e\x51\x3e\x16\x1a\x8d\ +\x3d\x5e\x5e\x8e\xf9\x00\xba\xde\xa2\x08\xcd\xf7\x57\x5e\xe9\x61\ +\x60\x5d\x9a\x05\xbd\xd0\x36\x9b\xa9\x4c\x5e\x16\x94\x05\xb0\x0e\ +\x3d\x9b\x1a\xce\x54\xc6\x55\x57\x44\x75\x9e\xef\x2a\x4b\x85\x66\ +\x19\x90\x0b\x9c\x21\x5a\xb3\x36\x1b\x35\xab\x01\x3b\xea\xd9\x25\ +\xe0\xa5\x4f\x2a\x03\x15\xc9\xa0\xf5\x2e\x87\x0f\x5a\xd4\x5e\x8e\ +\x1b\x00\x4c\x70\x84\xde\x0f\x8d\xf9\xb4\x3d\x4e\xe4\x9c\x15\x16\ +\xf9\x6b\xd7\x31\xf8\x83\xe9\x31\x8d\xf5\x47\x62\xe9\x50\x1d\x55\ +\xb9\xa4\x9f\x3b\x63\x22\x57\x67\xbb\xfd\x81\x5e\x0c\xe8\xb8\x16\ +\x2f\xc3\xdd\x19\x96\xa7\x61\x97\xfb\xa2\xb2\x84\x38\xbb\x0c\xdf\ +\x03\x5d\x83\xb7\xc3\x65\x06\x6b\x72\xf1\x73\xaf\x0c\x91\x22\x79\ +\xb7\x27\x76\x53\x38\xae\x8c\x79\xb5\xc1\x82\x29\xcf\xeb\x5c\x4a\ +\xae\x25\x7c\x88\xf7\xef\xa8\x67\xc6\x10\xf8\x63\xf4\xba\x36\xb8\ +\x3b\xc2\x36\x50\xcf\xba\xf8\x52\x3c\xbc\x51\x17\x14\x27\xd5\x7f\ +\x54\x47\x55\x1e\x48\x69\x03\xdc\x7b\x88\x5e\x4b\x1d\xc2\xa3\xbd\ +\xd5\xeb\x73\x75\x38\x20\x73\x17\xdc\xb3\xab\x55\x4a\xa9\xe5\x9a\ +\xcd\xf2\x6e\x8e\xfa\x4c\x31\x32\x68\x1f\x21\x70\xa5\x23\x94\x34\ +\xe4\xe2\xbe\x36\x55\xf6\x69\xc0\xce\x06\x7e\x08\xf1\x5a\x01\xa7\ +\x3e\x8e\x91\x98\x7e\xb8\xdb\x3e\xd6\xb3\x80\xfa\xd9\x23\x1c\xd3\ +\xed\x02\xbf\xef\x8c\x89\x5c\x92\xcf\xb6\x9d\xbc\x1b\x10\x8e\x69\ +\x21\x28\xf7\x8e\x0b\xe9\x77\xc7\xd3\xe6\x0e\xef\x3b\xf6\x80\x41\ +\x62\x6d\x1c\x77\x08\x5a\x0d\xe7\xc5\xa4\x1e\x4e\x44\x02\x3f\xce\ +\x27\x45\x41\x57\xb0\x36\x96\x7e\x40\xe4\x52\x97\x06\x60\x5b\x3a\ +\xc8\x05\x9d\xf3\x79\x28\x57\xbd\x52\xa0\x3a\xaa\xf2\x91\x01\xfb\ +\x98\xc8\x5b\x5d\x05\xc4\x8b\xa1\x73\x38\x37\xd7\x63\xcf\x8b\x82\ +\x76\x89\x55\xa5\xcd\xdd\x04\xe2\xee\xf3\xe1\xca\x60\x4a\x1d\x75\ +\xad\xba\xac\x90\x5c\xc5\x60\x7a\x8b\xce\xaf\x0c\xea\x4f\x19\x8d\ +\x07\xde\x38\x05\x5e\x9f\x6f\xe3\x81\x7e\x6c\x94\xbc\x2e\xaa\xc0\ +\x81\xa0\xfd\x95\x40\xef\x2d\x96\x04\xb4\x26\x00\xb3\x72\x67\x03\ +\x3f\x2c\x34\x6f\x3e\xa8\x8b\x2a\x94\x0e\xe2\x87\x84\x96\x01\xf8\ +\xbc\xa7\x78\x4b\x2a\xc5\x1b\x3a\x9b\x78\xb4\x90\x9c\xfd\xdf\x2a\ +\x1b\xd7\xad\x94\xd6\x00\x28\xf3\x14\x9d\xa0\xf4\x90\x42\x66\x55\ +\x21\x1b\x16\x7b\xc3\xac\xad\x0a\x76\x1f\xc6\x22\x51\xcb\xe1\xde\ +\xaf\x04\x00\x10\xb4\x6a\x6c\xca\x2c\x5d\xdf\xc4\x74\xa1\xb9\x8b\ +\xea\xc5\x6b\x62\x9a\x69\xa8\x16\x00\x63\xb2\x14\x1f\x01\xb4\x09\ +\x32\x9b\x10\xc2\x4b\x85\x9a\x51\x1d\x55\xf9\x48\x83\x99\x32\x76\ +\x1e\xc0\x7a\x00\xd9\x86\xe1\x49\x91\x4b\xda\x23\x7c\xb2\x3f\xfa\ +\x01\x1f\xb6\xcb\xd7\xb4\xaa\xca\x58\x3d\x0c\xa0\xa1\x17\x5a\x12\ +\xc4\x36\x59\x6e\xa5\xc1\x5f\x25\xfc\x4d\x06\x87\x2b\x82\x38\x91\ +\x34\x48\x9b\x13\xa8\xb4\xe5\x18\xa5\x34\xc6\x81\x18\x4f\xd8\x3a\ +\x80\x57\xa3\xe7\x93\x9a\x5c\xc2\x3b\x44\x2e\x49\x44\xd8\x59\x8c\ +\x7e\xdf\x9e\xe3\xb5\x71\x5d\x23\xe9\x01\x00\xa5\xee\x0c\xbb\x24\ +\xfe\x6c\x6c\x1a\x4f\xf4\xe7\x96\xf7\xc2\xdf\x81\x4c\xb3\xcc\xb4\ +\x49\xa8\x37\xd4\x32\x01\x35\xbe\xe6\x06\xde\x06\xb8\x2a\x74\x14\ +\x4f\xfa\xb9\x47\xb1\x64\x23\xb9\x9a\x0d\x9a\x68\x8c\x5d\x74\xe6\ +\x63\x87\xf1\xfd\x4c\xf3\x3e\xa0\xcd\x56\x66\x6d\xc7\x6b\x78\xa5\ +\x3f\xdf\x03\xf4\x85\x01\x19\xca\xd6\xb4\xaa\x8a\x16\xb3\x8d\xec\ +\x44\x91\x13\x00\x8c\x23\x31\x4a\xc2\x48\xf4\xac\xdc\x1c\x45\xcf\ +\x67\x73\x07\x00\xed\x23\xcd\x3e\x11\xdb\x12\xf5\xd8\x3b\x58\xb6\ +\xe3\x0e\x63\x18\xc3\xf8\xdf\xc4\x7f\x01\x16\x1d\xd4\x53\x92\x2f\ +\x1f\x88\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xeb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x9d\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xbd\x6e\x13\x41\x14\x46\xcf\x75\x08\xa1\x09\x5d\xde\x80\x37\ +\xb0\x5d\xd1\xf0\x08\x34\x58\x36\x09\x08\x1a\x7b\x0b\x6c\x57\x74\ +\xb4\x3c\x80\x6d\x90\x6c\x37\xfc\xe6\x47\x50\x20\xde\x80\x1a\x70\ +\xc5\x73\x20\x21\xd1\x40\x24\x7c\x29\x22\x24\x33\x5e\xc7\xb1\x77\ +\x66\x76\x66\xe3\x5b\xee\xde\xfd\x34\xe7\x68\x76\x76\x35\x1a\xd8\ +\xd4\xa6\x36\x75\x99\x4b\xf2\x1e\x80\xeb\x2a\x37\x07\xb7\x11\x7d\ +\x2a\xc2\x0f\x9d\x4a\x32\x19\xb7\xbf\xcd\xde\xbf\x92\xd7\xc0\x7c\ +\x54\x25\xe9\xd5\x51\x3d\x04\x4a\x28\x48\x49\x87\xc0\xcd\xd9\x9e\ +\x52\x3e\x43\x73\x5f\x67\xf0\x72\x06\xff\xaf\x94\xeb\x66\x5f\x21\ +\x05\xa4\xc2\xc3\x1f\xd0\x27\x66\x6f\xe1\x5e\x81\x45\xf0\xaa\xd2\ +\x98\x8c\x3b\x1f\xcd\xfe\x42\x2d\x82\xe7\xc3\xb7\xdf\xa7\x3d\x53\ +\x18\x01\xeb\xc0\x43\x41\x04\xac\x0b\x0f\x05\x10\x90\x05\x1e\x22\ +\x17\x90\x15\x1e\x22\x16\x60\x03\x1e\x22\x15\x60\x0b\x1e\x22\x14\ +\x60\x13\x1e\x22\x13\x60\x1b\x1e\x22\x12\xe0\x02\x1e\x22\x11\xe0\ +\x0a\x1e\x22\x10\xe0\x12\x1e\x02\x17\xe0\x1a\x1e\x02\x16\xe0\x03\ +\x1e\x02\x15\xe0\x0b\x1e\x02\x14\x60\x1b\xbe\xdc\x1c\xdc\x91\x92\ +\x3e\x07\x28\xa1\xad\xcf\xc3\xee\x87\xd9\xfb\x41\xed\x08\xd9\x86\ +\xaf\x24\xbd\xba\x88\x9e\xa0\xec\xa1\xec\x4d\x91\x91\xd9\x13\x8c\ +\x00\x17\xf0\x29\x79\x73\x15\x84\x00\x4f\xf0\x53\x41\x1f\x99\xbd\ +\xb9\x0b\xf0\x06\x2f\xdc\xff\x32\xec\xbe\x33\xfb\x73\x5d\x04\xfd\ +\xc2\x77\x0e\xd3\x9e\xc9\x4d\x40\x08\xf0\x90\x93\x80\x50\xe0\x21\ +\x07\x01\x21\xc1\x83\x67\x01\xa1\xc1\x83\x47\x01\x21\xc2\x83\x27\ +\x01\xbe\xe0\x55\xe5\xde\x64\xdc\x3e\x5a\x25\xcb\xb9\x80\x90\xe1\ +\xc1\xb1\x80\xd0\xe1\xc1\xa1\x80\x18\xe0\xc1\x91\x80\x58\xe0\xc1\ +\x81\x80\x98\xe0\xc1\xb2\x80\xd8\xe0\xc1\xa2\x80\x18\xe1\xc1\x92\ +\x80\x58\xe1\xc1\xc2\x19\x21\x5f\xf0\xc0\xc1\x64\xdc\x3e\x5e\x35\ +\xaf\x9a\xf4\x6a\x8a\x3c\x03\x07\x7b\x82\x3e\xe1\xbf\x8e\x3a\xab\ +\xc3\xb7\x06\x07\xaa\x72\xec\x64\x4f\x30\x0a\x78\xf4\x15\x4b\x18\ +\xd7\x12\x10\x3c\x7c\xd2\xdf\x4f\x81\xb7\xb3\x27\x18\x05\xbc\xf2\ +\xda\xcc\xb3\xb2\x27\x18\x37\x7c\xc6\x3d\xc1\xd0\xe1\xcb\xcd\xc1\ +\x5d\x11\x7d\x63\xe6\x2d\xfb\x74\x5e\x48\x40\x51\xe1\xe1\x02\x6b\ +\x80\x37\x78\xd1\x7d\xdf\xf0\xb0\x64\x06\x78\x85\x1f\x76\x4f\x56\ +\xcd\xcb\x0a\x0f\xe7\xfc\x09\x86\x0e\x5f\x69\xf5\x1b\x30\x0f\xcf\ +\x8a\x7f\x8c\xa9\x33\x20\x0e\x78\xde\xce\xe5\xad\xb1\x86\x6c\x99\ +\x17\xaa\x49\xaf\x86\xca\x11\x96\xe0\x17\xe4\xad\x0d\x5f\x4d\x7a\ +\x35\x48\xc9\x5b\x73\x01\xfd\x6f\x06\x94\x9b\xa3\x6d\x91\xdf\xdf\ +\x81\xdd\x99\xcb\x19\x0e\x27\xa4\xe6\x65\x78\xe7\xed\xe6\x81\xf1\ +\x15\xd8\x3d\xbd\xba\x05\xec\xcc\x5c\xca\x74\x2c\x25\x25\x2f\xd3\ +\x60\x6d\xe7\x81\x21\xe0\xd3\xcb\x87\xbf\x54\x79\x0c\x9c\x02\x3f\ +\x81\x7a\x96\x33\x39\x66\x9e\x88\x36\xb2\x0c\xd6\x76\xde\xc2\xba\ +\xd1\xee\xef\x94\x9b\xa3\xed\x50\xf3\x6e\x3d\x78\x71\xcd\x66\xde\ +\xa6\x36\x75\x89\xeb\x2f\x57\x3e\x7f\x9e\x34\x61\xbc\xb4\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\xde\x50\x80\x05\xfc\x5b\x20\ +\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\xf5\x64\xf5\x6c\x3e\xde\x66\ +\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xc0\x07\xe4\xc6\x04\x35\x1a\x89\x95\x2e\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x86\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x38\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x0d\x00\x40\x08\x03\x41\x72\xaa\x90\x87\x21\x24\x92\x9c\ +\x08\x78\xce\xfe\xdb\x4c\xc4\xa2\xec\xa9\xec\xa9\xcd\xc7\xdb\x8c\ +\x2f\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xf8\xac\x79\x05\x03\xdf\x56\x31\xc9\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x03\xa2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x54\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x4f\x53\x51\x18\x87\x9f\xb7\x85\x58\x07\x8d\x9d\x18\x24\ +\x3a\xcb\xa0\x24\x92\x36\x6e\x98\x28\x0c\x1a\x91\x26\xc8\x20\x09\ +\xff\x81\x71\x53\x18\x24\x9a\xf8\x11\x27\x3f\xfe\x02\x12\x17\x31\ +\x82\x18\x1d\x44\x13\x9c\x34\x25\x98\xa0\x03\xce\x12\x1c\x70\xb0\ +\xc4\xc5\x1a\xa4\xaf\x83\x17\x73\xef\xed\xad\xd2\x9e\x7b\x7b\x40\ +\xce\xb3\x9d\xf7\x9e\x9e\xfe\xde\xdf\x3d\x5f\x69\xcf\x01\x87\xc3\ +\xb1\x93\x91\xcd\x54\xea\x9e\xd5\x96\x72\x89\x33\x15\x2a\x83\x82\ +\x74\x29\xec\x17\xd8\x95\xb4\xb8\x7a\x50\xf8\x21\xf0\x59\xd1\xf9\ +\x14\xa9\x87\x99\x2c\x4f\x5f\x1f\x97\x9f\xff\xfa\xdc\x3f\x0d\xc8\ +\x4f\xea\x49\xd0\xbb\xc0\xa1\x58\x94\x36\x8f\x45\x90\x8b\xc5\x82\ +\xbc\xfc\x5b\xa5\x54\xcd\x27\xaa\x92\x7b\xac\xa3\xa0\x33\x6c\xbf\ +\xe4\x01\x3a\x40\x67\xf2\x53\x3a\x82\x6a\xcd\x17\x5d\xd3\x80\xdc\ +\x24\x23\x22\x7a\x3d\x19\x6d\x4d\x44\xf5\x46\xfe\x09\x97\x6b\x3d\ +\x8e\x74\xc6\xeb\xf6\x33\xa1\x70\x49\x45\xae\x90\xe6\xf9\xc1\x32\ +\x4b\x8f\xce\xc9\x7a\xac\x42\x0d\x19\x98\xd0\xf4\xa7\x0c\x07\x58\ +\xe7\x94\xa8\x5e\x03\xb2\xc1\x1a\xd2\x13\x35\x1c\xaa\x0c\xe8\x9e\ +\xd5\x96\xef\x25\xfd\x80\xbf\xdb\x0b\xaf\x48\xc9\x50\xb1\x4f\x56\ +\x62\x57\x9e\x00\xf9\x69\x6d\xa3\xa2\x0f\x50\x4e\xf8\xc2\x8b\xbb\ +\xb3\x72\x24\x3c\x31\x56\x0d\x81\x72\x89\x33\x04\xc7\xfc\xd7\xb4\ +\xca\xf9\xed\x92\x3c\x40\xb1\x4f\x56\x48\xc9\x10\x50\xf2\x85\x3b\ +\xbc\xdc\x02\x54\x19\x50\xa1\x32\xe8\x2f\xab\xc8\xd8\x9b\x82\x7c\ +\x89\x5f\x66\xb2\x14\xfb\x64\x45\x54\xc6\xfc\xb1\x70\x6e\x10\x61\ +\x80\x20\x5d\x81\x40\x9a\xe7\xb1\xab\x6b\x12\x95\x56\x9e\x05\x23\ +\x72\x34\x5c\xa7\xca\x00\x85\xfd\xfe\xf2\xc1\x32\x4b\x71\x0b\x6b\ +\x16\x11\xda\xdb\xc3\x75\x22\x7a\x40\x70\x87\xb7\xd5\x66\xfb\x7a\ +\x08\x6b\x8f\xda\xbd\xd6\xde\x08\xed\x10\x9c\x01\xb6\x05\xd8\xc6\ +\x19\x60\x5b\x80\x6d\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\ +\x9c\x01\xb6\x05\xd8\xc6\x19\x60\x5b\x80\x6d\x5a\xe2\x68\x24\x3f\ +\xa5\x3d\xa8\xde\x06\x0e\xb3\xc9\xff\x1a\x0c\x50\xe0\x3d\x22\x97\ +\x8a\xfd\x12\xfe\xdd\xb2\x6e\x8c\x7b\x40\x6e\x52\x87\x51\x7d\x01\ +\x1c\x21\xf9\xe4\xf1\xbe\xa3\x13\xd5\x17\xb9\x49\x1d\x36\x6d\xcc\ +\xc8\x80\xce\x29\xdd\x27\xe8\x7d\x53\x11\x8d\x22\xe8\xbd\xce\x29\ +\xdd\x67\xd2\x86\x91\x01\x19\x38\x06\xec\x31\x69\xc3\x90\xbd\x9e\ +\x86\x86\xd9\xf1\x93\xa0\x91\x01\x65\x78\x0b\x7c\x8b\x49\x4b\x23\ +\x7c\xf3\x34\x34\x8c\x91\x01\x0b\xfd\xb2\xaa\xc8\x05\x93\x36\x4c\ +\x50\xe4\xc2\x42\xbf\xac\x9a\xb4\x61\x3c\x04\xe6\x0a\x32\x8e\x48\ +\x2f\xb0\xc0\xef\x25\x2a\x69\x36\x96\xc1\xde\xb9\x82\x8c\x9b\x36\ +\x16\xcb\x3e\xc0\x5b\x8f\x8d\xd7\x64\x1b\xb8\x49\xd0\xb6\x00\xdb\ +\x38\x03\x6c\x0b\xb0\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\ +\x8d\x33\xc0\xb6\x00\xdb\x38\x03\x6c\x0b\xb0\x8d\x33\x20\x1c\x50\ +\xf8\xe1\x2f\x0f\x4c\x68\xba\x79\x72\xe2\x25\xac\x3d\x9c\x1b\x44\ +\x1f\x92\xfa\xec\x2f\x7f\xca\x70\x20\x7e\x69\xcd\x21\x42\xfb\x72\ +\xb8\x4e\x44\x0f\xd0\xf9\x40\x60\x9d\x53\xf1\xca\x6a\x1e\xa9\x35\ +\x4e\x07\x23\xfa\xae\xaa\x4e\x75\x20\xf5\xd0\x5f\x16\xd5\x6b\xf9\ +\x69\x6d\x8b\x5b\x5c\xd2\xe4\xa7\xb5\x4d\x45\xaf\xfa\x63\xe1\xdc\ +\x7e\xc7\x42\x64\xb2\x3c\x05\x3e\xfa\x42\x59\x2a\xfa\x60\x3b\x99\ +\xf0\xe7\xb0\x74\xf0\xc4\xf8\xa2\x97\x5b\x80\xba\x8e\xcb\x8b\xca\ +\x58\xa5\x95\x67\x5b\xf9\xb8\x7c\x6a\x8d\xd3\xde\x9b\x6f\xec\xb8\ +\xfc\x06\xb9\xc7\x3a\xfa\x5f\x5c\x98\x00\x10\x19\x2d\xf6\xcb\xcd\ +\xa8\x47\x35\xf7\x01\x73\x05\x6e\x22\x32\x9a\x9c\xaa\xa6\xa0\x20\ +\x23\xc5\xb3\xdc\xaa\x55\x61\xb3\x97\xa6\xee\x00\x1d\xb1\x4a\x4b\ +\x9e\x4d\x5d\x9a\xaa\xfb\xda\x9c\x77\xe4\xbc\x7d\x2b\x5e\x9b\x03\ +\x96\x41\xdf\xd5\x73\x6d\xce\xe1\x70\xec\x6c\x7e\x01\x43\x8d\x07\ +\x87\xbb\xe6\x3f\x9a\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x08\xe5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x08\x97\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x6d\x6c\x14\xc7\x19\x7e\xde\xb9\x0f\xdb\xa1\xfe\x68\x21\xa1\ +\xc8\xd0\x06\xac\x20\x28\xa6\x2a\x98\x56\x35\x45\x60\xc0\x9c\xeb\ +\xaa\x98\xf8\x60\xd5\x90\x0a\x62\xe3\x8f\x86\xa4\xad\x4a\x94\x46\ +\x02\x29\x39\xdc\x86\x7e\xa4\x0d\x09\x89\x14\x08\x9c\x8d\x21\xd0\ +\x48\x3d\x6c\x23\x93\xc6\xe1\x6c\xa7\x46\xa4\x80\x42\x20\x55\x02\ +\x36\x51\x52\x87\x50\x6a\x25\x51\xb1\x9d\x03\x81\xed\xbb\x9b\xb7\ +\x3f\xf8\xda\xdd\x5b\x9f\xef\x7c\xbb\xae\x69\xfd\xfc\x9b\x67\xde\ +\x7d\xf7\xd9\xe7\x66\x67\x66\x67\xe6\x80\x31\x8c\x61\x0c\xff\xcf\ +\xa0\x91\xb8\x49\xa1\x52\x7a\x77\x50\xda\x17\x0a\xe2\xd9\x92\x31\ +\x83\x80\x69\x00\x67\x80\x28\x0d\x12\x36\x10\x02\x00\x02\x20\xbe\ +\x00\x89\x0e\x16\xd4\x2e\x08\x47\xfd\x3e\xef\xc7\x56\x6b\xb3\xcc\ +\x80\x25\xf7\x57\x66\x09\x7b\xb8\x44\x30\x15\x31\xf0\xcd\x61\xa6\ +\xf9\x98\x99\x9b\x18\xa2\xb6\xb5\x7e\xd7\x3b\x00\xd8\x4c\x8d\x80\ +\xf9\x06\xd0\xd2\xe2\xb2\x02\x12\xe2\x09\x02\x2f\x36\x39\xf7\x19\ +\x26\x6c\xed\xf9\x8a\xd8\x77\x6a\xe7\xce\xa0\x59\x49\x4d\x33\xa0\ +\xc0\xbd\x6e\xb1\x24\xf1\x0c\x80\x79\x66\xe5\x34\x06\x9f\x27\x60\ +\xb3\xbf\xae\x7a\x2f\x4c\x68\x11\x09\x1b\xb0\xb4\xa8\x7c\x22\xd9\ +\xf1\x2c\x11\x7e\x1c\x25\x4c\x32\xf0\x37\x62\xb4\x31\xf8\x9c\x20\ +\xdb\x3f\x18\xd4\x1d\x14\xfd\x97\x53\x40\xe1\x81\x30\x52\x89\x44\ +\x3a\x88\xa6\x82\x31\x9d\x88\x73\xc1\xb4\x0c\x40\xca\x60\x09\x19\ +\x38\x6a\x03\xad\x3f\x5c\xb7\xeb\x6c\x22\xfa\x13\x32\xa0\x40\x29\ +\xfb\x8e\x94\x74\x10\xc0\x24\x7d\x1d\x03\x97\x01\xbc\x2e\x88\x0e\ +\x85\xc3\xfd\x6f\xb4\x36\xec\xbd\x14\x4f\xee\x5c\x65\x43\xca\xb8\ +\x70\x60\x09\x41\x2c\x07\x71\x91\xd1\x3d\x00\xf4\x01\x58\xd7\x5c\ +\xe7\x7d\x75\x58\x0f\x80\x04\x0c\xc8\x77\x97\x3d\x48\x44\x35\x00\ +\x92\x22\x44\x11\xbd\xe0\x74\xda\x7f\xf7\x97\x3f\x6d\xef\x19\x6e\ +\x7e\x35\x14\x45\x71\xf6\xca\xf4\x0a\x00\x4f\x01\xb8\x47\x5f\x4f\ +\xc0\x96\xdc\xec\xcc\xa7\xaa\xaa\xaa\x64\xbc\xb9\xe3\x36\xc0\xe3\ +\xf1\x88\x63\x67\xbb\x9e\x06\xf3\x46\x5d\x95\x04\xa3\xc6\x0e\x54\ +\x35\xd5\x7b\x2f\xc6\x9b\x37\x16\x14\x15\xad\x4b\xbd\x6a\x17\x8f\ +\x11\xe1\x71\x00\x5f\x52\xd7\x31\xe8\x60\x48\x38\xd6\xb4\xf9\x5e\ +\xba\x12\x4f\xce\xb8\x0c\xf0\x78\x3c\xe2\xd8\xfb\x17\xf7\x83\xe8\ +\x01\x5d\x96\x2e\x41\x5c\x7c\xd8\x57\xfd\x76\x3c\xf9\x86\x8b\x42\ +\x77\xf9\xe4\x10\xa1\x01\x91\x1d\xee\xbb\xf6\xe4\x6b\x79\x4d\xfb\ +\xf7\x07\x62\xcd\x65\x8b\xe7\xc6\xce\xf1\xf7\x55\x81\xe8\x51\x1d\ +\x7d\x42\xb0\x58\x7a\xb8\xce\xfb\x41\x3c\xb9\x12\xc1\x47\x1d\xa7\ +\x03\x13\xb3\x17\xed\x73\xc8\x81\x7b\x89\x34\x73\x8c\x49\xe1\x90\ +\x63\x76\x4e\x76\xd6\x9f\xdb\xdb\xdb\x63\x1a\x21\x62\x36\xc0\xe5\ +\x2e\xff\x11\x08\x2f\xea\xe8\x3d\xc1\xd4\x90\xd2\xfa\x6a\x75\x6f\ +\xac\x79\xcc\xc2\xc5\xf6\x13\xa1\xce\x8e\xd3\x0d\x59\x33\xe7\x5c\ +\x05\x51\x3e\x6e\xb4\x66\x02\xa6\xf7\x21\x25\xb9\xb3\xfd\x74\x4b\ +\x2c\x79\x62\x7a\x05\x96\xad\x5c\x37\x0f\x10\x47\x01\x24\xab\xe8\ +\x7d\xcd\x75\xde\xb5\xb0\x60\x76\x16\x2f\xf2\xdd\xe5\xbf\x20\xc2\ +\x73\x6a\x8e\x09\x0f\xb5\x1c\xf0\xee\x1d\xea\x5a\x31\x54\xc0\xd2\ +\xe2\xb5\xe3\x01\x71\x10\xea\x87\x67\xbc\x1d\x4c\x0d\x55\x60\x14\ +\x3c\x3c\x00\xb4\xd4\x7b\xb7\x81\xb1\x5b\xcd\x11\x63\x57\x81\xbb\ +\x72\xee\x50\xd7\x0e\x69\x00\x89\xa4\x67\x00\x64\xde\x26\xd0\x85\ +\x90\x2c\x6e\xab\xad\xed\x1b\x8e\x58\x8b\xc0\xf6\x6b\x29\xeb\x01\ +\x1c\x53\x71\xce\x30\xc9\x5d\x79\x79\x1e\x7b\xb4\x0b\xa3\x1a\x90\ +\xaf\x54\x2e\x20\xf0\x3a\xf5\x8d\x58\x62\x65\x73\x63\x4d\x57\x02\ +\x62\x2d\x41\x53\xd3\x8b\xfd\x32\x08\x37\x18\xff\xbe\xc9\x11\x30\ +\xd7\x39\xfe\x5f\x8f\x44\xbb\x2e\x9a\x01\x44\xe1\xf0\x6f\x75\xdc\ +\xfe\x96\x7a\xef\x89\x44\x84\x5a\x89\xd6\x46\xef\x67\x0c\x6c\x51\ +\x73\xcc\x78\xd2\xb5\x66\xcd\xb8\xc1\xae\x19\xd4\x80\x65\x4a\xc5\ +\x42\x10\x2d\x50\x51\x41\xc9\x61\x8f\x09\x3a\x2d\x45\x28\x2d\xb4\ +\x03\xc0\x85\x5b\x04\x61\x02\x5f\x4d\xfe\xc9\x60\xf1\x83\xb7\x00\ +\xc6\x2f\xb5\x04\xbd\xdc\x5a\xbf\xbb\x33\x61\x85\x16\xa3\xad\xb6\ +\xb6\x0f\x4c\xba\x1f\x8a\x1f\x53\x14\xc5\x70\xc8\x37\x34\x20\x4f\ +\x29\xf9\x2a\x98\xbf\xaf\xa2\x82\x32\xc8\x4f\x9b\xa6\xd2\x62\x64\ +\xd8\x7a\x5f\x01\xf8\x43\x15\x95\xd9\x23\x33\xf2\x8d\x62\x0d\x0d\ +\x70\x48\xc7\x83\xd0\x4e\x92\xde\x6c\x6d\xf4\x7e\x66\xa2\x46\x4b\ +\xe1\xf3\xf9\xc2\x60\xf2\xa9\x39\x02\x3f\x64\x14\x3b\xc8\x2b\xc0\ +\xcb\x35\x17\x13\x35\x9a\x25\x6e\xa4\x40\x24\xf4\x9a\x7f\x60\xf4\ +\x1a\x44\x18\x70\xa3\xc7\x9c\xaf\xe6\x24\xd1\x6b\xe6\xca\xb3\x1e\ +\xb9\xd9\x93\x4e\x82\xa0\x6e\xb5\xe9\x01\xa4\xe5\xe8\xe3\x22\x0c\ +\xe0\x6b\xce\xef\x02\x70\xaa\xa8\xbf\xb7\xf8\x76\x5e\xd0\xc7\x8d\ +\x76\x54\x55\x55\x49\x30\x34\x3f\x9c\x64\x11\xb1\x4e\x19\xf9\x0a\ +\xb0\xc8\x56\x17\x89\x70\xd4\x74\x75\x23\x04\x02\x6b\xb5\x33\x66\ +\xe9\x63\x0c\x0c\xc0\x4c\x75\x51\x4a\xfa\x30\x22\xe6\x4e\x01\x09\ +\x9d\x76\x9e\xa9\x0f\x89\x34\x80\xf8\x5e\x2d\x21\x47\xfd\xd8\x3f\ +\x18\x06\x28\xa8\xd7\x3e\x55\x1f\x63\x34\x0a\xa4\xaa\x0b\x04\x8c\ +\xf8\xb7\xbe\x69\x18\x17\xa1\x3d\x55\x1f\x32\xa4\x01\x82\x39\xae\ +\x35\xb6\xd1\x84\xb6\xda\xda\x7e\x00\x21\x15\xe5\x54\x14\x45\xdd\ +\xc1\x1b\x1a\xa0\x59\x24\x09\x09\x31\x2a\xbe\xf9\xad\x42\x84\x01\ +\xc4\xb8\xac\x09\x60\x8e\x68\x36\x77\x0a\xf2\x4a\x4a\x92\x00\xa8\ +\xd7\x03\x06\x7c\x3e\xdf\x80\x3a\x26\x72\x1e\x70\x7d\xa7\xf6\x76\ +\x19\xc8\xb0\x46\x9e\xf5\xb0\x75\xdb\xd3\x75\xd4\x65\x7d\x4c\xa4\ +\x01\xc0\x27\x1a\x82\x22\x7b\xce\x3b\x06\x49\x72\x9a\xa6\xcc\x38\ +\xaf\x0f\x31\x9a\x07\x74\xa8\x8b\x04\xba\xcf\x64\x59\x23\x06\x62\ +\xa1\xd1\xce\xc0\x39\x7d\x4c\x84\x01\x82\xa1\xd9\x6c\x64\x60\x81\ +\x3e\xe6\x4e\x81\x60\xd6\x6a\x27\x9c\x89\x88\xd1\x13\x03\x76\xe7\ +\x71\x00\xb7\xf6\xdf\x09\x98\x5b\xe8\x2e\x9f\x6c\x85\x40\x2b\xe1\ +\xf1\x78\x04\x83\x7e\xa8\x21\x19\x6d\xfa\xb8\x08\x03\x6e\xec\xad\ +\x1d\x57\x73\x21\xd2\x25\xba\x03\xf0\xd6\xfb\x5d\x39\xd0\xec\x28\ +\x53\x20\xd4\x9d\xf9\x8e\x3e\xce\x70\x3d\x80\x00\xdd\xe7\xaf\x2c\ +\x32\x55\xdd\x08\x80\x84\x5e\x33\xbf\xd1\xd6\x56\x15\xd2\xc7\x19\ +\x1a\xc0\x41\xb9\x1f\x80\x6a\xab\x99\x96\x14\x2a\xa5\x77\x9b\xaa\ +\xd0\x42\x78\x3c\x1e\x41\x4c\xab\x74\xf4\x1e\xa3\x58\x43\x03\x9a\ +\x1b\x6b\xba\x88\xe0\x57\x51\x49\x41\x69\xd7\x6f\x87\x8f\x5a\x1c\ +\x3f\xdb\xb5\x1a\xc0\x8c\x9b\x65\x02\x3e\x0d\x5e\xca\xf4\x1b\xc5\ +\x0e\xba\x2a\xcc\xe0\x3f\xaa\xcb\x04\x7e\x74\x89\xbb\xec\xeb\xa6\ +\xa9\xb4\x08\x8a\xa2\x38\x99\xf9\xd7\x6a\x8e\x99\x9f\x33\x6a\xfe\ +\x40\x14\x03\x9a\x0f\x54\xbf\x49\xac\xe9\x0c\x9d\x36\xc2\x66\x73\ +\x64\x5a\x87\x1e\x99\x56\x09\xed\x67\x6f\x77\x4a\x88\xb7\x0f\x16\ +\x1f\x6d\x67\x88\xa5\xc0\x26\x2d\x45\x6b\x5d\x4a\x79\xc4\xba\xda\ +\x68\x41\xde\xea\xca\x09\x04\x7a\x52\x43\x32\x7e\xd3\xd8\x58\x13\ +\x31\x05\xbe\x89\xa8\x7b\x83\x2d\x07\xbc\x6d\x00\xbd\xa2\x8e\x67\ +\x89\x86\xa5\x45\xe5\x13\x13\x52\x6a\x01\x14\x45\x71\x3a\xfa\xe5\ +\x01\xa8\xce\x10\x11\xf0\x5e\xf7\x04\xf1\x42\xb4\xeb\x86\xde\x1d\ +\x96\xb6\xc7\x75\xab\xab\x53\x84\x03\xf5\x85\x85\x3f\xd3\x1f\x8e\ +\xfa\xaf\xa2\x57\xa6\x6f\x03\x61\x91\x8a\x0a\x92\xe0\x8a\xa1\x0e\ +\x55\x0e\x69\x80\xbf\x61\xc7\xe7\x2c\x71\x3f\x80\x7e\x15\x3d\x3f\ +\x78\x57\xdf\x4b\x18\xa1\xb3\xc6\x43\xc1\xb5\xaa\xe2\x11\x00\x0f\ +\xab\x39\x62\xac\x8f\xe5\xcc\x52\x4c\x47\x64\x3a\x3b\x4e\x5f\xcc\ +\x9a\x39\xe7\x13\x10\x15\xdf\xba\x01\x30\x67\xda\x37\xe6\x4e\xca\ +\xc9\xce\xf2\xb7\xb7\xb7\x87\xe3\x56\x6d\x0e\xc8\xb5\xb2\xfc\xe7\ +\x0c\x6c\x83\xea\xc7\x20\xc2\xf3\xfe\x3a\xaf\x7e\x67\xdb\x10\x31\ +\x9f\x11\xea\xec\x78\xf7\xbd\xac\x59\x39\x77\x01\xf8\xde\xad\x1b\ +\x01\x39\x7d\x32\x79\xe1\xd7\xbe\x35\xef\xb5\xf3\x67\x4e\x5d\x8d\ +\x47\x79\xa2\x50\x14\xc5\x99\x39\x73\xfe\xcb\x00\x36\x41\xdb\x12\ +\x0f\x07\x2f\x65\x96\x9e\x3f\x7f\x24\xa6\x33\x83\x43\xbe\x02\x6a\ +\x64\x50\xef\x26\x5c\x3f\x9e\x76\x1b\x84\x45\x8e\x81\xf0\xc9\x7c\ +\xa5\x72\x76\x3c\xb9\x12\x81\xab\xf8\xe1\x7b\x7a\xc3\x69\xad\x00\ +\xca\x74\x55\x67\x83\xe1\xd0\x03\x83\x8d\xf9\x46\x88\xfb\x1d\x56\ +\x14\xc5\xd6\x23\x33\xfe\x40\xe0\x0d\xba\xaa\x20\x80\xed\x24\xed\ +\x5b\xfc\x0d\x3b\x3e\x8f\x37\x6f\x2c\xc8\x55\x36\xa4\xa4\xca\xcb\ +\x3f\x65\xc6\x46\x10\xbe\xac\xad\xe5\x26\x16\xb6\xd5\x2d\xbe\x9d\ +\x5f\xc4\x93\x73\xd8\x9d\x98\xcb\x5d\x5e\xc6\x84\xed\x00\x1c\xba\ +\xaa\x2b\x44\x78\xd6\x96\x74\x6d\x6b\x3c\x07\x16\xa3\x21\x2f\xcf\ +\x63\x77\x4c\xb8\x58\x02\xa6\xcd\x50\x9f\x57\xba\x05\xde\x9a\x21\ +\x02\x4f\xf8\x7c\xbe\xb8\xfb\xa2\x84\x7a\x71\x97\xbb\x6c\x21\x13\ +\xd5\x03\x18\x1f\xa9\x09\x3d\x04\x1c\x02\x70\xc8\x96\x72\xcd\x1f\ +\xaf\x19\x8a\xa2\x38\xbb\xc3\x19\x0b\x05\xf1\x72\x00\x2b\x00\x18\ +\x4d\xc3\x83\xc4\x58\xef\xaf\xf7\x56\x0f\x47\x3f\x60\xc2\x30\xe6\ +\x5a\x51\x3a\x85\xed\xb6\xe7\x01\xb8\xa3\x84\x05\x09\x38\xc2\x84\ +\xbf\x32\xd3\x07\x36\x19\xfe\x88\x25\x77\x3b\xc6\x25\x5f\x91\x14\ +\x08\xf7\x0f\xa4\xa6\x12\xfa\xd3\x29\x2c\xa6\x0a\xc2\x74\x66\xca\ +\x05\x51\x01\xc0\x69\x51\x72\x9e\x24\x81\xf5\x7e\x9f\xf7\x54\x22\ +\xfa\x4d\x1b\xc7\x5d\xab\x2a\x0a\x99\xf9\xf7\x00\xac\xed\x0c\x09\ +\x5d\x00\xff\x2a\x83\x02\xde\xe1\x34\xf9\xc8\x74\x26\xe2\xfa\x61\ +\xea\xae\x15\x20\xde\x08\xe0\xdb\x66\xe6\x06\xd0\x09\x60\x6b\x30\ +\x35\x54\x6d\xe6\x19\x45\xcb\x66\x72\x05\x2b\x2b\x66\x31\x50\xc2\ +\xe0\x22\x00\xd3\x87\x93\x83\x80\x4f\x25\xe8\x75\xc1\x72\x4f\xee\ +\xec\xc9\x6f\x0d\xe7\xff\x00\x31\xdc\xc3\x7a\xb8\x56\x94\x4e\x91\ +\x0e\xdb\x62\x02\xcd\x02\xe4\x0c\x30\x4d\x05\x90\x0e\x20\x0d\xd7\ +\x77\x6e\xbe\x00\x10\x00\xe8\x9f\x00\x9f\x63\xe0\x1c\x8b\xf0\x91\ +\x56\xdf\xee\x0e\x8c\x92\xe3\xb8\x63\x18\xc3\x18\xfe\x37\xf1\x1f\ +\x38\xf1\xe0\xe7\x81\x02\x5e\x62\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\xcd\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\xff\xca\x50\x41\x83\x10\x90\ +\xb1\x24\x9d\x31\x70\x2f\x9b\xfe\x75\x26\x74\xaf\xe7\xbd\xd7\xf3\ +\x96\x1b\xce\xf2\xf8\x1f\x08\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ +\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ +\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\ +\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x09\x50\x0f\xa8\x6d\x1f\ +\xe0\x28\x8f\xd7\x5f\xe3\x33\xf1\x0b\x38\x66\xae\xf2\x3e\x00\x00\ +\x00\x00\x00\x00\x00\x6c\xe2\x03\x9c\x6d\x0b\xf4\x94\x3b\x8d\x4b\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x30\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\xc2\x30\x18\x05\xe1\x67\x86\x48\x87\x94\x99\x58\x21\ +\x15\x13\xb1\x05\x33\x45\xa1\x61\x0b\x53\x80\xa8\xa0\xb2\x9d\x43\ +\xe2\xbe\x2a\xc5\x2f\x78\xbe\x44\xd2\x3f\x2b\xa3\xff\x60\x5d\x6f\ +\xa7\x94\x5c\x92\x24\x35\xe7\x79\x3e\x5e\x7b\xde\xb7\x3a\x8c\xfc\ +\xf1\x24\x79\x3d\x66\x4a\x32\xbd\x1f\xd6\xf3\xbe\xd1\xf8\x00\xcf\ +\xc7\x7c\xfa\xee\x75\xdf\x64\x8f\x00\x3f\xcd\x00\xf4\x00\x9a\x01\ +\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\ +\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\ +\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\ +\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ +\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ +\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ +\x00\xda\x1e\x01\xee\x5f\xbe\x7b\xdd\x37\x19\x1f\xa0\x66\x49\xc9\ +\x96\x92\x2d\x35\x4b\xf7\x7b\x49\x6a\xf0\x00\xc5\x3d\x1c\x34\xe1\ +\xa3\xf7\x6f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x2c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xde\x49\x44\x41\x54\x78\x9c\xed\ +\x98\xcf\x6b\x5c\x55\x14\xc7\x3f\xe7\xbe\x34\x34\x91\x8a\x60\x71\ +\x93\xb6\x2e\xb2\xd0\x90\x22\xc6\x42\x17\xad\x59\xc4\xa6\x69\x0a\ +\x5a\x35\x31\x0b\x17\x22\x4d\x13\xf0\x1f\x10\x7f\x40\x91\xa0\x82\ +\xba\x50\x0a\x2e\x34\x9d\x69\x04\x89\x05\x33\x9d\x74\x84\x9a\x32\ +\x33\x29\x23\xe2\xaa\x36\xe9\xaa\x31\x5d\x04\x6d\x2b\x88\xa6\x0b\ +\x9b\xd2\x40\x66\xe6\x1d\x17\x49\x63\xdf\x9b\x37\xc9\x64\x66\xde\ +\x34\xda\xfb\x59\xbe\xf3\xee\x79\xdf\x73\xef\xb9\xe7\xbe\x7b\xc0\ +\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\xf2\x60\ +\x21\xfe\x07\x9d\x3d\xfd\xef\x89\x31\xc7\x51\x1c\xc0\x05\xb4\xf6\ +\xb2\xaa\x8a\x00\x06\x21\xaf\xae\xfb\x7e\x3a\x7e\x6a\xe8\x5e\x63\ +\x5d\xc1\xdb\xb2\x1a\x3c\x80\xa9\x85\xc2\x9a\xa0\x38\x22\xe6\x38\ +\xe0\x99\x80\xff\x4f\x80\x65\x52\x30\x01\xaa\xee\x07\xa0\xff\xf5\ +\xb4\x0f\x40\x75\x39\x36\x2f\x05\x35\x00\xe0\x50\x4f\x7f\x47\x5e\ +\x4c\x42\x60\x9b\xc7\x05\xa8\x2c\xd7\x85\xcd\x8b\xaa\x41\xc4\x13\ +\x97\xc2\x02\xc2\x91\x74\x2c\x92\xf1\xbf\x1e\x38\x01\x00\x5d\x7d\ +\x03\x7b\x34\xcf\x79\x84\xed\xfe\x2f\x80\x71\x37\x5f\x6d\x14\x40\ +\x0d\xfe\x98\x94\x79\x71\xe8\x4e\x8e\x45\x2e\x15\x1b\x55\x94\xee\ +\xbe\xfe\x27\xf2\xae\x49\x01\x3b\xbd\x4e\x55\x11\xd9\x6c\x99\x50\ +\x18\x3c\x5c\x73\x8c\xdb\x75\x7e\xec\xd4\x6c\xb1\x41\x6b\x4e\x00\ +\x40\xd7\x8b\x47\x77\x6a\x9d\x93\x04\x9e\xf4\x99\x94\xcd\xb3\x1d\ +\x82\x82\xff\x45\x72\xf9\xae\x64\x62\xe4\xfa\x7a\x03\xd7\x24\x99\ +\x18\xb9\x9e\xad\x37\xed\xc0\xcf\x3e\x93\x80\x3a\x41\x63\x6a\x87\ +\xb0\xa2\xc1\x1f\xfc\xc5\x6c\xbd\x69\x5f\x2f\x78\x28\xf1\x18\xcc\ +\x9c\x1e\x9e\x6f\xc8\xba\xcf\x21\x5c\x28\x22\xa0\xe6\x08\x08\xb8\ +\x4e\x40\x12\x4f\x36\x64\xdd\x03\x99\xd3\xc3\xf3\xa5\xf8\x29\x59\ +\xfc\xec\xec\xf4\xd2\xae\xbd\x4f\x7d\xeb\x64\x4d\x2b\xd0\xe2\x91\ +\x02\xa6\x84\xdd\x54\x45\x44\x8a\x7c\x33\x5e\x77\xa7\xa1\xf7\xdc\ +\xb9\x2f\xef\x94\xea\x69\x43\xab\xf7\xeb\xe5\xcb\xb9\x5d\x8f\xbd\ +\x70\xc6\x69\x5c\x68\x02\x9e\x09\x52\x15\x36\x72\xf7\xd7\xb6\x90\ +\xe8\x23\xe6\xef\xd7\x13\x89\x91\xec\x06\xfd\x95\xa7\xa3\xb3\x77\ +\xe0\x63\x81\x37\x03\x1c\xba\x1a\xd6\x19\x29\x08\x1a\x10\xbc\xc8\ +\x27\xa9\xd8\xc9\xb7\x29\xe3\xbb\x65\xef\xdf\xb9\x99\xa9\x54\x73\ +\x4b\xdb\x22\x22\x07\xfd\x72\xc2\xc8\x85\xa2\x2b\xaf\xfa\x56\xea\ +\x4c\x64\xa8\x70\x44\x69\x54\x54\xc0\xe6\x66\xa6\x7f\x6a\x6e\x6d\ +\xfb\x1d\xe4\x79\xbc\xd9\x54\xd5\x19\x10\x10\x2d\x0c\xde\x15\x65\ +\x30\x15\x8f\x7e\x5e\xa1\xef\xca\xe9\xec\x1d\xec\x15\xf4\x1b\xa0\ +\xde\x67\xaa\xf8\x5f\x41\x51\x13\x90\x52\x4b\x2a\xbc\x9a\x8e\x45\ +\xe2\x95\xf8\x86\x2a\xae\xd4\x81\x9e\xc1\x4e\x23\x7a\x16\x78\xc8\ +\x6b\x51\x85\xf2\xfe\x1a\x15\x8c\x14\x6a\xbc\x8d\xe8\x4b\xa9\x58\ +\x74\xb2\x3c\xa5\x5e\xaa\x9a\xaa\x87\xfa\x8e\xed\x75\x5d\xf9\x1e\ +\x78\xd4\x63\x50\x14\xd9\x60\x26\x28\x06\x29\xd0\x77\xd3\x55\x39\ +\x3c\x19\x3f\x79\xb1\x32\xa5\xff\x52\xf5\x6a\xd5\xf9\xf2\x40\x8b\ +\x18\x52\x40\x93\xcf\x54\xfa\x76\x08\xb8\xd1\x01\x37\xd4\xa5\x2b\ +\x3d\x1e\x99\xa9\x82\xcc\x55\xaa\xde\x10\x49\x8f\x47\x66\xf2\xaa\ +\xfb\x81\xab\x3e\x53\xf0\x11\xe6\x43\x09\x0c\xfe\xaa\x1a\xb3\xbf\ +\xda\xc1\x43\x48\x1d\xa1\x0b\xf1\xe8\x6f\xe2\xd6\xb5\x2b\x4c\x79\ +\x0c\xcb\x29\xbd\xd6\xc9\xe3\xf8\x0b\x9e\xc2\x54\x9d\xc9\x3f\x9b\ +\x1e\x1b\xbe\x16\x82\xd4\xf0\x5a\x62\xc9\xf1\x2f\xfe\xdc\xb2\x75\ +\xb1\x03\xe5\x07\xbf\x4d\x03\x27\x21\xf0\x4e\x91\xd9\xb2\x75\xb1\ +\x63\x62\x6c\xe4\xaf\x10\x24\x02\x21\xf7\x04\x27\x46\x47\x6f\x65\ +\x1f\xce\x75\x23\xfa\xdd\xbd\xcf\x57\x96\xd8\x11\x41\x64\x35\x2b\ +\xbc\x59\x2f\x90\xc8\x6e\xcb\x1d\x9e\x18\x1d\xbd\x15\xa6\xc6\xd0\ +\x6f\x72\xcb\xf7\x87\x23\x31\xa7\x71\xe1\x71\xe0\x69\x9f\x59\x08\ +\x2c\xc4\xfa\x55\xf6\xe6\x8e\xd7\x32\x67\x4f\x2c\x85\xad\xaf\x26\ +\x5d\xe1\x4c\x66\x28\xb7\x6f\x77\x53\xbf\x22\x9f\xad\xff\xb6\x7e\ +\xba\x6f\xf7\x8e\x63\x99\xcc\x50\x2e\x7c\x65\xb5\xbd\xc3\x02\xc8\ +\xc1\x57\x06\xde\x41\xf9\x30\xd0\xa8\xfa\x6e\x32\x1e\xfd\x88\x1a\ +\x36\x1c\x6b\xde\xcc\x98\xbb\x32\xf5\x63\x73\x6b\xdb\x1f\x2b\xf7\ +\x87\xbb\xa8\x28\x6f\x24\xe3\xd1\x13\xb5\xd6\x73\x5f\xba\x39\x73\ +\x57\xa6\x2f\x35\xb7\xee\x69\x64\xb9\xcf\x78\x5b\x94\xa3\xc9\x78\ +\xe4\xeb\xfb\xa1\xc5\x62\xb1\x58\x2c\x16\x8b\xc5\x62\xb1\x58\x2c\ +\x16\x8b\xc5\xf2\xa0\xf1\x0f\x64\x76\x37\x12\x6f\xd4\x61\x03\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xc8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xb1\x0d\x83\x40\x10\x44\xd1\xbf\x4b\x0f\x96\x08\x08\xdc\x09\ +\x9d\x10\x90\xb8\x24\x02\xc7\xae\x81\x6e\x08\x1c\x20\xd1\x03\xb7\ +\x8e\x0e\x59\x42\x22\xe3\x2e\x99\x97\x8d\xb4\xd2\x4c\xb0\x20\x22\ +\x22\x52\x99\xfd\x87\x88\x30\xa0\xb9\xb9\x73\x37\xb3\x38\x0d\x58\ +\x96\x6f\x6f\xce\x07\x68\x6f\x1e\xb0\x85\x33\x3c\xbb\x6e\x06\xf0\ +\x63\x89\x33\x15\x28\x07\x78\x58\xe2\x9d\x83\x5f\x5d\x96\x70\x0c\ +\x88\xc4\x0b\x58\x0b\x74\x6e\x61\x31\xe6\x50\xfd\x09\x45\x44\x44\ +\xaa\xfb\x01\x02\x66\x1a\x07\xaf\xc1\xa8\xac\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x63\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x15\x49\x44\x41\x54\x78\x9c\xed\ +\x99\x5f\x48\x53\x61\x18\xc6\x9f\xef\x9c\xcd\xe9\xa0\x14\x2b\x92\ +\xbc\x52\x8c\xae\xba\xda\x99\x56\x26\x44\x04\xa1\x37\x15\x61\xd1\ +\x55\x46\xe2\x51\x6b\xb3\x24\xe8\x22\x68\x17\x75\x17\x99\x6d\x91\ +\x73\x81\x7a\x11\x12\x49\x10\x05\x26\x04\xd9\x45\x65\xe5\x66\x94\ +\x41\x08\xf6\xe7\xa2\x34\x44\x4b\x34\x1c\xfb\xfb\x76\x63\x31\xb7\ +\x63\x43\xf0\xfb\x8e\xd0\xf7\xbb\xdb\xfb\xc2\x9e\xe7\x7b\xce\xbb\ +\x9d\x77\x67\x80\x44\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\ +\x92\xff\x0d\xc6\x5b\x40\xd3\xbd\xbd\x00\x8e\x01\x00\x63\x38\x31\ +\xec\x77\xf7\xf0\xd6\x5c\x09\x5c\x03\xd8\x53\xd7\x9d\xfb\xcb\x36\ +\x1f\x4e\xad\x11\xd1\xde\x50\xa0\x65\x90\xa7\xee\x4a\x50\x78\xbe\ +\xf9\x94\x7d\xc1\x92\x5e\x63\x8c\x3d\xd1\x9a\xda\x4a\x79\xea\xae\ +\x04\x11\x1f\x01\x32\xaa\xdb\x62\xe1\xf5\xcf\xbb\xce\xcf\xf3\xd6\ +\xcf\x06\xd7\x09\x00\x80\x92\x1f\x45\x19\x53\x00\x00\x11\x6b\xde\ +\x1c\x3c\x1e\xee\xfa\xd9\xe0\x6e\xa0\xaf\xef\x48\x42\xcd\x41\xbe\ +\x51\x4f\xfb\xbe\x21\xc1\x5b\x3f\x1b\x42\xae\xc0\x2b\x9f\x7b\x2e\ +\xa9\xaa\x5b\x8d\x7a\x9a\xee\x7d\x26\xc2\xc3\x72\x08\x1b\xc1\x91\ +\x9b\xa7\xc6\x19\x68\x9f\x41\xab\xd2\xa1\xfb\xae\x88\xf2\x91\x8e\ +\x2a\x52\x6c\x22\x34\xf0\x79\x8b\xb3\x7a\x06\x40\x4d\x6a\x9d\x01\ +\xbb\x8a\x9d\xd5\xe3\x13\xc1\x47\xa3\x22\xfd\x2c\x6a\x8b\xc7\xd9\ +\xe8\xeb\x21\xa2\xe3\x19\x0d\x86\x8a\xa0\xdf\xfd\x5a\xa4\x17\x53\ +\x02\x00\x00\x4d\xf7\x7d\x04\x28\x63\x1f\x48\x58\x59\xf1\x9b\x1b\ +\xae\x09\x51\x3e\x4c\x0b\x00\x58\x7e\x47\xb0\xda\xe3\xf6\xa1\x6b\ +\xad\x61\xa3\xde\x6a\x63\xea\x7d\x98\xc8\x96\x63\x54\x8f\x2d\x58\ +\x16\x00\x12\x72\x71\x4c\x0d\x20\x14\xd0\x63\x44\xd1\x4d\x46\x3d\ +\x4d\xf7\xfd\x14\xe1\xc1\xf4\x4d\x2c\x14\x38\x37\x0d\x46\xdb\x0d\ +\x5a\xf9\x9a\xee\xbd\xc3\x5b\xdf\xf4\x00\x00\x20\xe8\x6f\x79\x0f\ +\xd0\x41\x83\xd6\x51\xde\xda\x6b\x22\x00\x00\x20\x52\xc6\xcc\xd0\ +\x5d\x13\x01\x54\xd4\xb7\x6f\x66\x8c\xfa\x33\x1a\x0c\x2f\x78\x6b\ +\x9b\x1e\x80\xa3\xa1\xd3\x9e\x50\x95\x07\x00\x4a\x52\xeb\x8c\xd1\ +\xa5\xa0\xdf\x5d\xc9\x5b\xdf\xd4\x00\x6a\x6b\xef\xaa\x8c\x45\x7a\ +\x01\x94\xa7\xd6\x09\xb8\x35\xec\x77\x7b\x44\x78\x30\x35\x80\x4f\ +\x85\x93\x57\x01\x1c\x48\x2b\x0f\xac\x2b\x9a\x69\x06\x98\xe1\x92\ +\xb4\xda\x98\xb6\x09\x3a\x75\x5f\x0b\x81\xda\x53\x6b\x04\xbc\xcd\ +\x8d\x85\xab\x44\x3e\x29\x32\x25\x80\xf2\xc6\xeb\x87\x92\xc4\xee\ +\xa5\xe9\x7f\xb5\xb2\xf8\x8e\x21\x7f\xeb\x37\x91\x5e\x84\x07\xe0\ +\x68\x68\xaf\x60\x4c\x19\x04\x90\x97\x52\x9e\x4f\x2a\xc9\xdd\x23\ +\x1d\x67\xde\x89\xf6\x63\xf8\xbc\x8e\x17\x5a\x53\x5b\x29\x48\x79\ +\x08\x5a\x72\xf8\x38\xa0\x1c\x1e\xe9\x70\x0b\x3f\x3c\x20\xf0\x4b\ +\x70\xe7\xc9\xb6\x42\x24\x2d\xfd\x20\x2c\xdd\xfd\x19\xf4\x60\xe7\ +\xe9\xc7\xa2\x7c\xa4\x23\x64\x02\xca\x5c\x5e\x5b\x3c\x8a\xfb\x00\ +\xb6\xa5\xd6\x19\x70\x79\xd8\xef\xee\x12\xe1\x61\x39\xf8\x4f\x80\ +\xc7\xa3\x14\x44\xd1\x4d\x40\xd5\xd2\x06\xdd\x1e\xee\x74\x5d\xe4\ +\xae\x9f\x05\xee\x01\x38\x26\x37\x5e\xc0\xe2\x7f\x83\x29\x3c\x9d\ +\xcd\x61\xf5\xa2\xee\xf5\xff\x82\xeb\x5d\xa0\xcc\xe5\xb5\x15\x44\ +\x31\x0b\x20\xf7\x6f\x91\xd8\x87\x88\xaa\x56\x8e\x76\x34\x0b\xf9\ +\xbd\x9f\x0d\xae\x13\x90\x1f\xb1\x25\x01\xc4\xfe\xbc\x66\xc0\x94\ +\x45\x89\xd7\xac\x95\xc3\x03\x9c\x03\x08\x05\xf4\x18\x03\xea\x00\ +\x4c\x03\x18\x43\x32\xb1\xff\xa5\xff\xec\x17\x9e\x9a\x12\x89\x44\ +\x22\x91\x48\x24\x12\x89\x44\x22\x91\x48\x24\xd9\xf8\x0d\x59\x9b\ +\xda\x0c\x1f\xf1\x22\x4f\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x01\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3b\x49\x44\x41\x54\x58\x85\xed\ +\x97\x31\x4e\x02\x41\x14\x86\xbf\xb7\x81\xa5\x74\x69\x56\x0a\x43\ +\x34\xd9\x66\x2f\xe0\x09\x4c\xe4\x0e\x9c\x02\x6b\xb5\x90\x1e\x4e\ +\xc1\x19\x8c\x89\x27\xe0\x02\xdb\x6c\xc0\x80\xc5\x86\x06\x2c\x59\ +\xc8\x3e\x0b\x67\x0d\x2c\x62\xa1\xbb\xb1\x70\xfe\x6a\x32\x33\xc9\ +\xf7\x65\xa6\x79\x3f\xfc\xf7\x48\x71\x63\x3a\x9b\x5d\x3b\x2a\x37\ +\x0a\x97\x80\x57\x12\x67\x25\x30\xce\x44\x07\x17\xed\xf6\xd3\x51\ +\x81\x97\xd9\x6b\x1f\xd5\x5b\x60\x0d\x44\x28\x6f\xa5\xe0\x85\x13\ +\x20\x04\x1a\x88\xf4\xcf\xdb\x67\xf7\x07\x02\xd3\xf9\xbc\x23\x19\ +\x8f\xa0\xcf\xdb\x8d\xdb\x0d\x82\xd6\xa2\x14\xb8\x49\x1c\x27\x7e\ +\xad\x9e\x8e\x40\xae\x54\xb4\x93\xbf\x84\x93\x5f\x70\x32\x7a\xc0\ +\xba\x0a\x38\x40\x10\xb4\x16\xdb\x8d\xdb\x05\x52\x47\xa5\xf7\xc9\ +\xcd\x17\xe6\xcf\xa3\x2a\xe0\xbb\x12\x08\x91\x61\xed\x0b\x00\x5e\ +\x69\x7f\xfe\x5d\x32\x56\x40\xf3\x2b\x81\x3f\x89\x15\xb0\x02\x56\ +\xc0\x0a\x58\x01\x2b\x60\x05\xac\xc0\xae\xc0\xca\x4c\xaf\x55\x13\ +\x3d\x60\x79\x20\x20\x30\x06\xc2\x38\x4e\xfc\xaa\xd8\x71\x9c\xf8\ +\x28\xa1\x61\xed\x0b\x64\xa2\x03\xa0\x51\xab\xa7\xa3\x2a\x24\x26\ +\x93\xc9\xe9\xc7\x58\x8e\x9b\x89\x0e\xf3\xfd\x62\x31\x79\x40\xf5\ +\x0e\x48\x11\x22\x33\x40\xfe\x3e\x0e\x1e\x4a\x08\xb8\x47\x8b\x49\ +\x1e\x53\xcd\x7a\x66\x74\x6e\x16\xcf\x7f\x98\xa5\xa9\x66\xc3\x62\ +\x35\xb3\x79\x07\x25\xbf\x6e\x2c\x3a\x0b\x42\xe7\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xd3\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x85\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\xe8\x01\x51\x0a\x75\x20\x3a\ +\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x26\xb5\ +\x1e\xd9\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\x60\x3b\ +\x4a\x1b\x9c\x6e\xf5\x5c\x53\xc7\x24\x87\x0e\x7d\x96\x34\xe5\x5d\ +\xae\x8f\x4b\xb9\x7f\x87\xbb\x76\x6a\xa5\xcb\x27\xc9\xb1\xec\xeb\ +\xd8\x86\xb3\x03\x6c\xcd\xec\x00\x25\x65\x48\xf2\xec\xd0\x65\x69\ +\x53\x7d\x95\xa1\x77\x09\x00\xe0\x7f\xf8\x05\xda\xa9\x95\x2e\x9f\ +\xf8\x05\x7e\xf3\x0b\x00\x00\x00\x00\x00\x00\xb0\x11\x1f\x5d\xbc\ +\x24\x0f\x6c\x9f\x83\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x01\x8c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3e\x49\x44\x41\x54\x58\x85\xed\ +\xd2\xbf\x2b\x85\x51\x00\xc6\xf1\xef\xf3\xca\x62\x90\x52\xac\xfc\ +\x05\x14\xbd\xf7\x96\xcd\x24\x3f\x8a\x9b\x98\x58\x29\x7f\x80\xcd\ +\x24\x93\xc9\x2c\x52\x06\x03\x2f\x29\x25\x8b\x22\xf1\x8a\xa2\xcc\ +\x16\x65\xb1\xd0\x1d\xa4\xee\xbd\x8f\x81\x01\xc5\xeb\xde\x4d\xce\ +\x67\x3c\x3d\x3d\x3d\xa7\x73\x20\x08\x82\x20\xf8\xef\x94\x15\xc8\ +\x6f\x95\x97\x2d\x75\x95\xd1\xc4\x45\x41\x37\xbf\x29\xcd\x6f\xbb\ +\xcd\xf6\x3a\xe2\x29\x1d\xd6\x20\x92\xbf\xcb\x46\x59\x65\x46\x4d\ +\x40\x67\x1d\x3e\x89\x13\xf7\x66\xe5\x73\xdb\xee\xb2\x7d\x06\xf4\ +\x50\xa1\x39\x2b\x9f\x39\x20\x2a\x6b\x02\xd8\x04\x1a\x85\xf7\xe3\ +\xc4\x93\xdf\x65\xe3\x2d\x0f\x60\x1f\x01\xad\xc0\xe1\x4b\xa4\xbe\ +\x9f\x6e\xff\xab\x01\xa7\x63\x7a\x4e\xaf\x35\x0e\x5e\x04\xea\x85\ +\xd7\x72\x89\xe7\xb0\x3f\x3d\x5f\x9c\x78\x5a\xf2\x2e\xd0\x00\x5e\ +\x2f\x96\xd4\x77\x35\xa2\xc7\xac\xfe\xcc\x3f\xf0\x51\x2e\xf1\x0c\ +\x78\xe9\x6d\xb8\x57\x4b\x0f\xd1\xd4\xe5\x3d\xe5\xb8\xa3\xb2\x20\ +\x34\x0b\x80\x3d\x9f\x16\xa2\xb9\xac\x9b\xd7\x34\x00\x20\xbf\xe3\ +\x21\x57\xbc\x01\x34\x00\xc7\x88\x22\xa6\x1f\x28\x81\xa6\xd2\x82\ +\x56\xaa\xe9\xab\x7a\x00\x40\xbc\xe9\x6e\x45\xde\x03\x5a\xde\x8f\ +\x8a\x48\xa3\xe9\x88\x0e\xaa\xed\xaa\x69\x00\x40\xbc\xeb\x76\x95\ +\x7c\x0b\xdc\x19\x0d\x9d\x17\x74\x5d\x6b\x57\xed\x6c\x7d\xfd\x8c\ +\x41\x10\x04\xc1\x9f\xf3\x0a\x0d\x2b\x72\x05\x90\xf4\xef\x82\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x21\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd3\x49\x44\x41\x54\x58\x85\xed\ +\x97\xb1\x6b\x53\x51\x14\xc6\x7f\x5f\x5e\xe9\x22\x15\xb4\xc4\xfe\ +\x01\x1d\x4a\x47\x5d\x2c\x28\x2e\x79\xea\x10\x09\x54\x5e\xd7\x22\ +\xe4\xe9\x20\x98\xa9\x54\xff\x04\x33\x38\x18\xc1\xc5\x64\xd0\x0e\ +\x45\x94\x08\x85\x0c\x1a\xe2\x20\xa8\x75\xd1\x4d\xb7\xee\x6d\x51\ +\x90\xe0\x52\xc8\x3d\x0e\xbe\x17\x9f\x52\x5e\x89\x7d\x69\x45\xf3\ +\x4d\xf7\x9d\x7b\x38\xdf\xef\xde\x73\x79\xdc\x0b\xff\xbb\xf4\x7b\ +\xe0\xfc\xe5\xf2\x19\xa4\x9b\xc0\x1c\x90\xcf\xc8\x67\x1b\x58\xc7\ +\xac\xda\x6e\x36\x5e\x27\x27\xbc\xe4\x87\x1f\x94\x97\x84\x56\x81\ +\x19\xe0\x48\x46\xe6\x44\xb5\x66\x90\xae\x4c\xcf\x9e\xfa\xb6\xf1\ +\xe9\xfd\xdb\x78\xa2\xbf\x03\xfe\xc2\xb5\xb3\x72\xee\x15\xf0\x15\ +\xb3\x4a\xce\xa3\xf5\xfc\x49\xe3\x4b\x16\xee\x17\x17\xca\xc7\x5d\ +\x8f\x22\x52\x0d\x38\x8a\xd9\xb9\x78\x27\xc6\xfa\x24\xce\x2d\x03\ +\xc2\xac\xd2\x6e\x36\x56\xb2\x30\x8e\x15\x2d\x64\xc5\x0f\x42\xc9\ +\x78\x18\xb5\xb8\x04\x90\x4b\xe4\xcd\x01\xe4\x3c\x5a\x59\x9a\x27\ +\x65\xbd\x9d\xb8\xf6\xe9\x38\x96\x04\xc8\x27\x68\x87\xa2\xce\xb3\ +\x47\x9f\xa3\xe1\x89\xdd\x00\x0e\x45\x23\x80\x11\xc0\xa1\x03\x8c\ +\xed\x95\x70\x21\xb8\x7a\xdd\x99\xdd\x16\x4c\x0c\x52\xd8\xa0\x9b\ +\x93\x6e\xbd\x78\xfa\xe0\x7e\x5a\x5e\xea\x0e\x14\x4a\xe1\x94\x99\ +\xdd\x1b\xd4\x1c\x40\x30\x61\x66\xb5\x42\x29\x9c\xfa\x63\x80\x83\ +\x50\x2a\x40\x67\xad\xbe\x29\xe9\x86\x41\x77\xd0\xc2\x06\x5d\x49\ +\x95\xce\x5a\x7d\x33\x2d\x6f\xcf\x33\x10\xf5\x30\xb5\x8f\xfb\xd1\ +\xdf\xdd\x82\x11\xc0\x08\xe0\xa0\x01\xb6\xe1\xc7\x05\x72\x58\x66\ +\x85\xf9\xc5\xc9\x68\xb8\xb5\x1b\xc0\x3a\x80\xeb\x51\x1c\x16\x80\ +\xbc\xf1\xb8\xf6\xbb\x38\xf6\xf3\x47\x64\x56\x45\xba\x84\x54\xf3\ +\x83\x50\xd6\xdb\x69\x25\xee\x70\xfb\x52\x61\x7e\x71\x52\xde\x78\ +\x51\xc6\x5d\xc0\x61\x56\xed\x43\x25\x13\xfd\xa0\xbc\x24\x53\x95\ +\xe1\x9d\x0d\x87\xb1\xdc\x6e\xd6\xef\xc4\x81\x5f\x5e\x46\x1b\x1f\ +\x3f\xbc\x99\x9e\x3d\xd9\x41\xca\x03\xc7\xc8\xee\x75\xb4\x05\xbc\ +\xc4\x2c\x6c\x37\x1b\x8f\x33\xaa\xf9\x8f\xe8\x3b\xaa\x2b\x8c\x73\ +\x1f\xb4\x18\x18\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x01\xaa\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x5c\x49\x44\x41\x54\x58\x85\xed\ +\x94\x3f\x4b\x42\x51\x18\x87\x9f\x57\xad\x4d\xac\x21\x8a\x5a\x0c\ +\xb7\x6c\x72\x74\x70\x09\x6d\x68\x08\xba\xda\x16\x05\x1a\x41\xdf\ +\xa0\x49\xce\xd0\xd2\x27\xa8\x54\x70\x0a\x32\x8d\x86\x5a\x14\xa4\ +\xbe\x80\xd0\xe4\x94\xd4\x14\xd1\x90\x53\x43\xea\x3d\x4d\x5a\x8d\ +\xf7\x5c\xb8\x4b\xf7\xd9\x5e\x38\xe7\xf7\x3e\xbc\xe7\x0f\xf8\xf8\ +\xf8\xfc\x77\xc4\xe9\xfa\xb4\x55\xb0\x01\x06\xa3\xe1\xec\xfd\x4d\ +\xb5\xef\x56\x20\xe0\x64\x71\xb1\x58\x9c\x08\x4f\x05\x43\x1f\xb9\ +\x5c\x2e\xe8\xa9\x80\x52\xca\x46\xf4\xf6\xb8\xee\xdb\x91\xa1\xa7\ +\x02\x00\xad\x7a\xe5\x4a\xe0\x78\x5c\x67\xac\xc2\xa3\x1b\x01\xa3\ +\x11\x3e\x75\x3b\xed\x58\x3c\x91\x02\x96\x81\xf9\xd8\x4a\x62\xa1\ +\xd7\xed\xdc\x99\x64\x39\xbd\x84\x7f\x48\x5b\x05\x3d\x09\xd2\x1c\ +\x34\xaf\xcb\xe7\x4e\x33\x1c\x1f\xc1\x6f\x92\xab\x4b\x93\x09\x6a\ +\xe1\x2c\xb3\x95\x4f\x79\x2a\xa0\x94\xb2\x07\x81\xe9\xf0\x8f\x84\ +\x3c\x78\x2a\x00\x30\xc7\xfb\x17\xe8\x67\xd3\xfd\x6e\x05\xa4\x6f\ +\xcf\x94\x41\xa2\x08\x6f\x23\xad\xa3\x9e\x0a\x64\xb2\x85\x22\xe8\ +\x1d\xe0\x53\x84\x8d\xf6\x75\xe5\xc5\x69\x86\xf1\x2b\xc8\x58\xf9\ +\x5d\x8d\x54\x01\x5b\x44\x36\x9b\xf5\xd2\xad\x49\x8e\xd1\x3f\x90\ +\xce\xe6\xd7\x40\x6a\x40\x00\xe4\xb0\xd5\x28\x5d\x98\xe4\x80\xc1\ +\x11\xac\x5b\xfb\x71\xb4\x34\x80\x10\x22\x27\xad\x46\xe9\xd4\xb4\ +\xb9\x89\x80\xd8\x50\x03\x22\x1a\x2e\x93\xf1\xc5\x23\x37\xcd\x01\ +\x42\xce\xb7\xe8\x57\x0d\xbd\x61\x78\xb8\xa7\x94\xb2\xdd\x0a\xf8\ +\xf8\xf8\xf8\x7c\x03\xa5\xd7\x5e\xc1\x97\x2b\x14\xb6\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x31\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe3\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x11\x82\x40\x18\x05\xe1\xf7\x5b\x04\xb5\x58\x07\x2d\x18\ +\x59\x91\x5d\x50\x87\x75\x10\x59\x05\x18\xa0\x99\x46\x77\xb0\xce\ +\xb8\x5f\x74\xc1\x0d\xbc\xdb\x44\xd2\x3f\xab\xbd\x7f\x70\x9e\xd6\ +\x71\xcd\x7a\xdb\x7e\x56\xd7\xfb\x58\x53\xcf\xfb\xad\x4e\x7b\x7e\ +\x3c\x49\x5e\x8f\x19\x92\x0c\xef\x87\xf5\xbc\xdf\x6a\xf7\x00\xd9\ +\x1e\xf3\xe9\xdc\xeb\x7e\x93\x23\x02\xfc\x34\x03\xd0\x03\x68\x06\ +\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\ +\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\ +\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\ +\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\ +\x68\x06\xa0\x07\xd0\x0c\x40\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\ +\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\ +\x03\x68\x47\x04\x78\x7c\x39\xf7\xba\xdf\x64\xff\x00\x4b\x5d\xaa\ +\x32\x57\x65\xce\x52\x97\xee\xf7\x25\xa9\xc1\x13\x85\x02\x26\x2c\ +\x67\x7d\xc5\x41\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x02\xda\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x8c\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3b\x6f\x13\x41\x14\x46\xcf\xb5\x13\x42\x13\xba\xfc\x92\x48\ +\xb6\x25\x1a\x5a\xba\x3c\x44\xe4\x90\x80\x44\x05\x05\x2d\x1d\x2d\ +\xff\x00\x24\x5c\x21\x1e\x79\x08\x84\x57\x34\xd4\x74\x80\x5b\x7e\ +\x07\x12\x12\x0d\x42\x72\x3e\x0a\x84\x64\x36\xeb\x38\xde\x9d\x99\ +\x9d\x59\xfb\x96\xb3\x77\x3f\xcd\x39\xda\x5d\x5b\x57\x03\xcb\x5a\ +\xd6\xb2\x16\xb9\xac\xee\x0d\xf8\xae\x4e\xa6\x2d\x93\x9e\x48\xfc\ +\x68\xb7\xed\xc1\xe7\x2d\xfb\x36\x79\x7d\xa5\xae\x8d\x85\xa8\xee\ +\x50\x7d\xa4\x23\xa0\x65\x06\xe3\xb1\x9e\x03\xd7\x27\x7b\x5a\xf5\ +\x6c\xcd\x7f\x75\x87\xea\xc3\x5f\xf8\x7f\x6b\x2d\xe3\x5a\xbe\xaf\ +\x91\x02\x8a\xe0\x81\xb1\xb0\xc7\xf9\xde\xc6\xbd\x02\x17\xc0\xef\ +\x8f\x76\xec\x43\xbe\xbf\x51\x1f\xc1\x19\xf0\xef\x8a\xee\x69\x8c\ +\x80\x32\xf0\xd0\x10\x01\x65\xe1\xa1\x01\x02\xaa\xc0\x43\xe2\x02\ +\xaa\xc2\x43\xc2\x02\x5c\xc0\x43\xa2\x02\x5c\xc1\x43\x82\x02\x5c\ +\xc2\x43\x62\x02\x5c\xc3\x43\x42\x02\x7c\xc0\x43\x22\x02\x7c\xc1\ +\x43\x02\x02\x7c\xc2\x43\xe4\x02\x7c\xc3\x43\xc4\x02\x42\xc0\x43\ +\xa4\x02\x42\xc1\x43\x84\x02\x5c\xc3\x77\x86\xba\x05\x7a\x06\x80\ +\xec\xfe\x68\xd7\xb2\xc9\xeb\x51\x4d\x84\x5c\xc3\x77\x87\xea\x1b\ +\x3a\x35\xd8\x30\xd8\xc0\x34\xc8\xf7\x44\x23\xc0\x07\x7c\x41\xde\ +\xb9\x8a\x42\x40\x20\xf8\xb3\x96\xd9\xc3\x7c\x6f\xed\x02\x42\xc1\ +\x1b\x76\xf7\xcb\xb6\xbd\xcd\xf7\xd7\xfa\x11\x0c\x0a\xbf\x63\x47\ +\x45\xf7\xd4\x26\x20\x06\x78\xa8\x49\x40\x2c\xf0\x50\x83\x80\x98\ +\xe0\x21\xb0\x80\xd8\xe0\x21\xa0\x80\x18\xe1\x21\x90\x80\x50\xf0\ +\x92\xdd\x19\xed\xda\xf1\x3c\x59\xde\x05\xc4\x0c\x0f\x9e\x05\xc4\ +\x0e\x0f\x1e\x05\xa4\x00\x0f\x9e\x04\xa4\x02\x0f\x1e\x04\xa4\x04\ +\x0f\x8e\x05\xa4\x06\x0f\x0e\x05\xa4\x08\x0f\x8e\x04\xa4\x0a\x0f\ +\x0e\x04\x04\x83\x37\x3b\x1c\x6d\xdb\xc9\xbc\x79\xbd\x4c\x7b\x67\ +\xd2\x53\xc0\xfd\x4c\x30\x76\xf8\x6e\xa6\x43\x49\x27\x5e\x66\x82\ +\x29\xc0\x23\xbd\x64\x06\x63\x29\x01\xb1\xc3\xf7\x86\x3a\x28\x80\ +\x77\x33\x13\x4c\x01\x5e\xe8\x55\x3e\xcf\xc9\x4c\x30\x69\xf8\xaa\ +\x33\xc1\xd8\xe1\x3b\xef\x75\xdb\x4c\xaf\xcf\xe5\xcd\xf8\xe9\xbc\ +\x94\x80\xa6\xc2\xc3\x25\xce\x0a\x87\x82\x07\x3b\x18\x6d\xdb\xe9\ +\xbc\x79\x55\xe0\x61\xc6\x13\x10\x12\xfe\xeb\x4e\x78\x78\xb8\x40\ +\x40\xf4\xf0\x99\xf6\x4d\x7a\x93\xcf\x9b\xf7\x35\x2a\x14\xb0\x28\ +\xf0\x00\xed\xfc\x42\x2f\xd3\x1e\xe8\x18\x47\xf0\x53\xf2\x4a\xc3\ +\xf7\x32\xed\xa1\xf3\x79\x65\x3f\xa0\xff\x3d\x01\x9b\x03\xad\xae\ +\x6c\xe8\x3b\xb0\x3e\xb1\x5c\x1a\x7e\x4a\x5e\x69\x78\xd7\x79\x90\ +\xfb\x27\xb8\x7e\x85\x36\xb0\x36\xb1\x54\xe9\x58\x4a\x41\x5e\xa5\ +\xcd\xba\xce\x83\x9c\x80\x4f\xf7\xec\x97\x61\x8f\x80\xdf\xc0\x4f\ +\x64\xfd\x2a\x67\x72\xf2\x79\x66\xb6\x5f\x65\xb3\xae\xf3\xa6\xd6\ +\xcd\x8f\x5a\xdb\x1c\x68\x35\xd6\xbc\x1b\x2f\x74\xd5\x65\xde\xb2\ +\x96\xb5\xc0\xf5\x07\xd6\x41\x4c\x2b\x6c\xde\x0f\x7f\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xee\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa0\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x0d\x00\x20\x00\x03\x31\x82\x7f\x91\x10\x84\x80\x8c\xf2\ +\xb8\x1a\xd8\x65\x63\x40\x6b\x9f\xbb\xf6\xb9\xb2\x61\xca\xf1\x1f\ +\x74\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\ +\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\ +\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\ +\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\ +\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\ +\x00\xad\x03\x74\x80\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\ +\xd0\x3a\x40\x07\x68\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\ +\xad\x03\x74\x80\xd6\x01\x3a\x40\x7b\xd6\x8f\x07\xc5\x02\xeb\xa3\ +\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x0a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbc\x49\x44\x41\x54\x58\x85\xed\ +\x94\x3d\x6b\x14\x61\x14\x85\x9f\xf3\x6e\x84\x85\x80\x68\x23\x83\ +\x9b\x9d\x37\x0b\xfe\x00\x7f\x81\x9d\x28\x12\xb4\xd1\x52\x48\x2b\ +\x41\xf2\x1f\xf4\x0f\x88\x16\x96\x36\x16\x8a\x58\x69\xa1\x58\x5a\ +\x68\xa9\xbd\x98\xcc\xec\x46\xd6\x4a\x63\x12\x30\xc8\xce\xb1\xd8\ +\x0f\x96\x7c\xed\xce\xfa\x91\x66\x1e\x18\xb8\x33\x5c\xce\x39\xdc\ +\x79\xef\x0b\x15\x15\x15\x15\xc7\x8c\x86\xc5\x7a\x96\x7f\x03\x9d\ +\xfa\x3f\xb6\xfe\xbe\x18\xd3\xd3\x00\x61\xf4\x69\xac\xfe\xe7\xf6\ +\x63\x5e\xa3\x62\x2e\xa8\x85\x78\xdf\xef\x30\x98\x02\xe8\xfd\x95\ +\xc7\x14\xd8\x43\xab\x77\x73\x41\xad\xe1\xcb\xe8\x17\x00\x74\xbb\ +\xdd\xf9\xdd\xdd\x5f\xcf\x0d\x97\x06\x49\x0b\x81\xf9\x03\x0c\x12\ +\x0e\x20\x30\xaf\xea\xf5\x13\xd7\x93\x24\xd9\xd9\x37\x01\x80\x24\ +\x49\x76\xb6\xb6\x36\xaf\x0a\x3d\x1d\xa4\x0b\x7b\x43\x96\xb4\x57\ +\x5f\x43\x60\x3d\xd9\xde\xde\xbc\x36\x6e\xce\x61\xe2\xb6\x6b\x59\ +\xb6\xf1\x00\xf9\x96\x6d\x24\x15\x94\x9c\x84\x40\x85\x1d\x24\x81\ +\xf5\x30\xc6\xc6\x6d\x49\xbd\xbd\x7d\x07\x1e\x3c\x49\xbd\x18\x1b\ +\x2b\x48\x77\x25\x01\x04\x95\x98\x84\x40\x86\x20\x09\xc3\x9d\x18\ +\x1b\x2b\x07\x99\x0f\x7a\x8f\x26\xcb\xda\xab\x86\x7b\x00\x06\x0b\ +\x8a\xa3\xfa\x3d\x16\x56\xb0\x1a\x63\xf3\xfe\x84\xb0\x93\xc9\xb2\ +\xce\x4d\xe3\x47\x40\xad\xef\x71\x48\x08\x13\x10\x02\x7a\x82\xe5\ +\x18\x9b\x8f\x27\x69\x4f\x3d\xd6\x2c\xeb\x2c\x19\x3f\x03\xea\x18\ +\xa3\x7d\x21\x86\x07\xf6\xa7\xd0\x8d\x18\x17\x5e\x4e\xa3\x5b\xea\ +\x84\x7f\xce\xf3\x0b\xc1\x7a\x01\x9c\x44\x78\x70\x57\x80\x08\x18\ +\x01\x3f\x82\xbc\x94\xa6\xe9\xdb\x69\x35\x4b\xaf\xd8\xda\x5a\xe7\ +\xbc\x82\x5f\x03\x67\x40\x76\x7f\xd5\x00\x7d\x75\xc1\xe5\x56\x6b\ +\xe1\x43\x19\xbd\x99\x76\xbc\xdd\x6e\x9f\xeb\x15\x7a\x03\x5e\x1c\ +\xc8\xac\xd7\x82\x2f\x36\x9b\xcd\x4f\x65\xb5\x66\xbe\x64\xf2\x3c\ +\x3f\x5b\x58\x1b\x88\x8f\x01\x5f\x49\xd3\xf4\xcb\xac\x5a\x15\x15\ +\x15\x15\xc7\xca\x6f\xbc\xd7\xa4\x72\xc7\xdc\xd0\xf5\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x78\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x01\x00\x20\x0c\xc4\xb0\x0d\x4d\x78\x9a\x1f\x0c\x83\x8c\ +\xe3\x91\x18\x68\xab\x00\x80\xb0\xde\x73\x6e\x72\x60\x25\xe3\x00\ +\xc0\x17\x1e\xbe\x17\x02\x30\xed\xb9\x5b\x96\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x20\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd2\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\xc2\x40\x14\x44\xc1\x35\x45\x38\x43\x72\x4d\xb4\xe0\ +\x88\x8a\xe8\x82\x9a\x2c\x93\xd0\x85\x09\x40\x44\x90\x7a\x90\xd8\ +\x89\x2e\xbb\xfd\x2f\xa9\xaa\x7f\x36\xa8\x8f\x97\xe5\x76\xca\x90\ +\x4b\x92\x64\xcb\x79\x9a\x8e\x57\xb1\xe3\x20\x3e\x4d\x92\xd7\xf1\ +\x63\x92\xf1\x1d\x02\x70\x01\x9e\xc7\x7f\x7a\xef\x4a\x06\xf8\x09\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\x0d\xa0\x07\x68\ +\x0d\xa0\x07\x68\x32\xc0\xfd\xcb\x7b\x57\x2e\xc0\x96\x39\x43\xd6\ +\x0c\x59\xb3\x65\x66\x3b\xaa\xea\xaf\x3d\x00\x08\x2d\x0e\x52\x29\ +\x6c\xf3\x60\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x03\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xb5\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5d\x68\x9b\x55\x18\xc7\x7f\xcf\x79\xfb\x81\x53\xe7\x6c\x07\ +\x8b\xd8\xb2\x59\xaa\x62\x41\x91\x35\xcd\xf4\xc2\xaf\x39\x36\x44\ +\xb6\x4e\xb0\x88\xc8\x9c\x0c\xd7\x74\xad\xe9\xaa\x20\x74\x78\x11\ +\x83\x43\x0b\x82\xc5\x34\xad\x26\x1b\x88\xa2\x57\x03\x8b\xed\x74\ +\x3a\x50\xba\x2b\xe9\xb2\x58\xbc\xb0\x14\x84\x0a\x9a\x36\x1d\xae\ +\x05\xc5\x6d\x36\xcb\x7b\x1e\x2f\x92\x7e\x66\xed\x5a\x9a\x7a\xb3\ +\xff\xe5\xf3\x3e\xe7\xfc\x7f\xcf\xe1\x3d\xe7\x3c\x07\x6e\x76\xc9\ +\x6a\x92\xeb\x9a\xbb\x2b\xad\x9b\xd9\x2f\x2a\xbb\x10\x2a\x11\x2a\ +\x50\x0c\xca\x18\x22\x49\x84\x73\x8e\xda\xde\xc1\xe8\xd1\x5f\x0b\ +\x0a\xe0\x6d\x0a\xfb\x50\x3a\x80\xa7\x56\x38\x6b\x5c\x54\x8f\xc5\ +\xa3\x47\xbf\x5f\x13\x40\x6d\x63\xf4\x0e\x91\xe9\x8f\x80\x17\x73\ +\xa1\x14\x48\xbf\x2a\x67\xd4\x71\x47\xf5\x5f\x93\x2a\xde\x60\xac\ +\xa6\xf1\x58\xb1\xdb\x8c\x61\xb7\x5a\xea\x11\xb6\xe6\xa6\xff\xc6\ +\x71\xdd\x43\x83\x27\xdb\x2e\xae\x1a\x60\x7b\x73\x77\xb5\xc9\xd8\ +\x3e\x44\x1f\x00\x52\x22\x04\x6f\xdd\x32\xf9\xc9\x40\x28\x94\x59\ +\xb6\xa4\x60\xd0\x78\x27\xca\x5f\x00\x39\x0e\x5a\x05\xfc\x6e\x60\ +\xdf\xf9\x68\xeb\xcf\x2b\x06\xf0\x1e\xf9\xa0\x0a\x5b\x34\x08\x6c\ +\x06\xbe\x72\x4a\x78\x79\xb0\xab\xf5\xef\x65\x8d\x17\xa9\x3a\x10\ +\x2e\xdd\x34\x4d\x0f\xc2\x21\xe0\x32\xc2\x63\x17\x3e\x6e\x1d\xba\ +\x21\xc0\x8e\x40\x78\x63\x26\xcd\x8f\x02\x35\x8a\x7e\x98\xf0\x4c\ +\xbd\x41\x28\x64\x57\x63\x3e\x27\x95\x3a\x7f\xb8\x5d\x91\x77\x81\ +\xa4\xaa\xeb\x4b\xc4\x5e\x4f\xcd\xcf\x30\x8b\x87\xb8\xd3\x44\x04\ +\x6a\x80\xfe\xb5\x99\x03\x88\xc6\xa3\xad\x1d\x22\x9c\x04\x2a\x8c\ +\x38\x9f\x83\x2e\x28\x7a\x01\x80\xcf\xdf\xe5\x45\x38\x80\xf0\xa7\ +\x6a\xe9\x81\xb5\x99\xcf\x41\x5c\x9e\x9c\x6c\x01\x46\x14\x76\x7a\ +\xfd\xe1\x67\x96\x04\xb0\xa2\xef\x01\xa8\xea\x3b\x89\x98\xff\xaf\ +\xb5\x9b\x67\x35\x7c\x2a\x94\x16\x78\x2b\x07\xd4\x31\x7f\x15\x66\ +\x01\x6a\x1b\x3b\xef\x42\x79\x1a\x98\xba\x3a\x35\x15\x2d\x94\xf9\ +\x8c\xe2\xd1\x40\x2f\x30\x02\x3c\xe8\xf3\x77\x3d\x94\x07\x20\x98\ +\xbd\x80\xa0\x7c\x3d\x7c\x2a\x94\x2e\x34\x00\x88\xa2\xda\x07\x60\ +\x45\x9f\xcb\x03\x40\xe4\x49\x00\x45\xbe\x2d\xbc\x79\x56\xd6\x98\ +\xef\xb2\x28\xb2\x33\x1f\x00\x2a\x01\x1c\x91\xdf\xd6\x0b\xa0\x84\ +\xcc\x28\x80\x42\x45\x1e\xc0\x4c\xd0\xc8\xb5\x54\xfe\xd0\xc2\xe8\ +\x52\xb1\x33\x33\xf7\xdd\x33\x3f\x62\xde\x39\xf0\xbf\x29\xf8\xf6\ +\x42\x00\x81\x31\x80\xb4\x38\x9e\xf5\xf2\xbc\xdd\x1a\x0f\x80\xc2\ +\xf8\xcc\x19\x33\xb7\x02\x2a\x7f\x00\x18\xcb\x3d\xeb\x05\x60\xae\ +\xb9\x55\x00\x02\xc9\xd9\xd8\xdc\x57\x1d\x00\x10\x91\x3d\xeb\x06\ +\x60\xd8\x0d\xa0\xf0\x43\x1e\x80\x5b\x24\xfd\x00\xaa\xfa\x6c\x6d\ +\x63\xb4\xb8\xf0\xf6\x2a\x56\x65\x1f\x80\xb1\x6e\x6f\x1e\xc0\x50\ +\x24\x30\x2e\x59\xb2\xcd\x30\xfd\x6a\xa1\xed\xbd\x47\x22\x7b\x73\ +\x97\xdc\x2f\xf1\x13\x6d\xb3\xbd\xc1\xc2\x5d\x60\x6d\x3b\x80\x08\ +\xc1\x1d\x81\xf0\xc6\x42\x99\xd7\x34\x04\x4b\xd4\x66\xef\x19\x81\ +\x63\x20\x7a\x5d\x80\xf8\x89\xb6\xb8\xc2\x17\xc0\x16\x37\xcd\x67\ +\x04\x83\x05\xd8\xa6\x2a\x1b\xee\x2c\x0f\xe7\xaa\x1f\x88\x47\x03\ +\xa7\xe7\x7f\xcd\x37\xd0\xd2\x16\xb2\x97\x46\xbd\x77\xa2\xfc\xfd\ +\xb5\x41\xa8\x78\x9b\x22\x6f\x22\xf8\x51\xc6\xdd\x62\x79\x69\x7e\ +\xf5\xb0\x44\x4b\xb6\xbd\xb9\xbb\xda\xb8\xee\x20\x50\x06\x7c\x79\ +\xc5\x71\x0e\x0e\xf7\xb4\xfc\xb3\x1a\xeb\x9a\x86\x60\xc9\x2d\x65\ +\xe5\x11\x81\xc3\xc0\x15\x83\x3c\x71\x3e\x1a\xb8\xb0\x38\x6f\xc9\ +\xa6\xd4\x77\x38\x72\x9f\x35\xb6\x0f\xb8\x5f\x91\x31\x81\xe0\x6d\ +\x9e\x4b\x9f\xae\xa4\x29\xad\xbb\x58\xf6\xbc\x55\x39\x2e\x70\x2f\ +\x90\x54\x35\xf5\x89\xd8\x6b\x3f\x5d\x2f\x7d\xd9\xb6\xfc\xe1\x57\ +\x3a\x37\x15\x95\x9a\x18\x48\x43\x2e\x94\x14\xa1\x1f\xe5\x0c\xd6\ +\x8c\x16\xd9\x74\xea\xaa\x2b\xd6\x29\x29\xf2\xa8\x61\xab\xb1\x76\ +\x0f\x62\xea\x73\xdd\x30\xc0\x59\x71\x9c\x83\xf1\x9e\x96\x89\xa5\ +\x3c\x56\xf4\x30\xf1\xf9\x23\x8f\x5a\xb4\x03\xf4\xf1\x95\xe4\x03\ +\x43\xaa\xb4\x27\x62\xad\x67\x6f\x94\xb8\xaa\xa7\xd9\x23\x4d\x9d\ +\xdb\x32\xd6\xd9\x8f\xb0\x0b\xcd\x3d\xcd\xc0\x01\x92\xd9\xe3\x55\ +\xcf\x59\x35\xbd\x89\x58\x60\x64\x35\xf3\xde\xdc\xfa\x0f\x80\xbd\ +\x5b\x45\x41\xb4\xc0\xa5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x04\xe8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x9a\x49\x44\x41\x54\x58\x85\xc5\ +\x97\xd9\x76\xe2\x46\x10\x86\xbf\x66\x11\x12\x60\x50\x9c\xc4\x9e\ +\xf1\x24\x39\x59\xde\xff\x9d\x72\x31\x9e\x49\x1c\xcf\x18\x6c\x23\ +\x19\x24\xa8\x5c\xd4\xdf\xa8\x91\x71\x72\x97\xd4\x39\x1c\x89\x56\ +\xd7\xf6\xd7\xd6\x0d\x58\x09\x16\xf8\xcf\xc9\x02\x58\x19\xa4\x7c\ +\x09\xac\x21\x58\xf7\x91\x4b\x20\x1a\x96\x25\xef\x93\x44\x4a\x5c\ +\xb3\x64\x6d\x9b\xac\xed\xf4\x7e\x00\x1e\x7a\xf2\x97\xc0\x3a\xf4\ +\x16\x0e\xc0\x05\x30\x00\xaa\x44\x59\x90\x11\x13\xd8\x0d\x21\x8c\ +\x81\x71\xcf\xa5\x16\xac\x81\xac\x95\x11\x51\xb9\x01\x0d\x90\x4b\ +\xfe\x23\x30\x3c\x75\xd8\xf7\x2d\xc0\x7e\x11\x34\x63\xb0\x99\xd6\ +\x33\xb0\xf7\xf0\x50\x82\xe5\x60\x13\xb0\x82\x57\x64\x85\xbe\x4d\ +\xb5\xf7\xca\x79\xc1\xd7\x2c\x93\xec\x5f\xc1\x2e\xfa\x10\x02\xf6\ +\x01\xf8\x24\x24\x0c\x78\x01\x0a\xd8\xbd\x87\xec\xa3\xbc\x00\x58\ +\xc8\x8b\x73\x94\x7e\x9b\xc0\xee\x06\xb2\x5b\x21\x92\x4b\xdf\x1a\ +\xb8\x81\x70\x0b\x30\x92\xf2\x80\xc3\x3e\x96\xf2\x1b\xe0\xde\x19\ +\xb2\xfb\x44\xf9\x04\x0f\x91\x71\x1a\xf7\xe8\xcc\x4c\xca\xf4\xcb\ +\xbe\xc2\xa6\x80\xd9\x18\x78\x07\x7c\x94\x8e\x41\x0f\x01\xfb\x4e\ +\xff\x2b\x08\x15\xd8\xb5\xbe\xfd\x09\xcc\x1d\x8d\xd5\x0c\x4a\x5c\ +\x70\xa8\xcf\x03\x60\x73\xa0\xc5\xf3\xa5\xd2\xf3\x80\x27\xf4\x0e\ +\x78\xc2\xe3\xff\x0d\xb0\x82\xb0\x19\x25\xdc\x63\x29\xcf\xe5\xdd\ +\x1a\xb8\x92\xc5\x39\x94\x4f\x82\x71\x02\x66\x1d\x0f\x24\x08\xe5\ +\xc0\xb3\x94\x95\x42\x38\x03\xee\xf0\xf0\x64\x10\x9e\x12\x07\x3b\ +\x28\xdc\x52\x9b\xc0\xcb\xb5\x18\x83\xa0\x5c\x48\x68\xa4\x39\x1e\ +\x86\xb9\xf8\x07\xfa\x1f\xd7\x22\x6d\xc4\xbb\x93\xac\x00\xdb\xf7\ +\x4a\xcc\x63\xee\xc5\x10\xbc\x73\x41\x15\x30\xfd\x8c\xc7\xb2\x96\ +\xf5\x23\xc1\x56\x43\x75\x09\xd3\xb5\x23\x75\x8e\x6c\x21\x99\x35\ +\x30\x95\x03\x53\xba\xd2\x1b\x49\xf6\x1c\x0f\xc1\x97\x14\x81\x09\ +\xb4\x2f\x49\x6d\x16\x8a\xb5\xe1\x96\x5d\xc3\x74\xe5\x48\xbd\x49\ +\xb1\xce\xbf\x17\x8f\x09\x89\x58\xb6\x2d\x3c\x36\x78\xe8\xfa\x21\ +\x68\x4a\x58\x3c\x74\xc6\x30\x54\x3e\xe4\x78\xd2\xfc\x25\xc1\x85\ +\xfa\x41\xee\x49\x67\xb3\xee\x3f\x05\x9e\x37\x5f\x61\x73\x29\xde\ +\x3c\x91\x09\x2c\x9e\x49\x42\x15\x0d\xc8\xbc\x8b\x91\x0b\xc6\x52\ +\x1e\xb4\x62\x5c\xe1\x89\xf6\x20\x48\x73\x3d\x83\xa0\x9d\xba\x0c\ +\xa6\xae\x9c\x06\x66\x0f\xda\xd7\xe2\x3d\xe5\x12\xef\x31\x43\x68\ +\x4c\xfb\x63\x1f\x20\x40\x50\xd7\x0a\x8f\xde\xb9\x82\x32\xdb\x0c\ +\x82\xfa\xbb\x35\x12\x36\x06\xee\x7b\xbd\xfd\xca\x8d\x8e\x7c\xb4\ +\x60\x7b\x7f\x86\x1d\xd8\x33\x5e\x86\x03\xba\x24\x3f\xa9\x82\x61\ +\x52\xdf\x49\x93\xa9\xd3\x3d\xda\xc7\xbd\x7b\x63\xe9\x30\xbb\x4b\ +\x1c\x8a\x94\x4e\x59\xc9\x0c\x55\xe7\x6c\xc7\x30\x82\xf1\x21\xf1\ +\x86\xe4\xbd\x4d\x84\x8c\x80\xc6\x3d\xb7\x35\xea\x4c\x78\x46\x5b\ +\xd2\x1f\x52\x4a\x1d\x78\x35\x3d\x07\xc9\x73\x7f\x86\xb9\x4f\x87\ +\x9e\xc0\x3e\x9d\x6b\xcf\x96\xbc\xbf\xda\x17\x85\xed\xa0\x51\x57\ +\x0b\xd6\x6d\x0e\x06\xf5\xb0\x67\xc0\x30\x81\x7d\xa5\xdf\x32\x99\ +\x27\x7d\x83\x4f\x46\x6e\xdf\x98\x94\xa1\x55\x29\xf5\xac\x2d\xfa\ +\x75\xdf\xe2\x09\xa7\x79\x1e\x62\xdb\xbe\xa6\x3b\x03\x44\x0a\xaf\ +\xdf\xad\x00\x3b\xee\x8b\x39\x60\xca\x70\x53\x19\xce\x34\x58\xc0\ +\x4b\xb3\x94\xe2\x02\x6f\xb9\x6a\x36\x96\x42\xdc\x00\xdf\x4a\xb8\ +\x49\xb6\x0e\x21\x16\x3b\x20\x32\x76\x1f\xf9\xa2\x01\x3b\x08\x43\ +\x95\xdb\xd6\x0f\x24\x34\xfe\xdf\xc0\x33\x7f\x23\x21\x9f\xff\x61\ +\x1a\xee\x38\x9e\x76\xd6\x25\x2c\xef\x3a\x07\x79\xc0\x4b\x38\xee\ +\xd9\xc1\x49\x08\xc6\x75\xe2\xf5\x16\x35\x0a\x51\x05\x2f\x3f\xc9\ +\xf3\x73\x99\x7e\xb4\x40\x1e\x7e\x80\xe5\x53\xb7\xbc\x2a\xa4\x1c\ +\x37\x6c\xbc\x89\x5f\x06\x09\xe3\x06\xea\xb2\x63\xa2\xf6\x86\x14\ +\x0f\x1a\xf9\x2d\x3e\xdd\xfa\x67\xc1\x94\x22\xd4\x7f\xe0\xed\x36\ +\xf8\xb3\x4c\x86\x57\x36\x93\x31\x27\x21\xd8\xfb\xe6\xe2\x19\xec\ +\x86\x6e\xe0\x14\xf8\x49\xe6\x77\x3c\x9e\x7b\xa0\x74\xa4\xea\x41\ +\x97\xa0\xf5\x50\x02\xd5\x21\x8f\x7b\x7f\xc6\xbb\x9f\x8e\x77\x2c\ +\xa1\xb8\x95\xcc\x6d\x6a\x00\x6e\x40\x78\x06\x1b\xd0\xc5\x7c\x24\ +\x6f\x0e\x10\x36\x60\x2d\xf0\x0c\xe1\xe5\x3c\x00\x36\x77\x19\xa0\ +\x83\xeb\x67\x7c\x96\x6c\x24\x73\xe5\xf9\xd3\x45\x31\x0d\x41\xe3\ +\x93\x2d\x3c\x42\x7d\xe1\x9e\xb2\x96\xf5\x5b\xe5\xc7\x71\x8c\xbe\ +\x4d\x36\x56\xe8\x1a\x3c\xd1\xd6\xc0\x25\x54\x33\x47\xc3\x66\x5a\ +\x3f\x09\xc1\x57\xe0\x07\xdf\x6c\x4b\x60\x06\x2f\x41\x93\x74\x42\ +\x67\xb2\x0e\x97\x55\x05\x85\xd1\x75\xcf\xd8\xac\x0a\x3c\xdb\x77\ +\x38\xf3\xc2\x8d\xaf\xa7\x30\x9d\xe3\x13\x76\xe3\x8e\x87\x4d\x62\ +\x40\x30\xb0\x03\x5e\xeb\x01\xf8\x04\x45\x34\x86\x0e\x56\xf0\x30\ +\x4c\x75\xf4\x36\x21\x18\xe2\x1c\x59\x38\x82\xc7\xbd\x17\x6e\xcc\ +\xf4\x8b\x64\xc5\xd9\x72\xee\x50\x63\x17\xba\x34\xf4\x2f\x26\x0b\ +\xa8\x7e\xec\x2e\x23\xff\x76\x31\x01\xe7\xad\x3e\x74\x65\x7d\x72\ +\x31\xf9\xed\xcc\xc5\xe4\xd8\xdb\xf7\x82\x6d\x20\x2b\x33\x1c\xfe\ +\x81\x7f\x6f\x32\x79\x30\x84\x71\x7a\xf7\xcb\x75\x30\x6e\x7d\xd4\ +\x8e\x6a\xbc\x67\xec\xc5\xdb\xd0\x0d\xa6\x35\xc9\xd5\xec\x8d\xcb\ +\x69\xf4\xe2\x98\x70\xc3\xe4\x7d\xa2\xf7\x09\x6c\x35\x3b\x26\x95\ +\x94\x18\xdd\xe5\x54\x06\xb9\xb0\x18\xf3\x9e\xc3\x6b\xf8\x9f\xaf\ +\xe7\x7f\x03\x88\x7c\xd3\x3b\xed\x32\x4f\xdf\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x06\x7b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\x2d\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xc9\x73\x5c\x57\x15\xc6\x7f\xdf\xb5\x49\x39\x09\x91\x83\x33\ +\x40\x15\x2b\xb6\x78\x48\x9c\x48\x3d\x24\x14\xc4\x8a\x63\xc9\x93\ +\x2c\x75\xab\xf2\x87\xb0\x0a\x0b\x58\x50\x5e\xb0\xc9\x12\xfe\x88\ +\x54\xab\x25\x92\x38\x65\x6b\x34\x09\xa0\x1e\x0c\x45\x18\x56\x29\ +\x2a\x95\x62\x45\x26\xb0\x6c\x63\x29\x46\xf7\xb0\xe8\x6e\xe8\x74\ +\xb7\xf4\xee\xeb\x7e\x4f\xea\x14\xfa\x96\xf7\x9e\x3e\xf7\x7c\xbf\ +\x3a\xe7\xf5\xeb\xa7\x27\x38\xd0\x81\x0e\xf4\xff\x2c\xf5\x5a\x3c\ +\x75\xc3\x1e\x7d\xf8\x2e\x3f\x94\xec\xb2\xc1\x11\xcc\xd6\xed\x6b\ +\xee\x67\xb5\x29\x7d\xb8\xd7\x05\xf6\xa3\xcc\x9b\xf6\x1d\x3d\xf0\ +\xaf\x21\xe5\x05\x9b\x5e\xba\xf6\xc8\x03\x5e\xbf\xf9\xaa\xee\x76\ +\xc6\x76\x01\x78\xf1\x97\xf6\xd8\x03\x6f\xbf\x92\x71\xba\x63\xeb\ +\xb6\x9c\x26\x2a\xd3\xaa\xa6\x56\x79\x02\x1a\x9b\xb3\x31\x27\x5b\ +\x02\x8e\x76\x6c\xbd\xcf\x11\x7d\xbf\x7a\x41\x1b\xed\x8b\xae\x33\ +\xc1\xf6\xb6\x7f\xad\x87\x79\x80\xa3\xe6\x6d\x31\xb7\x60\xd9\x04\ +\xeb\x4d\x54\xbb\x98\x07\x78\x86\x4d\xff\xa3\xce\xc5\x2e\x00\xa0\ +\xa9\x5d\xce\x18\x19\x56\x08\x11\xe6\x9b\xd2\x95\xce\x95\x2e\x00\ +\x1e\x1e\x8e\x38\x6b\xc4\xbc\x2d\xe6\xe7\x2d\x13\xb7\xc8\xb4\x94\ +\x29\xd9\x68\xb4\x79\xc0\x38\xd2\xb9\xd4\x05\x40\xd8\x6f\x02\xce\ +\x1c\xf1\x66\x4b\xc3\x00\x21\x53\xb2\x51\x39\x5b\x26\xca\x3c\x80\ +\xba\xbd\x75\x8f\x80\x77\x57\x81\xdb\x01\x67\xef\x3b\x84\x58\xe6\ +\x61\x03\xef\x7e\xda\xb9\xd8\x05\xa0\x3a\xab\x0f\x9c\x74\x8e\x70\ +\x08\xfb\x32\x0e\x4d\xf3\xd1\x6d\xdf\xd0\x06\xa6\x89\xea\xac\x3e\ +\xe8\xdc\xe8\x79\x1f\x00\x90\x9f\xb7\x8c\x37\x5b\x02\x46\x02\x0e\ +\xb8\xed\x4d\xaf\xd4\x8b\xaa\x07\xc4\x0e\xac\xec\xbc\x3d\x8f\xd9\ +\x32\xf0\x78\x40\xf8\x1d\x4c\xe7\xaa\x45\x55\x7a\x6d\xee\x08\x00\ +\x86\x13\x42\x92\xe6\x21\x02\x00\x0c\x17\x84\xa4\xcd\x43\x00\x00\ +\x80\xdc\x82\x65\xcd\xdb\x22\x81\x10\xcc\xeb\x6c\x6d\x56\xb7\x42\ +\x72\x87\x2a\x37\x67\xcf\x99\x6c\x19\xf8\x46\x40\xf8\x1d\x43\x13\ +\xb5\x82\xd6\xa3\x02\x83\x00\xc0\xfe\x42\x48\xcb\x3c\xf4\xbc\x13\ +\xec\xad\xca\xb4\xaa\x98\x26\x80\x8d\xc8\x60\x38\x2a\x67\xcb\x99\ +\x92\x8d\x86\xe6\xdf\x49\x71\xcd\x3b\xa7\xc9\x50\xf3\x10\xa3\x03\ +\x5a\xca\xce\x59\x0e\xd9\x22\xf0\x58\x40\xf8\x3f\xcd\xeb\x95\x7e\ +\x3b\x21\xa6\xf9\xbb\xce\x69\x62\x7d\x5a\xbf\x8d\x73\x46\x6c\x00\ +\x10\x1f\x02\xd2\xd9\xea\x8c\x7e\x17\xe7\x8c\xbd\x30\x0f\x31\x46\ +\xa0\x5d\xd5\xa2\x2a\x98\xce\x01\x77\x02\xc2\x1f\xc7\x6c\x39\x3b\ +\x6f\xcf\x87\xe6\xcf\x97\xec\xf4\x5e\x98\x87\x3e\x01\x40\x03\x82\ +\xa1\x09\x12\x86\x90\x2f\xd9\x69\xef\x6c\x85\x40\xf3\x32\x4d\xf6\ +\x6b\x1e\xfa\x1c\x81\x76\x65\xca\x96\x17\x76\x83\x04\xc6\xa1\x1f\ +\xf3\x95\xa2\x42\x7e\xbc\xed\xa8\xbe\x3b\xa0\xa5\x5a\x41\xeb\xce\ +\x69\x92\xf0\x4e\x58\xca\xcd\xd9\x73\x9d\x1b\x4d\xf3\xc1\x6d\x0f\ +\x3a\x3f\xa8\x79\x48\xa0\x03\x5a\xca\x2f\xd8\x0b\xde\xdb\x0d\xe0\ +\xeb\x01\xe1\xff\x90\xe9\x6c\xa5\xa8\xdf\x03\x8c\xcd\xdb\xb3\xce\ +\x6c\x05\x38\x16\xf9\x49\xe3\x1e\xd2\x64\xb5\xa0\x5f\x0f\x56\x71\ +\x43\x89\x01\x80\xfe\x20\x6c\x3b\xfc\x7e\x99\x87\x84\x01\x40\x3c\ +\x08\x26\x36\x64\x40\xc8\xdd\x65\x0a\xe6\x21\x05\x00\x00\xb9\x39\ +\x7b\xd1\x64\xd7\x09\xeb\x84\x68\x19\xf7\xec\x90\xce\xd7\xa6\xf5\ +\x5e\x22\xf9\xda\x94\x0a\x00\x48\x10\x42\x8a\xe6\x21\x81\x6f\x81\ +\x9d\xd4\xb8\x42\xeb\x3c\xd0\xf5\xc7\x88\x60\x19\xf7\x3c\xba\x90\ +\x96\x79\x48\xb1\x03\x5a\xca\x96\xed\x7b\x98\x5d\x47\x3c\x1a\xeb\ +\x83\x4d\xf3\xf5\xa2\xde\x4d\xa9\x34\x60\x0f\x00\xc0\x7f\x21\x2c\ +\xa2\xc8\x47\xee\x0d\x19\x9b\x1e\x4d\xa4\x6d\x1e\x52\x1c\x81\x2f\ +\xc9\xb3\x81\xf8\x22\x38\xde\xe9\x0b\x5c\xd0\xcf\xee\x81\x95\x3a\ +\x80\x6c\xc9\x4e\xe1\x6c\x95\xb0\xa7\xb7\x0d\x99\x8d\x38\xb3\x95\ +\xb1\x79\x7b\x36\xbd\xca\x1a\x4a\x75\x04\xda\xcc\x3f\xd1\x67\x8a\ +\xcf\xbd\xf4\x72\x7d\x46\x7f\x48\xb2\xae\x76\xa5\x06\xa0\x69\x7e\ +\x05\x78\x72\xc0\x54\x9f\x1b\x1a\xaf\x15\xf4\x7e\x12\x75\x75\x2a\ +\x95\x11\xc8\x2f\xd8\xc9\x84\xcc\x03\x1c\x13\xb6\x9a\x29\xdb\x33\ +\x09\xe4\xea\x52\xe2\x00\xf2\x0b\x76\xd2\x7b\x5b\x25\xc0\xbc\xc1\ +\x96\x60\x2b\x20\xed\x31\x61\x2b\x69\x40\x48\x14\x40\x1c\xf3\xc0\ +\x7d\x27\x4d\x6e\x37\x9e\x2c\xfd\x2b\x20\xfe\x89\x34\x20\x24\x06\ +\x60\xb4\x6c\x27\xe2\x98\xc7\x74\xb1\x32\xa3\x9b\xf5\xa2\xde\x75\ +\xe8\x02\x31\x20\x64\x4b\x76\x6a\xb0\x6a\xff\xa7\x44\x2e\x82\xa3\ +\x65\x3b\x71\x08\x5b\x23\x86\xf9\x6a\x51\x6b\xed\x8b\xf9\xb2\xfd\ +\xc0\x63\xef\x00\x8f\x04\xe4\xf8\x0c\xaf\xf1\xea\xac\xfe\xd8\x4f\ +\xbd\xed\x1a\x18\x40\x5c\xf3\x86\x2e\xd5\x0a\x5a\xed\xb5\x99\x9b\ +\xb7\x97\xcc\xec\x1a\x7b\x08\x61\xa0\x11\x18\x2d\xdb\x09\x47\x78\ +\xdb\xef\x66\x1e\xa0\x32\xa3\x9b\x92\x2e\x12\x38\x0e\xb8\xc1\xc7\ +\xa1\xef\x0e\x68\x99\x17\x3c\x15\x10\x7e\xdf\x4b\x97\xeb\x33\x5a\ +\x09\xc9\xdd\xec\x84\x77\x88\x7e\x5d\x07\xe0\x53\xe7\x34\xbe\x3e\ +\xad\x3f\x85\xe4\xee\x54\x5f\x00\xc6\x4a\x76\x5c\xce\xd6\x02\xcd\ +\x6f\x7a\xe9\x52\xa8\xf9\x96\xf6\x0a\x42\xec\x11\xd8\x0b\xf3\xd0\ +\x18\x07\x4c\x17\x81\xfb\x01\xe1\x4f\x7a\x6f\xab\xf9\x05\x3b\x19\ +\xf7\x9c\x58\x1d\x30\x56\xb2\xe3\xae\x71\x6f\xff\x74\x40\x78\xdf\ +\xe6\xdb\x95\x9d\xb3\x33\xc8\xae\x11\xd8\x09\xdb\xe8\xcc\xad\x82\ +\xfe\x1c\x9a\x3f\xb8\x03\xe2\x9a\x97\x0f\x9f\xf9\xdd\x54\x2d\x6a\ +\xcd\xd0\x25\x02\x3b\xe1\x10\xb6\x36\x5a\xb6\x13\xa1\xf9\x83\x3a\ +\x20\xbb\x60\xdf\xc5\xdb\x1a\x31\xcc\x57\x66\xb5\x1c\x5a\x44\x88\ +\x32\x65\x1b\x17\xf6\x36\x09\x77\x42\x24\x80\xb8\xe6\x41\x53\xd5\ +\x82\x96\x02\x62\x63\x6b\x6c\xde\x5e\x76\x66\x6f\x11\x00\xc1\xe0\ +\x13\x8f\xc6\xa3\x20\xec\x0a\x60\x98\xcc\xb7\xd4\x84\xf0\x36\x74\ +\xbf\xf5\xd9\xa9\x10\x08\x3b\x5e\x03\x9a\xe6\x83\x67\x1e\xe9\x4a\ +\xda\xe6\x01\xea\x33\x5a\xf1\xd2\x25\x60\x33\x2a\x56\xf0\x94\xc3\ +\x56\xc7\x4a\x76\x7c\x97\x98\x6e\xb5\x99\xff\x66\xd4\x21\x06\x5b\ +\x92\xa6\xaa\x33\x5a\x8c\x8a\x4d\x52\x71\x3b\xc1\xbc\xce\xd4\x67\ +\xf5\x97\xce\xbd\x2e\x00\xf9\x37\xec\xdb\xfe\xb0\xdd\x02\xbe\x15\ +\x90\x78\x5f\xcc\xb7\x94\x2b\xd9\x59\x73\xf6\x16\x01\x10\x80\x8f\ +\xbd\xd3\x68\x7d\x5a\x7f\x6b\x5f\xec\x7e\x5b\xfc\xb0\xff\x31\x5f\ +\x01\xf3\x00\x95\x59\x2d\xcb\xeb\x32\x01\xe3\x00\x3c\x2d\xef\x7f\ +\xd2\xb9\xd8\xeb\xff\x05\x5e\x8a\xca\x64\xb0\x85\xd7\x95\xfd\x34\ +\xdf\x52\xe3\xeb\x56\x53\x04\x41\xd0\x99\xce\x95\x5e\x17\xc1\xed\ +\xdd\x52\xb4\xcc\xd7\x66\x75\x23\xb4\xc8\xb4\xd5\xb8\xf8\x46\x43\ +\x50\x0f\x6f\xdd\x00\x1a\x6f\x7f\xf5\x94\xc1\xd6\x21\x34\x3d\x4c\ +\xe6\x5b\xaa\x16\xb4\x84\x74\x85\x5d\x21\xd8\xf5\xce\x95\x2e\x00\ +\x66\xee\xaa\xc1\x5f\xbb\xd6\x9b\xe6\xd7\x0b\xea\x4a\x32\x2c\xaa\ +\xce\x68\x71\x47\x08\xc6\x87\x0f\xfd\xdb\x5d\xed\x5c\xee\x02\x50\ +\x2b\xe8\xb3\xed\xc3\xca\x81\xfd\x1c\xf8\x08\xf8\x18\x78\xd3\x99\ +\x5e\x18\x66\xf3\x2d\x55\x67\xb4\xe8\xa5\x3c\xc6\x02\xf0\x77\xe0\ +\x23\x64\xbf\x78\x68\x5b\xd9\xf7\x5e\xd5\x27\xfb\x5d\xdf\x81\x0e\ +\x74\xa0\xe1\xd2\x7f\x00\x72\xd2\x49\x30\x2e\xe9\xad\x3a\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x58\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x0a\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4b\x88\x5c\x45\x18\x85\xcf\xa9\x19\x34\x41\xa2\xa0\x21\x1b\ +\x09\xee\x7c\xac\x04\x13\x7b\xda\xb8\x30\x06\x13\x99\x80\x26\xdd\ +\x1d\x06\x17\x82\xe0\x83\x08\xae\x14\x09\x24\x88\x1a\x4c\x40\x11\ +\x5c\x28\xf8\x42\xd1\x85\x28\x8a\xdd\xf3\x40\x26\x32\x41\x1c\x10\ +\x64\x7a\x9a\x11\xb2\x10\x41\x5c\x04\x11\x41\x83\x09\x11\x25\x0d\ +\xe9\x5b\xc7\x45\xcf\xa8\xdc\x2a\x35\x9d\x54\x55\x17\xd8\xdf\xf2\ +\x2e\xea\xfc\xff\xb9\x55\x7f\xd5\x7f\x1f\xc0\x88\x11\x23\xfe\xcf\ +\x30\xd4\x40\x95\xa6\x9e\x35\xb4\x4f\x89\x94\x2c\x8f\x2c\x37\x78\ +\x38\xd4\xd8\x31\x09\x66\xc0\x44\xb3\x28\x40\x9a\xd5\x51\x45\x70\ +\xc7\x52\x8d\x8b\xa1\xc6\x8f\x85\x09\x36\xd2\x5a\xf2\x00\x20\x50\ +\xd2\xdc\xc4\xb4\xb6\x04\x1b\x3f\x12\xc1\x0c\x10\x60\x4b\x97\x36\ +\x40\xfa\x74\xeb\xac\x6e\x08\xa5\x11\x83\x60\x06\x10\x90\xe7\xf2\ +\xc6\xb1\x42\xc7\x6f\x9d\xd1\xe6\x50\x3a\xa1\x09\xb7\x04\xfe\x99\ +\xcd\xc6\x6a\x61\xcb\x9c\x36\x26\xd0\x1a\x98\x14\x06\x00\xc0\x8d\ +\xe3\x85\x8e\xdd\x3e\xab\x0d\x89\xf4\x2e\x98\x68\x06\xa8\xbc\x24\ +\x84\xad\xbd\x42\x33\x93\xf3\xba\x3c\x96\xe6\xc5\x10\xcd\x00\x02\ +\x16\x74\xea\xc2\x8e\xd3\x5d\xbd\xbf\xfd\x73\x8d\xc7\xd2\x1d\x94\ +\xb8\x4b\x40\xb0\x70\x8b\x63\xbd\x7b\xda\xbe\x0e\x29\xd8\x19\xe4\ +\x52\x48\x51\x03\x9c\x99\x20\xf2\xa1\x6a\xcb\x3e\x9f\x40\xfb\x3f\ +\x49\x53\x04\x05\xab\x72\x49\x20\x0f\x54\xa6\x75\x20\x89\xfe\xbf\ +\x90\x6a\x17\x00\x69\x0a\xe7\x9a\xf4\x42\xb5\xa9\x87\x53\xc5\xe0\ +\x23\x99\x01\x90\x7c\xa7\x45\x88\x7a\xa3\xda\x52\x3d\x59\x1c\x25\ +\xd2\x19\x80\xfe\x69\xd1\x63\x82\x11\xf4\x41\xf5\x63\xdd\x95\x32\ +\x96\x3f\xc5\x53\x0b\x12\xd0\xea\xee\xf0\x77\x2e\x13\x35\x73\xdb\ +\xb4\x2a\xa9\xe3\x49\x6e\x00\x00\x80\x9e\x99\x40\x5c\x61\xa5\xf9\ +\x6a\x4b\x37\xa5\x0c\x65\x38\x06\x60\xad\x79\x62\x79\x26\x5c\x23\ +\xe8\xf8\xb6\xa6\xae\x4b\x15\xc7\xd0\x0c\xe8\x23\x9f\x09\xd7\x16\ +\xd4\xc2\xb6\x96\x36\xa5\x88\x60\xc8\x06\x00\x7d\x13\x54\x3e\x2d\ +\x5e\x5f\x40\xc7\x26\xe6\x75\x65\x6c\xf5\x0c\x0c\x00\x00\x5a\xa7\ +\x79\x02\x6e\x51\x57\x73\xdb\xdf\xd1\xba\x98\xca\x99\x18\xb0\xda\ +\x3c\x95\x4c\x20\x70\xc7\xb9\xab\xf4\x61\xcc\xe6\x29\x1b\x03\x56\ +\xf1\x35\x4f\xf7\x76\xcf\xd8\xb7\xf0\x8c\xa2\xc4\x9a\x9b\x01\x80\ +\xaf\x79\x02\x1f\xa8\xdc\x6c\x5f\x8c\xd1\x41\xe6\x68\x40\xbf\x8d\ +\x2e\xd5\x45\x82\x4f\x54\x5a\x38\x18\x5a\x2a\x4f\x03\x00\x80\x74\ +\x9b\x27\xea\x68\xa5\xa9\xfd\x21\x65\xf2\x35\x00\x80\x04\x5b\xae\ +\x08\xa4\x5e\x9b\x68\x6a\x5f\x28\x8d\xac\x0d\xa0\xef\xc8\x0c\x10\ +\xd4\x2b\xa1\x34\xb2\x36\x00\x00\xe8\x2f\x7b\xc1\xb6\xc5\xbc\x0d\ +\xe8\x67\xef\xc4\x28\xe8\xed\x50\x12\xd9\x3c\x9d\xf5\x22\x8d\xb9\ +\xd7\xf8\xd8\x72\xc3\xbc\x1a\x4a\x22\xe3\x19\xe0\x4d\xfe\xe9\x76\ +\x83\xc1\x92\x07\x72\x34\x80\x80\x08\xe3\xbe\xb9\xd7\xcb\xed\x3a\ +\x8e\x84\x96\xcb\xce\x00\x09\x86\x2a\x67\xaf\xf7\xda\x27\xcc\xe3\ +\x20\x7d\x2f\x60\x2f\x89\xbc\x0c\x20\x0c\x4b\xb7\x9e\xc0\x27\xbd\ +\x53\xe6\x41\x1c\x76\x9e\x1b\x04\x21\x27\x03\x0c\x9c\x3b\x8f\x2f\ +\xd8\xe3\xd4\xca\x7e\x9e\x8f\x25\x9a\xc9\x2e\x20\xe3\xd9\xf1\x4f\ +\xf4\x7a\xbc\x67\x65\x8a\xe7\x62\x2a\x0f\xdd\x00\x81\x2c\x4f\x7b\ +\x08\xdf\x61\x9c\x77\xaf\xd4\x79\x36\xb6\xfe\x50\x97\x40\x3f\x79\ +\xa7\xcf\xff\x91\x86\x3b\xdb\x7b\xf8\x53\x8a\x18\x86\x67\x80\xe0\ +\x4b\xfe\x8c\xb5\xdc\xb5\x54\xe3\xc9\x54\x61\x0c\xc5\x00\x09\x04\ +\x4b\xda\xc2\xef\x10\x77\x77\xf6\xf1\xeb\x94\xb1\x24\xaf\x01\x02\ +\xc8\x72\xf2\xc0\x79\x18\xd6\xdb\x35\x2e\xa5\x8e\x27\xe9\x0c\x90\ +\x40\xca\xd1\x14\xc9\xfb\xdb\x35\x2e\xa4\x8c\x65\x8d\x74\x33\x80\ +\x84\x67\xcd\x03\xe4\xa3\x4b\x35\x7e\x94\x2c\x8e\x12\xc9\x66\x80\ +\x64\xdd\xe6\x86\x3c\xd4\xae\xf1\xcd\x54\x31\xf8\x48\x63\x00\x61\ +\xe8\x6c\xf5\x7a\xa9\xbd\x17\x43\xff\x4c\x26\x85\x01\xee\x11\x57\ +\x7a\x77\xb9\x66\x9e\x8c\xd1\xdc\x0c\x4a\x5c\x03\xfa\xd5\xbe\x7c\ +\xc4\x9d\x5d\x7f\xb5\x79\x24\x87\xe4\x81\xb8\x1f\x4a\xfa\x9a\x9b\ +\xc5\xf5\x67\x79\xdf\xe2\x9d\xec\xc5\xd2\x1d\x94\x68\xbb\x80\x73\ +\xbe\x07\xbe\xc2\x3a\xee\x59\xac\xb3\x1b\x4b\xf3\x62\x48\xb5\x0b\ +\x7c\x3b\x06\x4e\xb6\x77\xf3\xd7\x44\x7a\x17\x4c\x0a\x03\x7e\xe8\ +\xf5\xb8\xf3\xcb\x3a\x7f\x4e\xa0\x35\x30\x21\x7f\x98\xf0\x3d\xc1\ +\xff\x85\xe0\xae\x95\x29\x7e\x1f\x4a\x27\x34\xc1\x6a\x00\x5d\x33\ +\x7f\xb3\xe2\x64\xa7\xc1\x6f\x42\x69\xc4\x20\xe4\x12\xf8\xeb\x99\ +\x1d\x21\x4b\xee\xed\x34\xd8\x09\x38\x7e\x14\x42\xfe\x34\x75\x14\ +\x40\x01\xa0\x80\xf8\x5c\xa7\xc6\xcf\x82\x8d\x3d\x62\xc4\x88\x11\ +\x91\xf8\x03\x6e\xfe\x4e\x7e\xe0\xc6\x25\x53\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcd\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7f\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x51\x0d\x80\x30\x10\x05\xc1\x03\x6f\x55\x80\x05\xd4\x62\xaa\ +\xc8\x58\x12\x66\x0c\xdc\xcb\xa6\x7f\x9d\x09\xad\xeb\xde\xeb\xba\ +\x77\xb9\xe1\x2c\x8f\x7f\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xef\ +\x03\x1c\xe5\xf1\xfa\x6b\x7c\xa6\x7e\x01\x7b\x9e\xf4\x3e\x00\x00\ +\x00\x00\x00\x00\x00\xfc\xc3\x0b\xb7\x26\x07\xfa\x17\x1e\x2a\x64\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x8f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x41\x49\x44\x41\x54\x58\x85\xed\ +\x97\x31\x6b\x14\x51\x14\x85\xbf\x33\x59\xab\x80\x85\x62\x20\x76\ +\xf9\x03\x62\xb5\xbb\xa2\x88\x82\x5d\x42\x8a\x24\xf8\x07\x02\x6a\ +\x95\xca\x24\x65\x08\xa9\x56\xb0\x30\x60\x50\x41\x41\xd2\x04\xc1\ +\x2d\x82\x0b\x76\x01\x41\xb2\xbb\x95\xf8\x07\x92\x3a\x41\xc1\x22\ +\x95\xc9\x1c\x8b\x9d\xb7\xac\x9b\xd9\xec\x4e\x76\xb4\xd1\xaf\x7a\ +\xdc\x77\x67\xee\x99\x73\xdf\xcc\xbc\x07\xff\x3a\xea\x0e\x94\xdf\ +\xfb\x66\x8c\x97\x11\x65\xc1\x95\x3c\x8a\x18\x0e\x31\xf5\x08\x55\ +\xea\xb3\xfa\xdc\x53\x40\xa9\xea\xc7\xe0\x27\x69\xc2\x72\x22\xc6\ +\x5a\x6a\xcc\xea\xe9\x29\x01\xa5\xaa\x6f\x81\x3f\x01\x3f\xb0\x16\ +\xa2\x13\x6a\xbb\xf7\xf5\x3d\x8f\xaa\x37\xde\xf9\x52\x3c\xc2\x24\ +\xf2\x3a\x70\x51\xd6\xed\xe0\x44\x21\x24\xd9\x5e\x92\x10\xd6\x42\ +\x63\x56\x9b\x79\x14\x0e\x24\x0f\xb2\x59\xac\x5a\xc2\x6f\x63\xbc\ +\x0c\x4c\x03\x44\xed\x2c\x51\x06\x88\x4e\xa8\xe5\x59\xbc\x8b\x1a\ +\x80\x44\x29\x04\xda\x02\xc2\x82\xcb\xcb\xf6\x34\x9a\x33\xfa\x96\ +\x0c\xc7\x42\xac\xd0\x23\xf7\xdc\x14\xab\x9e\x12\x7e\x05\x60\xf4\ +\xa0\x39\xa3\x0f\x67\xe5\xe7\x2a\xa0\xb8\xed\x09\xfd\xf4\x16\x62\ +\x14\x20\x11\x72\xf5\xac\x6b\xa2\xb3\x26\x33\xb1\xe2\x48\xc7\x7e\ +\x13\x8a\x0f\x4a\x6e\x02\x4a\xd7\x78\x04\xdc\xe9\x8c\x49\x5a\xfb\ +\x2b\x02\x8a\xdb\x9e\x48\x3e\x60\x9d\xec\xd4\xbf\xf0\xf2\xcf\x0b\ +\x48\xb3\xde\x1c\xb9\xa0\x79\x56\x15\xf7\xbb\xbc\xef\x22\xec\xb7\ +\xaa\x53\xad\x8f\xb4\xd8\x98\xd6\xde\x20\xfa\xfb\x3a\x90\x14\x1f\ +\x07\xc6\x65\x6f\xb5\xec\x4e\xc4\x0d\x61\x7d\x20\xdb\x6b\x28\x46\ +\x75\xec\xd7\xac\xf8\x1e\x40\xaa\xf5\x17\x06\xb3\x7e\x60\x01\x92\ +\xd6\x6c\x6f\x74\x84\xee\x96\xaf\xf3\xd0\x31\x62\x08\xeb\x03\x7d\ +\x5b\x90\xd8\xb9\xd3\x19\xb3\xbd\x81\xfc\xbc\x2b\x35\x93\xf5\x03\ +\x0b\x60\x55\xb1\x0b\x9a\xc7\x1c\xf5\xcc\xc9\xb0\xea\xb3\x0b\x00\ +\x9a\xd3\xda\x03\x2d\xf5\x9a\x57\xa4\xc5\x66\x46\xeb\x33\x09\x00\ +\x68\x7c\xe5\x05\x5d\xad\x48\x38\x97\xf5\x99\x05\xa4\xb6\x62\x08\ +\xeb\xb3\x0b\xa0\xd5\x8a\x48\x9a\x03\xf6\x81\xfd\x48\x9a\x3b\xaf\ +\xf5\x81\xcc\xbf\xe3\xdd\x19\x7d\x04\x26\xfa\x26\x0e\x48\xdb\x01\ +\xc3\x21\xb4\x36\x90\x79\xdd\xbc\x9b\x62\xd5\x97\x93\xe1\xc1\x29\ +\x01\x98\x3a\x40\x3c\xc2\xe4\x9f\x12\x00\xad\x7b\xdb\x34\x42\xa0\ +\xdd\x82\x08\x55\x8c\xa7\x90\xd7\x8b\x55\x0b\xa8\x75\xec\xe1\x86\ +\x22\x79\xf2\x49\xe1\x67\x40\x1c\xa1\x4a\x98\x4b\x3b\x98\x54\xc8\ +\x73\xa7\xf4\x3b\xbd\x0f\x26\x81\x70\x34\x4b\xb6\xce\x63\xdd\xf3\ +\xe7\xe4\xc0\xa6\x91\x76\x34\xfb\xcf\x2f\xa6\x4e\xeb\xad\xb9\x6d\ +\xcb\x1e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x8b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3d\x49\x44\x41\x54\x58\x85\xed\ +\xd3\x21\x12\x00\x10\x00\x05\xd1\xe5\x52\xaa\xe2\x00\x2e\xea\x04\ +\x66\x64\x97\x32\x92\x2a\x52\xf6\xa5\xdf\x36\x7d\x90\x24\x7d\x16\ +\xce\x48\x6d\x0d\x20\x3f\xaa\xf6\x59\x63\x01\x88\x4f\x82\xd2\x85\ +\x2f\x90\x24\xe9\xbb\x0d\xbb\x58\x0a\x07\x83\x32\x65\x0f\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x26\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xd8\x49\x44\x41\x54\x78\x9c\xed\ +\xd2\xb1\x4d\xc3\x50\x18\x46\xd1\x1f\x86\xf0\x26\x2c\x92\x15\x52\ +\x20\x1a\x86\xa1\x89\xb2\x44\x16\x61\x8b\x54\x6c\x61\x0a\x2c\xa5\ +\x88\x68\x7d\x22\xe5\x1e\xc9\xd2\x73\xf5\x3e\x5f\x79\x26\xc9\x33\ +\x7b\x51\x17\xbf\xbd\x7f\x1d\x66\xe6\xb4\xbd\x7e\x7c\x9f\x3f\x2f\ +\x62\xc7\xab\xb8\x74\x73\x5a\x67\x96\x75\x66\x99\x5b\x88\xdd\xb1\ +\x00\xdb\x87\xdf\x9d\xf7\x26\xff\x80\x87\x50\x00\x3d\x40\x2b\x80\ +\x1e\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\ +\x01\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\ +\xa0\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\ +\x5a\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x2b\x80\x1e\xa0\ +\x15\x40\x0f\xd0\x0a\xa0\x07\x68\x05\xd0\x03\xb4\x02\xe8\x01\x5a\ +\x01\xf4\x00\xad\x00\x7a\x80\x56\x00\x3d\x40\x93\x01\x7e\xfe\x39\ +\xef\x0a\x06\x58\x8f\x33\x73\xfd\x7b\xd6\xa3\xdb\x91\xe4\x99\xfd\ +\x02\xc9\x6e\x11\x4a\x9d\x22\x1c\x0a\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x03\x5c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x0e\x49\x44\x41\x54\x78\x9c\xed\ +\xd5\x4b\x6c\x54\x75\x14\xc7\xf1\xef\xb9\x53\xa6\xda\x81\xd0\xd0\ +\x98\x50\x4d\x4a\x64\x63\x52\x36\xc0\x4c\xc7\x47\xa2\xa9\xcf\xa4\ +\x16\x24\x2c\x70\x41\x04\x4b\x02\x33\x03\xed\x80\x62\xe2\xc2\xc4\ +\x4c\xba\x33\xf1\x51\x3b\x03\xa5\x0f\x89\x04\x16\x18\x0a\x29\x31\ +\x60\xdd\x98\x58\x92\x52\x18\xda\x59\xb2\x00\xa2\x1b\x83\x84\xd0\ +\x0a\x49\x83\x9d\xda\xce\x71\x51\xa3\xd3\x6b\x25\xd8\x7b\x67\xba\ +\xe0\x7c\x96\xff\x73\xef\x6f\x7e\xf7\xcc\x0b\x8c\x31\xc6\x18\x63\ +\x8c\x31\xc6\x18\x63\x8c\x31\xc6\x18\xf3\xa8\x10\xaf\x01\xcf\xc6\ +\xd3\xf5\xb3\xca\x71\x84\xa7\x50\xbe\x18\xed\x4d\x7e\x06\xa2\x7e\ +\x94\x5b\x48\x34\xd1\xb9\xb5\xa0\xf2\x29\x00\x05\x49\x8e\xf6\x25\ +\x07\xbd\xe4\x79\x5e\x40\x24\x9e\x19\x02\x7d\xe9\xef\x03\xe5\xc4\ +\xfd\xdf\xc6\x77\x5f\xed\x6f\x9f\xf6\x9a\x3d\x9f\x4a\x38\x9e\xf9\ +\x50\xe0\x93\xa2\xc3\x7b\xaa\x95\x4f\x8c\xf5\xc6\xff\x58\x6c\xaa\ +\xe3\x43\xb1\xf9\x19\xc2\x8e\xaa\x55\x35\xdf\xaf\x6f\xe9\xa8\xf6\ +\x9e\x3d\xa7\x31\x95\xaa\x88\xc4\xd3\x5d\xae\x87\x9f\x7b\x35\x8f\ +\xbc\x2f\x40\x74\xaf\xc0\x6d\xd7\xe9\xcb\x81\xca\xc0\xf0\x86\xd6\ +\x43\x6b\xbc\xc6\xd7\xef\x3b\xbc\x7c\xf2\x56\xcd\x59\x90\x84\x6b\ +\x94\x17\x78\xc7\xcb\xbb\x0f\x3e\x6c\x10\x20\xba\x3b\xf3\x74\x21\ +\xa0\x83\xc0\x33\xae\xd1\x2d\x55\xa7\x79\xac\xb7\x2d\xb7\x98\xdc\ +\x70\xac\xa3\x56\x24\x70\x0e\xd8\xe8\x1a\x4d\x20\xf2\xd6\x68\x77\ +\x72\x78\x31\xb9\xc5\x7c\xf8\x0a\x40\xf6\xab\xe4\xcf\xcb\x66\x66\ +\x5e\x00\xb9\xe0\x1a\xad\x16\x29\x5c\x08\xc7\xd2\xcd\xff\x37\xb3\ +\x61\xcf\xa1\x75\x22\x81\x4b\xfc\xeb\xe1\xe5\x27\xa7\xe0\x3c\xef\ +\xc7\xc3\x83\x4f\x0b\x00\x18\x39\x7a\x70\xe2\x6e\x50\xdf\x00\x4e\ +\xba\x46\x21\x11\xbe\x0d\xc7\xd2\x7b\x1f\x36\x6b\x63\x22\xf3\x8a\ +\x3a\x85\x61\xa0\x6e\xfe\x44\x2e\xcf\x4e\xeb\x73\xd9\xbe\xb6\x6b\ +\x9e\x0b\xff\x25\xe0\x57\x10\xc0\x44\x76\x70\xf6\xe6\xa6\xe8\x40\ +\xed\x64\x28\x28\xf0\x62\xd1\x48\x44\x68\x7e\x32\xd2\x14\xba\xb9\ +\x29\xfa\x03\x43\x43\xff\xf9\x37\x19\x89\xa7\x77\x0a\x9c\x02\xaa\ +\x8a\xcf\x15\x19\x40\x83\x5b\x72\x47\x5b\xef\xf9\xd9\xd9\x97\xdf\ +\x80\x85\x44\x62\x9d\x31\x44\xba\x70\x2d\x59\xe1\xd4\x8a\xfc\x8a\ +\x77\x7f\x3c\xb6\x6b\x6a\xfe\x1d\x2a\x0d\xf1\xcc\xc7\x0a\xed\xee\ +\x2c\x45\x3b\xd7\x4e\xd4\x7e\xd0\xdf\xff\xf6\xac\xdf\x3d\x4b\xb6\ +\x00\x80\xc8\x9e\x4c\x13\x8e\xf6\x03\x21\xd7\x68\xd8\xa9\x70\xb6\ +\x64\x0f\xb7\x8d\x03\xd4\x6f\x4b\x05\x1f\x5f\x55\xd3\x23\xd0\xe2\ +\xba\x4e\x05\x79\xff\x4a\x4f\xb2\xb3\x54\x1d\x4b\xba\x00\x80\x48\ +\x22\xbd\x01\xe5\x3c\x50\x5b\x7c\xae\x70\x1d\xa5\x09\x2a\xef\x88\ +\x93\x3f\x8d\xf2\x9a\xeb\xd6\x29\x47\x74\x7b\xb6\xfb\xc0\x40\x29\ +\xfb\x95\x7c\x01\x00\xe1\xd8\x97\x75\x22\xce\x77\xc0\xba\x87\xbc\ +\xe5\x4e\xc1\x61\x73\xee\xc8\xfe\x4b\xa5\xec\x05\x65\x5a\x00\x40\ +\x38\xd6\xb3\x52\x24\x7f\x06\x78\xf5\x41\xd7\x29\x5c\xd7\x40\xe0\ +\xcd\x5c\x57\xeb\x8d\x72\xf4\xf2\xf5\x5f\xe0\x41\x7e\x1d\x3b\x97\ +\xaf\x5e\x1b\xfd\x26\x58\x15\xaa\x03\xd6\x2f\x78\x91\x70\x11\x9d\ +\x7e\x3d\xd7\xfd\xde\x2f\xe5\xea\x55\xb6\x4f\xc0\x3f\x54\x22\x89\ +\x74\x0a\x95\x94\x6b\x70\x7a\x59\xd5\xcc\xce\x91\x8e\x83\xbf\x97\ +\xb3\xcd\x12\x2c\x60\x4e\x43\x22\xdd\xa7\xca\x2e\x40\x81\xcf\x47\ +\x57\x8f\x7f\x44\x7b\x7b\x61\xa9\xfa\x2c\x89\xc6\x54\xaa\xa2\xb1\ +\xe5\xeb\xc7\x96\xba\x87\x31\xc6\x18\x63\x8c\x31\xc6\x18\x63\x8c\ +\x31\xc6\x18\xf3\x88\xf8\x13\xba\x50\xdf\xc1\x6b\x55\xb9\xde\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xc4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x76\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xc1\x0d\x82\x40\x14\x04\xd0\x59\x8b\x30\x36\x62\x23\xb6\xc0\ +\xc1\x70\xb2\x17\x2f\x84\x46\xa8\x82\x42\x88\x4d\xac\x57\x43\xf6\ +\x0a\x24\xf2\xde\x71\xf2\x0f\xf3\x27\x01\x00\x00\x00\x00\x00\x00\ +\xce\xa0\xac\x83\xfb\xf3\xfd\x48\x32\xd4\xe4\x7a\x40\x9f\x2d\x2d\ +\x49\xed\xe6\xf1\x35\xfd\x86\x97\xc6\xe1\x3f\x3e\x9f\x24\xb7\xa4\ +\x0c\xeb\xb0\x35\xc0\xa9\xb4\x06\xe8\x4b\xf2\xd9\xbd\xc9\xf6\x96\ +\xa4\xf6\x47\x97\x00\x00\x00\x00\x00\x00\x00\x00\xf6\xf7\x05\x16\ +\xa6\x0e\x08\x70\x11\x84\x99\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x88\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x14\x44\x05\x88\x0e\ +\x20\x71\x45\x4e\x68\x81\x94\xc4\x0d\x59\x34\xf1\xa4\xc8\x2f\x42\ +\xeb\x91\x3d\x13\xae\x2e\xd8\xbb\xec\x12\x00\x00\x00\x00\x00\xf6\ +\xa3\x2c\x83\xf3\xf5\x7e\x29\x35\x63\x92\x63\x87\x3e\xab\x29\xc9\ +\x5c\x93\xdb\xf4\x7c\xbc\xbe\xf3\x43\x33\xb8\xc1\xe5\x93\xa4\x26\ +\xa7\x24\xe3\x32\x6f\x0e\xb0\x37\xcd\x01\x6a\xc9\x90\xe4\xdd\xa1\ +\xcb\xaa\x4a\x32\x27\x19\x7a\xf7\x00\x00\xfe\x87\x5f\xa0\x19\xdc\ +\xe0\xf2\x89\x5f\xe0\x27\xbf\x00\x00\x00\x00\x00\x00\x00\x3b\xf1\ +\x01\xd7\x53\x1e\x0f\x14\xfc\xaf\x10\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\xc4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x76\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3d\x6f\xd3\x40\x1c\x87\x9f\x4b\xa8\xca\x02\x4b\x78\x59\x6a\ +\xe7\xfc\x39\xf8\x12\x2c\x54\x0d\x2d\xac\x74\x60\x65\x63\xe5\x1b\ +\x80\xc4\xca\x4b\x0b\x82\x01\xf1\x3d\xbc\x31\x66\x70\xed\x66\x43\ +\x48\x48\x2c\xa8\x52\x7b\x2c\x11\x32\x87\x9d\x36\xf6\xdd\xf9\xce\ +\xf1\x6f\xb3\xfd\xcf\x4f\xf7\x3c\x8a\x9d\xe8\x64\x18\x32\x64\xc8\ +\x26\x47\x74\xbd\x00\xdb\xc9\x8a\xe2\xbe\x50\xe2\x05\xf0\x73\x3c\ +\xe2\x30\x8a\xa2\x6f\xe5\xeb\xd7\x3a\x5a\x97\x93\x64\x45\xb1\x27\ +\x94\x38\x02\x46\x00\xe7\x17\xbc\x06\xee\x95\x67\x46\x5d\x2c\xcc\ +\x45\x74\xf8\x65\x6e\xea\x73\xbd\x14\x50\x03\x7f\xae\x84\x7a\xae\ +\xcf\xf6\xee\x16\xa8\x83\x17\x88\x99\x8c\xa3\xaf\xfa\x7c\xaf\x1e\ +\x82\xab\xe0\xa7\xd3\x9d\xcf\x55\x9f\xe9\x8d\x80\x26\xf0\xd0\x13\ +\x01\x4d\xe1\xa1\x07\x02\xda\xc0\x43\xe0\x02\xda\xc2\x43\xc0\x02\ +\x4c\xc0\x43\xa0\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\ +\xc3\x43\x40\x02\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\ +\x83\xe7\x02\x6c\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\ +\x87\x02\x4c\xc3\xe7\xf9\xe2\x81\x52\xea\xd5\xf2\xf0\x89\x94\xd1\ +\x97\xf2\x75\xaf\x04\x98\x86\xff\xaf\x4f\xf1\x5d\xca\xe8\x4e\x79\ +\xc6\x9b\x2d\x31\xeb\xf0\x35\xf1\x42\x80\x23\xf8\x0b\x21\xc4\x53\ +\x7d\xb6\x73\x01\xae\xe0\x51\x3c\x9e\x4e\x77\x3e\xe9\xf3\x9d\x3e\ +\x03\x5c\xc2\x4b\x19\x1d\x55\x7d\xa6\x33\x01\x3e\xc0\x43\x47\x02\ +\x7c\x81\x87\x0e\x04\xf8\x04\x0f\x8e\x05\xf8\x06\x0f\x0e\x05\xf8\ +\x08\x0f\x8e\x04\x38\x84\x7f\x24\x65\x74\xbc\x4e\x97\x75\x01\x3e\ +\xc3\x83\x65\x01\xbe\xc3\x83\x45\x01\x21\xc0\x83\x25\x01\xa1\xc0\ +\x83\x05\x01\x21\xc1\x83\x61\x01\xa1\xc1\x83\x41\x01\x21\xc2\x83\ +\x21\x01\xa1\xc2\x83\x01\x01\xae\xe0\x95\x50\x07\x49\x1c\x7f\x58\ +\xb7\x2f\xcf\x17\xbb\x4a\xa9\x97\xcb\x43\xb3\x7b\x82\xfe\xc3\x9f\ +\x1e\x28\x78\xf3\xb7\xcf\xe4\x9e\x60\x70\xf0\x35\x69\x24\xc0\x77\ +\xf8\x93\x93\xd3\xfd\x0a\x78\x33\x7b\x82\x21\xc0\x23\x78\xab\xf7\ +\x19\xd9\x13\x0c\x19\xbe\xf5\x9e\x60\x00\xf0\x0f\x11\xbc\xd3\xfb\ +\x2e\xfb\xe9\xbc\x92\x80\xbe\xc2\xc3\x15\x04\x38\x84\xdf\x4f\xe2\ +\xf8\xe3\xba\x7d\x6d\xe0\xe1\x12\x01\x7d\x87\x87\x15\x02\x7c\x87\ +\xcf\x8a\x62\x26\x94\x78\x5f\xd1\xb7\xd6\x6d\x54\x29\x60\x53\xe0\ +\x01\xc6\xfa\x89\x3c\x5f\xec\x02\xc7\x18\x82\xaf\xe9\x6b\x0c\xbf\ +\xa2\xaf\xd1\x03\xf4\x9f\x6f\x40\x9a\xa6\x5b\xb7\x6e\xdf\xfd\x01\ +\xdc\x28\x9d\x6e\x0c\x5f\xd3\xd7\x18\xde\x74\x1f\x68\xff\x04\x27\ +\x93\xc9\x18\xd8\x2e\x9d\x6a\xf5\x5a\x4a\x45\x5f\xab\xc5\x9a\xee\ +\x03\x4d\x40\x92\x24\xbf\x05\x3c\x03\xce\x80\x5f\x02\xb1\xd7\xe6\ +\x9d\x9c\x8a\xbe\x59\x9b\xc5\x9a\xee\xab\xcd\x7c\x3e\xdf\x4e\xd3\ +\x74\xcb\xd7\xbe\x2c\xcb\xae\x9b\xec\x1b\x32\x64\x83\xf3\x07\x17\ +\xa8\x1d\x6f\x59\x60\x0c\x9b\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x0a\xf4\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xa6\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7b\x70\x54\xd5\x19\xff\x7d\xf7\xee\x6e\x60\x93\x08\x64\x11\ +\x83\xd2\x91\xd8\x96\xd1\x58\x98\x21\xbb\x0b\x52\x35\x22\xda\xd1\ +\x5a\xc5\x07\xae\xf5\x31\x28\x51\xd8\x4d\x80\x2c\xc2\x54\x5b\x9d\ +\xa9\x4b\xac\x76\xb4\x6a\x08\xbb\x60\xdc\x08\x18\x41\xa6\xad\x99\ +\x51\xa7\x3a\x8a\x4c\xb5\xa1\xd4\x22\x64\x03\x96\xfa\xc0\xf1\x11\ +\x1f\x34\x90\x4a\xc2\x23\x12\xb2\xd9\xdd\xf3\xf5\x8f\x20\xdc\x7b\ +\xf7\xee\xbd\x77\x93\x5d\xa6\xd3\xf2\xfb\x6f\xbf\xf3\x3b\xdf\xf9\ +\x9d\xef\x9e\x3d\xf7\x3c\xbe\x0b\x9c\xc6\x69\x9c\xc6\xff\x33\xe8\ +\x54\x34\x32\xb5\x2a\x7c\xa6\x5c\x40\x95\x80\x98\x0c\xa6\xf3\x41\ +\x38\x8f\x19\xa3\x09\x38\x03\x80\x0c\xd0\x11\x00\x47\xc0\xfc\x15\ +\x08\x1f\x01\xf8\x50\x4a\xd1\xd6\x1d\x6b\x6a\x3b\xf2\xad\x2d\x6f\ +\x01\x70\xfb\xc3\xdf\x97\x08\xf3\x98\x31\x1b\x84\x29\x43\x74\xd3\ +\xc1\xe0\x37\x24\xc1\xcd\x6d\xcf\x2e\x89\x01\xc4\x39\x15\x89\x9c\ +\x07\x80\xc9\x1b\x08\x5f\xc5\xa0\xfb\x01\x5c\x9e\x5b\xdf\x78\x9f\ +\x40\xf5\x82\x1d\x2f\xb4\x37\x05\x12\xb9\x72\x9a\xb3\x00\xb8\xfd\ +\x2b\x2f\x27\xa2\xdf\x01\xf0\xe4\xca\xa7\x1e\x18\xf8\x02\xcc\xcb\ +\xdb\x9b\x82\xeb\x73\x31\x22\x86\x1d\x80\xe9\xf3\x1b\xce\x4a\xca\ +\xd2\x53\x04\xdc\x61\x40\x13\x04\xbc\x03\xe2\x56\x21\xa4\x3d\x40\ +\xea\x33\x1b\x51\x8f\x90\x6d\xbd\xc9\x63\xa9\x94\x3c\x22\x59\x0c\ +\xb6\x8d\x22\x46\x99\x60\x9a\x44\xe0\x19\x20\xfc\x04\xc0\x48\x03\ +\xe1\x5b\x21\xa4\x9a\xb6\x67\x17\x7f\x30\x1c\xfd\xc3\x0a\x80\xa7\ +\x3a\x3c\x0d\x8c\x57\x00\x8c\xd7\x29\xee\x05\xf0\x3a\x11\x5e\x25\ +\x59\xda\xb4\x63\xf5\xe2\xee\x6c\x7c\xcf\x58\x5a\x3f\x72\xe0\xa8\ +\x6d\x16\x01\xd7\x81\x30\x3b\x43\x1b\xfd\x00\xee\x8e\x45\x83\xbf\ +\xcf\x5e\xfd\x20\x86\x1c\x00\xb7\x3f\x72\x3b\x11\xaf\x03\x50\x90\ +\x26\x8a\x39\x1c\x97\xed\x8f\xfd\xb3\x71\xe1\xc1\xa1\xfa\x57\xa2\ +\xdc\x17\x72\x38\xc7\x94\x2c\x20\xa2\x87\x18\x18\x97\x46\x60\x7a\ +\x34\x36\xfe\xc0\x43\xa8\xab\x13\xd9\xfa\xce\x3e\x00\xa1\x90\xe4\ +\xde\x3f\xf6\x11\x02\x3f\xa0\x29\x11\x44\x58\x27\x25\x51\xb7\x7d\ +\x4d\x70\x6f\xd6\x7e\x2d\xe0\xe2\xbb\x1f\x2f\x8e\xdb\x9c\xcb\x40\ +\xfc\x0b\x00\x45\x9a\xe2\x57\xfa\x64\x79\xee\x87\x4f\x2f\xfa\x36\ +\x1b\x9f\xd9\x05\x20\x14\x92\x3c\xfb\xc6\x6e\x04\xf1\xad\x2a\x3b\ +\xa3\x13\x12\x6e\x8c\x3d\x13\xdc\x91\x95\xbf\x21\x62\xfa\xfc\xf0\ +\x84\x94\x8c\x97\x91\x3e\xe1\xee\x92\x1d\x98\xb9\x3d\x12\x3c\x62\ +\xd5\x97\x94\x4d\xc3\xde\xae\x92\xe5\xda\xce\x13\xf0\x2e\x23\xe5\ +\x39\x55\x9d\x07\x80\xed\x6b\x82\x7b\xed\xce\x64\x25\x03\x1b\x35\ +\x45\x53\xc5\x00\x6f\xf4\xf9\x5e\x94\xad\xfa\xb2\x4c\xf4\x06\x22\ +\x3f\x67\x20\xa2\xb4\x11\xd1\xf3\x85\xf1\x62\xdf\xb6\xb5\x35\x87\ +\xac\xfa\xc9\x15\xf6\xbe\xfb\x66\x72\x5f\xfb\xeb\x2f\x9f\xed\x6d\ +\xeb\x03\x70\x25\x4e\x8c\x66\x9a\x74\x68\x44\xef\x88\xce\xf6\x4d\ +\x7f\xb6\xe2\xc7\xd2\x5f\x60\x5a\x20\xe2\x11\xe0\xad\x00\x46\x9c\ +\xb4\xf2\x0b\xb1\x68\xf0\xce\x7c\xac\xce\xb2\x85\xc7\x1f\xbe\x17\ +\x84\x15\x1a\xf3\x5d\xb1\x68\x70\xbd\x59\x5d\xd3\x00\x4c\x5b\xb4\ +\xca\x95\x4a\xf2\x3f\x08\x7c\x8e\xc2\xbc\xa3\x28\x5e\x7c\x59\x6b\ +\x73\x55\x7f\x36\x42\x2b\x16\xae\xb8\x40\x4a\xca\x37\x1e\x5f\x1a\ +\x4f\x00\x63\x02\x88\x52\x00\xf6\x12\x89\xbd\x42\xd0\x4e\x59\xd0\ +\x4b\xd9\xef\x01\x98\x3c\x81\xf0\x5a\x80\xaa\x14\xc6\x01\x66\x69\ +\x46\x7b\xd3\xe2\x9d\x46\x35\x4d\x03\xe0\xf1\x87\xd7\x82\x70\xf7\ +\xc9\xb6\xd0\x99\x72\x90\x77\xd7\xaa\xda\x4e\x2b\xd2\xca\x7d\x21\ +\x47\x61\xc9\xd8\x1a\x06\x57\x03\x38\xdf\x4a\x1d\x00\xbb\x88\x10\ +\x9e\xd8\x5d\xba\xa1\xa5\xe5\x96\x94\x95\x0a\x3f\xa8\x0d\x17\x8c\ +\x4e\xe0\x6d\x30\x7e\xac\x30\xef\x2c\x2a\xed\x9e\xde\x5a\x57\x97\ +\xcc\x54\xcf\x70\x12\x74\xfb\x1b\x2e\x51\x75\x1e\x60\x21\x63\x8e\ +\xd5\xce\xbb\xfd\x91\x1b\x9c\x63\x5c\x1f\x30\xb8\x01\xd6\x3b\x0f\ +\x00\x53\x99\xf1\x5c\x47\x49\x57\xac\xa2\x3a\x32\xcb\x4a\x85\x4f\ +\x23\xc1\xb8\x9c\x14\x37\x01\x38\xa0\x30\x57\xf4\xee\x73\x2d\x34\ +\xaa\x67\x30\x02\x98\x3c\x81\xc8\x5f\x01\x5c\xa2\xb0\xbd\x10\x8b\ +\x2e\x99\x6b\x26\xc6\xed\x8f\xda\x41\xfd\x0d\x04\x32\x6c\xdc\x32\ +\x88\xeb\x62\x67\xf5\x3c\x6c\x65\xa1\xa3\x33\x1f\x1c\x18\xe8\x8b\ +\x4f\xdc\xbd\xe1\xbe\xa3\x7a\xfc\x8c\x23\xc0\xbb\x20\x52\x09\x55\ +\xe7\x91\x80\x94\x0a\x99\x09\x98\x5c\xf3\xf4\x18\xa2\xf8\x1b\x39\ +\xeb\x3c\x00\x30\x85\x3c\xfb\x5d\x7f\x74\xfb\xa3\x4e\x33\x6a\xd1\ +\x40\xf1\x33\x00\xbe\x52\x98\xc6\xda\x9d\x8e\x40\x26\x7e\xc6\x00\ +\xb0\x84\xfb\xd4\x06\x44\x63\x8d\xcb\x3e\x37\x6a\xbc\xdc\x17\x72\ +\x14\x88\xd4\x2b\x00\xae\x30\x13\x3a\x04\xdc\x4c\xe8\x5f\x8f\x50\ +\xc8\xf0\x6f\xdb\xda\x5c\xd5\x4f\x04\xcd\x83\x92\x96\x65\x5a\x1b\ +\xe8\x3a\xf3\x2e\x5c\x5d\x0a\xe0\x6a\x85\x29\x21\x0b\xf1\x88\xb1\ +\x3e\xa6\x42\x97\x6b\x35\xc0\x95\xc6\xbc\x61\x80\x68\x8e\x7b\xbf\ +\xcb\x74\x14\x4e\xec\x2e\xdd\xc0\xc0\x27\x27\xaa\x81\xcf\xf9\xcc\ +\xd5\x75\xa5\x1e\x57\x37\x00\x22\x95\xbc\x1d\x8a\x45\x12\x01\x6f\ +\x6f\x5f\x73\x6f\x97\x51\xa3\xde\xc0\xaa\x3b\x98\x31\xdf\x4c\xdc\ +\x70\x41\xc0\x43\x9e\x05\x61\xdd\xce\x7c\x87\x96\x96\x5b\x52\x44\ +\x68\x51\xda\x24\xe6\xbb\xf4\xb8\xba\x01\x20\xd0\x75\x1a\xcb\x9f\ +\x8c\x1a\x74\xfb\xa3\x4e\x01\x3c\x66\xc4\xc9\x29\x24\xd4\x9b\x2d\ +\x77\x59\x08\xad\xe6\x6b\xf4\xea\xa4\x05\x60\xca\xdc\x27\x0a\x01\ +\xd5\xbb\x14\x82\x53\xaf\x19\x0a\xa2\xf8\x32\xcd\x42\x29\xdf\x98\ +\xdc\x51\xd2\x35\xcf\x88\xd0\x3e\xfe\x60\x1b\x00\xe5\xa8\x1d\xd5\ +\xe1\xda\xef\xd6\xf2\xd2\x02\x50\xe0\x74\x5c\x04\xc0\x71\xd2\x42\ +\xef\xb5\x37\xdd\xfb\x95\x96\xf7\x1d\x7c\xbe\x17\x65\x22\x04\xcd\ +\x35\xe7\x1a\xbc\xc4\xb0\xb8\xae\x4e\x00\xac\x7a\x70\xcc\xe9\xe7\ +\x94\x3a\x7f\x01\xe9\x47\x1a\xc3\x56\xa3\x76\x3a\x5c\x5d\x97\x82\ +\x71\xa6\xa1\x98\xfc\x60\xf2\xf4\xc0\xca\x1f\x1a\x11\x98\xd5\xda\ +\x89\x71\xa1\x96\x93\x16\x00\x66\xbe\x40\xf5\x1b\xe2\x13\x2d\x47\ +\x53\xe1\x66\xc3\xf2\x3c\x22\xc9\xd2\x1c\xa3\x72\x89\xa1\xd6\x4e\ +\xb8\x20\x8d\xa3\x35\x10\x61\xa2\xca\xc0\x64\xf8\xee\x07\x28\xaf\ +\xa7\xc0\x86\x2d\x13\xa7\xfd\xa7\x55\xb0\xdb\xb4\xda\xcb\xb4\x94\ +\xf4\x11\x40\x28\x56\x35\x22\x91\xc9\x5e\xff\x94\x4e\x7e\x2a\x10\ +\x30\xc1\xa8\xbc\xb0\xcf\xa9\xd5\x5e\xac\xe5\xa4\xcf\x01\xac\x26\ +\x49\xcc\x99\xcf\xd8\x06\x57\x65\x7a\xa7\xb5\xa7\x04\x6c\x12\x80\ +\xd6\xe6\x79\x71\x00\xca\x9d\xa0\xa3\xdc\x17\x72\x28\x39\x7a\xeb\ +\x00\xd5\x06\x29\x29\x89\x8c\x07\x1e\x33\x07\xeb\x67\x75\xac\x96\ +\x63\xd8\x87\xeb\x40\x4f\x7c\xaf\x8a\xc0\x72\xda\xb0\xf9\x0e\xc7\ +\xf7\xd9\x86\x2b\xc4\xbc\x82\x61\x78\xfa\x3c\x73\x5e\x73\x01\x00\ +\x9b\xc2\x34\xf0\x61\x4b\xdd\x80\x92\x93\x3e\x09\x02\xaa\x13\x55\ +\x16\x3c\xda\x44\xc4\xbf\x4c\x85\xe6\x0b\x64\x1c\x80\x63\xb6\xc3\ +\xa3\x34\xa6\x5e\x2d\x27\x7d\x12\x04\x7d\xa9\x6a\x43\x4a\x9f\x39\ +\xd5\xe5\xf4\xbe\x51\x79\x5e\xc1\xc6\x6d\xb3\x6c\x3b\x4f\x6d\xc0\ +\x17\x5a\x8e\xce\x24\xc8\x1f\x29\x7f\x12\x60\xbc\xd8\x20\xbc\x64\ +\x54\x9e\x4f\x30\xc8\xb0\x6d\x01\xa1\xd2\xce\x84\x3d\x5a\x4e\x7a\ +\x00\x48\x52\x5d\x36\x32\xab\x0e\x45\xd2\x50\x74\xac\x68\x33\x80\ +\xac\x6e\x63\x72\x02\xc6\x97\xed\x4d\x8b\x76\x19\x53\x34\xda\x75\ +\x46\x4c\x5a\x00\xfa\x64\xda\x06\x40\x79\xff\x5e\x31\x7d\x7e\x38\ +\xe3\xeb\xa6\xb5\xb9\xaa\x1f\x8c\x66\x33\xbd\x79\x40\x93\xe1\x91\ +\x7c\x28\x24\x11\x70\xad\xd2\xc4\x32\xb7\x6a\x69\x69\x01\x18\xbc\ +\x5b\xa3\x6d\x4a\x5b\x52\xa6\x6b\xb5\x3c\x25\x52\x09\x3c\x0c\xe0\ +\xb0\x89\xe0\x5c\xe2\x6b\x7b\x61\x52\x7b\x0f\xa0\x82\xb7\x73\x8c\ +\x1b\xea\x35\xca\x91\x33\xc6\x75\xc7\xb4\x3c\xfd\x77\x38\xab\x77\ +\x51\x44\x3c\xdb\xa8\xb1\x5d\xcf\x05\xbf\x21\xb0\xc9\x89\x51\xee\ +\x40\xa0\x07\xb7\xad\x58\x76\xcc\x90\x24\x49\x2a\xcd\x0c\x6c\xd2\ +\x3b\x1e\xd7\x0d\x40\xca\x41\x1b\x01\x9c\x3c\x81\x65\xcc\x9a\x5a\ +\x15\x36\xdc\xf1\x15\x96\xf6\x34\x10\xf0\xa6\xa1\xa8\x5c\x80\xb1\ +\xa1\x2d\xba\x58\x7b\x27\xa8\x46\x28\x24\x31\xa0\xda\xa4\x11\xf8\ +\x79\x3d\xaa\x6e\x00\x8e\x9f\xfb\x6f\x56\x98\x0a\x64\x7b\xda\x75\ +\xb8\x0a\xad\x75\x75\xc9\x44\x3c\x75\x2b\x80\x8f\x0d\xc5\x0d\x03\ +\x04\xbc\x5b\x34\x50\xec\x37\xbb\x8e\xf3\x76\xb9\x6e\x83\xfa\x1e\ +\x62\x7f\x51\x69\xcf\x66\x3d\x6e\xc6\x65\x2c\x81\x9f\x54\x1b\x68\ +\xd1\xd4\x45\xab\xce\x35\x6a\xf8\xbd\xe6\xa5\x87\x20\x25\xaf\x41\ +\x7e\x82\x10\x93\x52\xe2\x06\xb3\xeb\xb8\x72\x5f\xc8\xc1\x8c\xdf\ +\xa8\x8c\x44\x2b\x32\xdd\x0e\x65\x0c\x40\x5b\x34\xf8\x36\x00\xe5\ +\x64\xe8\x90\x92\x62\xb9\xa9\xca\xc6\x65\x9f\x27\xe3\xa9\x8b\xa0\ +\x1e\x41\xc3\x03\xd3\x1f\xec\xce\x64\xa5\xd9\xc1\x2c\x00\x38\x5d\ +\x2e\x3f\xd4\xdb\xde\x9e\x82\x81\xbe\xc6\x4c\x7c\x83\x8d\x0c\x31\ +\x88\x1e\x54\x59\x80\x3b\x2b\x6a\x56\x1a\xef\xc1\x31\x38\x12\x8a\ +\x4a\xbb\x7f\xc6\xc0\xaf\xa0\xb3\xfc\xcc\x02\x07\x18\x54\x13\x6b\ +\x5a\x7c\xbb\xe9\xa4\x07\xc0\xed\x7f\x72\x2c\x31\x7e\xad\xb4\x31\ +\xe3\xb7\xef\xac\xfb\x65\x46\x0d\x56\x2e\x47\xd7\x83\xa0\xbc\x0e\ +\xfb\x5a\x4e\x09\xaf\x95\xa7\x01\x00\x53\xaa\x1b\xc7\x15\x20\xb1\ +\x9c\x19\x77\x01\x30\xbd\xd9\x39\x8e\xc3\x44\xdc\x28\xc4\x88\xc7\ +\xda\x9b\x02\x96\x5e\xaf\xe5\xbe\x90\xc3\xe9\x72\x6d\x06\xe3\xb2\ +\x13\x46\xc6\x6e\x46\x81\xc7\x28\xaf\xd0\x34\x00\x53\xaa\x1b\xc7\ +\x39\x38\xb1\x1b\xc0\x59\x8a\x5a\x7f\x3f\x64\xc7\xac\x4f\x23\xc1\ +\xb8\x15\x71\xc0\xe0\xd1\xb9\x44\xf1\xab\x41\x3c\x87\x99\x26\x03\ +\x38\x07\x40\xc9\x71\x7f\xdf\x30\xa3\x93\xc0\x3b\x21\xa4\x96\xbe\ +\x43\x07\xde\xd2\xee\xda\xcc\xe0\x09\xac\x6c\x04\xa8\x5a\x61\x4a\ +\x80\x70\x89\x59\xe6\x8a\xa5\x04\x89\x8a\x9a\xf0\x45\x92\x40\x2b\ +\x94\x19\x61\x8c\x75\xb1\xa6\xda\xf9\xc3\x49\x90\x98\xb1\xb4\x7e\ +\xe4\x37\x49\x9b\xc8\x26\x90\x7a\xf0\x06\x22\x0b\x19\xbc\x5a\x6d\ +\xa5\xf9\xb1\x68\xed\x5a\xb3\xba\x96\x93\xa4\x3c\xd5\x2b\xe7\x82\ +\x49\x93\x71\x41\x4d\x7d\x3d\x07\x6a\xb3\x7d\x5a\xb9\x03\x93\xdb\ +\x1f\xa9\xa5\xc1\xdb\x60\xe5\x7c\xd6\x10\x8b\x06\x97\x5a\xf1\x60\ +\x39\x47\xa8\x33\xb6\x69\xf7\xd9\xee\xab\x9d\x20\xba\x58\x61\x76\ +\xdb\x9d\xce\xca\xf1\x15\x57\xbc\xb6\xaf\x7d\x73\x9f\x55\x5f\xb9\ +\x40\xb9\x2f\xe4\x38\xf7\xd2\xdd\x51\x1a\x9c\xa8\x4f\x3c\x48\x02\ +\xde\x2c\x2a\xed\xae\xfa\x62\xcb\x16\x4b\x39\x83\x59\x1d\x67\x95\ +\x1d\x1c\xff\x20\x83\x5e\x56\x19\x19\x97\x81\x1c\x6d\x6e\x7f\x64\ +\x72\x36\xbe\x86\x83\x29\xd5\x8d\xe3\x9c\x25\xae\xb7\x00\xba\x47\ +\x53\xf4\x41\x22\x9e\xba\xd5\x28\x23\x44\x8b\xac\x13\x25\x7d\xbe\ +\x17\xe5\x8e\x31\xfb\x9e\x00\x91\x76\x88\x25\x88\xd0\x18\x87\xfd\ +\xd1\xdd\xcf\xd4\xfc\x3b\x5b\xbf\x56\x30\x63\x69\xfd\xc8\xc4\x51\ +\xdb\x62\x10\x1e\x00\x30\x46\x55\x48\x78\x83\x45\xc1\x6d\x56\xdf\ +\x1a\x27\xab\x0d\x11\x9e\x40\xe4\x1e\x80\x1b\x91\x7e\x30\xf9\x2d\ +\x88\x9f\x92\xed\x54\x9f\x4d\xc2\xa2\x11\x66\x86\x42\xb6\xde\x7d\ +\x25\xf3\x40\xd2\xf2\x0c\x77\x90\xf5\x65\x3d\xa5\xf7\x5b\xcd\x27\ +\x52\x62\x58\xc9\xd2\xde\x40\x43\x25\x43\x7a\x09\x80\x4b\xa7\xf8\ +\x20\x80\x57\x01\xbc\x2a\x3b\xb0\x39\xdb\x60\x94\xfb\x42\x0e\xe7\ +\x68\x57\x25\xc9\xb8\x8e\x05\xae\x07\x41\x6f\x19\x9e\x00\xa8\xc6\ +\xca\x6c\x9f\x09\xc3\x4e\x97\xf7\x2e\x5c\xfd\x3d\x4e\xa5\x1a\x00\ +\xdc\x64\x40\x4b\x80\xb0\x05\x02\x7f\x81\x44\x1f\x4b\xcc\x9f\xb2\ +\x2c\xf7\xf4\x33\x7d\xeb\xb4\x25\x53\x52\x22\x59\x2c\xd8\x36\x2a\ +\xc9\x28\x23\x89\x26\x81\xc5\x0c\x80\xae\xc2\xe0\x27\x35\x99\x94\ +\xb7\x09\xe2\x9a\x9d\x8d\x4b\xda\x87\xa3\x3f\x67\x1f\x4c\x78\x16\ +\x44\x7e\x0a\x89\x1f\x07\x90\xdf\xc9\x70\x30\x2f\xf9\xe1\xb2\xee\ +\xd2\x35\x43\x19\xf2\x5a\xe4\xf6\x93\x99\x50\x48\x9a\xd6\x55\x72\ +\xbd\x00\x3d\x00\x86\x37\xa7\xbe\x41\x9f\x83\x45\x7d\xd1\xc0\x19\ +\x6b\xb3\x4d\xd0\x34\xf4\x9a\x2b\x47\x5a\x78\x17\xac\xba\x50\x48\ +\x3c\x8f\xc0\xb3\x01\x4c\x1a\xa2\x9b\xfd\x60\xbc\x4e\x24\x9e\x6f\ +\x2b\x3d\xf8\xb7\xa1\x7c\x0f\x60\x86\x53\xf2\xd9\xdc\xf1\x79\xe2\ +\x72\x30\x5f\x08\xd0\xf9\x20\x94\x01\x18\x85\xc1\xff\xb8\x8d\x41\ +\x87\x89\x71\x04\xc4\x5f\x13\x61\x8f\x10\xd8\x63\x23\x6c\xd9\x1e\ +\xad\xfd\xe8\xbf\x21\x17\xf9\x34\x4e\xe3\x34\xfe\x77\xf1\x1f\x1c\ +\x6b\xc6\x54\xc2\x9c\x88\xf8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\x9b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x4d\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xc1\x09\x00\x20\x08\x46\x61\x8b\x46\x72\x80\xb6\x71\x9f\xe6\ +\x09\x5c\xad\x0d\x32\xa5\xe3\x7b\xc7\x1f\x84\xef\xaa\x08\x25\x53\ +\x5b\xae\xb6\xfc\x75\x8f\x1a\x05\xc3\x4c\xee\xd7\x7a\xe5\xe8\x67\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x90\xff\x8c\ +\x9a\xec\xd4\x4e\x41\x07\x39\xb5\x09\xe5\x39\xad\x0d\x4e\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xc7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x79\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\x31\x4e\xc3\x30\x14\xc6\xf1\xff\xb3\x9b\x72\x03\x3a\x70\x82\ +\x82\x84\xc4\xd4\xb9\xe5\x00\x48\x70\x85\x0e\xb0\x54\xdc\x20\x1c\ +\xa1\x1b\x54\xe2\x12\x88\x05\x09\xa9\x99\x91\x3a\x51\x28\x27\x60\ +\x80\x89\xb9\x21\x35\x43\x15\xa1\xb6\x69\x63\xa7\x4e\x18\xf0\x68\ +\x3f\xf9\xf7\xc9\xb6\x9e\x0c\xff\x7d\x48\x95\x58\xab\xdb\x6f\x24\ +\x5a\xdf\x81\x79\x1f\x0d\x7a\x67\x00\xaa\x52\x5c\xe9\x08\x4c\x0b\ +\x64\x2f\x9d\xaf\x55\x8a\x8b\x69\x62\xe4\x4d\xcf\x92\x93\x74\xad\ +\xf4\x2b\xc8\xc0\xdb\x4f\xb7\x97\x1f\x95\x04\xc8\xc3\x4b\x0d\x60\ +\x83\x97\x16\xc0\x16\x2f\x25\x80\x0b\xee\x3d\x80\x2b\xee\x35\x40\ +\x11\xdc\x5b\x00\x5b\xfc\xf0\xfc\x7a\xb7\x6e\xe2\x07\xe0\x6b\x34\ +\xe8\x75\xc0\x43\x27\x74\xc4\x87\xc0\x11\x50\x4f\xe7\xb7\x0a\x50\ +\x00\x3f\x00\x5e\xa6\x12\x9c\xa6\x6b\x85\xaf\x60\x0b\xfc\xf8\xf9\ +\xe6\xe2\x73\xab\x00\xbe\xf0\x42\x01\x5c\xf0\xc0\xc4\x91\xc0\x3e\ +\xf0\x3a\x95\xa0\xb3\x8c\x3b\x07\xf0\x8d\x3b\x05\x28\x03\x07\xd0\ +\x3e\xf1\x56\xb7\xdf\x10\x31\xd6\x38\x58\x9c\x80\x0b\xfe\xad\xd5\ +\xd0\x05\xcf\x0d\x50\x04\x37\x30\x89\x25\x68\x67\xe1\x4e\x9d\xb0\ +\x24\x7c\xa5\x13\x66\xfe\x09\xcb\xc0\x03\x13\x47\xcc\xaf\x67\xa1\ +\x13\xae\x3c\x42\x17\x3c\x51\x3a\x12\xd9\x8c\x67\x3c\xcc\x85\x66\ +\xa4\xb2\x36\xb5\xc5\x11\xd3\x34\x30\xa9\x25\xb3\xcc\x07\x67\xf3\ +\x30\x25\x6b\x53\x57\xdc\xa6\x6e\xdd\x09\xcd\x4f\x20\x0c\x55\xa2\ +\xd5\x63\xfe\x67\xc2\x48\x52\x53\xf7\x79\xf8\x72\xdd\x3a\xfc\x37\ +\xc0\x7c\xec\x00\xe3\x8d\x3f\x99\xf0\x4a\x8c\xa1\x0e\x8c\xd7\xe3\ +\xab\x75\x36\xfd\x00\xc2\x50\x81\xb1\x68\xcd\x46\xfc\xd6\xfd\xf1\ +\xf8\x01\x9a\x8b\x01\xab\xe8\x4a\xa0\x68\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x2a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xdc\x49\x44\x41\x54\x58\x85\xed\ +\x95\xbf\x6b\x53\x51\x14\xc7\x3f\xdf\x9b\x68\x4a\x07\xab\x06\x2a\ +\xb5\xab\x2e\x82\x54\x92\x06\x51\xe9\x6c\x8b\x9d\x44\x07\x51\x70\ +\x32\x3f\x14\x2b\xfe\x05\x21\x9b\x93\xc5\x18\x85\x66\xea\xe6\xe2\ +\xa0\xa0\x54\xbb\x05\xec\x52\x1a\xd4\xbf\x40\xa7\xaa\x83\xe2\x24\ +\xb4\x4d\xee\x71\xc8\xb3\xa9\x69\xaa\xcd\x6b\xc4\xe5\x7d\xe0\x0d\ +\xef\xde\x7b\xce\xf9\x70\xee\xbb\xef\x42\x44\x44\x44\xc4\x7f\x46\ +\x61\x03\xcf\xe4\xef\x8f\xae\x5b\xfc\xa5\x60\xac\xb9\x4f\xa3\x6f\ +\x2b\xb7\x57\xc3\xe4\x71\x61\x82\x4e\xe7\x1e\x1c\x5f\xb7\xf8\x1b\ +\xc1\x18\x80\xdb\xb0\xa5\xd4\xcd\x47\xc7\xc2\xe4\xea\xb9\x03\x99\ +\x1b\xb3\xa7\x70\xb1\xd7\x06\xc3\x1d\x53\x5f\x1c\x9c\x5f\x9e\x9b\ +\x79\xdf\x4b\xbe\x9e\x3a\x90\x2a\x94\x27\xcc\xc5\x6a\x06\xc3\x18\ +\x06\x34\x5b\x8f\x0c\x38\xe2\xa1\x96\x2a\x94\x27\xfe\x89\x40\x2a\ +\x5f\x99\x76\x9e\x45\xe0\x80\x81\x21\x7c\x7b\xd6\xbc\x99\x0c\x18\ +\x72\x9e\xc5\x74\xb6\x7c\xa1\xaf\x02\x99\xdc\xc3\x6b\xce\xfc\x33\ +\x60\x00\x30\xb1\xb5\x78\x0b\xc9\x7c\xd0\x95\x01\x89\xe7\x99\x7c\ +\xf9\xea\x6e\x72\xc7\xfe\xb6\x20\x9d\x2d\xcf\x20\xaa\x81\xac\xd1\ +\xa5\x78\xdb\x02\xc3\x10\xc2\x01\x17\x47\xc6\x27\xbf\x7d\xaa\xbf\ +\x5a\x0e\x29\x60\x4a\xe7\x92\x25\x89\x7b\xc1\x80\x0f\x04\xfe\x8c\ +\x30\x13\x08\x24\x34\x75\x34\x33\xa9\xd5\x95\x85\x1a\x94\x76\x58\ +\xde\x8d\x62\xd1\x8d\x7f\x4e\x96\x81\x5b\xb4\xaa\x7a\xed\xa6\xf8\ +\x56\x7d\x4c\x42\x2e\x78\xa9\xac\x8c\x7c\xbd\x43\xa9\xb4\x7d\xeb\ +\x3a\x07\x4e\x5c\x2e\xee\x1f\x3c\x9c\x9c\x07\xae\x00\x98\xf0\xb2\ +\xde\x8a\x6f\x4a\x08\xc9\x36\xbf\xb3\x27\x66\x89\xeb\xf5\x6a\x6e\ +\x63\x47\x81\x74\x76\x6e\x50\x6e\xed\x29\xc6\x14\x06\x26\xf3\x6a\ +\x1d\xb1\xd0\xfc\xd6\x09\xb1\x60\x3e\x71\xa9\x5e\xcd\xfd\xd8\x26\ +\x70\xb2\xf0\xf8\x50\xc2\x1a\x2f\x30\xce\x06\x81\x7b\x2e\xde\x96\ +\x40\x6a\x9f\xb8\xa5\xc6\x5a\x73\xfa\xdd\xfc\xdd\xef\x00\xf1\x5f\ +\x8b\x12\xbe\xf1\x01\x18\x6a\x9b\x29\xd4\x6f\xba\x1b\x1d\xfb\x7c\ +\x2e\x9e\x88\x7f\x04\x0e\x42\xc8\xbb\x60\xef\xf4\xa5\xb1\x11\x11\ +\x11\x11\xfd\xe1\x27\x68\xea\x98\xa0\x5e\x6e\x43\xde\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x47\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xf9\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\x21\x4e\xc4\x50\x14\x85\xe1\x73\x5b\xa6\x04\x04\x0a\x6c\x43\ +\x9a\x54\x92\x20\xd8\x03\x2c\x80\x75\x60\x58\x00\x61\x01\xb3\x09\ +\x3c\x92\x64\x58\x06\xba\x06\x53\x12\x32\x0e\x41\x86\x0e\xf3\x2e\ +\x96\xbc\x07\xb8\xbe\x49\xe8\xff\xc9\x73\x2b\x4e\x8f\x69\x25\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x60\x12\xec\xaf\xa3\xbb\x9b\xa4\ +\x32\x53\x97\xb1\x04\x33\x0b\xbf\x1d\x7f\x1c\xa0\xef\xfb\xc3\xe1\ +\x73\x33\x37\xd9\xa5\xa4\xfd\xd1\xaa\xe5\xb1\x92\xf4\x50\x98\x5f\ +\xd5\x75\xfd\x12\x1f\x93\x01\xba\xae\x3b\x98\x55\x7b\x4f\x92\x1f\ +\xe7\x68\x97\x8d\x6b\x19\xc2\xfa\xa4\x69\x9a\xd7\xef\x71\x11\x3f\ +\x57\x55\xbb\xb7\xff\xee\xe5\x25\xc9\x74\x54\x94\xb3\x79\x1c\x27\ +\x03\xb8\x74\x9e\xa7\xd1\x56\x5c\xc4\x41\x32\xc0\xd4\x24\x03\x98\ +\xf4\xb8\x8d\x22\x99\x2c\xe2\x20\x19\x60\x18\x3e\x6e\x24\x7b\xce\ +\x52\x27\x27\xd7\x32\x6c\xd6\xd7\x71\x9c\x0c\xd0\xb6\xed\xdb\x4e\ +\xa9\x33\x97\xdf\x49\x7a\xcf\x52\x6e\x5c\x2b\x49\xf7\x45\xe1\xa7\ +\xf1\x17\x40\xe2\x47\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x98\ +\x8a\x2f\xe6\x4f\x38\x6a\x74\xad\x97\x2f\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xef\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xa1\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x41\x11\x00\x20\x00\xc3\x30\x0e\x4d\x78\xc2\x0f\x86\x41\x46\ +\x78\x34\x06\xd6\xdb\x18\xd0\xda\xe7\xae\x7d\xae\x6c\x98\x72\xfc\ +\x07\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\ +\xd6\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\ +\x1d\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\ +\x01\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\ +\xa0\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\ +\x3a\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x3a\x40\x07\x68\x1d\xa0\ +\x03\xb4\x0e\xd0\x01\x5a\x07\xe8\x00\xad\x03\x74\x80\xd6\x01\x3a\ +\x40\xeb\x00\x1d\xa0\x75\x80\x0e\xd0\x1e\x06\x73\x04\xd7\x28\x98\ +\xcd\x67\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x52\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x04\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x4f\x14\x51\x14\xc5\xcf\x99\xac\x05\x6c\xa9\x1b\xbe\x7a\ +\x1b\x59\x1a\xe2\x62\x21\x35\x35\x9f\x46\x12\xb1\x93\x68\x02\x5a\ +\xc2\x5f\xa0\x35\x98\x08\xa5\x9a\x48\xc2\x67\x2c\xa9\xb1\x20\x24\ +\x34\x2c\x54\xd6\x2c\x12\xb4\xdc\xa5\x60\x9d\x63\xe1\xb2\x3b\xcc\ +\x0c\x1f\x22\xbb\x77\x37\xbc\x5f\xb5\xf7\xdd\x3b\xc9\x79\x27\xef\ +\xcd\x6c\x71\x2f\xe0\x70\x38\x6e\x33\xbc\x4a\x51\xd7\xba\x92\x4d\ +\x79\x8c\x80\x1a\x22\xd0\x29\xa1\x1d\x40\xa2\xca\xda\xfe\x95\x22\ +\x89\x9c\x80\x5d\x88\xcb\xc7\x49\x2c\xee\xf4\x31\x7f\xd9\x43\x17\ +\x1b\x20\x31\xb3\x86\x31\x42\x6f\x01\xb4\xdd\x94\xd2\x1a\x71\x20\ +\x70\x6a\xab\x1f\x9f\x41\xea\xbc\xa2\x73\x0d\xe8\x9e\xd7\x9d\x44\ +\xca\x9f\x05\x38\x5e\x1d\x7d\xb5\x42\xf3\xc5\x23\x6f\x62\x7b\x9c\ +\x27\x71\xd9\xf8\x63\x2c\x31\xb1\xea\xbf\x07\xf8\x22\x94\xc9\x4a\ +\xfa\x46\x7a\x3f\x48\xf8\x37\x2d\xf5\x7f\x90\xe0\x49\x7e\x2b\xc9\ +\xc7\x00\xd2\x95\x0c\xc7\x13\x29\x1f\x90\x5e\xc6\x9d\x84\xd8\x13\ +\x90\x59\xd5\x18\xa1\x8f\x81\xa5\x5f\x12\x27\xb7\x06\xb0\x70\xd1\ +\x71\xaa\x0b\x24\x66\x56\xf1\x94\xd4\x0c\x80\xbb\xe5\x65\xf0\xf9\ +\xd6\x00\x3f\x85\xcb\x23\x06\xfc\x7d\xe1\xe9\x3b\x2a\x77\xfe\x67\ +\x51\xec\xda\x1e\xe4\x41\xd5\x44\x57\x81\xee\x15\xb5\x25\xa8\x1d\ +\x00\xf7\x4a\x4b\xb9\xe3\x24\xef\x87\x5f\x8c\x5e\xf8\xc1\xa6\x3c\ +\x46\x10\x78\xe1\x49\x7c\xdd\x68\x9b\x07\x80\xed\x41\x1e\x10\x7c\ +\x13\x58\x6a\x6f\x2e\x60\x38\x5c\x17\x31\x00\xd4\x50\x20\xca\x6e\ +\x0d\x60\xa1\x0a\xfa\x6a\xc2\x66\x3f\xbe\x00\xc8\x9e\xc6\x82\x2e\ +\x37\x80\x40\x67\x25\xd0\x46\xdd\xdf\xf9\x8b\x20\x05\x6a\xa3\x1c\ +\x0b\x0f\xc2\x25\x11\x03\x4a\x7f\x72\x4a\x81\x77\x58\x2d\x6d\x35\ +\xe3\xec\x1e\x3a\xc2\xe9\xe8\x15\x08\x7c\x1a\xeb\xed\x53\x77\x1d\ +\x42\x7b\x88\x7c\xf6\xe3\x0c\xb8\x55\x38\x03\xac\x05\x58\xe3\x0c\ +\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\ +\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\ +\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\x16\x60\x8d\x33\xc0\ +\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\x05\x58\xe3\x0c\xb0\ +\x16\x60\x8d\x33\xc0\x5a\x80\x35\xce\x00\x6b\x01\xd6\x38\x03\xac\ +\x05\x58\x13\x67\x40\xf1\xf4\x87\xd4\xf8\x06\x85\xf6\x50\x0c\xe7\ +\xa3\x6d\x72\x44\xae\x12\xf8\x2d\xd5\x91\x55\x43\xce\xee\x61\x3f\ +\x9c\x8e\xb6\xc9\x01\xbb\x95\x80\xbd\x90\xae\x34\x53\x50\x97\x48\ +\x84\xd8\x5b\x8e\x89\xbd\x70\x49\xf4\x88\x8b\xcb\x81\x28\xfd\x68\ +\x15\x23\x55\x11\x57\x03\x7a\xd6\xf0\x04\x81\xce\x71\x82\x4b\xe1\ +\x9a\x88\x01\xc7\x49\x2c\x02\x28\xf7\x06\xfb\xd4\x6c\xcf\x57\x35\ +\xdc\x55\x78\xb8\xa8\x56\x41\x33\x81\xa5\x5c\xa1\x19\x97\x1b\xb0\ +\xd3\xc7\xbc\xc0\xa9\xd3\x98\x40\x4a\xbf\x95\xcd\xac\x68\xb4\x21\ +\xae\x83\xc4\xcc\x8a\x46\x99\xd0\x0e\x81\x54\x79\x19\x9c\x8e\x1b\ +\xa1\x89\xdf\x90\xc4\x9e\x35\xff\x43\xcc\xb4\x48\x16\xd4\x06\xe4\ +\x1d\xd6\x5b\x17\xa9\x04\x0f\xf4\x5b\x4a\x77\x3e\x1d\xcc\x11\x9a\ +\xdb\xec\xf7\x5e\xc5\xf5\x3d\xc7\x4f\x8c\x90\x2a\xce\x6b\x22\x91\ +\xf2\x11\x32\x21\x0d\x31\x0d\x08\xaa\xc7\x16\xea\x98\x03\x4a\x68\ +\xee\xe4\xc8\x9b\x3c\xaf\xe9\xfb\x2a\x43\x53\xcf\x08\xbd\x43\xe3\ +\x0d\x4d\xe5\x04\x4e\x5f\x7b\x68\x2a\x48\xd7\xba\x92\xcd\x05\x0c\ +\x0b\x1a\x2e\xb5\x9c\x77\xa0\x0e\xc7\xe6\x00\xec\x83\xd8\x23\xb8\ +\x54\x68\xc6\xd2\x55\xc6\xe6\x1c\x0e\xc7\xed\xe6\x0f\xfd\x5b\xf6\ +\x1a\x3c\xff\xda\x47\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\xc5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x77\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x0d\xc2\x40\x10\x04\xc0\x3d\xe8\x01\x51\x0a\x75\x20\x3a\ +\x20\x72\x45\xee\x82\x90\x1e\xe8\xc4\xa2\x07\x78\x52\xf4\x8e\x8d\ +\x25\x3c\x13\xae\x2e\xd8\xdb\x04\x00\x00\x00\x00\x00\x00\xd8\x82\ +\xea\x83\xd3\xad\x9d\x5b\xda\x98\xe4\xb0\x42\x9f\x25\x4d\x79\xd7\ +\xf5\x71\xa9\xfb\x77\xb8\xeb\xaf\xfe\xf4\xf9\x24\x39\xd6\xbe\x8d\ +\x7d\x38\x1b\x60\x6b\x66\x03\x54\x6a\x48\xf2\x5c\xa1\xcb\xd2\xa6\ +\xf6\xaa\x61\xed\x12\x00\x00\x00\x00\x00\x00\x00\xc0\xef\x7d\x00\ +\x4e\xfe\x12\x08\x2a\x3f\xe7\x81\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x05\x27\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xd9\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x68\x14\x57\x1c\xc7\xbf\xbf\x99\xd1\x42\xd3\x22\x76\x85\ +\xdd\x90\xa2\x87\xc6\x43\x45\xb0\x24\x5b\xf6\xe0\x65\xa1\xb5\x17\ +\x6d\x2e\x6d\x6a\x4b\x55\x3c\x84\xac\x8d\x36\xe6\xd2\x82\x81\x66\ +\xb2\x81\x62\x6b\x2f\xd9\x60\xc4\xb5\x81\x16\x1a\x5a\x34\xf6\x12\ +\x22\x94\xb4\x87\xa0\xbd\x2c\xd9\x78\x90\xba\xbd\xd8\x83\x21\xd6\ +\xac\x10\x45\x30\x48\xc2\xce\xfc\x7a\x48\x5e\x3b\xbb\x3b\xbb\x3b\ +\x9b\xf9\x9b\x66\x3f\xb0\x87\x79\xf3\x9b\x79\xbf\xf9\xee\xf7\x37\ +\xf3\x66\x78\x0f\x68\xd0\xa0\xc1\x56\x86\xac\x04\xc5\x55\x55\x59\ +\x5e\x0c\x75\xe8\xc0\x51\x02\x45\x01\x6e\x01\xf0\x82\xcb\xb9\xd5\ +\xcb\x0a\x40\x0f\x18\x9c\x95\x80\xab\x4d\x91\xa5\xc9\x99\x64\xb2\ +\x50\xeb\xa0\x9a\x02\x44\x13\x17\x0f\x81\x39\x05\xe2\xd7\x9d\xc9\ +\xd3\x1b\x18\xc8\x11\xa4\xbe\x6c\xfa\xcc\xaf\xd5\xe2\xa4\x2a\xa7\ +\xa0\x68\xf7\x48\x3f\xa0\x4f\x6f\xb6\x8b\x07\x00\x02\xf6\x01\xfa\ +\xf4\x9b\x89\xd4\x39\x80\x2b\xfe\xd1\x72\xa5\x1d\xd1\xee\x50\x3f\ +\x08\x5f\xba\x93\x9e\x97\xd0\x5b\x2d\xd1\xcc\xca\xdf\x73\xbf\xfc\ +\x6e\xba\xd7\xac\x31\x9a\xb8\x78\x08\xd0\xa7\x4b\x9a\x9f\x80\x30\ +\x20\x15\xe8\xc6\x9e\xa7\xe1\xf9\x89\x89\x0f\x34\xc7\x73\xb5\x41\ +\x67\xe7\x35\xf9\xfe\x8e\xfc\x6e\x5d\xe1\xc3\x60\x0c\x01\xd8\x59\ +\x1c\x21\xbd\x63\x56\x0e\x65\x02\xc4\x55\x55\x79\xf6\x70\xd7\x9d\ +\x22\xdb\x13\x7e\x93\x0b\xfa\xb1\xcc\x58\x5f\xde\xf9\xd4\x9d\x27\ +\xd6\x35\x1c\xd6\x14\x69\x1c\x8c\xb7\x45\x1b\x03\xb9\x97\x23\x4b\ +\x07\x4a\x6f\x8c\x65\xf7\x80\xe5\xc5\x50\x47\x49\xcd\x3f\x5e\xc5\ +\xb6\x8f\x37\xcb\xc5\x03\x40\x66\xac\x2f\x2f\x17\xf4\x63\x00\x9e\ +\x88\x36\x02\xf6\x2d\x2f\x86\x3a\x4a\x63\xcb\x04\xd0\x81\xa3\x45\ +\x0d\x04\xf5\xce\xe5\x4f\x1e\xb9\x91\xa8\x9b\x64\xc6\xfa\xf2\x0c\ +\x56\x8d\x6d\x65\xd7\x06\x13\x01\xd6\x9e\xf3\x86\x80\x02\xdd\x70\ +\x3e\x3d\x6f\x90\x35\x69\xca\xb8\x4d\x40\x7b\x69\x8c\xc9\x63\x90\ +\x5b\x8c\x5b\x7b\x9e\x86\xe7\x9d\x4e\xcc\x2b\x4c\x72\x7f\xb5\x34\ +\xc6\x6c\x1c\x50\x34\xc2\x0b\xda\xdd\xbe\x1e\x4c\x72\x2f\x1b\xbd\ +\x56\x19\x08\x6d\x0d\x14\xbf\x13\xb0\x42\x5b\xcf\x68\xab\x54\xd0\ +\x06\x40\x78\x6f\xbd\xe9\x3a\x33\x86\xe6\xae\xf4\xfe\x65\xf7\xdc\ +\x81\x77\x40\x2c\x91\xda\x2b\x69\xda\x4d\x10\x8e\x03\x78\x71\xfd\ +\x77\x82\x08\xb7\xda\x7a\x46\x5b\xed\x9e\x3f\xd0\x02\xc4\x55\x55\ +\xd1\x98\x7e\x02\xd0\x6c\xb2\xbb\x59\xd2\xb4\x2f\xec\xf6\x11\x68\ +\x01\x9e\x3d\x0c\x7d\x0e\x2a\x7f\x74\x19\x78\xdf\x6e\x1f\x81\x15\ +\x20\x7a\x2a\xb5\x1f\x84\x41\xb7\xfb\x09\xa4\x00\x71\x55\x55\xa0\ +\xd3\xf7\x00\xb6\x55\x8b\x23\xa2\x09\xbb\x7d\x05\x52\x00\x0b\xd6\ +\x07\x80\x55\x89\xf9\x82\xdd\xbe\x02\x27\x80\x55\xeb\x13\x78\x30\ +\x93\xee\xcd\xd9\xed\x2f\x50\x02\x58\xb5\x3e\x80\x6c\x53\xe4\xf1\ +\x37\x4e\xf4\x19\x28\x01\xac\x5a\x9f\x74\xe9\xa4\x95\x0f\x9e\x56\ +\x08\x8c\x00\xf5\x58\x7f\xf6\xdb\x33\x77\x9d\xea\x37\x10\x02\xf8\ +\x61\x7d\x81\x23\xef\x02\xed\xdd\x23\xaf\x11\x61\x00\x62\x60\xc2\ +\xf8\x59\x57\xe4\xa1\xdb\x97\x4e\xdf\xb3\x72\xbc\x1f\xd6\x17\xd8\ +\x76\x40\x5b\xcf\x68\x2b\x11\x6e\x01\x38\x01\x31\x56\x27\x1c\x97\ +\x34\xed\x66\x2c\x91\xda\x5b\xeb\x78\xbf\xac\x2f\xb0\x2d\x80\x54\ +\xd0\x06\x50\x61\xac\xae\x81\x7e\x8c\xab\x6a\x45\x97\xf9\x69\x7d\ +\x81\xfd\x7b\xc0\x7f\xaf\xa8\x66\x44\x97\x17\x5f\xf9\xac\xd2\x4e\ +\x3f\xad\x2f\x70\xfd\x26\xc8\xa0\xc1\xe8\xa9\xd4\xfe\xd2\x76\xbf\ +\xad\x2f\x70\x42\x80\xeb\x35\xf6\x6f\x07\xd3\x77\xc6\x52\x08\x82\ +\xf5\x05\xb6\x05\x90\x81\xaf\x01\xac\xd6\x08\x2b\x2a\x85\x20\x58\ +\x5f\x60\x5b\x80\x4c\xba\x37\x07\x46\xb2\x56\x9c\x28\x85\xa0\x58\ +\x5f\xe0\xc8\x3d\xe0\xa5\xe6\xa5\x0b\x60\xcc\xd5\x08\xdb\x0e\x96\ +\x7e\x60\xa6\x71\x04\xc0\xfa\x02\x47\x04\x98\x49\x26\x0b\x90\xf8\ +\x24\x6a\x96\x02\xbf\x41\xc0\x81\x1a\xa7\xf3\xc4\xfa\x02\xc7\x9e\ +\x02\xd9\xcb\x67\xff\xb0\x52\x0a\xb5\xf0\xca\xfa\x02\x47\x1f\x83\ +\x16\x4b\xa1\x1a\x9e\x59\x5f\xe0\xa8\x00\xd6\x4b\xc1\x14\x4f\xad\ +\x2f\x70\x7c\x20\xb4\xd1\x52\xf0\xda\xfa\x02\x57\x46\x82\x1b\x28\ +\x05\xcf\xad\x2f\x70\x45\x80\x3a\x4b\xc1\x17\xeb\x0b\x5c\x7b\x17\ +\xb0\x5a\x0a\x7e\x59\x5f\xe0\xea\xcb\x90\x85\x52\xf0\xcd\xfa\x02\ +\x57\x05\x98\x49\x26\x0b\xba\x22\x7f\x08\xc0\x6c\x92\xc5\xbc\x2e\ +\xcb\x1f\xf9\x65\x7d\x81\xeb\xaf\xc3\xb7\x2f\x9d\xbe\x27\x6b\x38\ +\x48\xe0\x29\x00\xcf\x01\x3c\x27\xf0\x94\xac\xe1\xa0\xd5\x4f\x66\ +\x6e\xe2\xc9\xfc\x80\xcc\x58\xef\x02\x80\x77\xbd\xe8\xab\x5e\x02\ +\xf1\x55\xd8\x4f\xcc\x04\x58\x31\x6e\x74\x76\x5e\xab\x38\x9d\x36\ +\xe8\x98\xe4\xbe\x52\x1a\x63\x22\x00\x3d\x30\x6e\xdd\xdf\x91\xdf\ +\xed\x68\x56\x1e\x62\x92\xfb\x42\x69\x4c\x99\x00\x0c\xce\x1a\xb7\ +\x75\x85\x0f\x3b\x9c\x97\x67\x68\xb2\x7e\xc4\xb8\xcd\x28\x7f\x24\ +\x97\x09\x20\x01\x57\x8b\x1a\x18\x43\xb1\xae\xe1\xb0\xe3\xd9\xb9\ +\x4c\xac\x6b\x38\x4c\xa0\xa2\x81\x58\xd9\xb5\xc1\x44\x80\xa6\xc8\ +\xd2\x24\x98\xfe\x34\x34\xed\xd4\x14\x69\x7c\x33\x89\xf0\xef\x64\ +\x69\xc3\x8c\x71\x06\x72\x4d\x91\xa5\xc9\xd2\xd8\xba\xa6\xcb\x33\ +\x58\x95\x35\x69\x2a\xc8\xd3\xe5\x35\x59\x3f\xb2\xfe\xcf\x6f\x6c\ +\xba\xbc\x20\xda\x3d\xf2\x3f\x59\x30\x01\x10\xb8\x7f\x36\x7d\xf6\ +\xbc\xd9\xbe\x8a\xe3\x80\xec\x95\x4f\xcf\x13\xb8\xdf\xbd\xb4\x3c\ +\x81\x99\xe9\xdc\x6c\xba\xf7\xab\x4a\x01\x96\x16\x4d\x31\xf4\xe1\ +\xb5\x35\x38\x9b\x07\xab\x8b\xa6\x36\xb0\x6c\x0e\xed\x58\x9b\x75\ +\x1d\xc0\x65\x73\x58\x60\x60\xae\x9e\x65\x73\x0d\x1a\x34\xd8\xda\ +\xfc\x03\xf8\xad\xf2\xfb\x1a\x49\x36\xd6\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x39\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xbf\x4e\xc2\x50\x14\xc7\xf1\xef\xb9\x21\x30\x5a\x17\x7c\x86\ +\xbe\x40\x5f\x80\x8a\x4c\x26\xa8\x1b\x23\x98\xb0\xd6\x59\x1d\x64\ +\x87\x95\x44\x57\x46\x65\x34\x22\x4f\xd0\x17\xe8\x3b\xb0\x50\x47\ +\x08\xe1\x38\x94\x2a\x7f\x5d\x6c\xe3\xe0\xfd\x8d\x37\x37\xfd\x7d\ +\xd2\xbb\x9c\x03\xff\x3d\xb2\x7d\xe0\x5f\x5e\x9f\x09\xdc\x80\x7a\ +\x80\x93\x51\x4f\x0c\x12\x2a\x74\xc7\xcf\x8f\x6f\x07\x01\xfe\x55\ +\xb3\x23\x2a\xb7\xc0\x0c\x88\x50\x3e\x32\xa9\x17\x8e\x00\x17\x28\ +\xa1\x74\xde\x5f\x9e\xee\x77\x00\x95\x7a\xb3\x66\x8c\xbc\x0a\x8c\ +\x59\x16\x1a\xa3\x61\x7f\x92\x49\xf9\x2a\xd5\x7a\xbb\x8c\x59\x0c\ +\x14\x7c\x45\x6a\xe9\x9f\x30\xe9\x05\x63\x4c\x00\xcc\xf2\x28\x07\ +\x18\x0d\xfb\x13\x96\x85\x06\x30\x17\x34\xf8\xea\xfd\xbe\xa2\x1e\ +\x10\xe5\x51\xbe\x81\x40\x22\x14\x6f\x0f\x00\x27\xb3\x37\xff\x29\ +\xaa\x31\xc2\xf1\x3e\xc0\x9f\xc4\x02\x2c\xc0\x02\x2c\xc0\x02\x2c\ +\xc0\x02\x2c\x60\x1d\x10\xaf\xa6\xd7\x7c\x23\xe2\xa0\x4c\xf7\x00\ +\x24\x04\xdc\x6a\xbd\x5d\xce\xab\x3b\xf9\xb6\xba\x08\xe1\x0e\x40\ +\xa1\x0b\x94\x30\x8b\x41\x1e\x88\xca\x79\xeb\x04\xb3\x18\x00\x45\ +\x45\x7a\xe9\xf9\xc6\x62\x72\x7a\xd1\x7a\x40\xb8\x03\xe6\xc9\xf4\ +\xaa\x71\x26\xed\x22\x0e\xa8\x0b\x14\x0f\x2e\x26\x69\x92\xd5\x4c\ +\x03\x14\x6f\x7d\x7a\xfd\x55\x94\x29\x42\xa8\x48\x6f\x7b\x35\xb3\ +\xf9\x04\xc3\x25\x66\x2f\xe5\x8f\x2b\x3d\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\x4e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x00\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4f\x4f\x13\x51\x14\xc5\xcf\x41\x40\x09\x4b\xad\x94\x3f\xb6\ +\x0d\x0b\x37\x80\x2b\x96\xf2\x2d\x00\x23\x89\xb8\x93\x68\x22\xba\ +\x84\x4f\xa0\x6b\x35\x11\x97\x6a\x22\x89\xf0\x2d\x70\xc9\x8a\xc2\ +\xca\x05\x43\x0b\xa5\x50\x5d\x12\xb4\x20\xc7\x05\x2d\x0e\xd3\x81\ +\x56\xe2\xf4\xb6\xf2\x7e\xab\xd7\xfb\xde\x34\xe7\x9e\xbe\x37\xaf\ +\x8b\x7b\x01\x87\xc3\x71\x99\x61\x2d\x8b\xf2\xf9\x7c\xe7\x7e\xb1\ +\x38\x4e\x71\x14\xc4\x20\x84\x1e\x00\xad\x11\x6b\xfb\x5b\x0e\x41\ +\xe4\x20\xac\x8a\x5a\xec\x68\x6f\xff\x1c\x8f\xc7\xf7\xaa\x3d\x74\ +\xae\x01\x92\xe8\x65\xb6\x26\x09\xbd\x00\xd0\xfd\xcf\xa4\xd6\x87\ +\x6d\x82\x33\x89\x44\xef\x47\x92\x3a\x6b\xd1\x99\x06\x2c\x2f\x2f\ +\xb7\xc5\x62\x37\x5f\x0b\x9c\x8a\x46\x5f\x7d\x20\xf4\xae\x50\xd8\ +\x7d\x3a\x3c\x3c\x7c\x10\x36\x1f\xba\x8d\x8f\x7f\xf9\xcd\x37\x02\ +\x1e\x9d\x8a\x03\x69\x8a\x5f\x48\xe5\x25\x1d\x45\x21\xf8\xa2\x90\ +\x6c\x91\x18\x17\x75\x97\xc0\x50\x39\x2e\x70\x2a\x16\xbb\x09\x49\ +\x8f\xc3\x76\x42\xe8\x0e\xd8\xd8\xd8\x9c\x14\xf4\xde\x17\xfa\x0e\ +\x61\x3a\x99\xec\x9b\x3f\x6f\x3b\x35\x02\x92\xb8\xb1\xb1\x79\x1f\ +\xc4\x2b\x00\xd7\xcb\x71\x82\x0f\x93\xc9\xbe\x0f\xc1\xf5\x15\x06\ +\xe4\xf3\xf9\xce\x1f\x3f\x0f\xbe\xe2\xcf\x99\xff\x06\xfd\xba\x93\ +\x4a\xa5\xb6\x23\x53\x1d\x01\x9e\xe7\x75\x83\x57\x56\x00\xdc\x28\ +\x85\x72\xd7\xae\xb6\xdd\x0e\xbe\x18\x5b\x82\x0f\xee\x17\x8b\xe3\ +\xf0\xbf\xf0\x84\x67\xcd\x96\x3c\x00\xa4\x52\xa9\x6d\x08\xcf\x7d\ +\xa1\x9e\xfd\x62\x71\x2c\xb8\xae\xc2\x00\x8a\xa3\xe5\xb1\x80\x74\ +\x32\xd9\x37\x1f\x91\xc6\xc8\x49\x26\xfb\x3e\x09\x48\x97\x3f\x53\ +\xac\x6e\x00\x88\x41\xdf\x03\x4b\x8d\x7e\xe6\xcf\x83\xa4\x28\x2e\ +\xf9\x42\x03\xc1\x35\x95\x06\x1c\xff\xc9\x29\x7d\x81\x76\xa2\x91\ +\x56\x3f\x02\x39\xf4\x06\xe7\x2b\x0d\xf0\x5d\x8d\x8d\x76\xd5\x5d\ +\x84\x40\x0e\x15\xd7\x7e\x98\x01\x97\x0a\x67\x80\xb5\x00\x6b\x9c\ +\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\ +\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\ +\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\xd6\x02\xac\x71\x06\ +\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\xb5\x00\x6b\x9c\x01\ +\xd6\x02\xac\x71\x06\x58\x0b\xb0\xc6\x19\x60\x2d\xc0\x1a\x67\x80\ +\xb5\x00\x6b\xc2\x0c\x38\x2c\x0f\x48\x36\xbd\x41\x81\x1c\x0e\x83\ +\xf3\x61\x65\x72\xb9\xf2\x50\x62\x57\x34\xb2\xea\x47\x20\x87\xad\ +\xe0\x7c\x58\x99\xdc\xea\xc9\x90\x1a\x91\x54\x53\x4f\x41\x23\x22\ +\x89\xa2\x46\x7c\xa1\xb5\xe0\x9a\x0a\x03\x44\x2d\x96\xc7\x04\x86\ +\xbc\x6c\x76\x3c\x22\x7d\x91\xe3\x65\xb3\xf7\x4e\x55\x8e\x53\x0b\ +\xc1\x35\xd5\x8b\xa5\x85\xc2\xd1\xd1\xc1\x50\x7f\x7f\x7f\x53\x15\ +\x4d\xae\xaf\xaf\xc7\xc9\xd6\x15\x10\xb1\x52\xa8\xb6\x62\xe9\x78\ +\x3c\xbe\x47\x70\xe6\x24\x40\xc4\x5a\x5a\xda\xd2\x9e\x97\x9d\x68\ +\x86\xe3\x20\x89\x9e\x97\x9d\x08\x24\x0f\x82\xb3\x61\x2d\x34\xa1\ +\x09\x49\x62\x26\x93\x7d\x1b\xec\x16\x29\x35\x4c\x2c\x91\xda\x69\ +\xb4\x2a\xd2\x52\xc3\x44\x97\xa8\x11\xff\xb6\x07\x00\x42\x73\x89\ +\xc4\xad\x27\x35\x37\x4c\x00\xff\x55\xcb\xcc\x5c\xa1\xb0\x3b\x7d\ +\x56\xcb\x4c\xd5\xa6\xa9\x4c\x66\xeb\x81\xa0\x97\x68\xbe\xa6\xa9\ +\x1c\xc1\xd9\x0b\x37\x4d\xf9\x29\xb5\xcd\x8d\x95\xea\xed\x07\x70\ +\x5c\x75\xdd\x78\x6d\x73\xc7\xf7\xfc\x9a\xa8\x85\x8e\xf6\xf6\x85\ +\x5a\xda\xe6\x1c\x0e\xc7\xe5\xe6\x37\x49\x9a\x11\x82\x28\x6e\xc8\ +\x6e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x78\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x2a\x49\x44\x41\x54\x58\x85\xed\ +\xce\x41\x11\x00\x20\x0c\x04\xb1\x16\xff\x22\xe9\x20\x04\x64\x1c\ +\x8f\xc4\xc0\x6e\x15\x00\x10\xd6\x7b\xce\x4d\x0e\xac\x64\x1c\x00\ +\xf8\xc2\x03\x48\xae\x03\xa7\xd4\xed\xa0\x47\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x06\x65\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x06\x17\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xc9\x73\x5c\xd5\x15\x87\xbf\x73\x5b\x31\x32\x83\x4c\x6c\x50\ +\x00\xf5\x1b\x5a\x15\x6f\xb0\x31\x93\xc1\x98\xa4\x12\x2c\x1c\x24\ +\x83\x6d\xe5\x6f\x61\x05\x8b\x64\x91\xf2\x82\x0d\xcb\xe4\xef\xa0\ +\x98\xca\xd6\x18\x46\x43\x85\xa4\x42\x80\x2a\xaa\x28\xd4\x6f\x90\ +\x29\x07\xc7\x0e\x96\x71\x2c\x19\xeb\x1e\x16\x52\x3b\xe2\x75\xab\ +\xfb\xbe\xee\xf7\x24\x51\xe8\x5b\xde\x77\xfa\xbe\xf3\xfb\xfa\xdc\ +\x1e\xa4\x86\x6d\xb6\xd9\xe6\xa7\x8c\xb4\x5a\x3c\x7f\xfe\xfc\x6d\ +\x8b\x8b\xd7\x9f\x57\x91\x13\x40\x3f\x70\x56\x74\xf9\xa5\x30\x0c\ +\xeb\x1b\xdb\x5e\x77\x44\x51\x54\x53\xa9\xbc\x00\x1c\x06\x16\x0d\ +\xbc\xb1\x73\xe7\x2d\x2f\x0f\x0e\x0e\x7e\x9b\xad\x6d\x12\xf0\xf9\ +\xe7\x17\xee\xe8\xdf\xb9\xf8\x16\xf0\x70\xe6\xd2\x65\x35\x8c\xd6\ +\x3c\xef\xc3\x72\xda\x2e\x86\x24\x49\x1e\xb3\x2a\x93\xc0\xae\x1f\ +\x5c\x10\x3e\xfe\x6e\x69\xf1\x37\x7b\xf7\xee\x5d\x58\xbb\x6c\xb2\ +\x1b\xf4\xf7\x5f\x7b\x81\xe6\xf0\x00\xbb\xc4\x32\x51\x4f\xd3\x43\ +\x45\x36\x5c\x24\xeb\x86\x07\x50\x1e\xdc\xb1\xa3\xff\xc5\xec\x72\ +\x93\x00\x44\x4e\xb6\xb9\xc7\xc0\x56\x95\xd0\x36\xfc\x2a\x8a\x8e\ +\x67\xd7\x9a\x05\xc0\xce\x0e\xf7\x1a\x10\xcb\xc4\x5c\x9a\x3e\x9e\ +\xb3\xc7\xd2\x48\x92\xe4\x60\xa7\xf0\x2b\x48\x7f\x76\xa5\x49\x80\ +\xa2\xef\x39\xdc\x73\xc0\x58\x26\xb7\x82\x84\xd5\xf0\x53\x74\x0c\ +\x0f\x40\x53\xb6\x26\x01\x7d\x46\x4e\x01\x97\x1d\x36\xdb\x74\x09\ +\x39\xc3\x2f\x54\x0c\x7f\xca\x2e\x36\x09\xf0\x3c\xef\x0b\x6b\x78\ +\x06\x77\x09\x9b\x72\x1c\xdc\xc7\x1e\x80\x05\xb5\x32\xea\x79\xde\ +\x17\xd9\x0b\x2d\x3f\x07\x00\xcc\xa5\xe9\xe3\xc6\x32\x09\x0c\x38\ +\xdc\xe0\xb2\x11\xfd\x9d\xef\xfb\x7f\x73\xa8\xed\x99\x38\x8e\x1f\ +\x55\xcc\x14\x70\xa7\x43\xf9\x15\xb5\xf2\x4c\xad\x56\xfd\xa0\xd5\ +\xc5\x75\x05\xc0\xd6\x94\x50\x64\x78\xe8\x20\x00\xb6\x96\x84\xa2\ +\xc3\x83\x83\x00\x80\x7a\x9a\x1e\x12\xcb\x04\xee\x12\x8e\xfa\xbe\ +\xff\x91\xcb\xde\xae\x44\xd1\x57\x8f\x20\xcb\x53\xc0\xcf\x1d\xca\ +\xaf\xa0\x32\x1a\x86\xd5\xb3\x9d\x0a\x9d\x04\xc0\xe6\x4a\x28\x2b\ +\x3c\xb4\xfe\x20\xd4\x92\x9a\xe7\x7d\xa8\x56\x46\x81\x85\x8e\xc5\ +\xb0\xcb\xaa\x4c\x25\x49\x72\xd0\x75\xff\xf5\xc8\x1f\xde\x8c\xb9\ +\x86\x87\x1c\x13\xd0\xa0\x5e\x9f\x7f\x42\x8c\x4e\x00\x77\x38\x94\ +\x7f\xb3\xfa\x9a\xd0\xd5\x24\xe4\x0c\xff\x2d\x6a\x46\xc3\x70\xe8\ +\xfd\x3c\xf7\xc8\x2d\x00\xf2\x4b\x10\xec\xd1\x20\x08\xfe\x9e\xe7\ +\x1e\x1b\x11\x1e\xba\x14\x00\xe5\x4a\x88\xa2\x73\x0f\x23\x76\x9a\ +\x92\xc3\x43\x0f\x02\x00\xa2\x68\xfe\x30\xa2\x67\x28\x50\x42\xde\ +\xf0\x82\x19\x0b\x82\x21\x97\xef\x2f\x2d\xe9\x49\x00\x14\x2b\x61\ +\xa3\xc3\x43\x8e\x77\x81\xf5\x08\xc3\xea\x59\xd4\x8c\x01\x57\x1c\ +\xca\xef\x54\xcc\x64\x14\x7d\xf5\x48\xf6\xc2\x6a\x78\xe7\x33\x2f\ +\xd8\x63\xbd\x86\x87\x02\x26\xa0\x41\x14\x9d\x7b\x12\xb1\x67\x80\ +\xdb\x1d\xca\xff\x8b\x56\x8e\x86\xe1\x7d\xff\x00\xa8\xd7\xe7\x1f\ +\x12\xa3\xd3\xc0\x6e\x87\xc7\x5e\x15\xec\x58\x10\x04\xef\xf6\xd2\ +\x6f\x83\xc2\x04\x40\x77\x12\x54\xad\xdd\xac\xf0\x50\xb0\x00\xc8\ +\x29\x41\x59\x50\x14\x11\x71\xf9\x74\x59\x78\x78\x28\x41\x00\x40\ +\x1c\x9f\xfb\x95\x62\x4f\xe3\x36\x09\x2e\x5c\x35\xa2\xc7\x7c\xdf\ +\x7f\xa7\xa0\xfd\x6e\x52\x8a\x00\x28\x54\x42\x69\xe1\xa1\x80\x77\ +\x81\xf5\x08\x82\xa1\xf7\x04\x7b\x0c\x68\xfa\x67\x44\x0e\xae\x5a\ +\xd1\x67\xcb\x0a\x0f\x25\x4e\x40\x83\x38\x8e\x7f\xad\x98\xd3\xc0\ +\x6d\x39\x1f\x7a\xd5\x8a\x3e\x3b\xec\xfb\x6f\x97\xd1\x57\x83\xd2\ +\x05\xc0\xaa\x04\x35\x13\x48\xc7\x3f\xb9\x37\x58\xb4\xa2\xa3\x65\ +\x87\x87\x12\x8f\xc0\x5a\x96\x8d\x59\x40\xb8\xee\x5a\xaf\x70\x5d\ +\x96\x8d\xcb\xd7\xee\x9e\x29\x5d\xc0\x5c\x9a\x1e\x30\x96\x19\xdc\ +\xfe\x7a\x0b\x80\xc0\x80\x18\x9d\xae\xd7\xe7\x1f\x2a\xb1\xb5\xc6\ +\xbd\xca\x63\x4d\xf8\x3d\x5d\x6e\x71\x49\xad\x3c\x5d\xab\x55\xff\ +\x59\x64\x5f\x6b\x29\x6d\x02\x56\xc3\x4f\xd3\x7d\x78\x80\xdd\x62\ +\x74\x7a\x6e\x6e\xfe\xc1\xa2\xfa\xca\x52\xca\x04\xa4\x69\xfa\xc0\ +\xf2\xca\x33\x7f\x57\x41\x5b\x5e\xb2\xcb\x32\x32\x3c\x5c\xfd\xb8\ +\xa0\xfd\x6e\x52\xf8\x04\xe4\x0c\xbf\xa4\xaa\x4b\x0e\x75\xbb\x4d\ +\xa5\x9c\x49\x28\x54\x40\xce\xf0\xd7\xd4\x32\xa6\x2b\xff\x86\xfb\ +\x9f\x43\xfd\x9e\x32\x24\x14\x76\x04\x92\x24\xd9\x6f\x55\x66\x71\ +\x0c\x8f\xca\x73\x61\x58\x9d\x05\xa8\xa7\xe9\x6f\xc5\xf2\x26\x70\ +\xab\xc3\x63\x2f\x5a\xc3\xc8\xb0\xe7\xfd\xab\x97\x7e\x1b\x14\x22\ +\xa0\x97\xf0\x0d\x36\x4b\x42\xcf\x47\xa0\x8b\xf0\xc7\xb3\xe1\x01\ +\x6a\x9e\xf7\x96\x5a\x9e\xc3\xf5\x38\x58\x66\xe6\xd2\xf4\x40\xde\ +\x7e\xb3\xf4\x24\x20\x49\x92\xfd\xd6\x8a\xf3\x99\x5f\x0d\x3f\xb3\ +\x5e\x41\xad\xe6\xfd\x35\xa7\x84\xe9\x5e\x25\x74\x7d\x04\x6e\x86\ +\x17\xee\x76\x28\xbf\x26\xc8\x89\x20\xa8\x4e\xbb\xec\x5d\xaf\xa7\ +\x4f\x89\xe1\x4d\x3a\xff\x5c\x07\xe0\x3f\x15\xc3\x88\xe7\x79\x9f\ +\xb8\xec\x9d\xa5\x2b\x01\x71\x1c\xef\x53\x35\xb3\x8e\xe1\x17\x05\ +\x39\xee\x1a\xbe\xc1\x46\x49\xc8\x2d\x60\x23\xc2\x37\x88\xa2\xf9\ +\x23\x88\xbe\x41\x89\x12\x72\x09\x88\xe3\x78\x9f\x62\x66\x80\x41\ +\x87\xf2\x9e\xc2\x37\xc8\x2b\xc1\x88\x1e\xf1\x7d\xff\x53\xd7\xfd\ +\x9d\x5f\x04\xf3\x87\x37\xce\x67\xbe\x1d\x61\x58\x9d\x45\xe5\x38\ +\x70\xcd\xa1\xfc\x2e\xab\x32\x9b\x24\xc9\x7e\xd7\xfd\x9d\x26\x20\ +\x8e\xe3\xfb\x15\x33\x4b\xae\xf0\x43\x53\xae\x4d\xb8\x10\x45\xf3\ +\x23\x88\xbe\x4e\xc1\x93\xd0\x71\x02\xf2\x87\xb7\x27\x8b\x0e\x0f\ +\x10\x86\xd5\x19\x41\x4e\xe0\x3a\x09\x56\x66\x5c\x26\xa1\xed\x04\ +\x74\x17\x3e\x98\x74\xa8\xed\x9a\x38\x9e\x7f\x5a\xd1\xd7\x59\xf9\ +\x15\x7b\x7b\x94\x0b\xc6\xe8\x48\xbb\x49\x58\x77\x02\x56\xc2\x57\ +\x9c\xcf\xbc\x15\x1d\x2f\x3b\x3c\x40\x10\x54\xa7\x05\x39\x0e\x2c\ +\x76\x2c\x16\xee\xb6\x56\x66\xe2\x38\xde\xb7\x7e\x49\x0b\xfe\x1f\ +\x5e\x7f\xe1\xd0\xd3\x92\x15\x3d\x39\xec\xfb\x13\x0e\xb5\x85\x91\ +\x77\x12\x44\xec\x91\x20\x08\x3e\xcb\x5e\x6a\x12\x90\xa6\xe9\xd0\ +\xb2\xe5\x23\xe0\x1e\x87\x3e\x36\x25\x7c\x83\x38\x3e\x77\x54\xb1\ +\xaf\xe1\x22\x01\xbe\xbe\xd1\x67\x0e\xfe\x72\x68\x28\x5d\xbb\xd8\ +\x74\x04\xac\xd5\x3f\xf0\x23\x08\x0f\x10\x04\x43\x53\x82\x39\x81\ +\xcb\x71\x80\xc1\xbe\x1b\xf6\x8f\xd9\xc5\x16\xbf\x16\x97\xa7\x1c\ +\x36\x5b\x52\xd1\xf1\xcd\x0c\xdf\x60\x45\x82\x3d\x89\x9b\x84\x23\ +\xd9\x85\x56\x2f\x82\xcb\x1d\x36\x59\x52\xd1\xf1\x9a\xef\x9f\x71\ +\x69\x70\x23\x08\x82\x60\xd2\x49\x82\x36\x67\x6b\x12\x20\x68\xbb\ +\x67\x75\x49\x0d\xbf\xdf\x4a\xe1\x1b\x04\x41\x30\x69\x45\xc7\x69\ +\x23\x41\x85\xd3\xd9\xb5\x26\x01\x95\x8a\x39\x05\x7c\xd9\xe2\xf1\ +\x2b\xe1\x3d\xaf\x69\x93\xad\xc2\xb0\xef\x4f\xb4\x91\x50\xbf\xb1\ +\xa3\xef\x54\x76\xb1\x49\x40\xb5\x5a\xbd\xf8\xb3\x3e\xf3\x04\xc2\ +\x9f\x81\x18\xf8\x5a\x91\x57\xd1\xca\x93\x5b\x39\x7c\x83\x61\xdf\ +\x9f\x50\x2b\x87\x51\x5e\x01\xf9\x37\x10\xa3\xf2\x97\xef\x76\xf4\ +\x1d\xda\x7b\xef\xbd\x17\x36\xbb\xbf\x6d\xb6\xd9\x66\x6b\xf1\x3d\ +\x64\x29\x23\xc7\x02\xc7\xba\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x01\x06\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb8\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\xc1\x0d\x83\x50\x10\xc4\xd0\x0d\xa2\x24\x7a\xe2\x46\x31\xdc\ +\xe8\x29\x3d\x91\x32\x5e\xa4\x6f\x37\xb0\x96\x35\xb7\x9d\x81\x1c\ +\xe7\xfd\x1e\xe7\xfd\x4a\x87\x4d\x1e\xff\x07\x0a\xa0\x05\x34\x05\ +\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\ +\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\ +\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\ +\xa0\x59\x3e\xc0\x47\x1e\xd7\xaf\xf1\x99\x16\x30\xbb\x16\x98\x99\ +\xf9\x3e\x17\x5b\xe2\xf2\x0b\x28\x80\x16\xd0\x14\x40\x0b\x68\x0a\ +\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\ +\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\ +\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\x80\x66\xf9\x00\ +\x3f\xfa\xaa\x08\xd8\xe7\x6a\x2c\xe4\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x04\x72\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x24\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x88\x1c\x55\x14\x85\xbf\x5b\xdd\x09\x8a\x8a\x20\x2a\x62\ +\x4f\x57\x75\x0d\x19\x14\x77\xc2\xe0\x52\x50\x34\x1a\xc4\xe0\x0f\ +\xe8\x4a\x44\x51\xd0\x85\x18\x41\x11\x74\x11\x21\x8a\x11\x04\x17\ +\x22\x1a\x70\xe3\xc2\xa0\xae\xc2\x80\x46\x47\x5d\x08\x82\xe0\x42\ +\x10\x44\x82\x66\xa6\xe7\x75\xcd\x24\xd1\x88\x8a\x60\x18\xec\xee\ +\x77\x5d\xcc\x88\x55\x35\x43\x98\x21\xef\xbd\x7a\x9a\x3e\xcb\x73\ +\xa0\xee\x7d\xa7\xee\x7d\x3f\xf5\x03\x13\x4c\x30\xc1\x04\xff\x01\ +\x18\xb3\xb2\xdf\x0c\x8a\xe1\x92\x29\x46\xc6\x14\x2f\xb8\xba\xae\ +\xb8\xba\x90\x4f\x2c\x2d\x2d\xdf\x84\xe8\xe7\xfc\x9b\xaf\xed\x65\ +\xdd\x96\x8b\x6b\x27\x2e\x2e\xe2\x13\x83\xc1\x60\x16\xd1\x39\x4a\ +\x37\x4b\x55\x9d\xe5\x1d\xb5\x01\xfd\xfe\xca\xb5\x56\xe5\x28\x70\ +\x71\x99\x17\x11\xeb\x2a\x46\xb4\x06\x2c\x2c\xac\xa4\x49\x62\xe7\ +\x81\xcb\x37\x91\xd5\x55\x9c\x28\x0d\xf8\xf1\xe4\xc9\x2b\x5a\x6d\ +\x3b\xaf\xd0\xf5\x1d\x2b\x3a\x03\x8e\x1d\x3b\x7d\xc9\x8e\xbf\x46\ +\x1f\x01\xd7\x84\x88\xd7\x0e\x11\x64\xab\xe8\xf7\xfb\x17\x48\xb2\ +\x7a\x04\x98\xad\x49\x8a\xa7\x15\x2b\x9a\x0a\x50\xd5\xb6\xb4\xda\ +\x87\x81\x9b\xeb\x12\xe0\x6c\xd2\xab\x23\x0a\x03\x54\x55\x4c\xb1\ +\x7c\x08\xe5\xee\xaa\x22\x5e\x07\x0f\x91\x18\x60\x06\xcb\xaf\xa0\ +\x3c\x5c\xe6\x44\x50\x50\xaf\x83\x87\x08\xe6\x00\x63\x8a\x67\x15\ +\x9e\x29\x73\xba\xb6\xc8\x79\x1f\x3c\x34\x5c\x01\xc6\x14\x8f\x2a\ +\x1c\xac\xf3\x22\x8c\x43\xe5\xd0\x98\x01\x4b\x4b\xc5\xbd\x0a\x6f\ +\x6d\x54\xfc\x97\x7d\x19\x8d\x18\x60\xcc\xca\x2d\x08\x87\x37\xc4\ +\x57\xec\xfa\xc4\x17\x0c\xc1\x0d\x58\x2c\x8a\x1b\x14\x7b\x04\xd8\ +\x59\xe6\x15\x2c\xe2\x6e\x8b\xbb\x55\x04\x9d\x04\x8d\x31\xd7\xa9\ +\xe5\x28\x70\x51\x4d\xb2\xe2\x70\x7f\xbf\x1d\x04\xab\x80\xc5\xc5\ +\x13\x99\x92\xcc\x03\x97\x55\x04\xc1\xd2\xd0\xe0\x21\x90\x01\xc7\ +\x8f\x9f\xba\x52\x5a\xe3\x4f\x81\x4e\x99\x17\xb0\x68\x73\x83\x87\ +\x00\x2d\xb0\xb0\xb0\x70\x69\xab\x3d\xfc\x18\x98\xa9\x2a\xaa\x1a\ +\x78\xc2\xdb\x0c\x5e\x0d\x28\x8a\xe2\x42\x6b\x99\x53\xb8\xbe\x26\ +\x29\xb8\x7b\xa8\x71\x2e\xf0\xd6\x02\xaa\xda\x1e\x59\x79\x4f\xe1\ +\xc6\xba\x44\xa0\x5d\xde\x56\xe0\xc5\x00\x55\x4d\x06\x83\xe2\x6d\ +\x41\xf7\x96\x79\x89\x6c\xf0\xe0\xc1\x00\x55\x15\x63\x8a\x57\x15\ +\x79\xb0\xcc\x8b\xa0\x1a\xd9\xe0\xc1\xc3\x1c\x60\x8a\xe2\x39\x44\ +\x9e\x2a\x73\x21\x0f\x37\xdb\x85\xd3\x0a\xe8\x0f\x96\x1f\x43\xe5\ +\xc5\x3a\x1f\xf2\x70\xb3\x5d\x38\x33\xa0\x6f\x8a\x83\xa2\xfa\xe6\ +\x46\x25\xec\xe1\x66\xbb\x70\x66\x80\xd4\x1e\x68\xc0\xfa\xfe\x3e\ +\x82\xb5\xfe\x6c\x70\xd7\x02\x9b\x94\x79\x03\x67\x9b\x6d\xc3\x5d\ +\x05\x20\x4f\x52\xdb\xd3\x2b\x12\xc5\x23\xb7\xb3\xc1\x59\x82\x59\ +\x36\xf5\x01\xaa\x4f\x94\x39\x01\x14\x5a\x31\xbf\x83\x75\x7a\x87\ +\x7a\xbd\xf4\x0d\x81\xfd\x65\x4e\x00\xd4\x46\x6b\x82\xf3\x12\x4d\ +\xd3\xa9\x03\xc0\xeb\x15\x52\x04\xc4\xdd\x1b\x5d\x97\x70\x9e\x94\ +\x88\x68\x96\x4e\xed\x03\xde\xad\x08\x8a\x20\x71\x3c\x86\x2f\xc3\ +\x4b\x42\x22\x62\x7f\x39\xfd\xd3\x43\xc0\x87\x15\x41\x11\x90\x44\ +\x22\xea\x06\x6f\x77\x64\x76\x76\x76\xb8\xa3\x9d\xdc\x07\xf2\x65\ +\x55\x51\x71\xf9\x81\xc3\xb9\xc2\x6b\x22\x9d\x4e\xe7\x8c\xda\xe1\ +\x9d\x08\xdf\x56\x15\x11\x34\x8e\x76\xf0\x9e\x44\x9e\xe7\xbf\xeb\ +\x78\x74\x3b\xb0\x50\x11\x04\x41\x9a\x6f\x86\x20\x77\x21\xcf\xf3\ +\x53\xe8\xf8\x56\xe0\x44\x45\x50\x4d\xd6\x96\x88\xe6\x10\xac\x0c\ +\x7b\xbd\x5e\x3f\x11\xbd\x0d\xf8\xad\xaa\x68\x42\x83\x9b\x84\xa0\ +\x7d\x98\xa6\xe9\x77\xa8\xdc\x01\x9c\xa9\xe7\xa1\x0d\x99\x10\x7c\ +\x22\xea\xf5\xa6\xbe\x52\xd1\x7b\x80\x61\x99\x17\x48\x54\xc3\x9b\ +\xd0\xc8\x4c\x9c\xa7\xe9\x27\x2a\xfa\x00\xb5\xc3\x93\x08\x09\x68\ +\x50\x13\x1a\x5b\x8a\xf2\x34\x7d\x5f\x91\xc7\x37\x2a\x61\x4f\x90\ +\x8d\xae\xc5\x79\x36\x75\x08\x91\xe7\xeb\xbc\x2a\x4e\x3e\x83\xdd\ +\x0a\x1a\xdf\x8c\x64\xdd\xce\xcb\xa8\xbe\x56\xe6\x44\xfe\x69\x07\ +\xff\x68\xdc\x00\x11\xd1\x2c\xeb\x3e\x2d\xe8\x3b\x65\x5e\xd7\xcf\ +\x0d\xbe\xe3\x37\x6e\x00\xac\x1d\x9e\xd2\xb4\xfb\x88\x22\x73\x55\ +\x45\x05\xcf\x39\x46\x61\x00\x80\x88\x8c\xb0\xc3\xfb\x51\xbe\xa8\ +\x4b\x78\xcc\x33\x1a\x03\x00\xf2\x3c\x5f\x1d\x0e\x57\xf7\x82\x7e\ +\x53\x93\xbc\x2d\x8d\x51\x19\x00\x30\x33\x33\xf3\xc7\x68\xb8\x73\ +\x0f\xca\x0f\x21\xe2\x45\x67\x00\xc0\xae\x5d\x57\xfd\x6c\x6d\x6b\ +\x37\xb0\xe2\x3b\x56\x94\x06\x00\x4c\x4f\x5f\x6d\x04\xbb\x1b\xf8\ +\x75\x13\xd9\x59\x4b\x44\x6b\x00\x40\x96\x65\xdf\xdb\x84\x3d\xc0\ +\x9f\x65\xfe\xbc\xf9\x65\x06\x60\xba\xdb\xfd\x5a\x48\xee\x2a\xbf\ +\x62\x3b\x2f\x7e\x99\x29\x23\xcb\x3a\x9f\x09\x72\x00\x18\x83\x8c\ +\x13\x91\x97\x9a\xce\x69\x82\x09\x26\xf8\x7f\xe0\x6f\x3e\x50\x4e\ +\x18\x86\xf9\x70\xa3\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\x61\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x13\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\xbf\x6b\x14\x41\x14\xc7\xbf\x6f\x93\x70\x9e\x04\x1b\x31\x46\ +\x72\x9b\xdd\x8d\xb9\x42\x08\xd8\xda\xfb\x03\xb4\xb0\x93\x80\x5d\ +\x0e\x44\x25\x9d\x4d\xc8\x5f\x60\x2c\x85\x04\xd1\x22\xa5\x4d\x6c\ +\x44\x48\x04\xb5\xb3\xb0\x15\x52\x08\xd1\xec\xde\xde\x82\x78\x62\ +\xa1\xa8\xe7\x91\xdc\x8c\x4d\x08\x78\xbb\x77\x97\xdd\xb9\x97\xc9\ +\xb9\xf3\x29\xe7\xe6\xbe\xef\xbb\xdf\xdb\x9d\x7d\xcc\x0d\x60\x30\ +\x18\xf2\x0c\xa9\x0a\xd4\xeb\xf5\xd1\x46\xa3\x39\x2f\x81\x1b\x00\ +\x66\x00\x14\xd4\x6d\x29\xd1\x04\xb0\x49\xc0\x5a\xb1\x58\x58\x19\ +\x1b\x1b\xfb\xd9\x6d\xb2\x52\x00\xd5\x6a\xf5\xb2\x84\xb5\x0a\xa0\ +\xa4\xa2\xc3\x48\x44\x10\x15\xc7\x71\x5e\x75\x9a\x60\x65\x55\x0e\ +\x82\xb0\x22\x61\xbd\xc4\xd1\xbd\x78\x00\x28\x49\x58\x1b\x7e\x18\ +\xce\x75\x9a\x90\xe9\x0e\xd8\x0e\xc3\x2b\x96\xa4\x0d\x28\x04\x78\ +\xc8\xb4\x08\xe2\x6a\xd2\x9d\x90\x3a\x80\x7a\xbd\x3e\xfa\xbb\xd1\ +\xfc\x00\x60\xa2\x2f\xd6\x0e\x8f\xe8\x78\xb1\x70\xae\x7d\x4d\x48\ +\xfd\x0b\x36\x1a\xcd\x79\x0c\xde\xc5\x03\x40\x69\xcf\xfb\x3f\xa4\ +\x0e\x60\x6f\xb5\x1f\x48\x92\xbc\x67\x79\x86\x67\xfa\xe0\x45\x17\ +\x31\xef\xc3\x19\x44\xba\xbe\xe7\x5d\xc7\x56\xee\x2d\x54\x08\xaa\ +\x35\xd9\xe5\xe3\x98\xf7\x41\x59\xc5\xd9\x30\x01\xe8\x36\xa0\x1b\ +\x13\x80\x6e\x03\xba\x31\x01\xe8\x36\xa0\x9b\xdc\x07\xd0\xb3\x11\ +\x0a\x82\xe0\x0c\xac\xe1\xbb\x90\xf2\x22\x80\xd3\x3d\xe7\x57\x6b\ +\x1f\x15\xfc\x48\x10\x22\x08\xac\xef\xec\xfc\x79\x5c\x2e\x97\x7f\ +\x28\x68\x1d\x88\xae\x5d\x5b\x18\x86\xd7\x85\xa4\x55\x00\x27\xb9\ +\x8d\x24\xe0\x4b\x41\x37\x3d\xaf\xf4\x2e\xcd\x97\x7a\x74\x82\xb1\ +\x4e\xb5\xe3\x23\xe0\x57\x6b\x4b\x42\xd2\x73\xe8\xb9\x78\x00\xf0\ +\xc8\x92\x6f\xfd\x30\xba\xc3\x59\x24\x31\x00\x3f\x0c\x67\x09\x58\ +\xe0\x2c\x7c\x40\x86\x48\xca\x65\xdf\x8f\x2e\x70\x15\x88\x05\xe0\ +\xfb\xbe\x4b\x92\x9e\x70\x15\xcc\xc0\x10\x59\xf2\xe9\xd6\xd6\xd6\ +\x09\x0e\xf1\xf8\x1d\x60\x0d\x2f\x02\x60\x29\xa6\x80\x37\x32\x72\ +\xec\x36\x87\x70\x2c\x00\x02\xae\x71\x14\x52\xc6\xe2\xf1\x95\xb4\ +\x06\x1c\xcd\x5d\x5e\xc9\xe3\x2b\xf5\x86\xc8\x90\x85\x32\x87\x91\ +\x5d\x60\x9a\x04\x36\xba\x4c\x61\xd9\x68\x49\x1d\x80\x6d\xdb\x2a\ +\x8d\x4e\x47\x6a\xb5\x1a\x5a\x1c\xc2\x3d\xc8\x7d\x2b\x6c\x02\xd0\ +\x6d\x40\x37\x26\x00\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\ +\xdd\x06\x74\x63\x02\xd0\x6d\x40\x37\x26\x00\xdd\x06\x74\x93\xe5\ +\x7c\x80\x2e\xce\xf6\xda\xf1\x3d\x00\xcd\xf6\x81\xbc\xdd\x01\x9b\ +\xed\x03\xb9\x0a\x80\x80\xb5\xf6\xb1\x3c\x05\x10\x15\x8b\x85\x95\ +\xf6\xc1\xbc\x04\xd0\x22\x88\x4a\xd2\xb9\xe1\x3c\x04\xd0\x92\x24\ +\x6f\x75\x3a\x2f\x3c\x48\x6f\x81\x2c\x44\x04\x51\x71\x27\x3b\x1f\ +\x96\xfe\x1f\x03\xd8\x3f\x2e\x5f\x28\x8c\x2c\x8f\x8f\x8f\xff\xea\ +\x36\x39\xb6\xd5\xdc\x87\x77\x2d\x17\x9f\x5c\xc7\x9e\xee\xb7\x68\ +\x7c\x0d\x90\xf8\xda\xef\x22\x7d\xe2\x0b\x87\x68\xd2\x22\xf8\x9a\ +\xa3\x90\x32\x44\x6f\x38\x64\x63\x01\x08\x41\x0f\x00\xec\x70\x14\ +\x53\xe0\x1b\xc4\xee\x23\x0e\xe1\x58\x00\x53\x53\xa5\xf7\x92\xe8\ +\x28\x9c\x0d\xd8\x87\x60\xcd\xb9\xae\xfb\x99\x43\x3b\xb1\x0f\x70\ +\xed\x89\x87\x00\x9e\x71\x14\x4c\x0b\x01\x4b\x8e\x33\xf1\x82\x4b\ +\x3f\x31\x00\x22\x12\xce\x64\x69\x56\x12\xdd\x83\xbe\xc7\xe1\x3b\ +\x81\x66\x1d\xc7\x5e\xe4\x2c\xd2\xf3\x1f\xd7\xed\xed\xe8\xbc\x65\ +\xc9\x05\x00\x97\x40\x38\xc5\x69\x66\x8f\x48\x02\xeb\x10\xbb\xf7\ +\x3d\xcf\x0b\x0e\xa1\x9e\xc1\x60\xc8\x31\x7f\x01\x50\x46\xc4\x66\ +\xcc\x07\x14\xea\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x09\xc0\x30\x0c\x04\x41\xc9\x49\xdf\x71\x4d\x6e\x48\x08\ +\xd5\x11\xec\x22\xce\xa0\xcf\xce\xff\x8e\x35\x13\x44\xd6\x8c\xac\ +\xa9\x7c\x0c\x65\x7c\x03\x01\x04\x10\x40\x00\x01\x04\xb4\x07\xbc\ +\xea\x81\x9b\x7d\x91\xd5\x13\xe0\xfb\x59\xdb\x7f\xe5\x02\x00\x00\ +\xf4\x3b\x2b\x9a\x0d\x40\x4d\xe0\x05\x89\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x85\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x37\x49\x44\x41\x54\x58\x85\xed\ +\xce\xc1\x0d\x00\x30\x08\x03\x31\xd4\xc9\xd9\x14\x21\x16\xe9\x10\ +\xf0\xf4\xfd\x13\x39\x62\x51\xf5\x64\xf5\xe4\xe6\xe3\x6d\xc6\x17\ +\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x7c\ +\x9f\x23\x06\x85\x22\x0f\x12\xcb\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x05\x38\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xea\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x5b\x6c\x54\x55\x14\x86\xbf\xb5\x67\x3a\x20\x24\xe5\x22\x46\ +\x04\x2a\xd0\x80\x29\x04\x4c\x04\x25\x01\x82\xa2\xd0\xd6\x8a\x40\ +\x29\x39\x1a\x52\x22\xf6\x02\x21\x26\xfa\x60\x82\x82\x10\x27\x0d\ +\x0a\xf5\xc5\x04\x45\x94\xda\x16\x8d\xf2\xc2\xf4\xa2\x6d\x28\xd0\ +\x01\xd2\xbe\x80\x04\x6b\x43\xc0\x42\x62\x2c\x17\x4b\xab\x31\x10\ +\x30\x8a\xb4\x9d\xd9\xcb\x87\x99\x29\x67\x7a\x6f\xf1\x8d\xf5\x74\ +\xf6\xda\xeb\xfc\xff\xbf\xd7\xd9\x6b\xaf\x7d\xe0\x41\x37\x19\x4a\ +\x70\xda\xea\x9c\x24\xeb\xf1\x66\x8a\xb1\xcb\x51\x49\x02\xa6\x00\ +\x46\xe0\xba\x42\x0b\xaa\xf5\x88\xb7\x32\x58\xbe\xff\x97\xff\x55\ +\x40\xba\x93\xb7\x20\x6c\x4d\xa1\xa0\xcf\x0f\x12\xf7\x2c\xa2\xdb\ +\x82\x65\x25\x27\xee\x4b\xc0\x72\x67\xd3\x18\xb1\xf6\x73\x60\x5d\ +\xd4\xd5\xa6\x50\x6d\xd0\x23\x61\xa4\xd9\x67\xc2\x6d\x1d\xa1\xb0\ +\xf5\x9a\x11\x13\xc3\x6a\xa7\x89\x48\x1a\xb0\x1a\x98\x1a\x8d\xaf\ +\xb1\x9d\xe4\x9e\xa8\x2a\xfe\x63\xc8\x02\xd2\x9d\xbc\x19\xd6\x4a\ +\x15\x30\x2b\x42\x2c\xfe\xd0\x8d\x49\x07\xea\xea\x0a\x42\xfd\x89\ +\xf6\xfb\xfd\xe6\xd4\x85\xeb\xaf\x02\x1f\x00\xc9\xc0\x35\x63\xed\ +\xaa\x63\x95\xa5\xe7\x06\x2d\x60\x59\x56\x4e\xb2\xc1\x73\x06\x61\ +\x82\xc0\xf7\x9e\x91\xff\xbe\x76\xe4\xe0\xc1\xbf\xfa\x23\xee\x6e\ +\x19\x19\x6f\x8e\xe8\x1c\x75\x77\x9f\xa0\xb9\xc0\x3f\x8a\x2e\x39\ +\x5e\x5e\xd2\x38\xa0\x80\x8c\xec\xec\xc4\xd0\xdd\x51\xa7\x41\x67\ +\x83\xee\x59\x34\x67\xca\xdb\x05\x05\x05\x76\x28\xe4\x6e\xfc\xb4\ +\xac\xbc\xad\x2a\xb2\x0b\x68\x31\x6a\x16\x1c\xab\x28\x6a\x73\x07\ +\x78\xbb\xbf\x11\xba\x3b\x6a\x6f\x84\x9c\xea\xde\xc8\xd3\x56\xe7\ +\x24\xa9\xd7\x9b\x0f\xfa\x12\xf0\xb8\x80\x55\xf4\x2a\x22\x87\x8d\ +\x35\xc5\xdd\x08\xb4\xb6\xa2\xa4\x30\x35\x2b\x3f\x19\x21\xdf\x1a\ +\xfb\x2d\xb0\x1c\xd0\x5e\x33\x90\xba\x36\xf7\x69\x30\x67\x81\x3f\ +\xd5\x98\x99\xc7\x03\x45\xb7\x63\x73\x7e\xbf\xdf\x9c\x3e\xdf\xf2\ +\xae\x8a\xbc\x0f\x8c\xec\x63\xc5\xff\x08\xbc\x57\x5b\x5e\xfc\xa9\ +\x9b\xc4\x71\x1c\xdf\x2d\x3b\xe6\x1c\x90\x02\xac\x08\x96\x17\xd7\ +\xc4\xe6\x4c\x5c\xbe\x30\xbb\x01\x54\x65\x67\x77\xf2\x53\x17\xae\ +\x7f\x1d\x4d\x65\x5f\xe4\x00\xa3\x15\xf6\xa4\xae\xcd\xdf\xe7\x5e\ +\x5c\x20\x10\xe8\x50\x61\x7b\x74\x58\xe8\x9e\xeb\x12\x90\x9e\xb5\ +\xe9\x31\x85\x65\xc0\xcd\x71\x9e\x5b\xfb\xdd\xa8\xa7\x2e\xb4\xec\ +\x00\xd6\xdf\x5b\x53\x3f\x16\x89\xd9\x9c\xba\x76\xe3\x5b\x6e\xf7\ +\xf1\xb2\xe2\x4a\xe0\x12\x30\x37\x7d\x4d\xee\x93\x3d\x04\x28\x76\ +\x65\x44\x99\x1c\x0e\x04\x02\x1d\x31\xff\xb2\xac\x9c\x64\x90\x1d\ +\xc0\xe0\x8e\xad\xae\x18\xfd\x30\x75\x55\xee\xa4\x38\x69\x22\x55\ +\x00\xea\x31\x6b\x7a\x0a\x10\x96\x02\xa8\xda\xa3\x6e\x3c\x63\x3c\ +\x6f\x00\x09\x83\xa0\xee\x6e\xa3\xd5\x6b\x36\xc6\x69\x0b\xeb\x31\ +\x00\xab\xbc\xd0\x43\x00\xaa\x49\x11\x75\x7a\x39\x0e\x46\x59\x31\ +\x0c\xf2\x08\xa1\xf0\xb2\x7b\x6c\xd4\xdb\x0c\x20\x91\x1e\xd2\x4d\ +\x80\x44\x9c\x09\x9d\x3e\x77\x19\x09\x91\xd3\x6c\xb8\x36\xd5\x3d\ +\x90\xf6\x84\x18\xf6\xe4\x28\x76\x7c\x15\x74\x37\xbf\xdf\x2f\x03\ +\xc5\x0c\x60\x9e\x01\xb0\xdd\xe0\x72\x1d\x20\x64\x42\x13\x63\x9e\ +\x82\x82\x02\x2b\x70\xf5\x3e\x04\x5c\x73\x0f\xda\x1f\xba\x13\xc5\ +\xd6\xd6\xd8\x01\xe7\xde\x03\xbf\x01\x88\x30\x3d\x0e\x42\xa8\x61\ +\xb8\xa6\xf1\xef\x26\xa0\xc9\x51\x7f\x4b\xcc\x77\x4f\x80\xa1\x2e\ +\xfa\x94\xee\x7e\x29\x2c\xe1\x2f\x80\xe1\xf4\x82\x0e\xf1\x50\x1c\ +\xa7\x47\x4c\x1a\x00\x62\x4e\xf6\x14\xd0\xa1\xd5\x51\x75\x2b\xe6\ +\x6f\xda\xd4\x55\x76\x27\x02\x07\x9a\x44\xf8\x24\x3a\x37\xa0\xc5\ +\x42\x54\xd9\x55\x1b\x28\x76\x57\x94\x28\xb2\x2a\xca\x5a\xd9\x43\ +\x40\xb0\xaa\xb4\x15\xe1\x24\xc2\x84\x71\x37\x6c\xbe\x1b\xf4\xc6\ +\x78\xf3\x0e\x50\x33\x98\x83\x48\x22\x2a\x02\x8b\xe7\x4e\xde\xe9\ +\xf6\xa7\x66\x6d\x5c\x19\x6d\x72\x3f\x07\x03\x5f\x76\xdd\x0d\xe2\ +\x76\xb8\xb5\xb2\x15\x40\x04\x7f\x46\x76\x76\x62\xcc\xdf\x50\x54\ +\xd4\x79\xf3\x61\x93\x09\xba\x87\xfe\x3f\x47\x08\x65\xd7\x58\xcf\ +\xed\x75\xee\x2e\xea\x38\x8e\x0f\x61\x77\x44\xa0\x6e\xc3\x95\xcb\ +\xb8\x32\xb9\x7c\xf1\xa7\xd6\xe4\x59\xf3\x66\x0a\x2c\xd4\x50\xc2\ +\xec\xf5\xaf\xac\x3c\x54\x5f\x5f\xaf\x00\x6d\x0d\x0d\xb6\xf9\x62\ +\xe3\xd1\x19\x29\x4f\x55\x20\xa2\xc0\x23\x40\x22\x60\x05\x2e\x83\ +\x7e\xe3\x31\x9a\x5b\x5b\x5e\x72\xa8\xa9\xa9\xc9\xfd\xb1\x64\x72\ +\xca\xe2\xcf\x10\xcd\x00\xea\x82\xe5\x25\xdb\xdd\x9c\x3d\x92\x1a\ +\xbd\x07\xfe\x00\xa4\x80\x7e\xbc\x68\xce\x94\x2d\x7d\x5d\x48\x1c\ +\xc7\xf1\x00\x04\x02\x81\x70\x1f\x19\x91\xd4\xac\xbc\x2d\x88\x7c\ +\x84\xd0\x4a\x87\x7d\x26\x58\x55\xda\xda\xaf\x00\xe8\xba\x0f\x9e\ +\x01\xc6\x03\x15\x9d\xc6\xb7\xa1\x2e\xb0\xef\xef\x3e\x48\x7a\x35\ +\xc7\x71\x7c\xb7\x6d\xe2\x5e\x45\x36\x02\x77\xc0\x3e\x17\x2c\x2f\ +\xfd\xb1\x7b\x5c\xaf\x27\xd5\xaf\x4d\x8d\x37\xa7\xa7\xcc\xff\x0e\ +\x21\x4d\x60\x89\x47\xc3\x1b\x66\xcc\x9a\x77\x3b\xe9\xd1\x95\xe7\ +\xaf\x5c\xa9\xef\xb7\x24\xfd\x7e\xbf\x49\x98\xf0\x84\xd3\xae\xbe\ +\x32\x90\x54\x22\x57\xb1\xb4\xda\x8a\xe2\x86\xde\xe2\xfb\xdd\xd7\ +\x4b\x33\x5f\x1f\x9b\x60\xbc\x45\x08\x4e\xd4\xd5\x22\x50\x0d\x7a\ +\x44\x30\xcd\x18\xdb\xd6\xde\x19\xb6\x3e\x8f\x6f\xa2\x45\xa7\x02\ +\xe9\x82\xae\xa6\xab\x7f\x48\x6d\xa7\xe9\xdc\x50\x17\xf8\xea\xf7\ +\xbe\x38\x06\xf5\x63\xb2\xcc\xc9\x5d\x68\xac\x29\x04\x9e\x1d\x4c\ +\x3c\xd0\x88\xd8\xad\xc1\xb2\xd2\xda\x81\x02\x87\xf4\x6b\xf6\x62\ +\xe6\xe6\x69\x21\x13\xca\x14\x23\xcb\x45\x35\x49\x23\x6d\xd5\x03\ +\xb4\x00\x2d\xa2\x5a\x8f\x78\x2a\x6b\xcb\x8b\x2e\x0d\x05\xf7\xc1\ +\xb6\xff\x00\xf7\x80\xda\xb0\x80\x19\xdd\x42\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcc\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7e\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x41\x0d\xc0\x20\x14\x05\x41\x5a\x4d\x78\xc2\x4f\x65\xd5\x14\ +\x95\xb1\x4d\x98\x31\xf0\x5f\x36\xdc\x18\x23\x34\xd7\xb3\xe7\x7a\ +\x76\xb9\xe1\x2e\x8f\xff\x81\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\ +\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\x9a\x00\xf5\x80\xda\xf1\ +\x01\xae\xf2\x78\xfd\x35\x3e\x46\xff\x02\xde\xf8\x3e\x00\x00\x00\ +\x00\x00\x00\x00\x9c\xe0\x03\xda\xaf\x07\x8e\xa0\xaf\x15\x04\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x68\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x1a\x49\x44\x41\x54\x58\x85\xed\ +\xc1\x01\x01\x00\x00\x00\x82\x20\xff\xaf\x6e\x48\x40\x01\x00\x00\ +\x00\xef\x06\x10\x20\x00\x01\x47\x01\xa0\x88\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xf7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xa9\x49\x44\x41\x54\x58\x85\xed\ +\x96\xb1\x4a\xc3\x50\x14\x86\xff\x93\x64\xb1\x05\x5f\x40\xd4\x37\ +\xa8\x60\xa1\x11\x41\x7c\x03\x29\x0d\x2a\x5d\x7c\x01\x5d\x04\x11\ +\x97\x4e\x1d\x1c\x44\x97\xe2\x13\x38\x59\x49\x3a\x17\x17\x41\x0a\ +\x86\x52\xb0\x8f\x50\x3b\xb8\xb8\x28\xd4\xa9\xb9\xc7\xa1\x26\x36\ +\xb5\xb7\x4d\x4c\x6b\x86\xf6\x9f\x6e\x92\x73\xcf\xff\xe5\xdc\x7b\ +\x0f\x17\x98\x75\xd1\xa8\x8f\xa9\x2a\x27\x13\x1d\x51\x64\x50\x0e\ +\xc0\x6a\x44\xaf\x16\x83\x4d\x47\x53\x0a\x8d\x1d\xfa\x1c\x0b\x90\ +\xaa\x72\x72\xa1\xc3\x35\x00\x6b\x11\x8d\x07\xd5\xec\x6a\xb4\xe9\ +\x42\x28\xb2\xa8\x44\x47\x14\xa7\x60\x0e\x00\x6b\x6a\x57\x14\xdd\ +\x07\x29\xc0\x77\xd9\xa7\x22\x02\x19\xee\x58\x1b\x11\xe7\x5b\x73\ +\x3b\xa7\x8c\xdc\x2f\xe3\xa4\x5b\x82\x87\xe5\x96\x56\xe0\xbf\x34\ +\x07\xf8\xb5\x07\xd2\x65\x5e\xd1\x54\x6c\x03\xec\x7b\x9f\xa9\xf0\ +\x91\x2c\x09\x09\x08\x02\x9a\xcb\x0e\x9e\xee\xf6\xc8\xf9\x33\x80\ +\x6e\xf1\x09\xc0\xe7\xc3\xc0\x88\xb9\x24\xcd\x42\x3d\xdc\x17\x0d\ +\x8f\x69\x93\xf7\x1b\x06\xbd\x06\x05\xf0\x96\x20\x53\xe1\x3c\xc0\ +\x17\xc3\xcc\x43\x68\x4b\x23\xbe\xdd\x2d\xb3\x1a\x1a\x80\x98\x4f\ +\x23\x18\xfb\x20\xda\x2a\x36\x82\x06\xf7\xff\xed\x40\xd7\xe3\xeb\ +\xe0\x9e\x94\x05\xb0\xe4\xcd\xec\xe5\xaa\x85\x05\xf0\x35\x1a\x3b\ +\xa7\x4a\x37\xdd\xa0\x74\xcb\x01\x40\x87\x1e\x80\x12\xfc\x74\xc5\ +\x7e\x0c\xe7\x00\x73\x80\xd8\x01\xa2\x74\x3d\xa9\x88\xb9\xa4\x5b\ +\x42\xde\xba\x81\x96\x3b\x88\xa5\x02\x0c\x36\xe3\x04\x68\x3a\x9a\ +\x52\x88\x03\xa0\xc5\xe0\xab\xfe\x1b\x31\xd0\xd7\x7e\x75\x4b\xbc\ +\x03\x58\x9c\x88\x15\xd3\x81\x6d\xd0\x4d\x90\xd0\x9f\x0a\x30\xee\ +\x27\x62\x0e\x74\x85\x8a\x87\xa0\xc1\x1e\x80\x50\xe9\x18\xc0\x5b\ +\x64\x7b\xa6\xb3\x7a\x96\xda\xa1\x01\xea\x59\x6a\x0b\x85\xd6\xc1\ +\x30\x01\x7c\x84\xb5\x05\xf0\x0c\x50\xde\x36\xe8\x32\xe4\xdc\x19\ +\xd7\x17\x91\x1d\x7b\x32\x62\xe5\x6b\x14\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x94\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x46\x49\x44\x41\x54\x58\x85\xed\ +\xd1\x21\x4b\x43\x51\x18\xc6\xf1\xff\x7b\xc7\x8a\x41\x04\x41\xcb\ +\x76\xdd\xf6\x09\x04\x6d\x36\x93\xa8\x6b\x82\x49\xab\x82\xdf\xc1\ +\x62\x31\xf8\x11\x64\x20\x18\x0c\x26\x41\x10\x8b\xa0\x08\x86\x15\ +\xc1\xec\x7d\xcf\x3d\xd7\xee\x98\x60\x71\x7b\x2d\x1a\x14\xb6\xbb\ +\xbb\x24\x78\x7e\xf1\xf0\xf0\xf0\x1c\x5e\x08\x82\x20\x08\xfe\x3b\ +\xc9\x0b\x68\xea\x8f\x31\x16\x22\xb1\xad\x38\x8e\x9f\x46\x29\x4d\ +\x92\xa4\x26\x51\xe9\x14\xa4\x33\x17\x57\xd6\x45\xc4\x06\x65\xa3\ +\xdc\x36\x63\x0a\x98\xef\x9b\xdc\xab\x66\xcb\x79\x71\xe7\xdc\x82\ +\x44\xe5\x07\x90\x25\x8c\xe9\xbc\x7c\xee\x80\x52\xc4\x16\x70\x0e\ +\x4c\x22\x76\xe5\x5c\xb6\x3d\x28\xab\x9a\xad\x19\xd1\x2d\xd8\x2c\ +\x70\x63\xf6\xb1\x32\xec\xf7\x23\x0d\xa8\x56\xab\xef\x73\x71\x65\ +\x13\xe1\x08\x28\x1b\x76\xe2\x9c\xdf\x37\xb3\x1f\xe7\x4b\xd2\x6c\ +\x17\xb1\x0b\x60\x02\x38\x7d\xeb\x76\x56\xea\xf5\xfa\x6b\x5e\x7f\ +\x21\xaa\xe9\x9e\x3a\xdf\x53\xe7\x4d\x35\x6b\xb5\xdb\xed\xb2\x99\ +\x45\x89\xf3\x87\xea\xbc\xa9\xf3\xa6\x69\x76\xf0\x7b\xdc\x30\x23\ +\x07\xbf\x39\xf7\xd2\x34\xfa\x67\xc0\x84\xc1\x9d\x40\x17\x58\x05\ +\x3e\x30\xdb\xa9\xd5\xe2\x56\x91\xbe\xc2\x03\x00\xd2\x34\x5d\xec\ +\x9b\x5c\x02\x33\x5f\x4f\xdd\xbe\xd8\x46\x23\x8e\xaf\x8b\x76\x8d\ +\x35\x00\x40\x55\xeb\x48\xe9\x59\xc0\xf7\x7a\xd2\x6c\x34\x2a\x8f\ +\xe3\x76\x8d\xcd\xcc\xa4\xc8\xbd\x83\x20\x08\x82\x3f\xe9\x13\xfa\ +\xca\x87\x49\xdf\x83\x3a\x35\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x04\x83\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x35\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4b\x88\x1c\x55\x14\x86\xbf\x53\xdd\x93\x31\x24\x41\x88\xf1\ +\x85\xa8\x2b\x51\x5c\x08\x43\xb7\x11\x11\x64\x14\x8d\x06\x31\xf8\ +\x00\x5d\x89\x4e\x30\xd3\x1d\x92\x9e\x76\x40\x11\x7c\xd0\x36\x89\ +\x98\x80\xf8\xe8\x36\xa6\x7b\x0c\x18\x17\x06\x75\x15\x06\x34\x3a\ +\xba\x48\x40\x90\xcc\x74\xe2\x03\x71\x21\x88\xb8\xd0\xa8\x84\x28\ +\x9a\x09\x66\x66\xba\x7e\x17\x6d\xa0\xaa\x18\x83\xd1\x7a\x5c\x4c\ +\xff\xcb\xff\x40\xdd\x73\xbf\x3a\x7d\xef\x3d\x55\xd5\xd0\x57\x5f\ +\x7d\x9d\xcd\xb2\xac\x13\xf8\xa7\x2a\x8e\x36\x6b\x66\x7a\x4a\x60\ +\x48\x5b\x3b\x13\xd5\x67\xe2\xb8\xae\x17\xc7\x45\x92\x56\x61\xf4\ +\xe5\x9b\x30\x6a\x82\x3c\x90\xc3\xec\xe9\xb8\xae\xed\x3c\x80\xd5\ +\xa5\x66\xd1\xcc\x26\x41\xc1\x6a\x8d\x2d\x6f\xa7\x01\x14\x46\x9b\ +\x57\xf9\x68\x1f\xb0\x3c\xe8\x0b\xfc\xb8\xc6\x70\x16\x40\x61\xf4\ +\xa5\xcb\xcc\x34\x05\xac\x8a\xc6\x0c\x14\xd7\x38\xf9\xb8\x2e\x14\ +\xa7\x86\x46\x1a\xe7\x9b\x31\x05\x5c\x9a\xf4\x58\xce\x55\xc0\x0d\ +\xeb\xb7\xaf\xc8\x2d\xe1\x3d\xe0\xca\x34\xc6\x73\x0a\xc0\xf0\x43\ +\xaf\x9f\x33\x37\xb0\x74\x2f\x50\x0c\xfa\x8a\xb1\xe4\xa3\x72\x06\ +\xc0\x70\xad\x96\xff\x7d\xf0\xf8\x1e\xc1\xcd\x91\x90\x2c\xc6\x45\ +\x2f\x2a\x47\x00\xc8\x8e\x1f\x39\xaf\x6d\xe8\xee\xb0\x6f\x22\xc1\ +\xc9\x83\x23\x00\x8a\xa5\xe6\x76\x8c\xf5\x41\x4f\x98\x40\x89\x4e\ +\x1e\x1c\x00\x50\x28\x35\x1e\x07\x1e\x8b\xfa\x96\xc2\xe4\x21\x63\ +\x00\xd7\x96\x1b\x1b\x0c\xb6\x2d\x12\xea\xa6\x95\x43\x66\x00\x8a\ +\xe5\xe6\xbd\x12\xad\xa8\xaf\x94\xee\xfc\x29\x65\x02\xa0\xb8\xa1\ +\x71\x0b\xd2\x9e\x45\xc6\xf7\xad\xb7\xf0\xa5\xa6\xd4\x01\x14\xcb\ +\x8d\xd5\x78\xec\x05\x96\x04\x7d\x19\x3e\x09\xee\xf7\x7f\xa7\x54\ +\x01\x5c\x57\x6a\x5c\x8d\xd8\x07\x2c\x8b\x84\x7c\x53\xfa\x93\x87\ +\x14\x01\x0c\x6d\x7a\xe5\xf2\x05\x6c\x0a\x58\x19\xf4\xff\xea\xec\ +\x32\x99\x3c\xa4\x04\xe0\x9a\xf2\xce\x0b\xbc\x05\xff\x43\x43\x97\ +\x04\x7d\x81\x1f\x67\x67\xf7\x6f\x94\x78\x37\x58\x18\x6d\x9f\x6b\ +\x3a\xf9\x3e\x70\x45\xd0\x57\xef\x88\x9b\xe9\xe4\x21\xe1\x0a\xb8\ +\x7e\xfc\x85\xa5\x66\x73\x93\xc0\x50\x28\x20\x4b\xf4\x7c\x7f\x26\ +\x4a\x0c\xc0\x70\xad\x96\x9f\x9f\xcd\xbf\x05\xba\x31\xe8\xab\x77\ +\xca\x75\x62\xf2\x90\x14\x80\x5a\xcd\x9b\xfd\x69\xd5\x2e\x8c\x75\ +\x41\x5b\xb8\x73\xe7\x4f\x29\x01\x00\xb2\xe2\x91\x95\xcf\x4b\x7a\ +\x30\xec\xbb\x37\x79\x48\x60\x11\x2c\x96\x1b\x4f\x20\x1b\x0f\x99\ +\x12\x98\x7b\x93\x87\x98\x2b\xa0\x50\x6a\x96\x91\x6d\x0d\x99\x02\ +\x33\x4b\xad\xb9\x39\x53\xc5\x06\xa0\x58\x6a\x6c\x33\xb4\x33\xea\ +\xcb\xf0\x33\xdf\xeb\x4e\xa3\xf8\x2a\x20\xf2\x40\x03\x7a\x9d\x9d\ +\x0b\x7b\xfd\xe9\x14\x1f\x00\xa5\xd7\xc3\xc7\xa9\xd8\x00\x98\xa9\ +\x4a\xe4\x6e\x1b\xe6\xb9\xfe\xfa\x35\x36\x00\x33\xad\xea\x3b\x48\ +\x95\xa8\x2f\x91\x73\x19\x42\xac\xbb\x40\x67\xa2\xba\xc3\xa0\x16\ +\xf4\x0c\x40\xca\xb9\xfa\x26\x3e\xf6\x83\xd0\x4c\xbb\xb2\x05\xac\ +\x19\x76\x0d\x50\xe6\x0f\x60\x17\x53\x02\x49\x99\x3a\x17\x1d\x7d\ +\x44\xf0\x66\x34\x90\xcc\x78\xff\x4d\xc9\x24\x54\xaf\xfb\x68\x70\ +\x04\x78\x37\x12\x31\xe4\x16\x84\xc4\x92\x39\x34\x51\x9a\x97\x06\ +\xef\x03\x3e\x0e\x05\x0c\x03\x73\x06\x42\xa2\x89\x1c\x9a\x28\x9d\ +\x58\x38\xd9\xbd\x53\xf0\x79\x38\x22\x67\x7e\x0e\x89\x27\xf1\xd9\ +\xee\xf1\x5f\xbd\x5c\xee\x76\xe0\x9b\x48\xc8\x7a\xd5\x90\xad\x52\ +\xb9\x0b\x33\xaf\x6e\xfa\xd1\xeb\xda\xad\x88\x1f\x42\x01\xe1\x29\ +\x63\x08\xa9\x95\xe1\xf4\xae\xca\xb7\x78\xba\x0d\xf8\x25\xe8\x9b\ +\xf0\x7a\x8f\x0a\xb2\x51\xaa\xbf\xc3\x4e\xab\xfa\xa5\x87\x77\x07\ +\x70\x22\x14\x90\x79\x22\x1b\x08\xa9\x2f\x44\xd3\xed\xcd\x9f\xf8\ +\x66\xf7\x00\xf3\x41\xdf\x30\x4f\x19\x54\x42\x26\x2b\xf1\xe1\x56\ +\xe5\x03\xc3\x1e\x20\xda\x3c\xc9\x3c\xa5\x7c\x66\xce\x6c\x2b\x9a\ +\x69\x57\xde\xc6\xd8\x18\xf5\x4d\x78\x69\x12\xc8\x74\x2f\xee\xb4\ +\xc6\xda\x88\x27\x43\xa6\x81\xa4\x5c\x5a\x39\x64\x7e\x18\xe9\x4c\ +\x54\x9e\x43\x7a\x31\x64\x9a\xa1\x94\x4e\x8b\x99\x03\x00\x53\xe7\ +\xe2\x63\x8f\x9a\xd9\x1b\x21\x17\xa5\xd2\x37\x38\x00\x00\xa8\xd7\ +\xfd\x65\x17\x1e\x7d\x18\x31\x19\xf2\x2d\xf9\x0e\xd2\x0d\x00\xc0\ +\xfe\x7a\x7d\x61\xf9\xdc\x8a\xfb\x31\x0e\x44\x42\xa6\x04\xf3\x74\ +\x06\x00\xc0\xfe\xdd\x23\x7f\xe4\x06\x58\x07\x1c\x0e\xfa\x96\xe0\ +\xd6\xe8\x14\x00\x80\x83\xcd\xb1\xdf\xe6\x6c\x60\x2d\xf0\x75\x1a\ +\xe3\x39\x07\x00\xe0\x8b\xd6\xc6\x9f\xbb\x79\x6f\x8d\xb0\xef\x93\ +\x1e\xcb\x49\x00\x00\x9f\xee\xd8\xfc\x5d\x1e\xad\x01\x8e\x45\x63\ +\x71\x9e\x16\x9d\x05\x00\x70\xb0\x3d\xf6\x15\xc6\x5a\x60\x36\xe8\ +\xdb\xd9\xf2\x97\x19\x80\x4e\x6b\x6c\x1a\x9f\xbb\x14\xf8\x7e\x30\ +\xce\x8f\x29\x9d\x07\x00\xd0\x79\x6d\xec\x23\xd0\x16\xb0\xae\x89\ +\x2e\xe6\x3d\x9b\x75\x4e\x7d\xf5\xd5\xd7\xff\x43\x7f\x02\x97\x76\ +\x3e\x83\x62\x89\x8e\x83\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\x89\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3b\x49\x44\x41\x54\x58\x85\xed\ +\xcd\xb1\x11\x00\x10\x10\x05\xd1\x4f\x21\x28\x45\xa2\x6b\x33\x5a\ +\x31\x14\x72\x22\xa1\xf4\x12\xfb\xa2\xcd\x56\x02\x00\xe0\x77\xe1\ +\xc6\x5c\x7b\xc8\x54\x7d\xb6\xd6\x4b\x4e\x4d\x92\xa2\xcf\x10\x00\ +\x00\xe0\xed\x00\x5a\x36\x07\x04\x97\xc1\x22\x16\x00\x00\x00\x00\ +\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xca\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\x7c\x49\x44\x41\x54\x58\x85\xed\ +\x97\x4b\x72\xd3\x40\x14\x45\xcf\x73\x32\x00\xb6\x10\x59\x2d\xcd\ +\x60\x0b\x6c\x81\x01\x90\x00\x81\x90\x8a\xf3\x71\x15\x2c\x20\x55\ +\xac\x81\x61\x66\x0c\x20\xc4\xf9\x3b\x21\x14\x55\xac\x81\x35\xc0\ +\x08\xb7\x24\x03\x3b\x00\x06\xc4\x8f\x41\xe4\x20\xeb\x63\x49\x2e\ +\x33\x82\x1e\x59\xaf\xba\xef\x39\x7e\x6a\x5b\x2d\xf8\xd7\x87\x0c\ +\x3f\x58\xfb\xe5\xa6\xca\xe0\x85\xc0\x55\x94\x67\x9e\xd7\x7c\x3b\ +\x4d\x90\xb5\xd1\x3c\xc2\x73\xe0\xa7\xd0\x78\x6a\xcc\xdc\x87\x51\ +\x81\x20\xfa\x08\x5c\x8f\x2f\x07\x2a\xba\xe4\xbb\x6e\x77\x1a\xf0\ +\x5e\x18\x3e\x14\x95\x03\xa0\x11\x97\x3e\x79\xa6\x79\x83\x44\x01\ +\x90\x2b\x89\x35\x0d\x51\x39\xec\x85\xe1\xe2\x5f\x80\x83\x70\xed\ +\x12\x74\x59\x54\xdd\x04\x06\xd3\x94\xe8\x85\xe1\x62\x06\x0e\x03\ +\x51\xd9\xcc\x08\x78\x5e\xf3\x4c\x45\x97\x73\x24\x0e\x26\x91\x88\ +\xe1\x87\x19\x38\xb4\x8c\x71\x4e\x33\x02\x00\xbe\xeb\x1e\xe5\x48\ +\xcc\xd4\x95\x28\xfc\xe6\xd0\x32\xa6\xb9\x9f\x9c\x2b\xe4\x0c\x6b\ +\xa3\x25\x84\xbd\x54\xc0\xb9\x20\x4b\xc6\x38\x27\xe3\xe0\x41\xd0\ +\x7f\xa0\xe8\x21\x30\x53\x06\x2f\x14\x98\x54\xa2\x00\xae\x02\x2b\ +\x79\xf0\xb1\x02\xb1\xc4\x63\x84\xdd\x2a\x12\x41\xd0\xbf\xaf\xe8\ +\x51\x1d\x78\xa9\x40\x89\xc4\xa3\xe1\x66\x9a\x14\x5e\x49\xe0\x02\ +\x10\x2d\x2b\x74\xf2\x24\x00\xf2\xe1\xd2\x32\xc6\xd9\x2b\xcb\xae\ +\x24\x30\x46\x62\xf8\x6b\x49\xd6\x2a\xc3\x6b\x09\x24\x24\x76\xc7\ +\xac\xab\x05\x87\xd4\xff\x40\xd9\x30\xa6\xb9\x2f\xb0\x02\x68\x01\ +\x7c\xb5\x0e\xbc\xb6\x00\x80\x2a\x3f\xf2\x04\xe4\xa2\xf6\xbd\x6e\ +\x5e\x2d\x01\x6b\xa3\x05\x84\xe3\xbc\x75\x0a\x0d\x45\x8f\x83\xa0\ +\x7f\xaf\x4e\x66\xe5\x3d\x10\x3f\xcf\xbb\xc0\xec\x08\x57\x04\x54\ +\x93\x39\xe7\x28\x8b\x9e\xd7\x3c\xab\x92\x5b\xa9\x03\x45\x70\x45\ +\xd6\x44\x59\x65\xf4\x96\xcc\x20\x74\xad\x8d\x16\xa6\x22\x60\x6d\ +\x74\xb7\x08\xee\x1b\xa7\x63\x8c\xb3\xab\xc8\xda\xa4\x12\x63\x05\ +\x62\xf8\x49\x06\x2e\xba\xee\x1b\xa7\x33\x2c\xf8\xc6\xe9\x14\x48\ +\x1c\x97\x49\x14\x0a\x8c\x85\xbb\xee\x4e\x7a\xbe\x6f\x9c\x8e\x8a\ +\xae\xa7\x24\x66\xcb\x24\x72\x37\x61\x2f\x0c\xef\x88\xca\x69\x55\ +\x78\x6a\xed\xaa\xa8\x6c\xa7\xb2\x7f\xc5\x1b\x33\x73\xd0\xcd\x74\ +\x60\x0c\x7c\xa3\x0c\x0e\xe0\xbb\xee\x8e\x8a\x6e\x90\xed\x44\xd7\ +\xda\x68\x3e\x3d\x7f\xa4\x03\xbd\x30\xbc\x2d\x2a\x6f\x0a\xe0\xaf\ +\xcb\xe0\xa9\xac\x35\x51\x79\x45\x49\x27\x12\xef\x05\xfd\x5b\x88\ +\xbe\x9b\x06\xfc\x4f\x66\xb8\x8e\xc8\xcb\xb4\x84\xd0\x98\x37\x66\ +\xee\x3d\x8c\x1c\x95\x75\x2b\x0d\x47\xb5\x3d\x29\x1c\xc0\xf3\xdc\ +\x6d\x54\xdb\xa4\x6e\x87\x32\xd8\x1a\x5e\x5c\x0a\xe8\xe8\x41\x54\ +\x51\x6d\x7b\x9e\xbb\x3d\x29\xbc\x44\xe2\x3c\x23\x20\x2a\x4f\x80\ +\xcf\xc0\x37\x41\x5a\xd3\x80\x27\x25\xe2\xa7\xe8\x57\xa0\xc7\x05\ +\xeb\xff\x00\xe0\x37\x93\x02\x62\x58\xa2\x39\x4a\x39\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xce\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x80\x49\x44\x41\x54\x58\x85\xed\ +\xd2\x21\x0e\xc2\x40\x14\x84\xe1\x7f\x96\x3b\x90\x70\x13\xe4\x9e\ +\x81\x0b\x20\x30\x1c\x09\x81\xc6\xd6\x22\xeb\x38\x0a\x49\xef\x40\ +\x07\xd5\x26\x0d\x09\xae\x5b\x33\x9f\x7b\x6f\x37\x99\x11\x0f\x22\ +\x22\x22\x36\xa6\xc5\x64\xab\xf6\xec\xd6\x0c\xec\x2b\x1f\x24\xff\ +\x14\x38\x76\xae\xb6\x1f\xc0\x61\xcd\x02\xc0\x50\xd0\xf9\x75\xd2\ +\x13\xa0\x4c\x5b\xdb\xb7\x06\xe1\x00\xfb\x11\xdf\xa7\xa1\xfc\xfb\ +\xd9\xc2\x5c\x40\xd2\x15\x78\x37\xc8\x1c\x3c\xea\x32\xe7\x2e\x9e\ +\x36\x38\xc2\x88\x88\x88\xcd\x7d\x01\x5e\x93\x20\x04\x37\xe4\x99\ +\xec\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0b\x37\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0a\xe9\x49\x44\x41\x54\x78\x9c\xed\ +\x5b\x7d\x70\x54\xd5\x15\xff\x9d\xbb\x9b\x4d\x22\xe6\x43\xc1\xaf\ +\x06\x3f\x30\xc8\x40\x43\xac\x12\xb4\xc6\xd2\xc8\x47\xb2\x18\x85\ +\x60\x36\xbc\x56\xb1\x68\x20\x9b\x08\x5a\xdb\xe2\xb4\x4e\x65\xa6\ +\xae\xb1\xda\xb1\x1f\x02\x23\xa3\x68\xd8\x40\x44\xa3\x6d\x97\x04\ +\x06\xac\x31\x5f\x76\x53\x14\x1c\x85\xd0\x22\x04\x18\x35\x44\xc5\ +\xd4\x56\x49\x42\x40\x20\xfb\x76\xdf\xe9\x1f\x21\xf0\xf6\xed\xdb\ +\xb7\x6f\x93\x5d\xa6\xd3\xf2\x9b\xd9\x3f\xde\xb9\xbf\x7b\xce\x79\ +\xe7\xdd\x77\xdf\xbd\xe7\x9e\x05\xce\xe3\x3c\xce\xe3\xff\x19\x74\ +\x2e\x8c\x14\x4a\x8b\x2e\x91\x15\x6b\x9e\x20\xce\x56\x18\x13\x09\ +\xb8\x16\xe0\x74\x10\xa5\x42\x81\x05\x84\x7e\x00\xfd\x20\xfe\x0c\ +\x0a\xf6\xb3\xa0\x0e\x41\xd8\xd6\xe4\x71\x1f\x8a\xb7\x6f\x71\x0b\ +\xc0\xcc\xbb\x2a\x32\x85\x35\x50\x2a\x98\x8a\x18\xb8\x7e\x98\x6a\ +\x0e\x31\x73\x03\x43\xd4\xb4\xd6\xaf\xdd\x09\x80\x63\xe9\x23\x10\ +\xfb\x00\xd0\xac\xe2\xb2\xd9\x24\xc4\xa3\x04\x9e\x11\x63\xdd\x7b\ +\x99\xb0\xa2\xf7\x62\xf1\xea\xae\xaa\x2a\x39\x56\x4a\x63\x16\x80\ +\xd9\x8e\xc5\x33\x14\x12\xbf\x03\x30\x35\x56\x3a\xf5\xc1\x5d\x04\ +\x3c\xd1\x54\x57\xbd\x01\x31\x18\x11\x23\x0e\xc0\xac\x22\xe7\x65\ +\x64\xc5\xb3\x44\xb8\xd7\x80\xa6\x30\xf0\x2e\x31\xbc\x0c\x3e\x20\ +\xc8\xf2\x09\x83\x7a\x64\x31\x70\x2c\x19\x14\xf0\x05\x90\x42\x24\ +\xd2\x40\x34\x0e\x8c\x09\x44\x9c\x0b\xa6\x02\x00\xc9\xe1\x14\x32\ +\xb0\xcd\x02\x5a\xda\x58\xb7\x76\xdf\x48\xfc\x1f\x51\x00\x66\x4b\ +\x65\x37\x2b\x0a\x6d\x06\x70\x85\xb6\x8d\x81\x63\x00\xde\x14\x44\ +\x5b\x03\x81\x81\xb7\x5a\x37\x6d\x38\x12\x8d\xee\x5c\x69\x59\xf2\ +\xa8\x40\xff\x4c\x82\x98\x0b\xe2\x22\x3d\x1b\x00\x4e\x01\x58\xdc\ +\x5c\xe7\x7e\x7d\x58\x37\x80\x11\x04\x20\xdf\x51\xb6\x80\x88\xd6\ +\x01\x48\x0c\x71\x8a\xe8\x39\x9b\xcd\xfa\xcc\x5f\x5e\x5b\xd3\x3b\ +\x5c\xfd\x6a\x48\x92\x64\xeb\x53\xd2\xca\x01\x3c\x0e\xe0\x52\x6d\ +\x3b\x01\x4f\xe7\x4e\xce\x78\xbc\xb2\xb2\x52\x89\x56\x77\xd4\x01\ +\x70\xb9\x5c\x62\xfb\xbe\xee\xa7\xc0\xfc\x98\xa6\x49\x01\x63\x9d\ +\x15\xa8\x6c\xa8\x77\x1f\x8e\x56\xaf\x19\x14\x15\x2d\x4e\x39\x61\ +\x15\x8f\x10\xe1\xe7\x00\x2e\x54\xb7\x31\x68\xb3\x5f\x24\x2c\xf4\ +\x7a\x5e\x38\x1e\x8d\xce\xa8\x02\xe0\x72\xb9\xc4\xf6\x0f\x0f\xd7\ +\x82\xe8\x6e\x8d\x96\x6e\x41\x5c\xdc\xe8\xa9\x7e\x3f\x1a\x7d\xc3\ +\x45\xa1\xc3\x39\xd6\x4f\xd8\x84\xd0\x09\x77\xb7\x35\xe9\xe4\xf4\ +\x86\xda\xda\x7e\xb3\xba\x2c\xd1\x18\xb6\x8d\xbe\xae\x12\x44\x0f\ +\x69\xc4\xef\x09\x16\xb3\x1a\xeb\xdc\x07\xa3\xd1\x35\x12\x7c\xbc\ +\xbf\xbd\xff\xb2\xc9\xb7\xbd\x9a\xa0\xf8\xae\x21\x0a\x5a\x63\x5c\ +\x11\xf0\x27\x64\xe7\x4c\xce\xfc\x73\x47\x47\x87\xa9\x2f\x84\xe9\ +\x00\xd8\x1d\xce\x1f\x82\xb0\x5a\x23\x7e\x59\x4e\xf1\x4b\xad\xaf\ +\x57\xf7\x99\xd5\x13\x2b\x1c\xee\x78\xcf\xdf\xb9\xbf\x7d\x53\xe6\ +\xa4\x1b\x4f\x80\x28\x1f\xa7\x47\x33\x01\x13\x4e\x21\x39\xa9\xb3\ +\xa3\xbd\xc5\x8c\x1e\x53\xaf\x40\x41\xc9\xe2\xa9\x80\xd8\x06\x20\ +\x49\x25\x7e\xb5\xb9\xce\x7d\x1f\xe2\xb0\x3a\x8b\x16\xf9\x0e\xe7\ +\xcf\x88\xb0\x52\x2d\x63\xc2\xfd\x2d\x1b\xdd\x1b\x22\xf5\x8d\x18\ +\x80\x59\xc5\xf7\x8d\x16\xc2\xf6\x0f\x00\x19\x67\xb5\xe3\x7d\x39\ +\xd5\x7f\x9b\xb7\xa6\xe6\x54\x54\x8e\x16\x3b\x27\x91\x05\xc5\xcc\ +\xb8\x9e\x80\xb1\x18\xfc\x05\x00\x1c\x26\xe0\x30\x33\xda\xc9\x82\ +\xfa\x61\xec\x01\xa8\xc0\xe1\xac\x06\x61\x91\x4a\xe6\x13\x2c\x72\ +\x1b\xeb\xab\xda\x0d\x3b\x46\x74\xba\xa4\xbc\x9a\xc0\x8b\x55\x3d\ +\xba\xe1\x53\x6e\x6a\xde\xb2\xae\xdb\x8c\x67\x83\x9f\xb0\xf4\xa5\ +\x00\x2f\x01\x30\xd1\x4c\x1f\x00\xbb\xc1\xf4\x5c\xba\xa5\xef\x15\ +\x8f\xc7\x13\x30\xd3\xa1\xb0\xf0\xe1\x44\xff\x05\x27\xdf\x06\x70\ +\xeb\x90\x8c\x81\x76\xff\x91\x8c\xef\x7a\xbd\x95\xfe\x70\xfd\x84\ +\x91\xd2\x7c\xa9\x62\x5a\xd0\xcd\x03\xcc\x0a\x4a\xcc\xde\xbc\xbd\ +\xa4\xec\xae\x3e\x25\x6d\x1f\xc0\xab\x60\xfe\xe6\x01\xe0\x46\x10\ +\xaf\xef\x53\xd2\x76\xda\x8b\x9d\x33\xcd\x74\x68\x68\x58\x3d\xa0\ +\xc8\x70\x80\xf1\xf5\x90\x8c\x80\x29\xb6\xd1\x5f\x3c\x68\xd4\xcf\ +\x68\x12\xa4\xcc\x89\x37\xd4\x82\xe8\x2a\x95\xac\xb6\xa5\xde\xad\ +\x9d\x08\x43\x90\x53\x51\x91\x90\x75\xf5\x0d\xab\x41\xf4\x2c\x80\ +\x8b\x23\x7a\x1f\x1e\x97\x83\x70\xff\xf8\xac\x29\xf4\x23\x69\xee\ +\xdf\xda\xda\xda\x0c\xe7\x9b\x43\x07\xdb\xbf\xb9\x76\xd2\x14\x99\ +\x08\xb7\x9f\x11\x32\x6e\x1a\x3f\x35\xeb\x85\x4f\xf6\xec\xd1\xdd\ +\x40\x85\x1d\x01\x05\x52\x79\x1e\x88\xa6\xa9\x44\xb2\xc2\x01\x57\ +\x24\x8f\xef\x5c\xb0\xf4\xa2\x8b\x8f\x28\x0d\x44\x64\x18\xf9\x68\ +\xc0\x0c\xd7\xf6\x7d\x5f\xfc\x69\xce\x9c\x8a\x0b\x22\x71\xfd\xa9\ +\xfe\x17\x01\x7c\x76\x46\x40\x18\xc3\x27\x92\x1e\x08\xc7\x0f\xff\ +\x0a\x30\x7e\x11\x2c\xa0\x97\x5a\xeb\xd7\x77\x1a\x19\x97\x24\xc9\ +\xe6\x1b\x90\x37\x03\x98\x15\xc9\xd1\xa8\xc1\x98\xef\x4b\x0c\x6c\ +\x70\xb9\x5c\x86\xaf\xad\xb7\xa6\xe6\x14\x98\x34\x0f\x8a\x1f\x91\ +\x24\x49\x77\xb4\xeb\x2a\x9b\x2e\x95\x5e\x0e\xe6\xdb\x55\x22\x59\ +\x91\xf9\xa9\x08\x2e\x52\x5f\x20\xed\x79\x00\x79\x11\x78\xc3\x06\ +\x83\x4a\xb6\xef\xed\x8e\x38\x0a\xd3\x2d\x7d\xaf\x00\xfc\x91\x4a\ +\x94\xd1\xab\xa4\xe7\xeb\x71\x75\x03\x90\xa0\x24\x2c\x40\xf0\xfc\ +\xf0\x76\xeb\x16\xf7\xbf\x8c\x8c\x16\x94\x38\xef\x05\xc1\x19\xc9\ +\xb9\x91\x83\x1f\x9f\xe5\x28\xd7\xbd\x99\x21\x78\x3c\x9e\x00\x98\ +\x3c\x6a\x19\x81\xef\xd7\xe3\x86\x19\x4e\x3c\x37\xa8\x33\xd1\x16\ +\x23\x83\xa7\xdf\xcd\x67\x8c\x38\xb1\x84\x20\x5e\x11\x6e\x48\x0f\ +\x81\x48\x68\x7d\xbe\x43\xaf\x4f\x48\x00\xec\x0b\x17\x8e\x82\xea\ +\x5b\x0a\x00\x0a\xd1\x1b\x46\xc6\x7c\x36\x7e\x04\xea\x85\x52\xfc\ +\x91\x7d\x34\x90\x56\x6a\x44\xc8\x9d\x7c\xc5\x07\x20\xa8\x47\x6d\ +\x5a\x3f\x52\x73\xb4\xbc\x90\x00\xf0\x49\xdb\x2d\x00\x6c\x2a\xd1\ +\xdf\x5b\x3c\x55\x9f\x69\x79\x43\x90\x24\xc9\xc2\xc4\x3f\x89\xec\ +\x73\x6c\xc1\x84\x9f\x1a\xb5\x57\x56\x56\x2a\x60\x04\x3d\x38\x85\ +\x45\x48\x9e\x32\xf4\x15\x60\x31\x59\x7d\x49\x84\x6d\x46\x86\x7a\ +\x39\xed\xfb\x00\x2e\x31\xe2\xc4\x09\xd9\x05\x25\x0f\x5c\x67\x44\ +\x20\x70\xb0\xef\x8c\x2c\x2d\x47\x27\x00\x98\xa4\xbe\x54\x14\xfa\ +\x28\x84\xa3\x36\xc2\x98\x6f\xd4\x1e\x4f\x30\x02\x25\x86\x04\x12\ +\x1a\xdf\x79\x92\x96\x12\x1a\x00\xe2\x6b\x82\x05\x8a\xe1\xb7\x1f\ +\xe0\x38\x67\x81\xc3\x83\x08\x21\xef\xb4\x1a\x3e\x92\xb5\xbe\x8f\ +\xd3\x72\xf4\xbe\x02\x29\x41\x46\x80\x08\x7b\x7d\x3a\x97\x93\x5f\ +\x30\x18\x63\x0d\xdb\x47\x85\xf8\x9e\xa2\xa5\x44\x0c\x80\x60\x0e\ +\x9b\x63\x3b\xbd\x2a\xd3\xcb\xd6\x9e\x2b\x18\x06\xc0\x5b\x53\x33\ +\x00\x40\xbd\x13\xb4\x49\x92\xa4\x9e\xe0\x75\x03\x10\xb4\x45\xf6\ +\x0b\x11\x76\x03\xd2\xd6\x06\x11\x46\xc7\xb9\x01\x21\x61\xa4\x2a\ +\x42\x9c\x27\xc6\xb1\x20\x02\x73\xc8\xb0\x19\x82\xd7\x5b\xe9\x27\ +\xc0\x70\x85\x18\x57\x28\x30\xcc\x3e\x4f\x2f\x2d\x4d\x04\x60\x55\ +\x89\x7c\x1e\x8f\xc7\xa7\xe6\x84\xae\x03\x06\x4f\x6a\xcf\x5e\x03\ +\xe9\x46\x46\x98\xf1\x45\x64\x4f\xe3\x03\x22\xe3\x00\x58\x7a\xac\ +\x69\x1a\xd1\x31\x2d\x27\x34\x00\xc0\xa7\xc1\x56\x42\x67\x4e\x4d\ +\xfb\x5e\xc3\xf6\xf8\xc2\xd8\x76\xa2\x72\x6d\xd0\x35\xa3\x4b\x4b\ +\xd1\x5b\x07\xec\x57\x5f\x12\xc8\x70\xb1\x01\xa6\x7a\xc3\xf6\x38\ +\x82\x58\x18\xda\x26\x16\x41\xbe\x33\x70\x40\xcb\x09\x09\x80\x60\ +\x04\x1d\x36\x32\x30\x4d\xcb\x51\x43\x4e\x95\x9b\x00\x44\x75\x1a\ +\x13\x23\x7c\xda\x58\x5f\xb5\xdb\x88\x20\x98\x83\x7d\xd7\x19\xad\ +\x21\x01\xf0\x59\x6d\x3b\x00\x9c\x49\x1f\x11\x30\xa5\xd0\xe1\x0c\ +\xfb\xb9\x19\xcc\x0c\x53\x8d\x09\x87\x63\x0b\x42\x15\x0c\x52\xf2\ +\x2e\x97\x4b\x30\x68\x4e\x90\x90\xe1\xd5\xf2\x42\x02\x70\xfa\x6c\ +\x6d\x87\x5a\xe6\x27\x8d\x22\x0d\xac\xc2\xff\x24\x80\xa3\x86\x0e\ +\xc7\x16\x9f\x1f\xa7\x94\x95\x46\x84\x77\x3e\xec\xce\x41\xd0\x1a\ +\x85\xfa\xfd\x3d\x19\x3b\xb5\x3c\xdd\x6f\x38\x01\x9a\xed\xaf\x52\ +\x64\x64\xac\xc1\xb3\xfe\x2b\xa6\x88\x19\xa3\x58\x62\xf9\x0e\xcf\ +\xca\x93\x46\x04\x12\x5a\x9f\xf9\x2d\xbd\xf4\xb8\x6e\x00\x58\x56\ +\x6a\x01\xa8\x8e\x9a\x69\x66\xa1\xb4\xc8\x70\xc7\xe7\xff\x7a\xec\ +\x2a\x00\x8d\x46\x9c\xd8\x80\x5e\x69\xae\x73\xd7\x1a\x31\x5c\x2e\ +\x97\x20\x26\xed\x26\xed\x65\x3d\xae\x6e\x00\x9a\xb7\xac\xeb\x26\ +\x42\x93\x4a\x94\x28\x2b\x56\xed\x71\x78\x10\xbc\xde\x4a\xbf\x1c\ +\xf0\xdf\xcd\x40\x3c\x0f\x49\xdf\x93\x53\xe4\x0a\x44\x38\x8e\xdb\ +\xb1\xaf\xfb\x1e\xa8\xce\x21\x08\xf8\x52\x3e\x92\xd1\xa4\xc7\x0d\ +\xbb\x8c\x65\xf0\x1f\xd4\xd7\x04\x7e\x68\xa6\xa3\xec\x6a\x23\xc3\ +\xde\xcd\x35\x7d\xcc\x81\x3b\xe2\x14\x84\x9d\x8a\x8c\xbb\x22\x1d\ +\xc7\x49\x92\x64\x63\xe6\x5f\xab\x65\xcc\xbc\x32\xdc\xe9\x50\xd8\ +\x00\x34\x6f\xac\x7e\x9b\x38\x68\x32\xb4\x59\x08\x4f\x44\xf2\xb2\ +\xb5\x7e\x7d\xa7\x3f\xe0\xbf\x05\x20\xdd\x88\x0f\x0b\xcc\x7f\x3c\ +\x2e\x52\xf2\x22\x25\x66\x01\xa0\x57\x49\xad\x40\xf0\xb6\xb7\x27\ +\xd9\xcf\x6b\xc2\xf1\x8d\x36\x32\xac\x08\x2c\x0f\x16\xd1\x7d\x76\ +\xc9\x69\xb8\x07\x07\x06\x47\x82\x7c\xe4\x5b\x77\x82\xe8\x97\xac\ +\xb3\xfc\x34\x0d\xc6\xd7\x00\x2d\x6d\xae\xaf\x5e\x10\x69\xd2\x03\ +\x80\xe9\xf7\x54\x8c\x21\xd0\xaf\x34\x3a\x7e\xb3\x65\xcb\xba\xb0\ +\x3e\x18\x66\x56\x3b\x3b\xda\xbb\x32\xbf\x9d\x93\x09\xe0\x3b\xa7\ +\x45\x04\x46\xe1\xb8\xeb\xa6\xbc\x76\xe8\x60\xfb\x37\x46\x7d\xbb\ +\xba\xda\x94\xce\x8e\xf6\x77\xc7\x4f\xbc\xb9\x9a\x48\xb9\x10\x40\ +\x16\x60\x7a\xf7\x76\x94\x80\x55\x6c\x11\x3f\x68\xd9\xb8\xf6\x5d\ +\x33\x1d\x24\x49\xb2\xc9\x72\xe2\x56\xd0\xd9\xb4\x17\x01\x7b\x7a\ +\xc6\x88\xb2\x7f\xee\xda\x15\xb6\x76\x28\xe2\xe9\xb0\xbd\x78\xc9\ +\xa5\x6c\xf1\xef\x01\xe3\x32\x95\x78\xbb\xf5\x44\xf2\xcc\x86\x86\ +\xd5\x03\x66\x9c\x03\x06\x53\xe7\xa7\x92\x94\xdb\x05\xa3\x84\x81\ +\x6c\x0c\x66\x91\x87\xce\x0d\xbf\x02\xa8\x1b\xcc\xed\x24\xc8\x93\ +\x46\x7d\xad\xda\x5d\x5b\x24\x14\x94\x38\xd7\x00\x58\xa2\x12\xc9\ +\x42\xf0\xb4\x48\x65\x3b\xa6\x0a\x24\xf2\x1d\xce\x5b\x88\xe0\x85\ +\xaa\x22\x8c\x41\xeb\x5a\xea\xd6\x3a\x31\x82\x02\x89\x5c\x69\x59\ +\x72\xfa\x71\xbf\x12\x4d\x20\xf5\x60\x9f\x5f\xfe\x20\x33\x3f\xaf\ +\x96\x11\xc3\xd9\x54\xef\xae\x8e\xd4\xd7\x74\x91\x54\x81\xa3\x6c\ +\x21\x88\x82\x2a\x2e\x18\xa8\xba\x48\x1c\x7d\x38\xda\xa7\x15\x43\ +\x90\xbd\xc4\xf9\x30\x03\x2b\xa1\x9a\xcf\x88\xb0\xaa\x69\xa3\x7b\ +\x99\x19\x05\xa6\x6b\x84\x3a\xf7\xef\xde\x93\x99\x95\x73\x01\x80\ +\xef\x9d\x31\x04\xe4\x9c\x52\x92\xf2\xae\xba\x61\xea\x1b\x5d\x7b\ +\x77\x9d\x88\xc6\xf3\x91\x42\x92\x24\x5b\xc6\xa4\x5b\x5f\x02\xb0\ +\x1c\xc1\x0f\xb2\x51\x3e\x92\xb1\xa8\xab\xab\xcd\x54\xcd\x60\x54\ +\xe9\xac\x74\xea\x5b\x8e\xc1\xf2\xb4\xb3\x20\xdc\x96\xe0\x0b\x7c\ +\x90\x2f\x55\x64\x47\xa3\x6b\x24\xb0\x17\x2f\xb9\xb4\x2f\x90\xda\ +\x0a\xa0\x4c\xd3\xb4\x4f\x0e\xf8\xef\x36\xaa\x08\xd1\x22\xea\x42\ +\x49\x49\x92\x2c\xbd\x4a\xfa\xef\x09\xac\x1d\x62\x32\x80\x35\xa4\ +\x58\x9f\x6e\xda\xf4\xe2\xbf\xa3\xd5\x6b\x06\xb9\xd2\xb2\xe4\x14\ +\xe5\xd8\x8f\x99\xf1\x18\x08\x17\x05\xb7\x72\x03\x0b\xcb\x3d\x2d\ +\x9e\xaa\xa8\x36\x65\xc3\x2e\x95\xb5\x3b\x9c\x65\x4c\x58\x83\xd0\ +\x4f\xdb\x71\x22\x3c\x6b\x49\x3c\xb9\x22\x9a\x82\x45\x23\x4c\x9f\ +\xee\xb2\x26\x8c\x39\x5c\x0a\xa6\x27\xa0\x7b\x06\xc9\x2b\xd2\x45\ +\xff\xa3\x66\xeb\x89\xd4\x18\x51\xb1\xb4\xdd\x51\x96\xc7\x44\xf5\ +\x00\x46\x87\xfa\x84\x5e\x02\xb6\x02\xd8\x6a\x49\x3e\xd9\x14\x6d\ +\x30\x24\x49\xb2\xf5\x04\xd2\xf3\x04\xf1\x5c\x00\xf3\x00\xe8\x2d\ +\xc3\x65\x62\x2c\x35\x33\xdb\x87\xc3\x88\xcb\xe5\xed\xf3\x16\x5d\ +\xc9\x56\xcb\x2a\x00\x0e\x03\x9a\x4c\x40\x1b\x13\xfe\xca\x4c\x07\ +\x2d\x4a\xe0\x63\x56\xb8\x27\x61\x54\xd2\x71\x85\xfa\x03\x03\xbe\ +\x94\x14\xc2\x40\x1a\x05\xc4\x38\x41\x98\xc0\x4c\xb9\x20\x9a\x0d\ +\x70\xaa\x81\xce\x0f\x48\x60\x69\x93\xc7\xbd\x6b\x24\xfe\xc7\xec\ +\x0f\x13\xf6\xf9\xe5\x85\xcc\xfc\x5b\x0c\x2e\x72\xe2\x07\x42\x37\ +\xc0\x4f\xa6\x53\xbf\x7b\x38\x43\x3e\x54\x5d\x0c\x31\x58\x4c\xdd\ +\x3d\x0f\xc4\x8f\x01\xb8\x29\x96\xba\x01\x74\x02\x58\x21\xa7\xf8\ +\xab\xa3\x2d\xd0\x34\x42\xdc\xfe\x34\x35\xbb\xa4\x3c\x8b\x81\x52\ +\x06\x17\x01\x98\x30\x1c\x1d\x04\x7c\xa9\x80\xde\x14\xac\xbc\x9c\ +\x9b\x3d\xf6\x9d\xe1\xfc\x1f\xc0\x84\x8d\xf8\xc3\x3e\x6f\xd1\x95\ +\x4a\x82\x65\x06\x81\xb2\x00\x65\x22\x98\xc6\x01\x48\x03\x90\x8a\ +\xc1\x93\x9b\xa3\x00\xfa\x01\xfa\x1c\xe0\x03\x0c\x1c\x60\x11\x68\ +\x6b\xf5\xac\xdf\x8f\xff\x82\x5a\xe4\xf3\x38\x8f\xf3\xf8\xdf\xc5\ +\x7f\x00\x80\x02\xea\x80\xb2\xb7\x05\xfa\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\xb2\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x64\x49\x44\x41\x54\x58\x85\xe5\ +\xd6\xb1\x4a\x03\x31\x1c\xc7\xf1\x6f\x72\x97\xfa\x06\x56\x90\x6a\ +\x29\x5d\xaa\x93\x93\x73\xeb\x03\x08\xfa\xa4\xe2\x52\x10\xda\x87\ +\x50\xeb\x52\x6e\x13\xd4\xc9\xfd\xae\xf7\x77\x90\x13\xda\x5e\xbd\ +\x24\x4d\xce\xc1\x8c\xc9\x1f\x3e\x3f\x92\x3f\x7f\x02\xff\x7d\xa9\ +\x36\xb1\x2c\xcb\xba\x5a\x9b\x3b\x34\xaf\xfd\x93\xde\x2d\x80\x6e\ +\x15\x4f\xd2\x39\x8a\x4b\x4a\x8e\xab\xfd\xb4\x55\x1c\x35\x02\x79\ +\x29\xcb\xe2\xba\x3a\x8b\xfe\x04\x5b\xf8\xaa\x18\x0f\x06\x83\xf7\ +\x56\x02\x34\xe1\x51\x03\xd8\xe0\xd1\x02\xd8\xe2\x51\x02\xb8\xe0\ +\xc1\x03\xb8\xe2\x41\x03\xf8\xe0\xc1\x02\xd8\xe2\xcb\xe5\xdb\x61\ +\x6a\xf2\x29\xf0\xd9\x3f\xed\x4d\x20\xc0\x24\x74\xc4\x67\xc0\x05\ +\x48\xa7\xda\xdf\x2b\x80\x07\x7e\x0e\x3c\x15\x79\xe7\xa6\x3a\xf3\ +\x7e\x02\x7f\xdc\x5c\x0d\x87\x47\x1f\x7b\x05\x08\x85\x7b\x05\x70\ +\xc4\xe7\xc0\x19\xf0\x5c\xe4\x66\xb2\x89\x3b\x07\x08\x8d\x3b\x05\ +\x88\x81\x03\x24\x21\xf1\x2c\xcb\xba\x49\x8a\x35\x0e\x16\x37\xe0\ +\x82\xeb\xc4\xcc\x5c\xf0\xc6\x00\x9e\xf8\xa2\xc8\xcd\xb8\x0e\x77\ +\x9a\x84\x91\xf0\xad\x49\x58\xfb\x27\x8c\x84\x57\xbd\xb1\x36\x09\ +\xb7\x9a\xd0\x0d\x4f\xe7\xa0\x7e\xc5\x6b\x1a\x73\x6d\x18\xe9\xcd\ +\x62\x47\x7c\x04\x2c\xca\x55\x5e\xdb\x70\x36\x8d\xa9\xd6\x8b\xfd\ +\x70\x9b\xba\x5d\x37\xa4\x01\x44\x44\xab\xc4\x3c\x34\xe1\x22\xa2\ +\x54\x62\xee\x9b\xf0\xcd\xba\x5d\xf8\x4f\x00\x00\x25\x1c\x08\x3c\ +\x36\xfc\x64\x94\x52\x74\xbe\xeb\xea\xf1\xba\x3a\x9b\x79\x80\x88\ +\x68\x11\x69\x1c\x4c\x22\xa2\x42\xd6\xfd\xf9\xfa\x02\x53\x42\xe8\ +\x88\x61\x1a\x4e\x81\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x03\x5e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x10\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x4f\x13\x51\x14\x86\xdf\x53\xd1\x21\x74\xa9\x84\x0f\xf7\ +\x6e\xb0\xdd\xb4\xc4\x8d\xfe\x0b\xc1\x48\x52\xdc\x98\x56\x89\xad\ +\xb2\x30\x81\x5f\xa0\x09\x0b\x4d\x5b\x23\xed\x4e\x49\x34\x01\xfe\ +\x05\xee\xa4\x1b\x0a\x2b\xd7\x14\x49\x74\x09\x32\x0a\x7d\x5d\xb4\ +\x94\x61\x66\x4a\x2b\x32\x3d\x6d\xb8\xcf\x6a\x3a\xe7\x4e\xf2\xde\ +\x27\xf7\xf6\x6e\xee\x01\x0c\x06\xc3\x65\x46\xda\x19\x14\x4d\x2c\ +\x84\xad\x81\xfe\x49\x02\xf7\x01\xde\x06\x30\x0a\xa0\x2f\xd8\x68\ +\xff\xcc\x21\x80\x0a\x20\x9b\x02\xac\xda\xfb\x07\xcb\x1b\x4b\x2f\ +\xf7\x5a\x7d\xd4\x42\x00\x25\x96\xcc\x4e\x8b\xc8\x2b\x00\x23\x17\ +\x93\xb3\x63\xec\x00\x98\x5b\x2f\xa4\x97\x00\x61\xb3\x41\x4d\x05\ +\xc4\x92\x85\xab\x02\x3b\x07\x41\x2a\x90\x78\x9d\x82\x28\x10\x56\ +\xba\x54\x4c\xfd\xf1\x2b\x37\x59\xc6\x14\x91\x7c\x1e\x40\xd2\x55\ +\x28\x8b\xe0\x0b\x88\xef\x55\xa0\x7a\xb1\x49\xff\x8f\x10\x10\x82\ +\x60\x98\xc4\x5d\x00\x91\x46\x41\x90\x12\xda\x00\xf8\xd4\x6f\x25\ +\xf8\xae\x80\x78\x2a\x3b\x0d\xe0\x83\xe3\xd5\x4f\x52\x32\xa5\xe2\ +\xb3\xcf\x67\x2d\xa7\xee\x80\x12\x4b\xe6\x1f\x8a\x30\x0b\xe0\xba\ +\xa3\xf0\x68\xbd\x90\xf9\xe8\x1e\xed\x11\x10\x4d\x2c\x84\xaf\x0d\ +\x58\xdf\x70\xb2\xe7\x7f\x90\x47\xd1\x52\x71\x76\x27\x98\xc0\xc1\ +\x10\x4b\xbe\x19\x11\xb9\xb2\x01\xe0\x06\x00\x80\xa8\xfc\xfe\x65\ +\xdf\x72\xff\x31\x86\xdc\x1f\x5a\x03\xfd\x93\x70\xfc\xe1\x91\xf2\ +\xbc\xd7\x26\x0f\x00\xa5\xe2\xec\x8e\x08\x5e\x34\x5e\x08\x46\xad\ +\xb0\x35\xe1\x1e\xe7\x11\x50\x3b\xea\x1a\x94\x6b\xcb\xbe\x37\xf9\ +\xba\x98\xfe\x04\xa0\x7c\xfc\x9b\x94\xd6\x02\xea\xe7\x7c\xed\x09\ +\x5c\xeb\xfe\x3d\x7f\x16\xc2\xda\x1c\xea\x90\x63\xee\x11\x3e\x02\ +\x30\x7a\x52\x94\xdd\x60\x82\x75\x8e\x53\x73\x10\xdc\xf4\xd6\xbd\ +\x34\x8e\xc6\x6e\x3b\xea\xce\x83\x6b\x0e\x9e\x63\xdf\x4f\xc0\xa5\ +\xc2\x08\xd0\x0e\xa0\x8d\x11\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\ +\x46\x80\x76\x00\x6d\x8c\x00\xed\x00\xda\x18\x01\xda\x01\xb4\x31\ +\x02\xb4\x03\x68\x63\x04\x68\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x11\ +\xa0\x1d\x40\x1b\x23\x40\x3b\x80\x36\x46\x80\x76\x00\x6d\x8c\x00\ +\xed\x00\xda\x18\x01\xda\x01\xb4\x31\x02\xb4\x03\x68\x63\x04\x68\ +\x07\xd0\xc6\x08\xd0\x0e\xa0\x8d\x9f\x80\x43\x47\xb1\xe7\x05\xb9\ +\xe6\x70\xe8\x53\xf7\x50\x39\x7e\xa8\x82\x43\x41\x84\xea\x24\xa7\ +\xe6\x40\x6c\xbb\xeb\x3e\x02\x64\xb3\xf1\x04\xb9\x07\xb0\xad\x9e\ +\x82\xee\x84\x52\x9b\x43\x1d\x91\x2d\xf7\x08\x8f\x00\x01\x56\x1d\ +\x3f\x23\xe3\xa9\xfc\x64\x30\xe1\x82\x27\xfe\x24\xfb\x00\x8e\x9b\ +\xe3\x22\x5c\x71\x8f\xf1\x08\xb0\xf7\x0f\x96\x51\x6b\x36\x00\x00\ +\x50\x98\xbb\xf3\xf8\x6d\xcf\x6d\x85\xf1\x99\x77\xc3\x80\x64\x1b\ +\x2f\x88\x8a\xbd\x67\xb7\x16\x50\xbf\x4d\x3d\xe7\xf8\x70\xf0\xa8\ +\x2f\x54\x8e\x25\x73\x53\xbd\xb1\x1d\x28\xb1\x64\x6e\x8a\xd5\xa3\ +\x0d\x10\x83\x8d\xd7\x82\x79\xbf\x16\x9a\x26\x13\xa2\xc4\x93\xb9\ +\xf7\x3e\xdd\x22\x65\x82\x6b\x21\xc8\x6e\xb7\xdd\x22\x0d\x01\xa1\ +\x2a\x38\x54\xdf\xf3\x91\xd3\x55\x2e\xae\x17\x32\x33\x7e\xf7\x9e\ +\x9b\x74\x8c\x08\x89\x42\x5a\x68\xc3\x25\x21\x22\x90\x08\xd1\x66\ +\xb7\x55\x07\xa9\x65\xf2\x4b\xc5\x45\xb2\x3f\xd3\xec\xd2\x77\xcb\ +\xa6\xa9\x78\x2a\x97\x00\xf0\x1a\xbd\xd6\x34\x45\x54\x20\x98\x3f\ +\x77\xd3\x94\x93\x68\x62\x21\x6c\x85\xad\x09\x52\x26\x40\x8e\xd5\ +\x6f\x5d\x77\x5f\xdb\x1c\xb1\x0d\x91\x2d\x11\xae\xd8\x7b\xf6\x4a\ +\x3b\x6d\x73\x06\x83\xe1\x72\xf3\x17\xf4\xb0\xe5\x26\x61\x1e\x11\ +\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x8d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x3f\x49\x44\x41\x54\x58\x85\xed\ +\x92\xb1\x4a\x03\x51\x10\x45\xcf\x4d\x02\xa2\x18\x82\xad\xac\xd9\ +\x4d\x5a\xc1\x5f\xb0\xb0\xb4\xb0\xb3\x13\xed\x2c\xfc\x02\x41\xb0\ +\xb2\xf1\x07\x14\x49\x61\xab\x62\x67\x2d\xe8\x1f\xf8\x03\xba\x6f\ +\xb3\x20\xa6\xd1\xca\x42\x93\x37\x56\x09\x62\xb7\x6f\x61\x1b\xf7\ +\x74\x03\x33\x77\x0e\xef\x0d\xd4\xd4\xd4\xfc\x77\x54\xa4\xd9\xcc\ +\xe4\xb2\xdc\x03\x98\x1f\x2f\xf5\x7a\xbd\x8f\xb2\x02\x8d\x82\xfd\ +\x33\x61\x35\x5a\xef\x66\xd6\xac\x54\x40\x92\x17\xda\x9e\xd6\x2e\ +\xcb\xc7\x95\x0a\x00\xc4\x71\x74\x83\xe9\x64\x5a\xa7\xe9\xf0\xa9\ +\x52\x01\x80\x24\x89\x8e\x80\x7b\x00\xc4\x9a\x73\xd9\x59\xa8\x40\ +\xa1\x23\xfc\x4b\xea\x86\xf6\x2b\x68\x3f\x8e\x57\x2e\x2a\x15\x30\ +\xb3\x86\xcb\xf2\xc9\xb4\xf6\xb2\xf5\x7e\xb7\xfb\x58\x24\x23\xe8\ +\x0b\xa6\x48\xf2\x0b\xf3\x73\xed\x59\x98\xe9\xa1\x68\x46\x29\x01\ +\x80\xd1\x68\xf4\x05\x4a\x43\xe7\x4b\x09\x98\x99\x16\xdb\x9d\x01\ +\x58\x02\x7a\xf3\x93\x66\x52\xa9\x40\x9a\xe5\xc7\xc0\x0e\xf0\x29\ +\x26\x9b\xfd\xfe\xb2\x2b\x9a\x11\x7c\x84\x2f\x2e\xdf\x15\x76\x09\ +\x78\xa1\xad\x38\x8e\xee\x42\x72\x82\x5e\xc0\xb9\x7c\x43\xd8\x00\ +\xc0\xa4\x83\xd0\xe5\x41\x02\xce\xb9\x55\xc3\x6e\x81\x96\xc1\x69\ +\xaf\x1b\x9d\x87\x2e\x2f\x2c\x60\x66\x32\x1a\xd7\x40\x47\xe8\x2a\ +\xe9\x46\x87\x65\x96\x03\xb4\x02\x66\x5e\x81\x67\xef\xbf\xf7\x24\ +\xf9\xb2\x02\x35\x35\x35\x35\x3f\x6e\x39\x66\xc8\x1a\xa6\xbc\x56\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x83\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x35\x49\x44\x41\x54\x58\x85\xed\ +\x97\x31\x4e\x02\x51\x14\x45\xcf\x65\x12\x28\x91\x06\xd7\x30\x1b\ +\x18\x22\xb5\x09\xb4\x1a\x3b\x56\x81\xb5\x5a\x48\x2f\xab\xa0\x53\ +\x8c\x95\x31\xb1\x36\x71\x36\xc0\x1e\x68\xc0\x52\x93\x99\x6b\x01\ +\x93\x20\x82\x85\x99\x89\x85\xff\x96\xef\xbf\xfc\x7b\xf2\xfe\x2f\ +\xde\x85\xff\x2e\x6d\x17\x92\x5b\xf7\x54\xf3\x39\x90\x00\x07\x25\ +\xf9\x2c\x81\xd4\xb9\x6e\xd2\x33\x3d\xed\x05\xe8\xdc\x65\x23\xa4\ +\x0b\xc3\xbb\x60\x66\x78\x2b\xc3\x5d\xd0\x34\xc4\x82\x06\xf2\xe8\ +\xf5\x24\xba\xfa\x06\x70\x34\x75\x3f\xc7\x8f\x88\xe7\xc8\x1a\xbc\ +\x9c\x6a\x5e\x86\x79\xa1\xee\xd4\xed\x4c\x9e\x60\x8e\x9d\xab\x5f\ +\x4c\xa2\x56\x34\xe4\x78\x68\x78\xaf\xc2\x1c\xe0\xe5\x54\xf3\xc8\ +\x1a\x00\x1f\x8a\x3c\x2c\xea\xb5\x8d\x9e\x44\x30\xab\xc2\x7c\x13\ +\x02\x98\x61\x92\x5d\x00\x07\x65\xbd\xf9\x4f\xf2\xea\x43\xb6\x76\ +\x01\xfc\x89\x02\x40\x00\x08\x00\x01\x20\x00\x04\x80\x00\x10\x00\ +\x36\x01\x96\x82\x66\xd5\x86\x5a\xad\xfa\x8b\x5d\x00\xa9\x21\xee\ +\x4e\xdd\xae\xca\x7c\x7d\x77\x8c\x48\xbf\x01\x38\xd7\x8d\xa0\x91\ +\xc9\x93\x2a\x20\x3a\x0f\x3e\xcc\xe4\x09\x50\x77\xa6\x71\x51\xff\ +\x1a\x4c\xee\xb3\x6b\xac\x4b\xe0\x83\x55\x30\x59\x96\x61\xbe\x1e\ +\x7b\x0c\xd4\xf7\x06\x93\x42\xc9\xad\x7b\x8a\x3c\x5c\xaf\xce\xad\ +\xed\xf3\x5f\x6a\x81\x48\x9d\x69\xbc\x1d\xcd\x82\x3e\x01\x68\xb1\ +\x6f\x2f\x7c\x41\x27\x3e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x03\xeb\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x9d\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x3f\x6c\x52\x51\x14\xc6\xbf\xf3\x78\xe8\xa4\xd8\xa8\x69\x22\ +\xc6\xa9\x83\x75\x50\x6b\x5d\xdc\x48\x10\x1c\x34\xa4\xa6\x25\x0e\ +\xd6\xd8\x28\xb3\x71\x33\x61\x90\xd4\xc4\x18\xdd\xd4\xc5\x01\x4c\ +\x35\x2e\xa6\xf6\x4f\x88\x0e\x52\x9b\x30\x54\x5d\xaa\x55\x07\x98\ +\xea\x60\x64\xa8\xf1\x1f\x6e\xd8\xf2\x8e\x43\xd1\x3e\x1e\x0f\x5a\ +\x7a\xdf\xe3\xb6\x72\x7f\xdb\x3d\xef\xdc\xc3\x77\xbf\xbc\x77\xef\ +\x4d\xb8\x17\x50\x28\x14\xed\x0c\xad\x25\x29\x10\x48\xe8\xfa\xae\ +\x42\x84\x18\x67\x00\x1c\x05\xe0\x07\xb0\xd5\x55\x65\xcd\x53\x02\ +\x50\x00\x30\xcb\x84\xc7\x4b\x5f\xfd\xe9\x6c\x76\x78\x69\xb5\x4e\ +\xab\x1a\x10\x3e\x1d\x0b\xb1\x86\xdb\x00\xba\x1d\x10\xd9\x42\x28\ +\x47\x06\x5f\xce\x4c\x24\xa7\x1a\x65\x79\x1a\x55\x08\x0d\xc4\xe2\ +\x20\x8c\x00\xd8\xed\xa8\xb6\xd6\xb0\x1b\x84\x73\x5d\xdd\x3d\xbf\ +\xe7\xf3\x73\x2f\xeb\x25\xd5\x35\x20\x34\x10\x8b\x83\x71\xdd\x1d\ +\x6d\x2d\x84\x28\xd8\xd5\xdd\x53\x9a\xcf\xcf\xcd\xd8\x3e\xb6\x0b\ +\x56\x5e\xfb\x4c\x55\x90\xf1\x83\x89\xaf\x6a\x1a\x3d\xf3\xa1\xf8\ +\x69\x74\x74\xb4\xec\x82\xdc\x75\x13\x8d\x46\x3d\x45\xf8\xf6\x19\ +\x06\x9f\x24\xa6\x6b\x20\x74\x98\x9f\x93\x81\xb0\xdd\xe7\x50\x63\ +\x40\x20\x90\xd0\xbd\x3b\x0b\x1f\x60\xfa\xe6\x09\x78\x51\x5e\xc4\ +\xe0\x74\x3a\xb9\xe0\x8a\x7a\x87\x09\x46\x62\x9d\x1e\x2f\x1e\x31\ +\x70\x7c\x25\x4a\xb9\xc5\x6f\x7b\x0e\x59\x27\x46\xcd\xda\x59\xdf\ +\x55\x88\xa0\x7a\xc2\xfb\x0e\x43\x3f\xbb\x59\x06\x0f\x00\xd3\xe9\ +\xe4\x42\x79\x11\x83\x60\xfc\x58\x89\xf2\x81\xca\xd8\xaa\xa8\x31\ +\xa0\xb2\xd4\xad\x74\x03\x27\x32\x13\xf7\xbe\xb8\x21\xd4\x4d\xa6\ +\xd3\xc9\x05\x06\x25\xcc\x31\xeb\xd8\x00\x1b\x03\xb0\xbc\xce\xaf\ +\x24\x68\xf4\xcc\x61\x6d\x2d\x43\xf3\xf0\x53\x73\x9b\x80\xde\x9a\ +\x1c\x9b\x7e\x7e\x73\xc3\x87\xe2\x27\x87\x75\xb5\x0c\xab\x76\x06\ +\xf6\x5a\x73\xec\x0c\xa8\xda\xe1\x6d\xb4\xd9\xbe\x19\x6c\xb4\xd7\ +\xec\x5e\xed\x0c\x68\x2b\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\ +\x6c\x94\x01\xb2\x05\xc8\x46\x19\x20\x5b\x80\x6c\x94\x01\xb2\x05\ +\xc8\x46\x19\x20\x5b\x80\x6c\x74\x27\x8a\x84\x06\x2e\x84\xc1\x9e\ +\x5b\x00\x1f\xc4\x1a\xff\x6b\x10\x80\x01\xbc\x07\x19\x57\xa6\x9e\ +\xdc\xcf\xac\x9a\xbd\x0a\xc2\x6f\x40\xb8\xff\xe2\x79\xb0\xf6\x1c\ +\xe0\x43\x70\x7f\xf0\xa8\xfc\xc6\x61\xb0\xf6\x3c\xdc\x7f\xf1\xbc\ +\x68\x31\x21\x03\x02\x7d\x43\x3b\x0c\xd0\x5d\x51\x11\xeb\x85\xa1\ +\xdd\x09\xf4\x0d\xed\x10\xa9\x21\x64\xc0\x16\xdd\x7b\x8c\x80\x6d\ +\x22\x35\xc4\xe0\xed\x5b\x74\xef\x31\x91\x0a\x6d\x3f\x09\x0a\x19\ +\xf0\x7b\x69\xf1\x35\x40\xbf\x9c\x12\xd3\x3c\xf4\x6b\x59\xc3\xfa\ +\x11\x32\x20\x3b\x39\xf2\x93\x60\x5c\x12\xa9\x21\x02\xc1\xb8\x94\ +\x9d\x1c\xf9\x29\x52\x43\xf8\x13\xc8\x8c\xa5\x1e\x80\x8c\x13\x00\ +\xde\x61\x79\x89\x72\x1b\x06\xe8\x3d\xc8\x38\x91\x19\x4b\x3d\x10\ +\x2d\xe6\xc8\x3e\xa0\xb2\x1e\x0b\xaf\xc9\x32\x50\x93\xa0\x6c\x01\ +\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\ +\x20\x1b\x65\x80\x6c\x01\xb2\x51\x06\xc8\x16\x20\x1b\x65\x80\x4d\ +\xac\x64\x6e\x44\xa3\xd1\x46\xe7\x89\x37\x34\x36\xda\x4b\xd6\x1c\ +\x3b\x03\x0a\xe6\x46\x11\xbe\x7d\x4e\x8a\x6a\x25\x56\xed\x04\x7c\ +\xb6\xe6\xd8\x19\x30\x6b\x6e\x18\x06\x9f\x74\x58\x57\xcb\x30\xca\ +\x74\xca\xdc\x66\xe0\x8d\x35\xa7\xc6\x00\x26\x3c\x36\xb7\x89\xe9\ +\x5a\x30\x12\xeb\x74\x5e\x9e\xbb\x04\x23\xb1\x4e\x02\x0f\x9b\x63\ +\xd6\xb1\x01\x36\x06\x2c\x7d\xf5\xa7\x01\xe4\xff\x05\x08\x1d\x1e\ +\x2f\x1e\x6d\x26\x13\xfe\x1e\x96\xae\x3e\x31\x4e\xb9\xca\xd8\xaa\ +\x68\xee\xb8\x3c\x28\xa1\x79\xf8\xe9\x86\x3e\x2e\x5f\xa6\x53\x04\ +\x1e\x5e\xf7\x71\xf9\xbf\xfc\x37\x17\x26\x00\x10\x73\x3c\x33\x9e\ +\xba\x61\xf7\xac\xee\x12\xf7\x31\xf7\x76\xa6\xab\xbb\xa7\x04\xa2\ +\xa0\x7b\xd2\x5c\x87\x19\x88\x4f\x8d\xa7\x6e\xd6\x4b\x68\xb8\xc6\ +\xcf\xe7\xe7\x66\xba\xf6\x1f\x79\x05\xa2\x5e\x6c\xba\x7b\x43\x94\ +\x23\x03\x83\x53\xe3\xc9\x87\x0d\xb3\xd6\x52\xca\x7c\x6d\x8e\x80\ +\xde\xca\xa9\xeb\x0d\x77\x6d\x8e\x80\xcf\x0c\xbc\x69\xe6\xda\x9c\ +\x42\xa1\x68\x6f\xfe\x00\x06\x14\x1b\x10\x41\x9d\x58\x08\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\x15\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xc7\x49\x44\x41\x54\x58\x85\xe5\ +\x97\x51\x48\x5d\x65\x1c\xc0\x7f\xff\xef\xea\x5d\xf3\xc1\x6d\x21\ +\xcc\x4a\xd9\x26\x2b\xb6\xa8\x1e\x5a\x0c\x0a\x56\x2b\xf5\x9a\x0c\ +\xa7\x33\x0e\x11\x42\x36\x6d\x16\x44\x2f\x41\xe0\xe8\xe1\x20\x45\ +\x13\x7a\x2a\xc6\x62\x4e\x2d\x22\x9f\xae\x57\x4b\x6b\xb6\x7b\x75\ +\x5c\x5f\x16\xc3\x42\x46\x2b\x84\xc8\x46\x5d\xb5\x88\x0d\x8d\x5a\ +\xea\xbd\xf7\xfb\xf7\x70\xaf\x76\xbd\xd7\x39\x2f\x5e\x7b\xd9\xff\ +\xe9\x9c\xef\xfc\xbf\xff\xef\xf7\x1d\xce\x39\xdf\xff\xc0\x9d\x1e\ +\x92\x4d\xb2\xaf\xf6\x78\xa9\xf5\xe4\xd5\x89\xb1\x15\xa8\x94\x02\ +\x25\x80\x11\x98\x52\x88\xa0\x3a\x8a\xe4\xf5\x87\x02\x67\x7f\xcc\ +\xa9\x40\x95\xd3\x7c\x30\x6e\x4d\xbb\xa0\x4f\xaf\xb3\xee\x18\xa2\ +\x27\x43\xbd\x5d\x23\x1b\x12\xa8\x70\x5a\xb6\x89\xb5\x1f\x02\x2f\ +\x24\x87\x66\x14\x06\x0d\x3a\x14\x47\x26\xbd\x26\x3e\xb3\x18\x8b\ +\xdb\x3c\xb3\xa5\x38\xae\x76\xb7\x88\xf8\x80\x5a\x60\x57\x32\xff\ +\xbc\x8d\xd2\x34\x32\xd0\xf9\x7b\xd6\x02\x55\x4e\xf3\x5e\x6b\x65\ +\x00\xd8\x9f\x00\x8b\x1b\xbb\x7e\xef\x47\xe1\x70\x5b\x6c\x2d\x69\ +\xd7\x75\xcd\xa5\xab\x53\xcf\x03\xef\x00\x65\xc0\x2f\xc6\xda\xa3\ +\x17\xfa\xbb\xaf\xac\x5b\xa0\xbc\xfe\x78\x99\xc1\x73\x19\xa1\x48\ +\xe0\x73\xcf\x5d\xff\xbc\x38\xd4\xd3\xf3\xe7\x5a\xe0\xf4\xa8\xae\ +\x7e\x7d\x4b\xb4\x60\xfe\x8c\xa0\x4d\xc0\xdf\x8a\x1e\x1a\x0e\x74\ +\x8d\xdf\x56\xa0\xba\xa1\xa1\x30\x36\x5f\xf0\x35\xe8\x83\xa0\xef\ +\x3f\xf1\x50\xc9\x1b\x6d\x6d\x6d\x36\x1b\x78\x6a\x7d\x5f\x7d\x73\ +\xab\x8a\xbc\x0b\x44\x8c\x9a\x83\x17\xfa\x3a\x66\x52\x13\x4c\xfa\ +\x8c\xd8\x7c\xc1\xe9\x04\x9c\xc1\x0d\xc2\x01\x34\xd8\xd7\xd5\x8e\ +\xd2\x09\x94\x58\x63\x3f\x25\x6d\xd1\x2b\x4e\x2a\x9f\x6b\x7a\x0c\ +\xcc\x18\xf0\x87\x1a\x73\xff\xb0\xbf\x63\x6e\x03\xf0\xe5\x70\x1c\ +\xc7\x3b\x6b\xb7\x5d\x01\xf6\x01\x47\x42\x81\xce\xf3\x4b\xd7\x56\ +\xdc\x01\xc1\x9c\x02\x50\x95\xb7\x73\x05\x07\xf0\xfb\xfd\x8b\x2a\ +\xbc\x95\x3c\x6d\x27\x65\xe1\xcb\x02\x55\xf5\x2d\xf7\x28\x94\x03\ +\x37\x76\x78\x66\xcf\xe6\x0a\xbe\x14\xc3\xbd\x9d\xfd\xc0\x04\xf0\ +\x70\xd5\xb1\xa6\x47\x32\x04\x14\x5b\x93\x30\x93\x2f\xfd\x7e\xff\ +\x62\xae\x05\x00\x45\x64\x00\x40\x3d\xe6\x58\xa6\x80\x70\x18\x40\ +\xd5\x7e\xb5\x09\x70\x00\x24\xae\x17\x00\xac\xf2\x4c\x86\x00\xaa\ +\xa5\x09\x3b\xfd\x79\xb3\x04\x8c\xe6\x4d\x02\x48\x62\x0f\x49\x13\ +\x90\xc4\x60\x7e\xd4\x3b\x93\x31\x33\x47\x21\x0b\xf9\x4b\xb5\xef\ +\x23\xf9\x20\x66\x7c\x07\xfe\xaf\x70\x5d\x37\x5d\x40\xa6\x00\x62\ +\x26\x56\xbc\x59\xd0\x85\xad\x37\x93\xb5\x75\x7a\xe9\x03\x97\xfa\ +\x0c\xfc\x0a\x20\xc2\x9e\xcd\x12\xc8\x47\xcb\x12\x2c\x22\x4b\x63\ +\xff\x09\x18\xc2\xc9\xa3\xaa\xcd\x12\x50\x31\x3e\x00\xc4\x5c\xcc\ +\x14\x58\xd4\xc1\xa4\xdd\x91\x03\x2d\x2d\xf9\x9b\xc0\x17\x45\x8e\ +\x26\xa9\xfd\x19\x02\xa1\x81\xee\x69\x84\x8b\x08\x45\x3b\xae\xdb\ +\x97\x73\x4d\xaf\xac\x3f\x51\x93\xdc\xe4\xbe\x0f\xf9\xcf\x2d\xf7\ +\x06\x2b\xde\x02\x6b\xa5\x15\x40\x04\xb7\xba\xa1\xa1\x30\x57\x70\ +\xc7\x71\xbc\x08\xa7\x00\x04\x3d\x09\xe8\xaa\x02\x23\x7d\xe7\xc6\ +\x54\xe9\x41\xd9\x19\x9f\xdf\xfa\x89\xeb\xba\xb9\x78\x4d\x65\x36\ +\xbe\xfd\x83\xe4\xea\xc3\xc1\x40\xd7\x17\xa9\x17\x33\x01\x1e\xf3\ +\x1a\x30\xa1\x50\x7b\xe9\x6a\xe4\xbd\x0d\x4a\x48\x65\x7d\xf3\x9b\ +\x88\xbe\x82\x30\x4d\xd4\x36\x90\xb2\x7a\xb8\x45\x4b\x96\xec\x07\ +\x2f\x03\x77\x03\x7d\x51\xe3\x6d\x0c\xfb\xcf\xfc\x95\x0d\xd9\x71\ +\x1c\xef\x9c\x2d\x3c\xad\xc8\x09\xe0\x26\xd8\xa7\x42\x81\xee\x6f\ +\xd2\xf3\x3c\xab\x4d\xfe\xe9\x87\xf1\x1b\x7b\xf6\x1d\xf8\x0c\xc1\ +\x27\x70\xc8\xa3\xf1\xc6\xbd\xfb\x1f\x9d\x2b\xdd\x59\xf3\xdd\xb5\ +\x6b\xa3\x6b\x76\x48\xae\xeb\x9a\xfc\xa2\x07\x9c\x05\xf5\xf6\x82\ +\x54\x92\x68\xc5\x7c\xc1\xbe\xce\x6f\x57\xcb\x5f\xb3\x2d\x3f\x5c\ +\xf7\xd2\xf6\x7c\x93\xd7\x81\xe0\x24\x87\x22\x02\x83\xa0\x43\x82\ +\x99\xc4\xd8\x99\x85\x68\xdc\x7a\x3d\xde\x62\x8b\xee\x02\xaa\x04\ +\xad\x25\xd1\x0d\x03\x12\x8c\x9a\x68\x63\xd8\xff\xf1\x6f\xb7\x62\ +\xac\xeb\xc7\xa4\xdc\x69\x7a\xdc\x58\xd3\x0e\x3c\xb9\x9e\x7c\x60\ +\x1c\xb1\xad\xa1\xde\xee\xe0\xed\x12\xb3\xfa\x35\x7b\xb6\xee\xd5\ +\xdd\x31\x13\xab\x13\x23\x15\xa2\x5a\xaa\x89\x6d\xd5\x03\x44\x80\ +\x88\xa8\x8e\x22\x9e\xfe\x60\xa0\x63\x22\x9b\xba\x77\x76\xfc\x0b\ +\xeb\x32\x64\xd4\x54\xc2\x43\x07\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x03\x64\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x16\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbf\x4f\x53\x51\x14\xc7\xbf\xdf\x17\x08\x90\x4e\xf2\x23\x02\ +\xee\x2e\x58\x17\x57\x4d\x4c\xac\x75\x73\xa8\x05\x23\x49\xd1\xa4\ +\xa5\x44\x13\xd0\x11\xfe\x02\x9d\xc1\x44\xac\x38\x68\x13\x4d\xa0\ +\xb2\x83\x6c\xb8\xba\x50\x98\x9c\x29\x92\x14\xb6\x0a\x44\xf2\x8e\ +\x03\x7d\x4d\x73\xfb\x6a\x11\x69\x4f\x1b\xee\x67\xba\x3d\xf7\xbe\ +\xf6\x7b\xbe\xbd\xf7\xdd\xe5\x1c\xc0\x62\xb1\x5c\x64\x78\x9a\x45\ +\xe1\x58\x2c\xe0\x1e\x74\x8c\x50\x10\x05\x70\x0d\xc0\x20\x80\xb6\ +\xba\x2a\xfb\x77\x8e\x01\xe4\x00\x6c\x0a\x91\x71\xba\x8e\x16\x57\ +\xd3\xe9\x42\xad\x87\x6a\x19\xc0\xf0\x83\xf8\x98\x80\x2f\x01\x0c\ +\x9c\x87\xca\x06\xb2\x23\xc4\xf4\x5a\x66\x21\x0d\x40\xaa\x2d\xaa\ +\x6a\xc0\x8d\x64\xb2\xbd\x3b\x2f\x73\xa0\x4c\xd4\x45\x5e\xa3\x10\ +\xbe\xdd\xef\xe5\xe4\xf7\x54\xea\xb7\xdf\x74\xb5\x6d\xcc\x4b\x7b\ +\xee\x6b\x10\x49\x23\x9e\x25\xf0\x4d\x20\x3f\x29\x8e\x7b\xbe\x4a\ +\xff\x0f\xa1\xeb\x10\xec\x17\xe0\x26\x80\x60\x69\x82\x32\xd1\x9d\ +\x07\x00\x3c\x85\xcf\x4e\xf0\xdd\x01\xa1\x68\x62\x8c\x82\x0f\x65\ +\xa1\x3d\x11\x99\x5a\x5b\x7e\xff\xd9\xef\x4b\x9a\x0c\x86\x22\xf1\ +\x47\x24\x67\x01\xf4\x78\x41\x21\x1e\xaf\x65\x16\x3e\x56\x2c\x36\ +\x03\xe1\x58\x2c\x20\xbf\x3a\x7e\xc0\x3b\xf3\x82\xbc\x03\xe7\xfa\ +\xca\x72\x6a\xa7\x8e\xa2\xcf\x9d\x7b\x91\xe4\x80\x0b\x77\x03\x44\ +\x2f\x00\x80\xc8\xb1\xeb\xe8\xaa\xf9\x62\x74\xcc\x07\xdd\x83\x8e\ +\x11\x94\xbd\xf0\x04\xf2\xbc\xd5\x92\x07\x80\x95\xe5\xd4\x0e\x1d\ +\xbe\x28\x05\x04\x83\x52\xe8\x1c\x36\xd7\x55\x18\x50\xbc\xea\x3c\ +\xb2\xc5\x6d\xdf\x92\xac\x66\xde\x7d\x02\x90\x2d\x05\x28\xb5\x0d\ +\xc0\xc9\x3d\x0f\x00\x10\x91\x75\x34\xff\x99\xff\x1b\x52\xcc\xc1\ +\x63\xc8\x5c\xe0\x67\xc0\xa0\x37\x20\xb1\x5b\x0f\x55\x8d\xc4\xc8\ +\xe1\x8a\x39\xef\x67\x40\xe9\x6a\x6c\xb6\xab\xee\x2c\x18\x39\x54\ +\x5c\xfb\x7e\x06\x5c\x28\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\ +\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\ +\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\ +\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\x1a\xa0\x2d\x40\x1b\ +\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xb1\x06\x68\x0b\xd0\xc6\ +\x1a\xa0\x2d\x40\x1b\x6b\x80\xb6\x00\x6d\xac\x01\xda\x02\xb4\xf1\ +\x33\xe0\xd8\x1b\x08\xdd\x96\x37\xc8\xc8\xe1\xd8\x9c\xf7\x4b\x30\ +\x57\x7a\x58\x70\xb9\x1e\xa2\x1a\x89\x91\xc3\xb6\x39\xef\x67\xc0\ +\xa6\x37\x20\x79\x0b\xa7\xec\x29\x68\x52\x58\xcc\xc1\x63\xcb\x5c\ +\x50\x61\x80\x10\x99\xb2\x8f\xc1\x70\x24\x31\x52\x0f\x65\x8d\x20\ +\x1c\x1d\x7f\x88\xf2\xca\x71\xe1\x92\xb9\xa6\xc2\x00\xa7\xeb\x68\ +\x11\x40\xa9\x36\x58\x88\xb9\x3b\xf7\x13\x2d\x77\x14\x6e\x0f\x3f\ +\xe9\x17\x91\xd9\x52\x80\xc8\x31\x70\x58\xdb\x80\xd5\x74\xba\x20\ +\xc4\x74\x59\xa8\xcf\x69\x47\x36\x14\x89\x8f\xa2\x35\x8e\x03\x43\ +\x91\xf8\x68\xbb\xdb\xb6\x01\xa0\xcf\x0b\x0a\x30\xe3\xd7\x42\x53\ +\x2d\x21\xde\x8d\x8c\xbf\xf1\xe9\x16\xc9\x8a\xc8\x3a\x89\xdd\x66\ +\xab\x22\x15\xba\x8e\x08\x2e\x17\xcf\x7c\xd0\x98\x9e\xff\xfa\x65\ +\xe1\x19\x7c\xea\x9e\xab\x75\x8c\xc8\x7e\x2f\x27\xbb\xf3\x80\x61\ +\x42\x90\x64\xf0\xe4\x07\x9b\xad\x86\x9a\xa0\xff\xdf\x39\xbf\xdf\ +\xe3\x4c\xa1\x4a\xd1\x77\xcd\xa6\xa9\x50\x34\x11\xa3\xe0\x15\x5a\ +\xad\x69\x8a\xc8\x09\x30\x73\xe6\xa6\xa9\x72\xc2\xb1\x58\x40\x0a\ +\x9d\xc3\xc5\x7a\xfb\x21\x9c\x54\x5d\x37\x63\xdb\xdc\x36\x80\x2d\ +\x08\x97\x18\x38\x5c\x3a\x4d\xdb\x9c\xc5\x62\xb9\xd8\xfc\x01\xdf\ +\x73\xe1\xb5\xcf\x33\xa6\xd1\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\xc8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x7a\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\xb1\x6d\xc2\x60\x14\x85\xd1\xef\x67\x88\x88\x81\x32\x01\x62\ +\x83\xd0\x78\x22\x9a\xac\x90\x36\x0d\x0b\x59\x2c\xe1\xb4\x91\x5d\ +\x83\x25\x38\xa7\xbc\x7a\xc5\x7d\xb7\x00\x00\x00\x00\x00\x00\x80\ +\x77\x30\xd6\xc1\xe7\xf9\x72\x1a\x4b\xd7\xea\x63\x87\x3e\x0f\x33\ +\x6a\x5e\xea\xeb\xf6\xf3\xfd\xfb\x3f\x3f\x6c\x0e\x5f\xf0\xf9\xaa\ +\xa5\x8e\xd5\x75\x9d\x6f\x06\x78\x37\x9b\x01\x96\xd1\x54\xdd\x77\ +\xe8\xf2\x50\xa3\xe6\x6a\xda\xbb\x07\x00\x00\x00\x00\x00\x00\x00\ +\xf0\x7c\x7f\x0b\xd1\x0f\x08\x20\x9f\x5b\xc7\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x04\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xb6\x49\x44\x41\x54\x78\x9c\xed\ +\xd9\x41\x0d\xc3\x40\x10\xc5\xd0\x69\x14\x4e\xe1\x51\xa0\xe1\x11\ +\x52\x9b\xc2\x78\x95\xd6\x26\x30\x96\xf5\x6f\x33\x03\xb9\xee\xf5\ +\x5e\xf7\x7a\xa5\xc3\x21\x8f\xff\x03\x05\xd0\x02\x9a\x02\x68\x01\ +\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ +\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ +\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x6c\ +\x1f\xe0\x23\x8f\xeb\xd7\xf8\x4c\x0b\x98\x53\x0b\xcc\xcc\x3c\xdf\ +\x83\x2d\x71\xfb\x05\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\ +\x9a\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\ +\x29\x80\x16\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\ +\x02\x68\x01\x4d\x01\xb4\x80\xa6\x00\x5a\x40\xb3\x7d\x80\x1f\x17\ +\x67\x0a\x44\xf8\xee\xeb\x4c\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x02\x1d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xcf\x49\x44\x41\x54\x58\x85\xed\ +\xd6\x3d\x8b\x53\x41\x18\xc5\xf1\xff\x99\x44\xf1\x05\x5f\x3a\x41\ +\x1b\x11\x2b\x0b\xb5\x31\x61\x11\x4b\x49\xb3\xb2\x59\x65\xd7\x46\ +\xd0\xd6\x42\xf6\x13\x88\x2c\x7e\x01\x51\xb0\x16\xb1\x90\x15\xcd\ +\x2e\x04\x71\xb1\x14\x89\x49\xa5\x16\x56\x16\x6b\x23\xd8\x28\x8b\ +\xf8\x82\x26\x73\x2c\xe6\x46\x2c\x73\x93\x30\x16\xfa\x14\x97\x5b\ +\xcc\xcc\xf9\xcd\xdc\x67\xe0\xc2\xbf\x5e\x1a\x65\x50\xad\x15\x3f\ +\xc9\x28\xf4\x75\xa8\xb3\xa8\x8f\xd3\x04\x84\x51\x06\xc9\xec\x05\ +\xf6\xc4\xaa\xdb\x47\xd7\xbd\x33\x3b\xe0\x8f\x9a\xd9\xfe\xd5\x0f\ +\x8f\xac\x78\xeb\x5f\x01\x38\x3d\x1a\xbb\xb6\xc4\xbb\x0b\x2b\xae\ +\x64\x07\x60\x22\xc2\x58\xe7\xdf\x55\xe2\x2d\xec\x91\x7a\x68\x6a\ +\x00\x09\x63\x6c\x83\xa4\xcb\xf5\xd5\xb8\x9c\x15\x50\x94\x81\x98\ +\xde\x74\xb5\xde\xf2\x52\x6e\x00\x12\xf6\x6f\x84\x6f\xd4\x5b\xbe\ +\x90\x15\x00\x20\xb0\xd1\x10\x71\xa7\xf6\xc8\xb3\x59\x01\x09\x61\ +\x1b\x1b\xa8\x08\x3f\xa8\xad\xfa\x54\x56\x40\x42\x28\x92\x10\xdb\ +\x14\xdd\x3e\xd1\xf2\xf1\xac\x80\x82\x11\x9d\x9a\x73\x77\xb0\x9f\ +\xcc\xac\xf9\x70\x66\x00\x28\x35\xa5\x81\x7d\x71\xe0\xa7\x27\xd7\ +\xbc\x3f\x2b\xa0\x50\xc4\xf4\x35\x38\xd8\x1f\xf8\x71\x7e\x40\x42\ +\x0c\xeb\x58\x7e\x80\x09\x85\x60\xa3\x5a\xd1\x81\xac\x00\x8b\x40\ +\x4a\xff\x10\x2a\x3a\xfd\x7c\x4e\xef\x33\x02\x1c\x64\x04\x6c\x1a\ +\x35\x3a\x73\x7a\x3b\xea\xcc\xea\xc4\xd1\x38\x08\x09\xf8\xee\xa0\ +\x33\xbd\xa6\x5e\x95\x99\x3f\xd1\x09\xd8\x52\x11\x3e\x30\x5a\xe8\ +\x35\xf5\xac\xec\x1a\x63\x9f\x80\x8d\x24\xa7\x0d\x48\x97\x7a\xf3\ +\x6a\x8f\xb3\xce\xb8\x27\x20\xa5\xa6\x43\x68\xa9\x3b\xaf\x7b\x63\ +\xae\x53\x1e\x60\x23\x18\xee\xdc\xd7\x5f\x9c\xd5\xcd\x71\xc3\x4b\ +\x03\x9c\x7e\x05\xd2\x5d\x97\x6f\x77\x9b\xe1\xda\x24\xe1\xa5\x01\ +\xc2\x21\xf5\x9c\xef\x77\x5f\x86\x2b\x48\xce\x0a\x48\x3b\x67\xfd\ +\x73\x3f\x5c\x64\xb9\xf8\x19\x99\xb0\xca\xde\x82\xce\xb7\x1d\x3a\ +\xf7\xa6\xa1\x1f\xd3\x08\x2f\x03\xd8\x44\x56\xf8\x19\x66\x5f\x37\ +\xf4\x65\x5a\xe1\xff\x0b\xe0\x17\x0f\x9e\xa4\x40\x97\xf1\x9c\xea\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xf8\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xaa\x49\x44\x41\x54\x78\x9c\xed\ +\xd0\x31\x15\x80\x30\x00\xc4\x50\x8a\xa6\x7a\x62\x43\x0c\x1b\x9e\ +\xf0\x54\x56\x1c\x7c\x86\x64\xbb\xe9\xf2\x32\x36\xc4\x3c\xae\xf5\ +\xdd\xcf\x7d\x0e\xe1\xb1\x8b\xd3\x3f\x51\x00\x2d\xa0\x29\x80\x16\ +\xd0\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\ +\x4d\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\ +\x14\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\ +\x01\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\ +\x40\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\ +\xb4\x80\xa6\x00\x5a\x40\x53\x00\x2d\xa0\x29\x80\x16\xd0\x14\x40\ +\x0b\x68\x0a\xa0\x05\x34\x05\xd0\x02\x9a\x02\x68\x01\x4d\x01\xb4\ +\x80\xe6\x05\x58\xe1\x04\x80\x5c\x86\x43\xbc\x00\x00\x00\x00\x49\ +\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x4d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xff\x49\x44\x41\x54\x78\x9c\xed\ +\xd6\xa1\x4a\x04\x51\x14\xc6\xf1\xef\xcc\x8c\x08\x06\xd3\xda\x7d\ +\x01\x41\x50\xb0\xda\x5c\xb6\x6c\xf1\x39\x2c\x3e\x80\xec\x03\xec\ +\x4b\xd8\x2d\xc2\x8a\xb6\x29\x86\x8d\xbe\x81\x69\x41\x6c\x06\x19\ +\x41\xef\x31\x58\xe4\x5e\xb5\xcd\x59\x70\xfe\xbf\x78\xce\x84\xef\ +\x7e\xe1\xce\x95\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x41\xb0\ +\x3f\xb7\xee\x76\xdc\xaa\x0e\xca\xd2\x8b\xb6\x55\xd2\xcc\xd2\x6f\ +\xfb\x1f\x0b\x38\xb8\xf6\x51\xf3\x9e\xe6\x92\x9d\x4a\xda\xea\x2d\ +\x5d\x8c\x4e\xae\x45\xd3\xd8\xd9\xfd\xd4\x56\xf9\xb2\x28\xe0\xe8\ +\xc6\xb7\xd5\xf9\x83\xa4\xdd\x88\x74\x51\x5c\x7a\xb6\xda\xf6\x96\ +\x53\x7b\xfa\x3e\xaf\x8a\x2f\xdf\xd2\x4c\xff\xec\xf0\x92\x64\xd2\ +\x8e\x7f\xa4\x79\x3e\x2f\x0b\x70\x3b\x09\x49\xb4\x06\x26\x1b\xe7\ +\xb3\xb2\x80\x81\x29\x0b\x30\xbf\x5b\x43\x8e\x10\x2e\xbf\xcd\x67\ +\x65\x01\x9b\xd5\x85\xa4\xc7\x80\x3c\xa1\xbe\x2e\xc1\xea\x3c\x9f\ +\x17\x05\x2c\x27\xf6\xe2\xb2\x43\xc9\x2f\x25\xbd\x86\xa4\xeb\x57\ +\x27\xd7\xd5\x46\x6d\xfb\xf9\x1f\x40\xe2\x21\x04\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x0c\xc5\x27\x17\xb6\x3b\xc1\x0d\x7c\x50\x9f\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x22\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ +\xd6\x31\x6b\x14\x41\x18\xc6\xf1\xff\x33\x17\x8d\x20\xd1\x74\x1e\ +\xde\xed\xad\x1c\x96\x82\xb6\x16\x96\x92\x26\x56\x22\x36\x82\xb6\ +\x16\x92\x4f\x20\x22\x7e\x01\x51\xb0\x16\xb1\x10\xc4\xee\x10\xc5\ +\xd2\xc2\x5a\xb8\x52\x48\x76\x37\x91\xb3\x51\x03\x11\x8c\x72\xf3\ +\x58\xec\x5d\x5a\x6f\xef\x96\x4d\xa1\xd3\xec\x2e\xcc\x3b\xcf\x6f\ +\xdf\x9d\x81\x85\x7f\x7d\x68\x96\x49\x5b\x59\xfe\x0d\xa4\x56\xa0\ +\x9f\x24\xc9\xd7\x3a\x01\x61\xb6\x69\x5a\x05\x4e\x8e\x23\x83\xd1\ +\x68\x74\xfc\x10\x00\x07\xe3\xe2\xfe\xfe\xef\x57\xc3\xe1\xf0\xe8\ +\xe1\x00\x6c\x0c\x6b\x2b\x2b\xab\xcf\x6c\xb7\x9a\x07\xa0\x28\x61\ +\xe3\xeb\x59\xb6\xf3\xd8\xf6\x4c\x7b\xa8\x3e\x80\x70\x34\x2e\xef\ +\x7d\x3b\x2b\x76\xee\x37\x0b\x00\x04\x06\x47\xdb\x60\xdf\xcd\xb2\ +\x62\xa3\x51\xc0\x84\x61\x29\x44\x00\xc3\xc3\x2c\x2b\x6e\x34\x0c\ +\x00\xb0\x91\xa6\x88\xa7\x59\xb6\xbd\xde\x30\x00\xb0\x4d\xb9\x27\ +\x5a\xc6\x2f\xf3\x3c\xbf\xd4\x2c\x00\x40\x44\xb0\x81\x63\xd1\x1a\ +\x6c\x6e\x6e\x5f\x68\x16\x50\x2a\x22\x60\xe0\x84\x02\x6f\x8a\xa2\ +\x38\xdb\x30\x00\x80\x38\x39\x21\xa7\xc6\x51\xef\xf2\x3c\x3f\xdd\ +\x34\x00\x43\x2c\x1b\xe1\x33\x11\xbd\x6e\x1c\x30\x55\x4c\xae\xe7\ +\x1b\x07\x08\x02\x12\xa0\xad\x20\x77\x66\xa9\x59\xaa\x31\x3f\x18\ +\x04\xfa\xd2\x0a\xbe\x9c\x24\xbd\xcf\x33\x15\xd5\x93\xed\x40\xf9\ +\x73\xb3\x1b\xc7\xac\x25\x49\xf2\x69\xd6\xca\x85\x01\x86\x40\xd9\ +\xf7\x9f\x41\xbe\xd2\xef\x77\x3f\x56\xa9\x5f\x10\x20\xa9\x7c\xf3\ +\xb1\xd0\xb5\x5e\xaf\xf7\xbe\xea\x0a\x8b\x00\x34\x69\x3d\x82\x5b\ +\x69\xda\x1d\xcc\xb3\xc8\xbc\x00\xd9\x07\xe1\x1b\x69\x9a\x3c\x9f\ +\x73\x9d\xea\xa7\xc0\xe5\x07\x0f\x65\xf3\xf5\x20\xed\x75\x1f\xcd\ +\x1b\x0e\x15\x3b\x60\x97\xe1\xe5\x83\x9e\xa4\x49\xe7\xde\x22\xe1\ +\x95\x01\x92\xa7\xe1\x2f\xd2\xb4\x73\x47\x92\xff\x52\x52\x2f\x00\ +\x84\xe0\xed\xde\xde\xf7\x9b\x9a\xfc\x8c\x2c\x3a\xaa\xee\x81\x0f\ +\xcb\xcb\x47\xae\xa6\xe9\xb9\x5f\x75\x84\x57\x00\x78\xd7\x46\x4b\ +\x2d\xad\xb7\xdb\xed\x1f\x75\x85\xff\x1f\x00\x7f\x00\x61\x3f\xa0\ +\x35\x7d\x81\xed\xd8\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x04\xe7\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x99\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xbd\x6f\x1c\x45\x18\xc6\x9f\x77\xf7\x1c\xa4\x74\xa9\x4c\x74\ +\x1f\x63\x1f\x4e\x91\x28\x52\x90\x92\x2e\x6d\xa0\x09\x50\x60\xa4\ +\x80\x44\xa2\xfc\x03\x11\x69\x40\xd8\x12\x4e\xb0\x14\x02\xa1\x81\ +\xbf\x00\x24\x2c\x50\x44\x42\x11\x39\x8d\xa1\x4a\x5a\xa7\x41\x60\ +\x37\xe1\xd8\x8f\xbb\x22\x14\x50\x22\x87\xdb\x7d\x28\xce\x23\xf6\ +\x6e\xf7\xbc\x7b\xde\x4f\xe3\xfb\x49\x2e\x76\xe6\xbd\x9b\x77\x1f\ +\x3f\xef\xec\xec\x69\x06\x98\x32\x65\xca\x61\x46\x92\x04\x91\xac\ +\xd9\x76\xf7\x0d\x0a\x2f\x09\xe4\x1c\x80\x3a\x80\x17\xf2\x4d\x6d\ +\x62\x76\x00\xf4\x08\x6e\x0a\xe5\xae\x52\x8d\x07\x22\xd2\x8f\xfb\ +\x50\xac\x00\xb6\x6d\xbf\x42\xc8\x97\x80\x9c\xcc\x24\xcd\xe2\xd8\ +\x12\xf8\xd7\x95\x52\x3f\xee\x15\x64\x8c\xeb\x20\x29\x96\xd3\x5d\ +\x26\x8c\x8d\x03\x78\xf3\x00\x70\x8a\x30\x36\x7e\xb7\xbb\x4b\x24\ +\xc7\xfe\xa3\xc7\x0a\x60\xbb\xbd\x25\x90\xb7\xf2\xc9\xad\x38\x04\ +\xfc\xc4\x72\x7a\x1f\x8e\xef\x8f\x60\x60\x7b\x63\x63\xa4\xf9\x2f\ +\x10\x2b\x80\xf7\x50\x29\xe5\x88\x88\x97\x69\xa6\x29\x21\x69\xda\ +\xb6\xdd\x02\xcc\x8b\x10\xac\x02\x38\x16\xec\x17\xf8\xaf\x46\x95\ +\x43\x48\x00\x92\x35\xdb\x71\x7f\x1e\xb6\x3d\x7f\xf2\xbd\xfe\xbb\ +\xed\x76\xfb\x59\x0e\xb9\x67\x4e\xa7\xd3\x99\x35\xcc\xda\x1a\x20\ +\x17\x02\xcd\x5b\xaa\xd5\x38\x33\x3a\x31\x86\x04\xb0\x2c\xf7\x4d\ +\x08\xee\x07\x9a\xfe\xec\xff\x33\x73\x72\x61\xe1\xc5\x3f\xf2\x4a\ +\x38\x0f\x06\x22\xcc\x6c\x23\xe8\x04\x62\x71\x6e\xae\xf9\x43\x30\ +\x2e\x34\x07\x50\x78\x69\xb8\x01\x37\x0e\xda\xcd\x03\x40\xbb\xdd\ +\x7e\x26\xc0\x8d\x60\x5b\xe8\xde\x10\x21\xc0\xee\x73\x3e\x80\xf7\ +\x30\xeb\xe4\x8a\x82\xf4\xd6\x83\xd7\x02\x39\x3b\x1a\x13\xf5\x14\ +\xa8\x07\x2f\x94\x52\x4e\xc6\x79\x15\x46\x44\xee\x8d\xd1\x98\x28\ +\x01\x86\x56\x78\x55\x9b\xed\x27\x21\x22\xf7\xd0\xea\x75\xec\x3a\ +\xe0\xb0\x50\x2b\x3b\x81\x24\xb8\xae\xbb\xe0\xf9\x58\x01\xb0\x08\ +\x00\x04\xef\x99\x82\xd5\x56\xab\xf5\x5b\xda\xef\xae\xbc\x03\x5c\ +\xd7\x3d\xe1\xf9\x78\x04\xe0\x32\x80\xa3\x00\x8e\x0a\xe4\x8a\x4f\ +\x79\xec\xba\xee\x42\xda\xef\xaf\xb4\x00\x24\x6b\x9e\x8f\xef\x00\ +\x1c\x8f\xe8\x3e\xde\xf7\xf9\x51\xda\x31\x2a\x2d\x80\xed\xf6\x3e\ +\x00\x10\x7a\x74\x69\x04\xf2\x56\xda\x31\x2a\x2b\x80\xe3\x38\xa7\ +\x41\xde\xcc\x7b\x9c\x4a\x0a\x40\xb2\xe6\x53\xbe\x06\x30\xb3\x57\ +\x9c\x80\xdf\xa7\x1d\xab\x92\x02\xc4\x59\x7f\x97\xe7\x00\xef\xa4\ +\x1d\xab\x72\x02\x24\xb5\x3e\x21\x37\x95\x52\x5b\x69\xc7\xab\x94\ +\x00\x49\xad\x0f\x60\x73\xae\x55\xff\x3c\x8b\x31\x2b\x25\x40\x52\ +\xeb\x0b\xfc\xab\x49\x7e\xf0\x4c\x42\x65\x04\x98\xd0\xfa\xbf\x66\ +\x35\x6e\x25\x04\x28\xc3\xfa\x9a\x4c\xde\x05\x1c\xc7\x79\xc9\x23\ +\x56\x02\x0b\x93\xfb\xa6\x81\xd5\x66\xb3\xf9\x34\xc9\xe7\xcb\xb0\ +\xbe\x26\xb5\x03\x5c\xd7\x5d\xf0\x29\x8f\x05\x72\x05\xbb\x6b\x75\ +\x00\x97\x3d\x1f\x8f\x5c\xd7\x3d\x11\xf7\xf9\xb2\xac\xaf\x49\x2d\ +\xc0\xee\x5b\x5a\xe4\x5a\xdd\xf3\xf1\x2d\xc9\xb1\x2e\x2b\xd3\xfa\ +\x9a\x2c\xe6\x80\xc5\x3d\xfa\xce\x59\x4e\xef\xfd\x71\x9d\x65\x5a\ +\x5f\x93\xfb\x24\x28\xe0\x4d\xc7\x71\x4e\x8f\xb6\x97\x6d\x7d\x4d\ +\x6a\x01\x08\xde\x8b\x09\x39\xe2\x53\xbe\x0a\x96\x42\x15\xac\xaf\ +\x49\x2d\x80\x01\x7e\x06\xe0\x79\x4c\xd8\x50\x29\x54\xc1\xfa\x9a\ +\xd4\x02\x28\xa5\xb6\x20\xf2\x71\x5c\x9c\x2e\x85\xaa\x58\x5f\x93\ +\xc9\x1c\xa0\x9a\xf5\x3b\x00\x9e\xc4\x84\x1d\xf1\x29\xdf\xf8\x90\ +\x35\x54\xc0\xfa\x9a\x4c\x04\x10\x91\xbe\x21\xbc\x8a\xf8\x52\x78\ +\x19\xc4\x99\x98\x98\x42\xac\xaf\xc9\xec\x29\xd0\x6a\xb5\x7e\x49\ +\x52\x0a\x71\x14\x65\x7d\x4d\xa6\x8f\xc1\x84\xa5\xb0\x17\x85\x59\ +\x5f\x93\xa9\x00\x13\x94\x42\x14\x85\x5a\x5f\x93\xf9\x42\x68\xbf\ +\xa5\x50\xb4\xf5\x35\xb9\xac\x04\xf7\x51\x0a\x85\x5b\x5f\x93\x8b\ +\x00\x13\x96\x42\x29\xd6\xd7\xe4\xf6\x2e\x90\xb4\x14\xca\xb2\xbe\ +\x26\xd7\x97\xa1\x04\xa5\x50\x9a\xf5\x35\xb9\x0a\x20\x22\x7d\xd3\ +\xc0\xdb\x10\x84\x37\x59\x08\x1c\xd3\xc0\x3b\x65\x59\x5f\x93\xfb\ +\xeb\x70\xb3\xd9\x7c\x5a\x33\xe4\x3c\x80\x75\x00\x7f\xef\xfe\xad\ +\xd7\x0c\x39\x9f\xf4\x27\xb3\x3c\x29\x64\x7f\x40\xa3\xd1\xe8\x02\ +\x78\xbd\x88\xb1\x26\xa5\x12\xbf\x0a\x97\x49\x94\x00\x3b\xc1\x0b\ +\x92\x66\x41\xb9\x64\x4e\x44\xee\x3b\xa3\x31\x51\x02\xf4\x82\x17\ +\x83\xed\xa7\x07\x93\x88\xdc\xbb\xa3\x31\xe1\x8d\x92\xe0\xe6\x70\ +\x8b\x79\x31\xd3\xac\x0a\x44\xc4\x7c\x2d\x78\x4d\x30\xf4\x48\x0e\ +\x6f\x94\xa4\xdc\x1d\x6e\xc0\x6a\xa7\xd3\x99\xcd\x3c\xbb\x9c\xe9\ +\x74\x3a\xb3\x04\x86\x16\x62\xa1\x7b\x43\x84\x00\x4a\x35\x1e\x00\ +\xdc\x0e\x34\x1d\x33\xcc\xda\xda\x41\x12\xe1\xbf\xcd\xd2\x43\x3b\ +\xc6\xb7\x06\xf7\x36\x4c\xd8\x01\x22\x7d\x01\xdf\x1b\x69\xbd\x60\ +\x98\x33\xdb\xb6\xed\x5e\xb3\x2c\x6b\xbe\x8a\x13\x23\x49\xd3\xb2\ +\xac\x79\xdb\x76\xaf\x0d\x36\x49\x0f\xed\x14\x87\xc0\xbf\x1e\xb5\ +\xe8\x1a\x7b\x92\xc2\x72\xba\xcb\xff\x87\x03\x13\x00\x40\xc8\xf2\ +\xbc\x6a\xdc\x8e\xea\x1b\xbb\x0e\x50\xcd\xfa\x6d\x42\x96\xf3\x4b\ +\xab\x10\x48\x60\x69\xae\x55\xff\x74\x5c\x40\xc2\x43\x53\xc6\x17\ +\x00\x4e\x65\x9a\x5a\xfe\x24\x3a\x34\xb5\x9f\x63\x73\x67\x31\xd8\ +\x75\x5d\xc5\x63\x73\x5d\x82\x4f\x26\x39\x36\x37\x65\xca\x94\xc3\ +\xcd\xbf\x5b\x3f\xf6\x3c\xa0\xff\x9c\x5c\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x04\xf5\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\xa7\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xcf\x6f\x15\x55\x14\xc7\xbf\x67\xa6\x85\xc2\xca\xe7\xa6\x21\ +\x10\x58\x58\x16\x36\x4d\x30\xf1\xa5\x2f\x95\x4d\x9b\xa8\x1b\x90\ +\x96\x02\xa2\x11\x08\x7f\x82\x1b\x89\x6d\x62\x5b\x9b\x28\x8a\x1b\ +\xfd\x0b\x34\xb1\xd1\x00\x6d\xf1\x91\xb2\xa9\x26\x6d\x20\x81\x3c\ +\x2d\x1b\xa3\x75\x83\x0b\x9a\xb2\xa8\x8b\xd6\x15\x2d\xd0\xb9\x5f\ +\x17\x7d\x53\x66\xe6\xcd\x74\xe6\x31\x77\x7e\xd4\xbe\x4f\xf2\x16\ +\x73\xee\x79\xef\x9e\x7b\xde\xf7\xdc\xb9\x33\xb9\x17\x68\xd0\xa0\ +\xc1\x4e\x46\xa2\x38\x75\xcf\xb0\x69\x6d\x05\x27\x14\xd4\x59\x81\ +\x14\x09\xec\x17\x60\x77\xd2\xc1\xd5\x03\x81\x27\x02\x3c\x22\x38\ +\x67\xc0\xb8\xda\x52\xc0\xcd\xd9\x1e\x59\x0f\xfb\x5e\x68\x02\x4a\ +\x93\x7c\x0b\xe0\x37\x00\x5e\xd5\x12\x69\x7a\xcc\x03\xf2\x61\xa5\ +\x5f\x7e\xde\xca\xc9\x08\x6c\x21\xa5\x73\x82\x83\x00\xa7\xb1\xfd\ +\x06\x0f\x00\xed\x00\xa7\x4b\x37\x38\x00\x32\xf0\x8f\x0e\x4c\x40\ +\xe7\x24\x06\x44\xf8\x59\x32\xb1\xa5\x08\xf9\x79\xe9\x27\x7c\x1c\ +\xd4\xec\x9b\x99\xaa\xec\xa7\x3d\xe6\x15\x8a\x0c\xc1\xc4\xad\x43\ +\x6b\x58\xb8\xfe\xae\x58\x5a\x03\x8d\xc9\x99\x6b\x34\x1f\xb6\xe0\ +\x20\x2c\x1c\x13\x72\x14\x40\xc1\xed\x21\x6f\xfb\x95\x43\x4d\x02\ +\xba\x67\xd8\xb4\xba\xc2\xdf\xe1\x94\xbd\xe0\x17\x18\x72\xae\xd2\ +\x2b\x4b\xda\x23\x4f\x80\x52\x99\xad\x50\x1c\x03\xf1\xa6\xc3\x3c\ +\xbf\xa7\x20\x47\xbc\x13\x63\x4d\x09\xac\xad\xe0\x04\xdc\x35\xbf\ +\x6c\x52\x3e\xd8\x2e\x83\x07\x80\x4a\xaf\x2c\xc1\x90\x73\x00\x56\ +\x1c\xe6\xf6\xea\xd8\x5c\xd4\x24\x40\x41\x9d\x75\x5e\x53\x64\xf8\ +\x6e\xbf\xfc\xa3\x3f\xcc\x64\xa9\xf4\xca\x92\x50\x86\x9d\x36\xef\ +\xd8\x00\x9f\x04\x08\xa4\xe8\x32\x98\xb8\xa5\x3d\xba\x94\x50\xcd\ +\x98\x72\x5b\xe4\x75\xaf\x4f\x4d\x02\x08\xec\x77\x5e\x1f\x5a\xc3\ +\x82\xee\xc0\xd2\xc2\x27\xf6\x03\x5e\x1f\x1f\x05\xb8\x57\x78\x79\ +\x9b\xed\xeb\xc1\x1b\xbb\xdf\xea\x35\x78\x21\xb4\x43\x68\xca\x3a\ +\x80\x28\x74\x95\xd9\xa6\x94\x1a\x02\xe5\xd4\x86\x85\xe3\xa6\x18\ +\xa3\x77\x4f\xca\xdf\x71\x7f\x3b\xf7\x0a\x28\x8d\xf3\xb0\xb2\x78\ +\x1b\x94\xf3\x00\xf6\x6e\x7c\xe4\x82\x45\xde\xe9\x2a\xb3\x2d\xee\ +\xef\xe7\x3a\x01\xdd\x33\x6c\x82\xc1\x1f\x01\xec\xf3\x69\xde\xa7\ +\x2c\xf5\x49\xdc\x3e\x72\x9d\x80\xc7\xcb\xb8\x04\xa0\xe6\xd6\xf5\ +\x1c\x39\x1d\xb7\x8f\xdc\xce\x01\xc5\x49\x76\x08\x38\x92\x74\x3f\ +\xb9\x54\x40\xf7\x0c\x9b\x4c\xf0\x3b\x00\xcd\x5b\xf9\x09\x78\x3d\ +\x6e\x5f\xb9\x4c\x40\xb8\xf4\x01\x00\x4f\x69\x18\x57\xe2\xf6\x95\ +\xbb\x12\x88\x2c\x7d\x91\x91\x4a\x9f\xcc\xc7\xed\x2f\x57\x0a\x88\ +\x2a\x7d\x08\xe6\xf6\xbc\x84\xaf\x74\xf4\x99\xab\x04\x44\x95\xbe\ +\xb2\xe4\x62\x94\x17\x9e\x51\xc8\x4d\x09\xd4\x23\xfd\xdf\x4e\xcb\ +\x9f\xba\xfa\xcd\x85\x02\xb2\x90\xbe\x8d\x16\x05\xbc\x71\x83\xaf\ +\x58\x54\x43\x9b\x0b\x13\xe1\x84\x61\x18\xa3\xf7\x7a\xe5\x41\x94\ +\xef\x3f\x5e\xc6\x25\x91\x74\xa5\x6f\x13\x5b\x01\x5d\x65\xb6\x59\ +\xe4\x1d\x40\x2e\xc0\x5e\xab\x53\xce\x2b\x8b\xb7\x4b\xe3\x3c\x1c\ +\xf6\xfd\xe2\x24\x3b\x44\xd2\x97\xbe\x4d\xec\x04\x28\xa5\x86\x10\ +\xb0\x56\x87\xc9\x1f\xba\x67\x18\xa8\xb2\x2c\xa5\x6f\x13\x7f\x0e\ +\xd8\x7c\x44\xf5\x6b\x43\x71\xf5\x5f\x7c\x14\xd4\x9c\xc5\xac\xef\ +\x25\xf9\x49\x90\x1c\x29\x4e\xb2\xc3\x6b\xce\x5a\xfa\x36\x1a\x12\ +\xc0\xf1\x10\x87\x5d\xa6\xf0\x5b\x67\x29\xe4\x41\xfa\x36\xf1\x13\ +\x60\x18\x5f\x02\x78\xba\xa5\x8f\xa7\x14\xf2\x20\x7d\x9b\xd8\x09\ +\xa8\xf4\xc9\x3c\x29\x9f\x86\x3a\x56\x4b\x21\x2f\xd2\xb7\xd1\x32\ +\x07\xec\x7d\x19\x57\x00\xdc\x0f\x71\xdb\x65\x82\xdf\x9b\xe0\x18\ +\x72\x20\x7d\x1b\x2d\x09\x98\xed\x91\x75\x0b\x72\x11\x61\xa5\x00\ +\xbc\x06\xe0\x48\x88\x4f\x2a\xd2\xb7\xd1\x76\x17\x98\xeb\x97\x3f\ +\x22\x95\x42\x18\x29\x49\xdf\x46\xeb\x6d\x30\x62\x29\x04\x93\xa2\ +\xf4\x6d\xb4\x26\xa0\x8e\x52\xf0\x23\x55\xe9\xdb\x68\x5f\x08\xbd\ +\x70\x29\xa4\x2c\x7d\x9b\x44\x56\x82\x75\x97\x42\x06\xd2\xb7\x49\ +\x24\x01\x75\x96\x42\x26\xd2\xb7\x49\xec\x59\x20\x72\x29\x64\x24\ +\x7d\x9b\x44\x1f\x86\x42\x4b\x21\x43\xe9\xdb\x24\x9a\x80\xd9\x1e\ +\x59\x37\x4c\x79\x4f\xa4\x76\x93\x85\x08\x16\x0c\x43\xde\xcf\x4a\ +\xfa\x36\x89\x3f\x0e\xdf\xeb\x95\x07\x54\x72\x54\x80\x29\x00\xab\ +\x00\x56\x05\x98\xa2\x92\xa3\x51\x5f\x99\x25\x49\x2a\x6f\x85\x2b\ +\xa7\x64\x11\xc0\x3b\x69\xf4\x55\x2f\xb9\x78\x2b\x9c\x25\x7e\x9b\ +\xa4\x9e\x38\xaf\xcf\x5c\xa3\x99\x5e\x38\x7a\xf1\xc6\xee\x1d\x1b\ +\xe0\xbf\x49\xea\x91\xf3\xfa\x61\x0b\x0e\xea\x0f\x2d\x1d\x7c\x62\ +\x5f\xf4\xfa\xf8\x28\x80\x73\x2e\x83\x85\x63\x7a\xc3\x4a\x0f\xe3\ +\x19\x8e\xbb\x2d\xac\xb9\x25\xd7\x24\xc0\x80\x71\xd5\x79\x2d\xe4\ +\x68\xa9\xcc\x56\xdd\xc1\x25\x4d\xa9\xcc\x56\x0a\x5d\x0b\x31\xef\ +\xd8\x36\x6c\x1e\x5a\x0a\xb8\x09\xe0\x2f\x87\xa9\x00\xc5\xb1\xed\ +\x94\x84\xcd\xcd\xd2\xee\x1d\xe3\xf3\xd5\xb1\xb9\xa8\x6b\xbb\xbc\ +\x50\x86\x55\x33\xa6\xf2\xbc\x5d\xde\x78\x86\xe3\xd5\x7f\xfe\xc5\ +\xb6\xcb\xdb\x74\x4e\x70\xf0\x7f\x71\x60\x02\x00\x44\x06\x2b\x27\ +\xe5\xb2\x5f\x53\xe0\x3a\xe0\xd7\x7e\x5c\x86\xc8\x60\x72\x51\xa5\ +\x02\x01\x19\xa8\xf4\xe1\x8b\x20\x87\xa8\x87\xa6\xbe\x06\xd0\xae\ +\x35\xb4\xe4\x89\x74\x68\xaa\xee\x63\x73\xd5\x2d\xe7\x07\xf2\x78\ +\x6c\x0e\xc0\x22\xc0\xfb\xf5\x1c\x9b\x6b\xd0\xa0\xc1\xce\xe6\x3f\ +\xb7\x37\xe9\x8b\xf9\x5d\x56\x0e\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xd7\x41\x0d\x00\x20\x0c\x04\xc1\x83\x20\xa9\x02\x70\x53\x3f\xd5\ +\x43\x52\x6b\x88\x38\x7e\xec\xfe\x7b\x99\x6f\x25\x32\x8a\xac\x8e\ +\xac\x76\x36\x96\x69\xd8\xe6\xbd\xa6\x3b\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x6e\xde\x67\x34\x74\x1e\x39\x3e\ +\xee\x02\x8e\xc2\x05\x10\x61\x1a\xbe\x91\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x03\xde\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x90\x49\x44\x41\x54\x78\x9c\xed\ +\x98\xcf\x6f\x54\x55\x1c\xc5\xcf\xb9\xf3\xd2\xd4\x04\x31\x4a\xdd\ +\x89\x2e\x81\x75\xdb\x99\x31\xc6\x64\xaa\x81\x98\x2e\xb4\xd3\x1a\ +\x16\xec\x90\x10\xfd\x03\x54\xe2\x82\x18\x62\x42\xfc\xb1\x36\x21\ +\x50\x60\x45\x4c\xa0\xf3\xa6\xb8\x60\x92\x26\x32\x24\xd8\xc8\x88\ +\xac\xd5\x35\xee\x24\x1a\xe3\xa2\x55\xda\x7b\x5c\xcc\x80\xd3\x77\ +\x6f\x3b\xbf\xde\x9b\xa9\x78\x3f\xcb\xfb\xee\xfd\x7e\xcf\xf7\xbc\ +\xef\xdc\x77\xef\x00\x81\x40\x20\x10\x08\x04\x02\x81\x40\x20\x10\ +\x08\x04\x02\x81\xff\x17\x1c\x55\xe2\x7c\x45\x65\x52\x5f\x02\x30\ +\x90\x2e\x34\x16\x72\xa7\x47\xa1\x63\x24\x06\x14\x63\x9d\x14\x74\ +\x0e\x80\x79\x2c\x44\x3c\x79\x67\x81\x8b\xc3\xd6\x62\x3a\x4f\x49\ +\x97\x62\xac\x53\x82\xce\x27\x73\x8b\xba\x90\xaf\xea\xc3\x61\xeb\ +\x19\x5e\x07\x48\x2c\x54\xed\xe7\x00\xdf\xef\x30\xf1\x8b\x46\xd9\ +\x9c\x02\xa9\x61\xc8\x1a\x8a\x01\xa5\xba\xa2\xb5\xdf\xed\x79\x80\ +\xc7\xbb\x5b\xa1\x4b\x4f\x3d\x6b\xde\xbd\x35\xc3\x8d\x6c\x95\x0d\ +\xc1\x80\xd2\x65\x8d\xaf\xed\xd5\x57\x20\xe6\x92\xcf\x24\x58\x36\ +\x15\x38\x3f\x45\x02\xd5\xf1\x3f\x78\xec\xd6\x71\xae\x67\xa9\x2f\ +\x53\x03\x0a\x37\xb4\x17\xeb\x5a\x06\x30\xe3\x49\xbd\x09\x3c\xea\ +\x72\x02\x50\xce\x13\xe2\x66\x94\xe3\xdc\xea\x5b\xfc\x33\x2b\x8d\ +\x99\x19\xf0\xea\x55\x3d\xff\x77\xa4\x1a\x80\xc9\xad\x4f\x84\x66\ +\xf1\x3e\x94\x73\x24\x11\x3f\x8c\x3d\xe4\xec\xed\xa3\xfc\x35\x0b\ +\x9d\x99\x18\x30\x79\x55\x2f\x46\x91\x56\x00\x1c\x48\x64\x13\x05\ +\xbb\xe3\xee\x46\x18\xc8\xd1\xf5\xb3\x35\x3c\x7c\x77\x8e\xf7\x53\ +\x96\x9a\xbe\x01\xc5\x58\x87\x04\xad\x00\x78\x21\xf1\x48\x20\x2c\ +\x3a\xed\xed\x04\x24\x18\xba\xda\xee\x1b\xcb\x23\xdf\xbd\xcd\x9f\ +\xd2\x53\x9b\xf2\x39\x60\xba\xa2\x69\x41\xb7\xe1\x2b\x1e\x5d\x14\ +\xdf\x9a\x49\xc0\x82\xce\xec\xfd\xd6\xe8\xdb\xfc\x92\xa6\x52\x11\ +\xdb\x22\x35\x03\xa6\xab\x7a\xdd\x50\x37\x01\xec\x6b\x1f\x17\xd4\ +\x2c\xbe\x57\x04\x0b\x38\x26\xec\xa3\x51\x3d\x1f\xeb\xb5\xbe\x85\ +\x26\x48\xc5\x80\x62\xac\x79\x23\xdd\x00\xb0\xa7\x7d\x5c\x90\x08\ +\xf6\x5e\xfc\xbf\x58\x34\x0d\x6c\x67\x0f\xa1\x5a\xbe\xa2\xf2\x00\ +\x71\x1f\x33\xb0\x01\xf9\xaa\x4e\x08\xba\x06\x60\xac\x7d\x5c\xa0\ +\x1d\xb0\xf8\x16\xb4\x72\xe3\x8c\x91\x5a\x2a\xc4\x7a\x67\xd0\xe8\ +\x03\x19\x90\x8f\xf5\x01\xa5\xc5\x64\x9c\x66\xf1\xce\x9b\xeb\x1b\ +\x42\xf2\x98\x60\x00\x5d\x2c\xc4\xea\x70\xb4\xee\x14\xbb\x1f\x24\ +\x16\x63\xfb\xa9\x48\xe7\xf2\x22\xc0\xd2\xfd\xed\xa6\x05\xe1\x79\ +\x69\x82\x3e\xfb\xbe\x6c\x3e\xea\xe7\xfe\xd0\xb3\x01\xa5\xba\xa2\ +\xf5\xdf\xec\x39\x91\x27\x5c\x21\x99\x16\xdf\xcc\x21\x90\xf4\x9a\ +\xb0\xf8\xd2\x86\x79\xef\xda\xd1\xed\x0e\x59\x7e\x7a\x32\xa0\x74\ +\x59\xe3\x6b\xcf\xe8\x0a\x80\xf9\x44\xf6\x66\xf1\xee\xa7\x2b\x13\ +\x24\x90\x80\xf1\xa8\x8f\x9f\x1b\xe7\xb1\xda\x2c\xff\xea\x36\x56\ +\xd7\x06\xbc\x72\x5d\x4f\x6f\x6c\x6a\x19\x80\xf3\x09\x6a\x5d\x6a\ +\x86\x52\x7c\x5b\x4e\x6f\x27\x10\xf8\x26\x97\x63\xb9\xdb\xfb\x43\ +\x57\x06\x4c\x7e\xad\x89\x68\x53\x35\x08\x5b\x0f\x21\x12\xc0\xde\ +\x5a\x2e\x55\x48\xc0\xda\x1c\xb8\xb5\x0c\x02\x77\x1f\x46\x9c\xbd\ +\xf7\x26\x1f\x74\x0c\xd1\x69\xc2\xf4\xb2\xf6\x1b\xab\x15\x00\x07\ +\x13\x8f\xfa\x3b\xe0\x64\x81\xff\xfe\xf0\x23\xc4\x23\x8d\x05\xfe\ +\xb2\xd3\xd2\x1d\x3f\x83\x2f\x2f\xe9\xa0\xb1\x5a\xc5\x6e\x2e\x1e\ +\xd8\xee\xd4\x78\x88\x46\xab\x53\xd7\x75\xc0\xb7\xe4\x11\xdb\x76\ +\x40\x7e\x49\x53\x34\xaa\x01\x98\x70\xd2\xed\xa6\xe2\xdb\xf1\x77\ +\xc2\x03\x90\x6f\x34\xca\xbc\xe7\x5b\xe2\xed\x80\x42\x45\x33\x34\ +\xaa\x23\x51\xbc\x76\x73\xf1\x00\xd0\xbc\x6a\x27\x3b\x61\x02\x52\ +\xbd\x58\x55\xc9\xb7\xc4\xe9\x80\x42\x45\xa7\x61\x74\xc6\xe3\xe4\ +\x70\xb7\xf9\x01\x71\xc4\x13\x82\xe5\xc7\x8d\x05\x7e\xb2\xe3\xbc\ +\x62\x6c\x37\x04\xf8\xfe\x9e\xfa\xcf\x43\x60\xf3\xce\xbc\x89\xda\ +\xc7\x3c\x27\xaa\x27\x17\x5f\x6d\xee\x1e\x40\x9e\x6d\xed\xaa\x4f\ +\x16\x82\x05\x79\x76\xd4\x32\x02\x81\x40\x20\x10\x08\x04\x02\x81\ +\x40\x20\x10\x08\x04\x02\xa3\xe6\x1f\x3c\x8f\x50\x7d\x3b\xd7\xa3\ +\xf5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\xfc\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x02\xae\x49\x44\x41\x54\x78\x9c\xed\ +\x9a\x3f\x6e\x13\x41\x14\x87\xbf\xd9\x10\x85\x26\x48\x14\xb9\x01\ +\x15\x25\x29\x69\x90\x88\x2d\xa5\x43\xd8\xa0\x84\x24\x10\xc9\xb1\ +\xa1\x80\x1b\xd0\x72\x03\x90\x00\xc7\x05\x7f\x82\x03\xb1\x8d\x68\ +\xb3\x3e\x44\x24\x2e\xc0\x05\x22\x21\x0a\x8a\x08\xfc\x68\x90\x70\ +\xc6\xde\x18\xef\xce\xcc\xce\x6c\xfc\xca\xf5\xdb\x9f\xe6\xfb\xb4\ +\x9e\x1d\x3d\x2d\xcc\x6a\x56\xb3\x3a\xcf\xa5\xf2\x5e\x80\xed\x2a\ +\x57\x6a\xb7\x84\xe8\x19\xc8\x77\x89\xa2\x47\xfd\x83\xd7\x5f\x87\ +\x7f\xbf\x90\xd7\xc2\x5c\x54\xb9\x5a\x5f\x13\x91\x3d\x90\x08\x40\ +\x0d\x06\x2f\x81\xeb\xc3\x3d\x51\x2e\x2b\x73\x50\xff\xe0\x4f\x31\ +\x5e\xd2\xfb\x0a\x29\x20\x01\xfe\xb7\x28\x9e\xea\xbd\x85\xfb\x0b\ +\x24\xc1\xa3\x64\xbd\xdf\x69\x7d\xd1\xfb\x0b\xb5\x09\x9e\x05\x1f\ +\x77\x5a\x07\xe3\xee\x29\x8c\x80\x34\xf0\x50\x10\x01\x69\xe1\xa1\ +\x00\x02\xb2\xc0\x43\xe0\x02\xb2\xc2\x43\xc0\x02\x4c\xc0\x43\xa0\ +\x02\x4c\xc1\x43\x80\x02\x4c\xc2\x43\x60\x02\x4c\xc3\x43\x40\x02\ +\x6c\xc0\x43\x20\x02\x6c\xc1\x43\x00\x02\x6c\xc2\x83\xe7\x02\x6c\ +\xc3\x83\xc7\x02\x5c\xc0\x83\xa7\x02\x5c\xc1\x83\x87\x02\x4c\xc3\ +\x97\xaa\xb5\x3b\x88\x7a\x01\x80\xa8\x87\x71\xaf\xf9\x79\xf8\x77\ +\xaf\x26\x42\xa6\xe1\xcb\xd5\xfa\x1a\xa2\xf6\x81\x25\x60\x09\x25\ +\xaf\xf4\x1e\x6f\x04\xd8\x80\x1f\x93\x37\x52\x5e\x08\x70\x04\x3f\ +\x10\xd4\x63\xbd\x37\x77\x01\xae\xe0\x95\x52\xf7\xfb\xdd\xe6\x27\ +\xbd\x3f\xd7\x4d\xd0\x25\xfc\x61\xa7\xb9\x37\xee\x9e\xdc\x04\xf8\ +\x00\x0f\x39\x09\xf0\x05\x1e\x72\x10\xe0\x13\x3c\x38\x16\xe0\x1b\ +\x3c\x38\x14\xe0\x23\x3c\x38\x12\xe0\xec\x3d\x2f\xb2\xd5\xef\xb5\ +\x3e\x4c\x93\x65\x5d\x80\xcf\xf0\x60\x59\x80\xef\xf0\x60\x51\x40\ +\x08\xf0\x60\x49\x40\x28\xf0\x60\x41\x40\x48\xf0\x60\x58\x40\x68\ +\xf0\x60\x50\x40\x88\xf0\x60\x48\x40\xa8\xf0\x60\xe0\x1b\x21\x57\ +\xf0\xc0\x66\xbf\xd7\x6a\x4f\x9b\xb7\x52\xa9\xdf\x55\xc8\x73\xc0\ +\xfc\x4c\xd0\x25\x7c\xdc\xdd\x9d\x1a\xbe\x54\xd9\xd9\x54\x48\x1b\ +\x1b\x33\xc1\x10\xe0\x81\x37\x4c\x60\x4c\x25\xc0\x77\xf8\x72\xb5\ +\xbe\xc1\x28\xbc\x99\x99\x60\x08\xf0\x22\xf2\x56\xcf\x33\x32\x13\ +\x0c\x19\x3e\xf3\x4c\xd0\x77\xf8\x95\xdb\xb5\x7b\x4a\xa9\x77\x7a\ +\xde\xa4\x57\xe7\x7f\x09\x28\x2a\x3c\xc0\x5c\xca\xc5\xda\x98\xe4\ +\x6c\xc4\xdd\xdd\xfd\x69\xf3\xb2\xc0\xc3\x84\x27\xc0\x25\xfc\x61\ +\xa7\xe9\x1c\x1e\xce\x38\x09\xfa\x0e\x5f\xaa\xec\xac\x03\x23\xf0\ +\x4c\x79\x62\x1c\xfb\x04\x04\x02\xff\x5e\xcf\x23\xc5\x1e\x32\x22\ +\xe0\xef\xd9\xb9\x8d\x21\xf8\x84\xbc\xf4\x8f\x7d\x42\x1e\x29\x37\ +\xd0\x53\x02\x96\x1b\x8d\xf9\xcb\xc7\x83\x63\x05\x8b\x43\x97\x53\ +\xc3\x27\xe4\xa5\x86\x37\x9d\x07\xda\x49\x70\xf1\xe4\x64\x4e\xc1\ +\xc2\xd0\xa5\x4c\x9f\xa5\x8c\xc9\xcb\xb4\x58\xd3\x79\xa0\xbd\x06\ +\xbf\x1d\x1d\xfd\xba\x72\xf5\xda\x0f\xe0\xa6\xc0\xcf\x48\xd8\x8a\ +\xbb\xad\x4e\xda\x70\x3d\x0f\xd4\x83\xb8\xdb\xfc\xe8\x4b\x5e\x62\ +\xad\xae\x3e\x59\x58\x6e\x34\xe6\x7d\xcd\xbb\xb1\xbd\x7d\xd1\x64\ +\xde\xac\x66\x75\x8e\xeb\x0f\x00\x7d\xea\x19\xbf\xa0\x8f\x59\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x14\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xc6\x49\x44\x41\x54\x58\x85\xed\ +\x94\xb1\x6a\x14\x51\x14\x86\xbf\xff\xee\xa0\x41\xd0\x68\x13\x8b\ +\xb4\xda\xd8\xac\x20\xee\x6e\xd4\xd4\x22\x06\x45\xb1\x11\x05\x4b\ +\x0b\x51\x1f\x41\xf3\x08\x06\x1f\x40\x50\x10\x42\x76\xb3\x91\x88\ +\x98\x2e\xe0\x82\x08\x01\xf5\x05\xb4\x12\xc4\xc6\x4a\x58\xb3\x73\ +\x7f\x8b\x99\x84\x24\xbb\xd1\xec\xb0\x6a\x33\x5f\x75\x87\x7b\xee\ +\xf9\xff\x73\xce\xbd\x03\x25\x25\x25\x25\xff\x19\x15\x3d\x38\x35\ +\xef\xc9\x98\xf8\x25\x50\x4d\x2a\x9a\xec\x5c\xd6\x97\x22\x79\x42\ +\x91\x43\xf5\x05\x1f\x8f\x89\xdf\x00\x55\x80\x5e\xea\xce\xd4\x92\ +\x8f\x15\xc9\x35\x74\x07\x4e\x2f\xfa\x64\xb0\x5f\x03\x13\xd8\x79\ +\x16\x01\x7c\x35\x3a\xff\xee\xaa\x3e\x0c\x93\x6f\xa8\x0e\xd4\xda\ +\x9e\x0e\xf6\x2a\x30\x81\x30\x41\x29\x41\x29\x60\xe0\xa8\xf0\x6a\ +\xad\xed\xe9\xbf\x62\xa0\xd6\xf2\x8c\xa2\x57\x80\x43\x16\xc6\x44\ +\x9c\x4b\x43\x74\xb6\x1a\x57\xf4\x4a\xad\xe9\x8b\x23\x35\x50\x5f\ +\xf4\x4d\xe1\x36\x30\x06\xb6\x4c\xdc\x19\x23\x88\x64\x33\x19\x93\ +\xbc\xd4\x68\xf9\xc6\x48\x0c\x34\x5a\xbe\x87\xfd\x14\xa8\x18\x1b\ +\xd4\x27\xbe\xc5\x46\xcc\x62\xa8\x18\x3f\x6b\x34\x7d\xb7\xb8\x01\ +\x5b\xf5\x56\x3a\x6b\xfc\x28\xff\x8c\xfa\xad\x78\x6e\x01\x45\xe7\ +\x71\x96\xe7\x1a\xcd\xf4\x21\xf6\xae\x97\x7d\xf0\xc6\x03\x87\x7a\ +\x35\xce\x81\xee\x00\x18\xa2\x36\xa6\xbd\x47\x9c\xbd\x8d\x00\x20\ +\xfb\xf1\xdb\x8f\xe1\x3e\xb3\xfd\x05\xf4\x19\x38\x31\xef\x7d\x07\ +\x93\xf8\x04\x74\xdd\x59\xa6\x28\x0d\x27\xbe\x69\xc2\x08\x11\x32\ +\x11\x3f\xef\x7d\x0b\xb7\xd6\x6e\x6b\x7d\x57\x03\xa7\x5e\xf8\x40\ +\xd2\xf3\x02\x70\x21\x1b\xb7\x22\x43\x56\x3e\x00\x81\x43\x2e\xf5\ +\xaa\x97\xe8\xda\xda\x25\xfd\xe8\x33\x70\x6e\xd9\x47\x7e\x76\xbd\ +\x2c\x71\xc6\x80\x4c\xa4\x60\xe5\x3b\xd9\xde\x09\x3a\x5d\x69\xe6\ +\xfd\x15\x7d\x07\x48\x36\x82\xd6\xbb\xfe\x24\x31\xbe\xe9\x4a\xc5\ +\x7e\xd3\x83\xd0\xf6\x41\x9f\xdd\x6f\x7f\x06\x0e\xc3\x96\x57\xe0\ +\xd1\x14\xbb\x27\xec\x7f\xa7\x55\x52\x52\x52\xf2\x47\x7e\x01\x51\ +\xe3\xba\x72\x94\x2f\x72\xc5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x00\xd1\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x83\x49\x44\x41\x54\x78\x9c\xed\ +\xd7\xb1\x0d\xc2\x40\x10\x04\xc0\x7d\x8a\x40\x34\x42\x23\xb4\x40\ +\x80\x1c\xd1\x0b\x89\x45\x23\x54\xe1\x42\x2c\x9a\x78\x52\x64\x7d\ +\x6a\x8c\xfc\x33\xe1\xea\x82\xbd\xcb\x2e\x01\x00\x00\x00\x00\xa0\ +\x1f\x65\x19\x9c\x6f\x8f\x4b\x92\xb1\x26\xc7\x0d\xfa\xac\x69\x4e\ +\xea\x75\x7a\xde\x5f\xdf\xe1\xa1\x31\xb8\xc7\xe5\x93\xe4\x94\x94\ +\x71\x19\xb6\x0e\xd0\x95\xd6\x01\x86\x92\xbc\x7f\xde\x64\x7d\x73\ +\x52\x87\xad\x4b\x00\x00\xff\xc3\x2f\xd0\x18\xdc\xe3\xf2\x89\x5f\ +\xa0\xcd\x2f\x00\x00\x00\x00\x00\x00\x40\x27\x3e\xec\xfd\x1c\x0f\ +\x3a\x57\x98\xc9\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x01\x34\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\xe6\x49\x44\x41\x54\x78\x9c\xed\ +\xd2\xb1\x09\xc2\x40\x00\x46\xe1\x5f\x87\xc8\x26\x2e\xe2\x0a\x29\ +\xc4\xc6\x61\x6c\x82\x4b\xb8\x88\x5b\xa4\x72\x8b\xb3\x30\x60\x21\ +\x36\xde\x5d\x9e\xe0\xfb\x20\x90\xc0\xa1\x7f\x1e\x49\x24\xfd\xb3\ +\x4d\xef\x3f\xd8\x1d\xce\xfb\x24\xd3\xf2\x78\xbc\x5d\x4e\xd7\x96\ +\xe7\x6b\x6d\x7b\xfe\xf8\x62\x2a\xc9\x50\x92\x21\xaf\x17\x6b\x79\ +\xbe\x4a\xf7\x00\xcb\x8b\xbc\xdd\xb7\x3a\x5f\x6b\x8d\x2f\xe0\xa7\ +\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\x00\ +\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\x0f\ +\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\xf4\ +\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\x40\ +\x0f\xa0\x19\x80\x1e\x40\x33\x00\x3d\x80\x66\x00\x7a\x00\xcd\x00\ +\xf4\x00\x9a\x01\xe8\x01\x34\x03\xd0\x03\x68\x06\xa0\x07\xd0\x0c\ +\x40\x0f\xa0\x19\x80\x1e\x40\x5b\x23\xc0\xfd\xc3\x7d\xab\xf3\x55\ +\x56\x08\x50\xc6\x24\xf3\xf3\x2a\x63\xfb\xf3\x92\xf4\xbd\x07\x47\ +\xdd\x22\x24\x17\x57\x09\xda\x00\x00\x00\x00\x49\x45\x4e\x44\xae\ +\x42\x60\x82\ +\x00\x00\x04\x2e\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\xe0\x49\x44\x41\x54\x78\x9c\xed\ +\x98\x4d\x68\x5c\x55\x14\xc7\x7f\xe7\xbd\x32\xa9\x9a\xb8\xb1\x94\ +\xb4\x52\xc4\x8d\xd6\x8d\x60\x32\x16\xba\x28\x34\x7e\x84\x88\x52\ +\x94\x4a\x51\x57\xcd\xa2\xe9\xa4\x69\x26\x11\xea\x27\x04\x09\x56\ +\xb0\x5d\xa8\xcd\xd4\x7c\x8c\x94\x44\x84\x82\x9b\x62\x5d\x18\x69\ +\xa9\x4c\x16\xae\xe6\x4d\x0a\x6e\xfc\xc0\x45\x69\x35\x0b\x9b\x48\ +\x21\x81\xa6\x53\xe7\x1d\x17\xc9\x68\xe6\xbd\x97\x4e\x66\xe6\xbd\ +\x49\x4a\xef\x6f\x79\xcf\xbb\xe7\xfe\xcf\xb9\xef\xde\x7b\xee\x05\ +\x83\xc1\x60\x30\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\xc3\xbd\ +\x85\x78\x1b\xe2\x5d\xa9\x0f\x04\x1d\x50\xc1\x56\x70\x05\x74\x3d\ +\x84\x85\x85\x82\x08\x58\xa2\x14\x14\xf9\xd0\x49\xf7\x0e\xae\xb4\ +\x6f\xf2\xf5\x10\x1d\x50\xb0\x01\x04\xac\x3a\xe9\x8c\x8c\xe2\x0c\ +\xab\x60\x83\x0e\x00\x25\x09\xb8\xeb\x03\xac\x15\x7f\x02\x54\x8f\ +\x2b\x72\x57\xff\xf6\x41\x28\xa2\xa8\x1e\xf7\xb6\xfb\xf6\x00\x80\ +\xd6\xae\x53\x6d\x22\x72\x1e\x68\xf2\x7c\xae\xa0\x6e\x24\x0a\xc3\ +\xc3\xc2\x1f\xd7\x3c\x22\xfb\x9c\xd1\xde\x8c\xf7\xe3\xc0\x04\x00\ +\xb4\x74\x9f\x6a\xb5\x5c\xf9\x1e\xd8\x52\x62\x50\x14\x61\x43\x26\ +\x41\xc1\x12\x7f\x4c\xb3\xae\xa5\x1d\xd3\x23\x7d\xb9\xa0\x3e\xab\ +\x26\x00\x20\xde\xfd\xd9\xe3\xb8\xd6\x45\x60\x87\xa7\x9b\x02\xee\ +\xc6\x39\x20\x64\x39\x78\xf5\xc6\x73\x15\xcb\x6d\x77\x46\xfa\x7f\ +\x5d\xbd\x67\x19\x9e\x3e\xf2\xf9\x0e\x2d\x14\x2e\x00\x3b\x3d\x5d\ +\x37\x48\x12\x04\xc0\xc2\x1f\xfc\x2f\x62\xdb\xed\xd9\xe1\x9e\x6b\ +\x77\xea\x5d\xf6\x14\xc8\x0e\xf7\x5c\x53\xcd\xef\x01\x9c\x52\x8b\ +\x8a\xa2\x76\xf9\x14\x46\x87\x00\x8a\xda\xbe\xe0\x85\xac\x6a\x7e\ +\x4f\xb9\xe0\x61\x8d\xc7\x60\x2e\x7d\x6c\xb6\xe1\xf6\xcd\x67\x04\ +\x7e\xf0\x09\x50\xec\xf5\xc8\x81\x82\xb8\x04\x8e\x7d\xa9\x21\x7f\ +\xf3\xd9\x5c\xfa\xd8\xec\x5a\xfc\x54\xa4\x7d\xef\xc1\xf1\xcd\xf3\ +\x0d\x0b\x67\x05\x7d\xc5\x2f\x48\x5d\xa9\xd3\xf1\xa9\xa8\x08\x12\ +\x34\x79\xe7\x6e\xc4\x78\xe3\xf7\x54\xf2\xd6\x5a\x7d\x55\x54\x08\ +\x65\x26\x3a\x17\x9b\x9a\x67\x0f\x80\x9e\xf1\xda\x04\xb1\xb4\xc2\ +\x84\x56\xc3\x52\x69\x1b\x14\xbc\x9e\x79\xf4\xef\xe6\x03\x95\x04\ +\x0f\x55\x0b\x56\x89\x1f\x4e\x9d\x00\xde\x0a\x10\x18\xd9\xfd\xa1\ +\x58\xd7\xfb\x0d\x7a\xd2\x49\x27\xdf\xa5\x8a\x3f\xb0\xa6\x19\x8b\ +\x27\x52\x6f\xa3\x7a\x22\xc0\xab\x8b\x86\x9d\x04\x15\x82\x66\x5e\ +\xe4\x1d\x67\xb4\xf7\x64\xb5\x5e\xed\x5a\x24\xcd\x38\x93\x3f\x6e\ +\x6b\xed\xf8\x53\x44\x5e\xa2\x34\x99\xa2\x84\xb8\x1e\x84\xa0\xe0\ +\x5d\x90\x43\xce\x58\xef\xe9\xda\x5c\x87\x40\x3c\x91\xda\x8f\xea\ +\x59\x20\xe6\x31\x2d\xd7\x0a\x35\x11\x54\xda\xe6\x05\x5e\xcf\x8e\ +\x25\xcf\xd5\xe8\x3b\xbc\x49\x8a\x1f\x1a\x7a\x0e\x8b\x6f\x80\x07\ +\x56\xb6\xeb\xd2\x96\x5d\x65\x12\x24\xa8\xc0\x59\x10\xf4\xe5\xec\ +\x58\xdf\xa5\xea\x7c\x7a\x46\x08\xc3\x49\x91\x78\x62\x68\x17\xca\ +\x77\xc0\x43\x9e\x61\xaa\xb8\x44\x05\x06\x3f\x27\xae\xfb\x42\xf6\ +\x8b\xfe\x6c\x2d\x3a\x4b\x46\x09\xcb\x51\x91\x96\x23\x9f\x3e\x21\ +\x85\x4d\x17\x05\x7d\xd8\x63\xaa\x60\x39\x04\x06\xff\x87\x6b\x17\ +\xda\xa7\x87\xdf\xfc\x39\x04\x99\xff\x8f\x14\xa6\xb3\x22\x4f\xf5\ +\x9c\x7e\xc4\xfe\xc7\xbd\x00\x3c\x56\x62\x50\x51\xe4\x4e\x7f\x82\ +\x00\x1a\xb4\xe6\x7f\x53\x75\x9f\xcf\xa5\xfb\xaf\x86\x2c\x35\xba\ +\xc2\xe5\xc9\xc4\xc8\xd6\x98\xde\x9e\x04\x5a\x4a\x2d\x0a\x48\x21\ +\x50\x89\xaa\x1d\x20\x69\xba\x90\xa7\xe3\xf2\x78\xf2\x7a\x14\x3a\ +\x23\x7b\x12\xfb\x69\xb4\xfb\x2f\x3b\x46\x1b\xc2\x54\xa9\x45\x00\ +\x4a\x2e\x51\xc5\x3b\x45\x40\xf0\x19\x3b\x46\x5b\x54\xc1\xff\xa7\ +\x26\x4a\xf6\x1e\x1c\xdf\xbc\x10\x9b\xff\x1a\x61\x9f\xd7\xa6\xcb\ +\x7b\xc2\x2a\x8f\xaf\xe7\x1b\x6f\x35\xbd\x96\x99\xe8\x5c\x8c\x52\ +\x5f\xe4\x8f\xa2\x99\x89\xce\xc5\xc6\x6d\x73\xfb\x45\xe4\x4b\xaf\ +\x4d\x96\x5e\x70\x7c\x1a\x14\x26\x1a\x9b\xe7\x5e\x8d\x3a\x78\xa8\ +\xb1\x12\x5c\x2b\x57\xa6\xa6\xdc\x99\x17\x77\x7d\xbb\x7d\xfe\xbe\ +\x07\x11\xd9\x5d\xe6\xf3\x4f\x72\xcd\x73\x47\xaf\x0c\x0e\xfa\xf7\ +\x89\x08\xa8\xf3\x55\x5e\x25\xde\x95\x7a\x0f\xe1\xa3\x60\x31\xfa\ +\x7e\x76\x2c\xf9\x71\x35\x97\x9a\x6a\x59\x97\xf7\x9c\x78\x62\xe8\ +\x30\xca\xe8\x8a\x26\x45\x35\xe1\xa4\xfb\xd2\xf5\xd6\x52\x97\x25\ +\xe0\x65\xc6\x99\xcc\x6d\x6f\xed\xb8\x1f\x91\x9d\x02\x0b\x40\xa7\ +\x93\xee\xfb\x6a\x3d\xb4\x18\x0c\x06\x83\xc1\x60\x30\x18\x0c\x06\ +\x83\xc1\x60\x30\x18\xee\x35\xfe\x05\x2f\xee\x41\x9b\x3f\x6f\x48\ +\xfe\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x22\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xd4\x49\x44\x41\x54\x58\x85\xed\ +\x94\xb1\x6b\x13\x51\x1c\xc7\x3f\xdf\x17\x84\xa0\x20\x71\xd0\xc1\ +\x49\x89\x08\x4a\x06\x25\xb8\x3a\x79\xb5\x48\xe9\x50\x0d\x8e\x82\ +\x6d\x66\xff\x02\x41\xdd\xfc\x0b\x1c\x92\xb8\x56\xbc\x06\xa1\x75\ +\xf0\x7a\x43\x07\x07\x75\x11\xed\x10\x17\x2d\x2e\x0a\x2e\xb5\x64\ +\xb1\xa1\xe6\x7e\x0e\x97\x33\xa7\x6d\x63\x92\x16\xbb\xdc\x17\x0e\ +\xde\xdd\xfb\xbe\xef\xf7\xfb\x7e\xef\xf7\x0e\x32\x64\xc8\x90\xe1\ +\x80\xa1\x64\xe0\x5d\x9f\xfb\x0e\x14\xfe\x93\xef\x46\xd8\xac\x1f\ +\x03\x70\xfd\x28\x72\xbb\xd2\xf7\x1b\x29\xaf\xfe\x40\xd1\x69\xe0\ +\x75\x8a\x16\x01\xdd\xfd\x78\x84\xa2\xdf\xde\xc6\xab\x9e\xd7\x9f\ +\x01\x02\xbf\xb1\xae\xc3\x9d\x2b\x40\x00\x80\xe1\x48\x1d\xd1\x1e\ +\x76\xab\x08\x73\xf1\x90\x17\x1c\xe9\x78\x81\xdf\x58\x4f\xa6\x73\ +\x69\xee\xa7\xd5\xd5\xad\x72\xa9\xf8\xf4\x87\xe5\xcf\x4a\x94\x30\ +\xb4\xb7\x08\x12\x98\x13\x80\xd9\x93\x82\x6b\xdf\x5c\x9a\x9f\xdf\ +\x4c\x33\x72\x7f\x2f\x69\xb5\x5a\xdd\x72\xa9\xf8\xac\x63\xf9\xe3\ +\x88\x4b\x8c\x5b\x05\xc5\xe6\xc4\x02\x8f\x0a\xb9\x76\xd5\xf7\xfd\ +\x9f\xdb\x68\x83\x24\xbc\x99\xb9\xfb\x88\xbb\xbd\xd7\x08\xcc\x86\ +\x75\x4f\xcc\x41\x0f\xc2\x66\xed\x1e\xb0\xe3\xda\x6d\x15\x48\x63\ +\xed\xc3\xdb\x95\xe2\xf9\xf2\x06\x30\xd9\x0b\xab\xdd\x84\x12\x98\ +\xe1\x24\x92\x9d\xdf\x09\x9b\xf5\x87\x83\xf8\x03\x03\xf4\x42\xbc\ +\x29\x9e\xbb\xb8\x86\x34\x0d\xb8\x5e\x5f\xec\x18\xc2\xcc\x9c\x24\ +\x11\x77\xff\xad\xb0\x59\xaf\xfd\x4b\x7f\xe8\xf3\x9d\xb8\x51\x9d\ +\x32\x33\x1f\xc8\x13\x57\x21\x4a\xcf\xa7\xcc\x37\x25\x55\x96\x17\ +\x6a\xcf\x87\xd1\x1d\xa9\xc1\x26\x66\x66\x2f\x9b\xdc\x12\xd8\x51\ +\x33\x33\x29\xbe\xdf\x7d\x73\xb5\x9d\x6c\x2a\x58\xa8\xbf\x1c\x56\ +\x73\xe4\x0e\xf7\x2a\xd5\x0b\x44\x16\x00\x27\x0c\x4c\x89\x86\xf8\ +\x86\x34\x19\xfa\xb5\x77\xa3\xe8\x8d\x75\xc5\xae\x56\x66\xcf\x44\ +\x11\x21\xe8\x54\xfc\xc5\x3e\x3b\x87\x17\xf8\x8d\x8f\xa3\x6a\x8d\ +\xfd\x9b\xf1\xa6\x6f\x9f\xe4\x90\xfb\x02\x7a\xcf\x56\xf7\x5a\xb8\ +\xf8\xf8\xeb\xb8\x5a\x19\x32\x64\xc8\x70\xa0\xf8\x05\xa4\xf1\xa4\ +\x8e\x44\xc6\x51\x5e\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\ +\x82\ +\x00\x00\x00\x8a\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x3c\x49\x44\x41\x54\x58\x85\xed\ +\xcd\x21\x15\x00\x21\x00\xc0\xd0\x41\x26\x02\x60\xc8\x82\xbb\x30\ +\xa7\x08\xc3\x7b\x14\x20\x14\x0a\x8b\xc4\xb0\xaf\xe6\x06\x92\x24\ +\xbd\x2e\xec\x48\xf5\x1f\x40\xbe\x74\xed\xb3\x7d\x05\x20\x5e\x19\ +\x4a\x92\x24\x1d\x2c\x16\x1c\x05\x04\xcb\x08\x93\xc5\x00\x00\x00\ +\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x93\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x45\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x4e\xc2\x50\x14\xc6\xf1\xff\x29\xa1\x8c\x96\x05\x9f\xa1\ +\x0b\x03\x09\xf8\x02\x26\xf0\x0e\xac\x26\x94\xc1\x18\x9c\xd5\x41\ +\x76\x10\x19\xe8\x0b\xf0\x0c\xc6\xc4\x27\xa8\x89\x03\x4b\xdf\x81\ +\x05\x1c\x29\x81\xe3\x00\x35\x58\xc0\x41\xdb\x38\x78\xbf\xf1\xb4\ +\xc9\xf7\x4b\x6f\x87\x7b\xe0\xbf\x47\x92\x83\x8a\x37\xac\x5b\xaa\ +\xd7\x40\x0d\x70\x52\xea\x99\x03\xc1\x5a\xa4\xf7\xe6\x5f\x3e\x1f\ +\x05\x54\x5b\x8f\x5d\x85\x1b\x60\x01\x12\x22\xfa\x9e\x4a\xbd\xca\ +\x09\xa8\x0b\x14\x44\xb4\xfb\xea\x5f\xdd\xed\x01\xaa\xad\x41\x43\ +\x91\x27\x84\x97\x88\x7c\x73\xe2\xb7\xa7\xa9\x94\x6f\x53\xf6\x46\ +\x25\x9b\xe5\x18\xe5\x7c\x2d\xd2\x88\xbf\x84\xf5\x89\x44\x3a\xc0\ +\x22\x8b\x72\x80\x89\xdf\x9e\x46\xe4\x9b\x40\x94\x53\xed\xc4\x73\ +\x6b\xe7\x9d\x1a\x48\x98\x45\xf9\x2e\x42\x21\xd4\xcd\xff\xb5\x07\ +\x70\x52\x3b\xf3\x6f\x22\xc2\x1c\x28\x1e\x02\xfc\x49\x0c\xc0\x00\ +\x0c\xc0\x00\x0c\xc0\x00\x0c\xc0\x00\x76\x01\xf3\xcd\xed\x35\xdb\ +\xa8\xe2\x00\xb3\x43\x80\x00\xd4\x2d\x7b\xa3\x52\x56\xe5\x65\x6f\ +\x54\x12\x70\x05\x82\x3d\xc0\x5a\xa4\x07\x14\x6c\x96\xe3\x2c\x10\ +\x67\x17\x0f\xa7\x36\xcb\x31\x60\xaf\x44\xfa\xf1\xfc\xeb\x62\xe2\ +\x0d\xee\x55\xe5\x16\x88\x14\xc2\xed\x05\xf2\xd7\x51\xc5\x11\x70\ +\x01\xfb\xe8\x62\x12\xa7\xe2\x0d\xeb\x39\xd5\xce\xf6\xea\x5c\x4c\ +\x3e\xff\x61\x66\x02\xc1\x4a\xa4\x9f\x5c\xcd\x4c\x3e\x00\xa7\x7c\ +\x6e\x32\xdb\xbd\x64\x45\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\ +\x60\x82\ +\x00\x00\x00\xa1\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x53\x49\x44\x41\x54\x58\x85\x63\ +\x60\xa0\x00\x98\x64\x4c\x6c\x30\xc9\x98\xd8\x40\x89\x19\x4c\x94\ +\x68\xa6\x06\x18\x75\xc0\xa8\x03\x46\x1d\x30\xea\x80\x51\x07\x8c\ +\x3a\x60\xc0\x1d\xc0\x42\x05\x33\x1c\x28\xa9\x92\x87\x45\x08\x1c\ +\x38\x33\x23\xbf\x81\x5c\xcd\x03\x1e\x02\xa3\x0e\x18\x75\xc0\xa8\ +\x03\x46\x1d\x30\xea\x80\x51\x07\x0c\xb8\x03\x00\xb9\x93\x08\x9d\ +\x47\x2d\xcd\xca\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\ +\x00\x00\x03\x9c\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x03\x4e\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\xcd\x6b\x13\x41\x18\xc6\x9f\x77\xd3\xa8\x85\x52\x0f\x22\x22\ +\xf6\x60\x6d\x3c\xa8\x05\xd1\x93\xde\x8a\x36\x89\x15\x14\x9b\x18\ +\x94\x16\x11\xd2\x54\xfb\xf1\x07\x14\xff\x02\xeb\x51\x69\xfd\x22\ +\xed\xa5\xd4\x83\x31\x55\x11\x5a\x4d\x2a\xb4\xe0\xc1\x8b\x1f\x87\ +\x22\x3d\x58\x11\xcc\xa5\x8a\x87\x96\x8a\xa9\x49\x66\x3c\x18\x04\ +\xb3\x9b\x4d\xb3\xbb\x93\x31\xcd\xfc\x8e\xb3\xc3\xf3\x3e\xfb\x64\ +\x32\x33\xec\xce\x02\x0a\x85\xa2\x96\x21\xbb\x02\x6d\xa1\x81\x06\ +\x37\xcf\x0c\x82\xf1\x10\x08\xad\x00\xb6\x3a\xe0\xcb\x0e\xeb\xe0\ +\x58\x80\x46\xb1\x0c\xb9\x47\xe7\x62\xb7\xd7\xcc\x3a\xdb\x0a\xc0\ +\xd7\x19\xf1\x72\x0d\xe3\x00\x9a\xec\xe8\x08\x24\x45\x0c\xe1\xc4\ +\xe3\x68\xb2\x58\x07\x97\x55\x65\x5f\xb0\x27\xcc\x89\x1e\x02\xd8\ +\x6e\x55\xa3\x02\x34\x82\xd0\xb5\xef\xd0\xd1\x2f\x9f\x3e\xbc\x7d\ +\x6f\xd4\xc1\xd2\x08\xf0\x9e\x0f\xfb\xc0\xb5\x19\x00\x9a\x2d\x7b\ +\x95\x23\x47\x0c\x1d\x46\x23\xa1\xec\x00\xda\x42\x03\x0d\x6e\xf6\ +\x6b\x11\xc0\x1e\x47\xac\x55\x8e\x54\x46\xdb\x72\xa0\x70\x4e\x28\ +\xfb\x17\x74\xf3\xcc\x20\xaa\xef\xe6\x01\xa0\x29\xef\xfd\x1f\xca\ +\x1f\xc2\x8c\x87\x1c\xb1\x23\x03\x03\xef\xe5\x07\xf0\x67\xa9\xab\ +\x4e\x0c\xbc\xd7\x59\x90\x31\x5d\xe7\x93\xf1\xa8\xed\xbd\x85\x1d\ +\xbc\xc1\x08\x37\xb9\xac\xf3\x5e\x2d\xb3\xb8\x30\x54\x00\xb2\x0d\ +\xc8\x46\x05\x20\xdb\x80\x6c\x54\x00\xb2\x0d\xc8\xa6\xe6\x03\x28\ +\xb9\x11\xf2\x07\xae\xec\x66\x60\xfd\x20\x9c\x24\x60\x97\xd9\x2e\ +\x03\x00\x7c\xc1\xc8\x47\xab\x66\x38\xc0\x01\xa4\x08\x98\x76\x6d\ +\xfb\x79\x6f\x66\x72\x72\xd5\xaa\xd6\x46\x31\x0d\xc0\x1b\xe8\x3d\ +\xcb\x88\x8d\x03\xd8\x91\x37\x58\x12\x0e\xb4\xd8\xf4\xe4\xe1\x40\ +\x5b\x36\x5d\xdf\xdf\x1e\x88\x74\xcd\x4e\x45\x5f\xdb\xd4\x33\xa5\ +\xe8\x5f\xc0\x1b\xe8\x19\x06\xf1\xa7\xc8\xdf\xbc\x04\x9a\x89\xf0\ +\xca\x1b\xec\xed\x13\x59\xc4\x30\x00\x5f\x20\x72\x01\x44\x43\x22\ +\x0b\x6f\x10\x17\xc0\x47\xda\x03\x91\x63\xa2\x0a\xe8\x02\x38\x75\ +\xae\x6f\x2f\x27\xba\x2f\xaa\xa0\x05\x5c\x44\x78\xd0\xd1\xdd\xdd\ +\x28\x42\x5c\x17\x40\xd6\x95\xbd\x06\x70\x21\xc5\x6c\xd0\x9c\x4b\ +\xd7\x5f\x15\x21\xac\x0b\x80\x80\xd3\x22\x0a\xd9\x85\x0b\xf2\x65\ +\x34\x07\xfc\xaf\x8f\xb8\x85\xf8\x2a\xfb\x81\x88\xa6\xf1\xfd\x22\ +\x8c\x64\xb3\xf0\x68\x1a\xcd\x14\xbb\x4e\x0e\xbc\xc4\x31\xa2\xec\ +\x00\x5e\xc4\xc6\x2c\x6f\x74\xcc\xf0\x87\x7a\xc0\x98\x08\x65\x73\ +\x6a\x7e\x2b\xac\x02\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\ +\x90\x6d\x40\x36\x2a\x00\xd9\x06\x64\xa3\x02\x90\x6d\x40\x36\x2a\ +\x00\xd9\x06\x64\x63\xe5\x7c\x80\x14\x38\xd0\x52\xe2\xdd\xff\x46\ +\x58\x2f\x6c\xa8\xad\x11\xc0\xb1\x50\xd8\x54\x5b\x01\x68\x14\xd3\ +\x35\xc9\xf0\x21\x89\x54\x86\xdc\xa3\x85\x8d\x55\x33\x07\xd8\x24\ +\x47\x0c\xe1\xb9\xb8\xfe\xdc\x70\x2d\x04\x90\xe3\x84\xde\x64\x91\ +\xf3\xc2\x9b\x3d\x80\x14\x31\x84\x8b\xdd\x3c\xb0\x39\x03\xf8\x7b\ +\x5c\x9e\xea\xd3\x23\x89\x89\x89\x1f\x66\x9d\x75\x8f\x9a\x1d\x58\ +\x6b\x85\x40\xc0\x52\x22\x1e\xf5\x38\xad\x6b\xb4\x0a\x7c\x73\xba\ +\x88\x13\x70\x60\x59\x84\xae\x51\x00\xb3\x22\x0a\xd9\x86\xe3\xa5\ +\x08\x59\x5d\x00\x1a\x63\x37\x00\x64\x44\x14\xb3\xc1\x77\x0d\xda\ +\x1d\x11\xc2\xba\x2f\x46\x96\x16\xdf\x2d\x7b\x0e\x1e\x59\x03\xc8\ +\x2f\xa2\xa0\x15\x08\xfc\x62\x62\x2a\xfa\x46\x84\xb6\xe1\x4e\xf0\ +\x78\x6b\xd3\x4d\x10\x1e\x89\x28\x58\x2e\x04\x0c\x27\xe2\x63\xcf\ +\x44\xe9\x1b\x7e\x33\x34\x3f\x3f\xcf\x2f\x85\xce\xc4\x53\x5f\x57\ +\x57\x00\x3a\x51\xac\x9f\x60\x56\x38\xe8\x72\x32\x1e\xbd\x25\xb2\ +\x48\xc9\x37\xae\xfe\xce\xf0\x61\xa6\x69\x43\x00\xda\x01\xec\x14\ +\x69\x26\x4f\x8a\x03\xd3\x75\xb9\xba\xeb\xcf\x9f\xdc\xfd\x5c\x81\ +\x7a\x0a\x85\xa2\x86\xf9\x0d\x29\x0e\xd0\xf4\xc6\x6c\xeb\x8f\x00\ +\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x01\x9f\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\x51\x49\x44\x41\x54\x58\x85\xed\ +\x94\x2d\x48\x43\x51\x14\x80\xbf\xf3\x36\x10\x14\x15\x67\xd1\x66\ +\x17\x2c\xbe\x55\x8b\x98\x4d\xb3\x6a\x71\x4f\xd0\x4d\x8c\x82\xe0\ +\x5e\xb0\x98\xdc\x14\xdd\xc6\xc2\xaa\x13\x9b\x59\xb0\xcf\xbf\x64\ +\x53\x9b\x7f\xf8\x93\x06\x8a\xbb\xc7\xb4\x89\xf1\xdd\x07\xaf\xf8\ +\xbe\x76\xe0\xfc\x7c\xdc\x7b\xee\x85\x98\x98\x98\xff\x8e\x04\x4b\ +\x57\x71\xbd\x5d\x03\xf0\xfd\xd9\x1e\xba\xaa\xaf\x7d\x84\x15\x70\ +\x02\x65\x6f\x16\xba\xc2\xc9\x9e\xc4\x7b\x26\xd3\x48\x44\x2b\xe0\ +\xfb\x46\x55\xe6\x3a\xe1\x5d\xea\xf1\x3b\x5a\x01\xe0\xbc\x9a\x3b\ +\x42\x65\xab\x13\xbb\xd9\xd2\x75\xa4\x02\x00\xcd\x6a\x6e\x43\xe0\ +\x14\x00\x61\xc2\xf5\x8a\x07\xb6\x02\x01\x97\xf0\x2f\xae\x57\xd2\ +\x6e\xa0\xea\x35\xab\xab\xd5\xa0\x3d\xac\x4e\xa0\x43\x73\xe4\xf5\ +\x77\x09\x45\x2a\x69\x6f\x67\x2a\x52\x01\x7c\xdf\xb4\x12\x89\xfe\ +\x4e\xa8\x38\x67\xd1\x0a\x00\xbc\x3c\x7f\x29\xdc\xdb\x96\x87\x14\ +\x50\xe9\x1d\x1a\xae\x09\x8c\x01\x4f\xed\xa4\x33\x16\xb4\x43\xa8\ +\x8f\xc4\x5d\x4a\x15\x40\xf2\x40\xcb\x38\x3a\x73\xb9\x9f\xbf\x09\ +\xda\xc3\xfa\x15\x4c\x66\x8b\xf3\x22\x52\x07\x8c\x11\x67\xf6\xa2\ +\xbc\x72\x62\xd3\x27\x69\x53\x94\xf6\x8a\xd3\x8a\xd4\x00\x14\x59\ +\xb6\x1d\x0e\x16\x3b\x90\x5e\xdc\x1b\x57\xe4\x18\x48\xa2\xba\x7d\ +\x5e\xc9\x95\x6d\x87\x5b\x08\xa8\x18\xc7\x34\x80\x41\xe0\xb0\x39\ +\xfa\xb6\x1e\x66\x38\x58\x5c\x81\xc0\x83\xa0\xb7\x7d\x9f\x03\x0b\ +\xf8\x79\x13\x56\x20\x26\x26\x26\xe6\x07\x9e\x35\x61\x37\x0a\x6d\ +\x65\xe5\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x0b\x31\x18\x83\x23\x65\x15\x94\ +\x0c\x12\x86\x30\x1d\xff\x7d\xac\x6b\x23\x91\xd1\xc9\x8a\x93\x15\ +\xce\xc6\xb4\x04\xad\x65\xdd\x4b\x1a\xee\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\xb8\x79\x9f\x91\x7a\xbf\x61\xfc\ +\xdc\x05\xd1\x25\x09\xfd\x18\x55\xe2\x51\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x87\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x39\x49\x44\x41\x54\x58\x85\xed\ +\xce\x31\x11\x00\x30\x08\x04\x41\x26\x9a\x10\x85\x0c\x2c\xe0\x38\ +\x22\xa0\xdc\xeb\xff\x67\x23\x16\x65\x4d\x67\x4d\x6f\x3e\xde\x66\ +\x7c\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ +\xc0\x07\x39\x3f\x03\x99\x39\x3b\x26\x1f\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x02\x0d\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbf\x49\x44\x41\x54\x58\x85\xed\ +\x94\xb1\x6a\x54\x41\x14\x86\xbf\x7f\x36\x4a\x90\xe0\x6a\x13\x8b\ +\x8d\x91\x04\xad\x63\x91\x4a\x49\x2d\x62\x4a\x1b\x51\xf0\x01\x44\ +\x7d\x05\x7d\x04\x83\x0f\x20\x28\xd8\x58\x28\x28\x62\xba\x80\x79\ +\x00\x61\xfb\xdd\xd9\xd9\x15\x02\x29\xac\x6c\xc2\x9d\xdf\xe2\xee\ +\x26\x31\xbb\x01\xf7\xba\x62\x73\xbf\xe2\x32\x70\xee\x9c\xff\x9b\ +\x73\x87\x0b\x35\x35\x35\x35\xff\x19\x55\xdd\x98\x52\x6a\x15\xe6\ +\x13\x66\x2d\xc8\xad\xe5\xe5\xe5\xef\x55\xfa\x84\x8a\xe1\xd7\x8a\ +\xac\xaf\x98\x35\x80\xec\xb0\x9b\x52\xba\x5a\xa5\xd7\xd4\x13\xe8\ +\x74\xfa\xd7\x15\xfc\x05\x58\x04\x1f\x6b\xa3\xbd\x5c\x70\x6b\x75\ +\x75\xe9\xdb\x34\xfd\xa6\x9a\x40\xaf\xd7\xdb\x50\xf0\x0e\xb0\x28\ +\x30\xa8\x00\x15\xe5\xda\x97\x42\xc3\x3b\xbd\x5e\x6f\xe3\x9f\x08\ +\xc4\xd8\xdf\xcc\xd6\x36\x70\x1e\xb0\x21\x8f\x6a\xc3\xb5\x81\x66\ +\xb6\xb6\xbb\xdd\xfe\x9d\x99\x0a\xc4\x98\x1e\x18\xbf\x07\xe6\xcb\ +\xec\xa3\xf0\x63\xe4\x61\x6d\x1e\xf9\x43\xb7\x9b\xee\xcf\x44\x20\ +\xc6\xf4\xc4\xf0\x1a\x68\xb8\x1c\xfb\xa4\xf0\x21\xca\x18\x03\x0d\ +\xc4\x9b\x18\xd3\xe3\xca\x02\xb6\xd5\x89\xe9\xb9\xe1\xc5\xa8\xb9\ +\x26\x9f\xfc\x84\x03\x19\x95\x92\x86\xad\x4e\x4c\xcf\x6c\x9f\x7a\ +\xd9\x27\x16\x6c\x87\x98\xfa\x5b\x98\x47\xb6\x09\x52\xf6\xd1\x95\ +\xff\x43\x24\x3b\x07\x49\x20\x5e\x5e\xb9\xbc\xf4\x54\x1a\x9f\xde\ +\x98\x40\xbb\xdd\x3e\xbb\xb0\xd0\x7c\x85\xb8\x37\xd4\xc9\xa0\x29\ +\xc3\x0f\x8f\x22\x50\x39\x65\xf3\x76\x7f\x7f\xef\xe1\xfa\xfa\xfa\ +\xc1\xa9\x02\x83\xc1\xe0\xdc\x41\x91\xdf\x61\x6e\x97\x7b\xc8\x9a\ +\xfa\xe4\x27\x14\x40\xc2\x01\x04\xe2\xf3\x99\x46\xb8\xdb\x6a\xb5\ +\x7e\x8e\x09\xc4\x18\x2f\x9a\xf0\x11\xb8\x51\x5e\x66\x65\xf4\x77\ +\xe1\xc7\x2c\x04\x0e\x48\x80\x77\x9d\x8b\xcd\x95\x95\x95\x1f\x00\ +\x73\xa3\x77\xb2\x43\x47\xa2\x59\x6a\x09\x2a\xfe\xa6\x27\xa2\xc3\ +\x07\xa0\x9b\x0a\x73\x5d\xe0\xc2\xef\x21\x55\x3f\x73\x05\x3c\xa3\ +\xc1\xd6\xd4\xd4\xd4\xcc\x84\x5f\x30\x7d\xb9\x9b\x4b\x8f\xb2\x18\ +\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x75\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x27\x49\x44\x41\x54\x78\x9c\xed\ +\xc1\x01\x0d\x00\x00\x00\xc2\xa0\xf7\x4f\x6d\x0e\x37\xa0\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x80\x77\x03\ +\x40\x40\x00\x01\x8f\xf2\xc9\x51\x00\x00\x00\x00\x49\x45\x4e\x44\ +\xae\x42\x60\x82\ +\x00\x00\x04\x67\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x04\x19\x49\x44\x41\x54\x78\x9c\xed\ +\x9b\x4d\x88\x1c\x45\x18\x86\xdf\xb7\x67\x27\x59\x91\x78\x31\x88\ +\x30\x3b\xdd\xd3\x3b\x89\x3f\x57\x5d\xbc\x0a\xc1\x44\x22\xf8\xc3\ +\x22\xe2\x41\x10\xfc\x41\xc1\x93\x22\x01\x3d\xa8\xa0\x01\x45\xf0\ +\xa0\xe0\x1f\x0a\x1e\x44\xd1\x53\x0c\x62\x64\x83\x10\xf0\x22\x08\ +\x82\x07\x31\x38\xcb\x6c\xd7\xf4\x74\x30\x46\x11\x45\x71\xcd\xf4\ +\xd4\xe7\x61\x26\xc6\xed\x6a\xcd\x8e\xa9\xaa\xee\xc3\x3c\xb7\x6d\ +\x96\x7a\xbf\x7a\xa6\xba\xbb\xbe\xee\x19\x60\xce\x9c\x39\x73\x2c\ +\xa0\x54\xfa\x4c\xa2\xd2\x5c\x0d\xd2\x91\x52\xd9\xd3\x55\xd7\xb3\ +\x5d\x68\x6b\xa0\x44\xa5\x63\x00\xc1\xf4\x4f\x11\x8d\x7d\x71\xdc\ +\x3e\x61\x6b\x7c\x57\x04\x17\xfe\x97\xed\x21\x22\xff\x1c\x8b\x0c\ +\x70\x54\x29\x75\xbd\xad\xf1\x5d\x61\x4d\x00\x49\x5d\x38\xb4\x4b\ +\x10\x7c\xda\xef\x67\x57\xdb\xca\x70\x81\x35\x01\x00\xa4\xe4\xd8\ +\xee\x46\x43\x1f\x5f\xcf\xb2\xb6\xc5\x1c\xab\xd8\x14\x50\x8a\x00\ +\xed\x85\x5c\xaf\x65\x59\xb6\xdb\x75\xd6\xff\xc1\xb9\x80\x29\xd7\ +\x8c\x72\x7d\xec\xe4\xc9\x33\xbb\x3c\xe5\x6d\x1b\x97\x02\x8a\xa7\ +\xc4\xca\xe2\x25\x9b\x47\x7a\xbd\xde\x4e\x87\x99\x33\xe3\x52\x80\ +\x86\x29\x61\x5f\x73\xe7\xe2\x7b\x22\xb2\xe0\x30\x77\x26\x5c\x9f\ +\x02\x1a\xe0\x56\x09\x82\x55\x95\x0e\x5f\x17\x11\x6b\x7b\x90\x8b\ +\xc1\xc3\x35\x40\x34\x8b\x2b\x41\x70\x7f\x32\x18\x3e\xef\x3e\xfb\ +\xc2\x78\xb9\x08\x0a\xa0\xa5\x70\x32\x10\x38\xa4\x54\x7a\xc8\x47\ +\xfe\x7f\xe1\xeb\x2e\x00\x12\xe3\xe2\x31\x01\x5e\x48\x92\xf4\x01\ +\x5f\x35\x94\xe1\x4d\xc0\x04\x29\xee\x16\x01\xe2\x8d\x24\x49\x57\ +\xfd\xd6\x71\x1e\xcf\x02\x28\x10\x14\x25\x04\x20\xde\x57\x2a\xbb\ +\xc9\x6f\x2d\xe7\xc2\x7d\x43\x08\x60\x48\xd8\x21\xd0\x47\xfa\x69\ +\x7a\x83\xef\x72\xfc\x0b\x98\x50\x26\xe1\xd2\x40\xe3\x93\x24\x49\ +\xae\xf5\x59\x48\x55\x02\x00\x40\x40\x43\xc2\xe5\x60\xe3\x78\xbf\ +\x7f\x2a\xf2\x55\x44\x95\x02\x00\x81\xd0\x5c\x09\xad\x20\x18\xaf\ +\xad\xaf\x7f\x7f\x85\x8f\x12\xaa\x15\x00\x40\x00\x91\xe2\x46\x89\ +\xb8\x6a\xa1\x79\xf6\x58\xaf\xd7\xbb\xcc\x75\x7e\xe5\x02\x00\x80\ +\xa5\x7d\x03\xaf\x6b\x36\x17\x8f\x6e\x6c\x6c\x2c\xba\xcc\xae\x85\ +\x80\x29\xa6\x04\xe2\x46\x04\xcd\x0f\x5c\x36\x4f\x75\x12\x00\x94\ +\x34\x4f\x84\xdc\x36\x18\xa4\x6f\x15\x9e\x39\x5a\xa3\x6e\x02\x00\ +\x88\x26\xb7\xae\x04\x01\xef\x55\x2a\x7b\xd1\x45\x07\x59\x43\x01\ +\x80\x88\xd9\x3c\x81\xf2\x98\x4a\xb3\x27\x6c\x67\xd5\x52\x00\x50\ +\xde\x3c\x41\xe4\xf0\x86\x1a\x3e\x64\x33\xa7\xb6\x02\x26\x98\xcd\ +\x13\x21\xaf\x29\x35\xbc\xd3\x56\x42\xcd\x05\x50\xc4\x6c\x9e\x28\ +\x90\x57\x6c\x25\xd4\x5c\x00\xfe\xed\xe5\x9d\xb5\xdb\x62\x6d\x1e\ +\x4e\x96\x31\x9d\xbb\xf1\x21\x09\xf0\xb6\xad\x8c\x1a\x0b\x20\x34\ +\xa4\x61\x2c\x00\xca\x23\x71\x18\xbe\x6a\x2b\xa5\xa6\xa7\x00\x21\ +\x52\x32\x79\x91\xa7\x3a\x16\x27\x0f\xd4\x55\x00\x25\x60\x61\xf6\ +\x02\xbc\x1c\x45\xed\xe7\x6c\x47\xd5\x4e\x00\x81\x00\x62\x5c\xfa\ +\xde\xed\x84\x4b\x8f\x92\x2c\x7b\x01\x7b\x51\xd4\x46\xc0\xe4\x13\ +\x67\x20\xe6\x75\xff\xe3\x1f\xcf\x9c\xbe\xaf\xe4\xf5\xbb\x15\x6a\ +\x23\x60\xd2\xec\x6c\xdd\xeb\x0b\xf0\x79\x23\xc0\x5d\x2b\x2b\x2b\ +\x23\x57\xb9\xf5\x10\x20\x12\x9c\x5b\x03\x7f\x43\x7c\xad\xf3\xb3\ +\xb7\xb6\xdb\xed\x3f\x5c\x46\x57\x7f\x1b\x24\x09\x73\xd9\xaf\xeb\ +\x7c\x74\x73\xb7\xdb\xfd\xc5\x75\x7c\xc5\x2b\x80\x84\xd9\xe7\x9f\ +\x12\x9d\xef\x5f\x5e\x5e\x3e\xed\xa3\x82\x2a\x57\x00\x01\x63\xf2\ +\x3f\x13\xfa\x40\x27\x8e\x13\x5f\x45\x54\xb2\x02\xa6\x57\xfa\x62\ +\xf6\xef\xa2\x79\x4b\x14\x45\xdf\xf8\xac\xc5\xbf\x00\x01\x69\xe6\ +\x8e\x34\x65\x35\x8e\x97\xbe\xf0\x5d\x8e\xef\x97\xa3\x04\x8d\x4c\ +\x21\x78\xcf\x72\x18\xae\xf9\xad\x65\x82\xef\x97\xa3\x46\x1e\x81\ +\x87\xa3\x68\xe9\x43\xbf\x75\x9c\xc7\x9b\x00\x11\x34\x8c\x63\xe0\ +\x93\x51\xd4\x7e\xd3\x57\x0d\x65\x78\xb9\x0b\xd0\x5c\xf6\x80\xf0\ +\xa5\x4e\xd4\xaa\xfc\x6b\x32\x1e\x56\x00\x03\x29\x34\x37\x04\xdf\ +\x89\xa2\xd6\xe3\x2e\x9a\x9b\x59\x71\x2d\xc0\xd8\xdf\x13\xf8\x28\ +\x0c\x5b\x0f\xd6\x61\xf2\x80\x5b\x01\x01\x8a\x5b\x5c\xe2\x84\xd6\ +\xf9\xdd\x24\x73\x87\xb9\x33\xe1\x52\x40\xf1\x91\xc6\x57\xa3\x3f\ +\x37\x6f\x8f\xe3\x78\xd3\x61\xe6\xcc\xf8\xd9\x0a\x0b\xbe\xcb\xf3\ +\x1d\x07\xf7\xee\x0d\x7f\xf5\x92\x37\x03\x3e\x6e\x83\xc3\xf1\x38\ +\xd8\xbf\x67\xcf\x95\x3f\x78\xc8\x9a\x19\x9b\x02\xca\x9e\xe0\xff\ +\x04\x19\x1f\xe8\x76\x5b\x03\x8b\x39\x56\x71\xf5\x93\x19\x00\xf8\ +\x2d\xa0\x1c\xec\x74\x3a\xdf\xda\xca\x70\x81\xa3\x9f\xcc\x50\x08\ +\xde\x11\x86\xe1\x97\xb6\xc6\x77\x85\x35\x01\x01\x79\x18\xe0\x18\ +\xc0\x98\xe0\xb3\x51\xb4\xf4\x99\xad\xb1\xe7\xcc\x99\x33\xc7\x15\ +\x7f\x01\x49\x16\x4b\x51\x69\x18\xd5\x52\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\x97\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x49\x49\x44\x41\x54\x58\x85\xed\ +\xd7\xb1\x0d\x00\x20\x0c\x03\x41\x83\x18\x8c\x26\x13\x64\x85\x8c\ +\x89\x94\xd5\x18\xc2\x74\xfc\xf7\xb1\xae\x8d\x44\x46\x91\xd5\x91\ +\xd5\xce\xc6\x32\x0d\xdb\xbc\xd7\x74\x07\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x00\x00\xc0\xcd\xfa\x8c\x86\x74\x5e\x41\xfe\ +\xed\x02\xdd\xeb\x04\xae\xa2\x49\x76\xdf\x00\x00\x00\x00\x49\x45\ +\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x0c\xd6\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x40\x00\x00\x00\x40\x08\x06\x00\x00\x00\xaa\x69\x71\xde\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x0c\x88\x49\x44\x41\x54\x78\x9c\xe5\ +\x9b\x5b\x6f\x5b\xc7\x11\x80\xbf\x25\x45\x8a\x94\x28\x89\x92\xad\ +\xbb\x64\xc9\x4e\x9a\xc2\x41\xe0\x26\x45\xd1\xa0\x48\x0a\xf4\xa9\ +\x7d\xe9\x7b\x81\x16\xfd\xa3\x7d\x2a\x50\xb4\x0f\x41\x90\x36\x4e\ +\x52\x20\x69\x92\xc6\x96\x6c\xc9\x37\x5d\x48\x49\xa4\x2e\xe4\xf4\ +\x61\xf6\x1c\xee\xd9\x33\x87\xa4\xe4\xf4\xc9\x03\x10\x24\x77\xf7\ +\xcc\xce\xcc\xee\xce\x6d\xe7\x00\xb2\x05\xe2\x78\xe3\x40\x9c\xf2\ +\x9e\xfe\x78\x93\x84\x90\xe3\xf9\x4d\x12\x42\x96\x57\x97\xed\xe0\ +\x0e\xf0\x18\x9c\x14\x3c\xdc\x00\x6e\x19\x1d\x25\x60\x32\x8b\x2f\ +\x6d\xaf\x0d\xa1\x66\x12\x10\xe0\x62\xc8\x98\x73\xa0\x67\xb4\x77\ +\x81\xbe\xd1\xfe\x12\xdc\xa9\x8d\x2a\xcf\xa3\x1b\x35\x00\x64\x1b\ +\xb8\xed\x09\x3d\x01\x5e\xf8\x89\xa7\x80\x39\xdf\x2e\xc0\x59\xd0\ +\x3e\xeb\xdb\xfa\xbe\x1d\x8f\xa3\x0a\x34\x81\x8a\xef\x3f\xf7\x34\ +\x54\xfd\xf7\x25\x70\x04\x97\xa7\x50\x39\xf2\x6d\x53\xa8\x20\x9d\ +\x9f\xff\xc4\xff\x9f\xf2\x6d\x0e\x68\x01\xa7\xbe\x7d\x29\xe8\x7b\ +\x01\xee\x71\x31\x6f\x85\x52\x92\x2d\x90\x09\x90\x8f\x40\x56\x8d\ +\x31\x6b\x20\x0b\x46\xfb\x06\xc8\xbc\xff\x3d\x05\x72\x0f\xe4\xae\ +\xff\xcc\x80\xdc\x01\x19\xb2\x23\xa4\xee\xc7\x2c\xa8\xe0\xe5\xae\ +\xc7\x31\xe1\xfb\xe7\x40\x36\xf3\x47\x55\x9a\x05\xed\x1b\x20\xbf\ +\x06\x29\x5f\xf3\x88\xcb\x04\xc8\x9f\xf5\xc1\x5c\xdf\x36\x48\xc5\ +\x68\x7f\xdb\x3f\xb7\xe2\x27\x5b\x8e\xf0\xdd\x1b\x73\x72\x3c\xe3\ +\x25\xff\xdb\x79\x46\xb6\xa0\x75\x4b\xdb\xe5\x2d\x83\xd9\x32\xc8\ +\x4f\x8c\xf6\x09\x90\x3f\xda\xbc\x14\x13\xf0\x91\x7f\x30\x92\x9a\ +\xac\x17\x30\x7f\xc7\x7f\xb6\xed\x15\x96\xed\x6b\x4c\x4e\x60\xa2\ +\xe2\xf6\x59\x15\x4e\x7b\x49\xe7\xcb\xf5\x97\xb3\xcf\xa5\xbb\xb9\ +\x02\xf2\xab\x71\x27\xdf\x1e\x6c\xfb\x50\x63\xca\x14\xc8\x6d\x63\ +\xfc\x2a\xc8\x07\xba\x7d\x4d\x7c\xf3\x5e\x79\x5e\x13\x64\x56\xb7\ +\xbc\xd9\x37\x07\xf2\x00\x64\xd1\xe8\x6b\xfa\x67\x23\xcb\x26\x9b\ +\xfa\xc9\x82\x71\x26\xe4\x17\xe0\x3e\x0d\xfe\x27\xca\xa3\x07\xec\ +\x01\x21\xa3\xab\x70\x79\x0b\x2a\x5f\x0e\xe1\x64\x0d\x78\x5a\xd0\ +\x97\xda\xe1\x1b\x3c\x0b\xf0\x00\xba\x4f\xa0\xf6\x2a\x68\xeb\x28\ +\x5d\x94\xc9\x29\xbc\x98\x37\x98\x30\x90\xc6\xc4\x34\x50\xe6\x1f\ +\xa0\x5a\xbd\xed\xc7\x6c\x01\x2f\x54\xa1\x0f\x05\xf1\xc4\x2c\xf9\ +\xff\x89\xe9\x4a\x34\x78\xd8\x46\xd0\xf6\xc2\xa0\x25\x86\x17\x20\ +\x82\x32\xbc\xe7\x9f\x5d\x02\x7e\x06\x7c\x0e\xcc\xa0\x16\x22\x81\ +\x9c\xd9\x8c\x04\x20\x0d\xd4\xcc\x24\xff\x37\x80\x36\xb8\x5d\x3f\ +\x51\x05\x35\x5d\x9b\xc0\xd7\xe0\xae\xf4\x7c\xb9\x13\x72\x20\xce\ +\x8f\x9b\x42\x7d\x81\x6f\x47\x98\x9f\xf8\xd9\x45\x60\x1a\x35\xa9\ +\x7b\xf6\xb3\xd2\x86\xfa\x0b\xd4\x9f\x58\x01\x7e\x00\x16\x80\xcf\ +\x80\xe7\x80\xb7\x3c\xec\xf8\xe7\x7b\xaa\xdb\xdc\x55\xd1\xc4\x5b\ +\x03\xf3\x26\x5b\x59\xcd\x29\x1b\x5e\x0f\x7c\x1c\x29\x46\xcb\x4c\ +\x2e\xa1\xa6\x72\x46\x3f\x37\x05\x59\xf5\xca\x78\x3d\x6b\x55\xd2\ +\xfe\x99\x81\x7e\x91\x09\x90\xdf\x78\x2b\x11\xb6\x07\x8a\x51\xee\ +\xaa\x8e\x18\x40\xc9\x98\xb5\xaf\x13\xb2\x0b\xae\x17\x8d\x5d\x03\ +\xfe\x0e\xdc\x09\x84\x10\xac\xcc\x61\x53\x19\xe7\x10\xdc\x53\xdf\ +\x37\xe6\xaa\x9b\xe0\x9f\x75\x4f\x80\x03\xc5\x7d\xd8\xcc\xf7\x8b\ +\x03\xd6\x81\xbf\x01\xf7\xb2\x73\xba\x9e\xf2\x22\xeb\x18\x47\xc0\ +\x12\xc0\x14\x70\x16\x31\x0f\x7a\xe6\xbf\xf3\x5b\xe9\x31\x59\x21\ +\xa0\x1a\xb9\xd9\x57\xc6\xdd\xe5\xf8\x3c\x8e\x0b\xee\x52\x71\x37\ +\xfb\xd1\x6e\x08\x3d\xbc\x1e\xf0\x04\x3d\x7a\xe1\x90\x1e\xea\x29\ +\x4e\xc7\x58\x2d\x25\x38\xe7\x57\x2f\x00\xd9\x46\x95\x4c\x29\x30\ +\x77\x07\xc0\x7d\xe0\xd2\x9b\xab\x57\xe8\xee\x09\x4d\x9e\x9f\xd0\ +\xdc\x04\x25\xe8\xfa\xe3\x56\x3b\xc4\xf6\xf7\xa7\x81\x2e\x48\x78\ +\x66\xfb\x3a\x56\xee\x03\x47\xe8\xca\x7f\xad\x63\x05\xa0\x03\x9d\ +\x13\xa8\x2f\x92\xd1\x67\xee\x08\xe4\xa7\xf1\x04\x63\x58\x01\x79\ +\x0b\x2e\x2a\x50\x9d\x46\x15\xd3\x29\x83\xad\xbd\x0b\xfc\x0e\xf8\ +\x4b\x01\x03\x01\x74\xe6\xa1\x9e\x04\x3f\x3e\x4e\xa8\x1d\xf9\xce\ +\x79\xd4\x52\xf8\x1d\xd5\x39\x87\xfa\xe1\x10\x64\x5d\xd4\x3c\xfe\ +\x06\xf8\x24\xa0\xd9\x2b\xcf\x7a\x0d\xb8\x0d\x72\x1e\x2d\x66\x6e\ +\x25\x62\x01\xc4\xd1\xe1\x5d\x60\x1a\x26\x1f\xaa\x12\x74\xfb\xd9\ +\xe1\xb2\x0e\xfc\x03\x0d\x70\x8c\x20\x43\x80\xee\x6d\xa8\x4d\x40\ +\xfd\x25\xb8\x4e\x01\x43\x47\xd9\xbf\x52\x07\x16\xe0\xa2\x06\xd5\ +\x93\xbc\xd6\x4e\x7d\x93\xbf\x02\x6b\xe0\xf6\x82\xce\x36\xc8\x09\ +\xba\x63\xdf\xf6\x9e\x6b\x42\x5b\x9f\xe8\xd8\xc7\x3a\xa0\x0a\x9c\ +\xfb\x09\xee\xa1\xab\xf2\x85\x4d\xb3\x2c\xa1\xdb\xbe\x87\xad\x13\ +\xa6\x81\x55\xa8\xb5\x55\x89\x15\x32\x6f\x80\xeb\xe8\x33\xd5\xb6\ +\x32\x18\x1e\xab\x30\xaa\xa3\x87\xfa\x02\x2b\x05\x88\xbe\xf1\x63\ +\xee\xf9\xe7\x3a\x64\x1d\xb9\x22\x2b\xc0\x06\xf0\x0c\xf5\x01\x8c\ +\x03\x7c\xd8\x04\xba\xe0\xba\x9e\xe0\x48\x31\x1e\xcd\x43\xbb\x86\ +\xae\xc2\xf9\x58\x3c\xdb\x70\x01\x3c\x85\xf6\x24\x1c\x2f\x60\x87\ +\xb4\x5d\xe0\x4c\xe7\x8c\xc1\x9d\xa1\x8b\xfa\x83\xe7\x29\xc7\x8b\ +\x25\x80\x06\xea\x3d\x2d\xe6\xb7\x7c\x02\xcd\x29\x70\xad\x6c\x5b\ +\x22\x84\xcb\xf7\x61\xae\x07\xb3\xaf\xcc\x47\x6f\x04\xb3\xaf\x60\ +\xf6\x52\x71\x5b\x47\xcd\xb5\x60\xae\x20\x16\x61\x07\x35\xdf\x2d\ +\xd4\xc2\x65\xc0\x12\xc0\x34\xaa\x3d\x0b\x94\x9a\x2c\xa3\x6e\xaa\ +\x01\xc7\x4d\xa8\x7c\x0f\xcc\x33\x7e\xec\x3d\x06\x88\x03\x16\xa0\ +\xf2\x9d\xce\x61\xc2\x73\xdb\x59\x72\x97\x40\x19\xdc\x31\xba\xb8\ +\x19\xb0\x04\x20\xa8\x69\xd9\x29\x20\x64\xc2\xb6\xf3\x32\x05\xa5\ +\x64\x22\x7f\x1c\xac\x60\xeb\xda\x10\x6e\xfb\x16\x94\x4a\x5e\xbf\ +\xc4\xc3\xae\x94\x36\xb1\x78\x3a\xd4\x23\x34\xda\x0a\x94\x07\x83\ +\x4c\xbf\x7d\x13\xd5\xb2\xe1\x2a\xcc\x82\x74\x81\x15\x98\xd9\x0f\ +\xfa\x5a\xc0\xbb\xc0\x13\xd2\x8c\x4e\x06\x92\xd4\x19\xa8\x4f\x61\ +\xe5\x05\xe7\xd0\x40\xe7\x07\xfd\x2d\xa0\x3b\x73\x03\xe4\x19\x03\ +\x3f\x23\xc1\x7f\xa6\x7d\x1c\x64\xd1\xb8\x63\xef\x0e\x27\x81\x59\ +\x0a\x31\x61\x35\x72\x49\x48\x99\x47\x83\x8d\x65\x4f\x64\x84\x9c\ +\x1e\x74\x66\xa1\x7e\x00\xc4\x41\xc6\x23\x4f\xd0\xd7\xc1\xe4\x2b\ +\x40\x1f\x3a\x67\x50\xdf\x05\x1c\x74\x6f\x41\x2d\xc9\x2f\x3e\xf3\ +\xdf\xce\xcf\xf9\x05\x9a\x2b\x0c\xe1\x15\x74\x66\xa0\x9e\x08\x2d\ +\x9c\xb7\x89\x2a\xbe\xbe\xee\x86\x54\x57\x25\x79\xcb\x4c\xc2\xc6\ +\x5a\x99\x45\xe0\x4b\x90\xaa\x27\xe0\x25\xb8\x43\x34\xd3\x73\x96\ +\x8f\xfc\xa4\x01\xf5\x32\xb8\xe7\x79\x54\x82\x67\x7e\x01\x38\x46\ +\x57\xec\x1b\x63\x77\xb5\xfd\xf8\x32\xba\xe2\x07\x9e\x8e\xff\x68\ +\x5f\x2e\x7a\x3b\xf1\xa6\xcf\x67\x7f\x43\x9a\x64\x1f\x15\x98\x17\ +\x9a\x6c\x02\x4f\xe0\xa4\x03\x8d\x29\xb2\xe1\xb1\xa9\x03\x4a\xa8\ +\x04\x6f\x83\xdb\x09\xec\xf7\x2d\x6c\xe5\x37\x0d\x47\x05\x69\x68\ +\xa5\x00\xcd\xf4\x6e\x01\x4f\x87\x87\xc4\xa9\x2f\x7f\x1f\x0d\x67\ +\x87\x05\x52\x27\x18\xbe\xbd\x5f\x08\x9f\xb9\x72\x27\xa8\xb7\xba\ +\x01\x8d\x03\xf4\x48\x65\xa0\x48\x09\x2e\xe5\xe3\x01\x28\x20\xbe\ +\x01\xf3\x47\x46\x7b\x02\x65\x25\xb4\xf2\x90\x9c\xb3\x94\x9b\x3a\ +\x51\x78\x9f\x61\xdf\x3f\x84\xb4\x14\x08\x20\x37\x4e\x7c\x6a\x7c\ +\xcd\xea\xb5\x04\xb0\x00\x58\xf6\xdf\xba\x84\x18\x07\x56\x18\x24\ +\x34\x0c\x8f\x31\x81\x9c\x93\xf3\x12\x2e\x8c\xd4\x7b\x06\x8a\x84\ +\x69\xd1\xfa\x0a\x43\x60\x05\x47\xe0\x5a\xe1\xec\x28\xc1\xf4\x07\ +\x3b\xa7\x30\x94\x36\x3c\x3c\xd7\x85\xea\xa8\x7c\xdb\x35\x72\x0d\ +\xee\x0c\x55\xe6\x19\x88\x05\x30\x41\x71\x54\x77\x13\x9b\x5e\x83\ +\x6e\x64\xde\x62\x21\x0c\xbd\xb1\xb9\xa9\x1f\x51\xf4\x5c\xae\x3d\ +\xb6\x02\xcb\x70\x65\x69\xf3\xc0\x3f\xc8\xb4\x97\xec\xf6\x14\x9a\ +\x50\x7b\x66\xd0\x21\x20\x8f\xd1\x24\x0b\xc0\xa3\x02\xfd\x32\x62\ +\x85\xbb\x7d\x8d\x34\x73\xd0\xc3\xce\xd6\x8e\x8a\x05\x7a\x15\x98\ +\xb8\xce\xf6\x4f\xec\x75\x11\xf4\x47\xf4\xbf\x26\xd4\x1c\xc5\x47\ +\x70\xac\x79\x23\x01\x94\x9f\xa1\xf6\x37\xc6\xd5\xb3\x11\x8e\xcc\ +\xf2\x1e\x90\x9a\xa4\x10\xd2\x6d\xff\xc8\x7f\x46\x58\x87\x42\x28\ +\x12\x40\x19\xdb\xb3\xcc\xcd\x11\xeb\x80\x2e\x51\xbc\x1c\x40\x11\ +\xb3\xc3\x08\xbf\xca\xcf\x11\x9f\xf9\x51\xd6\x61\x28\x14\x8d\x1f\ +\x5b\x39\xc6\x02\x48\x72\xe7\x39\x6d\x79\x03\x22\x12\xe8\x93\xde\ +\x27\x16\x29\x3c\x4b\x08\x32\x43\xea\xe9\xdd\x78\xee\x00\xc4\xe7\ +\x17\xb3\x60\x99\xc1\x23\x06\xb7\x38\x3f\x06\x3c\x07\x56\x46\x68\ +\x7b\x22\x21\x94\x50\xaf\xcd\xb8\x70\xc9\xc0\x98\xbe\x49\x12\x4e\ +\xe7\x05\x6a\x09\xc0\x01\xfb\xe4\x2f\x12\x8b\xa4\x7d\x00\x6d\x43\ +\x6f\x64\xe0\x25\xf0\x21\x23\x8b\x13\x9c\xa0\x61\xf8\x47\x0c\xbf\ +\x13\xc4\x67\x80\x8e\x8b\x10\x0d\x7e\x8a\x43\xad\xcd\x2e\x63\xe8\ +\x00\x00\xf1\x8e\xd0\x53\x15\x42\x7a\xb3\x73\x80\x79\x1b\xcb\x25\ +\x34\xaa\x43\x28\x4d\xee\xeb\xfe\x05\x6c\x6a\xde\xa0\x08\x64\x8e\ +\xc1\xe5\xcb\xa6\x45\xf0\x00\xe6\x26\x31\xd3\x6d\xed\x45\xd2\x88\ +\x55\x9a\x68\x6e\xe3\x91\xc7\x35\x32\x1f\x00\x9a\xe7\x9f\x04\x77\ +\x0e\xec\x28\x12\xd9\x40\xad\xc3\xbc\x8f\xbd\x43\x44\x4b\xc0\x19\ +\xc8\x3b\x44\x91\x16\x9a\x81\x59\x43\xa3\xba\x26\x70\x01\x17\x5b\ +\x5e\xc7\x58\x4e\xcf\x29\x1a\x19\x2e\xe9\x58\x1e\x00\xff\x06\x89\ +\x4d\x73\x92\xd9\x49\xf2\x01\xc9\xff\x24\x84\xee\x78\xfc\x7b\x7a\ +\xaf\x09\x3e\x83\x9d\xf3\x49\x62\x01\x74\x7c\xdb\x32\x7a\x1e\xd1\ +\x0b\x05\x8e\x3c\xbd\x02\xec\x67\xb7\xb1\xa0\xb9\x43\x59\xcf\xe6\ +\x10\xd3\x73\xf7\x4f\x70\xed\x60\x8e\x82\x3c\xa3\x05\x02\x9a\x38\ +\xd9\x8d\xe6\x5c\xd3\x60\x2d\x61\x3c\x09\x87\xc5\xa1\xbb\xfa\x38\ +\xdb\x0e\x0c\x0a\xb6\x32\xd9\xe9\xf8\x08\x84\x57\xd7\x16\xec\xa1\ +\xc1\x8d\x05\xcf\xc8\x14\x56\xe0\x6f\x65\x5f\xfb\x6e\x30\xb6\x0e\ +\x2b\x14\xe6\x24\x93\xc0\xcb\x84\xe4\x3a\x3e\xa3\x38\x8b\x94\xe0\ +\x85\x6d\x0a\x5d\x5f\x89\xb2\xea\x6d\xdc\x15\xd0\xf2\x67\x30\xc9\ +\xdb\xbf\x0e\xf3\x09\x04\x42\x68\xdd\x46\x13\x24\x56\x4e\xb2\x1c\ +\xd0\x18\xf7\x2d\xa3\xd6\x68\x2c\x25\xd8\x46\xed\xa5\x19\x3f\xfb\ +\x6d\x6e\x64\x5f\x01\x38\x83\xc6\x32\x9c\x9c\x8d\xe1\x25\x5e\x03\ +\x9c\x28\xce\x99\x15\x06\x65\x77\x31\x2c\x53\x7c\xbc\x92\x1a\x85\ +\x9c\x59\xb5\x04\x70\x86\x2a\x97\x72\x41\x86\x15\x38\xee\x90\xbb\ +\xf7\x4f\xb7\xfd\x57\xd0\x38\xd3\x73\xfa\x63\x81\xac\x2a\x4e\xbe\ +\xc2\xf4\x18\xa5\x01\xad\xae\x2d\x74\x99\x83\xb3\x2e\xca\x53\x4e\ +\x78\x45\xf9\x80\xc4\x66\xbe\x6d\x13\xd4\x3c\x54\x84\xc9\x31\xc9\ +\xb9\xb7\xa7\xe8\x96\x5b\x85\x4e\x41\xa1\xd3\x38\x70\x3e\xab\x38\ +\x92\xea\x4f\xd3\x6d\x9e\x04\x66\x61\x2e\x4e\xd6\x26\xb0\x02\x53\ +\xd3\x01\x4f\x19\x88\x05\x70\x41\x9a\x34\x70\xde\x74\xc9\xba\x8d\ +\xd7\xed\x2b\x72\x4a\xd8\xee\xed\x15\xb0\x07\xf5\x4b\x55\x5c\xb2\ +\x38\x9e\xaf\x2f\xce\x8f\x5d\x81\x49\x8f\x23\x3c\xf3\xa1\x10\x28\ +\x01\xab\x76\xfa\x0e\xd4\x34\x5f\x54\xc0\x7d\xeb\x1b\xea\x44\x56\ +\x20\x36\x83\xf1\x95\xd3\x27\x68\x39\x1a\xc0\x32\x5a\x27\xd4\x0f\ +\xc6\x5d\x02\xbf\x45\xaf\xc7\x97\x0d\x9d\x97\xa4\xa0\x4e\xd1\xf8\ +\xfc\x3d\x2f\x84\x61\x89\x0f\x21\xad\x35\xa0\x81\xba\xd1\x56\x4d\ +\xcf\x25\xf0\x7b\xe0\x53\x06\x97\xa3\x89\x19\x4c\xca\x6b\x27\xf5\ +\x66\x3b\x85\x12\xc3\xdd\x67\xd9\x42\x0b\x0f\xc2\xb6\x86\xf7\x08\ +\x37\xa2\xf6\xa4\x0e\x6f\xcd\x7f\x1b\x56\x43\x1a\xdc\xa8\x46\x30\ +\x7d\x7e\x05\xf3\x52\x45\xaa\x68\x09\xed\x1c\xc8\xbb\xb6\x4e\x90\ +\xf7\xf3\xd6\x4a\x3e\x64\x8c\x1a\xa1\x43\x90\x20\x23\xeb\x4e\xe0\ +\xa4\xab\xf5\x80\x29\xa2\xf0\x8a\xba\x0f\xee\x11\xea\x25\xbe\x06\ +\xb3\xe3\x82\xcc\xa0\x29\xfb\xef\xd1\xcc\xcf\x0e\x79\xc5\xb8\x81\ +\xa6\xe0\xc3\x0b\x9e\xe4\x6e\x22\x03\x96\x00\xba\x40\x95\x4c\x49\ +\xec\xcc\x0b\xa8\x4c\x7a\xc9\x16\x85\xb4\xfb\xd0\xaa\xaa\xce\xb8\ +\x56\x5d\xee\x98\x20\x65\xc5\xdd\xaa\x90\xaf\xfa\x08\x14\x63\x7b\ +\x11\xba\x1d\x32\x1a\x5f\x2a\xa8\x6e\xcb\xd5\x28\x58\xb1\x40\x09\ +\xdc\x9e\x6e\x79\x79\x16\x28\xa0\xa7\xa8\x46\xee\x01\xff\x0d\x98\ +\x0f\x24\x3f\x77\xe0\x05\x94\x84\xbf\xa1\x0b\x7c\x13\x48\xbc\xbf\ +\x55\x94\xd1\xa7\x30\x27\x51\xbf\x04\x39\xc6\xfb\xd0\x68\x91\xb9\ +\xbe\x93\x8a\xd2\xe3\x76\x40\xee\x1a\xcc\x66\xe0\x25\x69\x2e\xc0\ +\xed\xa2\x75\x36\xc9\xd6\x17\x54\xf1\x54\xc8\x66\x8d\x22\x1c\x4e\ +\x54\x80\xec\xa3\xb5\x3f\xf7\xc6\x08\x97\x0d\x68\xdd\x46\x9d\x9b\ +\x25\xe0\xb9\xee\xb0\x9c\x9d\x9f\x26\x5d\xd5\xe3\x26\xba\xea\x65\ +\x54\x79\x76\xd0\xda\xe6\x25\x65\x1e\xd0\xcb\xd8\x8c\x33\x14\xed\ +\x00\x77\x9a\x0d\x57\xdd\x1e\x5a\xc3\xbf\x81\x46\x66\x9f\xa3\x42\ +\x78\x00\xe7\x27\x50\x3d\x52\x22\x0b\xcd\x5b\x5f\xe7\x68\x24\x15\ +\x9b\x49\x1b\x80\x83\x0b\xbf\xbb\xaa\xc9\x0b\x14\x21\x1c\x7b\x66\ +\xbc\xa9\x33\x1d\xcb\x65\xc5\x2f\x4b\x1e\x6f\x12\x23\x7c\x00\x3c\ +\x04\x0e\xc0\xbd\x0c\xc6\x97\xe3\x7b\x46\xeb\x08\xc4\xcc\x74\x3d\ +\x21\x0f\xd1\x82\x45\xd0\x2b\xef\x65\xdf\xbe\x1f\xb4\x1b\x20\x62\ +\xf7\x8b\x83\xea\xa4\x67\xb0\x53\xe0\xc5\xad\x8f\xc0\x7d\x05\x4c\ +\xc1\xd1\xf7\xd9\xeb\x39\x71\x9e\xb6\xf8\xcc\x8f\x93\x42\x93\x3b\ +\x03\xe7\x27\x53\x2e\x5f\xcf\x5a\x07\xf0\x66\xe8\x7d\xec\x44\x49\ +\x32\xe6\xff\x50\x2e\x0f\xba\x00\xf2\xf3\xbc\xf9\x95\xa6\x5a\x8a\ +\x5c\xb9\xfc\x1d\xcc\xb2\x5e\x1b\xf9\xc7\xd8\x2f\x4c\xac\x92\x7b\ +\x61\x42\x1c\xfa\x82\x85\xf1\x02\x43\x3a\x66\x7b\xcc\x89\x43\x9c\ +\x05\xcf\x88\x43\xdf\x18\xf9\xa5\xd1\x57\xce\xfa\x2b\xa9\x10\xaa\ +\x8c\xff\xc2\x44\x8a\xe8\x4f\x05\x4e\xc8\x46\x5e\x08\x00\xf2\x1e\ +\xfa\xca\x4a\xee\xa5\x04\x5e\xeb\x95\x99\xb4\xad\xe4\x9d\x9f\xb7\ +\x40\xde\x31\x9c\x9f\xb2\xa5\xe5\x3d\xf3\x7f\xc8\xe3\x2b\x9e\x3c\ +\x91\x5a\x59\xa5\x16\x7b\x80\xe0\x77\x82\x71\x7d\x2d\x1b\x7e\x6b\ +\xde\xd3\x4f\x2b\x74\x9e\x2a\x8c\x7e\x69\x6a\xca\x8f\x09\x04\x2f\ +\x2b\x0c\x5e\xbe\x2a\x7a\x39\x6a\x1e\x33\x66\x91\x2d\xcf\x43\x29\ +\xbf\x9b\x15\x62\x44\x86\x93\x23\x9b\xa8\xb6\xf5\x35\xba\xb4\xfc\ +\xef\x1a\x6a\xe6\x1c\x7a\x01\x72\xc1\xe0\xb5\xb9\x19\x40\xa0\x37\ +\x0d\xe5\xc4\x29\x4a\x4a\x64\x7b\xc1\xff\xe4\xf6\x26\x79\x6d\x2e\ +\x28\x97\x4d\xe9\xeb\xfa\x71\x0e\x35\x61\xa7\xfe\xf7\x24\xaa\xc4\ +\x7d\x01\x06\x1d\x54\xa1\xce\x06\x78\xf6\x06\x4e\x93\xed\xc0\x8d\ +\xb8\xa2\x8e\x41\x26\x30\x4a\xcd\x3c\x9e\x3a\x79\x2d\x1b\xbf\x38\ +\x59\x42\xaf\xca\x92\x23\x54\x65\xe0\x5f\xe0\x99\x38\x24\x6b\xf3\ +\xac\x17\x27\x85\x41\xe2\x33\x06\xa3\xb4\x36\x7d\xac\x88\xc7\x37\ +\xf7\xd5\x59\xab\xe1\x0d\x80\x0c\xcf\x6f\x1a\xf3\x09\xa8\x10\xfe\ +\x07\xb4\x0a\xfd\x7e\xcf\x22\x5b\xc2\x00\x00\x00\x00\x49\x45\x4e\ +\x44\xae\x42\x60\x82\ +\x00\x00\x02\x0b\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x01\xbd\x49\x44\x41\x54\x58\x85\xed\ +\x94\x3d\x6b\x14\x51\x18\x85\x9f\x73\xd7\x42\x09\x88\x36\x16\x16\ +\x41\xc1\x5a\x6c\x92\x45\x04\x3b\x59\x91\xe0\xba\x8b\xa6\x51\xc1\ +\x7f\x90\x5f\x20\xa8\xbf\x40\x6c\x52\xda\x58\x28\xb2\x89\x41\x0b\ +\x43\x4a\x91\x24\x6b\xa3\x29\x52\x59\xd8\x28\x58\x25\xa8\x91\x90\ +\xdd\xbd\xc7\x62\x66\xdd\x65\xa3\x9b\x99\xf5\x23\xcd\x3c\x30\xf0\ +\x32\xdc\x39\xe7\xdc\xfb\xbe\x77\xa0\xa0\xa0\xa0\x60\x9f\x51\xb7\ +\x98\x9c\x8b\x1b\x82\x23\xff\xc3\xd4\xb0\xd9\xac\x87\xa3\x00\xe1\ +\x67\x12\xf5\xea\x7f\x4d\xbf\x57\xaf\x68\xe9\x24\xb0\x92\x26\x04\ +\x13\x81\xce\xdf\x78\x6c\xa2\x7b\xfe\xcb\xa9\x57\x12\xa6\x3f\xd9\ +\xe9\x45\x8f\x1d\xfa\xee\x06\xa6\x82\x8d\x51\x94\x30\x7f\x86\xc0\ +\x01\x84\xe1\xe5\xf6\x98\xae\xae\x55\xb4\xb5\xeb\x04\x00\xd6\x2a\ +\xda\xfa\xda\xd2\x65\xe4\x27\x48\x48\x0e\x83\x21\xf3\x60\x23\x43\ +\x48\x24\xfc\xf8\x5b\x5b\xd5\x7e\xf3\x5d\x01\x00\xd6\xa7\xb5\x33\ +\xde\x0a\xd7\x6d\xcf\xa6\xde\xc1\xce\x1f\xc2\x20\x89\x20\xc0\xf6\ +\xec\x78\x3b\xdc\x58\x9f\xd6\xce\xe0\xba\xdf\x0b\xdb\x2a\x3f\x8b\ +\x77\xb1\x6e\x27\x82\x8a\xc2\x99\xda\x61\x24\xe1\x74\x73\xbe\xb7\ +\x5a\x0b\x77\x90\x7e\xf9\xed\x9e\x3b\x2b\xcf\x7b\x06\xfb\x7e\x37\ +\x15\x28\x0e\x37\x77\x10\x52\x22\xae\x99\x95\xba\x1e\x0c\x5b\x9f\ +\xe9\x68\xcb\x0d\xdf\x44\x7e\x08\x94\x86\x85\xe8\x33\xef\x20\xdd\ +\x5a\xad\xe9\xd1\x5e\xda\x99\x7b\x3b\x39\xe7\x29\xe1\xa7\xc0\x41\ +\x92\x9b\x3a\x18\xa2\x3b\xb0\xdb\x46\xd7\x9a\x75\xbd\xc8\xa2\x9b\ +\x6b\xb8\x26\x1a\x3e\x1f\xe4\xe7\xc0\x61\x83\x95\x86\x30\x04\x25\ +\x5a\x5f\x1c\x34\xd5\xbc\xa2\x57\x59\x35\x73\x4f\xf7\xc4\xbc\xcf\ +\x04\x7b\x11\x38\x86\x30\xd1\xdd\x96\x7f\x8e\xd2\xc5\x37\x35\xbd\ +\xcd\xa3\x37\xd2\x1d\x3f\xbb\xe0\x53\xb1\xe3\x25\xe0\x44\xfa\xea\ +\x43\x28\xe9\xc2\x72\x55\xef\xf3\x6a\x8d\xfc\x93\x39\xb7\xe0\xe3\ +\xed\x8e\x3f\x02\xef\x0e\x94\x74\xe9\x75\x55\x9f\x46\xd5\x2a\x28\ +\x28\x28\xd8\x57\x7e\x00\xa4\xf8\xb1\x06\x78\x8b\xc7\xb8\x00\x00\ +\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +\x00\x00\x00\xcf\ +\x89\ +\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49\x48\x44\x52\x00\ +\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7a\x7a\xf4\ +\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0e\xc4\x00\x00\x0e\xc4\ +\x01\x95\x2b\x0e\x1b\x00\x00\x00\x81\x49\x44\x41\x54\x58\x85\xed\ +\xd2\x31\x0e\x82\x50\x10\x84\xe1\x7f\x9f\x77\x20\xe1\x36\xaf\xe0\ +\x08\xf6\x16\x5a\x70\x0b\xc2\x2d\x28\xb0\xb5\xb5\xb5\x31\xe1\x36\ +\x26\xdc\x01\x96\x0a\x88\x98\xd8\xf1\x68\xe6\xeb\x76\xb3\xc9\x4c\ +\xb1\x20\x22\x22\x72\x30\xdb\xce\x31\x56\xa7\x3d\x03\xbb\xae\x1e\ +\x00\xff\x29\x50\x9c\x6f\xd1\x9c\x07\x90\xef\x59\x00\xe8\xc7\xd1\ +\x2f\xef\xe7\xfd\x05\x10\x96\xb5\xd3\x24\x08\x07\xc8\x42\xb0\x76\ +\x1e\xc2\xbf\xcb\x14\xd6\x02\x46\x09\x7c\x12\x64\xf6\x8e\x5d\xd7\ +\xd8\x6f\xc9\x9f\x50\x44\x44\xe4\x70\x13\x6a\x59\x1a\x0e\xce\xfb\ +\x3e\xfc\x00\x00\x00\x00\x49\x45\x4e\x44\xae\x42\x60\x82\ +" + +qt_resource_name = b"\ +\x00\x09\ +\x09\x5f\x97\x13\ +\x00\x71\ +\x00\x73\x00\x73\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x73\ +\x00\x0a\ +\x09\x24\x4d\x25\ +\x00\x71\ +\x00\x64\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\ +\x00\x04\ +\x00\x06\xa8\x8b\ +\x00\x64\ +\x00\x61\x00\x72\x00\x6b\ +\x00\x0d\ +\x0d\x36\x0c\x63\ +\x00\x64\ +\x00\x61\x00\x72\x00\x6b\x00\x73\x00\x74\x00\x79\x00\x6c\x00\x65\x00\x2e\x00\x71\x00\x73\x00\x73\ +\x00\x02\ +\x00\x00\x07\x83\ +\x00\x72\ +\x00\x63\ +\x00\x17\ +\x0e\xfe\x32\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x27\ +\x0d\x0d\x92\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x0c\x09\x66\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x01\x87\xae\x67\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x20\ +\x0e\xfe\x76\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x09\xcb\xcc\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x18\ +\x07\x8b\xec\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\x9d\x97\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x09\x07\x81\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x09\x0d\xa6\xc7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x07\x36\x1b\x47\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0c\xeb\x5f\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x10\ +\x05\x3e\x39\x67\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x00\x4f\x29\xc7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x04\x24\xf6\xe7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x27\ +\x0e\x3d\xd7\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x07\x50\x2b\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\x6c\x22\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x03\xae\x62\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0e\x19\x8b\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x04\xf8\x32\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x02\x75\x51\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x21\ +\x01\xf6\xa2\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x18\ +\x07\x83\xfe\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x01\xe9\xfd\xe7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x08\xc8\x96\xe7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x14\ +\x07\xec\xd1\xc7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x03\x94\x39\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x29\ +\x09\x81\xd3\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x08\x8f\x96\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x17\ +\x07\x06\x3d\xa7\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x0e\x35\xf3\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x05\x35\xb6\x67\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x00\x10\xb9\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0b\x46\x72\x87\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x09\xc8\xa4\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0c\xa5\xc5\x27\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0a\x12\x4a\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x06\x16\x25\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x04\x8d\x48\xc7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x02\xb6\xb5\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x0c\xa4\x6f\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x00\x6c\xa3\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x0e\x0c\xda\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x25\ +\x06\x6c\x47\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x01\x0e\xe5\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0c\xd5\x5a\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x07\x86\x4e\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x00\x68\xca\xe7\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x1a\ +\x0f\x5a\xb4\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x05\x7a\xd3\x67\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x2c\ +\x0c\xa4\x5a\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x24\ +\x05\x94\xa0\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0f\x1e\x9b\x47\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x01\x41\xee\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x14\ +\x00\x2e\x0a\x07\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x03\x9f\x72\x87\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x0f\x35\xfb\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x0f\xd0\x9c\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0e\ +\x08\xfa\xe1\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\x0d\x28\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x0f\xd7\x34\x67\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0c\x24\xec\x07\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x21\ +\x05\x70\x30\x27\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x18\ +\x06\x60\x39\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x0a\xe5\x6c\x07\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1a\ +\x0a\xa0\x05\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0f\x7e\x6f\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0c\x60\x8e\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0b\x59\x6e\x87\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x02\x0d\xa6\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x0e\x31\x43\xa7\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x0c\x24\x39\x47\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x21\ +\x0e\xf1\x37\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1b\ +\x0b\xea\x1b\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x05\x2a\x70\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x20\ +\x09\xd7\x1f\xa7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x01\xc7\x25\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x04\x3c\x09\xc7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x0d\xfd\xa2\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x0c\xe2\x68\x67\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x06\x6d\x9b\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x0f\x80\x4f\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0e\x26\x93\xe7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x06\x14\xad\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x00\x44\xa0\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x07\xa5\xb1\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x04\xce\xfa\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x24\ +\x04\x0b\x8d\x27\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x04\x34\xf0\xc7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0f\xac\xe3\xc7\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x0b\x2d\x81\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x0a\x7a\x87\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x06\xf8\x08\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x01\x40\x2d\xa7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xb5\x9d\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x17\ +\x0f\x18\x45\x87\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x05\xe4\x2d\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x07\xac\x39\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x0a\x19\xf4\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x08\x8a\x08\x27\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x16\ +\x0a\x1a\xd6\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xb1\x94\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x1e\ +\x0c\xd2\xb9\x87\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x08\x21\xa7\xc7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x05\x12\xcf\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x04\x73\x5f\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x08\x2e\xd3\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x00\x06\x3d\xc7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0a\x14\xed\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0d\x33\x2d\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0b\x78\x08\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x07\x14\x6d\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1f\ +\x02\x4f\x6a\xa7\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x01\xf6\xff\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1e\ +\x05\x75\xad\x27\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x09\x2e\xa9\x47\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x05\x76\x1e\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1c\ +\x0c\xfb\xa0\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x01\x75\xcc\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x00\xa7\x99\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x15\ +\x06\x62\x08\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x06\xf2\x1a\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1a\ +\x05\x28\x8d\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x24\ +\x05\xed\xfa\xe7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x02\x48\x15\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0d\ +\x0b\x72\x3d\x07\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xb3\x4c\x27\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x0e\ +\x06\x0c\xe6\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x0f\x79\xa3\xc7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x03\x43\xb9\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1b\ +\x0a\xfb\x2d\x27\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\ +\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x04\x9c\xa4\xa7\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0e\x98\x18\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\ +\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x06\x43\xc6\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x04\x64\xf7\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x05\x11\xe0\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x06\x75\x64\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x2b\ +\x03\xd2\xba\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0f\x9a\xe5\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x29\ +\x09\xe4\xb0\x07\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x25\ +\x08\x07\x7e\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x06\xa7\x5a\x47\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x1c\ +\x08\xb5\x77\x67\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x23\ +\x03\xa5\x91\x47\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x17\ +\x0d\xdf\xcf\xa7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x0b\x23\x21\x67\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x16\ +\x07\x09\xf8\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x02\x38\x25\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x0b\x48\x50\x87\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x27\ +\x0c\xeb\xe5\x67\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x03\xf7\x18\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1f\ +\x0a\xae\x27\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0a\x27\x78\x07\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x13\ +\x0b\x4e\x57\xa7\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x13\ +\x00\xcf\x5c\xc7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\ +\x00\x6e\x00\x67\ +\x00\x1a\ +\x07\x88\x25\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x11\ +\x08\xfc\x49\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x14\ +\x0a\x20\x6e\x07\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x0e\ +\x0d\x4e\x71\x87\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x00\xd6\x25\xc7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1a\ +\x0e\xbc\xc3\x67\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x09\x5e\xb0\x07\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x65\x00\x6e\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x03\x1c\x93\x87\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x09\x2f\xda\x87\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x66\x00\x6f\x00\x63\ +\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x06\x53\x25\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6f\x00\x70\x00\x65\x00\x6e\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0c\x33\x94\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x6c\x00\x65\x00\x66\x00\x74\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x0f\x96\x71\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x10\ +\x00\x55\x62\x07\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x00\x38\x7f\xa7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x0a\xd8\x81\x27\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x00\x6f\x04\x87\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x21\ +\x0a\x51\x5f\x47\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x11\ +\x0b\xda\x30\xa7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\ +\x00\x1c\ +\x08\x3f\xda\x67\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x07\x4b\x88\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x69\x00\x6e\x00\x64\x00\x65\x00\x74\x00\x65\x00\x72\x00\x6d\ +\x00\x69\x00\x6e\x00\x61\x00\x74\x00\x65\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x01\xe0\x4a\x07\ +\x00\x72\ +\x00\x61\x00\x64\x00\x69\x00\x6f\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x22\ +\x04\x9a\x03\x67\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x2a\ +\x0f\xc4\xf7\x07\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x06\x65\x89\xe7\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x04\x90\x0a\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x07\x5b\xb0\x67\ +\x00\x6c\ +\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x01\x15\x51\xe7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x66\ +\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0f\ +\x0f\x2c\x24\xc7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0b\xf3\xab\x27\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x40\ +\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x08\xe1\xf6\xc7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\x00\x64\x00\x5f\ +\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x28\ +\x0f\x63\x53\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\ +\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x15\ +\x0d\x86\xf9\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x40\x00\x32\x00\x78\ +\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x00\xc1\x23\x67\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x67\x00\x72\x00\x69\x00\x70\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x0d\x78\xb6\x87\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x24\ +\x05\x98\x88\x87\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\ +\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x0f\xfb\x22\x07\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x6d\x00\x6f\x00\x76\x00\x65\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\ +\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x40\x00\x32\ +\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x0b\x8a\x15\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0f\xff\xfc\x07\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x26\ +\x0f\x35\xf0\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x76\x00\x65\x00\x72\x00\x74\x00\x69\x00\x63\x00\x61\x00\x6c\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\ +\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1e\ +\x00\x4f\xcb\xe7\ +\x00\x63\ +\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x62\x00\x6f\x00\x78\x00\x5f\x00\x75\x00\x6e\x00\x63\x00\x68\x00\x65\x00\x63\x00\x6b\x00\x65\ +\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0b\x9d\x16\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6d\x00\x6f\x00\x72\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1d\ +\x06\xba\x02\xa7\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x6e\x00\x64\x00\x6f\x00\x63\x00\x6b\x00\x5f\x00\x64\x00\x69\x00\x73\ +\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x19\ +\x07\xb7\xa1\x47\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x63\x00\x6c\x00\x6f\x00\x73\x00\x65\x00\x64\x00\x5f\x00\x70\x00\x72\x00\x65\ +\x00\x73\x00\x73\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x20\ +\x07\x4e\x5a\xc7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x17\ +\x0b\x9d\x4d\x67\ +\x00\x62\ +\x00\x72\x00\x61\x00\x6e\x00\x63\x00\x68\x00\x5f\x00\x6c\x00\x69\x00\x6e\x00\x65\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\ +\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x0c\ +\x0b\xd0\x7a\xe7\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x75\x00\x70\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x1b\ +\x02\xd4\x90\x87\ +\x00\x74\ +\x00\x72\x00\x61\x00\x6e\x00\x73\x00\x70\x00\x61\x00\x72\x00\x65\x00\x6e\x00\x74\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\x00\x62\ +\x00\x6c\x00\x65\x00\x64\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x12\ +\x04\xa2\xb3\x27\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x72\x00\x69\x00\x67\x00\x68\x00\x74\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\ +\x00\x67\ +\x00\x29\ +\x08\x67\xa4\xa7\ +\x00\x74\ +\x00\x6f\x00\x6f\x00\x6c\x00\x62\x00\x61\x00\x72\x00\x5f\x00\x73\x00\x65\x00\x70\x00\x61\x00\x72\x00\x61\x00\x74\x00\x6f\x00\x72\ +\x00\x5f\x00\x68\x00\x6f\x00\x72\x00\x69\x00\x7a\x00\x6f\x00\x6e\x00\x74\x00\x61\x00\x6c\x00\x5f\x00\x64\x00\x69\x00\x73\x00\x61\ +\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x18\ +\x08\xd2\xa3\x27\ +\x00\x62\ +\x00\x61\x00\x73\x00\x65\x00\x5f\x00\x69\x00\x63\x00\x6f\x00\x6e\x00\x5f\x00\x70\x00\x72\x00\x65\x00\x73\x00\x73\x00\x65\x00\x64\ +\x00\x40\x00\x32\x00\x78\x00\x2e\x00\x70\x00\x6e\x00\x67\ +\x00\x14\ +\x06\xe9\x8f\x67\ +\x00\x61\ +\x00\x72\x00\x72\x00\x6f\x00\x77\x00\x5f\x00\x64\x00\x6f\x00\x77\x00\x6e\x00\x5f\x00\x66\x00\x6f\x00\x63\x00\x75\x00\x73\x00\x2e\ +\x00\x70\x00\x6e\x00\x67\ +\x00\x1c\ +\x00\xf3\x26\x27\ +\x00\x77\ +\x00\x69\x00\x6e\x00\x64\x00\x6f\x00\x77\x00\x5f\x00\x6d\x00\x69\x00\x6e\x00\x69\x00\x6d\x00\x69\x00\x7a\x00\x65\x00\x5f\x00\x64\ +\x00\x69\x00\x73\x00\x61\x00\x62\x00\x6c\x00\x65\x00\x64\x00\x2e\x00\x70\x00\x6e\x00\x67\ +" + +qt_resource_struct_v1 = b"\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ +\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ +\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ +\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ +\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ +\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ +\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ +\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ +\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ +\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ +\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ +\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ +\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ +\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ +\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ +\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ +\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ +\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ +\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ +\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ +\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ +\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ +\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ +\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ +\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ +\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ +\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ +\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ +\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ +\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ +\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ +\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ +\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ +\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ +\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ +\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ +\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ +\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ +\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ +\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ +\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ +\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ +\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ +\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ +\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ +\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ +\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ +\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ +\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ +\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ +\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ +\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ +\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ +\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ +\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ +\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ +\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ +\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ +\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ +\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ +\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ +\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ +\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ +\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ +\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ +\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ +\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ +\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ +\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ +\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ +\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ +\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ +\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ +\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ +\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ +\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ +\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ +\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ +\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ +\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ +\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ +\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ +\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ +\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ +\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ +\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ +\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ +\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ +\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ +\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ +\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ +\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ +\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ +\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ +\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ +\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ +\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ +\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ +\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ +\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ +\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ +\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ +\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ +\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ +\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ +\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ +\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ +\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ +\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ +\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ +\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ +\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ +\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ +\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ +\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ +\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ +\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ +\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ +\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ +\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ +\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ +\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ +\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ +\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ +\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ +\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ +\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ +\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ +\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ +\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ +\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ +\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ +\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ +\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ +\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ +\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ +\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ +\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ +\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ +\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ +\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ +\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ +\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ +\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ +\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ +\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ +\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ +\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ +\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ +\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ +\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ +\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ +\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ +\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ +\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ +\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ +\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ +\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ +\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ +\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ +\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ +\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ +\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ +\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ +\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ +\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ +\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ +\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ +\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ +\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ +\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ +\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ +\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ +\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ +\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ +\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ +\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ +\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ +\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ +\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ +\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ +\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ +\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ +\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ +\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ +\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ +\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ +\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ +\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ +\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ +\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ +\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ +\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ +\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ +\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ +\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ +\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ +\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ +\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ +\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ +\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ +\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ +\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ +\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ +\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ +\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ +\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ +\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ +\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ +\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ +\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ +\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ +" + +qt_resource_struct_v2 = b"\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x02\x00\x00\x00\x01\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x18\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd5\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x03\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\x04\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x60\x00\x02\x00\x00\x00\xd0\x00\x00\x00\x05\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x18\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x3b\x76\ +\x00\x00\x01\x81\x15\x91\x87\xb0\ +\x00\x00\x07\xe8\x00\x00\x00\x00\x00\x01\x00\x00\x68\x2b\ +\x00\x00\x01\x81\x15\x91\x88\x41\ +\x00\x00\x0d\x0e\x00\x00\x00\x00\x00\x01\x00\x00\xb6\x47\ +\x00\x00\x01\x81\x15\x91\x87\x94\ +\x00\x00\x25\xea\x00\x00\x00\x00\x00\x01\x00\x01\xd7\xaf\ +\x00\x00\x01\x81\x15\x91\x86\x7f\ +\x00\x00\x13\x62\x00\x00\x00\x00\x00\x01\x00\x01\x04\xe1\ +\x00\x00\x01\x81\x15\x91\x84\xf5\ +\x00\x00\x03\x52\x00\x00\x00\x00\x00\x01\x00\x00\x41\xeb\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x2c\x2c\x00\x00\x00\x00\x00\x01\x00\x02\x1c\x30\ +\x00\x00\x01\x81\x15\x91\x85\x87\ +\x00\x00\x25\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xd4\xe1\ +\x00\x00\x01\x81\x15\x91\x86\x4c\ +\x00\x00\x0b\x4e\x00\x00\x00\x00\x00\x01\x00\x00\x97\x7a\ +\x00\x00\x01\x81\x15\x91\x88\x2e\ +\x00\x00\x09\xec\x00\x00\x00\x00\x00\x01\x00\x00\x88\x43\ +\x00\x00\x01\x81\x15\x91\x85\xba\ +\x00\x00\x26\x62\x00\x00\x00\x00\x00\x01\x00\x01\xe3\xbc\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x1a\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x60\x51\ +\x00\x00\x01\x81\x15\x91\x87\xe7\ +\x00\x00\x2a\x68\x00\x00\x00\x00\x00\x01\x00\x02\x0e\x25\ +\x00\x00\x01\x81\x15\x91\x88\x51\ +\x00\x00\x23\x4e\x00\x00\x00\x00\x00\x01\x00\x01\xb5\x50\ +\x00\x00\x01\x81\x15\x91\x88\x3d\ +\x00\x00\x24\x2c\x00\x00\x00\x00\x00\x01\x00\x01\xc5\x39\ +\x00\x00\x01\x81\x15\x91\x85\x07\ +\x00\x00\x2e\xd4\x00\x00\x00\x00\x00\x01\x00\x02\x3b\x4e\ +\x00\x00\x01\x81\x15\x91\x86\x7c\ +\x00\x00\x0a\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x90\xe9\ +\x00\x00\x01\x81\x15\x91\x85\xd5\ +\x00\x00\x29\x0c\x00\x00\x00\x00\x00\x01\x00\x01\xfc\x4d\ +\x00\x00\x01\x81\x15\x91\x88\x67\ +\x00\x00\x15\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x17\x04\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x0c\xc4\x00\x00\x00\x00\x00\x01\x00\x00\xb5\xb7\ +\x00\x00\x01\x81\x15\x91\x86\x10\ +\x00\x00\x1a\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x5e\xc4\ +\x00\x00\x01\x81\x15\x91\x85\x6a\ +\x00\x00\x01\x32\x00\x00\x00\x00\x00\x01\x00\x00\x23\x58\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x11\xb4\x00\x00\x00\x00\x00\x01\x00\x00\xe4\x33\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x27\x86\x00\x00\x00\x00\x00\x01\x00\x01\xef\xdb\ +\x00\x00\x01\x81\x15\x91\x85\xda\ +\x00\x00\x06\x00\x00\x00\x00\x00\x00\x01\x00\x00\x56\xae\ +\x00\x00\x01\x81\x15\x91\x87\x84\ +\x00\x00\x05\x82\x00\x00\x00\x00\x00\x01\x00\x00\x55\x3f\ +\x00\x00\x01\x81\x15\x91\x88\x17\ +\x00\x00\x19\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x54\x5c\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x10\x24\x00\x00\x00\x00\x00\x01\x00\x00\xda\x1f\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x21\x90\x00\x00\x00\x00\x00\x01\x00\x01\xa5\xba\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x1c\x4c\x00\x00\x00\x00\x00\x01\x00\x01\x67\xc0\ +\x00\x00\x01\x81\x15\x91\x88\x57\ +\x00\x00\x19\x7a\x00\x00\x00\x00\x00\x01\x00\x01\x4b\x73\ +\x00\x00\x01\x81\x15\x91\x87\xaa\ +\x00\x00\x05\x44\x00\x00\x00\x00\x00\x01\x00\x00\x52\x7b\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x09\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x83\x3b\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x2d\xb2\x00\x00\x00\x00\x00\x01\x00\x02\x26\xe6\ +\x00\x00\x01\x81\x15\x91\x88\x33\ +\x00\x00\x24\xc2\x00\x00\x00\x00\x00\x01\x00\x01\xcb\xce\ +\x00\x00\x01\x81\x15\x91\x86\x4c\ +\x00\x00\x1d\x2a\x00\x00\x00\x00\x00\x01\x00\x01\x73\x06\ +\x00\x00\x01\x81\x15\x91\x87\xfb\ +\x00\x00\x06\x88\x00\x00\x00\x00\x00\x01\x00\x00\x5e\x2e\ +\x00\x00\x01\x81\x15\x91\x87\x75\ +\x00\x00\x0d\x3c\x00\x00\x00\x00\x00\x01\x00\x00\xc0\xd9\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x20\xb0\x00\x00\x00\x00\x00\x01\x00\x01\x9f\xd7\ +\x00\x00\x01\x81\x15\x91\x85\xf9\ +\x00\x00\x04\xa6\x00\x00\x00\x00\x00\x01\x00\x00\x48\xc0\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x1f\x0a\x00\x00\x00\x00\x00\x01\x00\x01\x8b\xeb\ +\x00\x00\x01\x81\x15\x91\x88\x13\ +\x00\x00\x22\x62\x00\x00\x00\x00\x00\x01\x00\x01\xaa\xcc\ +\x00\x00\x01\x81\x15\x91\x87\x4e\ +\x00\x00\x14\x00\x00\x00\x00\x00\x00\x01\x00\x01\x0a\xcd\ +\x00\x00\x01\x81\x15\x91\x85\xf9\ +\x00\x00\x03\x8a\x00\x00\x00\x00\x00\x01\x00\x00\x44\x0a\ +\x00\x00\x01\x81\x15\x91\x86\x2b\ +\x00\x00\x14\x4e\x00\x00\x00\x00\x00\x01\x00\x01\x0b\x6c\ +\x00\x00\x01\x81\x15\x91\x87\x88\ +\x00\x00\x11\xee\x00\x00\x00\x00\x00\x01\x00\x00\xe8\xc1\ +\x00\x00\x01\x81\x15\x91\x87\xb5\ +\x00\x00\x1e\x52\x00\x00\x00\x00\x00\x01\x00\x01\x87\xf8\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x17\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x37\x5c\ +\x00\x00\x01\x81\x15\x91\x88\x7c\ +\x00\x00\x09\x2a\x00\x00\x00\x00\x00\x01\x00\x00\x81\xe7\ +\x00\x00\x01\x81\x15\x91\x88\x62\ +\x00\x00\x28\x9e\x00\x00\x00\x00\x00\x01\x00\x01\xf9\x30\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x27\xc4\x00\x00\x00\x00\x00\x01\x00\x01\xf3\xf4\ +\x00\x00\x01\x81\x15\x91\x87\x69\ +\x00\x00\x1d\xb2\x00\x00\x00\x00\x00\x01\x00\x01\x78\x31\ +\x00\x00\x01\x81\x15\x91\x84\xbb\ +\x00\x00\x2d\xee\x00\x00\x00\x00\x00\x01\x00\x02\x27\x5f\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x16\xf2\x00\x00\x00\x00\x00\x01\x00\x01\x2f\x6e\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x1c\xa2\x00\x00\x00\x00\x00\x01\x00\x01\x6f\x8a\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x15\x72\x00\x00\x00\x00\x00\x01\x00\x01\x1a\xf8\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x13\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x07\x9f\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x05\x10\x00\x00\x00\x00\x00\x01\x00\x00\x4e\x5a\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x1e\x8c\x00\x00\x00\x00\x00\x01\x00\x01\x88\xc9\ +\x00\x00\x01\x81\x15\x91\x85\x52\ +\x00\x00\x17\x9a\x00\x00\x00\x00\x00\x01\x00\x01\x34\x70\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x1b\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x64\xdd\ +\x00\x00\x01\x81\x15\x91\x84\xcb\ +\x00\x00\x11\x46\x00\x00\x00\x00\x00\x01\x00\x00\xe1\xd4\ +\x00\x00\x01\x81\x15\x91\x85\xa9\ +\x00\x00\x07\xae\x00\x00\x00\x00\x00\x01\x00\x00\x67\xb2\ +\x00\x00\x01\x81\x15\x91\x88\x39\ +\x00\x00\x03\x2c\x00\x00\x00\x00\x00\x01\x00\x00\x35\x11\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x0e\xa4\x00\x00\x00\x00\x00\x01\x00\x00\xc8\x4d\ +\x00\x00\x01\x81\x15\x91\x85\xf9\ +\x00\x00\x19\xe6\x00\x00\x00\x00\x00\x01\x00\x01\x55\x2d\ +\x00\x00\x01\x81\x15\x91\x87\xc3\ +\x00\x00\x1a\x62\x00\x00\x00\x00\x00\x01\x00\x01\x5a\x91\ +\x00\x00\x01\x81\x15\x91\x86\x6b\ +\x00\x00\x0b\xb2\x00\x00\x00\x00\x00\x01\x00\x00\xa2\x57\ +\x00\x00\x01\x81\x15\x91\x86\xdd\ +\x00\x00\x0c\x42\x00\x00\x00\x00\x00\x01\x00\x00\xb0\x58\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x2a\xce\x00\x00\x00\x00\x00\x01\x00\x02\x13\x3d\ +\x00\x00\x01\x81\x15\x91\x87\xec\ +\x00\x00\x15\xd0\x00\x00\x00\x00\x00\x01\x00\x01\x20\x5a\ +\x00\x00\x01\x81\x15\x91\x86\xdd\ +\x00\x00\x1b\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x66\x8b\ +\x00\x00\x01\x81\x15\x91\x87\xd5\ +\x00\x00\x1c\xcc\x00\x00\x00\x00\x00\x01\x00\x01\x70\x7c\ +\x00\x00\x01\x81\x15\x91\x84\x48\ +\x00\x00\x13\x30\x00\x00\x00\x00\x00\x01\x00\x01\x02\x9f\ +\x00\x00\x01\x81\x15\x91\x84\x87\ +\x00\x00\x09\x06\x00\x00\x00\x00\x00\x01\x00\x00\x81\x3d\ +\x00\x00\x01\x81\x15\x91\x85\x1a\ +\x00\x00\x1e\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x83\x9c\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x25\x26\x00\x00\x00\x00\x00\x01\x00\x01\xce\x35\ +\x00\x00\x01\x81\x15\x91\x85\x2e\ +\x00\x00\x0e\xec\x00\x00\x00\x00\x00\x01\x00\x00\xc8\xeb\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x1b\x48\x00\x00\x00\x00\x00\x01\x00\x01\x61\x28\ +\x00\x00\x01\x81\x15\x91\x85\x34\ +\x00\x00\x28\x68\x00\x00\x00\x00\x00\x01\x00\x01\xf8\x28\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x0a\x56\x00\x00\x00\x00\x00\x01\x00\x00\x8d\x02\ +\x00\x00\x01\x81\x15\x91\x87\x61\ +\x00\x00\x12\x90\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x83\ +\x00\x00\x01\x81\x15\x91\x87\x23\ +\x00\x00\x1e\xc6\x00\x00\x00\x00\x00\x01\x00\x01\x8b\x5c\ +\x00\x00\x01\x81\x15\x91\x86\x13\ +\x00\x00\x20\x48\x00\x00\x00\x00\x00\x01\x00\x01\x92\x17\ +\x00\x00\x01\x81\x15\x91\x88\x4e\ +\x00\x00\x2c\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x1e\x6c\ +\x00\x00\x01\x81\x15\x91\x88\x75\ +\x00\x00\x2e\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x39\x3f\ +\x00\x00\x01\x81\x15\x91\x84\x65\ +\x00\x00\x1b\x78\x00\x00\x00\x00\x00\x01\x00\x01\x62\xb8\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x15\x1e\x00\x00\x00\x00\x00\x01\x00\x01\x16\x5c\ +\x00\x00\x01\x81\x15\x91\x85\x27\ +\x00\x00\x07\x3a\x00\x00\x00\x00\x00\x01\x00\x00\x63\xe4\ +\x00\x00\x01\x81\x15\x91\x86\x4c\ +\x00\x00\x21\x5e\x00\x00\x00\x00\x00\x01\x00\x01\xa4\x6f\ +\x00\x00\x01\x81\x15\x91\x88\x5e\ +\x00\x00\x19\x2e\x00\x00\x00\x00\x00\x01\x00\x01\x47\xcd\ +\x00\x00\x01\x81\x15\x91\x87\x5d\ +\x00\x00\x02\xc0\x00\x00\x00\x00\x00\x01\x00\x00\x33\xb8\ +\x00\x00\x01\x81\x15\x91\x85\xbd\ +\x00\x00\x27\x34\x00\x00\x00\x00\x00\x01\x00\x01\xeb\xec\ +\x00\x00\x01\x81\x15\x91\x87\x58\ +\x00\x00\x2d\x1a\x00\x00\x00\x00\x00\x01\x00\x02\x23\xaf\ +\x00\x00\x01\x81\x15\x91\x86\x1f\ +\x00\x00\x04\x30\x00\x00\x00\x00\x00\x01\x00\x00\x45\xdc\ +\x00\x00\x01\x81\x15\x91\x88\x6b\ +\x00\x00\x28\xce\x00\x00\x00\x00\x00\x01\x00\x01\xfb\x51\ +\x00\x00\x01\x81\x15\x91\x87\x90\ +\x00\x00\x05\xca\x00\x00\x00\x00\x00\x01\x00\x00\x56\x03\ +\x00\x00\x01\x81\x15\x91\x85\x1d\ +\x00\x00\x0b\x18\x00\x00\x00\x00\x00\x01\x00\x00\x96\xef\ +\x00\x00\x01\x81\x15\x91\x85\x0a\ +\x00\x00\x23\x7a\x00\x00\x00\x00\x00\x01\x00\x01\xbb\xb9\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x01\xda\x00\x00\x00\x00\x00\x01\x00\x00\x2c\x7b\ +\x00\x00\x01\x81\x15\x91\x85\x31\ +\x00\x00\x13\x90\x00\x00\x00\x00\x00\x01\x00\x01\x05\x7a\ +\x00\x00\x01\x81\x15\x91\x84\x8c\ +\x00\x00\x15\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x23\x96\ +\x00\x00\x01\x81\x15\x91\x85\xe9\ +\x00\x00\x2c\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x22\x0c\ +\x00\x00\x01\x81\x15\x91\x84\xdb\ +\x00\x00\x06\x5a\x00\x00\x00\x00\x00\x01\x00\x00\x5b\xa0\ +\x00\x00\x01\x81\x15\x91\x85\x46\ +\x00\x00\x1f\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x91\x3d\ +\x00\x00\x01\x81\x15\x91\x87\xe3\ +\x00\x00\x17\x5e\x00\x00\x00\x00\x00\x01\x00\x01\x31\x04\ +\x00\x00\x01\x81\x15\x91\x87\x1b\ +\x00\x00\x18\x0e\x00\x00\x00\x00\x00\x01\x00\x01\x3a\xe9\ +\x00\x00\x01\x81\x15\x91\x87\x7d\ +\x00\x00\x26\xf6\x00\x00\x00\x00\x00\x01\x00\x01\xea\x65\ +\x00\x00\x01\x81\x15\x91\x85\x7d\ +\x00\x00\x2e\x18\x00\x00\x00\x00\x00\x01\x00\x02\x2b\xca\ +\x00\x00\x01\x81\x15\x91\x86\x28\ +\x00\x00\x16\x76\x00\x00\x00\x00\x00\x01\x00\x01\x2b\x29\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x07\x12\x00\x00\x00\x00\x00\x01\x00\x00\x5f\xdf\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x20\x72\x00\x00\x00\x00\x00\x01\x00\x01\x94\xdf\ +\x00\x00\x01\x81\x15\x91\x87\xa3\ +\x00\x00\x06\x2e\x00\x00\x00\x00\x00\x01\x00\x00\x57\xa8\ +\x00\x00\x01\x81\x15\x91\x85\xda\ +\x00\x00\x2e\x70\x00\x00\x00\x00\x00\x01\x00\x02\x2c\x65\ +\x00\x00\x01\x81\x15\x91\x86\xdd\ +\x00\x00\x29\xa2\x00\x00\x00\x00\x00\x01\x00\x02\x04\xaf\ +\x00\x00\x01\x81\x15\x91\x87\x48\ +\x00\x00\x0d\xe0\x00\x00\x00\x00\x00\x01\x00\x00\xc4\x8b\ +\x00\x00\x01\x81\x15\x91\x84\x7c\ +\x00\x00\x23\xb4\x00\x00\x00\x00\x00\x01\x00\x01\xbc\xc3\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x02\x44\x00\x00\x00\x00\x00\x01\x00\x00\x2f\xce\ +\x00\x00\x01\x81\x15\x91\x85\x4f\ +\x00\x00\x02\x84\x00\x00\x00\x00\x00\x01\x00\x00\x32\xad\ +\x00\x00\x01\x81\x15\x91\x87\x0c\ +\x00\x00\x1a\x28\x00\x00\x00\x00\x00\x01\x00\x01\x56\x61\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x24\xf2\x00\x00\x00\x00\x00\x01\x00\x01\xcc\x3a\ +\x00\x00\x01\x81\x15\x91\x86\x8f\ +\x00\x00\x24\x8a\x00\x00\x00\x00\x00\x01\x00\x01\xca\xfe\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x06\xba\x00\x00\x00\x00\x00\x01\x00\x00\x5e\xbb\ +\x00\x00\x01\x81\x15\x91\x88\x0d\ +\x00\x00\x08\x60\x00\x00\x00\x00\x00\x01\x00\x00\x72\x4a\ +\x00\x00\x01\x81\x15\x91\x85\x93\ +\x00\x00\x01\xb2\x00\x00\x00\x00\x00\x01\x00\x00\x2a\x72\ +\x00\x00\x01\x81\x15\x91\x86\x7f\ +\x00\x00\x11\x6e\x00\x00\x00\x00\x00\x01\x00\x00\xe2\x5d\ +\x00\x00\x01\x81\x15\x91\x85\x54\ +\x00\x00\x1f\xa0\x00\x00\x00\x00\x00\x01\x00\x01\x90\x75\ +\x00\x00\x01\x81\x15\x91\x88\x2b\ +\x00\x00\x08\xd6\x00\x00\x00\x00\x00\x01\x00\x00\x7f\xa1\ +\x00\x00\x01\x81\x15\x91\x86\x6b\ +\x00\x00\x18\x8a\x00\x00\x00\x00\x00\x01\x00\x01\x43\xc9\ +\x00\x00\x01\x81\x15\x91\x88\x5b\ +\x00\x00\x16\x3a\x00\x00\x00\x00\x00\x01\x00\x01\x24\x34\ +\x00\x00\x01\x81\x15\x91\x88\x4a\ +\x00\x00\x16\xc0\x00\x00\x00\x00\x00\x01\x00\x01\x2d\x33\ +\x00\x00\x01\x81\x15\x91\x84\x72\ +\x00\x00\x23\xdc\x00\x00\x00\x00\x00\x01\x00\x01\xc1\x39\ +\x00\x00\x01\x81\x15\x91\x88\x70\ +\x00\x00\x22\xea\x00\x00\x00\x00\x00\x01\x00\x01\xb1\x82\ +\x00\x00\x01\x81\x15\x91\x87\x66\ +\x00\x00\x26\x86\x00\x00\x00\x00\x00\x01\x00\x01\xe5\x72\ +\x00\x00\x01\x81\x15\x91\x87\x72\ +\x00\x00\x14\xec\x00\x00\x00\x00\x00\x01\x00\x01\x13\x80\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x0f\x4a\x00\x00\x00\x00\x00\x01\x00\x00\xce\xcb\ +\x00\x00\x01\x81\x15\x91\x86\x8f\ +\x00\x00\x22\xa6\x00\x00\x00\x00\x00\x01\x00\x01\xaf\xf7\ +\x00\x00\x01\x81\x15\x91\x85\x74\ +\x00\x00\x26\x22\x00\x00\x00\x00\x00\x01\x00\x01\xd8\x81\ +\x00\x00\x01\x81\x15\x91\x87\x99\ +\x00\x00\x0f\x22\x00\x00\x00\x00\x00\x01\x00\x00\xc9\xdd\ +\x00\x00\x01\x81\x15\x91\x85\xc6\ +\x00\x00\x1d\x76\x00\x00\x00\x00\x00\x01\x00\x01\x74\x2a\ +\x00\x00\x01\x81\x15\x91\x85\xe9\ +\x00\x00\x21\x30\x00\x00\x00\x00\x00\x01\x00\x01\xa2\x41\ +\x00\x00\x01\x81\x15\x91\x84\xac\ +\x00\x00\x14\xbe\x00\x00\x00\x00\x00\x01\x00\x01\x11\x55\ +\x00\x00\x01\x81\x15\x91\x84\x84\ +\x00\x00\x08\x26\x00\x00\x00\x00\x00\x01\x00\x00\x6e\xe4\ +\x00\x00\x01\x81\x15\x91\x88\x79\ +\x00\x00\x21\xca\x00\x00\x00\x00\x00\x01\x00\x01\xa6\xad\ +\x00\x00\x01\x81\x15\x91\x87\x6e\ +\x00\x00\x23\x22\x00\x00\x00\x00\x00\x01\x00\x01\xb4\xd4\ +\x00\x00\x01\x81\x15\x91\x85\x8b\ +\x00\x00\x0f\xec\x00\x00\x00\x00\x00\x01\x00\x00\xd6\x48\ +\x00\x00\x01\x81\x15\x91\x85\xda\ +\x00\x00\x1c\x82\x00\x00\x00\x00\x00\x01\x00\x01\x6a\x9e\ +\x00\x00\x01\x81\x15\x91\x84\xac\ +\x00\x00\x18\xfe\x00\x00\x00\x00\x00\x01\x00\x01\x47\x43\ +\x00\x00\x01\x81\x15\x91\x85\x0d\ +\x00\x00\x2b\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x15\x4a\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x2c\x6e\x00\x00\x00\x00\x00\x01\x00\x02\x1d\xc7\ +\x00\x00\x01\x81\x15\x91\x85\x2a\ +\x00\x00\x2d\x60\x00\x00\x00\x00\x00\x01\x00\x02\x24\x4a\ +\x00\x00\x01\x81\x15\x91\x85\x17\ +\x00\x00\x2d\x94\x00\x00\x00\x00\x00\x01\x00\x02\x24\xd5\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x26\xce\x00\x00\x00\x00\x00\x01\x00\x01\xe8\xd4\ +\x00\x00\x01\x81\x15\x91\x84\xcb\ +\x00\x00\x11\x0a\x00\x00\x00\x00\x00\x01\x00\x00\xe0\xfe\ +\x00\x00\x01\x81\x15\x91\x86\x7f\ +\x00\x00\x29\x6e\x00\x00\x00\x00\x00\x01\x00\x01\xff\xc4\ +\x00\x00\x01\x81\x15\x91\x87\x3e\ +\x00\x00\x00\xf2\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x99\ +\x00\x00\x01\x81\x15\x91\x87\x53\ +\x00\x00\x10\x96\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x7f\ +\x00\x00\x01\x81\x15\x91\x84\xbb\ +\x00\x00\x0e\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xc7\xd2\ +\x00\x00\x01\x81\x15\x91\x85\x9c\ +\x00\x00\x25\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xcf\xcd\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x0f\xbc\x00\x00\x00\x00\x00\x01\x00\x00\xd4\x1f\ +\x00\x00\x01\x81\x15\x91\x84\x9c\ +\x00\x00\x0b\xe4\x00\x00\x00\x00\x00\x01\x00\x00\xaf\x31\ +\x00\x00\x01\x81\x15\x91\x88\x09\ +\x00\x00\x09\xa8\x00\x00\x00\x00\x00\x01\x00\x00\x87\xb4\ +\x00\x00\x01\x81\x15\x91\x87\x79\ +\x00\x00\x08\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x72\xc7\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x17\x1c\x00\x00\x00\x00\x00\x01\x00\x01\x30\x76\ +\x00\x00\x01\x81\x15\x91\x87\x80\ +\x00\x00\x0a\xde\x00\x00\x00\x00\x00\x01\x00\x00\x95\xf5\ +\x00\x00\x01\x81\x15\x91\x87\x8c\ +\x00\x00\x12\x6c\x00\x00\x00\x00\x00\x01\x00\x00\xf6\x17\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x02\xf8\x00\x00\x00\x00\x00\x01\x00\x00\x34\x42\ +\x00\x00\x01\x81\x15\x91\x86\xfc\ +\x00\x00\x22\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xaa\x03\ +\x00\x00\x01\x81\x15\x91\x88\x1f\ +\x00\x00\x1a\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x5b\x5d\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x0e\x02\x00\x00\x00\x00\x00\x01\x00\x00\xc6\xbd\ +\x00\x00\x01\x81\x15\x91\x84\xea\ +\x00\x00\x00\x9e\x00\x00\x00\x00\x00\x01\x00\x00\x1f\x0d\ +\x00\x00\x01\x81\x15\x91\x86\x2d\ +\x00\x00\x18\xc4\x00\x00\x00\x00\x00\x01\x00\x01\x46\xb8\ +\x00\x00\x01\x81\x15\x91\x85\xb1\ +\x00\x00\x24\x0a\x00\x00\x00\x00\x00\x01\x00\x01\xc4\x9e\ +\x00\x00\x01\x81\x15\x91\x84\xdb\ +\x00\x00\x04\x72\x00\x00\x00\x00\x00\x01\x00\x00\x47\x31\ +\x00\x00\x01\x81\x15\x91\x84\xdb\ +\x00\x00\x2a\xa4\x00\x00\x00\x00\x00\x01\x00\x02\x11\x25\ +\x00\x00\x01\x81\x15\x91\x84\xac\ +\x00\x00\x2a\x38\x00\x00\x00\x00\x00\x01\x00\x02\x0a\x43\ +\x00\x00\x01\x81\x15\x91\x86\xcd\ +\x00\x00\x02\x10\x00\x00\x00\x00\x00\x01\x00\x00\x2e\x25\ +\x00\x00\x01\x81\x15\x91\x85\x3e\ +\x00\x00\x20\xfc\x00\x00\x00\x00\x00\x01\x00\x01\xa0\x76\ +\x00\x00\x01\x81\x15\x91\x86\x6b\ +\x00\x00\x12\x30\x00\x00\x00\x00\x00\x01\x00\x00\xf1\x9c\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x0a\x20\x00\x00\x00\x00\x00\x01\x00\x00\x88\xcc\ +\x00\x00\x01\x81\x15\x91\x86\xbe\ +\x00\x00\x04\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x4a\x76\ +\x00\x00\x01\x81\x15\x91\x86\x9e\ +\x00\x00\x12\xf8\x00\x00\x00\x00\x00\x01\x00\x01\x02\x0e\ +\x00\x00\x01\x81\x15\x91\x86\x0d\ +\x00\x00\x10\x60\x00\x00\x00\x00\x00\x01\x00\x00\xdb\x13\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x07\x6e\x00\x00\x00\x00\x00\x01\x00\x00\x64\x50\ +\x00\x00\x01\x81\x15\x91\x86\xec\ +\x00\x00\x03\xdc\x00\x00\x00\x00\x00\x01\x00\x00\x44\xa3\ +\x00\x00\x01\x81\x15\x91\x87\xd0\ +\x00\x00\x1d\xe4\x00\x00\x00\x00\x00\x01\x00\x01\x7d\x1d\ +\x00\x00\x01\x81\x15\x91\x88\x46\ +\x00\x00\x24\x50\x00\x00\x00\x00\x00\x01\x00\x01\xc5\xc2\ +\x00\x00\x01\x81\x15\x91\x85\xc9\ +\x00\x00\x10\xc2\x00\x00\x00\x00\x00\x01\x00\x00\xe0\x6b\ +\x00\x00\x01\x81\x15\x91\x86\x16\ +\x00\x00\x00\x6a\x00\x00\x00\x00\x00\x01\x00\x00\x1a\xaa\ +\x00\x00\x01\x81\x15\x91\x86\xae\ +\x00\x00\x01\x6c\x00\x00\x00\x00\x00\x01\x00\x00\x25\x38\ +\x00\x00\x01\x81\x15\x91\x87\x43\ +\x00\x00\x15\x9c\x00\x00\x00\x00\x00\x01\x00\x01\x1e\x29\ +\x00\x00\x01\x81\x15\x91\x84\x81\ +\x00\x00\x0c\x90\x00\x00\x00\x00\x00\x01\x00\x00\xb0\xe3\ +\x00\x00\x01\x81\x15\x91\x85\xcd\ +\x00\x00\x29\x4a\x00\x00\x00\x00\x00\x01\x00\x01\xfd\x9e\ +\x00\x00\x01\x81\x15\x91\x84\x8c\ +\x00\x00\x2b\xda\x00\x00\x00\x00\x00\x01\x00\x02\x1b\xa2\ +\x00\x00\x01\x81\x15\x91\x86\x3d\ +\x00\x00\x0d\x70\x00\x00\x00\x00\x00\x01\x00\x00\xc3\x1b\ +\x00\x00\x01\x81\x15\x91\x84\xfd\ +\x00\x00\x0b\x78\x00\x00\x00\x00\x00\x01\x00\x00\x97\xf3\ +\x00\x00\x01\x81\x15\x91\x87\x9f\ +\x00\x00\x29\xe2\x00\x00\x00\x00\x00\x01\x00\x02\x09\xa8\ +\x00\x00\x01\x81\x15\x91\x86\x2d\ +\x00\x00\x1c\xee\x00\x00\x00\x00\x00\x01\x00\x01\x72\x8a\ +\x00\x00\x01\x81\x15\x91\x85\x9f\ +\x00\x00\x0f\x84\x00\x00\x00\x00\x00\x01\x00\x00\xd0\xe7\ +\x00\x00\x01\x81\x15\x91\x86\x5c\ +\x00\x00\x12\xc6\x00\x00\x00\x00\x00\x01\x00\x00\xf9\x9e\ +\x00\x00\x01\x81\x15\x91\x87\xa7\ +\x00\x00\x25\x82\x00\x00\x00\x00\x00\x01\x00\x01\xd4\x54\ +\x00\x00\x01\x81\x15\x91\x86\x2d\ +\x00\x00\x1f\x66\x00\x00\x00\x00\x00\x01\x00\x01\x8d\x15\ +\x00\x00\x01\x81\x15\x91\x87\x32\ +\x00\x00\x14\x8e\x00\x00\x00\x00\x00\x01\x00\x01\x0c\x69\ +\x00\x00\x01\x81\x15\x91\x84\xbb\ +\x00\x00\x28\x0e\x00\x00\x00\x00\x00\x01\x00\x01\xf7\x5c\ +\x00\x00\x01\x81\x15\x91\x88\x1b\ +\x00\x00\x0d\xa2\x00\x00\x00\x00\x00\x01\x00\x00\xc3\xb7\ +\x00\x00\x01\x81\x15\x91\x87\xdd\ +\x00\x00\x0e\x36\x00\x00\x00\x00\x00\x01\x00\x00\xc7\x59\ +\x00\x00\x01\x81\x15\x91\x88\x36\ +\x00\x00\x2b\x1c\x00\x00\x00\x00\x00\x01\x00\x02\x14\x12\ +\x00\x00\x01\x81\x15\x91\x87\xd9\ +\x00\x00\x2b\xa6\x00\x00\x00\x00\x00\x01\x00\x02\x19\x7c\ +\x00\x00\x01\x81\x15\x91\x84\x53\ +\x00\x00\x00\x32\x00\x02\x00\x00\x00\x01\x00\x00\x00\xd6\ +\x00\x00\x00\x00\x00\x00\x00\x00\ +\x00\x00\x00\x40\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\ +\x00\x00\x01\x81\x15\x91\x89\x29\ +" + +qt_version = [int(v) for v in QtCore.qVersion().split('.')] +if qt_version < [5, 8, 0]: + rcc_version = 1 + qt_resource_struct = qt_resource_struct_v1 +else: + rcc_version = 2 + qt_resource_struct = qt_resource_struct_v2 + +def qInitResources(): + QtCore.qRegisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + +def qCleanupResources(): + QtCore.qUnregisterResourceData(rcc_version, qt_resource_struct, qt_resource_name, qt_resource_data) + +qInitResources() diff --git a/3rdParty/qdarkstyle/dark/main.scss b/3rdParty/qdarkstyle/dark/main.scss index 44409319fb..dc40bc521c 100644 --- a/3rdParty/qdarkstyle/dark/main.scss +++ b/3rdParty/qdarkstyle/dark/main.scss @@ -1,4 +1,4 @@ -/* Light Style - QDarkStyleSheet ------------------------------------------ */ - -@import '_variables'; -@import '../qss/_styles'; +/* Light Style - QDarkStyleSheet ------------------------------------------ */ + +@import '_variables'; +@import '../qss/_styles'; diff --git a/3rdParty/qdarkstyle/dark/palette.py b/3rdParty/qdarkstyle/dark/palette.py index 791e1a759e..23a1d1f837 100644 --- a/3rdParty/qdarkstyle/dark/palette.py +++ b/3rdParty/qdarkstyle/dark/palette.py @@ -1,36 +1,36 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""QDarkStyle default dark palette.""" - -# Local imports -from qdarkstyle.colorsystem import Blue, Gray -from qdarkstyle.palette import Palette - - -class DarkPalette(Palette): - """Dark palette variables.""" - - # Identifier - ID = 'dark' - - # Color - COLOR_BACKGROUND_1 = Gray.B10 - COLOR_BACKGROUND_2 = Gray.B20 - COLOR_BACKGROUND_3 = Gray.B30 - COLOR_BACKGROUND_4 = Gray.B40 - COLOR_BACKGROUND_5 = Gray.B50 - COLOR_BACKGROUND_6 = Gray.B60 - - COLOR_TEXT_1 = Gray.B130 - COLOR_TEXT_2 = Gray.B110 - COLOR_TEXT_3 = Gray.B90 - COLOR_TEXT_4 = Gray.B80 - - COLOR_ACCENT_1 = Blue.B20 - COLOR_ACCENT_2 = Blue.B40 - COLOR_ACCENT_3 = Blue.B50 - COLOR_ACCENT_4 = Blue.B70 - COLOR_ACCENT_5 = Blue.B80 - - OPACITY_TOOLTIP = 230 +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""QDarkStyle default dark palette.""" + +# Local imports +from qdarkstyle.colorsystem import Blue, Gray +from qdarkstyle.palette import Palette + + +class DarkPalette(Palette): + """Dark palette variables.""" + + # Identifier + ID = 'dark' + + # Color + COLOR_BACKGROUND_1 = Gray.B10 + COLOR_BACKGROUND_2 = Gray.B20 + COLOR_BACKGROUND_3 = Gray.B30 + COLOR_BACKGROUND_4 = Gray.B40 + COLOR_BACKGROUND_5 = Gray.B50 + COLOR_BACKGROUND_6 = Gray.B60 + + COLOR_TEXT_1 = Gray.B130 + COLOR_TEXT_2 = Gray.B110 + COLOR_TEXT_3 = Gray.B90 + COLOR_TEXT_4 = Gray.B80 + + COLOR_ACCENT_1 = Blue.B20 + COLOR_ACCENT_2 = Blue.B40 + COLOR_ACCENT_3 = Blue.B50 + COLOR_ACCENT_4 = Blue.B70 + COLOR_ACCENT_5 = Blue.B80 + + OPACITY_TOOLTIP = 230 diff --git a/3rdParty/qdarkstyle/dark/rc/.keep b/3rdParty/qdarkstyle/dark/rc/.keep index 56f3b36e27..8d1c8b69c3 100644 --- a/3rdParty/qdarkstyle/dark/rc/.keep +++ b/3rdParty/qdarkstyle/dark/rc/.keep @@ -1 +1 @@ - + diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down.png b/3rdParty/qdarkstyle/dark/rc/arrow_down.png index aa9938ab44..87279d6e9c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_down@2x.png index c1f33469ae..6dc434db41 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled.png b/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled.png index 972df9cd16..31f9385b38 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled@2x.png index b0fb4ad11d..3800bb21a3 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down_focus.png b/3rdParty/qdarkstyle/dark/rc/arrow_down_focus.png index 22df2c525c..998bbaea70 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down_focus.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_down_focus@2x.png index 06b80be4bc..b2ff36f493 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed.png b/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed.png index 50f41cc6f8..3e9ce7601d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed@2x.png index ef20f2cb07..c441dc4923 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_down_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left.png b/3rdParty/qdarkstyle/dark/rc/arrow_left.png index c8981363f4..ebd3fceb96 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_left@2x.png index 129d2e13a8..b22b881038 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled.png b/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled.png index 79b1f05651..bb078aeede 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled@2x.png index 144fdb5f8f..e271b40a49 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left_focus.png b/3rdParty/qdarkstyle/dark/rc/arrow_left_focus.png index ef02849947..1e6a29e948 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left_focus.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_left_focus@2x.png index ca821dcac5..318313e084 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed.png b/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed.png index c723d3bff7..b2d30e9e64 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed@2x.png index f0bcb5229b..65131dffb6 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_left_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right.png b/3rdParty/qdarkstyle/dark/rc/arrow_right.png index 86bc42aeb1..82afe29bd0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_right@2x.png index 4526704b8f..cf95c5d117 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled.png b/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled.png index 88da1f980b..9abba0972c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled@2x.png index 5351587e3d..facc83894f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right_focus.png b/3rdParty/qdarkstyle/dark/rc/arrow_right_focus.png index 92271a8ed9..7f158c5dc8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right_focus.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_right_focus@2x.png index d6c31bdda9..01d556cfb8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed.png b/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed.png index 22902cf4fc..ed869d1087 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed@2x.png index f6181eb64d..8e1dd43383 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_right_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up.png b/3rdParty/qdarkstyle/dark/rc/arrow_up.png index 5ade740805..1a8bc6592c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_up@2x.png index 65276abff9..40cc869a83 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled.png b/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled.png index 48054a8ae9..bd077de21b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled@2x.png index e99960594e..97bc54fc29 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up_focus.png b/3rdParty/qdarkstyle/dark/rc/arrow_up_focus.png index 567ec8bdf2..80b3bc7585 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up_focus.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_up_focus@2x.png index f6998104b5..dac3ad3498 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed.png b/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed.png index 2233201069..e52df55de3 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed@2x.png index 9954cf5194..74e0feb96b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/arrow_up_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon.png b/3rdParty/qdarkstyle/dark/rc/base_icon.png index bb00857a4e..1f0f20e283 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon.png and b/3rdParty/qdarkstyle/dark/rc/base_icon.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon@2x.png b/3rdParty/qdarkstyle/dark/rc/base_icon@2x.png index bc4ab78a28..f2904029c8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon@2x.png and b/3rdParty/qdarkstyle/dark/rc/base_icon@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon_disabled.png b/3rdParty/qdarkstyle/dark/rc/base_icon_disabled.png index bb00857a4e..1f0f20e283 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon_disabled.png and b/3rdParty/qdarkstyle/dark/rc/base_icon_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/base_icon_disabled@2x.png index bc4ab78a28..f2904029c8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/base_icon_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon_focus.png b/3rdParty/qdarkstyle/dark/rc/base_icon_focus.png index bb00857a4e..1f0f20e283 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon_focus.png and b/3rdParty/qdarkstyle/dark/rc/base_icon_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/base_icon_focus@2x.png index bc4ab78a28..f2904029c8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/base_icon_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon_pressed.png b/3rdParty/qdarkstyle/dark/rc/base_icon_pressed.png index bb00857a4e..1f0f20e283 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon_pressed.png and b/3rdParty/qdarkstyle/dark/rc/base_icon_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/base_icon_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/base_icon_pressed@2x.png index bc4ab78a28..f2904029c8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/base_icon_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/base_icon_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed.png b/3rdParty/qdarkstyle/dark/rc/branch_closed.png index 2ef5957f4f..dbeb5c8143 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_closed@2x.png index 564ba0e977..14c2068822 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled.png b/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled.png index 165fae29ba..3a00a92432 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled@2x.png index 421e8e094f..f7322d2673 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed_focus.png b/3rdParty/qdarkstyle/dark/rc/branch_closed_focus.png index ccc249a59a..25fd7dc110 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed_focus.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_closed_focus@2x.png index 88dd0a62b1..b0cc342592 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed.png b/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed.png index 2aae68a0a1..bcb5edb82c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed@2x.png index 3849a7ff02..c25897a04b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_closed_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end.png b/3rdParty/qdarkstyle/dark/rc/branch_end.png index 85de228d8f..b48df90b9e 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end.png and b/3rdParty/qdarkstyle/dark/rc/branch_end.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_end@2x.png index 9f99c24a95..16448cbda0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_end@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end_disabled.png b/3rdParty/qdarkstyle/dark/rc/branch_end_disabled.png index bb4344c785..34a594ed22 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end_disabled.png and b/3rdParty/qdarkstyle/dark/rc/branch_end_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_end_disabled@2x.png index 8feb46d464..9264ec92a5 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_end_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end_focus.png b/3rdParty/qdarkstyle/dark/rc/branch_end_focus.png index ff713cf5f0..ff839d9204 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end_focus.png and b/3rdParty/qdarkstyle/dark/rc/branch_end_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_end_focus@2x.png index 0bd0e4ba33..8932092948 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_end_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end_pressed.png b/3rdParty/qdarkstyle/dark/rc/branch_end_pressed.png index 2020162f23..a3f5f001b0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end_pressed.png and b/3rdParty/qdarkstyle/dark/rc/branch_end_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_end_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_end_pressed@2x.png index 2a5c4fabf6..fd1e02624d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_end_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_end_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line.png b/3rdParty/qdarkstyle/dark/rc/branch_line.png index 803e6a4a1a..2267fdef7d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line.png and b/3rdParty/qdarkstyle/dark/rc/branch_line.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_line@2x.png index 4236fe58d8..a197facbe0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_line@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line_disabled.png b/3rdParty/qdarkstyle/dark/rc/branch_line_disabled.png index 9c8c47b3d0..a1ecc4f17b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line_disabled.png and b/3rdParty/qdarkstyle/dark/rc/branch_line_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_line_disabled@2x.png index 9b868f2a5c..5bfc0ed0b5 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_line_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line_focus.png b/3rdParty/qdarkstyle/dark/rc/branch_line_focus.png index c2ab3e19e6..e707feceba 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line_focus.png and b/3rdParty/qdarkstyle/dark/rc/branch_line_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_line_focus@2x.png index 512ee13a25..56f27889af 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_line_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line_pressed.png b/3rdParty/qdarkstyle/dark/rc/branch_line_pressed.png index 3ca15c5d0b..f1b3fd0752 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line_pressed.png and b/3rdParty/qdarkstyle/dark/rc/branch_line_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_line_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_line_pressed@2x.png index 3685531020..7226ba66da 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_line_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_line_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more.png b/3rdParty/qdarkstyle/dark/rc/branch_more.png index a664c2a543..d38a502cfb 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more.png and b/3rdParty/qdarkstyle/dark/rc/branch_more.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_more@2x.png index 1e7b08a5cb..672bbdeba9 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_more@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more_disabled.png b/3rdParty/qdarkstyle/dark/rc/branch_more_disabled.png index 29d99a63e8..bf77c39fbf 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more_disabled.png and b/3rdParty/qdarkstyle/dark/rc/branch_more_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_more_disabled@2x.png index aba830362c..520826614c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_more_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more_focus.png b/3rdParty/qdarkstyle/dark/rc/branch_more_focus.png index 20a6f27b83..23f878d0f0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more_focus.png and b/3rdParty/qdarkstyle/dark/rc/branch_more_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_more_focus@2x.png index 6f42eea846..d824d76427 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_more_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more_pressed.png b/3rdParty/qdarkstyle/dark/rc/branch_more_pressed.png index 4f4d9fb917..5b3a422241 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more_pressed.png and b/3rdParty/qdarkstyle/dark/rc/branch_more_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_more_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_more_pressed@2x.png index 5f18f83415..2d8e59a33a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_more_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_more_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open.png b/3rdParty/qdarkstyle/dark/rc/branch_open.png index 1ff7b48d19..e049a1f37d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open.png and b/3rdParty/qdarkstyle/dark/rc/branch_open.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_open@2x.png index aad66f8bad..69a4a585ec 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_open@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open_disabled.png b/3rdParty/qdarkstyle/dark/rc/branch_open_disabled.png index 8328e84d72..0b1973dcae 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open_disabled.png and b/3rdParty/qdarkstyle/dark/rc/branch_open_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_open_disabled@2x.png index d8d0faecb1..4c0394b776 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_open_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open_focus.png b/3rdParty/qdarkstyle/dark/rc/branch_open_focus.png index 711ce0979f..6c51a6088c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open_focus.png and b/3rdParty/qdarkstyle/dark/rc/branch_open_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_open_focus@2x.png index b38e17a33c..d58b67d360 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_open_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open_pressed.png b/3rdParty/qdarkstyle/dark/rc/branch_open_pressed.png index 441c27344e..eb6f9a9e5d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open_pressed.png and b/3rdParty/qdarkstyle/dark/rc/branch_open_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/branch_open_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/branch_open_pressed@2x.png index 0e43e8b733..0960a85794 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/branch_open_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/branch_open_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked.png index f860ca78b7..613b45803b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked@2x.png index 48773d75fa..ec2e4b74c6 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled.png index e3cb2f127c..4c6e223fc2 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled@2x.png index 0c8c28a245..a723d55d9c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus.png index 58982ce87b..73df6faa11 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus@2x.png index ba33ba4fbc..767a5b3d1a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed.png index f104bb2403..2e4c42ea73 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed@2x.png index bb972d68f3..9476ca2c54 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_checked_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate.png index 85672bfb7f..927e3093aa 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate@2x.png index 2bb245284e..f35aa0a42f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled.png index 181625a000..fc023ebf64 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled@2x.png index 0d32c78f36..1ed8c1dc42 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus.png index d7b19f61ad..8c1730e4c7 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus@2x.png index d6403ca424..2e090722fd 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed.png index 37f46ca3d5..b604d45047 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed@2x.png index aa7493edc6..1c5ecb4761 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_indeterminate_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked.png index 172b90ac00..2d5b9b39b9 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked@2x.png index f54b080a73..8900d7717e 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled.png index 066185ee7f..886f86ac57 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled@2x.png index 9c80ad75a5..7422229333 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus.png index 366b868dee..fbdd9f7b1d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus@2x.png index 4ab217356e..cae411371f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed.png index d9a0bf71c7..fca67c1426 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed@2x.png index 9e2b0515e7..4fe1c58333 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/checkbox_unchecked_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal.png index 8774e3d018..09f4a33ae7 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal@2x.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal@2x.png index cb11d1d2b6..830173f8da 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled.png index 941f14a385..f88c365c76 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled@2x.png index 972fa08004..ad644bf54a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus.png index 221fd4607f..16c5c6530e 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus@2x.png index 7e6505cae3..2fea7539a5 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed.png index 9f9113323f..c50e692aff 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed@2x.png index 465680c3b0..bab19fd214 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_horizontal_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical.png b/3rdParty/qdarkstyle/dark/rc/line_vertical.png index 5529f413e4..738189241b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical@2x.png b/3rdParty/qdarkstyle/dark/rc/line_vertical@2x.png index 6a334e7468..c697df4eb6 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled.png b/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled.png index c7c4c8959f..b4c5b092c0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled@2x.png index b052de522e..4fa751c013 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical_focus.png b/3rdParty/qdarkstyle/dark/rc/line_vertical_focus.png index 36baa09362..169e28b82c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical_focus.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/line_vertical_focus@2x.png index 24a2b771c3..937e55f8ab 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed.png b/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed.png index 60e3574460..91323b8c2c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed@2x.png index c9494051cd..cb21943013 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/line_vertical_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked.png b/3rdParty/qdarkstyle/dark/rc/radio_checked.png index 274afe1e29..05623e804b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_checked@2x.png index 8c16b38cc5..d65fd19b34 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled.png b/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled.png index 49df43922d..bbded28d68 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled@2x.png index a9ffd40ced..d18e834506 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked_focus.png b/3rdParty/qdarkstyle/dark/rc/radio_checked_focus.png index 4bd472e160..423bc6918e 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked_focus.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_checked_focus@2x.png index aed5e0c94d..1e5942e2c9 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed.png b/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed.png index ebb323b8c5..ca4cc04d2c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed@2x.png index ffe0fd8517..aeaf3c7a4a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_checked_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked.png index 93365a85e7..509f0a9654 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked@2x.png index 8237e4062a..3b7aa254ab 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled.png index 7ddff642df..12790ffc3a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled@2x.png index 4de5d0d2d8..139323ff0f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus.png index e62b996b1c..38dfe541d0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus@2x.png index eaf7bc26b9..a953c96c42 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed.png index 8aaa343e88..5968345324 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed@2x.png index ba4f83b91e..745ccbef17 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/radio_unchecked_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal.png index 54993316db..6b58ee35c5 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal@2x.png index 143b62ec55..7956a79cbd 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled.png index 568b0fbe18..eb6e926b47 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled@2x.png index 4d15f1478b..355cb1caa5 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus.png index cdb96bfb96..64519b70f8 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus@2x.png index 23e06a0152..63d9b37402 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed.png index 9ce6f8d89d..5dcd893e20 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed@2x.png index 4d8e53e8e7..2c375c3e03 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_horizontal_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical.png index ade2a20b95..5bbdbc529d 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical@2x.png index 453d7b71f9..eb508b0d78 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled.png index 37453ac258..2b44bba7d4 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled@2x.png index cca8f6d961..32a7092c88 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus.png index b548771816..761059678e 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus@2x.png index d4dd49dec9..173598b922 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed.png index 768ebaf4ca..f27d21bd22 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed@2x.png index 2f170ffd8f..a62e4f1098 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_move_vertical_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal.png index ecf2ab7d0c..751d71c7dd 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal@2x.png index ac2b343264..2e25a99b01 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled.png index f8796f9e6b..9698fcb399 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled@2x.png index 1d9f20421c..3defe2bb96 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus.png index b592e61c16..200660ebf2 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus@2x.png index a593a7e761..f30d89fa82 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed.png index a806257e06..b0fe8e4d42 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed@2x.png index e1e8e3c148..f7124a3119 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_horizontal_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical.png index a894304e69..d8c04abe56 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical@2x.png index 2f66e93d34..539120d9db 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled.png index 48b2657f50..d3acf0c626 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled@2x.png index a2173c5eef..996ba2ac8a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus.png index e31c694b05..1fed8ce0ec 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus@2x.png index ce743cc862..8332cb14dc 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed.png index 4ee7aaaabd..fe354e7978 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed@2x.png index d8bf93bf65..7b3ae743a6 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/toolbar_separator_vertical_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent.png b/3rdParty/qdarkstyle/dark/rc/transparent.png index 67753617fe..6f7b6b5a88 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent.png and b/3rdParty/qdarkstyle/dark/rc/transparent.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent@2x.png b/3rdParty/qdarkstyle/dark/rc/transparent@2x.png index 4012944b58..d545e5c9e7 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent@2x.png and b/3rdParty/qdarkstyle/dark/rc/transparent@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent_disabled.png b/3rdParty/qdarkstyle/dark/rc/transparent_disabled.png index 67753617fe..6f7b6b5a88 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent_disabled.png and b/3rdParty/qdarkstyle/dark/rc/transparent_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/transparent_disabled@2x.png index 4012944b58..d545e5c9e7 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/transparent_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent_focus.png b/3rdParty/qdarkstyle/dark/rc/transparent_focus.png index 67753617fe..6f7b6b5a88 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent_focus.png and b/3rdParty/qdarkstyle/dark/rc/transparent_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/transparent_focus@2x.png index 4012944b58..d545e5c9e7 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/transparent_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent_pressed.png b/3rdParty/qdarkstyle/dark/rc/transparent_pressed.png index 67753617fe..6f7b6b5a88 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent_pressed.png and b/3rdParty/qdarkstyle/dark/rc/transparent_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/transparent_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/transparent_pressed@2x.png index 4012944b58..d545e5c9e7 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/transparent_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/transparent_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close.png b/3rdParty/qdarkstyle/dark/rc/window_close.png index 2b36479382..76783dfa9f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close.png and b/3rdParty/qdarkstyle/dark/rc/window_close.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close@2x.png b/3rdParty/qdarkstyle/dark/rc/window_close@2x.png index c6bec556f1..8c98b49c4c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_close@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close_disabled.png b/3rdParty/qdarkstyle/dark/rc/window_close_disabled.png index 46de804b88..0dc359b7fc 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close_disabled.png and b/3rdParty/qdarkstyle/dark/rc/window_close_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/window_close_disabled@2x.png index 8e4cd15d86..41e9b07a35 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_close_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close_focus.png b/3rdParty/qdarkstyle/dark/rc/window_close_focus.png index bb7d8c5110..7caae50f5a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close_focus.png and b/3rdParty/qdarkstyle/dark/rc/window_close_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/window_close_focus@2x.png index 692ce24f2f..54aab65094 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_close_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close_pressed.png b/3rdParty/qdarkstyle/dark/rc/window_close_pressed.png index 53ae7f38e0..b487005c00 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close_pressed.png and b/3rdParty/qdarkstyle/dark/rc/window_close_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_close_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/window_close_pressed@2x.png index e02b12292d..706ab5fa60 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_close_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_close_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip.png b/3rdParty/qdarkstyle/dark/rc/window_grip.png index fc2f6dffcb..23c703eec2 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip.png and b/3rdParty/qdarkstyle/dark/rc/window_grip.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip@2x.png b/3rdParty/qdarkstyle/dark/rc/window_grip@2x.png index 6a8e86cef2..770ee52c35 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_grip@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip_disabled.png b/3rdParty/qdarkstyle/dark/rc/window_grip_disabled.png index 97c0e0f90b..57093550b1 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip_disabled.png and b/3rdParty/qdarkstyle/dark/rc/window_grip_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/window_grip_disabled@2x.png index 7a3d8de6de..f2d08f96be 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_grip_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip_focus.png b/3rdParty/qdarkstyle/dark/rc/window_grip_focus.png index 99b27c9cec..cb8ddb328f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip_focus.png and b/3rdParty/qdarkstyle/dark/rc/window_grip_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/window_grip_focus@2x.png index 833cb90a9a..f921b6835e 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_grip_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip_pressed.png b/3rdParty/qdarkstyle/dark/rc/window_grip_pressed.png index afea9749e8..521a9afc9a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip_pressed.png and b/3rdParty/qdarkstyle/dark/rc/window_grip_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_grip_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/window_grip_pressed@2x.png index c1c1a0e4b1..de0a315a46 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_grip_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_grip_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize.png b/3rdParty/qdarkstyle/dark/rc/window_minimize.png index 64404308d3..3ffe0db8b6 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize@2x.png b/3rdParty/qdarkstyle/dark/rc/window_minimize@2x.png index 0e25540417..f5c5623575 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled.png b/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled.png index cc51ed0eed..6a95e43c30 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled@2x.png index c1676469f9..1900b91f2f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize_focus.png b/3rdParty/qdarkstyle/dark/rc/window_minimize_focus.png index 1dcd083c00..652cd6f48a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize_focus.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/window_minimize_focus@2x.png index 2a4c868e09..9aadef4a1f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed.png b/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed.png index 0bb532126c..5e5f849bbf 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed@2x.png index 5a515c806b..6cb9c4528f 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_minimize_pressed@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock.png b/3rdParty/qdarkstyle/dark/rc/window_undock.png index 3bd2863274..e20c1efb3c 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock.png and b/3rdParty/qdarkstyle/dark/rc/window_undock.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock@2x.png b/3rdParty/qdarkstyle/dark/rc/window_undock@2x.png index 44c147feb9..24169d325b 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_undock@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock_disabled.png b/3rdParty/qdarkstyle/dark/rc/window_undock_disabled.png index 6a609492b3..ab2aff13a0 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock_disabled.png and b/3rdParty/qdarkstyle/dark/rc/window_undock_disabled.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock_disabled@2x.png b/3rdParty/qdarkstyle/dark/rc/window_undock_disabled@2x.png index c2e1b8fa72..52f8b9da7a 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock_disabled@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_undock_disabled@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock_focus.png b/3rdParty/qdarkstyle/dark/rc/window_undock_focus.png index d6eebbdc27..5ad3fe0c97 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock_focus.png and b/3rdParty/qdarkstyle/dark/rc/window_undock_focus.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock_focus@2x.png b/3rdParty/qdarkstyle/dark/rc/window_undock_focus@2x.png index 1aef06053d..245adfc1eb 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock_focus@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_undock_focus@2x.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock_pressed.png b/3rdParty/qdarkstyle/dark/rc/window_undock_pressed.png index 8b6beb19e9..e8ffdd40ac 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock_pressed.png and b/3rdParty/qdarkstyle/dark/rc/window_undock_pressed.png differ diff --git a/3rdParty/qdarkstyle/dark/rc/window_undock_pressed@2x.png b/3rdParty/qdarkstyle/dark/rc/window_undock_pressed@2x.png index 677ded4251..8e17ff95c2 100644 Binary files a/3rdParty/qdarkstyle/dark/rc/window_undock_pressed@2x.png and b/3rdParty/qdarkstyle/dark/rc/window_undock_pressed@2x.png differ diff --git a/3rdPartyBinaries/Sleepy.dll b/3rdPartyBinaries/Sleepy.dll index 3d7b601fed..ea8b824725 100644 Binary files a/3rdPartyBinaries/Sleepy.dll and b/3rdPartyBinaries/Sleepy.dll differ diff --git a/3rdPartyBinaries/dpp.dll b/3rdPartyBinaries/dpp.dll index c53f63be66..8e619a76f6 100644 Binary files a/3rdPartyBinaries/dpp.dll and b/3rdPartyBinaries/dpp.dll differ diff --git a/3rdPartyBinaries/dpp.lib b/3rdPartyBinaries/dpp.lib index d83210bd47..4ca9d57ac4 100644 Binary files a/3rdPartyBinaries/dpp.lib and b/3rdPartyBinaries/dpp.lib differ diff --git a/3rdPartyBinaries/dppd.lib b/3rdPartyBinaries/dppd.lib index 4a41c40394..5c22f5ba69 100644 Binary files a/3rdPartyBinaries/dppd.lib and b/3rdPartyBinaries/dppd.lib differ diff --git a/3rdPartyBinaries/libcrypto-1_1-x64.dll b/3rdPartyBinaries/libcrypto-1_1-x64.dll index 8a06122706..f4665d576b 100644 Binary files a/3rdPartyBinaries/libcrypto-1_1-x64.dll and b/3rdPartyBinaries/libcrypto-1_1-x64.dll differ diff --git a/3rdPartyBinaries/libdpp_macos_arm64.a b/3rdPartyBinaries/libdpp_macos_arm64.a index f845ff0c4e..710f209597 100644 Binary files a/3rdPartyBinaries/libdpp_macos_arm64.a and b/3rdPartyBinaries/libdpp_macos_arm64.a differ diff --git a/3rdPartyBinaries/libsodium.dll b/3rdPartyBinaries/libsodium.dll index 0fc90b1231..4c559ebdbe 100644 Binary files a/3rdPartyBinaries/libsodium.dll and b/3rdPartyBinaries/libsodium.dll differ diff --git a/3rdPartyBinaries/libssl-1_1-x64.dll b/3rdPartyBinaries/libssl-1_1-x64.dll index 139496c89f..898c8e5024 100644 Binary files a/3rdPartyBinaries/libssl-1_1-x64.dll and b/3rdPartyBinaries/libssl-1_1-x64.dll differ diff --git a/3rdPartyBinaries/onnxruntime.dll b/3rdPartyBinaries/onnxruntime.dll index 8fd1f9cdfd..87f984e43e 100644 Binary files a/3rdPartyBinaries/onnxruntime.dll and b/3rdPartyBinaries/onnxruntime.dll differ diff --git a/3rdPartyBinaries/onnxruntime_providers_shared.dll b/3rdPartyBinaries/onnxruntime_providers_shared.dll index f38ede414b..d13df9c56d 100644 Binary files a/3rdPartyBinaries/onnxruntime_providers_shared.dll and b/3rdPartyBinaries/onnxruntime_providers_shared.dll differ diff --git a/3rdPartyBinaries/opencv_world4110.dll b/3rdPartyBinaries/opencv_world4110.dll index 122c350f87..79d59bcf55 100644 Binary files a/3rdPartyBinaries/opencv_world4110.dll and b/3rdPartyBinaries/opencv_world4110.dll differ diff --git a/3rdPartyBinaries/opencv_world4110.lib b/3rdPartyBinaries/opencv_world4110.lib index 468311ef53..0f89595082 100644 Binary files a/3rdPartyBinaries/opencv_world4110.lib and b/3rdPartyBinaries/opencv_world4110.lib differ diff --git a/3rdPartyBinaries/opencv_world4110d.lib b/3rdPartyBinaries/opencv_world4110d.lib index bcb3c4ae6f..09d15277f8 100644 Binary files a/3rdPartyBinaries/opencv_world4110d.lib and b/3rdPartyBinaries/opencv_world4110d.lib differ diff --git a/3rdPartyBinaries/opencv_world4110d.zip b/3rdPartyBinaries/opencv_world4110d.zip index a2df06ec3a..6c76e8e0f8 100644 Binary files a/3rdPartyBinaries/opencv_world4110d.zip and b/3rdPartyBinaries/opencv_world4110d.zip differ diff --git a/3rdPartyBinaries/opus.dll b/3rdPartyBinaries/opus.dll index e23428e3f1..cf6a8333ee 100644 Binary files a/3rdPartyBinaries/opus.dll and b/3rdPartyBinaries/opus.dll differ diff --git a/3rdPartyBinaries/tesseractPA.dll b/3rdPartyBinaries/tesseractPA.dll index fc9ce8b981..72c42da6d7 100644 Binary files a/3rdPartyBinaries/tesseractPA.dll and b/3rdPartyBinaries/tesseractPA.dll differ diff --git a/3rdPartyBinaries/zlib1.dll b/3rdPartyBinaries/zlib1.dll index 897a1fe665..82ca3b2668 100644 Binary files a/3rdPartyBinaries/zlib1.dll and b/3rdPartyBinaries/zlib1.dll differ diff --git a/Cleanup.cmd b/Cleanup.cmd index 9bee38f830..6bd5ef10df 100644 --- a/Cleanup.cmd +++ b/Cleanup.cmd @@ -1,24 +1,24 @@ - -rd /s /q "..\build-SerialPrograms*" - -del 3rdPartyBinaries\opencv_world460d.dll - -cd %~dp0\SerialPrograms -@call Cleanup.cmd - - - -rd /s /q "..\build-HexGenerator-Desktop_Qt_5_12_12_MinGW_32_bit-Debug" -rd /s /q "..\build-HexGenerator-Desktop_Qt_5_12_12_MinGW_32_bit-Release" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_5_12_12_MSVC2017_64bit-Release" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_5_12_12_MSVC2017_64bit-RelWithDebInfo" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_1_MSVC2019_64bit-Debug" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_1_MSVC2019_64bit-RelWithDebInfo" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_2_MSVC2019_64bit-Debug" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_2_MSVC2019_64bit-RelWithDebInfo" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_4_0_MSVC2019_64bit-Debug" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_4_0_MSVC2019_64bit-RelWithDebInfo" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_2_MSVC2019_64bit-Debug" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_2_MSVC2019_64bit-RelWithDebInfo" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-Debug" -rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo" + +rd /s /q "..\build-SerialPrograms*" + +del 3rdPartyBinaries\opencv_world460d.dll + +cd %~dp0\SerialPrograms +@call Cleanup.cmd + + + +rd /s /q "..\build-HexGenerator-Desktop_Qt_5_12_12_MinGW_32_bit-Debug" +rd /s /q "..\build-HexGenerator-Desktop_Qt_5_12_12_MinGW_32_bit-Release" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_5_12_12_MSVC2017_64bit-Release" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_5_12_12_MSVC2017_64bit-RelWithDebInfo" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_1_MSVC2019_64bit-Debug" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_1_MSVC2019_64bit-RelWithDebInfo" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_2_MSVC2019_64bit-Debug" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_3_2_MSVC2019_64bit-RelWithDebInfo" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_4_0_MSVC2019_64bit-Debug" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_4_0_MSVC2019_64bit-RelWithDebInfo" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_2_MSVC2019_64bit-Debug" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_2_MSVC2019_64bit-RelWithDebInfo" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-Debug" +rd /s /q "..\build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo" diff --git a/ClientSource/Connection/BotBase.cpp b/ClientSource/Connection/BotBase.cpp index bac4024420..2c178579f0 100644 --- a/ClientSource/Connection/BotBase.cpp +++ b/ClientSource/Connection/BotBase.cpp @@ -1,18 +1,18 @@ -/* Pokemon Automation Bot-Base Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "BotBaseMessage.h" -#include "BotBase.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -} +/* Pokemon Automation Bot-Base Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "BotBaseMessage.h" +#include "BotBase.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +} diff --git a/ClientSource/Connection/BotBase.h b/ClientSource/Connection/BotBase.h index f1ea3734d1..a0390548ec 100644 --- a/ClientSource/Connection/BotBase.h +++ b/ClientSource/Connection/BotBase.h @@ -1,83 +1,83 @@ -/* Pokemon Automation Bot-Base Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AbstractBotBase_H -#define PokemonAutomation_AbstractBotBase_H - -#include -#include "Common/Cpp/CancellableScope.h" - -namespace PokemonAutomation{ - -class Logger; -struct BotBaseMessage; -class BotBaseRequest; -class BotBaseControllerContext; - - - -class BotBaseController{ -public: - using ContextType = BotBaseControllerContext; - - enum class State{ - RUNNING, - STOPPING, - STOPPED, -// ERROR, - }; - -public: - virtual ~BotBaseController() = default; - virtual void stop(std::string error_message = "") = 0; - - virtual Logger& logger() = 0; - virtual State state() const = 0; - virtual size_t queue_limit() const = 0; - - virtual void notify_all() = 0; - - // Waits for all pending requests to finish. - virtual void wait_for_all_requests(const Cancellable* cancelled = nullptr) = 0; - - // Stop all pending commands. This wipes the command queue on both sides - // and stops any currently executing command. - virtual void stop_all_commands() = 0; - - // Tell the device that the next command should replace the command queue. - // - // So once the next command is issued, it will stop all ongoing commands - // and run the new command instead. - // - // Once this function is called, all commands before it are no longer - // guaranteed to finish even if no command interrupts it. - virtual void next_command_interrupt() = 0; - -public: - virtual bool try_issue_request( - const BotBaseRequest& request, - const Cancellable* cancelled = nullptr - ) = 0; - virtual void issue_request( - const BotBaseRequest& request, - const Cancellable* cancelled = nullptr - ) = 0; - virtual BotBaseMessage issue_request_and_wait( - const BotBaseRequest& request, - const Cancellable* cancelled = nullptr - ) = 0; - -}; - - - - - -} - - -#endif - +/* Pokemon Automation Bot-Base Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AbstractBotBase_H +#define PokemonAutomation_AbstractBotBase_H + +#include +#include "Common/Cpp/CancellableScope.h" + +namespace PokemonAutomation{ + +class Logger; +struct BotBaseMessage; +class BotBaseRequest; +class BotBaseControllerContext; + + + +class BotBaseController{ +public: + using ContextType = BotBaseControllerContext; + + enum class State{ + RUNNING, + STOPPING, + STOPPED, +// ERROR, + }; + +public: + virtual ~BotBaseController() = default; + virtual void stop(std::string error_message = "") = 0; + + virtual Logger& logger() = 0; + virtual State state() const = 0; + virtual size_t queue_limit() const = 0; + + virtual void notify_all() = 0; + + // Waits for all pending requests to finish. + virtual void wait_for_all_requests(const Cancellable* cancelled = nullptr) = 0; + + // Stop all pending commands. This wipes the command queue on both sides + // and stops any currently executing command. + virtual void stop_all_commands() = 0; + + // Tell the device that the next command should replace the command queue. + // + // So once the next command is issued, it will stop all ongoing commands + // and run the new command instead. + // + // Once this function is called, all commands before it are no longer + // guaranteed to finish even if no command interrupts it. + virtual void next_command_interrupt() = 0; + +public: + virtual bool try_issue_request( + const BotBaseRequest& request, + const Cancellable* cancelled = nullptr + ) = 0; + virtual void issue_request( + const BotBaseRequest& request, + const Cancellable* cancelled = nullptr + ) = 0; + virtual BotBaseMessage issue_request_and_wait( + const BotBaseRequest& request, + const Cancellable* cancelled = nullptr + ) = 0; + +}; + + + + + +} + + +#endif + diff --git a/ClientSource/Connection/BotBaseMessage.h b/ClientSource/Connection/BotBaseMessage.h index b05cc23691..e2a3afea0b 100644 --- a/ClientSource/Connection/BotBaseMessage.h +++ b/ClientSource/Connection/BotBaseMessage.h @@ -1,78 +1,78 @@ -/* Bot-Base Message - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_BotBaseMessage_H -#define PokemonAutomation_BotBaseMessage_H - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/LifetimeSanitizer.h" - -namespace PokemonAutomation{ - - -struct BotBaseMessage{ - uint8_t type; - std::string body; - - LifetimeSanitizer sanitizer; - - BotBaseMessage() = default; - BotBaseMessage(uint8_t p_type, std::string p_body) - : type(p_type) - , body(std::move(p_body)) - {} - - template - BotBaseMessage(uint8_t p_type, const Params& params) - : type(p_type) - , body((char*)¶ms, sizeof(params)) - {} - - template - void convert(Logger& logger, MessageBody& params) const{ - sanitizer.check_usage(); - if (type != MessageType){ - throw SerialProtocolException( - logger, PA_CURRENT_FUNCTION, - "Received incorrect response type: " + std::to_string(type) - ); - } - if (body.size() != sizeof(MessageBody)){ - throw SerialProtocolException( - logger, PA_CURRENT_FUNCTION, - "Received incorrect response size: " + std::to_string(body.size()) - ); - } - memcpy(¶ms, body.c_str(), body.size()); - sanitizer.check_usage(); - } - -}; - -class BotBaseRequest{ -public: - BotBaseRequest(bool is_command) - : m_is_command(is_command) - {} - virtual ~BotBaseRequest() = default; - virtual BotBaseMessage message() const = 0; - - bool is_command() const{ return m_is_command; } - -private: - bool m_is_command; -}; - - - - - - -} -#endif +/* Bot-Base Message + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_BotBaseMessage_H +#define PokemonAutomation_BotBaseMessage_H + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/LifetimeSanitizer.h" + +namespace PokemonAutomation{ + + +struct BotBaseMessage{ + uint8_t type; + std::string body; + + LifetimeSanitizer sanitizer; + + BotBaseMessage() = default; + BotBaseMessage(uint8_t p_type, std::string p_body) + : type(p_type) + , body(std::move(p_body)) + {} + + template + BotBaseMessage(uint8_t p_type, const Params& params) + : type(p_type) + , body((char*)¶ms, sizeof(params)) + {} + + template + void convert(Logger& logger, MessageBody& params) const{ + sanitizer.check_usage(); + if (type != MessageType){ + throw SerialProtocolException( + logger, PA_CURRENT_FUNCTION, + "Received incorrect response type: " + std::to_string(type) + ); + } + if (body.size() != sizeof(MessageBody)){ + throw SerialProtocolException( + logger, PA_CURRENT_FUNCTION, + "Received incorrect response size: " + std::to_string(body.size()) + ); + } + memcpy(¶ms, body.c_str(), body.size()); + sanitizer.check_usage(); + } + +}; + +class BotBaseRequest{ +public: + BotBaseRequest(bool is_command) + : m_is_command(is_command) + {} + virtual ~BotBaseRequest() = default; + virtual BotBaseMessage message() const = 0; + + bool is_command() const{ return m_is_command; } + +private: + bool m_is_command; +}; + + + + + + +} +#endif diff --git a/ClientSource/Connection/MessageLogger.cpp b/ClientSource/Connection/MessageLogger.cpp index 5c608ace08..4f72fcb88d 100644 --- a/ClientSource/Connection/MessageLogger.cpp +++ b/ClientSource/Connection/MessageLogger.cpp @@ -1,129 +1,129 @@ -/* Message Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "BotBaseMessage.h" -#include "MessageLogger.h" - -namespace PokemonAutomation{ - - -//void MessageLogger::log(std::string msg){ -// log(msg); -//} -void MessageLogger::on_send(const BotBaseMessage& message, bool is_retransmit){ - bool print = false; - do{ - if (is_retransmit){ - print = true; - } - if (PABB_MSG_IS_REQUEST(message.type)){ - print = true; - } - if (PABB_MSG_IS_COMMAND(message.type)){ - print = true; - } - if (message.type == PABB_MSG_REQUEST_CLOCK){ - print = false; - } -#if 0 - if (message.type == PABB_MSG_CONTROLLER_STATE){ -// pabb_controller_state body; -// memcpy(&body, message.body.c_str(), sizeof(pabb_controller_state)); -// print = body.ticks >= 5; - print = false; - } -#endif - - if (m_log_everything.load(std::memory_order_relaxed)){ - print = true; - } - - }while (false); - if (!print){ - return; - } - std::string str = message_to_string(message); - if (str.empty()){ - return; - } - if (is_retransmit){ - log("Re-Send: " + str); - }else{ - log("Sending: " + str); - } -} -void MessageLogger::on_recv(const BotBaseMessage& message){ - bool print = false; - do{ - if (PABB_MSG_IS_ERROR(message.type)){ - print = true; - } - if (PABB_MSG_IS_INFO(message.type)){ - print = true; - } - - if (m_log_everything.load(std::memory_order_relaxed)){ - print = true; - } - - }while (false); - if (!print){ - return; - } - log("Receive: " + message_to_string(message)); -} - - - -SerialLogger::SerialLogger(Logger& logger, bool log_everything) - : MessageLogger(log_everything) - , m_logger(logger) - , m_history(200) -{} -void SerialLogger::log(const char* msg, Color color){ - if (ok_to_log()){ - m_logger.log(msg, color); - } -} -void SerialLogger::log(const std::string& msg, Color color){ - if (ok_to_log()){ - m_logger.log(msg, color); - } -} -void SerialLogger::log(std::string msg){ - if (ok_to_log()){ - m_logger.log(msg, COLOR_DARKGREEN); - } -} - -bool SerialLogger::ok_to_log(){ - WallClock now = current_time(); - WriteSpinLock lg(m_lock); - while (!m_history.empty()){ - if (now - m_history.front() < std::chrono::seconds(1)){ - break; - } - m_history.pop_front(); - } - if (!m_history.try_push_back(now)){ - m_messages_dropped++; - return false; - } - - if (m_messages_dropped != 0){ - m_logger.log("Dropped " + tostr_u_commas(m_messages_dropped) + " message(s) due to logging rate limit.", COLOR_RED); - m_messages_dropped = 0; - } - - return true; -} - - - -} +/* Message Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "BotBaseMessage.h" +#include "MessageLogger.h" + +namespace PokemonAutomation{ + + +//void MessageLogger::log(std::string msg){ +// log(msg); +//} +void MessageLogger::on_send(const BotBaseMessage& message, bool is_retransmit){ + bool print = false; + do{ + if (is_retransmit){ + print = true; + } + if (PABB_MSG_IS_REQUEST(message.type)){ + print = true; + } + if (PABB_MSG_IS_COMMAND(message.type)){ + print = true; + } + if (message.type == PABB_MSG_REQUEST_CLOCK){ + print = false; + } +#if 0 + if (message.type == PABB_MSG_CONTROLLER_STATE){ +// pabb_controller_state body; +// memcpy(&body, message.body.c_str(), sizeof(pabb_controller_state)); +// print = body.ticks >= 5; + print = false; + } +#endif + + if (m_log_everything.load(std::memory_order_relaxed)){ + print = true; + } + + }while (false); + if (!print){ + return; + } + std::string str = message_to_string(message); + if (str.empty()){ + return; + } + if (is_retransmit){ + log("Re-Send: " + str); + }else{ + log("Sending: " + str); + } +} +void MessageLogger::on_recv(const BotBaseMessage& message){ + bool print = false; + do{ + if (PABB_MSG_IS_ERROR(message.type)){ + print = true; + } + if (PABB_MSG_IS_INFO(message.type)){ + print = true; + } + + if (m_log_everything.load(std::memory_order_relaxed)){ + print = true; + } + + }while (false); + if (!print){ + return; + } + log("Receive: " + message_to_string(message)); +} + + + +SerialLogger::SerialLogger(Logger& logger, bool log_everything) + : MessageLogger(log_everything) + , m_logger(logger) + , m_history(200) +{} +void SerialLogger::log(const char* msg, Color color){ + if (ok_to_log()){ + m_logger.log(msg, color); + } +} +void SerialLogger::log(const std::string& msg, Color color){ + if (ok_to_log()){ + m_logger.log(msg, color); + } +} +void SerialLogger::log(std::string msg){ + if (ok_to_log()){ + m_logger.log(msg, COLOR_DARKGREEN); + } +} + +bool SerialLogger::ok_to_log(){ + WallClock now = current_time(); + WriteSpinLock lg(m_lock); + while (!m_history.empty()){ + if (now - m_history.front() < std::chrono::seconds(1)){ + break; + } + m_history.pop_front(); + } + if (!m_history.try_push_back(now)){ + m_messages_dropped++; + return false; + } + + if (m_messages_dropped != 0){ + m_logger.log("Dropped " + tostr_u_commas(m_messages_dropped) + " message(s) due to logging rate limit.", COLOR_RED); + m_messages_dropped = 0; + } + + return true; +} + + + +} diff --git a/ClientSource/Connection/MessageLogger.h b/ClientSource/Connection/MessageLogger.h index c2eee1b4c4..8904a7ae4a 100644 --- a/ClientSource/Connection/MessageLogger.h +++ b/ClientSource/Connection/MessageLogger.h @@ -1,65 +1,65 @@ -/* Message Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_MessageLogger_H -#define PokemonAutomation_MessageLogger_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Containers/CircularBuffer.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "MessageSniffer.h" - -namespace PokemonAutomation{ - - -class MessageLogger : public MessageSniffer{ -public: - MessageLogger(bool log_everything = false) - : m_log_everything_owner(log_everything) - , m_log_everything(m_log_everything_owner) - {} - MessageLogger(std::atomic& log_everything) - : m_log_everything_owner(false) - , m_log_everything(log_everything) - {} - - -// virtual void log(std::string msg) override; - virtual void on_send(const BotBaseMessage& message, bool is_retransmit) override; - virtual void on_recv(const BotBaseMessage& message) override; - -private: - std::atomic m_log_everything_owner; - std::atomic& m_log_everything; -}; - - - -class SerialLogger : public Logger, public MessageLogger{ -public: - SerialLogger(Logger& logger, bool log_everything); - - virtual void log(const char* msg, Color color = Color()) override; - virtual void log(const std::string& msg, Color color = Color()) override; - virtual void log(std::string msg) override; - -private: - bool ok_to_log(); - -private: - Logger& m_logger; - SpinLock m_lock; - size_t m_messages_dropped = 0; - CircularBuffer m_history; -}; - - - - -} -#endif +/* Message Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MessageLogger_H +#define PokemonAutomation_MessageLogger_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Containers/CircularBuffer.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "MessageSniffer.h" + +namespace PokemonAutomation{ + + +class MessageLogger : public MessageSniffer{ +public: + MessageLogger(bool log_everything = false) + : m_log_everything_owner(log_everything) + , m_log_everything(m_log_everything_owner) + {} + MessageLogger(std::atomic& log_everything) + : m_log_everything_owner(false) + , m_log_everything(log_everything) + {} + + +// virtual void log(std::string msg) override; + virtual void on_send(const BotBaseMessage& message, bool is_retransmit) override; + virtual void on_recv(const BotBaseMessage& message) override; + +private: + std::atomic m_log_everything_owner; + std::atomic& m_log_everything; +}; + + + +class SerialLogger : public Logger, public MessageLogger{ +public: + SerialLogger(Logger& logger, bool log_everything); + + virtual void log(const char* msg, Color color = Color()) override; + virtual void log(const std::string& msg, Color color = Color()) override; + virtual void log(std::string msg) override; + +private: + bool ok_to_log(); + +private: + Logger& m_logger; + SpinLock m_lock; + size_t m_messages_dropped = 0; + CircularBuffer m_history; +}; + + + + +} +#endif diff --git a/ClientSource/Connection/MessageSniffer.h b/ClientSource/Connection/MessageSniffer.h index db755e39af..5545e6adda 100644 --- a/ClientSource/Connection/MessageSniffer.h +++ b/ClientSource/Connection/MessageSniffer.h @@ -1,28 +1,28 @@ -/* Message Sniffer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_MessageSniffer_H -#define PokemonAutomation_MessageSniffer_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ - -struct BotBaseMessage; - - -class MessageSniffer{ -public: - virtual void log(std::string msg){} - virtual void on_send(const BotBaseMessage& message, bool is_retransmit){} - virtual void on_recv(const BotBaseMessage& message){} -}; - - - -} -#endif +/* Message Sniffer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MessageSniffer_H +#define PokemonAutomation_MessageSniffer_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ + +struct BotBaseMessage; + + +class MessageSniffer{ +public: + virtual void log(std::string msg){} + virtual void on_send(const BotBaseMessage& message, bool is_retransmit){} + virtual void on_recv(const BotBaseMessage& message){} +}; + + + +} +#endif diff --git a/ClientSource/Connection/PABotBase.cpp b/ClientSource/Connection/PABotBase.cpp index 3f8403596b..e5fd42b9a7 100644 --- a/ClientSource/Connection/PABotBase.cpp +++ b/ClientSource/Connection/PABotBase.cpp @@ -1,957 +1,957 @@ -/* Pokemon Automation Bot Base - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "PABotBase.h" - -//#include -//using std::cout; -//using std::endl; - - -// Intentionally drop some messages to test self-recovery. -//#define INTENTIONALLY_DROP_MESSAGES - - - -// #define DEBUG_STACK_TRACE - -#ifdef DEBUG_STACK_TRACE - -#if defined(__APPLE__) -#include -#include -#endif - -#endif // DEBUG_STACK_TRACE - -namespace PokemonAutomation{ - - - -PABotBase::PABotBase( - Logger& logger, - std::unique_ptr connection, - MessageLogger* message_logger, - std::chrono::milliseconds retransmit_delay -) - : PABotBaseConnection(logger, std::move(connection)) - , m_logger(logger) - , m_max_pending_requests(PABB_DEVICE_MINIMUM_QUEUE_SIZE) - , m_send_seq(1) - , m_retransmit_delay(retransmit_delay) - , m_last_ack(current_time()) - , m_state(State::RUNNING) - , m_error(false) -{ - set_sniffer(message_logger); - - // We must initialize this last because it will trigger the lifetime - // sanitizer if it beats it to construction. - m_retransmit_thread = std::thread( - run_with_catch, - "PABotBase::retransmit_thread()", - [this]{ retransmit_thread(); } - ); -} -PABotBase::~PABotBase(){ - stop(); - while (m_state.load(std::memory_order_acquire) != State::STOPPED){ - pause(); - } -} - -size_t PABotBase::inflight_requests(){ - auto scope_check = m_sanitizer.check_scope(); - - // Must be called under m_state_lock. - - size_t ret = m_pending_requests.size(); - for (const auto& item : m_pending_commands){ - if (item.second.state == AckState::NOT_ACKED){ - ret++; - } - } - return ret; -} - -void PABotBase::connect(){ - auto scope_check = m_sanitizer.check_scope(); - - pabb_MsgAckRequest response; - issue_request_and_wait( - SerialPABotBase::DeviceRequest_seqnum_reset(), nullptr - ).convert(logger(), response); -} -void PABotBase::stop(std::string error_message){ - auto scope_check = m_sanitizer.check_scope(); - - // Make sure only one thread can get in here. - State expected = State::RUNNING; - if (!m_state.compare_exchange_strong(expected, State::STOPPING)){ - return; - } - - if (!error_message.empty()){ - ReadSpinLock lg(m_state_lock); - m_error_message = std::move(error_message); - } - - // Wake everyone up. - { - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); - } - m_retransmit_thread.join(); - - { - ReadSpinLock lg(m_state_lock, "PABotBase::stop()"); - - // Send a stop request, but don't wait for a response that we may never - // receive. - pabb_MsgRequestStop params; - uint64_t seqnum = m_send_seq; - seqnum_t seqnum_s = (seqnum_t)seqnum; - memcpy(¶ms, &seqnum_s, sizeof(seqnum_t)); -// try_issue_request(params); -// m_state.store(State::STOPPING, std::memory_order_release); - BotBaseMessage stop_request(PABB_MSG_REQUEST_STOP, std::string((char*)¶ms, sizeof(params))); - send_message(stop_request, false); - } - - // Must call this to stop the receiver thread from making any more async - // calls into this class which touch its fields. - safely_stop(); - - // Now the receiver thread is dead. Nobody else is touching this class so - // it is safe to destruct. - m_state.store(State::STOPPED, std::memory_order_release); -} -void PABotBase::notify_all(){ - std::unique_lock lg(m_sleep_lock); - m_cv.notify_all(); -} - -void PABotBase::set_queue_limit(size_t queue_limit){ - m_max_pending_requests.store(queue_limit, std::memory_order_relaxed); -} - -void PABotBase::wait_for_all_requests(const Cancellable* cancelled){ - auto scope_check = m_sanitizer.check_scope(); - - std::unique_lock lg(m_sleep_lock); - m_logger.log("Waiting for all requests to finish...", COLOR_DARKGREEN); - while (true){ - if (cancelled != nullptr && cancelled->cancelled()){ - throw OperationCancelledException(); - } - if (m_state.load(std::memory_order_acquire) != State::RUNNING){ - ReadSpinLock lg0(m_state_lock); - throw InvalidConnectionStateException(m_error_message); - } - { - ReadSpinLock lg1(m_state_lock, "PABotBase::wait_for_all_requests()"); -#if 0 - m_logger.log( - "Waiting for all requests to finish... (Requests: " + - std::to_string(m_pending_requests.size()) + - ", Commands: " + std::to_string(m_pending_commands.size()) + ")", - COLOR_DARKGREEN - ); -#endif - if (m_pending_requests.empty() && m_pending_commands.empty()){ - break; - } - } - m_cv.wait(lg); - } - -// m_logger.log("Waiting for all requests to finish... Completed.", COLOR_DARKGREEN); -} -void PABotBase::stop_all_commands(){ - -#ifdef DEBUG_STACK_TRACE - cout << __FILE__ << ":" << __LINE__ << " PABotBase::stop_all_commands()" << endl; - cout << "-----------------------------------------------------------------------------------------" << endl; -#if defined(__APPLE__) - void* callstack[128]; - int i, frames = backtrace(callstack, 128); - char** strs = backtrace_symbols(callstack, frames); - for (i = 0; i < frames; ++i) { - cout << strs[i] << endl; - } - free(strs); -#endif - cout << "-----------------------------------------------------------------------------------------" << endl; -#endif - - auto scope_check = m_sanitizer.check_scope(); - - uint64_t seqnum = issue_request(nullptr, SerialPABotBase::DeviceRequest_request_stop(), true, true); - clear_all_active_commands(seqnum); -} -void PABotBase::next_command_interrupt(){ - auto scope_check = m_sanitizer.check_scope(); - - uint64_t seqnum = issue_request(nullptr, SerialPABotBase::DeviceRequest_next_command_interrupt(), true, true); - clear_all_active_commands(seqnum); -} -void PABotBase::clear_all_active_commands(uint64_t seqnum){ - auto scope_check = m_sanitizer.check_scope(); - - // Remove all commands at or before the specified seqnum. - std::lock_guard lg0(m_sleep_lock); - WriteSpinLock lg1(m_state_lock, "PABotBase::next_command_interrupt()"); - m_logger.log("Clearing all active commands... (Commands: " + std::to_string(m_pending_commands.size()) + ")", COLOR_DARKGREEN); - - m_cv.notify_all(); - - if (m_pending_commands.empty()){ - return; - } - - // Remove all active commands up to the seqnum. - while (true){ - auto iter = m_pending_commands.begin(); - if (iter == m_pending_commands.end() || iter->first > seqnum){ - break; - } - iter->second.sanitizer.check_usage(); - - // We cannot remove un-acked messages from our buffer. If an un-acked - // message is dropped and the receiver is still waiting for it, it will - // wait forever since we will never retransmit. - - if (iter->second.state == AckState::NOT_ACKED){ - // Convert the command into a no-op request. - SerialPABotBase::DeviceRequest_program_id request; - BotBaseMessage message = request.message(); - seqnum_t seqnum_s = (seqnum_t)iter->first; - memcpy(&message.body[0], &seqnum_s, sizeof(seqnum_t)); - -// cout << "removing = " << seqnum_s << ", " << (int)iter->second.state << endl; - - std::pair::iterator, bool> ret = m_pending_requests.emplace( - std::piecewise_construct, - std::forward_as_tuple(iter->first), - std::forward_as_tuple() - ); - if (!ret.second){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Duplicate sequence number: " + std::to_string(seqnum)); - } - - // This block will never throw. - { - PendingRequest& handle = ret.first->second; - handle.silent_remove = true; - handle.request = std::move(message); - handle.first_sent = current_time(); - } - } - - m_pending_commands.erase(iter); - } -} -template -uint64_t PABotBase::infer_full_seqnum(const Map& map, seqnum_t seqnum) const{ - auto scope_check = m_sanitizer.check_scope(); - - // The protocol uses a 32-bit seqnum that wraps around. For our purposes of - // retransmits, we use a full 64-bit seqnum to maintain sorting order - // across the wrap-arounds. - - // Since the oldest unacked messaged will never be more than 63 (MAX_SEQNUM_GAP) - // requests old, there is no ambiguity on which request is being referred - // to with just the lower 32 bits. - // Here we infer the upper 32 bits of the seqnum to obtain the full 64-bit - // seqnum that we need to index our map. - - // This needs to be called inside the lock. Furthermore, the map must not - // be empty. If it is empty, we know we don't have it and can drop it - // before we even call this function. - - // Figure out the upper 32 bits of the seqnum. - uint64_t lo = map.begin()->first; - uint64_t hi = map.rbegin()->first; - uint64_t lo_candidate = (lo & 0xffffffff00000000) | seqnum; - uint64_t hi_candidate = (hi & 0xffffffff00000000) | seqnum; - return lo_candidate >= lo - ? lo_candidate - : hi_candidate; -} - -uint64_t PABotBase::oldest_live_seqnum() const{ - auto scope_check = m_sanitizer.check_scope(); - - // Must call under state lock. - uint64_t oldest = m_send_seq; - if (!m_pending_requests.empty()){ - oldest = std::min(oldest, m_pending_requests.begin()->first); - } - if (!m_pending_commands.empty()){ - oldest = std::min(oldest, m_pending_commands.begin()->first); - } - return oldest; -} - -template -void PABotBase::process_ack_request(BotBaseMessage message){ - auto scope_check = m_sanitizer.check_scope(); - - if constexpr (!variable_length){ - if (message.body.size() != sizeof(Params)){ - m_sniffer->log("Ignoring message with invalid size."); - return; - } - } - const Params* params = (const Params*)message.body.c_str(); - seqnum_t seqnum = params->seqnum; - - AckState state; - { - WriteSpinLock lg(m_state_lock, "PABotBase::process_ack_request()"); - - if (m_pending_requests.empty()){ - m_sniffer->log("Unexpected request ack message: seqnum = " + std::to_string(seqnum)); - return; - } - - uint64_t full_seqnum = infer_full_seqnum(m_pending_requests, seqnum); - std::map::iterator iter = m_pending_requests.find(full_seqnum); - if (iter == m_pending_requests.end()){ - m_sniffer->log("Unexpected request ack message: seqnum = " + std::to_string(seqnum)); - return; - } - iter->second.sanitizer.check_usage(); - - state = iter->second.state; - if (state == AckState::NOT_ACKED){ - if (iter->second.silent_remove){ - m_pending_requests.erase(iter); - }else{ - iter->second.state = AckState::ACKED; - iter->second.ack = std::move(message); - } - } - } - - m_last_ack.store(current_time(), std::memory_order_release); - - switch (state){ - case AckState::NOT_ACKED: - { - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); - } - return; - case AckState::ACKED: - m_sniffer->log("Duplicate request ack message: seqnum = " + std::to_string(seqnum)); - return; - case AckState::FINISHED: - m_sniffer->log("Request ack on command finish: seqnum = " + std::to_string(seqnum)); - return; - } -} -template -void PABotBase::process_ack_command(BotBaseMessage message){ - auto scope_check = m_sanitizer.check_scope(); - - if (message.body.size() != sizeof(Params)){ - m_sniffer->log("Ignoring message with invalid size."); - return; - } - const Params* params = (const Params*)message.body.c_str(); - seqnum_t seqnum = params->seqnum; - - WriteSpinLock lg(m_state_lock, "PABotBase::process_ack_command()"); - - if (m_pending_commands.empty()){ - m_sniffer->log("Unexpected command ack message: seqnum = " + std::to_string(seqnum)); - return; - } - - uint64_t full_seqnum = infer_full_seqnum(m_pending_commands, seqnum); - auto iter = m_pending_commands.find(full_seqnum); - if (iter == m_pending_commands.end()){ - m_sniffer->log("Unexpected command ack message: seqnum = " + std::to_string(seqnum)); - return; - } - iter->second.sanitizer.check_usage(); - - m_last_ack.store(current_time(), std::memory_order_release); - - switch (iter->second.state){ - case AckState::NOT_ACKED: -// std::cout << "acked: " << full_seqnum << std::endl; - iter->second.state = AckState::ACKED; - iter->second.ack = std::move(message); - return; - case AckState::ACKED: - m_sniffer->log("Duplicate command ack message: seqnum = " + std::to_string(seqnum)); - return; - case AckState::FINISHED: - m_sniffer->log("Command ack on finished command: seqnum = " + std::to_string(seqnum)); - return; - } -} -template -void PABotBase::process_command_finished(BotBaseMessage message){ - auto scope_check = m_sanitizer.check_scope(); - - if (message.body.size() != sizeof(Params)){ - m_sniffer->log("Ignoring message with invalid size."); - return; - } - const Params* params = (const Params*)message.body.c_str(); - seqnum_t seqnum = params->seqnum; - seqnum_t command_seqnum = params->seq_of_original_command; - - // Send the ack first. - pabb_MsgAckRequest ack; - ack.seqnum = seqnum; -// m_send_queue.emplace_back((uint8_t)PABB_MSG_ACK, std::string((char*)&ack, sizeof(ack))); - - std::lock_guard lg0(m_sleep_lock); - WriteSpinLock lg1(m_state_lock, "PABotBase::process_command_finished() - 0"); - -#ifdef INTENTIONALLY_DROP_MESSAGES - if (rand() % 10 != 0){ - send_message(BotBaseMessage(PABB_MSG_ACK_REQUEST, std::string((char*)&ack, sizeof(ack))), false); - }else{ - m_logger.log("Intentionally dropping finish ack: " + std::to_string(seqnum), COLOR_RED); - } -#else - send_message(BotBaseMessage(PABB_MSG_ACK_REQUEST, std::string((char*)&ack, sizeof(ack))), false); -#endif - - if (m_pending_commands.empty()){ - m_sniffer->log( - "Unexpected command finished message: seqnum = " + std::to_string(seqnum) + - ", command_seqnum = " + std::to_string(command_seqnum) - ); - return; - } - - uint64_t full_seqnum = infer_full_seqnum(m_pending_commands, command_seqnum); - auto iter = m_pending_commands.find(full_seqnum); - if (iter == m_pending_commands.end()){ - m_sniffer->log( - "Unexpected command finished message: seqnum = " + std::to_string(seqnum) + - ", command_seqnum = " + std::to_string(command_seqnum) - ); - return; - } - iter->second.sanitizer.check_usage(); - - switch (iter->second.state){ - case AckState::NOT_ACKED: - case AckState::ACKED: - iter->second.state = AckState::FINISHED; - iter->second.ack = std::move(message); - if (iter->second.silent_remove){ - m_pending_commands.erase(iter); - } - m_cv.notify_all(); - return; - case AckState::FINISHED: - m_sniffer->log("Duplicate command finish: seqnum = " + std::to_string(seqnum)); - return; - } -} -void PABotBase::on_recv_message(BotBaseMessage message){ - auto scope_check = m_sanitizer.check_scope(); - - switch (message.type){ - case PABB_MSG_ACK_COMMAND: - process_ack_command(std::move(message)); - return; - case PABB_MSG_ACK_REQUEST: - process_ack_request(std::move(message)); - return; - case PABB_MSG_ACK_REQUEST_I8: - process_ack_request(std::move(message)); - return; - case PABB_MSG_ACK_REQUEST_I16: - process_ack_request(std::move(message)); - return; - case PABB_MSG_ACK_REQUEST_I32: - process_ack_request(std::move(message)); - return; - case PABB_MSG_ACK_REQUEST_DATA: - process_ack_request(std::move(message)); - return; - case PABB_MSG_ERROR_INVALID_TYPE:{ - if (message.body.size() != sizeof(pabb_MsgInfoInvalidType)){ - m_sniffer->log("Ignoring message with invalid size."); - return; - } - const pabb_MsgInfoInvalidType* params = (const pabb_MsgInfoInvalidType*)message.body.c_str(); - { - WriteSpinLock lg(m_state_lock); - m_error_message = "PABotBase incompatibility. Device does not recognize message type: " + std::to_string(params->type); - m_logger.log(m_error_message, COLOR_RED); - } - m_error.store(true, std::memory_order_release); - std::lock_guard lg0(m_sleep_lock); - m_cv.notify_all(); - } - case PABB_MSG_ERROR_MISSED_REQUEST:{ - if (message.body.size() != sizeof(pabb_MsgInfoMissedRequest)){ - m_sniffer->log("Ignoring message with invalid size."); - return; - } - const pabb_MsgInfoMissedRequest* params = (const pabb_MsgInfoMissedRequest*)message.body.c_str(); - if (params->seqnum == 1){ - { - WriteSpinLock lg(m_state_lock); - m_error_message = "Serial connection has been interrupted."; - m_logger.log(m_error_message, COLOR_RED); - } - m_error.store(true, std::memory_order_release); - std::lock_guard lg0(m_sleep_lock); - m_cv.notify_all(); - } - return; - } - case PABB_MSG_ERROR_DISCONNECTED:{ - m_logger.log("The console has disconnected the controller.", COLOR_RED); - { - WriteSpinLock lg(m_state_lock); - m_error_message = "Disconnected by console."; - } - m_error.store(true, std::memory_order_release); - std::lock_guard lg0(m_sleep_lock); - m_cv.notify_all(); - return; - } - case PABB_MSG_REQUEST_COMMAND_FINISHED:{ - process_command_finished(std::move(message)); - return; - } - } -} - -void PABotBase::retransmit_thread(){ - auto scope_check = m_sanitizer.check_scope(); - -// cout << "retransmit_thread()" << endl; - auto last_sent = current_time(); - while (m_state.load(std::memory_order_acquire) == State::RUNNING){ - auto now = current_time(); - - if (now - last_sent < m_retransmit_delay){ - std::unique_lock lg(m_sleep_lock); - if (m_state.load(std::memory_order_acquire) != State::RUNNING){ - break; - } - if (m_error.load(std::memory_order_acquire)){ - break; - } - m_cv.wait_for(lg, m_retransmit_delay); - continue; - } - - // Process retransmits. - WriteSpinLock lg(m_state_lock, "PABotBase::retransmit_thread()"); -// std::cout << "retransmit_thread - m_pending_messages.size(): " << m_pending_messages.size() << std::endl; -// cout << "m_pending_messages.size()" << endl; - - // Retransmit - // Iterate through all pending requests and retransmit them in - // chronological order. ~~Skip the ones that are new.~~ - // (Don't skip the new ones since it will lead to gaps.) - - // Gather together all requests/commands. Sort them by seqnum and - // resend everything. - - WallClock oldest = last_sent; - - std::map messages; - for (auto& item : m_pending_requests){ - item.second.sanitizer.check_usage(); - if (item.second.state == AckState::NOT_ACKED){ - oldest = std::max(oldest, item.second.first_sent); - messages[item.first] = &item.second.request; - } - } - for (auto& item : m_pending_commands){ - item.second.sanitizer.check_usage(); - if (item.second.state == AckState::NOT_ACKED){ - oldest = std::max(oldest, item.second.first_sent); - messages[item.first] = &item.second.request; - } - } - - if (!messages.empty() && now - oldest >= m_retransmit_delay){ - for (const auto& item : messages){ - send_message(*item.second, true); - } - } - -#if 0 - for (auto& item : m_pending_requests){ - item.second.sanitizer.check_usage(); - if (item.second.state == AckState::NOT_ACKED && - current_time() - item.second.first_sent >= m_retransmit_delay - ){ - send_message(item.second.request, true); - } - } - for (auto& item : m_pending_commands){ - item.second.sanitizer.check_usage(); - if (item.second.state == AckState::NOT_ACKED && - current_time() - item.second.first_sent >= m_retransmit_delay - ){ - send_message(item.second.request, true); - } - } -#endif - - last_sent = current_time(); - } -// cout << "retransmit_thread() - exit" << endl; -} - - - - -uint64_t PABotBase::try_issue_request( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove, bool do_not_block -){ - auto scope_check = m_sanitizer.check_scope(); - - BotBaseMessage message = request.message(); - if (message.body.size() < sizeof(uint32_t)){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too short."); - } - if (message.body.size() > MAX_MESSAGE_SIZE){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); - } - - WriteSpinLock lg(m_state_lock, "PABotBase::try_issue_request()"); - if (cancelled != nullptr && cancelled->cancelled()){ - throw OperationCancelledException(); - } - - State state = m_state.load(std::memory_order_acquire); - if (state != State::RUNNING){ - throw InvalidConnectionStateException(m_error_message); - } - if (m_error.load(std::memory_order_acquire)){ - throw ConnectionException(&m_logger, m_error_message); - } - - size_t queue_limit = m_max_pending_requests.load(std::memory_order_relaxed); - - // Too many unacked requests in flight. - if (!do_not_block && inflight_requests() >= queue_limit){ -// m_logger.log("Message throttled due to too many inflight requests."); - return 0; - } - - // Don't get too far ahead of the oldest seqnum. - uint64_t seqnum = m_send_seq; - if (seqnum - oldest_live_seqnum() > MAX_SEQNUM_GAP){ - if (do_not_block){ - throw ConnectionException( - &m_logger, - "Connection has stalled for a long time. Assuming it is dead." - ); - } - return 0; - } - - seqnum_t seqnum_s = (seqnum_t)seqnum; - memcpy(&message.body[0], &seqnum_s, sizeof(seqnum_t)); - - std::pair::iterator, bool> ret = m_pending_requests.emplace( - std::piecewise_construct, - std::forward_as_tuple(seqnum), - std::forward_as_tuple() - ); - if (!ret.second){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Duplicate sequence number: " + std::to_string(seqnum)); - } - - m_send_seq = seqnum + 1; - - PendingRequest& handle = ret.first->second; - - handle.silent_remove = silent_remove; - handle.request = std::move(message); - handle.first_sent = current_time(); - -#ifdef INTENTIONALLY_DROP_MESSAGES - if (rand() % 10 != 0){ - send_message(handle.request, false); - }else{ - m_logger.log("Intentionally dropping request: " + std::to_string(seqnum), COLOR_RED); - } -#else - send_message(handle.request, false); -#endif - - return seqnum; -} -uint64_t PABotBase::try_issue_command( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove -){ - auto scope_check = m_sanitizer.check_scope(); - - BotBaseMessage message = request.message(); - if (message.body.size() < sizeof(uint32_t)){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too short."); - } - if (message.body.size() > MAX_MESSAGE_SIZE){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); - } - - WriteSpinLock lg(m_state_lock, "PABotBase::try_issue_command()"); - if (cancelled != nullptr && cancelled->cancelled()){ - throw OperationCancelledException(); - } - - State state = m_state.load(std::memory_order_acquire); - if (state != State::RUNNING){ - throw InvalidConnectionStateException(m_error_message); - } - if (m_error.load(std::memory_order_acquire)){ - throw ConnectionException(&m_logger, m_error_message); - } - - size_t queue_limit = m_max_pending_requests.load(std::memory_order_relaxed); - - // Command queue is full. - if (m_pending_commands.size() >= queue_limit){ -// cout << "Command queue is full" << endl; - return 0; - } - - // Too many unacked requests in flight. - if (inflight_requests() >= queue_limit){ -// m_logger.log("Message throttled due to too many inflight requests."); - return 0; - } - - // Don't get too far ahead of the oldest seqnum. - uint64_t seqnum = m_send_seq; - if (seqnum - oldest_live_seqnum() > MAX_SEQNUM_GAP){ - return 0; - } - - seqnum_t seqnum_s = (seqnum_t)seqnum; - memcpy(&message.body[0], &seqnum_s, sizeof(seqnum_t)); - - std::pair::iterator, bool> ret = m_pending_commands.emplace( - std::piecewise_construct, - std::forward_as_tuple(seqnum), - std::forward_as_tuple() - ); - if (!ret.second){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Duplicate sequence number: " + std::to_string(seqnum)); - } - - m_send_seq = seqnum + 1; - - PendingCommand& handle = ret.first->second; - - handle.silent_remove = silent_remove; - handle.request = std::move(message); - handle.first_sent = current_time(); - -#ifdef INTENTIONALLY_DROP_MESSAGES - if (rand() % 10 != 0){ - send_message(handle.request, false); - }else{ - m_logger.log("Intentionally dropping command: " + std::to_string(seqnum), COLOR_RED); - } -#else - send_message(handle.request, false); -#endif - - return seqnum; -} -uint64_t PABotBase::issue_request( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove, bool do_not_block -){ - auto scope_check = m_sanitizer.check_scope(); - - // Issue a request and return. - // - // If it cannot be issued (because we're over the limits), this function - // will wait until it can be issued. - // - // The "silent_remove" parameter determines what to do when the - // ack (for a request) or a finish (for a command) is received. - // - // If (silent_remove = true), the receiving thread will remove the request - // from the map and do nothing else. This is for async commands. - // - // If (silent_remove = false), the receiving thread will not remove the - // request. Instead, it will notify whatever thread is waiting for the - // result. That waiting thread will process the return value (if any) and - // remove the request from the map. This is for synchronous commands where - // the function waits for the command to finish before returning. - // - - while (true){ - uint64_t seqnum = try_issue_request(cancelled, request, silent_remove, do_not_block); - if (seqnum != 0){ - return seqnum; - } - std::unique_lock lg(m_sleep_lock); - if (cancelled != nullptr && cancelled->cancelled()){ - throw OperationCancelledException(); - } - if (m_state.load(std::memory_order_acquire) != State::RUNNING){ - ReadSpinLock lg0(m_state_lock); - throw InvalidConnectionStateException(m_error_message); - } - if (m_error.load(std::memory_order_acquire)){ - ReadSpinLock lg0(m_state_lock); - throw ConnectionException(&m_logger, m_error_message); - } - m_cv.wait(lg); - } -} -uint64_t PABotBase::issue_command( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove -){ - auto scope_check = m_sanitizer.check_scope(); - - // Issue a command and return. - // - // If it cannot be issued (because we're over the limits), this function - // will wait until it can be issued. - // - // The "silent_remove" parameter determines what to do when the - // ack (for a request) or a finish (for a command) is received. - // - // If (silent_remove = true), the receiving thread will remove the request - // from the map and do nothing else. This is for async commands. - // - // If (silent_remove = false), the receiving thread will not remove the - // request. Instead, it will notify whatever thread is waiting for the - // result. That waiting thread will process the return value (if any) and - // remove the request from the map. This is for synchronous commands where - // the function waits for the command to finish before returning. - // - - while (true){ - uint64_t seqnum = try_issue_command(cancelled, request, silent_remove); - if (seqnum != 0){ - return seqnum; - } - std::unique_lock lg(m_sleep_lock); - if (cancelled != nullptr && cancelled->cancelled()){ - throw OperationCancelledException(); - } - if (m_state.load(std::memory_order_acquire) != State::RUNNING){ - ReadSpinLock lg0(m_state_lock); - throw InvalidConnectionStateException(m_error_message); - } - if (m_error.load(std::memory_order_acquire)){ - ReadSpinLock lg0(m_state_lock); - throw ConnectionException(&m_logger, m_error_message); - } - m_cv.wait(lg); - } -} - -bool PABotBase::try_issue_request( - const BotBaseRequest& request, - const Cancellable* cancelled -){ - auto scope_check = m_sanitizer.check_scope(); - - if (!request.is_command()){ - return try_issue_request(cancelled, request, true, false) != 0; - }else{ - return try_issue_command(cancelled, request, true) != 0; - } -} -void PABotBase::issue_request( - const BotBaseRequest& request, - const Cancellable* cancelled -){ - auto scope_check = m_sanitizer.check_scope(); - - if (!request.is_command()){ - issue_request(cancelled, request, true, false); - }else{ - issue_command(cancelled, request, true); - } -} - -BotBaseMessage PABotBase::issue_request_and_wait( - const BotBaseRequest& request, - const Cancellable* cancelled -){ - auto scope_check = m_sanitizer.check_scope(); - - if (request.is_command()){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "This function only supports requests."); - } - - uint64_t seqnum = issue_request(cancelled, request, false, false); - return wait_for_request(seqnum, cancelled); -} -BotBaseMessage PABotBase::wait_for_request(uint64_t seqnum, const Cancellable* cancelled){ - auto scope_check = m_sanitizer.check_scope(); - - std::unique_lock lg(m_sleep_lock); - while (true){ - if (cancelled && cancelled->cancelled()){ - throw OperationCancelledException(); - } - - { - WriteSpinLock slg(m_state_lock, "PABotBase::issue_request_and_wait()"); - auto iter = m_pending_requests.find(seqnum); - if (iter == m_pending_requests.end()){ - throw OperationCancelledException(); - } - iter->second.sanitizer.check_usage(); - - State state = m_state.load(std::memory_order_acquire); - if (state != State::RUNNING){ - m_pending_requests.erase(iter); - m_cv.notify_all(); - throw InvalidConnectionStateException(m_error_message); - } - if (m_error.load(std::memory_order_acquire)){ - m_pending_requests.erase(iter); - m_cv.notify_all(); - throw ConnectionException(&m_logger, m_error_message); - } - if (iter->second.state == AckState::ACKED){ - BotBaseMessage ret = std::move(iter->second.ack); - m_pending_requests.erase(iter); - m_cv.notify_all(); - return ret; - } - } - m_cv.wait(lg); - } -} - - - - -} +/* Pokemon Automation Bot Base + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "PABotBase.h" + +//#include +//using std::cout; +//using std::endl; + + +// Intentionally drop some messages to test self-recovery. +//#define INTENTIONALLY_DROP_MESSAGES + + + +// #define DEBUG_STACK_TRACE + +#ifdef DEBUG_STACK_TRACE + +#if defined(__APPLE__) +#include +#include +#endif + +#endif // DEBUG_STACK_TRACE + +namespace PokemonAutomation{ + + + +PABotBase::PABotBase( + Logger& logger, + std::unique_ptr connection, + MessageLogger* message_logger, + std::chrono::milliseconds retransmit_delay +) + : PABotBaseConnection(logger, std::move(connection)) + , m_logger(logger) + , m_max_pending_requests(PABB_DEVICE_MINIMUM_QUEUE_SIZE) + , m_send_seq(1) + , m_retransmit_delay(retransmit_delay) + , m_last_ack(current_time()) + , m_state(State::RUNNING) + , m_error(false) +{ + set_sniffer(message_logger); + + // We must initialize this last because it will trigger the lifetime + // sanitizer if it beats it to construction. + m_retransmit_thread = std::thread( + run_with_catch, + "PABotBase::retransmit_thread()", + [this]{ retransmit_thread(); } + ); +} +PABotBase::~PABotBase(){ + stop(); + while (m_state.load(std::memory_order_acquire) != State::STOPPED){ + pause(); + } +} + +size_t PABotBase::inflight_requests(){ + auto scope_check = m_sanitizer.check_scope(); + + // Must be called under m_state_lock. + + size_t ret = m_pending_requests.size(); + for (const auto& item : m_pending_commands){ + if (item.second.state == AckState::NOT_ACKED){ + ret++; + } + } + return ret; +} + +void PABotBase::connect(){ + auto scope_check = m_sanitizer.check_scope(); + + pabb_MsgAckRequest response; + issue_request_and_wait( + SerialPABotBase::DeviceRequest_seqnum_reset(), nullptr + ).convert(logger(), response); +} +void PABotBase::stop(std::string error_message){ + auto scope_check = m_sanitizer.check_scope(); + + // Make sure only one thread can get in here. + State expected = State::RUNNING; + if (!m_state.compare_exchange_strong(expected, State::STOPPING)){ + return; + } + + if (!error_message.empty()){ + ReadSpinLock lg(m_state_lock); + m_error_message = std::move(error_message); + } + + // Wake everyone up. + { + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); + } + m_retransmit_thread.join(); + + { + ReadSpinLock lg(m_state_lock, "PABotBase::stop()"); + + // Send a stop request, but don't wait for a response that we may never + // receive. + pabb_MsgRequestStop params; + uint64_t seqnum = m_send_seq; + seqnum_t seqnum_s = (seqnum_t)seqnum; + memcpy(¶ms, &seqnum_s, sizeof(seqnum_t)); +// try_issue_request(params); +// m_state.store(State::STOPPING, std::memory_order_release); + BotBaseMessage stop_request(PABB_MSG_REQUEST_STOP, std::string((char*)¶ms, sizeof(params))); + send_message(stop_request, false); + } + + // Must call this to stop the receiver thread from making any more async + // calls into this class which touch its fields. + safely_stop(); + + // Now the receiver thread is dead. Nobody else is touching this class so + // it is safe to destruct. + m_state.store(State::STOPPED, std::memory_order_release); +} +void PABotBase::notify_all(){ + std::unique_lock lg(m_sleep_lock); + m_cv.notify_all(); +} + +void PABotBase::set_queue_limit(size_t queue_limit){ + m_max_pending_requests.store(queue_limit, std::memory_order_relaxed); +} + +void PABotBase::wait_for_all_requests(const Cancellable* cancelled){ + auto scope_check = m_sanitizer.check_scope(); + + std::unique_lock lg(m_sleep_lock); + m_logger.log("Waiting for all requests to finish...", COLOR_DARKGREEN); + while (true){ + if (cancelled != nullptr && cancelled->cancelled()){ + throw OperationCancelledException(); + } + if (m_state.load(std::memory_order_acquire) != State::RUNNING){ + ReadSpinLock lg0(m_state_lock); + throw InvalidConnectionStateException(m_error_message); + } + { + ReadSpinLock lg1(m_state_lock, "PABotBase::wait_for_all_requests()"); +#if 0 + m_logger.log( + "Waiting for all requests to finish... (Requests: " + + std::to_string(m_pending_requests.size()) + + ", Commands: " + std::to_string(m_pending_commands.size()) + ")", + COLOR_DARKGREEN + ); +#endif + if (m_pending_requests.empty() && m_pending_commands.empty()){ + break; + } + } + m_cv.wait(lg); + } + +// m_logger.log("Waiting for all requests to finish... Completed.", COLOR_DARKGREEN); +} +void PABotBase::stop_all_commands(){ + +#ifdef DEBUG_STACK_TRACE + cout << __FILE__ << ":" << __LINE__ << " PABotBase::stop_all_commands()" << endl; + cout << "-----------------------------------------------------------------------------------------" << endl; +#if defined(__APPLE__) + void* callstack[128]; + int i, frames = backtrace(callstack, 128); + char** strs = backtrace_symbols(callstack, frames); + for (i = 0; i < frames; ++i) { + cout << strs[i] << endl; + } + free(strs); +#endif + cout << "-----------------------------------------------------------------------------------------" << endl; +#endif + + auto scope_check = m_sanitizer.check_scope(); + + uint64_t seqnum = issue_request(nullptr, SerialPABotBase::DeviceRequest_request_stop(), true, true); + clear_all_active_commands(seqnum); +} +void PABotBase::next_command_interrupt(){ + auto scope_check = m_sanitizer.check_scope(); + + uint64_t seqnum = issue_request(nullptr, SerialPABotBase::DeviceRequest_next_command_interrupt(), true, true); + clear_all_active_commands(seqnum); +} +void PABotBase::clear_all_active_commands(uint64_t seqnum){ + auto scope_check = m_sanitizer.check_scope(); + + // Remove all commands at or before the specified seqnum. + std::lock_guard lg0(m_sleep_lock); + WriteSpinLock lg1(m_state_lock, "PABotBase::next_command_interrupt()"); + m_logger.log("Clearing all active commands... (Commands: " + std::to_string(m_pending_commands.size()) + ")", COLOR_DARKGREEN); + + m_cv.notify_all(); + + if (m_pending_commands.empty()){ + return; + } + + // Remove all active commands up to the seqnum. + while (true){ + auto iter = m_pending_commands.begin(); + if (iter == m_pending_commands.end() || iter->first > seqnum){ + break; + } + iter->second.sanitizer.check_usage(); + + // We cannot remove un-acked messages from our buffer. If an un-acked + // message is dropped and the receiver is still waiting for it, it will + // wait forever since we will never retransmit. + + if (iter->second.state == AckState::NOT_ACKED){ + // Convert the command into a no-op request. + SerialPABotBase::DeviceRequest_program_id request; + BotBaseMessage message = request.message(); + seqnum_t seqnum_s = (seqnum_t)iter->first; + memcpy(&message.body[0], &seqnum_s, sizeof(seqnum_t)); + +// cout << "removing = " << seqnum_s << ", " << (int)iter->second.state << endl; + + std::pair::iterator, bool> ret = m_pending_requests.emplace( + std::piecewise_construct, + std::forward_as_tuple(iter->first), + std::forward_as_tuple() + ); + if (!ret.second){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Duplicate sequence number: " + std::to_string(seqnum)); + } + + // This block will never throw. + { + PendingRequest& handle = ret.first->second; + handle.silent_remove = true; + handle.request = std::move(message); + handle.first_sent = current_time(); + } + } + + m_pending_commands.erase(iter); + } +} +template +uint64_t PABotBase::infer_full_seqnum(const Map& map, seqnum_t seqnum) const{ + auto scope_check = m_sanitizer.check_scope(); + + // The protocol uses a 32-bit seqnum that wraps around. For our purposes of + // retransmits, we use a full 64-bit seqnum to maintain sorting order + // across the wrap-arounds. + + // Since the oldest unacked messaged will never be more than 63 (MAX_SEQNUM_GAP) + // requests old, there is no ambiguity on which request is being referred + // to with just the lower 32 bits. + // Here we infer the upper 32 bits of the seqnum to obtain the full 64-bit + // seqnum that we need to index our map. + + // This needs to be called inside the lock. Furthermore, the map must not + // be empty. If it is empty, we know we don't have it and can drop it + // before we even call this function. + + // Figure out the upper 32 bits of the seqnum. + uint64_t lo = map.begin()->first; + uint64_t hi = map.rbegin()->first; + uint64_t lo_candidate = (lo & 0xffffffff00000000) | seqnum; + uint64_t hi_candidate = (hi & 0xffffffff00000000) | seqnum; + return lo_candidate >= lo + ? lo_candidate + : hi_candidate; +} + +uint64_t PABotBase::oldest_live_seqnum() const{ + auto scope_check = m_sanitizer.check_scope(); + + // Must call under state lock. + uint64_t oldest = m_send_seq; + if (!m_pending_requests.empty()){ + oldest = std::min(oldest, m_pending_requests.begin()->first); + } + if (!m_pending_commands.empty()){ + oldest = std::min(oldest, m_pending_commands.begin()->first); + } + return oldest; +} + +template +void PABotBase::process_ack_request(BotBaseMessage message){ + auto scope_check = m_sanitizer.check_scope(); + + if constexpr (!variable_length){ + if (message.body.size() != sizeof(Params)){ + m_sniffer->log("Ignoring message with invalid size."); + return; + } + } + const Params* params = (const Params*)message.body.c_str(); + seqnum_t seqnum = params->seqnum; + + AckState state; + { + WriteSpinLock lg(m_state_lock, "PABotBase::process_ack_request()"); + + if (m_pending_requests.empty()){ + m_sniffer->log("Unexpected request ack message: seqnum = " + std::to_string(seqnum)); + return; + } + + uint64_t full_seqnum = infer_full_seqnum(m_pending_requests, seqnum); + std::map::iterator iter = m_pending_requests.find(full_seqnum); + if (iter == m_pending_requests.end()){ + m_sniffer->log("Unexpected request ack message: seqnum = " + std::to_string(seqnum)); + return; + } + iter->second.sanitizer.check_usage(); + + state = iter->second.state; + if (state == AckState::NOT_ACKED){ + if (iter->second.silent_remove){ + m_pending_requests.erase(iter); + }else{ + iter->second.state = AckState::ACKED; + iter->second.ack = std::move(message); + } + } + } + + m_last_ack.store(current_time(), std::memory_order_release); + + switch (state){ + case AckState::NOT_ACKED: + { + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); + } + return; + case AckState::ACKED: + m_sniffer->log("Duplicate request ack message: seqnum = " + std::to_string(seqnum)); + return; + case AckState::FINISHED: + m_sniffer->log("Request ack on command finish: seqnum = " + std::to_string(seqnum)); + return; + } +} +template +void PABotBase::process_ack_command(BotBaseMessage message){ + auto scope_check = m_sanitizer.check_scope(); + + if (message.body.size() != sizeof(Params)){ + m_sniffer->log("Ignoring message with invalid size."); + return; + } + const Params* params = (const Params*)message.body.c_str(); + seqnum_t seqnum = params->seqnum; + + WriteSpinLock lg(m_state_lock, "PABotBase::process_ack_command()"); + + if (m_pending_commands.empty()){ + m_sniffer->log("Unexpected command ack message: seqnum = " + std::to_string(seqnum)); + return; + } + + uint64_t full_seqnum = infer_full_seqnum(m_pending_commands, seqnum); + auto iter = m_pending_commands.find(full_seqnum); + if (iter == m_pending_commands.end()){ + m_sniffer->log("Unexpected command ack message: seqnum = " + std::to_string(seqnum)); + return; + } + iter->second.sanitizer.check_usage(); + + m_last_ack.store(current_time(), std::memory_order_release); + + switch (iter->second.state){ + case AckState::NOT_ACKED: +// std::cout << "acked: " << full_seqnum << std::endl; + iter->second.state = AckState::ACKED; + iter->second.ack = std::move(message); + return; + case AckState::ACKED: + m_sniffer->log("Duplicate command ack message: seqnum = " + std::to_string(seqnum)); + return; + case AckState::FINISHED: + m_sniffer->log("Command ack on finished command: seqnum = " + std::to_string(seqnum)); + return; + } +} +template +void PABotBase::process_command_finished(BotBaseMessage message){ + auto scope_check = m_sanitizer.check_scope(); + + if (message.body.size() != sizeof(Params)){ + m_sniffer->log("Ignoring message with invalid size."); + return; + } + const Params* params = (const Params*)message.body.c_str(); + seqnum_t seqnum = params->seqnum; + seqnum_t command_seqnum = params->seq_of_original_command; + + // Send the ack first. + pabb_MsgAckRequest ack; + ack.seqnum = seqnum; +// m_send_queue.emplace_back((uint8_t)PABB_MSG_ACK, std::string((char*)&ack, sizeof(ack))); + + std::lock_guard lg0(m_sleep_lock); + WriteSpinLock lg1(m_state_lock, "PABotBase::process_command_finished() - 0"); + +#ifdef INTENTIONALLY_DROP_MESSAGES + if (rand() % 10 != 0){ + send_message(BotBaseMessage(PABB_MSG_ACK_REQUEST, std::string((char*)&ack, sizeof(ack))), false); + }else{ + m_logger.log("Intentionally dropping finish ack: " + std::to_string(seqnum), COLOR_RED); + } +#else + send_message(BotBaseMessage(PABB_MSG_ACK_REQUEST, std::string((char*)&ack, sizeof(ack))), false); +#endif + + if (m_pending_commands.empty()){ + m_sniffer->log( + "Unexpected command finished message: seqnum = " + std::to_string(seqnum) + + ", command_seqnum = " + std::to_string(command_seqnum) + ); + return; + } + + uint64_t full_seqnum = infer_full_seqnum(m_pending_commands, command_seqnum); + auto iter = m_pending_commands.find(full_seqnum); + if (iter == m_pending_commands.end()){ + m_sniffer->log( + "Unexpected command finished message: seqnum = " + std::to_string(seqnum) + + ", command_seqnum = " + std::to_string(command_seqnum) + ); + return; + } + iter->second.sanitizer.check_usage(); + + switch (iter->second.state){ + case AckState::NOT_ACKED: + case AckState::ACKED: + iter->second.state = AckState::FINISHED; + iter->second.ack = std::move(message); + if (iter->second.silent_remove){ + m_pending_commands.erase(iter); + } + m_cv.notify_all(); + return; + case AckState::FINISHED: + m_sniffer->log("Duplicate command finish: seqnum = " + std::to_string(seqnum)); + return; + } +} +void PABotBase::on_recv_message(BotBaseMessage message){ + auto scope_check = m_sanitizer.check_scope(); + + switch (message.type){ + case PABB_MSG_ACK_COMMAND: + process_ack_command(std::move(message)); + return; + case PABB_MSG_ACK_REQUEST: + process_ack_request(std::move(message)); + return; + case PABB_MSG_ACK_REQUEST_I8: + process_ack_request(std::move(message)); + return; + case PABB_MSG_ACK_REQUEST_I16: + process_ack_request(std::move(message)); + return; + case PABB_MSG_ACK_REQUEST_I32: + process_ack_request(std::move(message)); + return; + case PABB_MSG_ACK_REQUEST_DATA: + process_ack_request(std::move(message)); + return; + case PABB_MSG_ERROR_INVALID_TYPE:{ + if (message.body.size() != sizeof(pabb_MsgInfoInvalidType)){ + m_sniffer->log("Ignoring message with invalid size."); + return; + } + const pabb_MsgInfoInvalidType* params = (const pabb_MsgInfoInvalidType*)message.body.c_str(); + { + WriteSpinLock lg(m_state_lock); + m_error_message = "PABotBase incompatibility. Device does not recognize message type: " + std::to_string(params->type); + m_logger.log(m_error_message, COLOR_RED); + } + m_error.store(true, std::memory_order_release); + std::lock_guard lg0(m_sleep_lock); + m_cv.notify_all(); + } + case PABB_MSG_ERROR_MISSED_REQUEST:{ + if (message.body.size() != sizeof(pabb_MsgInfoMissedRequest)){ + m_sniffer->log("Ignoring message with invalid size."); + return; + } + const pabb_MsgInfoMissedRequest* params = (const pabb_MsgInfoMissedRequest*)message.body.c_str(); + if (params->seqnum == 1){ + { + WriteSpinLock lg(m_state_lock); + m_error_message = "Serial connection has been interrupted."; + m_logger.log(m_error_message, COLOR_RED); + } + m_error.store(true, std::memory_order_release); + std::lock_guard lg0(m_sleep_lock); + m_cv.notify_all(); + } + return; + } + case PABB_MSG_ERROR_DISCONNECTED:{ + m_logger.log("The console has disconnected the controller.", COLOR_RED); + { + WriteSpinLock lg(m_state_lock); + m_error_message = "Disconnected by console."; + } + m_error.store(true, std::memory_order_release); + std::lock_guard lg0(m_sleep_lock); + m_cv.notify_all(); + return; + } + case PABB_MSG_REQUEST_COMMAND_FINISHED:{ + process_command_finished(std::move(message)); + return; + } + } +} + +void PABotBase::retransmit_thread(){ + auto scope_check = m_sanitizer.check_scope(); + +// cout << "retransmit_thread()" << endl; + auto last_sent = current_time(); + while (m_state.load(std::memory_order_acquire) == State::RUNNING){ + auto now = current_time(); + + if (now - last_sent < m_retransmit_delay){ + std::unique_lock lg(m_sleep_lock); + if (m_state.load(std::memory_order_acquire) != State::RUNNING){ + break; + } + if (m_error.load(std::memory_order_acquire)){ + break; + } + m_cv.wait_for(lg, m_retransmit_delay); + continue; + } + + // Process retransmits. + WriteSpinLock lg(m_state_lock, "PABotBase::retransmit_thread()"); +// std::cout << "retransmit_thread - m_pending_messages.size(): " << m_pending_messages.size() << std::endl; +// cout << "m_pending_messages.size()" << endl; + + // Retransmit + // Iterate through all pending requests and retransmit them in + // chronological order. ~~Skip the ones that are new.~~ + // (Don't skip the new ones since it will lead to gaps.) + + // Gather together all requests/commands. Sort them by seqnum and + // resend everything. + + WallClock oldest = last_sent; + + std::map messages; + for (auto& item : m_pending_requests){ + item.second.sanitizer.check_usage(); + if (item.second.state == AckState::NOT_ACKED){ + oldest = std::max(oldest, item.second.first_sent); + messages[item.first] = &item.second.request; + } + } + for (auto& item : m_pending_commands){ + item.second.sanitizer.check_usage(); + if (item.second.state == AckState::NOT_ACKED){ + oldest = std::max(oldest, item.second.first_sent); + messages[item.first] = &item.second.request; + } + } + + if (!messages.empty() && now - oldest >= m_retransmit_delay){ + for (const auto& item : messages){ + send_message(*item.second, true); + } + } + +#if 0 + for (auto& item : m_pending_requests){ + item.second.sanitizer.check_usage(); + if (item.second.state == AckState::NOT_ACKED && + current_time() - item.second.first_sent >= m_retransmit_delay + ){ + send_message(item.second.request, true); + } + } + for (auto& item : m_pending_commands){ + item.second.sanitizer.check_usage(); + if (item.second.state == AckState::NOT_ACKED && + current_time() - item.second.first_sent >= m_retransmit_delay + ){ + send_message(item.second.request, true); + } + } +#endif + + last_sent = current_time(); + } +// cout << "retransmit_thread() - exit" << endl; +} + + + + +uint64_t PABotBase::try_issue_request( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove, bool do_not_block +){ + auto scope_check = m_sanitizer.check_scope(); + + BotBaseMessage message = request.message(); + if (message.body.size() < sizeof(uint32_t)){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too short."); + } + if (message.body.size() > MAX_MESSAGE_SIZE){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); + } + + WriteSpinLock lg(m_state_lock, "PABotBase::try_issue_request()"); + if (cancelled != nullptr && cancelled->cancelled()){ + throw OperationCancelledException(); + } + + State state = m_state.load(std::memory_order_acquire); + if (state != State::RUNNING){ + throw InvalidConnectionStateException(m_error_message); + } + if (m_error.load(std::memory_order_acquire)){ + throw ConnectionException(&m_logger, m_error_message); + } + + size_t queue_limit = m_max_pending_requests.load(std::memory_order_relaxed); + + // Too many unacked requests in flight. + if (!do_not_block && inflight_requests() >= queue_limit){ +// m_logger.log("Message throttled due to too many inflight requests."); + return 0; + } + + // Don't get too far ahead of the oldest seqnum. + uint64_t seqnum = m_send_seq; + if (seqnum - oldest_live_seqnum() > MAX_SEQNUM_GAP){ + if (do_not_block){ + throw ConnectionException( + &m_logger, + "Connection has stalled for a long time. Assuming it is dead." + ); + } + return 0; + } + + seqnum_t seqnum_s = (seqnum_t)seqnum; + memcpy(&message.body[0], &seqnum_s, sizeof(seqnum_t)); + + std::pair::iterator, bool> ret = m_pending_requests.emplace( + std::piecewise_construct, + std::forward_as_tuple(seqnum), + std::forward_as_tuple() + ); + if (!ret.second){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Duplicate sequence number: " + std::to_string(seqnum)); + } + + m_send_seq = seqnum + 1; + + PendingRequest& handle = ret.first->second; + + handle.silent_remove = silent_remove; + handle.request = std::move(message); + handle.first_sent = current_time(); + +#ifdef INTENTIONALLY_DROP_MESSAGES + if (rand() % 10 != 0){ + send_message(handle.request, false); + }else{ + m_logger.log("Intentionally dropping request: " + std::to_string(seqnum), COLOR_RED); + } +#else + send_message(handle.request, false); +#endif + + return seqnum; +} +uint64_t PABotBase::try_issue_command( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove +){ + auto scope_check = m_sanitizer.check_scope(); + + BotBaseMessage message = request.message(); + if (message.body.size() < sizeof(uint32_t)){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too short."); + } + if (message.body.size() > MAX_MESSAGE_SIZE){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); + } + + WriteSpinLock lg(m_state_lock, "PABotBase::try_issue_command()"); + if (cancelled != nullptr && cancelled->cancelled()){ + throw OperationCancelledException(); + } + + State state = m_state.load(std::memory_order_acquire); + if (state != State::RUNNING){ + throw InvalidConnectionStateException(m_error_message); + } + if (m_error.load(std::memory_order_acquire)){ + throw ConnectionException(&m_logger, m_error_message); + } + + size_t queue_limit = m_max_pending_requests.load(std::memory_order_relaxed); + + // Command queue is full. + if (m_pending_commands.size() >= queue_limit){ +// cout << "Command queue is full" << endl; + return 0; + } + + // Too many unacked requests in flight. + if (inflight_requests() >= queue_limit){ +// m_logger.log("Message throttled due to too many inflight requests."); + return 0; + } + + // Don't get too far ahead of the oldest seqnum. + uint64_t seqnum = m_send_seq; + if (seqnum - oldest_live_seqnum() > MAX_SEQNUM_GAP){ + return 0; + } + + seqnum_t seqnum_s = (seqnum_t)seqnum; + memcpy(&message.body[0], &seqnum_s, sizeof(seqnum_t)); + + std::pair::iterator, bool> ret = m_pending_commands.emplace( + std::piecewise_construct, + std::forward_as_tuple(seqnum), + std::forward_as_tuple() + ); + if (!ret.second){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Duplicate sequence number: " + std::to_string(seqnum)); + } + + m_send_seq = seqnum + 1; + + PendingCommand& handle = ret.first->second; + + handle.silent_remove = silent_remove; + handle.request = std::move(message); + handle.first_sent = current_time(); + +#ifdef INTENTIONALLY_DROP_MESSAGES + if (rand() % 10 != 0){ + send_message(handle.request, false); + }else{ + m_logger.log("Intentionally dropping command: " + std::to_string(seqnum), COLOR_RED); + } +#else + send_message(handle.request, false); +#endif + + return seqnum; +} +uint64_t PABotBase::issue_request( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove, bool do_not_block +){ + auto scope_check = m_sanitizer.check_scope(); + + // Issue a request and return. + // + // If it cannot be issued (because we're over the limits), this function + // will wait until it can be issued. + // + // The "silent_remove" parameter determines what to do when the + // ack (for a request) or a finish (for a command) is received. + // + // If (silent_remove = true), the receiving thread will remove the request + // from the map and do nothing else. This is for async commands. + // + // If (silent_remove = false), the receiving thread will not remove the + // request. Instead, it will notify whatever thread is waiting for the + // result. That waiting thread will process the return value (if any) and + // remove the request from the map. This is for synchronous commands where + // the function waits for the command to finish before returning. + // + + while (true){ + uint64_t seqnum = try_issue_request(cancelled, request, silent_remove, do_not_block); + if (seqnum != 0){ + return seqnum; + } + std::unique_lock lg(m_sleep_lock); + if (cancelled != nullptr && cancelled->cancelled()){ + throw OperationCancelledException(); + } + if (m_state.load(std::memory_order_acquire) != State::RUNNING){ + ReadSpinLock lg0(m_state_lock); + throw InvalidConnectionStateException(m_error_message); + } + if (m_error.load(std::memory_order_acquire)){ + ReadSpinLock lg0(m_state_lock); + throw ConnectionException(&m_logger, m_error_message); + } + m_cv.wait(lg); + } +} +uint64_t PABotBase::issue_command( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove +){ + auto scope_check = m_sanitizer.check_scope(); + + // Issue a command and return. + // + // If it cannot be issued (because we're over the limits), this function + // will wait until it can be issued. + // + // The "silent_remove" parameter determines what to do when the + // ack (for a request) or a finish (for a command) is received. + // + // If (silent_remove = true), the receiving thread will remove the request + // from the map and do nothing else. This is for async commands. + // + // If (silent_remove = false), the receiving thread will not remove the + // request. Instead, it will notify whatever thread is waiting for the + // result. That waiting thread will process the return value (if any) and + // remove the request from the map. This is for synchronous commands where + // the function waits for the command to finish before returning. + // + + while (true){ + uint64_t seqnum = try_issue_command(cancelled, request, silent_remove); + if (seqnum != 0){ + return seqnum; + } + std::unique_lock lg(m_sleep_lock); + if (cancelled != nullptr && cancelled->cancelled()){ + throw OperationCancelledException(); + } + if (m_state.load(std::memory_order_acquire) != State::RUNNING){ + ReadSpinLock lg0(m_state_lock); + throw InvalidConnectionStateException(m_error_message); + } + if (m_error.load(std::memory_order_acquire)){ + ReadSpinLock lg0(m_state_lock); + throw ConnectionException(&m_logger, m_error_message); + } + m_cv.wait(lg); + } +} + +bool PABotBase::try_issue_request( + const BotBaseRequest& request, + const Cancellable* cancelled +){ + auto scope_check = m_sanitizer.check_scope(); + + if (!request.is_command()){ + return try_issue_request(cancelled, request, true, false) != 0; + }else{ + return try_issue_command(cancelled, request, true) != 0; + } +} +void PABotBase::issue_request( + const BotBaseRequest& request, + const Cancellable* cancelled +){ + auto scope_check = m_sanitizer.check_scope(); + + if (!request.is_command()){ + issue_request(cancelled, request, true, false); + }else{ + issue_command(cancelled, request, true); + } +} + +BotBaseMessage PABotBase::issue_request_and_wait( + const BotBaseRequest& request, + const Cancellable* cancelled +){ + auto scope_check = m_sanitizer.check_scope(); + + if (request.is_command()){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "This function only supports requests."); + } + + uint64_t seqnum = issue_request(cancelled, request, false, false); + return wait_for_request(seqnum, cancelled); +} +BotBaseMessage PABotBase::wait_for_request(uint64_t seqnum, const Cancellable* cancelled){ + auto scope_check = m_sanitizer.check_scope(); + + std::unique_lock lg(m_sleep_lock); + while (true){ + if (cancelled && cancelled->cancelled()){ + throw OperationCancelledException(); + } + + { + WriteSpinLock slg(m_state_lock, "PABotBase::issue_request_and_wait()"); + auto iter = m_pending_requests.find(seqnum); + if (iter == m_pending_requests.end()){ + throw OperationCancelledException(); + } + iter->second.sanitizer.check_usage(); + + State state = m_state.load(std::memory_order_acquire); + if (state != State::RUNNING){ + m_pending_requests.erase(iter); + m_cv.notify_all(); + throw InvalidConnectionStateException(m_error_message); + } + if (m_error.load(std::memory_order_acquire)){ + m_pending_requests.erase(iter); + m_cv.notify_all(); + throw ConnectionException(&m_logger, m_error_message); + } + if (iter->second.state == AckState::ACKED){ + BotBaseMessage ret = std::move(iter->second.ack); + m_pending_requests.erase(iter); + m_cv.notify_all(); + return ret; + } + } + m_cv.wait(lg); + } +} + + + + +} diff --git a/ClientSource/Connection/PABotBase.h b/ClientSource/Connection/PABotBase.h index 9d87e590eb..aed97ef31c 100644 --- a/ClientSource/Connection/PABotBase.h +++ b/ClientSource/Connection/PABotBase.h @@ -1,211 +1,211 @@ -/* Pokemon Automation Bot Base - * - * From: https://github.com/PokemonAutomation/ - * - * This is the main PABotBase class. - * - * This class represents a connection to a single PABotBase instance running on - * a user specified COM port. You can have multiple instances of this class if - * you are connecting to multiple devices at once. - * - * This class implements the full communication protocol. So you directly - * invoke commands from this class which will be passed on to the Arduino/Teensy. - * - * Requests and commands may be asynchronous. They may return before the device - * executes it. - * - * - * Note that button commands will only work if the device is running PABotBase - * and is not already running a command. The regular programs do not listen to - * button press requests since they are already running their own program. - * - */ - -#ifndef PokemonAutomation_PABotBase_H -#define PokemonAutomation_PABotBase_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "ClientSource/Connection/MessageLogger.h" -#include "ClientSource/Connection/PABotBaseConnection.h" -#include "BotBase.h" -#include "BotBaseMessage.h" - - -namespace PokemonAutomation{ - - -class PABotBase : public BotBaseController, private PABotBaseConnection{ - static const seqnum_t MAX_SEQNUM_GAP = (seqnum_t)-1 >> 2; - -public: - PABotBase( - Logger& logger, - std::unique_ptr connection, - MessageLogger* message_logger = nullptr, - std::chrono::milliseconds retransmit_delay = std::chrono::milliseconds(100) - ); - virtual ~PABotBase(); - - using PABotBaseConnection::set_sniffer; - - void connect(); - virtual void stop(std::string error_message = "") override; - - std::chrono::time_point last_ack() const{ - return m_last_ack.load(std::memory_order_acquire); - } - - virtual Logger& logger() override{ - return m_logger; - } - virtual State state() const override{ - return m_state.load(std::memory_order_acquire); - } - virtual void notify_all() override; - - virtual size_t queue_limit() const override{ - return m_max_pending_requests.load(std::memory_order_relaxed); - } - void set_queue_limit(size_t queue_limit); - -public: - // Basic Requests - - virtual void wait_for_all_requests(const Cancellable* cancelled = nullptr) override; - virtual void stop_all_commands() override; - virtual void next_command_interrupt() override; - - -public: - // For Command Implementations - -// using BotBaseController::try_issue_request; - using BotBaseController::issue_request; - using BotBaseController::issue_request_and_wait; - - -private: - enum class AckState{ - NOT_ACKED, - ACKED, - FINISHED, - }; - struct PendingRequest{ - AckState state = AckState::NOT_ACKED; - bool silent_remove; - BotBaseMessage request; - BotBaseMessage ack; - WallClock first_sent; - LifetimeSanitizer sanitizer; - }; - struct PendingCommand{ - AckState state = AckState::NOT_ACKED; - bool silent_remove; - BotBaseMessage request; - BotBaseMessage ack; - WallClock first_sent; - LifetimeSanitizer sanitizer; - }; - - template - uint64_t infer_full_seqnum(const Map& map, seqnum_t seqnum) const; - - uint64_t oldest_live_seqnum() const; - - template - void process_ack_request(BotBaseMessage message); - template - void process_ack_command(BotBaseMessage message); - - template void process_command_finished(BotBaseMessage message); - virtual void on_recv_message(BotBaseMessage message) override; - - void clear_all_active_commands(uint64_t seqnum); - - void retransmit_thread(); - -private: - size_t inflight_requests(); - - // Returns the seqnum of the request. If failed, returns zero. - uint64_t try_issue_request( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove, bool do_not_block - ); - uint64_t try_issue_command( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove - ); - - // Returns the seqnum of the request. - uint64_t issue_request( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove, bool do_not_block - ); - uint64_t issue_command( - const Cancellable* cancelled, - const BotBaseRequest& request, - bool silent_remove - ); - -public: - virtual bool try_issue_request( - const BotBaseRequest& request, - const Cancellable* cancelled - ) override; - virtual void issue_request( - const BotBaseRequest& request, - const Cancellable* cancelled - ) override; - virtual BotBaseMessage issue_request_and_wait( - const BotBaseRequest& request, - const Cancellable* cancelled - ) override; - -private: - BotBaseMessage wait_for_request(uint64_t seqnum, const Cancellable* cancelled = nullptr); - -private: - Logger& m_logger; - - std::atomic m_max_pending_requests; - - uint64_t m_send_seq; - std::chrono::milliseconds m_retransmit_delay; - std::atomic> m_last_ack; - - std::map m_pending_requests; - std::map m_pending_commands; - - // If you need both locks, always acquire m_sleep_lock first! - SpinLock m_state_lock; - std::mutex m_sleep_lock; - - std::condition_variable m_cv; - std::atomic m_state; - std::atomic m_error; - std::string m_error_message; - std::thread m_retransmit_thread; - - LifetimeSanitizer m_sanitizer; -}; - - - - - - - -} - -#endif +/* Pokemon Automation Bot Base + * + * From: https://github.com/PokemonAutomation/ + * + * This is the main PABotBase class. + * + * This class represents a connection to a single PABotBase instance running on + * a user specified COM port. You can have multiple instances of this class if + * you are connecting to multiple devices at once. + * + * This class implements the full communication protocol. So you directly + * invoke commands from this class which will be passed on to the Arduino/Teensy. + * + * Requests and commands may be asynchronous. They may return before the device + * executes it. + * + * + * Note that button commands will only work if the device is running PABotBase + * and is not already running a command. The regular programs do not listen to + * button press requests since they are already running their own program. + * + */ + +#ifndef PokemonAutomation_PABotBase_H +#define PokemonAutomation_PABotBase_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "ClientSource/Connection/MessageLogger.h" +#include "ClientSource/Connection/PABotBaseConnection.h" +#include "BotBase.h" +#include "BotBaseMessage.h" + + +namespace PokemonAutomation{ + + +class PABotBase : public BotBaseController, private PABotBaseConnection{ + static const seqnum_t MAX_SEQNUM_GAP = (seqnum_t)-1 >> 2; + +public: + PABotBase( + Logger& logger, + std::unique_ptr connection, + MessageLogger* message_logger = nullptr, + std::chrono::milliseconds retransmit_delay = std::chrono::milliseconds(100) + ); + virtual ~PABotBase(); + + using PABotBaseConnection::set_sniffer; + + void connect(); + virtual void stop(std::string error_message = "") override; + + std::chrono::time_point last_ack() const{ + return m_last_ack.load(std::memory_order_acquire); + } + + virtual Logger& logger() override{ + return m_logger; + } + virtual State state() const override{ + return m_state.load(std::memory_order_acquire); + } + virtual void notify_all() override; + + virtual size_t queue_limit() const override{ + return m_max_pending_requests.load(std::memory_order_relaxed); + } + void set_queue_limit(size_t queue_limit); + +public: + // Basic Requests + + virtual void wait_for_all_requests(const Cancellable* cancelled = nullptr) override; + virtual void stop_all_commands() override; + virtual void next_command_interrupt() override; + + +public: + // For Command Implementations + +// using BotBaseController::try_issue_request; + using BotBaseController::issue_request; + using BotBaseController::issue_request_and_wait; + + +private: + enum class AckState{ + NOT_ACKED, + ACKED, + FINISHED, + }; + struct PendingRequest{ + AckState state = AckState::NOT_ACKED; + bool silent_remove; + BotBaseMessage request; + BotBaseMessage ack; + WallClock first_sent; + LifetimeSanitizer sanitizer; + }; + struct PendingCommand{ + AckState state = AckState::NOT_ACKED; + bool silent_remove; + BotBaseMessage request; + BotBaseMessage ack; + WallClock first_sent; + LifetimeSanitizer sanitizer; + }; + + template + uint64_t infer_full_seqnum(const Map& map, seqnum_t seqnum) const; + + uint64_t oldest_live_seqnum() const; + + template + void process_ack_request(BotBaseMessage message); + template + void process_ack_command(BotBaseMessage message); + + template void process_command_finished(BotBaseMessage message); + virtual void on_recv_message(BotBaseMessage message) override; + + void clear_all_active_commands(uint64_t seqnum); + + void retransmit_thread(); + +private: + size_t inflight_requests(); + + // Returns the seqnum of the request. If failed, returns zero. + uint64_t try_issue_request( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove, bool do_not_block + ); + uint64_t try_issue_command( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove + ); + + // Returns the seqnum of the request. + uint64_t issue_request( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove, bool do_not_block + ); + uint64_t issue_command( + const Cancellable* cancelled, + const BotBaseRequest& request, + bool silent_remove + ); + +public: + virtual bool try_issue_request( + const BotBaseRequest& request, + const Cancellable* cancelled + ) override; + virtual void issue_request( + const BotBaseRequest& request, + const Cancellable* cancelled + ) override; + virtual BotBaseMessage issue_request_and_wait( + const BotBaseRequest& request, + const Cancellable* cancelled + ) override; + +private: + BotBaseMessage wait_for_request(uint64_t seqnum, const Cancellable* cancelled = nullptr); + +private: + Logger& m_logger; + + std::atomic m_max_pending_requests; + + uint64_t m_send_seq; + std::chrono::milliseconds m_retransmit_delay; + std::atomic> m_last_ack; + + std::map m_pending_requests; + std::map m_pending_commands; + + // If you need both locks, always acquire m_sleep_lock first! + SpinLock m_state_lock; + std::mutex m_sleep_lock; + + std::condition_variable m_cv; + std::atomic m_state; + std::atomic m_error; + std::string m_error_message; + std::thread m_retransmit_thread; + + LifetimeSanitizer m_sanitizer; +}; + + + + + + + +} + +#endif diff --git a/ClientSource/Connection/PABotBaseConnection.cpp b/ClientSource/Connection/PABotBaseConnection.cpp index 3863765e31..fbf25b6dfa 100644 --- a/ClientSource/Connection/PABotBaseConnection.cpp +++ b/ClientSource/Connection/PABotBaseConnection.cpp @@ -1,152 +1,152 @@ -/* Pokemon Automation Bot Base - Client Example - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/CRC32.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "ClientSource/Libraries/Logging.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "BotBaseMessage.h" -#include "PABotBaseConnection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -MessageSniffer null_sniffer; - -PABotBaseConnection::PABotBaseConnection(Logger& logger, std::unique_ptr connection) - : m_connection(std::move(connection)) - , m_logger(logger) - , m_sniffer(&null_sniffer) -{ - m_connection->add_listener(*this); -} -PABotBaseConnection::~PABotBaseConnection(){ - if (m_connection){ - safely_stop(); - } -} -void PABotBaseConnection::safely_stop(){ - if (m_connection){ - m_connection->stop(); - m_connection.reset(); - } -} - - -void PABotBaseConnection::set_sniffer(MessageSniffer* sniffer){ - if (sniffer == nullptr){ - sniffer = &null_sniffer; - } - m_sniffer = sniffer; -} - - -void PABotBaseConnection::send_zeros(uint8_t bytes){ - if (!m_connection){ - return; - } - - char ch = 0; - for (uint8_t c = 0; c < bytes; c++){ - m_connection->send(&ch, 1); -// Sleep(10); - } -} -void PABotBaseConnection::send_message(const BotBaseMessage& message, bool is_retransmit){ - if (!m_connection){ - return; - } - -// log("Sending: " + message_to_string(type, msg)); - m_sniffer->on_send(message, is_retransmit); - - size_t total_bytes = PABB_PROTOCOL_OVERHEAD + message.body.size(); - if (total_bytes > MAX_MESSAGE_SIZE){ - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); - } - - std::string buffer; - buffer += ~(uint8_t)total_bytes; - buffer += message.type; - buffer += message.body; - buffer += std::string(sizeof(uint32_t), 0); - pabb_crc32_write_to_message(&buffer[0], buffer.size()); - - m_connection->send(&buffer[0], buffer.size()); -} - - -void PABotBaseConnection::on_recv(const void* data, size_t bytes){ - // Push into receive buffer. - for (size_t c = 0; c < bytes; c++){ - m_recv_buffer.emplace_back(((const char*)data)[c]); - } - - while (!m_recv_buffer.empty()){ - uint8_t length = ~m_recv_buffer[0]; - - if (m_recv_buffer[0] == 0){ - m_sniffer->log("Skipping zero byte."); - m_recv_buffer.pop_front(); - continue; - } - - // Message is too short. - if (length < PABB_PROTOCOL_OVERHEAD){ - m_sniffer->log("Message is too short: bytes = " + std::to_string(length)); - m_recv_buffer.pop_front(); - continue; - } - - // Message is too long. - if (length > MAX_MESSAGE_SIZE){ - char ascii = ~length; - std::string text = ascii < 32 - ? ", ascii = " + std::to_string(ascii) - : std::string(", char = ") + ascii; - m_sniffer->log("Message is too long: bytes = " + std::to_string(length) + text); - m_recv_buffer.pop_front(); - continue; - } - - // Message is incomplete. - if (length > m_recv_buffer.size()){ - return; - } - - std::string message(m_recv_buffer.begin(), m_recv_buffer.begin() + length); - - // Verify checksum - { - // Calculate checksum. - uint32_t checksumA = pabb_crc32(0xffffffff, &message[0], length - sizeof(uint32_t)); - - // Read the checksum from the message. - uint32_t checksumE = ((uint32_t*)(&message[0] + length))[-1]; - - // Compare -// std::cout << checksumA << " / " << checksumE << std::endl; - if (checksumA != checksumE){ - m_sniffer->log("Invalid Checksum: bytes = " + std::to_string(length)); -// std::cout << checksumA << " / " << checksumE << std::endl; -// log(message_to_string(message[1], &message[2], length - PABB_PROTOCOL_OVERHEAD)); - m_recv_buffer.pop_front(); - continue; - } - } - m_recv_buffer.erase(m_recv_buffer.begin(), m_recv_buffer.begin() + length); - - BotBaseMessage msg(message[1], std::string(&message[2], length - PABB_PROTOCOL_OVERHEAD)); - m_sniffer->on_recv(msg); - on_recv_message(std::move(msg)); - } -} - - -} +/* Pokemon Automation Bot Base - Client Example + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/CRC32.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "ClientSource/Libraries/Logging.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "BotBaseMessage.h" +#include "PABotBaseConnection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +MessageSniffer null_sniffer; + +PABotBaseConnection::PABotBaseConnection(Logger& logger, std::unique_ptr connection) + : m_connection(std::move(connection)) + , m_logger(logger) + , m_sniffer(&null_sniffer) +{ + m_connection->add_listener(*this); +} +PABotBaseConnection::~PABotBaseConnection(){ + if (m_connection){ + safely_stop(); + } +} +void PABotBaseConnection::safely_stop(){ + if (m_connection){ + m_connection->stop(); + m_connection.reset(); + } +} + + +void PABotBaseConnection::set_sniffer(MessageSniffer* sniffer){ + if (sniffer == nullptr){ + sniffer = &null_sniffer; + } + m_sniffer = sniffer; +} + + +void PABotBaseConnection::send_zeros(uint8_t bytes){ + if (!m_connection){ + return; + } + + char ch = 0; + for (uint8_t c = 0; c < bytes; c++){ + m_connection->send(&ch, 1); +// Sleep(10); + } +} +void PABotBaseConnection::send_message(const BotBaseMessage& message, bool is_retransmit){ + if (!m_connection){ + return; + } + +// log("Sending: " + message_to_string(type, msg)); + m_sniffer->on_send(message, is_retransmit); + + size_t total_bytes = PABB_PROTOCOL_OVERHEAD + message.body.size(); + if (total_bytes > MAX_MESSAGE_SIZE){ + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Message is too long."); + } + + std::string buffer; + buffer += ~(uint8_t)total_bytes; + buffer += message.type; + buffer += message.body; + buffer += std::string(sizeof(uint32_t), 0); + pabb_crc32_write_to_message(&buffer[0], buffer.size()); + + m_connection->send(&buffer[0], buffer.size()); +} + + +void PABotBaseConnection::on_recv(const void* data, size_t bytes){ + // Push into receive buffer. + for (size_t c = 0; c < bytes; c++){ + m_recv_buffer.emplace_back(((const char*)data)[c]); + } + + while (!m_recv_buffer.empty()){ + uint8_t length = ~m_recv_buffer[0]; + + if (m_recv_buffer[0] == 0){ + m_sniffer->log("Skipping zero byte."); + m_recv_buffer.pop_front(); + continue; + } + + // Message is too short. + if (length < PABB_PROTOCOL_OVERHEAD){ + m_sniffer->log("Message is too short: bytes = " + std::to_string(length)); + m_recv_buffer.pop_front(); + continue; + } + + // Message is too long. + if (length > MAX_MESSAGE_SIZE){ + char ascii = ~length; + std::string text = ascii < 32 + ? ", ascii = " + std::to_string(ascii) + : std::string(", char = ") + ascii; + m_sniffer->log("Message is too long: bytes = " + std::to_string(length) + text); + m_recv_buffer.pop_front(); + continue; + } + + // Message is incomplete. + if (length > m_recv_buffer.size()){ + return; + } + + std::string message(m_recv_buffer.begin(), m_recv_buffer.begin() + length); + + // Verify checksum + { + // Calculate checksum. + uint32_t checksumA = pabb_crc32(0xffffffff, &message[0], length - sizeof(uint32_t)); + + // Read the checksum from the message. + uint32_t checksumE = ((uint32_t*)(&message[0] + length))[-1]; + + // Compare +// std::cout << checksumA << " / " << checksumE << std::endl; + if (checksumA != checksumE){ + m_sniffer->log("Invalid Checksum: bytes = " + std::to_string(length)); +// std::cout << checksumA << " / " << checksumE << std::endl; +// log(message_to_string(message[1], &message[2], length - PABB_PROTOCOL_OVERHEAD)); + m_recv_buffer.pop_front(); + continue; + } + } + m_recv_buffer.erase(m_recv_buffer.begin(), m_recv_buffer.begin() + length); + + BotBaseMessage msg(message[1], std::string(&message[2], length - PABB_PROTOCOL_OVERHEAD)); + m_sniffer->on_recv(msg); + on_recv_message(std::move(msg)); + } +} + + +} diff --git a/ClientSource/Connection/PABotBaseConnection.h b/ClientSource/Connection/PABotBaseConnection.h index 758dc94dce..f70867f9f3 100644 --- a/ClientSource/Connection/PABotBaseConnection.h +++ b/ClientSource/Connection/PABotBaseConnection.h @@ -1,64 +1,64 @@ -/* PABotBase Connection - * - * From: https://github.com/PokemonAutomation/ - * - * This class wraps a raw SerialConnection object and applies the - * communication protocol on top of it. It automatically throws out bad - * messsages and passes only the relevant message body onto the child - * listener class. - * - * This class does not handle retransmissions. - * - */ - -#ifndef PokemonAutomation_PABotBaseConnection_H -#define PokemonAutomation_PABotBaseConnection_H - -#include -#include -//#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "BotBase.h" -#include "MessageSniffer.h" -#include "StreamInterface.h" - -namespace PokemonAutomation{ - - -// None the functions in this class are thread-safe. It is up to -// the child class to wrap and make them thread-safe. -class PABotBaseConnection : public StreamListener{ -public: - static const size_t MAX_MESSAGE_SIZE = 64; - -public: - PABotBaseConnection(Logger& logger, std::unique_ptr connection); - virtual ~PABotBaseConnection(); - - void set_sniffer(MessageSniffer* sniffer); - -public: - void send_zeros(uint8_t bytes = MAX_MESSAGE_SIZE); - void send_message(const BotBaseMessage& message, bool is_retransmit); - -protected: - // Not thread-safe with sends. - void safely_stop(); - -private: - virtual void on_recv(const void* data, size_t bytes) override; - virtual void on_recv_message(BotBaseMessage message) = 0; - -private: - std::unique_ptr m_connection; - std::deque m_recv_buffer; - -protected: - Logger& m_logger; - MessageSniffer* m_sniffer; -}; - - - -} - -#endif +/* PABotBase Connection + * + * From: https://github.com/PokemonAutomation/ + * + * This class wraps a raw SerialConnection object and applies the + * communication protocol on top of it. It automatically throws out bad + * messsages and passes only the relevant message body onto the child + * listener class. + * + * This class does not handle retransmissions. + * + */ + +#ifndef PokemonAutomation_PABotBaseConnection_H +#define PokemonAutomation_PABotBaseConnection_H + +#include +#include +//#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "BotBase.h" +#include "MessageSniffer.h" +#include "StreamInterface.h" + +namespace PokemonAutomation{ + + +// None the functions in this class are thread-safe. It is up to +// the child class to wrap and make them thread-safe. +class PABotBaseConnection : public StreamListener{ +public: + static const size_t MAX_MESSAGE_SIZE = 64; + +public: + PABotBaseConnection(Logger& logger, std::unique_ptr connection); + virtual ~PABotBaseConnection(); + + void set_sniffer(MessageSniffer* sniffer); + +public: + void send_zeros(uint8_t bytes = MAX_MESSAGE_SIZE); + void send_message(const BotBaseMessage& message, bool is_retransmit); + +protected: + // Not thread-safe with sends. + void safely_stop(); + +private: + virtual void on_recv(const void* data, size_t bytes) override; + virtual void on_recv_message(BotBaseMessage message) = 0; + +private: + std::unique_ptr m_connection; + std::deque m_recv_buffer; + +protected: + Logger& m_logger; + MessageSniffer* m_sniffer; +}; + + + +} + +#endif diff --git a/ClientSource/Connection/SerialConnection.h b/ClientSource/Connection/SerialConnection.h index 612a1f94d6..cdd771f8ef 100644 --- a/ClientSource/Connection/SerialConnection.h +++ b/ClientSource/Connection/SerialConnection.h @@ -1,16 +1,16 @@ -/* Serial Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialConnection_H -#define PokemonAutomation_SerialConnection_H - -#ifdef _WIN32 -#include "SerialConnectionWinAPI.h" -#else -#include "SerialConnectionPOSIX.h" -#endif - -#endif +/* Serial Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialConnection_H +#define PokemonAutomation_SerialConnection_H + +#ifdef _WIN32 +#include "SerialConnectionWinAPI.h" +#else +#include "SerialConnectionPOSIX.h" +#endif + +#endif diff --git a/ClientSource/Connection/SerialConnectionPOSIX.h b/ClientSource/Connection/SerialConnectionPOSIX.h index 680770b7ee..f240a6b0b0 100644 --- a/ClientSource/Connection/SerialConnectionPOSIX.h +++ b/ClientSource/Connection/SerialConnectionPOSIX.h @@ -1,170 +1,170 @@ -/* Serial Connection for POSIX - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialConnectionPOSIX_H -#define PokemonAutomation_SerialConnectionPOSIX_H - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "StreamInterface.h" - -namespace PokemonAutomation{ - -class SerialConnection : public StreamConnection{ -public: - // UTF-8 - SerialConnection(const std::string& name, uint32_t baud_rate) - : m_exit(false) - { - speed_t baud = B9600; - switch (baud_rate){ - case 9600: baud = B9600; break; - case 19200: baud = B19200; break; - case 38400: baud = B38400; break; - case 57600: baud = B57600; break; - case 115200: baud = B115200; break; - default: - throw ConnectionException(nullptr, "Unsupported Baud Rate: " + std::to_string(baud_rate)); - } -// std::cout << "desired baud = " << baud << std::endl; - - m_fd = open(name.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); - if (m_fd == -1){ - int error = errno; - std::string str = "Unable to open serial connection. Error = " + std::to_string(error); - if (error == EACCES){ - str += " (permission denied)\nPlease run as sudo."; - } - throw ConnectionException(nullptr, std::move(str)); - } - - struct termios options; - if (tcgetattr(m_fd, &options) == -1){ - int error = errno; - throw ConnectionException(nullptr, "tcgetattr() failed. Error = " + std::to_string(error)); - } -// std::cout << "read baud = " << cfgetispeed(&options) << std::endl; -// std::cout << "write baud = " << cfgetospeed(&options) << std::endl; - - // Baud Rate - if (cfsetispeed(&options, baud) == -1){ - int error = errno; - throw ConnectionException(nullptr, "cfsetispeed() failed. Error = " + std::to_string(error)); - } - if (cfsetospeed(&options, baud) == -1){ - int error = errno; - throw ConnectionException(nullptr, "cfsetospeed() failed. Error = " + std::to_string(error)); - } -// std::cout << "write baud = " << cfgetispeed(&options) << std::endl; -// std::cout << "write baud = " << cfgetospeed(&options) << std::endl; - -#if 0 - std::cout << "BRKINT = " << (options.c_iflag & BRKINT) << std::endl; - std::cout << "ICRNL = " << (options.c_iflag & ICRNL) << std::endl; - std::cout << "IMAXBEL = " << (options.c_iflag & IMAXBEL) << std::endl; - std::cout << "OPOST = " << (options.c_oflag & OPOST) << std::endl; - std::cout << "ONLCR = " << (options.c_oflag & ONLCR) << std::endl; - std::cout << "ISIG = " << (options.c_lflag & ISIG) << std::endl; - std::cout << "ICANON = " << (options.c_lflag & ICANON) << std::endl; - std::cout << "ECHO = " << (options.c_lflag & ECHO) << std::endl; - std::cout << "ECHOE = " << (options.c_lflag & ECHOE) << std::endl; -#endif -#if 1 - // 8 bits, no parity, 1 stop bit - options.c_cflag &= ~PARENB; - options.c_cflag &= ~CSTOPB; - options.c_cflag &= ~CSIZE; - options.c_cflag |= CS8; -#endif -#if 1 - // Override all of Linux's stupid text defaults. - options.c_iflag &= ~BRKINT; - options.c_iflag &= ~ICRNL; - options.c_iflag &= ~(IXON | IXOFF); - options.c_iflag &= ~IMAXBEL; - options.c_oflag &= ~OPOST; - options.c_oflag &= ~ONLCR; - options.c_lflag &= ~ISIG; - options.c_lflag &= ~ICANON; - options.c_lflag &= ~ECHO; - options.c_lflag &= ~ECHOE; -#endif - - if (tcsetattr(m_fd, TCSANOW, &options) == -1){ - int error = errno; - throw ConnectionException(nullptr, "tcsetattr() failed. Error = " + std::to_string(error)); - } - - if (tcgetattr(m_fd, &options) == -1){ - int error = errno; - throw ConnectionException(nullptr, "tcgetattr() failed. Error = " + std::to_string(error)); - } - if (cfgetispeed(&options) != baud){ -// std::cout << "actual baud = " << cfgetispeed(&options) << std::endl; - throw ConnectionException(nullptr, "Unable to set input baud rate."); - } - if (cfgetospeed(&options) != baud){ -// std::cout << "actual baud = " << cfgetospeed(&options) << std::endl; - throw ConnectionException(nullptr, "Unable to set output baud rate."); - } - - // Start receiver thread. - try{ - m_listener = std::thread(run_with_catch, "SerialConnection::SerialConnection()", [this]{ recv_loop(); }); - }catch (...){ - close(m_fd); - throw; - } - } - - virtual ~SerialConnection(){ - if (!m_exit.load(std::memory_order_acquire)){ - stop(); - } - } - - virtual void stop() final{ - m_exit.store(true, std::memory_order_release); - close(m_fd); - m_listener.join(); - } - -private: - virtual void send(const void* data, size_t bytes){ - WriteSpinLock lg(m_send_lock, "SerialConnection::send()"); - bytes = write(m_fd, data, bytes); - } - - void recv_loop(){ - char buffer[32]; - while (!m_exit.load(std::memory_order_acquire)){ - ssize_t actual = read(m_fd, buffer, sizeof(buffer)); - if (actual > 0){ - on_recv(buffer, actual); - } - } - } - - - -private: - int m_fd; - std::atomic m_exit; - SpinLock m_send_lock; - std::thread m_listener; -}; - - -} - -#endif +/* Serial Connection for POSIX + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialConnectionPOSIX_H +#define PokemonAutomation_SerialConnectionPOSIX_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "StreamInterface.h" + +namespace PokemonAutomation{ + +class SerialConnection : public StreamConnection{ +public: + // UTF-8 + SerialConnection(const std::string& name, uint32_t baud_rate) + : m_exit(false) + { + speed_t baud = B9600; + switch (baud_rate){ + case 9600: baud = B9600; break; + case 19200: baud = B19200; break; + case 38400: baud = B38400; break; + case 57600: baud = B57600; break; + case 115200: baud = B115200; break; + default: + throw ConnectionException(nullptr, "Unsupported Baud Rate: " + std::to_string(baud_rate)); + } +// std::cout << "desired baud = " << baud << std::endl; + + m_fd = open(name.c_str(), O_RDWR | O_NOCTTY | O_NDELAY); + if (m_fd == -1){ + int error = errno; + std::string str = "Unable to open serial connection. Error = " + std::to_string(error); + if (error == EACCES){ + str += " (permission denied)\nPlease run as sudo."; + } + throw ConnectionException(nullptr, std::move(str)); + } + + struct termios options; + if (tcgetattr(m_fd, &options) == -1){ + int error = errno; + throw ConnectionException(nullptr, "tcgetattr() failed. Error = " + std::to_string(error)); + } +// std::cout << "read baud = " << cfgetispeed(&options) << std::endl; +// std::cout << "write baud = " << cfgetospeed(&options) << std::endl; + + // Baud Rate + if (cfsetispeed(&options, baud) == -1){ + int error = errno; + throw ConnectionException(nullptr, "cfsetispeed() failed. Error = " + std::to_string(error)); + } + if (cfsetospeed(&options, baud) == -1){ + int error = errno; + throw ConnectionException(nullptr, "cfsetospeed() failed. Error = " + std::to_string(error)); + } +// std::cout << "write baud = " << cfgetispeed(&options) << std::endl; +// std::cout << "write baud = " << cfgetospeed(&options) << std::endl; + +#if 0 + std::cout << "BRKINT = " << (options.c_iflag & BRKINT) << std::endl; + std::cout << "ICRNL = " << (options.c_iflag & ICRNL) << std::endl; + std::cout << "IMAXBEL = " << (options.c_iflag & IMAXBEL) << std::endl; + std::cout << "OPOST = " << (options.c_oflag & OPOST) << std::endl; + std::cout << "ONLCR = " << (options.c_oflag & ONLCR) << std::endl; + std::cout << "ISIG = " << (options.c_lflag & ISIG) << std::endl; + std::cout << "ICANON = " << (options.c_lflag & ICANON) << std::endl; + std::cout << "ECHO = " << (options.c_lflag & ECHO) << std::endl; + std::cout << "ECHOE = " << (options.c_lflag & ECHOE) << std::endl; +#endif +#if 1 + // 8 bits, no parity, 1 stop bit + options.c_cflag &= ~PARENB; + options.c_cflag &= ~CSTOPB; + options.c_cflag &= ~CSIZE; + options.c_cflag |= CS8; +#endif +#if 1 + // Override all of Linux's stupid text defaults. + options.c_iflag &= ~BRKINT; + options.c_iflag &= ~ICRNL; + options.c_iflag &= ~(IXON | IXOFF); + options.c_iflag &= ~IMAXBEL; + options.c_oflag &= ~OPOST; + options.c_oflag &= ~ONLCR; + options.c_lflag &= ~ISIG; + options.c_lflag &= ~ICANON; + options.c_lflag &= ~ECHO; + options.c_lflag &= ~ECHOE; +#endif + + if (tcsetattr(m_fd, TCSANOW, &options) == -1){ + int error = errno; + throw ConnectionException(nullptr, "tcsetattr() failed. Error = " + std::to_string(error)); + } + + if (tcgetattr(m_fd, &options) == -1){ + int error = errno; + throw ConnectionException(nullptr, "tcgetattr() failed. Error = " + std::to_string(error)); + } + if (cfgetispeed(&options) != baud){ +// std::cout << "actual baud = " << cfgetispeed(&options) << std::endl; + throw ConnectionException(nullptr, "Unable to set input baud rate."); + } + if (cfgetospeed(&options) != baud){ +// std::cout << "actual baud = " << cfgetospeed(&options) << std::endl; + throw ConnectionException(nullptr, "Unable to set output baud rate."); + } + + // Start receiver thread. + try{ + m_listener = std::thread(run_with_catch, "SerialConnection::SerialConnection()", [this]{ recv_loop(); }); + }catch (...){ + close(m_fd); + throw; + } + } + + virtual ~SerialConnection(){ + if (!m_exit.load(std::memory_order_acquire)){ + stop(); + } + } + + virtual void stop() final{ + m_exit.store(true, std::memory_order_release); + close(m_fd); + m_listener.join(); + } + +private: + virtual void send(const void* data, size_t bytes){ + WriteSpinLock lg(m_send_lock, "SerialConnection::send()"); + bytes = write(m_fd, data, bytes); + } + + void recv_loop(){ + char buffer[32]; + while (!m_exit.load(std::memory_order_acquire)){ + ssize_t actual = read(m_fd, buffer, sizeof(buffer)); + if (actual > 0){ + on_recv(buffer, actual); + } + } + } + + + +private: + int m_fd; + std::atomic m_exit; + SpinLock m_send_lock; + std::thread m_listener; +}; + + +} + +#endif diff --git a/ClientSource/Connection/SerialConnectionWinAPI.h b/ClientSource/Connection/SerialConnectionWinAPI.h index 1b3360184a..02362175b6 100644 --- a/ClientSource/Connection/SerialConnectionWinAPI.h +++ b/ClientSource/Connection/SerialConnectionWinAPI.h @@ -1,223 +1,223 @@ -/* Serial Connection for Windows - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialConnectionWinAPI_H -#define PokemonAutomation_SerialConnectionWinAPI_H - -#include -#include -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Unicode.h" -#include "Common/Cpp/PanicDump.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "ClientSource/Libraries/Logging.h" -#include "StreamInterface.h" - -namespace PokemonAutomation{ - -class SerialConnection : public StreamConnection{ -public: - // UTF-8 - SerialConnection(const std::string& name, uint32_t baud_rate) - : SerialConnection(name, utf8_to_wstr(name), baud_rate) - {} - SerialConnection(const std::string& name, const std::wstring& wname, uint32_t baud_rate) - : m_exit(false) - { - m_handle = CreateFileW( - (L"\\\\.\\" + wname).c_str(), - GENERIC_READ | GENERIC_WRITE, - 0, 0, - OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, - 0 - ); - if (m_handle == INVALID_HANDLE_VALUE){ - DWORD error = GetLastError(); - throw ConnectionException(nullptr, "Unable to open serial connection (" + name + "). Error = " + std::to_string(error)); - } - - DCB serial_params{0}; - serial_params.DCBlength = sizeof(serial_params); - - if (!GetCommState(m_handle, &serial_params)){ - DWORD error = GetLastError(); - CloseHandle(m_handle); - throw ConnectionException(nullptr, "GetCommState() failed. Error = " + std::to_string(error)); - } -// cout << "BaudRate = " << (int)serial_params.BaudRate << endl; -// cout << "ByteSize = " << (int)serial_params.ByteSize << endl; -// cout << "StopBits = " << (int)serial_params.StopBits << "0 means 1 bit" << endl; -// cout << "Parity = " << (int)serial_params.Parity << endl; - serial_params.BaudRate = baud_rate; - serial_params.ByteSize = 8; - serial_params.StopBits = 0; - serial_params.Parity = 0; - if (!SetCommState(m_handle, &serial_params)){ - DWORD error = GetLastError(); - CloseHandle(m_handle); - throw ConnectionException(nullptr, "SetCommState() failed. Error = " + std::to_string(error)); - } - -#if 1 - COMMTIMEOUTS timeouts{0}; - if (!GetCommTimeouts(m_handle, &timeouts)){ - DWORD error = GetLastError(); - CloseHandle(m_handle); - throw ConnectionException(nullptr, "GetCommTimeouts() failed. Error = " + std::to_string(error)); - } - - //std::cout << "ReadIntervalTimeout = " << timeouts.ReadIntervalTimeout << std::endl; - //std::cout << "ReadTotalTimeoutMultiplier = " << timeouts.ReadTotalTimeoutMultiplier << std::endl; - //std::cout << "ReadTotalTimeoutConstant = " << timeouts.ReadTotalTimeoutConstant << std::endl; - //std::cout << "WriteTotalTimeoutMultiplier = " << timeouts.WriteTotalTimeoutMultiplier << std::endl; - //std::cout << "WriteTotalTimeoutConstant = " << timeouts.WriteTotalTimeoutConstant << std::endl; - -#if 1 - timeouts = COMMTIMEOUTS{(DWORD)-1, 0, 0, 0, 100}; -#else - // Need to set a read timer. In some cases, a pending ReadFile() call - // will block a WriteFile() call until it returns - leading to a - // deadlock if the device isn't sending any information. - timeouts.ReadIntervalTimeout = 0; - timeouts.ReadTotalTimeoutMultiplier = 0; - timeouts.ReadTotalTimeoutConstant = 1; -#endif - if (!SetCommTimeouts(m_handle, &timeouts)){ - DWORD error = GetLastError(); - CloseHandle(m_handle); - throw ConnectionException(nullptr, "SetCommTimeouts() failed. Error = " + std::to_string(error)); - } -#endif - - // Start receiver thread. - try{ - m_listener = std::thread(run_with_catch, "SerialConnection::SerialConnection()", [this]{ recv_loop(); }); - }catch (...){ - CloseHandle(m_handle); - throw; - } - } - virtual ~SerialConnection(){ - if (!m_exit.load(std::memory_order_acquire)){ - stop(); - } - } - - virtual void stop() final{ - m_exit.store(true, std::memory_order_release); - CloseHandle(m_handle); - m_listener.join(); - } - -private: - void process_error(const std::string& message){ - m_errors++; - if (m_errors < 100 || m_errors % 1000 == 0){ - log(message); - } - - std::string clear_error; - DWORD comm_error; - if (ClearCommError(m_handle, &comm_error, nullptr) == 0){ - DWORD error = GetLastError(); - clear_error = "ClearCommError() failed. Error = " + std::to_string(error); - }else{ - clear_error = "ClearCommError error flag = " + std::to_string(comm_error); - } - - if (m_errors < 100 || m_errors % 1000 == 0){ - log(clear_error); - } - } - - - virtual void send(const void* data, size_t bytes){ - WriteSpinLock lg(m_send_lock, "SerialConnection::send()"); -#if 0 - for (size_t c = 0; c < bytes; c++){ - std::cout << "Send: " << (int)((const char*)data)[c] << std::endl; - } -#endif - -// std::cout << "start write" << std::endl; -// auto start = current_time(); - DWORD written; - if (WriteFile(m_handle, data, (DWORD)bytes, &written, nullptr) == 0 || bytes != written){ - DWORD error = GetLastError(); - process_error( - "Failed to write: " + std::to_string(written) + - " / " + std::to_string(bytes) + - ", error = " + std::to_string(error) - ); - } -// auto stop = current_time(); -// cout << "WriteFile() : " << std::chrono::duration_cast(stop - start).count() << endl; - -// std::cout << "end send()" << std::endl; - } - - void recv_loop(){ -// std::lock_guard lg(m_send_lock); - char buffer[32]; - auto last_recv = current_time(); - while (!m_exit.load(std::memory_order_acquire)){ -// auto start = current_time(); -// std::cout << "start read" << std::endl; - DWORD read; - if (ReadFile(m_handle, buffer, 32, &read, nullptr) == 0){ - DWORD error = GetLastError(); - process_error("ReadFile() failed. Error = " + std::to_string(error)); - } -// auto stop = current_time(); -// cout << "ReadFile() : " << std::chrono::duration_cast(stop - start).count() << endl; -// std::cout << "read = " << read << std::endl; -// set_timouts(); -#if 0 - for (size_t c = 0; c < read; c++){ - cout << "Recv: " << (int)buffer[c] << endl; - } -#endif - if (read != 0){ - on_recv(buffer, read); - last_recv = current_time(); - continue; - } - - -#if 1 -// auto start = current_time(); - Sleep(1); -// auto stop = current_time(); -#else - auto now = current_time(); - uint64_t millis_since_last_recv = std::chrono::duration_cast(now - last_recv).count(); - if (millis_since_last_recv > 100){ - Sleep(1); - }else{ - pause(); - } -#endif - } - } - -private: - HANDLE m_handle; - std::atomic m_exit; - uint64_t m_errors = 0; - SpinLock m_send_lock; - std::thread m_listener; -}; - - - -} - -#endif +/* Serial Connection for Windows + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialConnectionWinAPI_H +#define PokemonAutomation_SerialConnectionWinAPI_H + +#include +#include +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Unicode.h" +#include "Common/Cpp/PanicDump.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "ClientSource/Libraries/Logging.h" +#include "StreamInterface.h" + +namespace PokemonAutomation{ + +class SerialConnection : public StreamConnection{ +public: + // UTF-8 + SerialConnection(const std::string& name, uint32_t baud_rate) + : SerialConnection(name, utf8_to_wstr(name), baud_rate) + {} + SerialConnection(const std::string& name, const std::wstring& wname, uint32_t baud_rate) + : m_exit(false) + { + m_handle = CreateFileW( + (L"\\\\.\\" + wname).c_str(), + GENERIC_READ | GENERIC_WRITE, + 0, 0, + OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, + 0 + ); + if (m_handle == INVALID_HANDLE_VALUE){ + DWORD error = GetLastError(); + throw ConnectionException(nullptr, "Unable to open serial connection (" + name + "). Error = " + std::to_string(error)); + } + + DCB serial_params{0}; + serial_params.DCBlength = sizeof(serial_params); + + if (!GetCommState(m_handle, &serial_params)){ + DWORD error = GetLastError(); + CloseHandle(m_handle); + throw ConnectionException(nullptr, "GetCommState() failed. Error = " + std::to_string(error)); + } +// cout << "BaudRate = " << (int)serial_params.BaudRate << endl; +// cout << "ByteSize = " << (int)serial_params.ByteSize << endl; +// cout << "StopBits = " << (int)serial_params.StopBits << "0 means 1 bit" << endl; +// cout << "Parity = " << (int)serial_params.Parity << endl; + serial_params.BaudRate = baud_rate; + serial_params.ByteSize = 8; + serial_params.StopBits = 0; + serial_params.Parity = 0; + if (!SetCommState(m_handle, &serial_params)){ + DWORD error = GetLastError(); + CloseHandle(m_handle); + throw ConnectionException(nullptr, "SetCommState() failed. Error = " + std::to_string(error)); + } + +#if 1 + COMMTIMEOUTS timeouts{0}; + if (!GetCommTimeouts(m_handle, &timeouts)){ + DWORD error = GetLastError(); + CloseHandle(m_handle); + throw ConnectionException(nullptr, "GetCommTimeouts() failed. Error = " + std::to_string(error)); + } + + //std::cout << "ReadIntervalTimeout = " << timeouts.ReadIntervalTimeout << std::endl; + //std::cout << "ReadTotalTimeoutMultiplier = " << timeouts.ReadTotalTimeoutMultiplier << std::endl; + //std::cout << "ReadTotalTimeoutConstant = " << timeouts.ReadTotalTimeoutConstant << std::endl; + //std::cout << "WriteTotalTimeoutMultiplier = " << timeouts.WriteTotalTimeoutMultiplier << std::endl; + //std::cout << "WriteTotalTimeoutConstant = " << timeouts.WriteTotalTimeoutConstant << std::endl; + +#if 1 + timeouts = COMMTIMEOUTS{(DWORD)-1, 0, 0, 0, 100}; +#else + // Need to set a read timer. In some cases, a pending ReadFile() call + // will block a WriteFile() call until it returns - leading to a + // deadlock if the device isn't sending any information. + timeouts.ReadIntervalTimeout = 0; + timeouts.ReadTotalTimeoutMultiplier = 0; + timeouts.ReadTotalTimeoutConstant = 1; +#endif + if (!SetCommTimeouts(m_handle, &timeouts)){ + DWORD error = GetLastError(); + CloseHandle(m_handle); + throw ConnectionException(nullptr, "SetCommTimeouts() failed. Error = " + std::to_string(error)); + } +#endif + + // Start receiver thread. + try{ + m_listener = std::thread(run_with_catch, "SerialConnection::SerialConnection()", [this]{ recv_loop(); }); + }catch (...){ + CloseHandle(m_handle); + throw; + } + } + virtual ~SerialConnection(){ + if (!m_exit.load(std::memory_order_acquire)){ + stop(); + } + } + + virtual void stop() final{ + m_exit.store(true, std::memory_order_release); + CloseHandle(m_handle); + m_listener.join(); + } + +private: + void process_error(const std::string& message){ + m_errors++; + if (m_errors < 100 || m_errors % 1000 == 0){ + log(message); + } + + std::string clear_error; + DWORD comm_error; + if (ClearCommError(m_handle, &comm_error, nullptr) == 0){ + DWORD error = GetLastError(); + clear_error = "ClearCommError() failed. Error = " + std::to_string(error); + }else{ + clear_error = "ClearCommError error flag = " + std::to_string(comm_error); + } + + if (m_errors < 100 || m_errors % 1000 == 0){ + log(clear_error); + } + } + + + virtual void send(const void* data, size_t bytes){ + WriteSpinLock lg(m_send_lock, "SerialConnection::send()"); +#if 0 + for (size_t c = 0; c < bytes; c++){ + std::cout << "Send: " << (int)((const char*)data)[c] << std::endl; + } +#endif + +// std::cout << "start write" << std::endl; +// auto start = current_time(); + DWORD written; + if (WriteFile(m_handle, data, (DWORD)bytes, &written, nullptr) == 0 || bytes != written){ + DWORD error = GetLastError(); + process_error( + "Failed to write: " + std::to_string(written) + + " / " + std::to_string(bytes) + + ", error = " + std::to_string(error) + ); + } +// auto stop = current_time(); +// cout << "WriteFile() : " << std::chrono::duration_cast(stop - start).count() << endl; + +// std::cout << "end send()" << std::endl; + } + + void recv_loop(){ +// std::lock_guard lg(m_send_lock); + char buffer[32]; + auto last_recv = current_time(); + while (!m_exit.load(std::memory_order_acquire)){ +// auto start = current_time(); +// std::cout << "start read" << std::endl; + DWORD read; + if (ReadFile(m_handle, buffer, 32, &read, nullptr) == 0){ + DWORD error = GetLastError(); + process_error("ReadFile() failed. Error = " + std::to_string(error)); + } +// auto stop = current_time(); +// cout << "ReadFile() : " << std::chrono::duration_cast(stop - start).count() << endl; +// std::cout << "read = " << read << std::endl; +// set_timouts(); +#if 0 + for (size_t c = 0; c < read; c++){ + cout << "Recv: " << (int)buffer[c] << endl; + } +#endif + if (read != 0){ + on_recv(buffer, read); + last_recv = current_time(); + continue; + } + + +#if 1 +// auto start = current_time(); + Sleep(1); +// auto stop = current_time(); +#else + auto now = current_time(); + uint64_t millis_since_last_recv = std::chrono::duration_cast(now - last_recv).count(); + if (millis_since_last_recv > 100){ + Sleep(1); + }else{ + pause(); + } +#endif + } + } + +private: + HANDLE m_handle; + std::atomic m_exit; + uint64_t m_errors = 0; + SpinLock m_send_lock; + std::thread m_listener; +}; + + + +} + +#endif diff --git a/ClientSource/Connection/StreamInterface.h b/ClientSource/Connection/StreamInterface.h index aefe6450bf..47272a9128 100644 --- a/ClientSource/Connection/StreamInterface.h +++ b/ClientSource/Connection/StreamInterface.h @@ -1,56 +1,56 @@ -/* Stream Connection Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StreamInterface_H -#define PokemonAutomation_StreamInterface_H - -#include -#include - -namespace PokemonAutomation{ - - -class StreamListener{ -public: - virtual void on_recv(const void* data, size_t bytes) = 0; -}; - - -class StreamConnection{ -public: - virtual ~StreamConnection(){} - virtual void stop() = 0; - - void add_listener(StreamListener& listener){ - std::lock_guard lg(m_listener_lock); - m_listeners.insert(&listener); - } - void remove_listener(StreamListener& listener){ - std::lock_guard lg(m_listener_lock); - m_listeners.erase(&listener); - } - - virtual void send(const void* data, size_t bytes) = 0; - -protected: - void on_recv(const void* data, size_t bytes){ - std::lock_guard lg(m_listener_lock); - for (StreamListener* listener : m_listeners){ - listener->on_recv(data, bytes); - } - } - -protected: - std::mutex m_listener_lock; - std::set m_listeners; -}; - - - - -} - -#endif +/* Stream Connection Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StreamInterface_H +#define PokemonAutomation_StreamInterface_H + +#include +#include + +namespace PokemonAutomation{ + + +class StreamListener{ +public: + virtual void on_recv(const void* data, size_t bytes) = 0; +}; + + +class StreamConnection{ +public: + virtual ~StreamConnection(){} + virtual void stop() = 0; + + void add_listener(StreamListener& listener){ + std::lock_guard lg(m_listener_lock); + m_listeners.insert(&listener); + } + void remove_listener(StreamListener& listener){ + std::lock_guard lg(m_listener_lock); + m_listeners.erase(&listener); + } + + virtual void send(const void* data, size_t bytes) = 0; + +protected: + void on_recv(const void* data, size_t bytes){ + std::lock_guard lg(m_listener_lock); + for (StreamListener* listener : m_listeners){ + listener->on_recv(data, bytes); + } + } + +protected: + std::mutex m_listener_lock; + std::set m_listeners; +}; + + + + +} + +#endif diff --git a/ClientSource/Libraries/Logging.cpp b/ClientSource/Libraries/Logging.cpp index a91903ddd5..44a4c0ca39 100644 --- a/ClientSource/Libraries/Logging.cpp +++ b/ClientSource/Libraries/Logging.cpp @@ -1,67 +1,67 @@ -/* Pokemon Automation Bot Base - Client Example - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Logging.h" - -namespace PokemonAutomation{ - -std::string current_time_to_str(){ - // Based off of: https://stackoverflow.com/questions/15957805/extract-year-month-day-etc-from-stdchronotime-point-in-c - - using namespace std; - using namespace std::chrono; - typedef duration >::type> days; - system_clock::time_point now = system_clock::now(); - system_clock::duration tp = now.time_since_epoch(); - days d = duration_cast(tp); - tp -= d; - hours h = duration_cast(tp); - tp -= h; - minutes m = duration_cast(tp); - tp -= m; - seconds s = duration_cast(tp); - tp -= s; - auto micros = 1000000 * tp.count() * system_clock::duration::period::num / system_clock::duration::period::den; - time_t tt = system_clock::to_time_t(now); -// tm utc_tm = *gmtime(&tt); - tm local_tm = *localtime(&tt); - - std::ostringstream ss; - ss << local_tm.tm_year + 1900 << '-'; - ss << tostr_padded(2, local_tm.tm_mon + 1) << '-'; - ss << tostr_padded(2, local_tm.tm_mday) << ' '; - ss << tostr_padded(2, local_tm.tm_hour) << ':'; - ss << tostr_padded(2, local_tm.tm_min) << ':'; - ss << tostr_padded(2, local_tm.tm_sec) << '.'; - ss << tostr_padded(6, micros); - - return ss.str(); -} - - - - -std::mutex logging_lock; - -void log(const std::ostringstream& ss){ - log(ss.str()); -} -void log(const std::string& msg){ - std::lock_guard lg(logging_lock); - std::cout << current_time_to_str() << " - " << msg << std::endl; -} - - - - - -} - +/* Pokemon Automation Bot Base - Client Example + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Logging.h" + +namespace PokemonAutomation{ + +std::string current_time_to_str(){ + // Based off of: https://stackoverflow.com/questions/15957805/extract-year-month-day-etc-from-stdchronotime-point-in-c + + using namespace std; + using namespace std::chrono; + typedef duration >::type> days; + system_clock::time_point now = system_clock::now(); + system_clock::duration tp = now.time_since_epoch(); + days d = duration_cast(tp); + tp -= d; + hours h = duration_cast(tp); + tp -= h; + minutes m = duration_cast(tp); + tp -= m; + seconds s = duration_cast(tp); + tp -= s; + auto micros = 1000000 * tp.count() * system_clock::duration::period::num / system_clock::duration::period::den; + time_t tt = system_clock::to_time_t(now); +// tm utc_tm = *gmtime(&tt); + tm local_tm = *localtime(&tt); + + std::ostringstream ss; + ss << local_tm.tm_year + 1900 << '-'; + ss << tostr_padded(2, local_tm.tm_mon + 1) << '-'; + ss << tostr_padded(2, local_tm.tm_mday) << ' '; + ss << tostr_padded(2, local_tm.tm_hour) << ':'; + ss << tostr_padded(2, local_tm.tm_min) << ':'; + ss << tostr_padded(2, local_tm.tm_sec) << '.'; + ss << tostr_padded(6, micros); + + return ss.str(); +} + + + + +std::mutex logging_lock; + +void log(const std::ostringstream& ss){ + log(ss.str()); +} +void log(const std::string& msg){ + std::lock_guard lg(logging_lock); + std::cout << current_time_to_str() << " - " << msg << std::endl; +} + + + + + +} + diff --git a/ClientSource/Libraries/Logging.h b/ClientSource/Libraries/Logging.h index b6a1e54476..a3e185808f 100644 --- a/ClientSource/Libraries/Logging.h +++ b/ClientSource/Libraries/Logging.h @@ -1,24 +1,24 @@ -/* Pokemon Automation Bot Base - Client Example - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Logging_H -#define PokemonAutomation_Logging_H - -#include -#include - -namespace PokemonAutomation{ - - -void log(const std::ostringstream& ss); -void log(const std::string& msg); - -std::string current_time_to_str(); - - - -} -#endif +/* Pokemon Automation Bot Base - Client Example + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Logging_H +#define PokemonAutomation_Logging_H + +#include +#include + +namespace PokemonAutomation{ + + +void log(const std::ostringstream& ss); +void log(const std::string& msg); + +std::string current_time_to_str(); + + + +} +#endif diff --git a/ClientSource/Libraries/MessageConverter.cpp b/ClientSource/Libraries/MessageConverter.cpp index a4d80616f6..457991793b 100644 --- a/ClientSource/Libraries/MessageConverter.cpp +++ b/ClientSource/Libraries/MessageConverter.cpp @@ -1,461 +1,461 @@ -/* Message Pretty Printing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include -#include -#include -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "Common/Cpp/Exceptions.h" -//#include "Common/Microcontroller/PABotBaseIDs.h" -//#include "Common/NintendoSwitch/NintendoSwitch_Protocol_PushButtons.h" -#include "ClientSource/Connection/BotBaseMessage.h" -#include "MessageConverter.h" - -namespace PokemonAutomation{ - - -std::map& converter_map(){ - static std::map converters; - return converters; -} -void register_message_converter(uint8_t type, MessageConverter converter){ - std::map& converters = converter_map(); - auto iter = converters.find(type); - if (iter != converters.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate message type."); - } - converters[type] = converter; -} - - -int register_message_converters_framework_errors(){ - register_message_converter( - PABB_MSG_ERROR_READY, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_READY - "; - if (body.size() != 0){ ss << "(invalid size)" << std::endl; return ss.str(); } - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_INVALID_MESSAGE, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_INVALID_MESSAGE - "; - if (body.size() != sizeof(pabb_MsgInfoInvalidMessage)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoInvalidMessage*)body.c_str(); - ss << "length = " << (unsigned)params->message_length; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_CHECKSUM_MISMATCH, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_CHECKSUM_MISMATCH - "; - if (body.size() != sizeof(pabb_MsgInfoChecksumMismatch)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoChecksumMismatch*)body.c_str(); - ss << "length = " << (unsigned)params->message_length; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_INVALID_TYPE, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_INVALID_TYPE - "; - if (body.size() != sizeof(pabb_MsgInfoInvalidType)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoInvalidType*)body.c_str(); - ss << "type = " << (unsigned)params->type; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_INVALID_REQUEST, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_INVALID_REQUEST - "; - if (body.size() != sizeof(pabb_MsgInfoInvalidRequest)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoInvalidRequest*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_MISSED_REQUEST, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_MISSED_REQUEST - "; - if (body.size() != sizeof(pabb_MsgInfoMissedRequest)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoMissedRequest*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_COMMAND_DROPPED, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_COMMAND_DROPPED - "; - if (body.size() != sizeof(pabb_MsgInfoCommandDropped)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoCommandDropped*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_WARNING, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_WARNING - "; - if (body.size() != sizeof(pabb_MsgInfoWARNING)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoWARNING*)body.c_str(); - ss << "error code = " << (unsigned)params->error_code; - switch (params->error_code){ - case 1: - ss << " (Device was slow to respond to USB request.)"; - break; - } - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ERROR_DISCONNECTED, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ERROR_DISCONNECTED - "; - if (body.size() != sizeof(pabb_MsgInfoDisconnected)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoDisconnected*)body.c_str(); - ss << "error code = " << params->error_code; - return ss.str(); - } - ); - return 0; -} -int register_message_converters_framework_acks(){ - register_message_converter( - PABB_MSG_ACK_COMMAND, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ACK_COMMAND - "; - if (body.size() != sizeof(pabb_MsgAckCommand)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgAckCommand*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ACK_REQUEST, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ACK_REQUEST - "; - if (body.size() != sizeof(pabb_MsgAckRequest)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgAckRequest*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ACK_REQUEST_I8, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ACK_REQUEST_I8 - "; - if (body.size() != sizeof(pabb_MsgAckRequestI8)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgAckRequestI8*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", message = " << (unsigned)params->data; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ACK_REQUEST_I16, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ACK_REQUEST_I16 - "; - if (body.size() != sizeof(pabb_MsgAckRequestI16)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgAckRequestI16*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", message = " << (unsigned)params->data; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ACK_REQUEST_I32, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ACK_REQUEST_I32 - "; - if (body.size() != sizeof(pabb_MsgAckRequestI32)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgAckRequestI32*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", message = " << params->data; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ACK_REQUEST_DATA, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ACK_REQUEST_DATA - "; -// if (body.size() != sizeof(pabb_MsgAckRequestI32)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgAckRequestI32*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", bytes = " << body.size() - sizeof(seqnum_t); - ss << ", data ="; - static const char HEX_DIGITS[] = "0123456789abcdef"; - for (size_t c = sizeof(seqnum_t); c < body.size(); c++){ - uint8_t byte = body[c]; - ss << " " << HEX_DIGITS[(byte >> 4)] << HEX_DIGITS[byte & 15]; - } - return ss.str(); - } - ); - return 0; -} -int register_message_converters_framework_requests(){ - register_message_converter( - PABB_MSG_SEQNUM_RESET, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_SEQNUM_RESET - "; - if (body.size() != sizeof(pabb_MsgInfoSeqnumReset)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoSeqnumReset*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_PROTOCOL_VERSION, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_PROTOCOL_VERSION - "; - if (body.size() != sizeof(pabb_MsgRequestProtocolVersion)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestProtocolVersion*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_PROGRAM_VERSION, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_PROGRAM_VERSION - "; - if (body.size() != sizeof(pabb_MsgRequestProgramVersion)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestProgramVersion*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_PROGRAM_ID, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_PROGRAM_ID - "; - if (body.size() != sizeof(pabb_MsgRequestProgramID)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestProgramID*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_CLOCK, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_CLOCK - "; - if (body.size() != sizeof(pabb_system_clock)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_system_clock*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_COMMAND_FINISHED, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_COMMAND_FINISHED - "; - if (body.size() != sizeof(pabb_MsgRequestCommandFinished)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestCommandFinished*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", seq_of_original_command = " << (unsigned)params->seq_of_original_command; - ss << ", finish_time = " << params->finish_time; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_STOP, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_STOP - "; - if (body.size() != sizeof(pabb_MsgRequestStop)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestStop*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT - "; - if (body.size() != sizeof(pabb_MsgRequestStop)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestStop*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_QUEUE_SIZE, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_QUEUE_SIZE - "; - if (body.size() != sizeof(pabb_MsgRequestQueueSize)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestQueueSize*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_READ_CONTROLLER_MODE, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_READ_CONTROLLER_MODE - "; - if (body.size() != sizeof(pabb_MsgRequestReadControllerMode)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestReadControllerMode*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE - "; - if (body.size() != sizeof(pabb_MsgRequestChangeControllerMode)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgRequestChangeControllerMode*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", mode = " << params->mode; - return ss.str(); - } - ); -#if 0 - register_message_converter( - PABB_MSG_COMMAND_SET_LED_STATE, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_COMMAND_SET_LED_STATE - "; - if (body.size() != sizeof(pabb_MsgCommandSetLeds)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgCommandSetLeds*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", on = " << params->on; - return ss.str(); - } - ); -#endif - return 0; -} -int register_message_converters_custom_info(){ - register_message_converter( - PABB_MSG_INFO_I32, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_INFO_I32 - "; - if (body.size() != sizeof(pabb_MsgInfoI32)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_MsgInfoI32*)body.c_str(); -// switch (params->tag){ -// case PABB_MSG_INFO_I32_TAG_SCHEDULE_THROTTLED: -// ss << "Command schedule throttled by: " << params->data; -// break; -// default: - ss << "tag = " << (unsigned)params->tag; - ss << ", data = " << params->data; -// } - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_INFO_DATA, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_INFO_DATA - "; - const auto* params = (const pabb_MsgInfoData*)body.c_str(); - ss << "tag = " << (uint32_t)params->tag; - ss << ", bytes = " << body.size() - sizeof(uint32_t); - ss << ", data ="; - static const char HEX_DIGITS[] = "0123456789abcdef"; - for (size_t c = sizeof(seqnum_t); c < body.size(); c++){ - uint8_t byte = body[c]; - ss << " " << HEX_DIGITS[(byte >> 4)] << HEX_DIGITS[byte & 15]; - } - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_INFO_STRING, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_INFO_STRING - "; - ss << body; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_INFO_I32_LABEL, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_INFO_I32_LABEL - "; - if (body.size() < sizeof(uint32_t)){ - ss << "(invalid size)" << std::endl; - return ss.str(); - } - const auto* params = (const pabb_MsgInfoI32Label*)body.c_str(); - ss << std::string(body.data() + sizeof(uint32_t), body.size() - sizeof(uint32_t)); - ss << ": " << params->value; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_INFO_H32_LABEL, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_INFO_I32_LABEL - "; - if (body.size() < sizeof(uint32_t)){ - ss << "(invalid size)" << std::endl; - return ss.str(); - } - const auto* params = (const pabb_MsgInfoI32Label*)body.c_str(); - ss << std::string(body.data() + sizeof(uint32_t), body.size() - sizeof(uint32_t)); - ss << ": 0x" << std::hex << params->value; - return ss.str(); - } - ); - return 0; -} - - -int init_MessageLogger = - register_message_converters_framework_errors() + - register_message_converters_framework_acks() + - register_message_converters_framework_requests() + - register_message_converters_custom_info(); - - -std::string message_to_string(const BotBaseMessage& message){ - const std::map& converters = converter_map(); - auto iter = converters.find(message.type); - if (iter == converters.end()){ - std::ostringstream ss; - ss << "Unknown Message Type " << (unsigned)message.type << ": length = " << message.body.size(); - return ss.str(); - } - return iter->second(message.body); -} - - - - - -} - +/* Message Pretty Printing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include +#include +#include +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "Common/Cpp/Exceptions.h" +//#include "Common/Microcontroller/PABotBaseIDs.h" +//#include "Common/NintendoSwitch/NintendoSwitch_Protocol_PushButtons.h" +#include "ClientSource/Connection/BotBaseMessage.h" +#include "MessageConverter.h" + +namespace PokemonAutomation{ + + +std::map& converter_map(){ + static std::map converters; + return converters; +} +void register_message_converter(uint8_t type, MessageConverter converter){ + std::map& converters = converter_map(); + auto iter = converters.find(type); + if (iter != converters.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate message type."); + } + converters[type] = converter; +} + + +int register_message_converters_framework_errors(){ + register_message_converter( + PABB_MSG_ERROR_READY, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_READY - "; + if (body.size() != 0){ ss << "(invalid size)" << std::endl; return ss.str(); } + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_INVALID_MESSAGE, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_INVALID_MESSAGE - "; + if (body.size() != sizeof(pabb_MsgInfoInvalidMessage)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoInvalidMessage*)body.c_str(); + ss << "length = " << (unsigned)params->message_length; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_CHECKSUM_MISMATCH, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_CHECKSUM_MISMATCH - "; + if (body.size() != sizeof(pabb_MsgInfoChecksumMismatch)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoChecksumMismatch*)body.c_str(); + ss << "length = " << (unsigned)params->message_length; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_INVALID_TYPE, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_INVALID_TYPE - "; + if (body.size() != sizeof(pabb_MsgInfoInvalidType)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoInvalidType*)body.c_str(); + ss << "type = " << (unsigned)params->type; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_INVALID_REQUEST, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_INVALID_REQUEST - "; + if (body.size() != sizeof(pabb_MsgInfoInvalidRequest)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoInvalidRequest*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_MISSED_REQUEST, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_MISSED_REQUEST - "; + if (body.size() != sizeof(pabb_MsgInfoMissedRequest)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoMissedRequest*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_COMMAND_DROPPED, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_COMMAND_DROPPED - "; + if (body.size() != sizeof(pabb_MsgInfoCommandDropped)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoCommandDropped*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_WARNING, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_WARNING - "; + if (body.size() != sizeof(pabb_MsgInfoWARNING)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoWARNING*)body.c_str(); + ss << "error code = " << (unsigned)params->error_code; + switch (params->error_code){ + case 1: + ss << " (Device was slow to respond to USB request.)"; + break; + } + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ERROR_DISCONNECTED, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ERROR_DISCONNECTED - "; + if (body.size() != sizeof(pabb_MsgInfoDisconnected)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoDisconnected*)body.c_str(); + ss << "error code = " << params->error_code; + return ss.str(); + } + ); + return 0; +} +int register_message_converters_framework_acks(){ + register_message_converter( + PABB_MSG_ACK_COMMAND, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ACK_COMMAND - "; + if (body.size() != sizeof(pabb_MsgAckCommand)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgAckCommand*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ACK_REQUEST, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ACK_REQUEST - "; + if (body.size() != sizeof(pabb_MsgAckRequest)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgAckRequest*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ACK_REQUEST_I8, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ACK_REQUEST_I8 - "; + if (body.size() != sizeof(pabb_MsgAckRequestI8)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgAckRequestI8*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", message = " << (unsigned)params->data; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ACK_REQUEST_I16, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ACK_REQUEST_I16 - "; + if (body.size() != sizeof(pabb_MsgAckRequestI16)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgAckRequestI16*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", message = " << (unsigned)params->data; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ACK_REQUEST_I32, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ACK_REQUEST_I32 - "; + if (body.size() != sizeof(pabb_MsgAckRequestI32)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgAckRequestI32*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", message = " << params->data; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ACK_REQUEST_DATA, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ACK_REQUEST_DATA - "; +// if (body.size() != sizeof(pabb_MsgAckRequestI32)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgAckRequestI32*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", bytes = " << body.size() - sizeof(seqnum_t); + ss << ", data ="; + static const char HEX_DIGITS[] = "0123456789abcdef"; + for (size_t c = sizeof(seqnum_t); c < body.size(); c++){ + uint8_t byte = body[c]; + ss << " " << HEX_DIGITS[(byte >> 4)] << HEX_DIGITS[byte & 15]; + } + return ss.str(); + } + ); + return 0; +} +int register_message_converters_framework_requests(){ + register_message_converter( + PABB_MSG_SEQNUM_RESET, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_SEQNUM_RESET - "; + if (body.size() != sizeof(pabb_MsgInfoSeqnumReset)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoSeqnumReset*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_PROTOCOL_VERSION, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_PROTOCOL_VERSION - "; + if (body.size() != sizeof(pabb_MsgRequestProtocolVersion)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestProtocolVersion*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_PROGRAM_VERSION, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_PROGRAM_VERSION - "; + if (body.size() != sizeof(pabb_MsgRequestProgramVersion)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestProgramVersion*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_PROGRAM_ID, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_PROGRAM_ID - "; + if (body.size() != sizeof(pabb_MsgRequestProgramID)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestProgramID*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_CLOCK, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_CLOCK - "; + if (body.size() != sizeof(pabb_system_clock)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_system_clock*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_COMMAND_FINISHED, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_COMMAND_FINISHED - "; + if (body.size() != sizeof(pabb_MsgRequestCommandFinished)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestCommandFinished*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", seq_of_original_command = " << (unsigned)params->seq_of_original_command; + ss << ", finish_time = " << params->finish_time; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_STOP, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_STOP - "; + if (body.size() != sizeof(pabb_MsgRequestStop)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestStop*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT - "; + if (body.size() != sizeof(pabb_MsgRequestStop)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestStop*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_QUEUE_SIZE, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_QUEUE_SIZE - "; + if (body.size() != sizeof(pabb_MsgRequestQueueSize)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestQueueSize*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_READ_CONTROLLER_MODE, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_READ_CONTROLLER_MODE - "; + if (body.size() != sizeof(pabb_MsgRequestReadControllerMode)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestReadControllerMode*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE - "; + if (body.size() != sizeof(pabb_MsgRequestChangeControllerMode)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgRequestChangeControllerMode*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", mode = " << params->mode; + return ss.str(); + } + ); +#if 0 + register_message_converter( + PABB_MSG_COMMAND_SET_LED_STATE, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_COMMAND_SET_LED_STATE - "; + if (body.size() != sizeof(pabb_MsgCommandSetLeds)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgCommandSetLeds*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", on = " << params->on; + return ss.str(); + } + ); +#endif + return 0; +} +int register_message_converters_custom_info(){ + register_message_converter( + PABB_MSG_INFO_I32, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_INFO_I32 - "; + if (body.size() != sizeof(pabb_MsgInfoI32)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_MsgInfoI32*)body.c_str(); +// switch (params->tag){ +// case PABB_MSG_INFO_I32_TAG_SCHEDULE_THROTTLED: +// ss << "Command schedule throttled by: " << params->data; +// break; +// default: + ss << "tag = " << (unsigned)params->tag; + ss << ", data = " << params->data; +// } + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_INFO_DATA, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_INFO_DATA - "; + const auto* params = (const pabb_MsgInfoData*)body.c_str(); + ss << "tag = " << (uint32_t)params->tag; + ss << ", bytes = " << body.size() - sizeof(uint32_t); + ss << ", data ="; + static const char HEX_DIGITS[] = "0123456789abcdef"; + for (size_t c = sizeof(seqnum_t); c < body.size(); c++){ + uint8_t byte = body[c]; + ss << " " << HEX_DIGITS[(byte >> 4)] << HEX_DIGITS[byte & 15]; + } + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_INFO_STRING, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_INFO_STRING - "; + ss << body; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_INFO_I32_LABEL, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_INFO_I32_LABEL - "; + if (body.size() < sizeof(uint32_t)){ + ss << "(invalid size)" << std::endl; + return ss.str(); + } + const auto* params = (const pabb_MsgInfoI32Label*)body.c_str(); + ss << std::string(body.data() + sizeof(uint32_t), body.size() - sizeof(uint32_t)); + ss << ": " << params->value; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_INFO_H32_LABEL, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_INFO_I32_LABEL - "; + if (body.size() < sizeof(uint32_t)){ + ss << "(invalid size)" << std::endl; + return ss.str(); + } + const auto* params = (const pabb_MsgInfoI32Label*)body.c_str(); + ss << std::string(body.data() + sizeof(uint32_t), body.size() - sizeof(uint32_t)); + ss << ": 0x" << std::hex << params->value; + return ss.str(); + } + ); + return 0; +} + + +int init_MessageLogger = + register_message_converters_framework_errors() + + register_message_converters_framework_acks() + + register_message_converters_framework_requests() + + register_message_converters_custom_info(); + + +std::string message_to_string(const BotBaseMessage& message){ + const std::map& converters = converter_map(); + auto iter = converters.find(message.type); + if (iter == converters.end()){ + std::ostringstream ss; + ss << "Unknown Message Type " << (unsigned)message.type << ": length = " << message.body.size(); + return ss.str(); + } + return iter->second(message.body); +} + + + + + +} + diff --git a/ClientSource/Libraries/MessageConverter.h b/ClientSource/Libraries/MessageConverter.h index cf43560c15..8a29c6cdb4 100644 --- a/ClientSource/Libraries/MessageConverter.h +++ b/ClientSource/Libraries/MessageConverter.h @@ -1,21 +1,21 @@ -/* Message Pretty Printing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ClientSource/Connection/BotBase.h" - -namespace PokemonAutomation{ - - -using MessageConverter = std::string (*)(const std::string& body); -void register_message_converter(uint8_t type, MessageConverter converter); - -std::string message_to_string(const BotBaseMessage& message); - - - -} - +/* Message Pretty Printing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ClientSource/Connection/BotBase.h" + +namespace PokemonAutomation{ + + +using MessageConverter = std::string (*)(const std::string& body); +void register_message_converter(uint8_t type, MessageConverter converter); + +std::string message_to_string(const BotBaseMessage& message); + + + +} + diff --git a/Common/CRC32.c b/Common/CRC32.c index ab753c5b3b..fbaae5652a 100644 --- a/Common/CRC32.c +++ b/Common/CRC32.c @@ -1,133 +1,133 @@ -/* CRC32 - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "CRC32.h" - -uint32_t pabb_crc32_byte_basic(uint32_t crc, uint8_t byte){ - crc ^= byte; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; - return crc; -} -uint32_t pabb_crc32_basic(uint32_t crc, const void* data, size_t length){ - const char* ptr = (const char*)data; - for (size_t c = 0; c < length; c++){ - crc = pabb_crc32_byte_basic(crc, ptr[c]); - } - return crc; -} - - -#if __AVR__ -#include -#else -#define PROGMEM -#endif -#if 0 // defined __AVR_ATmega16U2__ -// 4-bit table (we used to use this on atmega16u2 because 8-bit is too much of memory hog) -const uint32_t PROGMEM CRC32_TABLE4[] = { - 0x00000000, 0x105ec76f, 0x20bd8ede, 0x30e349b1, - 0x417b1dbc, 0x5125dad3, 0x61c69362, 0x7198540d, - 0x82f63b78, 0x92a8fc17, 0xa24bb5a6, 0xb21572c9, - 0xc38d26c4, 0xd3d3e1ab, 0xe330a81a, 0xf36e6f75, -}; -void iterate_table(uint32_t* crc, uint8_t nibble){ -#if __AVR__ - uint32_t entry; - memcpy_P(&entry, CRC32_TABLE4 + (((uint8_t)*crc ^ nibble) & 0x0f), sizeof(uint32_t)); - *crc = entry ^ (*crc >> 4); -#else - *crc = CRC32_TABLE4[((uint8_t)*crc ^ nibble) & 0x0f] ^ (*crc >> 4); -#endif -} -//uint32_t pabb_crc32_byte_table(uint32_t crc, uint8_t byte){ -// iterate_table(&crc, byte); -// iterate_table(&crc, byte >> 4); -// return crc; -//} -uint32_t pabb_crc32_table(uint32_t crc, const void* str, size_t length){ - const char* ptr = (const char*)str; - for (size_t c = 0; c < length; c++){ -// crc = pabb_crc32_byte_table(crc, ptr[c]); - uint8_t byte = ptr[c]; - iterate_table(&crc, byte); - iterate_table(&crc, byte >> 4); - } - return crc; -} -#else -// 8-bit table -const uint32_t PROGMEM CRC32_TABLE8[] = { - 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb, - 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, - 0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, - 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b, - 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, - 0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, - 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a, - 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, - 0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, - 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198, - 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, - 0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, - 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789, - 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, - 0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, - 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829, - 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, - 0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, - 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc, - 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, - 0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, - 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982, - 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, - 0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, - 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f, - 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, - 0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, - 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f, - 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, - 0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, - 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e, - 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, -}; -uint32_t pabb_crc32_byte_table(uint32_t crc, uint8_t byte){ - uint32_t entry; -#if __AVR__ - memcpy_P(&entry, CRC32_TABLE8 + ((uint8_t)crc ^ byte), sizeof(uint32_t)); -#else - entry = CRC32_TABLE8[(uint8_t)crc ^ byte]; -#endif - return entry ^ (crc >> 8); -} -uint32_t pabb_crc32_table(uint32_t crc, const void* data, size_t length){ - const char* ptr = (const char*)data; - for (size_t c = 0; c < length; c++){ - uint32_t entry; -#if __AVR__ - memcpy_P(&entry, CRC32_TABLE8 + ((uint8_t)crc ^ (uint8_t)ptr[c]), sizeof(uint32_t)); -#else - entry = CRC32_TABLE8[(uint8_t)crc ^ (uint8_t)ptr[c]]; -#endif - crc = entry ^ (crc >> 8); - } - return crc; -} -#endif - - - -void pabb_crc32_write_to_message(const void* data, size_t full_message_length){ - const char* ptr = (const char*)data; - size_t length_before_crc = full_message_length - sizeof(uint32_t); - *(uint32_t*)(ptr + length_before_crc) = pabb_crc32(0xffffffff, ptr, length_before_crc); -} +/* CRC32 + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "CRC32.h" + +uint32_t pabb_crc32_byte_basic(uint32_t crc, uint8_t byte){ + crc ^= byte; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + crc = (crc & 1) ? (crc >> 1) ^ 0x82f63b78 : crc >> 1; + return crc; +} +uint32_t pabb_crc32_basic(uint32_t crc, const void* data, size_t length){ + const char* ptr = (const char*)data; + for (size_t c = 0; c < length; c++){ + crc = pabb_crc32_byte_basic(crc, ptr[c]); + } + return crc; +} + + +#if __AVR__ +#include +#else +#define PROGMEM +#endif +#if 0 // defined __AVR_ATmega16U2__ +// 4-bit table (we used to use this on atmega16u2 because 8-bit is too much of memory hog) +const uint32_t PROGMEM CRC32_TABLE4[] = { + 0x00000000, 0x105ec76f, 0x20bd8ede, 0x30e349b1, + 0x417b1dbc, 0x5125dad3, 0x61c69362, 0x7198540d, + 0x82f63b78, 0x92a8fc17, 0xa24bb5a6, 0xb21572c9, + 0xc38d26c4, 0xd3d3e1ab, 0xe330a81a, 0xf36e6f75, +}; +void iterate_table(uint32_t* crc, uint8_t nibble){ +#if __AVR__ + uint32_t entry; + memcpy_P(&entry, CRC32_TABLE4 + (((uint8_t)*crc ^ nibble) & 0x0f), sizeof(uint32_t)); + *crc = entry ^ (*crc >> 4); +#else + *crc = CRC32_TABLE4[((uint8_t)*crc ^ nibble) & 0x0f] ^ (*crc >> 4); +#endif +} +//uint32_t pabb_crc32_byte_table(uint32_t crc, uint8_t byte){ +// iterate_table(&crc, byte); +// iterate_table(&crc, byte >> 4); +// return crc; +//} +uint32_t pabb_crc32_table(uint32_t crc, const void* str, size_t length){ + const char* ptr = (const char*)str; + for (size_t c = 0; c < length; c++){ +// crc = pabb_crc32_byte_table(crc, ptr[c]); + uint8_t byte = ptr[c]; + iterate_table(&crc, byte); + iterate_table(&crc, byte >> 4); + } + return crc; +} +#else +// 8-bit table +const uint32_t PROGMEM CRC32_TABLE8[] = { + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, 0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb, + 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, + 0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b, 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, 0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b, + 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, + 0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5, 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, 0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a, + 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, + 0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48, 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, 0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198, + 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, + 0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8, 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, 0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789, + 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, + 0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9, 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, 0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829, + 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, + 0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043, 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, 0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc, + 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, + 0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652, 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, 0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982, + 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, + 0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2, 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, 0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f, + 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, + 0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f, 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, 0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f, + 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, + 0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321, 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, 0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e, + 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, +}; +uint32_t pabb_crc32_byte_table(uint32_t crc, uint8_t byte){ + uint32_t entry; +#if __AVR__ + memcpy_P(&entry, CRC32_TABLE8 + ((uint8_t)crc ^ byte), sizeof(uint32_t)); +#else + entry = CRC32_TABLE8[(uint8_t)crc ^ byte]; +#endif + return entry ^ (crc >> 8); +} +uint32_t pabb_crc32_table(uint32_t crc, const void* data, size_t length){ + const char* ptr = (const char*)data; + for (size_t c = 0; c < length; c++){ + uint32_t entry; +#if __AVR__ + memcpy_P(&entry, CRC32_TABLE8 + ((uint8_t)crc ^ (uint8_t)ptr[c]), sizeof(uint32_t)); +#else + entry = CRC32_TABLE8[(uint8_t)crc ^ (uint8_t)ptr[c]]; +#endif + crc = entry ^ (crc >> 8); + } + return crc; +} +#endif + + + +void pabb_crc32_write_to_message(const void* data, size_t full_message_length){ + const char* ptr = (const char*)data; + size_t length_before_crc = full_message_length - sizeof(uint32_t); + *(uint32_t*)(ptr + length_before_crc) = pabb_crc32(0xffffffff, ptr, length_before_crc); +} diff --git a/Common/CRC32.cpp b/Common/CRC32.cpp index 0e5b87c740..68b5084c13 100644 --- a/Common/CRC32.cpp +++ b/Common/CRC32.cpp @@ -1,2 +1,2 @@ - -#include "CRC32.c" + +#include "CRC32.c" diff --git a/Common/CRC32.h b/Common/CRC32.h index e5f3ab8630..6a007f718a 100644 --- a/Common/CRC32.h +++ b/Common/CRC32.h @@ -1,45 +1,45 @@ -/* CRC32 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CRC32_H -#define PokemonAutomation_CRC32_H - -#include -#include - - -// Basic Implementation -uint32_t pabb_crc32_basic(uint32_t crc, const void* data, size_t length); - -// Table Implementation -uint32_t pabb_crc32_table(uint32_t crc, const void* data, size_t length); - -// SSE4.2 -#if _M_IX86 || _M_X64 -#include -#include "Common/Compiler.h" -PA_FORCE_INLINE uint32_t pabb_crc32_SSE42(uint32_t crc, const void* data, size_t length){ - const char* ptr = (const char*)data; - for (size_t c = 0; c < length; c++){ - crc = _mm_crc32_u8(crc, ptr[c]); - } - return crc; -} -#endif - - -#if _M_IX86 || _M_X64 -#define pabb_crc32 pabb_crc32_SSE42 -#elif __AVR__ -#define pabb_crc32 pabb_crc32_table -#else -#define pabb_crc32 pabb_crc32_basic -#endif - -void pabb_crc32_write_to_message(const void* data, size_t full_message_length); - - -#endif +/* CRC32 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CRC32_H +#define PokemonAutomation_CRC32_H + +#include +#include + + +// Basic Implementation +uint32_t pabb_crc32_basic(uint32_t crc, const void* data, size_t length); + +// Table Implementation +uint32_t pabb_crc32_table(uint32_t crc, const void* data, size_t length); + +// SSE4.2 +#if _M_IX86 || _M_X64 +#include +#include "Common/Compiler.h" +PA_FORCE_INLINE uint32_t pabb_crc32_SSE42(uint32_t crc, const void* data, size_t length){ + const char* ptr = (const char*)data; + for (size_t c = 0; c < length; c++){ + crc = _mm_crc32_u8(crc, ptr[c]); + } + return crc; +} +#endif + + +#if _M_IX86 || _M_X64 +#define pabb_crc32 pabb_crc32_SSE42 +#elif __AVR__ +#define pabb_crc32 pabb_crc32_table +#else +#define pabb_crc32 pabb_crc32_basic +#endif + +void pabb_crc32_write_to_message(const void* data, size_t full_message_length); + + +#endif diff --git a/Common/Compiler.h b/Common/Compiler.h index 2b636bbf97..ac7f22e7ba 100644 --- a/Common/Compiler.h +++ b/Common/Compiler.h @@ -1,70 +1,70 @@ -/* Compiler Specifics - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Compiler_H -#define PokemonAutomation_Compiler_H - -//#include -namespace PokemonAutomation{ - - -#define PA_ALIGNMENT 64 - - -#if 0 -#elif _MSC_VER - -#define PA_NO_INLINE __declspec(noinline) -#define PA_FORCE_INLINE inline __forceinline -template using r_ptr = type *__restrict; -template using c_ptr = type const*__restrict; -template using r_ref = type &__restrict; -template using c_ref = type const&__restrict; -template using r_rref = type &&__restrict; - -//using ssize_t = ptrdiff_t; - -#pragma warning(disable:4100) // Unreferenced Formal Parameter -#pragma warning(disable:4127) // Conditional expresstion is constant -#pragma warning(disable:4324) // structure was padded due to alignment specifier -#pragma warning(disable:4458) // Hiding of class members -#pragma warning(disable:4996) // Unsafe function - -#define PA_CURRENT_FUNCTION __FUNCSIG__ - - -#elif __GNUC__ - -#define PA_NO_INLINE __attribute__ ((noinline)) -#define PA_FORCE_INLINE inline __attribute__ ((always_inline)) -template using r_ptr = type *__restrict__; -template using c_ptr = type const*__restrict__; -template using r_ref = type &__restrict__; -template using c_ref = type const&__restrict__; -template using r_rref = type &&__restrict__; - -// Align a struct on x-byte boundary. -// It's the minimum alignment for a struct or a struct member. -#define PA_ALIGN_STRUCT(x) __attribute__((aligned(x))) - -#pragma GCC diagnostic ignored "-Wunused-parameter" -#pragma GCC diagnostic ignored "-Wunused-function" -#pragma GCC diagnostic ignored "-Wmissing-field-initializers" -#pragma GCC diagnostic ignored "-Woverloaded-virtual" -#pragma GCC diagnostic ignored "-Wimplicit-fallthrough" - -#define PA_CURRENT_FUNCTION __PRETTY_FUNCTION__ - - -#else -#error "Unsupported Compiler." -#endif - - - - -} -#endif +/* Compiler Specifics + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Compiler_H +#define PokemonAutomation_Compiler_H + +//#include +namespace PokemonAutomation{ + + +#define PA_ALIGNMENT 64 + + +#if 0 +#elif _MSC_VER + +#define PA_NO_INLINE __declspec(noinline) +#define PA_FORCE_INLINE inline __forceinline +template using r_ptr = type *__restrict; +template using c_ptr = type const*__restrict; +template using r_ref = type &__restrict; +template using c_ref = type const&__restrict; +template using r_rref = type &&__restrict; + +//using ssize_t = ptrdiff_t; + +#pragma warning(disable:4100) // Unreferenced Formal Parameter +#pragma warning(disable:4127) // Conditional expresstion is constant +#pragma warning(disable:4324) // structure was padded due to alignment specifier +#pragma warning(disable:4458) // Hiding of class members +#pragma warning(disable:4996) // Unsafe function + +#define PA_CURRENT_FUNCTION __FUNCSIG__ + + +#elif __GNUC__ + +#define PA_NO_INLINE __attribute__ ((noinline)) +#define PA_FORCE_INLINE inline __attribute__ ((always_inline)) +template using r_ptr = type *__restrict__; +template using c_ptr = type const*__restrict__; +template using r_ref = type &__restrict__; +template using c_ref = type const&__restrict__; +template using r_rref = type &&__restrict__; + +// Align a struct on x-byte boundary. +// It's the minimum alignment for a struct or a struct member. +#define PA_ALIGN_STRUCT(x) __attribute__((aligned(x))) + +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wunused-function" +#pragma GCC diagnostic ignored "-Wmissing-field-initializers" +#pragma GCC diagnostic ignored "-Woverloaded-virtual" +#pragma GCC diagnostic ignored "-Wimplicit-fallthrough" + +#define PA_CURRENT_FUNCTION __PRETTY_FUNCTION__ + + +#else +#error "Unsupported Compiler." +#endif + + + + +} +#endif diff --git a/Common/Cpp/AbstractLogger.h b/Common/Cpp/AbstractLogger.h index 1ffeb8b62e..18c7d995e8 100644 --- a/Common/Cpp/AbstractLogger.h +++ b/Common/Cpp/AbstractLogger.h @@ -1,34 +1,34 @@ -/* Abstract Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AbstractLogger_H -#define PokemonAutomation_AbstractLogger_H - -#include -#include -#include "Color.h" - -namespace PokemonAutomation{ - - -class Logger{ -public: - virtual void log(const std::string& msg, Color color = Color()) = 0; - virtual void log(std::string&& msg, Color color = Color()){ - log((const std::string&)msg, color); - } - virtual void log(const char* msg, Color color = Color()){ - log(std::string(msg), color); - } - - virtual std::vector get_last() const{ - return {}; - } -}; - - -} -#endif +/* Abstract Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AbstractLogger_H +#define PokemonAutomation_AbstractLogger_H + +#include +#include +#include "Color.h" + +namespace PokemonAutomation{ + + +class Logger{ +public: + virtual void log(const std::string& msg, Color color = Color()) = 0; + virtual void log(std::string&& msg, Color color = Color()){ + log((const std::string&)msg, color); + } + virtual void log(const char* msg, Color color = Color()){ + log(std::string(msg), color); + } + + virtual std::vector get_last() const{ + return {}; + } +}; + + +} +#endif diff --git a/Common/Cpp/CancellableScope.cpp b/Common/Cpp/CancellableScope.cpp index b0ffb8a653..5d58a00336 100644 --- a/Common/Cpp/CancellableScope.cpp +++ b/Common/Cpp/CancellableScope.cpp @@ -1,192 +1,192 @@ -/* Cancellable Scope - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Exceptions.h" -#include "Containers/Pimpl.tpp" -#include "Concurrency/SpinLock.h" -#include "CancellableScope.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct CancellableData{ - CancellableData() - : cancelled(false) - {} - std::atomic cancelled; - mutable SpinLock lock; - std::exception_ptr exception; -}; - - - -Cancellable::Cancellable() - : m_impl(CONSTRUCT_TOKEN) -{ -// cout << "Constructing: " << this << endl; -} -Cancellable::~Cancellable(){ - detach(); -// cout << "Deleting: " << this << endl; -} -CancellableScope* Cancellable::scope() const{ - auto scope_check = m_sanitizer.check_scope(); - return m_scope; -} -bool Cancellable::cancelled() const noexcept{ - auto scope_check = m_sanitizer.check_scope(); - return m_impl->cancelled.load(std::memory_order_acquire); -} -bool Cancellable::cancel(std::exception_ptr exception) noexcept{ - auto scope_check = m_sanitizer.check_scope(); - CancellableData& data(*m_impl); - WriteSpinLock lg(data.lock); - if (exception && !data.exception){ - data.exception = std::move(exception); - } - if (data.cancelled.load(std::memory_order_acquire)){ - return true; - } - return data.cancelled.exchange(true, std::memory_order_relaxed); -} -void Cancellable::throw_if_cancelled() const{ - auto scope_check = m_sanitizer.check_scope(); - const CancellableData& data(*m_impl); - if (!data.cancelled.load(std::memory_order_acquire)){ - return; - } - ReadSpinLock lg(data.lock); - if (data.exception){ - std::rethrow_exception(data.exception); - }else{ - throw OperationCancelledException(); - } -} -bool Cancellable::throw_if_cancelled_with_exception() const{ - auto scope_check = m_sanitizer.check_scope(); - const CancellableData& data(*m_impl); - if (!data.cancelled.load(std::memory_order_acquire)){ - return false; - } - ReadSpinLock lg(data.lock); - if (data.exception){ - std::rethrow_exception(data.exception); - } - return true; -} -void Cancellable::attach(CancellableScope& scope){ - auto scope_check = m_sanitizer.check_scope(); - m_scope = &scope; - scope += *this; -} -void Cancellable::detach() noexcept{ - auto scope_check = m_sanitizer.check_scope(); - if (m_scope){ - *m_scope -= *this; - } -} - - - - - -struct CancellableScopeData{ - std::set children; - - std::mutex lock; - std::condition_variable cv; -}; - - - -CancellableScope::CancellableScope() - : m_impl(CONSTRUCT_TOKEN) -{} -CancellableScope::~CancellableScope(){ - detach(); -} -bool CancellableScope::cancel(std::exception_ptr exception) noexcept{ - if (Cancellable::cancel(exception)){ - return true; - } - CancellableScopeData& data(*m_impl); - std::lock_guard lg(data.lock); - for (Cancellable* child : data.children){ -// cout << "Canceling: " << child << endl; -// cout << "Canceling: " << child->name() << endl; - auto scope_check = child->m_sanitizer.check_scope(); - child->cancel(exception); - } -// cout << "Done Canceling" << endl; - data.children.clear(); - data.cv.notify_all(); - return false; -} -void CancellableScope::wait_for(std::chrono::milliseconds duration){ - auto scope_check = m_sanitizer.check_scope(); - wait_until(current_time() + duration); -} -void CancellableScope::wait_until(WallClock stop){ - auto scope_check = m_sanitizer.check_scope(); - throw_if_cancelled(); - CancellableScopeData& data(*m_impl); - { - std::unique_lock lg(data.lock); - data.cv.wait_until( - lg, stop, - [this, stop]{ - return current_time() >= stop || cancelled(); - } - ); - } - throw_if_cancelled(); -} -void CancellableScope::wait_until_cancel(){ - auto scope_check = m_sanitizer.check_scope(); - throw_if_cancelled(); - CancellableScopeData& data(*m_impl); - { - std::unique_lock lg(data.lock); - data.cv.wait( - lg, - [this]{ - return cancelled(); - } - ); - } - throw_if_cancelled(); -} -void CancellableScope::operator+=(Cancellable& cancellable){ -// cout << "Attaching: " << &cancellable << endl; - auto scope_check = m_sanitizer.check_scope(); - CancellableScopeData& data(*m_impl); - std::lock_guard lg(data.lock); - throw_if_cancelled(); - data.children.insert(&cancellable); -} -void CancellableScope::operator-=(Cancellable& cancellable){ -// cout << "Detaching: " << &cancellable << endl; - auto scope_check = m_sanitizer.check_scope(); - CancellableScopeData& data(*m_impl); - std::lock_guard lg(data.lock); - data.children.erase(&cancellable); -} - - - - - - -} +/* Cancellable Scope + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Exceptions.h" +#include "Containers/Pimpl.tpp" +#include "Concurrency/SpinLock.h" +#include "CancellableScope.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct CancellableData{ + CancellableData() + : cancelled(false) + {} + std::atomic cancelled; + mutable SpinLock lock; + std::exception_ptr exception; +}; + + + +Cancellable::Cancellable() + : m_impl(CONSTRUCT_TOKEN) +{ +// cout << "Constructing: " << this << endl; +} +Cancellable::~Cancellable(){ + detach(); +// cout << "Deleting: " << this << endl; +} +CancellableScope* Cancellable::scope() const{ + auto scope_check = m_sanitizer.check_scope(); + return m_scope; +} +bool Cancellable::cancelled() const noexcept{ + auto scope_check = m_sanitizer.check_scope(); + return m_impl->cancelled.load(std::memory_order_acquire); +} +bool Cancellable::cancel(std::exception_ptr exception) noexcept{ + auto scope_check = m_sanitizer.check_scope(); + CancellableData& data(*m_impl); + WriteSpinLock lg(data.lock); + if (exception && !data.exception){ + data.exception = std::move(exception); + } + if (data.cancelled.load(std::memory_order_acquire)){ + return true; + } + return data.cancelled.exchange(true, std::memory_order_relaxed); +} +void Cancellable::throw_if_cancelled() const{ + auto scope_check = m_sanitizer.check_scope(); + const CancellableData& data(*m_impl); + if (!data.cancelled.load(std::memory_order_acquire)){ + return; + } + ReadSpinLock lg(data.lock); + if (data.exception){ + std::rethrow_exception(data.exception); + }else{ + throw OperationCancelledException(); + } +} +bool Cancellable::throw_if_cancelled_with_exception() const{ + auto scope_check = m_sanitizer.check_scope(); + const CancellableData& data(*m_impl); + if (!data.cancelled.load(std::memory_order_acquire)){ + return false; + } + ReadSpinLock lg(data.lock); + if (data.exception){ + std::rethrow_exception(data.exception); + } + return true; +} +void Cancellable::attach(CancellableScope& scope){ + auto scope_check = m_sanitizer.check_scope(); + m_scope = &scope; + scope += *this; +} +void Cancellable::detach() noexcept{ + auto scope_check = m_sanitizer.check_scope(); + if (m_scope){ + *m_scope -= *this; + } +} + + + + + +struct CancellableScopeData{ + std::set children; + + std::mutex lock; + std::condition_variable cv; +}; + + + +CancellableScope::CancellableScope() + : m_impl(CONSTRUCT_TOKEN) +{} +CancellableScope::~CancellableScope(){ + detach(); +} +bool CancellableScope::cancel(std::exception_ptr exception) noexcept{ + if (Cancellable::cancel(exception)){ + return true; + } + CancellableScopeData& data(*m_impl); + std::lock_guard lg(data.lock); + for (Cancellable* child : data.children){ +// cout << "Canceling: " << child << endl; +// cout << "Canceling: " << child->name() << endl; + auto scope_check = child->m_sanitizer.check_scope(); + child->cancel(exception); + } +// cout << "Done Canceling" << endl; + data.children.clear(); + data.cv.notify_all(); + return false; +} +void CancellableScope::wait_for(std::chrono::milliseconds duration){ + auto scope_check = m_sanitizer.check_scope(); + wait_until(current_time() + duration); +} +void CancellableScope::wait_until(WallClock stop){ + auto scope_check = m_sanitizer.check_scope(); + throw_if_cancelled(); + CancellableScopeData& data(*m_impl); + { + std::unique_lock lg(data.lock); + data.cv.wait_until( + lg, stop, + [this, stop]{ + return current_time() >= stop || cancelled(); + } + ); + } + throw_if_cancelled(); +} +void CancellableScope::wait_until_cancel(){ + auto scope_check = m_sanitizer.check_scope(); + throw_if_cancelled(); + CancellableScopeData& data(*m_impl); + { + std::unique_lock lg(data.lock); + data.cv.wait( + lg, + [this]{ + return cancelled(); + } + ); + } + throw_if_cancelled(); +} +void CancellableScope::operator+=(Cancellable& cancellable){ +// cout << "Attaching: " << &cancellable << endl; + auto scope_check = m_sanitizer.check_scope(); + CancellableScopeData& data(*m_impl); + std::lock_guard lg(data.lock); + throw_if_cancelled(); + data.children.insert(&cancellable); +} +void CancellableScope::operator-=(Cancellable& cancellable){ +// cout << "Detaching: " << &cancellable << endl; + auto scope_check = m_sanitizer.check_scope(); + CancellableScopeData& data(*m_impl); + std::lock_guard lg(data.lock); + data.children.erase(&cancellable); +} + + + + + + +} diff --git a/Common/Cpp/CancellableScope.h b/Common/Cpp/CancellableScope.h index 5d2e780cd3..b6343ae033 100644 --- a/Common/Cpp/CancellableScope.h +++ b/Common/Cpp/CancellableScope.h @@ -1,163 +1,163 @@ -/* Cancellable Scope - * - * From: https://github.com/PokemonAutomation/ - * - * A cancellable scope is a node with a tree. If "cancel()" is called on - * a scope, only the scope and all child scopes will be canceled. Parents are - * not affected. - * - * This is used in nested async-cancel routines. - * - * If the user stops the program, "cancel()" is called on the root node which - * will propagate down the entire tree. - * - * If a subroutine cancels due to an inference trigger, it ends just that - * scope and passes control up to the parent. - * - * The lifetime of a parent must entirely enclose that of the children and - * attached cancellables. This must hold even when an exception is thrown. - * - */ - -#ifndef PokemonAutomation_CancellableScope_H -#define PokemonAutomation_CancellableScope_H - -#if 1 -#include -#else -namespace std{ - class exception_ptr; -} -#endif - -#include "Containers/Pimpl.h" -#include "Time.h" -#include "LifetimeSanitizer.h" - -namespace PokemonAutomation{ - - -class CancellableScope; - - - -struct CancellableData; -class Cancellable{ - Cancellable(const Cancellable&) = delete; - void operator=(const Cancellable&) = delete; -public: - virtual ~Cancellable(); - -// virtual std::string name() const{ return "Cancellable"; }; - - CancellableScope* scope() const; - - bool cancelled() const noexcept; - - // Throw an exception if this object has been cancelled. - // If there is no exception, it throws OperationCancelledException. - // Otherwise, it throws the stored exception. - void throw_if_cancelled() const; - - // If object has not been cancelled, return false. - // If object has been cancelled with no exception, return true. - // If object has been cancelled with an exception, rethrow the exception. - bool throw_if_cancelled_with_exception() const; - - // Returns true if it was already cancelled. - virtual bool cancel(std::exception_ptr exception) noexcept; - - -protected: - // This class needs special handling for subclasses. - // - // 1. The constructors of all sub-classes should be protected except for - // the most-derived class. - // - // 2. The most-derived class must be marked final. - // - // 3. The most-derived class must call "attach()" at the end of its - // constructor. - // - // 4. The most-derived class must call "detach()" at the start of its - // destructor. - // - // The moment you attach to a scope, the scope may call "cancel()" on you - // at any time - even before you are done constructing. Therefore you must - // not attach until you are done constructing. - // - // Because "cancel()" can be called on you at any time, you must detach - // before you begin destructing. - Cancellable(); - - // You must call last in the constructor of the most-derived subclass. - void attach(CancellableScope& scope); - - // You must call this first in the destructor of the most-derived subclass. - void detach() noexcept; - - -private: - CancellableScope* m_scope = nullptr; - Pimpl m_impl; -public: - LifetimeSanitizer m_sanitizer; -}; - - - -struct CancellableScopeData; -class CancellableScope : public Cancellable{ -public: - virtual ~CancellableScope() override; - - virtual bool cancel(std::exception_ptr exception) noexcept override; - - void wait_for(std::chrono::milliseconds duration); - void wait_until(WallClock stop); - void wait_until_cancel(); - -protected: - CancellableScope(); - -private: - friend class Cancellable; - void operator+=(Cancellable& cancellable); - void operator-=(Cancellable& cancellable); - -private: - Pimpl m_impl; - LifetimeSanitizer m_sanitizer; -}; - - - -template -class CancellableHolder final : public CancellableType{ -public: - // Construct with no parent. - template - CancellableHolder(Args&&... args) - : CancellableType(std::forward(args)...) - {} - - // Construct with a parent. - template - CancellableHolder(CancellableScope& parent, Args&&... args) - : CancellableType(std::forward(args)...) - { - this->attach(parent); - } - - virtual ~CancellableHolder(){ - this->detach(); - } -}; - - - - - - -} -#endif +/* Cancellable Scope + * + * From: https://github.com/PokemonAutomation/ + * + * A cancellable scope is a node with a tree. If "cancel()" is called on + * a scope, only the scope and all child scopes will be canceled. Parents are + * not affected. + * + * This is used in nested async-cancel routines. + * + * If the user stops the program, "cancel()" is called on the root node which + * will propagate down the entire tree. + * + * If a subroutine cancels due to an inference trigger, it ends just that + * scope and passes control up to the parent. + * + * The lifetime of a parent must entirely enclose that of the children and + * attached cancellables. This must hold even when an exception is thrown. + * + */ + +#ifndef PokemonAutomation_CancellableScope_H +#define PokemonAutomation_CancellableScope_H + +#if 1 +#include +#else +namespace std{ + class exception_ptr; +} +#endif + +#include "Containers/Pimpl.h" +#include "Time.h" +#include "LifetimeSanitizer.h" + +namespace PokemonAutomation{ + + +class CancellableScope; + + + +struct CancellableData; +class Cancellable{ + Cancellable(const Cancellable&) = delete; + void operator=(const Cancellable&) = delete; +public: + virtual ~Cancellable(); + +// virtual std::string name() const{ return "Cancellable"; }; + + CancellableScope* scope() const; + + bool cancelled() const noexcept; + + // Throw an exception if this object has been cancelled. + // If there is no exception, it throws OperationCancelledException. + // Otherwise, it throws the stored exception. + void throw_if_cancelled() const; + + // If object has not been cancelled, return false. + // If object has been cancelled with no exception, return true. + // If object has been cancelled with an exception, rethrow the exception. + bool throw_if_cancelled_with_exception() const; + + // Returns true if it was already cancelled. + virtual bool cancel(std::exception_ptr exception) noexcept; + + +protected: + // This class needs special handling for subclasses. + // + // 1. The constructors of all sub-classes should be protected except for + // the most-derived class. + // + // 2. The most-derived class must be marked final. + // + // 3. The most-derived class must call "attach()" at the end of its + // constructor. + // + // 4. The most-derived class must call "detach()" at the start of its + // destructor. + // + // The moment you attach to a scope, the scope may call "cancel()" on you + // at any time - even before you are done constructing. Therefore you must + // not attach until you are done constructing. + // + // Because "cancel()" can be called on you at any time, you must detach + // before you begin destructing. + Cancellable(); + + // You must call last in the constructor of the most-derived subclass. + void attach(CancellableScope& scope); + + // You must call this first in the destructor of the most-derived subclass. + void detach() noexcept; + + +private: + CancellableScope* m_scope = nullptr; + Pimpl m_impl; +public: + LifetimeSanitizer m_sanitizer; +}; + + + +struct CancellableScopeData; +class CancellableScope : public Cancellable{ +public: + virtual ~CancellableScope() override; + + virtual bool cancel(std::exception_ptr exception) noexcept override; + + void wait_for(std::chrono::milliseconds duration); + void wait_until(WallClock stop); + void wait_until_cancel(); + +protected: + CancellableScope(); + +private: + friend class Cancellable; + void operator+=(Cancellable& cancellable); + void operator-=(Cancellable& cancellable); + +private: + Pimpl m_impl; + LifetimeSanitizer m_sanitizer; +}; + + + +template +class CancellableHolder final : public CancellableType{ +public: + // Construct with no parent. + template + CancellableHolder(Args&&... args) + : CancellableType(std::forward(args)...) + {} + + // Construct with a parent. + template + CancellableHolder(CancellableScope& parent, Args&&... args) + : CancellableType(std::forward(args)...) + { + this->attach(parent); + } + + virtual ~CancellableHolder(){ + this->detach(); + } +}; + + + + + + +} +#endif diff --git a/Common/Cpp/Color.cpp b/Common/Cpp/Color.cpp index c03bbc3845..bf4c48ac52 100644 --- a/Common/Cpp/Color.cpp +++ b/Common/Cpp/Color.cpp @@ -1,27 +1,27 @@ -/* Color - * - * From: https://github.com/PokemonAutomation/ - * - * A very lightweight color class to avoid pulling in . - * - */ - -#include -#include -#include "Color.h" - -namespace PokemonAutomation{ - -std::string Color::to_string() const{ - std::ostringstream os; - os << "[0x" << std::internal << std::setfill('0'); - os << std::hex << std::uppercase << std::setw(8) << m_argb << std::dec; - os << " A=" << std::setw(2) << int(alpha()); - os << " R=" << std::setw(2) << int(red()); - os << " G=" << std::setw(2) << int(green()); - os << " B=" << std::setw(2) << int(blue()) << "]"; - return os.str(); -} - -} - +/* Color + * + * From: https://github.com/PokemonAutomation/ + * + * A very lightweight color class to avoid pulling in . + * + */ + +#include +#include +#include "Color.h" + +namespace PokemonAutomation{ + +std::string Color::to_string() const{ + std::ostringstream os; + os << "[0x" << std::internal << std::setfill('0'); + os << std::hex << std::uppercase << std::setw(8) << m_argb << std::dec; + os << " A=" << std::setw(2) << int(alpha()); + os << " R=" << std::setw(2) << int(red()); + os << " G=" << std::setw(2) << int(green()); + os << " B=" << std::setw(2) << int(blue()) << "]"; + return os.str(); +} + +} + diff --git a/Common/Cpp/Color.h b/Common/Cpp/Color.h index c843d9df94..67cdba1575 100644 --- a/Common/Cpp/Color.h +++ b/Common/Cpp/Color.h @@ -1,89 +1,89 @@ -/* Color - * - * From: https://github.com/PokemonAutomation/ - * - * A very lightweight color class to avoid pulling in . - * - */ - -#ifndef PokemonAutomation_Color_H -#define PokemonAutomation_Color_H - -#include -#include - -namespace PokemonAutomation{ - - -constexpr inline uint32_t combine_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b){ - return (((uint32_t)a << 8 | r) << 8 | g) << 8 | b; -} - -constexpr inline uint32_t combine_rgb(uint8_t r, uint8_t g, uint8_t b){ - return (((uint32_t)255 << 8 | r) << 8 | g) << 8 | b; -} - - -class Color{ -public: - constexpr Color() : m_argb(0) {} - constexpr explicit Color(uint32_t argb) : m_argb(argb) {} - constexpr Color(uint8_t red, uint8_t green, uint8_t blue) : m_argb(combine_rgb(red, green, blue)) {} - constexpr Color(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue) : m_argb(combine_argb(alpha, red, green, blue)) {} - - constexpr explicit operator bool() const{ - return m_argb != 0; - } - constexpr explicit operator uint32_t() const{ - return m_argb; - } - bool operator<(Color color) const{ - return m_argb < color.m_argb; - } - bool operator==(Color color) const{ - return m_argb == color.m_argb; - } - bool operator!=(Color color) const{ - return m_argb != color.m_argb; - } - - uint8_t alpha () const { return (uint8_t)(m_argb >> 24); } - uint8_t red () const { return (uint8_t)(m_argb >> 16); } - uint8_t green () const { return (uint8_t)(m_argb >> 8); } - uint8_t blue () const { return (uint8_t)(m_argb >> 0); } - - // Example: "[0xFFFDBD00 A=255 R=253 G=189 B=00]" - std::string to_string() const; - -private: - uint32_t m_argb; -}; - - -constexpr Color COLOR_WHITE(0xffffffff); -constexpr Color COLOR_BLACK(0xff000000); -constexpr Color COLOR_GRAY(0xff808080); - -constexpr Color COLOR_RED(0xffff0000); -constexpr Color COLOR_GREEN(0xff00ff00); -constexpr Color COLOR_BLUE(0xff0080ff); -constexpr Color COLOR_DARK_BLUE(0xff0000ff); // Hard to see on dark theme. - -constexpr Color COLOR_MAGENTA(0xffff00ff); -constexpr Color COLOR_YELLOW(0xffffff00); -constexpr Color COLOR_CYAN(0xff00ffff); - -constexpr Color COLOR_ORANGE(0xffffa500); -//constexpr Color COLOR_PURPLE(0xff800080); // Hard to see on dark theme. -constexpr Color COLOR_PURPLE(0xff8a2be2); - -constexpr Color COLOR_DARKGREEN(0xff008000); -constexpr Color COLOR_DARKCYAN(0xff008080); - -constexpr Color COLOR_GREEN2(0xff00aa00); - - - - -} -#endif +/* Color + * + * From: https://github.com/PokemonAutomation/ + * + * A very lightweight color class to avoid pulling in . + * + */ + +#ifndef PokemonAutomation_Color_H +#define PokemonAutomation_Color_H + +#include +#include + +namespace PokemonAutomation{ + + +constexpr inline uint32_t combine_argb(uint8_t a, uint8_t r, uint8_t g, uint8_t b){ + return (((uint32_t)a << 8 | r) << 8 | g) << 8 | b; +} + +constexpr inline uint32_t combine_rgb(uint8_t r, uint8_t g, uint8_t b){ + return (((uint32_t)255 << 8 | r) << 8 | g) << 8 | b; +} + + +class Color{ +public: + constexpr Color() : m_argb(0) {} + constexpr explicit Color(uint32_t argb) : m_argb(argb) {} + constexpr Color(uint8_t red, uint8_t green, uint8_t blue) : m_argb(combine_rgb(red, green, blue)) {} + constexpr Color(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue) : m_argb(combine_argb(alpha, red, green, blue)) {} + + constexpr explicit operator bool() const{ + return m_argb != 0; + } + constexpr explicit operator uint32_t() const{ + return m_argb; + } + bool operator<(Color color) const{ + return m_argb < color.m_argb; + } + bool operator==(Color color) const{ + return m_argb == color.m_argb; + } + bool operator!=(Color color) const{ + return m_argb != color.m_argb; + } + + uint8_t alpha () const { return (uint8_t)(m_argb >> 24); } + uint8_t red () const { return (uint8_t)(m_argb >> 16); } + uint8_t green () const { return (uint8_t)(m_argb >> 8); } + uint8_t blue () const { return (uint8_t)(m_argb >> 0); } + + // Example: "[0xFFFDBD00 A=255 R=253 G=189 B=00]" + std::string to_string() const; + +private: + uint32_t m_argb; +}; + + +constexpr Color COLOR_WHITE(0xffffffff); +constexpr Color COLOR_BLACK(0xff000000); +constexpr Color COLOR_GRAY(0xff808080); + +constexpr Color COLOR_RED(0xffff0000); +constexpr Color COLOR_GREEN(0xff00ff00); +constexpr Color COLOR_BLUE(0xff0080ff); +constexpr Color COLOR_DARK_BLUE(0xff0000ff); // Hard to see on dark theme. + +constexpr Color COLOR_MAGENTA(0xffff00ff); +constexpr Color COLOR_YELLOW(0xffffff00); +constexpr Color COLOR_CYAN(0xff00ffff); + +constexpr Color COLOR_ORANGE(0xffffa500); +//constexpr Color COLOR_PURPLE(0xff800080); // Hard to see on dark theme. +constexpr Color COLOR_PURPLE(0xff8a2be2); + +constexpr Color COLOR_DARKGREEN(0xff008000); +constexpr Color COLOR_DARKCYAN(0xff008080); + +constexpr Color COLOR_GREEN2(0xff00aa00); + + + + +} +#endif diff --git a/Common/Cpp/Concurrency/AsyncDispatcher.cpp b/Common/Cpp/Concurrency/AsyncDispatcher.cpp index 2fa60c52b0..032015994b 100644 --- a/Common/Cpp/Concurrency/AsyncDispatcher.cpp +++ b/Common/Cpp/Concurrency/AsyncDispatcher.cpp @@ -1,202 +1,202 @@ -/* Thread Pool - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PanicDump.h" -#include "AsyncDispatcher.h" - -//#include -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -AsyncTask::~AsyncTask(){ - std::unique_lock lg(m_lock); - m_cv.wait(lg, [this]{ return m_finished; }); -} -void AsyncTask::rethrow_exceptions(){ - if (!m_stopped_with_error.load(std::memory_order_acquire)){ - return; - } - std::unique_lock lg(m_lock); - if (m_exception){ - std::rethrow_exception(m_exception); - } -} -void AsyncTask::wait_and_rethrow_exceptions(){ - std::unique_lock lg(m_lock); - m_cv.wait(lg, [this]{ return m_finished; }); - if (m_exception){ - std::rethrow_exception(m_exception); - } -} -void AsyncTask::signal(){ - std::lock_guard lg(m_lock); - m_finished = true; - m_cv.notify_all(); -} - - -#if 0 -AsyncDispatcher::AsyncDispatcher(size_t starting_threads) - : AsyncDispatcher(nullptr, starting_threads) -{} -#endif -AsyncDispatcher::AsyncDispatcher(std::function&& new_thread_callback, size_t starting_threads) - : m_new_thread_callback(std::move(new_thread_callback)) - , m_stopping(false) - , m_busy_count(0) -{ - for (size_t c = 0; c < starting_threads; c++){ - m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); - } -} -AsyncDispatcher::~AsyncDispatcher(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_cv.notify_all(); - } - for (std::thread& thread : m_threads){ -// cout << "AsyncDispatcher::~AsyncDispatcher() joining = " << thread.get_id() << endl; - thread.join(); - } - for (AsyncTask* task : m_queue){ - task->signal(); - } -} - -void AsyncDispatcher::ensure_threads(size_t threads){ - std::lock_guard lg(m_lock); - while (m_threads.size() < threads){ - m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); - } -} - -void AsyncDispatcher::dispatch_task(AsyncTask& task){ -// cout << "dispatch_task() - enter" << endl; - std::lock_guard lg(m_lock); - - // Enqueue task. - m_queue.emplace_back(&task); - - // Make sure a thread is ready for it. - if (m_queue.size() > m_threads.size() - m_busy_count){ - m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); - } - - m_cv.notify_one(); -// cout << "dispatch_task() - exit" << endl; -} - -std::unique_ptr AsyncDispatcher::dispatch(std::function&& func){ - std::unique_ptr task(new AsyncTask(std::move(func))); - dispatch_task(*task); -// cout << "dispatch_task - 1() - exit" << endl; - return task; -} -void AsyncDispatcher::run_in_parallel( - size_t s, size_t e, - const std::function& func -){ - if (s >= e){ - return; - } - - // Build tasks. - std::vector> tasks; - for (size_t index = 0; s + index < e; index++){ - size_t local_index = s + index; - tasks.emplace_back(new AsyncTask( - [&func, local_index]{ func(local_index); } - )); - } - - { - std::lock_guard lg(m_lock); - - // Enqueue tasks. - for (std::unique_ptr& task : tasks){ - m_queue.emplace_back(task.get()); - } - - // Make sure there are enough threads. - while (m_queue.size() > m_threads.size() - m_busy_count){ - m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); - } - - for (size_t c = 0; c < tasks.size(); c++){ - m_cv.notify_one(); - } - } - - // Wait -// cout << "begin wait()" << endl; - for (std::unique_ptr& task : tasks){ - task->wait_and_rethrow_exceptions(); - } -// cout << "end wait()" << endl; -} - - - -void AsyncDispatcher::thread_loop(){ -// cout << "AsyncDispatcher::thread_loop() Start = " << GetCurrentThreadId() << ", threads = " << m_threads.size() << endl; - if (m_new_thread_callback){ - m_new_thread_callback(); - } - bool busy = false; - while (true){ - AsyncTask* task; - { - std::unique_lock lg(m_lock); - if (busy){ - m_busy_count--; - busy = false; - } - - if (m_stopping){ -// cout << "AsyncDispatcher::thread_loop() End (inside-start) = " << GetCurrentThreadId() << endl; -// Sleep(10000); -// cout << "AsyncDispatcher::thread_loop() End (inside-done) = " << GetCurrentThreadId() << endl; - return; - } - if (m_queue.empty()){ - m_cv.wait(lg); - continue; - } - - task = m_queue.front(); - m_queue.pop_front(); - - busy = true; - m_busy_count++; - } - - try{ - task->m_task(); - }catch (...){ - task->m_exception = std::current_exception(); - task->m_stopped_with_error.store(true, std::memory_order_release); -// cout << "Task threw an exception." << endl; -// std::lock_guard lg(m_lock); -// for (AsyncTask* t : m_queue){ -// t->signal(); -// } - } - task->signal(); - } -// cout << "AsyncDispatcher::thread_loop() End (outside) = " << GetCurrentThreadId() << endl; -} - - - - - -} - +/* Thread Pool + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PanicDump.h" +#include "AsyncDispatcher.h" + +//#include +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +AsyncTask::~AsyncTask(){ + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ return m_finished; }); +} +void AsyncTask::rethrow_exceptions(){ + if (!m_stopped_with_error.load(std::memory_order_acquire)){ + return; + } + std::unique_lock lg(m_lock); + if (m_exception){ + std::rethrow_exception(m_exception); + } +} +void AsyncTask::wait_and_rethrow_exceptions(){ + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ return m_finished; }); + if (m_exception){ + std::rethrow_exception(m_exception); + } +} +void AsyncTask::signal(){ + std::lock_guard lg(m_lock); + m_finished = true; + m_cv.notify_all(); +} + + +#if 0 +AsyncDispatcher::AsyncDispatcher(size_t starting_threads) + : AsyncDispatcher(nullptr, starting_threads) +{} +#endif +AsyncDispatcher::AsyncDispatcher(std::function&& new_thread_callback, size_t starting_threads) + : m_new_thread_callback(std::move(new_thread_callback)) + , m_stopping(false) + , m_busy_count(0) +{ + for (size_t c = 0; c < starting_threads; c++){ + m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); + } +} +AsyncDispatcher::~AsyncDispatcher(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_cv.notify_all(); + } + for (std::thread& thread : m_threads){ +// cout << "AsyncDispatcher::~AsyncDispatcher() joining = " << thread.get_id() << endl; + thread.join(); + } + for (AsyncTask* task : m_queue){ + task->signal(); + } +} + +void AsyncDispatcher::ensure_threads(size_t threads){ + std::lock_guard lg(m_lock); + while (m_threads.size() < threads){ + m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); + } +} + +void AsyncDispatcher::dispatch_task(AsyncTask& task){ +// cout << "dispatch_task() - enter" << endl; + std::lock_guard lg(m_lock); + + // Enqueue task. + m_queue.emplace_back(&task); + + // Make sure a thread is ready for it. + if (m_queue.size() > m_threads.size() - m_busy_count){ + m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); + } + + m_cv.notify_one(); +// cout << "dispatch_task() - exit" << endl; +} + +std::unique_ptr AsyncDispatcher::dispatch(std::function&& func){ + std::unique_ptr task(new AsyncTask(std::move(func))); + dispatch_task(*task); +// cout << "dispatch_task - 1() - exit" << endl; + return task; +} +void AsyncDispatcher::run_in_parallel( + size_t s, size_t e, + const std::function& func +){ + if (s >= e){ + return; + } + + // Build tasks. + std::vector> tasks; + for (size_t index = 0; s + index < e; index++){ + size_t local_index = s + index; + tasks.emplace_back(new AsyncTask( + [&func, local_index]{ func(local_index); } + )); + } + + { + std::lock_guard lg(m_lock); + + // Enqueue tasks. + for (std::unique_ptr& task : tasks){ + m_queue.emplace_back(task.get()); + } + + // Make sure there are enough threads. + while (m_queue.size() > m_threads.size() - m_busy_count){ + m_threads.emplace_back(run_with_catch, "AsyncDispatcher::thread_loop()", [this]{ thread_loop(); }); + } + + for (size_t c = 0; c < tasks.size(); c++){ + m_cv.notify_one(); + } + } + + // Wait +// cout << "begin wait()" << endl; + for (std::unique_ptr& task : tasks){ + task->wait_and_rethrow_exceptions(); + } +// cout << "end wait()" << endl; +} + + + +void AsyncDispatcher::thread_loop(){ +// cout << "AsyncDispatcher::thread_loop() Start = " << GetCurrentThreadId() << ", threads = " << m_threads.size() << endl; + if (m_new_thread_callback){ + m_new_thread_callback(); + } + bool busy = false; + while (true){ + AsyncTask* task; + { + std::unique_lock lg(m_lock); + if (busy){ + m_busy_count--; + busy = false; + } + + if (m_stopping){ +// cout << "AsyncDispatcher::thread_loop() End (inside-start) = " << GetCurrentThreadId() << endl; +// Sleep(10000); +// cout << "AsyncDispatcher::thread_loop() End (inside-done) = " << GetCurrentThreadId() << endl; + return; + } + if (m_queue.empty()){ + m_cv.wait(lg); + continue; + } + + task = m_queue.front(); + m_queue.pop_front(); + + busy = true; + m_busy_count++; + } + + try{ + task->m_task(); + }catch (...){ + task->m_exception = std::current_exception(); + task->m_stopped_with_error.store(true, std::memory_order_release); +// cout << "Task threw an exception." << endl; +// std::lock_guard lg(m_lock); +// for (AsyncTask* t : m_queue){ +// t->signal(); +// } + } + task->signal(); + } +// cout << "AsyncDispatcher::thread_loop() End (outside) = " << GetCurrentThreadId() << endl; +} + + + + + +} + diff --git a/Common/Cpp/Concurrency/AsyncDispatcher.h b/Common/Cpp/Concurrency/AsyncDispatcher.h index 3f0327d4d5..531bf9951b 100644 --- a/Common/Cpp/Concurrency/AsyncDispatcher.h +++ b/Common/Cpp/Concurrency/AsyncDispatcher.h @@ -1,102 +1,102 @@ -/* Async Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - * This class is meant for asynchronous tasks, not for parallel computation. - * This class will always spawn enough threads run all tasks in parallel. - * - * If you need to spam a bunch of compute tasks in parallel, use ParallelTaskRunner. - * - */ - -#ifndef PokemonAutomation_AsyncDispatcher_H -#define PokemonAutomation_AsyncDispatcher_H - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace PokemonAutomation{ - - -class AsyncTask{ -public: - // Wait for the task to finish before destructing. Doesn't rethrow exceptions. - ~AsyncTask(); - - // If the task ended with an exception, rethrow it here. - // This does not clear the exception. - void rethrow_exceptions(); - - // Wait for the task to finish. Will rethrow any exceptions. - void wait_and_rethrow_exceptions(); - - -private: - template - AsyncTask(Args&&... args) - : m_task(std::forward(args)...) - , m_finished(false) - , m_stopped_with_error(false) - {} - void signal(); - -private: - friend class FireForgetDispatcher; - friend class AsyncDispatcher; - friend class ParallelTaskRunner; - - std::function m_task; - bool m_finished; - std::atomic m_stopped_with_error; - std::exception_ptr m_exception; - std::mutex m_lock; - std::condition_variable m_cv; -}; - - - -class AsyncDispatcher{ -public: -// AsyncDispatcher(size_t starting_threads); - AsyncDispatcher(std::function&& new_thread_callback, size_t starting_threads); - ~AsyncDispatcher(); - - // Ensure a certain # of threads so they don't need to be lazily created. - void ensure_threads(size_t threads); - - // Dispatch the specified task and return a handle to it. - // Call "handle->wait()" to wait for the task to finish. - std::unique_ptr dispatch(std::function&& func); - - // Run the specified lambda for indices [s, e) in parallel. - void run_in_parallel( - size_t s, size_t e, - const std::function& func - ); - -private: - void dispatch_task(AsyncTask& task); - void thread_loop(); - -private: - std::function m_new_thread_callback; - std::deque m_queue; - std::vector m_threads; - bool m_stopping; - size_t m_busy_count; - std::mutex m_lock; - std::condition_variable m_cv; -}; - - - - -} - -#endif +/* Async Task Runner + * + * From: https://github.com/PokemonAutomation/ + * + * This class is meant for asynchronous tasks, not for parallel computation. + * This class will always spawn enough threads run all tasks in parallel. + * + * If you need to spam a bunch of compute tasks in parallel, use ParallelTaskRunner. + * + */ + +#ifndef PokemonAutomation_AsyncDispatcher_H +#define PokemonAutomation_AsyncDispatcher_H + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ + + +class AsyncTask{ +public: + // Wait for the task to finish before destructing. Doesn't rethrow exceptions. + ~AsyncTask(); + + // If the task ended with an exception, rethrow it here. + // This does not clear the exception. + void rethrow_exceptions(); + + // Wait for the task to finish. Will rethrow any exceptions. + void wait_and_rethrow_exceptions(); + + +private: + template + AsyncTask(Args&&... args) + : m_task(std::forward(args)...) + , m_finished(false) + , m_stopped_with_error(false) + {} + void signal(); + +private: + friend class FireForgetDispatcher; + friend class AsyncDispatcher; + friend class ParallelTaskRunner; + + std::function m_task; + bool m_finished; + std::atomic m_stopped_with_error; + std::exception_ptr m_exception; + std::mutex m_lock; + std::condition_variable m_cv; +}; + + + +class AsyncDispatcher{ +public: +// AsyncDispatcher(size_t starting_threads); + AsyncDispatcher(std::function&& new_thread_callback, size_t starting_threads); + ~AsyncDispatcher(); + + // Ensure a certain # of threads so they don't need to be lazily created. + void ensure_threads(size_t threads); + + // Dispatch the specified task and return a handle to it. + // Call "handle->wait()" to wait for the task to finish. + std::unique_ptr dispatch(std::function&& func); + + // Run the specified lambda for indices [s, e) in parallel. + void run_in_parallel( + size_t s, size_t e, + const std::function& func + ); + +private: + void dispatch_task(AsyncTask& task); + void thread_loop(); + +private: + std::function m_new_thread_callback; + std::deque m_queue; + std::vector m_threads; + bool m_stopping; + size_t m_busy_count; + std::mutex m_lock; + std::condition_variable m_cv; +}; + + + + +} + +#endif diff --git a/Common/Cpp/Concurrency/FireForgetDispatcher.cpp b/Common/Cpp/Concurrency/FireForgetDispatcher.cpp index 12005ea3d1..8c70bccbd4 100644 --- a/Common/Cpp/Concurrency/FireForgetDispatcher.cpp +++ b/Common/Cpp/Concurrency/FireForgetDispatcher.cpp @@ -1,69 +1,69 @@ -/* Fire and Forget Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "FireForgetDispatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -FireForgetDispatcher global_dispatcher; - - - -FireForgetDispatcher::FireForgetDispatcher() - : m_stopping(false) -{} -FireForgetDispatcher::~FireForgetDispatcher(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_cv.notify_all(); - } - if (m_thread.joinable()){ - m_thread.join(); - } -} -void FireForgetDispatcher::dispatch(std::function&& func){ - std::lock_guard lg(m_lock); - m_queue.emplace_back(std::move(func)); - m_cv.notify_one(); - - // Lazy create thread. - if (!m_thread.joinable()){ - m_thread = std::thread(run_with_catch, "FireForgetDispatcher::thread_loop()", [this]{ thread_loop(); }); - } -} - -void FireForgetDispatcher::thread_loop(){ - while (true){ - std::function task; - { - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - if (m_queue.empty()){ - m_cv.wait(lg); - continue; - } - - task = std::move(m_queue.front()); - m_queue.pop_front(); - } - - task(); - } -} - - - -} +/* Fire and Forget Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "FireForgetDispatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +FireForgetDispatcher global_dispatcher; + + + +FireForgetDispatcher::FireForgetDispatcher() + : m_stopping(false) +{} +FireForgetDispatcher::~FireForgetDispatcher(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_cv.notify_all(); + } + if (m_thread.joinable()){ + m_thread.join(); + } +} +void FireForgetDispatcher::dispatch(std::function&& func){ + std::lock_guard lg(m_lock); + m_queue.emplace_back(std::move(func)); + m_cv.notify_one(); + + // Lazy create thread. + if (!m_thread.joinable()){ + m_thread = std::thread(run_with_catch, "FireForgetDispatcher::thread_loop()", [this]{ thread_loop(); }); + } +} + +void FireForgetDispatcher::thread_loop(){ + while (true){ + std::function task; + { + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + if (m_queue.empty()){ + m_cv.wait(lg); + continue; + } + + task = std::move(m_queue.front()); + m_queue.pop_front(); + } + + task(); + } +} + + + +} diff --git a/Common/Cpp/Concurrency/FireForgetDispatcher.h b/Common/Cpp/Concurrency/FireForgetDispatcher.h index fc4961bd0c..dd48770404 100644 --- a/Common/Cpp/Concurrency/FireForgetDispatcher.h +++ b/Common/Cpp/Concurrency/FireForgetDispatcher.h @@ -1,49 +1,49 @@ -/* Fire and Forget Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_FireForgetDispatcher_H -#define PokemonAutomation_FireForgetDispatcher_H - -#include -#include -#include -#include -#include - -namespace PokemonAutomation{ - - -class FireForgetDispatcher{ -public: - FireForgetDispatcher(); - ~FireForgetDispatcher(); - - // Dispatch the specified task and return a handle to it. - // Call "handle->wait()" to wait for the task to finish. - void dispatch(std::function&& func); - - -private: - void thread_loop(); - -private: - std::deque> m_queue; - std::thread m_thread; - bool m_stopping; - std::mutex m_lock; - std::condition_variable m_cv; -}; - - -extern FireForgetDispatcher global_dispatcher; - - - - - -} -#endif - +/* Fire and Forget Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_FireForgetDispatcher_H +#define PokemonAutomation_FireForgetDispatcher_H + +#include +#include +#include +#include +#include + +namespace PokemonAutomation{ + + +class FireForgetDispatcher{ +public: + FireForgetDispatcher(); + ~FireForgetDispatcher(); + + // Dispatch the specified task and return a handle to it. + // Call "handle->wait()" to wait for the task to finish. + void dispatch(std::function&& func); + + +private: + void thread_loop(); + +private: + std::deque> m_queue; + std::thread m_thread; + bool m_stopping; + std::mutex m_lock; + std::condition_variable m_cv; +}; + + +extern FireForgetDispatcher global_dispatcher; + + + + + +} +#endif + diff --git a/Common/Cpp/Concurrency/ParallelTaskRunner.cpp b/Common/Cpp/Concurrency/ParallelTaskRunner.cpp index ade11dd5fa..1798663d59 100644 --- a/Common/Cpp/Concurrency/ParallelTaskRunner.cpp +++ b/Common/Cpp/Concurrency/ParallelTaskRunner.cpp @@ -1,159 +1,159 @@ -/* Parallel Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#if _WIN32 -#include -#endif -#include "Common/Cpp/PanicDump.h" -#include "ParallelTaskRunner.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ParallelTaskRunner::ParallelTaskRunner( - std::function&& new_thread_callback, - size_t starting_threads, - size_t max_threads -) - : m_new_thread_callback(std::move(new_thread_callback)) - , m_max_threads(max_threads == 0 ? std::thread::hardware_concurrency() : max_threads) - , m_stopping(false) - , m_busy_count(0) -{ - for (size_t c = 0; c < starting_threads; c++){ - m_threads.emplace_back(run_with_catch, "ParallelTaskRunner::thread_loop()", [this]{ thread_loop(); }); - } -} -ParallelTaskRunner::~ParallelTaskRunner(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_thread_cv.notify_all(); -// m_dispatch_cv.notify_all(); - } - for (std::thread& thread : m_threads){ - thread.join(); - } - for (auto& task : m_queue){ - task->signal(); - } -} - -void ParallelTaskRunner::wait_for_everything(){ - std::unique_lock lg(m_lock); - m_dispatch_cv.wait(lg, [this]{ - return m_queue.size() + m_busy_count == 0; - }); -} - -std::shared_ptr ParallelTaskRunner::dispatch(std::function&& func){ - std::shared_ptr task(new AsyncTask(std::move(func))); - - std::unique_lock lg(m_lock); - - m_dispatch_cv.wait(lg, [this]{ - return m_queue.size() + m_busy_count < m_max_threads; - }); - - // Enqueue task. - m_queue.emplace_back(task); - - if (m_queue.size() + m_busy_count > m_threads.size()){ - m_threads.emplace_back(run_with_catch, "ParallelTaskRunner::thread_loop()", [this]{ thread_loop(); }); - } - - m_thread_cv.notify_one(); - - return task; -} - - -void ParallelTaskRunner::run_in_parallel( - const std::function& func, - size_t start, size_t end, - size_t block_size -){ - if (start >= end){ - return; - } - size_t total = end - start; - size_t blocks = (total + block_size - 1) / block_size; - - std::vector> tasks; - for (size_t c = 0; c < blocks; c++){ - tasks.emplace_back(dispatch([=, &func]{ - size_t s = start + c * block_size; - size_t e = std::min(s + block_size, end); -// cout << "Running: [" << s << "," << e << ")" << endl; - for (; s < e; s++){ - func(s); - } - })); - } - - for (std::shared_ptr& task : tasks){ - task->wait_and_rethrow_exceptions(); - } -} - - - - -void ParallelTaskRunner::thread_loop(){ -//#if _WIN32 -// SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); -//#endif - if (m_new_thread_callback){ - m_new_thread_callback(); - } - - bool busy = false; - while (true){ - std::shared_ptr task; - { - std::unique_lock lg(m_lock); - if (busy){ - m_busy_count--; - busy = false; - m_dispatch_cv.notify_all(); - } - - if (m_stopping){ - return; - } - if (m_queue.empty()){ - m_thread_cv.wait(lg); - continue; - } - - task = m_queue.front(); - m_queue.pop_front(); - - busy = true; - m_busy_count++; - } - - try{ - task->m_task(); - }catch (...){ - task->m_exception = std::current_exception(); -// std::lock_guard lg(m_lock); -// for (std::shared_ptr& t : m_queue){ -// t->signal(); -// } - } - task->signal(); - } -} - - - -} +/* Parallel Task Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#if _WIN32 +#include +#endif +#include "Common/Cpp/PanicDump.h" +#include "ParallelTaskRunner.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ParallelTaskRunner::ParallelTaskRunner( + std::function&& new_thread_callback, + size_t starting_threads, + size_t max_threads +) + : m_new_thread_callback(std::move(new_thread_callback)) + , m_max_threads(max_threads == 0 ? std::thread::hardware_concurrency() : max_threads) + , m_stopping(false) + , m_busy_count(0) +{ + for (size_t c = 0; c < starting_threads; c++){ + m_threads.emplace_back(run_with_catch, "ParallelTaskRunner::thread_loop()", [this]{ thread_loop(); }); + } +} +ParallelTaskRunner::~ParallelTaskRunner(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_thread_cv.notify_all(); +// m_dispatch_cv.notify_all(); + } + for (std::thread& thread : m_threads){ + thread.join(); + } + for (auto& task : m_queue){ + task->signal(); + } +} + +void ParallelTaskRunner::wait_for_everything(){ + std::unique_lock lg(m_lock); + m_dispatch_cv.wait(lg, [this]{ + return m_queue.size() + m_busy_count == 0; + }); +} + +std::shared_ptr ParallelTaskRunner::dispatch(std::function&& func){ + std::shared_ptr task(new AsyncTask(std::move(func))); + + std::unique_lock lg(m_lock); + + m_dispatch_cv.wait(lg, [this]{ + return m_queue.size() + m_busy_count < m_max_threads; + }); + + // Enqueue task. + m_queue.emplace_back(task); + + if (m_queue.size() + m_busy_count > m_threads.size()){ + m_threads.emplace_back(run_with_catch, "ParallelTaskRunner::thread_loop()", [this]{ thread_loop(); }); + } + + m_thread_cv.notify_one(); + + return task; +} + + +void ParallelTaskRunner::run_in_parallel( + const std::function& func, + size_t start, size_t end, + size_t block_size +){ + if (start >= end){ + return; + } + size_t total = end - start; + size_t blocks = (total + block_size - 1) / block_size; + + std::vector> tasks; + for (size_t c = 0; c < blocks; c++){ + tasks.emplace_back(dispatch([=, &func]{ + size_t s = start + c * block_size; + size_t e = std::min(s + block_size, end); +// cout << "Running: [" << s << "," << e << ")" << endl; + for (; s < e; s++){ + func(s); + } + })); + } + + for (std::shared_ptr& task : tasks){ + task->wait_and_rethrow_exceptions(); + } +} + + + + +void ParallelTaskRunner::thread_loop(){ +//#if _WIN32 +// SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_IDLE); +//#endif + if (m_new_thread_callback){ + m_new_thread_callback(); + } + + bool busy = false; + while (true){ + std::shared_ptr task; + { + std::unique_lock lg(m_lock); + if (busy){ + m_busy_count--; + busy = false; + m_dispatch_cv.notify_all(); + } + + if (m_stopping){ + return; + } + if (m_queue.empty()){ + m_thread_cv.wait(lg); + continue; + } + + task = m_queue.front(); + m_queue.pop_front(); + + busy = true; + m_busy_count++; + } + + try{ + task->m_task(); + }catch (...){ + task->m_exception = std::current_exception(); +// std::lock_guard lg(m_lock); +// for (std::shared_ptr& t : m_queue){ +// t->signal(); +// } + } + task->signal(); + } +} + + + +} diff --git a/Common/Cpp/Concurrency/ParallelTaskRunner.h b/Common/Cpp/Concurrency/ParallelTaskRunner.h index b682d41398..e544312d34 100644 --- a/Common/Cpp/Concurrency/ParallelTaskRunner.h +++ b/Common/Cpp/Concurrency/ParallelTaskRunner.h @@ -1,57 +1,57 @@ -/* Parallel Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ParallelTaskRunner_H -#define PokemonAutomation_ParallelTaskRunner_H - -#include "AsyncDispatcher.h" - -namespace PokemonAutomation{ - - -class ParallelTaskRunner{ -public: - ParallelTaskRunner( - std::function&& new_thread_callback, - size_t starting_threads, - size_t max_threads - ); - ~ParallelTaskRunner(); - - void wait_for_everything(); - - std::shared_ptr dispatch(std::function&& func); - - void run_in_parallel( - const std::function& func, - size_t start, size_t end, - size_t block_size = 0 - ); - - -private: -// void dispatch_task(AsyncTask& task); - void thread_loop(); - - -private: - std::function m_new_thread_callback; - size_t m_max_threads; - std::deque> m_queue; - std::vector m_threads; - bool m_stopping; - size_t m_busy_count; - std::mutex m_lock; - std::condition_variable m_thread_cv; - std::condition_variable m_dispatch_cv; -}; - - - - - -} -#endif +/* Parallel Task Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ParallelTaskRunner_H +#define PokemonAutomation_ParallelTaskRunner_H + +#include "AsyncDispatcher.h" + +namespace PokemonAutomation{ + + +class ParallelTaskRunner{ +public: + ParallelTaskRunner( + std::function&& new_thread_callback, + size_t starting_threads, + size_t max_threads + ); + ~ParallelTaskRunner(); + + void wait_for_everything(); + + std::shared_ptr dispatch(std::function&& func); + + void run_in_parallel( + const std::function& func, + size_t start, size_t end, + size_t block_size = 0 + ); + + +private: +// void dispatch_task(AsyncTask& task); + void thread_loop(); + + +private: + std::function m_new_thread_callback; + size_t m_max_threads; + std::deque> m_queue; + std::vector m_threads; + bool m_stopping; + size_t m_busy_count; + std::mutex m_lock; + std::condition_variable m_thread_cv; + std::condition_variable m_dispatch_cv; +}; + + + + + +} +#endif diff --git a/Common/Cpp/Concurrency/PeriodicScheduler.cpp b/Common/Cpp/Concurrency/PeriodicScheduler.cpp index 61e60745b4..e664255080 100644 --- a/Common/Cpp/Concurrency/PeriodicScheduler.cpp +++ b/Common/Cpp/Concurrency/PeriodicScheduler.cpp @@ -1,216 +1,216 @@ -/* Periodic Scheduler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PeriodicScheduler.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -size_t PeriodicScheduler::events() const{ - return m_events.size(); -} -bool PeriodicScheduler::add_event(void* event, std::chrono::milliseconds period, WallClock start){ - auto ret = m_events.emplace(event, PeriodicEvent{m_callback_id, period}); - if (!ret.second){ - // Already exists. Do nothing. - return false; - } - - // Now add to schedule. Need to ensure strong exception safety. - try{ - m_schedule.emplace(start, SingleEvent{m_callback_id, event}); - }catch (...){ - m_events.erase(ret.first); - throw; - } - - m_callback_id++; - return true; -} -void PeriodicScheduler::remove_event(void* event){ - // No need to remove from scheduler since it will be skipped over automatically. - m_events.erase(event); -} -WallClock PeriodicScheduler::next_event() const{ - auto iter = m_schedule.begin(); - if (iter == m_schedule.end()){ - return WallClock::max(); - } - return iter->first; -} -void* PeriodicScheduler::request_next_event(WallClock timestamp){ - while (true){ - auto iter0 = m_schedule.begin(); - - // Schedule is empty. - if (iter0 == m_schedule.end()){ - return nullptr; - } - - // Next event isn't due. - if (timestamp < iter0->first){ - return nullptr; - } - - // Current SingleEvent refers to a no longer existing PeriodicEvent. - SingleEvent event = iter0->second; - auto iter1 = m_events.find(event.event); - if (iter1 == m_events.end() || event.id != iter1->second.id){ - m_schedule.erase(iter0); - continue; - } - - // Schedule the next event first so that we retain strong exception safety if it throws. - WallClock next = std::max(iter0->first + iter1->second.period, timestamp); - m_schedule.emplace(next, iter0->second); - - // Now remove the current event. - m_schedule.erase(iter0); - - return event.event; - } -} - - - - - - -#if 0 -class ScopedCounter{ -public: - ScopedCounter(std::atomic& counter) - : m_counter(counter) - { - counter++; - } - ~ScopedCounter(){ - m_counter--; - } - -private: - std::atomic& m_counter; -}; -#endif - - - - - -PeriodicRunner::PeriodicRunner(AsyncDispatcher& dispatcher) - : m_dispatcher(dispatcher) - , m_pending_waits(0) -{} -bool PeriodicRunner::add_event(void* event, std::chrono::milliseconds period, WallClock start){ - throw_if_cancelled(); - - m_pending_waits++; - std::lock_guard lg(m_lock); - m_pending_waits--; - - // Thread not started yet. Do this first for strong exception safety. - if (!m_runner){ - m_runner = m_dispatcher.dispatch([this]{ thread_loop(); }); - } - - bool ret = m_scheduler.add_event(event, period, start); - m_cv.notify_all(); - return ret; -} -void PeriodicRunner::remove_event(void* event){ - m_pending_waits++; - std::lock_guard lg(m_lock); - m_pending_waits--; - m_scheduler.remove_event(event); - m_cv.notify_all(); - - if (m_scheduler.events() == 0){ - WriteSpinLock lg1(m_stats_lock); - m_utilization.push_idle(); - } -} -bool PeriodicRunner::cancel(std::exception_ptr exception) noexcept{ - if (Cancellable::cancel(std::move(exception))){ - return true; - } - std::lock_guard lg(m_lock); - m_cv.notify_all(); - return false; -} -void PeriodicRunner::thread_loop(){ - bool is_back_to_back = false; - std::unique_lock lg(m_lock); - WallClock last_check_timestamp = current_time(); - WallClock::duration idle_since_last_check = WallClock::duration(0); - while (true){ - if (cancelled()){ - return; - } - - // If anyone is trying to get the lock, yield now. - if (m_pending_waits.load(std::memory_order_acquire) != 0){ - m_cv.wait(lg, [this]{ return m_pending_waits.load(std::memory_order_acquire) == 0; }); - } - - WallClock now = current_time(); - - { - WriteSpinLock lg1(m_stats_lock); - m_utilization.push_event(now - last_check_timestamp - idle_since_last_check, now); - } - last_check_timestamp = now; - idle_since_last_check = WallClock::duration(0); -// cout << m_utilization.utilization() << endl; - - void* event = m_scheduler.request_next_event(now); - - // Event is available now. Run it. - if (event != nullptr){ - run(event, is_back_to_back); - is_back_to_back = true; - continue; - } - is_back_to_back = false; - - // Wait for next scheduled event. - WallClock next = m_scheduler.next_event(); - - if (cancelled()){ - return; - } - - WallClock start = current_time(); - if (next < WallClock::max()){ - m_cv.wait_until(lg, next); - }else{ - m_cv.wait(lg); - } - WallClock end = current_time(); - idle_since_last_check += end - start; - } -} -void PeriodicRunner::stop_thread(){ - PeriodicRunner::cancel(nullptr); - m_runner.reset(); -} - -double PeriodicRunner::current_utilization() const{ - ReadSpinLock lg(m_stats_lock); - return m_utilization.utilization(); -} - - - - - - - - -} +/* Periodic Scheduler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PeriodicScheduler.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +size_t PeriodicScheduler::events() const{ + return m_events.size(); +} +bool PeriodicScheduler::add_event(void* event, std::chrono::milliseconds period, WallClock start){ + auto ret = m_events.emplace(event, PeriodicEvent{m_callback_id, period}); + if (!ret.second){ + // Already exists. Do nothing. + return false; + } + + // Now add to schedule. Need to ensure strong exception safety. + try{ + m_schedule.emplace(start, SingleEvent{m_callback_id, event}); + }catch (...){ + m_events.erase(ret.first); + throw; + } + + m_callback_id++; + return true; +} +void PeriodicScheduler::remove_event(void* event){ + // No need to remove from scheduler since it will be skipped over automatically. + m_events.erase(event); +} +WallClock PeriodicScheduler::next_event() const{ + auto iter = m_schedule.begin(); + if (iter == m_schedule.end()){ + return WallClock::max(); + } + return iter->first; +} +void* PeriodicScheduler::request_next_event(WallClock timestamp){ + while (true){ + auto iter0 = m_schedule.begin(); + + // Schedule is empty. + if (iter0 == m_schedule.end()){ + return nullptr; + } + + // Next event isn't due. + if (timestamp < iter0->first){ + return nullptr; + } + + // Current SingleEvent refers to a no longer existing PeriodicEvent. + SingleEvent event = iter0->second; + auto iter1 = m_events.find(event.event); + if (iter1 == m_events.end() || event.id != iter1->second.id){ + m_schedule.erase(iter0); + continue; + } + + // Schedule the next event first so that we retain strong exception safety if it throws. + WallClock next = std::max(iter0->first + iter1->second.period, timestamp); + m_schedule.emplace(next, iter0->second); + + // Now remove the current event. + m_schedule.erase(iter0); + + return event.event; + } +} + + + + + + +#if 0 +class ScopedCounter{ +public: + ScopedCounter(std::atomic& counter) + : m_counter(counter) + { + counter++; + } + ~ScopedCounter(){ + m_counter--; + } + +private: + std::atomic& m_counter; +}; +#endif + + + + + +PeriodicRunner::PeriodicRunner(AsyncDispatcher& dispatcher) + : m_dispatcher(dispatcher) + , m_pending_waits(0) +{} +bool PeriodicRunner::add_event(void* event, std::chrono::milliseconds period, WallClock start){ + throw_if_cancelled(); + + m_pending_waits++; + std::lock_guard lg(m_lock); + m_pending_waits--; + + // Thread not started yet. Do this first for strong exception safety. + if (!m_runner){ + m_runner = m_dispatcher.dispatch([this]{ thread_loop(); }); + } + + bool ret = m_scheduler.add_event(event, period, start); + m_cv.notify_all(); + return ret; +} +void PeriodicRunner::remove_event(void* event){ + m_pending_waits++; + std::lock_guard lg(m_lock); + m_pending_waits--; + m_scheduler.remove_event(event); + m_cv.notify_all(); + + if (m_scheduler.events() == 0){ + WriteSpinLock lg1(m_stats_lock); + m_utilization.push_idle(); + } +} +bool PeriodicRunner::cancel(std::exception_ptr exception) noexcept{ + if (Cancellable::cancel(std::move(exception))){ + return true; + } + std::lock_guard lg(m_lock); + m_cv.notify_all(); + return false; +} +void PeriodicRunner::thread_loop(){ + bool is_back_to_back = false; + std::unique_lock lg(m_lock); + WallClock last_check_timestamp = current_time(); + WallClock::duration idle_since_last_check = WallClock::duration(0); + while (true){ + if (cancelled()){ + return; + } + + // If anyone is trying to get the lock, yield now. + if (m_pending_waits.load(std::memory_order_acquire) != 0){ + m_cv.wait(lg, [this]{ return m_pending_waits.load(std::memory_order_acquire) == 0; }); + } + + WallClock now = current_time(); + + { + WriteSpinLock lg1(m_stats_lock); + m_utilization.push_event(now - last_check_timestamp - idle_since_last_check, now); + } + last_check_timestamp = now; + idle_since_last_check = WallClock::duration(0); +// cout << m_utilization.utilization() << endl; + + void* event = m_scheduler.request_next_event(now); + + // Event is available now. Run it. + if (event != nullptr){ + run(event, is_back_to_back); + is_back_to_back = true; + continue; + } + is_back_to_back = false; + + // Wait for next scheduled event. + WallClock next = m_scheduler.next_event(); + + if (cancelled()){ + return; + } + + WallClock start = current_time(); + if (next < WallClock::max()){ + m_cv.wait_until(lg, next); + }else{ + m_cv.wait(lg); + } + WallClock end = current_time(); + idle_since_last_check += end - start; + } +} +void PeriodicRunner::stop_thread(){ + PeriodicRunner::cancel(nullptr); + m_runner.reset(); +} + +double PeriodicRunner::current_utilization() const{ + ReadSpinLock lg(m_stats_lock); + return m_utilization.utilization(); +} + + + + + + + + +} diff --git a/Common/Cpp/Concurrency/PeriodicScheduler.h b/Common/Cpp/Concurrency/PeriodicScheduler.h index d7259f3cf0..16a5e77d31 100644 --- a/Common/Cpp/Concurrency/PeriodicScheduler.h +++ b/Common/Cpp/Concurrency/PeriodicScheduler.h @@ -1,111 +1,111 @@ -/* Periodic Scheduler - * - * From: https://github.com/PokemonAutomation/ - * - * Periodically call a set of callbacks at custom intervals. - * - */ - -#ifndef PokemonAutomation_PeriodicScheduler_H -#define PokemonAutomation_PeriodicScheduler_H - -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/EventRateTracker.h" -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "AsyncDispatcher.h" - -namespace PokemonAutomation{ - - -// -// This is the raw (unprotected) data structure that tracks all the events -// and determines what event should be fired next and when. -// -class PeriodicScheduler{ -public: - size_t events() const; - - // Returns true if event was successfully added. - bool add_event(void* event, std::chrono::milliseconds period, WallClock start = current_time()); - void remove_event(void* event); - - // Returns the next scheduled event. If no events are scheduled, returns WallClock::max(). - WallClock next_event() const; - - // If an event is before the current timestamp, return it and reschedule for next period. - // If nothing is before the current timestamp, return nullptr. - void* request_next_event(WallClock timestamp = current_time()); - -private: - // "id" is needed to solve the ABA problem if the same pointer is removed/re-added. - struct PeriodicEvent{ - uint64_t id; - std::chrono::milliseconds period; - }; - struct SingleEvent{ - uint64_t id; - void* event; - }; - -private: - uint64_t m_callback_id = 0; - std::map m_events; - std::multimap m_schedule; -}; - - - -// -// This is the actual callback runner class that will run the callbacks -// at their specified periods. -// -// Adding and removing callbacks is thread-safe. -// -class PeriodicRunner : public Cancellable{ -public: - virtual bool cancel(std::exception_ptr exception) noexcept override; - - double current_utilization() const; - -protected: - PeriodicRunner(AsyncDispatcher& dispatcher); - bool add_event(void* event, std::chrono::milliseconds period, WallClock start = current_time()); - void remove_event(void* event); - - // Run the event. "is_back_to_back" is true if there was no wait between - // this event and the previous one. - // This can be used is a performance hint to the child class to reuse - // state for two close-in-time events or to determine if the inference - // is too slow to keep up. - virtual void run(void* event, bool is_back_to_back) noexcept = 0; - -private: - void thread_loop(); -protected: - void stop_thread(); - -private: - AsyncDispatcher& m_dispatcher; - - std::atomic m_pending_waits; - std::mutex m_lock; - std::condition_variable m_cv; - - mutable SpinLock m_stats_lock; - UtilizationTracker m_utilization; - - PeriodicScheduler m_scheduler; - - std::unique_ptr m_runner; -}; - - - - -} -#endif +/* Periodic Scheduler + * + * From: https://github.com/PokemonAutomation/ + * + * Periodically call a set of callbacks at custom intervals. + * + */ + +#ifndef PokemonAutomation_PeriodicScheduler_H +#define PokemonAutomation_PeriodicScheduler_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/EventRateTracker.h" +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "AsyncDispatcher.h" + +namespace PokemonAutomation{ + + +// +// This is the raw (unprotected) data structure that tracks all the events +// and determines what event should be fired next and when. +// +class PeriodicScheduler{ +public: + size_t events() const; + + // Returns true if event was successfully added. + bool add_event(void* event, std::chrono::milliseconds period, WallClock start = current_time()); + void remove_event(void* event); + + // Returns the next scheduled event. If no events are scheduled, returns WallClock::max(). + WallClock next_event() const; + + // If an event is before the current timestamp, return it and reschedule for next period. + // If nothing is before the current timestamp, return nullptr. + void* request_next_event(WallClock timestamp = current_time()); + +private: + // "id" is needed to solve the ABA problem if the same pointer is removed/re-added. + struct PeriodicEvent{ + uint64_t id; + std::chrono::milliseconds period; + }; + struct SingleEvent{ + uint64_t id; + void* event; + }; + +private: + uint64_t m_callback_id = 0; + std::map m_events; + std::multimap m_schedule; +}; + + + +// +// This is the actual callback runner class that will run the callbacks +// at their specified periods. +// +// Adding and removing callbacks is thread-safe. +// +class PeriodicRunner : public Cancellable{ +public: + virtual bool cancel(std::exception_ptr exception) noexcept override; + + double current_utilization() const; + +protected: + PeriodicRunner(AsyncDispatcher& dispatcher); + bool add_event(void* event, std::chrono::milliseconds period, WallClock start = current_time()); + void remove_event(void* event); + + // Run the event. "is_back_to_back" is true if there was no wait between + // this event and the previous one. + // This can be used is a performance hint to the child class to reuse + // state for two close-in-time events or to determine if the inference + // is too slow to keep up. + virtual void run(void* event, bool is_back_to_back) noexcept = 0; + +private: + void thread_loop(); +protected: + void stop_thread(); + +private: + AsyncDispatcher& m_dispatcher; + + std::atomic m_pending_waits; + std::mutex m_lock; + std::condition_variable m_cv; + + mutable SpinLock m_stats_lock; + UtilizationTracker m_utilization; + + PeriodicScheduler m_scheduler; + + std::unique_ptr m_runner; +}; + + + + +} +#endif diff --git a/Common/Cpp/Concurrency/ReverseLockGuard.h b/Common/Cpp/Concurrency/ReverseLockGuard.h index 312a3a7312..69de98cad8 100644 --- a/Common/Cpp/Concurrency/ReverseLockGuard.h +++ b/Common/Cpp/Concurrency/ReverseLockGuard.h @@ -1,40 +1,40 @@ -/* Reverse Lock Guard - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ReverseLockGuard_H -#define PokemonAutomation_ReverseLockGuard_H - -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - -template -class ReverseLockGuard{ -public: - ReverseLockGuard(Mutex& lock) - : m_lock(lock) - { - if (lock.try_lock()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Attempted to unlock an already unlocked lock." - ); - } - lock.unlock(); - } - ~ReverseLockGuard(){ - m_lock.lock(); - } - - -private: - Mutex& m_lock; -}; - - -} -#endif +/* Reverse Lock Guard + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ReverseLockGuard_H +#define PokemonAutomation_ReverseLockGuard_H + +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + +template +class ReverseLockGuard{ +public: + ReverseLockGuard(Mutex& lock) + : m_lock(lock) + { + if (lock.try_lock()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Attempted to unlock an already unlocked lock." + ); + } + lock.unlock(); + } + ~ReverseLockGuard(){ + m_lock.lock(); + } + + +private: + Mutex& m_lock; +}; + + +} +#endif diff --git a/Common/Cpp/Concurrency/ScheduledTaskRunner.cpp b/Common/Cpp/Concurrency/ScheduledTaskRunner.cpp index d170bde897..7c60923e62 100644 --- a/Common/Cpp/Concurrency/ScheduledTaskRunner.cpp +++ b/Common/Cpp/Concurrency/ScheduledTaskRunner.cpp @@ -1,112 +1,112 @@ -/* Scheduled Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - * Run tasks at their scheduled times. - * - */ - -#include "ScheduledTaskRunner.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ScheduledTaskRunner::~ScheduledTaskRunner(){ -// ScheduledTaskRunner::cancel(nullptr); - { - std::lock_guard lg(m_lock); -// cout << "ScheduledTaskRunner: (Destructor - start): " << this << endl; - m_stopped = true; - m_cv.notify_all(); - } - m_runner.reset(); -// cout << "ScheduledTaskRunner: (Destructor - end): " << this << endl; -} -ScheduledTaskRunner::ScheduledTaskRunner(AsyncDispatcher& dispatcher) - : m_stopped(false) - , m_runner(dispatcher.dispatch([this]{ thread_loop(); })) -{ -// cout << "ScheduledTaskRunner: (Constructor): " << this << endl; -} -size_t ScheduledTaskRunner::size() const{ - std::lock_guard lg(m_lock); - return m_schedule.size(); -} -WallClock ScheduledTaskRunner::next_event() const{ - std::lock_guard lg(m_lock); - if (m_stopped || m_schedule.empty()){ - return WallClock::max(); - } - return m_schedule.begin()->first; -} -void ScheduledTaskRunner::add_event(WallClock time, std::function callback){ - std::lock_guard lg(m_lock); - if (m_stopped){ - return; - } - m_schedule.emplace(time, std::move(callback)); - m_cv.notify_all(); -} -void ScheduledTaskRunner::add_event(std::chrono::milliseconds time_from_now, std::function callback){ - std::lock_guard lg(m_lock); - if (m_stopped){ - return; - } - m_schedule.emplace(current_time() + time_from_now, std::move(callback)); - m_cv.notify_all(); -} -#if 0 -bool ScheduledTaskRunner::cancel(std::exception_ptr exception) noexcept{ - if (Cancellable::cancel(std::move(exception))){ - return true; - } - std::lock_guard lg(m_lock); - m_cv.notify_all(); - return false; -} -#endif -void ScheduledTaskRunner::thread_loop(){ - std::unique_lock lg(m_lock); -// cout << "ScheduledTaskRunner: (Starting thread loop): " << this << endl; -// WallClock last_check_timestamp = current_time(); - while (!m_stopped){ -#if 0 - if (cancelled()){ - return; - } -#endif - - if (m_schedule.empty()){ -// cout << "ScheduledTaskRunner: (Sleeping): " << this << endl; - m_cv.wait(lg); -// cout << "ScheduledTaskRunner: (Waking): " << this << endl; - continue; - } - - auto item = m_schedule.begin(); - WallClock now = current_time(); - if (item->first > now){ - m_cv.wait_until(lg, item->first); - continue; - } -// cout << "ScheduledTaskRunner: (task - start): " << this << endl; - lg.unlock(); - item->second(); - lg.lock(); -// cout << "ScheduledTaskRunner: (task - end): " << this << endl; - m_schedule.erase(item); - } -// cout << "ScheduledTaskRunner: (Clearing schedule): " << this << endl; - m_schedule.clear(); -} - - - - - -} +/* Scheduled Task Runner + * + * From: https://github.com/PokemonAutomation/ + * + * Run tasks at their scheduled times. + * + */ + +#include "ScheduledTaskRunner.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ScheduledTaskRunner::~ScheduledTaskRunner(){ +// ScheduledTaskRunner::cancel(nullptr); + { + std::lock_guard lg(m_lock); +// cout << "ScheduledTaskRunner: (Destructor - start): " << this << endl; + m_stopped = true; + m_cv.notify_all(); + } + m_runner.reset(); +// cout << "ScheduledTaskRunner: (Destructor - end): " << this << endl; +} +ScheduledTaskRunner::ScheduledTaskRunner(AsyncDispatcher& dispatcher) + : m_stopped(false) + , m_runner(dispatcher.dispatch([this]{ thread_loop(); })) +{ +// cout << "ScheduledTaskRunner: (Constructor): " << this << endl; +} +size_t ScheduledTaskRunner::size() const{ + std::lock_guard lg(m_lock); + return m_schedule.size(); +} +WallClock ScheduledTaskRunner::next_event() const{ + std::lock_guard lg(m_lock); + if (m_stopped || m_schedule.empty()){ + return WallClock::max(); + } + return m_schedule.begin()->first; +} +void ScheduledTaskRunner::add_event(WallClock time, std::function callback){ + std::lock_guard lg(m_lock); + if (m_stopped){ + return; + } + m_schedule.emplace(time, std::move(callback)); + m_cv.notify_all(); +} +void ScheduledTaskRunner::add_event(std::chrono::milliseconds time_from_now, std::function callback){ + std::lock_guard lg(m_lock); + if (m_stopped){ + return; + } + m_schedule.emplace(current_time() + time_from_now, std::move(callback)); + m_cv.notify_all(); +} +#if 0 +bool ScheduledTaskRunner::cancel(std::exception_ptr exception) noexcept{ + if (Cancellable::cancel(std::move(exception))){ + return true; + } + std::lock_guard lg(m_lock); + m_cv.notify_all(); + return false; +} +#endif +void ScheduledTaskRunner::thread_loop(){ + std::unique_lock lg(m_lock); +// cout << "ScheduledTaskRunner: (Starting thread loop): " << this << endl; +// WallClock last_check_timestamp = current_time(); + while (!m_stopped){ +#if 0 + if (cancelled()){ + return; + } +#endif + + if (m_schedule.empty()){ +// cout << "ScheduledTaskRunner: (Sleeping): " << this << endl; + m_cv.wait(lg); +// cout << "ScheduledTaskRunner: (Waking): " << this << endl; + continue; + } + + auto item = m_schedule.begin(); + WallClock now = current_time(); + if (item->first > now){ + m_cv.wait_until(lg, item->first); + continue; + } +// cout << "ScheduledTaskRunner: (task - start): " << this << endl; + lg.unlock(); + item->second(); + lg.lock(); +// cout << "ScheduledTaskRunner: (task - end): " << this << endl; + m_schedule.erase(item); + } +// cout << "ScheduledTaskRunner: (Clearing schedule): " << this << endl; + m_schedule.clear(); +} + + + + + +} diff --git a/Common/Cpp/Concurrency/ScheduledTaskRunner.h b/Common/Cpp/Concurrency/ScheduledTaskRunner.h index c2d504425c..0bb42c7df2 100644 --- a/Common/Cpp/Concurrency/ScheduledTaskRunner.h +++ b/Common/Cpp/Concurrency/ScheduledTaskRunner.h @@ -1,53 +1,53 @@ -/* Scheduled Task Runner - * - * From: https://github.com/PokemonAutomation/ - * - * Run tasks at their scheduled times. - * - */ - -#ifndef PokemonAutomation_ScheduledTaskRunner_H -#define PokemonAutomation_ScheduledTaskRunner_H - -#include -#include "Common/Cpp/Time.h" -//#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" - -namespace PokemonAutomation{ - - -class ScheduledTaskRunner{ -public: - ~ScheduledTaskRunner(); - ScheduledTaskRunner(AsyncDispatcher& dispatcher); - - // Returns the # of events in the schedule. - size_t size() const; - - // Returns the time of the next event. Returns WallClock::max() is no - // events are scheduled. - WallClock next_event() const; - - void add_event(WallClock time, std::function callback); - void add_event(std::chrono::milliseconds time_from_now, std::function callback); - -// virtual bool cancel(std::exception_ptr exception) noexcept override; - -private: - void thread_loop(); - -private: - mutable std::mutex m_lock; - std::condition_variable m_cv; - bool m_stopped; - - std::multimap> m_schedule; - - std::unique_ptr m_runner; -}; - - - -} -#endif +/* Scheduled Task Runner + * + * From: https://github.com/PokemonAutomation/ + * + * Run tasks at their scheduled times. + * + */ + +#ifndef PokemonAutomation_ScheduledTaskRunner_H +#define PokemonAutomation_ScheduledTaskRunner_H + +#include +#include "Common/Cpp/Time.h" +//#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" + +namespace PokemonAutomation{ + + +class ScheduledTaskRunner{ +public: + ~ScheduledTaskRunner(); + ScheduledTaskRunner(AsyncDispatcher& dispatcher); + + // Returns the # of events in the schedule. + size_t size() const; + + // Returns the time of the next event. Returns WallClock::max() is no + // events are scheduled. + WallClock next_event() const; + + void add_event(WallClock time, std::function callback); + void add_event(std::chrono::milliseconds time_from_now, std::function callback); + +// virtual bool cancel(std::exception_ptr exception) noexcept override; + +private: + void thread_loop(); + +private: + mutable std::mutex m_lock; + std::condition_variable m_cv; + bool m_stopped; + + std::multimap> m_schedule; + + std::unique_ptr m_runner; +}; + + + +} +#endif diff --git a/Common/Cpp/Concurrency/SpinLock.cpp b/Common/Cpp/Concurrency/SpinLock.cpp index a7f5d91a2a..e8a6c458b9 100644 --- a/Common/Cpp/Concurrency/SpinLock.cpp +++ b/Common/Cpp/Concurrency/SpinLock.cpp @@ -1,140 +1,140 @@ -/* Spin Lock - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" - - -#if 0 -#elif defined _WIN32 && defined PA_ARCH_x86 -#include -uint64_t x86_rdtsc(){ - return __rdtsc(); -} -#elif defined PA_ARCH_x86 -uint64_t x86_rdtsc(){ - unsigned int lo, hi; - __asm__ volatile ("rdtsc" : "=a" (lo), "=d" (hi)); - return ((uint64_t)hi << 32) | lo; -} -#else -#define PA_NO_RDTSC -#endif - - -#include "SpinPause.h" -#include "SpinLock.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - - -#if 0 -void SpinLock::spin_acquire(){ - bool state = false; - if (m_locked.compare_exchange_weak(state, true)){ - return; - } - do{ - pause(); - state = false; - }while (m_locked.load(std::memory_order_acquire) || !m_locked.compare_exchange_weak(state, true)); -} - -void SpinLock::spin_acquire(const char* label){ -#if _WIN32 && defined PA_ARCH_x86 - bool state = false; - if (m_locked.compare_exchange_weak(state, true)){ -// cout << "early" << endl; -// printf("early\n"); - return; - } - uint64_t start = __rdtsc(); - do{ -// cout << "late" << endl; -// printf("late\n"); - pause(); - if (__rdtsc() - start > 10000000000){ - cout << "Slow SpinLock: " << label << endl; - start = __rdtsc(); - } - state = false; - }while (m_locked.load(std::memory_order_acquire) || !m_locked.compare_exchange_weak(state, true)); -#else - spin_acquire(); -#endif -} -#endif - - - -void SpinLockMRSW::internal_acquire_read(){ -// cout << "SpinLockMRSW::internal_acquire_read()" << endl; - - while (true){ - size_t state = m_readers.load(std::memory_order_acquire); - if (state != (size_t)-1 && m_readers.compare_exchange_weak(state, state + 1)){ - return; - } - pause(); - } -} -void SpinLockMRSW::internal_acquire_write(){ -// cout << "SpinLockMRSW::internal_acquire_write()" << endl; - - size_t state; - do{ - pause(); - state = m_readers.load(std::memory_order_acquire); - }while (state != 0 || !m_readers.compare_exchange_weak(state, (size_t)-1)); -} -void SpinLockMRSW::internal_acquire_read(const char* label){ -// cout << "SpinLockMRSW::internal_acquire_read()" << endl; - -#ifdef PA_NO_RDTSC - internal_acquire_read(); -#else - uint64_t start = x86_rdtsc(); - while (true){ - size_t state = m_readers.load(std::memory_order_acquire); - if (state != (size_t)-1 && m_readers.compare_exchange_weak(state, state + 1)){ - return; - } - pause(); - if (x86_rdtsc() - start > 10000000000){ - cout << "Slow ReadSpinLock: " << label << endl; - start = x86_rdtsc(); - } - } -#endif -} -void SpinLockMRSW::internal_acquire_write(const char* label){ -// cout << "SpinLockMRSW::internal_acquire_write()" << endl; - -#ifdef PA_NO_RDTSC - internal_acquire_write(); -#else - uint64_t start = x86_rdtsc(); - size_t state; - do{ - pause(); - if (x86_rdtsc() - start > 10000000000){ - cout << "Slow WriteSpinLock: " << label << endl; - start = x86_rdtsc(); - } - state = m_readers.load(std::memory_order_acquire); - }while (state != 0 || !m_readers.compare_exchange_weak(state, (size_t)-1)); -#endif -} - - - - -} +/* Spin Lock + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" + + +#if 0 +#elif defined _WIN32 && defined PA_ARCH_x86 +#include +uint64_t x86_rdtsc(){ + return __rdtsc(); +} +#elif defined PA_ARCH_x86 +uint64_t x86_rdtsc(){ + unsigned int lo, hi; + __asm__ volatile ("rdtsc" : "=a" (lo), "=d" (hi)); + return ((uint64_t)hi << 32) | lo; +} +#else +#define PA_NO_RDTSC +#endif + + +#include "SpinPause.h" +#include "SpinLock.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + + +#if 0 +void SpinLock::spin_acquire(){ + bool state = false; + if (m_locked.compare_exchange_weak(state, true)){ + return; + } + do{ + pause(); + state = false; + }while (m_locked.load(std::memory_order_acquire) || !m_locked.compare_exchange_weak(state, true)); +} + +void SpinLock::spin_acquire(const char* label){ +#if _WIN32 && defined PA_ARCH_x86 + bool state = false; + if (m_locked.compare_exchange_weak(state, true)){ +// cout << "early" << endl; +// printf("early\n"); + return; + } + uint64_t start = __rdtsc(); + do{ +// cout << "late" << endl; +// printf("late\n"); + pause(); + if (__rdtsc() - start > 10000000000){ + cout << "Slow SpinLock: " << label << endl; + start = __rdtsc(); + } + state = false; + }while (m_locked.load(std::memory_order_acquire) || !m_locked.compare_exchange_weak(state, true)); +#else + spin_acquire(); +#endif +} +#endif + + + +void SpinLockMRSW::internal_acquire_read(){ +// cout << "SpinLockMRSW::internal_acquire_read()" << endl; + + while (true){ + size_t state = m_readers.load(std::memory_order_acquire); + if (state != (size_t)-1 && m_readers.compare_exchange_weak(state, state + 1)){ + return; + } + pause(); + } +} +void SpinLockMRSW::internal_acquire_write(){ +// cout << "SpinLockMRSW::internal_acquire_write()" << endl; + + size_t state; + do{ + pause(); + state = m_readers.load(std::memory_order_acquire); + }while (state != 0 || !m_readers.compare_exchange_weak(state, (size_t)-1)); +} +void SpinLockMRSW::internal_acquire_read(const char* label){ +// cout << "SpinLockMRSW::internal_acquire_read()" << endl; + +#ifdef PA_NO_RDTSC + internal_acquire_read(); +#else + uint64_t start = x86_rdtsc(); + while (true){ + size_t state = m_readers.load(std::memory_order_acquire); + if (state != (size_t)-1 && m_readers.compare_exchange_weak(state, state + 1)){ + return; + } + pause(); + if (x86_rdtsc() - start > 10000000000){ + cout << "Slow ReadSpinLock: " << label << endl; + start = x86_rdtsc(); + } + } +#endif +} +void SpinLockMRSW::internal_acquire_write(const char* label){ +// cout << "SpinLockMRSW::internal_acquire_write()" << endl; + +#ifdef PA_NO_RDTSC + internal_acquire_write(); +#else + uint64_t start = x86_rdtsc(); + size_t state; + do{ + pause(); + if (x86_rdtsc() - start > 10000000000){ + cout << "Slow WriteSpinLock: " << label << endl; + start = x86_rdtsc(); + } + state = m_readers.load(std::memory_order_acquire); + }while (state != 0 || !m_readers.compare_exchange_weak(state, (size_t)-1)); +#endif +} + + + + +} diff --git a/Common/Cpp/Concurrency/SpinLock.h b/Common/Cpp/Concurrency/SpinLock.h index bf79a3501d..63453b3f2b 100644 --- a/Common/Cpp/Concurrency/SpinLock.h +++ b/Common/Cpp/Concurrency/SpinLock.h @@ -1,158 +1,158 @@ -/* Spin Lock - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SpinLock_H -#define PokemonAutomation_SpinLock_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ - - -#if 0 -class SpinLock{ -public: - SpinLock() : m_locked(false) {} - - void spin_acquire(); - void spin_acquire(const char* label); - - void unlock(){ - m_locked.store(false, std::memory_order_release); - } - -private: - std::atomic m_locked; -}; -class SpinLockGuard{ -public: - SpinLockGuard(const SpinLockGuard&) = delete; - void operator=(const SpinLockGuard&) = delete; - - SpinLockGuard(SpinLock& lock, const char* label = "(unnamed lock)") - : m_lock(lock) - { - lock.spin_acquire(label); - } - ~SpinLockGuard(){ - m_lock.unlock(); - } - -private: - SpinLock& m_lock; -}; -#endif - - - -// -// This is a simple multi-reader/single-writer (MRSW) spin lock. -// Fairness is not guaranteed. Multiple readers can starve a writer indefinitely. -// -// As a spin lock, this is optimized for low contention. -// - -class SpinLockMRSW{ -public: - SpinLockMRSW() : m_readers(0) {} - - PA_FORCE_INLINE void acquire_read(const char* label = nullptr){ - // Optimization: Assume unlocked - size_t state = 0; - if (m_readers.compare_exchange_weak(state, 1)){ - return; - } - - // Only if we fail do we enter the (slow) retry logic. - if (label == nullptr){ - internal_acquire_read(); - }else{ - internal_acquire_read(label); - } - } - PA_FORCE_INLINE void acquire_write(const char* label = nullptr){ - // Optimization: Assume unlocked - size_t state = 0; - if (m_readers.compare_exchange_weak(state, (size_t)-1)){ - return; - } - - // Only if we fail do we enter the (slow) retry logic. - if (label == nullptr){ - internal_acquire_write(); - }else{ - internal_acquire_write(label); - } - } - - PA_FORCE_INLINE void unlock_read(){ - m_readers.fetch_sub(1); - } - PA_FORCE_INLINE void unlock_write(){ - m_readers.store(0, std::memory_order_release); - } - -private: - void internal_acquire_read(); - void internal_acquire_write(); - void internal_acquire_read(const char* label); - void internal_acquire_write(const char* label); - -private: - // 0 = unlocked - // positive = # of readers holding lock - // -1 = write locked - std::atomic m_readers; -}; - - -class ReadSpinLock{ -public: - ReadSpinLock(const ReadSpinLock&) = delete; - void operator=(const ReadSpinLock&) = delete; - - PA_FORCE_INLINE ReadSpinLock(SpinLockMRSW& lock, const char* label = "(unnamed lock)") - : m_lock(lock) - { - lock.acquire_read(label); - } - PA_FORCE_INLINE ~ReadSpinLock(){ - m_lock.unlock_read(); - } - -private: - SpinLockMRSW& m_lock; -}; - - -class WriteSpinLock{ -public: - WriteSpinLock(const WriteSpinLock&) = delete; - void operator=(const WriteSpinLock&) = delete; - - PA_FORCE_INLINE WriteSpinLock(SpinLockMRSW& lock, const char* label = "(unnamed lock)") - : m_lock(lock) - { - lock.acquire_write(label); - } - PA_FORCE_INLINE ~WriteSpinLock(){ - m_lock.unlock_write(); - } - -private: - SpinLockMRSW& m_lock; -}; - - -using SpinLock = SpinLockMRSW; -using SpinLockGuard = WriteSpinLock; - - - - -} -#endif +/* Spin Lock + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SpinLock_H +#define PokemonAutomation_SpinLock_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ + + +#if 0 +class SpinLock{ +public: + SpinLock() : m_locked(false) {} + + void spin_acquire(); + void spin_acquire(const char* label); + + void unlock(){ + m_locked.store(false, std::memory_order_release); + } + +private: + std::atomic m_locked; +}; +class SpinLockGuard{ +public: + SpinLockGuard(const SpinLockGuard&) = delete; + void operator=(const SpinLockGuard&) = delete; + + SpinLockGuard(SpinLock& lock, const char* label = "(unnamed lock)") + : m_lock(lock) + { + lock.spin_acquire(label); + } + ~SpinLockGuard(){ + m_lock.unlock(); + } + +private: + SpinLock& m_lock; +}; +#endif + + + +// +// This is a simple multi-reader/single-writer (MRSW) spin lock. +// Fairness is not guaranteed. Multiple readers can starve a writer indefinitely. +// +// As a spin lock, this is optimized for low contention. +// + +class SpinLockMRSW{ +public: + SpinLockMRSW() : m_readers(0) {} + + PA_FORCE_INLINE void acquire_read(const char* label = nullptr){ + // Optimization: Assume unlocked + size_t state = 0; + if (m_readers.compare_exchange_weak(state, 1)){ + return; + } + + // Only if we fail do we enter the (slow) retry logic. + if (label == nullptr){ + internal_acquire_read(); + }else{ + internal_acquire_read(label); + } + } + PA_FORCE_INLINE void acquire_write(const char* label = nullptr){ + // Optimization: Assume unlocked + size_t state = 0; + if (m_readers.compare_exchange_weak(state, (size_t)-1)){ + return; + } + + // Only if we fail do we enter the (slow) retry logic. + if (label == nullptr){ + internal_acquire_write(); + }else{ + internal_acquire_write(label); + } + } + + PA_FORCE_INLINE void unlock_read(){ + m_readers.fetch_sub(1); + } + PA_FORCE_INLINE void unlock_write(){ + m_readers.store(0, std::memory_order_release); + } + +private: + void internal_acquire_read(); + void internal_acquire_write(); + void internal_acquire_read(const char* label); + void internal_acquire_write(const char* label); + +private: + // 0 = unlocked + // positive = # of readers holding lock + // -1 = write locked + std::atomic m_readers; +}; + + +class ReadSpinLock{ +public: + ReadSpinLock(const ReadSpinLock&) = delete; + void operator=(const ReadSpinLock&) = delete; + + PA_FORCE_INLINE ReadSpinLock(SpinLockMRSW& lock, const char* label = "(unnamed lock)") + : m_lock(lock) + { + lock.acquire_read(label); + } + PA_FORCE_INLINE ~ReadSpinLock(){ + m_lock.unlock_read(); + } + +private: + SpinLockMRSW& m_lock; +}; + + +class WriteSpinLock{ +public: + WriteSpinLock(const WriteSpinLock&) = delete; + void operator=(const WriteSpinLock&) = delete; + + PA_FORCE_INLINE WriteSpinLock(SpinLockMRSW& lock, const char* label = "(unnamed lock)") + : m_lock(lock) + { + lock.acquire_write(label); + } + PA_FORCE_INLINE ~WriteSpinLock(){ + m_lock.unlock_write(); + } + +private: + SpinLockMRSW& m_lock; +}; + + +using SpinLock = SpinLockMRSW; +using SpinLockGuard = WriteSpinLock; + + + + +} +#endif diff --git a/Common/Cpp/Concurrency/SpinPause.h b/Common/Cpp/Concurrency/SpinPause.h index 59613eaa6e..a0f28d00e9 100644 --- a/Common/Cpp/Concurrency/SpinPause.h +++ b/Common/Cpp/Concurrency/SpinPause.h @@ -1,29 +1,29 @@ -/* Spin Pause - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SpinPause_H -#define PokemonAutomation_SpinPause_H - -#include "Common/Compiler.h" - - -#if 0 - -#elif _M_IX86 || _M_X64 || __i386__ || __x86_64__ -#include -namespace PokemonAutomation{ - PA_FORCE_INLINE void pause(){ - _mm_pause(); - } -} -#else -namespace PokemonAutomation{ - PA_FORCE_INLINE void pause(){} -} -#endif - - -#endif +/* Spin Pause + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SpinPause_H +#define PokemonAutomation_SpinPause_H + +#include "Common/Compiler.h" + + +#if 0 + +#elif _M_IX86 || _M_X64 || __i386__ || __x86_64__ +#include +namespace PokemonAutomation{ + PA_FORCE_INLINE void pause(){ + _mm_pause(); + } +} +#else +namespace PokemonAutomation{ + PA_FORCE_INLINE void pause(){} +} +#endif + + +#endif diff --git a/Common/Cpp/Concurrency/Watchdog.cpp b/Common/Cpp/Concurrency/Watchdog.cpp index b1f3edb381..68bed81d45 100644 --- a/Common/Cpp/Concurrency/Watchdog.cpp +++ b/Common/Cpp/Concurrency/Watchdog.cpp @@ -1,216 +1,216 @@ -/* Watchdog - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "Watchdog.h" - -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -Watchdog::~Watchdog(){ - { - std::lock_guard lg(m_sleep_lock); - m_stopped = true; - m_cv.notify_all(); - } - m_thread.join(); -} -Watchdog::Watchdog() - : m_thread(&Watchdog::thread_body, this) -{} - - -void Watchdog::add(WatchdogCallback& callback, std::chrono::milliseconds period){ - bool signal = true; - - WallClock now = current_time(); - { - WriteSpinLock slg(m_state_lock); - - auto iter = m_callbacks.find(&callback); - if (iter == m_callbacks.end()){ - // Callback doesn't exist. Add it. - auto iter1 = m_schedule.emplace(now + period, callback); - try{ - m_callbacks.emplace( - std::piecewise_construct, - std::forward_as_tuple(&callback), - std::forward_as_tuple(callback, period, iter1) - ); - }catch (...){ - m_schedule.erase(iter1); - throw; - } - }else{ - // Callback already exists. Update the period. - iter->second.period = period; - signal = update_unprotected(iter, now + period); - } - } - - if (signal){ - std::lock_guard wlg(m_sleep_lock); - m_cv.notify_all(); - } -} -void Watchdog::remove(WatchdogCallback& callback){ - while (true){ - { - WriteSpinLock slg(m_state_lock); - auto iter_c = m_callbacks.find(&callback); - if (iter_c == m_callbacks.end()){ - return; - } - - std::mutex& entry_lock = iter_c->second.lock; - if (entry_lock.try_lock()){ - // Remove from the schedule first. - auto iter_s = iter_c->second.iter; - m_schedule.erase(iter_s); - - // Unlock and remove from callback set. - entry_lock.unlock(); - m_callbacks.erase(iter_c); - return; - } - } - pause(); - } -} - - - -bool Watchdog::update_unprotected(CallbackMap::iterator iter, WallClock next_call){ - // Must be called under the "m_state_lock". - - if (next_call == iter->second.iter->first){ - // No change in time. - return false; - } - - WallClock current_wake_time = m_schedule.begin()->first; - - // Add the new time first. Then remove the old one. This ensures strong - // exception safety. - auto new_iter = m_schedule.emplace(next_call, *iter->first); - m_schedule.erase(iter->second.iter); - iter->second.iter = new_iter; - - WallClock new_wake_time = m_schedule.begin()->first; - return new_wake_time < current_wake_time; -} -void Watchdog::delay(WatchdogCallback& callback, WallClock next_call){ - bool signal = false; - - WallClock now = current_time(); - { - WriteSpinLock slg(m_state_lock); - auto iter = m_callbacks.find(&callback); - if (iter == m_callbacks.end()){ - return; - } - signal = update_unprotected( - iter, - next_call == WallClock::min() - ? now + iter->second.period - : next_call - ); - } - - if (signal){ - std::lock_guard wlg(m_sleep_lock); - m_cv.notify_all(); - } -} -void Watchdog::delay(WatchdogCallback& callback){ - this->delay(callback, WallClock::min()); -} -void Watchdog::delay(WatchdogCallback& callback, std::chrono::milliseconds delay){ - this->delay(callback, current_time() + delay); -} - - -void Watchdog::thread_body(){ - WallClock wake_time = WallClock::min(); - while (true){ - { - std::unique_lock wlg(m_sleep_lock); - if (m_stopped){ - break; - } - if (wake_time == WallClock::max()){ -// cout << "Sleeping indefinitely..." << endl; - m_cv.wait(wlg); -// cout << "Waking up..." << endl; - }else if (wake_time != WallClock::min()){ -// cout << "Sleeping until... " << std::chrono::duration_cast(wake_time - current_time()) << endl; - m_cv.wait_until(wlg, wake_time); -// cout << "Waking up..." << endl; - } - } -// cout << "Checking..." << endl; - - WallClock now = current_time(); - - std::unique_lock elg; - Entry* entry; - CallbackMap::iterator iter_c; - { - WriteSpinLock slg(m_state_lock); - - // Nothing scheduled. - if (m_schedule.empty()){ -// cout << "Nothing scheduled..." << endl; - wake_time = WallClock::max(); - continue; - } - - // Check if the next scheduled thing is ready to run. - - Schedule::iterator iter_s = m_schedule.begin(); - iter_c = m_callbacks.find(&iter_s->second); - if (now < iter_s->first){ - // Not ready to run yet. -// cout << "Not ready to run yet..." << endl; - wake_time = iter_s->first; - continue; - }else{ - // Ready to run. - entry = &iter_c->second; - elg = std::unique_lock(entry->lock); - } - } -// cout << "Running..." << endl; - - // Run the callback. - try{ - entry->callback.on_watchdog_timeout(); - }catch (Exception& e){ - std::cerr << "Watchdog callback threw an exception: " << e.to_str() << std::endl; - }catch (std::exception& e){ - std::cerr << "Watchdog callback threw an exception: " << e.what() << std::endl; - }catch (...){ - std::cerr << "Watchdog callback threw an exception." << std::endl; - } - - WriteSpinLock slg(m_state_lock); - update_unprotected(iter_c, current_time() + entry->period); -// entry->lock.unlock(); - - wake_time = WallClock::min(); - } -} - - - - -} +/* Watchdog + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "Watchdog.h" + +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +Watchdog::~Watchdog(){ + { + std::lock_guard lg(m_sleep_lock); + m_stopped = true; + m_cv.notify_all(); + } + m_thread.join(); +} +Watchdog::Watchdog() + : m_thread(&Watchdog::thread_body, this) +{} + + +void Watchdog::add(WatchdogCallback& callback, std::chrono::milliseconds period){ + bool signal = true; + + WallClock now = current_time(); + { + WriteSpinLock slg(m_state_lock); + + auto iter = m_callbacks.find(&callback); + if (iter == m_callbacks.end()){ + // Callback doesn't exist. Add it. + auto iter1 = m_schedule.emplace(now + period, callback); + try{ + m_callbacks.emplace( + std::piecewise_construct, + std::forward_as_tuple(&callback), + std::forward_as_tuple(callback, period, iter1) + ); + }catch (...){ + m_schedule.erase(iter1); + throw; + } + }else{ + // Callback already exists. Update the period. + iter->second.period = period; + signal = update_unprotected(iter, now + period); + } + } + + if (signal){ + std::lock_guard wlg(m_sleep_lock); + m_cv.notify_all(); + } +} +void Watchdog::remove(WatchdogCallback& callback){ + while (true){ + { + WriteSpinLock slg(m_state_lock); + auto iter_c = m_callbacks.find(&callback); + if (iter_c == m_callbacks.end()){ + return; + } + + std::mutex& entry_lock = iter_c->second.lock; + if (entry_lock.try_lock()){ + // Remove from the schedule first. + auto iter_s = iter_c->second.iter; + m_schedule.erase(iter_s); + + // Unlock and remove from callback set. + entry_lock.unlock(); + m_callbacks.erase(iter_c); + return; + } + } + pause(); + } +} + + + +bool Watchdog::update_unprotected(CallbackMap::iterator iter, WallClock next_call){ + // Must be called under the "m_state_lock". + + if (next_call == iter->second.iter->first){ + // No change in time. + return false; + } + + WallClock current_wake_time = m_schedule.begin()->first; + + // Add the new time first. Then remove the old one. This ensures strong + // exception safety. + auto new_iter = m_schedule.emplace(next_call, *iter->first); + m_schedule.erase(iter->second.iter); + iter->second.iter = new_iter; + + WallClock new_wake_time = m_schedule.begin()->first; + return new_wake_time < current_wake_time; +} +void Watchdog::delay(WatchdogCallback& callback, WallClock next_call){ + bool signal = false; + + WallClock now = current_time(); + { + WriteSpinLock slg(m_state_lock); + auto iter = m_callbacks.find(&callback); + if (iter == m_callbacks.end()){ + return; + } + signal = update_unprotected( + iter, + next_call == WallClock::min() + ? now + iter->second.period + : next_call + ); + } + + if (signal){ + std::lock_guard wlg(m_sleep_lock); + m_cv.notify_all(); + } +} +void Watchdog::delay(WatchdogCallback& callback){ + this->delay(callback, WallClock::min()); +} +void Watchdog::delay(WatchdogCallback& callback, std::chrono::milliseconds delay){ + this->delay(callback, current_time() + delay); +} + + +void Watchdog::thread_body(){ + WallClock wake_time = WallClock::min(); + while (true){ + { + std::unique_lock wlg(m_sleep_lock); + if (m_stopped){ + break; + } + if (wake_time == WallClock::max()){ +// cout << "Sleeping indefinitely..." << endl; + m_cv.wait(wlg); +// cout << "Waking up..." << endl; + }else if (wake_time != WallClock::min()){ +// cout << "Sleeping until... " << std::chrono::duration_cast(wake_time - current_time()) << endl; + m_cv.wait_until(wlg, wake_time); +// cout << "Waking up..." << endl; + } + } +// cout << "Checking..." << endl; + + WallClock now = current_time(); + + std::unique_lock elg; + Entry* entry; + CallbackMap::iterator iter_c; + { + WriteSpinLock slg(m_state_lock); + + // Nothing scheduled. + if (m_schedule.empty()){ +// cout << "Nothing scheduled..." << endl; + wake_time = WallClock::max(); + continue; + } + + // Check if the next scheduled thing is ready to run. + + Schedule::iterator iter_s = m_schedule.begin(); + iter_c = m_callbacks.find(&iter_s->second); + if (now < iter_s->first){ + // Not ready to run yet. +// cout << "Not ready to run yet..." << endl; + wake_time = iter_s->first; + continue; + }else{ + // Ready to run. + entry = &iter_c->second; + elg = std::unique_lock(entry->lock); + } + } +// cout << "Running..." << endl; + + // Run the callback. + try{ + entry->callback.on_watchdog_timeout(); + }catch (Exception& e){ + std::cerr << "Watchdog callback threw an exception: " << e.to_str() << std::endl; + }catch (std::exception& e){ + std::cerr << "Watchdog callback threw an exception: " << e.what() << std::endl; + }catch (...){ + std::cerr << "Watchdog callback threw an exception." << std::endl; + } + + WriteSpinLock slg(m_state_lock); + update_unprotected(iter_c, current_time() + entry->period); +// entry->lock.unlock(); + + wake_time = WallClock::min(); + } +} + + + + +} diff --git a/Common/Cpp/Concurrency/Watchdog.h b/Common/Cpp/Concurrency/Watchdog.h index 293b5fd666..510b3865d0 100644 --- a/Common/Cpp/Concurrency/Watchdog.h +++ b/Common/Cpp/Concurrency/Watchdog.h @@ -1,103 +1,103 @@ -/* Watchdog - * - * From: https://github.com/PokemonAutomation/ - * - * This class runs callbacks at specified intervals. The user can also - * delay the next call. - * - * The primary use case here is watchdog timers. If nothing happens within a - * time window, fire a callback to sound an alarm. But if something does - * happen, delay it since there's nothing wrong. - * - */ - -#ifndef PokemonAutomation_Watchdog_H -#define PokemonAutomation_Watchdog_H - -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - - - -struct WatchdogCallback{ - virtual void on_watchdog_timeout() = 0; -}; - - -class Watchdog{ -public: - ~Watchdog(); - Watchdog(); - - // Add a callback which will be called at the specified period. - // If callback already exists, the period will be overwritten and the next - // call will be set to (now + period). - void add(WatchdogCallback& callback, std::chrono::milliseconds period); - void remove(WatchdogCallback& callback); - - // Delay the specified callback. If the callback is current running, this - // function does nothing. - void delay(WatchdogCallback& callback); // Delay by the set period. - void delay(WatchdogCallback& callback, WallClock next_call); // Delay to timestamp. - void delay(WatchdogCallback& callback, std::chrono::milliseconds delay); // Delay by specific duration. - - // - // All public methods are fully thread-safe with each other. (except the destructor) - // - // The above methods add() and delay(), are fast and will return quickly. - // So it is safe to call them in semi-performance critical places. - // (The critical section involves one spin-lock acquisition and 3 map lookups.) - // - // remove() will also return quickly unless the callback being removed - // is currently running. In that case, it will block until it is done - // running. - // - -private: - using Schedule = std::multimap; - - struct Entry{ - WatchdogCallback& callback; - std::chrono::milliseconds period; - Schedule::iterator iter; - std::mutex lock; - - Entry( - WatchdogCallback& p_callback, - std::chrono::milliseconds p_period, - Schedule::iterator p_iter - ) - : callback(p_callback), period(p_period), iter(p_iter) - {} - }; - using CallbackMap = std::map; - - // Return true if the next call has moved up and we should signal. - bool update_unprotected(CallbackMap::iterator iter, WallClock next_call); - void thread_body(); - -private: - bool m_stopped = false; - CallbackMap m_callbacks; - Schedule m_schedule; - - // Nothing should ever acquire both locks at once. - SpinLock m_state_lock; - std::mutex m_sleep_lock; - - std::condition_variable m_cv; - std::thread m_thread; -}; - - - - - -} -#endif +/* Watchdog + * + * From: https://github.com/PokemonAutomation/ + * + * This class runs callbacks at specified intervals. The user can also + * delay the next call. + * + * The primary use case here is watchdog timers. If nothing happens within a + * time window, fire a callback to sound an alarm. But if something does + * happen, delay it since there's nothing wrong. + * + */ + +#ifndef PokemonAutomation_Watchdog_H +#define PokemonAutomation_Watchdog_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + + + +struct WatchdogCallback{ + virtual void on_watchdog_timeout() = 0; +}; + + +class Watchdog{ +public: + ~Watchdog(); + Watchdog(); + + // Add a callback which will be called at the specified period. + // If callback already exists, the period will be overwritten and the next + // call will be set to (now + period). + void add(WatchdogCallback& callback, std::chrono::milliseconds period); + void remove(WatchdogCallback& callback); + + // Delay the specified callback. If the callback is current running, this + // function does nothing. + void delay(WatchdogCallback& callback); // Delay by the set period. + void delay(WatchdogCallback& callback, WallClock next_call); // Delay to timestamp. + void delay(WatchdogCallback& callback, std::chrono::milliseconds delay); // Delay by specific duration. + + // + // All public methods are fully thread-safe with each other. (except the destructor) + // + // The above methods add() and delay(), are fast and will return quickly. + // So it is safe to call them in semi-performance critical places. + // (The critical section involves one spin-lock acquisition and 3 map lookups.) + // + // remove() will also return quickly unless the callback being removed + // is currently running. In that case, it will block until it is done + // running. + // + +private: + using Schedule = std::multimap; + + struct Entry{ + WatchdogCallback& callback; + std::chrono::milliseconds period; + Schedule::iterator iter; + std::mutex lock; + + Entry( + WatchdogCallback& p_callback, + std::chrono::milliseconds p_period, + Schedule::iterator p_iter + ) + : callback(p_callback), period(p_period), iter(p_iter) + {} + }; + using CallbackMap = std::map; + + // Return true if the next call has moved up and we should signal. + bool update_unprotected(CallbackMap::iterator iter, WallClock next_call); + void thread_body(); + +private: + bool m_stopped = false; + CallbackMap m_callbacks; + Schedule m_schedule; + + // Nothing should ever acquire both locks at once. + SpinLock m_state_lock; + std::mutex m_sleep_lock; + + std::condition_variable m_cv; + std::thread m_thread; +}; + + + + + +} +#endif diff --git a/Common/Cpp/Containers/AlignedMalloc.cpp b/Common/Cpp/Containers/AlignedMalloc.cpp index c97cda272c..f44b15dcf9 100644 --- a/Common/Cpp/Containers/AlignedMalloc.cpp +++ b/Common/Cpp/Containers/AlignedMalloc.cpp @@ -1,100 +1,100 @@ -/* Aligned Malloc - * - * From: https://github.com/PokemonAutomation/ - * - * Copy-edited from: - * https://github.com/Mysticial/y-cruncher/blob/master/trunk/Source/PublicLibs/BasicLibs/Memory/AlignedMalloc.cpp - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "AlignedMalloc.h" - -#define PA_ENABLE_MALLOC_CHECKING -//#define PA_ZERO_INITIALIZE - -const size_t BUFFER_CHECK_BOT = (size_t)0xea097be64bd0187d; -const size_t BUFFER_CHECK_TOP = (size_t)0xc72bf73f0559cfe4; - -namespace PokemonAutomation{ - - -void* aligned_malloc(size_t bytes, size_t alignment){ - if (alignment < sizeof(size_t)){ - alignment = sizeof(size_t); - } -#ifdef PA_ENABLE_MALLOC_CHECKING - if ((alignment & (alignment - 1)) != 0){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Alignment must be a power of two."); - } -#endif - - size_t actual_bytes = bytes + alignment + sizeof(size_t)*4; - void* free_ptr = malloc(actual_bytes); - if (free_ptr == nullptr){ - throw std::bad_alloc(); -// return nullptr; - } -#ifdef PA_ZERO_INITIALIZE - memset(free_ptr, 0, actual_bytes); -#endif - size_t free_address = (size_t)free_ptr; - size_t min_ret_address = free_address + sizeof(size_t)*3; - - // Align - size_t ret_address = min_ret_address; - ret_address &= ~(size_t)(alignment - 1); - ret_address += alignment; - - size_t* ret = (size_t*)ret_address; - ret[-3] = free_address; - -#ifdef PA_ENABLE_MALLOC_CHECKING - ret[-2] = bytes; - ret[-1] = BUFFER_CHECK_BOT; - memcpy((char*)ret + bytes, &BUFFER_CHECK_TOP, sizeof(size_t)); -#endif - - return ret; -} -void aligned_free(void* ptr){ - if (ptr == nullptr){ - return; - } - - check_aligned_ptr(ptr); - - size_t* ret = (size_t*)ptr; - size_t free_int = ret[-3]; - - ptr = (void*)free_int; - free(ptr); -} -void check_aligned_ptr(const void* ptr){ -#ifdef PA_ENABLE_MALLOC_CHECKING - if (ptr == nullptr){ - return; - } - - const size_t* ret = (const size_t*)ptr; -// size_t free_int = ret[-3]; - - size_t bytes = ret[-2]; - size_t check = ret[-1]; - if (check != BUFFER_CHECK_BOT){ -// std::terminate(); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Memory buffer has been underrun."); - } - memcpy(&check, (const char*)ptr + bytes, sizeof(size_t)); - if (check != BUFFER_CHECK_TOP){ -// std::terminate(); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Memory buffer has been overrun."); - } -#endif -} - - -} +/* Aligned Malloc + * + * From: https://github.com/PokemonAutomation/ + * + * Copy-edited from: + * https://github.com/Mysticial/y-cruncher/blob/master/trunk/Source/PublicLibs/BasicLibs/Memory/AlignedMalloc.cpp + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "AlignedMalloc.h" + +#define PA_ENABLE_MALLOC_CHECKING +//#define PA_ZERO_INITIALIZE + +const size_t BUFFER_CHECK_BOT = (size_t)0xea097be64bd0187d; +const size_t BUFFER_CHECK_TOP = (size_t)0xc72bf73f0559cfe4; + +namespace PokemonAutomation{ + + +void* aligned_malloc(size_t bytes, size_t alignment){ + if (alignment < sizeof(size_t)){ + alignment = sizeof(size_t); + } +#ifdef PA_ENABLE_MALLOC_CHECKING + if ((alignment & (alignment - 1)) != 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Alignment must be a power of two."); + } +#endif + + size_t actual_bytes = bytes + alignment + sizeof(size_t)*4; + void* free_ptr = malloc(actual_bytes); + if (free_ptr == nullptr){ + throw std::bad_alloc(); +// return nullptr; + } +#ifdef PA_ZERO_INITIALIZE + memset(free_ptr, 0, actual_bytes); +#endif + size_t free_address = (size_t)free_ptr; + size_t min_ret_address = free_address + sizeof(size_t)*3; + + // Align + size_t ret_address = min_ret_address; + ret_address &= ~(size_t)(alignment - 1); + ret_address += alignment; + + size_t* ret = (size_t*)ret_address; + ret[-3] = free_address; + +#ifdef PA_ENABLE_MALLOC_CHECKING + ret[-2] = bytes; + ret[-1] = BUFFER_CHECK_BOT; + memcpy((char*)ret + bytes, &BUFFER_CHECK_TOP, sizeof(size_t)); +#endif + + return ret; +} +void aligned_free(void* ptr){ + if (ptr == nullptr){ + return; + } + + check_aligned_ptr(ptr); + + size_t* ret = (size_t*)ptr; + size_t free_int = ret[-3]; + + ptr = (void*)free_int; + free(ptr); +} +void check_aligned_ptr(const void* ptr){ +#ifdef PA_ENABLE_MALLOC_CHECKING + if (ptr == nullptr){ + return; + } + + const size_t* ret = (const size_t*)ptr; +// size_t free_int = ret[-3]; + + size_t bytes = ret[-2]; + size_t check = ret[-1]; + if (check != BUFFER_CHECK_BOT){ +// std::terminate(); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Memory buffer has been underrun."); + } + memcpy(&check, (const char*)ptr + bytes, sizeof(size_t)); + if (check != BUFFER_CHECK_TOP){ +// std::terminate(); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Memory buffer has been overrun."); + } +#endif +} + + +} diff --git a/Common/Cpp/Containers/AlignedMalloc.h b/Common/Cpp/Containers/AlignedMalloc.h index 3cf9487373..3587adfdab 100644 --- a/Common/Cpp/Containers/AlignedMalloc.h +++ b/Common/Cpp/Containers/AlignedMalloc.h @@ -1,21 +1,21 @@ -/* Aligned Malloc - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AlignedMalloc_H -#define PokemonAutomation_AlignedMalloc_H - -#include - -namespace PokemonAutomation{ - - -void* aligned_malloc(size_t bytes, size_t alignment); -void aligned_free(void* ptr); -void check_aligned_ptr(const void *ptr); - - -} -#endif +/* Aligned Malloc + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AlignedMalloc_H +#define PokemonAutomation_AlignedMalloc_H + +#include + +namespace PokemonAutomation{ + + +void* aligned_malloc(size_t bytes, size_t alignment); +void aligned_free(void* ptr); +void check_aligned_ptr(const void *ptr); + + +} +#endif diff --git a/Common/Cpp/Containers/AlignedVector.h b/Common/Cpp/Containers/AlignedVector.h index 23eae89a4a..736672e343 100644 --- a/Common/Cpp/Containers/AlignedVector.h +++ b/Common/Cpp/Containers/AlignedVector.h @@ -1,94 +1,94 @@ -/* Aligned Vector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AlignedVector_H -#define PokemonAutomation_AlignedVector_H - -#include - -namespace PokemonAutomation{ - - -template -class AlignedVector{ -public: - ~AlignedVector(); - AlignedVector(AlignedVector&& x) noexcept; - void operator=(AlignedVector&& x) noexcept; - AlignedVector(const AlignedVector& x); - void operator=(const AlignedVector& x); - -public: - AlignedVector(); - AlignedVector(size_t items); - - void clear() noexcept; - -public: - size_t empty() const{ return m_size == 0; } - size_t size() const{ return m_size; } - size_t capacity() const{ return m_capacity; } - - const Object& operator[](size_t index) const{ return m_ptr[index]; } - Object& operator[](size_t index) { return m_ptr[index]; } - const Object& back() const{ return m_ptr[m_size - 1]; } - Object& back() { return m_ptr[m_size - 1]; } - - const Object* data() const{ return m_ptr; } - Object* data() { return m_ptr; } - - template - void emplace_back(Args&&... args); - void pop_back(); - - const Object* begin() const; - Object* begin(); - const Object* end() const; - Object* end(); - -private: - void expand(); - - -private: - Object* m_ptr; - size_t m_size; - size_t m_capacity; -}; - - - - - -template -AlignedVector::AlignedVector() - : m_ptr(nullptr) - , m_size(0) - , m_capacity(0) -{} - -template -const Object* AlignedVector::begin() const{ - return m_ptr; -} -template -Object* AlignedVector::begin(){ - return m_ptr; -} -template -const Object* AlignedVector::end() const{ - return m_ptr + m_size; -} -template -Object* AlignedVector::end(){ - return m_ptr + m_size; -} - - - - -} -#endif +/* Aligned Vector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AlignedVector_H +#define PokemonAutomation_AlignedVector_H + +#include + +namespace PokemonAutomation{ + + +template +class AlignedVector{ +public: + ~AlignedVector(); + AlignedVector(AlignedVector&& x) noexcept; + void operator=(AlignedVector&& x) noexcept; + AlignedVector(const AlignedVector& x); + void operator=(const AlignedVector& x); + +public: + AlignedVector(); + AlignedVector(size_t items); + + void clear() noexcept; + +public: + size_t empty() const{ return m_size == 0; } + size_t size() const{ return m_size; } + size_t capacity() const{ return m_capacity; } + + const Object& operator[](size_t index) const{ return m_ptr[index]; } + Object& operator[](size_t index) { return m_ptr[index]; } + const Object& back() const{ return m_ptr[m_size - 1]; } + Object& back() { return m_ptr[m_size - 1]; } + + const Object* data() const{ return m_ptr; } + Object* data() { return m_ptr; } + + template + void emplace_back(Args&&... args); + void pop_back(); + + const Object* begin() const; + Object* begin(); + const Object* end() const; + Object* end(); + +private: + void expand(); + + +private: + Object* m_ptr; + size_t m_size; + size_t m_capacity; +}; + + + + + +template +AlignedVector::AlignedVector() + : m_ptr(nullptr) + , m_size(0) + , m_capacity(0) +{} + +template +const Object* AlignedVector::begin() const{ + return m_ptr; +} +template +Object* AlignedVector::begin(){ + return m_ptr; +} +template +const Object* AlignedVector::end() const{ + return m_ptr + m_size; +} +template +Object* AlignedVector::end(){ + return m_ptr + m_size; +} + + + + +} +#endif diff --git a/Common/Cpp/Containers/AlignedVector.tpp b/Common/Cpp/Containers/AlignedVector.tpp index c8d7f0a643..ac08869102 100644 --- a/Common/Cpp/Containers/AlignedVector.tpp +++ b/Common/Cpp/Containers/AlignedVector.tpp @@ -1,178 +1,178 @@ -/* Aligned Vector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_AlignedVector_TPP -#define PokemonAutomation_AlignedVector_TPP - -#include -#include -#include -#include -#include -#include "Common/Compiler.h" -#include "AlignedMalloc.h" -#include "AlignedVector.h" - -namespace PokemonAutomation{ - - - -template -AlignedVector::~AlignedVector(){ - clear(); - aligned_free(m_ptr); - m_capacity = 0; -} -template -AlignedVector::AlignedVector(AlignedVector&& x) noexcept - : m_ptr(x.m_ptr) - , m_size(x.m_size) - , m_capacity(x.m_capacity) -{ - x.m_ptr = nullptr; - x.m_size = 0; - x.m_capacity = 0; -} -template -void AlignedVector::operator=(AlignedVector&& x) noexcept{ - clear(); - aligned_free(m_ptr); - m_ptr = x.m_ptr; - m_size = x.m_size; - m_capacity = x.m_capacity; - x.m_ptr = nullptr; - x.m_size = 0; - x.m_capacity = 0; -} -template -AlignedVector::AlignedVector(const AlignedVector& x) - : m_capacity(x.m_capacity) -{ - // Shrink to fit. - while (m_capacity > 0){ - size_t half = m_capacity / 2; - if (half >= x.m_size){ - m_capacity = half; - } else{ - break; - } - } - m_ptr = (Object*)aligned_malloc( - m_capacity * sizeof(Object), - std::max(alignof(Object), 64) - ); - if (m_ptr == nullptr){ - throw std::bad_alloc(); - } - - if constexpr (std::is_trivially_copyable::value){ - memcpy(m_ptr, x.m_ptr, x.m_size * sizeof(Object)); - m_size = x.m_size; - return; - } - - m_size = 0; - try{ - for (size_t c = 0; c < x.m_size; c++){ - new (m_ptr + m_size) Object(x[c]); - m_size++; - } - }catch (...){ - clear(); - aligned_free(m_ptr); - throw; - } -} -template -void AlignedVector::operator=(const AlignedVector& x){ - if (this == &x){ - return; - } - AlignedVector tmp(x); - *this = std::move(tmp); -} - - - -template -AlignedVector::AlignedVector(size_t items){ - m_ptr = (Object*)aligned_malloc(items * sizeof(Object), PA_ALIGNMENT); - if (m_ptr == nullptr){ - throw std::bad_alloc(); - } - m_capacity = items; - - if constexpr (std::is_trivially_constructible::value){ - m_size = items; - return; - } - - m_size = 0; - try{ - for (size_t c = 0; c < items; c++){ - new (m_ptr + m_size) Object; - m_size++; - } - }catch (...){ - clear(); - aligned_free(m_ptr); - throw; - } -} - -template -void AlignedVector::clear() noexcept{ - if constexpr (std::is_trivially_constructible::value){ - m_size = 0; - }else{ - while (m_size > 0){ - pop_back(); - } - } -} - -template -template -void AlignedVector::emplace_back(Args&&... args){ - if (m_size >= m_capacity){ - expand(); - } - new (m_ptr + m_size) Object(std::forward(args)...); - m_size++; -} -template -void AlignedVector::pop_back(){ - m_ptr[--m_size].~Object(); -} - -template -PA_NO_INLINE void AlignedVector::expand(){ - size_t size = m_capacity == 0 ? 1 : m_capacity * 2; - Object* ptr = (Object*)aligned_malloc(size * sizeof(Object), PA_ALIGNMENT); - if (ptr == nullptr){ - throw std::bad_alloc(); - } - if constexpr (std::is_trivially_copyable::value){ - memcpy(ptr, m_ptr, m_size * sizeof(Object)); - }else{ - for (size_t c = 0; c < m_size; c++){ - new (ptr + c) Object(std::move(m_ptr[c])); - m_ptr[c].~Object(); - } - } - aligned_free(m_ptr); - m_ptr = ptr; - m_capacity = size; -} - - - - - - - -} -#endif +/* Aligned Vector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_AlignedVector_TPP +#define PokemonAutomation_AlignedVector_TPP + +#include +#include +#include +#include +#include +#include "Common/Compiler.h" +#include "AlignedMalloc.h" +#include "AlignedVector.h" + +namespace PokemonAutomation{ + + + +template +AlignedVector::~AlignedVector(){ + clear(); + aligned_free(m_ptr); + m_capacity = 0; +} +template +AlignedVector::AlignedVector(AlignedVector&& x) noexcept + : m_ptr(x.m_ptr) + , m_size(x.m_size) + , m_capacity(x.m_capacity) +{ + x.m_ptr = nullptr; + x.m_size = 0; + x.m_capacity = 0; +} +template +void AlignedVector::operator=(AlignedVector&& x) noexcept{ + clear(); + aligned_free(m_ptr); + m_ptr = x.m_ptr; + m_size = x.m_size; + m_capacity = x.m_capacity; + x.m_ptr = nullptr; + x.m_size = 0; + x.m_capacity = 0; +} +template +AlignedVector::AlignedVector(const AlignedVector& x) + : m_capacity(x.m_capacity) +{ + // Shrink to fit. + while (m_capacity > 0){ + size_t half = m_capacity / 2; + if (half >= x.m_size){ + m_capacity = half; + } else{ + break; + } + } + m_ptr = (Object*)aligned_malloc( + m_capacity * sizeof(Object), + std::max(alignof(Object), 64) + ); + if (m_ptr == nullptr){ + throw std::bad_alloc(); + } + + if constexpr (std::is_trivially_copyable::value){ + memcpy(m_ptr, x.m_ptr, x.m_size * sizeof(Object)); + m_size = x.m_size; + return; + } + + m_size = 0; + try{ + for (size_t c = 0; c < x.m_size; c++){ + new (m_ptr + m_size) Object(x[c]); + m_size++; + } + }catch (...){ + clear(); + aligned_free(m_ptr); + throw; + } +} +template +void AlignedVector::operator=(const AlignedVector& x){ + if (this == &x){ + return; + } + AlignedVector tmp(x); + *this = std::move(tmp); +} + + + +template +AlignedVector::AlignedVector(size_t items){ + m_ptr = (Object*)aligned_malloc(items * sizeof(Object), PA_ALIGNMENT); + if (m_ptr == nullptr){ + throw std::bad_alloc(); + } + m_capacity = items; + + if constexpr (std::is_trivially_constructible::value){ + m_size = items; + return; + } + + m_size = 0; + try{ + for (size_t c = 0; c < items; c++){ + new (m_ptr + m_size) Object; + m_size++; + } + }catch (...){ + clear(); + aligned_free(m_ptr); + throw; + } +} + +template +void AlignedVector::clear() noexcept{ + if constexpr (std::is_trivially_constructible::value){ + m_size = 0; + }else{ + while (m_size > 0){ + pop_back(); + } + } +} + +template +template +void AlignedVector::emplace_back(Args&&... args){ + if (m_size >= m_capacity){ + expand(); + } + new (m_ptr + m_size) Object(std::forward(args)...); + m_size++; +} +template +void AlignedVector::pop_back(){ + m_ptr[--m_size].~Object(); +} + +template +PA_NO_INLINE void AlignedVector::expand(){ + size_t size = m_capacity == 0 ? 1 : m_capacity * 2; + Object* ptr = (Object*)aligned_malloc(size * sizeof(Object), PA_ALIGNMENT); + if (ptr == nullptr){ + throw std::bad_alloc(); + } + if constexpr (std::is_trivially_copyable::value){ + memcpy(ptr, m_ptr, m_size * sizeof(Object)); + }else{ + for (size_t c = 0; c < m_size; c++){ + new (ptr + c) Object(std::move(m_ptr[c])); + m_ptr[c].~Object(); + } + } + aligned_free(m_ptr); + m_ptr = ptr; + m_capacity = size; +} + + + + + + + +} +#endif diff --git a/Common/Cpp/Containers/BoxSet.h b/Common/Cpp/Containers/BoxSet.h index 2956c90b51..1ba8ac8691 100644 --- a/Common/Cpp/Containers/BoxSet.h +++ b/Common/Cpp/Containers/BoxSet.h @@ -1,355 +1,355 @@ -/* Box Set - * - * From: https://github.com/PokemonAutomation/ - * - * This class is experimental. It currently doesn't actually accomplish - * what it was intended for. - * - */ - -#ifndef PokemonAutomation_BoxSet_H -#define PokemonAutomation_BoxSet_H - -#include -#include -#include "Common/Cpp/Rectangle.h" -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - - -// -// An unordered container holding a set of boxes. -// -// Iterating this container normally will iterate all the boxes in a fixed, but -// undefined order. -// -// This class provides "axis iterators" that allow you to iterate the elements -// in order of each of the axis points on the box. This lets you efficiently -// iterate boxes that overlap with a point or another box. -// -template -class BoxSet{ -public: - size_t size() const{ return m_boxes.size(); } - std::string dump() const; - -public: - class Entry; - - // Normal iterators. These iterate all the elements in a fixed, but - // undefined order. - class iterator; - class const_iterator; - - const_iterator cbegin() const; - const_iterator begin () const; - iterator begin (); - - const_iterator cend() const; - const_iterator end () const; - iterator end (); - -public: - // Axis iterator. These iterate the elements in increasing order either on - // the X or Y axis. - - using axis_iterator = typename std::multimap::const_iterator; - - axis_iterator end_min_x() const{ return m_min_x.end(); } - axis_iterator end_max_x() const{ return m_max_x.end(); } - axis_iterator end_min_y() const{ return m_min_y.end(); } - axis_iterator end_max_y() const{ return m_max_y.end(); } - - axis_iterator lower_bound_min_x(Type x) const{ return m_min_x.lower_bound(x); } - axis_iterator upper_bound_min_x(Type x) const{ return m_min_x.upper_bound(x); } - axis_iterator lower_bound_max_x(Type x) const{ return m_max_x.lower_bound(x); } - axis_iterator upper_bound_max_x(Type x) const{ return m_max_x.upper_bound(x); } - axis_iterator lower_bound_min_y(Type y) const{ return m_min_y.lower_bound(y); } - axis_iterator upper_bound_min_y(Type y) const{ return m_min_y.upper_bound(y); } - axis_iterator lower_bound_max_y(Type y) const{ return m_max_y.lower_bound(y); } - axis_iterator upper_bound_max_y(Type y) const{ return m_max_y.upper_bound(y); } - -public: - // Insert box into set and return a normal iterator to it. - iterator insert(const Rectangle& box); - - // Erase an iterator and return the next iterator. This will invalidate - // all other iterators pointing to the same element. - iterator erase(iterator item); - axis_iterator erase(axis_iterator item); - -public: - // Advanced Functions - - // Iterate on all boxes which either contain this point or on its border. - template - void iterate_in_or_on(Type x, Type y, Func&& lambda); - - -private: - static size_t get_key(const Rectangle& box); - -private: - std::multimap m_boxes; - std::multimap m_min_x; - std::multimap m_max_x; - std::multimap m_min_y; - std::multimap m_max_y; -}; - - - -template -class BoxSet::Entry{ -public: - Entry(const Rectangle& box) - : m_box(box) - {} - - operator const Rectangle&() const{ return m_box; } - const Rectangle* operator->() const{ return &m_box; } - const Rectangle& box() const{ return m_box; } - -private: - friend class BoxSet; - Rectangle m_box; - typename std::multimap::iterator m_min_x; - typename std::multimap::iterator m_max_x; - typename std::multimap::iterator m_min_y; - typename std::multimap::iterator m_max_y; -}; - - -template -class BoxSet::iterator{ -public: - bool operator==(const iterator& iter) const{ return m_iter == iter.m_iter; } - - iterator operator++(){ - ++m_iter; - return *this; - } - auto operator*() const{ return *m_iter; } - auto operator*(){ return *m_iter; } - auto operator->() const{ return m_iter.operator->(); } - auto operator->(){ return m_iter.operator->(); } - - axis_iterator iterator_min_x() const{ - return m_iter->second.m_min_x; - } - axis_iterator iterator_max_x() const{ - return m_iter->second.m_max_x; - } - axis_iterator iterator_min_y() const{ - return m_iter->second.m_min_y; - } - axis_iterator iterator_max_y() const{ - return m_iter->second.m_max_y; - } - -private: - friend class BoxSet; - friend class const_iterator; - - typename std::multimap::iterator m_iter; - - iterator(typename std::multimap::iterator iter) - : m_iter(iter) - {} -}; - - -template -class BoxSet::const_iterator{ -public: - bool operator==(const iterator& iter) const{ return m_iter == iter.m_iter; } - - const_iterator(iterator iter) - : m_iter(iter.m_iter) - {} - const_iterator operator++(){ - ++m_iter; - return *this; - } - auto operator*() const{ return *m_iter; } - auto operator*(){ return *m_iter; } - auto operator->() const{ return m_iter.operator->(); } - auto operator->(){ return m_iter.operator->(); } - - axis_iterator iterator_min_x() const{ - return m_iter->second.m_min_x; - } - axis_iterator iterator_max_x() const{ - return m_iter->second.m_max_x; - } - axis_iterator iterator_min_y() const{ - return m_iter->second.m_min_y; - } - axis_iterator iterator_max_y() const{ - return m_iter->second.m_max_y; - } - -private: - friend class BoxSet; - - typename std::multimap::iterator m_iter; - - const_iterator(typename std::multimap::iterator iter) - : m_iter(iter) - {} -}; - - - - - -// -// Implementations -// - - - -template -inline typename BoxSet::const_iterator BoxSet::cbegin() const{ - return m_boxes.cbegin(); -} -template -inline typename BoxSet::const_iterator BoxSet::begin () const{ - return m_boxes.begin(); -} -template -inline typename BoxSet::iterator BoxSet::begin(){ - return m_boxes.begin(); -} - -template -inline typename BoxSet::const_iterator BoxSet::cend() const{ - return m_boxes.cend(); -} -template -inline typename BoxSet::const_iterator BoxSet::end() const{ - return m_boxes.end(); -} -template -inline typename BoxSet::iterator BoxSet::end(){ - return m_boxes.end(); -} - - - -template -size_t BoxSet::get_key(const Rectangle& box){ - // Basically a simple hash function that preserves some sort of visual - // order if everything is small. - return box.min_x + (box.min_y << 32) + (box.min_y >> 32); -} - -template -std::string BoxSet::dump() const{ - std::string str = "BoxSet: "; - if (m_boxes.empty()){ - str += "(empty)"; - str += "\r\n"; - return str; - } - str += std::to_string(m_boxes.size()) + " items\r\n"; - for (const auto& item : m_boxes){ - str += " {" + std::to_string(item.second.m_box.min_x); - str += "-" + std::to_string(item.second.m_box.max_x); - str += ", " + std::to_string(item.second.m_box.min_y); - str += "-" + std::to_string(item.second.m_box.max_y); - str += "}\r\n"; - } - return str; -} - -template -typename BoxSet::iterator BoxSet::insert(const Rectangle& box){ - auto iter = m_boxes.end(); - auto min_x = m_min_x.end(); - auto max_x = m_max_x.end(); - auto min_y = m_min_y.end(); - auto max_y = m_max_y.end(); - try{ - iter = m_boxes.emplace(get_key(box), box); - min_x = m_min_x.emplace(box.min_x, &iter->second); - max_x = m_max_x.emplace(box.max_x, &iter->second); - min_y = m_min_y.emplace(box.min_y, &iter->second); - max_y = m_max_y.emplace(box.max_y, &iter->second); - iter->second.m_min_x = min_x; - iter->second.m_max_x = max_x; - iter->second.m_min_y = min_y; - iter->second.m_max_y = max_y; - }catch (...){ - if (iter != m_boxes.end()){ m_boxes.erase(iter); } - if (min_x != m_min_x.end()){ m_min_x.erase(min_x); } - if (max_x != m_max_x.end()){ m_max_x.erase(max_x); } - if (min_y != m_min_y.end()){ m_min_y.erase(min_x); } - if (max_y != m_max_y.end()){ m_max_y.erase(max_x); } - throw; - } - return iter; -} -template -typename BoxSet::iterator BoxSet::erase(iterator item){ - m_min_x.erase(item.iterator_min_x()); - m_max_x.erase(item.iterator_max_x()); - m_min_y.erase(item.iterator_min_y()); - m_max_y.erase(item.iterator_max_y()); - return m_boxes.erase(item.m_iter); -} -template -typename BoxSet::axis_iterator BoxSet::erase(axis_iterator item){ - axis_iterator next = item; - ++next; - - size_t key = get_key(*item->second); - auto iter = m_boxes.find(key); - Entry* entry = item->second; - - // Find element in the boxes map. - while (true){ - if (iter == m_boxes.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "axis_iterator points in invalid box."); - } - if (&iter->second == entry){ - break; - } - ++iter; - } - - // Remove it. - erase(iter); - - return next; -} - - -#if 0 -template -template -void BoxSet::iterate_in_or_on(Type x, Type y, Func&& lambda){ - axis_iterator iter = lower_bound_min_x(x); - - // Iterate for every x within - while (iter == end_min_x() && iter->first <= x){ - Entry& entry = *iter->second; - - ++iter; - if (entry.m_min_y <= y && y <= entry.m_min_y){ - lambda(); - } - } -} -#endif - - - - - - - -} -#endif +/* Box Set + * + * From: https://github.com/PokemonAutomation/ + * + * This class is experimental. It currently doesn't actually accomplish + * what it was intended for. + * + */ + +#ifndef PokemonAutomation_BoxSet_H +#define PokemonAutomation_BoxSet_H + +#include +#include +#include "Common/Cpp/Rectangle.h" +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + + +// +// An unordered container holding a set of boxes. +// +// Iterating this container normally will iterate all the boxes in a fixed, but +// undefined order. +// +// This class provides "axis iterators" that allow you to iterate the elements +// in order of each of the axis points on the box. This lets you efficiently +// iterate boxes that overlap with a point or another box. +// +template +class BoxSet{ +public: + size_t size() const{ return m_boxes.size(); } + std::string dump() const; + +public: + class Entry; + + // Normal iterators. These iterate all the elements in a fixed, but + // undefined order. + class iterator; + class const_iterator; + + const_iterator cbegin() const; + const_iterator begin () const; + iterator begin (); + + const_iterator cend() const; + const_iterator end () const; + iterator end (); + +public: + // Axis iterator. These iterate the elements in increasing order either on + // the X or Y axis. + + using axis_iterator = typename std::multimap::const_iterator; + + axis_iterator end_min_x() const{ return m_min_x.end(); } + axis_iterator end_max_x() const{ return m_max_x.end(); } + axis_iterator end_min_y() const{ return m_min_y.end(); } + axis_iterator end_max_y() const{ return m_max_y.end(); } + + axis_iterator lower_bound_min_x(Type x) const{ return m_min_x.lower_bound(x); } + axis_iterator upper_bound_min_x(Type x) const{ return m_min_x.upper_bound(x); } + axis_iterator lower_bound_max_x(Type x) const{ return m_max_x.lower_bound(x); } + axis_iterator upper_bound_max_x(Type x) const{ return m_max_x.upper_bound(x); } + axis_iterator lower_bound_min_y(Type y) const{ return m_min_y.lower_bound(y); } + axis_iterator upper_bound_min_y(Type y) const{ return m_min_y.upper_bound(y); } + axis_iterator lower_bound_max_y(Type y) const{ return m_max_y.lower_bound(y); } + axis_iterator upper_bound_max_y(Type y) const{ return m_max_y.upper_bound(y); } + +public: + // Insert box into set and return a normal iterator to it. + iterator insert(const Rectangle& box); + + // Erase an iterator and return the next iterator. This will invalidate + // all other iterators pointing to the same element. + iterator erase(iterator item); + axis_iterator erase(axis_iterator item); + +public: + // Advanced Functions + + // Iterate on all boxes which either contain this point or on its border. + template + void iterate_in_or_on(Type x, Type y, Func&& lambda); + + +private: + static size_t get_key(const Rectangle& box); + +private: + std::multimap m_boxes; + std::multimap m_min_x; + std::multimap m_max_x; + std::multimap m_min_y; + std::multimap m_max_y; +}; + + + +template +class BoxSet::Entry{ +public: + Entry(const Rectangle& box) + : m_box(box) + {} + + operator const Rectangle&() const{ return m_box; } + const Rectangle* operator->() const{ return &m_box; } + const Rectangle& box() const{ return m_box; } + +private: + friend class BoxSet; + Rectangle m_box; + typename std::multimap::iterator m_min_x; + typename std::multimap::iterator m_max_x; + typename std::multimap::iterator m_min_y; + typename std::multimap::iterator m_max_y; +}; + + +template +class BoxSet::iterator{ +public: + bool operator==(const iterator& iter) const{ return m_iter == iter.m_iter; } + + iterator operator++(){ + ++m_iter; + return *this; + } + auto operator*() const{ return *m_iter; } + auto operator*(){ return *m_iter; } + auto operator->() const{ return m_iter.operator->(); } + auto operator->(){ return m_iter.operator->(); } + + axis_iterator iterator_min_x() const{ + return m_iter->second.m_min_x; + } + axis_iterator iterator_max_x() const{ + return m_iter->second.m_max_x; + } + axis_iterator iterator_min_y() const{ + return m_iter->second.m_min_y; + } + axis_iterator iterator_max_y() const{ + return m_iter->second.m_max_y; + } + +private: + friend class BoxSet; + friend class const_iterator; + + typename std::multimap::iterator m_iter; + + iterator(typename std::multimap::iterator iter) + : m_iter(iter) + {} +}; + + +template +class BoxSet::const_iterator{ +public: + bool operator==(const iterator& iter) const{ return m_iter == iter.m_iter; } + + const_iterator(iterator iter) + : m_iter(iter.m_iter) + {} + const_iterator operator++(){ + ++m_iter; + return *this; + } + auto operator*() const{ return *m_iter; } + auto operator*(){ return *m_iter; } + auto operator->() const{ return m_iter.operator->(); } + auto operator->(){ return m_iter.operator->(); } + + axis_iterator iterator_min_x() const{ + return m_iter->second.m_min_x; + } + axis_iterator iterator_max_x() const{ + return m_iter->second.m_max_x; + } + axis_iterator iterator_min_y() const{ + return m_iter->second.m_min_y; + } + axis_iterator iterator_max_y() const{ + return m_iter->second.m_max_y; + } + +private: + friend class BoxSet; + + typename std::multimap::iterator m_iter; + + const_iterator(typename std::multimap::iterator iter) + : m_iter(iter) + {} +}; + + + + + +// +// Implementations +// + + + +template +inline typename BoxSet::const_iterator BoxSet::cbegin() const{ + return m_boxes.cbegin(); +} +template +inline typename BoxSet::const_iterator BoxSet::begin () const{ + return m_boxes.begin(); +} +template +inline typename BoxSet::iterator BoxSet::begin(){ + return m_boxes.begin(); +} + +template +inline typename BoxSet::const_iterator BoxSet::cend() const{ + return m_boxes.cend(); +} +template +inline typename BoxSet::const_iterator BoxSet::end() const{ + return m_boxes.end(); +} +template +inline typename BoxSet::iterator BoxSet::end(){ + return m_boxes.end(); +} + + + +template +size_t BoxSet::get_key(const Rectangle& box){ + // Basically a simple hash function that preserves some sort of visual + // order if everything is small. + return box.min_x + (box.min_y << 32) + (box.min_y >> 32); +} + +template +std::string BoxSet::dump() const{ + std::string str = "BoxSet: "; + if (m_boxes.empty()){ + str += "(empty)"; + str += "\r\n"; + return str; + } + str += std::to_string(m_boxes.size()) + " items\r\n"; + for (const auto& item : m_boxes){ + str += " {" + std::to_string(item.second.m_box.min_x); + str += "-" + std::to_string(item.second.m_box.max_x); + str += ", " + std::to_string(item.second.m_box.min_y); + str += "-" + std::to_string(item.second.m_box.max_y); + str += "}\r\n"; + } + return str; +} + +template +typename BoxSet::iterator BoxSet::insert(const Rectangle& box){ + auto iter = m_boxes.end(); + auto min_x = m_min_x.end(); + auto max_x = m_max_x.end(); + auto min_y = m_min_y.end(); + auto max_y = m_max_y.end(); + try{ + iter = m_boxes.emplace(get_key(box), box); + min_x = m_min_x.emplace(box.min_x, &iter->second); + max_x = m_max_x.emplace(box.max_x, &iter->second); + min_y = m_min_y.emplace(box.min_y, &iter->second); + max_y = m_max_y.emplace(box.max_y, &iter->second); + iter->second.m_min_x = min_x; + iter->second.m_max_x = max_x; + iter->second.m_min_y = min_y; + iter->second.m_max_y = max_y; + }catch (...){ + if (iter != m_boxes.end()){ m_boxes.erase(iter); } + if (min_x != m_min_x.end()){ m_min_x.erase(min_x); } + if (max_x != m_max_x.end()){ m_max_x.erase(max_x); } + if (min_y != m_min_y.end()){ m_min_y.erase(min_x); } + if (max_y != m_max_y.end()){ m_max_y.erase(max_x); } + throw; + } + return iter; +} +template +typename BoxSet::iterator BoxSet::erase(iterator item){ + m_min_x.erase(item.iterator_min_x()); + m_max_x.erase(item.iterator_max_x()); + m_min_y.erase(item.iterator_min_y()); + m_max_y.erase(item.iterator_max_y()); + return m_boxes.erase(item.m_iter); +} +template +typename BoxSet::axis_iterator BoxSet::erase(axis_iterator item){ + axis_iterator next = item; + ++next; + + size_t key = get_key(*item->second); + auto iter = m_boxes.find(key); + Entry* entry = item->second; + + // Find element in the boxes map. + while (true){ + if (iter == m_boxes.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "axis_iterator points in invalid box."); + } + if (&iter->second == entry){ + break; + } + ++iter; + } + + // Remove it. + erase(iter); + + return next; +} + + +#if 0 +template +template +void BoxSet::iterate_in_or_on(Type x, Type y, Func&& lambda){ + axis_iterator iter = lower_bound_min_x(x); + + // Iterate for every x within + while (iter == end_min_x() && iter->first <= x){ + Entry& entry = *iter->second; + + ++iter; + if (entry.m_min_y <= y && y <= entry.m_min_y){ + lambda(); + } + } +} +#endif + + + + + + + +} +#endif diff --git a/Common/Cpp/Containers/CircularBuffer (disabled).cpp b/Common/Cpp/Containers/CircularBuffer (disabled).cpp index a702ef8e24..6f06b76364 100644 --- a/Common/Cpp/Containers/CircularBuffer (disabled).cpp +++ b/Common/Cpp/Containers/CircularBuffer (disabled).cpp @@ -1,359 +1,359 @@ -/* Circular Buffer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Exceptions.h" -#include "AlignedVector.tpp" -#include "CircularBuffer.h" - -namespace PokemonAutomation{ - - - -CircularBuffer::CircularBuffer(size_t initial_size) - : m_buffer(initial_size) -{ -#ifdef PA_DEBUG_CircularBuffer - memset(m_buffer.data(), '-', m_buffer.size()); -#endif -} -CircularBuffer::~CircularBuffer(){} -void CircularBuffer::push_back(const void* data, size_t bytes){ - size_t new_size = m_size + bytes; - if (new_size > m_buffer.size()){ - expand(new_size); - } - - if (m_size == 0){ - m_start = 0; - m_end = 0; - } - - // Copy all the way to the end. - size_t block = m_buffer.size() - std::max(m_size, m_end); - block = std::min(block, bytes); - memcpy(m_buffer.data() + m_end, data, block); - m_size += block; - m_end += block; - data = (char*)data + block; - bytes -= block; - - // Rewind the pointer if necessary. - if (m_end == m_buffer.size()){ - m_end = 0; - } - - // Now copy the bottom. - if (bytes > 0){ - memcpy(m_buffer.data() + m_end, data, bytes); - m_size += bytes; - m_end += bytes; - } -} -size_t CircularBuffer::pop_front(void* data, size_t bytes) noexcept{ - bytes = std::min(bytes, m_size); - - size_t remaining = bytes; - - // Copy all the way to the end. - size_t block = std::min(remaining, m_buffer.size() - m_start); - memcpy(data, m_buffer.data() + m_start, block); - m_size -= block; - m_start += block; - data = (char*)data + block; - remaining -= block; - - // Rewind the pointer if necessary. - if (m_start == m_buffer.size()){ - m_start = 0; - } - - // Now copy the bottom. - if (remaining > 0){ - memcpy(data, m_buffer.data() + m_start, remaining); - m_size -= remaining; - m_start += remaining; - } - - return bytes; -} -void CircularBuffer::expand(size_t min_size){ - size_t buffer_size = m_buffer.size(); - while (buffer_size < min_size){ - buffer_size *= 2; - } - AlignedVector new_buffer(buffer_size); -#ifdef PA_DEBUG_CircularBuffer - memset(new_buffer.data(), '-', new_buffer.size()); -#endif - size_t size = m_size; - pop_front(new_buffer.data(), size); - m_buffer = std::move(new_buffer); - m_size = size; - m_start = 0; - m_end = size; -} -#ifdef PA_DEBUG_CircularBuffer -std::string CircularBuffer::dump() const{ - std::string ret; - ret += "size = " + std::to_string(m_size) + "\n"; - ret += "start = " + std::to_string(m_start) + "\n"; - ret += "end = " + std::to_string(m_end) + "\n"; - ret += "buffer = " + std::string(m_buffer.data(), m_buffer.size()); - return ret; -} -#endif - - - - - -StreamReader::StreamReader(size_t initial_size){ - size_t buffer_size = 1; - while (buffer_size < initial_size){ - buffer_size *= 2; - } - m_buffer = AlignedVector(buffer_size); -#ifdef PA_DEBUG_CircularBuffer - memset(m_buffer.data(), '-', m_buffer.size()); -#endif -} -StreamReader::~StreamReader(){} -void StreamReader::push_back(const void* data, size_t bytes){ - size_t size = m_end - m_start; - size_t new_size = size + bytes; - if (new_size > m_buffer.size()){ - expand(new_size); - } - - size_t mask = m_buffer.size() - 1; -// size_t idx_s = (size_t)m_start & mask; - size_t idx_e = (size_t)m_end & mask; - - // Copy all the way to the end. - size_t block = m_buffer.size() - std::max(size, idx_e); - block = std::min(block, bytes); - memcpy(m_buffer.data() + idx_e, data, block); - m_end += block; - idx_e = (size_t)m_end & mask; - data = (char*)data + block; - bytes -= block; - - - // Now copy the bottom. - if (bytes > 0){ - memcpy(m_buffer.data() + idx_e, data, bytes); - m_end += bytes; - } -} -void StreamReader::read(void* data, uint64_t offset, size_t bytes) noexcept{ -#ifdef PA_DEBUG_CircularBuffer - constexpr char PADDING = '*'; -#else - constexpr char PADDING = 0; -#endif - uint64_t read_end = offset + bytes; - - // Completely before. - if (read_end <= m_start){ - memset(data, PADDING, bytes); - return; - } - - // Completely after. - if (offset >= m_end){ - memset(data, PADDING, bytes); - return; - } - - // Starts before. - if (offset < m_start){ - size_t block = (size_t)(m_start - offset); - memset(data, PADDING, block); - data = (char*)data + block; - offset += block; - bytes -= block; - } - - // Ends after. - if (read_end > m_end){ - size_t block = (size_t)(read_end - m_end); - memset((char*)data + bytes - block, PADDING, block); - bytes -= block; - } - - size_t available = m_end - offset; - size_t mask = m_buffer.size() - 1; - size_t idx_s = (size_t)offset & mask; -// size_t idx_e = (size_t)m_end & mask; - - // Find out how many bytes we can read contiguously. - size_t block = std::min(m_buffer.size() - idx_s, available); - - // Don't read more bytes than is requested. - block = std::min(block, bytes); - - // Perform the read. - memcpy(data, m_buffer.data() + idx_s, block); - data = (char*)data + block; - offset += block; - bytes -= block; - idx_s = (size_t)offset & mask; - - // Wrap around and read the rest. - if (bytes > 0){ - memcpy(data, m_buffer.data() + idx_s, bytes); - } -} -void StreamReader::pop_to(uint64_t offset) noexcept{ - m_start = std::max(m_start, offset); -} -void StreamReader::expand(size_t min_size){ - size_t buffer_size = m_buffer.size(); - while (buffer_size < min_size){ - buffer_size *= 2; - } - - // TODO: Optimize out this allocation + copy. - size_t size = (size_t)(m_end - m_start); - AlignedVector tmp(size); - read(tmp.data(), m_start, size); - - m_buffer = AlignedVector(buffer_size); -#ifdef PA_DEBUG_CircularBuffer - memset(m_buffer.data(), '-', m_buffer.size()); -#endif - m_end = m_start; - push_back(tmp.data(), size); -} -#ifdef PA_DEBUG_CircularBuffer -std::string StreamReader::dump() const{ - std::string ret; - ret += "start = " + std::to_string(m_start) + "\n"; - ret += "end = " + std::to_string(m_end) + "\n"; - ret += "buffer = " + std::string(m_buffer.data(), m_buffer.size()); - return ret; -} -#endif - - - - -#if 0 -ConvertedStreamReader::ConvertedStreamReader( - size_t raw_object_size, - size_t converted_object_size, - size_t initial_objects // Will be rounded up to a power-of-two. -) - : m_raw_object_size(raw_object_size) - , m_converted_object_size(converted_object_size) - , m_edge(raw_object_size) -{ - m_buffer_capacity = 1; - while (m_buffer_capacity < initial_objects){ - m_buffer_capacity *= 2; - } - m_buffer = AlignedVector(m_buffer_capacity * converted_object_size); -#ifdef PA_DEBUG_CircularBuffer - memset(m_buffer.data(), '-', m_buffer.size()); -#endif -} -ConvertedStreamReader::~ConvertedStreamReader(){} -void ConvertedStreamReader::push_back(const void* data, size_t bytes){ - size_t stored = m_end - m_start; - size_t objects = (bytes + m_edge_size) / m_raw_object_size; - - // Make sure there is enough space in the buffer. - if (stored + objects > m_buffer_capacity){ - - } - - // Fill the edge block. - if (m_edge_size > 0){ - size_t block = std::min(m_raw_object_size - m_edge_size, bytes); - memcpy(m_edge.data() + m_edge_size, data, block); - data = (char*)data + block; - bytes -= block; - } - - size_t mask = m_buffer_capacity - 1; -// size_t index_s = (size_t)m_start & mask; - size_t index_e = (size_t)m_end & mask; - - // Process completed edge block. - if (m_edge_size >= m_raw_object_size){ - convert(m_buffer.data() + index_e * m_converted_object_size, m_edge.data(), 1); - m_edge_size = 0; - m_end++; - index_e = (size_t)m_end & mask; - stored++; - objects--; - } - - { - // Write as far as we can. - size_t block = m_buffer_capacity - std::max(stored, index_e); - - // But don't write more than we have right now. - block = std::min(block, objects); - - convert(m_buffer.data() + index_e * m_converted_object_size, data, block); - size_t raw_bytes = block * m_raw_object_size; - data = (char*)data + raw_bytes; - bytes -= raw_bytes; - objects -= block; - m_end += block; -// stored += block; - index_e = (size_t)m_end & mask; - } - - // Now handle the wrap-around. - if (objects > 0){ - size_t block = objects; - convert(m_buffer.data() + index_e * m_converted_object_size, data, block); - size_t raw_bytes = block * m_raw_object_size; - data = (char*)data + raw_bytes; - bytes -= raw_bytes; -// objects -= block; - m_end += block; -// stored += block; -// index_e = (size_t)m_end & mask; - } - - // Copy remaining bytes into edge buffer. - memcpy(m_edge.data(), data, bytes); - m_edge_size = bytes; -} - - - - -#ifdef PA_DEBUG_CircularBuffer -std::string ConvertedStreamReader::dump() const{ - std::string ret; - ret += "start = " + std::to_string(m_start) + "\n"; - ret += "end = " + std::to_string(m_end) + "\n"; - ret += "capacity = " + std::to_string(m_buffer_capacity) + "\n"; - ret += "buffer = " + std::string(m_buffer.data(), m_buffer.size()); - ret += "edge = " + std::string(m_edge.data(), m_edge_size); - return ret; -} -#endif - -#endif - - - - - - - - - - - -} +/* Circular Buffer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Exceptions.h" +#include "AlignedVector.tpp" +#include "CircularBuffer.h" + +namespace PokemonAutomation{ + + + +CircularBuffer::CircularBuffer(size_t initial_size) + : m_buffer(initial_size) +{ +#ifdef PA_DEBUG_CircularBuffer + memset(m_buffer.data(), '-', m_buffer.size()); +#endif +} +CircularBuffer::~CircularBuffer(){} +void CircularBuffer::push_back(const void* data, size_t bytes){ + size_t new_size = m_size + bytes; + if (new_size > m_buffer.size()){ + expand(new_size); + } + + if (m_size == 0){ + m_start = 0; + m_end = 0; + } + + // Copy all the way to the end. + size_t block = m_buffer.size() - std::max(m_size, m_end); + block = std::min(block, bytes); + memcpy(m_buffer.data() + m_end, data, block); + m_size += block; + m_end += block; + data = (char*)data + block; + bytes -= block; + + // Rewind the pointer if necessary. + if (m_end == m_buffer.size()){ + m_end = 0; + } + + // Now copy the bottom. + if (bytes > 0){ + memcpy(m_buffer.data() + m_end, data, bytes); + m_size += bytes; + m_end += bytes; + } +} +size_t CircularBuffer::pop_front(void* data, size_t bytes) noexcept{ + bytes = std::min(bytes, m_size); + + size_t remaining = bytes; + + // Copy all the way to the end. + size_t block = std::min(remaining, m_buffer.size() - m_start); + memcpy(data, m_buffer.data() + m_start, block); + m_size -= block; + m_start += block; + data = (char*)data + block; + remaining -= block; + + // Rewind the pointer if necessary. + if (m_start == m_buffer.size()){ + m_start = 0; + } + + // Now copy the bottom. + if (remaining > 0){ + memcpy(data, m_buffer.data() + m_start, remaining); + m_size -= remaining; + m_start += remaining; + } + + return bytes; +} +void CircularBuffer::expand(size_t min_size){ + size_t buffer_size = m_buffer.size(); + while (buffer_size < min_size){ + buffer_size *= 2; + } + AlignedVector new_buffer(buffer_size); +#ifdef PA_DEBUG_CircularBuffer + memset(new_buffer.data(), '-', new_buffer.size()); +#endif + size_t size = m_size; + pop_front(new_buffer.data(), size); + m_buffer = std::move(new_buffer); + m_size = size; + m_start = 0; + m_end = size; +} +#ifdef PA_DEBUG_CircularBuffer +std::string CircularBuffer::dump() const{ + std::string ret; + ret += "size = " + std::to_string(m_size) + "\n"; + ret += "start = " + std::to_string(m_start) + "\n"; + ret += "end = " + std::to_string(m_end) + "\n"; + ret += "buffer = " + std::string(m_buffer.data(), m_buffer.size()); + return ret; +} +#endif + + + + + +StreamReader::StreamReader(size_t initial_size){ + size_t buffer_size = 1; + while (buffer_size < initial_size){ + buffer_size *= 2; + } + m_buffer = AlignedVector(buffer_size); +#ifdef PA_DEBUG_CircularBuffer + memset(m_buffer.data(), '-', m_buffer.size()); +#endif +} +StreamReader::~StreamReader(){} +void StreamReader::push_back(const void* data, size_t bytes){ + size_t size = m_end - m_start; + size_t new_size = size + bytes; + if (new_size > m_buffer.size()){ + expand(new_size); + } + + size_t mask = m_buffer.size() - 1; +// size_t idx_s = (size_t)m_start & mask; + size_t idx_e = (size_t)m_end & mask; + + // Copy all the way to the end. + size_t block = m_buffer.size() - std::max(size, idx_e); + block = std::min(block, bytes); + memcpy(m_buffer.data() + idx_e, data, block); + m_end += block; + idx_e = (size_t)m_end & mask; + data = (char*)data + block; + bytes -= block; + + + // Now copy the bottom. + if (bytes > 0){ + memcpy(m_buffer.data() + idx_e, data, bytes); + m_end += bytes; + } +} +void StreamReader::read(void* data, uint64_t offset, size_t bytes) noexcept{ +#ifdef PA_DEBUG_CircularBuffer + constexpr char PADDING = '*'; +#else + constexpr char PADDING = 0; +#endif + uint64_t read_end = offset + bytes; + + // Completely before. + if (read_end <= m_start){ + memset(data, PADDING, bytes); + return; + } + + // Completely after. + if (offset >= m_end){ + memset(data, PADDING, bytes); + return; + } + + // Starts before. + if (offset < m_start){ + size_t block = (size_t)(m_start - offset); + memset(data, PADDING, block); + data = (char*)data + block; + offset += block; + bytes -= block; + } + + // Ends after. + if (read_end > m_end){ + size_t block = (size_t)(read_end - m_end); + memset((char*)data + bytes - block, PADDING, block); + bytes -= block; + } + + size_t available = m_end - offset; + size_t mask = m_buffer.size() - 1; + size_t idx_s = (size_t)offset & mask; +// size_t idx_e = (size_t)m_end & mask; + + // Find out how many bytes we can read contiguously. + size_t block = std::min(m_buffer.size() - idx_s, available); + + // Don't read more bytes than is requested. + block = std::min(block, bytes); + + // Perform the read. + memcpy(data, m_buffer.data() + idx_s, block); + data = (char*)data + block; + offset += block; + bytes -= block; + idx_s = (size_t)offset & mask; + + // Wrap around and read the rest. + if (bytes > 0){ + memcpy(data, m_buffer.data() + idx_s, bytes); + } +} +void StreamReader::pop_to(uint64_t offset) noexcept{ + m_start = std::max(m_start, offset); +} +void StreamReader::expand(size_t min_size){ + size_t buffer_size = m_buffer.size(); + while (buffer_size < min_size){ + buffer_size *= 2; + } + + // TODO: Optimize out this allocation + copy. + size_t size = (size_t)(m_end - m_start); + AlignedVector tmp(size); + read(tmp.data(), m_start, size); + + m_buffer = AlignedVector(buffer_size); +#ifdef PA_DEBUG_CircularBuffer + memset(m_buffer.data(), '-', m_buffer.size()); +#endif + m_end = m_start; + push_back(tmp.data(), size); +} +#ifdef PA_DEBUG_CircularBuffer +std::string StreamReader::dump() const{ + std::string ret; + ret += "start = " + std::to_string(m_start) + "\n"; + ret += "end = " + std::to_string(m_end) + "\n"; + ret += "buffer = " + std::string(m_buffer.data(), m_buffer.size()); + return ret; +} +#endif + + + + +#if 0 +ConvertedStreamReader::ConvertedStreamReader( + size_t raw_object_size, + size_t converted_object_size, + size_t initial_objects // Will be rounded up to a power-of-two. +) + : m_raw_object_size(raw_object_size) + , m_converted_object_size(converted_object_size) + , m_edge(raw_object_size) +{ + m_buffer_capacity = 1; + while (m_buffer_capacity < initial_objects){ + m_buffer_capacity *= 2; + } + m_buffer = AlignedVector(m_buffer_capacity * converted_object_size); +#ifdef PA_DEBUG_CircularBuffer + memset(m_buffer.data(), '-', m_buffer.size()); +#endif +} +ConvertedStreamReader::~ConvertedStreamReader(){} +void ConvertedStreamReader::push_back(const void* data, size_t bytes){ + size_t stored = m_end - m_start; + size_t objects = (bytes + m_edge_size) / m_raw_object_size; + + // Make sure there is enough space in the buffer. + if (stored + objects > m_buffer_capacity){ + + } + + // Fill the edge block. + if (m_edge_size > 0){ + size_t block = std::min(m_raw_object_size - m_edge_size, bytes); + memcpy(m_edge.data() + m_edge_size, data, block); + data = (char*)data + block; + bytes -= block; + } + + size_t mask = m_buffer_capacity - 1; +// size_t index_s = (size_t)m_start & mask; + size_t index_e = (size_t)m_end & mask; + + // Process completed edge block. + if (m_edge_size >= m_raw_object_size){ + convert(m_buffer.data() + index_e * m_converted_object_size, m_edge.data(), 1); + m_edge_size = 0; + m_end++; + index_e = (size_t)m_end & mask; + stored++; + objects--; + } + + { + // Write as far as we can. + size_t block = m_buffer_capacity - std::max(stored, index_e); + + // But don't write more than we have right now. + block = std::min(block, objects); + + convert(m_buffer.data() + index_e * m_converted_object_size, data, block); + size_t raw_bytes = block * m_raw_object_size; + data = (char*)data + raw_bytes; + bytes -= raw_bytes; + objects -= block; + m_end += block; +// stored += block; + index_e = (size_t)m_end & mask; + } + + // Now handle the wrap-around. + if (objects > 0){ + size_t block = objects; + convert(m_buffer.data() + index_e * m_converted_object_size, data, block); + size_t raw_bytes = block * m_raw_object_size; + data = (char*)data + raw_bytes; + bytes -= raw_bytes; +// objects -= block; + m_end += block; +// stored += block; +// index_e = (size_t)m_end & mask; + } + + // Copy remaining bytes into edge buffer. + memcpy(m_edge.data(), data, bytes); + m_edge_size = bytes; +} + + + + +#ifdef PA_DEBUG_CircularBuffer +std::string ConvertedStreamReader::dump() const{ + std::string ret; + ret += "start = " + std::to_string(m_start) + "\n"; + ret += "end = " + std::to_string(m_end) + "\n"; + ret += "capacity = " + std::to_string(m_buffer_capacity) + "\n"; + ret += "buffer = " + std::string(m_buffer.data(), m_buffer.size()); + ret += "edge = " + std::string(m_edge.data(), m_edge_size); + return ret; +} +#endif + +#endif + + + + + + + + + + + +} diff --git a/Common/Cpp/Containers/CircularBuffer (disabled).h b/Common/Cpp/Containers/CircularBuffer (disabled).h index 427f3ef1ef..364d5b3458 100644 --- a/Common/Cpp/Containers/CircularBuffer (disabled).h +++ b/Common/Cpp/Containers/CircularBuffer (disabled).h @@ -1,146 +1,146 @@ -/* Circular Buffer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CircularBuffer_H -#define PokemonAutomation_CircularBuffer_H - -#include -#include "AlignedVector.h" - -#define PA_DEBUG_CircularBuffer - -#ifdef PA_DEBUG_CircularBuffer -#include -#endif - - -namespace PokemonAutomation{ - - -class CircularBuffer{ -public: - CircularBuffer(size_t initial_size); - ~CircularBuffer(); - - size_t size() const{ return m_size; } - - void push_back(const void* data, size_t bytes); - size_t pop_front(void* data, size_t bytes) noexcept; - -#ifdef PA_DEBUG_CircularBuffer - std::string dump() const; -#endif - -private: - void expand(size_t min_size); - -private: - AlignedVector m_buffer; - size_t m_size = 0; - size_t m_start = 0; - size_t m_end = 0; -}; - - - -class StreamReader{ -public: - StreamReader(size_t initial_size); // Will be rounded up to a power-of-two. - ~StreamReader(); - - // Return the offset of the oldest byte that is still stored. - size_t oldest() const{ return m_start; } - - // Return the 1 past the newest byte that is still stored. - size_t end() const{ return m_end; } - - // Return the # of bytes stored. - size_t bytes_stored() const{ return m_end - m_start; } - - // Push the specified buffer into the end of this stream. - void push_back(const void* data, size_t bytes); - - // Read "bytes" bytes starting from the specified offset. - // Bytes that are not stored are set to zero. - void read(void* data, uint64_t offset, size_t bytes) noexcept; - - // Evict all bytes before the specified offset from this stream. - void pop_to(uint64_t offset) noexcept; - -#ifdef PA_DEBUG_CircularBuffer - std::string dump() const; -#endif - -private: - void expand(size_t min_size); - -private: - AlignedVector m_buffer; - uint64_t m_start = 0; - uint64_t m_end = 0; -}; - - - -#if 0 -class ConvertedStreamReader{ -public: - ConvertedStreamReader( - size_t raw_object_size, // Size of each object in the raw input stream. - size_t converted_object_size, // Size of each object after conversion to preferred format. - size_t initial_objects // Will be rounded up to a power-of-two. - ); - ~ConvertedStreamReader(); - - // Return the offset of the oldest byte that is still stored. - size_t oldest() const{ return m_start; } - - // Return the 1 past the newest byte that is still stored. - size_t end() const{ return m_end; } - - // Return the # of bytes stored. - size_t objects_stored() const{ return m_end - m_start; } - - // Push the specified buffer into the end of this stream. - void push_back(const void* data, size_t bytes); - - // Evict all objects before the specified offset from this stream. - void pop_to(uint64_t offset) noexcept; - -#ifdef PA_DEBUG_CircularBuffer - std::string dump() const; -#endif - - -protected: - virtual void convert(void* object, const void* raw, size_t count) = 0; - - -private: - size_t m_raw_object_size; - size_t m_converted_object_size; - - AlignedVector m_edge; - size_t m_edge_size = 0; - - AlignedVector m_buffer; - size_t m_buffer_capacity = 0; - uint64_t m_start = 0; - uint64_t m_end = 0; -}; -#endif - - - - - - - - - - -} -#endif +/* Circular Buffer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CircularBuffer_H +#define PokemonAutomation_CircularBuffer_H + +#include +#include "AlignedVector.h" + +#define PA_DEBUG_CircularBuffer + +#ifdef PA_DEBUG_CircularBuffer +#include +#endif + + +namespace PokemonAutomation{ + + +class CircularBuffer{ +public: + CircularBuffer(size_t initial_size); + ~CircularBuffer(); + + size_t size() const{ return m_size; } + + void push_back(const void* data, size_t bytes); + size_t pop_front(void* data, size_t bytes) noexcept; + +#ifdef PA_DEBUG_CircularBuffer + std::string dump() const; +#endif + +private: + void expand(size_t min_size); + +private: + AlignedVector m_buffer; + size_t m_size = 0; + size_t m_start = 0; + size_t m_end = 0; +}; + + + +class StreamReader{ +public: + StreamReader(size_t initial_size); // Will be rounded up to a power-of-two. + ~StreamReader(); + + // Return the offset of the oldest byte that is still stored. + size_t oldest() const{ return m_start; } + + // Return the 1 past the newest byte that is still stored. + size_t end() const{ return m_end; } + + // Return the # of bytes stored. + size_t bytes_stored() const{ return m_end - m_start; } + + // Push the specified buffer into the end of this stream. + void push_back(const void* data, size_t bytes); + + // Read "bytes" bytes starting from the specified offset. + // Bytes that are not stored are set to zero. + void read(void* data, uint64_t offset, size_t bytes) noexcept; + + // Evict all bytes before the specified offset from this stream. + void pop_to(uint64_t offset) noexcept; + +#ifdef PA_DEBUG_CircularBuffer + std::string dump() const; +#endif + +private: + void expand(size_t min_size); + +private: + AlignedVector m_buffer; + uint64_t m_start = 0; + uint64_t m_end = 0; +}; + + + +#if 0 +class ConvertedStreamReader{ +public: + ConvertedStreamReader( + size_t raw_object_size, // Size of each object in the raw input stream. + size_t converted_object_size, // Size of each object after conversion to preferred format. + size_t initial_objects // Will be rounded up to a power-of-two. + ); + ~ConvertedStreamReader(); + + // Return the offset of the oldest byte that is still stored. + size_t oldest() const{ return m_start; } + + // Return the 1 past the newest byte that is still stored. + size_t end() const{ return m_end; } + + // Return the # of bytes stored. + size_t objects_stored() const{ return m_end - m_start; } + + // Push the specified buffer into the end of this stream. + void push_back(const void* data, size_t bytes); + + // Evict all objects before the specified offset from this stream. + void pop_to(uint64_t offset) noexcept; + +#ifdef PA_DEBUG_CircularBuffer + std::string dump() const; +#endif + + +protected: + virtual void convert(void* object, const void* raw, size_t count) = 0; + + +private: + size_t m_raw_object_size; + size_t m_converted_object_size; + + AlignedVector m_edge; + size_t m_edge_size = 0; + + AlignedVector m_buffer; + size_t m_buffer_capacity = 0; + uint64_t m_start = 0; + uint64_t m_end = 0; +}; +#endif + + + + + + + + + + +} +#endif diff --git a/Common/Cpp/Containers/CircularBuffer.h b/Common/Cpp/Containers/CircularBuffer.h index 488dac8392..58a18f6fb3 100644 --- a/Common/Cpp/Containers/CircularBuffer.h +++ b/Common/Cpp/Containers/CircularBuffer.h @@ -1,215 +1,215 @@ -/* Circular Buffer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CircularBuffer_H -#define PokemonAutomation_CircularBuffer_H - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedMalloc.h" - -namespace PokemonAutomation{ - - - -template -class CircularBuffer{ -public: - ~CircularBuffer(); - CircularBuffer(CircularBuffer&& x) noexcept; - void operator=(CircularBuffer&& x) noexcept; - CircularBuffer(const CircularBuffer& x); - void operator=(const CircularBuffer& x); - -public: - CircularBuffer(); - CircularBuffer(size_t capacity); - - void clear() noexcept; - - size_t empty() const{ return m_front == m_back; } - size_t full() const{ return m_back - m_front >= m_capacity; } - size_t size() const{ return m_back - m_front; } - - const Object& front() const; - Object& front(); - const Object& operator[](size_t index) const; - Object& operator[](size_t index); - - - template - Object& push_back(Args&&... args); - template - Object* try_push_back(Args&&... args); - void pop_front(); - -private: - size_t m_capacity; - size_t m_front; - size_t m_back; - Object* m_ptr; -}; - - - -template -CircularBuffer::~CircularBuffer(){ - clear(); - aligned_free(m_ptr); -} -template -CircularBuffer::CircularBuffer(CircularBuffer&& x) noexcept - : m_capacity(x.m_capacity) - , m_front(x.m_front) - , m_back(x.m_back) - , m_ptr(x.m_ptr) -{ - x.m_capacity = 0; - x.m_front = 0; - x.m_back = 0; - x.m_ptr = nullptr; -} -template -void CircularBuffer::operator=(CircularBuffer&& x) noexcept{ - if (this == &x){ - return; - } - clear(); - aligned_free(m_ptr); - m_capacity = x.m_capacity; - m_front = x.m_front; - m_back = x.m_back; - m_ptr = x.m_ptr; - x.m_capacity = 0; - x.m_front = 0; - x.m_back = 0; - x.m_ptr = nullptr; -} -template -CircularBuffer::CircularBuffer(const CircularBuffer& x) - : CircularBuffer(x.m_capacity) -{ - size_t size = x.size(); - for (size_t c = 0; c < size; c++){ - push_back(x[c]); - } -} -template -void CircularBuffer::operator=(const CircularBuffer& x){ - if (this == &x){ - return; - } - CircularBuffer tmp(x); - *this = std::move(tmp); -} - -template -CircularBuffer::CircularBuffer() - : m_capacity(0) - , m_front(0) - , m_back(0) - , m_ptr(nullptr) -{} -template -CircularBuffer::CircularBuffer(size_t capacity) - : m_capacity(capacity) - , m_front(0) - , m_back(0) - , m_ptr(nullptr) -{ - if (capacity == 0){ - return; - } - m_ptr = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); - if (m_ptr == nullptr){ - throw std::bad_alloc(); - } -} - -template -void CircularBuffer::clear() noexcept{ - while (m_back > m_front){ - pop_front(); - } -} - - -template -const Object& CircularBuffer::front() const{ - return m_ptr[m_front]; -} -template -Object& CircularBuffer::front(){ - return m_ptr[m_front]; -} -template -const Object& CircularBuffer::operator[](size_t index) const{ - index += m_front; - if (index >= m_capacity){ - index -= m_capacity; - } - return m_ptr[index]; -} -template -Object& CircularBuffer::operator[](size_t index){ - index += m_front; - if (index >= m_capacity){ - index -= m_capacity; - } - return m_ptr[index]; -} - -template -template -Object& CircularBuffer::push_back(Args&&... args){ - if (m_back - m_front >= m_capacity){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to push while full."); - } - size_t back = m_back; - if (back >= m_capacity){ - back -= m_capacity; - } - new (m_ptr + back) Object(std::forward(args)...); - m_back++; - return m_ptr[back]; -} -template -template -Object* CircularBuffer::try_push_back(Args&&... args){ - if (m_back - m_front >= m_capacity){ - return nullptr; - } - size_t back = m_back; - if (back >= m_capacity){ - back -= m_capacity; - } - new (m_ptr + back) Object(std::forward(args)...); - m_back++; - return &m_ptr[back]; -} - -template -void CircularBuffer::pop_front(){ - if (m_front == m_back){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to pop while empty."); - } - size_t front = m_front; - m_ptr[front].~Object(); - front++; - size_t diff = front >= m_capacity ? m_capacity : 0; - m_front = front - diff; - m_back -= diff; -} - - - - - - - -} -#endif +/* Circular Buffer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CircularBuffer_H +#define PokemonAutomation_CircularBuffer_H + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedMalloc.h" + +namespace PokemonAutomation{ + + + +template +class CircularBuffer{ +public: + ~CircularBuffer(); + CircularBuffer(CircularBuffer&& x) noexcept; + void operator=(CircularBuffer&& x) noexcept; + CircularBuffer(const CircularBuffer& x); + void operator=(const CircularBuffer& x); + +public: + CircularBuffer(); + CircularBuffer(size_t capacity); + + void clear() noexcept; + + size_t empty() const{ return m_front == m_back; } + size_t full() const{ return m_back - m_front >= m_capacity; } + size_t size() const{ return m_back - m_front; } + + const Object& front() const; + Object& front(); + const Object& operator[](size_t index) const; + Object& operator[](size_t index); + + + template + Object& push_back(Args&&... args); + template + Object* try_push_back(Args&&... args); + void pop_front(); + +private: + size_t m_capacity; + size_t m_front; + size_t m_back; + Object* m_ptr; +}; + + + +template +CircularBuffer::~CircularBuffer(){ + clear(); + aligned_free(m_ptr); +} +template +CircularBuffer::CircularBuffer(CircularBuffer&& x) noexcept + : m_capacity(x.m_capacity) + , m_front(x.m_front) + , m_back(x.m_back) + , m_ptr(x.m_ptr) +{ + x.m_capacity = 0; + x.m_front = 0; + x.m_back = 0; + x.m_ptr = nullptr; +} +template +void CircularBuffer::operator=(CircularBuffer&& x) noexcept{ + if (this == &x){ + return; + } + clear(); + aligned_free(m_ptr); + m_capacity = x.m_capacity; + m_front = x.m_front; + m_back = x.m_back; + m_ptr = x.m_ptr; + x.m_capacity = 0; + x.m_front = 0; + x.m_back = 0; + x.m_ptr = nullptr; +} +template +CircularBuffer::CircularBuffer(const CircularBuffer& x) + : CircularBuffer(x.m_capacity) +{ + size_t size = x.size(); + for (size_t c = 0; c < size; c++){ + push_back(x[c]); + } +} +template +void CircularBuffer::operator=(const CircularBuffer& x){ + if (this == &x){ + return; + } + CircularBuffer tmp(x); + *this = std::move(tmp); +} + +template +CircularBuffer::CircularBuffer() + : m_capacity(0) + , m_front(0) + , m_back(0) + , m_ptr(nullptr) +{} +template +CircularBuffer::CircularBuffer(size_t capacity) + : m_capacity(capacity) + , m_front(0) + , m_back(0) + , m_ptr(nullptr) +{ + if (capacity == 0){ + return; + } + m_ptr = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); + if (m_ptr == nullptr){ + throw std::bad_alloc(); + } +} + +template +void CircularBuffer::clear() noexcept{ + while (m_back > m_front){ + pop_front(); + } +} + + +template +const Object& CircularBuffer::front() const{ + return m_ptr[m_front]; +} +template +Object& CircularBuffer::front(){ + return m_ptr[m_front]; +} +template +const Object& CircularBuffer::operator[](size_t index) const{ + index += m_front; + if (index >= m_capacity){ + index -= m_capacity; + } + return m_ptr[index]; +} +template +Object& CircularBuffer::operator[](size_t index){ + index += m_front; + if (index >= m_capacity){ + index -= m_capacity; + } + return m_ptr[index]; +} + +template +template +Object& CircularBuffer::push_back(Args&&... args){ + if (m_back - m_front >= m_capacity){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to push while full."); + } + size_t back = m_back; + if (back >= m_capacity){ + back -= m_capacity; + } + new (m_ptr + back) Object(std::forward(args)...); + m_back++; + return m_ptr[back]; +} +template +template +Object* CircularBuffer::try_push_back(Args&&... args){ + if (m_back - m_front >= m_capacity){ + return nullptr; + } + size_t back = m_back; + if (back >= m_capacity){ + back -= m_capacity; + } + new (m_ptr + back) Object(std::forward(args)...); + m_back++; + return &m_ptr[back]; +} + +template +void CircularBuffer::pop_front(){ + if (m_front == m_back){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "CircularBuffer: Attempted to pop while empty."); + } + size_t front = m_front; + m_ptr[front].~Object(); + front++; + size_t diff = front >= m_capacity ? m_capacity : 0; + m_front = front - diff; + m_back -= diff; +} + + + + + + + +} +#endif diff --git a/Common/Cpp/Containers/DllSafeString.h b/Common/Cpp/Containers/DllSafeString.h index f5b5528bdd..3911bce10d 100644 --- a/Common/Cpp/Containers/DllSafeString.h +++ b/Common/Cpp/Containers/DllSafeString.h @@ -1,109 +1,109 @@ -/* DLL Safe String - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DllSafeString_H -#define PokemonAutomation_DllSafeString_H - -#include -#include -#include - -namespace PokemonAutomation{ - - -class DllSafeString{ -public: - // Rule of 5 - ~DllSafeString(){ clear(); } - DllSafeString(const DllSafeString&) = delete; - void operator=(const DllSafeString&) = delete; - DllSafeString(DllSafeString&& x) - : m_ptr(x.m_ptr) - , m_size(x.m_size) - , m_deleter(x.m_deleter) - { - x.m_ptr = nullptr; - x.m_size = 0; - x.m_deleter = nullptr; - } - void operator=(DllSafeString&& x){ - clear(); - m_ptr = x.m_ptr; - m_size = x.m_size; - m_deleter = x.m_deleter; - x.m_ptr = nullptr; - x.m_size = 0; - x.m_deleter = nullptr; - } - - -public: - DllSafeString() - : m_ptr(nullptr) - , m_size(0) - , m_deleter(nullptr) - {} - DllSafeString(const char* str) - : DllSafeString(std::string(str)) - {} - DllSafeString(const std::string& str) - : m_ptr(new char[str.size()]) - , m_size(str.size()) - , m_deleter(&deleter) - { - memcpy(m_ptr, str.c_str(), str.size()); - } - void clear(){ - if (m_ptr != nullptr){ - m_deleter(m_ptr); - m_size = 0; - m_deleter = nullptr; - } - } - - -public: - operator std::string() const{ - return std::string(m_ptr, m_size); - } - const char* c_str() const{ - return m_ptr; - } - bool empty() const{ - return m_size == 0; - } - size_t size() const{ - return m_size; - } - - char& operator[](size_t index){ - return m_ptr[index]; - } - char operator[](size_t index) const{ - return m_ptr[index]; - } - - friend std::basic_ostream& operator<<(std::basic_ostream& os, const DllSafeString& str){ - return os << str.c_str(); - } - - -private: - static void deleter(char* ptr){ - delete[] ptr; - } - - -private: - char* m_ptr; - size_t m_size; - void (*m_deleter)(char*); -}; - - - -} -#endif +/* DLL Safe String + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DllSafeString_H +#define PokemonAutomation_DllSafeString_H + +#include +#include +#include + +namespace PokemonAutomation{ + + +class DllSafeString{ +public: + // Rule of 5 + ~DllSafeString(){ clear(); } + DllSafeString(const DllSafeString&) = delete; + void operator=(const DllSafeString&) = delete; + DllSafeString(DllSafeString&& x) + : m_ptr(x.m_ptr) + , m_size(x.m_size) + , m_deleter(x.m_deleter) + { + x.m_ptr = nullptr; + x.m_size = 0; + x.m_deleter = nullptr; + } + void operator=(DllSafeString&& x){ + clear(); + m_ptr = x.m_ptr; + m_size = x.m_size; + m_deleter = x.m_deleter; + x.m_ptr = nullptr; + x.m_size = 0; + x.m_deleter = nullptr; + } + + +public: + DllSafeString() + : m_ptr(nullptr) + , m_size(0) + , m_deleter(nullptr) + {} + DllSafeString(const char* str) + : DllSafeString(std::string(str)) + {} + DllSafeString(const std::string& str) + : m_ptr(new char[str.size()]) + , m_size(str.size()) + , m_deleter(&deleter) + { + memcpy(m_ptr, str.c_str(), str.size()); + } + void clear(){ + if (m_ptr != nullptr){ + m_deleter(m_ptr); + m_size = 0; + m_deleter = nullptr; + } + } + + +public: + operator std::string() const{ + return std::string(m_ptr, m_size); + } + const char* c_str() const{ + return m_ptr; + } + bool empty() const{ + return m_size == 0; + } + size_t size() const{ + return m_size; + } + + char& operator[](size_t index){ + return m_ptr[index]; + } + char operator[](size_t index) const{ + return m_ptr[index]; + } + + friend std::basic_ostream& operator<<(std::basic_ostream& os, const DllSafeString& str){ + return os << str.c_str(); + } + + +private: + static void deleter(char* ptr){ + delete[] ptr; + } + + +private: + char* m_ptr; + size_t m_size; + void (*m_deleter)(char*); +}; + + + +} +#endif diff --git a/Common/Cpp/Containers/FixedLimitVector.h b/Common/Cpp/Containers/FixedLimitVector.h index acfdfe2e4b..b13f1990a3 100644 --- a/Common/Cpp/Containers/FixedLimitVector.h +++ b/Common/Cpp/Containers/FixedLimitVector.h @@ -1,107 +1,107 @@ -/* Fixed Limit Vector - * - * From: https://github.com/PokemonAutomation/ - * - * A non-copyable, non-movable vector whose buffer cannot be resized. - * It supports emplace_back() and pop_back(). All elements are unchanged - * through either operation unless it's the one being popped by pop_back(). - * - * There are no requirements of the elements. They need not be copyable nor - * movable since they will stay in place. - * - * - * This file will compile with an imcomplete type for headers. But - * you need to include "FixedLimitVector.tpp" to really use it. - * - */ - -#ifndef PokemonAutomation_FixedLimitVector_H -#define PokemonAutomation_FixedLimitVector_H - -#include - -namespace PokemonAutomation{ - - -template -class FixedLimitVector{ -public: - ~FixedLimitVector(); - FixedLimitVector(const FixedLimitVector&) = delete; - void operator=(const FixedLimitVector&) = delete; - FixedLimitVector(FixedLimitVector&& x); - void operator=(FixedLimitVector&& x); - -public: - FixedLimitVector(); - FixedLimitVector(size_t capacity); - - void reset(); - void reset(size_t capacity); - -public: - size_t size() const{ return m_size; } - size_t capacity() const{ return m_capacity; } - - const Object& operator[](size_t index) const{ return m_data[index]; } - Object& operator[](size_t index) { return m_data[index]; } - const Object& back() const{ return m_data[m_size - 1]; } - Object& back() { return m_data[m_size - 1]; } - - template - bool emplace_back(Args&&... args); - void pop_back(); - - const Object* begin() const{ return m_data; } - Object* begin() { return m_data; }; - const Object* end() const{ return m_data + m_size; } - Object* end() { return m_data + m_size; } - - const Object* data() const{ return m_data; } - Object* data() { return m_data; }; - -private: - Object* m_data; - size_t m_size; - size_t m_capacity; -}; - - - - - -// Implementations - -template -FixedLimitVector::FixedLimitVector(FixedLimitVector&& x) - : m_data(x.m_data) - , m_size(x.m_size) - , m_capacity(x.m_capacity) -{ - x.m_data = nullptr; - x.m_size = 0; - x.m_capacity = 0; -} -template -void FixedLimitVector::operator=(FixedLimitVector&& x){ - reset(); - m_data = x.m_data; - m_size = x.m_size; - m_capacity = x.m_capacity; - x.m_data = nullptr; - x.m_size = 0; - x.m_capacity = 0; -} - -template -FixedLimitVector::FixedLimitVector() - : m_data(nullptr) - , m_size(0) - , m_capacity(0) -{} - - - - -} -#endif +/* Fixed Limit Vector + * + * From: https://github.com/PokemonAutomation/ + * + * A non-copyable, non-movable vector whose buffer cannot be resized. + * It supports emplace_back() and pop_back(). All elements are unchanged + * through either operation unless it's the one being popped by pop_back(). + * + * There are no requirements of the elements. They need not be copyable nor + * movable since they will stay in place. + * + * + * This file will compile with an imcomplete type for headers. But + * you need to include "FixedLimitVector.tpp" to really use it. + * + */ + +#ifndef PokemonAutomation_FixedLimitVector_H +#define PokemonAutomation_FixedLimitVector_H + +#include + +namespace PokemonAutomation{ + + +template +class FixedLimitVector{ +public: + ~FixedLimitVector(); + FixedLimitVector(const FixedLimitVector&) = delete; + void operator=(const FixedLimitVector&) = delete; + FixedLimitVector(FixedLimitVector&& x); + void operator=(FixedLimitVector&& x); + +public: + FixedLimitVector(); + FixedLimitVector(size_t capacity); + + void reset(); + void reset(size_t capacity); + +public: + size_t size() const{ return m_size; } + size_t capacity() const{ return m_capacity; } + + const Object& operator[](size_t index) const{ return m_data[index]; } + Object& operator[](size_t index) { return m_data[index]; } + const Object& back() const{ return m_data[m_size - 1]; } + Object& back() { return m_data[m_size - 1]; } + + template + bool emplace_back(Args&&... args); + void pop_back(); + + const Object* begin() const{ return m_data; } + Object* begin() { return m_data; }; + const Object* end() const{ return m_data + m_size; } + Object* end() { return m_data + m_size; } + + const Object* data() const{ return m_data; } + Object* data() { return m_data; }; + +private: + Object* m_data; + size_t m_size; + size_t m_capacity; +}; + + + + + +// Implementations + +template +FixedLimitVector::FixedLimitVector(FixedLimitVector&& x) + : m_data(x.m_data) + , m_size(x.m_size) + , m_capacity(x.m_capacity) +{ + x.m_data = nullptr; + x.m_size = 0; + x.m_capacity = 0; +} +template +void FixedLimitVector::operator=(FixedLimitVector&& x){ + reset(); + m_data = x.m_data; + m_size = x.m_size; + m_capacity = x.m_capacity; + x.m_data = nullptr; + x.m_size = 0; + x.m_capacity = 0; +} + +template +FixedLimitVector::FixedLimitVector() + : m_data(nullptr) + , m_size(0) + , m_capacity(0) +{} + + + + +} +#endif diff --git a/Common/Cpp/Containers/FixedLimitVector.tpp b/Common/Cpp/Containers/FixedLimitVector.tpp index 3eac2f6b4d..4359b50515 100644 --- a/Common/Cpp/Containers/FixedLimitVector.tpp +++ b/Common/Cpp/Containers/FixedLimitVector.tpp @@ -1,92 +1,92 @@ -/* Fixed Limit Vector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_FixedLimitVector_IPP -#define PokemonAutomation_FixedLimitVector_IPP - -#include -#include -#include "AlignedMalloc.h" -#include "FixedLimitVector.h" - -namespace PokemonAutomation{ - - -// Rule of 5 - -template -FixedLimitVector::~FixedLimitVector(){ - while (m_size > 0){ - pop_back(); - } - aligned_free(m_data); -} - - - -// Constructors - -template -FixedLimitVector::FixedLimitVector(size_t capacity) - : m_size(0) - , m_capacity(capacity) -{ - m_data = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); - if (m_data == nullptr){ - throw std::bad_alloc(); - } -} - -template -void FixedLimitVector::reset(){ - while (m_size > 0){ - pop_back(); - } - aligned_free(m_data); - m_data = nullptr; - m_capacity = 0; -} -template -void FixedLimitVector::reset(size_t capacity){ - Object* data = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); - if (data == nullptr){ - throw std::bad_alloc(); - } - while (m_size > 0){ - pop_back(); - } - aligned_free(m_data); - m_data = data; - m_capacity = capacity; -} - - - -// Functions - -template -template -bool FixedLimitVector::emplace_back(Args&&... args){ - if (m_size < m_capacity){ - new (m_data + m_size) Object(std::forward(args)...); - m_size++; - return true; - }else{ - return false; - } -} -template -void FixedLimitVector::pop_back(){ - m_data[--m_size].~Object(); -} - - - - - - -} -#endif +/* Fixed Limit Vector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_FixedLimitVector_IPP +#define PokemonAutomation_FixedLimitVector_IPP + +#include +#include +#include "AlignedMalloc.h" +#include "FixedLimitVector.h" + +namespace PokemonAutomation{ + + +// Rule of 5 + +template +FixedLimitVector::~FixedLimitVector(){ + while (m_size > 0){ + pop_back(); + } + aligned_free(m_data); +} + + + +// Constructors + +template +FixedLimitVector::FixedLimitVector(size_t capacity) + : m_size(0) + , m_capacity(capacity) +{ + m_data = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); + if (m_data == nullptr){ + throw std::bad_alloc(); + } +} + +template +void FixedLimitVector::reset(){ + while (m_size > 0){ + pop_back(); + } + aligned_free(m_data); + m_data = nullptr; + m_capacity = 0; +} +template +void FixedLimitVector::reset(size_t capacity){ + Object* data = (Object*)aligned_malloc(capacity * sizeof(Object), alignof(Object)); + if (data == nullptr){ + throw std::bad_alloc(); + } + while (m_size > 0){ + pop_back(); + } + aligned_free(m_data); + m_data = data; + m_capacity = capacity; +} + + + +// Functions + +template +template +bool FixedLimitVector::emplace_back(Args&&... args){ + if (m_size < m_capacity){ + new (m_data + m_size) Object(std::forward(args)...); + m_size++; + return true; + }else{ + return false; + } +} +template +void FixedLimitVector::pop_back(){ + m_data[--m_size].~Object(); +} + + + + + + +} +#endif diff --git a/Common/Cpp/Containers/Pimpl.h b/Common/Cpp/Containers/Pimpl.h index c72158cb42..fc6fcd0786 100644 --- a/Common/Cpp/Containers/Pimpl.h +++ b/Common/Cpp/Containers/Pimpl.h @@ -1,83 +1,83 @@ -/* Pimpl - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pimpl_H -#define PokemonAutomation_Pimpl_H - -namespace PokemonAutomation{ - - -enum PimplConstruct{ - CONSTRUCT_TOKEN -}; - - -template -class Pimpl{ -public: - ~Pimpl(); - Pimpl(Pimpl&& x) noexcept; - void operator=(Pimpl&& x) noexcept; - Pimpl(const Pimpl& x); - void operator=(const Pimpl& x); - - -public: - Pimpl() = default; - - template - Pimpl(PimplConstruct, Args&&... args); - - void clear(); - - template - void reset(Args&&... args); - - -public: - operator bool() const{ return m_ptr != nullptr; } - - operator const Type&() const{ return *m_ptr; } - operator Type&() { return *m_ptr; } - - const Type& operator*() const { return *m_ptr; } - Type& operator*() { return *m_ptr; } - - const Type* operator->() const { return m_ptr; } - Type* operator->() { return m_ptr; } - - const Type* get() const { return m_ptr; } - Type* get() { return m_ptr; } - - -private: - Type* m_ptr = nullptr; -}; - - - -template -Pimpl::Pimpl(Pimpl&& x) noexcept - : m_ptr(x.m_ptr) -{ - x.m_ptr = nullptr; -} -template -void Pimpl::operator=(Pimpl&& x) noexcept{ - if (this == &x){ - return; - } - delete m_ptr; - m_ptr = x.m_ptr; - x.m_ptr = nullptr; -} - - - - - -} -#endif +/* Pimpl + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pimpl_H +#define PokemonAutomation_Pimpl_H + +namespace PokemonAutomation{ + + +enum PimplConstruct{ + CONSTRUCT_TOKEN +}; + + +template +class Pimpl{ +public: + ~Pimpl(); + Pimpl(Pimpl&& x) noexcept; + void operator=(Pimpl&& x) noexcept; + Pimpl(const Pimpl& x); + void operator=(const Pimpl& x); + + +public: + Pimpl() = default; + + template + Pimpl(PimplConstruct, Args&&... args); + + void clear(); + + template + void reset(Args&&... args); + + +public: + operator bool() const{ return m_ptr != nullptr; } + + operator const Type&() const{ return *m_ptr; } + operator Type&() { return *m_ptr; } + + const Type& operator*() const { return *m_ptr; } + Type& operator*() { return *m_ptr; } + + const Type* operator->() const { return m_ptr; } + Type* operator->() { return m_ptr; } + + const Type* get() const { return m_ptr; } + Type* get() { return m_ptr; } + + +private: + Type* m_ptr = nullptr; +}; + + + +template +Pimpl::Pimpl(Pimpl&& x) noexcept + : m_ptr(x.m_ptr) +{ + x.m_ptr = nullptr; +} +template +void Pimpl::operator=(Pimpl&& x) noexcept{ + if (this == &x){ + return; + } + delete m_ptr; + m_ptr = x.m_ptr; + x.m_ptr = nullptr; +} + + + + + +} +#endif diff --git a/Common/Cpp/Containers/Pimpl.tpp b/Common/Cpp/Containers/Pimpl.tpp index ad58e8b80a..0830d5ad1f 100644 --- a/Common/Cpp/Containers/Pimpl.tpp +++ b/Common/Cpp/Containers/Pimpl.tpp @@ -1,63 +1,63 @@ -/* Pimpl - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_Pimpl_TPP -#define PokemonAutomation_Pimpl_TPP - -#include -#include -#include "Pimpl.h" - -namespace PokemonAutomation{ - - - -template -Pimpl::~Pimpl(){ - delete m_ptr; -} - -template -Pimpl::Pimpl(const Pimpl& x) - : m_ptr(new Type(*x.m_ptr)) -{} -template -void Pimpl::operator=(const Pimpl& x){ - if (this == &x){ - return; - } - Type* copy = new Type(*x.m_ptr); - Type* ptr = m_ptr; - m_ptr = copy; - delete ptr; -} - -template -template -Pimpl::Pimpl(PimplConstruct, Args&&... args) - : m_ptr(new Type(std::forward(args)...)) -{} - - -template -void Pimpl::clear(){ - delete m_ptr; - m_ptr = nullptr; -} - -template -template -void Pimpl::reset(Args&&... args){ - Type* ptr = new Type(std::forward(args)...); - delete m_ptr; - m_ptr = ptr; -} - - - - -} -#endif +/* Pimpl + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_Pimpl_TPP +#define PokemonAutomation_Pimpl_TPP + +#include +#include +#include "Pimpl.h" + +namespace PokemonAutomation{ + + + +template +Pimpl::~Pimpl(){ + delete m_ptr; +} + +template +Pimpl::Pimpl(const Pimpl& x) + : m_ptr(new Type(*x.m_ptr)) +{} +template +void Pimpl::operator=(const Pimpl& x){ + if (this == &x){ + return; + } + Type* copy = new Type(*x.m_ptr); + Type* ptr = m_ptr; + m_ptr = copy; + delete ptr; +} + +template +template +Pimpl::Pimpl(PimplConstruct, Args&&... args) + : m_ptr(new Type(std::forward(args)...)) +{} + + +template +void Pimpl::clear(){ + delete m_ptr; + m_ptr = nullptr; +} + +template +template +void Pimpl::reset(Args&&... args){ + Type* ptr = new Type(std::forward(args)...); + delete m_ptr; + m_ptr = ptr; +} + + + + +} +#endif diff --git a/Common/Cpp/Containers/SparseArray.cpp b/Common/Cpp/Containers/SparseArray.cpp index 317a4cbfa7..454a5db61f 100644 --- a/Common/Cpp/Containers/SparseArray.cpp +++ b/Common/Cpp/Containers/SparseArray.cpp @@ -1,199 +1,199 @@ -/* Sparse Array - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "SparseArray.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void SparseArray::write(size_t address, size_t bytes, const void* data){ - if (m_data.empty()){ - m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(address), - std::forward_as_tuple((char*)data, (char*)data + bytes) - ); - return; - } - - // Below bottom. - size_t top = address + bytes; - size_t lowest = m_data.begin()->first; - if (top < lowest){ - m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(address), - std::forward_as_tuple((char*)data, (char*)data + bytes) - ); - return; - } - - // Above top. - size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); - if (highest < address){ - m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(address), - std::forward_as_tuple((char*)data, (char*)data + bytes) - ); - return; - } - - // Get the first and last blocks that will be affected. - auto lower = m_data.upper_bound(address); - if (lower != m_data.begin()){ - --lower; - } - if (lower->first + lower->second.size() < address){ - ++lower; - } - auto upper = m_data.lower_bound(top); - if (upper != m_data.begin()){ - --upper; - } - - lowest = lower->first; - highest = upper->first + upper->second.size(); - if (lower == upper && lowest <= address && top <= highest){ - // Completely inside. - memcpy(lower->second.data() + address - lowest, data, bytes); - return; - } - - lowest = std::min(lowest, address); - highest = std::max(highest, top); - - std::string block(highest - lowest, 0); - - // Copy in the partial blocks. - bool one_block = lower == upper; - { - size_t shift = lower->first - lowest; - memcpy( - block.data() + shift, - lower->second.data(), - lower->second.size() - ); - } - if (!one_block){ - size_t shift = highest - upper->first - upper->second.size(); - memcpy( - block.data() + block.size() - upper->second.size() - shift, - upper->second.data(), - upper->second.size() - ); - } - -// cout << "lower = " << lower->first << endl; -// cout << "upper = " << upper->first << endl; -// cout << "lowest = " << lowest << endl; -// cout << "highest = " << highest << endl; - - // Copy the newly written block. - memcpy(block.data() + address - lowest, data, bytes); - -// cout << std::string((char*)block.data(), block.size()) << endl; - - // Insert into table. - if (lower->first == lowest){ -// cout << "replace" << endl; - lower->second = std::move(block); - ++lower; - }else{ -// cout << "add" << endl; - auto iter = m_data.emplace( - std::piecewise_construct, - std::forward_as_tuple(lowest), - std::forward_as_tuple(std::move(block)) - ).first; - m_data.erase(lower); - ++iter; - lower = iter; - } - - // Remove all the blocks that it touched. - if (!one_block){ - while (lower != upper){ - lower = m_data.erase(lower); - } - m_data.erase(lower); - } -} -void SparseArray::read(size_t address, size_t bytes, void* data) const{ - if (m_data.empty()){ - return; - } - - // Below bottom. - size_t top = address + bytes; - size_t lowest = m_data.begin()->first; - if (top < lowest){ - return; - } - - // Above top. - size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); - if (highest < address){ - return; - } - - auto lower = m_data.upper_bound(address); - if (lower != m_data.begin()){ - --lower; - } - - while (lower != m_data.end() && bytes > 0){ - size_t block = lower->first; - if (block >= top){ - break; - } - -// cout << "bytes = " << bytes << endl; -// cout << "address = " << address << endl; -// cout << "block = " << block << endl; - - const char* ptr = lower->second.data(); - size_t len = lower->second.size(); - - if (block < address){ -// cout << "block is before" << endl; - size_t shift = address - block; - block = address; - ptr += shift; - len -= shift; // Cannot go negative since it's guaranteed to overlap with region. - } - if (block > address){ -// cout << "block is later" << endl; - size_t shift = block - address; -// cout << "shift = " << shift << endl; - address = block; - data = (char*)data + shift; - bytes -= shift; // Cannot go negative since it's guaranteed to overlap with block. - } - - len = std::min(len, bytes); - -// cout << "len = " << len << endl; - - memcpy(data, ptr, len); - data = (char*)data + len; - address += len; - bytes -= len; - ++lower; - } - -} - - - - -} +/* Sparse Array + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "SparseArray.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void SparseArray::write(size_t address, size_t bytes, const void* data){ + if (m_data.empty()){ + m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(address), + std::forward_as_tuple((char*)data, (char*)data + bytes) + ); + return; + } + + // Below bottom. + size_t top = address + bytes; + size_t lowest = m_data.begin()->first; + if (top < lowest){ + m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(address), + std::forward_as_tuple((char*)data, (char*)data + bytes) + ); + return; + } + + // Above top. + size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); + if (highest < address){ + m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(address), + std::forward_as_tuple((char*)data, (char*)data + bytes) + ); + return; + } + + // Get the first and last blocks that will be affected. + auto lower = m_data.upper_bound(address); + if (lower != m_data.begin()){ + --lower; + } + if (lower->first + lower->second.size() < address){ + ++lower; + } + auto upper = m_data.lower_bound(top); + if (upper != m_data.begin()){ + --upper; + } + + lowest = lower->first; + highest = upper->first + upper->second.size(); + if (lower == upper && lowest <= address && top <= highest){ + // Completely inside. + memcpy(lower->second.data() + address - lowest, data, bytes); + return; + } + + lowest = std::min(lowest, address); + highest = std::max(highest, top); + + std::string block(highest - lowest, 0); + + // Copy in the partial blocks. + bool one_block = lower == upper; + { + size_t shift = lower->first - lowest; + memcpy( + block.data() + shift, + lower->second.data(), + lower->second.size() + ); + } + if (!one_block){ + size_t shift = highest - upper->first - upper->second.size(); + memcpy( + block.data() + block.size() - upper->second.size() - shift, + upper->second.data(), + upper->second.size() + ); + } + +// cout << "lower = " << lower->first << endl; +// cout << "upper = " << upper->first << endl; +// cout << "lowest = " << lowest << endl; +// cout << "highest = " << highest << endl; + + // Copy the newly written block. + memcpy(block.data() + address - lowest, data, bytes); + +// cout << std::string((char*)block.data(), block.size()) << endl; + + // Insert into table. + if (lower->first == lowest){ +// cout << "replace" << endl; + lower->second = std::move(block); + ++lower; + }else{ +// cout << "add" << endl; + auto iter = m_data.emplace( + std::piecewise_construct, + std::forward_as_tuple(lowest), + std::forward_as_tuple(std::move(block)) + ).first; + m_data.erase(lower); + ++iter; + lower = iter; + } + + // Remove all the blocks that it touched. + if (!one_block){ + while (lower != upper){ + lower = m_data.erase(lower); + } + m_data.erase(lower); + } +} +void SparseArray::read(size_t address, size_t bytes, void* data) const{ + if (m_data.empty()){ + return; + } + + // Below bottom. + size_t top = address + bytes; + size_t lowest = m_data.begin()->first; + if (top < lowest){ + return; + } + + // Above top. + size_t highest = m_data.rbegin()->first + m_data.rbegin()->second.size(); + if (highest < address){ + return; + } + + auto lower = m_data.upper_bound(address); + if (lower != m_data.begin()){ + --lower; + } + + while (lower != m_data.end() && bytes > 0){ + size_t block = lower->first; + if (block >= top){ + break; + } + +// cout << "bytes = " << bytes << endl; +// cout << "address = " << address << endl; +// cout << "block = " << block << endl; + + const char* ptr = lower->second.data(); + size_t len = lower->second.size(); + + if (block < address){ +// cout << "block is before" << endl; + size_t shift = address - block; + block = address; + ptr += shift; + len -= shift; // Cannot go negative since it's guaranteed to overlap with region. + } + if (block > address){ +// cout << "block is later" << endl; + size_t shift = block - address; +// cout << "shift = " << shift << endl; + address = block; + data = (char*)data + shift; + bytes -= shift; // Cannot go negative since it's guaranteed to overlap with block. + } + + len = std::min(len, bytes); + +// cout << "len = " << len << endl; + + memcpy(data, ptr, len); + data = (char*)data + len; + address += len; + bytes -= len; + ++lower; + } + +} + + + + +} diff --git a/Common/Cpp/Containers/SparseArray.h b/Common/Cpp/Containers/SparseArray.h index 045f453f04..26cec21912 100644 --- a/Common/Cpp/Containers/SparseArray.h +++ b/Common/Cpp/Containers/SparseArray.h @@ -1,68 +1,68 @@ -/* Sparse Array - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SparseArray_H -#define PokemonAutomation_SparseArray_H - -#include -#include -#include - -namespace PokemonAutomation{ - - -struct SparseArrayBlock{ - size_t address; - std::string data; - - SparseArrayBlock(size_t p_address, const char* str) - : address(p_address) - , data(str, str + strlen(str)) - {} - SparseArrayBlock(size_t p_address, std::initializer_list p_data) - : address(p_address) - , data(p_data) - {} -}; - - -class SparseArray{ -public: - SparseArray() = default; - SparseArray(std::initializer_list list){ - for (auto& item : list){ - write(item.address, item.data.size(), item.data.data()); - } - } - - void write(size_t address, size_t bytes, const void* data); - void read(size_t address, size_t bytes, void* data) const; - -#if 1 - std::string dump() const{ - std::string ret; - for (const auto& item : m_data){ - ret += "{"; - ret += std::to_string(item.first); - ret += " : "; - ret += std::to_string(item.first + item.second.size()); - ret += "} = "; - ret += item.second; - ret += "\n"; - } - return ret; - } -#endif - -private: - std::map m_data; -}; - - - - -} -#endif +/* Sparse Array + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SparseArray_H +#define PokemonAutomation_SparseArray_H + +#include +#include +#include + +namespace PokemonAutomation{ + + +struct SparseArrayBlock{ + size_t address; + std::string data; + + SparseArrayBlock(size_t p_address, const char* str) + : address(p_address) + , data(str, str + strlen(str)) + {} + SparseArrayBlock(size_t p_address, std::initializer_list p_data) + : address(p_address) + , data(p_data) + {} +}; + + +class SparseArray{ +public: + SparseArray() = default; + SparseArray(std::initializer_list list){ + for (auto& item : list){ + write(item.address, item.data.size(), item.data.data()); + } + } + + void write(size_t address, size_t bytes, const void* data); + void read(size_t address, size_t bytes, void* data) const; + +#if 1 + std::string dump() const{ + std::string ret; + for (const auto& item : m_data){ + ret += "{"; + ret += std::to_string(item.first); + ret += " : "; + ret += std::to_string(item.first + item.second.size()); + ret += "} = "; + ret += item.second; + ret += "\n"; + } + return ret; + } +#endif + +private: + std::map m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/CpuId/CpuId.cpp b/Common/Cpp/CpuId/CpuId.cpp index ea6c5d522b..a07e44a82c 100644 --- a/Common/Cpp/CpuId/CpuId.cpp +++ b/Common/Cpp/CpuId/CpuId.cpp @@ -1,52 +1,52 @@ -/* CPU ID - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CpuId.h" - -#if 0 -#elif defined PokemonAutomation_CpuId_x86_H -#include "CpuId_x86.tpp" -#elif defined PokemonAutomation_CpuId_arm64_H -#include "CpuId_arm64.tpp" -#else - -namespace PokemonAutomation{ - -const char* PA_ARCH_STRING = "Unknown"; - -const CPU_Features CPU_CAPABILITY_NATIVE; - -const std::vector& AVAILABLE_CAPABILITIES(){ - static const std::vector LIST{ - {"none", "Nothing (C++ Only)", CPU_CAPABILITY_NATIVE, true}, - }; - return LIST; -} - -} - -#endif - -namespace PokemonAutomation{ - -CPU_Features CPU_CAPABILITY_CURRENT = CPU_CAPABILITY_NATIVE; - -IntegerEnumDropdownDatabase make_CAPABILITIES_DATABASE(){ - IntegerEnumDropdownDatabase ret; - size_t c = 0; - for (const CpuCapabilityOption& item : AVAILABLE_CAPABILITIES()){ - ret.add(c, item.slug, item.display, item.available); - c++; - } - return ret; -}; -const IntegerEnumDropdownDatabase& CAPABILITIES_DATABASE(){ - static const IntegerEnumDropdownDatabase database = make_CAPABILITIES_DATABASE(); - return database; -} - -} - +/* CPU ID + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CpuId.h" + +#if 0 +#elif defined PokemonAutomation_CpuId_x86_H +#include "CpuId_x86.tpp" +#elif defined PokemonAutomation_CpuId_arm64_H +#include "CpuId_arm64.tpp" +#else + +namespace PokemonAutomation{ + +const char* PA_ARCH_STRING = "Unknown"; + +const CPU_Features CPU_CAPABILITY_NATIVE; + +const std::vector& AVAILABLE_CAPABILITIES(){ + static const std::vector LIST{ + {"none", "Nothing (C++ Only)", CPU_CAPABILITY_NATIVE, true}, + }; + return LIST; +} + +} + +#endif + +namespace PokemonAutomation{ + +CPU_Features CPU_CAPABILITY_CURRENT = CPU_CAPABILITY_NATIVE; + +IntegerEnumDropdownDatabase make_CAPABILITIES_DATABASE(){ + IntegerEnumDropdownDatabase ret; + size_t c = 0; + for (const CpuCapabilityOption& item : AVAILABLE_CAPABILITIES()){ + ret.add(c, item.slug, item.display, item.available); + c++; + } + return ret; +}; +const IntegerEnumDropdownDatabase& CAPABILITIES_DATABASE(){ + static const IntegerEnumDropdownDatabase database = make_CAPABILITIES_DATABASE(); + return database; +} + +} + diff --git a/Common/Cpp/CpuId/CpuId.h b/Common/Cpp/CpuId/CpuId.h index cb45dcaa7a..55d1bb9f3d 100644 --- a/Common/Cpp/CpuId/CpuId.h +++ b/Common/Cpp/CpuId/CpuId.h @@ -1,75 +1,75 @@ -/* CPU ID - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CpuId_H -#define PokemonAutomation_CpuId_H - -#include "Common/Cpp/Options/EnumDropdownDatabase.h" - -#if 0 -#elif _M_IX86 || _M_X64 || __i386__ || __x86_64__ -#define PA_ARCH_x86 1 -#include "CpuId_x86.h" -#elif __arm64__ -#define PA_ARCH_arm64 1 -#include "CpuId_arm64.h" -#else -namespace PokemonAutomation{ - struct CPU_Features{}; -} -#endif - - -#include - -namespace PokemonAutomation{ - -// CPU arch name, for Intel CPU it is "x64" or x86 -extern const char* PA_ARCH_STRING; - -// The running machine's CPU capability -extern const CPU_Features CPU_CAPABILITY_NATIVE; -// The CPU capability used to determine what Pokemon Automation code to run. -// e.g. to run with or without Intel AVX instructions. -// This capability is intialized to be the same as `CPU_CAPABILITY_NATIVE`. -// The reason we define two capability, native and current, is that at runtime -// we can chagne the values in current to test the code that runs with weaker capability. -extern CPU_Features CPU_CAPABILITY_CURRENT; - -// Struct for a set of CPU features. -// This struct is used to build UI that lets user set different CPU features -// to test the code that runs with weaker capability. -// For example, on a machine with Intel AVX and AVX2 instructions, there can be three -// `CpuCapabilityOption`, representing non-AVX (pure C++), AVX and AVX2 implementations -// of some computation. The user can choose between those options to test the implementations, -// profile and compare their performance. -struct CpuCapabilityOption{ - const char* slug; - const char* display; - const CPU_Features& features; - bool available; - - CpuCapabilityOption( - const char* p_slug, const char* p_display, - const CPU_Features& p_features, bool p_available - ) - : slug(p_slug) - , display(p_display) - , features(p_features) - , available(p_available) - {} -}; - -// The available CPU instruction choices. See comments of `CpuCapabilityOption` for more details. -const std::vector& AVAILABLE_CAPABILITIES(); -// An enum database to select `CpuCapabilityOption`. -// This database is built by `AVAILABLE_CAPABILITIES()`, used for UI of choosing CPU instructions. -const IntegerEnumDropdownDatabase& CAPABILITIES_DATABASE(); - - - -} -#endif +/* CPU ID + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CpuId_H +#define PokemonAutomation_CpuId_H + +#include "Common/Cpp/Options/EnumDropdownDatabase.h" + +#if 0 +#elif _M_IX86 || _M_X64 || __i386__ || __x86_64__ +#define PA_ARCH_x86 1 +#include "CpuId_x86.h" +#elif __arm64__ +#define PA_ARCH_arm64 1 +#include "CpuId_arm64.h" +#else +namespace PokemonAutomation{ + struct CPU_Features{}; +} +#endif + + +#include + +namespace PokemonAutomation{ + +// CPU arch name, for Intel CPU it is "x64" or x86 +extern const char* PA_ARCH_STRING; + +// The running machine's CPU capability +extern const CPU_Features CPU_CAPABILITY_NATIVE; +// The CPU capability used to determine what Pokemon Automation code to run. +// e.g. to run with or without Intel AVX instructions. +// This capability is intialized to be the same as `CPU_CAPABILITY_NATIVE`. +// The reason we define two capability, native and current, is that at runtime +// we can chagne the values in current to test the code that runs with weaker capability. +extern CPU_Features CPU_CAPABILITY_CURRENT; + +// Struct for a set of CPU features. +// This struct is used to build UI that lets user set different CPU features +// to test the code that runs with weaker capability. +// For example, on a machine with Intel AVX and AVX2 instructions, there can be three +// `CpuCapabilityOption`, representing non-AVX (pure C++), AVX and AVX2 implementations +// of some computation. The user can choose between those options to test the implementations, +// profile and compare their performance. +struct CpuCapabilityOption{ + const char* slug; + const char* display; + const CPU_Features& features; + bool available; + + CpuCapabilityOption( + const char* p_slug, const char* p_display, + const CPU_Features& p_features, bool p_available + ) + : slug(p_slug) + , display(p_display) + , features(p_features) + , available(p_available) + {} +}; + +// The available CPU instruction choices. See comments of `CpuCapabilityOption` for more details. +const std::vector& AVAILABLE_CAPABILITIES(); +// An enum database to select `CpuCapabilityOption`. +// This database is built by `AVAILABLE_CAPABILITIES()`, used for UI of choosing CPU instructions. +const IntegerEnumDropdownDatabase& CAPABILITIES_DATABASE(); + + + +} +#endif diff --git a/Common/Cpp/CpuId/CpuId_arm64.h b/Common/Cpp/CpuId/CpuId_arm64.h index e382bf5c74..268055bf57 100644 --- a/Common/Cpp/CpuId/CpuId_arm64.h +++ b/Common/Cpp/CpuId/CpuId_arm64.h @@ -1,28 +1,28 @@ -/* CPU ID (arm64) - * - * From: https://github.com/PokemonAutomation/ - * - * - */ - -#ifndef PokemonAutomation_CpuId_arm64_H -#define PokemonAutomation_CpuId_arm64_H - -#include - -namespace PokemonAutomation{ - -// Currently we assume Apple M1 as the only arm64 we support, so not much CPU feature variety. -struct CPU_Features{ - CPU_Features& set_to_current(); - - bool OK_M1 = false; -}; - - - - - - -} -#endif +/* CPU ID (arm64) + * + * From: https://github.com/PokemonAutomation/ + * + * + */ + +#ifndef PokemonAutomation_CpuId_arm64_H +#define PokemonAutomation_CpuId_arm64_H + +#include + +namespace PokemonAutomation{ + +// Currently we assume Apple M1 as the only arm64 we support, so not much CPU feature variety. +struct CPU_Features{ + CPU_Features& set_to_current(); + + bool OK_M1 = false; +}; + + + + + + +} +#endif diff --git a/Common/Cpp/CpuId/CpuId_arm64.tpp b/Common/Cpp/CpuId/CpuId_arm64.tpp index a897a16a42..379adbb5cf 100644 --- a/Common/Cpp/CpuId/CpuId_arm64.tpp +++ b/Common/Cpp/CpuId/CpuId_arm64.tpp @@ -1,66 +1,66 @@ -/* CPU ID (arm64) - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include -#include - -#include "CpuId.h" - -namespace PokemonAutomation{ - -const char* PA_ARCH_STRING = "arm64"; - - -uint64_t detect_NEON() -{ - // https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_instruction_set_characteristics - uint64_t available = 0; - size_t size = sizeof(available); - - if (sysctlbyname("hw.optional.AdvSIMD", &available, &size, NULL, 0) < 0) - { - perror("sysctl"); - } - return available; -} - -CPU_Features& CPU_Features::set_to_current(){ - OK_M1 = detect_NEON() > 0; - return *this; -} - -CPU_Features make_M1(){ - CPU_Features ret; - - ret.OK_M1 = true; - return ret; -} - -// The CPU feature we use in the program will be C++ only, no SIMD -const CPU_Features CPU_CAPABILITY_NOTHING; - -// The CPU feature we use in the program will be those from Apple M1 architecture, including Arm NEON SIMD instruction set -const CPU_Features CPU_CAPABILITY_M1 = make_M1(); - -// We assume all kinds of Apple M1 chips has the same SIMD support. -// So they should all be the same CPU feature set as M1. -const CPU_Features CPU_CAPABILITY_NATIVE = CPU_Features().set_to_current(); - -const std::vector& AVAILABLE_CAPABILITIES(){ - static const std::vector LIST{ - {"none", "Nothing (C++ Only)", CPU_CAPABILITY_NOTHING, true}, - {"m1-neon", "Apple M1 (NEON)", CPU_CAPABILITY_M1, CPU_CAPABILITY_NATIVE.OK_M1}, - }; - return LIST; -} - - - - -} - - +/* CPU ID (arm64) + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include +#include + +#include "CpuId.h" + +namespace PokemonAutomation{ + +const char* PA_ARCH_STRING = "arm64"; + + +uint64_t detect_NEON() +{ + // https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_instruction_set_characteristics + uint64_t available = 0; + size_t size = sizeof(available); + + if (sysctlbyname("hw.optional.AdvSIMD", &available, &size, NULL, 0) < 0) + { + perror("sysctl"); + } + return available; +} + +CPU_Features& CPU_Features::set_to_current(){ + OK_M1 = detect_NEON() > 0; + return *this; +} + +CPU_Features make_M1(){ + CPU_Features ret; + + ret.OK_M1 = true; + return ret; +} + +// The CPU feature we use in the program will be C++ only, no SIMD +const CPU_Features CPU_CAPABILITY_NOTHING; + +// The CPU feature we use in the program will be those from Apple M1 architecture, including Arm NEON SIMD instruction set +const CPU_Features CPU_CAPABILITY_M1 = make_M1(); + +// We assume all kinds of Apple M1 chips has the same SIMD support. +// So they should all be the same CPU feature set as M1. +const CPU_Features CPU_CAPABILITY_NATIVE = CPU_Features().set_to_current(); + +const std::vector& AVAILABLE_CAPABILITIES(){ + static const std::vector LIST{ + {"none", "Nothing (C++ Only)", CPU_CAPABILITY_NOTHING, true}, + {"m1-neon", "Apple M1 (NEON)", CPU_CAPABILITY_M1, CPU_CAPABILITY_NATIVE.OK_M1}, + }; + return LIST; +} + + + + +} + + diff --git a/Common/Cpp/CpuId/CpuId_x86.h b/Common/Cpp/CpuId/CpuId_x86.h index 2d022c7011..a9b0e582a7 100644 --- a/Common/Cpp/CpuId/CpuId_x86.h +++ b/Common/Cpp/CpuId/CpuId_x86.h @@ -1,116 +1,116 @@ -/* CPU ID (x86) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CpuId_x86_H -#define PokemonAutomation_CpuId_x86_H - -#include - -namespace PokemonAutomation{ - -void x86_cpuid(uint32_t eabcdx[4], uint32_t eax, uint32_t ecx); - - -struct CPU_Features{ - CPU_Features& set_to_current(); - - // CPU Compatibility - bool OK_08_Nehalem = false; - bool OK_13_Haswell = false; - bool OK_17_Skylake = false; - bool OK_19_IceLake = false; - - void update_CPU_compatibility(); - - - // OS Features - bool OS_AVX = false; - bool OS_AVX512 = false; - - // Misc. - bool HW_MMX = false; - bool HW_x64 = false; - bool HW_ABM = false; - bool HW_RDRAND = false; - bool HW_RDSEED = false; - bool HW_BMI1 = false; - bool HW_BMI2 = false; - bool HW_ADX = false; - bool HW_MPX = false; - bool HW_PREFETCHW = false; - bool HW_PREFETCHWT1 = false; - bool HW_RDPID = false; - - // SIMD: 128-bit - bool HW_SSE = false; - bool HW_SSE2 = false; - bool HW_SSE3 = false; - bool HW_SSSE3 = false; - bool HW_SSE41 = false; - bool HW_SSE42 = false; - bool HW_SSE4a = false; - bool HW_AES = false; - bool HW_SHA = false; - - // SIMD: 256-bit - bool HW_AVX = false; - bool HW_XOP = false; - bool HW_FMA3 = false; - bool HW_FMA4 = false; - bool HW_AVX2 = false; - - // SIMD: 512-bit - bool HW_AVX512_F = false; - bool HW_AVX512_CD = false; - - // Knights Landing - bool HW_AVX512_PF = false; - bool HW_AVX512_ER = false; - - // Skylake Purley - bool HW_AVX512_VL = false; - bool HW_AVX512_BW = false; - bool HW_AVX512_DQ = false; - - // Cannon Lake - bool HW_AVX512_IFMA = false; - bool HW_AVX512_VBMI = false; - - // Knights Mill - bool HW_AVX512_VPOPCNTDQ = false; - bool HW_AVX512_4FMAPS = false; - bool HW_AVX512_4VNNIW = false; - - // Cascade Lake - bool HW_AVX512_VNNI = false; - - // Cooper Lake - bool HW_AVX512_BF16 = false; - - // Ice Lake - bool HW_AVX512_VBMI2 = false; - bool HW_GFNI = false; - bool HW_VAES = false; - bool HW_AVX512_VPCLMUL = false; - bool HW_AVX512_BITALG = false; - -}; - - -extern const CPU_Features CPU_CAPABILITY_NOTHING; -extern const CPU_Features CPU_CAPABILITY_09_NEHALEM; -extern const CPU_Features CPU_CAPABILITY_13_Haswell; -extern const CPU_Features CPU_CAPABILITY_17_Skylake; -extern const CPU_Features CPU_CAPABILITY_19_IceLake; - - - - - - - -} -#endif +/* CPU ID (x86) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CpuId_x86_H +#define PokemonAutomation_CpuId_x86_H + +#include + +namespace PokemonAutomation{ + +void x86_cpuid(uint32_t eabcdx[4], uint32_t eax, uint32_t ecx); + + +struct CPU_Features{ + CPU_Features& set_to_current(); + + // CPU Compatibility + bool OK_08_Nehalem = false; + bool OK_13_Haswell = false; + bool OK_17_Skylake = false; + bool OK_19_IceLake = false; + + void update_CPU_compatibility(); + + + // OS Features + bool OS_AVX = false; + bool OS_AVX512 = false; + + // Misc. + bool HW_MMX = false; + bool HW_x64 = false; + bool HW_ABM = false; + bool HW_RDRAND = false; + bool HW_RDSEED = false; + bool HW_BMI1 = false; + bool HW_BMI2 = false; + bool HW_ADX = false; + bool HW_MPX = false; + bool HW_PREFETCHW = false; + bool HW_PREFETCHWT1 = false; + bool HW_RDPID = false; + + // SIMD: 128-bit + bool HW_SSE = false; + bool HW_SSE2 = false; + bool HW_SSE3 = false; + bool HW_SSSE3 = false; + bool HW_SSE41 = false; + bool HW_SSE42 = false; + bool HW_SSE4a = false; + bool HW_AES = false; + bool HW_SHA = false; + + // SIMD: 256-bit + bool HW_AVX = false; + bool HW_XOP = false; + bool HW_FMA3 = false; + bool HW_FMA4 = false; + bool HW_AVX2 = false; + + // SIMD: 512-bit + bool HW_AVX512_F = false; + bool HW_AVX512_CD = false; + + // Knights Landing + bool HW_AVX512_PF = false; + bool HW_AVX512_ER = false; + + // Skylake Purley + bool HW_AVX512_VL = false; + bool HW_AVX512_BW = false; + bool HW_AVX512_DQ = false; + + // Cannon Lake + bool HW_AVX512_IFMA = false; + bool HW_AVX512_VBMI = false; + + // Knights Mill + bool HW_AVX512_VPOPCNTDQ = false; + bool HW_AVX512_4FMAPS = false; + bool HW_AVX512_4VNNIW = false; + + // Cascade Lake + bool HW_AVX512_VNNI = false; + + // Cooper Lake + bool HW_AVX512_BF16 = false; + + // Ice Lake + bool HW_AVX512_VBMI2 = false; + bool HW_GFNI = false; + bool HW_VAES = false; + bool HW_AVX512_VPCLMUL = false; + bool HW_AVX512_BITALG = false; + +}; + + +extern const CPU_Features CPU_CAPABILITY_NOTHING; +extern const CPU_Features CPU_CAPABILITY_09_NEHALEM; +extern const CPU_Features CPU_CAPABILITY_13_Haswell; +extern const CPU_Features CPU_CAPABILITY_17_Skylake; +extern const CPU_Features CPU_CAPABILITY_19_IceLake; + + + + + + + +} +#endif diff --git a/Common/Cpp/CpuId/CpuId_x86.tpp b/Common/Cpp/CpuId/CpuId_x86.tpp index 5aaa48e13a..590b436ddd 100644 --- a/Common/Cpp/CpuId/CpuId_x86.tpp +++ b/Common/Cpp/CpuId/CpuId_x86.tpp @@ -1,381 +1,381 @@ -/* CPU ID (x86) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include - -#ifdef _WIN32 -#include -#include -#endif - -#if __GNUC__ -#ifndef cpuid_H -#define cpuid_H -#include -#endif -#endif - -#include "CpuId.h" - -namespace PokemonAutomation{ - -#if _M_X64 || __x86_64__ -const char* PA_ARCH_STRING = "x64"; -#else -const char* PA_ARCH_STRING = "x86"; -#endif - - -#if __GNUC__ -void x86_cpuid(uint32_t eabcdx[4], uint32_t eax, uint32_t ecx){ - __cpuid_count(eax, ecx, eabcdx[0], eabcdx[1], eabcdx[2], eabcdx[3]); -} -uint64_t xgetbv(unsigned int index){ - uint32_t eax, edx; - __asm__ volatile ("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index)); - return ((uint64_t)edx << 32) | eax; -} -#define _XCR_XFEATURE_ENABLED_MASK 0 -#else -void x86_cpuid(uint32_t eabcdx[4], uint32_t eax, uint32_t ecx){ - int out[4]; - __cpuidex(out, eax, ecx); - eabcdx[0] = out[0]; - eabcdx[1] = out[1]; - eabcdx[2] = out[2]; - eabcdx[3] = out[3]; -} -__int64 xgetbv(unsigned int x){ - return _xgetbv(x); -} -#endif - - -bool detect_OS_AVX(){ - // Copied from: http://stackoverflow.com/a/22521619/922184 - - bool avxSupported = false; - - uint32_t cpuInfo[4]; - x86_cpuid(cpuInfo, 1, 0); - - bool osUsesXSAVE_XRSTORE = (cpuInfo[2] & (1 << 27)) != 0; - bool cpuAVXSuport = (cpuInfo[2] & (1 << 28)) != 0; - - if (osUsesXSAVE_XRSTORE && cpuAVXSuport) - { - uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); - avxSupported = (xcrFeatureMask & 0x6) == 0x6; - } - - return avxSupported; -} -bool detect_OS_AVX512(){ - if (!detect_OS_AVX()) - return false; - - uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); - return (xcrFeatureMask & 0xe6) == 0xe6; -} - - -CPU_Features& CPU_Features::set_to_current(){ - // OS Features - OS_AVX = detect_OS_AVX(); - OS_AVX512 = detect_OS_AVX512(); - - uint32_t info[4]; - x86_cpuid(info, 0, 0); - uint32_t nIds = info[0]; - - x86_cpuid(info, 0x80000000, 0); - uint32_t nExIds = info[0]; - - // Detect Features - if (nIds >= 0x00000001){ - x86_cpuid(info, 0x00000001, 0); - HW_MMX = (info[3] & ((int)1 << 23)) != 0; - HW_SSE = (info[3] & ((int)1 << 25)) != 0; - HW_SSE2 = (info[3] & ((int)1 << 26)) != 0; - HW_SSE3 = (info[2] & ((int)1 << 0)) != 0; - - HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0; - HW_SSE41 = (info[2] & ((int)1 << 19)) != 0; - HW_SSE42 = (info[2] & ((int)1 << 20)) != 0; - HW_AES = (info[2] & ((int)1 << 25)) != 0; - - HW_AVX = (info[2] & ((int)1 << 28)) != 0; - HW_FMA3 = (info[2] & ((int)1 << 12)) != 0; - - HW_RDRAND = (info[2] & ((int)1 << 30)) != 0; - } - if (nIds >= 0x00000007){ - x86_cpuid(info, 0x00000007, 0); - HW_AVX2 = (info[1] & ((int)1 << 5)) != 0; - - HW_BMI1 = (info[1] & ((int)1 << 3)) != 0; - HW_BMI2 = (info[1] & ((int)1 << 8)) != 0; - HW_ADX = (info[1] & ((int)1 << 19)) != 0; - HW_MPX = (info[1] & ((int)1 << 14)) != 0; - HW_SHA = (info[1] & ((int)1 << 29)) != 0; - HW_RDSEED = (info[1] & ((int)1 << 18)) != 0; - HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0; - HW_RDPID = (info[2] & ((int)1 << 22)) != 0; - - HW_AVX512_F = (info[1] & ((int)1 << 16)) != 0; - HW_AVX512_CD = (info[1] & ((int)1 << 28)) != 0; - HW_AVX512_PF = (info[1] & ((int)1 << 26)) != 0; - HW_AVX512_ER = (info[1] & ((int)1 << 27)) != 0; - - HW_AVX512_VL = (info[1] & ((int)1 << 31)) != 0; - HW_AVX512_BW = (info[1] & ((int)1 << 30)) != 0; - HW_AVX512_DQ = (info[1] & ((int)1 << 17)) != 0; - - HW_AVX512_IFMA = (info[1] & ((int)1 << 21)) != 0; - HW_AVX512_VBMI = (info[2] & ((int)1 << 1)) != 0; - - HW_AVX512_VPOPCNTDQ = (info[2] & ((int)1 << 14)) != 0; - HW_AVX512_4FMAPS = (info[3] & ((int)1 << 2)) != 0; - HW_AVX512_4VNNIW = (info[3] & ((int)1 << 3)) != 0; - - HW_AVX512_VNNI = (info[2] & ((int)1 << 11)) != 0; - - HW_AVX512_VBMI2 = (info[2] & ((int)1 << 6)) != 0; - HW_GFNI = (info[2] & ((int)1 << 8)) != 0; - HW_VAES = (info[2] & ((int)1 << 9)) != 0; - HW_AVX512_VPCLMUL = (info[2] & ((int)1 << 10)) != 0; - HW_AVX512_BITALG = (info[2] & ((int)1 << 12)) != 0; - - - x86_cpuid(info, 0x00000007, 1); - HW_AVX512_BF16 = (info[0] & ((int)1 << 5)) != 0; - - } - if (nExIds >= 0x80000001){ - x86_cpuid(info, 0x80000001, 0); - HW_x64 = (info[3] & ((int)1 << 29)) != 0; - HW_ABM = (info[2] & ((int)1 << 5)) != 0; - HW_SSE4a = (info[2] & ((int)1 << 6)) != 0; - HW_PREFETCHW = (info[2] & ((int)1 << 8)) != 0; - HW_XOP = (info[2] & ((int)1 << 11)) != 0; - HW_FMA4 = (info[2] & ((int)1 << 16)) != 0; - } - - update_CPU_compatibility(); - return *this; -} - -void CPU_Features::update_CPU_compatibility(){ - OK_08_Nehalem = true; - OK_08_Nehalem &= HW_SSE42; - - OK_13_Haswell = OK_08_Nehalem; - OK_13_Haswell &= OS_AVX; - OK_13_Haswell &= HW_BMI2; - OK_13_Haswell &= HW_FMA3; - OK_13_Haswell &= HW_AVX2; - - OK_17_Skylake = OK_13_Haswell; - OK_17_Skylake &= HW_AVX512_F; - OK_17_Skylake &= HW_AVX512_CD; - OK_17_Skylake &= HW_AVX512_VL; - OK_17_Skylake &= HW_AVX512_BW; - OK_17_Skylake &= HW_AVX512_DQ; - - OK_19_IceLake = OK_17_Skylake; - OK_19_IceLake &= HW_AVX512_IFMA; - OK_19_IceLake &= HW_AVX512_VBMI; - OK_19_IceLake &= HW_AVX512_VPOPCNTDQ; - OK_19_IceLake &= HW_AVX512_VNNI; - OK_19_IceLake &= HW_AVX512_VBMI2; - OK_19_IceLake &= HW_GFNI; - OK_19_IceLake &= HW_VAES; - OK_19_IceLake &= HW_AVX512_VPCLMUL; - OK_19_IceLake &= HW_AVX512_BITALG; -} - - -const CPU_Features CPU_CAPABILITY_NATIVE = CPU_Features().set_to_current(); - - - -const CPU_Features CPU_CAPABILITY_NOTHING; - -CPU_Features make_09_Nehalem(){ - CPU_Features ret; - - ret.HW_MMX = true; - ret.HW_x64 = true; - - ret.HW_SSE = true; - ret.HW_SSE2 = true; - ret.HW_SSE3 = true; - ret.HW_SSSE3 = true; - ret.HW_SSE41 = true; - ret.HW_SSE42 = true; - - ret.update_CPU_compatibility(); - return ret; -} -const CPU_Features CPU_CAPABILITY_09_NEHALEM = make_09_Nehalem(); - -CPU_Features make_13_Haswell(){ - CPU_Features ret; - - ret.OS_AVX = CPU_CAPABILITY_NATIVE.OS_AVX; - - ret.HW_MMX = true; - ret.HW_x64 = true; - ret.HW_ABM = true; - ret.HW_RDRAND = true; - ret.HW_BMI1 = true; - ret.HW_BMI2 = true; - - ret.HW_SSE = true; - ret.HW_SSE2 = true; - ret.HW_SSE3 = true; - ret.HW_SSSE3 = true; - ret.HW_SSE41 = true; - ret.HW_SSE42 = true; - - ret.HW_AVX = true; - ret.HW_FMA3 = true; - ret.HW_AVX2 = true; - - ret.update_CPU_compatibility(); - return ret; -} -const CPU_Features CPU_CAPABILITY_13_Haswell = make_13_Haswell(); - -CPU_Features make_17_Skylake(){ - CPU_Features ret; - - ret.OS_AVX = CPU_CAPABILITY_NATIVE.OS_AVX; - ret.OS_AVX512 = CPU_CAPABILITY_NATIVE.OS_AVX512; - - ret.HW_MMX = true; - ret.HW_x64 = true; - ret.HW_ABM = true; - ret.HW_RDRAND = true; - ret.HW_RDSEED = true; - ret.HW_BMI1 = true; - ret.HW_BMI2 = true; - ret.HW_ADX = true; - ret.HW_PREFETCHW = true; - - ret.HW_SSE = true; - ret.HW_SSE2 = true; - ret.HW_SSE3 = true; - ret.HW_SSSE3 = true; - ret.HW_SSE41 = true; - ret.HW_SSE42 = true; - ret.HW_AES = true; - - ret.HW_AVX = true; - ret.HW_FMA3 = true; - ret.HW_AVX2 = true; - - ret.HW_AVX512_F = true; - ret.HW_AVX512_CD = true; - ret.HW_AVX512_VL = true; - ret.HW_AVX512_BW = true; - ret.HW_AVX512_DQ = true; - - ret.update_CPU_compatibility(); - return ret; -} -const CPU_Features CPU_CAPABILITY_17_Skylake = make_17_Skylake(); - -CPU_Features make_19_IceLake(){ - CPU_Features ret; - - ret.OS_AVX = CPU_CAPABILITY_NATIVE.OS_AVX; - ret.OS_AVX512 = CPU_CAPABILITY_NATIVE.OS_AVX512; - - ret.HW_MMX = true; - ret.HW_x64 = true; - ret.HW_ABM = true; - ret.HW_RDRAND = true; - ret.HW_RDSEED = true; - ret.HW_BMI1 = true; - ret.HW_BMI2 = true; - ret.HW_ADX = true; - ret.HW_PREFETCHW = true; - - ret.HW_SSE = true; - ret.HW_SSE2 = true; - ret.HW_SSE3 = true; - ret.HW_SSSE3 = true; - ret.HW_SSE41 = true; - ret.HW_SSE42 = true; - ret.HW_AES = true; - - ret.HW_AVX = true; - ret.HW_FMA3 = true; - ret.HW_AVX2 = true; - - ret.HW_AVX512_F = true; - ret.HW_AVX512_CD = true; - ret.HW_AVX512_VL = true; - ret.HW_AVX512_BW = true; - ret.HW_AVX512_DQ = true; - ret.HW_AVX512_IFMA = true; - ret.HW_AVX512_VBMI = true; - ret.HW_AVX512_VPOPCNTDQ = true; - ret.HW_AVX512_VNNI = true; - ret.HW_AVX512_VBMI2 = true; - ret.HW_GFNI = true; - ret.HW_VAES = true; - ret.HW_AVX512_VPCLMUL = true; - ret.HW_AVX512_BITALG = true; - - ret.update_CPU_compatibility(); - return ret; -} -const CPU_Features CPU_CAPABILITY_19_IceLake = make_19_IceLake(); - -const std::vector& AVAILABLE_CAPABILITIES(){ - static const std::vector LIST{ - { - "none", "Nothing (C++ Only)", - CPU_CAPABILITY_NOTHING, true - }, -#ifdef PA_AutoDispatch_x64_08_Nehalem - { - "nehalem-sse4.2", "Intel Nehalem (x64 SSE4.2)", - CPU_CAPABILITY_09_NEHALEM, CPU_CAPABILITY_NATIVE.OK_08_Nehalem - }, -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - { - "haswell-avx2", "Intel Haswell (x64 AVX2)", - CPU_CAPABILITY_13_Haswell, CPU_CAPABILITY_NATIVE.OK_13_Haswell - }, -#endif -#ifdef PA_AutoDispatch_x64_17_Skylake - { - "skylake-avx512", "Intel Skylake (x64 AVX512)", - CPU_CAPABILITY_17_Skylake, CPU_CAPABILITY_NATIVE.OK_17_Skylake - }, -#endif -#ifdef PA_AutoDispatch_x64_19_IceLake - { - "icelake-avx512gf", "Intel Ice Lake (x64 AVX512-GF)", - CPU_CAPABILITY_19_IceLake, CPU_CAPABILITY_NATIVE.OK_19_IceLake - }, -#endif - }; - return LIST; -} - - - - - - -} - - +/* CPU ID (x86) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include + +#ifdef _WIN32 +#include +#include +#endif + +#if __GNUC__ +#ifndef cpuid_H +#define cpuid_H +#include +#endif +#endif + +#include "CpuId.h" + +namespace PokemonAutomation{ + +#if _M_X64 || __x86_64__ +const char* PA_ARCH_STRING = "x64"; +#else +const char* PA_ARCH_STRING = "x86"; +#endif + + +#if __GNUC__ +void x86_cpuid(uint32_t eabcdx[4], uint32_t eax, uint32_t ecx){ + __cpuid_count(eax, ecx, eabcdx[0], eabcdx[1], eabcdx[2], eabcdx[3]); +} +uint64_t xgetbv(unsigned int index){ + uint32_t eax, edx; + __asm__ volatile ("xgetbv" : "=a"(eax), "=d"(edx) : "c"(index)); + return ((uint64_t)edx << 32) | eax; +} +#define _XCR_XFEATURE_ENABLED_MASK 0 +#else +void x86_cpuid(uint32_t eabcdx[4], uint32_t eax, uint32_t ecx){ + int out[4]; + __cpuidex(out, eax, ecx); + eabcdx[0] = out[0]; + eabcdx[1] = out[1]; + eabcdx[2] = out[2]; + eabcdx[3] = out[3]; +} +__int64 xgetbv(unsigned int x){ + return _xgetbv(x); +} +#endif + + +bool detect_OS_AVX(){ + // Copied from: http://stackoverflow.com/a/22521619/922184 + + bool avxSupported = false; + + uint32_t cpuInfo[4]; + x86_cpuid(cpuInfo, 1, 0); + + bool osUsesXSAVE_XRSTORE = (cpuInfo[2] & (1 << 27)) != 0; + bool cpuAVXSuport = (cpuInfo[2] & (1 << 28)) != 0; + + if (osUsesXSAVE_XRSTORE && cpuAVXSuport) + { + uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); + avxSupported = (xcrFeatureMask & 0x6) == 0x6; + } + + return avxSupported; +} +bool detect_OS_AVX512(){ + if (!detect_OS_AVX()) + return false; + + uint64_t xcrFeatureMask = xgetbv(_XCR_XFEATURE_ENABLED_MASK); + return (xcrFeatureMask & 0xe6) == 0xe6; +} + + +CPU_Features& CPU_Features::set_to_current(){ + // OS Features + OS_AVX = detect_OS_AVX(); + OS_AVX512 = detect_OS_AVX512(); + + uint32_t info[4]; + x86_cpuid(info, 0, 0); + uint32_t nIds = info[0]; + + x86_cpuid(info, 0x80000000, 0); + uint32_t nExIds = info[0]; + + // Detect Features + if (nIds >= 0x00000001){ + x86_cpuid(info, 0x00000001, 0); + HW_MMX = (info[3] & ((int)1 << 23)) != 0; + HW_SSE = (info[3] & ((int)1 << 25)) != 0; + HW_SSE2 = (info[3] & ((int)1 << 26)) != 0; + HW_SSE3 = (info[2] & ((int)1 << 0)) != 0; + + HW_SSSE3 = (info[2] & ((int)1 << 9)) != 0; + HW_SSE41 = (info[2] & ((int)1 << 19)) != 0; + HW_SSE42 = (info[2] & ((int)1 << 20)) != 0; + HW_AES = (info[2] & ((int)1 << 25)) != 0; + + HW_AVX = (info[2] & ((int)1 << 28)) != 0; + HW_FMA3 = (info[2] & ((int)1 << 12)) != 0; + + HW_RDRAND = (info[2] & ((int)1 << 30)) != 0; + } + if (nIds >= 0x00000007){ + x86_cpuid(info, 0x00000007, 0); + HW_AVX2 = (info[1] & ((int)1 << 5)) != 0; + + HW_BMI1 = (info[1] & ((int)1 << 3)) != 0; + HW_BMI2 = (info[1] & ((int)1 << 8)) != 0; + HW_ADX = (info[1] & ((int)1 << 19)) != 0; + HW_MPX = (info[1] & ((int)1 << 14)) != 0; + HW_SHA = (info[1] & ((int)1 << 29)) != 0; + HW_RDSEED = (info[1] & ((int)1 << 18)) != 0; + HW_PREFETCHWT1 = (info[2] & ((int)1 << 0)) != 0; + HW_RDPID = (info[2] & ((int)1 << 22)) != 0; + + HW_AVX512_F = (info[1] & ((int)1 << 16)) != 0; + HW_AVX512_CD = (info[1] & ((int)1 << 28)) != 0; + HW_AVX512_PF = (info[1] & ((int)1 << 26)) != 0; + HW_AVX512_ER = (info[1] & ((int)1 << 27)) != 0; + + HW_AVX512_VL = (info[1] & ((int)1 << 31)) != 0; + HW_AVX512_BW = (info[1] & ((int)1 << 30)) != 0; + HW_AVX512_DQ = (info[1] & ((int)1 << 17)) != 0; + + HW_AVX512_IFMA = (info[1] & ((int)1 << 21)) != 0; + HW_AVX512_VBMI = (info[2] & ((int)1 << 1)) != 0; + + HW_AVX512_VPOPCNTDQ = (info[2] & ((int)1 << 14)) != 0; + HW_AVX512_4FMAPS = (info[3] & ((int)1 << 2)) != 0; + HW_AVX512_4VNNIW = (info[3] & ((int)1 << 3)) != 0; + + HW_AVX512_VNNI = (info[2] & ((int)1 << 11)) != 0; + + HW_AVX512_VBMI2 = (info[2] & ((int)1 << 6)) != 0; + HW_GFNI = (info[2] & ((int)1 << 8)) != 0; + HW_VAES = (info[2] & ((int)1 << 9)) != 0; + HW_AVX512_VPCLMUL = (info[2] & ((int)1 << 10)) != 0; + HW_AVX512_BITALG = (info[2] & ((int)1 << 12)) != 0; + + + x86_cpuid(info, 0x00000007, 1); + HW_AVX512_BF16 = (info[0] & ((int)1 << 5)) != 0; + + } + if (nExIds >= 0x80000001){ + x86_cpuid(info, 0x80000001, 0); + HW_x64 = (info[3] & ((int)1 << 29)) != 0; + HW_ABM = (info[2] & ((int)1 << 5)) != 0; + HW_SSE4a = (info[2] & ((int)1 << 6)) != 0; + HW_PREFETCHW = (info[2] & ((int)1 << 8)) != 0; + HW_XOP = (info[2] & ((int)1 << 11)) != 0; + HW_FMA4 = (info[2] & ((int)1 << 16)) != 0; + } + + update_CPU_compatibility(); + return *this; +} + +void CPU_Features::update_CPU_compatibility(){ + OK_08_Nehalem = true; + OK_08_Nehalem &= HW_SSE42; + + OK_13_Haswell = OK_08_Nehalem; + OK_13_Haswell &= OS_AVX; + OK_13_Haswell &= HW_BMI2; + OK_13_Haswell &= HW_FMA3; + OK_13_Haswell &= HW_AVX2; + + OK_17_Skylake = OK_13_Haswell; + OK_17_Skylake &= HW_AVX512_F; + OK_17_Skylake &= HW_AVX512_CD; + OK_17_Skylake &= HW_AVX512_VL; + OK_17_Skylake &= HW_AVX512_BW; + OK_17_Skylake &= HW_AVX512_DQ; + + OK_19_IceLake = OK_17_Skylake; + OK_19_IceLake &= HW_AVX512_IFMA; + OK_19_IceLake &= HW_AVX512_VBMI; + OK_19_IceLake &= HW_AVX512_VPOPCNTDQ; + OK_19_IceLake &= HW_AVX512_VNNI; + OK_19_IceLake &= HW_AVX512_VBMI2; + OK_19_IceLake &= HW_GFNI; + OK_19_IceLake &= HW_VAES; + OK_19_IceLake &= HW_AVX512_VPCLMUL; + OK_19_IceLake &= HW_AVX512_BITALG; +} + + +const CPU_Features CPU_CAPABILITY_NATIVE = CPU_Features().set_to_current(); + + + +const CPU_Features CPU_CAPABILITY_NOTHING; + +CPU_Features make_09_Nehalem(){ + CPU_Features ret; + + ret.HW_MMX = true; + ret.HW_x64 = true; + + ret.HW_SSE = true; + ret.HW_SSE2 = true; + ret.HW_SSE3 = true; + ret.HW_SSSE3 = true; + ret.HW_SSE41 = true; + ret.HW_SSE42 = true; + + ret.update_CPU_compatibility(); + return ret; +} +const CPU_Features CPU_CAPABILITY_09_NEHALEM = make_09_Nehalem(); + +CPU_Features make_13_Haswell(){ + CPU_Features ret; + + ret.OS_AVX = CPU_CAPABILITY_NATIVE.OS_AVX; + + ret.HW_MMX = true; + ret.HW_x64 = true; + ret.HW_ABM = true; + ret.HW_RDRAND = true; + ret.HW_BMI1 = true; + ret.HW_BMI2 = true; + + ret.HW_SSE = true; + ret.HW_SSE2 = true; + ret.HW_SSE3 = true; + ret.HW_SSSE3 = true; + ret.HW_SSE41 = true; + ret.HW_SSE42 = true; + + ret.HW_AVX = true; + ret.HW_FMA3 = true; + ret.HW_AVX2 = true; + + ret.update_CPU_compatibility(); + return ret; +} +const CPU_Features CPU_CAPABILITY_13_Haswell = make_13_Haswell(); + +CPU_Features make_17_Skylake(){ + CPU_Features ret; + + ret.OS_AVX = CPU_CAPABILITY_NATIVE.OS_AVX; + ret.OS_AVX512 = CPU_CAPABILITY_NATIVE.OS_AVX512; + + ret.HW_MMX = true; + ret.HW_x64 = true; + ret.HW_ABM = true; + ret.HW_RDRAND = true; + ret.HW_RDSEED = true; + ret.HW_BMI1 = true; + ret.HW_BMI2 = true; + ret.HW_ADX = true; + ret.HW_PREFETCHW = true; + + ret.HW_SSE = true; + ret.HW_SSE2 = true; + ret.HW_SSE3 = true; + ret.HW_SSSE3 = true; + ret.HW_SSE41 = true; + ret.HW_SSE42 = true; + ret.HW_AES = true; + + ret.HW_AVX = true; + ret.HW_FMA3 = true; + ret.HW_AVX2 = true; + + ret.HW_AVX512_F = true; + ret.HW_AVX512_CD = true; + ret.HW_AVX512_VL = true; + ret.HW_AVX512_BW = true; + ret.HW_AVX512_DQ = true; + + ret.update_CPU_compatibility(); + return ret; +} +const CPU_Features CPU_CAPABILITY_17_Skylake = make_17_Skylake(); + +CPU_Features make_19_IceLake(){ + CPU_Features ret; + + ret.OS_AVX = CPU_CAPABILITY_NATIVE.OS_AVX; + ret.OS_AVX512 = CPU_CAPABILITY_NATIVE.OS_AVX512; + + ret.HW_MMX = true; + ret.HW_x64 = true; + ret.HW_ABM = true; + ret.HW_RDRAND = true; + ret.HW_RDSEED = true; + ret.HW_BMI1 = true; + ret.HW_BMI2 = true; + ret.HW_ADX = true; + ret.HW_PREFETCHW = true; + + ret.HW_SSE = true; + ret.HW_SSE2 = true; + ret.HW_SSE3 = true; + ret.HW_SSSE3 = true; + ret.HW_SSE41 = true; + ret.HW_SSE42 = true; + ret.HW_AES = true; + + ret.HW_AVX = true; + ret.HW_FMA3 = true; + ret.HW_AVX2 = true; + + ret.HW_AVX512_F = true; + ret.HW_AVX512_CD = true; + ret.HW_AVX512_VL = true; + ret.HW_AVX512_BW = true; + ret.HW_AVX512_DQ = true; + ret.HW_AVX512_IFMA = true; + ret.HW_AVX512_VBMI = true; + ret.HW_AVX512_VPOPCNTDQ = true; + ret.HW_AVX512_VNNI = true; + ret.HW_AVX512_VBMI2 = true; + ret.HW_GFNI = true; + ret.HW_VAES = true; + ret.HW_AVX512_VPCLMUL = true; + ret.HW_AVX512_BITALG = true; + + ret.update_CPU_compatibility(); + return ret; +} +const CPU_Features CPU_CAPABILITY_19_IceLake = make_19_IceLake(); + +const std::vector& AVAILABLE_CAPABILITIES(){ + static const std::vector LIST{ + { + "none", "Nothing (C++ Only)", + CPU_CAPABILITY_NOTHING, true + }, +#ifdef PA_AutoDispatch_x64_08_Nehalem + { + "nehalem-sse4.2", "Intel Nehalem (x64 SSE4.2)", + CPU_CAPABILITY_09_NEHALEM, CPU_CAPABILITY_NATIVE.OK_08_Nehalem + }, +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + { + "haswell-avx2", "Intel Haswell (x64 AVX2)", + CPU_CAPABILITY_13_Haswell, CPU_CAPABILITY_NATIVE.OK_13_Haswell + }, +#endif +#ifdef PA_AutoDispatch_x64_17_Skylake + { + "skylake-avx512", "Intel Skylake (x64 AVX512)", + CPU_CAPABILITY_17_Skylake, CPU_CAPABILITY_NATIVE.OK_17_Skylake + }, +#endif +#ifdef PA_AutoDispatch_x64_19_IceLake + { + "icelake-avx512gf", "Intel Ice Lake (x64 AVX512-GF)", + CPU_CAPABILITY_19_IceLake, CPU_CAPABILITY_NATIVE.OK_19_IceLake + }, +#endif + }; + return LIST; +} + + + + + + +} + + diff --git a/Common/Cpp/DateTime.h b/Common/Cpp/DateTime.h index 7706d8f0cf..f375a2b349 100644 --- a/Common/Cpp/DateTime.h +++ b/Common/Cpp/DateTime.h @@ -1,48 +1,48 @@ -/* DateTime - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DateTime_H -#define PokemonAutomation_DateTime_H - -#include - -namespace PokemonAutomation{ - - -struct DateTime{ - // Negative means invalid or cannot read. - int16_t year = -1; - int8_t month = -1; - int8_t day = -1; - int8_t hour = -1; - int8_t minute = -1; - int8_t second = -1; - - bool operator<(const DateTime& x) const{ - if (year != x.year) return year < x.year; - if (month != x.month) return month < x.month; - if (day != x.day) return day < x.day; - if (hour != x.hour) return hour < x.hour; - if (minute != x.minute) return minute < x.minute; - if (second != x.second) return second < x.second; - return false; - } - bool operator>(const DateTime& x) const{ - return x < *this; - } - bool operator==(const DateTime& x) const{ - return year == x.year - && month == x.month - && day == x.day - && hour == x.hour - && minute == x.minute - && second == x.second; - } -}; - - -} -#endif +/* DateTime + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DateTime_H +#define PokemonAutomation_DateTime_H + +#include + +namespace PokemonAutomation{ + + +struct DateTime{ + // Negative means invalid or cannot read. + int16_t year = -1; + int8_t month = -1; + int8_t day = -1; + int8_t hour = -1; + int8_t minute = -1; + int8_t second = -1; + + bool operator<(const DateTime& x) const{ + if (year != x.year) return year < x.year; + if (month != x.month) return month < x.month; + if (day != x.day) return day < x.day; + if (hour != x.hour) return hour < x.hour; + if (minute != x.minute) return minute < x.minute; + if (second != x.second) return second < x.second; + return false; + } + bool operator>(const DateTime& x) const{ + return x < *this; + } + bool operator==(const DateTime& x) const{ + return year == x.year + && month == x.month + && day == x.day + && hour == x.hour + && minute == x.minute + && second == x.second; + } +}; + + +} +#endif diff --git a/Common/Cpp/EnumStringMap.h b/Common/Cpp/EnumStringMap.h index 9e24edc861..72b110f324 100644 --- a/Common/Cpp/EnumStringMap.h +++ b/Common/Cpp/EnumStringMap.h @@ -1,70 +1,70 @@ -/* Enum Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_EnumStringMap_H -#define PokemonAutomation_EnumStringMap_H - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - - -template -class EnumStringMap{ -public: - EnumStringMap(std::initializer_list> x) - : m_enum_to_string(std::move(x)) - { - for (const auto& item : m_enum_to_string){ - auto ret = m_string_to_enum.emplace(item.second, item.first); - if (!ret.second){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Duplicate Enum String: " + item.second - ); - } - } - } - - const std::string& get_string(EnumType type) const{ - auto iter = m_enum_to_string.find(type); - if (iter == m_enum_to_string.end()){ - throw ParseException("Invalid Enum: " + std::to_string((uint64_t)type)); - } - return iter->second; - } - EnumType get_enum(const std::string& str) const{ - auto iter = m_string_to_enum.find(str); - if (iter == m_string_to_enum.end()){ - throw ParseException("Invalid Enum String: " + str); - } - return iter->second; - } - EnumType get_enum(const std::string& str, EnumType default_value) const{ - auto iter = m_string_to_enum.find(str); - return iter == m_string_to_enum.end() ? default_value : iter->second; - } - - auto begin() const{ - return m_enum_to_string.begin(); - } - auto end() const{ - return m_enum_to_string.end(); - } - -private: - std::map m_enum_to_string; - std::map m_string_to_enum; -}; - - - -} -#endif +/* Enum Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_EnumStringMap_H +#define PokemonAutomation_EnumStringMap_H + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + + +template +class EnumStringMap{ +public: + EnumStringMap(std::initializer_list> x) + : m_enum_to_string(std::move(x)) + { + for (const auto& item : m_enum_to_string){ + auto ret = m_string_to_enum.emplace(item.second, item.first); + if (!ret.second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Duplicate Enum String: " + item.second + ); + } + } + } + + const std::string& get_string(EnumType type) const{ + auto iter = m_enum_to_string.find(type); + if (iter == m_enum_to_string.end()){ + throw ParseException("Invalid Enum: " + std::to_string((uint64_t)type)); + } + return iter->second; + } + EnumType get_enum(const std::string& str) const{ + auto iter = m_string_to_enum.find(str); + if (iter == m_string_to_enum.end()){ + throw ParseException("Invalid Enum String: " + str); + } + return iter->second; + } + EnumType get_enum(const std::string& str, EnumType default_value) const{ + auto iter = m_string_to_enum.find(str); + return iter == m_string_to_enum.end() ? default_value : iter->second; + } + + auto begin() const{ + return m_enum_to_string.begin(); + } + auto end() const{ + return m_enum_to_string.end(); + } + +private: + std::map m_enum_to_string; + std::map m_string_to_enum; +}; + + + +} +#endif diff --git a/Common/Cpp/EventRateTracker.h b/Common/Cpp/EventRateTracker.h index 3fa284cff1..1195cf1fa6 100644 --- a/Common/Cpp/EventRateTracker.h +++ b/Common/Cpp/EventRateTracker.h @@ -1,124 +1,124 @@ -/* Event Rate Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_EventRateTracker_H -#define PokemonAutomation_EventRateTracker_H - -#include -#include "Time.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -// A class for calculating stuff like frames/second. -class EventRateTracker{ -public: - EventRateTracker(std::chrono::milliseconds window = std::chrono::milliseconds(1000)) - : m_window(window) - {} - - void push_event(WallClock timestamp = current_time()){ - WallClock threshold = timestamp - m_window; - while (!m_history.empty()){ - if (m_history.front() >= threshold){ - break; - } - m_history.pop_front(); - } - m_history.emplace_back(timestamp); - } - - size_t events_in_window() const{ - return m_history.size(); - } - double events_per_second() const{ - if (m_history.size() < 2){ - return 0; - } - if (current_time() > m_history.back() + m_window){ - return 0; - } - auto delta = m_history.back() - m_history.front(); - return (double)(m_history.size() - 1) / std::chrono::duration_cast(delta).count() * 1000000; - } - -private: - std::chrono::milliseconds m_window; - std::deque m_history; -}; - - - -class UtilizationTracker{ -public: - UtilizationTracker(WallClock::duration window = std::chrono::milliseconds(1000)) - : m_window(window) - , m_min_window(window / 2) - , m_running_usage(0) - {} - - void push_event(WallClock::duration usage_since_last, WallClock timestamp = current_time()){ - WallClock threshold = timestamp - m_window; - while (m_history.size() > 1){ - if (m_history.front().timestamp >= threshold){ - break; - } - m_running_usage -= m_history.front().usage; - m_history.pop_front(); - } - m_history.emplace_back(Entry{timestamp, usage_since_last}); - m_running_usage += usage_since_last; - } - void push_idle(){ - m_history.clear(); - m_running_usage = WallClock::duration(0); - } - - size_t events_in_window() const{ - return m_history.size(); - } - WallClock::duration usage_in_window() const{ - return m_running_usage; - } - double utilization() const{ - if (m_history.size() < 2){ - return 0; - } - auto iter = m_history.begin(); - auto delta_time = m_history.back().timestamp - iter->timestamp; - delta_time = std::max(delta_time, m_min_window); - auto usage = m_running_usage - iter->usage; - std::chrono::microseconds time_usec = std::chrono::duration_cast(delta_time); - if (time_usec.count() == 0){ - return 0; - } - std::chrono::microseconds usage_usec = std::chrono::duration_cast(usage); - return (double)usage_usec.count() / time_usec.count(); - } - - -private: - struct Entry{ - WallClock timestamp; - WallClock::duration usage; - }; - - WallClock::duration m_window; - WallClock::duration m_min_window; - - std::deque m_history; - WallClock::duration m_running_usage; -}; - - - - -} -#endif +/* Event Rate Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_EventRateTracker_H +#define PokemonAutomation_EventRateTracker_H + +#include +#include "Time.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +// A class for calculating stuff like frames/second. +class EventRateTracker{ +public: + EventRateTracker(std::chrono::milliseconds window = std::chrono::milliseconds(1000)) + : m_window(window) + {} + + void push_event(WallClock timestamp = current_time()){ + WallClock threshold = timestamp - m_window; + while (!m_history.empty()){ + if (m_history.front() >= threshold){ + break; + } + m_history.pop_front(); + } + m_history.emplace_back(timestamp); + } + + size_t events_in_window() const{ + return m_history.size(); + } + double events_per_second() const{ + if (m_history.size() < 2){ + return 0; + } + if (current_time() > m_history.back() + m_window){ + return 0; + } + auto delta = m_history.back() - m_history.front(); + return (double)(m_history.size() - 1) / std::chrono::duration_cast(delta).count() * 1000000; + } + +private: + std::chrono::milliseconds m_window; + std::deque m_history; +}; + + + +class UtilizationTracker{ +public: + UtilizationTracker(WallClock::duration window = std::chrono::milliseconds(1000)) + : m_window(window) + , m_min_window(window / 2) + , m_running_usage(0) + {} + + void push_event(WallClock::duration usage_since_last, WallClock timestamp = current_time()){ + WallClock threshold = timestamp - m_window; + while (m_history.size() > 1){ + if (m_history.front().timestamp >= threshold){ + break; + } + m_running_usage -= m_history.front().usage; + m_history.pop_front(); + } + m_history.emplace_back(Entry{timestamp, usage_since_last}); + m_running_usage += usage_since_last; + } + void push_idle(){ + m_history.clear(); + m_running_usage = WallClock::duration(0); + } + + size_t events_in_window() const{ + return m_history.size(); + } + WallClock::duration usage_in_window() const{ + return m_running_usage; + } + double utilization() const{ + if (m_history.size() < 2){ + return 0; + } + auto iter = m_history.begin(); + auto delta_time = m_history.back().timestamp - iter->timestamp; + delta_time = std::max(delta_time, m_min_window); + auto usage = m_running_usage - iter->usage; + std::chrono::microseconds time_usec = std::chrono::duration_cast(delta_time); + if (time_usec.count() == 0){ + return 0; + } + std::chrono::microseconds usage_usec = std::chrono::duration_cast(usage); + return (double)usage_usec.count() / time_usec.count(); + } + + +private: + struct Entry{ + WallClock timestamp; + WallClock::duration usage; + }; + + WallClock::duration m_window; + WallClock::duration m_min_window; + + std::deque m_history; + WallClock::duration m_running_usage; +}; + + + + +} +#endif diff --git a/Common/Cpp/Exceptions.cpp b/Common/Cpp/Exceptions.cpp index 5496bbf0fb..f2ff66929f 100644 --- a/Common/Cpp/Exceptions.cpp +++ b/Common/Cpp/Exceptions.cpp @@ -1,126 +1,126 @@ -/* Exceptions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Exceptions.h" - -namespace PokemonAutomation{ - - - -void Exception::log(Logger& logger) const{ - logger.log(std::string(name()) + ": " + message(), COLOR_RED); -} -std::string Exception::message() const{ - return ""; -} -std::string Exception::to_str() const{ - std::string str = name(); - std::string msg = message(); - if (!msg.empty()){ - str += "\n\n"; - str += msg; - } - return str; -} - - - - -FileException::FileException(Logger* logger, const char* location, std::string message, std::string file) - : m_location(location) - , m_message(std::move(message)) - , m_file(std::move(file)) -{ - std::string str = FileException::name(); - str += ": " + m_message; - if (logger != nullptr){ - logger->log(str, COLOR_RED); - }else{ - std::cerr << str << std::endl; - } -} -std::string FileException::message() const{ - return m_message + "\nFile: " + m_file + "\nLocation: " + m_location; -} - - - -ConnectionException::ConnectionException(Logger* logger, std::string message) - : m_message(std::move(message)) -{ - if (logger != nullptr){ - logger->log(std::string(ConnectionException::name()) + ": " + ConnectionException::message(), COLOR_RED); - }else{ - std::cerr << std::string(ConnectionException::name()) + ": " + ConnectionException::message() << std::endl; - } -} - - - -SerialProtocolException::SerialProtocolException(Logger& logger, const char* /*location*/, std::string message) - //: m_location(location) - : m_message(std::move(message)) -{ - logger.log(std::string(SerialProtocolException::name()) + ": " + SerialProtocolException::message(), COLOR_RED); -} -std::string SerialProtocolException::message() const{ - return m_message; -// return m_message + "\nLocation: " + m_location; -} - - -InternalProgramError::InternalProgramError(Logger* logger, const char* location, std::string message) - : m_location(location) - , m_message(std::move(message)) -{ - if (logger != nullptr){ - logger->log(std::string(InternalProgramError::name()) + ": " + InternalProgramError::message(), COLOR_RED); - }else{ - std::cerr << std::string(InternalProgramError::name()) + ": " + InternalProgramError::message() << std::endl; - } -} -std::string InternalProgramError::message() const{ - return m_message + "\nLocation: " + m_location + "\nPlease report this as a bug."; -} - - -InternalSystemError::InternalSystemError(Logger* logger, const char* location, std::string message) - : m_location(location) - , m_message(std::move(message)) -{ - if (logger != nullptr){ - logger->log(std::string(InternalSystemError::name()) + ": " + InternalSystemError::message(), COLOR_RED); - }else{ - std::cerr << std::string(InternalSystemError::name()) + ": " + InternalSystemError::message() << std::endl; - } -} -std::string InternalSystemError::message() const{ - return m_message + "\nLocation: " + m_location; -} - - - -UserSetupError::UserSetupError(Logger& logger, std::string message) - : m_message(std::move(message)) -{ - logger.log(std::string(UserSetupError::name()) + ": " + UserSetupError::message(), COLOR_RED); -} -std::string UserSetupError::message() const{ - return m_message; -} - - - - - - - - - - - -} +/* Exceptions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Exceptions.h" + +namespace PokemonAutomation{ + + + +void Exception::log(Logger& logger) const{ + logger.log(std::string(name()) + ": " + message(), COLOR_RED); +} +std::string Exception::message() const{ + return ""; +} +std::string Exception::to_str() const{ + std::string str = name(); + std::string msg = message(); + if (!msg.empty()){ + str += "\n\n"; + str += msg; + } + return str; +} + + + + +FileException::FileException(Logger* logger, const char* location, std::string message, std::string file) + : m_location(location) + , m_message(std::move(message)) + , m_file(std::move(file)) +{ + std::string str = FileException::name(); + str += ": " + m_message; + if (logger != nullptr){ + logger->log(str, COLOR_RED); + }else{ + std::cerr << str << std::endl; + } +} +std::string FileException::message() const{ + return m_message + "\nFile: " + m_file + "\nLocation: " + m_location; +} + + + +ConnectionException::ConnectionException(Logger* logger, std::string message) + : m_message(std::move(message)) +{ + if (logger != nullptr){ + logger->log(std::string(ConnectionException::name()) + ": " + ConnectionException::message(), COLOR_RED); + }else{ + std::cerr << std::string(ConnectionException::name()) + ": " + ConnectionException::message() << std::endl; + } +} + + + +SerialProtocolException::SerialProtocolException(Logger& logger, const char* /*location*/, std::string message) + //: m_location(location) + : m_message(std::move(message)) +{ + logger.log(std::string(SerialProtocolException::name()) + ": " + SerialProtocolException::message(), COLOR_RED); +} +std::string SerialProtocolException::message() const{ + return m_message; +// return m_message + "\nLocation: " + m_location; +} + + +InternalProgramError::InternalProgramError(Logger* logger, const char* location, std::string message) + : m_location(location) + , m_message(std::move(message)) +{ + if (logger != nullptr){ + logger->log(std::string(InternalProgramError::name()) + ": " + InternalProgramError::message(), COLOR_RED); + }else{ + std::cerr << std::string(InternalProgramError::name()) + ": " + InternalProgramError::message() << std::endl; + } +} +std::string InternalProgramError::message() const{ + return m_message + "\nLocation: " + m_location + "\nPlease report this as a bug."; +} + + +InternalSystemError::InternalSystemError(Logger* logger, const char* location, std::string message) + : m_location(location) + , m_message(std::move(message)) +{ + if (logger != nullptr){ + logger->log(std::string(InternalSystemError::name()) + ": " + InternalSystemError::message(), COLOR_RED); + }else{ + std::cerr << std::string(InternalSystemError::name()) + ": " + InternalSystemError::message() << std::endl; + } +} +std::string InternalSystemError::message() const{ + return m_message + "\nLocation: " + m_location; +} + + + +UserSetupError::UserSetupError(Logger& logger, std::string message) + : m_message(std::move(message)) +{ + logger.log(std::string(UserSetupError::name()) + ": " + UserSetupError::message(), COLOR_RED); +} +std::string UserSetupError::message() const{ + return m_message; +} + + + + + + + + + + + +} diff --git a/Common/Cpp/Exceptions.h b/Common/Cpp/Exceptions.h index 5a572c88db..d7e8baa7e8 100644 --- a/Common/Cpp/Exceptions.h +++ b/Common/Cpp/Exceptions.h @@ -1,161 +1,161 @@ -/* Exceptions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Exceptions_H -#define PokemonAutomation_Exceptions_H - -#include -#include "Common/Compiler.h" -#include "AbstractLogger.h" - -namespace PokemonAutomation{ - - -template -[[noreturn]] void throw_and_log(Logger& logger, Args&&... args){ - ExceptionType exception(std::forward(args)...); - exception.log(logger); - throw exception; -} - - -// Definitions: -// Catch: To catch the exception using a try-catch. -// Consume: To catch the exception and not rethrow it. - - -// Base class. Don't use this directly. This is for the infra to catch everything. -class Exception{ -public: - virtual ~Exception() = default; - - virtual void log(Logger& logger) const; - virtual const char* name() const = 0; - virtual std::string message() const; - virtual std::string to_str() const; -}; - - -// Thrown when the user stops the program. -// - This should not be consumed except by the infra. -// - Non-infra are allowed to catch and rethrow this exception. -class ProgramCancelledException : public Exception{ -public: - virtual const char* name() const override{ return "ProgramCancelledException"; } -}; - - -// Thrown by BotBase connections when a command is issued while the connection -// is in a state that isn't accepting commands. -// - This should not be consumed except by the infra. -// - Non-infra are allowed to catch and rethrow this exception. -class InvalidConnectionStateException : public Exception{ -public: - InvalidConnectionStateException(std::string message) : m_message(std::move(message)) {} - virtual const char* name() const override{ return "InvalidConnectionStateException"; } - virtual std::string message() const override{ return m_message; } -protected: - std::string m_message; -}; - - -// Thrown when a local operation is cancelled. -// This can be caught by local handlers that do async-cancel. -// If this propagates up to the infra, it is considered an error. -class OperationCancelledException : public Exception{ -public: - virtual const char* name() const override{ return "OperationCancelledException"; } -}; - - - - - -class ParseException : public Exception{ -public: - ParseException() = default; - ParseException(std::string message) : m_message(std::move(message)) {} - virtual const char* name() const override{ return "ParseException"; } - virtual std::string message() const override{ return m_message; } -protected: - std::string m_message; -}; - - -class FileException : public Exception{ -public: - FileException(Logger* logger, const char* location, std::string message, std::string file); - virtual const char* name() const override{ return "FileException"; } - virtual std::string message() const override; -private: - const char* m_location; - std::string m_message; - std::string m_file; -}; - - -class ConnectionException : public Exception{ -public: - ConnectionException(Logger* logger, std::string message); - virtual const char* name() const override{ return "ConnectionException"; } - virtual std::string message() const override{ return m_message; } -private: - std::string m_message; -}; - - -class SerialProtocolException : public Exception{ -public: - SerialProtocolException(Logger& logger, const char* location, std::string message); - virtual const char* name() const override{ return "SerialProtocolException"; } - virtual std::string message() const override; -private: - // const char* m_location; - std::string m_message; -}; - - -// These are thrown for logic errors. They are always bugs. -class InternalProgramError : public Exception{ -public: - InternalProgramError(Logger* logger, const char* location, std::string message); - virtual const char* name() const override{ return "InternalProgramError"; } - virtual std::string message() const override; -private: - const char* m_location; - std::string m_message; -}; - - -// These are thrown for failed system errors. They are not necessarily bugs. -class InternalSystemError : public Exception{ -public: - InternalSystemError(Logger* logger, const char* location, std::string message); - virtual const char* name() const override{ return "InternalSystemError"; } - virtual std::string message() const override; -private: - const char* m_location; - std::string m_message; -}; - - -class UserSetupError : public Exception{ -public: - UserSetupError(Logger& logger, std::string message); - virtual const char* name() const override{ return "UserSetupError"; } - virtual std::string message() const override; -private: - std::string m_message; -}; - - - - - - - -} -#endif +/* Exceptions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Exceptions_H +#define PokemonAutomation_Exceptions_H + +#include +#include "Common/Compiler.h" +#include "AbstractLogger.h" + +namespace PokemonAutomation{ + + +template +[[noreturn]] void throw_and_log(Logger& logger, Args&&... args){ + ExceptionType exception(std::forward(args)...); + exception.log(logger); + throw exception; +} + + +// Definitions: +// Catch: To catch the exception using a try-catch. +// Consume: To catch the exception and not rethrow it. + + +// Base class. Don't use this directly. This is for the infra to catch everything. +class Exception{ +public: + virtual ~Exception() = default; + + virtual void log(Logger& logger) const; + virtual const char* name() const = 0; + virtual std::string message() const; + virtual std::string to_str() const; +}; + + +// Thrown when the user stops the program. +// - This should not be consumed except by the infra. +// - Non-infra are allowed to catch and rethrow this exception. +class ProgramCancelledException : public Exception{ +public: + virtual const char* name() const override{ return "ProgramCancelledException"; } +}; + + +// Thrown by BotBase connections when a command is issued while the connection +// is in a state that isn't accepting commands. +// - This should not be consumed except by the infra. +// - Non-infra are allowed to catch and rethrow this exception. +class InvalidConnectionStateException : public Exception{ +public: + InvalidConnectionStateException(std::string message) : m_message(std::move(message)) {} + virtual const char* name() const override{ return "InvalidConnectionStateException"; } + virtual std::string message() const override{ return m_message; } +protected: + std::string m_message; +}; + + +// Thrown when a local operation is cancelled. +// This can be caught by local handlers that do async-cancel. +// If this propagates up to the infra, it is considered an error. +class OperationCancelledException : public Exception{ +public: + virtual const char* name() const override{ return "OperationCancelledException"; } +}; + + + + + +class ParseException : public Exception{ +public: + ParseException() = default; + ParseException(std::string message) : m_message(std::move(message)) {} + virtual const char* name() const override{ return "ParseException"; } + virtual std::string message() const override{ return m_message; } +protected: + std::string m_message; +}; + + +class FileException : public Exception{ +public: + FileException(Logger* logger, const char* location, std::string message, std::string file); + virtual const char* name() const override{ return "FileException"; } + virtual std::string message() const override; +private: + const char* m_location; + std::string m_message; + std::string m_file; +}; + + +class ConnectionException : public Exception{ +public: + ConnectionException(Logger* logger, std::string message); + virtual const char* name() const override{ return "ConnectionException"; } + virtual std::string message() const override{ return m_message; } +private: + std::string m_message; +}; + + +class SerialProtocolException : public Exception{ +public: + SerialProtocolException(Logger& logger, const char* location, std::string message); + virtual const char* name() const override{ return "SerialProtocolException"; } + virtual std::string message() const override; +private: + // const char* m_location; + std::string m_message; +}; + + +// These are thrown for logic errors. They are always bugs. +class InternalProgramError : public Exception{ +public: + InternalProgramError(Logger* logger, const char* location, std::string message); + virtual const char* name() const override{ return "InternalProgramError"; } + virtual std::string message() const override; +private: + const char* m_location; + std::string m_message; +}; + + +// These are thrown for failed system errors. They are not necessarily bugs. +class InternalSystemError : public Exception{ +public: + InternalSystemError(Logger* logger, const char* location, std::string message); + virtual const char* name() const override{ return "InternalSystemError"; } + virtual std::string message() const override; +private: + const char* m_location; + std::string m_message; +}; + + +class UserSetupError : public Exception{ +public: + UserSetupError(Logger& logger, std::string message); + virtual const char* name() const override{ return "UserSetupError"; } + virtual std::string message() const override; +private: + std::string m_message; +}; + + + + + + + +} +#endif diff --git a/Common/Cpp/ExpressionEvaluator.cpp b/Common/Cpp/ExpressionEvaluator.cpp index a40879ab4e..9ec2d3afa4 100644 --- a/Common/Cpp/ExpressionEvaluator.cpp +++ b/Common/Cpp/ExpressionEvaluator.cpp @@ -1,373 +1,373 @@ -/* Simple (and incomplete) Expression Evaluator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "ExpressionEvaluator.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -bool is_whitespace(char ch){ - switch (ch){ - case ' ': return true; - case '\t': return true; - case '\r': return true; - case '\n': return true; - case '\0': return true; - } - return false; -} -bool is_digit(char ch){ - return '0' <= ch && ch <= '9'; -} -bool is_symbol(char ch){ - if ('a' <= ch && ch <= 'z'){ - return true; - } - if ('A' <= ch && ch <= 'Z'){ - return true; - } - if (ch == '_'){ - return true; - } - return false; -} -bool skip_whitespace(const char*& str){ - while (true){ - char ch = *str; - if (ch == '\0'){ - return true; - } - if (!is_whitespace(ch)){ - return false; - } - str++; - } -} - -template -T checked_multiply(T x, T y){ - if (x == 0 || y == 0){ - return 0; - } - T ret = x * y; - if (ret / x != y){ - throw ParseException("Overflow"); - } - return ret; -} -template -T checked_add(T x, T y){ - if constexpr (std::is_unsigned_v){ - T ret = x + y; - if (ret < x){ - throw ParseException("Overflow"); - } - return ret; - }else{ - if (x >= 0 && std::numeric_limits::max() - x < y){ - throw ParseException("Overflow"); - } - if (x < 0 && y < std::numeric_limits::min() - x){ - throw ParseException("Overflow"); - } - return x + y; - } -} -template -T checked_sub(T x, T y){ - if (x >= 0 && x - std::numeric_limits::max() > y){ - throw ParseException("Overflow"); - } - if (x < 0 && y > x - std::numeric_limits::min()){ - throw ParseException("Overflow"); - } - return x - y; -} - -template -T parse_integer(const char*& str){ - const char* ptr = str; - - T x = 0; - while (true){ - char ch = *str; - if (is_whitespace(ch)){ - return x; - } - if (is_digit(ch)){ - x = checked_multiply(x, 10); - x = checked_add(x, ch - '0'); - str++; - continue; - } - switch (ch){ - case '+': - case '-': - case '*': - case ')': - return x; - } - if (is_symbol(ch)){ - return x; - } - throw ParseException(std::string("Invalid integer: ") + ptr); - } -} -std::string parse_symbol(const char*& str){ - const char* ptr = str; - - std::string ret; - ret += *str++; - while (true){ - char ch = *str; - if (is_whitespace(ch)){ - return ret; - } - if (is_symbol(ch)){ - ret += ch; - str++; - continue; - } - if (is_digit(ch)){ - ret += ch; - str++; - continue; - } - switch (ch){ - case '+': - case '-': - case '*': - case ')': - return ret; - } - throw ParseException(std::string("Invalid symbol: ") + ptr); - } -} - -uint8_t precedence(char ch){ - switch (ch){ - case '+': - case '-': - return 0; - case '*': - return 1; - } - throw ParseException(std::string("Invalid operator: ") + ch); -} - -int64_t parse_expression( - const std::map& variables, - const std::string& expression -){ - const char* str = expression.c_str(); - - std::vector> num; - std::vector op; - - size_t consecutive_values = 0; - while (true){ - // Consecutive values is an implied multiply. - if (consecutive_values > 1){ - consecutive_values = 0; - op.push_back('*'); - while (op.size() >= 2){ - char top = op.back(); - char next = op[op.size() - 2]; - uint8_t p_top = precedence(top); - uint8_t p_next = precedence(next); - if (p_top > p_next){ - break; - } - op.pop_back(); - op.pop_back(); - num.emplace_back(next, 0); - op.push_back(top); - if (p_top == p_next){ - break; - } - } - continue; - } - - if (skip_whitespace(str)){ - break; - } - char ch = *str; -// cout << "ch = " << ch << endl; - - - if (is_digit(ch)){ - consecutive_values++; - num.emplace_back('\0', parse_integer(str)); - continue; - } - if (is_symbol(ch)){ - consecutive_values++; - std::string symbol = parse_symbol(str); - auto iter = variables.find(symbol); - if (iter == variables.end()){ - throw ParseException("Undefined Symbol: " + symbol); - } - num.emplace_back('\0', iter->second); - continue; - } - if (ch == '+' || ch == '-' || ch == '*'){ - consecutive_values = 0; - op.push_back(ch); - str++; - while (op.size() >= 2){ - char top = op.back(); - char next = op[op.size() - 2]; - uint8_t p_top = precedence(top); - uint8_t p_next = precedence(next); - if (p_top > p_next){ - break; - } - op.pop_back(); - op.pop_back(); - num.emplace_back(next, 0); - op.push_back(top); - if (p_top == p_next){ - break; - } - } - continue; - } - // if (ch == '('){ - // - // } - // if (ch == ')'){ - // - // } - throw ParseException("Invalid expression: " + expression); - } - - while (!op.empty()){ - num.emplace_back(op.back(), 0); - op.pop_back(); - } - -#if 0 - cout << "operands: "; - for (const auto& item : num){ - if (item.first == 0){ - cout << item.second << " "; - }else{ - cout << item.first << " "; - } - } - cout << endl; - //cout << "operators: "; - //for (const auto& item : op){ - // cout << item << " "; - //} - //cout << endl; -#endif - - std::vector stack; - for (const auto& item : num){ - if (item.first == 0){ - stack.push_back(item.second); - num.pop_back(); - continue; - } - switch (item.first){ - case '+':{ - if (stack.size() < 2){ - throw ParseException("Invalid expression: unexpected +"); - } - int64_t x = stack[stack.size() - 2]; - int64_t y = stack[stack.size() - 1]; - stack.pop_back(); - stack.pop_back(); - - x = checked_add(x, y); - stack.push_back(x); - continue; - } - case '-':{ - if (stack.size() == 0){ - throw ParseException("Invalid expression: unexpected -"); - } - - // If we have at least two integers (x, y) in the stack, perform x - y - // If we have only one integer y in the stack, perform - y (by leaving x = 0) - - int64_t y = stack[stack.size() - 1]; - stack.pop_back(); - - int64_t x = 0; - if (stack.size() > 0){ - x = stack[stack.size() - 1]; - stack.pop_back(); - } - x = checked_sub(x, y); - stack.push_back(x); - continue; - } - case '*':{ - if (stack.size() < 2){ - throw ParseException("Invalid expression: unexpected *"); - } - int64_t x = stack[stack.size() - 2]; - int64_t y = stack[stack.size() - 1]; - stack.pop_back(); - stack.pop_back(); - x = checked_multiply(x, y); - stack.push_back(x); - continue; - } - } - throw ParseException("Invalid operator."); - } - if (stack.size() != 1){ - throw ParseException("Invalid expression."); - } - - return stack[0]; -} - -const std::map& SYMBOLS(){ - static const std::map SYMBOLS{ - {"TICKS_PER_SECOND", 125}, - }; - return SYMBOLS; -} - - -uint32_t parse_ticks_ui32(const std::string& expression){ - int64_t x = parse_expression(SYMBOLS(), expression); - if (x < 0){ - throw ParseException("Value cannot be negative."); - } - if ((int32_t)x != x){ - throw ParseException("Overflow"); - } - return (int32_t)x; -} - - -int32_t parse_ticks_i32(const std::string& expression){ - int64_t x = parse_expression(SYMBOLS(), expression); - if ((int32_t)x != x){ - throw ParseException("Overflow"); - } - return (int32_t)x; -} - - -} - - +/* Simple (and incomplete) Expression Evaluator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "ExpressionEvaluator.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +bool is_whitespace(char ch){ + switch (ch){ + case ' ': return true; + case '\t': return true; + case '\r': return true; + case '\n': return true; + case '\0': return true; + } + return false; +} +bool is_digit(char ch){ + return '0' <= ch && ch <= '9'; +} +bool is_symbol(char ch){ + if ('a' <= ch && ch <= 'z'){ + return true; + } + if ('A' <= ch && ch <= 'Z'){ + return true; + } + if (ch == '_'){ + return true; + } + return false; +} +bool skip_whitespace(const char*& str){ + while (true){ + char ch = *str; + if (ch == '\0'){ + return true; + } + if (!is_whitespace(ch)){ + return false; + } + str++; + } +} + +template +T checked_multiply(T x, T y){ + if (x == 0 || y == 0){ + return 0; + } + T ret = x * y; + if (ret / x != y){ + throw ParseException("Overflow"); + } + return ret; +} +template +T checked_add(T x, T y){ + if constexpr (std::is_unsigned_v){ + T ret = x + y; + if (ret < x){ + throw ParseException("Overflow"); + } + return ret; + }else{ + if (x >= 0 && std::numeric_limits::max() - x < y){ + throw ParseException("Overflow"); + } + if (x < 0 && y < std::numeric_limits::min() - x){ + throw ParseException("Overflow"); + } + return x + y; + } +} +template +T checked_sub(T x, T y){ + if (x >= 0 && x - std::numeric_limits::max() > y){ + throw ParseException("Overflow"); + } + if (x < 0 && y > x - std::numeric_limits::min()){ + throw ParseException("Overflow"); + } + return x - y; +} + +template +T parse_integer(const char*& str){ + const char* ptr = str; + + T x = 0; + while (true){ + char ch = *str; + if (is_whitespace(ch)){ + return x; + } + if (is_digit(ch)){ + x = checked_multiply(x, 10); + x = checked_add(x, ch - '0'); + str++; + continue; + } + switch (ch){ + case '+': + case '-': + case '*': + case ')': + return x; + } + if (is_symbol(ch)){ + return x; + } + throw ParseException(std::string("Invalid integer: ") + ptr); + } +} +std::string parse_symbol(const char*& str){ + const char* ptr = str; + + std::string ret; + ret += *str++; + while (true){ + char ch = *str; + if (is_whitespace(ch)){ + return ret; + } + if (is_symbol(ch)){ + ret += ch; + str++; + continue; + } + if (is_digit(ch)){ + ret += ch; + str++; + continue; + } + switch (ch){ + case '+': + case '-': + case '*': + case ')': + return ret; + } + throw ParseException(std::string("Invalid symbol: ") + ptr); + } +} + +uint8_t precedence(char ch){ + switch (ch){ + case '+': + case '-': + return 0; + case '*': + return 1; + } + throw ParseException(std::string("Invalid operator: ") + ch); +} + +int64_t parse_expression( + const std::map& variables, + const std::string& expression +){ + const char* str = expression.c_str(); + + std::vector> num; + std::vector op; + + size_t consecutive_values = 0; + while (true){ + // Consecutive values is an implied multiply. + if (consecutive_values > 1){ + consecutive_values = 0; + op.push_back('*'); + while (op.size() >= 2){ + char top = op.back(); + char next = op[op.size() - 2]; + uint8_t p_top = precedence(top); + uint8_t p_next = precedence(next); + if (p_top > p_next){ + break; + } + op.pop_back(); + op.pop_back(); + num.emplace_back(next, 0); + op.push_back(top); + if (p_top == p_next){ + break; + } + } + continue; + } + + if (skip_whitespace(str)){ + break; + } + char ch = *str; +// cout << "ch = " << ch << endl; + + + if (is_digit(ch)){ + consecutive_values++; + num.emplace_back('\0', parse_integer(str)); + continue; + } + if (is_symbol(ch)){ + consecutive_values++; + std::string symbol = parse_symbol(str); + auto iter = variables.find(symbol); + if (iter == variables.end()){ + throw ParseException("Undefined Symbol: " + symbol); + } + num.emplace_back('\0', iter->second); + continue; + } + if (ch == '+' || ch == '-' || ch == '*'){ + consecutive_values = 0; + op.push_back(ch); + str++; + while (op.size() >= 2){ + char top = op.back(); + char next = op[op.size() - 2]; + uint8_t p_top = precedence(top); + uint8_t p_next = precedence(next); + if (p_top > p_next){ + break; + } + op.pop_back(); + op.pop_back(); + num.emplace_back(next, 0); + op.push_back(top); + if (p_top == p_next){ + break; + } + } + continue; + } + // if (ch == '('){ + // + // } + // if (ch == ')'){ + // + // } + throw ParseException("Invalid expression: " + expression); + } + + while (!op.empty()){ + num.emplace_back(op.back(), 0); + op.pop_back(); + } + +#if 0 + cout << "operands: "; + for (const auto& item : num){ + if (item.first == 0){ + cout << item.second << " "; + }else{ + cout << item.first << " "; + } + } + cout << endl; + //cout << "operators: "; + //for (const auto& item : op){ + // cout << item << " "; + //} + //cout << endl; +#endif + + std::vector stack; + for (const auto& item : num){ + if (item.first == 0){ + stack.push_back(item.second); + num.pop_back(); + continue; + } + switch (item.first){ + case '+':{ + if (stack.size() < 2){ + throw ParseException("Invalid expression: unexpected +"); + } + int64_t x = stack[stack.size() - 2]; + int64_t y = stack[stack.size() - 1]; + stack.pop_back(); + stack.pop_back(); + + x = checked_add(x, y); + stack.push_back(x); + continue; + } + case '-':{ + if (stack.size() == 0){ + throw ParseException("Invalid expression: unexpected -"); + } + + // If we have at least two integers (x, y) in the stack, perform x - y + // If we have only one integer y in the stack, perform - y (by leaving x = 0) + + int64_t y = stack[stack.size() - 1]; + stack.pop_back(); + + int64_t x = 0; + if (stack.size() > 0){ + x = stack[stack.size() - 1]; + stack.pop_back(); + } + x = checked_sub(x, y); + stack.push_back(x); + continue; + } + case '*':{ + if (stack.size() < 2){ + throw ParseException("Invalid expression: unexpected *"); + } + int64_t x = stack[stack.size() - 2]; + int64_t y = stack[stack.size() - 1]; + stack.pop_back(); + stack.pop_back(); + x = checked_multiply(x, y); + stack.push_back(x); + continue; + } + } + throw ParseException("Invalid operator."); + } + if (stack.size() != 1){ + throw ParseException("Invalid expression."); + } + + return stack[0]; +} + +const std::map& SYMBOLS(){ + static const std::map SYMBOLS{ + {"TICKS_PER_SECOND", 125}, + }; + return SYMBOLS; +} + + +uint32_t parse_ticks_ui32(const std::string& expression){ + int64_t x = parse_expression(SYMBOLS(), expression); + if (x < 0){ + throw ParseException("Value cannot be negative."); + } + if ((int32_t)x != x){ + throw ParseException("Overflow"); + } + return (int32_t)x; +} + + +int32_t parse_ticks_i32(const std::string& expression){ + int64_t x = parse_expression(SYMBOLS(), expression); + if ((int32_t)x != x){ + throw ParseException("Overflow"); + } + return (int32_t)x; +} + + +} + + diff --git a/Common/Cpp/ExpressionEvaluator.h b/Common/Cpp/ExpressionEvaluator.h index 01061f9886..0185915e6c 100644 --- a/Common/Cpp/ExpressionEvaluator.h +++ b/Common/Cpp/ExpressionEvaluator.h @@ -1,24 +1,24 @@ -/* Simple (and incomplete) Expression Evaluator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include - -namespace PokemonAutomation{ - - - -int64_t parse_expression( - const std::map& variables, - const std::string& expression -); - -uint32_t parse_ticks_ui32(const std::string& expression); -int32_t parse_ticks_i32(const std::string& expression); - - -} +/* Simple (and incomplete) Expression Evaluator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include + +namespace PokemonAutomation{ + + + +int64_t parse_expression( + const std::map& variables, + const std::string& expression +); + +uint32_t parse_ticks_ui32(const std::string& expression); +int32_t parse_ticks_i32(const std::string& expression); + + +} diff --git a/Common/Cpp/ImageResolution.cpp b/Common/Cpp/ImageResolution.cpp index 4a3e2f3b79..0004ef0b01 100644 --- a/Common/Cpp/ImageResolution.cpp +++ b/Common/Cpp/ImageResolution.cpp @@ -1,51 +1,51 @@ -/* Image Resolution - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ImageResolution.h" - -namespace PokemonAutomation{ - - -std::string Resolution::to_string() const{ - return std::to_string(width) + " x " + std::to_string(height); -} - -std::ostream& operator<<(std::ostream& os, const Resolution& resolution){ - os << resolution.width << " x " << resolution.height; - return os; -} - -std::string aspect_ratio_as_string(const Resolution& resolution){ - size_t w = resolution.width; - size_t h = resolution.height; - if (w <= 0 || h <= 0){ - return ""; - } - size_t gcd; - while (true){ - if (h == 0){ - gcd = w; - break; - } - w %= h; - if (w == 0){ - gcd = h; - break; - } - h %= w; - } - w = resolution.width; - h = resolution.height; - w /= gcd; - h /= gcd; - return "(" + std::to_string(w) + ":" + std::to_string(h) + ")"; -} - - - - -} +/* Image Resolution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ImageResolution.h" + +namespace PokemonAutomation{ + + +std::string Resolution::to_string() const{ + return std::to_string(width) + " x " + std::to_string(height); +} + +std::ostream& operator<<(std::ostream& os, const Resolution& resolution){ + os << resolution.width << " x " << resolution.height; + return os; +} + +std::string aspect_ratio_as_string(const Resolution& resolution){ + size_t w = resolution.width; + size_t h = resolution.height; + if (w <= 0 || h <= 0){ + return ""; + } + size_t gcd; + while (true){ + if (h == 0){ + gcd = w; + break; + } + w %= h; + if (w == 0){ + gcd = h; + break; + } + h %= w; + } + w = resolution.width; + h = resolution.height; + w /= gcd; + h /= gcd; + return "(" + std::to_string(w) + ":" + std::to_string(h) + ")"; +} + + + + +} diff --git a/Common/Cpp/ImageResolution.h b/Common/Cpp/ImageResolution.h index ab72588308..9f032db7e5 100644 --- a/Common/Cpp/ImageResolution.h +++ b/Common/Cpp/ImageResolution.h @@ -1,51 +1,51 @@ -/* Image Resolution - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ImageResolution_H -#define PokemonAutomation_ImageResolution_H - -#include - -namespace PokemonAutomation{ - - -struct Resolution{ - size_t width = 0; - size_t height = 0; - - Resolution() = default; - Resolution(size_t p_width, size_t p_height) - : width(p_width) - , height(p_height) - {} - - explicit operator bool() const{ return width != 0 && height != 0; } - double aspect_ratio() const{ return (double)width / height; } - - bool operator==(const Resolution& x) const{ - return width == x.width && height == x.height; - } - bool operator!=(const Resolution& x) const{ - return width != x.width || height != x.height; - } - bool operator<(const Resolution& x) const{ - if (width != x.width){ - return width < x.width; - } - return height < x.height; - } - - std::string to_string() const; - - friend std::ostream& operator<<(std::ostream& os, const Resolution& resolution); -}; - -std::string aspect_ratio_as_string(const Resolution& resolution); - - - -} -#endif +/* Image Resolution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ImageResolution_H +#define PokemonAutomation_ImageResolution_H + +#include + +namespace PokemonAutomation{ + + +struct Resolution{ + size_t width = 0; + size_t height = 0; + + Resolution() = default; + Resolution(size_t p_width, size_t p_height) + : width(p_width) + , height(p_height) + {} + + explicit operator bool() const{ return width != 0 && height != 0; } + double aspect_ratio() const{ return (double)width / height; } + + bool operator==(const Resolution& x) const{ + return width == x.width && height == x.height; + } + bool operator!=(const Resolution& x) const{ + return width != x.width || height != x.height; + } + bool operator<(const Resolution& x) const{ + if (width != x.width){ + return width < x.width; + } + return height < x.height; + } + + std::string to_string() const; + + friend std::ostream& operator<<(std::ostream& os, const Resolution& resolution); +}; + +std::string aspect_ratio_as_string(const Resolution& resolution); + + + +} +#endif diff --git a/Common/Cpp/Json/JsonArray.cpp b/Common/Cpp/Json/JsonArray.cpp index e57ee1b862..b3a43eecb9 100644 --- a/Common/Cpp/Json/JsonArray.cpp +++ b/Common/Cpp/Json/JsonArray.cpp @@ -1,55 +1,55 @@ -/* JSON Array - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "JsonArray.h" -#include "JsonTools.h" - -namespace PokemonAutomation{ - - -JsonArray::JsonArray(const JsonArray& x){ - for (const auto& item : x.m_data){ - m_data.emplace_back(item.clone()); - } -} -JsonArray& JsonArray::operator=(const JsonArray& x){ - JsonArray tmp(x); - return operator=(std::move(tmp)); -} -JsonArray JsonArray::clone() const{ - return *this; -} - - - -std::string JsonArray::dump(int indent) const{ - nlohmann::json::array_t ret; - for (const auto& item : *this){ - ret.emplace_back(to_nlohmann(item)); - } - return nlohmann::json(ret).dump(indent); -} -void JsonArray::dump(const std::string& filename, int indent) const{ - string_to_file(filename, dump(indent)); -} - - -const JsonValue& JsonArray::operator[](size_t index) const{ - if (index >= m_data.size()){ - throw JsonParseException("", m_data.size(), index); - } - return m_data[index]; -} -JsonValue& JsonArray::operator[](size_t index){ - if (index >= m_data.size()){ - throw JsonParseException("", m_data.size(), index); - } - return m_data[index]; -} - - - -} +/* JSON Array + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "JsonArray.h" +#include "JsonTools.h" + +namespace PokemonAutomation{ + + +JsonArray::JsonArray(const JsonArray& x){ + for (const auto& item : x.m_data){ + m_data.emplace_back(item.clone()); + } +} +JsonArray& JsonArray::operator=(const JsonArray& x){ + JsonArray tmp(x); + return operator=(std::move(tmp)); +} +JsonArray JsonArray::clone() const{ + return *this; +} + + + +std::string JsonArray::dump(int indent) const{ + nlohmann::json::array_t ret; + for (const auto& item : *this){ + ret.emplace_back(to_nlohmann(item)); + } + return nlohmann::json(ret).dump(indent); +} +void JsonArray::dump(const std::string& filename, int indent) const{ + string_to_file(filename, dump(indent)); +} + + +const JsonValue& JsonArray::operator[](size_t index) const{ + if (index >= m_data.size()){ + throw JsonParseException("", m_data.size(), index); + } + return m_data[index]; +} +JsonValue& JsonArray::operator[](size_t index){ + if (index >= m_data.size()){ + throw JsonParseException("", m_data.size(), index); + } + return m_data[index]; +} + + + +} diff --git a/Common/Cpp/Json/JsonArray.h b/Common/Cpp/Json/JsonArray.h index 42bf70d4a3..b9d948a5b6 100644 --- a/Common/Cpp/Json/JsonArray.h +++ b/Common/Cpp/Json/JsonArray.h @@ -1,61 +1,61 @@ -/* JSON Array - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Common_Json_JsonArray_H -#define PokemonAutomation_Common_Json_JsonArray_H - -#include -#include "JsonValue.h" - -namespace PokemonAutomation{ - - - -class JsonArray{ -public: - JsonArray() = default; - JsonArray(JsonArray&& x) = default; - JsonArray& operator=(JsonArray&& x) = default; -private: - // Private to avoid accidental copying. - JsonArray(const JsonArray& x); - JsonArray& operator=(const JsonArray& x); -public: - JsonArray clone() const; - -public: - std::string dump(int indent = 4) const; - void dump(const std::string& filename, int indent = 4) const; - - bool empty () const{ return m_data.empty(); } - size_t size () const{ return m_data.size(); } - - const JsonValue& operator[](size_t index) const; - JsonValue& operator[](size_t index) ; - - void push_back(JsonValue&& x){ m_data.emplace_back(std::move(x)); } - -public: - using const_iterator = std::vector::const_iterator; - using iterator = std::vector::iterator; - - const_iterator cbegin () const{ return m_data.cbegin(); } - const_iterator begin () const{ return m_data.begin(); } - iterator begin () { return m_data.begin(); } - - const_iterator cend () const{ return m_data.cend(); } - const_iterator end () const{ return m_data.end(); } - iterator end () { return m_data.end(); } - -private: - friend class JsonValue; - std::vector m_data; -}; - - - -} -#endif +/* JSON Array + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Common_Json_JsonArray_H +#define PokemonAutomation_Common_Json_JsonArray_H + +#include +#include "JsonValue.h" + +namespace PokemonAutomation{ + + + +class JsonArray{ +public: + JsonArray() = default; + JsonArray(JsonArray&& x) = default; + JsonArray& operator=(JsonArray&& x) = default; +private: + // Private to avoid accidental copying. + JsonArray(const JsonArray& x); + JsonArray& operator=(const JsonArray& x); +public: + JsonArray clone() const; + +public: + std::string dump(int indent = 4) const; + void dump(const std::string& filename, int indent = 4) const; + + bool empty () const{ return m_data.empty(); } + size_t size () const{ return m_data.size(); } + + const JsonValue& operator[](size_t index) const; + JsonValue& operator[](size_t index) ; + + void push_back(JsonValue&& x){ m_data.emplace_back(std::move(x)); } + +public: + using const_iterator = std::vector::const_iterator; + using iterator = std::vector::iterator; + + const_iterator cbegin () const{ return m_data.cbegin(); } + const_iterator begin () const{ return m_data.begin(); } + iterator begin () { return m_data.begin(); } + + const_iterator cend () const{ return m_data.cend(); } + const_iterator end () const{ return m_data.end(); } + iterator end () { return m_data.end(); } + +private: + friend class JsonValue; + std::vector m_data; +}; + + + +} +#endif diff --git a/Common/Cpp/Json/JsonObject.cpp b/Common/Cpp/Json/JsonObject.cpp index 882022c15f..29b72e33b9 100644 --- a/Common/Cpp/Json/JsonObject.cpp +++ b/Common/Cpp/Json/JsonObject.cpp @@ -1,239 +1,239 @@ -/* JSON Object - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "JsonObject.h" -#include "JsonTools.h" - -namespace PokemonAutomation{ - - - -// RAII - -JsonObject::JsonObject(const JsonObject& x){ - for (const auto& item : x.m_data){ - m_data.emplace(item.first, item.second.clone()); - } -} -JsonObject& JsonObject::operator=(const JsonObject& x){ - JsonObject tmp(x); - return operator=(std::move(tmp)); -} -JsonObject JsonObject::clone() const{ - return *this; -} - - - -// Get with exception. - -bool JsonObject::get_boolean_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_boolean_throw(filename); -} -int64_t JsonObject::get_integer_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_integer_throw(filename); -} -double JsonObject::get_double_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_double_throw(filename); -} -const std::string& JsonObject::get_string_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_string_throw(filename); -} -std::string& JsonObject::get_string_throw(const std::string& key, const std::string& filename){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_string_throw(filename); -} -const JsonArray& JsonObject::get_array_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_array_throw(filename); -} -JsonArray& JsonObject::get_array_throw(const std::string& key, const std::string& filename){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_array_throw(filename); -} -const JsonObject& JsonObject::get_object_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_object_throw(filename); -} -JsonObject& JsonObject::get_object_throw(const std::string& key, const std::string& filename){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second.to_object_throw(filename); -} -const JsonValue& JsonObject::get_value_throw(const std::string& key, const std::string& filename) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second; -} -JsonValue& JsonObject::get_value_throw(const std::string& key, const std::string& filename){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - throw JsonParseException(filename, key); - } - return iter->second; -} - - - -// Get pointer. - -const std::string* JsonObject::get_string(const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return iter->second.to_string(); -} -std::string* JsonObject::get_string(const std::string& key){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return iter->second.to_string(); -} -const JsonArray* JsonObject::get_array(const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return iter->second.to_array(); -} -JsonArray* JsonObject::get_array(const std::string& key){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return iter->second.to_array(); -} -const JsonObject* JsonObject::get_object(const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return iter->second.to_object(); -} -JsonObject* JsonObject::get_object(const std::string& key){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return iter->second.to_object(); -} -const JsonValue* JsonObject::get_value(const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return &iter->second; -} -JsonValue* JsonObject::get_value(const std::string& key){ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return nullptr; - } - return &iter->second; -} - - - -#if 0 - -// Read with defaults. - -bool JsonObject::to_boolean(const std::string& key, bool default_value) const{ - read_boolean(default_value, key); - return default_value; -} -int64_t JsonObject::to_integer(const std::string& key, int64_t default_value) const{ - read_integer(default_value, key); - return default_value; -} -double JsonObject::to_double(const std::string& key, double default_value) const{ - read_float(default_value, key); - return default_value; -} -std::string JsonObject::to_string(const std::string& key, const char* default_value) const{ - const std::string* str = get_string(key); - return str == nullptr ? default_value : *str; -} -#endif - - - -// Conditional read. - -bool JsonObject::read_boolean(bool& value, const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return false; - } - return iter->second.read_boolean(value); -} -bool JsonObject::read_float(double& value, const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return false; - } - return iter->second.read_float(value); -} -bool JsonObject::read_string(std::string& value, const std::string& key) const{ - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return false; - } - return iter->second.read_string(value); -} - - - - -std::string JsonObject::dump(int indent) const{ - nlohmann::json ret; - for (const auto& item : *this){ - ret[item.first] = to_nlohmann(item.second); - } - return nlohmann::json(ret).dump(indent); -} -void JsonObject::dump(const std::string& filename, int indent) const{ - string_to_file(filename, dump(indent)); -} - - - - -} +/* JSON Object + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "JsonObject.h" +#include "JsonTools.h" + +namespace PokemonAutomation{ + + + +// RAII + +JsonObject::JsonObject(const JsonObject& x){ + for (const auto& item : x.m_data){ + m_data.emplace(item.first, item.second.clone()); + } +} +JsonObject& JsonObject::operator=(const JsonObject& x){ + JsonObject tmp(x); + return operator=(std::move(tmp)); +} +JsonObject JsonObject::clone() const{ + return *this; +} + + + +// Get with exception. + +bool JsonObject::get_boolean_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_boolean_throw(filename); +} +int64_t JsonObject::get_integer_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_integer_throw(filename); +} +double JsonObject::get_double_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_double_throw(filename); +} +const std::string& JsonObject::get_string_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_string_throw(filename); +} +std::string& JsonObject::get_string_throw(const std::string& key, const std::string& filename){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_string_throw(filename); +} +const JsonArray& JsonObject::get_array_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_array_throw(filename); +} +JsonArray& JsonObject::get_array_throw(const std::string& key, const std::string& filename){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_array_throw(filename); +} +const JsonObject& JsonObject::get_object_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_object_throw(filename); +} +JsonObject& JsonObject::get_object_throw(const std::string& key, const std::string& filename){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second.to_object_throw(filename); +} +const JsonValue& JsonObject::get_value_throw(const std::string& key, const std::string& filename) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second; +} +JsonValue& JsonObject::get_value_throw(const std::string& key, const std::string& filename){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + throw JsonParseException(filename, key); + } + return iter->second; +} + + + +// Get pointer. + +const std::string* JsonObject::get_string(const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return iter->second.to_string(); +} +std::string* JsonObject::get_string(const std::string& key){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return iter->second.to_string(); +} +const JsonArray* JsonObject::get_array(const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return iter->second.to_array(); +} +JsonArray* JsonObject::get_array(const std::string& key){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return iter->second.to_array(); +} +const JsonObject* JsonObject::get_object(const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return iter->second.to_object(); +} +JsonObject* JsonObject::get_object(const std::string& key){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return iter->second.to_object(); +} +const JsonValue* JsonObject::get_value(const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return &iter->second; +} +JsonValue* JsonObject::get_value(const std::string& key){ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return nullptr; + } + return &iter->second; +} + + + +#if 0 + +// Read with defaults. + +bool JsonObject::to_boolean(const std::string& key, bool default_value) const{ + read_boolean(default_value, key); + return default_value; +} +int64_t JsonObject::to_integer(const std::string& key, int64_t default_value) const{ + read_integer(default_value, key); + return default_value; +} +double JsonObject::to_double(const std::string& key, double default_value) const{ + read_float(default_value, key); + return default_value; +} +std::string JsonObject::to_string(const std::string& key, const char* default_value) const{ + const std::string* str = get_string(key); + return str == nullptr ? default_value : *str; +} +#endif + + + +// Conditional read. + +bool JsonObject::read_boolean(bool& value, const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return false; + } + return iter->second.read_boolean(value); +} +bool JsonObject::read_float(double& value, const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return false; + } + return iter->second.read_float(value); +} +bool JsonObject::read_string(std::string& value, const std::string& key) const{ + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return false; + } + return iter->second.read_string(value); +} + + + + +std::string JsonObject::dump(int indent) const{ + nlohmann::json ret; + for (const auto& item : *this){ + ret[item.first] = to_nlohmann(item.second); + } + return nlohmann::json(ret).dump(indent); +} +void JsonObject::dump(const std::string& filename, int indent) const{ + string_to_file(filename, dump(indent)); +} + + + + +} diff --git a/Common/Cpp/Json/JsonObject.h b/Common/Cpp/Json/JsonObject.h index 4fe2765c65..117506628e 100644 --- a/Common/Cpp/Json/JsonObject.h +++ b/Common/Cpp/Json/JsonObject.h @@ -1,122 +1,122 @@ -/* JSON Object - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Common_Json_JsonObject_H -#define PokemonAutomation_Common_Json_JsonObject_H - -#include -#include "JsonValue.h" - -namespace PokemonAutomation{ - - -class JsonObject{ -public: - JsonObject() = default; - JsonObject(JsonObject&& x) = default; - JsonObject& operator=(JsonObject&& x) = default; -private: - // Private to avoid accidental copying. - JsonObject(const JsonObject& x); - JsonObject& operator=(const JsonObject& x); -public: - JsonObject clone() const; - -public: - std::string dump(int indent = 4) const; - void dump(const std::string& filename, int indent = 4) const; - - bool empty () const{ return m_data.empty(); } - size_t size () const{ return m_data.size(); } - - JsonValue& operator[](const std::string& key){ return m_data[key]; } - JsonValue& operator[]( std::string&& key){ return m_data[std::move(key)]; } - - // Get the value. Throws if the type doesn't match. - bool get_boolean_throw (const std::string& key, const std::string& filename = std::string()) const; - int64_t get_integer_throw (const std::string& key, const std::string& filename = std::string()) const; - double get_double_throw (const std::string& key, const std::string& filename = std::string()) const; - const std::string& get_string_throw (const std::string& key, const std::string& filename = std::string()) const; - std::string& get_string_throw (const std::string& key, const std::string& filename = std::string()); - const JsonArray& get_array_throw (const std::string& key, const std::string& filename = std::string()) const; - JsonArray& get_array_throw (const std::string& key, const std::string& filename = std::string()); - const JsonObject& get_object_throw (const std::string& key, const std::string& filename = std::string()) const; - JsonObject& get_object_throw (const std::string& key, const std::string& filename = std::string()); - const JsonValue& get_value_throw (const std::string& key, const std::string& filename = std::string()) const; - JsonValue& get_value_throw (const std::string& key, const std::string& filename = std::string()); - - // Get a pointer to the value at the specified key. - // If the key exists and the type matches, returns the pointer. - // If the type does match, returns nullptr. - const std::string* get_string (const std::string& key) const; - std::string* get_string (const std::string& key); - const JsonArray* get_array (const std::string& key) const; - JsonArray* get_array (const std::string& key); - const JsonObject* get_object (const std::string& key) const; - JsonObject* get_object (const std::string& key); - const JsonValue* get_value (const std::string& key) const; - JsonValue* get_value (const std::string& key); - -#if 0 - // Convert to the specified type. If the type doesn't match, return the default. - bool to_boolean (const std::string& key, bool default_value = false) const; - int64_t to_integer (const std::string& key, int64_t default_value = 0) const; - double to_double (const std::string& key, double default_value = 0) const; - std::string to_string (const std::string& key, const char* default_value = "") const; -#endif - - // Attempt to read this value at the specified key. - // If the key exists and the type matches, the value is assigned to "value" and returns true. - // Otherwise returns false and "value" remains unchanged. - bool read_boolean(bool& value, const std::string& key) const; - bool read_float(double& value, const std::string& key) const; - bool read_string(std::string& value, const std::string& key) const; - - // Same as the above, but will saturate the value to the specific min/max. - template - bool read_integer( - Type& value, const std::string& key, - int64_t min = std::numeric_limits::min(), - int64_t max = std::numeric_limits::max() - ) const; - -public: - using const_iterator = std::map::const_iterator; - using iterator = std::map::iterator; - - const_iterator find(const std::string& key) const{ return m_data.find(key); } - iterator find(const std::string& key) { return m_data.find(key); } - - const_iterator cbegin () const{ return m_data.cbegin(); } - const_iterator begin () const{ return m_data.begin(); } - iterator begin () { return m_data.begin(); } - - const_iterator cend () const{ return m_data.cend(); } - const_iterator end () const{ return m_data.end(); } - iterator end () { return m_data.end(); } - -private: - friend class JsonValue; - std::map m_data; -}; - - - -template -bool JsonObject::read_integer(Type& value, const std::string& key, int64_t min, int64_t max) const{ - static_assert(std::is_integral::value); - auto iter = m_data.find(key); - if (iter == m_data.end()){ - return false; - } - return iter->second.read_integer(value, min, max); -} - - - - -} -#endif +/* JSON Object + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Common_Json_JsonObject_H +#define PokemonAutomation_Common_Json_JsonObject_H + +#include +#include "JsonValue.h" + +namespace PokemonAutomation{ + + +class JsonObject{ +public: + JsonObject() = default; + JsonObject(JsonObject&& x) = default; + JsonObject& operator=(JsonObject&& x) = default; +private: + // Private to avoid accidental copying. + JsonObject(const JsonObject& x); + JsonObject& operator=(const JsonObject& x); +public: + JsonObject clone() const; + +public: + std::string dump(int indent = 4) const; + void dump(const std::string& filename, int indent = 4) const; + + bool empty () const{ return m_data.empty(); } + size_t size () const{ return m_data.size(); } + + JsonValue& operator[](const std::string& key){ return m_data[key]; } + JsonValue& operator[]( std::string&& key){ return m_data[std::move(key)]; } + + // Get the value. Throws if the type doesn't match. + bool get_boolean_throw (const std::string& key, const std::string& filename = std::string()) const; + int64_t get_integer_throw (const std::string& key, const std::string& filename = std::string()) const; + double get_double_throw (const std::string& key, const std::string& filename = std::string()) const; + const std::string& get_string_throw (const std::string& key, const std::string& filename = std::string()) const; + std::string& get_string_throw (const std::string& key, const std::string& filename = std::string()); + const JsonArray& get_array_throw (const std::string& key, const std::string& filename = std::string()) const; + JsonArray& get_array_throw (const std::string& key, const std::string& filename = std::string()); + const JsonObject& get_object_throw (const std::string& key, const std::string& filename = std::string()) const; + JsonObject& get_object_throw (const std::string& key, const std::string& filename = std::string()); + const JsonValue& get_value_throw (const std::string& key, const std::string& filename = std::string()) const; + JsonValue& get_value_throw (const std::string& key, const std::string& filename = std::string()); + + // Get a pointer to the value at the specified key. + // If the key exists and the type matches, returns the pointer. + // If the type does match, returns nullptr. + const std::string* get_string (const std::string& key) const; + std::string* get_string (const std::string& key); + const JsonArray* get_array (const std::string& key) const; + JsonArray* get_array (const std::string& key); + const JsonObject* get_object (const std::string& key) const; + JsonObject* get_object (const std::string& key); + const JsonValue* get_value (const std::string& key) const; + JsonValue* get_value (const std::string& key); + +#if 0 + // Convert to the specified type. If the type doesn't match, return the default. + bool to_boolean (const std::string& key, bool default_value = false) const; + int64_t to_integer (const std::string& key, int64_t default_value = 0) const; + double to_double (const std::string& key, double default_value = 0) const; + std::string to_string (const std::string& key, const char* default_value = "") const; +#endif + + // Attempt to read this value at the specified key. + // If the key exists and the type matches, the value is assigned to "value" and returns true. + // Otherwise returns false and "value" remains unchanged. + bool read_boolean(bool& value, const std::string& key) const; + bool read_float(double& value, const std::string& key) const; + bool read_string(std::string& value, const std::string& key) const; + + // Same as the above, but will saturate the value to the specific min/max. + template + bool read_integer( + Type& value, const std::string& key, + int64_t min = std::numeric_limits::min(), + int64_t max = std::numeric_limits::max() + ) const; + +public: + using const_iterator = std::map::const_iterator; + using iterator = std::map::iterator; + + const_iterator find(const std::string& key) const{ return m_data.find(key); } + iterator find(const std::string& key) { return m_data.find(key); } + + const_iterator cbegin () const{ return m_data.cbegin(); } + const_iterator begin () const{ return m_data.begin(); } + iterator begin () { return m_data.begin(); } + + const_iterator cend () const{ return m_data.cend(); } + const_iterator end () const{ return m_data.end(); } + iterator end () { return m_data.end(); } + +private: + friend class JsonValue; + std::map m_data; +}; + + + +template +bool JsonObject::read_integer(Type& value, const std::string& key, int64_t min, int64_t max) const{ + static_assert(std::is_integral::value); + auto iter = m_data.find(key); + if (iter == m_data.end()){ + return false; + } + return iter->second.read_integer(value, min, max); +} + + + + +} +#endif diff --git a/Common/Cpp/Json/JsonTools.cpp b/Common/Cpp/Json/JsonTools.cpp index c608575ba9..eff6d70e7a 100644 --- a/Common/Cpp/Json/JsonTools.cpp +++ b/Common/Cpp/Json/JsonTools.cpp @@ -1,224 +1,224 @@ -/* JSON Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "JsonTools.h" -#include "JsonArray.h" -#include "JsonObject.h" - -namespace PokemonAutomation{ - - - -void string_to_file(const std::string& filename, const std::string& str){ - std::string json_out = "\xef\xbb\xbf"; - // Convert to CRLF. - char previous = 0; - for (char ch : str){ - if (ch == '\n' && previous != '\r'){ - json_out += '\r'; - } - json_out += ch; - previous = ch; - } - - QFile file(QString::fromStdString(filename)); - if (!file.open(QFile::WriteOnly)){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to create file.", filename); - } - if (file.write(json_out.c_str(), json_out.size()) != (int)json_out.size()){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to write file.", filename); - } - file.close(); -} - - -std::string file_to_string(const std::string& filename){ - QFile file(QString::fromStdString(filename)); - if (!file.open(QFile::ReadOnly)){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to open file.", filename); - } - return file.readAll().toStdString(); -} - - -bool file_to_string(const std::string& filename, std::string& content){ - QFile file(QString::fromStdString(filename)); - if (!file.open(QFile::ReadOnly)){ - return false; - } - content = file.readAll().toStdString(); - return true; -} - - - - -JsonValue from_nlohmann(const nlohmann::json& json){ - if (json.is_null()){ - return JsonValue(); - } - if (json.is_boolean()){ - return JsonValue((bool)json); - } - if (json.is_number_integer()){ - return JsonValue((int64_t)json); - } - if (json.is_number()){ - return JsonValue((double)json); - } - if (json.is_string()){ - return JsonValue((std::string)json); - } - if (json.is_array()){ - JsonArray array; - size_t size = json.size(); - for (size_t c = 0; c < size; c++){ - array.push_back(from_nlohmann(json[c])); - } - return array; - } - if (json.is_object()){ - JsonObject object; - for (auto it = json.begin(); it != json.end(); ++it){ - object[it.key()] = from_nlohmann(it.value()); - } - return object; - } - return JsonValue(); -} -nlohmann::json to_nlohmann(const JsonValue& json){ - if (json.is_null()){ - return nlohmann::json(); - } - { - bool value; - if (json.read_boolean(value)){ - return value; - } - } - { - int64_t value; - if (json.read_integer(value)){ - return value; - } - } - { - double value; - if (json.read_float(value)){ - return value; - } - } - { - std::string value; - if (json.read_string(value)){ - return value; - } - } - if (json.is_array()){ - nlohmann::json::array_t ret; - for (const auto& item : *json.to_array()){ - ret.emplace_back(to_nlohmann(item)); - } - return ret; - } - if (json.is_object()){ - nlohmann::json ret; - for (const auto& item : *json.to_object()){ - ret[item.first] = to_nlohmann(item.second); - } - return ret; - } - return nlohmann::json(); -} - - -JsonValue from_QJson(const QJsonValue& json){ - if (json.isNull()){ - return JsonValue(); - } - if (json.isBool()){ - return JsonValue(json.toBool()); - } - if (json.isDouble()){ - double value = json.toDouble(); - return value == (int64_t)value - ? JsonValue(json.toInt()) - : JsonValue(value); - } - if (json.isString()){ - return JsonValue(json.toString().toStdString()); - } - if (json.isArray()){ - JsonArray array; - for (QJsonValueRef item : json.toArray()){ - array.push_back(from_QJson(item)); - } - return array; - } - if (json.isObject()){ - QJsonObject obj = json.toObject(); - JsonObject object; - for (auto it = obj.begin(); it != obj.end(); ++it){ - object[it.key().toStdString()] = from_QJson(it.value()); - } - return object; - } - return JsonValue(); -} -QJsonValue to_QJson(const JsonValue& json){ - if (json.is_null()){ - return QJsonValue(); - } - { - bool value; - if (json.read_boolean(value)){ - return value; - } - } - { - qint64 value; - if (json.read_integer(value)){ - return value; - } - } - { - double value; - if (json.read_float(value)){ - return value; - } - } - { - std::string value; - if (json.read_string(value)){ - return QString::fromStdString(value); - } - } - if (json.is_array()){ - QJsonArray ret; - for (const auto& item : *json.to_array()){ - ret.append(to_QJson(item)); - } - return ret; - } - if (json.is_object()){ - QJsonObject ret; - for (const auto& item : *json.to_object()){ - ret.insert(QString::fromStdString(item.first), to_QJson(item.second)); - } - return ret; - } - return QJsonValue(); -} - - - - -} +/* JSON Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "JsonTools.h" +#include "JsonArray.h" +#include "JsonObject.h" + +namespace PokemonAutomation{ + + + +void string_to_file(const std::string& filename, const std::string& str){ + std::string json_out = "\xef\xbb\xbf"; + // Convert to CRLF. + char previous = 0; + for (char ch : str){ + if (ch == '\n' && previous != '\r'){ + json_out += '\r'; + } + json_out += ch; + previous = ch; + } + + QFile file(QString::fromStdString(filename)); + if (!file.open(QFile::WriteOnly)){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to create file.", filename); + } + if (file.write(json_out.c_str(), json_out.size()) != (int)json_out.size()){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to write file.", filename); + } + file.close(); +} + + +std::string file_to_string(const std::string& filename){ + QFile file(QString::fromStdString(filename)); + if (!file.open(QFile::ReadOnly)){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to open file.", filename); + } + return file.readAll().toStdString(); +} + + +bool file_to_string(const std::string& filename, std::string& content){ + QFile file(QString::fromStdString(filename)); + if (!file.open(QFile::ReadOnly)){ + return false; + } + content = file.readAll().toStdString(); + return true; +} + + + + +JsonValue from_nlohmann(const nlohmann::json& json){ + if (json.is_null()){ + return JsonValue(); + } + if (json.is_boolean()){ + return JsonValue((bool)json); + } + if (json.is_number_integer()){ + return JsonValue((int64_t)json); + } + if (json.is_number()){ + return JsonValue((double)json); + } + if (json.is_string()){ + return JsonValue((std::string)json); + } + if (json.is_array()){ + JsonArray array; + size_t size = json.size(); + for (size_t c = 0; c < size; c++){ + array.push_back(from_nlohmann(json[c])); + } + return array; + } + if (json.is_object()){ + JsonObject object; + for (auto it = json.begin(); it != json.end(); ++it){ + object[it.key()] = from_nlohmann(it.value()); + } + return object; + } + return JsonValue(); +} +nlohmann::json to_nlohmann(const JsonValue& json){ + if (json.is_null()){ + return nlohmann::json(); + } + { + bool value; + if (json.read_boolean(value)){ + return value; + } + } + { + int64_t value; + if (json.read_integer(value)){ + return value; + } + } + { + double value; + if (json.read_float(value)){ + return value; + } + } + { + std::string value; + if (json.read_string(value)){ + return value; + } + } + if (json.is_array()){ + nlohmann::json::array_t ret; + for (const auto& item : *json.to_array()){ + ret.emplace_back(to_nlohmann(item)); + } + return ret; + } + if (json.is_object()){ + nlohmann::json ret; + for (const auto& item : *json.to_object()){ + ret[item.first] = to_nlohmann(item.second); + } + return ret; + } + return nlohmann::json(); +} + + +JsonValue from_QJson(const QJsonValue& json){ + if (json.isNull()){ + return JsonValue(); + } + if (json.isBool()){ + return JsonValue(json.toBool()); + } + if (json.isDouble()){ + double value = json.toDouble(); + return value == (int64_t)value + ? JsonValue(json.toInt()) + : JsonValue(value); + } + if (json.isString()){ + return JsonValue(json.toString().toStdString()); + } + if (json.isArray()){ + JsonArray array; + for (QJsonValueRef item : json.toArray()){ + array.push_back(from_QJson(item)); + } + return array; + } + if (json.isObject()){ + QJsonObject obj = json.toObject(); + JsonObject object; + for (auto it = obj.begin(); it != obj.end(); ++it){ + object[it.key().toStdString()] = from_QJson(it.value()); + } + return object; + } + return JsonValue(); +} +QJsonValue to_QJson(const JsonValue& json){ + if (json.is_null()){ + return QJsonValue(); + } + { + bool value; + if (json.read_boolean(value)){ + return value; + } + } + { + qint64 value; + if (json.read_integer(value)){ + return value; + } + } + { + double value; + if (json.read_float(value)){ + return value; + } + } + { + std::string value; + if (json.read_string(value)){ + return QString::fromStdString(value); + } + } + if (json.is_array()){ + QJsonArray ret; + for (const auto& item : *json.to_array()){ + ret.append(to_QJson(item)); + } + return ret; + } + if (json.is_object()){ + QJsonObject ret; + for (const auto& item : *json.to_object()){ + ret.insert(QString::fromStdString(item.first), to_QJson(item.second)); + } + return ret; + } + return QJsonValue(); +} + + + + +} diff --git a/Common/Cpp/Json/JsonTools.h b/Common/Cpp/Json/JsonTools.h index b28d8e3d62..6d9a7efa88 100644 --- a/Common/Cpp/Json/JsonTools.h +++ b/Common/Cpp/Json/JsonTools.h @@ -1,34 +1,34 @@ -/* JSON Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Common_Json_JsonTools_H -#define PokemonAutomation_Common_Json_JsonTools_H - -#include -#include "3rdParty/nlohmann/json.hpp" -#include "JsonValue.h" - -class QJsonValue; - -namespace PokemonAutomation{ - - -void string_to_file(const std::string& filename, const std::string& str); -// Load file from `filename` into a string -// If unable to open the file, FileException is thrown -std::string file_to_string(const std::string& filename); -// Load file from `filename` into a string. Return true if the file can be read successfully -bool file_to_string(const std::string& filename, std::string& content); - -JsonValue from_nlohmann(const nlohmann::json& json); -nlohmann::json to_nlohmann(const JsonValue& json); - -JsonValue from_QJson(const QJsonValue& json); -QJsonValue to_QJson(const JsonValue& json); - - -} -#endif +/* JSON Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Common_Json_JsonTools_H +#define PokemonAutomation_Common_Json_JsonTools_H + +#include +#include "3rdParty/nlohmann/json.hpp" +#include "JsonValue.h" + +class QJsonValue; + +namespace PokemonAutomation{ + + +void string_to_file(const std::string& filename, const std::string& str); +// Load file from `filename` into a string +// If unable to open the file, FileException is thrown +std::string file_to_string(const std::string& filename); +// Load file from `filename` into a string. Return true if the file can be read successfully +bool file_to_string(const std::string& filename, std::string& content); + +JsonValue from_nlohmann(const nlohmann::json& json); +nlohmann::json to_nlohmann(const JsonValue& json); + +JsonValue from_QJson(const QJsonValue& json); +QJsonValue to_QJson(const JsonValue& json); + + +} +#endif diff --git a/Common/Cpp/Json/JsonValue.cpp b/Common/Cpp/Json/JsonValue.cpp index 23f2fc91c5..82f2c2e25e 100644 --- a/Common/Cpp/Json/JsonValue.cpp +++ b/Common/Cpp/Json/JsonValue.cpp @@ -1,389 +1,389 @@ -/* JSON Value - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "3rdParty/nlohmann/json.hpp" -#include "JsonValue.h" -#include "JsonArray.h" -#include "JsonObject.h" -#include "JsonTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -const std::string& get_typename(JsonType type){ - static const std::string NAMES[] = { - "null", - "Boolean", - "Integer", - "Float", - "String", - "Array", - "Object", - }; - return NAMES[(int)type]; -} - -JsonParseException::JsonParseException( - const std::string& filename, - JsonType expected_type, - JsonType actual_type -){ - m_message += "Expected: " + get_typename(expected_type) + "\n"; - m_message += "Actual: " + get_typename(actual_type); - if (!filename.empty()){ - m_message += "\n\n"; - m_message += filename; - } -} -JsonParseException::JsonParseException( - const std::string& filename, - size_t size, size_t index -) - : ParseException("Index Out-of-Bounds: size = " + std::to_string(size) + ", index = " + std::to_string(index)) -{ - if (!filename.empty()){ - m_message += "\n\n"; - m_message += filename; - } -} -JsonParseException::JsonParseException( - const std::string& filename, - const std::string& key -) - : ParseException("Key not Found: " + key) -{ - if (!filename.empty()){ - m_message += "\n\n"; - m_message += filename; - } -} -JsonParseException::JsonParseException( - const std::string& filename, - const std::string& key, - JsonType expected_type, - JsonType actual_type -) - : ParseException("Key: " + key + "\n\n") -{ - m_message += "Expected: " + get_typename(expected_type) + "\n"; - m_message += "Actual: " + get_typename(actual_type); - if (!filename.empty()){ - m_message += "\n\n"; - m_message += filename; - } -} - - - - - -// RAII - -JsonValue::~JsonValue(){ - clear(); -} -JsonValue::JsonValue(JsonValue&& x) - : m_type(x.m_type) - , u(x.u) -{ - x.m_type = JsonType::EMPTY; -} -void JsonValue::operator=(JsonValue&& x){ - if (this == &x){ - return; - } - clear(); - m_type = x.m_type; - u = x.u; - x.m_type = JsonType::EMPTY; -} -JsonValue::JsonValue(const JsonValue& x) - : m_type(x.m_type) -{ - switch (m_type){ - case JsonType::EMPTY: - break; - case JsonType::BOOLEAN: - u.m_bool = x.u.m_bool; - break; - case JsonType::INTEGER: - u.m_integer = x.u.m_integer; - break; - case JsonType::FLOAT: - u.m_float = x.u.m_float; - break; - case JsonType::STRING: - u.m_string = new std::string(*x.u.m_string); - break; - case JsonType::ARRAY: - u.m_array = new JsonArray(*x.u.m_array); - break; - case JsonType::OBJECT: - u.m_object = new JsonObject(*x.u.m_object); - break; - } -} -void JsonValue::operator=(const JsonValue& x){ - if (this == &x){ - return; - } - JsonValue tmp(x); - operator=(std::move(tmp)); -} -JsonValue JsonValue::clone() const{ - return *this; -} -void JsonValue::clear(){ - switch (m_type){ - case JsonType::STRING: - delete u.m_string; - break; - case JsonType::ARRAY: - delete u.m_array; - break; - case JsonType::OBJECT: - delete u.m_object; - break; - default:; - } - m_type = JsonType::EMPTY; -} - - - -// Constructors - -JsonValue::JsonValue(bool x) - : m_type(JsonType::BOOLEAN) -{ - u.m_bool = x; -} -JsonValue::JsonValue(int64_t x) - : m_type(JsonType::INTEGER) -{ - u.m_integer = x; -} -JsonValue::JsonValue(double x) - : m_type(JsonType::FLOAT) -{ - u.m_float = x; -} -JsonValue::JsonValue(const char* x) - : m_type(JsonType::STRING) -{ - u.m_string = new std::string(x); -} -JsonValue::JsonValue(std::string x) - : m_type(JsonType::STRING) -{ - u.m_string = new std::string(std::move(x)); -} -JsonValue::JsonValue(JsonArray&& x) - : m_type(JsonType::ARRAY) -{ - u.m_array = new JsonArray(std::move(x)); -} -JsonValue::JsonValue(JsonObject&& x) - : m_type(JsonType::OBJECT) -{ - u.m_object = new JsonObject(std::move(x)); -} - - - -// Get with exception. - -bool JsonValue::to_boolean_throw(const std::string& filename) const{ - if (m_type == JsonType::BOOLEAN){ - return u.m_bool; - } - throw JsonParseException(filename, JsonType::BOOLEAN, m_type); -} -int64_t JsonValue::to_integer_throw(const std::string& filename) const{ - if (m_type == JsonType::INTEGER){ - return u.m_integer; - } - throw JsonParseException(filename, JsonType::INTEGER, m_type); -} -double JsonValue::to_double_throw(const std::string& filename) const{ - if (m_type == JsonType::INTEGER){ - return (double)u.m_integer; - } - if (m_type == JsonType::FLOAT){ - return u.m_float; - } - throw JsonParseException(filename, JsonType::FLOAT, m_type); -} -const std::string& JsonValue::to_string_throw(const std::string& filename) const{ - if (m_type == JsonType::STRING){ - return *u.m_string; - } - throw JsonParseException(filename, JsonType::STRING, m_type); -} -std::string& JsonValue::to_string_throw(const std::string& filename){ - if (m_type == JsonType::STRING){ - return *u.m_string; - } - throw JsonParseException(filename, JsonType::STRING, m_type); -} -const JsonArray& JsonValue::to_array_throw(const std::string& filename) const{ - if (m_type == JsonType::ARRAY){ - return *u.m_array; - } - throw JsonParseException(filename, JsonType::ARRAY, m_type); -} -JsonArray& JsonValue::to_array_throw(const std::string& filename){ - if (m_type == JsonType::ARRAY){ - return *u.m_array; - } - throw JsonParseException(filename, JsonType::ARRAY, m_type); -} -const JsonObject& JsonValue::to_object_throw(const std::string& filename) const{ - if (m_type == JsonType::OBJECT){ - return *u.m_object; - } - throw JsonParseException(filename, JsonType::OBJECT, m_type); -} -JsonObject& JsonValue::to_object_throw(const std::string& filename){ - if (m_type == JsonType::OBJECT){ - return *u.m_object; - } - throw JsonParseException(filename, JsonType::OBJECT, m_type); -} - - - -// Get pointer. - -const std::string* JsonValue::to_string() const{ - if (m_type != JsonType::STRING){ - return nullptr; - } - return u.m_string; -} -std::string* JsonValue::to_string(){ - if (m_type != JsonType::STRING){ - return nullptr; - } - return u.m_string; -} -const JsonArray* JsonValue::to_array() const{ - return m_type == JsonType::ARRAY ? u.m_array : nullptr; -} -JsonArray* JsonValue::to_array(){ - return m_type == JsonType::ARRAY ? u.m_array : nullptr; -} -const JsonObject* JsonValue::to_object() const{ - return m_type == JsonType::OBJECT ? u.m_object : nullptr; -} -JsonObject* JsonValue::to_object(){ - return m_type == JsonType::OBJECT ? u.m_object : nullptr; -} - - - -// Get with default. - -bool JsonValue::to_boolean_default(bool default_value) const{ - if (m_type == JsonType::BOOLEAN){ - return u.m_bool; - } - return default_value; -} -int64_t JsonValue::to_integer_default(int64_t default_value) const{ - if (m_type == JsonType::INTEGER){ - return u.m_integer; - } - return default_value; -} -double JsonValue::to_double_default(double default_value) const{ - if (m_type == JsonType::INTEGER){ - return (double)u.m_integer; - } - if (m_type == JsonType::FLOAT){ - return u.m_float; - } - return default_value; -} -std::string JsonValue::to_string_default(const char* default_value) const{ - if (m_type == JsonType::STRING){ - return *u.m_string; - } - return default_value; -} - - - -// Read if matching. - -bool JsonValue::read_boolean(bool& value) const{ - if (m_type == JsonType::BOOLEAN){ - value = u.m_bool; - return true; - } - return false; -} -bool JsonValue::read_integer(int64_t& value) const{ - if (m_type == JsonType::INTEGER){ - value = u.m_integer; - return true; - } - return false; -} -bool JsonValue::read_integer(uint64_t& value) const{ - if (m_type == JsonType::INTEGER){ - value = u.m_integer; - return true; - } - return false; -} -bool JsonValue::read_float(double& value) const{ - if (m_type == JsonType::INTEGER){ - value = (double)u.m_integer; - return true; - } - if (m_type == JsonType::FLOAT){ - value = u.m_float; - return true; - } - return false; -} -bool JsonValue::read_string(std::string& value) const{ - if (m_type == JsonType::STRING){ - value = *u.m_string; - return true; - } - return false; -} - - - - -JsonValue parse_json(const std::string& str){ - return from_nlohmann(nlohmann::json::parse(str, nullptr, false)); -} -JsonValue load_json_file(const std::string& filename){ - std::string str = file_to_string(filename); - return parse_json(str); -} -std::string JsonValue::dump(int indent) const{ - return to_nlohmann(*this).dump(indent); -} -void JsonValue::dump(const std::string& filename, int indent) const{ - string_to_file(filename, dump(indent)); -} - - - - - - - -} +/* JSON Value + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "3rdParty/nlohmann/json.hpp" +#include "JsonValue.h" +#include "JsonArray.h" +#include "JsonObject.h" +#include "JsonTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +const std::string& get_typename(JsonType type){ + static const std::string NAMES[] = { + "null", + "Boolean", + "Integer", + "Float", + "String", + "Array", + "Object", + }; + return NAMES[(int)type]; +} + +JsonParseException::JsonParseException( + const std::string& filename, + JsonType expected_type, + JsonType actual_type +){ + m_message += "Expected: " + get_typename(expected_type) + "\n"; + m_message += "Actual: " + get_typename(actual_type); + if (!filename.empty()){ + m_message += "\n\n"; + m_message += filename; + } +} +JsonParseException::JsonParseException( + const std::string& filename, + size_t size, size_t index +) + : ParseException("Index Out-of-Bounds: size = " + std::to_string(size) + ", index = " + std::to_string(index)) +{ + if (!filename.empty()){ + m_message += "\n\n"; + m_message += filename; + } +} +JsonParseException::JsonParseException( + const std::string& filename, + const std::string& key +) + : ParseException("Key not Found: " + key) +{ + if (!filename.empty()){ + m_message += "\n\n"; + m_message += filename; + } +} +JsonParseException::JsonParseException( + const std::string& filename, + const std::string& key, + JsonType expected_type, + JsonType actual_type +) + : ParseException("Key: " + key + "\n\n") +{ + m_message += "Expected: " + get_typename(expected_type) + "\n"; + m_message += "Actual: " + get_typename(actual_type); + if (!filename.empty()){ + m_message += "\n\n"; + m_message += filename; + } +} + + + + + +// RAII + +JsonValue::~JsonValue(){ + clear(); +} +JsonValue::JsonValue(JsonValue&& x) + : m_type(x.m_type) + , u(x.u) +{ + x.m_type = JsonType::EMPTY; +} +void JsonValue::operator=(JsonValue&& x){ + if (this == &x){ + return; + } + clear(); + m_type = x.m_type; + u = x.u; + x.m_type = JsonType::EMPTY; +} +JsonValue::JsonValue(const JsonValue& x) + : m_type(x.m_type) +{ + switch (m_type){ + case JsonType::EMPTY: + break; + case JsonType::BOOLEAN: + u.m_bool = x.u.m_bool; + break; + case JsonType::INTEGER: + u.m_integer = x.u.m_integer; + break; + case JsonType::FLOAT: + u.m_float = x.u.m_float; + break; + case JsonType::STRING: + u.m_string = new std::string(*x.u.m_string); + break; + case JsonType::ARRAY: + u.m_array = new JsonArray(*x.u.m_array); + break; + case JsonType::OBJECT: + u.m_object = new JsonObject(*x.u.m_object); + break; + } +} +void JsonValue::operator=(const JsonValue& x){ + if (this == &x){ + return; + } + JsonValue tmp(x); + operator=(std::move(tmp)); +} +JsonValue JsonValue::clone() const{ + return *this; +} +void JsonValue::clear(){ + switch (m_type){ + case JsonType::STRING: + delete u.m_string; + break; + case JsonType::ARRAY: + delete u.m_array; + break; + case JsonType::OBJECT: + delete u.m_object; + break; + default:; + } + m_type = JsonType::EMPTY; +} + + + +// Constructors + +JsonValue::JsonValue(bool x) + : m_type(JsonType::BOOLEAN) +{ + u.m_bool = x; +} +JsonValue::JsonValue(int64_t x) + : m_type(JsonType::INTEGER) +{ + u.m_integer = x; +} +JsonValue::JsonValue(double x) + : m_type(JsonType::FLOAT) +{ + u.m_float = x; +} +JsonValue::JsonValue(const char* x) + : m_type(JsonType::STRING) +{ + u.m_string = new std::string(x); +} +JsonValue::JsonValue(std::string x) + : m_type(JsonType::STRING) +{ + u.m_string = new std::string(std::move(x)); +} +JsonValue::JsonValue(JsonArray&& x) + : m_type(JsonType::ARRAY) +{ + u.m_array = new JsonArray(std::move(x)); +} +JsonValue::JsonValue(JsonObject&& x) + : m_type(JsonType::OBJECT) +{ + u.m_object = new JsonObject(std::move(x)); +} + + + +// Get with exception. + +bool JsonValue::to_boolean_throw(const std::string& filename) const{ + if (m_type == JsonType::BOOLEAN){ + return u.m_bool; + } + throw JsonParseException(filename, JsonType::BOOLEAN, m_type); +} +int64_t JsonValue::to_integer_throw(const std::string& filename) const{ + if (m_type == JsonType::INTEGER){ + return u.m_integer; + } + throw JsonParseException(filename, JsonType::INTEGER, m_type); +} +double JsonValue::to_double_throw(const std::string& filename) const{ + if (m_type == JsonType::INTEGER){ + return (double)u.m_integer; + } + if (m_type == JsonType::FLOAT){ + return u.m_float; + } + throw JsonParseException(filename, JsonType::FLOAT, m_type); +} +const std::string& JsonValue::to_string_throw(const std::string& filename) const{ + if (m_type == JsonType::STRING){ + return *u.m_string; + } + throw JsonParseException(filename, JsonType::STRING, m_type); +} +std::string& JsonValue::to_string_throw(const std::string& filename){ + if (m_type == JsonType::STRING){ + return *u.m_string; + } + throw JsonParseException(filename, JsonType::STRING, m_type); +} +const JsonArray& JsonValue::to_array_throw(const std::string& filename) const{ + if (m_type == JsonType::ARRAY){ + return *u.m_array; + } + throw JsonParseException(filename, JsonType::ARRAY, m_type); +} +JsonArray& JsonValue::to_array_throw(const std::string& filename){ + if (m_type == JsonType::ARRAY){ + return *u.m_array; + } + throw JsonParseException(filename, JsonType::ARRAY, m_type); +} +const JsonObject& JsonValue::to_object_throw(const std::string& filename) const{ + if (m_type == JsonType::OBJECT){ + return *u.m_object; + } + throw JsonParseException(filename, JsonType::OBJECT, m_type); +} +JsonObject& JsonValue::to_object_throw(const std::string& filename){ + if (m_type == JsonType::OBJECT){ + return *u.m_object; + } + throw JsonParseException(filename, JsonType::OBJECT, m_type); +} + + + +// Get pointer. + +const std::string* JsonValue::to_string() const{ + if (m_type != JsonType::STRING){ + return nullptr; + } + return u.m_string; +} +std::string* JsonValue::to_string(){ + if (m_type != JsonType::STRING){ + return nullptr; + } + return u.m_string; +} +const JsonArray* JsonValue::to_array() const{ + return m_type == JsonType::ARRAY ? u.m_array : nullptr; +} +JsonArray* JsonValue::to_array(){ + return m_type == JsonType::ARRAY ? u.m_array : nullptr; +} +const JsonObject* JsonValue::to_object() const{ + return m_type == JsonType::OBJECT ? u.m_object : nullptr; +} +JsonObject* JsonValue::to_object(){ + return m_type == JsonType::OBJECT ? u.m_object : nullptr; +} + + + +// Get with default. + +bool JsonValue::to_boolean_default(bool default_value) const{ + if (m_type == JsonType::BOOLEAN){ + return u.m_bool; + } + return default_value; +} +int64_t JsonValue::to_integer_default(int64_t default_value) const{ + if (m_type == JsonType::INTEGER){ + return u.m_integer; + } + return default_value; +} +double JsonValue::to_double_default(double default_value) const{ + if (m_type == JsonType::INTEGER){ + return (double)u.m_integer; + } + if (m_type == JsonType::FLOAT){ + return u.m_float; + } + return default_value; +} +std::string JsonValue::to_string_default(const char* default_value) const{ + if (m_type == JsonType::STRING){ + return *u.m_string; + } + return default_value; +} + + + +// Read if matching. + +bool JsonValue::read_boolean(bool& value) const{ + if (m_type == JsonType::BOOLEAN){ + value = u.m_bool; + return true; + } + return false; +} +bool JsonValue::read_integer(int64_t& value) const{ + if (m_type == JsonType::INTEGER){ + value = u.m_integer; + return true; + } + return false; +} +bool JsonValue::read_integer(uint64_t& value) const{ + if (m_type == JsonType::INTEGER){ + value = u.m_integer; + return true; + } + return false; +} +bool JsonValue::read_float(double& value) const{ + if (m_type == JsonType::INTEGER){ + value = (double)u.m_integer; + return true; + } + if (m_type == JsonType::FLOAT){ + value = u.m_float; + return true; + } + return false; +} +bool JsonValue::read_string(std::string& value) const{ + if (m_type == JsonType::STRING){ + value = *u.m_string; + return true; + } + return false; +} + + + + +JsonValue parse_json(const std::string& str){ + return from_nlohmann(nlohmann::json::parse(str, nullptr, false)); +} +JsonValue load_json_file(const std::string& filename){ + std::string str = file_to_string(filename); + return parse_json(str); +} +std::string JsonValue::dump(int indent) const{ + return to_nlohmann(*this).dump(indent); +} +void JsonValue::dump(const std::string& filename, int indent) const{ + string_to_file(filename, dump(indent)); +} + + + + + + + +} diff --git a/Common/Cpp/Json/JsonValue.h b/Common/Cpp/Json/JsonValue.h index 09eb5621bc..18039a3125 100644 --- a/Common/Cpp/Json/JsonValue.h +++ b/Common/Cpp/Json/JsonValue.h @@ -1,205 +1,205 @@ -/* JSON Value - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Common_Json_JsonValue_H -#define PokemonAutomation_Common_Json_JsonValue_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - -enum class JsonType{ - EMPTY, - BOOLEAN, - INTEGER, - FLOAT, - STRING, - ARRAY, - OBJECT, -}; -const std::string& get_typename(JsonType type); - - -class JsonParseException : public ParseException{ -public: - JsonParseException( // Mismatching Type - const std::string& filename, - JsonType expected_type, - JsonType actual_type - ); - JsonParseException( // Out-of-bounds index. - const std::string& filename, - size_t size, size_t index - ); - JsonParseException( // Missing Key - const std::string& filename, - const std::string& key - ); - JsonParseException( // Mismatching Type through an object. - const std::string& filename, - const std::string& key, - JsonType expected_type, - JsonType actual_type - ); - virtual const char* name() const override{ return "JsonParseException"; } - virtual std::string message() const override{ return m_message; } -}; - - -class JsonValue; -class JsonArray; -class JsonObject; - - -class JsonValue{ -public: - ~JsonValue(); - JsonValue(JsonValue&& x); - void operator=(JsonValue&& x); -private: - // Private to avoid accidental copying. - JsonValue(const JsonValue& x); - void operator=(const JsonValue& x); -public: - JsonValue clone() const; - -public: - JsonValue() = default; - JsonValue(bool x); - JsonValue(int64_t x); - JsonValue(double x); - JsonValue(const char* x); - JsonValue(std::string x); - JsonValue(JsonArray&& x); - JsonValue(JsonObject&& x); - - template - JsonValue(const Type*) = delete; - - template ::value>::type> - JsonValue(Type x) - : JsonValue((int64_t)x) - {} - - void clear(); - - std::string dump(int indent = 4) const; - void dump(const std::string& filename, int indent = 4) const; - - JsonType type () const{ return m_type; } - bool is_null () const{ return m_type == JsonType::EMPTY; } - bool is_boolean () const{ return m_type == JsonType::BOOLEAN; } - bool is_integer () const{ return m_type == JsonType::INTEGER; } - bool is_float () const{ return m_type == JsonType::INTEGER || m_type == JsonType::FLOAT; } - bool is_string () const{ return m_type == JsonType::STRING; } - bool is_array () const{ return m_type == JsonType::ARRAY; } - bool is_object () const{ return m_type == JsonType::OBJECT; } - - // Get the value. Throws if the type doesn't match. - bool to_boolean_throw(const std::string& filename = std::string()) const; - int64_t to_integer_throw(const std::string& filename = std::string()) const; - double to_double_throw (const std::string& filename = std::string()) const; - const std::string& to_string_throw (const std::string& filename = std::string()) const; - std::string& to_string_throw (const std::string& filename = std::string()); - const JsonArray& to_array_throw (const std::string& filename = std::string()) const; - JsonArray& to_array_throw (const std::string& filename = std::string()); - const JsonObject& to_object_throw (const std::string& filename = std::string()) const; - JsonObject& to_object_throw (const std::string& filename = std::string()); - - // Get a pointer to the data for this value. - // If the type matches, returns the pointer. - // If the type does match, returns nullptr. - const std::string* to_string () const; - std::string* to_string (); - const JsonArray* to_array () const; - JsonArray* to_array (); - const JsonObject* to_object () const; - JsonObject* to_object (); - - // Convert to the specified type. If the type doesn't match, return the default. - bool to_boolean_default (bool default_value = false) const; - int64_t to_integer_default (int64_t default_value = 0) const; - double to_double_default (double default_value = 0) const; - std::string to_string_default (const char* default_value = "") const; - - // Attempt to read this value as a specific type. - // If the type matches, the value is assigned to "value" and returns true. - // Otherwise returns false and "value" remains unchanged. - bool read_boolean (bool& value) const; - bool read_integer (int64_t& value) const; - bool read_integer (uint64_t& value) const; - bool read_float (double& value) const; - bool read_string (std::string& value) const; - - // Same as the above, but will saturate the value to the specific min/max. - template - bool read_integer( - Type& value, - int64_t min = std::numeric_limits::min(), - int64_t max = std::numeric_limits::max() - ) const; - -private: - JsonType m_type = JsonType::EMPTY; - union{ - bool m_bool; - int64_t m_integer; - double m_float; - std::string* m_string; - JsonArray* m_array; - JsonObject* m_object; - } u; -}; - -// Given a string as a raw JSON, parse it into a `JsonValue`. -// If there is error parsing the JSON, it will not throw exception. -// The input string is usually loaded directly from a JSON file. -// You can call JsonTools.h:file_to_string() to load a file as a raw JSON string. -JsonValue parse_json(const std::string& str); -// Load file from `filename` and parse it into a `JsonValue`. -// If unable to open the file, FileException is thrown -// If there is error parsing the JSON, it will not throw exception. -JsonValue load_json_file(const std::string& filename); - - -template -bool JsonValue::read_integer(Type& value, int64_t min, int64_t max) const{ - static_assert(std::is_integral::value); - if (std::is_unsigned::value){ - uint64_t tmp; - bool ret = read_integer(tmp); - if (!ret){ - return false; - } - tmp = std::max(tmp, min); - tmp = std::min(tmp, max); - value = (Type)tmp; - }else{ - int64_t tmp; - bool ret = read_integer(tmp); - if (!ret){ - return false; - } - tmp = std::max(tmp, min); - tmp = std::min(tmp, max); - value = (Type)tmp; - } - return true; -} - - - - - - -} -#endif +/* JSON Value + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Common_Json_JsonValue_H +#define PokemonAutomation_Common_Json_JsonValue_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + +enum class JsonType{ + EMPTY, + BOOLEAN, + INTEGER, + FLOAT, + STRING, + ARRAY, + OBJECT, +}; +const std::string& get_typename(JsonType type); + + +class JsonParseException : public ParseException{ +public: + JsonParseException( // Mismatching Type + const std::string& filename, + JsonType expected_type, + JsonType actual_type + ); + JsonParseException( // Out-of-bounds index. + const std::string& filename, + size_t size, size_t index + ); + JsonParseException( // Missing Key + const std::string& filename, + const std::string& key + ); + JsonParseException( // Mismatching Type through an object. + const std::string& filename, + const std::string& key, + JsonType expected_type, + JsonType actual_type + ); + virtual const char* name() const override{ return "JsonParseException"; } + virtual std::string message() const override{ return m_message; } +}; + + +class JsonValue; +class JsonArray; +class JsonObject; + + +class JsonValue{ +public: + ~JsonValue(); + JsonValue(JsonValue&& x); + void operator=(JsonValue&& x); +private: + // Private to avoid accidental copying. + JsonValue(const JsonValue& x); + void operator=(const JsonValue& x); +public: + JsonValue clone() const; + +public: + JsonValue() = default; + JsonValue(bool x); + JsonValue(int64_t x); + JsonValue(double x); + JsonValue(const char* x); + JsonValue(std::string x); + JsonValue(JsonArray&& x); + JsonValue(JsonObject&& x); + + template + JsonValue(const Type*) = delete; + + template ::value>::type> + JsonValue(Type x) + : JsonValue((int64_t)x) + {} + + void clear(); + + std::string dump(int indent = 4) const; + void dump(const std::string& filename, int indent = 4) const; + + JsonType type () const{ return m_type; } + bool is_null () const{ return m_type == JsonType::EMPTY; } + bool is_boolean () const{ return m_type == JsonType::BOOLEAN; } + bool is_integer () const{ return m_type == JsonType::INTEGER; } + bool is_float () const{ return m_type == JsonType::INTEGER || m_type == JsonType::FLOAT; } + bool is_string () const{ return m_type == JsonType::STRING; } + bool is_array () const{ return m_type == JsonType::ARRAY; } + bool is_object () const{ return m_type == JsonType::OBJECT; } + + // Get the value. Throws if the type doesn't match. + bool to_boolean_throw(const std::string& filename = std::string()) const; + int64_t to_integer_throw(const std::string& filename = std::string()) const; + double to_double_throw (const std::string& filename = std::string()) const; + const std::string& to_string_throw (const std::string& filename = std::string()) const; + std::string& to_string_throw (const std::string& filename = std::string()); + const JsonArray& to_array_throw (const std::string& filename = std::string()) const; + JsonArray& to_array_throw (const std::string& filename = std::string()); + const JsonObject& to_object_throw (const std::string& filename = std::string()) const; + JsonObject& to_object_throw (const std::string& filename = std::string()); + + // Get a pointer to the data for this value. + // If the type matches, returns the pointer. + // If the type does match, returns nullptr. + const std::string* to_string () const; + std::string* to_string (); + const JsonArray* to_array () const; + JsonArray* to_array (); + const JsonObject* to_object () const; + JsonObject* to_object (); + + // Convert to the specified type. If the type doesn't match, return the default. + bool to_boolean_default (bool default_value = false) const; + int64_t to_integer_default (int64_t default_value = 0) const; + double to_double_default (double default_value = 0) const; + std::string to_string_default (const char* default_value = "") const; + + // Attempt to read this value as a specific type. + // If the type matches, the value is assigned to "value" and returns true. + // Otherwise returns false and "value" remains unchanged. + bool read_boolean (bool& value) const; + bool read_integer (int64_t& value) const; + bool read_integer (uint64_t& value) const; + bool read_float (double& value) const; + bool read_string (std::string& value) const; + + // Same as the above, but will saturate the value to the specific min/max. + template + bool read_integer( + Type& value, + int64_t min = std::numeric_limits::min(), + int64_t max = std::numeric_limits::max() + ) const; + +private: + JsonType m_type = JsonType::EMPTY; + union{ + bool m_bool; + int64_t m_integer; + double m_float; + std::string* m_string; + JsonArray* m_array; + JsonObject* m_object; + } u; +}; + +// Given a string as a raw JSON, parse it into a `JsonValue`. +// If there is error parsing the JSON, it will not throw exception. +// The input string is usually loaded directly from a JSON file. +// You can call JsonTools.h:file_to_string() to load a file as a raw JSON string. +JsonValue parse_json(const std::string& str); +// Load file from `filename` and parse it into a `JsonValue`. +// If unable to open the file, FileException is thrown +// If there is error parsing the JSON, it will not throw exception. +JsonValue load_json_file(const std::string& filename); + + +template +bool JsonValue::read_integer(Type& value, int64_t min, int64_t max) const{ + static_assert(std::is_integral::value); + if (std::is_unsigned::value){ + uint64_t tmp; + bool ret = read_integer(tmp); + if (!ret){ + return false; + } + tmp = std::max(tmp, min); + tmp = std::min(tmp, max); + value = (Type)tmp; + }else{ + int64_t tmp; + bool ret = read_integer(tmp); + if (!ret){ + return false; + } + tmp = std::max(tmp, min); + tmp = std::min(tmp, max); + value = (Type)tmp; + } + return true; +} + + + + + + +} +#endif diff --git a/Common/Cpp/LifetimeSanitizer.cpp b/Common/Cpp/LifetimeSanitizer.cpp index d49357476a..2699bd03c7 100644 --- a/Common/Cpp/LifetimeSanitizer.cpp +++ b/Common/Cpp/LifetimeSanitizer.cpp @@ -1,208 +1,208 @@ -/* Lifetime Sanitizer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -//#include -#include -#include -#include "Concurrency/SpinLock.h" -#include "LifetimeSanitizer.h" - -#ifdef _WIN32 -#include -#endif - - - -namespace PokemonAutomation{ - - -#ifdef PA_SANITIZER_ENABLE - -//#define PA_SANITIZER_PRINT_ALL -const std::set SANITIZER_FILTER = { -// "MultiSwitchProgramSession", -// "MultiSwitchProgramWidget2", -// "ControllerFeatures", -}; - -SpinLock sanitizer_lock; -std::set sanitizer_map; - - -std::atomic LifetimeSanitizer_disabled(false); - -void LifetimeSanitizer::disable(){ - WriteSpinLock lg(sanitizer_lock); - LifetimeSanitizer_disabled.store(true, std::memory_order_relaxed); - sanitizer_map.clear(); -} - -PA_NO_INLINE void LifetimeSanitizer::terminate_with_dump(){ - // Intentionally crash the program here and let the crash dump deal with - // the error reporting. - -#ifdef _WIN32 - Sleep(500); -#endif - - std::cerr << (char*)nullptr << std::endl; -} - - - - -LifetimeSanitizer::LifetimeSanitizer(const char* name){ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - internal_construct(name); -} -LifetimeSanitizer::~LifetimeSanitizer(){ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - internal_destruct(); -} - - -LifetimeSanitizer::LifetimeSanitizer(LifetimeSanitizer&& x){ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - x.check_usage(); - internal_construct(x.m_name); -} -void LifetimeSanitizer::operator=(LifetimeSanitizer&& x){ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - check_usage(); - x.check_usage(); -} -LifetimeSanitizer::LifetimeSanitizer(const LifetimeSanitizer& x){ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - x.check_usage(); - internal_construct(x.m_name); -} -void LifetimeSanitizer::operator=(const LifetimeSanitizer& x){ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - check_usage(); - x.check_usage(); -} - - - -void LifetimeSanitizer::check_usage() const{ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - ReadSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Using: " << this << " : " << m_name << std::endl; - } - auto iter = sanitizer_map.find(this); - if (iter == sanitizer_map.end()){ - std::cerr << "Use non-existent: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - if (m_token != SANITIZER_TOKEN || m_self != this){ - std::cerr << "Use corrupted: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } -} -void LifetimeSanitizer::start_using() const{ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - ReadSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Start using: " << this << " : " << m_name << std::endl; - } - auto iter = sanitizer_map.find(this); - if (iter == sanitizer_map.end()){ - std::cerr << "Start using non-existent: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - if (m_token != SANITIZER_TOKEN || m_self != this){ - std::cerr << "Start using corrupted: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - m_use_counter++; -} -void LifetimeSanitizer::done_using() const{ - if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ - return; - } - ReadSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Done using: " << this << " : " << m_name << std::endl; - } - auto iter = sanitizer_map.find(this); - if (iter == sanitizer_map.end()){ - std::cerr << "Done using non-existent: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - if (m_token != SANITIZER_TOKEN || m_self != this){ - std::cerr << "Done using corrupted: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - m_use_counter--; -} - - -void LifetimeSanitizer::internal_construct(const char* name){ - WriteSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(name)){ - std::cout << "LifetimeSanitizer - Allocating: " << this << " : " << name << std::endl; - } - - auto iter = sanitizer_map.find(this); - if (iter != sanitizer_map.end()){ - std::cerr << "LifetimeSanitizer - Double allocation: " << this << " : " << name << std::endl; - terminate_with_dump(); - } - sanitizer_map.insert(this); - - m_token = SANITIZER_TOKEN; - m_self = this; - m_name = name; -} -void LifetimeSanitizer::internal_destruct(){ - WriteSpinLock lg(sanitizer_lock); - if (SANITIZER_FILTER.contains(m_name)){ - std::cout << "LifetimeSanitizer - Freeing: " << this << " : " << m_name << std::endl; - } - - auto iter = sanitizer_map.find(this); - if (iter == sanitizer_map.end()){ - std::cerr << "LifetimeSanitizer - Free non-existent: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - sanitizer_map.erase(this); - - if (m_token != SANITIZER_TOKEN || m_self != this){ - std::cerr << "LifetimeSanitizer - Free non-existent: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - if (m_use_counter != 0){ - std::cerr << "LifetimeSanitizer - Freeing while in-use: " << this << " : " << m_name << std::endl; - terminate_with_dump(); - } - m_self = nullptr; -} -#endif - - - - - - -} +/* Lifetime Sanitizer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include +#include +#include +#include "Concurrency/SpinLock.h" +#include "LifetimeSanitizer.h" + +#ifdef _WIN32 +#include +#endif + + + +namespace PokemonAutomation{ + + +#ifdef PA_SANITIZER_ENABLE + +//#define PA_SANITIZER_PRINT_ALL +const std::set SANITIZER_FILTER = { +// "MultiSwitchProgramSession", +// "MultiSwitchProgramWidget2", +// "ControllerFeatures", +}; + +SpinLock sanitizer_lock; +std::set sanitizer_map; + + +std::atomic LifetimeSanitizer_disabled(false); + +void LifetimeSanitizer::disable(){ + WriteSpinLock lg(sanitizer_lock); + LifetimeSanitizer_disabled.store(true, std::memory_order_relaxed); + sanitizer_map.clear(); +} + +PA_NO_INLINE void LifetimeSanitizer::terminate_with_dump(){ + // Intentionally crash the program here and let the crash dump deal with + // the error reporting. + +#ifdef _WIN32 + Sleep(500); +#endif + + std::cerr << (char*)nullptr << std::endl; +} + + + + +LifetimeSanitizer::LifetimeSanitizer(const char* name){ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + internal_construct(name); +} +LifetimeSanitizer::~LifetimeSanitizer(){ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + internal_destruct(); +} + + +LifetimeSanitizer::LifetimeSanitizer(LifetimeSanitizer&& x){ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + x.check_usage(); + internal_construct(x.m_name); +} +void LifetimeSanitizer::operator=(LifetimeSanitizer&& x){ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + check_usage(); + x.check_usage(); +} +LifetimeSanitizer::LifetimeSanitizer(const LifetimeSanitizer& x){ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + x.check_usage(); + internal_construct(x.m_name); +} +void LifetimeSanitizer::operator=(const LifetimeSanitizer& x){ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + check_usage(); + x.check_usage(); +} + + + +void LifetimeSanitizer::check_usage() const{ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + ReadSpinLock lg(sanitizer_lock); + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Using: " << this << " : " << m_name << std::endl; + } + auto iter = sanitizer_map.find(this); + if (iter == sanitizer_map.end()){ + std::cerr << "Use non-existent: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + if (m_token != SANITIZER_TOKEN || m_self != this){ + std::cerr << "Use corrupted: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } +} +void LifetimeSanitizer::start_using() const{ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + ReadSpinLock lg(sanitizer_lock); + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Start using: " << this << " : " << m_name << std::endl; + } + auto iter = sanitizer_map.find(this); + if (iter == sanitizer_map.end()){ + std::cerr << "Start using non-existent: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + if (m_token != SANITIZER_TOKEN || m_self != this){ + std::cerr << "Start using corrupted: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + m_use_counter++; +} +void LifetimeSanitizer::done_using() const{ + if (LifetimeSanitizer_disabled.load(std::memory_order_relaxed)){ + return; + } + ReadSpinLock lg(sanitizer_lock); + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Done using: " << this << " : " << m_name << std::endl; + } + auto iter = sanitizer_map.find(this); + if (iter == sanitizer_map.end()){ + std::cerr << "Done using non-existent: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + if (m_token != SANITIZER_TOKEN || m_self != this){ + std::cerr << "Done using corrupted: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + m_use_counter--; +} + + +void LifetimeSanitizer::internal_construct(const char* name){ + WriteSpinLock lg(sanitizer_lock); + if (SANITIZER_FILTER.contains(name)){ + std::cout << "LifetimeSanitizer - Allocating: " << this << " : " << name << std::endl; + } + + auto iter = sanitizer_map.find(this); + if (iter != sanitizer_map.end()){ + std::cerr << "LifetimeSanitizer - Double allocation: " << this << " : " << name << std::endl; + terminate_with_dump(); + } + sanitizer_map.insert(this); + + m_token = SANITIZER_TOKEN; + m_self = this; + m_name = name; +} +void LifetimeSanitizer::internal_destruct(){ + WriteSpinLock lg(sanitizer_lock); + if (SANITIZER_FILTER.contains(m_name)){ + std::cout << "LifetimeSanitizer - Freeing: " << this << " : " << m_name << std::endl; + } + + auto iter = sanitizer_map.find(this); + if (iter == sanitizer_map.end()){ + std::cerr << "LifetimeSanitizer - Free non-existent: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + sanitizer_map.erase(this); + + if (m_token != SANITIZER_TOKEN || m_self != this){ + std::cerr << "LifetimeSanitizer - Free non-existent: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + if (m_use_counter != 0){ + std::cerr << "LifetimeSanitizer - Freeing while in-use: " << this << " : " << m_name << std::endl; + terminate_with_dump(); + } + m_self = nullptr; +} +#endif + + + + + + +} diff --git a/Common/Cpp/LifetimeSanitizer.h b/Common/Cpp/LifetimeSanitizer.h index 9e0ff56aa1..58ba53f781 100644 --- a/Common/Cpp/LifetimeSanitizer.h +++ b/Common/Cpp/LifetimeSanitizer.h @@ -1,101 +1,101 @@ -/* Lifetime Sanitizer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_LifetimeSanitizer_H -#define PokemonAutomation_LifetimeSanitizer_H - -#include -#include - -#define PA_SANITIZER_ENABLE - -namespace PokemonAutomation{ - - -#ifdef PA_SANITIZER_ENABLE - - -class LifetimeSanitizer{ - static constexpr uint64_t SANITIZER_TOKEN = 0x7db76f7a6a834ef0; - - -public: - // Rule of 5 - - ~LifetimeSanitizer(); - LifetimeSanitizer(LifetimeSanitizer&& x); - void operator=(LifetimeSanitizer&& x); - LifetimeSanitizer(const LifetimeSanitizer& x); - void operator=(const LifetimeSanitizer& x); - - -public: - // Constructor - - LifetimeSanitizer(const char* name = "(unnamed class)"); - - -public: - // Misc. - - class CheckScope{ - public: - CheckScope(const LifetimeSanitizer& parent) - : m_parent(parent) - { - parent.check_usage(); - } - ~CheckScope(){ - m_parent.check_usage(); - } - - private: - const LifetimeSanitizer& m_parent; - }; - - void check_usage() const; - void start_using() const; - void done_using() const; - CheckScope check_scope() const{ - return CheckScope(*this); - } - - static void disable(); - - -private: - static void terminate_with_dump(); - void internal_construct(const char* name); - void internal_destruct(); - - -private: - uint64_t m_token; - void* m_self; - const char* m_name; - mutable size_t m_use_counter = 0; -}; - - -#else -class LifetimeSanitizer{ -public: - LifetimeSanitizer(const char* = ""){} - - void check_usage() const{} - static void disable(){} - - struct CheckScope{}; - CheckScope check_scope() const{ - return CheckScope(); - } -}; -#endif - - - -} -#endif +/* Lifetime Sanitizer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_LifetimeSanitizer_H +#define PokemonAutomation_LifetimeSanitizer_H + +#include +#include + +#define PA_SANITIZER_ENABLE + +namespace PokemonAutomation{ + + +#ifdef PA_SANITIZER_ENABLE + + +class LifetimeSanitizer{ + static constexpr uint64_t SANITIZER_TOKEN = 0x7db76f7a6a834ef0; + + +public: + // Rule of 5 + + ~LifetimeSanitizer(); + LifetimeSanitizer(LifetimeSanitizer&& x); + void operator=(LifetimeSanitizer&& x); + LifetimeSanitizer(const LifetimeSanitizer& x); + void operator=(const LifetimeSanitizer& x); + + +public: + // Constructor + + LifetimeSanitizer(const char* name = "(unnamed class)"); + + +public: + // Misc. + + class CheckScope{ + public: + CheckScope(const LifetimeSanitizer& parent) + : m_parent(parent) + { + parent.check_usage(); + } + ~CheckScope(){ + m_parent.check_usage(); + } + + private: + const LifetimeSanitizer& m_parent; + }; + + void check_usage() const; + void start_using() const; + void done_using() const; + CheckScope check_scope() const{ + return CheckScope(*this); + } + + static void disable(); + + +private: + static void terminate_with_dump(); + void internal_construct(const char* name); + void internal_destruct(); + + +private: + uint64_t m_token; + void* m_self; + const char* m_name; + mutable size_t m_use_counter = 0; +}; + + +#else +class LifetimeSanitizer{ +public: + LifetimeSanitizer(const char* = ""){} + + void check_usage() const{} + static void disable(){} + + struct CheckScope{}; + CheckScope check_scope() const{ + return CheckScope(); + } +}; +#endif + + + +} +#endif diff --git a/Common/Cpp/ListenerSet.h b/Common/Cpp/ListenerSet.h index 40ed067ca3..8e39c1a9fe 100644 --- a/Common/Cpp/ListenerSet.h +++ b/Common/Cpp/ListenerSet.h @@ -1,119 +1,119 @@ -/* Listener Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ListenerSet_H -#define PokemonAutomation_ListenerSet_H - -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -class ListenerSet{ -public: - bool empty() const{ - return m_count.load(std::memory_order_relaxed) == 0; - } - size_t count_unique() const{ - return m_count.load(std::memory_order_relaxed); - } - - void add(ListenerType& listener){ - WriteSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - m_listeners[&listener]++; - m_count.store(m_listeners.size(), std::memory_order_relaxed); - } - void remove(ListenerType& listener){ - WriteSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - auto iter = m_listeners.find(&listener); - if (iter == m_listeners.end()){ - return; - } - if (--iter->second == 0){ - m_listeners.erase(iter); - } - m_count.store(m_listeners.size(), std::memory_order_relaxed); - } - - template - void run_lambda_unique(Lambda&& lambda){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - lambda(*item.first); - } - } - template - void run_lambda_with_duplicates(Lambda&& lambda){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - ListenerType& listener = *item.first; - size_t count = item.second; - do{ - lambda(listener); - }while (--count); - } - } - - template - void run_method_unique(Function function, Args&&... args){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - (item.first->*function)(std::forward(args)...); - } - } - template - void run_method_with_duplicates(Function function, Args&&... args){ - if (empty()){ - return; - } - ReadSpinLock lg(m_lock); -// std::lock_guard lg(m_lock); - for (auto& item : m_listeners){ - ListenerType& listener = *item.first; - size_t count = item.second; - do{ - (listener->*function)(std::forward(args)...); - }while (--count); - } - } - -private: - // Optimization. Keep an atomic version of the count. This will let us - // skip the lock when there are no listeners. - std::atomic m_count; - - mutable SpinLock m_lock; -// mutable std::mutex m_lock; - std::map m_listeners; -}; - - - - -} -#endif +/* Listener Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ListenerSet_H +#define PokemonAutomation_ListenerSet_H + +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +template +class ListenerSet{ +public: + bool empty() const{ + return m_count.load(std::memory_order_relaxed) == 0; + } + size_t count_unique() const{ + return m_count.load(std::memory_order_relaxed); + } + + void add(ListenerType& listener){ + WriteSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + m_listeners[&listener]++; + m_count.store(m_listeners.size(), std::memory_order_relaxed); + } + void remove(ListenerType& listener){ + WriteSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + auto iter = m_listeners.find(&listener); + if (iter == m_listeners.end()){ + return; + } + if (--iter->second == 0){ + m_listeners.erase(iter); + } + m_count.store(m_listeners.size(), std::memory_order_relaxed); + } + + template + void run_lambda_unique(Lambda&& lambda){ + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + lambda(*item.first); + } + } + template + void run_lambda_with_duplicates(Lambda&& lambda){ + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + ListenerType& listener = *item.first; + size_t count = item.second; + do{ + lambda(listener); + }while (--count); + } + } + + template + void run_method_unique(Function function, Args&&... args){ + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + (item.first->*function)(std::forward(args)...); + } + } + template + void run_method_with_duplicates(Function function, Args&&... args){ + if (empty()){ + return; + } + ReadSpinLock lg(m_lock); +// std::lock_guard lg(m_lock); + for (auto& item : m_listeners){ + ListenerType& listener = *item.first; + size_t count = item.second; + do{ + (listener->*function)(std::forward(args)...); + }while (--count); + } + } + +private: + // Optimization. Keep an atomic version of the count. This will let us + // skip the lock when there are no listeners. + std::atomic m_count; + + mutable SpinLock m_lock; +// mutable std::mutex m_lock; + std::map m_listeners; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/BatchOption.cpp b/Common/Cpp/Options/BatchOption.cpp index 4f90be20fa..1508bfa55a 100644 --- a/Common/Cpp/Options/BatchOption.cpp +++ b/Common/Cpp/Options/BatchOption.cpp @@ -1,108 +1,108 @@ -/* Batch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "BatchOption.h" - -namespace PokemonAutomation{ - - -struct BatchOption::Data{ - const bool m_horizontal; - std::vector> m_options; - - Data(bool horizontal) - : m_horizontal(horizontal) - {} -}; - - - -BatchOption::~BatchOption() = default; -BatchOption::BatchOption(LockMode lock_while_program_is_running, bool horizontal) - : ConfigOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, horizontal) -{} -void BatchOption::add_option(ConfigOption& option, std::string serialization_string){ - m_data->m_options.emplace_back(&option, std::move(serialization_string)); -} - -void BatchOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - for (auto& item : m_data->m_options){ - if (!item.second.empty()){ - const JsonValue* value = obj->get_value(item.second); - if (value){ - item.first->load_json(*value); - } - } - } -} -JsonValue BatchOption::to_json() const{ - JsonObject obj; - for (auto& item : m_data->m_options){ - if (!item.second.empty()){ - obj[item.second] = item.first->to_json(); - } - } - return obj; -} - -std::string BatchOption::check_validity() const{ - for (const auto& item : m_data->m_options){ - std::string error = item.first->check_validity(); - if (!error.empty()){ - return error; - } - } - return std::string(); -} -void BatchOption::restore_defaults(){ - for (const auto& item : m_data->m_options){ - item.first->restore_defaults(); - } -} -void BatchOption::reset_state(){ - for (const auto& item : m_data->m_options){ - item.first->reset_state(); - } -} -void BatchOption::report_program_state(bool program_is_running){ - ConfigOption::report_program_state(program_is_running); - for (const auto& item : m_data->m_options){ - item.first->report_program_state(program_is_running); - } -} - -bool BatchOption::horizontal() const{ - return m_data->m_horizontal; -} -FixedLimitVector BatchOption::options() const{ - FixedLimitVector ret(m_data->m_options.size()); - for (const auto& item : m_data->m_options){ - ret.emplace_back(item.first); - } - return ret; -} - - - - -template class FixedLimitVector; - - - - -} +/* Batch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "BatchOption.h" + +namespace PokemonAutomation{ + + +struct BatchOption::Data{ + const bool m_horizontal; + std::vector> m_options; + + Data(bool horizontal) + : m_horizontal(horizontal) + {} +}; + + + +BatchOption::~BatchOption() = default; +BatchOption::BatchOption(LockMode lock_while_program_is_running, bool horizontal) + : ConfigOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, horizontal) +{} +void BatchOption::add_option(ConfigOption& option, std::string serialization_string){ + m_data->m_options.emplace_back(&option, std::move(serialization_string)); +} + +void BatchOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + for (auto& item : m_data->m_options){ + if (!item.second.empty()){ + const JsonValue* value = obj->get_value(item.second); + if (value){ + item.first->load_json(*value); + } + } + } +} +JsonValue BatchOption::to_json() const{ + JsonObject obj; + for (auto& item : m_data->m_options){ + if (!item.second.empty()){ + obj[item.second] = item.first->to_json(); + } + } + return obj; +} + +std::string BatchOption::check_validity() const{ + for (const auto& item : m_data->m_options){ + std::string error = item.first->check_validity(); + if (!error.empty()){ + return error; + } + } + return std::string(); +} +void BatchOption::restore_defaults(){ + for (const auto& item : m_data->m_options){ + item.first->restore_defaults(); + } +} +void BatchOption::reset_state(){ + for (const auto& item : m_data->m_options){ + item.first->reset_state(); + } +} +void BatchOption::report_program_state(bool program_is_running){ + ConfigOption::report_program_state(program_is_running); + for (const auto& item : m_data->m_options){ + item.first->report_program_state(program_is_running); + } +} + +bool BatchOption::horizontal() const{ + return m_data->m_horizontal; +} +FixedLimitVector BatchOption::options() const{ + FixedLimitVector ret(m_data->m_options.size()); + for (const auto& item : m_data->m_options){ + ret.emplace_back(item.first); + } + return ret; +} + + + + +template class FixedLimitVector; + + + + +} diff --git a/Common/Cpp/Options/BatchOption.h b/Common/Cpp/Options/BatchOption.h index 40ea5d447f..1718270dc2 100644 --- a/Common/Cpp/Options/BatchOption.h +++ b/Common/Cpp/Options/BatchOption.h @@ -1,56 +1,56 @@ -/* Batch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_BatchOption_H -#define PokemonAutomation_Options_BatchOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - -// A ConfigOption that groups one or more options. -class BatchOption : public ConfigOption{ -public: - ~BatchOption(); - BatchOption(LockMode lock_while_program_is_running, bool horizontal = false); - -public: - // This is not thread-safe with the rest of this class. You must - // fully initialize the class (by adding all the options it will ever have) - // before you start using it. - void add_option(ConfigOption& option, std::string serialization_string); -#define PA_ADD_STATIC(x) add_option(x, "") -#define PA_ADD_OPTION(x) add_option(x, #x) - - -public: - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - std::string check_validity() const override; - virtual void restore_defaults() override; - virtual void reset_state() override; - - virtual void report_program_state(bool program_is_running) override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - bool horizontal() const; - FixedLimitVector options() const; - - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Batch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_BatchOption_H +#define PokemonAutomation_Options_BatchOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + +// A ConfigOption that groups one or more options. +class BatchOption : public ConfigOption{ +public: + ~BatchOption(); + BatchOption(LockMode lock_while_program_is_running, bool horizontal = false); + +public: + // This is not thread-safe with the rest of this class. You must + // fully initialize the class (by adding all the options it will ever have) + // before you start using it. + void add_option(ConfigOption& option, std::string serialization_string); +#define PA_ADD_STATIC(x) add_option(x, "") +#define PA_ADD_OPTION(x) add_option(x, #x) + + +public: + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + std::string check_validity() const override; + virtual void restore_defaults() override; + virtual void reset_state() override; + + virtual void report_program_state(bool program_is_running) override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + bool horizontal() const; + FixedLimitVector options() const; + + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/BooleanCheckBoxOption.cpp b/Common/Cpp/Options/BooleanCheckBoxOption.cpp index 02d780ff22..4c5a816418 100644 --- a/Common/Cpp/Options/BooleanCheckBoxOption.cpp +++ b/Common/Cpp/Options/BooleanCheckBoxOption.cpp @@ -1,98 +1,98 @@ -/* Boolean Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "BooleanCheckBoxOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct BooleanCheckBoxCell::Data{ - const bool m_default; - std::atomic m_current; - - Data(bool default_value, bool current_value) - : m_default(default_value) - , m_current(current_value) - {} -}; - -BooleanCheckBoxCell::~BooleanCheckBoxCell() = default; -BooleanCheckBoxCell::BooleanCheckBoxCell(const BooleanCheckBoxCell& x) - : ConfigOption(x) - , m_data(CONSTRUCT_TOKEN, x.default_value(), x.current_value()) -{} -BooleanCheckBoxCell::BooleanCheckBoxCell( - LockMode lock_while_running, - bool default_value, bool current_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, default_value, current_value) -{} -BooleanCheckBoxCell::BooleanCheckBoxCell( - LockMode lock_while_running, - bool default_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, default_value, default_value) -{} - -bool BooleanCheckBoxCell::default_value() const{ - return m_data->m_default; -} -bool BooleanCheckBoxCell::current_value() const{ - return m_data->m_current.load(std::memory_order_relaxed); -} -BooleanCheckBoxCell::operator bool() const{ - return m_data->m_current.load(std::memory_order_relaxed); -} -void BooleanCheckBoxCell::operator=(bool x){ - if (x != m_data->m_current.exchange(x, std::memory_order_relaxed)){ - report_value_changed(this); - } -} -void BooleanCheckBoxCell::load_json(const JsonValue& json){ - bool value; - if (json.read_boolean(value)){ - *this = value; - } -} -JsonValue BooleanCheckBoxCell::to_json() const{ - return (bool)*this; -} -void BooleanCheckBoxCell::restore_defaults(){ - *this = m_data->m_default; -} - - - - -BooleanCheckBoxOption::BooleanCheckBoxOption( - std::string label, - LockMode lock_while_running, - bool default_value -) - : BooleanCheckBoxCell(lock_while_running, default_value) - , m_label(std::move(label)) -{} -BooleanCheckBoxOption::BooleanCheckBoxOption( - std::string label, - LockMode lock_while_running, - bool default_value, bool value -) - : BooleanCheckBoxCell(lock_while_running, default_value, value) - , m_label(std::move(label)) -{} - - - -} +/* Boolean Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "BooleanCheckBoxOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct BooleanCheckBoxCell::Data{ + const bool m_default; + std::atomic m_current; + + Data(bool default_value, bool current_value) + : m_default(default_value) + , m_current(current_value) + {} +}; + +BooleanCheckBoxCell::~BooleanCheckBoxCell() = default; +BooleanCheckBoxCell::BooleanCheckBoxCell(const BooleanCheckBoxCell& x) + : ConfigOption(x) + , m_data(CONSTRUCT_TOKEN, x.default_value(), x.current_value()) +{} +BooleanCheckBoxCell::BooleanCheckBoxCell( + LockMode lock_while_running, + bool default_value, bool current_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, default_value, current_value) +{} +BooleanCheckBoxCell::BooleanCheckBoxCell( + LockMode lock_while_running, + bool default_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, default_value, default_value) +{} + +bool BooleanCheckBoxCell::default_value() const{ + return m_data->m_default; +} +bool BooleanCheckBoxCell::current_value() const{ + return m_data->m_current.load(std::memory_order_relaxed); +} +BooleanCheckBoxCell::operator bool() const{ + return m_data->m_current.load(std::memory_order_relaxed); +} +void BooleanCheckBoxCell::operator=(bool x){ + if (x != m_data->m_current.exchange(x, std::memory_order_relaxed)){ + report_value_changed(this); + } +} +void BooleanCheckBoxCell::load_json(const JsonValue& json){ + bool value; + if (json.read_boolean(value)){ + *this = value; + } +} +JsonValue BooleanCheckBoxCell::to_json() const{ + return (bool)*this; +} +void BooleanCheckBoxCell::restore_defaults(){ + *this = m_data->m_default; +} + + + + +BooleanCheckBoxOption::BooleanCheckBoxOption( + std::string label, + LockMode lock_while_running, + bool default_value +) + : BooleanCheckBoxCell(lock_while_running, default_value) + , m_label(std::move(label)) +{} +BooleanCheckBoxOption::BooleanCheckBoxOption( + std::string label, + LockMode lock_while_running, + bool default_value, bool value +) + : BooleanCheckBoxCell(lock_while_running, default_value, value) + , m_label(std::move(label)) +{} + + + +} diff --git a/Common/Cpp/Options/BooleanCheckBoxOption.h b/Common/Cpp/Options/BooleanCheckBoxOption.h index 8039c523d0..e3260c26f3 100644 --- a/Common/Cpp/Options/BooleanCheckBoxOption.h +++ b/Common/Cpp/Options/BooleanCheckBoxOption.h @@ -1,82 +1,82 @@ -/* Boolean Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_BooleanCheckBoxOption_H -#define PokemonAutomation_Options_BooleanCheckBoxOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - - -class BooleanCheckBoxCell : public ConfigOption{ -public: - ~BooleanCheckBoxCell(); - BooleanCheckBoxCell(const BooleanCheckBoxCell& x); - BooleanCheckBoxCell( - LockMode lock_while_running, - bool default_value, bool current_value - ); - -public: - BooleanCheckBoxCell( - LockMode lock_while_running, - bool default_value - ); - - bool default_value() const; - bool current_value() const; - - operator bool() const; - void operator=(bool x); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - struct Data; - Pimpl m_data; -}; - - - - -class BooleanCheckBoxOption : public BooleanCheckBoxCell{ -public: - BooleanCheckBoxOption(const BooleanCheckBoxOption& x) = delete; - BooleanCheckBoxOption( - std::string label, - LockMode lock_while_running, - bool default_value - ); - BooleanCheckBoxOption( - std::string label, - LockMode lock_while_running, - bool default_value, bool value - ); - - const std::string& label() const{ return m_label; } - using BooleanCheckBoxCell::operator=; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - - - -} -#endif - +/* Boolean Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_BooleanCheckBoxOption_H +#define PokemonAutomation_Options_BooleanCheckBoxOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + + +class BooleanCheckBoxCell : public ConfigOption{ +public: + ~BooleanCheckBoxCell(); + BooleanCheckBoxCell(const BooleanCheckBoxCell& x); + BooleanCheckBoxCell( + LockMode lock_while_running, + bool default_value, bool current_value + ); + +public: + BooleanCheckBoxCell( + LockMode lock_while_running, + bool default_value + ); + + bool default_value() const; + bool current_value() const; + + operator bool() const; + void operator=(bool x); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + struct Data; + Pimpl m_data; +}; + + + + +class BooleanCheckBoxOption : public BooleanCheckBoxCell{ +public: + BooleanCheckBoxOption(const BooleanCheckBoxOption& x) = delete; + BooleanCheckBoxOption( + std::string label, + LockMode lock_while_running, + bool default_value + ); + BooleanCheckBoxOption( + std::string label, + LockMode lock_while_running, + bool default_value, bool value + ); + + const std::string& label() const{ return m_label; } + using BooleanCheckBoxCell::operator=; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + + + +} +#endif + diff --git a/Common/Cpp/Options/ButtonOption.cpp b/Common/Cpp/Options/ButtonOption.cpp index 5a800fede0..7ce22c01f8 100644 --- a/Common/Cpp/Options/ButtonOption.cpp +++ b/Common/Cpp/Options/ButtonOption.cpp @@ -1,183 +1,183 @@ -/* Button Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -//#include "Common/Cpp/Json/JsonValue.h" -#include "ButtonOption.h" - -namespace PokemonAutomation{ - - -struct ButtonCell::Data{ - std::atomic m_state; - - mutable SpinLock m_text_lock; - std::string m_text; - - std::atomic m_button_height; - std::atomic m_text_size; - - mutable SpinLock m_listener_lock; - std::set m_listeners; - - Data( - Enabled state, - std::string text, - int button_height, - int text_size - ) - : m_state(state) - , m_text(std::move(text)) - , m_button_height(button_height) - , m_text_size(text_size) - {} - - std::string text() const{ - ReadSpinLock lg(m_text_lock); - return m_text; - } -}; - -ButtonCell::~ButtonCell() = default; -ButtonCell::ButtonCell(const ButtonCell& x) - : ConfigOption(x) - , m_data( - CONSTRUCT_TOKEN, - x.m_data->m_state, - x.m_data->text(), - x.m_data->m_button_height.load(std::memory_order_relaxed), - x.m_data->m_text_size.load(std::memory_order_relaxed) - ) -{} -ButtonCell::ButtonCell( - std::string text, - int button_height, - int text_size -) - : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) - , m_data(CONSTRUCT_TOKEN, ButtonCell::ENABLED, std::move(text), button_height, text_size) -{} -ButtonCell::ButtonCell( - Enabled state, - std::string text, - int button_height, - int text_size -) - : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) - , m_data(CONSTRUCT_TOKEN, state, std::move(text), button_height, text_size) -{} - -void ButtonCell::add_listener(ButtonListener& listener){ - WriteSpinLock lg(m_data->m_listener_lock); - m_data->m_listeners.insert(&listener); -} -void ButtonCell::remove_listener(ButtonListener& listener){ - WriteSpinLock lg(m_data->m_listener_lock); - m_data->m_listeners.erase(&listener); -} - -bool ButtonCell::is_enabled() const{ - return m_data->m_state.load(std::memory_order_relaxed) == Enabled::ENABLED; -} -void ButtonCell::set_enabled(bool enabled){ - Enabled e = enabled ? ENABLED : DISABLED; - if (e != m_data->m_state.exchange(e, std::memory_order_relaxed)){ - report_value_changed(this); - } -} -std::string ButtonCell::text() const{ - return m_data->text(); -} -int ButtonCell::button_height() const{ - return m_data->m_button_height.load(std::memory_order_relaxed); -} -int ButtonCell::text_size() const{ - return m_data->m_text_size.load(std::memory_order_relaxed); -} -void ButtonCell::set_text(std::string text){ - { - WriteSpinLock lg(m_data->m_text_lock); - if (text == m_data->m_text){ - return; - } - m_data->m_text = std::move(text); - } - report_value_changed(this); -} - -void ButtonCell::press_button(){ - ReadSpinLock lg(m_data->m_listener_lock); - for (ButtonListener* listener : m_data->m_listeners){ - listener->on_press(); - } -} - -//void ButtonCell::restore_defaults(){ -// *this = m_data->m_default; -//} - - - - - - -struct ButtonOption::Data{ - mutable SpinLock m_label_lock; - std::string m_label; - - Data(std::string label) - : m_label(std::move(label)) - {} -}; - - -ButtonOption::~ButtonOption() = default; -ButtonOption::ButtonOption( - std::string label, - std::string text, - int button_height, - int text_size -) - : ButtonCell(std::move(text), button_height, text_size) - , m_data(CONSTRUCT_TOKEN, std::move(label)) -{} -ButtonOption::ButtonOption( - std::string label, - Enabled state, - std::string text, - int button_height, - int text_size -) - : ButtonCell(state, std::move(text), button_height, text_size) - , m_data(CONSTRUCT_TOKEN, std::move(label)) -{} - - -std::string ButtonOption::label() const{ - ReadSpinLock lg(m_data->m_label_lock); - return m_data->m_label; -} -void ButtonOption::set_label(std::string label){ - { - WriteSpinLock lg(m_data->m_label_lock); - if (label == m_data->m_label){ - return; - } - m_data->m_label = std::move(label); - } - report_value_changed(this); -} - - - - - - - -} +/* Button Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +//#include "Common/Cpp/Json/JsonValue.h" +#include "ButtonOption.h" + +namespace PokemonAutomation{ + + +struct ButtonCell::Data{ + std::atomic m_state; + + mutable SpinLock m_text_lock; + std::string m_text; + + std::atomic m_button_height; + std::atomic m_text_size; + + mutable SpinLock m_listener_lock; + std::set m_listeners; + + Data( + Enabled state, + std::string text, + int button_height, + int text_size + ) + : m_state(state) + , m_text(std::move(text)) + , m_button_height(button_height) + , m_text_size(text_size) + {} + + std::string text() const{ + ReadSpinLock lg(m_text_lock); + return m_text; + } +}; + +ButtonCell::~ButtonCell() = default; +ButtonCell::ButtonCell(const ButtonCell& x) + : ConfigOption(x) + , m_data( + CONSTRUCT_TOKEN, + x.m_data->m_state, + x.m_data->text(), + x.m_data->m_button_height.load(std::memory_order_relaxed), + x.m_data->m_text_size.load(std::memory_order_relaxed) + ) +{} +ButtonCell::ButtonCell( + std::string text, + int button_height, + int text_size +) + : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) + , m_data(CONSTRUCT_TOKEN, ButtonCell::ENABLED, std::move(text), button_height, text_size) +{} +ButtonCell::ButtonCell( + Enabled state, + std::string text, + int button_height, + int text_size +) + : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) + , m_data(CONSTRUCT_TOKEN, state, std::move(text), button_height, text_size) +{} + +void ButtonCell::add_listener(ButtonListener& listener){ + WriteSpinLock lg(m_data->m_listener_lock); + m_data->m_listeners.insert(&listener); +} +void ButtonCell::remove_listener(ButtonListener& listener){ + WriteSpinLock lg(m_data->m_listener_lock); + m_data->m_listeners.erase(&listener); +} + +bool ButtonCell::is_enabled() const{ + return m_data->m_state.load(std::memory_order_relaxed) == Enabled::ENABLED; +} +void ButtonCell::set_enabled(bool enabled){ + Enabled e = enabled ? ENABLED : DISABLED; + if (e != m_data->m_state.exchange(e, std::memory_order_relaxed)){ + report_value_changed(this); + } +} +std::string ButtonCell::text() const{ + return m_data->text(); +} +int ButtonCell::button_height() const{ + return m_data->m_button_height.load(std::memory_order_relaxed); +} +int ButtonCell::text_size() const{ + return m_data->m_text_size.load(std::memory_order_relaxed); +} +void ButtonCell::set_text(std::string text){ + { + WriteSpinLock lg(m_data->m_text_lock); + if (text == m_data->m_text){ + return; + } + m_data->m_text = std::move(text); + } + report_value_changed(this); +} + +void ButtonCell::press_button(){ + ReadSpinLock lg(m_data->m_listener_lock); + for (ButtonListener* listener : m_data->m_listeners){ + listener->on_press(); + } +} + +//void ButtonCell::restore_defaults(){ +// *this = m_data->m_default; +//} + + + + + + +struct ButtonOption::Data{ + mutable SpinLock m_label_lock; + std::string m_label; + + Data(std::string label) + : m_label(std::move(label)) + {} +}; + + +ButtonOption::~ButtonOption() = default; +ButtonOption::ButtonOption( + std::string label, + std::string text, + int button_height, + int text_size +) + : ButtonCell(std::move(text), button_height, text_size) + , m_data(CONSTRUCT_TOKEN, std::move(label)) +{} +ButtonOption::ButtonOption( + std::string label, + Enabled state, + std::string text, + int button_height, + int text_size +) + : ButtonCell(state, std::move(text), button_height, text_size) + , m_data(CONSTRUCT_TOKEN, std::move(label)) +{} + + +std::string ButtonOption::label() const{ + ReadSpinLock lg(m_data->m_label_lock); + return m_data->m_label; +} +void ButtonOption::set_label(std::string label){ + { + WriteSpinLock lg(m_data->m_label_lock); + if (label == m_data->m_label){ + return; + } + m_data->m_label = std::move(label); + } + report_value_changed(this); +} + + + + + + + +} diff --git a/Common/Cpp/Options/ButtonOption.h b/Common/Cpp/Options/ButtonOption.h index 76bab93fd8..527ec7b44a 100644 --- a/Common/Cpp/Options/ButtonOption.h +++ b/Common/Cpp/Options/ButtonOption.h @@ -1,109 +1,109 @@ -/* Button Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_ButtonOption_H -#define PokemonAutomation_Options_ButtonOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -struct ButtonListener{ - virtual void on_press() = 0; -}; - - -class ButtonCell : public ConfigOption{ -public: - enum Enabled : bool{ - DISABLED, - ENABLED, - }; - -public: - ~ButtonCell(); - ButtonCell(const ButtonCell& x); - ButtonCell( - std::string text, - int button_height = 0, - int text_size = 0 - ); - ButtonCell( - Enabled state, - std::string text, - int button_height = 0, - int text_size = 0 - ); - - using ConfigOption::add_listener; - using ConfigOption::remove_listener; - void add_listener(ButtonListener& listener); - void remove_listener(ButtonListener& listener); - -public: - bool is_enabled() const; - void set_enabled(bool enabled); - - std::string text() const; - void set_text(std::string text); - - int button_height() const; - int text_size() const; - - void press_button(); - -// virtual void load_json(const JsonValue& json) override; -// virtual JsonValue to_json() const override; - -// virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - - -protected: - struct Data; - Pimpl m_data; -}; - - - -class ButtonOption : public ButtonCell{ -public: - ~ButtonOption(); - ButtonOption(const ButtonOption& x) = delete; - ButtonOption( - std::string label, - std::string text, - int button_height = 0, - int text_size = 0 - ); - ButtonOption( - std::string label, - Enabled state, - std::string text, - int button_height = 0, - int text_size = 0 - ); - - std::string label() const; - void set_label(std::string label); - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Button Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_ButtonOption_H +#define PokemonAutomation_Options_ButtonOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +struct ButtonListener{ + virtual void on_press() = 0; +}; + + +class ButtonCell : public ConfigOption{ +public: + enum Enabled : bool{ + DISABLED, + ENABLED, + }; + +public: + ~ButtonCell(); + ButtonCell(const ButtonCell& x); + ButtonCell( + std::string text, + int button_height = 0, + int text_size = 0 + ); + ButtonCell( + Enabled state, + std::string text, + int button_height = 0, + int text_size = 0 + ); + + using ConfigOption::add_listener; + using ConfigOption::remove_listener; + void add_listener(ButtonListener& listener); + void remove_listener(ButtonListener& listener); + +public: + bool is_enabled() const; + void set_enabled(bool enabled); + + std::string text() const; + void set_text(std::string text); + + int button_height() const; + int text_size() const; + + void press_button(); + +// virtual void load_json(const JsonValue& json) override; +// virtual JsonValue to_json() const override; + +// virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + + +protected: + struct Data; + Pimpl m_data; +}; + + + +class ButtonOption : public ButtonCell{ +public: + ~ButtonOption(); + ButtonOption(const ButtonOption& x) = delete; + ButtonOption( + std::string label, + std::string text, + int button_height = 0, + int text_size = 0 + ); + ButtonOption( + std::string label, + Enabled state, + std::string text, + int button_height = 0, + int text_size = 0 + ); + + std::string label() const; + void set_label(std::string label); + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/ColorOption.cpp b/Common/Cpp/Options/ColorOption.cpp index 8d6a61dce9..a4cdbb5f32 100644 --- a/Common/Cpp/Options/ColorOption.cpp +++ b/Common/Cpp/Options/ColorOption.cpp @@ -1,126 +1,126 @@ -/* Color Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" - #include "ColorOption.h" - -namespace PokemonAutomation{ - - -ColorCell::ColorCell(const ColorCell& x) - : ConfigOption(x) - , m_default_value(x.m_default_value) - , m_current_value(x) -{} -ColorCell::ColorCell( - LockMode lock_while_running, - bool has_alpha, - uint32_t default_value, uint32_t current_value -) - : ConfigOption(lock_while_running) - , m_has_alpha(has_alpha) - , m_default_value(default_value) - , m_current_value(current_value) -{ - if (!m_has_alpha){ - m_default_value &= 0x00ffffff; - m_current_value &= 0x00ffffff; - } -} -uint32_t ColorCell::default_value() const{ - return m_default_value; -} -std::string ColorCell::to_str() const{ - return color_to_str(*this, m_has_alpha); -} -std::string ColorCell::color_to_str(uint32_t color, bool has_alpha){ - static const char HEX_DIGITS[] = "0123456789ABCDEF"; - std::string str; - if (has_alpha){ - str += HEX_DIGITS[(color >> 28) & 0xf]; - str += HEX_DIGITS[(color >> 24) & 0xf]; - } - str += HEX_DIGITS[(color >> 20) & 0xf]; - str += HEX_DIGITS[(color >> 16) & 0xf]; - str += HEX_DIGITS[(color >> 12) & 0xf]; - str += HEX_DIGITS[(color >> 8) & 0xf]; - str += HEX_DIGITS[(color >> 4) & 0xf]; - str += HEX_DIGITS[(color >> 0) & 0xf]; - return str; -} -ColorCell::operator uint32_t() const{ - return m_current_value.load(std::memory_order_relaxed); -} -void ColorCell::set(uint32_t x){ - if (!m_has_alpha){ - x &= 0x00ffffff; - } - if (x != m_current_value.exchange(x, std::memory_order_relaxed)){ - report_value_changed(this); - } -} -void ColorCell::set(const std::string& str){ - size_t max_digits = m_has_alpha ? 8 : 6; - - uint32_t x = 0; - size_t count = 0; - for (char ch : str){ - if (count >= max_digits){ - break; - } - switch (ch){ - case '\0': - break; - case '-': - case ':': - case ' ': - continue; - } - - if ('0' <= ch && ch <= '9'){ - x <<= 4; - x |= ch - '0'; - count++; - continue; - } - if ('a' <= ch && ch <= 'f'){ - x <<= 4; - x |= ch - 'a' + 10; - count++; - continue; - } - if ('A' <= ch && ch <= 'F'){ - x <<= 4; - x |= ch - 'A' + 10; - count++; - continue; - } - - break; - } - if (!m_has_alpha){ - x &= 0x00ffffff; - } - set(x); -} - -void ColorCell::load_json(const JsonValue& json){ - uint32_t value; - if (!json.read_integer(value)){ - return; - } - set(value); -} -JsonValue ColorCell::to_json() const{ - return (uint32_t)*this; -} -void ColorCell::restore_defaults(){ - set(m_default_value); -} - - - -} +/* Color Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" + #include "ColorOption.h" + +namespace PokemonAutomation{ + + +ColorCell::ColorCell(const ColorCell& x) + : ConfigOption(x) + , m_default_value(x.m_default_value) + , m_current_value(x) +{} +ColorCell::ColorCell( + LockMode lock_while_running, + bool has_alpha, + uint32_t default_value, uint32_t current_value +) + : ConfigOption(lock_while_running) + , m_has_alpha(has_alpha) + , m_default_value(default_value) + , m_current_value(current_value) +{ + if (!m_has_alpha){ + m_default_value &= 0x00ffffff; + m_current_value &= 0x00ffffff; + } +} +uint32_t ColorCell::default_value() const{ + return m_default_value; +} +std::string ColorCell::to_str() const{ + return color_to_str(*this, m_has_alpha); +} +std::string ColorCell::color_to_str(uint32_t color, bool has_alpha){ + static const char HEX_DIGITS[] = "0123456789ABCDEF"; + std::string str; + if (has_alpha){ + str += HEX_DIGITS[(color >> 28) & 0xf]; + str += HEX_DIGITS[(color >> 24) & 0xf]; + } + str += HEX_DIGITS[(color >> 20) & 0xf]; + str += HEX_DIGITS[(color >> 16) & 0xf]; + str += HEX_DIGITS[(color >> 12) & 0xf]; + str += HEX_DIGITS[(color >> 8) & 0xf]; + str += HEX_DIGITS[(color >> 4) & 0xf]; + str += HEX_DIGITS[(color >> 0) & 0xf]; + return str; +} +ColorCell::operator uint32_t() const{ + return m_current_value.load(std::memory_order_relaxed); +} +void ColorCell::set(uint32_t x){ + if (!m_has_alpha){ + x &= 0x00ffffff; + } + if (x != m_current_value.exchange(x, std::memory_order_relaxed)){ + report_value_changed(this); + } +} +void ColorCell::set(const std::string& str){ + size_t max_digits = m_has_alpha ? 8 : 6; + + uint32_t x = 0; + size_t count = 0; + for (char ch : str){ + if (count >= max_digits){ + break; + } + switch (ch){ + case '\0': + break; + case '-': + case ':': + case ' ': + continue; + } + + if ('0' <= ch && ch <= '9'){ + x <<= 4; + x |= ch - '0'; + count++; + continue; + } + if ('a' <= ch && ch <= 'f'){ + x <<= 4; + x |= ch - 'a' + 10; + count++; + continue; + } + if ('A' <= ch && ch <= 'F'){ + x <<= 4; + x |= ch - 'A' + 10; + count++; + continue; + } + + break; + } + if (!m_has_alpha){ + x &= 0x00ffffff; + } + set(x); +} + +void ColorCell::load_json(const JsonValue& json){ + uint32_t value; + if (!json.read_integer(value)){ + return; + } + set(value); +} +JsonValue ColorCell::to_json() const{ + return (uint32_t)*this; +} +void ColorCell::restore_defaults(){ + set(m_default_value); +} + + + +} diff --git a/Common/Cpp/Options/ColorOption.h b/Common/Cpp/Options/ColorOption.h index 905063cd33..ec74c83c0b 100644 --- a/Common/Cpp/Options/ColorOption.h +++ b/Common/Cpp/Options/ColorOption.h @@ -1,50 +1,50 @@ -/* Color Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ColorOption_H -#define PokemonAutomation_ColorOption_H - -#include -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - - -class ColorCell : public ConfigOption{ -public: - ColorCell(const ColorCell& x); - ColorCell( - LockMode lock_while_running, - bool has_alpha, - uint32_t default_value, uint32_t current_value - ); - - uint32_t default_value() const; - std::string to_str() const; - static std::string color_to_str(uint32_t color, bool has_alpha); - - operator uint32_t() const; - void set(uint32_t x); - void set(const std::string& str); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -private: - bool m_has_alpha; - uint32_t m_default_value; - std::atomic m_current_value; -}; - - - -} -#endif +/* Color Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ColorOption_H +#define PokemonAutomation_ColorOption_H + +#include +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + + +class ColorCell : public ConfigOption{ +public: + ColorCell(const ColorCell& x); + ColorCell( + LockMode lock_while_running, + bool has_alpha, + uint32_t default_value, uint32_t current_value + ); + + uint32_t default_value() const; + std::string to_str() const; + static std::string color_to_str(uint32_t color, bool has_alpha); + + operator uint32_t() const; + void set(uint32_t x); + void set(const std::string& str); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +private: + bool m_has_alpha; + uint32_t m_default_value; + std::atomic m_current_value; +}; + + + +} +#endif diff --git a/Common/Cpp/Options/ConfigOption.cpp b/Common/Cpp/Options/ConfigOption.cpp index e6dfe13198..146c738bcd 100644 --- a/Common/Cpp/Options/ConfigOption.cpp +++ b/Common/Cpp/Options/ConfigOption.cpp @@ -1,135 +1,135 @@ -/* Config Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "ConfigOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct ConfigOption::Data{ - const LockMode lock_mode; - std::atomic visibility; - - ListenerSet listeners; - - Data(LockMode p_lock_mode, ConfigOptionState p_visibility) - : lock_mode(p_lock_mode) - , visibility(p_visibility) - {} - - bool set_visibility(ConfigOptionState state){ - while (true){ - ConfigOptionState current = visibility.load(std::memory_order_acquire); - - // Already in that state. No change. - if (current == state){ - return false; - } - - // Attempt to change. - if (visibility.compare_exchange_weak(current, state)){ - return true; - } - } - } -}; - - - -ConfigOption::~ConfigOption() = default; -ConfigOption::ConfigOption(const ConfigOption& x) - : m_data(CONSTRUCT_TOKEN, x.lock_mode(), x.visibility()) -{} - -ConfigOption::ConfigOption() - : m_data(CONSTRUCT_TOKEN, LockMode::LOCK_WHILE_RUNNING, ConfigOptionState::ENABLED) -{} -ConfigOption::ConfigOption(LockMode lock_mode) - : m_data(CONSTRUCT_TOKEN, lock_mode, ConfigOptionState::ENABLED) -{} -ConfigOption::ConfigOption(ConfigOptionState visibility) - : m_data(CONSTRUCT_TOKEN, LockMode::LOCK_WHILE_RUNNING, visibility) -{} - -void ConfigOption::add_listener(Listener& listener){ - auto scope = m_lifetime_sanitizer.check_scope(); - Data& data = *m_data; - data.listeners.add(listener); -} -void ConfigOption::remove_listener(Listener& listener){ - auto scope = m_lifetime_sanitizer.check_scope(); - Data& data = *m_data; - data.listeners.remove(listener); -} -size_t ConfigOption::total_listeners() const{ - auto scope = m_lifetime_sanitizer.check_scope(); - const Data& data = *m_data; - return data.listeners.count_unique(); -} - - - - - -void ConfigOption::load_json(const JsonValue& json){ - m_lifetime_sanitizer.check_usage(); -} -JsonValue ConfigOption::to_json() const{ - m_lifetime_sanitizer.check_usage(); - return JsonValue(); -} -LockMode ConfigOption::lock_mode() const{ - m_lifetime_sanitizer.check_usage(); - return m_data->lock_mode; -} -std::string ConfigOption::check_validity() const{ - m_lifetime_sanitizer.check_usage(); - return std::string(); -} -void ConfigOption::restore_defaults(){ - m_lifetime_sanitizer.check_usage(); -} -ConfigOptionState ConfigOption::visibility() const{ - m_lifetime_sanitizer.check_usage(); - return m_data->visibility.load(std::memory_order_relaxed); -} -void ConfigOption::set_visibility(ConfigOptionState visibility){ - auto scope = m_lifetime_sanitizer.check_scope(); - if (m_data->set_visibility(visibility)){ - report_visibility_changed(); - } -} - - -void ConfigOption::report_visibility_changed(){ - auto scope = m_lifetime_sanitizer.check_scope(); - Data& data = *m_data; - data.listeners.run_method_unique(&Listener::on_config_visibility_changed); -} -void ConfigOption::report_program_state(bool program_is_running){ - auto scope = m_lifetime_sanitizer.check_scope(); - Data& data = *m_data; - data.listeners.run_method_unique(&Listener::on_program_state_changed, program_is_running); -} -void ConfigOption::report_value_changed(void* object){ - auto scope = m_lifetime_sanitizer.check_scope(); - Data& data = *m_data; - data.listeners.run_method_unique(&Listener::on_config_value_changed, object); -} - - - - - -} +/* Config Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "ConfigOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct ConfigOption::Data{ + const LockMode lock_mode; + std::atomic visibility; + + ListenerSet listeners; + + Data(LockMode p_lock_mode, ConfigOptionState p_visibility) + : lock_mode(p_lock_mode) + , visibility(p_visibility) + {} + + bool set_visibility(ConfigOptionState state){ + while (true){ + ConfigOptionState current = visibility.load(std::memory_order_acquire); + + // Already in that state. No change. + if (current == state){ + return false; + } + + // Attempt to change. + if (visibility.compare_exchange_weak(current, state)){ + return true; + } + } + } +}; + + + +ConfigOption::~ConfigOption() = default; +ConfigOption::ConfigOption(const ConfigOption& x) + : m_data(CONSTRUCT_TOKEN, x.lock_mode(), x.visibility()) +{} + +ConfigOption::ConfigOption() + : m_data(CONSTRUCT_TOKEN, LockMode::LOCK_WHILE_RUNNING, ConfigOptionState::ENABLED) +{} +ConfigOption::ConfigOption(LockMode lock_mode) + : m_data(CONSTRUCT_TOKEN, lock_mode, ConfigOptionState::ENABLED) +{} +ConfigOption::ConfigOption(ConfigOptionState visibility) + : m_data(CONSTRUCT_TOKEN, LockMode::LOCK_WHILE_RUNNING, visibility) +{} + +void ConfigOption::add_listener(Listener& listener){ + auto scope = m_lifetime_sanitizer.check_scope(); + Data& data = *m_data; + data.listeners.add(listener); +} +void ConfigOption::remove_listener(Listener& listener){ + auto scope = m_lifetime_sanitizer.check_scope(); + Data& data = *m_data; + data.listeners.remove(listener); +} +size_t ConfigOption::total_listeners() const{ + auto scope = m_lifetime_sanitizer.check_scope(); + const Data& data = *m_data; + return data.listeners.count_unique(); +} + + + + + +void ConfigOption::load_json(const JsonValue& json){ + m_lifetime_sanitizer.check_usage(); +} +JsonValue ConfigOption::to_json() const{ + m_lifetime_sanitizer.check_usage(); + return JsonValue(); +} +LockMode ConfigOption::lock_mode() const{ + m_lifetime_sanitizer.check_usage(); + return m_data->lock_mode; +} +std::string ConfigOption::check_validity() const{ + m_lifetime_sanitizer.check_usage(); + return std::string(); +} +void ConfigOption::restore_defaults(){ + m_lifetime_sanitizer.check_usage(); +} +ConfigOptionState ConfigOption::visibility() const{ + m_lifetime_sanitizer.check_usage(); + return m_data->visibility.load(std::memory_order_relaxed); +} +void ConfigOption::set_visibility(ConfigOptionState visibility){ + auto scope = m_lifetime_sanitizer.check_scope(); + if (m_data->set_visibility(visibility)){ + report_visibility_changed(); + } +} + + +void ConfigOption::report_visibility_changed(){ + auto scope = m_lifetime_sanitizer.check_scope(); + Data& data = *m_data; + data.listeners.run_method_unique(&Listener::on_config_visibility_changed); +} +void ConfigOption::report_program_state(bool program_is_running){ + auto scope = m_lifetime_sanitizer.check_scope(); + Data& data = *m_data; + data.listeners.run_method_unique(&Listener::on_program_state_changed, program_is_running); +} +void ConfigOption::report_value_changed(void* object){ + auto scope = m_lifetime_sanitizer.check_scope(); + Data& data = *m_data; + data.listeners.run_method_unique(&Listener::on_config_value_changed, object); +} + + + + + +} diff --git a/Common/Cpp/Options/ConfigOption.h b/Common/Cpp/Options/ConfigOption.h index b90916df6c..4909df42ee 100644 --- a/Common/Cpp/Options/ConfigOption.h +++ b/Common/Cpp/Options/ConfigOption.h @@ -1,141 +1,141 @@ -/* Config Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_ConfigOption_H -#define PokemonAutomation_Options_ConfigOption_H - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Containers/Pimpl.h" - -class QWidget; - -namespace PokemonAutomation{ - -class JsonValue; -class ConfigWidget; - - -enum class LockMode{ - UNLOCK_WHILE_RUNNING, - LOCK_WHILE_RUNNING, - READ_ONLY, -}; -enum class ConfigOptionState{ - ENABLED, - DISABLED, - HIDDEN, -}; - - -// Abstract base class for An option of a program, like the number of boxes of -// eggs to hatch, the number of frames to skip, or what type of pokeballs to throw. -// It is responsible for setting the UI (by calling make_QtWidget()) of this option. -// It also uses load_json() and to_json() to load and save the option to -// a json file, so that the program can remember what user has selected. -class ConfigOption{ -public: - // the objects that listen to changes on the ConfigOption should inherit - // this Listener struct and call ConfigOption::add_listener() to add themselves - // to the listener set. - // Afterwards, whenever the config state is changed, all added listeners' - // corresponding member functions (e.g. value_changed()) will get called by - // the config option. - struct Listener{ - // When the config option value is changed, all added listeners' - // value_changed() will get called. - // object: the object that initiated the change. e.g. If the user changes - // a UI content, object would be the UI option that is changed. This is - // mainly used to avoid infinite loops. So if the initial change triggers - // the original UI option's value_changed() get called, it will know that - // object == this and therefore a loop is formed. - virtual void on_config_value_changed(void* object){} - // When the config UI visibility is changed, all added listeners' - // visibility_changed() will get called. - virtual void on_config_visibility_changed(){} - // When the program state is changed, all added listeners' - // program_state_changed() will get called. - virtual void on_program_state_changed(bool program_is_running){} - }; - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - size_t total_listeners() const; - -public: - virtual ~ConfigOption(); - ConfigOption(ConfigOption&&) = delete; - void operator=(ConfigOption&&) = delete; -protected: - ConfigOption(const ConfigOption& x); - -public: - ConfigOption(); - ConfigOption(LockMode lock_mode); - ConfigOption(ConfigOptionState visibility); - -// // Deep copy this entire config. This will not copy listeners. -// // Returns null if config cannot be copied. -// virtual std::unique_ptr clone() const = 0; - - virtual void load_json(const JsonValue& json); - virtual JsonValue to_json() const; - - // Lifetime sanitizer - void check_usage() const{ - m_lifetime_sanitizer.check_usage(); - } - LifetimeSanitizer::CheckScope check_scope() const{ - return m_lifetime_sanitizer.check_scope(); - } - -public: - LockMode lock_mode() const; - - // Returns error message if invalid. Otherwise returns empty string. - virtual std::string check_validity() const; - - virtual void restore_defaults(); - - // This is called by the framework at the start of a program to reset any - // transient state that the option object may have. - virtual void reset_state(){}; - - ConfigOptionState visibility() const; - virtual void set_visibility(ConfigOptionState visibility); - - -public: - // Report that the visibility has changed. Attached UI elements should - // respond accordingly to show, hide, or lock this element. - virtual void report_visibility_changed(); - - // Report that the program state has changed. This will cause UI elements - // to lock/unlock depending on whether they are allowed to be changed by - // the user while the program is running. - virtual void report_program_state(bool program_is_running); - -protected: - // Report that the value of this config has changed. This will be pushed to - // all listeners. - void report_value_changed(void* object); - - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) = 0; - -private: - struct Data; - Pimpl m_data; - - LifetimeSanitizer m_lifetime_sanitizer; -}; - - - - -} -#endif +/* Config Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_ConfigOption_H +#define PokemonAutomation_Options_ConfigOption_H + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Containers/Pimpl.h" + +class QWidget; + +namespace PokemonAutomation{ + +class JsonValue; +class ConfigWidget; + + +enum class LockMode{ + UNLOCK_WHILE_RUNNING, + LOCK_WHILE_RUNNING, + READ_ONLY, +}; +enum class ConfigOptionState{ + ENABLED, + DISABLED, + HIDDEN, +}; + + +// Abstract base class for An option of a program, like the number of boxes of +// eggs to hatch, the number of frames to skip, or what type of pokeballs to throw. +// It is responsible for setting the UI (by calling make_QtWidget()) of this option. +// It also uses load_json() and to_json() to load and save the option to +// a json file, so that the program can remember what user has selected. +class ConfigOption{ +public: + // the objects that listen to changes on the ConfigOption should inherit + // this Listener struct and call ConfigOption::add_listener() to add themselves + // to the listener set. + // Afterwards, whenever the config state is changed, all added listeners' + // corresponding member functions (e.g. value_changed()) will get called by + // the config option. + struct Listener{ + // When the config option value is changed, all added listeners' + // value_changed() will get called. + // object: the object that initiated the change. e.g. If the user changes + // a UI content, object would be the UI option that is changed. This is + // mainly used to avoid infinite loops. So if the initial change triggers + // the original UI option's value_changed() get called, it will know that + // object == this and therefore a loop is formed. + virtual void on_config_value_changed(void* object){} + // When the config UI visibility is changed, all added listeners' + // visibility_changed() will get called. + virtual void on_config_visibility_changed(){} + // When the program state is changed, all added listeners' + // program_state_changed() will get called. + virtual void on_program_state_changed(bool program_is_running){} + }; + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + size_t total_listeners() const; + +public: + virtual ~ConfigOption(); + ConfigOption(ConfigOption&&) = delete; + void operator=(ConfigOption&&) = delete; +protected: + ConfigOption(const ConfigOption& x); + +public: + ConfigOption(); + ConfigOption(LockMode lock_mode); + ConfigOption(ConfigOptionState visibility); + +// // Deep copy this entire config. This will not copy listeners. +// // Returns null if config cannot be copied. +// virtual std::unique_ptr clone() const = 0; + + virtual void load_json(const JsonValue& json); + virtual JsonValue to_json() const; + + // Lifetime sanitizer + void check_usage() const{ + m_lifetime_sanitizer.check_usage(); + } + LifetimeSanitizer::CheckScope check_scope() const{ + return m_lifetime_sanitizer.check_scope(); + } + +public: + LockMode lock_mode() const; + + // Returns error message if invalid. Otherwise returns empty string. + virtual std::string check_validity() const; + + virtual void restore_defaults(); + + // This is called by the framework at the start of a program to reset any + // transient state that the option object may have. + virtual void reset_state(){}; + + ConfigOptionState visibility() const; + virtual void set_visibility(ConfigOptionState visibility); + + +public: + // Report that the visibility has changed. Attached UI elements should + // respond accordingly to show, hide, or lock this element. + virtual void report_visibility_changed(); + + // Report that the program state has changed. This will cause UI elements + // to lock/unlock depending on whether they are allowed to be changed by + // the user while the program is running. + virtual void report_program_state(bool program_is_running); + +protected: + // Report that the value of this config has changed. This will be pushed to + // all listeners. + void report_value_changed(void* object); + + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) = 0; + +private: + struct Data; + Pimpl m_data; + + LifetimeSanitizer m_lifetime_sanitizer; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/DateOption.cpp b/Common/Cpp/Options/DateOption.cpp index 5a893a3a0c..fb88f0fa8c 100644 --- a/Common/Cpp/Options/DateOption.cpp +++ b/Common/Cpp/Options/DateOption.cpp @@ -1,190 +1,190 @@ -/* Date - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -//#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "DateOption.h" - -namespace PokemonAutomation{ - - - - - -bool DateTimeCell::is_valid(const DateTime& date) const{ - if (date.year < 0){ - return false; - } - if (date.month < 0){ - return false; - } - if (date.day < 0){ - return false; - } - - if (m_level < DATE_HOUR_MIN){ - return true; - } - - if (date.hour < 0){ - return false; - } - if (date.minute < 0){ - return false; - } - - if (m_level < DATE_HOUR_MIN_SEC){ - return true; - } - - if (date.second < 0){ - return false; - } - - return true; -} - -DateTimeCell::DateTimeCell( - LockMode lock_while_running, - Level level, - const DateTime& min_value, const DateTime& max_value, - const DateTime& default_value -) - : ConfigOption(lock_while_running) - , m_level(level) - , m_min_value(min_value) - , m_max_value(max_value) - , m_default(default_value) - , m_current(default_value) -{ - if (!is_valid(min_value)){ - throw InternalProgramError(nullptr, "DateTimeCell()", "Date is invalid."); - } - if (!is_valid(max_value)){ - throw InternalProgramError(nullptr, "DateTimeCell()", "Date is invalid."); - } - if (!is_valid(default_value)){ - throw InternalProgramError(nullptr, "DateTimeCell()", "Date is invalid."); - } -} - -DateTimeCell::operator DateTime() const{ - ReadSpinLock lg(m_lock); - return m_current; -} -DateTime DateTimeCell::get() const{ - ReadSpinLock lg(m_lock); - return m_current; -} -std::string DateTimeCell::set(const DateTime& x){ - std::string err = check_validity(x); - if (!err.empty()){ - return err; - } - { - WriteSpinLock lg(m_lock); - if (x == m_current){ - return std::string(); - } - m_current = x; - } - report_value_changed(this); - return std::string(); -} - -std::string DateTimeCell::check_validity(const DateTime& x) const{ - if (x < m_min_value || x > m_max_value){ - return "Invalid date."; - } - return std::string(); -} -std::string DateTimeCell::check_validity() const{ - ReadSpinLock lg(m_lock); - return check_validity(m_current); -} -void DateTimeCell::restore_defaults(){ - set(m_default); -} - -DateTime DateTimeCell::from_json(const JsonValue& json){ - DateTime ret; - - const JsonObject* object = json.to_object(); - if (object == nullptr){ - return ret; - } - - object->read_integer(ret.year, "Year", 0, 9999); - object->read_integer(ret.month, "Month", 1, 12); - object->read_integer(ret.day, "Day", 1, 31); - object->read_integer(ret.hour, "Hour", 0, 23); - object->read_integer(ret.minute, "Minute", 0, 59); - object->read_integer(ret.second, "Second", 0, 59); - - return ret; -} -JsonValue DateTimeCell::to_json(const DateTime& date){ - JsonObject ret; - if (date.year >= 0) ret["Year" ] = date.year; - if (date.month >= 0) ret["Month" ] = date.month; - if (date.day >= 0) ret["Day" ] = date.day; - if (date.hour >= 0) ret["Hour" ] = date.hour; - if (date.minute >= 0) ret["Minute"] = date.minute; - if (date.second >= 0) ret["Second"] = date.second; - return ret; -} -void DateTimeCell::load_json(const JsonValue& json){ - DateTime date = from_json(json); - if (!is_valid(date) || !check_validity(date).empty()){ - return; - } - { - WriteSpinLock lg(m_lock); - m_current = date; - } - report_value_changed(this); -} -JsonValue DateTimeCell::to_json() const{ - DateTime current; - { - ReadSpinLock lg(m_lock); - current = m_current; - } - return to_json(current); -} - - - - -DateTimeOption::DateTimeOption( - std::string label, - LockMode lock_while_running, - Level level, - const DateTime& min_value, const DateTime& max_value, - const DateTime& default_value -) - : DateTimeCell(lock_while_running, level, min_value, max_value, default_value) - , m_label(std::move(label)) -{} - - - - - - - - - - - - - - - - -} +/* Date + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +//#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "DateOption.h" + +namespace PokemonAutomation{ + + + + + +bool DateTimeCell::is_valid(const DateTime& date) const{ + if (date.year < 0){ + return false; + } + if (date.month < 0){ + return false; + } + if (date.day < 0){ + return false; + } + + if (m_level < DATE_HOUR_MIN){ + return true; + } + + if (date.hour < 0){ + return false; + } + if (date.minute < 0){ + return false; + } + + if (m_level < DATE_HOUR_MIN_SEC){ + return true; + } + + if (date.second < 0){ + return false; + } + + return true; +} + +DateTimeCell::DateTimeCell( + LockMode lock_while_running, + Level level, + const DateTime& min_value, const DateTime& max_value, + const DateTime& default_value +) + : ConfigOption(lock_while_running) + , m_level(level) + , m_min_value(min_value) + , m_max_value(max_value) + , m_default(default_value) + , m_current(default_value) +{ + if (!is_valid(min_value)){ + throw InternalProgramError(nullptr, "DateTimeCell()", "Date is invalid."); + } + if (!is_valid(max_value)){ + throw InternalProgramError(nullptr, "DateTimeCell()", "Date is invalid."); + } + if (!is_valid(default_value)){ + throw InternalProgramError(nullptr, "DateTimeCell()", "Date is invalid."); + } +} + +DateTimeCell::operator DateTime() const{ + ReadSpinLock lg(m_lock); + return m_current; +} +DateTime DateTimeCell::get() const{ + ReadSpinLock lg(m_lock); + return m_current; +} +std::string DateTimeCell::set(const DateTime& x){ + std::string err = check_validity(x); + if (!err.empty()){ + return err; + } + { + WriteSpinLock lg(m_lock); + if (x == m_current){ + return std::string(); + } + m_current = x; + } + report_value_changed(this); + return std::string(); +} + +std::string DateTimeCell::check_validity(const DateTime& x) const{ + if (x < m_min_value || x > m_max_value){ + return "Invalid date."; + } + return std::string(); +} +std::string DateTimeCell::check_validity() const{ + ReadSpinLock lg(m_lock); + return check_validity(m_current); +} +void DateTimeCell::restore_defaults(){ + set(m_default); +} + +DateTime DateTimeCell::from_json(const JsonValue& json){ + DateTime ret; + + const JsonObject* object = json.to_object(); + if (object == nullptr){ + return ret; + } + + object->read_integer(ret.year, "Year", 0, 9999); + object->read_integer(ret.month, "Month", 1, 12); + object->read_integer(ret.day, "Day", 1, 31); + object->read_integer(ret.hour, "Hour", 0, 23); + object->read_integer(ret.minute, "Minute", 0, 59); + object->read_integer(ret.second, "Second", 0, 59); + + return ret; +} +JsonValue DateTimeCell::to_json(const DateTime& date){ + JsonObject ret; + if (date.year >= 0) ret["Year" ] = date.year; + if (date.month >= 0) ret["Month" ] = date.month; + if (date.day >= 0) ret["Day" ] = date.day; + if (date.hour >= 0) ret["Hour" ] = date.hour; + if (date.minute >= 0) ret["Minute"] = date.minute; + if (date.second >= 0) ret["Second"] = date.second; + return ret; +} +void DateTimeCell::load_json(const JsonValue& json){ + DateTime date = from_json(json); + if (!is_valid(date) || !check_validity(date).empty()){ + return; + } + { + WriteSpinLock lg(m_lock); + m_current = date; + } + report_value_changed(this); +} +JsonValue DateTimeCell::to_json() const{ + DateTime current; + { + ReadSpinLock lg(m_lock); + current = m_current; + } + return to_json(current); +} + + + + +DateTimeOption::DateTimeOption( + std::string label, + LockMode lock_while_running, + Level level, + const DateTime& min_value, const DateTime& max_value, + const DateTime& default_value +) + : DateTimeCell(lock_while_running, level, min_value, max_value, default_value) + , m_label(std::move(label)) +{} + + + + + + + + + + + + + + + + +} diff --git a/Common/Cpp/Options/DateOption.h b/Common/Cpp/Options/DateOption.h index ee44aeecf1..04c82ff8b2 100644 --- a/Common/Cpp/Options/DateOption.h +++ b/Common/Cpp/Options/DateOption.h @@ -1,92 +1,92 @@ -/* Date Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_DateOption_H -#define PokemonAutomation_Options_DateOption_H - -#include "Common/Cpp/DateTime.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - - -class DateTimeCell : public ConfigOption{ -public: - enum Level{ - DATE, - DATE_HOUR_MIN, - DATE_HOUR_MIN_SEC, - }; - -public: - DateTimeCell( - LockMode lock_while_running, - Level level, - const DateTime& min_value, const DateTime& max_value, - const DateTime& default_value - ); - - Level level() const{ return m_level; } - const DateTime& min_value() const{ return m_min_value; } - const DateTime& max_value() const{ return m_max_value; } - const DateTime& default_value() const{ return m_default; } - - operator DateTime() const; - DateTime get() const; - std::string set(const DateTime& x); - - std::string check_validity(const DateTime& x) const; - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - -public: - static DateTime from_json(const JsonValue& json); - static JsonValue to_json(const DateTime& date); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - bool is_valid(const DateTime& date) const; - -private: - const Level m_level; - const DateTime m_min_value; - const DateTime m_max_value; - const DateTime m_default; - - mutable SpinLock m_lock; - DateTime m_current; -}; - - -class DateTimeOption : public DateTimeCell{ -public: - DateTimeOption( - std::string label, - LockMode lock_while_running, - Level level, - const DateTime& min_value, const DateTime& max_value, - const DateTime& default_value - ); - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - -} -#endif - +/* Date Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_DateOption_H +#define PokemonAutomation_Options_DateOption_H + +#include "Common/Cpp/DateTime.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + + +class DateTimeCell : public ConfigOption{ +public: + enum Level{ + DATE, + DATE_HOUR_MIN, + DATE_HOUR_MIN_SEC, + }; + +public: + DateTimeCell( + LockMode lock_while_running, + Level level, + const DateTime& min_value, const DateTime& max_value, + const DateTime& default_value + ); + + Level level() const{ return m_level; } + const DateTime& min_value() const{ return m_min_value; } + const DateTime& max_value() const{ return m_max_value; } + const DateTime& default_value() const{ return m_default; } + + operator DateTime() const; + DateTime get() const; + std::string set(const DateTime& x); + + std::string check_validity(const DateTime& x) const; + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + +public: + static DateTime from_json(const JsonValue& json); + static JsonValue to_json(const DateTime& date); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + bool is_valid(const DateTime& date) const; + +private: + const Level m_level; + const DateTime m_min_value; + const DateTime m_max_value; + const DateTime m_default; + + mutable SpinLock m_lock; + DateTime m_current; +}; + + +class DateTimeOption : public DateTimeCell{ +public: + DateTimeOption( + std::string label, + LockMode lock_while_running, + Level level, + const DateTime& min_value, const DateTime& max_value, + const DateTime& default_value + ); + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + +} +#endif + diff --git a/Common/Cpp/Options/EditableTableOption.cpp b/Common/Cpp/Options/EditableTableOption.cpp index 056e13d910..2d31d633af 100644 --- a/Common/Cpp/Options/EditableTableOption.cpp +++ b/Common/Cpp/Options/EditableTableOption.cpp @@ -1,277 +1,277 @@ -/* Editable Table Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "EditableTableOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -//EditableTableRow::EditableTableRow(void*) -// : m_parent(nullptr) -// , m_index((size_t)0 - 1) -//{} -EditableTableRow::EditableTableRow(EditableTableOption& parent_table) - : m_parent_table(parent_table) - , m_index((size_t)0 - 1) -{} -void EditableTableRow::add_option(ConfigOption& option, std::string serialization_string){ - m_options.emplace_back(std::move(serialization_string), &option); -} -void EditableTableRow::load_json(const JsonValue& json){ - if (m_options.size() == 1){ - m_options[0].second->load_json(json); - return; - } - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - for (auto& item : m_options){ - if (!item.first.empty()){ - const JsonValue* value = obj->get_value(item.first); - if (value){ - item.second->load_json(*value); - } - } - } -} -JsonValue EditableTableRow::to_json() const{ - if (m_options.size() == 1){ - return m_options[0].second->to_json(); - } - JsonObject obj; - for (auto& item : m_options){ - if (!item.first.empty()){ - obj[item.first] = item.second->to_json(); - } - } - return obj; -} -std::string EditableTableRow::check_validity() const{ - for (const auto& item : m_options){ - std::string error = item.second->check_validity(); - if (!error.empty()){ - return error; - } - } - return std::string(); -} -std::vector EditableTableRow::make_cells(){ - std::vector ret; - ret.reserve(m_options.size()); - for (const auto& item : m_options){ - ret.emplace_back(item.second); - } - return ret; -} - - - - -EditableTableOption::EditableTableOption( - std::string label, - LockMode lock_while_running, - std::vector> default_value -) - : ConfigOption(lock_while_running) - , m_label(std::move(label)) - , m_enable_saveload(true) - , m_default(std::move(default_value)) -{ - restore_defaults(); -} -EditableTableOption::EditableTableOption( - std::string label, - LockMode lock_while_running, - bool enable_saveload, - std::vector> default_value -) - : ConfigOption(lock_while_running) - , m_label(std::move(label)) - , m_enable_saveload(enable_saveload) - , m_default(std::move(default_value)) -{ - restore_defaults(); -} -void EditableTableOption::set_default(std::vector> default_value){ - WriteSpinLock lg(m_default_lock); - m_default = std::move(default_value); -} -size_t EditableTableOption::current_rows() const{ - ReadSpinLock lg(m_current_lock); - return m_current.size(); -} -std::vector> EditableTableOption::current_refs() const{ - ReadSpinLock lg(m_current_lock); - return m_current; -} - -void EditableTableOption::clear(){ - WriteSpinLock lg(m_current_lock); - m_current.clear(); -} -void EditableTableOption::load_json(const JsonValue& json){ -// cout << "EditableTableOption::load_json(): " << this << endl; - - const JsonArray* array = json.to_array(); - if (array == nullptr){ - return; - } - { - // Pre-allocate seqnums. - uint64_t seqnum = m_seqnum.fetch_add(array->size()); - - // Build table outside of lock first. - // If the table is built inside of the lock, you can get issues with deadlock. - // The reason for this is that during the construction of the new table, - // the listeners get triggered. Specifically, the row elements trigger - // their own Row.report_value_changed(), which may then propagate up with Table.report_value_changed(). - // If the table's listener includes any functions that accesses the table (e.g. current_refs()), - // then this can result in deadlock since current_refs() can't access the table - // until the table is finished building and releases the lock. - // But the table can't finish building until current_refs() finishes. - // Building the table outside of the lock bypasses this issue since the listeners won't be - // triggered in the first place. - std::vector> table; - for (const auto& item : *array){ - std::unique_ptr row = make_row(); - row->m_seqnum = seqnum++; - row->m_index = table.size(); - table.emplace_back(std::move(row)); - table.back()->load_json(item); - } - - // Now commit the table inside the lock. - WriteSpinLock lg(m_current_lock); - m_current = std::move(table); - } - report_value_changed(this); -} -JsonValue EditableTableOption::to_json() const{ - ReadSpinLock lg(m_current_lock); - JsonArray array; - for (const std::shared_ptr& row : m_current){ - array.push_back(row->to_json()); - } - return array; -} - -std::string EditableTableOption::check_validity() const{ - ReadSpinLock lg(m_current_lock); - for (const std::shared_ptr& item : m_current){ - std::string error = item->check_validity(); - if (!error.empty()){ - return error; - } - } - return std::string(); -} -void EditableTableOption::restore_defaults(){ - { - std::vector> tmp; - { - ReadSpinLock lg(m_default_lock); - - // Pre-allocate seqnums. - uint64_t seqnum = m_seqnum.fetch_add(m_default.size()); - - // Build table outside of lock first. - // If the table is built inside of the lock, you can get issues with deadlock. - // (see load_json() for more details) - for (const std::unique_ptr& item : m_default){ - tmp.emplace_back(item->clone()); - tmp.back()->m_seqnum = seqnum++; - tmp.back()->m_index = tmp.size() - 1; - } - } - - // Now commit the table inside the lock. - WriteSpinLock lg(m_current_lock); - m_current = std::move(tmp); - } - report_value_changed(this); -} - - - -void EditableTableOption::insert_row(size_t index, std::unique_ptr row){ - { - WriteSpinLock lg(m_current_lock); - index = std::min(index, m_current.size()); - row->m_seqnum = m_seqnum++; - m_current.insert(m_current.begin() + index, std::move(row)); - size_t stop = m_current.size(); - for (size_t c = index; c < stop; c++){ - m_current[c]->m_index.store(c, std::memory_order_relaxed); - } - } - report_value_changed(this); -} -void EditableTableOption::append_row(std::unique_ptr row){ - insert_row((size_t)-1, std::move(row)); -} -void EditableTableOption::clone_row(const EditableTableRow& row){ - { - size_t index = row.m_index; - if (index == (size_t)0 - 1){ -// cout << "EditableTableOptionCore::clone_row(): Orphaned row" << endl; - return; - } - - // Copy the row first. - // If the row is cloned inside of the lock, you can get issues with deadlock. - // (see load_json() for more details) - std::unique_ptr new_row = row.clone(); - new_row->m_seqnum = m_seqnum++; - - // Now add it to the table. - WriteSpinLock lg(m_current_lock); - index = std::min(index, m_current.size()); - m_current.insert(m_current.begin() + index, std::move(new_row)); - size_t stop = m_current.size(); - for (size_t c = index; c < stop; c++){ - m_current[c]->m_index.store(c, std::memory_order_relaxed); - } - } - report_value_changed(this); -} -void EditableTableOption::remove_row(EditableTableRow& row){ - { - size_t index = row.m_index; - if (index == (size_t)0 - 1){ -// cout << "EditableTableOptionCore::remove_row(): Orphaned row" << endl; - return; - } - - WriteSpinLock lg(m_current_lock); - auto iter = m_current.begin() + index; - (*iter)->m_index.store((size_t)0 - 1, std::memory_order_relaxed); - m_current.erase(iter); - size_t stop = m_current.size(); - for (size_t c = index; c < stop; c++){ - m_current[c]->m_index.store(c, std::memory_order_relaxed); - } - } - report_value_changed(this); -} - - - - - - - - - -} +/* Editable Table Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "EditableTableOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +//EditableTableRow::EditableTableRow(void*) +// : m_parent(nullptr) +// , m_index((size_t)0 - 1) +//{} +EditableTableRow::EditableTableRow(EditableTableOption& parent_table) + : m_parent_table(parent_table) + , m_index((size_t)0 - 1) +{} +void EditableTableRow::add_option(ConfigOption& option, std::string serialization_string){ + m_options.emplace_back(std::move(serialization_string), &option); +} +void EditableTableRow::load_json(const JsonValue& json){ + if (m_options.size() == 1){ + m_options[0].second->load_json(json); + return; + } + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + for (auto& item : m_options){ + if (!item.first.empty()){ + const JsonValue* value = obj->get_value(item.first); + if (value){ + item.second->load_json(*value); + } + } + } +} +JsonValue EditableTableRow::to_json() const{ + if (m_options.size() == 1){ + return m_options[0].second->to_json(); + } + JsonObject obj; + for (auto& item : m_options){ + if (!item.first.empty()){ + obj[item.first] = item.second->to_json(); + } + } + return obj; +} +std::string EditableTableRow::check_validity() const{ + for (const auto& item : m_options){ + std::string error = item.second->check_validity(); + if (!error.empty()){ + return error; + } + } + return std::string(); +} +std::vector EditableTableRow::make_cells(){ + std::vector ret; + ret.reserve(m_options.size()); + for (const auto& item : m_options){ + ret.emplace_back(item.second); + } + return ret; +} + + + + +EditableTableOption::EditableTableOption( + std::string label, + LockMode lock_while_running, + std::vector> default_value +) + : ConfigOption(lock_while_running) + , m_label(std::move(label)) + , m_enable_saveload(true) + , m_default(std::move(default_value)) +{ + restore_defaults(); +} +EditableTableOption::EditableTableOption( + std::string label, + LockMode lock_while_running, + bool enable_saveload, + std::vector> default_value +) + : ConfigOption(lock_while_running) + , m_label(std::move(label)) + , m_enable_saveload(enable_saveload) + , m_default(std::move(default_value)) +{ + restore_defaults(); +} +void EditableTableOption::set_default(std::vector> default_value){ + WriteSpinLock lg(m_default_lock); + m_default = std::move(default_value); +} +size_t EditableTableOption::current_rows() const{ + ReadSpinLock lg(m_current_lock); + return m_current.size(); +} +std::vector> EditableTableOption::current_refs() const{ + ReadSpinLock lg(m_current_lock); + return m_current; +} + +void EditableTableOption::clear(){ + WriteSpinLock lg(m_current_lock); + m_current.clear(); +} +void EditableTableOption::load_json(const JsonValue& json){ +// cout << "EditableTableOption::load_json(): " << this << endl; + + const JsonArray* array = json.to_array(); + if (array == nullptr){ + return; + } + { + // Pre-allocate seqnums. + uint64_t seqnum = m_seqnum.fetch_add(array->size()); + + // Build table outside of lock first. + // If the table is built inside of the lock, you can get issues with deadlock. + // The reason for this is that during the construction of the new table, + // the listeners get triggered. Specifically, the row elements trigger + // their own Row.report_value_changed(), which may then propagate up with Table.report_value_changed(). + // If the table's listener includes any functions that accesses the table (e.g. current_refs()), + // then this can result in deadlock since current_refs() can't access the table + // until the table is finished building and releases the lock. + // But the table can't finish building until current_refs() finishes. + // Building the table outside of the lock bypasses this issue since the listeners won't be + // triggered in the first place. + std::vector> table; + for (const auto& item : *array){ + std::unique_ptr row = make_row(); + row->m_seqnum = seqnum++; + row->m_index = table.size(); + table.emplace_back(std::move(row)); + table.back()->load_json(item); + } + + // Now commit the table inside the lock. + WriteSpinLock lg(m_current_lock); + m_current = std::move(table); + } + report_value_changed(this); +} +JsonValue EditableTableOption::to_json() const{ + ReadSpinLock lg(m_current_lock); + JsonArray array; + for (const std::shared_ptr& row : m_current){ + array.push_back(row->to_json()); + } + return array; +} + +std::string EditableTableOption::check_validity() const{ + ReadSpinLock lg(m_current_lock); + for (const std::shared_ptr& item : m_current){ + std::string error = item->check_validity(); + if (!error.empty()){ + return error; + } + } + return std::string(); +} +void EditableTableOption::restore_defaults(){ + { + std::vector> tmp; + { + ReadSpinLock lg(m_default_lock); + + // Pre-allocate seqnums. + uint64_t seqnum = m_seqnum.fetch_add(m_default.size()); + + // Build table outside of lock first. + // If the table is built inside of the lock, you can get issues with deadlock. + // (see load_json() for more details) + for (const std::unique_ptr& item : m_default){ + tmp.emplace_back(item->clone()); + tmp.back()->m_seqnum = seqnum++; + tmp.back()->m_index = tmp.size() - 1; + } + } + + // Now commit the table inside the lock. + WriteSpinLock lg(m_current_lock); + m_current = std::move(tmp); + } + report_value_changed(this); +} + + + +void EditableTableOption::insert_row(size_t index, std::unique_ptr row){ + { + WriteSpinLock lg(m_current_lock); + index = std::min(index, m_current.size()); + row->m_seqnum = m_seqnum++; + m_current.insert(m_current.begin() + index, std::move(row)); + size_t stop = m_current.size(); + for (size_t c = index; c < stop; c++){ + m_current[c]->m_index.store(c, std::memory_order_relaxed); + } + } + report_value_changed(this); +} +void EditableTableOption::append_row(std::unique_ptr row){ + insert_row((size_t)-1, std::move(row)); +} +void EditableTableOption::clone_row(const EditableTableRow& row){ + { + size_t index = row.m_index; + if (index == (size_t)0 - 1){ +// cout << "EditableTableOptionCore::clone_row(): Orphaned row" << endl; + return; + } + + // Copy the row first. + // If the row is cloned inside of the lock, you can get issues with deadlock. + // (see load_json() for more details) + std::unique_ptr new_row = row.clone(); + new_row->m_seqnum = m_seqnum++; + + // Now add it to the table. + WriteSpinLock lg(m_current_lock); + index = std::min(index, m_current.size()); + m_current.insert(m_current.begin() + index, std::move(new_row)); + size_t stop = m_current.size(); + for (size_t c = index; c < stop; c++){ + m_current[c]->m_index.store(c, std::memory_order_relaxed); + } + } + report_value_changed(this); +} +void EditableTableOption::remove_row(EditableTableRow& row){ + { + size_t index = row.m_index; + if (index == (size_t)0 - 1){ +// cout << "EditableTableOptionCore::remove_row(): Orphaned row" << endl; + return; + } + + WriteSpinLock lg(m_current_lock); + auto iter = m_current.begin() + index; + (*iter)->m_index.store((size_t)0 - 1, std::memory_order_relaxed); + m_current.erase(iter); + size_t stop = m_current.size(); + for (size_t c = index; c < stop; c++){ + m_current[c]->m_index.store(c, std::memory_order_relaxed); + } + } + report_value_changed(this); +} + + + + + + + + + +} diff --git a/Common/Cpp/Options/EditableTableOption.h b/Common/Cpp/Options/EditableTableOption.h index 76e48a6872..cbb56f2e46 100644 --- a/Common/Cpp/Options/EditableTableOption.h +++ b/Common/Cpp/Options/EditableTableOption.h @@ -1,204 +1,204 @@ -/* Editable Table Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_EditableTableOption_H -#define PokemonAutomation_Options_EditableTableOption_H - -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - -class EditableTableOption; - - -// Represents a row of the table. Users should subclass this and add all the -// configs/fields that is in the row. -class EditableTableRow{ -public: - virtual ~EditableTableRow() = default; -// EditableTableRow(void* = nullptr); - EditableTableRow(EditableTableOption& parent_table); - - // Duplicate/deep-copy the entire row. Does not copy over listeners. - virtual std::unique_ptr clone() const = 0; - - EditableTableOption& parent() const{ - return m_parent_table; - } - - virtual void load_json(const JsonValue& json); - virtual JsonValue to_json() const; - - virtual std::string check_validity() const; - - -protected: - void add_option(ConfigOption& option, std::string serialization_string); - -#define PA_ADD_OPTION(x) add_option(x, #x) - - -public: - // Internal use by table. - uint64_t seqnum() const{ return m_seqnum; } - size_t index() const{ return m_index.load(std::memory_order_relaxed); } - std::vector make_cells(); - - -private: - friend class EditableTableOption; - - EditableTableOption& m_parent_table; - - // A unique # for this row within its table. - uint64_t m_seqnum = 0; - - // The index in the table it resides in. - // -1 means it's orphaned and not in the table. - std::atomic m_index; - - std::vector> m_options; -}; - - - - -// This is the table itself. -class EditableTableOption : public ConfigOption{ -public: - EditableTableOption( - std::string label, - LockMode lock_while_running, - std::vector> default_value = {} - ); - EditableTableOption( - std::string label, - LockMode lock_while_running, - bool enable_saveload, - std::vector> default_value = {} - ); - void set_default(std::vector> default_value); - -public: - const std::string& label() const{ return m_label; } - - // Returns the # of rows at this moment of time. - // Since this value can be out-of-date before you return, do not use - // this for bound-checking where it's unsafe to read out-of-bounds. - size_t current_rows() const; - - // Return a list of references to all the rows at this exact moment. - // These reference are live in that they may be asynchronously changed. - std::vector> current_refs() const; - -// SpinLock& get_lock() const{ -// return m_current_lock; -// } - - // Return a copy of the entire table at the exact moment this is called. - template - std::vector> copy_snapshot() const{ - std::vector> ret; - ReadSpinLock lg(m_current_lock); - ret.reserve(m_current.size()); - for (auto& item : m_current){ - std::unique_ptr parent = item->clone(); - std::unique_ptr ptr(static_cast(parent.release())); - ret.emplace_back(std::move(ptr)); - } - return ret; - } - template - std::vector snapshot() const{ - std::vector ret; - ReadSpinLock lg(m_current_lock); - ret.reserve(m_current.size()); - for (auto& item : m_current){ - RowType& row = static_cast(*item); - ret.emplace_back(row.snapshot()); - } - return ret; - } - - // Lambda returns a boolean. False to continue running. True to stop. - template - void run_on_all_rows(Lambda function){ - ReadSpinLock lg(m_current_lock); - for (auto& item : m_current){ - if (function(static_cast(*item))){ - return; - } - } - } - - void clear(); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override final; - -public: - bool saveload_enabled() const{ return m_enable_saveload; } - virtual std::vector make_header() const = 0; - virtual std::unique_ptr make_row() = 0; - - // Undefined behavior to call these on rows that aren't part of the table. - void insert_row(size_t index, std::unique_ptr row); - void append_row(std::unique_ptr row); - void clone_row(const EditableTableRow& row); - void remove_row(EditableTableRow& row); - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; - const bool m_enable_saveload; - mutable SpinLock m_default_lock; - std::vector> m_default; - - mutable SpinLock m_current_lock; - std::atomic m_seqnum = 0; - std::vector> m_current; -}; - - -// Convenience helper class that's type-aware. -template -class EditableTableOption_t : public EditableTableOption{ -public: - using EditableTableOption::EditableTableOption; - - std::vector> copy_snapshot() const{ - return EditableTableOption::copy_snapshot(); - } - - template - std::vector snapshot() const{ - return EditableTableOption::snapshot(); - } - - // Lambda returns a boolean. False to continue running. True to stop. - template - void run_on_all_rows(Lambda function){ - EditableTableOption::run_on_all_rows(std::move(function)); - } - - virtual std::unique_ptr make_row() override{ - return std::unique_ptr(new RowType(*this)); - } -}; - - - - -} -#endif +/* Editable Table Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_EditableTableOption_H +#define PokemonAutomation_Options_EditableTableOption_H + +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + +class EditableTableOption; + + +// Represents a row of the table. Users should subclass this and add all the +// configs/fields that is in the row. +class EditableTableRow{ +public: + virtual ~EditableTableRow() = default; +// EditableTableRow(void* = nullptr); + EditableTableRow(EditableTableOption& parent_table); + + // Duplicate/deep-copy the entire row. Does not copy over listeners. + virtual std::unique_ptr clone() const = 0; + + EditableTableOption& parent() const{ + return m_parent_table; + } + + virtual void load_json(const JsonValue& json); + virtual JsonValue to_json() const; + + virtual std::string check_validity() const; + + +protected: + void add_option(ConfigOption& option, std::string serialization_string); + +#define PA_ADD_OPTION(x) add_option(x, #x) + + +public: + // Internal use by table. + uint64_t seqnum() const{ return m_seqnum; } + size_t index() const{ return m_index.load(std::memory_order_relaxed); } + std::vector make_cells(); + + +private: + friend class EditableTableOption; + + EditableTableOption& m_parent_table; + + // A unique # for this row within its table. + uint64_t m_seqnum = 0; + + // The index in the table it resides in. + // -1 means it's orphaned and not in the table. + std::atomic m_index; + + std::vector> m_options; +}; + + + + +// This is the table itself. +class EditableTableOption : public ConfigOption{ +public: + EditableTableOption( + std::string label, + LockMode lock_while_running, + std::vector> default_value = {} + ); + EditableTableOption( + std::string label, + LockMode lock_while_running, + bool enable_saveload, + std::vector> default_value = {} + ); + void set_default(std::vector> default_value); + +public: + const std::string& label() const{ return m_label; } + + // Returns the # of rows at this moment of time. + // Since this value can be out-of-date before you return, do not use + // this for bound-checking where it's unsafe to read out-of-bounds. + size_t current_rows() const; + + // Return a list of references to all the rows at this exact moment. + // These reference are live in that they may be asynchronously changed. + std::vector> current_refs() const; + +// SpinLock& get_lock() const{ +// return m_current_lock; +// } + + // Return a copy of the entire table at the exact moment this is called. + template + std::vector> copy_snapshot() const{ + std::vector> ret; + ReadSpinLock lg(m_current_lock); + ret.reserve(m_current.size()); + for (auto& item : m_current){ + std::unique_ptr parent = item->clone(); + std::unique_ptr ptr(static_cast(parent.release())); + ret.emplace_back(std::move(ptr)); + } + return ret; + } + template + std::vector snapshot() const{ + std::vector ret; + ReadSpinLock lg(m_current_lock); + ret.reserve(m_current.size()); + for (auto& item : m_current){ + RowType& row = static_cast(*item); + ret.emplace_back(row.snapshot()); + } + return ret; + } + + // Lambda returns a boolean. False to continue running. True to stop. + template + void run_on_all_rows(Lambda function){ + ReadSpinLock lg(m_current_lock); + for (auto& item : m_current){ + if (function(static_cast(*item))){ + return; + } + } + } + + void clear(); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override final; + +public: + bool saveload_enabled() const{ return m_enable_saveload; } + virtual std::vector make_header() const = 0; + virtual std::unique_ptr make_row() = 0; + + // Undefined behavior to call these on rows that aren't part of the table. + void insert_row(size_t index, std::unique_ptr row); + void append_row(std::unique_ptr row); + void clone_row(const EditableTableRow& row); + void remove_row(EditableTableRow& row); + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; + const bool m_enable_saveload; + mutable SpinLock m_default_lock; + std::vector> m_default; + + mutable SpinLock m_current_lock; + std::atomic m_seqnum = 0; + std::vector> m_current; +}; + + +// Convenience helper class that's type-aware. +template +class EditableTableOption_t : public EditableTableOption{ +public: + using EditableTableOption::EditableTableOption; + + std::vector> copy_snapshot() const{ + return EditableTableOption::copy_snapshot(); + } + + template + std::vector snapshot() const{ + return EditableTableOption::snapshot(); + } + + // Lambda returns a boolean. False to continue running. True to stop. + template + void run_on_all_rows(Lambda function){ + EditableTableOption::run_on_all_rows(std::move(function)); + } + + virtual std::unique_ptr make_row() override{ + return std::unique_ptr(new RowType(*this)); + } +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/EnumDropdownDatabase.cpp b/Common/Cpp/Options/EnumDropdownDatabase.cpp index eaaf066bec..1bb1834a5e 100644 --- a/Common/Cpp/Options/EnumDropdownDatabase.cpp +++ b/Common/Cpp/Options/EnumDropdownDatabase.cpp @@ -1,129 +1,129 @@ -/* Named Enum - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "EnumDropdownDatabase.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -class IntegerEnumDropdownDatabaseImpl{ -public: - void add(EnumEntry entry){ - auto scope_check = m_sanitizer.check_scope(); - size_t enum_value = entry.enum_value; - m_list.emplace_back(enum_value); - - auto ret = m_map.emplace(enum_value, std::move(entry)); - if (!ret.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string(enum_value)); - } - - auto ret1 = m_slug_to_enum.emplace(ret.first->second.slug, &ret.first->second); - if (!ret1.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Slug: " + ret.first->second.slug); - } - - auto ret2 = m_display_to_enum.emplace(ret.first->second.display, &ret.first->second); - if (!ret2.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Display: " + ret.first->second.display); - } - } - - const EnumEntry* find(size_t value) const{ - auto scope_check = m_sanitizer.check_scope(); - auto iter = m_map.find(value); - if (iter == m_map.end()){ - return nullptr; - } - return &iter->second; - } - const EnumEntry* find_slug(const std::string& slug) const{ - auto scope_check = m_sanitizer.check_scope(); - auto iter = m_slug_to_enum.find(slug); - if (iter == m_slug_to_enum.end()){ - return nullptr; - } - return iter->second; - } - const EnumEntry* find_display(const std::string& display) const{ - auto scope_check = m_sanitizer.check_scope(); - auto iter = m_display_to_enum.find(display); - if (iter == m_display_to_enum.end()){ - return nullptr; - } - return iter->second; - } - - FixedLimitVector all_values() const{ - auto scope_check = m_sanitizer.check_scope(); - FixedLimitVector ret(m_map.size()); - for (const auto& item : m_map){ - ret.emplace_back(item.first); - } - return ret; - } - -private: - using Node = typename std::map::const_iterator; - std::vector m_list; - std::map m_map; - std::map m_slug_to_enum; - std::map m_display_to_enum; - - LifetimeSanitizer m_sanitizer; -}; - - - -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x) = default; -IntegerEnumDropdownDatabase& IntegerEnumDropdownDatabase::operator=(IntegerEnumDropdownDatabase&& x) = default; -IntegerEnumDropdownDatabase::~IntegerEnumDropdownDatabase() = default; - -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(void*){} -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase() - : m_core(CONSTRUCT_TOKEN) -{} -IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(std::initializer_list list) - : m_core(CONSTRUCT_TOKEN) -{ - size_t index = 0; - for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ - add(iter->enum_value, std::move(iter->slug), std::move(iter->display), iter->enabled); - } -} -void IntegerEnumDropdownDatabase::add(EnumEntry entry){ - m_core->add(entry); -} -const EnumEntry* IntegerEnumDropdownDatabase::find(size_t value) const{ - return m_core->find(value); -} -const EnumEntry* IntegerEnumDropdownDatabase::find_slug(const std::string& slug) const{ - return m_core->find_slug(slug); -} -const EnumEntry* IntegerEnumDropdownDatabase::find_display(const std::string& display) const{ - return m_core->find_display(display); -} -FixedLimitVector IntegerEnumDropdownDatabase::all_values() const{ - return m_core->all_values(); -} - - -template class FixedLimitVector; - - - -} +/* Named Enum + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "EnumDropdownDatabase.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +class IntegerEnumDropdownDatabaseImpl{ +public: + void add(EnumEntry entry){ + auto scope_check = m_sanitizer.check_scope(); + size_t enum_value = entry.enum_value; + m_list.emplace_back(enum_value); + + auto ret = m_map.emplace(enum_value, std::move(entry)); + if (!ret.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string(enum_value)); + } + + auto ret1 = m_slug_to_enum.emplace(ret.first->second.slug, &ret.first->second); + if (!ret1.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Slug: " + ret.first->second.slug); + } + + auto ret2 = m_display_to_enum.emplace(ret.first->second.display, &ret.first->second); + if (!ret2.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum Display: " + ret.first->second.display); + } + } + + const EnumEntry* find(size_t value) const{ + auto scope_check = m_sanitizer.check_scope(); + auto iter = m_map.find(value); + if (iter == m_map.end()){ + return nullptr; + } + return &iter->second; + } + const EnumEntry* find_slug(const std::string& slug) const{ + auto scope_check = m_sanitizer.check_scope(); + auto iter = m_slug_to_enum.find(slug); + if (iter == m_slug_to_enum.end()){ + return nullptr; + } + return iter->second; + } + const EnumEntry* find_display(const std::string& display) const{ + auto scope_check = m_sanitizer.check_scope(); + auto iter = m_display_to_enum.find(display); + if (iter == m_display_to_enum.end()){ + return nullptr; + } + return iter->second; + } + + FixedLimitVector all_values() const{ + auto scope_check = m_sanitizer.check_scope(); + FixedLimitVector ret(m_map.size()); + for (const auto& item : m_map){ + ret.emplace_back(item.first); + } + return ret; + } + +private: + using Node = typename std::map::const_iterator; + std::vector m_list; + std::map m_map; + std::map m_slug_to_enum; + std::map m_display_to_enum; + + LifetimeSanitizer m_sanitizer; +}; + + + +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x) = default; +IntegerEnumDropdownDatabase& IntegerEnumDropdownDatabase::operator=(IntegerEnumDropdownDatabase&& x) = default; +IntegerEnumDropdownDatabase::~IntegerEnumDropdownDatabase() = default; + +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(void*){} +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase() + : m_core(CONSTRUCT_TOKEN) +{} +IntegerEnumDropdownDatabase::IntegerEnumDropdownDatabase(std::initializer_list list) + : m_core(CONSTRUCT_TOKEN) +{ + size_t index = 0; + for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ + add(iter->enum_value, std::move(iter->slug), std::move(iter->display), iter->enabled); + } +} +void IntegerEnumDropdownDatabase::add(EnumEntry entry){ + m_core->add(entry); +} +const EnumEntry* IntegerEnumDropdownDatabase::find(size_t value) const{ + return m_core->find(value); +} +const EnumEntry* IntegerEnumDropdownDatabase::find_slug(const std::string& slug) const{ + return m_core->find_slug(slug); +} +const EnumEntry* IntegerEnumDropdownDatabase::find_display(const std::string& display) const{ + return m_core->find_display(display); +} +FixedLimitVector IntegerEnumDropdownDatabase::all_values() const{ + return m_core->all_values(); +} + + +template class FixedLimitVector; + + + +} diff --git a/Common/Cpp/Options/EnumDropdownDatabase.h b/Common/Cpp/Options/EnumDropdownDatabase.h index 132e29aa21..2e3494d18d 100644 --- a/Common/Cpp/Options/EnumDropdownDatabase.h +++ b/Common/Cpp/Options/EnumDropdownDatabase.h @@ -1,118 +1,118 @@ -/* Enum Database - * - * From: https://github.com/PokemonAutomation/ - * - * A database that goes with an enum. - * - * This database contains information about the enum such as the display names - * and serialization slugs. - * - * This database is used to initialize an EnumDropdownCell/Option. - * - */ - -#ifndef PokemonAutomation_Options_EnumDropdownDatabase_H -#define PokemonAutomation_Options_EnumDropdownDatabase_H - -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" - -namespace PokemonAutomation{ - -class IntegerEnumDropdownDatabaseImpl; - - - - -struct EnumEntry{ - size_t enum_value; // Integer value of the enum. - std::string slug; - std::string display; - bool enabled = true; -}; - - -// This is the typeless database that uses an integer for the enum value. -class IntegerEnumDropdownDatabase{ -public: - IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x); - IntegerEnumDropdownDatabase& operator=(IntegerEnumDropdownDatabase&& x); - IntegerEnumDropdownDatabase(const IntegerEnumDropdownDatabase& x) = delete; - IntegerEnumDropdownDatabase& operator=(const IntegerEnumDropdownDatabase& x) = delete; - ~IntegerEnumDropdownDatabase(); - -public: - IntegerEnumDropdownDatabase(); // Constructs empty database. - IntegerEnumDropdownDatabase(std::initializer_list list); - - void add(EnumEntry entry); - void add(size_t value, std::string slug, std::string display, bool enabled){ - add(EnumEntry{value, std::move(slug), std::move(display), enabled}); - } - - // Find an enum. Returns null if not in the database. - const EnumEntry* find(size_t value) const; - const EnumEntry* find_slug(const std::string& slug) const; - const EnumEntry* find_display(const std::string& display) const; - - // Returns the integer enum values of everything in the database. - FixedLimitVector all_values() const; - -protected: - IntegerEnumDropdownDatabase(void*); // Constructs null database. -private: - Pimpl m_core; -}; - - - -// This is the type-safe database for your specific enum. -template -class EnumDropdownDatabase : public IntegerEnumDropdownDatabase{ -public: - struct Entry{ - EnumType value; - std::string slug; - std::string display; - bool enabled = true; - }; - -//public: -// EnumDropdownDatabase(EnumDropdownDatabase&& x) = default; -// EnumDropdownDatabase& operator=(EnumDropdownDatabase&& x) = default; - -public: - EnumDropdownDatabase() : IntegerEnumDropdownDatabase() {} - EnumDropdownDatabase(std::initializer_list list){ - size_t index = 0; - for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ - add(iter->value, std::move(iter->slug), std::move(iter->display), iter->enabled); - } - } - - void add(EnumType value, std::string slug, std::string display, bool enabled){ - IntegerEnumDropdownDatabase::add(EnumEntry{(size_t)value, std::move(slug), std::move(display), enabled}); - } - - // Find an enum. Returns null if not in the database. - const EnumEntry* find(EnumType value) const{ - return IntegerEnumDropdownDatabase::find((size_t)value); - } - EnumType find_slug(const std::string& slug) const{ - return (EnumType)IntegerEnumDropdownDatabase::find_slug(slug); - } - EnumType find_display(const std::string& display) const{ - return (EnumType)IntegerEnumDropdownDatabase::find_display(display); - } - -protected: - EnumDropdownDatabase(void*) : IntegerEnumDropdownDatabase(nullptr) {} -}; - - - - - -} -#endif +/* Enum Database + * + * From: https://github.com/PokemonAutomation/ + * + * A database that goes with an enum. + * + * This database contains information about the enum such as the display names + * and serialization slugs. + * + * This database is used to initialize an EnumDropdownCell/Option. + * + */ + +#ifndef PokemonAutomation_Options_EnumDropdownDatabase_H +#define PokemonAutomation_Options_EnumDropdownDatabase_H + +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" + +namespace PokemonAutomation{ + +class IntegerEnumDropdownDatabaseImpl; + + + + +struct EnumEntry{ + size_t enum_value; // Integer value of the enum. + std::string slug; + std::string display; + bool enabled = true; +}; + + +// This is the typeless database that uses an integer for the enum value. +class IntegerEnumDropdownDatabase{ +public: + IntegerEnumDropdownDatabase(IntegerEnumDropdownDatabase&& x); + IntegerEnumDropdownDatabase& operator=(IntegerEnumDropdownDatabase&& x); + IntegerEnumDropdownDatabase(const IntegerEnumDropdownDatabase& x) = delete; + IntegerEnumDropdownDatabase& operator=(const IntegerEnumDropdownDatabase& x) = delete; + ~IntegerEnumDropdownDatabase(); + +public: + IntegerEnumDropdownDatabase(); // Constructs empty database. + IntegerEnumDropdownDatabase(std::initializer_list list); + + void add(EnumEntry entry); + void add(size_t value, std::string slug, std::string display, bool enabled){ + add(EnumEntry{value, std::move(slug), std::move(display), enabled}); + } + + // Find an enum. Returns null if not in the database. + const EnumEntry* find(size_t value) const; + const EnumEntry* find_slug(const std::string& slug) const; + const EnumEntry* find_display(const std::string& display) const; + + // Returns the integer enum values of everything in the database. + FixedLimitVector all_values() const; + +protected: + IntegerEnumDropdownDatabase(void*); // Constructs null database. +private: + Pimpl m_core; +}; + + + +// This is the type-safe database for your specific enum. +template +class EnumDropdownDatabase : public IntegerEnumDropdownDatabase{ +public: + struct Entry{ + EnumType value; + std::string slug; + std::string display; + bool enabled = true; + }; + +//public: +// EnumDropdownDatabase(EnumDropdownDatabase&& x) = default; +// EnumDropdownDatabase& operator=(EnumDropdownDatabase&& x) = default; + +public: + EnumDropdownDatabase() : IntegerEnumDropdownDatabase() {} + EnumDropdownDatabase(std::initializer_list list){ + size_t index = 0; + for (auto iter = list.begin(); iter != list.end(); ++iter, index++){ + add(iter->value, std::move(iter->slug), std::move(iter->display), iter->enabled); + } + } + + void add(EnumType value, std::string slug, std::string display, bool enabled){ + IntegerEnumDropdownDatabase::add(EnumEntry{(size_t)value, std::move(slug), std::move(display), enabled}); + } + + // Find an enum. Returns null if not in the database. + const EnumEntry* find(EnumType value) const{ + return IntegerEnumDropdownDatabase::find((size_t)value); + } + EnumType find_slug(const std::string& slug) const{ + return (EnumType)IntegerEnumDropdownDatabase::find_slug(slug); + } + EnumType find_display(const std::string& display) const{ + return (EnumType)IntegerEnumDropdownDatabase::find_display(display); + } + +protected: + EnumDropdownDatabase(void*) : IntegerEnumDropdownDatabase(nullptr) {} +}; + + + + + +} +#endif diff --git a/Common/Cpp/Options/EnumDropdownOption.cpp b/Common/Cpp/Options/EnumDropdownOption.cpp index 570e24bb72..dee10c5d26 100644 --- a/Common/Cpp/Options/EnumDropdownOption.cpp +++ b/Common/Cpp/Options/EnumDropdownOption.cpp @@ -1,118 +1,118 @@ -/* Enum Dropdown Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "EnumDropdownOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct IntegerEnumDropdownCell::Data{ - const IntegerEnumDropdownDatabase& m_database; - const size_t m_default; - std::atomic m_current; - - Data(const IntegerEnumDropdownDatabase& database, size_t default_value, size_t current_value) - : m_database(database) - , m_default(default_value) - , m_current(current_value) - {} -}; - - - - -IntegerEnumDropdownCell::~IntegerEnumDropdownCell() = default; -IntegerEnumDropdownCell::IntegerEnumDropdownCell(const IntegerEnumDropdownCell& x) - : ConfigOption(x) - , m_data(CONSTRUCT_TOKEN, x.database(), x.default_value(), x.current_value()) -{} -IntegerEnumDropdownCell::IntegerEnumDropdownCell( - const IntegerEnumDropdownDatabase& database, - LockMode lock_while_running, - size_t default_value, size_t current_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, database, default_value, current_value) -{ - if (database.find(default_value) == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Default value is not in the database: " + std::to_string(default_value)); - } - if (database.find(current_value) == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Current value is not in the database: " + std::to_string(current_value)); - } -} -IntegerEnumDropdownCell::IntegerEnumDropdownCell( - const IntegerEnumDropdownDatabase& database, - LockMode lock_while_running, - size_t default_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, database, default_value, default_value) -{ - if (database.find(default_value) == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Default value is not in the database: " + std::to_string(default_value)); - } -} -size_t IntegerEnumDropdownCell::default_value() const{ - return m_data->m_default; -} -size_t IntegerEnumDropdownCell::current_value() const{ - return m_data->m_current.load(std::memory_order_relaxed); -} -bool IntegerEnumDropdownCell::set_value(size_t value){ - Data& data = *m_data; - if (data.m_database.find(value) == nullptr){ - return false; - } -// cout << "value = " << value << ", current = " << data.m_current.load() << endl; - if (value != data.m_current.exchange(value, std::memory_order_relaxed)){ - report_value_changed(this); - } - return true; -} -const IntegerEnumDropdownDatabase& IntegerEnumDropdownCell::database() const{ - return m_data->m_database; -} -void IntegerEnumDropdownCell::load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - Data& data = *m_data; - const EnumEntry* entry = data.m_database.find_slug(*str); - if (entry != nullptr && entry->enabled){ - data.m_current.store(entry->enum_value, std::memory_order_relaxed); - report_value_changed(this); - } - - // Backward compatibility with display names. - entry = data.m_database.find_display(*str); - if (entry != nullptr && entry->enabled){ - data.m_current.store(entry->enum_value, std::memory_order_relaxed); - report_value_changed(this); - } -} -JsonValue IntegerEnumDropdownCell::to_json() const{ - const Data& data = *m_data; - return data.m_database.find(data.m_current.load(std::memory_order_relaxed))->slug; -} -void IntegerEnumDropdownCell::restore_defaults(){ - set_value(m_data->m_default); -} - - - - - - -} +/* Enum Dropdown Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "EnumDropdownOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct IntegerEnumDropdownCell::Data{ + const IntegerEnumDropdownDatabase& m_database; + const size_t m_default; + std::atomic m_current; + + Data(const IntegerEnumDropdownDatabase& database, size_t default_value, size_t current_value) + : m_database(database) + , m_default(default_value) + , m_current(current_value) + {} +}; + + + + +IntegerEnumDropdownCell::~IntegerEnumDropdownCell() = default; +IntegerEnumDropdownCell::IntegerEnumDropdownCell(const IntegerEnumDropdownCell& x) + : ConfigOption(x) + , m_data(CONSTRUCT_TOKEN, x.database(), x.default_value(), x.current_value()) +{} +IntegerEnumDropdownCell::IntegerEnumDropdownCell( + const IntegerEnumDropdownDatabase& database, + LockMode lock_while_running, + size_t default_value, size_t current_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, database, default_value, current_value) +{ + if (database.find(default_value) == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Default value is not in the database: " + std::to_string(default_value)); + } + if (database.find(current_value) == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Current value is not in the database: " + std::to_string(current_value)); + } +} +IntegerEnumDropdownCell::IntegerEnumDropdownCell( + const IntegerEnumDropdownDatabase& database, + LockMode lock_while_running, + size_t default_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, database, default_value, default_value) +{ + if (database.find(default_value) == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Default value is not in the database: " + std::to_string(default_value)); + } +} +size_t IntegerEnumDropdownCell::default_value() const{ + return m_data->m_default; +} +size_t IntegerEnumDropdownCell::current_value() const{ + return m_data->m_current.load(std::memory_order_relaxed); +} +bool IntegerEnumDropdownCell::set_value(size_t value){ + Data& data = *m_data; + if (data.m_database.find(value) == nullptr){ + return false; + } +// cout << "value = " << value << ", current = " << data.m_current.load() << endl; + if (value != data.m_current.exchange(value, std::memory_order_relaxed)){ + report_value_changed(this); + } + return true; +} +const IntegerEnumDropdownDatabase& IntegerEnumDropdownCell::database() const{ + return m_data->m_database; +} +void IntegerEnumDropdownCell::load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + Data& data = *m_data; + const EnumEntry* entry = data.m_database.find_slug(*str); + if (entry != nullptr && entry->enabled){ + data.m_current.store(entry->enum_value, std::memory_order_relaxed); + report_value_changed(this); + } + + // Backward compatibility with display names. + entry = data.m_database.find_display(*str); + if (entry != nullptr && entry->enabled){ + data.m_current.store(entry->enum_value, std::memory_order_relaxed); + report_value_changed(this); + } +} +JsonValue IntegerEnumDropdownCell::to_json() const{ + const Data& data = *m_data; + return data.m_database.find(data.m_current.load(std::memory_order_relaxed))->slug; +} +void IntegerEnumDropdownCell::restore_defaults(){ + set_value(m_data->m_default); +} + + + + + + +} diff --git a/Common/Cpp/Options/EnumDropdownOption.h b/Common/Cpp/Options/EnumDropdownOption.h index 7512412c1a..e1f7404303 100644 --- a/Common/Cpp/Options/EnumDropdownOption.h +++ b/Common/Cpp/Options/EnumDropdownOption.h @@ -1,179 +1,179 @@ -/* Enum Dropdown Option - * - * From: https://github.com/PokemonAutomation/ - * - * A simple dropdown menu for enums. - * - * This should only be used when the number of options is small. If you need - * something for many options, use StringSelectCell/Option instead. - * - */ - -#ifndef PokemonAutomation_Options_EnumDropdownOption_H -#define PokemonAutomation_Options_EnumDropdownOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" -#include "EnumDropdownDatabase.h" - -namespace PokemonAutomation{ - - -// This is the typeless class that uses an integer for the enum value. -class IntegerEnumDropdownCell : public ConfigOption{ -public: - ~IntegerEnumDropdownCell(); - IntegerEnumDropdownCell(const IntegerEnumDropdownCell& x); - -public: - IntegerEnumDropdownCell( - const IntegerEnumDropdownDatabase& database, - LockMode lock_while_running, - size_t default_value, size_t current_value - ); - IntegerEnumDropdownCell( - const IntegerEnumDropdownDatabase& database, - LockMode lock_while_running, - size_t default_value - ); - - // Constructing from inlined database is not supported for cell. - IntegerEnumDropdownCell(IntegerEnumDropdownDatabase&& database, - LockMode lock_while_running, - size_t default_value, size_t current_value - ) = delete; - IntegerEnumDropdownCell(IntegerEnumDropdownDatabase&& database, - LockMode lock_while_running, - size_t default_value - ) = delete; - - size_t default_value() const; - size_t current_value() const; - - virtual bool set_value(size_t value); - - const IntegerEnumDropdownDatabase& database() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - -// This is the type-safe class for your enum type. -template -class EnumDropdownCell : public IntegerEnumDropdownCell{ -public: - EnumDropdownCell( - const EnumDropdownDatabase& database, - LockMode lock_while_running, - EnumType default_value - ) - : IntegerEnumDropdownCell(database, lock_while_running, (size_t)default_value) - {} - - // Constructing from inlined database is not supported for cell. - EnumDropdownCell( - EnumDropdownDatabase&& database, - LockMode lock_while_running, - EnumType default_value - ) = delete; - - operator EnumType() const{ - return (EnumType)current_value(); - } - bool set(EnumType value){ - return set_value((size_t)value); - } - -#if 1 - const std::string& current_slug() const{ - return database().find(current_value())->slug; - } - const std::string& current_display() const{ - return database().find(current_value())->display; - } -#endif -}; - - - - -class IntegerEnumDropdownOption : private IntegerEnumDropdownDatabase, public IntegerEnumDropdownCell{ -public: - IntegerEnumDropdownOption(const IntegerEnumDropdownOption& x) = delete; - IntegerEnumDropdownOption( - std::string label, - const IntegerEnumDropdownDatabase& database, - LockMode lock_while_running, - size_t default_value - ) - : IntegerEnumDropdownDatabase(nullptr) - , IntegerEnumDropdownCell(database, lock_while_running, default_value) - , m_label(std::move(label)) - {} - IntegerEnumDropdownOption( - std::string label, - IntegerEnumDropdownDatabase&& database, - LockMode lock_while_running, - size_t default_value - ) - : IntegerEnumDropdownDatabase(std::move(database)) - , IntegerEnumDropdownCell(*this, lock_while_running, default_value) - , m_label(std::move(label)) - {} - - const std::string& label() const{ return m_label; } - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - -template -class EnumDropdownOption : public IntegerEnumDropdownOption{ -public: - EnumDropdownOption( - std::string label, - const EnumDropdownDatabase& database, - LockMode lock_while_running, - EnumType default_value - ) - : IntegerEnumDropdownOption(std::move(label), database, lock_while_running, (size_t)default_value) - {} - EnumDropdownOption( - std::string label, - EnumDropdownDatabase&& database, - LockMode lock_while_running, - EnumType default_value - ) - : IntegerEnumDropdownOption(std::move(label), std::move(database), lock_while_running, (size_t)default_value) - {} - - operator EnumType() const{ - return (EnumType)current_value(); - } - EnumType get() const{ - return (EnumType)current_value(); - } - bool set(EnumType value){ - return set_value((size_t)value); - } -}; - - - - - - -} -#endif +/* Enum Dropdown Option + * + * From: https://github.com/PokemonAutomation/ + * + * A simple dropdown menu for enums. + * + * This should only be used when the number of options is small. If you need + * something for many options, use StringSelectCell/Option instead. + * + */ + +#ifndef PokemonAutomation_Options_EnumDropdownOption_H +#define PokemonAutomation_Options_EnumDropdownOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" +#include "EnumDropdownDatabase.h" + +namespace PokemonAutomation{ + + +// This is the typeless class that uses an integer for the enum value. +class IntegerEnumDropdownCell : public ConfigOption{ +public: + ~IntegerEnumDropdownCell(); + IntegerEnumDropdownCell(const IntegerEnumDropdownCell& x); + +public: + IntegerEnumDropdownCell( + const IntegerEnumDropdownDatabase& database, + LockMode lock_while_running, + size_t default_value, size_t current_value + ); + IntegerEnumDropdownCell( + const IntegerEnumDropdownDatabase& database, + LockMode lock_while_running, + size_t default_value + ); + + // Constructing from inlined database is not supported for cell. + IntegerEnumDropdownCell(IntegerEnumDropdownDatabase&& database, + LockMode lock_while_running, + size_t default_value, size_t current_value + ) = delete; + IntegerEnumDropdownCell(IntegerEnumDropdownDatabase&& database, + LockMode lock_while_running, + size_t default_value + ) = delete; + + size_t default_value() const; + size_t current_value() const; + + virtual bool set_value(size_t value); + + const IntegerEnumDropdownDatabase& database() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + +// This is the type-safe class for your enum type. +template +class EnumDropdownCell : public IntegerEnumDropdownCell{ +public: + EnumDropdownCell( + const EnumDropdownDatabase& database, + LockMode lock_while_running, + EnumType default_value + ) + : IntegerEnumDropdownCell(database, lock_while_running, (size_t)default_value) + {} + + // Constructing from inlined database is not supported for cell. + EnumDropdownCell( + EnumDropdownDatabase&& database, + LockMode lock_while_running, + EnumType default_value + ) = delete; + + operator EnumType() const{ + return (EnumType)current_value(); + } + bool set(EnumType value){ + return set_value((size_t)value); + } + +#if 1 + const std::string& current_slug() const{ + return database().find(current_value())->slug; + } + const std::string& current_display() const{ + return database().find(current_value())->display; + } +#endif +}; + + + + +class IntegerEnumDropdownOption : private IntegerEnumDropdownDatabase, public IntegerEnumDropdownCell{ +public: + IntegerEnumDropdownOption(const IntegerEnumDropdownOption& x) = delete; + IntegerEnumDropdownOption( + std::string label, + const IntegerEnumDropdownDatabase& database, + LockMode lock_while_running, + size_t default_value + ) + : IntegerEnumDropdownDatabase(nullptr) + , IntegerEnumDropdownCell(database, lock_while_running, default_value) + , m_label(std::move(label)) + {} + IntegerEnumDropdownOption( + std::string label, + IntegerEnumDropdownDatabase&& database, + LockMode lock_while_running, + size_t default_value + ) + : IntegerEnumDropdownDatabase(std::move(database)) + , IntegerEnumDropdownCell(*this, lock_while_running, default_value) + , m_label(std::move(label)) + {} + + const std::string& label() const{ return m_label; } + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + +template +class EnumDropdownOption : public IntegerEnumDropdownOption{ +public: + EnumDropdownOption( + std::string label, + const EnumDropdownDatabase& database, + LockMode lock_while_running, + EnumType default_value + ) + : IntegerEnumDropdownOption(std::move(label), database, lock_while_running, (size_t)default_value) + {} + EnumDropdownOption( + std::string label, + EnumDropdownDatabase&& database, + LockMode lock_while_running, + EnumType default_value + ) + : IntegerEnumDropdownOption(std::move(label), std::move(database), lock_while_running, (size_t)default_value) + {} + + operator EnumType() const{ + return (EnumType)current_value(); + } + EnumType get() const{ + return (EnumType)current_value(); + } + bool set(EnumType value){ + return set_value((size_t)value); + } +}; + + + + + + +} +#endif diff --git a/Common/Cpp/Options/FixedCodeOption.cpp b/Common/Cpp/Options/FixedCodeOption.cpp index 3072b38be4..9ff9ea9fca 100644 --- a/Common/Cpp/Options/FixedCodeOption.cpp +++ b/Common/Cpp/Options/FixedCodeOption.cpp @@ -1,134 +1,134 @@ -/* Fixed Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/CodeValidator.h" -#include "FixedCodeOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct FixedCodeOption::Data{ - std::string m_label; - const size_t m_digits; - const std::string m_default; - - mutable SpinLock m_lock; - std::string m_current; - - Data( - std::string label, - size_t digits, - std::string default_value - ) - : m_label(std::move(label)) - , m_digits(digits) - , m_default(default_value) - , m_current(std::move(default_value)) - {} -}; - - -FixedCodeOption::~FixedCodeOption() = default; -FixedCodeOption::FixedCodeOption( - std::string label, - size_t digits, - std::string default_value -) - : m_data(CONSTRUCT_TOKEN, std::move(label), digits, std::move(default_value)) -{} -#if 0 -std::unique_ptr FixedCodeOption::clone() const{ - std::unique_ptr ret(new FixedCodeOption(m_label, m_digits, m_default)); - ret->m_current = m_current; - return ret; -} -#endif - -const std::string& FixedCodeOption::label() const{ - return m_data->m_label; -} -size_t FixedCodeOption::digits() const{ - return m_data->m_digits; -} - -FixedCodeOption::operator const std::string&() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -const std::string& FixedCodeOption::get() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -std::string FixedCodeOption::set(std::string x){ - std::string error = check_validity(x); - if (!error.empty()){ - return error; - } - { - WriteSpinLock lg(m_data->m_lock); - if (m_data->m_current == x){ - return std::string(); - } - m_data->m_current = std::move(x); - } - report_value_changed(this); - return std::string(); -} - -void FixedCodeOption::load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - { - WriteSpinLock lg(m_data->m_lock); - m_data->m_current = *str; - } - report_value_changed(this); -} -JsonValue FixedCodeOption::to_json() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} - -std::string FixedCodeOption::to_str() const{ - { - ReadSpinLock lg(m_data->m_lock); - return sanitize_code(8, m_data->m_current); - } -} - -std::string FixedCodeOption::check_validity() const{ - ReadSpinLock lg(m_data->m_lock); - return check_validity(m_data->m_current); -} -std::string FixedCodeOption::check_validity(const std::string& x) const{ - return validate_code(m_data->m_digits, x) ? std::string() : "Code is invalid."; -} -void FixedCodeOption::restore_defaults(){ - { - WriteSpinLock lg(m_data->m_lock); - if (m_data->m_current == m_data->m_default){ - return; - } - m_data->m_current = m_data->m_default; - } - report_value_changed(this); -} - - - - - - -} +/* Fixed Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/CodeValidator.h" +#include "FixedCodeOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct FixedCodeOption::Data{ + std::string m_label; + const size_t m_digits; + const std::string m_default; + + mutable SpinLock m_lock; + std::string m_current; + + Data( + std::string label, + size_t digits, + std::string default_value + ) + : m_label(std::move(label)) + , m_digits(digits) + , m_default(default_value) + , m_current(std::move(default_value)) + {} +}; + + +FixedCodeOption::~FixedCodeOption() = default; +FixedCodeOption::FixedCodeOption( + std::string label, + size_t digits, + std::string default_value +) + : m_data(CONSTRUCT_TOKEN, std::move(label), digits, std::move(default_value)) +{} +#if 0 +std::unique_ptr FixedCodeOption::clone() const{ + std::unique_ptr ret(new FixedCodeOption(m_label, m_digits, m_default)); + ret->m_current = m_current; + return ret; +} +#endif + +const std::string& FixedCodeOption::label() const{ + return m_data->m_label; +} +size_t FixedCodeOption::digits() const{ + return m_data->m_digits; +} + +FixedCodeOption::operator const std::string&() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +const std::string& FixedCodeOption::get() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +std::string FixedCodeOption::set(std::string x){ + std::string error = check_validity(x); + if (!error.empty()){ + return error; + } + { + WriteSpinLock lg(m_data->m_lock); + if (m_data->m_current == x){ + return std::string(); + } + m_data->m_current = std::move(x); + } + report_value_changed(this); + return std::string(); +} + +void FixedCodeOption::load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + { + WriteSpinLock lg(m_data->m_lock); + m_data->m_current = *str; + } + report_value_changed(this); +} +JsonValue FixedCodeOption::to_json() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} + +std::string FixedCodeOption::to_str() const{ + { + ReadSpinLock lg(m_data->m_lock); + return sanitize_code(8, m_data->m_current); + } +} + +std::string FixedCodeOption::check_validity() const{ + ReadSpinLock lg(m_data->m_lock); + return check_validity(m_data->m_current); +} +std::string FixedCodeOption::check_validity(const std::string& x) const{ + return validate_code(m_data->m_digits, x) ? std::string() : "Code is invalid."; +} +void FixedCodeOption::restore_defaults(){ + { + WriteSpinLock lg(m_data->m_lock); + if (m_data->m_current == m_data->m_default){ + return; + } + m_data->m_current = m_data->m_default; + } + report_value_changed(this); +} + + + + + + +} diff --git a/Common/Cpp/Options/FixedCodeOption.h b/Common/Cpp/Options/FixedCodeOption.h index 32614712a6..fca2625b59 100644 --- a/Common/Cpp/Options/FixedCodeOption.h +++ b/Common/Cpp/Options/FixedCodeOption.h @@ -1,51 +1,51 @@ -/* Fixed Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_FixedCodeOption_H -#define PokemonAutomation_Options_FixedCodeOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -class FixedCodeOption : public ConfigOption{ -public: - ~FixedCodeOption(); - FixedCodeOption( - std::string label, - size_t digits, - std::string default_value - ); -// virtual std::unique_ptr clone() const override; - - const std::string& label() const; - size_t digits() const; - - operator const std::string&() const; - const std::string& get() const; - std::string set(std::string x); - std::string to_str() const; - - virtual std::string check_validity() const override; - std::string check_validity(const std::string& x) const; - virtual void restore_defaults() override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - -} -#endif +/* Fixed Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_FixedCodeOption_H +#define PokemonAutomation_Options_FixedCodeOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +class FixedCodeOption : public ConfigOption{ +public: + ~FixedCodeOption(); + FixedCodeOption( + std::string label, + size_t digits, + std::string default_value + ); +// virtual std::unique_ptr clone() const override; + + const std::string& label() const; + size_t digits() const; + + operator const std::string&() const; + const std::string& get() const; + std::string set(std::string x); + std::string to_str() const; + + virtual std::string check_validity() const override; + std::string check_validity(const std::string& x) const; + virtual void restore_defaults() override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + +} +#endif diff --git a/Common/Cpp/Options/FloatingPointOption.cpp b/Common/Cpp/Options/FloatingPointOption.cpp index 6d5b63d9f2..d99aac81de 100644 --- a/Common/Cpp/Options/FloatingPointOption.cpp +++ b/Common/Cpp/Options/FloatingPointOption.cpp @@ -1,150 +1,150 @@ -/* Floating-Point Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "FloatingPointOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct FloatingPointCell::Data{ - const double m_min_value; - const double m_max_value; - const double m_default; - std::atomic m_current; - - Data( - double min_value, double max_value, - double default_value, double current_value - ) - : m_min_value(min_value) - , m_max_value(max_value) - , m_default(default_value) - , m_current(current_value) - {} -}; - - - -FloatingPointCell::~FloatingPointCell() = default; -FloatingPointCell::FloatingPointCell(const FloatingPointCell& x) - : ConfigOption(x) - , m_data(CONSTRUCT_TOKEN, x.min_value(), x.max_value(), x.default_value(), x) -{} -FloatingPointCell::FloatingPointCell( - LockMode lock_while_running, - double min_value, double max_value, - double default_value, double current_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, current_value) -{} - - -FloatingPointCell::FloatingPointCell( - LockMode lock_while_running, - double default_value, - double min_value, - double max_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, default_value) -{} - - -double FloatingPointCell::min_value() const{ - return m_data->m_min_value; -} -double FloatingPointCell::max_value() const{ - return m_data->m_max_value; -} -double FloatingPointCell::default_value() const{ - return m_data->m_default; -} - -FloatingPointCell::operator double() const{ - return m_data->m_current.load(std::memory_order_relaxed); -} - - -std::string FloatingPointCell::set(double x){ - std::string err = check_validity(x); - if (!err.empty()){ - return err; - } - if (x != m_data->m_current.exchange(x, std::memory_order_relaxed)){ - report_value_changed(this); - } - return err; -} - -void FloatingPointCell::load_json(const JsonValue& json){ - double value; - if (!json.read_float(value)){ - return; - } - Data& data = *m_data; - value = std::max(value, data.m_min_value); - value = std::min(value, data.m_max_value); - if (std::isnan(value)){ - value = data.m_default; - } - set(value); -} -JsonValue FloatingPointCell::to_json() const{ - return (double)*this; -} - -std::string FloatingPointCell::check_validity(double x) const{ - const Data& data = *m_data; - if (x < data.m_min_value){ - std::ostringstream ss; - return "Value too small: min = " + tostr_default(data.m_min_value) + ", value = " + tostr_default(x); - } - if (x > data.m_max_value){ - std::ostringstream ss; - return "Value too large: max = " + tostr_default(data.m_max_value) + ", value = " + tostr_default(x); - } - if (std::isnan(x)){ - return "Value is NaN."; - } - return std::string(); -} -std::string FloatingPointCell::check_validity() const{ - return check_validity(*this); -} -void FloatingPointCell::restore_defaults(){ - set(m_data->m_default); -} - - - - - -FloatingPointOption::FloatingPointOption( - std::string label, - LockMode lock_while_running, - double default_value, - double min_value, - double max_value -) - : FloatingPointCell(lock_while_running, default_value, min_value, max_value) - , m_label(std::move(label)) -{} - - - - -} +/* Floating-Point Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "FloatingPointOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct FloatingPointCell::Data{ + const double m_min_value; + const double m_max_value; + const double m_default; + std::atomic m_current; + + Data( + double min_value, double max_value, + double default_value, double current_value + ) + : m_min_value(min_value) + , m_max_value(max_value) + , m_default(default_value) + , m_current(current_value) + {} +}; + + + +FloatingPointCell::~FloatingPointCell() = default; +FloatingPointCell::FloatingPointCell(const FloatingPointCell& x) + : ConfigOption(x) + , m_data(CONSTRUCT_TOKEN, x.min_value(), x.max_value(), x.default_value(), x) +{} +FloatingPointCell::FloatingPointCell( + LockMode lock_while_running, + double min_value, double max_value, + double default_value, double current_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, current_value) +{} + + +FloatingPointCell::FloatingPointCell( + LockMode lock_while_running, + double default_value, + double min_value, + double max_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, default_value) +{} + + +double FloatingPointCell::min_value() const{ + return m_data->m_min_value; +} +double FloatingPointCell::max_value() const{ + return m_data->m_max_value; +} +double FloatingPointCell::default_value() const{ + return m_data->m_default; +} + +FloatingPointCell::operator double() const{ + return m_data->m_current.load(std::memory_order_relaxed); +} + + +std::string FloatingPointCell::set(double x){ + std::string err = check_validity(x); + if (!err.empty()){ + return err; + } + if (x != m_data->m_current.exchange(x, std::memory_order_relaxed)){ + report_value_changed(this); + } + return err; +} + +void FloatingPointCell::load_json(const JsonValue& json){ + double value; + if (!json.read_float(value)){ + return; + } + Data& data = *m_data; + value = std::max(value, data.m_min_value); + value = std::min(value, data.m_max_value); + if (std::isnan(value)){ + value = data.m_default; + } + set(value); +} +JsonValue FloatingPointCell::to_json() const{ + return (double)*this; +} + +std::string FloatingPointCell::check_validity(double x) const{ + const Data& data = *m_data; + if (x < data.m_min_value){ + std::ostringstream ss; + return "Value too small: min = " + tostr_default(data.m_min_value) + ", value = " + tostr_default(x); + } + if (x > data.m_max_value){ + std::ostringstream ss; + return "Value too large: max = " + tostr_default(data.m_max_value) + ", value = " + tostr_default(x); + } + if (std::isnan(x)){ + return "Value is NaN."; + } + return std::string(); +} +std::string FloatingPointCell::check_validity() const{ + return check_validity(*this); +} +void FloatingPointCell::restore_defaults(){ + set(m_data->m_default); +} + + + + + +FloatingPointOption::FloatingPointOption( + std::string label, + LockMode lock_while_running, + double default_value, + double min_value, + double max_value +) + : FloatingPointCell(lock_while_running, default_value, min_value, max_value) + , m_label(std::move(label)) +{} + + + + +} diff --git a/Common/Cpp/Options/FloatingPointOption.h b/Common/Cpp/Options/FloatingPointOption.h index 78dbd28ebc..edd36c3b5e 100644 --- a/Common/Cpp/Options/FloatingPointOption.h +++ b/Common/Cpp/Options/FloatingPointOption.h @@ -1,81 +1,81 @@ -/* Floating-Point Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_FloatingPointOption_H -#define PokemonAutomation_Options_FloatingPointOption_H - -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -class FloatingPointCell : public ConfigOption{ -public: - ~FloatingPointCell(); - FloatingPointCell(const FloatingPointCell& x); - FloatingPointCell( - LockMode lock_while_running, - double min_value, double max_value, - double default_value, double current_value - ); - -public: - FloatingPointCell( - LockMode lock_while_running, - double default_value, - double min_value = -std::numeric_limits::max(), - double max_value = std::numeric_limits::max() - ); - - double min_value() const; - double max_value() const; - double default_value() const; - - operator double() const; - std::string set(double x); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - std::string check_validity(double x) const; - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - -class FloatingPointOption : public FloatingPointCell{ -public: - FloatingPointOption(const FloatingPointOption& x) = delete; - - FloatingPointOption( - std::string label, - LockMode lock_while_running, - double default_value, - double min_value = -std::numeric_limits::max(), - double max_value = std::numeric_limits::max() - ); - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - -} -#endif - +/* Floating-Point Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_FloatingPointOption_H +#define PokemonAutomation_Options_FloatingPointOption_H + +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +class FloatingPointCell : public ConfigOption{ +public: + ~FloatingPointCell(); + FloatingPointCell(const FloatingPointCell& x); + FloatingPointCell( + LockMode lock_while_running, + double min_value, double max_value, + double default_value, double current_value + ); + +public: + FloatingPointCell( + LockMode lock_while_running, + double default_value, + double min_value = -std::numeric_limits::max(), + double max_value = std::numeric_limits::max() + ); + + double min_value() const; + double max_value() const; + double default_value() const; + + operator double() const; + std::string set(double x); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + std::string check_validity(double x) const; + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + +class FloatingPointOption : public FloatingPointCell{ +public: + FloatingPointOption(const FloatingPointOption& x) = delete; + + FloatingPointOption( + std::string label, + LockMode lock_while_running, + double default_value, + double min_value = -std::numeric_limits::max(), + double max_value = std::numeric_limits::max() + ); + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + +} +#endif + diff --git a/Common/Cpp/Options/GroupOption.cpp b/Common/Cpp/Options/GroupOption.cpp index 9d62ff3e34..f0959d3c3f 100644 --- a/Common/Cpp/Options/GroupOption.cpp +++ b/Common/Cpp/Options/GroupOption.cpp @@ -1,110 +1,110 @@ -/* Group Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "GroupOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct GroupOption::Data{ - const std::string m_label; - const EnableMode m_enable_mode; - const bool m_show_restore_defaults_button; - - std::atomic m_enabled; - - Data( - std::string label, - EnableMode enable_mode, - bool show_restore_defaults_button - ) - : m_label(std::move(label)) - , m_enable_mode(enable_mode) - , m_show_restore_defaults_button(show_restore_defaults_button) - , m_enabled(enable_mode != EnableMode::DEFAULT_DISABLED) - {} -}; - - -GroupOption::~GroupOption() = default; -GroupOption::GroupOption( - std::string label, - LockMode lock_while_program_is_running, - EnableMode enable_mode, - bool show_restore_defaults_button -) - : BatchOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, std::move(label), enable_mode, show_restore_defaults_button) -{} - -const std::string GroupOption::label() const{ - return m_data->m_label; -} -bool GroupOption::toggleable() const{ - return m_data->m_enable_mode != EnableMode::ALWAYS_ENABLED; -} -bool GroupOption::enabled() const{ - return m_data->m_enabled.load(std::memory_order_relaxed); -} -void GroupOption::set_enabled(bool enabled){ - if (enabled != m_data->m_enabled.exchange(enabled, std::memory_order_relaxed)){ - report_value_changed(this); - on_set_enabled(enabled); - } -} -bool GroupOption::restore_defaults_button_enabled() const{ - return m_data->m_show_restore_defaults_button; -} - -void GroupOption::load_json(const JsonValue& json){ - BatchOption::load_json(json); - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - if (toggleable()){ - bool enabled; - if (obj->read_boolean(enabled, "Enabled")){ - if (enabled != m_data->m_enabled.exchange(enabled, std::memory_order_relaxed)){ - report_value_changed(this); - } - on_set_enabled(enabled); - } - } -} -JsonValue GroupOption::to_json() const{ - JsonObject obj = std::move(*BatchOption::to_json().to_object()); - if (toggleable()){ - obj["Enabled"] = m_data->m_enabled.load(std::memory_order_relaxed); - } - return obj; -} -void GroupOption::restore_defaults(){ - BatchOption::restore_defaults(); - if (toggleable()){ - bool default_value = m_data->m_enable_mode == EnableMode::DEFAULT_ENABLED; - if (default_value != m_data->m_enabled.exchange(default_value, std::memory_order_relaxed)){ - report_value_changed(this); - on_set_enabled(default_value); - } - } -} -void GroupOption::on_set_enabled(bool enabled){} - - - - - -} +/* Group Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "GroupOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct GroupOption::Data{ + const std::string m_label; + const EnableMode m_enable_mode; + const bool m_show_restore_defaults_button; + + std::atomic m_enabled; + + Data( + std::string label, + EnableMode enable_mode, + bool show_restore_defaults_button + ) + : m_label(std::move(label)) + , m_enable_mode(enable_mode) + , m_show_restore_defaults_button(show_restore_defaults_button) + , m_enabled(enable_mode != EnableMode::DEFAULT_DISABLED) + {} +}; + + +GroupOption::~GroupOption() = default; +GroupOption::GroupOption( + std::string label, + LockMode lock_while_program_is_running, + EnableMode enable_mode, + bool show_restore_defaults_button +) + : BatchOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, std::move(label), enable_mode, show_restore_defaults_button) +{} + +const std::string GroupOption::label() const{ + return m_data->m_label; +} +bool GroupOption::toggleable() const{ + return m_data->m_enable_mode != EnableMode::ALWAYS_ENABLED; +} +bool GroupOption::enabled() const{ + return m_data->m_enabled.load(std::memory_order_relaxed); +} +void GroupOption::set_enabled(bool enabled){ + if (enabled != m_data->m_enabled.exchange(enabled, std::memory_order_relaxed)){ + report_value_changed(this); + on_set_enabled(enabled); + } +} +bool GroupOption::restore_defaults_button_enabled() const{ + return m_data->m_show_restore_defaults_button; +} + +void GroupOption::load_json(const JsonValue& json){ + BatchOption::load_json(json); + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + if (toggleable()){ + bool enabled; + if (obj->read_boolean(enabled, "Enabled")){ + if (enabled != m_data->m_enabled.exchange(enabled, std::memory_order_relaxed)){ + report_value_changed(this); + } + on_set_enabled(enabled); + } + } +} +JsonValue GroupOption::to_json() const{ + JsonObject obj = std::move(*BatchOption::to_json().to_object()); + if (toggleable()){ + obj["Enabled"] = m_data->m_enabled.load(std::memory_order_relaxed); + } + return obj; +} +void GroupOption::restore_defaults(){ + BatchOption::restore_defaults(); + if (toggleable()){ + bool default_value = m_data->m_enable_mode == EnableMode::DEFAULT_ENABLED; + if (default_value != m_data->m_enabled.exchange(default_value, std::memory_order_relaxed)){ + report_value_changed(this); + on_set_enabled(default_value); + } + } +} +void GroupOption::on_set_enabled(bool enabled){} + + + + + +} diff --git a/Common/Cpp/Options/GroupOption.h b/Common/Cpp/Options/GroupOption.h index 5cbc177ea7..e32d9ec944 100644 --- a/Common/Cpp/Options/GroupOption.h +++ b/Common/Cpp/Options/GroupOption.h @@ -1,60 +1,60 @@ -/* Group Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_GroupOption_H -#define PokemonAutomation_Options_GroupOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "BatchOption.h" - -namespace PokemonAutomation{ - - -class GroupOption : public BatchOption{ -public: - enum class EnableMode{ - ALWAYS_ENABLED, - DEFAULT_DISABLED, - DEFAULT_ENABLED, - }; - - ~GroupOption(); - GroupOption( - std::string label, - LockMode lock_while_program_is_running, - EnableMode enable_mode = EnableMode::ALWAYS_ENABLED, - bool show_restore_defaults_button = false - ); - - const std::string label() const; - - bool toggleable() const; - bool enabled() const; - void set_enabled(bool enabled); - - bool restore_defaults_button_enabled() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -public: - // Callbacks - virtual void on_set_enabled(bool enabled); - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Group Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_GroupOption_H +#define PokemonAutomation_Options_GroupOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "BatchOption.h" + +namespace PokemonAutomation{ + + +class GroupOption : public BatchOption{ +public: + enum class EnableMode{ + ALWAYS_ENABLED, + DEFAULT_DISABLED, + DEFAULT_ENABLED, + }; + + ~GroupOption(); + GroupOption( + std::string label, + LockMode lock_while_program_is_running, + EnableMode enable_mode = EnableMode::ALWAYS_ENABLED, + bool show_restore_defaults_button = false + ); + + const std::string label() const; + + bool toggleable() const; + bool enabled() const; + void set_enabled(bool enabled); + + bool restore_defaults_button_enabled() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +public: + // Callbacks + virtual void on_set_enabled(bool enabled); + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/IntegerRangeOption.cpp b/Common/Cpp/Options/IntegerRangeOption.cpp index 4789bf518e..9d08627ebc 100644 --- a/Common/Cpp/Options/IntegerRangeOption.cpp +++ b/Common/Cpp/Options/IntegerRangeOption.cpp @@ -1,265 +1,265 @@ -/* Integer Range Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "IntegerRangeOption.h" - -#include "Common/Qt/Options/IntegerRangeWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -ConfigWidget* IntegerRangeCell::make_QtWidget(QWidget& parent){ - return new IntegerRangeCellWidget(parent, *this); -} - - - -template -struct IntegerRangeCell::Data{ - const Type m_lo_min_value; - const Type m_lo_max_value; - const Type m_hi_min_value; - const Type m_hi_max_value; - const Type m_lo_default; - const Type m_hi_default; - - mutable SpinLock m_lock; - std::atomic m_lo_current; - std::atomic m_hi_current; - - Data( - Type lo_min_value, Type lo_max_value, Type lo_default_value, Type lo_current_value, - Type hi_min_value, Type hi_max_value, Type hi_default_value, Type hi_current_value - ) - : m_lo_min_value(lo_min_value), m_lo_max_value(lo_max_value) - , m_hi_min_value(hi_min_value), m_hi_max_value(hi_max_value) - , m_lo_default(lo_default_value) - , m_hi_default(hi_default_value) - , m_lo_current(lo_current_value) - , m_hi_current(hi_current_value) - { - if (lo_min_value > lo_max_value || - hi_min_value > hi_max_value || - lo_min_value > hi_min_value || - lo_max_value > hi_max_value || - lo_max_value < hi_min_value - ){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Limits are incompatible."); - } - if (!(lo_min_value <= lo_default_value && lo_default_value <= lo_max_value)){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Low default is out of range."); - } - if (!(hi_min_value <= hi_default_value && hi_default_value <= hi_max_value)){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "High default is out of range."); - } - if (lo_default_value > hi_default_value){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Default values are incompatible."); - } - if (lo_current_value > hi_current_value){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Current values are incompatible."); - } - } -}; - - - -template -IntegerRangeCell::~IntegerRangeCell() = default; -template -IntegerRangeCell::IntegerRangeCell(const IntegerRangeCell& x) - : ConfigOption(x) - , m_data( - CONSTRUCT_TOKEN, - x.lo_min_value(), x.lo_max_value(), x.lo_default_value(), x.lo_current_value(), - x.hi_min_value(), x.hi_max_value(), x.hi_default_value(), x.hi_current_value() - ) -{} -template -IntegerRangeCell::IntegerRangeCell( - LockMode lock_while_running, - Type lo_min_value, Type lo_max_value, Type lo_default_value, Type lo_current_value, - Type hi_min_value, Type hi_max_value, Type hi_default_value, Type hi_current_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - lo_min_value, lo_max_value, lo_default_value, lo_current_value, - hi_min_value, hi_max_value, hi_default_value, hi_current_value - ) -{} - -template -Type IntegerRangeCell::lo_min_value() const{ - return m_data->m_lo_min_value; -} -template -Type IntegerRangeCell::lo_max_value() const{ - return m_data->m_lo_max_value; -} -template -Type IntegerRangeCell::lo_default_value() const{ - return m_data->m_lo_default; -} -template -Type IntegerRangeCell::hi_min_value() const{ - return m_data->m_hi_min_value; - -} -template -Type IntegerRangeCell::hi_max_value() const{ - return m_data->m_hi_max_value; -} -template -Type IntegerRangeCell::hi_default_value() const{ - return m_data->m_hi_default; -} - -template -Type IntegerRangeCell::lo_current_value() const{ - return m_data->m_lo_current.load(std::memory_order_relaxed); -} -template -Type IntegerRangeCell::hi_current_value() const{ - return m_data->m_hi_current.load(std::memory_order_relaxed); -} -template -void IntegerRangeCell::current_values(Type& lo, Type& hi) const{ - ReadSpinLock lg(m_data->m_lock); - lo = lo_current_value(); - hi = hi_current_value(); -} - -template -void IntegerRangeCell::set_lo(Type lo){ - lo = std::max(lo, lo_min_value()); - lo = std::min(lo, lo_max_value()); - - Type current_lo; - { - WriteSpinLock lg(m_data->m_lock); - current_lo = lo_current_value(); - if (hi_current_value() < lo){ - m_data->m_hi_current.store(lo, std::memory_order_relaxed); - } - if (current_lo != lo){ - m_data->m_lo_current.store(lo, std::memory_order_relaxed); - } - } - // It is impossible for hi to change without also changing lo. So we only - // need to check for lo. If this condition fails, we were already in a bad - // state to begin with. - if (current_lo != lo){ - report_value_changed(this); - } -} -template -void IntegerRangeCell::set_hi(Type hi){ - hi = std::max(hi, hi_min_value()); - hi = std::min(hi, hi_max_value()); - - Type current_hi; - { - WriteSpinLock lg(m_data->m_lock); - current_hi = hi_current_value(); - if (lo_current_value() > hi){ - m_data->m_lo_current.store(hi, std::memory_order_relaxed); - } - if (current_hi != hi){ - m_data->m_hi_current.store(hi, std::memory_order_relaxed); - } - } - // It is impossible for lo to change without also changing hi. So we only - // need to check for hi. If this condition fails, we were already in a bad - // state to begin with. - if (current_hi != hi){ - report_value_changed(this); - } -} -template -void IntegerRangeCell::set(Type lo, Type hi){ - lo = std::max(lo, lo_min_value()); - lo = std::min(lo, lo_max_value()); - hi = std::max(hi, hi_min_value()); - hi = std::min(hi, hi_max_value()); - hi = std::max(hi, lo); - - Type current_lo, current_hi; - { - WriteSpinLock lg(m_data->m_lock); - current_lo = lo_current_value(); - current_hi = hi_current_value(); - if (current_lo != lo){ - m_data->m_lo_current.store(lo, std::memory_order_relaxed); - } - if (current_hi != hi){ - m_data->m_hi_current.store(hi, std::memory_order_relaxed); - } - } - if (current_lo != lo || current_hi != hi){ - report_value_changed(this); - } -} - -template -void IntegerRangeCell::set(const IntegerRangeCell& option){ - Type lo, hi; - option.current_values(lo, hi); - set(lo, hi); - current_values(lo, hi); -} - -template -void IntegerRangeCell::load_json(const JsonValue& json){ - const JsonArray* array = json.to_array(); - if (array == nullptr || array->size() != 2){ - return; - } - set( - (Type)(*array)[0].to_integer_default(m_data->m_lo_default), - (Type)(*array)[1].to_integer_default(m_data->m_hi_default) - ); -} -template -JsonValue IntegerRangeCell::to_json() const{ - Type lo, hi; - current_values(lo, hi); - JsonArray array; - array.push_back(lo); - array.push_back(hi); - return array; -} -template -void IntegerRangeCell::restore_defaults(){ - set(m_data->m_lo_default, m_data->m_hi_default); -} - - - - - - - -template class IntegerRangeCell; - - - -} - +/* Integer Range Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "IntegerRangeOption.h" + +#include "Common/Qt/Options/IntegerRangeWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +template +ConfigWidget* IntegerRangeCell::make_QtWidget(QWidget& parent){ + return new IntegerRangeCellWidget(parent, *this); +} + + + +template +struct IntegerRangeCell::Data{ + const Type m_lo_min_value; + const Type m_lo_max_value; + const Type m_hi_min_value; + const Type m_hi_max_value; + const Type m_lo_default; + const Type m_hi_default; + + mutable SpinLock m_lock; + std::atomic m_lo_current; + std::atomic m_hi_current; + + Data( + Type lo_min_value, Type lo_max_value, Type lo_default_value, Type lo_current_value, + Type hi_min_value, Type hi_max_value, Type hi_default_value, Type hi_current_value + ) + : m_lo_min_value(lo_min_value), m_lo_max_value(lo_max_value) + , m_hi_min_value(hi_min_value), m_hi_max_value(hi_max_value) + , m_lo_default(lo_default_value) + , m_hi_default(hi_default_value) + , m_lo_current(lo_current_value) + , m_hi_current(hi_current_value) + { + if (lo_min_value > lo_max_value || + hi_min_value > hi_max_value || + lo_min_value > hi_min_value || + lo_max_value > hi_max_value || + lo_max_value < hi_min_value + ){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Limits are incompatible."); + } + if (!(lo_min_value <= lo_default_value && lo_default_value <= lo_max_value)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Low default is out of range."); + } + if (!(hi_min_value <= hi_default_value && hi_default_value <= hi_max_value)){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "High default is out of range."); + } + if (lo_default_value > hi_default_value){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Default values are incompatible."); + } + if (lo_current_value > hi_current_value){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Current values are incompatible."); + } + } +}; + + + +template +IntegerRangeCell::~IntegerRangeCell() = default; +template +IntegerRangeCell::IntegerRangeCell(const IntegerRangeCell& x) + : ConfigOption(x) + , m_data( + CONSTRUCT_TOKEN, + x.lo_min_value(), x.lo_max_value(), x.lo_default_value(), x.lo_current_value(), + x.hi_min_value(), x.hi_max_value(), x.hi_default_value(), x.hi_current_value() + ) +{} +template +IntegerRangeCell::IntegerRangeCell( + LockMode lock_while_running, + Type lo_min_value, Type lo_max_value, Type lo_default_value, Type lo_current_value, + Type hi_min_value, Type hi_max_value, Type hi_default_value, Type hi_current_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + lo_min_value, lo_max_value, lo_default_value, lo_current_value, + hi_min_value, hi_max_value, hi_default_value, hi_current_value + ) +{} + +template +Type IntegerRangeCell::lo_min_value() const{ + return m_data->m_lo_min_value; +} +template +Type IntegerRangeCell::lo_max_value() const{ + return m_data->m_lo_max_value; +} +template +Type IntegerRangeCell::lo_default_value() const{ + return m_data->m_lo_default; +} +template +Type IntegerRangeCell::hi_min_value() const{ + return m_data->m_hi_min_value; + +} +template +Type IntegerRangeCell::hi_max_value() const{ + return m_data->m_hi_max_value; +} +template +Type IntegerRangeCell::hi_default_value() const{ + return m_data->m_hi_default; +} + +template +Type IntegerRangeCell::lo_current_value() const{ + return m_data->m_lo_current.load(std::memory_order_relaxed); +} +template +Type IntegerRangeCell::hi_current_value() const{ + return m_data->m_hi_current.load(std::memory_order_relaxed); +} +template +void IntegerRangeCell::current_values(Type& lo, Type& hi) const{ + ReadSpinLock lg(m_data->m_lock); + lo = lo_current_value(); + hi = hi_current_value(); +} + +template +void IntegerRangeCell::set_lo(Type lo){ + lo = std::max(lo, lo_min_value()); + lo = std::min(lo, lo_max_value()); + + Type current_lo; + { + WriteSpinLock lg(m_data->m_lock); + current_lo = lo_current_value(); + if (hi_current_value() < lo){ + m_data->m_hi_current.store(lo, std::memory_order_relaxed); + } + if (current_lo != lo){ + m_data->m_lo_current.store(lo, std::memory_order_relaxed); + } + } + // It is impossible for hi to change without also changing lo. So we only + // need to check for lo. If this condition fails, we were already in a bad + // state to begin with. + if (current_lo != lo){ + report_value_changed(this); + } +} +template +void IntegerRangeCell::set_hi(Type hi){ + hi = std::max(hi, hi_min_value()); + hi = std::min(hi, hi_max_value()); + + Type current_hi; + { + WriteSpinLock lg(m_data->m_lock); + current_hi = hi_current_value(); + if (lo_current_value() > hi){ + m_data->m_lo_current.store(hi, std::memory_order_relaxed); + } + if (current_hi != hi){ + m_data->m_hi_current.store(hi, std::memory_order_relaxed); + } + } + // It is impossible for lo to change without also changing hi. So we only + // need to check for hi. If this condition fails, we were already in a bad + // state to begin with. + if (current_hi != hi){ + report_value_changed(this); + } +} +template +void IntegerRangeCell::set(Type lo, Type hi){ + lo = std::max(lo, lo_min_value()); + lo = std::min(lo, lo_max_value()); + hi = std::max(hi, hi_min_value()); + hi = std::min(hi, hi_max_value()); + hi = std::max(hi, lo); + + Type current_lo, current_hi; + { + WriteSpinLock lg(m_data->m_lock); + current_lo = lo_current_value(); + current_hi = hi_current_value(); + if (current_lo != lo){ + m_data->m_lo_current.store(lo, std::memory_order_relaxed); + } + if (current_hi != hi){ + m_data->m_hi_current.store(hi, std::memory_order_relaxed); + } + } + if (current_lo != lo || current_hi != hi){ + report_value_changed(this); + } +} + +template +void IntegerRangeCell::set(const IntegerRangeCell& option){ + Type lo, hi; + option.current_values(lo, hi); + set(lo, hi); + current_values(lo, hi); +} + +template +void IntegerRangeCell::load_json(const JsonValue& json){ + const JsonArray* array = json.to_array(); + if (array == nullptr || array->size() != 2){ + return; + } + set( + (Type)(*array)[0].to_integer_default(m_data->m_lo_default), + (Type)(*array)[1].to_integer_default(m_data->m_hi_default) + ); +} +template +JsonValue IntegerRangeCell::to_json() const{ + Type lo, hi; + current_values(lo, hi); + JsonArray array; + array.push_back(lo); + array.push_back(hi); + return array; +} +template +void IntegerRangeCell::restore_defaults(){ + set(m_data->m_lo_default, m_data->m_hi_default); +} + + + + + + + +template class IntegerRangeCell; + + + +} + diff --git a/Common/Cpp/Options/IntegerRangeOption.h b/Common/Cpp/Options/IntegerRangeOption.h index ce6653df0d..c200f2a99a 100644 --- a/Common/Cpp/Options/IntegerRangeOption.h +++ b/Common/Cpp/Options/IntegerRangeOption.h @@ -1,65 +1,65 @@ -/* Integer Range Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#ifndef PokemonAutomation_Options_IntegerRangeOption_H -#define PokemonAutomation_Options_IntegerRangeOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -template -class IntegerRangeCell : public ConfigOption{ -public: - ~IntegerRangeCell(); - IntegerRangeCell(const IntegerRangeCell& x); - IntegerRangeCell( - LockMode lock_while_running, - Type lo_min_value, Type lo_max_value, Type lo_default_value, Type lo_current_value, - Type hi_min_value, Type hi_max_value, Type hi_default_value, Type hi_current_value - ); - - Type lo_min_value() const; - Type lo_max_value() const; - Type lo_default_value() const; - - Type hi_min_value() const; - Type hi_max_value() const; - Type hi_default_value() const; - - Type lo_current_value() const; - Type hi_current_value() const; - void current_values(Type& lo, Type& hi) const; - - virtual void set_lo(Type x); - virtual void set_hi(Type x); - virtual void set(Type lo, Type hi); - virtual void set(const IntegerRangeCell& option); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -// std::string check_validity(Type x) const; -// virtual std::string check_validity() const override; - virtual void restore_defaults() override; - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - struct Data; - Pimpl m_data; -}; - - - -} -#endif - +/* Integer Range Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#ifndef PokemonAutomation_Options_IntegerRangeOption_H +#define PokemonAutomation_Options_IntegerRangeOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +template +class IntegerRangeCell : public ConfigOption{ +public: + ~IntegerRangeCell(); + IntegerRangeCell(const IntegerRangeCell& x); + IntegerRangeCell( + LockMode lock_while_running, + Type lo_min_value, Type lo_max_value, Type lo_default_value, Type lo_current_value, + Type hi_min_value, Type hi_max_value, Type hi_default_value, Type hi_current_value + ); + + Type lo_min_value() const; + Type lo_max_value() const; + Type lo_default_value() const; + + Type hi_min_value() const; + Type hi_max_value() const; + Type hi_default_value() const; + + Type lo_current_value() const; + Type hi_current_value() const; + void current_values(Type& lo, Type& hi) const; + + virtual void set_lo(Type x); + virtual void set_hi(Type x); + virtual void set(Type lo, Type hi); + virtual void set(const IntegerRangeCell& option); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +// std::string check_validity(Type x) const; +// virtual std::string check_validity() const override; + virtual void restore_defaults() override; + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + struct Data; + Pimpl m_data; +}; + + + +} +#endif + diff --git a/Common/Cpp/Options/KeyBindingOption.cpp b/Common/Cpp/Options/KeyBindingOption.cpp index a24074e0ff..664774e087 100644 --- a/Common/Cpp/Options/KeyBindingOption.cpp +++ b/Common/Cpp/Options/KeyBindingOption.cpp @@ -1,82 +1,82 @@ -/* Key Binding Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "KeyBindingOption.h" - -namespace PokemonAutomation{ - - - -struct KeyBindingCell::Data{ - const uint32_t m_default; - - mutable SpinLock m_lock; - uint32_t m_current; - std::string m_current_text; - - Data(uint32_t default_value) - : m_default(default_value) - , m_current(default_value) - {} -}; - - - -KeyBindingCell::~KeyBindingCell(){ - -} -KeyBindingCell::KeyBindingCell(LockMode lock_while_program_is_running) - : ConfigOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, 0) -{} - - -KeyBindingCell::operator uint32_t() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -KeyBindingCell::operator std::string() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current_text; -} -void KeyBindingCell::set(uint32_t key){ - { - ReadSpinLock lg(m_data->m_lock); - m_data->m_current = key; - } - report_value_changed(this); -} -void KeyBindingCell::set(std::string text){ - ReadSpinLock lg(m_data->m_lock); - m_data->m_current_text = std::move(text); -} - - - -void KeyBindingCell::load_json(const JsonValue& json){ - set((uint32_t)json.to_integer_default(0)); -} -JsonValue KeyBindingCell::to_json() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} - -void KeyBindingCell::restore_defaults(){ - set(m_data->m_default); -} - - - - - - - - - -} +/* Key Binding Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "KeyBindingOption.h" + +namespace PokemonAutomation{ + + + +struct KeyBindingCell::Data{ + const uint32_t m_default; + + mutable SpinLock m_lock; + uint32_t m_current; + std::string m_current_text; + + Data(uint32_t default_value) + : m_default(default_value) + , m_current(default_value) + {} +}; + + + +KeyBindingCell::~KeyBindingCell(){ + +} +KeyBindingCell::KeyBindingCell(LockMode lock_while_program_is_running) + : ConfigOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, 0) +{} + + +KeyBindingCell::operator uint32_t() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +KeyBindingCell::operator std::string() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current_text; +} +void KeyBindingCell::set(uint32_t key){ + { + ReadSpinLock lg(m_data->m_lock); + m_data->m_current = key; + } + report_value_changed(this); +} +void KeyBindingCell::set(std::string text){ + ReadSpinLock lg(m_data->m_lock); + m_data->m_current_text = std::move(text); +} + + + +void KeyBindingCell::load_json(const JsonValue& json){ + set((uint32_t)json.to_integer_default(0)); +} +JsonValue KeyBindingCell::to_json() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} + +void KeyBindingCell::restore_defaults(){ + set(m_data->m_default); +} + + + + + + + + + +} diff --git a/Common/Cpp/Options/KeyBindingOption.h b/Common/Cpp/Options/KeyBindingOption.h index f5c5489e9b..305da9a915 100644 --- a/Common/Cpp/Options/KeyBindingOption.h +++ b/Common/Cpp/Options/KeyBindingOption.h @@ -1,48 +1,48 @@ -/* Key Binding Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_KeyBindingOption_H -#define PokemonAutomation_Options_KeyBindingOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - - -class KeyBindingCell : public ConfigOption{ -public: - ~KeyBindingCell(); - KeyBindingCell(LockMode lock_while_program_is_running); - - operator uint32_t() const; - operator std::string() const; - void set(uint32_t key); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -public: - // UI Functions - void set(std::string text); - - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Key Binding Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_KeyBindingOption_H +#define PokemonAutomation_Options_KeyBindingOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + + +class KeyBindingCell : public ConfigOption{ +public: + ~KeyBindingCell(); + KeyBindingCell(LockMode lock_while_program_is_running); + + operator uint32_t() const; + operator std::string() const; + void set(uint32_t key); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +public: + // UI Functions + void set(std::string text); + + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/MacAddressOption.cpp b/Common/Cpp/Options/MacAddressOption.cpp index 8ecdb98868..17c40e6e70 100644 --- a/Common/Cpp/Options/MacAddressOption.cpp +++ b/Common/Cpp/Options/MacAddressOption.cpp @@ -1,151 +1,151 @@ -/* MAC Address Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "MacAddressOption.h" - -#include "Common/Qt/Options/MacAddressWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* MacAddressCell::make_QtWidget(QWidget& parent){ - return new MacAddressCellWidget(parent, *this); -} - - - -std::string write_MAC_address(size_t length, const uint8_t* address){ - static const char HEX_DIGITS[] = "0123456789ABCDEF"; - std::string ret; - for (size_t c = 0; c < length; c++){ - if (!ret.empty()){ - ret += "-"; - } - ret += HEX_DIGITS[address[c] >> 4]; - ret += HEX_DIGITS[address[c] & 0xf]; - } - return ret; -} -void parse_MAC_address(size_t length, uint8_t* address, const std::string& str){ - memset(address, 0, length); - size_t current_index = 0; - for (char ch : str){ - if (current_index >= 2*length){ - return; - } - if ('0' <= ch && ch <= '9'){ - ch -= '0'; - }else if ('a' <= ch && ch <= 'f'){ - ch += 10 - 'a'; - }else if ('A' <= ch && ch <= 'F'){ - ch += 10 - 'A'; - }else{ - continue; - } - address[current_index / 2] |= ch << 4*(1 - current_index % 2); - current_index++; - } -} - - - -struct MacAddressCell::Data{ - mutable std::mutex m_lock; - std::vector m_current; - - Data(size_t bytes, const uint8_t* current) - : m_current(bytes) - { - if (current != nullptr){ - memcpy(m_current.data(), current, bytes); - } - } -}; - - - -MacAddressCell::~MacAddressCell() = default; -MacAddressCell::MacAddressCell(const MacAddressCell& x) - : ConfigOption(x) - , m_data(CONSTRUCT_TOKEN, x.m_data->m_current.size(), x.m_data->m_current.data()) -{} -void MacAddressCell::operator=(const MacAddressCell& x){ - if (bytes() != x.bytes()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Attempt to assign a MAC address is mismatching size." - ); - } - { - std::scoped_lock lg(m_data->m_lock, x.m_data->m_lock); - memcpy(m_data->m_current.data(), x.m_data->m_current.data(), bytes()); - } - report_value_changed(this); -} -MacAddressCell::MacAddressCell( - LockMode lock_while_running, - size_t bytes, - uint8_t* current_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, bytes, current_value) -{} - - -size_t MacAddressCell::bytes() const{ - return m_data->m_current.size(); -} -std::string MacAddressCell::to_string() const{ - std::lock_guard lg(m_data->m_lock); - return write_MAC_address(m_data->m_current.size(), m_data->m_current.data()); -} -void MacAddressCell::current_value(uint8_t* address) const{ - std::lock_guard lg(m_data->m_lock); - memcpy(address, m_data->m_current.data(), m_data->m_current.size()); -} -void MacAddressCell::set(const uint8_t* address){ - { - std::lock_guard lg(m_data->m_lock); - if (memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0){ - return; - } - memcpy(m_data->m_current.data(), address, m_data->m_current.size()); - } - report_value_changed(this); -} -void MacAddressCell::set(const std::string& address){ - std::vector new_value(m_data->m_current.size()); - parse_MAC_address(new_value.size(), new_value.data(), address); - set(new_value.data()); -} - - -bool MacAddressCell::operator==(const uint8_t* address) const{ - std::lock_guard lg(m_data->m_lock); - return memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0; -} - - -void MacAddressCell::load_json(const JsonValue& json){ - set(json.to_string_default()); -} -JsonValue MacAddressCell::to_json() const{ - return to_string(); -} - - - - - -} +/* MAC Address Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "MacAddressOption.h" + +#include "Common/Qt/Options/MacAddressWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* MacAddressCell::make_QtWidget(QWidget& parent){ + return new MacAddressCellWidget(parent, *this); +} + + + +std::string write_MAC_address(size_t length, const uint8_t* address){ + static const char HEX_DIGITS[] = "0123456789ABCDEF"; + std::string ret; + for (size_t c = 0; c < length; c++){ + if (!ret.empty()){ + ret += "-"; + } + ret += HEX_DIGITS[address[c] >> 4]; + ret += HEX_DIGITS[address[c] & 0xf]; + } + return ret; +} +void parse_MAC_address(size_t length, uint8_t* address, const std::string& str){ + memset(address, 0, length); + size_t current_index = 0; + for (char ch : str){ + if (current_index >= 2*length){ + return; + } + if ('0' <= ch && ch <= '9'){ + ch -= '0'; + }else if ('a' <= ch && ch <= 'f'){ + ch += 10 - 'a'; + }else if ('A' <= ch && ch <= 'F'){ + ch += 10 - 'A'; + }else{ + continue; + } + address[current_index / 2] |= ch << 4*(1 - current_index % 2); + current_index++; + } +} + + + +struct MacAddressCell::Data{ + mutable std::mutex m_lock; + std::vector m_current; + + Data(size_t bytes, const uint8_t* current) + : m_current(bytes) + { + if (current != nullptr){ + memcpy(m_current.data(), current, bytes); + } + } +}; + + + +MacAddressCell::~MacAddressCell() = default; +MacAddressCell::MacAddressCell(const MacAddressCell& x) + : ConfigOption(x) + , m_data(CONSTRUCT_TOKEN, x.m_data->m_current.size(), x.m_data->m_current.data()) +{} +void MacAddressCell::operator=(const MacAddressCell& x){ + if (bytes() != x.bytes()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Attempt to assign a MAC address is mismatching size." + ); + } + { + std::scoped_lock lg(m_data->m_lock, x.m_data->m_lock); + memcpy(m_data->m_current.data(), x.m_data->m_current.data(), bytes()); + } + report_value_changed(this); +} +MacAddressCell::MacAddressCell( + LockMode lock_while_running, + size_t bytes, + uint8_t* current_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, bytes, current_value) +{} + + +size_t MacAddressCell::bytes() const{ + return m_data->m_current.size(); +} +std::string MacAddressCell::to_string() const{ + std::lock_guard lg(m_data->m_lock); + return write_MAC_address(m_data->m_current.size(), m_data->m_current.data()); +} +void MacAddressCell::current_value(uint8_t* address) const{ + std::lock_guard lg(m_data->m_lock); + memcpy(address, m_data->m_current.data(), m_data->m_current.size()); +} +void MacAddressCell::set(const uint8_t* address){ + { + std::lock_guard lg(m_data->m_lock); + if (memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0){ + return; + } + memcpy(m_data->m_current.data(), address, m_data->m_current.size()); + } + report_value_changed(this); +} +void MacAddressCell::set(const std::string& address){ + std::vector new_value(m_data->m_current.size()); + parse_MAC_address(new_value.size(), new_value.data(), address); + set(new_value.data()); +} + + +bool MacAddressCell::operator==(const uint8_t* address) const{ + std::lock_guard lg(m_data->m_lock); + return memcmp(m_data->m_current.data(), address, m_data->m_current.size()) == 0; +} + + +void MacAddressCell::load_json(const JsonValue& json){ + set(json.to_string_default()); +} +JsonValue MacAddressCell::to_json() const{ + return to_string(); +} + + + + + +} diff --git a/Common/Cpp/Options/MacAddressOption.h b/Common/Cpp/Options/MacAddressOption.h index f24e545a1e..0fcb901d56 100644 --- a/Common/Cpp/Options/MacAddressOption.h +++ b/Common/Cpp/Options/MacAddressOption.h @@ -1,63 +1,63 @@ -/* MAC Address Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#ifndef PokemonAutomation_Options_MacAddressOption_H -#define PokemonAutomation_Options_MacAddressOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -std::string write_MAC_address(size_t length, const uint8_t* address); -void parse_MAC_address(size_t length, uint8_t* address, const std::string& str); - - -class MacAddressCell : public ConfigOption{ -public: - ~MacAddressCell(); - MacAddressCell(const MacAddressCell& x); - void operator=(const MacAddressCell& x); - MacAddressCell( - LockMode lock_while_running, - size_t bytes, - uint8_t* current_value - ); - -public: - size_t bytes() const; - std::string to_string() const; - - // Buffer must be long enough. - - void current_value(uint8_t* address) const; - void set(const uint8_t* address); - void set(const std::string& address); - - bool operator==(const uint8_t* address) const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - struct Data; - Pimpl m_data; -}; - - - - - - -} -#endif - +/* MAC Address Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#ifndef PokemonAutomation_Options_MacAddressOption_H +#define PokemonAutomation_Options_MacAddressOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +std::string write_MAC_address(size_t length, const uint8_t* address); +void parse_MAC_address(size_t length, uint8_t* address, const std::string& str); + + +class MacAddressCell : public ConfigOption{ +public: + ~MacAddressCell(); + MacAddressCell(const MacAddressCell& x); + void operator=(const MacAddressCell& x); + MacAddressCell( + LockMode lock_while_running, + size_t bytes, + uint8_t* current_value + ); + +public: + size_t bytes() const; + std::string to_string() const; + + // Buffer must be long enough. + + void current_value(uint8_t* address) const; + void set(const uint8_t* address); + void set(const std::string& address); + + bool operator==(const uint8_t* address) const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + struct Data; + Pimpl m_data; +}; + + + + + + +} +#endif + diff --git a/Common/Cpp/Options/RandomCodeOption.cpp b/Common/Cpp/Options/RandomCodeOption.cpp index f2b65ec1d4..e7ded8341b 100644 --- a/Common/Cpp/Options/RandomCodeOption.cpp +++ b/Common/Cpp/Options/RandomCodeOption.cpp @@ -1,209 +1,209 @@ -/* Random Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/CodeValidator.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "RandomCodeOption.h" - -namespace PokemonAutomation{ - - - -RaidCodeOption::~RaidCodeOption() = default; -RaidCodeOption::RaidCodeOption(size_t total_digits) - : m_digits(total_digits) - , m_random_digits(0) - , m_code(std::string(total_digits, '1')) -{} -RaidCodeOption::RaidCodeOption(size_t total_digits, size_t random_digits, std::string code_string) - : m_digits(total_digits) - , m_random_digits(random_digits) - , m_code(std::move(code_string)) -{} -std::string RaidCodeOption::check_validity() const{ - if (m_random_digits == 0){ - return validate_code(m_digits, m_code) - ? std::string() - : "Code is invalid."; - }else{ - return m_random_digits <= m_digits - ? std::string() - : "Random digits cannot be greater than " + std::to_string(m_digits) + "."; - } -} -bool RaidCodeOption::code_enabled() const{ - return m_random_digits != 0 || m_code.size() > 0; -} -std::string RaidCodeOption::get_code() const{ - if (!code_enabled()){ - return ""; - } - std::string code; - code.resize(8); - if (m_random_digits == 0){ - std::string qstr = sanitize_code(8, m_code); - for (int c = 0; c < 8; c++){ - code[c] = qstr[c]; - } - return code; - } - srand((unsigned)time(nullptr)); - for (uint8_t c = 0; c < m_random_digits; c++){ - uint8_t x; - do{ - x = rand() & 0x0f; - }while (x >= 10); - code[c] = x + '0'; - } - for (size_t c = m_random_digits; c < m_digits; c++){ - code[c] = code[c - 1]; - } - return code; -} -bool RaidCodeOption::operator==(const RaidCodeOption& x) const{ - return - m_digits == x.m_digits && - m_random_digits == x.m_random_digits && - m_code == x.m_code; -} - - -struct RandomCodeOption::Data{ - const std::string m_label; - const RaidCodeOption m_default; - - mutable SpinLock m_lock; - RaidCodeOption m_current; - - Data(size_t total_digits) - : m_label( - "Raid Code:
Blank for no raid code. Set random digits to zero for a fixed code. Otherwise, it is the # of leading random digits." - ) - , m_default(total_digits) - , m_current(m_default) - {} - Data(std::string label, size_t total_digits, size_t random_digits, std::string code_string) - : m_label(std::move(label)) - , m_default(total_digits, random_digits, std::move(code_string)) - , m_current(m_default) - {} -}; - - - -RandomCodeOption::~RandomCodeOption() = default; -RandomCodeOption::RandomCodeOption(size_t total_digits) - : m_data(CONSTRUCT_TOKEN, total_digits) -{} -RandomCodeOption::RandomCodeOption(std::string label, size_t total_digits, size_t random_digits, std::string code_string) - : m_data(CONSTRUCT_TOKEN, std::move(label), total_digits, random_digits, std::move(code_string)) -{} -#if 0 -std::unique_ptr RandomCodeOption::clone() const{ - std::unique_ptr ret(new RandomCodeOption( - m_label, - m_default.total_digits(), - m_default.random_digits(), - m_default.code_string() - )); - ret->m_current = m_current; - return ret; -} -#endif - -const std::string& RandomCodeOption::label() const{ - return m_data->m_label; -} - -void RandomCodeOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - RaidCodeOption code(m_data->m_default.total_digits()); - - obj->read_integer(code.m_random_digits, "RandomDigits"); - - std::string str; - if (obj->read_string(str, "RaidCode")){ - code.m_code = str; - } - - { - WriteSpinLock lg(m_data->m_lock); - m_data->m_current = code; - } - report_value_changed(this); -} -JsonValue RandomCodeOption::to_json() const{ - ReadSpinLock lg(m_data->m_lock); - JsonObject obj; - obj["RandomDigits"] = m_data->m_current.m_random_digits; - obj["RaidCode"] = m_data->m_current.m_code; - return obj; -} - - - -RandomCodeOption::operator RaidCodeOption() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -std::string RandomCodeOption::set(RaidCodeOption code){ - std::string error = code.check_validity(); - if (!error.empty()){ - return error; - } - { - WriteSpinLock lg(m_data->m_lock); - if (m_data->m_current == code){ - return std::string(); - } - m_data->m_current = code; - } - report_value_changed(this); - return std::string(); -} -bool RandomCodeOption::code_enabled() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current.code_enabled(); -} -std::string RandomCodeOption::get_code() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current.get_code(); -} - -std::string RandomCodeOption::check_validity() const{ - return m_data->m_current.check_validity(); -} -void RandomCodeOption::restore_defaults(){ - { - WriteSpinLock lg(m_data->m_lock); - m_data->m_current = m_data->m_default; - } - report_value_changed(this); -} - - - - - -} - - - - - - - - - +/* Random Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/CodeValidator.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "RandomCodeOption.h" + +namespace PokemonAutomation{ + + + +RaidCodeOption::~RaidCodeOption() = default; +RaidCodeOption::RaidCodeOption(size_t total_digits) + : m_digits(total_digits) + , m_random_digits(0) + , m_code(std::string(total_digits, '1')) +{} +RaidCodeOption::RaidCodeOption(size_t total_digits, size_t random_digits, std::string code_string) + : m_digits(total_digits) + , m_random_digits(random_digits) + , m_code(std::move(code_string)) +{} +std::string RaidCodeOption::check_validity() const{ + if (m_random_digits == 0){ + return validate_code(m_digits, m_code) + ? std::string() + : "Code is invalid."; + }else{ + return m_random_digits <= m_digits + ? std::string() + : "Random digits cannot be greater than " + std::to_string(m_digits) + "."; + } +} +bool RaidCodeOption::code_enabled() const{ + return m_random_digits != 0 || m_code.size() > 0; +} +std::string RaidCodeOption::get_code() const{ + if (!code_enabled()){ + return ""; + } + std::string code; + code.resize(8); + if (m_random_digits == 0){ + std::string qstr = sanitize_code(8, m_code); + for (int c = 0; c < 8; c++){ + code[c] = qstr[c]; + } + return code; + } + srand((unsigned)time(nullptr)); + for (uint8_t c = 0; c < m_random_digits; c++){ + uint8_t x; + do{ + x = rand() & 0x0f; + }while (x >= 10); + code[c] = x + '0'; + } + for (size_t c = m_random_digits; c < m_digits; c++){ + code[c] = code[c - 1]; + } + return code; +} +bool RaidCodeOption::operator==(const RaidCodeOption& x) const{ + return + m_digits == x.m_digits && + m_random_digits == x.m_random_digits && + m_code == x.m_code; +} + + +struct RandomCodeOption::Data{ + const std::string m_label; + const RaidCodeOption m_default; + + mutable SpinLock m_lock; + RaidCodeOption m_current; + + Data(size_t total_digits) + : m_label( + "Raid Code:
Blank for no raid code. Set random digits to zero for a fixed code. Otherwise, it is the # of leading random digits." + ) + , m_default(total_digits) + , m_current(m_default) + {} + Data(std::string label, size_t total_digits, size_t random_digits, std::string code_string) + : m_label(std::move(label)) + , m_default(total_digits, random_digits, std::move(code_string)) + , m_current(m_default) + {} +}; + + + +RandomCodeOption::~RandomCodeOption() = default; +RandomCodeOption::RandomCodeOption(size_t total_digits) + : m_data(CONSTRUCT_TOKEN, total_digits) +{} +RandomCodeOption::RandomCodeOption(std::string label, size_t total_digits, size_t random_digits, std::string code_string) + : m_data(CONSTRUCT_TOKEN, std::move(label), total_digits, random_digits, std::move(code_string)) +{} +#if 0 +std::unique_ptr RandomCodeOption::clone() const{ + std::unique_ptr ret(new RandomCodeOption( + m_label, + m_default.total_digits(), + m_default.random_digits(), + m_default.code_string() + )); + ret->m_current = m_current; + return ret; +} +#endif + +const std::string& RandomCodeOption::label() const{ + return m_data->m_label; +} + +void RandomCodeOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + RaidCodeOption code(m_data->m_default.total_digits()); + + obj->read_integer(code.m_random_digits, "RandomDigits"); + + std::string str; + if (obj->read_string(str, "RaidCode")){ + code.m_code = str; + } + + { + WriteSpinLock lg(m_data->m_lock); + m_data->m_current = code; + } + report_value_changed(this); +} +JsonValue RandomCodeOption::to_json() const{ + ReadSpinLock lg(m_data->m_lock); + JsonObject obj; + obj["RandomDigits"] = m_data->m_current.m_random_digits; + obj["RaidCode"] = m_data->m_current.m_code; + return obj; +} + + + +RandomCodeOption::operator RaidCodeOption() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +std::string RandomCodeOption::set(RaidCodeOption code){ + std::string error = code.check_validity(); + if (!error.empty()){ + return error; + } + { + WriteSpinLock lg(m_data->m_lock); + if (m_data->m_current == code){ + return std::string(); + } + m_data->m_current = code; + } + report_value_changed(this); + return std::string(); +} +bool RandomCodeOption::code_enabled() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current.code_enabled(); +} +std::string RandomCodeOption::get_code() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current.get_code(); +} + +std::string RandomCodeOption::check_validity() const{ + return m_data->m_current.check_validity(); +} +void RandomCodeOption::restore_defaults(){ + { + WriteSpinLock lg(m_data->m_lock); + m_data->m_current = m_data->m_default; + } + report_value_changed(this); +} + + + + + +} + + + + + + + + + diff --git a/Common/Cpp/Options/RandomCodeOption.h b/Common/Cpp/Options/RandomCodeOption.h index 65723f79a6..b00a977cd1 100644 --- a/Common/Cpp/Options/RandomCodeOption.h +++ b/Common/Cpp/Options/RandomCodeOption.h @@ -1,74 +1,74 @@ -/* Random Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_RandomCodeOption_H -#define PokemonAutomation_Options_RandomCodeOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -class RaidCodeOption{ -public: - ~RaidCodeOption(); - RaidCodeOption(size_t total_digits); - RaidCodeOption(size_t total_digits, size_t random_digits, std::string code_string); - - size_t total_digits() const{ return m_digits; } - size_t random_digits() const{ return m_random_digits; } - const std::string& code_string() const{ return m_code; } - - std::string check_validity() const; - bool code_enabled() const; - std::string get_code() const; - - bool operator==(const RaidCodeOption& x) const; - -//private: - size_t m_digits; - size_t m_random_digits; - std::string m_code; -}; - - - -class RandomCodeOption : public ConfigOption{ -public: - ~RandomCodeOption(); - RandomCodeOption(size_t total_digits); - RandomCodeOption(std::string label, size_t total_digits, size_t random_digits, std::string code_string); -// virtual std::unique_ptr clone() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - const std::string& label() const; - - operator RaidCodeOption() const; - std::string set(RaidCodeOption code); - - bool code_enabled() const; - std::string get_code() const; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - - - - -} -#endif +/* Random Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_RandomCodeOption_H +#define PokemonAutomation_Options_RandomCodeOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +class RaidCodeOption{ +public: + ~RaidCodeOption(); + RaidCodeOption(size_t total_digits); + RaidCodeOption(size_t total_digits, size_t random_digits, std::string code_string); + + size_t total_digits() const{ return m_digits; } + size_t random_digits() const{ return m_random_digits; } + const std::string& code_string() const{ return m_code; } + + std::string check_validity() const; + bool code_enabled() const; + std::string get_code() const; + + bool operator==(const RaidCodeOption& x) const; + +//private: + size_t m_digits; + size_t m_random_digits; + std::string m_code; +}; + + + +class RandomCodeOption : public ConfigOption{ +public: + ~RandomCodeOption(); + RandomCodeOption(size_t total_digits); + RandomCodeOption(std::string label, size_t total_digits, size_t random_digits, std::string code_string); +// virtual std::unique_ptr clone() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + const std::string& label() const; + + operator RaidCodeOption() const; + std::string set(RaidCodeOption code); + + bool code_enabled() const; + std::string get_code() const; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + + + + +} +#endif diff --git a/Common/Cpp/Options/SimpleIntegerOption.cpp b/Common/Cpp/Options/SimpleIntegerOption.cpp index 3f899e7d0b..90e0bffbe2 100644 --- a/Common/Cpp/Options/SimpleIntegerOption.cpp +++ b/Common/Cpp/Options/SimpleIntegerOption.cpp @@ -1,224 +1,224 @@ -/* Simple Integer Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "SimpleIntegerOption.h" - -#include "Common/Qt/Options/SimpleIntegerWidget.h" - -namespace PokemonAutomation{ - - - - -template -ConfigWidget* SimpleIntegerCell::make_QtWidget(QWidget& parent){ - return new SimpleIntegerCellWidget(parent, *this); -} -template -ConfigWidget* SimpleIntegerOption::make_QtWidget(QWidget& parent){ - return new SimpleIntegerOptionWidget(parent, *this); -} - - - -template -struct SimpleIntegerCell::Data{ - const Type m_min_value; - const Type m_max_value; - const Type m_default; - std::atomic m_current; - - Data(Type min_value, Type max_value, Type default_value, Type value) - : m_min_value(min_value) - , m_max_value(max_value) - , m_default(default_value) - , m_current(value) - {} -}; - - - - -template -SimpleIntegerCell::~SimpleIntegerCell() = default; -template -SimpleIntegerCell::SimpleIntegerCell(const SimpleIntegerCell& x) - : ConfigOption(x) - , m_data(CONSTRUCT_TOKEN, x.min_value(), x.max_value(), x.default_value(), x.current_value()) -{} -template -SimpleIntegerCell::SimpleIntegerCell( - LockMode lock_while_running, - Type min_value, Type max_value, - Type default_value, Type current_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, current_value) -{} - -template -SimpleIntegerCell::SimpleIntegerCell( - LockMode lock_while_running, - Type default_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, std::numeric_limits::min(), std::numeric_limits::max(), default_value, default_value) -{} -template -SimpleIntegerCell::SimpleIntegerCell( - LockMode lock_while_running, - Type default_value, Type min_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, min_value, std::numeric_limits::max(), default_value, default_value) -{} -template -SimpleIntegerCell::SimpleIntegerCell( - LockMode lock_while_running, - Type default_value, Type min_value, Type max_value -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, default_value) -{} - -template -Type SimpleIntegerCell::min_value() const{ - return m_data->m_min_value; -} -template -Type SimpleIntegerCell::max_value() const{ - return m_data->m_max_value; -} -template -Type SimpleIntegerCell::default_value() const{ - return m_data->m_default; -} -template -Type SimpleIntegerCell::current_value() const{ - return m_data->m_current.load(std::memory_order_relaxed); -} -template -SimpleIntegerCell::operator Type() const{ - return m_data->m_current.load(std::memory_order_relaxed); -} -template -std::string SimpleIntegerCell::set(Type x){ - std::string err = check_validity(x); - if (!err.empty()){ - return err; - } - if ((Type)*this == x){ - return std::string(); - } - if (x != m_data->m_current.exchange(x, std::memory_order_relaxed)){ - report_value_changed(this); - } - return std::string(); -} -template -void SimpleIntegerCell::load_json(const JsonValue& json){ - Type value; - if (json.read_integer(value, m_data->m_min_value, m_data->m_max_value)){ - set(value); - } -} -template -JsonValue SimpleIntegerCell::to_json() const{ - return (Type)*this; -} - -template -std::string SimpleIntegerCell::check_validity(Type x) const{ - if (x < m_data->m_min_value){ - return "Value too small: min = " + std::to_string(m_data->m_min_value) + ", value = " + std::to_string(x); - } - if (x > m_data->m_max_value){ - return "Value too large: max = " + std::to_string(m_data->m_max_value) + ", value = " + std::to_string(x); - } - return std::string(); -} -template -std::string SimpleIntegerCell::check_validity() const{ - return check_validity(*this); -} -template -void SimpleIntegerCell::restore_defaults(){ - set(m_data->m_default); -} - - - - - -template -SimpleIntegerOption::SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type min_value, Type max_value, - Type default_value, Type current_value -) - : SimpleIntegerCell(lock_while_running, min_value, max_value, default_value, current_value) - , m_label(std::move(label)) -{} -template -SimpleIntegerOption::SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type default_value -) - : SimpleIntegerCell(lock_while_running, default_value) - , m_label(std::move(label)) -{} -template -SimpleIntegerOption::SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type default_value, Type min_value -) - : SimpleIntegerCell(lock_while_running, default_value, min_value) - , m_label(std::move(label)) -{} -template -SimpleIntegerOption::SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type default_value, Type min_value, Type max_value -) - : SimpleIntegerCell(lock_while_running, default_value, min_value, max_value) - , m_label(std::move(label)) -{} - - - - - - - -template class SimpleIntegerCell; -template class SimpleIntegerCell; -template class SimpleIntegerCell; -template class SimpleIntegerCell; -template class SimpleIntegerCell; -template class SimpleIntegerCell; -template class SimpleIntegerCell; -template class SimpleIntegerCell; - -template class SimpleIntegerOption; -template class SimpleIntegerOption; -template class SimpleIntegerOption; -template class SimpleIntegerOption; -template class SimpleIntegerOption; -template class SimpleIntegerOption; -template class SimpleIntegerOption; -template class SimpleIntegerOption; - - - -} +/* Simple Integer Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "SimpleIntegerOption.h" + +#include "Common/Qt/Options/SimpleIntegerWidget.h" + +namespace PokemonAutomation{ + + + + +template +ConfigWidget* SimpleIntegerCell::make_QtWidget(QWidget& parent){ + return new SimpleIntegerCellWidget(parent, *this); +} +template +ConfigWidget* SimpleIntegerOption::make_QtWidget(QWidget& parent){ + return new SimpleIntegerOptionWidget(parent, *this); +} + + + +template +struct SimpleIntegerCell::Data{ + const Type m_min_value; + const Type m_max_value; + const Type m_default; + std::atomic m_current; + + Data(Type min_value, Type max_value, Type default_value, Type value) + : m_min_value(min_value) + , m_max_value(max_value) + , m_default(default_value) + , m_current(value) + {} +}; + + + + +template +SimpleIntegerCell::~SimpleIntegerCell() = default; +template +SimpleIntegerCell::SimpleIntegerCell(const SimpleIntegerCell& x) + : ConfigOption(x) + , m_data(CONSTRUCT_TOKEN, x.min_value(), x.max_value(), x.default_value(), x.current_value()) +{} +template +SimpleIntegerCell::SimpleIntegerCell( + LockMode lock_while_running, + Type min_value, Type max_value, + Type default_value, Type current_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, current_value) +{} + +template +SimpleIntegerCell::SimpleIntegerCell( + LockMode lock_while_running, + Type default_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, std::numeric_limits::min(), std::numeric_limits::max(), default_value, default_value) +{} +template +SimpleIntegerCell::SimpleIntegerCell( + LockMode lock_while_running, + Type default_value, Type min_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, min_value, std::numeric_limits::max(), default_value, default_value) +{} +template +SimpleIntegerCell::SimpleIntegerCell( + LockMode lock_while_running, + Type default_value, Type min_value, Type max_value +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, min_value, max_value, default_value, default_value) +{} + +template +Type SimpleIntegerCell::min_value() const{ + return m_data->m_min_value; +} +template +Type SimpleIntegerCell::max_value() const{ + return m_data->m_max_value; +} +template +Type SimpleIntegerCell::default_value() const{ + return m_data->m_default; +} +template +Type SimpleIntegerCell::current_value() const{ + return m_data->m_current.load(std::memory_order_relaxed); +} +template +SimpleIntegerCell::operator Type() const{ + return m_data->m_current.load(std::memory_order_relaxed); +} +template +std::string SimpleIntegerCell::set(Type x){ + std::string err = check_validity(x); + if (!err.empty()){ + return err; + } + if ((Type)*this == x){ + return std::string(); + } + if (x != m_data->m_current.exchange(x, std::memory_order_relaxed)){ + report_value_changed(this); + } + return std::string(); +} +template +void SimpleIntegerCell::load_json(const JsonValue& json){ + Type value; + if (json.read_integer(value, m_data->m_min_value, m_data->m_max_value)){ + set(value); + } +} +template +JsonValue SimpleIntegerCell::to_json() const{ + return (Type)*this; +} + +template +std::string SimpleIntegerCell::check_validity(Type x) const{ + if (x < m_data->m_min_value){ + return "Value too small: min = " + std::to_string(m_data->m_min_value) + ", value = " + std::to_string(x); + } + if (x > m_data->m_max_value){ + return "Value too large: max = " + std::to_string(m_data->m_max_value) + ", value = " + std::to_string(x); + } + return std::string(); +} +template +std::string SimpleIntegerCell::check_validity() const{ + return check_validity(*this); +} +template +void SimpleIntegerCell::restore_defaults(){ + set(m_data->m_default); +} + + + + + +template +SimpleIntegerOption::SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type min_value, Type max_value, + Type default_value, Type current_value +) + : SimpleIntegerCell(lock_while_running, min_value, max_value, default_value, current_value) + , m_label(std::move(label)) +{} +template +SimpleIntegerOption::SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type default_value +) + : SimpleIntegerCell(lock_while_running, default_value) + , m_label(std::move(label)) +{} +template +SimpleIntegerOption::SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type default_value, Type min_value +) + : SimpleIntegerCell(lock_while_running, default_value, min_value) + , m_label(std::move(label)) +{} +template +SimpleIntegerOption::SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type default_value, Type min_value, Type max_value +) + : SimpleIntegerCell(lock_while_running, default_value, min_value, max_value) + , m_label(std::move(label)) +{} + + + + + + + +template class SimpleIntegerCell; +template class SimpleIntegerCell; +template class SimpleIntegerCell; +template class SimpleIntegerCell; +template class SimpleIntegerCell; +template class SimpleIntegerCell; +template class SimpleIntegerCell; +template class SimpleIntegerCell; + +template class SimpleIntegerOption; +template class SimpleIntegerOption; +template class SimpleIntegerOption; +template class SimpleIntegerOption; +template class SimpleIntegerOption; +template class SimpleIntegerOption; +template class SimpleIntegerOption; +template class SimpleIntegerOption; + + + +} diff --git a/Common/Cpp/Options/SimpleIntegerOption.h b/Common/Cpp/Options/SimpleIntegerOption.h index 484e18cad1..1daa1d0b88 100644 --- a/Common/Cpp/Options/SimpleIntegerOption.h +++ b/Common/Cpp/Options/SimpleIntegerOption.h @@ -1,113 +1,113 @@ -/* Simple Integer Option - * - * From: https://github.com/PokemonAutomation/ - * - * This option is thread-safe. - * - */ - -#ifndef PokemonAutomation_Options_SimpleIntegerOption_H -#define PokemonAutomation_Options_SimpleIntegerOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - - -template -class SimpleIntegerCell : public ConfigOption{ -public: - ~SimpleIntegerCell(); - SimpleIntegerCell(const SimpleIntegerCell& x); - SimpleIntegerCell( - LockMode lock_while_running, - Type min_value, Type max_value, - Type default_value, Type current_value - ); - -public: - SimpleIntegerCell( - LockMode lock_while_running, - Type default_value - ); - SimpleIntegerCell( - LockMode lock_while_running, - Type default_value, Type min_value - ); - SimpleIntegerCell( - LockMode lock_while_running, - Type default_value, Type min_value, Type max_value - ); - - Type min_value() const; - Type max_value() const; - Type default_value() const; - Type current_value() const; - - operator Type() const; - std::string set(Type x); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - std::string check_validity(Type x) const; - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - struct Data; - Pimpl m_data; -}; - - - - - -template -class SimpleIntegerOption : public SimpleIntegerCell{ -public: - SimpleIntegerOption(const SimpleIntegerOption& x) = delete; - SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type min_value, Type max_value, - Type default_value, Type current_value - ); - -public: - SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type default_value - ); - SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type default_value, Type min_value - ); - SimpleIntegerOption( - std::string label, - LockMode lock_while_running, - Type default_value, Type min_value, Type max_value - ); - - const std::string& label() const{ return m_label; } - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - - -} -#endif - +/* Simple Integer Option + * + * From: https://github.com/PokemonAutomation/ + * + * This option is thread-safe. + * + */ + +#ifndef PokemonAutomation_Options_SimpleIntegerOption_H +#define PokemonAutomation_Options_SimpleIntegerOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + + +template +class SimpleIntegerCell : public ConfigOption{ +public: + ~SimpleIntegerCell(); + SimpleIntegerCell(const SimpleIntegerCell& x); + SimpleIntegerCell( + LockMode lock_while_running, + Type min_value, Type max_value, + Type default_value, Type current_value + ); + +public: + SimpleIntegerCell( + LockMode lock_while_running, + Type default_value + ); + SimpleIntegerCell( + LockMode lock_while_running, + Type default_value, Type min_value + ); + SimpleIntegerCell( + LockMode lock_while_running, + Type default_value, Type min_value, Type max_value + ); + + Type min_value() const; + Type max_value() const; + Type default_value() const; + Type current_value() const; + + operator Type() const; + std::string set(Type x); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + std::string check_validity(Type x) const; + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + struct Data; + Pimpl m_data; +}; + + + + + +template +class SimpleIntegerOption : public SimpleIntegerCell{ +public: + SimpleIntegerOption(const SimpleIntegerOption& x) = delete; + SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type min_value, Type max_value, + Type default_value, Type current_value + ); + +public: + SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type default_value + ); + SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type default_value, Type min_value + ); + SimpleIntegerOption( + std::string label, + LockMode lock_while_running, + Type default_value, Type min_value, Type max_value + ); + + const std::string& label() const{ return m_label; } + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + + +} +#endif + diff --git a/Common/Cpp/Options/StaticTableOption.cpp b/Common/Cpp/Options/StaticTableOption.cpp index 7bbf91e413..54f0c35763 100644 --- a/Common/Cpp/Options/StaticTableOption.cpp +++ b/Common/Cpp/Options/StaticTableOption.cpp @@ -1,279 +1,279 @@ -/* Static Table Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "StaticTableOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -StaticTableRow::StaticTableRow(std::string slug) - : m_slug(std::move(slug)) -{} -void StaticTableRow::add_option(ConfigOption& option, std::string serialization_string){ - m_options.emplace_back(std::move(serialization_string), &option); -} -void StaticTableRow::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - for (auto& item : m_options){ - if (!item.first.empty()){ - const JsonValue* value = obj->get_value(item.first); - if (value){ - item.second->load_json(*value); - } - } - } -} -JsonValue StaticTableRow::to_json() const{ - JsonObject obj; - for (auto& item : m_options){ - if (!item.first.empty()){ - obj[item.first] = item.second->to_json(); - } - } - return obj; -} -std::string StaticTableRow::check_validity() const{ - for (const auto& item : m_options){ - std::string error = item.second->check_validity(); - if (!error.empty()){ - return error; - } - } - return std::string(); -} -void StaticTableRow::restore_defaults(){ - for (const auto& item : m_options){ - item.second->restore_defaults(); - } -} -void StaticTableRow::report_program_state(bool program_is_running){ - for (const auto& item : m_options){ - item.second->report_program_state(program_is_running); - } -} -std::vector StaticTableRow::make_cells(){ - std::vector ret; - ret.reserve(m_options.size()); - for (const auto& item : m_options){ - ret.emplace_back(item.second); - } - return ret; -} - - - - -struct StaticTableOption::Data{ - const std::string m_label; - const bool m_enable_saveload; - std::vector> m_owners; - std::vector m_table; - - bool m_finished = false; - std::map m_index_map; - - - Data(std::string label, bool enable_saveload) - : m_label(std::move(label)) - , m_enable_saveload(enable_saveload) - {} - - void add_row(std::unique_ptr row){ - if (m_finished){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add row to finalized table."); - } - - const std::string& slug = row->slug(); - - bool owners_pushed = false; - bool table_pushed = false; - try{ - m_owners.emplace_back(std::move(row)); - owners_pushed = true; - m_table.emplace_back(m_owners.back().get()); - table_pushed = true; - - auto ret = m_index_map.emplace(slug, m_index_map.size()); - if (!ret.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + slug); - } - }catch (...){ - if (owners_pushed){ - m_owners.pop_back(); - } - if (table_pushed){ - m_table.pop_back(); - } - throw; - } - } - void add_row(StaticTableRow* row){ - if (m_finished){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add row to finalized table."); - } - - const std::string& slug = row->slug(); - - bool table_pushed = false; - try{ - m_table.emplace_back(row); - table_pushed = true; - - auto ret = m_index_map.emplace(slug, m_index_map.size()); - if (!ret.second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + slug); - } - }catch (...){ - if (table_pushed){ - m_table.pop_back(); - } - throw; - } - } - - // You must call this when done populating rows. Afterwards, you cannot add more. - void finish_construction(){ - if (m_finished){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to finalize and already finalized table."); - } - m_finished = true; - } - - void load_json(const JsonValue& json){ - if (!m_finished){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to use an unfinalized table."); - } - - const JsonArray* array = json.to_array(); - if (array == nullptr){ - return; - } - - for (const auto& item : *array){ - const JsonObject* obj = item.to_object(); - if (obj == nullptr){ - continue; - } - const std::string* slug = obj->get_string("slug"); - if (slug == nullptr){ - slug = obj->get_string("Slug"); - } - if (slug == nullptr){ - continue; - } - auto iter = m_index_map.find(*slug); - if (iter == m_index_map.end()){ - // cout << "slug not found: " << *slug << endl; - continue; - } - m_table[iter->second]->load_json(item); - } - } - JsonValue to_json() const{ - JsonArray array; - for (const StaticTableRow* row : m_table){ - JsonValue val = row->to_json(); - val.to_object_throw()["slug"] = row->slug(); - array.push_back(std::move(val)); - } - return array; - } - std::string check_validity() const{ - for (const StaticTableRow* row : m_table){ - std::string error = row->check_validity(); - if (!error.empty()){ - return error; - } - } - return std::string(); - } - void restore_defaults(){ - for (StaticTableRow* row : m_table){ - row->restore_defaults(); - } - } -}; - - -StaticTableOption::~StaticTableOption() = default; -StaticTableOption::StaticTableOption( - std::string label, - LockMode lock_while_program_is_running, - bool enable_saveload -) - : ConfigOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, std::move(label), enable_saveload) -{} -void StaticTableOption::add_row(std::unique_ptr row){ - m_data->add_row(std::move(row)); -} -void StaticTableOption::add_row(StaticTableRow* row){ - m_data->add_row(row); -} -void StaticTableOption::finish_construction(){ - m_data->finish_construction(); -} - -const std::string& StaticTableOption::label() const{ - return m_data->m_label; -} -const std::vector& StaticTableOption::table() const{ - return m_data->m_table; -} - -void StaticTableOption::load_json(const JsonValue& json){ - m_data->load_json(json); -} -JsonValue StaticTableOption::to_json() const{ - return m_data->to_json(); -} -std::string StaticTableOption::check_validity() const{ - return m_data->check_validity(); -} -void StaticTableOption::restore_defaults(){ - m_data->restore_defaults(); -} -void StaticTableOption::report_program_state(bool program_is_running){ - for (StaticTableRow* row : m_data->m_table){ - row->report_program_state(program_is_running); - } -} - -bool StaticTableOption::saveload_enabled() const{ - return m_data->m_enable_saveload; -} - - - - - - - - - - - - - - - - - - -} +/* Static Table Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "StaticTableOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +StaticTableRow::StaticTableRow(std::string slug) + : m_slug(std::move(slug)) +{} +void StaticTableRow::add_option(ConfigOption& option, std::string serialization_string){ + m_options.emplace_back(std::move(serialization_string), &option); +} +void StaticTableRow::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + for (auto& item : m_options){ + if (!item.first.empty()){ + const JsonValue* value = obj->get_value(item.first); + if (value){ + item.second->load_json(*value); + } + } + } +} +JsonValue StaticTableRow::to_json() const{ + JsonObject obj; + for (auto& item : m_options){ + if (!item.first.empty()){ + obj[item.first] = item.second->to_json(); + } + } + return obj; +} +std::string StaticTableRow::check_validity() const{ + for (const auto& item : m_options){ + std::string error = item.second->check_validity(); + if (!error.empty()){ + return error; + } + } + return std::string(); +} +void StaticTableRow::restore_defaults(){ + for (const auto& item : m_options){ + item.second->restore_defaults(); + } +} +void StaticTableRow::report_program_state(bool program_is_running){ + for (const auto& item : m_options){ + item.second->report_program_state(program_is_running); + } +} +std::vector StaticTableRow::make_cells(){ + std::vector ret; + ret.reserve(m_options.size()); + for (const auto& item : m_options){ + ret.emplace_back(item.second); + } + return ret; +} + + + + +struct StaticTableOption::Data{ + const std::string m_label; + const bool m_enable_saveload; + std::vector> m_owners; + std::vector m_table; + + bool m_finished = false; + std::map m_index_map; + + + Data(std::string label, bool enable_saveload) + : m_label(std::move(label)) + , m_enable_saveload(enable_saveload) + {} + + void add_row(std::unique_ptr row){ + if (m_finished){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add row to finalized table."); + } + + const std::string& slug = row->slug(); + + bool owners_pushed = false; + bool table_pushed = false; + try{ + m_owners.emplace_back(std::move(row)); + owners_pushed = true; + m_table.emplace_back(m_owners.back().get()); + table_pushed = true; + + auto ret = m_index_map.emplace(slug, m_index_map.size()); + if (!ret.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + slug); + } + }catch (...){ + if (owners_pushed){ + m_owners.pop_back(); + } + if (table_pushed){ + m_table.pop_back(); + } + throw; + } + } + void add_row(StaticTableRow* row){ + if (m_finished){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add row to finalized table."); + } + + const std::string& slug = row->slug(); + + bool table_pushed = false; + try{ + m_table.emplace_back(row); + table_pushed = true; + + auto ret = m_index_map.emplace(slug, m_index_map.size()); + if (!ret.second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + slug); + } + }catch (...){ + if (table_pushed){ + m_table.pop_back(); + } + throw; + } + } + + // You must call this when done populating rows. Afterwards, you cannot add more. + void finish_construction(){ + if (m_finished){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to finalize and already finalized table."); + } + m_finished = true; + } + + void load_json(const JsonValue& json){ + if (!m_finished){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to use an unfinalized table."); + } + + const JsonArray* array = json.to_array(); + if (array == nullptr){ + return; + } + + for (const auto& item : *array){ + const JsonObject* obj = item.to_object(); + if (obj == nullptr){ + continue; + } + const std::string* slug = obj->get_string("slug"); + if (slug == nullptr){ + slug = obj->get_string("Slug"); + } + if (slug == nullptr){ + continue; + } + auto iter = m_index_map.find(*slug); + if (iter == m_index_map.end()){ + // cout << "slug not found: " << *slug << endl; + continue; + } + m_table[iter->second]->load_json(item); + } + } + JsonValue to_json() const{ + JsonArray array; + for (const StaticTableRow* row : m_table){ + JsonValue val = row->to_json(); + val.to_object_throw()["slug"] = row->slug(); + array.push_back(std::move(val)); + } + return array; + } + std::string check_validity() const{ + for (const StaticTableRow* row : m_table){ + std::string error = row->check_validity(); + if (!error.empty()){ + return error; + } + } + return std::string(); + } + void restore_defaults(){ + for (StaticTableRow* row : m_table){ + row->restore_defaults(); + } + } +}; + + +StaticTableOption::~StaticTableOption() = default; +StaticTableOption::StaticTableOption( + std::string label, + LockMode lock_while_program_is_running, + bool enable_saveload +) + : ConfigOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, std::move(label), enable_saveload) +{} +void StaticTableOption::add_row(std::unique_ptr row){ + m_data->add_row(std::move(row)); +} +void StaticTableOption::add_row(StaticTableRow* row){ + m_data->add_row(row); +} +void StaticTableOption::finish_construction(){ + m_data->finish_construction(); +} + +const std::string& StaticTableOption::label() const{ + return m_data->m_label; +} +const std::vector& StaticTableOption::table() const{ + return m_data->m_table; +} + +void StaticTableOption::load_json(const JsonValue& json){ + m_data->load_json(json); +} +JsonValue StaticTableOption::to_json() const{ + return m_data->to_json(); +} +std::string StaticTableOption::check_validity() const{ + return m_data->check_validity(); +} +void StaticTableOption::restore_defaults(){ + m_data->restore_defaults(); +} +void StaticTableOption::report_program_state(bool program_is_running){ + for (StaticTableRow* row : m_data->m_table){ + row->report_program_state(program_is_running); + } +} + +bool StaticTableOption::saveload_enabled() const{ + return m_data->m_enable_saveload; +} + + + + + + + + + + + + + + + + + + +} diff --git a/Common/Cpp/Options/StaticTableOption.h b/Common/Cpp/Options/StaticTableOption.h index e97cbd7042..e76b1741a0 100644 --- a/Common/Cpp/Options/StaticTableOption.h +++ b/Common/Cpp/Options/StaticTableOption.h @@ -1,120 +1,120 @@ -/* Static Table Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_StaticTableOption_H -#define PokemonAutomation_Options_StaticTableOption_H - -#include -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -// Represents a row of the table. Users should subclass this and add all the -// configs/fields that is in the row. -class StaticTableRow{ - StaticTableRow(const StaticTableRow&) = delete; - void operator=(const StaticTableRow&) = delete; -public: - virtual ~StaticTableRow() = default; - StaticTableRow(std::string slug); - - const std::string& slug() const{ return m_slug; } - - virtual void load_json(const JsonValue& json); - virtual JsonValue to_json() const; - - virtual std::string check_validity() const; - virtual void restore_defaults(); - - void report_program_state(bool program_is_running); - - -protected: - void add_option(ConfigOption& option, std::string serialization_string); - -#define PA_ADD_STATIC(x) add_option(x, "") -#define PA_ADD_OPTION(x) add_option(x, #x) - - -public: - // Internal use by table. - std::vector make_cells(); - - -private: - friend class StaticTableOption; - std::string m_slug; - std::vector> m_options; -}; - - - - -// This is the table itself. -class StaticTableOption : public ConfigOption{ -public: - ~StaticTableOption(); - StaticTableOption( - std::string label, - LockMode lock_while_program_is_running, - bool enable_saveload = true - ); -protected: - // Construction Steps: - - // Call this to populate the rows. - void add_row(std::unique_ptr row); - void add_row(StaticTableRow* row); - - // You must call this when done populating rows. Afterwards, you cannot add more. - void finish_construction(); - -public: - const std::string& label() const; - const std::vector& table() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override final; - - virtual void report_program_state(bool program_is_running) override; - -public: - bool saveload_enabled() const; - virtual std::vector make_header() const = 0; - -public: - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - -#if 0 -// Convenience helper class that's type-aware. -template -class StaticTableOption_t : public StaticTableOption{ -public: - using StaticTableOption::StaticTableOption; - - -}; -#endif - - - - - - -} -#endif +/* Static Table Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_StaticTableOption_H +#define PokemonAutomation_Options_StaticTableOption_H + +#include +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +// Represents a row of the table. Users should subclass this and add all the +// configs/fields that is in the row. +class StaticTableRow{ + StaticTableRow(const StaticTableRow&) = delete; + void operator=(const StaticTableRow&) = delete; +public: + virtual ~StaticTableRow() = default; + StaticTableRow(std::string slug); + + const std::string& slug() const{ return m_slug; } + + virtual void load_json(const JsonValue& json); + virtual JsonValue to_json() const; + + virtual std::string check_validity() const; + virtual void restore_defaults(); + + void report_program_state(bool program_is_running); + + +protected: + void add_option(ConfigOption& option, std::string serialization_string); + +#define PA_ADD_STATIC(x) add_option(x, "") +#define PA_ADD_OPTION(x) add_option(x, #x) + + +public: + // Internal use by table. + std::vector make_cells(); + + +private: + friend class StaticTableOption; + std::string m_slug; + std::vector> m_options; +}; + + + + +// This is the table itself. +class StaticTableOption : public ConfigOption{ +public: + ~StaticTableOption(); + StaticTableOption( + std::string label, + LockMode lock_while_program_is_running, + bool enable_saveload = true + ); +protected: + // Construction Steps: + + // Call this to populate the rows. + void add_row(std::unique_ptr row); + void add_row(StaticTableRow* row); + + // You must call this when done populating rows. Afterwards, you cannot add more. + void finish_construction(); + +public: + const std::string& label() const; + const std::vector& table() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override final; + + virtual void report_program_state(bool program_is_running) override; + +public: + bool saveload_enabled() const; + virtual std::vector make_header() const = 0; + +public: + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + +#if 0 +// Convenience helper class that's type-aware. +template +class StaticTableOption_t : public StaticTableOption{ +public: + using StaticTableOption::StaticTableOption; + + +}; +#endif + + + + + + +} +#endif diff --git a/Common/Cpp/Options/StaticTextOption.cpp b/Common/Cpp/Options/StaticTextOption.cpp index b4a68ee963..b4cc4524b5 100644 --- a/Common/Cpp/Options/StaticTextOption.cpp +++ b/Common/Cpp/Options/StaticTextOption.cpp @@ -1,115 +1,115 @@ -/* Static Text - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "StaticTextOption.h" - -namespace PokemonAutomation{ - - - -struct StaticTextOption::Data{ - mutable SpinLock m_lock; - std::string m_text; - bool m_text_wrapping; - - Data(std::string text, bool text_wrapping) - : m_text(std::move(text)) - , m_text_wrapping(text_wrapping) - {} -}; - - -StaticTextOption::~StaticTextOption() = default; -StaticTextOption::StaticTextOption(std::string label, bool text_wrapping) - : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) - , m_data(CONSTRUCT_TOKEN, std::move(label), text_wrapping) -{} -#if 0 -std::unique_ptr StaticTextOption::clone() const{ - return std::unique_ptr(new StaticTextOption(m_text)); -} -#endif -bool StaticTextOption::text_wrapping() const{ - return m_data->m_text_wrapping; -} -std::string StaticTextOption::text() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_text; -} -void StaticTextOption::set_text(std::string label){ - { - WriteSpinLock lg(m_data->m_lock); - if (label == m_data->m_text){ - return; - } - m_data->m_text = std::move(label); - } - report_value_changed(this); -} -void StaticTextOption::load_json(const JsonValue&){ - report_value_changed(this); -} -JsonValue StaticTextOption::to_json() const{ - return JsonValue(); -} - - - - - - -struct SectionDividerOption::Data{ - mutable SpinLock m_lock; - std::string m_text; - bool m_text_wrapping; - - Data(std::string text, bool text_wrapping) - : m_text(std::move(text)) - , m_text_wrapping(text_wrapping) - {} -}; - -SectionDividerOption::~SectionDividerOption() = default; -SectionDividerOption::SectionDividerOption(std::string label, bool text_wrapping) - : m_data(CONSTRUCT_TOKEN, std::move(label), text_wrapping) -{} -bool SectionDividerOption::text_wrapping() const{ - return m_data->m_text_wrapping; -} -std::string SectionDividerOption::text() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_text; -} -void SectionDividerOption::set_text(std::string label){ - { - WriteSpinLock lg(m_data->m_lock); - if (label == m_data->m_text){ - return; - } - m_data->m_text = std::move(label); - } - report_value_changed(this); -} -void SectionDividerOption::load_json(const JsonValue&){ - report_value_changed(this); -} -JsonValue SectionDividerOption::to_json() const{ - return JsonValue(); -} - - - - - - - - - - -} +/* Static Text + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "StaticTextOption.h" + +namespace PokemonAutomation{ + + + +struct StaticTextOption::Data{ + mutable SpinLock m_lock; + std::string m_text; + bool m_text_wrapping; + + Data(std::string text, bool text_wrapping) + : m_text(std::move(text)) + , m_text_wrapping(text_wrapping) + {} +}; + + +StaticTextOption::~StaticTextOption() = default; +StaticTextOption::StaticTextOption(std::string label, bool text_wrapping) + : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) + , m_data(CONSTRUCT_TOKEN, std::move(label), text_wrapping) +{} +#if 0 +std::unique_ptr StaticTextOption::clone() const{ + return std::unique_ptr(new StaticTextOption(m_text)); +} +#endif +bool StaticTextOption::text_wrapping() const{ + return m_data->m_text_wrapping; +} +std::string StaticTextOption::text() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_text; +} +void StaticTextOption::set_text(std::string label){ + { + WriteSpinLock lg(m_data->m_lock); + if (label == m_data->m_text){ + return; + } + m_data->m_text = std::move(label); + } + report_value_changed(this); +} +void StaticTextOption::load_json(const JsonValue&){ + report_value_changed(this); +} +JsonValue StaticTextOption::to_json() const{ + return JsonValue(); +} + + + + + + +struct SectionDividerOption::Data{ + mutable SpinLock m_lock; + std::string m_text; + bool m_text_wrapping; + + Data(std::string text, bool text_wrapping) + : m_text(std::move(text)) + , m_text_wrapping(text_wrapping) + {} +}; + +SectionDividerOption::~SectionDividerOption() = default; +SectionDividerOption::SectionDividerOption(std::string label, bool text_wrapping) + : m_data(CONSTRUCT_TOKEN, std::move(label), text_wrapping) +{} +bool SectionDividerOption::text_wrapping() const{ + return m_data->m_text_wrapping; +} +std::string SectionDividerOption::text() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_text; +} +void SectionDividerOption::set_text(std::string label){ + { + WriteSpinLock lg(m_data->m_lock); + if (label == m_data->m_text){ + return; + } + m_data->m_text = std::move(label); + } + report_value_changed(this); +} +void SectionDividerOption::load_json(const JsonValue&){ + report_value_changed(this); +} +JsonValue SectionDividerOption::to_json() const{ + return JsonValue(); +} + + + + + + + + + + +} diff --git a/Common/Cpp/Options/StaticTextOption.h b/Common/Cpp/Options/StaticTextOption.h index acece933d4..397125e862 100644 --- a/Common/Cpp/Options/StaticTextOption.h +++ b/Common/Cpp/Options/StaticTextOption.h @@ -1,68 +1,68 @@ -/* Static Text Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_StaticTextOption_H -#define PokemonAutomation_Options_StaticTextOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - - -class StaticTextOption : public ConfigOption{ -public: - ~StaticTextOption(); - StaticTextOption(std::string label, bool text_wrapping = true); - - bool text_wrapping() const; - std::string text() const; - void set_text(std::string label); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override{} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - -class SectionDividerOption : public ConfigOption{ -public: - ~SectionDividerOption(); - SectionDividerOption(std::string label, bool text_wrapping = true); - - bool text_wrapping() const; - std::string text() const; - void set_text(std::string label); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override{} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - - - -} -#endif - - +/* Static Text Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_StaticTextOption_H +#define PokemonAutomation_Options_StaticTextOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + + +class StaticTextOption : public ConfigOption{ +public: + ~StaticTextOption(); + StaticTextOption(std::string label, bool text_wrapping = true); + + bool text_wrapping() const; + std::string text() const; + void set_text(std::string label); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override{} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + +class SectionDividerOption : public ConfigOption{ +public: + ~SectionDividerOption(); + SectionDividerOption(std::string label, bool text_wrapping = true); + + bool text_wrapping() const; + std::string text() const; + void set_text(std::string label); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override{} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + + + +} +#endif + + diff --git a/Common/Cpp/Options/StringOption.cpp b/Common/Cpp/Options/StringOption.cpp index 9e5b40ebd6..fadd8cd8c8 100644 --- a/Common/Cpp/Options/StringOption.cpp +++ b/Common/Cpp/Options/StringOption.cpp @@ -1,123 +1,123 @@ -/* String Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "StringOption.h" - -namespace PokemonAutomation{ - - -struct StringCell::Data{ - const bool m_is_password; - const std::string m_default; - const std::string m_placeholder_text; - - std::atomic m_locked; - - mutable SpinLock m_lock; - std::string m_current; - - Data( - bool is_password, - std::string default_value, - std::string placeholder_text - ) - : m_is_password(is_password) - , m_default(std::move(default_value)) - , m_placeholder_text(std::move(placeholder_text)) - , m_current(m_default) - {} -}; - - -StringCell::~StringCell() = default; -StringCell::StringCell( - bool is_password, - LockMode lock_while_program_is_running, - std::string default_value, - std::string placeholder_text -) - : ConfigOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, is_password, std::move(default_value), std::move(placeholder_text)) -{} - -bool StringCell::is_password() const{ - return m_data->m_is_password; -} -const std::string& StringCell::placeholder_text() const{ - return m_data->m_placeholder_text; -} -const std::string StringCell::default_value() const{ - return m_data->m_default; -} - - -bool StringCell::is_locked() const{ - return m_data->m_locked.load(std::memory_order_relaxed); -} -void StringCell::set_locked(bool locked){ - if (locked == is_locked()){ - return; - } - m_data->m_locked.store(locked, std::memory_order_relaxed); - report_visibility_changed(); -} - - -StringCell::operator std::string() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -void StringCell::set(std::string x){ - sanitize(x); - { - WriteSpinLock lg(m_data->m_lock); - if (m_data->m_current == x){ - return; - } - m_data->m_current = std::move(x); - } - report_value_changed(this); -} - -void StringCell::load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - set(*str); -} -JsonValue StringCell::to_json() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} - -void StringCell::restore_defaults(){ - set(m_data->m_default); -} - - - -StringOption::StringOption( - bool is_password, - std::string label, - LockMode lock_while_program_is_running, - std::string default_value, - std::string placeholder_text -) - : StringCell(is_password, lock_while_program_is_running, default_value, placeholder_text) - , m_label(std::move(label)) -{} - - - - - - - -} +/* String Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "StringOption.h" + +namespace PokemonAutomation{ + + +struct StringCell::Data{ + const bool m_is_password; + const std::string m_default; + const std::string m_placeholder_text; + + std::atomic m_locked; + + mutable SpinLock m_lock; + std::string m_current; + + Data( + bool is_password, + std::string default_value, + std::string placeholder_text + ) + : m_is_password(is_password) + , m_default(std::move(default_value)) + , m_placeholder_text(std::move(placeholder_text)) + , m_current(m_default) + {} +}; + + +StringCell::~StringCell() = default; +StringCell::StringCell( + bool is_password, + LockMode lock_while_program_is_running, + std::string default_value, + std::string placeholder_text +) + : ConfigOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, is_password, std::move(default_value), std::move(placeholder_text)) +{} + +bool StringCell::is_password() const{ + return m_data->m_is_password; +} +const std::string& StringCell::placeholder_text() const{ + return m_data->m_placeholder_text; +} +const std::string StringCell::default_value() const{ + return m_data->m_default; +} + + +bool StringCell::is_locked() const{ + return m_data->m_locked.load(std::memory_order_relaxed); +} +void StringCell::set_locked(bool locked){ + if (locked == is_locked()){ + return; + } + m_data->m_locked.store(locked, std::memory_order_relaxed); + report_visibility_changed(); +} + + +StringCell::operator std::string() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +void StringCell::set(std::string x){ + sanitize(x); + { + WriteSpinLock lg(m_data->m_lock); + if (m_data->m_current == x){ + return; + } + m_data->m_current = std::move(x); + } + report_value_changed(this); +} + +void StringCell::load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + set(*str); +} +JsonValue StringCell::to_json() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} + +void StringCell::restore_defaults(){ + set(m_data->m_default); +} + + + +StringOption::StringOption( + bool is_password, + std::string label, + LockMode lock_while_program_is_running, + std::string default_value, + std::string placeholder_text +) + : StringCell(is_password, lock_while_program_is_running, default_value, placeholder_text) + , m_label(std::move(label)) +{} + + + + + + + +} diff --git a/Common/Cpp/Options/StringOption.h b/Common/Cpp/Options/StringOption.h index 1b34f4f496..cc3f685d7e 100644 --- a/Common/Cpp/Options/StringOption.h +++ b/Common/Cpp/Options/StringOption.h @@ -1,75 +1,75 @@ -/* String Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_StringOption_H -#define PokemonAutomation_Options_StringOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -class StringCell : public ConfigOption{ -public: - ~StringCell(); - StringCell( - bool is_password, - LockMode lock_while_program_is_running, - std::string default_value, - std::string placeholder_text - ); - - bool is_password() const; - const std::string& placeholder_text() const; - const std::string default_value() const; - - bool is_locked() const; - void set_locked(bool locked); - - operator std::string() const; - void set(std::string x); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - virtual void sanitize(std::string& str){} - -private: - struct Data; - Pimpl m_data; -}; - - -class StringOption : public StringCell{ -public: - StringOption( - bool is_password, - std::string label, - LockMode lock_while_program_is_running, - std::string default_value, - std::string placeholder_text - ); - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - - -} -#endif - +/* String Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_StringOption_H +#define PokemonAutomation_Options_StringOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +class StringCell : public ConfigOption{ +public: + ~StringCell(); + StringCell( + bool is_password, + LockMode lock_while_program_is_running, + std::string default_value, + std::string placeholder_text + ); + + bool is_password() const; + const std::string& placeholder_text() const; + const std::string default_value() const; + + bool is_locked() const; + void set_locked(bool locked); + + operator std::string() const; + void set(std::string x); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + virtual void sanitize(std::string& str){} + +private: + struct Data; + Pimpl m_data; +}; + + +class StringOption : public StringCell{ +public: + StringOption( + bool is_password, + std::string label, + LockMode lock_while_program_is_running, + std::string default_value, + std::string placeholder_text + ); + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + + +} +#endif + diff --git a/Common/Cpp/Options/TextEditOption.cpp b/Common/Cpp/Options/TextEditOption.cpp index 8d9e0ba2e5..520951f2be 100644 --- a/Common/Cpp/Options/TextEditOption.cpp +++ b/Common/Cpp/Options/TextEditOption.cpp @@ -1,128 +1,128 @@ -/* Text Edit - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "TextEditOption.h" - -namespace PokemonAutomation{ - - -struct TextEditOption::Data{ - const std::string m_label; - const std::string m_default; - const std::string m_placeholder_text; - const bool m_report_all_text_changes; - - mutable SpinLock m_lock; - std::string m_current; - std::set listeners; - - Data( - std::string label, - std::string default_value, - std::string placeholder_text, - bool report_all_text_changes - ) - : m_label(std::move(label)) - , m_default(std::move(default_value)) - , m_placeholder_text(std::move(placeholder_text)) - , m_report_all_text_changes(report_all_text_changes) - , m_current(m_default) - {} -}; - -void TextEditOption::add_listener(FocusListener& listener){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - data.listeners.insert(&listener); -} -void TextEditOption::remove_listener(FocusListener& listener){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - data.listeners.erase(&listener); -} -void TextEditOption::report_focus_in(){ - Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - for (FocusListener* listener : data.listeners){ - listener->focus_in(); - } -} - -TextEditOption::~TextEditOption() = default; -TextEditOption::TextEditOption( - std::string label, - LockMode lock_while_program_is_running, - std::string default_value, - std::string placeholder_text, - bool signal_all_text_changes -) - : ConfigOption(lock_while_program_is_running) - , m_data(CONSTRUCT_TOKEN, std::move(label), std::move(default_value), std::move(placeholder_text), signal_all_text_changes) -{} -#if 0 -std::unique_ptr TextEditOption::clone() const{ - std::unique_ptr ret(new TextEditOption(m_label, m_default, m_placeholder_text)); - ret->m_current = m_current; - return ret; -} -#endif - -const std::string& TextEditOption::label() const{ - return m_data->m_label; -} -const std::string& TextEditOption::placeholder_text() const{ - return m_data->m_placeholder_text; -} -bool TextEditOption::signal_all_text_changes() const{ - return m_data->m_report_all_text_changes; -} - -TextEditOption::operator std::string() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -void TextEditOption::set(std::string x){ - { - WriteSpinLock lg(m_data->m_lock); - if (m_data->m_current == x){ - return; - } - m_data->m_current = std::move(x); - } - report_value_changed(this); -} - - -void TextEditOption::load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - set(*str); -} -JsonValue TextEditOption::to_json() const{ - ReadSpinLock lg(m_data->m_lock); - return m_data->m_current; -} -void TextEditOption::restore_defaults(){ - set(m_data->m_default); -} - - - - - - - - - - - -} +/* Text Edit + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "TextEditOption.h" + +namespace PokemonAutomation{ + + +struct TextEditOption::Data{ + const std::string m_label; + const std::string m_default; + const std::string m_placeholder_text; + const bool m_report_all_text_changes; + + mutable SpinLock m_lock; + std::string m_current; + std::set listeners; + + Data( + std::string label, + std::string default_value, + std::string placeholder_text, + bool report_all_text_changes + ) + : m_label(std::move(label)) + , m_default(std::move(default_value)) + , m_placeholder_text(std::move(placeholder_text)) + , m_report_all_text_changes(report_all_text_changes) + , m_current(m_default) + {} +}; + +void TextEditOption::add_listener(FocusListener& listener){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + data.listeners.insert(&listener); +} +void TextEditOption::remove_listener(FocusListener& listener){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + data.listeners.erase(&listener); +} +void TextEditOption::report_focus_in(){ + Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + for (FocusListener* listener : data.listeners){ + listener->focus_in(); + } +} + +TextEditOption::~TextEditOption() = default; +TextEditOption::TextEditOption( + std::string label, + LockMode lock_while_program_is_running, + std::string default_value, + std::string placeholder_text, + bool signal_all_text_changes +) + : ConfigOption(lock_while_program_is_running) + , m_data(CONSTRUCT_TOKEN, std::move(label), std::move(default_value), std::move(placeholder_text), signal_all_text_changes) +{} +#if 0 +std::unique_ptr TextEditOption::clone() const{ + std::unique_ptr ret(new TextEditOption(m_label, m_default, m_placeholder_text)); + ret->m_current = m_current; + return ret; +} +#endif + +const std::string& TextEditOption::label() const{ + return m_data->m_label; +} +const std::string& TextEditOption::placeholder_text() const{ + return m_data->m_placeholder_text; +} +bool TextEditOption::signal_all_text_changes() const{ + return m_data->m_report_all_text_changes; +} + +TextEditOption::operator std::string() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +void TextEditOption::set(std::string x){ + { + WriteSpinLock lg(m_data->m_lock); + if (m_data->m_current == x){ + return; + } + m_data->m_current = std::move(x); + } + report_value_changed(this); +} + + +void TextEditOption::load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + set(*str); +} +JsonValue TextEditOption::to_json() const{ + ReadSpinLock lg(m_data->m_lock); + return m_data->m_current; +} +void TextEditOption::restore_defaults(){ + set(m_data->m_default); +} + + + + + + + + + + + +} diff --git a/Common/Cpp/Options/TextEditOption.h b/Common/Cpp/Options/TextEditOption.h index 5212c60152..0fbef7f1c4 100644 --- a/Common/Cpp/Options/TextEditOption.h +++ b/Common/Cpp/Options/TextEditOption.h @@ -1,61 +1,61 @@ -/* Text Edit Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TextEditOption_H -#define PokemonAutomation_Options_TextEditOption_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "ConfigOption.h" - -namespace PokemonAutomation{ - - -class TextEditOption : public ConfigOption{ -public: - // Listeners for when the user focuses on this box. - struct FocusListener{ - virtual void focus_in(){} - }; - void add_listener(FocusListener& listener); - void remove_listener(FocusListener& listener); - - void report_focus_in(); - -public: - ~TextEditOption(); - TextEditOption( - std::string label, - LockMode lock_while_program_is_running, - std::string default_value, - std::string placeholder_text, - bool signal_all_text_changes = false - ); -// virtual std::unique_ptr clone() const override; - - const std::string& label() const; - const std::string& placeholder_text() const; - bool signal_all_text_changes() const; - - operator std::string() const; - void set(std::string x); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Text Edit Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TextEditOption_H +#define PokemonAutomation_Options_TextEditOption_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "ConfigOption.h" + +namespace PokemonAutomation{ + + +class TextEditOption : public ConfigOption{ +public: + // Listeners for when the user focuses on this box. + struct FocusListener{ + virtual void focus_in(){} + }; + void add_listener(FocusListener& listener); + void remove_listener(FocusListener& listener); + + void report_focus_in(); + +public: + ~TextEditOption(); + TextEditOption( + std::string label, + LockMode lock_while_program_is_running, + std::string default_value, + std::string placeholder_text, + bool signal_all_text_changes = false + ); +// virtual std::unique_ptr clone() const override; + + const std::string& label() const; + const std::string& placeholder_text() const; + bool signal_all_text_changes() const; + + operator std::string() const; + void set(std::string x); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/TimeDurationOption.cpp b/Common/Cpp/Options/TimeDurationOption.cpp index 53d34007e3..e9c53a8465 100644 --- a/Common/Cpp/Options/TimeDurationOption.cpp +++ b/Common/Cpp/Options/TimeDurationOption.cpp @@ -1,337 +1,337 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/ExpressionEvaluator.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/Options/TimeDurationWidget.h" -#include "TimeDurationOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -template -struct TimeDurationCell::Data{ - const std::string m_units; - const bool m_show_summary; - const Type m_min_value; - const Type m_max_value; - const std::string m_default; - - mutable SpinLock m_lock; - std::string m_current; - Type m_value; - std::string m_error; - - Data( - std::string units, bool show_summary, - Type min_value, Type max_value, - std::string default_value - ) - : m_units(units) - , m_show_summary(show_summary) - , m_min_value(min_value) - , m_max_value(max_value) - , m_default(std::move(default_value)) - , m_current(m_default) - , m_value(0) - { - m_error = process(m_current, m_value); - } - - static std::map make_symbol_map(){ - std::map map; - - auto self = std::chrono::duration_cast(Type(1)).count(); - auto microseconds = std::chrono::duration_cast(std::chrono::microseconds(1)).count(); - auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); - auto seconds = std::chrono::duration_cast(std::chrono::seconds(1)).count(); - auto minutes = std::chrono::duration_cast(std::chrono::minutes(1)).count(); - auto hours = std::chrono::duration_cast(std::chrono::hours(1)).count(); - auto days = std::chrono::duration_cast(std::chrono::days(1)).count(); - auto weeks = days * 7; - auto years = std::chrono::duration_cast(std::chrono::years(1)).count(); - - if (self <= microseconds){ - map["us"] = map["microsecond"] = map["microseconds"] = microseconds / self; - } - if (self <= milliseconds){ - map["ms"] = map["millisecond"] = map["milliseconds"] = milliseconds / self; - } - if (self <= seconds){ - map["s"] = map["secs"] = map["second"] = map["seconds"] = seconds / self; - } - if (self <= minutes){ - map["min"] = map["minute"] = map["minutes"] = minutes / self; - } - if (self <= hours){ - map["h"] = map["hour"] = map["hours"] = hours / self; - } - if (self <= days){ - map["d"] = map["day"] = map["days"] = days / self; - } - if (self <= weeks){ - map["w"] = map["week"] = map["weeks"] = weeks / self; - } - if (self <= years){ - map["y"] = map["year"] = map["years"] = years / self; - } - - return map; - } - - std::string process(const std::string& text, Type& value) const{ - if (text.empty()){ - return "Expression is empty."; - } - - static const std::map SYMBOLS = make_symbol_map(); - - using Rep = typename Type::rep; - Rep parsed; - try{ - parsed = parse_expression(SYMBOLS, text); - }catch (const ParseException& str){ - return str.message(); - } - // std::cout << "value = " << parsed << " " << m_min_value << " " << m_max_value << std::endl; - - if (Type(parsed) < m_min_value){ - return "Overflow: Number is too small."; - } - if (Type(parsed) > m_max_value){ - return "Overflow: Number is too large."; - } - value = (Type)parsed; - return std::string(); - } -}; - - - - - -template -TimeDurationCell::~TimeDurationCell() = default; -template -TimeDurationCell::TimeDurationCell( - std::string units, bool show_summary, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), show_summary, - min_value, max_value, - std::move(default_value) - ) -{} - -template -TimeDurationCell::TimeDurationCell( - std::string units, - LockMode lock_while_running, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), true, - Type(0), Type::max(), - std::move(default_value) - ) -{} -template -TimeDurationCell::TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), true, - min_value, Type::max(), - std::move(default_value) - ) -{} - -template -TimeDurationCell::TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - std::move(units), true, - min_value, max_value, - std::move(default_value) - ) -{} - - -template -const std::string& TimeDurationCell::units() const{ - return m_data->m_units; -} -template -bool TimeDurationCell::show_summary() const{ - return m_data->m_show_summary; -} -template -Type TimeDurationCell::min_value() const{ - return m_data->m_min_value; -} -template -Type TimeDurationCell::max_value() const{ - return m_data->m_max_value; -} -template -const std::string& TimeDurationCell::default_value() const{ - return m_data->m_default; -} -template -std::string TimeDurationCell::current_text() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_current; -} -template -Type TimeDurationCell::get() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_value; -} -template -std::string TimeDurationCell::set(std::string text){ - Data& data = *m_data; - Type value(0); - std::string error; - { - WriteSpinLock lg(data.m_lock); - if (data.m_current == text){ - return std::string(); - } - error = data.process(text, value); - data.m_current = std::move(text); - data.m_value = value; - data.m_error.clear(); - } - report_value_changed(this); - return error; -} - -template -std::string TimeDurationCell::time_string() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - if (!data.m_error.empty()){ - return "" + data.m_error + ""; - } - return time_string(data.m_current); -} -template -std::string TimeDurationCell::time_string(const std::string& text) const{ - const Data& data = *m_data; - Type value; - std::string error = data.process(text, value); - if (!error.empty()){ - return "" + error + ""; - } - - constexpr auto self = std::chrono::duration_cast(Type(1)).count(); - constexpr auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); - if constexpr (self >= milliseconds){ - return duration_to_string(std::chrono::duration_cast(value)); - }else{ - return tostr_u_commas(value.count()) + " " + m_data->m_units; - } -} - -template -void TimeDurationCell::load_json(const JsonValue& json){ - Data& data = *m_data; - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - { - WriteSpinLock lg(data.m_lock); - data.m_current = *str; - data.m_error = data.process(data.m_current, data.m_value); - } - report_value_changed(this); -} -template -JsonValue TimeDurationCell::to_json() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_current; -} - -template -std::string TimeDurationCell::check_validity() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_error; -} -template -void TimeDurationCell::restore_defaults(){ - Data& data = *m_data; - { - WriteSpinLock lg(data.m_lock); - data.m_current = data.m_default; - data.m_error = data.process(data.m_current, data.m_value); - } - report_value_changed(this); -} - - - - - - - - - -template -ConfigWidget* TimeDurationCell::make_QtWidget(QWidget& parent){ - return new TimeDurationCellWidget(parent, *this); -} - -template -ConfigWidget* TimeDurationOption::make_QtWidget(QWidget& parent){ - return new TimeDurationOptionWidget(parent, *this); -} - - - - - -template class TimeDurationCell; -template class TimeDurationCell; -template class TimeDurationOption; -template class TimeDurationOption; - - - - - - - -} +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/ExpressionEvaluator.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/Options/TimeDurationWidget.h" +#include "TimeDurationOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +template +struct TimeDurationCell::Data{ + const std::string m_units; + const bool m_show_summary; + const Type m_min_value; + const Type m_max_value; + const std::string m_default; + + mutable SpinLock m_lock; + std::string m_current; + Type m_value; + std::string m_error; + + Data( + std::string units, bool show_summary, + Type min_value, Type max_value, + std::string default_value + ) + : m_units(units) + , m_show_summary(show_summary) + , m_min_value(min_value) + , m_max_value(max_value) + , m_default(std::move(default_value)) + , m_current(m_default) + , m_value(0) + { + m_error = process(m_current, m_value); + } + + static std::map make_symbol_map(){ + std::map map; + + auto self = std::chrono::duration_cast(Type(1)).count(); + auto microseconds = std::chrono::duration_cast(std::chrono::microseconds(1)).count(); + auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); + auto seconds = std::chrono::duration_cast(std::chrono::seconds(1)).count(); + auto minutes = std::chrono::duration_cast(std::chrono::minutes(1)).count(); + auto hours = std::chrono::duration_cast(std::chrono::hours(1)).count(); + auto days = std::chrono::duration_cast(std::chrono::days(1)).count(); + auto weeks = days * 7; + auto years = std::chrono::duration_cast(std::chrono::years(1)).count(); + + if (self <= microseconds){ + map["us"] = map["microsecond"] = map["microseconds"] = microseconds / self; + } + if (self <= milliseconds){ + map["ms"] = map["millisecond"] = map["milliseconds"] = milliseconds / self; + } + if (self <= seconds){ + map["s"] = map["secs"] = map["second"] = map["seconds"] = seconds / self; + } + if (self <= minutes){ + map["min"] = map["minute"] = map["minutes"] = minutes / self; + } + if (self <= hours){ + map["h"] = map["hour"] = map["hours"] = hours / self; + } + if (self <= days){ + map["d"] = map["day"] = map["days"] = days / self; + } + if (self <= weeks){ + map["w"] = map["week"] = map["weeks"] = weeks / self; + } + if (self <= years){ + map["y"] = map["year"] = map["years"] = years / self; + } + + return map; + } + + std::string process(const std::string& text, Type& value) const{ + if (text.empty()){ + return "Expression is empty."; + } + + static const std::map SYMBOLS = make_symbol_map(); + + using Rep = typename Type::rep; + Rep parsed; + try{ + parsed = parse_expression(SYMBOLS, text); + }catch (const ParseException& str){ + return str.message(); + } + // std::cout << "value = " << parsed << " " << m_min_value << " " << m_max_value << std::endl; + + if (Type(parsed) < m_min_value){ + return "Overflow: Number is too small."; + } + if (Type(parsed) > m_max_value){ + return "Overflow: Number is too large."; + } + value = (Type)parsed; + return std::string(); + } +}; + + + + + +template +TimeDurationCell::~TimeDurationCell() = default; +template +TimeDurationCell::TimeDurationCell( + std::string units, bool show_summary, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), show_summary, + min_value, max_value, + std::move(default_value) + ) +{} + +template +TimeDurationCell::TimeDurationCell( + std::string units, + LockMode lock_while_running, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), true, + Type(0), Type::max(), + std::move(default_value) + ) +{} +template +TimeDurationCell::TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), true, + min_value, Type::max(), + std::move(default_value) + ) +{} + +template +TimeDurationCell::TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + std::move(units), true, + min_value, max_value, + std::move(default_value) + ) +{} + + +template +const std::string& TimeDurationCell::units() const{ + return m_data->m_units; +} +template +bool TimeDurationCell::show_summary() const{ + return m_data->m_show_summary; +} +template +Type TimeDurationCell::min_value() const{ + return m_data->m_min_value; +} +template +Type TimeDurationCell::max_value() const{ + return m_data->m_max_value; +} +template +const std::string& TimeDurationCell::default_value() const{ + return m_data->m_default; +} +template +std::string TimeDurationCell::current_text() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_current; +} +template +Type TimeDurationCell::get() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_value; +} +template +std::string TimeDurationCell::set(std::string text){ + Data& data = *m_data; + Type value(0); + std::string error; + { + WriteSpinLock lg(data.m_lock); + if (data.m_current == text){ + return std::string(); + } + error = data.process(text, value); + data.m_current = std::move(text); + data.m_value = value; + data.m_error.clear(); + } + report_value_changed(this); + return error; +} + +template +std::string TimeDurationCell::time_string() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + if (!data.m_error.empty()){ + return "" + data.m_error + ""; + } + return time_string(data.m_current); +} +template +std::string TimeDurationCell::time_string(const std::string& text) const{ + const Data& data = *m_data; + Type value; + std::string error = data.process(text, value); + if (!error.empty()){ + return "" + error + ""; + } + + constexpr auto self = std::chrono::duration_cast(Type(1)).count(); + constexpr auto milliseconds = std::chrono::duration_cast(std::chrono::milliseconds(1)).count(); + if constexpr (self >= milliseconds){ + return duration_to_string(std::chrono::duration_cast(value)); + }else{ + return tostr_u_commas(value.count()) + " " + m_data->m_units; + } +} + +template +void TimeDurationCell::load_json(const JsonValue& json){ + Data& data = *m_data; + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + { + WriteSpinLock lg(data.m_lock); + data.m_current = *str; + data.m_error = data.process(data.m_current, data.m_value); + } + report_value_changed(this); +} +template +JsonValue TimeDurationCell::to_json() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_current; +} + +template +std::string TimeDurationCell::check_validity() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_error; +} +template +void TimeDurationCell::restore_defaults(){ + Data& data = *m_data; + { + WriteSpinLock lg(data.m_lock); + data.m_current = data.m_default; + data.m_error = data.process(data.m_current, data.m_value); + } + report_value_changed(this); +} + + + + + + + + + +template +ConfigWidget* TimeDurationCell::make_QtWidget(QWidget& parent){ + return new TimeDurationCellWidget(parent, *this); +} + +template +ConfigWidget* TimeDurationOption::make_QtWidget(QWidget& parent){ + return new TimeDurationOptionWidget(parent, *this); +} + + + + + +template class TimeDurationCell; +template class TimeDurationCell; +template class TimeDurationOption; +template class TimeDurationOption; + + + + + + + +} diff --git a/Common/Cpp/Options/TimeDurationOption.h b/Common/Cpp/Options/TimeDurationOption.h index 0db97e386e..5207fa485e 100644 --- a/Common/Cpp/Options/TimeDurationOption.h +++ b/Common/Cpp/Options/TimeDurationOption.h @@ -1,149 +1,149 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TimeDurationOption_H -#define PokemonAutomation_Options_TimeDurationOption_H - -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -template -class TimeDurationCell : public ConfigOption{ -public: - ~TimeDurationCell(); - TimeDurationCell(const TimeDurationCell& x) = delete; - TimeDurationCell( - std::string units, bool show_summary, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value - ); - -public: - TimeDurationCell( - std::string units, - LockMode lock_while_running, - std::string default_value - ); - TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, - std::string default_value - ); - TimeDurationCell( - std::string units, - LockMode lock_while_running, - Type min_value, Type max_value, - std::string default_value - ); - - -public: - const std::string& units() const; - bool show_summary() const; - Type min_value() const; - Type max_value() const; - const std::string& default_value() const; - std::string current_text() const; - - template - operator std::chrono::duration() const{ - return std::chrono::duration_cast>(get()); - } - - Type get() const; - std::string set(std::string text); - - -public: - // Get the description text using the current value. - std::string time_string() const; - - // Get the description text if you were to set the box to this value. - std::string time_string(const std::string& text) const; - - -public: - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - -protected: - struct Data; - Pimpl m_data; -}; - - - -template -class TimeDurationOption : public TimeDurationCell{ -public: - template - TimeDurationOption(std::string label, Args&&... args) - : TimeDurationCell(std::forward(args)...) - , m_label(std::move(label)) - {} - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - - - -class MillisecondsCell : public TimeDurationCell{ -public: - template - MillisecondsCell(Args&&... args) - : TimeDurationCell("milliseconds", std::forward(args)...) - {} -}; -class MillisecondsOption : public TimeDurationOption{ -public: - template - MillisecondsOption(std::string label, Args&&... args) - : TimeDurationOption( - std::move(label), - "milliseconds", - std::forward(args)... - ) - {} -}; - - - -class MicrosecondsOption : public TimeDurationOption{ -public: - template - MicrosecondsOption(std::string label, Args&&... args) - : TimeDurationOption( - std::move(label), - "microseconds", - std::forward(args)... - ) - {} -}; - - - - -} -#endif +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TimeDurationOption_H +#define PokemonAutomation_Options_TimeDurationOption_H + +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +template +class TimeDurationCell : public ConfigOption{ +public: + ~TimeDurationCell(); + TimeDurationCell(const TimeDurationCell& x) = delete; + TimeDurationCell( + std::string units, bool show_summary, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value + ); + +public: + TimeDurationCell( + std::string units, + LockMode lock_while_running, + std::string default_value + ); + TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, + std::string default_value + ); + TimeDurationCell( + std::string units, + LockMode lock_while_running, + Type min_value, Type max_value, + std::string default_value + ); + + +public: + const std::string& units() const; + bool show_summary() const; + Type min_value() const; + Type max_value() const; + const std::string& default_value() const; + std::string current_text() const; + + template + operator std::chrono::duration() const{ + return std::chrono::duration_cast>(get()); + } + + Type get() const; + std::string set(std::string text); + + +public: + // Get the description text using the current value. + std::string time_string() const; + + // Get the description text if you were to set the box to this value. + std::string time_string(const std::string& text) const; + + +public: + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + +protected: + struct Data; + Pimpl m_data; +}; + + + +template +class TimeDurationOption : public TimeDurationCell{ +public: + template + TimeDurationOption(std::string label, Args&&... args) + : TimeDurationCell(std::forward(args)...) + , m_label(std::move(label)) + {} + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + + + +class MillisecondsCell : public TimeDurationCell{ +public: + template + MillisecondsCell(Args&&... args) + : TimeDurationCell("milliseconds", std::forward(args)...) + {} +}; +class MillisecondsOption : public TimeDurationOption{ +public: + template + MillisecondsOption(std::string label, Args&&... args) + : TimeDurationOption( + std::move(label), + "milliseconds", + std::forward(args)... + ) + {} +}; + + + +class MicrosecondsOption : public TimeDurationOption{ +public: + template + MicrosecondsOption(std::string label, Args&&... args) + : TimeDurationOption( + std::move(label), + "microseconds", + std::forward(args)... + ) + {} +}; + + + + +} +#endif diff --git a/Common/Cpp/Options/TimeExpressionOption.cpp b/Common/Cpp/Options/TimeExpressionOption.cpp index e698bb63c8..1bbca067fa 100644 --- a/Common/Cpp/Options/TimeExpressionOption.cpp +++ b/Common/Cpp/Options/TimeExpressionOption.cpp @@ -1,355 +1,355 @@ -/* Time Expression Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/ExpressionEvaluator.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/Options/TimeExpressionWidget.h" -#include "TimeExpressionOption.h" - -namespace PokemonAutomation{ - - - -std::string ticks_to_time(double ticks_per_second, int64_t ticks){ - const double SECOND = ticks_per_second; - const double MINUTE = SECOND * 60; - const double HOUR = MINUTE * 60; - const double DAY = HOUR * 24; - - std::string str; - str += tostr_u_commas(ticks); - str += " tick"; - // Compute absolute value of the ticks: - uint64_t abs_ticks = 0; - // int64_t range from [-2^63, 2^63-1], so if ticks is -2^63, abs(ticks) will overflow. - // This if-statement handles this case. - if (ticks == std::numeric_limits::min()){ - abs_ticks = uint64_t(std::numeric_limits::max()) + 1; - } else{ - abs_ticks = std::abs(ticks); - } - if (abs_ticks != 1){ - str += "s"; - } - str += " ("; - if (ticks < 0){ - str += "-"; - } - if (abs_ticks < MINUTE * 2){ - str += tostr_fixed((double)abs_ticks / SECOND, 3); - str += " seconds"; - }else if (abs_ticks < HOUR * 2){ - str += tostr_fixed((double)abs_ticks / MINUTE, 3); - str += " minutes"; - }else if (abs_ticks < DAY * 2){ - str += tostr_fixed((double)abs_ticks / HOUR, 3); - str += " hours"; - }else{ - str += tostr_fixed((double)abs_ticks / DAY, 3); - str += " days"; - } - str += ")"; - return str; -} - - - - -template -struct TimeExpressionCell::Data{ - const double m_ticks_per_second; - const double m_milliseconds_per_tick; - const Type m_min_value; - const Type m_max_value; - const std::string m_default; - - mutable SpinLock m_lock; - std::string m_current; - Type m_value; - std::string m_error; - - Data( - double ticks_per_second, Type min_value, Type max_value, - std::string default_value - ) - : m_ticks_per_second(ticks_per_second) - , m_milliseconds_per_tick(1000 / ticks_per_second) - , m_min_value(min_value) - , m_max_value(max_value) - , m_default(std::move(default_value)) - , m_current(m_default) - , m_value(0) - { - m_error = process(m_current, m_value); - } - - std::string process(const std::string& text, Type& value) const{ - if (text.empty()){ - return "Expression is empty."; - } - int32_t parsed; - try{ - parsed = parse_ticks_i32(text); - }catch (const ParseException& str){ - return str.message(); - } - // std::cout << "value = " << parsed << " " << m_min_value << " " << m_max_value << std::endl; - - if (parsed < (int64_t)m_min_value){ - return "Overflow: Number is too small."; - } - if (parsed > (int64_t)m_max_value){ - return "Overflow: Number is too large."; - } - value = (Type)parsed; - return std::string(); - } -}; - - -template -TimeExpressionCell::~TimeExpressionCell() = default; -template -TimeExpressionCell::TimeExpressionCell( - LockMode lock_while_running, - double ticks_per_second, - Type min_value, Type max_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - ticks_per_second, - min_value, max_value, - std::move(default_value) - ) -{} - -template -TimeExpressionCell::TimeExpressionCell( - LockMode lock_while_running, - double ticks_per_second, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - ticks_per_second, - std::numeric_limits::min(), std::numeric_limits::max(), - std::move(default_value) - ) -{} -template -TimeExpressionCell::TimeExpressionCell( - LockMode lock_while_running, - double ticks_per_second, - Type min_value, - std::string default_value -) - : ConfigOption(lock_while_running) - , m_data( - CONSTRUCT_TOKEN, - ticks_per_second, - min_value, std::numeric_limits::max(), - std::move(default_value) - ) -{} - -template -double TimeExpressionCell::ticks_per_second() const{ - return m_data->m_ticks_per_second; -} -template -Type TimeExpressionCell::min_value() const{ - return m_data->m_min_value; -} -template -Type TimeExpressionCell::max_value() const{ - return m_data->m_max_value; -} -template -const std::string& TimeExpressionCell::default_value() const{ - return m_data->m_default; -} -template -std::string TimeExpressionCell::current_text() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_current; -} -template -TimeExpressionCell::operator Type() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_value; -} -#if 0 -template -TimeExpressionCell::operator Milliseconds() const{ - Type value = (Type)*this; - double millis = (double)value * m_data->m_milliseconds_per_tick; - return Milliseconds(Milliseconds::rep(millis > 0 ? millis + 0.5 : millis - 0.5)); -} -#endif -template -Type TimeExpressionCell::get() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_value; -} -template -std::string TimeExpressionCell::set(std::string text){ - Data& data = *m_data; - Type value = 0; - std::string error; - { - WriteSpinLock lg(data.m_lock); - if (data.m_current == text){ - return std::string(); - } - error = data.process(text, value); - data.m_current = std::move(text); - data.m_value = value; - data.m_error.clear(); - } - report_value_changed(this); - return error; -} -template -std::string TimeExpressionCell::time_string() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - if (!data.m_error.empty()){ - return "" + data.m_error + ""; - } - return ticks_to_time(data.m_ticks_per_second, data.m_value); -} - -template -void TimeExpressionCell::load_json(const JsonValue& json){ - Data& data = *m_data; - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - { - WriteSpinLock lg(data.m_lock); - data.m_current = *str; - data.m_error = data.process(data.m_current, data.m_value); - } - report_value_changed(this); -} -template -JsonValue TimeExpressionCell::to_json() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_current; -} - -template -std::string TimeExpressionCell::check_validity() const{ - const Data& data = *m_data; - ReadSpinLock lg(data.m_lock); - return data.m_error; -} -template -void TimeExpressionCell::restore_defaults(){ - Data& data = *m_data; - { - WriteSpinLock lg(data.m_lock); - data.m_current = data.m_default; - data.m_error = data.process(data.m_current, data.m_value); - } - report_value_changed(this); -} - - - - -template -TimeExpressionOption::TimeExpressionOption( - std::string label, - LockMode lock_while_running, - double ticks_per_second, - Type min_value, Type max_value, - std::string default_value -) - : TimeExpressionCell( - lock_while_running, - ticks_per_second, - min_value, max_value, - std::move(default_value) - ) - , m_label(std::move(label)) -{} -template -TimeExpressionOption::TimeExpressionOption( - std::string label, - LockMode lock_while_running, - double ticks_per_second, - std::string default_value -) - : TimeExpressionCell( - lock_while_running, - ticks_per_second, - std::move(default_value) - ) - , m_label(std::move(label)) -{} -template -TimeExpressionOption::TimeExpressionOption( - std::string label, - LockMode lock_while_running, - double ticks_per_second, - Type min_value, - std::string default_value -) - : TimeExpressionCell( - lock_while_running, - ticks_per_second, - min_value, - std::move(default_value) - ) - , m_label(std::move(label)) -{} - - - - - - - -template -ConfigWidget* TimeExpressionCell::make_QtWidget(QWidget& parent){ - return new TimeExpressionCellWidget(parent, *this); -} - -template -ConfigWidget* TimeExpressionOption::make_QtWidget(QWidget& parent){ - return new TimeExpressionOptionWidget(parent, *this); -} - - -template class TimeExpressionCell; -template class TimeExpressionCell; -template class TimeExpressionCell; -template class TimeExpressionCell; -template class TimeExpressionCell; - -template class TimeExpressionOption; -template class TimeExpressionOption; -template class TimeExpressionOption; -template class TimeExpressionOption; -template class TimeExpressionOption; - - - -} +/* Time Expression Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/ExpressionEvaluator.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/Options/TimeExpressionWidget.h" +#include "TimeExpressionOption.h" + +namespace PokemonAutomation{ + + + +std::string ticks_to_time(double ticks_per_second, int64_t ticks){ + const double SECOND = ticks_per_second; + const double MINUTE = SECOND * 60; + const double HOUR = MINUTE * 60; + const double DAY = HOUR * 24; + + std::string str; + str += tostr_u_commas(ticks); + str += " tick"; + // Compute absolute value of the ticks: + uint64_t abs_ticks = 0; + // int64_t range from [-2^63, 2^63-1], so if ticks is -2^63, abs(ticks) will overflow. + // This if-statement handles this case. + if (ticks == std::numeric_limits::min()){ + abs_ticks = uint64_t(std::numeric_limits::max()) + 1; + } else{ + abs_ticks = std::abs(ticks); + } + if (abs_ticks != 1){ + str += "s"; + } + str += " ("; + if (ticks < 0){ + str += "-"; + } + if (abs_ticks < MINUTE * 2){ + str += tostr_fixed((double)abs_ticks / SECOND, 3); + str += " seconds"; + }else if (abs_ticks < HOUR * 2){ + str += tostr_fixed((double)abs_ticks / MINUTE, 3); + str += " minutes"; + }else if (abs_ticks < DAY * 2){ + str += tostr_fixed((double)abs_ticks / HOUR, 3); + str += " hours"; + }else{ + str += tostr_fixed((double)abs_ticks / DAY, 3); + str += " days"; + } + str += ")"; + return str; +} + + + + +template +struct TimeExpressionCell::Data{ + const double m_ticks_per_second; + const double m_milliseconds_per_tick; + const Type m_min_value; + const Type m_max_value; + const std::string m_default; + + mutable SpinLock m_lock; + std::string m_current; + Type m_value; + std::string m_error; + + Data( + double ticks_per_second, Type min_value, Type max_value, + std::string default_value + ) + : m_ticks_per_second(ticks_per_second) + , m_milliseconds_per_tick(1000 / ticks_per_second) + , m_min_value(min_value) + , m_max_value(max_value) + , m_default(std::move(default_value)) + , m_current(m_default) + , m_value(0) + { + m_error = process(m_current, m_value); + } + + std::string process(const std::string& text, Type& value) const{ + if (text.empty()){ + return "Expression is empty."; + } + int32_t parsed; + try{ + parsed = parse_ticks_i32(text); + }catch (const ParseException& str){ + return str.message(); + } + // std::cout << "value = " << parsed << " " << m_min_value << " " << m_max_value << std::endl; + + if (parsed < (int64_t)m_min_value){ + return "Overflow: Number is too small."; + } + if (parsed > (int64_t)m_max_value){ + return "Overflow: Number is too large."; + } + value = (Type)parsed; + return std::string(); + } +}; + + +template +TimeExpressionCell::~TimeExpressionCell() = default; +template +TimeExpressionCell::TimeExpressionCell( + LockMode lock_while_running, + double ticks_per_second, + Type min_value, Type max_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + ticks_per_second, + min_value, max_value, + std::move(default_value) + ) +{} + +template +TimeExpressionCell::TimeExpressionCell( + LockMode lock_while_running, + double ticks_per_second, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + ticks_per_second, + std::numeric_limits::min(), std::numeric_limits::max(), + std::move(default_value) + ) +{} +template +TimeExpressionCell::TimeExpressionCell( + LockMode lock_while_running, + double ticks_per_second, + Type min_value, + std::string default_value +) + : ConfigOption(lock_while_running) + , m_data( + CONSTRUCT_TOKEN, + ticks_per_second, + min_value, std::numeric_limits::max(), + std::move(default_value) + ) +{} + +template +double TimeExpressionCell::ticks_per_second() const{ + return m_data->m_ticks_per_second; +} +template +Type TimeExpressionCell::min_value() const{ + return m_data->m_min_value; +} +template +Type TimeExpressionCell::max_value() const{ + return m_data->m_max_value; +} +template +const std::string& TimeExpressionCell::default_value() const{ + return m_data->m_default; +} +template +std::string TimeExpressionCell::current_text() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_current; +} +template +TimeExpressionCell::operator Type() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_value; +} +#if 0 +template +TimeExpressionCell::operator Milliseconds() const{ + Type value = (Type)*this; + double millis = (double)value * m_data->m_milliseconds_per_tick; + return Milliseconds(Milliseconds::rep(millis > 0 ? millis + 0.5 : millis - 0.5)); +} +#endif +template +Type TimeExpressionCell::get() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_value; +} +template +std::string TimeExpressionCell::set(std::string text){ + Data& data = *m_data; + Type value = 0; + std::string error; + { + WriteSpinLock lg(data.m_lock); + if (data.m_current == text){ + return std::string(); + } + error = data.process(text, value); + data.m_current = std::move(text); + data.m_value = value; + data.m_error.clear(); + } + report_value_changed(this); + return error; +} +template +std::string TimeExpressionCell::time_string() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + if (!data.m_error.empty()){ + return "" + data.m_error + ""; + } + return ticks_to_time(data.m_ticks_per_second, data.m_value); +} + +template +void TimeExpressionCell::load_json(const JsonValue& json){ + Data& data = *m_data; + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + { + WriteSpinLock lg(data.m_lock); + data.m_current = *str; + data.m_error = data.process(data.m_current, data.m_value); + } + report_value_changed(this); +} +template +JsonValue TimeExpressionCell::to_json() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_current; +} + +template +std::string TimeExpressionCell::check_validity() const{ + const Data& data = *m_data; + ReadSpinLock lg(data.m_lock); + return data.m_error; +} +template +void TimeExpressionCell::restore_defaults(){ + Data& data = *m_data; + { + WriteSpinLock lg(data.m_lock); + data.m_current = data.m_default; + data.m_error = data.process(data.m_current, data.m_value); + } + report_value_changed(this); +} + + + + +template +TimeExpressionOption::TimeExpressionOption( + std::string label, + LockMode lock_while_running, + double ticks_per_second, + Type min_value, Type max_value, + std::string default_value +) + : TimeExpressionCell( + lock_while_running, + ticks_per_second, + min_value, max_value, + std::move(default_value) + ) + , m_label(std::move(label)) +{} +template +TimeExpressionOption::TimeExpressionOption( + std::string label, + LockMode lock_while_running, + double ticks_per_second, + std::string default_value +) + : TimeExpressionCell( + lock_while_running, + ticks_per_second, + std::move(default_value) + ) + , m_label(std::move(label)) +{} +template +TimeExpressionOption::TimeExpressionOption( + std::string label, + LockMode lock_while_running, + double ticks_per_second, + Type min_value, + std::string default_value +) + : TimeExpressionCell( + lock_while_running, + ticks_per_second, + min_value, + std::move(default_value) + ) + , m_label(std::move(label)) +{} + + + + + + + +template +ConfigWidget* TimeExpressionCell::make_QtWidget(QWidget& parent){ + return new TimeExpressionCellWidget(parent, *this); +} + +template +ConfigWidget* TimeExpressionOption::make_QtWidget(QWidget& parent){ + return new TimeExpressionOptionWidget(parent, *this); +} + + +template class TimeExpressionCell; +template class TimeExpressionCell; +template class TimeExpressionCell; +template class TimeExpressionCell; +template class TimeExpressionCell; + +template class TimeExpressionOption; +template class TimeExpressionOption; +template class TimeExpressionOption; +template class TimeExpressionOption; +template class TimeExpressionOption; + + + +} diff --git a/Common/Cpp/Options/TimeExpressionOption.h b/Common/Cpp/Options/TimeExpressionOption.h index d1b20400a8..a50169d776 100644 --- a/Common/Cpp/Options/TimeExpressionOption.h +++ b/Common/Cpp/Options/TimeExpressionOption.h @@ -1,115 +1,115 @@ -/* Time Expression Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TimeExpressionOption_H -#define PokemonAutomation_Options_TimeExpressionOption_H - -//#include "Common/Cpp/Time.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -std::string ticks_to_time(double ticks_per_second, int64_t ticks); - - - -template -class TimeExpressionCell : public ConfigOption{ -public: - ~TimeExpressionCell(); - TimeExpressionCell(const TimeExpressionCell& x) = delete; - TimeExpressionCell( - LockMode lock_while_running, - double ticks_per_second, - Type min_value, Type max_value, - std::string default_value - ); - -public: - TimeExpressionCell( - LockMode lock_while_running, - double ticks_per_second, - std::string default_value - ); - TimeExpressionCell( - LockMode lock_while_running, - double ticks_per_second, - Type min_value, - std::string default_value - ); - - double ticks_per_second() const; - Type min_value() const; - Type max_value() const; - const std::string& default_value() const; - std::string current_text() const; - - operator Type() const; -// operator Milliseconds() const; - Type get() const; - std::string set(std::string text); - - std::string time_string() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -protected: - struct Data; - Pimpl m_data; -}; - - - -template -class TimeExpressionOption : public TimeExpressionCell{ -public: - TimeExpressionOption(const TimeExpressionOption& x) = delete; - TimeExpressionOption( - std::string label, - LockMode lock_while_running, - double ticks_per_second, - Type min_value, Type max_value, - std::string default_value - ); - -public: - TimeExpressionOption( - std::string label, - LockMode lock_while_running, - double ticks_per_second, - std::string default_value - ); - TimeExpressionOption( - std::string label, - LockMode lock_while_running, - double ticks_per_second, - Type min_value, - std::string default_value - ); - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - const std::string m_label; -}; - - - - -} -#endif - - +/* Time Expression Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TimeExpressionOption_H +#define PokemonAutomation_Options_TimeExpressionOption_H + +//#include "Common/Cpp/Time.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +std::string ticks_to_time(double ticks_per_second, int64_t ticks); + + + +template +class TimeExpressionCell : public ConfigOption{ +public: + ~TimeExpressionCell(); + TimeExpressionCell(const TimeExpressionCell& x) = delete; + TimeExpressionCell( + LockMode lock_while_running, + double ticks_per_second, + Type min_value, Type max_value, + std::string default_value + ); + +public: + TimeExpressionCell( + LockMode lock_while_running, + double ticks_per_second, + std::string default_value + ); + TimeExpressionCell( + LockMode lock_while_running, + double ticks_per_second, + Type min_value, + std::string default_value + ); + + double ticks_per_second() const; + Type min_value() const; + Type max_value() const; + const std::string& default_value() const; + std::string current_text() const; + + operator Type() const; +// operator Milliseconds() const; + Type get() const; + std::string set(std::string text); + + std::string time_string() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +protected: + struct Data; + Pimpl m_data; +}; + + + +template +class TimeExpressionOption : public TimeExpressionCell{ +public: + TimeExpressionOption(const TimeExpressionOption& x) = delete; + TimeExpressionOption( + std::string label, + LockMode lock_while_running, + double ticks_per_second, + Type min_value, Type max_value, + std::string default_value + ); + +public: + TimeExpressionOption( + std::string label, + LockMode lock_while_running, + double ticks_per_second, + std::string default_value + ); + TimeExpressionOption( + std::string label, + LockMode lock_while_running, + double ticks_per_second, + Type min_value, + std::string default_value + ); + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + const std::string m_label; +}; + + + + +} +#endif + + diff --git a/Common/Cpp/PanicDump.cpp b/Common/Cpp/PanicDump.cpp index 26610c4105..685576efc1 100644 --- a/Common/Cpp/PanicDump.cpp +++ b/Common/Cpp/PanicDump.cpp @@ -1,62 +1,62 @@ -/* Panic Dumping - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ClientSource/Libraries/Logging.h" -#include "PrettyPrint.h" -#include "PanicDump.h" - -namespace PokemonAutomation{ - - - -void panic_dump(const char* location, const char* message){ - std::string body; - body += "\xef\xbb\xbf"; // UTF-8 BOM -// body += "Panic Dump:\r\n"; - - body += "Caught Location: "; - body += location; - body += "\r\n\r\n"; - -// body += "Exception: "; - body += message; - body += "\r\n"; - - FILE* file = fopen(("PanicDump-" + now_to_filestring() + ".log").c_str(), "wb"); - fwrite(body.c_str(), sizeof(char), body.size() * sizeof(char), file); - fclose(file); -} - - -void run_with_catch(const char* location, std::function&& lambda){ -#if 1 - lambda(); -#else - try{ - lambda(); - }catch (Exception& e){ - panic_dump(location, e.message().c_str()); - throw; - }catch (const char* e){ - panic_dump(location, e); - throw; - }catch (const std::string& e){ - panic_dump(location, e.c_str()); - throw; - }catch (const std::exception& e){ - panic_dump(location, e.what()); - throw; - }catch (...){ - panic_dump(location, "Unknown Exception"); - throw; - } -#endif -} - - - -} +/* Panic Dumping + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ClientSource/Libraries/Logging.h" +#include "PrettyPrint.h" +#include "PanicDump.h" + +namespace PokemonAutomation{ + + + +void panic_dump(const char* location, const char* message){ + std::string body; + body += "\xef\xbb\xbf"; // UTF-8 BOM +// body += "Panic Dump:\r\n"; + + body += "Caught Location: "; + body += location; + body += "\r\n\r\n"; + +// body += "Exception: "; + body += message; + body += "\r\n"; + + FILE* file = fopen(("PanicDump-" + now_to_filestring() + ".log").c_str(), "wb"); + fwrite(body.c_str(), sizeof(char), body.size() * sizeof(char), file); + fclose(file); +} + + +void run_with_catch(const char* location, std::function&& lambda){ +#if 1 + lambda(); +#else + try{ + lambda(); + }catch (Exception& e){ + panic_dump(location, e.message().c_str()); + throw; + }catch (const char* e){ + panic_dump(location, e); + throw; + }catch (const std::string& e){ + panic_dump(location, e.c_str()); + throw; + }catch (const std::exception& e){ + panic_dump(location, e.what()); + throw; + }catch (...){ + panic_dump(location, "Unknown Exception"); + throw; + } +#endif +} + + + +} diff --git a/Common/Cpp/PanicDump.h b/Common/Cpp/PanicDump.h index 886cf1a47f..0007f8c410 100644 --- a/Common/Cpp/PanicDump.h +++ b/Common/Cpp/PanicDump.h @@ -1,22 +1,22 @@ -/* Panic Dumping - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanicDumping_H -#define PokemonAutomation_PanicDumping_H - -#include - -namespace PokemonAutomation{ - - -void panic_dump(const char* location, const char* message); - -void run_with_catch(const char* location, std::function&& lambda); - - -} -#endif - +/* Panic Dumping + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanicDumping_H +#define PokemonAutomation_PanicDumping_H + +#include + +namespace PokemonAutomation{ + + +void panic_dump(const char* location, const char* message); + +void run_with_catch(const char* location, std::function&& lambda); + + +} +#endif + diff --git a/Common/Cpp/PixelRGB32.h b/Common/Cpp/PixelRGB32.h index 3a51449895..fb428c2a25 100644 --- a/Common/Cpp/PixelRGB32.h +++ b/Common/Cpp/PixelRGB32.h @@ -1,51 +1,51 @@ -/* Pixel: RGB32 - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Pixel_RGB32_H -#define PokemonAutomation_Pixel_RGB32_H - -#include - -namespace PokemonAutomation{ - - - - - -union PixelRGB32{ - struct{ - uint8_t blue; - uint8_t green; - uint8_t red; - uint8_t alpha; - } parts; - uint32_t u32; - - PixelRGB32(uint32_t value) - : u32(value) - {} - PixelRGB32(uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = 0xff; - parts.red = red; - parts.green = green; - parts.blue = blue; - } - PixelRGB32(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = alpha; - parts.red = red; - parts.green = green; - parts.blue = blue; - } -}; - - - - - -} -#endif +/* Pixel: RGB32 + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Pixel_RGB32_H +#define PokemonAutomation_Pixel_RGB32_H + +#include + +namespace PokemonAutomation{ + + + + + +union PixelRGB32{ + struct{ + uint8_t blue; + uint8_t green; + uint8_t red; + uint8_t alpha; + } parts; + uint32_t u32; + + PixelRGB32(uint32_t value) + : u32(value) + {} + PixelRGB32(uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = 0xff; + parts.red = red; + parts.green = green; + parts.blue = blue; + } + PixelRGB32(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = alpha; + parts.red = red; + parts.green = green; + parts.blue = blue; + } +}; + + + + + +} +#endif diff --git a/Common/Cpp/PrettyPrint.cpp b/Common/Cpp/PrettyPrint.cpp index 3682499a5e..40948d8940 100644 --- a/Common/Cpp/PrettyPrint.cpp +++ b/Common/Cpp/PrettyPrint.cpp @@ -1,170 +1,170 @@ -/* Pretty Printing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Exceptions.h" -#include "PrettyPrint.h" - -namespace PokemonAutomation{ - - - -std::string tostr_padded(size_t digits, uint64_t x){ - std::string str = std::to_string(x); - if (digits < str.size()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Number is too big to convert to fixed length string."); - } - return std::string(digits - str.size(), '0') + str; -} -std::string tostr_u_commas(int64_t x){ - // Prints out x with comma separators. - - std::string str = std::to_string(x); - std::string out; - - const char* ptr = str.c_str(); - // len: how many digits, don't count "-" in the negative numbers - size_t len = str.size() - (x < 0); - - size_t commas = (len + 2) / 3 - 1; - size_t shift = len - commas * 3 + (x < 0); - - while (true){ - char ch = *ptr++; - if (ch == '\0') - break; - if (shift == 0){ - out += ','; - shift = 3; - } - out += ch; - shift--; - } - - return out; -} -std::string tostr_default(double x){ - std::ostringstream ss; - ss << x; - return ss.str(); -} -std::string tostr_fixed(double x, int precision){ - std::ostringstream out; - out << std::setprecision(precision); - out << std::fixed; - out << x; - return out.str(); -} - - -std::string now_to_filestring(){ -#if _WIN32 && _MSC_VER -#pragma warning(disable:4996) -#endif - - // Based off of: https://stackoverflow.com/questions/15957805/extract-year-month-day-etc-from-stdchronotime-point-in-c - - using namespace std; - using namespace std::chrono; - typedef duration >::type> days; - system_clock::time_point now = system_clock::now(); - system_clock::duration tp = now.time_since_epoch(); - days d = duration_cast(tp); - tp -= d; - hours h = duration_cast(tp); - tp -= h; - minutes m = duration_cast(tp); - tp -= m; - seconds s = duration_cast(tp); - tp -= s; - auto micros = 1000000 * tp.count() * system_clock::duration::period::num / system_clock::duration::period::den; - time_t tt = system_clock::to_time_t(now); -// tm utc_tm = *gmtime(&tt); - tm local_tm = *localtime(&tt); - - std::stringstream ss; - ss << local_tm.tm_year + 1900; - ss << tostr_padded(2, local_tm.tm_mon + 1); - ss << tostr_padded(2, local_tm.tm_mday) << '-'; - ss << tostr_padded(2, local_tm.tm_hour); - ss << tostr_padded(2, local_tm.tm_min); - ss << tostr_padded(2, local_tm.tm_sec); - ss << tostr_padded(6, micros); - - return ss.str(); -} - -std::string set_to_str(const std::set& set){ - std::string str = "{"; - bool first = true; - for (const std::string& item : set){ - if (!first){ - str += ", "; - } - first = false; - str += "\""; - str += item; - str += "\""; - } - str += "}"; - return str; -} - -std::string duration_to_string(std::chrono::milliseconds milliseconds){ - const uint64_t SECOND = 1000; - const uint64_t MINUTE = SECOND * 60; - const uint64_t HOUR = MINUTE * 60; - const uint64_t DAY = HOUR * 24; - const uint64_t WEEK = DAY * 7; - const uint64_t YEARS = std::chrono::duration_cast(std::chrono::years(1)).count(); - const uint64_t MILLION_YEARS = YEARS * 1000000; - - uint64_t ticks = milliseconds.count(); - - std::string str; - if (ticks < MINUTE * 2){ - str += tostr_fixed((double)ticks / SECOND, 3); - str += " seconds"; - }else if (ticks < HOUR * 2){ - str += tostr_fixed((double)ticks / MINUTE, 3); - str += " minutes"; - }else if (ticks < DAY * 2){ - str += tostr_fixed((double)ticks / HOUR, 3); - str += " hours"; - }else if (ticks < WEEK * 2){ - str += tostr_fixed((double)ticks / DAY, 3); - str += " days"; - }else if (ticks < YEARS * 2){ - str += tostr_fixed((double)ticks / WEEK, 3); - str += " weeks"; - }else if (ticks < MILLION_YEARS){ - str += tostr_fixed((double)ticks / YEARS, 3); - str += " years"; - }else{ - str += tostr_fixed((double)ticks / MILLION_YEARS, 3); - str += " million years"; - } - return str; -} - - -// After C++20 format or fmt::format is adopted, we can use: -// std::format("{:x}", value)); -std::string tostr_hex(uint64_t x){ - std::ostringstream ss; - ss << std::hex << x; - return ss.str(); -} - - - - - - -} +/* Pretty Printing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Exceptions.h" +#include "PrettyPrint.h" + +namespace PokemonAutomation{ + + + +std::string tostr_padded(size_t digits, uint64_t x){ + std::string str = std::to_string(x); + if (digits < str.size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Number is too big to convert to fixed length string."); + } + return std::string(digits - str.size(), '0') + str; +} +std::string tostr_u_commas(int64_t x){ + // Prints out x with comma separators. + + std::string str = std::to_string(x); + std::string out; + + const char* ptr = str.c_str(); + // len: how many digits, don't count "-" in the negative numbers + size_t len = str.size() - (x < 0); + + size_t commas = (len + 2) / 3 - 1; + size_t shift = len - commas * 3 + (x < 0); + + while (true){ + char ch = *ptr++; + if (ch == '\0') + break; + if (shift == 0){ + out += ','; + shift = 3; + } + out += ch; + shift--; + } + + return out; +} +std::string tostr_default(double x){ + std::ostringstream ss; + ss << x; + return ss.str(); +} +std::string tostr_fixed(double x, int precision){ + std::ostringstream out; + out << std::setprecision(precision); + out << std::fixed; + out << x; + return out.str(); +} + + +std::string now_to_filestring(){ +#if _WIN32 && _MSC_VER +#pragma warning(disable:4996) +#endif + + // Based off of: https://stackoverflow.com/questions/15957805/extract-year-month-day-etc-from-stdchronotime-point-in-c + + using namespace std; + using namespace std::chrono; + typedef duration >::type> days; + system_clock::time_point now = system_clock::now(); + system_clock::duration tp = now.time_since_epoch(); + days d = duration_cast(tp); + tp -= d; + hours h = duration_cast(tp); + tp -= h; + minutes m = duration_cast(tp); + tp -= m; + seconds s = duration_cast(tp); + tp -= s; + auto micros = 1000000 * tp.count() * system_clock::duration::period::num / system_clock::duration::period::den; + time_t tt = system_clock::to_time_t(now); +// tm utc_tm = *gmtime(&tt); + tm local_tm = *localtime(&tt); + + std::stringstream ss; + ss << local_tm.tm_year + 1900; + ss << tostr_padded(2, local_tm.tm_mon + 1); + ss << tostr_padded(2, local_tm.tm_mday) << '-'; + ss << tostr_padded(2, local_tm.tm_hour); + ss << tostr_padded(2, local_tm.tm_min); + ss << tostr_padded(2, local_tm.tm_sec); + ss << tostr_padded(6, micros); + + return ss.str(); +} + +std::string set_to_str(const std::set& set){ + std::string str = "{"; + bool first = true; + for (const std::string& item : set){ + if (!first){ + str += ", "; + } + first = false; + str += "\""; + str += item; + str += "\""; + } + str += "}"; + return str; +} + +std::string duration_to_string(std::chrono::milliseconds milliseconds){ + const uint64_t SECOND = 1000; + const uint64_t MINUTE = SECOND * 60; + const uint64_t HOUR = MINUTE * 60; + const uint64_t DAY = HOUR * 24; + const uint64_t WEEK = DAY * 7; + const uint64_t YEARS = std::chrono::duration_cast(std::chrono::years(1)).count(); + const uint64_t MILLION_YEARS = YEARS * 1000000; + + uint64_t ticks = milliseconds.count(); + + std::string str; + if (ticks < MINUTE * 2){ + str += tostr_fixed((double)ticks / SECOND, 3); + str += " seconds"; + }else if (ticks < HOUR * 2){ + str += tostr_fixed((double)ticks / MINUTE, 3); + str += " minutes"; + }else if (ticks < DAY * 2){ + str += tostr_fixed((double)ticks / HOUR, 3); + str += " hours"; + }else if (ticks < WEEK * 2){ + str += tostr_fixed((double)ticks / DAY, 3); + str += " days"; + }else if (ticks < YEARS * 2){ + str += tostr_fixed((double)ticks / WEEK, 3); + str += " weeks"; + }else if (ticks < MILLION_YEARS){ + str += tostr_fixed((double)ticks / YEARS, 3); + str += " years"; + }else{ + str += tostr_fixed((double)ticks / MILLION_YEARS, 3); + str += " million years"; + } + return str; +} + + +// After C++20 format or fmt::format is adopted, we can use: +// std::format("{:x}", value)); +std::string tostr_hex(uint64_t x){ + std::ostringstream ss; + ss << std::hex << x; + return ss.str(); +} + + + + + + +} diff --git a/Common/Cpp/PrettyPrint.h b/Common/Cpp/PrettyPrint.h index 970029593d..0be493a595 100644 --- a/Common/Cpp/PrettyPrint.h +++ b/Common/Cpp/PrettyPrint.h @@ -1,34 +1,34 @@ -/* Pretty Printing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PrettyPrint_H -#define PokemonAutomation_PrettyPrint_H - -#include -#include -#include - -namespace PokemonAutomation{ - -std::string tostr_padded(size_t digits, uint64_t x); -std::string tostr_u_commas(int64_t x); - -std::string tostr_default(double x); -std::string tostr_fixed(double x, int precision); - -// Format current time to a string to be used as filenames. -// e.g. "20220320-044444408355" -std::string now_to_filestring(); - -std::string set_to_str(const std::set& set); - -std::string duration_to_string(std::chrono::milliseconds milliseconds); - -std::string tostr_hex(uint64_t x); - -} -#endif - +/* Pretty Printing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PrettyPrint_H +#define PokemonAutomation_PrettyPrint_H + +#include +#include +#include + +namespace PokemonAutomation{ + +std::string tostr_padded(size_t digits, uint64_t x); +std::string tostr_u_commas(int64_t x); + +std::string tostr_default(double x); +std::string tostr_fixed(double x, int precision); + +// Format current time to a string to be used as filenames. +// e.g. "20220320-044444408355" +std::string now_to_filestring(); + +std::string set_to_str(const std::set& set); + +std::string duration_to_string(std::chrono::milliseconds milliseconds); + +std::string tostr_hex(uint64_t x); + +} +#endif + diff --git a/Common/Cpp/PrintDebuggers.h b/Common/Cpp/PrintDebuggers.h index 02734070f4..d1319055d4 100644 --- a/Common/Cpp/PrintDebuggers.h +++ b/Common/Cpp/PrintDebuggers.h @@ -1,69 +1,69 @@ -/* Print Debuggers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PrintDebuggers_H -#define PokemonAutomation_PrintDebuggers_H - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -template -void print_array(const Type* ptr, size_t len){ - cout << "{"; - bool first = true; - for (size_t c = 0; c < len; c++){ - if (!first){ - cout << ", "; - } - first = false; - cout << ptr[c]; - } - cout << "}" << endl; -} -inline void print_u8(const uint8_t* ptr, size_t len){ - cout << "{"; - bool first = true; - for (size_t c = 0; c < len; c++){ - if (!first){ - cout << ", "; - } - first = false; - cout << (unsigned)ptr[c]; - } - cout << "}" << endl; -} - -void print_bits(uint64_t m){ - for (int i = 0; i < 8; i++){ - for (int j = 0; j < 8; j++){ - cout << (m & 1); - m >>= 1; - } - cout << endl; - } - cout << endl; -} -void print_8x8(uint64_t m){ - for (int i = 0; i < 8; i++){ - for (int j = 0; j < 8; j++){ - cout << (m & 1); - m >>= 1; - } - cout << " "; - } - cout << endl; -} - - - - - -} -#endif +/* Print Debuggers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PrintDebuggers_H +#define PokemonAutomation_PrintDebuggers_H + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +template +void print_array(const Type* ptr, size_t len){ + cout << "{"; + bool first = true; + for (size_t c = 0; c < len; c++){ + if (!first){ + cout << ", "; + } + first = false; + cout << ptr[c]; + } + cout << "}" << endl; +} +inline void print_u8(const uint8_t* ptr, size_t len){ + cout << "{"; + bool first = true; + for (size_t c = 0; c < len; c++){ + if (!first){ + cout << ", "; + } + first = false; + cout << (unsigned)ptr[c]; + } + cout << "}" << endl; +} + +void print_bits(uint64_t m){ + for (int i = 0; i < 8; i++){ + for (int j = 0; j < 8; j++){ + cout << (m & 1); + m >>= 1; + } + cout << endl; + } + cout << endl; +} +void print_8x8(uint64_t m){ + for (int i = 0; i < 8; i++){ + for (int j = 0; j < 8; j++){ + cout << (m & 1); + m >>= 1; + } + cout << " "; + } + cout << endl; +} + + + + + +} +#endif diff --git a/Common/Cpp/Rectangle.h b/Common/Cpp/Rectangle.h index 86621b1e6a..8cfcfb4604 100644 --- a/Common/Cpp/Rectangle.h +++ b/Common/Cpp/Rectangle.h @@ -1,82 +1,82 @@ -/* Rectangle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Rectangle_H -#define PokemonAutomation_Rectangle_H - -namespace PokemonAutomation{ - - -template -struct Rectangle{ - // min is the start of the box. - // max is the end of the box. - // max - min is the width or height of the box. - Type min_x; - Type min_y; - Type max_x; - Type max_y; - - Rectangle() = default; - Rectangle(Type p_min_x, Type p_min_y, Type p_max_x, Type p_max_y); - - Type width() const{ return max_x - min_x; } - Type height() const{ return max_y - min_y; } - Type area() const{ return width() * height(); } - - bool operator==(const Rectangle& box) const; - - // Return whether two boxes overlap. Boxes touching each other does not count as overlap. - bool overlaps_with(const Rectangle& box) const; - Type overlapping_area(const Rectangle& box) const; - - // Create a box covering both `this` box and the parameter `box` passed in. - // If the parameter `box` has 0 area, do no change. - // If `this` box has 0 area, `this` becomes the parameter `box`. - void merge_with(const Rectangle& box); - - // Whether a point (x, y) is inside the box. - bool is_inside(Type x, Type y) const; // Excludes border. - bool is_inside_or_on(Type x, Type y) const; // Includes border. - - // Whether this box completely encloses "box". - bool encloses(const Rectangle& box) const; // Includes border. - -}; - - -// -// Implementations -// - -template -bool Rectangle::operator==(const Rectangle& box) const{ - return - min_x == box.min_x && min_y == box.min_y && - max_x == box.max_x && max_y == box.max_y; -} -template -bool Rectangle::overlaps_with(const Rectangle& box) const{ - return !(box.min_x >= max_x || box.max_x <= min_x || box.min_y >= max_y || box.max_y <= min_y); -} -template -bool Rectangle::is_inside(Type x, Type y) const{ - return x > min_x && x < max_x && y > min_y && y < max_y; -} -template -bool Rectangle::is_inside_or_on(Type x, Type y) const{ - return x >= min_x && x <= max_x && y >= min_y && y <= max_y; -} -template -bool Rectangle::encloses(const Rectangle& box) const{ - return min_x <= box.min_x && box.max_x <= max_x && min_y <= box.min_y && box.max_y <= max_y; -} - - - - -} -#endif +/* Rectangle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Rectangle_H +#define PokemonAutomation_Rectangle_H + +namespace PokemonAutomation{ + + +template +struct Rectangle{ + // min is the start of the box. + // max is the end of the box. + // max - min is the width or height of the box. + Type min_x; + Type min_y; + Type max_x; + Type max_y; + + Rectangle() = default; + Rectangle(Type p_min_x, Type p_min_y, Type p_max_x, Type p_max_y); + + Type width() const{ return max_x - min_x; } + Type height() const{ return max_y - min_y; } + Type area() const{ return width() * height(); } + + bool operator==(const Rectangle& box) const; + + // Return whether two boxes overlap. Boxes touching each other does not count as overlap. + bool overlaps_with(const Rectangle& box) const; + Type overlapping_area(const Rectangle& box) const; + + // Create a box covering both `this` box and the parameter `box` passed in. + // If the parameter `box` has 0 area, do no change. + // If `this` box has 0 area, `this` becomes the parameter `box`. + void merge_with(const Rectangle& box); + + // Whether a point (x, y) is inside the box. + bool is_inside(Type x, Type y) const; // Excludes border. + bool is_inside_or_on(Type x, Type y) const; // Includes border. + + // Whether this box completely encloses "box". + bool encloses(const Rectangle& box) const; // Includes border. + +}; + + +// +// Implementations +// + +template +bool Rectangle::operator==(const Rectangle& box) const{ + return + min_x == box.min_x && min_y == box.min_y && + max_x == box.max_x && max_y == box.max_y; +} +template +bool Rectangle::overlaps_with(const Rectangle& box) const{ + return !(box.min_x >= max_x || box.max_x <= min_x || box.min_y >= max_y || box.max_y <= min_y); +} +template +bool Rectangle::is_inside(Type x, Type y) const{ + return x > min_x && x < max_x && y > min_y && y < max_y; +} +template +bool Rectangle::is_inside_or_on(Type x, Type y) const{ + return x >= min_x && x <= max_x && y >= min_y && y <= max_y; +} +template +bool Rectangle::encloses(const Rectangle& box) const{ + return min_x <= box.min_x && box.max_x <= max_x && min_y <= box.min_y && box.max_y <= max_y; +} + + + + +} +#endif diff --git a/Common/Cpp/Rectangle.tpp b/Common/Cpp/Rectangle.tpp index f897bbb65b..529a12a612 100644 --- a/Common/Cpp/Rectangle.tpp +++ b/Common/Cpp/Rectangle.tpp @@ -1,65 +1,65 @@ -/* Rectangle - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_Rectangle_TPP -#define PokemonAutomation_Rectangle_TPP - -#include -#include "Common/Cpp/Exceptions.h" -#include "Rectangle.h" - -namespace PokemonAutomation{ - - -template -Rectangle::Rectangle(Type p_min_x, Type p_min_y, Type p_max_x, Type p_max_y) - : min_x(p_min_x) , min_y(p_min_y) , max_x(p_max_x) , max_y(p_max_y) -{ - if (min_x > max_x){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Box: min_x = " + std::to_string(min_x) + ", max_x = " + std::to_string(max_x) - ); - } - if (min_y > max_y){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Box: min_y = " + std::to_string(min_y) + ", max_y = " + std::to_string(max_y) - ); - } -} -template -void Rectangle::merge_with(const Rectangle& box){ - if (box.area() == 0){ - return; - } - if (this->area() == 0){ - *this = box; - } - min_x = std::min(min_x, box.min_x); - min_y = std::min(min_y, box.min_y); - max_x = std::max(max_x, box.max_x); - max_y = std::max(max_y, box.max_y); -} -template -Type Rectangle::overlapping_area(const Rectangle& box) const{ - Type min_x = std::max(this->min_x, box.min_x); - Type max_x = std::min(this->max_x, box.max_x); - if (min_x >= max_x){ - return 0; - } - Type min_y = std::max(this->min_y, box.min_y); - Type max_y = std::min(this->max_y, box.max_y); - if (min_y >= max_y){ - return 0; - } - return (max_x - min_x) * (max_y - min_y); -} - - - -} -#endif +/* Rectangle + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_Rectangle_TPP +#define PokemonAutomation_Rectangle_TPP + +#include +#include "Common/Cpp/Exceptions.h" +#include "Rectangle.h" + +namespace PokemonAutomation{ + + +template +Rectangle::Rectangle(Type p_min_x, Type p_min_y, Type p_max_x, Type p_max_y) + : min_x(p_min_x) , min_y(p_min_y) , max_x(p_max_x) , max_y(p_max_y) +{ + if (min_x > max_x){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Box: min_x = " + std::to_string(min_x) + ", max_x = " + std::to_string(max_x) + ); + } + if (min_y > max_y){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Box: min_y = " + std::to_string(min_y) + ", max_y = " + std::to_string(max_y) + ); + } +} +template +void Rectangle::merge_with(const Rectangle& box){ + if (box.area() == 0){ + return; + } + if (this->area() == 0){ + *this = box; + } + min_x = std::min(min_x, box.min_x); + min_y = std::min(min_y, box.min_y); + max_x = std::max(max_x, box.max_x); + max_y = std::max(max_y, box.max_y); +} +template +Type Rectangle::overlapping_area(const Rectangle& box) const{ + Type min_x = std::max(this->min_x, box.min_x); + Type max_x = std::min(this->max_x, box.max_x); + if (min_x >= max_x){ + return 0; + } + Type min_y = std::max(this->min_y, box.min_y); + Type max_y = std::min(this->max_y, box.max_y); + if (min_y >= max_y){ + return 0; + } + return (max_x - min_x) * (max_y - min_y); +} + + + +} +#endif diff --git a/Common/Cpp/RecursiveThrottler.h b/Common/Cpp/RecursiveThrottler.h index 4fb4aec6bf..2b833ef8fd 100644 --- a/Common/Cpp/RecursiveThrottler.h +++ b/Common/Cpp/RecursiveThrottler.h @@ -1,56 +1,56 @@ -/* Recursive Throttler - * - * From: https://github.com/PokemonAutomation/ - * - * Used to suppress recursive logging. - * Log only at the top level. And limit to 1 thread at a time. - * - */ - -#ifndef PokemonAutomation_RecursiveThrottler_H -#define PokemonAutomation_RecursiveThrottler_H - -#include - -namespace PokemonAutomation{ - -class RecursiveThrottler{ -public: - // Returns true if ok to run. (not throttled) - operator bool() const{ - std::lock_guard lg(m_lock); - return m_depth == 0; - } - -private: - friend class ThrottleScope; - mutable std::recursive_mutex m_lock; - size_t m_depth = 0; -}; - -class ThrottleScope{ - ThrottleScope(const ThrottleScope&) = delete; - void operator=(const ThrottleScope&) = delete; -public: - ThrottleScope(RecursiveThrottler& throttler) - : m_throttler(throttler) - , m_guard(throttler.m_lock) - { - throttler.m_depth++; - } - ~ThrottleScope(){ - m_throttler.m_depth--; - } - - // Returns true if ok to run. (not throttled) - operator bool() const{ - return m_throttler.m_depth == 1; - } - -private: - RecursiveThrottler& m_throttler; - std::lock_guard m_guard; -}; - -} -#endif +/* Recursive Throttler + * + * From: https://github.com/PokemonAutomation/ + * + * Used to suppress recursive logging. + * Log only at the top level. And limit to 1 thread at a time. + * + */ + +#ifndef PokemonAutomation_RecursiveThrottler_H +#define PokemonAutomation_RecursiveThrottler_H + +#include + +namespace PokemonAutomation{ + +class RecursiveThrottler{ +public: + // Returns true if ok to run. (not throttled) + operator bool() const{ + std::lock_guard lg(m_lock); + return m_depth == 0; + } + +private: + friend class ThrottleScope; + mutable std::recursive_mutex m_lock; + size_t m_depth = 0; +}; + +class ThrottleScope{ + ThrottleScope(const ThrottleScope&) = delete; + void operator=(const ThrottleScope&) = delete; +public: + ThrottleScope(RecursiveThrottler& throttler) + : m_throttler(throttler) + , m_guard(throttler.m_lock) + { + throttler.m_depth++; + } + ~ThrottleScope(){ + m_throttler.m_depth--; + } + + // Returns true if ok to run. (not throttled) + operator bool() const{ + return m_throttler.m_depth == 1; + } + +private: + RecursiveThrottler& m_throttler; + std::lock_guard m_guard; +}; + +} +#endif diff --git a/Common/Cpp/SIMDDebuggers.h b/Common/Cpp/SIMDDebuggers.h index a1e1d06a9a..df75da7290 100644 --- a/Common/Cpp/SIMDDebuggers.h +++ b/Common/Cpp/SIMDDebuggers.h @@ -1,53 +1,53 @@ -/* SIMD Debuggers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SIMDDebuggers_H -#define PokemonAutomation_SIMDDebuggers_H - -#include -#include - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -inline void print8(__m128i x){ - union{ - __m128i v; - uint8_t s[16]; - }; - v = x; - bool first = true; - for (int c = 0; c < 16; c++){ - if (!first){ - cout << " "; - } - first = false; - cout << (unsigned)s[c]; - } -} -inline void print16(__m128i x){ - union{ - __m128i v; - uint16_t s[8]; - }; - v = x; - cout << s[0] << " " << s[1] << " " << s[2] << " " << s[3] << " " << s[4] << " " << s[5] << " " << s[6] << " " << s[7]; -} -inline void print32(__m128i x){ - union{ - __m128i v; - uint32_t s[4]; - }; - v = x; - cout << s[0] << " " << s[1] << " " << s[2] << " " << s[3]; -} - - -} -#endif +/* SIMD Debuggers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SIMDDebuggers_H +#define PokemonAutomation_SIMDDebuggers_H + +#include +#include + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +inline void print8(__m128i x){ + union{ + __m128i v; + uint8_t s[16]; + }; + v = x; + bool first = true; + for (int c = 0; c < 16; c++){ + if (!first){ + cout << " "; + } + first = false; + cout << (unsigned)s[c]; + } +} +inline void print16(__m128i x){ + union{ + __m128i v; + uint16_t s[8]; + }; + v = x; + cout << s[0] << " " << s[1] << " " << s[2] << " " << s[3] << " " << s[4] << " " << s[5] << " " << s[6] << " " << s[7]; +} +inline void print32(__m128i x){ + union{ + __m128i v; + uint32_t s[4]; + }; + v = x; + cout << s[0] << " " << s[1] << " " << s[2] << " " << s[3]; +} + + +} +#endif diff --git a/Common/Cpp/Sockets/AbstractClientSocket.h b/Common/Cpp/Sockets/AbstractClientSocket.h index f1c5a1c8be..d0bce4b086 100644 --- a/Common/Cpp/Sockets/AbstractClientSocket.h +++ b/Common/Cpp/Sockets/AbstractClientSocket.h @@ -1,75 +1,75 @@ -/* Abstract Client Socket - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Sockets_AbstractClientSocket_H -#define PokemonAutomation_Sockets_AbstractClientSocket_H - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/ListenerSet.h" - -namespace PokemonAutomation{ - - - -class AbstractClientSocket{ -public: - enum class State{ - NOT_RUNNING, - CONNECTING, - CONNECTED, - DESTRUCTING, - }; - - struct Listener{ - // Called at the start of the receiver thread. This can be used to set - // the thread priority of the thread. - virtual void on_thread_start(){} - - // Called when a connection attempt finishes. - // If successful, "error_message" is empty. - // Otherwise, it contains the error message. - virtual void on_connect_finished(const std::string& error_message){} - - // Called when the socket receives data from the server. - virtual void on_receive_data(const void* data, size_t bytes){} - }; - - void add_listener(Listener& listener){ - m_listeners.add(listener); - } - void remove_listener(Listener& listener){ - m_listeners.add(listener); - } - - -public: - AbstractClientSocket() - : m_state(State::NOT_RUNNING) - {} - virtual ~AbstractClientSocket() = default; - - State state() const{ - return m_state.load(std::memory_order_relaxed); - } - - virtual void close() noexcept = 0; - virtual void connect(const std::string& address, uint16_t port) = 0; - - virtual size_t blocking_send(const void* data, size_t bytes) = 0; - - -protected: - std::atomic m_state; - ListenerSet m_listeners; -}; - - - - - -} -#endif +/* Abstract Client Socket + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Sockets_AbstractClientSocket_H +#define PokemonAutomation_Sockets_AbstractClientSocket_H + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/ListenerSet.h" + +namespace PokemonAutomation{ + + + +class AbstractClientSocket{ +public: + enum class State{ + NOT_RUNNING, + CONNECTING, + CONNECTED, + DESTRUCTING, + }; + + struct Listener{ + // Called at the start of the receiver thread. This can be used to set + // the thread priority of the thread. + virtual void on_thread_start(){} + + // Called when a connection attempt finishes. + // If successful, "error_message" is empty. + // Otherwise, it contains the error message. + virtual void on_connect_finished(const std::string& error_message){} + + // Called when the socket receives data from the server. + virtual void on_receive_data(const void* data, size_t bytes){} + }; + + void add_listener(Listener& listener){ + m_listeners.add(listener); + } + void remove_listener(Listener& listener){ + m_listeners.add(listener); + } + + +public: + AbstractClientSocket() + : m_state(State::NOT_RUNNING) + {} + virtual ~AbstractClientSocket() = default; + + State state() const{ + return m_state.load(std::memory_order_relaxed); + } + + virtual void close() noexcept = 0; + virtual void connect(const std::string& address, uint16_t port) = 0; + + virtual size_t blocking_send(const void* data, size_t bytes) = 0; + + +protected: + std::atomic m_state; + ListenerSet m_listeners; +}; + + + + + +} +#endif diff --git a/Common/Cpp/Sockets/ClientSocket.cpp b/Common/Cpp/Sockets/ClientSocket.cpp index 66d38393e0..10183d77b9 100644 --- a/Common/Cpp/Sockets/ClientSocket.cpp +++ b/Common/Cpp/Sockets/ClientSocket.cpp @@ -1,14 +1,14 @@ -/* Client Socket - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSocket.h" - -namespace PokemonAutomation{ - - - - -} +/* Client Socket + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSocket.h" + +namespace PokemonAutomation{ + + + + +} diff --git a/Common/Cpp/Sockets/ClientSocket.h b/Common/Cpp/Sockets/ClientSocket.h index f08086a8e1..61d38b7784 100644 --- a/Common/Cpp/Sockets/ClientSocket.h +++ b/Common/Cpp/Sockets/ClientSocket.h @@ -1,26 +1,26 @@ -/* Client Socket - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ClientSocket_H -#define PokemonAutomation_ClientSocket_H - - - -#ifdef _WIN32 -#include "ClientSocket_WinSocket.h" -namespace PokemonAutomation{ - using ClientSocket = ClientSocket_WinSocket; -} -#else -#include "ClientSocket_POSIX.h" -namespace PokemonAutomation{ - using ClientSocket = ClientSocket_POSIX; -} -#endif - - - -#endif +/* Client Socket + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ClientSocket_H +#define PokemonAutomation_ClientSocket_H + + + +#ifdef _WIN32 +#include "ClientSocket_WinSocket.h" +namespace PokemonAutomation{ + using ClientSocket = ClientSocket_WinSocket; +} +#else +#include "ClientSocket_POSIX.h" +namespace PokemonAutomation{ + using ClientSocket = ClientSocket_POSIX; +} +#endif + + + +#endif diff --git a/Common/Cpp/Sockets/ClientSocket_POSIX.h b/Common/Cpp/Sockets/ClientSocket_POSIX.h index 02a72163b3..135082ab1f 100644 --- a/Common/Cpp/Sockets/ClientSocket_POSIX.h +++ b/Common/Cpp/Sockets/ClientSocket_POSIX.h @@ -1,241 +1,241 @@ -/* Client Socket (POSIX) - * - * From: https://github.com/PokemonAutomation/ - * - * This file is completely untested! - * - */ - -#ifndef PokemonAutomation_ClientSocket_POSIX_H -#define PokemonAutomation_ClientSocket_POSIX_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "AbstractClientSocket.h" - -namespace PokemonAutomation{ - - - -class ClientSocket_POSIX final : public AbstractClientSocket{ -public: - ClientSocket_POSIX() - : m_socket(socket(AF_INET, SOCK_STREAM, 0)) - { - fcntl(m_socket, F_SETFL, O_NONBLOCK); - } - - virtual ~ClientSocket_POSIX(){ - close(); - if (m_thread.joinable()){ - m_thread.join(); - } - if (m_socket != -1){ - ::close(m_socket); - } - } - virtual void close() noexcept override{ - { - std::lock_guard lg1(m_lock); - m_state.store(State::DESTRUCTING, std::memory_order_relaxed); - m_cv.notify_all(); - } - } - - virtual void connect(const std::string& address, uint16_t port) override{ - std::lock_guard lg1(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ - return; - } - try{ - m_state.store(State::CONNECTING, std::memory_order_relaxed); - m_thread = std::thread( - &ClientSocket_POSIX::thread_loop, - this, address, port - ); - }catch (...){ - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - throw; - } - } - - - virtual size_t blocking_send(const void* data, size_t bytes) override{ - if (m_socket == -1){ - return 0; - } - - constexpr int BLOCK_SIZE = (int)1 << 30; - const char* ptr = (const char*)data; - size_t sent = 0; - - while (bytes > 0){ - size_t current = std::min(bytes, BLOCK_SIZE); - ssize_t current_sent = ::send(m_socket, ptr, (int)current, MSG_DONTWAIT); - if (current_sent != -1){ - sent += current; - if ((size_t)current_sent < current){ - return sent; - } - ptr += current; - bytes -= current; - continue; - } - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - break; - } - - int error = errno; -// cout << "error = " << error << endl; - switch (error){ - case EAGAIN: -// case EWOULDBLOCK: - break; - default: - m_error = "POSIX Error Code: " + std::to_string(error); - return sent; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - return sent; - } - - -private: - void thread_loop(const std::string& address, uint16_t port){ - try{ - thread_loop_internal(address, port); - }catch (...){ - try{ - std::cout << "ClientSocket_POSIX(): An exception was thrown from the receive thread." << std::endl; - }catch (...){} - } - } - - void thread_loop_internal(const std::string& address, uint16_t port){ - m_listeners.run_method_unique(&Listener::on_thread_start); - - { - std::unique_lock lg(m_lock); - - sockaddr_in server; - server.sin_family = AF_INET; - server.sin_port = htons(port); - server.sin_addr.s_addr = inet_addr(address.c_str()); - - // Connect - while (true){ - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - - if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != -1){ - break; - } - - int error = errno; -// cout << "error = " << error << endl; - - switch (error){ - case EISCONN: - goto Connected; - case EAGAIN: - case EALREADY: - case EINPROGRESS: - break; - case ETIMEDOUT: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "Connection timed out."; - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - default: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "WSA Error Code: " + std::to_string(error); - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(10)); - - } - -Connected: - m_state.store(State::CONNECTED, std::memory_order_relaxed); - } - - m_listeners.run_method_unique(&Listener::on_connect_finished, ""); - - - constexpr size_t BUFFER_SIZE = 4096; - char buffer[BUFFER_SIZE]; - - while (true){ - ssize_t bytes; - int error = 0; - { - std::unique_lock lg(m_lock); - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); - if (bytes < 0){ - error = errno; - } - } - - if (bytes > 0){ - m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); - continue; - } - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - return; - } - - if (bytes < 0){ -// cout << "error = " << error << endl; - switch (error){ - case EAGAIN: -// case EWOULDBLOCK: - break; - default: - std::unique_lock lg(m_lock); - m_error = "POSIX Error Code: " + std::to_string(error); - return; - } - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - - } - - -private: - const int m_socket; - - std::string m_error; - - mutable std::mutex m_lock; - std::condition_variable m_cv; - std::thread m_thread; -}; - - -} -#endif +/* Client Socket (POSIX) + * + * From: https://github.com/PokemonAutomation/ + * + * This file is completely untested! + * + */ + +#ifndef PokemonAutomation_ClientSocket_POSIX_H +#define PokemonAutomation_ClientSocket_POSIX_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "AbstractClientSocket.h" + +namespace PokemonAutomation{ + + + +class ClientSocket_POSIX final : public AbstractClientSocket{ +public: + ClientSocket_POSIX() + : m_socket(socket(AF_INET, SOCK_STREAM, 0)) + { + fcntl(m_socket, F_SETFL, O_NONBLOCK); + } + + virtual ~ClientSocket_POSIX(){ + close(); + if (m_thread.joinable()){ + m_thread.join(); + } + if (m_socket != -1){ + ::close(m_socket); + } + } + virtual void close() noexcept override{ + { + std::lock_guard lg1(m_lock); + m_state.store(State::DESTRUCTING, std::memory_order_relaxed); + m_cv.notify_all(); + } + } + + virtual void connect(const std::string& address, uint16_t port) override{ + std::lock_guard lg1(m_lock); + if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ + return; + } + try{ + m_state.store(State::CONNECTING, std::memory_order_relaxed); + m_thread = std::thread( + &ClientSocket_POSIX::thread_loop, + this, address, port + ); + }catch (...){ + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + throw; + } + } + + + virtual size_t blocking_send(const void* data, size_t bytes) override{ + if (m_socket == -1){ + return 0; + } + + constexpr int BLOCK_SIZE = (int)1 << 30; + const char* ptr = (const char*)data; + size_t sent = 0; + + while (bytes > 0){ + size_t current = std::min(bytes, BLOCK_SIZE); + ssize_t current_sent = ::send(m_socket, ptr, (int)current, MSG_DONTWAIT); + if (current_sent != -1){ + sent += current; + if ((size_t)current_sent < current){ + return sent; + } + ptr += current; + bytes -= current; + continue; + } + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + break; + } + + int error = errno; +// cout << "error = " << error << endl; + switch (error){ + case EAGAIN: +// case EWOULDBLOCK: + break; + default: + m_error = "POSIX Error Code: " + std::to_string(error); + return sent; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + return sent; + } + + +private: + void thread_loop(const std::string& address, uint16_t port){ + try{ + thread_loop_internal(address, port); + }catch (...){ + try{ + std::cout << "ClientSocket_POSIX(): An exception was thrown from the receive thread." << std::endl; + }catch (...){} + } + } + + void thread_loop_internal(const std::string& address, uint16_t port){ + m_listeners.run_method_unique(&Listener::on_thread_start); + + { + std::unique_lock lg(m_lock); + + sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = inet_addr(address.c_str()); + + // Connect + while (true){ + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + + if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != -1){ + break; + } + + int error = errno; +// cout << "error = " << error << endl; + + switch (error){ + case EISCONN: + goto Connected; + case EAGAIN: + case EALREADY: + case EINPROGRESS: + break; + case ETIMEDOUT: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "Connection timed out."; + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + default: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "WSA Error Code: " + std::to_string(error); + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(10)); + + } + +Connected: + m_state.store(State::CONNECTED, std::memory_order_relaxed); + } + + m_listeners.run_method_unique(&Listener::on_connect_finished, ""); + + + constexpr size_t BUFFER_SIZE = 4096; + char buffer[BUFFER_SIZE]; + + while (true){ + ssize_t bytes; + int error = 0; + { + std::unique_lock lg(m_lock); + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); + if (bytes < 0){ + error = errno; + } + } + + if (bytes > 0){ + m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); + continue; + } + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + return; + } + + if (bytes < 0){ +// cout << "error = " << error << endl; + switch (error){ + case EAGAIN: +// case EWOULDBLOCK: + break; + default: + std::unique_lock lg(m_lock); + m_error = "POSIX Error Code: " + std::to_string(error); + return; + } + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + + } + + +private: + const int m_socket; + + std::string m_error; + + mutable std::mutex m_lock; + std::condition_variable m_cv; + std::thread m_thread; +}; + + +} +#endif diff --git a/Common/Cpp/Sockets/ClientSocket_WinSocket.h b/Common/Cpp/Sockets/ClientSocket_WinSocket.h index df42c8c164..026e6795f3 100644 --- a/Common/Cpp/Sockets/ClientSocket_WinSocket.h +++ b/Common/Cpp/Sockets/ClientSocket_WinSocket.h @@ -1,250 +1,250 @@ -/* Client Socket (Windows) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ClientSocket_WinSocket_H -#define PokemonAutomation_ClientSocket_WinSocket_H - -#include -#include -#include -#include -#include -#include "AbstractClientSocket.h" - -#pragma comment(lib, "Ws2_32.lib") - -namespace PokemonAutomation{ - - - -class ClientSocket_WinSocket final : public AbstractClientSocket{ -public: - ClientSocket_WinSocket() - : m_socket(::socket(AF_INET, SOCK_STREAM, 0)) - { - u_long non_blocking = 1; - if (ioctlsocket(m_socket, FIONBIO, &non_blocking)){ -// cout << "ioctlsocket() Failed" << endl; - close_socket(); - return; - } - } - - virtual ~ClientSocket_WinSocket(){ - close(); - if (m_thread.joinable()){ - m_thread.join(); - } - close_socket(); - } - virtual void close() noexcept override{ - { - std::lock_guard lg1(m_lock); - m_state.store(State::DESTRUCTING, std::memory_order_relaxed); - m_cv.notify_all(); - } - } - - virtual void connect(const std::string& address, uint16_t port) override{ - std::lock_guard lg1(m_lock); - if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ - return; - } - try{ - m_state.store(State::CONNECTING, std::memory_order_relaxed); - m_thread = std::thread( - &ClientSocket_WinSocket::thread_loop, - this, address, port - ); - }catch (...){ - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - throw; - } - } - - - virtual size_t blocking_send(const void* data, size_t bytes) override{ - if (m_socket == INVALID_SOCKET){ - return 0; - } - - constexpr int BLOCK_SIZE = (int)1 << 30; - const char* ptr = (const char*)data; - size_t sent = 0; - - while (bytes > 0 && state() == State::CONNECTED){ - size_t current = std::min(bytes, BLOCK_SIZE); - int current_sent = ::send(m_socket, ptr, (int)current, 0); - if (current_sent != SOCKET_ERROR){ - sent += current; - if ((size_t)current_sent < current){ - return sent; - } - ptr += current; - bytes -= current; - continue; - } - - int error = WSAGetLastError(); -// cout << "error = " << error << endl; - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - break; - } - - switch (error){ - case WSAEWOULDBLOCK: - break; - default: - m_error = "WSA Error Code: " + std::to_string(error); - return sent; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - return sent; - } - - -private: - void close_socket(){ - if (m_socket == INVALID_SOCKET){ - return; - } - int ret = closesocket(m_socket); - if (ret == 0){ - return; - } - try{ - std::cout << "Failed closesocket(): WSA Error Code = " + std::to_string(ret) << std::endl; - }catch (...){} - } - - void thread_loop(const std::string& address, uint16_t port){ - try{ - thread_loop_internal(address, port); - }catch (...){ - try{ - std::cout << "ClientSocket_WinSocket(): An exception was thrown from the receive thread." << std::endl; - }catch (...){} - } - } - - void thread_loop_internal(const std::string& address, uint16_t port){ - m_listeners.run_method_unique(&Listener::on_thread_start); - - { - std::unique_lock lg(m_lock); - - sockaddr_in server; - server.sin_family = AF_INET; - server.sin_port = htons(port); - server.sin_addr.s_addr = inet_addr(address.c_str()); - - // Connect - while (true){ - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - - if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != SOCKET_ERROR){ - break; - } - - int error = WSAGetLastError(); -// cout << "error = " << error << endl; - - switch (error){ - case WSAEISCONN: - goto Connected; - case WSAEWOULDBLOCK: - case WSAEINVAL: - break; - case WSAETIMEDOUT: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "Connection timed out."; - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - default: - m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); - m_error = "WSA Error Code: " + std::to_string(error); - m_lock.unlock(); - m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); - return; - } - - m_cv.wait_for(lg, std::chrono::milliseconds(10)); - - } - -Connected: - m_state.store(State::CONNECTED, std::memory_order_relaxed); - } - - m_listeners.run_method_unique(&Listener::on_connect_finished, ""); - - - constexpr size_t BUFFER_SIZE = 4096; - char buffer[BUFFER_SIZE]; - - while (true){ - int bytes; - int error = 0; - { - State state = m_state.load(std::memory_order_relaxed); - if (state == State::DESTRUCTING){ - return; - } - bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); - if (bytes == SOCKET_ERROR){ - error = WSAGetLastError(); - } - } - - if (bytes > 0){ - m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); - continue; - } - - std::unique_lock lg(m_lock); - if (state() == State::DESTRUCTING){ - return; - } - - if (bytes == SOCKET_ERROR){ -// cout << "error = " << error << endl; - switch (error){ - case WSAEWOULDBLOCK: - break; - default: - m_error = "WSA Error Code: " + std::to_string(error); - return; - } - } - - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - - } - - -private: - const SOCKET m_socket; - - std::string m_error; - - mutable std::mutex m_lock; - std::condition_variable m_cv; - std::thread m_thread; -}; - - - -} -#endif +/* Client Socket (Windows) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ClientSocket_WinSocket_H +#define PokemonAutomation_ClientSocket_WinSocket_H + +#include +#include +#include +#include +#include +#include "AbstractClientSocket.h" + +#pragma comment(lib, "Ws2_32.lib") + +namespace PokemonAutomation{ + + + +class ClientSocket_WinSocket final : public AbstractClientSocket{ +public: + ClientSocket_WinSocket() + : m_socket(::socket(AF_INET, SOCK_STREAM, 0)) + { + u_long non_blocking = 1; + if (ioctlsocket(m_socket, FIONBIO, &non_blocking)){ +// cout << "ioctlsocket() Failed" << endl; + close_socket(); + return; + } + } + + virtual ~ClientSocket_WinSocket(){ + close(); + if (m_thread.joinable()){ + m_thread.join(); + } + close_socket(); + } + virtual void close() noexcept override{ + { + std::lock_guard lg1(m_lock); + m_state.store(State::DESTRUCTING, std::memory_order_relaxed); + m_cv.notify_all(); + } + } + + virtual void connect(const std::string& address, uint16_t port) override{ + std::lock_guard lg1(m_lock); + if (m_state.load(std::memory_order_relaxed) != State::NOT_RUNNING){ + return; + } + try{ + m_state.store(State::CONNECTING, std::memory_order_relaxed); + m_thread = std::thread( + &ClientSocket_WinSocket::thread_loop, + this, address, port + ); + }catch (...){ + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + throw; + } + } + + + virtual size_t blocking_send(const void* data, size_t bytes) override{ + if (m_socket == INVALID_SOCKET){ + return 0; + } + + constexpr int BLOCK_SIZE = (int)1 << 30; + const char* ptr = (const char*)data; + size_t sent = 0; + + while (bytes > 0 && state() == State::CONNECTED){ + size_t current = std::min(bytes, BLOCK_SIZE); + int current_sent = ::send(m_socket, ptr, (int)current, 0); + if (current_sent != SOCKET_ERROR){ + sent += current; + if ((size_t)current_sent < current){ + return sent; + } + ptr += current; + bytes -= current; + continue; + } + + int error = WSAGetLastError(); +// cout << "error = " << error << endl; + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + break; + } + + switch (error){ + case WSAEWOULDBLOCK: + break; + default: + m_error = "WSA Error Code: " + std::to_string(error); + return sent; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + return sent; + } + + +private: + void close_socket(){ + if (m_socket == INVALID_SOCKET){ + return; + } + int ret = closesocket(m_socket); + if (ret == 0){ + return; + } + try{ + std::cout << "Failed closesocket(): WSA Error Code = " + std::to_string(ret) << std::endl; + }catch (...){} + } + + void thread_loop(const std::string& address, uint16_t port){ + try{ + thread_loop_internal(address, port); + }catch (...){ + try{ + std::cout << "ClientSocket_WinSocket(): An exception was thrown from the receive thread." << std::endl; + }catch (...){} + } + } + + void thread_loop_internal(const std::string& address, uint16_t port){ + m_listeners.run_method_unique(&Listener::on_thread_start); + + { + std::unique_lock lg(m_lock); + + sockaddr_in server; + server.sin_family = AF_INET; + server.sin_port = htons(port); + server.sin_addr.s_addr = inet_addr(address.c_str()); + + // Connect + while (true){ + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + + if (::connect(m_socket, (struct sockaddr*)&server, sizeof(server)) != SOCKET_ERROR){ + break; + } + + int error = WSAGetLastError(); +// cout << "error = " << error << endl; + + switch (error){ + case WSAEISCONN: + goto Connected; + case WSAEWOULDBLOCK: + case WSAEINVAL: + break; + case WSAETIMEDOUT: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "Connection timed out."; + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + default: + m_state.store(State::NOT_RUNNING, std::memory_order_relaxed); + m_error = "WSA Error Code: " + std::to_string(error); + m_lock.unlock(); + m_listeners.run_method_unique(&Listener::on_connect_finished, m_error); + return; + } + + m_cv.wait_for(lg, std::chrono::milliseconds(10)); + + } + +Connected: + m_state.store(State::CONNECTED, std::memory_order_relaxed); + } + + m_listeners.run_method_unique(&Listener::on_connect_finished, ""); + + + constexpr size_t BUFFER_SIZE = 4096; + char buffer[BUFFER_SIZE]; + + while (true){ + int bytes; + int error = 0; + { + State state = m_state.load(std::memory_order_relaxed); + if (state == State::DESTRUCTING){ + return; + } + bytes = ::recv(m_socket, buffer, BUFFER_SIZE, 0); + if (bytes == SOCKET_ERROR){ + error = WSAGetLastError(); + } + } + + if (bytes > 0){ + m_listeners.run_method_unique(&Listener::on_receive_data, buffer, bytes); + continue; + } + + std::unique_lock lg(m_lock); + if (state() == State::DESTRUCTING){ + return; + } + + if (bytes == SOCKET_ERROR){ +// cout << "error = " << error << endl; + switch (error){ + case WSAEWOULDBLOCK: + break; + default: + m_error = "WSA Error Code: " + std::to_string(error); + return; + } + } + + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + + } + + +private: + const SOCKET m_socket; + + std::string m_error; + + mutable std::mutex m_lock; + std::condition_variable m_cv; + std::thread m_thread; +}; + + + +} +#endif diff --git a/Common/Cpp/StreamConverters.cpp b/Common/Cpp/StreamConverters.cpp index afb963dec7..9f64fe35f8 100644 --- a/Common/Cpp/StreamConverters.cpp +++ b/Common/Cpp/StreamConverters.cpp @@ -1,129 +1,129 @@ -/* Stream Converters - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Exceptions.h" -#include "Containers/AlignedVector.tpp" -#include "StreamConverters.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -StreamConverter::StreamConverter( - size_t object_size_in, - size_t object_size_out, - size_t buffer_capacity -) - : m_object_size_in(object_size_in) - , m_object_size_out(object_size_out) - , m_buffer_capacity(buffer_capacity) - , m_buffer(object_size_out * buffer_capacity) -{} -StreamConverter::~StreamConverter(){} -void StreamConverter::add_listener(StreamListener& listener){ - if (listener.object_size != m_object_size_out){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching object size."); - } - m_listeners.insert(&listener); -} -void StreamConverter::remove_listener(StreamListener& listener){ - m_listeners.erase(&listener); -} -void StreamConverter::push_objects(const void* data, size_t objects){ - while (objects > 0){ - size_t block = std::min(objects, m_buffer_capacity); - convert(m_buffer.data(), data, block); - data = (char*)data + block * m_object_size_in; - objects -= block; - for (StreamListener* listener : m_listeners){ - listener->on_objects(m_buffer.data(), block); - } - } -} - - -//void print_u8(const uint8_t* ptr, size_t len); - - -MisalignedStreamConverter::MisalignedStreamConverter( - size_t object_size_in, - size_t object_size_out, - size_t buffer_capacity -) - : m_object_size_in(object_size_in) - , m_object_size_out(object_size_out) - , m_edge(object_size_in) - , m_buffer_capacity(buffer_capacity) - , m_buffer(object_size_out * buffer_capacity) -{} -MisalignedStreamConverter::~MisalignedStreamConverter(){} -void MisalignedStreamConverter::add_listener(StreamListener& listener){ - if (listener.object_size != m_object_size_out){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching object size."); - } - m_listeners.insert(&listener); -} -void MisalignedStreamConverter::remove_listener(StreamListener& listener){ - m_listeners.erase(&listener); -} -void MisalignedStreamConverter::push_bytes(const void* data, size_t bytes){ -// cout << "push: "; -// print_u8((uint8_t*)data, bytes); - - // Fill the edge block. - if (m_edge_size > 0){ -// cout << "m_edge_size = " << m_edge_size << endl; - size_t block = std::min(m_object_size_in - m_edge_size, bytes); - memcpy(m_edge.data() + m_edge_size, data, block); - m_edge_size += block; - data = (char*)data + block; - bytes -= block; - } - - size_t stored = 0; - - // Process completed edge block. - if (m_edge_size >= m_object_size_in){ -// print_u8((uint8_t*)m_edge.data(), m_edge_size); - convert(m_buffer.data() + stored * m_object_size_out, m_edge.data(), 1); - m_edge_size = 0; - stored++; - } - - size_t objects = bytes / m_object_size_in; - while (stored + objects > 0){ - size_t block = std::min(objects, m_buffer_capacity - stored); -// cout << "stored = " << stored << endl; -// cout << "block = " << block << endl; -// print_u8((uint8_t*)data, block * m_object_size_in); - convert(m_buffer.data() + stored * m_object_size_out, data, block); - data = (char*)data + block * m_object_size_in; - bytes -= block * m_object_size_in; - stored += block; - objects -= block; - for (StreamListener* listener : m_listeners){ - listener->on_objects(m_buffer.data(), stored); - } - stored = 0; - } - -// cout << "left = " << bytes << endl; - - // Copy remaining bytes into edge buffer. - memcpy(m_edge.data(), data, bytes); - m_edge_size = bytes; -} - - - - - - -} +/* Stream Converters + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Exceptions.h" +#include "Containers/AlignedVector.tpp" +#include "StreamConverters.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +StreamConverter::StreamConverter( + size_t object_size_in, + size_t object_size_out, + size_t buffer_capacity +) + : m_object_size_in(object_size_in) + , m_object_size_out(object_size_out) + , m_buffer_capacity(buffer_capacity) + , m_buffer(object_size_out * buffer_capacity) +{} +StreamConverter::~StreamConverter(){} +void StreamConverter::add_listener(StreamListener& listener){ + if (listener.object_size != m_object_size_out){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching object size."); + } + m_listeners.insert(&listener); +} +void StreamConverter::remove_listener(StreamListener& listener){ + m_listeners.erase(&listener); +} +void StreamConverter::push_objects(const void* data, size_t objects){ + while (objects > 0){ + size_t block = std::min(objects, m_buffer_capacity); + convert(m_buffer.data(), data, block); + data = (char*)data + block * m_object_size_in; + objects -= block; + for (StreamListener* listener : m_listeners){ + listener->on_objects(m_buffer.data(), block); + } + } +} + + +//void print_u8(const uint8_t* ptr, size_t len); + + +MisalignedStreamConverter::MisalignedStreamConverter( + size_t object_size_in, + size_t object_size_out, + size_t buffer_capacity +) + : m_object_size_in(object_size_in) + , m_object_size_out(object_size_out) + , m_edge(object_size_in) + , m_buffer_capacity(buffer_capacity) + , m_buffer(object_size_out * buffer_capacity) +{} +MisalignedStreamConverter::~MisalignedStreamConverter(){} +void MisalignedStreamConverter::add_listener(StreamListener& listener){ + if (listener.object_size != m_object_size_out){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching object size."); + } + m_listeners.insert(&listener); +} +void MisalignedStreamConverter::remove_listener(StreamListener& listener){ + m_listeners.erase(&listener); +} +void MisalignedStreamConverter::push_bytes(const void* data, size_t bytes){ +// cout << "push: "; +// print_u8((uint8_t*)data, bytes); + + // Fill the edge block. + if (m_edge_size > 0){ +// cout << "m_edge_size = " << m_edge_size << endl; + size_t block = std::min(m_object_size_in - m_edge_size, bytes); + memcpy(m_edge.data() + m_edge_size, data, block); + m_edge_size += block; + data = (char*)data + block; + bytes -= block; + } + + size_t stored = 0; + + // Process completed edge block. + if (m_edge_size >= m_object_size_in){ +// print_u8((uint8_t*)m_edge.data(), m_edge_size); + convert(m_buffer.data() + stored * m_object_size_out, m_edge.data(), 1); + m_edge_size = 0; + stored++; + } + + size_t objects = bytes / m_object_size_in; + while (stored + objects > 0){ + size_t block = std::min(objects, m_buffer_capacity - stored); +// cout << "stored = " << stored << endl; +// cout << "block = " << block << endl; +// print_u8((uint8_t*)data, block * m_object_size_in); + convert(m_buffer.data() + stored * m_object_size_out, data, block); + data = (char*)data + block * m_object_size_in; + bytes -= block * m_object_size_in; + stored += block; + objects -= block; + for (StreamListener* listener : m_listeners){ + listener->on_objects(m_buffer.data(), stored); + } + stored = 0; + } + +// cout << "left = " << bytes << endl; + + // Copy remaining bytes into edge buffer. + memcpy(m_edge.data(), data, bytes); + m_edge_size = bytes; +} + + + + + + +} diff --git a/Common/Cpp/StreamConverters.h b/Common/Cpp/StreamConverters.h index aacc3d208d..1d7eba90d9 100644 --- a/Common/Cpp/StreamConverters.h +++ b/Common/Cpp/StreamConverters.h @@ -1,96 +1,96 @@ -/* Stream Converters - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StreamConverters_H -#define PokemonAutomation_StreamConverters_H - -#include -#include "Containers/AlignedVector.h" - -namespace PokemonAutomation{ - - -class StreamListener{ -public: - StreamListener(size_t p_object_size) - : object_size(p_object_size) - {} - virtual ~StreamListener() = default; - virtual void on_objects(const void* data, size_t objects) = 0; - - const size_t object_size; -}; - - - -class StreamConverter{ -public: - void add_listener(StreamListener& listener); - void remove_listener(StreamListener& listener); - -public: - StreamConverter( - size_t object_size_in, - size_t object_size_out, - size_t buffer_capacity - ); - virtual ~StreamConverter(); - - void push_objects(const void* data, size_t objects); - -protected: - virtual void convert(void* out, const void* in, size_t count) = 0; - -private: - size_t m_object_size_in; - size_t m_object_size_out; - - size_t m_buffer_capacity; - AlignedVector m_buffer; - - std::set m_listeners; -}; - - - -// Given a stream of objects A that is arbitrarily broken up with no regards to -// alignment, convert it to a stream of objects B. -class MisalignedStreamConverter{ -public: - void add_listener(StreamListener& listener); - void remove_listener(StreamListener& listener); - -public: - MisalignedStreamConverter( - size_t object_size_in, - size_t object_size_out, - size_t buffer_capacity - ); - virtual ~MisalignedStreamConverter(); - - void push_bytes(const void* data, size_t bytes); - -protected: - virtual void convert(void* out, const void* in, size_t count) = 0; - -private: - size_t m_object_size_in; - size_t m_object_size_out; - - AlignedVector m_edge; - size_t m_edge_size = 0; - - size_t m_buffer_capacity; - AlignedVector m_buffer; - - std::set m_listeners; -}; - - - - -} -#endif +/* Stream Converters + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StreamConverters_H +#define PokemonAutomation_StreamConverters_H + +#include +#include "Containers/AlignedVector.h" + +namespace PokemonAutomation{ + + +class StreamListener{ +public: + StreamListener(size_t p_object_size) + : object_size(p_object_size) + {} + virtual ~StreamListener() = default; + virtual void on_objects(const void* data, size_t objects) = 0; + + const size_t object_size; +}; + + + +class StreamConverter{ +public: + void add_listener(StreamListener& listener); + void remove_listener(StreamListener& listener); + +public: + StreamConverter( + size_t object_size_in, + size_t object_size_out, + size_t buffer_capacity + ); + virtual ~StreamConverter(); + + void push_objects(const void* data, size_t objects); + +protected: + virtual void convert(void* out, const void* in, size_t count) = 0; + +private: + size_t m_object_size_in; + size_t m_object_size_out; + + size_t m_buffer_capacity; + AlignedVector m_buffer; + + std::set m_listeners; +}; + + + +// Given a stream of objects A that is arbitrarily broken up with no regards to +// alignment, convert it to a stream of objects B. +class MisalignedStreamConverter{ +public: + void add_listener(StreamListener& listener); + void remove_listener(StreamListener& listener); + +public: + MisalignedStreamConverter( + size_t object_size_in, + size_t object_size_out, + size_t buffer_capacity + ); + virtual ~MisalignedStreamConverter(); + + void push_bytes(const void* data, size_t bytes); + +protected: + virtual void convert(void* out, const void* in, size_t count) = 0; + +private: + size_t m_object_size_in; + size_t m_object_size_out; + + AlignedVector m_edge; + size_t m_edge_size = 0; + + size_t m_buffer_capacity; + AlignedVector m_buffer; + + std::set m_listeners; +}; + + + + +} +#endif diff --git a/Common/Cpp/StringTools.cpp b/Common/Cpp/StringTools.cpp index 0ff9c5b96d..c0a6c617d9 100644 --- a/Common/Cpp/StringTools.cpp +++ b/Common/Cpp/StringTools.cpp @@ -1,33 +1,33 @@ -/* String Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "StringTools.h" - -namespace PokemonAutomation{ -namespace StringTools{ - - -std::string replace(const std::string& str, const std::string& desired, const std::string& replace_with){ - std::string ret; - size_t index = 0; - while (index < str.size()){ - size_t pos = str.find(desired, index); - if (pos == std::string::npos){ - break; - } - ret += str.substr(index, pos - index); - ret += replace_with; - index = pos + desired.size(); - } - ret += str.substr(index); - return ret;; -} - - - - -} -} +/* String Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "StringTools.h" + +namespace PokemonAutomation{ +namespace StringTools{ + + +std::string replace(const std::string& str, const std::string& desired, const std::string& replace_with){ + std::string ret; + size_t index = 0; + while (index < str.size()){ + size_t pos = str.find(desired, index); + if (pos == std::string::npos){ + break; + } + ret += str.substr(index, pos - index); + ret += replace_with; + index = pos + desired.size(); + } + ret += str.substr(index); + return ret;; +} + + + + +} +} diff --git a/Common/Cpp/StringTools.h b/Common/Cpp/StringTools.h index 1bcd5aaa39..89456b916a 100644 --- a/Common/Cpp/StringTools.h +++ b/Common/Cpp/StringTools.h @@ -1,22 +1,22 @@ -/* String Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StringTools_H -#define PokemonAutomation_StringTools_H - -#include - -namespace PokemonAutomation{ -namespace StringTools{ - - -std::string replace(const std::string& str, const std::string& desired, const std::string& replace_with); - - - -} -} -#endif +/* String Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StringTools_H +#define PokemonAutomation_StringTools_H + +#include + +namespace PokemonAutomation{ +namespace StringTools{ + + +std::string replace(const std::string& str, const std::string& desired, const std::string& replace_with); + + + +} +} +#endif diff --git a/Common/Cpp/Time.cpp b/Common/Cpp/Time.cpp index 397f39d841..f65ffd575b 100644 --- a/Common/Cpp/Time.cpp +++ b/Common/Cpp/Time.cpp @@ -1,40 +1,40 @@ -/* Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -//#include -#include "Time.h" - -namespace PokemonAutomation{ - - - -uint16_t current_year(){ -#if 0 - // This requires C++20. (https://stackoverflow.com/a/58152002) - return (uint16_t)std::atoi( - std::format("{:%Y}", std::chrono::system_clock::now()) - ); -#endif - -#if 1 - // This is not thread-safe. (https://stackoverflow.com/a/58153628) - // (Thread-safe on Windows because it uses TLS, but unclear on other platforms.) - std::time_t t = std::time(nullptr); - std::tm* info = std::localtime(&t); - return (uint16_t)(info->tm_year + 1900); -#endif - -#if 0 - // This is wrong. (https://stackoverflow.com/a/67459754) - time_t current_time = time(nullptr); - return (uint16_t)(1970 + current_time / 31537970); -#endif -} - - - -} +/* Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include +#include "Time.h" + +namespace PokemonAutomation{ + + + +uint16_t current_year(){ +#if 0 + // This requires C++20. (https://stackoverflow.com/a/58152002) + return (uint16_t)std::atoi( + std::format("{:%Y}", std::chrono::system_clock::now()) + ); +#endif + +#if 1 + // This is not thread-safe. (https://stackoverflow.com/a/58153628) + // (Thread-safe on Windows because it uses TLS, but unclear on other platforms.) + std::time_t t = std::time(nullptr); + std::tm* info = std::localtime(&t); + return (uint16_t)(info->tm_year + 1900); +#endif + +#if 0 + // This is wrong. (https://stackoverflow.com/a/67459754) + time_t current_time = time(nullptr); + return (uint16_t)(1970 + current_time / 31537970); +#endif +} + + + +} diff --git a/Common/Cpp/Time.h b/Common/Cpp/Time.h index df380ae142..b4ebe4cdc2 100644 --- a/Common/Cpp/Time.h +++ b/Common/Cpp/Time.h @@ -1,30 +1,30 @@ -/* Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Time_H -#define PokemonAutomation_Time_H - -#include - -namespace PokemonAutomation{ - - -using WallClock = std::chrono::system_clock::time_point; -using WallDuration = std::chrono::system_clock::duration; - -using Milliseconds = std::chrono::milliseconds; -using Seconds = std::chrono::seconds; - -inline WallClock current_time(){ - return std::chrono::system_clock::now(); -} - - -uint16_t current_year(); - - -} -#endif +/* Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Time_H +#define PokemonAutomation_Time_H + +#include + +namespace PokemonAutomation{ + + +using WallClock = std::chrono::system_clock::time_point; +using WallDuration = std::chrono::system_clock::duration; + +using Milliseconds = std::chrono::milliseconds; +using Seconds = std::chrono::seconds; + +inline WallClock current_time(){ + return std::chrono::system_clock::now(); +} + + +uint16_t current_year(); + + +} +#endif diff --git a/Common/Cpp/Unicode.cpp b/Common/Cpp/Unicode.cpp index eab6a21d91..5d991ba3f6 100644 --- a/Common/Cpp/Unicode.cpp +++ b/Common/Cpp/Unicode.cpp @@ -1,105 +1,105 @@ -/* Unicode - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Unicode.h" -#include - -namespace PokemonAutomation{ - - -const uint32_t MAX_CODEPOINT = 0x10ffff; -const uint32_t REPLACEMENT = 0xfffd; - -void utf8_skip_to_next_codepoint(const char*& str){ - while (true){ - str++; - unsigned ch = str[0]; - if ((ch & 0x80u) == 0){ - return; - } - if ((ch & 0xc0u) == 0xc0u){ - return; - } - } -} -uint32_t utf8_to_unicode(const char*& str){ - unsigned char ch = str[0]; - if (ch <= 0x7f){ - str++; - return ch; - } - - uint32_t codepoint; - - if (ch < 0xc0){ - utf8_skip_to_next_codepoint(str); - return REPLACEMENT; - } - - int bytes = 0; - bytes = ch <= 0xf7 ? 4 : bytes; - bytes = ch <= 0xef ? 3 : bytes; - bytes = ch <= 0xdf ? 2 : bytes; - - if (bytes == 0){ - utf8_skip_to_next_codepoint(str); - return REPLACEMENT; - } - - ch &= ((unsigned char)1 << (7 - bytes)) - 1; - codepoint = ch; - - for (int c = 1; c < bytes; c++){ - ch = str[c]; - if ((ch & 0xc0) != 0x80){ - utf8_skip_to_next_codepoint(str); - return REPLACEMENT; - } - codepoint <<= 6; - codepoint |= ch & 0x3f; - } - - if (codepoint > MAX_CODEPOINT){ - utf8_skip_to_next_codepoint(str); - return REPLACEMENT; - } - - str += bytes; - return codepoint; -} -void append_to_utf16(std::u16string& str, uint32_t codepoint){ - if (codepoint < 0xffff){ - str += (char16_t)codepoint; - return; - } - str.reserve(str.size() + 2); - - codepoint -= 0x10000; - str += (char16_t)(codepoint >> 10) + 0xd800; - str += (char16_t)(codepoint & 0x3ff) + 0xdc00; -} - -std::u16string utf8_to_utf16(const std::string& str){ - std::u16string out; - const char* utf8 = str.c_str(); - const char* stop = utf8 + str.size(); - while (utf8 < stop){ - append_to_utf16(out, utf8_to_unicode(utf8)); - } - return out; -} - -#ifdef _WIN32 -std::wstring utf8_to_wstr(const std::string& str){ - std::u16string tmp(utf8_to_utf16(str)); - return std::wstring(tmp.begin(), tmp.end()); -} -#endif - - - -} - +/* Unicode + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Unicode.h" +#include + +namespace PokemonAutomation{ + + +const uint32_t MAX_CODEPOINT = 0x10ffff; +const uint32_t REPLACEMENT = 0xfffd; + +void utf8_skip_to_next_codepoint(const char*& str){ + while (true){ + str++; + unsigned ch = str[0]; + if ((ch & 0x80u) == 0){ + return; + } + if ((ch & 0xc0u) == 0xc0u){ + return; + } + } +} +uint32_t utf8_to_unicode(const char*& str){ + unsigned char ch = str[0]; + if (ch <= 0x7f){ + str++; + return ch; + } + + uint32_t codepoint; + + if (ch < 0xc0){ + utf8_skip_to_next_codepoint(str); + return REPLACEMENT; + } + + int bytes = 0; + bytes = ch <= 0xf7 ? 4 : bytes; + bytes = ch <= 0xef ? 3 : bytes; + bytes = ch <= 0xdf ? 2 : bytes; + + if (bytes == 0){ + utf8_skip_to_next_codepoint(str); + return REPLACEMENT; + } + + ch &= ((unsigned char)1 << (7 - bytes)) - 1; + codepoint = ch; + + for (int c = 1; c < bytes; c++){ + ch = str[c]; + if ((ch & 0xc0) != 0x80){ + utf8_skip_to_next_codepoint(str); + return REPLACEMENT; + } + codepoint <<= 6; + codepoint |= ch & 0x3f; + } + + if (codepoint > MAX_CODEPOINT){ + utf8_skip_to_next_codepoint(str); + return REPLACEMENT; + } + + str += bytes; + return codepoint; +} +void append_to_utf16(std::u16string& str, uint32_t codepoint){ + if (codepoint < 0xffff){ + str += (char16_t)codepoint; + return; + } + str.reserve(str.size() + 2); + + codepoint -= 0x10000; + str += (char16_t)(codepoint >> 10) + 0xd800; + str += (char16_t)(codepoint & 0x3ff) + 0xdc00; +} + +std::u16string utf8_to_utf16(const std::string& str){ + std::u16string out; + const char* utf8 = str.c_str(); + const char* stop = utf8 + str.size(); + while (utf8 < stop){ + append_to_utf16(out, utf8_to_unicode(utf8)); + } + return out; +} + +#ifdef _WIN32 +std::wstring utf8_to_wstr(const std::string& str){ + std::u16string tmp(utf8_to_utf16(str)); + return std::wstring(tmp.begin(), tmp.end()); +} +#endif + + + +} + diff --git a/Common/Cpp/Unicode.h b/Common/Cpp/Unicode.h index 94440fccc5..261df8447f 100644 --- a/Common/Cpp/Unicode.h +++ b/Common/Cpp/Unicode.h @@ -1,21 +1,21 @@ -/* Unicode - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Unicode_H -#define PokemonAutomation_Unicode_H - -#include - -namespace PokemonAutomation{ - -std::u16string utf8_to_utf16(const std::string& str); - -#ifdef _WIN32 -std::wstring utf8_to_wstr(const std::string& str); -#endif - -} -#endif +/* Unicode + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Unicode_H +#define PokemonAutomation_Unicode_H + +#include + +namespace PokemonAutomation{ + +std::u16string utf8_to_utf16(const std::string& str); + +#ifdef _WIN32 +std::wstring utf8_to_wstr(const std::string& str); +#endif + +} +#endif diff --git a/Common/Cpp/ValueDebouncer.h b/Common/Cpp/ValueDebouncer.h index a12e865e71..d87d1168e5 100644 --- a/Common/Cpp/ValueDebouncer.h +++ b/Common/Cpp/ValueDebouncer.h @@ -1,62 +1,62 @@ -/* Value Debouncer - * - * From: https://github.com/PokemonAutomation/ - * - * This class is used to debounce a resizing loop in Qt with widgets of - * fixed aspect ratio. - * - * When resizing a QScrollArea's width, the height of the contents may change. - * If this height changes in a way that adds/removes the scroll bar, the width - * will change again. If this 2nd change then toggles the scroll bar again, - * you get an infinite loop. - * - * This class is used to help detect these infinite loops and stop the resizing. - * - */ - -#ifndef PokemonAutomation_ValueDebouncer_H -#define PokemonAutomation_ValueDebouncer_H - -#include -#include - -namespace PokemonAutomation{ - - -template -class ValueDebouncer{ -public: - ValueDebouncer(size_t history = 10) - : m_max_history(history) - {} - - void clear(){ - m_history.clear(); - m_recent.clear(); - } - - bool check(Type value){ - auto iter = m_recent.find(value); - if (iter != m_recent.end()){ - return false; - } - m_history.push_back(value); - try{ - m_recent.insert(value); - }catch (...){ - m_history.pop_back(); - throw; - } - return true; - } - -private: - size_t m_max_history; - std::deque m_history; - std::set m_recent; -}; - - - -} -#endif +/* Value Debouncer + * + * From: https://github.com/PokemonAutomation/ + * + * This class is used to debounce a resizing loop in Qt with widgets of + * fixed aspect ratio. + * + * When resizing a QScrollArea's width, the height of the contents may change. + * If this height changes in a way that adds/removes the scroll bar, the width + * will change again. If this 2nd change then toggles the scroll bar again, + * you get an infinite loop. + * + * This class is used to help detect these infinite loops and stop the resizing. + * + */ + +#ifndef PokemonAutomation_ValueDebouncer_H +#define PokemonAutomation_ValueDebouncer_H + +#include +#include + +namespace PokemonAutomation{ + + +template +class ValueDebouncer{ +public: + ValueDebouncer(size_t history = 10) + : m_max_history(history) + {} + + void clear(){ + m_history.clear(); + m_recent.clear(); + } + + bool check(Type value){ + auto iter = m_recent.find(value); + if (iter != m_recent.end()){ + return false; + } + m_history.push_back(value); + try{ + m_recent.insert(value); + }catch (...){ + m_history.pop_back(); + throw; + } + return true; + } + +private: + size_t m_max_history; + std::deque m_history; + std::set m_recent; +}; + + + +} +#endif diff --git a/Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h b/Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h index 83bdc5fa1b..4ee59ad57f 100644 --- a/Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h +++ b/Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h @@ -1,64 +1,64 @@ -/* Controller Types and Definitions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerDefs_H -#define PokemonAutomation_NintendoSwitch_ControllerDefs_H - -#include -#include - - -#ifdef __cplusplus - -#error "C++ shouldn't include this file." - -#else - -// One second = 125 ticks. Thus each tick is 8 milliseconds. -#define TICKS_PER_SECOND 125 - -// Buttons -#define Button uint16_t -#define BUTTON_Y ((uint16_t)1 << 0) -#define BUTTON_B ((uint16_t)1 << 1) -#define BUTTON_A ((uint16_t)1 << 2) -#define BUTTON_X ((uint16_t)1 << 3) -#define BUTTON_L ((uint16_t)1 << 4) -#define BUTTON_R ((uint16_t)1 << 5) -#define BUTTON_ZL ((uint16_t)1 << 6) -#define BUTTON_ZR ((uint16_t)1 << 7) -#define BUTTON_MINUS ((uint16_t)1 << 8) -#define BUTTON_PLUS ((uint16_t)1 << 9) -#define BUTTON_LCLICK ((uint16_t)1 << 10) -#define BUTTON_RCLICK ((uint16_t)1 << 11) -#define BUTTON_HOME ((uint16_t)1 << 12) -#define BUTTON_CAPTURE ((uint16_t)1 << 13) - -// Dpad -#define DpadPosition uint8_t -#define DPAD_UP 0 -#define DPAD_UP_RIGHT 1 -#define DPAD_RIGHT 2 -#define DPAD_DOWN_RIGHT 3 -#define DPAD_DOWN 4 -#define DPAD_DOWN_LEFT 5 -#define DPAD_LEFT 6 -#define DPAD_UP_LEFT 7 -#define DPAD_NONE 8 - -// Joysticks -#define STICK_MIN 0x00 -#define STICK_CENTER 0x80 -#define STICK_MAX 0xff - -#endif - - - - - - -#endif +/* Controller Types and Definitions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerDefs_H +#define PokemonAutomation_NintendoSwitch_ControllerDefs_H + +#include +#include + + +#ifdef __cplusplus + +#error "C++ shouldn't include this file." + +#else + +// One second = 125 ticks. Thus each tick is 8 milliseconds. +#define TICKS_PER_SECOND 125 + +// Buttons +#define Button uint16_t +#define BUTTON_Y ((uint16_t)1 << 0) +#define BUTTON_B ((uint16_t)1 << 1) +#define BUTTON_A ((uint16_t)1 << 2) +#define BUTTON_X ((uint16_t)1 << 3) +#define BUTTON_L ((uint16_t)1 << 4) +#define BUTTON_R ((uint16_t)1 << 5) +#define BUTTON_ZL ((uint16_t)1 << 6) +#define BUTTON_ZR ((uint16_t)1 << 7) +#define BUTTON_MINUS ((uint16_t)1 << 8) +#define BUTTON_PLUS ((uint16_t)1 << 9) +#define BUTTON_LCLICK ((uint16_t)1 << 10) +#define BUTTON_RCLICK ((uint16_t)1 << 11) +#define BUTTON_HOME ((uint16_t)1 << 12) +#define BUTTON_CAPTURE ((uint16_t)1 << 13) + +// Dpad +#define DpadPosition uint8_t +#define DPAD_UP 0 +#define DPAD_UP_RIGHT 1 +#define DPAD_RIGHT 2 +#define DPAD_DOWN_RIGHT 3 +#define DPAD_DOWN 4 +#define DPAD_DOWN_LEFT 5 +#define DPAD_LEFT 6 +#define DPAD_UP_LEFT 7 +#define DPAD_NONE 8 + +// Joysticks +#define STICK_MIN 0x00 +#define STICK_CENTER 0x80 +#define STICK_MAX 0xff + +#endif + + + + + + +#endif diff --git a/Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h b/Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h index 6ce8750e8e..a8f5f003a4 100644 --- a/Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h +++ b/Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h @@ -1,40 +1,40 @@ -/* Slot Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SlotDatabase_H -#define PokemonAutomation_NintendoSwitch_SlotDatabase_H - -#include "Common/Cpp/Options/EnumDropdownDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -inline const IntegerEnumDropdownDatabase& GameSlot_Database(){ - static const IntegerEnumDropdownDatabase database({ - {1, "game1", "Game 1"}, - {2, "game2", "Game 2"}, - }); - return database; -} -inline const IntegerEnumDropdownDatabase& UserSlot_Database(){ - static const IntegerEnumDropdownDatabase database({ - {1, "user1", "User 1"}, - {2, "user2", "User 2"}, - {3, "user3", "User 3"}, - {4, "user4", "User 4"}, - {5, "user5", "User 5"}, - {6, "user6", "User 6"}, - {7, "user7", "User 7"}, - {8, "user8", "User 8"}, - }); - return database; -} - - -} -} -#endif +/* Slot Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SlotDatabase_H +#define PokemonAutomation_NintendoSwitch_SlotDatabase_H + +#include "Common/Cpp/Options/EnumDropdownDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +inline const IntegerEnumDropdownDatabase& GameSlot_Database(){ + static const IntegerEnumDropdownDatabase database({ + {1, "game1", "Game 1"}, + {2, "game2", "Game 2"}, + }); + return database; +} +inline const IntegerEnumDropdownDatabase& UserSlot_Database(){ + static const IntegerEnumDropdownDatabase database({ + {1, "user1", "User 1"}, + {2, "user2", "User 2"}, + {3, "user3", "User 3"}, + {4, "user4", "User 4"}, + {5, "user5", "User 5"}, + {6, "user6", "User 6"}, + {7, "user7", "User 7"}, + {8, "user8", "User 8"}, + }); + return database; +} + + +} +} +#endif diff --git a/Common/PokemonSwSh/PokemonSwSh_FossilTable.h b/Common/PokemonSwSh/PokemonSwSh_FossilTable.h index 6f3751093d..475c82633f 100644 --- a/Common/PokemonSwSh/PokemonSwSh_FossilTable.h +++ b/Common/PokemonSwSh/PokemonSwSh_FossilTable.h @@ -1,112 +1,112 @@ -/* Fossil Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_FossilTableOption_H -#define PokemonAutomation_PokemonSwSh_FossilTableOption_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -enum class Fossil{ - Dracozolt = 0, - Arctozolt = 1, - Dracovish = 2, - Arctovish = 3, -}; - - -class FossilGame : public EditableTableRow{ -private: - static const EnumDropdownDatabase& Fossil_Database(){ - static const EnumDropdownDatabase database({ - {Fossil::Dracozolt, "dracozolt", "Dracozolt"}, - {Fossil::Arctozolt, "arctozolt", "Arctozolt"}, - {Fossil::Dracovish, "dracovish", "Dracovish"}, - {Fossil::Arctovish, "arctovish", "Arctovish"}, - }); - return database; - } - -public: - FossilGame(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , game_slot(GameSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) - , user_slot(UserSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) - , fossil(Fossil_Database(), LockMode::LOCK_WHILE_RUNNING, Fossil::Dracovish) - , revives(LockMode::LOCK_WHILE_RUNNING, 960, 0, 965) - { - PA_ADD_OPTION(game_slot); - PA_ADD_OPTION(user_slot); - PA_ADD_OPTION(fossil); - PA_ADD_OPTION(revives); - } - FossilGame( - EditableTableOption& parent_table, - uint8_t p_game_slot, uint8_t p_user_slot, Fossil p_fossil, uint16_t p_revives - ) - : FossilGame(parent_table) - { - game_slot.set_value(p_game_slot); - user_slot.set_value(p_user_slot); - fossil.set(p_fossil); - revives.set(p_revives); - } - virtual std::unique_ptr clone() const override{ - std::unique_ptr ret(new FossilGame(parent())); - ret->game_slot.set_value(game_slot.current_value()); - ret->user_slot.set_value(user_slot.current_value()); - ret->fossil.set(fossil); - ret->revives.set(revives); - return ret; - } - -public: - IntegerEnumDropdownCell game_slot; - IntegerEnumDropdownCell user_slot; - EnumDropdownCell fossil; - SimpleIntegerCell revives; -}; - - -class FossilTable : public EditableTableOption_t{ -public: - FossilTable() - : EditableTableOption_t( - "Game List:", - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) - {} - virtual std::vector make_header() const override{ - return std::vector{ - "Game", - "User", - "Fossil", - "Revives" - }; - } - - std::vector> make_defaults(){ - std::vector> ret; - ret.emplace_back(new FossilGame(*this, 1, 1, Fossil::Dracovish, 960)); - return ret; - } -}; - - - - -} -} -} -#endif +/* Fossil Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_FossilTableOption_H +#define PokemonAutomation_PokemonSwSh_FossilTableOption_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +enum class Fossil{ + Dracozolt = 0, + Arctozolt = 1, + Dracovish = 2, + Arctovish = 3, +}; + + +class FossilGame : public EditableTableRow{ +private: + static const EnumDropdownDatabase& Fossil_Database(){ + static const EnumDropdownDatabase database({ + {Fossil::Dracozolt, "dracozolt", "Dracozolt"}, + {Fossil::Arctozolt, "arctozolt", "Arctozolt"}, + {Fossil::Dracovish, "dracovish", "Dracovish"}, + {Fossil::Arctovish, "arctovish", "Arctovish"}, + }); + return database; + } + +public: + FossilGame(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , game_slot(GameSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) + , user_slot(UserSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) + , fossil(Fossil_Database(), LockMode::LOCK_WHILE_RUNNING, Fossil::Dracovish) + , revives(LockMode::LOCK_WHILE_RUNNING, 960, 0, 965) + { + PA_ADD_OPTION(game_slot); + PA_ADD_OPTION(user_slot); + PA_ADD_OPTION(fossil); + PA_ADD_OPTION(revives); + } + FossilGame( + EditableTableOption& parent_table, + uint8_t p_game_slot, uint8_t p_user_slot, Fossil p_fossil, uint16_t p_revives + ) + : FossilGame(parent_table) + { + game_slot.set_value(p_game_slot); + user_slot.set_value(p_user_slot); + fossil.set(p_fossil); + revives.set(p_revives); + } + virtual std::unique_ptr clone() const override{ + std::unique_ptr ret(new FossilGame(parent())); + ret->game_slot.set_value(game_slot.current_value()); + ret->user_slot.set_value(user_slot.current_value()); + ret->fossil.set(fossil); + ret->revives.set(revives); + return ret; + } + +public: + IntegerEnumDropdownCell game_slot; + IntegerEnumDropdownCell user_slot; + EnumDropdownCell fossil; + SimpleIntegerCell revives; +}; + + +class FossilTable : public EditableTableOption_t{ +public: + FossilTable() + : EditableTableOption_t( + "Game List:", + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) + {} + virtual std::vector make_header() const override{ + return std::vector{ + "Game", + "User", + "Fossil", + "Revives" + }; + } + + std::vector> make_defaults(){ + std::vector> ret; + ret.emplace_back(new FossilGame(*this, 1, 1, Fossil::Dracovish, 960)); + return ret; + } +}; + + + + +} +} +} +#endif diff --git a/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.cpp b/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.cpp index 4daa901506..5bad0fdd2c 100644 --- a/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.cpp +++ b/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.cpp @@ -1,103 +1,103 @@ -/* Multi-Host Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h" -#include "PokemonSwSh_MultiHostTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -MultiHostSlot::MultiHostSlot(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , game_slot(GameSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) - , user_slot(UserSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) - , skips(LockMode::LOCK_WHILE_RUNNING, 3, 0, 7) - , backup_save(LockMode::LOCK_WHILE_RUNNING, false) - , always_catchable(LockMode::LOCK_WHILE_RUNNING, true) - , use_raid_code(LockMode::LOCK_WHILE_RUNNING, true) - , accept_FRs(LockMode::LOCK_WHILE_RUNNING, true) - , move_slot(LockMode::LOCK_WHILE_RUNNING, 0, 0, 4) - , dynamax(LockMode::LOCK_WHILE_RUNNING, true) - , post_raid_delay(LockMode::LOCK_WHILE_RUNNING, "0 s") -{ - PA_ADD_OPTION(game_slot); - PA_ADD_OPTION(user_slot); - PA_ADD_OPTION(skips); - PA_ADD_OPTION(backup_save); - PA_ADD_OPTION(always_catchable); - if (static_cast(parent_table).raid_code_option){ - PA_ADD_OPTION(use_raid_code); - } - PA_ADD_OPTION(accept_FRs); - PA_ADD_OPTION(move_slot); - PA_ADD_OPTION(dynamax); - PA_ADD_OPTION(post_raid_delay); -} - -std::unique_ptr MultiHostSlot::clone() const{ - std::unique_ptr ret(new MultiHostSlot(parent())); - ret->game_slot.set_value(game_slot.current_value()); - ret->user_slot.set_value(user_slot.current_value()); - ret->skips.set(skips); - ret->backup_save = (bool)backup_save; - ret->always_catchable = (bool)always_catchable; - ret->use_raid_code = (bool)use_raid_code; - ret->accept_FRs = (bool)accept_FRs; - ret->move_slot.set(move_slot); - ret->dynamax = (bool)dynamax; - ret->post_raid_delay.set(post_raid_delay.current_text()); - return ret; -} - - - -MultiHostTable::MultiHostTable(bool p_raid_code_option) - : EditableTableOption("Game List:", LockMode::LOCK_WHILE_RUNNING) - , raid_code_option(p_raid_code_option) -{} -std::vector> MultiHostTable::copy_snapshot() const{ - return EditableTableOption::copy_snapshot(); -} -std::vector MultiHostTable::make_header() const{ - if (raid_code_option){ - return std::vector{ - "Game", - "User", - "Skips", - "Backup Save", - "Always Catchable", - "Use Raid Code", - "Accept FRs", - "1st Move", - "Dynamax", - "Post Raid Delay", - }; - }else{ - return std::vector{ - "Game", - "User", - "Skips", - "Backup Save", - "Always Catchable", - "Accept FRs", - "1st Move", - "Dynamax", - "Post Raid Delay", - }; - } -} -std::unique_ptr MultiHostTable::make_row(){ - return std::unique_ptr(new MultiHostSlot(*this)); -} - - - - -} -} -} +/* Multi-Host Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h" +#include "PokemonSwSh_MultiHostTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +MultiHostSlot::MultiHostSlot(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , game_slot(GameSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) + , user_slot(UserSlot_Database(), LockMode::LOCK_WHILE_RUNNING, 1) + , skips(LockMode::LOCK_WHILE_RUNNING, 3, 0, 7) + , backup_save(LockMode::LOCK_WHILE_RUNNING, false) + , always_catchable(LockMode::LOCK_WHILE_RUNNING, true) + , use_raid_code(LockMode::LOCK_WHILE_RUNNING, true) + , accept_FRs(LockMode::LOCK_WHILE_RUNNING, true) + , move_slot(LockMode::LOCK_WHILE_RUNNING, 0, 0, 4) + , dynamax(LockMode::LOCK_WHILE_RUNNING, true) + , post_raid_delay(LockMode::LOCK_WHILE_RUNNING, "0 s") +{ + PA_ADD_OPTION(game_slot); + PA_ADD_OPTION(user_slot); + PA_ADD_OPTION(skips); + PA_ADD_OPTION(backup_save); + PA_ADD_OPTION(always_catchable); + if (static_cast(parent_table).raid_code_option){ + PA_ADD_OPTION(use_raid_code); + } + PA_ADD_OPTION(accept_FRs); + PA_ADD_OPTION(move_slot); + PA_ADD_OPTION(dynamax); + PA_ADD_OPTION(post_raid_delay); +} + +std::unique_ptr MultiHostSlot::clone() const{ + std::unique_ptr ret(new MultiHostSlot(parent())); + ret->game_slot.set_value(game_slot.current_value()); + ret->user_slot.set_value(user_slot.current_value()); + ret->skips.set(skips); + ret->backup_save = (bool)backup_save; + ret->always_catchable = (bool)always_catchable; + ret->use_raid_code = (bool)use_raid_code; + ret->accept_FRs = (bool)accept_FRs; + ret->move_slot.set(move_slot); + ret->dynamax = (bool)dynamax; + ret->post_raid_delay.set(post_raid_delay.current_text()); + return ret; +} + + + +MultiHostTable::MultiHostTable(bool p_raid_code_option) + : EditableTableOption("Game List:", LockMode::LOCK_WHILE_RUNNING) + , raid_code_option(p_raid_code_option) +{} +std::vector> MultiHostTable::copy_snapshot() const{ + return EditableTableOption::copy_snapshot(); +} +std::vector MultiHostTable::make_header() const{ + if (raid_code_option){ + return std::vector{ + "Game", + "User", + "Skips", + "Backup Save", + "Always Catchable", + "Use Raid Code", + "Accept FRs", + "1st Move", + "Dynamax", + "Post Raid Delay", + }; + }else{ + return std::vector{ + "Game", + "User", + "Skips", + "Backup Save", + "Always Catchable", + "Accept FRs", + "1st Move", + "Dynamax", + "Post Raid Delay", + }; + } +} +std::unique_ptr MultiHostTable::make_row(){ + return std::unique_ptr(new MultiHostSlot(*this)); +} + + + + +} +} +} diff --git a/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h b/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h index 3e7f1f9995..a21332a70a 100644 --- a/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h +++ b/Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h @@ -1,63 +1,63 @@ -/* Multi-Host Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MultiHostTableOption_H -#define PokemonAutomation_PokemonSwSh_MultiHostTableOption_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -class MultiHostTable; - - -class MultiHostSlot : public EditableTableRow{ -public: - MultiHostSlot(EditableTableOption& parent_table); - - virtual std::unique_ptr clone() const override; - -public: - IntegerEnumDropdownCell game_slot; - IntegerEnumDropdownCell user_slot; - SimpleIntegerCell skips; - BooleanCheckBoxCell backup_save; - BooleanCheckBoxCell always_catchable; - BooleanCheckBoxCell use_raid_code; - BooleanCheckBoxCell accept_FRs; - SimpleIntegerCell move_slot; - BooleanCheckBoxCell dynamax; - MillisecondsCell post_raid_delay; -}; - - - -class MultiHostTable : public EditableTableOption{ -public: - MultiHostTable(bool p_raid_code_option); - std::vector> copy_snapshot() const; - virtual std::vector make_header() const override; - virtual std::unique_ptr make_row() override; - -public: - const bool raid_code_option; -}; - - - - - - -} -} -} -#endif +/* Multi-Host Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MultiHostTableOption_H +#define PokemonAutomation_PokemonSwSh_MultiHostTableOption_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +class MultiHostTable; + + +class MultiHostSlot : public EditableTableRow{ +public: + MultiHostSlot(EditableTableOption& parent_table); + + virtual std::unique_ptr clone() const override; + +public: + IntegerEnumDropdownCell game_slot; + IntegerEnumDropdownCell user_slot; + SimpleIntegerCell skips; + BooleanCheckBoxCell backup_save; + BooleanCheckBoxCell always_catchable; + BooleanCheckBoxCell use_raid_code; + BooleanCheckBoxCell accept_FRs; + SimpleIntegerCell move_slot; + BooleanCheckBoxCell dynamax; + MillisecondsCell post_raid_delay; +}; + + + +class MultiHostTable : public EditableTableOption{ +public: + MultiHostTable(bool p_raid_code_option); + std::vector> copy_snapshot() const; + virtual std::vector make_header() const override; + virtual std::unique_ptr make_row() override; + +public: + const bool raid_code_option; +}; + + + + + + +} +} +} +#endif diff --git a/Common/PokemonSwSh/PokemonSwSh_Protocol_DaySkippers.h b/Common/PokemonSwSh/PokemonSwSh_Protocol_DaySkippers.h index 6b074c60f6..669746b9cb 100644 --- a/Common/PokemonSwSh/PokemonSwSh_Protocol_DaySkippers.h +++ b/Common/PokemonSwSh/PokemonSwSh_Protocol_DaySkippers.h @@ -1,90 +1,90 @@ -/* Day Skippers - * - * From: https://github.com/PokemonAutomation/ - * - * This file requires (PABB_PABOTBASE_LEVEL >= 31). - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Protocol_DaySkippers_H -#define PokemonAutomation_PokemonSwSh_Protocol_DaySkippers_H - -#ifdef __AVR__ -#include "NativePrograms/NintendoSwitch/Framework/Master.h" -#endif -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// Protocols -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#else -#define PABB_PACK __attribute__((packed)) -#endif -#ifdef __cplusplus -namespace PokemonAutomation{ -namespace NintendoSwitch{ -#endif -//////////////////////////////////////////////////////////////////////////////// - -#define PABB_MSG_COMMAND_SKIPPER_INIT_VIEW 0xbd -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_skipper_init_view; - -#define PABB_MSG_COMMAND_SKIPPER_AUTO_RECOVERY 0xbe -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_skipper_auto_recovery; - -#define PABB_MSG_COMMAND_SKIPPER_ROLLBACK_YEAR_FULL 0xbf -typedef struct{ - seqnum_t seqnum; - bool date_us; -} PABB_PACK pabb_skipper_rollback_year_full; - -#define PABB_MSG_COMMAND_SKIPPER_ROLLBACK_YEAR_SYNC 0xc0 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_skipper_rollback_year_sync; - -#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_DAY 0xc1 -typedef struct{ - seqnum_t seqnum; - bool date_us; -} PABB_PACK pabb_skipper_increment_day; - -#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_MONTH 0xc2 -typedef struct{ - seqnum_t seqnum; - uint8_t days; -} PABB_PACK pabb_skipper_increment_month; - -#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_ALL 0xc3 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_skipper_increment_all; - -#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_ALL_ROLLBACK 0xc4 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_skipper_increment_all_rollback; - -//////////////////////////////////////////////////////////////////////////////// -#ifdef __cplusplus -} -} -#endif -#if _WIN32 -#pragma pack(pop) -#endif -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -#endif - +/* Day Skippers + * + * From: https://github.com/PokemonAutomation/ + * + * This file requires (PABB_PABOTBASE_LEVEL >= 31). + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Protocol_DaySkippers_H +#define PokemonAutomation_PokemonSwSh_Protocol_DaySkippers_H + +#ifdef __AVR__ +#include "NativePrograms/NintendoSwitch/Framework/Master.h" +#endif +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// Protocols +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#else +#define PABB_PACK __attribute__((packed)) +#endif +#ifdef __cplusplus +namespace PokemonAutomation{ +namespace NintendoSwitch{ +#endif +//////////////////////////////////////////////////////////////////////////////// + +#define PABB_MSG_COMMAND_SKIPPER_INIT_VIEW 0xbd +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_skipper_init_view; + +#define PABB_MSG_COMMAND_SKIPPER_AUTO_RECOVERY 0xbe +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_skipper_auto_recovery; + +#define PABB_MSG_COMMAND_SKIPPER_ROLLBACK_YEAR_FULL 0xbf +typedef struct{ + seqnum_t seqnum; + bool date_us; +} PABB_PACK pabb_skipper_rollback_year_full; + +#define PABB_MSG_COMMAND_SKIPPER_ROLLBACK_YEAR_SYNC 0xc0 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_skipper_rollback_year_sync; + +#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_DAY 0xc1 +typedef struct{ + seqnum_t seqnum; + bool date_us; +} PABB_PACK pabb_skipper_increment_day; + +#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_MONTH 0xc2 +typedef struct{ + seqnum_t seqnum; + uint8_t days; +} PABB_PACK pabb_skipper_increment_month; + +#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_ALL 0xc3 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_skipper_increment_all; + +#define PABB_MSG_COMMAND_SKIPPER_INCREMENT_ALL_ROLLBACK 0xc4 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_skipper_increment_all_rollback; + +//////////////////////////////////////////////////////////////////////////////// +#ifdef __cplusplus +} +} +#endif +#if _WIN32 +#pragma pack(pop) +#endif +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +#endif + diff --git a/Common/Qt/AutoHeightTable.cpp b/Common/Qt/AutoHeightTable.cpp index 184645bdf3..77b044da16 100644 --- a/Common/Qt/AutoHeightTable.cpp +++ b/Common/Qt/AutoHeightTable.cpp @@ -1,46 +1,46 @@ -/* QTableWidth with auto-adjusting height. - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "AutoHeightTable.h" - -namespace PokemonAutomation{ - - -void AutoHeightTableWidget::update_height(){ - int rows = this->rowCount(); - int total_height = 5; - total_height += this->horizontalHeader()->height(); - total_height += this->horizontalScrollBar()->height(); - for (int c = 0; c < rows; c++){ - total_height += this->verticalHeader()->sectionSize(c); - } -// cout << total_height << endl; - this->setMinimumHeight(total_height); - this->setMaximumHeight(total_height); -// this->adjustSize(); -// this->parentWidget()->adjustSize(); -// this->parentWidget()->parentWidget()->adjustSize(); -} - -void AutoHeightTableWidget::setRowCount(int rows){ - QTableWidget::setRowCount(rows); - update_height(); -} -void AutoHeightTableWidget::insertRow(int row){ - QTableWidget::insertRow(row); - update_height(); -} -void AutoHeightTableWidget::removeRow(int row){ - QTableWidget::removeRow(row); - update_height(); -} - - - - -} +/* QTableWidth with auto-adjusting height. + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "AutoHeightTable.h" + +namespace PokemonAutomation{ + + +void AutoHeightTableWidget::update_height(){ + int rows = this->rowCount(); + int total_height = 5; + total_height += this->horizontalHeader()->height(); + total_height += this->horizontalScrollBar()->height(); + for (int c = 0; c < rows; c++){ + total_height += this->verticalHeader()->sectionSize(c); + } +// cout << total_height << endl; + this->setMinimumHeight(total_height); + this->setMaximumHeight(total_height); +// this->adjustSize(); +// this->parentWidget()->adjustSize(); +// this->parentWidget()->parentWidget()->adjustSize(); +} + +void AutoHeightTableWidget::setRowCount(int rows){ + QTableWidget::setRowCount(rows); + update_height(); +} +void AutoHeightTableWidget::insertRow(int row){ + QTableWidget::insertRow(row); + update_height(); +} +void AutoHeightTableWidget::removeRow(int row){ + QTableWidget::removeRow(row); + update_height(); +} + + + + +} diff --git a/Common/Qt/AutoHeightTable.h b/Common/Qt/AutoHeightTable.h index 4027cc2f7b..ec82c22f40 100644 --- a/Common/Qt/AutoHeightTable.h +++ b/Common/Qt/AutoHeightTable.h @@ -1,31 +1,31 @@ -/* QTableWidth with auto-adjusting height. - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AutoHeightTable_H -#define PokemonAutomation_AutoHeightTable_H - -#include - -namespace PokemonAutomation{ - - -class AutoHeightTableWidget : public QTableWidget{ -public: - using QTableWidget::QTableWidget; - - // Suppress mouse-over events since they change focus. - virtual void mouseMoveEvent(QMouseEvent*) override{} - - void setRowCount(int rows); - void insertRow(int row); - void removeRow(int row); - - void update_height(); -}; - - -} -#endif +/* QTableWidth with auto-adjusting height. + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AutoHeightTable_H +#define PokemonAutomation_AutoHeightTable_H + +#include + +namespace PokemonAutomation{ + + +class AutoHeightTableWidget : public QTableWidget{ +public: + using QTableWidget::QTableWidget; + + // Suppress mouse-over events since they change focus. + virtual void mouseMoveEvent(QMouseEvent*) override{} + + void setRowCount(int rows); + void insertRow(int row); + void removeRow(int row); + + void update_height(); +}; + + +} +#endif diff --git a/Common/Qt/AutoWidthLineEdit.cpp b/Common/Qt/AutoWidthLineEdit.cpp index 71ec8ced0e..c5b73966d1 100644 --- a/Common/Qt/AutoWidthLineEdit.cpp +++ b/Common/Qt/AutoWidthLineEdit.cpp @@ -1,34 +1,34 @@ -/* QLineEdit with auto-width sizing. - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "Common/Compiler.h" -#include "AutoWidthLineEdit.h" - -namespace PokemonAutomation{ - - -AutoWidthLineEdit::AutoWidthLineEdit(QWidget* parent) - : QLineEdit(parent) -{ - connect( - this, &QLineEdit::textChanged, - this, [this](const QString& line){ - resize_to_content(); - } - ); -} - -void AutoWidthLineEdit::resize_to_content(){ - QString text = this->text(); - QFontMetrics fm(this->font()); - int pixelsWide = fm.boundingRect(text).width(); - this->setFixedWidth(pixelsWide); - adjustSize(); -} - - -} +/* QLineEdit with auto-width sizing. + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "Common/Compiler.h" +#include "AutoWidthLineEdit.h" + +namespace PokemonAutomation{ + + +AutoWidthLineEdit::AutoWidthLineEdit(QWidget* parent) + : QLineEdit(parent) +{ + connect( + this, &QLineEdit::textChanged, + this, [this](const QString& line){ + resize_to_content(); + } + ); +} + +void AutoWidthLineEdit::resize_to_content(){ + QString text = this->text(); + QFontMetrics fm(this->font()); + int pixelsWide = fm.boundingRect(text).width(); + this->setFixedWidth(pixelsWide); + adjustSize(); +} + + +} diff --git a/Common/Qt/AutoWidthLineEdit.h b/Common/Qt/AutoWidthLineEdit.h index 6fb423c3fc..9fb2be8a12 100644 --- a/Common/Qt/AutoWidthLineEdit.h +++ b/Common/Qt/AutoWidthLineEdit.h @@ -1,25 +1,25 @@ -/* QLineEdit with auto-width sizing. - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AutoWidthLineEdit_H -#define PokemonAutomation_AutoWidthLineEdit_H - -#include - -namespace PokemonAutomation{ - - -class AutoWidthLineEdit : public QLineEdit{ -public: - AutoWidthLineEdit(QWidget* parent); - -private: - void resize_to_content(); - -}; - -} -#endif +/* QLineEdit with auto-width sizing. + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AutoWidthLineEdit_H +#define PokemonAutomation_AutoWidthLineEdit_H + +#include + +namespace PokemonAutomation{ + + +class AutoWidthLineEdit : public QLineEdit{ +public: + AutoWidthLineEdit(QWidget* parent); + +private: + void resize_to_content(); + +}; + +} +#endif diff --git a/Common/Qt/CodeValidator.cpp b/Common/Qt/CodeValidator.cpp index 1cc9b5bf0f..590fd300fe 100644 --- a/Common/Qt/CodeValidator.cpp +++ b/Common/Qt/CodeValidator.cpp @@ -1,59 +1,59 @@ -/* Raid/Trade Code Validator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CodeValidator.h" - -namespace PokemonAutomation{ - - -bool validate_code(size_t digits, const std::string& code){ - if (code.empty()){ - return true; - } - size_t c = 0; - for (const auto& ch : code){ - if (ch == ' ' || ch == '-'){ - continue; - } - if (ch < '0'){ - return false; - } - if (ch > '9'){ - return false; - } - c++; - if (c > digits){ - return false; - } - } - return c == digits; -} - -std::string sanitize_code(size_t digits, const std::string& code){ - std::string ret; - size_t c = 0; - for (const auto& ch : code){ - if (ch == ' ' || ch == '-'){ - continue; - } - if (ch < '0' || ch > '9'){ - throw ParseException(std::string("Invalid code digit: ") + ch); - } - c++; - if (c > digits){ - throw ParseException(std::string("Code is too long: ") + code); - } - ret += ch; - } - if (c < digits){ - throw ParseException(std::string("Code is too short: ") + code); - } - return ret; -} - - -} +/* Raid/Trade Code Validator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CodeValidator.h" + +namespace PokemonAutomation{ + + +bool validate_code(size_t digits, const std::string& code){ + if (code.empty()){ + return true; + } + size_t c = 0; + for (const auto& ch : code){ + if (ch == ' ' || ch == '-'){ + continue; + } + if (ch < '0'){ + return false; + } + if (ch > '9'){ + return false; + } + c++; + if (c > digits){ + return false; + } + } + return c == digits; +} + +std::string sanitize_code(size_t digits, const std::string& code){ + std::string ret; + size_t c = 0; + for (const auto& ch : code){ + if (ch == ' ' || ch == '-'){ + continue; + } + if (ch < '0' || ch > '9'){ + throw ParseException(std::string("Invalid code digit: ") + ch); + } + c++; + if (c > digits){ + throw ParseException(std::string("Code is too long: ") + code); + } + ret += ch; + } + if (c < digits){ + throw ParseException(std::string("Code is too short: ") + code); + } + return ret; +} + + +} diff --git a/Common/Qt/CodeValidator.h b/Common/Qt/CodeValidator.h index 4fe73b3c58..fe981114a6 100644 --- a/Common/Qt/CodeValidator.h +++ b/Common/Qt/CodeValidator.h @@ -1,20 +1,20 @@ -/* Raid/Trade Code Validator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CodeValidator_H -#define PokemonAutomation_CodeValidator_H - -#include - -namespace PokemonAutomation{ - - -bool validate_code(size_t digits, const std::string& code); -std::string sanitize_code(size_t digits, const std::string& code); - - -} -#endif +/* Raid/Trade Code Validator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CodeValidator_H +#define PokemonAutomation_CodeValidator_H + +#include + +namespace PokemonAutomation{ + + +bool validate_code(size_t digits, const std::string& code); +std::string sanitize_code(size_t digits, const std::string& code); + + +} +#endif diff --git a/Common/Qt/CollapsibleGroupBox.cpp b/Common/Qt/CollapsibleGroupBox.cpp index 010d027e65..9ed6953232 100644 --- a/Common/Qt/CollapsibleGroupBox.cpp +++ b/Common/Qt/CollapsibleGroupBox.cpp @@ -1,98 +1,98 @@ -/* Collapsible Group Box - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "CollapsibleGroupBox.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -CollapsibleGroupBox::CollapsibleGroupBox(QWidget& parent, const QString& title, bool expanded) - : QGroupBox(title, &parent) - , m_widget(nullptr) -{ - this->setCheckable(true); - this->setChecked(expanded); - new QVBoxLayout(this); - set_expanded(expanded); - - connect( - this, &QGroupBox::toggled, - this, [this](bool on){ - set_expanded(on); - } - ); -} -void CollapsibleGroupBox::set_expanded(bool expanded){ - if (expanded){ - this->setFlat(false); - this->layout()->setContentsMargins(6, 6, 6, 6); - }else{ - this->setFlat(true); - this->layout()->setContentsMargins(0, 0, 0, 0); - } - if (m_widget != nullptr){ - m_widget->setVisible(expanded); - } -} - -QWidget* CollapsibleGroupBox::widget(){ - return m_widget; -} -void CollapsibleGroupBox::set_widget(QWidget* widget){ - delete m_widget; - if (widget != nullptr){ - widget->setParent(this); - m_widget = widget; - this->layout()->addWidget(widget); - } -} - - - -#if 0 -CollapsibleGroupBox::CollapsibleGroupBox(QWidget& parent, const QString& title) - : QWidget(&parent) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - m_arrow = new QToolButton(this); - m_arrow->setStyleSheet("QToolButton {border: none;}"); - m_arrow->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); - m_arrow->setArrowType(Qt::ArrowType::DownArrow); - m_arrow->setText(title); - m_arrow->setCheckable(true); - m_arrow->setChecked(true); - layout->addWidget(m_arrow); - - m_box = new QGroupBox(this); - layout->addWidget(m_box); - - connect( - m_arrow, &QToolButton::toggled, - this, [m_arrow, m_box](bool on){ - m_arrow->setArrowType(on ? Qt::ArrowType::DownArrow : Qt::ArrowType::RightArrow); - m_box->setVisible(on); - } - ); -} -QWidget* CollapsibleGroupBox::box(){ - return m_box; -} -#endif - - - - - -} +/* Collapsible Group Box + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CollapsibleGroupBox.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +CollapsibleGroupBox::CollapsibleGroupBox(QWidget& parent, const QString& title, bool expanded) + : QGroupBox(title, &parent) + , m_widget(nullptr) +{ + this->setCheckable(true); + this->setChecked(expanded); + new QVBoxLayout(this); + set_expanded(expanded); + + connect( + this, &QGroupBox::toggled, + this, [this](bool on){ + set_expanded(on); + } + ); +} +void CollapsibleGroupBox::set_expanded(bool expanded){ + if (expanded){ + this->setFlat(false); + this->layout()->setContentsMargins(6, 6, 6, 6); + }else{ + this->setFlat(true); + this->layout()->setContentsMargins(0, 0, 0, 0); + } + if (m_widget != nullptr){ + m_widget->setVisible(expanded); + } +} + +QWidget* CollapsibleGroupBox::widget(){ + return m_widget; +} +void CollapsibleGroupBox::set_widget(QWidget* widget){ + delete m_widget; + if (widget != nullptr){ + widget->setParent(this); + m_widget = widget; + this->layout()->addWidget(widget); + } +} + + + +#if 0 +CollapsibleGroupBox::CollapsibleGroupBox(QWidget& parent, const QString& title) + : QWidget(&parent) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + m_arrow = new QToolButton(this); + m_arrow->setStyleSheet("QToolButton {border: none;}"); + m_arrow->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); + m_arrow->setArrowType(Qt::ArrowType::DownArrow); + m_arrow->setText(title); + m_arrow->setCheckable(true); + m_arrow->setChecked(true); + layout->addWidget(m_arrow); + + m_box = new QGroupBox(this); + layout->addWidget(m_box); + + connect( + m_arrow, &QToolButton::toggled, + this, [m_arrow, m_box](bool on){ + m_arrow->setArrowType(on ? Qt::ArrowType::DownArrow : Qt::ArrowType::RightArrow); + m_box->setVisible(on); + } + ); +} +QWidget* CollapsibleGroupBox::box(){ + return m_box; +} +#endif + + + + + +} diff --git a/Common/Qt/CollapsibleGroupBox.h b/Common/Qt/CollapsibleGroupBox.h index 93baa6dd88..354791bffd 100644 --- a/Common/Qt/CollapsibleGroupBox.h +++ b/Common/Qt/CollapsibleGroupBox.h @@ -1,49 +1,49 @@ -/* Collapsible Group Box - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CollapsibleGroupBox_H -#define PokemonAutomation_CollapsibleGroupBox_H - -#include -#include - -class QToolButton; - -namespace PokemonAutomation{ - -class CollapsibleGroupBox : public QGroupBox{ -public: - CollapsibleGroupBox(QWidget& parent, const QString& title, bool expanded = true); - - QWidget* widget(); - void set_widget(QWidget* widget); - -private: - void set_expanded(bool expanded); - - QWidget* m_widget; -}; - - - - -#if 0 -class CollapsibleGroupBox : public QWidget{ -public: - explicit CollapsibleGroupBox(QWidget& parent, const QString& title); - QWidget* box(); - -private: - QToolButton* m_arrow; - QGroupBox* m_box; - -}; -#endif - - - -} -#endif +/* Collapsible Group Box + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CollapsibleGroupBox_H +#define PokemonAutomation_CollapsibleGroupBox_H + +#include +#include + +class QToolButton; + +namespace PokemonAutomation{ + +class CollapsibleGroupBox : public QGroupBox{ +public: + CollapsibleGroupBox(QWidget& parent, const QString& title, bool expanded = true); + + QWidget* widget(); + void set_widget(QWidget* widget); + +private: + void set_expanded(bool expanded); + + QWidget* m_widget; +}; + + + + +#if 0 +class CollapsibleGroupBox : public QWidget{ +public: + explicit CollapsibleGroupBox(QWidget& parent, const QString& title); + QWidget* box(); + +private: + QToolButton* m_arrow; + QGroupBox* m_box; + +}; +#endif + + + +} +#endif diff --git a/Common/Qt/NoWheelComboBox.h b/Common/Qt/NoWheelComboBox.h index 850f532ef5..5fca9f5dae 100644 --- a/Common/Qt/NoWheelComboBox.h +++ b/Common/Qt/NoWheelComboBox.h @@ -1,55 +1,55 @@ -/* ComboBox without mouse wheel scrolling. - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NoWheelComboBox_H -#define PokemonAutomation_NoWheelComboBox_H - -#include - -//#define PA_ENABLE_SIZE_CACHING - -namespace PokemonAutomation{ - - -class NoWheelComboBox : public QComboBox{ -public: - using QComboBox::QComboBox; - - void update_size_cache(){ -#ifdef PA_ENABLE_SIZE_CACHING - m_cached_size = QComboBox::sizeHint(); - m_cached_minimum_size = QComboBox::minimumSizeHint(); -#endif - } - - virtual void wheelEvent(QWheelEvent* event) override{ - QWidget::wheelEvent(event); - } - -#ifdef PA_ENABLE_SIZE_CACHING - virtual QSize sizeHint() const override{ - if (m_cached_size.isValid()){ - return m_cached_size; - } - return QComboBox::sizeHint(); - } - virtual QSize minimumSizeHint() const override{ - if (m_cached_minimum_size.isValid()){ - return m_cached_minimum_size; - } - return QComboBox::minimumSizeHint(); - } - -protected: - QSize m_cached_size; - QSize m_cached_minimum_size; -#endif -}; - - - -} -#endif +/* ComboBox without mouse wheel scrolling. + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NoWheelComboBox_H +#define PokemonAutomation_NoWheelComboBox_H + +#include + +//#define PA_ENABLE_SIZE_CACHING + +namespace PokemonAutomation{ + + +class NoWheelComboBox : public QComboBox{ +public: + using QComboBox::QComboBox; + + void update_size_cache(){ +#ifdef PA_ENABLE_SIZE_CACHING + m_cached_size = QComboBox::sizeHint(); + m_cached_minimum_size = QComboBox::minimumSizeHint(); +#endif + } + + virtual void wheelEvent(QWheelEvent* event) override{ + QWidget::wheelEvent(event); + } + +#ifdef PA_ENABLE_SIZE_CACHING + virtual QSize sizeHint() const override{ + if (m_cached_size.isValid()){ + return m_cached_size; + } + return QComboBox::sizeHint(); + } + virtual QSize minimumSizeHint() const override{ + if (m_cached_minimum_size.isValid()){ + return m_cached_minimum_size; + } + return QComboBox::minimumSizeHint(); + } + +protected: + QSize m_cached_size; + QSize m_cached_minimum_size; +#endif +}; + + + +} +#endif diff --git a/Common/Qt/Options/BatchWidget.cpp b/Common/Qt/Options/BatchWidget.cpp index 4bdc9a9e86..18fbfe0cf7 100644 --- a/Common/Qt/Options/BatchWidget.cpp +++ b/Common/Qt/Options/BatchWidget.cpp @@ -1,65 +1,65 @@ -/* Batch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "BatchWidget.h" - -namespace PokemonAutomation{ - - - -ConfigWidget* BatchOption::make_QtWidget(QWidget& parent){ - return new BatchWidget(parent, *this); -} - - - -BatchWidget::~BatchWidget(){ - m_value.remove_listener(*this); -} -BatchWidget::BatchWidget(QWidget& parent, BatchOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QBoxLayout* options_layout; - if (value.horizontal()){ - options_layout = new QHBoxLayout(this); - options_layout->setAlignment(Qt::AlignLeft); - options_layout->setContentsMargins(0, 0, 0, 0); - }else{ - options_layout = new QVBoxLayout(this); - options_layout->setAlignment(Qt::AlignTop); - options_layout->setContentsMargins(0, 0, 0, 0); - } - - for (auto& item : value.options()){ - m_options.emplace_back(item->make_QtWidget(parent)); - if (value.horizontal()){ - m_options.back()->widget().setContentsMargins(3, 0, 3, 0); - }else{ - m_options.back()->widget().setContentsMargins(0, 3, 0, 3); - } - options_layout->addWidget(&m_options.back()->widget(), 0); - } - - value.add_listener(*this); -} -void BatchWidget::update_value(){ - for (ConfigWidget* item : m_options){ - item->update_value(); - } -} -void BatchWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - -} +/* Batch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "BatchWidget.h" + +namespace PokemonAutomation{ + + + +ConfigWidget* BatchOption::make_QtWidget(QWidget& parent){ + return new BatchWidget(parent, *this); +} + + + +BatchWidget::~BatchWidget(){ + m_value.remove_listener(*this); +} +BatchWidget::BatchWidget(QWidget& parent, BatchOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QBoxLayout* options_layout; + if (value.horizontal()){ + options_layout = new QHBoxLayout(this); + options_layout->setAlignment(Qt::AlignLeft); + options_layout->setContentsMargins(0, 0, 0, 0); + }else{ + options_layout = new QVBoxLayout(this); + options_layout->setAlignment(Qt::AlignTop); + options_layout->setContentsMargins(0, 0, 0, 0); + } + + for (auto& item : value.options()){ + m_options.emplace_back(item->make_QtWidget(parent)); + if (value.horizontal()){ + m_options.back()->widget().setContentsMargins(3, 0, 3, 0); + }else{ + m_options.back()->widget().setContentsMargins(0, 3, 0, 3); + } + options_layout->addWidget(&m_options.back()->widget(), 0); + } + + value.add_listener(*this); +} +void BatchWidget::update_value(){ + for (ConfigWidget* item : m_options){ + item->update_value(); + } +} +void BatchWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + +} diff --git a/Common/Qt/Options/BatchWidget.h b/Common/Qt/Options/BatchWidget.h index b1f8bd0287..f163ac1208 100644 --- a/Common/Qt/Options/BatchWidget.h +++ b/Common/Qt/Options/BatchWidget.h @@ -1,35 +1,35 @@ -/* Batch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_BatchWidget_H -#define PokemonAutomation_Options_BatchWidget_H - -#include -#include "Common/Cpp/Options/BatchOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -class BatchWidget : public QWidget, public ConfigWidget{ -public: - ~BatchWidget(); - BatchWidget(QWidget& parent, BatchOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -protected: - BatchOption& m_value; - std::vector m_options; -}; - - - - -} -#endif +/* Batch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_BatchWidget_H +#define PokemonAutomation_Options_BatchWidget_H + +#include +#include "Common/Cpp/Options/BatchOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +class BatchWidget : public QWidget, public ConfigWidget{ +public: + ~BatchWidget(); + BatchWidget(QWidget& parent, BatchOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +protected: + BatchOption& m_value; + std::vector m_options; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/BooleanCheckBoxWidget.cpp b/Common/Qt/Options/BooleanCheckBoxWidget.cpp index 045ab359d9..a8d81a8ec6 100644 --- a/Common/Qt/Options/BooleanCheckBoxWidget.cpp +++ b/Common/Qt/Options/BooleanCheckBoxWidget.cpp @@ -1,126 +1,126 @@ -/* Boolean Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "BooleanCheckBoxWidget.h" - -namespace PokemonAutomation{ - - - - -ConfigWidget* BooleanCheckBoxCell::make_QtWidget(QWidget& parent){ - return new BooleanCheckBoxCellWidget(parent, *this); -} -ConfigWidget* BooleanCheckBoxOption::make_QtWidget(QWidget& parent){ - return new BooleanCheckBoxOptionWidget(parent, *this); -} - - - - -BooleanCheckBoxCellWidget::~BooleanCheckBoxCellWidget(){ - m_value.remove_listener(*this); -} -BooleanCheckBoxCellWidget::BooleanCheckBoxCellWidget(QWidget& parent, BooleanCheckBoxCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setAlignment(Qt::AlignHCenter); - layout->setContentsMargins(0, 0, 0, 0); - m_box = new QCheckBox(this); - m_box->setChecked(m_value); - layout->addWidget(m_box); -#if QT_VERSION < 0x060700 - connect( - m_box, &QCheckBox::stateChanged, - this, [this](int){ - m_value = m_box->isChecked(); - } - ); -#else - connect( - m_box, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState){ - m_value = m_box->isChecked(); - } - ); -#endif - value.add_listener(*this); -} -void BooleanCheckBoxCellWidget::update_value(){ - if (m_value != m_box->isChecked()){ - m_box->setChecked(m_value); - } -} -void BooleanCheckBoxCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - -BooleanCheckBoxOptionWidget::~BooleanCheckBoxOptionWidget(){ - m_value.remove_listener(*this); -} -BooleanCheckBoxOptionWidget::BooleanCheckBoxOptionWidget(QWidget& parent, BooleanCheckBoxOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 3); - m_box = new QCheckBox(this); - m_box->setChecked(m_value); - layout->addWidget(m_box, 1); -#if QT_VERSION < 0x060700 - connect( - m_box, &QCheckBox::stateChanged, - this, [this](int){ - m_value = m_box->isChecked(); - } - ); -#else - connect( - m_box, &QCheckBox::checkStateChanged, - this, [this](int){ - m_value = m_box->isChecked(); - } - ); -#endif - value.add_listener(*this); -} -void BooleanCheckBoxOptionWidget::update_value(){ - if (m_value != m_box->isChecked()){ - m_box->setChecked(m_value); - } -} -void BooleanCheckBoxOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -} - +/* Boolean Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "BooleanCheckBoxWidget.h" + +namespace PokemonAutomation{ + + + + +ConfigWidget* BooleanCheckBoxCell::make_QtWidget(QWidget& parent){ + return new BooleanCheckBoxCellWidget(parent, *this); +} +ConfigWidget* BooleanCheckBoxOption::make_QtWidget(QWidget& parent){ + return new BooleanCheckBoxOptionWidget(parent, *this); +} + + + + +BooleanCheckBoxCellWidget::~BooleanCheckBoxCellWidget(){ + m_value.remove_listener(*this); +} +BooleanCheckBoxCellWidget::BooleanCheckBoxCellWidget(QWidget& parent, BooleanCheckBoxCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setAlignment(Qt::AlignHCenter); + layout->setContentsMargins(0, 0, 0, 0); + m_box = new QCheckBox(this); + m_box->setChecked(m_value); + layout->addWidget(m_box); +#if QT_VERSION < 0x060700 + connect( + m_box, &QCheckBox::stateChanged, + this, [this](int){ + m_value = m_box->isChecked(); + } + ); +#else + connect( + m_box, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState){ + m_value = m_box->isChecked(); + } + ); +#endif + value.add_listener(*this); +} +void BooleanCheckBoxCellWidget::update_value(){ + if (m_value != m_box->isChecked()){ + m_box->setChecked(m_value); + } +} +void BooleanCheckBoxCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + +BooleanCheckBoxOptionWidget::~BooleanCheckBoxOptionWidget(){ + m_value.remove_listener(*this); +} +BooleanCheckBoxOptionWidget::BooleanCheckBoxOptionWidget(QWidget& parent, BooleanCheckBoxOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 3); + m_box = new QCheckBox(this); + m_box->setChecked(m_value); + layout->addWidget(m_box, 1); +#if QT_VERSION < 0x060700 + connect( + m_box, &QCheckBox::stateChanged, + this, [this](int){ + m_value = m_box->isChecked(); + } + ); +#else + connect( + m_box, &QCheckBox::checkStateChanged, + this, [this](int){ + m_value = m_box->isChecked(); + } + ); +#endif + value.add_listener(*this); +} +void BooleanCheckBoxOptionWidget::update_value(){ + if (m_value != m_box->isChecked()){ + m_box->setChecked(m_value); + } +} +void BooleanCheckBoxOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +} + diff --git a/Common/Qt/Options/BooleanCheckBoxWidget.h b/Common/Qt/Options/BooleanCheckBoxWidget.h index 5ab0b72e32..e561eb4d36 100644 --- a/Common/Qt/Options/BooleanCheckBoxWidget.h +++ b/Common/Qt/Options/BooleanCheckBoxWidget.h @@ -1,49 +1,49 @@ -/* Boolean Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_BooleanCheckBoxWidget_H -#define PokemonAutomation_BooleanCheckBoxWidget_H - -#include -#include "ConfigWidget.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" - -namespace PokemonAutomation{ - - - -class BooleanCheckBoxCellWidget : public QWidget, public ConfigWidget{ -public: - ~BooleanCheckBoxCellWidget(); - BooleanCheckBoxCellWidget(QWidget& parent, BooleanCheckBoxCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - BooleanCheckBoxCell& m_value; - QCheckBox* m_box; -}; - - - - -class BooleanCheckBoxOptionWidget : public QWidget, public ConfigWidget{ -public: - ~BooleanCheckBoxOptionWidget(); - BooleanCheckBoxOptionWidget(QWidget& parent, BooleanCheckBoxOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - BooleanCheckBoxOption& m_value; - QCheckBox* m_box; -}; - - -} -#endif +/* Boolean Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_BooleanCheckBoxWidget_H +#define PokemonAutomation_BooleanCheckBoxWidget_H + +#include +#include "ConfigWidget.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" + +namespace PokemonAutomation{ + + + +class BooleanCheckBoxCellWidget : public QWidget, public ConfigWidget{ +public: + ~BooleanCheckBoxCellWidget(); + BooleanCheckBoxCellWidget(QWidget& parent, BooleanCheckBoxCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + BooleanCheckBoxCell& m_value; + QCheckBox* m_box; +}; + + + + +class BooleanCheckBoxOptionWidget : public QWidget, public ConfigWidget{ +public: + ~BooleanCheckBoxOptionWidget(); + BooleanCheckBoxOptionWidget(QWidget& parent, BooleanCheckBoxOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + BooleanCheckBoxOption& m_value; + QCheckBox* m_box; +}; + + +} +#endif diff --git a/Common/Qt/Options/ButtonWidget.cpp b/Common/Qt/Options/ButtonWidget.cpp index 6fb0baee43..242e292ad2 100644 --- a/Common/Qt/Options/ButtonWidget.cpp +++ b/Common/Qt/Options/ButtonWidget.cpp @@ -1,152 +1,152 @@ -/* Boolean Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "ButtonWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget* ButtonCell::make_QtWidget(QWidget& parent){ - return new ButtonCellWidget(parent, *this); -} -ConfigWidget* ButtonOption::make_QtWidget(QWidget& parent){ - return new ButtonOptionWidget(parent, *this); -} - - -ButtonCellWidget::~ButtonCellWidget(){ - m_value.remove_listener(*this); -} -ButtonCellWidget::ButtonCellWidget(QWidget& parent, ButtonCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) - , m_button(new QPushButton(this)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(m_button); - - ButtonCellWidget::update_value(); - -// cout << "height = " << this->height() << endl; - - connect( - m_button, &QPushButton::pressed, - this, [this]{ - m_value.press_button(); -// cout << "Press: " << this->font().pointSize() << endl; -// cout << "height = " << this->height() << endl; - } - ); - value.add_listener(*this); -} - -void ButtonCellWidget::update_value(){ - m_button->setText(QString::fromStdString(m_value.text())); - - int button_size = m_value.button_height(); - if (button_size > 0){ - m_button->setFixedHeight(button_size); - } - - int text_size = m_value.text_size(); - if (text_size > 0){ - QFont font = m_button->font(); - font.setPointSize(text_size); -// font.setPointSize(16); - m_button->setFont(font); -// cout << "Post set: " << this->font().pointSize() << endl; - } -// cout << "Update: " << this->font().pointSize() << endl; -} -void ButtonCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - -ButtonOptionWidget::~ButtonOptionWidget(){ - m_value.remove_listener(*this); -} -ButtonOptionWidget::ButtonOptionWidget(QWidget& parent, ButtonOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) - , m_label(new QLabel(this)) - , m_button(new QPushButton(this)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - m_label->setWordWrap(true); - m_label->setTextFormat(Qt::RichText); - m_label->setTextInteractionFlags(Qt::TextBrowserInteraction); - m_label->setOpenExternalLinks(true); - layout->addWidget(m_label); - - layout->addWidget(m_button); - - ButtonOptionWidget::update_value(); - -// cout << "height = " << this->height() << endl; - - connect( - m_button, &QPushButton::pressed, - this, [this]{ - m_value.press_button(); -// cout << "Press: " << this->font().pointSize() << endl; -// cout << "height = " << this->height() << endl; - } - ); - value.add_listener(*this); -} - - -void ButtonOptionWidget::update_value(){ - m_label->setText(QString::fromStdString(m_value.label())); - m_button->setEnabled(m_value.is_enabled()); - m_button->setText(QString::fromStdString(m_value.text())); - - int button_size = m_value.button_height(); - if (button_size > 0){ - m_button->setFixedHeight(button_size); - } - - int text_size = m_value.text_size(); - if (text_size > 0){ - QFont font = m_button->font(); - font.setPointSize(text_size); -// font.setPointSize(16); - m_button->setFont(font); -// cout << "Post set: " << this->font().pointSize() << endl; - } -// cout << "Update: " << this->font().pointSize() << endl; -} -void ButtonOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - -} +/* Boolean Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "ButtonWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget* ButtonCell::make_QtWidget(QWidget& parent){ + return new ButtonCellWidget(parent, *this); +} +ConfigWidget* ButtonOption::make_QtWidget(QWidget& parent){ + return new ButtonOptionWidget(parent, *this); +} + + +ButtonCellWidget::~ButtonCellWidget(){ + m_value.remove_listener(*this); +} +ButtonCellWidget::ButtonCellWidget(QWidget& parent, ButtonCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) + , m_button(new QPushButton(this)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(m_button); + + ButtonCellWidget::update_value(); + +// cout << "height = " << this->height() << endl; + + connect( + m_button, &QPushButton::pressed, + this, [this]{ + m_value.press_button(); +// cout << "Press: " << this->font().pointSize() << endl; +// cout << "height = " << this->height() << endl; + } + ); + value.add_listener(*this); +} + +void ButtonCellWidget::update_value(){ + m_button->setText(QString::fromStdString(m_value.text())); + + int button_size = m_value.button_height(); + if (button_size > 0){ + m_button->setFixedHeight(button_size); + } + + int text_size = m_value.text_size(); + if (text_size > 0){ + QFont font = m_button->font(); + font.setPointSize(text_size); +// font.setPointSize(16); + m_button->setFont(font); +// cout << "Post set: " << this->font().pointSize() << endl; + } +// cout << "Update: " << this->font().pointSize() << endl; +} +void ButtonCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + +ButtonOptionWidget::~ButtonOptionWidget(){ + m_value.remove_listener(*this); +} +ButtonOptionWidget::ButtonOptionWidget(QWidget& parent, ButtonOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) + , m_label(new QLabel(this)) + , m_button(new QPushButton(this)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + m_label->setWordWrap(true); + m_label->setTextFormat(Qt::RichText); + m_label->setTextInteractionFlags(Qt::TextBrowserInteraction); + m_label->setOpenExternalLinks(true); + layout->addWidget(m_label); + + layout->addWidget(m_button); + + ButtonOptionWidget::update_value(); + +// cout << "height = " << this->height() << endl; + + connect( + m_button, &QPushButton::pressed, + this, [this]{ + m_value.press_button(); +// cout << "Press: " << this->font().pointSize() << endl; +// cout << "height = " << this->height() << endl; + } + ); + value.add_listener(*this); +} + + +void ButtonOptionWidget::update_value(){ + m_label->setText(QString::fromStdString(m_value.label())); + m_button->setEnabled(m_value.is_enabled()); + m_button->setText(QString::fromStdString(m_value.text())); + + int button_size = m_value.button_height(); + if (button_size > 0){ + m_button->setFixedHeight(button_size); + } + + int text_size = m_value.text_size(); + if (text_size > 0){ + QFont font = m_button->font(); + font.setPointSize(text_size); +// font.setPointSize(16); + m_button->setFont(font); +// cout << "Post set: " << this->font().pointSize() << endl; + } +// cout << "Update: " << this->font().pointSize() << endl; +} +void ButtonOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + +} diff --git a/Common/Qt/Options/ButtonWidget.h b/Common/Qt/Options/ButtonWidget.h index 9d75361dbc..98a799152d 100644 --- a/Common/Qt/Options/ButtonWidget.h +++ b/Common/Qt/Options/ButtonWidget.h @@ -1,55 +1,55 @@ -/* Button Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_ButtonWidget_H -#define PokemonAutomation_Options_ButtonWidget_H - -#include -#include -#include -#include "Common/Cpp/Options/ButtonOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -class ButtonCellWidget : public QWidget, public ConfigWidget{ -public: - ~ButtonCellWidget(); - ButtonCellWidget(QWidget& parent, ButtonCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - ButtonCell& m_value; - QPushButton* m_button; -}; - - - - - -class ButtonOptionWidget : public QWidget, public ConfigWidget{ -public: - ~ButtonOptionWidget(); - ButtonOptionWidget(QWidget& parent, ButtonOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - ButtonOption& m_value; - QLabel* m_label; - QPushButton* m_button; -}; - - - - -} -#endif +/* Button Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_ButtonWidget_H +#define PokemonAutomation_Options_ButtonWidget_H + +#include +#include +#include +#include "Common/Cpp/Options/ButtonOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +class ButtonCellWidget : public QWidget, public ConfigWidget{ +public: + ~ButtonCellWidget(); + ButtonCellWidget(QWidget& parent, ButtonCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + ButtonCell& m_value; + QPushButton* m_button; +}; + + + + + +class ButtonOptionWidget : public QWidget, public ConfigWidget{ +public: + ~ButtonOptionWidget(); + ButtonOptionWidget(QWidget& parent, ButtonOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + ButtonOption& m_value; + QLabel* m_label; + QPushButton* m_button; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/ColorWidget.cpp b/Common/Qt/Options/ColorWidget.cpp index d86918c5de..6bd88f5900 100644 --- a/Common/Qt/Options/ColorWidget.cpp +++ b/Common/Qt/Options/ColorWidget.cpp @@ -1,67 +1,67 @@ -/* Color Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "QHBoxLayout" -#include "ColorWidget.h" - -namespace PokemonAutomation{ - - -ConfigWidget* ColorCell::make_QtWidget(QWidget& parent){ - return new ColorCellWidget(parent, *this); -} - - -ColorCellWidget::~ColorCellWidget(){ - m_value.remove_listener(*this); -} -ColorCellWidget::ColorCellWidget(QWidget& parent, ColorCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 5, 0); - - QString str = QString::fromStdString(value.to_str()); - - m_line_edit = new QLineEdit(str, this); - m_line_edit->setFixedWidth(60); - layout->addWidget(m_line_edit); - - m_box = new QLabel(this); - m_box->setTextFormat(Qt::RichText); - layout->addWidget(m_box); - - ColorCellWidget::update_value(); - - connect( - m_line_edit, &QLineEdit::editingFinished, - this, [this](){ - m_value.set(m_line_edit->text().toStdString()); - update_value(); - } - ); - - m_value.add_listener(*this); -} -void ColorCellWidget::update_value(){ - QString str = QString::fromStdString(m_value.to_str()); - m_line_edit->setText(str); - m_box->setText(""); -} -void ColorCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - -} +/* Color Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "QHBoxLayout" +#include "ColorWidget.h" + +namespace PokemonAutomation{ + + +ConfigWidget* ColorCell::make_QtWidget(QWidget& parent){ + return new ColorCellWidget(parent, *this); +} + + +ColorCellWidget::~ColorCellWidget(){ + m_value.remove_listener(*this); +} +ColorCellWidget::ColorCellWidget(QWidget& parent, ColorCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 5, 0); + + QString str = QString::fromStdString(value.to_str()); + + m_line_edit = new QLineEdit(str, this); + m_line_edit->setFixedWidth(60); + layout->addWidget(m_line_edit); + + m_box = new QLabel(this); + m_box->setTextFormat(Qt::RichText); + layout->addWidget(m_box); + + ColorCellWidget::update_value(); + + connect( + m_line_edit, &QLineEdit::editingFinished, + this, [this](){ + m_value.set(m_line_edit->text().toStdString()); + update_value(); + } + ); + + m_value.add_listener(*this); +} +void ColorCellWidget::update_value(){ + QString str = QString::fromStdString(m_value.to_str()); + m_line_edit->setText(str); + m_box->setText(""); +} +void ColorCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + +} diff --git a/Common/Qt/Options/ColorWidget.h b/Common/Qt/Options/ColorWidget.h index d800804faa..0ed7343359 100644 --- a/Common/Qt/Options/ColorWidget.h +++ b/Common/Qt/Options/ColorWidget.h @@ -1,40 +1,40 @@ -/* Color Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ColorWidget_H -#define PokemonAutomation_ColorWidget_H - -#include -#include "Common/Cpp/Options/ColorOption.h" -#include "ConfigWidget.h" - -class QLabel; -class QLineEdit; - -namespace PokemonAutomation{ - - - -class ColorCellWidget : public QWidget, public ConfigWidget{ -public: - ~ColorCellWidget(); - ColorCellWidget(QWidget& parent, ColorCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - - -private: - ColorCell& m_value; - QLineEdit* m_line_edit; - QLabel* m_box; -}; - - - - -} -#endif +/* Color Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ColorWidget_H +#define PokemonAutomation_ColorWidget_H + +#include +#include "Common/Cpp/Options/ColorOption.h" +#include "ConfigWidget.h" + +class QLabel; +class QLineEdit; + +namespace PokemonAutomation{ + + + +class ColorCellWidget : public QWidget, public ConfigWidget{ +public: + ~ColorCellWidget(); + ColorCellWidget(QWidget& parent, ColorCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + + +private: + ColorCell& m_value; + QLineEdit* m_line_edit; + QLabel* m_box; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/ConfigWidget.cpp b/Common/Qt/Options/ConfigWidget.cpp index c1242475f8..bf0482ab1e 100644 --- a/Common/Qt/Options/ConfigWidget.cpp +++ b/Common/Qt/Options/ConfigWidget.cpp @@ -1,89 +1,89 @@ -/* Config Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ConfigWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget::~ConfigWidget(){ - m_value.remove_listener(*this); -} -ConfigWidget::ConfigWidget(ConfigOption& m_value) - : m_value(m_value) -{ - m_value.add_listener(*this); -} -ConfigWidget::ConfigWidget(ConfigOption& m_value, QWidget& widget) - : m_value(m_value) - , m_widget(&widget) -{ -// cout << "ConfigWidget::ConfigWidget(): " << (int)m_value.visibility() << endl; - m_program_is_running = false; - ConfigWidget::update_visibility(); - m_value.add_listener(*this); -} -void ConfigWidget::update_visibility(){ - auto scope = m_value.check_scope(); - m_value.check_usage(); - if (m_widget == nullptr){ - return; - } -// cout << "update_visibility = " << program_is_running << endl; -// if (!m_program_is_running){ -// cout << "asdf" << endl; -// } -// cout << "lock_while_program_is_running = " << m_value.lock_while_program_is_running() << endl; -// cout << "program_is_running = " << m_program_is_running << endl; -// cout << "ConfigWidget::update_visibility(): " << (int)m_value.visibility() << endl; - switch (m_value.visibility()){ - case ConfigOptionState::ENABLED: - m_widget->setEnabled(m_value.lock_mode() != LockMode::LOCK_WHILE_RUNNING || !m_program_is_running); - m_widget->setVisible(true); - break; - case ConfigOptionState::DISABLED: - m_widget->setEnabled(false); - m_widget->setVisible(true); - break; - case ConfigOptionState::HIDDEN: - m_widget->setEnabled(false); - m_widget->setVisible(false); - break; - } -} -void ConfigWidget::update_visibility(bool program_is_running){ - auto scope = m_value.check_scope(); - m_program_is_running = program_is_running; - update_visibility(); -} -void ConfigWidget::update_all(bool program_is_running){ - auto scope = m_value.check_scope(); - update_value(); - update_visibility(program_is_running); -} - -void ConfigWidget::on_config_visibility_changed(){ - auto scope = m_value.check_scope(); - QMetaObject::invokeMethod(m_widget, [this]{ - update_visibility(); - }, Qt::QueuedConnection); -} -void ConfigWidget::on_program_state_changed(bool program_is_running){ - auto scope = m_value.check_scope(); - QMetaObject::invokeMethod(m_widget, [this, program_is_running]{ - update_visibility(program_is_running); - }, Qt::QueuedConnection); -} - - - - -} +/* Config Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ConfigWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget::~ConfigWidget(){ + m_value.remove_listener(*this); +} +ConfigWidget::ConfigWidget(ConfigOption& m_value) + : m_value(m_value) +{ + m_value.add_listener(*this); +} +ConfigWidget::ConfigWidget(ConfigOption& m_value, QWidget& widget) + : m_value(m_value) + , m_widget(&widget) +{ +// cout << "ConfigWidget::ConfigWidget(): " << (int)m_value.visibility() << endl; + m_program_is_running = false; + ConfigWidget::update_visibility(); + m_value.add_listener(*this); +} +void ConfigWidget::update_visibility(){ + auto scope = m_value.check_scope(); + m_value.check_usage(); + if (m_widget == nullptr){ + return; + } +// cout << "update_visibility = " << program_is_running << endl; +// if (!m_program_is_running){ +// cout << "asdf" << endl; +// } +// cout << "lock_while_program_is_running = " << m_value.lock_while_program_is_running() << endl; +// cout << "program_is_running = " << m_program_is_running << endl; +// cout << "ConfigWidget::update_visibility(): " << (int)m_value.visibility() << endl; + switch (m_value.visibility()){ + case ConfigOptionState::ENABLED: + m_widget->setEnabled(m_value.lock_mode() != LockMode::LOCK_WHILE_RUNNING || !m_program_is_running); + m_widget->setVisible(true); + break; + case ConfigOptionState::DISABLED: + m_widget->setEnabled(false); + m_widget->setVisible(true); + break; + case ConfigOptionState::HIDDEN: + m_widget->setEnabled(false); + m_widget->setVisible(false); + break; + } +} +void ConfigWidget::update_visibility(bool program_is_running){ + auto scope = m_value.check_scope(); + m_program_is_running = program_is_running; + update_visibility(); +} +void ConfigWidget::update_all(bool program_is_running){ + auto scope = m_value.check_scope(); + update_value(); + update_visibility(program_is_running); +} + +void ConfigWidget::on_config_visibility_changed(){ + auto scope = m_value.check_scope(); + QMetaObject::invokeMethod(m_widget, [this]{ + update_visibility(); + }, Qt::QueuedConnection); +} +void ConfigWidget::on_program_state_changed(bool program_is_running){ + auto scope = m_value.check_scope(); + QMetaObject::invokeMethod(m_widget, [this, program_is_running]{ + update_visibility(program_is_running); + }, Qt::QueuedConnection); +} + + + + +} diff --git a/Common/Qt/Options/ConfigWidget.h b/Common/Qt/Options/ConfigWidget.h index 4d27c505e9..3d84b0b610 100644 --- a/Common/Qt/Options/ConfigWidget.h +++ b/Common/Qt/Options/ConfigWidget.h @@ -1,45 +1,45 @@ -/* Config Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ConfigWidget_H -#define PokemonAutomation_ConfigWidget_H - -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ - - -class ConfigWidget : protected ConfigOption::Listener{ -public: - virtual ~ConfigWidget(); - ConfigWidget(ConfigOption& m_value); - ConfigWidget(ConfigOption& m_value, QWidget& widget); - - const ConfigOption& option() const{ return m_value; } - ConfigOption& option(){ return m_value; } - - QWidget& widget(){ return *m_widget; } - - // Needs to be called on the UI thread. - virtual void update_value(){} - virtual void update_visibility(); - void update_visibility(bool program_is_running); - void update_all(bool program_is_running); - -protected: - virtual void on_config_visibility_changed() override; - virtual void on_program_state_changed(bool program_is_running) override; - -protected: - ConfigOption& m_value; - QWidget* m_widget = nullptr; - bool m_program_is_running = false; -}; - - - -} -#endif +/* Config Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ConfigWidget_H +#define PokemonAutomation_ConfigWidget_H + +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ + + +class ConfigWidget : protected ConfigOption::Listener{ +public: + virtual ~ConfigWidget(); + ConfigWidget(ConfigOption& m_value); + ConfigWidget(ConfigOption& m_value, QWidget& widget); + + const ConfigOption& option() const{ return m_value; } + ConfigOption& option(){ return m_value; } + + QWidget& widget(){ return *m_widget; } + + // Needs to be called on the UI thread. + virtual void update_value(){} + virtual void update_visibility(); + void update_visibility(bool program_is_running); + void update_all(bool program_is_running); + +protected: + virtual void on_config_visibility_changed() override; + virtual void on_program_state_changed(bool program_is_running) override; + +protected: + ConfigOption& m_value; + QWidget* m_widget = nullptr; + bool m_program_is_running = false; +}; + + + +} +#endif diff --git a/Common/Qt/Options/DateWidget.cpp b/Common/Qt/Options/DateWidget.cpp index eeda42b60d..8cd368e3d3 100644 --- a/Common/Qt/Options/DateWidget.cpp +++ b/Common/Qt/Options/DateWidget.cpp @@ -1,133 +1,133 @@ -/* Date Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "DateWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - -ConfigWidget* DateTimeCell::make_QtWidget(QWidget& parent){ - return new DateTimeCellWidget(parent, *this); -} -ConfigWidget* DateTimeOption::make_QtWidget(QWidget& parent){ - return new DateTimeOptionWidget(parent, *this); -} - - - - - -QDateTime DateTime_to_QDateTime(const DateTime& date){ - return QDateTime( - QDate(date.year, date.month, date.day), - QTime( - std::max(date.hour, 0), - std::max(date.minute, 0), - std::max(date.second, 0) - ) - ); -} -DateTime QDateTime_to_DateTime(const QDateTime& date, DateTimeOption::Level level){ - DateTime ret; - QDate qdate = date.date(); - ret.year = (int16_t)qdate.year(); - ret.month = (int8_t)qdate.month(); - ret.day = (int8_t)qdate.day(); - - if (level < DateTimeOption::DATE_HOUR_MIN){ - return ret; - } - - QTime qtime = date.time(); - ret.hour = (int8_t)qtime.hour(); - ret.minute = (int8_t)qtime.minute(); - - if (level < DateTimeOption::DATE_HOUR_MIN_SEC){ - return ret; - } - - ret.second = (int8_t)qtime.second(); - - return ret; -} - - - -DateTimeCellWidget::~DateTimeCellWidget(){ - m_value.remove_listener(*this); -} -DateTimeCellWidget::DateTimeCellWidget(QWidget& parent, DateTimeCell& value) - : QDateTimeEdit(DateTime_to_QDateTime(value.get()), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - switch (value.level()){ - case DateTimeOption::DATE: - this->setDisplayFormat("MMMM d, yyyy"); - break; - case DateTimeOption::DATE_HOUR_MIN: - this->setDisplayFormat("MMMM d, yyyy hh:mm"); - break; - case DateTimeOption::DATE_HOUR_MIN_SEC: - this->setDisplayFormat("MMMM d, yyyy hh:mm:ss"); - break; - } - this->setMinimumDateTime(DateTime_to_QDateTime(value.min_value())); - this->setMaximumDateTime(DateTime_to_QDateTime(value.max_value())); - -// cout << "Max time = " << m_date_edit->maximumTime().toString().toStdString() << endl; - - connect( - this, &QDateTimeEdit::dateTimeChanged, - this, [this](const QDateTime& date){ - m_value.set(QDateTime_to_DateTime(date, m_value.level())); - } - ); - - value.add_listener(*this); -} -void DateTimeCellWidget::update_value(){ - this->setDateTime(DateTime_to_QDateTime(m_value.get())); -} -void DateTimeCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - -DateTimeOptionWidget::DateTimeOptionWidget(QWidget& parent, DateTimeOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - - m_date_edit = new DateTimeCellWidget(*this, value); - layout->addWidget(m_date_edit, 1); -} - - - - - -} +/* Date Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "DateWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +ConfigWidget* DateTimeCell::make_QtWidget(QWidget& parent){ + return new DateTimeCellWidget(parent, *this); +} +ConfigWidget* DateTimeOption::make_QtWidget(QWidget& parent){ + return new DateTimeOptionWidget(parent, *this); +} + + + + + +QDateTime DateTime_to_QDateTime(const DateTime& date){ + return QDateTime( + QDate(date.year, date.month, date.day), + QTime( + std::max(date.hour, 0), + std::max(date.minute, 0), + std::max(date.second, 0) + ) + ); +} +DateTime QDateTime_to_DateTime(const QDateTime& date, DateTimeOption::Level level){ + DateTime ret; + QDate qdate = date.date(); + ret.year = (int16_t)qdate.year(); + ret.month = (int8_t)qdate.month(); + ret.day = (int8_t)qdate.day(); + + if (level < DateTimeOption::DATE_HOUR_MIN){ + return ret; + } + + QTime qtime = date.time(); + ret.hour = (int8_t)qtime.hour(); + ret.minute = (int8_t)qtime.minute(); + + if (level < DateTimeOption::DATE_HOUR_MIN_SEC){ + return ret; + } + + ret.second = (int8_t)qtime.second(); + + return ret; +} + + + +DateTimeCellWidget::~DateTimeCellWidget(){ + m_value.remove_listener(*this); +} +DateTimeCellWidget::DateTimeCellWidget(QWidget& parent, DateTimeCell& value) + : QDateTimeEdit(DateTime_to_QDateTime(value.get()), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + switch (value.level()){ + case DateTimeOption::DATE: + this->setDisplayFormat("MMMM d, yyyy"); + break; + case DateTimeOption::DATE_HOUR_MIN: + this->setDisplayFormat("MMMM d, yyyy hh:mm"); + break; + case DateTimeOption::DATE_HOUR_MIN_SEC: + this->setDisplayFormat("MMMM d, yyyy hh:mm:ss"); + break; + } + this->setMinimumDateTime(DateTime_to_QDateTime(value.min_value())); + this->setMaximumDateTime(DateTime_to_QDateTime(value.max_value())); + +// cout << "Max time = " << m_date_edit->maximumTime().toString().toStdString() << endl; + + connect( + this, &QDateTimeEdit::dateTimeChanged, + this, [this](const QDateTime& date){ + m_value.set(QDateTime_to_DateTime(date, m_value.level())); + } + ); + + value.add_listener(*this); +} +void DateTimeCellWidget::update_value(){ + this->setDateTime(DateTime_to_QDateTime(m_value.get())); +} +void DateTimeCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + +DateTimeOptionWidget::DateTimeOptionWidget(QWidget& parent, DateTimeOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + + m_date_edit = new DateTimeCellWidget(*this, value); + layout->addWidget(m_date_edit, 1); +} + + + + + +} diff --git a/Common/Qt/Options/DateWidget.h b/Common/Qt/Options/DateWidget.h index 095c104ee6..5540fd3176 100644 --- a/Common/Qt/Options/DateWidget.h +++ b/Common/Qt/Options/DateWidget.h @@ -1,46 +1,46 @@ -/* Date Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_DateWidget_H -#define PokemonAutomation_Options_DateWidget_H - -#include -#include -#include "Common/Cpp/Options/DateOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -class DateTimeCellWidget : public QDateTimeEdit, public ConfigWidget{ -public: - ~DateTimeCellWidget(); - DateTimeCellWidget(QWidget& parent, DateTimeCell& value); - - virtual void wheelEvent(QWheelEvent* event) override{ - QWidget::wheelEvent(event); - } - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - DateTimeCell& m_value; -}; - - -class DateTimeOptionWidget : public QWidget, public ConfigWidget{ -public: - DateTimeOptionWidget(QWidget& parent, DateTimeOption& value); - -private: - DateTimeCellWidget* m_date_edit; -}; - - -} -#endif +/* Date Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_DateWidget_H +#define PokemonAutomation_Options_DateWidget_H + +#include +#include +#include "Common/Cpp/Options/DateOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +class DateTimeCellWidget : public QDateTimeEdit, public ConfigWidget{ +public: + ~DateTimeCellWidget(); + DateTimeCellWidget(QWidget& parent, DateTimeCell& value); + + virtual void wheelEvent(QWheelEvent* event) override{ + QWidget::wheelEvent(event); + } + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + DateTimeCell& m_value; +}; + + +class DateTimeOptionWidget : public QWidget, public ConfigWidget{ +public: + DateTimeOptionWidget(QWidget& parent, DateTimeOption& value); + +private: + DateTimeCellWidget* m_date_edit; +}; + + +} +#endif diff --git a/Common/Qt/Options/EditableTableWidget.cpp b/Common/Qt/Options/EditableTableWidget.cpp index 12a5451140..aff77a990f 100644 --- a/Common/Qt/Options/EditableTableWidget.cpp +++ b/Common/Qt/Options/EditableTableWidget.cpp @@ -1,334 +1,334 @@ -/* Editable Table Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/AutoHeightTable.h" -#include "EditableTableWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget* EditableTableOption::make_QtWidget(QWidget& parent){ - return new EditableTableWidget(parent, *this); -} - - - -EditableTableWidget::~EditableTableWidget(){ - m_value.remove_listener(*this); - delete m_table; -} -EditableTableWidget::EditableTableWidget(QWidget& parent, EditableTableOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) - , m_table(nullptr) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - if (!value.label().empty()){ - QLabel* label = new QLabel(QString::fromStdString(value.label()), this); - label->setWordWrap(true); - label->setTextFormat(Qt::RichText); - label->setTextInteractionFlags(Qt::TextBrowserInteraction); - label->setOpenExternalLinks(true); - layout->addWidget(label); - } - - m_table = new AutoHeightTableWidget(this); - layout->addWidget(m_table, 0, Qt::AlignTop); -// m_table->setMouseTracking(false); - - QStringList header; - for (const std::string& name : m_value.make_header()){ - header << QString::fromStdString(name); - } - header << "" << "" << ""; - m_table->setColumnCount(int(header.size())); - m_table->setHorizontalHeaderLabels(header); - - QFont font; - font.setBold(true); - m_table->horizontalHeader()->setFont(font); -// m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); - - // Add row button. - { - int row = m_table->rowCount(); - m_table->insertRow(row); - - QPushButton* button = new QPushButton(m_table); - button->setText("Add Row"); - m_table->setCellWidget(row, 0, button); - connect( - button, &QPushButton::clicked, - this, [this](bool){ - int index = (int)m_current.size(); - m_value.insert_row(index, m_value.make_row()); - } - ); - } - - EditableTableWidget::update_value(); -// EditableTableWidget2::value_changed(); - -// m_table->resizeColumnsToContents(); -// m_table->resizeRowsToContents(); - m_table->update_height(); - - - if (value.saveload_enabled()){ - QHBoxLayout* buttons = new QHBoxLayout(); - layout->addLayout(buttons); - { - QPushButton* button = new QPushButton("Load Table", this); - buttons->addWidget(button, 1); - connect( - button, &QPushButton::clicked, - this, [this, &value](bool){ - std::string path = QFileDialog::getOpenFileName( - this, - tr("Select a file to load."), "", tr("JSON files (*.json)") - ).toStdString(); - if (path.empty()){ - return; - } - value.load_json(load_json_file(path)); - } - ); - } - { - QPushButton* button = new QPushButton("Save Table", this); - buttons->addWidget(button, 1); - connect( - button, &QPushButton::clicked, - this, [this, &value](bool){ - std::string path = QFileDialog::getSaveFileName( - this, - tr("Select a file name to save to."), "", tr("JSON files (*.json)") - ).toStdString(); - if (path.empty()){ - return; - } - JsonValue json = value.to_json(); - json.dump(path); - } - ); - } - { - QPushButton* button = new QPushButton("Restore Defaults", this); - buttons->addWidget(button, 1); - connect( - button, &QPushButton::clicked, - this, [&value](bool){ - QMessageBox::StandardButton button = QMessageBox::question( - nullptr, - "Restore Defaults", - "Are you sure you wish to this table back to defaults? This will wipe the current table.", - QMessageBox::Ok | QMessageBox::Cancel - ); - if (button == QMessageBox::Ok){ - value.restore_defaults(); - } - } - ); - } - buttons->addStretch(2); - } - - value.add_listener(*this); -} - -void EditableTableWidget::update_value(){ - std::vector> latest = m_value.current_refs(); -// cout << "latest.size() = " << latest.size() << endl; - -// // Adding cells to a table overwrites their visibility. Store all the cells -// // here so we can correct their visibility later. -// std::vector cell_widgets; - - // Iterate the old and new rows and resolve only the differences. - size_t index_old = 0; - size_t index_new = 0; - while (true){ - // End of both lists. - if (index_old == m_current.size() && index_new == latest.size()){ - break; - } - - // Rows are the same. No change needed. - if (index_old < m_current.size() && index_new < latest.size() && - m_current[index_old]->seqnum() == latest[index_new]->seqnum() - ){ - index_old++; - index_new++; - continue; - } - -// cout << index_old << " - " << index_new << endl; - - // End of new list or row no longer valid. Remove it. - if (index_new == latest.size() || - (index_old < m_current.size() && m_current[index_old]->index() == (size_t)0 - 1) - ){ - // QTableWidget::removeRow() does not immediately delete the - // widgets in that row. So we need to do it manually to drop the - // references to the row objects. - int stop = m_table->columnCount(); - for (int c = 0; c < stop; c++){ - delete m_table->cellWidget((int)index_new, c); - } - m_table->removeRow((int)index_new); - index_old++; - continue; - } - - // Add the row from the new list. - m_table->insertRow((int)index_new); - - // Populate widgets. - { - EditableTableRow& row = *latest[index_new]; - std::vector cells = row.make_cells(); - int c = 0; - int stop = (int)cells.size(); - for (; c < stop; c++){ - // Wrap the widget so that it preserves its visibility. - // QTableWidget for some reason forces the visibility of its - // cells to visible. -// cout << "make cell widget" << endl; - QWidget* widget = &cells[c]->make_QtWidget(*m_table)->widget(); - QWidget* cell_widget = new QWidget(this); - QVBoxLayout* layout = new QVBoxLayout(cell_widget); - layout->setContentsMargins(0, 0, 0, 0); -// cell_widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - layout->addWidget(widget); -// cell_widgets.emplace_back(widget); - m_table->setCellWidget((int)index_new, c, cell_widget); -// cell_widget->update(); -// cout << "cell_widget->width() = " << cell_widget->width() << endl; -// cout << "cell_widget->sizeHint().width() = " << cell_widget->sizeHint().width() << endl; - } - m_table->setCellWidget((int)index_new, c++, make_clone_button(row)); - m_table->setCellWidget((int)index_new, c++, make_insert_button(row)); - m_table->setCellWidget((int)index_new, c++, make_delete_button(row)); - } - - index_new++; - } - -#if 0 - for (int r = 0; r < m_table->rowCount() - 1; r++){ - for (int c = 0; c < m_table->columnCount(); c++){ - cout << m_table->cellWidget(r, c)->sizeHint().width() << " "; - } - cout << endl; - } -#endif - -// cout << "latest.size() = " << latest.size() << endl; - m_current = std::move(latest); - EditableTableWidget::update_sizes(); - -#if 0 - for (ConfigWidget* cell : cell_widgets){ - cout << "Before: " << cell->widget().isVisible() << endl; - cell->update_visibility(); - cout << "After: " << cell->widget().isVisible() << endl; - } -#endif -} -void EditableTableWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_table, [this]{ - update_value(); - }, Qt::QueuedConnection); -} -void EditableTableWidget::update_sizes(){ -// cout << "update_sizes()" << endl; - QMetaObject::invokeMethod(m_table, [this]{ -// cout << "before = " << m_table->cellWidget(0, 1)->width() << endl; - m_table->resizeColumnsToContents(); - m_table->resizeRowsToContents(); - m_table->update_height(); -// cout << "after = " << m_table->cellWidget(0, 1)->width() << endl; - }, Qt::QueuedConnection); -} - - - -QWidget* EditableTableWidget::make_clone_button(EditableTableRow& row){ - QPushButton* button = new QPushButton(m_table); - - QFont font; - font.setBold(true); - button->setFont(font); - button->setText("Copy"); - button->setMaximumWidth(60); - - connect( - button, &QPushButton::clicked, - this, [&](bool){ - m_value.clone_row(row); - } - ); - - return button; -} -QWidget* EditableTableWidget::make_insert_button(EditableTableRow& row){ - QPushButton* button = new QPushButton(m_table); - - QFont font; - font.setBold(true); - button->setFont(font); - button->setText("Insert"); - button->setMaximumWidth(60); - - connect( - button, &QPushButton::clicked, - this, [&](bool){ - m_value.insert_row(row.index(), m_value.make_row()); - } - ); - - return button; -} -QWidget* EditableTableWidget::make_delete_button(EditableTableRow& row){ - QPushButton* button = new QPushButton(m_table); - - QFont font; - font.setBold(true); - button->setFont(font); - button->setText("Delete"); - button->setMaximumWidth(60); - - connect( - button, &QPushButton::clicked, - this, [&](bool){ - m_value.remove_row(row); - } - ); - - return button; -} - - - - -} +/* Editable Table Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/AutoHeightTable.h" +#include "EditableTableWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget* EditableTableOption::make_QtWidget(QWidget& parent){ + return new EditableTableWidget(parent, *this); +} + + + +EditableTableWidget::~EditableTableWidget(){ + m_value.remove_listener(*this); + delete m_table; +} +EditableTableWidget::EditableTableWidget(QWidget& parent, EditableTableOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) + , m_table(nullptr) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + if (!value.label().empty()){ + QLabel* label = new QLabel(QString::fromStdString(value.label()), this); + label->setWordWrap(true); + label->setTextFormat(Qt::RichText); + label->setTextInteractionFlags(Qt::TextBrowserInteraction); + label->setOpenExternalLinks(true); + layout->addWidget(label); + } + + m_table = new AutoHeightTableWidget(this); + layout->addWidget(m_table, 0, Qt::AlignTop); +// m_table->setMouseTracking(false); + + QStringList header; + for (const std::string& name : m_value.make_header()){ + header << QString::fromStdString(name); + } + header << "" << "" << ""; + m_table->setColumnCount(int(header.size())); + m_table->setHorizontalHeaderLabels(header); + + QFont font; + font.setBold(true); + m_table->horizontalHeader()->setFont(font); +// m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + + // Add row button. + { + int row = m_table->rowCount(); + m_table->insertRow(row); + + QPushButton* button = new QPushButton(m_table); + button->setText("Add Row"); + m_table->setCellWidget(row, 0, button); + connect( + button, &QPushButton::clicked, + this, [this](bool){ + int index = (int)m_current.size(); + m_value.insert_row(index, m_value.make_row()); + } + ); + } + + EditableTableWidget::update_value(); +// EditableTableWidget2::value_changed(); + +// m_table->resizeColumnsToContents(); +// m_table->resizeRowsToContents(); + m_table->update_height(); + + + if (value.saveload_enabled()){ + QHBoxLayout* buttons = new QHBoxLayout(); + layout->addLayout(buttons); + { + QPushButton* button = new QPushButton("Load Table", this); + buttons->addWidget(button, 1); + connect( + button, &QPushButton::clicked, + this, [this, &value](bool){ + std::string path = QFileDialog::getOpenFileName( + this, + tr("Select a file to load."), "", tr("JSON files (*.json)") + ).toStdString(); + if (path.empty()){ + return; + } + value.load_json(load_json_file(path)); + } + ); + } + { + QPushButton* button = new QPushButton("Save Table", this); + buttons->addWidget(button, 1); + connect( + button, &QPushButton::clicked, + this, [this, &value](bool){ + std::string path = QFileDialog::getSaveFileName( + this, + tr("Select a file name to save to."), "", tr("JSON files (*.json)") + ).toStdString(); + if (path.empty()){ + return; + } + JsonValue json = value.to_json(); + json.dump(path); + } + ); + } + { + QPushButton* button = new QPushButton("Restore Defaults", this); + buttons->addWidget(button, 1); + connect( + button, &QPushButton::clicked, + this, [&value](bool){ + QMessageBox::StandardButton button = QMessageBox::question( + nullptr, + "Restore Defaults", + "Are you sure you wish to this table back to defaults? This will wipe the current table.", + QMessageBox::Ok | QMessageBox::Cancel + ); + if (button == QMessageBox::Ok){ + value.restore_defaults(); + } + } + ); + } + buttons->addStretch(2); + } + + value.add_listener(*this); +} + +void EditableTableWidget::update_value(){ + std::vector> latest = m_value.current_refs(); +// cout << "latest.size() = " << latest.size() << endl; + +// // Adding cells to a table overwrites their visibility. Store all the cells +// // here so we can correct their visibility later. +// std::vector cell_widgets; + + // Iterate the old and new rows and resolve only the differences. + size_t index_old = 0; + size_t index_new = 0; + while (true){ + // End of both lists. + if (index_old == m_current.size() && index_new == latest.size()){ + break; + } + + // Rows are the same. No change needed. + if (index_old < m_current.size() && index_new < latest.size() && + m_current[index_old]->seqnum() == latest[index_new]->seqnum() + ){ + index_old++; + index_new++; + continue; + } + +// cout << index_old << " - " << index_new << endl; + + // End of new list or row no longer valid. Remove it. + if (index_new == latest.size() || + (index_old < m_current.size() && m_current[index_old]->index() == (size_t)0 - 1) + ){ + // QTableWidget::removeRow() does not immediately delete the + // widgets in that row. So we need to do it manually to drop the + // references to the row objects. + int stop = m_table->columnCount(); + for (int c = 0; c < stop; c++){ + delete m_table->cellWidget((int)index_new, c); + } + m_table->removeRow((int)index_new); + index_old++; + continue; + } + + // Add the row from the new list. + m_table->insertRow((int)index_new); + + // Populate widgets. + { + EditableTableRow& row = *latest[index_new]; + std::vector cells = row.make_cells(); + int c = 0; + int stop = (int)cells.size(); + for (; c < stop; c++){ + // Wrap the widget so that it preserves its visibility. + // QTableWidget for some reason forces the visibility of its + // cells to visible. +// cout << "make cell widget" << endl; + QWidget* widget = &cells[c]->make_QtWidget(*m_table)->widget(); + QWidget* cell_widget = new QWidget(this); + QVBoxLayout* layout = new QVBoxLayout(cell_widget); + layout->setContentsMargins(0, 0, 0, 0); +// cell_widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + layout->addWidget(widget); +// cell_widgets.emplace_back(widget); + m_table->setCellWidget((int)index_new, c, cell_widget); +// cell_widget->update(); +// cout << "cell_widget->width() = " << cell_widget->width() << endl; +// cout << "cell_widget->sizeHint().width() = " << cell_widget->sizeHint().width() << endl; + } + m_table->setCellWidget((int)index_new, c++, make_clone_button(row)); + m_table->setCellWidget((int)index_new, c++, make_insert_button(row)); + m_table->setCellWidget((int)index_new, c++, make_delete_button(row)); + } + + index_new++; + } + +#if 0 + for (int r = 0; r < m_table->rowCount() - 1; r++){ + for (int c = 0; c < m_table->columnCount(); c++){ + cout << m_table->cellWidget(r, c)->sizeHint().width() << " "; + } + cout << endl; + } +#endif + +// cout << "latest.size() = " << latest.size() << endl; + m_current = std::move(latest); + EditableTableWidget::update_sizes(); + +#if 0 + for (ConfigWidget* cell : cell_widgets){ + cout << "Before: " << cell->widget().isVisible() << endl; + cell->update_visibility(); + cout << "After: " << cell->widget().isVisible() << endl; + } +#endif +} +void EditableTableWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_table, [this]{ + update_value(); + }, Qt::QueuedConnection); +} +void EditableTableWidget::update_sizes(){ +// cout << "update_sizes()" << endl; + QMetaObject::invokeMethod(m_table, [this]{ +// cout << "before = " << m_table->cellWidget(0, 1)->width() << endl; + m_table->resizeColumnsToContents(); + m_table->resizeRowsToContents(); + m_table->update_height(); +// cout << "after = " << m_table->cellWidget(0, 1)->width() << endl; + }, Qt::QueuedConnection); +} + + + +QWidget* EditableTableWidget::make_clone_button(EditableTableRow& row){ + QPushButton* button = new QPushButton(m_table); + + QFont font; + font.setBold(true); + button->setFont(font); + button->setText("Copy"); + button->setMaximumWidth(60); + + connect( + button, &QPushButton::clicked, + this, [&](bool){ + m_value.clone_row(row); + } + ); + + return button; +} +QWidget* EditableTableWidget::make_insert_button(EditableTableRow& row){ + QPushButton* button = new QPushButton(m_table); + + QFont font; + font.setBold(true); + button->setFont(font); + button->setText("Insert"); + button->setMaximumWidth(60); + + connect( + button, &QPushButton::clicked, + this, [&](bool){ + m_value.insert_row(row.index(), m_value.make_row()); + } + ); + + return button; +} +QWidget* EditableTableWidget::make_delete_button(EditableTableRow& row){ + QPushButton* button = new QPushButton(m_table); + + QFont font; + font.setBold(true); + button->setFont(font); + button->setText("Delete"); + button->setMaximumWidth(60); + + connect( + button, &QPushButton::clicked, + this, [&](bool){ + m_value.remove_row(row); + } + ); + + return button; +} + + + + +} diff --git a/Common/Qt/Options/EditableTableWidget.h b/Common/Qt/Options/EditableTableWidget.h index 6cc7449fb0..5379907d7c 100644 --- a/Common/Qt/Options/EditableTableWidget.h +++ b/Common/Qt/Options/EditableTableWidget.h @@ -1,44 +1,44 @@ -/* Editable Table Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_EditableTableWidget_H -#define PokemonAutomation_Options_EditableTableWidget_H - -#include -#include "Common/Cpp/Options/EditableTableOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - -class AutoHeightTableWidget; - - -class EditableTableWidget : public QWidget, public ConfigWidget{ -public: - ~EditableTableWidget(); - EditableTableWidget(QWidget& parent, EditableTableOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - - void update_sizes(); - -private: - QWidget* make_clone_button(EditableTableRow& row); - QWidget* make_insert_button(EditableTableRow& row); - QWidget* make_delete_button(EditableTableRow& row); - -private: - EditableTableOption& m_value; - AutoHeightTableWidget* m_table; - std::vector> m_current; -}; - - - - -} -#endif +/* Editable Table Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_EditableTableWidget_H +#define PokemonAutomation_Options_EditableTableWidget_H + +#include +#include "Common/Cpp/Options/EditableTableOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + +class AutoHeightTableWidget; + + +class EditableTableWidget : public QWidget, public ConfigWidget{ +public: + ~EditableTableWidget(); + EditableTableWidget(QWidget& parent, EditableTableOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + + void update_sizes(); + +private: + QWidget* make_clone_button(EditableTableRow& row); + QWidget* make_insert_button(EditableTableRow& row); + QWidget* make_delete_button(EditableTableRow& row); + +private: + EditableTableOption& m_value; + AutoHeightTableWidget* m_table; + std::vector> m_current; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/EnumDropdownWidget.cpp b/Common/Qt/Options/EnumDropdownWidget.cpp index b2ea90406e..8763a86df3 100644 --- a/Common/Qt/Options/EnumDropdownWidget.cpp +++ b/Common/Qt/Options/EnumDropdownWidget.cpp @@ -1,111 +1,111 @@ -/* Enum Dropdown Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "EnumDropdownWidget.h" - -namespace PokemonAutomation{ - - -ConfigWidget* IntegerEnumDropdownCell::make_QtWidget(QWidget& parent){ - return new EnumDropdownCellWidget(parent, *this); -} -ConfigWidget* IntegerEnumDropdownOption::make_QtWidget(QWidget& parent){ - return new EnumDropdownOptionWidget(parent, *this); -} - - - -EnumDropdownCellWidget::~EnumDropdownCellWidget(){ - m_value.remove_listener(*this); -} -EnumDropdownCellWidget::EnumDropdownCellWidget(QWidget& parent, IntegerEnumDropdownCell& value) - : NoWheelComboBox(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ -// this->setFrame(false); - - for (const auto& item : value.database().all_values()){ - int index = this->count(); - m_value_to_index[item] = index; - m_index_to_value.emplace_back(item); - - const EnumEntry& entry = *value.database().find(item); - - this->addItem(QString::fromStdString(entry.display)); - if (entry.enabled){ - continue; - } - auto* model = qobject_cast(this->model()); - if (model == nullptr){ - continue; - } - QStandardItem* line_handle = model->item(this->count() - 1); - if (line_handle != nullptr){ - line_handle->setEnabled(false); - } - } - this->setCurrentIndex(m_value_to_index[m_value.current_value()]); - - connect( - this, static_cast(&QComboBox::currentIndexChanged), - this, [this](int index){ - if (index < 0 || (size_t)index >= m_index_to_value.size()){ - m_value.restore_defaults(); - return; - } - m_value.set_value(m_index_to_value[index]); - } - ); - - m_value.add_listener(*this); -} - - -void EnumDropdownCellWidget::update_value(){ - this->setCurrentIndex(m_value_to_index[m_value.current_value()]); -} -void EnumDropdownCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -EnumDropdownOptionWidget::EnumDropdownOptionWidget(QWidget& parent, IntegerEnumDropdownOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_cell(new EnumDropdownCellWidget(*this, value)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - layout->addWidget(m_cell, 1); -} - - -void EnumDropdownOptionWidget::update_value(){ - m_cell->update_value(); -} - - - - - - - -} +/* Enum Dropdown Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "EnumDropdownWidget.h" + +namespace PokemonAutomation{ + + +ConfigWidget* IntegerEnumDropdownCell::make_QtWidget(QWidget& parent){ + return new EnumDropdownCellWidget(parent, *this); +} +ConfigWidget* IntegerEnumDropdownOption::make_QtWidget(QWidget& parent){ + return new EnumDropdownOptionWidget(parent, *this); +} + + + +EnumDropdownCellWidget::~EnumDropdownCellWidget(){ + m_value.remove_listener(*this); +} +EnumDropdownCellWidget::EnumDropdownCellWidget(QWidget& parent, IntegerEnumDropdownCell& value) + : NoWheelComboBox(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ +// this->setFrame(false); + + for (const auto& item : value.database().all_values()){ + int index = this->count(); + m_value_to_index[item] = index; + m_index_to_value.emplace_back(item); + + const EnumEntry& entry = *value.database().find(item); + + this->addItem(QString::fromStdString(entry.display)); + if (entry.enabled){ + continue; + } + auto* model = qobject_cast(this->model()); + if (model == nullptr){ + continue; + } + QStandardItem* line_handle = model->item(this->count() - 1); + if (line_handle != nullptr){ + line_handle->setEnabled(false); + } + } + this->setCurrentIndex(m_value_to_index[m_value.current_value()]); + + connect( + this, static_cast(&QComboBox::currentIndexChanged), + this, [this](int index){ + if (index < 0 || (size_t)index >= m_index_to_value.size()){ + m_value.restore_defaults(); + return; + } + m_value.set_value(m_index_to_value[index]); + } + ); + + m_value.add_listener(*this); +} + + +void EnumDropdownCellWidget::update_value(){ + this->setCurrentIndex(m_value_to_index[m_value.current_value()]); +} +void EnumDropdownCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +EnumDropdownOptionWidget::EnumDropdownOptionWidget(QWidget& parent, IntegerEnumDropdownOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_cell(new EnumDropdownCellWidget(*this, value)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + layout->addWidget(m_cell, 1); +} + + +void EnumDropdownOptionWidget::update_value(){ + m_cell->update_value(); +} + + + + + + + +} diff --git a/Common/Qt/Options/EnumDropdownWidget.h b/Common/Qt/Options/EnumDropdownWidget.h index bf8cd3f237..3db1849049 100644 --- a/Common/Qt/Options/EnumDropdownWidget.h +++ b/Common/Qt/Options/EnumDropdownWidget.h @@ -1,48 +1,48 @@ -/* Enum Dropdown Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_EnumDropdownWidget_H -#define PokemonAutomation_Options_EnumDropdownWidget_H - -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - -class EnumDropdownCellWidget : public NoWheelComboBox, public ConfigWidget{ -public: - ~EnumDropdownCellWidget(); - EnumDropdownCellWidget(QWidget& parent, IntegerEnumDropdownCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -protected: - IntegerEnumDropdownCell& m_value; - std::map m_value_to_index; - std::vector m_index_to_value; -}; - - -class EnumDropdownOptionWidget : public QWidget, public ConfigWidget{ -public: - EnumDropdownOptionWidget(QWidget& parent, IntegerEnumDropdownOption& value); - - virtual void update_value() override; - -private: - EnumDropdownCellWidget* m_cell; -}; - - - - - -} -#endif +/* Enum Dropdown Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_EnumDropdownWidget_H +#define PokemonAutomation_Options_EnumDropdownWidget_H + +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + +class EnumDropdownCellWidget : public NoWheelComboBox, public ConfigWidget{ +public: + ~EnumDropdownCellWidget(); + EnumDropdownCellWidget(QWidget& parent, IntegerEnumDropdownCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +protected: + IntegerEnumDropdownCell& m_value; + std::map m_value_to_index; + std::vector m_index_to_value; +}; + + +class EnumDropdownOptionWidget : public QWidget, public ConfigWidget{ +public: + EnumDropdownOptionWidget(QWidget& parent, IntegerEnumDropdownOption& value); + + virtual void update_value() override; + +private: + EnumDropdownCellWidget* m_cell; +}; + + + + + +} +#endif diff --git a/Common/Qt/Options/FixedCodeWidget.cpp b/Common/Qt/Options/FixedCodeWidget.cpp index c8bc03f424..c6b741923b 100644 --- a/Common/Qt/Options/FixedCodeWidget.cpp +++ b/Common/Qt/Options/FixedCodeWidget.cpp @@ -1,89 +1,89 @@ -/* Fixed Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Qt/CodeValidator.h" -#include "FixedCodeWidget.h" - -namespace PokemonAutomation{ - - -ConfigWidget* FixedCodeOption::make_QtWidget(QWidget& parent){ - return new FixedCodeWidget(parent, *this); -} - - - - -std::string FixedCodeWidget::sanitized_code(const std::string& text) const{ - std::string message; - try{ - message = "Code: " + sanitize_code(m_value.digits(), text); - }catch (const ParseException& e){ - message = "" + e.message() + ""; - } - return message; -} -FixedCodeWidget::~FixedCodeWidget(){ - m_value.remove_listener(*this); -} -FixedCodeWidget::FixedCodeWidget(QWidget& parent, FixedCodeOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - - QVBoxLayout* right = new QVBoxLayout(); - layout->addLayout(right, 1); - - std::string current = m_value.get(); - m_box = new QLineEdit(QString::fromStdString(current), this); - right->addWidget(m_box); - QLabel* under_text = new QLabel(QString::fromStdString(sanitized_code(current)), this); - under_text->setWordWrap(true); - right->addWidget(under_text); - - connect( - m_box, &QLineEdit::textChanged, - this, [this, under_text](const QString& text){ - std::string str = text.toStdString(); - under_text->setText(QString::fromStdString(sanitized_code(str))); -// m_value.set(str); - } - ); - connect( - m_box, &QLineEdit::editingFinished, - m_box, [this, under_text](){ - std::string current = m_box->text().toStdString(); - under_text->setText(QString::fromStdString(sanitized_code(current))); -// m_box->setText(QString::fromStdString(current)); - m_value.set(current); - } - ); - m_value.add_listener(*this); -} -void FixedCodeWidget::update_value(){ - m_box->setText(QString::fromStdString(m_value)); -} -void FixedCodeWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -} +/* Fixed Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Qt/CodeValidator.h" +#include "FixedCodeWidget.h" + +namespace PokemonAutomation{ + + +ConfigWidget* FixedCodeOption::make_QtWidget(QWidget& parent){ + return new FixedCodeWidget(parent, *this); +} + + + + +std::string FixedCodeWidget::sanitized_code(const std::string& text) const{ + std::string message; + try{ + message = "Code: " + sanitize_code(m_value.digits(), text); + }catch (const ParseException& e){ + message = "" + e.message() + ""; + } + return message; +} +FixedCodeWidget::~FixedCodeWidget(){ + m_value.remove_listener(*this); +} +FixedCodeWidget::FixedCodeWidget(QWidget& parent, FixedCodeOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + + QVBoxLayout* right = new QVBoxLayout(); + layout->addLayout(right, 1); + + std::string current = m_value.get(); + m_box = new QLineEdit(QString::fromStdString(current), this); + right->addWidget(m_box); + QLabel* under_text = new QLabel(QString::fromStdString(sanitized_code(current)), this); + under_text->setWordWrap(true); + right->addWidget(under_text); + + connect( + m_box, &QLineEdit::textChanged, + this, [this, under_text](const QString& text){ + std::string str = text.toStdString(); + under_text->setText(QString::fromStdString(sanitized_code(str))); +// m_value.set(str); + } + ); + connect( + m_box, &QLineEdit::editingFinished, + m_box, [this, under_text](){ + std::string current = m_box->text().toStdString(); + under_text->setText(QString::fromStdString(sanitized_code(current))); +// m_box->setText(QString::fromStdString(current)); + m_value.set(current); + } + ); + m_value.add_listener(*this); +} +void FixedCodeWidget::update_value(){ + m_box->setText(QString::fromStdString(m_value)); +} +void FixedCodeWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +} diff --git a/Common/Qt/Options/FixedCodeWidget.h b/Common/Qt/Options/FixedCodeWidget.h index a399af9dcb..099dccb4ea 100644 --- a/Common/Qt/Options/FixedCodeWidget.h +++ b/Common/Qt/Options/FixedCodeWidget.h @@ -1,39 +1,39 @@ -/* Fixed Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_FixedCodeWidget_H -#define PokemonAutomation_Options_FixedCodeWidget_H - -#include -#include "Common/Cpp/Options/FixedCodeOption.h" -#include "ConfigWidget.h" - -class QLineEdit; - -namespace PokemonAutomation{ - - -class FixedCodeWidget : public QWidget, public ConfigWidget{ -public: - ~FixedCodeWidget(); - FixedCodeWidget(QWidget& parent, FixedCodeOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - std::string sanitized_code(const std::string& text) const; - -private: - FixedCodeOption& m_value; - QLineEdit* m_box; -}; - - - - -} -#endif +/* Fixed Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_FixedCodeWidget_H +#define PokemonAutomation_Options_FixedCodeWidget_H + +#include +#include "Common/Cpp/Options/FixedCodeOption.h" +#include "ConfigWidget.h" + +class QLineEdit; + +namespace PokemonAutomation{ + + +class FixedCodeWidget : public QWidget, public ConfigWidget{ +public: + ~FixedCodeWidget(); + FixedCodeWidget(QWidget& parent, FixedCodeOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + std::string sanitized_code(const std::string& text) const; + +private: + FixedCodeOption& m_value; + QLineEdit* m_box; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/FloatingPointWidget.cpp b/Common/Qt/Options/FloatingPointWidget.cpp index 75b0b824ce..cd68caab48 100644 --- a/Common/Qt/Options/FloatingPointWidget.cpp +++ b/Common/Qt/Options/FloatingPointWidget.cpp @@ -1,110 +1,110 @@ -/* Floating-Point Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "ConfigWidget.h" -#include "FloatingPointWidget.h" - -namespace PokemonAutomation{ - - - -ConfigWidget* FloatingPointCell::make_QtWidget(QWidget& parent){ - return new FloatingPointCellWidget(parent, *this); -} -ConfigWidget* FloatingPointOption::make_QtWidget(QWidget& parent){ - return new FloatingPointOptionWidget(parent, *this); -} - - - - -FloatingPointCellWidget::~FloatingPointCellWidget(){ - m_value.remove_listener(*this); -} -FloatingPointCellWidget::FloatingPointCellWidget(QWidget& parent, FloatingPointCell& value) - : QLineEdit(QString::number(value, 'f'), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - connect( - this, &QLineEdit::textChanged, - this, [this](const QString& text){ - bool ok; - double current = text.toDouble(&ok); - QPalette palette; - if (ok && m_value.check_validity(current).empty()){ - palette.setColor(QPalette::Text, Qt::black); - }else{ - palette.setColor(QPalette::Text, Qt::red); - } - this->setPalette(palette); - } - ); - connect( - this, &QLineEdit::editingFinished, - this, [this](){ - bool ok; - double current = this->text().toDouble(&ok); - QPalette palette; - if (ok && m_value.check_validity(current).empty()){ - palette.setColor(QPalette::Text, Qt::black); - }else{ - palette.setColor(QPalette::Text, Qt::red); - } - this->setPalette(palette); - m_value.set(current); - } - ); - value.add_listener(*this); -} -void FloatingPointCellWidget::update_value(){ - this->setText(QString::number(m_value, 'f')); -} -void FloatingPointCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -FloatingPointOptionWidget::~FloatingPointOptionWidget(){ - m_value.remove_listener(*this); -} -FloatingPointOptionWidget::FloatingPointOptionWidget(QWidget& parent, FloatingPointOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - m_cell = new FloatingPointCellWidget(*this, value); - layout->addWidget(m_cell, 1); - value.add_listener(*this); -} -void FloatingPointOptionWidget::update_value(){ - m_cell->update_value(); -} -void FloatingPointOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - -} +/* Floating-Point Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "ConfigWidget.h" +#include "FloatingPointWidget.h" + +namespace PokemonAutomation{ + + + +ConfigWidget* FloatingPointCell::make_QtWidget(QWidget& parent){ + return new FloatingPointCellWidget(parent, *this); +} +ConfigWidget* FloatingPointOption::make_QtWidget(QWidget& parent){ + return new FloatingPointOptionWidget(parent, *this); +} + + + + +FloatingPointCellWidget::~FloatingPointCellWidget(){ + m_value.remove_listener(*this); +} +FloatingPointCellWidget::FloatingPointCellWidget(QWidget& parent, FloatingPointCell& value) + : QLineEdit(QString::number(value, 'f'), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + connect( + this, &QLineEdit::textChanged, + this, [this](const QString& text){ + bool ok; + double current = text.toDouble(&ok); + QPalette palette; + if (ok && m_value.check_validity(current).empty()){ + palette.setColor(QPalette::Text, Qt::black); + }else{ + palette.setColor(QPalette::Text, Qt::red); + } + this->setPalette(palette); + } + ); + connect( + this, &QLineEdit::editingFinished, + this, [this](){ + bool ok; + double current = this->text().toDouble(&ok); + QPalette palette; + if (ok && m_value.check_validity(current).empty()){ + palette.setColor(QPalette::Text, Qt::black); + }else{ + palette.setColor(QPalette::Text, Qt::red); + } + this->setPalette(palette); + m_value.set(current); + } + ); + value.add_listener(*this); +} +void FloatingPointCellWidget::update_value(){ + this->setText(QString::number(m_value, 'f')); +} +void FloatingPointCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +FloatingPointOptionWidget::~FloatingPointOptionWidget(){ + m_value.remove_listener(*this); +} +FloatingPointOptionWidget::FloatingPointOptionWidget(QWidget& parent, FloatingPointOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + m_cell = new FloatingPointCellWidget(*this, value); + layout->addWidget(m_cell, 1); + value.add_listener(*this); +} +void FloatingPointOptionWidget::update_value(){ + m_cell->update_value(); +} +void FloatingPointOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + +} diff --git a/Common/Qt/Options/FloatingPointWidget.h b/Common/Qt/Options/FloatingPointWidget.h index ced25e0c8d..6beaaae3f2 100644 --- a/Common/Qt/Options/FloatingPointWidget.h +++ b/Common/Qt/Options/FloatingPointWidget.h @@ -1,45 +1,45 @@ -/* Floating-Point Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_FloatingPointWidget_H -#define PokemonAutomation_FloatingPointWidget_H - -#include -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - -class FloatingPointCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~FloatingPointCellWidget(); - FloatingPointCellWidget(QWidget& parent, FloatingPointCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - FloatingPointCell& m_value; -}; - - -class FloatingPointOptionWidget : public QWidget, public ConfigWidget{ -public: - ~FloatingPointOptionWidget(); - FloatingPointOptionWidget(QWidget& parent, FloatingPointOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - FloatingPointCellWidget* m_cell; -}; - - - -} -#endif +/* Floating-Point Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_FloatingPointWidget_H +#define PokemonAutomation_FloatingPointWidget_H + +#include +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + +class FloatingPointCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~FloatingPointCellWidget(); + FloatingPointCellWidget(QWidget& parent, FloatingPointCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + FloatingPointCell& m_value; +}; + + +class FloatingPointOptionWidget : public QWidget, public ConfigWidget{ +public: + ~FloatingPointOptionWidget(); + FloatingPointOptionWidget(QWidget& parent, FloatingPointOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + FloatingPointCellWidget* m_cell; +}; + + + +} +#endif diff --git a/Common/Qt/Options/GroupWidget.cpp b/Common/Qt/Options/GroupWidget.cpp index 1c5d8f6eba..5537d989e8 100644 --- a/Common/Qt/Options/GroupWidget.cpp +++ b/Common/Qt/Options/GroupWidget.cpp @@ -1,143 +1,143 @@ -/* Group Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -//#include "Common/Compiler.h" -#include "GroupWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* GroupOption::make_QtWidget(QWidget& parent){ - return new GroupWidget(parent, *this); -} - - -GroupWidget::~GroupWidget(){ - m_value.remove_listener(*this); -} -GroupWidget::GroupWidget(QWidget& parent, GroupOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) - , m_restore_defaults_button(nullptr) -{ - QVBoxLayout* layout = new QVBoxLayout(this); -// layout->setAlignment(Qt::AlignTop); - layout->setContentsMargins(0, 0, 0, 0); - m_group_box = new QGroupBox(QString::fromStdString(value.label()), this); - m_group_box->setCheckable(value.toggleable()); - m_group_box->setChecked(value.enabled()); - layout->addWidget(m_group_box); - -#if 0 - QVBoxLayout* mid_layout = new QVBoxLayout(group_box); - QWidget* mid_widget = new QWidget(group_box); - mid_layout->addWidget(mid_widget); - mid_layout-setContentsMargins(0, 0, 0, 0); - - QFont font = group_box->font(); - mid_widget->setFont(font); - font.setBold(true); - group_box->setFont(font); -#endif - - QVBoxLayout* group_layout = new QVBoxLayout(m_group_box); - group_layout->setAlignment(Qt::AlignTop); - group_layout->setContentsMargins(0, 10, 0, 0); - - m_expand_text = new QWidget(m_group_box); - m_expand_text->setLayout(new QVBoxLayout()); - m_expand_text->layout()->addWidget(new QLabel("(double click to expand)", this)); - m_expand_text->setVisible(false); - group_layout->addWidget(m_expand_text); - - - m_options_holder = new QWidget(m_group_box); - group_layout->addWidget(m_options_holder); - m_options_layout = new QVBoxLayout(m_options_holder); - m_options_layout->setContentsMargins(0, 0, 0, 0); - - for (auto& item : value.options()){ - m_options.emplace_back(item->make_QtWidget(parent)); - m_options.back()->widget().setContentsMargins(5, 5, 5, 5); - m_options_layout->addWidget(&m_options.back()->widget()); - } - - if (value.restore_defaults_button_enabled()){ - m_restore_defaults_button = new QPushButton("Restore Defaults", this); - m_restore_defaults_button->setContentsMargins(5, 5, 5, 5); - QHBoxLayout* row = new QHBoxLayout(); - m_options_layout->addLayout(row); - row->addWidget(m_restore_defaults_button, 1); - row->addStretch(3); - connect( - m_restore_defaults_button, &QPushButton::clicked, - this, [this](bool on){ - QMessageBox::StandardButton button = QMessageBox::question( - nullptr, - "Restore Defaults", - "Are you sure you wish to restore this section back to defaults?", - QMessageBox::Ok | QMessageBox::Cancel - ); - if (button == QMessageBox::Ok){ - m_value.restore_defaults(); - } - } - ); - } - - connect( - m_group_box, &QGroupBox::toggled, - this, [this](bool on){ - m_value.set_enabled(on); -// m_value.on_set_enabled(on); - } - ); - - value.add_listener(*this); -} - -#if 0 -void GroupWidget::set_options_enabled(bool enabled){ - for (ConfigWidget* item : m_options){ - item->widget().setEnabled(enabled); - } -} -#endif -void GroupWidget::update_value(){ - bool on = m_value.enabled(); -// cout << "on = " << on << endl; - m_group_box->setChecked(on); - for (ConfigWidget* item : m_options){ - item->update_value(); - } -} -void GroupWidget::on_config_value_changed(void* object){ -// cout << "GroupWidget::value_changed()" << endl; - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} -void GroupWidget::mouseDoubleClickEvent(QMouseEvent*){ - m_expand_text->setVisible(m_expanded); - m_expanded = !m_expanded; - m_options_holder->setVisible(m_expanded); -} - - - - -} +/* Group Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +//#include "Common/Compiler.h" +#include "GroupWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* GroupOption::make_QtWidget(QWidget& parent){ + return new GroupWidget(parent, *this); +} + + +GroupWidget::~GroupWidget(){ + m_value.remove_listener(*this); +} +GroupWidget::GroupWidget(QWidget& parent, GroupOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) + , m_restore_defaults_button(nullptr) +{ + QVBoxLayout* layout = new QVBoxLayout(this); +// layout->setAlignment(Qt::AlignTop); + layout->setContentsMargins(0, 0, 0, 0); + m_group_box = new QGroupBox(QString::fromStdString(value.label()), this); + m_group_box->setCheckable(value.toggleable()); + m_group_box->setChecked(value.enabled()); + layout->addWidget(m_group_box); + +#if 0 + QVBoxLayout* mid_layout = new QVBoxLayout(group_box); + QWidget* mid_widget = new QWidget(group_box); + mid_layout->addWidget(mid_widget); + mid_layout-setContentsMargins(0, 0, 0, 0); + + QFont font = group_box->font(); + mid_widget->setFont(font); + font.setBold(true); + group_box->setFont(font); +#endif + + QVBoxLayout* group_layout = new QVBoxLayout(m_group_box); + group_layout->setAlignment(Qt::AlignTop); + group_layout->setContentsMargins(0, 10, 0, 0); + + m_expand_text = new QWidget(m_group_box); + m_expand_text->setLayout(new QVBoxLayout()); + m_expand_text->layout()->addWidget(new QLabel("(double click to expand)", this)); + m_expand_text->setVisible(false); + group_layout->addWidget(m_expand_text); + + + m_options_holder = new QWidget(m_group_box); + group_layout->addWidget(m_options_holder); + m_options_layout = new QVBoxLayout(m_options_holder); + m_options_layout->setContentsMargins(0, 0, 0, 0); + + for (auto& item : value.options()){ + m_options.emplace_back(item->make_QtWidget(parent)); + m_options.back()->widget().setContentsMargins(5, 5, 5, 5); + m_options_layout->addWidget(&m_options.back()->widget()); + } + + if (value.restore_defaults_button_enabled()){ + m_restore_defaults_button = new QPushButton("Restore Defaults", this); + m_restore_defaults_button->setContentsMargins(5, 5, 5, 5); + QHBoxLayout* row = new QHBoxLayout(); + m_options_layout->addLayout(row); + row->addWidget(m_restore_defaults_button, 1); + row->addStretch(3); + connect( + m_restore_defaults_button, &QPushButton::clicked, + this, [this](bool on){ + QMessageBox::StandardButton button = QMessageBox::question( + nullptr, + "Restore Defaults", + "Are you sure you wish to restore this section back to defaults?", + QMessageBox::Ok | QMessageBox::Cancel + ); + if (button == QMessageBox::Ok){ + m_value.restore_defaults(); + } + } + ); + } + + connect( + m_group_box, &QGroupBox::toggled, + this, [this](bool on){ + m_value.set_enabled(on); +// m_value.on_set_enabled(on); + } + ); + + value.add_listener(*this); +} + +#if 0 +void GroupWidget::set_options_enabled(bool enabled){ + for (ConfigWidget* item : m_options){ + item->widget().setEnabled(enabled); + } +} +#endif +void GroupWidget::update_value(){ + bool on = m_value.enabled(); +// cout << "on = " << on << endl; + m_group_box->setChecked(on); + for (ConfigWidget* item : m_options){ + item->update_value(); + } +} +void GroupWidget::on_config_value_changed(void* object){ +// cout << "GroupWidget::value_changed()" << endl; + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} +void GroupWidget::mouseDoubleClickEvent(QMouseEvent*){ + m_expand_text->setVisible(m_expanded); + m_expanded = !m_expanded; + m_options_holder->setVisible(m_expanded); +} + + + + +} diff --git a/Common/Qt/Options/GroupWidget.h b/Common/Qt/Options/GroupWidget.h index 49f49924d0..f2e5cbf224 100644 --- a/Common/Qt/Options/GroupWidget.h +++ b/Common/Qt/Options/GroupWidget.h @@ -1,49 +1,49 @@ -/* Group Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ConfigWidget.h" -#include "Common/Cpp/Options/GroupOption.h" - -#ifndef PokemonAutomation_Options_GroupWidget_H -#define PokemonAutomation_Options_GroupWidget_H - -class QVBoxLayout; -class QGroupBox; -class QPushButton; - -namespace PokemonAutomation{ - - - -class GroupWidget : public QWidget, public ConfigWidget{ -public: - ~GroupWidget(); - GroupWidget(QWidget& parent, GroupOption& value); - -// void set_options_enabled(bool enabled); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - virtual void mouseDoubleClickEvent(QMouseEvent* event) override; - -protected: - GroupOption& m_value; - QGroupBox* m_group_box; - QWidget* m_expand_text; - QWidget* m_options_holder; - std::vector m_options; - QPushButton* m_restore_defaults_button; - bool m_expanded = true; - QVBoxLayout* m_options_layout; -}; - - - -} -#endif +/* Group Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ConfigWidget.h" +#include "Common/Cpp/Options/GroupOption.h" + +#ifndef PokemonAutomation_Options_GroupWidget_H +#define PokemonAutomation_Options_GroupWidget_H + +class QVBoxLayout; +class QGroupBox; +class QPushButton; + +namespace PokemonAutomation{ + + + +class GroupWidget : public QWidget, public ConfigWidget{ +public: + ~GroupWidget(); + GroupWidget(QWidget& parent, GroupOption& value); + +// void set_options_enabled(bool enabled); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + virtual void mouseDoubleClickEvent(QMouseEvent* event) override; + +protected: + GroupOption& m_value; + QGroupBox* m_group_box; + QWidget* m_expand_text; + QWidget* m_options_holder; + std::vector m_options; + QPushButton* m_restore_defaults_button; + bool m_expanded = true; + QVBoxLayout* m_options_layout; +}; + + + +} +#endif diff --git a/Common/Qt/Options/IntegerRangeWidget.cpp b/Common/Qt/Options/IntegerRangeWidget.cpp index e9be85b9ac..da24643c06 100644 --- a/Common/Qt/Options/IntegerRangeWidget.cpp +++ b/Common/Qt/Options/IntegerRangeWidget.cpp @@ -1,94 +1,94 @@ -/* Integer Range Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "ConfigWidget.h" -#include "IntegerRangeWidget.h" - -namespace PokemonAutomation{ - - -template -IntegerRangeCellWidget::~IntegerRangeCellWidget(){ - m_value.remove_listener(*this); -} -template -IntegerRangeCellWidget::IntegerRangeCellWidget(QWidget& parent, IntegerRangeCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - - m_lo = new QLineEdit(this); - m_hi = new QLineEdit(this); - layout->addWidget(m_lo); - layout->addWidget(new QLabel(" - ", this)); - layout->addWidget(m_hi); - - Type lo, hi; - value.current_values(lo, hi); - m_lo->setText(QString::number(lo)); - m_hi->setText(QString::number(hi)); - - if (sizeof(Type) <= 1){ - m_lo->setMaximumWidth(30); - m_hi->setMaximumWidth(30); - } - - connect( - m_lo, &QLineEdit::editingFinished, - this, [this](){ - bool ok; - if (std::is_unsigned_v){ - uint64_t current = m_lo->text().toULongLong(&ok); - m_value.set_lo((Type)current); - }else{ - uint64_t current = m_lo->text().toLongLong(&ok); - m_value.set_lo((Type)current); - } - } - ); - connect( - m_hi, &QLineEdit::editingFinished, - this, [this](){ - bool ok; - if (std::is_unsigned_v){ - uint64_t current = m_hi->text().toULongLong(&ok); - m_value.set_hi((Type)current); - }else{ - uint64_t current = m_hi->text().toLongLong(&ok); - m_value.set_hi((Type)current); - } - } - ); - - value.add_listener(*this); -} -template -void IntegerRangeCellWidget::update_value(){ - Type lo, hi; - m_value.current_values(lo, hi); - m_lo->setText(QString::number(lo)); - m_hi->setText(QString::number(hi)); -} -template -void IntegerRangeCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - -template class IntegerRangeCellWidget; - - - - -} +/* Integer Range Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "ConfigWidget.h" +#include "IntegerRangeWidget.h" + +namespace PokemonAutomation{ + + +template +IntegerRangeCellWidget::~IntegerRangeCellWidget(){ + m_value.remove_listener(*this); +} +template +IntegerRangeCellWidget::IntegerRangeCellWidget(QWidget& parent, IntegerRangeCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + + m_lo = new QLineEdit(this); + m_hi = new QLineEdit(this); + layout->addWidget(m_lo); + layout->addWidget(new QLabel(" - ", this)); + layout->addWidget(m_hi); + + Type lo, hi; + value.current_values(lo, hi); + m_lo->setText(QString::number(lo)); + m_hi->setText(QString::number(hi)); + + if (sizeof(Type) <= 1){ + m_lo->setMaximumWidth(30); + m_hi->setMaximumWidth(30); + } + + connect( + m_lo, &QLineEdit::editingFinished, + this, [this](){ + bool ok; + if (std::is_unsigned_v){ + uint64_t current = m_lo->text().toULongLong(&ok); + m_value.set_lo((Type)current); + }else{ + uint64_t current = m_lo->text().toLongLong(&ok); + m_value.set_lo((Type)current); + } + } + ); + connect( + m_hi, &QLineEdit::editingFinished, + this, [this](){ + bool ok; + if (std::is_unsigned_v){ + uint64_t current = m_hi->text().toULongLong(&ok); + m_value.set_hi((Type)current); + }else{ + uint64_t current = m_hi->text().toLongLong(&ok); + m_value.set_hi((Type)current); + } + } + ); + + value.add_listener(*this); +} +template +void IntegerRangeCellWidget::update_value(){ + Type lo, hi; + m_value.current_values(lo, hi); + m_lo->setText(QString::number(lo)); + m_hi->setText(QString::number(hi)); +} +template +void IntegerRangeCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + +template class IntegerRangeCellWidget; + + + + +} diff --git a/Common/Qt/Options/IntegerRangeWidget.h b/Common/Qt/Options/IntegerRangeWidget.h index 38c6e3fed3..c191060131 100644 --- a/Common/Qt/Options/IntegerRangeWidget.h +++ b/Common/Qt/Options/IntegerRangeWidget.h @@ -1,39 +1,39 @@ -/* Integer Range Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_IntegerRangeWidget_H -#define PokemonAutomation_IntegerRangeWidget_H - -#include -#include "ConfigWidget.h" -#include "Common/Cpp/Options/IntegerRangeOption.h" - -namespace PokemonAutomation{ - - - -template -class IntegerRangeCellWidget : public QWidget, public ConfigWidget{ -public: - ~IntegerRangeCellWidget(); - IntegerRangeCellWidget(QWidget& parent, IntegerRangeCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - IntegerRangeCell& m_value; - QLineEdit* m_lo; - QLineEdit* m_hi; -}; - - - - - - -} -#endif +/* Integer Range Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_IntegerRangeWidget_H +#define PokemonAutomation_IntegerRangeWidget_H + +#include +#include "ConfigWidget.h" +#include "Common/Cpp/Options/IntegerRangeOption.h" + +namespace PokemonAutomation{ + + + +template +class IntegerRangeCellWidget : public QWidget, public ConfigWidget{ +public: + ~IntegerRangeCellWidget(); + IntegerRangeCellWidget(QWidget& parent, IntegerRangeCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + IntegerRangeCell& m_value; + QLineEdit* m_lo; + QLineEdit* m_hi; +}; + + + + + + +} +#endif diff --git a/Common/Qt/Options/KeyBindingWidget.cpp b/Common/Qt/Options/KeyBindingWidget.cpp index 3fe755c19f..6a26618a69 100644 --- a/Common/Qt/Options/KeyBindingWidget.cpp +++ b/Common/Qt/Options/KeyBindingWidget.cpp @@ -1,60 +1,60 @@ -/* Key Binding Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "KeyBindingWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* KeyBindingCell::make_QtWidget(QWidget& parent){ - return new KeyBindingCellWidget(parent, *this); -} - - - -KeyBindingCellWidget::~KeyBindingCellWidget(){ - m_value.remove_listener(*this); -} -KeyBindingCellWidget::KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value) - : QLineEdit(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - KeyBindingCellWidget::update_value(); - m_value.add_listener(*this); -} - - -void KeyBindingCellWidget::keyPressEvent(QKeyEvent* event){ - m_value.set(event->key()); -} - - -void KeyBindingCellWidget::update_value(){ - QKeySequence seq((Qt::Key)(uint32_t)m_value); -// cout << (uint32_t)m_value << endl; - this->setText(seq.toString()); -} -void KeyBindingCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - - - -} +/* Key Binding Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "KeyBindingWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* KeyBindingCell::make_QtWidget(QWidget& parent){ + return new KeyBindingCellWidget(parent, *this); +} + + + +KeyBindingCellWidget::~KeyBindingCellWidget(){ + m_value.remove_listener(*this); +} +KeyBindingCellWidget::KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value) + : QLineEdit(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + KeyBindingCellWidget::update_value(); + m_value.add_listener(*this); +} + + +void KeyBindingCellWidget::keyPressEvent(QKeyEvent* event){ + m_value.set(event->key()); +} + + +void KeyBindingCellWidget::update_value(){ + QKeySequence seq((Qt::Key)(uint32_t)m_value); +// cout << (uint32_t)m_value << endl; + this->setText(seq.toString()); +} +void KeyBindingCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + + + +} diff --git a/Common/Qt/Options/KeyBindingWidget.h b/Common/Qt/Options/KeyBindingWidget.h index b492102077..21877003ac 100644 --- a/Common/Qt/Options/KeyBindingWidget.h +++ b/Common/Qt/Options/KeyBindingWidget.h @@ -1,36 +1,36 @@ -/* Key Binding Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_KeyBindingWidget_H -#define PokemonAutomation_Options_KeyBindingWidget_H - -#include -#include "Common/Cpp/Options/KeyBindingOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -class KeyBindingCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~KeyBindingCellWidget(); - KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - - virtual void keyPressEvent(QKeyEvent* event) override; - -private: - KeyBindingCell& m_value; -}; - - - - -} -#endif +/* Key Binding Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_KeyBindingWidget_H +#define PokemonAutomation_Options_KeyBindingWidget_H + +#include +#include "Common/Cpp/Options/KeyBindingOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +class KeyBindingCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~KeyBindingCellWidget(); + KeyBindingCellWidget(QWidget& parent, KeyBindingCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + + virtual void keyPressEvent(QKeyEvent* event) override; + +private: + KeyBindingCell& m_value; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/MacAddressWidget.cpp b/Common/Qt/Options/MacAddressWidget.cpp index 1085de25e8..ee897ade12 100644 --- a/Common/Qt/Options/MacAddressWidget.cpp +++ b/Common/Qt/Options/MacAddressWidget.cpp @@ -1,50 +1,50 @@ -/* MAC Address Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ConfigWidget.h" -#include "MacAddressWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -MacAddressCellWidget::~MacAddressCellWidget(){ - m_value.remove_listener(*this); -} - -MacAddressCellWidget::MacAddressCellWidget(QWidget& parent, MacAddressCell& value) - : QLineEdit(QString::fromStdString(value.to_string()), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ -// cout << "sizeHint() = " << this->sizeHint().width() << endl; - - this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); - - connect( - this, &QLineEdit::editingFinished, - this, [this](){ - m_value.set(this->text().toStdString()); - } - ); - value.add_listener(*this); -} -void MacAddressCellWidget::update_value(){ - this->setText(QString::fromStdString(m_value.to_string())); -} -void MacAddressCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - -} +/* MAC Address Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ConfigWidget.h" +#include "MacAddressWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +MacAddressCellWidget::~MacAddressCellWidget(){ + m_value.remove_listener(*this); +} + +MacAddressCellWidget::MacAddressCellWidget(QWidget& parent, MacAddressCell& value) + : QLineEdit(QString::fromStdString(value.to_string()), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ +// cout << "sizeHint() = " << this->sizeHint().width() << endl; + + this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); + + connect( + this, &QLineEdit::editingFinished, + this, [this](){ + m_value.set(this->text().toStdString()); + } + ); + value.add_listener(*this); +} +void MacAddressCellWidget::update_value(){ + this->setText(QString::fromStdString(m_value.to_string())); +} +void MacAddressCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + +} diff --git a/Common/Qt/Options/MacAddressWidget.h b/Common/Qt/Options/MacAddressWidget.h index c5039448ca..a5290aaf17 100644 --- a/Common/Qt/Options/MacAddressWidget.h +++ b/Common/Qt/Options/MacAddressWidget.h @@ -1,35 +1,35 @@ -/* MAC Address option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_MacAddressWidget_H -#define PokemonAutomation_MacAddressWidget_H - -#include -#include "ConfigWidget.h" -#include "Common/Cpp/Options/MacAddressOption.h" - -namespace PokemonAutomation{ - - - - -class MacAddressCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~MacAddressCellWidget(); - MacAddressCellWidget(QWidget& parent, MacAddressCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - MacAddressCell& m_value; -}; - - - - -} -#endif +/* MAC Address option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MacAddressWidget_H +#define PokemonAutomation_MacAddressWidget_H + +#include +#include "ConfigWidget.h" +#include "Common/Cpp/Options/MacAddressOption.h" + +namespace PokemonAutomation{ + + + + +class MacAddressCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~MacAddressCellWidget(); + MacAddressCellWidget(QWidget& parent, MacAddressCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + MacAddressCell& m_value; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/RandomCodeWidget.cpp b/Common/Qt/Options/RandomCodeWidget.cpp index 957f5f8f4f..5b7f2a6a67 100644 --- a/Common/Qt/Options/RandomCodeWidget.cpp +++ b/Common/Qt/Options/RandomCodeWidget.cpp @@ -1,145 +1,145 @@ -/* Random Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Qt/CodeValidator.h" -#include "RandomCodeWidget.h" - -namespace PokemonAutomation{ - - - -ConfigWidget* RandomCodeOption::make_QtWidget(QWidget& parent){ - return new RandomCodeWidget(parent, *this); -} - - -RandomCodeWidget::~RandomCodeWidget(){ - m_value.remove_listener(*this); -} -RandomCodeWidget::RandomCodeWidget(QWidget& parent, RandomCodeOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - - QVBoxLayout* right = new QVBoxLayout(); - layout->addLayout(right, 1); - - RaidCodeOption current = m_value; - - { - QHBoxLayout* box_row = new QHBoxLayout(); - right->addLayout(box_row); - - box_row->addWidget(new QLabel("Random Digits: ", this), 1); - - m_box_random = new QLineEdit(QString::number(current.random_digits()), this); - box_row->addWidget(m_box_random, 1); - m_box_random->setValidator(new QIntValidator(0, (int)current.total_digits(), this)); - } - { - QHBoxLayout* box_row = new QHBoxLayout(); - right->addLayout(box_row); - - m_label_code = new QLabel("Raid Code: ", this); - box_row->addWidget(m_label_code, 1); - - m_box_code = new QLineEdit(QString::fromStdString(current.code_string()), this); - box_row->addWidget(m_box_code, 1); - } - m_under_text = new QLabel(QString::fromStdString(sanitized_code(current.code_string())), this); - right->addWidget(m_under_text); - update_labels(); - - connect( - m_box_random, &QLineEdit::textChanged, - this, [this](const QString& text){ - int read = text.toInt(); - RaidCodeOption code = m_value; - code.m_random_digits = read; - m_under_text->setText(QString::fromStdString(sanitized_code(text.toStdString()))); - m_value.set(code); - } - ); - connect( - m_box_code, &QLineEdit::textChanged, - this, [this](const QString& text){ - RaidCodeOption code = m_value; - code.m_code = text.toStdString(); - m_under_text->setText(QString::fromStdString(sanitized_code(text.toStdString()))); - m_value.set(code); - } - ); - - m_value.add_listener(*this); -} -std::string RandomCodeWidget::sanitized_code(const std::string& text) const{ - if (text.empty()){ - return "No Raid Code"; - } - std::string message; - try{ - RaidCodeOption current = m_value; - message = "Fixed Raid Code: " + sanitize_code(current.total_digits(), text); - }catch (const ParseException& e){ - message = "" + e.message() + ""; - } - return message; -} -std::string RandomCodeWidget::random_code_string() const{ - std::string str; - char ch = 'A' - 1; - RaidCodeOption current = m_value; - size_t c = 0; - for (; c < current.random_digits(); c++){ - ch++; - str += ch; - } - for (; c < current.total_digits(); c++){ - str += ch; - } - return str; -} -void RandomCodeWidget::update_labels(){ - RaidCodeOption current = m_value; - if (current.random_digits() == 0){ -// m_label_code->setText("Raid Code: "); -// m_code_row->setEnabled(true); - m_box_code->setEnabled(true); - m_under_text->setText(QString::fromStdString(sanitized_code(current.code_string()))); - }else{ -// m_label_code->setText("RNG Seed: "); -// m_code_row->setEnabled(false); - m_box_code->setEnabled(false); - m_under_text->setText(QString::fromStdString("Random Code: " + random_code_string())); - } -} -void RandomCodeWidget::update_value(){ - RaidCodeOption current = m_value; - m_box_random->setText(QString::number(current.random_digits())); - m_box_code->setText(QString::fromStdString(current.code_string())); - update_labels(); -} -void RandomCodeWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - -} +/* Random Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Qt/CodeValidator.h" +#include "RandomCodeWidget.h" + +namespace PokemonAutomation{ + + + +ConfigWidget* RandomCodeOption::make_QtWidget(QWidget& parent){ + return new RandomCodeWidget(parent, *this); +} + + +RandomCodeWidget::~RandomCodeWidget(){ + m_value.remove_listener(*this); +} +RandomCodeWidget::RandomCodeWidget(QWidget& parent, RandomCodeOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + + QVBoxLayout* right = new QVBoxLayout(); + layout->addLayout(right, 1); + + RaidCodeOption current = m_value; + + { + QHBoxLayout* box_row = new QHBoxLayout(); + right->addLayout(box_row); + + box_row->addWidget(new QLabel("Random Digits: ", this), 1); + + m_box_random = new QLineEdit(QString::number(current.random_digits()), this); + box_row->addWidget(m_box_random, 1); + m_box_random->setValidator(new QIntValidator(0, (int)current.total_digits(), this)); + } + { + QHBoxLayout* box_row = new QHBoxLayout(); + right->addLayout(box_row); + + m_label_code = new QLabel("Raid Code: ", this); + box_row->addWidget(m_label_code, 1); + + m_box_code = new QLineEdit(QString::fromStdString(current.code_string()), this); + box_row->addWidget(m_box_code, 1); + } + m_under_text = new QLabel(QString::fromStdString(sanitized_code(current.code_string())), this); + right->addWidget(m_under_text); + update_labels(); + + connect( + m_box_random, &QLineEdit::textChanged, + this, [this](const QString& text){ + int read = text.toInt(); + RaidCodeOption code = m_value; + code.m_random_digits = read; + m_under_text->setText(QString::fromStdString(sanitized_code(text.toStdString()))); + m_value.set(code); + } + ); + connect( + m_box_code, &QLineEdit::textChanged, + this, [this](const QString& text){ + RaidCodeOption code = m_value; + code.m_code = text.toStdString(); + m_under_text->setText(QString::fromStdString(sanitized_code(text.toStdString()))); + m_value.set(code); + } + ); + + m_value.add_listener(*this); +} +std::string RandomCodeWidget::sanitized_code(const std::string& text) const{ + if (text.empty()){ + return "No Raid Code"; + } + std::string message; + try{ + RaidCodeOption current = m_value; + message = "Fixed Raid Code: " + sanitize_code(current.total_digits(), text); + }catch (const ParseException& e){ + message = "" + e.message() + ""; + } + return message; +} +std::string RandomCodeWidget::random_code_string() const{ + std::string str; + char ch = 'A' - 1; + RaidCodeOption current = m_value; + size_t c = 0; + for (; c < current.random_digits(); c++){ + ch++; + str += ch; + } + for (; c < current.total_digits(); c++){ + str += ch; + } + return str; +} +void RandomCodeWidget::update_labels(){ + RaidCodeOption current = m_value; + if (current.random_digits() == 0){ +// m_label_code->setText("Raid Code: "); +// m_code_row->setEnabled(true); + m_box_code->setEnabled(true); + m_under_text->setText(QString::fromStdString(sanitized_code(current.code_string()))); + }else{ +// m_label_code->setText("RNG Seed: "); +// m_code_row->setEnabled(false); + m_box_code->setEnabled(false); + m_under_text->setText(QString::fromStdString("Random Code: " + random_code_string())); + } +} +void RandomCodeWidget::update_value(){ + RaidCodeOption current = m_value; + m_box_random->setText(QString::number(current.random_digits())); + m_box_code->setText(QString::fromStdString(current.code_string())); + update_labels(); +} +void RandomCodeWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + +} diff --git a/Common/Qt/Options/RandomCodeWidget.h b/Common/Qt/Options/RandomCodeWidget.h index cdcf15621e..e0355e78dc 100644 --- a/Common/Qt/Options/RandomCodeWidget.h +++ b/Common/Qt/Options/RandomCodeWidget.h @@ -1,46 +1,46 @@ -/* Random Code Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_RandomCodeWidget_H -#define PokemonAutomation_Options_RandomCodeWidget_H - -#include -#include "Common/Cpp/Options/RandomCodeOption.h" -#include "ConfigWidget.h" - -class QLabel; -class QLineEdit; - -namespace PokemonAutomation{ - - - -class RandomCodeWidget : public QWidget, public ConfigWidget{ -public: - ~RandomCodeWidget(); - RandomCodeWidget(QWidget& parent, RandomCodeOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - std::string sanitized_code(const std::string& text) const; - std::string random_code_string() const; - void update_labels(); - -private: - RandomCodeOption& m_value; - QLabel* m_label_code; - QLabel* m_under_text; - QLineEdit* m_box_random; - QLineEdit* m_box_code; -}; - - - - -} -#endif +/* Random Code Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_RandomCodeWidget_H +#define PokemonAutomation_Options_RandomCodeWidget_H + +#include +#include "Common/Cpp/Options/RandomCodeOption.h" +#include "ConfigWidget.h" + +class QLabel; +class QLineEdit; + +namespace PokemonAutomation{ + + + +class RandomCodeWidget : public QWidget, public ConfigWidget{ +public: + ~RandomCodeWidget(); + RandomCodeWidget(QWidget& parent, RandomCodeOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + std::string sanitized_code(const std::string& text) const; + std::string random_code_string() const; + void update_labels(); + +private: + RandomCodeOption& m_value; + QLabel* m_label_code; + QLabel* m_under_text; + QLineEdit* m_box_random; + QLineEdit* m_box_code; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/SimpleIntegerWidget.cpp b/Common/Qt/Options/SimpleIntegerWidget.cpp index 1ec19b6601..98ca4470b2 100644 --- a/Common/Qt/Options/SimpleIntegerWidget.cpp +++ b/Common/Qt/Options/SimpleIntegerWidget.cpp @@ -1,139 +1,139 @@ -/* Simple Integer Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "ConfigWidget.h" -#include "SimpleIntegerWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - -template -SimpleIntegerCellWidget::~SimpleIntegerCellWidget(){ - m_value.remove_listener(*this); -} -template -SimpleIntegerCellWidget::SimpleIntegerCellWidget(QWidget& parent, SimpleIntegerCell& value) - : QLineEdit(QString::number(value), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ -// cout << "sizeHint() = " << this->sizeHint().width() << endl; - - this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); - - connect( - this, &QLineEdit::textChanged, - this, [this](const QString& text){ - bool ok; - Type current = (Type)text.toLong(&ok); - QPalette palette; - if (ok && m_value.check_validity(current).empty()){ - palette.setColor(QPalette::Text, Qt::black); - }else{ - palette.setColor(QPalette::Text, Qt::red); - } - this->setPalette(palette); - } - ); - connect( - this, &QLineEdit::editingFinished, - this, [this](){ - bool ok; - if (std::is_unsigned_v){ - uint64_t current = this->text().toULongLong(&ok); - current = std::max(current, m_value.min_value()); - current = std::min(current, m_value.max_value()); - this->setText(QString::number(current)); - m_value.set((Type)current); - }else{ - int64_t current = this->text().toLongLong(&ok); - current = std::max(current, m_value.min_value()); - current = std::min(current, m_value.max_value()); - this->setText(QString::number(current)); - m_value.set((Type)current); - } - } - ); - value.add_listener(*this); -} -template -void SimpleIntegerCellWidget::update_value(){ - this->setText(QString::number(m_value)); -} -template -void SimpleIntegerCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - - -template -SimpleIntegerOptionWidget::~SimpleIntegerOptionWidget(){ - m_value.remove_listener(*this); -} -template -SimpleIntegerOptionWidget::SimpleIntegerOptionWidget(QWidget& parent, SimpleIntegerOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_cell(new SimpleIntegerCellWidget(*this, value)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - layout->addWidget(m_cell, 1); - value.add_listener(*this); -} -template -void SimpleIntegerOptionWidget::update_value(){ - m_cell->update_value(); -} -template -void SimpleIntegerOptionWidget::on_config_value_changed(void* object){ - m_cell->on_config_value_changed(object); -} - - - -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; -template class SimpleIntegerCellWidget; - -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; -template class SimpleIntegerOptionWidget; - - -} +/* Simple Integer Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "ConfigWidget.h" +#include "SimpleIntegerWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +template +SimpleIntegerCellWidget::~SimpleIntegerCellWidget(){ + m_value.remove_listener(*this); +} +template +SimpleIntegerCellWidget::SimpleIntegerCellWidget(QWidget& parent, SimpleIntegerCell& value) + : QLineEdit(QString::number(value), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ +// cout << "sizeHint() = " << this->sizeHint().width() << endl; + + this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); + + connect( + this, &QLineEdit::textChanged, + this, [this](const QString& text){ + bool ok; + Type current = (Type)text.toLong(&ok); + QPalette palette; + if (ok && m_value.check_validity(current).empty()){ + palette.setColor(QPalette::Text, Qt::black); + }else{ + palette.setColor(QPalette::Text, Qt::red); + } + this->setPalette(palette); + } + ); + connect( + this, &QLineEdit::editingFinished, + this, [this](){ + bool ok; + if (std::is_unsigned_v){ + uint64_t current = this->text().toULongLong(&ok); + current = std::max(current, m_value.min_value()); + current = std::min(current, m_value.max_value()); + this->setText(QString::number(current)); + m_value.set((Type)current); + }else{ + int64_t current = this->text().toLongLong(&ok); + current = std::max(current, m_value.min_value()); + current = std::min(current, m_value.max_value()); + this->setText(QString::number(current)); + m_value.set((Type)current); + } + } + ); + value.add_listener(*this); +} +template +void SimpleIntegerCellWidget::update_value(){ + this->setText(QString::number(m_value)); +} +template +void SimpleIntegerCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + + +template +SimpleIntegerOptionWidget::~SimpleIntegerOptionWidget(){ + m_value.remove_listener(*this); +} +template +SimpleIntegerOptionWidget::SimpleIntegerOptionWidget(QWidget& parent, SimpleIntegerOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_cell(new SimpleIntegerCellWidget(*this, value)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + layout->addWidget(m_cell, 1); + value.add_listener(*this); +} +template +void SimpleIntegerOptionWidget::update_value(){ + m_cell->update_value(); +} +template +void SimpleIntegerOptionWidget::on_config_value_changed(void* object){ + m_cell->on_config_value_changed(object); +} + + + +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; +template class SimpleIntegerCellWidget; + +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; +template class SimpleIntegerOptionWidget; + + +} diff --git a/Common/Qt/Options/SimpleIntegerWidget.h b/Common/Qt/Options/SimpleIntegerWidget.h index 05f050bfb2..6f32f3bd0d 100644 --- a/Common/Qt/Options/SimpleIntegerWidget.h +++ b/Common/Qt/Options/SimpleIntegerWidget.h @@ -1,50 +1,50 @@ -/* Simple Integer Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SimpleIntegerWidget_H -#define PokemonAutomation_SimpleIntegerWidget_H - -#include -#include "ConfigWidget.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ - - - -template -class SimpleIntegerCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~SimpleIntegerCellWidget(); - SimpleIntegerCellWidget(QWidget& parent, SimpleIntegerCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - SimpleIntegerCell& m_value; -}; - - - -template -class SimpleIntegerOptionWidget : public QWidget, public ConfigWidget{ -public: - ~SimpleIntegerOptionWidget(); - SimpleIntegerOptionWidget(QWidget& parent, SimpleIntegerOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - SimpleIntegerCellWidget* m_cell; -}; - - - - -} -#endif +/* Simple Integer Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SimpleIntegerWidget_H +#define PokemonAutomation_SimpleIntegerWidget_H + +#include +#include "ConfigWidget.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ + + + +template +class SimpleIntegerCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~SimpleIntegerCellWidget(); + SimpleIntegerCellWidget(QWidget& parent, SimpleIntegerCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + SimpleIntegerCell& m_value; +}; + + + +template +class SimpleIntegerOptionWidget : public QWidget, public ConfigWidget{ +public: + ~SimpleIntegerOptionWidget(); + SimpleIntegerOptionWidget(QWidget& parent, SimpleIntegerOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + SimpleIntegerCellWidget* m_cell; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/StaticTableWidget.cpp b/Common/Qt/Options/StaticTableWidget.cpp index c10ffa6c72..770a03fbbb 100644 --- a/Common/Qt/Options/StaticTableWidget.cpp +++ b/Common/Qt/Options/StaticTableWidget.cpp @@ -1,122 +1,122 @@ -/* Static Table Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/AutoHeightTable.h" -#include "StaticTableWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget* StaticTableOption::make_QtWidget(QWidget& parent){ - return new StaticTableWidget(parent, *this); -} - - - -StaticTableWidget::~StaticTableWidget(){} -StaticTableWidget::StaticTableWidget(QWidget& parent, StaticTableOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) - , m_table(nullptr) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - if (!value.label().empty()){ - QLabel* label = new QLabel(QString::fromStdString(value.label()), this); - label->setWordWrap(true); - layout->addWidget(label); - } - - m_table = new AutoHeightTableWidget(this); - layout->addWidget(m_table, 0, Qt::AlignTop); - - const std::vector& table = value.table(); -// cout << "table = " << table.size() << endl; - - QStringList header; - for (const std::string& name : m_value.make_header()){ - header << QString::fromStdString(name); - } - m_table->setColumnCount(int(header.size())); - m_table->setRowCount((int)table.size()); - m_table->setHorizontalHeaderLabels(header); - - QFont font; - font.setBold(true); - m_table->horizontalHeader()->setFont(font); -// m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); - m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); - - for (size_t r = 0; r < table.size(); r++){ - std::vector cells = table[r]->make_cells(); - for (size_t c = 0; c < cells.size(); c++){ - m_table->setCellWidget((int)r, (int)c, &cells[c]->make_QtWidget(*this)->widget()); - } - } - - m_table->resizeColumnsToContents(); - m_table->resizeRowsToContents(); - m_table->update_height(); - - if (value.saveload_enabled()){ - QHBoxLayout* buttons = new QHBoxLayout(); - layout->addLayout(buttons); - { - QPushButton* load_button = new QPushButton("Load Table", this); - buttons->addWidget(load_button, 1); - connect( - load_button, &QPushButton::clicked, - this, [this, &value](bool){ - std::string path = QFileDialog::getOpenFileName( - this, - tr("Select a file to load."), "", tr("JSON files (*.json)") - ).toStdString(); - if (path.empty()){ - return; - } - value.load_json(load_json_file(path)); - } - ); - } - { - QPushButton* save_button = new QPushButton("Save Table", this); - buttons->addWidget(save_button, 1); - connect( - save_button, &QPushButton::clicked, - this, [this, &value](bool){ - std::string path = QFileDialog::getSaveFileName( - this, - tr("Select a file name to save to."), "", tr("JSON files (*.json)") - ).toStdString(); - if (path.empty()){ - return; - } - JsonValue json = value.to_json(); - json.dump(path); - } - ); - } - buttons->addStretch(2); - } -} - - - -} +/* Static Table Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/AutoHeightTable.h" +#include "StaticTableWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget* StaticTableOption::make_QtWidget(QWidget& parent){ + return new StaticTableWidget(parent, *this); +} + + + +StaticTableWidget::~StaticTableWidget(){} +StaticTableWidget::StaticTableWidget(QWidget& parent, StaticTableOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) + , m_table(nullptr) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + if (!value.label().empty()){ + QLabel* label = new QLabel(QString::fromStdString(value.label()), this); + label->setWordWrap(true); + layout->addWidget(label); + } + + m_table = new AutoHeightTableWidget(this); + layout->addWidget(m_table, 0, Qt::AlignTop); + + const std::vector& table = value.table(); +// cout << "table = " << table.size() << endl; + + QStringList header; + for (const std::string& name : m_value.make_header()){ + header << QString::fromStdString(name); + } + m_table->setColumnCount(int(header.size())); + m_table->setRowCount((int)table.size()); + m_table->setHorizontalHeaderLabels(header); + + QFont font; + font.setBold(true); + m_table->horizontalHeader()->setFont(font); +// m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + m_table->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive); + + for (size_t r = 0; r < table.size(); r++){ + std::vector cells = table[r]->make_cells(); + for (size_t c = 0; c < cells.size(); c++){ + m_table->setCellWidget((int)r, (int)c, &cells[c]->make_QtWidget(*this)->widget()); + } + } + + m_table->resizeColumnsToContents(); + m_table->resizeRowsToContents(); + m_table->update_height(); + + if (value.saveload_enabled()){ + QHBoxLayout* buttons = new QHBoxLayout(); + layout->addLayout(buttons); + { + QPushButton* load_button = new QPushButton("Load Table", this); + buttons->addWidget(load_button, 1); + connect( + load_button, &QPushButton::clicked, + this, [this, &value](bool){ + std::string path = QFileDialog::getOpenFileName( + this, + tr("Select a file to load."), "", tr("JSON files (*.json)") + ).toStdString(); + if (path.empty()){ + return; + } + value.load_json(load_json_file(path)); + } + ); + } + { + QPushButton* save_button = new QPushButton("Save Table", this); + buttons->addWidget(save_button, 1); + connect( + save_button, &QPushButton::clicked, + this, [this, &value](bool){ + std::string path = QFileDialog::getSaveFileName( + this, + tr("Select a file name to save to."), "", tr("JSON files (*.json)") + ).toStdString(); + if (path.empty()){ + return; + } + JsonValue json = value.to_json(); + json.dump(path); + } + ); + } + buttons->addStretch(2); + } +} + + + +} diff --git a/Common/Qt/Options/StaticTableWidget.h b/Common/Qt/Options/StaticTableWidget.h index 06af5d6cfe..d7c45e2b2d 100644 --- a/Common/Qt/Options/StaticTableWidget.h +++ b/Common/Qt/Options/StaticTableWidget.h @@ -1,34 +1,34 @@ -/* Static Table Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_StaticTableWidget_H -#define PokemonAutomation_Options_StaticTableWidget_H - -#include -#include "Common/Cpp/Options/StaticTableOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - -class AutoHeightTableWidget; - - -class StaticTableWidget : public QWidget, public ConfigWidget{ -public: - ~StaticTableWidget(); - StaticTableWidget(QWidget& parent, StaticTableOption& value); - -private: - StaticTableOption& m_value; - AutoHeightTableWidget* m_table; - std::vector> m_current; -}; - - - - -} -#endif +/* Static Table Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_StaticTableWidget_H +#define PokemonAutomation_Options_StaticTableWidget_H + +#include +#include "Common/Cpp/Options/StaticTableOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + +class AutoHeightTableWidget; + + +class StaticTableWidget : public QWidget, public ConfigWidget{ +public: + ~StaticTableWidget(); + StaticTableWidget(QWidget& parent, StaticTableOption& value); + +private: + StaticTableOption& m_value; + AutoHeightTableWidget* m_table; + std::vector> m_current; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/StaticTextWidget.cpp b/Common/Qt/Options/StaticTextWidget.cpp index 79bd0c1471..6cbbe783ec 100644 --- a/Common/Qt/Options/StaticTextWidget.cpp +++ b/Common/Qt/Options/StaticTextWidget.cpp @@ -1,91 +1,91 @@ -/* Static Text Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "StaticTextWidget.h" - -namespace PokemonAutomation{ - - - -ConfigWidget* StaticTextOption::make_QtWidget(QWidget& parent){ - return new StaticTextWidget(parent, *this); -} -ConfigWidget* SectionDividerOption::make_QtWidget(QWidget& parent){ - return new SectionDividerWidget(parent, *this); -} - - - - -StaticTextWidget::~StaticTextWidget(){ - m_value.remove_listener(*this); -} -StaticTextWidget::StaticTextWidget(QWidget& parent, StaticTextOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - m_text = new QLabel(QString::fromStdString(value.text()), this); - m_text->setWordWrap(value.text_wrapping()); - layout->addWidget(m_text); -// text->setTextInteractionFlags(Qt::TextBrowserInteraction); - m_text->setOpenExternalLinks(true); - - m_value.add_listener(*this); -} -void StaticTextWidget::update_value(){ - m_text->setText(QString::fromStdString(m_value.text())); -} -void StaticTextWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_text, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - -SectionDividerWidget::~SectionDividerWidget(){ - m_value.remove_listener(*this); -} -SectionDividerWidget::SectionDividerWidget(QWidget& parent, SectionDividerOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 10, 0, 0); - - QFrame* frame = new QFrame(this); - layout->addWidget(frame); - frame->setFrameShape(QFrame::HLine); - - m_text = new QLabel(QString::fromStdString(value.text()), this); - m_text->setWordWrap(value.text_wrapping()); - layout->addWidget(m_text); -// text->setTextInteractionFlags(Qt::TextBrowserInteraction); - m_text->setOpenExternalLinks(true); - - m_value.add_listener(*this); -} -void SectionDividerWidget::update_value(){ - m_text->setText(QString::fromStdString(m_value.text())); -} -void SectionDividerWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_text, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -} +/* Static Text Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "StaticTextWidget.h" + +namespace PokemonAutomation{ + + + +ConfigWidget* StaticTextOption::make_QtWidget(QWidget& parent){ + return new StaticTextWidget(parent, *this); +} +ConfigWidget* SectionDividerOption::make_QtWidget(QWidget& parent){ + return new SectionDividerWidget(parent, *this); +} + + + + +StaticTextWidget::~StaticTextWidget(){ + m_value.remove_listener(*this); +} +StaticTextWidget::StaticTextWidget(QWidget& parent, StaticTextOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + m_text = new QLabel(QString::fromStdString(value.text()), this); + m_text->setWordWrap(value.text_wrapping()); + layout->addWidget(m_text); +// text->setTextInteractionFlags(Qt::TextBrowserInteraction); + m_text->setOpenExternalLinks(true); + + m_value.add_listener(*this); +} +void StaticTextWidget::update_value(){ + m_text->setText(QString::fromStdString(m_value.text())); +} +void StaticTextWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_text, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + +SectionDividerWidget::~SectionDividerWidget(){ + m_value.remove_listener(*this); +} +SectionDividerWidget::SectionDividerWidget(QWidget& parent, SectionDividerOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 10, 0, 0); + + QFrame* frame = new QFrame(this); + layout->addWidget(frame); + frame->setFrameShape(QFrame::HLine); + + m_text = new QLabel(QString::fromStdString(value.text()), this); + m_text->setWordWrap(value.text_wrapping()); + layout->addWidget(m_text); +// text->setTextInteractionFlags(Qt::TextBrowserInteraction); + m_text->setOpenExternalLinks(true); + + m_value.add_listener(*this); +} +void SectionDividerWidget::update_value(){ + m_text->setText(QString::fromStdString(m_value.text())); +} +void SectionDividerWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_text, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +} diff --git a/Common/Qt/Options/StaticTextWidget.h b/Common/Qt/Options/StaticTextWidget.h index a32615fe1e..e782b3adf3 100644 --- a/Common/Qt/Options/StaticTextWidget.h +++ b/Common/Qt/Options/StaticTextWidget.h @@ -1,51 +1,51 @@ -/* Static Text Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_StaticTextWidget_H -#define PokemonAutomation_Options_StaticTextWidget_H - -#include -#include "Common/Cpp/Options/StaticTextOption.h" -#include "ConfigWidget.h" - -class QLabel; - -namespace PokemonAutomation{ - - - -class StaticTextWidget : public QWidget, public ConfigWidget{ -public: - ~StaticTextWidget(); - StaticTextWidget(QWidget& parent, StaticTextOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - StaticTextOption& m_value; - QLabel* m_text; -}; - - -class SectionDividerWidget : public QWidget, public ConfigWidget{ -public: - ~SectionDividerWidget(); - SectionDividerWidget(QWidget& parent, SectionDividerOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - SectionDividerOption& m_value; - QLabel* m_text; -}; - - - - -} -#endif +/* Static Text Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_StaticTextWidget_H +#define PokemonAutomation_Options_StaticTextWidget_H + +#include +#include "Common/Cpp/Options/StaticTextOption.h" +#include "ConfigWidget.h" + +class QLabel; + +namespace PokemonAutomation{ + + + +class StaticTextWidget : public QWidget, public ConfigWidget{ +public: + ~StaticTextWidget(); + StaticTextWidget(QWidget& parent, StaticTextOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + StaticTextOption& m_value; + QLabel* m_text; +}; + + +class SectionDividerWidget : public QWidget, public ConfigWidget{ +public: + ~SectionDividerWidget(); + SectionDividerWidget(QWidget& parent, SectionDividerOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + SectionDividerOption& m_value; + QLabel* m_text; +}; + + + + +} +#endif diff --git a/Common/Qt/Options/StringWidget.cpp b/Common/Qt/Options/StringWidget.cpp index 34fa56c386..f7ebb23064 100644 --- a/Common/Qt/Options/StringWidget.cpp +++ b/Common/Qt/Options/StringWidget.cpp @@ -1,120 +1,120 @@ -/* String Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "StringWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget* StringCell::make_QtWidget(QWidget& parent){ - return new StringCellWidget(parent, *this); -} - -ConfigWidget* StringOption::make_QtWidget(QWidget& parent){ - return new StringOptionWidget(parent, *this); -} - - - -StringCellWidget::~StringCellWidget(){ - m_value.remove_listener(*this); -} -StringCellWidget::StringCellWidget(QWidget& parent, StringCell& value) - : QLineEdit(QString::fromStdString(value), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - this->setPlaceholderText(QString::fromStdString(value.placeholder_text())); - - this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY || m_value.is_locked()); - if (m_value.is_password()){ - this->setEchoMode(QLineEdit::PasswordEchoOnEdit); - } - - connect( - this, &QLineEdit::editingFinished, - this, [this](){ - m_value.set(this->text().toStdString()); - } - ); - - m_value.add_listener(*this); -} -void StringCellWidget::update_value(){ - this->setText(QString::fromStdString(m_value)); -} -void StringCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} -void StringCellWidget::on_config_visibility_changed(){ - QMetaObject::invokeMethod(this, [this]{ - setReadOnly(m_value.lock_mode() == LockMode::READ_ONLY || m_value.is_locked()); - }, Qt::QueuedConnection); -} - - - - -StringOptionWidget::~StringOptionWidget(){ - m_value.remove_listener(*this); -} -StringOptionWidget::StringOptionWidget(QWidget& parent, StringOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - - m_box = new QLineEdit(QString::fromStdString(m_value), this); - m_box->setPlaceholderText(QString::fromStdString(value.placeholder_text())); - layout->addWidget(m_box, 1); - - m_box->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); - if (m_value.is_password()){ - m_box->setEchoMode(QLineEdit::PasswordEchoOnEdit); - } - - connect( - m_box, &QLineEdit::editingFinished, - this, [this](){ - m_value.set(m_box->text().toStdString()); - } - ); - - m_value.add_listener(*this); -} -void StringOptionWidget::update_value(){ - m_box->setText(QString::fromStdString(m_value)); -} -void StringOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} -void StringOptionWidget::on_config_visibility_changed(){ - QMetaObject::invokeMethod(m_box, [this]{ - m_box->setReadOnly(m_value.is_locked()); - }, Qt::QueuedConnection); -} - - - - - -} +/* String Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "StringWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget* StringCell::make_QtWidget(QWidget& parent){ + return new StringCellWidget(parent, *this); +} + +ConfigWidget* StringOption::make_QtWidget(QWidget& parent){ + return new StringOptionWidget(parent, *this); +} + + + +StringCellWidget::~StringCellWidget(){ + m_value.remove_listener(*this); +} +StringCellWidget::StringCellWidget(QWidget& parent, StringCell& value) + : QLineEdit(QString::fromStdString(value), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + this->setPlaceholderText(QString::fromStdString(value.placeholder_text())); + + this->setReadOnly(value.lock_mode() == LockMode::READ_ONLY || m_value.is_locked()); + if (m_value.is_password()){ + this->setEchoMode(QLineEdit::PasswordEchoOnEdit); + } + + connect( + this, &QLineEdit::editingFinished, + this, [this](){ + m_value.set(this->text().toStdString()); + } + ); + + m_value.add_listener(*this); +} +void StringCellWidget::update_value(){ + this->setText(QString::fromStdString(m_value)); +} +void StringCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} +void StringCellWidget::on_config_visibility_changed(){ + QMetaObject::invokeMethod(this, [this]{ + setReadOnly(m_value.lock_mode() == LockMode::READ_ONLY || m_value.is_locked()); + }, Qt::QueuedConnection); +} + + + + +StringOptionWidget::~StringOptionWidget(){ + m_value.remove_listener(*this); +} +StringOptionWidget::StringOptionWidget(QWidget& parent, StringOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + + m_box = new QLineEdit(QString::fromStdString(m_value), this); + m_box->setPlaceholderText(QString::fromStdString(value.placeholder_text())); + layout->addWidget(m_box, 1); + + m_box->setReadOnly(value.lock_mode() == LockMode::READ_ONLY); + if (m_value.is_password()){ + m_box->setEchoMode(QLineEdit::PasswordEchoOnEdit); + } + + connect( + m_box, &QLineEdit::editingFinished, + this, [this](){ + m_value.set(m_box->text().toStdString()); + } + ); + + m_value.add_listener(*this); +} +void StringOptionWidget::update_value(){ + m_box->setText(QString::fromStdString(m_value)); +} +void StringOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} +void StringOptionWidget::on_config_visibility_changed(){ + QMetaObject::invokeMethod(m_box, [this]{ + m_box->setReadOnly(m_value.is_locked()); + }, Qt::QueuedConnection); +} + + + + + +} diff --git a/Common/Qt/Options/StringWidget.h b/Common/Qt/Options/StringWidget.h index 22a5fec456..df9d1a574b 100644 --- a/Common/Qt/Options/StringWidget.h +++ b/Common/Qt/Options/StringWidget.h @@ -1,52 +1,52 @@ -/* String Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_StringWidget_H -#define PokemonAutomation_Options_StringWidget_H - -#include -#include "Common/Cpp/Options/StringOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -class StringCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~StringCellWidget(); - StringCellWidget(QWidget& parent, StringCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - virtual void on_config_visibility_changed() override; - -private: - StringCell& m_value; -}; - - - -class StringOptionWidget : public QWidget, public ConfigWidget{ -public: - ~StringOptionWidget(); - StringOptionWidget(QWidget& parent, StringOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - virtual void on_config_visibility_changed() override; - -private: - StringOption& m_value; - QLineEdit* m_box; -}; - - - - - -} -#endif +/* String Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_StringWidget_H +#define PokemonAutomation_Options_StringWidget_H + +#include +#include "Common/Cpp/Options/StringOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +class StringCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~StringCellWidget(); + StringCellWidget(QWidget& parent, StringCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + virtual void on_config_visibility_changed() override; + +private: + StringCell& m_value; +}; + + + +class StringOptionWidget : public QWidget, public ConfigWidget{ +public: + ~StringOptionWidget(); + StringOptionWidget(QWidget& parent, StringOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + virtual void on_config_visibility_changed() override; + +private: + StringOption& m_value; + QLineEdit* m_box; +}; + + + + + +} +#endif diff --git a/Common/Qt/Options/TextEditWidget.cpp b/Common/Qt/Options/TextEditWidget.cpp index 6d0595950a..00345d826e 100644 --- a/Common/Qt/Options/TextEditWidget.cpp +++ b/Common/Qt/Options/TextEditWidget.cpp @@ -1,122 +1,122 @@ -/* Text Edit Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "TextEditWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* TextEditOption::make_QtWidget(QWidget& parent){ - return new TextEditWidget(parent, *this); -} - - - -class TextEditWidget::Box : public QTextEdit{ -public: - Box(TextEditWidget& parent) - : QTextEdit(&parent) - , m_parent(parent) - { - this->setAcceptRichText(false); - this->setFocusPolicy(Qt::StrongFocus); - this->setPlaceholderText(QString::fromStdString(parent.m_value.placeholder_text())); - -// QPalette palette = this->palette(); -// palette.setColor(QPalette::Text, "blue"); -// palette.setColor(QPalette::PlaceholderText, "red"); -// this->setPalette(palette); - -// QColor default_color = this->textColor(); - - if (parent.m_value.signal_all_text_changes()){ - connect( - this, &QTextEdit::textChanged, - [this]{ - std::string new_value = (std::string)m_parent.m_value; - std::string text = this->toPlainText().toStdString(); - if (new_value == text){ - return; - } -// cout << new_value << " : " << text << endl; - m_parent.m_value.set(std::move(text)); - } - ); - } - -// this->hide(); - } - - virtual void focusInEvent(QFocusEvent* event) override{ - QTextEdit::focusInEvent(event); - m_parent.m_value.report_focus_in(); - } - virtual void focusOutEvent(QFocusEvent* event) override{ - QTextEdit::focusOutEvent(event); -// static size_t c = 0; -// cout << "focusOutEvent: " << c++ << endl; - m_parent.m_value.set(this->toPlainText().toStdString()); - } - -private: - TextEditWidget& m_parent; -}; - - - - - -TextEditWidget::~TextEditWidget(){ - m_value.ConfigOption::remove_listener(*this); -} -TextEditWidget::TextEditWidget(QWidget& parent, TextEditOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* label = new QLabel(QString::fromStdString(value.label()), this); - label->setWordWrap(true); - layout->addWidget(label); - m_box = new Box(*this); - m_box->setText(QString::fromStdString(value)); - layout->addWidget(m_box); - - m_value.ConfigOption::add_listener(*this); -} -void TextEditWidget::update_value(){ - std::string new_value = (std::string)m_value; - std::string text = m_box->toPlainText().toStdString(); - if (new_value == text){ - return; - } - m_box->setText(QString::fromStdString(m_value)); -} -void TextEditWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - - - - -} +/* Text Edit Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "TextEditWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* TextEditOption::make_QtWidget(QWidget& parent){ + return new TextEditWidget(parent, *this); +} + + + +class TextEditWidget::Box : public QTextEdit{ +public: + Box(TextEditWidget& parent) + : QTextEdit(&parent) + , m_parent(parent) + { + this->setAcceptRichText(false); + this->setFocusPolicy(Qt::StrongFocus); + this->setPlaceholderText(QString::fromStdString(parent.m_value.placeholder_text())); + +// QPalette palette = this->palette(); +// palette.setColor(QPalette::Text, "blue"); +// palette.setColor(QPalette::PlaceholderText, "red"); +// this->setPalette(palette); + +// QColor default_color = this->textColor(); + + if (parent.m_value.signal_all_text_changes()){ + connect( + this, &QTextEdit::textChanged, + [this]{ + std::string new_value = (std::string)m_parent.m_value; + std::string text = this->toPlainText().toStdString(); + if (new_value == text){ + return; + } +// cout << new_value << " : " << text << endl; + m_parent.m_value.set(std::move(text)); + } + ); + } + +// this->hide(); + } + + virtual void focusInEvent(QFocusEvent* event) override{ + QTextEdit::focusInEvent(event); + m_parent.m_value.report_focus_in(); + } + virtual void focusOutEvent(QFocusEvent* event) override{ + QTextEdit::focusOutEvent(event); +// static size_t c = 0; +// cout << "focusOutEvent: " << c++ << endl; + m_parent.m_value.set(this->toPlainText().toStdString()); + } + +private: + TextEditWidget& m_parent; +}; + + + + + +TextEditWidget::~TextEditWidget(){ + m_value.ConfigOption::remove_listener(*this); +} +TextEditWidget::TextEditWidget(QWidget& parent, TextEditOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* label = new QLabel(QString::fromStdString(value.label()), this); + label->setWordWrap(true); + layout->addWidget(label); + m_box = new Box(*this); + m_box->setText(QString::fromStdString(value)); + layout->addWidget(m_box); + + m_value.ConfigOption::add_listener(*this); +} +void TextEditWidget::update_value(){ + std::string new_value = (std::string)m_value; + std::string text = m_box->toPlainText().toStdString(); + if (new_value == text){ + return; + } + m_box->setText(QString::fromStdString(m_value)); +} +void TextEditWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + + + + +} diff --git a/Common/Qt/Options/TextEditWidget.h b/Common/Qt/Options/TextEditWidget.h index bb0ac6a528..5aab3f5f2b 100644 --- a/Common/Qt/Options/TextEditWidget.h +++ b/Common/Qt/Options/TextEditWidget.h @@ -1,38 +1,38 @@ -/* Text Edit Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TextEditWidget_H -#define PokemonAutomation_Options_TextEditWidget_H - -#include -#include "Common/Cpp/Options/TextEditOption.h" -#include "ConfigWidget.h" - -class QTextEdit; - -namespace PokemonAutomation{ - - - -class TextEditWidget : public QWidget, public ConfigWidget{ -public: - ~TextEditWidget(); - TextEditWidget(QWidget& parent, TextEditOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - class Box; - - TextEditOption& m_value; - QTextEdit* m_box; -}; - - - -} -#endif +/* Text Edit Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TextEditWidget_H +#define PokemonAutomation_Options_TextEditWidget_H + +#include +#include "Common/Cpp/Options/TextEditOption.h" +#include "ConfigWidget.h" + +class QTextEdit; + +namespace PokemonAutomation{ + + + +class TextEditWidget : public QWidget, public ConfigWidget{ +public: + ~TextEditWidget(); + TextEditWidget(QWidget& parent, TextEditOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + class Box; + + TextEditOption& m_value; + QTextEdit* m_box; +}; + + + +} +#endif diff --git a/Common/Qt/Options/TimeDurationWidget.cpp b/Common/Qt/Options/TimeDurationWidget.cpp index 2fb0f7db52..8ff3ca8556 100644 --- a/Common/Qt/Options/TimeDurationWidget.cpp +++ b/Common/Qt/Options/TimeDurationWidget.cpp @@ -1,165 +1,165 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "TimeDurationWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -TimeDurationCellWidget::~TimeDurationCellWidget(){ - m_value.remove_listener(*this); -} -template -TimeDurationCellWidget::TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value) - : QLineEdit(QString::fromStdString(value.current_text()), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - this->setToolTip(QString::fromStdString( - "Time duration in " + value.units() + - "

" - "For controller timings, this will be rounded " - "up to the tick size of the controller." - "

" - "The tick size for wired controllers is usually 8ms and are very precise." - "

" - "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." - )); - - connect( - this, &QLineEdit::textChanged, - this, [this](const QString& text){ - std::string error = m_value.set(text.toStdString()); - } - ); - - value.add_listener(*this); -} -template -void TimeDurationCellWidget::update_value(){ - this->setText(QString::fromStdString(m_value.current_text())); -} -template -void TimeDurationCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - this->update_value(); - }, Qt::QueuedConnection); -} - - - - - -template -TimeDurationOptionWidget::~TimeDurationOptionWidget(){ - m_value.remove_listener(*this); -} -template -TimeDurationOptionWidget::TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - QVBoxLayout* rows = new QVBoxLayout(); - layout->addLayout(rows, 1); - - QHBoxLayout* row0 = new QHBoxLayout(); - rows->addLayout(row0); - QHBoxLayout* row1 = new QHBoxLayout(); - rows->addLayout(row1); - - m_box = new QLineEdit(QString::fromStdString(m_value.current_text()), this); - row0->addWidget(m_box); - if (value.show_summary()){ - row0->addWidget(new QLabel(QString::fromStdString(value.units()), this)); - } - m_box->setToolTip(QString::fromStdString( - "Time duration in " + value.units() + - "

" - "For controller timings, this will be rounded " - "up to the tick size of the controller." - "

" - "The tick size for wired controllers is usually 8ms and are very precise." - "

" - "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." - )); - - QLabel* description = nullptr; - if (value.show_summary()){ - description = new QLabel(QString::fromStdString(m_value.time_string()), this); - description->setAlignment(Qt::AlignHCenter); - row1->addWidget(description); - } - - connect( - m_box, &QLineEdit::editingFinished, - this, [this, description](){ - std::string error = m_value.set(m_box->text().toStdString()); - if (description == nullptr){ - return; - } - if (error.empty()){ - description->setText(QString::fromStdString(m_value.time_string())); - }else{ - description->setText(QString::fromStdString("" + error + "")); - } - } - ); - connect( - m_box, &QLineEdit::textChanged, - this, [this, description](){ - if (description == nullptr){ - return; - } - std::string text = m_value.time_string(m_box->text().toStdString()); - description->setText(QString::fromStdString(text)); - } - ); - - value.add_listener(*this); -} -template -void TimeDurationOptionWidget::update_value(){ - m_box->setText(QString::fromStdString(m_value.current_text())); -} -template -void TimeDurationOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - this->update_value(); - }, Qt::QueuedConnection); -} - - - - - -template class TimeDurationCellWidget; -template class TimeDurationCellWidget; -template class TimeDurationOptionWidget; -template class TimeDurationOptionWidget; - - - - -} +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "TimeDurationWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +template +TimeDurationCellWidget::~TimeDurationCellWidget(){ + m_value.remove_listener(*this); +} +template +TimeDurationCellWidget::TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value) + : QLineEdit(QString::fromStdString(value.current_text()), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + this->setToolTip(QString::fromStdString( + "Time duration in " + value.units() + + "

" + "For controller timings, this will be rounded " + "up to the tick size of the controller." + "

" + "The tick size for wired controllers is usually 8ms and are very precise." + "

" + "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." + )); + + connect( + this, &QLineEdit::textChanged, + this, [this](const QString& text){ + std::string error = m_value.set(text.toStdString()); + } + ); + + value.add_listener(*this); +} +template +void TimeDurationCellWidget::update_value(){ + this->setText(QString::fromStdString(m_value.current_text())); +} +template +void TimeDurationCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + this->update_value(); + }, Qt::QueuedConnection); +} + + + + + +template +TimeDurationOptionWidget::~TimeDurationOptionWidget(){ + m_value.remove_listener(*this); +} +template +TimeDurationOptionWidget::TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + QVBoxLayout* rows = new QVBoxLayout(); + layout->addLayout(rows, 1); + + QHBoxLayout* row0 = new QHBoxLayout(); + rows->addLayout(row0); + QHBoxLayout* row1 = new QHBoxLayout(); + rows->addLayout(row1); + + m_box = new QLineEdit(QString::fromStdString(m_value.current_text()), this); + row0->addWidget(m_box); + if (value.show_summary()){ + row0->addWidget(new QLabel(QString::fromStdString(value.units()), this)); + } + m_box->setToolTip(QString::fromStdString( + "Time duration in " + value.units() + + "

" + "For controller timings, this will be rounded " + "up to the tick size of the controller." + "

" + "The tick size for wired controllers is usually 8ms and are very precise." + "

" + "Wireless controllers have larger tick sizes and are imprecise due to wireless communication latency." + )); + + QLabel* description = nullptr; + if (value.show_summary()){ + description = new QLabel(QString::fromStdString(m_value.time_string()), this); + description->setAlignment(Qt::AlignHCenter); + row1->addWidget(description); + } + + connect( + m_box, &QLineEdit::editingFinished, + this, [this, description](){ + std::string error = m_value.set(m_box->text().toStdString()); + if (description == nullptr){ + return; + } + if (error.empty()){ + description->setText(QString::fromStdString(m_value.time_string())); + }else{ + description->setText(QString::fromStdString("" + error + "")); + } + } + ); + connect( + m_box, &QLineEdit::textChanged, + this, [this, description](){ + if (description == nullptr){ + return; + } + std::string text = m_value.time_string(m_box->text().toStdString()); + description->setText(QString::fromStdString(text)); + } + ); + + value.add_listener(*this); +} +template +void TimeDurationOptionWidget::update_value(){ + m_box->setText(QString::fromStdString(m_value.current_text())); +} +template +void TimeDurationOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + this->update_value(); + }, Qt::QueuedConnection); +} + + + + + +template class TimeDurationCellWidget; +template class TimeDurationCellWidget; +template class TimeDurationOptionWidget; +template class TimeDurationOptionWidget; + + + + +} diff --git a/Common/Qt/Options/TimeDurationWidget.h b/Common/Qt/Options/TimeDurationWidget.h index c4f7d9290c..d41c7ae43c 100644 --- a/Common/Qt/Options/TimeDurationWidget.h +++ b/Common/Qt/Options/TimeDurationWidget.h @@ -1,49 +1,49 @@ -/* Time Duration Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TimeDurationWidget_H -#define PokemonAutomation_Options_TimeDurationWidget_H - -#include -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -template -class TimeDurationCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~TimeDurationCellWidget(); - TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - TimeDurationCell& m_value; -}; - - - -template -class TimeDurationOptionWidget : public QWidget, public ConfigWidget{ -public: - ~TimeDurationOptionWidget(); - TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - TimeDurationOption& m_value; - QLineEdit* m_box; -}; - - -} -#endif +/* Time Duration Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TimeDurationWidget_H +#define PokemonAutomation_Options_TimeDurationWidget_H + +#include +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +template +class TimeDurationCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~TimeDurationCellWidget(); + TimeDurationCellWidget(QWidget& parent, TimeDurationCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + TimeDurationCell& m_value; +}; + + + +template +class TimeDurationOptionWidget : public QWidget, public ConfigWidget{ +public: + ~TimeDurationOptionWidget(); + TimeDurationOptionWidget(QWidget& parent, TimeDurationOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + TimeDurationOption& m_value; + QLineEdit* m_box; +}; + + +} +#endif diff --git a/Common/Qt/Options/TimeExpressionWidget.cpp b/Common/Qt/Options/TimeExpressionWidget.cpp index 72e83056be..07c37221f4 100644 --- a/Common/Qt/Options/TimeExpressionWidget.cpp +++ b/Common/Qt/Options/TimeExpressionWidget.cpp @@ -1,128 +1,128 @@ -/* Time Expression Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "TimeExpressionWidget.h" - -namespace PokemonAutomation{ - - - -template -TimeExpressionCellWidget::~TimeExpressionCellWidget(){ - m_value.remove_listener(*this); -} -template -TimeExpressionCellWidget::TimeExpressionCellWidget(QWidget& parent, TimeExpressionCell& value) - : QLineEdit(QString::fromStdString(value.current_text()), &parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - connect( - this, &QLineEdit::textChanged, - this, [this](const QString& text){ - std::string error = m_value.set(text.toStdString()); - } - ); - - value.add_listener(*this); -} -template -void TimeExpressionCellWidget::update_value(){ - this->setText(QString::fromStdString(m_value.current_text())); -} -template -void TimeExpressionCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - this->update_value(); - }, Qt::QueuedConnection); -} - - - - - -template -TimeExpressionOptionWidget::~TimeExpressionOptionWidget(){ - m_value.remove_listener(*this); -} -template -TimeExpressionOptionWidget::TimeExpressionOptionWidget(QWidget& parent, TimeExpressionOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); - text->setWordWrap(true); - text->setTextFormat(Qt::RichText); - text->setTextInteractionFlags(Qt::TextBrowserInteraction); - text->setOpenExternalLinks(true); - layout->addWidget(text, 1); - QVBoxLayout* rows = new QVBoxLayout(); - layout->addLayout(rows, 1); - - QHBoxLayout* row0 = new QHBoxLayout(); - rows->addLayout(row0); - QHBoxLayout* row1 = new QHBoxLayout(); - rows->addLayout(row1); - - m_box = new QLineEdit(QString::fromStdString(m_value.current_text()), this); - row0->addWidget(m_box); - row0->addWidget(new QLabel("ticks", this)); - - QLabel* seconds = new QLabel(QString::fromStdString(m_value.time_string()), this); - seconds->setAlignment(Qt::AlignHCenter); - row1->addWidget(seconds); - - connect( - m_box, &QLineEdit::editingFinished, - this, [this, seconds](){ - std::string error = m_value.set(m_box->text().toStdString()); - if (error.empty()){ - seconds->setText(QString::fromStdString(m_value.time_string())); - }else{ - seconds->setText(QString::fromStdString("" + error + "")); - } - } - ); - - value.add_listener(*this); -} -template -void TimeExpressionOptionWidget::update_value(){ - m_box->setText(QString::fromStdString(m_value.current_text())); -} -template -void TimeExpressionOptionWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - this->update_value(); - }, Qt::QueuedConnection); -} - - - - - -template class TimeExpressionCellWidget; -template class TimeExpressionCellWidget; -template class TimeExpressionCellWidget; -template class TimeExpressionCellWidget; -template class TimeExpressionCellWidget; - -template class TimeExpressionOptionWidget; -template class TimeExpressionOptionWidget; -template class TimeExpressionOptionWidget; -template class TimeExpressionOptionWidget; -template class TimeExpressionOptionWidget; - - - - -} +/* Time Expression Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "TimeExpressionWidget.h" + +namespace PokemonAutomation{ + + + +template +TimeExpressionCellWidget::~TimeExpressionCellWidget(){ + m_value.remove_listener(*this); +} +template +TimeExpressionCellWidget::TimeExpressionCellWidget(QWidget& parent, TimeExpressionCell& value) + : QLineEdit(QString::fromStdString(value.current_text()), &parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + connect( + this, &QLineEdit::textChanged, + this, [this](const QString& text){ + std::string error = m_value.set(text.toStdString()); + } + ); + + value.add_listener(*this); +} +template +void TimeExpressionCellWidget::update_value(){ + this->setText(QString::fromStdString(m_value.current_text())); +} +template +void TimeExpressionCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + this->update_value(); + }, Qt::QueuedConnection); +} + + + + + +template +TimeExpressionOptionWidget::~TimeExpressionOptionWidget(){ + m_value.remove_listener(*this); +} +template +TimeExpressionOptionWidget::TimeExpressionOptionWidget(QWidget& parent, TimeExpressionOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(m_value.label()), this); + text->setWordWrap(true); + text->setTextFormat(Qt::RichText); + text->setTextInteractionFlags(Qt::TextBrowserInteraction); + text->setOpenExternalLinks(true); + layout->addWidget(text, 1); + QVBoxLayout* rows = new QVBoxLayout(); + layout->addLayout(rows, 1); + + QHBoxLayout* row0 = new QHBoxLayout(); + rows->addLayout(row0); + QHBoxLayout* row1 = new QHBoxLayout(); + rows->addLayout(row1); + + m_box = new QLineEdit(QString::fromStdString(m_value.current_text()), this); + row0->addWidget(m_box); + row0->addWidget(new QLabel("ticks", this)); + + QLabel* seconds = new QLabel(QString::fromStdString(m_value.time_string()), this); + seconds->setAlignment(Qt::AlignHCenter); + row1->addWidget(seconds); + + connect( + m_box, &QLineEdit::editingFinished, + this, [this, seconds](){ + std::string error = m_value.set(m_box->text().toStdString()); + if (error.empty()){ + seconds->setText(QString::fromStdString(m_value.time_string())); + }else{ + seconds->setText(QString::fromStdString("" + error + "")); + } + } + ); + + value.add_listener(*this); +} +template +void TimeExpressionOptionWidget::update_value(){ + m_box->setText(QString::fromStdString(m_value.current_text())); +} +template +void TimeExpressionOptionWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + this->update_value(); + }, Qt::QueuedConnection); +} + + + + + +template class TimeExpressionCellWidget; +template class TimeExpressionCellWidget; +template class TimeExpressionCellWidget; +template class TimeExpressionCellWidget; +template class TimeExpressionCellWidget; + +template class TimeExpressionOptionWidget; +template class TimeExpressionOptionWidget; +template class TimeExpressionOptionWidget; +template class TimeExpressionOptionWidget; +template class TimeExpressionOptionWidget; + + + + +} diff --git a/Common/Qt/Options/TimeExpressionWidget.h b/Common/Qt/Options/TimeExpressionWidget.h index 7e185e0c8d..9b16bad3c5 100644 --- a/Common/Qt/Options/TimeExpressionWidget.h +++ b/Common/Qt/Options/TimeExpressionWidget.h @@ -1,49 +1,49 @@ -/* Time Expression Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_TimeExpressionWidget_H -#define PokemonAutomation_Options_TimeExpressionWidget_H - -#include -#include "Common/Cpp/Options/TimeExpressionOption.h" -#include "ConfigWidget.h" - -namespace PokemonAutomation{ - - - -template -class TimeExpressionCellWidget : public QLineEdit, public ConfigWidget{ -public: - ~TimeExpressionCellWidget(); - TimeExpressionCellWidget(QWidget& parent, TimeExpressionCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - TimeExpressionCell& m_value; -}; - - - -template -class TimeExpressionOptionWidget : public QWidget, public ConfigWidget{ -public: - ~TimeExpressionOptionWidget(); - TimeExpressionOptionWidget(QWidget& parent, TimeExpressionOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - TimeExpressionOption& m_value; - QLineEdit* m_box; -}; - - -} -#endif +/* Time Expression Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_TimeExpressionWidget_H +#define PokemonAutomation_Options_TimeExpressionWidget_H + +#include +#include "Common/Cpp/Options/TimeExpressionOption.h" +#include "ConfigWidget.h" + +namespace PokemonAutomation{ + + + +template +class TimeExpressionCellWidget : public QLineEdit, public ConfigWidget{ +public: + ~TimeExpressionCellWidget(); + TimeExpressionCellWidget(QWidget& parent, TimeExpressionCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + TimeExpressionCell& m_value; +}; + + + +template +class TimeExpressionOptionWidget : public QWidget, public ConfigWidget{ +public: + ~TimeExpressionOptionWidget(); + TimeExpressionOptionWidget(QWidget& parent, TimeExpressionOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + TimeExpressionOption& m_value; + QLineEdit* m_box; +}; + + +} +#endif diff --git a/Common/Qt/Redispatch.cpp b/Common/Qt/Redispatch.cpp index 7e462da5ea..5b5380c133 100644 --- a/Common/Qt/Redispatch.cpp +++ b/Common/Qt/Redispatch.cpp @@ -1,45 +1,45 @@ -/* Redispatch - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Redispatch.h" - -namespace PokemonAutomation{ - - -void dispatch_to_main_thread(std::function lambda){ - QMetaObject::invokeMethod(QCoreApplication::instance(), lambda); -} -void queue_on_main_thread(std::function lambda){ - QMetaObject::invokeMethod(QCoreApplication::instance(), lambda, Qt::QueuedConnection); -} - - -void run_on_main_thread_and_wait(std::function lambda){ - if (QCoreApplication::instance()->thread() == QThread::currentThread()){ - lambda(); - return; - } - - std::mutex lock; - std::condition_variable cv; - bool done = false; - QMetaObject::invokeMethod(QCoreApplication::instance(), [&]{ - lambda(); - std::lock_guard lg(lock); - done = true; - cv.notify_all(); - }); - std::unique_lock lg(lock); - cv.wait(lg, [&]{ return done; }); -} - - - -} +/* Redispatch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Redispatch.h" + +namespace PokemonAutomation{ + + +void dispatch_to_main_thread(std::function lambda){ + QMetaObject::invokeMethod(QCoreApplication::instance(), lambda); +} +void queue_on_main_thread(std::function lambda){ + QMetaObject::invokeMethod(QCoreApplication::instance(), lambda, Qt::QueuedConnection); +} + + +void run_on_main_thread_and_wait(std::function lambda){ + if (QCoreApplication::instance()->thread() == QThread::currentThread()){ + lambda(); + return; + } + + std::mutex lock; + std::condition_variable cv; + bool done = false; + QMetaObject::invokeMethod(QCoreApplication::instance(), [&]{ + lambda(); + std::lock_guard lg(lock); + done = true; + cv.notify_all(); + }); + std::unique_lock lg(lock); + cv.wait(lg, [&]{ return done; }); +} + + + +} diff --git a/Common/Qt/Redispatch.h b/Common/Qt/Redispatch.h index c9cb8ae73d..a5638921cd 100644 --- a/Common/Qt/Redispatch.h +++ b/Common/Qt/Redispatch.h @@ -1,25 +1,25 @@ -/* Redispatch - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Qt_Redispatch_H -#define PokemonAutomation_Qt_Redispatch_H - -#include - -namespace PokemonAutomation{ - - -// Be careful with these due to re-entrancy and object lifetime. -void dispatch_to_main_thread(std::function lambda); -void queue_on_main_thread(std::function lambda); - - -void run_on_main_thread_and_wait(std::function lambda); - - - -} -#endif +/* Redispatch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Qt_Redispatch_H +#define PokemonAutomation_Qt_Redispatch_H + +#include + +namespace PokemonAutomation{ + + +// Be careful with these due to re-entrancy and object lifetime. +void dispatch_to_main_thread(std::function lambda); +void queue_on_main_thread(std::function lambda); + + +void run_on_main_thread_and_wait(std::function lambda); + + + +} +#endif diff --git a/Common/Qt/StringToolsQt.cpp b/Common/Qt/StringToolsQt.cpp index e85a06a778..58400e61bb 100644 --- a/Common/Qt/StringToolsQt.cpp +++ b/Common/Qt/StringToolsQt.cpp @@ -1,59 +1,59 @@ -/* String Tools (Qt) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "StringToolsQt.h" - -namespace PokemonAutomation{ - - - -std::u32string to_utf32(const std::string& str){ - return QString::fromStdString(str).toStdU32String(); -} -std::string to_utf8(const std::u32string& str){ - return QString::fromStdU32String(str).toStdString(); -} - - -std::string to_lower(const std::string& str){ - return QString::fromStdString(str).toLower().toStdString(); -} -void to_lower(std::u32string& str){ - for (char32_t& ch : str){ - ch = QChar::toLower(ch); - } -} - -bool is_alphanumberic(char32_t ch){ - return QChar::isLetterOrNumber(ch); -} - -bool has_extension(const std::string& str, const std::string& extension){ - if (extension.empty()){ - return true; - } - if (str.empty()){ - return false; - } - - size_t c = str.size(); - while (c > 0){ - char ch = str[c - 1]; - if (ch == '.'){ - break; - } - c--; - } - std::string end = str.substr(c); - return to_lower(end) == to_lower(extension); -} - - - - -} +/* String Tools (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "StringToolsQt.h" + +namespace PokemonAutomation{ + + + +std::u32string to_utf32(const std::string& str){ + return QString::fromStdString(str).toStdU32String(); +} +std::string to_utf8(const std::u32string& str){ + return QString::fromStdU32String(str).toStdString(); +} + + +std::string to_lower(const std::string& str){ + return QString::fromStdString(str).toLower().toStdString(); +} +void to_lower(std::u32string& str){ + for (char32_t& ch : str){ + ch = QChar::toLower(ch); + } +} + +bool is_alphanumberic(char32_t ch){ + return QChar::isLetterOrNumber(ch); +} + +bool has_extension(const std::string& str, const std::string& extension){ + if (extension.empty()){ + return true; + } + if (str.empty()){ + return false; + } + + size_t c = str.size(); + while (c > 0){ + char ch = str[c - 1]; + if (ch == '.'){ + break; + } + c--; + } + std::string end = str.substr(c); + return to_lower(end) == to_lower(extension); +} + + + + +} diff --git a/Common/Qt/StringToolsQt.h b/Common/Qt/StringToolsQt.h index 8e3bc1d62e..4165fc030d 100644 --- a/Common/Qt/StringToolsQt.h +++ b/Common/Qt/StringToolsQt.h @@ -1,27 +1,27 @@ -/* String Tools (Qt) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StringToolsQt_H -#define PokemonAutomation_StringToolsQt_H - -#include - -namespace PokemonAutomation{ - - -std::u32string to_utf32(const std::string& str); -std::string to_utf8(const std::u32string& str); - -std::string to_lower(const std::string& str); -void to_lower(std::u32string& str); - -bool is_alphanumberic(char32_t ch); - -bool has_extension(const std::string& str, const std::string& extension); - - -} -#endif +/* String Tools (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StringToolsQt_H +#define PokemonAutomation_StringToolsQt_H + +#include + +namespace PokemonAutomation{ + + +std::u32string to_utf32(const std::string& str); +std::string to_utf8(const std::u32string& str); + +std::string to_lower(const std::string& str); +void to_lower(std::u32string& str); + +bool is_alphanumberic(char32_t ch); + +bool has_extension(const std::string& str, const std::string& extension); + + +} +#endif diff --git a/Common/Qt/TimeQt.cpp b/Common/Qt/TimeQt.cpp index 6973f78799..0b3ff7a5aa 100644 --- a/Common/Qt/TimeQt.cpp +++ b/Common/Qt/TimeQt.cpp @@ -1,179 +1,179 @@ -/* Time Tools (Qt) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "TimeQt.h" - -namespace PokemonAutomation{ - - - -std::string to_utc_time_str(WallClock time){ -#if 0 - time_t tt = std::chrono::system_clock::to_time_t(time); - static SpinLock lock; - WriteSpinLock lg(lock); - std::tm* utc = gmtime(&tt); - std::string str; - str += std::to_string(utc->tm_year + 1900); - str += "-" + tostr_padded(2, utc->tm_mon + 1); - str += "-" + tostr_padded(2, utc->tm_mday); - str += " " + tostr_padded(2, utc->tm_hour); - str += ":" + tostr_padded(2, utc->tm_min); - str += ":" + tostr_padded(2, utc->tm_sec); - return str; -#endif -#if 0 - QDateTime now = QDateTime::fromStdTimePoint(time); - - QDate qdate = now.date(); - QTime qtime = now.time(); - std::string str; - str += std::to_string(qdate.year()); - str += "-" + tostr_padded(2, qdate.month()); - str += "-" + tostr_padded(2, qdate.day()); - str += " " + tostr_padded(2, qtime.hour()); - str += ":" + tostr_padded(2, qtime.minute()); - str += ":" + tostr_padded(2, qtime.second()); - return str; - -#endif - - int64_t secs_since_epoch = std::chrono::duration_cast(time.time_since_epoch()).count(); - QDateTime qdatetime = QDateTime::fromSecsSinceEpoch(secs_since_epoch, QTimeZone::utc()); - QDate qdate = qdatetime.date(); - QTime qtime = qdatetime.time(); - std::string str; - str += std::to_string(qdate.year()); - str += "-" + tostr_padded(2, qdate.month()); - str += "-" + tostr_padded(2, qdate.day()); - str += " " + tostr_padded(2, qtime.hour()); - str += ":" + tostr_padded(2, qtime.minute()); - str += ":" + tostr_padded(2, qtime.second()); - return str; -} -WallClock parse_utc_time_str(const std::string& str){ - int year = std::atoi(&str[0]); - if (year <= 1900){ - throw ParseException("Invalid date format: Year must be greater than 1900."); - } -// cout << year << endl; - - auto index = str.find("-"); - if (index == std::string::npos){ - throw ParseException("Invalid date format: Expected hyphen."); - } - int month = std::atoi(&str[++index]); -// cout << month << endl; - if (month < 1 || month > 12){ - throw ParseException("Invalid date format: Month out of range."); - } - - index = str.find("-", index); - if (index == std::string::npos){ - throw ParseException("Invalid date format: Expected hyphen."); - } - int day = std::atoi(&str[++index]); - if (day < 1 || day > 31){ - throw ParseException("Invalid date format: Day out of range."); - } -// cout << day << endl; - - index = str.find(" ", index); - if (index == std::string::npos){ - throw ParseException("Invalid date format: Expected space."); - } - int hour = std::atoi(&str[++index]); - if (hour < 0 || hour > 23){ - throw ParseException("Invalid date format: Hour out of range."); - } -// cout << hour << endl; - - index = str.find(":", index); - if (index == std::string::npos){ - throw ParseException("Invalid date format: Expected colon."); - } - int minutes = std::atoi(&str[++index]); - if (minutes < 0 || minutes > 60){ - throw ParseException("Invalid date format: Minutes out of range."); - } -// cout << minutes << endl; - - index = str.find(":", index); - if (index == std::string::npos){ - throw ParseException("Invalid date format: Expected colon."); - } - int seconds = std::atoi(&str[++index]); - if (seconds < 0 || seconds > 61){ - throw ParseException("Invalid date format: Seconds out of range."); - } -// cout << seconds << endl; - -#if 0 - std::tm tm{}; - tm.tm_year = year - 1900; - tm.tm_mon = month - 1; - tm.tm_mday = day; - tm.tm_hour = hour; - tm.tm_min = minutes; - tm.tm_sec = seconds; - std::time_t t = std::mktime(&tm); -// std::tm* tm1 = std::localtime(&t); - if (t == -1){ - throw ParseException("Invalid date."); - } -#endif - -// std::chrono::utc_clock::fr - -// WallClock utc = std::chrono::system_clock::from_time_t(t); - - QDate qdate(year, month, day); - if (!qdate.isValid()){ - throw ParseException("Invalid date."); - } - QTime qtime(hour, minutes, seconds); - if (!qtime.isValid()){ - throw ParseException("Invalid time."); - } - - QDateTime qdatetime(qdate, qtime, QTimeZone::utc()); - int64_t secs_since_epoch = qdatetime.toSecsSinceEpoch(); - - return WallClock{} + std::chrono::seconds(secs_since_epoch); -} - - - -int64_t to_seconds_since_epoch(const DateTime& date){ - QDate qdate(date.year, date.month, date.day); - QTime qtime(date.hour, date.minute, date.second); - QDateTime qdatetime(qdate, qtime, QTimeZone::utc()); - int64_t secs_since_epoch = qdatetime.toSecsSinceEpoch(); - return secs_since_epoch; -} -DateTime from_seconds_since_epoch(int64_t seconds_since_epoch){ - QDateTime qdatetime = QDateTime::fromSecsSinceEpoch(seconds_since_epoch, QTimeZone::utc()); - QDate qdate = qdatetime.date(); - QTime qtime = qdatetime.time(); - return DateTime{ - (int16_t)qdate.year(), - (int8_t)qdate.month(), - (int8_t)qdate.day(), - (int8_t)qtime.hour(), - (int8_t)qtime.minute(), - (int8_t)qtime.second(), - }; -} - - - - - -} +/* Time Tools (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "TimeQt.h" + +namespace PokemonAutomation{ + + + +std::string to_utc_time_str(WallClock time){ +#if 0 + time_t tt = std::chrono::system_clock::to_time_t(time); + static SpinLock lock; + WriteSpinLock lg(lock); + std::tm* utc = gmtime(&tt); + std::string str; + str += std::to_string(utc->tm_year + 1900); + str += "-" + tostr_padded(2, utc->tm_mon + 1); + str += "-" + tostr_padded(2, utc->tm_mday); + str += " " + tostr_padded(2, utc->tm_hour); + str += ":" + tostr_padded(2, utc->tm_min); + str += ":" + tostr_padded(2, utc->tm_sec); + return str; +#endif +#if 0 + QDateTime now = QDateTime::fromStdTimePoint(time); + + QDate qdate = now.date(); + QTime qtime = now.time(); + std::string str; + str += std::to_string(qdate.year()); + str += "-" + tostr_padded(2, qdate.month()); + str += "-" + tostr_padded(2, qdate.day()); + str += " " + tostr_padded(2, qtime.hour()); + str += ":" + tostr_padded(2, qtime.minute()); + str += ":" + tostr_padded(2, qtime.second()); + return str; + +#endif + + int64_t secs_since_epoch = std::chrono::duration_cast(time.time_since_epoch()).count(); + QDateTime qdatetime = QDateTime::fromSecsSinceEpoch(secs_since_epoch, QTimeZone::utc()); + QDate qdate = qdatetime.date(); + QTime qtime = qdatetime.time(); + std::string str; + str += std::to_string(qdate.year()); + str += "-" + tostr_padded(2, qdate.month()); + str += "-" + tostr_padded(2, qdate.day()); + str += " " + tostr_padded(2, qtime.hour()); + str += ":" + tostr_padded(2, qtime.minute()); + str += ":" + tostr_padded(2, qtime.second()); + return str; +} +WallClock parse_utc_time_str(const std::string& str){ + int year = std::atoi(&str[0]); + if (year <= 1900){ + throw ParseException("Invalid date format: Year must be greater than 1900."); + } +// cout << year << endl; + + auto index = str.find("-"); + if (index == std::string::npos){ + throw ParseException("Invalid date format: Expected hyphen."); + } + int month = std::atoi(&str[++index]); +// cout << month << endl; + if (month < 1 || month > 12){ + throw ParseException("Invalid date format: Month out of range."); + } + + index = str.find("-", index); + if (index == std::string::npos){ + throw ParseException("Invalid date format: Expected hyphen."); + } + int day = std::atoi(&str[++index]); + if (day < 1 || day > 31){ + throw ParseException("Invalid date format: Day out of range."); + } +// cout << day << endl; + + index = str.find(" ", index); + if (index == std::string::npos){ + throw ParseException("Invalid date format: Expected space."); + } + int hour = std::atoi(&str[++index]); + if (hour < 0 || hour > 23){ + throw ParseException("Invalid date format: Hour out of range."); + } +// cout << hour << endl; + + index = str.find(":", index); + if (index == std::string::npos){ + throw ParseException("Invalid date format: Expected colon."); + } + int minutes = std::atoi(&str[++index]); + if (minutes < 0 || minutes > 60){ + throw ParseException("Invalid date format: Minutes out of range."); + } +// cout << minutes << endl; + + index = str.find(":", index); + if (index == std::string::npos){ + throw ParseException("Invalid date format: Expected colon."); + } + int seconds = std::atoi(&str[++index]); + if (seconds < 0 || seconds > 61){ + throw ParseException("Invalid date format: Seconds out of range."); + } +// cout << seconds << endl; + +#if 0 + std::tm tm{}; + tm.tm_year = year - 1900; + tm.tm_mon = month - 1; + tm.tm_mday = day; + tm.tm_hour = hour; + tm.tm_min = minutes; + tm.tm_sec = seconds; + std::time_t t = std::mktime(&tm); +// std::tm* tm1 = std::localtime(&t); + if (t == -1){ + throw ParseException("Invalid date."); + } +#endif + +// std::chrono::utc_clock::fr + +// WallClock utc = std::chrono::system_clock::from_time_t(t); + + QDate qdate(year, month, day); + if (!qdate.isValid()){ + throw ParseException("Invalid date."); + } + QTime qtime(hour, minutes, seconds); + if (!qtime.isValid()){ + throw ParseException("Invalid time."); + } + + QDateTime qdatetime(qdate, qtime, QTimeZone::utc()); + int64_t secs_since_epoch = qdatetime.toSecsSinceEpoch(); + + return WallClock{} + std::chrono::seconds(secs_since_epoch); +} + + + +int64_t to_seconds_since_epoch(const DateTime& date){ + QDate qdate(date.year, date.month, date.day); + QTime qtime(date.hour, date.minute, date.second); + QDateTime qdatetime(qdate, qtime, QTimeZone::utc()); + int64_t secs_since_epoch = qdatetime.toSecsSinceEpoch(); + return secs_since_epoch; +} +DateTime from_seconds_since_epoch(int64_t seconds_since_epoch){ + QDateTime qdatetime = QDateTime::fromSecsSinceEpoch(seconds_since_epoch, QTimeZone::utc()); + QDate qdate = qdatetime.date(); + QTime qtime = qdatetime.time(); + return DateTime{ + (int16_t)qdate.year(), + (int8_t)qdate.month(), + (int8_t)qdate.day(), + (int8_t)qtime.hour(), + (int8_t)qtime.minute(), + (int8_t)qtime.second(), + }; +} + + + + + +} diff --git a/Common/Qt/TimeQt.h b/Common/Qt/TimeQt.h index 13f81e108b..3d59f3806e 100644 --- a/Common/Qt/TimeQt.h +++ b/Common/Qt/TimeQt.h @@ -1,25 +1,25 @@ -/* Time Tools (Qt) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_TimeQt_H -#define PokemonAutomation_TimeQt_H - -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/DateTime.h" - -namespace PokemonAutomation{ - - -std::string to_utc_time_str(WallClock time); -WallClock parse_utc_time_str(const std::string& str); - -int64_t to_seconds_since_epoch(const DateTime& date); -DateTime from_seconds_since_epoch(int64_t seconds_since_epoch); - - -} -#endif +/* Time Tools (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_TimeQt_H +#define PokemonAutomation_TimeQt_H + +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/DateTime.h" + +namespace PokemonAutomation{ + + +std::string to_utc_time_str(WallClock time); +WallClock parse_utc_time_str(const std::string& str); + +int64_t to_seconds_since_epoch(const DateTime& date); +DateTime from_seconds_since_epoch(int64_t seconds_since_epoch); + + +} +#endif diff --git a/Common/Qt/WidgetStackFixedAspectRatio.cpp b/Common/Qt/WidgetStackFixedAspectRatio.cpp index 70fc2c693e..f331607859 100644 --- a/Common/Qt/WidgetStackFixedAspectRatio.cpp +++ b/Common/Qt/WidgetStackFixedAspectRatio.cpp @@ -1,162 +1,162 @@ -/* Widget Stack Fixed Aspect Ratio - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "WidgetStackFixedAspectRatio.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -WidgetStackFixedAspectRatio::WidgetStackFixedAspectRatio( - QWidget& parent, - SizePolicy size_policy, - double aspect_ratio -) - : QWidget(&parent) - , m_size_policy(size_policy) - , m_aspect_ratio(sanitize_aspect_ratio(aspect_ratio)) -{ - m_detached_internal = new QWidget(this); - QVBoxLayout* layout = new QVBoxLayout(m_detached_internal); - layout->setContentsMargins(0, 0, 0, 0); - layout->setAlignment(Qt::AlignCenter); - m_stack_holder = new QWidget(m_detached_internal); - layout->addWidget(m_stack_holder); -// this->setFixedHeight(495); -} - -void WidgetStackFixedAspectRatio::add_widget(QWidget& widget){ - widget.setParent(m_stack_holder); - m_widgets.insert(&widget); - widget.show(); -} -void WidgetStackFixedAspectRatio::remove_widget(QWidget* widget){ - m_widgets.erase(widget); - delete widget; -} -double WidgetStackFixedAspectRatio::sanitize_aspect_ratio(double aspect_ratio) const{ - if (aspect_ratio == 0 || std::isnan(aspect_ratio)){ - aspect_ratio = 16/9.; - } -// cout << "aspect_ratio = " << aspect_ratio << endl; - aspect_ratio = std::min(aspect_ratio, 10.); - aspect_ratio = std::max(aspect_ratio, 0.1); - return aspect_ratio; -} -void WidgetStackFixedAspectRatio::set_size_policy(SizePolicy size_policy){ - if (m_size_policy != size_policy){ - clear_fixed_dimensions(); - } - m_size_policy = size_policy; - m_debouncer.clear(); - update_size(this->size()); -} -void WidgetStackFixedAspectRatio::set_aspect_ratio(double aspect_ratio){ -// cout << "WidgetStackFixedAspectRatio::set_aspect_ratio(): " << aspect_ratio << endl; - m_aspect_ratio = sanitize_aspect_ratio(aspect_ratio); - m_debouncer.clear(); - update_size(this->size()); -} -void WidgetStackFixedAspectRatio::set_all(SizePolicy size_policy, double aspect_ratio){ - if (m_size_policy != size_policy){ - clear_fixed_dimensions(); - } - m_size_policy = size_policy; - m_aspect_ratio = sanitize_aspect_ratio(aspect_ratio); - m_debouncer.clear(); - update_size(this->size()); -} - -void WidgetStackFixedAspectRatio::clear_fixed_dimensions(){ - this->setMinimumSize(QSize(0, 0)); - this->setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); -} -void WidgetStackFixedAspectRatio::resize_to_box(QSize enclosing_box){ -// cout << "resize_to_box()" << endl; - int width, height; - - double box_ratio = (double)enclosing_box.width() / enclosing_box.height(); - if (m_aspect_ratio < box_ratio){ - height = enclosing_box.height(); - width = (int)(height * m_aspect_ratio); - }else{ - width = enclosing_box.width(); - height = (int)(width / m_aspect_ratio); - } - - QSize size(width, height); - - m_detached_internal->setFixedSize(enclosing_box); - m_stack_holder->setFixedSize(size); - for (QWidget* widget : m_widgets){ - widget->setFixedSize(size); - } -} -void WidgetStackFixedAspectRatio::resize_to_width(int width){ -// cout << "resize_to_width()" << endl; -#if 0 - double aspect_ratio = (double)enclosing_box.width() / enclosing_box.height(); - cout << "resize_to_width - aspect_ratio = " << aspect_ratio << endl; - cout << "resize_to_width - min_aspect_ratio = " << m_min_aspect_ratio << endl; - if (aspect_ratio < m_min_aspect_ratio){ - resize_to_box(enclosing_box); - return; - } -#endif - - int previous_width = m_stack_holder->width(); -// cout << "WidgetStackFixedAspectRatio::resize_to_width(): " << width << " <- " << previous_width << endl; - - if (width > previous_width && width < previous_width + 50 && !m_debouncer.check(width)){ -// cout << "Supressing potential infinite resizing loop." << endl; - return; - } - - - int height = (int)(width / m_aspect_ratio); -// cout << "Resizing: " << width << " x " << height << " from: " << previous_width << " x " << m_stack_holder->height() << endl; - - if (width == previous_width && height == m_stack_holder->height() && height != this->height()){ -// cout << "Same size" << endl; - return; - } - - QSize size(width, height); - this->setFixedHeight(height); - - m_detached_internal->setFixedSize(size); - m_stack_holder->setFixedSize(size); - for (QWidget* widget : m_widgets){ - widget->setFixedSize(size); - } -} -void WidgetStackFixedAspectRatio::update_size(QSize size){ -// cout << "size = " << size.width() << ", " << size.height() << endl; - switch (m_size_policy){ - case EXPAND_TO_BOX: - resize_to_box(size); - return; - case ADJUST_HEIGHT_TO_WIDTH: - resize_to_width(size.width()); - return; - } -} -void WidgetStackFixedAspectRatio::resizeEvent(QResizeEvent* event){ -// cout << "WidgetStackFixedAspectRatio::resizeEvent(): " << this->width() << " x " << this->height() << endl; -// cout << "WidgetStackFixedAspectRatio::resizeEvent(): " << event->size().width() << " x " << event->size().height() << endl; - update_size(event->size()); -} - - - -} +/* Widget Stack Fixed Aspect Ratio + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "WidgetStackFixedAspectRatio.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +WidgetStackFixedAspectRatio::WidgetStackFixedAspectRatio( + QWidget& parent, + SizePolicy size_policy, + double aspect_ratio +) + : QWidget(&parent) + , m_size_policy(size_policy) + , m_aspect_ratio(sanitize_aspect_ratio(aspect_ratio)) +{ + m_detached_internal = new QWidget(this); + QVBoxLayout* layout = new QVBoxLayout(m_detached_internal); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(Qt::AlignCenter); + m_stack_holder = new QWidget(m_detached_internal); + layout->addWidget(m_stack_holder); +// this->setFixedHeight(495); +} + +void WidgetStackFixedAspectRatio::add_widget(QWidget& widget){ + widget.setParent(m_stack_holder); + m_widgets.insert(&widget); + widget.show(); +} +void WidgetStackFixedAspectRatio::remove_widget(QWidget* widget){ + m_widgets.erase(widget); + delete widget; +} +double WidgetStackFixedAspectRatio::sanitize_aspect_ratio(double aspect_ratio) const{ + if (aspect_ratio == 0 || std::isnan(aspect_ratio)){ + aspect_ratio = 16/9.; + } +// cout << "aspect_ratio = " << aspect_ratio << endl; + aspect_ratio = std::min(aspect_ratio, 10.); + aspect_ratio = std::max(aspect_ratio, 0.1); + return aspect_ratio; +} +void WidgetStackFixedAspectRatio::set_size_policy(SizePolicy size_policy){ + if (m_size_policy != size_policy){ + clear_fixed_dimensions(); + } + m_size_policy = size_policy; + m_debouncer.clear(); + update_size(this->size()); +} +void WidgetStackFixedAspectRatio::set_aspect_ratio(double aspect_ratio){ +// cout << "WidgetStackFixedAspectRatio::set_aspect_ratio(): " << aspect_ratio << endl; + m_aspect_ratio = sanitize_aspect_ratio(aspect_ratio); + m_debouncer.clear(); + update_size(this->size()); +} +void WidgetStackFixedAspectRatio::set_all(SizePolicy size_policy, double aspect_ratio){ + if (m_size_policy != size_policy){ + clear_fixed_dimensions(); + } + m_size_policy = size_policy; + m_aspect_ratio = sanitize_aspect_ratio(aspect_ratio); + m_debouncer.clear(); + update_size(this->size()); +} + +void WidgetStackFixedAspectRatio::clear_fixed_dimensions(){ + this->setMinimumSize(QSize(0, 0)); + this->setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)); +} +void WidgetStackFixedAspectRatio::resize_to_box(QSize enclosing_box){ +// cout << "resize_to_box()" << endl; + int width, height; + + double box_ratio = (double)enclosing_box.width() / enclosing_box.height(); + if (m_aspect_ratio < box_ratio){ + height = enclosing_box.height(); + width = (int)(height * m_aspect_ratio); + }else{ + width = enclosing_box.width(); + height = (int)(width / m_aspect_ratio); + } + + QSize size(width, height); + + m_detached_internal->setFixedSize(enclosing_box); + m_stack_holder->setFixedSize(size); + for (QWidget* widget : m_widgets){ + widget->setFixedSize(size); + } +} +void WidgetStackFixedAspectRatio::resize_to_width(int width){ +// cout << "resize_to_width()" << endl; +#if 0 + double aspect_ratio = (double)enclosing_box.width() / enclosing_box.height(); + cout << "resize_to_width - aspect_ratio = " << aspect_ratio << endl; + cout << "resize_to_width - min_aspect_ratio = " << m_min_aspect_ratio << endl; + if (aspect_ratio < m_min_aspect_ratio){ + resize_to_box(enclosing_box); + return; + } +#endif + + int previous_width = m_stack_holder->width(); +// cout << "WidgetStackFixedAspectRatio::resize_to_width(): " << width << " <- " << previous_width << endl; + + if (width > previous_width && width < previous_width + 50 && !m_debouncer.check(width)){ +// cout << "Supressing potential infinite resizing loop." << endl; + return; + } + + + int height = (int)(width / m_aspect_ratio); +// cout << "Resizing: " << width << " x " << height << " from: " << previous_width << " x " << m_stack_holder->height() << endl; + + if (width == previous_width && height == m_stack_holder->height() && height != this->height()){ +// cout << "Same size" << endl; + return; + } + + QSize size(width, height); + this->setFixedHeight(height); + + m_detached_internal->setFixedSize(size); + m_stack_holder->setFixedSize(size); + for (QWidget* widget : m_widgets){ + widget->setFixedSize(size); + } +} +void WidgetStackFixedAspectRatio::update_size(QSize size){ +// cout << "size = " << size.width() << ", " << size.height() << endl; + switch (m_size_policy){ + case EXPAND_TO_BOX: + resize_to_box(size); + return; + case ADJUST_HEIGHT_TO_WIDTH: + resize_to_width(size.width()); + return; + } +} +void WidgetStackFixedAspectRatio::resizeEvent(QResizeEvent* event){ +// cout << "WidgetStackFixedAspectRatio::resizeEvent(): " << this->width() << " x " << this->height() << endl; +// cout << "WidgetStackFixedAspectRatio::resizeEvent(): " << event->size().width() << " x " << event->size().height() << endl; + update_size(event->size()); +} + + + +} diff --git a/Common/Qt/WidgetStackFixedAspectRatio.h b/Common/Qt/WidgetStackFixedAspectRatio.h index c49b95a068..739ee1287c 100644 --- a/Common/Qt/WidgetStackFixedAspectRatio.h +++ b/Common/Qt/WidgetStackFixedAspectRatio.h @@ -1,63 +1,63 @@ -/* Widget Stack Fixed Aspect Ratio - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_WidgetStackFixedAspectRatio_H -#define PokemonAutomation_WidgetStackFixedAspectRatio_H - -#include -#include -#include "Common/Cpp/ValueDebouncer.h" - -namespace PokemonAutomation{ - - -class WidgetStackFixedAspectRatio : public QWidget{ -public: - enum SizePolicy{ - EXPAND_TO_BOX, - ADJUST_HEIGHT_TO_WIDTH, - }; - -public: - WidgetStackFixedAspectRatio( - QWidget& parent, - SizePolicy size_policy, - double aspect_ratio = 16/9. - ); - - double sanitize_aspect_ratio(double aspect_ratio) const; - - void set_size_policy(SizePolicy size_policy); - void set_aspect_ratio(double aspect_ratio); - void set_all(SizePolicy size_policy, double aspect_ratio); - - void add_widget(QWidget& widget); - void remove_widget(QWidget* widget); - - virtual void resizeEvent(QResizeEvent* event) override; - -private: - void clear_fixed_dimensions(); - void resize_to_box(QSize enclosing_box); - void resize_to_width(int width); - - void update_size(QSize size); - -private: - SizePolicy m_size_policy; - double m_aspect_ratio; - std::set m_widgets; - - QWidget* m_detached_internal; - QWidget* m_stack_holder; - - ValueDebouncer m_debouncer; -}; - - - -} -#endif +/* Widget Stack Fixed Aspect Ratio + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_WidgetStackFixedAspectRatio_H +#define PokemonAutomation_WidgetStackFixedAspectRatio_H + +#include +#include +#include "Common/Cpp/ValueDebouncer.h" + +namespace PokemonAutomation{ + + +class WidgetStackFixedAspectRatio : public QWidget{ +public: + enum SizePolicy{ + EXPAND_TO_BOX, + ADJUST_HEIGHT_TO_WIDTH, + }; + +public: + WidgetStackFixedAspectRatio( + QWidget& parent, + SizePolicy size_policy, + double aspect_ratio = 16/9. + ); + + double sanitize_aspect_ratio(double aspect_ratio) const; + + void set_size_policy(SizePolicy size_policy); + void set_aspect_ratio(double aspect_ratio); + void set_all(SizePolicy size_policy, double aspect_ratio); + + void add_widget(QWidget& widget); + void remove_widget(QWidget* widget); + + virtual void resizeEvent(QResizeEvent* event) override; + +private: + void clear_fixed_dimensions(); + void resize_to_box(QSize enclosing_box); + void resize_to_width(int width); + + void update_size(QSize size); + +private: + SizePolicy m_size_policy; + double m_aspect_ratio; + std::set m_widgets; + + QWidget* m_detached_internal; + QWidget* m_stack_holder; + + ValueDebouncer m_debouncer; +}; + + + +} +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h b/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h index 7fe3b30e8a..7d9c9f2881 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h +++ b/Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h @@ -1,111 +1,111 @@ -/* SerialPABotBase Messages (ESP32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Messages_ESP32_H -#define PokemonAutomation_SerialPABotBase_Messages_ESP32_H - -#include "SerialPABotBase_Protocol.h" - -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#elif __GNUC__ -#define PABB_PACK __attribute__((packed)) -#else -#define PABB_PACK -#endif - - -#ifdef __cplusplus -extern "C" { -#endif - - - -typedef struct{ - uint8_t body[3]; - uint8_t buttons[3]; - uint8_t left_grip[3]; - uint8_t right_grip[3]; -} PABB_NintendoSwitch_ControllerColors; - -typedef struct{ - uint8_t button3; - uint8_t button4; - uint8_t button5; - uint8_t left_joystick[3]; - uint8_t right_joystick[3]; - uint8_t vibrator; -} PABB_NintendoSwitch_ButtonState; - -typedef struct{ - int16_t accel_x; - int16_t accel_y; - int16_t accel_z; - int16_t rotation_x; - int16_t rotation_y; - int16_t rotation_z; -} PABB_NintendoSwitch_GyroState; - -typedef struct{ - PABB_NintendoSwitch_GyroState time0; - PABB_NintendoSwitch_GyroState time1; - PABB_NintendoSwitch_GyroState time2; -} PABB_NintendoSwitch_GyroStateX3; - - - - - -#define PABB_MSG_ESP32_REQUEST_READ_SPI 0x60 -typedef struct{ - seqnum_t seqnum; - uint32_t controller_type; - uint32_t address; - uint8_t bytes; -} PABB_PACK pabb_Message_ESP32_ReadSpi; - -#define PABB_MSG_ESP32_REQUEST_WRITE_SPI 0x61 -typedef struct{ - seqnum_t seqnum; - uint32_t controller_type; - uint32_t address; - uint8_t bytes; -} PABB_PACK pabb_Message_ESP32_WriteSpi; - - - -#define PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS 0xa0 -typedef struct{ - seqnum_t seqnum; - uint16_t milliseconds; - PABB_NintendoSwitch_ButtonState buttons; -} PABB_PACK pabb_Message_ESP32_CommandButtonState; - - -#define PABB_MSG_ESP32_CONTROLLER_STATE_FULL 0xa1 -typedef struct{ - seqnum_t seqnum; - uint16_t milliseconds; - PABB_NintendoSwitch_ButtonState buttons; - PABB_NintendoSwitch_GyroStateX3 gyro; -} PABB_PACK pabb_Message_ESP32_CommandFullState; - - - - -#ifdef __cplusplus -} -#endif - - - -#if _WIN32 -#pragma pack(pop) -#endif - - -#endif +/* SerialPABotBase Messages (ESP32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Messages_ESP32_H +#define PokemonAutomation_SerialPABotBase_Messages_ESP32_H + +#include "SerialPABotBase_Protocol.h" + +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#elif __GNUC__ +#define PABB_PACK __attribute__((packed)) +#else +#define PABB_PACK +#endif + + +#ifdef __cplusplus +extern "C" { +#endif + + + +typedef struct{ + uint8_t body[3]; + uint8_t buttons[3]; + uint8_t left_grip[3]; + uint8_t right_grip[3]; +} PABB_NintendoSwitch_ControllerColors; + +typedef struct{ + uint8_t button3; + uint8_t button4; + uint8_t button5; + uint8_t left_joystick[3]; + uint8_t right_joystick[3]; + uint8_t vibrator; +} PABB_NintendoSwitch_ButtonState; + +typedef struct{ + int16_t accel_x; + int16_t accel_y; + int16_t accel_z; + int16_t rotation_x; + int16_t rotation_y; + int16_t rotation_z; +} PABB_NintendoSwitch_GyroState; + +typedef struct{ + PABB_NintendoSwitch_GyroState time0; + PABB_NintendoSwitch_GyroState time1; + PABB_NintendoSwitch_GyroState time2; +} PABB_NintendoSwitch_GyroStateX3; + + + + + +#define PABB_MSG_ESP32_REQUEST_READ_SPI 0x60 +typedef struct{ + seqnum_t seqnum; + uint32_t controller_type; + uint32_t address; + uint8_t bytes; +} PABB_PACK pabb_Message_ESP32_ReadSpi; + +#define PABB_MSG_ESP32_REQUEST_WRITE_SPI 0x61 +typedef struct{ + seqnum_t seqnum; + uint32_t controller_type; + uint32_t address; + uint8_t bytes; +} PABB_PACK pabb_Message_ESP32_WriteSpi; + + + +#define PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS 0xa0 +typedef struct{ + seqnum_t seqnum; + uint16_t milliseconds; + PABB_NintendoSwitch_ButtonState buttons; +} PABB_PACK pabb_Message_ESP32_CommandButtonState; + + +#define PABB_MSG_ESP32_CONTROLLER_STATE_FULL 0xa1 +typedef struct{ + seqnum_t seqnum; + uint16_t milliseconds; + PABB_NintendoSwitch_ButtonState buttons; + PABB_NintendoSwitch_GyroStateX3 gyro; +} PABB_PACK pabb_Message_ESP32_CommandFullState; + + + + +#ifdef __cplusplus +} +#endif + + + +#if _WIN32 +#pragma pack(pop) +#endif + + +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h b/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h index 8874aa39bb..1a267eee6c 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h +++ b/Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h @@ -1,67 +1,67 @@ -/* SerialPABotBase Messages (Nintendo Switch Generic Wired Controller) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H -#define PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H - -#include "SerialPABotBase_Protocol.h" - -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#elif __GNUC__ -#define PABB_PACK __attribute__((packed)) -#else -#define PABB_PACK -#endif - - -#ifdef __cplusplus -namespace PokemonAutomation{ -namespace SerialPABotBase{ -#endif - - - -#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS 0x9f -typedef struct{ - seqnum_t seqnum; - uint16_t buttons; - uint8_t dpad; - uint8_t left_joystick_x; - uint8_t left_joystick_y; - uint8_t right_joystick_x; - uint8_t right_joystick_y; - uint8_t ticks; -} PABB_PACK pabb_Message_NS_Generic_ControllerStateTicks; - - - -#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS 0x90 -typedef struct{ - seqnum_t seqnum; - uint16_t milliseconds; - uint16_t buttons; - uint8_t dpad; - uint8_t left_joystick_x; - uint8_t left_joystick_y; - uint8_t right_joystick_x; - uint8_t right_joystick_y; -} PABB_PACK pabb_Message_NS_Generic_ControllerStateMs; - - - -#ifdef __cplusplus -} -} -#endif - - -#if _WIN32 -#pragma pack(pop) -#endif - -#endif +/* SerialPABotBase Messages (Nintendo Switch Generic Wired Controller) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H +#define PokemonAutomation_SerialPABotBase_Messages_NS_Generic_H + +#include "SerialPABotBase_Protocol.h" + +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#elif __GNUC__ +#define PABB_PACK __attribute__((packed)) +#else +#define PABB_PACK +#endif + + +#ifdef __cplusplus +namespace PokemonAutomation{ +namespace SerialPABotBase{ +#endif + + + +#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS 0x9f +typedef struct{ + seqnum_t seqnum; + uint16_t buttons; + uint8_t dpad; + uint8_t left_joystick_x; + uint8_t left_joystick_y; + uint8_t right_joystick_x; + uint8_t right_joystick_y; + uint8_t ticks; +} PABB_PACK pabb_Message_NS_Generic_ControllerStateTicks; + + + +#define PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS 0x90 +typedef struct{ + seqnum_t seqnum; + uint16_t milliseconds; + uint16_t buttons; + uint8_t dpad; + uint8_t left_joystick_x; + uint8_t left_joystick_y; + uint8_t right_joystick_x; + uint8_t right_joystick_y; +} PABB_PACK pabb_Message_NS_Generic_ControllerStateMs; + + + +#ifdef __cplusplus +} +} +#endif + + +#if _WIN32 +#pragma pack(pop) +#endif + +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Protocol.h b/Common/SerialPABotBase/SerialPABotBase_Protocol.h index 4100806185..7258c7924e 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Protocol.h +++ b/Common/SerialPABotBase/SerialPABotBase_Protocol.h @@ -1,362 +1,362 @@ -/* Serial PABotBase Message Protocol - * - * From: https://github.com/PokemonAutomation/ - * - * - * Pokemon Automation Bot-Base implements reliable data transmissions over - * serial communication. This is done by checksumming messages along with a - * protocol that is tolerant to data drops. - * - * This file describes the message protocol. The data being transmitted is raw - * binary and not is readable text. - * - * - * Message Format: - * byte 0: Length of the entire message. (bits are inverted) - * byte 1: Message Type - * byte X: Optional data of variable length. - * Last 4 bytes: CRC32C of the entire message except these last 4 bytes. - * - * Thus there are 6 bytes of overhead for each message. - * - * - * There are currently 4 categories of message types: - * - * 1. Info: These are simple one-way messages. They do not need to be - * acked and may be dropped without adversely affecting anything. - * - * 2. Ack/Response: These are messages sent in response to an earlier - * message that was received. - * - * 3. Request: The sender requests the receiver to do something simple. - * The receiver must respond with an ack. - * - * This is used for things that take no clock time. For example, querying - * for program identifiers, turning on/off LEDs, or setting flags in the - * program to change its behavior in the future. - * - * 4. Command: The sender requests the receiver to do a large asynchronous - * operation. The receiver must ack this message. Once the command is - * finished, the receiver must send a request message back to the sender - * to indicate that the command is finished. - * - * This is used for issuing button presses or other subroutines that - * consume time. - * - * - * General Protocol: - * - * 1. Every time you send a new request/command message, you increment - * your sequence number (seqnum) by 1. - * - * 2. If you receive an invalid message (bad length or bad checksum), ignore - * the first byte and attempt to parse the next byte as the start of a - * new message. - * - * 3. If you receive a zero for the 1st byte of a message, ignore it and - * attempt to parse the next byte as the start of a new message. - * - * 4. At any point, you can send a bunch of zero bytes. This will cause - * the receiver to re-synchronize. - * - * 5. If you receive a request/command message, you must send the appropriate - * ack/response message using the same seqnum. - * - * 6. If you receive a command message, you must first ack the message itself. - * Once the command is finished, you must send a request referencing the - * command to indicate that it is finished. You will receive an ack for - * this short (finishing) command, and if you don't, send it again until - * you do. If the command finishes immediately, you can skip the ack and - * just send the finish request. - * - * 7. If you send a request/command message and don't get a response after - * a time limit, you should resend the message with the same seqnum. - * - * 8. If you receive a request/command that has a seqnum ahead of what you - * are expecting, it means an earlier request/command was dropped. - * Do not process the request/command since you will lose ordering. - * - * 9. If you receive a request/command that has an old seqnum, it is a - * retransmit. Send an ack for it, but don't process it again. (idempotency) - * - * - * Failure Analysis: - * - * - Corrupted messages will either fail checksum or will have an invalid - * length/type. These are simply ignored and dropped. - * - * - If either sender or receiver gets out-of-sync and loses track of - * message boundaries, it will eventually find the boundary again by - * simply trying to parse every byte as the start of a new message and - * verifying the length and CRC. - * - * - If a request/command is dropped, no ack will be received. The sender - * will eventually send the command again. (#7) - * - * - If an ack is dropped, the sender will eventually resend the - * request/command again. The receiver will see the duplicate - * request/command and ack it. But the receiver will not process it - * again to preserve idempotency. (#9) - * - * The current protocol guarantees that all commands are processed in order - * exactly once. Requests are not guaranteed to process in order and may execute - * more than once so they should be idempotent. - * - * The protocol also allows both sides to queue up requests and commands. - * In other words, it is possible to send multiple requests/commands at once - * without waiting for the individual acks. - * - * - * PABotBase Specifics: - * - * - PABotBase can queue up to 4 commands. If it receives any commands - * while the queue is full, it drops it and responds with - * "PABB_MSG_ERROR_COMMAND_DROPPED". (Any command that results in a - * button press or a wait is a long command.) - * - * - PABotBase can still handle other messages while it is running a long - * command. - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Protocol_H -#define PokemonAutomation_SerialPABotBase_Protocol_H - -#include -#include - -#if _WIN32 -#pragma pack(push, 1) -#define PABB_PACK -#elif __GNUC__ -#define PABB_PACK __attribute__((packed)) -#else -#define PABB_PACK -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -#define PABB_BAUD_RATE 115200 -#define PABB_PROTOCOL_OVERHEAD (2 + sizeof(uint32_t)) - -// Must be a power-of-two. -#define PABB_DEVICE_MINIMUM_QUEUE_SIZE 4 - -typedef uint32_t seqnum_t; - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// -// Basic Message Types - -#define PABB_MSG_IS_ERROR(x) (((x) & 0xf0) == 0x00) // Framework errors between 0x00 - 0x0f. -#define PABB_MSG_IS_ACK(x) (((x) & 0xf0) == 0x10) // Acks between 0x10 - 0x1f. -#define PABB_MSG_IS_INFO(x) (((x) & 0xe0) == 0x20) // Custom info between 0x20 - 0x3f. -#define PABB_MSG_IS_REQUEST(x) (((x) & 0xc0) == 0x40) // Requests between 0x40 - 0x7f. -#define PABB_MSG_IS_COMMAND(x) ((x) >= 0x80) // Commands between 0x80 - 0xff. - -#define PABB_MSG_IS_REQUEST_OR_COMMAND(x) ((x) >= 0x40) - -//////////////////////////////////////////////////////////////////////////////// -// Framework Errors -#define PABB_MSG_ERROR_READY 0x00 -// No Parameters - -#define PABB_MSG_ERROR_INVALID_MESSAGE 0x01 -typedef struct{ - uint8_t message_length; -} PABB_PACK pabb_MsgInfoInvalidMessage; - -#define PABB_MSG_ERROR_CHECKSUM_MISMATCH 0x02 -typedef struct{ - uint8_t message_length; -} PABB_PACK pabb_MsgInfoChecksumMismatch; - -#define PABB_MSG_ERROR_INVALID_TYPE 0x03 -typedef struct{ - uint8_t type; -} PABB_PACK pabb_MsgInfoInvalidType; - -#define PABB_MSG_ERROR_INVALID_REQUEST 0x04 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoInvalidRequest; - -#define PABB_MSG_ERROR_MISSED_REQUEST 0x05 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoMissedRequest; - -#define PABB_MSG_ERROR_COMMAND_DROPPED 0x06 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoCommandDropped; - -#define PABB_MSG_ERROR_WARNING 0x07 -typedef struct{ - uint16_t error_code; -} PABB_PACK pabb_MsgInfoWARNING; - -#define PABB_MSG_ERROR_DISCONNECTED 0x08 -typedef struct{ - uint16_t error_code; -} PABB_PACK pabb_MsgInfoDisconnected; - -//////////////////////////////////////////////////////////////////////////////// -// Ack - -#define PABB_MSG_ACK_COMMAND 0x10 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgAckCommand; - -#define PABB_MSG_ACK_REQUEST 0x11 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgAckRequest; - -#define PABB_MSG_ACK_REQUEST_I8 0x12 -typedef struct{ - seqnum_t seqnum; - uint8_t data; -} PABB_PACK pabb_MsgAckRequestI8; - -#define PABB_MSG_ACK_REQUEST_I16 0x13 -typedef struct{ - seqnum_t seqnum; - uint16_t data; -} PABB_PACK pabb_MsgAckRequestI16; - -#define PABB_MSG_ACK_REQUEST_I32 0x14 -typedef struct{ - seqnum_t seqnum; - uint32_t data; -} PABB_PACK pabb_MsgAckRequestI32; - -#define PABB_MSG_ACK_REQUEST_DATA 0x1f -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgAckRequestData; - -//////////////////////////////////////////////////////////////////////////////// -// Custom Info - -#define PABB_MSG_INFO_I32 0x20 -typedef struct{ - uint8_t tag; - uint32_t data; -} PABB_PACK pabb_MsgInfoI32; - -#define PABB_MSG_INFO_DATA 0x21 -typedef struct{ - uint32_t tag; -} PABB_PACK pabb_MsgInfoData; - -#define PABB_MSG_INFO_STRING 0x23 - -#define PABB_MSG_INFO_I32_LABEL 0x24 -#define PABB_MSG_INFO_H32_LABEL 0x25 -typedef struct{ - uint32_t value; -} PABB_PACK pabb_MsgInfoI32Label; - -//////////////////////////////////////////////////////////////////////////////// -// Requests - -#define PABB_MSG_SEQNUM_RESET 0x40 -// After you send this message, the next seqnum you should use is (seqnum + 1). -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgInfoSeqnumReset; - -#define PABB_MSG_REQUEST_PROTOCOL_VERSION 0x41 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestProtocolVersion; - -#define PABB_MSG_REQUEST_PROGRAM_VERSION 0x42 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestProgramVersion; - -#define PABB_MSG_REQUEST_PROGRAM_ID 0x43 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestProgramID; - -#define PABB_MSG_REQUEST_CLOCK 0x44 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_system_clock; - -#define PABB_MSG_REQUEST_COMMAND_FINISHED 0x45 -// When you receive this message, you must ack it with PABB_MSG_ACK_REQUEST. -typedef struct{ - seqnum_t seqnum; - seqnum_t seq_of_original_command; - uint32_t finish_time; -} PABB_PACK pabb_MsgRequestCommandFinished; - -#define PABB_MSG_REQUEST_STOP 0x46 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestStop; - -#define PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT 0x47 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestNextCmdInterrupt; - -#define PABB_MSG_REQUEST_QUEUE_SIZE 0x48 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestQueueSize; - -#define PABB_MSG_REQUEST_READ_CONTROLLER_MODE 0x49 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_MsgRequestReadControllerMode; - -#define PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE 0x4a -typedef struct{ - seqnum_t seqnum; - uint32_t mode; -} PABB_PACK pabb_MsgRequestChangeControllerMode; - -//////////////////////////////////////////////////////////////////////////////// -// Common Requests - -#define PABB_MSG_REQUEST_STATUS 0x50 -typedef struct{ - seqnum_t seqnum; -} PABB_PACK pabb_Message_RequestStatus; - -//////////////////////////////////////////////////////////////////////////////// -// Commands - -// These are no longer supported by anything. - -#if 0 -#define PABB_MSG_COMMAND_SET_LED_STATE 0x81 -typedef struct{ - seqnum_t seqnum; - bool on; -} PABB_PACK pabb_MsgCommandSetLeds; -#endif - -//////////////////////////////////////////////////////////////////////////////// -//////////////////////////////////////////////////////////////////////////////// - -#ifdef __cplusplus -} -#endif - -#if _WIN32 -#pragma pack(pop) -#endif - -#endif +/* Serial PABotBase Message Protocol + * + * From: https://github.com/PokemonAutomation/ + * + * + * Pokemon Automation Bot-Base implements reliable data transmissions over + * serial communication. This is done by checksumming messages along with a + * protocol that is tolerant to data drops. + * + * This file describes the message protocol. The data being transmitted is raw + * binary and not is readable text. + * + * + * Message Format: + * byte 0: Length of the entire message. (bits are inverted) + * byte 1: Message Type + * byte X: Optional data of variable length. + * Last 4 bytes: CRC32C of the entire message except these last 4 bytes. + * + * Thus there are 6 bytes of overhead for each message. + * + * + * There are currently 4 categories of message types: + * + * 1. Info: These are simple one-way messages. They do not need to be + * acked and may be dropped without adversely affecting anything. + * + * 2. Ack/Response: These are messages sent in response to an earlier + * message that was received. + * + * 3. Request: The sender requests the receiver to do something simple. + * The receiver must respond with an ack. + * + * This is used for things that take no clock time. For example, querying + * for program identifiers, turning on/off LEDs, or setting flags in the + * program to change its behavior in the future. + * + * 4. Command: The sender requests the receiver to do a large asynchronous + * operation. The receiver must ack this message. Once the command is + * finished, the receiver must send a request message back to the sender + * to indicate that the command is finished. + * + * This is used for issuing button presses or other subroutines that + * consume time. + * + * + * General Protocol: + * + * 1. Every time you send a new request/command message, you increment + * your sequence number (seqnum) by 1. + * + * 2. If you receive an invalid message (bad length or bad checksum), ignore + * the first byte and attempt to parse the next byte as the start of a + * new message. + * + * 3. If you receive a zero for the 1st byte of a message, ignore it and + * attempt to parse the next byte as the start of a new message. + * + * 4. At any point, you can send a bunch of zero bytes. This will cause + * the receiver to re-synchronize. + * + * 5. If you receive a request/command message, you must send the appropriate + * ack/response message using the same seqnum. + * + * 6. If you receive a command message, you must first ack the message itself. + * Once the command is finished, you must send a request referencing the + * command to indicate that it is finished. You will receive an ack for + * this short (finishing) command, and if you don't, send it again until + * you do. If the command finishes immediately, you can skip the ack and + * just send the finish request. + * + * 7. If you send a request/command message and don't get a response after + * a time limit, you should resend the message with the same seqnum. + * + * 8. If you receive a request/command that has a seqnum ahead of what you + * are expecting, it means an earlier request/command was dropped. + * Do not process the request/command since you will lose ordering. + * + * 9. If you receive a request/command that has an old seqnum, it is a + * retransmit. Send an ack for it, but don't process it again. (idempotency) + * + * + * Failure Analysis: + * + * - Corrupted messages will either fail checksum or will have an invalid + * length/type. These are simply ignored and dropped. + * + * - If either sender or receiver gets out-of-sync and loses track of + * message boundaries, it will eventually find the boundary again by + * simply trying to parse every byte as the start of a new message and + * verifying the length and CRC. + * + * - If a request/command is dropped, no ack will be received. The sender + * will eventually send the command again. (#7) + * + * - If an ack is dropped, the sender will eventually resend the + * request/command again. The receiver will see the duplicate + * request/command and ack it. But the receiver will not process it + * again to preserve idempotency. (#9) + * + * The current protocol guarantees that all commands are processed in order + * exactly once. Requests are not guaranteed to process in order and may execute + * more than once so they should be idempotent. + * + * The protocol also allows both sides to queue up requests and commands. + * In other words, it is possible to send multiple requests/commands at once + * without waiting for the individual acks. + * + * + * PABotBase Specifics: + * + * - PABotBase can queue up to 4 commands. If it receives any commands + * while the queue is full, it drops it and responds with + * "PABB_MSG_ERROR_COMMAND_DROPPED". (Any command that results in a + * button press or a wait is a long command.) + * + * - PABotBase can still handle other messages while it is running a long + * command. + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Protocol_H +#define PokemonAutomation_SerialPABotBase_Protocol_H + +#include +#include + +#if _WIN32 +#pragma pack(push, 1) +#define PABB_PACK +#elif __GNUC__ +#define PABB_PACK __attribute__((packed)) +#else +#define PABB_PACK +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +#define PABB_BAUD_RATE 115200 +#define PABB_PROTOCOL_OVERHEAD (2 + sizeof(uint32_t)) + +// Must be a power-of-two. +#define PABB_DEVICE_MINIMUM_QUEUE_SIZE 4 + +typedef uint32_t seqnum_t; + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// +// Basic Message Types + +#define PABB_MSG_IS_ERROR(x) (((x) & 0xf0) == 0x00) // Framework errors between 0x00 - 0x0f. +#define PABB_MSG_IS_ACK(x) (((x) & 0xf0) == 0x10) // Acks between 0x10 - 0x1f. +#define PABB_MSG_IS_INFO(x) (((x) & 0xe0) == 0x20) // Custom info between 0x20 - 0x3f. +#define PABB_MSG_IS_REQUEST(x) (((x) & 0xc0) == 0x40) // Requests between 0x40 - 0x7f. +#define PABB_MSG_IS_COMMAND(x) ((x) >= 0x80) // Commands between 0x80 - 0xff. + +#define PABB_MSG_IS_REQUEST_OR_COMMAND(x) ((x) >= 0x40) + +//////////////////////////////////////////////////////////////////////////////// +// Framework Errors +#define PABB_MSG_ERROR_READY 0x00 +// No Parameters + +#define PABB_MSG_ERROR_INVALID_MESSAGE 0x01 +typedef struct{ + uint8_t message_length; +} PABB_PACK pabb_MsgInfoInvalidMessage; + +#define PABB_MSG_ERROR_CHECKSUM_MISMATCH 0x02 +typedef struct{ + uint8_t message_length; +} PABB_PACK pabb_MsgInfoChecksumMismatch; + +#define PABB_MSG_ERROR_INVALID_TYPE 0x03 +typedef struct{ + uint8_t type; +} PABB_PACK pabb_MsgInfoInvalidType; + +#define PABB_MSG_ERROR_INVALID_REQUEST 0x04 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoInvalidRequest; + +#define PABB_MSG_ERROR_MISSED_REQUEST 0x05 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoMissedRequest; + +#define PABB_MSG_ERROR_COMMAND_DROPPED 0x06 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoCommandDropped; + +#define PABB_MSG_ERROR_WARNING 0x07 +typedef struct{ + uint16_t error_code; +} PABB_PACK pabb_MsgInfoWARNING; + +#define PABB_MSG_ERROR_DISCONNECTED 0x08 +typedef struct{ + uint16_t error_code; +} PABB_PACK pabb_MsgInfoDisconnected; + +//////////////////////////////////////////////////////////////////////////////// +// Ack + +#define PABB_MSG_ACK_COMMAND 0x10 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgAckCommand; + +#define PABB_MSG_ACK_REQUEST 0x11 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgAckRequest; + +#define PABB_MSG_ACK_REQUEST_I8 0x12 +typedef struct{ + seqnum_t seqnum; + uint8_t data; +} PABB_PACK pabb_MsgAckRequestI8; + +#define PABB_MSG_ACK_REQUEST_I16 0x13 +typedef struct{ + seqnum_t seqnum; + uint16_t data; +} PABB_PACK pabb_MsgAckRequestI16; + +#define PABB_MSG_ACK_REQUEST_I32 0x14 +typedef struct{ + seqnum_t seqnum; + uint32_t data; +} PABB_PACK pabb_MsgAckRequestI32; + +#define PABB_MSG_ACK_REQUEST_DATA 0x1f +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgAckRequestData; + +//////////////////////////////////////////////////////////////////////////////// +// Custom Info + +#define PABB_MSG_INFO_I32 0x20 +typedef struct{ + uint8_t tag; + uint32_t data; +} PABB_PACK pabb_MsgInfoI32; + +#define PABB_MSG_INFO_DATA 0x21 +typedef struct{ + uint32_t tag; +} PABB_PACK pabb_MsgInfoData; + +#define PABB_MSG_INFO_STRING 0x23 + +#define PABB_MSG_INFO_I32_LABEL 0x24 +#define PABB_MSG_INFO_H32_LABEL 0x25 +typedef struct{ + uint32_t value; +} PABB_PACK pabb_MsgInfoI32Label; + +//////////////////////////////////////////////////////////////////////////////// +// Requests + +#define PABB_MSG_SEQNUM_RESET 0x40 +// After you send this message, the next seqnum you should use is (seqnum + 1). +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgInfoSeqnumReset; + +#define PABB_MSG_REQUEST_PROTOCOL_VERSION 0x41 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestProtocolVersion; + +#define PABB_MSG_REQUEST_PROGRAM_VERSION 0x42 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestProgramVersion; + +#define PABB_MSG_REQUEST_PROGRAM_ID 0x43 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestProgramID; + +#define PABB_MSG_REQUEST_CLOCK 0x44 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_system_clock; + +#define PABB_MSG_REQUEST_COMMAND_FINISHED 0x45 +// When you receive this message, you must ack it with PABB_MSG_ACK_REQUEST. +typedef struct{ + seqnum_t seqnum; + seqnum_t seq_of_original_command; + uint32_t finish_time; +} PABB_PACK pabb_MsgRequestCommandFinished; + +#define PABB_MSG_REQUEST_STOP 0x46 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestStop; + +#define PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT 0x47 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestNextCmdInterrupt; + +#define PABB_MSG_REQUEST_QUEUE_SIZE 0x48 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestQueueSize; + +#define PABB_MSG_REQUEST_READ_CONTROLLER_MODE 0x49 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_MsgRequestReadControllerMode; + +#define PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE 0x4a +typedef struct{ + seqnum_t seqnum; + uint32_t mode; +} PABB_PACK pabb_MsgRequestChangeControllerMode; + +//////////////////////////////////////////////////////////////////////////////// +// Common Requests + +#define PABB_MSG_REQUEST_STATUS 0x50 +typedef struct{ + seqnum_t seqnum; +} PABB_PACK pabb_Message_RequestStatus; + +//////////////////////////////////////////////////////////////////////////////// +// Commands + +// These are no longer supported by anything. + +#if 0 +#define PABB_MSG_COMMAND_SET_LED_STATE 0x81 +typedef struct{ + seqnum_t seqnum; + bool on; +} PABB_PACK pabb_MsgCommandSetLeds; +#endif + +//////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +} +#endif + +#if _WIN32 +#pragma pack(pop) +#endif + +#endif diff --git a/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h b/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h index bf78950ce7..e3689040e1 100644 --- a/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h +++ b/Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h @@ -1,41 +1,41 @@ -/* SerialPABotBase Protocol IDs - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Protocol_IDs_H -#define PokemonAutomation_SerialPABotBase_Protocol_IDs_H - - -// Program IDs -#define PABB_PID_UNSPECIFIED 0x00 - -// Old AVR8 -#define PABB_PID_PABOTBASE_12KB 0x08 -#define PABB_PID_PABOTBASE_31KB 0x09 - -// New AVR8 -#define PABB_PID_PABOTBASE_ArduinoUnoR3 0x01 -#define PABB_PID_PABOTBASE_ArduinoLeonardo 0x02 -#define PABB_PID_PABOTBASE_ProMicro 0x03 -#define PABB_PID_PABOTBASE_Teensy2 0x04 -#define PABB_PID_PABOTBASE_TeensyPP2 0x05 - -// Misc. -#define PABB_PID_PABOTBASE_CH552 0x0a - -// ESP32 -#define PABB_PID_PABOTBASE_ESP32 0x10 -#define PABB_PID_PABOTBASE_ESP32S3 0x12 - - -// Controller IDs -#define PABB_CID_NONE 0 -#define PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER 1 -#define PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER 2 -#define PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON 3 -#define PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON 4 - - -#endif +/* SerialPABotBase Protocol IDs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Protocol_IDs_H +#define PokemonAutomation_SerialPABotBase_Protocol_IDs_H + + +// Program IDs +#define PABB_PID_UNSPECIFIED 0x00 + +// Old AVR8 +#define PABB_PID_PABOTBASE_12KB 0x08 +#define PABB_PID_PABOTBASE_31KB 0x09 + +// New AVR8 +#define PABB_PID_PABOTBASE_ArduinoUnoR3 0x01 +#define PABB_PID_PABOTBASE_ArduinoLeonardo 0x02 +#define PABB_PID_PABOTBASE_ProMicro 0x03 +#define PABB_PID_PABOTBASE_Teensy2 0x04 +#define PABB_PID_PABOTBASE_TeensyPP2 0x05 + +// Misc. +#define PABB_PID_PABOTBASE_CH552 0x0a + +// ESP32 +#define PABB_PID_PABOTBASE_ESP32 0x10 +#define PABB_PID_PABOTBASE_ESP32S3 0x12 + + +// Controller IDs +#define PABB_CID_NONE 0 +#define PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER 1 +#define PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER 2 +#define PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON 3 +#define PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON 4 + + +#endif diff --git a/IconResource/icon.icns b/IconResource/icon.icns index 9483d6da0f..88d138637b 100644 Binary files a/IconResource/icon.icns and b/IconResource/icon.icns differ diff --git a/README.md b/README.md index 086ba6e3b3..0af400e96a 100644 --- a/README.md +++ b/README.md @@ -1,31 +1,31 @@ -# Arduino-Source - -This is the source code for all the main Arduino programs. - -[](https://discord.gg/cQ4gWxN) - - -# Licensing: -- Unless otherwise specified, all source code in this repository is under the MIT license. -- Some files may be under other (compatible) licenses. -- All precompiled binaries and object files are free for non-commercial use only. For all other uses, please contact the Pokémon Automation server admins. - -# Dependencies: - -| **Dependency** | **License** | -| --- | --- | -| Qt5 and Qt6 | LGPLv3 | -| [QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet) | MIT | -| [Qt Wav Reader](https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15) | BSD | -| [nlohmann json](https://github.com/nlohmann/json) | MIT | -| [Sleepy Discord](https://github.com/yourWaifu/sleepy-discord) | MIT | -| [D++](https://github.com/brainboxdotcc/DPP) | Apache 2.0 | -| [LUFA](https://github.com/abcminiuser/lufa) | MIT | -| [Tesseract](https://github.com/tesseract-ocr/tesseract) | Apache 2.0 | -| [Tesseract for Windows](https://github.com/peirick/Tesseract-OCR_for_Windows) | Apache 2.0 | -| [OpenCV](https://github.com/opencv/opencv) | Apache 2.0 | -| [ONNX](https://github.com/microsoft/onnxruntime) | MIT | - -Vanilla GPL is disallowed, though LGPL is allowed. This is for the following reasons: -1. A tiny portion of the project is not open-sourced. (mostly related to telemetry and internal research experiments) -2. We reserve right to re-license the project in ways that do not abide by the copy-left requirement of GPL. +# Arduino-Source + +This is the source code for all the main Arduino programs. + +[](https://discord.gg/cQ4gWxN) + + +# Licensing: +- Unless otherwise specified, all source code in this repository is under the MIT license. +- Some files may be under other (compatible) licenses. +- All precompiled binaries and object files are free for non-commercial use only. For all other uses, please contact the Pokémon Automation server admins. + +# Dependencies: + +| **Dependency** | **License** | +| --- | --- | +| Qt5 and Qt6 | LGPLv3 | +| [QDarkStyleSheet](https://github.com/ColinDuquesnoy/QDarkStyleSheet) | MIT | +| [Qt Wav Reader](https://code.qt.io/cgit/qt/qtmultimedia.git/tree/examples/multimedia/spectrum/app/wavfile.cpp?h=5.15) | BSD | +| [nlohmann json](https://github.com/nlohmann/json) | MIT | +| [Sleepy Discord](https://github.com/yourWaifu/sleepy-discord) | MIT | +| [D++](https://github.com/brainboxdotcc/DPP) | Apache 2.0 | +| [LUFA](https://github.com/abcminiuser/lufa) | MIT | +| [Tesseract](https://github.com/tesseract-ocr/tesseract) | Apache 2.0 | +| [Tesseract for Windows](https://github.com/peirick/Tesseract-OCR_for_Windows) | Apache 2.0 | +| [OpenCV](https://github.com/opencv/opencv) | Apache 2.0 | +| [ONNX](https://github.com/microsoft/onnxruntime) | MIT | + +Vanilla GPL is disallowed, though LGPL is allowed. This is for the following reasons: +1. A tiny portion of the project is not open-sourced. (mostly related to telemetry and internal research experiments) +2. We reserve right to re-license the project in ways that do not abide by the copy-left requirement of GPL. diff --git a/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md b/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md index ad65c8191a..ce0129337a 100644 --- a/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md +++ b/SerialPrograms/BuildInstructions/Build-Ubuntu-Qt6.8.2.md @@ -1,54 +1,54 @@ -# How to Build (Qt 6.8.2) - Ubuntu 24.04 - -Note that our Ubuntu setup does not work. The video display flickers to the point of being unusable. - -## Build Tools: - -Install the following packages: - -``` -sudo apt install cmake -sudo apt install libglx-dev libgl1-mesa-dev -sudo apt install libopencv-dev -``` - - -## Install Qt 6.8.2: - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select custom install settings. -3. Select the following options: - - Qt 6.8.2 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.2-Components.png) - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. Enable parallel build: Build & Run -> Build Steps -> Build -> Details -> CMake arguments: `-j16` (the # of cores you have) -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.2) - Ubuntu 24.04 + +Note that our Ubuntu setup does not work. The video display flickers to the point of being unusable. + +## Build Tools: + +Install the following packages: + +``` +sudo apt install cmake +sudo apt install libglx-dev libgl1-mesa-dev +sudo apt install libopencv-dev +``` + + +## Install Qt 6.8.2: + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select custom install settings. +3. Select the following options: + - Qt 6.8.2 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.2-Components.png) + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. Enable parallel build: Build & Run -> Build Steps -> Build -> Details -> CMake arguments: `-j16` (the # of cores you have) +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md index bde70b48ac..050a4f4773 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt5.12.md @@ -1,60 +1,60 @@ -# How to Build (Qt 5.12) - Windows - -## Build Tools: - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". -4. Install Qt 5.12.12: - 1. [Download the offline installer.](https://www.qt.io/offline-installers) [Direct Download Link](https://download.qt.io/official_releases/qt/5.12/5.12.12/qt-opensource-windows-x86-5.12.12.exe) - 2. Disconnect from the internet. This is needed to keep it from forcing you to create an account. - 3. Run the installer. - 4. When prompted for components, select all of the following: - - Qt 5.12.12 - - MSVC 2017 32-bit - - MSVC 2017 64-bit - - MinGW 7.3.0 32-bit - - MinGW 7.3.0 64-bit - - Developer and Designer Tools - - Qt Creator 5.0.2 CDB Debugger Support - - MinGW 7.3.0 32-bit - - MinGW 7.3.0 64-bit - -![](Images/Windows-Install-Qt.png) - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `Projects` -> `Open`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 5.12.12 MSVC2017 64bit`*. -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `5`.![](Images/QT_MAJOR-6.png) -10. Click the upper green arrow** to compile and launch the program. - -![](Images/Windows-Configuration.png) - - -*Even though it says "MSVC2017", it will be using your MSVC 2019 installation instead. - -**Note that you will not be able to feasibly run with a debugger attached. This is because Qt Creator places a breakpoint on every single thrown exception and this application heavily uses exceptions even for non-error situations. So the debugger will break on literally everything. If you know how to disable break on exceptions, please let us know. - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 5.12) - Windows + +## Build Tools: + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". +4. Install Qt 5.12.12: + 1. [Download the offline installer.](https://www.qt.io/offline-installers) [Direct Download Link](https://download.qt.io/official_releases/qt/5.12/5.12.12/qt-opensource-windows-x86-5.12.12.exe) + 2. Disconnect from the internet. This is needed to keep it from forcing you to create an account. + 3. Run the installer. + 4. When prompted for components, select all of the following: + - Qt 5.12.12 + - MSVC 2017 32-bit + - MSVC 2017 64-bit + - MinGW 7.3.0 32-bit + - MinGW 7.3.0 64-bit + - Developer and Designer Tools + - Qt Creator 5.0.2 CDB Debugger Support + - MinGW 7.3.0 32-bit + - MinGW 7.3.0 64-bit + +![](Images/Windows-Install-Qt.png) + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `Projects` -> `Open`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 5.12.12 MSVC2017 64bit`*. +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `5`.![](Images/QT_MAJOR-6.png) +10. Click the upper green arrow** to compile and launch the program. + +![](Images/Windows-Configuration.png) + + +*Even though it says "MSVC2017", it will be using your MSVC 2019 installation instead. + +**Note that you will not be able to feasibly run with a debugger attached. This is because Qt Creator places a breakpoint on every single thrown exception and this application heavily uses exceptions even for non-error situations. So the debugger will break on literally everything. If you know how to disable break on exceptions, please let us know. + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md index 0109817209..ae21e17237 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.3.2.md @@ -1,81 +1,81 @@ -# How to Build (Qt 6.3.2) - Windows - -We recommend that you install everything here in the exact order listed and the exact versions mentioned. Failing either will likely result in a broken Qt Creator installation that must be fixed by manually configuring it (which is not fun if you don't know what you're doing). - -Required Versions: -- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. -- **Qt 6.3.2** - Do not install a later version of Qt. All Qt versions 6.4.x - 6.5.2 are broken for this project. - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.3.2: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. When prompted to select components, check `Archive` on the right side bar, then click `Filter`. Then select the following options: - - - Qt 6.3.2 - - MSVC 2019 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.3.1.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.3.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.3.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 6.3.2 MSVC2019 64bit`. Click `Configure Project`. -![](Images/Windows-configure-project.png) -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -![](Images/Windows-Configuration-Qt6.png) -9. At the bottom left corner, click the upper green arrow to compile and launch the program. - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.3.2) - Windows + +We recommend that you install everything here in the exact order listed and the exact versions mentioned. Failing either will likely result in a broken Qt Creator installation that must be fixed by manually configuring it (which is not fun if you don't know what you're doing). + +Required Versions: +- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. +- **Qt 6.3.2** - Do not install a later version of Qt. All Qt versions 6.4.x - 6.5.2 are broken for this project. + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.3.2: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. When prompted to select components, check `Archive` on the right side bar, then click `Filter`. Then select the following options: + + - Qt 6.3.2 + - MSVC 2019 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.3.1.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.3.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.3.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 6.3.2 MSVC2019 64bit`. Click `Configure Project`. +![](Images/Windows-configure-project.png) +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +![](Images/Windows-Configuration-Qt6.png) +9. At the bottom left corner, click the upper green arrow to compile and launch the program. + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md index e5d464243c..67c560b804 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.4.md @@ -1,67 +1,67 @@ -# How to Build (Qt 6.4) - Windows - -***Note: Qt 6.4 is not recommended at this time due to a bug in their video pipeline that distorts colors.*** - -## Build Tools: - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.4: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.4.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.4.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `Projects` -> `Open`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 6.4.0 MSVC2019 64bit`. -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) -10. Click the upper green arrow to compile and launch the program. - -![](Images/Windows-Configuration-Qt6.png) - - - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.4) - Windows + +***Note: Qt 6.4 is not recommended at this time due to a bug in their video pipeline that distorts colors.*** + +## Build Tools: + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.4: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.4.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.4.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 8.0.1 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `Projects` -> `Open`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 6.4.0 MSVC2019 64bit`. +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) +10. Click the upper green arrow to compile and launch the program. + +![](Images/Windows-Configuration-Qt6.png) + + + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md index a6b479b310..4c35a3baed 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.2.md @@ -1,73 +1,73 @@ -# How to Build (Qt 6.5.2) - Windows - -***Qt 6.5.2 is broken for this project. Please use [Qt 6.3.2](Build-Qt6.3.2.md) instead.*** - -Required Versions: -- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. -- **Qt 6.5.2** - N/A. This version is broken. - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.5.2: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.5.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.5.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.2 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `Projects` -> `Open`. -6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Select `Desktop Qt 6.5.2 MSVC2019 64bit`. -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. -9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) -10. Click the upper green arrow to compile and launch the program. - -![](Images/Windows-Configuration-Qt6.png) - - - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.5.2) - Windows + +***Qt 6.5.2 is broken for this project. Please use [Qt 6.3.2](Build-Qt6.3.2.md) instead.*** + +Required Versions: +- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. +- **Qt 6.5.2** - N/A. This version is broken. + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.5.2: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select the following options: ![](Images/Windows-Install-Qt6.4.0.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.5.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.5.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.2 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `Projects` -> `Open`. +6. Navigate to [`SerialPrograms`](./) and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Select `Desktop Qt 6.5.2 MSVC2019 64bit`. +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. +9. Open up the file `CMakeLists.txt`. Change `QT_MAJOR` to `6`.![](Images/QT_MAJOR-6.png) +10. Click the upper green arrow to compile and launch the program. + +![](Images/Windows-Configuration-Qt6.png) + + + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md index 22ccb2c376..14f80303d4 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.5.3.md @@ -1,92 +1,92 @@ -# How to Build (Qt 6.5.3) - Windows - -Required Versions: -- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2019: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.5.3: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select the following options: - - Qt 6.5.3 - - MSVC 2019 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.5.3.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.5.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.5.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.3 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.5.3 MSVC2019 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.5.3) - Windows + +Required Versions: +- **Visual Studio 2019** - You must install VS2019. If you install VS2022 instead, your Qt Creator installation will be broken. It is ok to have both VS2019 and VS2022 installed. But you must have VS2019 as that is the version that Qt Creator will look for. + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2019: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2019/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.5.3: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select the following options: + - Qt 6.5.3 + - MSVC 2019 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.5.3.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.5.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.5.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 11.0.3 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.5.3 MSVC2019 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_5_3_MSVC2019_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md index 97a9401ca1..c8f0c6572a 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.7.3.md @@ -1,93 +1,93 @@ -# How to Build (Qt 6.7.3) - Windows - -**(Note: These instructions have not been fully tested for 6.7.3. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.7.3: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select custom install settings. -3. Select the following options: - - Qt 6.7.3 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.7.3-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.7.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.7.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.7.3 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.7.3) - Windows + +**(Note: These instructions have not been fully tested for 6.7.3. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.7.3: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select custom install settings. +3. Select the following options: + - Qt 6.7.3 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.7.3-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.7.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.7.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.7.3 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_7_3_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md index c8b5c12c58..bc0c2ee0df 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.0.md @@ -1,93 +1,93 @@ -# How to Build (Qt 6.8.0) - Windows - -**(Note: These instructions have not been fully tested for 6.8.0. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.0: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-installer -2. Select custom install settings. -3. Select the following options: - - Qt 6.8.0 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.0-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.0 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.0) - Windows + +**(Note: These instructions have not been fully tested for 6.8.0. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.0: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-installer +2. Select custom install settings. +3. Select the following options: + - Qt 6.8.0 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.0-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 14.0.2 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.0 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_0_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md index ef5a42af85..7edd88177d 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.1.md @@ -1,90 +1,90 @@ -# How to Build (Qt 6.8.1) - Windows - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.1: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.8.1 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.1-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.1.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.1\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.0 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.1 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.1) - Windows + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.1: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.8.1 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.1-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.1.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.1\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.0 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.1 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md index 3029c96f52..6081212503 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.2.md @@ -1,90 +1,90 @@ -# How to Build (Qt 6.8.2) - Windows - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.2: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.8.2 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.7.3-Custom.png) -![](Images/Windows-Install-Qt6.8.2-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.1 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.2 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` - - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.2) - Windows + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.2: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.8.2 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.7.3-Custom.png) +![](Images/Windows-Install-Qt6.8.2-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.2.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.2\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 15.0.1 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.2 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_1_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` + + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md index 21165e9ff4..6f007a31c6 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.8.3.md @@ -1,126 +1,126 @@ -# How to Build (Qt 6.8.3) - Windows - -**(Note: These instructions have not been fully tested for 6.8.3. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.8.3: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.8.3 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.8.3-Custom.png) -![](Images/Windows-Install-Qt6.8.3-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.8.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.8.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.3 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` - - -## Upgrading Qt components - -### Installing newer Qt version -If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). - -- When prompted, in `Maintenance Actions`, choose `Add or remove components`. -- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. -- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. - -### Building with the newer Qt version -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) - - -- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. -- Click `Ok`, to save Kits preferences. -- Click the Monitor symbol at the bottom left - - -- Under `Kit`: choose the desired Qt version. -- Under `Build`: choose `Release with Debug Information` -- Click the green arrow to compile and launch the program. -- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. - -### Upgrade compiler -- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. -- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. - -When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.8.3) - Windows + +**(Note: These instructions have not been fully tested for 6.8.3. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.8.3: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.8.3 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.8.3-Custom.png) +![](Images/Windows-Install-Qt6.8.3-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.8.3.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.8.3\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.8.3 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_8_2_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_8_3_MSVC2022_64bit-RelWithDebInfo` + + +## Upgrading Qt components + +### Installing newer Qt version +If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). + +- When prompted, in `Maintenance Actions`, choose `Add or remove components`. +- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. +- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. + +### Building with the newer Qt version +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) + + +- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. +- Click `Ok`, to save Kits preferences. +- Click the Monitor symbol at the bottom left + + +- Under `Kit`: choose the desired Qt version. +- Under `Build`: choose `Release with Debug Information` +- Click the green arrow to compile and launch the program. +- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. + +### Upgrade compiler +- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. +- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. + +When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md index 7011973486..e992af6ddd 100644 --- a/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md +++ b/SerialPrograms/BuildInstructions/Build-Windows-Qt6.9.0.md @@ -1,126 +1,126 @@ -# How to Build (Qt 6.9.0) - Windows - -**(Note: These instructions have not been fully tested for 6.9.0. Let us know if you encounter any issues.)** - -## Build Tools: - -The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. - -1. Install Visual Studio 2022: - 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) - 2. Make sure you select the C++ development tools. -2. Install Windows Development SDK: - 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) -3. Install CMake: - 1. [Download Page](https://cmake.org/download/) - 2. When prompted select, "Add CMake to the system PATH for all users". - -## Install Qt 6.9.0: - -Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. - -### Official Online Installer: - -If you are ok with creating an account with Qt and using their online installer, then use this method. - -1. Download the online installer from here: https://www.qt.io/download-qt-Images/ -3. Select the following options: - - Qt 6.9.0 - - MSVC 2022 64-bit - - Sources - - Additional Libraries - - Qt Image Formats - - Qt Multimedia - - Qt Serial Port - - Qt Debug Information Files - -![](Images/Windows-Install-Qt6.9.0-Custom.png) -![](Images/Windows-Install-Qt6.9.0-Components.png) - -If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. - -### Unofficial Installation Copy: - -If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. - -1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. -2. Download `Qt6.9.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. -3. Move this folder to `C:\`. It will probably ask you for permissions to do it. -4. Navigate to: `C:\Qt6.9.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) - -*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. - -## Setup: - -1. Clone this repo. -2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). -3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. - -![](Images/Directory.png) - -4. Open Qt Creator. -5. Click on `File` -> `Open File or Project`. -6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. -7. It will then ask you to configure the project. Ensure `Desktop Qt 6.9.0 MSVC2022 64bit` and `Release with Debug Information` are selected. - - Ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - Click `Configure Project`. - -![](Images/Windows-configure-project-qt-creator-13.png) - -8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. - -![](Images/Windows-Configuration-Qt6.png) - -9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. - -## Troubleshooting - -### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing - -- Click `Projects` on the left sidebar. -- In `Build directory`, ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). - - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` - - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` - - -## Upgrading Qt components - -### Installing newer Qt version -If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). - -- When prompted, in `Maintenance Actions`, choose `Add or remove components`. -- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. -- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. - -### Building with the newer Qt version -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) - - -- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. -- Click `Ok`, to save Kits preferences. -- Click the Monitor symbol at the bottom left - - -- Under `Kit`: choose the desired Qt version. -- Under `Build`: choose `Release with Debug Information` -- Click the green arrow to compile and launch the program. -- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. - -### Upgrade compiler -- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. -- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. -- In the toolbar, click `Edit` -> `Preferences` -- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. -- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. - -When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. - -
- -**Discord Server:** - - -[](https://discord.gg/cQ4gWxN) - +# How to Build (Qt 6.9.0) - Windows + +**(Note: These instructions have not been fully tested for 6.9.0. Let us know if you encounter any issues.)** + +## Build Tools: + +The installation order here is important. While other orderings may work, this is the specific order that we have tested. And the Qt installation must be the last thing installed. + +1. Install Visual Studio 2022: + 1. [Download Page](https://docs.microsoft.com/en-us/visualstudio/releases/2022/release-notes) + 2. Make sure you select the C++ development tools. +2. Install Windows Development SDK: + 1. [Download Page](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/) +3. Install CMake: + 1. [Download Page](https://cmake.org/download/) + 2. When prompted select, "Add CMake to the system PATH for all users". + +## Install Qt 6.9.0: + +Unlike with Qt 5.12, there is no offline installer for it. So you have two options here, use the online installer, or use a copy of an installation. + +### Official Online Installer: + +If you are ok with creating an account with Qt and using their online installer, then use this method. + +1. Download the online installer from here: https://www.qt.io/download-qt-Images/ +3. Select the following options: + - Qt 6.9.0 + - MSVC 2022 64-bit + - Sources + - Additional Libraries + - Qt Image Formats + - Qt Multimedia + - Qt Serial Port + - Qt Debug Information Files + +![](Images/Windows-Install-Qt6.9.0-Custom.png) +![](Images/Windows-Install-Qt6.9.0-Components.png) + +If you repeatedly run into an error involving "SSL handshake failed", you will not be able to use the online installer. Please try the other option. + +### Unofficial Installation Copy: + +If you are unable or unwilling to use the online installer, the alternative is to copy an installation directly into your system. To do this, you will need to download the installation from us, and copy it into your C drive. + +1. Join our [Discord server](https://discord.gg/cQ4gWxN) and ask for the link to the Qt6 standalone. Someone will DM you with a link*. +2. Download `Qt6.9.0.7z` and decompress it. You can use [7-zip](https://www.7-zip.org/) to decompress it. This will create a folder with the same name. +3. Move this folder to `C:\`. It will probably ask you for permissions to do it. +4. Navigate to: `C:\Qt6.9.0\Tools\QtCreator\bin\` and create a shortcut to `qtcreator.exe`. Copy this shortcut to somewhere convenient. (By default this shortcut is named, `Qt Creator 16.0.0 (Community)`) + +*This Qt6 standalone file is 3GB in size and is being hosted by our staff for our own developers. We don't want the entire world converging here and overrunning the server. + +## Setup: + +1. Clone this repo. +2. Clone the [Packages Repo](https://github.com/PokemonAutomation/Packages). +3. In the `Packages` repo, copy the `SerialPrograms/Resources` folder into the root of the `Arduino-Source` repo. + +![](Images/Directory.png) + +4. Open Qt Creator. +5. Click on `File` -> `Open File or Project`. +6. Navigate to `SerialPrograms` and select `CMakeLists.txt`. +7. It will then ask you to configure the project. Ensure `Desktop Qt 6.9.0 MSVC2022 64bit` and `Release with Debug Information` are selected. + - Ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - Click `Configure Project`. + +![](Images/Windows-configure-project-qt-creator-13.png) + +8. At the bottom left corner, click on the little monitor and select `Release with Debug Information`. + +![](Images/Windows-Configuration-Qt6.png) + +9. Still in the bottom left corner, click the upper green arrow to compile and launch the program. + +## Troubleshooting + +### Failed to open '../3rdPartyBinaries/opencv_world460d.zip', or file missing + +- Click `Projects` on the left sidebar. +- In `Build directory`, ensure the build directory for `Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` is located in the root of the `Arduino-Source` repo, and not buried in subfolders (e.g. `build` or `SerialPrograms`). + - e.g. change the default build directory from: `Arduino-Source/SerialPrograms/build/Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` + - to: `Arduino-Source/build-SerialPrograms-Desktop_Qt_6_9_0_MSVC2022_64bit-RelWithDebInfo` + + +## Upgrading Qt components + +### Installing newer Qt version +If you have already have older versions of Qt installed, but need to upgrade Qt components, you can use the Maintenance tool, which comes pre-instaled with Qt (C:\Qt\MaintenanceTool.exe). + +- When prompted, in `Maintenance Actions`, choose `Add or remove components`. +- You may select the components needed, as per the instructions above, for the newer version. And de-select old versions to remove them, if you wish. +- Optional: In `Maintenance Actions`, you may also choose `Update components` as well. To update Qt Creator, and other components. + +### Building with the newer Qt version +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Under `Kits` tab, choose the newer Qt version (e.g. Desktop Qt 6.8.3) + + +- Under `Compiler`, set it to Microsoft Visual C++ Compiler or Visual Studio, if not already set. +- Click `Ok`, to save Kits preferences. +- Click the Monitor symbol at the bottom left + + +- Under `Kit`: choose the desired Qt version. +- Under `Build`: choose `Release with Debug Information` +- Click the green arrow to compile and launch the program. +- Optional: Move the `UserSettings` folder from the old build folder to the new build folder, to keep your old settings, such as the dev key. + +### Upgrade compiler +- Upgrade the compiler by installing a new version of Visual Studio. Ensure `Desktop development with C++` is checked, so the latest MSVC compiler is also installed. +- Open the `SerialPrograms` project in Qt, as outlined in the "Setup" section above. +- In the toolbar, click `Edit` -> `Preferences` +- Click the `Kits` tab on the left. Then click the `Compilers` tab, click `Re-detect` to refresh the list of compilers. Then click `Apply` in the bottom right. +- Back in the `Kits` tab, your newly installed compilers should now show up in the list of compilers. + +When building, if you get the error `yvals_core.h:931: error: STL1001: Unexpected compiler version, expected MSVC 19.42 or newer` (or something similar), consider deleting the old build folder, and rebuilding from scratch. + +
+ +**Discord Server:** + + +[](https://discord.gg/cQ4gWxN) + diff --git a/SerialPrograms/BuildInstructions/Images/Directory.png b/SerialPrograms/BuildInstructions/Images/Directory.png index 78f63f041e..d96076bb0d 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Directory.png and b/SerialPrograms/BuildInstructions/Images/Directory.png differ diff --git a/SerialPrograms/BuildInstructions/Images/QT-kit-build.png b/SerialPrograms/BuildInstructions/Images/QT-kit-build.png index 53a19c8eb5..1dfa845baf 100644 Binary files a/SerialPrograms/BuildInstructions/Images/QT-kit-build.png and b/SerialPrograms/BuildInstructions/Images/QT-kit-build.png differ diff --git a/SerialPrograms/BuildInstructions/Images/QT-kits.png b/SerialPrograms/BuildInstructions/Images/QT-kits.png index ffc3d8f555..407515b89d 100644 Binary files a/SerialPrograms/BuildInstructions/Images/QT-kits.png and b/SerialPrograms/BuildInstructions/Images/QT-kits.png differ diff --git a/SerialPrograms/BuildInstructions/Images/QT_MAJOR-6.png b/SerialPrograms/BuildInstructions/Images/QT_MAJOR-6.png index 1f7bdc263a..5492e9b20e 100644 Binary files a/SerialPrograms/BuildInstructions/Images/QT_MAJOR-6.png and b/SerialPrograms/BuildInstructions/Images/QT_MAJOR-6.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Configuration-Qt6.png b/SerialPrograms/BuildInstructions/Images/Windows-Configuration-Qt6.png index 948361bb1d..993c9f4928 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Configuration-Qt6.png and b/SerialPrograms/BuildInstructions/Images/Windows-Configuration-Qt6.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Configuration.png b/SerialPrograms/BuildInstructions/Images/Windows-Configuration.png index c75006fd4a..606f1fe9b5 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Configuration.png and b/SerialPrograms/BuildInstructions/Images/Windows-Configuration.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt.png index c7a7b0f561..d04b451b1c 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.3.1.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.3.1.png index 3cb304200c..f1fb97c8bc 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.3.1.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.3.1.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.4.0.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.4.0.png index f79a1c82fb..2acb59acf3 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.4.0.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.4.0.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.5.3.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.5.3.png index 28cac7ee14..2d958c6c21 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.5.3.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.5.3.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Components.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Components.png index 13296edc3a..4b0769ec9b 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Components.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Components.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Custom.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Custom.png index 005298b53e..caeee94289 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Custom.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.7.3-Custom.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.0-Components.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.0-Components.png index 176c4fd267..4a5f05d5ff 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.0-Components.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.0-Components.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.1-Components.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.1-Components.png index e5490c9f7c..b703993b09 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.1-Components.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.1-Components.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.2-Components.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.2-Components.png index a9494407be..218158dc43 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.2-Components.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.2-Components.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Components.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Components.png index c3760871b3..72acaeb2a8 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Components.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Components.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Custom.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Custom.png index fbd65aa25a..944b1a0270 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Custom.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.8.3-Custom.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Components.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Components.png index 5fe593ed75..2c76a9f67e 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Components.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Components.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Custom.png b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Custom.png index 8299c7b385..40e2cbe6b4 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Custom.png and b/SerialPrograms/BuildInstructions/Images/Windows-Install-Qt6.9.0-Custom.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-configure-project-qt-creator-13.png b/SerialPrograms/BuildInstructions/Images/Windows-configure-project-qt-creator-13.png index 2ed418caf8..f1d182995c 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-configure-project-qt-creator-13.png and b/SerialPrograms/BuildInstructions/Images/Windows-configure-project-qt-creator-13.png differ diff --git a/SerialPrograms/BuildInstructions/Images/Windows-configure-project.png b/SerialPrograms/BuildInstructions/Images/Windows-configure-project.png index 3bd217455f..f30fdfa43c 100644 Binary files a/SerialPrograms/BuildInstructions/Images/Windows-configure-project.png and b/SerialPrograms/BuildInstructions/Images/Windows-configure-project.png differ diff --git a/SerialPrograms/CMakeLists.txt b/SerialPrograms/CMakeLists.txt index eee2e93fdd..3b036e4032 100644 --- a/SerialPrograms/CMakeLists.txt +++ b/SerialPrograms/CMakeLists.txt @@ -1,2682 +1,2682 @@ -#set the minimum cmake version required -cmake_minimum_required(VERSION 3.18.0) - -#set the name of the project -project(SerialPrograms) - -#enable c++ 23 -set(CMAKE_CXX_STANDARD 23) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -#produce clang tidy file -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) -#set(CMAKE_VERBOSE_MAKEFILE ON) - -set(CMAKE_AUTOMOC ON) -set(CMAKE_AUTORCC ON) -set(CMAKE_AUTOUIC ON) - -add_custom_target(build-time-make-directory ALL - COMMAND ${CMAKE_COMMAND} -E make_directory Assembly/) - -#Find threads library -set(THREADS_PREFER_PTHREAD_FLAG ON) -find_package(Threads REQUIRED) - -#find Qt -if(NOT QT_MAJOR) - set(QT_MAJOR 6) -endif() -find_package(Qt${QT_MAJOR} COMPONENTS Widgets SerialPort Multimedia MultimediaWidgets REQUIRED) -#disable deprecated Qt APIs -add_compile_definitions(QT_DISABLE_DEPRECATED_BEFORE=0x050F00) - -#add current directory to find tesseractPA.lib -link_directories(${CMAKE_CURRENT_LIST_DIR}) - -file(GLOB MAIN_SOURCES - ../3rdParty/ONNX/OnnxToolsPA.h - ../3rdParty/QtWavFile/WavFile.cpp - ../3rdParty/QtWavFile/WavFile.h - ../3rdParty/TesseractPA/TesseractPA.cpp - ../3rdParty/TesseractPA/TesseractPA.h - ../3rdParty/qdarkstyle/dark/darkstyle.qrc - ../ClientSource/Connection/BotBase.cpp - ../ClientSource/Connection/BotBase.h - ../ClientSource/Connection/BotBaseMessage.h - ../ClientSource/Connection/MessageLogger.cpp - ../ClientSource/Connection/MessageLogger.h - ../ClientSource/Connection/MessageSniffer.h - ../ClientSource/Connection/PABotBase.cpp - ../ClientSource/Connection/PABotBase.h - ../ClientSource/Connection/PABotBaseConnection.cpp - ../ClientSource/Connection/PABotBaseConnection.h - ../ClientSource/Connection/SerialConnection.h - ../ClientSource/Connection/SerialConnectionPOSIX.h - ../ClientSource/Connection/SerialConnectionWinAPI.h - ../ClientSource/Connection/StreamInterface.h - ../ClientSource/Libraries/Logging.cpp - ../ClientSource/Libraries/Logging.h - ../ClientSource/Libraries/MessageConverter.cpp - ../ClientSource/Libraries/MessageConverter.h - ../Common/CRC32.cpp - ../Common/CRC32.h - ../Common/Compiler.h - ../Common/Cpp/AbstractLogger.h - ../Common/Cpp/CancellableScope.cpp - ../Common/Cpp/CancellableScope.h - ../Common/Cpp/Color.cpp - ../Common/Cpp/Color.h - ../Common/Cpp/Concurrency/AsyncDispatcher.cpp - ../Common/Cpp/Concurrency/AsyncDispatcher.h - ../Common/Cpp/Concurrency/FireForgetDispatcher.cpp - ../Common/Cpp/Concurrency/FireForgetDispatcher.h - ../Common/Cpp/Concurrency/ParallelTaskRunner.cpp - ../Common/Cpp/Concurrency/ParallelTaskRunner.h - ../Common/Cpp/Concurrency/PeriodicScheduler.cpp - ../Common/Cpp/Concurrency/PeriodicScheduler.h - ../Common/Cpp/Concurrency/ReverseLockGuard.h - ../Common/Cpp/Concurrency/ScheduledTaskRunner.cpp - ../Common/Cpp/Concurrency/ScheduledTaskRunner.h - ../Common/Cpp/Concurrency/SpinLock.cpp - ../Common/Cpp/Concurrency/SpinLock.h - ../Common/Cpp/Concurrency/SpinPause.h - ../Common/Cpp/Concurrency/Watchdog.cpp - ../Common/Cpp/Concurrency/Watchdog.h - ../Common/Cpp/Containers/AlignedMalloc.cpp - ../Common/Cpp/Containers/AlignedMalloc.h - ../Common/Cpp/Containers/AlignedVector.h - ../Common/Cpp/Containers/AlignedVector.tpp - ../Common/Cpp/Containers/BoxSet.h - ../Common/Cpp/Containers/CircularBuffer.h - ../Common/Cpp/Containers/DllSafeString.h - ../Common/Cpp/Containers/FixedLimitVector.h - ../Common/Cpp/Containers/FixedLimitVector.tpp - ../Common/Cpp/Containers/Pimpl.h - ../Common/Cpp/Containers/Pimpl.tpp - ../Common/Cpp/Containers/SparseArray.cpp - ../Common/Cpp/Containers/SparseArray.h - ../Common/Cpp/CpuId/CpuId.cpp - ../Common/Cpp/CpuId/CpuId.h - ../Common/Cpp/CpuId/CpuId_arm64.h - ../Common/Cpp/CpuId/CpuId_arm64.tpp - ../Common/Cpp/CpuId/CpuId_x86.h - ../Common/Cpp/CpuId/CpuId_x86.tpp - ../Common/Cpp/DateTime.h - ../Common/Cpp/EnumStringMap.h - ../Common/Cpp/EventRateTracker.h - ../Common/Cpp/Exceptions.cpp - ../Common/Cpp/Exceptions.h - ../Common/Cpp/ExpressionEvaluator.cpp - ../Common/Cpp/ExpressionEvaluator.h - ../Common/Cpp/ImageResolution.cpp - ../Common/Cpp/ImageResolution.h - ../Common/Cpp/Json/JsonArray.cpp - ../Common/Cpp/Json/JsonArray.h - ../Common/Cpp/Json/JsonObject.cpp - ../Common/Cpp/Json/JsonObject.h - ../Common/Cpp/Json/JsonTools.cpp - ../Common/Cpp/Json/JsonTools.h - ../Common/Cpp/Json/JsonValue.cpp - ../Common/Cpp/Json/JsonValue.h - ../Common/Cpp/LifetimeSanitizer.cpp - ../Common/Cpp/LifetimeSanitizer.h - ../Common/Cpp/ListenerSet.h - ../Common/Cpp/Options/BatchOption.cpp - ../Common/Cpp/Options/BatchOption.h - ../Common/Cpp/Options/BooleanCheckBoxOption.cpp - ../Common/Cpp/Options/BooleanCheckBoxOption.h - ../Common/Cpp/Options/ButtonOption.cpp - ../Common/Cpp/Options/ButtonOption.h - ../Common/Cpp/Options/ColorOption.cpp - ../Common/Cpp/Options/ColorOption.h - ../Common/Cpp/Options/ConfigOption.cpp - ../Common/Cpp/Options/ConfigOption.h - ../Common/Cpp/Options/DateOption.cpp - ../Common/Cpp/Options/DateOption.h - ../Common/Cpp/Options/EditableTableOption.cpp - ../Common/Cpp/Options/EditableTableOption.h - ../Common/Cpp/Options/EnumDropdownDatabase.cpp - ../Common/Cpp/Options/EnumDropdownDatabase.h - ../Common/Cpp/Options/EnumDropdownOption.cpp - ../Common/Cpp/Options/EnumDropdownOption.h - ../Common/Cpp/Options/FixedCodeOption.cpp - ../Common/Cpp/Options/FixedCodeOption.h - ../Common/Cpp/Options/FloatingPointOption.cpp - ../Common/Cpp/Options/FloatingPointOption.h - ../Common/Cpp/Options/GroupOption.cpp - ../Common/Cpp/Options/GroupOption.h - ../Common/Cpp/Options/IntegerRangeOption.cpp - ../Common/Cpp/Options/IntegerRangeOption.h - ../Common/Cpp/Options/KeyBindingOption.cpp - ../Common/Cpp/Options/KeyBindingOption.h - ../Common/Cpp/Options/MacAddressOption.cpp - ../Common/Cpp/Options/MacAddressOption.h - ../Common/Cpp/Options/RandomCodeOption.cpp - ../Common/Cpp/Options/RandomCodeOption.h - ../Common/Cpp/Options/SimpleIntegerOption.cpp - ../Common/Cpp/Options/SimpleIntegerOption.h - ../Common/Cpp/Options/StaticTableOption.cpp - ../Common/Cpp/Options/StaticTableOption.h - ../Common/Cpp/Options/StaticTextOption.cpp - ../Common/Cpp/Options/StaticTextOption.h - ../Common/Cpp/Options/StringOption.cpp - ../Common/Cpp/Options/StringOption.h - ../Common/Cpp/Options/TextEditOption.cpp - ../Common/Cpp/Options/TextEditOption.h - ../Common/Cpp/Options/TimeDurationOption.cpp - ../Common/Cpp/Options/TimeDurationOption.h - ../Common/Cpp/Options/TimeExpressionOption.cpp - ../Common/Cpp/Options/TimeExpressionOption.h - ../Common/Cpp/PanicDump.cpp - ../Common/Cpp/PanicDump.h - ../Common/Cpp/PixelRGB32.h - ../Common/Cpp/PrettyPrint.cpp - ../Common/Cpp/PrettyPrint.h - ../Common/Cpp/PrintDebuggers.h - ../Common/Cpp/Rectangle.h - ../Common/Cpp/Rectangle.tpp - ../Common/Cpp/RecursiveThrottler.h - ../Common/Cpp/SIMDDebuggers.h - ../Common/Cpp/Sockets/AbstractClientSocket.h - ../Common/Cpp/Sockets/ClientSocket.cpp - ../Common/Cpp/Sockets/ClientSocket.h - ../Common/Cpp/Sockets/ClientSocket_POSIX.h - ../Common/Cpp/Sockets/ClientSocket_WinSocket.h - ../Common/Cpp/StreamConverters.cpp - ../Common/Cpp/StreamConverters.h - ../Common/Cpp/StringTools.cpp - ../Common/Cpp/StringTools.h - ../Common/Cpp/Time.cpp - ../Common/Cpp/Time.h - ../Common/Cpp/Unicode.cpp - ../Common/Cpp/Unicode.h - ../Common/Cpp/ValueDebouncer.h - ../Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h - ../Common/NintendoSwitch/NintendoSwitch_Protocol_PushButtons.h - ../Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h - ../Common/PokemonSwSh/PokemonSwSh_FossilTable.h - ../Common/PokemonSwSh/PokemonSwSh_MultiHostTable.cpp - ../Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h - ../Common/PokemonSwSh/PokemonSwSh_Protocol_DaySkippers.h - ../Common/Qt/AutoHeightTable.cpp - ../Common/Qt/AutoHeightTable.h - ../Common/Qt/AutoWidthLineEdit.cpp - ../Common/Qt/AutoWidthLineEdit.h - ../Common/Qt/CodeValidator.cpp - ../Common/Qt/CodeValidator.h - ../Common/Qt/CollapsibleGroupBox.cpp - ../Common/Qt/CollapsibleGroupBox.h - ../Common/Qt/NoWheelComboBox.h - ../Common/Qt/Options/BatchWidget.cpp - ../Common/Qt/Options/BatchWidget.h - ../Common/Qt/Options/BooleanCheckBoxWidget.cpp - ../Common/Qt/Options/BooleanCheckBoxWidget.h - ../Common/Qt/Options/ButtonWidget.cpp - ../Common/Qt/Options/ButtonWidget.h - ../Common/Qt/Options/ColorWidget.cpp - ../Common/Qt/Options/ColorWidget.h - ../Common/Qt/Options/ConfigWidget.cpp - ../Common/Qt/Options/ConfigWidget.h - ../Common/Qt/Options/DateWidget.cpp - ../Common/Qt/Options/DateWidget.h - ../Common/Qt/Options/EditableTableWidget.cpp - ../Common/Qt/Options/EditableTableWidget.h - ../Common/Qt/Options/EnumDropdownWidget.cpp - ../Common/Qt/Options/EnumDropdownWidget.h - ../Common/Qt/Options/FixedCodeWidget.cpp - ../Common/Qt/Options/FixedCodeWidget.h - ../Common/Qt/Options/FloatingPointWidget.cpp - ../Common/Qt/Options/FloatingPointWidget.h - ../Common/Qt/Options/GroupWidget.cpp - ../Common/Qt/Options/GroupWidget.h - ../Common/Qt/Options/IntegerRangeWidget.cpp - ../Common/Qt/Options/IntegerRangeWidget.h - ../Common/Qt/Options/KeyBindingWidget.cpp - ../Common/Qt/Options/KeyBindingWidget.h - ../Common/Qt/Options/MacAddressWidget.cpp - ../Common/Qt/Options/MacAddressWidget.h - ../Common/Qt/Options/RandomCodeWidget.cpp - ../Common/Qt/Options/RandomCodeWidget.h - ../Common/Qt/Options/SimpleIntegerWidget.cpp - ../Common/Qt/Options/SimpleIntegerWidget.h - ../Common/Qt/Options/StaticTableWidget.cpp - ../Common/Qt/Options/StaticTableWidget.h - ../Common/Qt/Options/StaticTextWidget.cpp - ../Common/Qt/Options/StaticTextWidget.h - ../Common/Qt/Options/StringWidget.cpp - ../Common/Qt/Options/StringWidget.h - ../Common/Qt/Options/TextEditWidget.cpp - ../Common/Qt/Options/TextEditWidget.h - ../Common/Qt/Options/TimeDurationWidget.cpp - ../Common/Qt/Options/TimeDurationWidget.h - ../Common/Qt/Options/TimeExpressionWidget.cpp - ../Common/Qt/Options/TimeExpressionWidget.h - ../Common/Qt/Redispatch.cpp - ../Common/Qt/Redispatch.h - ../Common/Qt/StringToolsQt.cpp - ../Common/Qt/StringToolsQt.h - ../Common/Qt/TimeQt.cpp - ../Common/Qt/TimeQt.h - ../Common/Qt/WidgetStackFixedAspectRatio.cpp - ../Common/Qt/WidgetStackFixedAspectRatio.h - ../Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h - ../Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h - ../Common/SerialPABotBase/SerialPABotBase_Protocol.h - ../Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h - ../IconResource/IconResource.rc - Source/CommonFramework/AudioPipeline/AudioConstants.h - Source/CommonFramework/AudioPipeline/AudioFeed.h - Source/CommonFramework/AudioPipeline/AudioInfo.cpp - Source/CommonFramework/AudioPipeline/AudioInfo.h - Source/CommonFramework/AudioPipeline/AudioNormalization.h - Source/CommonFramework/AudioPipeline/AudioOption.cpp - Source/CommonFramework/AudioPipeline/AudioOption.h - Source/CommonFramework/AudioPipeline/AudioPassthroughPair.h - Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h - Source/CommonFramework/AudioPipeline/AudioSession.cpp - Source/CommonFramework/AudioPipeline/AudioSession.h - Source/CommonFramework/AudioPipeline/AudioStream.cpp - Source/CommonFramework/AudioPipeline/AudioStream.h - Source/CommonFramework/AudioPipeline/AudioTemplate.cpp - Source/CommonFramework/AudioPipeline/AudioTemplate.h - Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.cpp - Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.h - Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp - Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.h - Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.cpp - Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.h - Source/CommonFramework/AudioPipeline/IO/AudioSink.cpp - Source/CommonFramework/AudioPipeline/IO/AudioSink.h - Source/CommonFramework/AudioPipeline/IO/AudioSource.cpp - Source/CommonFramework/AudioPipeline/IO/AudioSource.h - Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.cpp - Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.h - Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.cpp - Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h - Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.cpp - Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.h - Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.cpp - Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h - Source/CommonFramework/AudioPipeline/Tools/AudioNormalization.h - Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.cpp - Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.h - Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.cpp - Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.h - Source/CommonFramework/AudioPipeline/Tools/TimeSampleWriter.h - Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.cpp - Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h - Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.cpp - Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h - Source/CommonFramework/Environment/Environment.cpp - Source/CommonFramework/Environment/Environment.h - Source/CommonFramework/Environment/Environment_Linux.h - Source/CommonFramework/Environment/Environment_Linux.tpp - Source/CommonFramework/Environment/Environment_Windows.h - Source/CommonFramework/Environment/Environment_Windows.tpp - Source/CommonFramework/Environment/Environment_arm64_Linux.tpp - Source/CommonFramework/Environment/Environment_x86.tpp - Source/CommonFramework/Environment/Environment_x86_Linux.tpp - Source/CommonFramework/Environment/Environment_x86_Windows.tpp - Source/CommonFramework/Environment/HardwareValidation.cpp - Source/CommonFramework/Environment/HardwareValidation.h - Source/CommonFramework/Environment/HardwareValidation_arm64.tpp - Source/CommonFramework/Environment/HardwareValidation_x86.tpp - Source/CommonFramework/Environment/SystemSleep.cpp - Source/CommonFramework/Environment/SystemSleep.h - Source/CommonFramework/Environment/SystemSleep_Apple.tpp - Source/CommonFramework/Environment/SystemSleep_Windows.tpp - Source/CommonFramework/ErrorReports/ErrorReports.cpp - Source/CommonFramework/ErrorReports/ErrorReports.h - Source/CommonFramework/ErrorReports/ProgramDumper.cpp - Source/CommonFramework/ErrorReports/ProgramDumper.h - Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp - Source/CommonFramework/Exceptions/FatalProgramException.h - Source/CommonFramework/Exceptions/OperationFailedException.h - Source/CommonFramework/Exceptions/ProgramFinishedException.cpp - Source/CommonFramework/Exceptions/ProgramFinishedException.h - Source/CommonFramework/Exceptions/ScreenshotException.cpp - Source/CommonFramework/Exceptions/ScreenshotException.h - Source/CommonFramework/Exceptions/UnexpectedBattleException.h - Source/CommonFramework/GlobalServices.cpp - Source/CommonFramework/GlobalServices.h - Source/CommonFramework/GlobalSettingsPanel.cpp - Source/CommonFramework/GlobalSettingsPanel.h - Source/CommonFramework/Globals.cpp - Source/CommonFramework/Globals.h - Source/CommonFramework/ImageTools/FloatPixel.cpp - Source/CommonFramework/ImageTools/FloatPixel.h - Source/CommonFramework/ImageTools/ImageBoxes.cpp - Source/CommonFramework/ImageTools/ImageBoxes.h - Source/CommonFramework/ImageTools/ImageDiff.cpp - Source/CommonFramework/ImageTools/ImageDiff.h - Source/CommonFramework/ImageTools/ImageStats.cpp - Source/CommonFramework/ImageTools/ImageStats.h - Source/CommonFramework/ImageTypes/BinaryImage.cpp - Source/CommonFramework/ImageTypes/BinaryImage.h - Source/CommonFramework/ImageTypes/ImageHSV32.cpp - Source/CommonFramework/ImageTypes/ImageHSV32.h - Source/CommonFramework/ImageTypes/ImageRGB32.cpp - Source/CommonFramework/ImageTypes/ImageRGB32.h - Source/CommonFramework/ImageTypes/ImageViewHSV32.cpp - Source/CommonFramework/ImageTypes/ImageViewHSV32.h - Source/CommonFramework/ImageTypes/ImageViewPlanar32.cpp - Source/CommonFramework/ImageTypes/ImageViewPlanar32.h - Source/CommonFramework/ImageTypes/ImageViewRGB32.cpp - Source/CommonFramework/ImageTypes/ImageViewRGB32.h - Source/CommonFramework/Language.cpp - Source/CommonFramework/Language.h - Source/CommonFramework/Logging/FileWindowLogger.cpp - Source/CommonFramework/Logging/FileWindowLogger.h - Source/CommonFramework/Logging/Logger.cpp - Source/CommonFramework/Logging/Logger.h - Source/CommonFramework/Logging/OutputRedirector.cpp - Source/CommonFramework/Logging/OutputRedirector.h - Source/CommonFramework/Logging/QueuedLogger.cpp - Source/CommonFramework/Logging/QueuedLogger.h - Source/CommonFramework/Main.cpp - Source/CommonFramework/Notifications/EventNotificationOption.cpp - Source/CommonFramework/Notifications/EventNotificationOption.h - Source/CommonFramework/Notifications/EventNotificationsTable.cpp - Source/CommonFramework/Notifications/EventNotificationsTable.h - Source/CommonFramework/Notifications/MessageAttachment.cpp - Source/CommonFramework/Notifications/MessageAttachment.h - Source/CommonFramework/Notifications/ProgramInfo.h - Source/CommonFramework/Notifications/ProgramNotifications.cpp - Source/CommonFramework/Notifications/ProgramNotifications.h - Source/CommonFramework/Notifications/SenderNotificationTable.cpp - Source/CommonFramework/Notifications/SenderNotificationTable.h - Source/CommonFramework/Options/CheckForUpdatesOption.h - Source/CommonFramework/Options/Environment/PerformanceOptions.h - Source/CommonFramework/Options/Environment/ProcessPriorityOption.h - Source/CommonFramework/Options/Environment/ProcessorLevelOption.cpp - Source/CommonFramework/Options/Environment/ProcessorLevelOption.h - Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp - Source/CommonFramework/Options/Environment/SleepSuppressOption.h - Source/CommonFramework/Options/Environment/ThemeSelectorOption.cpp - Source/CommonFramework/Options/Environment/ThemeSelectorOption.h - Source/CommonFramework/Options/LabelCellOption.cpp - Source/CommonFramework/Options/LabelCellOption.h - Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp - Source/CommonFramework/Options/QtWidget/LabelCellWidget.h - Source/CommonFramework/Options/ResolutionOption.cpp - Source/CommonFramework/Options/ResolutionOption.h - Source/CommonFramework/Options/ScreenshotFormatOption.h - Source/CommonFramework/Panels/PanelDescriptor.cpp - Source/CommonFramework/Panels/PanelDescriptor.h - Source/CommonFramework/Panels/PanelInstance.cpp - Source/CommonFramework/Panels/PanelInstance.h - Source/CommonFramework/Panels/PanelList.cpp - Source/CommonFramework/Panels/PanelList.h - Source/CommonFramework/Panels/PanelTools.h - Source/CommonFramework/Panels/ProgramDescriptor.cpp - Source/CommonFramework/Panels/ProgramDescriptor.h - Source/CommonFramework/Panels/SettingsPanel.cpp - Source/CommonFramework/Panels/SettingsPanel.h - Source/CommonFramework/Panels/UI/PanelElements.cpp - Source/CommonFramework/Panels/UI/PanelElements.h - Source/CommonFramework/Panels/UI/PanelListWidget.cpp - Source/CommonFramework/Panels/UI/PanelListWidget.h - Source/CommonFramework/Panels/UI/PanelWidget.cpp - Source/CommonFramework/Panels/UI/PanelWidget.h - Source/CommonFramework/Panels/UI/SettingsPanelWidget.cpp - Source/CommonFramework/Panels/UI/SettingsPanelWidget.h - Source/CommonFramework/PersistentSettings.cpp - Source/CommonFramework/PersistentSettings.h - Source/CommonFramework/ProgramSession.cpp - Source/CommonFramework/ProgramSession.h - Source/CommonFramework/ProgramStats/StatsDatabase.cpp - Source/CommonFramework/ProgramStats/StatsDatabase.h - Source/CommonFramework/ProgramStats/StatsTracking.cpp - Source/CommonFramework/ProgramStats/StatsTracking.h - Source/CommonFramework/Recording/StreamHistoryOption.cpp - Source/CommonFramework/Recording/StreamHistoryOption.h - Source/CommonFramework/Recording/StreamHistorySession.cpp - Source/CommonFramework/Recording/StreamHistorySession.h - Source/CommonFramework/Recording/StreamHistoryTracker_Null.h - Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h - Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h - Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h - Source/CommonFramework/Recording/StreamRecorder.cpp - Source/CommonFramework/Recording/StreamRecorder.h - Source/CommonFramework/Startup/NewVersionCheck.cpp - Source/CommonFramework/Startup/NewVersionCheck.h - Source/CommonFramework/Startup/SetupSettings.cpp - Source/CommonFramework/Startup/SetupSettings.h - Source/CommonFramework/Tools/DebugDumper.cpp - Source/CommonFramework/Tools/DebugDumper.h - Source/CommonFramework/Tools/ErrorDumper.cpp - Source/CommonFramework/Tools/ErrorDumper.h - Source/CommonFramework/Tools/FileDownloader.cpp - Source/CommonFramework/Tools/FileDownloader.h - Source/CommonFramework/Tools/ProgramEnvironment.cpp - Source/CommonFramework/Tools/ProgramEnvironment.h - Source/CommonFramework/Tools/StatAccumulator.cpp - Source/CommonFramework/Tools/StatAccumulator.h - Source/CommonFramework/Tools/VideoStream.cpp - Source/CommonFramework/Tools/VideoStream.h - Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.cpp - Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.h - Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp - Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h - Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp - Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h - Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp - Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h - Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h - Source/CommonFramework/VideoPipeline/CameraInfo.h - Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h - Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp - Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h - Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.cpp - Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h - Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp - Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.h - Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp - Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h - Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp - Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h - Source/CommonFramework/VideoPipeline/VideoFeed.h - Source/CommonFramework/VideoPipeline/VideoOverlay.cpp - Source/CommonFramework/VideoPipeline/VideoOverlay.h - Source/CommonFramework/VideoPipeline/VideoOverlayOption.cpp - Source/CommonFramework/VideoPipeline/VideoOverlayOption.h - Source/CommonFramework/VideoPipeline/VideoOverlayScopes.h - Source/CommonFramework/VideoPipeline/VideoOverlaySession.cpp - Source/CommonFramework/VideoPipeline/VideoOverlaySession.h - Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp - Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h - Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h - Source/CommonFramework/VideoPipeline/VideoSession.cpp - Source/CommonFramework/VideoPipeline/VideoSession.h - Source/CommonFramework/VideoPipeline/VideoSource.cpp - Source/CommonFramework/VideoPipeline/VideoSource.h - Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp - Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h - Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp - Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h - Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp - Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h - Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp - Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h - Source/CommonFramework/Windows/ButtonDiagram.cpp - Source/CommonFramework/Windows/ButtonDiagram.h - Source/CommonFramework/Windows/DpiScaler.cpp - Source/CommonFramework/Windows/DpiScaler.h - Source/CommonFramework/Windows/MainWindow.cpp - Source/CommonFramework/Windows/MainWindow.h - Source/CommonFramework/Windows/WindowTracker.cpp - Source/CommonFramework/Windows/WindowTracker.h - Source/CommonTools/Async/InferenceRoutines.cpp - Source/CommonTools/Async/InferenceRoutines.h - Source/CommonTools/Async/InferenceSession.cpp - Source/CommonTools/Async/InferenceSession.h - Source/CommonTools/Async/InterruptableCommands.h - Source/CommonTools/Async/InterruptableCommands.tpp - Source/CommonTools/Async/SuperControlSession.h - Source/CommonTools/Async/SuperControlSession.tpp - Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp - Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h - Source/CommonTools/Audio/AudioTemplateCache.cpp - Source/CommonTools/Audio/AudioTemplateCache.h - Source/CommonTools/Audio/SpectrogramMatcher.cpp - Source/CommonTools/Audio/SpectrogramMatcher.h - Source/CommonTools/DetectionDebouncer.h - Source/CommonTools/FailureWatchdog.h - Source/CommonTools/GlobalInferenceRunner.cpp - Source/CommonTools/GlobalInferenceRunner.h - Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp - Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h - Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp - Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h - Source/CommonTools/ImageMatch/ExactImageMatcher.cpp - Source/CommonTools/ImageMatch/ExactImageMatcher.h - Source/CommonTools/ImageMatch/FilterToAlpha.cpp - Source/CommonTools/ImageMatch/FilterToAlpha.h - Source/CommonTools/ImageMatch/ImageCropper.cpp - Source/CommonTools/ImageMatch/ImageCropper.h - Source/CommonTools/ImageMatch/ImageMatchOption.cpp - Source/CommonTools/ImageMatch/ImageMatchOption.h - Source/CommonTools/ImageMatch/ImageMatchResult.cpp - Source/CommonTools/ImageMatch/ImageMatchResult.h - Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp - Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h - Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp - Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h - Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp - Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h - Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp - Source/CommonTools/Images/BinaryImage_FilterRgb32.h - Source/CommonTools/Images/ColorClustering.cpp - Source/CommonTools/Images/ColorClustering.h - Source/CommonTools/Images/DistanceToLine.h - Source/CommonTools/Images/ImageFilter.cpp - Source/CommonTools/Images/ImageFilter.h - Source/CommonTools/Images/ImageGradient.cpp - Source/CommonTools/Images/ImageGradient.h - Source/CommonTools/Images/ImageManip.cpp - Source/CommonTools/Images/ImageManip.h - Source/CommonTools/Images/ImageTools.cpp - Source/CommonTools/Images/ImageTools.h - Source/CommonTools/Images/SolidColorTest.cpp - Source/CommonTools/Images/SolidColorTest.h - Source/CommonTools/Images/WaterfillUtilities.cpp - Source/CommonTools/Images/WaterfillUtilities.h - Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h - Source/CommonTools/InferenceCallbacks/InferenceCallback.h - Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp - Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h - Source/CommonTools/InferencePivots/AudioInferencePivot.cpp - Source/CommonTools/InferencePivots/AudioInferencePivot.h - Source/CommonTools/InferencePivots/VisualInferencePivot.cpp - Source/CommonTools/InferencePivots/VisualInferencePivot.h - Source/CommonTools/InferenceThrottler.h - Source/CommonTools/MultiConsoleErrors.cpp - Source/CommonTools/MultiConsoleErrors.h - Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp - Source/CommonTools/OCR/OCR_DictionaryMatcher.h - Source/CommonTools/OCR/OCR_DictionaryOCR.cpp - Source/CommonTools/OCR/OCR_DictionaryOCR.h - Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp - Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h - Source/CommonTools/OCR/OCR_NumberReader.cpp - Source/CommonTools/OCR/OCR_NumberReader.h - Source/CommonTools/OCR/OCR_RawOCR.cpp - Source/CommonTools/OCR/OCR_RawOCR.h - Source/CommonTools/OCR/OCR_Routines.cpp - Source/CommonTools/OCR/OCR_Routines.h - Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp - Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h - Source/CommonTools/OCR/OCR_StringMatchResult.cpp - Source/CommonTools/OCR/OCR_StringMatchResult.h - Source/CommonTools/OCR/OCR_StringNormalization.cpp - Source/CommonTools/OCR/OCR_StringNormalization.h - Source/CommonTools/OCR/OCR_TextMatcher.cpp - Source/CommonTools/OCR/OCR_TextMatcher.h - Source/CommonTools/OCR/OCR_TrainingTools.cpp - Source/CommonTools/OCR/OCR_TrainingTools.h - Source/CommonTools/Options/LanguageOCROption.cpp - Source/CommonTools/Options/LanguageOCROption.h - Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp - Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h - Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp - Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h - Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp - Source/CommonTools/Options/QtWidgets/StringSelectWidget.h - Source/CommonTools/Options/ScreenWatchOption.cpp - Source/CommonTools/Options/ScreenWatchOption.h - Source/CommonTools/Options/StringSelectOption.cpp - Source/CommonTools/Options/StringSelectOption.h - Source/CommonTools/Options/StringSelectTableOption.h - Source/CommonTools/Options/TrainOCRModeOption.h - Source/CommonTools/Resources/SpriteDatabase.cpp - Source/CommonTools/Resources/SpriteDatabase.h - Source/CommonTools/StartupChecks/StartProgramChecks.cpp - Source/CommonTools/StartupChecks/StartProgramChecks.h - Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp - Source/CommonTools/StartupChecks/VideoResolutionCheck.h - Source/CommonTools/TrendInference/AnomalyDetector.cpp - Source/CommonTools/TrendInference/AnomalyDetector.h - Source/CommonTools/TrendInference/TimeWindowStatTracker.h - Source/CommonTools/VisualDetector.h - Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp - Source/CommonTools/VisualDetectors/BlackBorderDetector.h - Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp - Source/CommonTools/VisualDetectors/BlackScreenDetector.h - Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp - Source/CommonTools/VisualDetectors/FrozenImageDetector.h - Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp - Source/CommonTools/VisualDetectors/ImageMatchDetector.h - Source/ComputerPrograms/ComputerProgram.cpp - Source/ComputerPrograms/ComputerProgram.h - Source/ComputerPrograms/Framework/ComputerProgramOption.cpp - Source/ComputerPrograms/Framework/ComputerProgramOption.h - Source/ComputerPrograms/Framework/ComputerProgramSession.cpp - Source/ComputerPrograms/Framework/ComputerProgramSession.h - Source/ComputerPrograms/Framework/ComputerProgramWidget.cpp - Source/ComputerPrograms/Framework/ComputerProgramWidget.h - Source/Controllers/Controller.h - Source/Controllers/ControllerCapability.cpp - Source/Controllers/ControllerCapability.h - Source/Controllers/ControllerConnection.cpp - Source/Controllers/ControllerConnection.h - Source/Controllers/ControllerDescriptor.cpp - Source/Controllers/ControllerDescriptor.h - Source/Controllers/ControllerSelectorWidget.cpp - Source/Controllers/ControllerSelectorWidget.h - Source/Controllers/ControllerSession.cpp - Source/Controllers/ControllerSession.h - Source/Controllers/ControllerTypeStrings.cpp - Source/Controllers/ControllerTypeStrings.h - Source/Controllers/ControllerTypes.h - Source/Controllers/JoystickTools.h - Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp - Source/Controllers/KeyboardInput/GlobalQtKeyMap.h - Source/Controllers/KeyboardInput/KeyboardInput.cpp - Source/Controllers/KeyboardInput/KeyboardInput.h - Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp - Source/Controllers/KeyboardInput/KeyboardStateTracker.h - Source/Controllers/NullController.cpp - Source/Controllers/NullController.h - Source/Controllers/SerialPABotBase/SerialPABotBase.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase.h - Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h - Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h - Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h - Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h - Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h - Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp - Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h - Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h - Source/Controllers/SuperscalarScheduler.cpp - Source/Controllers/SuperscalarScheduler.h - Source/Integrations/DiscordIntegrationSettings.cpp - Source/Integrations/DiscordIntegrationSettings.h - Source/Integrations/DiscordIntegrationTable.cpp - Source/Integrations/DiscordIntegrationTable.h - Source/Integrations/DiscordSettingsOption.cpp - Source/Integrations/DiscordSettingsOption.h - Source/Integrations/DiscordWebhook.cpp - Source/Integrations/DiscordWebhook.h - Source/Integrations/DiscordWebhookSettings.cpp - Source/Integrations/DiscordWebhookSettings.h - Source/Integrations/DppIntegration/DppClient.cpp - Source/Integrations/DppIntegration/DppClient.h - Source/Integrations/DppIntegration/DppCommandHandler.cpp - Source/Integrations/DppIntegration/DppCommandHandler.h - Source/Integrations/DppIntegration/DppUtility.cpp - Source/Integrations/DppIntegration/DppUtility.h - Source/Integrations/IntegrationsAPI.cpp - Source/Integrations/IntegrationsAPI.h - Source/Integrations/ProgramTracker.cpp - Source/Integrations/ProgramTracker.h - Source/Integrations/SleepyDiscordRunner.cpp - Source/Integrations/SleepyDiscordRunner.h - Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp - Source/Kernels/AbsFFT/Kernels_AbsFFT.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_Default.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_AVX2.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_SSE41.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_AVX2.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_SSE41.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_BitReverse.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_Butterflies.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexScalar.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexToAbs.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexVector.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_Default.cpp - Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp - Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp - Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.tpp - Source/Kernels/AbsFFT/Kernels_AbsFFT_Reductions.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.h - Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.tpp - Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.cpp - Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h - Source/Kernels/AudioStreamConversion/AudioStreamConversion.cpp - Source/Kernels/AudioStreamConversion/AudioStreamConversion.h - Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_Default.cpp - Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x4_Default.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_arm64_NEON.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Routines.h - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h - Source/Kernels/BinaryImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x16_x64_AVX2.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x32_x64_AVX512.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x64_x64_AVX512.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_x64_SSE42.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_Debugging.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x4_Default.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64xH_Default.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_arm64_NEON.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h - Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrix.h - Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h - Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.tpp - Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h - Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.tpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Default.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_Default.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_arm64_NEON.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.h - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_Default.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_Default.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp - Source/Kernels/Kernels_Alignment.h - Source/Kernels/Kernels_BitScan.h - Source/Kernels/Kernels_BitSet.h - Source/Kernels/Kernels_arm64_NEON.h - Source/Kernels/Kernels_x64_AVX2.h - Source/Kernels/Kernels_x64_AVX512.h - Source/Kernels/Kernels_x64_SSE41.h - Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h - Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h - Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_Default.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Routines.h - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.h - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_Default.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Routines.h - Source/Kernels/Waterfill/Kernels_Waterfill.cpp - Source/Kernels/Waterfill/Kernels_Waterfill.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h - Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h - Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h - Source/Kernels/Waterfill/Kernels_Waterfill_Routines.h - Source/Kernels/Waterfill/Kernels_Waterfill_Session.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Session.h - Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp - Source/Kernels/Waterfill/Kernels_Waterfill_Types.h - Source/ML/DataLabeling/SegmentAnythingModel.cpp - Source/ML/DataLabeling/SegmentAnythingModel.h - Source/ML/ML_Panels.cpp - Source/ML/ML_Panels.h - Source/ML/Programs/ML_LabelImages.cpp - Source/ML/Programs/ML_LabelImages.h - Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp - Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h - Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp - Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h - Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp - Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h - Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h - Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h - Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h - Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h - Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h - Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h - Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp - Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp - Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h - Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h - Source/NintendoSwitch/DevPrograms/BoxDraw.cpp - Source/NintendoSwitch/DevPrograms/BoxDraw.h - Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp - Source/NintendoSwitch/DevPrograms/JoyconProgram.h - Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp - Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h - Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp - Source/NintendoSwitch/DevPrograms/TestProgramComputer.h - Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp - Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h - Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h - Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h - Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h - Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.cpp - Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h - Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp - Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h - Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp - Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.h - Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.cpp - Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h - Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp - Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h - Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp - Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h - Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.h - Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h - Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp - Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h - Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp - Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h - Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp - Source/NintendoSwitch/NintendoSwitch_ConsoleState.h - Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp - Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h - Source/NintendoSwitch/NintendoSwitch_Panels.cpp - Source/NintendoSwitch/NintendoSwitch_Panels.h - Source/NintendoSwitch/NintendoSwitch_Settings.cpp - Source/NintendoSwitch/NintendoSwitch_Settings.h - Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp - Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h - Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp - Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h - Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.cpp - Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h - Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.cpp - Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h - Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h - Source/NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h - Source/NintendoSwitch/Options/TurboMacroTable.cpp - Source/NintendoSwitch/Options/TurboMacroTable.h - Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.cpp - Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.h - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp - Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp - Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp - Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp - Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h - Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp - Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h - Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp - Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h - Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h - Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.h - Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h - Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h - Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.h - Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.h - Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.h - Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.h - Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.h - Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.h - Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.h - Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.cpp - Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.h - Source/PanelLists.cpp - Source/PanelLists.h - Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp - Source/Pokemon/Inference/Pokemon_BerryNameReader.h - Source/Pokemon/Inference/Pokemon_BoxGenderDetector.cpp - Source/Pokemon/Inference/Pokemon_BoxGenderDetector.h - Source/Pokemon/Inference/Pokemon_IvJudgeReader.cpp - Source/Pokemon/Inference/Pokemon_IvJudgeReader.h - Source/Pokemon/Inference/Pokemon_NameReader.cpp - Source/Pokemon/Inference/Pokemon_NameReader.h - Source/Pokemon/Inference/Pokemon_NatureReader.cpp - Source/Pokemon/Inference/Pokemon_NatureReader.h - Source/Pokemon/Inference/Pokemon_PokeballNameReader.cpp - Source/Pokemon/Inference/Pokemon_PokeballNameReader.h - Source/Pokemon/Inference/Pokemon_ReadHpBar.cpp - Source/Pokemon/Inference/Pokemon_ReadHpBar.h - Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.cpp - Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h - Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.cpp - Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h - Source/Pokemon/Options/Pokemon_EncounterBotOptions.h - Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp - Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h - Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp - Source/Pokemon/Options/Pokemon_IvJudgeOption.h - Source/Pokemon/Options/Pokemon_NameSelectOption.cpp - Source/Pokemon/Options/Pokemon_NameSelectOption.h - Source/Pokemon/Options/Pokemon_NameSelectWidget.cpp - Source/Pokemon/Options/Pokemon_NameSelectWidget.h - Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp - Source/Pokemon/Options/Pokemon_StatsHuntFilter.h - Source/Pokemon/Pokemon_DataTypes.h - Source/Pokemon/Pokemon_EncounterStats.cpp - Source/Pokemon/Pokemon_EncounterStats.h - Source/Pokemon/Pokemon_IvJudge.cpp - Source/Pokemon/Pokemon_IvJudge.h - Source/Pokemon/Pokemon_NatureChecker.cpp - Source/Pokemon/Pokemon_NatureChecker.h - Source/Pokemon/Pokemon_Notification.cpp - Source/Pokemon/Pokemon_Notification.h - Source/Pokemon/Pokemon_ShinySparkleSet.cpp - Source/Pokemon/Pokemon_ShinySparkleSet.h - Source/Pokemon/Pokemon_StatsCalculation.cpp - Source/Pokemon/Pokemon_StatsCalculation.h - Source/Pokemon/Pokemon_Strings.cpp - Source/Pokemon/Pokemon_Strings.h - Source/Pokemon/Pokemon_Types.cpp - Source/Pokemon/Pokemon_Types.h - Source/Pokemon/Pokemon_Xoroshiro128Plus.cpp - Source/Pokemon/Pokemon_Xoroshiro128Plus.h - Source/Pokemon/Resources/Pokemon_BerryNames.cpp - Source/Pokemon/Resources/Pokemon_BerryNames.h - Source/Pokemon/Resources/Pokemon_BerrySprites.cpp - Source/Pokemon/Resources/Pokemon_BerrySprites.h - Source/Pokemon/Resources/Pokemon_EggSteps.cpp - Source/Pokemon/Resources/Pokemon_EggSteps.h - Source/Pokemon/Resources/Pokemon_PokeballNames.cpp - Source/Pokemon/Resources/Pokemon_PokeballNames.h - Source/Pokemon/Resources/Pokemon_PokemonForms.cpp - Source/Pokemon/Resources/Pokemon_PokemonForms.h - Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.cpp - Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.h - Source/Pokemon/Resources/Pokemon_PokemonNames.cpp - Source/Pokemon/Resources/Pokemon_PokemonNames.h - Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp - Source/Pokemon/Resources/Pokemon_PokemonSlugs.h - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.cpp - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.cpp - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.cpp - Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.cpp - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.cpp - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.cpp - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.cpp - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.cpp - Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h - Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h - Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h - Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h - Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h - Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h - Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h - Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h - Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.cpp - Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h - Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.cpp - Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h - Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp - Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h - Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.cpp - Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.cpp - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.h - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.cpp - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.cpp - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.h - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.cpp - Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.h - Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.cpp - Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.h - Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.cpp - Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.h - Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.cpp - Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.h - Source/PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h - Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h - Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp - Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h - Source/PokemonBDSP/Panels_PokemonBDSP.cpp - Source/PokemonBDSP/Panels_PokemonBDSP.h - Source/PokemonBDSP/PokemonBDSP_Panels.cpp - Source/PokemonBDSP/PokemonBDSP_Panels.h - Source/PokemonBDSP/PokemonBDSP_Settings.cpp - Source/PokemonBDSP/PokemonBDSP_Settings.h - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.h - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.cpp - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.cpp - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.h - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.cpp - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.h - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp - Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.cpp - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.cpp - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.h - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.cpp - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.h - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.cpp - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.cpp - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.cpp - Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.h - Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.cpp - Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.h - Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.cpp - Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.h - Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.cpp - Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h - Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.cpp - Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h - Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.cpp - Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h - Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h - Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h - Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h - Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h - Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.h - Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h - Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h - Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h - Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.cpp - Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.cpp - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.cpp - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.cpp - Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.h - Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.cpp - Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h - Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.cpp - Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.h - Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.cpp - Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.h - Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.cpp - Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.h - Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.cpp - Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.h - Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.cpp - Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h - Source/PokemonHome/Inference/PokemonHome_BallReader.cpp - Source/PokemonHome/Inference/PokemonHome_BallReader.h - Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp - Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h - Source/PokemonHome/Options/PokemonHome_BoxSortingTable.cpp - Source/PokemonHome/Options/PokemonHome_BoxSortingTable.h - Source/PokemonHome/PokemonHome_Panels.cpp - Source/PokemonHome/PokemonHome_Panels.h - Source/PokemonHome/PokemonHome_Settings.cpp - Source/PokemonHome/PokemonHome_Settings.h - Source/PokemonHome/Programs/PokemonHome_BoxSorting.cpp - Source/PokemonHome/Programs/PokemonHome_BoxSorting.h - Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp - Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h - Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp - Source/PokemonHome/Programs/PokemonHome_PageSwap.h - Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp - Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h - Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp - Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.h - Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.cpp - Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h - Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.cpp - Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h - Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.cpp - Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h - Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.cpp - Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h - Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.cpp - Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h - Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.cpp - Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.h - Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.cpp - Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h - Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.cpp - Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h - Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.cpp - Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h - Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.cpp - Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h - Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.cpp - Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h - Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.cpp - Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h - Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp - Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h - Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h - Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.cpp - Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h - Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.cpp - Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.h - Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.cpp - Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.h - Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.cpp - Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.h - Source/PokemonLA/Inference/PokemonLA_DialogDetector.cpp - Source/PokemonLA/Inference/PokemonLA_DialogDetector.h - Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.cpp - Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h - Source/PokemonLA/Inference/PokemonLA_MountDetector.cpp - Source/PokemonLA/Inference/PokemonLA_MountDetector.h - Source/PokemonLA/Inference/PokemonLA_NotificationReader.cpp - Source/PokemonLA/Inference/PokemonLA_NotificationReader.h - Source/PokemonLA/Inference/PokemonLA_OverworldDetector.cpp - Source/PokemonLA/Inference/PokemonLA_OverworldDetector.h - Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.cpp - Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h - Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.cpp - Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.h - Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.cpp - Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h - Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.cpp - Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h - Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.cpp - Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h - Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.cpp - Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h - Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.cpp - Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h - Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.cpp - Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h - Source/PokemonLA/Options/PokemonLA_CustomPathTable.cpp - Source/PokemonLA/Options/PokemonLA_CustomPathTable.h - Source/PokemonLA/Options/PokemonLA_IngoOpponent.cpp - Source/PokemonLA/Options/PokemonLA_IngoOpponent.h - Source/PokemonLA/Options/PokemonLA_MiscOptions.h - Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.cpp - Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.h - Source/PokemonLA/Options/PokemonLA_TradeCountTable.cpp - Source/PokemonLA/Options/PokemonLA_TradeCountTable.h - Source/PokemonLA/Options/PokemonLA_TravelLocation.cpp - Source/PokemonLA/Options/PokemonLA_TravelLocation.h - Source/PokemonLA/Panels_PokemonLA.cpp - Source/PokemonLA/Panels_PokemonLA.h - Source/PokemonLA/PokemonLA_Locations.cpp - Source/PokemonLA/PokemonLA_Locations.h - Source/PokemonLA/PokemonLA_Panels.cpp - Source/PokemonLA/PokemonLA_Panels.h - Source/PokemonLA/PokemonLA_Settings.cpp - Source/PokemonLA/PokemonLA_Settings.h - Source/PokemonLA/PokemonLA_TravelLocations.cpp - Source/PokemonLA/PokemonLA_TravelLocations.h - Source/PokemonLA/PokemonLA_WeatherAndTime.cpp - Source/PokemonLA/PokemonLA_WeatherAndTime.h - Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.cpp - Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.h - Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.cpp - Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.h - Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.cpp - Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h - Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.cpp - Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.h - Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.cpp - Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.h - Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.cpp - Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.h - Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.cpp - Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.h - Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.cpp - Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.h - Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.cpp - Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.h - Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.cpp - Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.h - Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp - Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h - Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.cpp - Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.h - Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.cpp - Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.h - Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.cpp - Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h - Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.cpp - Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.h - Source/PokemonLA/Programs/PokemonLA_BattleRoutines.cpp - Source/PokemonLA/Programs/PokemonLA_BattleRoutines.h - Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.cpp - Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.h - Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.cpp - Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.h - Source/PokemonLA/Programs/PokemonLA_GameEntry.cpp - Source/PokemonLA/Programs/PokemonLA_GameEntry.h - Source/PokemonLA/Programs/PokemonLA_GameSave.cpp - Source/PokemonLA/Programs/PokemonLA_GameSave.h - Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.cpp - Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.h - Source/PokemonLA/Programs/PokemonLA_MountChange.cpp - Source/PokemonLA/Programs/PokemonLA_MountChange.h - Source/PokemonLA/Programs/PokemonLA_RegionNavigation.cpp - Source/PokemonLA/Programs/PokemonLA_RegionNavigation.h - Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.cpp - Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.cpp - Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h - Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.cpp - Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.h - Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.cpp - Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.h - Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.cpp - Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.h - Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.cpp - Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.h - Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.cpp - Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.h - Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.cpp - Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.h - Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.cpp - Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.h - Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp - Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.h - Source/PokemonLA/Resources/PokemonLA_NameDatabase.cpp - Source/PokemonLA/Resources/PokemonLA_NameDatabase.h - Source/PokemonLA/Resources/PokemonLA_PokemonInfo.cpp - Source/PokemonLA/Resources/PokemonLA_PokemonInfo.h - Source/PokemonLA/Resources/PokemonLA_PokemonSprites.cpp - Source/PokemonLA/Resources/PokemonLA_PokemonSprites.h - Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.cpp - Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h - Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp - Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h - Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp - Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h - Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp - Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h - Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp - Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h - Source/PokemonLGPE/PokemonLGPE_Panels.cpp - Source/PokemonLGPE/PokemonLGPE_Panels.h - Source/PokemonLGPE/PokemonLGPE_Settings.cpp - Source/PokemonLGPE/PokemonLGPE_Settings.h - Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp - Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h - Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp - Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp - Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h - Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp - Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h - Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.cpp - Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.h - Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp - Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h - Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp - Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h - Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp - Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h - Source/PokemonRSE/PokemonRSE_Navigation.cpp - Source/PokemonRSE/PokemonRSE_Navigation.h - Source/PokemonRSE/PokemonRSE_Panels.cpp - Source/PokemonRSE/PokemonRSE_Panels.h - Source/PokemonRSE/PokemonRSE_Settings.cpp - Source/PokemonRSE/PokemonRSE_Settings.h - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp - Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h - Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp - Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h - Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.cpp - Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h - Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.cpp - Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h - Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.cpp - Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h - Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.cpp - Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h - Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp - Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h - Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp - Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h - Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h - Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.cpp - Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h - Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp - Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h - Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp - Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h - Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.cpp - Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp - Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h - Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp - Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h - Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.cpp - Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h - Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.cpp - Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.h - Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.cpp - Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h - Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.cpp - Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h - Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h - Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp - Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h - Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp - Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.cpp - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.cpp - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.cpp - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.cpp - Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h - Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.cpp - Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h - Source/PokemonSV/Inference/PokemonSV_BagDetector.cpp - Source/PokemonSV/Inference/PokemonSV_BagDetector.h - Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.cpp - Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h - Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.cpp - Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h - Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.cpp - Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.h - Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.cpp - Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h - Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.cpp - Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.h - Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp - Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h - Source/PokemonSV/Inference/PokemonSV_MoneyReader.cpp - Source/PokemonSV/Inference/PokemonSV_MoneyReader.h - Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.cpp - Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.h - Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp - Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h - Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.cpp - Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h - Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.cpp - Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.h - Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.cpp - Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h - Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.cpp - Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h - Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp - Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h - Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.cpp - Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h - Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.cpp - Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h - Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp - Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h - Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp - Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h - Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.cpp - Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h - Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.cpp - Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h - Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.cpp - Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.h - Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.cpp - Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.h - Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.cpp - Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.h - Source/PokemonSV/Options/PokemonSV_AuctionItemTable.cpp - Source/PokemonSV/Options/PokemonSV_AuctionItemTable.h - Source/PokemonSV/Options/PokemonSV_AutoHostOptions.h - Source/PokemonSV/Options/PokemonSV_BBQOption.cpp - Source/PokemonSV/Options/PokemonSV_BBQOption.h - Source/PokemonSV/Options/PokemonSV_BattleMoveTable.cpp - Source/PokemonSV/Options/PokemonSV_BattleMoveTable.h - Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.cpp - Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h - Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.cpp - Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.h - Source/PokemonSV/Options/PokemonSV_EncounterBotCommon.h - Source/PokemonSV/Options/PokemonSV_PlayerList.cpp - Source/PokemonSV/Options/PokemonSV_PlayerList.h - Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.cpp - Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.h - Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.cpp - Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.h - Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.cpp - Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.h - Source/PokemonSV/Options/PokemonSV_SinglesAIOption.cpp - Source/PokemonSV/Options/PokemonSV_SinglesAIOption.h - Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.cpp - Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.h - Source/PokemonSV/Options/PokemonSV_TeraAIOption.cpp - Source/PokemonSV/Options/PokemonSV_TeraAIOption.h - Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.cpp - Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h - Source/PokemonSV/Options/PokemonSV_TeraMoveTable.cpp - Source/PokemonSV/Options/PokemonSV_TeraMoveTable.h - Source/PokemonSV/Options/PokemonSV_TeraRollFilter.cpp - Source/PokemonSV/Options/PokemonSV_TeraRollFilter.h - Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.cpp - Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.h - Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.cpp - Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.h - Source/PokemonSV/PokemonSV_Panels.cpp - Source/PokemonSV/PokemonSV_Panels.h - Source/PokemonSV/PokemonSV_Settings.cpp - Source/PokemonSV/PokemonSV_Settings.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp - Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h - Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h - Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.cpp - Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h - Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp - Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h - Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.cpp - Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h - Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.cpp - Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h - Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp - Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h - Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp - Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h - Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.cpp - Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.h - Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.cpp - Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.h - Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp - Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h - Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.cpp - Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.h - Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp - Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.h - Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp - Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h - Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h - Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h - Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.h - Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h - Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h - Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.cpp - Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.h - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.cpp - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.cpp - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.cpp - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp - Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h - Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.cpp - Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h - Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.cpp - Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.h - Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.cpp - Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.h - Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.cpp - Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.h - Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.cpp - Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.h - Source/PokemonSV/Programs/General/PokemonSV_StatsReset.cpp - Source/PokemonSV/Programs/General/PokemonSV_StatsReset.h - Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.cpp - Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.h - Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.cpp - Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.h - Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.cpp - Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.h - Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp - Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.cpp - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.h - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.cpp - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp - Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h - Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp - Source/PokemonSV/Programs/PokemonSV_AreaZero.h - Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.cpp - Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.h - Source/PokemonSV/Programs/PokemonSV_GameEntry.cpp - Source/PokemonSV/Programs/PokemonSV_GameEntry.h - Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp - Source/PokemonSV/Programs/PokemonSV_MenuNavigation.h - Source/PokemonSV/Programs/PokemonSV_SaveGame.cpp - Source/PokemonSV/Programs/PokemonSV_SaveGame.h - Source/PokemonSV/Programs/PokemonSV_Terarium.cpp - Source/PokemonSV/Programs/PokemonSV_Terarium.h - Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp - Source/PokemonSV/Programs/PokemonSV_WorldNavigation.h - Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp - Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h - Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp - Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h - Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp - Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp - Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.cpp - Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h - Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.cpp - Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.h - Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.cpp - Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.h - Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.cpp - Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h - Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.cpp - Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.h - Source/PokemonSV/Resources/PokemonSV_FillingsCoordinates.h - Source/PokemonSV/Resources/PokemonSV_Ingredients.cpp - Source/PokemonSV/Resources/PokemonSV_Ingredients.h - Source/PokemonSV/Resources/PokemonSV_ItemSprites.cpp - Source/PokemonSV/Resources/PokemonSV_ItemSprites.h - Source/PokemonSV/Resources/PokemonSV_NameDatabase.cpp - Source/PokemonSV/Resources/PokemonSV_NameDatabase.h - Source/PokemonSV/Resources/PokemonSV_PokemonSprites.cpp - Source/PokemonSV/Resources/PokemonSV_PokemonSprites.h - Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.cpp - Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp - Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.cpp - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.cpp - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.cpp - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.cpp - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.cpp - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.cpp - Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.cpp - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.cpp - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.cpp - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.cpp - Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h - Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h - Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h - Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h - Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h - Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h - Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h - Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h - Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.cpp - Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h - Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.cpp - Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.cpp - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.cpp - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.cpp - Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h - Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.cpp - Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h - Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.cpp - Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h - Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.cpp - Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h - Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.cpp - Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectItem.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectMove.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectPath.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectStarter.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapCatch.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapProfessor.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.cpp - Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.h - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.cpp - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.cpp - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.cpp - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.cpp - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h - Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.cpp - Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.cpp - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.cpp - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.h - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.cpp - Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h - Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.cpp - Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.h - Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.cpp - Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.h - Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.cpp - Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.cpp - Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.h - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.cpp - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.cpp - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.h - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.cpp - Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.h - Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.cpp - Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h - Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp - Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h - Source/PokemonSwSh/Options/PokemonSwSh_Catchability.h - Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.cpp - Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h - Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.cpp - Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.h - Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.cpp - Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.h - Source/PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h - Source/PokemonSwSh/Options/PokemonSwSh_RegiSelector.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.h - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.cpp - Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.h - Source/PokemonSwSh/PokemonSwSh_Panels.cpp - Source/PokemonSwSh/PokemonSwSh_Panels.h - Source/PokemonSwSh/PokemonSwSh_Settings.cpp - Source/PokemonSwSh/PokemonSwSh_Settings.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp - Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperStats.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.h - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.cpp - Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombinedShared.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp - Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.h - Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp - Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.cpp - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.cpp - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.cpp - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.cpp - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.cpp - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h - Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_LobbyWait.h - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.cpp - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.cpp - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.cpp - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.cpp - Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.h - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.cpp - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.h - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.cpp - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.h - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.cpp - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.cpp - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.h - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp - Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h - Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h - Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h - Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h - Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h - Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.h - Source/PokemonSwSh/Programs/PokemonSwSh_Internet.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_Internet.h - Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h - Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.h - Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h - Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.cpp - Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.h - Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.cpp - Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h - Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.cpp - Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.cpp - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.cpp - Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.cpp - Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp - Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h - Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.cpp - Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h - Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h - Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h - Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h - Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h - Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h - Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h - Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.cpp - Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h - Source/PokemonSwSh/ShinyHuntTracker.cpp - Source/PokemonSwSh/ShinyHuntTracker.h - Source/Tests/CommandLineTests.cpp - Source/Tests/CommandLineTests.h - Source/Tests/CommonFramework_Tests.cpp - Source/Tests/CommonFramework_Tests.h - Source/Tests/Kernels_Tests.cpp - Source/Tests/Kernels_Tests.h - Source/Tests/NintendoSwitch_Tests.cpp - Source/Tests/NintendoSwitch_Tests.h - Source/Tests/PokemonLA_Tests.cpp - Source/Tests/PokemonLA_Tests.h - Source/Tests/PokemonLZA_Tests.cpp - Source/Tests/PokemonLZA_Tests.h - Source/Tests/PokemonSV_Tests.cpp - Source/Tests/PokemonSV_Tests.h - Source/Tests/PokemonSwSh_Tests.cpp - Source/Tests/PokemonSwSh_Tests.h - Source/Tests/TestMap.cpp - Source/Tests/TestMap.h - Source/Tests/TestUtils.cpp - Source/Tests/TestUtils.h - Source/ZeldaTotK/Programs/ZeldaTotK_BowItemDuper.cpp - Source/ZeldaTotK/Programs/ZeldaTotK_BowItemDuper.h - Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.cpp - Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.h - Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.cpp - Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.h - Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.cpp - Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.h - Source/ZeldaTotK/Programs/ZeldaTotK_WeaponDuper.cpp - Source/ZeldaTotK/Programs/ZeldaTotK_WeaponDuper.h - Source/ZeldaTotK/ZeldaTotK_Panels.cpp - Source/ZeldaTotK/ZeldaTotK_Panels.h - Source/ZeldaTotK/ZeldaTotK_Settings.cpp - Source/ZeldaTotK/ZeldaTotK_Settings.h -) -source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}../../ FILES ${MAIN_SOURCES}) - -if (APPLE) - set(SerialPrograms_ICON ${CMAKE_CURRENT_SOURCE_DIR}/../IconResource/icon.icns) - # set_source_files_properties(SerialPrograms_ICON PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") - - # Links on how to create a MacOS app bundle with cmake - # https://stackoverflow.com/questions/53560288/how-to-create-a-macos-app-bundle-with-cmake - # https://cmake.org/cmake/help/latest/command/add_executable.html - add_executable(SerialPrograms MACOSX_BUNDLE ${SerialPrograms_ICON} ${MAIN_SOURCES}) - set_target_properties(SerialPrograms PROPERTIES - BUNDLE True - MACOSX_BUNDLE_GUI_IDENTIFIER PokemonAutomation.SerialPrograms - MACOSX_BUNDLE_BUNDLE_NAME SerialPrograms - MACOSX_BUNDLE_BUNDLE_VERSION "0.1" - MACOSX_BUNDLE_SHORT_VERSION_STRING "0.1" - MACOSX_BUNDLE_ICON_FILE "icon.icns" - # MacOSXBundleInfo.plist.in is modified from https://github.com/Kitware/CMake/blob/master/Modules/MacOSXBundleInfo.plist.in - MACOSX_BUNDLE_INFO_PLIST ${CMAKE_SOURCE_DIR}/cmake/MacOSXBundleInfo.plist.in - RESOURCE ${SerialPrograms_ICON} - ) - - # make sure Packages repo, https://github.com/PokemonAutomation/Packages is placed in the same folder as this Arduino-Source repo - # so the post-build command can copy the resources folder Packages/SerialPrograms/Resources/ into the built app bundle: - string(FIND "${CMAKE_CURRENT_SOURCE_DIR}" "Arduino-Source-Internal" internal_repro_position) # determine if this is an internal repo - if (internal_repro_position EQUAL -1) # no "Arduino-Source-Internal" substr in the current source dir - # we are building the public repo - set(RESOURCES_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../Packages/SerialPrograms/Resources") - else() - # we are building the internal repo - set(RESOURCES_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Packages/SerialPrograms/Resources") - endif() - message(STATUS "Set Resources folder path from Packages repo: ${RESOURCES_PATH}") - add_custom_command( - TARGET SerialPrograms - POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_directory - "${RESOURCES_PATH}" - "$/../Resources" - ) -else() # WIN and Linux: - add_executable(SerialPrograms WIN32 ${MAIN_SOURCES}) -endif() - -set_target_properties(SerialPrograms PROPERTIES LINKER_LANGUAGE CXX) -target_link_libraries(SerialPrograms PRIVATE Qt${QT_MAJOR}::Widgets Qt${QT_MAJOR}::SerialPort Qt${QT_MAJOR}::Multimedia Qt${QT_MAJOR}::MultimediaWidgets) -target_link_libraries(SerialPrograms PRIVATE Threads::Threads) - -#add defines -target_compile_definitions(SerialPrograms PRIVATE NOMINMAX) - -if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../Internal/SerialPrograms/Internal0.cpp") - target_compile_definitions(SerialPrograms PRIVATE PA_OFFICIAL) - target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.cpp) - target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.h) - target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/Internal0.cpp) - target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/Internal1.cpp) -endif() - -#extract opencv_world4110d.dll from archive on Windows Debug builds -if (MSVC) - file(ARCHIVE_EXTRACT - INPUT ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/opencv_world4110d.zip - DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/ - ) -endif() - -#add include directory -target_include_directories(SerialPrograms SYSTEM PRIVATE ../3rdParty/) -target_include_directories(SerialPrograms PRIVATE ../ ../../Internal/ Source/) -target_link_directories(SerialPrograms PRIVATE ../3rdPartyBinaries/) - - - - -if (MSVC) - add_library(OpenCV_lib IMPORTED UNKNOWN) - target_include_directories(SerialPrograms SYSTEM PRIVATE ../3rdParty/opencv-4.11.0/) - set_target_properties(OpenCV_lib PROPERTIES - IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/opencv_world4110.lib - IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/opencv_world4110d.lib) - set_target_properties(OpenCV_lib PROPERTIES - MAP_IMPORTED_CONFIG_DEBUG DEBUG - MAP_IMPORTED_CONFIG_RELEASE RELEASE - MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE - MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE - ) - - add_library(ONNX_lib IMPORTED UNKNOWN) - target_include_directories(SerialPrograms SYSTEM PRIVATE ../3rdParty/ONNX/) - set_target_properties(ONNX_lib PROPERTIES - IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime.lib - IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime.lib) - set_target_properties(ONNX_lib PROPERTIES - MAP_IMPORTED_CONFIG_DEBUG DEBUG - MAP_IMPORTED_CONFIG_RELEASE RELEASE - MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE - MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE - ) - - add_library(ONNX_Providers_lib IMPORTED UNKNOWN) - set_target_properties(ONNX_Providers_lib PROPERTIES - IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime_providers_shared.lib - IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime_providers_shared.lib) - set_target_properties(ONNX_Providers_lib PROPERTIES - MAP_IMPORTED_CONFIG_DEBUG DEBUG - MAP_IMPORTED_CONFIG_RELEASE RELEASE - MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE - MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE - ) - - add_library(dpp_lib IMPORTED UNKNOWN) - set_target_properties(dpp_lib PROPERTIES - IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/dpp.lib - IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/dppd.lib) - set_target_properties(dpp_lib PROPERTIES - MAP_IMPORTED_CONFIG_DEBUG DEBUG - MAP_IMPORTED_CONFIG_RELEASE RELEASE - MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE - MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE - ) - - target_link_libraries( - SerialPrograms PRIVATE - tesseractPA.lib - OpenCV_lib - ONNX_lib - ONNX_Providers_lib - Sleepy.lib - dpp_lib - ) - target_compile_definitions( - SerialPrograms PRIVATE - _CRT_SECURE_NO_WARNINGS - _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR - PA_TESSERACT - PA_SLEEPY - PA_DPP - ) - - target_compile_options(SerialPrograms PRIVATE /FAs /FaAssembly/ /MP /W4 /WX /external:anglebrackets /external:W0 /utf-8) - target_compile_options(SerialPrograms PRIVATE /wd5054) # Deprecated enum arithemtic - target_compile_options(SerialPrograms PRIVATE /wd4505) # unreferenced local function has been removed - - set(ARCH_FLAGS_09_Nehalem /W4) # Dummy parameter - set(ARCH_FLAGS_13_Haswell /arch:AVX2) - set(ARCH_FLAGS_17_Skylake /arch:AVX512) - set(ARCH_FLAGS_19_IceLake /arch:AVX512) - - # Run-time ISA dispatching - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_08_Nehalem) - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_13_Haswell) - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_17_Skylake) - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_19_IceLake) - -# target_compile_options(SerialPrograms PRIVATE /arch:AVX2 /DPA_Arch_x64_AVX2) -# target_compile_options(SerialPrograms PRIVATE /arch:AVX512 /DPA_Arch_x64_AVX512) -# target_compile_options(SerialPrograms PRIVATE /arch:AVX512 /DPA_Arch_x64_AVX512GF) -else() # macOS and Linux - if (APPLE) - # Get root path where Homebrew installs libraries. Example root path: "/opt/homebrew/", - # where you can find libraries in "/opt/homebrew/lib/" and headers in "/opt/homebrew/include/". - # CMake does not support ONNX Runtime, so we have to add ONNX Runtime paths on our own. - # Save the root path as CMake variable HOMEBREW_PREFIX. - execute_process(COMMAND brew --prefix OUTPUT_VARIABLE HOMEBREW_PREFIX OUTPUT_STRIP_TRAILING_WHITESPACE) - - # Get ONNX Runtime paths - target_include_directories(SerialPrograms PRIVATE ${HOMEBREW_PREFIX}/include/onnxruntime) - target_link_libraries(SerialPrograms PRIVATE ${HOMEBREW_PREFIX}/lib/libonnxruntime.dylib) - else() # Linux - # Instructions took from https://github.com/microsoft/onnxruntime/discussions/6489 - # Step 1: Download the file - file(DOWNLOAD - https://github.com/microsoft/onnxruntime/releases/download/v1.22.0/onnxruntime-linux-x64-1.22.0.tgz - ${CMAKE_BINARY_DIR}/onnxruntime-linux-x64-1.22.0.tgz - SHOW_PROGRESS - ) - - # Step 2: Extract the archive - execute_process( - COMMAND tar -xzf onnxruntime-linux-x64-1.22.0.tgz - WORKING_DIRECTORY ${CMAKE_BINARY_DIR} - ) - - # Step 3: Copy files to /usr/local - execute_process( - COMMAND sudo cp -r ${CMAKE_BINARY_DIR}/onnxruntime-linux-x64-1.22.0/include /usr/local/ - ) - execute_process( - COMMAND sudo cp -r ${CMAKE_BINARY_DIR}/onnxruntime-linux-x64-1.22.0/lib /usr/local/ - ) - - # Step 4: Run ldconfig - execute_process( - COMMAND sudo ldconfig - WORKING_DIRECTORY /usr/local/lib - ) - - # Link against ONNX Runtime - target_link_libraries(SerialPrograms PRIVATE onnxruntime) - endif() - - # Find OpenCV - # set(OPENCV_DIR, "/usr/local/opt/opencv/lib/cmake/opencv4") - find_package(OpenCV REQUIRED HINTS "/usr/local/opt/opencv/lib/cmake/opencv4/") - # set(ENV{PKG_CONFIG_PATH} "$ENV{PKG_CONFIG_PATH}:/usr/local/opt/opencv/lib/pkgconfig") - # pkg_search_module(OPENCV REQUIRED opencv) - include_directories(${OpenCV_INCLUDE_DIRS}) - link_directories(${OpenCV_LIBRARY_DIRS}) - target_link_libraries(SerialPrograms PRIVATE ${OpenCV_LIBS}) - - #we hope to use our own Tesseract build in future so we can rid that dependency - #but right now to run on Linux and Mac we need to use external Tesseract library - if (UNIX_LINK_TESSERACT) - find_package(PkgConfig REQUIRED) - target_compile_definitions(SerialPrograms PRIVATE PA_TESSERACT UNIX_LINK_TESSERACT) - pkg_search_module(TESSERACT REQUIRED tesseract) - pkg_search_module(LEPTONICA REQUIRED lept) - include_directories(${TESSERACT_INCLUDE_DIRS}) - include_directories(${LEPTONICA_INCLUDE_DIRS}) - link_directories(${TESSERACT_LIBRARY_DIRS}) - link_directories(${LEPTONICA_LIBRARY_DIRS}) - target_link_libraries(SerialPrograms PRIVATE ${TESSERACT_LINK_LIBRARIES}) - target_link_libraries(SerialPrograms PRIVATE ${LEPTONICA_LINK_LIBRARIES}) - endif() - - # enable dpp integration - if ((APPLE) AND (CMAKE_SYSTEM_PROCESSOR MATCHES "(arm64)|(ARM64)")) - add_library(libdpp STATIC IMPORTED) - set_target_properties(libdpp PROPERTIES - IMPORTED_LOCATION ../3rdPartyBinaries/libdpp_macos_arm64.a - INTERFACE_COMPILE_DEFINITIONS "PA_DPP" - INTERFACE_LINK_LIBRARIES "-L/opt/homebrew/lib -lssl -lcrypto -lopus -lsodium -lz" # add dpp's deps - ) - target_link_libraries(SerialPrograms PRIVATE libdpp) - endif() - - if (APPLE) - # Add -Wno-c11-extensions to avoid clang gives - # /usr/local/Cellar/opencv/4.5.5_3/include/opencv4/opencv2/core/mat.inl.hpp:2116:9: error: '_Atomic' is a C11 extension - # when compiling OpenCV - # target_compile_options(SerialPrograms PRIVATE -Wall -Wextra -Wpedantic -Werror -Wno-c11-extensions) - target_compile_options(SerialPrograms PRIVATE -Wall -Wextra -Wpedantic -Werror -Wshorten-64-to-32) - else() - # Assume GCC - target_compile_options(SerialPrograms PRIVATE -Wall -Wextra -Wpedantic -Werror -fno-strict-aliasing) - endif() - - # Set OS-specific flags - if (WIN32) - elseif (APPLE) - # on macOS, need this framework to query OS API to control display sleep and system sleep behavior - target_link_libraries(SerialPrograms PRIVATE "-framework IOKit -framework CoreFoundation") - elseif(UNIX) - endif() - - IF(${CMAKE_SYSTEM_PROCESSOR} MATCHES "arm") - # Arm CPU - # Run-time ISA dispatching - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_arm64_20_M1) - - else() - # Intel CPU - target_compile_options(SerialPrograms PRIVATE -msse4.2) - set(ARCH_FLAGS_09_Nehalem -march=nehalem) - set(ARCH_FLAGS_13_Haswell -march=haswell) - set(ARCH_FLAGS_17_Skylake -march=skylake-avx512) - set(ARCH_FLAGS_19_IceLake -march=icelake-client) - - # Run-time ISA dispatching - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_08_Nehalem) - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_13_Haswell) - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_17_Skylake) - target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_19_IceLake) - - endif() -endif() - - - -# Run-time CPU dispatching. - -if (ARCH_FLAGS_09_Nehalem) -SET_SOURCE_FILES_PROPERTIES( - Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp - Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp - PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_09_Nehalem} -) -endif() -if (ARCH_FLAGS_13_Haswell) -SET_SOURCE_FILES_PROPERTIES( - Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp - PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_13_Haswell} -) -endif() -if (ARCH_FLAGS_17_Skylake) -SET_SOURCE_FILES_PROPERTIES( - Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp - Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp - Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp - Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp - Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp - Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp - Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp - Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp - Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp - PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_17_Skylake} -) -endif() -if (ARCH_FLAGS_19_IceLake) -SET_SOURCE_FILES_PROPERTIES( - Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp - Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp - PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_19_IceLake} -) -endif() - - - - -if (WIN32) -#copy needed dlls -#file(COPY *.dll DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) -file(GLOB MY_DLLS - "../3rdPartyBinaries/*.dll" -) -file(COPY ${MY_DLLS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) -endif() - -if (QT_MAJOR GREATER_EQUAL 6) - qt_finalize_target(SerialPrograms) -endif() +#set the minimum cmake version required +cmake_minimum_required(VERSION 3.18.0) + +#set the name of the project +project(SerialPrograms) + +#enable c++ 23 +set(CMAKE_CXX_STANDARD 23) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +#produce clang tidy file +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +#set(CMAKE_VERBOSE_MAKEFILE ON) + +set(CMAKE_AUTOMOC ON) +set(CMAKE_AUTORCC ON) +set(CMAKE_AUTOUIC ON) + +add_custom_target(build-time-make-directory ALL + COMMAND ${CMAKE_COMMAND} -E make_directory Assembly/) + +#Find threads library +set(THREADS_PREFER_PTHREAD_FLAG ON) +find_package(Threads REQUIRED) + +#find Qt +if(NOT QT_MAJOR) + set(QT_MAJOR 6) +endif() +find_package(Qt${QT_MAJOR} COMPONENTS Widgets SerialPort Multimedia MultimediaWidgets REQUIRED) +#disable deprecated Qt APIs +add_compile_definitions(QT_DISABLE_DEPRECATED_BEFORE=0x050F00) + +#add current directory to find tesseractPA.lib +link_directories(${CMAKE_CURRENT_LIST_DIR}) + +file(GLOB MAIN_SOURCES + ../3rdParty/ONNX/OnnxToolsPA.h + ../3rdParty/QtWavFile/WavFile.cpp + ../3rdParty/QtWavFile/WavFile.h + ../3rdParty/TesseractPA/TesseractPA.cpp + ../3rdParty/TesseractPA/TesseractPA.h + ../3rdParty/qdarkstyle/dark/darkstyle.qrc + ../ClientSource/Connection/BotBase.cpp + ../ClientSource/Connection/BotBase.h + ../ClientSource/Connection/BotBaseMessage.h + ../ClientSource/Connection/MessageLogger.cpp + ../ClientSource/Connection/MessageLogger.h + ../ClientSource/Connection/MessageSniffer.h + ../ClientSource/Connection/PABotBase.cpp + ../ClientSource/Connection/PABotBase.h + ../ClientSource/Connection/PABotBaseConnection.cpp + ../ClientSource/Connection/PABotBaseConnection.h + ../ClientSource/Connection/SerialConnection.h + ../ClientSource/Connection/SerialConnectionPOSIX.h + ../ClientSource/Connection/SerialConnectionWinAPI.h + ../ClientSource/Connection/StreamInterface.h + ../ClientSource/Libraries/Logging.cpp + ../ClientSource/Libraries/Logging.h + ../ClientSource/Libraries/MessageConverter.cpp + ../ClientSource/Libraries/MessageConverter.h + ../Common/CRC32.cpp + ../Common/CRC32.h + ../Common/Compiler.h + ../Common/Cpp/AbstractLogger.h + ../Common/Cpp/CancellableScope.cpp + ../Common/Cpp/CancellableScope.h + ../Common/Cpp/Color.cpp + ../Common/Cpp/Color.h + ../Common/Cpp/Concurrency/AsyncDispatcher.cpp + ../Common/Cpp/Concurrency/AsyncDispatcher.h + ../Common/Cpp/Concurrency/FireForgetDispatcher.cpp + ../Common/Cpp/Concurrency/FireForgetDispatcher.h + ../Common/Cpp/Concurrency/ParallelTaskRunner.cpp + ../Common/Cpp/Concurrency/ParallelTaskRunner.h + ../Common/Cpp/Concurrency/PeriodicScheduler.cpp + ../Common/Cpp/Concurrency/PeriodicScheduler.h + ../Common/Cpp/Concurrency/ReverseLockGuard.h + ../Common/Cpp/Concurrency/ScheduledTaskRunner.cpp + ../Common/Cpp/Concurrency/ScheduledTaskRunner.h + ../Common/Cpp/Concurrency/SpinLock.cpp + ../Common/Cpp/Concurrency/SpinLock.h + ../Common/Cpp/Concurrency/SpinPause.h + ../Common/Cpp/Concurrency/Watchdog.cpp + ../Common/Cpp/Concurrency/Watchdog.h + ../Common/Cpp/Containers/AlignedMalloc.cpp + ../Common/Cpp/Containers/AlignedMalloc.h + ../Common/Cpp/Containers/AlignedVector.h + ../Common/Cpp/Containers/AlignedVector.tpp + ../Common/Cpp/Containers/BoxSet.h + ../Common/Cpp/Containers/CircularBuffer.h + ../Common/Cpp/Containers/DllSafeString.h + ../Common/Cpp/Containers/FixedLimitVector.h + ../Common/Cpp/Containers/FixedLimitVector.tpp + ../Common/Cpp/Containers/Pimpl.h + ../Common/Cpp/Containers/Pimpl.tpp + ../Common/Cpp/Containers/SparseArray.cpp + ../Common/Cpp/Containers/SparseArray.h + ../Common/Cpp/CpuId/CpuId.cpp + ../Common/Cpp/CpuId/CpuId.h + ../Common/Cpp/CpuId/CpuId_arm64.h + ../Common/Cpp/CpuId/CpuId_arm64.tpp + ../Common/Cpp/CpuId/CpuId_x86.h + ../Common/Cpp/CpuId/CpuId_x86.tpp + ../Common/Cpp/DateTime.h + ../Common/Cpp/EnumStringMap.h + ../Common/Cpp/EventRateTracker.h + ../Common/Cpp/Exceptions.cpp + ../Common/Cpp/Exceptions.h + ../Common/Cpp/ExpressionEvaluator.cpp + ../Common/Cpp/ExpressionEvaluator.h + ../Common/Cpp/ImageResolution.cpp + ../Common/Cpp/ImageResolution.h + ../Common/Cpp/Json/JsonArray.cpp + ../Common/Cpp/Json/JsonArray.h + ../Common/Cpp/Json/JsonObject.cpp + ../Common/Cpp/Json/JsonObject.h + ../Common/Cpp/Json/JsonTools.cpp + ../Common/Cpp/Json/JsonTools.h + ../Common/Cpp/Json/JsonValue.cpp + ../Common/Cpp/Json/JsonValue.h + ../Common/Cpp/LifetimeSanitizer.cpp + ../Common/Cpp/LifetimeSanitizer.h + ../Common/Cpp/ListenerSet.h + ../Common/Cpp/Options/BatchOption.cpp + ../Common/Cpp/Options/BatchOption.h + ../Common/Cpp/Options/BooleanCheckBoxOption.cpp + ../Common/Cpp/Options/BooleanCheckBoxOption.h + ../Common/Cpp/Options/ButtonOption.cpp + ../Common/Cpp/Options/ButtonOption.h + ../Common/Cpp/Options/ColorOption.cpp + ../Common/Cpp/Options/ColorOption.h + ../Common/Cpp/Options/ConfigOption.cpp + ../Common/Cpp/Options/ConfigOption.h + ../Common/Cpp/Options/DateOption.cpp + ../Common/Cpp/Options/DateOption.h + ../Common/Cpp/Options/EditableTableOption.cpp + ../Common/Cpp/Options/EditableTableOption.h + ../Common/Cpp/Options/EnumDropdownDatabase.cpp + ../Common/Cpp/Options/EnumDropdownDatabase.h + ../Common/Cpp/Options/EnumDropdownOption.cpp + ../Common/Cpp/Options/EnumDropdownOption.h + ../Common/Cpp/Options/FixedCodeOption.cpp + ../Common/Cpp/Options/FixedCodeOption.h + ../Common/Cpp/Options/FloatingPointOption.cpp + ../Common/Cpp/Options/FloatingPointOption.h + ../Common/Cpp/Options/GroupOption.cpp + ../Common/Cpp/Options/GroupOption.h + ../Common/Cpp/Options/IntegerRangeOption.cpp + ../Common/Cpp/Options/IntegerRangeOption.h + ../Common/Cpp/Options/KeyBindingOption.cpp + ../Common/Cpp/Options/KeyBindingOption.h + ../Common/Cpp/Options/MacAddressOption.cpp + ../Common/Cpp/Options/MacAddressOption.h + ../Common/Cpp/Options/RandomCodeOption.cpp + ../Common/Cpp/Options/RandomCodeOption.h + ../Common/Cpp/Options/SimpleIntegerOption.cpp + ../Common/Cpp/Options/SimpleIntegerOption.h + ../Common/Cpp/Options/StaticTableOption.cpp + ../Common/Cpp/Options/StaticTableOption.h + ../Common/Cpp/Options/StaticTextOption.cpp + ../Common/Cpp/Options/StaticTextOption.h + ../Common/Cpp/Options/StringOption.cpp + ../Common/Cpp/Options/StringOption.h + ../Common/Cpp/Options/TextEditOption.cpp + ../Common/Cpp/Options/TextEditOption.h + ../Common/Cpp/Options/TimeDurationOption.cpp + ../Common/Cpp/Options/TimeDurationOption.h + ../Common/Cpp/Options/TimeExpressionOption.cpp + ../Common/Cpp/Options/TimeExpressionOption.h + ../Common/Cpp/PanicDump.cpp + ../Common/Cpp/PanicDump.h + ../Common/Cpp/PixelRGB32.h + ../Common/Cpp/PrettyPrint.cpp + ../Common/Cpp/PrettyPrint.h + ../Common/Cpp/PrintDebuggers.h + ../Common/Cpp/Rectangle.h + ../Common/Cpp/Rectangle.tpp + ../Common/Cpp/RecursiveThrottler.h + ../Common/Cpp/SIMDDebuggers.h + ../Common/Cpp/Sockets/AbstractClientSocket.h + ../Common/Cpp/Sockets/ClientSocket.cpp + ../Common/Cpp/Sockets/ClientSocket.h + ../Common/Cpp/Sockets/ClientSocket_POSIX.h + ../Common/Cpp/Sockets/ClientSocket_WinSocket.h + ../Common/Cpp/StreamConverters.cpp + ../Common/Cpp/StreamConverters.h + ../Common/Cpp/StringTools.cpp + ../Common/Cpp/StringTools.h + ../Common/Cpp/Time.cpp + ../Common/Cpp/Time.h + ../Common/Cpp/Unicode.cpp + ../Common/Cpp/Unicode.h + ../Common/Cpp/ValueDebouncer.h + ../Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h + ../Common/NintendoSwitch/NintendoSwitch_Protocol_PushButtons.h + ../Common/NintendoSwitch/NintendoSwitch_SlotDatabase.h + ../Common/PokemonSwSh/PokemonSwSh_FossilTable.h + ../Common/PokemonSwSh/PokemonSwSh_MultiHostTable.cpp + ../Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h + ../Common/PokemonSwSh/PokemonSwSh_Protocol_DaySkippers.h + ../Common/Qt/AutoHeightTable.cpp + ../Common/Qt/AutoHeightTable.h + ../Common/Qt/AutoWidthLineEdit.cpp + ../Common/Qt/AutoWidthLineEdit.h + ../Common/Qt/CodeValidator.cpp + ../Common/Qt/CodeValidator.h + ../Common/Qt/CollapsibleGroupBox.cpp + ../Common/Qt/CollapsibleGroupBox.h + ../Common/Qt/NoWheelComboBox.h + ../Common/Qt/Options/BatchWidget.cpp + ../Common/Qt/Options/BatchWidget.h + ../Common/Qt/Options/BooleanCheckBoxWidget.cpp + ../Common/Qt/Options/BooleanCheckBoxWidget.h + ../Common/Qt/Options/ButtonWidget.cpp + ../Common/Qt/Options/ButtonWidget.h + ../Common/Qt/Options/ColorWidget.cpp + ../Common/Qt/Options/ColorWidget.h + ../Common/Qt/Options/ConfigWidget.cpp + ../Common/Qt/Options/ConfigWidget.h + ../Common/Qt/Options/DateWidget.cpp + ../Common/Qt/Options/DateWidget.h + ../Common/Qt/Options/EditableTableWidget.cpp + ../Common/Qt/Options/EditableTableWidget.h + ../Common/Qt/Options/EnumDropdownWidget.cpp + ../Common/Qt/Options/EnumDropdownWidget.h + ../Common/Qt/Options/FixedCodeWidget.cpp + ../Common/Qt/Options/FixedCodeWidget.h + ../Common/Qt/Options/FloatingPointWidget.cpp + ../Common/Qt/Options/FloatingPointWidget.h + ../Common/Qt/Options/GroupWidget.cpp + ../Common/Qt/Options/GroupWidget.h + ../Common/Qt/Options/IntegerRangeWidget.cpp + ../Common/Qt/Options/IntegerRangeWidget.h + ../Common/Qt/Options/KeyBindingWidget.cpp + ../Common/Qt/Options/KeyBindingWidget.h + ../Common/Qt/Options/MacAddressWidget.cpp + ../Common/Qt/Options/MacAddressWidget.h + ../Common/Qt/Options/RandomCodeWidget.cpp + ../Common/Qt/Options/RandomCodeWidget.h + ../Common/Qt/Options/SimpleIntegerWidget.cpp + ../Common/Qt/Options/SimpleIntegerWidget.h + ../Common/Qt/Options/StaticTableWidget.cpp + ../Common/Qt/Options/StaticTableWidget.h + ../Common/Qt/Options/StaticTextWidget.cpp + ../Common/Qt/Options/StaticTextWidget.h + ../Common/Qt/Options/StringWidget.cpp + ../Common/Qt/Options/StringWidget.h + ../Common/Qt/Options/TextEditWidget.cpp + ../Common/Qt/Options/TextEditWidget.h + ../Common/Qt/Options/TimeDurationWidget.cpp + ../Common/Qt/Options/TimeDurationWidget.h + ../Common/Qt/Options/TimeExpressionWidget.cpp + ../Common/Qt/Options/TimeExpressionWidget.h + ../Common/Qt/Redispatch.cpp + ../Common/Qt/Redispatch.h + ../Common/Qt/StringToolsQt.cpp + ../Common/Qt/StringToolsQt.h + ../Common/Qt/TimeQt.cpp + ../Common/Qt/TimeQt.h + ../Common/Qt/WidgetStackFixedAspectRatio.cpp + ../Common/Qt/WidgetStackFixedAspectRatio.h + ../Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h + ../Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h + ../Common/SerialPABotBase/SerialPABotBase_Protocol.h + ../Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h + ../IconResource/IconResource.rc + Source/CommonFramework/AudioPipeline/AudioConstants.h + Source/CommonFramework/AudioPipeline/AudioFeed.h + Source/CommonFramework/AudioPipeline/AudioInfo.cpp + Source/CommonFramework/AudioPipeline/AudioInfo.h + Source/CommonFramework/AudioPipeline/AudioNormalization.h + Source/CommonFramework/AudioPipeline/AudioOption.cpp + Source/CommonFramework/AudioPipeline/AudioOption.h + Source/CommonFramework/AudioPipeline/AudioPassthroughPair.h + Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h + Source/CommonFramework/AudioPipeline/AudioSession.cpp + Source/CommonFramework/AudioPipeline/AudioSession.h + Source/CommonFramework/AudioPipeline/AudioStream.cpp + Source/CommonFramework/AudioPipeline/AudioStream.h + Source/CommonFramework/AudioPipeline/AudioTemplate.cpp + Source/CommonFramework/AudioPipeline/AudioTemplate.h + Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.cpp + Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.h + Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp + Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.h + Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.cpp + Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.h + Source/CommonFramework/AudioPipeline/IO/AudioSink.cpp + Source/CommonFramework/AudioPipeline/IO/AudioSink.h + Source/CommonFramework/AudioPipeline/IO/AudioSource.cpp + Source/CommonFramework/AudioPipeline/IO/AudioSource.h + Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.cpp + Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.h + Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.cpp + Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h + Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.cpp + Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.h + Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.cpp + Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h + Source/CommonFramework/AudioPipeline/Tools/AudioNormalization.h + Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.cpp + Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.h + Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.cpp + Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.h + Source/CommonFramework/AudioPipeline/Tools/TimeSampleWriter.h + Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.cpp + Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h + Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.cpp + Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h + Source/CommonFramework/Environment/Environment.cpp + Source/CommonFramework/Environment/Environment.h + Source/CommonFramework/Environment/Environment_Linux.h + Source/CommonFramework/Environment/Environment_Linux.tpp + Source/CommonFramework/Environment/Environment_Windows.h + Source/CommonFramework/Environment/Environment_Windows.tpp + Source/CommonFramework/Environment/Environment_arm64_Linux.tpp + Source/CommonFramework/Environment/Environment_x86.tpp + Source/CommonFramework/Environment/Environment_x86_Linux.tpp + Source/CommonFramework/Environment/Environment_x86_Windows.tpp + Source/CommonFramework/Environment/HardwareValidation.cpp + Source/CommonFramework/Environment/HardwareValidation.h + Source/CommonFramework/Environment/HardwareValidation_arm64.tpp + Source/CommonFramework/Environment/HardwareValidation_x86.tpp + Source/CommonFramework/Environment/SystemSleep.cpp + Source/CommonFramework/Environment/SystemSleep.h + Source/CommonFramework/Environment/SystemSleep_Apple.tpp + Source/CommonFramework/Environment/SystemSleep_Windows.tpp + Source/CommonFramework/ErrorReports/ErrorReports.cpp + Source/CommonFramework/ErrorReports/ErrorReports.h + Source/CommonFramework/ErrorReports/ProgramDumper.cpp + Source/CommonFramework/ErrorReports/ProgramDumper.h + Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp + Source/CommonFramework/Exceptions/FatalProgramException.h + Source/CommonFramework/Exceptions/OperationFailedException.h + Source/CommonFramework/Exceptions/ProgramFinishedException.cpp + Source/CommonFramework/Exceptions/ProgramFinishedException.h + Source/CommonFramework/Exceptions/ScreenshotException.cpp + Source/CommonFramework/Exceptions/ScreenshotException.h + Source/CommonFramework/Exceptions/UnexpectedBattleException.h + Source/CommonFramework/GlobalServices.cpp + Source/CommonFramework/GlobalServices.h + Source/CommonFramework/GlobalSettingsPanel.cpp + Source/CommonFramework/GlobalSettingsPanel.h + Source/CommonFramework/Globals.cpp + Source/CommonFramework/Globals.h + Source/CommonFramework/ImageTools/FloatPixel.cpp + Source/CommonFramework/ImageTools/FloatPixel.h + Source/CommonFramework/ImageTools/ImageBoxes.cpp + Source/CommonFramework/ImageTools/ImageBoxes.h + Source/CommonFramework/ImageTools/ImageDiff.cpp + Source/CommonFramework/ImageTools/ImageDiff.h + Source/CommonFramework/ImageTools/ImageStats.cpp + Source/CommonFramework/ImageTools/ImageStats.h + Source/CommonFramework/ImageTypes/BinaryImage.cpp + Source/CommonFramework/ImageTypes/BinaryImage.h + Source/CommonFramework/ImageTypes/ImageHSV32.cpp + Source/CommonFramework/ImageTypes/ImageHSV32.h + Source/CommonFramework/ImageTypes/ImageRGB32.cpp + Source/CommonFramework/ImageTypes/ImageRGB32.h + Source/CommonFramework/ImageTypes/ImageViewHSV32.cpp + Source/CommonFramework/ImageTypes/ImageViewHSV32.h + Source/CommonFramework/ImageTypes/ImageViewPlanar32.cpp + Source/CommonFramework/ImageTypes/ImageViewPlanar32.h + Source/CommonFramework/ImageTypes/ImageViewRGB32.cpp + Source/CommonFramework/ImageTypes/ImageViewRGB32.h + Source/CommonFramework/Language.cpp + Source/CommonFramework/Language.h + Source/CommonFramework/Logging/FileWindowLogger.cpp + Source/CommonFramework/Logging/FileWindowLogger.h + Source/CommonFramework/Logging/Logger.cpp + Source/CommonFramework/Logging/Logger.h + Source/CommonFramework/Logging/OutputRedirector.cpp + Source/CommonFramework/Logging/OutputRedirector.h + Source/CommonFramework/Logging/QueuedLogger.cpp + Source/CommonFramework/Logging/QueuedLogger.h + Source/CommonFramework/Main.cpp + Source/CommonFramework/Notifications/EventNotificationOption.cpp + Source/CommonFramework/Notifications/EventNotificationOption.h + Source/CommonFramework/Notifications/EventNotificationsTable.cpp + Source/CommonFramework/Notifications/EventNotificationsTable.h + Source/CommonFramework/Notifications/MessageAttachment.cpp + Source/CommonFramework/Notifications/MessageAttachment.h + Source/CommonFramework/Notifications/ProgramInfo.h + Source/CommonFramework/Notifications/ProgramNotifications.cpp + Source/CommonFramework/Notifications/ProgramNotifications.h + Source/CommonFramework/Notifications/SenderNotificationTable.cpp + Source/CommonFramework/Notifications/SenderNotificationTable.h + Source/CommonFramework/Options/CheckForUpdatesOption.h + Source/CommonFramework/Options/Environment/PerformanceOptions.h + Source/CommonFramework/Options/Environment/ProcessPriorityOption.h + Source/CommonFramework/Options/Environment/ProcessorLevelOption.cpp + Source/CommonFramework/Options/Environment/ProcessorLevelOption.h + Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp + Source/CommonFramework/Options/Environment/SleepSuppressOption.h + Source/CommonFramework/Options/Environment/ThemeSelectorOption.cpp + Source/CommonFramework/Options/Environment/ThemeSelectorOption.h + Source/CommonFramework/Options/LabelCellOption.cpp + Source/CommonFramework/Options/LabelCellOption.h + Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp + Source/CommonFramework/Options/QtWidget/LabelCellWidget.h + Source/CommonFramework/Options/ResolutionOption.cpp + Source/CommonFramework/Options/ResolutionOption.h + Source/CommonFramework/Options/ScreenshotFormatOption.h + Source/CommonFramework/Panels/PanelDescriptor.cpp + Source/CommonFramework/Panels/PanelDescriptor.h + Source/CommonFramework/Panels/PanelInstance.cpp + Source/CommonFramework/Panels/PanelInstance.h + Source/CommonFramework/Panels/PanelList.cpp + Source/CommonFramework/Panels/PanelList.h + Source/CommonFramework/Panels/PanelTools.h + Source/CommonFramework/Panels/ProgramDescriptor.cpp + Source/CommonFramework/Panels/ProgramDescriptor.h + Source/CommonFramework/Panels/SettingsPanel.cpp + Source/CommonFramework/Panels/SettingsPanel.h + Source/CommonFramework/Panels/UI/PanelElements.cpp + Source/CommonFramework/Panels/UI/PanelElements.h + Source/CommonFramework/Panels/UI/PanelListWidget.cpp + Source/CommonFramework/Panels/UI/PanelListWidget.h + Source/CommonFramework/Panels/UI/PanelWidget.cpp + Source/CommonFramework/Panels/UI/PanelWidget.h + Source/CommonFramework/Panels/UI/SettingsPanelWidget.cpp + Source/CommonFramework/Panels/UI/SettingsPanelWidget.h + Source/CommonFramework/PersistentSettings.cpp + Source/CommonFramework/PersistentSettings.h + Source/CommonFramework/ProgramSession.cpp + Source/CommonFramework/ProgramSession.h + Source/CommonFramework/ProgramStats/StatsDatabase.cpp + Source/CommonFramework/ProgramStats/StatsDatabase.h + Source/CommonFramework/ProgramStats/StatsTracking.cpp + Source/CommonFramework/ProgramStats/StatsTracking.h + Source/CommonFramework/Recording/StreamHistoryOption.cpp + Source/CommonFramework/Recording/StreamHistoryOption.h + Source/CommonFramework/Recording/StreamHistorySession.cpp + Source/CommonFramework/Recording/StreamHistorySession.h + Source/CommonFramework/Recording/StreamHistoryTracker_Null.h + Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h + Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h + Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h + Source/CommonFramework/Recording/StreamRecorder.cpp + Source/CommonFramework/Recording/StreamRecorder.h + Source/CommonFramework/Startup/NewVersionCheck.cpp + Source/CommonFramework/Startup/NewVersionCheck.h + Source/CommonFramework/Startup/SetupSettings.cpp + Source/CommonFramework/Startup/SetupSettings.h + Source/CommonFramework/Tools/DebugDumper.cpp + Source/CommonFramework/Tools/DebugDumper.h + Source/CommonFramework/Tools/ErrorDumper.cpp + Source/CommonFramework/Tools/ErrorDumper.h + Source/CommonFramework/Tools/FileDownloader.cpp + Source/CommonFramework/Tools/FileDownloader.h + Source/CommonFramework/Tools/ProgramEnvironment.cpp + Source/CommonFramework/Tools/ProgramEnvironment.h + Source/CommonFramework/Tools/StatAccumulator.cpp + Source/CommonFramework/Tools/StatAccumulator.h + Source/CommonFramework/Tools/VideoStream.cpp + Source/CommonFramework/Tools/VideoStream.h + Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.cpp + Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.h + Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp + Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h + Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp + Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h + Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp + Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h + Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h + Source/CommonFramework/VideoPipeline/CameraInfo.h + Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h + Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp + Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h + Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.cpp + Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h + Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp + Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.h + Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp + Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h + Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp + Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h + Source/CommonFramework/VideoPipeline/VideoFeed.h + Source/CommonFramework/VideoPipeline/VideoOverlay.cpp + Source/CommonFramework/VideoPipeline/VideoOverlay.h + Source/CommonFramework/VideoPipeline/VideoOverlayOption.cpp + Source/CommonFramework/VideoPipeline/VideoOverlayOption.h + Source/CommonFramework/VideoPipeline/VideoOverlayScopes.h + Source/CommonFramework/VideoPipeline/VideoOverlaySession.cpp + Source/CommonFramework/VideoPipeline/VideoOverlaySession.h + Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp + Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h + Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h + Source/CommonFramework/VideoPipeline/VideoSession.cpp + Source/CommonFramework/VideoPipeline/VideoSession.h + Source/CommonFramework/VideoPipeline/VideoSource.cpp + Source/CommonFramework/VideoPipeline/VideoSource.h + Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp + Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h + Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp + Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h + Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp + Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h + Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp + Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h + Source/CommonFramework/Windows/ButtonDiagram.cpp + Source/CommonFramework/Windows/ButtonDiagram.h + Source/CommonFramework/Windows/DpiScaler.cpp + Source/CommonFramework/Windows/DpiScaler.h + Source/CommonFramework/Windows/MainWindow.cpp + Source/CommonFramework/Windows/MainWindow.h + Source/CommonFramework/Windows/WindowTracker.cpp + Source/CommonFramework/Windows/WindowTracker.h + Source/CommonTools/Async/InferenceRoutines.cpp + Source/CommonTools/Async/InferenceRoutines.h + Source/CommonTools/Async/InferenceSession.cpp + Source/CommonTools/Async/InferenceSession.h + Source/CommonTools/Async/InterruptableCommands.h + Source/CommonTools/Async/InterruptableCommands.tpp + Source/CommonTools/Async/SuperControlSession.h + Source/CommonTools/Async/SuperControlSession.tpp + Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp + Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h + Source/CommonTools/Audio/AudioTemplateCache.cpp + Source/CommonTools/Audio/AudioTemplateCache.h + Source/CommonTools/Audio/SpectrogramMatcher.cpp + Source/CommonTools/Audio/SpectrogramMatcher.h + Source/CommonTools/DetectionDebouncer.h + Source/CommonTools/FailureWatchdog.h + Source/CommonTools/GlobalInferenceRunner.cpp + Source/CommonTools/GlobalInferenceRunner.h + Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp + Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h + Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp + Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h + Source/CommonTools/ImageMatch/ExactImageMatcher.cpp + Source/CommonTools/ImageMatch/ExactImageMatcher.h + Source/CommonTools/ImageMatch/FilterToAlpha.cpp + Source/CommonTools/ImageMatch/FilterToAlpha.h + Source/CommonTools/ImageMatch/ImageCropper.cpp + Source/CommonTools/ImageMatch/ImageCropper.h + Source/CommonTools/ImageMatch/ImageMatchOption.cpp + Source/CommonTools/ImageMatch/ImageMatchOption.h + Source/CommonTools/ImageMatch/ImageMatchResult.cpp + Source/CommonTools/ImageMatch/ImageMatchResult.h + Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp + Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h + Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp + Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h + Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp + Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h + Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp + Source/CommonTools/Images/BinaryImage_FilterRgb32.h + Source/CommonTools/Images/ColorClustering.cpp + Source/CommonTools/Images/ColorClustering.h + Source/CommonTools/Images/DistanceToLine.h + Source/CommonTools/Images/ImageFilter.cpp + Source/CommonTools/Images/ImageFilter.h + Source/CommonTools/Images/ImageGradient.cpp + Source/CommonTools/Images/ImageGradient.h + Source/CommonTools/Images/ImageManip.cpp + Source/CommonTools/Images/ImageManip.h + Source/CommonTools/Images/ImageTools.cpp + Source/CommonTools/Images/ImageTools.h + Source/CommonTools/Images/SolidColorTest.cpp + Source/CommonTools/Images/SolidColorTest.h + Source/CommonTools/Images/WaterfillUtilities.cpp + Source/CommonTools/Images/WaterfillUtilities.h + Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h + Source/CommonTools/InferenceCallbacks/InferenceCallback.h + Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp + Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h + Source/CommonTools/InferencePivots/AudioInferencePivot.cpp + Source/CommonTools/InferencePivots/AudioInferencePivot.h + Source/CommonTools/InferencePivots/VisualInferencePivot.cpp + Source/CommonTools/InferencePivots/VisualInferencePivot.h + Source/CommonTools/InferenceThrottler.h + Source/CommonTools/MultiConsoleErrors.cpp + Source/CommonTools/MultiConsoleErrors.h + Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp + Source/CommonTools/OCR/OCR_DictionaryMatcher.h + Source/CommonTools/OCR/OCR_DictionaryOCR.cpp + Source/CommonTools/OCR/OCR_DictionaryOCR.h + Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp + Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h + Source/CommonTools/OCR/OCR_NumberReader.cpp + Source/CommonTools/OCR/OCR_NumberReader.h + Source/CommonTools/OCR/OCR_RawOCR.cpp + Source/CommonTools/OCR/OCR_RawOCR.h + Source/CommonTools/OCR/OCR_Routines.cpp + Source/CommonTools/OCR/OCR_Routines.h + Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp + Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h + Source/CommonTools/OCR/OCR_StringMatchResult.cpp + Source/CommonTools/OCR/OCR_StringMatchResult.h + Source/CommonTools/OCR/OCR_StringNormalization.cpp + Source/CommonTools/OCR/OCR_StringNormalization.h + Source/CommonTools/OCR/OCR_TextMatcher.cpp + Source/CommonTools/OCR/OCR_TextMatcher.h + Source/CommonTools/OCR/OCR_TrainingTools.cpp + Source/CommonTools/OCR/OCR_TrainingTools.h + Source/CommonTools/Options/LanguageOCROption.cpp + Source/CommonTools/Options/LanguageOCROption.h + Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp + Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h + Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp + Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h + Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp + Source/CommonTools/Options/QtWidgets/StringSelectWidget.h + Source/CommonTools/Options/ScreenWatchOption.cpp + Source/CommonTools/Options/ScreenWatchOption.h + Source/CommonTools/Options/StringSelectOption.cpp + Source/CommonTools/Options/StringSelectOption.h + Source/CommonTools/Options/StringSelectTableOption.h + Source/CommonTools/Options/TrainOCRModeOption.h + Source/CommonTools/Resources/SpriteDatabase.cpp + Source/CommonTools/Resources/SpriteDatabase.h + Source/CommonTools/StartupChecks/StartProgramChecks.cpp + Source/CommonTools/StartupChecks/StartProgramChecks.h + Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp + Source/CommonTools/StartupChecks/VideoResolutionCheck.h + Source/CommonTools/TrendInference/AnomalyDetector.cpp + Source/CommonTools/TrendInference/AnomalyDetector.h + Source/CommonTools/TrendInference/TimeWindowStatTracker.h + Source/CommonTools/VisualDetector.h + Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp + Source/CommonTools/VisualDetectors/BlackBorderDetector.h + Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp + Source/CommonTools/VisualDetectors/BlackScreenDetector.h + Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp + Source/CommonTools/VisualDetectors/FrozenImageDetector.h + Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp + Source/CommonTools/VisualDetectors/ImageMatchDetector.h + Source/ComputerPrograms/ComputerProgram.cpp + Source/ComputerPrograms/ComputerProgram.h + Source/ComputerPrograms/Framework/ComputerProgramOption.cpp + Source/ComputerPrograms/Framework/ComputerProgramOption.h + Source/ComputerPrograms/Framework/ComputerProgramSession.cpp + Source/ComputerPrograms/Framework/ComputerProgramSession.h + Source/ComputerPrograms/Framework/ComputerProgramWidget.cpp + Source/ComputerPrograms/Framework/ComputerProgramWidget.h + Source/Controllers/Controller.h + Source/Controllers/ControllerCapability.cpp + Source/Controllers/ControllerCapability.h + Source/Controllers/ControllerConnection.cpp + Source/Controllers/ControllerConnection.h + Source/Controllers/ControllerDescriptor.cpp + Source/Controllers/ControllerDescriptor.h + Source/Controllers/ControllerSelectorWidget.cpp + Source/Controllers/ControllerSelectorWidget.h + Source/Controllers/ControllerSession.cpp + Source/Controllers/ControllerSession.h + Source/Controllers/ControllerTypeStrings.cpp + Source/Controllers/ControllerTypeStrings.h + Source/Controllers/ControllerTypes.h + Source/Controllers/JoystickTools.h + Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp + Source/Controllers/KeyboardInput/GlobalQtKeyMap.h + Source/Controllers/KeyboardInput/KeyboardInput.cpp + Source/Controllers/KeyboardInput/KeyboardInput.h + Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp + Source/Controllers/KeyboardInput/KeyboardStateTracker.h + Source/Controllers/NullController.cpp + Source/Controllers/NullController.h + Source/Controllers/SerialPABotBase/SerialPABotBase.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase.h + Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h + Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h + Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h + Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h + Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h + Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp + Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h + Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h + Source/Controllers/SuperscalarScheduler.cpp + Source/Controllers/SuperscalarScheduler.h + Source/Integrations/DiscordIntegrationSettings.cpp + Source/Integrations/DiscordIntegrationSettings.h + Source/Integrations/DiscordIntegrationTable.cpp + Source/Integrations/DiscordIntegrationTable.h + Source/Integrations/DiscordSettingsOption.cpp + Source/Integrations/DiscordSettingsOption.h + Source/Integrations/DiscordWebhook.cpp + Source/Integrations/DiscordWebhook.h + Source/Integrations/DiscordWebhookSettings.cpp + Source/Integrations/DiscordWebhookSettings.h + Source/Integrations/DppIntegration/DppClient.cpp + Source/Integrations/DppIntegration/DppClient.h + Source/Integrations/DppIntegration/DppCommandHandler.cpp + Source/Integrations/DppIntegration/DppCommandHandler.h + Source/Integrations/DppIntegration/DppUtility.cpp + Source/Integrations/DppIntegration/DppUtility.h + Source/Integrations/IntegrationsAPI.cpp + Source/Integrations/IntegrationsAPI.h + Source/Integrations/ProgramTracker.cpp + Source/Integrations/ProgramTracker.h + Source/Integrations/SleepyDiscordRunner.cpp + Source/Integrations/SleepyDiscordRunner.h + Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp + Source/Kernels/AbsFFT/Kernels_AbsFFT.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_Default.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_AVX2.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_SSE41.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_AVX2.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_SSE41.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_BitReverse.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_Butterflies.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexScalar.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexToAbs.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexVector.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_Default.cpp + Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp + Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp + Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.tpp + Source/Kernels/AbsFFT/Kernels_AbsFFT_Reductions.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.h + Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.tpp + Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.cpp + Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h + Source/Kernels/AudioStreamConversion/AudioStreamConversion.cpp + Source/Kernels/AudioStreamConversion/AudioStreamConversion.h + Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_Default.cpp + Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x4_Default.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_arm64_NEON.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Routines.h + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h + Source/Kernels/BinaryImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x16_x64_AVX2.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x32_x64_AVX512.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x64_x64_AVX512.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_x64_SSE42.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_Debugging.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x4_Default.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64xH_Default.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_arm64_NEON.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h + Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrix.h + Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h + Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.tpp + Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h + Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.tpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Default.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_Default.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_arm64_NEON.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.h + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_Default.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_Default.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp + Source/Kernels/Kernels_Alignment.h + Source/Kernels/Kernels_BitScan.h + Source/Kernels/Kernels_BitSet.h + Source/Kernels/Kernels_arm64_NEON.h + Source/Kernels/Kernels_x64_AVX2.h + Source/Kernels/Kernels_x64_AVX512.h + Source/Kernels/Kernels_x64_SSE41.h + Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h + Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h + Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_Default.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Routines.h + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.h + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_Default.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Routines.h + Source/Kernels/Waterfill/Kernels_Waterfill.cpp + Source/Kernels/Waterfill/Kernels_Waterfill.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h + Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h + Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h + Source/Kernels/Waterfill/Kernels_Waterfill_Routines.h + Source/Kernels/Waterfill/Kernels_Waterfill_Session.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Session.h + Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp + Source/Kernels/Waterfill/Kernels_Waterfill_Types.h + Source/ML/DataLabeling/SegmentAnythingModel.cpp + Source/ML/DataLabeling/SegmentAnythingModel.h + Source/ML/ML_Panels.cpp + Source/ML/ML_Panels.h + Source/ML/Programs/ML_LabelImages.cpp + Source/ML/Programs/ML_LabelImages.h + Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp + Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h + Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp + Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h + Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp + Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h + Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h + Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h + Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h + Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h + Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h + Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h + Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp + Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp + Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h + Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h + Source/NintendoSwitch/DevPrograms/BoxDraw.cpp + Source/NintendoSwitch/DevPrograms/BoxDraw.h + Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp + Source/NintendoSwitch/DevPrograms/JoyconProgram.h + Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp + Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h + Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp + Source/NintendoSwitch/DevPrograms/TestProgramComputer.h + Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp + Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h + Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h + Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h + Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h + Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.cpp + Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h + Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp + Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h + Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp + Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.h + Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.cpp + Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h + Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp + Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h + Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp + Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h + Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.h + Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h + Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp + Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h + Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp + Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h + Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp + Source/NintendoSwitch/NintendoSwitch_ConsoleState.h + Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp + Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h + Source/NintendoSwitch/NintendoSwitch_Panels.cpp + Source/NintendoSwitch/NintendoSwitch_Panels.h + Source/NintendoSwitch/NintendoSwitch_Settings.cpp + Source/NintendoSwitch/NintendoSwitch_Settings.h + Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp + Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h + Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp + Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h + Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.cpp + Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h + Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.cpp + Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h + Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h + Source/NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h + Source/NintendoSwitch/Options/TurboMacroTable.cpp + Source/NintendoSwitch/Options/TurboMacroTable.h + Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.cpp + Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.h + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp + Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp + Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp + Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h + Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h + Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.h + Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h + Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h + Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.h + Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.h + Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.h + Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.h + Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.h + Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.h + Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.h + Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.cpp + Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.h + Source/PanelLists.cpp + Source/PanelLists.h + Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp + Source/Pokemon/Inference/Pokemon_BerryNameReader.h + Source/Pokemon/Inference/Pokemon_BoxGenderDetector.cpp + Source/Pokemon/Inference/Pokemon_BoxGenderDetector.h + Source/Pokemon/Inference/Pokemon_IvJudgeReader.cpp + Source/Pokemon/Inference/Pokemon_IvJudgeReader.h + Source/Pokemon/Inference/Pokemon_NameReader.cpp + Source/Pokemon/Inference/Pokemon_NameReader.h + Source/Pokemon/Inference/Pokemon_NatureReader.cpp + Source/Pokemon/Inference/Pokemon_NatureReader.h + Source/Pokemon/Inference/Pokemon_PokeballNameReader.cpp + Source/Pokemon/Inference/Pokemon_PokeballNameReader.h + Source/Pokemon/Inference/Pokemon_ReadHpBar.cpp + Source/Pokemon/Inference/Pokemon_ReadHpBar.h + Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.cpp + Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h + Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.cpp + Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h + Source/Pokemon/Options/Pokemon_EncounterBotOptions.h + Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp + Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h + Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp + Source/Pokemon/Options/Pokemon_IvJudgeOption.h + Source/Pokemon/Options/Pokemon_NameSelectOption.cpp + Source/Pokemon/Options/Pokemon_NameSelectOption.h + Source/Pokemon/Options/Pokemon_NameSelectWidget.cpp + Source/Pokemon/Options/Pokemon_NameSelectWidget.h + Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp + Source/Pokemon/Options/Pokemon_StatsHuntFilter.h + Source/Pokemon/Pokemon_DataTypes.h + Source/Pokemon/Pokemon_EncounterStats.cpp + Source/Pokemon/Pokemon_EncounterStats.h + Source/Pokemon/Pokemon_IvJudge.cpp + Source/Pokemon/Pokemon_IvJudge.h + Source/Pokemon/Pokemon_NatureChecker.cpp + Source/Pokemon/Pokemon_NatureChecker.h + Source/Pokemon/Pokemon_Notification.cpp + Source/Pokemon/Pokemon_Notification.h + Source/Pokemon/Pokemon_ShinySparkleSet.cpp + Source/Pokemon/Pokemon_ShinySparkleSet.h + Source/Pokemon/Pokemon_StatsCalculation.cpp + Source/Pokemon/Pokemon_StatsCalculation.h + Source/Pokemon/Pokemon_Strings.cpp + Source/Pokemon/Pokemon_Strings.h + Source/Pokemon/Pokemon_Types.cpp + Source/Pokemon/Pokemon_Types.h + Source/Pokemon/Pokemon_Xoroshiro128Plus.cpp + Source/Pokemon/Pokemon_Xoroshiro128Plus.h + Source/Pokemon/Resources/Pokemon_BerryNames.cpp + Source/Pokemon/Resources/Pokemon_BerryNames.h + Source/Pokemon/Resources/Pokemon_BerrySprites.cpp + Source/Pokemon/Resources/Pokemon_BerrySprites.h + Source/Pokemon/Resources/Pokemon_EggSteps.cpp + Source/Pokemon/Resources/Pokemon_EggSteps.h + Source/Pokemon/Resources/Pokemon_PokeballNames.cpp + Source/Pokemon/Resources/Pokemon_PokeballNames.h + Source/Pokemon/Resources/Pokemon_PokemonForms.cpp + Source/Pokemon/Resources/Pokemon_PokemonForms.h + Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.cpp + Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.h + Source/Pokemon/Resources/Pokemon_PokemonNames.cpp + Source/Pokemon/Resources/Pokemon_PokemonNames.h + Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp + Source/Pokemon/Resources/Pokemon_PokemonSlugs.h + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.cpp + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.cpp + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.cpp + Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.cpp + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.cpp + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.cpp + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.cpp + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.cpp + Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h + Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h + Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h + Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h + Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h + Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h + Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h + Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h + Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.cpp + Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h + Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.cpp + Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h + Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp + Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h + Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.cpp + Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.cpp + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.h + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.cpp + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.cpp + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.h + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.cpp + Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.h + Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.cpp + Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.h + Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.cpp + Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.h + Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.cpp + Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.h + Source/PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h + Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h + Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp + Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h + Source/PokemonBDSP/Panels_PokemonBDSP.cpp + Source/PokemonBDSP/Panels_PokemonBDSP.h + Source/PokemonBDSP/PokemonBDSP_Panels.cpp + Source/PokemonBDSP/PokemonBDSP_Panels.h + Source/PokemonBDSP/PokemonBDSP_Settings.cpp + Source/PokemonBDSP/PokemonBDSP_Settings.h + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.h + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.cpp + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.cpp + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.h + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.cpp + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.h + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp + Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.cpp + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.cpp + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.h + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.cpp + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.h + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.cpp + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.cpp + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.cpp + Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.h + Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.cpp + Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.h + Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.cpp + Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.h + Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.cpp + Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h + Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.cpp + Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h + Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.cpp + Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h + Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h + Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h + Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h + Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h + Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.h + Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h + Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h + Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h + Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.cpp + Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.cpp + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.cpp + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.cpp + Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.h + Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.cpp + Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h + Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.cpp + Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.h + Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.cpp + Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.h + Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.cpp + Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.h + Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.cpp + Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.h + Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.cpp + Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h + Source/PokemonHome/Inference/PokemonHome_BallReader.cpp + Source/PokemonHome/Inference/PokemonHome_BallReader.h + Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp + Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h + Source/PokemonHome/Options/PokemonHome_BoxSortingTable.cpp + Source/PokemonHome/Options/PokemonHome_BoxSortingTable.h + Source/PokemonHome/PokemonHome_Panels.cpp + Source/PokemonHome/PokemonHome_Panels.h + Source/PokemonHome/PokemonHome_Settings.cpp + Source/PokemonHome/PokemonHome_Settings.h + Source/PokemonHome/Programs/PokemonHome_BoxSorting.cpp + Source/PokemonHome/Programs/PokemonHome_BoxSorting.h + Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp + Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h + Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp + Source/PokemonHome/Programs/PokemonHome_PageSwap.h + Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp + Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h + Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp + Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.h + Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.cpp + Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h + Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.cpp + Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h + Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.cpp + Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h + Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.cpp + Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h + Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.cpp + Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h + Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.cpp + Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.h + Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.cpp + Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h + Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.cpp + Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h + Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.cpp + Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h + Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.cpp + Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h + Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.cpp + Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h + Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.cpp + Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h + Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp + Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h + Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h + Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.cpp + Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h + Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.cpp + Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.h + Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.cpp + Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.h + Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.cpp + Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.h + Source/PokemonLA/Inference/PokemonLA_DialogDetector.cpp + Source/PokemonLA/Inference/PokemonLA_DialogDetector.h + Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.cpp + Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h + Source/PokemonLA/Inference/PokemonLA_MountDetector.cpp + Source/PokemonLA/Inference/PokemonLA_MountDetector.h + Source/PokemonLA/Inference/PokemonLA_NotificationReader.cpp + Source/PokemonLA/Inference/PokemonLA_NotificationReader.h + Source/PokemonLA/Inference/PokemonLA_OverworldDetector.cpp + Source/PokemonLA/Inference/PokemonLA_OverworldDetector.h + Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.cpp + Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h + Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.cpp + Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.h + Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.cpp + Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h + Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.cpp + Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h + Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.cpp + Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h + Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.cpp + Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h + Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.cpp + Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h + Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.cpp + Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h + Source/PokemonLA/Options/PokemonLA_CustomPathTable.cpp + Source/PokemonLA/Options/PokemonLA_CustomPathTable.h + Source/PokemonLA/Options/PokemonLA_IngoOpponent.cpp + Source/PokemonLA/Options/PokemonLA_IngoOpponent.h + Source/PokemonLA/Options/PokemonLA_MiscOptions.h + Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.cpp + Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.h + Source/PokemonLA/Options/PokemonLA_TradeCountTable.cpp + Source/PokemonLA/Options/PokemonLA_TradeCountTable.h + Source/PokemonLA/Options/PokemonLA_TravelLocation.cpp + Source/PokemonLA/Options/PokemonLA_TravelLocation.h + Source/PokemonLA/Panels_PokemonLA.cpp + Source/PokemonLA/Panels_PokemonLA.h + Source/PokemonLA/PokemonLA_Locations.cpp + Source/PokemonLA/PokemonLA_Locations.h + Source/PokemonLA/PokemonLA_Panels.cpp + Source/PokemonLA/PokemonLA_Panels.h + Source/PokemonLA/PokemonLA_Settings.cpp + Source/PokemonLA/PokemonLA_Settings.h + Source/PokemonLA/PokemonLA_TravelLocations.cpp + Source/PokemonLA/PokemonLA_TravelLocations.h + Source/PokemonLA/PokemonLA_WeatherAndTime.cpp + Source/PokemonLA/PokemonLA_WeatherAndTime.h + Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.cpp + Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.h + Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.cpp + Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.h + Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.cpp + Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h + Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.cpp + Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.h + Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.cpp + Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.h + Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.cpp + Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.h + Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.cpp + Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.h + Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.cpp + Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.h + Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.cpp + Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.h + Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.cpp + Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.h + Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp + Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h + Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.cpp + Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.h + Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.cpp + Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.h + Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.cpp + Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h + Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.cpp + Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.h + Source/PokemonLA/Programs/PokemonLA_BattleRoutines.cpp + Source/PokemonLA/Programs/PokemonLA_BattleRoutines.h + Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.cpp + Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.h + Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.cpp + Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.h + Source/PokemonLA/Programs/PokemonLA_GameEntry.cpp + Source/PokemonLA/Programs/PokemonLA_GameEntry.h + Source/PokemonLA/Programs/PokemonLA_GameSave.cpp + Source/PokemonLA/Programs/PokemonLA_GameSave.h + Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.cpp + Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.h + Source/PokemonLA/Programs/PokemonLA_MountChange.cpp + Source/PokemonLA/Programs/PokemonLA_MountChange.h + Source/PokemonLA/Programs/PokemonLA_RegionNavigation.cpp + Source/PokemonLA/Programs/PokemonLA_RegionNavigation.h + Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.cpp + Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.cpp + Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h + Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.cpp + Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.h + Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.cpp + Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.h + Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.cpp + Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.h + Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.cpp + Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.h + Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.cpp + Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.h + Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.cpp + Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.h + Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.cpp + Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.h + Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp + Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.h + Source/PokemonLA/Resources/PokemonLA_NameDatabase.cpp + Source/PokemonLA/Resources/PokemonLA_NameDatabase.h + Source/PokemonLA/Resources/PokemonLA_PokemonInfo.cpp + Source/PokemonLA/Resources/PokemonLA_PokemonInfo.h + Source/PokemonLA/Resources/PokemonLA_PokemonSprites.cpp + Source/PokemonLA/Resources/PokemonLA_PokemonSprites.h + Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.cpp + Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h + Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp + Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h + Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp + Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h + Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp + Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h + Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp + Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h + Source/PokemonLGPE/PokemonLGPE_Panels.cpp + Source/PokemonLGPE/PokemonLGPE_Panels.h + Source/PokemonLGPE/PokemonLGPE_Settings.cpp + Source/PokemonLGPE/PokemonLGPE_Settings.h + Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp + Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h + Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp + Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp + Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h + Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp + Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h + Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.cpp + Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.h + Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp + Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h + Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp + Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h + Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp + Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h + Source/PokemonRSE/PokemonRSE_Navigation.cpp + Source/PokemonRSE/PokemonRSE_Navigation.h + Source/PokemonRSE/PokemonRSE_Panels.cpp + Source/PokemonRSE/PokemonRSE_Panels.h + Source/PokemonRSE/PokemonRSE_Settings.cpp + Source/PokemonRSE/PokemonRSE_Settings.h + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp + Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h + Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp + Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h + Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h + Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h + Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h + Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h + Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h + Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp + Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h + Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h + Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.cpp + Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h + Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp + Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h + Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp + Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h + Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.cpp + Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp + Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h + Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp + Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h + Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.cpp + Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h + Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.cpp + Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.h + Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.cpp + Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h + Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.cpp + Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h + Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h + Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp + Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h + Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp + Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.cpp + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.cpp + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.cpp + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.cpp + Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h + Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.cpp + Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h + Source/PokemonSV/Inference/PokemonSV_BagDetector.cpp + Source/PokemonSV/Inference/PokemonSV_BagDetector.h + Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.cpp + Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h + Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.cpp + Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h + Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.cpp + Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.h + Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.cpp + Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h + Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.cpp + Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.h + Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp + Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h + Source/PokemonSV/Inference/PokemonSV_MoneyReader.cpp + Source/PokemonSV/Inference/PokemonSV_MoneyReader.h + Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.cpp + Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.h + Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp + Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h + Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.cpp + Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h + Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.cpp + Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.h + Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.cpp + Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h + Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.cpp + Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h + Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp + Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h + Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.cpp + Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h + Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.cpp + Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h + Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp + Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h + Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp + Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h + Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.cpp + Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h + Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.cpp + Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h + Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.cpp + Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.h + Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.cpp + Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.h + Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.cpp + Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.h + Source/PokemonSV/Options/PokemonSV_AuctionItemTable.cpp + Source/PokemonSV/Options/PokemonSV_AuctionItemTable.h + Source/PokemonSV/Options/PokemonSV_AutoHostOptions.h + Source/PokemonSV/Options/PokemonSV_BBQOption.cpp + Source/PokemonSV/Options/PokemonSV_BBQOption.h + Source/PokemonSV/Options/PokemonSV_BattleMoveTable.cpp + Source/PokemonSV/Options/PokemonSV_BattleMoveTable.h + Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.cpp + Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h + Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.cpp + Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.h + Source/PokemonSV/Options/PokemonSV_EncounterBotCommon.h + Source/PokemonSV/Options/PokemonSV_PlayerList.cpp + Source/PokemonSV/Options/PokemonSV_PlayerList.h + Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.cpp + Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.h + Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.cpp + Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.h + Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.cpp + Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.h + Source/PokemonSV/Options/PokemonSV_SinglesAIOption.cpp + Source/PokemonSV/Options/PokemonSV_SinglesAIOption.h + Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.cpp + Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.h + Source/PokemonSV/Options/PokemonSV_TeraAIOption.cpp + Source/PokemonSV/Options/PokemonSV_TeraAIOption.h + Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.cpp + Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h + Source/PokemonSV/Options/PokemonSV_TeraMoveTable.cpp + Source/PokemonSV/Options/PokemonSV_TeraMoveTable.h + Source/PokemonSV/Options/PokemonSV_TeraRollFilter.cpp + Source/PokemonSV/Options/PokemonSV_TeraRollFilter.h + Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.cpp + Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.h + Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.cpp + Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.h + Source/PokemonSV/PokemonSV_Panels.cpp + Source/PokemonSV/PokemonSV_Panels.h + Source/PokemonSV/PokemonSV_Settings.cpp + Source/PokemonSV/PokemonSV_Settings.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp + Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h + Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h + Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.cpp + Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h + Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp + Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h + Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.cpp + Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h + Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.cpp + Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h + Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp + Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h + Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp + Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h + Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.cpp + Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.h + Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.cpp + Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.h + Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp + Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h + Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.cpp + Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.h + Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp + Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.h + Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp + Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h + Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h + Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h + Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.h + Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h + Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h + Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.cpp + Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.h + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.cpp + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.cpp + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.cpp + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp + Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h + Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.cpp + Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h + Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.cpp + Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.h + Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.cpp + Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.h + Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.cpp + Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.h + Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.cpp + Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.h + Source/PokemonSV/Programs/General/PokemonSV_StatsReset.cpp + Source/PokemonSV/Programs/General/PokemonSV_StatsReset.h + Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.cpp + Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.h + Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.cpp + Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.h + Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.cpp + Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.h + Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp + Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.cpp + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.h + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.cpp + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp + Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h + Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp + Source/PokemonSV/Programs/PokemonSV_AreaZero.h + Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.cpp + Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.h + Source/PokemonSV/Programs/PokemonSV_GameEntry.cpp + Source/PokemonSV/Programs/PokemonSV_GameEntry.h + Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp + Source/PokemonSV/Programs/PokemonSV_MenuNavigation.h + Source/PokemonSV/Programs/PokemonSV_SaveGame.cpp + Source/PokemonSV/Programs/PokemonSV_SaveGame.h + Source/PokemonSV/Programs/PokemonSV_Terarium.cpp + Source/PokemonSV/Programs/PokemonSV_Terarium.h + Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp + Source/PokemonSV/Programs/PokemonSV_WorldNavigation.h + Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp + Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h + Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp + Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h + Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp + Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp + Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.cpp + Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h + Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.cpp + Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.h + Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.cpp + Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.h + Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.cpp + Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h + Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.cpp + Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.h + Source/PokemonSV/Resources/PokemonSV_FillingsCoordinates.h + Source/PokemonSV/Resources/PokemonSV_Ingredients.cpp + Source/PokemonSV/Resources/PokemonSV_Ingredients.h + Source/PokemonSV/Resources/PokemonSV_ItemSprites.cpp + Source/PokemonSV/Resources/PokemonSV_ItemSprites.h + Source/PokemonSV/Resources/PokemonSV_NameDatabase.cpp + Source/PokemonSV/Resources/PokemonSV_NameDatabase.h + Source/PokemonSV/Resources/PokemonSV_PokemonSprites.cpp + Source/PokemonSV/Resources/PokemonSV_PokemonSprites.h + Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.cpp + Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp + Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.cpp + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.cpp + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.cpp + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.cpp + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.cpp + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.cpp + Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.cpp + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.cpp + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.cpp + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.cpp + Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h + Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h + Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h + Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h + Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h + Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h + Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h + Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h + Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.cpp + Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h + Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.cpp + Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.cpp + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.cpp + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.cpp + Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h + Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.cpp + Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h + Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.cpp + Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h + Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.cpp + Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h + Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.cpp + Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectItem.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectMove.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectPath.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectStarter.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapCatch.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapProfessor.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.cpp + Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.h + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.cpp + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.cpp + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.cpp + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.cpp + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h + Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.cpp + Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.cpp + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.cpp + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.h + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.cpp + Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h + Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.cpp + Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.h + Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.cpp + Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.h + Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.cpp + Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.cpp + Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.h + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.cpp + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.cpp + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.h + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.cpp + Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.h + Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.cpp + Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h + Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp + Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h + Source/PokemonSwSh/Options/PokemonSwSh_Catchability.h + Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.cpp + Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h + Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.cpp + Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.h + Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.cpp + Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.h + Source/PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h + Source/PokemonSwSh/Options/PokemonSwSh_RegiSelector.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.h + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.cpp + Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.h + Source/PokemonSwSh/PokemonSwSh_Panels.cpp + Source/PokemonSwSh/PokemonSwSh_Panels.h + Source/PokemonSwSh/PokemonSwSh_Settings.cpp + Source/PokemonSwSh/PokemonSwSh_Settings.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp + Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperStats.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.h + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.cpp + Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombinedShared.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp + Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.h + Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp + Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.cpp + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.cpp + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.cpp + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.cpp + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.cpp + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h + Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_LobbyWait.h + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.cpp + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.cpp + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.cpp + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.cpp + Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.h + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.cpp + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.h + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.cpp + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.h + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.cpp + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.cpp + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.h + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp + Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h + Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h + Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h + Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h + Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h + Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.h + Source/PokemonSwSh/Programs/PokemonSwSh_Internet.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_Internet.h + Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h + Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.h + Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h + Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.cpp + Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.h + Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.cpp + Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h + Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.cpp + Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.cpp + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.cpp + Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.cpp + Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp + Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h + Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.cpp + Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h + Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h + Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h + Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h + Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h + Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h + Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h + Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.cpp + Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h + Source/PokemonSwSh/ShinyHuntTracker.cpp + Source/PokemonSwSh/ShinyHuntTracker.h + Source/Tests/CommandLineTests.cpp + Source/Tests/CommandLineTests.h + Source/Tests/CommonFramework_Tests.cpp + Source/Tests/CommonFramework_Tests.h + Source/Tests/Kernels_Tests.cpp + Source/Tests/Kernels_Tests.h + Source/Tests/NintendoSwitch_Tests.cpp + Source/Tests/NintendoSwitch_Tests.h + Source/Tests/PokemonLA_Tests.cpp + Source/Tests/PokemonLA_Tests.h + Source/Tests/PokemonLZA_Tests.cpp + Source/Tests/PokemonLZA_Tests.h + Source/Tests/PokemonSV_Tests.cpp + Source/Tests/PokemonSV_Tests.h + Source/Tests/PokemonSwSh_Tests.cpp + Source/Tests/PokemonSwSh_Tests.h + Source/Tests/TestMap.cpp + Source/Tests/TestMap.h + Source/Tests/TestUtils.cpp + Source/Tests/TestUtils.h + Source/ZeldaTotK/Programs/ZeldaTotK_BowItemDuper.cpp + Source/ZeldaTotK/Programs/ZeldaTotK_BowItemDuper.h + Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.cpp + Source/ZeldaTotK/Programs/ZeldaTotK_MineruItemDuper.h + Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.cpp + Source/ZeldaTotK/Programs/ZeldaTotK_ParaglideItemDuper.h + Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.cpp + Source/ZeldaTotK/Programs/ZeldaTotK_SurfItemDuper.h + Source/ZeldaTotK/Programs/ZeldaTotK_WeaponDuper.cpp + Source/ZeldaTotK/Programs/ZeldaTotK_WeaponDuper.h + Source/ZeldaTotK/ZeldaTotK_Panels.cpp + Source/ZeldaTotK/ZeldaTotK_Panels.h + Source/ZeldaTotK/ZeldaTotK_Settings.cpp + Source/ZeldaTotK/ZeldaTotK_Settings.h +) +source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR}../../ FILES ${MAIN_SOURCES}) + +if (APPLE) + set(SerialPrograms_ICON ${CMAKE_CURRENT_SOURCE_DIR}/../IconResource/icon.icns) + # set_source_files_properties(SerialPrograms_ICON PROPERTIES MACOSX_PACKAGE_LOCATION "Resources") + + # Links on how to create a MacOS app bundle with cmake + # https://stackoverflow.com/questions/53560288/how-to-create-a-macos-app-bundle-with-cmake + # https://cmake.org/cmake/help/latest/command/add_executable.html + add_executable(SerialPrograms MACOSX_BUNDLE ${SerialPrograms_ICON} ${MAIN_SOURCES}) + set_target_properties(SerialPrograms PROPERTIES + BUNDLE True + MACOSX_BUNDLE_GUI_IDENTIFIER PokemonAutomation.SerialPrograms + MACOSX_BUNDLE_BUNDLE_NAME SerialPrograms + MACOSX_BUNDLE_BUNDLE_VERSION "0.1" + MACOSX_BUNDLE_SHORT_VERSION_STRING "0.1" + MACOSX_BUNDLE_ICON_FILE "icon.icns" + # MacOSXBundleInfo.plist.in is modified from https://github.com/Kitware/CMake/blob/master/Modules/MacOSXBundleInfo.plist.in + MACOSX_BUNDLE_INFO_PLIST ${CMAKE_SOURCE_DIR}/cmake/MacOSXBundleInfo.plist.in + RESOURCE ${SerialPrograms_ICON} + ) + + # make sure Packages repo, https://github.com/PokemonAutomation/Packages is placed in the same folder as this Arduino-Source repo + # so the post-build command can copy the resources folder Packages/SerialPrograms/Resources/ into the built app bundle: + string(FIND "${CMAKE_CURRENT_SOURCE_DIR}" "Arduino-Source-Internal" internal_repro_position) # determine if this is an internal repo + if (internal_repro_position EQUAL -1) # no "Arduino-Source-Internal" substr in the current source dir + # we are building the public repo + set(RESOURCES_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../Packages/SerialPrograms/Resources") + else() + # we are building the internal repo + set(RESOURCES_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../../../../Packages/SerialPrograms/Resources") + endif() + message(STATUS "Set Resources folder path from Packages repo: ${RESOURCES_PATH}") + add_custom_command( + TARGET SerialPrograms + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_directory + "${RESOURCES_PATH}" + "$/../Resources" + ) +else() # WIN and Linux: + add_executable(SerialPrograms WIN32 ${MAIN_SOURCES}) +endif() + +set_target_properties(SerialPrograms PROPERTIES LINKER_LANGUAGE CXX) +target_link_libraries(SerialPrograms PRIVATE Qt${QT_MAJOR}::Widgets Qt${QT_MAJOR}::SerialPort Qt${QT_MAJOR}::Multimedia Qt${QT_MAJOR}::MultimediaWidgets) +target_link_libraries(SerialPrograms PRIVATE Threads::Threads) + +#add defines +target_compile_definitions(SerialPrograms PRIVATE NOMINMAX) + +if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/../../Internal/SerialPrograms/Internal0.cpp") + target_compile_definitions(SerialPrograms PRIVATE PA_OFFICIAL) + target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.cpp) + target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.h) + target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/Internal0.cpp) + target_sources(SerialPrograms PRIVATE ../../Internal/SerialPrograms/Internal1.cpp) +endif() + +#extract opencv_world4110d.dll from archive on Windows Debug builds +if (MSVC) + file(ARCHIVE_EXTRACT + INPUT ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/opencv_world4110d.zip + DESTINATION ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/ + ) +endif() + +#add include directory +target_include_directories(SerialPrograms SYSTEM PRIVATE ../3rdParty/) +target_include_directories(SerialPrograms PRIVATE ../ ../../Internal/ Source/) +target_link_directories(SerialPrograms PRIVATE ../3rdPartyBinaries/) + + + + +if (MSVC) + add_library(OpenCV_lib IMPORTED UNKNOWN) + target_include_directories(SerialPrograms SYSTEM PRIVATE ../3rdParty/opencv-4.11.0/) + set_target_properties(OpenCV_lib PROPERTIES + IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/opencv_world4110.lib + IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/opencv_world4110d.lib) + set_target_properties(OpenCV_lib PROPERTIES + MAP_IMPORTED_CONFIG_DEBUG DEBUG + MAP_IMPORTED_CONFIG_RELEASE RELEASE + MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE + MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE + ) + + add_library(ONNX_lib IMPORTED UNKNOWN) + target_include_directories(SerialPrograms SYSTEM PRIVATE ../3rdParty/ONNX/) + set_target_properties(ONNX_lib PROPERTIES + IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime.lib + IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime.lib) + set_target_properties(ONNX_lib PROPERTIES + MAP_IMPORTED_CONFIG_DEBUG DEBUG + MAP_IMPORTED_CONFIG_RELEASE RELEASE + MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE + MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE + ) + + add_library(ONNX_Providers_lib IMPORTED UNKNOWN) + set_target_properties(ONNX_Providers_lib PROPERTIES + IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime_providers_shared.lib + IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/onnxruntime_providers_shared.lib) + set_target_properties(ONNX_Providers_lib PROPERTIES + MAP_IMPORTED_CONFIG_DEBUG DEBUG + MAP_IMPORTED_CONFIG_RELEASE RELEASE + MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE + MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE + ) + + add_library(dpp_lib IMPORTED UNKNOWN) + set_target_properties(dpp_lib PROPERTIES + IMPORTED_LOCATION_RELEASE ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/dpp.lib + IMPORTED_LOCATION_DEBUG ${CMAKE_CURRENT_SOURCE_DIR}/../3rdPartyBinaries/dppd.lib) + set_target_properties(dpp_lib PROPERTIES + MAP_IMPORTED_CONFIG_DEBUG DEBUG + MAP_IMPORTED_CONFIG_RELEASE RELEASE + MAP_IMPORTED_CONFIG_RELWITHDEBINFO RELEASE + MAP_IMPORTED_CONFIG_MINSIZEREL RELEASE + ) + + target_link_libraries( + SerialPrograms PRIVATE + tesseractPA.lib + OpenCV_lib + ONNX_lib + ONNX_Providers_lib + Sleepy.lib + dpp_lib + ) + target_compile_definitions( + SerialPrograms PRIVATE + _CRT_SECURE_NO_WARNINGS + _DISABLE_CONSTEXPR_MUTEX_CONSTRUCTOR + PA_TESSERACT + PA_SLEEPY + PA_DPP + ) + + target_compile_options(SerialPrograms PRIVATE /FAs /FaAssembly/ /MP /W4 /WX /external:anglebrackets /external:W0 /utf-8) + target_compile_options(SerialPrograms PRIVATE /wd5054) # Deprecated enum arithemtic + target_compile_options(SerialPrograms PRIVATE /wd4505) # unreferenced local function has been removed + + set(ARCH_FLAGS_09_Nehalem /W4) # Dummy parameter + set(ARCH_FLAGS_13_Haswell /arch:AVX2) + set(ARCH_FLAGS_17_Skylake /arch:AVX512) + set(ARCH_FLAGS_19_IceLake /arch:AVX512) + + # Run-time ISA dispatching + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_08_Nehalem) + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_13_Haswell) + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_17_Skylake) + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_19_IceLake) + +# target_compile_options(SerialPrograms PRIVATE /arch:AVX2 /DPA_Arch_x64_AVX2) +# target_compile_options(SerialPrograms PRIVATE /arch:AVX512 /DPA_Arch_x64_AVX512) +# target_compile_options(SerialPrograms PRIVATE /arch:AVX512 /DPA_Arch_x64_AVX512GF) +else() # macOS and Linux + if (APPLE) + # Get root path where Homebrew installs libraries. Example root path: "/opt/homebrew/", + # where you can find libraries in "/opt/homebrew/lib/" and headers in "/opt/homebrew/include/". + # CMake does not support ONNX Runtime, so we have to add ONNX Runtime paths on our own. + # Save the root path as CMake variable HOMEBREW_PREFIX. + execute_process(COMMAND brew --prefix OUTPUT_VARIABLE HOMEBREW_PREFIX OUTPUT_STRIP_TRAILING_WHITESPACE) + + # Get ONNX Runtime paths + target_include_directories(SerialPrograms PRIVATE ${HOMEBREW_PREFIX}/include/onnxruntime) + target_link_libraries(SerialPrograms PRIVATE ${HOMEBREW_PREFIX}/lib/libonnxruntime.dylib) + else() # Linux + # Instructions took from https://github.com/microsoft/onnxruntime/discussions/6489 + # Step 1: Download the file + file(DOWNLOAD + https://github.com/microsoft/onnxruntime/releases/download/v1.22.0/onnxruntime-linux-x64-1.22.0.tgz + ${CMAKE_BINARY_DIR}/onnxruntime-linux-x64-1.22.0.tgz + SHOW_PROGRESS + ) + + # Step 2: Extract the archive + execute_process( + COMMAND tar -xzf onnxruntime-linux-x64-1.22.0.tgz + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + ) + + # Step 3: Copy files to /usr/local + execute_process( + COMMAND sudo cp -r ${CMAKE_BINARY_DIR}/onnxruntime-linux-x64-1.22.0/include /usr/local/ + ) + execute_process( + COMMAND sudo cp -r ${CMAKE_BINARY_DIR}/onnxruntime-linux-x64-1.22.0/lib /usr/local/ + ) + + # Step 4: Run ldconfig + execute_process( + COMMAND sudo ldconfig + WORKING_DIRECTORY /usr/local/lib + ) + + # Link against ONNX Runtime + target_link_libraries(SerialPrograms PRIVATE onnxruntime) + endif() + + # Find OpenCV + # set(OPENCV_DIR, "/usr/local/opt/opencv/lib/cmake/opencv4") + find_package(OpenCV REQUIRED HINTS "/usr/local/opt/opencv/lib/cmake/opencv4/") + # set(ENV{PKG_CONFIG_PATH} "$ENV{PKG_CONFIG_PATH}:/usr/local/opt/opencv/lib/pkgconfig") + # pkg_search_module(OPENCV REQUIRED opencv) + include_directories(${OpenCV_INCLUDE_DIRS}) + link_directories(${OpenCV_LIBRARY_DIRS}) + target_link_libraries(SerialPrograms PRIVATE ${OpenCV_LIBS}) + + #we hope to use our own Tesseract build in future so we can rid that dependency + #but right now to run on Linux and Mac we need to use external Tesseract library + if (UNIX_LINK_TESSERACT) + find_package(PkgConfig REQUIRED) + target_compile_definitions(SerialPrograms PRIVATE PA_TESSERACT UNIX_LINK_TESSERACT) + pkg_search_module(TESSERACT REQUIRED tesseract) + pkg_search_module(LEPTONICA REQUIRED lept) + include_directories(${TESSERACT_INCLUDE_DIRS}) + include_directories(${LEPTONICA_INCLUDE_DIRS}) + link_directories(${TESSERACT_LIBRARY_DIRS}) + link_directories(${LEPTONICA_LIBRARY_DIRS}) + target_link_libraries(SerialPrograms PRIVATE ${TESSERACT_LINK_LIBRARIES}) + target_link_libraries(SerialPrograms PRIVATE ${LEPTONICA_LINK_LIBRARIES}) + endif() + + # enable dpp integration + if ((APPLE) AND (CMAKE_SYSTEM_PROCESSOR MATCHES "(arm64)|(ARM64)")) + add_library(libdpp STATIC IMPORTED) + set_target_properties(libdpp PROPERTIES + IMPORTED_LOCATION ../3rdPartyBinaries/libdpp_macos_arm64.a + INTERFACE_COMPILE_DEFINITIONS "PA_DPP" + INTERFACE_LINK_LIBRARIES "-L/opt/homebrew/lib -lssl -lcrypto -lopus -lsodium -lz" # add dpp's deps + ) + target_link_libraries(SerialPrograms PRIVATE libdpp) + endif() + + if (APPLE) + # Add -Wno-c11-extensions to avoid clang gives + # /usr/local/Cellar/opencv/4.5.5_3/include/opencv4/opencv2/core/mat.inl.hpp:2116:9: error: '_Atomic' is a C11 extension + # when compiling OpenCV + # target_compile_options(SerialPrograms PRIVATE -Wall -Wextra -Wpedantic -Werror -Wno-c11-extensions) + target_compile_options(SerialPrograms PRIVATE -Wall -Wextra -Wpedantic -Werror -Wshorten-64-to-32) + else() + # Assume GCC + target_compile_options(SerialPrograms PRIVATE -Wall -Wextra -Wpedantic -Werror -fno-strict-aliasing) + endif() + + # Set OS-specific flags + if (WIN32) + elseif (APPLE) + # on macOS, need this framework to query OS API to control display sleep and system sleep behavior + target_link_libraries(SerialPrograms PRIVATE "-framework IOKit -framework CoreFoundation") + elseif(UNIX) + endif() + + IF(${CMAKE_SYSTEM_PROCESSOR} MATCHES "arm") + # Arm CPU + # Run-time ISA dispatching + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_arm64_20_M1) + + else() + # Intel CPU + target_compile_options(SerialPrograms PRIVATE -msse4.2) + set(ARCH_FLAGS_09_Nehalem -march=nehalem) + set(ARCH_FLAGS_13_Haswell -march=haswell) + set(ARCH_FLAGS_17_Skylake -march=skylake-avx512) + set(ARCH_FLAGS_19_IceLake -march=icelake-client) + + # Run-time ISA dispatching + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_08_Nehalem) + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_13_Haswell) + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_17_Skylake) + target_compile_definitions(SerialPrograms PRIVATE PA_AutoDispatch_x64_19_IceLake) + + endif() +endif() + + + +# Run-time CPU dispatching. + +if (ARCH_FLAGS_09_Nehalem) +SET_SOURCE_FILES_PROPERTIES( + Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp + Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp + PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_09_Nehalem} +) +endif() +if (ARCH_FLAGS_13_Haswell) +SET_SOURCE_FILES_PROPERTIES( + Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp + PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_13_Haswell} +) +endif() +if (ARCH_FLAGS_17_Skylake) +SET_SOURCE_FILES_PROPERTIES( + Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp + Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp + Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp + Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp + Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp + Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp + Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp + Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp + Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp + PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_17_Skylake} +) +endif() +if (ARCH_FLAGS_19_IceLake) +SET_SOURCE_FILES_PROPERTIES( + Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp + Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp + PROPERTIES COMPILE_FLAGS ${ARCH_FLAGS_19_IceLake} +) +endif() + + + + +if (WIN32) +#copy needed dlls +#file(COPY *.dll DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +file(GLOB MY_DLLS + "../3rdPartyBinaries/*.dll" +) +file(COPY ${MY_DLLS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) +endif() + +if (QT_MAJOR GREATER_EQUAL 6) + qt_finalize_target(SerialPrograms) +endif() diff --git a/SerialPrograms/Cleanup.cmd b/SerialPrograms/Cleanup.cmd index 17008ad81d..797c53e77f 100644 --- a/SerialPrograms/Cleanup.cmd +++ b/SerialPrograms/Cleanup.cmd @@ -1,24 +1,24 @@ -del .qmake.stash -del *.log -del Makefile* -del object_script.* -del users* -del SerialPrograms.pro.user* -del *Settings.json -del *.png -del *.jpg -del *.dll -del CMakeLists.txt.user - -copy CMakeLists.txt CMakeLists.txt.tmp -del *.txt -move CMakeLists.txt.tmp CMakeLists.txt - -rd /s /q "debug\" -rd /s /q "release\" -rd /s /q "SerialPrograms\" -rd /s /q "ErrorDumps\" -rd /s /q "UserSettings\" - -::rd /s /q "..\build-SerialPrograms*" -rd /s /q "build\" +del .qmake.stash +del *.log +del Makefile* +del object_script.* +del users* +del SerialPrograms.pro.user* +del *Settings.json +del *.png +del *.jpg +del *.dll +del CMakeLists.txt.user + +copy CMakeLists.txt CMakeLists.txt.tmp +del *.txt +move CMakeLists.txt.tmp CMakeLists.txt + +rd /s /q "debug\" +rd /s /q "release\" +rd /s /q "SerialPrograms\" +rd /s /q "ErrorDumps\" +rd /s /q "UserSettings\" + +::rd /s /q "..\build-SerialPrograms*" +rd /s /q "build\" diff --git a/SerialPrograms/README.md b/SerialPrograms/README.md index 0c560b5c91..5e59999e37 100644 --- a/SerialPrograms/README.md +++ b/SerialPrograms/README.md @@ -1,27 +1,27 @@ -# Serial Programs - -Source code for the "Computer Control" programs. - -[](https://discord.gg/cQ4gWxN) - -## How to Build - -Currently, we build with Qt 6.8.3. But we still retain compatibility with Qt 5.12. - -**Windows:** - -- [How to Build (Qt 6.8.3) - Windows](BuildInstructions/Build-Windows-Qt6.8.3.md) -- [How to Build (Qt 6.8.2) - Windows](BuildInstructions/Build-Windows-Qt6.8.2.md) -- [How to Build (Qt 6.8.1) - Windows](BuildInstructions/Build-Windows-Qt6.8.1.md) -- [How to Build (Qt 6.8.0) - Windows](BuildInstructions/Build-Windows-Qt6.8.0.md) -- [How to Build (Qt 6.7.3) - Windows](BuildInstructions/Build-Windows-Qt6.7.3.md) -- [How to Build (Qt 6.5.3) - Windows](BuildInstructions/Build-Windows-Qt6.5.3.md) -- [How to Build (Qt 6.3.2) - Windows](BuildInstructions/Build-Windows-Qt6.3.2.md) -- [How to Build (Qt 5.12) - Windows](BuildInstructions/Build-Windows-Qt5.12.md) - - -**Ubuntu Linux:** - -This doesn't actually work. (flickering video display) But here are the instructions for setting it up anyway. - -- [How to Build (Qt 6.8.2) - Ubuntu](BuildInstructions/Build-Ubuntu-Qt6.8.2.md) +# Serial Programs + +Source code for the "Computer Control" programs. + +[](https://discord.gg/cQ4gWxN) + +## How to Build + +Currently, we build with Qt 6.8.3. But we still retain compatibility with Qt 5.12. + +**Windows:** + +- [How to Build (Qt 6.8.3) - Windows](BuildInstructions/Build-Windows-Qt6.8.3.md) +- [How to Build (Qt 6.8.2) - Windows](BuildInstructions/Build-Windows-Qt6.8.2.md) +- [How to Build (Qt 6.8.1) - Windows](BuildInstructions/Build-Windows-Qt6.8.1.md) +- [How to Build (Qt 6.8.0) - Windows](BuildInstructions/Build-Windows-Qt6.8.0.md) +- [How to Build (Qt 6.7.3) - Windows](BuildInstructions/Build-Windows-Qt6.7.3.md) +- [How to Build (Qt 6.5.3) - Windows](BuildInstructions/Build-Windows-Qt6.5.3.md) +- [How to Build (Qt 6.3.2) - Windows](BuildInstructions/Build-Windows-Qt6.3.2.md) +- [How to Build (Qt 5.12) - Windows](BuildInstructions/Build-Windows-Qt5.12.md) + + +**Ubuntu Linux:** + +This doesn't actually work. (flickering video display) But here are the instructions for setting it up anyway. + +- [How to Build (Qt 6.8.2) - Ubuntu](BuildInstructions/Build-Ubuntu-Qt6.8.2.md) diff --git a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp index 38a68fd358..2bdd30e3d7 100644 --- a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp +++ b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.cpp @@ -1,91 +1,91 @@ -/* Program Name - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "GameName_ProgramName.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace GameName{ - - -ProgramName_Descriptor::ProgramName_Descriptor() - : SingleSwitchProgramDescriptor( - "GameName:ProgramName", - "Game Name", "Program Name", - "ComputerControl/blob/master/Wiki/Programs/GameName/ProgramName.md", - ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ProgramName_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Attempts"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_attempts; - std::atomic& m_errors; -}; -std::unique_ptr ProgramName_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ProgramName::ProgramName() - : GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void ProgramName::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - ProgramName_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 100); - - try{ - - } catch(OperationFailedException&){ - stats.m_errors++; - env.update_stats(); - throw; - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Program Name + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "GameName_ProgramName.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace GameName{ + + +ProgramName_Descriptor::ProgramName_Descriptor() + : SingleSwitchProgramDescriptor( + "GameName:ProgramName", + "Game Name", "Program Name", + "ComputerControl/blob/master/Wiki/Programs/GameName/ProgramName.md", + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ProgramName_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Attempts"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_attempts; + std::atomic& m_errors; +}; +std::unique_ptr ProgramName_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ProgramName::ProgramName() + : GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void ProgramName::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + ProgramName_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 100); + + try{ + + } catch(OperationFailedException&){ + stats.m_errors++; + env.update_stats(); + throw; + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h index c3fadc92de..251c8de7a3 100644 --- a/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h +++ b/SerialPrograms/Scripts/CodeTemplates/Program/GameName_ProgramName.h @@ -1,51 +1,51 @@ -/* Program Name - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_GameName_ProgramName_H -#define PokemonAutomation_GameName_ProgramName_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace GameName{ - - -class ProgramName_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ProgramName_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ProgramName : public SingleSwitchProgramInstance{ -public: - ProgramName(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - -private: - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Program Name + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_GameName_ProgramName_H +#define PokemonAutomation_GameName_ProgramName_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace GameName{ + + +class ProgramName_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ProgramName_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ProgramName : public SingleSwitchProgramInstance{ +public: + ProgramName(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + +private: + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.cpp b/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.cpp index 6c62e34d6f..ec7ae41f04 100644 --- a/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.cpp +++ b/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.cpp @@ -1,123 +1,123 @@ -/* Object Name Detector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/WaterfillUtilities.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "GameName_ObjectNameDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace GameName{ - - -class ObjectNameMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - ObjectNameMatcher() : WaterfillTemplateMatcher( - "GameName/ObjectName-Template.png", Color(100,100,100), Color(255, 255, 255), 50 - ) { - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.1; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance() { - static ObjectNameMatcher matcher; - return matcher; - } -}; - - -ObjectNameDetector::~ObjectNameDetector() = default; - -ObjectNameDetector::ObjectNameDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} - -void ObjectNameDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool ObjectNameDetector::detect(const ImageViewRGB32& screen) const{ - std::vector hits = detect_all(screen); - return !hits.empty(); -} - -std::vector ObjectNameDetector::detect_all(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} - }; - - const double min_object_size = 5000.0; - const double rmsd_threshold = 60.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - ObjectNameMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return false; - } - ); - - return found_locations; -} - - - -ObjectNameWatcher::~ObjectNameWatcher() = default; - -ObjectNameWatcher::ObjectNameWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("ObjectNameWatcher") - , m_overlay(overlay) - , m_detector(color, box) -{} - -void ObjectNameWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool ObjectNameWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - std::vector hits = m_detector.detect_all(screen); - - m_hits.reset(hits.size()); - for (const ImageFloatBox& hit : hits){ - m_hits.emplace_back(m_overlay, hit, COLOR_MAGENTA); - } - return !hits.empty(); -} - - - - - - - - -} -} -} +/* Object Name Detector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/WaterfillUtilities.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "GameName_ObjectNameDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace GameName{ + + +class ObjectNameMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + ObjectNameMatcher() : WaterfillTemplateMatcher( + "GameName/ObjectName-Template.png", Color(100,100,100), Color(255, 255, 255), 50 + ) { + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.1; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance() { + static ObjectNameMatcher matcher; + return matcher; + } +}; + + +ObjectNameDetector::~ObjectNameDetector() = default; + +ObjectNameDetector::ObjectNameDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} + +void ObjectNameDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool ObjectNameDetector::detect(const ImageViewRGB32& screen) const{ + std::vector hits = detect_all(screen); + return !hits.empty(); +} + +std::vector ObjectNameDetector::detect_all(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} + }; + + const double min_object_size = 5000.0; + const double rmsd_threshold = 60.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + ObjectNameMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return false; + } + ); + + return found_locations; +} + + + +ObjectNameWatcher::~ObjectNameWatcher() = default; + +ObjectNameWatcher::ObjectNameWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("ObjectNameWatcher") + , m_overlay(overlay) + , m_detector(color, box) +{} + +void ObjectNameWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool ObjectNameWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + std::vector hits = m_detector.detect_all(screen); + + m_hits.reset(hits.size()); + for (const ImageFloatBox& hit : hits){ + m_hits.emplace_back(m_overlay, hit, COLOR_MAGENTA); + } + return !hits.empty(); +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.h b/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.h index 8c2add460d..2ee9805737 100644 --- a/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.h +++ b/SerialPrograms/Scripts/CodeTemplates/VisualDetector/GameName_ObjectNameDetector.h @@ -1,66 +1,66 @@ -/* Object Name Detector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_GameName_ObjectNameDetector_H -#define PokemonAutomation_GameName_ObjectNameDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/InferenceInfra/VisualInferenceCallback.h" -#include "CommonFramework/Inference/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace GameName{ - - -class ObjectNameDetector : public StaticScreenDetector{ -public: - ObjectNameDetector(Color color, const ImageFloatBox& box); - virtual ~ObjectNameDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) const override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - -protected: - Color m_color; - ImageFloatBox m_box; -}; - - - -class ObjectNameWatcher : public VisualInferenceCallback{ -public: - ObjectNameWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box); - virtual ~ObjectNameWatcher(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - -protected: - VideoOverlay& m_overlay; - ObjectNameDetector m_detector; - FixedLimitVector m_hits; -}; - - - - -} -} -} -#endif +/* Object Name Detector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_GameName_ObjectNameDetector_H +#define PokemonAutomation_GameName_ObjectNameDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/InferenceInfra/VisualInferenceCallback.h" +#include "CommonFramework/Inference/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace GameName{ + + +class ObjectNameDetector : public StaticScreenDetector{ +public: + ObjectNameDetector(Color color, const ImageFloatBox& box); + virtual ~ObjectNameDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) const override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + +protected: + Color m_color; + ImageFloatBox m_box; +}; + + + +class ObjectNameWatcher : public VisualInferenceCallback{ +public: + ObjectNameWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box); + virtual ~ObjectNameWatcher(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + +protected: + VideoOverlay& m_overlay; + ObjectNameDetector m_detector; + FixedLimitVector m_hits; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Scripts/add_new_file.py b/SerialPrograms/Scripts/add_new_file.py index bba2c7e2af..8e0e1b7269 100755 --- a/SerialPrograms/Scripts/add_new_file.py +++ b/SerialPrograms/Scripts/add_new_file.py @@ -1,166 +1,166 @@ -#!/usr/bin/python3 - -""" -Add a new file to CMakeList.txt and SerialPrograms.pro - -Usage: python3 add_new_file.py 1: - target_path = sys.argv[1] - print(f"Adding a new file path {target_path}") - -# Sanitize target path: -SerialPrograms_prefix = "SerialPrograms/" -if target_path.startswith(SerialPrograms_prefix): - target_path = target_path[len(SerialPrograms_prefix):] -Common_prefix = "Common/" -if target_path.startswith(Common_prefix) or target_path.startswith("ClientSource") or target_path.startswith("3rdParty"): - target_path = "../" + target_path - -cur_folder_path = os.path.abspath(os.getcwd()) - -# print(cur_folder_path) - -split_path = cur_folder_path.split(os.sep) - -code_root_pos = split_path.index('Arduino-Source') -code_root_path = os.sep.join(split_path[0:code_root_pos+1]) -# print(code_root_path) - - -def read_lines(file_path: str) -> List[str]: - with open(file_path, "r") as f: - file_lines = f.readlines() - file_lines = [line.rstrip() for line in file_lines] - return file_lines - -def get_code_file_range(file_lines: List[str], starting_line: str, ending_line: str) -> Tuple[int, int]: - """ - ... - - code_line_1.cpp - code_line_2.cpp - - ... - - Return the tuple of indices (start, end) in the input `file_lines` so that code lines can be found - by file_lines[start:end] - """ - code_file_list_start_pos = file_lines.index(starting_line) + 1 - code_file_list_end_pos = code_file_list_start_pos - for line_no in range(code_file_list_start_pos, len(file_lines)): - line = file_lines[line_no] - if line == ending_line: - code_file_list_end_pos = line_no - break - return code_file_list_start_pos, code_file_list_end_pos - - - -cmakelists_path = os.path.join(code_root_path, "SerialPrograms", "CMakeLists.txt") -pro_path = os.path.join(code_root_path, "SerialPrograms", "SerialPrograms.pro") -print(f"CMakeLists path: {cmakelists_path}") -print(f"QT Pro project file path: {pro_path}") - -file_lines = read_lines(cmakelists_path) -old_file_lines = file_lines - -code_file_start, code_file_end = get_code_file_range(file_lines, "file(GLOB MAIN_SOURCES", ")") -code_file_lines = set(file_lines[code_file_start:code_file_end]) -old_num_code_files = len(code_file_lines) -print(f"{old_num_code_files} lines from CMakeLists are for code file paths") - -# Add new file -if len(target_path) > 0: - code_file_lines.add(" " + target_path) - -code_file_lines = list(code_file_lines) -code_file_lines.sort() -if len(code_file_lines) == old_num_code_files: - print("Warning: you are adding an existing file! The added file is ignored") - -# print(f"\"{code_file_lines[0]}\"") - -file_lines = file_lines[0:code_file_start] + code_file_lines + file_lines[code_file_end:] -file_lines = [line + "\r\n" for line in file_lines] -with open(cmakelists_path, "w") as f: - f.writelines(file_lines) -print(f"Writed changes back to {cmakelists_path}") - -if not os.path.exists(pro_path): - print(f"Pro file not found. End.") - exit(0) - -file_lines = read_lines(pro_path) - -# print("\n".join(file_lines[0:70])) - -# lines = [line for line in file_lines if line.startswith("SOURCES")] -# print(lines) - - -def process_pro_lines(file_lines: List[str], starting_line: str, new_path: str) -> List[str]: - - code_file_start, code_file_end = get_code_file_range(file_lines, starting_line, "") - # print(code_file_start, code_file_end) - # print(f"Starting line {file_lines[code_file_start]}") - - code_file_lines = file_lines[code_file_start:code_file_end] - - code_file_lines = [ line[0:-1].rstrip() if line.endswith("\\") else line for line in code_file_lines] - - if len(new_path) > 0: - code_file_lines.append(" " + new_path) - - # Remove duplicates and sort - code_file_lines = list(set(code_file_lines)) - code_file_lines.sort() - - # Add back " \\": - code_file_lines = [line + " \\" for line in code_file_lines] - code_file_lines[-1] = code_file_lines[-1][0:-2] - - # print("\n".join(code_file_lines[0:10])) - - file_lines = file_lines[0:code_file_start] + code_file_lines + file_lines[code_file_end:] - - return file_lines - -if target_path.endswith(".cpp"): - file_lines = process_pro_lines(file_lines, "SOURCES += \\", target_path) -elif target_path.endswith(".h") or target_path.endswith(".tpp"): - file_lines = process_pro_lines(file_lines, "HEADERS += \\", target_path) -else: - file_lines = process_pro_lines(file_lines, "SOURCES += \\", "") - file_lines = process_pro_lines(file_lines, "HEADERS += \\", "") - -# print("\n".join(file_lines[0:30])) - -# Add back CRLF -file_lines = [line + "\r\n" for line in file_lines] - -with open(pro_path, "w") as f: - f.writelines(file_lines) -print(f"Writed changes back to {pro_path}") - - - - +#!/usr/bin/python3 + +""" +Add a new file to CMakeList.txt and SerialPrograms.pro + +Usage: python3 add_new_file.py 1: + target_path = sys.argv[1] + print(f"Adding a new file path {target_path}") + +# Sanitize target path: +SerialPrograms_prefix = "SerialPrograms/" +if target_path.startswith(SerialPrograms_prefix): + target_path = target_path[len(SerialPrograms_prefix):] +Common_prefix = "Common/" +if target_path.startswith(Common_prefix) or target_path.startswith("ClientSource") or target_path.startswith("3rdParty"): + target_path = "../" + target_path + +cur_folder_path = os.path.abspath(os.getcwd()) + +# print(cur_folder_path) + +split_path = cur_folder_path.split(os.sep) + +code_root_pos = split_path.index('Arduino-Source') +code_root_path = os.sep.join(split_path[0:code_root_pos+1]) +# print(code_root_path) + + +def read_lines(file_path: str) -> List[str]: + with open(file_path, "r") as f: + file_lines = f.readlines() + file_lines = [line.rstrip() for line in file_lines] + return file_lines + +def get_code_file_range(file_lines: List[str], starting_line: str, ending_line: str) -> Tuple[int, int]: + """ + ... + + code_line_1.cpp + code_line_2.cpp + + ... + + Return the tuple of indices (start, end) in the input `file_lines` so that code lines can be found + by file_lines[start:end] + """ + code_file_list_start_pos = file_lines.index(starting_line) + 1 + code_file_list_end_pos = code_file_list_start_pos + for line_no in range(code_file_list_start_pos, len(file_lines)): + line = file_lines[line_no] + if line == ending_line: + code_file_list_end_pos = line_no + break + return code_file_list_start_pos, code_file_list_end_pos + + + +cmakelists_path = os.path.join(code_root_path, "SerialPrograms", "CMakeLists.txt") +pro_path = os.path.join(code_root_path, "SerialPrograms", "SerialPrograms.pro") +print(f"CMakeLists path: {cmakelists_path}") +print(f"QT Pro project file path: {pro_path}") + +file_lines = read_lines(cmakelists_path) +old_file_lines = file_lines + +code_file_start, code_file_end = get_code_file_range(file_lines, "file(GLOB MAIN_SOURCES", ")") +code_file_lines = set(file_lines[code_file_start:code_file_end]) +old_num_code_files = len(code_file_lines) +print(f"{old_num_code_files} lines from CMakeLists are for code file paths") + +# Add new file +if len(target_path) > 0: + code_file_lines.add(" " + target_path) + +code_file_lines = list(code_file_lines) +code_file_lines.sort() +if len(code_file_lines) == old_num_code_files: + print("Warning: you are adding an existing file! The added file is ignored") + +# print(f"\"{code_file_lines[0]}\"") + +file_lines = file_lines[0:code_file_start] + code_file_lines + file_lines[code_file_end:] +file_lines = [line + "\r\n" for line in file_lines] +with open(cmakelists_path, "w") as f: + f.writelines(file_lines) +print(f"Writed changes back to {cmakelists_path}") + +if not os.path.exists(pro_path): + print(f"Pro file not found. End.") + exit(0) + +file_lines = read_lines(pro_path) + +# print("\n".join(file_lines[0:70])) + +# lines = [line for line in file_lines if line.startswith("SOURCES")] +# print(lines) + + +def process_pro_lines(file_lines: List[str], starting_line: str, new_path: str) -> List[str]: + + code_file_start, code_file_end = get_code_file_range(file_lines, starting_line, "") + # print(code_file_start, code_file_end) + # print(f"Starting line {file_lines[code_file_start]}") + + code_file_lines = file_lines[code_file_start:code_file_end] + + code_file_lines = [ line[0:-1].rstrip() if line.endswith("\\") else line for line in code_file_lines] + + if len(new_path) > 0: + code_file_lines.append(" " + new_path) + + # Remove duplicates and sort + code_file_lines = list(set(code_file_lines)) + code_file_lines.sort() + + # Add back " \\": + code_file_lines = [line + " \\" for line in code_file_lines] + code_file_lines[-1] = code_file_lines[-1][0:-2] + + # print("\n".join(code_file_lines[0:10])) + + file_lines = file_lines[0:code_file_start] + code_file_lines + file_lines[code_file_end:] + + return file_lines + +if target_path.endswith(".cpp"): + file_lines = process_pro_lines(file_lines, "SOURCES += \\", target_path) +elif target_path.endswith(".h") or target_path.endswith(".tpp"): + file_lines = process_pro_lines(file_lines, "HEADERS += \\", target_path) +else: + file_lines = process_pro_lines(file_lines, "SOURCES += \\", "") + file_lines = process_pro_lines(file_lines, "HEADERS += \\", "") + +# print("\n".join(file_lines[0:30])) + +# Add back CRLF +file_lines = [line + "\r\n" for line in file_lines] + +with open(pro_path, "w") as f: + f.writelines(file_lines) +print(f"Writed changes back to {pro_path}") + + + + diff --git a/SerialPrograms/Scripts/build_code_from_template.py b/SerialPrograms/Scripts/build_code_from_template.py index a3fa9032db..9d0a81d79c 100644 --- a/SerialPrograms/Scripts/build_code_from_template.py +++ b/SerialPrograms/Scripts/build_code_from_template.py @@ -1,145 +1,145 @@ -#!Python3 - -""" -Build C++ code from a template file. - -This is used to remove the manual work of creating boilerplate code like visual detector classes. - -Example usage: - -- python3 build_code_from_template.py VisualDetector PokemonSV Map PokeCenter Icon - Generates PokemonSV_MapPokeCenterIconDetector.h and PokemonSV_MapPokeCenterIconDetector.cpp. -- python3 build_code_from_template.py Program PokemonSV Auto Story - Generates PokemonSV_AutoStory.h and PokemonSV_AutoStory.cpp. -""" - -import sys -import os - -from typing import Dict, List - - -def apply_line_replacement(line: str, mapping: Dict[str, str]) -> str: - for source, target in mapping.items(): - line = line.replace(source, target) - return line - - -def build_file_from_template( - mapping: Dict[str, str], - template_folder: str, - template_filename: str, -) -> None: - """ - generate a file from a template file by mapping: template str -> target str - The file is saved at the current working dir. - """ - - file_ext: str = template_filename.split('.')[-1] - template_filepath: str = os.path.join(template_folder, template_filename) - - target_filename: str = apply_line_replacement(template_filename, mapping) - - with open(template_filepath, "r") as f: - lines = f.readlines() - lines = [apply_line_replacement(line, mapping) for line in lines] - - with open(target_filename, "w", newline='\r\n') as f: - f.writelines(lines) - - print(f"Saved template {file_ext} file to {target_filename}") - - -def build_files_from_templates( - mapping: Dict[str, str], - template_folder: str, - template_filenames: List[str], -) -> None: - """ - generate files from template files by a mapping: template str -> target str - The files are saved at the current working dir. - """ - - for filename in template_filenames: - build_file_from_template( - mapping=mapping, - template_folder=template_folder, - template_filename=filename, - ) - - -def create_cpp_class_name(name: str) -> str: - """ - Given a name (e.g. "Three-Segment Dudunsparce Finder"), convert it into a C++ class name (like "ThreeSegmentDudunsparceFinder") - """ - return name.replace(" ", "").replace("-", "").replace("_", "") - - -if len(sys.argv) == 1: - print( - "Usage:\n" - f"python3 {sys.argv[0]} VisualDetector PokemonSV Map PokeCenter Icon" - " - Generates PokemonSV_MapPokeCenterIconDetector.h and PokemonSV_MapPokeCenterIconDetector.cpp" - ) - exit(0) - -cur_folder_path = os.path.abspath(os.getcwd()) - -split_path = cur_folder_path.split(os.sep) - -code_root_pos = split_path.index('Arduino-Source') -code_root_path = os.sep.join(split_path[0:code_root_pos+1]) - -print(f"Found code root folder: {code_root_path}") - -template_folder = os.path.join(code_root_path, "SerialPrograms", "Scripts", "CodeTemplates") -print(f"Template folder: {template_folder}") - -template_folder = os.path.join(template_folder, sys.argv[1]) - -if sys.argv[1] == "VisualDetector": - assert len(sys.argv) >= 4 - game_name = sys.argv[2] # e.g. "PokemonSV" - object_name = " ".join(sys.argv[3:]) # e.g. "Map PokeCenter Icon" - print(f"Building a visual detector for object {object_name} in game {game_name}.") - - mapping = { - "GameName": game_name, - "Object Name": object_name, - "ObjectName": create_cpp_class_name(object_name) - } - - build_files_from_templates( - mapping=mapping, - template_folder=template_folder, - template_filenames=[ - "GameName_ObjectNameDetector.h", - "GameName_ObjectNameDetector.cpp", - ] - ) -elif sys.argv[1] == "Program": - assert len(sys.argv) >= 4 - game_name = sys.argv[2] # e.g. "PokemonSV" - program_name = " ".join(sys.argv[3:]) # e.g. "Auto Story" - print(f"Building a Program with name {program_name} in game {game_name}.") - - mapping = { - "GameName": game_name, - "Program Name": program_name, - "ProgramName": create_cpp_class_name(program_name) - } - - build_files_from_templates( - mapping=mapping, - template_folder=template_folder, - template_filenames=[ - "GameName_ProgramName.h", - "GameName_ProgramName.cpp", - ] - ) - - - - - - +#!Python3 + +""" +Build C++ code from a template file. + +This is used to remove the manual work of creating boilerplate code like visual detector classes. + +Example usage: + +- python3 build_code_from_template.py VisualDetector PokemonSV Map PokeCenter Icon + Generates PokemonSV_MapPokeCenterIconDetector.h and PokemonSV_MapPokeCenterIconDetector.cpp. +- python3 build_code_from_template.py Program PokemonSV Auto Story + Generates PokemonSV_AutoStory.h and PokemonSV_AutoStory.cpp. +""" + +import sys +import os + +from typing import Dict, List + + +def apply_line_replacement(line: str, mapping: Dict[str, str]) -> str: + for source, target in mapping.items(): + line = line.replace(source, target) + return line + + +def build_file_from_template( + mapping: Dict[str, str], + template_folder: str, + template_filename: str, +) -> None: + """ + generate a file from a template file by mapping: template str -> target str + The file is saved at the current working dir. + """ + + file_ext: str = template_filename.split('.')[-1] + template_filepath: str = os.path.join(template_folder, template_filename) + + target_filename: str = apply_line_replacement(template_filename, mapping) + + with open(template_filepath, "r") as f: + lines = f.readlines() + lines = [apply_line_replacement(line, mapping) for line in lines] + + with open(target_filename, "w", newline='\r\n') as f: + f.writelines(lines) + + print(f"Saved template {file_ext} file to {target_filename}") + + +def build_files_from_templates( + mapping: Dict[str, str], + template_folder: str, + template_filenames: List[str], +) -> None: + """ + generate files from template files by a mapping: template str -> target str + The files are saved at the current working dir. + """ + + for filename in template_filenames: + build_file_from_template( + mapping=mapping, + template_folder=template_folder, + template_filename=filename, + ) + + +def create_cpp_class_name(name: str) -> str: + """ + Given a name (e.g. "Three-Segment Dudunsparce Finder"), convert it into a C++ class name (like "ThreeSegmentDudunsparceFinder") + """ + return name.replace(" ", "").replace("-", "").replace("_", "") + + +if len(sys.argv) == 1: + print( + "Usage:\n" + f"python3 {sys.argv[0]} VisualDetector PokemonSV Map PokeCenter Icon" + " - Generates PokemonSV_MapPokeCenterIconDetector.h and PokemonSV_MapPokeCenterIconDetector.cpp" + ) + exit(0) + +cur_folder_path = os.path.abspath(os.getcwd()) + +split_path = cur_folder_path.split(os.sep) + +code_root_pos = split_path.index('Arduino-Source') +code_root_path = os.sep.join(split_path[0:code_root_pos+1]) + +print(f"Found code root folder: {code_root_path}") + +template_folder = os.path.join(code_root_path, "SerialPrograms", "Scripts", "CodeTemplates") +print(f"Template folder: {template_folder}") + +template_folder = os.path.join(template_folder, sys.argv[1]) + +if sys.argv[1] == "VisualDetector": + assert len(sys.argv) >= 4 + game_name = sys.argv[2] # e.g. "PokemonSV" + object_name = " ".join(sys.argv[3:]) # e.g. "Map PokeCenter Icon" + print(f"Building a visual detector for object {object_name} in game {game_name}.") + + mapping = { + "GameName": game_name, + "Object Name": object_name, + "ObjectName": create_cpp_class_name(object_name) + } + + build_files_from_templates( + mapping=mapping, + template_folder=template_folder, + template_filenames=[ + "GameName_ObjectNameDetector.h", + "GameName_ObjectNameDetector.cpp", + ] + ) +elif sys.argv[1] == "Program": + assert len(sys.argv) >= 4 + game_name = sys.argv[2] # e.g. "PokemonSV" + program_name = " ".join(sys.argv[3:]) # e.g. "Auto Story" + print(f"Building a Program with name {program_name} in game {game_name}.") + + mapping = { + "GameName": game_name, + "Program Name": program_name, + "ProgramName": create_cpp_class_name(program_name) + } + + build_files_from_templates( + mapping=mapping, + template_folder=template_folder, + template_filenames=[ + "GameName_ProgramName.h", + "GameName_ProgramName.cpp", + ] + ) + + + + + + diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioConstants.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioConstants.h index 78a89fbfde..1b0a9e54ee 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioConstants.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioConstants.h @@ -1,20 +1,20 @@ -/* Audio Constants - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioConstants_H -#define PokemonAutomation_AudioConstants_H - -#include - -// Largest FFT that is no more than 1/10 of a second. -const int FFT_LENGTH_POWER_OF_TWO = 12; - -const size_t NUM_FFT_SAMPLES = 1 << FFT_LENGTH_POWER_OF_TWO; -//const int NUM_FFT_WINDOWS = 100; -const size_t FFT_SLIDING_WINDOW_STEP = NUM_FFT_SAMPLES/4; - - -#endif +/* Audio Constants + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioConstants_H +#define PokemonAutomation_AudioConstants_H + +#include + +// Largest FFT that is no more than 1/10 of a second. +const int FFT_LENGTH_POWER_OF_TWO = 12; + +const size_t NUM_FFT_SAMPLES = 1 << FFT_LENGTH_POWER_OF_TWO; +//const int NUM_FFT_WINDOWS = 100; +const size_t FFT_SLIDING_WINDOW_STEP = NUM_FFT_SAMPLES/4; + + +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioFeed.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioFeed.h index e1a6df2dd7..eef86233b2 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioFeed.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioFeed.h @@ -1,62 +1,62 @@ -/* Audio Feed Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioFeedInterface_H -#define PokemonAutomation_AudioFeedInterface_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/AlignedVector.h" - -namespace PokemonAutomation{ - -// The result of one FFT computation, an array of the magnitudes of different -// frequencies. -// Each spectrum is computed using a sliding window on the incoming audio stream. -// It has a stamp to denote which window it is from. -class AudioSpectrum{ -public: - // The stamp to denote which audio window it is from. - // the stamp starts at 0 and becomes larger for later windows in the stream. - uint64_t stamp = 0; - - size_t sample_rate; - - // The frequency magnitudes from FFT. The order in the vector is from lower to - // higher frequencies. - std::shared_ptr> magnitudes; - - AudioSpectrum(uint64_t s, size_t rate, std::shared_ptr> m) - : stamp(s) - , sample_rate(rate) - , magnitudes(std::move(m)) - {} -}; - -// Define basic interface of an audio feed to be used by programs or other services. -// All the functions in the interface should be thread safe. -class AudioFeed{ -public: - // Reset the video. Note that this may return early. - virtual void reset() = 0; - - // Return all the spectrums with stamps greater or equal to `starting_stamp` - // Returned spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. - virtual std::vector spectrums_since(uint64_t starting_seqnum) = 0; - - // Return a specific number of latest spectrums. - // Returned spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. - virtual std::vector spectrums_latest(size_t num_last_spectrums) = 0; - - // Add visual overlay to the spectrums starting at `starting_stamp` and before `end_stamp` with `color`. - virtual void add_overlay(uint64_t starting_seqnum, size_t end_seqnum, Color color) = 0; -}; - - - -} -#endif +/* Audio Feed Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioFeedInterface_H +#define PokemonAutomation_AudioFeedInterface_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/AlignedVector.h" + +namespace PokemonAutomation{ + +// The result of one FFT computation, an array of the magnitudes of different +// frequencies. +// Each spectrum is computed using a sliding window on the incoming audio stream. +// It has a stamp to denote which window it is from. +class AudioSpectrum{ +public: + // The stamp to denote which audio window it is from. + // the stamp starts at 0 and becomes larger for later windows in the stream. + uint64_t stamp = 0; + + size_t sample_rate; + + // The frequency magnitudes from FFT. The order in the vector is from lower to + // higher frequencies. + std::shared_ptr> magnitudes; + + AudioSpectrum(uint64_t s, size_t rate, std::shared_ptr> m) + : stamp(s) + , sample_rate(rate) + , magnitudes(std::move(m)) + {} +}; + +// Define basic interface of an audio feed to be used by programs or other services. +// All the functions in the interface should be thread safe. +class AudioFeed{ +public: + // Reset the video. Note that this may return early. + virtual void reset() = 0; + + // Return all the spectrums with stamps greater or equal to `starting_stamp` + // Returned spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. + virtual std::vector spectrums_since(uint64_t starting_seqnum) = 0; + + // Return a specific number of latest spectrums. + // Returned spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. + virtual std::vector spectrums_latest(size_t num_last_spectrums) = 0; + + // Add visual overlay to the spectrums starting at `starting_stamp` and before `end_stamp` with `color`. + virtual void add_overlay(uint64_t starting_seqnum, size_t end_seqnum, Color color) = 0; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp index 71bc015170..696d5bde1e 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.cpp @@ -1,567 +1,567 @@ -/* Audio Input Device Info - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" -#include "AudioInfo.h" - -//#include -//using std::cout; -//using std::endl; - - -#if QT_VERSION_MAJOR == 5 -#include -#elif QT_VERSION_MAJOR == 6 -#include -#include -#else -#error "Unsupported Qt version." -#endif - - -#if QT_VERSION_MAJOR != 5 -#define PA_AUDIO_USE_CHANNEL_CONFIG -#endif - - -namespace PokemonAutomation{ - - - -const char* AUDIO_FORMAT_LABELS[] = { - "(none)", - "1 x 48,000 Hz (Mono)", - "2 x 44,100 Hz (Stereo)", - "2 x 48,000 Hz (Stereo)", - "1 x 96,000 Hz (Mono)", - "1 x 96,000 Hz (Interleaved Stereo L/R)", - "1 x 96,000 Hz (Interleaved Stereo R/L)", -}; - -void set_format(QAudioFormat& native_format, AudioChannelFormat format){ - switch (format){ - case AudioChannelFormat::MONO_48000: -#ifdef PA_AUDIO_USE_CHANNEL_CONFIG - if (native_format.channelConfig() != QAudioFormat::ChannelConfigMono){ - native_format.setChannelConfig(QAudioFormat::ChannelConfigMono); - } -#else - if (native_format.channelCount() != 1){ - native_format.setChannelCount(1); - } -#endif - if (native_format.sampleRate() != 48000){ - native_format.setSampleRate(48000); - } - break; - case AudioChannelFormat::DUAL_44100: -#ifdef PA_AUDIO_USE_CHANNEL_CONFIG - if (native_format.channelConfig() != QAudioFormat::ChannelConfigStereo){ - native_format.setChannelConfig(QAudioFormat::ChannelConfigStereo); - } -#else - if (native_format.channelCount() != 2){ - native_format.setChannelCount(2); - } -#endif - if (native_format.sampleRate() != 44100){ - native_format.setSampleRate(44100); - } - break; - case AudioChannelFormat::DUAL_48000: -#ifdef PA_AUDIO_USE_CHANNEL_CONFIG - if (native_format.channelConfig() != QAudioFormat::ChannelConfigStereo){ - native_format.setChannelConfig(QAudioFormat::ChannelConfigStereo); - } -#else - if (native_format.channelCount() != 2){ - native_format.setChannelCount(2); - } -#endif - if (native_format.sampleRate() != 48000){ - native_format.setSampleRate(48000); - } - break; - case AudioChannelFormat::MONO_96000: - case AudioChannelFormat::INTERLEAVE_LR_96000: - case AudioChannelFormat::INTERLEAVE_RL_96000: -#ifdef PA_AUDIO_USE_CHANNEL_CONFIG - if (native_format.channelConfig() != QAudioFormat::ChannelConfigMono){ - native_format.setChannelConfig(QAudioFormat::ChannelConfigMono); - } -#else - if (native_format.channelCount() != 1){ - native_format.setChannelCount(1); - } -#endif - if (native_format.sampleRate() != 96000){ - native_format.setSampleRate(96000); - } - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); - } -} - -AudioSampleFormat get_sample_format(QAudioFormat& native_format){ -#if QT_VERSION_MAJOR == 5 - if (native_format.sampleType() == QAudioFormat::SampleType::Float){ - return AudioSampleFormat::FLOAT32; - }else if (native_format.sampleType() == QAudioFormat::SampleType::UnSignedInt && native_format.sampleSize() == 8){ - return AudioSampleFormat::UINT8; - }else if (native_format.sampleType() == QAudioFormat::SampleType::SignedInt && native_format.sampleSize() == 16){ - return AudioSampleFormat::SINT16; - }else if (native_format.sampleType() == QAudioFormat::SampleType::SignedInt && native_format.sampleSize() == 32){ - return AudioSampleFormat::SINT32; - }else{ - return AudioSampleFormat::INVALID; - } -#elif QT_VERSION_MAJOR == 6 - switch (native_format.sampleFormat()){ - case QAudioFormat::SampleFormat::Float: - return AudioSampleFormat::FLOAT32; - case QAudioFormat::SampleFormat::UInt8: - return AudioSampleFormat::UINT8; - case QAudioFormat::SampleFormat::Int16: - return AudioSampleFormat::SINT16; - case QAudioFormat::SampleFormat::Int32: - return AudioSampleFormat::SINT32; - default: - return AudioSampleFormat::INVALID; - } -#else -#error "Unknown Qt version." -#endif -} - - -std::string format_to_str(const QAudioFormat& format){ - std::string str; - str += "Preferred Format:\n"; - str += " Channels: " + std::to_string(format.channelCount()) + "\n"; - str += " Sample Rate: " + std::to_string(format.sampleRate()) + "\n"; -#if QT_VERSION_MAJOR == 5 - str += " Sample Format: " + std::to_string(format.sampleType()) + "\n"; -#else - str += " Sample Format: " + std::to_string(format.sampleFormat()) + "\n"; -#endif - return str; -} - - -// Return a list of our formats that are supported by this device. -// "preferred_index" is set to the index of the list that is preferred by the device. -// If no preferred format matches our formats, -1 is returned. -std::vector supported_input_formats(int& preferred_index, const NativeAudioInfo& info, const std::string& display_name){ - QAudioFormat preferred_format = info.preferredFormat(); - - std::string str = display_name + "\n"; - str += format_to_str(preferred_format); - global_logger_tagged().log(str); - -// preferred_format.setSampleSize(16); -// preferred_format.setSampleType(QAudioFormat::SampleType::SignedInt); - - int preferred_channels = preferred_format.channelCount(); - int preferred_rate = preferred_format.sampleRate(); - -#if 0 - cout << "display_name = " << display_name << endl; - cout << "channelCount = " << preferred_format.channelCount() << endl; - cout << "sampleRate = " << preferred_format.sampleRate() << endl; - cout << "sampleFormat = " << (int)preferred_format.sampleFormat() << endl; - cout << "preferred_format = " << info.isFormatSupported(preferred_format) << endl; - - for (const QAudioFormat::SampleFormat& format : info.supportedSampleFormats()){ - cout << "supported format: " << (int)format << endl; - } -#endif - -#if 0 -#if QT_VERSION_MAJOR == 6 || (QT_VERSION_MAJOR == 5 && __GNUC__) - // On Qt6, "QAudioFormat::preferredFormat()" always returns stereo 44.1 kHz. - // Unlike Qt5, it does not return the native format of the device - // This actually makes it kind of impossible to figure out what the correct - // format we need to use to give proper stereo. So instead, we just assume - // mono 96000 which will be the case for standard capture cards. - preferred_channels = 1; - preferred_rate = 96000; -#endif -#endif - - std::vector ret; - preferred_index = -1; - -// bool stereo = false; - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::MONO_48000); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - } - ret.emplace_back(AudioChannelFormat::MONO_48000); - } - } -#if 1 - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::DUAL_44100); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - } - ret.emplace_back(AudioChannelFormat::DUAL_44100); -// stereo = true; - } - } - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::DUAL_48000); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - } - ret.emplace_back(AudioChannelFormat::DUAL_48000); -// stereo = true; - } - } -#endif - - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::INTERLEAVE_LR_96000); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - if (display_name.find("MiraBox") != std::string::npos){ - preferred_index += 2; - }else{ - preferred_index += 1; - } - } - ret.emplace_back(AudioChannelFormat::MONO_96000); - ret.emplace_back(AudioChannelFormat::INTERLEAVE_LR_96000); - ret.emplace_back(AudioChannelFormat::INTERLEAVE_RL_96000); - } - } - -// cout << "supported formats = " << ret.size() << endl; - return ret; -} -std::vector supported_output_formats(int& preferred_index, const NativeAudioInfo& info){ - QAudioFormat preferred_format = info.preferredFormat(); - int preferred_channels = preferred_format.channelCount(); - int preferred_rate = preferred_format.sampleRate(); - - std::vector ret; - preferred_index = -1; - - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::MONO_48000); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - } - ret.emplace_back(AudioChannelFormat::MONO_48000); - } - } - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::DUAL_44100); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - } - ret.emplace_back(AudioChannelFormat::DUAL_44100); - } - } - { - QAudioFormat format = preferred_format; - set_format(format, AudioChannelFormat::DUAL_48000); - if (info.isFormatSupported(format)){ - if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ - preferred_index = (int)ret.size(); - } - ret.emplace_back(AudioChannelFormat::DUAL_48000); - } - } - - return ret; -} - - - - -struct AudioDeviceInfo::Data{ - std::string device_name; // For serialization - std::string display_name; - - std::vector supported_formats; - int preferred_format_index; - -#if QT_VERSION_MAJOR == 5 - QAudioDeviceInfo info; -#elif QT_VERSION_MAJOR == 6 - QAudioDevice info; -#endif - -}; -std::vector AudioDeviceInfo::all_input_devices(){ - // The device list that Qt provides above will include duplicates on Windows - // due to Windows having a shadow device (winMM) that seems to be able to - // resample to all formats. - // - // https://bugreports.qt.io/browse/QTBUG-75781 - // - // What we need to do here it so try to de-dupe the list while keeping the - // ones that actually support the formats we need the best. - - // To do this, for all duplicates we first determine if any of the have a - // preferred format that matches a format that we want. If there is, we - // immediately throw out all the dupes that don't have a preferred format. - // This eliminates all the winMM devices if the primary can be used instead. - // - // Then we throw away all the ones that have fewer supported formats than - // the most. Identical (but different) devices will likely have identical - // names and format support. They won't be deduped. - - std::vector list; - - WallClock start = current_time(); - -#if QT_VERSION_MAJOR == 5 - for (NativeAudioInfo& device : QAudioDeviceInfo::availableDevices(QAudio::AudioInput)){ - list.emplace_back(); - Data& data = *list.back().m_body; - - std::string name = device.deviceName().toStdString(); - data.device_name = name; - data.display_name = std::move(name); - data.info = std::move(device); - - data.supported_formats = supported_input_formats(data.preferred_format_index, data.info, data.display_name); -// cout << "data.supported_formats = " << data.supported_formats.size() << endl; - } -#elif QT_VERSION_MAJOR == 6 - for (NativeAudioInfo& device : QMediaDevices::audioInputs()){ - list.emplace_back(); - Data& data = *list.back().m_body; - - data.device_name = device.id().toStdString(); - data.display_name = device.description().toStdString(); - data.info = std::move(device); - - data.supported_formats = supported_input_formats(data.preferred_format_index, data.info, data.display_name); - } -#endif - - WallClock end = current_time(); - double seconds = std::chrono::duration_cast(end - start).count() / 1000.; - global_logger_tagged().log("Done querying audio inputs... " + tostr_fixed(seconds, 3) + " seconds", COLOR_CYAN); - - bool show_all_devices = GlobalSettings::instance().AUDIO_PIPELINE->SHOW_ALL_DEVICES; - if (show_all_devices){ - return list; - } - - // Get map of best devices. - std::map best_devices; - for (const AudioDeviceInfo& device : list){ - size_t& best_score = best_devices[device.display_name()]; - size_t current_score = device.supported_formats().size(); - if (device.preferred_format_index() >= 0){ - current_score += 100; - } - best_score = std::max(best_score, current_score); - } - - // Keep only devices with the most # of formats. Duplicates allowed. - std::vector ret; - for (AudioDeviceInfo& device : list){ - size_t best_score = best_devices.find(device.display_name())->second; - size_t current_score = device.supported_formats().size(); - if (device.preferred_format_index() >= 0){ - current_score += 100; - } - if (current_score >= best_score || show_all_devices){ - ret.emplace_back(std::move(device)); - } - } - - return ret; -} -std::vector AudioDeviceInfo::all_output_devices(){ - // The device list that Qt provides above will include duplicates on Windows - // due to Windows having a shadow device (winMM) that seems to be able to - // resample to all formats. - // - // https://bugreports.qt.io/browse/QTBUG-75781 - // - // What we need to do here it so try to de-dupe the list while keeping the - // ones that actually support the formats we need the best. - - // To do this, for all duplicates we throw away the ones that have fewer - // supported formats than the most. Identical (but different) devices will - // likely have identical names and format support. They won't be deduped. - // - // This method will keep the winMM device which we want for audio output. - - std::vector list; - -#if QT_VERSION_MAJOR == 5 - for (NativeAudioInfo& device : QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)){ - list.emplace_back(); - Data& data = *list.back().m_body; - - std::string name = device.deviceName().toStdString(); - - std::string str = name + "\n"; - str += format_to_str(device.preferredFormat()); - global_logger_tagged().log(str); - - data.device_name = name; - data.display_name = std::move(name); - data.info = std::move(device); - - data.supported_formats = supported_output_formats(data.preferred_format_index, data.info); - - } -#elif QT_VERSION_MAJOR == 6 - for (NativeAudioInfo& device : QMediaDevices::audioOutputs()){ - list.emplace_back(); - Data& data = *list.back().m_body; - - std::string name = device.description().toStdString(); - - std::string str = name + "\n"; - str += format_to_str(device.preferredFormat()); - global_logger_tagged().log(str); - - data.device_name = device.id().toStdString(); - data.display_name = std::move(name); - data.info = std::move(device); - - data.supported_formats = supported_output_formats(data.preferred_format_index, data.info); - } -#endif - - bool show_all_devices = GlobalSettings::instance().AUDIO_PIPELINE->SHOW_ALL_DEVICES; - if (show_all_devices){ - return list; - } - - // Get map of greatest format counts. - std::map most_formats; - for (AudioDeviceInfo& device : list){ - size_t& count = most_formats[device.display_name()]; - count = std::max(count, device.supported_formats().size()); - } - - // Keep only devices with the most # of formats. Duplicates allowed. - std::vector ret; - for (AudioDeviceInfo& device : list){ - auto iter = most_formats.find(device.display_name()); - if (device.supported_formats().size() >= iter->second){ - ret.emplace_back(std::move(device)); - } - } - - return ret; -} - - -AudioDeviceInfo::~AudioDeviceInfo(){} -AudioDeviceInfo::AudioDeviceInfo(const AudioDeviceInfo& x) = default; -void AudioDeviceInfo::operator=(const AudioDeviceInfo& x){ - m_body = x.m_body; -} - -AudioDeviceInfo::AudioDeviceInfo() - : m_body(CONSTRUCT_TOKEN) -{} - -AudioDeviceInfo::AudioDeviceInfo(const std::string& device_name){ - for (AudioDeviceInfo& info : all_input_devices()){ - if (device_name == info.device_name()){ - *this = std::move(info); - return; - } - } - for (AudioDeviceInfo& info : all_output_devices()){ - if (device_name == info.device_name()){ - *this = std::move(info); - return; - } - } - m_body.reset(); -} - -AudioDeviceInfo::operator bool() const{ - return m_body && !m_body->device_name.empty(); -} -const std::string& AudioDeviceInfo::display_name() const{ - return m_body->display_name; -} -const std::string& AudioDeviceInfo::device_name() const{ - return m_body->device_name; -} -const std::vector& AudioDeviceInfo::supported_formats() const{ - return m_body->supported_formats; -} -int AudioDeviceInfo::preferred_format_index() const{ - return m_body->preferred_format_index; -} -QAudioFormat AudioDeviceInfo::preferred_format() const{ - QAudioFormat format = native_info().preferredFormat(); - int index = preferred_format_index(); - if (index >= 0){ - set_format(format, supported_formats()[index]); - } - return format; -} -const NativeAudioInfo& AudioDeviceInfo::native_info() const{ - return m_body->info; -} -bool AudioDeviceInfo::operator==(const AudioDeviceInfo& info) const{ - return device_name() == info.device_name(); -} - - - - - -} - - - - - - - - - - - - - - - - - - - - - +/* Audio Input Device Info + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" +#include "AudioInfo.h" + +//#include +//using std::cout; +//using std::endl; + + +#if QT_VERSION_MAJOR == 5 +#include +#elif QT_VERSION_MAJOR == 6 +#include +#include +#else +#error "Unsupported Qt version." +#endif + + +#if QT_VERSION_MAJOR != 5 +#define PA_AUDIO_USE_CHANNEL_CONFIG +#endif + + +namespace PokemonAutomation{ + + + +const char* AUDIO_FORMAT_LABELS[] = { + "(none)", + "1 x 48,000 Hz (Mono)", + "2 x 44,100 Hz (Stereo)", + "2 x 48,000 Hz (Stereo)", + "1 x 96,000 Hz (Mono)", + "1 x 96,000 Hz (Interleaved Stereo L/R)", + "1 x 96,000 Hz (Interleaved Stereo R/L)", +}; + +void set_format(QAudioFormat& native_format, AudioChannelFormat format){ + switch (format){ + case AudioChannelFormat::MONO_48000: +#ifdef PA_AUDIO_USE_CHANNEL_CONFIG + if (native_format.channelConfig() != QAudioFormat::ChannelConfigMono){ + native_format.setChannelConfig(QAudioFormat::ChannelConfigMono); + } +#else + if (native_format.channelCount() != 1){ + native_format.setChannelCount(1); + } +#endif + if (native_format.sampleRate() != 48000){ + native_format.setSampleRate(48000); + } + break; + case AudioChannelFormat::DUAL_44100: +#ifdef PA_AUDIO_USE_CHANNEL_CONFIG + if (native_format.channelConfig() != QAudioFormat::ChannelConfigStereo){ + native_format.setChannelConfig(QAudioFormat::ChannelConfigStereo); + } +#else + if (native_format.channelCount() != 2){ + native_format.setChannelCount(2); + } +#endif + if (native_format.sampleRate() != 44100){ + native_format.setSampleRate(44100); + } + break; + case AudioChannelFormat::DUAL_48000: +#ifdef PA_AUDIO_USE_CHANNEL_CONFIG + if (native_format.channelConfig() != QAudioFormat::ChannelConfigStereo){ + native_format.setChannelConfig(QAudioFormat::ChannelConfigStereo); + } +#else + if (native_format.channelCount() != 2){ + native_format.setChannelCount(2); + } +#endif + if (native_format.sampleRate() != 48000){ + native_format.setSampleRate(48000); + } + break; + case AudioChannelFormat::MONO_96000: + case AudioChannelFormat::INTERLEAVE_LR_96000: + case AudioChannelFormat::INTERLEAVE_RL_96000: +#ifdef PA_AUDIO_USE_CHANNEL_CONFIG + if (native_format.channelConfig() != QAudioFormat::ChannelConfigMono){ + native_format.setChannelConfig(QAudioFormat::ChannelConfigMono); + } +#else + if (native_format.channelCount() != 1){ + native_format.setChannelCount(1); + } +#endif + if (native_format.sampleRate() != 96000){ + native_format.setSampleRate(96000); + } + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); + } +} + +AudioSampleFormat get_sample_format(QAudioFormat& native_format){ +#if QT_VERSION_MAJOR == 5 + if (native_format.sampleType() == QAudioFormat::SampleType::Float){ + return AudioSampleFormat::FLOAT32; + }else if (native_format.sampleType() == QAudioFormat::SampleType::UnSignedInt && native_format.sampleSize() == 8){ + return AudioSampleFormat::UINT8; + }else if (native_format.sampleType() == QAudioFormat::SampleType::SignedInt && native_format.sampleSize() == 16){ + return AudioSampleFormat::SINT16; + }else if (native_format.sampleType() == QAudioFormat::SampleType::SignedInt && native_format.sampleSize() == 32){ + return AudioSampleFormat::SINT32; + }else{ + return AudioSampleFormat::INVALID; + } +#elif QT_VERSION_MAJOR == 6 + switch (native_format.sampleFormat()){ + case QAudioFormat::SampleFormat::Float: + return AudioSampleFormat::FLOAT32; + case QAudioFormat::SampleFormat::UInt8: + return AudioSampleFormat::UINT8; + case QAudioFormat::SampleFormat::Int16: + return AudioSampleFormat::SINT16; + case QAudioFormat::SampleFormat::Int32: + return AudioSampleFormat::SINT32; + default: + return AudioSampleFormat::INVALID; + } +#else +#error "Unknown Qt version." +#endif +} + + +std::string format_to_str(const QAudioFormat& format){ + std::string str; + str += "Preferred Format:\n"; + str += " Channels: " + std::to_string(format.channelCount()) + "\n"; + str += " Sample Rate: " + std::to_string(format.sampleRate()) + "\n"; +#if QT_VERSION_MAJOR == 5 + str += " Sample Format: " + std::to_string(format.sampleType()) + "\n"; +#else + str += " Sample Format: " + std::to_string(format.sampleFormat()) + "\n"; +#endif + return str; +} + + +// Return a list of our formats that are supported by this device. +// "preferred_index" is set to the index of the list that is preferred by the device. +// If no preferred format matches our formats, -1 is returned. +std::vector supported_input_formats(int& preferred_index, const NativeAudioInfo& info, const std::string& display_name){ + QAudioFormat preferred_format = info.preferredFormat(); + + std::string str = display_name + "\n"; + str += format_to_str(preferred_format); + global_logger_tagged().log(str); + +// preferred_format.setSampleSize(16); +// preferred_format.setSampleType(QAudioFormat::SampleType::SignedInt); + + int preferred_channels = preferred_format.channelCount(); + int preferred_rate = preferred_format.sampleRate(); + +#if 0 + cout << "display_name = " << display_name << endl; + cout << "channelCount = " << preferred_format.channelCount() << endl; + cout << "sampleRate = " << preferred_format.sampleRate() << endl; + cout << "sampleFormat = " << (int)preferred_format.sampleFormat() << endl; + cout << "preferred_format = " << info.isFormatSupported(preferred_format) << endl; + + for (const QAudioFormat::SampleFormat& format : info.supportedSampleFormats()){ + cout << "supported format: " << (int)format << endl; + } +#endif + +#if 0 +#if QT_VERSION_MAJOR == 6 || (QT_VERSION_MAJOR == 5 && __GNUC__) + // On Qt6, "QAudioFormat::preferredFormat()" always returns stereo 44.1 kHz. + // Unlike Qt5, it does not return the native format of the device + // This actually makes it kind of impossible to figure out what the correct + // format we need to use to give proper stereo. So instead, we just assume + // mono 96000 which will be the case for standard capture cards. + preferred_channels = 1; + preferred_rate = 96000; +#endif +#endif + + std::vector ret; + preferred_index = -1; + +// bool stereo = false; + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::MONO_48000); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + } + ret.emplace_back(AudioChannelFormat::MONO_48000); + } + } +#if 1 + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::DUAL_44100); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + } + ret.emplace_back(AudioChannelFormat::DUAL_44100); +// stereo = true; + } + } + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::DUAL_48000); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + } + ret.emplace_back(AudioChannelFormat::DUAL_48000); +// stereo = true; + } + } +#endif + + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::INTERLEAVE_LR_96000); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + if (display_name.find("MiraBox") != std::string::npos){ + preferred_index += 2; + }else{ + preferred_index += 1; + } + } + ret.emplace_back(AudioChannelFormat::MONO_96000); + ret.emplace_back(AudioChannelFormat::INTERLEAVE_LR_96000); + ret.emplace_back(AudioChannelFormat::INTERLEAVE_RL_96000); + } + } + +// cout << "supported formats = " << ret.size() << endl; + return ret; +} +std::vector supported_output_formats(int& preferred_index, const NativeAudioInfo& info){ + QAudioFormat preferred_format = info.preferredFormat(); + int preferred_channels = preferred_format.channelCount(); + int preferred_rate = preferred_format.sampleRate(); + + std::vector ret; + preferred_index = -1; + + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::MONO_48000); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + } + ret.emplace_back(AudioChannelFormat::MONO_48000); + } + } + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::DUAL_44100); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + } + ret.emplace_back(AudioChannelFormat::DUAL_44100); + } + } + { + QAudioFormat format = preferred_format; + set_format(format, AudioChannelFormat::DUAL_48000); + if (info.isFormatSupported(format)){ + if (format.channelCount() == preferred_channels && format.sampleRate() == preferred_rate){ + preferred_index = (int)ret.size(); + } + ret.emplace_back(AudioChannelFormat::DUAL_48000); + } + } + + return ret; +} + + + + +struct AudioDeviceInfo::Data{ + std::string device_name; // For serialization + std::string display_name; + + std::vector supported_formats; + int preferred_format_index; + +#if QT_VERSION_MAJOR == 5 + QAudioDeviceInfo info; +#elif QT_VERSION_MAJOR == 6 + QAudioDevice info; +#endif + +}; +std::vector AudioDeviceInfo::all_input_devices(){ + // The device list that Qt provides above will include duplicates on Windows + // due to Windows having a shadow device (winMM) that seems to be able to + // resample to all formats. + // + // https://bugreports.qt.io/browse/QTBUG-75781 + // + // What we need to do here it so try to de-dupe the list while keeping the + // ones that actually support the formats we need the best. + + // To do this, for all duplicates we first determine if any of the have a + // preferred format that matches a format that we want. If there is, we + // immediately throw out all the dupes that don't have a preferred format. + // This eliminates all the winMM devices if the primary can be used instead. + // + // Then we throw away all the ones that have fewer supported formats than + // the most. Identical (but different) devices will likely have identical + // names and format support. They won't be deduped. + + std::vector list; + + WallClock start = current_time(); + +#if QT_VERSION_MAJOR == 5 + for (NativeAudioInfo& device : QAudioDeviceInfo::availableDevices(QAudio::AudioInput)){ + list.emplace_back(); + Data& data = *list.back().m_body; + + std::string name = device.deviceName().toStdString(); + data.device_name = name; + data.display_name = std::move(name); + data.info = std::move(device); + + data.supported_formats = supported_input_formats(data.preferred_format_index, data.info, data.display_name); +// cout << "data.supported_formats = " << data.supported_formats.size() << endl; + } +#elif QT_VERSION_MAJOR == 6 + for (NativeAudioInfo& device : QMediaDevices::audioInputs()){ + list.emplace_back(); + Data& data = *list.back().m_body; + + data.device_name = device.id().toStdString(); + data.display_name = device.description().toStdString(); + data.info = std::move(device); + + data.supported_formats = supported_input_formats(data.preferred_format_index, data.info, data.display_name); + } +#endif + + WallClock end = current_time(); + double seconds = std::chrono::duration_cast(end - start).count() / 1000.; + global_logger_tagged().log("Done querying audio inputs... " + tostr_fixed(seconds, 3) + " seconds", COLOR_CYAN); + + bool show_all_devices = GlobalSettings::instance().AUDIO_PIPELINE->SHOW_ALL_DEVICES; + if (show_all_devices){ + return list; + } + + // Get map of best devices. + std::map best_devices; + for (const AudioDeviceInfo& device : list){ + size_t& best_score = best_devices[device.display_name()]; + size_t current_score = device.supported_formats().size(); + if (device.preferred_format_index() >= 0){ + current_score += 100; + } + best_score = std::max(best_score, current_score); + } + + // Keep only devices with the most # of formats. Duplicates allowed. + std::vector ret; + for (AudioDeviceInfo& device : list){ + size_t best_score = best_devices.find(device.display_name())->second; + size_t current_score = device.supported_formats().size(); + if (device.preferred_format_index() >= 0){ + current_score += 100; + } + if (current_score >= best_score || show_all_devices){ + ret.emplace_back(std::move(device)); + } + } + + return ret; +} +std::vector AudioDeviceInfo::all_output_devices(){ + // The device list that Qt provides above will include duplicates on Windows + // due to Windows having a shadow device (winMM) that seems to be able to + // resample to all formats. + // + // https://bugreports.qt.io/browse/QTBUG-75781 + // + // What we need to do here it so try to de-dupe the list while keeping the + // ones that actually support the formats we need the best. + + // To do this, for all duplicates we throw away the ones that have fewer + // supported formats than the most. Identical (but different) devices will + // likely have identical names and format support. They won't be deduped. + // + // This method will keep the winMM device which we want for audio output. + + std::vector list; + +#if QT_VERSION_MAJOR == 5 + for (NativeAudioInfo& device : QAudioDeviceInfo::availableDevices(QAudio::AudioOutput)){ + list.emplace_back(); + Data& data = *list.back().m_body; + + std::string name = device.deviceName().toStdString(); + + std::string str = name + "\n"; + str += format_to_str(device.preferredFormat()); + global_logger_tagged().log(str); + + data.device_name = name; + data.display_name = std::move(name); + data.info = std::move(device); + + data.supported_formats = supported_output_formats(data.preferred_format_index, data.info); + + } +#elif QT_VERSION_MAJOR == 6 + for (NativeAudioInfo& device : QMediaDevices::audioOutputs()){ + list.emplace_back(); + Data& data = *list.back().m_body; + + std::string name = device.description().toStdString(); + + std::string str = name + "\n"; + str += format_to_str(device.preferredFormat()); + global_logger_tagged().log(str); + + data.device_name = device.id().toStdString(); + data.display_name = std::move(name); + data.info = std::move(device); + + data.supported_formats = supported_output_formats(data.preferred_format_index, data.info); + } +#endif + + bool show_all_devices = GlobalSettings::instance().AUDIO_PIPELINE->SHOW_ALL_DEVICES; + if (show_all_devices){ + return list; + } + + // Get map of greatest format counts. + std::map most_formats; + for (AudioDeviceInfo& device : list){ + size_t& count = most_formats[device.display_name()]; + count = std::max(count, device.supported_formats().size()); + } + + // Keep only devices with the most # of formats. Duplicates allowed. + std::vector ret; + for (AudioDeviceInfo& device : list){ + auto iter = most_formats.find(device.display_name()); + if (device.supported_formats().size() >= iter->second){ + ret.emplace_back(std::move(device)); + } + } + + return ret; +} + + +AudioDeviceInfo::~AudioDeviceInfo(){} +AudioDeviceInfo::AudioDeviceInfo(const AudioDeviceInfo& x) = default; +void AudioDeviceInfo::operator=(const AudioDeviceInfo& x){ + m_body = x.m_body; +} + +AudioDeviceInfo::AudioDeviceInfo() + : m_body(CONSTRUCT_TOKEN) +{} + +AudioDeviceInfo::AudioDeviceInfo(const std::string& device_name){ + for (AudioDeviceInfo& info : all_input_devices()){ + if (device_name == info.device_name()){ + *this = std::move(info); + return; + } + } + for (AudioDeviceInfo& info : all_output_devices()){ + if (device_name == info.device_name()){ + *this = std::move(info); + return; + } + } + m_body.reset(); +} + +AudioDeviceInfo::operator bool() const{ + return m_body && !m_body->device_name.empty(); +} +const std::string& AudioDeviceInfo::display_name() const{ + return m_body->display_name; +} +const std::string& AudioDeviceInfo::device_name() const{ + return m_body->device_name; +} +const std::vector& AudioDeviceInfo::supported_formats() const{ + return m_body->supported_formats; +} +int AudioDeviceInfo::preferred_format_index() const{ + return m_body->preferred_format_index; +} +QAudioFormat AudioDeviceInfo::preferred_format() const{ + QAudioFormat format = native_info().preferredFormat(); + int index = preferred_format_index(); + if (index >= 0){ + set_format(format, supported_formats()[index]); + } + return format; +} +const NativeAudioInfo& AudioDeviceInfo::native_info() const{ + return m_body->info; +} +bool AudioDeviceInfo::operator==(const AudioDeviceInfo& info) const{ + return device_name() == info.device_name(); +} + + + + + +} + + + + + + + + + + + + + + + + + + + + + diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.h index 3a15adff71..e39b1bc3cd 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioInfo.h @@ -1,99 +1,99 @@ -/* Audio Device Info - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioInfo_H -#define PokemonAutomation_AudioPipeline_AudioInfo_H - -#include -#include -#include -#include "Common/Cpp/Containers/Pimpl.h" - -class QAudioFormat; - -#if QT_VERSION_MAJOR == 5 -class QAudioDeviceInfo; -using NativeAudioInfo = QAudioDeviceInfo; -#elif QT_VERSION_MAJOR == 6 -class QAudioDevice; -using NativeAudioInfo = QAudioDevice; -#else -#error "Unknown Qt version." -#endif - - - -namespace PokemonAutomation{ - - -enum class AudioSampleFormat{ - INVALID, - UINT8, - SINT16, - SINT32, - FLOAT32, -}; -size_t sample_size(AudioSampleFormat format); - - -enum class AudioChannelFormat{ - NONE, - MONO_48000, - DUAL_44100, - DUAL_48000, - MONO_96000, - INTERLEAVE_LR_96000, - INTERLEAVE_RL_96000, - END_LIST, -}; -extern const char* AUDIO_FORMAT_LABELS[]; - -// Set the QAudioFormat to the our audio format enum. -void set_format(QAudioFormat& native_format, AudioChannelFormat format); - - -AudioSampleFormat get_sample_format(QAudioFormat& native_format); - - - - -class AudioDeviceInfo{ -public: - ~AudioDeviceInfo(); - AudioDeviceInfo(const AudioDeviceInfo& x); - void operator=(const AudioDeviceInfo& x); - -public: - AudioDeviceInfo(); - explicit AudioDeviceInfo(const std::string& device_name); - - explicit operator bool() const; - - const std::string& display_name() const; - const std::string& device_name() const; - - const std::vector& supported_formats() const; - int preferred_format_index() const; - QAudioFormat preferred_format() const; - - const NativeAudioInfo& native_info() const; - - bool operator==(const AudioDeviceInfo& info) const; - - static std::vector all_input_devices(); - static std::vector all_output_devices(); - -private: - struct Data; - Pimpl m_body; -}; - - - - - -} -#endif +/* Audio Device Info + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioInfo_H +#define PokemonAutomation_AudioPipeline_AudioInfo_H + +#include +#include +#include +#include "Common/Cpp/Containers/Pimpl.h" + +class QAudioFormat; + +#if QT_VERSION_MAJOR == 5 +class QAudioDeviceInfo; +using NativeAudioInfo = QAudioDeviceInfo; +#elif QT_VERSION_MAJOR == 6 +class QAudioDevice; +using NativeAudioInfo = QAudioDevice; +#else +#error "Unknown Qt version." +#endif + + + +namespace PokemonAutomation{ + + +enum class AudioSampleFormat{ + INVALID, + UINT8, + SINT16, + SINT32, + FLOAT32, +}; +size_t sample_size(AudioSampleFormat format); + + +enum class AudioChannelFormat{ + NONE, + MONO_48000, + DUAL_44100, + DUAL_48000, + MONO_96000, + INTERLEAVE_LR_96000, + INTERLEAVE_RL_96000, + END_LIST, +}; +extern const char* AUDIO_FORMAT_LABELS[]; + +// Set the QAudioFormat to the our audio format enum. +void set_format(QAudioFormat& native_format, AudioChannelFormat format); + + +AudioSampleFormat get_sample_format(QAudioFormat& native_format); + + + + +class AudioDeviceInfo{ +public: + ~AudioDeviceInfo(); + AudioDeviceInfo(const AudioDeviceInfo& x); + void operator=(const AudioDeviceInfo& x); + +public: + AudioDeviceInfo(); + explicit AudioDeviceInfo(const std::string& device_name); + + explicit operator bool() const; + + const std::string& display_name() const; + const std::string& device_name() const; + + const std::vector& supported_formats() const; + int preferred_format_index() const; + QAudioFormat preferred_format() const; + + const NativeAudioInfo& native_info() const; + + bool operator==(const AudioDeviceInfo& info) const; + + static std::vector all_input_devices(); + static std::vector all_output_devices(); + +private: + struct Data; + Pimpl m_body; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.cpp index 0b0cd89a95..41ad84f6eb 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.cpp @@ -1,102 +1,102 @@ -/* Audio Selector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "AudioOption.h" - -namespace PokemonAutomation{ - - -const std::string AudioOption::JSON_INPUT_FILE = "InputFile"; -const std::string AudioOption::JSON_INPUT_DEVICE = "InputDevice"; -const std::string AudioOption::JSON_INPUT_FORMAT = "InputFormat"; -const std::string AudioOption::JSON_OUTPUT_DEVICE = "OutputDevice"; -const std::string AudioOption::JSON_AUDIO_VIS = "AudioVisualization"; -const std::string AudioOption::JSON_AUDIO_VOLUME = "Volume"; - -AudioOption::AudioDisplayType AudioOption::stringToAudioDisplayType(const std::string& value){ - if (value == "FREQ_BARS"){ - return AudioDisplayType::FREQ_BARS; - }else if (value == "SPECTROGRAM"){ - return AudioDisplayType::SPECTROGRAM; - } - return AudioDisplayType::NO_DISPLAY; -} - -std::string AudioOption::audioDisplayTypeToString(AudioOption::AudioDisplayType type){ - switch(type){ - case AudioDisplayType::FREQ_BARS: - return "FREQ_BARS"; - case AudioDisplayType::SPECTROGRAM: - return "SPECTROGRAM"; - case AudioDisplayType::NO_DISPLAY: - default: - return "NO_DISPLAY"; - } -} - -AudioOption::AudioOption(){} - -void AudioOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - const std::string* str; - str = obj->get_string(JSON_INPUT_FILE); - if (str != nullptr){ - m_input_file = *str; - } - if (m_input_file.empty()){ - str = obj->get_string(JSON_INPUT_DEVICE); - if (str != nullptr){ - m_input_device = AudioDeviceInfo(*str); - } - } - str = obj->get_string(JSON_INPUT_FORMAT); - if (str != nullptr){ - for (AudioChannelFormat format : m_input_device.supported_formats()){ - if (AUDIO_FORMAT_LABELS[(size_t)format] == *str){ - m_input_format = format; - break; - } - } - } -// cout << AUDIO_FORMAT_LABELS[(size_t)m_inputFormat] << endl; - str = obj->get_string(JSON_OUTPUT_DEVICE); - if (str != nullptr){ - m_output_device = AudioDeviceInfo(*str); - } - str = obj->get_string(JSON_AUDIO_VIS); - if (str != nullptr){ - m_display_type = stringToAudioDisplayType(*str); - } - double volume; - if (obj->read_float(volume, JSON_AUDIO_VOLUME)){ - volume = std::max(volume, 0.0); - volume = std::min(volume, 1.0); - m_volume = volume; - } -} - -JsonValue AudioOption::to_json() const{ - JsonObject root; - root[JSON_INPUT_FILE] = m_input_file; - root[JSON_INPUT_DEVICE] = m_input_device.device_name(); - root[JSON_INPUT_FORMAT] = AUDIO_FORMAT_LABELS[(size_t)m_input_format]; - root[JSON_OUTPUT_DEVICE] = m_output_device.device_name(); - root[JSON_AUDIO_VIS] = audioDisplayTypeToString(m_display_type); - root[JSON_AUDIO_VOLUME] = m_volume; - return root; -} - - - - - -} +/* Audio Selector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "AudioOption.h" + +namespace PokemonAutomation{ + + +const std::string AudioOption::JSON_INPUT_FILE = "InputFile"; +const std::string AudioOption::JSON_INPUT_DEVICE = "InputDevice"; +const std::string AudioOption::JSON_INPUT_FORMAT = "InputFormat"; +const std::string AudioOption::JSON_OUTPUT_DEVICE = "OutputDevice"; +const std::string AudioOption::JSON_AUDIO_VIS = "AudioVisualization"; +const std::string AudioOption::JSON_AUDIO_VOLUME = "Volume"; + +AudioOption::AudioDisplayType AudioOption::stringToAudioDisplayType(const std::string& value){ + if (value == "FREQ_BARS"){ + return AudioDisplayType::FREQ_BARS; + }else if (value == "SPECTROGRAM"){ + return AudioDisplayType::SPECTROGRAM; + } + return AudioDisplayType::NO_DISPLAY; +} + +std::string AudioOption::audioDisplayTypeToString(AudioOption::AudioDisplayType type){ + switch(type){ + case AudioDisplayType::FREQ_BARS: + return "FREQ_BARS"; + case AudioDisplayType::SPECTROGRAM: + return "SPECTROGRAM"; + case AudioDisplayType::NO_DISPLAY: + default: + return "NO_DISPLAY"; + } +} + +AudioOption::AudioOption(){} + +void AudioOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + const std::string* str; + str = obj->get_string(JSON_INPUT_FILE); + if (str != nullptr){ + m_input_file = *str; + } + if (m_input_file.empty()){ + str = obj->get_string(JSON_INPUT_DEVICE); + if (str != nullptr){ + m_input_device = AudioDeviceInfo(*str); + } + } + str = obj->get_string(JSON_INPUT_FORMAT); + if (str != nullptr){ + for (AudioChannelFormat format : m_input_device.supported_formats()){ + if (AUDIO_FORMAT_LABELS[(size_t)format] == *str){ + m_input_format = format; + break; + } + } + } +// cout << AUDIO_FORMAT_LABELS[(size_t)m_inputFormat] << endl; + str = obj->get_string(JSON_OUTPUT_DEVICE); + if (str != nullptr){ + m_output_device = AudioDeviceInfo(*str); + } + str = obj->get_string(JSON_AUDIO_VIS); + if (str != nullptr){ + m_display_type = stringToAudioDisplayType(*str); + } + double volume; + if (obj->read_float(volume, JSON_AUDIO_VOLUME)){ + volume = std::max(volume, 0.0); + volume = std::min(volume, 1.0); + m_volume = volume; + } +} + +JsonValue AudioOption::to_json() const{ + JsonObject root; + root[JSON_INPUT_FILE] = m_input_file; + root[JSON_INPUT_DEVICE] = m_input_device.device_name(); + root[JSON_INPUT_FORMAT] = AUDIO_FORMAT_LABELS[(size_t)m_input_format]; + root[JSON_OUTPUT_DEVICE] = m_output_device.device_name(); + root[JSON_AUDIO_VIS] = audioDisplayTypeToString(m_display_type); + root[JSON_AUDIO_VOLUME] = m_volume; + return root; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.h index 371b8fe1da..6eca3f8324 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioOption.h @@ -1,76 +1,76 @@ -/* Audio Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioOption_H -#define PokemonAutomation_AudioPipeline_AudioOption_H - -#include "AudioInfo.h" - -namespace PokemonAutomation{ - -class JsonValue; -class AudioSession; -class AudioDisplayWidget; -class AudioSelectorWidget; - - -// TODO: if needed, can add state of FFT parameters (FFT length, sliding -// window step, etc.) here. -class AudioOption{ - static const std::string JSON_INPUT_FILE; - static const std::string JSON_INPUT_DEVICE; - static const std::string JSON_INPUT_FORMAT; - static const std::string JSON_OUTPUT_DEVICE; - static const std::string JSON_AUDIO_VIS; - static const std::string JSON_AUDIO_VOLUME; - -public: - enum class AudioDisplayType{ - NO_DISPLAY, - FREQ_BARS, - SPECTROGRAM - }; - static AudioDisplayType stringToAudioDisplayType(const std::string& value); - static std::string audioDisplayTypeToString(AudioDisplayType type); - -public: - AudioOption(); - - const std::string& input_file() const{ return m_input_file; } - const AudioDeviceInfo& input_device() const{ return m_input_device; } - AudioChannelFormat input_format() const{ return m_input_format; } - - const AudioDeviceInfo& output_device() const{ return m_output_device; } - AudioDisplayType display_type() const{ return m_display_type; } - double volume() const{ return m_volume; } - -// void set_input_file(std::string&& value){ m_input_file = std::move(value); } -// void set_input_device(AudioDeviceInfo&& value){ m_input_device = std::move(value); } -// void set_input_format(AudioChannelFormat value){ m_input_format = value; } -// void set_output_device(AudioDeviceInfo&& value){ m_output_device = std::move(value); } -// void set_volume(double value){ m_volume = value; } -// void set_display_type(AudioDisplayType value){ m_display_type = value; } - -public: - void load_json(const JsonValue& json); - JsonValue to_json() const; - -private: - friend class AudioSession; - std::string m_input_file; - AudioDeviceInfo m_input_device; - AudioChannelFormat m_input_format = AudioChannelFormat::NONE; - AudioDeviceInfo m_output_device; - AudioDisplayType m_display_type = AudioDisplayType::FREQ_BARS; - double m_volume = 1.0; // Volume Range: [0, 1.0] -}; - - - - - -} -#endif +/* Audio Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioOption_H +#define PokemonAutomation_AudioPipeline_AudioOption_H + +#include "AudioInfo.h" + +namespace PokemonAutomation{ + +class JsonValue; +class AudioSession; +class AudioDisplayWidget; +class AudioSelectorWidget; + + +// TODO: if needed, can add state of FFT parameters (FFT length, sliding +// window step, etc.) here. +class AudioOption{ + static const std::string JSON_INPUT_FILE; + static const std::string JSON_INPUT_DEVICE; + static const std::string JSON_INPUT_FORMAT; + static const std::string JSON_OUTPUT_DEVICE; + static const std::string JSON_AUDIO_VIS; + static const std::string JSON_AUDIO_VOLUME; + +public: + enum class AudioDisplayType{ + NO_DISPLAY, + FREQ_BARS, + SPECTROGRAM + }; + static AudioDisplayType stringToAudioDisplayType(const std::string& value); + static std::string audioDisplayTypeToString(AudioDisplayType type); + +public: + AudioOption(); + + const std::string& input_file() const{ return m_input_file; } + const AudioDeviceInfo& input_device() const{ return m_input_device; } + AudioChannelFormat input_format() const{ return m_input_format; } + + const AudioDeviceInfo& output_device() const{ return m_output_device; } + AudioDisplayType display_type() const{ return m_display_type; } + double volume() const{ return m_volume; } + +// void set_input_file(std::string&& value){ m_input_file = std::move(value); } +// void set_input_device(AudioDeviceInfo&& value){ m_input_device = std::move(value); } +// void set_input_format(AudioChannelFormat value){ m_input_format = value; } +// void set_output_device(AudioDeviceInfo&& value){ m_output_device = std::move(value); } +// void set_volume(double value){ m_volume = value; } +// void set_display_type(AudioDisplayType value){ m_display_type = value; } + +public: + void load_json(const JsonValue& json); + JsonValue to_json() const; + +private: + friend class AudioSession; + std::string m_input_file; + AudioDeviceInfo m_input_device; + AudioChannelFormat m_input_format = AudioChannelFormat::NONE; + AudioDeviceInfo m_output_device; + AudioDisplayType m_display_type = AudioDisplayType::FREQ_BARS; + double m_volume = 1.0; // Volume Range: [0, 1.0] +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPassthroughPair.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPassthroughPair.h index c0b4a2bd99..79bf0d508c 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPassthroughPair.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPassthroughPair.h @@ -1,59 +1,59 @@ -/* Audio Passthrough Pair - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioPassthroughPair_H -#define PokemonAutomation_AudioPipeline_AudioPassthroughPair_H - -#include "AudioInfo.h" - -namespace PokemonAutomation{ - -struct AudioFloatStreamListener; -struct FFTListener; - - -// Represents an audio source/sink pair where audio is passed through from -// source -> sink with minimal latency. -// -// If desired, listeners can be attached to receive the FFT spectrums. -// -// This class is fully thread-safe. Both source and sink can be changed -// asynchronously. Listeners can be attached/detached asynchronously. -// -class AudioPassthroughPair{ -public: - virtual void add_listener(AudioFloatStreamListener& listener) = 0; - virtual void remove_listener(AudioFloatStreamListener& listener) = 0; - - virtual void add_listener(FFTListener& listener) = 0; - virtual void remove_listener(FFTListener& listener) = 0; - -public: - virtual ~AudioPassthroughPair() = default; - - virtual void reset( - const std::string& file, - const AudioDeviceInfo& output, double output_volume - ) = 0; - virtual void reset( - const AudioDeviceInfo& input, AudioChannelFormat format, - const AudioDeviceInfo& output, double output_volume - ) = 0; - - virtual void clear_audio_source() = 0; - virtual void set_audio_source(const std::string& file) = 0; - virtual void set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format) = 0; - - virtual void clear_audio_sink() = 0; - virtual void set_audio_sink(const AudioDeviceInfo& device, double volume) = 0; - - virtual void set_sink_volume(double volume) = 0; // Volume Range: [0, 1.0] -}; - - - -} -#endif +/* Audio Passthrough Pair + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioPassthroughPair_H +#define PokemonAutomation_AudioPipeline_AudioPassthroughPair_H + +#include "AudioInfo.h" + +namespace PokemonAutomation{ + +struct AudioFloatStreamListener; +struct FFTListener; + + +// Represents an audio source/sink pair where audio is passed through from +// source -> sink with minimal latency. +// +// If desired, listeners can be attached to receive the FFT spectrums. +// +// This class is fully thread-safe. Both source and sink can be changed +// asynchronously. Listeners can be attached/detached asynchronously. +// +class AudioPassthroughPair{ +public: + virtual void add_listener(AudioFloatStreamListener& listener) = 0; + virtual void remove_listener(AudioFloatStreamListener& listener) = 0; + + virtual void add_listener(FFTListener& listener) = 0; + virtual void remove_listener(FFTListener& listener) = 0; + +public: + virtual ~AudioPassthroughPair() = default; + + virtual void reset( + const std::string& file, + const AudioDeviceInfo& output, double output_volume + ) = 0; + virtual void reset( + const AudioDeviceInfo& input, AudioChannelFormat format, + const AudioDeviceInfo& output, double output_volume + ) = 0; + + virtual void clear_audio_source() = 0; + virtual void set_audio_source(const std::string& file) = 0; + virtual void set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format) = 0; + + virtual void clear_audio_sink() = 0; + virtual void set_audio_sink(const AudioDeviceInfo& device, double volume) = 0; + + virtual void set_sink_volume(double volume) = 0; // Volume Range: [0, 1.0] +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h index 282562bb47..353c28f031 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioPipelineOptions.h @@ -1,79 +1,79 @@ -/* Audio Pipeline Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioPipelineOptions_H -#define PokemonAutomation_AudioPipeline_AudioPipelineOptions_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -namespace PokemonAutomation{ - - -class AudioPipelineOptions : public GroupOption{ -public: - AudioPipelineOptions() - : GroupOption( - "Audio Pipeline", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , FILE_VOLUME_SCALE( - "Audio File Input Volume Scale:
" - "Multiply audio file playback by this factor. (This is linear scale. So each factor of 10 is 20dB.)", - LockMode::UNLOCK_WHILE_RUNNING, - 0.31622776601683793320, // -10dB - -10000, 10000 - ) - , DEVICE_VOLUME_SCALE( - "Audio Device Input Volume Scale:
" - "Multiply audio device input by this factor. (This is linear scale. So each factor of 10 is 20dB.)", - LockMode::UNLOCK_WHILE_RUNNING, - 1.0, -10000, 10000 - ) - , SHOW_ALL_DEVICES( - "Show all Audio Devices:
" - "Show all audio devices - including duplicates.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , SHOW_RECORD_FREQUENCIES( - "Show Record Frequencies:
" - "Show option to record audio frequencies.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , AUTO_RESET_SECONDS( - "Audio Auto-Reset:
" - "Attempt to reset the audio if this many seconds has elapsed since the last audio frame (in order to fix issues with RDP disconnection, etc).", - LockMode::UNLOCK_WHILE_RUNNING, - 5 - ) - { - PA_ADD_OPTION(FILE_VOLUME_SCALE); - PA_ADD_OPTION(DEVICE_VOLUME_SCALE); - PA_ADD_OPTION(SHOW_ALL_DEVICES); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SHOW_RECORD_FREQUENCIES); - } - PA_ADD_OPTION(AUTO_RESET_SECONDS); - } - -public: - FloatingPointOption FILE_VOLUME_SCALE; - FloatingPointOption DEVICE_VOLUME_SCALE; - BooleanCheckBoxOption SHOW_ALL_DEVICES; - BooleanCheckBoxOption SHOW_RECORD_FREQUENCIES; - SimpleIntegerOption AUTO_RESET_SECONDS; -}; - - - -} -#endif +/* Audio Pipeline Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioPipelineOptions_H +#define PokemonAutomation_AudioPipeline_AudioPipelineOptions_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +namespace PokemonAutomation{ + + +class AudioPipelineOptions : public GroupOption{ +public: + AudioPipelineOptions() + : GroupOption( + "Audio Pipeline", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , FILE_VOLUME_SCALE( + "Audio File Input Volume Scale:
" + "Multiply audio file playback by this factor. (This is linear scale. So each factor of 10 is 20dB.)", + LockMode::UNLOCK_WHILE_RUNNING, + 0.31622776601683793320, // -10dB + -10000, 10000 + ) + , DEVICE_VOLUME_SCALE( + "Audio Device Input Volume Scale:
" + "Multiply audio device input by this factor. (This is linear scale. So each factor of 10 is 20dB.)", + LockMode::UNLOCK_WHILE_RUNNING, + 1.0, -10000, 10000 + ) + , SHOW_ALL_DEVICES( + "Show all Audio Devices:
" + "Show all audio devices - including duplicates.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , SHOW_RECORD_FREQUENCIES( + "Show Record Frequencies:
" + "Show option to record audio frequencies.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , AUTO_RESET_SECONDS( + "Audio Auto-Reset:
" + "Attempt to reset the audio if this many seconds has elapsed since the last audio frame (in order to fix issues with RDP disconnection, etc).", + LockMode::UNLOCK_WHILE_RUNNING, + 5 + ) + { + PA_ADD_OPTION(FILE_VOLUME_SCALE); + PA_ADD_OPTION(DEVICE_VOLUME_SCALE); + PA_ADD_OPTION(SHOW_ALL_DEVICES); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SHOW_RECORD_FREQUENCIES); + } + PA_ADD_OPTION(AUTO_RESET_SECONDS); + } + +public: + FloatingPointOption FILE_VOLUME_SCALE; + FloatingPointOption DEVICE_VOLUME_SCALE; + BooleanCheckBoxOption SHOW_ALL_DEVICES; + BooleanCheckBoxOption SHOW_RECORD_FREQUENCIES; + SimpleIntegerOption AUTO_RESET_SECONDS; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.cpp index 0fdfec5524..a6be526bc9 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.cpp @@ -1,317 +1,317 @@ -/* Audio Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/GlobalServices.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Backends/AudioPassthroughPairQtThread.h" -#include "AudioPipelineOptions.h" -#include "AudioSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - - - -void AudioSession::add_state_listener(StateListener& listener){ - m_listeners.add(listener); -} -void AudioSession::remove_state_listener(StateListener& listener){ - m_listeners.remove(listener); -} -void AudioSession::add_stream_listener(AudioFloatStreamListener& listener){ - m_devices->add_listener(listener); -} -void AudioSession::remove_stream_listener(AudioFloatStreamListener& listener){ - m_devices->remove_listener(listener); -} -void AudioSession::add_spectrum_listener(AudioSpectrumHolder::Listener& listener){ - m_spectrum_holder.add_listener(listener); -} -void AudioSession::remove_spectrum_listener(AudioSpectrumHolder::Listener& listener){ - m_spectrum_holder.remove_listener(listener); -} - - - -AudioSession::AudioSession(Logger& logger, AudioOption& option) - : m_logger(logger) - , m_option(option) - , m_devices(new AudioPassthroughPairQtThread(logger)) -{ - AudioSession::reset(); - m_devices->add_listener(*this); - - uint8_t watchdog_timeout = GlobalSettings::instance().AUDIO_PIPELINE->AUTO_RESET_SECONDS; - if (watchdog_timeout != 0){ - global_watchdog().add(*this, std::chrono::seconds(watchdog_timeout)); - } -} -AudioSession::~AudioSession(){ - global_watchdog().remove(*this); - m_devices->remove_listener(*this); -} - - -void AudioSession::get(AudioOption& option){ - std::lock_guard lg(m_lock); - option.m_input_file = m_option.m_input_file; - option.m_input_device = m_option.m_input_device; - option.m_input_format = m_option.m_input_format; - option.m_output_device = m_option.m_output_device; - option.m_volume = m_option.m_volume; - option.m_display_type = m_option.m_display_type; -} -void AudioSession::set(const AudioOption& option){ - { - std::lock_guard lg(m_lock); - signal_pre_input_change(); - - m_option.m_input_file = option.m_input_file; - m_option.m_input_device = option.m_input_device; - m_option.m_input_format = option.m_input_format; - m_option.m_output_device = option.m_output_device; - m_option.m_volume = option.m_volume; - m_option.m_display_type = option.m_display_type; - - if (!m_option.m_input_file.empty()){ - sanitize_format(); - m_devices->set_audio_source(m_option.m_input_file); - }else if (sanitize_format()){ - m_devices->set_audio_source(m_option.m_input_device, m_option.m_input_format); - }else{ - m_devices->clear_audio_source(); - } - - m_devices->set_audio_sink(m_option.m_output_device, m_option.m_volume); - } - - signal_post_input_change(); - signal_post_output_change(); - m_listeners.run_method_unique(&StateListener::post_volume_change, m_option.volume()); - m_listeners.run_method_unique(&StateListener::post_display_change, m_option.m_display_type); -} -std::pair AudioSession::input_device() const{ - std::lock_guard lg(m_lock); - return {m_option.input_file(), m_option.m_input_device}; -} -AudioChannelFormat AudioSession::input_format() const{ - std::lock_guard lg(m_lock); - return m_option.m_input_format; -} -AudioDeviceInfo AudioSession::output_device() const{ - std::lock_guard lg(m_lock); - return m_option.m_output_device; -} -double AudioSession::output_volume() const{ - std::lock_guard lg(m_lock); - return m_option.m_volume; -} -AudioOption::AudioDisplayType AudioSession::display_type() const{ - std::lock_guard lg(m_lock); - return m_option.m_display_type; -} - - -void AudioSession::clear_audio_input(){ - std::lock_guard lg(m_lock); - m_logger.log("Clearing audio input..."); - signal_pre_input_change(); - m_devices->clear_audio_source(); - m_option.m_input_file.clear(); - m_option.m_input_device = AudioDeviceInfo(); - signal_post_input_change(); - - // We need to do this at the end. - // The previous line "signal_post_input_change()" is what will shut off the - // audio stream. If we clear the history before that, a race condition can - // add another spectrum to the history before the stream actually stops. - // When this happens, we will be left with a non-empty history which will - // be displayed as a non-moving freq-bars or spectrum instead of black. - m_spectrum_holder.clear(); -} -void AudioSession::set_audio_input(std::string file){ - std::lock_guard lg(m_lock); - signal_pre_input_change(); - m_option.m_input_file = std::move(file); - sanitize_format(); - m_devices->set_audio_source(m_option.m_input_file); - signal_post_input_change(); -} -void AudioSession::set_audio_input(AudioDeviceInfo info){ - std::lock_guard lg(m_lock); - m_logger.log("Setting audio input to: " + info.display_name()); - signal_pre_input_change(); - m_option.m_input_file.clear(); - m_option.m_input_device = std::move(info); - m_option.m_input_format = AudioChannelFormat::NONE; - if (sanitize_format()){ - m_devices->set_audio_source(info, m_option.m_input_format); - }else{ - m_devices->clear_audio_source(); - } - signal_post_input_change(); -} -void AudioSession::set_format(AudioChannelFormat format){ - std::lock_guard lg(m_lock); - signal_pre_input_change(); - m_option.m_input_format = format; - if (sanitize_format()){ - if (!m_option.m_input_file.empty()){ - m_devices->set_audio_source(m_option.m_input_file); - }else{ - m_devices->set_audio_source(m_option.m_input_device, m_option.m_input_format); - } - }else{ - m_devices->clear_audio_source(); - } - signal_post_input_change(); -} -void AudioSession::clear_audio_output(){ - std::lock_guard lg(m_lock); - m_logger.log("Clearing audio output..."); - m_devices->clear_audio_sink(); - m_option.m_output_device = AudioDeviceInfo(); - signal_post_output_change(); -} -void AudioSession::set_audio_output(AudioDeviceInfo info){ - std::lock_guard lg(m_lock); - m_logger.log("Setting audio output to: " + info.display_name()); - m_devices->set_audio_sink(info, m_option.m_volume); - m_option.m_output_device = std::move(info); - signal_post_output_change(); -} -void AudioSession::set_volume(double volume){ - { - std::lock_guard lg(m_lock); - if (m_option.m_volume == volume){ - return; - } - m_devices->set_sink_volume(volume); - m_option.m_volume = volume; - } - m_listeners.run_method_unique(&StateListener::post_volume_change, m_option.volume()); -} -void AudioSession::set_display(AudioOption::AudioDisplayType display){ - { - std::lock_guard lg(m_lock); - if (m_option.m_display_type == display){ - return; - } - m_option.m_display_type = display; - } - m_listeners.run_method_unique(&StateListener::post_display_change, m_option.m_display_type); -} - -bool AudioSession::sanitize_format(){ - if (!m_option.m_input_file.empty()){ - m_option.m_input_format = AudioChannelFormat::NONE; - return true; - } - AudioDeviceInfo& info = m_option.m_input_device; - const std::vector& supported_formats = info.supported_formats(); - int preferred_index = info.preferred_format_index(); - if (supported_formats.empty() || preferred_index < 0){ -// cout << "supported_formats = " << supported_formats.size() << endl; -// cout << "preferred_index = " << preferred_index << endl; - m_logger.log("No supported formats for this input device.", COLOR_RED); - m_option.m_input_format = AudioChannelFormat::NONE; - return false; - } - if (m_option.m_input_format == AudioChannelFormat::NONE){ - m_logger.log("No format set. Resetting to default...", COLOR_ORANGE); - }else{ - for (AudioChannelFormat supported_format : supported_formats){ - if (m_option.m_input_format == supported_format){ - return true; - } - } - m_logger.log("Desired format not supported. Resetting to default...", COLOR_RED); - } - m_option.m_input_format = supported_formats[preferred_index]; - return true; -} -void AudioSession::signal_pre_input_change(){ - m_listeners.run_method_unique(&StateListener::pre_input_change); -} -void AudioSession::signal_post_input_change(){ - m_listeners.run_method_unique( - &StateListener::post_input_change, - m_option.input_file(), - m_option.input_device(), - m_option.input_format() - ); -} -void AudioSession::signal_post_output_change(){ - m_listeners.run_method_unique(&StateListener::post_output_change, m_option.output_device()); -} - - - -void AudioSession::reset(){ - std::lock_guard lg(m_lock); - m_logger.log("AudioSession::reset()"); - signal_pre_input_change(); - if (!m_option.m_input_file.empty()){ -// cout << "AudioSession::reset() - file: " << m_option.m_input_file << " - " << m_option.m_input_file.size() << endl; - m_devices->reset( - m_option.m_input_file, - m_option.m_output_device, m_option.m_volume - ); - }else{ -// cout << "AudioSession::reset() - device: " << m_option.m_inputDevice.display_name() << endl; - m_devices->reset( - m_option.m_input_device, m_option.m_input_format, - m_option.m_output_device, m_option.m_volume - ); - } - signal_post_input_change(); -} -std::vector AudioSession::spectrums_since(uint64_t starting_seqnum){ - return m_spectrum_holder.spectrums_since(starting_seqnum); -} -std::vector AudioSession::spectrums_latest(size_t num_last_spectrums){ - return m_spectrum_holder.spectrums_latest(num_last_spectrums); -} -void AudioSession::add_overlay(uint64_t starting_seqnum, size_t end_seqnum, Color color){ - m_spectrum_holder.add_overlay(starting_seqnum, end_seqnum, color); -} - - -void AudioSession::on_fft(size_t sample_rate, std::shared_ptr> fft_output){ - m_spectrum_holder.push_spectrum(sample_rate, std::move(fft_output)); - global_watchdog().delay(*this); -} -void AudioSession::on_watchdog_timeout(){ -// m_logger.log("AudioSession::on_watchdog_timeout()", COLOR_RED); - if (m_option.m_input_file.empty() && !m_option.m_input_device){ - return; - } - - uint8_t watchdog_timeout = GlobalSettings::instance().AUDIO_PIPELINE->AUTO_RESET_SECONDS; - m_logger.log("No audio detected for " + std::to_string(watchdog_timeout) + " seconds...", COLOR_RED); - - if (watchdog_timeout == 0){ - return; - } - m_logger.log("Resetting the audio...", COLOR_GREEN); - reset(); -} - - - - - - - - -} +/* Audio Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/GlobalServices.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Backends/AudioPassthroughPairQtThread.h" +#include "AudioPipelineOptions.h" +#include "AudioSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + + + +void AudioSession::add_state_listener(StateListener& listener){ + m_listeners.add(listener); +} +void AudioSession::remove_state_listener(StateListener& listener){ + m_listeners.remove(listener); +} +void AudioSession::add_stream_listener(AudioFloatStreamListener& listener){ + m_devices->add_listener(listener); +} +void AudioSession::remove_stream_listener(AudioFloatStreamListener& listener){ + m_devices->remove_listener(listener); +} +void AudioSession::add_spectrum_listener(AudioSpectrumHolder::Listener& listener){ + m_spectrum_holder.add_listener(listener); +} +void AudioSession::remove_spectrum_listener(AudioSpectrumHolder::Listener& listener){ + m_spectrum_holder.remove_listener(listener); +} + + + +AudioSession::AudioSession(Logger& logger, AudioOption& option) + : m_logger(logger) + , m_option(option) + , m_devices(new AudioPassthroughPairQtThread(logger)) +{ + AudioSession::reset(); + m_devices->add_listener(*this); + + uint8_t watchdog_timeout = GlobalSettings::instance().AUDIO_PIPELINE->AUTO_RESET_SECONDS; + if (watchdog_timeout != 0){ + global_watchdog().add(*this, std::chrono::seconds(watchdog_timeout)); + } +} +AudioSession::~AudioSession(){ + global_watchdog().remove(*this); + m_devices->remove_listener(*this); +} + + +void AudioSession::get(AudioOption& option){ + std::lock_guard lg(m_lock); + option.m_input_file = m_option.m_input_file; + option.m_input_device = m_option.m_input_device; + option.m_input_format = m_option.m_input_format; + option.m_output_device = m_option.m_output_device; + option.m_volume = m_option.m_volume; + option.m_display_type = m_option.m_display_type; +} +void AudioSession::set(const AudioOption& option){ + { + std::lock_guard lg(m_lock); + signal_pre_input_change(); + + m_option.m_input_file = option.m_input_file; + m_option.m_input_device = option.m_input_device; + m_option.m_input_format = option.m_input_format; + m_option.m_output_device = option.m_output_device; + m_option.m_volume = option.m_volume; + m_option.m_display_type = option.m_display_type; + + if (!m_option.m_input_file.empty()){ + sanitize_format(); + m_devices->set_audio_source(m_option.m_input_file); + }else if (sanitize_format()){ + m_devices->set_audio_source(m_option.m_input_device, m_option.m_input_format); + }else{ + m_devices->clear_audio_source(); + } + + m_devices->set_audio_sink(m_option.m_output_device, m_option.m_volume); + } + + signal_post_input_change(); + signal_post_output_change(); + m_listeners.run_method_unique(&StateListener::post_volume_change, m_option.volume()); + m_listeners.run_method_unique(&StateListener::post_display_change, m_option.m_display_type); +} +std::pair AudioSession::input_device() const{ + std::lock_guard lg(m_lock); + return {m_option.input_file(), m_option.m_input_device}; +} +AudioChannelFormat AudioSession::input_format() const{ + std::lock_guard lg(m_lock); + return m_option.m_input_format; +} +AudioDeviceInfo AudioSession::output_device() const{ + std::lock_guard lg(m_lock); + return m_option.m_output_device; +} +double AudioSession::output_volume() const{ + std::lock_guard lg(m_lock); + return m_option.m_volume; +} +AudioOption::AudioDisplayType AudioSession::display_type() const{ + std::lock_guard lg(m_lock); + return m_option.m_display_type; +} + + +void AudioSession::clear_audio_input(){ + std::lock_guard lg(m_lock); + m_logger.log("Clearing audio input..."); + signal_pre_input_change(); + m_devices->clear_audio_source(); + m_option.m_input_file.clear(); + m_option.m_input_device = AudioDeviceInfo(); + signal_post_input_change(); + + // We need to do this at the end. + // The previous line "signal_post_input_change()" is what will shut off the + // audio stream. If we clear the history before that, a race condition can + // add another spectrum to the history before the stream actually stops. + // When this happens, we will be left with a non-empty history which will + // be displayed as a non-moving freq-bars or spectrum instead of black. + m_spectrum_holder.clear(); +} +void AudioSession::set_audio_input(std::string file){ + std::lock_guard lg(m_lock); + signal_pre_input_change(); + m_option.m_input_file = std::move(file); + sanitize_format(); + m_devices->set_audio_source(m_option.m_input_file); + signal_post_input_change(); +} +void AudioSession::set_audio_input(AudioDeviceInfo info){ + std::lock_guard lg(m_lock); + m_logger.log("Setting audio input to: " + info.display_name()); + signal_pre_input_change(); + m_option.m_input_file.clear(); + m_option.m_input_device = std::move(info); + m_option.m_input_format = AudioChannelFormat::NONE; + if (sanitize_format()){ + m_devices->set_audio_source(info, m_option.m_input_format); + }else{ + m_devices->clear_audio_source(); + } + signal_post_input_change(); +} +void AudioSession::set_format(AudioChannelFormat format){ + std::lock_guard lg(m_lock); + signal_pre_input_change(); + m_option.m_input_format = format; + if (sanitize_format()){ + if (!m_option.m_input_file.empty()){ + m_devices->set_audio_source(m_option.m_input_file); + }else{ + m_devices->set_audio_source(m_option.m_input_device, m_option.m_input_format); + } + }else{ + m_devices->clear_audio_source(); + } + signal_post_input_change(); +} +void AudioSession::clear_audio_output(){ + std::lock_guard lg(m_lock); + m_logger.log("Clearing audio output..."); + m_devices->clear_audio_sink(); + m_option.m_output_device = AudioDeviceInfo(); + signal_post_output_change(); +} +void AudioSession::set_audio_output(AudioDeviceInfo info){ + std::lock_guard lg(m_lock); + m_logger.log("Setting audio output to: " + info.display_name()); + m_devices->set_audio_sink(info, m_option.m_volume); + m_option.m_output_device = std::move(info); + signal_post_output_change(); +} +void AudioSession::set_volume(double volume){ + { + std::lock_guard lg(m_lock); + if (m_option.m_volume == volume){ + return; + } + m_devices->set_sink_volume(volume); + m_option.m_volume = volume; + } + m_listeners.run_method_unique(&StateListener::post_volume_change, m_option.volume()); +} +void AudioSession::set_display(AudioOption::AudioDisplayType display){ + { + std::lock_guard lg(m_lock); + if (m_option.m_display_type == display){ + return; + } + m_option.m_display_type = display; + } + m_listeners.run_method_unique(&StateListener::post_display_change, m_option.m_display_type); +} + +bool AudioSession::sanitize_format(){ + if (!m_option.m_input_file.empty()){ + m_option.m_input_format = AudioChannelFormat::NONE; + return true; + } + AudioDeviceInfo& info = m_option.m_input_device; + const std::vector& supported_formats = info.supported_formats(); + int preferred_index = info.preferred_format_index(); + if (supported_formats.empty() || preferred_index < 0){ +// cout << "supported_formats = " << supported_formats.size() << endl; +// cout << "preferred_index = " << preferred_index << endl; + m_logger.log("No supported formats for this input device.", COLOR_RED); + m_option.m_input_format = AudioChannelFormat::NONE; + return false; + } + if (m_option.m_input_format == AudioChannelFormat::NONE){ + m_logger.log("No format set. Resetting to default...", COLOR_ORANGE); + }else{ + for (AudioChannelFormat supported_format : supported_formats){ + if (m_option.m_input_format == supported_format){ + return true; + } + } + m_logger.log("Desired format not supported. Resetting to default...", COLOR_RED); + } + m_option.m_input_format = supported_formats[preferred_index]; + return true; +} +void AudioSession::signal_pre_input_change(){ + m_listeners.run_method_unique(&StateListener::pre_input_change); +} +void AudioSession::signal_post_input_change(){ + m_listeners.run_method_unique( + &StateListener::post_input_change, + m_option.input_file(), + m_option.input_device(), + m_option.input_format() + ); +} +void AudioSession::signal_post_output_change(){ + m_listeners.run_method_unique(&StateListener::post_output_change, m_option.output_device()); +} + + + +void AudioSession::reset(){ + std::lock_guard lg(m_lock); + m_logger.log("AudioSession::reset()"); + signal_pre_input_change(); + if (!m_option.m_input_file.empty()){ +// cout << "AudioSession::reset() - file: " << m_option.m_input_file << " - " << m_option.m_input_file.size() << endl; + m_devices->reset( + m_option.m_input_file, + m_option.m_output_device, m_option.m_volume + ); + }else{ +// cout << "AudioSession::reset() - device: " << m_option.m_inputDevice.display_name() << endl; + m_devices->reset( + m_option.m_input_device, m_option.m_input_format, + m_option.m_output_device, m_option.m_volume + ); + } + signal_post_input_change(); +} +std::vector AudioSession::spectrums_since(uint64_t starting_seqnum){ + return m_spectrum_holder.spectrums_since(starting_seqnum); +} +std::vector AudioSession::spectrums_latest(size_t num_last_spectrums){ + return m_spectrum_holder.spectrums_latest(num_last_spectrums); +} +void AudioSession::add_overlay(uint64_t starting_seqnum, size_t end_seqnum, Color color){ + m_spectrum_holder.add_overlay(starting_seqnum, end_seqnum, color); +} + + +void AudioSession::on_fft(size_t sample_rate, std::shared_ptr> fft_output){ + m_spectrum_holder.push_spectrum(sample_rate, std::move(fft_output)); + global_watchdog().delay(*this); +} +void AudioSession::on_watchdog_timeout(){ +// m_logger.log("AudioSession::on_watchdog_timeout()", COLOR_RED); + if (m_option.m_input_file.empty() && !m_option.m_input_device){ + return; + } + + uint8_t watchdog_timeout = GlobalSettings::instance().AUDIO_PIPELINE->AUTO_RESET_SECONDS; + m_logger.log("No audio detected for " + std::to_string(watchdog_timeout) + " seconds...", COLOR_RED); + + if (watchdog_timeout == 0){ + return; + } + m_logger.log("Resetting the audio...", COLOR_GREEN); + reset(); +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.h index 3f190151a5..80897b9039 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioSession.h @@ -1,111 +1,111 @@ -/* Audio Session - * - * From: https://github.com/PokemonAutomation/ - * - * AudioSession represents a live audio session. It holds onto the audio - * input/output sessions which can be asynchronously set at any time. - * - * This class is not responsible for any UI. However, any changes made to this - * class will be forwarded to any UI components that are attached to it. - * - * The UI that allows a user to control this class is in AudioSelectorWidget. - * The actual display of the audio spectrum is in AudioDisplayWidget. - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioSession_H -#define PokemonAutomation_AudioPipeline_AudioSession_H - -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/Concurrency/Watchdog.h" -#include "AudioFeed.h" -#include "AudioPassthroughPair.h" -#include "Spectrum/FFTStreamer.h" -#include "Spectrum/AudioSpectrumHolder.h" -#include "AudioOption.h" - -namespace PokemonAutomation{ - -class Logger; - - -class AudioSession final : public AudioFeed, private FFTListener, private WatchdogCallback{ -public: - struct StateListener{ - virtual void pre_input_change(){} - virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){} - virtual void post_output_change(const AudioDeviceInfo& device){} - virtual void post_volume_change(double volume){} - virtual void post_display_change(AudioOption::AudioDisplayType display){} - }; - void add_state_listener(StateListener& listener); - void remove_state_listener(StateListener& listener); - - void add_stream_listener(AudioFloatStreamListener& listener); - void remove_stream_listener(AudioFloatStreamListener& listener); - - void add_spectrum_listener(AudioSpectrumHolder::Listener& listener); - void remove_spectrum_listener(AudioSpectrumHolder::Listener& listener); - - -public: - ~AudioSession(); - AudioSession(Logger& logger, AudioOption& option); - - void get(AudioOption& option); - void set(const AudioOption& option); - - std::pair input_device() const; - AudioChannelFormat input_format() const; - - AudioDeviceInfo output_device() const; - double output_volume() const; - - AudioOption::AudioDisplayType display_type() const; - AudioSpectrumHolder& spectrums(){ return m_spectrum_holder; } - - void clear_audio_input(); - void set_audio_input(std::string file); - void set_audio_input(AudioDeviceInfo info); - void set_format(AudioChannelFormat format); - - void clear_audio_output(); - void set_audio_output(AudioDeviceInfo info); - void set_volume(double volume); - void set_display(AudioOption::AudioDisplayType display); - - -public: - virtual void reset() override; - virtual std::vector spectrums_since(uint64_t starting_seqnum) override; - virtual std::vector spectrums_latest(size_t num_last_spectrums) override; - virtual void add_overlay(uint64_t starting_seqnum, size_t end_seqnum, Color color) override; - - -private: - virtual void on_fft(size_t sample_rate, std::shared_ptr> fft_output) override; - virtual void on_watchdog_timeout() override; - - bool sanitize_format(); - - void signal_pre_input_change(); - void signal_post_input_change(); - void signal_post_output_change(); - - -private: - Logger& m_logger; - AudioOption& m_option; - AudioSpectrumHolder m_spectrum_holder; - std::unique_ptr m_devices; - - mutable std::mutex m_lock; - - ListenerSet m_listeners; - -}; - - - -} -#endif +/* Audio Session + * + * From: https://github.com/PokemonAutomation/ + * + * AudioSession represents a live audio session. It holds onto the audio + * input/output sessions which can be asynchronously set at any time. + * + * This class is not responsible for any UI. However, any changes made to this + * class will be forwarded to any UI components that are attached to it. + * + * The UI that allows a user to control this class is in AudioSelectorWidget. + * The actual display of the audio spectrum is in AudioDisplayWidget. + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioSession_H +#define PokemonAutomation_AudioPipeline_AudioSession_H + +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/Concurrency/Watchdog.h" +#include "AudioFeed.h" +#include "AudioPassthroughPair.h" +#include "Spectrum/FFTStreamer.h" +#include "Spectrum/AudioSpectrumHolder.h" +#include "AudioOption.h" + +namespace PokemonAutomation{ + +class Logger; + + +class AudioSession final : public AudioFeed, private FFTListener, private WatchdogCallback{ +public: + struct StateListener{ + virtual void pre_input_change(){} + virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){} + virtual void post_output_change(const AudioDeviceInfo& device){} + virtual void post_volume_change(double volume){} + virtual void post_display_change(AudioOption::AudioDisplayType display){} + }; + void add_state_listener(StateListener& listener); + void remove_state_listener(StateListener& listener); + + void add_stream_listener(AudioFloatStreamListener& listener); + void remove_stream_listener(AudioFloatStreamListener& listener); + + void add_spectrum_listener(AudioSpectrumHolder::Listener& listener); + void remove_spectrum_listener(AudioSpectrumHolder::Listener& listener); + + +public: + ~AudioSession(); + AudioSession(Logger& logger, AudioOption& option); + + void get(AudioOption& option); + void set(const AudioOption& option); + + std::pair input_device() const; + AudioChannelFormat input_format() const; + + AudioDeviceInfo output_device() const; + double output_volume() const; + + AudioOption::AudioDisplayType display_type() const; + AudioSpectrumHolder& spectrums(){ return m_spectrum_holder; } + + void clear_audio_input(); + void set_audio_input(std::string file); + void set_audio_input(AudioDeviceInfo info); + void set_format(AudioChannelFormat format); + + void clear_audio_output(); + void set_audio_output(AudioDeviceInfo info); + void set_volume(double volume); + void set_display(AudioOption::AudioDisplayType display); + + +public: + virtual void reset() override; + virtual std::vector spectrums_since(uint64_t starting_seqnum) override; + virtual std::vector spectrums_latest(size_t num_last_spectrums) override; + virtual void add_overlay(uint64_t starting_seqnum, size_t end_seqnum, Color color) override; + + +private: + virtual void on_fft(size_t sample_rate, std::shared_ptr> fft_output) override; + virtual void on_watchdog_timeout() override; + + bool sanitize_format(); + + void signal_pre_input_change(); + void signal_post_input_change(); + void signal_post_output_change(); + + +private: + Logger& m_logger; + AudioOption& m_option; + AudioSpectrumHolder m_spectrum_holder; + std::unique_ptr m_devices; + + mutable std::mutex m_lock; + + ListenerSet m_listeners; + +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.cpp index ccd76f95cd..5e5603f8a1 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.cpp @@ -1,215 +1,215 @@ -/* Audio Source Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "Kernels/AudioStreamConversion/AudioStreamConversion.h" -#include "Kernels/AbsFFT/Kernels_AbsFFT.h" -#include "AudioConstants.h" -#include "AudioStream.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -// Audio buffer size (measured in frames). -const size_t AUDIO_BUFFER_SIZE = 4096; - - - -size_t sample_size(AudioSampleFormat format){ - switch (format){ - case AudioSampleFormat::UINT8: - return sizeof(uint8_t); - case AudioSampleFormat::SINT16: - return sizeof(int16_t); - case AudioSampleFormat::SINT32: - return sizeof(int32_t); - case AudioSampleFormat::FLOAT32: - return sizeof(float); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioSampleFormat: " + std::to_string((size_t)format)); - } -} - - - -void AudioStreamToFloat::add_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - if (listener.expected_samples_per_frame != m_samples_per_frame){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching frame size."); - } - m_listeners.insert(&listener); -} -void AudioStreamToFloat::remove_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - m_listeners.erase(&listener); -} - -AudioStreamToFloat::~AudioStreamToFloat(){ - MisalignedStreamConverter::remove_listener(*this); -} -AudioStreamToFloat::AudioStreamToFloat( - AudioSampleFormat input_format, - size_t samples_per_frame, - float volume_multiplier, - bool reverse_channels -) - : MisalignedStreamConverter( - sample_size(input_format) * samples_per_frame, - sizeof(float) * samples_per_frame, - AUDIO_BUFFER_SIZE - ) - , StreamListener(sizeof(float) * samples_per_frame) - , m_format(input_format) - , m_samples_per_frame(samples_per_frame) - , m_volume_multiplier(volume_multiplier) - , m_reverse_channels(reverse_channels) - , m_sample_size(sample_size(input_format)) - , m_frame_size(m_sample_size * samples_per_frame) -{ - if (samples_per_frame == 0){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Must have at least one sample."); - } - if (reverse_channels && samples_per_frame != 2){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Reverse channels only works with 2 samples/frame."); - } - MisalignedStreamConverter::add_listener(*this); -} -void AudioStreamToFloat::on_objects(const void* data, size_t objects){ - auto scope_check = m_sanitizer.check_scope(); - for (AudioFloatStreamListener* listener : m_listeners){ - listener->on_samples((const float*)data, objects); - } -} -void AudioStreamToFloat::convert(void* out, const void* in, size_t count){ - auto scope_check = m_sanitizer.check_scope(); - switch (m_format){ - case AudioSampleFormat::UINT8: - Kernels::AudioStreamConversion::convert_audio_uint8_to_float( - (float*)out, (const uint8_t*)in, count * m_samples_per_frame, m_volume_multiplier - ); - break; - case AudioSampleFormat::SINT16: - Kernels::AudioStreamConversion::convert_audio_sint16_to_float( - (float*)out, (const int16_t*)in, count * m_samples_per_frame, m_volume_multiplier - ); - break; - case AudioSampleFormat::SINT32: - Kernels::AudioStreamConversion::convert_audio_sint32_to_float( - (float*)out, (const int32_t*)in, count * m_samples_per_frame, m_volume_multiplier - ); - break; - case AudioSampleFormat::FLOAT32: - if (m_volume_multiplier == 1.0){ - memcpy(out, in, count * m_frame_size); - }else{ - float volume_multiplier = m_volume_multiplier; - float* o = (float*)out; - const float* i = (float*)in; - size_t stop = count * m_samples_per_frame; - for (size_t c = 0; c < stop; c++){ - o[c] = i[c] * volume_multiplier; - } - } - break; - case AudioSampleFormat::INVALID: - break; - } - if (m_reverse_channels){ - float* ptr = (float*)out; - for (size_t c = 0; c < count; c++){ - float r0 = ptr[2*c + 0]; - float r1 = ptr[2*c + 1]; - ptr[2*c + 0] = r1; - ptr[2*c + 1] = r0; - } - } -} - - - - -void AudioFloatToStream::add_listener(StreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - if (listener.object_size != m_frame_size){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching frame size."); - } - m_listeners.add(listener); -} -void AudioFloatToStream::remove_listener(StreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - m_listeners.remove(listener); -} - -AudioFloatToStream::AudioFloatToStream(AudioSampleFormat output_format, size_t samples_per_frame) - : AudioFloatStreamListener(samples_per_frame) - , m_format(output_format) - , m_samples_per_frame(samples_per_frame) - , m_sample_size(sample_size(output_format)) - , m_frame_size(m_sample_size * samples_per_frame) - , m_buffer_size(AUDIO_BUFFER_SIZE) -{ - switch (output_format){ - case AudioSampleFormat::INVALID: - case AudioSampleFormat::FLOAT32: - break; - default: - m_buffer = AlignedVector(m_frame_size * m_buffer_size); - } -} -AudioFloatToStream::~AudioFloatToStream(){} -void AudioFloatToStream::on_samples(const float* data, size_t frames){ - auto scope_check = m_sanitizer.check_scope(); - if (m_format == AudioSampleFormat::INVALID){ - return; - } - if (m_format == AudioSampleFormat::FLOAT32){ - m_listeners.run_method_unique( - &StreamListener::on_objects, - data, frames - ); - return; - } - - while (frames > 0){ - size_t block = std::min(frames, m_buffer_size); - switch (m_format){ - case AudioSampleFormat::UINT8: - Kernels::AudioStreamConversion::convert_audio_float_to_uint8((uint8_t*)m_buffer.data(), data, block * m_samples_per_frame); - break; - case AudioSampleFormat::SINT16: - Kernels::AudioStreamConversion::convert_audio_float_to_sint16((int16_t*)m_buffer.data(), data, block * m_samples_per_frame); - break; - case AudioSampleFormat::SINT32: - Kernels::AudioStreamConversion::convert_audio_float_to_sint32((int32_t*)m_buffer.data(), data, block * m_samples_per_frame); - break; - case AudioSampleFormat::FLOAT32: - memcpy(m_buffer.data(), data, block * m_frame_size); - break; - default: - return; - } - m_listeners.run_method_unique( - &StreamListener::on_objects, - m_buffer.data(), block - ); - data = (const float*)((const char*)data + block * m_frame_size); - frames -= block; - } -} - - - - - - - - -} +/* Audio Source Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "Kernels/AudioStreamConversion/AudioStreamConversion.h" +#include "Kernels/AbsFFT/Kernels_AbsFFT.h" +#include "AudioConstants.h" +#include "AudioStream.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +// Audio buffer size (measured in frames). +const size_t AUDIO_BUFFER_SIZE = 4096; + + + +size_t sample_size(AudioSampleFormat format){ + switch (format){ + case AudioSampleFormat::UINT8: + return sizeof(uint8_t); + case AudioSampleFormat::SINT16: + return sizeof(int16_t); + case AudioSampleFormat::SINT32: + return sizeof(int32_t); + case AudioSampleFormat::FLOAT32: + return sizeof(float); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioSampleFormat: " + std::to_string((size_t)format)); + } +} + + + +void AudioStreamToFloat::add_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + if (listener.expected_samples_per_frame != m_samples_per_frame){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching frame size."); + } + m_listeners.insert(&listener); +} +void AudioStreamToFloat::remove_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_listeners.erase(&listener); +} + +AudioStreamToFloat::~AudioStreamToFloat(){ + MisalignedStreamConverter::remove_listener(*this); +} +AudioStreamToFloat::AudioStreamToFloat( + AudioSampleFormat input_format, + size_t samples_per_frame, + float volume_multiplier, + bool reverse_channels +) + : MisalignedStreamConverter( + sample_size(input_format) * samples_per_frame, + sizeof(float) * samples_per_frame, + AUDIO_BUFFER_SIZE + ) + , StreamListener(sizeof(float) * samples_per_frame) + , m_format(input_format) + , m_samples_per_frame(samples_per_frame) + , m_volume_multiplier(volume_multiplier) + , m_reverse_channels(reverse_channels) + , m_sample_size(sample_size(input_format)) + , m_frame_size(m_sample_size * samples_per_frame) +{ + if (samples_per_frame == 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Must have at least one sample."); + } + if (reverse_channels && samples_per_frame != 2){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Reverse channels only works with 2 samples/frame."); + } + MisalignedStreamConverter::add_listener(*this); +} +void AudioStreamToFloat::on_objects(const void* data, size_t objects){ + auto scope_check = m_sanitizer.check_scope(); + for (AudioFloatStreamListener* listener : m_listeners){ + listener->on_samples((const float*)data, objects); + } +} +void AudioStreamToFloat::convert(void* out, const void* in, size_t count){ + auto scope_check = m_sanitizer.check_scope(); + switch (m_format){ + case AudioSampleFormat::UINT8: + Kernels::AudioStreamConversion::convert_audio_uint8_to_float( + (float*)out, (const uint8_t*)in, count * m_samples_per_frame, m_volume_multiplier + ); + break; + case AudioSampleFormat::SINT16: + Kernels::AudioStreamConversion::convert_audio_sint16_to_float( + (float*)out, (const int16_t*)in, count * m_samples_per_frame, m_volume_multiplier + ); + break; + case AudioSampleFormat::SINT32: + Kernels::AudioStreamConversion::convert_audio_sint32_to_float( + (float*)out, (const int32_t*)in, count * m_samples_per_frame, m_volume_multiplier + ); + break; + case AudioSampleFormat::FLOAT32: + if (m_volume_multiplier == 1.0){ + memcpy(out, in, count * m_frame_size); + }else{ + float volume_multiplier = m_volume_multiplier; + float* o = (float*)out; + const float* i = (float*)in; + size_t stop = count * m_samples_per_frame; + for (size_t c = 0; c < stop; c++){ + o[c] = i[c] * volume_multiplier; + } + } + break; + case AudioSampleFormat::INVALID: + break; + } + if (m_reverse_channels){ + float* ptr = (float*)out; + for (size_t c = 0; c < count; c++){ + float r0 = ptr[2*c + 0]; + float r1 = ptr[2*c + 1]; + ptr[2*c + 0] = r1; + ptr[2*c + 1] = r0; + } + } +} + + + + +void AudioFloatToStream::add_listener(StreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + if (listener.object_size != m_frame_size){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching frame size."); + } + m_listeners.add(listener); +} +void AudioFloatToStream::remove_listener(StreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_listeners.remove(listener); +} + +AudioFloatToStream::AudioFloatToStream(AudioSampleFormat output_format, size_t samples_per_frame) + : AudioFloatStreamListener(samples_per_frame) + , m_format(output_format) + , m_samples_per_frame(samples_per_frame) + , m_sample_size(sample_size(output_format)) + , m_frame_size(m_sample_size * samples_per_frame) + , m_buffer_size(AUDIO_BUFFER_SIZE) +{ + switch (output_format){ + case AudioSampleFormat::INVALID: + case AudioSampleFormat::FLOAT32: + break; + default: + m_buffer = AlignedVector(m_frame_size * m_buffer_size); + } +} +AudioFloatToStream::~AudioFloatToStream(){} +void AudioFloatToStream::on_samples(const float* data, size_t frames){ + auto scope_check = m_sanitizer.check_scope(); + if (m_format == AudioSampleFormat::INVALID){ + return; + } + if (m_format == AudioSampleFormat::FLOAT32){ + m_listeners.run_method_unique( + &StreamListener::on_objects, + data, frames + ); + return; + } + + while (frames > 0){ + size_t block = std::min(frames, m_buffer_size); + switch (m_format){ + case AudioSampleFormat::UINT8: + Kernels::AudioStreamConversion::convert_audio_float_to_uint8((uint8_t*)m_buffer.data(), data, block * m_samples_per_frame); + break; + case AudioSampleFormat::SINT16: + Kernels::AudioStreamConversion::convert_audio_float_to_sint16((int16_t*)m_buffer.data(), data, block * m_samples_per_frame); + break; + case AudioSampleFormat::SINT32: + Kernels::AudioStreamConversion::convert_audio_float_to_sint32((int32_t*)m_buffer.data(), data, block * m_samples_per_frame); + break; + case AudioSampleFormat::FLOAT32: + memcpy(m_buffer.data(), data, block * m_frame_size); + break; + default: + return; + } + m_listeners.run_method_unique( + &StreamListener::on_objects, + m_buffer.data(), block + ); + data = (const float*)((const char*)data + block * m_frame_size); + frames -= block; + } +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.h index 445ab4ec65..0d57a8eaf3 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioStream.h @@ -1,92 +1,92 @@ -/* Audio Source Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioSourceReader_H -#define PokemonAutomation_AudioPipeline_AudioSourceReader_H - -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/StreamConverters.h" -#include "Common/Cpp/Containers/AlignedVector.h" -#include "AudioInfo.h" - -namespace PokemonAutomation{ - - -struct AudioFloatStreamListener{ - AudioFloatStreamListener(size_t p_expected_samples_per_frame) - : expected_samples_per_frame(p_expected_samples_per_frame) - {} - virtual ~AudioFloatStreamListener() = default; - virtual void on_samples(const float* data, size_t frames) = 0; - - size_t expected_samples_per_frame; -}; - - - -// Convert a stream of raw audio and output to aligned frames of float samples. -class AudioStreamToFloat : private MisalignedStreamConverter, private StreamListener{ -public: - void add_listener(AudioFloatStreamListener& listener); - void remove_listener(AudioFloatStreamListener& listener); - -public: - AudioStreamToFloat( - AudioSampleFormat input_format, - size_t samples_per_frame, // Typically the # of channels. Can be higher if you want to group more into each frame. - float volume_multiplier, // Multiply every sample by this constant. - bool reverse_channels // Only valid if "samples_per_frame == 2". - ); - virtual ~AudioStreamToFloat(); - - using MisalignedStreamConverter::push_bytes; - -private: - virtual void on_objects(const void* data, size_t objects) override; - virtual void convert(void* out, const void* in, size_t count) override; - -private: - AudioSampleFormat m_format; - size_t m_samples_per_frame; - float m_volume_multiplier; - bool m_reverse_channels; - size_t m_sample_size; - size_t m_frame_size; - std::set m_listeners; - - LifetimeSanitizer m_sanitizer; -}; - - - -// Convert a stream of float samples to raw audio. -class AudioFloatToStream : public AudioFloatStreamListener{ -public: - void add_listener(StreamListener& listener); - void remove_listener(StreamListener& listener); - -public: - AudioFloatToStream(AudioSampleFormat output_format, size_t samples_per_frame); - virtual ~AudioFloatToStream(); - virtual void on_samples(const float* data, size_t frames) override; - -private: - AudioSampleFormat m_format; - size_t m_samples_per_frame; - size_t m_sample_size; - size_t m_frame_size; - size_t m_buffer_size; - AlignedVector m_buffer; - ListenerSet m_listeners; - - LifetimeSanitizer m_sanitizer; -}; - - - -} -#endif +/* Audio Source Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioSourceReader_H +#define PokemonAutomation_AudioPipeline_AudioSourceReader_H + +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/StreamConverters.h" +#include "Common/Cpp/Containers/AlignedVector.h" +#include "AudioInfo.h" + +namespace PokemonAutomation{ + + +struct AudioFloatStreamListener{ + AudioFloatStreamListener(size_t p_expected_samples_per_frame) + : expected_samples_per_frame(p_expected_samples_per_frame) + {} + virtual ~AudioFloatStreamListener() = default; + virtual void on_samples(const float* data, size_t frames) = 0; + + size_t expected_samples_per_frame; +}; + + + +// Convert a stream of raw audio and output to aligned frames of float samples. +class AudioStreamToFloat : private MisalignedStreamConverter, private StreamListener{ +public: + void add_listener(AudioFloatStreamListener& listener); + void remove_listener(AudioFloatStreamListener& listener); + +public: + AudioStreamToFloat( + AudioSampleFormat input_format, + size_t samples_per_frame, // Typically the # of channels. Can be higher if you want to group more into each frame. + float volume_multiplier, // Multiply every sample by this constant. + bool reverse_channels // Only valid if "samples_per_frame == 2". + ); + virtual ~AudioStreamToFloat(); + + using MisalignedStreamConverter::push_bytes; + +private: + virtual void on_objects(const void* data, size_t objects) override; + virtual void convert(void* out, const void* in, size_t count) override; + +private: + AudioSampleFormat m_format; + size_t m_samples_per_frame; + float m_volume_multiplier; + bool m_reverse_channels; + size_t m_sample_size; + size_t m_frame_size; + std::set m_listeners; + + LifetimeSanitizer m_sanitizer; +}; + + + +// Convert a stream of float samples to raw audio. +class AudioFloatToStream : public AudioFloatStreamListener{ +public: + void add_listener(StreamListener& listener); + void remove_listener(StreamListener& listener); + +public: + AudioFloatToStream(AudioSampleFormat output_format, size_t samples_per_frame); + virtual ~AudioFloatToStream(); + virtual void on_samples(const float* data, size_t frames) override; + +private: + AudioSampleFormat m_format; + size_t m_samples_per_frame; + size_t m_sample_size; + size_t m_frame_size; + size_t m_buffer_size; + AlignedVector m_buffer; + ListenerSet m_listeners; + + LifetimeSanitizer m_sanitizer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.cpp index d4875e3714..aa3b22b1fe 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.cpp @@ -1,114 +1,114 @@ -/* Audio Template - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/Logging/Logger.h" -#include "Kernels/Kernels_Alignment.h" -#include "Kernels/AbsFFT/Kernels_AbsFFT.h" -#include "AudioConstants.h" -#include "AudioTemplate.h" -#include "Tools/AudioFormatUtils.h" -#include "IO/AudioFileLoader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -AudioTemplate::~AudioTemplate(){} -AudioTemplate::AudioTemplate(AudioTemplate&& x) = default; -AudioTemplate& AudioTemplate::operator=(AudioTemplate&& x) = default; -AudioTemplate::AudioTemplate(const AudioTemplate&) = default; -AudioTemplate& AudioTemplate::operator=(const AudioTemplate&) = default; - -AudioTemplate::AudioTemplate(){} -AudioTemplate::AudioTemplate(size_t frequencies, size_t windows) - : m_numWindows(windows) - , m_numFrequencies(frequencies) - , m_bytes_per_spectrum(Kernels::align_int_up(frequencies * sizeof(float))) - , m_spectrogram(windows * (m_bytes_per_spectrum / sizeof(float))) -{} - - -AudioTemplate loadAudioTemplate(const std::string& filename, size_t sample_rate){ - QAudioFormat outputAudioFormat; - outputAudioFormat.setChannelCount(1); -#if QT_VERSION_MAJOR == 5 - outputAudioFormat.setCodec("audio/pcm"); -#endif - outputAudioFormat.setSampleRate((int)sample_rate); - setSampleFormatToFloat(outputAudioFormat); - - AudioFileLoader loader(nullptr, filename, outputAudioFormat); - const auto ret = loader.loadFullAudio(); - const float* data = reinterpret_cast(std::get<0>(ret)); - size_t numSamples = std::get<1>(ret) / sizeof(float); -// cout << "numSamples = " << numSamples << endl; - - if (data == nullptr){ - return AudioTemplate(); - } - - size_t numFrequencies = NUM_FFT_SAMPLES / 2; - AlignedVector input_buffer(NUM_FFT_SAMPLES); - AlignedVector output_buffer(numFrequencies); - - size_t numWindows = 0; - AudioTemplate audio_template; - - // If sample count < FFT input requirement, we pad zeros in the end to do one FFT. - // Otherwise, we don't pad zeros and compute FFT as much as possible using fixed - // window step. - if (numSamples < NUM_FFT_SAMPLES){ - numWindows = 1; - audio_template = AudioTemplate(numFrequencies, 1); - - memset(input_buffer.data(), 0, sizeof(float) * NUM_FFT_SAMPLES); - memcpy(input_buffer.data(), data, sizeof(float) * numSamples); - Kernels::AbsFFT::fft_abs(FFT_LENGTH_POWER_OF_TWO, output_buffer.data(), input_buffer.data()); - memcpy(audio_template.getWindow(0), output_buffer.data(), sizeof(float) * numFrequencies); - }else{ - numWindows = (numSamples - NUM_FFT_SAMPLES) / FFT_SLIDING_WINDOW_STEP + 1; - audio_template = AudioTemplate(numFrequencies, numWindows); - - for (size_t i = 0, start = 0; start+NUM_FFT_SAMPLES <= numSamples; i++, start += FFT_SLIDING_WINDOW_STEP){ - assert(i < numWindows); - memcpy(input_buffer.data(), data + start, sizeof(float) * NUM_FFT_SAMPLES); - Kernels::AbsFFT::fft_abs(FFT_LENGTH_POWER_OF_TWO, output_buffer.data(), input_buffer.data()); - memcpy(audio_template.getWindow(i), output_buffer.data(), sizeof(float) * numFrequencies); - } - } - - - std::stringstream ss; - ss << "Built audio template with sample rate " << sample_rate << ", " << numWindows << " windows and " << numFrequencies << - " frequencies from " << filename; - global_logger_tagged().log(ss.str()); - - return audio_template; -} - - - - - - - - - - - - - - - - - - -} +/* Audio Template + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/Logging/Logger.h" +#include "Kernels/Kernels_Alignment.h" +#include "Kernels/AbsFFT/Kernels_AbsFFT.h" +#include "AudioConstants.h" +#include "AudioTemplate.h" +#include "Tools/AudioFormatUtils.h" +#include "IO/AudioFileLoader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +AudioTemplate::~AudioTemplate(){} +AudioTemplate::AudioTemplate(AudioTemplate&& x) = default; +AudioTemplate& AudioTemplate::operator=(AudioTemplate&& x) = default; +AudioTemplate::AudioTemplate(const AudioTemplate&) = default; +AudioTemplate& AudioTemplate::operator=(const AudioTemplate&) = default; + +AudioTemplate::AudioTemplate(){} +AudioTemplate::AudioTemplate(size_t frequencies, size_t windows) + : m_numWindows(windows) + , m_numFrequencies(frequencies) + , m_bytes_per_spectrum(Kernels::align_int_up(frequencies * sizeof(float))) + , m_spectrogram(windows * (m_bytes_per_spectrum / sizeof(float))) +{} + + +AudioTemplate loadAudioTemplate(const std::string& filename, size_t sample_rate){ + QAudioFormat outputAudioFormat; + outputAudioFormat.setChannelCount(1); +#if QT_VERSION_MAJOR == 5 + outputAudioFormat.setCodec("audio/pcm"); +#endif + outputAudioFormat.setSampleRate((int)sample_rate); + setSampleFormatToFloat(outputAudioFormat); + + AudioFileLoader loader(nullptr, filename, outputAudioFormat); + const auto ret = loader.loadFullAudio(); + const float* data = reinterpret_cast(std::get<0>(ret)); + size_t numSamples = std::get<1>(ret) / sizeof(float); +// cout << "numSamples = " << numSamples << endl; + + if (data == nullptr){ + return AudioTemplate(); + } + + size_t numFrequencies = NUM_FFT_SAMPLES / 2; + AlignedVector input_buffer(NUM_FFT_SAMPLES); + AlignedVector output_buffer(numFrequencies); + + size_t numWindows = 0; + AudioTemplate audio_template; + + // If sample count < FFT input requirement, we pad zeros in the end to do one FFT. + // Otherwise, we don't pad zeros and compute FFT as much as possible using fixed + // window step. + if (numSamples < NUM_FFT_SAMPLES){ + numWindows = 1; + audio_template = AudioTemplate(numFrequencies, 1); + + memset(input_buffer.data(), 0, sizeof(float) * NUM_FFT_SAMPLES); + memcpy(input_buffer.data(), data, sizeof(float) * numSamples); + Kernels::AbsFFT::fft_abs(FFT_LENGTH_POWER_OF_TWO, output_buffer.data(), input_buffer.data()); + memcpy(audio_template.getWindow(0), output_buffer.data(), sizeof(float) * numFrequencies); + }else{ + numWindows = (numSamples - NUM_FFT_SAMPLES) / FFT_SLIDING_WINDOW_STEP + 1; + audio_template = AudioTemplate(numFrequencies, numWindows); + + for (size_t i = 0, start = 0; start+NUM_FFT_SAMPLES <= numSamples; i++, start += FFT_SLIDING_WINDOW_STEP){ + assert(i < numWindows); + memcpy(input_buffer.data(), data + start, sizeof(float) * NUM_FFT_SAMPLES); + Kernels::AbsFFT::fft_abs(FFT_LENGTH_POWER_OF_TWO, output_buffer.data(), input_buffer.data()); + memcpy(audio_template.getWindow(i), output_buffer.data(), sizeof(float) * numFrequencies); + } + } + + + std::stringstream ss; + ss << "Built audio template with sample rate " << sample_rate << ", " << numWindows << " windows and " << numFrequencies << + " frequencies from " << filename; + global_logger_tagged().log(ss.str()); + + return audio_template; +} + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.h index a5356af1b0..04c67059ec 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/AudioTemplate.h @@ -1,69 +1,69 @@ -/* Audio Template - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioTemplate_H -#define PokemonAutomation_AudioPipeline_AudioTemplate_H - -#include -#include -#include -#include "Common/Cpp/Containers/AlignedVector.h" - -namespace PokemonAutomation{ - - -// Hold the spectrogram of an audio, used as a template to -// match sounds from an audio stream. -class AudioTemplate{ -public: - ~AudioTemplate(); - AudioTemplate(AudioTemplate&& x); - AudioTemplate& operator=(AudioTemplate&& x); - AudioTemplate(const AudioTemplate&); - AudioTemplate& operator=(const AudioTemplate&); - -public: - AudioTemplate(); - AudioTemplate(size_t frequencies, size_t windows); - - size_t numWindows() const{ return m_numWindows; } - size_t numFrequencies() const{ return m_numFrequencies; } - - // Size of the buffer that holds this template. - // This is "numFrequencies()", rounded up to the SIMD size. - size_t bufferSize() const{ return m_spectrogram.size(); } - - const float* getWindow(size_t windowIndex) const{ - return (const float*)((const char*)m_spectrogram.data() + windowIndex * m_bytes_per_spectrum); - } - float* getWindow(size_t windowIndex){ - return (float*)((char*)m_spectrogram.data() + windowIndex * m_bytes_per_spectrum); - } - -// void scale(float s) { for(auto& v: m_spectrogram) v *= s; } - -private: - size_t m_numWindows = 0; - size_t m_numFrequencies = 0; - size_t m_bytes_per_spectrum; - AlignedVector m_spectrogram; -}; - -// Load AudioTemplate from disk. Accept .wav format on any OS. -// Loading .mp3 format however is dependent on Qt's platform-dependent backend. -AudioTemplate loadAudioTemplate(const std::string& filename, size_t sample_rate = 48000); - - - - - - - - - -} - -#endif +/* Audio Template + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioTemplate_H +#define PokemonAutomation_AudioPipeline_AudioTemplate_H + +#include +#include +#include +#include "Common/Cpp/Containers/AlignedVector.h" + +namespace PokemonAutomation{ + + +// Hold the spectrogram of an audio, used as a template to +// match sounds from an audio stream. +class AudioTemplate{ +public: + ~AudioTemplate(); + AudioTemplate(AudioTemplate&& x); + AudioTemplate& operator=(AudioTemplate&& x); + AudioTemplate(const AudioTemplate&); + AudioTemplate& operator=(const AudioTemplate&); + +public: + AudioTemplate(); + AudioTemplate(size_t frequencies, size_t windows); + + size_t numWindows() const{ return m_numWindows; } + size_t numFrequencies() const{ return m_numFrequencies; } + + // Size of the buffer that holds this template. + // This is "numFrequencies()", rounded up to the SIMD size. + size_t bufferSize() const{ return m_spectrogram.size(); } + + const float* getWindow(size_t windowIndex) const{ + return (const float*)((const char*)m_spectrogram.data() + windowIndex * m_bytes_per_spectrum); + } + float* getWindow(size_t windowIndex){ + return (float*)((char*)m_spectrogram.data() + windowIndex * m_bytes_per_spectrum); + } + +// void scale(float s) { for(auto& v: m_spectrogram) v *= s; } + +private: + size_t m_numWindows = 0; + size_t m_numFrequencies = 0; + size_t m_bytes_per_spectrum; + AlignedVector m_spectrogram; +}; + +// Load AudioTemplate from disk. Accept .wav format on any OS. +// Loading .mp3 format however is dependent on Qt's platform-dependent backend. +AudioTemplate loadAudioTemplate(const std::string& filename, size_t sample_rate = 48000); + + + + + + + + + +} + +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.cpp index 92b7a1ff04..dd6a29ed7d 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.cpp @@ -1,299 +1,299 @@ -/* Audio Passthrough Pair (Qt) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" -//#include "CommonFramework/AudioPipeline/AudioConstants.h" -//#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" -#include "CommonFramework/AudioPipeline/IO/AudioSource.h" -#include "CommonFramework/AudioPipeline/IO/AudioSink.h" -#include "CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h" -#include "AudioPassthroughPairQt.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void AudioPassthroughPairQt::add_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - m_stream_listeners.add(listener); -} -void AudioPassthroughPairQt::remove_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - m_stream_listeners.remove(listener); -} -void AudioPassthroughPairQt::add_listener(FFTListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_fft_listeners.add(listener); -} -void AudioPassthroughPairQt::remove_listener(FFTListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_fft_listeners.remove(listener); -} - - - -class AudioPassthroughPairQt::SampleListener final : public AudioFloatStreamListener{ -public: - SampleListener(AudioPassthroughPairQt& parent, size_t samples_per_frame) - : AudioFloatStreamListener(samples_per_frame) - , m_parent(parent) - { - parent.m_reader->add_listener(*this); - } - ~SampleListener(){ - m_parent.m_reader->remove_listener(*this); - } - virtual void on_samples(const float* data, size_t frames) override{ - { - AudioPassthroughPairQt& parent = m_parent; - WriteSpinLock lg(parent.m_lock); - if (parent.m_writer){ - AudioFloatStreamListener* listener = parent.m_writer->float_stream_listener(); - if (listener){ - listener->on_samples(data, frames); - } - } - if (parent.m_fft_runner){ - parent.m_fft_runner->on_samples(data, frames); - } - } - m_parent.m_stream_listeners.run_method_unique( - &AudioFloatStreamListener::on_samples, - data, frames - ); - } - -private: - AudioPassthroughPairQt& m_parent; -}; - -class AudioPassthroughPairQt::InternalFFTListener final : public FFTListener{ -public: - InternalFFTListener(AudioPassthroughPairQt& parent) - : m_parent(parent) - { - parent.m_fft_runner->add_listener(*this); - } - ~InternalFFTListener(){ - m_parent.m_fft_runner->remove_listener(*this); - } - virtual void on_fft(size_t sample_rate, std::shared_ptr> fft_output) override{ - m_parent.m_fft_listeners.run_method_unique( - &FFTListener::on_fft, - sample_rate, fft_output - ); - } - -private: - AudioPassthroughPairQt& m_parent; -}; - - - - - -AudioPassthroughPairQt::~AudioPassthroughPairQt(){} - -AudioPassthroughPairQt::AudioPassthroughPairQt(Logger& logger) - : m_logger(logger) - , m_file_input_multiplier((float)GlobalSettings::instance().AUDIO_PIPELINE->FILE_VOLUME_SCALE) - , m_device_input_multiplier((float)GlobalSettings::instance().AUDIO_PIPELINE->DEVICE_VOLUME_SCALE) -{} - -void AudioPassthroughPairQt::reset( - const std::string& file, - const AudioDeviceInfo& output, double output_volume -){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, file, output, output_volume]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - if (m_reader){ - m_fft_listener.reset(); - m_fft_runner.reset(); - m_writer.reset(); - m_sample_listener.reset(); - m_reader.reset(); - m_input_format = AudioChannelFormat::NONE; - } - m_input_format = AudioChannelFormat::DUAL_48000; - m_reader.reset(new AudioSource(m_logger, file, m_input_format, m_file_input_multiplier)); - m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); - m_output_device = output; - m_output_volume = output_volume; - init_audio_sink(); - m_fft_runner = make_FFT_streamer(m_input_format); - m_fft_listener.reset(new InternalFFTListener(*this)); - }); -} -void AudioPassthroughPairQt::reset( - const AudioDeviceInfo& input, AudioChannelFormat format, - const AudioDeviceInfo& output, double output_volume -){ - auto scope_check = m_sanitizer.check_scope(); -// cout << "AudioPassthroughPairQt::reset(): " << output.display_name() << endl; - QMetaObject::invokeMethod(this, [this, format, output, output_volume, input]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - if (m_reader){ - m_fft_listener.reset(); - m_fft_runner.reset(); - m_writer.reset(); - m_sample_listener.reset(); - m_reader.reset(); - m_input_format = AudioChannelFormat::NONE; - } - m_input_format = format; - m_output_device = output; - m_output_volume = output_volume; - if (input && format != AudioChannelFormat::NONE){ - m_reader.reset(new AudioSource(m_logger, input, m_input_format, m_device_input_multiplier)); - m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); - init_audio_sink(); - m_fft_runner = make_FFT_streamer(m_input_format); - m_fft_listener.reset(new InternalFFTListener(*this)); - } - }); -} -void AudioPassthroughPairQt::clear_audio_source(){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - if (m_reader){ - m_fft_listener.reset(); - m_fft_runner.reset(); - m_sample_listener.reset(); - m_reader.reset(); - m_input_format = AudioChannelFormat::NONE; - } - }); -} -void AudioPassthroughPairQt::set_audio_source(const std::string& file){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, file]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - if (m_reader){ - m_fft_listener.reset(); - m_fft_runner.reset(); - m_writer.reset(); - m_sample_listener.reset(); - m_reader.reset(); - m_input_format = AudioChannelFormat::NONE; - } - m_input_format = AudioChannelFormat::DUAL_48000; - m_reader.reset(new AudioSource(m_logger, file, m_input_format, m_file_input_multiplier)); - m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); - init_audio_sink(); - m_fft_runner = make_FFT_streamer(m_input_format); - m_fft_listener.reset(new InternalFFTListener(*this)); - }); -} -void AudioPassthroughPairQt::set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, format, device]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - if (m_reader){ - m_fft_listener.reset(); - m_fft_runner.reset(); - m_writer.reset(); - m_sample_listener.reset(); - m_reader.reset(); - m_input_format = AudioChannelFormat::NONE; - } - m_input_format = format; - if (device){ - m_reader.reset(new AudioSource(m_logger, device, m_input_format, m_device_input_multiplier)); - m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); - init_audio_sink(); - m_fft_runner = make_FFT_streamer(m_input_format); - m_fft_listener.reset(new InternalFFTListener(*this)); - } - }); -} - -void AudioPassthroughPairQt::clear_audio_sink(){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_writer.reset(); - m_output_device = AudioDeviceInfo(); - }); -} -void AudioPassthroughPairQt::set_audio_sink(const AudioDeviceInfo& device, double volume){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, device, volume]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_writer.reset(); - m_output_device = device; - m_output_volume = volume; - init_audio_sink(); - }); -} -void AudioPassthroughPairQt::init_audio_sink(){ - auto scope_check = m_sanitizer.check_scope(); -// cout << "AudioPassthroughPairQt::init_audio_sink()" << endl; - QMetaObject::invokeMethod(this, [this]{ - auto scope_check = m_sanitizer.check_scope(); - if (!m_output_device){ -// cout << "AudioPassthroughPairQt::init_audio_sink() - early out" << endl; - return; - } - AudioChannelFormat output_format = m_input_format; - switch (output_format){ - case AudioChannelFormat::NONE: - return; - case AudioChannelFormat::MONO_48000: - case AudioChannelFormat::MONO_96000: - case AudioChannelFormat::DUAL_44100: - case AudioChannelFormat::DUAL_48000: - break; - case AudioChannelFormat::INTERLEAVE_LR_96000: - case AudioChannelFormat::INTERLEAVE_RL_96000: - output_format = AudioChannelFormat::DUAL_48000; - break; - default: - m_logger.log(std::string("Invalid AudioFormat: ") + AUDIO_FORMAT_LABELS[(size_t)output_format], COLOR_RED); - return; - } -// cout << "AudioPassthroughPairQt::init_audio_sink() - end" << endl; - m_writer.reset(new AudioSink(m_logger, m_output_device, output_format, m_output_volume)); - }); -} - - -void AudioPassthroughPairQt::set_sink_volume(double volume){ - auto scope_check = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, volume]{ - auto scope_check = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_output_volume = volume; - if (m_writer){ - m_writer->set_volume(volume); - } - }); -} - - - - - - - -} +/* Audio Passthrough Pair (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" +//#include "CommonFramework/AudioPipeline/AudioConstants.h" +//#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" +#include "CommonFramework/AudioPipeline/IO/AudioSource.h" +#include "CommonFramework/AudioPipeline/IO/AudioSink.h" +#include "CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h" +#include "AudioPassthroughPairQt.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void AudioPassthroughPairQt::add_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_stream_listeners.add(listener); +} +void AudioPassthroughPairQt::remove_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_stream_listeners.remove(listener); +} +void AudioPassthroughPairQt::add_listener(FFTListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_fft_listeners.add(listener); +} +void AudioPassthroughPairQt::remove_listener(FFTListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_fft_listeners.remove(listener); +} + + + +class AudioPassthroughPairQt::SampleListener final : public AudioFloatStreamListener{ +public: + SampleListener(AudioPassthroughPairQt& parent, size_t samples_per_frame) + : AudioFloatStreamListener(samples_per_frame) + , m_parent(parent) + { + parent.m_reader->add_listener(*this); + } + ~SampleListener(){ + m_parent.m_reader->remove_listener(*this); + } + virtual void on_samples(const float* data, size_t frames) override{ + { + AudioPassthroughPairQt& parent = m_parent; + WriteSpinLock lg(parent.m_lock); + if (parent.m_writer){ + AudioFloatStreamListener* listener = parent.m_writer->float_stream_listener(); + if (listener){ + listener->on_samples(data, frames); + } + } + if (parent.m_fft_runner){ + parent.m_fft_runner->on_samples(data, frames); + } + } + m_parent.m_stream_listeners.run_method_unique( + &AudioFloatStreamListener::on_samples, + data, frames + ); + } + +private: + AudioPassthroughPairQt& m_parent; +}; + +class AudioPassthroughPairQt::InternalFFTListener final : public FFTListener{ +public: + InternalFFTListener(AudioPassthroughPairQt& parent) + : m_parent(parent) + { + parent.m_fft_runner->add_listener(*this); + } + ~InternalFFTListener(){ + m_parent.m_fft_runner->remove_listener(*this); + } + virtual void on_fft(size_t sample_rate, std::shared_ptr> fft_output) override{ + m_parent.m_fft_listeners.run_method_unique( + &FFTListener::on_fft, + sample_rate, fft_output + ); + } + +private: + AudioPassthroughPairQt& m_parent; +}; + + + + + +AudioPassthroughPairQt::~AudioPassthroughPairQt(){} + +AudioPassthroughPairQt::AudioPassthroughPairQt(Logger& logger) + : m_logger(logger) + , m_file_input_multiplier((float)GlobalSettings::instance().AUDIO_PIPELINE->FILE_VOLUME_SCALE) + , m_device_input_multiplier((float)GlobalSettings::instance().AUDIO_PIPELINE->DEVICE_VOLUME_SCALE) +{} + +void AudioPassthroughPairQt::reset( + const std::string& file, + const AudioDeviceInfo& output, double output_volume +){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, file, output, output_volume]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + if (m_reader){ + m_fft_listener.reset(); + m_fft_runner.reset(); + m_writer.reset(); + m_sample_listener.reset(); + m_reader.reset(); + m_input_format = AudioChannelFormat::NONE; + } + m_input_format = AudioChannelFormat::DUAL_48000; + m_reader.reset(new AudioSource(m_logger, file, m_input_format, m_file_input_multiplier)); + m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); + m_output_device = output; + m_output_volume = output_volume; + init_audio_sink(); + m_fft_runner = make_FFT_streamer(m_input_format); + m_fft_listener.reset(new InternalFFTListener(*this)); + }); +} +void AudioPassthroughPairQt::reset( + const AudioDeviceInfo& input, AudioChannelFormat format, + const AudioDeviceInfo& output, double output_volume +){ + auto scope_check = m_sanitizer.check_scope(); +// cout << "AudioPassthroughPairQt::reset(): " << output.display_name() << endl; + QMetaObject::invokeMethod(this, [this, format, output, output_volume, input]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + if (m_reader){ + m_fft_listener.reset(); + m_fft_runner.reset(); + m_writer.reset(); + m_sample_listener.reset(); + m_reader.reset(); + m_input_format = AudioChannelFormat::NONE; + } + m_input_format = format; + m_output_device = output; + m_output_volume = output_volume; + if (input && format != AudioChannelFormat::NONE){ + m_reader.reset(new AudioSource(m_logger, input, m_input_format, m_device_input_multiplier)); + m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); + init_audio_sink(); + m_fft_runner = make_FFT_streamer(m_input_format); + m_fft_listener.reset(new InternalFFTListener(*this)); + } + }); +} +void AudioPassthroughPairQt::clear_audio_source(){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + if (m_reader){ + m_fft_listener.reset(); + m_fft_runner.reset(); + m_sample_listener.reset(); + m_reader.reset(); + m_input_format = AudioChannelFormat::NONE; + } + }); +} +void AudioPassthroughPairQt::set_audio_source(const std::string& file){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, file]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + if (m_reader){ + m_fft_listener.reset(); + m_fft_runner.reset(); + m_writer.reset(); + m_sample_listener.reset(); + m_reader.reset(); + m_input_format = AudioChannelFormat::NONE; + } + m_input_format = AudioChannelFormat::DUAL_48000; + m_reader.reset(new AudioSource(m_logger, file, m_input_format, m_file_input_multiplier)); + m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); + init_audio_sink(); + m_fft_runner = make_FFT_streamer(m_input_format); + m_fft_listener.reset(new InternalFFTListener(*this)); + }); +} +void AudioPassthroughPairQt::set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, format, device]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + if (m_reader){ + m_fft_listener.reset(); + m_fft_runner.reset(); + m_writer.reset(); + m_sample_listener.reset(); + m_reader.reset(); + m_input_format = AudioChannelFormat::NONE; + } + m_input_format = format; + if (device){ + m_reader.reset(new AudioSource(m_logger, device, m_input_format, m_device_input_multiplier)); + m_sample_listener.reset(new SampleListener(*this, m_reader->samples_per_frame())); + init_audio_sink(); + m_fft_runner = make_FFT_streamer(m_input_format); + m_fft_listener.reset(new InternalFFTListener(*this)); + } + }); +} + +void AudioPassthroughPairQt::clear_audio_sink(){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_writer.reset(); + m_output_device = AudioDeviceInfo(); + }); +} +void AudioPassthroughPairQt::set_audio_sink(const AudioDeviceInfo& device, double volume){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, device, volume]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_writer.reset(); + m_output_device = device; + m_output_volume = volume; + init_audio_sink(); + }); +} +void AudioPassthroughPairQt::init_audio_sink(){ + auto scope_check = m_sanitizer.check_scope(); +// cout << "AudioPassthroughPairQt::init_audio_sink()" << endl; + QMetaObject::invokeMethod(this, [this]{ + auto scope_check = m_sanitizer.check_scope(); + if (!m_output_device){ +// cout << "AudioPassthroughPairQt::init_audio_sink() - early out" << endl; + return; + } + AudioChannelFormat output_format = m_input_format; + switch (output_format){ + case AudioChannelFormat::NONE: + return; + case AudioChannelFormat::MONO_48000: + case AudioChannelFormat::MONO_96000: + case AudioChannelFormat::DUAL_44100: + case AudioChannelFormat::DUAL_48000: + break; + case AudioChannelFormat::INTERLEAVE_LR_96000: + case AudioChannelFormat::INTERLEAVE_RL_96000: + output_format = AudioChannelFormat::DUAL_48000; + break; + default: + m_logger.log(std::string("Invalid AudioFormat: ") + AUDIO_FORMAT_LABELS[(size_t)output_format], COLOR_RED); + return; + } +// cout << "AudioPassthroughPairQt::init_audio_sink() - end" << endl; + m_writer.reset(new AudioSink(m_logger, m_output_device, output_format, m_output_volume)); + }); +} + + +void AudioPassthroughPairQt::set_sink_volume(double volume){ + auto scope_check = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, volume]{ + auto scope_check = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_output_volume = volume; + if (m_writer){ + m_writer->set_volume(volume); + } + }); +} + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.h index 460bafca18..257b2571bb 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQt.h @@ -1,96 +1,96 @@ -/* Audio Passthrough Pair (Qt) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioPassthroughPairQt_H -#define PokemonAutomation_AudioPipeline_AudioPassthroughPairQt_H - -#include -#include -#include -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/AudioPipeline/AudioPassthroughPair.h" - -namespace PokemonAutomation{ - -class Logger; -class AudioSource; -class AudioSink; -class AudioFloatToFFT; - - -class AudioPassthroughPairQt final : public QObject, public AudioPassthroughPair{ -public: - virtual void add_listener(AudioFloatStreamListener& listener) override; - virtual void remove_listener(AudioFloatStreamListener& listener) override; - - virtual void add_listener(FFTListener& listener) override; - virtual void remove_listener(FFTListener& listener) override; - - -public: - virtual ~AudioPassthroughPairQt(); - AudioPassthroughPairQt(Logger& logger); - - virtual void reset( - const std::string& file, - const AudioDeviceInfo& output, double output_volume - ) override; - virtual void reset( - const AudioDeviceInfo& input, AudioChannelFormat format, - const AudioDeviceInfo& output, double output_volume - ) override; - - virtual void clear_audio_source() override; - virtual void set_audio_source(const std::string& file) override; - virtual void set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format) override; - - virtual void clear_audio_sink() override; - virtual void set_audio_sink(const AudioDeviceInfo& device, double volume) override; - - virtual void set_sink_volume(double volume) override; - - -private: - class SampleListener; - class InternalFFTListener; - - void init_audio_sink(); - - -private: - Logger& m_logger; - - mutable SpinLock m_lock; - - // The order of these parameters is important due to destruction order. - // Objects lower on this list attach to and hold references to those - // higher on the list. - - AudioChannelFormat m_input_format; - std::unique_ptr m_reader; - std::unique_ptr m_sample_listener; // Attaches to "m_reader". - - AudioDeviceInfo m_output_device; - float m_file_input_multiplier = 1.0; - float m_device_input_multiplier = 1.0; - double m_output_volume = 1.0; - std::unique_ptr m_writer; - - std::unique_ptr m_fft_runner; - std::unique_ptr m_fft_listener; // Attaches to m_fft_runner"". - - ListenerSet m_stream_listeners; - ListenerSet m_fft_listeners; - - LifetimeSanitizer m_sanitizer; -}; - - - -} -#endif +/* Audio Passthrough Pair (Qt) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioPassthroughPairQt_H +#define PokemonAutomation_AudioPipeline_AudioPassthroughPairQt_H + +#include +#include +#include +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/AudioPipeline/AudioPassthroughPair.h" + +namespace PokemonAutomation{ + +class Logger; +class AudioSource; +class AudioSink; +class AudioFloatToFFT; + + +class AudioPassthroughPairQt final : public QObject, public AudioPassthroughPair{ +public: + virtual void add_listener(AudioFloatStreamListener& listener) override; + virtual void remove_listener(AudioFloatStreamListener& listener) override; + + virtual void add_listener(FFTListener& listener) override; + virtual void remove_listener(FFTListener& listener) override; + + +public: + virtual ~AudioPassthroughPairQt(); + AudioPassthroughPairQt(Logger& logger); + + virtual void reset( + const std::string& file, + const AudioDeviceInfo& output, double output_volume + ) override; + virtual void reset( + const AudioDeviceInfo& input, AudioChannelFormat format, + const AudioDeviceInfo& output, double output_volume + ) override; + + virtual void clear_audio_source() override; + virtual void set_audio_source(const std::string& file) override; + virtual void set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format) override; + + virtual void clear_audio_sink() override; + virtual void set_audio_sink(const AudioDeviceInfo& device, double volume) override; + + virtual void set_sink_volume(double volume) override; + + +private: + class SampleListener; + class InternalFFTListener; + + void init_audio_sink(); + + +private: + Logger& m_logger; + + mutable SpinLock m_lock; + + // The order of these parameters is important due to destruction order. + // Objects lower on this list attach to and hold references to those + // higher on the list. + + AudioChannelFormat m_input_format; + std::unique_ptr m_reader; + std::unique_ptr m_sample_listener; // Attaches to "m_reader". + + AudioDeviceInfo m_output_device; + float m_file_input_multiplier = 1.0; + float m_device_input_multiplier = 1.0; + double m_output_volume = 1.0; + std::unique_ptr m_writer; + + std::unique_ptr m_fft_runner; + std::unique_ptr m_fft_listener; // Attaches to m_fft_runner"". + + ListenerSet m_stream_listeners; + ListenerSet m_fft_listeners; + + LifetimeSanitizer m_sanitizer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp index 69098a9f03..d81cc1508c 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.cpp @@ -1,123 +1,123 @@ -/* Audio Passthrough Pair (Qt separate thread) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "AudioPassthroughPairQt.h" -#include "AudioPassthroughPairQtThread.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -void AudioPassthroughPairQtThread::add_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->add_listener(listener); -} -void AudioPassthroughPairQtThread::remove_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->remove_listener(listener); -} -void AudioPassthroughPairQtThread::add_listener(FFTListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->add_listener(listener); -} -void AudioPassthroughPairQtThread::remove_listener(FFTListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->remove_listener(listener); -} - - -AudioPassthroughPairQtThread::AudioPassthroughPairQtThread(Logger& logger) - : m_logger(logger) - , m_body(nullptr) -{ - start(); - - // Wait for the thread to fully start up and construct the body. - while (m_body.load(std::memory_order_acquire) == nullptr){ - pause(); - } -} -AudioPassthroughPairQtThread::~AudioPassthroughPairQtThread(){ - m_body.store(nullptr, std::memory_order_relaxed); - quit(); - wait(); -} -void AudioPassthroughPairQtThread::run(){ - auto scope_check = m_sanitizer.check_scope(); - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - - AudioPassthroughPairQt body(m_logger); - m_body.store(&body, std::memory_order_relaxed); - exec(); - - // Wait until we are in the destructor before destroying the body. - while (m_body.load(std::memory_order_acquire) != nullptr){ - pause(); - } -} - - -void AudioPassthroughPairQtThread::reset( - const std::string& file, - const AudioDeviceInfo& output, double output_volume -){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->reset(file, output, output_volume); -} -void AudioPassthroughPairQtThread::reset( - const AudioDeviceInfo& input, AudioChannelFormat format, - const AudioDeviceInfo& output, double output_volume -){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->reset(input, format, output, output_volume); -} -void AudioPassthroughPairQtThread::clear_audio_source(){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->clear_audio_source(); -} -void AudioPassthroughPairQtThread::set_audio_source(const std::string& file){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->set_audio_source(file); -} -void AudioPassthroughPairQtThread::set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->set_audio_source(device, format); -} -void AudioPassthroughPairQtThread::clear_audio_sink(){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->clear_audio_sink(); -} -void AudioPassthroughPairQtThread::set_audio_sink(const AudioDeviceInfo& device, double volume){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->set_audio_sink(device, volume); -} -void AudioPassthroughPairQtThread::set_sink_volume(double volume){ - auto scope_check = m_sanitizer.check_scope(); - AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); - body->set_sink_volume(volume); -} - - - - -} +/* Audio Passthrough Pair (Qt separate thread) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "AudioPassthroughPairQt.h" +#include "AudioPassthroughPairQtThread.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +void AudioPassthroughPairQtThread::add_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->add_listener(listener); +} +void AudioPassthroughPairQtThread::remove_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->remove_listener(listener); +} +void AudioPassthroughPairQtThread::add_listener(FFTListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->add_listener(listener); +} +void AudioPassthroughPairQtThread::remove_listener(FFTListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->remove_listener(listener); +} + + +AudioPassthroughPairQtThread::AudioPassthroughPairQtThread(Logger& logger) + : m_logger(logger) + , m_body(nullptr) +{ + start(); + + // Wait for the thread to fully start up and construct the body. + while (m_body.load(std::memory_order_acquire) == nullptr){ + pause(); + } +} +AudioPassthroughPairQtThread::~AudioPassthroughPairQtThread(){ + m_body.store(nullptr, std::memory_order_relaxed); + quit(); + wait(); +} +void AudioPassthroughPairQtThread::run(){ + auto scope_check = m_sanitizer.check_scope(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + + AudioPassthroughPairQt body(m_logger); + m_body.store(&body, std::memory_order_relaxed); + exec(); + + // Wait until we are in the destructor before destroying the body. + while (m_body.load(std::memory_order_acquire) != nullptr){ + pause(); + } +} + + +void AudioPassthroughPairQtThread::reset( + const std::string& file, + const AudioDeviceInfo& output, double output_volume +){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->reset(file, output, output_volume); +} +void AudioPassthroughPairQtThread::reset( + const AudioDeviceInfo& input, AudioChannelFormat format, + const AudioDeviceInfo& output, double output_volume +){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->reset(input, format, output, output_volume); +} +void AudioPassthroughPairQtThread::clear_audio_source(){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->clear_audio_source(); +} +void AudioPassthroughPairQtThread::set_audio_source(const std::string& file){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->set_audio_source(file); +} +void AudioPassthroughPairQtThread::set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->set_audio_source(device, format); +} +void AudioPassthroughPairQtThread::clear_audio_sink(){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->clear_audio_sink(); +} +void AudioPassthroughPairQtThread::set_audio_sink(const AudioDeviceInfo& device, double volume){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->set_audio_sink(device, volume); +} +void AudioPassthroughPairQtThread::set_sink_volume(double volume){ + auto scope_check = m_sanitizer.check_scope(); + AudioPassthroughPairQt* body = m_body.load(std::memory_order_relaxed); + body->set_sink_volume(volume); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.h index 3a4d5bf8f3..7769aceea9 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Backends/AudioPassthroughPairQtThread.h @@ -1,66 +1,66 @@ -/* Audio Passthrough Pair (Qt separate thread) - * - * From: https://github.com/PokemonAutomation/ - * - * Same as AudioPassthroughPairQt, but with the audio running - * on a separate thread to avoid UI thread noise. - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioPassthroughPairQtThread_H -#define PokemonAutomation_AudioPipeline_AudioPassthroughPairQtThread_H - -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "CommonFramework/AudioPipeline/AudioPassthroughPair.h" - -namespace PokemonAutomation{ - -class Logger; -class AudioPassthroughPairQt; - - -class AudioPassthroughPairQtThread : private QThread, public AudioPassthroughPair{ -public: - virtual void add_listener(AudioFloatStreamListener& listener) override; - virtual void remove_listener(AudioFloatStreamListener& listener) override; - - virtual void add_listener(FFTListener& listener) override; - virtual void remove_listener(FFTListener& listener) override; - -public: - AudioPassthroughPairQtThread(Logger& logger); - ~AudioPassthroughPairQtThread(); - - virtual void reset( - const std::string& file, - const AudioDeviceInfo& output, double output_volume - ) override; - virtual void reset( - const AudioDeviceInfo& input, AudioChannelFormat format, - const AudioDeviceInfo& output, double output_volume - ) override; - - virtual void clear_audio_source() override; - virtual void set_audio_source(const std::string& file) override; - virtual void set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format) override; - - virtual void clear_audio_sink() override; - virtual void set_audio_sink(const AudioDeviceInfo& device, double volume) override; - - virtual void set_sink_volume(double volume) override; - -private: - virtual void run() override; - -private: - Logger& m_logger; - std::atomic m_body; - LifetimeSanitizer m_sanitizer; -}; - - - - -} -#endif +/* Audio Passthrough Pair (Qt separate thread) + * + * From: https://github.com/PokemonAutomation/ + * + * Same as AudioPassthroughPairQt, but with the audio running + * on a separate thread to avoid UI thread noise. + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioPassthroughPairQtThread_H +#define PokemonAutomation_AudioPipeline_AudioPassthroughPairQtThread_H + +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "CommonFramework/AudioPipeline/AudioPassthroughPair.h" + +namespace PokemonAutomation{ + +class Logger; +class AudioPassthroughPairQt; + + +class AudioPassthroughPairQtThread : private QThread, public AudioPassthroughPair{ +public: + virtual void add_listener(AudioFloatStreamListener& listener) override; + virtual void remove_listener(AudioFloatStreamListener& listener) override; + + virtual void add_listener(FFTListener& listener) override; + virtual void remove_listener(FFTListener& listener) override; + +public: + AudioPassthroughPairQtThread(Logger& logger); + ~AudioPassthroughPairQtThread(); + + virtual void reset( + const std::string& file, + const AudioDeviceInfo& output, double output_volume + ) override; + virtual void reset( + const AudioDeviceInfo& input, AudioChannelFormat format, + const AudioDeviceInfo& output, double output_volume + ) override; + + virtual void clear_audio_source() override; + virtual void set_audio_source(const std::string& file) override; + virtual void set_audio_source(const AudioDeviceInfo& device, AudioChannelFormat format) override; + + virtual void clear_audio_sink() override; + virtual void set_audio_sink(const AudioDeviceInfo& device, double volume) override; + + virtual void set_sink_volume(double volume) override; + +private: + virtual void run() override; + +private: + Logger& m_logger; + std::atomic m_body; + LifetimeSanitizer m_sanitizer; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.cpp index 586c88828c..0b98645ea6 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.cpp @@ -1,398 +1,398 @@ -/* Audio File Loader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "3rdParty/QtWavFile/WavFile.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" -#include "AudioFileLoader.h" - - - -// #define DEBUG_AUDIO_DECODER_WORKER - - -namespace PokemonAutomation{ - -AudioFileLoader::AudioFileLoader(QObject* parent, const std::string& filename, const QAudioFormat& audioFormat): - QObject(parent), m_filename(filename), m_audioFormat(audioFormat) {} - -AudioFileLoader::~AudioFileLoader(){ - if (m_audioDecoderWorker){ - m_audioDecoderWorker->stop(); - } - - m_audioDecoderThread.quit(); - m_audioDecoderThread.wait(); - - if (m_audioDecoderWorker){ - delete m_audioDecoderWorker; - m_audioDecoderWorker = nullptr; - } - - if (m_wavFile){ - m_wavFile->close(); - delete m_wavFile; - m_wavFile = nullptr; - } -} - -bool AudioFileLoader::start(){ - - m_frames_per_timeout = m_audioFormat.sampleRate() * m_timer_interval_ms / 1000; - - if (has_extension(m_filename, "wav")){ - // Use WavFile to load unencoded samples: - if (!initWavFile()){ - return false; - } - - const int wavSampleRate = m_wavFile->audioFormat().sampleRate(); - if (wavSampleRate != m_audioFormat.sampleRate()){ - std::cout << "Error: we don't interpolate wav file sample rate " << wavSampleRate << " to " << - m_audioFormat.sampleRate() << " during playback" << std::endl; - return false; - } - - - buildTimer(); - connect(m_timer, &QTimer::timeout, this, &AudioFileLoader::sendBufferFromWavFileOnTimer); - - return true; - } - - // Use QAudioDecoder to decode compressed audio file: - m_audioDecoderWorker = new AudioDecoderWorker(this, m_filename, m_audioFormat, m_rawBuffer); - - // When the decoder finishes decoding the entire file, launch a timer to send decoded audio - // frames to outside at desired frame rate. - // Note: here we save all the decoded raw samples to memory before sending them out. - // For a large audio file this is problematic, will consume lots of memory. But for small audio - // files this is OK. - connect(m_audioDecoderWorker, &AudioDecoderWorker::finished, this, [&](){ - std::cout << "Audio decoder finishes decoding. Start playing audio at desired sample rate" << std::endl; - buildTimer(); - connect(m_timer, &QTimer::timeout, this, &AudioFileLoader::sendDecodedBufferOnTimer); - }); - - m_audioDecoderWorker->start(); - - return m_audioDecoderWorker->startSucceeded(); -} - -void AudioFileLoader::buildTimer(){ - m_timer = new QTimer(this); - m_timer->setTimerType(Qt::PreciseTimer); - m_timer->start((int)m_timer_interval_ms); -} - -std::tuple AudioFileLoader::loadFullAudio(){ - if (has_extension(m_filename, "wav")){ - // Use WavFile to load unencoded samples: - if (!initWavFile()){ - return std::make_tuple(nullptr, 0); - } - - const size_t numBytes = m_wavFile->size() - m_wavFile->pos(); - m_rawBuffer.resize(numBytes); - const size_t bytesRead = m_wavFile->read(m_rawBuffer.data(), numBytes); - if (bytesRead != numBytes){ - std::cout << "Error: failed to read all bytes from wav file: " << bytesRead << " < " << numBytes << std::endl; - } - return convertRawWavSamples(); - } - - // Use QAudioDecoder to decode compressed audio file: - m_audioDecoderWorker = new AudioDecoderWorker(nullptr, m_filename, m_audioFormat, m_rawBuffer); - m_audioDecoderWorker->moveToThread(&m_audioDecoderThread); - - connect(this, &AudioFileLoader::runAudioDecoderAsync, m_audioDecoderWorker, &AudioDecoderWorker::start); - connect(&m_audioDecoderThread, &QThread::finished, m_audioDecoderWorker, &QObject::deleteLater); - - QEventLoop loop; - connect(m_audioDecoderWorker, &AudioDecoderWorker::errored, &loop, &QEventLoop::quit); - connect(m_audioDecoderWorker, &AudioDecoderWorker::finished, &loop, &QEventLoop::quit); - - // m_audioDecoderThread takes care of m_audioDecoderWorker via finished -> deleteLater connection. - // So we don't hold the pointer m_audioDecoderWorker anymore. - m_audioDecoderWorker = nullptr; - - m_audioDecoderThread.start(); - emit runAudioDecoderAsync(); - - // Block the current thread until the m_audioDecoderWorker errored or finished. - loop.exec(); - - m_audioDecoderThread.quit(); - m_audioDecoderThread.wait(); - return std::make_tuple(m_rawBuffer.data(), m_rawBuffer.size()); -} - -bool AudioFileLoader::initWavFile(){ - std::cout << "Initialize WavFile on " << m_filename << std::endl; - m_wavFile = new WavFile(this); - if (m_wavFile->open(QString::fromStdString(m_filename)) == false){ - std::cout << "Error: WavFile cannot open file " << m_filename << std::endl; - return false; - } - - std::cout << "Wav file audio format: " << dumpAudioFormat(m_wavFile->audioFormat()); - - if (m_audioFormat.sampleRate() != m_wavFile->audioFormat().sampleRate()){ - std::cout << "Error: WavFile sample rate " << m_wavFile->audioFormat().sampleRate() << - " does not match required " << m_audioFormat.sampleRate() << std::endl; - return false; - } - - return true; -} - - -void AudioFileLoader::sendDecodedBufferOnTimer(){ - const int bytesPerFrame = m_audioFormat.bytesPerFrame(); - const size_t bytesToSend = bytesPerFrame * m_frames_per_timeout; - - const auto& buffer = m_rawBuffer; - - const size_t m_bufferEnd = std::min(m_bufferNext + bytesToSend, buffer.size()); - -// const float* floatData = reinterpret_cast(buffer.data() + m_bufferNext); - // std::cout << "Timer: " << floatData[0] << " " << floatData[1] << "... " << buffer.size() << " " << m_bufferNext << std::endl; - - const size_t sentLen = m_bufferEnd - m_bufferNext; - emit bufferReady(buffer.data() + m_bufferNext, sentLen); - - m_bufferNext = m_bufferEnd; - - if (m_bufferEnd == buffer.size()){ - if (m_timer){ - m_timer->stop(); - } - emit finished(); - } -} - -void AudioFileLoader::sendBufferFromWavFileOnTimer(){ - const QAudioFormat& wavAudioFormat = m_wavFile->audioFormat(); - const int wavBytesPerFrame = wavAudioFormat.bytesPerFrame(); - const int wavBytesToRead = (int)(wavBytesPerFrame * m_frames_per_timeout); - m_rawBuffer.resize(wavBytesToRead); - const int64_t wavBytesRead = m_wavFile->read(m_rawBuffer.data(), wavBytesToRead); - m_rawBuffer.resize(wavBytesRead); - - if (wavBytesRead == 0){ - if (m_timer){ - m_timer->stop(); - } - emit finished(); - return; - } - - const auto bufferPtrLen = convertRawWavSamples(); - emit bufferReady(std::get<0>(bufferPtrLen), std::get<1>(bufferPtrLen)); -} - -std::pair AudioFileLoader::convertRawWavSamples(){ - const QAudioFormat& wavAudioFormat = m_wavFile->audioFormat(); - - const size_t wavBytesRead = m_rawBuffer.size(); - - // Simple case, the target audio format is the same as the format used in the wav file. - if (m_audioFormat == wavAudioFormat){ - return {m_rawBuffer.data(), wavBytesRead}; - } - - // Now we need to convert the audio samples to the target format: - - const size_t wavBytesPerFrame = wavAudioFormat.bytesPerFrame(); - const size_t wavNumChannels = wavAudioFormat.channelCount(); - const size_t wavBytesPerSample = wavBytesPerFrame / wavNumChannels; - const size_t framesRead = wavBytesRead / wavBytesPerFrame; - const size_t samplesRead = wavBytesRead / wavBytesPerSample; - - // m_floatBuffer holds the converted float-type samples - // TODO: design a general format conversion method - m_floatBuffer.resize(samplesRead); - convertSamplesToFloat(wavAudioFormat, m_rawBuffer.data(), wavBytesRead, m_floatBuffer.data()); - - if (m_audioFormat.channelCount() == wavAudioFormat.channelCount()){ - return { - reinterpret_cast(m_floatBuffer.data()), - m_floatBuffer.size() * sizeof(float) - }; - } - - if(m_audioFormat.channelCount() == 1){ - // Input wav file has stereo or more channels, but output format is mono, - // average L and R channel samples per frame: - for(size_t i = 0; i < framesRead; i++){ - m_floatBuffer[i] = (m_floatBuffer[2*i] + m_floatBuffer[2*i+1]) / 2.0f; - } - return {reinterpret_cast(m_floatBuffer.data()), framesRead * sizeof(float)}; - } - - if(wavAudioFormat.channelCount() == 1){ - // Input wav is mono but output format is stereo, - // Duplicate samples for each channel: - m_floatBuffer.resize(samplesRead * m_audioFormat.channelCount()); - for(size_t i = samplesRead; i-- > 0;){ - const float v = m_floatBuffer[i]; - for(int j = m_audioFormat.channelCount()-1; j >= 0; j--){ - m_floatBuffer[m_audioFormat.channelCount()*i+j] = v; - } - } - return { - reinterpret_cast(m_floatBuffer.data()), - framesRead * m_audioFormat.channelCount() * sizeof(float) - }; - } - - std::cout << "Error format conversion" << std::endl; - std::cout << "Wav file format: " << dumpAudioFormat(wavAudioFormat); - std::cout << "Audio format to convert to: " << dumpAudioFormat(m_audioFormat); - return {reinterpret_cast(m_floatBuffer.data()), 0}; -} - - -AudioDecoderWorker::AudioDecoderWorker( - QObject* parent, - const std::string& filename, - const QAudioFormat& audioFormat, - std::vector& decodedBuffer -): - QObject(parent), m_filename(filename), m_audioFormat(audioFormat), m_decodedBuffer(decodedBuffer){} - - -void AudioDecoderWorker::start(){ - m_audioDecoder = new QAudioDecoder(this); - -#if 0 - connect( - m_audioDecoder, &QAudioDecoder::bufferAvailableChanged, - this, [](bool available){ - std::cout << "QAudioDecoder::bufferAvailableChanged(): " << available << std::endl; - } - ); -#endif - -#if QT_VERSION_MAJOR == 5 - connect( - m_audioDecoder, &QAudioDecoder::stateChanged, - this, [this](QAudioDecoder::State state){ - std::cout << "QAudioDecoder::stateChanged(): " << (int)state << std::endl; - emit this->finished(); - } - ); -#endif - - // Whenever a new buffer of audo frames decoded, save them by calling readAudioDecoderBuffer(). - connect(m_audioDecoder, &QAudioDecoder::bufferReady, this, &AudioDecoderWorker::readAudioDecoderBuffer); - - // When the decoder finishes decoding the entire file, launch a timer to send decoded audio - // frames to outside at desired frame rate. - // Note: here we save all the decoded raw samples to memory before sending them out. - // For a large audio file this is problematic, will consume lots of memory. But for small audio - // files this is OK. - connect(m_audioDecoder, &QAudioDecoder::finished, this, &AudioDecoderWorker::finished); - - m_audioDecoder->setAudioFormat(m_audioFormat); - if (m_audioDecoder->error() != QAudioDecoder::NoError){ - handleAudioDecoderError(); - m_startSucceeded = false; - return; - } - - // Using Qt5, there may be errors about: - // defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.audiodecode" - // The QAudioDecoder object does not have a valid service - // For solution, see https://stackoverflow.com/questions/22783381/qaudiodecoder-no-service-found - connect(m_audioDecoder, QOverload::of(&QAudioDecoder::error), this, [&](QAudioDecoder::Error){ - handleAudioDecoderError(); - }); - - // m_audioDecoder->setSourceDevice(&m_file); -#if QT_VERSION_MAJOR == 5 - m_audioDecoder->setSourceFilename(QString::fromStdString(m_filename)); -#elif QT_VERSION_MAJOR == 6 - m_audioDecoder->setSource(QUrl::fromLocalFile(QString::fromStdString(m_filename))); -#endif - - m_audioDecoder->start(); - std::cout << "Start audio decoder." << std::endl; - - m_startSucceeded = true; - return; -} - -AudioDecoderWorker::~AudioDecoderWorker(){ - stop(); -} - -void AudioDecoderWorker::stop(){ - if (m_audioDecoder){ - m_audioDecoder->stop(); - } -} - -void AudioDecoderWorker::readAudioDecoderBuffer(){ - if (m_audioDecoder == nullptr){ - return; - } - - const QAudioBuffer& buffer = m_audioDecoder->read(); - size_t oldSize = m_decodedBuffer.size(); - m_decodedBuffer.resize(oldSize + buffer.byteCount()); - memcpy(m_decodedBuffer.data() + oldSize, buffer.data(), buffer.byteCount()); - -#ifdef DEBUG_AUDIO_DECODER_WORKER - std::cout << "Read QAudioBuffer (size " << buffer.byteCount() << ") from audio decoder, cur pos " << - m_audioDecoder->position() << " ms, total length " << m_audioDecoder->duration() << " ms, " << - "buffer length now " << m_decodedBuffer.size() << std::endl; -#endif -} - - -void AudioDecoderWorker::handleAudioDecoderError(){ - if (m_audioDecoder){ - QAudioDecoder::Error error = m_audioDecoder->error(); - std::string errorStr; - switch(error){ - case QAudioDecoder::ResourceError: - errorStr = "ResourceError"; - break; - case QAudioDecoder::AccessDeniedError: - errorStr = "AccessDeniedError"; - break; - case QAudioDecoder::FormatError: - errorStr = "FormatError"; - break; -#if QT_VERSION_MAJOR == 5 - case QAudioDecoder::ServiceMissingError: - errorStr = "ServiceMissingError"; - break; -#elif QT_VERSION_MAJOR == 6 - case QAudioDecoder::NotSupportedError: - errorStr = "NotSupportedError"; - break; -#endif - default: - errorStr = "UnownError"; - } - - std::cout << "QAudioDecoder error when loading file: " << m_filename << ", " << - errorStr << ": " << m_audioDecoder->errorString().toStdString() << std::endl; - - emit errored(); - } -} - -} +/* Audio File Loader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "3rdParty/QtWavFile/WavFile.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" +#include "AudioFileLoader.h" + + + +// #define DEBUG_AUDIO_DECODER_WORKER + + +namespace PokemonAutomation{ + +AudioFileLoader::AudioFileLoader(QObject* parent, const std::string& filename, const QAudioFormat& audioFormat): + QObject(parent), m_filename(filename), m_audioFormat(audioFormat) {} + +AudioFileLoader::~AudioFileLoader(){ + if (m_audioDecoderWorker){ + m_audioDecoderWorker->stop(); + } + + m_audioDecoderThread.quit(); + m_audioDecoderThread.wait(); + + if (m_audioDecoderWorker){ + delete m_audioDecoderWorker; + m_audioDecoderWorker = nullptr; + } + + if (m_wavFile){ + m_wavFile->close(); + delete m_wavFile; + m_wavFile = nullptr; + } +} + +bool AudioFileLoader::start(){ + + m_frames_per_timeout = m_audioFormat.sampleRate() * m_timer_interval_ms / 1000; + + if (has_extension(m_filename, "wav")){ + // Use WavFile to load unencoded samples: + if (!initWavFile()){ + return false; + } + + const int wavSampleRate = m_wavFile->audioFormat().sampleRate(); + if (wavSampleRate != m_audioFormat.sampleRate()){ + std::cout << "Error: we don't interpolate wav file sample rate " << wavSampleRate << " to " << + m_audioFormat.sampleRate() << " during playback" << std::endl; + return false; + } + + + buildTimer(); + connect(m_timer, &QTimer::timeout, this, &AudioFileLoader::sendBufferFromWavFileOnTimer); + + return true; + } + + // Use QAudioDecoder to decode compressed audio file: + m_audioDecoderWorker = new AudioDecoderWorker(this, m_filename, m_audioFormat, m_rawBuffer); + + // When the decoder finishes decoding the entire file, launch a timer to send decoded audio + // frames to outside at desired frame rate. + // Note: here we save all the decoded raw samples to memory before sending them out. + // For a large audio file this is problematic, will consume lots of memory. But for small audio + // files this is OK. + connect(m_audioDecoderWorker, &AudioDecoderWorker::finished, this, [&](){ + std::cout << "Audio decoder finishes decoding. Start playing audio at desired sample rate" << std::endl; + buildTimer(); + connect(m_timer, &QTimer::timeout, this, &AudioFileLoader::sendDecodedBufferOnTimer); + }); + + m_audioDecoderWorker->start(); + + return m_audioDecoderWorker->startSucceeded(); +} + +void AudioFileLoader::buildTimer(){ + m_timer = new QTimer(this); + m_timer->setTimerType(Qt::PreciseTimer); + m_timer->start((int)m_timer_interval_ms); +} + +std::tuple AudioFileLoader::loadFullAudio(){ + if (has_extension(m_filename, "wav")){ + // Use WavFile to load unencoded samples: + if (!initWavFile()){ + return std::make_tuple(nullptr, 0); + } + + const size_t numBytes = m_wavFile->size() - m_wavFile->pos(); + m_rawBuffer.resize(numBytes); + const size_t bytesRead = m_wavFile->read(m_rawBuffer.data(), numBytes); + if (bytesRead != numBytes){ + std::cout << "Error: failed to read all bytes from wav file: " << bytesRead << " < " << numBytes << std::endl; + } + return convertRawWavSamples(); + } + + // Use QAudioDecoder to decode compressed audio file: + m_audioDecoderWorker = new AudioDecoderWorker(nullptr, m_filename, m_audioFormat, m_rawBuffer); + m_audioDecoderWorker->moveToThread(&m_audioDecoderThread); + + connect(this, &AudioFileLoader::runAudioDecoderAsync, m_audioDecoderWorker, &AudioDecoderWorker::start); + connect(&m_audioDecoderThread, &QThread::finished, m_audioDecoderWorker, &QObject::deleteLater); + + QEventLoop loop; + connect(m_audioDecoderWorker, &AudioDecoderWorker::errored, &loop, &QEventLoop::quit); + connect(m_audioDecoderWorker, &AudioDecoderWorker::finished, &loop, &QEventLoop::quit); + + // m_audioDecoderThread takes care of m_audioDecoderWorker via finished -> deleteLater connection. + // So we don't hold the pointer m_audioDecoderWorker anymore. + m_audioDecoderWorker = nullptr; + + m_audioDecoderThread.start(); + emit runAudioDecoderAsync(); + + // Block the current thread until the m_audioDecoderWorker errored or finished. + loop.exec(); + + m_audioDecoderThread.quit(); + m_audioDecoderThread.wait(); + return std::make_tuple(m_rawBuffer.data(), m_rawBuffer.size()); +} + +bool AudioFileLoader::initWavFile(){ + std::cout << "Initialize WavFile on " << m_filename << std::endl; + m_wavFile = new WavFile(this); + if (m_wavFile->open(QString::fromStdString(m_filename)) == false){ + std::cout << "Error: WavFile cannot open file " << m_filename << std::endl; + return false; + } + + std::cout << "Wav file audio format: " << dumpAudioFormat(m_wavFile->audioFormat()); + + if (m_audioFormat.sampleRate() != m_wavFile->audioFormat().sampleRate()){ + std::cout << "Error: WavFile sample rate " << m_wavFile->audioFormat().sampleRate() << + " does not match required " << m_audioFormat.sampleRate() << std::endl; + return false; + } + + return true; +} + + +void AudioFileLoader::sendDecodedBufferOnTimer(){ + const int bytesPerFrame = m_audioFormat.bytesPerFrame(); + const size_t bytesToSend = bytesPerFrame * m_frames_per_timeout; + + const auto& buffer = m_rawBuffer; + + const size_t m_bufferEnd = std::min(m_bufferNext + bytesToSend, buffer.size()); + +// const float* floatData = reinterpret_cast(buffer.data() + m_bufferNext); + // std::cout << "Timer: " << floatData[0] << " " << floatData[1] << "... " << buffer.size() << " " << m_bufferNext << std::endl; + + const size_t sentLen = m_bufferEnd - m_bufferNext; + emit bufferReady(buffer.data() + m_bufferNext, sentLen); + + m_bufferNext = m_bufferEnd; + + if (m_bufferEnd == buffer.size()){ + if (m_timer){ + m_timer->stop(); + } + emit finished(); + } +} + +void AudioFileLoader::sendBufferFromWavFileOnTimer(){ + const QAudioFormat& wavAudioFormat = m_wavFile->audioFormat(); + const int wavBytesPerFrame = wavAudioFormat.bytesPerFrame(); + const int wavBytesToRead = (int)(wavBytesPerFrame * m_frames_per_timeout); + m_rawBuffer.resize(wavBytesToRead); + const int64_t wavBytesRead = m_wavFile->read(m_rawBuffer.data(), wavBytesToRead); + m_rawBuffer.resize(wavBytesRead); + + if (wavBytesRead == 0){ + if (m_timer){ + m_timer->stop(); + } + emit finished(); + return; + } + + const auto bufferPtrLen = convertRawWavSamples(); + emit bufferReady(std::get<0>(bufferPtrLen), std::get<1>(bufferPtrLen)); +} + +std::pair AudioFileLoader::convertRawWavSamples(){ + const QAudioFormat& wavAudioFormat = m_wavFile->audioFormat(); + + const size_t wavBytesRead = m_rawBuffer.size(); + + // Simple case, the target audio format is the same as the format used in the wav file. + if (m_audioFormat == wavAudioFormat){ + return {m_rawBuffer.data(), wavBytesRead}; + } + + // Now we need to convert the audio samples to the target format: + + const size_t wavBytesPerFrame = wavAudioFormat.bytesPerFrame(); + const size_t wavNumChannels = wavAudioFormat.channelCount(); + const size_t wavBytesPerSample = wavBytesPerFrame / wavNumChannels; + const size_t framesRead = wavBytesRead / wavBytesPerFrame; + const size_t samplesRead = wavBytesRead / wavBytesPerSample; + + // m_floatBuffer holds the converted float-type samples + // TODO: design a general format conversion method + m_floatBuffer.resize(samplesRead); + convertSamplesToFloat(wavAudioFormat, m_rawBuffer.data(), wavBytesRead, m_floatBuffer.data()); + + if (m_audioFormat.channelCount() == wavAudioFormat.channelCount()){ + return { + reinterpret_cast(m_floatBuffer.data()), + m_floatBuffer.size() * sizeof(float) + }; + } + + if(m_audioFormat.channelCount() == 1){ + // Input wav file has stereo or more channels, but output format is mono, + // average L and R channel samples per frame: + for(size_t i = 0; i < framesRead; i++){ + m_floatBuffer[i] = (m_floatBuffer[2*i] + m_floatBuffer[2*i+1]) / 2.0f; + } + return {reinterpret_cast(m_floatBuffer.data()), framesRead * sizeof(float)}; + } + + if(wavAudioFormat.channelCount() == 1){ + // Input wav is mono but output format is stereo, + // Duplicate samples for each channel: + m_floatBuffer.resize(samplesRead * m_audioFormat.channelCount()); + for(size_t i = samplesRead; i-- > 0;){ + const float v = m_floatBuffer[i]; + for(int j = m_audioFormat.channelCount()-1; j >= 0; j--){ + m_floatBuffer[m_audioFormat.channelCount()*i+j] = v; + } + } + return { + reinterpret_cast(m_floatBuffer.data()), + framesRead * m_audioFormat.channelCount() * sizeof(float) + }; + } + + std::cout << "Error format conversion" << std::endl; + std::cout << "Wav file format: " << dumpAudioFormat(wavAudioFormat); + std::cout << "Audio format to convert to: " << dumpAudioFormat(m_audioFormat); + return {reinterpret_cast(m_floatBuffer.data()), 0}; +} + + +AudioDecoderWorker::AudioDecoderWorker( + QObject* parent, + const std::string& filename, + const QAudioFormat& audioFormat, + std::vector& decodedBuffer +): + QObject(parent), m_filename(filename), m_audioFormat(audioFormat), m_decodedBuffer(decodedBuffer){} + + +void AudioDecoderWorker::start(){ + m_audioDecoder = new QAudioDecoder(this); + +#if 0 + connect( + m_audioDecoder, &QAudioDecoder::bufferAvailableChanged, + this, [](bool available){ + std::cout << "QAudioDecoder::bufferAvailableChanged(): " << available << std::endl; + } + ); +#endif + +#if QT_VERSION_MAJOR == 5 + connect( + m_audioDecoder, &QAudioDecoder::stateChanged, + this, [this](QAudioDecoder::State state){ + std::cout << "QAudioDecoder::stateChanged(): " << (int)state << std::endl; + emit this->finished(); + } + ); +#endif + + // Whenever a new buffer of audo frames decoded, save them by calling readAudioDecoderBuffer(). + connect(m_audioDecoder, &QAudioDecoder::bufferReady, this, &AudioDecoderWorker::readAudioDecoderBuffer); + + // When the decoder finishes decoding the entire file, launch a timer to send decoded audio + // frames to outside at desired frame rate. + // Note: here we save all the decoded raw samples to memory before sending them out. + // For a large audio file this is problematic, will consume lots of memory. But for small audio + // files this is OK. + connect(m_audioDecoder, &QAudioDecoder::finished, this, &AudioDecoderWorker::finished); + + m_audioDecoder->setAudioFormat(m_audioFormat); + if (m_audioDecoder->error() != QAudioDecoder::NoError){ + handleAudioDecoderError(); + m_startSucceeded = false; + return; + } + + // Using Qt5, there may be errors about: + // defaultServiceProvider::requestService(): no service found for - "org.qt-project.qt.audiodecode" + // The QAudioDecoder object does not have a valid service + // For solution, see https://stackoverflow.com/questions/22783381/qaudiodecoder-no-service-found + connect(m_audioDecoder, QOverload::of(&QAudioDecoder::error), this, [&](QAudioDecoder::Error){ + handleAudioDecoderError(); + }); + + // m_audioDecoder->setSourceDevice(&m_file); +#if QT_VERSION_MAJOR == 5 + m_audioDecoder->setSourceFilename(QString::fromStdString(m_filename)); +#elif QT_VERSION_MAJOR == 6 + m_audioDecoder->setSource(QUrl::fromLocalFile(QString::fromStdString(m_filename))); +#endif + + m_audioDecoder->start(); + std::cout << "Start audio decoder." << std::endl; + + m_startSucceeded = true; + return; +} + +AudioDecoderWorker::~AudioDecoderWorker(){ + stop(); +} + +void AudioDecoderWorker::stop(){ + if (m_audioDecoder){ + m_audioDecoder->stop(); + } +} + +void AudioDecoderWorker::readAudioDecoderBuffer(){ + if (m_audioDecoder == nullptr){ + return; + } + + const QAudioBuffer& buffer = m_audioDecoder->read(); + size_t oldSize = m_decodedBuffer.size(); + m_decodedBuffer.resize(oldSize + buffer.byteCount()); + memcpy(m_decodedBuffer.data() + oldSize, buffer.data(), buffer.byteCount()); + +#ifdef DEBUG_AUDIO_DECODER_WORKER + std::cout << "Read QAudioBuffer (size " << buffer.byteCount() << ") from audio decoder, cur pos " << + m_audioDecoder->position() << " ms, total length " << m_audioDecoder->duration() << " ms, " << + "buffer length now " << m_decodedBuffer.size() << std::endl; +#endif +} + + +void AudioDecoderWorker::handleAudioDecoderError(){ + if (m_audioDecoder){ + QAudioDecoder::Error error = m_audioDecoder->error(); + std::string errorStr; + switch(error){ + case QAudioDecoder::ResourceError: + errorStr = "ResourceError"; + break; + case QAudioDecoder::AccessDeniedError: + errorStr = "AccessDeniedError"; + break; + case QAudioDecoder::FormatError: + errorStr = "FormatError"; + break; +#if QT_VERSION_MAJOR == 5 + case QAudioDecoder::ServiceMissingError: + errorStr = "ServiceMissingError"; + break; +#elif QT_VERSION_MAJOR == 6 + case QAudioDecoder::NotSupportedError: + errorStr = "NotSupportedError"; + break; +#endif + default: + errorStr = "UnownError"; + } + + std::cout << "QAudioDecoder error when loading file: " << m_filename << ", " << + errorStr << ": " << m_audioDecoder->errorString().toStdString() << std::endl; + + emit errored(); + } +} + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.h index 89cffce4cf..077191b105 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioFileLoader.h @@ -1,170 +1,170 @@ -/* Audio File Loader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioFileLoader_H -#define PokemonAutomation_AudioPipeline_AudioFileLoader_H - -#include -#include -#include -#include -#include -#include - -class QAudioBuffer; -class QAudioDecoder; -class QTimer; -class WavFile; - - -namespace PokemonAutomation{ - - -class AudioDecoderWorker; - -// Load .wav and .mp3 audio from disk and optionally play at desired sample rate. - -// Note: for ease of implementation this class saves all the decoded raw samples to -// memory before sending them out when `start()` is called. For a large audio file this -// is problematic as it will consume lots of memory. But the purpose of this functionality -// is to load recorded audio for testing and developing audio inference programs. -// So the input audio files should be small. -// You can also call `loadFullAudio()` to load the audio directly into memory. -// The loader tries to convert the audio data into the format specified as `audioFormat` -// in the constructor. For .mp3 files this conversion is done by QtAudioDecoder, while -// for .wav files the converion is done in `AudioFileLoader`. -// Currently we hard code the code to only return float data because that's the rest of -// the audio pipeline uses. -// For .wav file the format conversion is not fully implement: we cannot convert sampling -// rate during playback (after 'start()' called), but support it in `loadFullAudio()`. -class AudioFileLoader: public QObject{ - Q_OBJECT - -public: - AudioFileLoader(QObject* parent, const std::string& filename, const QAudioFormat& audioFormat); - virtual ~AudioFileLoader(); - - // Start loading and decoding audio samples. - // Send the sample buffers at the desired speed determined by sample rate in `audioFormat` passed - // to the constructor. - // Retrieve sample buffer by connecting to signal `bufferReady` from the same thread. - // See comments of the class full more details. - bool start(); - - // Load and decode full audio from file. Return the internal buffer (pointer and size) holding - // the decoded audio data. If loading fails, the returned pointer is nullptr. - // Note: this is a blocking operation. - // See comments of the class full more details. - std::tuple loadFullAudio(); - - const QAudioFormat& audioFormat() const { return m_audioFormat; } - -signals: - // Send audio sample buffer at time interval `m_timer_interval_ms` after `start()` called - // Pass raw pointer. So must be connected to objects in the same thread! - void bufferReady(const char* data, size_t len); - - // When finished sending decoded audio frames after `start()` called - void finished(); - - // Used privately to launch audio decoder woker in a separate thread. - void runAudioDecoderAsync(); - -private: - void buildTimer(); - - bool initWavFile(); - - // Send audio samples decoded from m_audioDecoder on m_timer. - void sendDecodedBufferOnTimer(); - - // Convert raw samples read from m_wavFile (stored in m_rawBuffer) into - // float type and return the pointer and length of the converted data. - std::pair convertRawWavSamples(); - - // Send audio samples read fomr m_wavFile on m_timer. - void sendBufferFromWavFileOnTimer(); - -private: - std::string m_filename; - - QAudioFormat m_audioFormat; - - AudioDecoderWorker* m_audioDecoderWorker = nullptr; - QThread m_audioDecoderThread; - - WavFile* m_wavFile = nullptr; - - // Buffer to store raw audio data from m_wavFile or output from m_audioDecoderWorker - std::vector m_rawBuffer; - - // Since m_wavFile only reads raw audio file, we need to do sample type conversion ourselves. - // Therefore we need a buffer to store converted audio samples. - std::vector m_floatBuffer; - - // When reading m_rawBuffer, which index to start reading. - size_t m_bufferNext = 0; - - // To playback the decoded audio frames at sample rate, we need a timer. - QTimer* m_timer = nullptr; - - // The time interval (in milliseconds) that the timer will send a signal. - size_t m_timer_interval_ms = 10; - - // The timer sends a signal, how many audio frames we need to prepare to - // send to outside. - // m_frames_per_timeout = * m_timer_interval_ms / 1000 - size_t m_frames_per_timeout = 0; -}; - - - -// Used to run QAudioDecoder and collect decoded results -class AudioDecoderWorker: public QObject{ -Q_OBJECT - -public: - AudioDecoderWorker(QObject* parent, const std::string& filename, const QAudioFormat& audioFormat, std::vector& decodedBuffer); - virtual ~AudioDecoderWorker(); - - void start(); - - bool startSucceeded() { return m_startSucceeded; } - - void stop(); - -signals: - void errored(); - - void finished(); - -public slots: - // Read decoded buffer sent from m_audioDecoder and store it into m_decodedBuffer. - void readAudioDecoderBuffer(); - -private: - // Handle error from m_audioDecoder. - void handleAudioDecoderError(); - -private: - - std::string m_filename; - QAudioFormat m_audioFormat; - - QAudioDecoder* m_audioDecoder = nullptr; - - std::vector& m_decodedBuffer; - - bool m_startSucceeded = true; -}; - - - - - -} - -#endif +/* Audio File Loader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioFileLoader_H +#define PokemonAutomation_AudioPipeline_AudioFileLoader_H + +#include +#include +#include +#include +#include +#include + +class QAudioBuffer; +class QAudioDecoder; +class QTimer; +class WavFile; + + +namespace PokemonAutomation{ + + +class AudioDecoderWorker; + +// Load .wav and .mp3 audio from disk and optionally play at desired sample rate. + +// Note: for ease of implementation this class saves all the decoded raw samples to +// memory before sending them out when `start()` is called. For a large audio file this +// is problematic as it will consume lots of memory. But the purpose of this functionality +// is to load recorded audio for testing and developing audio inference programs. +// So the input audio files should be small. +// You can also call `loadFullAudio()` to load the audio directly into memory. +// The loader tries to convert the audio data into the format specified as `audioFormat` +// in the constructor. For .mp3 files this conversion is done by QtAudioDecoder, while +// for .wav files the converion is done in `AudioFileLoader`. +// Currently we hard code the code to only return float data because that's the rest of +// the audio pipeline uses. +// For .wav file the format conversion is not fully implement: we cannot convert sampling +// rate during playback (after 'start()' called), but support it in `loadFullAudio()`. +class AudioFileLoader: public QObject{ + Q_OBJECT + +public: + AudioFileLoader(QObject* parent, const std::string& filename, const QAudioFormat& audioFormat); + virtual ~AudioFileLoader(); + + // Start loading and decoding audio samples. + // Send the sample buffers at the desired speed determined by sample rate in `audioFormat` passed + // to the constructor. + // Retrieve sample buffer by connecting to signal `bufferReady` from the same thread. + // See comments of the class full more details. + bool start(); + + // Load and decode full audio from file. Return the internal buffer (pointer and size) holding + // the decoded audio data. If loading fails, the returned pointer is nullptr. + // Note: this is a blocking operation. + // See comments of the class full more details. + std::tuple loadFullAudio(); + + const QAudioFormat& audioFormat() const { return m_audioFormat; } + +signals: + // Send audio sample buffer at time interval `m_timer_interval_ms` after `start()` called + // Pass raw pointer. So must be connected to objects in the same thread! + void bufferReady(const char* data, size_t len); + + // When finished sending decoded audio frames after `start()` called + void finished(); + + // Used privately to launch audio decoder woker in a separate thread. + void runAudioDecoderAsync(); + +private: + void buildTimer(); + + bool initWavFile(); + + // Send audio samples decoded from m_audioDecoder on m_timer. + void sendDecodedBufferOnTimer(); + + // Convert raw samples read from m_wavFile (stored in m_rawBuffer) into + // float type and return the pointer and length of the converted data. + std::pair convertRawWavSamples(); + + // Send audio samples read fomr m_wavFile on m_timer. + void sendBufferFromWavFileOnTimer(); + +private: + std::string m_filename; + + QAudioFormat m_audioFormat; + + AudioDecoderWorker* m_audioDecoderWorker = nullptr; + QThread m_audioDecoderThread; + + WavFile* m_wavFile = nullptr; + + // Buffer to store raw audio data from m_wavFile or output from m_audioDecoderWorker + std::vector m_rawBuffer; + + // Since m_wavFile only reads raw audio file, we need to do sample type conversion ourselves. + // Therefore we need a buffer to store converted audio samples. + std::vector m_floatBuffer; + + // When reading m_rawBuffer, which index to start reading. + size_t m_bufferNext = 0; + + // To playback the decoded audio frames at sample rate, we need a timer. + QTimer* m_timer = nullptr; + + // The time interval (in milliseconds) that the timer will send a signal. + size_t m_timer_interval_ms = 10; + + // The timer sends a signal, how many audio frames we need to prepare to + // send to outside. + // m_frames_per_timeout = * m_timer_interval_ms / 1000 + size_t m_frames_per_timeout = 0; +}; + + + +// Used to run QAudioDecoder and collect decoded results +class AudioDecoderWorker: public QObject{ +Q_OBJECT + +public: + AudioDecoderWorker(QObject* parent, const std::string& filename, const QAudioFormat& audioFormat, std::vector& decodedBuffer); + virtual ~AudioDecoderWorker(); + + void start(); + + bool startSucceeded() { return m_startSucceeded; } + + void stop(); + +signals: + void errored(); + + void finished(); + +public slots: + // Read decoded buffer sent from m_audioDecoder and store it into m_decodedBuffer. + void readAudioDecoderBuffer(); + +private: + // Handle error from m_audioDecoder. + void handleAudioDecoderError(); + +private: + + std::string m_filename; + QAudioFormat m_audioFormat; + + QAudioDecoder* m_audioDecoder = nullptr; + + std::vector& m_decodedBuffer; + + bool m_startSucceeded = true; +}; + + + + + +} + +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.cpp index 4ec38998cf..3284beec2c 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.cpp @@ -1,178 +1,178 @@ -/* Audio Output Writer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if QT_VERSION_MAJOR == 5 -#include -using NativeAudioSink = QAudioOutput; -#elif QT_VERSION_MAJOR == 6 -#include -using NativeAudioSink = QAudioSink; -#endif - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" -#include "AudioSink.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -// Slider bar volume: [0, 100], in log scale -// Volume value passed to AudioDisplayWidget (and the audio thread it manages): [0.f, 1.f], linear scale -float convertAudioVolumeFromSlider(double volume){ - volume = std::max(volume, 0.0); - volume = std::min(volume, 1.0); - // The slider bar value is in the log scale because log scale matches human sound - // perception. - float linearVolume = QAudio::convertVolume( - (float)volume, - QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale - ); - return linearVolume; -} - - - - -class AudioOutputDevice : public AudioFloatToStream, private StreamListener{ -public: - AudioOutputDevice( - Logger& logger, - const NativeAudioInfo& device, const QAudioFormat& format, - AudioSampleFormat sample_format, size_t samples_per_frame, - double volume - ) - : AudioFloatToStream(sample_format, samples_per_frame) - , StreamListener(samples_per_frame * sample_size(sample_format)) - , m_logger(logger) - , m_sink(device, format) - { - m_sink.connect( - &m_sink, &NativeAudioSink::stateChanged, - &m_sink, [this](QAudio::State state){ - if (state == QAudio::State::StoppedState){ - m_io_device = nullptr; - m_logger.log("AudioOutputDevice has stopped.", COLOR_ORANGE); - } - } - ); - - m_io_device = m_sink.start(); - m_sink.setVolume(convertAudioVolumeFromSlider(volume)); - add_listener(*this); - } - ~AudioOutputDevice(){ - remove_listener(*this); - } - - void set_volume(double volume){ - auto scope_check = m_sanitizer.check_scope(); - double absolute = convertAudioVolumeFromSlider(volume); - m_logger.log("Volume set to: Slider = " + tostr_default(volume) + " -> Absolute = " + tostr_default(absolute)); - m_sink.setVolume(absolute); - } - - virtual void on_objects(const void* data, size_t objects) override{ - auto scope_check = m_sanitizer.check_scope(); - if (m_io_device != nullptr){ - m_io_device->write((const char*)data, objects * object_size); - } - } - -private: - Logger& m_logger; - NativeAudioSink m_sink; - QIODevice* m_io_device; - LifetimeSanitizer m_sanitizer; -}; - - -AudioSink::~AudioSink(){} - -AudioSink::AudioSink(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, double volume){ - NativeAudioInfo native_info = device.native_info(); - QAudioFormat native_format = native_info.preferredFormat(); - QAudioFormat target_format = native_format; - - set_format(target_format, format); - - AudioSampleFormat sample_format = get_sample_format(target_format); - if (sample_format == AudioSampleFormat::INVALID){ - sample_format = AudioSampleFormat::FLOAT32; - setSampleFormatToFloat(target_format); - } - - logger.log("AudioOutputDevice(): Target: " + dumpAudioFormat(target_format)); - logger.log("AudioOutputDevice(): Native: " + dumpAudioFormat(native_format)); - if (!native_info.isFormatSupported(native_format) && - native_format != target_format - ){ - logger.log("Audio output device does not support the requested audio format.", COLOR_RED); - return; - } - - switch (format){ - case AudioChannelFormat::MONO_48000: - m_sample_rate = 48000; - m_channels = 1; - m_multiplier = 1; - break; - case AudioChannelFormat::DUAL_44100: - m_sample_rate = 44100; - m_channels = 2; - m_multiplier = 1; - break; - case AudioChannelFormat::DUAL_48000: - m_sample_rate = 48000; - m_channels = 2; - m_multiplier = 1; - break; - case AudioChannelFormat::MONO_96000: - // Treat mono-96000 as 2-sample frames. - // The FFT will then average each pair to produce 48000Hz. - // The output will push the same stream at the original 4 bytes * 96000Hz. - m_sample_rate = 96000; - m_channels = 1; - m_multiplier = 2; - break; - case AudioChannelFormat::INTERLEAVE_LR_96000: - case AudioChannelFormat::INTERLEAVE_RL_96000: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Interleaved format not allowed for audio output."); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); - } - - m_writer = std::make_unique( - logger, - native_info, target_format, - sample_format, m_channels * m_multiplier, - volume - ); -} - -AudioFloatStreamListener* AudioSink::float_stream_listener(){ - auto scope_check = m_sanitizer.check_scope(); - return m_writer.get(); -} -void AudioSink::set_volume(double volume){ - auto scope_check = m_sanitizer.check_scope(); - if (!m_writer){ - return; - } - m_writer->set_volume(volume); -} - - - - -} +/* Audio Output Writer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if QT_VERSION_MAJOR == 5 +#include +using NativeAudioSink = QAudioOutput; +#elif QT_VERSION_MAJOR == 6 +#include +using NativeAudioSink = QAudioSink; +#endif + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" +#include "AudioSink.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +// Slider bar volume: [0, 100], in log scale +// Volume value passed to AudioDisplayWidget (and the audio thread it manages): [0.f, 1.f], linear scale +float convertAudioVolumeFromSlider(double volume){ + volume = std::max(volume, 0.0); + volume = std::min(volume, 1.0); + // The slider bar value is in the log scale because log scale matches human sound + // perception. + float linearVolume = QAudio::convertVolume( + (float)volume, + QAudio::LogarithmicVolumeScale, QAudio::LinearVolumeScale + ); + return linearVolume; +} + + + + +class AudioOutputDevice : public AudioFloatToStream, private StreamListener{ +public: + AudioOutputDevice( + Logger& logger, + const NativeAudioInfo& device, const QAudioFormat& format, + AudioSampleFormat sample_format, size_t samples_per_frame, + double volume + ) + : AudioFloatToStream(sample_format, samples_per_frame) + , StreamListener(samples_per_frame * sample_size(sample_format)) + , m_logger(logger) + , m_sink(device, format) + { + m_sink.connect( + &m_sink, &NativeAudioSink::stateChanged, + &m_sink, [this](QAudio::State state){ + if (state == QAudio::State::StoppedState){ + m_io_device = nullptr; + m_logger.log("AudioOutputDevice has stopped.", COLOR_ORANGE); + } + } + ); + + m_io_device = m_sink.start(); + m_sink.setVolume(convertAudioVolumeFromSlider(volume)); + add_listener(*this); + } + ~AudioOutputDevice(){ + remove_listener(*this); + } + + void set_volume(double volume){ + auto scope_check = m_sanitizer.check_scope(); + double absolute = convertAudioVolumeFromSlider(volume); + m_logger.log("Volume set to: Slider = " + tostr_default(volume) + " -> Absolute = " + tostr_default(absolute)); + m_sink.setVolume(absolute); + } + + virtual void on_objects(const void* data, size_t objects) override{ + auto scope_check = m_sanitizer.check_scope(); + if (m_io_device != nullptr){ + m_io_device->write((const char*)data, objects * object_size); + } + } + +private: + Logger& m_logger; + NativeAudioSink m_sink; + QIODevice* m_io_device; + LifetimeSanitizer m_sanitizer; +}; + + +AudioSink::~AudioSink(){} + +AudioSink::AudioSink(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, double volume){ + NativeAudioInfo native_info = device.native_info(); + QAudioFormat native_format = native_info.preferredFormat(); + QAudioFormat target_format = native_format; + + set_format(target_format, format); + + AudioSampleFormat sample_format = get_sample_format(target_format); + if (sample_format == AudioSampleFormat::INVALID){ + sample_format = AudioSampleFormat::FLOAT32; + setSampleFormatToFloat(target_format); + } + + logger.log("AudioOutputDevice(): Target: " + dumpAudioFormat(target_format)); + logger.log("AudioOutputDevice(): Native: " + dumpAudioFormat(native_format)); + if (!native_info.isFormatSupported(native_format) && + native_format != target_format + ){ + logger.log("Audio output device does not support the requested audio format.", COLOR_RED); + return; + } + + switch (format){ + case AudioChannelFormat::MONO_48000: + m_sample_rate = 48000; + m_channels = 1; + m_multiplier = 1; + break; + case AudioChannelFormat::DUAL_44100: + m_sample_rate = 44100; + m_channels = 2; + m_multiplier = 1; + break; + case AudioChannelFormat::DUAL_48000: + m_sample_rate = 48000; + m_channels = 2; + m_multiplier = 1; + break; + case AudioChannelFormat::MONO_96000: + // Treat mono-96000 as 2-sample frames. + // The FFT will then average each pair to produce 48000Hz. + // The output will push the same stream at the original 4 bytes * 96000Hz. + m_sample_rate = 96000; + m_channels = 1; + m_multiplier = 2; + break; + case AudioChannelFormat::INTERLEAVE_LR_96000: + case AudioChannelFormat::INTERLEAVE_RL_96000: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Interleaved format not allowed for audio output."); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); + } + + m_writer = std::make_unique( + logger, + native_info, target_format, + sample_format, m_channels * m_multiplier, + volume + ); +} + +AudioFloatStreamListener* AudioSink::float_stream_listener(){ + auto scope_check = m_sanitizer.check_scope(); + return m_writer.get(); +} +void AudioSink::set_volume(double volume){ + auto scope_check = m_sanitizer.check_scope(); + if (!m_writer){ + return; + } + m_writer->set_volume(volume); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.h index 59293903e2..b373409a86 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSink.h @@ -1,52 +1,52 @@ -/* Audio Sink - * - * From: https://github.com/PokemonAutomation/ - * - * AudioSink represents an audio output stream. Once constructed, - * you can push float audio samples to it and it will play it from the - * respective speaker or whatever. - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioSink_H -#define PokemonAutomation_AudioPipeline_AudioSink_H - -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "CommonFramework/AudioPipeline/AudioInfo.h" -#include "CommonFramework/AudioPipeline/AudioStream.h" - -namespace PokemonAutomation{ - -class Logger; -class AudioOutputDevice; - - -class AudioSink{ -public: - ~AudioSink(); - AudioSink(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, double volume); - - size_t sample_rate() const{ return m_sample_rate; } - size_t channels() const{ return m_channels; } - size_t samples_per_frame() const{ return m_channels * m_multiplier; } - - AudioFloatStreamListener* float_stream_listener(); - - void set_volume(double volume); - - -private: - size_t m_sample_rate; - size_t m_channels; - size_t m_multiplier; - - std::unique_ptr m_writer; - - LifetimeSanitizer m_sanitizer; -}; - - - -} -#endif +/* Audio Sink + * + * From: https://github.com/PokemonAutomation/ + * + * AudioSink represents an audio output stream. Once constructed, + * you can push float audio samples to it and it will play it from the + * respective speaker or whatever. + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioSink_H +#define PokemonAutomation_AudioPipeline_AudioSink_H + +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "CommonFramework/AudioPipeline/AudioInfo.h" +#include "CommonFramework/AudioPipeline/AudioStream.h" + +namespace PokemonAutomation{ + +class Logger; +class AudioOutputDevice; + + +class AudioSink{ +public: + ~AudioSink(); + AudioSink(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, double volume); + + size_t sample_rate() const{ return m_sample_rate; } + size_t channels() const{ return m_channels; } + size_t samples_per_frame() const{ return m_channels * m_multiplier; } + + AudioFloatStreamListener* float_stream_listener(); + + void set_volume(double volume); + + +private: + size_t m_sample_rate; + size_t m_channels; + size_t m_multiplier; + + std::unique_ptr m_writer; + + LifetimeSanitizer m_sanitizer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.cpp index d3d73fd088..d4b447f8d7 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.cpp @@ -1,216 +1,216 @@ -/* Audio Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if QT_VERSION_MAJOR == 5 -#include -using NativeAudioSource = QAudioInput; -#elif QT_VERSION_MAJOR == 6 -#include -using NativeAudioSource = QAudioSource; -#endif - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Time.h" -//#include "Common/Cpp/StreamConverters.h" -#include "CommonFramework/AudioPipeline/AudioStream.h" -#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" -#include "AudioFileLoader.h" -#include "AudioSource.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -class AudioInputFile final : public QObject{ -public: - AudioInputFile( - Logger& logger, AudioStreamToFloat& reader, - const std::string& file, const QAudioFormat& format - ) - : m_reader(reader) - { - logger.log("AudioInputFile(): " + dumpAudioFormat(format)); - m_source = std::make_unique(nullptr, file, format); - connect( - m_source.get(), &AudioFileLoader::bufferReady, - this, [this](const char* data, size_t len){ - m_reader.push_bytes(data, len); - } - ); - m_source->start(); - } - -private: - AudioStreamToFloat& m_reader; - std::unique_ptr m_source; -}; - -class AudioInputDevice final : public QIODevice{ -public: - AudioInputDevice( - Logger& logger, AudioStreamToFloat& reader, - const NativeAudioInfo& device, const QAudioFormat& format - ) - : m_reader(reader) - { - logger.log("AudioInputDevice(): " + dumpAudioFormat(format)); - if (!device.isFormatSupported(format)){ -// throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, "Format not supported: " + dumpAudioFormat(format)); - logger.log("Format not supported: " + dumpAudioFormat(format), COLOR_RED); - return; - } - m_source = std::make_unique(device, format); - - this->open(QIODevice::ReadWrite | QIODevice::Unbuffered); - - WallClock start = current_time(); - m_source->start(this); - WallClock end = current_time(); - double seconds = std::chrono::duration_cast(end - start).count() / 1000.; - logger.log("Done starting audio... " + tostr_fixed(seconds, 3) + " seconds", COLOR_CYAN); - } - ~AudioInputDevice(){ - if (m_source){ - m_source->stop(); - } - } - - virtual bool isSequential() const override { return true; } - virtual qint64 readData(char* data, qint64 maxlen) override { return 0; } - virtual qint64 writeData(const char* data, qint64 len) override{ - m_reader.push_bytes(data, len); - return len; - } - -private: - AudioStreamToFloat& m_reader; - std::unique_ptr m_source; -}; - - - -class AudioSource::InternalListener : public AudioFloatStreamListener{ -public: - InternalListener(AudioSource& parent) - : AudioFloatStreamListener(parent.m_channels * parent.m_multiplier) - , m_parent(parent) - {} - -private: - virtual void on_samples(const float* data, size_t objects) override{ -// cout << "objects = " << objects << endl; - m_parent.m_listeners.run_method_unique( - &AudioFloatStreamListener::on_samples, - data, objects - ); - } - - AudioSource& m_parent; -}; - - - - -void AudioSource::add_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - m_listeners.add(listener); -} -void AudioSource::remove_listener(AudioFloatStreamListener& listener){ - auto scope_check = m_sanitizer.check_scope(); - m_listeners.remove(listener); -} - - -AudioSource::~AudioSource(){} - -AudioSource::AudioSource(Logger& logger, const std::string& file, AudioChannelFormat format, float volume_multiplier){ - QAudioFormat native_format; - setSampleFormatToFloat(native_format); - set_format(native_format, format); - init(format, AudioSampleFormat::FLOAT32, volume_multiplier); - m_input_file = std::make_unique(logger, *m_reader, file, native_format); -} -AudioSource::AudioSource(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, float volume_multiplier){ - NativeAudioInfo native_info = device.native_info(); - QAudioFormat native_format = native_info.preferredFormat(); - - set_format(native_format, format); - - AudioSampleFormat stream_format = get_sample_format(native_format); - if (stream_format == AudioSampleFormat::INVALID){ - stream_format = AudioSampleFormat::FLOAT32; - setSampleFormatToFloat(native_format); - } - - init(format, stream_format, volume_multiplier); - m_input_device = std::make_unique(logger, *m_reader, native_info, native_format); -} - -void AudioSource::init(AudioChannelFormat format, AudioSampleFormat stream_format, float volume_multiplier){ - auto scope_check = m_sanitizer.check_scope(); - switch (format){ - case AudioChannelFormat::MONO_48000: - m_sample_rate = 48000; - m_channels = 1; - m_multiplier = 1; - m_reader.reset(new AudioStreamToFloat(stream_format, 1, volume_multiplier, false)); - break; - case AudioChannelFormat::DUAL_44100: - m_sample_rate = 44100; - m_channels = 2; - m_multiplier = 1; - m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); - break; - case AudioChannelFormat::DUAL_48000: - m_sample_rate = 48000; - m_channels = 2; - m_multiplier = 1; - m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); - break; - case AudioChannelFormat::MONO_96000: - // Treat mono-96000 as 2-sample frames. - // The FFT will then average each pair to produce 48000Hz. - // The output will push the same stream at the original 4 bytes * 96000Hz. - m_sample_rate = 96000; - m_channels = 1; - m_multiplier = 2; - m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); - break; - case AudioChannelFormat::INTERLEAVE_LR_96000: - m_sample_rate = 48000; - m_channels = 2; - m_multiplier = 1; - m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); - break; - case AudioChannelFormat::INTERLEAVE_RL_96000: - m_sample_rate = 48000; - m_channels = 2; - m_multiplier = 1; - m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, true)); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); - } - - m_internal_listener = std::make_unique(*this); - m_reader->add_listener(*m_internal_listener); -} - - - - - - - - - -} +/* Audio Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if QT_VERSION_MAJOR == 5 +#include +using NativeAudioSource = QAudioInput; +#elif QT_VERSION_MAJOR == 6 +#include +using NativeAudioSource = QAudioSource; +#endif + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Time.h" +//#include "Common/Cpp/StreamConverters.h" +#include "CommonFramework/AudioPipeline/AudioStream.h" +#include "CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h" +#include "AudioFileLoader.h" +#include "AudioSource.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +class AudioInputFile final : public QObject{ +public: + AudioInputFile( + Logger& logger, AudioStreamToFloat& reader, + const std::string& file, const QAudioFormat& format + ) + : m_reader(reader) + { + logger.log("AudioInputFile(): " + dumpAudioFormat(format)); + m_source = std::make_unique(nullptr, file, format); + connect( + m_source.get(), &AudioFileLoader::bufferReady, + this, [this](const char* data, size_t len){ + m_reader.push_bytes(data, len); + } + ); + m_source->start(); + } + +private: + AudioStreamToFloat& m_reader; + std::unique_ptr m_source; +}; + +class AudioInputDevice final : public QIODevice{ +public: + AudioInputDevice( + Logger& logger, AudioStreamToFloat& reader, + const NativeAudioInfo& device, const QAudioFormat& format + ) + : m_reader(reader) + { + logger.log("AudioInputDevice(): " + dumpAudioFormat(format)); + if (!device.isFormatSupported(format)){ +// throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, "Format not supported: " + dumpAudioFormat(format)); + logger.log("Format not supported: " + dumpAudioFormat(format), COLOR_RED); + return; + } + m_source = std::make_unique(device, format); + + this->open(QIODevice::ReadWrite | QIODevice::Unbuffered); + + WallClock start = current_time(); + m_source->start(this); + WallClock end = current_time(); + double seconds = std::chrono::duration_cast(end - start).count() / 1000.; + logger.log("Done starting audio... " + tostr_fixed(seconds, 3) + " seconds", COLOR_CYAN); + } + ~AudioInputDevice(){ + if (m_source){ + m_source->stop(); + } + } + + virtual bool isSequential() const override { return true; } + virtual qint64 readData(char* data, qint64 maxlen) override { return 0; } + virtual qint64 writeData(const char* data, qint64 len) override{ + m_reader.push_bytes(data, len); + return len; + } + +private: + AudioStreamToFloat& m_reader; + std::unique_ptr m_source; +}; + + + +class AudioSource::InternalListener : public AudioFloatStreamListener{ +public: + InternalListener(AudioSource& parent) + : AudioFloatStreamListener(parent.m_channels * parent.m_multiplier) + , m_parent(parent) + {} + +private: + virtual void on_samples(const float* data, size_t objects) override{ +// cout << "objects = " << objects << endl; + m_parent.m_listeners.run_method_unique( + &AudioFloatStreamListener::on_samples, + data, objects + ); + } + + AudioSource& m_parent; +}; + + + + +void AudioSource::add_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_listeners.add(listener); +} +void AudioSource::remove_listener(AudioFloatStreamListener& listener){ + auto scope_check = m_sanitizer.check_scope(); + m_listeners.remove(listener); +} + + +AudioSource::~AudioSource(){} + +AudioSource::AudioSource(Logger& logger, const std::string& file, AudioChannelFormat format, float volume_multiplier){ + QAudioFormat native_format; + setSampleFormatToFloat(native_format); + set_format(native_format, format); + init(format, AudioSampleFormat::FLOAT32, volume_multiplier); + m_input_file = std::make_unique(logger, *m_reader, file, native_format); +} +AudioSource::AudioSource(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, float volume_multiplier){ + NativeAudioInfo native_info = device.native_info(); + QAudioFormat native_format = native_info.preferredFormat(); + + set_format(native_format, format); + + AudioSampleFormat stream_format = get_sample_format(native_format); + if (stream_format == AudioSampleFormat::INVALID){ + stream_format = AudioSampleFormat::FLOAT32; + setSampleFormatToFloat(native_format); + } + + init(format, stream_format, volume_multiplier); + m_input_device = std::make_unique(logger, *m_reader, native_info, native_format); +} + +void AudioSource::init(AudioChannelFormat format, AudioSampleFormat stream_format, float volume_multiplier){ + auto scope_check = m_sanitizer.check_scope(); + switch (format){ + case AudioChannelFormat::MONO_48000: + m_sample_rate = 48000; + m_channels = 1; + m_multiplier = 1; + m_reader.reset(new AudioStreamToFloat(stream_format, 1, volume_multiplier, false)); + break; + case AudioChannelFormat::DUAL_44100: + m_sample_rate = 44100; + m_channels = 2; + m_multiplier = 1; + m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); + break; + case AudioChannelFormat::DUAL_48000: + m_sample_rate = 48000; + m_channels = 2; + m_multiplier = 1; + m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); + break; + case AudioChannelFormat::MONO_96000: + // Treat mono-96000 as 2-sample frames. + // The FFT will then average each pair to produce 48000Hz. + // The output will push the same stream at the original 4 bytes * 96000Hz. + m_sample_rate = 96000; + m_channels = 1; + m_multiplier = 2; + m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); + break; + case AudioChannelFormat::INTERLEAVE_LR_96000: + m_sample_rate = 48000; + m_channels = 2; + m_multiplier = 1; + m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, false)); + break; + case AudioChannelFormat::INTERLEAVE_RL_96000: + m_sample_rate = 48000; + m_channels = 2; + m_multiplier = 1; + m_reader.reset(new AudioStreamToFloat(stream_format, 2, volume_multiplier, true)); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); + } + + m_internal_listener = std::make_unique(*this); + m_reader->add_listener(*m_internal_listener); +} + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.h index ba60752564..2182dd13ea 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/IO/AudioSource.h @@ -1,74 +1,74 @@ -/* Audio Source - * - * From: https://github.com/PokemonAutomation/ - * - * AudioSource represents an audio input stream. Once constructed, - * it spits out the float samples. Listeners can attach themselves to this - * class to receive these audio frames. - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioSource_H -#define PokemonAutomation_AudioPipeline_AudioSource_H - -#include -#include -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/AudioPipeline/AudioInfo.h" -#include "CommonFramework/AudioPipeline/AudioStream.h" - -namespace PokemonAutomation{ - -class Logger; -class AudioStreamToFloat; -class AudioInputFile; -class AudioInputDevice; - - -class AudioSource{ -public: - void add_listener(AudioFloatStreamListener& listener); - void remove_listener(AudioFloatStreamListener& listener); - -public: - ~AudioSource(); - - // Read from an audio file. (i.e. .wav or .mp3) - AudioSource(Logger& logger, const std::string& file, AudioChannelFormat format, float volume_multiplier); - - // Read from an audio input device. (i.e. capture card) - AudioSource(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, float volume_multiplier); - - size_t sample_rate() const{ return m_sample_rate; } - size_t channels() const{ return m_channels; } - size_t samples_per_frame() const{ return m_channels * m_multiplier; } - -private: - void init(AudioChannelFormat format, AudioSampleFormat stream_format, float volume_multiplier); - -private: - class InternalListener; - - size_t m_sample_rate; - size_t m_channels; - size_t m_multiplier; - - SpinLock m_lock; - - std::unique_ptr m_internal_listener; - std::unique_ptr m_reader; - - std::unique_ptr m_input_file; - std::unique_ptr m_input_device; - - ListenerSet m_listeners; - - LifetimeSanitizer m_sanitizer; -}; - - - -} -#endif +/* Audio Source + * + * From: https://github.com/PokemonAutomation/ + * + * AudioSource represents an audio input stream. Once constructed, + * it spits out the float samples. Listeners can attach themselves to this + * class to receive these audio frames. + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioSource_H +#define PokemonAutomation_AudioPipeline_AudioSource_H + +#include +#include +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/AudioPipeline/AudioInfo.h" +#include "CommonFramework/AudioPipeline/AudioStream.h" + +namespace PokemonAutomation{ + +class Logger; +class AudioStreamToFloat; +class AudioInputFile; +class AudioInputDevice; + + +class AudioSource{ +public: + void add_listener(AudioFloatStreamListener& listener); + void remove_listener(AudioFloatStreamListener& listener); + +public: + ~AudioSource(); + + // Read from an audio file. (i.e. .wav or .mp3) + AudioSource(Logger& logger, const std::string& file, AudioChannelFormat format, float volume_multiplier); + + // Read from an audio input device. (i.e. capture card) + AudioSource(Logger& logger, const AudioDeviceInfo& device, AudioChannelFormat format, float volume_multiplier); + + size_t sample_rate() const{ return m_sample_rate; } + size_t channels() const{ return m_channels; } + size_t samples_per_frame() const{ return m_channels * m_multiplier; } + +private: + void init(AudioChannelFormat format, AudioSampleFormat stream_format, float volume_multiplier); + +private: + class InternalListener; + + size_t m_sample_rate; + size_t m_channels; + size_t m_multiplier; + + SpinLock m_lock; + + std::unique_ptr m_internal_listener; + std::unique_ptr m_reader; + + std::unique_ptr m_input_file; + std::unique_ptr m_input_device; + + ListenerSet m_listeners; + + LifetimeSanitizer m_sanitizer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.cpp index c872aafa7a..1aa073f3da 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.cpp @@ -1,363 +1,363 @@ -/* Audio Display State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "CommonFramework/AudioPipeline/AudioConstants.h" -#include "AudioSpectrumHolder.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -AudioSpectrumHolder::AudioSpectrumHolder() - : m_num_freqs(NUM_FFT_SAMPLES/2) - , m_num_freq_windows(1000) -// , m_num_freq_visualization_blocks(384) -// , m_freq_visualization_block_boundaries(m_num_freq_visualization_blocks + 1) -// , m_spectrograph(m_num_freq_visualization_blocks, m_num_freq_windows) - , m_freqVisStamps(m_num_freq_windows) -{ - // We will display frequencies in log scale, so need to convert - // log scale: 0, 1/m_numFreqVisBlocks, 2/m_numFreqVisBlocks, ..., 1.0 - // to linear scale: - // The conversion function is: linear_value = (exp(log_value * LOG_MAX) - 1) / 10 -// const float LOG_SCALE_MAX = std::log(11.0f); - - size_t blocks = 384; - std::vector boundaries(blocks); - - boundaries[0] = 1; - for (size_t i = 1; i < blocks - 1; i++){ -// const float logValue = i / (float)m_numFreqVisBlocks; -// float linearValue = (std::exp(logValue * LOG_SCALE_MAX) - 1.f) / 10.f; -// linearValue = std::max(std::min(linearValue, 1.0f), 0.0f); -// boundaries[i] = std::min(size_t(linearValue * m_num_freqs + 0.5), m_num_freqs); - - // (384 / 8 = 48) give us 48 bars per octave. - const float x = (float)i / blocks; - float freq = std::exp2f(8.0f * x + 3); - size_t index = (size_t)freq; - - index = std::max(index, (size_t)1); - index = std::min(index, m_num_freqs); - boundaries[i] = index; - } - boundaries[blocks - 1] = m_num_freqs; - - // Iterate buckets in reverse order and push the lower frequencies over so that everyone has - // a width of at least 1. - size_t last = boundaries[blocks - 1]; - for (size_t c = blocks - 1; c-- > 0;){ - size_t current = boundaries[c]; - if (current >= last){ - current = last - 1; - if (current == 0){ - current = 1; - } - } - m_freq_visualization_block_boundaries.emplace_back(current); - if (current == 1){ - break; - } - last = current; - } - - blocks = m_freq_visualization_block_boundaries.size(); - std::reverse(m_freq_visualization_block_boundaries.begin(), m_freq_visualization_block_boundaries.end()); - - -// for (size_t i = 1; i <= m_num_freq_visualization_blocks; i++){ -// assert(m_freq_visualization_block_boundaries[i-1] < m_freq_visualization_block_boundaries[i]); -// } -// for (size_t i = 0; i < m_num_freq_visualization_blocks; i++){ -// cout << "index = " << m_freq_visualization_block_boundaries[i] << endl; -// } - -// cout << "Freq vis block boundaries: "; -// for(const auto v : m_freq_visualization_block_boundaries){ -// cout << v << " "; -// } -// cout << endl; - - // saveAudioFrequenciesToDisk(true); - - m_spectrograph.reset(new Spectrograph(blocks, m_num_freq_windows)); - m_last_spectrum.timestamp = current_time(); - m_last_spectrum.values.resize(blocks); - m_last_spectrum.colors.resize(blocks); -} - - -void AudioSpectrumHolder::add_listener(Listener& listener){ - m_listeners.add(listener); -} -void AudioSpectrumHolder::remove_listener(Listener& listener){ - m_listeners.remove(listener); -} - -void AudioSpectrumHolder::clear(){ - { - std::lock_guard lg(m_state_lock); - - m_freqVisStamps.assign(m_freqVisStamps.size(), SIZE_MAX); - - { - // update m_spectrum_stamp_start in case the audio widget is used - // again to store new spectrums. - if (m_spectrums.size() > 0){ - m_spectrum_stamp_start = m_spectrums.front().stamp + 1; - } - m_spectrums.clear(); - - m_spectrograph->clear(); - m_last_spectrum.timestamp = current_time(); - memset(m_last_spectrum.values.data(), 0, m_last_spectrum.values.size() * sizeof(float)); - memset(m_last_spectrum.colors.data(), 0, m_last_spectrum.colors.size() * sizeof(uint32_t)); - } - - m_overlay.clear(); -// cout << "AudioSpectrumHolder::clear()" << endl; - } - - m_listeners.run_method_unique(&Listener::state_changed); -} - -//void AudioSpectrumHolder::reset(){} - - -// TODO: move this to a common lib folder: -PA_FORCE_INLINE uint32_t jetColorMap(float v){ - if (v <= 0.f){ - return combine_rgb(0,0,0); - }else if (v < 0.125f){ -// return qRgb(0, 0, int((0.5f + 4.f * v) * 255.f)); - return combine_rgb(0, 0, uint8_t((0.0f + 8.f * v) * 255.f)); - }else if (v < 0.375f){ - return combine_rgb(0, uint8_t((v - 0.125f)*1020.f), 255); - }else if (v < 0.625f){ - uint8_t c = uint8_t((v - 0.375f) * 1020.f); - return combine_rgb(c, 255, 255-c); - }else if (v < 0.875f){ - return combine_rgb(255, 255 - uint8_t((v-0.625f) * 1020.f), 0); - }else if (v <= 1.0){ - return combine_rgb(255 - uint8_t((v-0.875)*1020.f), 0, 0); - }else{ - return combine_rgb(255, 255, 255); - } -} - -void AudioSpectrumHolder::push_spectrum(size_t sample_rate, std::shared_ptr> fft_output){ - WallClock timestamp = current_time(); - - { - std::lock_guard lg(m_state_lock); - - const AlignedVector& output = *fft_output; - - { - const size_t stamp = (m_spectrums.size() > 0) ? m_spectrums.front().stamp + 1 : m_spectrum_stamp_start; - m_spectrums.emplace_front(stamp, sample_rate, fft_output); - if (m_spectrums.size() > m_spectrum_history_length){ - m_spectrums.pop_back(); - } - - // std::cout << "Load FFT output , stamp " << spectrum->stamp << std::endl; - m_freqVisStamps[m_nextFFTWindowIndex] = stamp; - } - - // Scale the by the square root of the transform length. - // For random noise input, the frequency domain will have an average - // magnitude of sqrt(transform length). - float scale = std::sqrt(0.25f / (float)output.size()); - -// // Divide by output size. Since samples can never be larger than 1.0, the -// // frequency domain can never be larger than the FFT length. So we scale by -// // the FFT length to guarantee that it also stays less than 1.0. -// float scale = 0.5f / (float)output.size(); - -// float skew_factor = 999.; -// float skew_scale = 1.f / (float)std::log1pf(skew_factor); - - // For one window, use how many blocks to show all frequencies: - float previous = 0; - m_last_spectrum.timestamp = timestamp; - for (size_t i = 0; i < m_freq_visualization_block_boundaries.size() - 1; i++){ - float mag = 0.0f; - for(size_t j = m_freq_visualization_block_boundaries[i]; j < m_freq_visualization_block_boundaries[i+1]; j++){ - mag += output[j]; - } - - size_t width = m_freq_visualization_block_boundaries[i+1] - m_freq_visualization_block_boundaries[i]; - - if (width == 0){ - mag = previous; - }else{ - mag /= width; - mag *= scale; - - mag = std::sqrt(mag); -// mag = std::log1pf(mag * skew_factor) * skew_scale; -// mag = std::log1pf(std::sqrtf(mag)) * std::log1pf(1); -// mag = std::sqrt(2*mag - mag*mag); -// float m1 = 1 - mag; -// mag = std::sqrtf(1 - m1*m1); - - // Clamp to [0.0, 1.0] - mag = std::min(mag, 1.0f); - mag = std::max(mag, 0.0f); - } - - m_last_spectrum.values[i] = mag; - m_last_spectrum.colors[i] = jetColorMap(mag); - previous = mag; - } -// cout << "AudioSpectrumHolder::push_spectrum" << endl; - m_spectrograph->push_spectrum(m_last_spectrum.colors.data()); - m_nextFFTWindowIndex = (m_nextFFTWindowIndex+1) % m_num_freq_windows; -// std::cout << "Computed FFT! " << magSum << std::endl; - - if (m_saveFreqToDisk){ - for(size_t i = 0; i < m_num_freqs; i++){ - m_freqStream << output[i] << " "; - } - m_freqStream << std::endl; - } - } - m_listeners.run_method_unique(&Listener::state_changed); -} -void AudioSpectrumHolder::add_overlay(uint64_t starting_stamp, uint64_t end_stamp, Color color){ - { - std::lock_guard lg(m_state_lock); - - m_overlay.emplace_front(std::forward_as_tuple(starting_stamp, end_stamp, color)); - - // Now try to remove old overlays that are no longer showed on the spectrogram view. - - // get the timestamp of the oldest window in the display history. - uint64_t oldestStamp = m_freqVisStamps[m_nextFFTWindowIndex]; - // SIZE_MAX means this slot is not yet assigned an FFT window - if (oldestStamp != SIZE_MAX){ - // Note: in this file we never consider the case that stamp may overflow. - // It requires on the order of 1e10 years to overflow if we have about 25ms per stamp. - while(!m_overlay.empty() && std::get<1>(m_overlay.back()) <= oldestStamp){ - m_overlay.pop_back(); - } - } - } - m_listeners.run_method_unique(&Listener::state_changed); -} - -std::vector AudioSpectrumHolder::spectrums_since(uint64_t starting_stamp){ - std::vector spectrums; - - std::lock_guard lg(m_state_lock); - - for (const auto& ptr : m_spectrums){ - if (ptr.stamp >= starting_stamp){ - spectrums.emplace_back(ptr); - }else{ - break; - } - } - return spectrums; -} -std::vector AudioSpectrumHolder::spectrums_latest(size_t num_latest_spectrums){ - std::vector spectrums; - - std::lock_guard lg(m_state_lock); - - size_t i = 0; - for (const auto& ptr : m_spectrums){ - if (i == num_latest_spectrums){ - break; - } - spectrums.push_back(ptr); - i++; - } - return spectrums; -} -AudioSpectrumHolder::SpectrumSnapshot AudioSpectrumHolder::get_last_spectrum() const{ - std::lock_guard lg(m_state_lock); - return m_last_spectrum; -} -AudioSpectrumHolder::SpectrographSnapshot AudioSpectrumHolder::get_spectrograph() const{ - std::lock_guard lg(m_state_lock); - - SpectrographSnapshot ret; - ret.image = m_spectrograph->to_image(); - - // Calculate overplay coordinates. - - // The oldest window on the spectrogram view has the oldest timestamp, - // and its position is left most on the spectrogram, assigning a window ID of 0. - size_t oldestStamp = m_freqVisStamps[m_nextFFTWindowIndex]; - size_t oldestWindowID = 0; - // When the audio stream starts coming in, the history of the spectrogram - // is not fully filled. So the oldest stamp may not be the leftmost one on the display. - // Here we use the validity of the time stamp to find the real oldest one. - for (; oldestWindowID < m_num_freq_windows; oldestWindowID++){ - if (oldestStamp != SIZE_MAX){ - // it's a window with valid stamp - break; - } - oldestStamp = m_freqVisStamps[(m_nextFFTWindowIndex+oldestWindowID) % m_num_freq_windows]; - } - if (oldestStamp == SIZE_MAX){ - // we have no valid windows in the spectrogram, so no overlays to render: - return ret; - } - size_t newestStamp = m_freqVisStamps[(m_nextFFTWindowIndex + m_num_freq_windows - 1) % m_num_freq_windows]; - // size_t newestWindowID = m_num_freq_windows - 1; - - for (const auto& box : m_overlay){ - const size_t starting_stamp = std::get<0>(box); - const size_t end_stamp = std::get<1>(box); - const Color color = std::get<2>(box); - if (starting_stamp >= end_stamp){ - continue; - } - - // std::cout << "Render overlay at (" << starting_stamp << ", " << end_stamp - // << ") oldestStamp " << oldestStamp << " wID " << oldestWindowID << " newest stamp " << newestStamp << std::endl; - - if (end_stamp <= oldestStamp || starting_stamp > newestStamp){ - continue; - } - - ret.overlays.emplace_back( - starting_stamp - oldestStamp + oldestWindowID, - end_stamp - starting_stamp, - color - ); - } - return ret; -} - - -void AudioSpectrumHolder::saveAudioFrequenciesToDisk(bool enable){ - std::lock_guard lg(m_state_lock); - if (enable){ - if (m_saveFreqToDisk == false){ - m_saveFreqToDisk = enable; - m_freqStream.open("./frequencies.txt"); - } - }else if (m_saveFreqToDisk){ - m_saveFreqToDisk = enable; - m_freqStream.close(); - } -} - - - - -} +/* Audio Display State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "CommonFramework/AudioPipeline/AudioConstants.h" +#include "AudioSpectrumHolder.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +AudioSpectrumHolder::AudioSpectrumHolder() + : m_num_freqs(NUM_FFT_SAMPLES/2) + , m_num_freq_windows(1000) +// , m_num_freq_visualization_blocks(384) +// , m_freq_visualization_block_boundaries(m_num_freq_visualization_blocks + 1) +// , m_spectrograph(m_num_freq_visualization_blocks, m_num_freq_windows) + , m_freqVisStamps(m_num_freq_windows) +{ + // We will display frequencies in log scale, so need to convert + // log scale: 0, 1/m_numFreqVisBlocks, 2/m_numFreqVisBlocks, ..., 1.0 + // to linear scale: + // The conversion function is: linear_value = (exp(log_value * LOG_MAX) - 1) / 10 +// const float LOG_SCALE_MAX = std::log(11.0f); + + size_t blocks = 384; + std::vector boundaries(blocks); + + boundaries[0] = 1; + for (size_t i = 1; i < blocks - 1; i++){ +// const float logValue = i / (float)m_numFreqVisBlocks; +// float linearValue = (std::exp(logValue * LOG_SCALE_MAX) - 1.f) / 10.f; +// linearValue = std::max(std::min(linearValue, 1.0f), 0.0f); +// boundaries[i] = std::min(size_t(linearValue * m_num_freqs + 0.5), m_num_freqs); + + // (384 / 8 = 48) give us 48 bars per octave. + const float x = (float)i / blocks; + float freq = std::exp2f(8.0f * x + 3); + size_t index = (size_t)freq; + + index = std::max(index, (size_t)1); + index = std::min(index, m_num_freqs); + boundaries[i] = index; + } + boundaries[blocks - 1] = m_num_freqs; + + // Iterate buckets in reverse order and push the lower frequencies over so that everyone has + // a width of at least 1. + size_t last = boundaries[blocks - 1]; + for (size_t c = blocks - 1; c-- > 0;){ + size_t current = boundaries[c]; + if (current >= last){ + current = last - 1; + if (current == 0){ + current = 1; + } + } + m_freq_visualization_block_boundaries.emplace_back(current); + if (current == 1){ + break; + } + last = current; + } + + blocks = m_freq_visualization_block_boundaries.size(); + std::reverse(m_freq_visualization_block_boundaries.begin(), m_freq_visualization_block_boundaries.end()); + + +// for (size_t i = 1; i <= m_num_freq_visualization_blocks; i++){ +// assert(m_freq_visualization_block_boundaries[i-1] < m_freq_visualization_block_boundaries[i]); +// } +// for (size_t i = 0; i < m_num_freq_visualization_blocks; i++){ +// cout << "index = " << m_freq_visualization_block_boundaries[i] << endl; +// } + +// cout << "Freq vis block boundaries: "; +// for(const auto v : m_freq_visualization_block_boundaries){ +// cout << v << " "; +// } +// cout << endl; + + // saveAudioFrequenciesToDisk(true); + + m_spectrograph.reset(new Spectrograph(blocks, m_num_freq_windows)); + m_last_spectrum.timestamp = current_time(); + m_last_spectrum.values.resize(blocks); + m_last_spectrum.colors.resize(blocks); +} + + +void AudioSpectrumHolder::add_listener(Listener& listener){ + m_listeners.add(listener); +} +void AudioSpectrumHolder::remove_listener(Listener& listener){ + m_listeners.remove(listener); +} + +void AudioSpectrumHolder::clear(){ + { + std::lock_guard lg(m_state_lock); + + m_freqVisStamps.assign(m_freqVisStamps.size(), SIZE_MAX); + + { + // update m_spectrum_stamp_start in case the audio widget is used + // again to store new spectrums. + if (m_spectrums.size() > 0){ + m_spectrum_stamp_start = m_spectrums.front().stamp + 1; + } + m_spectrums.clear(); + + m_spectrograph->clear(); + m_last_spectrum.timestamp = current_time(); + memset(m_last_spectrum.values.data(), 0, m_last_spectrum.values.size() * sizeof(float)); + memset(m_last_spectrum.colors.data(), 0, m_last_spectrum.colors.size() * sizeof(uint32_t)); + } + + m_overlay.clear(); +// cout << "AudioSpectrumHolder::clear()" << endl; + } + + m_listeners.run_method_unique(&Listener::state_changed); +} + +//void AudioSpectrumHolder::reset(){} + + +// TODO: move this to a common lib folder: +PA_FORCE_INLINE uint32_t jetColorMap(float v){ + if (v <= 0.f){ + return combine_rgb(0,0,0); + }else if (v < 0.125f){ +// return qRgb(0, 0, int((0.5f + 4.f * v) * 255.f)); + return combine_rgb(0, 0, uint8_t((0.0f + 8.f * v) * 255.f)); + }else if (v < 0.375f){ + return combine_rgb(0, uint8_t((v - 0.125f)*1020.f), 255); + }else if (v < 0.625f){ + uint8_t c = uint8_t((v - 0.375f) * 1020.f); + return combine_rgb(c, 255, 255-c); + }else if (v < 0.875f){ + return combine_rgb(255, 255 - uint8_t((v-0.625f) * 1020.f), 0); + }else if (v <= 1.0){ + return combine_rgb(255 - uint8_t((v-0.875)*1020.f), 0, 0); + }else{ + return combine_rgb(255, 255, 255); + } +} + +void AudioSpectrumHolder::push_spectrum(size_t sample_rate, std::shared_ptr> fft_output){ + WallClock timestamp = current_time(); + + { + std::lock_guard lg(m_state_lock); + + const AlignedVector& output = *fft_output; + + { + const size_t stamp = (m_spectrums.size() > 0) ? m_spectrums.front().stamp + 1 : m_spectrum_stamp_start; + m_spectrums.emplace_front(stamp, sample_rate, fft_output); + if (m_spectrums.size() > m_spectrum_history_length){ + m_spectrums.pop_back(); + } + + // std::cout << "Load FFT output , stamp " << spectrum->stamp << std::endl; + m_freqVisStamps[m_nextFFTWindowIndex] = stamp; + } + + // Scale the by the square root of the transform length. + // For random noise input, the frequency domain will have an average + // magnitude of sqrt(transform length). + float scale = std::sqrt(0.25f / (float)output.size()); + +// // Divide by output size. Since samples can never be larger than 1.0, the +// // frequency domain can never be larger than the FFT length. So we scale by +// // the FFT length to guarantee that it also stays less than 1.0. +// float scale = 0.5f / (float)output.size(); + +// float skew_factor = 999.; +// float skew_scale = 1.f / (float)std::log1pf(skew_factor); + + // For one window, use how many blocks to show all frequencies: + float previous = 0; + m_last_spectrum.timestamp = timestamp; + for (size_t i = 0; i < m_freq_visualization_block_boundaries.size() - 1; i++){ + float mag = 0.0f; + for(size_t j = m_freq_visualization_block_boundaries[i]; j < m_freq_visualization_block_boundaries[i+1]; j++){ + mag += output[j]; + } + + size_t width = m_freq_visualization_block_boundaries[i+1] - m_freq_visualization_block_boundaries[i]; + + if (width == 0){ + mag = previous; + }else{ + mag /= width; + mag *= scale; + + mag = std::sqrt(mag); +// mag = std::log1pf(mag * skew_factor) * skew_scale; +// mag = std::log1pf(std::sqrtf(mag)) * std::log1pf(1); +// mag = std::sqrt(2*mag - mag*mag); +// float m1 = 1 - mag; +// mag = std::sqrtf(1 - m1*m1); + + // Clamp to [0.0, 1.0] + mag = std::min(mag, 1.0f); + mag = std::max(mag, 0.0f); + } + + m_last_spectrum.values[i] = mag; + m_last_spectrum.colors[i] = jetColorMap(mag); + previous = mag; + } +// cout << "AudioSpectrumHolder::push_spectrum" << endl; + m_spectrograph->push_spectrum(m_last_spectrum.colors.data()); + m_nextFFTWindowIndex = (m_nextFFTWindowIndex+1) % m_num_freq_windows; +// std::cout << "Computed FFT! " << magSum << std::endl; + + if (m_saveFreqToDisk){ + for(size_t i = 0; i < m_num_freqs; i++){ + m_freqStream << output[i] << " "; + } + m_freqStream << std::endl; + } + } + m_listeners.run_method_unique(&Listener::state_changed); +} +void AudioSpectrumHolder::add_overlay(uint64_t starting_stamp, uint64_t end_stamp, Color color){ + { + std::lock_guard lg(m_state_lock); + + m_overlay.emplace_front(std::forward_as_tuple(starting_stamp, end_stamp, color)); + + // Now try to remove old overlays that are no longer showed on the spectrogram view. + + // get the timestamp of the oldest window in the display history. + uint64_t oldestStamp = m_freqVisStamps[m_nextFFTWindowIndex]; + // SIZE_MAX means this slot is not yet assigned an FFT window + if (oldestStamp != SIZE_MAX){ + // Note: in this file we never consider the case that stamp may overflow. + // It requires on the order of 1e10 years to overflow if we have about 25ms per stamp. + while(!m_overlay.empty() && std::get<1>(m_overlay.back()) <= oldestStamp){ + m_overlay.pop_back(); + } + } + } + m_listeners.run_method_unique(&Listener::state_changed); +} + +std::vector AudioSpectrumHolder::spectrums_since(uint64_t starting_stamp){ + std::vector spectrums; + + std::lock_guard lg(m_state_lock); + + for (const auto& ptr : m_spectrums){ + if (ptr.stamp >= starting_stamp){ + spectrums.emplace_back(ptr); + }else{ + break; + } + } + return spectrums; +} +std::vector AudioSpectrumHolder::spectrums_latest(size_t num_latest_spectrums){ + std::vector spectrums; + + std::lock_guard lg(m_state_lock); + + size_t i = 0; + for (const auto& ptr : m_spectrums){ + if (i == num_latest_spectrums){ + break; + } + spectrums.push_back(ptr); + i++; + } + return spectrums; +} +AudioSpectrumHolder::SpectrumSnapshot AudioSpectrumHolder::get_last_spectrum() const{ + std::lock_guard lg(m_state_lock); + return m_last_spectrum; +} +AudioSpectrumHolder::SpectrographSnapshot AudioSpectrumHolder::get_spectrograph() const{ + std::lock_guard lg(m_state_lock); + + SpectrographSnapshot ret; + ret.image = m_spectrograph->to_image(); + + // Calculate overplay coordinates. + + // The oldest window on the spectrogram view has the oldest timestamp, + // and its position is left most on the spectrogram, assigning a window ID of 0. + size_t oldestStamp = m_freqVisStamps[m_nextFFTWindowIndex]; + size_t oldestWindowID = 0; + // When the audio stream starts coming in, the history of the spectrogram + // is not fully filled. So the oldest stamp may not be the leftmost one on the display. + // Here we use the validity of the time stamp to find the real oldest one. + for (; oldestWindowID < m_num_freq_windows; oldestWindowID++){ + if (oldestStamp != SIZE_MAX){ + // it's a window with valid stamp + break; + } + oldestStamp = m_freqVisStamps[(m_nextFFTWindowIndex+oldestWindowID) % m_num_freq_windows]; + } + if (oldestStamp == SIZE_MAX){ + // we have no valid windows in the spectrogram, so no overlays to render: + return ret; + } + size_t newestStamp = m_freqVisStamps[(m_nextFFTWindowIndex + m_num_freq_windows - 1) % m_num_freq_windows]; + // size_t newestWindowID = m_num_freq_windows - 1; + + for (const auto& box : m_overlay){ + const size_t starting_stamp = std::get<0>(box); + const size_t end_stamp = std::get<1>(box); + const Color color = std::get<2>(box); + if (starting_stamp >= end_stamp){ + continue; + } + + // std::cout << "Render overlay at (" << starting_stamp << ", " << end_stamp + // << ") oldestStamp " << oldestStamp << " wID " << oldestWindowID << " newest stamp " << newestStamp << std::endl; + + if (end_stamp <= oldestStamp || starting_stamp > newestStamp){ + continue; + } + + ret.overlays.emplace_back( + starting_stamp - oldestStamp + oldestWindowID, + end_stamp - starting_stamp, + color + ); + } + return ret; +} + + +void AudioSpectrumHolder::saveAudioFrequenciesToDisk(bool enable){ + std::lock_guard lg(m_state_lock); + if (enable){ + if (m_saveFreqToDisk == false){ + m_saveFreqToDisk = enable; + m_freqStream.open("./frequencies.txt"); + } + }else if (m_saveFreqToDisk){ + m_saveFreqToDisk = enable; + m_freqStream.close(); + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.h index 663bc66329..f243786e9a 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/AudioSpectrumHolder.h @@ -1,118 +1,118 @@ -/* Audio Spectrum Holder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioSpectrumHolder_H -#define PokemonAutomation_AudioPipeline_AudioSpectrumHolder_H - -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/ListenerSet.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "Spectrograph.h" - -namespace PokemonAutomation{ - - -class AudioSpectrumHolder{ -public: - struct Listener{ - virtual void state_changed() = 0; - }; - - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - - -public: - AudioSpectrumHolder(); - - void clear(); -// virtual void reset() override; - - -public: - void push_spectrum(size_t sample_rate, std::shared_ptr> fft_output); - void add_overlay(uint64_t starting_stamp, uint64_t end_stamp, Color color); - - -public: - // Asynchronous and thread-safe getters. - - std::vector spectrums_since(uint64_t starting_stamp); - std::vector spectrums_latest(size_t num_latest_spectrums); - - struct SpectrumSnapshot{ - WallClock timestamp; - std::vector values; - std::vector colors; - }; - SpectrumSnapshot get_last_spectrum() const; - - struct SpectrographSnapshot{ - ImageRGB32 image; - std::vector> overlays; - }; - SpectrographSnapshot get_spectrograph() const; - - -public: - // Development usage: save the FFT results to disk so that it can be examined - // and edited to be used as samples for future audio matching. - void saveAudioFrequenciesToDisk(bool enable); - - -private: - // Num frequencies to store for the output of one fft computation. - const size_t m_num_freqs; - // Num sliding fft windows to visualize. - const size_t m_num_freq_windows; - // Num blocks of frequencies to visualize for one sliding window. -// const size_t m_num_freq_visualization_blocks; - - // The boundaries to separate each frequency vis block. - // i-th freq vis block is made by frequencies whose indices in m_spectrums - // fall inside the range: [ m_freq_visualization_block_boundaries[i], m_freq_visualization_block_boundaries[i+1] ) - std::vector m_freq_visualization_block_boundaries; - - SpectrumSnapshot m_last_spectrum; - std::unique_ptr m_spectrograph; - - // The timestamp of each window that's been visualized. - std::vector m_freqVisStamps; - // The index of the next window in m_freqVisBlocks. - size_t m_nextFFTWindowIndex = 0; - - // record the past FFT output frequencies to serve as the interface - // of audio inference for automation programs. - // The head of the list is the most recent FFT window, while the tail - // is the oldest in history. - std::list m_spectrums; - size_t m_spectrum_history_length = 40; - // The initial timestamp for the incoming spectrums. - size_t m_spectrum_stamp_start = 0; - - // Develop purpose: used to save received frequencies to disk - bool m_saveFreqToDisk = false; - std::ofstream m_freqStream; - - // The inference boxes - // to highlight FFT windows on spectrogram. Used to tell user which part - // of the audio is detected. - // The head of the list is the most recent overlay added. - std::list> m_overlay; - - mutable std::mutex m_state_lock; - ListenerSet m_listeners; -}; - - - -} -#endif +/* Audio Spectrum Holder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioSpectrumHolder_H +#define PokemonAutomation_AudioPipeline_AudioSpectrumHolder_H + +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/ListenerSet.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "Spectrograph.h" + +namespace PokemonAutomation{ + + +class AudioSpectrumHolder{ +public: + struct Listener{ + virtual void state_changed() = 0; + }; + + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + + +public: + AudioSpectrumHolder(); + + void clear(); +// virtual void reset() override; + + +public: + void push_spectrum(size_t sample_rate, std::shared_ptr> fft_output); + void add_overlay(uint64_t starting_stamp, uint64_t end_stamp, Color color); + + +public: + // Asynchronous and thread-safe getters. + + std::vector spectrums_since(uint64_t starting_stamp); + std::vector spectrums_latest(size_t num_latest_spectrums); + + struct SpectrumSnapshot{ + WallClock timestamp; + std::vector values; + std::vector colors; + }; + SpectrumSnapshot get_last_spectrum() const; + + struct SpectrographSnapshot{ + ImageRGB32 image; + std::vector> overlays; + }; + SpectrographSnapshot get_spectrograph() const; + + +public: + // Development usage: save the FFT results to disk so that it can be examined + // and edited to be used as samples for future audio matching. + void saveAudioFrequenciesToDisk(bool enable); + + +private: + // Num frequencies to store for the output of one fft computation. + const size_t m_num_freqs; + // Num sliding fft windows to visualize. + const size_t m_num_freq_windows; + // Num blocks of frequencies to visualize for one sliding window. +// const size_t m_num_freq_visualization_blocks; + + // The boundaries to separate each frequency vis block. + // i-th freq vis block is made by frequencies whose indices in m_spectrums + // fall inside the range: [ m_freq_visualization_block_boundaries[i], m_freq_visualization_block_boundaries[i+1] ) + std::vector m_freq_visualization_block_boundaries; + + SpectrumSnapshot m_last_spectrum; + std::unique_ptr m_spectrograph; + + // The timestamp of each window that's been visualized. + std::vector m_freqVisStamps; + // The index of the next window in m_freqVisBlocks. + size_t m_nextFFTWindowIndex = 0; + + // record the past FFT output frequencies to serve as the interface + // of audio inference for automation programs. + // The head of the list is the most recent FFT window, while the tail + // is the oldest in history. + std::list m_spectrums; + size_t m_spectrum_history_length = 40; + // The initial timestamp for the incoming spectrums. + size_t m_spectrum_stamp_start = 0; + + // Develop purpose: used to save received frequencies to disk + bool m_saveFreqToDisk = false; + std::ofstream m_freqStream; + + // The inference boxes + // to highlight FFT windows on spectrogram. Used to tell user which part + // of the audio is detected. + // The head of the list is the most recent overlay added. + std::list> m_overlay; + + mutable std::mutex m_state_lock; + ListenerSet m_listeners; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.cpp index 8ca9c86b06..39edb8aa24 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.cpp @@ -1,140 +1,140 @@ -/* FFT Streamer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "Kernels/AbsFFT/Kernels_AbsFFT.h" -#include "CommonFramework/AudioPipeline/AudioConstants.h" -#include "FFTStreamer.h" - -namespace PokemonAutomation{ - - - -std::unique_ptr make_FFT_streamer(AudioChannelFormat format){ - switch (format){ - case AudioChannelFormat::MONO_48000: - return std::make_unique(48000, 1, false); - case AudioChannelFormat::DUAL_44100: - return std::make_unique(44100, 2, true); - case AudioChannelFormat::DUAL_48000: - // Treat mono-96000 as 2-sample frames. - // The FFT will then average each pair to produce 48000Hz. - // The output will push the same stream at the original 4 bytes * 96000Hz. - case AudioChannelFormat::MONO_96000: - case AudioChannelFormat::INTERLEAVE_LR_96000: - case AudioChannelFormat::INTERLEAVE_RL_96000: - return std::make_unique(48000, 2, true); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); - } -} - - - -void AudioFloatToFFT::add_listener(FFTListener& listener){ - m_listeners.add(listener); -} -void AudioFloatToFFT::remove_listener(FFTListener& listener){ - m_listeners.remove(listener); -} - -AudioFloatToFFT::AudioFloatToFFT( - size_t sample_rate, - size_t samples_per_frame, bool average_pairs -) - : AudioFloatStreamListener(samples_per_frame) - , m_sample_rate(sample_rate) - , m_average(average_pairs) - , m_fft_sample_size(average_pairs ? 2 : 1) - , m_buffer(NUM_FFT_SAMPLES) - , m_buffered(NUM_FFT_SAMPLES) - , m_fft_input(NUM_FFT_SAMPLES) -{ - if (samples_per_frame == 0 || samples_per_frame > 2){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Channels must be 1 or 2."); - } - memset(m_buffer.data(), 0, m_buffer.size() * sizeof(float)); -} -AudioFloatToFFT::~AudioFloatToFFT(){} -void AudioFloatToFFT::on_samples(const float* data, size_t frames){ -// cout << "objects = " << objects << endl; - const float* ptr = data; - while (frames > 0){ - // Figure out how much space we can write contiguously. - size_t block = m_buffer.size() - std::max(m_buffered, m_end); - - // Don't write more than we have. - block = std::min(block, frames); - -// cout << "block = " << block << endl; - - // Write it. - convert(&m_buffer[m_end], ptr, block); - m_buffered += block; - m_end += block; - if (m_end == m_buffer.size()){ - m_end = 0; - } - ptr += block * m_fft_sample_size; - frames -= block; - - // Buffer is full. Time to run FFT! - if (m_buffered == m_buffer.size()){ -// cout << "run_fft()" << endl; - run_fft(); - drop_from_front(FFT_SLIDING_WINDOW_STEP); - } - } -} -void AudioFloatToFFT::convert(float* fft_input, const float* audio_stream, size_t frames){ - if (!m_average){ - memcpy(fft_input, audio_stream, frames * sizeof(float)); - return; - } - for (size_t c = 0; c < frames; c++){ - fft_input[c] = (audio_stream[2*c + 0] + audio_stream[2*c + 1]) * 0.5f; - } -} -void AudioFloatToFFT::run_fft(){ - float* ptr = m_fft_input.data(); - size_t remaining = NUM_FFT_SAMPLES; - size_t index = m_start; - while (remaining > 0){ - size_t block = std::min(remaining, m_buffer.size() - index); - memcpy(ptr, &m_buffer[index], block * sizeof(float)); - ptr += block; - remaining -= block; - index += block; - if (index == m_buffer.size()){ - index = 0; - } - } - std::shared_ptr> out = std::make_unique>(NUM_FFT_SAMPLES / 2); - Kernels::AbsFFT::fft_abs(FFT_LENGTH_POWER_OF_TWO, out->data(), m_fft_input.data()); - m_listeners.run_method_unique( - &FFTListener::on_fft, - m_sample_rate, out - ); -} -void AudioFloatToFFT::drop_from_front(size_t frames){ - if (frames >= m_buffered){ - m_buffered = 0; - m_start = 0; - m_end = 0; - return; - } - m_buffered -= frames; - m_start += frames; - while (m_start >= m_buffer.size()){ - m_start -= m_buffer.size(); - } -} - - - - -} +/* FFT Streamer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "Kernels/AbsFFT/Kernels_AbsFFT.h" +#include "CommonFramework/AudioPipeline/AudioConstants.h" +#include "FFTStreamer.h" + +namespace PokemonAutomation{ + + + +std::unique_ptr make_FFT_streamer(AudioChannelFormat format){ + switch (format){ + case AudioChannelFormat::MONO_48000: + return std::make_unique(48000, 1, false); + case AudioChannelFormat::DUAL_44100: + return std::make_unique(44100, 2, true); + case AudioChannelFormat::DUAL_48000: + // Treat mono-96000 as 2-sample frames. + // The FFT will then average each pair to produce 48000Hz. + // The output will push the same stream at the original 4 bytes * 96000Hz. + case AudioChannelFormat::MONO_96000: + case AudioChannelFormat::INTERLEAVE_LR_96000: + case AudioChannelFormat::INTERLEAVE_RL_96000: + return std::make_unique(48000, 2, true); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid AudioFormat: " + std::to_string((size_t)format)); + } +} + + + +void AudioFloatToFFT::add_listener(FFTListener& listener){ + m_listeners.add(listener); +} +void AudioFloatToFFT::remove_listener(FFTListener& listener){ + m_listeners.remove(listener); +} + +AudioFloatToFFT::AudioFloatToFFT( + size_t sample_rate, + size_t samples_per_frame, bool average_pairs +) + : AudioFloatStreamListener(samples_per_frame) + , m_sample_rate(sample_rate) + , m_average(average_pairs) + , m_fft_sample_size(average_pairs ? 2 : 1) + , m_buffer(NUM_FFT_SAMPLES) + , m_buffered(NUM_FFT_SAMPLES) + , m_fft_input(NUM_FFT_SAMPLES) +{ + if (samples_per_frame == 0 || samples_per_frame > 2){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Channels must be 1 or 2."); + } + memset(m_buffer.data(), 0, m_buffer.size() * sizeof(float)); +} +AudioFloatToFFT::~AudioFloatToFFT(){} +void AudioFloatToFFT::on_samples(const float* data, size_t frames){ +// cout << "objects = " << objects << endl; + const float* ptr = data; + while (frames > 0){ + // Figure out how much space we can write contiguously. + size_t block = m_buffer.size() - std::max(m_buffered, m_end); + + // Don't write more than we have. + block = std::min(block, frames); + +// cout << "block = " << block << endl; + + // Write it. + convert(&m_buffer[m_end], ptr, block); + m_buffered += block; + m_end += block; + if (m_end == m_buffer.size()){ + m_end = 0; + } + ptr += block * m_fft_sample_size; + frames -= block; + + // Buffer is full. Time to run FFT! + if (m_buffered == m_buffer.size()){ +// cout << "run_fft()" << endl; + run_fft(); + drop_from_front(FFT_SLIDING_WINDOW_STEP); + } + } +} +void AudioFloatToFFT::convert(float* fft_input, const float* audio_stream, size_t frames){ + if (!m_average){ + memcpy(fft_input, audio_stream, frames * sizeof(float)); + return; + } + for (size_t c = 0; c < frames; c++){ + fft_input[c] = (audio_stream[2*c + 0] + audio_stream[2*c + 1]) * 0.5f; + } +} +void AudioFloatToFFT::run_fft(){ + float* ptr = m_fft_input.data(); + size_t remaining = NUM_FFT_SAMPLES; + size_t index = m_start; + while (remaining > 0){ + size_t block = std::min(remaining, m_buffer.size() - index); + memcpy(ptr, &m_buffer[index], block * sizeof(float)); + ptr += block; + remaining -= block; + index += block; + if (index == m_buffer.size()){ + index = 0; + } + } + std::shared_ptr> out = std::make_unique>(NUM_FFT_SAMPLES / 2); + Kernels::AbsFFT::fft_abs(FFT_LENGTH_POWER_OF_TWO, out->data(), m_fft_input.data()); + m_listeners.run_method_unique( + &FFTListener::on_fft, + m_sample_rate, out + ); +} +void AudioFloatToFFT::drop_from_front(size_t frames){ + if (frames >= m_buffered){ + m_buffered = 0; + m_start = 0; + m_end = 0; + return; + } + m_buffered -= frames; + m_start += frames; + while (m_start >= m_buffer.size()){ + m_start -= m_buffer.size(); + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h index 899e076a22..0c111f2d0f 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/FFTStreamer.h @@ -1,66 +1,66 @@ -/* FFT Streamer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_FFTStreamer_H -#define PokemonAutomation_AudioPipeline_FFTStreamer_H - -#include -#include "Common/Cpp/ListenerSet.h" -#include "CommonFramework/AudioPipeline/AudioStream.h" - -namespace PokemonAutomation{ - - - -struct FFTListener{ - virtual void on_fft(size_t sample_rate, std::shared_ptr> fft_output) = 0; -}; - - - -// Listen to an audio stream and compute FFTs on it. -class AudioFloatToFFT : public AudioFloatStreamListener{ -public: - void add_listener(FFTListener& listener); - void remove_listener(FFTListener& listener); - -public: - AudioFloatToFFT( - size_t sample_rate, - size_t samples_per_frame, bool average_pairs - ); - virtual ~AudioFloatToFFT(); - virtual void on_samples(const float* data, size_t frames) override; - -private: - void convert(float* fft_input, const float* audio_stream, size_t frames); - void run_fft(); - void drop_from_front(size_t frames); - -private: - size_t m_sample_rate; - - bool m_average; - size_t m_fft_sample_size; - - AlignedVector m_buffer; - size_t m_buffered = 0; - size_t m_start = 0; - size_t m_end = 0; - - AlignedVector m_fft_input; - - ListenerSet m_listeners; -}; - - -std::unique_ptr make_FFT_streamer(AudioChannelFormat format); - - - - -} -#endif +/* FFT Streamer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_FFTStreamer_H +#define PokemonAutomation_AudioPipeline_FFTStreamer_H + +#include +#include "Common/Cpp/ListenerSet.h" +#include "CommonFramework/AudioPipeline/AudioStream.h" + +namespace PokemonAutomation{ + + + +struct FFTListener{ + virtual void on_fft(size_t sample_rate, std::shared_ptr> fft_output) = 0; +}; + + + +// Listen to an audio stream and compute FFTs on it. +class AudioFloatToFFT : public AudioFloatStreamListener{ +public: + void add_listener(FFTListener& listener); + void remove_listener(FFTListener& listener); + +public: + AudioFloatToFFT( + size_t sample_rate, + size_t samples_per_frame, bool average_pairs + ); + virtual ~AudioFloatToFFT(); + virtual void on_samples(const float* data, size_t frames) override; + +private: + void convert(float* fft_input, const float* audio_stream, size_t frames); + void run_fft(); + void drop_from_front(size_t frames); + +private: + size_t m_sample_rate; + + bool m_average; + size_t m_fft_sample_size; + + AlignedVector m_buffer; + size_t m_buffered = 0; + size_t m_start = 0; + size_t m_end = 0; + + AlignedVector m_fft_input; + + ListenerSet m_listeners; +}; + + +std::unique_ptr make_FFT_streamer(AudioChannelFormat format); + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.cpp index e5fe0dfbe1..3349f110ea 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.cpp @@ -1,62 +1,62 @@ -/* Audio Device Info - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "Spectrograph.h" - -namespace PokemonAutomation{ - - -Spectrograph::~Spectrograph(){} -Spectrograph::Spectrograph(size_t buckets, size_t frames) - : m_buckets(buckets) - , m_frames(frames) - , m_current_index(0) - , m_buffer(buckets * frames) -{ - memset(m_buffer.data(), 0, m_buffer.size() * sizeof(uint32_t)); -} - -void Spectrograph::clear(){ - memset(m_buffer.data(), 0, m_buffer.size() * sizeof(uint32_t)); -} - -void Spectrograph::push_spectrum(const uint32_t* spectrum){ - uint32_t* ptr = m_buffer.data() + m_current_index; - for (size_t c = 0; c < m_buckets; c++){ - ptr[0] = spectrum[c]; - ptr += m_frames; - } - m_current_index++; - if (m_current_index >= m_frames){ - m_current_index = 0; - } -} -ImageRGB32 Spectrograph::to_image() const{ - ImageRGB32 image(m_frames, m_buckets); - size_t bytes_per_line = image.bytes_per_row(); - uint32_t* dst = image.data(); - const uint32_t* src = m_buffer.data(); - - size_t frames = m_frames; - size_t front = m_current_index; - size_t back = frames - front; - for (size_t c = 0; c < m_buckets; c++){ - memcpy(dst, src + front, back * sizeof(uint32_t)); - memcpy(dst + back, src, front * sizeof(uint32_t)); - src += frames; - dst = (uint32_t*)((char*)dst + bytes_per_line); - } - - return image; -} - - - - - -} +/* Audio Device Info + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Spectrograph.h" + +namespace PokemonAutomation{ + + +Spectrograph::~Spectrograph(){} +Spectrograph::Spectrograph(size_t buckets, size_t frames) + : m_buckets(buckets) + , m_frames(frames) + , m_current_index(0) + , m_buffer(buckets * frames) +{ + memset(m_buffer.data(), 0, m_buffer.size() * sizeof(uint32_t)); +} + +void Spectrograph::clear(){ + memset(m_buffer.data(), 0, m_buffer.size() * sizeof(uint32_t)); +} + +void Spectrograph::push_spectrum(const uint32_t* spectrum){ + uint32_t* ptr = m_buffer.data() + m_current_index; + for (size_t c = 0; c < m_buckets; c++){ + ptr[0] = spectrum[c]; + ptr += m_frames; + } + m_current_index++; + if (m_current_index >= m_frames){ + m_current_index = 0; + } +} +ImageRGB32 Spectrograph::to_image() const{ + ImageRGB32 image(m_frames, m_buckets); + size_t bytes_per_line = image.bytes_per_row(); + uint32_t* dst = image.data(); + const uint32_t* src = m_buffer.data(); + + size_t frames = m_frames; + size_t front = m_current_index; + size_t back = frames - front; + for (size_t c = 0; c < m_buckets; c++){ + memcpy(dst, src + front, back * sizeof(uint32_t)); + memcpy(dst + back, src, front * sizeof(uint32_t)); + src += frames; + dst = (uint32_t*)((char*)dst + bytes_per_line); + } + + return image; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.h index 6022c08919..9fb3a8b9a4 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Spectrum/Spectrograph.h @@ -1,42 +1,42 @@ -/* Audio Device Info - * - * From: https://github.com/PokemonAutomation/ - * - * Holds a history of the most recent FFT spectrums as colors. - * This is used to render the spectrograph. - * - */ - -#ifndef PokemonAutomation_AudioPipeline_Spectrograph_H -#define PokemonAutomation_AudioPipeline_Spectrograph_H - -#include -#include "Common/Cpp/Containers/AlignedVector.h" - -namespace PokemonAutomation{ - -class ImageRGB32; - - -class Spectrograph{ -public: - Spectrograph(size_t buckets_per_spectrum, size_t frames); - ~Spectrograph(); - - void clear(); - - void push_spectrum(const uint32_t* spectrum); - - ImageRGB32 to_image() const; - - -private: - size_t m_buckets; - size_t m_frames; - size_t m_current_index; - AlignedVector m_buffer; -}; - - -} -#endif +/* Audio Device Info + * + * From: https://github.com/PokemonAutomation/ + * + * Holds a history of the most recent FFT spectrums as colors. + * This is used to render the spectrograph. + * + */ + +#ifndef PokemonAutomation_AudioPipeline_Spectrograph_H +#define PokemonAutomation_AudioPipeline_Spectrograph_H + +#include +#include "Common/Cpp/Containers/AlignedVector.h" + +namespace PokemonAutomation{ + +class ImageRGB32; + + +class Spectrograph{ +public: + Spectrograph(size_t buckets_per_spectrum, size_t frames); + ~Spectrograph(); + + void clear(); + + void push_spectrum(const uint32_t* spectrum); + + ImageRGB32 to_image() const; + + +private: + size_t m_buckets; + size_t m_frames; + size_t m_current_index; + AlignedVector m_buffer; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.cpp index e7bfdda5db..44482c672b 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.cpp @@ -1,191 +1,191 @@ -/* Audio format Utils - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "AudioFormatUtils.h" -#include "AudioNormalization.h" - - - -namespace PokemonAutomation{ - -#if QT_VERSION_MAJOR == 5 - -std::string dumpAudioFormat(const QAudioFormat& format){ - std::ostringstream ss; - ss << "Audio format: sample type "; - switch(format.sampleType()){ - case QAudioFormat::SampleType::Float: - ss << "Float"; - break; - case QAudioFormat::SampleType::SignedInt: - ss << "SignedInt"; - break; - case QAudioFormat::SampleType::UnSignedInt: - ss << "UnSignedInt"; - break; - default: - ss << "Error"; - } - - ss << - ", bytes per sample " << format.bytesPerFrame() / format.channelCount() << - ", num channels " << format.channelCount() << - ", sample rate " << format.sampleRate() << - ", codec " << format.codec().toStdString() << std::endl; - - return ss.str(); -} - -void setSampleFormatToFloat(QAudioFormat& format){ - format.setSampleType(QAudioFormat::SampleType::Float); - format.setSampleSize(32); -} - -template -void normalize_type(const QAudioFormat& format, const char* data, size_t len, float* out){ - if (format.byteOrder() == QAudioFormat::Endian::LittleEndian){ - normalize_audio_le(out, reinterpret_cast(data), len/sizeof(Type)); - }else{ - normalize_audio_be(out, reinterpret_cast(data), len/sizeof(Type)); - } -} - -void convertSamplesToFloat(const QAudioFormat& format, const char* data, size_t len, float* out){ - - switch(format.sampleType()){ - case QAudioFormat::SampleType::Float: - if (format.sampleSize() == sizeof(float)*8){ - memcpy(out, data, len); - return; - } - break; - case QAudioFormat::SampleType::SignedInt: - switch(format.sampleSize()){ - case 8: - normalize_type(format, data, len, out); - return; - case 16: - normalize_type(format, data, len, out); - return; - case 32: - normalize_type(format, data, len, out); - return; - default: - break; - } - break; - case QAudioFormat::SampleType::UnSignedInt: - switch(format.sampleSize()){ - case 8: - normalize_type(format, data, len, out); - return; - case 16: - normalize_type(format, data, len, out); - return; - case 32: - normalize_type(format, data, len, out); - return; - default: - break; - } - break; - default: - break; - } - std::cout << "Error: Unkwnon sample format in convertSamplesToFloat(): "; - dumpAudioFormat(format); -} - -#elif QT_VERSION_MAJOR == 6 - -std::string dumpAudioFormat(const QAudioFormat& format){ - std::string sampleFormatStr = ""; - switch(format.sampleFormat()){ - case QAudioFormat::SampleFormat::Float: - sampleFormatStr="Float"; - break; - case QAudioFormat::SampleFormat::Int16: - sampleFormatStr="Int16"; - break; - case QAudioFormat::SampleFormat::Int32: - sampleFormatStr="Int32"; - break; - case QAudioFormat::SampleFormat::UInt8: - sampleFormatStr="UInt8"; - break; - default: - sampleFormatStr="Error"; - } - - std::string channelConfigStr = ""; - switch(format.channelConfig()){ - case QAudioFormat::ChannelConfig::ChannelConfigMono: - channelConfigStr = "Mono"; - break; - case QAudioFormat::ChannelConfig::ChannelConfigStereo: - channelConfigStr = "Stereo"; - break; - case QAudioFormat::ChannelConfig::ChannelConfigUnknown: - channelConfigStr = "Unknown"; - break; - default: - channelConfigStr = "Non Mono or Stereo"; - } - std::ostringstream ss; - ss << "sample format " << sampleFormatStr << - ", bytes per sample " << format.bytesPerSample() << - ", channel config " << channelConfigStr << - ", num channels " << format.channelCount() << - ", sample rate " << format.sampleRate() << std::endl; - return ss.str(); -} - -void setSampleFormatToFloat(QAudioFormat& format){ - format.setSampleFormat(QAudioFormat::SampleFormat::Float); -} - -void convertSamplesToFloat(const QAudioFormat& format, const char* data, size_t len, float* out){ - switch(format.sampleFormat()){ - case QAudioFormat::SampleFormat::Float: - memcpy(out, data, len); - break; - case QAudioFormat::SampleFormat::Int16: - normalize_audio_le(out, reinterpret_cast(data), len/sizeof(int16_t)); - break; - case QAudioFormat::SampleFormat::Int32: - normalize_audio_le(out, reinterpret_cast(data), len/sizeof(int32_t)); - break; - case QAudioFormat::SampleFormat::UInt8: - normalize_audio_le(out, reinterpret_cast(data), len/sizeof(uint8_t)); - break; - default: - std::cout << "Error: Unkwnon sample format in convertSamplesToFloat()" << std::endl; - } -} - -#endif - - -float audioSampleSum(const QAudioFormat& format, const char* data, size_t len){ - const size_t frameBytes = format.bytesPerFrame(); - const size_t numChannels = format.channelCount(); - const size_t sampleBytes = frameBytes / numChannels; - const size_t numSamples = len / sampleBytes; - std::vector buffer(numSamples); - convertSamplesToFloat(format, data, len, buffer.data()); - - float sum = 0.0f; - for(float v: buffer){ - sum += v; - } - return sum; -} - - -} +/* Audio format Utils + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "AudioFormatUtils.h" +#include "AudioNormalization.h" + + + +namespace PokemonAutomation{ + +#if QT_VERSION_MAJOR == 5 + +std::string dumpAudioFormat(const QAudioFormat& format){ + std::ostringstream ss; + ss << "Audio format: sample type "; + switch(format.sampleType()){ + case QAudioFormat::SampleType::Float: + ss << "Float"; + break; + case QAudioFormat::SampleType::SignedInt: + ss << "SignedInt"; + break; + case QAudioFormat::SampleType::UnSignedInt: + ss << "UnSignedInt"; + break; + default: + ss << "Error"; + } + + ss << + ", bytes per sample " << format.bytesPerFrame() / format.channelCount() << + ", num channels " << format.channelCount() << + ", sample rate " << format.sampleRate() << + ", codec " << format.codec().toStdString() << std::endl; + + return ss.str(); +} + +void setSampleFormatToFloat(QAudioFormat& format){ + format.setSampleType(QAudioFormat::SampleType::Float); + format.setSampleSize(32); +} + +template +void normalize_type(const QAudioFormat& format, const char* data, size_t len, float* out){ + if (format.byteOrder() == QAudioFormat::Endian::LittleEndian){ + normalize_audio_le(out, reinterpret_cast(data), len/sizeof(Type)); + }else{ + normalize_audio_be(out, reinterpret_cast(data), len/sizeof(Type)); + } +} + +void convertSamplesToFloat(const QAudioFormat& format, const char* data, size_t len, float* out){ + + switch(format.sampleType()){ + case QAudioFormat::SampleType::Float: + if (format.sampleSize() == sizeof(float)*8){ + memcpy(out, data, len); + return; + } + break; + case QAudioFormat::SampleType::SignedInt: + switch(format.sampleSize()){ + case 8: + normalize_type(format, data, len, out); + return; + case 16: + normalize_type(format, data, len, out); + return; + case 32: + normalize_type(format, data, len, out); + return; + default: + break; + } + break; + case QAudioFormat::SampleType::UnSignedInt: + switch(format.sampleSize()){ + case 8: + normalize_type(format, data, len, out); + return; + case 16: + normalize_type(format, data, len, out); + return; + case 32: + normalize_type(format, data, len, out); + return; + default: + break; + } + break; + default: + break; + } + std::cout << "Error: Unkwnon sample format in convertSamplesToFloat(): "; + dumpAudioFormat(format); +} + +#elif QT_VERSION_MAJOR == 6 + +std::string dumpAudioFormat(const QAudioFormat& format){ + std::string sampleFormatStr = ""; + switch(format.sampleFormat()){ + case QAudioFormat::SampleFormat::Float: + sampleFormatStr="Float"; + break; + case QAudioFormat::SampleFormat::Int16: + sampleFormatStr="Int16"; + break; + case QAudioFormat::SampleFormat::Int32: + sampleFormatStr="Int32"; + break; + case QAudioFormat::SampleFormat::UInt8: + sampleFormatStr="UInt8"; + break; + default: + sampleFormatStr="Error"; + } + + std::string channelConfigStr = ""; + switch(format.channelConfig()){ + case QAudioFormat::ChannelConfig::ChannelConfigMono: + channelConfigStr = "Mono"; + break; + case QAudioFormat::ChannelConfig::ChannelConfigStereo: + channelConfigStr = "Stereo"; + break; + case QAudioFormat::ChannelConfig::ChannelConfigUnknown: + channelConfigStr = "Unknown"; + break; + default: + channelConfigStr = "Non Mono or Stereo"; + } + std::ostringstream ss; + ss << "sample format " << sampleFormatStr << + ", bytes per sample " << format.bytesPerSample() << + ", channel config " << channelConfigStr << + ", num channels " << format.channelCount() << + ", sample rate " << format.sampleRate() << std::endl; + return ss.str(); +} + +void setSampleFormatToFloat(QAudioFormat& format){ + format.setSampleFormat(QAudioFormat::SampleFormat::Float); +} + +void convertSamplesToFloat(const QAudioFormat& format, const char* data, size_t len, float* out){ + switch(format.sampleFormat()){ + case QAudioFormat::SampleFormat::Float: + memcpy(out, data, len); + break; + case QAudioFormat::SampleFormat::Int16: + normalize_audio_le(out, reinterpret_cast(data), len/sizeof(int16_t)); + break; + case QAudioFormat::SampleFormat::Int32: + normalize_audio_le(out, reinterpret_cast(data), len/sizeof(int32_t)); + break; + case QAudioFormat::SampleFormat::UInt8: + normalize_audio_le(out, reinterpret_cast(data), len/sizeof(uint8_t)); + break; + default: + std::cout << "Error: Unkwnon sample format in convertSamplesToFloat()" << std::endl; + } +} + +#endif + + +float audioSampleSum(const QAudioFormat& format, const char* data, size_t len){ + const size_t frameBytes = format.bytesPerFrame(); + const size_t numChannels = format.channelCount(); + const size_t sampleBytes = frameBytes / numChannels; + const size_t numSamples = len / sampleBytes; + std::vector buffer(numSamples); + convertSamplesToFloat(format, data, len, buffer.data()); + + float sum = 0.0f; + for(float v: buffer){ + sum += v; + } + return sum; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h index ad27993881..48dbea18a8 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioFormatUtils.h @@ -1,29 +1,29 @@ -/* Audio format Utils - * - * From: https://github.com/PokemonAutomation/ - * - * Host various util functions for audio format related tasks. - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioFormatUtils_H -#define PokemonAutomation_AudioPipeline_AudioFormatUtils_H - -#include - -class QAudioFormat; - -namespace PokemonAutomation{ - -std::string dumpAudioFormat(const QAudioFormat& format); - -void setSampleFormatToFloat(QAudioFormat& format); - -void convertSamplesToFloat(const QAudioFormat& format, const char* data, size_t len, float* out); - -// Compute sum of the sample buffer. -// Used to debug whether the audio stream is always the same values or always zeros. -float audioSampleSum(const QAudioFormat& format, const char* data, size_t len); - -} - -#endif +/* Audio format Utils + * + * From: https://github.com/PokemonAutomation/ + * + * Host various util functions for audio format related tasks. + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioFormatUtils_H +#define PokemonAutomation_AudioPipeline_AudioFormatUtils_H + +#include + +class QAudioFormat; + +namespace PokemonAutomation{ + +std::string dumpAudioFormat(const QAudioFormat& format); + +void setSampleFormatToFloat(QAudioFormat& format); + +void convertSamplesToFloat(const QAudioFormat& format, const char* data, size_t len, float* out); + +// Compute sum of the sample buffer. +// Used to debug whether the audio stream is always the same values or always zeros. +float audioSampleSum(const QAudioFormat& format, const char* data, size_t len); + +} + +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioNormalization.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioNormalization.h index 8a4a16a250..ce97bf6d71 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioNormalization.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/AudioNormalization.h @@ -1,86 +1,86 @@ -/* Audio Normalization - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_AudioPipeline_AudioNormalization_H -#define PokemonAutomation_CommonFramework_AudioPipeline_AudioNormalization_H - -#include -#include -#include -#include "Common/Compiler.h" - -#if _WIN32 -#include -#endif - -namespace PokemonAutomation{ - - -PA_FORCE_INLINE uint8_t byte_swap(uint8_t x){ - return x; -} -PA_FORCE_INLINE int8_t byte_swap(int8_t x){ - return x; -} -PA_FORCE_INLINE uint16_t byte_swap(uint16_t x){ -#if _WIN32 - return (uint32_t)_byteswap_ulong(x) >> 16; -#elif __GNUC__ - return (uint32_t)__builtin_bswap32(x) >> 16; -#else -#error "No bswap() intrinsic for this compiler." -#endif -} -PA_FORCE_INLINE int16_t byte_swap(int16_t x){ -#if _WIN32 - return (int16_t)((uint32_t)_byteswap_ulong(x) >> 16); -#elif __GNUC__ - return (int16_t)((uint32_t)__builtin_bswap32(x) >> 16); -#else -#error "No bswap() intrinsic for this compiler." -#endif -} -PA_FORCE_INLINE uint32_t byte_swap(uint32_t x){ -#if _WIN32 - return _byteswap_ulong(x); -#elif __GNUC__ - return __builtin_bswap32(x); -#else -#error "No bswap() intrinsic for this compiler." -#endif -} -PA_FORCE_INLINE int16_t byte_swap(int32_t x){ -#if _WIN32 - return (int16_t)_byteswap_ulong(x); -#elif __GNUC__ - return __builtin_bswap32(x); -#else -#error "No bswap() intrinsic for this compiler." -#endif -} - - -template -void normalize_audio_le(float* out, const Type* in, size_t count){ - const float rcp = (std::is_unsigned::value ? 2.0f : 1.0f) / (float)std::numeric_limits::max(); - const float sub = std::is_unsigned::value ? 1.0f : 0.0f; - for (size_t c = 0; c < count; c++){ - out[c] = (float)in[c] * rcp - sub; - } -} - -template -void normalize_audio_be(float* out, const Type* in, size_t count){ - const float rcp = (std::is_unsigned::value ? 2.0f : 1.0f) / (float)std::numeric_limits::max(); - const float sub = std::is_unsigned::value ? 1.0f : 0.0f; - for (size_t c = 0; c < count; c++){ - out[c] = (float)byte_swap(in[c]) * rcp - sub; - } -} - - -} -#endif +/* Audio Normalization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_AudioPipeline_AudioNormalization_H +#define PokemonAutomation_CommonFramework_AudioPipeline_AudioNormalization_H + +#include +#include +#include +#include "Common/Compiler.h" + +#if _WIN32 +#include +#endif + +namespace PokemonAutomation{ + + +PA_FORCE_INLINE uint8_t byte_swap(uint8_t x){ + return x; +} +PA_FORCE_INLINE int8_t byte_swap(int8_t x){ + return x; +} +PA_FORCE_INLINE uint16_t byte_swap(uint16_t x){ +#if _WIN32 + return (uint32_t)_byteswap_ulong(x) >> 16; +#elif __GNUC__ + return (uint32_t)__builtin_bswap32(x) >> 16; +#else +#error "No bswap() intrinsic for this compiler." +#endif +} +PA_FORCE_INLINE int16_t byte_swap(int16_t x){ +#if _WIN32 + return (int16_t)((uint32_t)_byteswap_ulong(x) >> 16); +#elif __GNUC__ + return (int16_t)((uint32_t)__builtin_bswap32(x) >> 16); +#else +#error "No bswap() intrinsic for this compiler." +#endif +} +PA_FORCE_INLINE uint32_t byte_swap(uint32_t x){ +#if _WIN32 + return _byteswap_ulong(x); +#elif __GNUC__ + return __builtin_bswap32(x); +#else +#error "No bswap() intrinsic for this compiler." +#endif +} +PA_FORCE_INLINE int16_t byte_swap(int32_t x){ +#if _WIN32 + return (int16_t)_byteswap_ulong(x); +#elif __GNUC__ + return __builtin_bswap32(x); +#else +#error "No bswap() intrinsic for this compiler." +#endif +} + + +template +void normalize_audio_le(float* out, const Type* in, size_t count){ + const float rcp = (std::is_unsigned::value ? 2.0f : 1.0f) / (float)std::numeric_limits::max(); + const float sub = std::is_unsigned::value ? 1.0f : 0.0f; + for (size_t c = 0; c < count; c++){ + out[c] = (float)in[c] * rcp - sub; + } +} + +template +void normalize_audio_be(float* out, const Type* in, size_t count){ + const float rcp = (std::is_unsigned::value ? 2.0f : 1.0f) / (float)std::numeric_limits::max(); + const float sub = std::is_unsigned::value ? 1.0f : 0.0f; + for (size_t c = 0; c < count; c++){ + out[c] = (float)byte_swap(in[c]) * rcp - sub; + } +} + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.cpp index 9750bd07ab..5c2b18c507 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.cpp @@ -1,184 +1,184 @@ -/* Time Sample Buffer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_TPP -#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_TPP - -#include "Common/Cpp/Exceptions.h" -#include "TimeSampleWriter.h" -#include "TimeSampleBuffer.h" - -namespace PokemonAutomation{ - - -template -TimeSampleBuffer::TimeSampleBuffer( - size_t samples_per_second, - Duration history, - Duration gap_threshold -) - : m_samples_per_second(samples_per_second) - , m_sample_period(Duration(std::chrono::seconds(1)) / samples_per_second) - , m_samples_to_buffer(samples_per_second * std::chrono::duration_cast(history).count() / 1000) - , m_duration_gap_threshold(gap_threshold) - , m_sample_gap_threshold(samples_per_second * std::chrono::duration_cast(gap_threshold).count() / 1000) - , m_samples_stored(0) -{ - if (gap_threshold < m_sample_period){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Gap threshold cannot be smaller than sample period."); - } -} - -template -void TimeSampleBuffer::push_samples( - const Type* samples, size_t count, - WallClock timestamp -){ - std::vector block(count); - memcpy(block.data(), samples, count * sizeof(Type)); - - WriteSpinLock lg(m_lock); - -#if 0 - auto iter = m_samples.find(timestamp); - if (iter != m_samples.end()){ - timestamp++; - } -#endif - - m_samples[timestamp] = std::move(block); - m_samples_stored += count; - - // Drop samples that are too old. - while (!m_samples.empty()){ - auto iter = m_samples.begin(); - size_t samples_to_drop = iter->second.size(); - if (m_samples_stored < m_samples_to_buffer + samples_to_drop){ - break; - } - m_samples.erase(iter); - m_samples_stored -= samples_to_drop; - } -} - -template -std::string TimeSampleBuffer::dump() const{ - ReadSpinLock lg(m_lock); - - std::string str; - if (m_samples.empty()){ - str += "(buffer is empty)"; - return str; - } - auto iter = m_samples.rbegin(); - WallClock latest = iter->first; - for (; iter != m_samples.rend(); ++iter){ - Duration last = iter->first - latest; - Duration first = last - m_sample_period * iter->second.size(); - str += std::to_string(std::chrono::duration_cast(last).count() / 1000.); - str += " - "; - str += std::to_string(std::chrono::duration_cast(first).count() / 1000.); - str += " : "; - str += std::to_string(iter->second.size()); - str += "\n"; - } - return str; -} - - -template -void TimeSampleBuffer::read_samples( - Type* samples, size_t count, - WallClock timestamp -) const{ - ReadSpinLock lg(m_lock); - - if (m_samples.empty()){ - memset(samples, 0, count * sizeof(Type)); - return; - } - - // Setup output state. - WallClock requested_time = timestamp; - TimeSampleWriterReverse output_buffer(samples, count); - - // Jump to the latest block that's relevant to this request. -// cout << requested - reference << endl; -// cout << timestamp - reference << endl; - auto current_block = m_samples.lower_bound(requested_time); - if (current_block == m_samples.end()){ -// cout << "front gap" << endl; - --current_block; - } - - // Setup input state. - WallClock current_time = current_block->first; - size_t current_index = current_block->second.size(); - - // State machine loop. Look at the current input and output states to - // decide on the next action. Stop when output is filled or we run out of - // blocks. - while (output_buffer.samples_left() > 0){ -// cout << "Requested: " << requested_time - reference << endl; -// cout << "Buffer : " << current_time - reference << endl; - - // Current block is empty. Move to previous block. - if (current_index == 0){ - if (current_block == m_samples.begin()){ - output_buffer.fill_rest_with_zeros(); - return; - } - --current_block; - current_time = current_block->first; - current_index = current_block->second.size(); - } - - Duration output_ahead = requested_time - current_time; - - // Requested is far ahead of what's next. Fill the gap with zeros. - if (output_ahead > m_duration_gap_threshold){ -// cout << "Output Ahead" << endl; - size_t block = output_ahead.count() / m_sample_period.count(); - output_buffer.push_zeros(block); - requested_time -= block * m_sample_period; - continue; - } - - Duration input_ahead = current_time - requested_time; - - // Requested is far behind what's next. Skip ahead. - if (input_ahead > m_duration_gap_threshold){ -// cout << "Input Ahead" << endl; - size_t block = input_ahead.count() / m_sample_period.count(); - block = std::min(block, current_index); - current_index -= block; - current_time -= block * m_sample_period; - continue; - } - - size_t block = output_buffer.push_block(current_block->second.data(), current_index); -// cout << "Push block: " << block << endl; - Duration block_time = block * m_sample_period; - current_index -= block; - current_time -= block_time; - requested_time -= block_time; - } -} - - - -template class TimeSampleBuffer; -template class TimeSampleBuffer; -template class TimeSampleBuffer; -template class TimeSampleBuffer; -template class TimeSampleBuffer; -template class TimeSampleBuffer; -template class TimeSampleBuffer; - - - -} -#endif +/* Time Sample Buffer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_TPP +#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_TPP + +#include "Common/Cpp/Exceptions.h" +#include "TimeSampleWriter.h" +#include "TimeSampleBuffer.h" + +namespace PokemonAutomation{ + + +template +TimeSampleBuffer::TimeSampleBuffer( + size_t samples_per_second, + Duration history, + Duration gap_threshold +) + : m_samples_per_second(samples_per_second) + , m_sample_period(Duration(std::chrono::seconds(1)) / samples_per_second) + , m_samples_to_buffer(samples_per_second * std::chrono::duration_cast(history).count() / 1000) + , m_duration_gap_threshold(gap_threshold) + , m_sample_gap_threshold(samples_per_second * std::chrono::duration_cast(gap_threshold).count() / 1000) + , m_samples_stored(0) +{ + if (gap_threshold < m_sample_period){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Gap threshold cannot be smaller than sample period."); + } +} + +template +void TimeSampleBuffer::push_samples( + const Type* samples, size_t count, + WallClock timestamp +){ + std::vector block(count); + memcpy(block.data(), samples, count * sizeof(Type)); + + WriteSpinLock lg(m_lock); + +#if 0 + auto iter = m_samples.find(timestamp); + if (iter != m_samples.end()){ + timestamp++; + } +#endif + + m_samples[timestamp] = std::move(block); + m_samples_stored += count; + + // Drop samples that are too old. + while (!m_samples.empty()){ + auto iter = m_samples.begin(); + size_t samples_to_drop = iter->second.size(); + if (m_samples_stored < m_samples_to_buffer + samples_to_drop){ + break; + } + m_samples.erase(iter); + m_samples_stored -= samples_to_drop; + } +} + +template +std::string TimeSampleBuffer::dump() const{ + ReadSpinLock lg(m_lock); + + std::string str; + if (m_samples.empty()){ + str += "(buffer is empty)"; + return str; + } + auto iter = m_samples.rbegin(); + WallClock latest = iter->first; + for (; iter != m_samples.rend(); ++iter){ + Duration last = iter->first - latest; + Duration first = last - m_sample_period * iter->second.size(); + str += std::to_string(std::chrono::duration_cast(last).count() / 1000.); + str += " - "; + str += std::to_string(std::chrono::duration_cast(first).count() / 1000.); + str += " : "; + str += std::to_string(iter->second.size()); + str += "\n"; + } + return str; +} + + +template +void TimeSampleBuffer::read_samples( + Type* samples, size_t count, + WallClock timestamp +) const{ + ReadSpinLock lg(m_lock); + + if (m_samples.empty()){ + memset(samples, 0, count * sizeof(Type)); + return; + } + + // Setup output state. + WallClock requested_time = timestamp; + TimeSampleWriterReverse output_buffer(samples, count); + + // Jump to the latest block that's relevant to this request. +// cout << requested - reference << endl; +// cout << timestamp - reference << endl; + auto current_block = m_samples.lower_bound(requested_time); + if (current_block == m_samples.end()){ +// cout << "front gap" << endl; + --current_block; + } + + // Setup input state. + WallClock current_time = current_block->first; + size_t current_index = current_block->second.size(); + + // State machine loop. Look at the current input and output states to + // decide on the next action. Stop when output is filled or we run out of + // blocks. + while (output_buffer.samples_left() > 0){ +// cout << "Requested: " << requested_time - reference << endl; +// cout << "Buffer : " << current_time - reference << endl; + + // Current block is empty. Move to previous block. + if (current_index == 0){ + if (current_block == m_samples.begin()){ + output_buffer.fill_rest_with_zeros(); + return; + } + --current_block; + current_time = current_block->first; + current_index = current_block->second.size(); + } + + Duration output_ahead = requested_time - current_time; + + // Requested is far ahead of what's next. Fill the gap with zeros. + if (output_ahead > m_duration_gap_threshold){ +// cout << "Output Ahead" << endl; + size_t block = output_ahead.count() / m_sample_period.count(); + output_buffer.push_zeros(block); + requested_time -= block * m_sample_period; + continue; + } + + Duration input_ahead = current_time - requested_time; + + // Requested is far behind what's next. Skip ahead. + if (input_ahead > m_duration_gap_threshold){ +// cout << "Input Ahead" << endl; + size_t block = input_ahead.count() / m_sample_period.count(); + block = std::min(block, current_index); + current_index -= block; + current_time -= block * m_sample_period; + continue; + } + + size_t block = output_buffer.push_block(current_block->second.data(), current_index); +// cout << "Push block: " << block << endl; + Duration block_time = block * m_sample_period; + current_index -= block; + current_time -= block_time; + requested_time -= block_time; + } +} + + + +template class TimeSampleBuffer; +template class TimeSampleBuffer; +template class TimeSampleBuffer; +template class TimeSampleBuffer; +template class TimeSampleBuffer; +template class TimeSampleBuffer; +template class TimeSampleBuffer; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.h index a453dd77b8..1d6c082565 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBuffer.h @@ -1,94 +1,94 @@ -/* Time Sample Buffer - * - * From: https://github.com/PokemonAutomation/ - * - * - * This is a buffer for raw audio samples taken from an audio input. - * - * It will store at least "history" worth of samples before dropping old data. - * - * This class isn't just a trivial circular buffer. It allows random write - * and random read access. Reads will intelligently try to construct a - * contiguous audio stream. If it can't, it will insert zeros or drop samples - * where appropriate to correct it. - * - * This class in effect, is fault-tolerant to interruptions by both the writer - * and reader(s). Gaps or delays will self-correct to avoid a situation where - * the reader(s) perpetually fall behind or get ahead of the writers. Drifts - * where the writer/reader(s) are of slightly different speeds will also be - * corrected. - * - * - * Both read and write access to the buffer is done by blocks with a timestamp - * indicating the approximate time of the latest sample in the block. - * - * If you need to read data contiguously, you need to use TimeSampleBufferReader - * to read it as it will ensure that the samples are contiguous across - * successive read calls. - * - */ - -#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_H -#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - - -template -class TimeSampleBufferReader; - - -template -class TimeSampleBuffer{ - using Duration = std::chrono::system_clock::duration; - -public: - TimeSampleBuffer( - size_t samples_per_second, - Duration history, - Duration gap_threshold = std::chrono::milliseconds(100) - ); - - // Write "count" samples ending on "timestamp". - void push_samples( - const Type* samples, size_t count, - WallClock timestamp = current_time() - ); - - // Read "count" samples ending on "timestamp". - void read_samples( - Type* samples, size_t count, - WallClock timestamp = current_time() - ) const; - - std::string dump() const; - -private: - friend class TimeSampleBufferReader; - using MapType = std::map>; - - const size_t m_samples_per_second; - const Duration m_sample_period; // Time between adjacent samples. - - // Minimum # of samples to keep. - const size_t m_samples_to_buffer; - - // # of samples in a gap or an overlap before we can no longer stretch. - const Duration m_duration_gap_threshold; - const size_t m_sample_gap_threshold; - - mutable SpinLock m_lock; - MapType m_samples; - size_t m_samples_stored; -}; - - - -} -#endif +/* Time Sample Buffer + * + * From: https://github.com/PokemonAutomation/ + * + * + * This is a buffer for raw audio samples taken from an audio input. + * + * It will store at least "history" worth of samples before dropping old data. + * + * This class isn't just a trivial circular buffer. It allows random write + * and random read access. Reads will intelligently try to construct a + * contiguous audio stream. If it can't, it will insert zeros or drop samples + * where appropriate to correct it. + * + * This class in effect, is fault-tolerant to interruptions by both the writer + * and reader(s). Gaps or delays will self-correct to avoid a situation where + * the reader(s) perpetually fall behind or get ahead of the writers. Drifts + * where the writer/reader(s) are of slightly different speeds will also be + * corrected. + * + * + * Both read and write access to the buffer is done by blocks with a timestamp + * indicating the approximate time of the latest sample in the block. + * + * If you need to read data contiguously, you need to use TimeSampleBufferReader + * to read it as it will ensure that the samples are contiguous across + * successive read calls. + * + */ + +#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_H +#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBuffer_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + + +template +class TimeSampleBufferReader; + + +template +class TimeSampleBuffer{ + using Duration = std::chrono::system_clock::duration; + +public: + TimeSampleBuffer( + size_t samples_per_second, + Duration history, + Duration gap_threshold = std::chrono::milliseconds(100) + ); + + // Write "count" samples ending on "timestamp". + void push_samples( + const Type* samples, size_t count, + WallClock timestamp = current_time() + ); + + // Read "count" samples ending on "timestamp". + void read_samples( + Type* samples, size_t count, + WallClock timestamp = current_time() + ) const; + + std::string dump() const; + +private: + friend class TimeSampleBufferReader; + using MapType = std::map>; + + const size_t m_samples_per_second; + const Duration m_sample_period; // Time between adjacent samples. + + // Minimum # of samples to keep. + const size_t m_samples_to_buffer; + + // # of samples in a gap or an overlap before we can no longer stretch. + const Duration m_duration_gap_threshold; + const size_t m_sample_gap_threshold; + + mutable SpinLock m_lock; + MapType m_samples; + size_t m_samples_stored; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.cpp index 3c094c5f20..0934ca4c49 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.cpp @@ -1,180 +1,180 @@ -/* Time Sample Buffer Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "TimeSampleWriter.h" -#include "TimeSampleBufferReader.h" - -namespace PokemonAutomation{ - - - -template -TimeSampleBufferReader::TimeSampleBufferReader(TimeSampleBuffer& buffer) - : m_buffer(buffer) -// , m_last_timestamp(TimePoint::min()) - , m_current_block(WallClock::min()) - , m_current_index(0) -{} - -template -void TimeSampleBufferReader::set_to_timestamp(WallClock timestamp){ - WriteSpinLock lg(m_buffer.m_lock); - set_to_timestamp_unprotected(timestamp); -} - -template -void TimeSampleBufferReader::set_to_timestamp_unprotected(WallClock timestamp){ - m_current_block = WallClock::min(); - m_current_index = 0; - - const typename TimeSampleBuffer::MapType& buffer = m_buffer.m_samples; - if (buffer.empty()){ - return; - } - - auto current_block = buffer.upper_bound(timestamp); - if (current_block == buffer.end()){ -// cout << "front gap" << endl; - --current_block; - } - - WallClock end = current_block->first; - WallClock start = end - current_block->second.size() * m_buffer.m_sample_period; - -// cout << start - REFERENCE << " - " << end - REFERENCE << endl; - - // Way ahead of the latest sample. - if (timestamp - end > m_buffer.m_duration_gap_threshold){ -// cout << "way ahead" << endl; - return; - } - - // Way before the earliest sample. - if (start - timestamp > m_buffer.m_duration_gap_threshold){ -// cout << "way behind" << endl; - return; - } - - size_t block_size = current_block->second.size(); - m_current_block = current_block->first; - - // Slightly ahead of latest sample. Clip to latest. - if (timestamp >= end){ -// cout << "slightly ahead" << endl; - m_current_index = block_size; - return; - } - - // Slightly behind oldest sample. Clip to oldest. - if (timestamp <= start){ -// cout << "slightly behind" << endl; - m_current_index = 0; - return; - } - - // Somewhere inside the block. - size_t block = (end - timestamp).count() / m_buffer.m_sample_period.count(); - block = std::min(block, block_size); - m_current_index = block_size - block; -} - -template -void TimeSampleBufferReader::read_samples( - Type* samples, size_t count, - WallClock timestamp -){ - const typename TimeSampleBuffer::MapType& buffer = m_buffer.m_samples; - - WriteSpinLock lg(m_buffer.m_lock); - - if (buffer.empty()){ - memset(samples, 0, count * sizeof(Type)); - return; - } - - // Setup output state. - WallClock requested_time = timestamp - count * m_buffer.m_sample_period; - TimeSampleWriterForward output_buffer(samples, count); - - auto current_block = buffer.lower_bound(m_current_block); - if (current_block == buffer.end()){ -// cout << "front gap" << endl; - --current_block; - } - - // If the block no longer exists, jump to whatever is best block for the requested timestamp. - if (current_block->first != m_current_block || current_block->second.size() <= m_current_index){ -// cout << "resetting state" << endl; - current_block = buffer.lower_bound(requested_time); - if (current_block == buffer.end()){ - --current_block; - } - m_current_block = current_block->first; - m_current_index = 0; - } - - // Setup input state. - WallClock current_time = current_block->first - current_block->second.size() * m_buffer.m_sample_period; - - while (output_buffer.samples_left() > 0){ - // Current block is empty. Move to next block. - if (m_current_index >= current_block->second.size()){ - ++current_block; - if (current_block == buffer.end()){ - output_buffer.fill_rest_with_zeros(); - return; - } - m_current_block = current_block->first; - m_current_index = 0; - current_time = current_block->first - current_block->second.size() * m_buffer.m_sample_period; - } - - const std::vector& data = current_block->second; - size_t samples_remaining_in_block = data.size() - m_current_index; - - // Requested is far ahead of what's next. Skip ahead. - Duration output_ahead = requested_time - current_time; - if (output_ahead > m_buffer.m_duration_gap_threshold){ -// cout << "Output Ahead" << endl; - size_t block = output_ahead.count() / m_buffer.m_sample_period.count(); - block = std::min(block, samples_remaining_in_block); - m_current_index += block; - current_time += block * m_buffer.m_sample_period; - continue; - } - - // Requested is far behind what's next. Fill the gap with zeros. - Duration input_ahead = current_time - requested_time; - if (input_ahead > m_buffer.m_duration_gap_threshold){ -// cout << "Input Ahead" << endl; - size_t block = input_ahead.count() / m_buffer.m_sample_period.count(); - output_buffer.push_zeros(block); - requested_time += block * m_buffer.m_sample_period; - continue; - } - - size_t block = output_buffer.push_block(data.data() + m_current_index, samples_remaining_in_block); - Duration block_time = block * m_buffer.m_sample_period; - m_current_index += block; - current_time += block_time; - requested_time += block_time; - } -} - - - -template class TimeSampleBufferReader; -template class TimeSampleBufferReader; -template class TimeSampleBufferReader; -template class TimeSampleBufferReader; -template class TimeSampleBufferReader; -template class TimeSampleBufferReader; -template class TimeSampleBufferReader; - - - - -} +/* Time Sample Buffer Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "TimeSampleWriter.h" +#include "TimeSampleBufferReader.h" + +namespace PokemonAutomation{ + + + +template +TimeSampleBufferReader::TimeSampleBufferReader(TimeSampleBuffer& buffer) + : m_buffer(buffer) +// , m_last_timestamp(TimePoint::min()) + , m_current_block(WallClock::min()) + , m_current_index(0) +{} + +template +void TimeSampleBufferReader::set_to_timestamp(WallClock timestamp){ + WriteSpinLock lg(m_buffer.m_lock); + set_to_timestamp_unprotected(timestamp); +} + +template +void TimeSampleBufferReader::set_to_timestamp_unprotected(WallClock timestamp){ + m_current_block = WallClock::min(); + m_current_index = 0; + + const typename TimeSampleBuffer::MapType& buffer = m_buffer.m_samples; + if (buffer.empty()){ + return; + } + + auto current_block = buffer.upper_bound(timestamp); + if (current_block == buffer.end()){ +// cout << "front gap" << endl; + --current_block; + } + + WallClock end = current_block->first; + WallClock start = end - current_block->second.size() * m_buffer.m_sample_period; + +// cout << start - REFERENCE << " - " << end - REFERENCE << endl; + + // Way ahead of the latest sample. + if (timestamp - end > m_buffer.m_duration_gap_threshold){ +// cout << "way ahead" << endl; + return; + } + + // Way before the earliest sample. + if (start - timestamp > m_buffer.m_duration_gap_threshold){ +// cout << "way behind" << endl; + return; + } + + size_t block_size = current_block->second.size(); + m_current_block = current_block->first; + + // Slightly ahead of latest sample. Clip to latest. + if (timestamp >= end){ +// cout << "slightly ahead" << endl; + m_current_index = block_size; + return; + } + + // Slightly behind oldest sample. Clip to oldest. + if (timestamp <= start){ +// cout << "slightly behind" << endl; + m_current_index = 0; + return; + } + + // Somewhere inside the block. + size_t block = (end - timestamp).count() / m_buffer.m_sample_period.count(); + block = std::min(block, block_size); + m_current_index = block_size - block; +} + +template +void TimeSampleBufferReader::read_samples( + Type* samples, size_t count, + WallClock timestamp +){ + const typename TimeSampleBuffer::MapType& buffer = m_buffer.m_samples; + + WriteSpinLock lg(m_buffer.m_lock); + + if (buffer.empty()){ + memset(samples, 0, count * sizeof(Type)); + return; + } + + // Setup output state. + WallClock requested_time = timestamp - count * m_buffer.m_sample_period; + TimeSampleWriterForward output_buffer(samples, count); + + auto current_block = buffer.lower_bound(m_current_block); + if (current_block == buffer.end()){ +// cout << "front gap" << endl; + --current_block; + } + + // If the block no longer exists, jump to whatever is best block for the requested timestamp. + if (current_block->first != m_current_block || current_block->second.size() <= m_current_index){ +// cout << "resetting state" << endl; + current_block = buffer.lower_bound(requested_time); + if (current_block == buffer.end()){ + --current_block; + } + m_current_block = current_block->first; + m_current_index = 0; + } + + // Setup input state. + WallClock current_time = current_block->first - current_block->second.size() * m_buffer.m_sample_period; + + while (output_buffer.samples_left() > 0){ + // Current block is empty. Move to next block. + if (m_current_index >= current_block->second.size()){ + ++current_block; + if (current_block == buffer.end()){ + output_buffer.fill_rest_with_zeros(); + return; + } + m_current_block = current_block->first; + m_current_index = 0; + current_time = current_block->first - current_block->second.size() * m_buffer.m_sample_period; + } + + const std::vector& data = current_block->second; + size_t samples_remaining_in_block = data.size() - m_current_index; + + // Requested is far ahead of what's next. Skip ahead. + Duration output_ahead = requested_time - current_time; + if (output_ahead > m_buffer.m_duration_gap_threshold){ +// cout << "Output Ahead" << endl; + size_t block = output_ahead.count() / m_buffer.m_sample_period.count(); + block = std::min(block, samples_remaining_in_block); + m_current_index += block; + current_time += block * m_buffer.m_sample_period; + continue; + } + + // Requested is far behind what's next. Fill the gap with zeros. + Duration input_ahead = current_time - requested_time; + if (input_ahead > m_buffer.m_duration_gap_threshold){ +// cout << "Input Ahead" << endl; + size_t block = input_ahead.count() / m_buffer.m_sample_period.count(); + output_buffer.push_zeros(block); + requested_time += block * m_buffer.m_sample_period; + continue; + } + + size_t block = output_buffer.push_block(data.data() + m_current_index, samples_remaining_in_block); + Duration block_time = block * m_buffer.m_sample_period; + m_current_index += block; + current_time += block_time; + requested_time += block_time; + } +} + + + +template class TimeSampleBufferReader; +template class TimeSampleBufferReader; +template class TimeSampleBufferReader; +template class TimeSampleBufferReader; +template class TimeSampleBufferReader; +template class TimeSampleBufferReader; +template class TimeSampleBufferReader; + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.h index e895a43c79..c66d1b44e3 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleBufferReader.h @@ -1,45 +1,45 @@ -/* Time Sample Buffer Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBufferReader_H -#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBufferReader_H - -#include "TimeSampleBuffer.h" - -namespace PokemonAutomation{ - - -template -class TimeSampleBufferReader{ - using Duration = std::chrono::system_clock::duration; - -public: - TimeSampleBufferReader(TimeSampleBuffer& buffer); - - void set_to_timestamp(WallClock timestamp = current_time()); - - void read_samples( - Type* samples, size_t count, - WallClock timestamp = current_time() - ); - -private: - void set_to_timestamp_unprotected(WallClock timestamp = current_time()); - -public: - TimeSampleBuffer& m_buffer; - -// TimePoint m_last_timestamp; - - // Last read sample. - WallClock m_current_block; - size_t m_current_index; -}; - - - -} -#endif +/* Time Sample Buffer Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBufferReader_H +#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleBufferReader_H + +#include "TimeSampleBuffer.h" + +namespace PokemonAutomation{ + + +template +class TimeSampleBufferReader{ + using Duration = std::chrono::system_clock::duration; + +public: + TimeSampleBufferReader(TimeSampleBuffer& buffer); + + void set_to_timestamp(WallClock timestamp = current_time()); + + void read_samples( + Type* samples, size_t count, + WallClock timestamp = current_time() + ); + +private: + void set_to_timestamp_unprotected(WallClock timestamp = current_time()); + +public: + TimeSampleBuffer& m_buffer; + +// TimePoint m_last_timestamp; + + // Last read sample. + WallClock m_current_block; + size_t m_current_index; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleWriter.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleWriter.h index 1b45c0135d..34ffd0a8da 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleWriter.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/Tools/TimeSampleWriter.h @@ -1,107 +1,107 @@ -/* Time Sample Writer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleWriter_H -#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleWriter_H - -#include -#include - -namespace PokemonAutomation{ - - -template -class TimeSampleWriterForward{ -public: - TimeSampleWriterForward(Type* output, size_t count) - : m_output(output) - , m_samples_left(count) - {} - - // # of samples still left to fill before the output buffer is full. - size_t samples_left() const{ return m_samples_left; } - - // Push the current block of samples into the output buffer. - // Returns the # of samples actually pushed. - size_t push_block(const Type* samples, size_t count){ - size_t block = std::min(m_samples_left, count); - memcpy(m_output, samples, block * sizeof(Type)); - m_output += block; - m_samples_left -= block; - return block; - } - - // Push zeros into the output buffer. - // Returns the # of samples actually pushed. - size_t push_zeros(size_t count){ - size_t block = std::min(m_samples_left, count); - memset(m_output, 0, block * sizeof(Type)); - m_output += block; - m_samples_left -= block; - return block; - } - - void fill_rest_with_zeros(){ - memset(m_output, 0, m_samples_left * sizeof(Type)); - m_output += m_samples_left; - m_samples_left = 0; - } - - -private: - Type* m_output; - size_t m_samples_left; -}; - - - -template -class TimeSampleWriterReverse{ -public: - TimeSampleWriterReverse(Type* output, size_t count) - : m_output(output + count) - , m_samples_left(count) - {} - - // # of samples still left to fill before the output buffer is full. - size_t samples_left() const{ return m_samples_left; } - - // Push the current block of samples into the output buffer. - // Returns the # of samples actually pushed. - size_t push_block(const Type* samples, size_t count){ - size_t block = std::min(m_samples_left, count); - memcpy(m_output - block, samples + count - block, block * sizeof(Type)); - m_output -= block; - m_samples_left -= block; - return block; - } - - // Push zeros into the output buffer. - // Returns the # of samples actually pushed. - size_t push_zeros(size_t count){ - size_t block = std::min(m_samples_left, count); - memset(m_output - block, 0, block * sizeof(Type)); - m_output -= block; - m_samples_left -= block; - return block; - } - - void fill_rest_with_zeros(){ - m_output -= m_samples_left; - memset(m_output, 0, m_samples_left * sizeof(Type)); - m_samples_left = 0; - } - - -private: - Type* m_output; - size_t m_samples_left; -}; - - - -} -#endif +/* Time Sample Writer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleWriter_H +#define PokemonAutomation_CommonFramework_AudioPipeline_TimeSampleWriter_H + +#include +#include + +namespace PokemonAutomation{ + + +template +class TimeSampleWriterForward{ +public: + TimeSampleWriterForward(Type* output, size_t count) + : m_output(output) + , m_samples_left(count) + {} + + // # of samples still left to fill before the output buffer is full. + size_t samples_left() const{ return m_samples_left; } + + // Push the current block of samples into the output buffer. + // Returns the # of samples actually pushed. + size_t push_block(const Type* samples, size_t count){ + size_t block = std::min(m_samples_left, count); + memcpy(m_output, samples, block * sizeof(Type)); + m_output += block; + m_samples_left -= block; + return block; + } + + // Push zeros into the output buffer. + // Returns the # of samples actually pushed. + size_t push_zeros(size_t count){ + size_t block = std::min(m_samples_left, count); + memset(m_output, 0, block * sizeof(Type)); + m_output += block; + m_samples_left -= block; + return block; + } + + void fill_rest_with_zeros(){ + memset(m_output, 0, m_samples_left * sizeof(Type)); + m_output += m_samples_left; + m_samples_left = 0; + } + + +private: + Type* m_output; + size_t m_samples_left; +}; + + + +template +class TimeSampleWriterReverse{ +public: + TimeSampleWriterReverse(Type* output, size_t count) + : m_output(output + count) + , m_samples_left(count) + {} + + // # of samples still left to fill before the output buffer is full. + size_t samples_left() const{ return m_samples_left; } + + // Push the current block of samples into the output buffer. + // Returns the # of samples actually pushed. + size_t push_block(const Type* samples, size_t count){ + size_t block = std::min(m_samples_left, count); + memcpy(m_output - block, samples + count - block, block * sizeof(Type)); + m_output -= block; + m_samples_left -= block; + return block; + } + + // Push zeros into the output buffer. + // Returns the # of samples actually pushed. + size_t push_zeros(size_t count){ + size_t block = std::min(m_samples_left, count); + memset(m_output - block, 0, block * sizeof(Type)); + m_output -= block; + m_samples_left -= block; + return block; + } + + void fill_rest_with_zeros(){ + m_output -= m_samples_left; + memset(m_output, 0, m_samples_left * sizeof(Type)); + m_samples_left = 0; + } + + +private: + Type* m_output; + size_t m_samples_left; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.cpp index d4cdd3d138..f0146dc061 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.cpp @@ -1,201 +1,201 @@ -/* Audio Display Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include -#include -#include "Common/Qt/Redispatch.h" -#include "AudioDisplayWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - - -AudioDisplayWidget::AudioDisplayWidget(QWidget& parent, Logger& logger, AudioSession& session) - : QWidget(&parent) - , m_session(session) - , m_display_type(session.display_type()) -{ - m_session.add_state_listener(*this); - m_session.add_spectrum_listener(*this); -} - -AudioDisplayWidget::~AudioDisplayWidget(){ - m_session.remove_spectrum_listener(*this); - m_session.remove_state_listener(*this); -} - - - -void AudioDisplayWidget::state_changed(){ -// cout << "AudioDisplayWidget::state_changed()" << endl; - QMetaObject::invokeMethod( - this, [this]{ - auto scope_check = m_sanitizer.check_scope(); - update_size(); - QWidget::update(); - }, Qt::QueuedConnection - ); -} -#if 0 -void AudioDisplayWidget::pre_input_change(){ - QMetaObject::invokeMethod( - this, [this]{ - auto scope_check = m_sanitizer.check_scope(); - update_size(); - QWidget::update(); - }, Qt::QueuedConnection - ); -} -#endif -void AudioDisplayWidget::post_display_change(AudioOption::AudioDisplayType display){ -// cout << "AudioDisplayWidget::display_changed()" << endl; - QMetaObject::invokeMethod( - this, [this, display]{ - auto scope_check = m_sanitizer.check_scope(); - m_display_type = display; - update_size(); - QWidget::update(); - }, Qt::QueuedConnection - ); -} - - - -void AudioDisplayWidget::render_bars(){ -// cout << "AudioDisplayWidget::render_bars()" << endl; - - QPainter painter(this); - painter.fillRect(rect(), Qt::black); - - const int widgetWidth = this->width(); - const int widgetHeight = this->height(); - - AudioSpectrumHolder::SpectrumSnapshot last_spectrum = m_session.spectrums().get_last_spectrum(); - - // Don't render if it's too old. - if (last_spectrum.timestamp < current_time() - std::chrono::milliseconds(500)){ - return; - } - - size_t num_buckets = last_spectrum.values.size(); - -#if 0 - for (int c = 0; c < 10; c++){ - cout << last_spectrum.values[c] << ", "; - } - cout << endl; -#endif - - const size_t barPlusGapWidth = widgetWidth / num_buckets; - const size_t barWidth = 0.8 * barPlusGapWidth; - const size_t gapWidth = barPlusGapWidth - barWidth; - const size_t paddingWidth = widgetWidth - num_buckets * (barWidth + gapWidth); - const size_t leftPaddingWidth = (paddingWidth + gapWidth) / 2; - const size_t barHeight = widgetHeight - 2 * gapWidth; -// cout << "barHeight = " << barHeight << endl; - - double bucket_rcp = (double)widgetWidth / num_buckets; - - for (size_t i = 0; i < num_buckets; i++){ - int s = (int)((i + 0 ) * bucket_rcp); // Start of bucket. - int e = (int)((i + 0.8) * bucket_rcp); // End of bucket. - -// size_t curWindow = (m_nextFFTWindowIndex + m_num_freq_windows - 1) % m_num_freq_windows; -// // +1 here to skip the freq-0 value -// float value = m_freqVisBlocks[curWindow * m_numFreqVisBlocks + i]; - float value = last_spectrum.values[i]; - QRect bar = rect(); - bar.setLeft((int)(rect().left() + leftPaddingWidth + (i * (gapWidth + barWidth)))); - bar.setWidth((int)barWidth); - bar.setTop((int)(rect().top() + gapWidth + (1.0 - value) * barHeight)); - bar.setBottom((int)(rect().bottom() - gapWidth)); - - bar.setLeft(s); - bar.setWidth(e - s); - - painter.fillRect(bar, last_spectrum.colors[i]); - } -} -void AudioDisplayWidget::render_spectrograph(){ - QPainter painter(this); - - const int widgetWidth = this->width(); - const int widgetHeight = this->height(); - - AudioSpectrumHolder::SpectrographSnapshot snapshot = m_session.spectrums().get_spectrograph(); - { - QImage graph_image = snapshot.image.to_QImage_ref(); - graph_image = graph_image.scaled( - widgetWidth, widgetHeight, - Qt::IgnoreAspectRatio, - Qt::SmoothTransformation - ); - painter.fillRect(rect(), graph_image); - } - - // Now render overlays: - - // Each window has width: widgetWidth / (m_num_freq_windows-1) on the spectrogram - const float FFTWindowWidth = widgetWidth / float(snapshot.image.width() - 1); - - for (const auto& box : snapshot.overlays){ - int xmin = int(std::get<0>(box) * FFTWindowWidth + 0.5); - int ymin = rect().top(); - int rangeWidth = int(FFTWindowWidth * std::get<1>(box) + 0.5); - painter.setPen(QColor((uint32_t)std::get<2>(box))); - painter.drawRect(xmin, ymin + 1, rangeWidth, widgetHeight - 2); - } -} -void AudioDisplayWidget::paintEvent(QPaintEvent* event){ -// cout << "AudioDisplayWidget::paintEvent()" << endl; - QWidget::paintEvent(event); - - switch (m_display_type){ - case AudioDisplayType::FREQ_BARS: - render_bars(); - break; - case AudioDisplayType::SPECTROGRAM: - render_spectrograph(); - break; - default: - break; - } -} - - -void AudioDisplayWidget::update_size(){ - int height = m_display_type == AudioDisplayType::NO_DISPLAY ? 0 : this->width() / 6; -// cout << "AudioDisplayWidget::update_size(): " << height << " <- " << m_previous_height << endl; - - if (height == m_previous_height){ - return; - } - - if (height > m_previous_height && height < m_previous_height + 10 && !m_debouncer.check(height)){ -// cout << "Suppressing potential infinite resizing loop." << endl; - return; - } - - this->setFixedHeight(height); - m_previous_height = height; -} - -void AudioDisplayWidget::resizeEvent(QResizeEvent* event){ - QWidget::resizeEvent(event); - - update_size(); -} - - - - -} +/* Audio Display Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include +#include +#include "Common/Qt/Redispatch.h" +#include "AudioDisplayWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + + +AudioDisplayWidget::AudioDisplayWidget(QWidget& parent, Logger& logger, AudioSession& session) + : QWidget(&parent) + , m_session(session) + , m_display_type(session.display_type()) +{ + m_session.add_state_listener(*this); + m_session.add_spectrum_listener(*this); +} + +AudioDisplayWidget::~AudioDisplayWidget(){ + m_session.remove_spectrum_listener(*this); + m_session.remove_state_listener(*this); +} + + + +void AudioDisplayWidget::state_changed(){ +// cout << "AudioDisplayWidget::state_changed()" << endl; + QMetaObject::invokeMethod( + this, [this]{ + auto scope_check = m_sanitizer.check_scope(); + update_size(); + QWidget::update(); + }, Qt::QueuedConnection + ); +} +#if 0 +void AudioDisplayWidget::pre_input_change(){ + QMetaObject::invokeMethod( + this, [this]{ + auto scope_check = m_sanitizer.check_scope(); + update_size(); + QWidget::update(); + }, Qt::QueuedConnection + ); +} +#endif +void AudioDisplayWidget::post_display_change(AudioOption::AudioDisplayType display){ +// cout << "AudioDisplayWidget::display_changed()" << endl; + QMetaObject::invokeMethod( + this, [this, display]{ + auto scope_check = m_sanitizer.check_scope(); + m_display_type = display; + update_size(); + QWidget::update(); + }, Qt::QueuedConnection + ); +} + + + +void AudioDisplayWidget::render_bars(){ +// cout << "AudioDisplayWidget::render_bars()" << endl; + + QPainter painter(this); + painter.fillRect(rect(), Qt::black); + + const int widgetWidth = this->width(); + const int widgetHeight = this->height(); + + AudioSpectrumHolder::SpectrumSnapshot last_spectrum = m_session.spectrums().get_last_spectrum(); + + // Don't render if it's too old. + if (last_spectrum.timestamp < current_time() - std::chrono::milliseconds(500)){ + return; + } + + size_t num_buckets = last_spectrum.values.size(); + +#if 0 + for (int c = 0; c < 10; c++){ + cout << last_spectrum.values[c] << ", "; + } + cout << endl; +#endif + + const size_t barPlusGapWidth = widgetWidth / num_buckets; + const size_t barWidth = 0.8 * barPlusGapWidth; + const size_t gapWidth = barPlusGapWidth - barWidth; + const size_t paddingWidth = widgetWidth - num_buckets * (barWidth + gapWidth); + const size_t leftPaddingWidth = (paddingWidth + gapWidth) / 2; + const size_t barHeight = widgetHeight - 2 * gapWidth; +// cout << "barHeight = " << barHeight << endl; + + double bucket_rcp = (double)widgetWidth / num_buckets; + + for (size_t i = 0; i < num_buckets; i++){ + int s = (int)((i + 0 ) * bucket_rcp); // Start of bucket. + int e = (int)((i + 0.8) * bucket_rcp); // End of bucket. + +// size_t curWindow = (m_nextFFTWindowIndex + m_num_freq_windows - 1) % m_num_freq_windows; +// // +1 here to skip the freq-0 value +// float value = m_freqVisBlocks[curWindow * m_numFreqVisBlocks + i]; + float value = last_spectrum.values[i]; + QRect bar = rect(); + bar.setLeft((int)(rect().left() + leftPaddingWidth + (i * (gapWidth + barWidth)))); + bar.setWidth((int)barWidth); + bar.setTop((int)(rect().top() + gapWidth + (1.0 - value) * barHeight)); + bar.setBottom((int)(rect().bottom() - gapWidth)); + + bar.setLeft(s); + bar.setWidth(e - s); + + painter.fillRect(bar, last_spectrum.colors[i]); + } +} +void AudioDisplayWidget::render_spectrograph(){ + QPainter painter(this); + + const int widgetWidth = this->width(); + const int widgetHeight = this->height(); + + AudioSpectrumHolder::SpectrographSnapshot snapshot = m_session.spectrums().get_spectrograph(); + { + QImage graph_image = snapshot.image.to_QImage_ref(); + graph_image = graph_image.scaled( + widgetWidth, widgetHeight, + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation + ); + painter.fillRect(rect(), graph_image); + } + + // Now render overlays: + + // Each window has width: widgetWidth / (m_num_freq_windows-1) on the spectrogram + const float FFTWindowWidth = widgetWidth / float(snapshot.image.width() - 1); + + for (const auto& box : snapshot.overlays){ + int xmin = int(std::get<0>(box) * FFTWindowWidth + 0.5); + int ymin = rect().top(); + int rangeWidth = int(FFTWindowWidth * std::get<1>(box) + 0.5); + painter.setPen(QColor((uint32_t)std::get<2>(box))); + painter.drawRect(xmin, ymin + 1, rangeWidth, widgetHeight - 2); + } +} +void AudioDisplayWidget::paintEvent(QPaintEvent* event){ +// cout << "AudioDisplayWidget::paintEvent()" << endl; + QWidget::paintEvent(event); + + switch (m_display_type){ + case AudioDisplayType::FREQ_BARS: + render_bars(); + break; + case AudioDisplayType::SPECTROGRAM: + render_spectrograph(); + break; + default: + break; + } +} + + +void AudioDisplayWidget::update_size(){ + int height = m_display_type == AudioDisplayType::NO_DISPLAY ? 0 : this->width() / 6; +// cout << "AudioDisplayWidget::update_size(): " << height << " <- " << m_previous_height << endl; + + if (height == m_previous_height){ + return; + } + + if (height > m_previous_height && height < m_previous_height + 10 && !m_debouncer.check(height)){ +// cout << "Suppressing potential infinite resizing loop." << endl; + return; + } + + this->setFixedHeight(height); + m_previous_height = height; +} + +void AudioDisplayWidget::resizeEvent(QResizeEvent* event){ + QWidget::resizeEvent(event); + + update_size(); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h index c1daa96fdf..bd4a39305a 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h @@ -1,65 +1,65 @@ -/* Audio Display Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioDisplayWidget_H -#define PokemonAutomation_AudioPipeline_AudioDisplayWidget_H - -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/ValueDebouncer.h" -#include "CommonFramework/AudioPipeline/AudioOption.h" -#include "CommonFramework/AudioPipeline/AudioSession.h" - -namespace PokemonAutomation{ - -class AudioDeviceInfo; -class Logger; - - -class AudioDisplayWidget - : public QWidget - , public AudioSpectrumHolder::Listener - , public AudioSession::StateListener -{ -public: - using AudioDisplayType = AudioOption::AudioDisplayType; - - AudioDisplayWidget(QWidget& parent, Logger& logger, AudioSession& session); - virtual ~AudioDisplayWidget(); - - void resizeEvent(QResizeEvent* event) override; - void paintEvent(QPaintEvent* event) override; - - -private: - virtual void state_changed() override; - -// virtual void pre_input_change() override; - virtual void post_display_change(AudioOption::AudioDisplayType display) override; - - -private: - void update_size(); - - void render_bars(); - void render_spectrograph(); - - -private: - AudioSession& m_session; - AudioOption::AudioDisplayType m_display_type; - - int m_previous_height = 0; - ValueDebouncer m_debouncer; - - LifetimeSanitizer m_sanitizer; -}; - - - - -} -#endif +/* Audio Display Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioDisplayWidget_H +#define PokemonAutomation_AudioPipeline_AudioDisplayWidget_H + +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/ValueDebouncer.h" +#include "CommonFramework/AudioPipeline/AudioOption.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" + +namespace PokemonAutomation{ + +class AudioDeviceInfo; +class Logger; + + +class AudioDisplayWidget + : public QWidget + , public AudioSpectrumHolder::Listener + , public AudioSession::StateListener +{ +public: + using AudioDisplayType = AudioOption::AudioDisplayType; + + AudioDisplayWidget(QWidget& parent, Logger& logger, AudioSession& session); + virtual ~AudioDisplayWidget(); + + void resizeEvent(QResizeEvent* event) override; + void paintEvent(QPaintEvent* event) override; + + +private: + virtual void state_changed() override; + +// virtual void pre_input_change() override; + virtual void post_display_change(AudioOption::AudioDisplayType display) override; + + +private: + void update_size(); + + void render_bars(); + void render_spectrograph(); + + +private: + AudioSession& m_session; + AudioOption::AudioDisplayType m_display_type; + + int m_previous_height = 0; + ValueDebouncer m_debouncer; + + LifetimeSanitizer m_sanitizer; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.cpp b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.cpp index fe596757e9..3ca7f0cd16 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.cpp @@ -1,344 +1,344 @@ -/* Audio Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonFramework/AudioPipeline/AudioSession.h" -#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" -#include "AudioDisplayWidget.h" -#include "AudioSelectorWidget.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -AudioSelectorWidget::~AudioSelectorWidget(){ - m_session.remove_state_listener(*this); -} - -AudioSelectorWidget::AudioSelectorWidget(QWidget& parent, AudioSession& session) - : QWidget(&parent) - , m_session(session) -// , m_slider_active(false) -{ - QVBoxLayout* vbox = new QVBoxLayout(this); - vbox->setContentsMargins(0, 0, 0, 0); - - { - QHBoxLayout* row0 = new QHBoxLayout(); - row0->setContentsMargins(0, 0, 0, 0); - vbox->addLayout(row0); - - row0->addWidget(new QLabel("Audio Input:", this), 2); - row0->addSpacing(5); - - QHBoxLayout* input_layout = new QHBoxLayout(); - row0->addLayout(input_layout, 10); - - m_audio_input_box = new NoWheelComboBox(this); - m_audio_input_box->setMaxVisibleItems(20); - input_layout->addWidget(m_audio_input_box, 10); - row0->addSpacing(5); - - m_audio_format_box = new NoWheelComboBox(this); - row0->addWidget(m_audio_format_box, 6); - row0->addSpacing(5); - - m_reset_button = new QPushButton("Reset Audio", this); - row0->addWidget(m_reset_button, 2); - } - - { - QHBoxLayout* row1 = new QHBoxLayout(); - row1->setContentsMargins(0, 0, 0, 0); - vbox->addLayout(row1); - - row1->addWidget(new QLabel("Audio Output:", this), 2); - row1->addSpacing(5); - - QHBoxLayout* output_layout = new QHBoxLayout(); - row1->addLayout(output_layout, 10); - m_audio_output_box = new NoWheelComboBox(this); - m_audio_output_box->setMaxVisibleItems(20); - if (GlobalSettings::instance().AUDIO_PIPELINE->SHOW_RECORD_FREQUENCIES){ - output_layout->addWidget(m_audio_output_box, 7); - m_record_button = new QPushButton("Record Frequencies", this); - output_layout->addWidget(m_record_button, 3); - }else{ - output_layout->addWidget(m_audio_output_box, 10); - } - row1->addSpacing(5); - - m_volume_slider = new QSlider(Qt::Horizontal, this); - m_volume_slider->setRange(0, 100); - m_volume_slider->setTickInterval(10); - m_volume_slider->setMinimumWidth(40); - m_volume_slider->setTickPosition(QSlider::TicksBothSides); - row1->addWidget(m_volume_slider, 4); - row1->addSpacing(5); - - m_audio_vis_box = new NoWheelComboBox(this); - m_audio_vis_box->addItem("No Display"); - m_audio_vis_box->addItem("Spectrum"); - m_audio_vis_box->addItem("Spectrogram"); - row1->addWidget(m_audio_vis_box, 4); - } - - refresh_all(); - - connect( - m_audio_input_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index <= 0 || index >= (int)m_input_audios.size() + 2){ - m_session.clear_audio_input(); - }else if (index == 1){ - std::string path = QFileDialog::getOpenFileName(this, "Open audio file", ".", "*.wav *.mp3").toStdString(); - if (path.empty()){ - m_session.clear_audio_input(); - }else{ - m_session.set_audio_input(std::move(path)); - } - }else{ - m_session.set_audio_input(m_input_audios[index - 2]); - } - } - ); - connect( - m_audio_format_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0 || index >= (int)m_input_formats.size()){ - return; - } - m_session.set_format(m_input_formats[index]); - } - ); - connect( - m_audio_output_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index <= 0 || index >= (int)m_output_audios.size() + 1){ - m_session.clear_audio_output(); - }else{ - m_session.set_audio_output(m_output_audios[index - 1]); - } - } - ); - connect( - m_reset_button, &QPushButton::clicked, - this, [this](bool){ - m_session.reset(); - refresh_all(); - } - ); - connect( - m_audio_vis_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0 || index > 2){ - index = 0; - } - m_session.set_display((AudioOption::AudioDisplayType)index); - } - ); - - connect( - m_volume_slider, &QSlider::valueChanged, this, [this](int value){ - m_session.set_volume(value / 100.); - } - ); -#if 0 - connect( - m_volume_slider, &QSlider::sliderMoved, this, [this](){ - m_session.set_volume(m_volume_slider->value() / 100.); - } - ); - connect( - m_volume_slider, &QSlider::sliderPressed, this, [this](){ - m_slider_active.store(true, std::memory_order_release); - } - ); - connect( - m_volume_slider, &QSlider::sliderReleased, this, [this](){ - m_slider_active.store(false, std::memory_order_release); - } - ); -#endif - - // only in developer mode: - // record audio - if (GlobalSettings::instance().AUDIO_PIPELINE->SHOW_RECORD_FREQUENCIES){ - connect(m_record_button, &QPushButton::clicked, this, [this](bool){ - m_record_is_on = !m_record_is_on; - m_session.spectrums().saveAudioFrequenciesToDisk(m_record_is_on); - if (m_record_is_on){ - m_record_button->setText("Stop recording"); - }else{ - m_record_button->setText("Record Frequencies"); - } - }); - } - - session.add_state_listener(*this); -} - - - -void AudioSelectorWidget::build_input_list(const std::string& file, const AudioDeviceInfo& device){ - m_input_audios = AudioDeviceInfo::all_input_devices(); - m_audio_input_box->clear(); - m_audio_input_box->addItem("(none)"); - m_audio_input_box->addItem("Play Audio File"); - size_t index = file.empty() ? 0 : 1; - for (size_t c = 0; c < m_input_audios.size(); c++){ - const AudioDeviceInfo& audio = m_input_audios[c]; - m_audio_input_box->addItem(QString::fromStdString(audio.display_name())); - if (device == audio){ - index = c + 2; - } - } - m_audio_input_box->setCurrentIndex((int)index); -} -void AudioSelectorWidget::build_output_list(const AudioDeviceInfo& device){ - m_output_audios = AudioDeviceInfo::all_output_devices(); - m_audio_output_box->clear(); - m_audio_output_box->addItem("(none)"); - size_t index = 0; - for (size_t c = 0; c < m_output_audios.size(); c++){ - const AudioDeviceInfo& audio = m_output_audios[c]; - m_audio_output_box->addItem(QString::fromStdString(audio.display_name())); - if (device == audio){ - index = c + 1; - } - } - m_audio_output_box->setCurrentIndex((int)index); -} - - -void AudioSelectorWidget::refresh_all(){ - auto input = m_session.input_device(); - refresh_input_device(input.first, input.second); - refresh_formats(input.first, input.second, m_session.input_format()); - refresh_output_device(m_session.output_device()); - refresh_volume(m_session.output_volume()); - refresh_display(m_session.display_type()); -} -void AudioSelectorWidget::refresh_formats(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ -// cout << "AudioSelectorWidget::refresh_formats()" << endl; - if (!file.empty() || !device){ - m_audio_format_box->clear(); - return; - } -// cout << "AudioSelectorWidget::refresh_formats() - inside" << endl; - - m_input_formats = device.supported_formats(); - m_audio_format_box->clear(); - int index = -1; - for (size_t c = 0; c < m_input_formats.size(); c++){ - m_audio_format_box->addItem(AUDIO_FORMAT_LABELS[(size_t)m_input_formats[c]]); - if (format == m_input_formats[c]){ - index = (int)c; - } - } - m_audio_format_box->setCurrentIndex(index); -} -void AudioSelectorWidget::refresh_input_device(const std::string& file, const AudioDeviceInfo& device){ - if (m_input_audios.empty()){ - build_input_list(file, device); - return; - } - - if (!file.empty()){ - m_audio_input_box->setCurrentIndex(1); - return; - } - - // See if it's in our cached list. - for (size_t c = 0; c < m_input_audios.size(); c++){ - if (device == m_input_audios[c]){ - m_audio_input_box->setCurrentIndex((int)c + 2); - return; - } - } - - build_input_list(file, device); -} -void AudioSelectorWidget::refresh_output_device(const AudioDeviceInfo& device){ - if (m_output_audios.empty()){ - build_output_list(device); - return; - } - - // See if it's in our cached list. - for (size_t c = 0; c < m_output_audios.size(); c++){ - if (device == m_output_audios[c]){ - m_audio_output_box->setCurrentIndex((int)c + 1); - return; - } - } - - build_output_list(device); -} -void AudioSelectorWidget::refresh_volume(double volume){ - m_volume_slider->setValue((int)(volume * 100)); -} -void AudioSelectorWidget::refresh_display(AudioOption::AudioDisplayType display){ - switch(display){ - case AudioOption::AudioDisplayType::NO_DISPLAY: - m_audio_vis_box->setCurrentIndex(0); - break; - case AudioOption::AudioDisplayType::FREQ_BARS: - m_audio_vis_box->setCurrentIndex(1); - break; - case AudioOption::AudioDisplayType::SPECTROGRAM: - m_audio_vis_box->setCurrentIndex(2); - break; - default: - m_audio_vis_box->setCurrentIndex(0); - } -} - - -void AudioSelectorWidget::post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ -// cout << "AudioSelectorWidget::input_changed()" << endl; - QMetaObject::invokeMethod(this, [this, device, file, format]{ - refresh_input_device(file, device); - refresh_formats(file, device, format); - }); -} -void AudioSelectorWidget::post_output_change(const AudioDeviceInfo& device){ - QMetaObject::invokeMethod(this, [this, device]{ - refresh_output_device(device); - }); -} -void AudioSelectorWidget::post_volume_change(double volume){ -// if (m_slider_active.load(std::memory_order_acquire)){ -// return; -// } - QMetaObject::invokeMethod(this, [this]{ -// refresh_volume(volume); - refresh_volume(m_session.output_volume()); - }, Qt::QueuedConnection); // Queued due to potential recursive call to the same lock. -} -void AudioSelectorWidget::post_display_change(AudioOption::AudioDisplayType display){ - QMetaObject::invokeMethod(this, [this]{ - refresh_display(m_session.display_type()); - }, Qt::QueuedConnection); // Queued due to potential recursive call to the same lock. -} - - - - - - -} +/* Audio Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" +#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" +#include "AudioDisplayWidget.h" +#include "AudioSelectorWidget.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +AudioSelectorWidget::~AudioSelectorWidget(){ + m_session.remove_state_listener(*this); +} + +AudioSelectorWidget::AudioSelectorWidget(QWidget& parent, AudioSession& session) + : QWidget(&parent) + , m_session(session) +// , m_slider_active(false) +{ + QVBoxLayout* vbox = new QVBoxLayout(this); + vbox->setContentsMargins(0, 0, 0, 0); + + { + QHBoxLayout* row0 = new QHBoxLayout(); + row0->setContentsMargins(0, 0, 0, 0); + vbox->addLayout(row0); + + row0->addWidget(new QLabel("Audio Input:", this), 2); + row0->addSpacing(5); + + QHBoxLayout* input_layout = new QHBoxLayout(); + row0->addLayout(input_layout, 10); + + m_audio_input_box = new NoWheelComboBox(this); + m_audio_input_box->setMaxVisibleItems(20); + input_layout->addWidget(m_audio_input_box, 10); + row0->addSpacing(5); + + m_audio_format_box = new NoWheelComboBox(this); + row0->addWidget(m_audio_format_box, 6); + row0->addSpacing(5); + + m_reset_button = new QPushButton("Reset Audio", this); + row0->addWidget(m_reset_button, 2); + } + + { + QHBoxLayout* row1 = new QHBoxLayout(); + row1->setContentsMargins(0, 0, 0, 0); + vbox->addLayout(row1); + + row1->addWidget(new QLabel("Audio Output:", this), 2); + row1->addSpacing(5); + + QHBoxLayout* output_layout = new QHBoxLayout(); + row1->addLayout(output_layout, 10); + m_audio_output_box = new NoWheelComboBox(this); + m_audio_output_box->setMaxVisibleItems(20); + if (GlobalSettings::instance().AUDIO_PIPELINE->SHOW_RECORD_FREQUENCIES){ + output_layout->addWidget(m_audio_output_box, 7); + m_record_button = new QPushButton("Record Frequencies", this); + output_layout->addWidget(m_record_button, 3); + }else{ + output_layout->addWidget(m_audio_output_box, 10); + } + row1->addSpacing(5); + + m_volume_slider = new QSlider(Qt::Horizontal, this); + m_volume_slider->setRange(0, 100); + m_volume_slider->setTickInterval(10); + m_volume_slider->setMinimumWidth(40); + m_volume_slider->setTickPosition(QSlider::TicksBothSides); + row1->addWidget(m_volume_slider, 4); + row1->addSpacing(5); + + m_audio_vis_box = new NoWheelComboBox(this); + m_audio_vis_box->addItem("No Display"); + m_audio_vis_box->addItem("Spectrum"); + m_audio_vis_box->addItem("Spectrogram"); + row1->addWidget(m_audio_vis_box, 4); + } + + refresh_all(); + + connect( + m_audio_input_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index <= 0 || index >= (int)m_input_audios.size() + 2){ + m_session.clear_audio_input(); + }else if (index == 1){ + std::string path = QFileDialog::getOpenFileName(this, "Open audio file", ".", "*.wav *.mp3").toStdString(); + if (path.empty()){ + m_session.clear_audio_input(); + }else{ + m_session.set_audio_input(std::move(path)); + } + }else{ + m_session.set_audio_input(m_input_audios[index - 2]); + } + } + ); + connect( + m_audio_format_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0 || index >= (int)m_input_formats.size()){ + return; + } + m_session.set_format(m_input_formats[index]); + } + ); + connect( + m_audio_output_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index <= 0 || index >= (int)m_output_audios.size() + 1){ + m_session.clear_audio_output(); + }else{ + m_session.set_audio_output(m_output_audios[index - 1]); + } + } + ); + connect( + m_reset_button, &QPushButton::clicked, + this, [this](bool){ + m_session.reset(); + refresh_all(); + } + ); + connect( + m_audio_vis_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0 || index > 2){ + index = 0; + } + m_session.set_display((AudioOption::AudioDisplayType)index); + } + ); + + connect( + m_volume_slider, &QSlider::valueChanged, this, [this](int value){ + m_session.set_volume(value / 100.); + } + ); +#if 0 + connect( + m_volume_slider, &QSlider::sliderMoved, this, [this](){ + m_session.set_volume(m_volume_slider->value() / 100.); + } + ); + connect( + m_volume_slider, &QSlider::sliderPressed, this, [this](){ + m_slider_active.store(true, std::memory_order_release); + } + ); + connect( + m_volume_slider, &QSlider::sliderReleased, this, [this](){ + m_slider_active.store(false, std::memory_order_release); + } + ); +#endif + + // only in developer mode: + // record audio + if (GlobalSettings::instance().AUDIO_PIPELINE->SHOW_RECORD_FREQUENCIES){ + connect(m_record_button, &QPushButton::clicked, this, [this](bool){ + m_record_is_on = !m_record_is_on; + m_session.spectrums().saveAudioFrequenciesToDisk(m_record_is_on); + if (m_record_is_on){ + m_record_button->setText("Stop recording"); + }else{ + m_record_button->setText("Record Frequencies"); + } + }); + } + + session.add_state_listener(*this); +} + + + +void AudioSelectorWidget::build_input_list(const std::string& file, const AudioDeviceInfo& device){ + m_input_audios = AudioDeviceInfo::all_input_devices(); + m_audio_input_box->clear(); + m_audio_input_box->addItem("(none)"); + m_audio_input_box->addItem("Play Audio File"); + size_t index = file.empty() ? 0 : 1; + for (size_t c = 0; c < m_input_audios.size(); c++){ + const AudioDeviceInfo& audio = m_input_audios[c]; + m_audio_input_box->addItem(QString::fromStdString(audio.display_name())); + if (device == audio){ + index = c + 2; + } + } + m_audio_input_box->setCurrentIndex((int)index); +} +void AudioSelectorWidget::build_output_list(const AudioDeviceInfo& device){ + m_output_audios = AudioDeviceInfo::all_output_devices(); + m_audio_output_box->clear(); + m_audio_output_box->addItem("(none)"); + size_t index = 0; + for (size_t c = 0; c < m_output_audios.size(); c++){ + const AudioDeviceInfo& audio = m_output_audios[c]; + m_audio_output_box->addItem(QString::fromStdString(audio.display_name())); + if (device == audio){ + index = c + 1; + } + } + m_audio_output_box->setCurrentIndex((int)index); +} + + +void AudioSelectorWidget::refresh_all(){ + auto input = m_session.input_device(); + refresh_input_device(input.first, input.second); + refresh_formats(input.first, input.second, m_session.input_format()); + refresh_output_device(m_session.output_device()); + refresh_volume(m_session.output_volume()); + refresh_display(m_session.display_type()); +} +void AudioSelectorWidget::refresh_formats(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ +// cout << "AudioSelectorWidget::refresh_formats()" << endl; + if (!file.empty() || !device){ + m_audio_format_box->clear(); + return; + } +// cout << "AudioSelectorWidget::refresh_formats() - inside" << endl; + + m_input_formats = device.supported_formats(); + m_audio_format_box->clear(); + int index = -1; + for (size_t c = 0; c < m_input_formats.size(); c++){ + m_audio_format_box->addItem(AUDIO_FORMAT_LABELS[(size_t)m_input_formats[c]]); + if (format == m_input_formats[c]){ + index = (int)c; + } + } + m_audio_format_box->setCurrentIndex(index); +} +void AudioSelectorWidget::refresh_input_device(const std::string& file, const AudioDeviceInfo& device){ + if (m_input_audios.empty()){ + build_input_list(file, device); + return; + } + + if (!file.empty()){ + m_audio_input_box->setCurrentIndex(1); + return; + } + + // See if it's in our cached list. + for (size_t c = 0; c < m_input_audios.size(); c++){ + if (device == m_input_audios[c]){ + m_audio_input_box->setCurrentIndex((int)c + 2); + return; + } + } + + build_input_list(file, device); +} +void AudioSelectorWidget::refresh_output_device(const AudioDeviceInfo& device){ + if (m_output_audios.empty()){ + build_output_list(device); + return; + } + + // See if it's in our cached list. + for (size_t c = 0; c < m_output_audios.size(); c++){ + if (device == m_output_audios[c]){ + m_audio_output_box->setCurrentIndex((int)c + 1); + return; + } + } + + build_output_list(device); +} +void AudioSelectorWidget::refresh_volume(double volume){ + m_volume_slider->setValue((int)(volume * 100)); +} +void AudioSelectorWidget::refresh_display(AudioOption::AudioDisplayType display){ + switch(display){ + case AudioOption::AudioDisplayType::NO_DISPLAY: + m_audio_vis_box->setCurrentIndex(0); + break; + case AudioOption::AudioDisplayType::FREQ_BARS: + m_audio_vis_box->setCurrentIndex(1); + break; + case AudioOption::AudioDisplayType::SPECTROGRAM: + m_audio_vis_box->setCurrentIndex(2); + break; + default: + m_audio_vis_box->setCurrentIndex(0); + } +} + + +void AudioSelectorWidget::post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ +// cout << "AudioSelectorWidget::input_changed()" << endl; + QMetaObject::invokeMethod(this, [this, device, file, format]{ + refresh_input_device(file, device); + refresh_formats(file, device, format); + }); +} +void AudioSelectorWidget::post_output_change(const AudioDeviceInfo& device){ + QMetaObject::invokeMethod(this, [this, device]{ + refresh_output_device(device); + }); +} +void AudioSelectorWidget::post_volume_change(double volume){ +// if (m_slider_active.load(std::memory_order_acquire)){ +// return; +// } + QMetaObject::invokeMethod(this, [this]{ +// refresh_volume(volume); + refresh_volume(m_session.output_volume()); + }, Qt::QueuedConnection); // Queued due to potential recursive call to the same lock. +} +void AudioSelectorWidget::post_display_change(AudioOption::AudioDisplayType display){ + QMetaObject::invokeMethod(this, [this]{ + refresh_display(m_session.display_type()); + }, Qt::QueuedConnection); // Queued due to potential recursive call to the same lock. +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h index dd67d4d11b..b22f55b9c7 100644 --- a/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h +++ b/SerialPrograms/Source/CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h @@ -1,72 +1,72 @@ -/* Audio Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_AudioPipeline_AudioSelectorWidget_H -#define PokemonAutomation_AudioPipeline_AudioSelectorWidget_H - -#include -#include -#include -#include -#include -#include "CommonFramework/AudioPipeline/AudioOption.h" -#include "CommonFramework/AudioPipeline/AudioSession.h" - -class QComboBox; -class QPushButton; - -namespace PokemonAutomation{ - - -class AudioSelectorWidget : public QWidget, private AudioSession::StateListener{ -public: - AudioSelectorWidget(QWidget& parent, AudioSession& session); - ~AudioSelectorWidget(); - -private: - void build_input_list(const std::string& file, const AudioDeviceInfo& device); - void build_output_list(const AudioDeviceInfo& device); - - void refresh_all(); - void refresh_formats(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format); - void refresh_input_device(const std::string& file, const AudioDeviceInfo& device); - void refresh_output_device(const AudioDeviceInfo& device); - void refresh_volume(double volume); - void refresh_display(AudioOption::AudioDisplayType display); - - virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format) override; - virtual void post_output_change(const AudioDeviceInfo& device) override; - virtual void post_volume_change(double volume) override; - virtual void post_display_change(AudioOption::AudioDisplayType display) override; - -private: - AudioSession& m_session; - - QComboBox* m_audio_input_box = nullptr; - QComboBox* m_audio_format_box = nullptr; - QComboBox* m_audio_output_box = nullptr; - QComboBox* m_audio_vis_box = nullptr; - - QSlider* m_volume_slider = nullptr; - - QPushButton* m_reset_button = nullptr; -// QPushButton* m_load_file_button = nullptr; - std::string m_absoluteFilepath; - QPushButton* m_record_button = nullptr; - bool m_record_is_on = false; - - std::vector m_input_audios; - std::vector m_input_formats; - - std::vector m_output_audios; - - std::mutex m_audio_lock; -// std::atomic m_slider_active; -}; - - -} -#endif +/* Audio Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_AudioPipeline_AudioSelectorWidget_H +#define PokemonAutomation_AudioPipeline_AudioSelectorWidget_H + +#include +#include +#include +#include +#include +#include "CommonFramework/AudioPipeline/AudioOption.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" + +class QComboBox; +class QPushButton; + +namespace PokemonAutomation{ + + +class AudioSelectorWidget : public QWidget, private AudioSession::StateListener{ +public: + AudioSelectorWidget(QWidget& parent, AudioSession& session); + ~AudioSelectorWidget(); + +private: + void build_input_list(const std::string& file, const AudioDeviceInfo& device); + void build_output_list(const AudioDeviceInfo& device); + + void refresh_all(); + void refresh_formats(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format); + void refresh_input_device(const std::string& file, const AudioDeviceInfo& device); + void refresh_output_device(const AudioDeviceInfo& device); + void refresh_volume(double volume); + void refresh_display(AudioOption::AudioDisplayType display); + + virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format) override; + virtual void post_output_change(const AudioDeviceInfo& device) override; + virtual void post_volume_change(double volume) override; + virtual void post_display_change(AudioOption::AudioDisplayType display) override; + +private: + AudioSession& m_session; + + QComboBox* m_audio_input_box = nullptr; + QComboBox* m_audio_format_box = nullptr; + QComboBox* m_audio_output_box = nullptr; + QComboBox* m_audio_vis_box = nullptr; + + QSlider* m_volume_slider = nullptr; + + QPushButton* m_reset_button = nullptr; +// QPushButton* m_load_file_button = nullptr; + std::string m_absoluteFilepath; + QPushButton* m_record_button = nullptr; + bool m_record_is_on = false; + + std::vector m_input_audios; + std::vector m_input_formats; + + std::vector m_output_audios; + + std::mutex m_audio_lock; +// std::atomic m_slider_active; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment.cpp b/SerialPrograms/Source/CommonFramework/Environment/Environment.cpp index 2011e21f0e..5cf275617c 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment.cpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment.cpp @@ -1,39 +1,39 @@ -/* Environment - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/CpuId/CpuId.h" -#include "Environment.h" - -#if _M_IX86 || _M_X64 || __i386__ || __x86_64__ -#include "Environment_x86.tpp" -#endif - -#if _WIN32 -#include "Environment_Windows.tpp" -#ifdef PA_ARCH_x86 -#include "Environment_x86_Windows.tpp" -#endif -#endif - -#if defined(__linux) || defined(__APPLE__) -#include "Environment_Linux.tpp" -#ifdef PA_ARCH_x86 -#include "Environment_x86_Linux.tpp" -#elif PA_ARCH_arm64 -#include "Environment_arm64_Linux.tpp" -#endif -#endif - - -namespace PokemonAutomation{ - - - - - - -} +/* Environment + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/CpuId/CpuId.h" +#include "Environment.h" + +#if _M_IX86 || _M_X64 || __i386__ || __x86_64__ +#include "Environment_x86.tpp" +#endif + +#if _WIN32 +#include "Environment_Windows.tpp" +#ifdef PA_ARCH_x86 +#include "Environment_x86_Windows.tpp" +#endif +#endif + +#if defined(__linux) || defined(__APPLE__) +#include "Environment_Linux.tpp" +#ifdef PA_ARCH_x86 +#include "Environment_x86_Linux.tpp" +#elif PA_ARCH_arm64 +#include "Environment_arm64_Linux.tpp" +#endif +#endif + + +namespace PokemonAutomation{ + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment.h b/SerialPrograms/Source/CommonFramework/Environment/Environment.h index 3501a065a0..f2f5f0b80a 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment.h +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment.h @@ -1,54 +1,54 @@ -/* Environment - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Environment_H -#define PokemonAutomation_Environment_H - -#include -#include -#include "Common/Cpp/Options/EnumDropdownDatabase.h" - -#if _WIN32 -#include "Environment_Windows.h" -#elif defined(__linux) || defined(__APPLE__) -#include "Environment_Linux.h" -#else -#error "Unsupported platform." -#endif - -namespace PokemonAutomation{ - - -const EnumDropdownDatabase& PRIORITY_DATABASE(); - -bool set_thread_priority(ThreadPriority priority); - - -class ThreadHandle; - - - -std::string get_processor_name(); -struct ProcessorSpecs{ - std::string name; - size_t threads = 0; - size_t cores = 0; - size_t sockets = 0; - size_t numa_nodes = 0; - size_t base_frequency = 0; -}; -ProcessorSpecs get_processor_specs(); - - - - - - - - - -} -#endif +/* Environment + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Environment_H +#define PokemonAutomation_Environment_H + +#include +#include +#include "Common/Cpp/Options/EnumDropdownDatabase.h" + +#if _WIN32 +#include "Environment_Windows.h" +#elif defined(__linux) || defined(__APPLE__) +#include "Environment_Linux.h" +#else +#error "Unsupported platform." +#endif + +namespace PokemonAutomation{ + + +const EnumDropdownDatabase& PRIORITY_DATABASE(); + +bool set_thread_priority(ThreadPriority priority); + + +class ThreadHandle; + + + +std::string get_processor_name(); +struct ProcessorSpecs{ + std::string name; + size_t threads = 0; + size_t cores = 0; + size_t sockets = 0; + size_t numa_nodes = 0; + size_t base_frequency = 0; +}; +ProcessorSpecs get_processor_specs(); + + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h index 36aeddf937..1ef30d2167 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.h @@ -1,65 +1,65 @@ -/* Environment (Linux) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Environment_Linux_H -#define PokemonAutomation_Environment_Linux_H - -#include -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -enum class ThreadPriority{ - Max, - Min, -}; - -constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME = ThreadPriority::Max; -constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME_INFERENCE = ThreadPriority::Max; -constexpr ThreadPriority DEFAULT_PRIORITY_NORMAL_INFERENCE = ThreadPriority::Min; -constexpr ThreadPriority DEFAULT_PRIORITY_COMPUTE = ThreadPriority::Min; - - - -class ThreadHandle{ -public: - pthread_t handle; -}; -ThreadHandle current_thread_handle(); -// Get the cpu time of the thread. -// This function must be called in the same process the thread belongs to. -WallClock::duration thread_cpu_time(const ThreadHandle& handle); - - - -class SystemCpuTime{ -public: - static SystemCpuTime now(); - static size_t vcores(); - - bool is_valid() const{ - return m_usec != 0 || m_sec != 0; - } - - std::chrono::microseconds operator-(const SystemCpuTime& x) const; - -private: - void set_to_now(); - static size_t read_cores(); - -private: - time_t m_sec = 0; - suseconds_t m_usec = 0; -}; - - - - -} -#endif +/* Environment (Linux) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Environment_Linux_H +#define PokemonAutomation_Environment_Linux_H + +#include +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +enum class ThreadPriority{ + Max, + Min, +}; + +constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME = ThreadPriority::Max; +constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME_INFERENCE = ThreadPriority::Max; +constexpr ThreadPriority DEFAULT_PRIORITY_NORMAL_INFERENCE = ThreadPriority::Min; +constexpr ThreadPriority DEFAULT_PRIORITY_COMPUTE = ThreadPriority::Min; + + + +class ThreadHandle{ +public: + pthread_t handle; +}; +ThreadHandle current_thread_handle(); +// Get the cpu time of the thread. +// This function must be called in the same process the thread belongs to. +WallClock::duration thread_cpu_time(const ThreadHandle& handle); + + + +class SystemCpuTime{ +public: + static SystemCpuTime now(); + static size_t vcores(); + + bool is_valid() const{ + return m_usec != 0 || m_sec != 0; + } + + std::chrono::microseconds operator-(const SystemCpuTime& x) const; + +private: + void set_to_now(); + static size_t read_cores(); + +private: + time_t m_sec = 0; + suseconds_t m_usec = 0; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp index 0cab243343..98dcf13cc5 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Linux.tpp @@ -1,145 +1,145 @@ -/* Environment (Linux) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#if defined(__linux) || defined(__APPLE__) - -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "Environment.h" - -#if defined(__APPLE__) -#include -#endif - -// #include - - -namespace PokemonAutomation{ - - - - -const EnumDropdownDatabase& PRIORITY_DATABASE(){ - static EnumDropdownDatabase database({ - {ThreadPriority::Max, "max", "Max Priority"}, - {ThreadPriority::Min, "min", "Min Priority"}, - }); - return database; -} - -bool set_thread_priority(ThreadPriority priority){ - int native_priority = sched_get_priority_min(SCHED_RR); - switch (priority){ - case ThreadPriority::Max: - native_priority = sched_get_priority_max(SCHED_RR); - break; - case ThreadPriority::Min: - native_priority = sched_get_priority_min(SCHED_RR); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Priority Index: " + std::to_string((int)priority)); - } - - struct sched_param param; - param.sched_priority = native_priority; - if (pthread_setschedparam(pthread_self(), SCHED_RR, ¶m) == 0){ - return true; - } - - int errorcode = errno; - global_logger_tagged().log("Unable to set process priority. Error Code = " + std::to_string(errorcode), COLOR_RED); - return false; -} - - - - - -ThreadHandle current_thread_handle(){ - return ThreadHandle{pthread_self()}; -} -WallClock::duration thread_cpu_time(const ThreadHandle& handle){ - uint64_t nanos = 0; - -#if defined(__APPLE__) - uint64_t tid = 0; - pthread_threadid_np(handle.handle, &tid); - struct proc_threadinfo pth; - if (PROC_PIDTHREADINFO_SIZE == - proc_pidinfo(getpid(), PROC_PIDTHREADID64INFO, tid, &pth, - PROC_PIDTHREADINFO_SIZE)) { - nanos = pth.pth_user_time + pth.pth_system_time; // user time + system time in ns - } - else{ - return WallClock::duration::min(); - } - -#else - clockid_t clockid; - int error = pthread_getcpuclockid(handle.handle, &clockid); - if (error){ - return WallClock::duration::min(); - } - - struct timespec ts; - if (clock_gettime(clockid, &ts) == -1){ - return WallClock::duration::min(); - } - - nanos = (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; -#endif - - return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); -} - - - - - - -std::chrono::microseconds SystemCpuTime::operator-(const SystemCpuTime& x) const{ - return std::chrono::microseconds((m_sec - x.m_sec) * 1000000ull + (m_usec - x.m_usec)); -} -SystemCpuTime SystemCpuTime::now(){ - SystemCpuTime ret; - ret.set_to_now(); - return ret; -} -size_t SystemCpuTime::vcores(){ - static size_t cores = read_cores(); - return cores; -} -void SystemCpuTime::set_to_now(){ - struct rusage ru; - if (getrusage(RUSAGE_SELF, &ru) == -1){ - m_sec = 0; - m_usec = 0; - }else{ - m_sec = ru.ru_utime.tv_sec + ru.ru_stime.tv_sec; - m_usec = ru.ru_utime.tv_usec + ru.ru_stime.tv_usec; - } -} -size_t SystemCpuTime::read_cores(){ - return std::thread::hardware_concurrency(); -} - - - - - - - - -} -#endif +/* Environment (Linux) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#if defined(__linux) || defined(__APPLE__) + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "Environment.h" + +#if defined(__APPLE__) +#include +#endif + +// #include + + +namespace PokemonAutomation{ + + + + +const EnumDropdownDatabase& PRIORITY_DATABASE(){ + static EnumDropdownDatabase database({ + {ThreadPriority::Max, "max", "Max Priority"}, + {ThreadPriority::Min, "min", "Min Priority"}, + }); + return database; +} + +bool set_thread_priority(ThreadPriority priority){ + int native_priority = sched_get_priority_min(SCHED_RR); + switch (priority){ + case ThreadPriority::Max: + native_priority = sched_get_priority_max(SCHED_RR); + break; + case ThreadPriority::Min: + native_priority = sched_get_priority_min(SCHED_RR); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Priority Index: " + std::to_string((int)priority)); + } + + struct sched_param param; + param.sched_priority = native_priority; + if (pthread_setschedparam(pthread_self(), SCHED_RR, ¶m) == 0){ + return true; + } + + int errorcode = errno; + global_logger_tagged().log("Unable to set process priority. Error Code = " + std::to_string(errorcode), COLOR_RED); + return false; +} + + + + + +ThreadHandle current_thread_handle(){ + return ThreadHandle{pthread_self()}; +} +WallClock::duration thread_cpu_time(const ThreadHandle& handle){ + uint64_t nanos = 0; + +#if defined(__APPLE__) + uint64_t tid = 0; + pthread_threadid_np(handle.handle, &tid); + struct proc_threadinfo pth; + if (PROC_PIDTHREADINFO_SIZE == + proc_pidinfo(getpid(), PROC_PIDTHREADID64INFO, tid, &pth, + PROC_PIDTHREADINFO_SIZE)) { + nanos = pth.pth_user_time + pth.pth_system_time; // user time + system time in ns + } + else{ + return WallClock::duration::min(); + } + +#else + clockid_t clockid; + int error = pthread_getcpuclockid(handle.handle, &clockid); + if (error){ + return WallClock::duration::min(); + } + + struct timespec ts; + if (clock_gettime(clockid, &ts) == -1){ + return WallClock::duration::min(); + } + + nanos = (uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec; +#endif + + return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); +} + + + + + + +std::chrono::microseconds SystemCpuTime::operator-(const SystemCpuTime& x) const{ + return std::chrono::microseconds((m_sec - x.m_sec) * 1000000ull + (m_usec - x.m_usec)); +} +SystemCpuTime SystemCpuTime::now(){ + SystemCpuTime ret; + ret.set_to_now(); + return ret; +} +size_t SystemCpuTime::vcores(){ + static size_t cores = read_cores(); + return cores; +} +void SystemCpuTime::set_to_now(){ + struct rusage ru; + if (getrusage(RUSAGE_SELF, &ru) == -1){ + m_sec = 0; + m_usec = 0; + }else{ + m_sec = ru.ru_utime.tv_sec + ru.ru_stime.tv_sec; + m_usec = ru.ru_utime.tv_usec + ru.ru_stime.tv_usec; + } +} +size_t SystemCpuTime::read_cores(){ + return std::thread::hardware_concurrency(); +} + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h index 2be6b3cce3..31c6f646bf 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.h @@ -1,87 +1,87 @@ -/* Environment (Windows) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Environment_Windows_H -#define PokemonAutomation_Environment_Windows_H - -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -enum class ThreadPriority{ - Realtime, - High, - AboveNormal, - Normal, - BelowNormal, - Low, -}; - -constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME = ThreadPriority::High; -constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME_INFERENCE = ThreadPriority::AboveNormal; -constexpr ThreadPriority DEFAULT_PRIORITY_NORMAL_INFERENCE = ThreadPriority::BelowNormal; -constexpr ThreadPriority DEFAULT_PRIORITY_COMPUTE = ThreadPriority::BelowNormal; - - - - - -class WinApiHandleHolder; - -class ThreadHandle{ -public: - ThreadHandle(ThreadHandle&& x); - ThreadHandle& operator=(ThreadHandle&& x); - ThreadHandle(const ThreadHandle& x); - ThreadHandle& operator=(const ThreadHandle& x); - ~ThreadHandle(); - - ThreadHandle(std::shared_ptr ptr = nullptr); - - std::shared_ptr m_ptr; -}; -ThreadHandle current_thread_handle(); -WallClock::duration thread_cpu_time(const ThreadHandle& handle); - - - - - -class SystemCpuTime{ -public: - static SystemCpuTime now(); - static size_t vcores(); - - bool is_valid() const{ - return m_kernel != 0; - } - - std::chrono::microseconds operator-(const SystemCpuTime& x) const{ - uint64_t idle = m_idle - x.m_idle; - uint64_t kernel = m_kernel - x.m_kernel; - uint64_t user = m_user - x.m_user; - uint64_t total_utilization = kernel + user - idle; - return std::chrono::microseconds(total_utilization / 10); - } - -private: - void set_to_now(); - static size_t read_cores(); - -private: - uint64_t m_idle = 0; - uint64_t m_kernel = 0; - uint64_t m_user = 0; -}; - - - - - -} -#endif +/* Environment (Windows) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Environment_Windows_H +#define PokemonAutomation_Environment_Windows_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +enum class ThreadPriority{ + Realtime, + High, + AboveNormal, + Normal, + BelowNormal, + Low, +}; + +constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME = ThreadPriority::High; +constexpr ThreadPriority DEFAULT_PRIORITY_REALTIME_INFERENCE = ThreadPriority::AboveNormal; +constexpr ThreadPriority DEFAULT_PRIORITY_NORMAL_INFERENCE = ThreadPriority::BelowNormal; +constexpr ThreadPriority DEFAULT_PRIORITY_COMPUTE = ThreadPriority::BelowNormal; + + + + + +class WinApiHandleHolder; + +class ThreadHandle{ +public: + ThreadHandle(ThreadHandle&& x); + ThreadHandle& operator=(ThreadHandle&& x); + ThreadHandle(const ThreadHandle& x); + ThreadHandle& operator=(const ThreadHandle& x); + ~ThreadHandle(); + + ThreadHandle(std::shared_ptr ptr = nullptr); + + std::shared_ptr m_ptr; +}; +ThreadHandle current_thread_handle(); +WallClock::duration thread_cpu_time(const ThreadHandle& handle); + + + + + +class SystemCpuTime{ +public: + static SystemCpuTime now(); + static size_t vcores(); + + bool is_valid() const{ + return m_kernel != 0; + } + + std::chrono::microseconds operator-(const SystemCpuTime& x) const{ + uint64_t idle = m_idle - x.m_idle; + uint64_t kernel = m_kernel - x.m_kernel; + uint64_t user = m_user - x.m_user; + uint64_t total_utilization = kernel + user - idle; + return std::chrono::microseconds(total_utilization / 10); + } + +private: + void set_to_now(); + static size_t read_cores(); + +private: + uint64_t m_idle = 0; + uint64_t m_kernel = 0; + uint64_t m_user = 0; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp index 6da3b651cc..28efededb0 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_Windows.tpp @@ -1,197 +1,197 @@ -/* Environment (Windows) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifdef _WIN32 - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "Environment.h" -#include "Environment_Windows.h" - -#if __GNUC__ -#ifndef cpuid_H -#define cpuid_H -#include -#endif -#endif - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -class WinApiHandleHolder{ -public: - WinApiHandleHolder(const WinApiHandleHolder& x) = delete; - void operator=(const WinApiHandleHolder& x) = delete; - ~WinApiHandleHolder(){ - CloseHandle(m_handle); - } - WinApiHandleHolder(HANDLE handle) - : m_handle(handle) - {} - operator HANDLE() const{ - return m_handle; - } - -private: - HANDLE m_handle; -}; - - - - -const EnumDropdownDatabase& PRIORITY_DATABASE(){ - static EnumDropdownDatabase database({ - {ThreadPriority::Realtime, "realtime", "Realtime"}, - {ThreadPriority::High, "high", "High"}, - {ThreadPriority::AboveNormal, "above-normal", "Above Normal"}, - {ThreadPriority::Normal, "normal", "Normal"}, - {ThreadPriority::BelowNormal, "below-normal", "Below Normal"}, - {ThreadPriority::Low, "low", "Low"}, - }); - return database; -} - -bool set_thread_priority(ThreadPriority priority){ - DWORD native_priority; - switch (priority){ - case ThreadPriority::Realtime: - native_priority = REALTIME_PRIORITY_CLASS; - break; - case ThreadPriority::High: - native_priority = HIGH_PRIORITY_CLASS; - break; - case ThreadPriority::AboveNormal: - native_priority = ABOVE_NORMAL_PRIORITY_CLASS; - break; - case ThreadPriority::Normal: - native_priority = NORMAL_PRIORITY_CLASS; - break; - case ThreadPriority::BelowNormal: - native_priority = BELOW_NORMAL_PRIORITY_CLASS; - break; - case ThreadPriority::Low: - native_priority = IDLE_PRIORITY_CLASS; - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Priority: " + std::to_string((int)priority)); - } - if (SetPriorityClass(GetCurrentProcess(), native_priority)){ -// cout << "Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display << endl; - global_logger_tagged().log("Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display, COLOR_BLUE); - return true; - } - DWORD error = GetLastError(); - global_logger_tagged().log("Unable to set process priority. Error Code = " + std::to_string(error), COLOR_RED); - return false; -} - - - - -ThreadHandle::ThreadHandle(ThreadHandle&& x) = default; -ThreadHandle& ThreadHandle::operator=(ThreadHandle&& x) = default; -ThreadHandle::ThreadHandle(const ThreadHandle& x) = default; -ThreadHandle& ThreadHandle::operator=(const ThreadHandle& x) = default; -ThreadHandle::~ThreadHandle() = default; -ThreadHandle::ThreadHandle(std::shared_ptr ptr) - : m_ptr(std::move(ptr)) -{} - - - -ThreadHandle current_thread_handle(){ - DWORD id = GetCurrentThreadId(); - HANDLE handle = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, id); -// cout << handle << endl; - if (handle == NULL){ - return ThreadHandle(); - } - return ThreadHandle{std::make_shared(handle)}; -} -WallClock::duration thread_cpu_time(const ThreadHandle& handle){ - FILETIME creation_time; - FILETIME exit_time; - FILETIME kernel_time; - FILETIME user_time; - - if (!handle.m_ptr){ - return WallClock::duration::min(); - } - - if (!GetThreadTimes(*handle.m_ptr, &creation_time, &exit_time, &kernel_time, &user_time)){ - return WallClock::duration::min(); - } - - uint64_t nanos = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); - nanos *= 100; - return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); -} - - - - - - - - -SystemCpuTime SystemCpuTime::now(){ - SystemCpuTime ret; - ret.set_to_now(); - return ret; -} -size_t SystemCpuTime::vcores(){ - static size_t cores = read_cores(); - return cores; -} -void SystemCpuTime::set_to_now(){ - FILETIME idle_time, kernel_time, user_time; - if (GetSystemTimes(&idle_time, &kernel_time, &user_time)){ - m_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); - m_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); - m_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); - }else{ - m_idle = 0; - m_kernel = 0; - m_user = 0; - } -} -size_t SystemCpuTime::read_cores(){ - size_t cores = 0; - WORD total_groups = GetActiveProcessorGroupCount(); - for (WORD group = 0; group < total_groups; group++){ - DWORD processors_within_group = GetActiveProcessorCount(group); - cores += processors_within_group; - } - return cores; -} - - - - - - - - - - - - - - - - - -} -#endif +/* Environment (Windows) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifdef _WIN32 + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "Environment.h" +#include "Environment_Windows.h" + +#if __GNUC__ +#ifndef cpuid_H +#define cpuid_H +#include +#endif +#endif + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +class WinApiHandleHolder{ +public: + WinApiHandleHolder(const WinApiHandleHolder& x) = delete; + void operator=(const WinApiHandleHolder& x) = delete; + ~WinApiHandleHolder(){ + CloseHandle(m_handle); + } + WinApiHandleHolder(HANDLE handle) + : m_handle(handle) + {} + operator HANDLE() const{ + return m_handle; + } + +private: + HANDLE m_handle; +}; + + + + +const EnumDropdownDatabase& PRIORITY_DATABASE(){ + static EnumDropdownDatabase database({ + {ThreadPriority::Realtime, "realtime", "Realtime"}, + {ThreadPriority::High, "high", "High"}, + {ThreadPriority::AboveNormal, "above-normal", "Above Normal"}, + {ThreadPriority::Normal, "normal", "Normal"}, + {ThreadPriority::BelowNormal, "below-normal", "Below Normal"}, + {ThreadPriority::Low, "low", "Low"}, + }); + return database; +} + +bool set_thread_priority(ThreadPriority priority){ + DWORD native_priority; + switch (priority){ + case ThreadPriority::Realtime: + native_priority = REALTIME_PRIORITY_CLASS; + break; + case ThreadPriority::High: + native_priority = HIGH_PRIORITY_CLASS; + break; + case ThreadPriority::AboveNormal: + native_priority = ABOVE_NORMAL_PRIORITY_CLASS; + break; + case ThreadPriority::Normal: + native_priority = NORMAL_PRIORITY_CLASS; + break; + case ThreadPriority::BelowNormal: + native_priority = BELOW_NORMAL_PRIORITY_CLASS; + break; + case ThreadPriority::Low: + native_priority = IDLE_PRIORITY_CLASS; + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Priority: " + std::to_string((int)priority)); + } + if (SetPriorityClass(GetCurrentProcess(), native_priority)){ +// cout << "Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display << endl; + global_logger_tagged().log("Thread priority set to: " + PRIORITY_DATABASE().find(priority)->display, COLOR_BLUE); + return true; + } + DWORD error = GetLastError(); + global_logger_tagged().log("Unable to set process priority. Error Code = " + std::to_string(error), COLOR_RED); + return false; +} + + + + +ThreadHandle::ThreadHandle(ThreadHandle&& x) = default; +ThreadHandle& ThreadHandle::operator=(ThreadHandle&& x) = default; +ThreadHandle::ThreadHandle(const ThreadHandle& x) = default; +ThreadHandle& ThreadHandle::operator=(const ThreadHandle& x) = default; +ThreadHandle::~ThreadHandle() = default; +ThreadHandle::ThreadHandle(std::shared_ptr ptr) + : m_ptr(std::move(ptr)) +{} + + + +ThreadHandle current_thread_handle(){ + DWORD id = GetCurrentThreadId(); + HANDLE handle = OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, id); +// cout << handle << endl; + if (handle == NULL){ + return ThreadHandle(); + } + return ThreadHandle{std::make_shared(handle)}; +} +WallClock::duration thread_cpu_time(const ThreadHandle& handle){ + FILETIME creation_time; + FILETIME exit_time; + FILETIME kernel_time; + FILETIME user_time; + + if (!handle.m_ptr){ + return WallClock::duration::min(); + } + + if (!GetThreadTimes(*handle.m_ptr, &creation_time, &exit_time, &kernel_time, &user_time)){ + return WallClock::duration::min(); + } + + uint64_t nanos = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); + nanos *= 100; + return std::chrono::duration_cast(std::chrono::nanoseconds(nanos)); +} + + + + + + + + +SystemCpuTime SystemCpuTime::now(){ + SystemCpuTime ret; + ret.set_to_now(); + return ret; +} +size_t SystemCpuTime::vcores(){ + static size_t cores = read_cores(); + return cores; +} +void SystemCpuTime::set_to_now(){ + FILETIME idle_time, kernel_time, user_time; + if (GetSystemTimes(&idle_time, &kernel_time, &user_time)){ + m_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); + m_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); + m_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); + }else{ + m_idle = 0; + m_kernel = 0; + m_user = 0; + } +} +size_t SystemCpuTime::read_cores(){ + size_t cores = 0; + WORD total_groups = GetActiveProcessorGroupCount(); + for (WORD group = 0; group < total_groups; group++){ + DWORD processors_within_group = GetActiveProcessorCount(group); + cores += processors_within_group; + } + return cores; +} + + + + + + + + + + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_arm64_Linux.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_arm64_Linux.tpp index 40a095bb3d..d93c640582 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_arm64_Linux.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_arm64_Linux.tpp @@ -1,51 +1,51 @@ -/* Environment (arm64 Linux) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - * Currently only used for M-series Apple environment - */ - - -#include -#include -#include - -#include "Environment.h" - -namespace PokemonAutomation{ - - -uint64_t get_cpu_freq() -{ - uint64_t freq = 0; - size_t size = sizeof(freq); - - if (sysctlbyname("hw.cpufrequency", &freq, &size, NULL, 0) < 0) - { - perror("sysctl"); - } - return freq; -} - -std::string get_processor_name(){ - char name_buffer[100] = ""; - size_t size = 100; - if (sysctlbyname("machdep.cpu.brand_string", name_buffer, &size, NULL, 0) < 0) - { - perror("sysctl"); - } - return name_buffer; -} - - -ProcessorSpecs get_processor_specs(){ - ProcessorSpecs specs; - specs.name = get_processor_name(); - specs.base_frequency = get_cpu_freq(); - specs.threads = std::thread::hardware_concurrency(); - - return specs; -} - - -} +/* Environment (arm64 Linux) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + * Currently only used for M-series Apple environment + */ + + +#include +#include +#include + +#include "Environment.h" + +namespace PokemonAutomation{ + + +uint64_t get_cpu_freq() +{ + uint64_t freq = 0; + size_t size = sizeof(freq); + + if (sysctlbyname("hw.cpufrequency", &freq, &size, NULL, 0) < 0) + { + perror("sysctl"); + } + return freq; +} + +std::string get_processor_name(){ + char name_buffer[100] = ""; + size_t size = 100; + if (sysctlbyname("machdep.cpu.brand_string", name_buffer, &size, NULL, 0) < 0) + { + perror("sysctl"); + } + return name_buffer; +} + + +ProcessorSpecs get_processor_specs(){ + ProcessorSpecs specs; + specs.name = get_processor_name(); + specs.base_frequency = get_cpu_freq(); + specs.threads = std::thread::hardware_concurrency(); + + return specs; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86.tpp index 597ae03e47..2a4ade7697 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86.tpp @@ -1,52 +1,52 @@ -/* Environment (x86) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/CpuId/CpuId_x86.h" -#include "Environment.h" - -namespace PokemonAutomation{ - - -uint64_t x86_measure_rdtsc_ticks_per_sec(); - - -void x86_CleanCPUName(char name[49]){ - size_t c0 = 0; - size_t c1 = 0; - bool space_flag = true; - while (c1 < 48){ - if (space_flag && name[c1] == ' '){ - c1++; - continue; - } - space_flag = name[c1] == ' '; - name[c0++] = name[c1++]; - } - - while (c0 < 48){ - name[c0++] = '\0'; - } -} -std::string get_processor_name(){ - union{ - uint32_t reg[12]; - char name[49]; - }; - x86_cpuid(reg + 0, 0x80000002, 0); - x86_cpuid(reg + 4, 0x80000003, 0); - x86_cpuid(reg + 8, 0x80000004, 0); - - x86_CleanCPUName(name); - return name; -} -uint64_t x86_rdtsc_ticks_per_sec(){ - static uint64_t cached = x86_measure_rdtsc_ticks_per_sec(); - return cached; -} - - - -} +/* Environment (x86) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/CpuId/CpuId_x86.h" +#include "Environment.h" + +namespace PokemonAutomation{ + + +uint64_t x86_measure_rdtsc_ticks_per_sec(); + + +void x86_CleanCPUName(char name[49]){ + size_t c0 = 0; + size_t c1 = 0; + bool space_flag = true; + while (c1 < 48){ + if (space_flag && name[c1] == ' '){ + c1++; + continue; + } + space_flag = name[c1] == ' '; + name[c0++] = name[c1++]; + } + + while (c0 < 48){ + name[c0++] = '\0'; + } +} +std::string get_processor_name(){ + union{ + uint32_t reg[12]; + char name[49]; + }; + x86_cpuid(reg + 0, 0x80000002, 0); + x86_cpuid(reg + 4, 0x80000003, 0); + x86_cpuid(reg + 8, 0x80000004, 0); + + x86_CleanCPUName(name); + return name; +} +uint64_t x86_rdtsc_ticks_per_sec(){ + static uint64_t cached = x86_measure_rdtsc_ticks_per_sec(); + return cached; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Linux.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Linux.tpp index 861fbbce23..3ac1d97556 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Linux.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Linux.tpp @@ -1,121 +1,121 @@ -/* Environment (x86 Linux) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Time.h" -#include "CommonFramework/Logging/Logger.h" -#include "Environment.h" - -#ifndef cpuid_H -#define cpuid_H -#include -#endif - -#include "Environment.h" - -namespace PokemonAutomation{ - - -uint64_t x86_rdtsc(){ - unsigned int lo, hi; - __asm__ volatile ("rdtsc" : "=a" (lo), "=d" (hi)); - return ((uint64_t)hi << 32) | lo; -} - - - -uint64_t x86_measure_rdtsc_ticks_per_sec(){ -// Time::WallClock w_start = Time::WallClock::Now(); - auto w_start = current_time(); - uint64_t r_start = x86_rdtsc(); - while (current_time() - w_start < std::chrono::microseconds(62500)); - auto w_end = current_time(); -// while (w_start.SecondsElapsed() < 0.0625); -// Time::WallClock w_end = Time::WallClock::Now(); - uint64_t r_end = x86_rdtsc(); - - auto elapsed = std::chrono::duration_cast(w_end - w_start); - double seconds = (double)elapsed.count() / 1000000.; - - return (uint64_t)((double)(r_end - r_start) / seconds); -} - - - - - -ProcessorSpecs get_processor_specs(){ - ProcessorSpecs specs; - specs.name = get_processor_name(); - specs.base_frequency = x86_rdtsc_ticks_per_sec(); - specs.threads = std::thread::hardware_concurrency(); - -#ifdef __linux - // Cores + Sockets - { -// std::set cores; - std::set sockets; - - int current_socket = 0; - std::map> cores_per_socket; - - std::ifstream file("/proc/cpuinfo"); - std::string line; - while (std::getline(file, line)){ - if (line.find("physical id") == 0){ - size_t pos = line.find(": "); - if (pos == std::string::npos){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Unable to parse: /proc/cpuinfo"); - } - current_socket = atoi(&line[pos + 2]); - sockets.insert(current_socket); - } - if (line.find("core id") == 0){ - size_t pos = line.find(": "); - if (pos == std::string::npos){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Unable to parse: /proc/cpuinfo"); - } -// specs.threads++; - int core = atoi(&line[pos + 2]); - cores_per_socket[current_socket].insert(core); -// cores.insert(core); - } - } - specs.sockets = sockets.size(); - specs.cores = 0; - for (const auto& socket : cores_per_socket){ - specs.cores += socket.second.size(); - } - } - - // NUMA Nodes - { - std::set nodes; - - std::ifstream file("/proc/zoneinfo"); - std::string line; - while (std::getline(file, line)){ - if (line.find("Node ") == 0){ - nodes.insert(atoi(&line[5])); - } - } - specs.numa_nodes = nodes.size(); - } -#endif - - return specs; -} - - -} +/* Environment (x86 Linux) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/Logging/Logger.h" +#include "Environment.h" + +#ifndef cpuid_H +#define cpuid_H +#include +#endif + +#include "Environment.h" + +namespace PokemonAutomation{ + + +uint64_t x86_rdtsc(){ + unsigned int lo, hi; + __asm__ volatile ("rdtsc" : "=a" (lo), "=d" (hi)); + return ((uint64_t)hi << 32) | lo; +} + + + +uint64_t x86_measure_rdtsc_ticks_per_sec(){ +// Time::WallClock w_start = Time::WallClock::Now(); + auto w_start = current_time(); + uint64_t r_start = x86_rdtsc(); + while (current_time() - w_start < std::chrono::microseconds(62500)); + auto w_end = current_time(); +// while (w_start.SecondsElapsed() < 0.0625); +// Time::WallClock w_end = Time::WallClock::Now(); + uint64_t r_end = x86_rdtsc(); + + auto elapsed = std::chrono::duration_cast(w_end - w_start); + double seconds = (double)elapsed.count() / 1000000.; + + return (uint64_t)((double)(r_end - r_start) / seconds); +} + + + + + +ProcessorSpecs get_processor_specs(){ + ProcessorSpecs specs; + specs.name = get_processor_name(); + specs.base_frequency = x86_rdtsc_ticks_per_sec(); + specs.threads = std::thread::hardware_concurrency(); + +#ifdef __linux + // Cores + Sockets + { +// std::set cores; + std::set sockets; + + int current_socket = 0; + std::map> cores_per_socket; + + std::ifstream file("/proc/cpuinfo"); + std::string line; + while (std::getline(file, line)){ + if (line.find("physical id") == 0){ + size_t pos = line.find(": "); + if (pos == std::string::npos){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Unable to parse: /proc/cpuinfo"); + } + current_socket = atoi(&line[pos + 2]); + sockets.insert(current_socket); + } + if (line.find("core id") == 0){ + size_t pos = line.find(": "); + if (pos == std::string::npos){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Unable to parse: /proc/cpuinfo"); + } +// specs.threads++; + int core = atoi(&line[pos + 2]); + cores_per_socket[current_socket].insert(core); +// cores.insert(core); + } + } + specs.sockets = sockets.size(); + specs.cores = 0; + for (const auto& socket : cores_per_socket){ + specs.cores += socket.second.size(); + } + } + + // NUMA Nodes + { + std::set nodes; + + std::ifstream file("/proc/zoneinfo"); + std::string line; + while (std::getline(file, line)){ + if (line.find("Node ") == 0){ + nodes.insert(atoi(&line[5])); + } + } + specs.numa_nodes = nodes.size(); + } +#endif + + return specs; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp index d4e44f343d..963cf1a796 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/Environment_x86_Windows.tpp @@ -1,139 +1,139 @@ -/* Environment (x86 Windows) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include - -#if __GNUC__ -#ifndef cpuid_H -#define cpuid_H -#include -#endif -#endif - -#include "Common/Cpp/Exceptions.h" -#include "Environment.h" - -namespace PokemonAutomation{ - - -uint64_t x86_rdtsc(){ - return __rdtsc(); -} - - -uint64_t x86_measure_rdtsc_ticks_per_sec(){ - HANDLE thread = GetCurrentThread(); - - GROUP_AFFINITY before_affinity; - if (GetThreadGroupAffinity(thread, &before_affinity) == 0){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "GetThreadGroupAffinity() failed: Unable to read thread affinity."); - } - - KAFFINITY t = 1; - while ((t & before_affinity.Mask) == 0){ - t <<= 1; - } - - GROUP_AFFINITY placeholder; - GROUP_AFFINITY new_affinity = before_affinity; - new_affinity.Mask = t; - if (SetThreadGroupAffinity(thread, &new_affinity, &placeholder) == 0){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "SetThreadGroupAffinity() failed: Unable to set Affinity Mask."); - - } - - LARGE_INTEGER frequency; - if (!QueryPerformanceFrequency(&frequency)){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "QueryPerformanceFrequency() failed: Unable to measure clock speed."); - } - uint64_t freq = frequency.QuadPart; - freq >>= 4; - - - uint64_t start_cycles = __rdtsc(); - - LARGE_INTEGER start_timer; - if (!QueryPerformanceCounter(&start_timer)){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "QueryPerformanceCounter() failed: Unable to measure clock speed."); - } - LARGE_INTEGER current_timer; - do { - if (!QueryPerformanceCounter(¤t_timer)){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "QueryPerformanceCounter() failed: Unable to measure clock speed."); - } - }while ((uint64_t)current_timer.QuadPart - (uint64_t)start_timer.QuadPart < freq); - - uint64_t end_cycles = __rdtsc(); - - if (SetThreadGroupAffinity(thread, &before_affinity, &placeholder) == 0){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "SetThreadGroupAffinity() failed: Unable to set Affinity Mask."); - } - - double cycle_dif = (double)(end_cycles - start_cycles); - double timer_dif = (double)((uint64_t)current_timer.QuadPart - (uint64_t)start_timer.QuadPart); - - return (uint64_t)(cycle_dif / timer_dif * frequency.QuadPart); -} - - - - - -ProcessorSpecs get_processor_specs(){ - ProcessorSpecs specs; - specs.name = get_processor_name(); - specs.base_frequency = x86_rdtsc_ticks_per_sec(); - - DWORD bytes = 0; - GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP::RelationAll, nullptr, &bytes); - if (GetLastError() != ERROR_INSUFFICIENT_BUFFER){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "GetLogicalProcessorInformationEx() failed."); - } - - std::vector ptr(bytes); - if (!GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP::RelationAll, (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)ptr.data(), &bytes)){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "GetLogicalProcessorInformationEx() failed."); - } - - std::map group_masks; - - for (size_t c = 0; c < bytes;){ - const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX& info = *(const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(ptr.data() + c); - switch (info.Relationship){ - case LOGICAL_PROCESSOR_RELATIONSHIP::RelationProcessorCore: - for (size_t g = 0; g < info.Processor.GroupCount; g++){ - const GROUP_AFFINITY& affinity = info.Processor.GroupMask[g]; - group_masks[affinity.Group] |= affinity.Mask; - } - specs.cores++; - break; - case LOGICAL_PROCESSOR_RELATIONSHIP::RelationProcessorPackage: - specs.sockets++; - break; - case LOGICAL_PROCESSOR_RELATIONSHIP::RelationNumaNode: - specs.numa_nodes++; - break; - default:; - } - c += info.Size; - } - - if (group_masks.size() == 0){ - specs.threads = std::thread::hardware_concurrency(); - }else{ - for (const auto& group : group_masks){ - specs.threads += _mm_popcnt_u64(group.second); - } - } - - return specs; -} - - - - - -} +/* Environment (x86 Windows) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include + +#if __GNUC__ +#ifndef cpuid_H +#define cpuid_H +#include +#endif +#endif + +#include "Common/Cpp/Exceptions.h" +#include "Environment.h" + +namespace PokemonAutomation{ + + +uint64_t x86_rdtsc(){ + return __rdtsc(); +} + + +uint64_t x86_measure_rdtsc_ticks_per_sec(){ + HANDLE thread = GetCurrentThread(); + + GROUP_AFFINITY before_affinity; + if (GetThreadGroupAffinity(thread, &before_affinity) == 0){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "GetThreadGroupAffinity() failed: Unable to read thread affinity."); + } + + KAFFINITY t = 1; + while ((t & before_affinity.Mask) == 0){ + t <<= 1; + } + + GROUP_AFFINITY placeholder; + GROUP_AFFINITY new_affinity = before_affinity; + new_affinity.Mask = t; + if (SetThreadGroupAffinity(thread, &new_affinity, &placeholder) == 0){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "SetThreadGroupAffinity() failed: Unable to set Affinity Mask."); + + } + + LARGE_INTEGER frequency; + if (!QueryPerformanceFrequency(&frequency)){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "QueryPerformanceFrequency() failed: Unable to measure clock speed."); + } + uint64_t freq = frequency.QuadPart; + freq >>= 4; + + + uint64_t start_cycles = __rdtsc(); + + LARGE_INTEGER start_timer; + if (!QueryPerformanceCounter(&start_timer)){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "QueryPerformanceCounter() failed: Unable to measure clock speed."); + } + LARGE_INTEGER current_timer; + do { + if (!QueryPerformanceCounter(¤t_timer)){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "QueryPerformanceCounter() failed: Unable to measure clock speed."); + } + }while ((uint64_t)current_timer.QuadPart - (uint64_t)start_timer.QuadPart < freq); + + uint64_t end_cycles = __rdtsc(); + + if (SetThreadGroupAffinity(thread, &before_affinity, &placeholder) == 0){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "SetThreadGroupAffinity() failed: Unable to set Affinity Mask."); + } + + double cycle_dif = (double)(end_cycles - start_cycles); + double timer_dif = (double)((uint64_t)current_timer.QuadPart - (uint64_t)start_timer.QuadPart); + + return (uint64_t)(cycle_dif / timer_dif * frequency.QuadPart); +} + + + + + +ProcessorSpecs get_processor_specs(){ + ProcessorSpecs specs; + specs.name = get_processor_name(); + specs.base_frequency = x86_rdtsc_ticks_per_sec(); + + DWORD bytes = 0; + GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP::RelationAll, nullptr, &bytes); + if (GetLastError() != ERROR_INSUFFICIENT_BUFFER){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "GetLogicalProcessorInformationEx() failed."); + } + + std::vector ptr(bytes); + if (!GetLogicalProcessorInformationEx(LOGICAL_PROCESSOR_RELATIONSHIP::RelationAll, (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)ptr.data(), &bytes)){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "GetLogicalProcessorInformationEx() failed."); + } + + std::map group_masks; + + for (size_t c = 0; c < bytes;){ + const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX& info = *(const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*)(ptr.data() + c); + switch (info.Relationship){ + case LOGICAL_PROCESSOR_RELATIONSHIP::RelationProcessorCore: + for (size_t g = 0; g < info.Processor.GroupCount; g++){ + const GROUP_AFFINITY& affinity = info.Processor.GroupMask[g]; + group_masks[affinity.Group] |= affinity.Mask; + } + specs.cores++; + break; + case LOGICAL_PROCESSOR_RELATIONSHIP::RelationProcessorPackage: + specs.sockets++; + break; + case LOGICAL_PROCESSOR_RELATIONSHIP::RelationNumaNode: + specs.numa_nodes++; + break; + default:; + } + c += info.Size; + } + + if (group_masks.size() == 0){ + specs.threads = std::thread::hardware_concurrency(); + }else{ + for (const auto& group : group_masks){ + specs.threads += _mm_popcnt_u64(group.second); + } + } + + return specs; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.cpp b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.cpp index 8f3c9293c9..84ec1be4f0 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.cpp +++ b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.cpp @@ -1,20 +1,20 @@ -/* Hardware Validation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" - -#ifdef PA_ARCH_x86 -#include "HardwareValidation_x86.tpp" -#elif PA_ARCH_arm64 -#include "HardwareValidation_arm64.tpp" -#else -#warning "No hardware validation for this architecture." -namespace PokemonAutomation{ - bool check_hardware(){ - return true; - } -} -#endif +/* Hardware Validation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" + +#ifdef PA_ARCH_x86 +#include "HardwareValidation_x86.tpp" +#elif PA_ARCH_arm64 +#include "HardwareValidation_arm64.tpp" +#else +#warning "No hardware validation for this architecture." +namespace PokemonAutomation{ + bool check_hardware(){ + return true; + } +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.h b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.h index f9f6f5d1ff..3a2c67fe8c 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.h +++ b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation.h @@ -1,19 +1,19 @@ -/* Hardware Validation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_HardwareValidation_H -#define PokemonAutomation_HardwareValidation_H - -namespace PokemonAutomation{ - -// Check user hardware. -// If the hardware is too old, send a QMessageBox to tell user and return false. -// If the hardware may not be powerful enough, send a QMessageBox to inform user. -bool check_hardware(); - - -} -#endif +/* Hardware Validation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_HardwareValidation_H +#define PokemonAutomation_HardwareValidation_H + +namespace PokemonAutomation{ + +// Check user hardware. +// If the hardware is too old, send a QMessageBox to tell user and return false. +// If the hardware may not be powerful enough, send a QMessageBox to inform user. +bool check_hardware(); + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_arm64.tpp b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_arm64.tpp index 7f716e8136..7a163ef377 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_arm64.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_arm64.tpp @@ -1,25 +1,25 @@ -/* Hardware Validation (arm64) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -// #include -// #include -// #include "Common/Cpp/PrettyPrint.h" -// #include "Common/Cpp/CpuId/CpuId.h" -#include "Environment.h" -#include "HardwareValidation.h" - -namespace PokemonAutomation{ - - -bool check_hardware(){ - // TODO: write computer power check for Apple M-series computers - - return true; -} - - - -} +/* Hardware Validation (arm64) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +// #include +// #include +// #include "Common/Cpp/PrettyPrint.h" +// #include "Common/Cpp/CpuId/CpuId.h" +#include "Environment.h" +#include "HardwareValidation.h" + +namespace PokemonAutomation{ + + +bool check_hardware(){ + // TODO: write computer power check for Apple M-series computers + + return true; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_x86.tpp b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_x86.tpp index 3c96afecc7..fb01667a50 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_x86.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/HardwareValidation_x86.tpp @@ -1,100 +1,100 @@ -/* Hardware Validation (x86) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Environment.h" -#include "HardwareValidation.h" - -namespace PokemonAutomation{ - - -bool check_hardware(){ - if (!CPU_CAPABILITY_NATIVE.OK_08_Nehalem){ - QMessageBox box; - box.critical( - nullptr, - "Error", - "This computer is too old to run this program.

" - "Please try a much newer computer.

" - "(Reason: SSE4.2 is required to run this program.)" - ); - return false; - } - - if (!CPU_CAPABILITY_NATIVE.OK_13_Haswell){ - QMessageBox box; - QString str; - str += "This computer may not be powerful enough to run this program.

"; - str += "You can continue, but the program may not work correctly.
"; - str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; - str += "(Reason: Computers that lack AVX2 are likely to be too old and too slow to handle this program.)

"; - str += "Recommendation: Use a more powerful computer."; - box.warning(nullptr, "Warning", str); - } - - ProcessorSpecs specs = get_processor_specs(); - - if (specs.threads < 4){ - QMessageBox box; - QString str; - str += "This computer may not be powerful enough to run this program.

"; - str += "You can continue, but the program may not work correctly.
"; - str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; - str += "(Reason: "; - str += QString::number(specs.threads); - str += " vcores is a weak CPU.)

"; - str += "Recommendation: Use a more powerful computer."; - box.warning(nullptr, "Warning", str); - } - - if (specs.base_frequency < 1'500'000'000){ - QMessageBox box; - QString str; - str += "This computer may not be powerful enough to run this program.

"; - str += "You can continue, but the program may not work correctly.
"; - str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; - str += "(Reason: Base frequency measured at "; - str += QString::fromStdString(tostr_fixed(specs.base_frequency / 1000000000., 3)); - str += " GHz which is very slow.)

"; - str += "Recommendation: Use a more powerful computer."; - box.warning(nullptr, "Warning", str); - } - -#if (defined _WIN32) || (defined __linux) - size_t vcores = specs.threads > specs.cores - ? specs.threads - specs.cores - : 0; - double efreq = (specs.cores + 0.2 * vcores) * specs.base_frequency; - if (efreq < 6'000'000'000){ - QMessageBox box; - QString str; - str += "This computer may not be powerful enough to run this program.

"; - str += "You can continue, but the program may not work correctly.
"; - str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; - str += "CPU: " + QString::fromStdString(specs.name) + "
"; - str += "Cores: " + QString::number(specs.cores) + "
"; - str += "Threads: " + QString::number(specs.threads) + "
"; - str += "Sockets: " + QString::number(specs.sockets) + "
"; - str += "Numa Nodes: " + QString::number(specs.numa_nodes) + "
"; - str += "Base Frequency: " + QString::fromStdString(tostr_fixed(specs.base_frequency / 1000000000., 3)) + " GHz
"; - str += "
"; - str += "(p-cores + 0.2 * v-cores) * base-frequency = "; - str += QString::fromStdString(tostr_fixed(efreq / 1000000000., 3)); - str += " GHz

"; - str += "Recommendation: Use a more powerful computer."; - box.warning(nullptr, "Warning", str); - } -#endif - - return true; -} - - - -} +/* Hardware Validation (x86) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Environment.h" +#include "HardwareValidation.h" + +namespace PokemonAutomation{ + + +bool check_hardware(){ + if (!CPU_CAPABILITY_NATIVE.OK_08_Nehalem){ + QMessageBox box; + box.critical( + nullptr, + "Error", + "This computer is too old to run this program.

" + "Please try a much newer computer.

" + "(Reason: SSE4.2 is required to run this program.)" + ); + return false; + } + + if (!CPU_CAPABILITY_NATIVE.OK_13_Haswell){ + QMessageBox box; + QString str; + str += "This computer may not be powerful enough to run this program.

"; + str += "You can continue, but the program may not work correctly.
"; + str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; + str += "(Reason: Computers that lack AVX2 are likely to be too old and too slow to handle this program.)

"; + str += "Recommendation: Use a more powerful computer."; + box.warning(nullptr, "Warning", str); + } + + ProcessorSpecs specs = get_processor_specs(); + + if (specs.threads < 4){ + QMessageBox box; + QString str; + str += "This computer may not be powerful enough to run this program.

"; + str += "You can continue, but the program may not work correctly.
"; + str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; + str += "(Reason: "; + str += QString::number(specs.threads); + str += " vcores is a weak CPU.)

"; + str += "Recommendation: Use a more powerful computer."; + box.warning(nullptr, "Warning", str); + } + + if (specs.base_frequency < 1'500'000'000){ + QMessageBox box; + QString str; + str += "This computer may not be powerful enough to run this program.

"; + str += "You can continue, but the program may not work correctly.
"; + str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; + str += "(Reason: Base frequency measured at "; + str += QString::fromStdString(tostr_fixed(specs.base_frequency / 1000000000., 3)); + str += " GHz which is very slow.)

"; + str += "Recommendation: Use a more powerful computer."; + box.warning(nullptr, "Warning", str); + } + +#if (defined _WIN32) || (defined __linux) + size_t vcores = specs.threads > specs.cores + ? specs.threads - specs.cores + : 0; + double efreq = (specs.cores + 0.2 * vcores) * specs.base_frequency; + if (efreq < 6'000'000'000){ + QMessageBox box; + QString str; + str += "This computer may not be powerful enough to run this program.

"; + str += "You can continue, but the program may not work correctly.
"; + str += "(i.e. Increased error rate. Fail to reliably detect shinies, etc...)

"; + str += "CPU: " + QString::fromStdString(specs.name) + "
"; + str += "Cores: " + QString::number(specs.cores) + "
"; + str += "Threads: " + QString::number(specs.threads) + "
"; + str += "Sockets: " + QString::number(specs.sockets) + "
"; + str += "Numa Nodes: " + QString::number(specs.numa_nodes) + "
"; + str += "Base Frequency: " + QString::fromStdString(tostr_fixed(specs.base_frequency / 1000000000., 3)) + " GHz
"; + str += "
"; + str += "(p-cores + 0.2 * v-cores) * base-frequency = "; + str += QString::fromStdString(tostr_fixed(efreq / 1000000000., 3)); + str += " GHz

"; + str += "Recommendation: Use a more powerful computer."; + box.warning(nullptr, "Warning", str); + } +#endif + + return true; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.cpp b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.cpp index 4dfcea3c10..7fae8ba458 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.cpp +++ b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.cpp @@ -1,86 +1,86 @@ -/* OS Sleep - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "SystemSleep.h" - -#if 0 -#elif _WIN32 -#include "SystemSleep_Windows.tpp" -#elif __APPLE__ -#include "SystemSleep_Apple.tpp" -#else -namespace PokemonAutomation{ - SystemSleepController& SystemSleepController::instance(){ - static SystemSleepController controller; - return controller; - } -} -#endif - -namespace PokemonAutomation{ - - - -SystemSleepController::SystemSleepController() - : m_state(SleepSuppress::NONE) -{} - -void SystemSleepController::add_listener(Listener& listener){ - m_listeners.add(listener); -} -void SystemSleepController::remove_listener(Listener& listener){ - m_listeners.remove(listener); -} -void SystemSleepController::notify_listeners(SleepSuppress state){ - m_listeners.run_method_unique(&Listener::sleep_suppress_state_changed, state); -} - -SleepSuppress SystemSleepController::current_state() const{ - return m_state.load(std::memory_order_relaxed); -} - - - - - - - -void SleepSuppressScope::clear(){ - switch (m_mode){ - case SleepSuppress::NONE: - break; - case SleepSuppress::NO_SLEEP: - SystemSleepController::instance().pop_no_sleep(); - break; - case SleepSuppress::SCREEN_ON: - SystemSleepController::instance().pop_screen_on(); - break; - } - m_mode = SleepSuppress::NONE; -} -void SleepSuppressScope::operator=(SleepSuppress mode){ - clear(); - set(mode); -} -void SleepSuppressScope::set(SleepSuppress mode){ - switch (mode){ - case SleepSuppress::NONE: - break; - case SleepSuppress::NO_SLEEP: - SystemSleepController::instance().push_no_sleep(); - break; - case SleepSuppress::SCREEN_ON: - SystemSleepController::instance().push_screen_on(); - break; - } - m_mode = mode; -} - - - - -} - +/* OS Sleep + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SystemSleep.h" + +#if 0 +#elif _WIN32 +#include "SystemSleep_Windows.tpp" +#elif __APPLE__ +#include "SystemSleep_Apple.tpp" +#else +namespace PokemonAutomation{ + SystemSleepController& SystemSleepController::instance(){ + static SystemSleepController controller; + return controller; + } +} +#endif + +namespace PokemonAutomation{ + + + +SystemSleepController::SystemSleepController() + : m_state(SleepSuppress::NONE) +{} + +void SystemSleepController::add_listener(Listener& listener){ + m_listeners.add(listener); +} +void SystemSleepController::remove_listener(Listener& listener){ + m_listeners.remove(listener); +} +void SystemSleepController::notify_listeners(SleepSuppress state){ + m_listeners.run_method_unique(&Listener::sleep_suppress_state_changed, state); +} + +SleepSuppress SystemSleepController::current_state() const{ + return m_state.load(std::memory_order_relaxed); +} + + + + + + + +void SleepSuppressScope::clear(){ + switch (m_mode){ + case SleepSuppress::NONE: + break; + case SleepSuppress::NO_SLEEP: + SystemSleepController::instance().pop_no_sleep(); + break; + case SleepSuppress::SCREEN_ON: + SystemSleepController::instance().pop_screen_on(); + break; + } + m_mode = SleepSuppress::NONE; +} +void SleepSuppressScope::operator=(SleepSuppress mode){ + clear(); + set(mode); +} +void SleepSuppressScope::set(SleepSuppress mode){ + switch (mode){ + case SleepSuppress::NONE: + break; + case SleepSuppress::NO_SLEEP: + SystemSleepController::instance().push_no_sleep(); + break; + case SleepSuppress::SCREEN_ON: + SystemSleepController::instance().push_screen_on(); + break; + } + m_mode = mode; +} + + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.h b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.h index e2d16a0167..8f72d3c878 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.h +++ b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep.h @@ -1,110 +1,110 @@ -/* System Sleep - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SystemSleep_H -#define PokemonAutomation_SystemSleep_H - -#include -#include -#include -#include "Common/Cpp/ListenerSet.h" - -#if _WIN32 -#define PA_ENABLE_SLEEP_SUPPRESS -#define PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP -#endif -#if __APPLE__ -#define PA_ENABLE_SLEEP_SUPPRESS -#endif - - -namespace PokemonAutomation{ - - - -enum class SleepSuppress{ - NONE, - NO_SLEEP, - SCREEN_ON, -}; - - -// Call OS API to prevent screen saver from running and OS from going to sleep. -// Useful for running some programs like PokemonSV_VideoFastCodeEntry that require -// the screen to be constantly on. -class SystemSleepController{ -public: - struct Listener{ - virtual void sleep_suppress_state_changed(SleepSuppress new_state) = 0; - }; - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - - -protected: - virtual ~SystemSleepController() = default; - SystemSleepController(); - - // Must be called under lock. - void notify_listeners(SleepSuppress state); - - -public: - static SystemSleepController& instance(); - - SleepSuppress current_state() const; - - // Push: Add a request for this type of sleep-disable. - // Pop: Remove a request for this type of sleep-disable. - // The sleep-disable will be active as long as there is at least one - // request is active for that type. - - // Keep the screen on and prevent sleep. - virtual void push_screen_on(){} - virtual void pop_screen_on(){} - - // Allow the screen to turn off, but don't sleep. - virtual void push_no_sleep(){} - virtual void pop_no_sleep(){} - - -protected: - std::atomic m_state; - - std::mutex m_lock; - ListenerSet m_listeners; -}; - - - - - -class SleepSuppressScope{ -public: - SleepSuppressScope(SleepSuppress mode){ - set(mode); - } - ~SleepSuppressScope(){ - clear(); - } - SleepSuppressScope(const SleepSuppressScope&) = delete; - void operator=(const SleepSuppressScope&) = delete; - - void clear(); - void operator=(SleepSuppress mode); - -private: - void set(SleepSuppress mode); - -private: - SleepSuppress m_mode; -}; - - - - -} -#endif +/* System Sleep + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SystemSleep_H +#define PokemonAutomation_SystemSleep_H + +#include +#include +#include +#include "Common/Cpp/ListenerSet.h" + +#if _WIN32 +#define PA_ENABLE_SLEEP_SUPPRESS +#define PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP +#endif +#if __APPLE__ +#define PA_ENABLE_SLEEP_SUPPRESS +#endif + + +namespace PokemonAutomation{ + + + +enum class SleepSuppress{ + NONE, + NO_SLEEP, + SCREEN_ON, +}; + + +// Call OS API to prevent screen saver from running and OS from going to sleep. +// Useful for running some programs like PokemonSV_VideoFastCodeEntry that require +// the screen to be constantly on. +class SystemSleepController{ +public: + struct Listener{ + virtual void sleep_suppress_state_changed(SleepSuppress new_state) = 0; + }; + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + + +protected: + virtual ~SystemSleepController() = default; + SystemSleepController(); + + // Must be called under lock. + void notify_listeners(SleepSuppress state); + + +public: + static SystemSleepController& instance(); + + SleepSuppress current_state() const; + + // Push: Add a request for this type of sleep-disable. + // Pop: Remove a request for this type of sleep-disable. + // The sleep-disable will be active as long as there is at least one + // request is active for that type. + + // Keep the screen on and prevent sleep. + virtual void push_screen_on(){} + virtual void pop_screen_on(){} + + // Allow the screen to turn off, but don't sleep. + virtual void push_no_sleep(){} + virtual void pop_no_sleep(){} + + +protected: + std::atomic m_state; + + std::mutex m_lock; + ListenerSet m_listeners; +}; + + + + + +class SleepSuppressScope{ +public: + SleepSuppressScope(SleepSuppress mode){ + set(mode); + } + ~SleepSuppressScope(){ + clear(); + } + SleepSuppressScope(const SleepSuppressScope&) = delete; + void operator=(const SleepSuppressScope&) = delete; + + void clear(); + void operator=(SleepSuppress mode); + +private: + void set(SleepSuppress mode); + +private: + SleepSuppress m_mode; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp index b0b645b61a..24cfe348d9 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Apple.tpp @@ -1,144 +1,144 @@ -/* OS Sleep (Apple) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "SystemSleep.h" - -namespace PokemonAutomation{ - - - -class AppleSleepController : public SystemSleepController{ -public: - virtual ~AppleSleepController(){ - std::lock_guard lg(m_lock); - m_screen_on_requests = 0; - m_no_sleep_requests = 0; - update_state(); - } - virtual void push_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests++; - update_state(); - } - virtual void pop_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests--; - update_state(); - } - virtual void push_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests++; - update_state(); - } - virtual void pop_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests--; - update_state(); - } - - -private: - // Disable/Enable screen saver and OS sleep. - // Return whether the setting is successful. - bool prevent_sleep(bool prevent); - void update_state(); - - bool disable_sleep(); - bool enable_sleep(); - - IOReturn m_prevention_succeeded = kIOReturnError; - IOPMAssertionID m_session_id = 0; - - size_t m_screen_on_requests = 0; - size_t m_no_sleep_requests = 0; -}; - - -// Code from https://stackoverflow.com/questions/5596319/how-to-programmatically-prevent-a-mac-from-going-to-sleep/8461182#8461182 - - -bool AppleSleepController::prevent_sleep(bool prevent){ - if (prevent){ - return disable_sleep(); - }else{ - return enable_sleep(); - } -} - -bool AppleSleepController::disable_sleep(){ - if (m_prevention_succeeded == kIOReturnSuccess){ - return true; - } - std::cout << "Disabling display sleep and OS sleep" << std::endl; - // kIOPMAssertionTypeNoDisplaySleep prevents display sleep, - // kIOPMAssertionTypeNoIdleSleep prevents idle sleep - - // NOTE: IOPMAssertionCreateWithName limits the string to 128 characters. - CFStringRef reasonForActivity = (CFStringRef) __builtin___CFStringMakeConstantString("SerialPrograms is running"); - - m_prevention_succeeded = kIOReturnError; - m_session_id = 0; - m_prevention_succeeded = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, - kIOPMAssertionLevelOn, reasonForActivity, &m_session_id); - if (m_prevention_succeeded != kIOReturnSuccess){ - m_session_id = 0; - std::cerr << "Cannot disable sleep. Error code " << m_prevention_succeeded << std::endl; - return false; - } - - std::cout << "Disabled display sleep and OS sleep" << std::endl; - return true; -} - -bool AppleSleepController::enable_sleep(){ - if (m_prevention_succeeded == kIOReturnSuccess){ - IOPMAssertionRelease(m_session_id); - m_session_id = 0; - m_prevention_succeeded = kIOReturnError; - std::cout << "Enabled display sleep and OS sleep." << std::endl; - } - return true; -} - - - -void AppleSleepController::update_state(){ - // Must call under lock. - - SleepSuppress before_state = m_state.load(std::memory_order_relaxed); - SleepSuppress after_state = SleepSuppress::NONE; - - // TODO: Distiguish these two. - bool enabled = m_screen_on_requests > 0 || m_no_sleep_requests > 0; - prevent_sleep(enabled); - - after_state = enabled - ? SleepSuppress::SCREEN_ON - : SleepSuppress::NONE, - - m_state.store(after_state, std::memory_order_release); - - if (before_state != after_state){ - notify_listeners(after_state); - } -} - - -SystemSleepController& SystemSleepController::instance(){ - static AppleSleepController controller; - return controller; -} - - - - - - -} +/* OS Sleep (Apple) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "SystemSleep.h" + +namespace PokemonAutomation{ + + + +class AppleSleepController : public SystemSleepController{ +public: + virtual ~AppleSleepController(){ + std::lock_guard lg(m_lock); + m_screen_on_requests = 0; + m_no_sleep_requests = 0; + update_state(); + } + virtual void push_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests++; + update_state(); + } + virtual void pop_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests--; + update_state(); + } + virtual void push_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests++; + update_state(); + } + virtual void pop_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests--; + update_state(); + } + + +private: + // Disable/Enable screen saver and OS sleep. + // Return whether the setting is successful. + bool prevent_sleep(bool prevent); + void update_state(); + + bool disable_sleep(); + bool enable_sleep(); + + IOReturn m_prevention_succeeded = kIOReturnError; + IOPMAssertionID m_session_id = 0; + + size_t m_screen_on_requests = 0; + size_t m_no_sleep_requests = 0; +}; + + +// Code from https://stackoverflow.com/questions/5596319/how-to-programmatically-prevent-a-mac-from-going-to-sleep/8461182#8461182 + + +bool AppleSleepController::prevent_sleep(bool prevent){ + if (prevent){ + return disable_sleep(); + }else{ + return enable_sleep(); + } +} + +bool AppleSleepController::disable_sleep(){ + if (m_prevention_succeeded == kIOReturnSuccess){ + return true; + } + std::cout << "Disabling display sleep and OS sleep" << std::endl; + // kIOPMAssertionTypeNoDisplaySleep prevents display sleep, + // kIOPMAssertionTypeNoIdleSleep prevents idle sleep + + // NOTE: IOPMAssertionCreateWithName limits the string to 128 characters. + CFStringRef reasonForActivity = (CFStringRef) __builtin___CFStringMakeConstantString("SerialPrograms is running"); + + m_prevention_succeeded = kIOReturnError; + m_session_id = 0; + m_prevention_succeeded = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep, + kIOPMAssertionLevelOn, reasonForActivity, &m_session_id); + if (m_prevention_succeeded != kIOReturnSuccess){ + m_session_id = 0; + std::cerr << "Cannot disable sleep. Error code " << m_prevention_succeeded << std::endl; + return false; + } + + std::cout << "Disabled display sleep and OS sleep" << std::endl; + return true; +} + +bool AppleSleepController::enable_sleep(){ + if (m_prevention_succeeded == kIOReturnSuccess){ + IOPMAssertionRelease(m_session_id); + m_session_id = 0; + m_prevention_succeeded = kIOReturnError; + std::cout << "Enabled display sleep and OS sleep." << std::endl; + } + return true; +} + + + +void AppleSleepController::update_state(){ + // Must call under lock. + + SleepSuppress before_state = m_state.load(std::memory_order_relaxed); + SleepSuppress after_state = SleepSuppress::NONE; + + // TODO: Distiguish these two. + bool enabled = m_screen_on_requests > 0 || m_no_sleep_requests > 0; + prevent_sleep(enabled); + + after_state = enabled + ? SleepSuppress::SCREEN_ON + : SleepSuppress::NONE, + + m_state.store(after_state, std::memory_order_release); + + if (before_state != after_state){ + notify_listeners(after_state); + } +} + + +SystemSleepController& SystemSleepController::instance(){ + static AppleSleepController controller; + return controller; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp index 2f71cd8223..6325b58dd2 100644 --- a/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/Environment/SystemSleep_Windows.tpp @@ -1,127 +1,127 @@ -/* OS Sleep (Windows) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include -#include -#include "Common/Qt/Redispatch.h" -#include "CommonFramework/Logging/Logger.h" -#include "SystemSleep.h" - -namespace PokemonAutomation{ - - -class WindowsSleepController : public SystemSleepController{ -public: - virtual ~WindowsSleepController(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_cv.notify_all(); - } - m_thread.join(); - if (m_state.load(std::memory_order_relaxed) != SleepSuppress::NONE){ - global_logger_tagged().log("Destroying WindowsSleepController with active requests...", COLOR_RED); - } - } - WindowsSleepController() - : m_screen_on_requests(0) - , m_no_sleep_requests(0) - , m_stopping(false) - , m_thread(&WindowsSleepController::thread_loop, this) - {} - - virtual void push_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests++; - m_cv.notify_all(); - } - virtual void pop_screen_on() override{ - std::lock_guard lg(m_lock); - m_screen_on_requests--; - m_cv.notify_all(); - } - virtual void push_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests++; - m_cv.notify_all(); - } - virtual void pop_no_sleep() override{ - std::lock_guard lg(m_lock); - m_no_sleep_requests--; - m_cv.notify_all(); - } - -private: - void thread_loop(){ - // SetThreadExecutionState(ES_CONTINUOUS) only lasts as long as the - // thread is alive. So we use our own thread. - while (true){ - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - - SleepSuppress before_state = m_state.load(std::memory_order_relaxed); - SleepSuppress after_state = SleepSuppress::NONE; - - EXECUTION_STATE flags = ES_CONTINUOUS; - if (m_no_sleep_requests > 0){ - flags |= ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED; - after_state = SleepSuppress::NO_SLEEP; - } - if (m_screen_on_requests > 0){ - flags |= ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED; - after_state = SleepSuppress::SCREEN_ON; - } - EXECUTION_STATE ret = SetThreadExecutionState(flags); - if (ret == 0){ - global_logger_tagged().log("Unable to set system sleep state.", COLOR_RED); - }else{ - switch (after_state){ - case SleepSuppress::NONE: - global_logger_tagged().log("Setting sleep state to: None", COLOR_BLUE); - break; - case SleepSuppress::NO_SLEEP: - global_logger_tagged().log("Setting sleep state to: No Sleep", COLOR_BLUE); - break; - case SleepSuppress::SCREEN_ON: - global_logger_tagged().log("Setting sleep state to: Screen On", COLOR_BLUE); - break; - } - - m_state.store(after_state, std::memory_order_release); - - if (before_state != after_state){ - notify_listeners(after_state); - } - } - - m_cv.wait(lg); - } - } - -private: - size_t m_screen_on_requests = 0; - size_t m_no_sleep_requests = 0; - - bool m_stopping; - std::condition_variable m_cv; - std::thread m_thread; -}; - - -SystemSleepController& SystemSleepController::instance(){ - static WindowsSleepController controller; - return controller; -} - - - - - - -} +/* OS Sleep (Windows) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include +#include +#include "Common/Qt/Redispatch.h" +#include "CommonFramework/Logging/Logger.h" +#include "SystemSleep.h" + +namespace PokemonAutomation{ + + +class WindowsSleepController : public SystemSleepController{ +public: + virtual ~WindowsSleepController(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_cv.notify_all(); + } + m_thread.join(); + if (m_state.load(std::memory_order_relaxed) != SleepSuppress::NONE){ + global_logger_tagged().log("Destroying WindowsSleepController with active requests...", COLOR_RED); + } + } + WindowsSleepController() + : m_screen_on_requests(0) + , m_no_sleep_requests(0) + , m_stopping(false) + , m_thread(&WindowsSleepController::thread_loop, this) + {} + + virtual void push_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests++; + m_cv.notify_all(); + } + virtual void pop_screen_on() override{ + std::lock_guard lg(m_lock); + m_screen_on_requests--; + m_cv.notify_all(); + } + virtual void push_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests++; + m_cv.notify_all(); + } + virtual void pop_no_sleep() override{ + std::lock_guard lg(m_lock); + m_no_sleep_requests--; + m_cv.notify_all(); + } + +private: + void thread_loop(){ + // SetThreadExecutionState(ES_CONTINUOUS) only lasts as long as the + // thread is alive. So we use our own thread. + while (true){ + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + + SleepSuppress before_state = m_state.load(std::memory_order_relaxed); + SleepSuppress after_state = SleepSuppress::NONE; + + EXECUTION_STATE flags = ES_CONTINUOUS; + if (m_no_sleep_requests > 0){ + flags |= ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED; + after_state = SleepSuppress::NO_SLEEP; + } + if (m_screen_on_requests > 0){ + flags |= ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED; + after_state = SleepSuppress::SCREEN_ON; + } + EXECUTION_STATE ret = SetThreadExecutionState(flags); + if (ret == 0){ + global_logger_tagged().log("Unable to set system sleep state.", COLOR_RED); + }else{ + switch (after_state){ + case SleepSuppress::NONE: + global_logger_tagged().log("Setting sleep state to: None", COLOR_BLUE); + break; + case SleepSuppress::NO_SLEEP: + global_logger_tagged().log("Setting sleep state to: No Sleep", COLOR_BLUE); + break; + case SleepSuppress::SCREEN_ON: + global_logger_tagged().log("Setting sleep state to: Screen On", COLOR_BLUE); + break; + } + + m_state.store(after_state, std::memory_order_release); + + if (before_state != after_state){ + notify_listeners(after_state); + } + } + + m_cv.wait(lg); + } + } + +private: + size_t m_screen_on_requests = 0; + size_t m_no_sleep_requests = 0; + + bool m_stopping; + std::condition_variable m_cv; + std::thread m_thread; +}; + + +SystemSleepController& SystemSleepController::instance(){ + static WindowsSleepController controller; + return controller; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp index 5d152c0da9..a91188b960 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.cpp @@ -1,428 +1,428 @@ -/* Error Reports - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/GlobalServices.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Environment/Environment.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "ProgramDumper.h" -#include "ErrorReports.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -const std::string& ERROR_LOGS_NAME = "Logs.log"; -const std::string& ERROR_DUMP_NAME = "Minidump.dmp"; -const std::string& ERROR_PATH_UNSENT = "ErrorReportsLocal"; -const std::string& ERROR_PATH_SENT = "ErrorReportsSent"; - - - -ErrorReportOption::ErrorReportOption() - : GroupOption( - "Error Reports", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , DESCRIPTION( - "Send error reports to the " + PROGRAM_NAME + " server to help them resolve issues and improve the program." - ) - , SEND_MODE( - "When to Send Error Reports:", - { - {ErrorReportSendMode::SEND_AUTOMATICALLY, "automatic", "Send automatically."}, - {ErrorReportSendMode::PROMPT_WHEN_CONVENIENT, "prompt", "Prompt when convenient."}, - {ErrorReportSendMode::NEVER_SEND_ANYTHING, "never", "Never send error reports."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - IS_BETA_VERSION - ? ErrorReportSendMode::SEND_AUTOMATICALLY - : ErrorReportSendMode::PROMPT_WHEN_CONVENIENT - ) - , SCREENSHOT( - "Include Screenshots:", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , VIDEO( - "Include Video:
Include a video leading up to the error. (if available)", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , LOGS( - "Include Logs:
Include the recent log leading up to the error.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , DUMPS( - "Include Dumps:
Include stack-trace and related information.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , FILES( - "Include Other Files:
Include other files that may be helpful for the developers.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(SEND_MODE); - PA_ADD_OPTION(SCREENSHOT); - PA_ADD_OPTION(VIDEO); - PA_ADD_OPTION(LOGS); - PA_ADD_OPTION(DUMPS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(FILES); - } -} - - -SendableErrorReport::SendableErrorReport() - : m_timestamp(now_to_filestring()) - , m_directory(ERROR_PATH_UNSENT + "/" + m_timestamp + "/") - , m_processor(get_processor_name()) - , m_program(PreloadSettings::instance().DEVELOPER_MODE - ? PROGRAM_NAME + " (" + PROGRAM_VERSION + "-dev)" - : PROGRAM_NAME + " (" + PROGRAM_VERSION + ")" - ) - , m_program_runtime_millis(0) - , m_dump_name(ERROR_DUMP_NAME) -{ - QDir().mkpath(QString::fromStdString(m_directory)); -} -SendableErrorReport::SendableErrorReport( - Logger* logger, - const ProgramInfo& info, - std::string title, - std::vector> messages, - const ImageViewRGB32& image, - const StreamHistorySession* stream_history -) - : SendableErrorReport() -{ - if (logger){ - logger->log("Compiling Error Report..."); - }else{ - std::cout << "Compiling Error Report..." << std::endl; - } - m_program_id = info.program_id; - if (info.start_time != WallClock::min()){ - m_program_runtime_millis = std::chrono::duration_cast(current_time() - info.start_time).count(); - } - m_title = std::move(title); - m_messages = std::move(messages); - m_image = image; - { - std::string log; - for (const std::string& line : global_logger_raw().get_last()){ - log += line; - log += "\r\n"; - } - QFile file(QString::fromStdString(m_directory + ERROR_LOGS_NAME)); - bool exists = file.exists(); - file.open(QIODevice::WriteOnly); - if (!exists){ - std::string bom = "\xef\xbb\xbf"; - file.write(bom.c_str(), bom.size()); - } - file.write(log.c_str()); - file.flush(); - m_logs_name = ERROR_LOGS_NAME; - } - if (stream_history){ - if (stream_history->save(m_directory + "Video.mp4")){ - m_video_name = "Video.mp4"; - } - } - if (program_dump(logger, m_directory + ERROR_DUMP_NAME)){ - m_dump_name = ERROR_DUMP_NAME; - } -} - -SendableErrorReport::SendableErrorReport(std::string directory) - : m_directory(std::move(directory)) -{ - if (m_directory.back() != '/'){ - m_directory += '/'; - } - - JsonValue json = load_json_file(m_directory + "Report.json"); - const JsonObject& obj = json.to_object_throw(); - m_timestamp = obj.get_string_throw("Timestamp"); - - // If we error from this point on, we'll just move it to the sent folder. - try{ - m_processor = obj.get_string_throw("Processor"); - m_program = obj.get_string_throw("Program"); - m_program_id = obj.get_string_throw("ProgramID"); - m_program_runtime_millis = obj.get_integer_throw("ElapsedTimeMillis"); - m_title = obj.get_string_throw("Title"); - { - const JsonArray& messages = obj.get_array_throw("Messages"); - for (const JsonValue& message : messages){ - const JsonArray& item = message.to_array_throw(); - if (item.size() != 2){ - throw ParseException("Expected 2 values for message."); - } - m_messages.emplace_back( - item[0].to_string_throw(), - item[1].to_string_throw() - ); - } - } - { - const std::string* image_name = obj.get_string("Screenshot"); - if (image_name){ - try{ - m_image_owner = ImageRGB32(m_directory + *image_name); - m_image = m_image_owner; - }catch (FileException&){} - } - } - { - const std::string* video_name = obj.get_string("Video"); - if (video_name){ - m_video_name = *video_name; - } - } - { - const std::string* dump_name = obj.get_string("Dump"); - if (dump_name){ - m_dump_name = *dump_name; - } - } - { - const std::string* logs_name = obj.get_string("Logs"); - if (logs_name){ - m_logs_name = *logs_name; - } - } - { - const JsonArray& files = obj.get_array_throw("Files"); - for (const JsonValue& file : files){ - m_files.emplace_back(file.to_string_throw()); - } - } - }catch (...){ - move_to_sent(); - throw; - } -} -void SendableErrorReport::add_file(std::string filename){ - m_files.emplace_back(std::move(filename)); -} - -void SendableErrorReport::save(Logger* logger) const{ - if (logger){ - logger->log("Saving Error Report..."); - }else{ - std::cout << "Saving Error Report..." << std::endl; - } - - JsonObject report; - - report["Timestamp"] = m_timestamp; - report["Processor"] = m_processor; - report["Program"] = m_program; - report["ProgramID"] = m_program_id; - report["ElapsedTimeMillis"] = m_program_runtime_millis; - report["Title"] = m_title; - { - JsonArray messages; - for (const std::pair& item : m_messages){ - JsonArray array; - array.push_back(item.first); - array.push_back(item.second); - messages.push_back(std::move(array)); - } - report["Messages"] = std::move(messages); - } - if (m_image){ - if (m_image.save(m_directory + "Screenshot.png")){ - report["Screenshot"] = "Screenshot.png"; - } - } - if (!m_video_name.empty()){ - report["Video"] = m_video_name; - } - if (!m_dump_name.empty()){ - report["Dump"] = m_dump_name; - } - if (!m_logs_name.empty()){ - report["Logs"] = m_logs_name; - } - - JsonArray array; - for (const std::string& file : m_files){ - array.push_back(file); - } - report["Files"] = std::move(array); - - report.dump(m_directory + "Report.json"); -} - -void SendableErrorReport::move_to_sent(){ -// cout << "move_to_sent()" << endl; - QDir().mkdir(QString::fromStdString(ERROR_PATH_SENT)); - - std::string new_directory = ERROR_PATH_SENT + "/" + m_timestamp + "/"; -// cout << "old: " << m_directory << endl; -// cout << "new: " << new_directory << endl; - bool success = QDir().rename( - QString::fromStdString(m_directory), - QString::fromStdString(new_directory) - ); - if (success){ - global_logger_tagged().log("Moved error report " + m_timestamp + "."); - }else{ - global_logger_tagged().log("Unable to move error report " + m_timestamp + ".", COLOR_RED); - } - m_directory = std::move(new_directory); -} - - -std::vector SendableErrorReport::get_pending_reports(){ - std::vector ret; - QDir dir(QString::fromStdString(ERROR_PATH_UNSENT)); - dir.setFilter(QDir::Filter::AllDirs); - QFileInfoList list = dir.entryInfoList(); - for (const auto& item : list){ - std::string path = item.filePath().toStdString(); - if (path.back() == '.'){ - continue; - } - ret.emplace_back(std::move(path)); - } - return ret; -} - -#ifndef PA_OFFICIAL -void SendableErrorReport::send(Logger& logger, std::shared_ptr report){} -#endif - - - -// Send all the reports. This function will return early and all the reports -// will be sent asynchronously in the background. -void send_reports(Logger& logger, const std::vector& reports){ - for (const std::string& path : reports){ - try{ -// static int c = 0; -// cout << "Sending... " << c++ << endl; - // std:::shared_ptr because it needs to take ownership for - // destruction at a later time. - SendableErrorReport::send(logger, std::make_shared(path)); - }catch (Exception& e){ - logger.log("Unable to send report: " + path + ", Message: " + e.to_str(), COLOR_RED); - }catch (...){ - logger.log("Unable to send report: " + path, COLOR_RED); - } - } -} -std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt){ -#ifdef PA_OFFICIAL - ErrorReportSendMode mode = GlobalSettings::instance().ERROR_REPORTS->SEND_MODE; - if (mode == ErrorReportSendMode::NEVER_SEND_ANYTHING){ - return nullptr; - } - - std::vector reports = SendableErrorReport::get_pending_reports(); - global_logger_tagged().log("Found " + std::to_string(reports.size()) + " unsent error reports.", COLOR_PURPLE); - - if (reports.empty()){ - return nullptr; - } - - if (mode == ErrorReportSendMode::PROMPT_WHEN_CONVENIENT){ - if (!allow_prompt){ - return nullptr; - } - QMessageBox box; - QMessageBox::StandardButton button = box.information( - nullptr, - "Error Reporting", - QString::fromStdString( - (reports.size() == 1 - ? "There is " + tostr_u_commas(reports.size()) + " error report.

" - "Would you like to help make this program better by sending it to the developers?

" - : "There are " + tostr_u_commas(reports.size()) + " error reports.

" - "Would you like to help make this program better by sending them to the developers?

" - ) + - make_text_url(ERROR_PATH_UNSENT, "View unsent error reports.")// + "

" -// "(You can change )" - ), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::StandardButton::Yes - ); - if (button != QMessageBox::StandardButton::Yes){ - return nullptr; - } - } - - global_logger_tagged().log("Attempting to send " + std::to_string(reports.size()) + " error reports.", COLOR_PURPLE); - - return global_async_dispatcher().dispatch([reports = std::move(reports)]{ - send_reports(global_logger_tagged(), reports); - }); -#else - return nullptr; -#endif -} - -void report_error( - Logger* logger, - const ProgramInfo& info, - std::string title, - std::vector> messages, - const ImageViewRGB32& image, - const StreamHistorySession* stream_history, - const std::vector& files -){ - if (logger == nullptr){ - logger = &global_logger_tagged(); - } - - { - SendableErrorReport report( - logger, - info, - std::move(title), - std::move(messages), - image, - stream_history - ); - - std::vector full_file_paths; - for (const std::string& file: files){ - full_file_paths.emplace_back(report.directory() + file); - } - - report.save(logger); - } - - send_all_unsent_reports(*logger, false); -} - - - - -} +/* Error Reports + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/GlobalServices.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Environment/Environment.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "ProgramDumper.h" +#include "ErrorReports.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +const std::string& ERROR_LOGS_NAME = "Logs.log"; +const std::string& ERROR_DUMP_NAME = "Minidump.dmp"; +const std::string& ERROR_PATH_UNSENT = "ErrorReportsLocal"; +const std::string& ERROR_PATH_SENT = "ErrorReportsSent"; + + + +ErrorReportOption::ErrorReportOption() + : GroupOption( + "Error Reports", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , DESCRIPTION( + "Send error reports to the " + PROGRAM_NAME + " server to help them resolve issues and improve the program." + ) + , SEND_MODE( + "When to Send Error Reports:", + { + {ErrorReportSendMode::SEND_AUTOMATICALLY, "automatic", "Send automatically."}, + {ErrorReportSendMode::PROMPT_WHEN_CONVENIENT, "prompt", "Prompt when convenient."}, + {ErrorReportSendMode::NEVER_SEND_ANYTHING, "never", "Never send error reports."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + IS_BETA_VERSION + ? ErrorReportSendMode::SEND_AUTOMATICALLY + : ErrorReportSendMode::PROMPT_WHEN_CONVENIENT + ) + , SCREENSHOT( + "Include Screenshots:", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , VIDEO( + "Include Video:
Include a video leading up to the error. (if available)", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , LOGS( + "Include Logs:
Include the recent log leading up to the error.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , DUMPS( + "Include Dumps:
Include stack-trace and related information.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , FILES( + "Include Other Files:
Include other files that may be helpful for the developers.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(SEND_MODE); + PA_ADD_OPTION(SCREENSHOT); + PA_ADD_OPTION(VIDEO); + PA_ADD_OPTION(LOGS); + PA_ADD_OPTION(DUMPS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(FILES); + } +} + + +SendableErrorReport::SendableErrorReport() + : m_timestamp(now_to_filestring()) + , m_directory(ERROR_PATH_UNSENT + "/" + m_timestamp + "/") + , m_processor(get_processor_name()) + , m_program(PreloadSettings::instance().DEVELOPER_MODE + ? PROGRAM_NAME + " (" + PROGRAM_VERSION + "-dev)" + : PROGRAM_NAME + " (" + PROGRAM_VERSION + ")" + ) + , m_program_runtime_millis(0) + , m_dump_name(ERROR_DUMP_NAME) +{ + QDir().mkpath(QString::fromStdString(m_directory)); +} +SendableErrorReport::SendableErrorReport( + Logger* logger, + const ProgramInfo& info, + std::string title, + std::vector> messages, + const ImageViewRGB32& image, + const StreamHistorySession* stream_history +) + : SendableErrorReport() +{ + if (logger){ + logger->log("Compiling Error Report..."); + }else{ + std::cout << "Compiling Error Report..." << std::endl; + } + m_program_id = info.program_id; + if (info.start_time != WallClock::min()){ + m_program_runtime_millis = std::chrono::duration_cast(current_time() - info.start_time).count(); + } + m_title = std::move(title); + m_messages = std::move(messages); + m_image = image; + { + std::string log; + for (const std::string& line : global_logger_raw().get_last()){ + log += line; + log += "\r\n"; + } + QFile file(QString::fromStdString(m_directory + ERROR_LOGS_NAME)); + bool exists = file.exists(); + file.open(QIODevice::WriteOnly); + if (!exists){ + std::string bom = "\xef\xbb\xbf"; + file.write(bom.c_str(), bom.size()); + } + file.write(log.c_str()); + file.flush(); + m_logs_name = ERROR_LOGS_NAME; + } + if (stream_history){ + if (stream_history->save(m_directory + "Video.mp4")){ + m_video_name = "Video.mp4"; + } + } + if (program_dump(logger, m_directory + ERROR_DUMP_NAME)){ + m_dump_name = ERROR_DUMP_NAME; + } +} + +SendableErrorReport::SendableErrorReport(std::string directory) + : m_directory(std::move(directory)) +{ + if (m_directory.back() != '/'){ + m_directory += '/'; + } + + JsonValue json = load_json_file(m_directory + "Report.json"); + const JsonObject& obj = json.to_object_throw(); + m_timestamp = obj.get_string_throw("Timestamp"); + + // If we error from this point on, we'll just move it to the sent folder. + try{ + m_processor = obj.get_string_throw("Processor"); + m_program = obj.get_string_throw("Program"); + m_program_id = obj.get_string_throw("ProgramID"); + m_program_runtime_millis = obj.get_integer_throw("ElapsedTimeMillis"); + m_title = obj.get_string_throw("Title"); + { + const JsonArray& messages = obj.get_array_throw("Messages"); + for (const JsonValue& message : messages){ + const JsonArray& item = message.to_array_throw(); + if (item.size() != 2){ + throw ParseException("Expected 2 values for message."); + } + m_messages.emplace_back( + item[0].to_string_throw(), + item[1].to_string_throw() + ); + } + } + { + const std::string* image_name = obj.get_string("Screenshot"); + if (image_name){ + try{ + m_image_owner = ImageRGB32(m_directory + *image_name); + m_image = m_image_owner; + }catch (FileException&){} + } + } + { + const std::string* video_name = obj.get_string("Video"); + if (video_name){ + m_video_name = *video_name; + } + } + { + const std::string* dump_name = obj.get_string("Dump"); + if (dump_name){ + m_dump_name = *dump_name; + } + } + { + const std::string* logs_name = obj.get_string("Logs"); + if (logs_name){ + m_logs_name = *logs_name; + } + } + { + const JsonArray& files = obj.get_array_throw("Files"); + for (const JsonValue& file : files){ + m_files.emplace_back(file.to_string_throw()); + } + } + }catch (...){ + move_to_sent(); + throw; + } +} +void SendableErrorReport::add_file(std::string filename){ + m_files.emplace_back(std::move(filename)); +} + +void SendableErrorReport::save(Logger* logger) const{ + if (logger){ + logger->log("Saving Error Report..."); + }else{ + std::cout << "Saving Error Report..." << std::endl; + } + + JsonObject report; + + report["Timestamp"] = m_timestamp; + report["Processor"] = m_processor; + report["Program"] = m_program; + report["ProgramID"] = m_program_id; + report["ElapsedTimeMillis"] = m_program_runtime_millis; + report["Title"] = m_title; + { + JsonArray messages; + for (const std::pair& item : m_messages){ + JsonArray array; + array.push_back(item.first); + array.push_back(item.second); + messages.push_back(std::move(array)); + } + report["Messages"] = std::move(messages); + } + if (m_image){ + if (m_image.save(m_directory + "Screenshot.png")){ + report["Screenshot"] = "Screenshot.png"; + } + } + if (!m_video_name.empty()){ + report["Video"] = m_video_name; + } + if (!m_dump_name.empty()){ + report["Dump"] = m_dump_name; + } + if (!m_logs_name.empty()){ + report["Logs"] = m_logs_name; + } + + JsonArray array; + for (const std::string& file : m_files){ + array.push_back(file); + } + report["Files"] = std::move(array); + + report.dump(m_directory + "Report.json"); +} + +void SendableErrorReport::move_to_sent(){ +// cout << "move_to_sent()" << endl; + QDir().mkdir(QString::fromStdString(ERROR_PATH_SENT)); + + std::string new_directory = ERROR_PATH_SENT + "/" + m_timestamp + "/"; +// cout << "old: " << m_directory << endl; +// cout << "new: " << new_directory << endl; + bool success = QDir().rename( + QString::fromStdString(m_directory), + QString::fromStdString(new_directory) + ); + if (success){ + global_logger_tagged().log("Moved error report " + m_timestamp + "."); + }else{ + global_logger_tagged().log("Unable to move error report " + m_timestamp + ".", COLOR_RED); + } + m_directory = std::move(new_directory); +} + + +std::vector SendableErrorReport::get_pending_reports(){ + std::vector ret; + QDir dir(QString::fromStdString(ERROR_PATH_UNSENT)); + dir.setFilter(QDir::Filter::AllDirs); + QFileInfoList list = dir.entryInfoList(); + for (const auto& item : list){ + std::string path = item.filePath().toStdString(); + if (path.back() == '.'){ + continue; + } + ret.emplace_back(std::move(path)); + } + return ret; +} + +#ifndef PA_OFFICIAL +void SendableErrorReport::send(Logger& logger, std::shared_ptr report){} +#endif + + + +// Send all the reports. This function will return early and all the reports +// will be sent asynchronously in the background. +void send_reports(Logger& logger, const std::vector& reports){ + for (const std::string& path : reports){ + try{ +// static int c = 0; +// cout << "Sending... " << c++ << endl; + // std:::shared_ptr because it needs to take ownership for + // destruction at a later time. + SendableErrorReport::send(logger, std::make_shared(path)); + }catch (Exception& e){ + logger.log("Unable to send report: " + path + ", Message: " + e.to_str(), COLOR_RED); + }catch (...){ + logger.log("Unable to send report: " + path, COLOR_RED); + } + } +} +std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt){ +#ifdef PA_OFFICIAL + ErrorReportSendMode mode = GlobalSettings::instance().ERROR_REPORTS->SEND_MODE; + if (mode == ErrorReportSendMode::NEVER_SEND_ANYTHING){ + return nullptr; + } + + std::vector reports = SendableErrorReport::get_pending_reports(); + global_logger_tagged().log("Found " + std::to_string(reports.size()) + " unsent error reports.", COLOR_PURPLE); + + if (reports.empty()){ + return nullptr; + } + + if (mode == ErrorReportSendMode::PROMPT_WHEN_CONVENIENT){ + if (!allow_prompt){ + return nullptr; + } + QMessageBox box; + QMessageBox::StandardButton button = box.information( + nullptr, + "Error Reporting", + QString::fromStdString( + (reports.size() == 1 + ? "There is " + tostr_u_commas(reports.size()) + " error report.

" + "Would you like to help make this program better by sending it to the developers?

" + : "There are " + tostr_u_commas(reports.size()) + " error reports.

" + "Would you like to help make this program better by sending them to the developers?

" + ) + + make_text_url(ERROR_PATH_UNSENT, "View unsent error reports.")// + "

" +// "(You can change )" + ), + QMessageBox::Yes | QMessageBox::No, + QMessageBox::StandardButton::Yes + ); + if (button != QMessageBox::StandardButton::Yes){ + return nullptr; + } + } + + global_logger_tagged().log("Attempting to send " + std::to_string(reports.size()) + " error reports.", COLOR_PURPLE); + + return global_async_dispatcher().dispatch([reports = std::move(reports)]{ + send_reports(global_logger_tagged(), reports); + }); +#else + return nullptr; +#endif +} + +void report_error( + Logger* logger, + const ProgramInfo& info, + std::string title, + std::vector> messages, + const ImageViewRGB32& image, + const StreamHistorySession* stream_history, + const std::vector& files +){ + if (logger == nullptr){ + logger = &global_logger_tagged(); + } + + { + SendableErrorReport report( + logger, + info, + std::move(title), + std::move(messages), + image, + stream_history + ); + + std::vector full_file_paths; + for (const std::string& file: files){ + full_file_paths.emplace_back(report.directory() + file); + } + + report.save(logger); + } + + send_all_unsent_reports(*logger, false); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h index 0988eb80e1..4814ff00fd 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ErrorReports.h @@ -1,126 +1,126 @@ -/* Error Reports - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ErrorReports_H -#define PokemonAutomation_ErrorReports_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" - -namespace PokemonAutomation{ - - -class AsyncTask; -class StreamHistorySession; - - -extern const std::string& ERROR_LOGS_NAME; -extern const std::string& ERROR_DUMP_NAME; -extern const std::string& ERROR_PATH_UNSENT; -extern const std::string& ERROR_PATH_SENT; - - - -enum class ErrorReportSendMode{ - SEND_AUTOMATICALLY, - PROMPT_WHEN_CONVENIENT, - NEVER_SEND_ANYTHING, -}; - -class ErrorReportOption : public GroupOption{ -public: - ErrorReportOption(); - - StaticTextOption DESCRIPTION; - - EnumDropdownOption SEND_MODE; - - BooleanCheckBoxOption SCREENSHOT; - BooleanCheckBoxOption VIDEO; - BooleanCheckBoxOption LOGS; - BooleanCheckBoxOption DUMPS; - BooleanCheckBoxOption FILES; -}; - - - -class SendableErrorReport{ -public: - SendableErrorReport(); - - // Create new report from current stack. - SendableErrorReport( - Logger* logger, - const ProgramInfo& info = ProgramInfo(), - std::string title = "", - std::vector> messages = {}, - const ImageViewRGB32& image = ImageViewRGB32(), - const StreamHistorySession* stream_history = nullptr - ); - - // Deserialize from existing report. - SendableErrorReport(std::string directory); - - const std::string& directory() const{ - return m_directory; - } - - void add_file(std::string filename); - - void save(Logger* logger) const; - void move_to_sent(); - - static std::vector get_pending_reports(); - static void send(Logger& logger, std::shared_ptr report); - -private: - std::string m_timestamp; - std::string m_directory; - std::string m_processor; - std::string m_program; - std::string m_program_id; - uint64_t m_program_runtime_millis = 0; - std::string m_title; - std::vector> m_messages; - ImageRGB32 m_image_owner; - ImageViewRGB32 m_image; - std::string m_logs_name; - std::string m_video_name; - std::string m_dump_name; - std::vector m_files; -}; - - -void send_reports(Logger& logger, const std::vector& reports); -std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt); - - -void report_error( - Logger* logger = nullptr, - const ProgramInfo& info = ProgramInfo(), - std::string title = "", - std::vector> messages = {}, - const ImageViewRGB32& image = ImageViewRGB32(), - const StreamHistorySession* stream_history = nullptr, - const std::vector& files = {} -); - - - - - - - -} - -#endif +/* Error Reports + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ErrorReports_H +#define PokemonAutomation_ErrorReports_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" + +namespace PokemonAutomation{ + + +class AsyncTask; +class StreamHistorySession; + + +extern const std::string& ERROR_LOGS_NAME; +extern const std::string& ERROR_DUMP_NAME; +extern const std::string& ERROR_PATH_UNSENT; +extern const std::string& ERROR_PATH_SENT; + + + +enum class ErrorReportSendMode{ + SEND_AUTOMATICALLY, + PROMPT_WHEN_CONVENIENT, + NEVER_SEND_ANYTHING, +}; + +class ErrorReportOption : public GroupOption{ +public: + ErrorReportOption(); + + StaticTextOption DESCRIPTION; + + EnumDropdownOption SEND_MODE; + + BooleanCheckBoxOption SCREENSHOT; + BooleanCheckBoxOption VIDEO; + BooleanCheckBoxOption LOGS; + BooleanCheckBoxOption DUMPS; + BooleanCheckBoxOption FILES; +}; + + + +class SendableErrorReport{ +public: + SendableErrorReport(); + + // Create new report from current stack. + SendableErrorReport( + Logger* logger, + const ProgramInfo& info = ProgramInfo(), + std::string title = "", + std::vector> messages = {}, + const ImageViewRGB32& image = ImageViewRGB32(), + const StreamHistorySession* stream_history = nullptr + ); + + // Deserialize from existing report. + SendableErrorReport(std::string directory); + + const std::string& directory() const{ + return m_directory; + } + + void add_file(std::string filename); + + void save(Logger* logger) const; + void move_to_sent(); + + static std::vector get_pending_reports(); + static void send(Logger& logger, std::shared_ptr report); + +private: + std::string m_timestamp; + std::string m_directory; + std::string m_processor; + std::string m_program; + std::string m_program_id; + uint64_t m_program_runtime_millis = 0; + std::string m_title; + std::vector> m_messages; + ImageRGB32 m_image_owner; + ImageViewRGB32 m_image; + std::string m_logs_name; + std::string m_video_name; + std::string m_dump_name; + std::vector m_files; +}; + + +void send_reports(Logger& logger, const std::vector& reports); +std::unique_ptr send_all_unsent_reports(Logger& logger, bool allow_prompt); + + +void report_error( + Logger* logger = nullptr, + const ProgramInfo& info = ProgramInfo(), + std::string title = "", + std::vector> messages = {}, + const ImageViewRGB32& image = ImageViewRGB32(), + const StreamHistorySession* stream_history = nullptr, + const std::vector& files = {} +); + + + + + + + +} + +#endif diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp index ccafa57691..fcfab9910f 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.cpp @@ -1,23 +1,23 @@ -/* Program Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "ProgramDumper.h" - - -#if _WIN32 && _MSC_VER -#include "ProgramDumper_Windows.tpp" - -#else -namespace PokemonAutomation{ - void setup_crash_handler(){ - // Not supported - } - bool program_dump(Logger* logger, const std::string& filename){ - return false; - } -} -#endif +/* Program Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "ProgramDumper.h" + + +#if _WIN32 && _MSC_VER +#include "ProgramDumper_Windows.tpp" + +#else +namespace PokemonAutomation{ + void setup_crash_handler(){ + // Not supported + } + bool program_dump(Logger* logger, const std::string& filename){ + return false; + } +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h index a1e5a595d8..8d2604b3c1 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper.h @@ -1,21 +1,21 @@ -/* Program Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramDumper_H -#define PokemonAutomation_ProgramDumper_H - -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ - - -void setup_crash_handler(); -bool program_dump(Logger* logger, const std::string& filename); - - -} -#endif +/* Program Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramDumper_H +#define PokemonAutomation_ProgramDumper_H + +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ + + +void setup_crash_handler(); +bool program_dump(Logger* logger, const std::string& filename); + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp index 211c9de148..8a668a520a 100644 --- a/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp +++ b/SerialPrograms/Source/CommonFramework/ErrorReports/ProgramDumper_Windows.tpp @@ -1,132 +1,132 @@ -/* Program Dumper (Windows) - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#pragma comment (lib, "Dbghelp.lib") -#include -#include -#include -#include -#include "Common/Cpp/Unicode.h" -#include "Common/Cpp/PrettyPrint.h" -#include "ErrorReports.h" -#include "ProgramDumper.h" - -namespace PokemonAutomation{ - - -class HandleHolder{ -public: - HandleHolder(const HandleHolder&) = delete; - void operator=(const HandleHolder&) = delete; - ~HandleHolder(){ - CloseHandle(m_handle); - } - HandleHolder(HANDLE handle) - : m_handle(handle) - {} - operator bool() const{ - return m_handle != INVALID_HANDLE_VALUE; - } - operator HANDLE() const{ - return m_handle; - } - -private: - HANDLE m_handle; -}; - - -bool program_dump(Logger* logger, const std::string& filename, EXCEPTION_POINTERS* e){ - HandleHolder handle = CreateFileW( - utf8_to_wstr(filename).c_str(), - FILE_WRITE_ACCESS, - FILE_SHARE_READ, - nullptr, - OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, - 0 - ); - if (!handle){ - DWORD error = GetLastError(); - if (logger){ - logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); - }else{ - std::cout << "Unable to create dump file: " << error << std::endl; - } - return false; - } - - int ret; - if (e != nullptr){ - MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; - exceptionInfo.ThreadId = GetCurrentThreadId(); - exceptionInfo.ExceptionPointers = e; - exceptionInfo.ClientPointers = FALSE; - ret = MiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - handle, - MiniDumpNormal, - &exceptionInfo, - nullptr, - nullptr - ); - }else{ - ret = MiniDumpWriteDump( - GetCurrentProcess(), - GetCurrentProcessId(), - handle, - MiniDumpNormal, - nullptr, - nullptr, - nullptr - ); - } - if (!ret){ - DWORD error = GetLastError(); - if (logger){ - logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); - }else{ - std::cout << "Unable to create dump file: " << error << std::endl; - } - return false; - } - - return true; -} -bool program_dump(Logger* logger, const std::string& filename){ - return program_dump(logger, filename, nullptr); -} - - - -long WINAPI crash_handler(EXCEPTION_POINTERS* e){ - static bool handled = false; - if (handled){ - return EXCEPTION_CONTINUE_SEARCH; - } - handled = true; - - SendableErrorReport report; - -// _wmkdir(utf8_to_wstr(ERROR_PATH_UNSENT).c_str()); - program_dump(nullptr, report.directory() + ERROR_DUMP_NAME, e); - report.save(nullptr); - - Sleep(1000); - - return EXCEPTION_CONTINUE_SEARCH; -} - - -void setup_crash_handler(){ -// AddVectoredExceptionHandler(0, crash_handler); - SetUnhandledExceptionFilter(crash_handler); -} - - - -} +/* Program Dumper (Windows) + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#pragma comment (lib, "Dbghelp.lib") +#include +#include +#include +#include +#include "Common/Cpp/Unicode.h" +#include "Common/Cpp/PrettyPrint.h" +#include "ErrorReports.h" +#include "ProgramDumper.h" + +namespace PokemonAutomation{ + + +class HandleHolder{ +public: + HandleHolder(const HandleHolder&) = delete; + void operator=(const HandleHolder&) = delete; + ~HandleHolder(){ + CloseHandle(m_handle); + } + HandleHolder(HANDLE handle) + : m_handle(handle) + {} + operator bool() const{ + return m_handle != INVALID_HANDLE_VALUE; + } + operator HANDLE() const{ + return m_handle; + } + +private: + HANDLE m_handle; +}; + + +bool program_dump(Logger* logger, const std::string& filename, EXCEPTION_POINTERS* e){ + HandleHolder handle = CreateFileW( + utf8_to_wstr(filename).c_str(), + FILE_WRITE_ACCESS, + FILE_SHARE_READ, + nullptr, + OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, + 0 + ); + if (!handle){ + DWORD error = GetLastError(); + if (logger){ + logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); + }else{ + std::cout << "Unable to create dump file: " << error << std::endl; + } + return false; + } + + int ret; + if (e != nullptr){ + MINIDUMP_EXCEPTION_INFORMATION exceptionInfo; + exceptionInfo.ThreadId = GetCurrentThreadId(); + exceptionInfo.ExceptionPointers = e; + exceptionInfo.ClientPointers = FALSE; + ret = MiniDumpWriteDump( + GetCurrentProcess(), + GetCurrentProcessId(), + handle, + MiniDumpNormal, + &exceptionInfo, + nullptr, + nullptr + ); + }else{ + ret = MiniDumpWriteDump( + GetCurrentProcess(), + GetCurrentProcessId(), + handle, + MiniDumpNormal, + nullptr, + nullptr, + nullptr + ); + } + if (!ret){ + DWORD error = GetLastError(); + if (logger){ + logger->log("Unable to create dump file: " + std::to_string(error), COLOR_RED); + }else{ + std::cout << "Unable to create dump file: " << error << std::endl; + } + return false; + } + + return true; +} +bool program_dump(Logger* logger, const std::string& filename){ + return program_dump(logger, filename, nullptr); +} + + + +long WINAPI crash_handler(EXCEPTION_POINTERS* e){ + static bool handled = false; + if (handled){ + return EXCEPTION_CONTINUE_SEARCH; + } + handled = true; + + SendableErrorReport report; + +// _wmkdir(utf8_to_wstr(ERROR_PATH_UNSENT).c_str()); + program_dump(nullptr, report.directory() + ERROR_DUMP_NAME, e); + report.save(nullptr); + + Sleep(1000); + + return EXCEPTION_CONTINUE_SEARCH; +} + + +void setup_crash_handler(){ +// AddVectoredExceptionHandler(0, crash_handler); + SetUnhandledExceptionFilter(crash_handler); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/FatalProgramException.h b/SerialPrograms/Source/CommonFramework/Exceptions/FatalProgramException.h index 9a9a65a77d..72c05ffc7d 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/FatalProgramException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/FatalProgramException.h @@ -1,36 +1,36 @@ -/* Fatal Program Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_FatalProgramException_H -#define PokemonAutomation_FatalProgramException_H - -#include "ScreenshotException.h" - -namespace PokemonAutomation{ - - -// A generic exception that should not be caught outside of infra. -class FatalProgramException : public ScreenshotException{ -public: - using ScreenshotException::ScreenshotException; - FatalProgramException(ScreenshotException&& e) - : ScreenshotException( - e.m_send_error_report, - std::move(e.m_message), - e.m_stream, - std::move(e.m_screenshot) - ) - {} - - virtual const char* name() const override{ return "FatalProgramException"; } -}; - - - - - -} -#endif +/* Fatal Program Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_FatalProgramException_H +#define PokemonAutomation_FatalProgramException_H + +#include "ScreenshotException.h" + +namespace PokemonAutomation{ + + +// A generic exception that should not be caught outside of infra. +class FatalProgramException : public ScreenshotException{ +public: + using ScreenshotException::ScreenshotException; + FatalProgramException(ScreenshotException&& e) + : ScreenshotException( + e.m_send_error_report, + std::move(e.m_message), + e.m_stream, + std::move(e.m_screenshot) + ) + {} + + virtual const char* name() const override{ return "FatalProgramException"; } +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/OperationFailedException.h b/SerialPrograms/Source/CommonFramework/Exceptions/OperationFailedException.h index 3a8cb845d2..cb3147e665 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/OperationFailedException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/OperationFailedException.h @@ -1,48 +1,48 @@ -/* Operation Failed Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_OperationFailedException_H -#define PokemonAutomation_OperationFailedException_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "ScreenshotException.h" - -namespace PokemonAutomation{ - - -// Thrown by subroutines if they fail for an in-game reason. -// These include recoverable errors which can be consumed by the program. -class OperationFailedException : public ScreenshotException{ -public: - using ScreenshotException::ScreenshotException; - - // This is the most common use case. Throw and log exception. - // Include console information for screenshot and stream history. - [[noreturn]] static void fire( - ErrorReport error_report, - std::string message, - VideoStream& stream - ){ - throw_and_log(stream.logger(), error_report, std::move(message), stream); - } - [[noreturn]] static void fire( - ErrorReport error_report, - std::string message, - VideoStream& stream, - std::shared_ptr screenshot - ){ - throw_and_log(stream.logger(), error_report, std::move(message), &stream, std::move(screenshot)); - } - - virtual const char* name() const override{ return "OperationFailedException"; } -}; - - - - - -} -#endif +/* Operation Failed Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_OperationFailedException_H +#define PokemonAutomation_OperationFailedException_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "ScreenshotException.h" + +namespace PokemonAutomation{ + + +// Thrown by subroutines if they fail for an in-game reason. +// These include recoverable errors which can be consumed by the program. +class OperationFailedException : public ScreenshotException{ +public: + using ScreenshotException::ScreenshotException; + + // This is the most common use case. Throw and log exception. + // Include console information for screenshot and stream history. + [[noreturn]] static void fire( + ErrorReport error_report, + std::string message, + VideoStream& stream + ){ + throw_and_log(stream.logger(), error_report, std::move(message), stream); + } + [[noreturn]] static void fire( + ErrorReport error_report, + std::string message, + VideoStream& stream, + std::shared_ptr screenshot + ){ + throw_and_log(stream.logger(), error_report, std::move(message), &stream, std::move(screenshot)); + } + + virtual const char* name() const override{ return "OperationFailedException"; } +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.cpp b/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.cpp index e0396fc636..def4699c85 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.cpp +++ b/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.cpp @@ -1,49 +1,49 @@ -/* Program Finished Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "ProgramFinishedException.h" - -namespace PokemonAutomation{ - - -ProgramFinishedException::ProgramFinishedException(){} -ProgramFinishedException::ProgramFinishedException(std::string message) - : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message)) -{} - - -ProgramFinishedException::ProgramFinishedException( - std::string message, - VideoStream& stream -) - : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message), stream) -{} -ProgramFinishedException::ProgramFinishedException( - ErrorReport error_report, - std::string message, - VideoStream* stream, - ImageRGB32 screenshot -) - : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message), stream, std::move(screenshot)) -{} -ProgramFinishedException::ProgramFinishedException( - std::string message, - VideoStream* stream, - std::shared_ptr screenshot -) - : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message), stream, std::move(screenshot)) -{} - -void ProgramFinishedException::log(Logger& logger) const{ - logger.log(std::string(name()) + ": " + message(), COLOR_BLUE); -} - - - - -} +/* Program Finished Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "ProgramFinishedException.h" + +namespace PokemonAutomation{ + + +ProgramFinishedException::ProgramFinishedException(){} +ProgramFinishedException::ProgramFinishedException(std::string message) + : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message)) +{} + + +ProgramFinishedException::ProgramFinishedException( + std::string message, + VideoStream& stream +) + : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message), stream) +{} +ProgramFinishedException::ProgramFinishedException( + ErrorReport error_report, + std::string message, + VideoStream* stream, + ImageRGB32 screenshot +) + : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message), stream, std::move(screenshot)) +{} +ProgramFinishedException::ProgramFinishedException( + std::string message, + VideoStream* stream, + std::shared_ptr screenshot +) + : ScreenshotException(ErrorReport::NO_ERROR_REPORT, std::move(message), stream, std::move(screenshot)) +{} + +void ProgramFinishedException::log(Logger& logger) const{ + logger.log(std::string(name()) + ": " + message(), COLOR_BLUE); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.h b/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.h index 45dd5fe942..931999d424 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/ProgramFinishedException.h @@ -1,65 +1,65 @@ -/* Program Finished Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramFinishedException_H -#define PokemonAutomation_ProgramFinishedException_H - -#include -#include "ScreenshotException.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; -class EventNotificationOption; -struct ProgramInfo; -class ProgramEnvironment; - - - -// Thrown when the program requests a normal stop to the program. -// - This should not be consumed except by the infra. -// - Non-infra are allowed to catch and rethrow this exception. -class ProgramFinishedException : public ScreenshotException{ -public: - ProgramFinishedException(); - explicit ProgramFinishedException(std::string message); - - // Construct exception with message and console information. - // This will take a screenshot and store the console if the stream history if requested later. - explicit ProgramFinishedException( - std::string message, - VideoStream& stream - ); - - // Construct exception with message with screenshot and (optionally) console information. - // Use the provided screenshot instead of taking one with the console. - // Store the console information (if provided) for stream history if requested later. - explicit ProgramFinishedException( - ErrorReport error_report, - std::string message, - VideoStream* stream, - ImageRGB32 screenshot - ); - explicit ProgramFinishedException( - std::string message, - VideoStream* stream, - std::shared_ptr screenshot - ); - - virtual Color color() const override{ return COLOR_GREEN; } - -public: - virtual void log(Logger& logger) const override; - virtual const char* name() const override{ return "ProgramFinishedException"; } -}; - - - - - -} -#endif +/* Program Finished Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramFinishedException_H +#define PokemonAutomation_ProgramFinishedException_H + +#include +#include "ScreenshotException.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; +class EventNotificationOption; +struct ProgramInfo; +class ProgramEnvironment; + + + +// Thrown when the program requests a normal stop to the program. +// - This should not be consumed except by the infra. +// - Non-infra are allowed to catch and rethrow this exception. +class ProgramFinishedException : public ScreenshotException{ +public: + ProgramFinishedException(); + explicit ProgramFinishedException(std::string message); + + // Construct exception with message and console information. + // This will take a screenshot and store the console if the stream history if requested later. + explicit ProgramFinishedException( + std::string message, + VideoStream& stream + ); + + // Construct exception with message with screenshot and (optionally) console information. + // Use the provided screenshot instead of taking one with the console. + // Store the console information (if provided) for stream history if requested later. + explicit ProgramFinishedException( + ErrorReport error_report, + std::string message, + VideoStream* stream, + ImageRGB32 screenshot + ); + explicit ProgramFinishedException( + std::string message, + VideoStream* stream, + std::shared_ptr screenshot + ); + + virtual Color color() const override{ return COLOR_GREEN; } + +public: + virtual void log(Logger& logger) const override; + virtual const char* name() const override{ return "ProgramFinishedException"; } +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp index 29c629b014..a4d16a09e8 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp +++ b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.cpp @@ -1,115 +1,115 @@ -/* Screenshot Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ErrorReports/ErrorReports.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "ScreenshotException.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -ScreenshotException::ScreenshotException(ErrorReport error_report, std::string message) - : m_send_error_report(error_report) - , m_message(std::move(message)) -{} -ScreenshotException::ScreenshotException( - ErrorReport error_report, - std::string message, - VideoStream& stream -) - : m_send_error_report(error_report) - , m_message(std::move(message)) - , m_stream(&stream) - , m_screenshot(stream.video().snapshot().frame) -{ - if (m_screenshot == nullptr || !*m_screenshot){ - stream.log("Camera returned empty screenshot. Is the camera frozen?", COLOR_RED); - } -} -ScreenshotException::ScreenshotException( - ErrorReport error_report, - std::string message, - VideoStream* stream, - ImageRGB32 screenshot -) - : m_send_error_report(error_report) - , m_message(std::move(message)) - , m_stream(stream) - , m_screenshot(std::make_shared(std::move(screenshot))) -{} -ScreenshotException::ScreenshotException( - ErrorReport error_report, - std::string message, - VideoStream* stream, - std::shared_ptr screenshot -) - : m_send_error_report(error_report) - , m_message(std::move(message)) - , m_stream(stream) - , m_screenshot(std::move(screenshot)) -{} - - -void ScreenshotException::add_stream_if_needed(VideoStream& stream){ - if (m_stream == nullptr){ - m_stream = &stream; - } - if (!m_screenshot){ - m_screenshot = stream.video().snapshot(); - if (m_screenshot == nullptr || !*m_screenshot){ - stream.log("Camera returned empty screenshot. Is the camera frozen?", COLOR_RED); - } - } -} - -ImageViewRGB32 ScreenshotException::screenshot() const{ - if (m_screenshot){ - return *m_screenshot; - }else{ - return ImageViewRGB32(); - } -} - - -void ScreenshotException::send_notification(ProgramEnvironment& env, EventNotificationOption& notification) const{ - std::vector> embeds; - if (!m_message.empty()){ - embeds.emplace_back(std::pair("Message:", m_message)); - } - - if (m_send_error_report == ErrorReport::SEND_ERROR_REPORT){ - report_error( - &env.logger(), - env.program_info(), - name(), - embeds, - screenshot(), - m_stream ? &m_stream->history() : nullptr - ); - } - - send_program_notification( - env, notification, - color(), - name(), - std::move(embeds), "", - screenshot() - ); -} - - - - - -} +/* Screenshot Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ErrorReports/ErrorReports.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "ScreenshotException.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +ScreenshotException::ScreenshotException(ErrorReport error_report, std::string message) + : m_send_error_report(error_report) + , m_message(std::move(message)) +{} +ScreenshotException::ScreenshotException( + ErrorReport error_report, + std::string message, + VideoStream& stream +) + : m_send_error_report(error_report) + , m_message(std::move(message)) + , m_stream(&stream) + , m_screenshot(stream.video().snapshot().frame) +{ + if (m_screenshot == nullptr || !*m_screenshot){ + stream.log("Camera returned empty screenshot. Is the camera frozen?", COLOR_RED); + } +} +ScreenshotException::ScreenshotException( + ErrorReport error_report, + std::string message, + VideoStream* stream, + ImageRGB32 screenshot +) + : m_send_error_report(error_report) + , m_message(std::move(message)) + , m_stream(stream) + , m_screenshot(std::make_shared(std::move(screenshot))) +{} +ScreenshotException::ScreenshotException( + ErrorReport error_report, + std::string message, + VideoStream* stream, + std::shared_ptr screenshot +) + : m_send_error_report(error_report) + , m_message(std::move(message)) + , m_stream(stream) + , m_screenshot(std::move(screenshot)) +{} + + +void ScreenshotException::add_stream_if_needed(VideoStream& stream){ + if (m_stream == nullptr){ + m_stream = &stream; + } + if (!m_screenshot){ + m_screenshot = stream.video().snapshot(); + if (m_screenshot == nullptr || !*m_screenshot){ + stream.log("Camera returned empty screenshot. Is the camera frozen?", COLOR_RED); + } + } +} + +ImageViewRGB32 ScreenshotException::screenshot() const{ + if (m_screenshot){ + return *m_screenshot; + }else{ + return ImageViewRGB32(); + } +} + + +void ScreenshotException::send_notification(ProgramEnvironment& env, EventNotificationOption& notification) const{ + std::vector> embeds; + if (!m_message.empty()){ + embeds.emplace_back(std::pair("Message:", m_message)); + } + + if (m_send_error_report == ErrorReport::SEND_ERROR_REPORT){ + report_error( + &env.logger(), + env.program_info(), + name(), + embeds, + screenshot(), + m_stream ? &m_stream->history() : nullptr + ); + } + + send_program_notification( + env, notification, + color(), + name(), + std::move(embeds), "", + screenshot() + ); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h index 0a654cff67..c9aaa38554 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/ScreenshotException.h @@ -1,87 +1,87 @@ -/* Screenshot Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ScreenshotException_H -#define PokemonAutomation_ScreenshotException_H - -#include -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; -class EventNotificationOption; -class VideoStream; -struct ProgramInfo; -class ProgramEnvironment; - - -enum class ErrorReport{ - NO_ERROR_REPORT, - SEND_ERROR_REPORT, -}; - - -// Do not use this class directly. It is just to reuse the screenshot holding -// logic that's shared by multiple exception types. -class ScreenshotException : public Exception{ -public: - ScreenshotException() = default; - - // Construct exception with a simple message. - explicit ScreenshotException(ErrorReport error_report, std::string message); - - // Construct exception with message and console information. - // This will take a screenshot and store the console if the stream history if requested later. - explicit ScreenshotException( - ErrorReport error_report, - std::string message, - VideoStream& stream - ); - - // Construct exception with message with screenshot and (optionally) console information. - // Use the provided screenshot instead of taking one with the console. - // Store the console information (if provided) for stream history if requested later. - explicit ScreenshotException( - ErrorReport error_report, - std::string message, - VideoStream* stream, - ImageRGB32 screenshot - ); - explicit ScreenshotException( - ErrorReport error_report, - std::string message, - VideoStream* stream, - std::shared_ptr screenshot - ); - - // Add console information if it isn't already requested. - // This will provide screenshot and stream history if requested later. - void add_stream_if_needed(VideoStream& stream); - - -public: -// virtual const char* name() const override{ return "ScreenshotException"; } - virtual std::string message() const override{ return m_message; } - ImageViewRGB32 screenshot() const; - - virtual Color color() const{ return COLOR_RED; } - virtual void send_notification(ProgramEnvironment& env, EventNotificationOption& notification) const; - -public: - ErrorReport m_send_error_report; - std::string m_message; - VideoStream* m_stream = nullptr; - std::shared_ptr m_screenshot; -}; - - - - - -} -#endif +/* Screenshot Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ScreenshotException_H +#define PokemonAutomation_ScreenshotException_H + +#include +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; +class EventNotificationOption; +class VideoStream; +struct ProgramInfo; +class ProgramEnvironment; + + +enum class ErrorReport{ + NO_ERROR_REPORT, + SEND_ERROR_REPORT, +}; + + +// Do not use this class directly. It is just to reuse the screenshot holding +// logic that's shared by multiple exception types. +class ScreenshotException : public Exception{ +public: + ScreenshotException() = default; + + // Construct exception with a simple message. + explicit ScreenshotException(ErrorReport error_report, std::string message); + + // Construct exception with message and console information. + // This will take a screenshot and store the console if the stream history if requested later. + explicit ScreenshotException( + ErrorReport error_report, + std::string message, + VideoStream& stream + ); + + // Construct exception with message with screenshot and (optionally) console information. + // Use the provided screenshot instead of taking one with the console. + // Store the console information (if provided) for stream history if requested later. + explicit ScreenshotException( + ErrorReport error_report, + std::string message, + VideoStream* stream, + ImageRGB32 screenshot + ); + explicit ScreenshotException( + ErrorReport error_report, + std::string message, + VideoStream* stream, + std::shared_ptr screenshot + ); + + // Add console information if it isn't already requested. + // This will provide screenshot and stream history if requested later. + void add_stream_if_needed(VideoStream& stream); + + +public: +// virtual const char* name() const override{ return "ScreenshotException"; } + virtual std::string message() const override{ return m_message; } + ImageViewRGB32 screenshot() const; + + virtual Color color() const{ return COLOR_RED; } + virtual void send_notification(ProgramEnvironment& env, EventNotificationOption& notification) const; + +public: + ErrorReport m_send_error_report; + std::string m_message; + VideoStream* m_stream = nullptr; + std::shared_ptr m_screenshot; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h b/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h index 30e609c5c1..7d0e9757b1 100644 --- a/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h +++ b/SerialPrograms/Source/CommonFramework/Exceptions/UnexpectedBattleException.h @@ -1,31 +1,31 @@ -/* Unexpected Battle Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_UnexpectedBattleException_H -#define PokemonAutomation_UnexpectedBattleException_H - -#include "ScreenshotException.h" - -namespace PokemonAutomation{ - -class FatalProgramException; - - -// Thrown by subroutines if caught in an wild battle in-game unexpectedly. -// These include recoverable errors which can be consumed by the program. -class UnexpectedBattleException : public ScreenshotException{ -public: - using ScreenshotException::ScreenshotException; - - virtual const char* name() const override{ return "UnexpectedBattleException"; } -}; - - - - - -} -#endif +/* Unexpected Battle Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_UnexpectedBattleException_H +#define PokemonAutomation_UnexpectedBattleException_H + +#include "ScreenshotException.h" + +namespace PokemonAutomation{ + +class FatalProgramException; + + +// Thrown by subroutines if caught in an wild battle in-game unexpectedly. +// These include recoverable errors which can be consumed by the program. +class UnexpectedBattleException : public ScreenshotException{ +public: + using ScreenshotException::ScreenshotException; + + virtual const char* name() const override{ return "UnexpectedBattleException"; } +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/GlobalServices.cpp b/SerialPrograms/Source/CommonFramework/GlobalServices.cpp index ae492e9bc3..c4ec416342 100644 --- a/SerialPrograms/Source/CommonFramework/GlobalServices.cpp +++ b/SerialPrograms/Source/CommonFramework/GlobalServices.cpp @@ -1,31 +1,31 @@ -/* Global Services - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "Common/Cpp/Concurrency/Watchdog.h" -#include "GlobalServices.h" - -namespace PokemonAutomation{ - - -AsyncDispatcher& global_async_dispatcher(){ - static AsyncDispatcher dispatcher(nullptr, 1); - return dispatcher; -} -#if 0 -ScheduledTaskRunner& global_scheduled_task_runner(){ - static ScheduledTaskRunner runner(global_async_dispatcher()); - return runner; -} -#endif -Watchdog& global_watchdog(){ - static Watchdog watchdog; - return watchdog; -} - - - -} +/* Global Services + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" +#include "Common/Cpp/Concurrency/Watchdog.h" +#include "GlobalServices.h" + +namespace PokemonAutomation{ + + +AsyncDispatcher& global_async_dispatcher(){ + static AsyncDispatcher dispatcher(nullptr, 1); + return dispatcher; +} +#if 0 +ScheduledTaskRunner& global_scheduled_task_runner(){ + static ScheduledTaskRunner runner(global_async_dispatcher()); + return runner; +} +#endif +Watchdog& global_watchdog(){ + static Watchdog watchdog; + return watchdog; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/GlobalServices.h b/SerialPrograms/Source/CommonFramework/GlobalServices.h index 59c81d4191..f81cb1cc38 100644 --- a/SerialPrograms/Source/CommonFramework/GlobalServices.h +++ b/SerialPrograms/Source/CommonFramework/GlobalServices.h @@ -1,24 +1,24 @@ -/* Global Services - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_GlobalServices_H -#define PokemonAutomation_GlobalServices_H - -namespace PokemonAutomation{ - -class AsyncDispatcher; -class ScheduledTaskRunner; -class Watchdog; - - -AsyncDispatcher& global_async_dispatcher(); -//ScheduledTaskRunner& global_scheduled_task_runner(); -Watchdog& global_watchdog(); - - - -} -#endif +/* Global Services + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_GlobalServices_H +#define PokemonAutomation_GlobalServices_H + +namespace PokemonAutomation{ + +class AsyncDispatcher; +class ScheduledTaskRunner; +class Watchdog; + + +AsyncDispatcher& global_async_dispatcher(); +//ScheduledTaskRunner& global_scheduled_task_runner(); +Watchdog& global_watchdog(); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp index 2aeed75bcc..b3f47f5baa 100644 --- a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp +++ b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.cpp @@ -1,401 +1,401 @@ -/* Global Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Options/CheckForUpdatesOption.h" -#include "CommonFramework/Options/ResolutionOption.h" -#include "CommonFramework/Options/Environment/SleepSuppressOption.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "CommonFramework/Recording/StreamHistoryOption.h" -#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" -#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" -#include "CommonFramework/ErrorReports/ErrorReports.h" -#include "Integrations/DiscordSettingsOption.h" -//#include "CommonFramework/Environment/Environment.h" -#include "GlobalSettingsPanel.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ - - -const std::set TOKENS{ -// "f6538243092d8a3b9959bca988f054e1670f57c7246df2cbba25c4df3fe7a4e7", - "2d04af67f6520e3550842d7eeb292868c6d0d4809b607f5a454712023d8815e1", - "475d0a0a305a02cbf8b602bd47c3b275dccd5ac19fbe480729804a8e4e360b71", - "6643d9fe87b3e54dc75dfac8ac22f0cc8bd17f6a8a786debf5fc4c517ee65469", - "8e48e38e49bffc8462ada9d2d9d850d5b3b5c9529d20978c09bc548bc9a614a4", - "7694adee4419d62c6a923c4efc9e7b41def7b96bb84ea882701b0bf2e8c13bee", - "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", // jw's token. - "e8d168bc482e96553ea9f9ecaea5a817474dbccc2a6a228a6bde67f2b2aa2889", // James' token. - "7555b7c63481cad42306718c67e7f9def5bfd1da8f6cd299ccd3d7dc95f307ae", // Kuro's token. - "3d475b46d121fc24559d100de2426feaa53cd6578aac2817c4857a610ccde2dd", // kichi's token. -}; - - - - - -PreloadSettings::PreloadSettings(){} -PreloadSettings& PreloadSettings::instance(){ - static PreloadSettings settings; - return settings; -} -DebugSettings& PreloadSettings::debug(){ - return PreloadSettings::instance().DEBUG; -} - -void PreloadSettings::load(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - // Naughty mode. - obj->read_boolean(NAUGHTY_MODE, "NAUGHTY_MODE"); - - // Developer mode stuff. - const std::string* dev_token = obj->get_string("DEVELOPER_TOKEN"); - if (dev_token){ - QCryptographicHash hash(QCryptographicHash::Algorithm::Sha256); -#if QT_VERSION < 0x060700 - hash.addData(dev_token->c_str(), (int)dev_token->size()); -#else - QByteArrayView dataView(dev_token->data(), dev_token->size()); - hash.addData(dataView); -#endif - DEVELOPER_MODE = TOKENS.find(hash.result().toHex().toStdString()) != TOKENS.end(); - } - - const JsonObject* debug_obj = obj->get_object("DEBUG"); - if (debug_obj){ - debug_obj->read_boolean(DEBUG.COLOR_CHECK, "COLOR_CHECK"); - debug_obj->read_boolean(DEBUG.IMAGE_TEMPLATE_MATCHING, "IMAGE_TEMPLATE_MATCHING"); - debug_obj->read_boolean(DEBUG.IMAGE_DICTIONARY_MATCHING, "IMAGE_DICTIONARY_MATCHING"); - } -} - - - - -GlobalSettings& GlobalSettings::instance(){ - static GlobalSettings settings; - return settings; -} -GlobalSettings::~GlobalSettings(){ - ENABLE_LIFETIME_SANITIZER0.remove_listener(*this); -} -GlobalSettings::GlobalSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , CHECK_FOR_UPDATES(CONSTRUCT_TOKEN) - , STATS_FILE( - false, - "Stats File:
Use the stats file here. Multiple instances of the program can use the same file.", - LockMode::LOCK_WHILE_RUNNING, -#if defined(__APPLE__) - QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/UserSettings/PA-Stats.txt", - QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/UserSettings/PA-Stats.txt" -#else - "UserSettings/PA-Stats.txt", - "UserSettings/PA-Stats.txt" -#endif - ) - , TEMP_FOLDER( - false, - "Temp Folder:
Place temporary files in this directory.", - LockMode::LOCK_WHILE_RUNNING, -#if defined(__APPLE__) - QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/TempFiles/", - QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/TempFiles/" -#else - "TempFiles/", - "TempFiles/" -#endif - ) - , THEME(CONSTRUCT_TOKEN) - , WINDOW_SIZE( - CONSTRUCT_TOKEN, - "Window Size/Position:", - "Set the size/position of the window. Takes effect immediately.
" - "Use this to easily set the window to a specific resolution for streaming alignment.", - 1280, 1000, - 0, 0 - ) - , LOG_WINDOW_SIZE( - CONSTRUCT_TOKEN, - "Output Window Size/Position:", - "Set the size/position of the output window. Takes effect immediately.
", - 600, 1200, - 0, 0 - ) - , LOG_WINDOW_STARTUP( - "Open Output Window at startup:", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , STREAM_HISTORY(CONSTRUCT_TOKEN) - , SLEEP_SUPPRESS(CONSTRUCT_TOKEN) - , m_discord_settings( - "Discord Settings: Integrate with Discord. (" + - make_text_url( - ONLINE_DOC_URL_BASE + "ComputerControl/blob/master/Wiki/Software/DiscordIntegration.md", - "online documentation" - ) + ")" - ) - , ALL_STATS( - "All Stats:
Include all-time stats for notifications.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , DISCORD(CONSTRUCT_TOKEN) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , LOG_EVERYTHING( - "Log Everything:
Log everything to the output window and output log. Will be very spammy.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , SAVE_DEBUG_IMAGES( - "Save Debug Images:
" - "If the program fails to read something when it should succeed, save the image for debugging purposes.", - LockMode::LOCK_WHILE_RUNNING, - true - ) -// , NAUGHTY_MODE_OPTION("Naughty Mode:", false) - , HIDE_NOTIF_DISCORD_LINK( - "Hide Discord Link in Notifications:
" - "Many Discord servers have rules forbidding links to other Discord servers. " - "Checking this box will hide the support link that appears in the footer of every Discord notification.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , PERFORMANCE(CONSTRUCT_TOKEN) - , AUDIO_PIPELINE(CONSTRUCT_TOKEN) - , VIDEO_PIPELINE(CONSTRUCT_TOKEN) - , ENABLE_LIFETIME_SANITIZER0( - "Enable Lifetime Sanitizer: (for debugging)
" - "Check for C++ object lifetime violations. Terminate program with stack dump if violations are found. " - "If enabling, you must restart the program for it to take effect.", - LockMode::UNLOCK_WHILE_RUNNING, - true -// IS_BETA_VERSION - ) - , ERROR_REPORTS(CONSTRUCT_TOKEN) - , DEVELOPER_TOKEN( - true, - "Developer Token:
Restart application to take full effect after changing this.", - LockMode::LOCK_WHILE_RUNNING, - "", "" - ) -{ - PA_ADD_OPTION(CHECK_FOR_UPDATES); - PA_ADD_OPTION(STATS_FILE); - PA_ADD_OPTION(TEMP_FOLDER); - PA_ADD_OPTION(THEME); - PA_ADD_OPTION(WINDOW_SIZE); - PA_ADD_OPTION(LOG_WINDOW_SIZE); - PA_ADD_OPTION(LOG_WINDOW_STARTUP); -#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) - if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(STREAM_HISTORY); - } -#else - STREAM_HISTORY->set_enabled(false); -#endif -#ifdef PA_ENABLE_SLEEP_SUPPRESS - PA_ADD_OPTION(SLEEP_SUPPRESS); -#endif - - PA_ADD_STATIC(m_discord_settings); - PA_ADD_OPTION(ALL_STATS); - PA_ADD_OPTION(DISCORD); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(LOG_EVERYTHING); - PA_ADD_OPTION(SAVE_DEBUG_IMAGES); -// PA_ADD_OPTION(NAUGHTY_MODE); - PA_ADD_OPTION(HIDE_NOTIF_DISCORD_LINK); - - PA_ADD_OPTION(PERFORMANCE); - - PA_ADD_OPTION(AUDIO_PIPELINE); - PA_ADD_OPTION(VIDEO_PIPELINE); - - PA_ADD_OPTION(ENABLE_LIFETIME_SANITIZER0); - -#ifdef PA_OFFICIAL - PA_ADD_OPTION(ERROR_REPORTS); -#endif - - PA_ADD_OPTION(DEVELOPER_TOKEN); - - GlobalSettings::on_config_value_changed(this); - ENABLE_LIFETIME_SANITIZER0.add_listener(*this); -} - -void GlobalSettings::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - PreloadSettings::instance().load(json); - - BatchOption::load_json(json); - - // Remake this to update the color. - m_discord_settings.set_text( - "Discord Settings: Integrate with Discord. (" + - make_text_url( - ONLINE_DOC_URL_BASE + "ComputerControl/blob/master/Wiki/Software/DiscordIntegration.md", - "online documentation" - ) + ")" - ); - - COMMAND_LINE_TEST_LIST.clear(); - COMMAND_LINE_IGNORE_LIST.clear(); - const JsonObject* command_line_tests_setting = obj->get_object("COMMAND_LINE_TESTS"); - if (command_line_tests_setting){ - command_line_tests_setting->read_boolean(COMMAND_LINE_TEST_MODE, "RUN"); - - if (!command_line_tests_setting->read_string(COMMAND_LINE_TEST_FOLDER, "FOLDER")){ - COMMAND_LINE_TEST_FOLDER = "CommandLineTests"; - } - - const JsonArray* test_list = command_line_tests_setting->get_array("TEST_LIST"); - if (test_list){ - for (const auto& value: *test_list){ - if (!value.is_string()){ - continue; - } - const std::string* test_name = value.to_string(); - if (test_name != nullptr && !test_name->empty()){ - COMMAND_LINE_TEST_LIST.emplace_back(*test_name); - } - } - } - const JsonArray* ignore_list = command_line_tests_setting->get_array("IGNORE_LIST"); - if (ignore_list){ - for (const auto& value: *ignore_list){ - if (!value.is_string()){ - continue; - } - const std::string* test_name = value.to_string(); - if (test_name != nullptr && !test_name->empty()){ - COMMAND_LINE_IGNORE_LIST.emplace_back(*test_name); - } - } - } - - if (COMMAND_LINE_TEST_MODE){ - std::cout << "Enter command line test mode:" << std::endl; - if (COMMAND_LINE_TEST_LIST.size() > 0){ - std::cout << "Run following tests: " << std::endl; - for(const auto& name : COMMAND_LINE_TEST_LIST){ - std::cout << "- " << name << std::endl; - } - } - if (COMMAND_LINE_IGNORE_LIST.size() > 0){ - std::cout << "Ignore following " << COMMAND_LINE_IGNORE_LIST.size() << " paths: " << std::endl; - const size_t MAX_LINES = 5; - for(size_t i = 0; i < COMMAND_LINE_IGNORE_LIST.size() && i < MAX_LINES; i++){ - std::cout << "- " << COMMAND_LINE_IGNORE_LIST[i] << std::endl; - } - if (COMMAND_LINE_IGNORE_LIST.size() > MAX_LINES){ - std::cout << "..." << std::endl; - } - } - } - } -} - - -JsonValue GlobalSettings::to_json() const{ - JsonObject obj = std::move(*BatchOption::to_json().to_object()); - obj["NAUGHTY_MODE"] = PreloadSettings::instance().NAUGHTY_MODE; - - JsonObject command_line_test_obj; - command_line_test_obj["RUN"] = COMMAND_LINE_TEST_MODE; - command_line_test_obj["FOLDER"] = COMMAND_LINE_TEST_FOLDER; - - { - JsonArray test_list; - for(const auto& name : COMMAND_LINE_TEST_LIST){ - test_list.push_back(name); - } - command_line_test_obj["TEST_LIST"] = std::move(test_list); - } - - { - JsonArray ignore_list; - for(const auto& name : COMMAND_LINE_IGNORE_LIST){ - ignore_list.push_back(name); - } - command_line_test_obj["IGNORE_LIST"] = std::move(ignore_list); - } - - obj["COMMAND_LINE_TESTS"] = std::move(command_line_test_obj); - - JsonObject debug_obj; - const auto& debug_settings = PreloadSettings::instance().DEBUG; - debug_obj["COLOR_CHECK"] = debug_settings.COLOR_CHECK; - debug_obj["IMAGE_TEMPLATE_MATCHING"] = debug_settings.IMAGE_TEMPLATE_MATCHING; - debug_obj["IMAGE_DICTIONARY_MATCHING"] = debug_settings.IMAGE_DICTIONARY_MATCHING; - obj["DEBUG"] = std::move(debug_obj); - - return obj; -} - -void GlobalSettings::on_config_value_changed(void* object){ - bool enabled = ENABLE_LIFETIME_SANITIZER0; - if (enabled){ - global_logger_tagged().log("LifeTime Sanitizer: Enabled", COLOR_BLUE); - }else{ - global_logger_tagged().log("LifeTime Sanitizer: Disabled", COLOR_BLUE); - LifetimeSanitizer::disable(); - } -} - - - - - - -PanelDescriptorWrapper GlobalSettings_Descriptor::INSTANCE; - -GlobalSettings_Descriptor::GlobalSettings_Descriptor() - : PanelDescriptor( - Color(), - "", - "Global Settings", "Global Settings", - "", - "Global Settings" - ) -{} - - -GlobalSettingsPanel::GlobalSettingsPanel(const GlobalSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GlobalSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - -} +/* Global Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Options/CheckForUpdatesOption.h" +#include "CommonFramework/Options/ResolutionOption.h" +#include "CommonFramework/Options/Environment/SleepSuppressOption.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" +#include "CommonFramework/AudioPipeline/AudioPipelineOptions.h" +#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" +#include "CommonFramework/ErrorReports/ErrorReports.h" +#include "Integrations/DiscordSettingsOption.h" +//#include "CommonFramework/Environment/Environment.h" +#include "GlobalSettingsPanel.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ + + +const std::set TOKENS{ +// "f6538243092d8a3b9959bca988f054e1670f57c7246df2cbba25c4df3fe7a4e7", + "2d04af67f6520e3550842d7eeb292868c6d0d4809b607f5a454712023d8815e1", + "475d0a0a305a02cbf8b602bd47c3b275dccd5ac19fbe480729804a8e4e360b71", + "6643d9fe87b3e54dc75dfac8ac22f0cc8bd17f6a8a786debf5fc4c517ee65469", + "8e48e38e49bffc8462ada9d2d9d850d5b3b5c9529d20978c09bc548bc9a614a4", + "7694adee4419d62c6a923c4efc9e7b41def7b96bb84ea882701b0bf2e8c13bee", + "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08", // jw's token. + "e8d168bc482e96553ea9f9ecaea5a817474dbccc2a6a228a6bde67f2b2aa2889", // James' token. + "7555b7c63481cad42306718c67e7f9def5bfd1da8f6cd299ccd3d7dc95f307ae", // Kuro's token. + "3d475b46d121fc24559d100de2426feaa53cd6578aac2817c4857a610ccde2dd", // kichi's token. +}; + + + + + +PreloadSettings::PreloadSettings(){} +PreloadSettings& PreloadSettings::instance(){ + static PreloadSettings settings; + return settings; +} +DebugSettings& PreloadSettings::debug(){ + return PreloadSettings::instance().DEBUG; +} + +void PreloadSettings::load(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + // Naughty mode. + obj->read_boolean(NAUGHTY_MODE, "NAUGHTY_MODE"); + + // Developer mode stuff. + const std::string* dev_token = obj->get_string("DEVELOPER_TOKEN"); + if (dev_token){ + QCryptographicHash hash(QCryptographicHash::Algorithm::Sha256); +#if QT_VERSION < 0x060700 + hash.addData(dev_token->c_str(), (int)dev_token->size()); +#else + QByteArrayView dataView(dev_token->data(), dev_token->size()); + hash.addData(dataView); +#endif + DEVELOPER_MODE = TOKENS.find(hash.result().toHex().toStdString()) != TOKENS.end(); + } + + const JsonObject* debug_obj = obj->get_object("DEBUG"); + if (debug_obj){ + debug_obj->read_boolean(DEBUG.COLOR_CHECK, "COLOR_CHECK"); + debug_obj->read_boolean(DEBUG.IMAGE_TEMPLATE_MATCHING, "IMAGE_TEMPLATE_MATCHING"); + debug_obj->read_boolean(DEBUG.IMAGE_DICTIONARY_MATCHING, "IMAGE_DICTIONARY_MATCHING"); + } +} + + + + +GlobalSettings& GlobalSettings::instance(){ + static GlobalSettings settings; + return settings; +} +GlobalSettings::~GlobalSettings(){ + ENABLE_LIFETIME_SANITIZER0.remove_listener(*this); +} +GlobalSettings::GlobalSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , CHECK_FOR_UPDATES(CONSTRUCT_TOKEN) + , STATS_FILE( + false, + "Stats File:
Use the stats file here. Multiple instances of the program can use the same file.", + LockMode::LOCK_WHILE_RUNNING, +#if defined(__APPLE__) + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/UserSettings/PA-Stats.txt", + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/UserSettings/PA-Stats.txt" +#else + "UserSettings/PA-Stats.txt", + "UserSettings/PA-Stats.txt" +#endif + ) + , TEMP_FOLDER( + false, + "Temp Folder:
Place temporary files in this directory.", + LockMode::LOCK_WHILE_RUNNING, +#if defined(__APPLE__) + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/TempFiles/", + QStandardPaths::writableLocation(QStandardPaths::AppDataLocation).toStdString() + "/TempFiles/" +#else + "TempFiles/", + "TempFiles/" +#endif + ) + , THEME(CONSTRUCT_TOKEN) + , WINDOW_SIZE( + CONSTRUCT_TOKEN, + "Window Size/Position:", + "Set the size/position of the window. Takes effect immediately.
" + "Use this to easily set the window to a specific resolution for streaming alignment.", + 1280, 1000, + 0, 0 + ) + , LOG_WINDOW_SIZE( + CONSTRUCT_TOKEN, + "Output Window Size/Position:", + "Set the size/position of the output window. Takes effect immediately.
", + 600, 1200, + 0, 0 + ) + , LOG_WINDOW_STARTUP( + "Open Output Window at startup:", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , STREAM_HISTORY(CONSTRUCT_TOKEN) + , SLEEP_SUPPRESS(CONSTRUCT_TOKEN) + , m_discord_settings( + "Discord Settings: Integrate with Discord. (" + + make_text_url( + ONLINE_DOC_URL_BASE + "ComputerControl/blob/master/Wiki/Software/DiscordIntegration.md", + "online documentation" + ) + ")" + ) + , ALL_STATS( + "All Stats:
Include all-time stats for notifications.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , DISCORD(CONSTRUCT_TOKEN) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , LOG_EVERYTHING( + "Log Everything:
Log everything to the output window and output log. Will be very spammy.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , SAVE_DEBUG_IMAGES( + "Save Debug Images:
" + "If the program fails to read something when it should succeed, save the image for debugging purposes.", + LockMode::LOCK_WHILE_RUNNING, + true + ) +// , NAUGHTY_MODE_OPTION("Naughty Mode:", false) + , HIDE_NOTIF_DISCORD_LINK( + "Hide Discord Link in Notifications:
" + "Many Discord servers have rules forbidding links to other Discord servers. " + "Checking this box will hide the support link that appears in the footer of every Discord notification.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , PERFORMANCE(CONSTRUCT_TOKEN) + , AUDIO_PIPELINE(CONSTRUCT_TOKEN) + , VIDEO_PIPELINE(CONSTRUCT_TOKEN) + , ENABLE_LIFETIME_SANITIZER0( + "Enable Lifetime Sanitizer: (for debugging)
" + "Check for C++ object lifetime violations. Terminate program with stack dump if violations are found. " + "If enabling, you must restart the program for it to take effect.", + LockMode::UNLOCK_WHILE_RUNNING, + true +// IS_BETA_VERSION + ) + , ERROR_REPORTS(CONSTRUCT_TOKEN) + , DEVELOPER_TOKEN( + true, + "Developer Token:
Restart application to take full effect after changing this.", + LockMode::LOCK_WHILE_RUNNING, + "", "" + ) +{ + PA_ADD_OPTION(CHECK_FOR_UPDATES); + PA_ADD_OPTION(STATS_FILE); + PA_ADD_OPTION(TEMP_FOLDER); + PA_ADD_OPTION(THEME); + PA_ADD_OPTION(WINDOW_SIZE); + PA_ADD_OPTION(LOG_WINDOW_SIZE); + PA_ADD_OPTION(LOG_WINDOW_STARTUP); +#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) + if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(STREAM_HISTORY); + } +#else + STREAM_HISTORY->set_enabled(false); +#endif +#ifdef PA_ENABLE_SLEEP_SUPPRESS + PA_ADD_OPTION(SLEEP_SUPPRESS); +#endif + + PA_ADD_STATIC(m_discord_settings); + PA_ADD_OPTION(ALL_STATS); + PA_ADD_OPTION(DISCORD); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(LOG_EVERYTHING); + PA_ADD_OPTION(SAVE_DEBUG_IMAGES); +// PA_ADD_OPTION(NAUGHTY_MODE); + PA_ADD_OPTION(HIDE_NOTIF_DISCORD_LINK); + + PA_ADD_OPTION(PERFORMANCE); + + PA_ADD_OPTION(AUDIO_PIPELINE); + PA_ADD_OPTION(VIDEO_PIPELINE); + + PA_ADD_OPTION(ENABLE_LIFETIME_SANITIZER0); + +#ifdef PA_OFFICIAL + PA_ADD_OPTION(ERROR_REPORTS); +#endif + + PA_ADD_OPTION(DEVELOPER_TOKEN); + + GlobalSettings::on_config_value_changed(this); + ENABLE_LIFETIME_SANITIZER0.add_listener(*this); +} + +void GlobalSettings::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + PreloadSettings::instance().load(json); + + BatchOption::load_json(json); + + // Remake this to update the color. + m_discord_settings.set_text( + "Discord Settings: Integrate with Discord. (" + + make_text_url( + ONLINE_DOC_URL_BASE + "ComputerControl/blob/master/Wiki/Software/DiscordIntegration.md", + "online documentation" + ) + ")" + ); + + COMMAND_LINE_TEST_LIST.clear(); + COMMAND_LINE_IGNORE_LIST.clear(); + const JsonObject* command_line_tests_setting = obj->get_object("COMMAND_LINE_TESTS"); + if (command_line_tests_setting){ + command_line_tests_setting->read_boolean(COMMAND_LINE_TEST_MODE, "RUN"); + + if (!command_line_tests_setting->read_string(COMMAND_LINE_TEST_FOLDER, "FOLDER")){ + COMMAND_LINE_TEST_FOLDER = "CommandLineTests"; + } + + const JsonArray* test_list = command_line_tests_setting->get_array("TEST_LIST"); + if (test_list){ + for (const auto& value: *test_list){ + if (!value.is_string()){ + continue; + } + const std::string* test_name = value.to_string(); + if (test_name != nullptr && !test_name->empty()){ + COMMAND_LINE_TEST_LIST.emplace_back(*test_name); + } + } + } + const JsonArray* ignore_list = command_line_tests_setting->get_array("IGNORE_LIST"); + if (ignore_list){ + for (const auto& value: *ignore_list){ + if (!value.is_string()){ + continue; + } + const std::string* test_name = value.to_string(); + if (test_name != nullptr && !test_name->empty()){ + COMMAND_LINE_IGNORE_LIST.emplace_back(*test_name); + } + } + } + + if (COMMAND_LINE_TEST_MODE){ + std::cout << "Enter command line test mode:" << std::endl; + if (COMMAND_LINE_TEST_LIST.size() > 0){ + std::cout << "Run following tests: " << std::endl; + for(const auto& name : COMMAND_LINE_TEST_LIST){ + std::cout << "- " << name << std::endl; + } + } + if (COMMAND_LINE_IGNORE_LIST.size() > 0){ + std::cout << "Ignore following " << COMMAND_LINE_IGNORE_LIST.size() << " paths: " << std::endl; + const size_t MAX_LINES = 5; + for(size_t i = 0; i < COMMAND_LINE_IGNORE_LIST.size() && i < MAX_LINES; i++){ + std::cout << "- " << COMMAND_LINE_IGNORE_LIST[i] << std::endl; + } + if (COMMAND_LINE_IGNORE_LIST.size() > MAX_LINES){ + std::cout << "..." << std::endl; + } + } + } + } +} + + +JsonValue GlobalSettings::to_json() const{ + JsonObject obj = std::move(*BatchOption::to_json().to_object()); + obj["NAUGHTY_MODE"] = PreloadSettings::instance().NAUGHTY_MODE; + + JsonObject command_line_test_obj; + command_line_test_obj["RUN"] = COMMAND_LINE_TEST_MODE; + command_line_test_obj["FOLDER"] = COMMAND_LINE_TEST_FOLDER; + + { + JsonArray test_list; + for(const auto& name : COMMAND_LINE_TEST_LIST){ + test_list.push_back(name); + } + command_line_test_obj["TEST_LIST"] = std::move(test_list); + } + + { + JsonArray ignore_list; + for(const auto& name : COMMAND_LINE_IGNORE_LIST){ + ignore_list.push_back(name); + } + command_line_test_obj["IGNORE_LIST"] = std::move(ignore_list); + } + + obj["COMMAND_LINE_TESTS"] = std::move(command_line_test_obj); + + JsonObject debug_obj; + const auto& debug_settings = PreloadSettings::instance().DEBUG; + debug_obj["COLOR_CHECK"] = debug_settings.COLOR_CHECK; + debug_obj["IMAGE_TEMPLATE_MATCHING"] = debug_settings.IMAGE_TEMPLATE_MATCHING; + debug_obj["IMAGE_DICTIONARY_MATCHING"] = debug_settings.IMAGE_DICTIONARY_MATCHING; + obj["DEBUG"] = std::move(debug_obj); + + return obj; +} + +void GlobalSettings::on_config_value_changed(void* object){ + bool enabled = ENABLE_LIFETIME_SANITIZER0; + if (enabled){ + global_logger_tagged().log("LifeTime Sanitizer: Enabled", COLOR_BLUE); + }else{ + global_logger_tagged().log("LifeTime Sanitizer: Disabled", COLOR_BLUE); + LifetimeSanitizer::disable(); + } +} + + + + + + +PanelDescriptorWrapper GlobalSettings_Descriptor::INSTANCE; + +GlobalSettings_Descriptor::GlobalSettings_Descriptor() + : PanelDescriptor( + Color(), + "", + "Global Settings", "Global Settings", + "", + "Global Settings" + ) +{} + + +GlobalSettingsPanel::GlobalSettingsPanel(const GlobalSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GlobalSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h index fcec0f2a9d..6284f7b390 100644 --- a/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h +++ b/SerialPrograms/Source/CommonFramework/GlobalSettingsPanel.h @@ -1,165 +1,165 @@ -/* Global Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_GlobalSettingsPanel_H -#define PokemonAutomation_GlobalSettingsPanel_H - -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -//#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" -#include "CommonFramework/Panels/PanelTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -class CheckForUpdatesOption; -class ThemeSelectorOption; -class ResolutionOption; -class StreamHistoryOption; -class SleepSuppressOptions; -namespace Integration{ - class DiscordSettingsOption; -} -class PerformanceOptions; -class AudioPipelineOptions; -class VideoPipelineOptions; -class ErrorReportOption; - - - - -class FolderInputOption : public StringOption{ -public: - using StringOption::StringOption; - - virtual void sanitize(std::string& str) override{ - if (!str.empty() && str.back() != '/'){ - str += '/'; - } - } -}; - - -struct DebugSettings{ - bool COLOR_CHECK = false; - bool IMAGE_TEMPLATE_MATCHING = false; - bool IMAGE_DICTIONARY_MATCHING = false; -}; - - - -class PreloadSettings{ - PreloadSettings(); -public: - static PreloadSettings& instance(); - static DebugSettings& debug(); - - void load(const JsonValue& json); - - bool NAUGHTY_MODE = false; - bool DEVELOPER_MODE = false; - - DebugSettings DEBUG; -}; - - - - -class GlobalSettings : public BatchOption, private ConfigOption::Listener{ - ~GlobalSettings(); - GlobalSettings(); -public: - static GlobalSettings& instance(); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -private: - virtual void on_config_value_changed(void* object) override; - -public: - Pimpl CHECK_FOR_UPDATES; - - StringOption STATS_FILE; - FolderInputOption TEMP_FOLDER; - - Pimpl THEME; - Pimpl WINDOW_SIZE; - Pimpl LOG_WINDOW_SIZE; - BooleanCheckBoxOption LOG_WINDOW_STARTUP; - - Pimpl STREAM_HISTORY; - Pimpl SLEEP_SUPPRESS; - - SectionDividerOption m_discord_settings; - BooleanCheckBoxOption ALL_STATS; - Pimpl DISCORD; - - SectionDividerOption m_advanced_options; - - BooleanCheckBoxOption LOG_EVERYTHING; - BooleanCheckBoxOption SAVE_DEBUG_IMAGES; -// BooleanCheckBoxOption NAUGHTY_MODE_OPTION; - BooleanCheckBoxOption HIDE_NOTIF_DISCORD_LINK; - - Pimpl PERFORMANCE; - Pimpl AUDIO_PIPELINE; - Pimpl VIDEO_PIPELINE; - - BooleanCheckBoxOption ENABLE_LIFETIME_SANITIZER0; - - Pimpl ERROR_REPORTS; - - StringOption DEVELOPER_TOKEN; - - // The mode that does not run Qt GUI, but instead runs some tests for - // debugging, unit testing and developing purposes. - bool COMMAND_LINE_TEST_MODE = false; - // The path to the command line test folder. - std::string COMMAND_LINE_TEST_FOLDER; - // Which tests to run if in the command line test mode. - std::vector COMMAND_LINE_TEST_LIST; - // Which tests to ignore running under the command line test mode. - // If a test path appears in both COMMAND_LINE_TEST_LIST and COMMAND_LINE_IGNORE_LIST, it's still ignored. - std::vector COMMAND_LINE_IGNORE_LIST; -}; - - - - - -class GlobalSettingsPanel; - -class GlobalSettings_Descriptor : public PanelDescriptor{ -public: - GlobalSettings_Descriptor(); -public: - static PanelDescriptorWrapper INSTANCE; -}; - - -class GlobalSettingsPanel : public SettingsPanelInstance{ -public: - GlobalSettingsPanel(const GlobalSettings_Descriptor& descriptor); -private: - GlobalSettings& settings; -}; - - - - - - -} -#endif +/* Global Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_GlobalSettingsPanel_H +#define PokemonAutomation_GlobalSettingsPanel_H + +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +//#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" +#include "CommonFramework/Panels/PanelTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +class CheckForUpdatesOption; +class ThemeSelectorOption; +class ResolutionOption; +class StreamHistoryOption; +class SleepSuppressOptions; +namespace Integration{ + class DiscordSettingsOption; +} +class PerformanceOptions; +class AudioPipelineOptions; +class VideoPipelineOptions; +class ErrorReportOption; + + + + +class FolderInputOption : public StringOption{ +public: + using StringOption::StringOption; + + virtual void sanitize(std::string& str) override{ + if (!str.empty() && str.back() != '/'){ + str += '/'; + } + } +}; + + +struct DebugSettings{ + bool COLOR_CHECK = false; + bool IMAGE_TEMPLATE_MATCHING = false; + bool IMAGE_DICTIONARY_MATCHING = false; +}; + + + +class PreloadSettings{ + PreloadSettings(); +public: + static PreloadSettings& instance(); + static DebugSettings& debug(); + + void load(const JsonValue& json); + + bool NAUGHTY_MODE = false; + bool DEVELOPER_MODE = false; + + DebugSettings DEBUG; +}; + + + + +class GlobalSettings : public BatchOption, private ConfigOption::Listener{ + ~GlobalSettings(); + GlobalSettings(); +public: + static GlobalSettings& instance(); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +private: + virtual void on_config_value_changed(void* object) override; + +public: + Pimpl CHECK_FOR_UPDATES; + + StringOption STATS_FILE; + FolderInputOption TEMP_FOLDER; + + Pimpl THEME; + Pimpl WINDOW_SIZE; + Pimpl LOG_WINDOW_SIZE; + BooleanCheckBoxOption LOG_WINDOW_STARTUP; + + Pimpl STREAM_HISTORY; + Pimpl SLEEP_SUPPRESS; + + SectionDividerOption m_discord_settings; + BooleanCheckBoxOption ALL_STATS; + Pimpl DISCORD; + + SectionDividerOption m_advanced_options; + + BooleanCheckBoxOption LOG_EVERYTHING; + BooleanCheckBoxOption SAVE_DEBUG_IMAGES; +// BooleanCheckBoxOption NAUGHTY_MODE_OPTION; + BooleanCheckBoxOption HIDE_NOTIF_DISCORD_LINK; + + Pimpl PERFORMANCE; + Pimpl AUDIO_PIPELINE; + Pimpl VIDEO_PIPELINE; + + BooleanCheckBoxOption ENABLE_LIFETIME_SANITIZER0; + + Pimpl ERROR_REPORTS; + + StringOption DEVELOPER_TOKEN; + + // The mode that does not run Qt GUI, but instead runs some tests for + // debugging, unit testing and developing purposes. + bool COMMAND_LINE_TEST_MODE = false; + // The path to the command line test folder. + std::string COMMAND_LINE_TEST_FOLDER; + // Which tests to run if in the command line test mode. + std::vector COMMAND_LINE_TEST_LIST; + // Which tests to ignore running under the command line test mode. + // If a test path appears in both COMMAND_LINE_TEST_LIST and COMMAND_LINE_IGNORE_LIST, it's still ignored. + std::vector COMMAND_LINE_IGNORE_LIST; +}; + + + + + +class GlobalSettingsPanel; + +class GlobalSettings_Descriptor : public PanelDescriptor{ +public: + GlobalSettings_Descriptor(); +public: + static PanelDescriptorWrapper INSTANCE; +}; + + +class GlobalSettingsPanel : public SettingsPanelInstance{ +public: + GlobalSettingsPanel(const GlobalSettings_Descriptor& descriptor); +private: + GlobalSettings& settings; +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Globals.cpp b/SerialPrograms/Source/CommonFramework/Globals.cpp index 529d93ba2f..ecff404fb1 100644 --- a/SerialPrograms/Source/CommonFramework/Globals.cpp +++ b/SerialPrograms/Source/CommonFramework/Globals.cpp @@ -1,209 +1,209 @@ -/* Globals - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Globals.h" - -namespace PokemonAutomation{ - - -// -// ATTENTION!!! -// -// If you are building from source, do not change any of these version numbers -// or tags. When filing reports or asking for support, we (the developers) need -// to know exactly what you are running. Changing these values can lead to -// misleading version information. -// - -const bool IS_BETA_VERSION = true; -const int PROGRAM_VERSION_MAJOR = 0; -const int PROGRAM_VERSION_MINOR = 54; -const int PROGRAM_VERSION_PATCH = 9; - -const std::string PROGRAM_VERSION_BASE = - "v" + std::to_string(PROGRAM_VERSION_MAJOR) + - "." + std::to_string(PROGRAM_VERSION_MINOR) + - "." + std::to_string(PROGRAM_VERSION_PATCH); - -#ifdef PA_OFFICIAL -const std::string PROGRAM_VERSION = IS_BETA_VERSION - ? PROGRAM_VERSION_BASE + "-beta" - : PROGRAM_VERSION_BASE; -#else -const std::string PROGRAM_VERSION = PROGRAM_VERSION_BASE + "-user"; -#endif - - - -const std::string PROGRAM_NAME = "Pok\u00e9mon Automation"; - -const std::string ONLINE_DOC_URL_BASE = "https://github.com/PokemonAutomation/"; -const std::string PROJECT_SOURCE_URL = "https://github.com/PokemonAutomation/Arduino-Source/"; -const std::string RESOURCES_URL_BASE = "https://github.com/PokemonAutomation/Packages/"; - - - -// This the URL that we display. We don't actually use this for linking. -const std::string GITHUB_LINK_TEXT = "github.com/PokemonAutomation"; - -// This is the URL that we actually link to. -const std::string GITHUB_LINK_URL = "https://github.com/PokemonAutomation/About/blob/master/README.md"; - - - -// URL to display. (the vanity link) -// We don't actually use this URL for linking since the vanity link will go -// away if we lose too many nitro boosts. -const std::string DISCORD_LINK_TEXT = "discord.gg/PokemonAutomation"; - -// URL to use inside the program. -const std::string DISCORD_LINK_URL_PROGRAM = "https://discord.gg/BSjDp27"; - -// URL to use in the Discord notifications/embeds. -const std::string DISCORD_LINK_URL_EMBED = "https://discord.gg/xMJcveK"; - - - -#if 0 -#elif __INTEL_LLVM_COMPILER -const std::string COMPILER_VERSION = "ICX " + std::to_string(__VERSION__); -#elif __INTEL_COMPILER -const std::string COMPILER_VERSION = "ICC " + std::to_string(__INTEL_COMPILER) + "." + std::to_string(__INTEL_COMPILER_UPDATE); -#elif _MSC_VER -const std::string COMPILER_VERSION = "MSVC " + std::to_string(_MSC_FULL_VER); -#elif __clang__ -const std::string COMPILER_VERSION = "Clang " + std::string(__clang_version__); -#elif __GNUC__ -const std::string COMPILER_VERSION = "GCC " + std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__); -#else -const std::string COMPILER_VERSION = "Unknown Compiler"; -#endif - - - -const size_t LOG_HISTORY_LINES = 10000; - - -namespace{ - -QString get_application_base_dir_path(){ - QString application_dir_path = qApp->applicationDirPath(); - if (application_dir_path.endsWith(".app/Contents/MacOS")){ - // a macOS bundle. Change working directory to the folder that hosts the .app folder. - QString app_bundle_path = application_dir_path.chopped(15); - QString base_folder_path = QFileInfo(app_bundle_path).dir().absolutePath(); - return base_folder_path; - } - return application_dir_path; -} -std::string get_resource_path(){ - // Find the resource directory. - QString path = get_application_base_dir_path(); - for (size_t c = 0; c < 5; c++){ - QString try_path = path + "/Resources/"; - QFile file(try_path); - if (file.exists()){ - return try_path.toStdString(); - } - path += "/.."; - } - return (QCoreApplication::applicationDirPath() + "/../Resources/").toStdString(); -} -std::string get_training_path(){ - // Find the training data directory. - QString path = get_application_base_dir_path(); - for (size_t c = 0; c < 5; c++){ - QString try_path = path + "/TrainingData/"; - QFile file(try_path); - if (file.exists()){ - return try_path.toStdString(); - } - path += "/.."; - } - return (QCoreApplication::applicationDirPath() + "/../TrainingData/").toStdString(); -} - -std::string get_runtime_base_path(){ - // On MacOS, find the writable application support directory - if (QSysInfo::productType() == "macos" || QSysInfo::productType() == "osx"){ - QString appSupportPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); - QDir dir(appSupportPath); - if (!dir.exists()) { - dir.mkpath("."); - } - return appSupportPath.toStdString() + "/"; - } - return "./"; -} - -const std::string& RUNTIME_BASE_PATH(){ - static std::string path = get_runtime_base_path(); - return path; -} - -std::string get_setting_path(){ - return RUNTIME_BASE_PATH() + "UserSettings/"; -} -std::string get_screenshot_path(){ - return RUNTIME_BASE_PATH() + "Screenshots/"; -} -std::string get_debug_path(){ - return RUNTIME_BASE_PATH() + "DebugDumps/"; -} -std::string get_error_path(){ - return RUNTIME_BASE_PATH() + "ErrorDumps/"; -} -std::string get_user_file_path(){ - return RUNTIME_BASE_PATH(); -} - -} // anonymous namespace - -const std::string& SETTINGS_PATH(){ - static std::string path = get_setting_path(); - return path; -} -const std::string& PROGRAM_SETTING_JSON_PATH(){ - static std::string path = SETTINGS_PATH() + QCoreApplication::applicationName().toStdString() + "-Settings.json"; - return path; -} -const std::string& SCREENSHOTS_PATH(){ - static std::string path = get_screenshot_path(); - return path; -} -const std::string& DEBUG_PATH(){ - static std::string path = get_debug_path(); - return path; -} -const std::string& ERROR_PATH(){ - static std::string path = get_error_path(); - return path; -} -const std::string& USER_FILE_PATH(){ - static std::string path = get_user_file_path(); - return path; -} -const std::string& RESOURCE_PATH(){ - static std::string path = get_resource_path(); - return path; -} -const std::string& TRAINING_PATH(){ - static std::string path = get_training_path(); - return path; -} - -const std::string& ML_ANNOTATION_PATH(){ - static const std::string path = RUNTIME_BASE_PATH() + "DataAnnotation/"; - return path; -} - -} - +/* Globals + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Globals.h" + +namespace PokemonAutomation{ + + +// +// ATTENTION!!! +// +// If you are building from source, do not change any of these version numbers +// or tags. When filing reports or asking for support, we (the developers) need +// to know exactly what you are running. Changing these values can lead to +// misleading version information. +// + +const bool IS_BETA_VERSION = true; +const int PROGRAM_VERSION_MAJOR = 0; +const int PROGRAM_VERSION_MINOR = 54; +const int PROGRAM_VERSION_PATCH = 9; + +const std::string PROGRAM_VERSION_BASE = + "v" + std::to_string(PROGRAM_VERSION_MAJOR) + + "." + std::to_string(PROGRAM_VERSION_MINOR) + + "." + std::to_string(PROGRAM_VERSION_PATCH); + +#ifdef PA_OFFICIAL +const std::string PROGRAM_VERSION = IS_BETA_VERSION + ? PROGRAM_VERSION_BASE + "-beta" + : PROGRAM_VERSION_BASE; +#else +const std::string PROGRAM_VERSION = PROGRAM_VERSION_BASE + "-user"; +#endif + + + +const std::string PROGRAM_NAME = "Pok\u00e9mon Automation"; + +const std::string ONLINE_DOC_URL_BASE = "https://github.com/PokemonAutomation/"; +const std::string PROJECT_SOURCE_URL = "https://github.com/PokemonAutomation/Arduino-Source/"; +const std::string RESOURCES_URL_BASE = "https://github.com/PokemonAutomation/Packages/"; + + + +// This the URL that we display. We don't actually use this for linking. +const std::string GITHUB_LINK_TEXT = "github.com/PokemonAutomation"; + +// This is the URL that we actually link to. +const std::string GITHUB_LINK_URL = "https://github.com/PokemonAutomation/About/blob/master/README.md"; + + + +// URL to display. (the vanity link) +// We don't actually use this URL for linking since the vanity link will go +// away if we lose too many nitro boosts. +const std::string DISCORD_LINK_TEXT = "discord.gg/PokemonAutomation"; + +// URL to use inside the program. +const std::string DISCORD_LINK_URL_PROGRAM = "https://discord.gg/BSjDp27"; + +// URL to use in the Discord notifications/embeds. +const std::string DISCORD_LINK_URL_EMBED = "https://discord.gg/xMJcveK"; + + + +#if 0 +#elif __INTEL_LLVM_COMPILER +const std::string COMPILER_VERSION = "ICX " + std::to_string(__VERSION__); +#elif __INTEL_COMPILER +const std::string COMPILER_VERSION = "ICC " + std::to_string(__INTEL_COMPILER) + "." + std::to_string(__INTEL_COMPILER_UPDATE); +#elif _MSC_VER +const std::string COMPILER_VERSION = "MSVC " + std::to_string(_MSC_FULL_VER); +#elif __clang__ +const std::string COMPILER_VERSION = "Clang " + std::string(__clang_version__); +#elif __GNUC__ +const std::string COMPILER_VERSION = "GCC " + std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__); +#else +const std::string COMPILER_VERSION = "Unknown Compiler"; +#endif + + + +const size_t LOG_HISTORY_LINES = 10000; + + +namespace{ + +QString get_application_base_dir_path(){ + QString application_dir_path = qApp->applicationDirPath(); + if (application_dir_path.endsWith(".app/Contents/MacOS")){ + // a macOS bundle. Change working directory to the folder that hosts the .app folder. + QString app_bundle_path = application_dir_path.chopped(15); + QString base_folder_path = QFileInfo(app_bundle_path).dir().absolutePath(); + return base_folder_path; + } + return application_dir_path; +} +std::string get_resource_path(){ + // Find the resource directory. + QString path = get_application_base_dir_path(); + for (size_t c = 0; c < 5; c++){ + QString try_path = path + "/Resources/"; + QFile file(try_path); + if (file.exists()){ + return try_path.toStdString(); + } + path += "/.."; + } + return (QCoreApplication::applicationDirPath() + "/../Resources/").toStdString(); +} +std::string get_training_path(){ + // Find the training data directory. + QString path = get_application_base_dir_path(); + for (size_t c = 0; c < 5; c++){ + QString try_path = path + "/TrainingData/"; + QFile file(try_path); + if (file.exists()){ + return try_path.toStdString(); + } + path += "/.."; + } + return (QCoreApplication::applicationDirPath() + "/../TrainingData/").toStdString(); +} + +std::string get_runtime_base_path(){ + // On MacOS, find the writable application support directory + if (QSysInfo::productType() == "macos" || QSysInfo::productType() == "osx"){ + QString appSupportPath = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); + QDir dir(appSupportPath); + if (!dir.exists()) { + dir.mkpath("."); + } + return appSupportPath.toStdString() + "/"; + } + return "./"; +} + +const std::string& RUNTIME_BASE_PATH(){ + static std::string path = get_runtime_base_path(); + return path; +} + +std::string get_setting_path(){ + return RUNTIME_BASE_PATH() + "UserSettings/"; +} +std::string get_screenshot_path(){ + return RUNTIME_BASE_PATH() + "Screenshots/"; +} +std::string get_debug_path(){ + return RUNTIME_BASE_PATH() + "DebugDumps/"; +} +std::string get_error_path(){ + return RUNTIME_BASE_PATH() + "ErrorDumps/"; +} +std::string get_user_file_path(){ + return RUNTIME_BASE_PATH(); +} + +} // anonymous namespace + +const std::string& SETTINGS_PATH(){ + static std::string path = get_setting_path(); + return path; +} +const std::string& PROGRAM_SETTING_JSON_PATH(){ + static std::string path = SETTINGS_PATH() + QCoreApplication::applicationName().toStdString() + "-Settings.json"; + return path; +} +const std::string& SCREENSHOTS_PATH(){ + static std::string path = get_screenshot_path(); + return path; +} +const std::string& DEBUG_PATH(){ + static std::string path = get_debug_path(); + return path; +} +const std::string& ERROR_PATH(){ + static std::string path = get_error_path(); + return path; +} +const std::string& USER_FILE_PATH(){ + static std::string path = get_user_file_path(); + return path; +} +const std::string& RESOURCE_PATH(){ + static std::string path = get_resource_path(); + return path; +} +const std::string& TRAINING_PATH(){ + static std::string path = get_training_path(); + return path; +} + +const std::string& ML_ANNOTATION_PATH(){ + static const std::string path = RUNTIME_BASE_PATH() + "DataAnnotation/"; + return path; +} + +} + diff --git a/SerialPrograms/Source/CommonFramework/Globals.h b/SerialPrograms/Source/CommonFramework/Globals.h index cc4afd1845..b09983715d 100644 --- a/SerialPrograms/Source/CommonFramework/Globals.h +++ b/SerialPrograms/Source/CommonFramework/Globals.h @@ -1,84 +1,84 @@ -/* Globals - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Globals_H -#define PokemonAutomation_Globals_H - -#include - -namespace PokemonAutomation{ - -extern const bool IS_BETA_VERSION; - -extern const int PROGRAM_VERSION_MAJOR; -extern const int PROGRAM_VERSION_MINOR; -extern const int PROGRAM_VERSION_PATCH; -extern const std::string PROGRAM_VERSION_BASE; -extern const std::string PROGRAM_VERSION; - -extern const std::string PROGRAM_NAME; - -extern const std::string ONLINE_DOC_URL_BASE; -extern const std::string PROJECT_SOURCE_URL; -extern const std::string RESOURCES_URL_BASE; - -extern const std::string GITHUB_LINK_TEXT; -extern const std::string GITHUB_LINK_URL; - -extern const std::string DISCORD_LINK_TEXT; -extern const std::string DISCORD_LINK_URL_PROGRAM; -extern const std::string DISCORD_LINK_URL_EMBED; - -extern const std::string COMPILER_VERSION; - -extern const size_t LOG_HISTORY_LINES; - -// Folder path (end with "/") to hold program setting files. -const std::string& SETTINGS_PATH(); -// The setting JSON file path. This path is a child of the folder SETTINGS_PATH(). -const std::string& PROGRAM_SETTING_JSON_PATH(); - -// Folder path (end with "/") to hold screenshots from the program "Screenshot" button. -const std::string& SCREENSHOTS_PATH(); - -// Folder path (end with "/") to hold debugging images and other debugging files -const std::string& DEBUG_PATH(); - -// Folder path (end with "/") to hold error images and other related files here. Useful for debugging the errors. -const std::string& ERROR_PATH(); - -// Folder path (end with "/") that holds various user genereated files. -// e.g. for a program that records and dumps screenshots, the saved images can go to USER_FILE_PATH()/ScreenshotDumper. -const std::string& USER_FILE_PATH(); - -// Resource folder path. Resources include JSON files, images, sound files and others required by -// various automation programs. -const std::string& RESOURCE_PATH(); -// Hold ML training data. -const std::string& TRAINING_PATH(); - -// Folder path (end with "/") to hold data annotation for ML labeling programs -const std::string& ML_ANNOTATION_PATH(); - - -enum class ProgramState{ - NOT_READY, - STOPPED, - RUNNING, - STOPPING, -}; - -enum class FeedbackType{ - NONE, - OPTIONAL_, // Naming conflict with macro. - REQUIRED, - VIDEO_AUDIO, -}; - - - -} -#endif +/* Globals + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Globals_H +#define PokemonAutomation_Globals_H + +#include + +namespace PokemonAutomation{ + +extern const bool IS_BETA_VERSION; + +extern const int PROGRAM_VERSION_MAJOR; +extern const int PROGRAM_VERSION_MINOR; +extern const int PROGRAM_VERSION_PATCH; +extern const std::string PROGRAM_VERSION_BASE; +extern const std::string PROGRAM_VERSION; + +extern const std::string PROGRAM_NAME; + +extern const std::string ONLINE_DOC_URL_BASE; +extern const std::string PROJECT_SOURCE_URL; +extern const std::string RESOURCES_URL_BASE; + +extern const std::string GITHUB_LINK_TEXT; +extern const std::string GITHUB_LINK_URL; + +extern const std::string DISCORD_LINK_TEXT; +extern const std::string DISCORD_LINK_URL_PROGRAM; +extern const std::string DISCORD_LINK_URL_EMBED; + +extern const std::string COMPILER_VERSION; + +extern const size_t LOG_HISTORY_LINES; + +// Folder path (end with "/") to hold program setting files. +const std::string& SETTINGS_PATH(); +// The setting JSON file path. This path is a child of the folder SETTINGS_PATH(). +const std::string& PROGRAM_SETTING_JSON_PATH(); + +// Folder path (end with "/") to hold screenshots from the program "Screenshot" button. +const std::string& SCREENSHOTS_PATH(); + +// Folder path (end with "/") to hold debugging images and other debugging files +const std::string& DEBUG_PATH(); + +// Folder path (end with "/") to hold error images and other related files here. Useful for debugging the errors. +const std::string& ERROR_PATH(); + +// Folder path (end with "/") that holds various user genereated files. +// e.g. for a program that records and dumps screenshots, the saved images can go to USER_FILE_PATH()/ScreenshotDumper. +const std::string& USER_FILE_PATH(); + +// Resource folder path. Resources include JSON files, images, sound files and others required by +// various automation programs. +const std::string& RESOURCE_PATH(); +// Hold ML training data. +const std::string& TRAINING_PATH(); + +// Folder path (end with "/") to hold data annotation for ML labeling programs +const std::string& ML_ANNOTATION_PATH(); + + +enum class ProgramState{ + NOT_READY, + STOPPED, + RUNNING, + STOPPING, +}; + +enum class FeedbackType{ + NONE, + OPTIONAL_, // Naming conflict with macro. + REQUIRED, + VIDEO_AUDIO, +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.cpp b/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.cpp index 67dd042c60..751b1b8039 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.cpp @@ -1,38 +1,38 @@ -/* Float Pixel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "FloatPixel.h" - -namespace PokemonAutomation{ - - -std::string FloatPixel::to_string() const{ - return "{" + std::to_string(r) + ", " + std::to_string(g) + ", " + std::to_string(b) + "}"; -} -double FloatPixel::stddev() const{ - double mean = (r + g + b) / 3; - double rd = (r - mean); - double gd = (g - mean); - double bd = (b - mean); - return std::sqrt((rd*rd + gd*gd + bd*bd) / 2); -} - -FloatPixel abs(const FloatPixel& x){ - return FloatPixel{ - x.r < 0 ? -x.r : x.r, - x.g < 0 ? -x.g : x.g, - x.b < 0 ? -x.b : x.b, - }; -} -double euclidean_distance(const FloatPixel& x, const FloatPixel& y){ - FloatPixel p = x - y; - p *= p; - return std::sqrt(p.r + p.g + p.b); -} - - -} +/* Float Pixel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "FloatPixel.h" + +namespace PokemonAutomation{ + + +std::string FloatPixel::to_string() const{ + return "{" + std::to_string(r) + ", " + std::to_string(g) + ", " + std::to_string(b) + "}"; +} +double FloatPixel::stddev() const{ + double mean = (r + g + b) / 3; + double rd = (r - mean); + double gd = (g - mean); + double bd = (b - mean); + return std::sqrt((rd*rd + gd*gd + bd*bd) / 2); +} + +FloatPixel abs(const FloatPixel& x){ + return FloatPixel{ + x.r < 0 ? -x.r : x.r, + x.g < 0 ? -x.g : x.g, + x.b < 0 ? -x.b : x.b, + }; +} +double euclidean_distance(const FloatPixel& x, const FloatPixel& y){ + FloatPixel p = x - y; + p *= p; + return std::sqrt(p.r + p.g + p.b); +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.h b/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.h index 599ee6abed..a8513911d2 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.h +++ b/SerialPrograms/Source/CommonFramework/ImageTools/FloatPixel.h @@ -1,118 +1,118 @@ -/* Float Pixel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_FloatPixel_H -#define PokemonAutomation_CommonFramework_FloatPixel_H - -#include -#include -#include "Common/Cpp/Color.h" - -namespace PokemonAutomation{ - - -struct FloatPixel{ - double r; - double g; - double b; - - FloatPixel() : r(0), g(0), b(0) {} - FloatPixel(double red, double green, double blue) - : r(red), g(green), b(blue) - {} - FloatPixel(uint32_t pixel) - : FloatPixel(Color(pixel)) - {} - FloatPixel(Color pixel) - : r(pixel.red()), g(pixel.green()), b(pixel.blue()) - {} - - Color round() const{ - return Color((uint8_t)(r + 0.5), (uint8_t)(g + 0.5), (uint8_t)(b + 0.5)); - } - void bound(double low, double high){ - r = std::max(r, low); - g = std::max(g, low); - b = std::max(b, low); - r = std::min(r, high); - g = std::min(g, high); - b = std::min(b, high); - } - - double sum() const{ return r + g + b; } - std::string to_string() const; - double stddev() const; -}; - -inline std::ostream& operator<<(std::ostream& stream, const FloatPixel& pixel){ - stream << "{" << pixel.r << ", " << pixel.g << ", " << pixel.b << "}"; - return stream; -} - - -inline void operator+=(FloatPixel& x, const FloatPixel& y){ - x.r += y.r; - x.g += y.g; - x.b += y.b; -} -inline void operator-=(FloatPixel& x, const FloatPixel& y){ - x.r -= y.r; - x.g -= y.g; - x.b -= y.b; -} -inline void operator*=(FloatPixel& x, const FloatPixel& y){ - x.r *= y.r; - x.g *= y.g; - x.b *= y.b; -} -inline void operator/=(FloatPixel& x, double y){ - x.r /= y; - x.g /= y; - x.b /= y; -} -inline FloatPixel operator+(const FloatPixel& x, const FloatPixel& y){ - return FloatPixel{ - x.r + y.r, - x.g + y.g, - x.b + y.b, - }; -} -inline FloatPixel operator-(const FloatPixel& x, const FloatPixel& y){ - return FloatPixel{ - x.r - y.r, - x.g - y.g, - x.b - y.b, - }; -} -inline FloatPixel operator*(const FloatPixel& x, const FloatPixel& y){ - return FloatPixel{ - x.r * y.r, - x.g * y.g, - x.b * y.b, - }; -} -inline FloatPixel operator/(const FloatPixel& x, double y){ - return FloatPixel{ - x.r / y, - x.g / y, - x.b / y, - }; -} -inline FloatPixel operator/(const FloatPixel& x, const FloatPixel& y){ - return FloatPixel{ - x.r / y.r, - x.g / y.g, - x.b / y.b, - }; -} - -FloatPixel abs(const FloatPixel& x); -double euclidean_distance(const FloatPixel& x, const FloatPixel& y); - - -} - -#endif +/* Float Pixel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_FloatPixel_H +#define PokemonAutomation_CommonFramework_FloatPixel_H + +#include +#include +#include "Common/Cpp/Color.h" + +namespace PokemonAutomation{ + + +struct FloatPixel{ + double r; + double g; + double b; + + FloatPixel() : r(0), g(0), b(0) {} + FloatPixel(double red, double green, double blue) + : r(red), g(green), b(blue) + {} + FloatPixel(uint32_t pixel) + : FloatPixel(Color(pixel)) + {} + FloatPixel(Color pixel) + : r(pixel.red()), g(pixel.green()), b(pixel.blue()) + {} + + Color round() const{ + return Color((uint8_t)(r + 0.5), (uint8_t)(g + 0.5), (uint8_t)(b + 0.5)); + } + void bound(double low, double high){ + r = std::max(r, low); + g = std::max(g, low); + b = std::max(b, low); + r = std::min(r, high); + g = std::min(g, high); + b = std::min(b, high); + } + + double sum() const{ return r + g + b; } + std::string to_string() const; + double stddev() const; +}; + +inline std::ostream& operator<<(std::ostream& stream, const FloatPixel& pixel){ + stream << "{" << pixel.r << ", " << pixel.g << ", " << pixel.b << "}"; + return stream; +} + + +inline void operator+=(FloatPixel& x, const FloatPixel& y){ + x.r += y.r; + x.g += y.g; + x.b += y.b; +} +inline void operator-=(FloatPixel& x, const FloatPixel& y){ + x.r -= y.r; + x.g -= y.g; + x.b -= y.b; +} +inline void operator*=(FloatPixel& x, const FloatPixel& y){ + x.r *= y.r; + x.g *= y.g; + x.b *= y.b; +} +inline void operator/=(FloatPixel& x, double y){ + x.r /= y; + x.g /= y; + x.b /= y; +} +inline FloatPixel operator+(const FloatPixel& x, const FloatPixel& y){ + return FloatPixel{ + x.r + y.r, + x.g + y.g, + x.b + y.b, + }; +} +inline FloatPixel operator-(const FloatPixel& x, const FloatPixel& y){ + return FloatPixel{ + x.r - y.r, + x.g - y.g, + x.b - y.b, + }; +} +inline FloatPixel operator*(const FloatPixel& x, const FloatPixel& y){ + return FloatPixel{ + x.r * y.r, + x.g * y.g, + x.b * y.b, + }; +} +inline FloatPixel operator/(const FloatPixel& x, double y){ + return FloatPixel{ + x.r / y, + x.g / y, + x.b / y, + }; +} +inline FloatPixel operator/(const FloatPixel& x, const FloatPixel& y){ + return FloatPixel{ + x.r / y.r, + x.g / y.g, + x.b / y.b, + }; +} + +FloatPixel abs(const FloatPixel& x); +double euclidean_distance(const FloatPixel& x, const FloatPixel& y); + + +} + +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.cpp b/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.cpp index b1dca98675..74a459ef04 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.cpp @@ -1,272 +1,272 @@ -/* Image Boxes - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Rectangle.tpp" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTypes/ImageViewHSV32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageBoxes.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -template struct Rectangle; - - -ImagePixelBox::ImagePixelBox(size_t p_min_x, size_t p_min_y, size_t p_max_x, size_t p_max_y) - : Rectangle(p_min_x, p_min_y, p_max_x, p_max_y) -{ - const size_t MAX_VALUE = 0xffffffff; - - // Check for potential negative values being passed here. - if (min_x > MAX_VALUE){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: min_x = " + std::to_string(min_x) - ); - } - if (min_y > MAX_VALUE){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: min_y = " + std::to_string(min_y) - ); - } - if (max_x > MAX_VALUE){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: max_x = " + std::to_string(max_x) - ); - } - if (max_y > MAX_VALUE){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: max_y = " + std::to_string(max_y) - ); - } -} - - -ImagePixelBox::ImagePixelBox(const Kernels::Waterfill::WaterfillObject& object) - : ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) -{} - - -void ImagePixelBox::clip(size_t image_width, size_t image_height){ - min_x = std::max((size_t)0, min_x); - min_y = std::max((size_t)0, min_y); - max_x = std::min(max_x, image_width); - max_y = std::min(max_y, image_height); -} -void ImagePixelBox::clip(const ImagePixelBox& box){ - min_x = std::max(min_x, box.min_x); - min_y = std::max(min_y, box.min_y); - max_x = std::min(max_x, box.max_x); - max_y = std::min(max_y, box.max_y); -} - -ImagePixelBox ImagePixelBox::expand_as(size_t per_side_increase) const{ - size_t new_min_x = min_x >= per_side_increase ? min_x - per_side_increase : 0; - size_t new_min_y = min_y >= per_side_increase ? min_y - per_side_increase : 0; - return ImagePixelBox(new_min_x, new_min_y, max_x + per_side_increase, max_y + per_side_increase); -} - -size_t ImagePixelBox::distance_x(const ImagePixelBox& box) const{ - size_t min_x = std::max(this->min_x, box.min_x); - size_t max_x = std::min(this->max_x, box.max_x); - if (min_x >= max_x){ - return min_x - max_x; - } - return 0; -} - -size_t ImagePixelBox::distance_y(const ImagePixelBox& box) const{ - size_t min_y = std::max(this->min_y, box.min_y); - size_t max_y = std::min(this->max_y, box.max_y); - if (min_y >= max_y){ - return min_y - max_y; - } - return 0; -} - - -ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImagePixelBox& box){ - return image.sub_image(box.min_x, box.min_y, box.width(), box.height()); -} -ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box){ - size_t min_x = (size_t)(image.width() * box.x + 0.5); - size_t min_y = (size_t)(image.height() * box.y + 0.5); - size_t width = (size_t)(image.width() * box.width + 0.5); - size_t height = (size_t)(image.height() * box.height + 0.5); - return image.sub_image(min_x, min_y, width, height); -} -ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y){ - ptrdiff_t min_x = (ptrdiff_t)(image.width() * box.x + 0.5) + offset_x; - ptrdiff_t min_y = (ptrdiff_t)(image.height() * box.y + 0.5) + offset_y; - ptrdiff_t width = (ptrdiff_t)(image.width() * box.width + 0.5); - ptrdiff_t height = (ptrdiff_t)(image.height() * box.height + 0.5); - - if (min_x < 0){ - width += min_x; - min_x = 0; - width = std::max(width, 0); - } - if (min_y < 0){ - height += min_y; - min_y = 0; - height = std::max(height, 0); - } - - return image.sub_image(min_x, min_y, width, height); -} - - -ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImagePixelBox& box){ - return image.sub_image(box.min_x, box.min_y, box.width(), box.height()); -} -ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box){ - size_t min_x = (size_t)(image.width() * box.x + 0.5); - size_t min_y = (size_t)(image.height() * box.y + 0.5); - size_t width = (size_t)(image.width() * box.width + 0.5); - size_t height = (size_t)(image.height() * box.height + 0.5); - return image.sub_image(min_x, min_y, width, height); -} -ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y){ - ptrdiff_t min_x = (ptrdiff_t)(image.width() * box.x + 0.5) + offset_x; - ptrdiff_t min_y = (ptrdiff_t)(image.height() * box.y + 0.5) + offset_y; - ptrdiff_t width = (ptrdiff_t)(image.width() * box.width + 0.5); - ptrdiff_t height = (ptrdiff_t)(image.height() * box.height + 0.5); - - if (min_x < 0){ - width += min_x; - min_x = 0; - width = std::max(width, 0); - } - if (min_y < 0){ - height += min_y; - min_y = 0; - height = std::max(height, 0); - } - - return image.sub_image(min_x, min_y, width, height); -} - - - -ImageFloatBox translate_to_parent( - const ImageViewRGB32& original_image, - const ImageFloatBox& inference_box, - const ImagePixelBox& box -){ - double width = (double)original_image.width(); - double height = (double)original_image.height(); - ptrdiff_t box_x = (ptrdiff_t)(width * inference_box.x + 0.5); - ptrdiff_t box_y = (ptrdiff_t)(height * inference_box.y + 0.5); - return ImageFloatBox( - (box_x + box.min_x) / width, - (box_y + box.min_y) / height, - (box.max_x - box.min_x) / width, - (box.max_y - box.min_y) / height - ); -} - - -ImagePixelBox floatbox_to_pixelbox(size_t width, size_t height, const ImageFloatBox& float_box){ - return ImagePixelBox( - (size_t)std::max(width * float_box.x + 0.5, 0), - (size_t)std::max(height * float_box.y + 0.5, 0), - (size_t)(width * (float_box.x + float_box.width) + 0.5), - (size_t)(height * (float_box.y + float_box.height) + 0.5) - ); -} -ImageFloatBox pixelbox_to_floatbox(size_t width, size_t height, const ImagePixelBox& pixel_box){ - double image_inverse_width = 1. / (double)width; - double image_inverse_height = 1. / (double)height; - return ImageFloatBox( - pixel_box.min_x * image_inverse_width, - pixel_box.min_y * image_inverse_height, - pixel_box.width() * image_inverse_width, - pixel_box.height() * image_inverse_height - ); -} -ImageFloatBox pixelbox_to_floatbox(const ImageViewRGB32& image, const ImagePixelBox& pixel_box){ - return pixelbox_to_floatbox(image.width(), image.height(), pixel_box); -} - - -ImagePixelBox extract_object_from_inner_feature( - size_t width, size_t height, - const ImagePixelBox& inner_relative_to_image, - const ImageFloatBox& inner_relative_to_object -){ - double scale_x = inner_relative_to_image.width() / inner_relative_to_object.width; - double scale_y = inner_relative_to_image.height() / inner_relative_to_object.height; - - double shift_x = inner_relative_to_image.min_x - inner_relative_to_object.x * scale_x; - double shift_y = inner_relative_to_image.min_y - inner_relative_to_object.y * scale_y; - shift_x = std::max(shift_x, 0); - shift_y = std::max(shift_y, 0); - - size_t max_x = (size_t)(shift_x + scale_x + 0.5); - size_t max_y = (size_t)(shift_y + scale_y + 0.5); - max_x = std::min(max_x, width); - max_y = std::min(max_y, height); - - return ImagePixelBox( - (size_t)(shift_x + 0.5), - (size_t)(shift_y + 0.5), - max_x, - max_y - ); -} - - -void draw_box(ImageRGB32& image, const ImagePixelBox& pixel_box, uint32_t color, size_t thickness){ - if (thickness == 0 || image.width() == 0 || image.height() == 0){ - return; - } - - auto clamp_x = [&](ptrdiff_t x){ - x = std::max(x, 0); - return std::min(x, (ptrdiff_t)image.width() - 1); - }; - auto clamp_y = [&](ptrdiff_t y){ - y = std::max(y, 0); - return std::min(y, (ptrdiff_t)image.height() - 1); - }; - - auto draw_solid_rect = [&](ptrdiff_t start_x, ptrdiff_t start_y, ptrdiff_t end_x, ptrdiff_t end_y){ - start_x = clamp_x(start_x); - end_x = clamp_x(end_x); - start_y = clamp_y(start_y); - end_y = clamp_y(end_y); - for (ptrdiff_t y = start_y; y <= end_y; ++y){ - for (ptrdiff_t x = start_x; x <= end_x; ++x){ - // setPixelColor(x, y, qColor); - image.pixel(x, y) = color; - } - } - }; - - ptrdiff_t lo = ((ptrdiff_t)thickness - 1) / 2; // lower offset - ptrdiff_t uo = (ptrdiff_t)thickness - lo - 1; // upper offset - - // draw the upper horizontal line - draw_solid_rect(pixel_box.min_x-lo, pixel_box.min_y-lo, pixel_box.max_x+uo-1, pixel_box.min_y+uo); - // draw the lower horizontal line - draw_solid_rect(pixel_box.min_x-lo, pixel_box.max_y-lo-1, pixel_box.max_x+uo-1, pixel_box.max_y+uo-1); - // draw the left vertical line - draw_solid_rect(pixel_box.min_x-lo, pixel_box.min_y-lo, pixel_box.min_x+uo, pixel_box.max_y+uo-1); - // draw the right vertical line - draw_solid_rect(pixel_box.max_x-lo-1, pixel_box.min_y-lo, pixel_box.max_x+uo-1, pixel_box.max_y+uo-1); -} - - - -} +/* Image Boxes + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Rectangle.tpp" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTypes/ImageViewHSV32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageBoxes.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +template struct Rectangle; + + +ImagePixelBox::ImagePixelBox(size_t p_min_x, size_t p_min_y, size_t p_max_x, size_t p_max_y) + : Rectangle(p_min_x, p_min_y, p_max_x, p_max_y) +{ + const size_t MAX_VALUE = 0xffffffff; + + // Check for potential negative values being passed here. + if (min_x > MAX_VALUE){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: min_x = " + std::to_string(min_x) + ); + } + if (min_y > MAX_VALUE){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: min_y = " + std::to_string(min_y) + ); + } + if (max_x > MAX_VALUE){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: max_x = " + std::to_string(max_x) + ); + } + if (max_y > MAX_VALUE){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, "Pixel Overflow: max_y = " + std::to_string(max_y) + ); + } +} + + +ImagePixelBox::ImagePixelBox(const Kernels::Waterfill::WaterfillObject& object) + : ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) +{} + + +void ImagePixelBox::clip(size_t image_width, size_t image_height){ + min_x = std::max((size_t)0, min_x); + min_y = std::max((size_t)0, min_y); + max_x = std::min(max_x, image_width); + max_y = std::min(max_y, image_height); +} +void ImagePixelBox::clip(const ImagePixelBox& box){ + min_x = std::max(min_x, box.min_x); + min_y = std::max(min_y, box.min_y); + max_x = std::min(max_x, box.max_x); + max_y = std::min(max_y, box.max_y); +} + +ImagePixelBox ImagePixelBox::expand_as(size_t per_side_increase) const{ + size_t new_min_x = min_x >= per_side_increase ? min_x - per_side_increase : 0; + size_t new_min_y = min_y >= per_side_increase ? min_y - per_side_increase : 0; + return ImagePixelBox(new_min_x, new_min_y, max_x + per_side_increase, max_y + per_side_increase); +} + +size_t ImagePixelBox::distance_x(const ImagePixelBox& box) const{ + size_t min_x = std::max(this->min_x, box.min_x); + size_t max_x = std::min(this->max_x, box.max_x); + if (min_x >= max_x){ + return min_x - max_x; + } + return 0; +} + +size_t ImagePixelBox::distance_y(const ImagePixelBox& box) const{ + size_t min_y = std::max(this->min_y, box.min_y); + size_t max_y = std::min(this->max_y, box.max_y); + if (min_y >= max_y){ + return min_y - max_y; + } + return 0; +} + + +ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImagePixelBox& box){ + return image.sub_image(box.min_x, box.min_y, box.width(), box.height()); +} +ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box){ + size_t min_x = (size_t)(image.width() * box.x + 0.5); + size_t min_y = (size_t)(image.height() * box.y + 0.5); + size_t width = (size_t)(image.width() * box.width + 0.5); + size_t height = (size_t)(image.height() * box.height + 0.5); + return image.sub_image(min_x, min_y, width, height); +} +ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y){ + ptrdiff_t min_x = (ptrdiff_t)(image.width() * box.x + 0.5) + offset_x; + ptrdiff_t min_y = (ptrdiff_t)(image.height() * box.y + 0.5) + offset_y; + ptrdiff_t width = (ptrdiff_t)(image.width() * box.width + 0.5); + ptrdiff_t height = (ptrdiff_t)(image.height() * box.height + 0.5); + + if (min_x < 0){ + width += min_x; + min_x = 0; + width = std::max(width, 0); + } + if (min_y < 0){ + height += min_y; + min_y = 0; + height = std::max(height, 0); + } + + return image.sub_image(min_x, min_y, width, height); +} + + +ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImagePixelBox& box){ + return image.sub_image(box.min_x, box.min_y, box.width(), box.height()); +} +ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box){ + size_t min_x = (size_t)(image.width() * box.x + 0.5); + size_t min_y = (size_t)(image.height() * box.y + 0.5); + size_t width = (size_t)(image.width() * box.width + 0.5); + size_t height = (size_t)(image.height() * box.height + 0.5); + return image.sub_image(min_x, min_y, width, height); +} +ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y){ + ptrdiff_t min_x = (ptrdiff_t)(image.width() * box.x + 0.5) + offset_x; + ptrdiff_t min_y = (ptrdiff_t)(image.height() * box.y + 0.5) + offset_y; + ptrdiff_t width = (ptrdiff_t)(image.width() * box.width + 0.5); + ptrdiff_t height = (ptrdiff_t)(image.height() * box.height + 0.5); + + if (min_x < 0){ + width += min_x; + min_x = 0; + width = std::max(width, 0); + } + if (min_y < 0){ + height += min_y; + min_y = 0; + height = std::max(height, 0); + } + + return image.sub_image(min_x, min_y, width, height); +} + + + +ImageFloatBox translate_to_parent( + const ImageViewRGB32& original_image, + const ImageFloatBox& inference_box, + const ImagePixelBox& box +){ + double width = (double)original_image.width(); + double height = (double)original_image.height(); + ptrdiff_t box_x = (ptrdiff_t)(width * inference_box.x + 0.5); + ptrdiff_t box_y = (ptrdiff_t)(height * inference_box.y + 0.5); + return ImageFloatBox( + (box_x + box.min_x) / width, + (box_y + box.min_y) / height, + (box.max_x - box.min_x) / width, + (box.max_y - box.min_y) / height + ); +} + + +ImagePixelBox floatbox_to_pixelbox(size_t width, size_t height, const ImageFloatBox& float_box){ + return ImagePixelBox( + (size_t)std::max(width * float_box.x + 0.5, 0), + (size_t)std::max(height * float_box.y + 0.5, 0), + (size_t)(width * (float_box.x + float_box.width) + 0.5), + (size_t)(height * (float_box.y + float_box.height) + 0.5) + ); +} +ImageFloatBox pixelbox_to_floatbox(size_t width, size_t height, const ImagePixelBox& pixel_box){ + double image_inverse_width = 1. / (double)width; + double image_inverse_height = 1. / (double)height; + return ImageFloatBox( + pixel_box.min_x * image_inverse_width, + pixel_box.min_y * image_inverse_height, + pixel_box.width() * image_inverse_width, + pixel_box.height() * image_inverse_height + ); +} +ImageFloatBox pixelbox_to_floatbox(const ImageViewRGB32& image, const ImagePixelBox& pixel_box){ + return pixelbox_to_floatbox(image.width(), image.height(), pixel_box); +} + + +ImagePixelBox extract_object_from_inner_feature( + size_t width, size_t height, + const ImagePixelBox& inner_relative_to_image, + const ImageFloatBox& inner_relative_to_object +){ + double scale_x = inner_relative_to_image.width() / inner_relative_to_object.width; + double scale_y = inner_relative_to_image.height() / inner_relative_to_object.height; + + double shift_x = inner_relative_to_image.min_x - inner_relative_to_object.x * scale_x; + double shift_y = inner_relative_to_image.min_y - inner_relative_to_object.y * scale_y; + shift_x = std::max(shift_x, 0); + shift_y = std::max(shift_y, 0); + + size_t max_x = (size_t)(shift_x + scale_x + 0.5); + size_t max_y = (size_t)(shift_y + scale_y + 0.5); + max_x = std::min(max_x, width); + max_y = std::min(max_y, height); + + return ImagePixelBox( + (size_t)(shift_x + 0.5), + (size_t)(shift_y + 0.5), + max_x, + max_y + ); +} + + +void draw_box(ImageRGB32& image, const ImagePixelBox& pixel_box, uint32_t color, size_t thickness){ + if (thickness == 0 || image.width() == 0 || image.height() == 0){ + return; + } + + auto clamp_x = [&](ptrdiff_t x){ + x = std::max(x, 0); + return std::min(x, (ptrdiff_t)image.width() - 1); + }; + auto clamp_y = [&](ptrdiff_t y){ + y = std::max(y, 0); + return std::min(y, (ptrdiff_t)image.height() - 1); + }; + + auto draw_solid_rect = [&](ptrdiff_t start_x, ptrdiff_t start_y, ptrdiff_t end_x, ptrdiff_t end_y){ + start_x = clamp_x(start_x); + end_x = clamp_x(end_x); + start_y = clamp_y(start_y); + end_y = clamp_y(end_y); + for (ptrdiff_t y = start_y; y <= end_y; ++y){ + for (ptrdiff_t x = start_x; x <= end_x; ++x){ + // setPixelColor(x, y, qColor); + image.pixel(x, y) = color; + } + } + }; + + ptrdiff_t lo = ((ptrdiff_t)thickness - 1) / 2; // lower offset + ptrdiff_t uo = (ptrdiff_t)thickness - lo - 1; // upper offset + + // draw the upper horizontal line + draw_solid_rect(pixel_box.min_x-lo, pixel_box.min_y-lo, pixel_box.max_x+uo-1, pixel_box.min_y+uo); + // draw the lower horizontal line + draw_solid_rect(pixel_box.min_x-lo, pixel_box.max_y-lo-1, pixel_box.max_x+uo-1, pixel_box.max_y+uo-1); + // draw the left vertical line + draw_solid_rect(pixel_box.min_x-lo, pixel_box.min_y-lo, pixel_box.min_x+uo, pixel_box.max_y+uo-1); + // draw the right vertical line + draw_solid_rect(pixel_box.max_x-lo-1, pixel_box.min_y-lo, pixel_box.max_x+uo-1, pixel_box.max_y+uo-1); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.h b/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.h index 44054e1743..48a28cbe0b 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.h +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageBoxes.h @@ -1,154 +1,154 @@ -/* Image Boxes - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageBoxes_H -#define PokemonAutomation_CommonFramework_ImageBoxes_H - -#include -#include -#include "Common/Cpp/Rectangle.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; - class ImageRGB32; - class ImageViewHSV32; -namespace Kernels{ -namespace Waterfill{ - class WaterfillObject; -} // end namespace Waterfill -} // end namespace Kernels - - -// Deprecated -using pxint_t = size_t; - -// An axis aligned box in the image pixel space. Used for getting a crop from an image for various -// visual detection. -// The box is measured in pixel units. Image coordinate system is: -// - x axis from left to right, range: [0, image_width) -// - y axis from top to bottom, range: [0, image_height) -// min_x: leftmost pixel coordinate of the box -// min_y: topmost pixel coordinate of the box -// max_x: 1 + rightmost pixel coordinate of the box -// max_y: 1 + bottommost pixel coordinate of the box -struct ImagePixelBox : public Rectangle{ - ImagePixelBox() = default; - ImagePixelBox(size_t p_min_x, size_t p_min_y, size_t p_max_x, size_t p_max_y); - ImagePixelBox(const Kernels::Waterfill::WaterfillObject& object); - - size_t center_x() const{ return (min_x + max_x)/2; } - size_t center_y() const{ return (min_y + max_y)/2; } - - // Clip this box to be within the image size. - void clip(size_t image_width, size_t image_height); - - // Clip this box to be within the specified box. - void clip(const ImagePixelBox& box); - - // Return a new box with an increased size. Each side of the box is increased by `per_side_increase`. - // `min_x` and `min_y` are clamped to 0 if becoming negative. - ImagePixelBox expand_as(size_t per_side_increase) const; - - // The distance to another box on x axis. If two boxes overlap, the distance is 0. - size_t distance_x(const ImagePixelBox& box) const; - // The distance to another box on y axis. If two boxes overlap, the distance is 0. - size_t distance_y(const ImagePixelBox& box) const; -}; - -// An axis aligned box in the normalized image space. Used for getting a crop from an image for various -// visual detection. -// The box is measured relative to the original image size. The coordinate system is: -// - x axis from left to right, range: [0.0, 1.0) -// - y axis from top to bottom, range: [0.0, 1.0) -// In this way, the box can be defined independent of the original image's resolution, allowing visual -// inference code to work on all video stream and image resolutions. -// x: leftmost coordinate of the box, range: [0.0, 1.0) -// y: topmost coordinate of the box, range: [0.0, 1.0) -// width: width of the box relative to the image width, range: [0.0, 1.0) -// height: height of the box relative to the image height, range: [0.0, 1.0) -struct ImageFloatBox{ - double x; - double y; - double width; - double height; - - ImageFloatBox() - : x(0), y(0) - , width(0), height(0) - {} - ImageFloatBox( - double p_x, double p_y, - double p_width, double p_height - ) - : x(p_x), y(p_y) - , width(p_width), height(p_height) - {} -}; - - -// Given an image, extract the request box from it. - -// Return a reference to the sub-region of the image. -ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImagePixelBox& box); -ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box); -ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y); - -ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImagePixelBox& box); -ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box); -ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y); - - - -// Given: -// - "inference_box" is a box within "original_image". -// - "box" is a box within "inference_box". -// -// Translate "box" into a new box in the orignal image. -// -// This is used for translating detection box within inference boxes back to -// the parent so it can be displayed in a VideoOverlay. -ImageFloatBox translate_to_parent( - const ImageViewRGB32& original_image, - const ImageFloatBox& inference_box, - const ImagePixelBox& box -); - - -// Given a ImagePixelBox within an image, get the ImageFloatBox for it. -ImagePixelBox floatbox_to_pixelbox(size_t width, size_t height, const ImageFloatBox& float_box); -ImageFloatBox pixelbox_to_floatbox(size_t width, size_t height, const ImagePixelBox& pixel_box); -ImageFloatBox pixelbox_to_floatbox(const ImageViewRGB32& image, const ImagePixelBox& pixel_box); - - -// Given: -// - "inner" is a feature within an "object". -// - "inner_relative_to_image" is the box for the "inner" feature relative to the image. -// - "inner_relative_to_object" is the box for the "inner" feature within the object. -// -// Return the enclosing box for the object in the original image. -// -// This used by detection methods that detect a sub-feature within a larger -// object. But then you need to expand out the object to match against a -// template to confirm the detection. -// -// The width and height parameters will ensure that the returned box stays -// within the dimensions of the original image. -ImagePixelBox extract_object_from_inner_feature( - size_t width, size_t height, - const ImagePixelBox& inner_relative_to_image, - const ImageFloatBox& inner_relative_to_object -); - -// Draw a box on the image. Used for debugging purposes: -// save inference results to an image on the disk. -// color: the color of the pixel. See Common/Cpp/Color.h:Color on the color format. -// thickness: thickness (in unit of pixels) of the box border. -void draw_box(ImageRGB32& image, const ImagePixelBox& pixel_box, uint32_t color, size_t thickness = 1); - - - -} -#endif +/* Image Boxes + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageBoxes_H +#define PokemonAutomation_CommonFramework_ImageBoxes_H + +#include +#include +#include "Common/Cpp/Rectangle.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + class ImageRGB32; + class ImageViewHSV32; +namespace Kernels{ +namespace Waterfill{ + class WaterfillObject; +} // end namespace Waterfill +} // end namespace Kernels + + +// Deprecated +using pxint_t = size_t; + +// An axis aligned box in the image pixel space. Used for getting a crop from an image for various +// visual detection. +// The box is measured in pixel units. Image coordinate system is: +// - x axis from left to right, range: [0, image_width) +// - y axis from top to bottom, range: [0, image_height) +// min_x: leftmost pixel coordinate of the box +// min_y: topmost pixel coordinate of the box +// max_x: 1 + rightmost pixel coordinate of the box +// max_y: 1 + bottommost pixel coordinate of the box +struct ImagePixelBox : public Rectangle{ + ImagePixelBox() = default; + ImagePixelBox(size_t p_min_x, size_t p_min_y, size_t p_max_x, size_t p_max_y); + ImagePixelBox(const Kernels::Waterfill::WaterfillObject& object); + + size_t center_x() const{ return (min_x + max_x)/2; } + size_t center_y() const{ return (min_y + max_y)/2; } + + // Clip this box to be within the image size. + void clip(size_t image_width, size_t image_height); + + // Clip this box to be within the specified box. + void clip(const ImagePixelBox& box); + + // Return a new box with an increased size. Each side of the box is increased by `per_side_increase`. + // `min_x` and `min_y` are clamped to 0 if becoming negative. + ImagePixelBox expand_as(size_t per_side_increase) const; + + // The distance to another box on x axis. If two boxes overlap, the distance is 0. + size_t distance_x(const ImagePixelBox& box) const; + // The distance to another box on y axis. If two boxes overlap, the distance is 0. + size_t distance_y(const ImagePixelBox& box) const; +}; + +// An axis aligned box in the normalized image space. Used for getting a crop from an image for various +// visual detection. +// The box is measured relative to the original image size. The coordinate system is: +// - x axis from left to right, range: [0.0, 1.0) +// - y axis from top to bottom, range: [0.0, 1.0) +// In this way, the box can be defined independent of the original image's resolution, allowing visual +// inference code to work on all video stream and image resolutions. +// x: leftmost coordinate of the box, range: [0.0, 1.0) +// y: topmost coordinate of the box, range: [0.0, 1.0) +// width: width of the box relative to the image width, range: [0.0, 1.0) +// height: height of the box relative to the image height, range: [0.0, 1.0) +struct ImageFloatBox{ + double x; + double y; + double width; + double height; + + ImageFloatBox() + : x(0), y(0) + , width(0), height(0) + {} + ImageFloatBox( + double p_x, double p_y, + double p_width, double p_height + ) + : x(p_x), y(p_y) + , width(p_width), height(p_height) + {} +}; + + +// Given an image, extract the request box from it. + +// Return a reference to the sub-region of the image. +ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImagePixelBox& box); +ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box); +ImageViewRGB32 extract_box_reference(const ImageViewRGB32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y); + +ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImagePixelBox& box); +ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box); +ImageViewHSV32 extract_box_reference(const ImageViewHSV32& image, const ImageFloatBox& box, ptrdiff_t offset_x, ptrdiff_t offset_y); + + + +// Given: +// - "inference_box" is a box within "original_image". +// - "box" is a box within "inference_box". +// +// Translate "box" into a new box in the orignal image. +// +// This is used for translating detection box within inference boxes back to +// the parent so it can be displayed in a VideoOverlay. +ImageFloatBox translate_to_parent( + const ImageViewRGB32& original_image, + const ImageFloatBox& inference_box, + const ImagePixelBox& box +); + + +// Given a ImagePixelBox within an image, get the ImageFloatBox for it. +ImagePixelBox floatbox_to_pixelbox(size_t width, size_t height, const ImageFloatBox& float_box); +ImageFloatBox pixelbox_to_floatbox(size_t width, size_t height, const ImagePixelBox& pixel_box); +ImageFloatBox pixelbox_to_floatbox(const ImageViewRGB32& image, const ImagePixelBox& pixel_box); + + +// Given: +// - "inner" is a feature within an "object". +// - "inner_relative_to_image" is the box for the "inner" feature relative to the image. +// - "inner_relative_to_object" is the box for the "inner" feature within the object. +// +// Return the enclosing box for the object in the original image. +// +// This used by detection methods that detect a sub-feature within a larger +// object. But then you need to expand out the object to match against a +// template to confirm the detection. +// +// The width and height parameters will ensure that the returned box stays +// within the dimensions of the original image. +ImagePixelBox extract_object_from_inner_feature( + size_t width, size_t height, + const ImagePixelBox& inner_relative_to_image, + const ImageFloatBox& inner_relative_to_object +); + +// Draw a box on the image. Used for debugging purposes: +// save inference results to an image on the disk. +// color: the color of the pixel. See Common/Cpp/Color.h:Color on the color format. +// thickness: thickness (in unit of pixels) of the box border. +void draw_box(ImageRGB32& image, const ImagePixelBox& pixel_box, uint32_t color, size_t thickness = 1); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp index 9f3674761f..2a4079b9a2 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.cpp @@ -1,115 +1,115 @@ -/* Image Diff - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" -#include "Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h" -#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageDiff.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - } - if (image.width() != alpha_mask.width() || image.height() != alpha_mask.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - Kernels::PixelSums sums; - Kernels::pixel_sum_sqr( - sums, image.width(), image.height(), - image.data(), image.bytes_per_row(), - alpha_mask.data(), alpha_mask.bytes_per_row() - ); - - FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); - sum /= (double)sums.count; - return sum; -} - - - -void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier){ - Kernels::scale_brightness( - image.width(), image.height(), - image.data(), image.bytes_per_row(), - (float)multiplier.r, (float)multiplier.g, (float)multiplier.b - ); -} - - - -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image){ - if (!image){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - return 765; // Max possible deviation. - } - if (reference.width() != image.width() || reference.height() != image.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - uint64_t count = 0; - uint64_t sumsqrs = 0; - Kernels::sum_sqr_deviation( - count, sumsqrs, - reference.width(), reference.height(), - reference.data(), reference.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - return std::sqrt((double)sumsqrs / (double)count); -} -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background){ - if (!image){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - return 765; // Max possible deviation. - } - if (reference.width() != image.width() || reference.height() != image.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - uint64_t count = 0; - uint64_t sumsqrs = 0; - Kernels::sum_sqr_deviation( - count, sumsqrs, - reference.width(), reference.height(), - reference.data(), reference.bytes_per_row(), - image.data(), image.bytes_per_row(), - (uint32_t)background - ); - return std::sqrt((double)sumsqrs / (double)count); -} -double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image){ - if (!image){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); - return 765; // Max possible deviation. - } - if (reference.width() != image.width() || reference.height() != image.height()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); - } - uint64_t count = 0; - uint64_t sumsqrs = 0; - Kernels::sum_sqr_deviation_masked( - count, sumsqrs, - reference.width(), reference.height(), - reference.data(), reference.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - return std::sqrt((double)sumsqrs / (double)count); -} - - - -} -} +/* Image Diff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" +#include "Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h" +#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageDiff.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + } + if (image.width() != alpha_mask.width() || image.height() != alpha_mask.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + Kernels::PixelSums sums; + Kernels::pixel_sum_sqr( + sums, image.width(), image.height(), + image.data(), image.bytes_per_row(), + alpha_mask.data(), alpha_mask.bytes_per_row() + ); + + FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); + sum /= (double)sums.count; + return sum; +} + + + +void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier){ + Kernels::scale_brightness( + image.width(), image.height(), + image.data(), image.bytes_per_row(), + (float)multiplier.r, (float)multiplier.g, (float)multiplier.b + ); +} + + + +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image){ + if (!image){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + return 765; // Max possible deviation. + } + if (reference.width() != image.width() || reference.height() != image.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + uint64_t count = 0; + uint64_t sumsqrs = 0; + Kernels::sum_sqr_deviation( + count, sumsqrs, + reference.width(), reference.height(), + reference.data(), reference.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + return std::sqrt((double)sumsqrs / (double)count); +} +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background){ + if (!image){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + return 765; // Max possible deviation. + } + if (reference.width() != image.width() || reference.height() != image.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + uint64_t count = 0; + uint64_t sumsqrs = 0; + Kernels::sum_sqr_deviation( + count, sumsqrs, + reference.width(), reference.height(), + reference.data(), reference.bytes_per_row(), + image.data(), image.bytes_per_row(), + (uint32_t)background + ); + return std::sqrt((double)sumsqrs / (double)count); +} +double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image){ + if (!image){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Dimensions"); + return 765; // Max possible deviation. + } + if (reference.width() != image.width() || reference.height() != image.height()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching Dimensions"); + } + uint64_t count = 0; + uint64_t sumsqrs = 0; + Kernels::sum_sqr_deviation_masked( + count, sumsqrs, + reference.width(), reference.height(), + reference.data(), reference.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + return std::sqrt((double)sumsqrs / (double)count); +} + + + +} +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h index 1bc8ad9f99..299c1204f9 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageDiff.h @@ -1,64 +1,64 @@ -/* Image Diff - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageDiff_H -#define PokemonAutomation_CommonFramework_ImageDiff_H - -#include "CommonFramework/ImageTools/FloatPixel.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; - class ImageRGB32; -namespace ImageMatch{ - - -// Compute average of all 4 components. -// - The two images must be the same dimensions. -// - The alpha channels of "reference" is used to indicate which parts to ignore. -// 0 means background. 255 means object. No other values are valid. -FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask); - - -// Multiply every pixel by "multiplier". Alpha channels are ignored. -void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier); - - -// Compute root-mean-square deviation of the two images. -// - The two images must be the same dimensions. -// - The alpha channels of "reference" must be 0 or 255. No other values are valid. -// -// If (reference.alpha == 255) Count the pixel. -// If (reference.alpha == 0) Ignore the pixel and exclude from pixel count. -// -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image); - - -// Compute root-mean-square deviation of the two images. -// - The two images must be the same dimensions. -// - The alpha channels of "reference" must be 0 or 255. No other values are valid. -// -// If (reference.alpha == 255) Count the pixel. -// If (reference.alpha == 0) Replace reference pixel with "background". -// -double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background); - - -// Compute root-mean-square deviation of the two images. -// - The two images must be the same dimensions. -// - The alpha channels of both images must be 0 or 255. No other values are valid. -// -// If (reference.alpha == 255 && image.alpha == 255) Count the pixel. -// If (reference.alpha == 255 && image.alpha == 0) Count the pixel as maximum possible distance. (255 for all RGB) -// If (reference.alpha == 0 && image.alpha == 255) Count the pixel as maximum possible distance. (255 for all RGB) -// If (reference.alpha == 0 && image.alpha == 0) Ignore the pixel and exclude from pixel count. -// -double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image); - - - -} -} -#endif +/* Image Diff + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageDiff_H +#define PokemonAutomation_CommonFramework_ImageDiff_H + +#include "CommonFramework/ImageTools/FloatPixel.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + class ImageRGB32; +namespace ImageMatch{ + + +// Compute average of all 4 components. +// - The two images must be the same dimensions. +// - The alpha channels of "reference" is used to indicate which parts to ignore. +// 0 means background. 255 means object. No other values are valid. +FloatPixel pixel_average(const ImageViewRGB32& image, const ImageViewRGB32& alpha_mask); + + +// Multiply every pixel by "multiplier". Alpha channels are ignored. +void scale_brightness(ImageRGB32& image, const FloatPixel& multiplier); + + +// Compute root-mean-square deviation of the two images. +// - The two images must be the same dimensions. +// - The alpha channels of "reference" must be 0 or 255. No other values are valid. +// +// If (reference.alpha == 255) Count the pixel. +// If (reference.alpha == 0) Ignore the pixel and exclude from pixel count. +// +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image); + + +// Compute root-mean-square deviation of the two images. +// - The two images must be the same dimensions. +// - The alpha channels of "reference" must be 0 or 255. No other values are valid. +// +// If (reference.alpha == 255) Count the pixel. +// If (reference.alpha == 0) Replace reference pixel with "background". +// +double pixel_RMSD(const ImageViewRGB32& reference, const ImageViewRGB32& image, Color background); + + +// Compute root-mean-square deviation of the two images. +// - The two images must be the same dimensions. +// - The alpha channels of both images must be 0 or 255. No other values are valid. +// +// If (reference.alpha == 255 && image.alpha == 255) Count the pixel. +// If (reference.alpha == 255 && image.alpha == 0) Count the pixel as maximum possible distance. (255 for all RGB) +// If (reference.alpha == 0 && image.alpha == 255) Count the pixel as maximum possible distance. (255 for all RGB) +// If (reference.alpha == 0 && image.alpha == 0) Ignore the pixel and exclude from pixel count. +// +double pixel_RMSD_masked(const ImageViewRGB32& reference, const ImageViewRGB32& image); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.cpp b/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.cpp index a9ded0b90d..839032596a 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.cpp @@ -1,135 +1,135 @@ -/* Image Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "ImageBoxes.h" -#include "ImageStats.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -FloatPixel image_average(const ImageViewRGB32& image){ - Kernels::PixelSums sums; - Kernels::pixel_sum_sqr( - sums, image.width(), image.height(), - image.data(), image.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - - FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); - - return sum / (double)sums.count; -} -FloatPixel image_stddev(const ImageViewRGB32& image){ - Kernels::PixelSums sums; - Kernels::pixel_sum_sqr( - sums, image.width(), image.height(), - image.data(), image.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - - FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); - FloatPixel sqr((double)sums.sqrR, (double)sums.sqrG, (double)sums.sqrB); - - FloatPixel variance = (sqr - sum*sum / (double)sums.count) / ((double)sums.count - 1); - - return FloatPixel( - std::sqrt(variance.r), - std::sqrt(variance.g), - std::sqrt(variance.b) - ); -} -ImageStats image_stats(const ImageViewRGB32& image){ - Kernels::PixelSums sums; - Kernels::pixel_sum_sqr( - sums, image.width(), image.height(), - image.data(), image.bytes_per_row(), - image.data(), image.bytes_per_row() - ); - - FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); - FloatPixel sqr((double)sums.sqrR, (double)sums.sqrG, (double)sums.sqrB); - - FloatPixel average = sum / (double)sums.count; - - FloatPixel variance = (sqr - sum*sum / (double)sums.count) / ((double)sums.count - 1); - FloatPixel stddev = FloatPixel( - std::sqrt(variance.r), - std::sqrt(variance.g), - std::sqrt(variance.b) - ); - - ImageStats stats(average, stddev, sums.count); - - if (PreloadSettings::debug().COLOR_CHECK){ - std::cout << "Compute imageStats: avg " << stats.average.to_string() << " (sum " << stats.average.sum() - << ") stddev " << stats.stddev.to_string() << " (sum " << stats.stddev.sum() - << ") count " << stats.count << std::endl; - } - - return stats; -} - - - - - -ImageStats image_border_stats(const ImageViewRGB32& image){ - size_t w = image.width(); - size_t h = image.height(); - if (w * h <= 1){ - return ImageStats(); - } - - FloatPixel sum; - FloatPixel sqr_sum; - - for (size_t c = 0; c < w; c++){ - FloatPixel p(image.pixel(c, 0)); - sum += p; - sqr_sum += p * p; - } - for (size_t c = 0; c < w; c++){ - FloatPixel p(image.pixel(c, h - 1)); - sum += p; - sqr_sum += p * p; - } - for (size_t r = 0; r < h; r++){ - FloatPixel p(image.pixel(0, r)); - sum += p; - sqr_sum += p * p; - } - for (size_t r = 0; r < h; r++){ - FloatPixel p(image.pixel(0, h - 1)); - sum += p; - sqr_sum += p * p; - } - - size_t total = 2 * (w + h); - double totalf = (double)total; - FloatPixel variance = (sqr_sum - sum*sum / totalf) / (totalf - 1); - return ImageStats{ - sum / totalf, - FloatPixel( - std::sqrt(variance.r), - std::sqrt(variance.g), - std::sqrt(variance.b) - ), - total - }; -} - - - -} +/* Image Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "ImageBoxes.h" +#include "ImageStats.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +FloatPixel image_average(const ImageViewRGB32& image){ + Kernels::PixelSums sums; + Kernels::pixel_sum_sqr( + sums, image.width(), image.height(), + image.data(), image.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + + FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); + + return sum / (double)sums.count; +} +FloatPixel image_stddev(const ImageViewRGB32& image){ + Kernels::PixelSums sums; + Kernels::pixel_sum_sqr( + sums, image.width(), image.height(), + image.data(), image.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + + FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); + FloatPixel sqr((double)sums.sqrR, (double)sums.sqrG, (double)sums.sqrB); + + FloatPixel variance = (sqr - sum*sum / (double)sums.count) / ((double)sums.count - 1); + + return FloatPixel( + std::sqrt(variance.r), + std::sqrt(variance.g), + std::sqrt(variance.b) + ); +} +ImageStats image_stats(const ImageViewRGB32& image){ + Kernels::PixelSums sums; + Kernels::pixel_sum_sqr( + sums, image.width(), image.height(), + image.data(), image.bytes_per_row(), + image.data(), image.bytes_per_row() + ); + + FloatPixel sum((double)sums.sumR, (double)sums.sumG, (double)sums.sumB); + FloatPixel sqr((double)sums.sqrR, (double)sums.sqrG, (double)sums.sqrB); + + FloatPixel average = sum / (double)sums.count; + + FloatPixel variance = (sqr - sum*sum / (double)sums.count) / ((double)sums.count - 1); + FloatPixel stddev = FloatPixel( + std::sqrt(variance.r), + std::sqrt(variance.g), + std::sqrt(variance.b) + ); + + ImageStats stats(average, stddev, sums.count); + + if (PreloadSettings::debug().COLOR_CHECK){ + std::cout << "Compute imageStats: avg " << stats.average.to_string() << " (sum " << stats.average.sum() + << ") stddev " << stats.stddev.to_string() << " (sum " << stats.stddev.sum() + << ") count " << stats.count << std::endl; + } + + return stats; +} + + + + + +ImageStats image_border_stats(const ImageViewRGB32& image){ + size_t w = image.width(); + size_t h = image.height(); + if (w * h <= 1){ + return ImageStats(); + } + + FloatPixel sum; + FloatPixel sqr_sum; + + for (size_t c = 0; c < w; c++){ + FloatPixel p(image.pixel(c, 0)); + sum += p; + sqr_sum += p * p; + } + for (size_t c = 0; c < w; c++){ + FloatPixel p(image.pixel(c, h - 1)); + sum += p; + sqr_sum += p * p; + } + for (size_t r = 0; r < h; r++){ + FloatPixel p(image.pixel(0, r)); + sum += p; + sqr_sum += p * p; + } + for (size_t r = 0; r < h; r++){ + FloatPixel p(image.pixel(0, h - 1)); + sum += p; + sqr_sum += p * p; + } + + size_t total = 2 * (w + h); + double totalf = (double)total; + FloatPixel variance = (sqr_sum - sum*sum / totalf) / (totalf - 1); + return ImageStats{ + sum / totalf, + FloatPixel( + std::sqrt(variance.r), + std::sqrt(variance.g), + std::sqrt(variance.b) + ), + total + }; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.h b/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.h index b0b665b0fe..faf989b1ee 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.h +++ b/SerialPrograms/Source/CommonFramework/ImageTools/ImageStats.h @@ -1,40 +1,40 @@ -/* Image Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageStats_H -#define PokemonAutomation_CommonFramework_ImageStats_H - -#include "FloatPixel.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; - -// Store basic stats of a group of pixels -struct ImageStats{ - // Average color among the pixels. - FloatPixel average; - // Stddev of the color for each color channel. - // The smaller the stddev on one channel, the closer the pixel values are on this channel. - FloatPixel stddev; - // How many pixels in the group. - uint64_t count; - ImageStats() : count(0) {} - ImageStats(FloatPixel a, FloatPixel s, uint64_t c) : average(a), stddev(s), count(c) {} -}; - - -// Pixels with alpha < 128 are ignored. -FloatPixel image_average(const ImageViewRGB32& image); -FloatPixel image_stddev(const ImageViewRGB32& image); -ImageStats image_stats(const ImageViewRGB32& image); - - -ImageStats image_border_stats(const ImageViewRGB32& image); - - - -} -#endif +/* Image Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageStats_H +#define PokemonAutomation_CommonFramework_ImageStats_H + +#include "FloatPixel.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + +// Store basic stats of a group of pixels +struct ImageStats{ + // Average color among the pixels. + FloatPixel average; + // Stddev of the color for each color channel. + // The smaller the stddev on one channel, the closer the pixel values are on this channel. + FloatPixel stddev; + // How many pixels in the group. + uint64_t count; + ImageStats() : count(0) {} + ImageStats(FloatPixel a, FloatPixel s, uint64_t c) : average(a), stddev(s), count(c) {} +}; + + +// Pixels with alpha < 128 are ignored. +FloatPixel image_average(const ImageViewRGB32& image); +FloatPixel image_stddev(const ImageViewRGB32& image); +ImageStats image_stats(const ImageViewRGB32& image); + + +ImageStats image_border_stats(const ImageViewRGB32& image); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.cpp b/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.cpp index ca2c945783..f13bd687f1 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.cpp @@ -1,24 +1,24 @@ -/* Binary Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "BinaryImage.h" - -namespace PokemonAutomation{ - - - -PackedBinaryMatrix::PackedBinaryMatrix(){ - m_matrix = Kernels::make_PackedBinaryMatrix(Kernels::get_BinaryMatrixType()); -} -PackedBinaryMatrix::PackedBinaryMatrix(size_t width, size_t height){ - m_matrix = Kernels::make_PackedBinaryMatrix(Kernels::get_BinaryMatrixType(), width, height); -} - - - - - -} +/* Binary Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "BinaryImage.h" + +namespace PokemonAutomation{ + + + +PackedBinaryMatrix::PackedBinaryMatrix(){ + m_matrix = Kernels::make_PackedBinaryMatrix(Kernels::get_BinaryMatrixType()); +} +PackedBinaryMatrix::PackedBinaryMatrix(size_t width, size_t height){ + m_matrix = Kernels::make_PackedBinaryMatrix(Kernels::get_BinaryMatrixType(), width, height); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.h b/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.h index f9271a5aec..38697499f8 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.h +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/BinaryImage.h @@ -1,90 +1,90 @@ -/* Binary Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_BinaryImage_H -#define PokemonAutomation_CommonFramework_BinaryImage_H - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ - -// A wrapper class of the packed binary matrix base class `Kernels::PackedBinaryMatrix_IB`. -// Those binary matrices are memory-efficient: each binary element is stored as just one bit in memory. -// They are mainly used by the Waterfill algorithm. -// See the comments of `PackedBinaryMatrix_IB` for more implementation details. -// -// This wrapper is useful in making the usage of matrix as a locally-defined class: you can use it like -// `PackedBinaryMatrix matrix;` -// Otherwise, because of -// `PackedBinaryMatrix_IB` being polymorphic, we have to write explictly -// `std::unique_ptr` to define a matrix. -class PackedBinaryMatrix{ -public: - // Rule of 5 - PackedBinaryMatrix(PackedBinaryMatrix&& x) : m_matrix(std::move(x.m_matrix)) {} - void operator=(PackedBinaryMatrix&& x){ m_matrix = std::move(x.m_matrix); } -// PackedBinaryMatrix(const PackedBinaryMatrix& x) : m_matrix(x.m_matrix->clone()) {} -// void operator=(const PackedBinaryMatrix& x){ m_matrix = x.m_matrix->clone(); } - - // Don't allow implicit copying. - PackedBinaryMatrix copy() const{ return m_matrix->clone(); }; - -public: - // Construction - PackedBinaryMatrix(); - PackedBinaryMatrix(size_t width, size_t height); - - Kernels::BinaryMatrixType type() const{ return m_matrix->type(); } - - void clear(){ m_matrix->clear(); } - - // Zero the entire matrix. - void set_zero(){ return m_matrix->set_zero(); } - - // Set entire matrix to ones. - void set_ones(){ return m_matrix->set_ones(); } - - // Invert all bits. - void invert(){ return m_matrix->invert(); } - - // Bitwise with another matrix. Dimensions must be the same! - void operator^=(const PackedBinaryMatrix& x){ *m_matrix ^= *x.m_matrix; } - void operator|=(const PackedBinaryMatrix& x){ *m_matrix |= *x.m_matrix; } - void operator&=(const PackedBinaryMatrix& x){ *m_matrix &= *x.m_matrix; } - - // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". - std::string dump() const{ return m_matrix->dump(); } - // Print part of max as 0s and 1s. Rows are ended with "\n". - std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const{ return m_matrix->dump(min_x, min_y, max_x, max_y); } - -public: - size_t width() const{ return m_matrix->width(); } - size_t height() const{ return m_matrix->height(); } - - // These are slow. - bool get(size_t x, size_t y) const{ return m_matrix->get(x, y); } - void set(size_t x, size_t y, bool set){ m_matrix->set(x, y, set); } - - PackedBinaryMatrix submatrix(size_t x, size_t y, size_t width, size_t height) const{ return m_matrix->submatrix(x, y, width, height); } - -public: - PackedBinaryMatrix(std::unique_ptr native) - : m_matrix(std::move(native)) - {} - - operator const Kernels::PackedBinaryMatrix_IB&() const{ return *m_matrix; } - operator Kernels::PackedBinaryMatrix_IB&() { return *m_matrix; } - -private: - std::unique_ptr m_matrix; -}; - - - - - -} -#endif +/* Binary Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_BinaryImage_H +#define PokemonAutomation_CommonFramework_BinaryImage_H + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ + +// A wrapper class of the packed binary matrix base class `Kernels::PackedBinaryMatrix_IB`. +// Those binary matrices are memory-efficient: each binary element is stored as just one bit in memory. +// They are mainly used by the Waterfill algorithm. +// See the comments of `PackedBinaryMatrix_IB` for more implementation details. +// +// This wrapper is useful in making the usage of matrix as a locally-defined class: you can use it like +// `PackedBinaryMatrix matrix;` +// Otherwise, because of +// `PackedBinaryMatrix_IB` being polymorphic, we have to write explictly +// `std::unique_ptr` to define a matrix. +class PackedBinaryMatrix{ +public: + // Rule of 5 + PackedBinaryMatrix(PackedBinaryMatrix&& x) : m_matrix(std::move(x.m_matrix)) {} + void operator=(PackedBinaryMatrix&& x){ m_matrix = std::move(x.m_matrix); } +// PackedBinaryMatrix(const PackedBinaryMatrix& x) : m_matrix(x.m_matrix->clone()) {} +// void operator=(const PackedBinaryMatrix& x){ m_matrix = x.m_matrix->clone(); } + + // Don't allow implicit copying. + PackedBinaryMatrix copy() const{ return m_matrix->clone(); }; + +public: + // Construction + PackedBinaryMatrix(); + PackedBinaryMatrix(size_t width, size_t height); + + Kernels::BinaryMatrixType type() const{ return m_matrix->type(); } + + void clear(){ m_matrix->clear(); } + + // Zero the entire matrix. + void set_zero(){ return m_matrix->set_zero(); } + + // Set entire matrix to ones. + void set_ones(){ return m_matrix->set_ones(); } + + // Invert all bits. + void invert(){ return m_matrix->invert(); } + + // Bitwise with another matrix. Dimensions must be the same! + void operator^=(const PackedBinaryMatrix& x){ *m_matrix ^= *x.m_matrix; } + void operator|=(const PackedBinaryMatrix& x){ *m_matrix |= *x.m_matrix; } + void operator&=(const PackedBinaryMatrix& x){ *m_matrix &= *x.m_matrix; } + + // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". + std::string dump() const{ return m_matrix->dump(); } + // Print part of max as 0s and 1s. Rows are ended with "\n". + std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const{ return m_matrix->dump(min_x, min_y, max_x, max_y); } + +public: + size_t width() const{ return m_matrix->width(); } + size_t height() const{ return m_matrix->height(); } + + // These are slow. + bool get(size_t x, size_t y) const{ return m_matrix->get(x, y); } + void set(size_t x, size_t y, bool set){ m_matrix->set(x, y, set); } + + PackedBinaryMatrix submatrix(size_t x, size_t y, size_t width, size_t height) const{ return m_matrix->submatrix(x, y, width, height); } + +public: + PackedBinaryMatrix(std::unique_ptr native) + : m_matrix(std::move(native)) + {} + + operator const Kernels::PackedBinaryMatrix_IB&() const{ return *m_matrix; } + operator Kernels::PackedBinaryMatrix_IB&() { return *m_matrix; } + +private: + std::unique_ptr m_matrix; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.cpp b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.cpp index a0580c4be2..5fa802d666 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.cpp @@ -1,138 +1,138 @@ -/* Image (HSV 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "ImageViewRGB32.h" -#include "ImageViewHSV32.h" -#include "ImageHSV32.h" - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ - -struct ImageHSV32::Data{ - AlignedVector self; - - Data(size_t items) : self(items) {} -}; - - - -ImageHSV32::~ImageHSV32() = default; -ImageHSV32::ImageHSV32(ImageHSV32&& x) noexcept{ - *this = std::move(x); -} -ImageHSV32& ImageHSV32::operator=(ImageHSV32&& x) noexcept{ - if (this != &x){ - ImageViewHSV32::operator=(x); - m_data = std::move(x.m_data); - x.m_bytes_per_row = 0; - x.m_ptr = nullptr; - x.m_width = 0; - x.m_height = 0; - } - return *this; -} - -ImageHSV32::ImageHSV32() = default; - -ImageHSV32::ImageHSV32(size_t width, size_t height) - : ImageViewHSV32(width, height) - , m_data(CONSTRUCT_TOKEN, m_bytes_per_row / sizeof(uint32_t) * height) -{ - m_ptr = m_data->self.data(); -} - - -uint32_t hsv_to_rgb(uint32_t p){ - int r = (uint32_t(0xff) & (p >> 16)); - int g = (uint32_t(0xff) & (p >> 8)); - int b = (uint32_t(0xff) & p); - - int M = std::max(std::max(r, g), b); - int m = std::min(std::min(r, g), b); - - int delta = M - m; - - // cout << "r=" << r << " g=" << g << " b=" << b << endl; - // cout << "M=" << M << " m=" << m << " delta=" << delta << endl; - - int S = 0; - if (M > 0){ - S = std::min(std::max(255 - (m*255 + M/2)/M, 0), 255); - } - - int V = M; - - double Hf = 0; - if (delta > 0){ - if (M == r){ - Hf = fmod((g - b)/(double)delta, 6.0); - }else if (M == g){ - Hf = (b - r)/(double)delta + 2.0; - }else{ - Hf = (r - g)/(double)delta + 4.0; - } - } - // cout << "H standard = " << Hf * 60.0 << endl; - // This Hf * 60.0 is the standard H value, which ranges in [0, 360). - // To hold it in a uint8, need to convert its range to [0, 255] - int H = std::max(int(Hf * 256.0 / 6.0 + 0.5) % 256, 0); - // cout << "H=" << H << ", S=" << S << ", M=" << M << endl; - - return (p & 0xff000000) | - ((uint32_t)(uint8_t)H << 16) | - ((uint32_t)(uint8_t)S << 8) | - (uint8_t)V; -} - - -ImageHSV32::ImageHSV32(const ImageViewRGB32& image) - : ImageViewHSV32(image.width(), image.height()) - , m_data(CONSTRUCT_TOKEN, m_bytes_per_row / sizeof(uint32_t) * m_height) -{ - m_ptr = m_data->self.data(); - - // { - // // XXX - // // auto p = combine_rgb(173,238,112); - // auto p = combine_rgb(200,255,133); - // auto p2 = hsv_to_rgb(p); - // auto h = (p2 & 0x00ff0000) >> 16; - // auto s = (p2 & 0x0000ff00) >> 8; - // auto v = (p2 & 0x000000ff); - // cout << "h " << h << " s " << s << " v " << v << endl; - // exit(0); - // } - - size_t width = image.width(); - size_t height = image.height(); - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - uint32_t p = image.pixel(x, y); - - this->pixel(x, y) = hsv_to_rgb(p); - } - } -} - - - - - - - -} +/* Image (HSV 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "ImageViewRGB32.h" +#include "ImageViewHSV32.h" +#include "ImageHSV32.h" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ + +struct ImageHSV32::Data{ + AlignedVector self; + + Data(size_t items) : self(items) {} +}; + + + +ImageHSV32::~ImageHSV32() = default; +ImageHSV32::ImageHSV32(ImageHSV32&& x) noexcept{ + *this = std::move(x); +} +ImageHSV32& ImageHSV32::operator=(ImageHSV32&& x) noexcept{ + if (this != &x){ + ImageViewHSV32::operator=(x); + m_data = std::move(x.m_data); + x.m_bytes_per_row = 0; + x.m_ptr = nullptr; + x.m_width = 0; + x.m_height = 0; + } + return *this; +} + +ImageHSV32::ImageHSV32() = default; + +ImageHSV32::ImageHSV32(size_t width, size_t height) + : ImageViewHSV32(width, height) + , m_data(CONSTRUCT_TOKEN, m_bytes_per_row / sizeof(uint32_t) * height) +{ + m_ptr = m_data->self.data(); +} + + +uint32_t hsv_to_rgb(uint32_t p){ + int r = (uint32_t(0xff) & (p >> 16)); + int g = (uint32_t(0xff) & (p >> 8)); + int b = (uint32_t(0xff) & p); + + int M = std::max(std::max(r, g), b); + int m = std::min(std::min(r, g), b); + + int delta = M - m; + + // cout << "r=" << r << " g=" << g << " b=" << b << endl; + // cout << "M=" << M << " m=" << m << " delta=" << delta << endl; + + int S = 0; + if (M > 0){ + S = std::min(std::max(255 - (m*255 + M/2)/M, 0), 255); + } + + int V = M; + + double Hf = 0; + if (delta > 0){ + if (M == r){ + Hf = fmod((g - b)/(double)delta, 6.0); + }else if (M == g){ + Hf = (b - r)/(double)delta + 2.0; + }else{ + Hf = (r - g)/(double)delta + 4.0; + } + } + // cout << "H standard = " << Hf * 60.0 << endl; + // This Hf * 60.0 is the standard H value, which ranges in [0, 360). + // To hold it in a uint8, need to convert its range to [0, 255] + int H = std::max(int(Hf * 256.0 / 6.0 + 0.5) % 256, 0); + // cout << "H=" << H << ", S=" << S << ", M=" << M << endl; + + return (p & 0xff000000) | + ((uint32_t)(uint8_t)H << 16) | + ((uint32_t)(uint8_t)S << 8) | + (uint8_t)V; +} + + +ImageHSV32::ImageHSV32(const ImageViewRGB32& image) + : ImageViewHSV32(image.width(), image.height()) + , m_data(CONSTRUCT_TOKEN, m_bytes_per_row / sizeof(uint32_t) * m_height) +{ + m_ptr = m_data->self.data(); + + // { + // // XXX + // // auto p = combine_rgb(173,238,112); + // auto p = combine_rgb(200,255,133); + // auto p2 = hsv_to_rgb(p); + // auto h = (p2 & 0x00ff0000) >> 16; + // auto s = (p2 & 0x0000ff00) >> 8; + // auto v = (p2 & 0x000000ff); + // cout << "h " << h << " s " << s << " v " << v << endl; + // exit(0); + // } + + size_t width = image.width(); + size_t height = image.height(); + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + uint32_t p = image.pixel(x, y); + + this->pixel(x, y) = hsv_to_rgb(p); + } + } +} + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.h b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.h index 0721bdfb3f..8acefecf64 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.h +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageHSV32.h @@ -1,77 +1,77 @@ -/* Image (HSV 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageHSV32_H -#define PokemonAutomation_CommonFramework_ImageHSV32_H - -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "ImageViewHSV32.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; - - -class ImageHSV32 : public ImageViewHSV32{ -public: -public: - ~ImageHSV32(); - ImageHSV32(ImageHSV32&& x) noexcept; - ImageHSV32& operator=(ImageHSV32&& x) noexcept; -private: - // Disable these to prevent implicit copying. - ImageHSV32(const ImageHSV32& x) = delete; - void operator=(const ImageHSV32& x) = delete; - - -public: - ImageHSV32(); - ImageHSV32(size_t width, size_t height); - - // Fill the entire image with the specified pixel. - using ImageViewPlanar32::fill; - - -public: - // Returns true if this image is valid. (non-null and non-zero dimensions) - using ImageViewHSV32::operator bool; - - const uint32_t* data() const{ return m_ptr; } - uint32_t* data(){ return m_ptr; } - - using ImageViewHSV32::bytes_per_row; - using ImageViewHSV32::width; - using ImageViewHSV32::height; - - // Direct Pixel Access - PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ - return ImageViewPlanar32::pixel(x, y); - } - PA_FORCE_INLINE uint32_t& pixel(size_t x, size_t y){ - return ImageViewPlanar32::pixel(x, y); - } - -public: - using ImageViewHSV32::sub_image; - - -public: - // HSV32 - - explicit ImageHSV32(const ImageViewRGB32& image); - - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Image (HSV 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageHSV32_H +#define PokemonAutomation_CommonFramework_ImageHSV32_H + +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "ImageViewHSV32.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; + + +class ImageHSV32 : public ImageViewHSV32{ +public: +public: + ~ImageHSV32(); + ImageHSV32(ImageHSV32&& x) noexcept; + ImageHSV32& operator=(ImageHSV32&& x) noexcept; +private: + // Disable these to prevent implicit copying. + ImageHSV32(const ImageHSV32& x) = delete; + void operator=(const ImageHSV32& x) = delete; + + +public: + ImageHSV32(); + ImageHSV32(size_t width, size_t height); + + // Fill the entire image with the specified pixel. + using ImageViewPlanar32::fill; + + +public: + // Returns true if this image is valid. (non-null and non-zero dimensions) + using ImageViewHSV32::operator bool; + + const uint32_t* data() const{ return m_ptr; } + uint32_t* data(){ return m_ptr; } + + using ImageViewHSV32::bytes_per_row; + using ImageViewHSV32::width; + using ImageViewHSV32::height; + + // Direct Pixel Access + PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ + return ImageViewPlanar32::pixel(x, y); + } + PA_FORCE_INLINE uint32_t& pixel(size_t x, size_t y){ + return ImageViewPlanar32::pixel(x, y); + } + +public: + using ImageViewHSV32::sub_image; + + +public: + // HSV32 + + explicit ImageHSV32(const ImageViewRGB32& image); + + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.cpp b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.cpp index 348574cc9f..7bdbe67086 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.cpp @@ -1,97 +1,97 @@ -/* Image (RGB 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "ImageViewRGB32.h" -#include "ImageRGB32.h" - -#include - - -namespace PokemonAutomation{ - -struct ImageRGB32::Data{ - AlignedVector self; - QImage qimage; - - Data(size_t items) : self(items) {} - Data(QImage image) : qimage(std::move(image)) {} -}; - - - -ImageRGB32::~ImageRGB32() = default; -ImageRGB32::ImageRGB32(ImageRGB32&& x) noexcept{ - *this = std::move(x); -} -ImageRGB32& ImageRGB32::operator=(ImageRGB32&& x) noexcept{ - if (this != &x){ - ImageViewRGB32::operator=(x); - m_data = std::move(x.m_data); - x.m_bytes_per_row = 0; - x.m_ptr = nullptr; - x.m_width = 0; - x.m_height = 0; - } - return *this; -} -#if 0 -ImageRGB32::ImageRGB32(const ImageRGB32& x){ - *this = copy(); -} -void ImageRGB32::operator=(const ImageRGB32& x){ - *this = copy(); -} -#endif - -ImageRGB32::ImageRGB32() = default; - -ImageRGB32::ImageRGB32(size_t width, size_t height) - : ImageViewRGB32(width, height) - , m_data(CONSTRUCT_TOKEN, m_bytes_per_row / sizeof(uint32_t) * height) -{ - m_ptr = m_data->self.data(); -} -ImageRGB32::ImageRGB32(const std::string& filename){ - QImage image(QString::fromStdString(filename)); - if (image.isNull()){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to open image.", filename); - } - if (image.format() != QImage::Format_RGB32 && image.format() != QImage::Format_ARGB32){ - image = image.convertToFormat(QImage::Format_ARGB32); - } - *this = std::move(image); -} - - - - -ImageRGB32::ImageRGB32(QImage image){ - if (image.isNull()){ - return; - } - QImage::Format format = image.format(); - if (format == QImage::Format_ARGB32_Premultiplied){ - image = image.convertToFormat(QImage::Format_ARGB32); - }else if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ - std::cout << "Non standard QImage format: " + std::to_string((int)format) << std::endl; - // image = image.convertToFormat(QImage::Format_ARGB32); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid QImage format: " + std::to_string((int)format)); - } - m_width = image.width(); - m_height = image.height(); - m_bytes_per_row = image.bytesPerLine(); - m_ptr = (uint32_t*)image.bits(); - m_data.reset(std::move(image)); -} - - - -} +/* Image (RGB 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "ImageViewRGB32.h" +#include "ImageRGB32.h" + +#include + + +namespace PokemonAutomation{ + +struct ImageRGB32::Data{ + AlignedVector self; + QImage qimage; + + Data(size_t items) : self(items) {} + Data(QImage image) : qimage(std::move(image)) {} +}; + + + +ImageRGB32::~ImageRGB32() = default; +ImageRGB32::ImageRGB32(ImageRGB32&& x) noexcept{ + *this = std::move(x); +} +ImageRGB32& ImageRGB32::operator=(ImageRGB32&& x) noexcept{ + if (this != &x){ + ImageViewRGB32::operator=(x); + m_data = std::move(x.m_data); + x.m_bytes_per_row = 0; + x.m_ptr = nullptr; + x.m_width = 0; + x.m_height = 0; + } + return *this; +} +#if 0 +ImageRGB32::ImageRGB32(const ImageRGB32& x){ + *this = copy(); +} +void ImageRGB32::operator=(const ImageRGB32& x){ + *this = copy(); +} +#endif + +ImageRGB32::ImageRGB32() = default; + +ImageRGB32::ImageRGB32(size_t width, size_t height) + : ImageViewRGB32(width, height) + , m_data(CONSTRUCT_TOKEN, m_bytes_per_row / sizeof(uint32_t) * height) +{ + m_ptr = m_data->self.data(); +} +ImageRGB32::ImageRGB32(const std::string& filename){ + QImage image(QString::fromStdString(filename)); + if (image.isNull()){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to open image.", filename); + } + if (image.format() != QImage::Format_RGB32 && image.format() != QImage::Format_ARGB32){ + image = image.convertToFormat(QImage::Format_ARGB32); + } + *this = std::move(image); +} + + + + +ImageRGB32::ImageRGB32(QImage image){ + if (image.isNull()){ + return; + } + QImage::Format format = image.format(); + if (format == QImage::Format_ARGB32_Premultiplied){ + image = image.convertToFormat(QImage::Format_ARGB32); + }else if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ + std::cout << "Non standard QImage format: " + std::to_string((int)format) << std::endl; + // image = image.convertToFormat(QImage::Format_ARGB32); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid QImage format: " + std::to_string((int)format)); + } + m_width = image.width(); + m_height = image.height(); + m_bytes_per_row = image.bytesPerLine(); + m_ptr = (uint32_t*)image.bits(); + m_data.reset(std::move(image)); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.h b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.h index 8d6899e401..bb354a3e4a 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.h +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageRGB32.h @@ -1,82 +1,82 @@ -/* Image (RGB 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageRGB32_H -#define PokemonAutomation_CommonFramework_ImageRGB32_H - -#include -#include "Common/Cpp/Containers/Pimpl.h" -#include "ImageViewRGB32.h" - -namespace PokemonAutomation{ - - -class ImageRGB32 : public ImageViewRGB32{ -public: - ~ImageRGB32(); - ImageRGB32(ImageRGB32&& x) noexcept; - ImageRGB32& operator=(ImageRGB32&& x) noexcept; -private: - // Disable these to prevent implicit copying. - ImageRGB32(const ImageRGB32& x) = delete; - void operator=(const ImageRGB32& x) = delete; - - -public: - ImageRGB32(); - ImageRGB32(size_t width, size_t height); - explicit ImageRGB32(const std::string& filename); - - // Fill the entire image with the specified pixel. - using ImageViewPlanar32::fill; - - -public: - // Returns true if this image is valid. (non-null and non-zero dimensions) - using ImageViewRGB32::operator bool; - - const uint32_t* data() const{ return m_ptr; } - uint32_t* data(){ return m_ptr; } - - using ImageViewRGB32::bytes_per_row; - using ImageViewRGB32::width; - using ImageViewRGB32::height; - - // Direct Pixel Access - PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ - return ImageViewPlanar32::pixel(x, y); - } - PA_FORCE_INLINE uint32_t& pixel(size_t x, size_t y){ - return ImageViewPlanar32::pixel(x, y); - } - -public: - using ImageViewRGB32::sub_image; - - -public: - using ImageViewRGB32::save; - - -public: - // QImage - - ImageRGB32(QImage image); - using ImageViewRGB32::to_QImage_ref; - using ImageViewRGB32::to_QImage_owning; - using ImageViewRGB32::scaled_to_QImage; - - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Image (RGB 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageRGB32_H +#define PokemonAutomation_CommonFramework_ImageRGB32_H + +#include +#include "Common/Cpp/Containers/Pimpl.h" +#include "ImageViewRGB32.h" + +namespace PokemonAutomation{ + + +class ImageRGB32 : public ImageViewRGB32{ +public: + ~ImageRGB32(); + ImageRGB32(ImageRGB32&& x) noexcept; + ImageRGB32& operator=(ImageRGB32&& x) noexcept; +private: + // Disable these to prevent implicit copying. + ImageRGB32(const ImageRGB32& x) = delete; + void operator=(const ImageRGB32& x) = delete; + + +public: + ImageRGB32(); + ImageRGB32(size_t width, size_t height); + explicit ImageRGB32(const std::string& filename); + + // Fill the entire image with the specified pixel. + using ImageViewPlanar32::fill; + + +public: + // Returns true if this image is valid. (non-null and non-zero dimensions) + using ImageViewRGB32::operator bool; + + const uint32_t* data() const{ return m_ptr; } + uint32_t* data(){ return m_ptr; } + + using ImageViewRGB32::bytes_per_row; + using ImageViewRGB32::width; + using ImageViewRGB32::height; + + // Direct Pixel Access + PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ + return ImageViewPlanar32::pixel(x, y); + } + PA_FORCE_INLINE uint32_t& pixel(size_t x, size_t y){ + return ImageViewPlanar32::pixel(x, y); + } + +public: + using ImageViewRGB32::sub_image; + + +public: + using ImageViewRGB32::save; + + +public: + // QImage + + ImageRGB32(QImage image); + using ImageViewRGB32::to_QImage_ref; + using ImageViewRGB32::to_QImage_owning; + using ImageViewRGB32::scaled_to_QImage; + + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.cpp b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.cpp index eafb0ef964..89aa0321cd 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.cpp @@ -1,46 +1,46 @@ -/* Image HSV (HSV 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "ImageHSV32.h" -#include "ImageViewHSV32.h" - -namespace PokemonAutomation{ - - - -ImageHSV32 ImageViewHSV32::copy() const{ - if (m_ptr == nullptr){ - return ImageHSV32(); - } - ImageHSV32 ret(m_width, m_height); - if (ret.m_bytes_per_row == m_bytes_per_row){ - memcpy( - ret.m_ptr, m_ptr, - (m_height - 1) * m_bytes_per_row + m_width * sizeof(uint32_t) - ); - }else{ - char* dst = (char*)ret.m_ptr; - const char* src = (const char*)m_ptr; - for (size_t c = 0; c < m_height; c++){ - memcpy(dst, src, m_width * sizeof(uint32_t)); - dst += ret.m_bytes_per_row; - src += m_bytes_per_row; - } - } - return ret; -} - - - - - - - - - -} +/* Image HSV (HSV 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "ImageHSV32.h" +#include "ImageViewHSV32.h" + +namespace PokemonAutomation{ + + + +ImageHSV32 ImageViewHSV32::copy() const{ + if (m_ptr == nullptr){ + return ImageHSV32(); + } + ImageHSV32 ret(m_width, m_height); + if (ret.m_bytes_per_row == m_bytes_per_row){ + memcpy( + ret.m_ptr, m_ptr, + (m_height - 1) * m_bytes_per_row + m_width * sizeof(uint32_t) + ); + }else{ + char* dst = (char*)ret.m_ptr; + const char* src = (const char*)m_ptr; + for (size_t c = 0; c < m_height; c++){ + memcpy(dst, src, m_width * sizeof(uint32_t)); + dst += ret.m_bytes_per_row; + src += m_bytes_per_row; + } + } + return ret; +} + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.h b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.h index 95319984da..1dc1ce3157 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.h +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewHSV32.h @@ -1,51 +1,51 @@ -/* Image View (HSV 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageViewHSV32_H -#define PokemonAutomation_CommonFramework_ImageViewHSV32_H - -#include -#include "ImageViewPlanar32.h" - -namespace PokemonAutomation{ - - -class ImageHSV32; - - -class ImageViewHSV32 : public ImageViewPlanar32{ -public: - using ImageViewPlanar32::ImageViewPlanar32; - -public: - using ImageViewPlanar32::operator bool; - - using ImageViewPlanar32::data; - using ImageViewPlanar32::bytes_per_row; - using ImageViewPlanar32::width; - using ImageViewPlanar32::height; - - using ImageViewPlanar32::pixel; - - ImageViewHSV32 sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const{ - return ImageViewPlanar32::sub_image(min_x, min_y, width, height); - } - -public: - ImageHSV32 copy() const; - -private: - ImageViewHSV32(const ImageViewPlanar32& x) - : ImageViewPlanar32(x) - {} -}; - - - - - -} -#endif +/* Image View (HSV 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageViewHSV32_H +#define PokemonAutomation_CommonFramework_ImageViewHSV32_H + +#include +#include "ImageViewPlanar32.h" + +namespace PokemonAutomation{ + + +class ImageHSV32; + + +class ImageViewHSV32 : public ImageViewPlanar32{ +public: + using ImageViewPlanar32::ImageViewPlanar32; + +public: + using ImageViewPlanar32::operator bool; + + using ImageViewPlanar32::data; + using ImageViewPlanar32::bytes_per_row; + using ImageViewPlanar32::width; + using ImageViewPlanar32::height; + + using ImageViewPlanar32::pixel; + + ImageViewHSV32 sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const{ + return ImageViewPlanar32::sub_image(min_x, min_y, width, height); + } + +public: + ImageHSV32 copy() const; + +private: + ImageViewHSV32(const ImageViewPlanar32& x) + : ImageViewPlanar32(x) + {} +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.cpp b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.cpp index 4f65b07ec0..6897dcbd82 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.cpp @@ -1,61 +1,61 @@ -/* Image Reference (Planar 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "ImageViewPlanar32.h" - -namespace PokemonAutomation{ - - - -ImageViewPlanar32 ImageViewPlanar32::sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const{ - if (min_x >= m_width || min_y >= m_height){ - return ImageViewPlanar32(); - } - width = std::min(width, m_width - min_x); - height = std::min(height, m_height - min_y); - return ImageViewPlanar32( - (uint32_t*)((char*)m_ptr + min_y * m_bytes_per_row) + min_x, - m_bytes_per_row, - width, height - ); -} - - -void ImageViewPlanar32::fill(uint32_t pixel){ - size_t width = m_width; - size_t height = m_height; - uint32_t* dst = m_ptr; - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - dst[c] = pixel; - } - dst = (uint32_t*)((char*)dst + m_bytes_per_row); - } -} -void ImageViewPlanar32::copy_from(const ImageViewPlanar32& source){ - if (m_bytes_per_row == source.m_bytes_per_row){ - memcpy( - m_ptr, source.m_ptr, - (m_height - 1) * m_bytes_per_row + m_width * sizeof(uint32_t) - ); - }else{ - char* dst = (char*)m_ptr; - const char* src = (const char*)source.m_ptr; - for (size_t c = 0; c < m_height; c++){ - memcpy(dst, src, m_width * sizeof(uint32_t)); - dst += m_bytes_per_row; - src += source.m_bytes_per_row; - } - } -} - - - - - -} +/* Image Reference (Planar 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "ImageViewPlanar32.h" + +namespace PokemonAutomation{ + + + +ImageViewPlanar32 ImageViewPlanar32::sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const{ + if (min_x >= m_width || min_y >= m_height){ + return ImageViewPlanar32(); + } + width = std::min(width, m_width - min_x); + height = std::min(height, m_height - min_y); + return ImageViewPlanar32( + (uint32_t*)((char*)m_ptr + min_y * m_bytes_per_row) + min_x, + m_bytes_per_row, + width, height + ); +} + + +void ImageViewPlanar32::fill(uint32_t pixel){ + size_t width = m_width; + size_t height = m_height; + uint32_t* dst = m_ptr; + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + dst[c] = pixel; + } + dst = (uint32_t*)((char*)dst + m_bytes_per_row); + } +} +void ImageViewPlanar32::copy_from(const ImageViewPlanar32& source){ + if (m_bytes_per_row == source.m_bytes_per_row){ + memcpy( + m_ptr, source.m_ptr, + (m_height - 1) * m_bytes_per_row + m_width * sizeof(uint32_t) + ); + }else{ + char* dst = (char*)m_ptr; + const char* src = (const char*)source.m_ptr; + for (size_t c = 0; c < m_height; c++){ + memcpy(dst, src, m_width * sizeof(uint32_t)); + dst += m_bytes_per_row; + src += source.m_bytes_per_row; + } + } +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.h b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.h index 3c03c9c6e8..c5af979ae2 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.h +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewPlanar32.h @@ -1,73 +1,73 @@ -/* Image Reference (Planar 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageViewPlanar32_H -#define PokemonAutomation_CommonFramework_ImageViewPlanar32_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ - - - -class ImageViewPlanar32{ -public: - PA_FORCE_INLINE ImageViewPlanar32() = default; - PA_FORCE_INLINE ImageViewPlanar32(size_t width, size_t height) - : m_width(width), m_height(height) - , m_bytes_per_row((width * sizeof(uint32_t) + PA_ALIGNMENT - 1) & ~(size_t)(PA_ALIGNMENT - 1)) - {} - PA_FORCE_INLINE ImageViewPlanar32(uint32_t* ptr, size_t bytes_per_row, size_t width, size_t height) - : m_width(width), m_height(height) - , m_bytes_per_row(bytes_per_row), m_ptr(ptr) - {} - - -public: - // Returns true if this image is valid. (non-null and non-zero dimensions) - PA_FORCE_INLINE explicit operator bool() const{ return m_ptr != nullptr; } - - PA_FORCE_INLINE const uint32_t* data () const{ return m_ptr; } - PA_FORCE_INLINE size_t bytes_per_row () const{ return m_bytes_per_row; } - PA_FORCE_INLINE size_t width () const{ return m_width; } - PA_FORCE_INLINE size_t height () const{ return m_height; } - PA_FORCE_INLINE size_t total_pixels () const{ return m_width * m_height; } - - // Direct Pixel Access - PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ - return *(const uint32_t*)((const char*)m_ptr + x * sizeof(uint32_t) + y * m_bytes_per_row); - } - - ImageViewPlanar32 sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const; - - -protected: - // Helpers for child classes that allow modifications. - PA_FORCE_INLINE uint32_t& pixel(size_t x, size_t y){ - return *(uint32_t*)((char*)m_ptr + x * sizeof(uint32_t) + y * m_bytes_per_row); - } - - // Fill the entire image with the specified pixel. - void fill(uint32_t pixel); - - // Copy the contents of the "source" into this object. The dimensions must match. - void copy_from(const ImageViewPlanar32& source); - - -protected: - size_t m_width = 0; - size_t m_height = 0; - size_t m_bytes_per_row = 0; - uint32_t* m_ptr = nullptr; -}; - - - - - -} -#endif +/* Image Reference (Planar 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageViewPlanar32_H +#define PokemonAutomation_CommonFramework_ImageViewPlanar32_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ + + + +class ImageViewPlanar32{ +public: + PA_FORCE_INLINE ImageViewPlanar32() = default; + PA_FORCE_INLINE ImageViewPlanar32(size_t width, size_t height) + : m_width(width), m_height(height) + , m_bytes_per_row((width * sizeof(uint32_t) + PA_ALIGNMENT - 1) & ~(size_t)(PA_ALIGNMENT - 1)) + {} + PA_FORCE_INLINE ImageViewPlanar32(uint32_t* ptr, size_t bytes_per_row, size_t width, size_t height) + : m_width(width), m_height(height) + , m_bytes_per_row(bytes_per_row), m_ptr(ptr) + {} + + +public: + // Returns true if this image is valid. (non-null and non-zero dimensions) + PA_FORCE_INLINE explicit operator bool() const{ return m_ptr != nullptr; } + + PA_FORCE_INLINE const uint32_t* data () const{ return m_ptr; } + PA_FORCE_INLINE size_t bytes_per_row () const{ return m_bytes_per_row; } + PA_FORCE_INLINE size_t width () const{ return m_width; } + PA_FORCE_INLINE size_t height () const{ return m_height; } + PA_FORCE_INLINE size_t total_pixels () const{ return m_width * m_height; } + + // Direct Pixel Access + PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ + return *(const uint32_t*)((const char*)m_ptr + x * sizeof(uint32_t) + y * m_bytes_per_row); + } + + ImageViewPlanar32 sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const; + + +protected: + // Helpers for child classes that allow modifications. + PA_FORCE_INLINE uint32_t& pixel(size_t x, size_t y){ + return *(uint32_t*)((char*)m_ptr + x * sizeof(uint32_t) + y * m_bytes_per_row); + } + + // Fill the entire image with the specified pixel. + void fill(uint32_t pixel); + + // Copy the contents of the "source" into this object. The dimensions must match. + void copy_from(const ImageViewPlanar32& source); + + +protected: + size_t m_width = 0; + size_t m_height = 0; + size_t m_bytes_per_row = 0; + uint32_t* m_ptr = nullptr; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.cpp b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.cpp index c2fc3b1266..563e3c17e8 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.cpp +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.cpp @@ -1,71 +1,71 @@ -/* Image View (RGB 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "ImageRGB32.h" -#include "ImageViewRGB32.h" - -namespace PokemonAutomation{ - - - - -ImageRGB32 ImageViewRGB32::copy() const{ - if (m_ptr == nullptr){ - return ImageRGB32(); - } - ImageRGB32 ret(m_width, m_height); - ret.copy_from(*this); - return ret; -} -bool ImageViewRGB32::save(const std::string& path) const{ - return to_QImage_ref().save(QString::fromStdString(path)); -} -ImageRGB32 ImageViewRGB32::scale_to(size_t width, size_t height) const{ - return scaled_to_QImage(width, height); -} - - - -ImageViewRGB32::ImageViewRGB32(const QImage& image){ - if (image.isNull()){ - return; - } - QImage::Format format = image.format(); - if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid QImage format."); - } - m_width = image.width(); - m_height = image.height(); - m_bytes_per_row = image.bytesPerLine(); - m_ptr = (uint32_t*)image.bits(); // Intentionally casting away const. It won't be modified. -} -QImage ImageViewRGB32::to_QImage_ref() const{ - return QImage((const uchar*)m_ptr, (int)m_width, (int)m_height, (int)m_bytes_per_row, QImage::Format_ARGB32); -} -QImage ImageViewRGB32::to_QImage_owning() const{ - return to_QImage_ref().copy(); -} -QImage ImageViewRGB32::scaled_to_QImage(size_t width, size_t height) const{ - QImage tmp((const uchar*)m_ptr, (int)m_width, (int)m_height, (int)m_bytes_per_row, QImage::Format_ARGB32); - if (m_width == width && m_height == height){ - return tmp.copy(); - } - return tmp.scaled((int)width, (int)height); -// return tmp.scaled((int)width, (int)height, Qt::IgnoreAspectRatio, Qt::TransformationMode::SmoothTransformation); -} -cv::Mat ImageViewRGB32::to_opencv_Mat() const{ - return cv::Mat{ static_cast(m_height), static_cast(m_width), CV_8UC4, (cv::Scalar*)m_ptr, m_bytes_per_row }; -} - - - - - - -} +/* Image View (RGB 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "ImageRGB32.h" +#include "ImageViewRGB32.h" + +namespace PokemonAutomation{ + + + + +ImageRGB32 ImageViewRGB32::copy() const{ + if (m_ptr == nullptr){ + return ImageRGB32(); + } + ImageRGB32 ret(m_width, m_height); + ret.copy_from(*this); + return ret; +} +bool ImageViewRGB32::save(const std::string& path) const{ + return to_QImage_ref().save(QString::fromStdString(path)); +} +ImageRGB32 ImageViewRGB32::scale_to(size_t width, size_t height) const{ + return scaled_to_QImage(width, height); +} + + + +ImageViewRGB32::ImageViewRGB32(const QImage& image){ + if (image.isNull()){ + return; + } + QImage::Format format = image.format(); + if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid QImage format."); + } + m_width = image.width(); + m_height = image.height(); + m_bytes_per_row = image.bytesPerLine(); + m_ptr = (uint32_t*)image.bits(); // Intentionally casting away const. It won't be modified. +} +QImage ImageViewRGB32::to_QImage_ref() const{ + return QImage((const uchar*)m_ptr, (int)m_width, (int)m_height, (int)m_bytes_per_row, QImage::Format_ARGB32); +} +QImage ImageViewRGB32::to_QImage_owning() const{ + return to_QImage_ref().copy(); +} +QImage ImageViewRGB32::scaled_to_QImage(size_t width, size_t height) const{ + QImage tmp((const uchar*)m_ptr, (int)m_width, (int)m_height, (int)m_bytes_per_row, QImage::Format_ARGB32); + if (m_width == width && m_height == height){ + return tmp.copy(); + } + return tmp.scaled((int)width, (int)height); +// return tmp.scaled((int)width, (int)height, Qt::IgnoreAspectRatio, Qt::TransformationMode::SmoothTransformation); +} +cv::Mat ImageViewRGB32::to_opencv_Mat() const{ + return cv::Mat{ static_cast(m_height), static_cast(m_width), CV_8UC4, (cv::Scalar*)m_ptr, m_bytes_per_row }; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.h b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.h index e9da7a2611..613260bfdf 100644 --- a/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.h +++ b/SerialPrograms/Source/CommonFramework/ImageTypes/ImageViewRGB32.h @@ -1,73 +1,73 @@ -/* Image View (RGB 32) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ImageViewRGB32_H -#define PokemonAutomation_CommonFramework_ImageViewRGB32_H - -#include -#include "ImageViewPlanar32.h" - -class QImage; -namespace cv{ - class Mat; -} - -namespace PokemonAutomation{ - - -class ImageRGB32; - - -class ImageViewRGB32 : public ImageViewPlanar32{ -public: - using ImageViewPlanar32::ImageViewPlanar32; - -public: - // Returns true if this image is valid. (non-null and non-zero dimensions) - using ImageViewPlanar32::operator bool; - - using ImageViewPlanar32::data; - using ImageViewPlanar32::bytes_per_row; - using ImageViewPlanar32::width; - using ImageViewPlanar32::height; - using ImageViewPlanar32::total_pixels; - - // Direct Pixel Access - PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ - return ImageViewPlanar32::pixel(x, y); - } - - PA_FORCE_INLINE ImageViewRGB32 sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const{ - return ImageViewPlanar32::sub_image(min_x, min_y, width, height); - } - -public: - ImageRGB32 copy() const; - bool save(const std::string& path) const; - ImageRGB32 scale_to(size_t width, size_t height) const; - -public: - // QImage - - ImageViewRGB32(const QImage& image); - QImage to_QImage_ref() const; // Return a shallow copy-on-write reference that points to this buffer. (fast) - QImage to_QImage_owning() const; // Return a copy that owns its own buffer. (slow) - QImage scaled_to_QImage(size_t width, size_t height) const; - - cv::Mat to_opencv_Mat() const; - -private: - PA_FORCE_INLINE ImageViewRGB32(const ImageViewPlanar32& x) - : ImageViewPlanar32(x) - {} -}; - - - - - -} -#endif +/* Image View (RGB 32) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ImageViewRGB32_H +#define PokemonAutomation_CommonFramework_ImageViewRGB32_H + +#include +#include "ImageViewPlanar32.h" + +class QImage; +namespace cv{ + class Mat; +} + +namespace PokemonAutomation{ + + +class ImageRGB32; + + +class ImageViewRGB32 : public ImageViewPlanar32{ +public: + using ImageViewPlanar32::ImageViewPlanar32; + +public: + // Returns true if this image is valid. (non-null and non-zero dimensions) + using ImageViewPlanar32::operator bool; + + using ImageViewPlanar32::data; + using ImageViewPlanar32::bytes_per_row; + using ImageViewPlanar32::width; + using ImageViewPlanar32::height; + using ImageViewPlanar32::total_pixels; + + // Direct Pixel Access + PA_FORCE_INLINE uint32_t pixel(size_t x, size_t y) const{ + return ImageViewPlanar32::pixel(x, y); + } + + PA_FORCE_INLINE ImageViewRGB32 sub_image(size_t min_x, size_t min_y, size_t width, size_t height) const{ + return ImageViewPlanar32::sub_image(min_x, min_y, width, height); + } + +public: + ImageRGB32 copy() const; + bool save(const std::string& path) const; + ImageRGB32 scale_to(size_t width, size_t height) const; + +public: + // QImage + + ImageViewRGB32(const QImage& image); + QImage to_QImage_ref() const; // Return a shallow copy-on-write reference that points to this buffer. (fast) + QImage to_QImage_owning() const; // Return a copy that owns its own buffer. (slow) + QImage scaled_to_QImage(size_t width, size_t height) const; + + cv::Mat to_opencv_Mat() const; + +private: + PA_FORCE_INLINE ImageViewRGB32(const ImageViewPlanar32& x) + : ImageViewPlanar32(x) + {} +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Language.cpp b/SerialPrograms/Source/CommonFramework/Language.cpp index c32a04d2f7..a7980d4967 100644 --- a/SerialPrograms/Source/CommonFramework/Language.cpp +++ b/SerialPrograms/Source/CommonFramework/Language.cpp @@ -1,88 +1,88 @@ -/* Language - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Language.h" - -namespace PokemonAutomation{ - - - -const std::map LANGUAGE_DATA{ - {Language::None, {"none", "None", 0}}, - {Language::English, {"eng", "English", 1. / 5}}, - {Language::Japanese, {"jpn", "Japanese", 1. / 10}}, - {Language::Spanish, {"spa", "Spanish", 1. / 5}}, - {Language::French, {"fra", "French", 1. / 5}}, - {Language::German, {"deu", "German", 1. / 5}}, - {Language::Italian, {"ita", "Italian", 1. / 5}}, - {Language::Korean, {"kor", "Korean", 1. / 10}}, - {Language::ChineseSimplified, {"chi_sim", "Chinese (Simplified)", 1. / 100}}, - {Language::ChineseTraditional, {"chi_tra", "Chinese (Traditional)", 1. / 100}}, -}; - - - -bool LanguageSet::operator[](Language language) const{ - return m_set.find(language) != m_set.end(); -} -void LanguageSet::operator+=(Language language){ - m_set.insert(language); -} -void LanguageSet::operator-=(Language language){ - m_set.erase(language); -} -void LanguageSet::operator+=(const LanguageSet& set){ - for (Language language : set.m_set){ - m_set.insert(language); - } -} -void LanguageSet::operator-=(const LanguageSet& set){ - for (Language language : set.m_set){ - m_set.erase(language); - } -} - - - - - - -const LanguageData& language_data(Language language){ - auto iter = LANGUAGE_DATA.find(language); - if (iter == LANGUAGE_DATA.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Language Enum: " + std::to_string((int)language) - ); - } - return iter->second; -} - -std::map build_code_to_enum_map(){ - std::map ret; - for (auto& iter : LANGUAGE_DATA){ - ret.emplace(iter.second.code, iter.first); - } - return ret; -} -const std::map CODE_TO_ENUM = build_code_to_enum_map(); - - -Language language_code_to_enum(const std::string& language){ - auto iter = CODE_TO_ENUM.find(language); - if (iter == CODE_TO_ENUM.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Unknown Language Code: " + language - ); - } - return iter->second; -} - - -} +/* Language + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Language.h" + +namespace PokemonAutomation{ + + + +const std::map LANGUAGE_DATA{ + {Language::None, {"none", "None", 0}}, + {Language::English, {"eng", "English", 1. / 5}}, + {Language::Japanese, {"jpn", "Japanese", 1. / 10}}, + {Language::Spanish, {"spa", "Spanish", 1. / 5}}, + {Language::French, {"fra", "French", 1. / 5}}, + {Language::German, {"deu", "German", 1. / 5}}, + {Language::Italian, {"ita", "Italian", 1. / 5}}, + {Language::Korean, {"kor", "Korean", 1. / 10}}, + {Language::ChineseSimplified, {"chi_sim", "Chinese (Simplified)", 1. / 100}}, + {Language::ChineseTraditional, {"chi_tra", "Chinese (Traditional)", 1. / 100}}, +}; + + + +bool LanguageSet::operator[](Language language) const{ + return m_set.find(language) != m_set.end(); +} +void LanguageSet::operator+=(Language language){ + m_set.insert(language); +} +void LanguageSet::operator-=(Language language){ + m_set.erase(language); +} +void LanguageSet::operator+=(const LanguageSet& set){ + for (Language language : set.m_set){ + m_set.insert(language); + } +} +void LanguageSet::operator-=(const LanguageSet& set){ + for (Language language : set.m_set){ + m_set.erase(language); + } +} + + + + + + +const LanguageData& language_data(Language language){ + auto iter = LANGUAGE_DATA.find(language); + if (iter == LANGUAGE_DATA.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Language Enum: " + std::to_string((int)language) + ); + } + return iter->second; +} + +std::map build_code_to_enum_map(){ + std::map ret; + for (auto& iter : LANGUAGE_DATA){ + ret.emplace(iter.second.code, iter.first); + } + return ret; +} +const std::map CODE_TO_ENUM = build_code_to_enum_map(); + + +Language language_code_to_enum(const std::string& language){ + auto iter = CODE_TO_ENUM.find(language); + if (iter == CODE_TO_ENUM.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Unknown Language Code: " + language + ); + } + return iter->second; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Language.h b/SerialPrograms/Source/CommonFramework/Language.h index 27891f03a0..3ce15a7ef0 100644 --- a/SerialPrograms/Source/CommonFramework/Language.h +++ b/SerialPrograms/Source/CommonFramework/Language.h @@ -1,68 +1,68 @@ -/* Language - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Language_H -#define PokemonAutomation_Language_H - -#include -#include - -namespace PokemonAutomation{ - -enum class Language{ - None, - English, - Japanese, - Spanish, - French, - German, - Italian, - Korean, - ChineseSimplified, - ChineseTraditional, - EndOfList, -}; - -struct LanguageData{ - std::string code; - std::string name; - double random_match_chance; -}; - -class LanguageSet{ -public: - LanguageSet() = default; - LanguageSet(std::initializer_list list) - : m_set(list) - {} - - bool operator[](Language language) const; - void operator+=(Language language); - void operator-=(Language language); - void operator+=(const LanguageSet& set); - void operator-=(const LanguageSet& set); - - std::set::const_iterator begin() const{ - return m_set.begin(); - } - std::set::const_iterator end() const{ - return m_set.end(); - } - - -private: - std::set m_set; -}; - - -const LanguageData& language_data(Language language); -Language language_code_to_enum(const std::string& language); - - - - -} -#endif +/* Language + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Language_H +#define PokemonAutomation_Language_H + +#include +#include + +namespace PokemonAutomation{ + +enum class Language{ + None, + English, + Japanese, + Spanish, + French, + German, + Italian, + Korean, + ChineseSimplified, + ChineseTraditional, + EndOfList, +}; + +struct LanguageData{ + std::string code; + std::string name; + double random_match_chance; +}; + +class LanguageSet{ +public: + LanguageSet() = default; + LanguageSet(std::initializer_list list) + : m_set(list) + {} + + bool operator[](Language language) const; + void operator+=(Language language); + void operator-=(Language language); + void operator+=(const LanguageSet& set); + void operator-=(const LanguageSet& set); + + std::set::const_iterator begin() const{ + return m_set.begin(); + } + std::set::const_iterator end() const{ + return m_set.end(); + } + + +private: + std::set m_set; +}; + + +const LanguageData& language_data(Language language); +Language language_code_to_enum(const std::string& language); + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp index e06b05e919..b2050efe47 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp +++ b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.cpp @@ -1,327 +1,327 @@ -/* File and Window Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Windows/DpiScaler.h" -#include "CommonFramework/Windows/WindowTracker.h" -#include "CommonFramework/Windows/MainWindow.h" -#include "CommonFramework/Options/ResolutionOption.h" -#include "FileWindowLogger.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -Logger& global_logger_raw(){ - static FileWindowLogger logger(USER_FILE_PATH() + (QCoreApplication::applicationName() + ".log").toStdString()); - return logger; -} - - -void LastLogTracker::operator+=(std::string line){ - m_lines.emplace_back(std::move(line)); - while (m_lines.size() > m_max_lines){ - m_lines.pop_front(); - } -} -std::vector LastLogTracker::snapshot() const{ - return std::vector(m_lines.begin(), m_lines.end()); -} - - -FileWindowLogger::~FileWindowLogger(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; - m_cv.notify_all(); - } - m_thread.join(); -} -FileWindowLogger::FileWindowLogger(const std::string& path) - : m_file(QString::fromStdString(path)) - , m_max_queue_size(LOG_HISTORY_LINES) - , m_stopping(false) -{ - bool exists = m_file.exists(); - m_file.open(QIODevice::WriteOnly | QIODevice::Append); - if (!exists){ - std::string bom = "\xef\xbb\xbf"; - m_file.write(bom.c_str(), bom.size()); - } - - m_thread = std::thread(&FileWindowLogger::thread_loop, this); -} -void FileWindowLogger::operator+=(FileWindowLoggerWindow& widget){ -// auto scope_check = m_sanitizer.check_scope(); - std::lock_guard lg(m_lock); - m_windows.insert(&widget); -} -void FileWindowLogger::operator-=(FileWindowLoggerWindow& widget){ -// auto scope_check = m_sanitizer.check_scope(); - std::lock_guard lg(m_lock); - m_windows.erase(&widget); -} - -void FileWindowLogger::log(const std::string& msg, Color color){ -// auto scope_check = m_sanitizer.check_scope(); - std::unique_lock lg(m_lock); - m_last_log_tracker += msg; - m_cv.wait(lg, [this]{ return m_queue.size() < m_max_queue_size; }); - m_queue.emplace_back(msg, color); - m_cv.notify_all(); -} -void FileWindowLogger::log(std::string&& msg, Color color){ -// auto scope_check = m_sanitizer.check_scope(); - std::unique_lock lg(m_lock); - m_last_log_tracker += msg; - m_cv.wait(lg, [this]{ return m_queue.size() < m_max_queue_size; }); - m_queue.emplace_back(std::move(msg), color); - m_cv.notify_all(); -} -std::vector FileWindowLogger::get_last() const{ -// auto scope_check = m_sanitizer.check_scope(); - std::unique_lock lg(m_lock); - return m_last_log_tracker.snapshot(); -} - - -std::string FileWindowLogger::normalize_newlines(const std::string& msg){ - std::string str; - size_t index = 0; - - while (true){ - auto pos = msg.find("\r\n", index); - if (pos == std::string::npos){ - str += msg.substr(index, pos); - break; - }else{ - str += msg.substr(index, pos); - str += "\n"; - index = pos + 2; - } - } - - if (!str.empty() && str.back() == '\n'){ - str.pop_back(); - } - - return str; -} -std::string FileWindowLogger::to_file_str(const std::string& msg){ - // Replace all newlines with: - //
for the output window. - // \r\n for the log file. - - std::string str; - for (char ch : msg){ - if (ch == '\n'){ - str += "\r\n"; - continue; - } - str += ch; - } - str += "\r\n"; - - return str; -} -QString FileWindowLogger::to_window_str(const std::string& msg, Color color){ - // Replace all newlines with: - //
for the output window. - // \r\n for the log file. - - std::string str; - if (color){ - str += ""; - }else{ - str += ""; - } - for (char ch : msg){ - if (ch == ' '){ - str += " "; - continue; - } - if (ch == '\n'){ - str += "
"; - continue; - } - str += ch; - } -// if (color){ - str += "
"; -// } - - return QString::fromStdString(str); -} -void FileWindowLogger::internal_log(const std::string& msg, Color color){ -// auto scope_check = m_sanitizer.check_scope(); - std::string line = normalize_newlines(msg); - { - if (!m_windows.empty()){ - QString str = to_window_str(line, color); - for (FileWindowLoggerWindow* window : m_windows){ - window->log(str); - } - } - } - { - m_file.write(to_file_str(msg).c_str()); - m_file.flush(); - } -} -void FileWindowLogger::thread_loop(){ -// auto scope_check = m_sanitizer.check_scope(); - std::unique_lock lg(m_lock); - while (true){ - m_cv.wait(lg, [&]{ - return m_stopping || !m_queue.empty(); - }); - if (m_stopping){ - break; - } - auto& item = m_queue.front(); - std::string msg = std::move(item.first); - Color color = item.second; - m_queue.pop_front(); - - lg.unlock(); - internal_log(msg, color); - lg.lock(); - - if (m_queue.size() <= m_max_queue_size / 2){ - m_cv.notify_all(); - } - } -} - - - - - - -FileWindowLoggerWindow::FileWindowLoggerWindow(FileWindowLogger& logger, QWidget* parent) - : QMainWindow(parent) - , m_logger(logger) -{ - if (objectName().isEmpty()){ - setObjectName(QString::fromUtf8("TextWindow")); - } - uint32_t width = GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH; - uint32_t height = GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT; - resize(scale_dpi_width(width), scale_dpi_height(height)); - m_text = new QTextEdit(this); - m_text->setObjectName(QString::fromUtf8("centralwidget")); - setCentralWidget(m_text); - m_menubar = new QMenuBar(this); - m_menubar->setObjectName(QString::fromUtf8("menubar")); - setMenuBar(m_menubar); -// m_statusbar = new QStatusBar(this); -// m_statusbar->setObjectName(QString::fromUtf8("statusbar")); -// setStatusBar(m_statusbar); - setWindowTitle("Program Output"); - - m_text->setReadOnly(true); - m_text->setAcceptRichText(true); - m_text->document()->setMaximumBlockCount(1000); - - connect( - this, &FileWindowLoggerWindow::signal_log, - m_text, [this](QString msg){ -// cout << "signal_log(): " << msg.toStdString() << endl; - m_text->append(msg); - } - ); - - GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.add_listener(*this); - GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.add_listener(*this); - GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.add_listener(*this); - GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.add_listener(*this); - - m_logger += *this; - log("================================================================================"); - log("Window Startup..."); - log("Current path: " + QDir::currentPath()); - log("Executable path: " + qApp->applicationDirPath()); - log(QString::fromStdString("Program setting folder: " + SETTINGS_PATH())); - log(QString::fromStdString("Program resources folder: " + RESOURCE_PATH())); - add_window(*this); -} -FileWindowLoggerWindow::~FileWindowLoggerWindow(){ - remove_window(*this); - m_logger -= *this; - GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.remove_listener(*this); - GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.remove_listener(*this); - GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.remove_listener(*this); - GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.remove_listener(*this); -} - -void FileWindowLoggerWindow::log(QString msg){ -// cout << "FileWindowLoggerWindow::log(): " << msg.toStdString() << endl; - emit signal_log(msg); -} - -void FileWindowLoggerWindow::resizeEvent(QResizeEvent* event){ - m_pending_resize = true; - GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.set(width()); - GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.set(height()); - m_pending_resize = false; -} - -void FileWindowLoggerWindow::moveEvent(QMoveEvent* event){ - m_pending_move = true; - GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.set(x()); - GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.set(y()); - m_pending_move = false; -} - -void FileWindowLoggerWindow::on_config_value_changed(void* object){ - if (object == &GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH || object == &GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT){ - QMetaObject::invokeMethod(this, [this]{ - if (!m_pending_resize){ - resize( - GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH, - GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT - ); - } - }); - }else if (object == &GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS || object == &GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS){ - QMetaObject::invokeMethod(this, [this]{ - if (!m_pending_move){ - move( - move_x_within_screen_bounds(GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS), - move_y_within_screen_bounds(GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS) - ); - } - }); - } -} - - - - - - - - - - - - - - - - - - - - -} +/* File and Window Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Windows/DpiScaler.h" +#include "CommonFramework/Windows/WindowTracker.h" +#include "CommonFramework/Windows/MainWindow.h" +#include "CommonFramework/Options/ResolutionOption.h" +#include "FileWindowLogger.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +Logger& global_logger_raw(){ + static FileWindowLogger logger(USER_FILE_PATH() + (QCoreApplication::applicationName() + ".log").toStdString()); + return logger; +} + + +void LastLogTracker::operator+=(std::string line){ + m_lines.emplace_back(std::move(line)); + while (m_lines.size() > m_max_lines){ + m_lines.pop_front(); + } +} +std::vector LastLogTracker::snapshot() const{ + return std::vector(m_lines.begin(), m_lines.end()); +} + + +FileWindowLogger::~FileWindowLogger(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; + m_cv.notify_all(); + } + m_thread.join(); +} +FileWindowLogger::FileWindowLogger(const std::string& path) + : m_file(QString::fromStdString(path)) + , m_max_queue_size(LOG_HISTORY_LINES) + , m_stopping(false) +{ + bool exists = m_file.exists(); + m_file.open(QIODevice::WriteOnly | QIODevice::Append); + if (!exists){ + std::string bom = "\xef\xbb\xbf"; + m_file.write(bom.c_str(), bom.size()); + } + + m_thread = std::thread(&FileWindowLogger::thread_loop, this); +} +void FileWindowLogger::operator+=(FileWindowLoggerWindow& widget){ +// auto scope_check = m_sanitizer.check_scope(); + std::lock_guard lg(m_lock); + m_windows.insert(&widget); +} +void FileWindowLogger::operator-=(FileWindowLoggerWindow& widget){ +// auto scope_check = m_sanitizer.check_scope(); + std::lock_guard lg(m_lock); + m_windows.erase(&widget); +} + +void FileWindowLogger::log(const std::string& msg, Color color){ +// auto scope_check = m_sanitizer.check_scope(); + std::unique_lock lg(m_lock); + m_last_log_tracker += msg; + m_cv.wait(lg, [this]{ return m_queue.size() < m_max_queue_size; }); + m_queue.emplace_back(msg, color); + m_cv.notify_all(); +} +void FileWindowLogger::log(std::string&& msg, Color color){ +// auto scope_check = m_sanitizer.check_scope(); + std::unique_lock lg(m_lock); + m_last_log_tracker += msg; + m_cv.wait(lg, [this]{ return m_queue.size() < m_max_queue_size; }); + m_queue.emplace_back(std::move(msg), color); + m_cv.notify_all(); +} +std::vector FileWindowLogger::get_last() const{ +// auto scope_check = m_sanitizer.check_scope(); + std::unique_lock lg(m_lock); + return m_last_log_tracker.snapshot(); +} + + +std::string FileWindowLogger::normalize_newlines(const std::string& msg){ + std::string str; + size_t index = 0; + + while (true){ + auto pos = msg.find("\r\n", index); + if (pos == std::string::npos){ + str += msg.substr(index, pos); + break; + }else{ + str += msg.substr(index, pos); + str += "\n"; + index = pos + 2; + } + } + + if (!str.empty() && str.back() == '\n'){ + str.pop_back(); + } + + return str; +} +std::string FileWindowLogger::to_file_str(const std::string& msg){ + // Replace all newlines with: + //
for the output window. + // \r\n for the log file. + + std::string str; + for (char ch : msg){ + if (ch == '\n'){ + str += "\r\n"; + continue; + } + str += ch; + } + str += "\r\n"; + + return str; +} +QString FileWindowLogger::to_window_str(const std::string& msg, Color color){ + // Replace all newlines with: + //
for the output window. + // \r\n for the log file. + + std::string str; + if (color){ + str += ""; + }else{ + str += ""; + } + for (char ch : msg){ + if (ch == ' '){ + str += " "; + continue; + } + if (ch == '\n'){ + str += "
"; + continue; + } + str += ch; + } +// if (color){ + str += "
"; +// } + + return QString::fromStdString(str); +} +void FileWindowLogger::internal_log(const std::string& msg, Color color){ +// auto scope_check = m_sanitizer.check_scope(); + std::string line = normalize_newlines(msg); + { + if (!m_windows.empty()){ + QString str = to_window_str(line, color); + for (FileWindowLoggerWindow* window : m_windows){ + window->log(str); + } + } + } + { + m_file.write(to_file_str(msg).c_str()); + m_file.flush(); + } +} +void FileWindowLogger::thread_loop(){ +// auto scope_check = m_sanitizer.check_scope(); + std::unique_lock lg(m_lock); + while (true){ + m_cv.wait(lg, [&]{ + return m_stopping || !m_queue.empty(); + }); + if (m_stopping){ + break; + } + auto& item = m_queue.front(); + std::string msg = std::move(item.first); + Color color = item.second; + m_queue.pop_front(); + + lg.unlock(); + internal_log(msg, color); + lg.lock(); + + if (m_queue.size() <= m_max_queue_size / 2){ + m_cv.notify_all(); + } + } +} + + + + + + +FileWindowLoggerWindow::FileWindowLoggerWindow(FileWindowLogger& logger, QWidget* parent) + : QMainWindow(parent) + , m_logger(logger) +{ + if (objectName().isEmpty()){ + setObjectName(QString::fromUtf8("TextWindow")); + } + uint32_t width = GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH; + uint32_t height = GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT; + resize(scale_dpi_width(width), scale_dpi_height(height)); + m_text = new QTextEdit(this); + m_text->setObjectName(QString::fromUtf8("centralwidget")); + setCentralWidget(m_text); + m_menubar = new QMenuBar(this); + m_menubar->setObjectName(QString::fromUtf8("menubar")); + setMenuBar(m_menubar); +// m_statusbar = new QStatusBar(this); +// m_statusbar->setObjectName(QString::fromUtf8("statusbar")); +// setStatusBar(m_statusbar); + setWindowTitle("Program Output"); + + m_text->setReadOnly(true); + m_text->setAcceptRichText(true); + m_text->document()->setMaximumBlockCount(1000); + + connect( + this, &FileWindowLoggerWindow::signal_log, + m_text, [this](QString msg){ +// cout << "signal_log(): " << msg.toStdString() << endl; + m_text->append(msg); + } + ); + + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.add_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.add_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.add_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.add_listener(*this); + + m_logger += *this; + log("================================================================================"); + log("Window Startup..."); + log("Current path: " + QDir::currentPath()); + log("Executable path: " + qApp->applicationDirPath()); + log(QString::fromStdString("Program setting folder: " + SETTINGS_PATH())); + log(QString::fromStdString("Program resources folder: " + RESOURCE_PATH())); + add_window(*this); +} +FileWindowLoggerWindow::~FileWindowLoggerWindow(){ + remove_window(*this); + m_logger -= *this; + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.remove_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.remove_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.remove_listener(*this); + GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.remove_listener(*this); +} + +void FileWindowLoggerWindow::log(QString msg){ +// cout << "FileWindowLoggerWindow::log(): " << msg.toStdString() << endl; + emit signal_log(msg); +} + +void FileWindowLoggerWindow::resizeEvent(QResizeEvent* event){ + m_pending_resize = true; + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH.set(width()); + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT.set(height()); + m_pending_resize = false; +} + +void FileWindowLoggerWindow::moveEvent(QMoveEvent* event){ + m_pending_move = true; + GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS.set(x()); + GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS.set(y()); + m_pending_move = false; +} + +void FileWindowLoggerWindow::on_config_value_changed(void* object){ + if (object == &GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH || object == &GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_resize){ + resize( + GlobalSettings::instance().LOG_WINDOW_SIZE->WIDTH, + GlobalSettings::instance().LOG_WINDOW_SIZE->HEIGHT + ); + } + }); + }else if (object == &GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS || object == &GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_move){ + move( + move_x_within_screen_bounds(GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS), + move_y_within_screen_bounds(GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS) + ); + } + }); + } +} + + + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h index a24bc4002d..d41b4f6da6 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h +++ b/SerialPrograms/Source/CommonFramework/Logging/FileWindowLogger.h @@ -1,101 +1,101 @@ -/* File and Window Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Logging_FileWindowLogger_H -#define PokemonAutomation_Logging_FileWindowLogger_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Options/ConfigOption.h" -//#include "Common/Cpp/LifetimeSanitizer.h" - -namespace PokemonAutomation{ - -class FileWindowLoggerWindow; - - -class LastLogTracker{ -public: - LastLogTracker(size_t max_lines = 10000) - : m_max_lines(max_lines) - {} - void operator+=(std::string line); - std::vector snapshot() const; - -private: - size_t m_max_lines; - std::deque m_lines; -}; - - -class FileWindowLogger : public Logger{ -public: - ~FileWindowLogger(); - FileWindowLogger(const std::string& path); - - void operator+=(FileWindowLoggerWindow& widget); - void operator-=(FileWindowLoggerWindow& widget); - - virtual void log(const std::string& msg, Color color = Color()) override; - virtual void log(std::string&& msg, Color color = Color()) override; - virtual std::vector get_last() const override; - -private: - static std::string normalize_newlines(const std::string& msg); - static std::string to_file_str(const std::string& msg); - static QString to_window_str(const std::string& msg, Color color); - - void internal_log(const std::string& msg, Color color); - void thread_loop(); - -private: - QFile m_file; - size_t m_max_queue_size; - mutable std::mutex m_lock; - std::condition_variable m_cv; - LastLogTracker m_last_log_tracker; - bool m_stopping; - std::deque> m_queue; - std::set m_windows; - std::thread m_thread; - -// LifetimeSanitizer m_sanitizer; -}; - - -class FileWindowLoggerWindow : public QMainWindow, public ConfigOption::Listener{ - Q_OBJECT - -public: - FileWindowLoggerWindow(FileWindowLogger& logger, QWidget* parent = nullptr); - virtual ~FileWindowLoggerWindow(); - - void log(QString msg); - virtual void resizeEvent(QResizeEvent* event) override; - virtual void moveEvent(QMoveEvent* event) override; - -signals: - void signal_log(QString msg); - -private: - virtual void on_config_value_changed(void* object) override; - FileWindowLogger& m_logger; - QMenuBar* m_menubar; - QTextEdit* m_text; - bool m_pending_resize = false; - bool m_pending_move = false; -}; - - -} -#endif +/* File and Window Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Logging_FileWindowLogger_H +#define PokemonAutomation_Logging_FileWindowLogger_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Options/ConfigOption.h" +//#include "Common/Cpp/LifetimeSanitizer.h" + +namespace PokemonAutomation{ + +class FileWindowLoggerWindow; + + +class LastLogTracker{ +public: + LastLogTracker(size_t max_lines = 10000) + : m_max_lines(max_lines) + {} + void operator+=(std::string line); + std::vector snapshot() const; + +private: + size_t m_max_lines; + std::deque m_lines; +}; + + +class FileWindowLogger : public Logger{ +public: + ~FileWindowLogger(); + FileWindowLogger(const std::string& path); + + void operator+=(FileWindowLoggerWindow& widget); + void operator-=(FileWindowLoggerWindow& widget); + + virtual void log(const std::string& msg, Color color = Color()) override; + virtual void log(std::string&& msg, Color color = Color()) override; + virtual std::vector get_last() const override; + +private: + static std::string normalize_newlines(const std::string& msg); + static std::string to_file_str(const std::string& msg); + static QString to_window_str(const std::string& msg, Color color); + + void internal_log(const std::string& msg, Color color); + void thread_loop(); + +private: + QFile m_file; + size_t m_max_queue_size; + mutable std::mutex m_lock; + std::condition_variable m_cv; + LastLogTracker m_last_log_tracker; + bool m_stopping; + std::deque> m_queue; + std::set m_windows; + std::thread m_thread; + +// LifetimeSanitizer m_sanitizer; +}; + + +class FileWindowLoggerWindow : public QMainWindow, public ConfigOption::Listener{ + Q_OBJECT + +public: + FileWindowLoggerWindow(FileWindowLogger& logger, QWidget* parent = nullptr); + virtual ~FileWindowLoggerWindow(); + + void log(QString msg); + virtual void resizeEvent(QResizeEvent* event) override; + virtual void moveEvent(QMoveEvent* event) override; + +signals: + void signal_log(QString msg); + +private: + virtual void on_config_value_changed(void* object) override; + FileWindowLogger& m_logger; + QMenuBar* m_menubar; + QTextEdit* m_text; + bool m_pending_resize = false; + bool m_pending_move = false; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Logging/Logger.cpp b/SerialPrograms/Source/CommonFramework/Logging/Logger.cpp index 940a698c3e..b7bd990e15 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/Logger.cpp +++ b/SerialPrograms/Source/CommonFramework/Logging/Logger.cpp @@ -1,68 +1,68 @@ -/* Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ClientSource/Libraries/Logging.h" -#include "Logger.h" - -#include - -namespace PokemonAutomation{ - - -Logger& global_logger_tagged(){ - static TaggedLogger logger(global_logger_raw(), "Global"); - return logger; -} - - -TaggedLogger::TaggedLogger(Logger& logger, std::string tag) - : m_logger(logger) - , m_tag(std::move(tag)) -{} - -void TaggedLogger::log(const std::string& msg, Color color){ - std::string str = - current_time_to_str() + - " - [" + m_tag + "]: " + - msg; - m_logger.log(std::move(str), color); -} - - - -class CommandLineLogger : public Logger{ -public: - CommandLineLogger(Logger& logger) - : m_logger(logger) {} - - virtual void log(const std::string& msg, Color color = Color()) override{ - std::cout << msg << std::endl; - m_logger.log(msg, color); - } - virtual void log(std::string&& msg, Color color = Color()) override{ - std::cout << msg << std::endl; - m_logger.log(std::move(msg), color); - } - virtual void log(const char* msg, Color color = Color()) override{ - std::cout << msg << std::endl; - m_logger.log(msg, color); - } - -private: - Logger& m_logger; - std::string m_tag; -}; - - -Logger& global_logger_command_line(){ - static CommandLineLogger logger(global_logger_raw()); - return logger; -} - - -} - +/* Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ClientSource/Libraries/Logging.h" +#include "Logger.h" + +#include + +namespace PokemonAutomation{ + + +Logger& global_logger_tagged(){ + static TaggedLogger logger(global_logger_raw(), "Global"); + return logger; +} + + +TaggedLogger::TaggedLogger(Logger& logger, std::string tag) + : m_logger(logger) + , m_tag(std::move(tag)) +{} + +void TaggedLogger::log(const std::string& msg, Color color){ + std::string str = + current_time_to_str() + + " - [" + m_tag + "]: " + + msg; + m_logger.log(std::move(str), color); +} + + + +class CommandLineLogger : public Logger{ +public: + CommandLineLogger(Logger& logger) + : m_logger(logger) {} + + virtual void log(const std::string& msg, Color color = Color()) override{ + std::cout << msg << std::endl; + m_logger.log(msg, color); + } + virtual void log(std::string&& msg, Color color = Color()) override{ + std::cout << msg << std::endl; + m_logger.log(std::move(msg), color); + } + virtual void log(const char* msg, Color color = Color()) override{ + std::cout << msg << std::endl; + m_logger.log(msg, color); + } + +private: + Logger& m_logger; + std::string m_tag; +}; + + +Logger& global_logger_command_line(){ + static CommandLineLogger logger(global_logger_raw()); + return logger; +} + + +} + diff --git a/SerialPrograms/Source/CommonFramework/Logging/Logger.h b/SerialPrograms/Source/CommonFramework/Logging/Logger.h index 293f4555af..0899436489 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/Logger.h +++ b/SerialPrograms/Source/CommonFramework/Logging/Logger.h @@ -1,50 +1,50 @@ -/* Logger Qt - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Logging_Logger_H -#define PokemonAutomation_Logging_Logger_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ - - - -// Print as is. Use this to build other loggers. -Logger& global_logger_raw(); - -// Print with timestamp and a default tag. use this directly. -Logger& global_logger_tagged(); - -// Print log also to command line. Useful for running command line tests. -Logger& global_logger_command_line(); - - - -class TaggedLogger : public Logger{ -public: - TaggedLogger(Logger& logger, std::string tag); - - Logger& base_logger(){ return m_logger; } - - virtual void log(const std::string& msg, Color color = Color()) override; - -private: - Logger& m_logger; - std::string m_tag; -}; - - - - - - - -} -#endif - +/* Logger Qt + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Logging_Logger_H +#define PokemonAutomation_Logging_Logger_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ + + + +// Print as is. Use this to build other loggers. +Logger& global_logger_raw(); + +// Print with timestamp and a default tag. use this directly. +Logger& global_logger_tagged(); + +// Print log also to command line. Useful for running command line tests. +Logger& global_logger_command_line(); + + + +class TaggedLogger : public Logger{ +public: + TaggedLogger(Logger& logger, std::string tag); + + Logger& base_logger(){ return m_logger; } + + virtual void log(const std::string& msg, Color color = Color()) override; + +private: + Logger& m_logger; + std::string m_tag; +}; + + + + + + + +} +#endif + diff --git a/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.cpp b/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.cpp index a4dca89883..e922fa0ce5 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.cpp +++ b/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.cpp @@ -1,50 +1,50 @@ -/* Output Redirector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "OutputRedirector.h" - -namespace PokemonAutomation{ - - -OutputRedirector::OutputRedirector(std::ostream& stream, std::string tag, Color color) - : m_stream(stream) - , m_old_buf(stream.rdbuf()) - , m_logger(global_logger_raw(), tag) - , m_color(color) -{ - stream.rdbuf(this); -} -OutputRedirector::~OutputRedirector(){ - this->m_stream.rdbuf(this->m_old_buf); -} - - - -OutputRedirector::int_type OutputRedirector::overflow(int_type ch){ - WriteSpinLock lg(m_lock); - m_old_buf->sputc((char)ch); - m_old_buf->pubsync(); - m_buffer += (char)ch; - if (ch == '\n'){ - m_logger.log(m_buffer, m_color); - m_buffer.clear(); - } - return ch; -} -std::streamsize OutputRedirector::xsputn(const char_type* s, std::streamsize count){ - WriteSpinLock lg(m_lock); - m_old_buf->sputn(s, count); - m_buffer.append(s, count); - if (!m_buffer.empty() && m_buffer.back() == '\n'){ - m_logger.log(m_buffer, m_color); - m_buffer.clear(); - } - return count; -} - - -} +/* Output Redirector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "OutputRedirector.h" + +namespace PokemonAutomation{ + + +OutputRedirector::OutputRedirector(std::ostream& stream, std::string tag, Color color) + : m_stream(stream) + , m_old_buf(stream.rdbuf()) + , m_logger(global_logger_raw(), tag) + , m_color(color) +{ + stream.rdbuf(this); +} +OutputRedirector::~OutputRedirector(){ + this->m_stream.rdbuf(this->m_old_buf); +} + + + +OutputRedirector::int_type OutputRedirector::overflow(int_type ch){ + WriteSpinLock lg(m_lock); + m_old_buf->sputc((char)ch); + m_old_buf->pubsync(); + m_buffer += (char)ch; + if (ch == '\n'){ + m_logger.log(m_buffer, m_color); + m_buffer.clear(); + } + return ch; +} +std::streamsize OutputRedirector::xsputn(const char_type* s, std::streamsize count){ + WriteSpinLock lg(m_lock); + m_old_buf->sputn(s, count); + m_buffer.append(s, count); + if (!m_buffer.empty() && m_buffer.back() == '\n'){ + m_logger.log(m_buffer, m_color); + m_buffer.clear(); + } + return count; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.h b/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.h index 4fc33d9cdf..0df6ce2114 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.h +++ b/SerialPrograms/Source/CommonFramework/Logging/OutputRedirector.h @@ -1,37 +1,37 @@ -/* Output Redirector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Logging_OutputRedirector_H -#define PokemonAutomation_Logging_OutputRedirector_H - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Logger.h" - -namespace PokemonAutomation{ - - -class OutputRedirector : public std::basic_streambuf{ -public: - OutputRedirector(std::ostream& stream, std::string tag, Color color); - ~OutputRedirector(); - -private: - virtual int_type overflow(int_type ch) override; - virtual std::streamsize xsputn(const char_type* s, std::streamsize count) override; - -private: - SpinLock m_lock; - std::ostream& m_stream; - std::streambuf* m_old_buf; - TaggedLogger m_logger; - Color m_color; - std::string m_buffer; -}; - - -} -#endif +/* Output Redirector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Logging_OutputRedirector_H +#define PokemonAutomation_Logging_OutputRedirector_H + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Logger.h" + +namespace PokemonAutomation{ + + +class OutputRedirector : public std::basic_streambuf{ +public: + OutputRedirector(std::ostream& stream, std::string tag, Color color); + ~OutputRedirector(); + +private: + virtual int_type overflow(int_type ch) override; + virtual std::streamsize xsputn(const char_type* s, std::streamsize count) override; + +private: + SpinLock m_lock; + std::ostream& m_stream; + std::streambuf* m_old_buf; + TaggedLogger m_logger; + Color m_color; + std::string m_buffer; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.cpp b/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.cpp index 35406c5e6f..180a1cf69f 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.cpp +++ b/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.cpp @@ -1,49 +1,49 @@ -/* Queued Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Unicode.h" -#include "QueuedLogger.h" - -namespace PokemonAutomation{ - - -#if 0 -void QueuedLogger::log(const char* msg, Color color){ - log(std::string(msg), color); -} -void QueuedLogger::log(const std::string& msg, Color color){ - std::lock_guard lg(m_lock); - m_queue.emplace_back(new Entry{ - current_time(), - color, - msg - }); - m_cv.notify_all(); -} -void QueuedLogger::log(const QString& msg, Color color){ - log(msg.toUtf8().toStdString(), color); -} - -std::unique_ptr QueuedLogger::get(){ - std::unique_lock lg(m_lock); - if (m_queue.empty()){ - m_cv.wait(lg); - } - if (m_queue.empty()){ - return nullptr; - } - std::unique_ptr entry = std::move(m_queue.front()); - m_queue.pop_front(); - return entry; -} -void QueuedLogger::signal(){ - std::lock_guard lg(m_lock); - m_cv.notify_all(); -} -#endif - - -} +/* Queued Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Unicode.h" +#include "QueuedLogger.h" + +namespace PokemonAutomation{ + + +#if 0 +void QueuedLogger::log(const char* msg, Color color){ + log(std::string(msg), color); +} +void QueuedLogger::log(const std::string& msg, Color color){ + std::lock_guard lg(m_lock); + m_queue.emplace_back(new Entry{ + current_time(), + color, + msg + }); + m_cv.notify_all(); +} +void QueuedLogger::log(const QString& msg, Color color){ + log(msg.toUtf8().toStdString(), color); +} + +std::unique_ptr QueuedLogger::get(){ + std::unique_lock lg(m_lock); + if (m_queue.empty()){ + m_cv.wait(lg); + } + if (m_queue.empty()){ + return nullptr; + } + std::unique_ptr entry = std::move(m_queue.front()); + m_queue.pop_front(); + return entry; +} +void QueuedLogger::signal(){ + std::lock_guard lg(m_lock); + m_cv.notify_all(); +} +#endif + + +} diff --git a/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.h b/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.h index 2dc86c61b8..744d58c0ef 100644 --- a/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.h +++ b/SerialPrograms/Source/CommonFramework/Logging/QueuedLogger.h @@ -1,49 +1,49 @@ -/* Queued Logger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Logging_QueuedLogger_H -#define PokemonAutomation_Logging_QueuedLogger_H - -#include -#include -#include -#include "Logger.h" - -namespace PokemonAutomation{ - - -#if 0 -class QueuedLogger : public Logger{ -public: - struct Entry{ - WallClock timestamp; - Color color; - std::string line; - }; - -public: - virtual void log(const char* msg, Color color = QColor()) override; - virtual void log(const std::string& msg, Color color = QColor()) override; - virtual void log(const QString& msg, Color color = QColor()) override; - - // Get a message from the queue. If it is empty, wait for a message. - // May return nullptr. - std::unique_ptr get(); - - // Signal any pending "get()" calls to return. - void signal(); - -private: - std::mutex m_lock; - std::condition_variable m_cv; - std::deque> m_queue; -}; -#endif - - - -} -#endif +/* Queued Logger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Logging_QueuedLogger_H +#define PokemonAutomation_Logging_QueuedLogger_H + +#include +#include +#include +#include "Logger.h" + +namespace PokemonAutomation{ + + +#if 0 +class QueuedLogger : public Logger{ +public: + struct Entry{ + WallClock timestamp; + Color color; + std::string line; + }; + +public: + virtual void log(const char* msg, Color color = QColor()) override; + virtual void log(const std::string& msg, Color color = QColor()) override; + virtual void log(const QString& msg, Color color = QColor()) override; + + // Get a message from the queue. If it is empty, wait for a message. + // May return nullptr. + std::unique_ptr get(); + + // Signal any pending "get()" calls to return. + void signal(); + +private: + std::mutex m_lock; + std::condition_variable m_cv; + std::deque> m_queue; +}; +#endif + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Main.cpp b/SerialPrograms/Source/CommonFramework/Main.cpp index 6765e5177b..f87331a73f 100644 --- a/SerialPrograms/Source/CommonFramework/Main.cpp +++ b/SerialPrograms/Source/CommonFramework/Main.cpp @@ -1,152 +1,152 @@ - -#include -#include -#include -//#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/ImageResolution.h" -#include "PersistentSettings.h" -#include "Tests/CommandLineTests.h" -#include "ErrorReports/ProgramDumper.h" -#include "ErrorReports/ErrorReports.h" -#include "Environment/HardwareValidation.h" -#include "Logging/Logger.h" -#include "Logging/OutputRedirector.h" -//#include "Tools/StatsDatabase.h" -#include "Integrations/SleepyDiscordRunner.h" -#include "Globals.h" -#include "GlobalSettingsPanel.h" -//#include "Windows/DpiScaler.h" -#include "Startup/SetupSettings.h" -#include "Startup/NewVersionCheck.h" -#include "Windows/MainWindow.h" - - -#include -using std::cout; -using std::endl; - - -using namespace PokemonAutomation; - -Q_DECLARE_METATYPE(std::string) - -void set_working_directory(){ - QString application_dir_path = qApp->applicationDirPath(); - if (application_dir_path.endsWith(".app/Contents/MacOS")){ - // a macOS bundle. Change working directory to the folder that hosts the .app folder. - QString app_bundle_path = application_dir_path.chopped(15); - QString base_folder_path = QFileInfo(app_bundle_path).dir().absolutePath(); - QDir::setCurrent(base_folder_path); - } -} - -int main(int argc, char *argv[]){ - setup_crash_handler(); - -#if defined(__linux) || defined(__APPLE__) - // By default Qt uses native menubar but this only works on Windows. - // We use menubar in our ButtonDiagram window to choose which controller's button mapping image to show. - // So we fix it by don't using native menubar on non-Windows OS. - QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar); -#endif - -//#if QT_VERSION_MAJOR == 5 // AA_EnableHighDpiScaling is deprecated in Qt6 -// QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); -//#endif - QApplication application(argc, argv); - - Logger& logger = global_logger_tagged(); - - logger.log("================================================================================"); - logger.log("Starting Program..."); - - qRegisterMetaType("size_t"); - qRegisterMetaType("uint8_t"); - qRegisterMetaType("std::string"); - qRegisterMetaType("Resolution"); - - OutputRedirector redirect_stdout(std::cout, "stdout", Color()); - OutputRedirector redirect_stderr(std::cerr, "stderr", COLOR_RED); - - QDir().mkpath(QString::fromStdString(SETTINGS_PATH())); - QDir().mkpath(QString::fromStdString(SCREENSHOTS_PATH())); - - // Several novice developers struggled to build and run the program due to missing Resources folder. - // Add this check to pop a message box when Resources folder is missing. - if (!check_resource_folder(logger)){ - return 1; - } - - // Read program settings from json file: SerialPrograms-Settings.json. - try{ - if (!migrate_settings(logger, application.applicationName().toStdString() + "-Settings.json")){ - return 1; - } - - std::cout << "Loading from program setting JSON: " << PROGRAM_SETTING_JSON_PATH() << std::endl; - PERSISTENT_SETTINGS().read(); - - if (!migrate_stats(logger)){ - return 1; - } - }catch (const FileException& error){ - logger.log(error.message(), COLOR_RED); - }catch (const ParseException& error){ - logger.log(error.message(), COLOR_RED); - } - - if (GlobalSettings::instance().COMMAND_LINE_TEST_MODE){ - return run_command_line_tests(); - } - - // Check whether the hardware is powerful enough to run this program. - if (!check_hardware()){ - return 1; - } - - check_new_version(logger); - - Integration::DiscordIntegrationSettingsOption& discord_settings = GlobalSettings::instance().DISCORD->integration; - if (discord_settings.run_on_start){ -#ifdef PA_SLEEPY - if (discord_settings.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ - Integration::SleepyDiscordRunner::sleepy_connect(); - } -#endif -#ifdef PA_DPP - if (discord_settings.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ - Integration::DppClient::Client::instance().connect(); - } -#endif - discord_settings.on_config_value_changed(nullptr); - } - - set_working_directory(); - - // Run this asynchronously to we don't block startup. - std::unique_ptr task = send_all_unsent_reports(logger, true); - - int ret = 0; - { - MainWindow w; - w.show(); - w.raise(); // bring the window to front on macOS - set_permissions(w); - ret = application.exec(); - } - - // Write program settings back to the json file. - PERSISTENT_SETTINGS().write(); - -#ifdef PA_DPP - Integration::DppClient::Client::instance().disconnect(); -#endif -#ifdef PA_SLEEPY - Integration::SleepyDiscordRunner::sleepy_terminate(); -#endif - - return ret; -} + +#include +#include +#include +//#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/ImageResolution.h" +#include "PersistentSettings.h" +#include "Tests/CommandLineTests.h" +#include "ErrorReports/ProgramDumper.h" +#include "ErrorReports/ErrorReports.h" +#include "Environment/HardwareValidation.h" +#include "Logging/Logger.h" +#include "Logging/OutputRedirector.h" +//#include "Tools/StatsDatabase.h" +#include "Integrations/SleepyDiscordRunner.h" +#include "Globals.h" +#include "GlobalSettingsPanel.h" +//#include "Windows/DpiScaler.h" +#include "Startup/SetupSettings.h" +#include "Startup/NewVersionCheck.h" +#include "Windows/MainWindow.h" + + +#include +using std::cout; +using std::endl; + + +using namespace PokemonAutomation; + +Q_DECLARE_METATYPE(std::string) + +void set_working_directory(){ + QString application_dir_path = qApp->applicationDirPath(); + if (application_dir_path.endsWith(".app/Contents/MacOS")){ + // a macOS bundle. Change working directory to the folder that hosts the .app folder. + QString app_bundle_path = application_dir_path.chopped(15); + QString base_folder_path = QFileInfo(app_bundle_path).dir().absolutePath(); + QDir::setCurrent(base_folder_path); + } +} + +int main(int argc, char *argv[]){ + setup_crash_handler(); + +#if defined(__linux) || defined(__APPLE__) + // By default Qt uses native menubar but this only works on Windows. + // We use menubar in our ButtonDiagram window to choose which controller's button mapping image to show. + // So we fix it by don't using native menubar on non-Windows OS. + QCoreApplication::setAttribute(Qt::AA_DontUseNativeMenuBar); +#endif + +//#if QT_VERSION_MAJOR == 5 // AA_EnableHighDpiScaling is deprecated in Qt6 +// QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); +//#endif + QApplication application(argc, argv); + + Logger& logger = global_logger_tagged(); + + logger.log("================================================================================"); + logger.log("Starting Program..."); + + qRegisterMetaType("size_t"); + qRegisterMetaType("uint8_t"); + qRegisterMetaType("std::string"); + qRegisterMetaType("Resolution"); + + OutputRedirector redirect_stdout(std::cout, "stdout", Color()); + OutputRedirector redirect_stderr(std::cerr, "stderr", COLOR_RED); + + QDir().mkpath(QString::fromStdString(SETTINGS_PATH())); + QDir().mkpath(QString::fromStdString(SCREENSHOTS_PATH())); + + // Several novice developers struggled to build and run the program due to missing Resources folder. + // Add this check to pop a message box when Resources folder is missing. + if (!check_resource_folder(logger)){ + return 1; + } + + // Read program settings from json file: SerialPrograms-Settings.json. + try{ + if (!migrate_settings(logger, application.applicationName().toStdString() + "-Settings.json")){ + return 1; + } + + std::cout << "Loading from program setting JSON: " << PROGRAM_SETTING_JSON_PATH() << std::endl; + PERSISTENT_SETTINGS().read(); + + if (!migrate_stats(logger)){ + return 1; + } + }catch (const FileException& error){ + logger.log(error.message(), COLOR_RED); + }catch (const ParseException& error){ + logger.log(error.message(), COLOR_RED); + } + + if (GlobalSettings::instance().COMMAND_LINE_TEST_MODE){ + return run_command_line_tests(); + } + + // Check whether the hardware is powerful enough to run this program. + if (!check_hardware()){ + return 1; + } + + check_new_version(logger); + + Integration::DiscordIntegrationSettingsOption& discord_settings = GlobalSettings::instance().DISCORD->integration; + if (discord_settings.run_on_start){ +#ifdef PA_SLEEPY + if (discord_settings.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ + Integration::SleepyDiscordRunner::sleepy_connect(); + } +#endif +#ifdef PA_DPP + if (discord_settings.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ + Integration::DppClient::Client::instance().connect(); + } +#endif + discord_settings.on_config_value_changed(nullptr); + } + + set_working_directory(); + + // Run this asynchronously to we don't block startup. + std::unique_ptr task = send_all_unsent_reports(logger, true); + + int ret = 0; + { + MainWindow w; + w.show(); + w.raise(); // bring the window to front on macOS + set_permissions(w); + ret = application.exec(); + } + + // Write program settings back to the json file. + PERSISTENT_SETTINGS().write(); + +#ifdef PA_DPP + Integration::DppClient::Client::instance().disconnect(); +#endif +#ifdef PA_SLEEPY + Integration::SleepyDiscordRunner::sleepy_terminate(); +#endif + + return ret; +} diff --git a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp index cb0917bc0a..2577f1657f 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.cpp @@ -1,299 +1,299 @@ -/* Event Notification Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Options/LabelCellOption.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "EventNotificationOption.h" - -#include -#include -#include "Common/Qt/Options/ConfigWidget.h" - -namespace PokemonAutomation{ - - -class TestButtonWidget : public ConfigWidget{ -public: - TestButtonWidget(QWidget& parent, TestMessageButton& value) - : ConfigWidget(value) - { - QPushButton* button = new QPushButton(&parent); - m_widget = button; - - QFont font; - font.setBold(true); - button->setFont(font); - button->setText("Send Test Message"); - - button->connect( - button, &QPushButton::clicked, - button, [&](bool){ - send_raw_program_notification( - global_logger_tagged(), value.option, - COLOR_GREEN, - ProgramInfo("Test Message"), - "Notification Test", - { - {"Event Type:", value.option.label()}, - } - ); - } - ); - } -}; -TestMessageButton::TestMessageButton(EventNotificationOption& p_option) - : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) - , option(p_option) -{} -ConfigWidget* TestMessageButton::make_QtWidget(QWidget& parent){ - return new TestButtonWidget(parent, *this); -} - - - - -std::string EventNotificationOption::sanitize_tag(const std::string& token){ - std::string str; - for (unsigned char ch : token){ - if (ch < 32) continue; - if (ch == ' ') continue; - str += ch; - } - return str; -} -std::string EventNotificationOption::tags_to_str(const std::vector& tags){ - std::string text; - bool first = true; - for (const std::string& tag : tags){ - if (!first){ - text += ", "; - } - first = false; - text += tag; - } - return text; -} -std::vector EventNotificationOption::parse_tags(const std::string& str){ - std::vector tags; - size_t start = 0; - - for (size_t end; (end = str.find(",", start)) != std::string::npos; start = end+1){ - std::string token = str.substr(start, end - start); - token = sanitize_tag(token); - if (!token.empty()){ - tags.emplace_back(std::move(token)); - } - } - std::string token = sanitize_tag(str.substr(start)); - if (!token.empty()){ - tags.emplace_back(std::move(token)); - } - - return tags; -} - - -struct EventNotificationOption::Data{ - Data( - std::string label, - bool enabled, bool ping, - std::chrono::seconds rate_limit - ) - : screenshot_supported(false) - , m_enabled(LockMode::UNLOCK_WHILE_RUNNING, enabled) - , m_label(LockMode::UNLOCK_WHILE_RUNNING, std::move(label)) - , m_ping(LockMode::UNLOCK_WHILE_RUNNING, ping) - , m_null_screenshot(LockMode::UNLOCK_WHILE_RUNNING, "---") - , m_screenshot(ImageAttachmentMode::NO_SCREENSHOT) - , m_tags(false, LockMode::UNLOCK_WHILE_RUNNING, "Notifs", "") - , m_rate_limit_seconds(LockMode::UNLOCK_WHILE_RUNNING, uint32_t(rate_limit.count())) - , m_last_sent(WallClock::min()) - , m_global_enable(true) - {} - Data( - std::string label, - bool enabled, bool ping, - std::vector tags, - std::chrono::seconds rate_limit - ) - : screenshot_supported(false) - , m_enabled(LockMode::UNLOCK_WHILE_RUNNING, enabled) - , m_label(LockMode::UNLOCK_WHILE_RUNNING, std::move(label)) - , m_ping(LockMode::UNLOCK_WHILE_RUNNING, ping) - , m_null_screenshot(LockMode::UNLOCK_WHILE_RUNNING, "---") - , m_screenshot(ImageAttachmentMode::NO_SCREENSHOT) - , m_tags(false, LockMode::UNLOCK_WHILE_RUNNING, tags_to_str(tags), "") - , m_rate_limit_seconds(LockMode::UNLOCK_WHILE_RUNNING, uint32_t(rate_limit.count())) - , m_last_sent(WallClock::min()) - , m_global_enable(true) - {} - Data( - std::string label, - bool enabled, bool ping, - ImageAttachmentMode screenshot, - std::vector tags, - std::chrono::seconds rate_limit - ) - : screenshot_supported(true) - , m_enabled(LockMode::UNLOCK_WHILE_RUNNING, enabled) - , m_label(LockMode::UNLOCK_WHILE_RUNNING, std::move(label)) - , m_ping(LockMode::UNLOCK_WHILE_RUNNING, ping) - , m_null_screenshot(LockMode::UNLOCK_WHILE_RUNNING, "---") - , m_screenshot(screenshot) - , m_tags(false, LockMode::UNLOCK_WHILE_RUNNING, tags_to_str(tags), "") - , m_rate_limit_seconds(LockMode::UNLOCK_WHILE_RUNNING, uint32_t(rate_limit.count())) - , m_last_sent(WallClock::min()) - , m_global_enable(true) - {} - - - bool screenshot_supported; - - BooleanCheckBoxCell m_enabled; - LabelCellOption m_label; - BooleanCheckBoxCell m_ping; - LabelCellOption m_null_screenshot; - ScreenshotCell m_screenshot; - StringCell m_tags; - SimpleIntegerCell m_rate_limit_seconds; - - std::atomic m_last_sent; - std::atomic m_global_enable; -}; - - - -EventNotificationOption::~EventNotificationOption(){} -EventNotificationOption::EventNotificationOption( - std::string label, - bool enabled, bool ping, - std::chrono::seconds rate_limit -) - : StaticTableRow(label) - , m_data(CONSTRUCT_TOKEN, std::move(label), enabled, ping, rate_limit) - , m_test_button(*this) -{ - add_option(m_data->m_enabled, "Enabled"); - add_option(m_data->m_label, ""); - add_option(m_data->m_ping, "Ping"); - add_option(m_data->m_null_screenshot, ""); - add_option(m_data->m_tags, "Tags"); - add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); - add_option(m_test_button, ""); - - reset_rate_limit(); -} -EventNotificationOption::EventNotificationOption( - std::string label, - bool enabled, bool ping, - std::vector tags, - std::chrono::seconds rate_limit -) - : StaticTableRow(label) - , m_data(CONSTRUCT_TOKEN, std::move(label), enabled, ping, std::move(tags), rate_limit) - , m_test_button(*this) -{ - add_option(m_data->m_enabled, "Enabled"); - add_option(m_data->m_label, ""); - add_option(m_data->m_ping, "Ping"); - add_option(m_data->m_null_screenshot, ""); - add_option(m_data->m_tags, "Tags"); - add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); - add_option(m_test_button, ""); - - reset_rate_limit(); -} -EventNotificationOption::EventNotificationOption( - std::string label, - bool enabled, bool ping, - ImageAttachmentMode screenshot, - std::vector tags, - std::chrono::seconds rate_limit -) - : StaticTableRow(label) - , m_data(CONSTRUCT_TOKEN, std::move(label), enabled, ping, screenshot, std::move(tags), rate_limit) - , m_test_button(*this) -{ - add_option(m_data->m_enabled, "Enabled"); - add_option(m_data->m_label, ""); - add_option(m_data->m_ping, "Ping"); - add_option(m_data->m_screenshot, "Screenshot"); - add_option(m_data->m_tags, "Tags"); - add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); - add_option(m_test_button, ""); - - reset_rate_limit(); -} - -const std::string& EventNotificationOption::label() const{ - return m_data->m_label.text(); -} -bool EventNotificationOption::ping() const{ - return m_data->m_ping; -} -ImageAttachmentMode EventNotificationOption::screenshot() const{ - return m_data->m_screenshot; -} -std::vector EventNotificationOption::tags() const{ - return parse_tags(m_data->m_tags); -} - -//void EventNotificationOption::set_tags(std::vector tags){ -// m_data->m_tags.set(tags_to_str(tags)); -//} - -void EventNotificationOption::set_global_enable(bool enabled){ - m_data->m_global_enable.store(enabled, std::memory_order_release); -} -void EventNotificationOption::reset_rate_limit(){ - m_data->m_last_sent.store(WallClock::min(), std::memory_order_release); -} -bool EventNotificationOption::ok_to_send_now(Logger& logger){ - const std::string& label = m_data->m_label.text(); - - if (!m_data->m_global_enable.load(std::memory_order_relaxed)){ - logger.log("EventNotification(" + label + "): Notifications not enabled.", COLOR_PURPLE); - return false; - } - if (!m_data->m_enabled){ - logger.log("EventNotification(" + label + "): Notifications disabled for this event type.", COLOR_PURPLE); - return false; - } -// if (m_current.rate_limit == std::chrono::seconds(0)){ -// return true; -// } - - WallClock now; - WallClock last; - do{ - now = current_time(); - last = m_data->m_last_sent.load(std::memory_order_acquire); - - if (now < last + std::chrono::seconds(m_data->m_rate_limit_seconds)){ - logger.log("EventNotification(" + label + "): Notification dropped due to rate limit.", COLOR_PURPLE); - return false; - } - - }while (!m_data->m_last_sent.compare_exchange_weak(last, now)); - - logger.log("EventNotification(" + label + "): Sending notification.", COLOR_BLUE); - return true; -} - - - - - - - - -} +/* Event Notification Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Options/LabelCellOption.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "EventNotificationOption.h" + +#include +#include +#include "Common/Qt/Options/ConfigWidget.h" + +namespace PokemonAutomation{ + + +class TestButtonWidget : public ConfigWidget{ +public: + TestButtonWidget(QWidget& parent, TestMessageButton& value) + : ConfigWidget(value) + { + QPushButton* button = new QPushButton(&parent); + m_widget = button; + + QFont font; + font.setBold(true); + button->setFont(font); + button->setText("Send Test Message"); + + button->connect( + button, &QPushButton::clicked, + button, [&](bool){ + send_raw_program_notification( + global_logger_tagged(), value.option, + COLOR_GREEN, + ProgramInfo("Test Message"), + "Notification Test", + { + {"Event Type:", value.option.label()}, + } + ); + } + ); + } +}; +TestMessageButton::TestMessageButton(EventNotificationOption& p_option) + : ConfigOption(LockMode::UNLOCK_WHILE_RUNNING) + , option(p_option) +{} +ConfigWidget* TestMessageButton::make_QtWidget(QWidget& parent){ + return new TestButtonWidget(parent, *this); +} + + + + +std::string EventNotificationOption::sanitize_tag(const std::string& token){ + std::string str; + for (unsigned char ch : token){ + if (ch < 32) continue; + if (ch == ' ') continue; + str += ch; + } + return str; +} +std::string EventNotificationOption::tags_to_str(const std::vector& tags){ + std::string text; + bool first = true; + for (const std::string& tag : tags){ + if (!first){ + text += ", "; + } + first = false; + text += tag; + } + return text; +} +std::vector EventNotificationOption::parse_tags(const std::string& str){ + std::vector tags; + size_t start = 0; + + for (size_t end; (end = str.find(",", start)) != std::string::npos; start = end+1){ + std::string token = str.substr(start, end - start); + token = sanitize_tag(token); + if (!token.empty()){ + tags.emplace_back(std::move(token)); + } + } + std::string token = sanitize_tag(str.substr(start)); + if (!token.empty()){ + tags.emplace_back(std::move(token)); + } + + return tags; +} + + +struct EventNotificationOption::Data{ + Data( + std::string label, + bool enabled, bool ping, + std::chrono::seconds rate_limit + ) + : screenshot_supported(false) + , m_enabled(LockMode::UNLOCK_WHILE_RUNNING, enabled) + , m_label(LockMode::UNLOCK_WHILE_RUNNING, std::move(label)) + , m_ping(LockMode::UNLOCK_WHILE_RUNNING, ping) + , m_null_screenshot(LockMode::UNLOCK_WHILE_RUNNING, "---") + , m_screenshot(ImageAttachmentMode::NO_SCREENSHOT) + , m_tags(false, LockMode::UNLOCK_WHILE_RUNNING, "Notifs", "") + , m_rate_limit_seconds(LockMode::UNLOCK_WHILE_RUNNING, uint32_t(rate_limit.count())) + , m_last_sent(WallClock::min()) + , m_global_enable(true) + {} + Data( + std::string label, + bool enabled, bool ping, + std::vector tags, + std::chrono::seconds rate_limit + ) + : screenshot_supported(false) + , m_enabled(LockMode::UNLOCK_WHILE_RUNNING, enabled) + , m_label(LockMode::UNLOCK_WHILE_RUNNING, std::move(label)) + , m_ping(LockMode::UNLOCK_WHILE_RUNNING, ping) + , m_null_screenshot(LockMode::UNLOCK_WHILE_RUNNING, "---") + , m_screenshot(ImageAttachmentMode::NO_SCREENSHOT) + , m_tags(false, LockMode::UNLOCK_WHILE_RUNNING, tags_to_str(tags), "") + , m_rate_limit_seconds(LockMode::UNLOCK_WHILE_RUNNING, uint32_t(rate_limit.count())) + , m_last_sent(WallClock::min()) + , m_global_enable(true) + {} + Data( + std::string label, + bool enabled, bool ping, + ImageAttachmentMode screenshot, + std::vector tags, + std::chrono::seconds rate_limit + ) + : screenshot_supported(true) + , m_enabled(LockMode::UNLOCK_WHILE_RUNNING, enabled) + , m_label(LockMode::UNLOCK_WHILE_RUNNING, std::move(label)) + , m_ping(LockMode::UNLOCK_WHILE_RUNNING, ping) + , m_null_screenshot(LockMode::UNLOCK_WHILE_RUNNING, "---") + , m_screenshot(screenshot) + , m_tags(false, LockMode::UNLOCK_WHILE_RUNNING, tags_to_str(tags), "") + , m_rate_limit_seconds(LockMode::UNLOCK_WHILE_RUNNING, uint32_t(rate_limit.count())) + , m_last_sent(WallClock::min()) + , m_global_enable(true) + {} + + + bool screenshot_supported; + + BooleanCheckBoxCell m_enabled; + LabelCellOption m_label; + BooleanCheckBoxCell m_ping; + LabelCellOption m_null_screenshot; + ScreenshotCell m_screenshot; + StringCell m_tags; + SimpleIntegerCell m_rate_limit_seconds; + + std::atomic m_last_sent; + std::atomic m_global_enable; +}; + + + +EventNotificationOption::~EventNotificationOption(){} +EventNotificationOption::EventNotificationOption( + std::string label, + bool enabled, bool ping, + std::chrono::seconds rate_limit +) + : StaticTableRow(label) + , m_data(CONSTRUCT_TOKEN, std::move(label), enabled, ping, rate_limit) + , m_test_button(*this) +{ + add_option(m_data->m_enabled, "Enabled"); + add_option(m_data->m_label, ""); + add_option(m_data->m_ping, "Ping"); + add_option(m_data->m_null_screenshot, ""); + add_option(m_data->m_tags, "Tags"); + add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); + add_option(m_test_button, ""); + + reset_rate_limit(); +} +EventNotificationOption::EventNotificationOption( + std::string label, + bool enabled, bool ping, + std::vector tags, + std::chrono::seconds rate_limit +) + : StaticTableRow(label) + , m_data(CONSTRUCT_TOKEN, std::move(label), enabled, ping, std::move(tags), rate_limit) + , m_test_button(*this) +{ + add_option(m_data->m_enabled, "Enabled"); + add_option(m_data->m_label, ""); + add_option(m_data->m_ping, "Ping"); + add_option(m_data->m_null_screenshot, ""); + add_option(m_data->m_tags, "Tags"); + add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); + add_option(m_test_button, ""); + + reset_rate_limit(); +} +EventNotificationOption::EventNotificationOption( + std::string label, + bool enabled, bool ping, + ImageAttachmentMode screenshot, + std::vector tags, + std::chrono::seconds rate_limit +) + : StaticTableRow(label) + , m_data(CONSTRUCT_TOKEN, std::move(label), enabled, ping, screenshot, std::move(tags), rate_limit) + , m_test_button(*this) +{ + add_option(m_data->m_enabled, "Enabled"); + add_option(m_data->m_label, ""); + add_option(m_data->m_ping, "Ping"); + add_option(m_data->m_screenshot, "Screenshot"); + add_option(m_data->m_tags, "Tags"); + add_option(m_data->m_rate_limit_seconds, "RateLimitSeconds"); + add_option(m_test_button, ""); + + reset_rate_limit(); +} + +const std::string& EventNotificationOption::label() const{ + return m_data->m_label.text(); +} +bool EventNotificationOption::ping() const{ + return m_data->m_ping; +} +ImageAttachmentMode EventNotificationOption::screenshot() const{ + return m_data->m_screenshot; +} +std::vector EventNotificationOption::tags() const{ + return parse_tags(m_data->m_tags); +} + +//void EventNotificationOption::set_tags(std::vector tags){ +// m_data->m_tags.set(tags_to_str(tags)); +//} + +void EventNotificationOption::set_global_enable(bool enabled){ + m_data->m_global_enable.store(enabled, std::memory_order_release); +} +void EventNotificationOption::reset_rate_limit(){ + m_data->m_last_sent.store(WallClock::min(), std::memory_order_release); +} +bool EventNotificationOption::ok_to_send_now(Logger& logger){ + const std::string& label = m_data->m_label.text(); + + if (!m_data->m_global_enable.load(std::memory_order_relaxed)){ + logger.log("EventNotification(" + label + "): Notifications not enabled.", COLOR_PURPLE); + return false; + } + if (!m_data->m_enabled){ + logger.log("EventNotification(" + label + "): Notifications disabled for this event type.", COLOR_PURPLE); + return false; + } +// if (m_current.rate_limit == std::chrono::seconds(0)){ +// return true; +// } + + WallClock now; + WallClock last; + do{ + now = current_time(); + last = m_data->m_last_sent.load(std::memory_order_acquire); + + if (now < last + std::chrono::seconds(m_data->m_rate_limit_seconds)){ + logger.log("EventNotification(" + label + "): Notification dropped due to rate limit.", COLOR_PURPLE); + return false; + } + + }while (!m_data->m_last_sent.compare_exchange_weak(last, now)); + + logger.log("EventNotification(" + label + "): Sending notification.", COLOR_BLUE); + return true; +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.h b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.h index 7b287482fa..ca47c647fa 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.h +++ b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationOption.h @@ -1,84 +1,84 @@ -/* Event Notification Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_EventNotificationOption_H -#define PokemonAutomation_EventNotificationOption_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/StaticTableOption.h" -#include "CommonFramework/Options/ScreenshotFormatOption.h" - -namespace PokemonAutomation{ - - -class EventNotificationOption; - - -class TestMessageButton : public ConfigOption{ -public: - TestMessageButton(EventNotificationOption& p_option); - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - EventNotificationOption& option; -}; - - - -class EventNotificationOption : public StaticTableRow{ -public: - static std::string sanitize_tag(const std::string& token); - static std::string tags_to_str(const std::vector& tags); - static std::vector parse_tags(const std::string& str); - -public: - ~EventNotificationOption(); - EventNotificationOption( - std::string label, - bool enabled, bool ping, - std::chrono::seconds rate_limit - ); - EventNotificationOption( - std::string label, - bool enabled, bool ping, - std::vector tags = {"Notifs"}, - std::chrono::seconds rate_limit = std::chrono::seconds(0) - ); - EventNotificationOption( - std::string label, - bool enabled, bool ping, - ImageAttachmentMode screenshot, - std::vector tags = {"Notifs"}, - std::chrono::seconds rate_limit = std::chrono::seconds(0) - ); - - const std::string& label () const; - bool ping () const; - ImageAttachmentMode screenshot () const; - std::vector tags () const; - -// void set_tags(std::vector tags); - - void set_global_enable(bool enabled); - void reset_rate_limit(); - - bool ok_to_send_now(Logger& logger); - -private: - friend class EventNotificationsTable; - - struct Data; - Pimpl m_data; - - TestMessageButton m_test_button; -}; - - - -} -#endif +/* Event Notification Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_EventNotificationOption_H +#define PokemonAutomation_EventNotificationOption_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/StaticTableOption.h" +#include "CommonFramework/Options/ScreenshotFormatOption.h" + +namespace PokemonAutomation{ + + +class EventNotificationOption; + + +class TestMessageButton : public ConfigOption{ +public: + TestMessageButton(EventNotificationOption& p_option); + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + EventNotificationOption& option; +}; + + + +class EventNotificationOption : public StaticTableRow{ +public: + static std::string sanitize_tag(const std::string& token); + static std::string tags_to_str(const std::vector& tags); + static std::vector parse_tags(const std::string& str); + +public: + ~EventNotificationOption(); + EventNotificationOption( + std::string label, + bool enabled, bool ping, + std::chrono::seconds rate_limit + ); + EventNotificationOption( + std::string label, + bool enabled, bool ping, + std::vector tags = {"Notifs"}, + std::chrono::seconds rate_limit = std::chrono::seconds(0) + ); + EventNotificationOption( + std::string label, + bool enabled, bool ping, + ImageAttachmentMode screenshot, + std::vector tags = {"Notifs"}, + std::chrono::seconds rate_limit = std::chrono::seconds(0) + ); + + const std::string& label () const; + bool ping () const; + ImageAttachmentMode screenshot () const; + std::vector tags () const; + +// void set_tags(std::vector tags); + + void set_global_enable(bool enabled); + void reset_rate_limit(); + + bool ok_to_send_now(Logger& logger); + +private: + friend class EventNotificationsTable; + + struct Data; + Pimpl m_data; + + TestMessageButton m_test_button; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.cpp b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.cpp index a865d1d8a0..be431b5e71 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.cpp @@ -1,66 +1,66 @@ -/* Program Notification Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "EventNotificationsTable.h" - -namespace PokemonAutomation{ - - -EventNotificationsTable::EventNotificationsTable(std::vector options) - : StaticTableOption("", LockMode::UNLOCK_WHILE_RUNNING, false) -{ - for (EventNotificationOption* option : options){ - add_row(option); - } - finish_construction(); -} - -void EventNotificationsTable::set_enabled(bool enabled){ - for (StaticTableRow* row : this->table()){ - EventNotificationOption* option = static_cast(row); - option->set_global_enable(enabled); - } -} - -std::vector EventNotificationsTable::make_header() const{ - std::vector ret{ - "Enable", - "Event", - "Should Ping", - "Screenshot", - "Tags", - "Rate Limit (seconds)", - "", - }; - return ret; -} - - -EventNotificationsOption::EventNotificationsOption(std::vector options) - : GroupOption( - "Discord Notifications", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_ENABLED, false - ) - , m_table(std::move(options)) -{ - PA_ADD_OPTION(m_table); -} -void EventNotificationsOption::on_set_enabled(bool enabled){ - m_table.set_enabled(enabled); -} - - - - - - - - - - - -} +/* Program Notification Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "EventNotificationsTable.h" + +namespace PokemonAutomation{ + + +EventNotificationsTable::EventNotificationsTable(std::vector options) + : StaticTableOption("", LockMode::UNLOCK_WHILE_RUNNING, false) +{ + for (EventNotificationOption* option : options){ + add_row(option); + } + finish_construction(); +} + +void EventNotificationsTable::set_enabled(bool enabled){ + for (StaticTableRow* row : this->table()){ + EventNotificationOption* option = static_cast(row); + option->set_global_enable(enabled); + } +} + +std::vector EventNotificationsTable::make_header() const{ + std::vector ret{ + "Enable", + "Event", + "Should Ping", + "Screenshot", + "Tags", + "Rate Limit (seconds)", + "", + }; + return ret; +} + + +EventNotificationsOption::EventNotificationsOption(std::vector options) + : GroupOption( + "Discord Notifications", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_ENABLED, false + ) + , m_table(std::move(options)) +{ + PA_ADD_OPTION(m_table); +} +void EventNotificationsOption::on_set_enabled(bool enabled){ + m_table.set_enabled(enabled); +} + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.h b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.h index a91f1bd25c..3272324c0d 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.h +++ b/SerialPrograms/Source/CommonFramework/Notifications/EventNotificationsTable.h @@ -1,45 +1,45 @@ -/* Event Notifications Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_EventNotificationsTable_H -#define PokemonAutomation_EventNotificationsTable_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTableOption.h" -#include "EventNotificationOption.h" - -namespace PokemonAutomation{ - - - -class EventNotificationsTable : public StaticTableOption{ -public: - EventNotificationsTable(std::vector options); - - void set_enabled(bool enabled); - - virtual std::vector make_header() const override; - -}; - - - - -class EventNotificationsOption : public GroupOption{ -public: - EventNotificationsOption(std::vector options); - virtual void on_set_enabled(bool enabled) override; -private: - EventNotificationsTable m_table; -}; - - - - - -} -#endif - +/* Event Notifications Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_EventNotificationsTable_H +#define PokemonAutomation_EventNotificationsTable_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTableOption.h" +#include "EventNotificationOption.h" + +namespace PokemonAutomation{ + + + +class EventNotificationsTable : public StaticTableOption{ +public: + EventNotificationsTable(std::vector options); + + void set_enabled(bool enabled); + + virtual std::vector make_header() const override; + +}; + + + + +class EventNotificationsOption : public GroupOption{ +public: + EventNotificationsOption(std::vector options); + virtual void on_set_enabled(bool enabled) override; +private: + EventNotificationsTable m_table; +}; + + + + + +} +#endif + diff --git a/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.cpp b/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.cpp index d7262d5a39..ab2a8f5478 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.cpp @@ -1,103 +1,103 @@ -/* Message Attachment - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "MessageAttachment.h" - -namespace PokemonAutomation{ - - - -ImageAttachment::ImageAttachment( - const ImageViewRGB32& p_image, - ImageAttachmentMode p_mode, - bool p_keep_file -) - : image(p_image) - , mode(p_mode) - , keep_file(p_keep_file) -{} - - - -PendingFileSend::~PendingFileSend(){ - if (m_filepath.empty()){ - return; - } - if (m_keep_file){ - return; - } - - if (m_extend_lifetime.load(std::memory_order_acquire)){ - return; - } - - QFile file(QString::fromStdString(m_filepath)); - file.remove(); -} -PendingFileSend::PendingFileSend(const std::string& file, bool keep_file) - : m_keep_file(keep_file) - , m_extend_lifetime(false) - , m_filepath(file) -{ - QFileInfo info(QString::fromStdString(file)); - m_filename = info.fileName().toStdString(); -} -PendingFileSend::PendingFileSend(Logger& logger, const ImageAttachment& image) - : m_keep_file(image.keep_file) - , m_extend_lifetime(false) -{ - if (image.mode == ImageAttachmentMode::NO_SCREENSHOT){ - return; - } - if (!image.image){ - logger.log("Screenshot is null.", COLOR_ORANGE); - return; - } - - std::string format; - switch (image.mode){ - case ImageAttachmentMode::NO_SCREENSHOT: - break; - case ImageAttachmentMode::JPG: - format = ".jpg"; - break; - case ImageAttachmentMode::PNG: - format = ".png"; - break; - } - - m_filename = now_to_filestring() + format; - - if (image.keep_file){ - m_filepath = SCREENSHOTS_PATH() + m_filename; - }else{ - m_filepath = GlobalSettings::instance().TEMP_FOLDER; - QDir().mkdir(QString::fromStdString(m_filepath)); - m_filepath += m_filename; - } - - if (image.image.save(m_filepath)){ - logger.log("Saved image to: " + m_filepath, COLOR_BLUE); - }else{ - logger.log("Unable to save screenshot to: " + m_filepath, COLOR_RED); - m_filename.clear(); - m_filepath.clear(); - } -} -void PendingFileSend::extend_lifetime(){ - m_extend_lifetime.store(true, std::memory_order_release); -} - - - - - -} +/* Message Attachment + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "MessageAttachment.h" + +namespace PokemonAutomation{ + + + +ImageAttachment::ImageAttachment( + const ImageViewRGB32& p_image, + ImageAttachmentMode p_mode, + bool p_keep_file +) + : image(p_image) + , mode(p_mode) + , keep_file(p_keep_file) +{} + + + +PendingFileSend::~PendingFileSend(){ + if (m_filepath.empty()){ + return; + } + if (m_keep_file){ + return; + } + + if (m_extend_lifetime.load(std::memory_order_acquire)){ + return; + } + + QFile file(QString::fromStdString(m_filepath)); + file.remove(); +} +PendingFileSend::PendingFileSend(const std::string& file, bool keep_file) + : m_keep_file(keep_file) + , m_extend_lifetime(false) + , m_filepath(file) +{ + QFileInfo info(QString::fromStdString(file)); + m_filename = info.fileName().toStdString(); +} +PendingFileSend::PendingFileSend(Logger& logger, const ImageAttachment& image) + : m_keep_file(image.keep_file) + , m_extend_lifetime(false) +{ + if (image.mode == ImageAttachmentMode::NO_SCREENSHOT){ + return; + } + if (!image.image){ + logger.log("Screenshot is null.", COLOR_ORANGE); + return; + } + + std::string format; + switch (image.mode){ + case ImageAttachmentMode::NO_SCREENSHOT: + break; + case ImageAttachmentMode::JPG: + format = ".jpg"; + break; + case ImageAttachmentMode::PNG: + format = ".png"; + break; + } + + m_filename = now_to_filestring() + format; + + if (image.keep_file){ + m_filepath = SCREENSHOTS_PATH() + m_filename; + }else{ + m_filepath = GlobalSettings::instance().TEMP_FOLDER; + QDir().mkdir(QString::fromStdString(m_filepath)); + m_filepath += m_filename; + } + + if (image.image.save(m_filepath)){ + logger.log("Saved image to: " + m_filepath, COLOR_BLUE); + }else{ + logger.log("Unable to save screenshot to: " + m_filepath, COLOR_RED); + m_filename.clear(); + m_filepath.clear(); + } +} +void PendingFileSend::extend_lifetime(){ + m_extend_lifetime.store(true, std::memory_order_release); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.h b/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.h index c1f25e5304..ddb813a31b 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.h +++ b/SerialPrograms/Source/CommonFramework/Notifications/MessageAttachment.h @@ -1,62 +1,62 @@ -/* Message Attachment - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_MessageAttachment_H -#define PokemonAutomation_MessageAttachment_H - -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Options/ScreenshotFormatOption.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - -struct ImageAttachment{ - ImageViewRGB32 image; - ImageAttachmentMode mode = ImageAttachmentMode::NO_SCREENSHOT; - bool keep_file = false; - - ImageAttachment() = default; - ImageAttachment( - const ImageViewRGB32& p_image, - ImageAttachmentMode p_mode, - bool p_keep_file = false - ); -}; - - - -// Represents a file that's in the process of being sent. -// If (keep_file = false), the file is automatically deleted after being sent. -class PendingFileSend{ -public: - ~PendingFileSend(); - - PendingFileSend(const std::string& file, bool keep_file); -// PendingFileSend(Logger& logger, const std::string& text_attachment); - PendingFileSend(Logger& logger, const ImageAttachment& image); - - const std::string& filename() const{ return m_filename; } - const std::string& filepath() const{ return m_filepath; } - bool keep_file() const{ return m_keep_file; } - - // Work around bug in Sleepy that destroys file before it's not needed anymore. - void extend_lifetime(); - -private: - bool m_keep_file; - std::atomic m_extend_lifetime; -// QFile m_file; - std::string m_filename; - std::string m_filepath; -}; - - - -} -#endif +/* Message Attachment + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MessageAttachment_H +#define PokemonAutomation_MessageAttachment_H + +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Options/ScreenshotFormatOption.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + +struct ImageAttachment{ + ImageViewRGB32 image; + ImageAttachmentMode mode = ImageAttachmentMode::NO_SCREENSHOT; + bool keep_file = false; + + ImageAttachment() = default; + ImageAttachment( + const ImageViewRGB32& p_image, + ImageAttachmentMode p_mode, + bool p_keep_file = false + ); +}; + + + +// Represents a file that's in the process of being sent. +// If (keep_file = false), the file is automatically deleted after being sent. +class PendingFileSend{ +public: + ~PendingFileSend(); + + PendingFileSend(const std::string& file, bool keep_file); +// PendingFileSend(Logger& logger, const std::string& text_attachment); + PendingFileSend(Logger& logger, const ImageAttachment& image); + + const std::string& filename() const{ return m_filename; } + const std::string& filepath() const{ return m_filepath; } + bool keep_file() const{ return m_keep_file; } + + // Work around bug in Sleepy that destroys file before it's not needed anymore. + void extend_lifetime(); + +private: + bool m_keep_file; + std::atomic m_extend_lifetime; +// QFile m_file; + std::string m_filename; + std::string m_filepath; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Notifications/ProgramInfo.h b/SerialPrograms/Source/CommonFramework/Notifications/ProgramInfo.h index 167abd990b..22a59d720a 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/ProgramInfo.h +++ b/SerialPrograms/Source/CommonFramework/Notifications/ProgramInfo.h @@ -1,42 +1,42 @@ -/* Program Information - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramInfo_H -#define PokemonAutomation_ProgramInfo_H - -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -struct ProgramInfo{ - std::string program_id; - std::string program_name; - WallClock start_time; - - ProgramInfo( - const std::string& module = "", - WallClock p_start_time = WallClock::min() - ) - : program_name(module) - , start_time(p_start_time) - {} - ProgramInfo( - std::string p_program_id, - std::string category, std::string display_name, - WallClock p_start_time = WallClock::min() - ) - : program_id(std::move(p_program_id)) - , program_name((category.empty() ? "" : category + ": ") + display_name) - , start_time(p_start_time) - {} -}; - - - -} -#endif +/* Program Information + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramInfo_H +#define PokemonAutomation_ProgramInfo_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +struct ProgramInfo{ + std::string program_id; + std::string program_name; + WallClock start_time; + + ProgramInfo( + const std::string& module = "", + WallClock p_start_time = WallClock::min() + ) + : program_name(module) + , start_time(p_start_time) + {} + ProgramInfo( + std::string p_program_id, + std::string category, std::string display_name, + WallClock p_start_time = WallClock::min() + ) + : program_id(std::move(p_program_id)) + , program_name((category.empty() ? "" : category + ": ") + display_name) + , start_time(p_start_time) + {} +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp b/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp index 76aecde236..20fa7a55a7 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.cpp @@ -1,401 +1,401 @@ -/* Program Notifications - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "Integrations/DiscordWebhook.h" -#include "Integrations/SleepyDiscordRunner.h" -#include "ProgramNotifications.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -void append_body_fields(JsonArray& fields, const std::vector>& messages){ - for (const auto& item : messages){ - JsonObject field; - field["name"] = item.first; - field["value"] = item.second; - if (!item.first.empty() && !item.second.empty()){ - fields.push_back(std::move(field)); - } - } -} -JsonObject make_credits_field(const ProgramInfo& info){ - JsonObject field; - field["name"] = "Powered By:"; - std::string text = PreloadSettings::instance().DEVELOPER_MODE - ? PROGRAM_NAME + " CC " + PROGRAM_VERSION + "-dev" - : PROGRAM_NAME + " CC " + PROGRAM_VERSION + ""; - if (GlobalSettings::instance().HIDE_NOTIF_DISCORD_LINK){ - text += " ([GitHub](" + GITHUB_LINK_URL + "))"; - }else{ - text += " ([GitHub](" + GITHUB_LINK_URL + ")/[Discord](" + DISCORD_LINK_URL_EMBED + "))"; - } - field["value"] = std::move(text); - return field; -} -std::pair make_session_field( - const ProgramInfo& info, - const StatsTracker* current_stats, const std::string& current_stats_addendum -){ - const std::string& instance_name = GlobalSettings::instance().DISCORD->message.instance_name; - std::string name = instance_name.empty() - ? "Current Session:" - : "Current Session: (" + instance_name + ")"; - - std::string text = info.program_name; - if (info.start_time != WallClock::min()){ - text += "\nUp Time: "; - text += duration_to_string( - std::chrono::duration_cast( - current_time() - info.start_time - ) - ); - } - if (current_stats){ - text += "\n"; - text += current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN); - if (!current_stats_addendum.empty()){ - text += "\n"; - text += current_stats_addendum; - } - } - - return {std::move(name), std::move(text)}; -} - - -void send_raw_notification( - Logger& logger, - Color color, bool should_ping, const std::vector& tags, - const ProgramInfo& info, - const std::string& title, - const std::vector>& messages, - const ImageAttachment& image -){ - std::shared_ptr file = std::make_shared(logger, image); - bool hasFile = !file->filepath().empty(); - - JsonObject embed; - JsonArray embeds; - { - embed["title"] = title; - - if (color){ - embed["color"] = (int)((uint32_t)color & 0xffffff); - } - - JsonArray fields; -// fields.push_back(make_header_field(info)); - append_body_fields(fields, messages); - fields.push_back(make_credits_field(info)); - embed["fields"] = std::move(fields); - - if (hasFile){ - JsonObject field; - field["url"] = "attachment://" + file->filename(); - embed["image"] = std::move(field); - } - embeds.push_back(embed.clone()); - } - - Integration::DiscordWebhook::send_embed( - logger, should_ping, tags, - std::move(embeds), - hasFile ? file : nullptr - ); - -#ifdef PA_SLEEPY - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ - Integration::SleepyDiscordRunner::send_embed_sleepy( - should_ping, tags, std::move(embed), - hasFile ? file : nullptr - ); - } -#endif - -#ifdef PA_DPP - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ - Integration::DppClient::Client::instance().send_embed_dpp( - should_ping, color, tags, std::move(embed), - hasFile ? file : nullptr - ); - } -#endif -} -void send_raw_notification( - Logger& logger, - Color color, bool should_ping, const std::vector& tags, - const ProgramInfo& info, - const std::string& title, - const std::vector>& messages, - const std::string& filepath -){ - std::shared_ptr file = std::make_shared(filepath, true); - bool hasFile = !file->filepath().empty(); - - JsonObject embed; - JsonArray embeds; - { - embed["title"] = title; - - if (color){ - embed["color"] = (int)((uint32_t)color & 0xffffff); - } - - JsonArray fields; -// fields.push_back(make_header_field(info)); - append_body_fields(fields, messages); - fields.push_back(make_credits_field(info)); - embed["fields"] = std::move(fields); - - embeds.push_back(embed.clone()); - } - - Integration::DiscordWebhook::send_embed( - logger, should_ping, tags, - std::move(embeds), - hasFile ? file : nullptr - ); - -#ifdef PA_SLEEPY - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ - Integration::SleepyDiscordRunner::send_embed_sleepy( - should_ping, tags, std::move(embed), - hasFile ? file : nullptr - ); - } -#endif - -#ifdef PA_DPP - if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ - Integration::DppClient::Client::instance().send_embed_dpp( - should_ping, color, tags, std::move(embed), - hasFile ? file : nullptr - ); - } -#endif -} - - - -void send_raw_program_notification_with_file( - Logger& logger, EventNotificationOption& settings, - Color color, - const ProgramInfo& info, - const std::string& title, - const std::vector>& messages, - const std::string& filepath -){ - if (!settings.ok_to_send_now(logger)){ - return; - } - send_raw_notification( - logger, - color, - settings.ping(), settings.tags(), - info, title, - messages, - filepath - ); -} -void send_raw_program_notification( - Logger& logger, EventNotificationOption& settings, - Color color, - const ProgramInfo& info, - const std::string& title, - const std::vector>& messages, - const ImageViewRGB32& image, bool keep_file -){ - if (!settings.ok_to_send_now(logger)){ - return; - } - send_raw_notification( - logger, - color, - settings.ping(), settings.tags(), - info, title, - messages, - ImageAttachment(image, settings.screenshot(), keep_file) - ); -} - - - -void send_program_notification_with_file( - ProgramEnvironment& env, EventNotificationOption& settings, - Color color, - const std::string& title, - std::vector> messages, - const std::string& current_stats_addendum, - const std::string& filepath -){ - if (!settings.ok_to_send_now(env.logger())){ - return; - } -#if 1 - messages.emplace_back( - make_session_field( - env.program_info(), - env.current_stats(), - current_stats_addendum - ) - ); -#else - const StatsTracker* current_stats = env.current_stats(); - if (current_stats){ - std::string str = env.current_stats()->to_str(); - if (!current_stats_addendum.empty()){ - str += "\n"; - str += current_stats_addendum; - } - messages.emplace_back("Session Stats:", std::move(str)); - } -#endif - const StatsTracker* historical_stats = env.historical_stats(); - if (GlobalSettings::instance().ALL_STATS && historical_stats){ - messages.emplace_back( - "Historical Stats:", - env.historical_stats()->to_str(StatsTracker::DISPLAY_ON_SCREEN) - ); - } - send_raw_notification( - env.logger(), - color, - settings.ping(), settings.tags(), - env.program_info(), - title, - messages, - filepath - ); -} -bool send_program_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - Color color, - const std::string& title, - std::vector> messages, - const std::string& current_stats_addendum, - const ImageViewRGB32& image, bool keep_file -){ - if (!settings.ok_to_send_now(env.logger())){ - return false; - } -#if 1 - messages.emplace_back( - make_session_field( - env.program_info(), - env.current_stats(), - current_stats_addendum - ) - ); -#else - const StatsTracker* current_stats = env.current_stats(); - if (current_stats){ - std::string str = env.current_stats()->to_str(); - if (!current_stats_addendum.empty()){ - str += "\n"; - str += current_stats_addendum; - } - messages.emplace_back("Session Stats:", std::move(str)); - } -#endif - const StatsTracker* historical_stats = env.historical_stats(); - if (GlobalSettings::instance().ALL_STATS && historical_stats){ - messages.emplace_back( - "Historical Stats:", - env.historical_stats()->to_str(StatsTracker::DISPLAY_ON_SCREEN) - ); - } - send_raw_notification( - env.logger(), - color, - settings.ping(), settings.tags(), - env.program_info(), - title, - messages, - ImageAttachment(image, settings.screenshot(), keep_file) - ); - - return true; -} - - - - - -void send_program_status_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message, - const ImageViewRGB32& image, bool keep_file -){ - send_program_notification( - env, settings, - Color(), - "Program Status", - {{"Message:", message}}, "", - image, keep_file - ); -} -void send_program_finished_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message, - const ImageViewRGB32& image, bool keep_file -){ - send_program_notification( - env, settings, - COLOR_GREEN, - "Program Finished", - {{"Message:", message}}, "", - image, keep_file - ); -} -void send_program_recoverable_error_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message, - const ImageViewRGB32& image, bool keep_file -){ - send_program_notification( - env, settings, - COLOR_RED, - "Program Error (Recoverable)", - {{"Message:", message}}, "", - image, keep_file - ); -} -void send_program_fatal_error_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message, - const ImageViewRGB32& image, bool keep_file -){ - send_program_notification( - env, settings, - COLOR_RED, - "Program Stopped (Fatal Error)", - {{"Message:", message}}, "", - image, keep_file - ); -} - - - - - - - - -} +/* Program Notifications + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "Integrations/DiscordWebhook.h" +#include "Integrations/SleepyDiscordRunner.h" +#include "ProgramNotifications.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +void append_body_fields(JsonArray& fields, const std::vector>& messages){ + for (const auto& item : messages){ + JsonObject field; + field["name"] = item.first; + field["value"] = item.second; + if (!item.first.empty() && !item.second.empty()){ + fields.push_back(std::move(field)); + } + } +} +JsonObject make_credits_field(const ProgramInfo& info){ + JsonObject field; + field["name"] = "Powered By:"; + std::string text = PreloadSettings::instance().DEVELOPER_MODE + ? PROGRAM_NAME + " CC " + PROGRAM_VERSION + "-dev" + : PROGRAM_NAME + " CC " + PROGRAM_VERSION + ""; + if (GlobalSettings::instance().HIDE_NOTIF_DISCORD_LINK){ + text += " ([GitHub](" + GITHUB_LINK_URL + "))"; + }else{ + text += " ([GitHub](" + GITHUB_LINK_URL + ")/[Discord](" + DISCORD_LINK_URL_EMBED + "))"; + } + field["value"] = std::move(text); + return field; +} +std::pair make_session_field( + const ProgramInfo& info, + const StatsTracker* current_stats, const std::string& current_stats_addendum +){ + const std::string& instance_name = GlobalSettings::instance().DISCORD->message.instance_name; + std::string name = instance_name.empty() + ? "Current Session:" + : "Current Session: (" + instance_name + ")"; + + std::string text = info.program_name; + if (info.start_time != WallClock::min()){ + text += "\nUp Time: "; + text += duration_to_string( + std::chrono::duration_cast( + current_time() - info.start_time + ) + ); + } + if (current_stats){ + text += "\n"; + text += current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN); + if (!current_stats_addendum.empty()){ + text += "\n"; + text += current_stats_addendum; + } + } + + return {std::move(name), std::move(text)}; +} + + +void send_raw_notification( + Logger& logger, + Color color, bool should_ping, const std::vector& tags, + const ProgramInfo& info, + const std::string& title, + const std::vector>& messages, + const ImageAttachment& image +){ + std::shared_ptr file = std::make_shared(logger, image); + bool hasFile = !file->filepath().empty(); + + JsonObject embed; + JsonArray embeds; + { + embed["title"] = title; + + if (color){ + embed["color"] = (int)((uint32_t)color & 0xffffff); + } + + JsonArray fields; +// fields.push_back(make_header_field(info)); + append_body_fields(fields, messages); + fields.push_back(make_credits_field(info)); + embed["fields"] = std::move(fields); + + if (hasFile){ + JsonObject field; + field["url"] = "attachment://" + file->filename(); + embed["image"] = std::move(field); + } + embeds.push_back(embed.clone()); + } + + Integration::DiscordWebhook::send_embed( + logger, should_ping, tags, + std::move(embeds), + hasFile ? file : nullptr + ); + +#ifdef PA_SLEEPY + if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ + Integration::SleepyDiscordRunner::send_embed_sleepy( + should_ping, tags, std::move(embed), + hasFile ? file : nullptr + ); + } +#endif + +#ifdef PA_DPP + if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ + Integration::DppClient::Client::instance().send_embed_dpp( + should_ping, color, tags, std::move(embed), + hasFile ? file : nullptr + ); + } +#endif +} +void send_raw_notification( + Logger& logger, + Color color, bool should_ping, const std::vector& tags, + const ProgramInfo& info, + const std::string& title, + const std::vector>& messages, + const std::string& filepath +){ + std::shared_ptr file = std::make_shared(filepath, true); + bool hasFile = !file->filepath().empty(); + + JsonObject embed; + JsonArray embeds; + { + embed["title"] = title; + + if (color){ + embed["color"] = (int)((uint32_t)color & 0xffffff); + } + + JsonArray fields; +// fields.push_back(make_header_field(info)); + append_body_fields(fields, messages); + fields.push_back(make_credits_field(info)); + embed["fields"] = std::move(fields); + + embeds.push_back(embed.clone()); + } + + Integration::DiscordWebhook::send_embed( + logger, should_ping, tags, + std::move(embeds), + hasFile ? file : nullptr + ); + +#ifdef PA_SLEEPY + if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::SleepyDiscord){ + Integration::SleepyDiscordRunner::send_embed_sleepy( + should_ping, tags, std::move(embed), + hasFile ? file : nullptr + ); + } +#endif + +#ifdef PA_DPP + if (GlobalSettings::instance().DISCORD->integration.library0 == Integration::DiscordIntegrationSettingsOption::Library::DPP){ + Integration::DppClient::Client::instance().send_embed_dpp( + should_ping, color, tags, std::move(embed), + hasFile ? file : nullptr + ); + } +#endif +} + + + +void send_raw_program_notification_with_file( + Logger& logger, EventNotificationOption& settings, + Color color, + const ProgramInfo& info, + const std::string& title, + const std::vector>& messages, + const std::string& filepath +){ + if (!settings.ok_to_send_now(logger)){ + return; + } + send_raw_notification( + logger, + color, + settings.ping(), settings.tags(), + info, title, + messages, + filepath + ); +} +void send_raw_program_notification( + Logger& logger, EventNotificationOption& settings, + Color color, + const ProgramInfo& info, + const std::string& title, + const std::vector>& messages, + const ImageViewRGB32& image, bool keep_file +){ + if (!settings.ok_to_send_now(logger)){ + return; + } + send_raw_notification( + logger, + color, + settings.ping(), settings.tags(), + info, title, + messages, + ImageAttachment(image, settings.screenshot(), keep_file) + ); +} + + + +void send_program_notification_with_file( + ProgramEnvironment& env, EventNotificationOption& settings, + Color color, + const std::string& title, + std::vector> messages, + const std::string& current_stats_addendum, + const std::string& filepath +){ + if (!settings.ok_to_send_now(env.logger())){ + return; + } +#if 1 + messages.emplace_back( + make_session_field( + env.program_info(), + env.current_stats(), + current_stats_addendum + ) + ); +#else + const StatsTracker* current_stats = env.current_stats(); + if (current_stats){ + std::string str = env.current_stats()->to_str(); + if (!current_stats_addendum.empty()){ + str += "\n"; + str += current_stats_addendum; + } + messages.emplace_back("Session Stats:", std::move(str)); + } +#endif + const StatsTracker* historical_stats = env.historical_stats(); + if (GlobalSettings::instance().ALL_STATS && historical_stats){ + messages.emplace_back( + "Historical Stats:", + env.historical_stats()->to_str(StatsTracker::DISPLAY_ON_SCREEN) + ); + } + send_raw_notification( + env.logger(), + color, + settings.ping(), settings.tags(), + env.program_info(), + title, + messages, + filepath + ); +} +bool send_program_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + Color color, + const std::string& title, + std::vector> messages, + const std::string& current_stats_addendum, + const ImageViewRGB32& image, bool keep_file +){ + if (!settings.ok_to_send_now(env.logger())){ + return false; + } +#if 1 + messages.emplace_back( + make_session_field( + env.program_info(), + env.current_stats(), + current_stats_addendum + ) + ); +#else + const StatsTracker* current_stats = env.current_stats(); + if (current_stats){ + std::string str = env.current_stats()->to_str(); + if (!current_stats_addendum.empty()){ + str += "\n"; + str += current_stats_addendum; + } + messages.emplace_back("Session Stats:", std::move(str)); + } +#endif + const StatsTracker* historical_stats = env.historical_stats(); + if (GlobalSettings::instance().ALL_STATS && historical_stats){ + messages.emplace_back( + "Historical Stats:", + env.historical_stats()->to_str(StatsTracker::DISPLAY_ON_SCREEN) + ); + } + send_raw_notification( + env.logger(), + color, + settings.ping(), settings.tags(), + env.program_info(), + title, + messages, + ImageAttachment(image, settings.screenshot(), keep_file) + ); + + return true; +} + + + + + +void send_program_status_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message, + const ImageViewRGB32& image, bool keep_file +){ + send_program_notification( + env, settings, + Color(), + "Program Status", + {{"Message:", message}}, "", + image, keep_file + ); +} +void send_program_finished_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message, + const ImageViewRGB32& image, bool keep_file +){ + send_program_notification( + env, settings, + COLOR_GREEN, + "Program Finished", + {{"Message:", message}}, "", + image, keep_file + ); +} +void send_program_recoverable_error_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message, + const ImageViewRGB32& image, bool keep_file +){ + send_program_notification( + env, settings, + COLOR_RED, + "Program Error (Recoverable)", + {{"Message:", message}}, "", + image, keep_file + ); +} +void send_program_fatal_error_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message, + const ImageViewRGB32& image, bool keep_file +){ + send_program_notification( + env, settings, + COLOR_RED, + "Program Stopped (Fatal Error)", + {{"Message:", message}}, "", + image, keep_file + ); +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.h b/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.h index 6a7ec679c1..1ea8dc529c 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.h +++ b/SerialPrograms/Source/CommonFramework/Notifications/ProgramNotifications.h @@ -1,164 +1,164 @@ -/* Program Notifications - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramNotifications_H -#define PokemonAutomation_ProgramNotifications_H - -#include -#include -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "ProgramInfo.h" -#include "EventNotificationOption.h" - -namespace PokemonAutomation{ - -class Logger; -class StatsTracker; -class ProgramEnvironment; - - - -// Send raw Discord notification according to the notification settings. -// Can control the message sidebar color, message title, and message body. -// messages: vector>, the sections of the Discord message. -// The first string in the pair is the section title (will shown as bold) while the second -// string is the section content. -// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): -// **Message** -// This is a message. -// The function will add an additional section "Powered By". -// filepath: send the file as a message attachment. -void send_raw_program_notification_with_file( - Logger& logger, EventNotificationOption& settings, - Color color, - const ProgramInfo& info, - const std::string& title, - const std::vector>& messages, - const std::string& filepath -); - -// Send raw Discord notification according to the notification settings. -// Can control the message sidebar color, message title, and message body. -// messages: vector>, the sections of the Discord message. -// The first string in the pair is the section title (will shown as bold) while the second -// string is the section content. -// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): -// **Message** -// This is a message. -// The function will add an additional section "Powered By". -// image: if not empty, send the screenshot image as part of the message according to the -// notification settings. -// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it -// will be saved to the program TEMP_FOLDER. -void send_raw_program_notification( - Logger& logger, EventNotificationOption& settings, - Color color, - const ProgramInfo& info, - const std::string& title, - const std::vector>& messages, - const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false -); - - - -// Send custom Discord notification according to the notification settings. -// Can control the message sidebar color, message title, and message body. -// messages: vector>, the sections of the Discord message. -// The first string in the pair is the section title (will shown as bold) while the second -// string is the section content. -// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): -// **Message** -// This is a message. -// The function will add additional sections: "Current Session", "Historical Stats" -// and "Powered By". -// current_stats_addendum: add additional message at the end of the "Current Session" section -// where it shows the current program stats message generated by StatsTracker. -// filepath: send the file as a message attachment. -void send_program_notification_with_file( - ProgramEnvironment& env, EventNotificationOption& settings, - Color color, - const std::string& title, - std::vector> messages, - const std::string& current_stats_addendum, - const std::string& filepath -); - -// Send custom Discord notification according to the notification settings. -// Can control the message sidebar color, message title, and message body. -// messages: vector>, the sections of the Discord message. -// The first string in the pair is the section title (will shown as bold) while the second -// string is the section content. -// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): -// **Message** -// This is a message. -// The function will add additional sections: "Current Session", "Historical Stats" -// and "Powered By". -// current_stats_addendum: add additional message at the end of the "Current Session" section -// where it shows the current program stats message generated by StatsTracker. -// image: if not empty, send the screenshot image as part of the message according to the -// notification settings. -// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it -// will be saved to the program TEMP_FOLDER. -bool send_program_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - Color color, - const std::string& title, - std::vector> messages, - const std::string& current_stats_addendum, - const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false -); - - - -// Send Discord notification of the current program status according to the notification settings. -// Can send additional message and screenshot image. -// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it -// will be saved to the program TEMP_FOLDER. -void send_program_status_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message = "", - const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false -); - -// Send Discord notification that the program has finished according to the notification settings. -// Can send additional message and screenshot image. -// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it -// will be saved to the program TEMP_FOLDER. -void send_program_finished_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message = "", - const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false -); - -// Send Discord notification that the program has encountered a recoverable error according to the -// notification settings. -// Can send additional message and screenshot image. -// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it -// will be saved to the program TEMP_FOLDER. -void send_program_recoverable_error_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message, - const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false -); - -// Send Discord notification that the program has a fatal error according to the notification -// settings. -// Can send additional message and screenshot image. -// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it -// will be saved to the program TEMP_FOLDER. -void send_program_fatal_error_notification( - ProgramEnvironment& env, EventNotificationOption& settings, - const std::string& message, - const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false -); - - - - - - -} -#endif +/* Program Notifications + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramNotifications_H +#define PokemonAutomation_ProgramNotifications_H + +#include +#include +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "ProgramInfo.h" +#include "EventNotificationOption.h" + +namespace PokemonAutomation{ + +class Logger; +class StatsTracker; +class ProgramEnvironment; + + + +// Send raw Discord notification according to the notification settings. +// Can control the message sidebar color, message title, and message body. +// messages: vector>, the sections of the Discord message. +// The first string in the pair is the section title (will shown as bold) while the second +// string is the section content. +// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): +// **Message** +// This is a message. +// The function will add an additional section "Powered By". +// filepath: send the file as a message attachment. +void send_raw_program_notification_with_file( + Logger& logger, EventNotificationOption& settings, + Color color, + const ProgramInfo& info, + const std::string& title, + const std::vector>& messages, + const std::string& filepath +); + +// Send raw Discord notification according to the notification settings. +// Can control the message sidebar color, message title, and message body. +// messages: vector>, the sections of the Discord message. +// The first string in the pair is the section title (will shown as bold) while the second +// string is the section content. +// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): +// **Message** +// This is a message. +// The function will add an additional section "Powered By". +// image: if not empty, send the screenshot image as part of the message according to the +// notification settings. +// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it +// will be saved to the program TEMP_FOLDER. +void send_raw_program_notification( + Logger& logger, EventNotificationOption& settings, + Color color, + const ProgramInfo& info, + const std::string& title, + const std::vector>& messages, + const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false +); + + + +// Send custom Discord notification according to the notification settings. +// Can control the message sidebar color, message title, and message body. +// messages: vector>, the sections of the Discord message. +// The first string in the pair is the section title (will shown as bold) while the second +// string is the section content. +// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): +// **Message** +// This is a message. +// The function will add additional sections: "Current Session", "Historical Stats" +// and "Powered By". +// current_stats_addendum: add additional message at the end of the "Current Session" section +// where it shows the current program stats message generated by StatsTracker. +// filepath: send the file as a message attachment. +void send_program_notification_with_file( + ProgramEnvironment& env, EventNotificationOption& settings, + Color color, + const std::string& title, + std::vector> messages, + const std::string& current_stats_addendum, + const std::string& filepath +); + +// Send custom Discord notification according to the notification settings. +// Can control the message sidebar color, message title, and message body. +// messages: vector>, the sections of the Discord message. +// The first string in the pair is the section title (will shown as bold) while the second +// string is the section content. +// e.g. {{"Message:", {"This is a message."}}} will shown as (in Markdown): +// **Message** +// This is a message. +// The function will add additional sections: "Current Session", "Historical Stats" +// and "Powered By". +// current_stats_addendum: add additional message at the end of the "Current Session" section +// where it shows the current program stats message generated by StatsTracker. +// image: if not empty, send the screenshot image as part of the message according to the +// notification settings. +// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it +// will be saved to the program TEMP_FOLDER. +bool send_program_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + Color color, + const std::string& title, + std::vector> messages, + const std::string& current_stats_addendum, + const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false +); + + + +// Send Discord notification of the current program status according to the notification settings. +// Can send additional message and screenshot image. +// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it +// will be saved to the program TEMP_FOLDER. +void send_program_status_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message = "", + const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false +); + +// Send Discord notification that the program has finished according to the notification settings. +// Can send additional message and screenshot image. +// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it +// will be saved to the program TEMP_FOLDER. +void send_program_finished_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message = "", + const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false +); + +// Send Discord notification that the program has encountered a recoverable error according to the +// notification settings. +// Can send additional message and screenshot image. +// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it +// will be saved to the program TEMP_FOLDER. +void send_program_recoverable_error_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message, + const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false +); + +// Send Discord notification that the program has a fatal error according to the notification +// settings. +// Can send additional message and screenshot image. +// keep_file: if true, the sent image will be saved to the screenshot dir on disk. Otherwise, it +// will be saved to the program TEMP_FOLDER. +void send_program_fatal_error_notification( + ProgramEnvironment& env, EventNotificationOption& settings, + const std::string& message, + const ImageViewRGB32& image = ImageViewRGB32(), bool keep_file = false +); + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.cpp b/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.cpp index 79bef4d739..303709d62a 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.cpp +++ b/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.cpp @@ -1,15 +1,15 @@ -/* Sender Notification Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "SenderNotificationTable.h" - -namespace PokemonAutomation{ - - - - - -} +/* Sender Notification Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SenderNotificationTable.h" + +namespace PokemonAutomation{ + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.h b/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.h index f39d20c2b1..57b691db2c 100644 --- a/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.h +++ b/SerialPrograms/Source/CommonFramework/Notifications/SenderNotificationTable.h @@ -1,23 +1,23 @@ -/* Sender Notification Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SenderNotificationTable_H -#define PokemonAutomation_SenderNotificationTable_H - -#include -#include -#include "Common/Cpp/Options/ConfigOption.h" -#include "Common/Qt/AutoHeightTable.h" - -namespace PokemonAutomation{ - - - - - - -} -#endif +/* Sender Notification Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SenderNotificationTable_H +#define PokemonAutomation_SenderNotificationTable_H + +#include +#include +#include "Common/Cpp/Options/ConfigOption.h" +#include "Common/Qt/AutoHeightTable.h" + +namespace PokemonAutomation{ + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h b/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h index b18ee97e99..2da321bbf1 100644 --- a/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/CheckForUpdatesOption.h @@ -1,67 +1,67 @@ -/* Check for Updates Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_CheckForUpdatesOption_H -#define PokemonAutomation_Options_CheckForUpdatesOption_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonFramework/Globals.h" - -namespace PokemonAutomation{ - - -class CheckForUpdatesOption : public GroupOption{ -public: - CheckForUpdatesOption() - : GroupOption( - "Check for Updates", - LockMode::UNLOCK_WHILE_RUNNING, - EnableMode::ALWAYS_ENABLED, - true - ) - , RELEASE0( - "New Releases:
Automatically check for new stable releases.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , PUBLIC_BETA0( - "Public Betas:
Automatically check for new public betas.", - LockMode::UNLOCK_WHILE_RUNNING, - IS_BETA_VERSION - ) - , PRIVATE_BETA0( - "Private Betas:
Automatically check for new private betas.", - LockMode::UNLOCK_WHILE_RUNNING, - IS_BETA_VERSION - ) - ,SKIP_VERSION( - false, - "Skip this Version:
Skip this version and don't notify until the next update.", - LockMode::UNLOCK_WHILE_RUNNING, - "", - "0.50.0" - ) - { - PA_ADD_OPTION(RELEASE0); - PA_ADD_OPTION(PUBLIC_BETA0); - if (IS_BETA_VERSION){ - PA_ADD_OPTION(PRIVATE_BETA0); - } - PA_ADD_OPTION(SKIP_VERSION); - } - -public: - BooleanCheckBoxOption RELEASE0; - BooleanCheckBoxOption PUBLIC_BETA0; - BooleanCheckBoxOption PRIVATE_BETA0; - StringOption SKIP_VERSION; -}; - - -} -#endif +/* Check for Updates Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_CheckForUpdatesOption_H +#define PokemonAutomation_Options_CheckForUpdatesOption_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Globals.h" + +namespace PokemonAutomation{ + + +class CheckForUpdatesOption : public GroupOption{ +public: + CheckForUpdatesOption() + : GroupOption( + "Check for Updates", + LockMode::UNLOCK_WHILE_RUNNING, + EnableMode::ALWAYS_ENABLED, + true + ) + , RELEASE0( + "New Releases:
Automatically check for new stable releases.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , PUBLIC_BETA0( + "Public Betas:
Automatically check for new public betas.", + LockMode::UNLOCK_WHILE_RUNNING, + IS_BETA_VERSION + ) + , PRIVATE_BETA0( + "Private Betas:
Automatically check for new private betas.", + LockMode::UNLOCK_WHILE_RUNNING, + IS_BETA_VERSION + ) + ,SKIP_VERSION( + false, + "Skip this Version:
Skip this version and don't notify until the next update.", + LockMode::UNLOCK_WHILE_RUNNING, + "", + "0.50.0" + ) + { + PA_ADD_OPTION(RELEASE0); + PA_ADD_OPTION(PUBLIC_BETA0); + if (IS_BETA_VERSION){ + PA_ADD_OPTION(PRIVATE_BETA0); + } + PA_ADD_OPTION(SKIP_VERSION); + } + +public: + BooleanCheckBoxOption RELEASE0; + BooleanCheckBoxOption PUBLIC_BETA0; + BooleanCheckBoxOption PRIVATE_BETA0; + StringOption SKIP_VERSION; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h b/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h index 503f48543e..87ae4043e3 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/PerformanceOptions.h @@ -1,85 +1,85 @@ -/* Performance Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PerformanceOptions_H -#define PokemonAutomation_PerformanceOptions_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "ProcessPriorityOption.h" -#include "ProcessorLevelOption.h" - -namespace PokemonAutomation{ - - -class PerformanceOptions : public GroupOption{ -public: - PerformanceOptions() - : GroupOption( - "Performance", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , PRECISE_WAKE_MARGIN( - "Precise Wake Time Margin:
" - "Some operations require a thread to wake up at a very precise time - " - "more precise than what the operating system's scheduler can provide. " - "This option will force such operations to wake up this many " - "microseconds earlier, then busy wait until the time is reached. " - "The sys-botbase controller is an example of something that requires " - "extremely precise wake times.", - LockMode::UNLOCK_WHILE_RUNNING, - "2000 us" - ) - , REALTIME_THREAD_PRIORITY( - "Realtime Thread Priority:
" - "Thread priority of real-time threads. (UI thread, audio threads)
" - "Restart the program for this to fully take effect.", - DEFAULT_PRIORITY_REALTIME - ) - , REALTIME_INFERENCE_PRIORITY( - "Inference Priority:
" - "Thread priority of realtime inference threads that must run fast " - "enough to keep a program working properly.", - DEFAULT_PRIORITY_REALTIME_INFERENCE - ) - , NORMAL_INFERENCE_PRIORITY( - "normal Inference Priority:
" - "Thread priority of non-realtime inference threads that can be slow " - "without negatively affecting a program.", - DEFAULT_PRIORITY_NORMAL_INFERENCE - ) - , COMPUTE_PRIORITY( - "Compute Priority:
" - "Thread priority of computation threads.", - DEFAULT_PRIORITY_COMPUTE - ) - { - PA_ADD_OPTION(PRECISE_WAKE_MARGIN); - PA_ADD_OPTION(REALTIME_THREAD_PRIORITY); - PA_ADD_OPTION(REALTIME_INFERENCE_PRIORITY); - PA_ADD_OPTION(NORMAL_INFERENCE_PRIORITY); - PA_ADD_OPTION(COMPUTE_PRIORITY); - PA_ADD_OPTION(PROCESSOR_LEVEL); - } - -public: - MicrosecondsOption PRECISE_WAKE_MARGIN; - - ThreadPriorityOption REALTIME_THREAD_PRIORITY; - ThreadPriorityOption REALTIME_INFERENCE_PRIORITY; - ThreadPriorityOption NORMAL_INFERENCE_PRIORITY; - ThreadPriorityOption COMPUTE_PRIORITY; - - ProcessorLevelOption PROCESSOR_LEVEL; -}; - - - - - -} -#endif +/* Performance Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PerformanceOptions_H +#define PokemonAutomation_PerformanceOptions_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "ProcessPriorityOption.h" +#include "ProcessorLevelOption.h" + +namespace PokemonAutomation{ + + +class PerformanceOptions : public GroupOption{ +public: + PerformanceOptions() + : GroupOption( + "Performance", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , PRECISE_WAKE_MARGIN( + "Precise Wake Time Margin:
" + "Some operations require a thread to wake up at a very precise time - " + "more precise than what the operating system's scheduler can provide. " + "This option will force such operations to wake up this many " + "microseconds earlier, then busy wait until the time is reached. " + "The sys-botbase controller is an example of something that requires " + "extremely precise wake times.", + LockMode::UNLOCK_WHILE_RUNNING, + "2000 us" + ) + , REALTIME_THREAD_PRIORITY( + "Realtime Thread Priority:
" + "Thread priority of real-time threads. (UI thread, audio threads)
" + "Restart the program for this to fully take effect.", + DEFAULT_PRIORITY_REALTIME + ) + , REALTIME_INFERENCE_PRIORITY( + "Inference Priority:
" + "Thread priority of realtime inference threads that must run fast " + "enough to keep a program working properly.", + DEFAULT_PRIORITY_REALTIME_INFERENCE + ) + , NORMAL_INFERENCE_PRIORITY( + "normal Inference Priority:
" + "Thread priority of non-realtime inference threads that can be slow " + "without negatively affecting a program.", + DEFAULT_PRIORITY_NORMAL_INFERENCE + ) + , COMPUTE_PRIORITY( + "Compute Priority:
" + "Thread priority of computation threads.", + DEFAULT_PRIORITY_COMPUTE + ) + { + PA_ADD_OPTION(PRECISE_WAKE_MARGIN); + PA_ADD_OPTION(REALTIME_THREAD_PRIORITY); + PA_ADD_OPTION(REALTIME_INFERENCE_PRIORITY); + PA_ADD_OPTION(NORMAL_INFERENCE_PRIORITY); + PA_ADD_OPTION(COMPUTE_PRIORITY); + PA_ADD_OPTION(PROCESSOR_LEVEL); + } + +public: + MicrosecondsOption PRECISE_WAKE_MARGIN; + + ThreadPriorityOption REALTIME_THREAD_PRIORITY; + ThreadPriorityOption REALTIME_INFERENCE_PRIORITY; + ThreadPriorityOption NORMAL_INFERENCE_PRIORITY; + ThreadPriorityOption COMPUTE_PRIORITY; + + ProcessorLevelOption PROCESSOR_LEVEL; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h index a66e0f0749..db86e22849 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessPriorityOption.h @@ -1,38 +1,38 @@ -/* Process Priority Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProcessPriorityOption_H -#define PokemonAutomation_ProcessPriorityOption_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "CommonFramework/Environment/Environment.h" - -namespace PokemonAutomation{ - - - - -class ThreadPriorityOption : public EnumDropdownOption{ -public: - ThreadPriorityOption(std::string label, ThreadPriority default_priority) - : EnumDropdownOption( - std::move(label), - PRIORITY_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_priority - ) - {} - void set_on_this_thread() const{ - set_thread_priority(*this); - } -}; - - - - -} -#endif +/* Process Priority Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProcessPriorityOption_H +#define PokemonAutomation_ProcessPriorityOption_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "CommonFramework/Environment/Environment.h" + +namespace PokemonAutomation{ + + + + +class ThreadPriorityOption : public EnumDropdownOption{ +public: + ThreadPriorityOption(std::string label, ThreadPriority default_priority) + : EnumDropdownOption( + std::move(label), + PRIORITY_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_priority + ) + {} + void set_on_this_thread() const{ + set_thread_priority(*this); + } +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.cpp b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.cpp index 2631e6f611..82874a3db9 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.cpp @@ -1,96 +1,96 @@ -/* Processor Level Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Environment/Environment.h" -#include "CommonFramework/Logging/Logger.h" -#include "ProcessorLevelOption.h" - -namespace PokemonAutomation{ - - - -size_t get_default_ProcessorLevel_index(){ - const std::vector& LEVELS = AVAILABLE_CAPABILITIES(); - size_t best = 0; - for (size_t c = 0; c < LEVELS.size(); c++){ - if (LEVELS[c].available){ - best = c; - } - } - return best; -} - - - -ProcessorLevelOption::ProcessorLevelOption() - : IntegerEnumDropdownOption( - "Processor Specific Optimization:
" - "Note that this only applies to this binary. External dependencies may ignore this and use higher instructions anyway.", - CAPABILITIES_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - get_default_ProcessorLevel_index() - ) -{ - set_global(); -} -bool ProcessorLevelOption::set_value(size_t value){ - if (!IntegerEnumDropdownOption::set_value(value)){ - return false; - } - set_global(value); - return true; -} -void ProcessorLevelOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - std::string processor_string = get_processor_name(); - global_logger_tagged().log("Processor String: " + processor_string); - - const std::string* saved_string = obj->get_string("ProcessorString"); - if (saved_string == nullptr){ - global_logger_tagged().log("No processor string saved.", COLOR_RED); - return; - } - - if (processor_string == *saved_string){ - global_logger_tagged().log("Processor string matches. Using stored processor level.", COLOR_BLUE); - const JsonValue* value = obj->get_value("Level"); - if (value){ - IntegerEnumDropdownOption::load_json(*value); - } - set_global(); - }else{ - global_logger_tagged().log("Mismatched processor string. Will not load saved processor level.", COLOR_RED); - } -} -JsonValue ProcessorLevelOption::to_json() const{ - JsonObject obj; - obj["Level"] = IntegerEnumDropdownOption::to_json(); - obj["ProcessorString"] = get_processor_name(); - return obj; -} -void ProcessorLevelOption::set_global(){ - set_global(current_value()); -} -void ProcessorLevelOption::set_global(size_t index){ - const auto& LIST = AVAILABLE_CAPABILITIES(); - if ((size_t)index >= LIST.size()){ - return; - } - CPU_CAPABILITY_CURRENT = LIST[index].features; - global_logger_tagged().log(std::string("Processor capability set to: ") + LIST[index].display, COLOR_BLUE); -} - - - - - - -} +/* Processor Level Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Environment/Environment.h" +#include "CommonFramework/Logging/Logger.h" +#include "ProcessorLevelOption.h" + +namespace PokemonAutomation{ + + + +size_t get_default_ProcessorLevel_index(){ + const std::vector& LEVELS = AVAILABLE_CAPABILITIES(); + size_t best = 0; + for (size_t c = 0; c < LEVELS.size(); c++){ + if (LEVELS[c].available){ + best = c; + } + } + return best; +} + + + +ProcessorLevelOption::ProcessorLevelOption() + : IntegerEnumDropdownOption( + "Processor Specific Optimization:
" + "Note that this only applies to this binary. External dependencies may ignore this and use higher instructions anyway.", + CAPABILITIES_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + get_default_ProcessorLevel_index() + ) +{ + set_global(); +} +bool ProcessorLevelOption::set_value(size_t value){ + if (!IntegerEnumDropdownOption::set_value(value)){ + return false; + } + set_global(value); + return true; +} +void ProcessorLevelOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + std::string processor_string = get_processor_name(); + global_logger_tagged().log("Processor String: " + processor_string); + + const std::string* saved_string = obj->get_string("ProcessorString"); + if (saved_string == nullptr){ + global_logger_tagged().log("No processor string saved.", COLOR_RED); + return; + } + + if (processor_string == *saved_string){ + global_logger_tagged().log("Processor string matches. Using stored processor level.", COLOR_BLUE); + const JsonValue* value = obj->get_value("Level"); + if (value){ + IntegerEnumDropdownOption::load_json(*value); + } + set_global(); + }else{ + global_logger_tagged().log("Mismatched processor string. Will not load saved processor level.", COLOR_RED); + } +} +JsonValue ProcessorLevelOption::to_json() const{ + JsonObject obj; + obj["Level"] = IntegerEnumDropdownOption::to_json(); + obj["ProcessorString"] = get_processor_name(); + return obj; +} +void ProcessorLevelOption::set_global(){ + set_global(current_value()); +} +void ProcessorLevelOption::set_global(size_t index){ + const auto& LIST = AVAILABLE_CAPABILITIES(); + if ((size_t)index >= LIST.size()){ + return; + } + CPU_CAPABILITY_CURRENT = LIST[index].features; + global_logger_tagged().log(std::string("Processor capability set to: ") + LIST[index].display, COLOR_BLUE); +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.h b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.h index 28df1ee6bd..cb8473ee99 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/ProcessorLevelOption.h @@ -1,32 +1,32 @@ -/* Processor Level Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProcessorLevelOption_H -#define PokemonAutomation_ProcessorLevelOption_H - -#include "Common/Cpp/CpuId/CpuId.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ - - -class ProcessorLevelOption : public IntegerEnumDropdownOption{ -public: - ProcessorLevelOption(); - - virtual bool set_value(size_t value) override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - void set_global(); - void set_global(size_t value); -}; - - - -} -#endif +/* Processor Level Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProcessorLevelOption_H +#define PokemonAutomation_ProcessorLevelOption_H + +#include "Common/Cpp/CpuId/CpuId.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ + + +class ProcessorLevelOption : public IntegerEnumDropdownOption{ +public: + ProcessorLevelOption(); + + virtual bool set_value(size_t value) override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + void set_global(); + void set_global(size_t value); +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp index bd7bb40f3c..c4cd6cb21b 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.cpp @@ -1,80 +1,80 @@ -/* Sleep Suppress Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "SleepSuppressOption.h" - -namespace PokemonAutomation{ - - -SleepSuppressOption::SleepSuppressOption(std::string label, SleepSuppress default_value) - : EnumDropdownOption( - std::move(label), - { - {SleepSuppress::NONE, "none", "Do not suppress sleep or screensaver."}, -#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP - {SleepSuppress::NO_SLEEP, "no-sleep", "Prevent computer from sleeping, but allow screen to turn off."}, -#endif - {SleepSuppress::SCREEN_ON, "screen-on", "Keep the screen on."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - default_value - ) -{} - - -SleepSuppressOptions::~SleepSuppressOptions(){ - PROGRAM_RUNNING.remove_listener(*this); - IDLE.remove_listener(*this); -} -SleepSuppressOptions::SleepSuppressOptions() - : GroupOption( - "Suppress Screensaver/Sleep:", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , IDLE("No Program Running:", SleepSuppress::NONE) -#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP - , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NO_SLEEP) -#else - , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NONE) -#endif - , m_idle_scope(IDLE) -{ - PA_ADD_OPTION(IDLE); - PA_ADD_OPTION(PROGRAM_RUNNING); - - IDLE.add_listener(*this); - PROGRAM_RUNNING.add_listener(*this); -} - -void SleepSuppressOptions::on_config_value_changed(void* object){ - if (object == &IDLE){ - m_idle_scope = IDLE; - PROGRAM_RUNNING.set_value(std::max(IDLE.current_value(), PROGRAM_RUNNING.current_value())); - }else{ - IDLE.set_value(std::min(IDLE.current_value(), PROGRAM_RUNNING.current_value())); - } -} - - -} - - - - - - - - - - - - - - - - - +/* Sleep Suppress Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SleepSuppressOption.h" + +namespace PokemonAutomation{ + + +SleepSuppressOption::SleepSuppressOption(std::string label, SleepSuppress default_value) + : EnumDropdownOption( + std::move(label), + { + {SleepSuppress::NONE, "none", "Do not suppress sleep or screensaver."}, +#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP + {SleepSuppress::NO_SLEEP, "no-sleep", "Prevent computer from sleeping, but allow screen to turn off."}, +#endif + {SleepSuppress::SCREEN_ON, "screen-on", "Keep the screen on."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + default_value + ) +{} + + +SleepSuppressOptions::~SleepSuppressOptions(){ + PROGRAM_RUNNING.remove_listener(*this); + IDLE.remove_listener(*this); +} +SleepSuppressOptions::SleepSuppressOptions() + : GroupOption( + "Suppress Screensaver/Sleep:", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , IDLE("No Program Running:", SleepSuppress::NONE) +#ifdef PA_ENABLE_SLEEP_SUPPRESS_NO_SLEEP + , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NO_SLEEP) +#else + , PROGRAM_RUNNING("Program is Running:", SleepSuppress::NONE) +#endif + , m_idle_scope(IDLE) +{ + PA_ADD_OPTION(IDLE); + PA_ADD_OPTION(PROGRAM_RUNNING); + + IDLE.add_listener(*this); + PROGRAM_RUNNING.add_listener(*this); +} + +void SleepSuppressOptions::on_config_value_changed(void* object){ + if (object == &IDLE){ + m_idle_scope = IDLE; + PROGRAM_RUNNING.set_value(std::max(IDLE.current_value(), PROGRAM_RUNNING.current_value())); + }else{ + IDLE.set_value(std::min(IDLE.current_value(), PROGRAM_RUNNING.current_value())); + } +} + + +} + + + + + + + + + + + + + + + + + diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h index a4422d5a65..338dc53ed5 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/SleepSuppressOption.h @@ -1,41 +1,41 @@ -/* Sleep Suppress Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SleepSuppressOption_H -#define PokemonAutomation_SleepSuppressOption_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "CommonFramework/Environment/SystemSleep.h" - -namespace PokemonAutomation{ - - - -class SleepSuppressOption : public EnumDropdownOption{ -public: - SleepSuppressOption(std::string label, SleepSuppress default_value); -}; - - -class SleepSuppressOptions : public GroupOption, public ConfigOption::Listener{ -public: - ~SleepSuppressOptions(); - SleepSuppressOptions(); - - virtual void on_config_value_changed(void* object) override; - -public: - SleepSuppressOption IDLE; - SleepSuppressOption PROGRAM_RUNNING; - -private: - SleepSuppressScope m_idle_scope; -}; - - -} -#endif +/* Sleep Suppress Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SleepSuppressOption_H +#define PokemonAutomation_SleepSuppressOption_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "CommonFramework/Environment/SystemSleep.h" + +namespace PokemonAutomation{ + + + +class SleepSuppressOption : public EnumDropdownOption{ +public: + SleepSuppressOption(std::string label, SleepSuppress default_value); +}; + + +class SleepSuppressOptions : public GroupOption, public ConfigOption::Listener{ +public: + ~SleepSuppressOptions(); + SleepSuppressOptions(); + + virtual void on_config_value_changed(void* object) override; + +public: + SleepSuppressOption IDLE; + SleepSuppressOption PROGRAM_RUNNING; + +private: + SleepSuppressScope m_idle_scope; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.cpp b/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.cpp index 951320f89b..dd6b1b5f2f 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.cpp @@ -1,116 +1,116 @@ -/* Theme Selector Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Windows/DpiScaler.h" -#include "ThemeSelectorOption.h" - -namespace PokemonAutomation{ - - -size_t current_theme = 0; - - -void set_theme(size_t index){ - if (index == current_theme){ - return; - } - QString stylesheet; - switch (index){ - case 0: - break; - case 1: - stylesheet = ":qdarkstyle/dark/darkstyle.qss"; - break; - } - - if (!stylesheet.isEmpty()){ - QFile f(stylesheet); - f.open(QFile::ReadOnly | QFile::Text); - QTextStream ts(&f); - stylesheet = scale_dpi_stylesheet(ts.readAll()); - } - - QApplication* app = static_cast(QApplication::instance()); - app->setStyleSheet(stylesheet); - - current_theme = index; -} - - -ThemeSelectorOption::ThemeSelectorOption() - : IntegerEnumDropdownOption( - "Theme:", - { - {0, "default", "Default"}, - {1, "dark", "Dark Mode"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) -{} - -bool ThemeSelectorOption::set_value(size_t index){ - if (!IntegerEnumDropdownOption::set_value(index)){ - return false; - } - set_theme(index); - return true; -} -void ThemeSelectorOption::load_json(const JsonValue& json){ - IntegerEnumDropdownOption::load_json(json); - set_theme(current_value()); -} - - - -#if 1 -Color theme_friendly_darkblue(){ - if (current_theme == 1){ - return Color(0xff0080ff); - } - return COLOR_DARK_BLUE; -} -#endif -std::string html_color_text(const std::string& text, Color color){ - if (color == Color()){ - return text; - } - const char HEX[] = "0123456789abcdef"; - uint32_t rgb = (uint32_t)color; - std::string str; - str += HEX[(rgb >> 20) & 15]; - str += HEX[(rgb >> 16) & 15]; - str += HEX[(rgb >> 12) & 15]; - str += HEX[(rgb >> 8) & 15]; - str += HEX[(rgb >> 4) & 15]; - str += HEX[(rgb >> 0) & 15]; - return "" + text + ""; -} -std::string make_text_url(const std::string& url, const std::string& text){ -#if 0 - switch (current_theme){ - case 0: - return "" + text + ""; - case 1: - return "" + text + ""; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid theme #."); -#endif - return "" + text + ""; -} - - - - - - - - -} +/* Theme Selector Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Windows/DpiScaler.h" +#include "ThemeSelectorOption.h" + +namespace PokemonAutomation{ + + +size_t current_theme = 0; + + +void set_theme(size_t index){ + if (index == current_theme){ + return; + } + QString stylesheet; + switch (index){ + case 0: + break; + case 1: + stylesheet = ":qdarkstyle/dark/darkstyle.qss"; + break; + } + + if (!stylesheet.isEmpty()){ + QFile f(stylesheet); + f.open(QFile::ReadOnly | QFile::Text); + QTextStream ts(&f); + stylesheet = scale_dpi_stylesheet(ts.readAll()); + } + + QApplication* app = static_cast(QApplication::instance()); + app->setStyleSheet(stylesheet); + + current_theme = index; +} + + +ThemeSelectorOption::ThemeSelectorOption() + : IntegerEnumDropdownOption( + "Theme:", + { + {0, "default", "Default"}, + {1, "dark", "Dark Mode"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) +{} + +bool ThemeSelectorOption::set_value(size_t index){ + if (!IntegerEnumDropdownOption::set_value(index)){ + return false; + } + set_theme(index); + return true; +} +void ThemeSelectorOption::load_json(const JsonValue& json){ + IntegerEnumDropdownOption::load_json(json); + set_theme(current_value()); +} + + + +#if 1 +Color theme_friendly_darkblue(){ + if (current_theme == 1){ + return Color(0xff0080ff); + } + return COLOR_DARK_BLUE; +} +#endif +std::string html_color_text(const std::string& text, Color color){ + if (color == Color()){ + return text; + } + const char HEX[] = "0123456789abcdef"; + uint32_t rgb = (uint32_t)color; + std::string str; + str += HEX[(rgb >> 20) & 15]; + str += HEX[(rgb >> 16) & 15]; + str += HEX[(rgb >> 12) & 15]; + str += HEX[(rgb >> 8) & 15]; + str += HEX[(rgb >> 4) & 15]; + str += HEX[(rgb >> 0) & 15]; + return "" + text + ""; +} +std::string make_text_url(const std::string& url, const std::string& text){ +#if 0 + switch (current_theme){ + case 0: + return "" + text + ""; + case 1: + return "" + text + ""; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid theme #."); +#endif + return "" + text + ""; +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.h b/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.h index 78709ebf80..fa5ae8003e 100644 --- a/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/Environment/ThemeSelectorOption.h @@ -1,32 +1,32 @@ -/* Theme Selector Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ThemeSelectorOption_H -#define PokemonAutomation_ThemeSelectorOption_H - -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ - - -class ThemeSelectorOption : public IntegerEnumDropdownOption{ -public: - ThemeSelectorOption(); - - virtual bool set_value(size_t value) override; - virtual void load_json(const JsonValue& json) override; -}; - - -Color theme_friendly_darkblue(); -std::string html_color_text(const std::string& text, Color color); -std::string make_text_url(const std::string& url, const std::string& text); - - - -} -#endif +/* Theme Selector Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ThemeSelectorOption_H +#define PokemonAutomation_ThemeSelectorOption_H + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ + + +class ThemeSelectorOption : public IntegerEnumDropdownOption{ +public: + ThemeSelectorOption(); + + virtual bool set_value(size_t value) override; + virtual void load_json(const JsonValue& json) override; +}; + + +Color theme_friendly_darkblue(); +std::string html_color_text(const std::string& text, Color color); +std::string make_text_url(const std::string& url, const std::string& text); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.cpp b/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.cpp index d998c6c78b..2bb6cbeed2 100644 --- a/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.cpp @@ -1,102 +1,102 @@ -/* Label Cell - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "LabelCellOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct LabelCellOption::Data{ -// mutable SpinLock m_lock; - std::string m_text; -// ImageRGB32 m_icon_owner; - ImageViewRGB32 m_icon; - Resolution m_resolution; - - Data(std::string text) - : m_text(std::move(text)) - {} - Data(std::string text, const ImageViewRGB32& icon) - : m_text(std::move(text)) - , m_icon(icon) - {} - Data(std::string text, const ImageViewRGB32& icon, size_t icon_size) - : m_text(std::move(text)) - , m_icon(icon) - { - size_t width = icon.width(); - size_t height = icon.height(); - if (width < height){ - width = width * icon_size / height; - height = icon_size; - }else{ - height = height * icon_size / width; - width = icon_size; - } - m_resolution.width = width; - m_resolution.height = height; - } -// Data(std::string text, ImageRGB32 icon) -// : m_text(std::move(text)) -// , m_icon_owner(std::move(icon)) -// , m_icon(m_icon_owner) -// {} -}; - - -LabelCellOption::~LabelCellOption() = default; -LabelCellOption::LabelCellOption( - LockMode lock_while_running, - std::string text -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, std::move(text)) -{} -LabelCellOption::LabelCellOption( - LockMode lock_while_running, - std::string text, const ImageViewRGB32& icon -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, std::move(text), icon) -{} -LabelCellOption::LabelCellOption( - LockMode lock_while_running, - std::string text, const ImageViewRGB32& icon, size_t icon_size -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, std::move(text), icon, icon_size) -{} -//LabelCellOption::LabelCellOption(std::string text, ImageRGB32 icon) -// : m_data(CONSTRUCT_TOKEN, std::move(text), std::move(icon)) -//{} -const std::string& LabelCellOption::text() const{ - return m_data->m_text; -} -const ImageViewRGB32& LabelCellOption::icon() const{ - return m_data->m_icon; -} -Resolution LabelCellOption::resolution() const{ - return m_data->m_resolution; -} -void LabelCellOption::load_json(const JsonValue&){ -} -JsonValue LabelCellOption::to_json() const{ - return JsonValue(); -} - - - - - -} +/* Label Cell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "LabelCellOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct LabelCellOption::Data{ +// mutable SpinLock m_lock; + std::string m_text; +// ImageRGB32 m_icon_owner; + ImageViewRGB32 m_icon; + Resolution m_resolution; + + Data(std::string text) + : m_text(std::move(text)) + {} + Data(std::string text, const ImageViewRGB32& icon) + : m_text(std::move(text)) + , m_icon(icon) + {} + Data(std::string text, const ImageViewRGB32& icon, size_t icon_size) + : m_text(std::move(text)) + , m_icon(icon) + { + size_t width = icon.width(); + size_t height = icon.height(); + if (width < height){ + width = width * icon_size / height; + height = icon_size; + }else{ + height = height * icon_size / width; + width = icon_size; + } + m_resolution.width = width; + m_resolution.height = height; + } +// Data(std::string text, ImageRGB32 icon) +// : m_text(std::move(text)) +// , m_icon_owner(std::move(icon)) +// , m_icon(m_icon_owner) +// {} +}; + + +LabelCellOption::~LabelCellOption() = default; +LabelCellOption::LabelCellOption( + LockMode lock_while_running, + std::string text +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, std::move(text)) +{} +LabelCellOption::LabelCellOption( + LockMode lock_while_running, + std::string text, const ImageViewRGB32& icon +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, std::move(text), icon) +{} +LabelCellOption::LabelCellOption( + LockMode lock_while_running, + std::string text, const ImageViewRGB32& icon, size_t icon_size +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, std::move(text), icon, icon_size) +{} +//LabelCellOption::LabelCellOption(std::string text, ImageRGB32 icon) +// : m_data(CONSTRUCT_TOKEN, std::move(text), std::move(icon)) +//{} +const std::string& LabelCellOption::text() const{ + return m_data->m_text; +} +const ImageViewRGB32& LabelCellOption::icon() const{ + return m_data->m_icon; +} +Resolution LabelCellOption::resolution() const{ + return m_data->m_resolution; +} +void LabelCellOption::load_json(const JsonValue&){ +} +JsonValue LabelCellOption::to_json() const{ + return JsonValue(); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.h b/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.h index ca373bade3..e6ee7be359 100644 --- a/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/LabelCellOption.h @@ -1,67 +1,67 @@ -/* Label Cell - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_LabelCellOption_H -#define PokemonAutomation_Options_LabelCellOption_H - -#include "Common/Cpp/ImageResolution.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -//#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - - -class LabelCellOption : public ConfigOption{ -public: - ~LabelCellOption(); - - // Make label with no icon. - LabelCellOption( - LockMode lock_while_running, - std::string text - ); - - // Make label with the icon in its original resolution. - LabelCellOption( - LockMode lock_while_running, - std::string text, const ImageViewRGB32& icon - ); - - // Make label with icon and scale it so that the largest dimension is "icon_size" pixels. - LabelCellOption( - LockMode lock_while_running, - std::string text, const ImageViewRGB32& icon, size_t icon_size - ); - -// LabelCellOption(std::string text, ImageRGB32 icon); - - const std::string& text() const; - const ImageViewRGB32& icon() const; - Resolution resolution() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override{} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - - - -} -#endif - - +/* Label Cell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_LabelCellOption_H +#define PokemonAutomation_Options_LabelCellOption_H + +#include "Common/Cpp/ImageResolution.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +//#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + + +class LabelCellOption : public ConfigOption{ +public: + ~LabelCellOption(); + + // Make label with no icon. + LabelCellOption( + LockMode lock_while_running, + std::string text + ); + + // Make label with the icon in its original resolution. + LabelCellOption( + LockMode lock_while_running, + std::string text, const ImageViewRGB32& icon + ); + + // Make label with icon and scale it so that the largest dimension is "icon_size" pixels. + LabelCellOption( + LockMode lock_while_running, + std::string text, const ImageViewRGB32& icon, size_t icon_size + ); + +// LabelCellOption(std::string text, ImageRGB32 icon); + + const std::string& text() const; + const ImageViewRGB32& icon() const; + Resolution resolution() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override{} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + + + +} +#endif + + diff --git a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp index 4786d1dab9..a2c25a3744 100644 --- a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.cpp @@ -1,60 +1,60 @@ -/* Label Cell - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "LabelCellWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* LabelCellOption::make_QtWidget(QWidget& parent){ - return new LabelCellWidget(parent, *this); -} - - -LabelCellWidget::~LabelCellWidget(){ -} -LabelCellWidget::LabelCellWidget(QWidget& parent, LabelCellOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) -// , m_value(value) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); -// layout->setAlignment(Qt::AlignLeft); - - if (value.icon()){ - m_icon = new QLabel(this); - Resolution resolution = value.resolution(); -// cout << resolution.width << " x " << resolution.height << endl; - QPixmap pixmap; - if (resolution.width == 0 || resolution.height == 0){ - pixmap = QPixmap::fromImage(value.icon().to_QImage_ref()); - }else{ - pixmap = QPixmap::fromImage(value.icon().scaled_to_QImage(resolution.width, resolution.height)); - } - m_icon->setPixmap(pixmap); - m_icon->setAlignment(Qt::AlignCenter); - layout->addWidget(m_icon); - } - - m_text = new QLabel(QString::fromStdString(value.text()), this); - layout->addWidget(m_text, 1); -// text->setTextInteractionFlags(Qt::TextBrowserInteraction); -// m_text->setOpenExternalLinks(true); -} - - - - -} +/* Label Cell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "LabelCellWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* LabelCellOption::make_QtWidget(QWidget& parent){ + return new LabelCellWidget(parent, *this); +} + + +LabelCellWidget::~LabelCellWidget(){ +} +LabelCellWidget::LabelCellWidget(QWidget& parent, LabelCellOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) +// , m_value(value) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); +// layout->setAlignment(Qt::AlignLeft); + + if (value.icon()){ + m_icon = new QLabel(this); + Resolution resolution = value.resolution(); +// cout << resolution.width << " x " << resolution.height << endl; + QPixmap pixmap; + if (resolution.width == 0 || resolution.height == 0){ + pixmap = QPixmap::fromImage(value.icon().to_QImage_ref()); + }else{ + pixmap = QPixmap::fromImage(value.icon().scaled_to_QImage(resolution.width, resolution.height)); + } + m_icon->setPixmap(pixmap); + m_icon->setAlignment(Qt::AlignCenter); + layout->addWidget(m_icon); + } + + m_text = new QLabel(QString::fromStdString(value.text()), this); + layout->addWidget(m_text, 1); +// text->setTextInteractionFlags(Qt::TextBrowserInteraction); +// m_text->setOpenExternalLinks(true); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h index 07982208b1..f9fa4c8677 100644 --- a/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h +++ b/SerialPrograms/Source/CommonFramework/Options/QtWidget/LabelCellWidget.h @@ -1,35 +1,35 @@ -/* Label Cell - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_LabelCellWidget_H -#define PokemonAutomation_Options_LabelCellWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/Options/LabelCellOption.h" - -class QLabel; - -namespace PokemonAutomation{ - - - -class LabelCellWidget : public QWidget, public ConfigWidget{ -public: - ~LabelCellWidget(); - LabelCellWidget(QWidget& parent, LabelCellOption& value); - -private: -// LabelCellOption& m_value; - QLabel* m_icon = nullptr; - QLabel* m_text; -}; - - - - -} -#endif +/* Label Cell + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_LabelCellWidget_H +#define PokemonAutomation_Options_LabelCellWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/Options/LabelCellOption.h" + +class QLabel; + +namespace PokemonAutomation{ + + + +class LabelCellWidget : public QWidget, public ConfigWidget{ +public: + ~LabelCellWidget(); + LabelCellWidget(QWidget& parent, LabelCellOption& value); + +private: +// LabelCellOption& m_value; + QLabel* m_icon = nullptr; + QLabel* m_text; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp index af8070551e..5167dfd340 100644 --- a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.cpp @@ -1,34 +1,34 @@ -/* Resolution Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Windows/DpiScaler.h" -#include "ResolutionOption.h" - -namespace PokemonAutomation{ - - -ResolutionOption::ResolutionOption( - std::string label, std::string description, - int default_width, int default_height, - int initial_x_pos, int initial_y_pos -) - : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) - , DESCRIPTION(std::move(description)) - , WIDTH("Width:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(default_width)) - , HEIGHT("Height:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(default_height)) - , X_POS("X-position:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(initial_x_pos)) - , Y_POS("Y-position:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(initial_y_pos)) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(WIDTH); - PA_ADD_OPTION(HEIGHT); - PA_ADD_OPTION(X_POS); - PA_ADD_OPTION(Y_POS); -} - - -} +/* Resolution Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Windows/DpiScaler.h" +#include "ResolutionOption.h" + +namespace PokemonAutomation{ + + +ResolutionOption::ResolutionOption( + std::string label, std::string description, + int default_width, int default_height, + int initial_x_pos, int initial_y_pos +) + : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , DESCRIPTION(std::move(description)) + , WIDTH("Width:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(default_width)) + , HEIGHT("Height:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(default_height)) + , X_POS("X-position:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_width(initial_x_pos)) + , Y_POS("Y-position:", LockMode::LOCK_WHILE_RUNNING, scale_dpi_height(initial_y_pos)) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(WIDTH); + PA_ADD_OPTION(HEIGHT); + PA_ADD_OPTION(X_POS); + PA_ADD_OPTION(Y_POS); +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h index a4ecfeb2e1..ba06ab107f 100644 --- a/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/ResolutionOption.h @@ -1,34 +1,34 @@ -/* Resolution Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Options_ResolutionOption_H -#define PokemonAutomation_Options_ResolutionOption_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/GroupOption.h" - -namespace PokemonAutomation{ - - -class ResolutionOption : public GroupOption{ -public: - ResolutionOption( - std::string label, std::string description, - int default_width, int default_height, - int initial_x_pos, int initial_y_pos - ); - - StaticTextOption DESCRIPTION; - SimpleIntegerOption WIDTH; - SimpleIntegerOption HEIGHT; - SimpleIntegerOption X_POS; - SimpleIntegerOption Y_POS; -}; - - -} -#endif +/* Resolution Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Options_ResolutionOption_H +#define PokemonAutomation_Options_ResolutionOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/GroupOption.h" + +namespace PokemonAutomation{ + + +class ResolutionOption : public GroupOption{ +public: + ResolutionOption( + std::string label, std::string description, + int default_width, int default_height, + int initial_x_pos, int initial_y_pos + ); + + StaticTextOption DESCRIPTION; + SimpleIntegerOption WIDTH; + SimpleIntegerOption HEIGHT; + SimpleIntegerOption X_POS; + SimpleIntegerOption Y_POS; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Options/ScreenshotFormatOption.h b/SerialPrograms/Source/CommonFramework/Options/ScreenshotFormatOption.h index ad351cfb06..bce318a109 100644 --- a/SerialPrograms/Source/CommonFramework/Options/ScreenshotFormatOption.h +++ b/SerialPrograms/Source/CommonFramework/Options/ScreenshotFormatOption.h @@ -1,55 +1,55 @@ -/* Screenshot Format - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ScreenshotFormat_H -#define PokemonAutomation_ScreenshotFormat_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ - - -enum class ImageAttachmentMode{ - NO_SCREENSHOT, - JPG, - PNG, -}; -inline const EnumDropdownDatabase& ImageAttachmentMode_Database(){ - static EnumDropdownDatabase database({ - {ImageAttachmentMode::NO_SCREENSHOT, "none", "No Screenshot."}, - {ImageAttachmentMode::JPG, "jpg", "Attach as .jpg."}, - {ImageAttachmentMode::PNG, "png", "Attach as .png."}, - }); - return database; -} - - - -class ScreenshotCell : public EnumDropdownCell{ -public: - ScreenshotCell(ImageAttachmentMode default_mode = ImageAttachmentMode::JPG) - : EnumDropdownCell( - ImageAttachmentMode_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - default_mode - ) - {} -}; -class ScreenshotOption : public EnumDropdownOption{ -public: - ScreenshotOption(std::string label) - : EnumDropdownOption( - std::move(label), - ImageAttachmentMode_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ImageAttachmentMode::JPG - ) - {} -}; - - -} -#endif +/* Screenshot Format + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ScreenshotFormat_H +#define PokemonAutomation_ScreenshotFormat_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ + + +enum class ImageAttachmentMode{ + NO_SCREENSHOT, + JPG, + PNG, +}; +inline const EnumDropdownDatabase& ImageAttachmentMode_Database(){ + static EnumDropdownDatabase database({ + {ImageAttachmentMode::NO_SCREENSHOT, "none", "No Screenshot."}, + {ImageAttachmentMode::JPG, "jpg", "Attach as .jpg."}, + {ImageAttachmentMode::PNG, "png", "Attach as .png."}, + }); + return database; +} + + + +class ScreenshotCell : public EnumDropdownCell{ +public: + ScreenshotCell(ImageAttachmentMode default_mode = ImageAttachmentMode::JPG) + : EnumDropdownCell( + ImageAttachmentMode_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + default_mode + ) + {} +}; +class ScreenshotOption : public EnumDropdownOption{ +public: + ScreenshotOption(std::string label) + : EnumDropdownOption( + std::move(label), + ImageAttachmentMode_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ImageAttachmentMode::JPG + ) + {} +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.cpp b/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.cpp index 4192cc3e1b..fe9c61ec2a 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.cpp @@ -1,33 +1,33 @@ -/* Panel Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PanelDescriptor.h" -#include "PanelInstance.h" - -namespace PokemonAutomation{ - - -PanelDescriptor::PanelDescriptor( - Color color, - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description -) - : m_color(color) - , m_identifier(std::move(identifier)) - , m_category(std::move(category)) - , m_display_name(std::move(display_name)) - , m_doc_link(std::move(doc_link)) - , m_description(std::move(description)) -{} -std::unique_ptr PanelDescriptor::make_panel() const{ - return std::unique_ptr(new PanelInstance(*this)); -} - - - -} +/* Panel Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PanelDescriptor.h" +#include "PanelInstance.h" + +namespace PokemonAutomation{ + + +PanelDescriptor::PanelDescriptor( + Color color, + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description +) + : m_color(color) + , m_identifier(std::move(identifier)) + , m_category(std::move(category)) + , m_display_name(std::move(display_name)) + , m_doc_link(std::move(doc_link)) + , m_description(std::move(description)) +{} +std::unique_ptr PanelDescriptor::make_panel() const{ + return std::unique_ptr(new PanelInstance(*this)); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.h b/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.h index 262b2a5e81..ce9461be98 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.h +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelDescriptor.h @@ -1,52 +1,52 @@ -/* Panel Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanelDescriptor_H -#define PokemonAutomation_PanelDescriptor_H - -#include -#include -#include "Common/Cpp/Color.h" - -namespace PokemonAutomation{ - -class PanelInstance; - -// Abstract base class that sets the interface for program descriptors. -// A program descriptor contains various information (descriptions) of a program panel UI. -// It can also use function `make_panel()` to create the corresponding panel. -class PanelDescriptor{ -public: - PanelDescriptor( - Color color, - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description - ); - virtual ~PanelDescriptor() = default; - - Color color() const{ return m_color; } - const std::string& identifier() const{ return m_identifier; } - const std::string& category() const{ return m_category; } - const std::string& display_name() const{ return m_display_name; } - const std::string& doc_link() const{ return m_doc_link; } - const std::string& description() const{ return m_description; } - - virtual std::unique_ptr make_panel() const = 0; - -private: - const Color m_color; - const std::string m_identifier; - const std::string m_category; - const std::string m_display_name; - const std::string m_doc_link; - const std::string m_description; -}; - - -} -#endif +/* Panel Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanelDescriptor_H +#define PokemonAutomation_PanelDescriptor_H + +#include +#include +#include "Common/Cpp/Color.h" + +namespace PokemonAutomation{ + +class PanelInstance; + +// Abstract base class that sets the interface for program descriptors. +// A program descriptor contains various information (descriptions) of a program panel UI. +// It can also use function `make_panel()` to create the corresponding panel. +class PanelDescriptor{ +public: + PanelDescriptor( + Color color, + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description + ); + virtual ~PanelDescriptor() = default; + + Color color() const{ return m_color; } + const std::string& identifier() const{ return m_identifier; } + const std::string& category() const{ return m_category; } + const std::string& display_name() const{ return m_display_name; } + const std::string& doc_link() const{ return m_doc_link; } + const std::string& description() const{ return m_description; } + + virtual std::unique_ptr make_panel() const = 0; + +private: + const Color m_color; + const std::string m_identifier; + const std::string m_category; + const std::string m_display_name; + const std::string m_doc_link; + const std::string m_description; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.cpp b/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.cpp index 48167da756..86fc61a3fc 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.cpp @@ -1,40 +1,40 @@ -/* Panel Instance - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "CommonFramework/PersistentSettings.h" -#include "CommonFramework/Logging/Logger.h" -#include "PanelInstance.h" - -namespace PokemonAutomation{ - - -PanelInstance::PanelInstance(const PanelDescriptor& descriptor) - : m_descriptor(descriptor) -{} - -void PanelInstance::from_json(){ - JsonValue* node = PERSISTENT_SETTINGS().panels.get_value(m_descriptor.identifier()); - if (node == nullptr){ - return; - } - from_json(*node); -} -JsonValue PanelInstance::to_json() const{ - return JsonValue(); -} -void PanelInstance::save_settings() const{ - const std::string& identifier = m_descriptor.identifier(); - if (!identifier.empty()){ - PERSISTENT_SETTINGS().panels[identifier] = to_json(); - } - global_logger_tagged().log("Saving panel settings..."); - PERSISTENT_SETTINGS().write(); -} - - - -} +/* Panel Instance + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "CommonFramework/PersistentSettings.h" +#include "CommonFramework/Logging/Logger.h" +#include "PanelInstance.h" + +namespace PokemonAutomation{ + + +PanelInstance::PanelInstance(const PanelDescriptor& descriptor) + : m_descriptor(descriptor) +{} + +void PanelInstance::from_json(){ + JsonValue* node = PERSISTENT_SETTINGS().panels.get_value(m_descriptor.identifier()); + if (node == nullptr){ + return; + } + from_json(*node); +} +JsonValue PanelInstance::to_json() const{ + return JsonValue(); +} +void PanelInstance::save_settings() const{ + const std::string& identifier = m_descriptor.identifier(); + if (!identifier.empty()){ + PERSISTENT_SETTINGS().panels[identifier] = to_json(); + } + global_logger_tagged().log("Saving panel settings..."); + PERSISTENT_SETTINGS().write(); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.h b/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.h index 830d0d9d57..62782fcc0b 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.h +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelInstance.h @@ -1,51 +1,51 @@ -/* Panel Instance - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanelInstance_H -#define PokemonAutomation_PanelInstance_H - -#include "Common/Compiler.h" -#include "PanelDescriptor.h" - -class QWidget; - -namespace PokemonAutomation{ - -class JsonValue; -struct PanelHolder; - -// Class to represent one instance of a pokemon automation program. -// Since programs are listed in the program panels, so this class is called PanelInstance. -// Its derived classes hold all the program data and program logic. It also calls -// `make_widget()` to generate the UI for the program. -class PanelInstance{ -public: - explicit PanelInstance(const PanelDescriptor& descriptor); - virtual ~PanelInstance() = default; - - const PanelDescriptor& descriptor() const{ return m_descriptor; } - - void save_settings() const; - -public: - // The implmentation is defined in "UI/PanelWidget.h" to avoid circular dependency - // Returns a UI/PanelWidget.h:PanelWidget - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder); - -public: - // Serialization - void from_json(); - virtual void from_json([[maybe_unused]] const JsonValue& json){} - virtual JsonValue to_json() const; - -protected: - const PanelDescriptor& m_descriptor; -}; - - - -} -#endif +/* Panel Instance + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanelInstance_H +#define PokemonAutomation_PanelInstance_H + +#include "Common/Compiler.h" +#include "PanelDescriptor.h" + +class QWidget; + +namespace PokemonAutomation{ + +class JsonValue; +struct PanelHolder; + +// Class to represent one instance of a pokemon automation program. +// Since programs are listed in the program panels, so this class is called PanelInstance. +// Its derived classes hold all the program data and program logic. It also calls +// `make_widget()` to generate the UI for the program. +class PanelInstance{ +public: + explicit PanelInstance(const PanelDescriptor& descriptor); + virtual ~PanelInstance() = default; + + const PanelDescriptor& descriptor() const{ return m_descriptor; } + + void save_settings() const; + +public: + // The implmentation is defined in "UI/PanelWidget.h" to avoid circular dependency + // Returns a UI/PanelWidget.h:PanelWidget + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder); + +public: + // Serialization + void from_json(); + virtual void from_json([[maybe_unused]] const JsonValue& json){} + virtual JsonValue to_json() const; + +protected: + const PanelDescriptor& m_descriptor; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelList.cpp b/SerialPrograms/Source/CommonFramework/Panels/PanelList.cpp index 776911a8e0..04b37a0f4f 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelList.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelList.cpp @@ -1,30 +1,30 @@ -/* Panel List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PanelList.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -PanelListDescriptor::PanelListDescriptor( - std::string name, - bool enabled -) - : m_name(std::move(name)) - , m_enabled(enabled) -{} - - - - -} - - +/* Panel List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PanelList.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +PanelListDescriptor::PanelListDescriptor( + std::string name, + bool enabled +) + : m_name(std::move(name)) + , m_enabled(enabled) +{} + + + + +} + + diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelList.h b/SerialPrograms/Source/CommonFramework/Panels/PanelList.h index 1f588b2861..5b101c54f9 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelList.h +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelList.h @@ -1,43 +1,43 @@ -/* Panel List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanelList_H -#define PokemonAutomation_PanelList_H - -#include -#include "CommonFramework/Panels/PanelTools.h" - -class QWidget; - -namespace PokemonAutomation{ - -class PanelListWidget; - - -class PanelListDescriptor{ - using MakePanelEntries = std::vector(*)(); - -public: - virtual ~PanelListDescriptor() = default; - PanelListDescriptor(std::string name, bool enabled = true); - - const std::string& name() const{ return m_name; } - bool enabled() const{ return m_enabled; } - - PanelListWidget* make_QWidget(QWidget& parent, PanelHolder& holder) const; - -protected: - virtual std::vector make_panels() const = 0; - -protected: - std::string m_name; - bool m_enabled; -}; - - - -} -#endif +/* Panel List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanelList_H +#define PokemonAutomation_PanelList_H + +#include +#include "CommonFramework/Panels/PanelTools.h" + +class QWidget; + +namespace PokemonAutomation{ + +class PanelListWidget; + + +class PanelListDescriptor{ + using MakePanelEntries = std::vector(*)(); + +public: + virtual ~PanelListDescriptor() = default; + PanelListDescriptor(std::string name, bool enabled = true); + + const std::string& name() const{ return m_name; } + bool enabled() const{ return m_enabled; } + + PanelListWidget* make_QWidget(QWidget& parent, PanelHolder& holder) const; + +protected: + virtual std::vector make_panels() const = 0; + +protected: + std::string m_name; + bool m_enabled; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/PanelTools.h b/SerialPrograms/Source/CommonFramework/Panels/PanelTools.h index 498a8ad4c0..31435df9b4 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/PanelTools.h +++ b/SerialPrograms/Source/CommonFramework/Panels/PanelTools.h @@ -1,100 +1,100 @@ -/* Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Panel_H -#define PokemonAutomation_Panel_H - -#include -#include "PanelDescriptor.h" - -namespace PokemonAutomation{ - -class Logger; -class JsonValue; -class PanelInstance; -class PanelDescriptor; - -// Abstract base class of a panel holder. -// It is named as the owner of all the panel instances. -// A panel instance, CommonFramework/Panels/PanelInstance.h:PanelInstance holds -// both the program panel UI and the implementation of the actual program logic. -// -// Currently the main window is the only class that implements PanelHolder. -// The reference of this panel holder is passed to various UI objects so that -// when they do sth they can call back to the main window. e.g. when the progra -// start button is pressed by user, the button code needs to lock the program -// list UI. This is achieved by letting the button code calls PanelHolder::on_busy() -// which is implemented by the main window -struct PanelHolder{ - // Returns true if ready for new panel. - virtual bool report_new_panel_intent(const PanelDescriptor& descriptor) = 0; - - virtual void load_panel( - std::shared_ptr descriptor, - std::unique_ptr panel - ) = 0; - virtual Logger& raw_logger() = 0; - // called when an automation program is running - virtual void on_busy() = 0; - // called when no automation program is not running - virtual void on_idle() = 0; -}; - - - -struct PanelEntry{ - std::string display_name; - std::unique_ptr descriptor; - - PanelEntry(std::string p_display_name) - : display_name(std::move(p_display_name)) - {} - PanelEntry(std::unique_ptr p_descriptor) - : display_name(p_descriptor->display_name()) - , descriptor(std::move(p_descriptor)) - {} -}; - - -// Used by `make_panel()` to link the panel instance to the panel descriptor. -// For more details, see `make_panel()` defined below. -template -class PanelDescriptorWrapper : public Descriptor{ -public: - // Instance must be an inherited class of PanelInstance and its constructor must be - // Instance(const Descriptor&) - virtual std::unique_ptr make_panel() const override{ - return std::make_unique(*this); - } -}; - -// Called by a program panel list factory to create a panel descriptor. -// A panel descriptor holds various info (title, title color, etc.) about a program panel -// and can also create the corresponding panel. -// -// template type `Descriptor` is a derived class of CommonFramework/Panels/PanelDescriptor.h:PanelDescriptor -// and `Instance` is the program panel UI instance, derived class of -// CommonFramework/Panels/PanelInstance.h:Panelnstance. -// -// Each panel descriptor instance should have implemented `make_panel()` to create the panel instance. -// But writing this creation for each unique program implementation is repetitive. In stead, this function -// uses `PanelDescriptorWrapper` to implement `make_panel()`. -template -std::unique_ptr make_panel(){ - return std::make_unique>(); -} -template -std::unique_ptr make_settings(){ - auto ret = std::make_unique>(); - ret->make_panel()->from_json(); - return ret; -} - - - - -} -#endif +/* Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Panel_H +#define PokemonAutomation_Panel_H + +#include +#include "PanelDescriptor.h" + +namespace PokemonAutomation{ + +class Logger; +class JsonValue; +class PanelInstance; +class PanelDescriptor; + +// Abstract base class of a panel holder. +// It is named as the owner of all the panel instances. +// A panel instance, CommonFramework/Panels/PanelInstance.h:PanelInstance holds +// both the program panel UI and the implementation of the actual program logic. +// +// Currently the main window is the only class that implements PanelHolder. +// The reference of this panel holder is passed to various UI objects so that +// when they do sth they can call back to the main window. e.g. when the progra +// start button is pressed by user, the button code needs to lock the program +// list UI. This is achieved by letting the button code calls PanelHolder::on_busy() +// which is implemented by the main window +struct PanelHolder{ + // Returns true if ready for new panel. + virtual bool report_new_panel_intent(const PanelDescriptor& descriptor) = 0; + + virtual void load_panel( + std::shared_ptr descriptor, + std::unique_ptr panel + ) = 0; + virtual Logger& raw_logger() = 0; + // called when an automation program is running + virtual void on_busy() = 0; + // called when no automation program is not running + virtual void on_idle() = 0; +}; + + + +struct PanelEntry{ + std::string display_name; + std::unique_ptr descriptor; + + PanelEntry(std::string p_display_name) + : display_name(std::move(p_display_name)) + {} + PanelEntry(std::unique_ptr p_descriptor) + : display_name(p_descriptor->display_name()) + , descriptor(std::move(p_descriptor)) + {} +}; + + +// Used by `make_panel()` to link the panel instance to the panel descriptor. +// For more details, see `make_panel()` defined below. +template +class PanelDescriptorWrapper : public Descriptor{ +public: + // Instance must be an inherited class of PanelInstance and its constructor must be + // Instance(const Descriptor&) + virtual std::unique_ptr make_panel() const override{ + return std::make_unique(*this); + } +}; + +// Called by a program panel list factory to create a panel descriptor. +// A panel descriptor holds various info (title, title color, etc.) about a program panel +// and can also create the corresponding panel. +// +// template type `Descriptor` is a derived class of CommonFramework/Panels/PanelDescriptor.h:PanelDescriptor +// and `Instance` is the program panel UI instance, derived class of +// CommonFramework/Panels/PanelInstance.h:Panelnstance. +// +// Each panel descriptor instance should have implemented `make_panel()` to create the panel instance. +// But writing this creation for each unique program implementation is repetitive. In stead, this function +// uses `PanelDescriptorWrapper` to implement `make_panel()`. +template +std::unique_ptr make_panel(){ + return std::make_unique>(); +} +template +std::unique_ptr make_settings(){ + auto ret = std::make_unique>(); + ret->make_panel()->from_json(); + return ret; +} + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.cpp b/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.cpp index 11546e2bc0..f1fca02541 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.cpp @@ -1,29 +1,29 @@ -/* Program Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "ProgramDescriptor.h" - -namespace PokemonAutomation{ - - - -std::unique_ptr ProgramDescriptor::make_stats() const{ - return nullptr; -} - - - - - - - - - - - - -} +/* Program Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "ProgramDescriptor.h" + +namespace PokemonAutomation{ + + + +std::unique_ptr ProgramDescriptor::make_stats() const{ + return nullptr; +} + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.h b/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.h index 518a3b8056..0b34b3ec18 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.h +++ b/SerialPrograms/Source/CommonFramework/Panels/ProgramDescriptor.h @@ -1,38 +1,38 @@ -/* Program Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_ProgramDescriptor_H -#define PokemonAutomation_CommonFramework_ProgramDescriptor_H - -#include "PanelDescriptor.h" - -namespace PokemonAutomation{ - -class StatsTracker; - - - -enum class AllowCommandsWhenRunning{ - DISABLE_COMMANDS, - ENABLE_COMMANDS, -}; - - -class ProgramDescriptor : public PanelDescriptor{ -public: - using PanelDescriptor::PanelDescriptor; - - virtual std::unique_ptr make_stats() const; -}; - - - - - - - -} -#endif +/* Program Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_ProgramDescriptor_H +#define PokemonAutomation_CommonFramework_ProgramDescriptor_H + +#include "PanelDescriptor.h" + +namespace PokemonAutomation{ + +class StatsTracker; + + + +enum class AllowCommandsWhenRunning{ + DISABLE_COMMANDS, + ENABLE_COMMANDS, +}; + + +class ProgramDescriptor : public PanelDescriptor{ +public: + using PanelDescriptor::PanelDescriptor; + + virtual std::unique_ptr make_stats() const; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.cpp b/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.cpp index ab4c77e13c..f8f59bb6c0 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.cpp @@ -1,32 +1,32 @@ -/* Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "SettingsPanel.h" - - -namespace PokemonAutomation{ - - -SettingsPanelInstance::SettingsPanelInstance(const PanelDescriptor& descriptor) - : PanelInstance(descriptor) - , m_options(LockMode::LOCK_WHILE_RUNNING) -{} - -void SettingsPanelInstance::from_json(const JsonValue& json){ - m_options.load_json(json); -} -JsonValue SettingsPanelInstance::to_json() const{ - return m_options.to_json(); -} - - - - - - - -} +/* Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "SettingsPanel.h" + + +namespace PokemonAutomation{ + + +SettingsPanelInstance::SettingsPanelInstance(const PanelDescriptor& descriptor) + : PanelInstance(descriptor) + , m_options(LockMode::LOCK_WHILE_RUNNING) +{} + +void SettingsPanelInstance::from_json(const JsonValue& json){ + m_options.load_json(json); +} +JsonValue SettingsPanelInstance::to_json() const{ + return m_options.to_json(); +} + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.h b/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.h index 5f8b754ead..93c906b5d3 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.h +++ b/SerialPrograms/Source/CommonFramework/Panels/SettingsPanel.h @@ -1,44 +1,44 @@ -/* Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SettingsPanel_H -#define PokemonAutomation_SettingsPanel_H - -#include "Common/Cpp/Options/ConfigOption.h" -#include "Common/Cpp/Options/BatchOption.h" -#include "CommonFramework/Panels/PanelInstance.h" - -namespace PokemonAutomation{ - - - -class SettingsPanelInstance : public PanelInstance{ -public: - SettingsPanelInstance(const PanelDescriptor& descriptor); - - void add_option(ConfigOption& option, std::string serialization_string){ - m_options.add_option(option, std::move(serialization_string)); - } - - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -public: - // Serialization - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -protected: - friend class SettingsPanelWidget; - BatchOption m_options; -}; - - - - -} -#endif - - +/* Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SettingsPanel_H +#define PokemonAutomation_SettingsPanel_H + +#include "Common/Cpp/Options/ConfigOption.h" +#include "Common/Cpp/Options/BatchOption.h" +#include "CommonFramework/Panels/PanelInstance.h" + +namespace PokemonAutomation{ + + + +class SettingsPanelInstance : public PanelInstance{ +public: + SettingsPanelInstance(const PanelDescriptor& descriptor); + + void add_option(ConfigOption& option, std::string serialization_string){ + m_options.add_option(option, std::move(serialization_string)); + } + + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +public: + // Serialization + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +protected: + friend class SettingsPanelWidget; + BatchOption m_options; +}; + + + + +} +#endif + + diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp index 1651f1882f..f34f942e13 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.cpp @@ -1,270 +1,270 @@ -/* Panel Elements - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/ControllerCapability.h" -#include "PanelElements.h" - -namespace PokemonAutomation{ - - - -CollapsibleGroupBox* make_panel_header( - QWidget& parent, - const std::string& display_name, - const std::string& doc_link, - const std::string& description -){ - CollapsibleGroupBox* header = new CollapsibleGroupBox(parent, "Current Program"); - - QWidget* body = new QWidget(header); - QVBoxLayout* vbox = new QVBoxLayout(body); - vbox->setContentsMargins(0, 0, 0, 0); - - std::string name_text = "Name: " + display_name; - if (!doc_link.empty()){ - std::string path = ONLINE_DOC_URL_BASE + doc_link; - name_text += " (" + make_text_url(path, "online documentation") + ")"; - } - QLabel* name_label = new QLabel(QString::fromStdString(name_text), header); - name_label->setWordWrap(true); - name_label->setTextFormat(Qt::RichText); - name_label->setTextInteractionFlags(Qt::TextBrowserInteraction); - name_label->setOpenExternalLinks(true); - vbox->addWidget(name_label); - - std::string description_text = "Description: "; - description_text += description; - QLabel* description_label = new QLabel(QString::fromStdString(description), header); - description_label->setWordWrap(true); - vbox->addWidget(description_label); - - header->set_widget(body); - - return header; -} -#if 0 -CollapsibleGroupBox* make_panel_header( - QWidget& parent, - const std::string& display_name, - const std::string& doc_link, - const std::string& description, - FeedbackType feedback -){ - CollapsibleGroupBox* header = make_panel_header(parent, display_name, doc_link, description); - QLayout* layout = header->widget()->layout(); - - QLabel* text = nullptr; - switch (feedback){ - case FeedbackType::NONE: - text = new QLabel( - QString::fromStdString(html_color_text("(This program does not use feedback. It can run without video input.)", COLOR_PURPLE)), - header - ); - break; - case FeedbackType::OPTIONAL_: - text = new QLabel( - QString::fromStdString(html_color_text("(This program will use video feedback if it is available. Video input is not required.)", COLOR_PURPLE)), - header - ); - break; - case FeedbackType::REQUIRED: - text = new QLabel( - "(This program requires video feedback. Please make sure you choose the correct capture device.)", - header - ); - break; - case FeedbackType::VIDEO_AUDIO: - text = new QLabel( - "(This program requires video and audio feedback. Please make sure you choose the correct capture device, as well as the correct audio device.)", - header - ); - break; - } - text->setWordWrap(true); - layout->addWidget(text); - - return header; -} -#endif -CollapsibleGroupBox* make_panel_header( - QWidget& parent, - const std::string& display_name, - const std::string& doc_link, - const std::string& description, - const ControllerFeatures& required_features, - FasterIfTickPrecise faster_if_tick_precise -){ - CollapsibleGroupBox* header = make_panel_header(parent, display_name, doc_link, description); - QLayout* layout = header->widget()->layout(); - - std::string text; - do{ - if (required_features.contains(ControllerFeature::NintendoSwitch_DateSkip)){ - text = html_color_text("(This program requires advanced RPCs.)", COLOR_RED); - break; - } - if (required_features.contains(ControllerFeature::TickPrecise)){ - text = html_color_text("(This program requires a tick-precise controller.)", COLOR_PURPLE); - break; - } - - switch (faster_if_tick_precise){ - case PokemonAutomation::FasterIfTickPrecise::MUCH_FASTER: - text = html_color_text( - "(This program does not have any special controller requirements. " - "However, it is strongly recommended to use a tick-precise controller as the program will run much faster and/or more reliably.)", - COLOR_DARKGREEN - ); - break; - case PokemonAutomation::FasterIfTickPrecise::FASTER: - text = html_color_text( - "(This program does not have any special controller requirements. " - "However, it runs faster if the controller is tick-precise.)", - COLOR_DARKGREEN - ); - break; - case PokemonAutomation::FasterIfTickPrecise::NOT_FASTER: - text = html_color_text("(This program does not have any special controller requirements.)", COLOR_BLUE); - break; - } - - }while (false); - - QLabel* label = new QLabel(QString::fromStdString(text), header); - label->setWordWrap(true); - layout->addWidget(label); - - return header; -} - - - -StatsBar::StatsBar(QWidget& parent) - : QLabel(&parent) -{ - this->setWordWrap(true); - this->setVisible(false); - this->setAlignment(Qt::AlignCenter); -// this->setText("Encounters: 1,267 - Corrections: 0 - Star Shinies: 1 - Square Shinies: 0"); - QFont font = this->font(); - font.setPointSize(10); - this->setFont(font); -} -void StatsBar::set_stats(std::string current_stats, std::string historical_stats){ - if (current_stats.empty() && historical_stats.empty()){ - this->setText(""); - this->setVisible(false); - return; - } - - if (!current_stats.empty() && historical_stats.empty()){ - this->setText(QString::fromStdString(current_stats)); - this->setVisible(true); - return; - } - - if (current_stats.empty() && !historical_stats.empty()){ - this->setText(QString::fromStdString("Past Runs - " + historical_stats)); - this->setVisible(true); - return; - } - - std::string str; - str += "Current Run - " + current_stats; - str += "
"; - str += "Past Totals - " + historical_stats; - - this->setText(QString::fromStdString(str)); - this->setVisible(true); -} - - - -RunnablePanelActionBar::RunnablePanelActionBar(QWidget& parent, ProgramState initial_state) - : QGroupBox("Actions", &parent) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - -// layout->addWidget(new QPushButton("Start Raid Now!", this)); - - QHBoxLayout* action_layout = new QHBoxLayout(); - layout->addLayout(action_layout); -// action_layout->setContentsMargins(0, 0, 0, 0); - - { - m_start_button = new QPushButton(this); - QFont font = m_start_button->font(); - font.setPointSize(16); - m_start_button->setFont(font); - action_layout->addWidget(m_start_button, 2); - } - { - m_default_button = new QPushButton("Restore Defaults", this); - QFont font = m_default_button->font(); - font.setPointSize(16); - m_default_button->setFont(font); - action_layout->addWidget(m_default_button, 1); - } - - set_state(initial_state); - - connect( - m_start_button, &QPushButton::clicked, - this, [this](bool){ emit start_clicked(m_last_known_state); } - ); - connect( - m_default_button, &QPushButton::clicked, - this, [this](bool){ - QMessageBox::StandardButton button = QMessageBox::question( - nullptr, - "Restore Defaults", - "Are you sure you wish to restore settings back to defaults? This will wipe the current settings.", - QMessageBox::Ok | QMessageBox::Cancel - ); - if (button == QMessageBox::Ok){ - emit defaults_clicked(); - } - } - ); -} -void RunnablePanelActionBar::set_state(ProgramState state){ - m_last_known_state = state; - switch (state){ - case ProgramState::NOT_READY: - m_start_button->setText("Loading..."); - m_start_button->setEnabled(false); - m_default_button->setEnabled(false); - break; - case ProgramState::STOPPED: - m_start_button->setText("Start Program..."); - m_start_button->setEnabled(true); - m_default_button->setEnabled(true); - break; - case ProgramState::RUNNING: - m_start_button->setText("Stop Program..."); - m_start_button->setEnabled(true); - m_default_button->setEnabled(false); - break; - case ProgramState::STOPPING: - m_start_button->setText("Stopping Program..."); - m_start_button->setEnabled(false); - m_default_button->setEnabled(false); - break; - } -} - - - - - - -} +/* Panel Elements + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/ControllerCapability.h" +#include "PanelElements.h" + +namespace PokemonAutomation{ + + + +CollapsibleGroupBox* make_panel_header( + QWidget& parent, + const std::string& display_name, + const std::string& doc_link, + const std::string& description +){ + CollapsibleGroupBox* header = new CollapsibleGroupBox(parent, "Current Program"); + + QWidget* body = new QWidget(header); + QVBoxLayout* vbox = new QVBoxLayout(body); + vbox->setContentsMargins(0, 0, 0, 0); + + std::string name_text = "Name: " + display_name; + if (!doc_link.empty()){ + std::string path = ONLINE_DOC_URL_BASE + doc_link; + name_text += " (" + make_text_url(path, "online documentation") + ")"; + } + QLabel* name_label = new QLabel(QString::fromStdString(name_text), header); + name_label->setWordWrap(true); + name_label->setTextFormat(Qt::RichText); + name_label->setTextInteractionFlags(Qt::TextBrowserInteraction); + name_label->setOpenExternalLinks(true); + vbox->addWidget(name_label); + + std::string description_text = "Description: "; + description_text += description; + QLabel* description_label = new QLabel(QString::fromStdString(description), header); + description_label->setWordWrap(true); + vbox->addWidget(description_label); + + header->set_widget(body); + + return header; +} +#if 0 +CollapsibleGroupBox* make_panel_header( + QWidget& parent, + const std::string& display_name, + const std::string& doc_link, + const std::string& description, + FeedbackType feedback +){ + CollapsibleGroupBox* header = make_panel_header(parent, display_name, doc_link, description); + QLayout* layout = header->widget()->layout(); + + QLabel* text = nullptr; + switch (feedback){ + case FeedbackType::NONE: + text = new QLabel( + QString::fromStdString(html_color_text("(This program does not use feedback. It can run without video input.)", COLOR_PURPLE)), + header + ); + break; + case FeedbackType::OPTIONAL_: + text = new QLabel( + QString::fromStdString(html_color_text("(This program will use video feedback if it is available. Video input is not required.)", COLOR_PURPLE)), + header + ); + break; + case FeedbackType::REQUIRED: + text = new QLabel( + "(This program requires video feedback. Please make sure you choose the correct capture device.)", + header + ); + break; + case FeedbackType::VIDEO_AUDIO: + text = new QLabel( + "(This program requires video and audio feedback. Please make sure you choose the correct capture device, as well as the correct audio device.)", + header + ); + break; + } + text->setWordWrap(true); + layout->addWidget(text); + + return header; +} +#endif +CollapsibleGroupBox* make_panel_header( + QWidget& parent, + const std::string& display_name, + const std::string& doc_link, + const std::string& description, + const ControllerFeatures& required_features, + FasterIfTickPrecise faster_if_tick_precise +){ + CollapsibleGroupBox* header = make_panel_header(parent, display_name, doc_link, description); + QLayout* layout = header->widget()->layout(); + + std::string text; + do{ + if (required_features.contains(ControllerFeature::NintendoSwitch_DateSkip)){ + text = html_color_text("(This program requires advanced RPCs.)", COLOR_RED); + break; + } + if (required_features.contains(ControllerFeature::TickPrecise)){ + text = html_color_text("(This program requires a tick-precise controller.)", COLOR_PURPLE); + break; + } + + switch (faster_if_tick_precise){ + case PokemonAutomation::FasterIfTickPrecise::MUCH_FASTER: + text = html_color_text( + "(This program does not have any special controller requirements. " + "However, it is strongly recommended to use a tick-precise controller as the program will run much faster and/or more reliably.)", + COLOR_DARKGREEN + ); + break; + case PokemonAutomation::FasterIfTickPrecise::FASTER: + text = html_color_text( + "(This program does not have any special controller requirements. " + "However, it runs faster if the controller is tick-precise.)", + COLOR_DARKGREEN + ); + break; + case PokemonAutomation::FasterIfTickPrecise::NOT_FASTER: + text = html_color_text("(This program does not have any special controller requirements.)", COLOR_BLUE); + break; + } + + }while (false); + + QLabel* label = new QLabel(QString::fromStdString(text), header); + label->setWordWrap(true); + layout->addWidget(label); + + return header; +} + + + +StatsBar::StatsBar(QWidget& parent) + : QLabel(&parent) +{ + this->setWordWrap(true); + this->setVisible(false); + this->setAlignment(Qt::AlignCenter); +// this->setText("Encounters: 1,267 - Corrections: 0 - Star Shinies: 1 - Square Shinies: 0"); + QFont font = this->font(); + font.setPointSize(10); + this->setFont(font); +} +void StatsBar::set_stats(std::string current_stats, std::string historical_stats){ + if (current_stats.empty() && historical_stats.empty()){ + this->setText(""); + this->setVisible(false); + return; + } + + if (!current_stats.empty() && historical_stats.empty()){ + this->setText(QString::fromStdString(current_stats)); + this->setVisible(true); + return; + } + + if (current_stats.empty() && !historical_stats.empty()){ + this->setText(QString::fromStdString("Past Runs - " + historical_stats)); + this->setVisible(true); + return; + } + + std::string str; + str += "Current Run - " + current_stats; + str += "
"; + str += "Past Totals - " + historical_stats; + + this->setText(QString::fromStdString(str)); + this->setVisible(true); +} + + + +RunnablePanelActionBar::RunnablePanelActionBar(QWidget& parent, ProgramState initial_state) + : QGroupBox("Actions", &parent) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + +// layout->addWidget(new QPushButton("Start Raid Now!", this)); + + QHBoxLayout* action_layout = new QHBoxLayout(); + layout->addLayout(action_layout); +// action_layout->setContentsMargins(0, 0, 0, 0); + + { + m_start_button = new QPushButton(this); + QFont font = m_start_button->font(); + font.setPointSize(16); + m_start_button->setFont(font); + action_layout->addWidget(m_start_button, 2); + } + { + m_default_button = new QPushButton("Restore Defaults", this); + QFont font = m_default_button->font(); + font.setPointSize(16); + m_default_button->setFont(font); + action_layout->addWidget(m_default_button, 1); + } + + set_state(initial_state); + + connect( + m_start_button, &QPushButton::clicked, + this, [this](bool){ emit start_clicked(m_last_known_state); } + ); + connect( + m_default_button, &QPushButton::clicked, + this, [this](bool){ + QMessageBox::StandardButton button = QMessageBox::question( + nullptr, + "Restore Defaults", + "Are you sure you wish to restore settings back to defaults? This will wipe the current settings.", + QMessageBox::Ok | QMessageBox::Cancel + ); + if (button == QMessageBox::Ok){ + emit defaults_clicked(); + } + } + ); +} +void RunnablePanelActionBar::set_state(ProgramState state){ + m_last_known_state = state; + switch (state){ + case ProgramState::NOT_READY: + m_start_button->setText("Loading..."); + m_start_button->setEnabled(false); + m_default_button->setEnabled(false); + break; + case ProgramState::STOPPED: + m_start_button->setText("Start Program..."); + m_start_button->setEnabled(true); + m_default_button->setEnabled(true); + break; + case ProgramState::RUNNING: + m_start_button->setText("Stop Program..."); + m_start_button->setEnabled(true); + m_default_button->setEnabled(false); + break; + case ProgramState::STOPPING: + m_start_button->setText("Stopping Program..."); + m_start_button->setEnabled(false); + m_default_button->setEnabled(false); + break; + } +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.h b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.h index 6b55d2d1f0..f1aaeed512 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.h +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelElements.h @@ -1,87 +1,87 @@ -/* Panel Elements - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanelElements_H -#define PokemonAutomation_PanelElements_H - -#include -#include -#include "Common/Qt/CollapsibleGroupBox.h" -#include "CommonFramework/Globals.h" -#include "Controllers/ControllerCapability.h" - -class QPushButton; - -namespace PokemonAutomation{ - - - - -CollapsibleGroupBox* make_panel_header( - QWidget& parent, - const std::string& display_name, - const std::string& doc_link, - const std::string& description -); -#if 0 -CollapsibleGroupBox* make_panel_header( - QWidget& parent, - const std::string& display_name, - const std::string& doc_link, - const std::string& description, - FeedbackType feedback -); -#endif -CollapsibleGroupBox* make_panel_header( - QWidget& parent, - const std::string& display_name, - const std::string& doc_link, - const std::string& description, - const ControllerFeatures& required_features, - FasterIfTickPrecise faster_if_tick_precise -); - - - -class StatsBar : public QLabel{ - Q_OBJECT -public: - StatsBar(QWidget& parent); - -public slots: - void set_stats(std::string current_stats, std::string historical_stats); -}; - - - -class RunnablePanelActionBar : public QGroupBox{ - Q_OBJECT -public: - RunnablePanelActionBar(QWidget& parent, ProgramState initial_state); - -public slots: - void set_state(PokemonAutomation::ProgramState state); - -signals: - void start_clicked(ProgramState state); - void defaults_clicked(); - -private: - PokemonAutomation::ProgramState m_last_known_state; - QPushButton* m_start_button; - QPushButton* m_default_button; -}; - - - - - - - - - -} -#endif +/* Panel Elements + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanelElements_H +#define PokemonAutomation_PanelElements_H + +#include +#include +#include "Common/Qt/CollapsibleGroupBox.h" +#include "CommonFramework/Globals.h" +#include "Controllers/ControllerCapability.h" + +class QPushButton; + +namespace PokemonAutomation{ + + + + +CollapsibleGroupBox* make_panel_header( + QWidget& parent, + const std::string& display_name, + const std::string& doc_link, + const std::string& description +); +#if 0 +CollapsibleGroupBox* make_panel_header( + QWidget& parent, + const std::string& display_name, + const std::string& doc_link, + const std::string& description, + FeedbackType feedback +); +#endif +CollapsibleGroupBox* make_panel_header( + QWidget& parent, + const std::string& display_name, + const std::string& doc_link, + const std::string& description, + const ControllerFeatures& required_features, + FasterIfTickPrecise faster_if_tick_precise +); + + + +class StatsBar : public QLabel{ + Q_OBJECT +public: + StatsBar(QWidget& parent); + +public slots: + void set_stats(std::string current_stats, std::string historical_stats); +}; + + + +class RunnablePanelActionBar : public QGroupBox{ + Q_OBJECT +public: + RunnablePanelActionBar(QWidget& parent, ProgramState initial_state); + +public slots: + void set_state(PokemonAutomation::ProgramState state); + +signals: + void start_clicked(ProgramState state); + void defaults_clicked(); + +private: + PokemonAutomation::ProgramState m_last_known_state; + QPushButton* m_start_button; + QPushButton* m_default_button; +}; + + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.cpp b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.cpp index d5af838a4e..3fafa6661d 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.cpp @@ -1,118 +1,118 @@ -/* Panel List Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/PersistentSettings.h" -//#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Panels/PanelInstance.h" -#include "PanelListWidget.h" - -namespace PokemonAutomation{ - - - - -PanelListWidget* PanelListDescriptor::make_QWidget(QWidget& parent, PanelHolder& holder) const{ - return new PanelListWidget( - parent, holder, - this->make_panels() - ); -} - - - -const std::string PanelListWidget::JSON_PROGRAM_PANEL = "ProgramPanel"; - -PanelListWidget::PanelListWidget( - QWidget& parent, PanelHolder& holder, - std::vector list -) - : QListWidget(&parent) - , m_panel_holder(holder) -{ -// QFontMetrics fm(this->font()); - for (PanelEntry& item : list){ - const std::string& display_name = item.display_name; - PanelDescriptor* descriptor = item.descriptor.get(); - - // Label/divider - if (descriptor == nullptr){ - addItem(QString::fromStdString(display_name)); - QListWidgetItem* list_item = this->item(this->count() - 1); - QFont font = list_item->font(); - font.setBold(true); - list_item->setFont(font); -// list_item->setTextAlignment(Qt::AlignCenter); - continue; - } - - // Program - if (!m_panel_map.emplace(display_name, std::move(item.descriptor)).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate program name: " + display_name); - } - - addItem(QString::fromStdString(display_name)); -// addItem(QString::fromStdString("DM Elvis for FREE SHINIES!!!")); - QListWidgetItem* list_item = this->item(this->count() - 1); - Color color = descriptor->color(); - if (color){ - QColor qcolor = QColor((uint32_t)color); - list_item->setForeground(qcolor); - } - list_item->setToolTip(QString::fromStdString(descriptor->description())); - } - connect( - this, &QListWidget::itemClicked, - this, [this](QListWidgetItem* item){ - handle_panel_clicked(item->text().toStdString()); - } - ); -} - - -void PanelListWidget::handle_panel_clicked(const std::string& text){ - auto iter = m_panel_map.find(text); - if (iter == m_panel_map.end()){ - PERSISTENT_SETTINGS().panels[JSON_PROGRAM_PANEL] = ""; - return; - } - std::shared_ptr& descriptor = iter->second; -// cout << descriptor->display_name() << endl; - if (!m_panel_holder.report_new_panel_intent(*descriptor)){ - return; - } - try{ - std::unique_ptr panel = descriptor->make_panel(); -// try{ - panel->from_json(PERSISTENT_SETTINGS().panels[descriptor->identifier()]); -// }catch (ParseException&){} - m_panel_holder.load_panel(descriptor, std::move(panel)); - - PERSISTENT_SETTINGS().panels[JSON_PROGRAM_PANEL] = iter->first; - }catch (const Exception& error){ - QMessageBox box; - box.critical( - nullptr, - "Error", - "Failed to load program.\n\n" + QString::fromStdString(error.to_str()) - ); - } -} - -void PanelListWidget::set_panel(const std::string& panel_name){ - const auto panels = findItems(QString::fromStdString(panel_name), Qt::MatchExactly); - if (panels.size() > 0){ - setCurrentItem(panels[0]); - } - - handle_panel_clicked(panel_name); -} - - - - -} +/* Panel List Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/PersistentSettings.h" +//#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Panels/PanelInstance.h" +#include "PanelListWidget.h" + +namespace PokemonAutomation{ + + + + +PanelListWidget* PanelListDescriptor::make_QWidget(QWidget& parent, PanelHolder& holder) const{ + return new PanelListWidget( + parent, holder, + this->make_panels() + ); +} + + + +const std::string PanelListWidget::JSON_PROGRAM_PANEL = "ProgramPanel"; + +PanelListWidget::PanelListWidget( + QWidget& parent, PanelHolder& holder, + std::vector list +) + : QListWidget(&parent) + , m_panel_holder(holder) +{ +// QFontMetrics fm(this->font()); + for (PanelEntry& item : list){ + const std::string& display_name = item.display_name; + PanelDescriptor* descriptor = item.descriptor.get(); + + // Label/divider + if (descriptor == nullptr){ + addItem(QString::fromStdString(display_name)); + QListWidgetItem* list_item = this->item(this->count() - 1); + QFont font = list_item->font(); + font.setBold(true); + list_item->setFont(font); +// list_item->setTextAlignment(Qt::AlignCenter); + continue; + } + + // Program + if (!m_panel_map.emplace(display_name, std::move(item.descriptor)).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate program name: " + display_name); + } + + addItem(QString::fromStdString(display_name)); +// addItem(QString::fromStdString("DM Elvis for FREE SHINIES!!!")); + QListWidgetItem* list_item = this->item(this->count() - 1); + Color color = descriptor->color(); + if (color){ + QColor qcolor = QColor((uint32_t)color); + list_item->setForeground(qcolor); + } + list_item->setToolTip(QString::fromStdString(descriptor->description())); + } + connect( + this, &QListWidget::itemClicked, + this, [this](QListWidgetItem* item){ + handle_panel_clicked(item->text().toStdString()); + } + ); +} + + +void PanelListWidget::handle_panel_clicked(const std::string& text){ + auto iter = m_panel_map.find(text); + if (iter == m_panel_map.end()){ + PERSISTENT_SETTINGS().panels[JSON_PROGRAM_PANEL] = ""; + return; + } + std::shared_ptr& descriptor = iter->second; +// cout << descriptor->display_name() << endl; + if (!m_panel_holder.report_new_panel_intent(*descriptor)){ + return; + } + try{ + std::unique_ptr panel = descriptor->make_panel(); +// try{ + panel->from_json(PERSISTENT_SETTINGS().panels[descriptor->identifier()]); +// }catch (ParseException&){} + m_panel_holder.load_panel(descriptor, std::move(panel)); + + PERSISTENT_SETTINGS().panels[JSON_PROGRAM_PANEL] = iter->first; + }catch (const Exception& error){ + QMessageBox box; + box.critical( + nullptr, + "Error", + "Failed to load program.\n\n" + QString::fromStdString(error.to_str()) + ); + } +} + +void PanelListWidget::set_panel(const std::string& panel_name){ + const auto panels = findItems(QString::fromStdString(panel_name), Qt::MatchExactly); + if (panels.size() > 0){ + setCurrentItem(panels[0]); + } + + handle_panel_clicked(panel_name); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.h b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.h index 7f977747f7..35640dbbe4 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.h +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelListWidget.h @@ -1,42 +1,42 @@ -/* Panel List Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanelListWidget_H -#define PokemonAutomation_PanelListWidget_H - -#include -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ - - - -class PanelListWidget : public QListWidget{ -public: - static const std::string JSON_PROGRAM_PANEL; - -public: - PanelListWidget( - QWidget& parent, PanelHolder& holder, - std::vector list - ); - - size_t items() const{ return m_panel_map.size(); } - - void set_panel(const std::string& panel_name); - -private: - void handle_panel_clicked(const std::string& text); - -private: - PanelHolder& m_panel_holder; - std::map> m_panel_map; -}; - - - -} -#endif +/* Panel List Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanelListWidget_H +#define PokemonAutomation_PanelListWidget_H + +#include +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ + + + +class PanelListWidget : public QListWidget{ +public: + static const std::string JSON_PROGRAM_PANEL; + +public: + PanelListWidget( + QWidget& parent, PanelHolder& holder, + std::vector list + ); + + size_t items() const{ return m_panel_map.size(); } + + void set_panel(const std::string& panel_name); + +private: + void handle_panel_clicked(const std::string& text); + +private: + PanelHolder& m_panel_holder; + std::map> m_panel_map; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.cpp b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.cpp index f52f375036..942bc1800d 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.cpp @@ -1,46 +1,46 @@ -/* Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Qt/CollapsibleGroupBox.h" -#include "CommonFramework/Panels/PanelDescriptor.h" -#include "CommonFramework/Panels/PanelInstance.h" -#include "PanelElements.h" -#include "PanelWidget.h" - -namespace PokemonAutomation{ - - - -QWidget* PanelInstance::make_widget(QWidget& parent, PanelHolder& holder){ - return new PanelWidget(parent, *this, holder); -} - - -PanelWidget::PanelWidget( - QWidget& parent, - PanelInstance& instance, - PanelHolder& holder -) - : QWidget(&parent) - , m_instance(instance) - , m_holder(holder) -{} - -CollapsibleGroupBox* PanelWidget::make_header(QWidget& parent){ - return make_panel_header( - *this, - m_instance.descriptor().display_name(), - m_instance.descriptor().doc_link(), - m_instance.descriptor().description() - ); -} - - - -} +/* Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Qt/CollapsibleGroupBox.h" +#include "CommonFramework/Panels/PanelDescriptor.h" +#include "CommonFramework/Panels/PanelInstance.h" +#include "PanelElements.h" +#include "PanelWidget.h" + +namespace PokemonAutomation{ + + + +QWidget* PanelInstance::make_widget(QWidget& parent, PanelHolder& holder){ + return new PanelWidget(parent, *this, holder); +} + + +PanelWidget::PanelWidget( + QWidget& parent, + PanelInstance& instance, + PanelHolder& holder +) + : QWidget(&parent) + , m_instance(instance) + , m_holder(holder) +{} + +CollapsibleGroupBox* PanelWidget::make_header(QWidget& parent){ + return make_panel_header( + *this, + m_instance.descriptor().display_name(), + m_instance.descriptor().doc_link(), + m_instance.descriptor().description() + ); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h index b9ead315a9..5f06de6c9a 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/PanelWidget.h @@ -1,45 +1,45 @@ -/* Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PanelWidget_H -#define PokemonAutomation_PanelWidget_H - -#include -#include "CommonFramework/Panels/PanelTools.h" - -namespace PokemonAutomation{ - -class CollapsibleGroupBox; - -// A base class to define the UI widgets of a program panel. -// A PanelInstance can call make_widget() to create it. -// Its derived classes can call make_header() to create a collabspile program header -// that shows program title, link to online documentation and others. -class PanelWidget : public QWidget{ -public: - PanelWidget( - QWidget& parent, - PanelInstance& instance, - PanelHolder& holder - ); - virtual ~PanelWidget() = default; - - // return the panel instance - PanelInstance& instance(){ return m_instance; } - -protected: - virtual CollapsibleGroupBox* make_header(QWidget& parent); - -protected: - PanelInstance& m_instance; - PanelHolder& m_holder; -}; - - - - -} -#endif +/* Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PanelWidget_H +#define PokemonAutomation_PanelWidget_H + +#include +#include "CommonFramework/Panels/PanelTools.h" + +namespace PokemonAutomation{ + +class CollapsibleGroupBox; + +// A base class to define the UI widgets of a program panel. +// A PanelInstance can call make_widget() to create it. +// Its derived classes can call make_header() to create a collabspile program header +// that shows program title, link to online documentation and others. +class PanelWidget : public QWidget{ +public: + PanelWidget( + QWidget& parent, + PanelInstance& instance, + PanelHolder& holder + ); + virtual ~PanelWidget() = default; + + // return the panel instance + PanelInstance& instance(){ return m_instance; } + +protected: + virtual CollapsibleGroupBox* make_header(QWidget& parent); + +protected: + PanelInstance& m_instance; + PanelHolder& m_holder; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.cpp b/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.cpp index f939ecb196..13b159c557 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.cpp @@ -1,104 +1,104 @@ -/* Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Qt/CollapsibleGroupBox.h" -#include "Common/Qt/Options/BatchWidget.h" -#include "SettingsPanelWidget.h" - -namespace PokemonAutomation{ - - -QWidget* SettingsPanelInstance::make_widget(QWidget& parent, PanelHolder& holder){ - return SettingsPanelWidget::make(parent, *this, holder); -} - - -SettingsPanelWidget* SettingsPanelWidget::make( - QWidget& parent, - SettingsPanelInstance& instance, - PanelHolder& holder -){ - SettingsPanelWidget* widget = new SettingsPanelWidget(parent, instance, holder); - widget->construct(); - return widget; -} -SettingsPanelWidget::SettingsPanelWidget( - QWidget& parent, - SettingsPanelInstance& instance, - PanelHolder& holder -) - : PanelWidget(parent, instance, holder) -{} -void SettingsPanelWidget::construct(){ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(make_header(*this)); - - QScrollArea* scroll = new QScrollArea(this); - layout->addWidget(scroll); - scroll->setWidgetResizable(true); - - scroll->setWidget(make_options(*scroll)); - layout->addWidget(make_actions(*this)); -} -QWidget* SettingsPanelWidget::make_options(QWidget& parent){ - QWidget* options_widget = new QWidget(&parent); - (new QVBoxLayout(&parent))->addWidget(options_widget); - - QVBoxLayout* options_layout = new QVBoxLayout(options_widget); - options_layout->setAlignment(Qt::AlignTop); - - - SettingsPanelInstance& instance = static_cast(m_instance); - m_options = static_cast(instance.m_options.make_QtWidget(parent)); - options_layout->addWidget(m_options); - options_layout->addStretch(); - - return options_widget; -} -QWidget* SettingsPanelWidget::make_actions(QWidget& parent){ - QGroupBox* actions_widget = new QGroupBox("Actions", &parent); - - QHBoxLayout* action_layout = new QHBoxLayout(actions_widget); -// action_layout->setContentsMargins(0, 0, 0, 0); - { - m_default_button = new QPushButton("Restore Defaults", actions_widget); - action_layout->addWidget(m_default_button, 1); - QFont font = m_default_button->font(); - font.setPointSize(16); - m_default_button->setFont(font); - } - - connect( - m_default_button, &QPushButton::clicked, - this, [this](bool){ - QMessageBox::StandardButton button = QMessageBox::question( - nullptr, - "Restore Defaults", - "Are you sure you wish to restore settings back to defaults? This will wipe the current settings.", - QMessageBox::Ok | QMessageBox::Cancel - ); - if (button == QMessageBox::Ok){ - restore_defaults(); - } - } - ); - - return actions_widget; -} - -void SettingsPanelWidget::restore_defaults(){ - m_options->option().restore_defaults(); -} - - - -} +/* Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Qt/CollapsibleGroupBox.h" +#include "Common/Qt/Options/BatchWidget.h" +#include "SettingsPanelWidget.h" + +namespace PokemonAutomation{ + + +QWidget* SettingsPanelInstance::make_widget(QWidget& parent, PanelHolder& holder){ + return SettingsPanelWidget::make(parent, *this, holder); +} + + +SettingsPanelWidget* SettingsPanelWidget::make( + QWidget& parent, + SettingsPanelInstance& instance, + PanelHolder& holder +){ + SettingsPanelWidget* widget = new SettingsPanelWidget(parent, instance, holder); + widget->construct(); + return widget; +} +SettingsPanelWidget::SettingsPanelWidget( + QWidget& parent, + SettingsPanelInstance& instance, + PanelHolder& holder +) + : PanelWidget(parent, instance, holder) +{} +void SettingsPanelWidget::construct(){ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(make_header(*this)); + + QScrollArea* scroll = new QScrollArea(this); + layout->addWidget(scroll); + scroll->setWidgetResizable(true); + + scroll->setWidget(make_options(*scroll)); + layout->addWidget(make_actions(*this)); +} +QWidget* SettingsPanelWidget::make_options(QWidget& parent){ + QWidget* options_widget = new QWidget(&parent); + (new QVBoxLayout(&parent))->addWidget(options_widget); + + QVBoxLayout* options_layout = new QVBoxLayout(options_widget); + options_layout->setAlignment(Qt::AlignTop); + + + SettingsPanelInstance& instance = static_cast(m_instance); + m_options = static_cast(instance.m_options.make_QtWidget(parent)); + options_layout->addWidget(m_options); + options_layout->addStretch(); + + return options_widget; +} +QWidget* SettingsPanelWidget::make_actions(QWidget& parent){ + QGroupBox* actions_widget = new QGroupBox("Actions", &parent); + + QHBoxLayout* action_layout = new QHBoxLayout(actions_widget); +// action_layout->setContentsMargins(0, 0, 0, 0); + { + m_default_button = new QPushButton("Restore Defaults", actions_widget); + action_layout->addWidget(m_default_button, 1); + QFont font = m_default_button->font(); + font.setPointSize(16); + m_default_button->setFont(font); + } + + connect( + m_default_button, &QPushButton::clicked, + this, [this](bool){ + QMessageBox::StandardButton button = QMessageBox::question( + nullptr, + "Restore Defaults", + "Are you sure you wish to restore settings back to defaults? This will wipe the current settings.", + QMessageBox::Ok | QMessageBox::Cancel + ); + if (button == QMessageBox::Ok){ + restore_defaults(); + } + } + ); + + return actions_widget; +} + +void SettingsPanelWidget::restore_defaults(){ + m_options->option().restore_defaults(); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.h b/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.h index 8eab72a52d..65e4eb5a8a 100644 --- a/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.h +++ b/SerialPrograms/Source/CommonFramework/Panels/UI/SettingsPanelWidget.h @@ -1,50 +1,50 @@ -/* Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SettingsPanelWidget_H -#define PokemonAutomation_SettingsPanelWidget_H - -#include "PanelWidget.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -class QPushButton; - -namespace PokemonAutomation{ - -class BatchWidget; - - -class SettingsPanelWidget : public PanelWidget{ -public: - static SettingsPanelWidget* make( - QWidget& parent, - SettingsPanelInstance& instance, - PanelHolder& holder - ); - - void restore_defaults(); - -private: - SettingsPanelWidget( - QWidget& parent, - SettingsPanelInstance& instance, - PanelHolder& holder - ); - void construct(); - QWidget* make_options(QWidget& parent); - QWidget* make_actions(QWidget& parent); - -private: - friend class SettingsPanelInstance; - - BatchWidget* m_options; - QPushButton* m_default_button; -}; - - - -} -#endif +/* Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SettingsPanelWidget_H +#define PokemonAutomation_SettingsPanelWidget_H + +#include "PanelWidget.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +class QPushButton; + +namespace PokemonAutomation{ + +class BatchWidget; + + +class SettingsPanelWidget : public PanelWidget{ +public: + static SettingsPanelWidget* make( + QWidget& parent, + SettingsPanelInstance& instance, + PanelHolder& holder + ); + + void restore_defaults(); + +private: + SettingsPanelWidget( + QWidget& parent, + SettingsPanelInstance& instance, + PanelHolder& holder + ); + void construct(); + QWidget* make_options(QWidget& parent); + QWidget* make_actions(QWidget& parent); + +private: + friend class SettingsPanelInstance; + + BatchWidget* m_options; + QPushButton* m_default_button; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp b/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp index b568d8d435..de493b3caf 100644 --- a/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp +++ b/SerialPrograms/Source/CommonFramework/PersistentSettings.cpp @@ -1,87 +1,87 @@ -/* Persistent Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "PersistentSettings.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ - - - -PersistentSettings& PERSISTENT_SETTINGS(){ - static PersistentSettings settings; - return settings; -} - - -PersistentSettings::PersistentSettings(){} - - - -void PersistentSettings::write() const{ - JsonObject root; - - root["20-GlobalSettings"] = GlobalSettings::instance().to_json(); -// root["50-SwitchKeyboardMapping"] = NintendoSwitch::read_keyboard_mapping(); - - root["99-Panels"] = panels.clone(); - - try{ - root.dump(PROGRAM_SETTING_JSON_PATH()); - }catch (FileException&){} -} - - -void PersistentSettings::read(){ - JsonValue json = load_json_file(PROGRAM_SETTING_JSON_PATH()); - JsonObject* obj = json.to_object(); - if (obj == nullptr){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid settings file.", PROGRAM_SETTING_JSON_PATH()); - } - - // Need to load this subset of settings first because they will affect how - // "GlobalSettings" is constructed. - const JsonValue* settings = obj->get_value("20-GlobalSettings"); - if (settings){ - PreloadSettings::instance().load(*settings); - GlobalSettings::instance().load_json(*settings); - } - -// GlobalSettings::instance().PROCESS_PRIORITY0.update_priority_to_option(); - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - -#if 0 - { - const JsonArray* array = obj->get_array("50-SwitchKeyboardMapping"); - if (array){ - NintendoSwitch::set_keyboard_mapping(*array); - } - } -#endif - { - JsonObject* value = obj->get_object("99-Panels"); - if (value){ -// panels = to_QJson(*value).toObject(); - panels = std::move(*value); - } - } -} - - - -} - +/* Persistent Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "PersistentSettings.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ + + + +PersistentSettings& PERSISTENT_SETTINGS(){ + static PersistentSettings settings; + return settings; +} + + +PersistentSettings::PersistentSettings(){} + + + +void PersistentSettings::write() const{ + JsonObject root; + + root["20-GlobalSettings"] = GlobalSettings::instance().to_json(); +// root["50-SwitchKeyboardMapping"] = NintendoSwitch::read_keyboard_mapping(); + + root["99-Panels"] = panels.clone(); + + try{ + root.dump(PROGRAM_SETTING_JSON_PATH()); + }catch (FileException&){} +} + + +void PersistentSettings::read(){ + JsonValue json = load_json_file(PROGRAM_SETTING_JSON_PATH()); + JsonObject* obj = json.to_object(); + if (obj == nullptr){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid settings file.", PROGRAM_SETTING_JSON_PATH()); + } + + // Need to load this subset of settings first because they will affect how + // "GlobalSettings" is constructed. + const JsonValue* settings = obj->get_value("20-GlobalSettings"); + if (settings){ + PreloadSettings::instance().load(*settings); + GlobalSettings::instance().load_json(*settings); + } + +// GlobalSettings::instance().PROCESS_PRIORITY0.update_priority_to_option(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + +#if 0 + { + const JsonArray* array = obj->get_array("50-SwitchKeyboardMapping"); + if (array){ + NintendoSwitch::set_keyboard_mapping(*array); + } + } +#endif + { + JsonObject* value = obj->get_object("99-Panels"); + if (value){ +// panels = to_QJson(*value).toObject(); + panels = std::move(*value); + } + } +} + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/PersistentSettings.h b/SerialPrograms/Source/CommonFramework/PersistentSettings.h index d7e2f5d907..ca4cf7fd97 100644 --- a/SerialPrograms/Source/CommonFramework/PersistentSettings.h +++ b/SerialPrograms/Source/CommonFramework/PersistentSettings.h @@ -1,44 +1,44 @@ -/* Persistent Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_PersistentSettings_H -#define PokemonAutomation_PersistentSettings_H - -#include "Common/Cpp/Json/JsonObject.h" - -namespace PokemonAutomation{ - -// Global setting of the whole program. -// The setting is stored in the local folder, named as SerialPrograms-Settings.json. -// The settings json has three fields: -// - "20-GlobalSettings": settings for CommonFramework/GlobalSettingsPanel.h: GlobalSetting, -// global settings like Discord settings, hardware instruction set, thread priority and debugging. -// - "50-SwitchKeyboardMapping": keyboard mapping. -// - "99-Panels": settings for all the programs listed in the program panels. -// Access via PersistentSettings::panels. -class PersistentSettings{ -public: - PersistentSettings(); - - // Write settings to the json file. - void write() const; - // Load settings from the json file. - void read(); - -public: - JsonObject panels; -}; - -// Return the singleton PersistentSettings. -PersistentSettings& PERSISTENT_SETTINGS(); - - - -} - - -#endif +/* Persistent Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_PersistentSettings_H +#define PokemonAutomation_PersistentSettings_H + +#include "Common/Cpp/Json/JsonObject.h" + +namespace PokemonAutomation{ + +// Global setting of the whole program. +// The setting is stored in the local folder, named as SerialPrograms-Settings.json. +// The settings json has three fields: +// - "20-GlobalSettings": settings for CommonFramework/GlobalSettingsPanel.h: GlobalSetting, +// global settings like Discord settings, hardware instruction set, thread priority and debugging. +// - "50-SwitchKeyboardMapping": keyboard mapping. +// - "99-Panels": settings for all the programs listed in the program panels. +// Access via PersistentSettings::panels. +class PersistentSettings{ +public: + PersistentSettings(); + + // Write settings to the json file. + void write() const; + // Load settings from the json file. + void read(); + +public: + JsonObject panels; +}; + +// Return the singleton PersistentSettings. +PersistentSettings& PERSISTENT_SETTINGS(); + + + +} + + +#endif diff --git a/SerialPrograms/Source/CommonFramework/ProgramSession.cpp b/SerialPrograms/Source/CommonFramework/ProgramSession.cpp index 83c174350a..3544f180dd 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramSession.cpp +++ b/SerialPrograms/Source/CommonFramework/ProgramSession.cpp @@ -1,257 +1,257 @@ -/* Program Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Panels/ProgramDescriptor.h" -#include "CommonFramework/ProgramSession.h" -#include "CommonFramework/ProgramStats/StatsDatabase.h" -#include "Integrations/ProgramTracker.h" - -namespace PokemonAutomation{ - - - -void ProgramSession::add_listener(Listener& listener){ - m_listeners.add(listener); -} -void ProgramSession::remove_listener(Listener& listener){ - m_listeners.remove(listener); -} - - - -ProgramSession::ProgramSession(const ProgramDescriptor& descriptor) - : m_descriptor(descriptor) - , m_instance_id(ProgramTracker::instance().add_program(*this)) -// , m_logger(global_logger_raw(), "Program:" + std::to_string(m_instance_id)) - , m_logger(global_logger_raw(), "Program") - , m_timestamp(current_time()) - , m_state(ProgramState::STOPPED) -{ - load_historical_stats(); -} -ProgramSession::~ProgramSession(){ - ProgramTracker::instance().remove_program(m_instance_id); -// ProgramSession::request_program_stop(); -// join_program_thread(); -} - -void ProgramSession::join_program_thread(){ - if (m_thread.joinable()){ - m_thread.join(); - } -} - - - -const std::string& ProgramSession::identifier() const{ - return m_descriptor.identifier(); -} -std::string ProgramSession::current_stats() const{ - std::lock_guard lg(m_lock); - if (m_current_stats){ - return m_current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN); - } - return ""; -} -std::string ProgramSession::historical_stats() const{ - std::lock_guard lg(m_lock); - if (m_historical_stats){ - return m_historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN); - } - return ""; -} -WallClock ProgramSession::timestamp() const{ - return m_timestamp.load(std::memory_order_relaxed); -} - - -void ProgramSession::report_stats_changed(){ - std::lock_guard lg(m_lock); - push_stats(); -} -void ProgramSession::report_error(const std::string& message){ - std::lock_guard lg(m_lock); - push_error(message); -} - - -void ProgramSession::set_state(ProgramState state){ - switch (state){ - case ProgramState::NOT_READY: - m_logger.log("Program State: NOT_READY"); - break; - case ProgramState::STOPPED: - m_logger.log("Program State: STOPPED"); - break; - case ProgramState::RUNNING: - m_logger.log("Program State: RUNNING"); - break; - case ProgramState::STOPPING: - m_logger.log("Program State: STOPPING"); - break; - } - m_state.store(state, std::memory_order_relaxed); - m_listeners.run_method_unique(&Listener::state_change, state); -} -void ProgramSession::push_stats(){ - m_listeners.run_method_unique( - &Listener::stats_update, - m_current_stats.get(), - m_historical_stats.get() - ); -} -void ProgramSession::push_error(const std::string& message){ - m_listeners.run_method_unique(&Listener::error, message); -} - -void ProgramSession::load_historical_stats(){ - // Load historical stats. - std::unique_ptr stats = m_descriptor.make_stats(); - if (stats){ - m_logger.log("Loading historical stats..."); -// m_current_stats = m_descriptor.make_stats(); - StatSet set; - set.open_from_file(GlobalSettings::instance().STATS_FILE); - const std::string& identifier = m_descriptor.identifier(); - StatList& list = set[identifier]; - if (list.size() != 0){ - list.aggregate(*stats); - } - m_historical_stats = std::move(stats); - } -} -void ProgramSession::update_historical_stats_with_current(){ - if (m_current_stats){ - m_logger.log("Saving historical stats..."); - bool ok = StatSet::update_file( - GlobalSettings::instance().STATS_FILE, - m_descriptor.identifier(), - *m_current_stats - ); - if (ok){ - m_logger.log("Stats successfully saved!", COLOR_BLUE); - }else{ - m_logger.log("Unable to save stats.", COLOR_RED); - push_error("Unable to save stats."); - } - } -} - - -std::string ProgramSession::start_program(){ - m_logger.log("Received Program Start Request"); - std::lock_guard lg(m_lock); - - ProgramState state = this->current_state(); - switch (state){ - case ProgramState::NOT_READY: - m_logger.log("Program is not ready.", COLOR_RED); - return "Program is not ready."; - - case ProgramState::STOPPED:{ - std::string error = check_validity(); - if (!error.empty()){ - m_logger.log(error, COLOR_RED); - return error; - } - - // Wait for previous program thread to finish. - join_program_thread(); - - // Now start the program. - m_logger.log("Starting program..."); - m_timestamp.store(current_time(), std::memory_order_relaxed); - set_state(ProgramState::RUNNING); - m_thread = std::thread( - run_with_catch, - "ProgramSession::start_program()", - [this]{ run_program(); } - ); - - return ""; - } - case ProgramState::RUNNING: - m_logger.log("Program is already running.", COLOR_RED); - return "Program is already running."; - - case ProgramState::STOPPING: - m_logger.log("Program is currently stopping.", COLOR_RED); - return "Program is currently stopping."; - } - - throw InternalProgramError( - &m_logger, - PA_CURRENT_FUNCTION, - "Invalid State: " + std::to_string((int)state) - ); -} -std::string ProgramSession::stop_program(){ - m_logger.log("Received Stop Request"); - { - std::lock_guard lg(m_lock); - - ProgramState state = this->current_state(); - switch (state){ - case ProgramState::NOT_READY: - m_logger.log("Program is not ready.", COLOR_RED); - return "Program is not ready."; - case ProgramState::STOPPED: - m_logger.log("Program is already stopped.", COLOR_RED); - return "Program is already stopped."; - case ProgramState::RUNNING: - m_logger.log("Stopping program..."); - set_state(ProgramState::STOPPING); - break; - case ProgramState::STOPPING: - m_logger.log("Program is already stopping.", COLOR_RED); - return "Program is already stopping."; - default: - throw InternalProgramError( - &m_logger, - PA_CURRENT_FUNCTION, - "Invalid State: " + std::to_string((int)state) - ); - } - } - internal_stop_program(); - return ""; -} - - - -void ProgramSession::run_program(){ - { - std::lock_guard lg(m_lock); - m_current_stats = m_descriptor.make_stats(); - load_historical_stats(); - push_stats(); - } - internal_run_program(); - { - std::lock_guard lg(m_lock); - push_stats(); - update_historical_stats_with_current(); - set_state(ProgramState::STOPPED); - } -} - - - - - - - - - - - - - - -} +/* Program Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Panels/ProgramDescriptor.h" +#include "CommonFramework/ProgramSession.h" +#include "CommonFramework/ProgramStats/StatsDatabase.h" +#include "Integrations/ProgramTracker.h" + +namespace PokemonAutomation{ + + + +void ProgramSession::add_listener(Listener& listener){ + m_listeners.add(listener); +} +void ProgramSession::remove_listener(Listener& listener){ + m_listeners.remove(listener); +} + + + +ProgramSession::ProgramSession(const ProgramDescriptor& descriptor) + : m_descriptor(descriptor) + , m_instance_id(ProgramTracker::instance().add_program(*this)) +// , m_logger(global_logger_raw(), "Program:" + std::to_string(m_instance_id)) + , m_logger(global_logger_raw(), "Program") + , m_timestamp(current_time()) + , m_state(ProgramState::STOPPED) +{ + load_historical_stats(); +} +ProgramSession::~ProgramSession(){ + ProgramTracker::instance().remove_program(m_instance_id); +// ProgramSession::request_program_stop(); +// join_program_thread(); +} + +void ProgramSession::join_program_thread(){ + if (m_thread.joinable()){ + m_thread.join(); + } +} + + + +const std::string& ProgramSession::identifier() const{ + return m_descriptor.identifier(); +} +std::string ProgramSession::current_stats() const{ + std::lock_guard lg(m_lock); + if (m_current_stats){ + return m_current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN); + } + return ""; +} +std::string ProgramSession::historical_stats() const{ + std::lock_guard lg(m_lock); + if (m_historical_stats){ + return m_historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN); + } + return ""; +} +WallClock ProgramSession::timestamp() const{ + return m_timestamp.load(std::memory_order_relaxed); +} + + +void ProgramSession::report_stats_changed(){ + std::lock_guard lg(m_lock); + push_stats(); +} +void ProgramSession::report_error(const std::string& message){ + std::lock_guard lg(m_lock); + push_error(message); +} + + +void ProgramSession::set_state(ProgramState state){ + switch (state){ + case ProgramState::NOT_READY: + m_logger.log("Program State: NOT_READY"); + break; + case ProgramState::STOPPED: + m_logger.log("Program State: STOPPED"); + break; + case ProgramState::RUNNING: + m_logger.log("Program State: RUNNING"); + break; + case ProgramState::STOPPING: + m_logger.log("Program State: STOPPING"); + break; + } + m_state.store(state, std::memory_order_relaxed); + m_listeners.run_method_unique(&Listener::state_change, state); +} +void ProgramSession::push_stats(){ + m_listeners.run_method_unique( + &Listener::stats_update, + m_current_stats.get(), + m_historical_stats.get() + ); +} +void ProgramSession::push_error(const std::string& message){ + m_listeners.run_method_unique(&Listener::error, message); +} + +void ProgramSession::load_historical_stats(){ + // Load historical stats. + std::unique_ptr stats = m_descriptor.make_stats(); + if (stats){ + m_logger.log("Loading historical stats..."); +// m_current_stats = m_descriptor.make_stats(); + StatSet set; + set.open_from_file(GlobalSettings::instance().STATS_FILE); + const std::string& identifier = m_descriptor.identifier(); + StatList& list = set[identifier]; + if (list.size() != 0){ + list.aggregate(*stats); + } + m_historical_stats = std::move(stats); + } +} +void ProgramSession::update_historical_stats_with_current(){ + if (m_current_stats){ + m_logger.log("Saving historical stats..."); + bool ok = StatSet::update_file( + GlobalSettings::instance().STATS_FILE, + m_descriptor.identifier(), + *m_current_stats + ); + if (ok){ + m_logger.log("Stats successfully saved!", COLOR_BLUE); + }else{ + m_logger.log("Unable to save stats.", COLOR_RED); + push_error("Unable to save stats."); + } + } +} + + +std::string ProgramSession::start_program(){ + m_logger.log("Received Program Start Request"); + std::lock_guard lg(m_lock); + + ProgramState state = this->current_state(); + switch (state){ + case ProgramState::NOT_READY: + m_logger.log("Program is not ready.", COLOR_RED); + return "Program is not ready."; + + case ProgramState::STOPPED:{ + std::string error = check_validity(); + if (!error.empty()){ + m_logger.log(error, COLOR_RED); + return error; + } + + // Wait for previous program thread to finish. + join_program_thread(); + + // Now start the program. + m_logger.log("Starting program..."); + m_timestamp.store(current_time(), std::memory_order_relaxed); + set_state(ProgramState::RUNNING); + m_thread = std::thread( + run_with_catch, + "ProgramSession::start_program()", + [this]{ run_program(); } + ); + + return ""; + } + case ProgramState::RUNNING: + m_logger.log("Program is already running.", COLOR_RED); + return "Program is already running."; + + case ProgramState::STOPPING: + m_logger.log("Program is currently stopping.", COLOR_RED); + return "Program is currently stopping."; + } + + throw InternalProgramError( + &m_logger, + PA_CURRENT_FUNCTION, + "Invalid State: " + std::to_string((int)state) + ); +} +std::string ProgramSession::stop_program(){ + m_logger.log("Received Stop Request"); + { + std::lock_guard lg(m_lock); + + ProgramState state = this->current_state(); + switch (state){ + case ProgramState::NOT_READY: + m_logger.log("Program is not ready.", COLOR_RED); + return "Program is not ready."; + case ProgramState::STOPPED: + m_logger.log("Program is already stopped.", COLOR_RED); + return "Program is already stopped."; + case ProgramState::RUNNING: + m_logger.log("Stopping program..."); + set_state(ProgramState::STOPPING); + break; + case ProgramState::STOPPING: + m_logger.log("Program is already stopping.", COLOR_RED); + return "Program is already stopping."; + default: + throw InternalProgramError( + &m_logger, + PA_CURRENT_FUNCTION, + "Invalid State: " + std::to_string((int)state) + ); + } + } + internal_stop_program(); + return ""; +} + + + +void ProgramSession::run_program(){ + { + std::lock_guard lg(m_lock); + m_current_stats = m_descriptor.make_stats(); + load_historical_stats(); + push_stats(); + } + internal_run_program(); + { + std::lock_guard lg(m_lock); + push_stats(); + update_historical_stats_with_current(); + set_state(ProgramState::STOPPED); + } +} + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ProgramSession.h b/SerialPrograms/Source/CommonFramework/ProgramSession.h index aa8444df8e..79ac3c2da1 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramSession.h +++ b/SerialPrograms/Source/CommonFramework/ProgramSession.h @@ -1,147 +1,147 @@ -/* Program Session - * - * From: https://github.com/PokemonAutomation/ - * - * ProgramSession represents the real-time state of a program. - * - * It holds the state machine whether it's running/stopping, etc... It also - * holds misc. data that is common to all programs. - * - * As with all "Session" classes, this class is fully thread-safe and is - * not responsible for any UI. UI classes must attach themselves to a - * session to receive updates. - * - */ - -#ifndef PokemonAutomation_CommonFramework_ProgramSession_H -#define PokemonAutomation_CommonFramework_ProgramSession_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/ListenerSet.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "Integrations/ProgramTrackerInterfaces.h" - -namespace PokemonAutomation{ - -class StatsTracker; -class CancellableScope; -class ProgramDescriptor; - - - -class ProgramSession : public TrackableProgram{ -public: - struct Listener{ - virtual void state_change(ProgramState state) = 0; - virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) = 0; - virtual void error(const std::string& message) = 0; - }; - - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - - -public: - // Setup - - ProgramSession(const ProgramDescriptor& descriptor); - - // Before the child-most class begins destruction, you must first: - // 1. Stop the program. - // 2. Join the program thread. - virtual ~ProgramSession(); - - const ProgramDescriptor& descriptor() const{ return m_descriptor; } - uint64_t instance_id() const{ return m_instance_id; } - Logger& logger(){ return m_logger; } - - -public: - // Getters - - virtual const std::string& identifier() const override final; - virtual ProgramState current_state() const override final{ return m_state.load(std::memory_order_relaxed); } - virtual std::string current_stats() const override final; - std::string historical_stats() const; - virtual WallClock timestamp() const final; - - // Temporary for migration. - StatsTracker* current_stats_tracker(){ return m_current_stats.get(); } - const StatsTracker* historical_stats_tracker() const{ return m_historical_stats.get(); } - - std::mutex& program_lock() const{ return m_lock; } - - -public: - // Program Control - - // Returns empty string on success. Otherwise returns error string. - // Note that these are asynchronous and will return before they are finished. - - std::string start_program(); // Returns before the program is fully started up. - std::string stop_program(); // Returns before the program is completely stopped. - - // Temporary - virtual void async_start() override{ start_program(); } - virtual void async_stop() override{ stop_program(); } - - -protected: - virtual void internal_run_program() = 0; - virtual void internal_stop_program() = 0; - -// virtual void restore_defaults(){ return; } - -public: - void report_stats_changed(); - void report_error(const std::string& message); - - -protected: - // Everything here must be called under the lock. - - virtual std::string check_validity() const{ return ""; } - void join_program_thread(); - -private: - // Everything here must be called under the lock. - - void set_state(ProgramState state); - void push_stats(); - void push_error(const std::string& message); - void load_historical_stats(); - void update_historical_stats_with_current(); - - -private: - void run_program(); - - -private: - const ProgramDescriptor& m_descriptor; - - uint64_t m_instance_id = 0; - TaggedLogger m_logger; - - mutable std::mutex m_lock; - - std::atomic m_timestamp; - std::atomic m_state; - std::thread m_thread; - -// std::mutex m_stats_lock; - std::unique_ptr m_historical_stats; - std::unique_ptr m_current_stats; -// CancellableScope* m_scope = nullptr; - - ListenerSet m_listeners; -}; - - - -} -#endif +/* Program Session + * + * From: https://github.com/PokemonAutomation/ + * + * ProgramSession represents the real-time state of a program. + * + * It holds the state machine whether it's running/stopping, etc... It also + * holds misc. data that is common to all programs. + * + * As with all "Session" classes, this class is fully thread-safe and is + * not responsible for any UI. UI classes must attach themselves to a + * session to receive updates. + * + */ + +#ifndef PokemonAutomation_CommonFramework_ProgramSession_H +#define PokemonAutomation_CommonFramework_ProgramSession_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/ListenerSet.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "Integrations/ProgramTrackerInterfaces.h" + +namespace PokemonAutomation{ + +class StatsTracker; +class CancellableScope; +class ProgramDescriptor; + + + +class ProgramSession : public TrackableProgram{ +public: + struct Listener{ + virtual void state_change(ProgramState state) = 0; + virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) = 0; + virtual void error(const std::string& message) = 0; + }; + + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + + +public: + // Setup + + ProgramSession(const ProgramDescriptor& descriptor); + + // Before the child-most class begins destruction, you must first: + // 1. Stop the program. + // 2. Join the program thread. + virtual ~ProgramSession(); + + const ProgramDescriptor& descriptor() const{ return m_descriptor; } + uint64_t instance_id() const{ return m_instance_id; } + Logger& logger(){ return m_logger; } + + +public: + // Getters + + virtual const std::string& identifier() const override final; + virtual ProgramState current_state() const override final{ return m_state.load(std::memory_order_relaxed); } + virtual std::string current_stats() const override final; + std::string historical_stats() const; + virtual WallClock timestamp() const final; + + // Temporary for migration. + StatsTracker* current_stats_tracker(){ return m_current_stats.get(); } + const StatsTracker* historical_stats_tracker() const{ return m_historical_stats.get(); } + + std::mutex& program_lock() const{ return m_lock; } + + +public: + // Program Control + + // Returns empty string on success. Otherwise returns error string. + // Note that these are asynchronous and will return before they are finished. + + std::string start_program(); // Returns before the program is fully started up. + std::string stop_program(); // Returns before the program is completely stopped. + + // Temporary + virtual void async_start() override{ start_program(); } + virtual void async_stop() override{ stop_program(); } + + +protected: + virtual void internal_run_program() = 0; + virtual void internal_stop_program() = 0; + +// virtual void restore_defaults(){ return; } + +public: + void report_stats_changed(); + void report_error(const std::string& message); + + +protected: + // Everything here must be called under the lock. + + virtual std::string check_validity() const{ return ""; } + void join_program_thread(); + +private: + // Everything here must be called under the lock. + + void set_state(ProgramState state); + void push_stats(); + void push_error(const std::string& message); + void load_historical_stats(); + void update_historical_stats_with_current(); + + +private: + void run_program(); + + +private: + const ProgramDescriptor& m_descriptor; + + uint64_t m_instance_id = 0; + TaggedLogger m_logger; + + mutable std::mutex m_lock; + + std::atomic m_timestamp; + std::atomic m_state; + std::thread m_thread; + +// std::mutex m_stats_lock; + std::unique_ptr m_historical_stats; + std::unique_ptr m_current_stats; +// CancellableScope* m_scope = nullptr; + + ListenerSet m_listeners; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp index b6465c4239..ab4eb16ac9 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.cpp @@ -1,248 +1,248 @@ -/* Stats Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "ClientSource/Libraries/Logging.h" -#include "StatsDatabase.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -const std::map STATS_DATABASE_ALIASES{ - {"Dex Rec Finder", "PokemonSwSh:DexRecFinder"}, - {"Day Skipper (JPN)", "PokemonSwSh:DaySkipperJPN"}, - {"Day Skipper (EU)", "PokemonSwSh:DaySkipperEU"}, - {"Day Skipper (US)", "PokemonSwSh:DaySkipperUS"}, - {"Day Skipper (JPN) - 7.8k", "PokemonSwSh:DaySkipperJPN7p8k"}, - {"Purple Beam Finder", "PokemonSwSh:PurpleBeamFinder"}, - {"Auto-Host Multi-Game", "PokemonSwSh:AutoHostMultiGame"}, - {"Auto-Host Rolling", "PokemonSwSh:AutoHostRolling"}, - {"Stats Reset", "PokemonSwSh:StatsReset"}, - {"Shiny Hunt Autonomous - Regi", "PokemonSwSh:ShinyHuntAutonomousRegi"}, - {"Shiny Hunt Autonomous - Swords Of Justice", "PokemonSwSh:ShinyHuntAutonomousSwordsOfJustice"}, - {"Shiny Hunt Autonomous - Strong Spawn", "PokemonSwSh:ShinyHuntAutonomousStrongSpawn"}, - {"Shiny Hunt Autonomous - Regigigas2", "PokemonSwSh:ShinyHuntAutonomousRegigigas2"}, - {"Shiny Hunt Autonomous - IoA Trade", "PokemonSwSh:ShinyHuntAutonomousIoATrade"}, - {"Shiny Hunt Autonomous - Berry Tree", "PokemonSwSh:ShinyHuntAutonomousBerryTree"}, - {"Shiny Hunt Autonomous - Whistling", "PokemonSwSh:ShinyHuntAutonomousWhistling"}, - {"Shiny Hunt Autonomous - Fishing", "PokemonSwSh:ShinyHuntAutonomousFishing"}, - {"Shiny Hunt Autonomous - Overworld", "PokemonSwSh:ShinyHuntAutonomousOverworld"}, - {"PokemonSV:StatsResetBloodmoon", "PokemonSV:StatsResetEventBattle"}, -}; - - - -StatLine::StatLine(StatsTracker& tracker) - : m_time(current_time_to_str()) - , m_stats(tracker.to_str(StatsTracker::SAVE_TO_STATS_FILE)) -{} -StatLine::StatLine(const std::string& line){ - size_t pos = line.find(" - "); - if (pos == std::string::npos){ - m_time = line; - return; - } - m_time = line.substr(0, pos); - - const char* ptr = line.c_str() + pos + 3; - - // Skip to stats. - while (true){ - char ch = *ptr; - if (ch < 32) return; - if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; - ptr++; - } - - m_stats = ptr; -} -std::string StatLine::to_str() const{ - return m_time + " - " + m_stats; -#if 0 - std::string str = m_time + " - "; - str += m_tracker - ? m_tracker->to_str() - : m_stats; - return m_time + " - " + - (m_tracker ? m_tracker->to_str() : m_stats); -#endif -} - - - - -void StatList::operator+=(StatsTracker& tracker){ - m_list.emplace_back(tracker); -} -void StatList::operator+=(const std::string& line){ - m_list.emplace_back(line); -} -std::string StatList::to_str() const{ - std::string str; - for (const StatLine& line : m_list){ - str += line.to_str(); - str += "\r\n"; - } - return str; -} - -void StatList::aggregate(StatsTracker& tracker) const{ - for (const StatLine& line : m_list){ - tracker.parse_and_append_line(line.stats()); -// cout << tracker.to_str() << endl; - } -} - - - - -#if 0 -StatList* StatSet::find(const std::string& label){ - auto iter = m_data.find(label); - return iter == m_data.end() - ? nullptr - : &iter->second; -} -#endif -StatList& StatSet::operator[](const std::string& identifier){ - return m_data[identifier]; -} - -std::string StatSet::to_str() const{ - std::string str; - for (const auto& item : m_data){ - if (item.second.size() == 0){ - continue; - } - str += "================================================================================\r\n"; - str += item.first; - str += "\r\n"; - str += "\r\n"; - str += item.second.to_str(); - str += "\r\n"; - } - return str; -} - -void StatSet::save_to_file(const std::string& filepath){ - QFile file(QString::fromStdString(filepath)); - file.open(QIODevice::WriteOnly); - std::string data = to_str(); - file.write(data.c_str(), data.size()); -} -void StatSet::open_from_file(const std::string& filepath){ - QFile file(QString::fromStdString(filepath)); - if (!file.open(QIODevice::ReadOnly)){ - return; - } - - std::string str = file.readAll().data(); - load_from_string(str.c_str()); -} - -bool StatSet::update_file( - const std::string& filepath, - const std::string& identifier, - StatsTracker& tracker -){ - QFile file(QString::fromStdString(filepath)); - while (!file.open(QIODevice::ReadWrite)){ - return false; - } - std::string data = file.readAll().data(); - - StatSet set; - set.load_from_string(data.c_str()); - - set[identifier] += tracker; - - data = set.to_str(); - file.seek(0); - file.write(data.c_str(), data.size()); - file.resize(data.size()); - - return true; -} - - -bool StatSet::get_line(std::string& line, const char*& ptr){ - line.clear(); - for (;; ptr++){ - char ch = *ptr; - if (ch == '\0'){ -// cout << line << endl; - ptr++; - return false; - } - if (ch == '\r'){ - continue; - } - if (ch == '\n'){ -// cout << line << endl; - ptr++; - return true; - } - line += ch; - } -} -void StatSet::load_from_string(const char* ptr){ - m_data.clear(); - - // Find first section. - while (true){ - std::string line; - if (!get_line(line, ptr)){ - return; - } - if (line[0] == '='){ - break; - } - } - - while (true){ - std::string line; - if (!get_line(line, ptr)){ - return; - } - if (line.empty()){ - continue; - } - - auto iter = STATS_DATABASE_ALIASES.find(line); - if (iter != STATS_DATABASE_ALIASES.end()){ - line = iter->second; - } - - StatList& program = m_data[line]; - while (true){ - if (!get_line(line, ptr)){ - return; - } - if (line.empty()){ - continue; - } - if (line[0] == '='){ - break; - } - program += line; - } - } -} - - - - - - - - - -} - +/* Stats Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "ClientSource/Libraries/Logging.h" +#include "StatsDatabase.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +const std::map STATS_DATABASE_ALIASES{ + {"Dex Rec Finder", "PokemonSwSh:DexRecFinder"}, + {"Day Skipper (JPN)", "PokemonSwSh:DaySkipperJPN"}, + {"Day Skipper (EU)", "PokemonSwSh:DaySkipperEU"}, + {"Day Skipper (US)", "PokemonSwSh:DaySkipperUS"}, + {"Day Skipper (JPN) - 7.8k", "PokemonSwSh:DaySkipperJPN7p8k"}, + {"Purple Beam Finder", "PokemonSwSh:PurpleBeamFinder"}, + {"Auto-Host Multi-Game", "PokemonSwSh:AutoHostMultiGame"}, + {"Auto-Host Rolling", "PokemonSwSh:AutoHostRolling"}, + {"Stats Reset", "PokemonSwSh:StatsReset"}, + {"Shiny Hunt Autonomous - Regi", "PokemonSwSh:ShinyHuntAutonomousRegi"}, + {"Shiny Hunt Autonomous - Swords Of Justice", "PokemonSwSh:ShinyHuntAutonomousSwordsOfJustice"}, + {"Shiny Hunt Autonomous - Strong Spawn", "PokemonSwSh:ShinyHuntAutonomousStrongSpawn"}, + {"Shiny Hunt Autonomous - Regigigas2", "PokemonSwSh:ShinyHuntAutonomousRegigigas2"}, + {"Shiny Hunt Autonomous - IoA Trade", "PokemonSwSh:ShinyHuntAutonomousIoATrade"}, + {"Shiny Hunt Autonomous - Berry Tree", "PokemonSwSh:ShinyHuntAutonomousBerryTree"}, + {"Shiny Hunt Autonomous - Whistling", "PokemonSwSh:ShinyHuntAutonomousWhistling"}, + {"Shiny Hunt Autonomous - Fishing", "PokemonSwSh:ShinyHuntAutonomousFishing"}, + {"Shiny Hunt Autonomous - Overworld", "PokemonSwSh:ShinyHuntAutonomousOverworld"}, + {"PokemonSV:StatsResetBloodmoon", "PokemonSV:StatsResetEventBattle"}, +}; + + + +StatLine::StatLine(StatsTracker& tracker) + : m_time(current_time_to_str()) + , m_stats(tracker.to_str(StatsTracker::SAVE_TO_STATS_FILE)) +{} +StatLine::StatLine(const std::string& line){ + size_t pos = line.find(" - "); + if (pos == std::string::npos){ + m_time = line; + return; + } + m_time = line.substr(0, pos); + + const char* ptr = line.c_str() + pos + 3; + + // Skip to stats. + while (true){ + char ch = *ptr; + if (ch < 32) return; + if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; + ptr++; + } + + m_stats = ptr; +} +std::string StatLine::to_str() const{ + return m_time + " - " + m_stats; +#if 0 + std::string str = m_time + " - "; + str += m_tracker + ? m_tracker->to_str() + : m_stats; + return m_time + " - " + + (m_tracker ? m_tracker->to_str() : m_stats); +#endif +} + + + + +void StatList::operator+=(StatsTracker& tracker){ + m_list.emplace_back(tracker); +} +void StatList::operator+=(const std::string& line){ + m_list.emplace_back(line); +} +std::string StatList::to_str() const{ + std::string str; + for (const StatLine& line : m_list){ + str += line.to_str(); + str += "\r\n"; + } + return str; +} + +void StatList::aggregate(StatsTracker& tracker) const{ + for (const StatLine& line : m_list){ + tracker.parse_and_append_line(line.stats()); +// cout << tracker.to_str() << endl; + } +} + + + + +#if 0 +StatList* StatSet::find(const std::string& label){ + auto iter = m_data.find(label); + return iter == m_data.end() + ? nullptr + : &iter->second; +} +#endif +StatList& StatSet::operator[](const std::string& identifier){ + return m_data[identifier]; +} + +std::string StatSet::to_str() const{ + std::string str; + for (const auto& item : m_data){ + if (item.second.size() == 0){ + continue; + } + str += "================================================================================\r\n"; + str += item.first; + str += "\r\n"; + str += "\r\n"; + str += item.second.to_str(); + str += "\r\n"; + } + return str; +} + +void StatSet::save_to_file(const std::string& filepath){ + QFile file(QString::fromStdString(filepath)); + file.open(QIODevice::WriteOnly); + std::string data = to_str(); + file.write(data.c_str(), data.size()); +} +void StatSet::open_from_file(const std::string& filepath){ + QFile file(QString::fromStdString(filepath)); + if (!file.open(QIODevice::ReadOnly)){ + return; + } + + std::string str = file.readAll().data(); + load_from_string(str.c_str()); +} + +bool StatSet::update_file( + const std::string& filepath, + const std::string& identifier, + StatsTracker& tracker +){ + QFile file(QString::fromStdString(filepath)); + while (!file.open(QIODevice::ReadWrite)){ + return false; + } + std::string data = file.readAll().data(); + + StatSet set; + set.load_from_string(data.c_str()); + + set[identifier] += tracker; + + data = set.to_str(); + file.seek(0); + file.write(data.c_str(), data.size()); + file.resize(data.size()); + + return true; +} + + +bool StatSet::get_line(std::string& line, const char*& ptr){ + line.clear(); + for (;; ptr++){ + char ch = *ptr; + if (ch == '\0'){ +// cout << line << endl; + ptr++; + return false; + } + if (ch == '\r'){ + continue; + } + if (ch == '\n'){ +// cout << line << endl; + ptr++; + return true; + } + line += ch; + } +} +void StatSet::load_from_string(const char* ptr){ + m_data.clear(); + + // Find first section. + while (true){ + std::string line; + if (!get_line(line, ptr)){ + return; + } + if (line[0] == '='){ + break; + } + } + + while (true){ + std::string line; + if (!get_line(line, ptr)){ + return; + } + if (line.empty()){ + continue; + } + + auto iter = STATS_DATABASE_ALIASES.find(line); + if (iter != STATS_DATABASE_ALIASES.end()){ + line = iter->second; + } + + StatList& program = m_data[line]; + while (true){ + if (!get_line(line, ptr)){ + return; + } + if (line.empty()){ + continue; + } + if (line[0] == '='){ + break; + } + program += line; + } + } +} + + + + + + + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h index 18aa914f91..196c5fc025 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsDatabase.h @@ -1,76 +1,76 @@ -/* Stats Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StatsDatabase_H -#define PokemonAutomation_StatsDatabase_H - -#include "StatsTracking.h" - -namespace PokemonAutomation{ - - -class StatLine{ -public: - StatLine(StatsTracker& tracker); - StatLine(const std::string& line); - - const std::string& stats() const{ return m_stats; } - std::string to_str() const; - -private: - std::string m_time; - std::string m_stats; -}; - - - -class StatList{ -public: - void operator+=(StatsTracker& tracker); - void operator+=(const std::string& line); - - size_t size() const{ return m_list.size(); } - std::string to_str() const; - - const std::vector& list() const{ return m_list; } - - void aggregate(StatsTracker& tracker) const; - -private: - std::vector m_list; -}; - - - - -class StatSet{ -public: -// StatList* find(const std::string& label); - StatList& operator[](const std::string& identifier); - - std::string to_str() const; - - void save_to_file(const std::string& filepath); - void open_from_file(const std::string& filepath); - - static bool update_file( - const std::string& filepath, - const std::string& identifier, - StatsTracker& tracker - ); - -private: - bool get_line(std::string& line, const char*& ptr); - void load_from_string(const char* ptr); - -private: - std::map m_data; -}; - - - -} -#endif +/* Stats Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StatsDatabase_H +#define PokemonAutomation_StatsDatabase_H + +#include "StatsTracking.h" + +namespace PokemonAutomation{ + + +class StatLine{ +public: + StatLine(StatsTracker& tracker); + StatLine(const std::string& line); + + const std::string& stats() const{ return m_stats; } + std::string to_str() const; + +private: + std::string m_time; + std::string m_stats; +}; + + + +class StatList{ +public: + void operator+=(StatsTracker& tracker); + void operator+=(const std::string& line); + + size_t size() const{ return m_list.size(); } + std::string to_str() const; + + const std::vector& list() const{ return m_list; } + + void aggregate(StatsTracker& tracker) const; + +private: + std::vector m_list; +}; + + + + +class StatSet{ +public: +// StatList* find(const std::string& label); + StatList& operator[](const std::string& identifier); + + std::string to_str() const; + + void save_to_file(const std::string& filepath); + void open_from_file(const std::string& filepath); + + static bool update_file( + const std::string& filepath, + const std::string& identifier, + StatsTracker& tracker + ); + +private: + bool get_line(std::string& line, const char*& ptr); + void load_from_string(const char* ptr); + +private: + std::map m_data; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp index b8f916bcce..54dfdf193c 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.cpp @@ -1,192 +1,192 @@ -/* Stats Tracking - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/PrettyPrint.h" -#include "StatsTracking.h" - -namespace PokemonAutomation{ - - - -StatsTracker::Stat::Stat(std::string&& p_label, DisplayMode p_display_node) - : label(p_label) - , display_mode(p_display_node) -{} -std::string StatsTracker::to_str(PrintMode mode) const{ - std::map stats; - for (const auto& item : m_stats){ - auto alias = m_aliases.find(item.first); - - // Not an alias. - if (alias == m_aliases.end()){ - stats[item.first] += item.second.load(std::memory_order_relaxed); - continue; - } - - // Find alias target. - auto iter = m_stats.find(alias->second); - if (iter != m_stats.end()){ - stats[alias->second] += item.second.load(std::memory_order_relaxed); - } - } - - std::string str; - for (const Stat& stat : m_display_order){ - auto iter = stats.find(stat.label); - uint64_t count = 0; - if (iter != stats.end()){ - count += iter->second; - } - - switch (stat.display_mode){ - case ALWAYS_VISIBLE: - break; - case HIDDEN_IF_ZERO: - if (count == 0){ - continue; - }else{ - break; - } - case ALWAYS_HIDDEN: - switch (mode){ - case DISPLAY_ON_SCREEN: - continue; - case SAVE_TO_STATS_FILE: - if (count == 0){ - continue; - }else{ - break; - } - } - } - - if (!str.empty()){ - str += " - "; - } - str += stat.label; - str += ": "; - str += tostr_u_commas(count); - } - return str; -} - - - -void StatsTracker::parse_and_append_line(const std::string& line){ - const char* ptr = line.c_str(); - while (true){ - // Parse label. - std::string label; - while (true){ - char ch = *ptr++; - if (ch < 32) return; - if (ch == ':') break; - label += ch; - } - - // Skip to number. - while (true){ - char ch = *ptr; - if (ch < 32) return; - if ('0' <= ch && ch <= '9') break; - ptr++; - } - - // Parse number. - uint64_t count = 0; - while (true){ - char ch = *ptr++; - if (ch < 32){ - m_stats[label] += count; - return; - } - if (ch == ',') continue; - if (!('0' <= ch && ch <= '9')) break; - count *= 10; - count += ch - '0'; - } - -// cout << label << " = " << count << endl; - m_stats[label] += count; - - // Skip to next; - while (true){ - char ch = *ptr; - if (ch < 32) return; - if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; - ptr++; - } - } -} - - - -std::string stats_to_bar( - Logger& logger, - const StatsTracker* historical, - const StatsTracker* current, - const std::string& override_current -){ - std::string current_str; - if (!override_current.empty()){ - current_str = override_current; - }else if (current){ - current_str = current->to_str(StatsTracker::DISPLAY_ON_SCREEN); - } - - std::string historical_str; - if (historical){ - historical_str = historical->to_str(StatsTracker::DISPLAY_ON_SCREEN); - } - - if (current_str.empty() && historical_str.empty()){ - return ""; - } - - if (!current_str.empty() && historical_str.empty()){ - logger.log(current_str); - return current_str; - } - if (current_str.empty() && !historical_str.empty()){ - return "Past Runs - " + historical_str; - } - - logger.log(current_str); - - std::string str; - str += "Current Run - " + current_str; - str += "
"; - str += "Past Totals - " + historical_str; - - return str; -} - - - - - - - - - - - - - - - - - - - - - - - - - -} +/* Stats Tracking + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/PrettyPrint.h" +#include "StatsTracking.h" + +namespace PokemonAutomation{ + + + +StatsTracker::Stat::Stat(std::string&& p_label, DisplayMode p_display_node) + : label(p_label) + , display_mode(p_display_node) +{} +std::string StatsTracker::to_str(PrintMode mode) const{ + std::map stats; + for (const auto& item : m_stats){ + auto alias = m_aliases.find(item.first); + + // Not an alias. + if (alias == m_aliases.end()){ + stats[item.first] += item.second.load(std::memory_order_relaxed); + continue; + } + + // Find alias target. + auto iter = m_stats.find(alias->second); + if (iter != m_stats.end()){ + stats[alias->second] += item.second.load(std::memory_order_relaxed); + } + } + + std::string str; + for (const Stat& stat : m_display_order){ + auto iter = stats.find(stat.label); + uint64_t count = 0; + if (iter != stats.end()){ + count += iter->second; + } + + switch (stat.display_mode){ + case ALWAYS_VISIBLE: + break; + case HIDDEN_IF_ZERO: + if (count == 0){ + continue; + }else{ + break; + } + case ALWAYS_HIDDEN: + switch (mode){ + case DISPLAY_ON_SCREEN: + continue; + case SAVE_TO_STATS_FILE: + if (count == 0){ + continue; + }else{ + break; + } + } + } + + if (!str.empty()){ + str += " - "; + } + str += stat.label; + str += ": "; + str += tostr_u_commas(count); + } + return str; +} + + + +void StatsTracker::parse_and_append_line(const std::string& line){ + const char* ptr = line.c_str(); + while (true){ + // Parse label. + std::string label; + while (true){ + char ch = *ptr++; + if (ch < 32) return; + if (ch == ':') break; + label += ch; + } + + // Skip to number. + while (true){ + char ch = *ptr; + if (ch < 32) return; + if ('0' <= ch && ch <= '9') break; + ptr++; + } + + // Parse number. + uint64_t count = 0; + while (true){ + char ch = *ptr++; + if (ch < 32){ + m_stats[label] += count; + return; + } + if (ch == ',') continue; + if (!('0' <= ch && ch <= '9')) break; + count *= 10; + count += ch - '0'; + } + +// cout << label << " = " << count << endl; + m_stats[label] += count; + + // Skip to next; + while (true){ + char ch = *ptr; + if (ch < 32) return; + if (('A' <= ch && ch <= 'Z') || ('a' <= ch && ch <= 'z')) break; + ptr++; + } + } +} + + + +std::string stats_to_bar( + Logger& logger, + const StatsTracker* historical, + const StatsTracker* current, + const std::string& override_current +){ + std::string current_str; + if (!override_current.empty()){ + current_str = override_current; + }else if (current){ + current_str = current->to_str(StatsTracker::DISPLAY_ON_SCREEN); + } + + std::string historical_str; + if (historical){ + historical_str = historical->to_str(StatsTracker::DISPLAY_ON_SCREEN); + } + + if (current_str.empty() && historical_str.empty()){ + return ""; + } + + if (!current_str.empty() && historical_str.empty()){ + logger.log(current_str); + return current_str; + } + if (current_str.empty() && !historical_str.empty()){ + return "Past Runs - " + historical_str; + } + + logger.log(current_str); + + std::string str; + str += "Current Run - " + current_str; + str += "
"; + str += "Past Totals - " + historical_str; + + return str; +} + + + + + + + + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h index f50f1323a8..4e12117e9f 100644 --- a/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h +++ b/SerialPrograms/Source/CommonFramework/ProgramStats/StatsTracking.h @@ -1,67 +1,67 @@ -/* Stats Tracking - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StatsTracking_H -#define PokemonAutomation_StatsTracking_H - -#include -#include -#include -#include - -namespace PokemonAutomation{ - -class Logger; - -class StatsTracker{ - StatsTracker(const StatsTracker&) = delete; - -public: - StatsTracker() = default; - virtual ~StatsTracker() = default; - - enum PrintMode{ - DISPLAY_ON_SCREEN, - SAVE_TO_STATS_FILE, - }; - virtual std::string to_str(PrintMode mode) const; - - void parse_and_append_line(const std::string& line); - - -protected: -// static constexpr bool HIDDEN_IF_ZERO = true; -// static constexpr bool ALWAYS_VISIBLE = false; - enum DisplayMode{ - ALWAYS_VISIBLE, - HIDDEN_IF_ZERO, - ALWAYS_HIDDEN, - }; - - struct Stat{ - std::string label; - DisplayMode display_mode; - Stat(std::string&& p_label, DisplayMode p_display_node = ALWAYS_VISIBLE); - }; - - std::vector m_display_order; - std::map> m_stats; - std::map m_aliases; -}; - - -std::string stats_to_bar( - Logger& logger, - const StatsTracker* historical, - const StatsTracker* current, - const std::string& override_current = "" -); - - - - -} -#endif +/* Stats Tracking + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StatsTracking_H +#define PokemonAutomation_StatsTracking_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ + +class Logger; + +class StatsTracker{ + StatsTracker(const StatsTracker&) = delete; + +public: + StatsTracker() = default; + virtual ~StatsTracker() = default; + + enum PrintMode{ + DISPLAY_ON_SCREEN, + SAVE_TO_STATS_FILE, + }; + virtual std::string to_str(PrintMode mode) const; + + void parse_and_append_line(const std::string& line); + + +protected: +// static constexpr bool HIDDEN_IF_ZERO = true; +// static constexpr bool ALWAYS_VISIBLE = false; + enum DisplayMode{ + ALWAYS_VISIBLE, + HIDDEN_IF_ZERO, + ALWAYS_HIDDEN, + }; + + struct Stat{ + std::string label; + DisplayMode display_mode; + Stat(std::string&& p_label, DisplayMode p_display_node = ALWAYS_VISIBLE); + }; + + std::vector m_display_order; + std::map> m_stats; + std::map m_aliases; +}; + + +std::string stats_to_bar( + Logger& logger, + const StatsTracker* historical, + const StatsTracker* current, + const std::string& override_current = "" +); + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp index 448a3e7566..d8d6d96518 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.cpp @@ -1,117 +1,117 @@ -/* Stream History Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "StreamHistoryOption.h" - -namespace PokemonAutomation{ - -StreamHistoryOption::StreamHistoryOption() - : GroupOption( - "Stream History", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_DISABLED, - true - ) - , DESCRIPTION( - "Keep a record of the recent video+audio streams. This will allow video capture " - "for unexpected events.

" - "Warning: This feature has a known memory leak. It will leak ~3GB per day per " - "video stream. You have been warned!" - "

" - "Warning: This feature is computationally expensive and " - "will require a more powerful computer to run (especially for multi-Switch programs).
" - "Furthermore, the current implementation is inefficient as it will write a lot " - "of data to disk. This feature is still a work-in-progress." - "
" - ) - , HISTORY_SECONDS( - "History (seconds):
" - "Keep this many seconds of video and audio feed for video capture and debugging purposes.

" - "Do not set this too large as it will consume a lot of memory and may exceed the " - "attachment size limit for Discord notifications." - "", - LockMode::UNLOCK_WHILE_RUNNING, - 30 - ) - , RESOLUTION( - "Resolution:", - { - {Resolution::MATCH_INPUT, "match", "Match Input Resolution"}, - {Resolution::FORCE_720p, "720p", "1280 x 720"}, - {Resolution::FORCE_1080p, "1080p", "1920 x 1080"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - Resolution::FORCE_720p - ) - , ENCODING_MODE( - "Encoding Mode:", - { - {EncodingMode::FIXED_QUALITY, "fixed-quality", "Fixed Quality"}, - {EncodingMode::FIXED_BITRATE, "fixed-bitrate", "Fixed Bit Rate"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - EncodingMode::FIXED_QUALITY - ) - , VIDEO_QUALITY( - "Video Quality:
" - "High quality videos will take more disk space " - "and may exceed the attachment size limit for Discord notifications." - "", - { - {VideoQuality::VERY_LOW, "very-low", "Very Low"}, - {VideoQuality::LOW, "low", "Low"}, - {VideoQuality::NORMAL, "normal", "Normal"}, - {VideoQuality::HIGH, "high", "High"}, - {VideoQuality::VERY_HIGH, "very-high", "Very High"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - VideoQuality::LOW - ) - , VIDEO_BITRATE( - "Video Bit-Rate (kbps):
" - "Lower = lower quality, smaller file size.
" - "Higher = high quality, larger file size.
" - "Large values can exceed the attachment size limit for Discord notifications." - "", - LockMode::UNLOCK_WHILE_RUNNING, - 5000 - ) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(HISTORY_SECONDS); - PA_ADD_OPTION(RESOLUTION); - PA_ADD_OPTION(ENCODING_MODE); - PA_ADD_OPTION(VIDEO_QUALITY); - PA_ADD_OPTION(VIDEO_BITRATE); - - StreamHistoryOption::on_config_value_changed(this); - - ENCODING_MODE.add_listener(*this); -} -StreamHistoryOption::~StreamHistoryOption(){ - ENCODING_MODE.remove_listener(*this); -} - -void StreamHistoryOption::on_config_value_changed(void* object){ - switch (ENCODING_MODE){ - case EncodingMode::FIXED_QUALITY: - VIDEO_QUALITY.set_visibility(ConfigOptionState::ENABLED); - VIDEO_BITRATE.set_visibility(ConfigOptionState::HIDDEN); - break; - case EncodingMode::FIXED_BITRATE: - VIDEO_QUALITY.set_visibility(ConfigOptionState::HIDDEN); - VIDEO_BITRATE.set_visibility(ConfigOptionState::ENABLED); - break; - } -} - - - - - - -} +/* Stream History Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "StreamHistoryOption.h" + +namespace PokemonAutomation{ + +StreamHistoryOption::StreamHistoryOption() + : GroupOption( + "Stream History", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_DISABLED, + true + ) + , DESCRIPTION( + "Keep a record of the recent video+audio streams. This will allow video capture " + "for unexpected events.

" + "Warning: This feature has a known memory leak. It will leak ~3GB per day per " + "video stream. You have been warned!" + "

" + "Warning: This feature is computationally expensive and " + "will require a more powerful computer to run (especially for multi-Switch programs).
" + "Furthermore, the current implementation is inefficient as it will write a lot " + "of data to disk. This feature is still a work-in-progress." + "
" + ) + , HISTORY_SECONDS( + "History (seconds):
" + "Keep this many seconds of video and audio feed for video capture and debugging purposes.

" + "Do not set this too large as it will consume a lot of memory and may exceed the " + "attachment size limit for Discord notifications." + "", + LockMode::UNLOCK_WHILE_RUNNING, + 30 + ) + , RESOLUTION( + "Resolution:", + { + {Resolution::MATCH_INPUT, "match", "Match Input Resolution"}, + {Resolution::FORCE_720p, "720p", "1280 x 720"}, + {Resolution::FORCE_1080p, "1080p", "1920 x 1080"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + Resolution::FORCE_720p + ) + , ENCODING_MODE( + "Encoding Mode:", + { + {EncodingMode::FIXED_QUALITY, "fixed-quality", "Fixed Quality"}, + {EncodingMode::FIXED_BITRATE, "fixed-bitrate", "Fixed Bit Rate"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + EncodingMode::FIXED_QUALITY + ) + , VIDEO_QUALITY( + "Video Quality:
" + "High quality videos will take more disk space " + "and may exceed the attachment size limit for Discord notifications." + "", + { + {VideoQuality::VERY_LOW, "very-low", "Very Low"}, + {VideoQuality::LOW, "low", "Low"}, + {VideoQuality::NORMAL, "normal", "Normal"}, + {VideoQuality::HIGH, "high", "High"}, + {VideoQuality::VERY_HIGH, "very-high", "Very High"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + VideoQuality::LOW + ) + , VIDEO_BITRATE( + "Video Bit-Rate (kbps):
" + "Lower = lower quality, smaller file size.
" + "Higher = high quality, larger file size.
" + "Large values can exceed the attachment size limit for Discord notifications." + "", + LockMode::UNLOCK_WHILE_RUNNING, + 5000 + ) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(HISTORY_SECONDS); + PA_ADD_OPTION(RESOLUTION); + PA_ADD_OPTION(ENCODING_MODE); + PA_ADD_OPTION(VIDEO_QUALITY); + PA_ADD_OPTION(VIDEO_BITRATE); + + StreamHistoryOption::on_config_value_changed(this); + + ENCODING_MODE.add_listener(*this); +} +StreamHistoryOption::~StreamHistoryOption(){ + ENCODING_MODE.remove_listener(*this); +} + +void StreamHistoryOption::on_config_value_changed(void* object){ + switch (ENCODING_MODE){ + case EncodingMode::FIXED_QUALITY: + VIDEO_QUALITY.set_visibility(ConfigOptionState::ENABLED); + VIDEO_BITRATE.set_visibility(ConfigOptionState::HIDDEN); + break; + case EncodingMode::FIXED_BITRATE: + VIDEO_QUALITY.set_visibility(ConfigOptionState::HIDDEN); + VIDEO_BITRATE.set_visibility(ConfigOptionState::ENABLED); + break; + } +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h index 11781c302f..8db78e0e9c 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryOption.h @@ -1,56 +1,56 @@ -/* Stream History Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StreamHistoryOption_H -#define PokemonAutomation_StreamHistoryOption_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" - -namespace PokemonAutomation{ - - - -class StreamHistoryOption : public GroupOption, public ConfigOption::Listener{ -public: - StreamHistoryOption(); - ~StreamHistoryOption(); - - virtual void on_config_value_changed(void* object) override; - - StaticTextOption DESCRIPTION; - SimpleIntegerOption HISTORY_SECONDS; - - enum class Resolution{ - MATCH_INPUT, - FORCE_720p, - FORCE_1080p, - }; - EnumDropdownOption RESOLUTION; - - enum class EncodingMode{ - FIXED_QUALITY, - FIXED_BITRATE, - }; - EnumDropdownOption ENCODING_MODE; - - - enum class VideoQuality{ - VERY_LOW, - LOW, - NORMAL, - HIGH, - VERY_HIGH, - }; - EnumDropdownOption VIDEO_QUALITY; - SimpleIntegerOption VIDEO_BITRATE; -}; - - -} -#endif +/* Stream History Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StreamHistoryOption_H +#define PokemonAutomation_StreamHistoryOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" + +namespace PokemonAutomation{ + + + +class StreamHistoryOption : public GroupOption, public ConfigOption::Listener{ +public: + StreamHistoryOption(); + ~StreamHistoryOption(); + + virtual void on_config_value_changed(void* object) override; + + StaticTextOption DESCRIPTION; + SimpleIntegerOption HISTORY_SECONDS; + + enum class Resolution{ + MATCH_INPUT, + FORCE_720p, + FORCE_1080p, + }; + EnumDropdownOption RESOLUTION; + + enum class EncodingMode{ + FIXED_QUALITY, + FIXED_BITRATE, + }; + EnumDropdownOption ENCODING_MODE; + + + enum class VideoQuality{ + VERY_LOW, + LOW, + NORMAL, + HIGH, + VERY_HIGH, + }; + EnumDropdownOption VIDEO_QUALITY; + SimpleIntegerOption VIDEO_BITRATE; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp index f7dc856aa0..e9b8c669b0 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.cpp @@ -1,244 +1,244 @@ -/* Stream History Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" -#include "CommonFramework/Recording/StreamHistoryOption.h" - -#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) -//#include "StreamHistoryTracker_SaveFrames.h" -//#include "StreamHistoryTracker_RecordOnTheFly.h" -#include "StreamHistoryTracker_ParallelStreams.h" -#else -#include "StreamHistoryTracker_Null.h" -#endif - - -#include "StreamHistorySession.h" - - - -namespace PokemonAutomation{ - - - - - -struct StreamHistorySession::Data{ - Logger& m_logger; - mutable SpinLock m_lock; - std::chrono::seconds m_window; - AudioChannelFormat m_audio_format; - bool m_has_video; - std::shared_ptr m_current; - - Data(Logger& logger) - : m_logger(logger) - , m_window(GlobalSettings::instance().STREAM_HISTORY->HISTORY_SECONDS) - , m_audio_format(AudioChannelFormat::NONE) - , m_has_video(false) - {} -}; - - - - -StreamHistorySession::~StreamHistorySession() = default; -StreamHistorySession::StreamHistorySession(Logger& logger) - : AudioFloatStreamListener(1) - , m_data(CONSTRUCT_TOKEN, logger) -{} -void StreamHistorySession::start(AudioChannelFormat format, bool has_video){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (!data.m_current){ - data.m_audio_format = format; - data.m_has_video = has_video; - initialize(); - } -} - - -#if 0 -class HistorySaverThread : public QThread{ -public: - HistorySaverThread(StreamHistoryTracker& tracker, const std::string& filename) - : m_tracker(tracker) - , m_filename(filename) - {} - ~HistorySaverThread(){ - quit(); - wait(); - } - bool save(){ - start(); - quit(); - wait(); - return m_success; - } - virtual void run() override{ -// m_success = m_tracker.save(m_logger, m_filename); - m_success = m_tracker.save(m_filename); - exec(); - } - -private: - StreamHistoryTracker& m_tracker; - const std::string& m_filename; - bool m_success = false; -}; -#endif - -bool StreamHistorySession::save(const std::string& filename) const{ - // This will be coming in from random threads. It will block until the save - // is finished or failed. - - const Data& data = *m_data; - - // Get an owning reference to the current tracker. - // This will allow us to promptly release the lock and unblock the UI from - // changing the streams (which will wipe the history). - std::shared_ptr tracker; - { - WriteSpinLock lg(data.m_lock); - if (!data.m_current){ - data.m_logger.log("Cannot save stream history: Stream history is not enabled.", COLOR_RED); - return false; - } - tracker = data.m_current; - } - -// tracker->save(m_logger, filename); -// HistorySaverThread saver(*tracker, filename); -// return saver.save(); - - return tracker->save(filename); -} -void StreamHistorySession::on_samples(const float* samples, size_t frames){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (data.m_current){ - data.m_current->on_samples(samples, frames); - } -} -void StreamHistorySession::on_frame(std::shared_ptr frame){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (data.m_current){ - data.m_current->on_frame(std::move(frame)); - } -} - - -void StreamHistorySession::clear(){ -// cout << "clear()" << endl; - - // Must call under lock. - Data& data = *m_data; - data.m_logger.log("Clearing stream history...", COLOR_ORANGE); - data.m_current.reset(); -// expected_samples_per_frame = 0; -// data.m_audio_format = AudioChannelFormat::NONE; -// data.m_has_video = false; -} -void StreamHistorySession::initialize(){ - if (!GlobalSettings::instance().STREAM_HISTORY->enabled()){ - return; - } - - // Must call under lock. - Data& data = *m_data; - data.m_logger.log("Starting stream history...", COLOR_ORANGE); - -// cout << "video = " << data.m_has_video << endl; - - switch (data.m_audio_format){ - case AudioChannelFormat::NONE: - expected_samples_per_frame = 0; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 0, 0, data.m_has_video)); - return; - case AudioChannelFormat::MONO_48000: - expected_samples_per_frame = 1; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 48000, data.m_has_video)); - return; - case AudioChannelFormat::DUAL_44100: - expected_samples_per_frame = 2; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 44100, data.m_has_video)); - return; - case AudioChannelFormat::DUAL_48000: - case AudioChannelFormat::MONO_96000: - case AudioChannelFormat::INTERLEAVE_LR_96000: - case AudioChannelFormat::INTERLEAVE_RL_96000: - expected_samples_per_frame = 2; - data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 2, 48000, data.m_has_video)); - return; - default: - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid AudioFormat: " + std::to_string((size_t)data.m_audio_format) - ); - } -} -void StreamHistorySession::pre_input_change(){ -// cout << "pre_input_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - clear(); -} -void StreamHistorySession::post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ -// cout << "post_input_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - if (device){ - data.m_audio_format = format; - }else{ - data.m_audio_format = AudioChannelFormat::NONE; - } - initialize(); -} -void StreamHistorySession::pre_shutdown(){ -// cout << "pre_shutdown()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - clear(); -} -void StreamHistorySession::post_shutdown(){ -// cout << "post_shutdown()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - data.m_has_video = false; - initialize(); -} -void StreamHistorySession::post_startup(VideoSource* source){ - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - data.m_has_video = source != nullptr; - initialize(); -} -void StreamHistorySession::pre_resolution_change(Resolution resolution){ -// cout << "pre_resolution_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - clear(); -} -void StreamHistorySession::post_resolution_change(Resolution resolution){ -// cout << "post_resolution_change()" << endl; - Data& data = *m_data; - WriteSpinLock lg(data.m_lock); - initialize(); -} - - - - - - - -} +/* Stream History Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" + +#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) +//#include "StreamHistoryTracker_SaveFrames.h" +//#include "StreamHistoryTracker_RecordOnTheFly.h" +#include "StreamHistoryTracker_ParallelStreams.h" +#else +#include "StreamHistoryTracker_Null.h" +#endif + + +#include "StreamHistorySession.h" + + + +namespace PokemonAutomation{ + + + + + +struct StreamHistorySession::Data{ + Logger& m_logger; + mutable SpinLock m_lock; + std::chrono::seconds m_window; + AudioChannelFormat m_audio_format; + bool m_has_video; + std::shared_ptr m_current; + + Data(Logger& logger) + : m_logger(logger) + , m_window(GlobalSettings::instance().STREAM_HISTORY->HISTORY_SECONDS) + , m_audio_format(AudioChannelFormat::NONE) + , m_has_video(false) + {} +}; + + + + +StreamHistorySession::~StreamHistorySession() = default; +StreamHistorySession::StreamHistorySession(Logger& logger) + : AudioFloatStreamListener(1) + , m_data(CONSTRUCT_TOKEN, logger) +{} +void StreamHistorySession::start(AudioChannelFormat format, bool has_video){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (!data.m_current){ + data.m_audio_format = format; + data.m_has_video = has_video; + initialize(); + } +} + + +#if 0 +class HistorySaverThread : public QThread{ +public: + HistorySaverThread(StreamHistoryTracker& tracker, const std::string& filename) + : m_tracker(tracker) + , m_filename(filename) + {} + ~HistorySaverThread(){ + quit(); + wait(); + } + bool save(){ + start(); + quit(); + wait(); + return m_success; + } + virtual void run() override{ +// m_success = m_tracker.save(m_logger, m_filename); + m_success = m_tracker.save(m_filename); + exec(); + } + +private: + StreamHistoryTracker& m_tracker; + const std::string& m_filename; + bool m_success = false; +}; +#endif + +bool StreamHistorySession::save(const std::string& filename) const{ + // This will be coming in from random threads. It will block until the save + // is finished or failed. + + const Data& data = *m_data; + + // Get an owning reference to the current tracker. + // This will allow us to promptly release the lock and unblock the UI from + // changing the streams (which will wipe the history). + std::shared_ptr tracker; + { + WriteSpinLock lg(data.m_lock); + if (!data.m_current){ + data.m_logger.log("Cannot save stream history: Stream history is not enabled.", COLOR_RED); + return false; + } + tracker = data.m_current; + } + +// tracker->save(m_logger, filename); +// HistorySaverThread saver(*tracker, filename); +// return saver.save(); + + return tracker->save(filename); +} +void StreamHistorySession::on_samples(const float* samples, size_t frames){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (data.m_current){ + data.m_current->on_samples(samples, frames); + } +} +void StreamHistorySession::on_frame(std::shared_ptr frame){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (data.m_current){ + data.m_current->on_frame(std::move(frame)); + } +} + + +void StreamHistorySession::clear(){ +// cout << "clear()" << endl; + + // Must call under lock. + Data& data = *m_data; + data.m_logger.log("Clearing stream history...", COLOR_ORANGE); + data.m_current.reset(); +// expected_samples_per_frame = 0; +// data.m_audio_format = AudioChannelFormat::NONE; +// data.m_has_video = false; +} +void StreamHistorySession::initialize(){ + if (!GlobalSettings::instance().STREAM_HISTORY->enabled()){ + return; + } + + // Must call under lock. + Data& data = *m_data; + data.m_logger.log("Starting stream history...", COLOR_ORANGE); + +// cout << "video = " << data.m_has_video << endl; + + switch (data.m_audio_format){ + case AudioChannelFormat::NONE: + expected_samples_per_frame = 0; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 0, 0, data.m_has_video)); + return; + case AudioChannelFormat::MONO_48000: + expected_samples_per_frame = 1; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 48000, data.m_has_video)); + return; + case AudioChannelFormat::DUAL_44100: + expected_samples_per_frame = 2; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 1, 44100, data.m_has_video)); + return; + case AudioChannelFormat::DUAL_48000: + case AudioChannelFormat::MONO_96000: + case AudioChannelFormat::INTERLEAVE_LR_96000: + case AudioChannelFormat::INTERLEAVE_RL_96000: + expected_samples_per_frame = 2; + data.m_current.reset(new StreamHistoryTracker(data.m_logger, data.m_window, 2, 48000, data.m_has_video)); + return; + default: + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid AudioFormat: " + std::to_string((size_t)data.m_audio_format) + ); + } +} +void StreamHistorySession::pre_input_change(){ +// cout << "pre_input_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + clear(); +} +void StreamHistorySession::post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format){ +// cout << "post_input_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + if (device){ + data.m_audio_format = format; + }else{ + data.m_audio_format = AudioChannelFormat::NONE; + } + initialize(); +} +void StreamHistorySession::pre_shutdown(){ +// cout << "pre_shutdown()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + clear(); +} +void StreamHistorySession::post_shutdown(){ +// cout << "post_shutdown()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + data.m_has_video = false; + initialize(); +} +void StreamHistorySession::post_startup(VideoSource* source){ + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + data.m_has_video = source != nullptr; + initialize(); +} +void StreamHistorySession::pre_resolution_change(Resolution resolution){ +// cout << "pre_resolution_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + clear(); +} +void StreamHistorySession::post_resolution_change(Resolution resolution){ +// cout << "post_resolution_change()" << endl; + Data& data = *m_data; + WriteSpinLock lg(data.m_lock); + initialize(); +} + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h index 7e01968428..91df2eb15a 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistorySession.h @@ -1,58 +1,58 @@ -/* Stream History Session - * - * From: https://github.com/PokemonAutomation/ - * - * Capture the last X seconds of audio and video. - * - */ - -#ifndef PokemonAutomation_StreamHistorySession_H -#define PokemonAutomation_StreamHistorySession_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "CommonFramework/AudioPipeline/AudioSession.h" -#include "CommonFramework/VideoPipeline/VideoSession.h" - -namespace PokemonAutomation{ - - -class StreamHistorySession - : public AudioFloatStreamListener - , public VideoFrameListener - , public AudioSession::StateListener - , public VideoSession::StateListener -{ -public: - ~StreamHistorySession(); - StreamHistorySession(Logger& logger); - void start(AudioChannelFormat format, bool has_video); - bool save(const std::string& filename) const; - -public: - virtual void on_samples(const float* data, size_t frames) override; - virtual void on_frame(std::shared_ptr frame) override; - -public: - virtual void pre_input_change() override; - virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format) override; - - virtual void pre_shutdown() override; - virtual void post_shutdown() override; - virtual void post_startup(VideoSource* source) override; - virtual void pre_resolution_change(Resolution resolution) override; - virtual void post_resolution_change(Resolution resolution) override; - -private: - void clear(); - void initialize(); - -private: - struct Data; - Pimpl m_data; -}; - - - -} -#endif +/* Stream History Session + * + * From: https://github.com/PokemonAutomation/ + * + * Capture the last X seconds of audio and video. + * + */ + +#ifndef PokemonAutomation_StreamHistorySession_H +#define PokemonAutomation_StreamHistorySession_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" +#include "CommonFramework/VideoPipeline/VideoSession.h" + +namespace PokemonAutomation{ + + +class StreamHistorySession + : public AudioFloatStreamListener + , public VideoFrameListener + , public AudioSession::StateListener + , public VideoSession::StateListener +{ +public: + ~StreamHistorySession(); + StreamHistorySession(Logger& logger); + void start(AudioChannelFormat format, bool has_video); + bool save(const std::string& filename) const; + +public: + virtual void on_samples(const float* data, size_t frames) override; + virtual void on_frame(std::shared_ptr frame) override; + +public: + virtual void pre_input_change() override; + virtual void post_input_change(const std::string& file, const AudioDeviceInfo& device, AudioChannelFormat format) override; + + virtual void pre_shutdown() override; + virtual void post_shutdown() override; + virtual void post_startup(VideoSource* source) override; + virtual void pre_resolution_change(Resolution resolution) override; + virtual void post_resolution_change(Resolution resolution) override; + +private: + void clear(); + void initialize(); + +private: + struct Data; + Pimpl m_data; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h index cf0012c387..55b1748ff6 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_Null.h @@ -1,47 +1,47 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * A null implementation that will compile before Qt 6.8. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_Null_H -#define PokemonAutomation_StreamHistoryTracker_Null_H - -#include "Common/Compiler.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - -namespace PokemonAutomation{ - - -class StreamHistoryTracker{ -public: - StreamHistoryTracker( - Logger& logger, - std::chrono::seconds window, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ) - : m_logger(logger) - {} - void set_window(std::chrono::seconds window){} - - bool save(const std::string& filename) const{ - m_logger.log("Cannot save stream history: Not implemented.", COLOR_RED); - return false; - } - -public: - void on_samples(const float* data, size_t frames){} - void on_frame(std::shared_ptr frame){} - -private: - Logger& m_logger; -}; - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * A null implementation that will compile before Qt 6.8. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_Null_H +#define PokemonAutomation_StreamHistoryTracker_Null_H + +#include "Common/Compiler.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + +namespace PokemonAutomation{ + + +class StreamHistoryTracker{ +public: + StreamHistoryTracker( + Logger& logger, + std::chrono::seconds window, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ) + : m_logger(logger) + {} + void set_window(std::chrono::seconds window){} + + bool save(const std::string& filename) const{ + m_logger.log("Cannot save stream history: Not implemented.", COLOR_RED); + return false; + } + +public: + void on_samples(const float* data, size_t frames){} + void on_frame(std::shared_ptr frame){} + +private: + Logger& m_logger; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h index 42c2a75620..12c14610ed 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_ParallelStreams.h @@ -1,181 +1,181 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * Implement by running two recordings in parallel. - * When each reaches 2X seconds, delete it start over. - * Both recordings are offset by X seconds - thus guaranteeing - * that the last X seconds are available. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_ParallelStreams_H -#define PokemonAutomation_StreamHistoryTracker_ParallelStreams_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/Redispatch.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" -#include "StreamRecorder.h" - -// REMOVE -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - - - - - - - -class StreamHistoryTracker{ - static constexpr size_t PARALLEL_RECORDINGS = 2; - -public: - StreamHistoryTracker( - Logger& logger, - std::chrono::seconds window, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ) - : m_logger(logger) - , m_window(window) // REMOVE -// , m_window(100) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_audio_frames_per_second(audio_frames_per_second) - , m_has_video(has_video) - { - update_streams(current_time()); - } - void set_window(std::chrono::seconds window){ - SpinLockGuard lg(m_lock); - m_window = window; - update_streams(current_time()); - } - - bool save(const std::string& filename){ - std::unique_ptr recording; - { - SpinLockGuard lg(m_lock); - if (m_recordings.empty()){ - m_logger.log("Cannot save stream history. Recording is not enabled.", COLOR_RED); - return false; - } - - m_logger.log("Saving stream history...", COLOR_BLUE); - - auto iter = m_recordings.begin(); - recording = std::move(iter->second); - m_recordings.erase(iter); - update_streams(current_time()); - } - return recording->stop_and_save(filename); - } - - - void on_samples(const float* samples, size_t frames){ - WallClock now = current_time(); - SpinLockGuard lg(m_lock); - for (auto& item : m_recordings){ - item.second->push_samples(now, samples, frames); - } - update_streams(now); - } - void on_frame(std::shared_ptr frame){ - WallClock now = current_time(); - SpinLockGuard lg(m_lock); - for (auto& item : m_recordings){ - item.second->push_frame(frame); - } - update_streams(now); - } - - -private: - void update_streams(WallClock current_time){ -// dispatch_to_main_thread([this, current_time]{ - internal_update_streams(current_time); -// }); - } - void internal_update_streams(WallClock current_time){ -// cout << "streams = " << m_recordings.size() << endl; - - // Must call under the lock. - WallClock threshold = current_time - m_window; - - // Clear any streams that are not needed any more. - // A stream is not needed anymore when there is a newer stream that - // is at least "m_window" long. - if (PARALLEL_RECORDINGS >= 2){ - while (m_recordings.size() >= PARALLEL_RECORDINGS){ - auto first = m_recordings.begin(); - auto second = first; - ++second; - if (second->first < threshold){ -// cout << "removing recording..." << endl; - m_recordings.erase(first); - }else{ - break; - } - } - } - - // If all recordings start in the future, reset everything. - if (!m_recordings.empty() && m_recordings.begin()->first > current_time){ - m_recordings.clear(); - } - - // Add recordings until we've reached the desired amount. - while (m_recordings.size() < PARALLEL_RECORDINGS){ -// cout << "adding recording = " << m_recordings.size() << endl; - // If no recordings are live, start it now. - // Otherwise, schedule to start "m_interval" after the start - // of the newest recording. - WallClock start_time = m_recordings.empty() - ? current_time - : m_recordings.rbegin()->first + m_window; - -// cout << std::chrono::duration_cast(start_time - current_time).count() / 1000. << endl; - - m_recordings.emplace( - std::piecewise_construct, - std::forward_as_tuple(start_time), - std::forward_as_tuple(new StreamRecording( - m_logger, std::chrono::milliseconds(500), - start_time, - m_audio_samples_per_frame, - m_audio_frames_per_second, - m_has_video - )) - ); - } - } - - -private: - Logger& m_logger; - mutable SpinLock m_lock; - std::chrono::milliseconds m_window; - const size_t m_audio_samples_per_frame; - const size_t m_audio_frames_per_second; - const bool m_has_video; - std::map> m_recordings; -}; - - - - - - - - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * Implement by running two recordings in parallel. + * When each reaches 2X seconds, delete it start over. + * Both recordings are offset by X seconds - thus guaranteeing + * that the last X seconds are available. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_ParallelStreams_H +#define PokemonAutomation_StreamHistoryTracker_ParallelStreams_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/Redispatch.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" +#include "StreamRecorder.h" + +// REMOVE +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + + + + + + + +class StreamHistoryTracker{ + static constexpr size_t PARALLEL_RECORDINGS = 2; + +public: + StreamHistoryTracker( + Logger& logger, + std::chrono::seconds window, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ) + : m_logger(logger) + , m_window(window) // REMOVE +// , m_window(100) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_audio_frames_per_second(audio_frames_per_second) + , m_has_video(has_video) + { + update_streams(current_time()); + } + void set_window(std::chrono::seconds window){ + SpinLockGuard lg(m_lock); + m_window = window; + update_streams(current_time()); + } + + bool save(const std::string& filename){ + std::unique_ptr recording; + { + SpinLockGuard lg(m_lock); + if (m_recordings.empty()){ + m_logger.log("Cannot save stream history. Recording is not enabled.", COLOR_RED); + return false; + } + + m_logger.log("Saving stream history...", COLOR_BLUE); + + auto iter = m_recordings.begin(); + recording = std::move(iter->second); + m_recordings.erase(iter); + update_streams(current_time()); + } + return recording->stop_and_save(filename); + } + + + void on_samples(const float* samples, size_t frames){ + WallClock now = current_time(); + SpinLockGuard lg(m_lock); + for (auto& item : m_recordings){ + item.second->push_samples(now, samples, frames); + } + update_streams(now); + } + void on_frame(std::shared_ptr frame){ + WallClock now = current_time(); + SpinLockGuard lg(m_lock); + for (auto& item : m_recordings){ + item.second->push_frame(frame); + } + update_streams(now); + } + + +private: + void update_streams(WallClock current_time){ +// dispatch_to_main_thread([this, current_time]{ + internal_update_streams(current_time); +// }); + } + void internal_update_streams(WallClock current_time){ +// cout << "streams = " << m_recordings.size() << endl; + + // Must call under the lock. + WallClock threshold = current_time - m_window; + + // Clear any streams that are not needed any more. + // A stream is not needed anymore when there is a newer stream that + // is at least "m_window" long. + if (PARALLEL_RECORDINGS >= 2){ + while (m_recordings.size() >= PARALLEL_RECORDINGS){ + auto first = m_recordings.begin(); + auto second = first; + ++second; + if (second->first < threshold){ +// cout << "removing recording..." << endl; + m_recordings.erase(first); + }else{ + break; + } + } + } + + // If all recordings start in the future, reset everything. + if (!m_recordings.empty() && m_recordings.begin()->first > current_time){ + m_recordings.clear(); + } + + // Add recordings until we've reached the desired amount. + while (m_recordings.size() < PARALLEL_RECORDINGS){ +// cout << "adding recording = " << m_recordings.size() << endl; + // If no recordings are live, start it now. + // Otherwise, schedule to start "m_interval" after the start + // of the newest recording. + WallClock start_time = m_recordings.empty() + ? current_time + : m_recordings.rbegin()->first + m_window; + +// cout << std::chrono::duration_cast(start_time - current_time).count() / 1000. << endl; + + m_recordings.emplace( + std::piecewise_construct, + std::forward_as_tuple(start_time), + std::forward_as_tuple(new StreamRecording( + m_logger, std::chrono::milliseconds(500), + start_time, + m_audio_samples_per_frame, + m_audio_frames_per_second, + m_has_video + )) + ); + } + } + + +private: + Logger& m_logger; + mutable SpinLock m_lock; + std::chrono::milliseconds m_window; + const size_t m_audio_samples_per_frame; + const size_t m_audio_frames_per_second; + const bool m_has_video; + std::map> m_recordings; +}; + + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h index 1ad030c774..c6fdca0f6a 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_RecordOnTheFly.h @@ -1,192 +1,192 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * Implement by recording in real-time. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H -#define PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H - -#include -#include -#include -#include -//#include -#include -#include -#include -#include -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -class RollingStream : public QIODevice{ -public: - ~RollingStream(){ - waitForBytesWritten(-1); -// cout << "~RollingStream()" << endl; - } - RollingStream(){ - setOpenMode(QIODeviceBase::WriteOnly); - } - virtual qint64 readData(char* data, qint64 maxlen){ return 0; } - virtual qint64 writeData(const char* data, qint64 len){ - auto scope_check = m_sanitizer.check_scope(); - m_bytes += len; - cout << "total = " << m_bytes << ", current = " << len << endl; - return len; - } - -private: - uint64_t m_bytes = 0; - - LifetimeSanitizer m_sanitizer; -}; - - - -class StreamHistoryTracker{ -public: - ~StreamHistoryTracker(); - StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window - ); - void set_window(std::chrono::seconds window); - - bool save(Logger& logger, const std::string& filename) const; - -public: -// void push_frame(QVideoFrame frame); - - void on_samples(const float* data, size_t frames); - void on_frame(std::shared_ptr frame); - -private: -// void clear_old(); - -private: - mutable SpinLock m_lock; - std::chrono::seconds m_window; - - const size_t m_audio_samples_per_frame; -// const size_t m_audio_frames_per_second; -// const size_t m_audio_samples_per_second; -// const double m_microseconds_per_sample; - -// mutable std::mutex m_lock; -// std::condition_variable m_cv; - - RollingStream m_stream; - - QAudioFormat m_audio_format; - QAudioBufferInput m_audio_input; - QVideoFrameInput m_video_input; - QMediaCaptureSession m_session; - - QMediaRecorder m_recorder; -}; - - -StreamHistoryTracker::~StreamHistoryTracker(){ - m_recorder.stop(); - while (m_recorder.recorderState() != QMediaRecorder::StoppedState){ -// cout << "StreamHistoryTracker: process" << endl; - try{ - QCoreApplication::processEvents(); - pause(); - }catch (...){} - } -// cout << "~StreamHistoryTracker()" << endl; -} -StreamHistoryTracker::StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window -) - : m_window(window) - , m_audio_samples_per_frame(audio_samples_per_frame) -// , m_audio_frames_per_second(audio_frames_per_second) -// , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) -// , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) -{ - m_audio_format.setChannelCount((int)audio_samples_per_frame); - m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - m_audio_format.setSampleRate((int)audio_frames_per_second); - m_audio_format.setSampleFormat(QAudioFormat::Float); - - m_session.setAudioBufferInput(&m_audio_input); - m_session.setVideoFrameInput(&m_video_input); - m_session.setRecorder(&m_recorder); - m_recorder.setMediaFormat(QMediaFormat::MPEG4); - m_recorder.setQuality(QMediaRecorder::HighQuality); - -#if 0 - m_recorder.connect( - &m_recorder, &QMediaRecorder::recorderStateChanged, - &m_recorder, [](QMediaRecorder::RecorderState state){ - - } - ); -#endif - - QFileInfo file(QString::fromStdString("capture-" + now_to_filestring() + ".mp4")); -#if 1 - m_recorder.setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); -#else - m_recorder.setOutputDevice(&m_stream); -#endif - - m_recorder.record(); -} - -void StreamHistoryTracker::set_window(std::chrono::seconds window){ - WriteSpinLock lg(m_lock); - m_window = window; -} - - -void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ - if (frames == 0){ - return; - } - QByteArray buffer((const char*)samples, m_audio_samples_per_frame * frames * sizeof(float)); - QAudioBuffer audio_buffer(buffer, m_audio_format); - m_audio_input.sendAudioBuffer(audio_buffer); -} -void StreamHistoryTracker::on_frame(std::shared_ptr frame){ - m_video_input.sendVideoFrame(frame->frame); -} - -bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ - logger.log("Cannot save stream history: Not implemented.", COLOR_RED); - - // TODO - - return false; -} - - - - - - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * Implement by recording in real-time. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H +#define PokemonAutomation_StreamHistoryTracker_RecordOnTheFly_H + +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +class RollingStream : public QIODevice{ +public: + ~RollingStream(){ + waitForBytesWritten(-1); +// cout << "~RollingStream()" << endl; + } + RollingStream(){ + setOpenMode(QIODeviceBase::WriteOnly); + } + virtual qint64 readData(char* data, qint64 maxlen){ return 0; } + virtual qint64 writeData(const char* data, qint64 len){ + auto scope_check = m_sanitizer.check_scope(); + m_bytes += len; + cout << "total = " << m_bytes << ", current = " << len << endl; + return len; + } + +private: + uint64_t m_bytes = 0; + + LifetimeSanitizer m_sanitizer; +}; + + + +class StreamHistoryTracker{ +public: + ~StreamHistoryTracker(); + StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window + ); + void set_window(std::chrono::seconds window); + + bool save(Logger& logger, const std::string& filename) const; + +public: +// void push_frame(QVideoFrame frame); + + void on_samples(const float* data, size_t frames); + void on_frame(std::shared_ptr frame); + +private: +// void clear_old(); + +private: + mutable SpinLock m_lock; + std::chrono::seconds m_window; + + const size_t m_audio_samples_per_frame; +// const size_t m_audio_frames_per_second; +// const size_t m_audio_samples_per_second; +// const double m_microseconds_per_sample; + +// mutable std::mutex m_lock; +// std::condition_variable m_cv; + + RollingStream m_stream; + + QAudioFormat m_audio_format; + QAudioBufferInput m_audio_input; + QVideoFrameInput m_video_input; + QMediaCaptureSession m_session; + + QMediaRecorder m_recorder; +}; + + +StreamHistoryTracker::~StreamHistoryTracker(){ + m_recorder.stop(); + while (m_recorder.recorderState() != QMediaRecorder::StoppedState){ +// cout << "StreamHistoryTracker: process" << endl; + try{ + QCoreApplication::processEvents(); + pause(); + }catch (...){} + } +// cout << "~StreamHistoryTracker()" << endl; +} +StreamHistoryTracker::StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window +) + : m_window(window) + , m_audio_samples_per_frame(audio_samples_per_frame) +// , m_audio_frames_per_second(audio_frames_per_second) +// , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) +// , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) +{ + m_audio_format.setChannelCount((int)audio_samples_per_frame); + m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + m_audio_format.setSampleRate((int)audio_frames_per_second); + m_audio_format.setSampleFormat(QAudioFormat::Float); + + m_session.setAudioBufferInput(&m_audio_input); + m_session.setVideoFrameInput(&m_video_input); + m_session.setRecorder(&m_recorder); + m_recorder.setMediaFormat(QMediaFormat::MPEG4); + m_recorder.setQuality(QMediaRecorder::HighQuality); + +#if 0 + m_recorder.connect( + &m_recorder, &QMediaRecorder::recorderStateChanged, + &m_recorder, [](QMediaRecorder::RecorderState state){ + + } + ); +#endif + + QFileInfo file(QString::fromStdString("capture-" + now_to_filestring() + ".mp4")); +#if 1 + m_recorder.setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); +#else + m_recorder.setOutputDevice(&m_stream); +#endif + + m_recorder.record(); +} + +void StreamHistoryTracker::set_window(std::chrono::seconds window){ + WriteSpinLock lg(m_lock); + m_window = window; +} + + +void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ + if (frames == 0){ + return; + } + QByteArray buffer((const char*)samples, m_audio_samples_per_frame * frames * sizeof(float)); + QAudioBuffer audio_buffer(buffer, m_audio_format); + m_audio_input.sendAudioBuffer(audio_buffer); +} +void StreamHistoryTracker::on_frame(std::shared_ptr frame){ + m_video_input.sendVideoFrame(frame->frame); +} + +bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ + logger.log("Cannot save stream history: Not implemented.", COLOR_RED); + + // TODO + + return false; +} + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h index df8334818a..5fb326c9e2 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamHistoryTracker_SaveFrames.h @@ -1,312 +1,312 @@ -/* Stream History Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * Implement by saving the last X seconds of frames. This is currently not - * viable because the QVideoFrames are uncompressed. - * - */ - -#ifndef PokemonAutomation_StreamHistoryTracker_SaveFrames_H -#define PokemonAutomation_StreamHistoryTracker_SaveFrames_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - - -//#include -//using std::cout; -//using std::endl; - - -namespace PokemonAutomation{ - - -struct AudioBlock{ - WallClock timestamp; - std::vector samples; - - AudioBlock(const AudioBlock&) = delete; - void operator=(const AudioBlock&) = delete; - - AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) - : timestamp(p_timestamp) - , samples(p_samples, p_samples + p_count) - {} -}; - - -class StreamHistoryTracker{ -public: - StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window - ); - void set_window(std::chrono::seconds window); - - bool save(Logger& logger, const std::string& filename) const; - -public: - void on_samples(const float* data, size_t frames); - void on_frame(std::shared_ptr frame); - -private: - void clear_old(); - -private: - mutable SpinLock m_lock; - std::chrono::seconds m_window; - - const size_t m_audio_samples_per_frame; - const size_t m_audio_frames_per_second; - const size_t m_audio_samples_per_second; - const double m_microseconds_per_sample; - - // We use shared_ptr here so it's fast to snapshot when we need to copy - // everything asynchronously. - std::deque> m_audio; - std::deque> m_frames; -}; - - - - -StreamHistoryTracker::StreamHistoryTracker( - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - std::chrono::seconds window -) - : m_window(window) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_audio_frames_per_second(audio_frames_per_second) - , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) - , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) -{} - -void StreamHistoryTracker::set_window(std::chrono::seconds window){ - WriteSpinLock lg(m_lock); - m_window = window; - clear_old(); -} -void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ - if (frames == 0){ - return; - } - WallClock now = current_time(); - WriteSpinLock lg(m_lock); -// cout << "on_samples() = " << m_audio.size() << endl; - m_audio.emplace_back(std::make_shared( - now, samples, frames * m_audio_samples_per_frame - )); - clear_old(); -} -void StreamHistoryTracker::on_frame(std::shared_ptr frame){ - // TODO: Find a more efficient way to buffer the frames. - // It takes almost 10GB of memory to store 30 seconds of QVideoFrames - // due to them caching uncompressed bitmaps. -// return; // TODO - - WriteSpinLock lg(m_lock); -// cout << "on_frame() = " << m_frames.size() << endl; - m_frames.emplace_back(std::move(frame)); - clear_old(); -} - - - -void StreamHistoryTracker::clear_old(){ - // Must call under lock. - WallClock now = current_time(); - WallClock threshold = now - m_window; - -// WriteSpinLock lg(m_lock); -// cout << "enter" << endl; - while (!m_audio.empty()){ -// cout << "audio.size() = " << m_audio.size() << endl; - AudioBlock& block = *m_audio.front(); - - WallClock end_block = block.timestamp; - end_block += std::chrono::microseconds( - static_cast((double)block.samples.size() * m_microseconds_per_sample) - ); - - if (end_block < threshold){ - m_audio.pop_front(); - }else{ - break; - } - } -// cout << "exit" << endl; - - while (!m_frames.empty()){ - if (m_frames.front()->timestamp < threshold){ - m_frames.pop_front(); - }else{ - break; - } - } -} - - - - - -bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ - logger.log("Saving stream history...", COLOR_BLUE); - - std::deque> audio; - std::deque> frames; - { - // Fast copy the current state of the stream. - WriteSpinLock lg(m_lock); - if (m_audio.empty() && m_frames.empty()){ - return false; - } - audio = m_audio; - frames = m_frames; - } - - // Now that the lock is released, we can take our time encoding it. - - // TODO - -#if 0 - WallClock start = WallClock::max(); - if (!audio.empty()){ - start = std::min(start, audio.front()->timestamp); - } - if (!frames.empty()){ - start = std::min(start, frames.front()->timestamp); - } - -#endif - - -// run_on_main_thread_and_wait([&]{ - - QAudioFormat audio_format; - audio_format.setChannelCount((int)m_audio_samples_per_frame); - audio_format.setChannelConfig(m_audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - audio_format.setSampleRate((int)m_audio_frames_per_second); - audio_format.setSampleFormat(QAudioFormat::Float); - -// cout << "audio_format = " << audio_format.isValid() << endl; - - QAudioBufferInput audio_input; - QVideoFrameInput video_input; - -// cout << "audio = " << audio.size() << endl; -// cout << "frames = " << frames.size() << endl; - - QMediaCaptureSession session; - QMediaRecorder recorder; - session.setAudioBufferInput(&audio_input); - session.setVideoFrameInput(&video_input); - session.setRecorder(&recorder); -#if 1 - recorder.setMediaFormat(QMediaFormat::MPEG4); -#else - QMediaFormat video_format; - video_format.setAudioCodec(QMediaFormat::AudioCodec::AAC); -// video_format.setVideoCodec(QMediaFormat::VideoCodec::H264); - video_format.setFileFormat(QMediaFormat::MPEG4); - recorder.setMediaFormat(video_format); -#endif - recorder.setQuality(QMediaRecorder::NormalQuality); - - QFileInfo file(QString::fromStdString(filename)); - recorder.setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); - - recorder.record(); - - WallClock last_change = current_time(); - QAudioBuffer audio_buffer; - bool success = true; - while (audio_buffer.isValid() || !frames.empty()){ -#if 1 - while (true){ - if (frames.empty()){ -// video_input.sendVideoFrame(QVideoFrame()); -// session.setVideoFrameInput(nullptr); - break; - } - if (!video_input.sendVideoFrame((*frames.begin())->frame)){ -// cout << "Failed Video: " << frames.size() << endl; - break; - } - frames.pop_front(); - last_change = current_time(); -// cout << "Pushed Video: " << frames.size() << endl; - } -#endif -#if 1 - while (true){ - if (!audio_buffer.isValid()){ - if (audio.empty()){ -// audio_input.sendAudioBuffer(QAudioBuffer()); -// session.setAudioBufferInput(nullptr); - break; - } -// cout << "constructing audio buffer: " << audio.size() << endl; - const std::vector& samples = audio.front()->samples; - QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); - audio_buffer = QAudioBuffer( - bytes, audio_format//, -// std::chrono::duration_cast(audio.front()->timestamp - start).count() - ); -// cout << "audio_buffer = " << audio_buffer.isValid() << endl; - audio.pop_front(); - } - if (!audio_buffer.isValid()){ - break; - } - if (!audio_input.sendAudioBuffer(audio_buffer)){ -// cout << "Failed Audio: " << audio.size() << endl; -// cout << audio_input.captureSession() << endl; - break; - } - audio_buffer = QAudioBuffer(); - last_change = current_time(); -// cout << "Pushed audio: " << audio.size() << endl; - } -#endif - - if (current_time() - last_change > std::chrono::seconds(10)){ - logger.log("Failed to record stream history: No progress made after 10 seconds.", COLOR_RED); - success = false; - break; - } - - QCoreApplication::processEvents(); - } - - recorder.stop(); - logger.log("Done saving stream history...", COLOR_BLUE); -// cout << recorder.duration() << endl; - - -// }); - return success; -} - - - - - - - -} -#endif +/* Stream History Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * Implement by saving the last X seconds of frames. This is currently not + * viable because the QVideoFrames are uncompressed. + * + */ + +#ifndef PokemonAutomation_StreamHistoryTracker_SaveFrames_H +#define PokemonAutomation_StreamHistoryTracker_SaveFrames_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + + +//#include +//using std::cout; +//using std::endl; + + +namespace PokemonAutomation{ + + +struct AudioBlock{ + WallClock timestamp; + std::vector samples; + + AudioBlock(const AudioBlock&) = delete; + void operator=(const AudioBlock&) = delete; + + AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) + : timestamp(p_timestamp) + , samples(p_samples, p_samples + p_count) + {} +}; + + +class StreamHistoryTracker{ +public: + StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window + ); + void set_window(std::chrono::seconds window); + + bool save(Logger& logger, const std::string& filename) const; + +public: + void on_samples(const float* data, size_t frames); + void on_frame(std::shared_ptr frame); + +private: + void clear_old(); + +private: + mutable SpinLock m_lock; + std::chrono::seconds m_window; + + const size_t m_audio_samples_per_frame; + const size_t m_audio_frames_per_second; + const size_t m_audio_samples_per_second; + const double m_microseconds_per_sample; + + // We use shared_ptr here so it's fast to snapshot when we need to copy + // everything asynchronously. + std::deque> m_audio; + std::deque> m_frames; +}; + + + + +StreamHistoryTracker::StreamHistoryTracker( + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + std::chrono::seconds window +) + : m_window(window) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_audio_frames_per_second(audio_frames_per_second) + , m_audio_samples_per_second(audio_samples_per_frame * audio_frames_per_second) + , m_microseconds_per_sample(1. / (m_audio_samples_per_second * 1000000.)) +{} + +void StreamHistoryTracker::set_window(std::chrono::seconds window){ + WriteSpinLock lg(m_lock); + m_window = window; + clear_old(); +} +void StreamHistoryTracker::on_samples(const float* samples, size_t frames){ + if (frames == 0){ + return; + } + WallClock now = current_time(); + WriteSpinLock lg(m_lock); +// cout << "on_samples() = " << m_audio.size() << endl; + m_audio.emplace_back(std::make_shared( + now, samples, frames * m_audio_samples_per_frame + )); + clear_old(); +} +void StreamHistoryTracker::on_frame(std::shared_ptr frame){ + // TODO: Find a more efficient way to buffer the frames. + // It takes almost 10GB of memory to store 30 seconds of QVideoFrames + // due to them caching uncompressed bitmaps. +// return; // TODO + + WriteSpinLock lg(m_lock); +// cout << "on_frame() = " << m_frames.size() << endl; + m_frames.emplace_back(std::move(frame)); + clear_old(); +} + + + +void StreamHistoryTracker::clear_old(){ + // Must call under lock. + WallClock now = current_time(); + WallClock threshold = now - m_window; + +// WriteSpinLock lg(m_lock); +// cout << "enter" << endl; + while (!m_audio.empty()){ +// cout << "audio.size() = " << m_audio.size() << endl; + AudioBlock& block = *m_audio.front(); + + WallClock end_block = block.timestamp; + end_block += std::chrono::microseconds( + static_cast((double)block.samples.size() * m_microseconds_per_sample) + ); + + if (end_block < threshold){ + m_audio.pop_front(); + }else{ + break; + } + } +// cout << "exit" << endl; + + while (!m_frames.empty()){ + if (m_frames.front()->timestamp < threshold){ + m_frames.pop_front(); + }else{ + break; + } + } +} + + + + + +bool StreamHistoryTracker::save(Logger& logger, const std::string& filename) const{ + logger.log("Saving stream history...", COLOR_BLUE); + + std::deque> audio; + std::deque> frames; + { + // Fast copy the current state of the stream. + WriteSpinLock lg(m_lock); + if (m_audio.empty() && m_frames.empty()){ + return false; + } + audio = m_audio; + frames = m_frames; + } + + // Now that the lock is released, we can take our time encoding it. + + // TODO + +#if 0 + WallClock start = WallClock::max(); + if (!audio.empty()){ + start = std::min(start, audio.front()->timestamp); + } + if (!frames.empty()){ + start = std::min(start, frames.front()->timestamp); + } + +#endif + + +// run_on_main_thread_and_wait([&]{ + + QAudioFormat audio_format; + audio_format.setChannelCount((int)m_audio_samples_per_frame); + audio_format.setChannelConfig(m_audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + audio_format.setSampleRate((int)m_audio_frames_per_second); + audio_format.setSampleFormat(QAudioFormat::Float); + +// cout << "audio_format = " << audio_format.isValid() << endl; + + QAudioBufferInput audio_input; + QVideoFrameInput video_input; + +// cout << "audio = " << audio.size() << endl; +// cout << "frames = " << frames.size() << endl; + + QMediaCaptureSession session; + QMediaRecorder recorder; + session.setAudioBufferInput(&audio_input); + session.setVideoFrameInput(&video_input); + session.setRecorder(&recorder); +#if 1 + recorder.setMediaFormat(QMediaFormat::MPEG4); +#else + QMediaFormat video_format; + video_format.setAudioCodec(QMediaFormat::AudioCodec::AAC); +// video_format.setVideoCodec(QMediaFormat::VideoCodec::H264); + video_format.setFileFormat(QMediaFormat::MPEG4); + recorder.setMediaFormat(video_format); +#endif + recorder.setQuality(QMediaRecorder::NormalQuality); + + QFileInfo file(QString::fromStdString(filename)); + recorder.setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); + + recorder.record(); + + WallClock last_change = current_time(); + QAudioBuffer audio_buffer; + bool success = true; + while (audio_buffer.isValid() || !frames.empty()){ +#if 1 + while (true){ + if (frames.empty()){ +// video_input.sendVideoFrame(QVideoFrame()); +// session.setVideoFrameInput(nullptr); + break; + } + if (!video_input.sendVideoFrame((*frames.begin())->frame)){ +// cout << "Failed Video: " << frames.size() << endl; + break; + } + frames.pop_front(); + last_change = current_time(); +// cout << "Pushed Video: " << frames.size() << endl; + } +#endif +#if 1 + while (true){ + if (!audio_buffer.isValid()){ + if (audio.empty()){ +// audio_input.sendAudioBuffer(QAudioBuffer()); +// session.setAudioBufferInput(nullptr); + break; + } +// cout << "constructing audio buffer: " << audio.size() << endl; + const std::vector& samples = audio.front()->samples; + QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); + audio_buffer = QAudioBuffer( + bytes, audio_format//, +// std::chrono::duration_cast(audio.front()->timestamp - start).count() + ); +// cout << "audio_buffer = " << audio_buffer.isValid() << endl; + audio.pop_front(); + } + if (!audio_buffer.isValid()){ + break; + } + if (!audio_input.sendAudioBuffer(audio_buffer)){ +// cout << "Failed Audio: " << audio.size() << endl; +// cout << audio_input.captureSession() << endl; + break; + } + audio_buffer = QAudioBuffer(); + last_change = current_time(); +// cout << "Pushed audio: " << audio.size() << endl; + } +#endif + + if (current_time() - last_change > std::chrono::seconds(10)){ + logger.log("Failed to record stream history: No progress made after 10 seconds.", COLOR_RED); + success = false; + break; + } + + QCoreApplication::processEvents(); + } + + recorder.stop(); + logger.log("Done saving stream history...", COLOR_BLUE); +// cout << recorder.duration() << endl; + + +// }); + return success; +} + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp index 28d5e54502..0d3e970b63 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.cpp @@ -1,792 +1,792 @@ -/* Stream Recorder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -//#include "Common/Qt/Redispatch.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" -#include "CommonFramework/Recording/StreamHistoryOption.h" -#include "StreamRecorder.h" - - -// This doesn't work yet. QMediaRecorder writes different bytes with -// setOutputDevice() vs. setOutputLocation(). -// So far I can't get setOutputDevice() to work. The bytes that it -// spits out is not a valid .mp4 file. - -//#define PA_STREAM_HISTORY_LOCAL_BUFFER - - -// REMOVE -#include -using std::cout; -using std::endl; - - -namespace PokemonAutomation{ - - -StreamRecording::StreamRecording( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video -) - : m_logger(logger) - , m_buffer_limit(buffer_limit) - , m_start_time(start_time) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_has_video(has_video) - , m_filename(GlobalSettings::instance().TEMP_FOLDER) - , m_stopping(false) - , m_last_drop(current_time()) - , m_last_frame_time(std::numeric_limits::min()) -{ - logger.log( - "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + - ", Video = " + std::to_string(has_video) - ); -// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; - - if (audio_samples_per_frame == 0 && !has_video){ - return; - } - - if (audio_samples_per_frame > 0){ - m_audio_format.setChannelCount((int)audio_samples_per_frame); - m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - m_audio_format.setSampleRate((int)audio_frames_per_second); - m_audio_format.setSampleFormat(QAudioFormat::Float); - } - -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - QDir().mkdir(QString::fromStdString(m_filename)); -#endif - if (has_video){ - m_filename += now_to_filestring() + ".mp4"; - }else{ - m_filename += now_to_filestring() + ".m4a"; - } - - start(); -} -StreamRecording::~StreamRecording(){ - { - std::lock_guard lg(m_lock); - m_stopping = true; -// cout << "signalling: ~StreamRecording()" << endl; - m_cv.notify_all(); - } - quit(); - wait(); -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - if (!m_filename.empty()){ - QDir().remove(QString::fromStdString(m_filename)); - } -#endif -} - -bool StreamRecording::stop_and_save(const std::string& filename){ - auto scope_check = m_santizer.check_scope(); - { - std::lock_guard lg(m_lock); - m_stopping = true; -// cout << "signalling: stop_and_save()" << endl; - m_cv.notify_all(); - } - quit(); - wait(); - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - return m_write_buffer.write(m_logger, filename); -#else - bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); - m_filename.clear(); - return ret; -#endif -} - - -void StreamRecording::push_samples(WallClock timestamp, const float* data, size_t frames){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (m_audio_samples_per_frame == 0 || now < m_start_time){ - return; - } - WallClock threshold = timestamp - m_buffer_limit; - - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - do{ - if (m_buffered_audio.empty()){ - break; - } - - // Too much has been buffered. Drop the block. - if (m_buffered_audio.front().timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); - } - return; - } - - }while (false); - - // Enqueue the sample block. - m_buffered_audio.emplace_back( - timestamp, - data, frames * m_audio_samples_per_frame - ); - m_cv.notify_all(); -#endif -} -void StreamRecording::push_frame(std::shared_ptr frame){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (!m_has_video || now < m_start_time){ - return; - } -// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; - WallClock threshold = frame->timestamp - m_buffer_limit; - - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - qint64 frame_time = frame->frame.startTime(); - do{ - if (m_buffered_frames.empty()){ - break; - } - - // Too much has been buffered. Drop the frame. - if (m_buffered_frames.front()->timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); - } - return; - } - - // Non-increasing timestamp. Drop possible duplicate frame. - if (frame_time <= m_last_frame_time){ - return; - } - }while (false); - - // Enqueue the frame. - m_buffered_frames.emplace_back(std::move(frame)); - m_last_frame_time = frame_time; - m_cv.notify_all(); -#endif -} - - - -std::unique_ptr StreamRecording::initialize_audio(){ - std::unique_ptr ret(new QAudioBufferInput()); - m_audio_input = ret.get(); - m_session->setAudioBufferInput(m_audio_input); - - connect( - m_audio_input, &QAudioBufferInput::readyToSendAudioBuffer, - m_recorder, [this](){ - std::lock_guard lg(m_lock); - m_cv.notify_all(); - }, - Qt::DirectConnection - ); - - return ret; -} -std::unique_ptr StreamRecording::initialize_video(){ - std::unique_ptr ret(new QVideoFrameInput()); - m_video_input = ret.get(); - m_session->setVideoFrameInput(m_video_input); - - const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; - - switch (settings.RESOLUTION){ - case StreamHistoryOption::Resolution::MATCH_INPUT: - break; - case StreamHistoryOption::Resolution::FORCE_720p: - m_recorder->setVideoResolution(1280, 720); - break; - case StreamHistoryOption::Resolution::FORCE_1080p: - m_recorder->setVideoResolution(1920, 1080); - break; - } - - switch (settings.ENCODING_MODE){ - case StreamHistoryOption::EncodingMode::FIXED_QUALITY: - switch (settings.VIDEO_QUALITY){ - case StreamHistoryOption::VideoQuality::VERY_LOW: - m_recorder->setQuality(QMediaRecorder::VeryLowQuality); - break; - case StreamHistoryOption::VideoQuality::LOW: - m_recorder->setQuality(QMediaRecorder::LowQuality); - break; - case StreamHistoryOption::VideoQuality::NORMAL: - m_recorder->setQuality(QMediaRecorder::NormalQuality); - break; - case StreamHistoryOption::VideoQuality::HIGH: - m_recorder->setQuality(QMediaRecorder::HighQuality); - break; - case StreamHistoryOption::VideoQuality::VERY_HIGH: - m_recorder->setQuality(QMediaRecorder::VeryHighQuality); - break; - } - break; - case StreamHistoryOption::EncodingMode::FIXED_BITRATE: - m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); - m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); - break; - } - - connect( - m_video_input, &QVideoFrameInput::readyToSendVideoFrame, - m_recorder, [this](){ - std::lock_guard lg(m_lock); - m_cv.notify_all(); - }, - Qt::DirectConnection - ); - - return ret; -} - -void StreamRecording::internal_run(){ - QMediaCaptureSession session; - QMediaRecorder recorder; - m_session = &session; - m_recorder = &recorder; - m_session->setRecorder(m_recorder); - - std::unique_ptr audio; - std::unique_ptr video; - - // Only initialize the streams we intend to use. - if (m_audio_samples_per_frame > 0){ - audio = initialize_audio(); - } - if (m_has_video){ - video = initialize_video(); - } - - m_recorder->setMediaFormat(QMediaFormat::MPEG4); - - connect( - m_recorder, &QMediaRecorder::recorderStateChanged, - m_recorder, [this](QMediaRecorder::RecorderState state){ - if (state == QMediaRecorder::StoppedState){ - std::lock_guard lg(m_lock); -// cout << "signalling: StoppedState" << endl; - m_stopping = true; - m_cv.notify_all(); - } - }, - Qt::DirectConnection - ); - - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - m_recorder->setOutputDevice(&m_write_buffer); -#else - QFileInfo file(QString::fromStdString(m_filename)); - m_recorder->setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); -#endif - -// cout << "Encoding Mode = " << (int)recorder.encodingMode() << endl; -// cout << "Bit Rate = " << (int)recorder.videoBitRate() << endl; - - -#if 1 -// cout << "starting recording" << endl; - m_recorder->record(); - - AudioBlock current_audio; - std::shared_ptr current_frame; - QAudioBuffer audio_buffer; - - while (true){ - QCoreApplication::processEvents(); - - { - std::unique_lock lg(m_lock); - if (m_stopping){ - break; - } - - if (!current_audio.is_valid() && !m_buffered_audio.empty()){ - current_audio = std::move(m_buffered_audio.front()); - m_buffered_audio.pop_front(); - } - if (!current_frame && !m_buffered_frames.empty()){ - current_frame = std::move(m_buffered_frames.front()); - m_buffered_frames.pop_front(); - } - - if (!current_audio.is_valid() && !current_frame){ -// cout << "sleeping 0..." << endl; - m_cv.wait(lg); -// cout << "waking 0..." << endl; - } - } - - bool progress_made = false; - - if (current_audio.is_valid()){ - if (!audio_buffer.isValid()){ - const std::vector& samples = current_audio.samples; - QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); - audio_buffer = QAudioBuffer(bytes, m_audio_format); - } - if (audio_buffer.isValid() && m_audio_input->sendAudioBuffer(audio_buffer)){ - current_audio.clear(); - audio_buffer = QAudioBuffer(); - progress_made = true; - } - } -// cout << "Before: " << m_video_input << endl; - if (current_frame && m_video_input->sendVideoFrame(current_frame->frame)){ -// cout << "push frame: " << current_frame->frame.startTime() << endl; - current_frame.reset(); - progress_made = true; - } -// cout << "After: " << m_video_input << endl; - - if (!progress_made){ - std::unique_lock lg(m_lock); - if (m_stopping){ - break; - } -// cout << "sleeping 1..." << endl; - m_cv.wait(lg); -// cout << "waking 1..." << endl; - } - } - - m_recorder->stop(); -// cout << "recorder.stop()" << endl; -#endif - - - while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ -// cout << "StreamHistoryTracker: process" << endl; - QCoreApplication::processEvents(); - pause(); - } - - exec(); - -} -void StreamRecording::run(){ - auto scope_check = m_santizer.check_scope(); - try{ - internal_run(); - }catch (...){ - m_logger.log("Exception thrown out of stream recorder...", COLOR_RED); - std::lock_guard lg(m_lock); - m_stopping = true; - } -} - - - - - -StreamRecording2::StreamRecording2( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video -) - : m_logger(logger) - , m_buffer_limit(buffer_limit) - , m_start_time(start_time) - , m_audio_samples_per_frame(audio_samples_per_frame) - , m_has_video(has_video) - , m_filename(GlobalSettings::instance().TEMP_FOLDER) - , m_stopping(false) - , m_last_drop(current_time()) - , m_last_frame_time(std::numeric_limits::min()) -{ - logger.log( - "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + - ", Video = " + std::to_string(has_video) - ); -// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; - - if (audio_samples_per_frame == 0 && !has_video){ - return; - } - - if (audio_samples_per_frame > 0){ - m_audio_format.setChannelCount((int)audio_samples_per_frame); - m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); - m_audio_format.setSampleRate((int)audio_frames_per_second); - m_audio_format.setSampleFormat(QAudioFormat::Float); - } - -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - QDir().mkdir(QString::fromStdString(m_filename)); -#endif - if (has_video){ - m_filename += now_to_filestring() + ".mp4"; - }else{ - m_filename += now_to_filestring() + ".m4a"; - } - - m_recorder.reset(new QMediaRecorder()); - m_session.setRecorder(m_recorder.get()); - - // Only initialize the streams we intend to use. - if (m_audio_samples_per_frame > 0){ - initialize_audio(); - } - if (m_has_video){ - initialize_video(); - } - - m_recorder->setMediaFormat(QMediaFormat::MPEG4); - - - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - m_recorder->setOutputDevice(&m_write_buffer); -#else - QFileInfo file(QString::fromStdString(m_filename)); - m_recorder->setOutputLocation( - QUrl::fromLocalFile(file.absoluteFilePath()) - ); -#endif - - m_recorder->record(); -} -StreamRecording2::~StreamRecording2(){ -#if 1 - stop(); -#else - { - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - m_stopping = true; - } - - m_recorder->stop(); - m_recorder.reset(); -#endif - -#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER - cout << QDir().remove(QString::fromStdString(m_filename)) << endl; // REMOVE -#endif -} - -void StreamRecording2::stop(){ - auto scope_check = m_santizer.check_scope(); - - { - std::unique_lock lg(m_lock); - if (m_stopping){ - return; - } - m_stopping = true; - } - -#if 0 - run_on_main_thread_and_wait([this]{ - QEventLoop loop; - m_recorder.connect( - &m_recorder, &QMediaRecorder::recorderStateChanged, - &m_recorder, [&](QMediaRecorder::RecorderState state){ - if (state == QMediaRecorder::StoppedState){ - loop.quit(); - } - } - ); - - emit m_recorder.stop(); - - if (m_recorder.recorderState() != QMediaRecorder::StoppedState){ - loop.exec(); - } - }); -#endif - - m_recorder->stop(); - - while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ - cout << "Spin waiting..." << endl; // REMOVE - pause(); - } -} - - -void StreamRecording2::initialize_audio(){ - m_audio_input.reset(new QAudioBufferInput()); - m_session.setAudioBufferInput(m_audio_input.get()); - - m_recorder->connect( - m_audio_input.get(), &QAudioBufferInput::readyToSendAudioBuffer, - m_recorder.get(), [this](){ -// cout << "readyToSendAudioBuffer()" << endl; -// std::lock_guard lg(m_lock); -// m_cv.notify_all(); - process(); - }, - Qt::DirectConnection - ); -} -void StreamRecording2::initialize_video(){ - m_video_input.reset(new QVideoFrameInput()); - m_session.setVideoFrameInput(m_video_input.get()); - - const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; - - switch (settings.RESOLUTION){ - case StreamHistoryOption::Resolution::MATCH_INPUT: - break; - case StreamHistoryOption::Resolution::FORCE_720p: - m_recorder->setVideoResolution(1280, 720); - break; - case StreamHistoryOption::Resolution::FORCE_1080p: - m_recorder->setVideoResolution(1920, 1080); - break; - } - - switch (settings.ENCODING_MODE){ - case StreamHistoryOption::EncodingMode::FIXED_QUALITY: - switch (settings.VIDEO_QUALITY){ - case StreamHistoryOption::VideoQuality::VERY_LOW: - m_recorder->setQuality(QMediaRecorder::VeryLowQuality); - break; - case StreamHistoryOption::VideoQuality::LOW: - m_recorder->setQuality(QMediaRecorder::LowQuality); - break; - case StreamHistoryOption::VideoQuality::NORMAL: - m_recorder->setQuality(QMediaRecorder::NormalQuality); - break; - case StreamHistoryOption::VideoQuality::HIGH: - m_recorder->setQuality(QMediaRecorder::HighQuality); - break; - case StreamHistoryOption::VideoQuality::VERY_HIGH: - m_recorder->setQuality(QMediaRecorder::VeryHighQuality); - break; - } - break; - case StreamHistoryOption::EncodingMode::FIXED_BITRATE: - m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); - m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); - break; - } - - m_recorder->connect( - m_video_input.get(), &QVideoFrameInput::readyToSendVideoFrame, - m_recorder.get(), [this](){ -// cout << "readyToSendVideoFrame()" << endl; -// std::lock_guard lg(m_lock); -// m_cv.notify_all(); - process(); - }, - Qt::DirectConnection - ); -} - - - - -void StreamRecording2::push_samples(WallClock timestamp, const float* data, size_t frames){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (m_audio_samples_per_frame == 0 || now < m_start_time){ - return; - } - WallClock threshold = timestamp - m_buffer_limit; - - { - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - do{ - if (m_buffered_audio.empty()){ - break; - } - - // Too much has been buffered. Drop the block. - if (m_buffered_audio.front().timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); - } - return; - } - - }while (false); - - // Enqueue the sample block. - m_buffered_audio.emplace_back( - timestamp, - data, frames * m_audio_samples_per_frame - ); - } - - emit m_audio_input->readyToSendAudioBuffer(); -#endif -} -void StreamRecording2::push_frame(std::shared_ptr frame){ - auto scope_check = m_santizer.check_scope(); -#if 1 - WallClock now = current_time(); - if (!m_has_video || now < m_start_time){ - return; - } -// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; - WallClock threshold = frame->timestamp - m_buffer_limit; - - { - std::lock_guard lg(m_lock); - if (m_stopping){ - return; - } - - qint64 frame_time = frame->frame.startTime(); - do{ - if (m_buffered_frames.empty()){ - break; - } - - // Too much has been buffered. Drop the frame. - if (m_buffered_frames.front()->timestamp < threshold){ - // Throttle the prints. - if (now - m_last_drop > std::chrono::seconds(5)){ - m_last_drop = now; - m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); - } - return; - } - - // Non-increasing timestamp. Drop possible duplicate frame. - if (frame_time <= m_last_frame_time){ - return; - } - }while (false); - - // Enqueue the frame. - m_buffered_frames.emplace_back(std::move(frame)); - m_last_frame_time = frame_time; - } - - emit m_video_input->readyToSendVideoFrame(); -#endif -} - - -bool StreamRecording2::stop_and_save(const std::string& filename){ - stop(); - -#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER - return m_write_buffer.write(m_logger, filename); -#else - bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); - m_filename.clear(); - return ret; -#endif -} - -void StreamRecording2::process(){ - auto scope_check = m_santizer.check_scope(); - -// cout << "StreamRecording2::process()" << endl; - - bool progress_made; - do{ - { - std::unique_lock lg(m_lock); - if (m_stopping){ - cout << "exit" << endl; // REMOVE - break; - } - - if (!m_current_audio.is_valid() && !m_buffered_audio.empty()){ - m_current_audio = std::move(m_buffered_audio.front()); - m_buffered_audio.pop_front(); - } - if (!m_current_frame && !m_buffered_frames.empty()){ - m_current_frame = std::move(m_buffered_frames.front()); - m_buffered_frames.pop_front(); - } - - if (!m_current_audio.is_valid() && !m_current_frame){ - return; - } - } - - progress_made = false; - - if (m_current_audio.is_valid()){ - if (!m_audio_buffer.isValid()){ - const std::vector& samples = m_current_audio.samples; - QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); - m_audio_buffer = QAudioBuffer(bytes, m_audio_format); - } - if (m_audio_buffer.isValid() && m_audio_input->sendAudioBuffer(m_audio_buffer)){ - m_current_audio.clear(); - m_audio_buffer = QAudioBuffer(); - progress_made = true; - } - } -// cout << "Before: " << m_video_input << endl; - if (m_current_frame && m_video_input->sendVideoFrame(m_current_frame->frame)){ -// cout << "push frame: " << current_frame->frame.startTime() << endl; - m_current_frame.reset(); - progress_made = true; - } - - }while (progress_made); -} - - - - - - - -} -#endif +/* Stream Recorder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +//#include "Common/Qt/Redispatch.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" +#include "StreamRecorder.h" + + +// This doesn't work yet. QMediaRecorder writes different bytes with +// setOutputDevice() vs. setOutputLocation(). +// So far I can't get setOutputDevice() to work. The bytes that it +// spits out is not a valid .mp4 file. + +//#define PA_STREAM_HISTORY_LOCAL_BUFFER + + +// REMOVE +#include +using std::cout; +using std::endl; + + +namespace PokemonAutomation{ + + +StreamRecording::StreamRecording( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video +) + : m_logger(logger) + , m_buffer_limit(buffer_limit) + , m_start_time(start_time) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_has_video(has_video) + , m_filename(GlobalSettings::instance().TEMP_FOLDER) + , m_stopping(false) + , m_last_drop(current_time()) + , m_last_frame_time(std::numeric_limits::min()) +{ + logger.log( + "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + + ", Video = " + std::to_string(has_video) + ); +// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; + + if (audio_samples_per_frame == 0 && !has_video){ + return; + } + + if (audio_samples_per_frame > 0){ + m_audio_format.setChannelCount((int)audio_samples_per_frame); + m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + m_audio_format.setSampleRate((int)audio_frames_per_second); + m_audio_format.setSampleFormat(QAudioFormat::Float); + } + +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + QDir().mkdir(QString::fromStdString(m_filename)); +#endif + if (has_video){ + m_filename += now_to_filestring() + ".mp4"; + }else{ + m_filename += now_to_filestring() + ".m4a"; + } + + start(); +} +StreamRecording::~StreamRecording(){ + { + std::lock_guard lg(m_lock); + m_stopping = true; +// cout << "signalling: ~StreamRecording()" << endl; + m_cv.notify_all(); + } + quit(); + wait(); +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + if (!m_filename.empty()){ + QDir().remove(QString::fromStdString(m_filename)); + } +#endif +} + +bool StreamRecording::stop_and_save(const std::string& filename){ + auto scope_check = m_santizer.check_scope(); + { + std::lock_guard lg(m_lock); + m_stopping = true; +// cout << "signalling: stop_and_save()" << endl; + m_cv.notify_all(); + } + quit(); + wait(); + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + return m_write_buffer.write(m_logger, filename); +#else + bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); + m_filename.clear(); + return ret; +#endif +} + + +void StreamRecording::push_samples(WallClock timestamp, const float* data, size_t frames){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (m_audio_samples_per_frame == 0 || now < m_start_time){ + return; + } + WallClock threshold = timestamp - m_buffer_limit; + + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + do{ + if (m_buffered_audio.empty()){ + break; + } + + // Too much has been buffered. Drop the block. + if (m_buffered_audio.front().timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); + } + return; + } + + }while (false); + + // Enqueue the sample block. + m_buffered_audio.emplace_back( + timestamp, + data, frames * m_audio_samples_per_frame + ); + m_cv.notify_all(); +#endif +} +void StreamRecording::push_frame(std::shared_ptr frame){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (!m_has_video || now < m_start_time){ + return; + } +// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; + WallClock threshold = frame->timestamp - m_buffer_limit; + + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + qint64 frame_time = frame->frame.startTime(); + do{ + if (m_buffered_frames.empty()){ + break; + } + + // Too much has been buffered. Drop the frame. + if (m_buffered_frames.front()->timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); + } + return; + } + + // Non-increasing timestamp. Drop possible duplicate frame. + if (frame_time <= m_last_frame_time){ + return; + } + }while (false); + + // Enqueue the frame. + m_buffered_frames.emplace_back(std::move(frame)); + m_last_frame_time = frame_time; + m_cv.notify_all(); +#endif +} + + + +std::unique_ptr StreamRecording::initialize_audio(){ + std::unique_ptr ret(new QAudioBufferInput()); + m_audio_input = ret.get(); + m_session->setAudioBufferInput(m_audio_input); + + connect( + m_audio_input, &QAudioBufferInput::readyToSendAudioBuffer, + m_recorder, [this](){ + std::lock_guard lg(m_lock); + m_cv.notify_all(); + }, + Qt::DirectConnection + ); + + return ret; +} +std::unique_ptr StreamRecording::initialize_video(){ + std::unique_ptr ret(new QVideoFrameInput()); + m_video_input = ret.get(); + m_session->setVideoFrameInput(m_video_input); + + const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; + + switch (settings.RESOLUTION){ + case StreamHistoryOption::Resolution::MATCH_INPUT: + break; + case StreamHistoryOption::Resolution::FORCE_720p: + m_recorder->setVideoResolution(1280, 720); + break; + case StreamHistoryOption::Resolution::FORCE_1080p: + m_recorder->setVideoResolution(1920, 1080); + break; + } + + switch (settings.ENCODING_MODE){ + case StreamHistoryOption::EncodingMode::FIXED_QUALITY: + switch (settings.VIDEO_QUALITY){ + case StreamHistoryOption::VideoQuality::VERY_LOW: + m_recorder->setQuality(QMediaRecorder::VeryLowQuality); + break; + case StreamHistoryOption::VideoQuality::LOW: + m_recorder->setQuality(QMediaRecorder::LowQuality); + break; + case StreamHistoryOption::VideoQuality::NORMAL: + m_recorder->setQuality(QMediaRecorder::NormalQuality); + break; + case StreamHistoryOption::VideoQuality::HIGH: + m_recorder->setQuality(QMediaRecorder::HighQuality); + break; + case StreamHistoryOption::VideoQuality::VERY_HIGH: + m_recorder->setQuality(QMediaRecorder::VeryHighQuality); + break; + } + break; + case StreamHistoryOption::EncodingMode::FIXED_BITRATE: + m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); + m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); + break; + } + + connect( + m_video_input, &QVideoFrameInput::readyToSendVideoFrame, + m_recorder, [this](){ + std::lock_guard lg(m_lock); + m_cv.notify_all(); + }, + Qt::DirectConnection + ); + + return ret; +} + +void StreamRecording::internal_run(){ + QMediaCaptureSession session; + QMediaRecorder recorder; + m_session = &session; + m_recorder = &recorder; + m_session->setRecorder(m_recorder); + + std::unique_ptr audio; + std::unique_ptr video; + + // Only initialize the streams we intend to use. + if (m_audio_samples_per_frame > 0){ + audio = initialize_audio(); + } + if (m_has_video){ + video = initialize_video(); + } + + m_recorder->setMediaFormat(QMediaFormat::MPEG4); + + connect( + m_recorder, &QMediaRecorder::recorderStateChanged, + m_recorder, [this](QMediaRecorder::RecorderState state){ + if (state == QMediaRecorder::StoppedState){ + std::lock_guard lg(m_lock); +// cout << "signalling: StoppedState" << endl; + m_stopping = true; + m_cv.notify_all(); + } + }, + Qt::DirectConnection + ); + + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + m_recorder->setOutputDevice(&m_write_buffer); +#else + QFileInfo file(QString::fromStdString(m_filename)); + m_recorder->setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); +#endif + +// cout << "Encoding Mode = " << (int)recorder.encodingMode() << endl; +// cout << "Bit Rate = " << (int)recorder.videoBitRate() << endl; + + +#if 1 +// cout << "starting recording" << endl; + m_recorder->record(); + + AudioBlock current_audio; + std::shared_ptr current_frame; + QAudioBuffer audio_buffer; + + while (true){ + QCoreApplication::processEvents(); + + { + std::unique_lock lg(m_lock); + if (m_stopping){ + break; + } + + if (!current_audio.is_valid() && !m_buffered_audio.empty()){ + current_audio = std::move(m_buffered_audio.front()); + m_buffered_audio.pop_front(); + } + if (!current_frame && !m_buffered_frames.empty()){ + current_frame = std::move(m_buffered_frames.front()); + m_buffered_frames.pop_front(); + } + + if (!current_audio.is_valid() && !current_frame){ +// cout << "sleeping 0..." << endl; + m_cv.wait(lg); +// cout << "waking 0..." << endl; + } + } + + bool progress_made = false; + + if (current_audio.is_valid()){ + if (!audio_buffer.isValid()){ + const std::vector& samples = current_audio.samples; + QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); + audio_buffer = QAudioBuffer(bytes, m_audio_format); + } + if (audio_buffer.isValid() && m_audio_input->sendAudioBuffer(audio_buffer)){ + current_audio.clear(); + audio_buffer = QAudioBuffer(); + progress_made = true; + } + } +// cout << "Before: " << m_video_input << endl; + if (current_frame && m_video_input->sendVideoFrame(current_frame->frame)){ +// cout << "push frame: " << current_frame->frame.startTime() << endl; + current_frame.reset(); + progress_made = true; + } +// cout << "After: " << m_video_input << endl; + + if (!progress_made){ + std::unique_lock lg(m_lock); + if (m_stopping){ + break; + } +// cout << "sleeping 1..." << endl; + m_cv.wait(lg); +// cout << "waking 1..." << endl; + } + } + + m_recorder->stop(); +// cout << "recorder.stop()" << endl; +#endif + + + while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ +// cout << "StreamHistoryTracker: process" << endl; + QCoreApplication::processEvents(); + pause(); + } + + exec(); + +} +void StreamRecording::run(){ + auto scope_check = m_santizer.check_scope(); + try{ + internal_run(); + }catch (...){ + m_logger.log("Exception thrown out of stream recorder...", COLOR_RED); + std::lock_guard lg(m_lock); + m_stopping = true; + } +} + + + + + +StreamRecording2::StreamRecording2( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video +) + : m_logger(logger) + , m_buffer_limit(buffer_limit) + , m_start_time(start_time) + , m_audio_samples_per_frame(audio_samples_per_frame) + , m_has_video(has_video) + , m_filename(GlobalSettings::instance().TEMP_FOLDER) + , m_stopping(false) + , m_last_drop(current_time()) + , m_last_frame_time(std::numeric_limits::min()) +{ + logger.log( + "StreamRecording: Audio = " + std::to_string(audio_samples_per_frame) + + ", Video = " + std::to_string(has_video) + ); +// cout << "audio = " << audio_samples_per_frame << ", video = " << has_video << endl; + + if (audio_samples_per_frame == 0 && !has_video){ + return; + } + + if (audio_samples_per_frame > 0){ + m_audio_format.setChannelCount((int)audio_samples_per_frame); + m_audio_format.setChannelConfig(audio_samples_per_frame == 1 ? QAudioFormat::ChannelConfigMono : QAudioFormat::ChannelConfigStereo); + m_audio_format.setSampleRate((int)audio_frames_per_second); + m_audio_format.setSampleFormat(QAudioFormat::Float); + } + +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + QDir().mkdir(QString::fromStdString(m_filename)); +#endif + if (has_video){ + m_filename += now_to_filestring() + ".mp4"; + }else{ + m_filename += now_to_filestring() + ".m4a"; + } + + m_recorder.reset(new QMediaRecorder()); + m_session.setRecorder(m_recorder.get()); + + // Only initialize the streams we intend to use. + if (m_audio_samples_per_frame > 0){ + initialize_audio(); + } + if (m_has_video){ + initialize_video(); + } + + m_recorder->setMediaFormat(QMediaFormat::MPEG4); + + + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + m_recorder->setOutputDevice(&m_write_buffer); +#else + QFileInfo file(QString::fromStdString(m_filename)); + m_recorder->setOutputLocation( + QUrl::fromLocalFile(file.absoluteFilePath()) + ); +#endif + + m_recorder->record(); +} +StreamRecording2::~StreamRecording2(){ +#if 1 + stop(); +#else + { + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + m_stopping = true; + } + + m_recorder->stop(); + m_recorder.reset(); +#endif + +#ifndef PA_STREAM_HISTORY_LOCAL_BUFFER + cout << QDir().remove(QString::fromStdString(m_filename)) << endl; // REMOVE +#endif +} + +void StreamRecording2::stop(){ + auto scope_check = m_santizer.check_scope(); + + { + std::unique_lock lg(m_lock); + if (m_stopping){ + return; + } + m_stopping = true; + } + +#if 0 + run_on_main_thread_and_wait([this]{ + QEventLoop loop; + m_recorder.connect( + &m_recorder, &QMediaRecorder::recorderStateChanged, + &m_recorder, [&](QMediaRecorder::RecorderState state){ + if (state == QMediaRecorder::StoppedState){ + loop.quit(); + } + } + ); + + emit m_recorder.stop(); + + if (m_recorder.recorderState() != QMediaRecorder::StoppedState){ + loop.exec(); + } + }); +#endif + + m_recorder->stop(); + + while (m_recorder->recorderState() != QMediaRecorder::StoppedState){ + cout << "Spin waiting..." << endl; // REMOVE + pause(); + } +} + + +void StreamRecording2::initialize_audio(){ + m_audio_input.reset(new QAudioBufferInput()); + m_session.setAudioBufferInput(m_audio_input.get()); + + m_recorder->connect( + m_audio_input.get(), &QAudioBufferInput::readyToSendAudioBuffer, + m_recorder.get(), [this](){ +// cout << "readyToSendAudioBuffer()" << endl; +// std::lock_guard lg(m_lock); +// m_cv.notify_all(); + process(); + }, + Qt::DirectConnection + ); +} +void StreamRecording2::initialize_video(){ + m_video_input.reset(new QVideoFrameInput()); + m_session.setVideoFrameInput(m_video_input.get()); + + const StreamHistoryOption& settings = GlobalSettings::instance().STREAM_HISTORY; + + switch (settings.RESOLUTION){ + case StreamHistoryOption::Resolution::MATCH_INPUT: + break; + case StreamHistoryOption::Resolution::FORCE_720p: + m_recorder->setVideoResolution(1280, 720); + break; + case StreamHistoryOption::Resolution::FORCE_1080p: + m_recorder->setVideoResolution(1920, 1080); + break; + } + + switch (settings.ENCODING_MODE){ + case StreamHistoryOption::EncodingMode::FIXED_QUALITY: + switch (settings.VIDEO_QUALITY){ + case StreamHistoryOption::VideoQuality::VERY_LOW: + m_recorder->setQuality(QMediaRecorder::VeryLowQuality); + break; + case StreamHistoryOption::VideoQuality::LOW: + m_recorder->setQuality(QMediaRecorder::LowQuality); + break; + case StreamHistoryOption::VideoQuality::NORMAL: + m_recorder->setQuality(QMediaRecorder::NormalQuality); + break; + case StreamHistoryOption::VideoQuality::HIGH: + m_recorder->setQuality(QMediaRecorder::HighQuality); + break; + case StreamHistoryOption::VideoQuality::VERY_HIGH: + m_recorder->setQuality(QMediaRecorder::VeryHighQuality); + break; + } + break; + case StreamHistoryOption::EncodingMode::FIXED_BITRATE: + m_recorder->setVideoBitRate(settings.VIDEO_BITRATE * 1000); + m_recorder->setEncodingMode(QMediaRecorder::AverageBitRateEncoding); + break; + } + + m_recorder->connect( + m_video_input.get(), &QVideoFrameInput::readyToSendVideoFrame, + m_recorder.get(), [this](){ +// cout << "readyToSendVideoFrame()" << endl; +// std::lock_guard lg(m_lock); +// m_cv.notify_all(); + process(); + }, + Qt::DirectConnection + ); +} + + + + +void StreamRecording2::push_samples(WallClock timestamp, const float* data, size_t frames){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (m_audio_samples_per_frame == 0 || now < m_start_time){ + return; + } + WallClock threshold = timestamp - m_buffer_limit; + + { + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + do{ + if (m_buffered_audio.empty()){ + break; + } + + // Too much has been buffered. Drop the block. + if (m_buffered_audio.front().timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with audio recording. Dropping samples.", COLOR_RED); + } + return; + } + + }while (false); + + // Enqueue the sample block. + m_buffered_audio.emplace_back( + timestamp, + data, frames * m_audio_samples_per_frame + ); + } + + emit m_audio_input->readyToSendAudioBuffer(); +#endif +} +void StreamRecording2::push_frame(std::shared_ptr frame){ + auto scope_check = m_santizer.check_scope(); +#if 1 + WallClock now = current_time(); + if (!m_has_video || now < m_start_time){ + return; + } +// cout << "push_frame(): " << frame->frame.startTime() << " - " << frame->frame.endTime() << endl; + WallClock threshold = frame->timestamp - m_buffer_limit; + + { + std::lock_guard lg(m_lock); + if (m_stopping){ + return; + } + + qint64 frame_time = frame->frame.startTime(); + do{ + if (m_buffered_frames.empty()){ + break; + } + + // Too much has been buffered. Drop the frame. + if (m_buffered_frames.front()->timestamp < threshold){ + // Throttle the prints. + if (now - m_last_drop > std::chrono::seconds(5)){ + m_last_drop = now; + m_logger.log("Unable to keep up with video recording. Dropping samples.", COLOR_RED); + } + return; + } + + // Non-increasing timestamp. Drop possible duplicate frame. + if (frame_time <= m_last_frame_time){ + return; + } + }while (false); + + // Enqueue the frame. + m_buffered_frames.emplace_back(std::move(frame)); + m_last_frame_time = frame_time; + } + + emit m_video_input->readyToSendVideoFrame(); +#endif +} + + +bool StreamRecording2::stop_and_save(const std::string& filename){ + stop(); + +#ifdef PA_STREAM_HISTORY_LOCAL_BUFFER + return m_write_buffer.write(m_logger, filename); +#else + bool ret = QDir().rename(QString::fromStdString(m_filename), QString::fromStdString(filename)); + m_filename.clear(); + return ret; +#endif +} + +void StreamRecording2::process(){ + auto scope_check = m_santizer.check_scope(); + +// cout << "StreamRecording2::process()" << endl; + + bool progress_made; + do{ + { + std::unique_lock lg(m_lock); + if (m_stopping){ + cout << "exit" << endl; // REMOVE + break; + } + + if (!m_current_audio.is_valid() && !m_buffered_audio.empty()){ + m_current_audio = std::move(m_buffered_audio.front()); + m_buffered_audio.pop_front(); + } + if (!m_current_frame && !m_buffered_frames.empty()){ + m_current_frame = std::move(m_buffered_frames.front()); + m_buffered_frames.pop_front(); + } + + if (!m_current_audio.is_valid() && !m_current_frame){ + return; + } + } + + progress_made = false; + + if (m_current_audio.is_valid()){ + if (!m_audio_buffer.isValid()){ + const std::vector& samples = m_current_audio.samples; + QByteArray bytes((const char*)samples.data(), samples.size() * sizeof(float)); + m_audio_buffer = QAudioBuffer(bytes, m_audio_format); + } + if (m_audio_buffer.isValid() && m_audio_input->sendAudioBuffer(m_audio_buffer)){ + m_current_audio.clear(); + m_audio_buffer = QAudioBuffer(); + progress_made = true; + } + } +// cout << "Before: " << m_video_input << endl; + if (m_current_frame && m_video_input->sendVideoFrame(m_current_frame->frame)){ +// cout << "push frame: " << current_frame->frame.startTime() << endl; + m_current_frame.reset(); + progress_made = true; + } + + }while (progress_made); +} + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h index a434f2c3a2..63455615b6 100644 --- a/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h +++ b/SerialPrograms/Source/CommonFramework/Recording/StreamRecorder.h @@ -1,234 +1,234 @@ -/* Stream Recorder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_StreamRecorder_H -#define PokemonAutomation_StreamRecorder_H - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" - -//#include -//using std::cout; -//using std::endl; - - -class QAudioBufferInput; -class QVideoFrameInput; -class QMediaCaptureSession; -class QMediaRecorder; - -namespace PokemonAutomation{ - - -struct AudioBlock{ - WallClock timestamp; - std::vector samples; - - AudioBlock(AudioBlock&&) = default; - AudioBlock& operator=(AudioBlock&&) = default; - AudioBlock(const AudioBlock&) = delete; - void operator=(const AudioBlock&) = delete; - - AudioBlock() - : timestamp(WallClock::min()) - {} - AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) - : timestamp(p_timestamp) - , samples(p_samples, p_samples + p_count) - {} - - void clear(){ - samples.clear(); - } - bool is_valid() const{ - return !samples.empty(); - } -}; - - - -class WriteBuffer : public QIODevice{ -public: - ~WriteBuffer(){ - waitForBytesWritten(-1); - } - WriteBuffer(){ - setOpenMode(QIODeviceBase::WriteOnly); - } - - virtual qint64 readData(char* data, qint64 maxlen){ return 0; } - virtual qint64 writeData(const char* data, qint64 len){ - m_bytes += len; -// cout << "total = " << m_bytes << ", current = " << len << endl; - m_blocks.emplace_back(data, data + len); -// cout << "data = " << (unsigned)data[0] << endl; - return len; - } - - bool write(Logger& logger, const std::string& filename) const{ -// cout << "write()" << endl; - QFile file(QString::fromStdString(filename)); - if (!file.open(QFile::WriteOnly)){ - logger.log("Failed to write file: " + filename, COLOR_RED); - return false; - } - for (const std::vector& block : m_blocks){ - if ((size_t)file.write(block.data(), block.size()) != block.size()){ - logger.log("Failed to write file: " + filename, COLOR_RED); - return false; - } - } - file.close(); - return true; - } - -private: - uint64_t m_bytes = 0; - std::deque> m_blocks; -}; - - - - -// -// This one works, but it leaks a tiny bit of memory each time QMediaRecorder -// is started and stopped. -// -class StreamRecording : public QThread{ -public: - StreamRecording( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ); - ~StreamRecording(); - - void push_samples(WallClock timestamp, const float* data, size_t frames); - void push_frame(std::shared_ptr frame); - - bool stop_and_save(const std::string& filename); - -private: - std::unique_ptr initialize_audio(); - std::unique_ptr initialize_video(); - void internal_run(); - virtual void run() override; - -private: - Logger& m_logger; - const std::chrono::milliseconds m_buffer_limit; - const WallClock m_start_time; - const size_t m_audio_samples_per_frame; - const bool m_has_video; - - QAudioFormat m_audio_format; - std::string m_filename; - - std::mutex m_lock; - std::condition_variable m_cv; - - bool m_stopping = false; - WallClock m_last_drop; - - std::deque m_buffered_audio; - - qint64 m_last_frame_time; - std::deque> m_buffered_frames; - - WriteBuffer m_write_buffer; - - QAudioBufferInput* m_audio_input = nullptr; - QVideoFrameInput* m_video_input = nullptr; - QMediaCaptureSession* m_session = nullptr; - QMediaRecorder* m_recorder = nullptr; - - LifetimeSanitizer m_santizer; -}; - - -// -// This one doesn't work. QMediaRecorder::stop() is an asynchronous operation -// that you must execute event loop to finish it. But we cannot call event -// loop because it leads to reentrancy issues with the destruction path. -// -class StreamRecording2{ -public: - StreamRecording2( - Logger& logger, - std::chrono::milliseconds buffer_limit, - WallClock start_time, - size_t audio_samples_per_frame, - size_t audio_frames_per_second, - bool has_video - ); - ~StreamRecording2(); - - void push_samples(WallClock timestamp, const float* data, size_t frames); - void push_frame(std::shared_ptr frame); - - void stop(); - bool stop_and_save(const std::string& filename); - -private: - void initialize_audio(); - void initialize_video(); - void process(); - - -private: - Logger& m_logger; - const std::chrono::milliseconds m_buffer_limit; - const WallClock m_start_time; - const size_t m_audio_samples_per_frame; - const bool m_has_video; - - QAudioFormat m_audio_format; - std::string m_filename; - - std::mutex m_lock; -// std::condition_variable m_cv; - - bool m_stopping = false; - WallClock m_last_drop; - - std::deque m_buffered_audio; - - qint64 m_last_frame_time; - std::deque> m_buffered_frames; - - WriteBuffer m_write_buffer; - - std::unique_ptr m_audio_input; - std::unique_ptr m_video_input; - QMediaCaptureSession m_session; - std::unique_ptr m_recorder; - - AudioBlock m_current_audio; - std::shared_ptr m_current_frame; - QAudioBuffer m_audio_buffer; - - LifetimeSanitizer m_santizer; -}; - - - - -} -#endif +/* Stream Recorder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_StreamRecorder_H +#define PokemonAutomation_StreamRecorder_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/Backends/VideoFrameQt.h" + +//#include +//using std::cout; +//using std::endl; + + +class QAudioBufferInput; +class QVideoFrameInput; +class QMediaCaptureSession; +class QMediaRecorder; + +namespace PokemonAutomation{ + + +struct AudioBlock{ + WallClock timestamp; + std::vector samples; + + AudioBlock(AudioBlock&&) = default; + AudioBlock& operator=(AudioBlock&&) = default; + AudioBlock(const AudioBlock&) = delete; + void operator=(const AudioBlock&) = delete; + + AudioBlock() + : timestamp(WallClock::min()) + {} + AudioBlock(WallClock p_timestamp, const float* p_samples, size_t p_count) + : timestamp(p_timestamp) + , samples(p_samples, p_samples + p_count) + {} + + void clear(){ + samples.clear(); + } + bool is_valid() const{ + return !samples.empty(); + } +}; + + + +class WriteBuffer : public QIODevice{ +public: + ~WriteBuffer(){ + waitForBytesWritten(-1); + } + WriteBuffer(){ + setOpenMode(QIODeviceBase::WriteOnly); + } + + virtual qint64 readData(char* data, qint64 maxlen){ return 0; } + virtual qint64 writeData(const char* data, qint64 len){ + m_bytes += len; +// cout << "total = " << m_bytes << ", current = " << len << endl; + m_blocks.emplace_back(data, data + len); +// cout << "data = " << (unsigned)data[0] << endl; + return len; + } + + bool write(Logger& logger, const std::string& filename) const{ +// cout << "write()" << endl; + QFile file(QString::fromStdString(filename)); + if (!file.open(QFile::WriteOnly)){ + logger.log("Failed to write file: " + filename, COLOR_RED); + return false; + } + for (const std::vector& block : m_blocks){ + if ((size_t)file.write(block.data(), block.size()) != block.size()){ + logger.log("Failed to write file: " + filename, COLOR_RED); + return false; + } + } + file.close(); + return true; + } + +private: + uint64_t m_bytes = 0; + std::deque> m_blocks; +}; + + + + +// +// This one works, but it leaks a tiny bit of memory each time QMediaRecorder +// is started and stopped. +// +class StreamRecording : public QThread{ +public: + StreamRecording( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ); + ~StreamRecording(); + + void push_samples(WallClock timestamp, const float* data, size_t frames); + void push_frame(std::shared_ptr frame); + + bool stop_and_save(const std::string& filename); + +private: + std::unique_ptr initialize_audio(); + std::unique_ptr initialize_video(); + void internal_run(); + virtual void run() override; + +private: + Logger& m_logger; + const std::chrono::milliseconds m_buffer_limit; + const WallClock m_start_time; + const size_t m_audio_samples_per_frame; + const bool m_has_video; + + QAudioFormat m_audio_format; + std::string m_filename; + + std::mutex m_lock; + std::condition_variable m_cv; + + bool m_stopping = false; + WallClock m_last_drop; + + std::deque m_buffered_audio; + + qint64 m_last_frame_time; + std::deque> m_buffered_frames; + + WriteBuffer m_write_buffer; + + QAudioBufferInput* m_audio_input = nullptr; + QVideoFrameInput* m_video_input = nullptr; + QMediaCaptureSession* m_session = nullptr; + QMediaRecorder* m_recorder = nullptr; + + LifetimeSanitizer m_santizer; +}; + + +// +// This one doesn't work. QMediaRecorder::stop() is an asynchronous operation +// that you must execute event loop to finish it. But we cannot call event +// loop because it leads to reentrancy issues with the destruction path. +// +class StreamRecording2{ +public: + StreamRecording2( + Logger& logger, + std::chrono::milliseconds buffer_limit, + WallClock start_time, + size_t audio_samples_per_frame, + size_t audio_frames_per_second, + bool has_video + ); + ~StreamRecording2(); + + void push_samples(WallClock timestamp, const float* data, size_t frames); + void push_frame(std::shared_ptr frame); + + void stop(); + bool stop_and_save(const std::string& filename); + +private: + void initialize_audio(); + void initialize_video(); + void process(); + + +private: + Logger& m_logger; + const std::chrono::milliseconds m_buffer_limit; + const WallClock m_start_time; + const size_t m_audio_samples_per_frame; + const bool m_has_video; + + QAudioFormat m_audio_format; + std::string m_filename; + + std::mutex m_lock; +// std::condition_variable m_cv; + + bool m_stopping = false; + WallClock m_last_drop; + + std::deque m_buffered_audio; + + qint64 m_last_frame_time; + std::deque> m_buffered_frames; + + WriteBuffer m_write_buffer; + + std::unique_ptr m_audio_input; + std::unique_ptr m_video_input; + QMediaCaptureSession m_session; + std::unique_ptr m_recorder; + + AudioBlock m_current_audio; + std::shared_ptr m_current_frame; + QAudioBuffer m_audio_buffer; + + LifetimeSanitizer m_santizer; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp index 66a847da50..2afb5a3976 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp +++ b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.cpp @@ -1,268 +1,268 @@ -/* New Version Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Options/CheckForUpdatesOption.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Tools/FileDownloader.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NewVersionCheck.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -static auto CHECK_FOR_UPDATES_PERIOD = std::chrono::days(1); - - -struct ProgramVersion{ - int major; - int minor; - int patch; - std::string version_text; - - ProgramVersion(Logger& logger, const JsonObject* json){ - if (!json->read_integer(major, "VersionMajor")){ - throw_and_log(logger, "Invalid version JSON: Missing major version."); - } - if (!json->read_integer(minor, "VersionMinor")){ - throw_and_log(logger, "Invalid version JSON: Missing minor version."); - } - if (!json->read_integer(patch, "VersionPatch")){ - throw_and_log(logger, "Invalid version JSON: Missing patch #."); - } - version_text = std::to_string(major) - + "." + std::to_string(minor) - + "." + std::to_string(patch); - } - - bool is_newer() const{ - if (major > PROGRAM_VERSION_MAJOR){ - return true; - } - if (major < PROGRAM_VERSION_MAJOR){ - return false; - } - - if (minor > PROGRAM_VERSION_MINOR){ - return true; - } - if (minor < PROGRAM_VERSION_MINOR){ - return false; - } - - if (patch > PROGRAM_VERSION_PATCH){ - return true; - } - - return false; - } - - bool show_update_nag() const{ - if (!is_newer()){ - return false; - } - std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; - return version_text != skip_version; - } -}; - -bool compare_version(Logger& logger, const JsonObject* json){ - if (json == nullptr){ - logger.log("Invalid version JSON.", COLOR_RED); - return false; - } - - int major; - int minor; - int patch; - if (!json->read_integer(major, "VersionMajor")){ - logger.log("Invalid version JSON: Missing major version.", COLOR_RED); - return false; - } - if (!json->read_integer(minor, "VersionMinor")){ - logger.log("Invalid version JSON: Missing minor version.", COLOR_RED); - return false; - } - if (!json->read_integer(patch, "VersionPatch")){ - logger.log("Invalid version JSON: Missing patch #.", COLOR_RED); - return false; - } - std::string full_version = std::to_string(major) - + "." + std::to_string(minor) - + "." + std::to_string(patch); - std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; - if (full_version == skip_version){ - return false; - } - - if (major > PROGRAM_VERSION_MAJOR){ - return true; - } - if (major < PROGRAM_VERSION_MAJOR){ - return false; - } - - if (minor > PROGRAM_VERSION_MINOR){ - return true; - } - if (minor < PROGRAM_VERSION_MINOR){ - return false; - } - - if (patch > PROGRAM_VERSION_PATCH){ - return true; - } - - return false; -} -std::string get_changes(const JsonObject& json){ - const std::string* changes = json.get_string("Changes"); - if (changes == nullptr){ - return ""; - } - return "

" + *changes; -} -void show_update_box( - const std::string& title, - const std::string& link_text, - const std::string& link_url, - const std::string& header, - const ProgramVersion& version, - const JsonObject& node -){ - QMessageBox box; - QPushButton* ok = box.addButton(QMessageBox::Ok); - QPushButton* skip = box.addButton("Skip this Version", QMessageBox::NoRole); - - box.setTextFormat(Qt::RichText); - std::string text = header + "
"; - text += make_text_url(link_url, link_text); - text += get_changes(node); - - - box.setWindowTitle(QString::fromStdString(title)); - box.setText(QString::fromStdString(text)); - -// box.open(); - - box.exec(); - - QAbstractButton* clicked = box.clickedButton(); - if (clicked == ok){ - return; - } - if (clicked == skip){ - GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION.set(version.version_text); - return; - } - - -// box.information( -// nullptr, -// QString::fromStdString(title), -// QString::fromStdString(text) -// ); -} - - -void check_new_version(Logger& logger){ - bool check_release = GlobalSettings::instance().CHECK_FOR_UPDATES->RELEASE0; - bool check_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PUBLIC_BETA0; - bool check_private_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PRIVATE_BETA0; - bool updates_enabled = false; - updates_enabled |= check_release; - updates_enabled |= check_beta; - updates_enabled |= check_private_beta; - - if (!updates_enabled){ - return; - } - - static WallClock last_version_check = WallClock::min(); - WallClock now = current_time(); - if (last_version_check != WallClock::min() && now - last_version_check < CHECK_FOR_UPDATES_PERIOD){ - return; - } - last_version_check = now; - - logger.log("Checking for new version..."); - JsonValue json; - try{ - json = FileDownloader::download_json_file( - logger, - "https://raw.githubusercontent.com/PokemonAutomation/ComputerControl/master/LatestVersion.json" - ); - }catch (OperationFailedException&){ - return; - } - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - logger.log("Invalid version JSON.", COLOR_RED); - return; - } - - -// cout << json.dump() << endl; - - if (check_private_beta){ - const JsonObject* node = obj->get_object("PrivateBeta"); - ProgramVersion latest(logger, node); - if (latest.show_update_nag()){ - show_update_box( - "New Private Beta Available!", - "Download from our Discord!", - "https://discord.com/channels/695809740428673034/732736538965704726", - "A new private beta is available!", - latest, *node - ); - return; - } - } - if (check_beta){ - const JsonObject* node = obj->get_object("Beta"); - ProgramVersion latest(logger, node); - if (latest.show_update_nag()){ - show_update_box( - "New Beta Available!", - "Download here.", - "https://github.com/PokemonAutomation/ComputerControl/releases", - "A new beta is available!", - latest, *node - ); - return; - } - } - if (check_release){ - const JsonObject* node = obj->get_object("Release"); - ProgramVersion latest(logger, node); - if (latest.show_update_nag()){ - show_update_box( - "New Version Available!", - "Download here.", - "https://github.com/PokemonAutomation/ComputerControl/releases", - "A new version is available!", - latest, *node - ); - return; - } - } - -} - - - - - -} +/* New Version Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Options/CheckForUpdatesOption.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Tools/FileDownloader.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NewVersionCheck.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +static auto CHECK_FOR_UPDATES_PERIOD = std::chrono::days(1); + + +struct ProgramVersion{ + int major; + int minor; + int patch; + std::string version_text; + + ProgramVersion(Logger& logger, const JsonObject* json){ + if (!json->read_integer(major, "VersionMajor")){ + throw_and_log(logger, "Invalid version JSON: Missing major version."); + } + if (!json->read_integer(minor, "VersionMinor")){ + throw_and_log(logger, "Invalid version JSON: Missing minor version."); + } + if (!json->read_integer(patch, "VersionPatch")){ + throw_and_log(logger, "Invalid version JSON: Missing patch #."); + } + version_text = std::to_string(major) + + "." + std::to_string(minor) + + "." + std::to_string(patch); + } + + bool is_newer() const{ + if (major > PROGRAM_VERSION_MAJOR){ + return true; + } + if (major < PROGRAM_VERSION_MAJOR){ + return false; + } + + if (minor > PROGRAM_VERSION_MINOR){ + return true; + } + if (minor < PROGRAM_VERSION_MINOR){ + return false; + } + + if (patch > PROGRAM_VERSION_PATCH){ + return true; + } + + return false; + } + + bool show_update_nag() const{ + if (!is_newer()){ + return false; + } + std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; + return version_text != skip_version; + } +}; + +bool compare_version(Logger& logger, const JsonObject* json){ + if (json == nullptr){ + logger.log("Invalid version JSON.", COLOR_RED); + return false; + } + + int major; + int minor; + int patch; + if (!json->read_integer(major, "VersionMajor")){ + logger.log("Invalid version JSON: Missing major version.", COLOR_RED); + return false; + } + if (!json->read_integer(minor, "VersionMinor")){ + logger.log("Invalid version JSON: Missing minor version.", COLOR_RED); + return false; + } + if (!json->read_integer(patch, "VersionPatch")){ + logger.log("Invalid version JSON: Missing patch #.", COLOR_RED); + return false; + } + std::string full_version = std::to_string(major) + + "." + std::to_string(minor) + + "." + std::to_string(patch); + std::string skip_version = GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION; + if (full_version == skip_version){ + return false; + } + + if (major > PROGRAM_VERSION_MAJOR){ + return true; + } + if (major < PROGRAM_VERSION_MAJOR){ + return false; + } + + if (minor > PROGRAM_VERSION_MINOR){ + return true; + } + if (minor < PROGRAM_VERSION_MINOR){ + return false; + } + + if (patch > PROGRAM_VERSION_PATCH){ + return true; + } + + return false; +} +std::string get_changes(const JsonObject& json){ + const std::string* changes = json.get_string("Changes"); + if (changes == nullptr){ + return ""; + } + return "

" + *changes; +} +void show_update_box( + const std::string& title, + const std::string& link_text, + const std::string& link_url, + const std::string& header, + const ProgramVersion& version, + const JsonObject& node +){ + QMessageBox box; + QPushButton* ok = box.addButton(QMessageBox::Ok); + QPushButton* skip = box.addButton("Skip this Version", QMessageBox::NoRole); + + box.setTextFormat(Qt::RichText); + std::string text = header + "
"; + text += make_text_url(link_url, link_text); + text += get_changes(node); + + + box.setWindowTitle(QString::fromStdString(title)); + box.setText(QString::fromStdString(text)); + +// box.open(); + + box.exec(); + + QAbstractButton* clicked = box.clickedButton(); + if (clicked == ok){ + return; + } + if (clicked == skip){ + GlobalSettings::instance().CHECK_FOR_UPDATES->SKIP_VERSION.set(version.version_text); + return; + } + + +// box.information( +// nullptr, +// QString::fromStdString(title), +// QString::fromStdString(text) +// ); +} + + +void check_new_version(Logger& logger){ + bool check_release = GlobalSettings::instance().CHECK_FOR_UPDATES->RELEASE0; + bool check_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PUBLIC_BETA0; + bool check_private_beta = GlobalSettings::instance().CHECK_FOR_UPDATES->PRIVATE_BETA0; + bool updates_enabled = false; + updates_enabled |= check_release; + updates_enabled |= check_beta; + updates_enabled |= check_private_beta; + + if (!updates_enabled){ + return; + } + + static WallClock last_version_check = WallClock::min(); + WallClock now = current_time(); + if (last_version_check != WallClock::min() && now - last_version_check < CHECK_FOR_UPDATES_PERIOD){ + return; + } + last_version_check = now; + + logger.log("Checking for new version..."); + JsonValue json; + try{ + json = FileDownloader::download_json_file( + logger, + "https://raw.githubusercontent.com/PokemonAutomation/ComputerControl/master/LatestVersion.json" + ); + }catch (OperationFailedException&){ + return; + } + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + logger.log("Invalid version JSON.", COLOR_RED); + return; + } + + +// cout << json.dump() << endl; + + if (check_private_beta){ + const JsonObject* node = obj->get_object("PrivateBeta"); + ProgramVersion latest(logger, node); + if (latest.show_update_nag()){ + show_update_box( + "New Private Beta Available!", + "Download from our Discord!", + "https://discord.com/channels/695809740428673034/732736538965704726", + "A new private beta is available!", + latest, *node + ); + return; + } + } + if (check_beta){ + const JsonObject* node = obj->get_object("Beta"); + ProgramVersion latest(logger, node); + if (latest.show_update_nag()){ + show_update_box( + "New Beta Available!", + "Download here.", + "https://github.com/PokemonAutomation/ComputerControl/releases", + "A new beta is available!", + latest, *node + ); + return; + } + } + if (check_release){ + const JsonObject* node = obj->get_object("Release"); + ProgramVersion latest(logger, node); + if (latest.show_update_nag()){ + show_update_box( + "New Version Available!", + "Download here.", + "https://github.com/PokemonAutomation/ComputerControl/releases", + "A new version is available!", + latest, *node + ); + return; + } + } + +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h index 174a609949..792e587f13 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h +++ b/SerialPrograms/Source/CommonFramework/Startup/NewVersionCheck.h @@ -1,19 +1,19 @@ -/* New Version Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NewVersionCheck_H -#define PokemonAutomation_NewVersionCheck_H - -#include "CommonFramework/Logging/Logger.h" - -namespace PokemonAutomation{ - -void check_new_version(Logger& logger = global_logger_tagged()); - - - -} -#endif +/* New Version Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NewVersionCheck_H +#define PokemonAutomation_NewVersionCheck_H + +#include "CommonFramework/Logging/Logger.h" + +namespace PokemonAutomation{ + +void check_new_version(Logger& logger = global_logger_tagged()); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp index f189977e43..0cf78e8c06 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp +++ b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.cpp @@ -1,223 +1,223 @@ -/* Setup Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) -#if QT_CONFIG(permissions) -#include -#endif -#endif -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "SetupSettings.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -bool migrate_settings(Logger& logger, const std::string& file_name){ - QFile cur_dir_file(QString::fromStdString(file_name)); - QFile folder_file(QString::fromStdString(SETTINGS_PATH() + file_name)); - - logger.log("Checking if user setting JSON file need to be migrated..."); - - if (!cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Clean install, nothing to migrate."); - return true; - } - - if (!cur_dir_file.exists() && folder_file.exists()){ - logger.log("Migrated, nothing to do."); - return true; - } - - if (cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Migrating old setting file to the new folder..."); - cur_dir_file.copy(folder_file.fileName()); - logger.log("Renaming old setting file as backup..."); - cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); - logger.log("Migrated."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.information( - nullptr, - "Settings Migrated!", - QString::fromStdString( - "Detected a settings file at the old location used by version 0.29 and earlier.
" - "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." - ) - ); - return true; - } - - // last case: cur_dir_file.exists() && folder_file.exists() - logger.log("Two configs detected, showing prompt..."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.critical( - nullptr, - "Two settings files detected!", - QString::fromStdString( - "Detected two settings files at these locations:

" + - cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + - folder_file.fileName().toStdString() + " (version 0.30)" + - "

This probably happened because you used an early beta of v0.30.x which created a new " - "settings file at the new location. Please either delete or rename the file you do not want to use." - ) - ); - return false; -} - -bool migrate_stats(Logger& logger){ - logger.log("Checking if stats file should be migrated..."); - - std::string path = GlobalSettings::instance().STATS_FILE; - if (path != "PA-Stats.txt"){ - logger.log("Stats file not at old default location. Will not attempt to migrate..."); - return true; - } - - const std::string new_path = GlobalSettings::instance().STATS_FILE.default_value(); - - // old location: current working directory - QFile cur_dir_file(QString::fromStdString(path)); - // new location: - QFile folder_file(QString::fromStdString(new_path)); - - if (!cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Clean install, nothing to migrate."); - return true; - } - - if (!cur_dir_file.exists() && folder_file.exists()){ - logger.log("File migrated. Stats path in settings not updated. Updating..."); - GlobalSettings::instance().STATS_FILE.restore_defaults(); - return true; - } - - if (cur_dir_file.exists() && !folder_file.exists()){ - logger.log("Migrating old stats file to the folder..."); - cur_dir_file.copy(folder_file.fileName()); - logger.log("Renaming old stats file as backup..."); - cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); - GlobalSettings::instance().STATS_FILE.restore_defaults(); - logger.log("Migrated."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.information( - nullptr, - "Settings Migrated!", - QString::fromStdString( - "Detected a stats file at the old location used by version 0.29 and earlier.
" - "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." - ) - ); - return true; - } - - // last case: cur_dir_file.exists() && folder_file.exists() - logger.log("Two stats files detected, showing prompt..."); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.critical( - nullptr, - "Two settings files detected!", - QString::fromStdString( - "Detected two stats files at these locations:

" + - cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + - folder_file.fileName().toStdString() + " (version 0.30)" + - "

This probably happened because you used an early beta of v0.30.x which created a new stats file at the new location. " - "Please either delete or rename the file you do not want to use." - ) - ); - return false; -} - - -void set_permissions(QObject& object){ -#if defined(__APPLE__) -#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) -#if QT_CONFIG(permissions) - cout << "Checking MacOS Permissions..." << endl; - QCameraPermission camera_permission; - switch(qApp->checkPermission(camera_permission)){ - case Qt::PermissionStatus::Undetermined: - cout << "Camera permission undetermined" << endl; - qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ - cout << "camera request is ready!" << endl; - }); - cout << "Requested Camera permission" << endl; - break; - case Qt::PermissionStatus::Denied: - cout << "No camera permission found" << endl; - qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ - cout << "camera request is ready!" << endl; - }); - cout << "Requested Camera permission" << endl; - break; - case Qt::PermissionStatus::Granted: - cout << "Camera permission granted" << endl; - break; - } - - QMicrophonePermission microphone_permission; - switch(qApp->checkPermission(microphone_permission)){ - case Qt::PermissionStatus::Undetermined: - cout << "Microphone permission undetermined" << endl; - qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ - cout << "Microphone request is ready!" << endl; - }); - cout << "Requested microphone permission" << endl; - break; - case Qt::PermissionStatus::Denied: - cout << "No microphone permission found" << endl; - qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ - cout << "Microphone request is ready!" << endl; - }); - cout << "Requested microphone permission" << endl; - break; - case Qt::PermissionStatus::Granted: - cout << "Microphone permission granted" << endl; - break; - } -#endif -#endif -#endif -} - - -bool check_resource_folder(Logger& logger){ - QDir resources_folder(QString::fromStdString(RESOURCE_PATH())); - if (resources_folder.exists()){ - logger.log("Found Resource folder at " + RESOURCE_PATH()); - return true; - } - logger.log("No Resources/ folder at " + RESOURCE_PATH()); - QMessageBox box; - box.setTextFormat(Qt::RichText); - box.critical( - nullptr, - "No Resources Folder!", - QString::fromStdString( - "No Resources Folder:

" - "Make sure you download Resources folder from latest release at
" - "https://github.com/PokemonAutomation/ComputerControl/releases/

" - "The Resources folder is part of PA-SerialPrograms-[VERSION]-[DATE].zip

" - "Extract the Resources folder from the zip file and place it at following path:

" + RESOURCE_PATH() - ) - ); - return false; -} - - - -} +/* Setup Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) +#if QT_CONFIG(permissions) +#include +#endif +#endif +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "SetupSettings.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +bool migrate_settings(Logger& logger, const std::string& file_name){ + QFile cur_dir_file(QString::fromStdString(file_name)); + QFile folder_file(QString::fromStdString(SETTINGS_PATH() + file_name)); + + logger.log("Checking if user setting JSON file need to be migrated..."); + + if (!cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Clean install, nothing to migrate."); + return true; + } + + if (!cur_dir_file.exists() && folder_file.exists()){ + logger.log("Migrated, nothing to do."); + return true; + } + + if (cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Migrating old setting file to the new folder..."); + cur_dir_file.copy(folder_file.fileName()); + logger.log("Renaming old setting file as backup..."); + cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); + logger.log("Migrated."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.information( + nullptr, + "Settings Migrated!", + QString::fromStdString( + "Detected a settings file at the old location used by version 0.29 and earlier.
" + "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." + ) + ); + return true; + } + + // last case: cur_dir_file.exists() && folder_file.exists() + logger.log("Two configs detected, showing prompt..."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.critical( + nullptr, + "Two settings files detected!", + QString::fromStdString( + "Detected two settings files at these locations:

" + + cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + + folder_file.fileName().toStdString() + " (version 0.30)" + + "

This probably happened because you used an early beta of v0.30.x which created a new " + "settings file at the new location. Please either delete or rename the file you do not want to use." + ) + ); + return false; +} + +bool migrate_stats(Logger& logger){ + logger.log("Checking if stats file should be migrated..."); + + std::string path = GlobalSettings::instance().STATS_FILE; + if (path != "PA-Stats.txt"){ + logger.log("Stats file not at old default location. Will not attempt to migrate..."); + return true; + } + + const std::string new_path = GlobalSettings::instance().STATS_FILE.default_value(); + + // old location: current working directory + QFile cur_dir_file(QString::fromStdString(path)); + // new location: + QFile folder_file(QString::fromStdString(new_path)); + + if (!cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Clean install, nothing to migrate."); + return true; + } + + if (!cur_dir_file.exists() && folder_file.exists()){ + logger.log("File migrated. Stats path in settings not updated. Updating..."); + GlobalSettings::instance().STATS_FILE.restore_defaults(); + return true; + } + + if (cur_dir_file.exists() && !folder_file.exists()){ + logger.log("Migrating old stats file to the folder..."); + cur_dir_file.copy(folder_file.fileName()); + logger.log("Renaming old stats file as backup..."); + cur_dir_file.rename(cur_dir_file.fileName() + ".bak"); + GlobalSettings::instance().STATS_FILE.restore_defaults(); + logger.log("Migrated."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.information( + nullptr, + "Settings Migrated!", + QString::fromStdString( + "Detected a stats file at the old location used by version 0.29 and earlier.
" + "It has been automatically moved into the \"" + SETTINGS_PATH() + "\" folder." + ) + ); + return true; + } + + // last case: cur_dir_file.exists() && folder_file.exists() + logger.log("Two stats files detected, showing prompt..."); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.critical( + nullptr, + "Two settings files detected!", + QString::fromStdString( + "Detected two stats files at these locations:

" + + cur_dir_file.fileName().toStdString() + " (versions 0.29 and older)
" + + folder_file.fileName().toStdString() + " (version 0.30)" + + "

This probably happened because you used an early beta of v0.30.x which created a new stats file at the new location. " + "Please either delete or rename the file you do not want to use." + ) + ); + return false; +} + + +void set_permissions(QObject& object){ +#if defined(__APPLE__) +#if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) +#if QT_CONFIG(permissions) + cout << "Checking MacOS Permissions..." << endl; + QCameraPermission camera_permission; + switch(qApp->checkPermission(camera_permission)){ + case Qt::PermissionStatus::Undetermined: + cout << "Camera permission undetermined" << endl; + qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ + cout << "camera request is ready!" << endl; + }); + cout << "Requested Camera permission" << endl; + break; + case Qt::PermissionStatus::Denied: + cout << "No camera permission found" << endl; + qApp->requestPermission(camera_permission, &object, [](const QPermission &permission){ + cout << "camera request is ready!" << endl; + }); + cout << "Requested Camera permission" << endl; + break; + case Qt::PermissionStatus::Granted: + cout << "Camera permission granted" << endl; + break; + } + + QMicrophonePermission microphone_permission; + switch(qApp->checkPermission(microphone_permission)){ + case Qt::PermissionStatus::Undetermined: + cout << "Microphone permission undetermined" << endl; + qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ + cout << "Microphone request is ready!" << endl; + }); + cout << "Requested microphone permission" << endl; + break; + case Qt::PermissionStatus::Denied: + cout << "No microphone permission found" << endl; + qApp->requestPermission(microphone_permission, &object, [](const QPermission &permission){ + cout << "Microphone request is ready!" << endl; + }); + cout << "Requested microphone permission" << endl; + break; + case Qt::PermissionStatus::Granted: + cout << "Microphone permission granted" << endl; + break; + } +#endif +#endif +#endif +} + + +bool check_resource_folder(Logger& logger){ + QDir resources_folder(QString::fromStdString(RESOURCE_PATH())); + if (resources_folder.exists()){ + logger.log("Found Resource folder at " + RESOURCE_PATH()); + return true; + } + logger.log("No Resources/ folder at " + RESOURCE_PATH()); + QMessageBox box; + box.setTextFormat(Qt::RichText); + box.critical( + nullptr, + "No Resources Folder!", + QString::fromStdString( + "No Resources Folder:

" + "Make sure you download Resources folder from latest release at
" + "https://github.com/PokemonAutomation/ComputerControl/releases/

" + "The Resources folder is part of PA-SerialPrograms-[VERSION]-[DATE].zip

" + "Extract the Resources folder from the zip file and place it at following path:

" + RESOURCE_PATH() + ) + ); + return false; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h index baf5d83f9f..63d230c79b 100644 --- a/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h +++ b/SerialPrograms/Source/CommonFramework/Startup/SetupSettings.h @@ -1,37 +1,37 @@ -/* Setup Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SetupSettings_H -#define PokemonAutomation_SetupSettings_H - -#include - -class QObject; - -namespace PokemonAutomation{ - -class Logger; - -// Move user setting JSON file from old location to the new one -// return true if there is no need for migration or the migration is successful -// return false if migration fails. In this case it will also pop a critical error message box -bool migrate_settings(Logger& logger, const std::string& file_name); - -// Move stats file from old location to the new one -// return true if there is no need for migration or the migration is successful -// return false if migration fails. In this case it will also pop a critical error message box -bool migrate_stats(Logger& logger); - -// Use Qt to setup permissions of cameras and microphones on macOS. -// See https://www.qt.io/blog/permission-apis-in-qt-6.5 -void set_permissions(QObject& object); - -// Return true if there is the required Resources/ folder. -// When the folder is missing, it will also pop a critical error message box -bool check_resource_folder(Logger& logger); - -} -#endif +/* Setup Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SetupSettings_H +#define PokemonAutomation_SetupSettings_H + +#include + +class QObject; + +namespace PokemonAutomation{ + +class Logger; + +// Move user setting JSON file from old location to the new one +// return true if there is no need for migration or the migration is successful +// return false if migration fails. In this case it will also pop a critical error message box +bool migrate_settings(Logger& logger, const std::string& file_name); + +// Move stats file from old location to the new one +// return true if there is no need for migration or the migration is successful +// return false if migration fails. In this case it will also pop a critical error message box +bool migrate_stats(Logger& logger); + +// Use Qt to setup permissions of cameras and microphones on macOS. +// See https://www.qt.io/blog/permission-apis-in-qt-6.5 +void set_permissions(QObject& object); + +// Return true if there is the required Resources/ folder. +// When the folder is missing, it will also pop a critical error message box +bool check_resource_folder(Logger& logger); + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.cpp b/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.cpp index 241fa534a4..b0aec815f3 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.cpp @@ -1,37 +1,37 @@ -/* Debug Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "DebugDumper.h" -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Logging/Logger.h" - -namespace PokemonAutomation{ - -// create a folder with path ./DebugDumps/`folder_path`. -// The function will create all parent folders necessary to create the folder. -void create_debug_folder(const std::string& folder_path){ - QDir().mkdir(DEBUG_PATH().c_str()); - QDir(DEBUG_PATH().c_str()).mkpath(folder_path.c_str()); -} - -std::string dump_debug_image( - Logger& logger, - const std::string& path, - const std::string& label, - const ImageViewRGB32& image -){ - create_debug_folder(path); - std::string full_path = DEBUG_PATH() + path + "/" + now_to_filestring() + "-" + label + ".png"; - logger.log("Saving debug image to: " + full_path, COLOR_YELLOW); - image.save(full_path); - return full_path; -} - - -} +/* Debug Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "DebugDumper.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Logging/Logger.h" + +namespace PokemonAutomation{ + +// create a folder with path ./DebugDumps/`folder_path`. +// The function will create all parent folders necessary to create the folder. +void create_debug_folder(const std::string& folder_path){ + QDir().mkdir(DEBUG_PATH().c_str()); + QDir(DEBUG_PATH().c_str()).mkpath(folder_path.c_str()); +} + +std::string dump_debug_image( + Logger& logger, + const std::string& path, + const std::string& label, + const ImageViewRGB32& image +){ + create_debug_folder(path); + std::string full_path = DEBUG_PATH() + path + "/" + now_to_filestring() + "-" + label + ".png"; + logger.log("Saving debug image to: " + full_path, COLOR_YELLOW); + image.save(full_path); + return full_path; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.h b/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.h index 2f75afd5c9..33d1ebee30 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.h +++ b/SerialPrograms/Source/CommonFramework/Tools/DebugDumper.h @@ -1,27 +1,27 @@ -/* Debug Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DebugDumper_H -#define PokemonAutomation_DebugDumper_H - -#include - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class Logger; - -// Dump debug image to ./DebugDumps/`path`/-`label`.png -// Return image path. -std::string dump_debug_image( - Logger& logger, - const std::string& path, - const std::string& label, - const ImageViewRGB32& image -); - -} -#endif +/* Debug Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DebugDumper_H +#define PokemonAutomation_DebugDumper_H + +#include + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class Logger; + +// Dump debug image to ./DebugDumps/`path`/-`label`.png +// Return image path. +std::string dump_debug_image( + Logger& logger, + const std::string& path, + const std::string& label, + const ImageViewRGB32& image +); + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.cpp b/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.cpp index 17da53b182..813a1cd721 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.cpp @@ -1,94 +1,94 @@ -/* Error Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -//#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ErrorReports/ErrorReports.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "ErrorDumper.h" -//#include "ProgramEnvironment.h" -namespace PokemonAutomation{ - - - -std::string dump_image_alone( - Logger& logger, - const ProgramInfo& program_info, const std::string& label, - const ImageViewRGB32& image -){ - static std::mutex lock; - std::lock_guard lg(lock); - - QDir().mkdir(ERROR_PATH().c_str()); - std::string name = ERROR_PATH() + now_to_filestring(); - name += "-"; - name += label; - name += ".png"; - logger.log("Saving failed inference image to: " + name, COLOR_RED); - image.save(name); - return name; -} -void dump_image( - Logger& logger, - const ProgramInfo& program_info, const std::string& label, - const ImageViewRGB32& image, - const StreamHistorySession* stream_history -){ - report_error( - &logger, - program_info, - label, - {}, - image, - stream_history - ); -} -void dump_image( - Logger& logger, - const ProgramInfo& program_info, - VideoFeed& video, - const std::string& label -){ - auto snapshot = video.snapshot(); - dump_image(logger, program_info, label, snapshot); -} - - -void dump_image_and_throw_recoverable_exception( - const ProgramInfo& program_info, - VideoStream& stream, - const std::string& error_name, - const std::string& error_message, - const ImageViewRGB32& screenshot -){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - error_message, - stream - ); -} - - - - - - - - - - - - - -} +/* Error Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +//#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ErrorReports/ErrorReports.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "ErrorDumper.h" +//#include "ProgramEnvironment.h" +namespace PokemonAutomation{ + + + +std::string dump_image_alone( + Logger& logger, + const ProgramInfo& program_info, const std::string& label, + const ImageViewRGB32& image +){ + static std::mutex lock; + std::lock_guard lg(lock); + + QDir().mkdir(ERROR_PATH().c_str()); + std::string name = ERROR_PATH() + now_to_filestring(); + name += "-"; + name += label; + name += ".png"; + logger.log("Saving failed inference image to: " + name, COLOR_RED); + image.save(name); + return name; +} +void dump_image( + Logger& logger, + const ProgramInfo& program_info, const std::string& label, + const ImageViewRGB32& image, + const StreamHistorySession* stream_history +){ + report_error( + &logger, + program_info, + label, + {}, + image, + stream_history + ); +} +void dump_image( + Logger& logger, + const ProgramInfo& program_info, + VideoFeed& video, + const std::string& label +){ + auto snapshot = video.snapshot(); + dump_image(logger, program_info, label, snapshot); +} + + +void dump_image_and_throw_recoverable_exception( + const ProgramInfo& program_info, + VideoStream& stream, + const std::string& error_name, + const std::string& error_message, + const ImageViewRGB32& screenshot +){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + error_message, + stream + ); +} + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.h b/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.h index 2726222d46..6ab7de8d34 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.h +++ b/SerialPrograms/Source/CommonFramework/Tools/ErrorDumper.h @@ -1,61 +1,61 @@ -/* Error Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ErrorDumper_H -#define PokemonAutomation_ErrorDumper_H - -#include -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ - -class VideoFeed; -class StreamHistorySession; -class VideoStream; -class EventNotificationOption; -class ImageViewRGB32; -class Logger; -struct VideoSnapshot; -class ProgramEnvironment; -struct ProgramInfo; - -#if 0 -std::string dump_image_alone( - Logger& logger, - const ProgramInfo& program_info, const std::string& label, - const ImageViewRGB32& image -); -#endif - -// Dump error image to ./ErrorDumps/ folder. Also send image as telemetry if user allows. -void dump_image( - Logger& logger, - const ProgramInfo& program_info, const std::string& label, - const ImageViewRGB32& image, - const StreamHistorySession* stream_history = nullptr -); -void dump_image( - Logger& logger, - const ProgramInfo& program_info, - VideoFeed& video, - const std::string& label -); - -// dump a screenshot to ./ErrorDumps/ folder and throw an OperationFailedException. -// error_name: the error name, used as the image name and show up on video overlay log. Typical format example: -// "NoHatchEnd", "NoYCommFound". -// error_message: the exception mesage. -[[noreturn]] void dump_image_and_throw_recoverable_exception( - const ProgramInfo& program_info, - VideoStream& stream, - const std::string& error_name, - const std::string& error_message, - const ImageViewRGB32& screenshot = ImageViewRGB32() -); - - -} -#endif +/* Error Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ErrorDumper_H +#define PokemonAutomation_ErrorDumper_H + +#include +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ + +class VideoFeed; +class StreamHistorySession; +class VideoStream; +class EventNotificationOption; +class ImageViewRGB32; +class Logger; +struct VideoSnapshot; +class ProgramEnvironment; +struct ProgramInfo; + +#if 0 +std::string dump_image_alone( + Logger& logger, + const ProgramInfo& program_info, const std::string& label, + const ImageViewRGB32& image +); +#endif + +// Dump error image to ./ErrorDumps/ folder. Also send image as telemetry if user allows. +void dump_image( + Logger& logger, + const ProgramInfo& program_info, const std::string& label, + const ImageViewRGB32& image, + const StreamHistorySession* stream_history = nullptr +); +void dump_image( + Logger& logger, + const ProgramInfo& program_info, + VideoFeed& video, + const std::string& label +); + +// dump a screenshot to ./ErrorDumps/ folder and throw an OperationFailedException. +// error_name: the error name, used as the image name and show up on video overlay log. Typical format example: +// "NoHatchEnd", "NoYCommFound". +// error_message: the exception mesage. +[[noreturn]] void dump_image_and_throw_recoverable_exception( + const ProgramInfo& program_info, + VideoStream& stream, + const std::string& error_name, + const std::string& error_message, + const ImageViewRGB32& screenshot = ImageViewRGB32() +); + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.cpp b/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.cpp index ec45866389..f55825b7e4 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.cpp @@ -1,101 +1,101 @@ -/* File Downloader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "FileDownloader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace FileDownloader{ - -std::string download_file(Logger& logger, const std::string& url){ -// cout << "download_file()" << endl; - QNetworkAccessManager network_access_manager; - QByteArray downloaded_data; - std::unique_ptr reply; - QEventLoop loop; - - QObject::connect( - &network_access_manager, &QNetworkAccessManager::finished, - &loop, [&downloaded_data, &loop](QNetworkReply* reply){ -// cout << "QNetworkAccessManager::finished" << endl; - downloaded_data = reply->readAll(); -// reply->deleteLater(); - loop.exit(); - } - ); - QObject::connect( - &network_access_manager, &QNetworkAccessManager::sslErrors, - &loop, [&downloaded_data, &loop](QNetworkReply* reply){ -// cout << "QNetworkAccessManager::sslErrors" << endl; - downloaded_data = reply->readAll(); -// reply->deleteLater(); - loop.exit(); - } - ); - - QNetworkRequest request(QUrl(QString::fromStdString(url))); - reply.reset(network_access_manager.get(request)); - -#if 0 - QTimer timer; - timer.singleShot( - 5000, [&downloaded_data, &url](){ - if (downloaded_data.isEmpty()){ - throw ConnectionException(nullptr, "Couldn't retrieved file from url : " + url + " after 5 seconds."); - } - }); - timer.stop(); - cout << "Stop timer" << endl; -#endif - -// cout << "loop.exec() - enter" << endl; - loop.exec(); -// cout << "loop.exec() - exit" << endl; - - if (!reply){ - std::string str = "QNetworkReply is null."; -// logger.log(str, COLOR_RED); - throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, str); - }else if (reply->error() == QNetworkReply::NoError){ -// QString contents = QString::fromUtf8(reply->readAll()); -// qDebug() << contents; - }else{ - QString error_string = reply->errorString(); - std::string str = "Network Error: " + error_string.toStdString(); -// logger.log(str, COLOR_RED); - throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, str); -// QString err = reply->errorString(); -// qDebug() << err; - } - - return std::string(downloaded_data.data(), downloaded_data.size()); -} -JsonValue download_json_file(Logger& logger, const std::string& url){ - std::string downloaded_data = download_file(logger, url); - return parse_json(downloaded_data); -} - - - - - -} -} +/* File Downloader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "FileDownloader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace FileDownloader{ + +std::string download_file(Logger& logger, const std::string& url){ +// cout << "download_file()" << endl; + QNetworkAccessManager network_access_manager; + QByteArray downloaded_data; + std::unique_ptr reply; + QEventLoop loop; + + QObject::connect( + &network_access_manager, &QNetworkAccessManager::finished, + &loop, [&downloaded_data, &loop](QNetworkReply* reply){ +// cout << "QNetworkAccessManager::finished" << endl; + downloaded_data = reply->readAll(); +// reply->deleteLater(); + loop.exit(); + } + ); + QObject::connect( + &network_access_manager, &QNetworkAccessManager::sslErrors, + &loop, [&downloaded_data, &loop](QNetworkReply* reply){ +// cout << "QNetworkAccessManager::sslErrors" << endl; + downloaded_data = reply->readAll(); +// reply->deleteLater(); + loop.exit(); + } + ); + + QNetworkRequest request(QUrl(QString::fromStdString(url))); + reply.reset(network_access_manager.get(request)); + +#if 0 + QTimer timer; + timer.singleShot( + 5000, [&downloaded_data, &url](){ + if (downloaded_data.isEmpty()){ + throw ConnectionException(nullptr, "Couldn't retrieved file from url : " + url + " after 5 seconds."); + } + }); + timer.stop(); + cout << "Stop timer" << endl; +#endif + +// cout << "loop.exec() - enter" << endl; + loop.exec(); +// cout << "loop.exec() - exit" << endl; + + if (!reply){ + std::string str = "QNetworkReply is null."; +// logger.log(str, COLOR_RED); + throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, str); + }else if (reply->error() == QNetworkReply::NoError){ +// QString contents = QString::fromUtf8(reply->readAll()); +// qDebug() << contents; + }else{ + QString error_string = reply->errorString(); + std::string str = "Network Error: " + error_string.toStdString(); +// logger.log(str, COLOR_RED); + throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, str); +// QString err = reply->errorString(); +// qDebug() << err; + } + + return std::string(downloaded_data.data(), downloaded_data.size()); +} +JsonValue download_json_file(Logger& logger, const std::string& url){ + std::string downloaded_data = download_file(logger, url); + return parse_json(downloaded_data); +} + + + + + +} +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.h b/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.h index 92243a3718..42045c6081 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.h +++ b/SerialPrograms/Source/CommonFramework/Tools/FileDownloader.h @@ -1,27 +1,27 @@ -/* File Downloader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_FileDownloader_H -#define PokemonAutomation_FileDownloader_H - -#include - -namespace PokemonAutomation{ - class Logger; - class JsonValue; -namespace FileDownloader{ - -// Throws OperationFailedException if failed to download. -std::string download_file(Logger& logger, const std::string& url); - -// Throws OperationFailedException if failed to download. -// Returns empty value if invalid JSON. -JsonValue download_json_file(Logger& logger, const std::string& url); - - -} -} -#endif +/* File Downloader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_FileDownloader_H +#define PokemonAutomation_FileDownloader_H + +#include + +namespace PokemonAutomation{ + class Logger; + class JsonValue; +namespace FileDownloader{ + +// Throws OperationFailedException if failed to download. +std::string download_file(Logger& logger, const std::string& url); + +// Throws OperationFailedException if failed to download. +// Returns empty value if invalid JSON. +JsonValue download_json_file(Logger& logger, const std::string& url); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp index 83e9546d77..7c47ba2a41 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.cpp @@ -1,96 +1,96 @@ -/* Program Environment - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ProgramSession.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "ProgramEnvironment.h" - - -namespace PokemonAutomation{ - - -struct ProgramEnvironmentData{ - const ProgramInfo& m_program_info; - - AsyncDispatcher m_realtime_dispatcher; - AsyncDispatcher m_realtime_inference_dispatcher; - AsyncDispatcher m_normal_inference_dispatcher; - - ProgramEnvironmentData( - const ProgramInfo& program_info - ) - : m_program_info(program_info) - , m_realtime_dispatcher( - [](){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - }, - 0 - ) - , m_realtime_inference_dispatcher( - [](){ - GlobalSettings::instance().PERFORMANCE->REALTIME_INFERENCE_PRIORITY.set_on_this_thread(); - }, - 0 - ) - , m_normal_inference_dispatcher( - [](){ - GlobalSettings::instance().PERFORMANCE->NORMAL_INFERENCE_PRIORITY.set_on_this_thread(); - }, - 0 - ) - {} -}; - - - - -ProgramEnvironment::~ProgramEnvironment(){} - -ProgramEnvironment::ProgramEnvironment( - const ProgramInfo& program_info, - ProgramSession& session, - StatsTracker* current_stats, - const StatsTracker* historical_stats -) - : m_session(session) - , m_logger(session.logger()) - , m_current_stats(current_stats) - , m_historical_stats(historical_stats) - , m_data(CONSTRUCT_TOKEN, program_info) -{} - -const ProgramInfo& ProgramEnvironment::program_info() const{ - return m_data->m_program_info; -} -AsyncDispatcher& ProgramEnvironment::realtime_dispatcher(){ - return m_data->m_realtime_dispatcher; -} -AsyncDispatcher& ProgramEnvironment::realtime_inference_dispatcher(){ - return m_data->m_realtime_inference_dispatcher; -} -AsyncDispatcher& ProgramEnvironment::normal_inference_dispatcher(){ - return m_data->m_normal_inference_dispatcher; -} - - -void ProgramEnvironment::update_stats(){ - m_session.report_stats_changed(); -} - - -std::string ProgramEnvironment::historical_stats_str() const{ - return m_historical_stats ? m_historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) : ""; -} - - - - -} +/* Program Environment + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ProgramSession.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "ProgramEnvironment.h" + + +namespace PokemonAutomation{ + + +struct ProgramEnvironmentData{ + const ProgramInfo& m_program_info; + + AsyncDispatcher m_realtime_dispatcher; + AsyncDispatcher m_realtime_inference_dispatcher; + AsyncDispatcher m_normal_inference_dispatcher; + + ProgramEnvironmentData( + const ProgramInfo& program_info + ) + : m_program_info(program_info) + , m_realtime_dispatcher( + [](){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + }, + 0 + ) + , m_realtime_inference_dispatcher( + [](){ + GlobalSettings::instance().PERFORMANCE->REALTIME_INFERENCE_PRIORITY.set_on_this_thread(); + }, + 0 + ) + , m_normal_inference_dispatcher( + [](){ + GlobalSettings::instance().PERFORMANCE->NORMAL_INFERENCE_PRIORITY.set_on_this_thread(); + }, + 0 + ) + {} +}; + + + + +ProgramEnvironment::~ProgramEnvironment(){} + +ProgramEnvironment::ProgramEnvironment( + const ProgramInfo& program_info, + ProgramSession& session, + StatsTracker* current_stats, + const StatsTracker* historical_stats +) + : m_session(session) + , m_logger(session.logger()) + , m_current_stats(current_stats) + , m_historical_stats(historical_stats) + , m_data(CONSTRUCT_TOKEN, program_info) +{} + +const ProgramInfo& ProgramEnvironment::program_info() const{ + return m_data->m_program_info; +} +AsyncDispatcher& ProgramEnvironment::realtime_dispatcher(){ + return m_data->m_realtime_dispatcher; +} +AsyncDispatcher& ProgramEnvironment::realtime_inference_dispatcher(){ + return m_data->m_realtime_inference_dispatcher; +} +AsyncDispatcher& ProgramEnvironment::normal_inference_dispatcher(){ + return m_data->m_normal_inference_dispatcher; +} + + +void ProgramEnvironment::update_stats(){ + m_session.report_stats_changed(); +} + + +std::string ProgramEnvironment::historical_stats_str() const{ + return m_historical_stats ? m_historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) : ""; +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h index 6915f42652..c92c50552d 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h +++ b/SerialPrograms/Source/CommonFramework/Tools/ProgramEnvironment.h @@ -1,95 +1,95 @@ -/* Program Environment - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramEnvironment_H -#define PokemonAutomation_ProgramEnvironment_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ - -class AsyncDispatcher; -class StatsTracker; -class ProgramSession; -struct ProgramInfo; - - - -struct ProgramEnvironmentData; - -class ProgramEnvironment{ -public: - ~ProgramEnvironment(); - ProgramEnvironment( - const ProgramInfo& program_info, - ProgramSession& session, - StatsTracker* current_stats, - const StatsTracker* historical_stats - ); - - const ProgramInfo& program_info() const; - -public: - // Logging - Logger& logger(){ return m_logger; } - void log(const char* msg, Color color = Color()){ m_logger.log(msg, color); } - void log(const std::string& msg, Color color = Color()){ m_logger.log(msg, color); } - -public: - // Thread Pools - - // A high-priority dispatcher for program and logic threads that cannot - // tolerate being delayed. - AsyncDispatcher& realtime_dispatcher(); - - // A high-priority dispatcher for inference where starvation may cause the - // program to encounter issues. - AsyncDispatcher& realtime_inference_dispatcher(); - - // A low-priority dispatcher for inference where starvation will not affect - // the functionality of the program. - AsyncDispatcher& normal_inference_dispatcher(); - -public: - // Stats Management - - void update_stats(); - - template - StatsType& current_stats(); - const StatsTracker* current_stats() const{ return m_current_stats; } - - const StatsTracker* historical_stats() const{ return m_historical_stats; } - std::string historical_stats_str() const; - - -private: - ProgramSession& m_session; - Logger& m_logger; - - StatsTracker* m_current_stats; - const StatsTracker* m_historical_stats; - - Pimpl m_data; -}; - - - - -// Templates - -template -StatsType& ProgramEnvironment::current_stats(){ - return *static_cast(m_current_stats); -} - - - - -} -#endif - +/* Program Environment + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramEnvironment_H +#define PokemonAutomation_ProgramEnvironment_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ + +class AsyncDispatcher; +class StatsTracker; +class ProgramSession; +struct ProgramInfo; + + + +struct ProgramEnvironmentData; + +class ProgramEnvironment{ +public: + ~ProgramEnvironment(); + ProgramEnvironment( + const ProgramInfo& program_info, + ProgramSession& session, + StatsTracker* current_stats, + const StatsTracker* historical_stats + ); + + const ProgramInfo& program_info() const; + +public: + // Logging + Logger& logger(){ return m_logger; } + void log(const char* msg, Color color = Color()){ m_logger.log(msg, color); } + void log(const std::string& msg, Color color = Color()){ m_logger.log(msg, color); } + +public: + // Thread Pools + + // A high-priority dispatcher for program and logic threads that cannot + // tolerate being delayed. + AsyncDispatcher& realtime_dispatcher(); + + // A high-priority dispatcher for inference where starvation may cause the + // program to encounter issues. + AsyncDispatcher& realtime_inference_dispatcher(); + + // A low-priority dispatcher for inference where starvation will not affect + // the functionality of the program. + AsyncDispatcher& normal_inference_dispatcher(); + +public: + // Stats Management + + void update_stats(); + + template + StatsType& current_stats(); + const StatsTracker* current_stats() const{ return m_current_stats; } + + const StatsTracker* historical_stats() const{ return m_historical_stats; } + std::string historical_stats_str() const; + + +private: + ProgramSession& m_session; + Logger& m_logger; + + StatsTracker* m_current_stats; + const StatsTracker* m_historical_stats; + + Pimpl m_data; +}; + + + + +// Templates + +template +StatsType& ProgramEnvironment::current_stats(){ + return *static_cast(m_current_stats); +} + + + + +} +#endif + diff --git a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp index 90e1c5d0c2..41a1e54155 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.cpp @@ -1,113 +1,113 @@ -/* Stat Accumulator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Logging/Logger.h" -#include "StatAccumulator.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -void StatAccumulatorI32::clear(){ - *this = StatAccumulatorI32(); -} -void StatAccumulatorI32::operator+=(uint32_t x){ - m_count++; - m_sum += x; - m_sqr += (uint64_t)x*x; - m_min = std::min(m_min, x); - m_max = std::max(m_max, x); -} - -double StatAccumulatorI32::mean() const{ - return (double)m_sum / m_count; -} -double StatAccumulatorI32::stddev() const{ - double diff = m_sqr - (double)m_sum*m_sum / m_count; - return std::sqrt(diff / (m_count - 1)); -} - - -std::string StatAccumulatorI32::dump(const char* units, double divider) const{ - divider = 1. / divider; - std::string str; - str += "Count = " + tostr_u_commas(m_count); - str += ", Mean = " + tostr_default(mean() * divider) + units; - str += ", Stddev = " + tostr_default(stddev() * divider) + units; - str += ", Min = " + tostr_default(min() * divider) + units; - str += ", Max = " + tostr_default(max() * divider) + units; - return str; -} -void StatAccumulatorI32::log(Logger& logger, const std::string& label, const char* units, double divider) const{ - logger.log(label + ": " + dump(units, divider), COLOR_MAGENTA); -} - - - -PeriodicStatsReporterI32::PeriodicStatsReporterI32( - const char* label, - const char* units, double divider, - std::chrono::milliseconds period -) - : m_label(label) - , m_units(units) - , m_divider(divider) - , m_period(period) - , m_last_report(current_time()) -{} -void PeriodicStatsReporterI32::report_data(Logger& logger, uint32_t x){ - StatAccumulatorI32::operator+=(x); - WallClock now = current_time(); - if (m_last_report + m_period <= now){ - log(logger, m_label, m_units, m_divider); - clear(); - m_last_report = now; - } - -} - - - - - - -FloatStatAccumulator::FloatStatAccumulator() - : m_count(0) - , m_sum(0) - , m_sqr(0) - , m_min(INFINITY) - , m_max(-INFINITY) -{} - -void FloatStatAccumulator::operator+=(double x){ - m_count++; - m_sum += x; - m_sqr += x*x; - m_min = std::min(m_min, x); - m_max = std::max(m_max, x); -} - -double FloatStatAccumulator::mean() const{ - return m_sum / m_count; -} -double FloatStatAccumulator::stddev() const{ - return std::sqrt((m_sqr - m_sum*m_sum / m_count) / (m_count - 1)); -} -double FloatStatAccumulator::diff_metric(double reference) const{ - return std::sqrt((m_sqr + reference*(reference * m_count - 2 * m_sum)) / m_count); -} - - - - -} +/* Stat Accumulator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Logging/Logger.h" +#include "StatAccumulator.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +void StatAccumulatorI32::clear(){ + *this = StatAccumulatorI32(); +} +void StatAccumulatorI32::operator+=(uint32_t x){ + m_count++; + m_sum += x; + m_sqr += (uint64_t)x*x; + m_min = std::min(m_min, x); + m_max = std::max(m_max, x); +} + +double StatAccumulatorI32::mean() const{ + return (double)m_sum / m_count; +} +double StatAccumulatorI32::stddev() const{ + double diff = m_sqr - (double)m_sum*m_sum / m_count; + return std::sqrt(diff / (m_count - 1)); +} + + +std::string StatAccumulatorI32::dump(const char* units, double divider) const{ + divider = 1. / divider; + std::string str; + str += "Count = " + tostr_u_commas(m_count); + str += ", Mean = " + tostr_default(mean() * divider) + units; + str += ", Stddev = " + tostr_default(stddev() * divider) + units; + str += ", Min = " + tostr_default(min() * divider) + units; + str += ", Max = " + tostr_default(max() * divider) + units; + return str; +} +void StatAccumulatorI32::log(Logger& logger, const std::string& label, const char* units, double divider) const{ + logger.log(label + ": " + dump(units, divider), COLOR_MAGENTA); +} + + + +PeriodicStatsReporterI32::PeriodicStatsReporterI32( + const char* label, + const char* units, double divider, + std::chrono::milliseconds period +) + : m_label(label) + , m_units(units) + , m_divider(divider) + , m_period(period) + , m_last_report(current_time()) +{} +void PeriodicStatsReporterI32::report_data(Logger& logger, uint32_t x){ + StatAccumulatorI32::operator+=(x); + WallClock now = current_time(); + if (m_last_report + m_period <= now){ + log(logger, m_label, m_units, m_divider); + clear(); + m_last_report = now; + } + +} + + + + + + +FloatStatAccumulator::FloatStatAccumulator() + : m_count(0) + , m_sum(0) + , m_sqr(0) + , m_min(INFINITY) + , m_max(-INFINITY) +{} + +void FloatStatAccumulator::operator+=(double x){ + m_count++; + m_sum += x; + m_sqr += x*x; + m_min = std::min(m_min, x); + m_max = std::max(m_max, x); +} + +double FloatStatAccumulator::mean() const{ + return m_sum / m_count; +} +double FloatStatAccumulator::stddev() const{ + return std::sqrt((m_sqr - m_sum*m_sum / m_count) / (m_count - 1)); +} +double FloatStatAccumulator::diff_metric(double reference) const{ + return std::sqrt((m_sqr + reference*(reference * m_count - 2 * m_sum)) / m_count); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h index b3a73b5a4c..e9ff8f0021 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h +++ b/SerialPrograms/Source/CommonFramework/Tools/StatAccumulator.h @@ -1,89 +1,89 @@ -/* Stat Accumulator - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonFramework_StatAccumulator_H -#define PokemonAutomation_CommonFramework_StatAccumulator_H - -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - -class Logger; - - -class StatAccumulatorI32{ -public: - using StatObject = uint32_t; - -public: - void clear(); - void operator+=(uint32_t x); - - uint64_t count() const{ return m_count; }; - uint32_t min() const{ return m_min; } - uint32_t max() const{ return m_max; } - double mean() const; - double stddev() const; - - std::string dump(const char* units, double divider) const; - void log(Logger& logger, const std::string& label, const char* units, double divider) const; - -private: - uint64_t m_count = 0; - uint64_t m_sum = 0; - uint64_t m_sqr = 0; - uint32_t m_min = (uint32_t)-1; - uint32_t m_max = 0; -}; - -class PeriodicStatsReporterI32 : public StatAccumulatorI32{ -public: - PeriodicStatsReporterI32( - const char* label, - const char* units, double divider, - std::chrono::milliseconds period - ); - void report_data(Logger& logger, uint32_t x); - -private: - const char* m_label; - const char* m_units; - double m_divider; - std::chrono::milliseconds m_period; - WallClock m_last_report; -}; - - - -class FloatStatAccumulator{ -public: - using StatObject = double; - -public: - FloatStatAccumulator(); - - void operator+=(double x); - - uint64_t count() const{ return m_count; }; - double min() const{ return m_min; } - double max() const{ return m_max; } - double mean() const; - double stddev() const; - double diff_metric(double reference) const; - -private: - uint64_t m_count; - double m_sum; - double m_sqr; - double m_min; - double m_max; -}; - - -} -#endif +/* Stat Accumulator + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonFramework_StatAccumulator_H +#define PokemonAutomation_CommonFramework_StatAccumulator_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + +class Logger; + + +class StatAccumulatorI32{ +public: + using StatObject = uint32_t; + +public: + void clear(); + void operator+=(uint32_t x); + + uint64_t count() const{ return m_count; }; + uint32_t min() const{ return m_min; } + uint32_t max() const{ return m_max; } + double mean() const; + double stddev() const; + + std::string dump(const char* units, double divider) const; + void log(Logger& logger, const std::string& label, const char* units, double divider) const; + +private: + uint64_t m_count = 0; + uint64_t m_sum = 0; + uint64_t m_sqr = 0; + uint32_t m_min = (uint32_t)-1; + uint32_t m_max = 0; +}; + +class PeriodicStatsReporterI32 : public StatAccumulatorI32{ +public: + PeriodicStatsReporterI32( + const char* label, + const char* units, double divider, + std::chrono::milliseconds period + ); + void report_data(Logger& logger, uint32_t x); + +private: + const char* m_label; + const char* m_units; + double m_divider; + std::chrono::milliseconds m_period; + WallClock m_last_report; +}; + + + +class FloatStatAccumulator{ +public: + using StatObject = double; + +public: + FloatStatAccumulator(); + + void operator+=(double x); + + uint64_t count() const{ return m_count; }; + double min() const{ return m_min; } + double max() const{ return m_max; } + double mean() const; + double stddev() const; + double diff_metric(double reference) const; + +private: + uint64_t m_count; + double m_sum; + double m_sqr; + double m_min; + double m_max; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp index 2c3f395f7a..8ec518cd97 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp +++ b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.cpp @@ -1,52 +1,52 @@ -/* Video Stream - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "CommonTools/InferencePivots/VisualInferencePivot.h" -#include "CommonTools/InferencePivots/AudioInferencePivot.h" -#include "VideoStream.h" - -namespace PokemonAutomation{ - - - -VideoStream::VideoStream(VideoStream&& x) = default; -VideoStream::~VideoStream(){ - m_overlay.remove_stat(*m_audio_pivot); - m_overlay.remove_stat(*m_video_pivot); -} -VideoStream::VideoStream( - Logger& logger, - AudioFeed& audio, - VideoFeed& video, - const StreamHistorySession& history, - VideoOverlay& overlay -) - : m_logger(logger) - , m_audio(audio) - , m_video(video) - , m_history(history) - , m_overlay(overlay) -{} - - -bool VideoStream::save_stream_history(const std::string& filename){ - return history().save(filename); -} - - -void VideoStream::initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher){ - m_video_pivot.reset(scope, m_video, dispatcher); - m_audio_pivot.reset(scope, m_audio, dispatcher); - m_overlay.add_stat(*m_video_pivot); - m_overlay.add_stat(*m_audio_pivot); -} - - - -} +/* Video Stream + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "CommonTools/InferencePivots/VisualInferencePivot.h" +#include "CommonTools/InferencePivots/AudioInferencePivot.h" +#include "VideoStream.h" + +namespace PokemonAutomation{ + + + +VideoStream::VideoStream(VideoStream&& x) = default; +VideoStream::~VideoStream(){ + m_overlay.remove_stat(*m_audio_pivot); + m_overlay.remove_stat(*m_video_pivot); +} +VideoStream::VideoStream( + Logger& logger, + AudioFeed& audio, + VideoFeed& video, + const StreamHistorySession& history, + VideoOverlay& overlay +) + : m_logger(logger) + , m_audio(audio) + , m_video(video) + , m_history(history) + , m_overlay(overlay) +{} + + +bool VideoStream::save_stream_history(const std::string& filename){ + return history().save(filename); +} + + +void VideoStream::initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher){ + m_video_pivot.reset(scope, m_video, dispatcher); + m_audio_pivot.reset(scope, m_audio, dispatcher); + m_overlay.add_stat(*m_video_pivot); + m_overlay.add_stat(*m_audio_pivot); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h index c180115378..4f599d649a 100644 --- a/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h +++ b/SerialPrograms/Source/CommonFramework/Tools/VideoStream.h @@ -1,95 +1,95 @@ -/* Video Stream - * - * From: https://github.com/PokemonAutomation/ - * - * Represents a single video stream. Includes video, audio, as well - * as their inference pivots. Also includes a logger and the video overlay. - * - * This is the class that should be passed into inference modules as it - * provides all the information needed for inference. - * - * This class has been separated from ConsoleHandle which used to take this - * role. But 95% of the uses don't require the controller. And the controller - * is messy due to being heterogeneous. - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoStream_H -#define PokemonAutomation_VideoPipeline_VideoStream_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" - -namespace PokemonAutomation{ - -class CancellableScope; -class AsyncDispatcher; -class Logger; -class AudioFeed; -class VideoFeed; -class StreamHistorySession; -class VideoOverlay; -class VisualInferencePivot; -class AudioInferencePivot; - - -class VideoStream{ -public: - VideoStream(VideoStream&& x); - void operator=(VideoStream&& x) = delete; - VideoStream(const VideoStream& x) = delete; - void operator=(const VideoStream& x) = delete; - ~VideoStream(); - -public: - VideoStream( - Logger& logger, - AudioFeed& audio, - VideoFeed& video, - const StreamHistorySession& history, - VideoOverlay& overlay - ); - - // log(string-like msg, Color color = Color()) - // string-like can be const char* or std::string - template - void log(Args&&... args){ - m_logger.log(std::forward(args)...); - } - - Logger& logger(){ return m_logger; } - - AudioFeed& audio(){ return m_audio; } - VideoFeed& video(){ return m_video; } - - const StreamHistorySession& history() const{ return m_history; } - bool save_stream_history(const std::string& filename); - - VideoOverlay& overlay(){ return m_overlay; } - - VisualInferencePivot& video_inference_pivot(){ return *m_video_pivot; } - AudioInferencePivot& audio_inference_pivot(){ return *m_audio_pivot; } - - -public: - void initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher); - - -private: - Logger& m_logger; - - AudioFeed& m_audio; - VideoFeed& m_video; - const StreamHistorySession& m_history; - - VideoOverlay& m_overlay; - - Pimpl m_video_pivot; - Pimpl m_audio_pivot; -}; - - - -} -#endif +/* Video Stream + * + * From: https://github.com/PokemonAutomation/ + * + * Represents a single video stream. Includes video, audio, as well + * as their inference pivots. Also includes a logger and the video overlay. + * + * This is the class that should be passed into inference modules as it + * provides all the information needed for inference. + * + * This class has been separated from ConsoleHandle which used to take this + * role. But 95% of the uses don't require the controller. And the controller + * is messy due to being heterogeneous. + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoStream_H +#define PokemonAutomation_VideoPipeline_VideoStream_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" + +namespace PokemonAutomation{ + +class CancellableScope; +class AsyncDispatcher; +class Logger; +class AudioFeed; +class VideoFeed; +class StreamHistorySession; +class VideoOverlay; +class VisualInferencePivot; +class AudioInferencePivot; + + +class VideoStream{ +public: + VideoStream(VideoStream&& x); + void operator=(VideoStream&& x) = delete; + VideoStream(const VideoStream& x) = delete; + void operator=(const VideoStream& x) = delete; + ~VideoStream(); + +public: + VideoStream( + Logger& logger, + AudioFeed& audio, + VideoFeed& video, + const StreamHistorySession& history, + VideoOverlay& overlay + ); + + // log(string-like msg, Color color = Color()) + // string-like can be const char* or std::string + template + void log(Args&&... args){ + m_logger.log(std::forward(args)...); + } + + Logger& logger(){ return m_logger; } + + AudioFeed& audio(){ return m_audio; } + VideoFeed& video(){ return m_video; } + + const StreamHistorySession& history() const{ return m_history; } + bool save_stream_history(const std::string& filename); + + VideoOverlay& overlay(){ return m_overlay; } + + VisualInferencePivot& video_inference_pivot(){ return *m_video_pivot; } + AudioInferencePivot& audio_inference_pivot(){ return *m_audio_pivot; } + + +public: + void initialize_inference_threads(CancellableScope& scope, AsyncDispatcher& dispatcher); + + +private: + Logger& m_logger; + + AudioFeed& m_audio; + VideoFeed& m_video; + const StreamHistorySession& m_history; + + VideoOverlay& m_overlay; + + Pimpl m_video_pivot; + Pimpl m_audio_pivot; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.cpp index 446a722af3..1ba2632586 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.cpp @@ -1,128 +1,128 @@ -/* Camera Implementations - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -//#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" -#include "CameraImplementations.h" - -//#include -//using std::cout; -//using std::endl; - -#if 0 -#elif QT_VERSION_MAJOR == 6 -#include "CameraWidgetQt6.h" -#if QT_VERSION_MINOR >= 5 -#include "CameraWidgetQt6.5.h" -#endif -#endif - - -namespace PokemonAutomation{ - - -struct CameraEntry{ - std::string slug; - std::string display; - std::unique_ptr backend; - - CameraEntry( - std::string p_slug, - std::string p_display, - std::unique_ptr p_backend - ) - : slug(std::move(p_slug)) - , display(std::move(p_display)) - , backend(std::move(p_backend)) - {} -}; - - -struct CameraBackends{ - static const CameraBackends& instance(){ - static CameraBackends backends; - return backends; - } - - CameraBackends(){ -#if QT_VERSION_MAJOR == 6 - m_backends.emplace_back( - "qt6-QVideoSink", "Qt6: QVideoSink", - std::make_unique() - ); -#endif -#if QT_VERSION_MAJOR == 6 && QT_VERSION_MINOR >= 5 - m_backends.emplace_back( - "qt6.5-QGraphicsScene", "Qt6.5: QGraphicsScene", - std::make_unique() - ); -#endif - - size_t items = 0; - for (const auto& item : m_backends){ - m_database.add(items, item.slug, item.display, true); - items++; - } - } - - std::vector m_backends; - IntegerEnumDropdownDatabase m_database; -}; - - - -VideoBackendOption::VideoBackendOption() - : IntegerEnumDropdownOption( - "Video Pipeline Backend:", - CameraBackends::instance().m_database, - LockMode::LOCK_WHILE_RUNNING, -#if 0 -#elif QT_VERSION_MAJOR == 6 -#if QT_VERSION_MINOR >= 5 - 1 -#else - 0 -#endif -#endif - ) -{} - - - - - -const CameraBackend& get_camera_backend(){ - size_t index = GlobalSettings::instance().VIDEO_PIPELINE->VIDEO_BACKEND.current_value(); - return *CameraBackends::instance().m_backends[index].backend; -} - - - -std::vector get_all_cameras(){ - const CameraBackend& backend = get_camera_backend(); -// global_logger_tagged().log("Start loading camera list..."); -// WallClock start = current_time(); - std::vector ret = backend.get_all_cameras(); -// WallClock end = current_time(); -// double seconds = std::chrono::duration_cast(end - start).count() / 1000.; -// global_logger_tagged().log("Done loading camera list... " + tostr_fixed(seconds, 3) + " seconds"); - return ret; -} -std::string get_camera_name(const CameraInfo& info){ - const CameraBackend& backend = get_camera_backend(); -// global_logger_tagged().log("Start reading camera name..."); -// WallClock start = current_time(); - std::string ret = backend.get_camera_name(info); -// WallClock end = current_time(); -// double seconds = std::chrono::duration_cast(end - start).count() / 1000.; -// global_logger_tagged().log("Done reading camera name... " + tostr_fixed(seconds, 3) + " seconds"); - return ret; -} - - -} +/* Camera Implementations + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" +#include "CameraImplementations.h" + +//#include +//using std::cout; +//using std::endl; + +#if 0 +#elif QT_VERSION_MAJOR == 6 +#include "CameraWidgetQt6.h" +#if QT_VERSION_MINOR >= 5 +#include "CameraWidgetQt6.5.h" +#endif +#endif + + +namespace PokemonAutomation{ + + +struct CameraEntry{ + std::string slug; + std::string display; + std::unique_ptr backend; + + CameraEntry( + std::string p_slug, + std::string p_display, + std::unique_ptr p_backend + ) + : slug(std::move(p_slug)) + , display(std::move(p_display)) + , backend(std::move(p_backend)) + {} +}; + + +struct CameraBackends{ + static const CameraBackends& instance(){ + static CameraBackends backends; + return backends; + } + + CameraBackends(){ +#if QT_VERSION_MAJOR == 6 + m_backends.emplace_back( + "qt6-QVideoSink", "Qt6: QVideoSink", + std::make_unique() + ); +#endif +#if QT_VERSION_MAJOR == 6 && QT_VERSION_MINOR >= 5 + m_backends.emplace_back( + "qt6.5-QGraphicsScene", "Qt6.5: QGraphicsScene", + std::make_unique() + ); +#endif + + size_t items = 0; + for (const auto& item : m_backends){ + m_database.add(items, item.slug, item.display, true); + items++; + } + } + + std::vector m_backends; + IntegerEnumDropdownDatabase m_database; +}; + + + +VideoBackendOption::VideoBackendOption() + : IntegerEnumDropdownOption( + "Video Pipeline Backend:", + CameraBackends::instance().m_database, + LockMode::LOCK_WHILE_RUNNING, +#if 0 +#elif QT_VERSION_MAJOR == 6 +#if QT_VERSION_MINOR >= 5 + 1 +#else + 0 +#endif +#endif + ) +{} + + + + + +const CameraBackend& get_camera_backend(){ + size_t index = GlobalSettings::instance().VIDEO_PIPELINE->VIDEO_BACKEND.current_value(); + return *CameraBackends::instance().m_backends[index].backend; +} + + + +std::vector get_all_cameras(){ + const CameraBackend& backend = get_camera_backend(); +// global_logger_tagged().log("Start loading camera list..."); +// WallClock start = current_time(); + std::vector ret = backend.get_all_cameras(); +// WallClock end = current_time(); +// double seconds = std::chrono::duration_cast(end - start).count() / 1000.; +// global_logger_tagged().log("Done loading camera list... " + tostr_fixed(seconds, 3) + " seconds"); + return ret; +} +std::string get_camera_name(const CameraInfo& info){ + const CameraBackend& backend = get_camera_backend(); +// global_logger_tagged().log("Start reading camera name..."); +// WallClock start = current_time(); + std::string ret = backend.get_camera_name(info); +// WallClock end = current_time(); +// double seconds = std::chrono::duration_cast(end - start).count() / 1000.; +// global_logger_tagged().log("Done reading camera name... " + tostr_fixed(seconds, 3) + " seconds"); + return ret; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.h index 2f19b14a6d..8eb4928297 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraImplementations.h @@ -1,52 +1,52 @@ -/* Camera Implementations - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_CameraImplementations_H -#define PokemonAutomation_VideoPipeline_CameraImplementations_H - -#include -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" -#include "CommonFramework/VideoPipeline/CameraInfo.h" - -namespace PokemonAutomation{ - - -class VideoBackendOption : public IntegerEnumDropdownOption{ -public: - VideoBackendOption(); -}; - - - -class CameraBackend{ -public: - virtual ~CameraBackend() = default; - - virtual std::vector get_all_cameras() const = 0; - virtual std::string get_camera_name(const CameraInfo& info) const = 0; - - virtual std::unique_ptr make_video_source( - Logger& logger, - const CameraInfo& info, - Resolution resolution - ) const = 0; -}; - - -const CameraBackend& get_camera_backend(); - -std::vector get_all_cameras(); -std::string get_camera_name(const CameraInfo& info); - - - - - - -} -#endif +/* Camera Implementations + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_CameraImplementations_H +#define PokemonAutomation_VideoPipeline_CameraImplementations_H + +#include +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" +#include "CommonFramework/VideoPipeline/CameraInfo.h" + +namespace PokemonAutomation{ + + +class VideoBackendOption : public IntegerEnumDropdownOption{ +public: + VideoBackendOption(); +}; + + + +class CameraBackend{ +public: + virtual ~CameraBackend() = default; + + virtual std::vector get_all_cameras() const = 0; + virtual std::string get_camera_name(const CameraInfo& info) const = 0; + + virtual std::unique_ptr make_video_source( + Logger& logger, + const CameraInfo& info, + Resolution resolution + ) const = 0; +}; + + +const CameraBackend& get_camera_backend(); + +std::vector get_all_cameras(); +std::string get_camera_name(const CameraInfo& info); + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp index 7a49e6d485..f42aa3dbe5 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.cpp @@ -1,315 +1,315 @@ -/* Camera Widget (Qt6.5) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if QT_VERSION_MAJOR == 6 && QT_VERSION_MINOR >= 5 - -#include -#include -//#include -#include -#include -#include -#include -#include -#include -//#include "Common/Cpp/Exceptions.h" -//#include "Common/Cpp/Time.h" -//#include "Common/Cpp/PrettyPrint.h" -#include "VideoFrameQt.h" -#include "MediaServicesQt6.h" -#include "CameraWidgetQt6.5.h" - -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace CameraQt65QMediaCaptureSession{ - - - - - - -std::vector CameraBackend::get_all_cameras() const{ -#if 1 - const auto cameras = GlobalMediaServices::instance().get_all_cameras(); -#else - const auto cameras = QMediaDevices::videoInputs(); -#endif - std::vector ret; - for (const auto& info : cameras){ - ret.emplace_back(info.id().toStdString()); - } - return ret; -} -std::string CameraBackend::get_camera_name(const CameraInfo& info) const{ -#if 1 - const auto cameras = GlobalMediaServices::instance().get_all_cameras(); -#else - const auto cameras = QMediaDevices::videoInputs(); -#endif - for (const auto& camera : cameras){ - if (camera.id().toStdString() == info.device_name()){ - return camera.description().toStdString(); - } - } - std::cout << "Error: no such camera for CameraInfo: " << info.device_name() << std::endl; - return ""; -} -std::unique_ptr CameraBackend::make_video_source( - Logger& logger, - const CameraInfo& info, - Resolution resolution -) const{ - return std::make_unique(logger, info, resolution); -} - - - - - - - -CameraVideoSource::~CameraVideoSource(){ - if (!m_capture_session){ - return; - } - try{ - m_logger.log("Stopping Camera..."); - }catch (...){} - - m_camera->stop(); - m_capture_session.reset(); - m_camera.reset(); -} -CameraVideoSource::CameraVideoSource( - Logger& logger, - const CameraInfo& info, - Resolution desired_resolution -) - : VideoSource(true) - , m_logger(logger) - , m_last_image_timestamp(WallClock::min()) - , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) - , m_last_frame_seqnum(0) -{ - if (!info){ - return; - } - m_logger.log("Starting Camera: Backend = CameraQt65QMediaCaptureSession"); - - auto cameras = QMediaDevices::videoInputs(); - const QCameraDevice* device = nullptr; - for (const auto& camera : cameras){ - if (camera.id().toStdString() == info.device_name()){ - device = &camera; - break; - } - } - if (device == nullptr){ - m_logger.log("Camera not found: " + info.device_name(), COLOR_RED); - return; - } - m_logger.log("Camera: " + device->description().toStdString()); - - QList formats = device->videoFormats(); - if (formats.empty()){ - m_logger.log("No usable resolutions: " + device->description().toStdString(), COLOR_RED); - return; - } - - std::map resolution_map; - for (const QCameraFormat& format : formats){ - QSize resolution = format.resolution(); - resolution_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(resolution.width(), resolution.height()), - std::forward_as_tuple(&format) - ); - } - - const QCameraFormat* format = nullptr; - m_resolutions.clear(); - for (const auto& res : resolution_map){ - m_resolutions.emplace_back(res.first); - if (res.first == desired_resolution){ - format = res.second; - } - } - if (format == nullptr){ - format = resolution_map.rbegin()->second; - } - - QSize size = format->resolution(); - m_resolution = Resolution(size.width(), size.height()); - m_logger.log("Resolution: " + m_resolution.to_string()); - - m_camera.reset(new QCamera(*device)); - m_camera->setCameraFormat(*format); - - m_capture_session.reset(new QMediaCaptureSession()); - m_capture_session->setCamera(m_camera.get()); - - connect(m_camera.get(), &QCamera::errorOccurred, this, [&](){ - if (m_camera->error() == QCamera::NoError){ - return; - } - m_logger.log("QCamera error: " + m_camera->errorString().toStdString(), COLOR_RED); - }); - - m_camera->start(); -} - - -void CameraVideoSource::set_video_output(QGraphicsVideoItem& item){ - if (m_capture_session == nullptr){ - return; - } - if (m_capture_session->videoSink() == item.videoSink()){ - return; - } - m_capture_session->setVideoOutput(&item); - - connect( - item.videoSink(), &QVideoSink::videoFrameChanged, - m_camera.get(), [&](const QVideoFrame& frame){ - // This will be on the main thread. So we waste as little time as - // possible. Shallow-copy the frame, update the listeners, and - // return immediately to unblock the main thread. - - WallClock now = current_time(); - { - WriteSpinLock lg(m_frame_lock); - - // Skip duplicate frames. - if (frame.startTime() != -1 && frame.startTime() <= m_last_frame.startTime()){ - return; - } - - m_last_frame = frame; - m_last_frame_timestamp = now; - uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - seqnum++; - m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); - } - report_source_frame(std::make_shared(now, frame)); - }, - Qt::DirectConnection - ); -} - - - - - -VideoSnapshot CameraVideoSource::snapshot(){ - // This will be coming in from random threads. (not the main thread) - // So we efficiently grab the last frame to unblock the main thread. - // Then we can do any expensive post-processing as needed. - - std::lock_guard lg(m_cache_lock); - - // Check the cached image frame. If it's not stale, return it immediately. - uint64_t frame_seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - if (!m_last_image.isNull() && m_last_image_seqnum == frame_seqnum){ - return VideoSnapshot(m_last_image, m_last_image_timestamp); - } - - // Cached image is stale. Grab the latest frame. - QVideoFrame frame; - WallClock frame_timestamp; - { - ReadSpinLock lg0(m_frame_lock); - frame_seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - frame = m_last_frame; - frame_timestamp = m_last_frame_timestamp; - } - - if (!frame.isValid()){ - m_logger.log("QVideoFrame is null.", COLOR_RED); - return VideoSnapshot(); - } - - // Converting the QVideoFrame to QImage is expensive. Time it and - // report performance. - WallClock time0 = current_time(); - - QImage image = frame.toImage(); - QImage::Format format = image.format(); - if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ - image = image.convertToFormat(QImage::Format_ARGB32); - } - - WallClock time1 = current_time(); - const int64_t duration = std::chrono::duration_cast(time1 - time0).count(); - m_stats_conversion.report_data(m_logger, uint32_t(duration)); - - // Update the cached image. - m_last_image = std::move(image); - m_last_image_timestamp = frame_timestamp; - m_last_image_seqnum = frame_seqnum; - - return VideoSnapshot(m_last_image, m_last_image_timestamp); -} - -QWidget* CameraVideoSource::make_display_QtWidget(QWidget* parent){ - return new CameraVideoDisplay(parent, *this); -} - - - - - - - - -CameraVideoDisplay::CameraVideoDisplay(QWidget* parent, CameraVideoSource& source) - : QWidget(parent) - , m_source(source) - , m_view(new StaticQGraphicsView(this)) - , m_sanitizer("CameraVideoDisplay") -{ - this->setMinimumSize(80, 45); - m_view->setFixedSize(this->size()); - m_view->setScene(&m_scene); - m_video.setSize(this->size()); - m_scene.setSceneRect(QRectF(QPointF(0, 0), this->size())); - m_scene.addItem(&m_video); - source.set_video_output(m_video); - - connect( - &m_scene, &QGraphicsScene::changed, - this, [&](const QList&){ - auto scope_check = m_sanitizer.check_scope(); - m_source.report_rendered_frame(current_time()); - } - ); -} -void CameraVideoDisplay::resizeEvent(QResizeEvent* event){ - auto scope_check = m_sanitizer.check_scope(); - m_view->setFixedSize(this->size()); - m_scene.setSceneRect(QRectF(QPointF(0, 0), this->size())); - m_video.setSize(this->size()); -} - - - - - - - - - - - - - - - -} -} -#endif +/* Camera Widget (Qt6.5) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if QT_VERSION_MAJOR == 6 && QT_VERSION_MINOR >= 5 + +#include +#include +//#include +#include +#include +#include +#include +#include +#include +//#include "Common/Cpp/Exceptions.h" +//#include "Common/Cpp/Time.h" +//#include "Common/Cpp/PrettyPrint.h" +#include "VideoFrameQt.h" +#include "MediaServicesQt6.h" +#include "CameraWidgetQt6.5.h" + +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace CameraQt65QMediaCaptureSession{ + + + + + + +std::vector CameraBackend::get_all_cameras() const{ +#if 1 + const auto cameras = GlobalMediaServices::instance().get_all_cameras(); +#else + const auto cameras = QMediaDevices::videoInputs(); +#endif + std::vector ret; + for (const auto& info : cameras){ + ret.emplace_back(info.id().toStdString()); + } + return ret; +} +std::string CameraBackend::get_camera_name(const CameraInfo& info) const{ +#if 1 + const auto cameras = GlobalMediaServices::instance().get_all_cameras(); +#else + const auto cameras = QMediaDevices::videoInputs(); +#endif + for (const auto& camera : cameras){ + if (camera.id().toStdString() == info.device_name()){ + return camera.description().toStdString(); + } + } + std::cout << "Error: no such camera for CameraInfo: " << info.device_name() << std::endl; + return ""; +} +std::unique_ptr CameraBackend::make_video_source( + Logger& logger, + const CameraInfo& info, + Resolution resolution +) const{ + return std::make_unique(logger, info, resolution); +} + + + + + + + +CameraVideoSource::~CameraVideoSource(){ + if (!m_capture_session){ + return; + } + try{ + m_logger.log("Stopping Camera..."); + }catch (...){} + + m_camera->stop(); + m_capture_session.reset(); + m_camera.reset(); +} +CameraVideoSource::CameraVideoSource( + Logger& logger, + const CameraInfo& info, + Resolution desired_resolution +) + : VideoSource(true) + , m_logger(logger) + , m_last_image_timestamp(WallClock::min()) + , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) + , m_last_frame_seqnum(0) +{ + if (!info){ + return; + } + m_logger.log("Starting Camera: Backend = CameraQt65QMediaCaptureSession"); + + auto cameras = QMediaDevices::videoInputs(); + const QCameraDevice* device = nullptr; + for (const auto& camera : cameras){ + if (camera.id().toStdString() == info.device_name()){ + device = &camera; + break; + } + } + if (device == nullptr){ + m_logger.log("Camera not found: " + info.device_name(), COLOR_RED); + return; + } + m_logger.log("Camera: " + device->description().toStdString()); + + QList formats = device->videoFormats(); + if (formats.empty()){ + m_logger.log("No usable resolutions: " + device->description().toStdString(), COLOR_RED); + return; + } + + std::map resolution_map; + for (const QCameraFormat& format : formats){ + QSize resolution = format.resolution(); + resolution_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(resolution.width(), resolution.height()), + std::forward_as_tuple(&format) + ); + } + + const QCameraFormat* format = nullptr; + m_resolutions.clear(); + for (const auto& res : resolution_map){ + m_resolutions.emplace_back(res.first); + if (res.first == desired_resolution){ + format = res.second; + } + } + if (format == nullptr){ + format = resolution_map.rbegin()->second; + } + + QSize size = format->resolution(); + m_resolution = Resolution(size.width(), size.height()); + m_logger.log("Resolution: " + m_resolution.to_string()); + + m_camera.reset(new QCamera(*device)); + m_camera->setCameraFormat(*format); + + m_capture_session.reset(new QMediaCaptureSession()); + m_capture_session->setCamera(m_camera.get()); + + connect(m_camera.get(), &QCamera::errorOccurred, this, [&](){ + if (m_camera->error() == QCamera::NoError){ + return; + } + m_logger.log("QCamera error: " + m_camera->errorString().toStdString(), COLOR_RED); + }); + + m_camera->start(); +} + + +void CameraVideoSource::set_video_output(QGraphicsVideoItem& item){ + if (m_capture_session == nullptr){ + return; + } + if (m_capture_session->videoSink() == item.videoSink()){ + return; + } + m_capture_session->setVideoOutput(&item); + + connect( + item.videoSink(), &QVideoSink::videoFrameChanged, + m_camera.get(), [&](const QVideoFrame& frame){ + // This will be on the main thread. So we waste as little time as + // possible. Shallow-copy the frame, update the listeners, and + // return immediately to unblock the main thread. + + WallClock now = current_time(); + { + WriteSpinLock lg(m_frame_lock); + + // Skip duplicate frames. + if (frame.startTime() != -1 && frame.startTime() <= m_last_frame.startTime()){ + return; + } + + m_last_frame = frame; + m_last_frame_timestamp = now; + uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); + seqnum++; + m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); + } + report_source_frame(std::make_shared(now, frame)); + }, + Qt::DirectConnection + ); +} + + + + + +VideoSnapshot CameraVideoSource::snapshot(){ + // This will be coming in from random threads. (not the main thread) + // So we efficiently grab the last frame to unblock the main thread. + // Then we can do any expensive post-processing as needed. + + std::lock_guard lg(m_cache_lock); + + // Check the cached image frame. If it's not stale, return it immediately. + uint64_t frame_seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); + if (!m_last_image.isNull() && m_last_image_seqnum == frame_seqnum){ + return VideoSnapshot(m_last_image, m_last_image_timestamp); + } + + // Cached image is stale. Grab the latest frame. + QVideoFrame frame; + WallClock frame_timestamp; + { + ReadSpinLock lg0(m_frame_lock); + frame_seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); + frame = m_last_frame; + frame_timestamp = m_last_frame_timestamp; + } + + if (!frame.isValid()){ + m_logger.log("QVideoFrame is null.", COLOR_RED); + return VideoSnapshot(); + } + + // Converting the QVideoFrame to QImage is expensive. Time it and + // report performance. + WallClock time0 = current_time(); + + QImage image = frame.toImage(); + QImage::Format format = image.format(); + if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ + image = image.convertToFormat(QImage::Format_ARGB32); + } + + WallClock time1 = current_time(); + const int64_t duration = std::chrono::duration_cast(time1 - time0).count(); + m_stats_conversion.report_data(m_logger, uint32_t(duration)); + + // Update the cached image. + m_last_image = std::move(image); + m_last_image_timestamp = frame_timestamp; + m_last_image_seqnum = frame_seqnum; + + return VideoSnapshot(m_last_image, m_last_image_timestamp); +} + +QWidget* CameraVideoSource::make_display_QtWidget(QWidget* parent){ + return new CameraVideoDisplay(parent, *this); +} + + + + + + + + +CameraVideoDisplay::CameraVideoDisplay(QWidget* parent, CameraVideoSource& source) + : QWidget(parent) + , m_source(source) + , m_view(new StaticQGraphicsView(this)) + , m_sanitizer("CameraVideoDisplay") +{ + this->setMinimumSize(80, 45); + m_view->setFixedSize(this->size()); + m_view->setScene(&m_scene); + m_video.setSize(this->size()); + m_scene.setSceneRect(QRectF(QPointF(0, 0), this->size())); + m_scene.addItem(&m_video); + source.set_video_output(m_video); + + connect( + &m_scene, &QGraphicsScene::changed, + this, [&](const QList&){ + auto scope_check = m_sanitizer.check_scope(); + m_source.report_rendered_frame(current_time()); + } + ); +} +void CameraVideoDisplay::resizeEvent(QResizeEvent* event){ + auto scope_check = m_sanitizer.check_scope(); + m_view->setFixedSize(this->size()); + m_scene.setSceneRect(QRectF(QPointF(0, 0), this->size())); + m_video.setSize(this->size()); +} + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h index 2df4180a0a..5273ef0172 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h @@ -1,177 +1,177 @@ -/* Camera Widget (Qt6.5) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_Qt65VideoWidget_H -#define PokemonAutomation_VideoPipeline_Qt65VideoWidget_H - -#include -#if QT_VERSION_MAJOR == 6 - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoSource.h" -#include "CommonFramework/VideoPipeline/CameraInfo.h" -#include "CameraImplementations.h" - -//#include -//using std::cout; -//using std::endl; - -class QCamera; -class QVideoSink; - -namespace PokemonAutomation{ -namespace CameraQt65QMediaCaptureSession{ - -class VideoDisplayWidget; - - -class CameraBackend : public PokemonAutomation::CameraBackend{ -public: - virtual std::vector get_all_cameras() const override; - virtual std::string get_camera_name(const CameraInfo& info) const override; - - virtual std::unique_ptr make_video_source( - Logger& logger, - const CameraInfo& info, - Resolution resolution - ) const override; -}; - - -class StaticQGraphicsView : public QGraphicsView{ -public: - StaticQGraphicsView(QWidget* parent) - : QGraphicsView(parent) - { - setContentsMargins(QMargins(0, 0, 0, 0)); - setFrameShape(QFrame::NoFrame); - setStyleSheet("QGraphicsView { border-style: none; }"); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setFocusPolicy(Qt::FocusPolicy::NoFocus); - } - - virtual void wheelEvent(QWheelEvent* e) override{ - QFrame::wheelEvent(e); - } - virtual void resizeEvent(QResizeEvent* e) override{ - QFrame::resizeEvent(e); - } - - // QGraphicsView doesn't like to propagate mouse events. - // https://forum.qt.io/topic/152138/struggling-with-mouse-events/2 - virtual void mousePressEvent(QMouseEvent* event) override{ - QWidget::mousePressEvent(event); - } - virtual void mouseReleaseEvent(QMouseEvent* event) override{ - QWidget::mouseReleaseEvent(event); - } - virtual void mouseMoveEvent(QMouseEvent* event) override{ - QWidget::mouseMoveEvent(event); - } - -}; - - -class CameraVideoSource : public QObject, public VideoSource{ -public: - virtual ~CameraVideoSource(); - CameraVideoSource( - Logger& logger, - const CameraInfo& info, - Resolution desired_resolution - ); - - virtual Resolution current_resolution() const override{ - return m_resolution; - } - virtual const std::vector& supported_resolutions() const override{ - return m_resolutions; - } - - virtual VideoSnapshot snapshot() override; - - virtual QWidget* make_display_QtWidget(QWidget* parent) override; - -private: - void set_video_output(QGraphicsVideoItem& item); - - -private: - friend class CameraVideoDisplay; - - Logger& m_logger; - Resolution m_resolution; - - std::unique_ptr m_camera; - std::unique_ptr m_video_sink; - std::unique_ptr m_capture_session; - - std::vector m_resolutions; - -private: - // Last Cached Image: All accesses must be under this lock. - - mutable std::mutex m_cache_lock; - - QImage m_last_image; - WallClock m_last_image_timestamp; - uint64_t m_last_image_seqnum = 0; - - PeriodicStatsReporterI32 m_stats_conversion; - -private: - // Last Frame: All accesses must be under this lock. - // These will be updated very rapidly by the main thread. - // Holding the frame lock will block the main thread. - // So accessors should minimize the time they hold the frame lock. - - mutable SpinLock m_frame_lock; - - QVideoFrame m_last_frame; - WallClock m_last_frame_timestamp; - std::atomic m_last_frame_seqnum; - -}; - - -class CameraVideoDisplay : public QWidget{ -public: - CameraVideoDisplay(QWidget* parent, CameraVideoSource& source); - -private: - virtual void resizeEvent(QResizeEvent* event) override; - -private: - CameraVideoSource& m_source; - - StaticQGraphicsView* m_view; - QGraphicsScene m_scene; - QGraphicsVideoItem m_video; - - LifetimeSanitizer m_sanitizer; -}; - - - - - - -} -} -#endif -#endif +/* Camera Widget (Qt6.5) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_Qt65VideoWidget_H +#define PokemonAutomation_VideoPipeline_Qt65VideoWidget_H + +#include +#if QT_VERSION_MAJOR == 6 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoSource.h" +#include "CommonFramework/VideoPipeline/CameraInfo.h" +#include "CameraImplementations.h" + +//#include +//using std::cout; +//using std::endl; + +class QCamera; +class QVideoSink; + +namespace PokemonAutomation{ +namespace CameraQt65QMediaCaptureSession{ + +class VideoDisplayWidget; + + +class CameraBackend : public PokemonAutomation::CameraBackend{ +public: + virtual std::vector get_all_cameras() const override; + virtual std::string get_camera_name(const CameraInfo& info) const override; + + virtual std::unique_ptr make_video_source( + Logger& logger, + const CameraInfo& info, + Resolution resolution + ) const override; +}; + + +class StaticQGraphicsView : public QGraphicsView{ +public: + StaticQGraphicsView(QWidget* parent) + : QGraphicsView(parent) + { + setContentsMargins(QMargins(0, 0, 0, 0)); + setFrameShape(QFrame::NoFrame); + setStyleSheet("QGraphicsView { border-style: none; }"); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setFocusPolicy(Qt::FocusPolicy::NoFocus); + } + + virtual void wheelEvent(QWheelEvent* e) override{ + QFrame::wheelEvent(e); + } + virtual void resizeEvent(QResizeEvent* e) override{ + QFrame::resizeEvent(e); + } + + // QGraphicsView doesn't like to propagate mouse events. + // https://forum.qt.io/topic/152138/struggling-with-mouse-events/2 + virtual void mousePressEvent(QMouseEvent* event) override{ + QWidget::mousePressEvent(event); + } + virtual void mouseReleaseEvent(QMouseEvent* event) override{ + QWidget::mouseReleaseEvent(event); + } + virtual void mouseMoveEvent(QMouseEvent* event) override{ + QWidget::mouseMoveEvent(event); + } + +}; + + +class CameraVideoSource : public QObject, public VideoSource{ +public: + virtual ~CameraVideoSource(); + CameraVideoSource( + Logger& logger, + const CameraInfo& info, + Resolution desired_resolution + ); + + virtual Resolution current_resolution() const override{ + return m_resolution; + } + virtual const std::vector& supported_resolutions() const override{ + return m_resolutions; + } + + virtual VideoSnapshot snapshot() override; + + virtual QWidget* make_display_QtWidget(QWidget* parent) override; + +private: + void set_video_output(QGraphicsVideoItem& item); + + +private: + friend class CameraVideoDisplay; + + Logger& m_logger; + Resolution m_resolution; + + std::unique_ptr m_camera; + std::unique_ptr m_video_sink; + std::unique_ptr m_capture_session; + + std::vector m_resolutions; + +private: + // Last Cached Image: All accesses must be under this lock. + + mutable std::mutex m_cache_lock; + + QImage m_last_image; + WallClock m_last_image_timestamp; + uint64_t m_last_image_seqnum = 0; + + PeriodicStatsReporterI32 m_stats_conversion; + +private: + // Last Frame: All accesses must be under this lock. + // These will be updated very rapidly by the main thread. + // Holding the frame lock will block the main thread. + // So accessors should minimize the time they hold the frame lock. + + mutable SpinLock m_frame_lock; + + QVideoFrame m_last_frame; + WallClock m_last_frame_timestamp; + std::atomic m_last_frame_seqnum; + +}; + + +class CameraVideoDisplay : public QWidget{ +public: + CameraVideoDisplay(QWidget* parent, CameraVideoSource& source); + +private: + virtual void resizeEvent(QResizeEvent* event) override; + +private: + CameraVideoSource& m_source; + + StaticQGraphicsView* m_view; + QGraphicsScene m_scene; + QGraphicsVideoItem m_video; + + LifetimeSanitizer m_sanitizer; +}; + + + + + + +} +} +#endif +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp index 1bb3632df2..d5e5749674 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.cpp @@ -1,287 +1,287 @@ -/* Camera Widget (Qt6) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if QT_VERSION_MAJOR == 6 - -#include -#include -#include -#include -#include -#include -//#include "Common/Cpp/Exceptions.h" -//#include "Common/Cpp/Time.h" -#include "VideoFrameQt.h" -#include "MediaServicesQt6.h" -#include "CameraWidgetQt6.h" - -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace CameraQt6QVideoSink{ - - - -std::vector CameraBackend::get_all_cameras() const{ -#if 1 - const auto cameras = GlobalMediaServices::instance().get_all_cameras(); -#else - const auto cameras = QMediaDevices::videoInputs(); -#endif - std::vector ret; - for (const auto& info : cameras){ - ret.emplace_back(info.id().toStdString()); - } - return ret; -} -std::string CameraBackend::get_camera_name(const CameraInfo& info) const{ -#if 1 - const auto cameras = GlobalMediaServices::instance().get_all_cameras(); -#else - const auto cameras = QMediaDevices::videoInputs(); -#endif - for (const auto& camera : cameras){ - if (camera.id().toStdString() == info.device_name()){ - return camera.description().toStdString(); - } - } - std::cout << "Error: no such camera for CameraInfo: " << info.device_name() << std::endl; - return ""; -} -std::unique_ptr CameraBackend::make_video_source( - Logger& logger, - const CameraInfo& info, - Resolution resolution -) const{ - return std::make_unique(logger, info, resolution); -} - - - - - - -CameraVideoSource::~CameraVideoSource(){ - if (!m_capture){ - return; - } - try{ - m_logger.log("Stopping Camera..."); - }catch (...){} - - m_camera->stop(); - m_capture.reset(); - m_video_sink.reset(); - m_camera.reset(); -} -CameraVideoSource::CameraVideoSource( - Logger& logger, - const CameraInfo& info, - Resolution desired_resolution -) - : VideoSource(true) - , m_logger(logger) - , m_last_image_timestamp(WallClock::min()) - , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) - , m_last_frame_seqnum(0) -{ - if (!info){ - return; - } - m_logger.log("Starting Camera: Backend = CameraQt6QVideoSink"); - - auto cameras = QMediaDevices::videoInputs(); - const QCameraDevice* device = nullptr; - for (const auto& camera : cameras){ - if (camera.id().toStdString() == info.device_name()){ - device = &camera; - break; - } - } - if (device == nullptr){ - m_logger.log("Camera not found: " + info.device_name(), COLOR_RED); - return; - } - - QList formats = device->videoFormats(); - if (formats.empty()){ - m_logger.log("No usable resolutions: " + device->description().toStdString(), COLOR_RED); - return; - } - - std::map resolution_map; - for (const QCameraFormat& format : formats){ - QSize resolution = format.resolution(); - resolution_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(resolution.width(), resolution.height()), - std::forward_as_tuple(&format) - ); - } - - const QCameraFormat* format = nullptr; - m_resolutions.clear(); - for (const auto& res : resolution_map){ - m_resolutions.emplace_back(res.first); - if (res.first == desired_resolution){ - format = res.second; - } - } - if (format == nullptr){ - format = resolution_map.rbegin()->second; - } - - QSize size = format->resolution(); - m_resolution = Resolution(size.width(), size.height()); - m_logger.log("Resolution: " + m_resolution.to_string()); - - m_camera.reset(new QCamera(*device)); - m_camera->setCameraFormat(*format); - m_video_sink.reset(new QVideoSink()); - m_capture.reset(new QMediaCaptureSession()); - m_capture->setCamera(m_camera.get()); - m_capture->setVideoSink(m_video_sink.get()); - - connect(m_camera.get(), &QCamera::errorOccurred, this, [&](){ - if (m_camera->error() != QCamera::NoError){ - m_logger.log("QCamera error: " + m_camera->errorString().toStdString()); - } - }); - connect( - m_video_sink.get(), &QVideoSink::videoFrameChanged, - m_camera.get(), [&](const QVideoFrame& frame){ - // This will be on the main thread. So we waste as little time as - // possible. Shallow-copy the frame, update the listeners, and - // return immediately to unblock the main thread. - - WallClock now = current_time(); - { - WriteSpinLock lg(m_frame_lock); -// cout << now << endl; - m_last_frame = frame; - m_last_frame_timestamp = now; - uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); - seqnum++; - m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); - } - report_source_frame(std::make_shared(now, frame)); - } - ); - - m_camera->start(); -} - -VideoSnapshot CameraVideoSource::snapshot(){ - // Prevent multiple concurrent screenshots from entering here. - std::lock_guard lg(m_snapshot_lock); - - if (m_camera == nullptr){ - return VideoSnapshot(); - } - - // Frame is already cached and is not stale. - QVideoFrame frame; - WallClock frame_timestamp; - uint64_t frame_seqnum; - { - SpinLockGuard lg0(m_frame_lock); - frame_seqnum = m_last_frame_seqnum; - if (!m_last_image.isNull() && m_last_image_seqnum == frame_seqnum){ - return VideoSnapshot(m_last_image, m_last_image_timestamp); - } - frame = m_last_frame; - frame_timestamp = m_last_frame_timestamp; - } - - if (!frame.isValid()){ - global_logger_tagged().log("QVideoFrame is null.", COLOR_RED); - return VideoSnapshot(); - } - - WallClock time0 = current_time(); - - QImage image = frame.toImage(); - QImage::Format format = image.format(); - if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ - image = image.convertToFormat(QImage::Format_ARGB32); - } - - // No lock needed here since this the only place that touches it. - m_last_image = std::move(image); - m_last_image_timestamp = frame_timestamp; - m_last_image_seqnum = frame_seqnum; - - WallClock time1 = current_time(); - const int64_t duration = std::chrono::duration_cast(time1 - time0).count(); - m_stats_conversion.report_data(m_logger, uint32_t(duration)); - - return VideoSnapshot(m_last_image, m_last_image_timestamp); -} - -QWidget* CameraVideoSource::make_display_QtWidget(QWidget* parent){ - return new CameraVideoDisplay(parent, *this); -} - - - - - -CameraVideoDisplay::~CameraVideoDisplay(){ - m_source.remove_source_frame_listener(*this); -} -CameraVideoDisplay::CameraVideoDisplay(QWidget* parent, CameraVideoSource& source) - : QWidget(parent) - , m_source(source) -{ - source.add_source_frame_listener(*this); -} -void CameraVideoDisplay::on_frame(std::shared_ptr frame){ - m_last_frame = frame; - this->update(); -} -void CameraVideoDisplay::paintEvent(QPaintEvent* event){ - QWidget::paintEvent(event); - - if (!m_last_frame){ - return; - } - - QVideoFrame frame = m_last_frame->frame; - if (!frame.isValid()){ - return; - } - - QRect rect(0, 0, this->width(), this->height()); - QVideoFrame::PaintOptions options; - QPainter painter(this); - - frame.paint(&painter, rect, options); - m_source.report_rendered_frame(current_time()); -} - - - - - - - - - - - - - - - - - - - -} -} -#endif +/* Camera Widget (Qt6) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if QT_VERSION_MAJOR == 6 + +#include +#include +#include +#include +#include +#include +//#include "Common/Cpp/Exceptions.h" +//#include "Common/Cpp/Time.h" +#include "VideoFrameQt.h" +#include "MediaServicesQt6.h" +#include "CameraWidgetQt6.h" + +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace CameraQt6QVideoSink{ + + + +std::vector CameraBackend::get_all_cameras() const{ +#if 1 + const auto cameras = GlobalMediaServices::instance().get_all_cameras(); +#else + const auto cameras = QMediaDevices::videoInputs(); +#endif + std::vector ret; + for (const auto& info : cameras){ + ret.emplace_back(info.id().toStdString()); + } + return ret; +} +std::string CameraBackend::get_camera_name(const CameraInfo& info) const{ +#if 1 + const auto cameras = GlobalMediaServices::instance().get_all_cameras(); +#else + const auto cameras = QMediaDevices::videoInputs(); +#endif + for (const auto& camera : cameras){ + if (camera.id().toStdString() == info.device_name()){ + return camera.description().toStdString(); + } + } + std::cout << "Error: no such camera for CameraInfo: " << info.device_name() << std::endl; + return ""; +} +std::unique_ptr CameraBackend::make_video_source( + Logger& logger, + const CameraInfo& info, + Resolution resolution +) const{ + return std::make_unique(logger, info, resolution); +} + + + + + + +CameraVideoSource::~CameraVideoSource(){ + if (!m_capture){ + return; + } + try{ + m_logger.log("Stopping Camera..."); + }catch (...){} + + m_camera->stop(); + m_capture.reset(); + m_video_sink.reset(); + m_camera.reset(); +} +CameraVideoSource::CameraVideoSource( + Logger& logger, + const CameraInfo& info, + Resolution desired_resolution +) + : VideoSource(true) + , m_logger(logger) + , m_last_image_timestamp(WallClock::min()) + , m_stats_conversion("ConvertFrame", "ms", 1000, std::chrono::seconds(10)) + , m_last_frame_seqnum(0) +{ + if (!info){ + return; + } + m_logger.log("Starting Camera: Backend = CameraQt6QVideoSink"); + + auto cameras = QMediaDevices::videoInputs(); + const QCameraDevice* device = nullptr; + for (const auto& camera : cameras){ + if (camera.id().toStdString() == info.device_name()){ + device = &camera; + break; + } + } + if (device == nullptr){ + m_logger.log("Camera not found: " + info.device_name(), COLOR_RED); + return; + } + + QList formats = device->videoFormats(); + if (formats.empty()){ + m_logger.log("No usable resolutions: " + device->description().toStdString(), COLOR_RED); + return; + } + + std::map resolution_map; + for (const QCameraFormat& format : formats){ + QSize resolution = format.resolution(); + resolution_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(resolution.width(), resolution.height()), + std::forward_as_tuple(&format) + ); + } + + const QCameraFormat* format = nullptr; + m_resolutions.clear(); + for (const auto& res : resolution_map){ + m_resolutions.emplace_back(res.first); + if (res.first == desired_resolution){ + format = res.second; + } + } + if (format == nullptr){ + format = resolution_map.rbegin()->second; + } + + QSize size = format->resolution(); + m_resolution = Resolution(size.width(), size.height()); + m_logger.log("Resolution: " + m_resolution.to_string()); + + m_camera.reset(new QCamera(*device)); + m_camera->setCameraFormat(*format); + m_video_sink.reset(new QVideoSink()); + m_capture.reset(new QMediaCaptureSession()); + m_capture->setCamera(m_camera.get()); + m_capture->setVideoSink(m_video_sink.get()); + + connect(m_camera.get(), &QCamera::errorOccurred, this, [&](){ + if (m_camera->error() != QCamera::NoError){ + m_logger.log("QCamera error: " + m_camera->errorString().toStdString()); + } + }); + connect( + m_video_sink.get(), &QVideoSink::videoFrameChanged, + m_camera.get(), [&](const QVideoFrame& frame){ + // This will be on the main thread. So we waste as little time as + // possible. Shallow-copy the frame, update the listeners, and + // return immediately to unblock the main thread. + + WallClock now = current_time(); + { + WriteSpinLock lg(m_frame_lock); +// cout << now << endl; + m_last_frame = frame; + m_last_frame_timestamp = now; + uint64_t seqnum = m_last_frame_seqnum.load(std::memory_order_relaxed); + seqnum++; + m_last_frame_seqnum.store(seqnum, std::memory_order_relaxed); + } + report_source_frame(std::make_shared(now, frame)); + } + ); + + m_camera->start(); +} + +VideoSnapshot CameraVideoSource::snapshot(){ + // Prevent multiple concurrent screenshots from entering here. + std::lock_guard lg(m_snapshot_lock); + + if (m_camera == nullptr){ + return VideoSnapshot(); + } + + // Frame is already cached and is not stale. + QVideoFrame frame; + WallClock frame_timestamp; + uint64_t frame_seqnum; + { + SpinLockGuard lg0(m_frame_lock); + frame_seqnum = m_last_frame_seqnum; + if (!m_last_image.isNull() && m_last_image_seqnum == frame_seqnum){ + return VideoSnapshot(m_last_image, m_last_image_timestamp); + } + frame = m_last_frame; + frame_timestamp = m_last_frame_timestamp; + } + + if (!frame.isValid()){ + global_logger_tagged().log("QVideoFrame is null.", COLOR_RED); + return VideoSnapshot(); + } + + WallClock time0 = current_time(); + + QImage image = frame.toImage(); + QImage::Format format = image.format(); + if (format != QImage::Format_ARGB32 && format != QImage::Format_RGB32){ + image = image.convertToFormat(QImage::Format_ARGB32); + } + + // No lock needed here since this the only place that touches it. + m_last_image = std::move(image); + m_last_image_timestamp = frame_timestamp; + m_last_image_seqnum = frame_seqnum; + + WallClock time1 = current_time(); + const int64_t duration = std::chrono::duration_cast(time1 - time0).count(); + m_stats_conversion.report_data(m_logger, uint32_t(duration)); + + return VideoSnapshot(m_last_image, m_last_image_timestamp); +} + +QWidget* CameraVideoSource::make_display_QtWidget(QWidget* parent){ + return new CameraVideoDisplay(parent, *this); +} + + + + + +CameraVideoDisplay::~CameraVideoDisplay(){ + m_source.remove_source_frame_listener(*this); +} +CameraVideoDisplay::CameraVideoDisplay(QWidget* parent, CameraVideoSource& source) + : QWidget(parent) + , m_source(source) +{ + source.add_source_frame_listener(*this); +} +void CameraVideoDisplay::on_frame(std::shared_ptr frame){ + m_last_frame = frame; + this->update(); +} +void CameraVideoDisplay::paintEvent(QPaintEvent* event){ + QWidget::paintEvent(event); + + if (!m_last_frame){ + return; + } + + QVideoFrame frame = m_last_frame->frame; + if (!frame.isValid()){ + return; + } + + QRect rect(0, 0, this->width(), this->height()); + QVideoFrame::PaintOptions options; + QPainter painter(this); + + frame.paint(&painter, rect, options); + m_source.report_rendered_frame(current_time()); +} + + + + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h index f48a6e3e12..b5bc15026b 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.h @@ -1,147 +1,147 @@ -/* Camera Widget (Qt6) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_Qt6VideoWidget_H -#define PokemonAutomation_VideoPipeline_Qt6VideoWidget_H - -#include -#if QT_VERSION_MAJOR == 6 - -#include -#include -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoSource.h" -#include "CommonFramework/VideoPipeline/CameraInfo.h" -#include "CameraImplementations.h" - -class QCamera; -class QVideoSink; - -namespace PokemonAutomation{ -namespace CameraQt6QVideoSink{ - - -class CameraBackend : public PokemonAutomation::CameraBackend{ -public: - virtual std::vector get_all_cameras() const override; - virtual std::string get_camera_name(const CameraInfo& info) const override; - - virtual std::unique_ptr make_video_source( - Logger& logger, - const CameraInfo& info, - Resolution resolution - ) const override; -}; - - - - - - - - -class CameraVideoSource : public QObject, public VideoSource{ -public: - virtual ~CameraVideoSource(); - CameraVideoSource( - Logger& logger, - const CameraInfo& info, - Resolution desired_resolution - ); - - virtual Resolution current_resolution() const override{ - return m_resolution; - } - virtual const std::vector& supported_resolutions() const override{ - return m_resolutions; - } - - virtual VideoSnapshot snapshot() override; - - virtual QWidget* make_display_QtWidget(QWidget* parent) override; - -private: -// void set_video_output(QGraphicsVideoItem& item); - - -private: - friend class CameraVideoDisplay; - - Logger& m_logger; - Resolution m_resolution; - - std::mutex m_snapshot_lock; - - std::unique_ptr m_camera; - std::unique_ptr m_video_sink; - std::unique_ptr m_capture; - - std::vector m_resolutions; - -private: - // Last Cached Image: All accesses must be under this lock. - - QImage m_last_image; - WallClock m_last_image_timestamp; - uint64_t m_last_image_seqnum = 0; - - PeriodicStatsReporterI32 m_stats_conversion; - - -private: - // Last Frame: All accesses must be under this lock. - // These will be updated very rapidly by the main thread. - // Holding the frame lock will block the main thread. - // So accessors should minimize the time they hold the frame lock. - - mutable SpinLock m_frame_lock; - - QVideoFrame m_last_frame; - WallClock m_last_frame_timestamp; - std::atomic m_last_frame_seqnum; - -}; - - -class CameraVideoDisplay : public QWidget, private VideoFrameListener{ -public: - ~CameraVideoDisplay(); - CameraVideoDisplay(QWidget* parent, CameraVideoSource& source); - -private: - virtual void on_frame(std::shared_ptr frame) override; - virtual void paintEvent(QPaintEvent* event) override; - -private: - CameraVideoSource& m_source; - std::shared_ptr m_last_frame; - - LifetimeSanitizer m_sanitizer; -}; - - - - - - - - - - - - - - - - -} -} -#endif -#endif +/* Camera Widget (Qt6) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_Qt6VideoWidget_H +#define PokemonAutomation_VideoPipeline_Qt6VideoWidget_H + +#include +#if QT_VERSION_MAJOR == 6 + +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoSource.h" +#include "CommonFramework/VideoPipeline/CameraInfo.h" +#include "CameraImplementations.h" + +class QCamera; +class QVideoSink; + +namespace PokemonAutomation{ +namespace CameraQt6QVideoSink{ + + +class CameraBackend : public PokemonAutomation::CameraBackend{ +public: + virtual std::vector get_all_cameras() const override; + virtual std::string get_camera_name(const CameraInfo& info) const override; + + virtual std::unique_ptr make_video_source( + Logger& logger, + const CameraInfo& info, + Resolution resolution + ) const override; +}; + + + + + + + + +class CameraVideoSource : public QObject, public VideoSource{ +public: + virtual ~CameraVideoSource(); + CameraVideoSource( + Logger& logger, + const CameraInfo& info, + Resolution desired_resolution + ); + + virtual Resolution current_resolution() const override{ + return m_resolution; + } + virtual const std::vector& supported_resolutions() const override{ + return m_resolutions; + } + + virtual VideoSnapshot snapshot() override; + + virtual QWidget* make_display_QtWidget(QWidget* parent) override; + +private: +// void set_video_output(QGraphicsVideoItem& item); + + +private: + friend class CameraVideoDisplay; + + Logger& m_logger; + Resolution m_resolution; + + std::mutex m_snapshot_lock; + + std::unique_ptr m_camera; + std::unique_ptr m_video_sink; + std::unique_ptr m_capture; + + std::vector m_resolutions; + +private: + // Last Cached Image: All accesses must be under this lock. + + QImage m_last_image; + WallClock m_last_image_timestamp; + uint64_t m_last_image_seqnum = 0; + + PeriodicStatsReporterI32 m_stats_conversion; + + +private: + // Last Frame: All accesses must be under this lock. + // These will be updated very rapidly by the main thread. + // Holding the frame lock will block the main thread. + // So accessors should minimize the time they hold the frame lock. + + mutable SpinLock m_frame_lock; + + QVideoFrame m_last_frame; + WallClock m_last_frame_timestamp; + std::atomic m_last_frame_seqnum; + +}; + + +class CameraVideoDisplay : public QWidget, private VideoFrameListener{ +public: + ~CameraVideoDisplay(); + CameraVideoDisplay(QWidget* parent, CameraVideoSource& source); + +private: + virtual void on_frame(std::shared_ptr frame) override; + virtual void paintEvent(QPaintEvent* event) override; + +private: + CameraVideoSource& m_source; + std::shared_ptr m_last_frame; + + LifetimeSanitizer m_sanitizer; +}; + + + + + + + + + + + + + + + + +} +} +#endif +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp index c811631c56..6c811d74da 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.cpp @@ -1,81 +1,81 @@ -/* Media Services (Qt6.5) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#if QT_VERSION_MAJOR == 6 - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Time.h" -#include "CommonFramework/Logging/Logger.h" -#include "MediaServicesQt6.h" - -namespace PokemonAutomation{ - - -GlobalMediaServices::~GlobalMediaServices(){ - { - std::lock_guard lg(m_sleep_lock); - m_stopping = true; - m_cv.notify_all(); - } - m_thread.join(); -} -GlobalMediaServices::GlobalMediaServices() - : m_thread(&GlobalMediaServices::thread_body, this) -{ - refresh_cameras(); - - m_media_devices.connect( - &m_media_devices, &QMediaDevices::videoInputsChanged, - this, [this]{ - std::lock_guard lg(m_sleep_lock); - m_refresh_cameras = true; - m_cv.notify_all(); - } - ); -} - - -void GlobalMediaServices::thread_body(){ - std::unique_lock lg(m_sleep_lock); - while (!m_stopping){ -// global_logger_tagged().log("GlobalMediaServices::thread_body() iteration", COLOR_CYAN); - if (m_refresh_cameras){ - refresh_cameras(); - } - m_cv.wait(lg); - } -} - - -void GlobalMediaServices::refresh_cameras(){ - try{ - global_logger_tagged().log("Start refreshing camera list...", COLOR_CYAN); - WallClock start = current_time(); - - QList cameras = QMediaDevices::videoInputs(); - { - WriteSpinLock lg(m_camera_lock); - m_cameras = std::move(cameras); - } - - WallClock end = current_time(); - double seconds = std::chrono::duration_cast(end - start).count() / 1000.; - global_logger_tagged().log("Done refreshing camera list... " + tostr_fixed(seconds, 3) + " seconds", COLOR_CYAN); - }catch (std::exception& e){ - global_logger_tagged().log( - std::string("Refreshing camera list returned exception: ") + e.what(), - COLOR_RED - ); - } - m_refresh_cameras = false; -} - - - - -} -#endif +/* Media Services (Qt6.5) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#if QT_VERSION_MAJOR == 6 + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/Logging/Logger.h" +#include "MediaServicesQt6.h" + +namespace PokemonAutomation{ + + +GlobalMediaServices::~GlobalMediaServices(){ + { + std::lock_guard lg(m_sleep_lock); + m_stopping = true; + m_cv.notify_all(); + } + m_thread.join(); +} +GlobalMediaServices::GlobalMediaServices() + : m_thread(&GlobalMediaServices::thread_body, this) +{ + refresh_cameras(); + + m_media_devices.connect( + &m_media_devices, &QMediaDevices::videoInputsChanged, + this, [this]{ + std::lock_guard lg(m_sleep_lock); + m_refresh_cameras = true; + m_cv.notify_all(); + } + ); +} + + +void GlobalMediaServices::thread_body(){ + std::unique_lock lg(m_sleep_lock); + while (!m_stopping){ +// global_logger_tagged().log("GlobalMediaServices::thread_body() iteration", COLOR_CYAN); + if (m_refresh_cameras){ + refresh_cameras(); + } + m_cv.wait(lg); + } +} + + +void GlobalMediaServices::refresh_cameras(){ + try{ + global_logger_tagged().log("Start refreshing camera list...", COLOR_CYAN); + WallClock start = current_time(); + + QList cameras = QMediaDevices::videoInputs(); + { + WriteSpinLock lg(m_camera_lock); + m_cameras = std::move(cameras); + } + + WallClock end = current_time(); + double seconds = std::chrono::duration_cast(end - start).count() / 1000.; + global_logger_tagged().log("Done refreshing camera list... " + tostr_fixed(seconds, 3) + " seconds", COLOR_CYAN); + }catch (std::exception& e){ + global_logger_tagged().log( + std::string("Refreshing camera list returned exception: ") + e.what(), + COLOR_RED + ); + } + m_refresh_cameras = false; +} + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h index a6c47bd1e6..149051799e 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/MediaServicesQt6.h @@ -1,59 +1,59 @@ -/* Media Services (Qt6.5) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_Qt65MediaServices_H -#define PokemonAutomation_VideoPipeline_Qt65MediaServices_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - - -class GlobalMediaServices : public QObject{ -public: - static GlobalMediaServices& instance(){ - static GlobalMediaServices self; - return self; - } - - QList get_all_cameras(){ - ReadSpinLock lg(m_camera_lock); - return m_cameras; - } - -private: - ~GlobalMediaServices(); - GlobalMediaServices(); - - void thread_body(); - - void refresh_cameras(); - -private: - QMediaDevices m_media_devices; - - std::mutex m_sleep_lock; - std::condition_variable m_cv; - - bool m_stopping = false; - bool m_refresh_cameras = false; - - SpinLock m_camera_lock; - QList m_cameras; - - std::thread m_thread; -}; - - - - -} -#endif +/* Media Services (Qt6.5) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_Qt65MediaServices_H +#define PokemonAutomation_VideoPipeline_Qt65MediaServices_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + + +class GlobalMediaServices : public QObject{ +public: + static GlobalMediaServices& instance(){ + static GlobalMediaServices self; + return self; + } + + QList get_all_cameras(){ + ReadSpinLock lg(m_camera_lock); + return m_cameras; + } + +private: + ~GlobalMediaServices(); + GlobalMediaServices(); + + void thread_body(); + + void refresh_cameras(); + +private: + QMediaDevices m_media_devices; + + std::mutex m_sleep_lock; + std::condition_variable m_cv; + + bool m_stopping = false; + bool m_refresh_cameras = false; + + SpinLock m_camera_lock; + QList m_cameras; + + std::thread m_thread; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h index f9bb51d896..4f798c0b6c 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Backends/VideoFrameQt.h @@ -1,44 +1,44 @@ -/* Video Frame - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoFrame_H -#define PokemonAutomation_VideoFrame_H - -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -class VideoFrame{ -public: - WallClock timestamp; - QVideoFrame frame; - - VideoFrame(VideoFrame&&) = default; - VideoFrame& operator=(VideoFrame&&) = default; - VideoFrame(const VideoFrame&) = delete; - void operator=(const VideoFrame&) = delete; - - VideoFrame() - : timestamp(WallClock::min()) - {} - VideoFrame(WallClock p_timestamp, QVideoFrame p_frame) - : timestamp(p_timestamp) - , frame(std::move(p_frame)) - {} - - void clear(){ - frame = QVideoFrame(); - } - bool is_valid() const{ - return frame.isValid(); - } -}; - - -} -#endif +/* Video Frame + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoFrame_H +#define PokemonAutomation_VideoFrame_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +class VideoFrame{ +public: + WallClock timestamp; + QVideoFrame frame; + + VideoFrame(VideoFrame&&) = default; + VideoFrame& operator=(VideoFrame&&) = default; + VideoFrame(const VideoFrame&) = delete; + void operator=(const VideoFrame&) = delete; + + VideoFrame() + : timestamp(WallClock::min()) + {} + VideoFrame(WallClock p_timestamp, QVideoFrame p_frame) + : timestamp(p_timestamp) + , frame(std::move(p_frame)) + {} + + void clear(){ + frame = QVideoFrame(); + } + bool is_valid() const{ + return frame.isValid(); + } +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/CameraInfo.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/CameraInfo.h index 9e2fa92b49..8db363fcaa 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/CameraInfo.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/CameraInfo.h @@ -1,38 +1,38 @@ -/* Camera Info - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_CameraInfo_H -#define PokemonAutomation_VideoPipeline_CameraInfo_H - -#include - -namespace PokemonAutomation{ - - -class CameraInfo{ -public: - CameraInfo() = default; - explicit CameraInfo(std::string device_name) - : m_device_name(std::move(device_name)) - {} - - void clear(){ m_device_name.clear(); } - - explicit operator bool() const{ return !m_device_name.empty(); } - const std::string& device_name() const{ return m_device_name; } - - bool operator==(const CameraInfo& info) const{ - return m_device_name == info.m_device_name; - } - -private: - std::string m_device_name; -}; - - - -} -#endif +/* Camera Info + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_CameraInfo_H +#define PokemonAutomation_VideoPipeline_CameraInfo_H + +#include + +namespace PokemonAutomation{ + + +class CameraInfo{ +public: + CameraInfo() = default; + explicit CameraInfo(std::string device_name) + : m_device_name(std::move(device_name)) + {} + + void clear(){ m_device_name.clear(); } + + explicit operator bool() const{ return !m_device_name.empty(); } + const std::string& device_name() const{ return m_device_name; } + + bool operator==(const CameraInfo& info) const{ + return m_device_name == info.m_device_name; + } + +private: + std::string m_device_name; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h index 6f564ef27c..aecbf65990 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h @@ -1,65 +1,65 @@ -/* CPU Utilization Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CpuUtilizationStats_H -#define PokemonAutomation_CpuUtilizationStats_H - -#include "Common/Cpp/Time.h" -#include "Common/Cpp/EventRateTracker.h" -#include "CommonFramework/Environment/Environment.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -class CpuUtilizationStat : public OverlayStat{ -public: - CpuUtilizationStat(); - - virtual OverlayStatSnapshot get_current() override; - -private: - std::mutex m_lock; - SystemCpuTime m_last_clock; - UtilizationTracker m_tracker; - - OverlayStatUtilizationPrinter m_printer; -}; - - -inline CpuUtilizationStat::CpuUtilizationStat() - : m_last_clock(SystemCpuTime::now()) -{} -inline OverlayStatSnapshot CpuUtilizationStat::get_current(){ - std::lock_guard lg(m_lock); - - WallClock now = current_time(); - SystemCpuTime current = SystemCpuTime::now(); - size_t vcores = SystemCpuTime::vcores(); - if (vcores == 0 || !current.is_valid()){ - return OverlayStatSnapshot{"CPU Utilization: ---"}; - } - - - if (m_last_clock.is_valid()){ - auto duration = current - m_last_clock; - duration /= vcores; - m_tracker.push_event(std::chrono::duration_cast(duration), now); - } - m_last_clock = current; - - return m_printer.get_snapshot("CPU Utilization (x" + std::to_string(vcores) + "):", m_tracker.utilization()); -} - - - - -} -#endif +/* CPU Utilization Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CpuUtilizationStats_H +#define PokemonAutomation_CpuUtilizationStats_H + +#include "Common/Cpp/Time.h" +#include "Common/Cpp/EventRateTracker.h" +#include "CommonFramework/Environment/Environment.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +class CpuUtilizationStat : public OverlayStat{ +public: + CpuUtilizationStat(); + + virtual OverlayStatSnapshot get_current() override; + +private: + std::mutex m_lock; + SystemCpuTime m_last_clock; + UtilizationTracker m_tracker; + + OverlayStatUtilizationPrinter m_printer; +}; + + +inline CpuUtilizationStat::CpuUtilizationStat() + : m_last_clock(SystemCpuTime::now()) +{} +inline OverlayStatSnapshot CpuUtilizationStat::get_current(){ + std::lock_guard lg(m_lock); + + WallClock now = current_time(); + SystemCpuTime current = SystemCpuTime::now(); + size_t vcores = SystemCpuTime::vcores(); + if (vcores == 0 || !current.is_valid()){ + return OverlayStatSnapshot{"CPU Utilization: ---"}; + } + + + if (m_last_clock.is_valid()){ + auto duration = current - m_last_clock; + duration /= vcores; + m_tracker.push_event(std::chrono::duration_cast(duration), now); + } + m_last_clock = current; + + return m_printer.get_snapshot("CPU Utilization (x" + std::to_string(vcores) + "):", m_tracker.utilization()); +} + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp index 13bf961aa1..e1ba89f056 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.cpp @@ -1,42 +1,42 @@ -/* Thread Utilization Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "ThreadUtilizationStats.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -ThreadUtilizationStat::ThreadUtilizationStat(ThreadHandle handle, std::string label) - : m_handle(handle) - , m_label(std::move(label)) - , m_last_clock(thread_cpu_time(handle)) -{} - -OverlayStatSnapshot ThreadUtilizationStat::get_current(){ - std::lock_guard lg(m_lock); - - WallClock now = current_time(); - WallClock::duration clock = thread_cpu_time(m_handle); - if (clock == WallClock::duration::min()){ - return OverlayStatSnapshot{m_label + " ---"}; - } - - if (m_last_clock != WallClock::duration::min()){ - m_tracker.push_event(clock - m_last_clock, now); - } - m_last_clock = clock; - - return m_printer.get_snapshot(m_label, m_tracker.utilization()); -} - - - -} +/* Thread Utilization Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "ThreadUtilizationStats.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +ThreadUtilizationStat::ThreadUtilizationStat(ThreadHandle handle, std::string label) + : m_handle(handle) + , m_label(std::move(label)) + , m_last_clock(thread_cpu_time(handle)) +{} + +OverlayStatSnapshot ThreadUtilizationStat::get_current(){ + std::lock_guard lg(m_lock); + + WallClock now = current_time(); + WallClock::duration clock = thread_cpu_time(m_handle); + if (clock == WallClock::duration::min()){ + return OverlayStatSnapshot{m_label + " ---"}; + } + + if (m_last_clock != WallClock::duration::min()){ + m_tracker.push_event(clock - m_last_clock, now); + } + m_last_clock = clock; + + return m_printer.get_snapshot(m_label, m_tracker.utilization()); +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h index 417f63b20d..eeb97c5b1c 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h @@ -1,38 +1,38 @@ -/* Thread Utilization Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ThreadUtilizationStats_H -#define PokemonAutomation_ThreadUtilizationStats_H - -#include "Common/Cpp/Time.h" -#include "Common/Cpp/EventRateTracker.h" -#include "CommonFramework/Environment/Environment.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" - -namespace PokemonAutomation{ - - -class ThreadUtilizationStat : public OverlayStat{ -public: - ThreadUtilizationStat(ThreadHandle handle, std::string label); - - virtual OverlayStatSnapshot get_current() override; - -private: - ThreadHandle m_handle; - std::string m_label; - - std::mutex m_lock; - WallClock::duration m_last_clock; - UtilizationTracker m_tracker; - - OverlayStatUtilizationPrinter m_printer; -}; - - - -} -#endif +/* Thread Utilization Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ThreadUtilizationStats_H +#define PokemonAutomation_ThreadUtilizationStats_H + +#include "Common/Cpp/Time.h" +#include "Common/Cpp/EventRateTracker.h" +#include "CommonFramework/Environment/Environment.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" + +namespace PokemonAutomation{ + + +class ThreadUtilizationStat : public OverlayStat{ +public: + ThreadUtilizationStat(ThreadHandle handle, std::string label); + + virtual OverlayStatSnapshot get_current() override; + +private: + ThreadHandle m_handle; + std::string m_label; + + std::mutex m_lock; + WallClock::duration m_last_clock; + UtilizationTracker m_tracker; + + OverlayStatUtilizationPrinter m_printer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.cpp index 68480967c5..8954320766 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.cpp @@ -1,242 +1,242 @@ -/* Video Display - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "VideoDisplayWidget.h" -#include "VideoDisplayWindow.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -VideoDisplayWidget::VideoDisplayWidget( - QWidget& parent, QLayout& holder, - size_t id, - CommandReceiver& command_receiver, - VideoSession& video_session, - VideoOverlaySession& overlay -) - : WidgetStackFixedAspectRatio(parent, WidgetStackFixedAspectRatio::ADJUST_HEIGHT_TO_WIDTH) - , m_holder(holder) - , m_id(id) - , m_command_receiver(command_receiver) - , m_video_session(video_session) - , m_overlay_session(overlay) - , m_overlay(new VideoOverlayWidget(*this, overlay)) - , m_underlay(new QWidget(this)) - , m_source_fps(*this) - , m_display_fps(*this) -{ - this->add_widget(*m_overlay); - - VideoSource* source = video_session.current_source(); - if (source){ - m_video = source->make_display_QtWidget(this); - this->add_widget(*m_video); - } - - Resolution resolution = video_session.current_resolution(); - if (resolution){ - set_aspect_ratio(resolution.aspect_ratio()); - } - - m_overlay->setVisible(true); - m_overlay->setHidden(false); - m_overlay->raise(); - -#if 1 - { - m_underlay->setHidden(true); - holder.addWidget(m_underlay); - - QVBoxLayout* layout = new QVBoxLayout(m_underlay); - layout->setAlignment(Qt::AlignTop); - - QHBoxLayout* row_width = new QHBoxLayout(); - layout->addLayout(row_width); - QHBoxLayout* row_height = new QHBoxLayout(); - layout->addLayout(row_height); - - row_width->addStretch(2); - row_height->addStretch(2); - row_width->addWidget(new QLabel("Window Width:", m_underlay), 1); - row_height->addWidget(new QLabel("Window Height:", m_underlay), 1); - - m_width_box = new QLineEdit(m_underlay); - row_width->addWidget(m_width_box, 1); - m_height_box = new QLineEdit(m_underlay); - row_height->addWidget(m_height_box, 1); - - row_width->addStretch(2); - row_height->addStretch(2); - - connect( - m_width_box, &QLineEdit::editingFinished, - this, [this]{ - bool ok; - int value = m_width_box->text().toInt(&ok); - if (ok && 100 <= value){ - m_last_width = value; - if (m_window){ - m_window->resize(m_last_width, m_last_height); - } - } - m_width_box->setText(QString::number(m_last_width)); - } - ); - connect( - m_height_box, &QLineEdit::editingFinished, - this, [this]{ - bool ok; - int value = m_height_box->text().toInt(&ok); - if (ok && 100 <= value){ - m_last_height = value; - if (m_window){ - m_window->resize(m_last_width, m_last_height); - } - } - m_height_box->setText(QString::number(m_last_height)); - } - ); - } -#endif - - overlay.add_stat(m_source_fps); - overlay.add_stat(m_display_fps); - video_session.add_state_listener(*this); -} -VideoDisplayWidget::~VideoDisplayWidget(){ - m_video_session.remove_state_listener(*this); - - // Close the window popout first since it holds references to this class. - move_back_from_window(); - m_overlay_session.remove_stat(m_display_fps); - m_overlay_session.remove_stat(m_source_fps); - delete m_underlay; -} - -void VideoDisplayWidget::clear_video_source(){ - if (m_video){ - this->remove_widget(m_video); - m_video = nullptr; - } -} - -void VideoDisplayWidget::post_startup(VideoSource* source){ - clear_video_source(); - if (source){ - m_video = source->make_display_QtWidget(this); - this->add_widget(*m_video); - set_aspect_ratio(source->current_resolution().aspect_ratio()); - m_overlay->raise(); - } -} -void VideoDisplayWidget::pre_shutdown(){ - clear_video_source(); -} - - - -void VideoDisplayWidget::move_to_new_window(){ - if (m_window){ - return; - } - // The constructor of VideoDisplayWindow handles the transfer of this VideoDisplayWidget to the new window. - // The constructor also displays the window. - // So there is nothing else to do in VideoDisplayWidget::move_to_new_window() besides building VideoDisplayWindow. - this->set_size_policy(EXPAND_TO_BOX); - m_window.reset(new VideoDisplayWindow(this)); - m_underlay->setHidden(false); -} -void VideoDisplayWidget::move_back_from_window(){ - if (!m_window){ - return; - } - m_underlay->setHidden(true); - this->set_size_policy(ADJUST_HEIGHT_TO_WIDTH); - m_holder.addWidget(this); -// this->resize(this->size()); -// cout << "VideoWidget Before: " << m_video->width() << " x " << m_video->height() << endl; - if (m_video){ - m_video->resize(this->size()); - } -// cout << "VideoWidget After: " << m_video->width() << " x " << m_video->height() << endl; - m_holder.update(); - m_window.reset(); -} - - - -void VideoDisplayWidget::mouseDoubleClickEvent(QMouseEvent* event){ -// if (!PreloadSettings::instance().DEVELOPER_MODE){ -// return; -// } - // If this widget is not already inside a VideoDisplayWindow, move it - // into a VideoDisplayWindow - if (!m_window){ - move_to_new_window(); - }else{ - QWidget::mouseDoubleClickEvent(event); - } -} -void VideoDisplayWidget::paintEvent(QPaintEvent* event){ - WidgetStackFixedAspectRatio::paintEvent(event); -// cout << "VideoDisplayWidget: " << this->width() << " x " << this->height() << endl; -// cout << "VideoWidget: " << m_video->width() << " x " << m_video->height() << endl; -} -void VideoDisplayWidget::resizeEvent(QResizeEvent* event){ - WidgetStackFixedAspectRatio::resizeEvent(event); - m_last_width = this->width(); - m_last_height = this->height(); - m_width_box->setText(QString::number(m_last_width)); - m_height_box->setText(QString::number(m_last_height)); -} - -void VideoDisplayWidget::mousePressEvent(QMouseEvent* event){ - WidgetStackFixedAspectRatio::mousePressEvent(event); - double x = (double)event->pos().x() / this->width(); - double y = (double)event->pos().y() / this->height(); - m_overlay_session.issue_mouse_press(x, y); -} -void VideoDisplayWidget::mouseReleaseEvent(QMouseEvent* event){ - WidgetStackFixedAspectRatio::mouseReleaseEvent(event); - double x = (double)event->pos().x() / this->width(); - double y = (double)event->pos().y() / this->height(); - m_overlay_session.issue_mouse_release(x, y); -} -void VideoDisplayWidget::mouseMoveEvent(QMouseEvent* event){ - WidgetStackFixedAspectRatio::mouseMoveEvent(event); - double x = (double)event->pos().x() / this->width(); - double y = (double)event->pos().y() / this->height(); - m_overlay_session.issue_mouse_move(x, y); -} - -OverlayStatSnapshot VideoSourceFPS::get_current(){ - double fps = m_parent.m_video_session.fps_source(); - return OverlayStatSnapshot{ - "Video Source FPS: " + tostr_fixed(fps, 2), - fps < 20 ? COLOR_RED : COLOR_WHITE - }; -} -OverlayStatSnapshot VideoDisplayFPS::get_current(){ - double fps = m_parent.m_video_session.fps_display(); - return OverlayStatSnapshot{ - "Video Display FPS: " + (fps < 0 ? "???" : tostr_fixed(fps, 2)), - fps >= 0 && fps < 20 ? COLOR_RED : COLOR_WHITE - }; -} - - - -} +/* Video Display + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "VideoDisplayWidget.h" +#include "VideoDisplayWindow.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +VideoDisplayWidget::VideoDisplayWidget( + QWidget& parent, QLayout& holder, + size_t id, + CommandReceiver& command_receiver, + VideoSession& video_session, + VideoOverlaySession& overlay +) + : WidgetStackFixedAspectRatio(parent, WidgetStackFixedAspectRatio::ADJUST_HEIGHT_TO_WIDTH) + , m_holder(holder) + , m_id(id) + , m_command_receiver(command_receiver) + , m_video_session(video_session) + , m_overlay_session(overlay) + , m_overlay(new VideoOverlayWidget(*this, overlay)) + , m_underlay(new QWidget(this)) + , m_source_fps(*this) + , m_display_fps(*this) +{ + this->add_widget(*m_overlay); + + VideoSource* source = video_session.current_source(); + if (source){ + m_video = source->make_display_QtWidget(this); + this->add_widget(*m_video); + } + + Resolution resolution = video_session.current_resolution(); + if (resolution){ + set_aspect_ratio(resolution.aspect_ratio()); + } + + m_overlay->setVisible(true); + m_overlay->setHidden(false); + m_overlay->raise(); + +#if 1 + { + m_underlay->setHidden(true); + holder.addWidget(m_underlay); + + QVBoxLayout* layout = new QVBoxLayout(m_underlay); + layout->setAlignment(Qt::AlignTop); + + QHBoxLayout* row_width = new QHBoxLayout(); + layout->addLayout(row_width); + QHBoxLayout* row_height = new QHBoxLayout(); + layout->addLayout(row_height); + + row_width->addStretch(2); + row_height->addStretch(2); + row_width->addWidget(new QLabel("Window Width:", m_underlay), 1); + row_height->addWidget(new QLabel("Window Height:", m_underlay), 1); + + m_width_box = new QLineEdit(m_underlay); + row_width->addWidget(m_width_box, 1); + m_height_box = new QLineEdit(m_underlay); + row_height->addWidget(m_height_box, 1); + + row_width->addStretch(2); + row_height->addStretch(2); + + connect( + m_width_box, &QLineEdit::editingFinished, + this, [this]{ + bool ok; + int value = m_width_box->text().toInt(&ok); + if (ok && 100 <= value){ + m_last_width = value; + if (m_window){ + m_window->resize(m_last_width, m_last_height); + } + } + m_width_box->setText(QString::number(m_last_width)); + } + ); + connect( + m_height_box, &QLineEdit::editingFinished, + this, [this]{ + bool ok; + int value = m_height_box->text().toInt(&ok); + if (ok && 100 <= value){ + m_last_height = value; + if (m_window){ + m_window->resize(m_last_width, m_last_height); + } + } + m_height_box->setText(QString::number(m_last_height)); + } + ); + } +#endif + + overlay.add_stat(m_source_fps); + overlay.add_stat(m_display_fps); + video_session.add_state_listener(*this); +} +VideoDisplayWidget::~VideoDisplayWidget(){ + m_video_session.remove_state_listener(*this); + + // Close the window popout first since it holds references to this class. + move_back_from_window(); + m_overlay_session.remove_stat(m_display_fps); + m_overlay_session.remove_stat(m_source_fps); + delete m_underlay; +} + +void VideoDisplayWidget::clear_video_source(){ + if (m_video){ + this->remove_widget(m_video); + m_video = nullptr; + } +} + +void VideoDisplayWidget::post_startup(VideoSource* source){ + clear_video_source(); + if (source){ + m_video = source->make_display_QtWidget(this); + this->add_widget(*m_video); + set_aspect_ratio(source->current_resolution().aspect_ratio()); + m_overlay->raise(); + } +} +void VideoDisplayWidget::pre_shutdown(){ + clear_video_source(); +} + + + +void VideoDisplayWidget::move_to_new_window(){ + if (m_window){ + return; + } + // The constructor of VideoDisplayWindow handles the transfer of this VideoDisplayWidget to the new window. + // The constructor also displays the window. + // So there is nothing else to do in VideoDisplayWidget::move_to_new_window() besides building VideoDisplayWindow. + this->set_size_policy(EXPAND_TO_BOX); + m_window.reset(new VideoDisplayWindow(this)); + m_underlay->setHidden(false); +} +void VideoDisplayWidget::move_back_from_window(){ + if (!m_window){ + return; + } + m_underlay->setHidden(true); + this->set_size_policy(ADJUST_HEIGHT_TO_WIDTH); + m_holder.addWidget(this); +// this->resize(this->size()); +// cout << "VideoWidget Before: " << m_video->width() << " x " << m_video->height() << endl; + if (m_video){ + m_video->resize(this->size()); + } +// cout << "VideoWidget After: " << m_video->width() << " x " << m_video->height() << endl; + m_holder.update(); + m_window.reset(); +} + + + +void VideoDisplayWidget::mouseDoubleClickEvent(QMouseEvent* event){ +// if (!PreloadSettings::instance().DEVELOPER_MODE){ +// return; +// } + // If this widget is not already inside a VideoDisplayWindow, move it + // into a VideoDisplayWindow + if (!m_window){ + move_to_new_window(); + }else{ + QWidget::mouseDoubleClickEvent(event); + } +} +void VideoDisplayWidget::paintEvent(QPaintEvent* event){ + WidgetStackFixedAspectRatio::paintEvent(event); +// cout << "VideoDisplayWidget: " << this->width() << " x " << this->height() << endl; +// cout << "VideoWidget: " << m_video->width() << " x " << m_video->height() << endl; +} +void VideoDisplayWidget::resizeEvent(QResizeEvent* event){ + WidgetStackFixedAspectRatio::resizeEvent(event); + m_last_width = this->width(); + m_last_height = this->height(); + m_width_box->setText(QString::number(m_last_width)); + m_height_box->setText(QString::number(m_last_height)); +} + +void VideoDisplayWidget::mousePressEvent(QMouseEvent* event){ + WidgetStackFixedAspectRatio::mousePressEvent(event); + double x = (double)event->pos().x() / this->width(); + double y = (double)event->pos().y() / this->height(); + m_overlay_session.issue_mouse_press(x, y); +} +void VideoDisplayWidget::mouseReleaseEvent(QMouseEvent* event){ + WidgetStackFixedAspectRatio::mouseReleaseEvent(event); + double x = (double)event->pos().x() / this->width(); + double y = (double)event->pos().y() / this->height(); + m_overlay_session.issue_mouse_release(x, y); +} +void VideoDisplayWidget::mouseMoveEvent(QMouseEvent* event){ + WidgetStackFixedAspectRatio::mouseMoveEvent(event); + double x = (double)event->pos().x() / this->width(); + double y = (double)event->pos().y() / this->height(); + m_overlay_session.issue_mouse_move(x, y); +} + +OverlayStatSnapshot VideoSourceFPS::get_current(){ + double fps = m_parent.m_video_session.fps_source(); + return OverlayStatSnapshot{ + "Video Source FPS: " + tostr_fixed(fps, 2), + fps < 20 ? COLOR_RED : COLOR_WHITE + }; +} +OverlayStatSnapshot VideoDisplayFPS::get_current(){ + double fps = m_parent.m_video_session.fps_display(); + return OverlayStatSnapshot{ + "Video Display FPS: " + (fps < 0 ? "???" : tostr_fixed(fps, 2)), + fps >= 0 && fps < 20 ? COLOR_RED : COLOR_WHITE + }; +} + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h index f64a16efba..34fabca5de 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h @@ -1,135 +1,135 @@ -/* Video Display - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoDisplayWidget_H -#define PokemonAutomation_VideoPipeline_VideoDisplayWidget_H - -//#include "Common/Cpp/ValueDebouncer.h" -#include "Common/Qt/WidgetStackFixedAspectRatio.h" -#include "CommonFramework/VideoPipeline/VideoSession.h" -#include "VideoOverlayWidget.h" - -class QLineEdit; - -namespace PokemonAutomation{ - -class VideoDisplayWindow; - - -// Interface for forwarding keyboard commands from the VideoDisplayWidget to -// whatever thing under it handles it. -struct CommandReceiver{ - virtual void key_press(QKeyEvent* event) = 0; - virtual void key_release(QKeyEvent* event) = 0; - - virtual void focus_in(QFocusEvent* event) = 0; - virtual void focus_out(QFocusEvent* event) = 0; -}; - - - - - -class VideoDisplayWidget; - -class VideoSourceFPS : public OverlayStat{ -public: - VideoSourceFPS(VideoDisplayWidget& parent) - : m_parent(parent) - {} - virtual OverlayStatSnapshot get_current() override; - -private: - VideoDisplayWidget& m_parent; -}; - -class VideoDisplayFPS : public OverlayStat{ -public: - VideoDisplayFPS(VideoDisplayWidget& parent) - : m_parent(parent) - {} - virtual OverlayStatSnapshot get_current() override; - -private: - VideoDisplayWidget& m_parent; -}; - - - -// The widget that owns the video window. -// It consists of a VideoWidget that loads the video content from Switch and a -// VideoOverlayWidget that renders inference boxes and other visualizations on -// top of the video content. -class VideoDisplayWidget : public WidgetStackFixedAspectRatio, private VideoSession::StateListener{ -public: - VideoDisplayWidget( - QWidget& parent, QLayout& holder, - size_t id, - CommandReceiver& command_receiver, - VideoSession& video_session, - VideoOverlaySession& overlay - ); - ~VideoDisplayWidget(); - - operator bool() const{ return m_video != nullptr; } - size_t id() const{ return m_id; } - - VideoOverlayWidget& overlay(){ return *m_overlay; } - CommandReceiver& command_receiver(){ return m_command_receiver; } - - // Move the video display widget to a new Qt window, so that we can make it full screen. - // We need to go to a new window to do fullscreen because Qt cannot fullscreen a widget unless - // it's a window. - void move_to_new_window(); - void move_back_from_window(); - -protected: - virtual void post_startup(VideoSource* source) override; - virtual void pre_shutdown() override; - - // Override QWidget::mouseDoubleClickEvent(). - // When double click, call move_to_new_window() to move to a new window to be ready for full screen. - virtual void mouseDoubleClickEvent(QMouseEvent *event) override; - - virtual void mousePressEvent(QMouseEvent* event) override; - virtual void mouseReleaseEvent(QMouseEvent* event) override; - virtual void mouseMoveEvent(QMouseEvent* event) override; - - virtual void paintEvent(QPaintEvent*) override; - virtual void resizeEvent(QResizeEvent* event) override; - -private: - void clear_video_source(); - -private: - friend class VideoSourceFPS; - friend class VideoDisplayFPS; - - QLayout& m_holder; - const size_t m_id; - CommandReceiver& m_command_receiver; - VideoSession& m_video_session; - VideoOverlaySession& m_overlay_session; - - QWidget* m_video = nullptr; - VideoOverlayWidget* m_overlay = nullptr; - - QWidget* m_underlay = nullptr; - QLineEdit* m_width_box = nullptr; - QLineEdit* m_height_box = nullptr; - int m_last_width = 0; - int m_last_height = 0; - - std::unique_ptr m_window; - - VideoSourceFPS m_source_fps; - VideoDisplayFPS m_display_fps; -}; - - - -} -#endif +/* Video Display + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoDisplayWidget_H +#define PokemonAutomation_VideoPipeline_VideoDisplayWidget_H + +//#include "Common/Cpp/ValueDebouncer.h" +#include "Common/Qt/WidgetStackFixedAspectRatio.h" +#include "CommonFramework/VideoPipeline/VideoSession.h" +#include "VideoOverlayWidget.h" + +class QLineEdit; + +namespace PokemonAutomation{ + +class VideoDisplayWindow; + + +// Interface for forwarding keyboard commands from the VideoDisplayWidget to +// whatever thing under it handles it. +struct CommandReceiver{ + virtual void key_press(QKeyEvent* event) = 0; + virtual void key_release(QKeyEvent* event) = 0; + + virtual void focus_in(QFocusEvent* event) = 0; + virtual void focus_out(QFocusEvent* event) = 0; +}; + + + + + +class VideoDisplayWidget; + +class VideoSourceFPS : public OverlayStat{ +public: + VideoSourceFPS(VideoDisplayWidget& parent) + : m_parent(parent) + {} + virtual OverlayStatSnapshot get_current() override; + +private: + VideoDisplayWidget& m_parent; +}; + +class VideoDisplayFPS : public OverlayStat{ +public: + VideoDisplayFPS(VideoDisplayWidget& parent) + : m_parent(parent) + {} + virtual OverlayStatSnapshot get_current() override; + +private: + VideoDisplayWidget& m_parent; +}; + + + +// The widget that owns the video window. +// It consists of a VideoWidget that loads the video content from Switch and a +// VideoOverlayWidget that renders inference boxes and other visualizations on +// top of the video content. +class VideoDisplayWidget : public WidgetStackFixedAspectRatio, private VideoSession::StateListener{ +public: + VideoDisplayWidget( + QWidget& parent, QLayout& holder, + size_t id, + CommandReceiver& command_receiver, + VideoSession& video_session, + VideoOverlaySession& overlay + ); + ~VideoDisplayWidget(); + + operator bool() const{ return m_video != nullptr; } + size_t id() const{ return m_id; } + + VideoOverlayWidget& overlay(){ return *m_overlay; } + CommandReceiver& command_receiver(){ return m_command_receiver; } + + // Move the video display widget to a new Qt window, so that we can make it full screen. + // We need to go to a new window to do fullscreen because Qt cannot fullscreen a widget unless + // it's a window. + void move_to_new_window(); + void move_back_from_window(); + +protected: + virtual void post_startup(VideoSource* source) override; + virtual void pre_shutdown() override; + + // Override QWidget::mouseDoubleClickEvent(). + // When double click, call move_to_new_window() to move to a new window to be ready for full screen. + virtual void mouseDoubleClickEvent(QMouseEvent *event) override; + + virtual void mousePressEvent(QMouseEvent* event) override; + virtual void mouseReleaseEvent(QMouseEvent* event) override; + virtual void mouseMoveEvent(QMouseEvent* event) override; + + virtual void paintEvent(QPaintEvent*) override; + virtual void resizeEvent(QResizeEvent* event) override; + +private: + void clear_video_source(); + +private: + friend class VideoSourceFPS; + friend class VideoDisplayFPS; + + QLayout& m_holder; + const size_t m_id; + CommandReceiver& m_command_receiver; + VideoSession& m_video_session; + VideoOverlaySession& m_overlay_session; + + QWidget* m_video = nullptr; + VideoOverlayWidget* m_overlay = nullptr; + + QWidget* m_underlay = nullptr; + QLineEdit* m_width_box = nullptr; + QLineEdit* m_height_box = nullptr; + int m_last_width = 0; + int m_last_height = 0; + + std::unique_ptr m_window; + + VideoSourceFPS m_source_fps; + VideoDisplayFPS m_display_fps; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp index 2ac269a2cd..1554795db0 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.cpp @@ -1,119 +1,119 @@ -/* Video Display Window - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "CommonFramework/Windows/WindowTracker.h" -#include "VideoDisplayWidget.h" -#include "VideoDisplayWindow.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -VideoDisplayWindow::VideoDisplayWindow(VideoDisplayWidget* display_widget) - : m_display_widget(display_widget) -{ -// m_display_widget->setParent(this); - setWindowTitle("Console: " + QString::number(m_display_widget->id())); - this->setWindowIcon(QIcon(QString::fromStdString(RESOURCE_PATH() + "icon.png"))); - -// this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); - this->setCentralWidget(m_display_widget); -// m_display_widget->setAlignment(Qt::AlignCenter); - -// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; - - m_normal_size = m_display_widget->size(); - this->resize(m_normal_size); -// cout << this->width() << " x " << this->height() << endl; - - this->show(); - this->raise(); // bring the window to front on macOS - this->activateWindow(); // bring the window to front on Windows - - setFocusPolicy(Qt::StrongFocus); - add_window(*this); -} -VideoDisplayWindow::~VideoDisplayWindow(){ - remove_window(*this); - close(); -} - -void VideoDisplayWindow::changeEvent(QEvent* event){ - QMainWindow::changeEvent(event); - if (this->windowState() == Qt::WindowMaximized){ - this->showFullScreen(); -// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; - } -} -void VideoDisplayWindow::closeEvent(QCloseEvent* event){ - close(); - QMainWindow::closeEvent(event); -} - -void VideoDisplayWindow::resizeEvent(QResizeEvent* event){ - QMainWindow::resizeEvent(event); -} - -void VideoDisplayWindow::close(){ - if (m_display_widget == nullptr){ - return; - } - m_display_widget->move_back_from_window(); - m_display_widget = nullptr; -} -void VideoDisplayWindow::exit_full_screen(){ - this->showNormal(); -} - -void VideoDisplayWindow::mouseDoubleClickEvent(QMouseEvent* event){ - if (this->isFullScreen()){ - exit_full_screen(); - }else{ - this->showFullScreen(); -// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; - } -// QWidget::mouseDoubleClickEvent(event); -} - -void VideoDisplayWindow::keyPressEvent(QKeyEvent* event){ - if ((Qt::Key)event->key() == Qt::Key::Key_Escape){ - exit_full_screen(); - return; - } - if (m_display_widget){ - m_display_widget->command_receiver().key_press(event); - return; - } - QWidget::keyPressEvent(event); -} -void VideoDisplayWindow::keyReleaseEvent(QKeyEvent* event){ - if (m_display_widget){ - m_display_widget->command_receiver().key_release(event); - return; - } - QWidget::keyReleaseEvent(event); -} -void VideoDisplayWindow::focusInEvent(QFocusEvent* event){ - if (m_display_widget){ - m_display_widget->command_receiver().focus_in(event); - } - QWidget::focusInEvent(event); -} -void VideoDisplayWindow::focusOutEvent(QFocusEvent* event){ - if (m_display_widget){ - m_display_widget->command_receiver().focus_out(event); - } - QWidget::focusOutEvent(event); -} - -} +/* Video Display Window + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "CommonFramework/Windows/WindowTracker.h" +#include "VideoDisplayWidget.h" +#include "VideoDisplayWindow.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +VideoDisplayWindow::VideoDisplayWindow(VideoDisplayWidget* display_widget) + : m_display_widget(display_widget) +{ +// m_display_widget->setParent(this); + setWindowTitle("Console: " + QString::number(m_display_widget->id())); + this->setWindowIcon(QIcon(QString::fromStdString(RESOURCE_PATH() + "icon.png"))); + +// this->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); + this->setCentralWidget(m_display_widget); +// m_display_widget->setAlignment(Qt::AlignCenter); + +// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; + + m_normal_size = m_display_widget->size(); + this->resize(m_normal_size); +// cout << this->width() << " x " << this->height() << endl; + + this->show(); + this->raise(); // bring the window to front on macOS + this->activateWindow(); // bring the window to front on Windows + + setFocusPolicy(Qt::StrongFocus); + add_window(*this); +} +VideoDisplayWindow::~VideoDisplayWindow(){ + remove_window(*this); + close(); +} + +void VideoDisplayWindow::changeEvent(QEvent* event){ + QMainWindow::changeEvent(event); + if (this->windowState() == Qt::WindowMaximized){ + this->showFullScreen(); +// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; + } +} +void VideoDisplayWindow::closeEvent(QCloseEvent* event){ + close(); + QMainWindow::closeEvent(event); +} + +void VideoDisplayWindow::resizeEvent(QResizeEvent* event){ + QMainWindow::resizeEvent(event); +} + +void VideoDisplayWindow::close(){ + if (m_display_widget == nullptr){ + return; + } + m_display_widget->move_back_from_window(); + m_display_widget = nullptr; +} +void VideoDisplayWindow::exit_full_screen(){ + this->showNormal(); +} + +void VideoDisplayWindow::mouseDoubleClickEvent(QMouseEvent* event){ + if (this->isFullScreen()){ + exit_full_screen(); + }else{ + this->showFullScreen(); +// cout << "Display Widget: " << m_display_widget->width() << " x " << m_display_widget->height() << endl; + } +// QWidget::mouseDoubleClickEvent(event); +} + +void VideoDisplayWindow::keyPressEvent(QKeyEvent* event){ + if ((Qt::Key)event->key() == Qt::Key::Key_Escape){ + exit_full_screen(); + return; + } + if (m_display_widget){ + m_display_widget->command_receiver().key_press(event); + return; + } + QWidget::keyPressEvent(event); +} +void VideoDisplayWindow::keyReleaseEvent(QKeyEvent* event){ + if (m_display_widget){ + m_display_widget->command_receiver().key_release(event); + return; + } + QWidget::keyReleaseEvent(event); +} +void VideoDisplayWindow::focusInEvent(QFocusEvent* event){ + if (m_display_widget){ + m_display_widget->command_receiver().focus_in(event); + } + QWidget::focusInEvent(event); +} +void VideoDisplayWindow::focusOutEvent(QFocusEvent* event){ + if (m_display_widget){ + m_display_widget->command_receiver().focus_out(event); + } + QWidget::focusOutEvent(event); +} + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.h index 86734823d3..06983c1219 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoDisplayWindow.h @@ -1,61 +1,61 @@ -/* Video Display Window - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoDisplayWindow_H -#define PokemonAutomation_VideoPipeline_VideoDisplayWindow_H - -#include -#include "VideoDisplayWidget.h" - -namespace PokemonAutomation{ - -namespace NintendoSwitch{ - class SwitchSystemWidget; -} - - -// A separate window to render video display. -// This is used when the user wants to pop out the video display widget to a separate window. -// A separate window has the benefit of becoming full screen. -// This window is built by VideoDisplayWidget. -class VideoDisplayWindow : public QMainWindow{ -public: - // The constructor of VideoDisplayWindow transfers of the ownership of VideoDisplayWidget from its parent - // SwitchSystemWidget to VideoDisplayWindow, and making SwitchSystemWidget the parent of the - // VideoDisplayWindow. - // The constructor then displays the window. - VideoDisplayWindow(VideoDisplayWidget* display_widget); - ~VideoDisplayWindow(); - -private: -// virtual QSize sizeHint() const override; - - virtual void changeEvent(QEvent* event) override; - virtual void closeEvent(QCloseEvent* event) override; - virtual void resizeEvent(QResizeEvent* event) override; - - void mouseDoubleClickEvent(QMouseEvent *event) override; - - // Override key and focus event handlers to pass those events back to the parent widget. - // The parent widget is SwitchSystemWidget. It needs to listen to key and focus events to - // realize virtual keyboard functionality. - virtual void keyPressEvent(QKeyEvent* event) override; - virtual void keyReleaseEvent(QKeyEvent* event) override; - virtual void focusInEvent(QFocusEvent* event) override; - virtual void focusOutEvent(QFocusEvent* event) override; - - void close(); - void exit_full_screen(); - - VideoDisplayWidget* m_display_widget; - - QSize m_normal_size; -}; - - - -} -#endif +/* Video Display Window + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoDisplayWindow_H +#define PokemonAutomation_VideoPipeline_VideoDisplayWindow_H + +#include +#include "VideoDisplayWidget.h" + +namespace PokemonAutomation{ + +namespace NintendoSwitch{ + class SwitchSystemWidget; +} + + +// A separate window to render video display. +// This is used when the user wants to pop out the video display widget to a separate window. +// A separate window has the benefit of becoming full screen. +// This window is built by VideoDisplayWidget. +class VideoDisplayWindow : public QMainWindow{ +public: + // The constructor of VideoDisplayWindow transfers of the ownership of VideoDisplayWidget from its parent + // SwitchSystemWidget to VideoDisplayWindow, and making SwitchSystemWidget the parent of the + // VideoDisplayWindow. + // The constructor then displays the window. + VideoDisplayWindow(VideoDisplayWidget* display_widget); + ~VideoDisplayWindow(); + +private: +// virtual QSize sizeHint() const override; + + virtual void changeEvent(QEvent* event) override; + virtual void closeEvent(QCloseEvent* event) override; + virtual void resizeEvent(QResizeEvent* event) override; + + void mouseDoubleClickEvent(QMouseEvent *event) override; + + // Override key and focus event handlers to pass those events back to the parent widget. + // The parent widget is SwitchSystemWidget. It needs to listen to key and focus events to + // realize virtual keyboard functionality. + virtual void keyPressEvent(QKeyEvent* event) override; + virtual void keyReleaseEvent(QKeyEvent* event) override; + virtual void focusInEvent(QFocusEvent* event) override; + virtual void focusOutEvent(QFocusEvent* event) override; + + void close(); + void exit_full_screen(); + + VideoDisplayWidget* m_display_widget; + + QSize m_normal_size; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp index 4ca829ff08..331c61e76b 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.cpp @@ -1,334 +1,334 @@ -/* Video Overlay - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "CommonFramework/GlobalServices.h" -#include "VideoOverlayWidget.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ - - - -//const ImageFloatBox ENTIRE_VIDEO(0.0, 0.0, 1.0, 1.0); - - - -void VideoOverlayWidget::detach(){ - m_session.remove_listener(*this); - global_watchdog().remove(*this); -} -VideoOverlayWidget::~VideoOverlayWidget(){ - detach(); -} -VideoOverlayWidget::VideoOverlayWidget(QWidget& parent, VideoOverlaySession& session) - : QWidget(&parent) - , m_session(session) - , m_boxes(std::make_shared>(session.boxes())) - , m_texts(std::make_shared>(session.texts())) - , m_images(std::make_shared>(session.images())) - , m_log(std::make_shared>(session.log_texts())) - , m_stats(nullptr) -{ - setAttribute(Qt::WA_NoSystemBackground); - setAttribute(Qt::WA_TranslucentBackground); - setAttribute(Qt::WA_TransparentForMouseEvents); - -// m_boxes.insert(&ENTIRE_VIDEO); - try{ - global_watchdog().add(*this, std::chrono::milliseconds(50)); - m_session.add_listener(*this); - }catch (...){ - detach(); - throw; - } -} - -void VideoOverlayWidget::async_update(){ - // by using QMetaObject::invokeMethod, we can call this->update() on a non-main thread - // without trigger Qt crash, as normally this->update() can only be called on the main - // thread. - QMetaObject::invokeMethod(this, [this]{ this->update(); }); -} - -void VideoOverlayWidget::on_overlay_update_boxes(const std::shared_ptr>& boxes){ - WriteSpinLock lg(m_lock, "VideoOverlay::update_boxes()"); - m_boxes = boxes; -} -void VideoOverlayWidget::on_overlay_update_text(const std::shared_ptr>& texts){ - WriteSpinLock lg(m_lock, "VideoOverlay::update_text()"); - m_texts = texts; -} -void VideoOverlayWidget::on_overlay_update_images(const std::shared_ptr>& images){ - WriteSpinLock lg(m_lock, "VideoOverlay::update_images()"); - m_images = images; -} - -void VideoOverlayWidget::on_overlay_update_log(const std::shared_ptr>& logs){ - WriteSpinLock lg(m_lock, "VideoOverlay::update_log_text()"); - m_log = logs; -} -#if 0 -void VideoOverlayWidget::update_log_background(const std::shared_ptr>& bg_boxes){ - WriteSpinLock lg(m_lock, "VideoOverlay::update_log_background()"); - m_log_text_bg_boxes = bg_boxes; -} -#endif -void VideoOverlayWidget::on_overlay_update_stats(const std::list* stats){ - WriteSpinLock lg(m_lock, "VideoOverlay::update_stats()"); - m_stats = stats; -} - -void VideoOverlayWidget::on_watchdog_timeout(){ - QMetaObject::invokeMethod(this, [this]{ this->update(); }); -// static int c = 0; -// cout << "VideoOverlayWidget::on_watchdog_timeout(): " << c++ << endl; -} - - -void VideoOverlayWidget::resizeEvent(QResizeEvent* event){} - -void VideoOverlayWidget::paintEvent(QPaintEvent*){ - QPainter painter(this); - { - WriteSpinLock lg(m_lock, "VideoOverlay::paintEvent()"); - - if (m_session.enabled_boxes()){ - render_boxes(painter); - } - if (m_session.enabled_text()){ - render_text(painter); - } - if (m_session.enabled_images()){ - render_images(painter); - } - if (m_session.enabled_log()){ - render_log(painter); - } - if (m_session.enabled_stats() && m_stats){ - render_stats(painter); - } - } - - global_watchdog().delay(*this); -} - - -void VideoOverlayWidget::render_boxes(QPainter& painter){ - const int width = this->width(); - const int height = this->height(); - for (const auto& item : *m_boxes){ - QColor color = QColor((uint32_t)item.color); - painter.setPen(color); -// cout << box->x << " " << box->y << ", " << box->width << " x " << box->height << endl; -// cout << (int)(width * box->x + 0.5) -// << " " << (int)(height * box->y + 0.5) -// << ", " << (int)(width * box->width + 0.5) -// << " x " << (int)(height * box->height + 0.5) << endl; -// cout << painter.pen().width() << endl; - - // Compute coordinates. Clip so that it stays in-bounds. - int xmin = std::max((int)(width * item.box.x + 0.5), 1); - int ymin = std::max((int)(height * item.box.y + 0.5), 1); -// int xmax = std::min(xmin + (int)(width * box->width + 0.5), width - painter.pen().width()); -// int ymax = std::min(ymin + (int)(height * box->height + 0.5), height - painter.pen().width()); - int xmax = std::min(xmin + (int)(width * item.box.width + 0.5), width - 1); - int ymax = std::min(ymin + (int)(height * item.box.height + 0.5), height - 1); - -// cout << "m_video_size.width() = " << m_widget_size.width() << ", xmax = " << xmax << endl; - - painter.drawRect( - xmin, - ymin, - xmax - xmin, - ymax - ymin - ); - - - // Draw the label. - - if (item.label.empty()){ - continue; - } - - QString text = QString::fromStdString(item.label); - - QFont text_font = this->font(); - text_font.setPointSizeF((int)(height * 0.015)); - painter.setFont(text_font); - - QRect br = painter.boundingRect(0, 0, width, height, 0, text); -// cout << br.x() << " " << br.y() << " : " << br.width() << " " << br.height() << endl; - - int padding_width = (int)(width * 0.005); - int padding_height = (int)(height * 0.004); - - int box_height = 3*padding_height + (int)(height * 0.02); - int box_width = 2*padding_width + br.width(); - - if (ymin - box_height < 0){ - ymin += box_height; - } - - painter.fillRect( - xmin, - std::max(ymin - box_height, 0), - box_width, - box_height, - color - ); - - uint32_t red = ((uint32_t)item.color >> 16) & 0xff; - uint32_t green = ((uint32_t)item.color >> 8) & 0xff; - uint32_t blue = ((uint32_t)item.color >> 0) & 0xff; - - double brightness = 0.299*red + 0.587*green + 0.114*blue; - if (brightness > 128){ - painter.setPen(QColor(0xff000000)); - }else{ - painter.setPen(QColor(0xffffffff)); - } - - painter.drawText(QPoint(xmin + padding_width, ymin - 2*padding_height), text); - } -} -void VideoOverlayWidget::render_text(QPainter& painter){ - const int width = this->width(); - const int height = this->height(); - for (const auto& item: *m_texts){ - painter.setPen(QColor((uint32_t)item.color)); - QFont text_font = this->font(); - text_font.setPointSizeF(item.font_size * height / 100.0); - painter.setFont(text_font); - - const int xmin = std::max((int)(width * item.x + 0.5), 1); - const int ymin = std::max((int)(height * item.y + 0.5), 1); - - painter.drawText(QPoint(xmin, ymin), QString::fromStdString(item.message)); - } -} -void VideoOverlayWidget::render_images(QPainter& painter){ - const double width = static_cast(this->width()); - const double height = static_cast(this->height()); - - for(const auto& image_overlay: *m_images){ - QImage q_image = image_overlay.image.to_QImage_ref(); - // source rect is the entire portion of the q_image, in pixel units - QRectF source_rect(0.0, 0.0, static_cast(q_image.width()), static_cast(q_image.height())); - // build a target_rect. target_rect is what region the overlay image should appear inside the overlay viewport. - // target_rect is in pixel units of the viewport - const double target_start_x = width * image_overlay.box.x; - const double target_start_y = height * image_overlay.box.y; - const double target_width = width * image_overlay.box.width; - const double target_height = height * image_overlay.box.height; - QRectF target_rect(target_start_x, target_start_y, target_width, target_height); - painter.drawImage(target_rect, q_image, source_rect); - } -} -void VideoOverlayWidget::render_log(QPainter& painter){ - if (m_log->empty()){ - return; - } - - const double LOG_MIN_X = 0.025; - const double LOG_WIDTH = 0.35; - const double LOG_FONT_SIZE = 0.04; - const double LOG_LINE_SPACING = 0.04; - const double LOG_BORDER_X = 0.009; - const double LOG_BORDER_Y = 0.016; - const double LOG_MAX_Y = 0.95; - - const double log_bg_height = VideoOverlaySession::LOG_MAX_LINES * LOG_LINE_SPACING + 2*LOG_BORDER_Y; - - int width = this->width(); - int height = this->height(); - - // Draw the box. - { - // set a semi-transparent dark color so that user can see the log lines while can also see - // vaguely the video stream content behind it - QColor box_color(10, 10, 10, 200); // r=g=b=10, alpha=200 - painter.setPen(box_color); - const int xmin = std::max((int)(width * LOG_MIN_X + 0.5), 1); - const int ymin = std::max((int)(height * (LOG_MAX_Y - log_bg_height) + 0.5), 1); - const int box_width = (int)(width * LOG_WIDTH + 0.5); - const int box_height = (int)(height * log_bg_height + 0.5); - painter.fillRect(xmin, ymin, box_width, box_height, box_color); - } - - // Draw the text lines. - double x = LOG_MIN_X + LOG_BORDER_X; - double y = LOG_MAX_Y - LOG_BORDER_Y; - for (const OverlayLogLine& item: *m_log){ - painter.setPen(QColor((uint32_t)item.color)); - QFont text_font = this->font(); - text_font.setPointSizeF(height * LOG_FONT_SIZE); - painter.setFont(text_font); - - const int xmin = std::max((int)(width * x + 0.5), 1); - const int ymin = std::max((int)(height * y + 0.5), 1); - - painter.drawText(QPoint(xmin, ymin), QString::fromStdString(item.message)); - - y -= LOG_LINE_SPACING; - } -} -void VideoOverlayWidget::render_stats(QPainter& painter){ - const double TEXT_SIZE = 0.02; - const double ROW_HEIGHT = 0.03; - - QColor box_color(10, 10, 10, 200); - painter.setPen(box_color); - - int width = this->width(); - int height = this->height(); - int start_x = (int)(width * 0.75); - - std::vector lines; - for (const auto& stat : *m_stats){ - OverlayStatSnapshot snapshot = stat->get_current(); - if (!snapshot.text.empty()){ - lines.emplace_back(std::move(snapshot)); - } - } - - - painter.fillRect( - start_x, - 0, - width - start_x, - (int)(height * (lines.size() * ROW_HEIGHT + 0.02)), - box_color - ); - - size_t c = 0; - for (const auto& stat : lines){ - painter.setPen(QColor((uint32_t)stat.color)); - - QFont text_font = this->font(); - text_font.setPointSizeF(height * TEXT_SIZE); - painter.setFont(text_font); - - int x = start_x + width * 0.01; - int y = height * ((c + 1) * ROW_HEIGHT + 0.005); - - painter.drawText(QPoint(x, y), QString::fromStdString(stat.text)); - - c++; - } -} - - - - - - - -} +/* Video Overlay + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/GlobalServices.h" +#include "VideoOverlayWidget.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ + + + +//const ImageFloatBox ENTIRE_VIDEO(0.0, 0.0, 1.0, 1.0); + + + +void VideoOverlayWidget::detach(){ + m_session.remove_listener(*this); + global_watchdog().remove(*this); +} +VideoOverlayWidget::~VideoOverlayWidget(){ + detach(); +} +VideoOverlayWidget::VideoOverlayWidget(QWidget& parent, VideoOverlaySession& session) + : QWidget(&parent) + , m_session(session) + , m_boxes(std::make_shared>(session.boxes())) + , m_texts(std::make_shared>(session.texts())) + , m_images(std::make_shared>(session.images())) + , m_log(std::make_shared>(session.log_texts())) + , m_stats(nullptr) +{ + setAttribute(Qt::WA_NoSystemBackground); + setAttribute(Qt::WA_TranslucentBackground); + setAttribute(Qt::WA_TransparentForMouseEvents); + +// m_boxes.insert(&ENTIRE_VIDEO); + try{ + global_watchdog().add(*this, std::chrono::milliseconds(50)); + m_session.add_listener(*this); + }catch (...){ + detach(); + throw; + } +} + +void VideoOverlayWidget::async_update(){ + // by using QMetaObject::invokeMethod, we can call this->update() on a non-main thread + // without trigger Qt crash, as normally this->update() can only be called on the main + // thread. + QMetaObject::invokeMethod(this, [this]{ this->update(); }); +} + +void VideoOverlayWidget::on_overlay_update_boxes(const std::shared_ptr>& boxes){ + WriteSpinLock lg(m_lock, "VideoOverlay::update_boxes()"); + m_boxes = boxes; +} +void VideoOverlayWidget::on_overlay_update_text(const std::shared_ptr>& texts){ + WriteSpinLock lg(m_lock, "VideoOverlay::update_text()"); + m_texts = texts; +} +void VideoOverlayWidget::on_overlay_update_images(const std::shared_ptr>& images){ + WriteSpinLock lg(m_lock, "VideoOverlay::update_images()"); + m_images = images; +} + +void VideoOverlayWidget::on_overlay_update_log(const std::shared_ptr>& logs){ + WriteSpinLock lg(m_lock, "VideoOverlay::update_log_text()"); + m_log = logs; +} +#if 0 +void VideoOverlayWidget::update_log_background(const std::shared_ptr>& bg_boxes){ + WriteSpinLock lg(m_lock, "VideoOverlay::update_log_background()"); + m_log_text_bg_boxes = bg_boxes; +} +#endif +void VideoOverlayWidget::on_overlay_update_stats(const std::list* stats){ + WriteSpinLock lg(m_lock, "VideoOverlay::update_stats()"); + m_stats = stats; +} + +void VideoOverlayWidget::on_watchdog_timeout(){ + QMetaObject::invokeMethod(this, [this]{ this->update(); }); +// static int c = 0; +// cout << "VideoOverlayWidget::on_watchdog_timeout(): " << c++ << endl; +} + + +void VideoOverlayWidget::resizeEvent(QResizeEvent* event){} + +void VideoOverlayWidget::paintEvent(QPaintEvent*){ + QPainter painter(this); + { + WriteSpinLock lg(m_lock, "VideoOverlay::paintEvent()"); + + if (m_session.enabled_boxes()){ + render_boxes(painter); + } + if (m_session.enabled_text()){ + render_text(painter); + } + if (m_session.enabled_images()){ + render_images(painter); + } + if (m_session.enabled_log()){ + render_log(painter); + } + if (m_session.enabled_stats() && m_stats){ + render_stats(painter); + } + } + + global_watchdog().delay(*this); +} + + +void VideoOverlayWidget::render_boxes(QPainter& painter){ + const int width = this->width(); + const int height = this->height(); + for (const auto& item : *m_boxes){ + QColor color = QColor((uint32_t)item.color); + painter.setPen(color); +// cout << box->x << " " << box->y << ", " << box->width << " x " << box->height << endl; +// cout << (int)(width * box->x + 0.5) +// << " " << (int)(height * box->y + 0.5) +// << ", " << (int)(width * box->width + 0.5) +// << " x " << (int)(height * box->height + 0.5) << endl; +// cout << painter.pen().width() << endl; + + // Compute coordinates. Clip so that it stays in-bounds. + int xmin = std::max((int)(width * item.box.x + 0.5), 1); + int ymin = std::max((int)(height * item.box.y + 0.5), 1); +// int xmax = std::min(xmin + (int)(width * box->width + 0.5), width - painter.pen().width()); +// int ymax = std::min(ymin + (int)(height * box->height + 0.5), height - painter.pen().width()); + int xmax = std::min(xmin + (int)(width * item.box.width + 0.5), width - 1); + int ymax = std::min(ymin + (int)(height * item.box.height + 0.5), height - 1); + +// cout << "m_video_size.width() = " << m_widget_size.width() << ", xmax = " << xmax << endl; + + painter.drawRect( + xmin, + ymin, + xmax - xmin, + ymax - ymin + ); + + + // Draw the label. + + if (item.label.empty()){ + continue; + } + + QString text = QString::fromStdString(item.label); + + QFont text_font = this->font(); + text_font.setPointSizeF((int)(height * 0.015)); + painter.setFont(text_font); + + QRect br = painter.boundingRect(0, 0, width, height, 0, text); +// cout << br.x() << " " << br.y() << " : " << br.width() << " " << br.height() << endl; + + int padding_width = (int)(width * 0.005); + int padding_height = (int)(height * 0.004); + + int box_height = 3*padding_height + (int)(height * 0.02); + int box_width = 2*padding_width + br.width(); + + if (ymin - box_height < 0){ + ymin += box_height; + } + + painter.fillRect( + xmin, + std::max(ymin - box_height, 0), + box_width, + box_height, + color + ); + + uint32_t red = ((uint32_t)item.color >> 16) & 0xff; + uint32_t green = ((uint32_t)item.color >> 8) & 0xff; + uint32_t blue = ((uint32_t)item.color >> 0) & 0xff; + + double brightness = 0.299*red + 0.587*green + 0.114*blue; + if (brightness > 128){ + painter.setPen(QColor(0xff000000)); + }else{ + painter.setPen(QColor(0xffffffff)); + } + + painter.drawText(QPoint(xmin + padding_width, ymin - 2*padding_height), text); + } +} +void VideoOverlayWidget::render_text(QPainter& painter){ + const int width = this->width(); + const int height = this->height(); + for (const auto& item: *m_texts){ + painter.setPen(QColor((uint32_t)item.color)); + QFont text_font = this->font(); + text_font.setPointSizeF(item.font_size * height / 100.0); + painter.setFont(text_font); + + const int xmin = std::max((int)(width * item.x + 0.5), 1); + const int ymin = std::max((int)(height * item.y + 0.5), 1); + + painter.drawText(QPoint(xmin, ymin), QString::fromStdString(item.message)); + } +} +void VideoOverlayWidget::render_images(QPainter& painter){ + const double width = static_cast(this->width()); + const double height = static_cast(this->height()); + + for(const auto& image_overlay: *m_images){ + QImage q_image = image_overlay.image.to_QImage_ref(); + // source rect is the entire portion of the q_image, in pixel units + QRectF source_rect(0.0, 0.0, static_cast(q_image.width()), static_cast(q_image.height())); + // build a target_rect. target_rect is what region the overlay image should appear inside the overlay viewport. + // target_rect is in pixel units of the viewport + const double target_start_x = width * image_overlay.box.x; + const double target_start_y = height * image_overlay.box.y; + const double target_width = width * image_overlay.box.width; + const double target_height = height * image_overlay.box.height; + QRectF target_rect(target_start_x, target_start_y, target_width, target_height); + painter.drawImage(target_rect, q_image, source_rect); + } +} +void VideoOverlayWidget::render_log(QPainter& painter){ + if (m_log->empty()){ + return; + } + + const double LOG_MIN_X = 0.025; + const double LOG_WIDTH = 0.35; + const double LOG_FONT_SIZE = 0.04; + const double LOG_LINE_SPACING = 0.04; + const double LOG_BORDER_X = 0.009; + const double LOG_BORDER_Y = 0.016; + const double LOG_MAX_Y = 0.95; + + const double log_bg_height = VideoOverlaySession::LOG_MAX_LINES * LOG_LINE_SPACING + 2*LOG_BORDER_Y; + + int width = this->width(); + int height = this->height(); + + // Draw the box. + { + // set a semi-transparent dark color so that user can see the log lines while can also see + // vaguely the video stream content behind it + QColor box_color(10, 10, 10, 200); // r=g=b=10, alpha=200 + painter.setPen(box_color); + const int xmin = std::max((int)(width * LOG_MIN_X + 0.5), 1); + const int ymin = std::max((int)(height * (LOG_MAX_Y - log_bg_height) + 0.5), 1); + const int box_width = (int)(width * LOG_WIDTH + 0.5); + const int box_height = (int)(height * log_bg_height + 0.5); + painter.fillRect(xmin, ymin, box_width, box_height, box_color); + } + + // Draw the text lines. + double x = LOG_MIN_X + LOG_BORDER_X; + double y = LOG_MAX_Y - LOG_BORDER_Y; + for (const OverlayLogLine& item: *m_log){ + painter.setPen(QColor((uint32_t)item.color)); + QFont text_font = this->font(); + text_font.setPointSizeF(height * LOG_FONT_SIZE); + painter.setFont(text_font); + + const int xmin = std::max((int)(width * x + 0.5), 1); + const int ymin = std::max((int)(height * y + 0.5), 1); + + painter.drawText(QPoint(xmin, ymin), QString::fromStdString(item.message)); + + y -= LOG_LINE_SPACING; + } +} +void VideoOverlayWidget::render_stats(QPainter& painter){ + const double TEXT_SIZE = 0.02; + const double ROW_HEIGHT = 0.03; + + QColor box_color(10, 10, 10, 200); + painter.setPen(box_color); + + int width = this->width(); + int height = this->height(); + int start_x = (int)(width * 0.75); + + std::vector lines; + for (const auto& stat : *m_stats){ + OverlayStatSnapshot snapshot = stat->get_current(); + if (!snapshot.text.empty()){ + lines.emplace_back(std::move(snapshot)); + } + } + + + painter.fillRect( + start_x, + 0, + width - start_x, + (int)(height * (lines.size() * ROW_HEIGHT + 0.02)), + box_color + ); + + size_t c = 0; + for (const auto& stat : lines){ + painter.setPen(QColor((uint32_t)stat.color)); + + QFont text_font = this->font(); + text_font.setPointSizeF(height * TEXT_SIZE); + painter.setFont(text_font); + + int x = start_x + width * 0.01; + int y = height * ((c + 1) * ROW_HEIGHT + 0.005); + + painter.drawText(QPoint(x, y), QString::fromStdString(stat.text)); + + c++; + } +} + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h index 7174894cfe..667ca3f73e 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h @@ -1,98 +1,98 @@ -/* Video Overlay Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoOverlayWidget_H -#define PokemonAutomation_VideoPipeline_VideoOverlayWidget_H - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/Watchdog.h" -#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" - -namespace PokemonAutomation{ - -struct OverlayText; - -class VideoOverlayWidget : public QWidget, private VideoOverlaySession::ContentListener, private WatchdogCallback{ -public: - static constexpr bool DEFAULT_ENABLE_BOXES = true; - static constexpr bool DEFAULT_ENABLE_TEXT = true; - static constexpr bool DEFAULT_ENABLE_IMAGES = true; - static constexpr bool DEFAULT_ENABLE_LOG = false; - static constexpr bool DEFAULT_ENABLE_STATS = true; - -public: - ~VideoOverlayWidget(); - VideoOverlayWidget(QWidget& parent, VideoOverlaySession& session); - -private: - void detach(); - - // Asynchronous changes to the overlays. - - // callback function from VideoOverlaySession on overlay boxes enabled - virtual void on_overlay_enabled_boxes (bool enabled) override{async_update();} - // callback function from VideoOverlaySession on overlay text enabled - virtual void on_overlay_enabled_text (bool enabled) override{async_update();} - // callback function from VideoOverlaySession on overlay images enabled - virtual void on_overlay_enabled_images(bool enabled) override{async_update();} - // callback function from VideoOverlaySession on overlay log enabled - virtual void on_overlay_enabled_log (bool enabled) override{async_update();} - // callback function from VideoOverlaySession on overlay stats enabled - virtual void on_overlay_enabled_stats (bool enabled) override{async_update();} - - // callback function from VideoOverlaySession on overlay boxes updated - virtual void on_overlay_update_boxes (const std::shared_ptr>& boxes) override; - // callback function from VideoOverlaySession on overlay text updated - virtual void on_overlay_update_text (const std::shared_ptr>& texts) override; - // callback function from VideoOverlaySession on overlay images updated - virtual void on_overlay_update_images(const std::shared_ptr>& images) override; - // callback function from VideoOverlaySession on overlay images updated - virtual void on_overlay_update_log (const std::shared_ptr>& logs) override; - // callback function from VideoOverlaySession on overlay stats updated - virtual void on_overlay_update_stats (const std::list* stats) override; - - virtual void on_watchdog_timeout() override; - - virtual void resizeEvent(QResizeEvent* event) override; - // render video overlay, override QWidget::paintEvent() - virtual void paintEvent(QPaintEvent*) override; - -private: - // Call QWidget::update() to notify Qt to schedule a re-rendering of the overlay widget. - // - // Threads other than the main thread may change video overlay, causing this VideoOverlayWidget, which - // listens to video overlay change, to get called on the non-main thread. - // Since QWidget::update() must be called on the main thread to not crash, we have to use this - // async_update() to avoid that. - void async_update(); - - // render overlay boxes - void render_boxes (QPainter& painter); - // render overlay texts - void render_text (QPainter& painter); - // render overlay images - void render_images (QPainter& painter); - // render overlay log lines - void render_log (QPainter& painter); - // render overlay stats - void render_stats (QPainter& painter); - -private: - VideoOverlaySession& m_session; - - SpinLock m_lock; - std::shared_ptr> m_boxes; - std::shared_ptr> m_texts; - std::shared_ptr> m_images; - std::shared_ptr> m_log; - const std::list* m_stats; -}; - - -} -#endif - +/* Video Overlay Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoOverlayWidget_H +#define PokemonAutomation_VideoPipeline_VideoOverlayWidget_H + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/Watchdog.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" + +namespace PokemonAutomation{ + +struct OverlayText; + +class VideoOverlayWidget : public QWidget, private VideoOverlaySession::ContentListener, private WatchdogCallback{ +public: + static constexpr bool DEFAULT_ENABLE_BOXES = true; + static constexpr bool DEFAULT_ENABLE_TEXT = true; + static constexpr bool DEFAULT_ENABLE_IMAGES = true; + static constexpr bool DEFAULT_ENABLE_LOG = false; + static constexpr bool DEFAULT_ENABLE_STATS = true; + +public: + ~VideoOverlayWidget(); + VideoOverlayWidget(QWidget& parent, VideoOverlaySession& session); + +private: + void detach(); + + // Asynchronous changes to the overlays. + + // callback function from VideoOverlaySession on overlay boxes enabled + virtual void on_overlay_enabled_boxes (bool enabled) override{async_update();} + // callback function from VideoOverlaySession on overlay text enabled + virtual void on_overlay_enabled_text (bool enabled) override{async_update();} + // callback function from VideoOverlaySession on overlay images enabled + virtual void on_overlay_enabled_images(bool enabled) override{async_update();} + // callback function from VideoOverlaySession on overlay log enabled + virtual void on_overlay_enabled_log (bool enabled) override{async_update();} + // callback function from VideoOverlaySession on overlay stats enabled + virtual void on_overlay_enabled_stats (bool enabled) override{async_update();} + + // callback function from VideoOverlaySession on overlay boxes updated + virtual void on_overlay_update_boxes (const std::shared_ptr>& boxes) override; + // callback function from VideoOverlaySession on overlay text updated + virtual void on_overlay_update_text (const std::shared_ptr>& texts) override; + // callback function from VideoOverlaySession on overlay images updated + virtual void on_overlay_update_images(const std::shared_ptr>& images) override; + // callback function from VideoOverlaySession on overlay images updated + virtual void on_overlay_update_log (const std::shared_ptr>& logs) override; + // callback function from VideoOverlaySession on overlay stats updated + virtual void on_overlay_update_stats (const std::list* stats) override; + + virtual void on_watchdog_timeout() override; + + virtual void resizeEvent(QResizeEvent* event) override; + // render video overlay, override QWidget::paintEvent() + virtual void paintEvent(QPaintEvent*) override; + +private: + // Call QWidget::update() to notify Qt to schedule a re-rendering of the overlay widget. + // + // Threads other than the main thread may change video overlay, causing this VideoOverlayWidget, which + // listens to video overlay change, to get called on the non-main thread. + // Since QWidget::update() must be called on the main thread to not crash, we have to use this + // async_update() to avoid that. + void async_update(); + + // render overlay boxes + void render_boxes (QPainter& painter); + // render overlay texts + void render_text (QPainter& painter); + // render overlay images + void render_images (QPainter& painter); + // render overlay log lines + void render_log (QPainter& painter); + // render overlay stats + void render_stats (QPainter& painter); + +private: + VideoOverlaySession& m_session; + + SpinLock m_lock; + std::shared_ptr> m_boxes; + std::shared_ptr> m_texts; + std::shared_ptr> m_images; + std::shared_ptr> m_log; + const std::list* m_stats; +}; + + +} +#endif + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp index 92707c8730..28e924ace6 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.cpp @@ -1,164 +1,164 @@ -/* Video Source Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" -#include "VideoSourceSelectorWidget.h" - -#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h" -#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -VideoSourceSelectorWidget::~VideoSourceSelectorWidget(){ - m_session.remove_state_listener(*this); -} -VideoSourceSelectorWidget::VideoSourceSelectorWidget(Logger& logger, VideoSession& session) - : m_logger(logger) - , m_session(session) -{ - QHBoxLayout* camera_row = new QHBoxLayout(this); - camera_row->setContentsMargins(0, 0, 0, 0); - - camera_row->addWidget(new QLabel("Video Input:", this), 1); - camera_row->addSpacing(5); - - m_sources_box = new NoWheelComboBox(this); - m_sources_box->setMaxVisibleItems(20); - camera_row->addWidget(m_sources_box, 5); - camera_row->addSpacing(5); - - m_resolution_box = new NoWheelComboBox(this); - m_resolution_box->setMaxVisibleItems(20); - camera_row->addWidget(m_resolution_box, 3); - camera_row->addSpacing(5); - - m_reset_button = new QPushButton("Reset Video", this); - camera_row->addWidget(m_reset_button, 1); - - update_source_list(); - update_resolution_list(); - - connect( - m_sources_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (0 <= index && index < (int)m_sources.size()){ - m_sources[index]->run_post_select(); - m_session.set_source(m_sources[index]); - }else{ - m_session.set_source(std::make_unique()); - } - } - ); - connect( - m_resolution_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0 || index >= (int)m_resolutions.size()){ - return; - } - Resolution resolution = m_resolutions[index]; - m_session.set_resolution(resolution); - } - ); - connect( - m_reset_button, &QPushButton::clicked, - this, [this](bool){ - update_source_list(); - m_session.reset(); - } - ); - - m_session.add_state_listener(*this); -} - - - - -void VideoSourceSelectorWidget::update_source_list(){ - m_sources_box->clear(); - m_sources.clear(); - - std::shared_ptr current_descriptor = m_session.descriptor(); - - // Add all the static options. - { - VideoSourceOption option; - m_session.get(option); - m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::None)); - m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::StillImage)); - } - - // Now add all the cameras. - for (const CameraInfo& info : get_all_cameras()){ - m_sources.emplace_back(std::make_unique(info)); - } - - int index = -1; - for (int c = 0; c < (int)m_sources.size(); c++){ - const VideoSourceDescriptor& descriptor = *m_sources[c]; - m_sources_box->addItem(QString::fromStdString(descriptor.display_name())); - if (*current_descriptor == descriptor){ - index = c; - } - } - if (index >= 0){ - m_sources_box->setCurrentIndex((int)index); - }else{ - m_logger.log("Unable to find entry for this source.", COLOR_RED); - } -} -void VideoSourceSelectorWidget::update_resolution_list(){ - m_resolution_box->clear(); - - Resolution camera_resolution = m_session.current_resolution(); - m_resolutions = m_session.supported_resolutions(); - - int index = -1; - for (int c = 0; c < (int)m_resolutions.size(); c++){ - const Resolution& size = m_resolutions[c]; - m_resolution_box->addItem( - QString::fromStdString( - std::to_string(size.width) + " x " + - std::to_string(size.height) + " " + - aspect_ratio_as_string(size) - ) - ); - if (size == camera_resolution){ - index = c; - } - } - if (index >= 0){ - m_resolution_box->setCurrentIndex(index); - }else{ - m_logger.log("Unable to find entry for this resolution.", COLOR_RED); - } -} - - - - -void VideoSourceSelectorWidget::post_startup(VideoSource* source){ - update_source_list(); - update_resolution_list(); -} - - - - - - - - -} +/* Video Source Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" +#include "VideoSourceSelectorWidget.h" + +#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h" +#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +VideoSourceSelectorWidget::~VideoSourceSelectorWidget(){ + m_session.remove_state_listener(*this); +} +VideoSourceSelectorWidget::VideoSourceSelectorWidget(Logger& logger, VideoSession& session) + : m_logger(logger) + , m_session(session) +{ + QHBoxLayout* camera_row = new QHBoxLayout(this); + camera_row->setContentsMargins(0, 0, 0, 0); + + camera_row->addWidget(new QLabel("Video Input:", this), 1); + camera_row->addSpacing(5); + + m_sources_box = new NoWheelComboBox(this); + m_sources_box->setMaxVisibleItems(20); + camera_row->addWidget(m_sources_box, 5); + camera_row->addSpacing(5); + + m_resolution_box = new NoWheelComboBox(this); + m_resolution_box->setMaxVisibleItems(20); + camera_row->addWidget(m_resolution_box, 3); + camera_row->addSpacing(5); + + m_reset_button = new QPushButton("Reset Video", this); + camera_row->addWidget(m_reset_button, 1); + + update_source_list(); + update_resolution_list(); + + connect( + m_sources_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (0 <= index && index < (int)m_sources.size()){ + m_sources[index]->run_post_select(); + m_session.set_source(m_sources[index]); + }else{ + m_session.set_source(std::make_unique()); + } + } + ); + connect( + m_resolution_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0 || index >= (int)m_resolutions.size()){ + return; + } + Resolution resolution = m_resolutions[index]; + m_session.set_resolution(resolution); + } + ); + connect( + m_reset_button, &QPushButton::clicked, + this, [this](bool){ + update_source_list(); + m_session.reset(); + } + ); + + m_session.add_state_listener(*this); +} + + + + +void VideoSourceSelectorWidget::update_source_list(){ + m_sources_box->clear(); + m_sources.clear(); + + std::shared_ptr current_descriptor = m_session.descriptor(); + + // Add all the static options. + { + VideoSourceOption option; + m_session.get(option); + m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::None)); + m_sources.emplace_back(option.get_descriptor_from_cache(VideoSourceType::StillImage)); + } + + // Now add all the cameras. + for (const CameraInfo& info : get_all_cameras()){ + m_sources.emplace_back(std::make_unique(info)); + } + + int index = -1; + for (int c = 0; c < (int)m_sources.size(); c++){ + const VideoSourceDescriptor& descriptor = *m_sources[c]; + m_sources_box->addItem(QString::fromStdString(descriptor.display_name())); + if (*current_descriptor == descriptor){ + index = c; + } + } + if (index >= 0){ + m_sources_box->setCurrentIndex((int)index); + }else{ + m_logger.log("Unable to find entry for this source.", COLOR_RED); + } +} +void VideoSourceSelectorWidget::update_resolution_list(){ + m_resolution_box->clear(); + + Resolution camera_resolution = m_session.current_resolution(); + m_resolutions = m_session.supported_resolutions(); + + int index = -1; + for (int c = 0; c < (int)m_resolutions.size(); c++){ + const Resolution& size = m_resolutions[c]; + m_resolution_box->addItem( + QString::fromStdString( + std::to_string(size.width) + " x " + + std::to_string(size.height) + " " + + aspect_ratio_as_string(size) + ) + ); + if (size == camera_resolution){ + index = c; + } + } + if (index >= 0){ + m_resolution_box->setCurrentIndex(index); + }else{ + m_logger.log("Unable to find entry for this resolution.", COLOR_RED); + } +} + + + + +void VideoSourceSelectorWidget::post_startup(VideoSource* source){ + update_source_list(); + update_resolution_list(); +} + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h index 3322ab97df..74c79c4a3e 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h @@ -1,50 +1,50 @@ -/* Video Source Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H -#define PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoSession.h" - -class QComboBox; -class QPushButton; - -namespace PokemonAutomation{ - - - -class VideoSourceSelectorWidget : public QWidget, public VideoSession::StateListener{ -public: - ~VideoSourceSelectorWidget(); - VideoSourceSelectorWidget(Logger& logger, VideoSession& session); - - -private: - void update_source_list(); - void update_resolution_list(); - - virtual void post_startup(VideoSource* source) override; - - -private: - Logger& m_logger; - VideoSession& m_session; - - QComboBox* m_sources_box; - QComboBox* m_resolution_box; - QPushButton* m_reset_button; - - std::vector> m_sources; - std::vector m_resolutions; - -}; - - - -} -#endif +/* Video Source Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H +#define PokemonAutomation_VideoPipeline_VideoSourceSelectorWidget_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoSession.h" + +class QComboBox; +class QPushButton; + +namespace PokemonAutomation{ + + + +class VideoSourceSelectorWidget : public QWidget, public VideoSession::StateListener{ +public: + ~VideoSourceSelectorWidget(); + VideoSourceSelectorWidget(Logger& logger, VideoSession& session); + + +private: + void update_source_list(); + void update_resolution_list(); + + virtual void post_startup(VideoSource* source) override; + + +private: + Logger& m_logger; + VideoSession& m_session; + + QComboBox* m_sources_box; + QComboBox* m_resolution_box; + QPushButton* m_reset_button; + + std::vector> m_sources; + std::vector m_resolutions; + +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h index fc20b9c8dc..17f0477477 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoFeed.h @@ -1,83 +1,83 @@ -/* Video Feed Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoFeedInterface_H -#define PokemonAutomation_VideoFeedInterface_H - -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - -struct VideoSnapshot{ - // The frame itself. Null means no snapshot was available. - std::shared_ptr frame; - - // The timestamp of when the frame was taken. - // This will be as close as possible to when the frame was taken. - WallClock timestamp = WallClock::min(); - - VideoSnapshot() - : frame(std::make_shared()) - , timestamp(WallClock::min()) - {} - VideoSnapshot(ImageRGB32 p_frame, WallClock p_timestamp) - : frame(std::make_shared(std::move(p_frame))) - , timestamp(p_timestamp) - {} - - // Returns true if the snapshot is valid. - explicit operator bool() const{ return frame && *frame; } - - const ImageRGB32* operator->() const{ return frame.get(); } - - operator std::shared_ptr() const{ return frame; } - operator ImageViewRGB32() const{ return *frame; } - - void clear(){ - frame.reset(); - timestamp = WallClock::min(); - } -}; - - -// Experimental: -// This video frame callback isn't guaranteed to be supported by all -// implementations. Unsupported implementations will never fire this callback. -class VideoFrame; -struct VideoFrameListener{ - virtual void on_frame(std::shared_ptr frame) = 0; -}; - - -// Define basic interface of a video feed to be used by programs. -class VideoFeed{ -public: - virtual void add_frame_listener(VideoFrameListener& listener) = 0; - virtual void remove_frame_listener(VideoFrameListener& listener) = 0; - - // Reset the video. Note that this may return early. - virtual void reset() = 0; - - // Do not call this on the main thread or it may deadlock. - virtual VideoSnapshot snapshot() = 0; - - // Returns the currently measured frames/second for the video source + display. - // Use this for diagnostic purposes. - virtual double fps_source() const = 0; - virtual double fps_display() const = 0; -}; - - - - - - - -} -#endif +/* Video Feed Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoFeedInterface_H +#define PokemonAutomation_VideoFeedInterface_H + +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + +struct VideoSnapshot{ + // The frame itself. Null means no snapshot was available. + std::shared_ptr frame; + + // The timestamp of when the frame was taken. + // This will be as close as possible to when the frame was taken. + WallClock timestamp = WallClock::min(); + + VideoSnapshot() + : frame(std::make_shared()) + , timestamp(WallClock::min()) + {} + VideoSnapshot(ImageRGB32 p_frame, WallClock p_timestamp) + : frame(std::make_shared(std::move(p_frame))) + , timestamp(p_timestamp) + {} + + // Returns true if the snapshot is valid. + explicit operator bool() const{ return frame && *frame; } + + const ImageRGB32* operator->() const{ return frame.get(); } + + operator std::shared_ptr() const{ return frame; } + operator ImageViewRGB32() const{ return *frame; } + + void clear(){ + frame.reset(); + timestamp = WallClock::min(); + } +}; + + +// Experimental: +// This video frame callback isn't guaranteed to be supported by all +// implementations. Unsupported implementations will never fire this callback. +class VideoFrame; +struct VideoFrameListener{ + virtual void on_frame(std::shared_ptr frame) = 0; +}; + + +// Define basic interface of a video feed to be used by programs. +class VideoFeed{ +public: + virtual void add_frame_listener(VideoFrameListener& listener) = 0; + virtual void remove_frame_listener(VideoFrameListener& listener) = 0; + + // Reset the video. Note that this may return early. + virtual void reset() = 0; + + // Do not call this on the main thread or it may deadlock. + virtual VideoSnapshot snapshot() = 0; + + // Returns the currently measured frames/second for the video source + display. + // Use this for diagnostic purposes. + virtual double fps_source() const = 0; + virtual double fps_display() const = 0; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp index 73adafd9f2..3f64ddfe28 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.cpp @@ -1,47 +1,47 @@ -/* Video Overlay - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "VideoOverlay.h" - -namespace PokemonAutomation{ - - - -struct VideoOverlay::Data{ - ListenerSet m_listeners; -}; - - -VideoOverlay::VideoOverlay() - : m_data(CONSTRUCT_TOKEN) -{} -VideoOverlay::~VideoOverlay() = default; - - - -void VideoOverlay::add_listener(MouseListener& listener){ - m_data->m_listeners.add(listener); -} -void VideoOverlay::remove_listener(MouseListener& listener){ - m_data->m_listeners.remove(listener); -} -void VideoOverlay::issue_mouse_press(double x, double y){ - m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_press, x, y); -} -void VideoOverlay::issue_mouse_release(double x, double y){ - m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_release, x, y); -} -void VideoOverlay::issue_mouse_move(double x, double y){ - m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_move, x, y); -} - - - - - -} +/* Video Overlay + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "VideoOverlay.h" + +namespace PokemonAutomation{ + + + +struct VideoOverlay::Data{ + ListenerSet m_listeners; +}; + + +VideoOverlay::VideoOverlay() + : m_data(CONSTRUCT_TOKEN) +{} +VideoOverlay::~VideoOverlay() = default; + + + +void VideoOverlay::add_listener(MouseListener& listener){ + m_data->m_listeners.add(listener); +} +void VideoOverlay::remove_listener(MouseListener& listener){ + m_data->m_listeners.remove(listener); +} +void VideoOverlay::issue_mouse_press(double x, double y){ + m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_press, x, y); +} +void VideoOverlay::issue_mouse_release(double x, double y){ + m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_release, x, y); +} +void VideoOverlay::issue_mouse_move(double x, double y){ + m_data->m_listeners.run_method_unique(&MouseListener::on_mouse_move, x, y); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.h index cfd715b468..865b0d3b34 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlay.h @@ -1,100 +1,100 @@ -/* Video Overlay - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoOverlaySet_H -#define PokemonAutomation_VideoOverlaySet_H - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "VideoOverlayTypes.h" - -namespace PokemonAutomation{ - -// Interface to add overlay objects (e.g. bounding boxes and texts) on top of rendered -// video stream -// The implementation is in CommonFramework/VideoPipeline/VideoOverlaySession.h:VideoOverlaySession -// The reason to create this interface is to reduce the header dependency on other code that relies -// on the overlay. -class VideoOverlay{ -public: - VideoOverlay(); - virtual ~VideoOverlay(); - -public: - // Asychronously, add an inference box as part of the video overlay. - // Once added, `box` cannot be destroyed until after `VideoOverlay::remove_box()` is called to remove it. - // If a `box` with the same address is added, it will override the old box's position, shape and color. You only need to - // call `remove_box()` once to remove it. - // - // Can use `InferenceBoxScope: public ImageFloatBox` to handle box removal automatically when it's destroyed. - // Can also use `VideoOverlay.h:VideoOverlaySet` to manage multiple boxes. - virtual void add_box(const OverlayBox& box) = 0; - - // Asychronously, remove an added inference box. - // The box must be already added. - // See `add_box()` for more info on managing boxes. - virtual void remove_box(const OverlayBox& box) = 0; - - // Asychronously, add a text, `OverlayText` as part of the video overlay. - // Once added, `text` cannot be destroyed until after `VideoOverlay::remove_text()` is called to remove it. - // If a `text` with the same address is added, it will override the old text's position, content and color. - // You only need to call `remove_text()` once to remove it. - // - // Can use `OverlayTextScope: public OverlayText` to handle text removal automatically when it's destroyed. - virtual void add_text(const OverlayText& text) = 0; - - // Asychronously, remove an added `OverlayText`. - // The OverlayText must be already added. - // See `add_text()` for more info on managing texts. - virtual void remove_text(const OverlayText& text) = 0; - - // Asychronously, add an image, `OverlayImage` as part of the video overlay. - // Allow transparency to create mask overlay. - // Once added, `image` cannot be destroyed until after `VideoOverlay::remove_image()` is called to remove it. - // If an `image` with the same address is added, it will override the old content. You only need - // to call `remove_text()` once to remove it. - virtual void add_image(const OverlayImage& image) = 0; - // Asychronously, remove an added `OverlayImage`. - // The OverlayImage must be already added. - // See `add_image()` for more info on managing overlay images. - virtual void remove_image(const OverlayImage& image) = 0; - - // Asynchronously, add a log message to the screen. The older messages added via `add_log_text()` - // will be placed higher like in the logging window. - // Use `OverlayLogTextScope` to remove the log messages automatically. - virtual void add_log(std::string message, Color color = COLOR_WHITE) = 0; - // Remove all messages added by `add_log_text()`. - // Use `OverlayLogTextScope` to remove log messages automatically. - virtual void clear_log() = 0; - - virtual void add_stat(OverlayStat& stat) = 0; - virtual void remove_stat(OverlayStat& stat) = 0; - - -public: - struct MouseListener{ - virtual void on_mouse_press(double x, double y){} - virtual void on_mouse_release(double x, double y){}; - virtual void on_mouse_move(double x, double y){}; - }; - void add_listener(MouseListener& listener); - void remove_listener(MouseListener& listener); - void issue_mouse_press(double x, double y); - void issue_mouse_release(double x, double y); - void issue_mouse_move(double x, double y); - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -#endif +/* Video Overlay + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoOverlaySet_H +#define PokemonAutomation_VideoOverlaySet_H + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "VideoOverlayTypes.h" + +namespace PokemonAutomation{ + +// Interface to add overlay objects (e.g. bounding boxes and texts) on top of rendered +// video stream +// The implementation is in CommonFramework/VideoPipeline/VideoOverlaySession.h:VideoOverlaySession +// The reason to create this interface is to reduce the header dependency on other code that relies +// on the overlay. +class VideoOverlay{ +public: + VideoOverlay(); + virtual ~VideoOverlay(); + +public: + // Asychronously, add an inference box as part of the video overlay. + // Once added, `box` cannot be destroyed until after `VideoOverlay::remove_box()` is called to remove it. + // If a `box` with the same address is added, it will override the old box's position, shape and color. You only need to + // call `remove_box()` once to remove it. + // + // Can use `InferenceBoxScope: public ImageFloatBox` to handle box removal automatically when it's destroyed. + // Can also use `VideoOverlay.h:VideoOverlaySet` to manage multiple boxes. + virtual void add_box(const OverlayBox& box) = 0; + + // Asychronously, remove an added inference box. + // The box must be already added. + // See `add_box()` for more info on managing boxes. + virtual void remove_box(const OverlayBox& box) = 0; + + // Asychronously, add a text, `OverlayText` as part of the video overlay. + // Once added, `text` cannot be destroyed until after `VideoOverlay::remove_text()` is called to remove it. + // If a `text` with the same address is added, it will override the old text's position, content and color. + // You only need to call `remove_text()` once to remove it. + // + // Can use `OverlayTextScope: public OverlayText` to handle text removal automatically when it's destroyed. + virtual void add_text(const OverlayText& text) = 0; + + // Asychronously, remove an added `OverlayText`. + // The OverlayText must be already added. + // See `add_text()` for more info on managing texts. + virtual void remove_text(const OverlayText& text) = 0; + + // Asychronously, add an image, `OverlayImage` as part of the video overlay. + // Allow transparency to create mask overlay. + // Once added, `image` cannot be destroyed until after `VideoOverlay::remove_image()` is called to remove it. + // If an `image` with the same address is added, it will override the old content. You only need + // to call `remove_text()` once to remove it. + virtual void add_image(const OverlayImage& image) = 0; + // Asychronously, remove an added `OverlayImage`. + // The OverlayImage must be already added. + // See `add_image()` for more info on managing overlay images. + virtual void remove_image(const OverlayImage& image) = 0; + + // Asynchronously, add a log message to the screen. The older messages added via `add_log_text()` + // will be placed higher like in the logging window. + // Use `OverlayLogTextScope` to remove the log messages automatically. + virtual void add_log(std::string message, Color color = COLOR_WHITE) = 0; + // Remove all messages added by `add_log_text()`. + // Use `OverlayLogTextScope` to remove log messages automatically. + virtual void clear_log() = 0; + + virtual void add_stat(OverlayStat& stat) = 0; + virtual void remove_stat(OverlayStat& stat) = 0; + + +public: + struct MouseListener{ + virtual void on_mouse_press(double x, double y){} + virtual void on_mouse_release(double x, double y){}; + virtual void on_mouse_move(double x, double y){}; + }; + void add_listener(MouseListener& listener); + void remove_listener(MouseListener& listener); + void issue_mouse_press(double x, double y); + void issue_mouse_release(double x, double y); + void issue_mouse_move(double x, double y); + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.cpp index d7d453e430..e03d5ad8a1 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.cpp @@ -1,67 +1,67 @@ -/* Video Overlay Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonObject.h" -#include "VideoOverlayOption.h" - -namespace PokemonAutomation{ - - - -const std::string VideoOverlayOption::JSON_BOXES = "Boxes"; -const std::string VideoOverlayOption::JSON_TEXT = "Text"; -const std::string VideoOverlayOption::JSON_IMAGES = "Images"; -const std::string VideoOverlayOption::JSON_LOG = "Log"; -const std::string VideoOverlayOption::JSON_STATS = "Stats"; - - -VideoOverlayOption::VideoOverlayOption() - : boxes(true) - , text(true) - , log(false) - , stats(true) -{} - - -void VideoOverlayOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - bool tmp; - if (obj->read_boolean(tmp, JSON_BOXES)){ - boxes.store(tmp, std::memory_order_relaxed); - } - if (obj->read_boolean(tmp, JSON_TEXT)){ - text.store(tmp, std::memory_order_relaxed); - } - if (obj->read_boolean(tmp, JSON_IMAGES)){ - images.store(tmp, std::memory_order_relaxed); - } else{ - // by default the image overlay is on - images.store(true, std::memory_order_relaxed); - } - if (obj->read_boolean(tmp, JSON_LOG)){ - log.store(tmp, std::memory_order_relaxed); - } - if (obj->read_boolean(tmp, JSON_STATS)){ - stats.store(tmp, std::memory_order_relaxed); - } -} -JsonValue VideoOverlayOption::to_json() const{ - JsonObject root; - root[JSON_BOXES] = boxes.load(std::memory_order_relaxed); - root[JSON_TEXT] = text.load(std::memory_order_relaxed); - root[JSON_IMAGES] = images.load(std::memory_order_relaxed); - root[JSON_LOG] = log.load(std::memory_order_relaxed); - root[JSON_STATS] = stats.load(std::memory_order_relaxed); - return root; -} - - - - -} +/* Video Overlay Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonObject.h" +#include "VideoOverlayOption.h" + +namespace PokemonAutomation{ + + + +const std::string VideoOverlayOption::JSON_BOXES = "Boxes"; +const std::string VideoOverlayOption::JSON_TEXT = "Text"; +const std::string VideoOverlayOption::JSON_IMAGES = "Images"; +const std::string VideoOverlayOption::JSON_LOG = "Log"; +const std::string VideoOverlayOption::JSON_STATS = "Stats"; + + +VideoOverlayOption::VideoOverlayOption() + : boxes(true) + , text(true) + , log(false) + , stats(true) +{} + + +void VideoOverlayOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + bool tmp; + if (obj->read_boolean(tmp, JSON_BOXES)){ + boxes.store(tmp, std::memory_order_relaxed); + } + if (obj->read_boolean(tmp, JSON_TEXT)){ + text.store(tmp, std::memory_order_relaxed); + } + if (obj->read_boolean(tmp, JSON_IMAGES)){ + images.store(tmp, std::memory_order_relaxed); + } else{ + // by default the image overlay is on + images.store(true, std::memory_order_relaxed); + } + if (obj->read_boolean(tmp, JSON_LOG)){ + log.store(tmp, std::memory_order_relaxed); + } + if (obj->read_boolean(tmp, JSON_STATS)){ + stats.store(tmp, std::memory_order_relaxed); + } +} +JsonValue VideoOverlayOption::to_json() const{ + JsonObject root; + root[JSON_BOXES] = boxes.load(std::memory_order_relaxed); + root[JSON_TEXT] = text.load(std::memory_order_relaxed); + root[JSON_IMAGES] = images.load(std::memory_order_relaxed); + root[JSON_LOG] = log.load(std::memory_order_relaxed); + root[JSON_STATS] = stats.load(std::memory_order_relaxed); + return root; +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.h index 69d6fb3b62..8b65e97528 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayOption.h @@ -1,44 +1,44 @@ -/* Video Overlay Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoOverlayOption_H -#define PokemonAutomation_VideoOverlayOption_H - -#include -#include - -namespace PokemonAutomation{ - -class JsonValue; - - -// store data related to the checkerboxes on UI: whether user enabled box overlay, -// text overlay, etc. -class VideoOverlayOption{ - static const std::string JSON_BOXES; - static const std::string JSON_TEXT; - static const std::string JSON_IMAGES; - static const std::string JSON_LOG; - static const std::string JSON_STATS; - -public: - VideoOverlayOption(); - - void load_json(const JsonValue& json); - JsonValue to_json() const; - -public: - std::atomic boxes; // whether user enabled box overlay - std::atomic text; // whether user enabled text overlay - std::atomic images; // whether user enabled image overlay - std::atomic log; // whether user enabled log overlay - std::atomic stats; // whether user enabled stats overlay -}; - - - -} -#endif +/* Video Overlay Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoOverlayOption_H +#define PokemonAutomation_VideoOverlayOption_H + +#include +#include + +namespace PokemonAutomation{ + +class JsonValue; + + +// store data related to the checkerboxes on UI: whether user enabled box overlay, +// text overlay, etc. +class VideoOverlayOption{ + static const std::string JSON_BOXES; + static const std::string JSON_TEXT; + static const std::string JSON_IMAGES; + static const std::string JSON_LOG; + static const std::string JSON_STATS; + +public: + VideoOverlayOption(); + + void load_json(const JsonValue& json); + JsonValue to_json() const; + +public: + std::atomic boxes; // whether user enabled box overlay + std::atomic text; // whether user enabled text overlay + std::atomic images; // whether user enabled image overlay + std::atomic log; // whether user enabled log overlay + std::atomic stats; // whether user enabled stats overlay +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayScopes.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayScopes.h index b36e9c9e63..b0772450e1 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayScopes.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayScopes.h @@ -1,192 +1,192 @@ -/* Video Overlay Scopes - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoOverlayScopes_H -#define PokemonAutomation_VideoOverlayScopes_H - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "VideoOverlay.h" - -namespace PokemonAutomation{ - - - -// A box as part of the video overlay. -// It handles its own life time on video overlay: once it's destroyed, it removes itself from VideoOverlay. -class OverlayBoxScope : public OverlayBox{ -public: - ~OverlayBoxScope(){ - m_overlay.remove_box(*this); - } - OverlayBoxScope(const OverlayBoxScope&) = delete; - void operator=(const OverlayBoxScope&) = delete; - -public: - OverlayBoxScope( - VideoOverlay& overlay, - Color color, - const ImageFloatBox& box, - std::string label - ) - : OverlayBox(color, box, std::move(label)) - , m_overlay(overlay) - { - overlay.add_box(*this); - } - - OverlayBoxScope( - VideoOverlay& overlay, - const ImageFloatBox& box, - Color color = COLOR_RED - ) - : OverlayBox(color, box, "") - , m_overlay(overlay) - { - overlay.add_box(*this); - } - -private: - VideoOverlay& m_overlay; -}; - - -// A text as part of the video overlay. -// It handles its own life time on video overlay: once it's destroyed, it removes itself from VideoOverlay. -class OverlayTextScope : public OverlayText{ - OverlayTextScope(const OverlayTextScope&) = delete; - void operator=(const OverlayTextScope&) = delete; - -public: - ~OverlayTextScope(){ - m_overlay.remove_text(*this); - } - -public: - OverlayTextScope( - VideoOverlay& overlay, - Color color, - std::string message, - double x, double y, double font_size - ) - : OverlayText(color, message, x, y, font_size) - , m_overlay(overlay) - { - overlay.add_text(*this); - } - -private: - VideoOverlay& m_overlay; -}; - - -// An image as part of the video overlay. -// It owns the image data and handles its own life time on video overlay: once it's destroyed, -// it removes itself from VideoOverlay. -class OverlayImageScope : public OverlayImage{ - OverlayImageScope(const OverlayImageScope&) = delete; - void operator=(const OverlayImageScope&) = delete; - -public: - ~OverlayImageScope(){ - m_overlay.remove_image(*this); - } - -public: - // the copied `image` is moved into OverlayImageScope - // so after this constructer, the caller can freely modify or delete `image`. - OverlayImageScope( - VideoOverlay& overlay, - ImageRGB32 image, - const ImageFloatBox& box - ) - : OverlayImage(ImageViewRGB32(), box) - , m_overlay(overlay) - , m_image_data(std::move(image)) - { - this->image = m_image_data; - overlay.add_image(*this); - } - - OverlayImageScope( - VideoOverlay& overlay, - ImageViewRGB32 image, - const ImageFloatBox& box - ) - : OverlayImage(ImageViewRGB32(), box) - , m_overlay(overlay) - , m_image_data(image.copy()) - { - this->image = m_image_data; - overlay.add_image(*this); - } - -private: - VideoOverlay& m_overlay; - // owns image content, in contrast to OverlayImage::image which is just a pointer - ImageRGB32 m_image_data; -}; - - - -// Used to clear log messages on video overlay automatically. -// Place this at the beginning of a program, so that when the program exits, it will -// clear the log messages from the overlay automatically. -class OverlayLogTextScope{ - OverlayLogTextScope(const OverlayLogTextScope&) = delete; - void operator=(const OverlayLogTextScope&) = delete; - -public: - OverlayLogTextScope(VideoOverlay& overlay) - : m_overlay(overlay) - {} - ~OverlayLogTextScope(){ - m_overlay.clear_log(); - } - -private: - VideoOverlay& m_overlay; -}; - - -// Used by video inference sessions to manage inference boxes. -// VideoOverlaySet will be passed to the inference callbacks in a session -// to store inference boxes. When the session ends, VideoOverlaySet::clear() -// is called to release those inference boxes. The boxes are also cleared -// automatically when VideoOverlaySet is destroyed. -// In this way, the user will see the inference boxes on the video overlay UI -// and those boxes will leave the UI after the session ends. -class VideoOverlaySet{ -public: - VideoOverlaySet(VideoOverlay& overlay) - : m_overlay(overlay) - {} - - void clear(){ - m_boxes.clear(); - m_images.clear(); - } - void add(Color color, const ImageFloatBox& box, std::string label = ""){ - m_boxes.emplace_back(m_overlay, color, box, std::move(label)); - } - void add(ImageRGB32 image, const ImageFloatBox& box){ - m_images.emplace_back(m_overlay, std::move(image), box); - } - void add(ImageViewRGB32 image, const ImageFloatBox& box){ - m_images.emplace_back(m_overlay, image, box); - } - -private: - VideoOverlay& m_overlay; - std::deque m_boxes; - std::deque m_images; -}; - - - - -} -#endif +/* Video Overlay Scopes + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoOverlayScopes_H +#define PokemonAutomation_VideoOverlayScopes_H + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "VideoOverlay.h" + +namespace PokemonAutomation{ + + + +// A box as part of the video overlay. +// It handles its own life time on video overlay: once it's destroyed, it removes itself from VideoOverlay. +class OverlayBoxScope : public OverlayBox{ +public: + ~OverlayBoxScope(){ + m_overlay.remove_box(*this); + } + OverlayBoxScope(const OverlayBoxScope&) = delete; + void operator=(const OverlayBoxScope&) = delete; + +public: + OverlayBoxScope( + VideoOverlay& overlay, + Color color, + const ImageFloatBox& box, + std::string label + ) + : OverlayBox(color, box, std::move(label)) + , m_overlay(overlay) + { + overlay.add_box(*this); + } + + OverlayBoxScope( + VideoOverlay& overlay, + const ImageFloatBox& box, + Color color = COLOR_RED + ) + : OverlayBox(color, box, "") + , m_overlay(overlay) + { + overlay.add_box(*this); + } + +private: + VideoOverlay& m_overlay; +}; + + +// A text as part of the video overlay. +// It handles its own life time on video overlay: once it's destroyed, it removes itself from VideoOverlay. +class OverlayTextScope : public OverlayText{ + OverlayTextScope(const OverlayTextScope&) = delete; + void operator=(const OverlayTextScope&) = delete; + +public: + ~OverlayTextScope(){ + m_overlay.remove_text(*this); + } + +public: + OverlayTextScope( + VideoOverlay& overlay, + Color color, + std::string message, + double x, double y, double font_size + ) + : OverlayText(color, message, x, y, font_size) + , m_overlay(overlay) + { + overlay.add_text(*this); + } + +private: + VideoOverlay& m_overlay; +}; + + +// An image as part of the video overlay. +// It owns the image data and handles its own life time on video overlay: once it's destroyed, +// it removes itself from VideoOverlay. +class OverlayImageScope : public OverlayImage{ + OverlayImageScope(const OverlayImageScope&) = delete; + void operator=(const OverlayImageScope&) = delete; + +public: + ~OverlayImageScope(){ + m_overlay.remove_image(*this); + } + +public: + // the copied `image` is moved into OverlayImageScope + // so after this constructer, the caller can freely modify or delete `image`. + OverlayImageScope( + VideoOverlay& overlay, + ImageRGB32 image, + const ImageFloatBox& box + ) + : OverlayImage(ImageViewRGB32(), box) + , m_overlay(overlay) + , m_image_data(std::move(image)) + { + this->image = m_image_data; + overlay.add_image(*this); + } + + OverlayImageScope( + VideoOverlay& overlay, + ImageViewRGB32 image, + const ImageFloatBox& box + ) + : OverlayImage(ImageViewRGB32(), box) + , m_overlay(overlay) + , m_image_data(image.copy()) + { + this->image = m_image_data; + overlay.add_image(*this); + } + +private: + VideoOverlay& m_overlay; + // owns image content, in contrast to OverlayImage::image which is just a pointer + ImageRGB32 m_image_data; +}; + + + +// Used to clear log messages on video overlay automatically. +// Place this at the beginning of a program, so that when the program exits, it will +// clear the log messages from the overlay automatically. +class OverlayLogTextScope{ + OverlayLogTextScope(const OverlayLogTextScope&) = delete; + void operator=(const OverlayLogTextScope&) = delete; + +public: + OverlayLogTextScope(VideoOverlay& overlay) + : m_overlay(overlay) + {} + ~OverlayLogTextScope(){ + m_overlay.clear_log(); + } + +private: + VideoOverlay& m_overlay; +}; + + +// Used by video inference sessions to manage inference boxes. +// VideoOverlaySet will be passed to the inference callbacks in a session +// to store inference boxes. When the session ends, VideoOverlaySet::clear() +// is called to release those inference boxes. The boxes are also cleared +// automatically when VideoOverlaySet is destroyed. +// In this way, the user will see the inference boxes on the video overlay UI +// and those boxes will leave the UI after the session ends. +class VideoOverlaySet{ +public: + VideoOverlaySet(VideoOverlay& overlay) + : m_overlay(overlay) + {} + + void clear(){ + m_boxes.clear(); + m_images.clear(); + } + void add(Color color, const ImageFloatBox& box, std::string label = ""){ + m_boxes.emplace_back(m_overlay, color, box, std::move(label)); + } + void add(ImageRGB32 image, const ImageFloatBox& box){ + m_images.emplace_back(m_overlay, std::move(image), box); + } + void add(ImageViewRGB32 image, const ImageFloatBox& box){ + m_images.emplace_back(m_overlay, image, box); + } + +private: + VideoOverlay& m_overlay; + std::deque m_boxes; + std::deque m_images; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.cpp index e1204e0a98..dd511ad8a4 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.cpp @@ -1,341 +1,341 @@ -/* Video Overlay Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "VideoOverlaySession.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ - - - -void VideoOverlaySession::add_listener(ContentListener& listener){ - WriteSpinLock lg(m_lock); - m_content_listeners.insert(&listener); - listener.on_overlay_update_stats(&m_stats_order); -} -void VideoOverlaySession::remove_listener(ContentListener& listener){ - WriteSpinLock lg(m_lock); -// listener.on_overlay_update_stats(nullptr); - m_content_listeners.erase(&listener); -} - - -VideoOverlaySession::~VideoOverlaySession(){ - ReadSpinLock lg(m_lock); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_stats(nullptr); - } -} -VideoOverlaySession::VideoOverlaySession(VideoOverlayOption& option) - : m_option(option) -{} - - -void VideoOverlaySession::get(VideoOverlayOption& option){ - bool boxes = m_option.boxes.load(std::memory_order_relaxed); - bool text = m_option.text.load(std::memory_order_relaxed); - bool images = m_option.images.load(std::memory_order_relaxed); - bool log = m_option.log.load(std::memory_order_relaxed); - bool stats = m_option.stats.load(std::memory_order_relaxed); - option.boxes.store(boxes, std::memory_order_relaxed); - option.text.store(text, std::memory_order_relaxed); - option.images.store(images, std::memory_order_relaxed); - option.log.store(log, std::memory_order_relaxed); - option.stats.store(stats, std::memory_order_relaxed); -} -void VideoOverlaySession::set(const VideoOverlayOption& option){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_boxes()"); - bool boxes = option.boxes.load(std::memory_order_relaxed); - bool text = option.text.load(std::memory_order_relaxed); - bool images = option.images.load(std::memory_order_relaxed); - bool log = option.log.load(std::memory_order_relaxed); - bool stats = option.stats.load(std::memory_order_relaxed); - m_option.boxes.store(boxes, std::memory_order_relaxed); - m_option.text.store(text, std::memory_order_relaxed); - m_option.images.store(images, std::memory_order_relaxed); - m_option.log.store(log, std::memory_order_relaxed); - m_option.stats.store(stats, std::memory_order_relaxed); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_enabled_boxes(boxes); - listener->on_overlay_enabled_text(text); - listener->on_overlay_enabled_images(images); - listener->on_overlay_enabled_log(log); - listener->on_overlay_enabled_stats(stats); - } -} - - -void VideoOverlaySession::set_enabled_boxes(bool enabled){ - m_option.boxes.store(enabled, std::memory_order_relaxed); - ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_boxes()"); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_enabled_boxes(enabled); - } -} -void VideoOverlaySession::set_enabled_text(bool enabled){ - m_option.text.store(enabled, std::memory_order_relaxed); - ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_text()"); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_enabled_text(enabled); - } -} -void VideoOverlaySession::set_enabled_images(bool enabled){ - m_option.images.store(enabled, std::memory_order_relaxed); - ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_images()"); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_enabled_images(enabled); - } -} -void VideoOverlaySession::set_enabled_log(bool enabled){ - m_option.log.store(enabled, std::memory_order_relaxed); - ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_log()"); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_enabled_log(enabled); - } -} -void VideoOverlaySession::set_enabled_stats(bool enabled){ - m_option.stats.store(enabled, std::memory_order_relaxed); - ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_stats()"); - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_enabled_stats(enabled); - } -} - - - -void VideoOverlaySession::add_box(const OverlayBox& box){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::add_box()"); - m_boxes.insert(&box); - push_box_update(); -} -void VideoOverlaySession::remove_box(const OverlayBox& box){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::remove_box()"); - m_boxes.erase(&box); - push_box_update(); -} - -void VideoOverlaySession::push_box_update(){ - if (m_content_listeners.empty()){ - return; - } - - // We create a newly allocated Box vector to avoid listener accessing - // `m_boxes` asynchronously. - std::shared_ptr> ptr = std::make_shared>(); - for (const auto& item : m_boxes){ - ptr->emplace_back(*item); - } - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_boxes(ptr); - } -} - -std::vector VideoOverlaySession::boxes() const{ - ReadSpinLock lg(m_lock); - std::vector ret; - for (const auto& item : m_boxes){ - ret.emplace_back(*item); - } - return ret; -} - -void VideoOverlaySession::add_text(const OverlayText& text){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::add_text()"); - m_texts.insert(&text); - push_text_update(); -} -void VideoOverlaySession::remove_text(const OverlayText& text){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::remove_text()"); - m_texts.erase(&text); - push_text_update(); -} - -void VideoOverlaySession::push_text_update(){ - if (m_content_listeners.empty()){ - return; - } - - // We create a newly allocated Box vector to avoid listener accessing - // `m_texts` asynchronously. - std::shared_ptr> ptr = std::make_shared>(); - for (const auto& item : m_texts){ - ptr->emplace_back(*item); - } - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_text(ptr); - } -} - -std::vector VideoOverlaySession::texts() const{ - ReadSpinLock lg(m_lock); - std::vector ret; - for (const auto& item : m_texts){ - ret.emplace_back(*item); - } - return ret; -} - - -void VideoOverlaySession::add_image(const OverlayImage& image){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::add_image()"); - m_images.insert(&image); - push_image_update(); -} -void VideoOverlaySession::remove_image(const OverlayImage& image){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::remove_image()"); - m_images.erase(&image); - push_image_update(); -} - -void VideoOverlaySession::push_image_update(){ - if (m_content_listeners.empty()){ - return; - } - - // We create a newly allocated Box vector to avoid listener accessing - // `m_images` asynchronously. - std::shared_ptr> ptr = std::make_shared>(); - for (const auto& item : m_images){ - ptr->emplace_back(*item); - } - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_images(ptr); - } -} - -std::vector VideoOverlaySession::images() const{ - ReadSpinLock lg(m_lock); - std::vector ret; - for (const auto& item : m_images){ - ret.emplace_back(*item); - } - return ret; -} - - -void VideoOverlaySession::add_log(std::string message, Color color){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::add_log_text()"); - m_log_texts.emplace_front(color, std::move(message)); - - if (m_log_texts.size() > LOG_MAX_LINES){ - m_log_texts.pop_back(); - } - - push_log_text_update(); -} - -void VideoOverlaySession::clear_log(){ - WriteSpinLock lg(m_lock, "VideoOverlaySession::clear_log_texts()"); - m_log_texts.clear(); - push_log_text_update(); -} - -void VideoOverlaySession::push_log_text_update(){ - if (m_content_listeners.empty()){ - return; - } - - // We create a newly allocated Box vector to avoid listener accessing - // `m_log_texts` asynchronously. - std::shared_ptr> ptr = std::make_shared>(); - for(const auto& item : m_log_texts){ - ptr->emplace_back(item); - } - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_log(ptr); - } -} - -std::vector VideoOverlaySession::log_texts() const{ - ReadSpinLock lg(m_lock); - std::vector ret; - for(const auto& item : m_log_texts){ - ret.emplace_back(item); - } - return ret; -} - - - - -void VideoOverlaySession::add_stat(OverlayStat& stat){ - WriteSpinLock lg(m_lock); - auto map_iter = m_stats.find(&stat); - if (map_iter != m_stats.end()){ - return; - } - - // Remove all stats so they aren't being referenced. - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_stats(nullptr); - } - - m_stats_order.emplace_back(&stat); - auto list_iter = m_stats_order.end(); - --list_iter; - try{ - m_stats.emplace(&stat, list_iter); - }catch (...){ - m_stats_order.pop_back(); - throw; - } - - // Add all the stats back. - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_stats(&m_stats_order); - } -} -void VideoOverlaySession::remove_stat(OverlayStat& stat){ - WriteSpinLock lg(m_lock); - auto iter = m_stats.find(&stat); - if (iter == m_stats.end()){ - return; - } - - // Remove all stats so they aren't being referenced. - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_stats(nullptr); - } - - m_stats_order.erase(iter->second); - m_stats.erase(iter); - - // Add all the stats back. - for (ContentListener* listener : m_content_listeners){ - listener->on_overlay_update_stats(&m_stats_order); - } -} - - - - - - - - - - - - - - - - - - - - - - - - - - - -} +/* Video Overlay Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "VideoOverlaySession.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ + + + +void VideoOverlaySession::add_listener(ContentListener& listener){ + WriteSpinLock lg(m_lock); + m_content_listeners.insert(&listener); + listener.on_overlay_update_stats(&m_stats_order); +} +void VideoOverlaySession::remove_listener(ContentListener& listener){ + WriteSpinLock lg(m_lock); +// listener.on_overlay_update_stats(nullptr); + m_content_listeners.erase(&listener); +} + + +VideoOverlaySession::~VideoOverlaySession(){ + ReadSpinLock lg(m_lock); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_stats(nullptr); + } +} +VideoOverlaySession::VideoOverlaySession(VideoOverlayOption& option) + : m_option(option) +{} + + +void VideoOverlaySession::get(VideoOverlayOption& option){ + bool boxes = m_option.boxes.load(std::memory_order_relaxed); + bool text = m_option.text.load(std::memory_order_relaxed); + bool images = m_option.images.load(std::memory_order_relaxed); + bool log = m_option.log.load(std::memory_order_relaxed); + bool stats = m_option.stats.load(std::memory_order_relaxed); + option.boxes.store(boxes, std::memory_order_relaxed); + option.text.store(text, std::memory_order_relaxed); + option.images.store(images, std::memory_order_relaxed); + option.log.store(log, std::memory_order_relaxed); + option.stats.store(stats, std::memory_order_relaxed); +} +void VideoOverlaySession::set(const VideoOverlayOption& option){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_boxes()"); + bool boxes = option.boxes.load(std::memory_order_relaxed); + bool text = option.text.load(std::memory_order_relaxed); + bool images = option.images.load(std::memory_order_relaxed); + bool log = option.log.load(std::memory_order_relaxed); + bool stats = option.stats.load(std::memory_order_relaxed); + m_option.boxes.store(boxes, std::memory_order_relaxed); + m_option.text.store(text, std::memory_order_relaxed); + m_option.images.store(images, std::memory_order_relaxed); + m_option.log.store(log, std::memory_order_relaxed); + m_option.stats.store(stats, std::memory_order_relaxed); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_enabled_boxes(boxes); + listener->on_overlay_enabled_text(text); + listener->on_overlay_enabled_images(images); + listener->on_overlay_enabled_log(log); + listener->on_overlay_enabled_stats(stats); + } +} + + +void VideoOverlaySession::set_enabled_boxes(bool enabled){ + m_option.boxes.store(enabled, std::memory_order_relaxed); + ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_boxes()"); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_enabled_boxes(enabled); + } +} +void VideoOverlaySession::set_enabled_text(bool enabled){ + m_option.text.store(enabled, std::memory_order_relaxed); + ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_text()"); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_enabled_text(enabled); + } +} +void VideoOverlaySession::set_enabled_images(bool enabled){ + m_option.images.store(enabled, std::memory_order_relaxed); + ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_images()"); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_enabled_images(enabled); + } +} +void VideoOverlaySession::set_enabled_log(bool enabled){ + m_option.log.store(enabled, std::memory_order_relaxed); + ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_log()"); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_enabled_log(enabled); + } +} +void VideoOverlaySession::set_enabled_stats(bool enabled){ + m_option.stats.store(enabled, std::memory_order_relaxed); + ReadSpinLock lg(m_lock, "VideoOverlaySession::set_enabled_stats()"); + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_enabled_stats(enabled); + } +} + + + +void VideoOverlaySession::add_box(const OverlayBox& box){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::add_box()"); + m_boxes.insert(&box); + push_box_update(); +} +void VideoOverlaySession::remove_box(const OverlayBox& box){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::remove_box()"); + m_boxes.erase(&box); + push_box_update(); +} + +void VideoOverlaySession::push_box_update(){ + if (m_content_listeners.empty()){ + return; + } + + // We create a newly allocated Box vector to avoid listener accessing + // `m_boxes` asynchronously. + std::shared_ptr> ptr = std::make_shared>(); + for (const auto& item : m_boxes){ + ptr->emplace_back(*item); + } + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_boxes(ptr); + } +} + +std::vector VideoOverlaySession::boxes() const{ + ReadSpinLock lg(m_lock); + std::vector ret; + for (const auto& item : m_boxes){ + ret.emplace_back(*item); + } + return ret; +} + +void VideoOverlaySession::add_text(const OverlayText& text){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::add_text()"); + m_texts.insert(&text); + push_text_update(); +} +void VideoOverlaySession::remove_text(const OverlayText& text){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::remove_text()"); + m_texts.erase(&text); + push_text_update(); +} + +void VideoOverlaySession::push_text_update(){ + if (m_content_listeners.empty()){ + return; + } + + // We create a newly allocated Box vector to avoid listener accessing + // `m_texts` asynchronously. + std::shared_ptr> ptr = std::make_shared>(); + for (const auto& item : m_texts){ + ptr->emplace_back(*item); + } + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_text(ptr); + } +} + +std::vector VideoOverlaySession::texts() const{ + ReadSpinLock lg(m_lock); + std::vector ret; + for (const auto& item : m_texts){ + ret.emplace_back(*item); + } + return ret; +} + + +void VideoOverlaySession::add_image(const OverlayImage& image){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::add_image()"); + m_images.insert(&image); + push_image_update(); +} +void VideoOverlaySession::remove_image(const OverlayImage& image){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::remove_image()"); + m_images.erase(&image); + push_image_update(); +} + +void VideoOverlaySession::push_image_update(){ + if (m_content_listeners.empty()){ + return; + } + + // We create a newly allocated Box vector to avoid listener accessing + // `m_images` asynchronously. + std::shared_ptr> ptr = std::make_shared>(); + for (const auto& item : m_images){ + ptr->emplace_back(*item); + } + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_images(ptr); + } +} + +std::vector VideoOverlaySession::images() const{ + ReadSpinLock lg(m_lock); + std::vector ret; + for (const auto& item : m_images){ + ret.emplace_back(*item); + } + return ret; +} + + +void VideoOverlaySession::add_log(std::string message, Color color){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::add_log_text()"); + m_log_texts.emplace_front(color, std::move(message)); + + if (m_log_texts.size() > LOG_MAX_LINES){ + m_log_texts.pop_back(); + } + + push_log_text_update(); +} + +void VideoOverlaySession::clear_log(){ + WriteSpinLock lg(m_lock, "VideoOverlaySession::clear_log_texts()"); + m_log_texts.clear(); + push_log_text_update(); +} + +void VideoOverlaySession::push_log_text_update(){ + if (m_content_listeners.empty()){ + return; + } + + // We create a newly allocated Box vector to avoid listener accessing + // `m_log_texts` asynchronously. + std::shared_ptr> ptr = std::make_shared>(); + for(const auto& item : m_log_texts){ + ptr->emplace_back(item); + } + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_log(ptr); + } +} + +std::vector VideoOverlaySession::log_texts() const{ + ReadSpinLock lg(m_lock); + std::vector ret; + for(const auto& item : m_log_texts){ + ret.emplace_back(item); + } + return ret; +} + + + + +void VideoOverlaySession::add_stat(OverlayStat& stat){ + WriteSpinLock lg(m_lock); + auto map_iter = m_stats.find(&stat); + if (map_iter != m_stats.end()){ + return; + } + + // Remove all stats so they aren't being referenced. + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_stats(nullptr); + } + + m_stats_order.emplace_back(&stat); + auto list_iter = m_stats_order.end(); + --list_iter; + try{ + m_stats.emplace(&stat, list_iter); + }catch (...){ + m_stats_order.pop_back(); + throw; + } + + // Add all the stats back. + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_stats(&m_stats_order); + } +} +void VideoOverlaySession::remove_stat(OverlayStat& stat){ + WriteSpinLock lg(m_lock); + auto iter = m_stats.find(&stat); + if (iter == m_stats.end()){ + return; + } + + // Remove all stats so they aren't being referenced. + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_stats(nullptr); + } + + m_stats_order.erase(iter->second); + m_stats.erase(iter); + + // Add all the stats back. + for (ContentListener* listener : m_content_listeners){ + listener->on_overlay_update_stats(&m_stats_order); + } +} + + + + + + + + + + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.h index d8212f5155..a445bd94d6 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlaySession.h @@ -1,160 +1,160 @@ -/* Video Overlay Session - * - * From: https://github.com/PokemonAutomation/ - * - * This class holds the real-time state of the video overlays. You can - * asychronously add/remove objects to it. - * - * This class is not responsible for any UI. However, any changes made to this - * class will be forwarded to any UI components that are attached to it. - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoOverlaySession_H -#define PokemonAutomation_VideoPipeline_VideoOverlaySession_H - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "VideoOverlay.h" -#include "VideoOverlayOption.h" - -namespace PokemonAutomation{ - -// This class holds the real-time state of the video overlays. You can -// asychronously add/remove objects to it. -// This class is not responsible for any UI. However, any changes made to this -// class will be forwarded to any UI components that are attached to it. -class VideoOverlaySession : public VideoOverlay{ -public: - static constexpr size_t LOG_MAX_LINES = 20; - -public: - // Video overlay UI class (e.g. VideoOverlayWidget) inherits this listener to listen - // to the overlay session. - struct ContentListener{ - // VideoOverlaySession will call these when they change. - - virtual void on_overlay_enabled_boxes (bool enabled){} - virtual void on_overlay_enabled_text (bool enabled){} - virtual void on_overlay_enabled_images (bool enabled){} - virtual void on_overlay_enabled_log (bool enabled){} - virtual void on_overlay_enabled_stats (bool enabled){} - - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_box(). - virtual void on_overlay_update_boxes (const std::shared_ptr>& boxes){} - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_text(). - virtual void on_overlay_update_text (const std::shared_ptr>& texts){} - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_image(). - virtual void on_overlay_update_images (const std::shared_ptr>& images){} - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_log(). - virtual void on_overlay_update_log (const std::shared_ptr>& boxes){} - - // This one is different from the others. The listeners will store this - // pointer and access it directly and asynchronously. If you need to - // change the structure of the list itself, you must first call this - // with null to remove it from all the listeners. Then add the updated - // one back when you're done. - // This is called immediately when attaching a listener to give the - // current stats. The listener must drop all references to the stats - // before detaching. - virtual void on_overlay_update_stats(const std::list* stats){} - - }; - - // Add a UI class to listen to any overlay change. The UI class needs to inherit Listener. - // Must call `remove_listener()` before listener is destroyed. - void add_listener(ContentListener& listener); - // Remove a UI class that listens to the overlay change, added by `add_listener()`. - void remove_listener(ContentListener& listener); - - -public: - ~VideoOverlaySession(); - VideoOverlaySession(VideoOverlayOption& option); - - void get(VideoOverlayOption& option); - void set(const VideoOverlayOption& option); - - bool enabled_boxes () const{ return m_option.boxes.load(std::memory_order_relaxed); } - bool enabled_text () const{ return m_option.text.load(std::memory_order_relaxed); } - bool enabled_images() const{ return m_option.images.load(std::memory_order_relaxed); } - bool enabled_log () const{ return m_option.log.load(std::memory_order_relaxed); } - bool enabled_stats () const{ return m_option.stats.load(std::memory_order_relaxed); } - - void set_enabled_boxes (bool enabled); - void set_enabled_text (bool enabled); - void set_enabled_images(bool enabled); - void set_enabled_log (bool enabled); - void set_enabled_stats (bool enabled); - - // Called by rendering infra to access a copy of the stored overlay boxes. - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_box(). - std::vector boxes() const; - // Called by rendering infra to access the overlay texts. - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_text(). - std::vector texts() const; - // Called by rendering infra to access the overlay images. - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_image(). - std::vector images() const; - // Called by rendering infra to access the overlay logs. - // Returns a copy to avoid the caller (UI object) accessing the data async while the data - // is modified by VideoOverlaySession::add/remove_log(). - std::vector log_texts() const; - - virtual void add_box(const OverlayBox& box) override; - virtual void remove_box(const OverlayBox& box) override; - - virtual void add_text(const OverlayText& text) override; - virtual void remove_text(const OverlayText& text) override; - - virtual void add_image(const OverlayImage& image) override; - virtual void remove_image(const OverlayImage& image) override; - - virtual void add_log(std::string message, Color color = COLOR_WHITE) override; - virtual void clear_log() override; - - virtual void add_stat(OverlayStat& stat) override; - virtual void remove_stat(OverlayStat& stat) override; - - -private: - // Push updates to the various listeners. - void push_box_update(); - void push_text_update(); - void push_image_update(); - void push_log_text_update(); - - -private: - mutable SpinLock m_lock; - - VideoOverlayOption& m_option; - - std::set m_boxes; - std::set m_texts; - std::set m_images; - std::deque m_log_texts; - - std::list m_stats_order; - std::map::iterator> m_stats; - - std::set m_content_listeners; -}; - - - -} -#endif +/* Video Overlay Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the real-time state of the video overlays. You can + * asychronously add/remove objects to it. + * + * This class is not responsible for any UI. However, any changes made to this + * class will be forwarded to any UI components that are attached to it. + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoOverlaySession_H +#define PokemonAutomation_VideoPipeline_VideoOverlaySession_H + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "VideoOverlay.h" +#include "VideoOverlayOption.h" + +namespace PokemonAutomation{ + +// This class holds the real-time state of the video overlays. You can +// asychronously add/remove objects to it. +// This class is not responsible for any UI. However, any changes made to this +// class will be forwarded to any UI components that are attached to it. +class VideoOverlaySession : public VideoOverlay{ +public: + static constexpr size_t LOG_MAX_LINES = 20; + +public: + // Video overlay UI class (e.g. VideoOverlayWidget) inherits this listener to listen + // to the overlay session. + struct ContentListener{ + // VideoOverlaySession will call these when they change. + + virtual void on_overlay_enabled_boxes (bool enabled){} + virtual void on_overlay_enabled_text (bool enabled){} + virtual void on_overlay_enabled_images (bool enabled){} + virtual void on_overlay_enabled_log (bool enabled){} + virtual void on_overlay_enabled_stats (bool enabled){} + + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_box(). + virtual void on_overlay_update_boxes (const std::shared_ptr>& boxes){} + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_text(). + virtual void on_overlay_update_text (const std::shared_ptr>& texts){} + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_image(). + virtual void on_overlay_update_images (const std::shared_ptr>& images){} + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_log(). + virtual void on_overlay_update_log (const std::shared_ptr>& boxes){} + + // This one is different from the others. The listeners will store this + // pointer and access it directly and asynchronously. If you need to + // change the structure of the list itself, you must first call this + // with null to remove it from all the listeners. Then add the updated + // one back when you're done. + // This is called immediately when attaching a listener to give the + // current stats. The listener must drop all references to the stats + // before detaching. + virtual void on_overlay_update_stats(const std::list* stats){} + + }; + + // Add a UI class to listen to any overlay change. The UI class needs to inherit Listener. + // Must call `remove_listener()` before listener is destroyed. + void add_listener(ContentListener& listener); + // Remove a UI class that listens to the overlay change, added by `add_listener()`. + void remove_listener(ContentListener& listener); + + +public: + ~VideoOverlaySession(); + VideoOverlaySession(VideoOverlayOption& option); + + void get(VideoOverlayOption& option); + void set(const VideoOverlayOption& option); + + bool enabled_boxes () const{ return m_option.boxes.load(std::memory_order_relaxed); } + bool enabled_text () const{ return m_option.text.load(std::memory_order_relaxed); } + bool enabled_images() const{ return m_option.images.load(std::memory_order_relaxed); } + bool enabled_log () const{ return m_option.log.load(std::memory_order_relaxed); } + bool enabled_stats () const{ return m_option.stats.load(std::memory_order_relaxed); } + + void set_enabled_boxes (bool enabled); + void set_enabled_text (bool enabled); + void set_enabled_images(bool enabled); + void set_enabled_log (bool enabled); + void set_enabled_stats (bool enabled); + + // Called by rendering infra to access a copy of the stored overlay boxes. + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_box(). + std::vector boxes() const; + // Called by rendering infra to access the overlay texts. + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_text(). + std::vector texts() const; + // Called by rendering infra to access the overlay images. + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_image(). + std::vector images() const; + // Called by rendering infra to access the overlay logs. + // Returns a copy to avoid the caller (UI object) accessing the data async while the data + // is modified by VideoOverlaySession::add/remove_log(). + std::vector log_texts() const; + + virtual void add_box(const OverlayBox& box) override; + virtual void remove_box(const OverlayBox& box) override; + + virtual void add_text(const OverlayText& text) override; + virtual void remove_text(const OverlayText& text) override; + + virtual void add_image(const OverlayImage& image) override; + virtual void remove_image(const OverlayImage& image) override; + + virtual void add_log(std::string message, Color color = COLOR_WHITE) override; + virtual void clear_log() override; + + virtual void add_stat(OverlayStat& stat) override; + virtual void remove_stat(OverlayStat& stat) override; + + +private: + // Push updates to the various listeners. + void push_box_update(); + void push_text_update(); + void push_image_update(); + void push_log_text_update(); + + +private: + mutable SpinLock m_lock; + + VideoOverlayOption& m_option; + + std::set m_boxes; + std::set m_texts; + std::set m_images; + std::deque m_log_texts; + + std::list m_stats_order; + std::map::iterator> m_stats; + + std::set m_content_listeners; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp index d7fd15743b..14041c5a00 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.cpp @@ -1,75 +1,75 @@ -/* Video Overlay Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -//#include "Common/Cpp/Containers/Pimpl.tpp" -//#include "Common/Cpp/Concurrency/SpinLock.h" -#include "VideoOverlayTypes.h" - -namespace PokemonAutomation{ - - - -#if 0 -struct OverlayStat::Data{ - mutable SpinLock m_lock; - OverlayStatSnapshot m_current; -}; - -OverlayStat::~OverlayStat() = default; -OverlayStat::OverlayStat() - : m_data(CONSTRUCT_TOKEN) -{} - -Color OverlayStat::get_text(std::string& text) const{ - ReadSpinLock lg(m_data->m_lock); - text = m_data->m_current.text; - return m_data->m_current.color; -} - -void OverlayStat::set_text(std::string text, Color color){ - WriteSpinLock lg(m_data->m_lock); - m_data->m_current.text = std::move(text); - m_data->m_current.color = color; -} -#endif - - -OverlayStatUtilizationPrinter::OverlayStatUtilizationPrinter() - : m_last_active(WallClock::min()) -{} -OverlayStatSnapshot OverlayStatUtilizationPrinter::get_snapshot(const std::string& label, double utilization){ - WallClock now = current_time(); - bool active = utilization >= 0.01; - - if (!active && - (m_last_active == WallClock::min() || now - m_last_active > std::chrono::seconds(10)) - ){ - return OverlayStatSnapshot(); - } - - if (active){ - m_last_active = now; - } - - Color color = COLOR_WHITE; - if (utilization > 0.90){ - color = COLOR_RED; - }else if (utilization > 0.80){ - color = COLOR_ORANGE; - }else if (utilization > 0.50){ - color = COLOR_YELLOW; - } - return OverlayStatSnapshot{ - label + " " + tostr_fixed(utilization * 100, 2) + " %", - color - }; -} - - - - -} +/* Video Overlay Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +//#include "Common/Cpp/Containers/Pimpl.tpp" +//#include "Common/Cpp/Concurrency/SpinLock.h" +#include "VideoOverlayTypes.h" + +namespace PokemonAutomation{ + + + +#if 0 +struct OverlayStat::Data{ + mutable SpinLock m_lock; + OverlayStatSnapshot m_current; +}; + +OverlayStat::~OverlayStat() = default; +OverlayStat::OverlayStat() + : m_data(CONSTRUCT_TOKEN) +{} + +Color OverlayStat::get_text(std::string& text) const{ + ReadSpinLock lg(m_data->m_lock); + text = m_data->m_current.text; + return m_data->m_current.color; +} + +void OverlayStat::set_text(std::string text, Color color){ + WriteSpinLock lg(m_data->m_lock); + m_data->m_current.text = std::move(text); + m_data->m_current.color = color; +} +#endif + + +OverlayStatUtilizationPrinter::OverlayStatUtilizationPrinter() + : m_last_active(WallClock::min()) +{} +OverlayStatSnapshot OverlayStatUtilizationPrinter::get_snapshot(const std::string& label, double utilization){ + WallClock now = current_time(); + bool active = utilization >= 0.01; + + if (!active && + (m_last_active == WallClock::min() || now - m_last_active > std::chrono::seconds(10)) + ){ + return OverlayStatSnapshot(); + } + + if (active){ + m_last_active = now; + } + + Color color = COLOR_WHITE; + if (utilization > 0.90){ + color = COLOR_RED; + }else if (utilization > 0.80){ + color = COLOR_ORANGE; + }else if (utilization > 0.50){ + color = COLOR_YELLOW; + } + return OverlayStatSnapshot{ + label + " " + tostr_fixed(utilization * 100, 2) + " %", + color + }; +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h index b3f36ac029..ff3928182f 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoOverlayTypes.h @@ -1,141 +1,141 @@ -/* Video Overlay Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoOverlayTypes_H -#define PokemonAutomation_VideoOverlayTypes_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ - -// A bounding box as part of the video overlay -// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. -struct OverlayBox{ - Color color; - ImageFloatBox box; - std::string label; - - OverlayBox(Color p_color, const ImageFloatBox& p_box, std::string p_label) - : color(p_color) - , box(p_box) - , label(std::move(p_label)) - {} - operator const ImageFloatBox&() const{ return box; } - operator ImageFloatBox&(){ return box; } -}; - - - -// A text as part of the video overlay. -// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. -struct OverlayText{ - // Text color. - Color color; - // Text content. - // Note overlay cannot handle newline character "\n". - std::string message; - // x coordinate of the text start, range: 0.0-1.0. - double x; - // y coordinate of the text start, range: 0.0-1.0. - double y; - // Font point size. This value is relative to the video overlay widget height. So you can - // set it without considering overlay widget resolution. - // Value of 4.0 gives a large, comfortable font size while not too large to clutter the screen. - double font_size; - - OverlayText( - Color color, - std::string message, - double x, double y, double font_size - ) - : color(color) - , message(std::move(message)) - , x(x), y(y) - , font_size(font_size) - {} -}; - -// An image as part of the video overlay. -// Allow transparency to create mask overlay. -// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. -// e.g. OverlayImage(image, {x=0.5, y=0.5, width=0.5, height=0.5}) will render -// an overlay image on the lower right quadrant of the view. -// Note: for efficiency, the image stored is just a pointer. Be careful not to -// modify the image data async or release it before the rendering code calls it. -struct OverlayImage{ - // Image view. The image data must live longer than the OverlayImage. - // Its alpha channel will be used during rendering. - ImageViewRGB32 image; - // starting x coordinate of the image in the video window, range: 0.0-1.0. - // starting y coordinate of the image in the video window, range: 0.0-1.0. - // relative width of the image in the video window, range: 0.0-1.0 - // relative height of the image in the video window, range: 0.0-1.0 - ImageFloatBox box; - - OverlayImage( - ImageViewRGB32 image, const ImageFloatBox& box - ) - : image(image) - , box(box) - {} -}; - - -// A log line to show as part of overlay. -// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. -struct OverlayLogLine{ - Color color; - std::string message; - - OverlayLogLine( - Color color, - std::string message - ) - : color(color) - , message(std::move(message)) - {} -}; - - - -struct OverlayStatSnapshot{ - std::string text; - Color color = COLOR_WHITE; -}; - -class OverlayStat{ -public: - OverlayStat(const OverlayStat&) = delete; - void operator=(const OverlayStat&) = delete; - -public: - virtual ~OverlayStat() = default; - OverlayStat() = default; - - virtual OverlayStatSnapshot get_current() = 0; -}; - - -class OverlayStatUtilizationPrinter{ -public: - OverlayStatUtilizationPrinter(); - OverlayStatSnapshot get_snapshot(const std::string& label, double utilization); - -private: - WallClock m_last_active; -}; - - - - - -} -#endif +/* Video Overlay Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoOverlayTypes_H +#define PokemonAutomation_VideoOverlayTypes_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ + +// A bounding box as part of the video overlay +// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. +struct OverlayBox{ + Color color; + ImageFloatBox box; + std::string label; + + OverlayBox(Color p_color, const ImageFloatBox& p_box, std::string p_label) + : color(p_color) + , box(p_box) + , label(std::move(p_label)) + {} + operator const ImageFloatBox&() const{ return box; } + operator ImageFloatBox&(){ return box; } +}; + + + +// A text as part of the video overlay. +// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. +struct OverlayText{ + // Text color. + Color color; + // Text content. + // Note overlay cannot handle newline character "\n". + std::string message; + // x coordinate of the text start, range: 0.0-1.0. + double x; + // y coordinate of the text start, range: 0.0-1.0. + double y; + // Font point size. This value is relative to the video overlay widget height. So you can + // set it without considering overlay widget resolution. + // Value of 4.0 gives a large, comfortable font size while not too large to clutter the screen. + double font_size; + + OverlayText( + Color color, + std::string message, + double x, double y, double font_size + ) + : color(color) + , message(std::move(message)) + , x(x), y(y) + , font_size(font_size) + {} +}; + +// An image as part of the video overlay. +// Allow transparency to create mask overlay. +// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. +// e.g. OverlayImage(image, {x=0.5, y=0.5, width=0.5, height=0.5}) will render +// an overlay image on the lower right quadrant of the view. +// Note: for efficiency, the image stored is just a pointer. Be careful not to +// modify the image data async or release it before the rendering code calls it. +struct OverlayImage{ + // Image view. The image data must live longer than the OverlayImage. + // Its alpha channel will be used during rendering. + ImageViewRGB32 image; + // starting x coordinate of the image in the video window, range: 0.0-1.0. + // starting y coordinate of the image in the video window, range: 0.0-1.0. + // relative width of the image in the video window, range: 0.0-1.0 + // relative height of the image in the video window, range: 0.0-1.0 + ImageFloatBox box; + + OverlayImage( + ImageViewRGB32 image, const ImageFloatBox& box + ) + : image(image) + , box(box) + {} +}; + + +// A log line to show as part of overlay. +// Check CommonFramework/VideoPipeline/VideoOverlay.h to see how it's used. +struct OverlayLogLine{ + Color color; + std::string message; + + OverlayLogLine( + Color color, + std::string message + ) + : color(color) + , message(std::move(message)) + {} +}; + + + +struct OverlayStatSnapshot{ + std::string text; + Color color = COLOR_WHITE; +}; + +class OverlayStat{ +public: + OverlayStat(const OverlayStat&) = delete; + void operator=(const OverlayStat&) = delete; + +public: + virtual ~OverlayStat() = default; + OverlayStat() = default; + + virtual OverlayStatSnapshot get_current() = 0; +}; + + +class OverlayStatUtilizationPrinter{ +public: + OverlayStatUtilizationPrinter(); + OverlayStatSnapshot get_snapshot(const std::string& label, double utilization); + +private: + WallClock m_last_active; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h index e7a4d19133..6a861ce584 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoPipelineOptions.h @@ -1,62 +1,62 @@ -/* Video Pipeline Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoPipelineOptions_H -#define PokemonAutomation_VideoPipeline_VideoPipelineOptions_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Backends/CameraImplementations.h" - -namespace PokemonAutomation{ - - -class VideoPipelineOptions : public GroupOption{ -public: - VideoPipelineOptions() - : GroupOption( - "Video Pipeline", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) -#if QT_VERSION_MAJOR == 5 - , ENABLE_FRAME_SCREENSHOTS( - "Enable Frame Screenshots:
" - "Attempt to use QVideoProbe and QVideoFrame for screenshots.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -#endif - , AUTO_RESET_SECONDS( - "Video Auto-Reset:
" - "Attempt to reset the video if this many seconds has elapsed since the last video frame (in order to fix issues with RDP disconnection, etc).
" - "This option is not supported by all video frameworks.", - LockMode::UNLOCK_WHILE_RUNNING, - 5 - ) - { - PA_ADD_OPTION(VIDEO_BACKEND); -#if QT_VERSION_MAJOR == 5 - PA_ADD_OPTION(ENABLE_FRAME_SCREENSHOTS); -#endif - - PA_ADD_OPTION(AUTO_RESET_SECONDS); - } - -public: - VideoBackendOption VIDEO_BACKEND; -#if QT_VERSION_MAJOR == 5 - BooleanCheckBoxOption ENABLE_FRAME_SCREENSHOTS; -#endif - - SimpleIntegerOption AUTO_RESET_SECONDS; -}; - - - -} -#endif +/* Video Pipeline Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoPipelineOptions_H +#define PokemonAutomation_VideoPipeline_VideoPipelineOptions_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Backends/CameraImplementations.h" + +namespace PokemonAutomation{ + + +class VideoPipelineOptions : public GroupOption{ +public: + VideoPipelineOptions() + : GroupOption( + "Video Pipeline", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) +#if QT_VERSION_MAJOR == 5 + , ENABLE_FRAME_SCREENSHOTS( + "Enable Frame Screenshots:
" + "Attempt to use QVideoProbe and QVideoFrame for screenshots.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +#endif + , AUTO_RESET_SECONDS( + "Video Auto-Reset:
" + "Attempt to reset the video if this many seconds has elapsed since the last video frame (in order to fix issues with RDP disconnection, etc).
" + "This option is not supported by all video frameworks.", + LockMode::UNLOCK_WHILE_RUNNING, + 5 + ) + { + PA_ADD_OPTION(VIDEO_BACKEND); +#if QT_VERSION_MAJOR == 5 + PA_ADD_OPTION(ENABLE_FRAME_SCREENSHOTS); +#endif + + PA_ADD_OPTION(AUTO_RESET_SECONDS); + } + +public: + VideoBackendOption VIDEO_BACKEND; +#if QT_VERSION_MAJOR == 5 + BooleanCheckBoxOption ENABLE_FRAME_SCREENSHOTS; +#endif + + SimpleIntegerOption AUTO_RESET_SECONDS; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp index 04c08c098f..03a0fac482 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.cpp @@ -1,259 +1,259 @@ -/* Video Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/Redispatch.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/GlobalServices.h" -#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" -#include "Backends/VideoFrameQt.h" -#include "VideoSources/VideoSource_Null.h" -#include "VideoSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void VideoSession::add_state_listener(StateListener& listener){ - m_state_listeners.add(listener); -} -void VideoSession::remove_state_listener(StateListener& listener){ - m_state_listeners.remove(listener); -} -void VideoSession::add_frame_listener(VideoFrameListener& listener){ - m_frame_listeners.add(listener); -} -void VideoSession::remove_frame_listener(VideoFrameListener& listener){ - m_frame_listeners.remove(listener); -} - - - - -VideoSession::~VideoSession(){ - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - } - global_watchdog().remove(*this); -} -VideoSession::VideoSession(Logger& logger, VideoSourceOption& option) - : m_logger(logger) - , m_option(option) - , m_descriptor(std::make_unique()) -{ - uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; - if (watchdog_timeout != 0){ - global_watchdog().add(*this, std::chrono::seconds(watchdog_timeout)); - } - set_source(option.descriptor()); -} - - - - -std::shared_ptr VideoSession::descriptor() const{ - ReadSpinLock lg(m_state_lock); - return m_descriptor; -} -Resolution VideoSession::current_resolution(){ - ReadSpinLock lg(m_state_lock); - if (m_video_source){ - return m_video_source->current_resolution(); - }else{ - return Resolution(); - } -} -std::vector VideoSession::supported_resolutions() const{ - ReadSpinLock lg(m_state_lock); - if (m_video_source){ - return m_video_source->supported_resolutions(); - }else{ - return {}; - } -} - - - -void VideoSession::get(VideoSourceOption& option){ - ReadSpinLock lg(m_state_lock); - option = m_option; -} -void VideoSession::set(const VideoSourceOption& option){ - set_source(option.descriptor()); -} - -void VideoSession::reset(){ - m_logger.log("Resetting the video...", COLOR_GREEN); - dispatch_to_main_thread([this]{ - std::lock_guard lg0(m_reset_lock); - - m_state_listeners.run_method_unique(&StateListener::pre_shutdown); - - { - WriteSpinLock lg(m_state_lock); - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - m_video_source.reset(); - } - - m_video_source = m_descriptor->make_VideoSource(m_logger, m_option.m_resolution); - - if (m_video_source){ - m_option.m_resolution = m_video_source->current_resolution(); - m_video_source->add_source_frame_listener(*this); - m_video_source->add_rendered_frame_listener(*this); - } - } - - m_state_listeners.run_method_unique( - &StateListener::post_startup, - m_video_source.get() - ); - }); -} -void VideoSession::set_source(const std::shared_ptr& device){ - m_logger.log("Changing video...", COLOR_GREEN); - dispatch_to_main_thread([this, device]{ - std::lock_guard lg0(m_reset_lock); - if (*m_descriptor == *device && !m_descriptor->should_reload()){ - return; - } - - m_state_listeners.run_method_unique(&StateListener::pre_shutdown); - - { - WriteSpinLock lg(m_state_lock); - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - m_video_source.reset(); - } - - m_option.set_descriptor(device); - m_descriptor = device; - - Resolution desired_resolution = m_option.m_resolution; - m_video_source = device->make_VideoSource(m_logger, desired_resolution); - - if (m_video_source){ - m_option.m_resolution = m_video_source->current_resolution(); - m_video_source->add_source_frame_listener(*this); - m_video_source->add_rendered_frame_listener(*this); - } - } - - m_state_listeners.run_method_unique( - &StateListener::post_startup, - m_video_source.get() - ); - }); -} -void VideoSession::set_resolution(Resolution resolution){ - m_logger.log("Changing resolution...", COLOR_GREEN); - dispatch_to_main_thread([this, resolution]{ - std::lock_guard lg0(m_reset_lock); - if (m_option.m_resolution == resolution){ - return; - } - - { - WriteSpinLock lg(m_state_lock); - m_state_listeners.run_method_unique(&StateListener::pre_shutdown); - - if (m_video_source){ - m_video_source->remove_source_frame_listener(*this); - m_video_source->remove_rendered_frame_listener(*this); - m_video_source.reset(); - } - - m_video_source = m_descriptor->make_VideoSource(m_logger, resolution); - - if (m_video_source){ - m_option.m_resolution = m_video_source->current_resolution(); - m_video_source->add_source_frame_listener(*this); - m_video_source->add_rendered_frame_listener(*this); - } - } - - m_state_listeners.run_method_unique( - &StateListener::post_startup, - m_video_source.get() - ); - }); -} - - -VideoSnapshot VideoSession::snapshot(){ - ReadSpinLock lg(m_state_lock); - if (m_video_source){ - return m_video_source->snapshot(); - }else{ - return VideoSnapshot(); - } -} - -double VideoSession::fps_source() const{ - ReadSpinLock lg(m_fps_lock); - return m_fps_tracker_source.events_per_second(); -} -double VideoSession::fps_display() const{ - ReadSpinLock lg(m_fps_lock); - return m_fps_tracker_rendered.events_per_second(); -} -void VideoSession::on_frame(std::shared_ptr frame){ - m_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); - { - WriteSpinLock lg(m_fps_lock); - m_fps_tracker_source.push_event(frame->timestamp); - } - global_watchdog().delay(*this); -} -void VideoSession::on_rendered_frame(WallClock timestamp){ - WriteSpinLock lg(m_fps_lock); - m_fps_tracker_rendered.push_event(timestamp); -} - - -void VideoSession::on_watchdog_timeout(){ - { - ReadSpinLock lg(m_state_lock); - if (!m_video_source || !m_video_source->allow_watchdog_reset()){ - return; - } - } - - uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; - m_logger.log("No video detected for " + std::to_string(watchdog_timeout) + " seconds...", COLOR_RED); - - if (watchdog_timeout == 0){ - return; - } - - reset(); -} - - - - - - - - - - - - - - - - - -} +/* Video Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/Redispatch.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/GlobalServices.h" +#include "CommonFramework/VideoPipeline/VideoPipelineOptions.h" +#include "Backends/VideoFrameQt.h" +#include "VideoSources/VideoSource_Null.h" +#include "VideoSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void VideoSession::add_state_listener(StateListener& listener){ + m_state_listeners.add(listener); +} +void VideoSession::remove_state_listener(StateListener& listener){ + m_state_listeners.remove(listener); +} +void VideoSession::add_frame_listener(VideoFrameListener& listener){ + m_frame_listeners.add(listener); +} +void VideoSession::remove_frame_listener(VideoFrameListener& listener){ + m_frame_listeners.remove(listener); +} + + + + +VideoSession::~VideoSession(){ + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + } + global_watchdog().remove(*this); +} +VideoSession::VideoSession(Logger& logger, VideoSourceOption& option) + : m_logger(logger) + , m_option(option) + , m_descriptor(std::make_unique()) +{ + uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; + if (watchdog_timeout != 0){ + global_watchdog().add(*this, std::chrono::seconds(watchdog_timeout)); + } + set_source(option.descriptor()); +} + + + + +std::shared_ptr VideoSession::descriptor() const{ + ReadSpinLock lg(m_state_lock); + return m_descriptor; +} +Resolution VideoSession::current_resolution(){ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->current_resolution(); + }else{ + return Resolution(); + } +} +std::vector VideoSession::supported_resolutions() const{ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->supported_resolutions(); + }else{ + return {}; + } +} + + + +void VideoSession::get(VideoSourceOption& option){ + ReadSpinLock lg(m_state_lock); + option = m_option; +} +void VideoSession::set(const VideoSourceOption& option){ + set_source(option.descriptor()); +} + +void VideoSession::reset(){ + m_logger.log("Resetting the video...", COLOR_GREEN); + dispatch_to_main_thread([this]{ + std::lock_guard lg0(m_reset_lock); + + m_state_listeners.run_method_unique(&StateListener::pre_shutdown); + + { + WriteSpinLock lg(m_state_lock); + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + m_video_source.reset(); + } + + m_video_source = m_descriptor->make_VideoSource(m_logger, m_option.m_resolution); + + if (m_video_source){ + m_option.m_resolution = m_video_source->current_resolution(); + m_video_source->add_source_frame_listener(*this); + m_video_source->add_rendered_frame_listener(*this); + } + } + + m_state_listeners.run_method_unique( + &StateListener::post_startup, + m_video_source.get() + ); + }); +} +void VideoSession::set_source(const std::shared_ptr& device){ + m_logger.log("Changing video...", COLOR_GREEN); + dispatch_to_main_thread([this, device]{ + std::lock_guard lg0(m_reset_lock); + if (*m_descriptor == *device && !m_descriptor->should_reload()){ + return; + } + + m_state_listeners.run_method_unique(&StateListener::pre_shutdown); + + { + WriteSpinLock lg(m_state_lock); + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + m_video_source.reset(); + } + + m_option.set_descriptor(device); + m_descriptor = device; + + Resolution desired_resolution = m_option.m_resolution; + m_video_source = device->make_VideoSource(m_logger, desired_resolution); + + if (m_video_source){ + m_option.m_resolution = m_video_source->current_resolution(); + m_video_source->add_source_frame_listener(*this); + m_video_source->add_rendered_frame_listener(*this); + } + } + + m_state_listeners.run_method_unique( + &StateListener::post_startup, + m_video_source.get() + ); + }); +} +void VideoSession::set_resolution(Resolution resolution){ + m_logger.log("Changing resolution...", COLOR_GREEN); + dispatch_to_main_thread([this, resolution]{ + std::lock_guard lg0(m_reset_lock); + if (m_option.m_resolution == resolution){ + return; + } + + { + WriteSpinLock lg(m_state_lock); + m_state_listeners.run_method_unique(&StateListener::pre_shutdown); + + if (m_video_source){ + m_video_source->remove_source_frame_listener(*this); + m_video_source->remove_rendered_frame_listener(*this); + m_video_source.reset(); + } + + m_video_source = m_descriptor->make_VideoSource(m_logger, resolution); + + if (m_video_source){ + m_option.m_resolution = m_video_source->current_resolution(); + m_video_source->add_source_frame_listener(*this); + m_video_source->add_rendered_frame_listener(*this); + } + } + + m_state_listeners.run_method_unique( + &StateListener::post_startup, + m_video_source.get() + ); + }); +} + + +VideoSnapshot VideoSession::snapshot(){ + ReadSpinLock lg(m_state_lock); + if (m_video_source){ + return m_video_source->snapshot(); + }else{ + return VideoSnapshot(); + } +} + +double VideoSession::fps_source() const{ + ReadSpinLock lg(m_fps_lock); + return m_fps_tracker_source.events_per_second(); +} +double VideoSession::fps_display() const{ + ReadSpinLock lg(m_fps_lock); + return m_fps_tracker_rendered.events_per_second(); +} +void VideoSession::on_frame(std::shared_ptr frame){ + m_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); + { + WriteSpinLock lg(m_fps_lock); + m_fps_tracker_source.push_event(frame->timestamp); + } + global_watchdog().delay(*this); +} +void VideoSession::on_rendered_frame(WallClock timestamp){ + WriteSpinLock lg(m_fps_lock); + m_fps_tracker_rendered.push_event(timestamp); +} + + +void VideoSession::on_watchdog_timeout(){ + { + ReadSpinLock lg(m_state_lock); + if (!m_video_source || !m_video_source->allow_watchdog_reset()){ + return; + } + } + + uint8_t watchdog_timeout = GlobalSettings::instance().VIDEO_PIPELINE->AUTO_RESET_SECONDS; + m_logger.log("No video detected for " + std::to_string(watchdog_timeout) + " seconds...", COLOR_RED); + + if (watchdog_timeout == 0){ + return; + } + + reset(); +} + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h index 3c41307aa8..d08889a506 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSession.h @@ -1,109 +1,109 @@ -/* Video Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSession_H -#define PokemonAutomation_VideoPipeline_VideoSession_H - -#include -#include -#include "Common/Cpp/EventRateTracker.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/Watchdog.h" -#include "VideoSourceDescriptor.h" -#include "VideoSource.h" - -namespace PokemonAutomation{ - - -class VideoSession - : public VideoFeed - , private VideoFrameListener - , private VideoSource::RenderedFrameListener - , private WatchdogCallback -{ -public: - struct StateListener{ - virtual void post_startup(VideoSource* source){} - - // Sent before the video source shuts down. Listeners should drop their - // references to the internal video source before returning. - virtual void pre_shutdown(){} - virtual void post_shutdown(){} - - virtual void pre_resolution_change(Resolution resolution){} - virtual void post_resolution_change(Resolution resolution){} - }; - - void add_state_listener(StateListener& listener); - void remove_state_listener(StateListener& listener); - - virtual void add_frame_listener(VideoFrameListener& listener) override; - virtual void remove_frame_listener(VideoFrameListener& listener) override; - - -public: - ~VideoSession(); - VideoSession(Logger& logger, VideoSourceOption& option); - - Logger& logger(){ - return m_logger; - } - - std::shared_ptr descriptor() const; - - // Warning, not thread-safe with any source changes. - VideoSource* current_source(){ - return m_video_source.get(); - } - - Resolution current_resolution(); - std::vector supported_resolutions() const; - - virtual VideoSnapshot snapshot() override; - - virtual double fps_source() const override; - virtual double fps_display() const override; - - -public: - void get(VideoSourceOption& option); - void set(const VideoSourceOption& option); - - virtual void reset() override; - void set_source(const std::shared_ptr& device); - void set_resolution(Resolution resolution); - - -private: - virtual void on_frame(std::shared_ptr frame) override; - virtual void on_rendered_frame(WallClock timestamp) override; - - virtual void on_watchdog_timeout() override; - - -private: - mutable std::mutex m_reset_lock; - mutable SpinLock m_state_lock; - - Logger& m_logger; - VideoSourceOption& m_option; - - mutable SpinLock m_fps_lock; - EventRateTracker m_fps_tracker_source; - EventRateTracker m_fps_tracker_rendered; - - std::shared_ptr m_descriptor; - std::unique_ptr m_video_source; - - ListenerSet m_state_listeners; - ListenerSet m_frame_listeners; -}; - - - - -} -#endif +/* Video Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSession_H +#define PokemonAutomation_VideoPipeline_VideoSession_H + +#include +#include +#include "Common/Cpp/EventRateTracker.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/Watchdog.h" +#include "VideoSourceDescriptor.h" +#include "VideoSource.h" + +namespace PokemonAutomation{ + + +class VideoSession + : public VideoFeed + , private VideoFrameListener + , private VideoSource::RenderedFrameListener + , private WatchdogCallback +{ +public: + struct StateListener{ + virtual void post_startup(VideoSource* source){} + + // Sent before the video source shuts down. Listeners should drop their + // references to the internal video source before returning. + virtual void pre_shutdown(){} + virtual void post_shutdown(){} + + virtual void pre_resolution_change(Resolution resolution){} + virtual void post_resolution_change(Resolution resolution){} + }; + + void add_state_listener(StateListener& listener); + void remove_state_listener(StateListener& listener); + + virtual void add_frame_listener(VideoFrameListener& listener) override; + virtual void remove_frame_listener(VideoFrameListener& listener) override; + + +public: + ~VideoSession(); + VideoSession(Logger& logger, VideoSourceOption& option); + + Logger& logger(){ + return m_logger; + } + + std::shared_ptr descriptor() const; + + // Warning, not thread-safe with any source changes. + VideoSource* current_source(){ + return m_video_source.get(); + } + + Resolution current_resolution(); + std::vector supported_resolutions() const; + + virtual VideoSnapshot snapshot() override; + + virtual double fps_source() const override; + virtual double fps_display() const override; + + +public: + void get(VideoSourceOption& option); + void set(const VideoSourceOption& option); + + virtual void reset() override; + void set_source(const std::shared_ptr& device); + void set_resolution(Resolution resolution); + + +private: + virtual void on_frame(std::shared_ptr frame) override; + virtual void on_rendered_frame(WallClock timestamp) override; + + virtual void on_watchdog_timeout() override; + + +private: + mutable std::mutex m_reset_lock; + mutable SpinLock m_state_lock; + + Logger& m_logger; + VideoSourceOption& m_option; + + mutable SpinLock m_fps_lock; + EventRateTracker m_fps_tracker_source; + EventRateTracker m_fps_tracker_rendered; + + std::shared_ptr m_descriptor; + std::unique_ptr m_video_source; + + ListenerSet m_state_listeners; + ListenerSet m_frame_listeners; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp index e3ba271115..9d61d0c2e9 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.cpp @@ -1,12 +1,12 @@ -/* Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "VideoSource.h" - -namespace PokemonAutomation{ - - -} +/* Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "VideoSource.h" + +namespace PokemonAutomation{ + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h index b45b35387e..dd153d3629 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource.h @@ -1,89 +1,89 @@ -/* Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_H -#define PokemonAutomation_VideoPipeline_VideoSource_H - -#include "Common/Cpp/LifetimeSanitizer.h" -#include "Common/Cpp/ImageResolution.h" -#include "Common/Cpp/ListenerSet.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" - -class QWidget; - -namespace PokemonAutomation{ - - - - -class VideoSource{ -public: - struct RenderedFrameListener{ - virtual void on_rendered_frame(WallClock timestamp) = 0; - }; - - void add_source_frame_listener(VideoFrameListener& listener){ - m_source_frame_listeners.add(listener); - } - void remove_source_frame_listener(VideoFrameListener& listener){ - m_source_frame_listeners.remove(listener); - } - void add_rendered_frame_listener(RenderedFrameListener& listener){ - m_rendered_frame_listeners.add(listener); - } - void remove_rendered_frame_listener(RenderedFrameListener& listener){ - m_rendered_frame_listeners.remove(listener); - } - - -public: - VideoSource(bool allow_watchdog_reset) - : m_allow_watchdog_reset(allow_watchdog_reset) - , m_sanitizer("VideoSource") - {} - virtual ~VideoSource() = default; - - -public: - bool allow_watchdog_reset() const{ - return m_allow_watchdog_reset; - } - - virtual Resolution current_resolution() const = 0; - virtual const std::vector& supported_resolutions() const = 0; - - virtual VideoSnapshot snapshot() = 0; - - -protected: - void report_source_frame(std::shared_ptr frame){ - auto scope_check = m_sanitizer.check_scope(); - m_source_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); - } - void report_rendered_frame(WallClock timestamp){ - auto scope_check = m_sanitizer.check_scope(); - m_rendered_frame_listeners.run_method_unique(&RenderedFrameListener::on_rendered_frame, timestamp); - } - - -public: - virtual QWidget* make_display_QtWidget(QWidget* parent) = 0; - - -private: - ListenerSet m_source_frame_listeners; - ListenerSet m_rendered_frame_listeners; - - const bool m_allow_watchdog_reset; - - LifetimeSanitizer m_sanitizer; -}; - - - - -} -#endif +/* Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_H +#define PokemonAutomation_VideoPipeline_VideoSource_H + +#include "Common/Cpp/LifetimeSanitizer.h" +#include "Common/Cpp/ImageResolution.h" +#include "Common/Cpp/ListenerSet.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" + +class QWidget; + +namespace PokemonAutomation{ + + + + +class VideoSource{ +public: + struct RenderedFrameListener{ + virtual void on_rendered_frame(WallClock timestamp) = 0; + }; + + void add_source_frame_listener(VideoFrameListener& listener){ + m_source_frame_listeners.add(listener); + } + void remove_source_frame_listener(VideoFrameListener& listener){ + m_source_frame_listeners.remove(listener); + } + void add_rendered_frame_listener(RenderedFrameListener& listener){ + m_rendered_frame_listeners.add(listener); + } + void remove_rendered_frame_listener(RenderedFrameListener& listener){ + m_rendered_frame_listeners.remove(listener); + } + + +public: + VideoSource(bool allow_watchdog_reset) + : m_allow_watchdog_reset(allow_watchdog_reset) + , m_sanitizer("VideoSource") + {} + virtual ~VideoSource() = default; + + +public: + bool allow_watchdog_reset() const{ + return m_allow_watchdog_reset; + } + + virtual Resolution current_resolution() const = 0; + virtual const std::vector& supported_resolutions() const = 0; + + virtual VideoSnapshot snapshot() = 0; + + +protected: + void report_source_frame(std::shared_ptr frame){ + auto scope_check = m_sanitizer.check_scope(); + m_source_frame_listeners.run_method_unique(&VideoFrameListener::on_frame, frame); + } + void report_rendered_frame(WallClock timestamp){ + auto scope_check = m_sanitizer.check_scope(); + m_rendered_frame_listeners.run_method_unique(&RenderedFrameListener::on_rendered_frame, timestamp); + } + + +public: + virtual QWidget* make_display_QtWidget(QWidget* parent) = 0; + + +private: + ListenerSet m_source_frame_listeners; + ListenerSet m_rendered_frame_listeners; + + const bool m_allow_watchdog_reset; + + LifetimeSanitizer m_sanitizer; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp index d611d1df01..f98a9122d4 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.cpp @@ -1,161 +1,161 @@ -/* Video Source Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/EnumStringMap.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "VideoSourceDescriptor.h" - -#include "VideoSources/VideoSource_Null.h" -#include "VideoSources/VideoSource_StillImage.h" -#include "VideoSources/VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -const EnumStringMap VIDEO_TYPE_STRINGS{ - {VideoSourceType::None, "None"}, - {VideoSourceType::StillImage, "Still Image"}, - {VideoSourceType::VideoPlayback, "Video Playback"}, - {VideoSourceType::Camera, "Camera"}, -}; - - -VideoSourceOption::VideoSourceOption() - : m_descriptor(new VideoSourceDescriptor_Null()) - , m_resolution(1920, 1080) -{} - -void VideoSourceOption::set_descriptor(std::shared_ptr descriptor){ - m_descriptor_cache[descriptor->type] = descriptor; - m_descriptor = std::move(descriptor); -} - -std::shared_ptr VideoSourceOption::get_descriptor_from_cache(VideoSourceType type){ - auto iter = m_descriptor_cache.find(type); - if (iter != m_descriptor_cache.end()){ - return iter->second; - } - std::shared_ptr descriptor; - switch (type){ - case VideoSourceType::None: - descriptor.reset(new VideoSourceDescriptor_Null()); - break; - case VideoSourceType::StillImage: - descriptor.reset(new VideoSourceDescriptor_StillImage()); - break; - case VideoSourceType::Camera: - descriptor.reset(new VideoSourceDescriptor_Camera()); - break; - default:; - descriptor.reset(new VideoSourceDescriptor_Null()); - } - m_descriptor_cache[descriptor->type] = descriptor; - return descriptor; -} - - - -void VideoSourceOption::load_json(const JsonValue& json){ - std::shared_ptr descriptor; - do{ - if (json.is_null()){ - break; - } - - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - break; - } - - const JsonArray* res = obj->get_array("Resolution"); - if (res != nullptr && res->size() == 2){ - do{ - size_t width, height; - if (!(*res)[0].read_integer(width)){ - break; - } - if (!(*res)[1].read_integer(height)){ - break; - } - m_resolution = Resolution(width, height); - }while (false); - } - - const std::string* type = obj->get_string("SourceType"); - if (type == nullptr){ - break; - } - -#if 0 - for (const auto& item : VIDEO_TYPE_STRINGS){ - const JsonValue* params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(item.first)); - if (params == nullptr){ - continue; - } - m_descriptor_cache[item.first] = item.second->make(*params); - } -#endif - - const JsonValue* params; - params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::StillImage)); - if (params != nullptr){ - auto x = std::make_unique(); - x->load_json(*params); - m_descriptor_cache[VideoSourceType::StillImage] = std::move(x); - } - params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::VideoPlayback)); - if (params != nullptr){ -// m_descriptor_cache[VideoSourceType::VideoPlayback] = - } - params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::Camera)); - if (params != nullptr){ - auto x = std::make_unique(); - x->load_json(*params); - m_descriptor_cache[VideoSourceType::Camera] = std::move(x); - } - - auto iter = m_descriptor_cache.find(VIDEO_TYPE_STRINGS.get_enum(*type, VideoSourceType::None)); - if (iter == m_descriptor_cache.end()){ - break; - } - - descriptor = iter->second; - }while (false); - - if (descriptor == nullptr){ - descriptor.reset(new VideoSourceDescriptor_Null()); - } - - m_descriptor = std::move(descriptor); -} -JsonValue VideoSourceOption::to_json() const{ - if (!m_descriptor){ - return JsonValue(); - } - JsonObject obj; - { - JsonArray res; - res.push_back(m_resolution.width); - res.push_back(m_resolution.height); - obj["Resolution"] = std::move(res); - } - obj["SourceType"] = VIDEO_TYPE_STRINGS.get_string(m_descriptor->type); - - for (const auto& item : m_descriptor_cache){ - obj[VIDEO_TYPE_STRINGS.get_string(item.first)] = item.second->to_json(); - } - - return obj; -} - - -} +/* Video Source Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/EnumStringMap.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "VideoSourceDescriptor.h" + +#include "VideoSources/VideoSource_Null.h" +#include "VideoSources/VideoSource_StillImage.h" +#include "VideoSources/VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +const EnumStringMap VIDEO_TYPE_STRINGS{ + {VideoSourceType::None, "None"}, + {VideoSourceType::StillImage, "Still Image"}, + {VideoSourceType::VideoPlayback, "Video Playback"}, + {VideoSourceType::Camera, "Camera"}, +}; + + +VideoSourceOption::VideoSourceOption() + : m_descriptor(new VideoSourceDescriptor_Null()) + , m_resolution(1920, 1080) +{} + +void VideoSourceOption::set_descriptor(std::shared_ptr descriptor){ + m_descriptor_cache[descriptor->type] = descriptor; + m_descriptor = std::move(descriptor); +} + +std::shared_ptr VideoSourceOption::get_descriptor_from_cache(VideoSourceType type){ + auto iter = m_descriptor_cache.find(type); + if (iter != m_descriptor_cache.end()){ + return iter->second; + } + std::shared_ptr descriptor; + switch (type){ + case VideoSourceType::None: + descriptor.reset(new VideoSourceDescriptor_Null()); + break; + case VideoSourceType::StillImage: + descriptor.reset(new VideoSourceDescriptor_StillImage()); + break; + case VideoSourceType::Camera: + descriptor.reset(new VideoSourceDescriptor_Camera()); + break; + default:; + descriptor.reset(new VideoSourceDescriptor_Null()); + } + m_descriptor_cache[descriptor->type] = descriptor; + return descriptor; +} + + + +void VideoSourceOption::load_json(const JsonValue& json){ + std::shared_ptr descriptor; + do{ + if (json.is_null()){ + break; + } + + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + break; + } + + const JsonArray* res = obj->get_array("Resolution"); + if (res != nullptr && res->size() == 2){ + do{ + size_t width, height; + if (!(*res)[0].read_integer(width)){ + break; + } + if (!(*res)[1].read_integer(height)){ + break; + } + m_resolution = Resolution(width, height); + }while (false); + } + + const std::string* type = obj->get_string("SourceType"); + if (type == nullptr){ + break; + } + +#if 0 + for (const auto& item : VIDEO_TYPE_STRINGS){ + const JsonValue* params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(item.first)); + if (params == nullptr){ + continue; + } + m_descriptor_cache[item.first] = item.second->make(*params); + } +#endif + + const JsonValue* params; + params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::StillImage)); + if (params != nullptr){ + auto x = std::make_unique(); + x->load_json(*params); + m_descriptor_cache[VideoSourceType::StillImage] = std::move(x); + } + params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::VideoPlayback)); + if (params != nullptr){ +// m_descriptor_cache[VideoSourceType::VideoPlayback] = + } + params = obj->get_value(VIDEO_TYPE_STRINGS.get_string(VideoSourceType::Camera)); + if (params != nullptr){ + auto x = std::make_unique(); + x->load_json(*params); + m_descriptor_cache[VideoSourceType::Camera] = std::move(x); + } + + auto iter = m_descriptor_cache.find(VIDEO_TYPE_STRINGS.get_enum(*type, VideoSourceType::None)); + if (iter == m_descriptor_cache.end()){ + break; + } + + descriptor = iter->second; + }while (false); + + if (descriptor == nullptr){ + descriptor.reset(new VideoSourceDescriptor_Null()); + } + + m_descriptor = std::move(descriptor); +} +JsonValue VideoSourceOption::to_json() const{ + if (!m_descriptor){ + return JsonValue(); + } + JsonObject obj; + { + JsonArray res; + res.push_back(m_resolution.width); + res.push_back(m_resolution.height); + obj["Resolution"] = std::move(res); + } + obj["SourceType"] = VIDEO_TYPE_STRINGS.get_string(m_descriptor->type); + + for (const auto& item : m_descriptor_cache){ + obj[VIDEO_TYPE_STRINGS.get_string(item.first)] = item.second->to_json(); + } + + return obj; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h index 3b73d9917d..387c15c5c6 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSourceDescriptor.h @@ -1,93 +1,93 @@ -/* Video Source Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H -#define PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H - -#include -#include -#include "Common/Cpp/ImageResolution.h" -#include "Common/Cpp/Json/JsonValue.h" - -namespace PokemonAutomation{ - -class VideoSource; - - - -enum class VideoSourceType{ - None, - StillImage, - VideoPlayback, - Camera, -}; - - - -class VideoSourceDescriptor{ -public: - const VideoSourceType type; - -public: - VideoSourceDescriptor(VideoSourceType p_type) - : type(p_type) - {} - virtual ~VideoSourceDescriptor() = default; - -public: - virtual bool should_reload() const{ return false; } - virtual bool operator==(const VideoSourceDescriptor& x) const = 0; - virtual std::string display_name() const = 0; - -public: - virtual void run_post_select(){}; - virtual void load_json(const JsonValue& json) = 0; - virtual JsonValue to_json() const = 0; - -public: - virtual std::unique_ptr make_VideoSource( - Logger& logger, - Resolution resolution - ) const = 0; -}; - - - - -class VideoSourceOption{ -public: - VideoSourceOption(); - - std::shared_ptr descriptor() const{ - return m_descriptor; - } - void set_descriptor(std::shared_ptr descriptor); - - // Remember the last used descriptor for each interface type. That way when - // the user switches back-and-forth between two interfaces, it will reload - // the previous one. - std::shared_ptr get_descriptor_from_cache(VideoSourceType type); - - -public: - void load_json(const JsonValue& json); - JsonValue to_json() const; - - -private: - std::shared_ptr m_descriptor; -public: - Resolution m_resolution; - -private: - std::map> m_descriptor_cache; -}; - - - - -} -#endif +/* Video Source Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H +#define PokemonAutomation_VideoPipeline_VideoSourceDescriptor_H + +#include +#include +#include "Common/Cpp/ImageResolution.h" +#include "Common/Cpp/Json/JsonValue.h" + +namespace PokemonAutomation{ + +class VideoSource; + + + +enum class VideoSourceType{ + None, + StillImage, + VideoPlayback, + Camera, +}; + + + +class VideoSourceDescriptor{ +public: + const VideoSourceType type; + +public: + VideoSourceDescriptor(VideoSourceType p_type) + : type(p_type) + {} + virtual ~VideoSourceDescriptor() = default; + +public: + virtual bool should_reload() const{ return false; } + virtual bool operator==(const VideoSourceDescriptor& x) const = 0; + virtual std::string display_name() const = 0; + +public: + virtual void run_post_select(){}; + virtual void load_json(const JsonValue& json) = 0; + virtual JsonValue to_json() const = 0; + +public: + virtual std::unique_ptr make_VideoSource( + Logger& logger, + Resolution resolution + ) const = 0; +}; + + + + +class VideoSourceOption{ +public: + VideoSourceOption(); + + std::shared_ptr descriptor() const{ + return m_descriptor; + } + void set_descriptor(std::shared_ptr descriptor); + + // Remember the last used descriptor for each interface type. That way when + // the user switches back-and-forth between two interfaces, it will reload + // the previous one. + std::shared_ptr get_descriptor_from_cache(VideoSourceType type); + + +public: + void load_json(const JsonValue& json); + JsonValue to_json() const; + + +private: + std::shared_ptr m_descriptor; +public: + Resolution m_resolution; + +private: + std::map> m_descriptor_cache; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp index 78bd958a17..e028436c80 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.cpp @@ -1,48 +1,48 @@ -/* Camera Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Backends/CameraImplementations.h" -#include "VideoSource.h" -#include "VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_info == static_cast(x).m_info; -} -std::string VideoSourceDescriptor_Camera::display_name() const{ - return get_camera_name(m_info); -} - -void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ - const std::string* name = json.to_string(); - if (name != nullptr){ - m_info = CameraInfo(*name); - } -} -JsonValue VideoSourceDescriptor_Camera::to_json() const{ - return m_info.device_name(); -} - -std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource(Logger& logger, Resolution resolution) const{ - return get_camera_backend().make_video_source(logger, m_info, resolution); -} - - - - -} - - +/* Camera Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Backends/CameraImplementations.h" +#include "VideoSource.h" +#include "VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_info == static_cast(x).m_info; +} +std::string VideoSourceDescriptor_Camera::display_name() const{ + return get_camera_name(m_info); +} + +void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ + const std::string* name = json.to_string(); + if (name != nullptr){ + m_info = CameraInfo(*name); + } +} +JsonValue VideoSourceDescriptor_Camera::to_json() const{ + return m_info.device_name(); +} + +std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource(Logger& logger, Resolution resolution) const{ + return get_camera_backend().make_video_source(logger, m_info, resolution); +} + + + + +} + + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h index 3e4213a51b..93ce2488e1 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Camera.h @@ -1,41 +1,41 @@ -/* Camera Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H -#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H - -#include "CameraInfo.h" -#include "VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Camera() - : VideoSourceDescriptor(VideoSourceType::Camera) - {} - VideoSourceDescriptor_Camera(CameraInfo info) - : VideoSourceDescriptor(VideoSourceType::Camera) - , m_info(std::move(info)) - {} - - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; - -private: - CameraInfo m_info; -}; - - - -} -#endif +/* Camera Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H +#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H + +#include "CameraInfo.h" +#include "VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Camera() + : VideoSourceDescriptor(VideoSourceType::Camera) + {} + VideoSourceDescriptor_Camera(CameraInfo info) + : VideoSourceDescriptor(VideoSourceType::Camera) + , m_info(std::move(info)) + {} + + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; + +private: + CameraInfo m_info; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp index 84ee7e5433..e0c8ee6dbb 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.cpp @@ -1,32 +1,32 @@ -/* Null Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "VideoSource.h" -#include "VideoSource_Null.h" - -namespace PokemonAutomation{ - - -bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ - return typeid(*this) == typeid(x); -} -std::string VideoSourceDescriptor_Null::display_name() const{ - return "(none)"; -} - -void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ - -} -JsonValue VideoSourceDescriptor_Null::to_json() const{ - return JsonValue(); -} - -std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource(Logger& logger, Resolution resolution) const{ - return nullptr; -} - - -} +/* Null Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "VideoSource.h" +#include "VideoSource_Null.h" + +namespace PokemonAutomation{ + + +bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ + return typeid(*this) == typeid(x); +} +std::string VideoSourceDescriptor_Null::display_name() const{ + return "(none)"; +} + +void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ + +} +JsonValue VideoSourceDescriptor_Null::to_json() const{ + return JsonValue(); +} + +std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource(Logger& logger, Resolution resolution) const{ + return nullptr; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h index 36942aff46..2faee8c114 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSource_Null.h @@ -1,33 +1,33 @@ -/* Null Video Source - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H -#define PokemonAutomation_VideoPipeline_VideoSource_Null_H - -#include "VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Null() - : VideoSourceDescriptor(VideoSourceType::None) - {} - - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; -}; - - - -} -#endif +/* Null Video Source + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H +#define PokemonAutomation_VideoPipeline_VideoSource_Null_H + +#include "VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Null() + : VideoSourceDescriptor(VideoSourceType::None) + {} + + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp index 49c90ff985..28041cfdd6 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.cpp @@ -1,51 +1,51 @@ -/* Video Source (Camera) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" -#include "CommonFramework/VideoPipeline/VideoSource.h" -#include "VideoSource_Camera.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_info == static_cast(x).m_info; -} -std::string VideoSourceDescriptor_Camera::display_name() const{ - return get_camera_name(m_info); -} - -void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ - const std::string* name = json.to_string(); - if (name != nullptr){ - m_info = CameraInfo(*name); - } -} -JsonValue VideoSourceDescriptor_Camera::to_json() const{ - return m_info.device_name(); -} - -std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource( - Logger& logger, - Resolution resolution -) const{ - return get_camera_backend().make_video_source(logger, m_info, resolution); -} - - - - -} - - +/* Video Source (Camera) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/Backends/CameraImplementations.h" +#include "CommonFramework/VideoPipeline/VideoSource.h" +#include "VideoSource_Camera.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +bool VideoSourceDescriptor_Camera::operator==(const VideoSourceDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_info == static_cast(x).m_info; +} +std::string VideoSourceDescriptor_Camera::display_name() const{ + return get_camera_name(m_info); +} + +void VideoSourceDescriptor_Camera::load_json(const JsonValue& json){ + const std::string* name = json.to_string(); + if (name != nullptr){ + m_info = CameraInfo(*name); + } +} +JsonValue VideoSourceDescriptor_Camera::to_json() const{ + return m_info.device_name(); +} + +std::unique_ptr VideoSourceDescriptor_Camera::make_VideoSource( + Logger& logger, + Resolution resolution +) const{ + return get_camera_backend().make_video_source(logger, m_info, resolution); +} + + + + +} + + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h index 5553f82e01..5fb93e2dad 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Camera.h @@ -1,47 +1,47 @@ -/* Video Source (Camera) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H -#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H - -#include "CommonFramework/VideoPipeline/CameraInfo.h" -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Camera() - : VideoSourceDescriptor(VideoSourceType::Camera) - {} - VideoSourceDescriptor_Camera(CameraInfo info) - : VideoSourceDescriptor(VideoSourceType::Camera) - , m_info(std::move(info)) - {} - - -public: - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource( - Logger& logger, - Resolution resolution - ) const override; - - -private: - CameraInfo m_info; -}; - - - -} -#endif +/* Video Source (Camera) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Camera_H +#define PokemonAutomation_VideoPipeline_VideoSource_Camera_H + +#include "CommonFramework/VideoPipeline/CameraInfo.h" +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Camera : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Camera() + : VideoSourceDescriptor(VideoSourceType::Camera) + {} + VideoSourceDescriptor_Camera(CameraInfo info) + : VideoSourceDescriptor(VideoSourceType::Camera) + , m_info(std::move(info)) + {} + + +public: + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource( + Logger& logger, + Resolution resolution + ) const override; + + +private: + CameraInfo m_info; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp index f3fcdf22f4..c4a31b01b1 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.cpp @@ -1,35 +1,35 @@ -/* Video Source (Null) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoSource.h" -#include "VideoSource_Null.h" - -namespace PokemonAutomation{ - - -bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ - return typeid(*this) == typeid(x); -} -std::string VideoSourceDescriptor_Null::display_name() const{ - return "(none)"; -} - -void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ - -} -JsonValue VideoSourceDescriptor_Null::to_json() const{ - return JsonValue(); -} - -std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource( - Logger& logger, - Resolution resolution -) const{ - return nullptr; -} - - -} +/* Video Source (Null) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoSource.h" +#include "VideoSource_Null.h" + +namespace PokemonAutomation{ + + +bool VideoSourceDescriptor_Null::operator==(const VideoSourceDescriptor& x) const{ + return typeid(*this) == typeid(x); +} +std::string VideoSourceDescriptor_Null::display_name() const{ + return "(none)"; +} + +void VideoSourceDescriptor_Null::load_json(const JsonValue& json){ + +} +JsonValue VideoSourceDescriptor_Null::to_json() const{ + return JsonValue(); +} + +std::unique_ptr VideoSourceDescriptor_Null::make_VideoSource( + Logger& logger, + Resolution resolution +) const{ + return nullptr; +} + + +} diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h index f59052a976..b8fadc4631 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_Null.h @@ -1,36 +1,36 @@ -/* Video Source (Null) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H -#define PokemonAutomation_VideoPipeline_VideoSource_Null_H - -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_Null() - : VideoSourceDescriptor(VideoSourceType::None) - {} - - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource( - Logger& logger, - Resolution resolution - ) const override; -}; - - - -} -#endif +/* Video Source (Null) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_Null_H +#define PokemonAutomation_VideoPipeline_VideoSource_Null_H + +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_Null : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_Null() + : VideoSourceDescriptor(VideoSourceType::None) + {} + + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource( + Logger& logger, + Resolution resolution + ) const override; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp index 208a56b24b..51fc8e72b0 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.cpp @@ -1,129 +1,129 @@ -/* Video Source (Still Image) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "VideoSource_StillImage.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -bool VideoSourceDescriptor_StillImage::operator==(const VideoSourceDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - - std::string other_path = static_cast(x).m_path; - - ReadSpinLock lg(m_lock); - return m_path == other_path; -} - -std::string VideoSourceDescriptor_StillImage::path() const{ - ReadSpinLock lg(m_lock); - return m_path; -} -void VideoSourceDescriptor_StillImage::set_path(std::string path){ - WriteSpinLock lg(m_lock); - m_path = std::move(path); - m_source_image_height = m_source_image_width = 0; -} - -void VideoSourceDescriptor_StillImage::run_post_select(){ -// if (!m_path.empty()){ -// return; -// } - std::string path = QFileDialog::getOpenFileName( - nullptr, "Open image file", ".", "*.png *.jpg" - ).toStdString(); - set_path(std::move(path)); -} -void VideoSourceDescriptor_StillImage::load_json(const JsonValue& json){ -// cout << "load_json: " << m_path << endl; - const std::string* name = json.to_string(); - if (name != nullptr){ - WriteSpinLock lg(m_lock); - m_path = *name; - m_source_image_height = m_source_image_width = 0; - } -} -JsonValue VideoSourceDescriptor_StillImage::to_json() const{ - ReadSpinLock lg(m_lock); - return m_path; -} - -std::unique_ptr VideoSourceDescriptor_StillImage::make_VideoSource(Logger& logger, Resolution resolution) const{ -// cout << "make_VideoSource: " << m_path << endl; - auto video_source = std::make_unique(path(), resolution); - - ReadSpinLock lg(m_lock); - m_source_image_width = video_source->original_image().width(); - m_source_image_height = video_source->original_image().height(); - return video_source; -} - - - - - -VideoSource_StillImage::VideoSource_StillImage(const std::string& path, Resolution resolution) - : VideoSource(false) - , m_original_image(QString::fromStdString(path)) -{ - m_snapshot = VideoSnapshot( - ImageRGB32(m_original_image).scale_to(resolution.width, resolution.height), - current_time() - ); - m_resolution = resolution; - m_resolutions = { - {1280, 720}, - {1920, 1080}, - {3840, 2160}, - {(size_t)m_original_image.width(), (size_t)m_original_image.height()} - }; -} - - - -class VideoWidget_StillImage : public QWidget{ -public: - VideoWidget_StillImage(QWidget* parent, VideoSource_StillImage& source) - : QWidget(parent) - , m_source(source) - {} - -private: - virtual void paintEvent(QPaintEvent* event) override{ - QWidget::paintEvent(event); - - QRect rect(0, 0, this->width(), this->height()); - QPainter painter(this); - painter.drawImage(rect, m_source.m_original_image); - } - -private: - VideoSource_StillImage& m_source; -}; - - - - - -QWidget* VideoSource_StillImage::make_display_QtWidget(QWidget* parent){ - return new VideoWidget_StillImage(parent, *this); -} - - - - -} - +/* Video Source (Still Image) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "VideoSource_StillImage.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +bool VideoSourceDescriptor_StillImage::operator==(const VideoSourceDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + + std::string other_path = static_cast(x).m_path; + + ReadSpinLock lg(m_lock); + return m_path == other_path; +} + +std::string VideoSourceDescriptor_StillImage::path() const{ + ReadSpinLock lg(m_lock); + return m_path; +} +void VideoSourceDescriptor_StillImage::set_path(std::string path){ + WriteSpinLock lg(m_lock); + m_path = std::move(path); + m_source_image_height = m_source_image_width = 0; +} + +void VideoSourceDescriptor_StillImage::run_post_select(){ +// if (!m_path.empty()){ +// return; +// } + std::string path = QFileDialog::getOpenFileName( + nullptr, "Open image file", ".", "*.png *.jpg" + ).toStdString(); + set_path(std::move(path)); +} +void VideoSourceDescriptor_StillImage::load_json(const JsonValue& json){ +// cout << "load_json: " << m_path << endl; + const std::string* name = json.to_string(); + if (name != nullptr){ + WriteSpinLock lg(m_lock); + m_path = *name; + m_source_image_height = m_source_image_width = 0; + } +} +JsonValue VideoSourceDescriptor_StillImage::to_json() const{ + ReadSpinLock lg(m_lock); + return m_path; +} + +std::unique_ptr VideoSourceDescriptor_StillImage::make_VideoSource(Logger& logger, Resolution resolution) const{ +// cout << "make_VideoSource: " << m_path << endl; + auto video_source = std::make_unique(path(), resolution); + + ReadSpinLock lg(m_lock); + m_source_image_width = video_source->original_image().width(); + m_source_image_height = video_source->original_image().height(); + return video_source; +} + + + + + +VideoSource_StillImage::VideoSource_StillImage(const std::string& path, Resolution resolution) + : VideoSource(false) + , m_original_image(QString::fromStdString(path)) +{ + m_snapshot = VideoSnapshot( + ImageRGB32(m_original_image).scale_to(resolution.width, resolution.height), + current_time() + ); + m_resolution = resolution; + m_resolutions = { + {1280, 720}, + {1920, 1080}, + {3840, 2160}, + {(size_t)m_original_image.width(), (size_t)m_original_image.height()} + }; +} + + + +class VideoWidget_StillImage : public QWidget{ +public: + VideoWidget_StillImage(QWidget* parent, VideoSource_StillImage& source) + : QWidget(parent) + , m_source(source) + {} + +private: + virtual void paintEvent(QPaintEvent* event) override{ + QWidget::paintEvent(event); + + QRect rect(0, 0, this->width(), this->height()); + QPainter painter(this); + painter.drawImage(rect, m_source.m_original_image); + } + +private: + VideoSource_StillImage& m_source; +}; + + + + + +QWidget* VideoSource_StillImage::make_display_QtWidget(QWidget* parent){ + return new VideoWidget_StillImage(parent, *this); +} + + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h index 981c5295b3..65e27dbca9 100644 --- a/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h +++ b/SerialPrograms/Source/CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h @@ -1,98 +1,98 @@ -/* Video Source (Still Image) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_VideoPipeline_VideoSource_StillImage_H -#define PokemonAutomation_VideoPipeline_VideoSource_StillImage_H - -#include -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" -#include "CommonFramework/VideoPipeline/VideoSource.h" - -namespace PokemonAutomation{ - - -class VideoSourceDescriptor_StillImage : public VideoSourceDescriptor{ -public: - VideoSourceDescriptor_StillImage() - : VideoSourceDescriptor(VideoSourceType::StillImage) - {} - VideoSourceDescriptor_StillImage(std::string path) - : VideoSourceDescriptor(VideoSourceType::StillImage) - , m_path(std::move(path)) - {} - -public: - // get the image source path - std::string path() const; - // set the image source path - void set_path(std::string path); - // Get the source image width. Its value is only loaded after `make_VideoSource()` is called. - // Otherwise, return 0. - size_t source_image_width() const{return m_source_image_width;} - // Get the source image height. Its value is only loaded after `make_VideoSource()` is called. - // Otherwise, return 0. - size_t source_image_height() const{return m_source_image_height;} - - virtual bool should_reload() const override{ return true; } - virtual bool operator==(const VideoSourceDescriptor& x) const override; - virtual std::string display_name() const override{ - return "Display Image"; - } - - virtual void run_post_select() override; - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; - - -private: - mutable SpinLock m_lock; - std::string m_path; - mutable size_t m_source_image_width = 0; - mutable size_t m_source_image_height = 0; -}; - - - -class VideoSource_StillImage : public VideoSource{ -public: - VideoSource_StillImage(const std::string& path, Resolution resolution); - - const std::string path() const{ - return m_path; - } - - virtual Resolution current_resolution() const override{ - return m_resolution; - } - virtual const std::vector& supported_resolutions() const override{ - return m_resolutions; - } - - virtual VideoSnapshot snapshot() override{ - return m_snapshot; - } - - virtual QWidget* make_display_QtWidget(QWidget* parent) override; - - const QImage& original_image() const { return m_original_image;} -private: - friend class VideoWidget_StillImage; - - std::string m_path; - QImage m_original_image; - VideoSnapshot m_snapshot; - Resolution m_resolution; - std::vector m_resolutions; -}; - - - - - -} -#endif +/* Video Source (Still Image) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_VideoPipeline_VideoSource_StillImage_H +#define PokemonAutomation_VideoPipeline_VideoSource_StillImage_H + +#include +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" +#include "CommonFramework/VideoPipeline/VideoSource.h" + +namespace PokemonAutomation{ + + +class VideoSourceDescriptor_StillImage : public VideoSourceDescriptor{ +public: + VideoSourceDescriptor_StillImage() + : VideoSourceDescriptor(VideoSourceType::StillImage) + {} + VideoSourceDescriptor_StillImage(std::string path) + : VideoSourceDescriptor(VideoSourceType::StillImage) + , m_path(std::move(path)) + {} + +public: + // get the image source path + std::string path() const; + // set the image source path + void set_path(std::string path); + // Get the source image width. Its value is only loaded after `make_VideoSource()` is called. + // Otherwise, return 0. + size_t source_image_width() const{return m_source_image_width;} + // Get the source image height. Its value is only loaded after `make_VideoSource()` is called. + // Otherwise, return 0. + size_t source_image_height() const{return m_source_image_height;} + + virtual bool should_reload() const override{ return true; } + virtual bool operator==(const VideoSourceDescriptor& x) const override; + virtual std::string display_name() const override{ + return "Display Image"; + } + + virtual void run_post_select() override; + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr make_VideoSource(Logger& logger, Resolution resolution) const override; + + +private: + mutable SpinLock m_lock; + std::string m_path; + mutable size_t m_source_image_width = 0; + mutable size_t m_source_image_height = 0; +}; + + + +class VideoSource_StillImage : public VideoSource{ +public: + VideoSource_StillImage(const std::string& path, Resolution resolution); + + const std::string path() const{ + return m_path; + } + + virtual Resolution current_resolution() const override{ + return m_resolution; + } + virtual const std::vector& supported_resolutions() const override{ + return m_resolutions; + } + + virtual VideoSnapshot snapshot() override{ + return m_snapshot; + } + + virtual QWidget* make_display_QtWidget(QWidget* parent) override; + + const QImage& original_image() const { return m_original_image;} +private: + friend class VideoWidget_StillImage; + + std::string m_path; + QImage m_original_image; + VideoSnapshot m_snapshot; + Resolution m_resolution; + std::vector m_resolutions; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.cpp b/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.cpp index d3584ae7cf..8ace441cd6 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.cpp +++ b/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.cpp @@ -1,103 +1,103 @@ -/* Button Diagram - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "WindowTracker.h" -#include "ButtonDiagram.h" - -// #include -// using std::cout; -// using std::endl; - - -namespace PokemonAutomation{ - -const char* PRO_CONTROLLER_MAPPING_PATH = "/NintendoSwitch/Layout-ProController.png"; -const char* JOYCON_VERTICAL_MAPPING_PATH = "/NintendoSwitch/Layout-JoyconVertical.png"; -const char* JOYCON_HORIZONTAL_MAPPING_PATH = "/NintendoSwitch/Layout-JoyconHorizontal.png"; - - -ButtonDiagram::ButtonDiagram(QWidget* parent) - : QMainWindow(parent) -{ - setWindowTitle("Controller Keyboard Mapping"); - - QMenuBar* menu = menuBar(); - QMenu* pro_controller = menu->addMenu("Pro Controller"); - QMenu* joycon_vertical = menu->addMenu("Joycon (Vertical)"); - QMenu* joycon_horizontal = menu->addMenu("Joycon (Horizontal)"); - -// pro_controller->addAction("asdfadf"); - - connect( - pro_controller, &QMenu::aboutToShow, - this, [this](){ - set_image(PRO_CONTROLLER_MAPPING_PATH); - } - ); - connect( - joycon_vertical, &QMenu::aboutToShow, - this, [this](){ - set_image(JOYCON_VERTICAL_MAPPING_PATH); - } - ); - connect( - joycon_horizontal, &QMenu::aboutToShow, - this, [this](){ - set_image(JOYCON_HORIZONTAL_MAPPING_PATH); - } - ); - - m_image_label = new QLabel(this); - setCentralWidget(m_image_label); - m_image_label->setAlignment(Qt::AlignCenter); -// m_image_label->setPixmap(m_image.scaled(800, 600, Qt::KeepAspectRatio)); -// m_image_label->setPixmap(m_image); -// m_image_label->setScaledContents(true); - m_image_label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); - -// image_label->resize(800, 600); -// image_label->setFixedSize(800, 600); - - resize(800, 600 + menu->sizeHint().height()); - - set_image(PRO_CONTROLLER_MAPPING_PATH); - - add_window(*this); -} -ButtonDiagram::~ButtonDiagram(){ - remove_window(*this); -} - -void ButtonDiagram::set_image(const std::string& resource_name){ - const std::string image_path = RESOURCE_PATH() + resource_name; - m_image = QPixmap(QString::fromStdString(image_path)); - ButtonDiagram::resizeEvent(nullptr); -} -void ButtonDiagram::resizeEvent(QResizeEvent*){ - int iw = m_image.width(); - int ih = m_image.height(); - int ww = m_image_label->width(); - int wh = m_image_label->height(); -// cout << "ww = " << ww << ", wh = " << wh << endl; - - double scale_w = (double)ww / iw; - double scale_h = (double)wh / ih; - double scale = std::min(scale_w, scale_h); - - iw = (int)(iw * scale); - ih = (int)(ih * scale); - - m_image_label->setPixmap(m_image.scaled(iw, ih, Qt::KeepAspectRatio, Qt::SmoothTransformation)); -} - - - -} - +/* Button Diagram + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "WindowTracker.h" +#include "ButtonDiagram.h" + +// #include +// using std::cout; +// using std::endl; + + +namespace PokemonAutomation{ + +const char* PRO_CONTROLLER_MAPPING_PATH = "/NintendoSwitch/Layout-ProController.png"; +const char* JOYCON_VERTICAL_MAPPING_PATH = "/NintendoSwitch/Layout-JoyconVertical.png"; +const char* JOYCON_HORIZONTAL_MAPPING_PATH = "/NintendoSwitch/Layout-JoyconHorizontal.png"; + + +ButtonDiagram::ButtonDiagram(QWidget* parent) + : QMainWindow(parent) +{ + setWindowTitle("Controller Keyboard Mapping"); + + QMenuBar* menu = menuBar(); + QMenu* pro_controller = menu->addMenu("Pro Controller"); + QMenu* joycon_vertical = menu->addMenu("Joycon (Vertical)"); + QMenu* joycon_horizontal = menu->addMenu("Joycon (Horizontal)"); + +// pro_controller->addAction("asdfadf"); + + connect( + pro_controller, &QMenu::aboutToShow, + this, [this](){ + set_image(PRO_CONTROLLER_MAPPING_PATH); + } + ); + connect( + joycon_vertical, &QMenu::aboutToShow, + this, [this](){ + set_image(JOYCON_VERTICAL_MAPPING_PATH); + } + ); + connect( + joycon_horizontal, &QMenu::aboutToShow, + this, [this](){ + set_image(JOYCON_HORIZONTAL_MAPPING_PATH); + } + ); + + m_image_label = new QLabel(this); + setCentralWidget(m_image_label); + m_image_label->setAlignment(Qt::AlignCenter); +// m_image_label->setPixmap(m_image.scaled(800, 600, Qt::KeepAspectRatio)); +// m_image_label->setPixmap(m_image); +// m_image_label->setScaledContents(true); + m_image_label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored); + +// image_label->resize(800, 600); +// image_label->setFixedSize(800, 600); + + resize(800, 600 + menu->sizeHint().height()); + + set_image(PRO_CONTROLLER_MAPPING_PATH); + + add_window(*this); +} +ButtonDiagram::~ButtonDiagram(){ + remove_window(*this); +} + +void ButtonDiagram::set_image(const std::string& resource_name){ + const std::string image_path = RESOURCE_PATH() + resource_name; + m_image = QPixmap(QString::fromStdString(image_path)); + ButtonDiagram::resizeEvent(nullptr); +} +void ButtonDiagram::resizeEvent(QResizeEvent*){ + int iw = m_image.width(); + int ih = m_image.height(); + int ww = m_image_label->width(); + int wh = m_image_label->height(); +// cout << "ww = " << ww << ", wh = " << wh << endl; + + double scale_w = (double)ww / iw; + double scale_h = (double)wh / ih; + double scale = std::min(scale_w, scale_h); + + iw = (int)(iw * scale); + ih = (int)(ih * scale); + + m_image_label->setPixmap(m_image.scaled(iw, ih, Qt::KeepAspectRatio, Qt::SmoothTransformation)); +} + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.h b/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.h index 98537595ce..fde0e8cd13 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.h +++ b/SerialPrograms/Source/CommonFramework/Windows/ButtonDiagram.h @@ -1,29 +1,29 @@ -/* Button Diagram - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include - -namespace PokemonAutomation{ - -// The window that shows button mapping: which keyboard keys are mapped to which -// Switch controller buttons. -class ButtonDiagram : public QMainWindow{ -public: - ButtonDiagram(QWidget* parent = nullptr); - ~ButtonDiagram(); - -private: - void set_image(const std::string& resource_name); - void resizeEvent(QResizeEvent*); - -private: - QPixmap m_image; - QLabel* m_image_label; -}; - - -} +/* Button Diagram + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include + +namespace PokemonAutomation{ + +// The window that shows button mapping: which keyboard keys are mapped to which +// Switch controller buttons. +class ButtonDiagram : public QMainWindow{ +public: + ButtonDiagram(QWidget* parent = nullptr); + ~ButtonDiagram(); + +private: + void set_image(const std::string& resource_name); + void resizeEvent(QResizeEvent*); + +private: + QPixmap m_image; + QLabel* m_image_label; +}; + + +} diff --git a/SerialPrograms/Source/CommonFramework/Windows/DpiScaler.cpp b/SerialPrograms/Source/CommonFramework/Windows/DpiScaler.cpp index 56f64de14a..4a917d040c 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/DpiScaler.cpp +++ b/SerialPrograms/Source/CommonFramework/Windows/DpiScaler.cpp @@ -1,95 +1,95 @@ -/* DPI Scaler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "DpiScaler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -int scale_dpi_width(int width){ - int dpi = 96; - QScreen* primaryScreen = QGuiApplication::primaryScreen(); - if (primaryScreen != nullptr){ - dpi = primaryScreen->logicalDotsPerInchX(); - } - return width * dpi / 96; -} -int scale_dpi_height(int height){ - int dpi = 96; - QScreen* primaryScreen = QGuiApplication::primaryScreen(); - if (primaryScreen != nullptr){ - dpi = primaryScreen->logicalDotsPerInchY(); - } - return height * dpi / 96; -} - - -void scale_dpi_token(QString& str, int dpi){ - size_t length = str.length(); - if (length < 3){ - return; - } - if (str[length - 2] != 'p' || str[length - 1] != 'x'){ - return; - } - - // Parse the integer in front. - int64_t value = 0; - for (size_t c = 0; c < length - 2; c++){ - QChar ch = str[c]; - if (!('0' <= ch && ch <= '9')){ - return; - } - value *= 10; - value += ch.unicode() - '0'; - } - value *= dpi; - value /= 96; - str = QString::number(value) + "px"; -} - - -QString scale_dpi_stylesheet(const QString& style_str){ - QScreen* primaryScreen = QGuiApplication::primaryScreen(); - if (primaryScreen == nullptr){ - return style_str; - } - int dpi_x = primaryScreen->logicalDotsPerInchX(); - int dpi_y = primaryScreen->logicalDotsPerInchY(); - int dpi = std::max(dpi_x, dpi_y); - - QString out; - -// cout << "style_str.length() = " < +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +int scale_dpi_width(int width){ + int dpi = 96; + QScreen* primaryScreen = QGuiApplication::primaryScreen(); + if (primaryScreen != nullptr){ + dpi = primaryScreen->logicalDotsPerInchX(); + } + return width * dpi / 96; +} +int scale_dpi_height(int height){ + int dpi = 96; + QScreen* primaryScreen = QGuiApplication::primaryScreen(); + if (primaryScreen != nullptr){ + dpi = primaryScreen->logicalDotsPerInchY(); + } + return height * dpi / 96; +} + + +void scale_dpi_token(QString& str, int dpi){ + size_t length = str.length(); + if (length < 3){ + return; + } + if (str[length - 2] != 'p' || str[length - 1] != 'x'){ + return; + } + + // Parse the integer in front. + int64_t value = 0; + for (size_t c = 0; c < length - 2; c++){ + QChar ch = str[c]; + if (!('0' <= ch && ch <= '9')){ + return; + } + value *= 10; + value += ch.unicode() - '0'; + } + value *= dpi; + value /= 96; + str = QString::number(value) + "px"; +} + + +QString scale_dpi_stylesheet(const QString& style_str){ + QScreen* primaryScreen = QGuiApplication::primaryScreen(); + if (primaryScreen == nullptr){ + return style_str; + } + int dpi_x = primaryScreen->logicalDotsPerInchX(); + int dpi_y = primaryScreen->logicalDotsPerInchY(); + int dpi = std::max(dpi_x, dpi_y); + + QString out; + +// cout << "style_str.length() = " < -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -MainWindow::MainWindow(QWidget* parent) - : QMainWindow(parent) - , m_current_panel_widget(nullptr) -{ - if (objectName().isEmpty()){ - setObjectName(QString::fromUtf8("MainWindow")); - } - this->setWindowIcon(QIcon(QString::fromStdString(RESOURCE_PATH() + "icon.png"))); -// QSize window_size = PERSISTENT_SETTINGS().window_size; - resize( - GlobalSettings::instance().WINDOW_SIZE->WIDTH, - GlobalSettings::instance().WINDOW_SIZE->HEIGHT - ); - // move main window to desired position on startup - // auto const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); - // uint32_t const screen_width = (uint32_t)screen_geometry.width(); - // uint32_t const screen_height = (uint32_t)screen_geometry.height(); - int32_t x_pos_main = GlobalSettings::instance().WINDOW_SIZE->X_POS; - int32_t y_pos_main = GlobalSettings::instance().WINDOW_SIZE->Y_POS; - int32_t move_x_main = move_x_within_screen_bounds(x_pos_main); - int32_t move_y_main = move_y_within_screen_bounds(y_pos_main); - move(move_x_main, move_y_main); - - centralwidget = new QWidget(this); - centralwidget->setObjectName(QString::fromUtf8("centralwidget")); - setCentralWidget(centralwidget); - menubar = new QMenuBar(this); - menubar->setObjectName(QString::fromUtf8("menubar")); - setMenuBar(menubar); -// statusbar = new QStatusBar(this); -// statusbar->setObjectName(QString::fromUtf8("statusbar")); -// setStatusBar(statusbar); - setWindowTitle(QString::fromStdString(PROGRAM_NAME + " Computer-Control Programs (" + PROGRAM_VERSION + ")")); - - QHBoxLayout* hbox = new QHBoxLayout(centralwidget); - QVBoxLayout* left_layout = new QVBoxLayout(); - hbox->addLayout(left_layout, 0); - -#if 0 - QGroupBox* program_box = new QGroupBox("Program Select", centralwidget); - left_layout->addWidget(program_box, 1); - QVBoxLayout* program_layout = new QVBoxLayout(program_box); - program_layout->setAlignment(Qt::AlignTop); - -// NoWheelComboBox* program_dropdown = new NoWheelComboBox(this); -// program_layout->addWidget(program_dropdown); - - m_program_list = new ProgramTabs(*this, *this); - program_layout->addWidget(m_program_list); -#else - m_program_list = new ProgramSelect(*this, *this); - left_layout->addWidget(m_program_list, 1); -#endif - - - QGroupBox* support_box = new QGroupBox( - QString::fromStdString(PROGRAM_NAME + " " + PROGRAM_VERSION + " (" + PA_ARCH_STRING + ")"), - centralwidget - ); - - - left_layout->addWidget(support_box); - QVBoxLayout* support_layout = new QVBoxLayout(support_box); - - { - QHBoxLayout* layout = new QHBoxLayout(); - support_layout->addLayout(layout); - layout->setAlignment(Qt::AlignHCenter); - layout->setContentsMargins(0, 0, 0, 0); - m_sleep_text = new QLabel(support_box); - layout->addWidget(m_sleep_text, 2); - m_sleep_box = new QCheckBox("Force On", support_box); - layout->addWidget(m_sleep_box, 1, Qt::AlignHCenter); - MainWindow::sleep_suppress_state_changed(SystemSleepController::instance().current_state()); -#if QT_VERSION < 0x060700 - connect( - m_sleep_box, &QCheckBox::stateChanged, - this, [this](int){ - if (m_sleep_box->isChecked()){ - m_sleep_scope.reset(new SleepSuppressScope(SleepSuppress::SCREEN_ON)); - }else{ - m_sleep_scope.reset(); - } - } - ); -#else - connect( - m_sleep_box, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState state){ - if (state == Qt::CheckState::Checked){ - m_sleep_scope.reset(new SleepSuppressScope(SleepSuppress::SCREEN_ON)); - }else{ - m_sleep_scope.reset(); - } - } - ); -#endif - } - - QHBoxLayout* support = new QHBoxLayout(); - support_layout->addLayout(support); -// support->setContentsMargins(0, 0, 0, 0); - - QVBoxLayout* links = new QVBoxLayout(); - support->addLayout(links); - { - QLabel* github = new QLabel(support_box); - links->addWidget(github); - github->setText(QString::fromStdString(make_text_url(ONLINE_DOC_URL_BASE + "ComputerControl/", "Online Documentation"))); - github->setTextFormat(Qt::RichText); - github->setTextInteractionFlags(Qt::TextBrowserInteraction); - github->setOpenExternalLinks(true); - } - { - QLabel* discord = new QLabel(support_box); - links->addWidget(discord); - discord->setText(QString::fromStdString(make_text_url(DISCORD_LINK_URL_PROGRAM, DISCORD_LINK_TEXT))); - discord->setTextFormat(Qt::RichText); - discord->setTextInteractionFlags(Qt::TextBrowserInteraction); - discord->setOpenExternalLinks(true); - } - { - QLabel* github = new QLabel(support_box); - links->addWidget(github); - github->setText(QString::fromStdString(make_text_url(GITHUB_LINK_URL, GITHUB_LINK_TEXT))); -// github->setText("GitHub Repository"); - github->setTextFormat(Qt::RichText); - github->setTextInteractionFlags(Qt::TextBrowserInteraction); - github->setOpenExternalLinks(true); - } - { - QLabel* about = new QLabel(support_box); - links->addWidget(about); - about->setText(QString::fromStdString(make_text_url(GITHUB_LINK_URL, "About this Program"))); - about->setTextFormat(Qt::RichText); - connect( - about, &QLabel::linkActivated, - this, [](const QString&){ - std::string str; - str += PROGRAM_NAME + " Computer-Control Programs
"; - str += "Copyright: 2020 - 2025
"; - str += "Version: " + PROGRAM_VERSION + "
"; - str += "
"; - str += "Framework: Qt " + std::to_string(QT_VERSION_MAJOR); - str += "." + std::to_string(QT_VERSION_MINOR); - str += "." + std::to_string(QT_VERSION_PATCH); - str += "
"; - str += "Compiler: " + COMPILER_VERSION; - str += "

"; - str += "Made by the " + PROGRAM_NAME + " Discord Server.
"; - str += "
"; - str += "This program uses Qt and dynamically links to unmodified Qt libraries under LGPL.
"; - - QMessageBox box; - box.information(nullptr, "About", QString::fromStdString(str)); - } - ); - } - - QVBoxLayout* buttons = new QVBoxLayout(); - support->addLayout(buttons); - { - QPushButton* keyboard = new QPushButton("Keyboard Layout", support_box); - buttons->addWidget(keyboard); - m_button_diagram.reset(new ButtonDiagram()); - connect( - keyboard, &QPushButton::clicked, - this, [button = m_button_diagram.get()](bool){ - button->show(); - button->raise(); // bring the window to front on macOS - button->activateWindow(); // bring the window to front on Windows - } - ); - } - { - m_output_window.reset(new FileWindowLoggerWindow((FileWindowLogger&)global_logger_raw())); - QPushButton* output = new QPushButton("Output Window", support_box); - buttons->addWidget(output); - connect( - output, &QPushButton::clicked, - this, [&](bool){ - m_output_window->show(); - m_output_window->raise(); // bring the window to front on macOS - m_output_window->activateWindow(); // bring the window to front on Windows - } - ); - // get snapshot of the saved initial x/y position, since activating the window seems to change the window coordinates, - // which then causes initial x/y position to change, due to triggering moveEvent(). - int32_t x_pos_log = GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS; - int32_t y_pos_log = GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS; - - if (GlobalSettings::instance().LOG_WINDOW_STARTUP){ // show the Output Window on startup - m_output_window->show(); - m_output_window->raise(); // bring the window to front on macOS - m_output_window->activateWindow(); // bring the window to front on Windows - } - - // move the output window to desired position on startup - int32_t move_x_log = move_x_within_screen_bounds(x_pos_log); - int32_t move_y_log = move_y_within_screen_bounds(y_pos_log); - m_output_window->move(move_x_log, move_y_log); - } - { - QPushButton* settings = new QPushButton("Settings", support_box); - m_settings = settings; - buttons->addWidget(settings); - connect( - settings, &QPushButton::clicked, - this, [this](bool){ - if (report_new_panel_intent(GlobalSettings_Descriptor::INSTANCE)){ - load_panel(nullptr, GlobalSettings_Descriptor::INSTANCE.make_panel()); - } - } - ); - } - - QVBoxLayout* right = new QVBoxLayout(); - m_right_panel_layout = right; - hbox->addLayout(right, 4); - right->setAlignment(Qt::AlignTop); - - // Load the program panel specified in the persistent setting. - m_program_list->load_persistent_panel(); - - GlobalSettings::instance().WINDOW_SIZE->WIDTH.add_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->HEIGHT.add_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->X_POS.add_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->Y_POS.add_listener(*this); - SystemSleepController::instance().add_listener(*this); -// cout << "Done constructing" << endl; -} -MainWindow::~MainWindow(){ - close_panel(); - SystemSleepController::instance().remove_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->WIDTH.remove_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->HEIGHT.remove_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->X_POS.remove_listener(*this); - GlobalSettings::instance().WINDOW_SIZE->Y_POS.remove_listener(*this); -} - -int32_t move_x_within_screen_bounds(int32_t x_pos){ - auto static const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); - uint32_t static const screen_width = (uint32_t)screen_geometry.width(); - // ensure move_x is greater than 0, but less than screen_width - return scale_dpi_width(std::max(0, std::min(x_pos, (int32_t)(screen_width*0.97)))); - -} - -int32_t move_y_within_screen_bounds(int32_t y_pos){ - auto static const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); - uint32_t const screen_height = (uint32_t)screen_geometry.height(); - // ensure move_y is greater than 0, but less than screen_height - return scale_dpi_width(std::max(0, std::min(y_pos, (int32_t)(screen_height*0.97)))); - -} - - -void MainWindow::closeEvent(QCloseEvent* event){ - close_all_windows(); - QMainWindow::closeEvent(event); -} -void MainWindow::resizeEvent(QResizeEvent* event){ - m_pending_resize = true; - GlobalSettings::instance().WINDOW_SIZE->WIDTH.set(width()); - GlobalSettings::instance().WINDOW_SIZE->HEIGHT.set(height()); - m_pending_resize = false; -} - -void MainWindow::moveEvent(QMoveEvent* event){ - m_pending_move = true; - GlobalSettings::instance().WINDOW_SIZE->X_POS.set(x()); - GlobalSettings::instance().WINDOW_SIZE->Y_POS.set(y()); - m_pending_move = false; -} - -void MainWindow::close_panel() noexcept{ -// cout << "close_panel(): enter: " << m_current_panel_widget << endl; - // Must destroy the widget first since it references the instance. - if (m_current_panel_widget != nullptr){ - m_right_panel_layout->removeWidget(m_current_panel_widget); - QWidget* widget = m_current_panel_widget; - m_current_panel_widget = nullptr; - delete widget; - } - -// cout << "close_panel(): mid: " << m_current_panel_widget << endl; - - // Now it's safe to destroy the instance. - if (m_current_panel == nullptr){ - return; - } - - try{ - m_current_panel->save_settings(); - }catch (...){} - - m_current_panel.reset(); - m_current_panel_descriptor.reset(); -} - -bool MainWindow::report_new_panel_intent(const PanelDescriptor& descriptor){ - // No active panel. Proceed with panel change. - if (m_current_panel == nullptr){ - return true; - } - - // Panel is already active. Don't change. - if (&m_current_panel->descriptor() == &descriptor){ - m_current_panel->save_settings(); - return false; - } - - return true; -} -void MainWindow::load_panel( - std::shared_ptr descriptor, - std::unique_ptr panel -){ - if (m_panel_transition){ - global_logger_tagged().log( - "Ignoring attempted panel change while existing one is still in progress.", - COLOR_RED - ); - return; - } - - m_panel_transition = true; - close_panel(); - - // Make new widget. - try{ - check_new_version(); - m_current_panel_widget = panel->make_widget(*this, *this); -// cout << "load_panel() = " << m_current_panel_widget << endl; - m_current_panel_descriptor = std::move(descriptor); - m_current_panel = std::move(panel); - m_right_panel_layout->addWidget(m_current_panel_widget); - }catch (...){ - if (m_current_panel_widget != nullptr){ - delete m_current_panel_widget; - } - m_panel_transition = false; - throw; - } - m_panel_transition = false; -} -void MainWindow::on_busy(){ - if (m_program_list){ - m_program_list->setEnabled(false); - m_settings->setEnabled(false); - } -} -void MainWindow::on_idle(){ - if (m_program_list){ - m_program_list->setEnabled(true); - m_settings->setEnabled(true); - } -} - - -void MainWindow::on_config_value_changed(void* object){ - if (object == &GlobalSettings::instance().WINDOW_SIZE->WIDTH || object == &GlobalSettings::instance().WINDOW_SIZE->HEIGHT){ - QMetaObject::invokeMethod(this, [this]{ - if (!m_pending_resize){ - resize( - GlobalSettings::instance().WINDOW_SIZE->WIDTH, - GlobalSettings::instance().WINDOW_SIZE->HEIGHT - ); - } - }); - }else if (object == &GlobalSettings::instance().WINDOW_SIZE->X_POS || object == &GlobalSettings::instance().WINDOW_SIZE->Y_POS){ - QMetaObject::invokeMethod(this, [this]{ - if (!m_pending_move){ - move( - move_x_within_screen_bounds(GlobalSettings::instance().WINDOW_SIZE->X_POS), - move_y_within_screen_bounds(GlobalSettings::instance().WINDOW_SIZE->Y_POS) - ); - } - }); - } -} -void MainWindow::sleep_suppress_state_changed(SleepSuppress new_state){ - QMetaObject::invokeMethod(this, [=, this]{ - switch (new_state){ - case PokemonAutomation::SleepSuppress::NONE: - m_sleep_text->setText("Sleep Suppress: None"); -// m_sleep_box->setEnabled(); -// m_sleep_box->setCheckState(Qt::CheckState::Unchecked); - break; - case PokemonAutomation::SleepSuppress::NO_SLEEP: - m_sleep_text->setText("Sleep Suppress: No Sleep"); - break; - case PokemonAutomation::SleepSuppress::SCREEN_ON: - m_sleep_text->setText("Sleep Suppress: Screen On"); - break; - } - }); -} - - - - -} - +/* Main Window UI + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/CpuId/CpuId.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/FileWindowLogger.h" +#include "CommonFramework/Startup/NewVersionCheck.h" +#include "CommonFramework/Options/ResolutionOption.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Windows/DpiScaler.h" +#include "PanelLists.h" +#include "WindowTracker.h" +#include "ButtonDiagram.h" +#include "MainWindow.h" + + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +MainWindow::MainWindow(QWidget* parent) + : QMainWindow(parent) + , m_current_panel_widget(nullptr) +{ + if (objectName().isEmpty()){ + setObjectName(QString::fromUtf8("MainWindow")); + } + this->setWindowIcon(QIcon(QString::fromStdString(RESOURCE_PATH() + "icon.png"))); +// QSize window_size = PERSISTENT_SETTINGS().window_size; + resize( + GlobalSettings::instance().WINDOW_SIZE->WIDTH, + GlobalSettings::instance().WINDOW_SIZE->HEIGHT + ); + // move main window to desired position on startup + // auto const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); + // uint32_t const screen_width = (uint32_t)screen_geometry.width(); + // uint32_t const screen_height = (uint32_t)screen_geometry.height(); + int32_t x_pos_main = GlobalSettings::instance().WINDOW_SIZE->X_POS; + int32_t y_pos_main = GlobalSettings::instance().WINDOW_SIZE->Y_POS; + int32_t move_x_main = move_x_within_screen_bounds(x_pos_main); + int32_t move_y_main = move_y_within_screen_bounds(y_pos_main); + move(move_x_main, move_y_main); + + centralwidget = new QWidget(this); + centralwidget->setObjectName(QString::fromUtf8("centralwidget")); + setCentralWidget(centralwidget); + menubar = new QMenuBar(this); + menubar->setObjectName(QString::fromUtf8("menubar")); + setMenuBar(menubar); +// statusbar = new QStatusBar(this); +// statusbar->setObjectName(QString::fromUtf8("statusbar")); +// setStatusBar(statusbar); + setWindowTitle(QString::fromStdString(PROGRAM_NAME + " Computer-Control Programs (" + PROGRAM_VERSION + ")")); + + QHBoxLayout* hbox = new QHBoxLayout(centralwidget); + QVBoxLayout* left_layout = new QVBoxLayout(); + hbox->addLayout(left_layout, 0); + +#if 0 + QGroupBox* program_box = new QGroupBox("Program Select", centralwidget); + left_layout->addWidget(program_box, 1); + QVBoxLayout* program_layout = new QVBoxLayout(program_box); + program_layout->setAlignment(Qt::AlignTop); + +// NoWheelComboBox* program_dropdown = new NoWheelComboBox(this); +// program_layout->addWidget(program_dropdown); + + m_program_list = new ProgramTabs(*this, *this); + program_layout->addWidget(m_program_list); +#else + m_program_list = new ProgramSelect(*this, *this); + left_layout->addWidget(m_program_list, 1); +#endif + + + QGroupBox* support_box = new QGroupBox( + QString::fromStdString(PROGRAM_NAME + " " + PROGRAM_VERSION + " (" + PA_ARCH_STRING + ")"), + centralwidget + ); + + + left_layout->addWidget(support_box); + QVBoxLayout* support_layout = new QVBoxLayout(support_box); + + { + QHBoxLayout* layout = new QHBoxLayout(); + support_layout->addLayout(layout); + layout->setAlignment(Qt::AlignHCenter); + layout->setContentsMargins(0, 0, 0, 0); + m_sleep_text = new QLabel(support_box); + layout->addWidget(m_sleep_text, 2); + m_sleep_box = new QCheckBox("Force On", support_box); + layout->addWidget(m_sleep_box, 1, Qt::AlignHCenter); + MainWindow::sleep_suppress_state_changed(SystemSleepController::instance().current_state()); +#if QT_VERSION < 0x060700 + connect( + m_sleep_box, &QCheckBox::stateChanged, + this, [this](int){ + if (m_sleep_box->isChecked()){ + m_sleep_scope.reset(new SleepSuppressScope(SleepSuppress::SCREEN_ON)); + }else{ + m_sleep_scope.reset(); + } + } + ); +#else + connect( + m_sleep_box, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ + if (state == Qt::CheckState::Checked){ + m_sleep_scope.reset(new SleepSuppressScope(SleepSuppress::SCREEN_ON)); + }else{ + m_sleep_scope.reset(); + } + } + ); +#endif + } + + QHBoxLayout* support = new QHBoxLayout(); + support_layout->addLayout(support); +// support->setContentsMargins(0, 0, 0, 0); + + QVBoxLayout* links = new QVBoxLayout(); + support->addLayout(links); + { + QLabel* github = new QLabel(support_box); + links->addWidget(github); + github->setText(QString::fromStdString(make_text_url(ONLINE_DOC_URL_BASE + "ComputerControl/", "Online Documentation"))); + github->setTextFormat(Qt::RichText); + github->setTextInteractionFlags(Qt::TextBrowserInteraction); + github->setOpenExternalLinks(true); + } + { + QLabel* discord = new QLabel(support_box); + links->addWidget(discord); + discord->setText(QString::fromStdString(make_text_url(DISCORD_LINK_URL_PROGRAM, DISCORD_LINK_TEXT))); + discord->setTextFormat(Qt::RichText); + discord->setTextInteractionFlags(Qt::TextBrowserInteraction); + discord->setOpenExternalLinks(true); + } + { + QLabel* github = new QLabel(support_box); + links->addWidget(github); + github->setText(QString::fromStdString(make_text_url(GITHUB_LINK_URL, GITHUB_LINK_TEXT))); +// github->setText("GitHub Repository"); + github->setTextFormat(Qt::RichText); + github->setTextInteractionFlags(Qt::TextBrowserInteraction); + github->setOpenExternalLinks(true); + } + { + QLabel* about = new QLabel(support_box); + links->addWidget(about); + about->setText(QString::fromStdString(make_text_url(GITHUB_LINK_URL, "About this Program"))); + about->setTextFormat(Qt::RichText); + connect( + about, &QLabel::linkActivated, + this, [](const QString&){ + std::string str; + str += PROGRAM_NAME + " Computer-Control Programs
"; + str += "Copyright: 2020 - 2025
"; + str += "Version: " + PROGRAM_VERSION + "
"; + str += "
"; + str += "Framework: Qt " + std::to_string(QT_VERSION_MAJOR); + str += "." + std::to_string(QT_VERSION_MINOR); + str += "." + std::to_string(QT_VERSION_PATCH); + str += "
"; + str += "Compiler: " + COMPILER_VERSION; + str += "

"; + str += "Made by the " + PROGRAM_NAME + " Discord Server.
"; + str += "
"; + str += "This program uses Qt and dynamically links to unmodified Qt libraries under LGPL.
"; + + QMessageBox box; + box.information(nullptr, "About", QString::fromStdString(str)); + } + ); + } + + QVBoxLayout* buttons = new QVBoxLayout(); + support->addLayout(buttons); + { + QPushButton* keyboard = new QPushButton("Keyboard Layout", support_box); + buttons->addWidget(keyboard); + m_button_diagram.reset(new ButtonDiagram()); + connect( + keyboard, &QPushButton::clicked, + this, [button = m_button_diagram.get()](bool){ + button->show(); + button->raise(); // bring the window to front on macOS + button->activateWindow(); // bring the window to front on Windows + } + ); + } + { + m_output_window.reset(new FileWindowLoggerWindow((FileWindowLogger&)global_logger_raw())); + QPushButton* output = new QPushButton("Output Window", support_box); + buttons->addWidget(output); + connect( + output, &QPushButton::clicked, + this, [&](bool){ + m_output_window->show(); + m_output_window->raise(); // bring the window to front on macOS + m_output_window->activateWindow(); // bring the window to front on Windows + } + ); + // get snapshot of the saved initial x/y position, since activating the window seems to change the window coordinates, + // which then causes initial x/y position to change, due to triggering moveEvent(). + int32_t x_pos_log = GlobalSettings::instance().LOG_WINDOW_SIZE->X_POS; + int32_t y_pos_log = GlobalSettings::instance().LOG_WINDOW_SIZE->Y_POS; + + if (GlobalSettings::instance().LOG_WINDOW_STARTUP){ // show the Output Window on startup + m_output_window->show(); + m_output_window->raise(); // bring the window to front on macOS + m_output_window->activateWindow(); // bring the window to front on Windows + } + + // move the output window to desired position on startup + int32_t move_x_log = move_x_within_screen_bounds(x_pos_log); + int32_t move_y_log = move_y_within_screen_bounds(y_pos_log); + m_output_window->move(move_x_log, move_y_log); + } + { + QPushButton* settings = new QPushButton("Settings", support_box); + m_settings = settings; + buttons->addWidget(settings); + connect( + settings, &QPushButton::clicked, + this, [this](bool){ + if (report_new_panel_intent(GlobalSettings_Descriptor::INSTANCE)){ + load_panel(nullptr, GlobalSettings_Descriptor::INSTANCE.make_panel()); + } + } + ); + } + + QVBoxLayout* right = new QVBoxLayout(); + m_right_panel_layout = right; + hbox->addLayout(right, 4); + right->setAlignment(Qt::AlignTop); + + // Load the program panel specified in the persistent setting. + m_program_list->load_persistent_panel(); + + GlobalSettings::instance().WINDOW_SIZE->WIDTH.add_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->HEIGHT.add_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->X_POS.add_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->Y_POS.add_listener(*this); + SystemSleepController::instance().add_listener(*this); +// cout << "Done constructing" << endl; +} +MainWindow::~MainWindow(){ + close_panel(); + SystemSleepController::instance().remove_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->WIDTH.remove_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->HEIGHT.remove_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->X_POS.remove_listener(*this); + GlobalSettings::instance().WINDOW_SIZE->Y_POS.remove_listener(*this); +} + +int32_t move_x_within_screen_bounds(int32_t x_pos){ + auto static const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); + uint32_t static const screen_width = (uint32_t)screen_geometry.width(); + // ensure move_x is greater than 0, but less than screen_width + return scale_dpi_width(std::max(0, std::min(x_pos, (int32_t)(screen_width*0.97)))); + +} + +int32_t move_y_within_screen_bounds(int32_t y_pos){ + auto static const screen_geometry = QGuiApplication::primaryScreen()->availableGeometry(); + uint32_t const screen_height = (uint32_t)screen_geometry.height(); + // ensure move_y is greater than 0, but less than screen_height + return scale_dpi_width(std::max(0, std::min(y_pos, (int32_t)(screen_height*0.97)))); + +} + + +void MainWindow::closeEvent(QCloseEvent* event){ + close_all_windows(); + QMainWindow::closeEvent(event); +} +void MainWindow::resizeEvent(QResizeEvent* event){ + m_pending_resize = true; + GlobalSettings::instance().WINDOW_SIZE->WIDTH.set(width()); + GlobalSettings::instance().WINDOW_SIZE->HEIGHT.set(height()); + m_pending_resize = false; +} + +void MainWindow::moveEvent(QMoveEvent* event){ + m_pending_move = true; + GlobalSettings::instance().WINDOW_SIZE->X_POS.set(x()); + GlobalSettings::instance().WINDOW_SIZE->Y_POS.set(y()); + m_pending_move = false; +} + +void MainWindow::close_panel() noexcept{ +// cout << "close_panel(): enter: " << m_current_panel_widget << endl; + // Must destroy the widget first since it references the instance. + if (m_current_panel_widget != nullptr){ + m_right_panel_layout->removeWidget(m_current_panel_widget); + QWidget* widget = m_current_panel_widget; + m_current_panel_widget = nullptr; + delete widget; + } + +// cout << "close_panel(): mid: " << m_current_panel_widget << endl; + + // Now it's safe to destroy the instance. + if (m_current_panel == nullptr){ + return; + } + + try{ + m_current_panel->save_settings(); + }catch (...){} + + m_current_panel.reset(); + m_current_panel_descriptor.reset(); +} + +bool MainWindow::report_new_panel_intent(const PanelDescriptor& descriptor){ + // No active panel. Proceed with panel change. + if (m_current_panel == nullptr){ + return true; + } + + // Panel is already active. Don't change. + if (&m_current_panel->descriptor() == &descriptor){ + m_current_panel->save_settings(); + return false; + } + + return true; +} +void MainWindow::load_panel( + std::shared_ptr descriptor, + std::unique_ptr panel +){ + if (m_panel_transition){ + global_logger_tagged().log( + "Ignoring attempted panel change while existing one is still in progress.", + COLOR_RED + ); + return; + } + + m_panel_transition = true; + close_panel(); + + // Make new widget. + try{ + check_new_version(); + m_current_panel_widget = panel->make_widget(*this, *this); +// cout << "load_panel() = " << m_current_panel_widget << endl; + m_current_panel_descriptor = std::move(descriptor); + m_current_panel = std::move(panel); + m_right_panel_layout->addWidget(m_current_panel_widget); + }catch (...){ + if (m_current_panel_widget != nullptr){ + delete m_current_panel_widget; + } + m_panel_transition = false; + throw; + } + m_panel_transition = false; +} +void MainWindow::on_busy(){ + if (m_program_list){ + m_program_list->setEnabled(false); + m_settings->setEnabled(false); + } +} +void MainWindow::on_idle(){ + if (m_program_list){ + m_program_list->setEnabled(true); + m_settings->setEnabled(true); + } +} + + +void MainWindow::on_config_value_changed(void* object){ + if (object == &GlobalSettings::instance().WINDOW_SIZE->WIDTH || object == &GlobalSettings::instance().WINDOW_SIZE->HEIGHT){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_resize){ + resize( + GlobalSettings::instance().WINDOW_SIZE->WIDTH, + GlobalSettings::instance().WINDOW_SIZE->HEIGHT + ); + } + }); + }else if (object == &GlobalSettings::instance().WINDOW_SIZE->X_POS || object == &GlobalSettings::instance().WINDOW_SIZE->Y_POS){ + QMetaObject::invokeMethod(this, [this]{ + if (!m_pending_move){ + move( + move_x_within_screen_bounds(GlobalSettings::instance().WINDOW_SIZE->X_POS), + move_y_within_screen_bounds(GlobalSettings::instance().WINDOW_SIZE->Y_POS) + ); + } + }); + } +} +void MainWindow::sleep_suppress_state_changed(SleepSuppress new_state){ + QMetaObject::invokeMethod(this, [=, this]{ + switch (new_state){ + case PokemonAutomation::SleepSuppress::NONE: + m_sleep_text->setText("Sleep Suppress: None"); +// m_sleep_box->setEnabled(); +// m_sleep_box->setCheckState(Qt::CheckState::Unchecked); + break; + case PokemonAutomation::SleepSuppress::NO_SLEEP: + m_sleep_text->setText("Sleep Suppress: No Sleep"); + break; + case PokemonAutomation::SleepSuppress::SCREEN_ON: + m_sleep_text->setText("Sleep Suppress: Screen On"); + break; + } + }); +} + + + + +} + diff --git a/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h b/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h index cb08eea269..a4818bddc1 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h +++ b/SerialPrograms/Source/CommonFramework/Windows/MainWindow.h @@ -1,101 +1,101 @@ -/* Main Window UI - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_MainWindow_H -#define PokemonAutomation_MainWindow_H - -#include -#include "Common/Cpp/Options/ConfigOption.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Environment/SystemSleep.h" -#include "CommonFramework/Panels/PanelTools.h" -#include "PanelLists.h" - -class QVBoxLayout; -class QLabel; -class QCheckBox; - -namespace PokemonAutomation{ - -class ButtonDiagram; -class FileWindowLoggerWindow; - - -class MainWindow : - public QMainWindow, - public PanelHolder, - public ConfigOption::Listener, - public SystemSleepController::Listener -{ -public: - MainWindow(QWidget* parent = nullptr); - ~MainWindow(); - - -private: - virtual void closeEvent(QCloseEvent* event) override; - virtual void resizeEvent(QResizeEvent* event) override; - virtual void moveEvent(QMoveEvent* event) override; - - void close_panel() noexcept; - - // implements PanelHolder::report_new_panel_intent() - virtual bool report_new_panel_intent(const PanelDescriptor& descriptor) override; - // implements PanelHolder::load_panel() - virtual void load_panel( - std::shared_ptr descriptor, - std::unique_ptr panel - ) override; - // implements PanelHolder::raw_logger() - virtual Logger& raw_logger() override{ return global_logger_raw(); } - -private: - // implements PanelHolder::on_busy() - // called when an automation program is running - virtual void on_busy() override; - // implements PanelHolder::on_idle() - // called when no automation program is not running - virtual void on_idle() override; - virtual void on_config_value_changed(void* object) override; - virtual void sleep_suppress_state_changed(SleepSuppress new_state) override; - -private: - QWidget* centralwidget; - QMenuBar* menubar; -// QStatusBar* statusbar; - -// ProgramTabs* m_program_list = nullptr; - ProgramSelect* m_program_list = nullptr; - QVBoxLayout* m_right_panel_layout; - - QWidget* m_settings; - - // Keep a reference to the panel descriptor since it is referenced by the - // panel instance and the original descriptor may destroyed at any time. - std::shared_ptr m_current_panel_descriptor; - std::unique_ptr m_current_panel; - QWidget* m_current_panel_widget; - - std::unique_ptr m_button_diagram; - std::unique_ptr m_output_window; - - QLabel* m_sleep_text; - QCheckBox* m_sleep_box; - std::unique_ptr m_sleep_scope; - - bool m_pending_resize = false; - bool m_pending_move = false; - bool m_panel_transition = false; -}; - -// returns given X value, but bounded by 0 and screen_width -int32_t move_x_within_screen_bounds(int32_t x_pos); -// returns given y value, but bounded by 0 and screen_height -int32_t move_y_within_screen_bounds(int32_t y_pos); - - -} -#endif +/* Main Window UI + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_MainWindow_H +#define PokemonAutomation_MainWindow_H + +#include +#include "Common/Cpp/Options/ConfigOption.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Environment/SystemSleep.h" +#include "CommonFramework/Panels/PanelTools.h" +#include "PanelLists.h" + +class QVBoxLayout; +class QLabel; +class QCheckBox; + +namespace PokemonAutomation{ + +class ButtonDiagram; +class FileWindowLoggerWindow; + + +class MainWindow : + public QMainWindow, + public PanelHolder, + public ConfigOption::Listener, + public SystemSleepController::Listener +{ +public: + MainWindow(QWidget* parent = nullptr); + ~MainWindow(); + + +private: + virtual void closeEvent(QCloseEvent* event) override; + virtual void resizeEvent(QResizeEvent* event) override; + virtual void moveEvent(QMoveEvent* event) override; + + void close_panel() noexcept; + + // implements PanelHolder::report_new_panel_intent() + virtual bool report_new_panel_intent(const PanelDescriptor& descriptor) override; + // implements PanelHolder::load_panel() + virtual void load_panel( + std::shared_ptr descriptor, + std::unique_ptr panel + ) override; + // implements PanelHolder::raw_logger() + virtual Logger& raw_logger() override{ return global_logger_raw(); } + +private: + // implements PanelHolder::on_busy() + // called when an automation program is running + virtual void on_busy() override; + // implements PanelHolder::on_idle() + // called when no automation program is not running + virtual void on_idle() override; + virtual void on_config_value_changed(void* object) override; + virtual void sleep_suppress_state_changed(SleepSuppress new_state) override; + +private: + QWidget* centralwidget; + QMenuBar* menubar; +// QStatusBar* statusbar; + +// ProgramTabs* m_program_list = nullptr; + ProgramSelect* m_program_list = nullptr; + QVBoxLayout* m_right_panel_layout; + + QWidget* m_settings; + + // Keep a reference to the panel descriptor since it is referenced by the + // panel instance and the original descriptor may destroyed at any time. + std::shared_ptr m_current_panel_descriptor; + std::unique_ptr m_current_panel; + QWidget* m_current_panel_widget; + + std::unique_ptr m_button_diagram; + std::unique_ptr m_output_window; + + QLabel* m_sleep_text; + QCheckBox* m_sleep_box; + std::unique_ptr m_sleep_scope; + + bool m_pending_resize = false; + bool m_pending_move = false; + bool m_panel_transition = false; +}; + +// returns given X value, but bounded by 0 and screen_width +int32_t move_x_within_screen_bounds(int32_t x_pos); +// returns given y value, but bounded by 0 and screen_height +int32_t move_y_within_screen_bounds(int32_t y_pos); + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).cpp b/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).cpp index 4987988128..0c779cda64 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).cpp +++ b/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).cpp @@ -1,148 +1,148 @@ -/* Text Window for Output Logging - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -//#include -#include "CommonFramework/PersistentSettings.h" -#include "OutputWindow.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -TaggedLoggerOld::TaggedLoggerOld(OutputWindow& window, QString tag) - : m_tag(std::move(tag)) -{ - connect( - this, &TaggedLoggerOld::signal_log, - &window, &OutputWindow::log - ); -} -void TaggedLoggerOld::log(const char* msg, QColor color){ - QString body = - QString::fromStdString(PokemonAutomation::current_time()) + - " - [" + m_tag + "]: " + - msg; -// cout << color.toUtf8().data() << " - " << body.toUtf8().data() << endl; - signal_log(std::move(body), color); -} -void TaggedLoggerOld::log(const std::string& msg, QColor color){ - QString body = - QString::fromStdString(PokemonAutomation::current_time()) + - " - [" + m_tag + "]: " + - QString::fromStdString(msg); -// cout << color.toUtf8().data() << " - " << body.toUtf8().data() << endl; - signal_log(std::move(body), color); -} -void TaggedLoggerOld::log(const QString& msg, QColor color){ - QString body = - QString::fromStdString(PokemonAutomation::current_time()) + - " - [" + m_tag + "]: " + - msg; -// cout << color.toUtf8().data() << " - " << body.toUtf8().data() << endl; - signal_log(std::move(body), color); -} - - -SerialLoggerOld::SerialLoggerOld(OutputWindow& window, QString tag) - : TaggedLoggerOld(window, std::move(tag)) - , PokemonAutomation::MessageLogger(PERSISTENT_SETTINGS().log_everything) -{} -void SerialLoggerOld::log(std::string msg){ - TaggedLoggerOld::log(msg, "green"); -} - - -OutputWindow::OutputWindow(QWidget* parent) - : QMainWindow(parent) -{ - if (objectName().isEmpty()){ - setObjectName(QString::fromUtf8("TextWindow")); - } - resize(800, 600); - m_text = new QTextEdit(this); - m_text->setObjectName(QString::fromUtf8("centralwidget")); - setCentralWidget(m_text); - m_menubar = new QMenuBar(this); - m_menubar->setObjectName(QString::fromUtf8("menubar")); - setMenuBar(m_menubar); -// m_statusbar = new QStatusBar(this); -// m_statusbar->setObjectName(QString::fromUtf8("statusbar")); -// setStatusBar(m_statusbar); - setWindowTitle("Program Output"); - - m_text->setReadOnly(true); - m_text->setAcceptRichText(true); - m_text->document()->setMaximumBlockCount(1000); - m_default_color = m_text->textColor(); - - m_log_file.setFileName(QCoreApplication::applicationFilePath() + ".log"); - bool exists = m_log_file.exists(); - m_log_file.open(QIODevice::WriteOnly | QIODevice::Append); - if (!exists){ - std::string bom = "\xef\xbb\xbf"; - m_log_file.write(bom.c_str(), bom.size()); - } - - log("================================================================================", ""); - log( - QString::fromStdString(PokemonAutomation::current_time()) + - " - [Application]: " + - "Application Startup...", - "" - ); -} -OutputWindow::~OutputWindow(){ - m_log_file.close(); -} - -void OutputWindow::log(QString msg, QColor color){ - // Replace all newlines with: - //
for the output window. - // \r\n for the log file. - - QString window_str = ""; - QString file_str; - bool pending_carrage_return = false; - for (QChar ch : msg){ - if (pending_carrage_return && ch == '\n'){ - window_str += "
"; - file_str += "\r\n"; - pending_carrage_return = false; - continue; - } - pending_carrage_return = false; - if (ch == '\n'){ - window_str += "
"; - file_str += "\r\n"; - continue; - } - window_str += ch; - file_str += ch; - } - - if (file_str.back() == "\n"){ - window_str.resize(window_str.size() - 4); - file_str.resize(file_str.size() - 2); - } - - window_str += "
"; - m_text->append(window_str); - - msg += "\r\n"; - m_log_file.write(msg.toUtf8().data()); - m_log_file.flush(); -} - - - - -} +/* Text Window for Output Logging + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +//#include +#include "CommonFramework/PersistentSettings.h" +#include "OutputWindow.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +TaggedLoggerOld::TaggedLoggerOld(OutputWindow& window, QString tag) + : m_tag(std::move(tag)) +{ + connect( + this, &TaggedLoggerOld::signal_log, + &window, &OutputWindow::log + ); +} +void TaggedLoggerOld::log(const char* msg, QColor color){ + QString body = + QString::fromStdString(PokemonAutomation::current_time()) + + " - [" + m_tag + "]: " + + msg; +// cout << color.toUtf8().data() << " - " << body.toUtf8().data() << endl; + signal_log(std::move(body), color); +} +void TaggedLoggerOld::log(const std::string& msg, QColor color){ + QString body = + QString::fromStdString(PokemonAutomation::current_time()) + + " - [" + m_tag + "]: " + + QString::fromStdString(msg); +// cout << color.toUtf8().data() << " - " << body.toUtf8().data() << endl; + signal_log(std::move(body), color); +} +void TaggedLoggerOld::log(const QString& msg, QColor color){ + QString body = + QString::fromStdString(PokemonAutomation::current_time()) + + " - [" + m_tag + "]: " + + msg; +// cout << color.toUtf8().data() << " - " << body.toUtf8().data() << endl; + signal_log(std::move(body), color); +} + + +SerialLoggerOld::SerialLoggerOld(OutputWindow& window, QString tag) + : TaggedLoggerOld(window, std::move(tag)) + , PokemonAutomation::MessageLogger(PERSISTENT_SETTINGS().log_everything) +{} +void SerialLoggerOld::log(std::string msg){ + TaggedLoggerOld::log(msg, "green"); +} + + +OutputWindow::OutputWindow(QWidget* parent) + : QMainWindow(parent) +{ + if (objectName().isEmpty()){ + setObjectName(QString::fromUtf8("TextWindow")); + } + resize(800, 600); + m_text = new QTextEdit(this); + m_text->setObjectName(QString::fromUtf8("centralwidget")); + setCentralWidget(m_text); + m_menubar = new QMenuBar(this); + m_menubar->setObjectName(QString::fromUtf8("menubar")); + setMenuBar(m_menubar); +// m_statusbar = new QStatusBar(this); +// m_statusbar->setObjectName(QString::fromUtf8("statusbar")); +// setStatusBar(m_statusbar); + setWindowTitle("Program Output"); + + m_text->setReadOnly(true); + m_text->setAcceptRichText(true); + m_text->document()->setMaximumBlockCount(1000); + m_default_color = m_text->textColor(); + + m_log_file.setFileName(QCoreApplication::applicationFilePath() + ".log"); + bool exists = m_log_file.exists(); + m_log_file.open(QIODevice::WriteOnly | QIODevice::Append); + if (!exists){ + std::string bom = "\xef\xbb\xbf"; + m_log_file.write(bom.c_str(), bom.size()); + } + + log("================================================================================", ""); + log( + QString::fromStdString(PokemonAutomation::current_time()) + + " - [Application]: " + + "Application Startup...", + "" + ); +} +OutputWindow::~OutputWindow(){ + m_log_file.close(); +} + +void OutputWindow::log(QString msg, QColor color){ + // Replace all newlines with: + //
for the output window. + // \r\n for the log file. + + QString window_str = ""; + QString file_str; + bool pending_carrage_return = false; + for (QChar ch : msg){ + if (pending_carrage_return && ch == '\n'){ + window_str += "
"; + file_str += "\r\n"; + pending_carrage_return = false; + continue; + } + pending_carrage_return = false; + if (ch == '\n'){ + window_str += "
"; + file_str += "\r\n"; + continue; + } + window_str += ch; + file_str += ch; + } + + if (file_str.back() == "\n"){ + window_str.resize(window_str.size() - 4); + file_str.resize(file_str.size() - 2); + } + + window_str += "
"; + m_text->append(window_str); + + msg += "\r\n"; + m_log_file.write(msg.toUtf8().data()); + m_log_file.flush(); +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).h b/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).h index 771fe36075..4ce2c4aa01 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).h +++ b/SerialPrograms/Source/CommonFramework/Windows/OutputWindow (disabled).h @@ -1,69 +1,69 @@ -/* Text Window for Output Logging - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_TextWindow_H -#define PokemonAutomation_TextWindow_H - -#include -#include -#include -#include "ClientSource/Libraries/Logging.h" -#include "CommonFramework/Logging/Logger.h" - -namespace PokemonAutomation{ - - -class OutputWindow; - -class TaggedLoggerOld : public QObject, public Logger{ - Q_OBJECT - -public: - TaggedLoggerOld(OutputWindow& window, QString tag); - virtual void log(const char* msg, Color color = QColor()) override; - virtual void log(const std::string& msg, Color color = QColor()) override; - virtual void log(const QString& msg, Color color = QColor()) override; - -signals: - void signal_log(QString msg, Color color); - -private: - const QString m_tag; -}; - -class SerialLoggerOld : public TaggedLoggerOld, public PokemonAutomation::MessageLogger{ -public: - SerialLoggerOld(OutputWindow& window, QString tag); - using TaggedLoggerOld::log; - virtual void log(std::string msg) override; -}; - - -class OutputWindow : public QMainWindow{ - Q_OBJECT - -public: - OutputWindow(QWidget *parent = nullptr); - ~OutputWindow(); - - void operator+=(TaggedLoggerOld& logger); - void operator-=(TaggedLoggerOld& logger); - -public slots: - void log(QString msg, Color color); - -private: - QColor m_default_color; - QTextEdit* m_text; - QMenuBar* m_menubar; -// QStatusBar* m_statusbar; - QFile m_log_file; -}; - - - -} -#endif +/* Text Window for Output Logging + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_TextWindow_H +#define PokemonAutomation_TextWindow_H + +#include +#include +#include +#include "ClientSource/Libraries/Logging.h" +#include "CommonFramework/Logging/Logger.h" + +namespace PokemonAutomation{ + + +class OutputWindow; + +class TaggedLoggerOld : public QObject, public Logger{ + Q_OBJECT + +public: + TaggedLoggerOld(OutputWindow& window, QString tag); + virtual void log(const char* msg, Color color = QColor()) override; + virtual void log(const std::string& msg, Color color = QColor()) override; + virtual void log(const QString& msg, Color color = QColor()) override; + +signals: + void signal_log(QString msg, Color color); + +private: + const QString m_tag; +}; + +class SerialLoggerOld : public TaggedLoggerOld, public PokemonAutomation::MessageLogger{ +public: + SerialLoggerOld(OutputWindow& window, QString tag); + using TaggedLoggerOld::log; + virtual void log(std::string msg) override; +}; + + +class OutputWindow : public QMainWindow{ + Q_OBJECT + +public: + OutputWindow(QWidget *parent = nullptr); + ~OutputWindow(); + + void operator+=(TaggedLoggerOld& logger); + void operator-=(TaggedLoggerOld& logger); + +public slots: + void log(QString msg, Color color); + +private: + QColor m_default_color; + QTextEdit* m_text; + QMenuBar* m_menubar; +// QStatusBar* m_statusbar; + QFile m_log_file; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.cpp b/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.cpp index 3abc4f2ccc..e708aaf4a3 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.cpp +++ b/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.cpp @@ -1,51 +1,51 @@ -/* WindowTracker.cpp - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "WindowTracker.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -std::mutex window_lock; -std::set open_windows; - -void add_window(QMainWindow& window){ - std::lock_guard lock(window_lock); - open_windows.insert(&window); -} -void remove_window(QMainWindow& window){ - std::lock_guard lock(window_lock); - open_windows.erase(&window); -} -void close_all_windows(){ - while (true){ - QMainWindow* window = nullptr; - { - std::lock_guard lock(window_lock); -// cout << "open_windows.size() = " << open_windows.size() << endl; - if (open_windows.empty()){ - return; - } - auto iter = open_windows.begin(); - window = *iter; - open_windows.erase(iter); - } - window->close(); - } -} - - - - -} +/* WindowTracker.cpp + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "WindowTracker.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +std::mutex window_lock; +std::set open_windows; + +void add_window(QMainWindow& window){ + std::lock_guard lock(window_lock); + open_windows.insert(&window); +} +void remove_window(QMainWindow& window){ + std::lock_guard lock(window_lock); + open_windows.erase(&window); +} +void close_all_windows(){ + while (true){ + QMainWindow* window = nullptr; + { + std::lock_guard lock(window_lock); +// cout << "open_windows.size() = " << open_windows.size() << endl; + if (open_windows.empty()){ + return; + } + auto iter = open_windows.begin(); + window = *iter; + open_windows.erase(iter); + } + window->close(); + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.h b/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.h index 0dcdd1c230..20b0eb0d9c 100644 --- a/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.h +++ b/SerialPrograms/Source/CommonFramework/Windows/WindowTracker.h @@ -1,21 +1,21 @@ -/* WindowTracker.h - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_WindowTracker_H -#define PokemonAutomation_WindowTracker_H - -class QMainWindow; - -namespace PokemonAutomation{ - - -void add_window(QMainWindow& window); -void remove_window(QMainWindow& window); -void close_all_windows(); - - -} -#endif +/* WindowTracker.h + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_WindowTracker_H +#define PokemonAutomation_WindowTracker_H + +class QMainWindow; + +namespace PokemonAutomation{ + + +void add_window(QMainWindow& window); +void remove_window(QMainWindow& window); +void close_all_windows(); + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp index 2c9d9a0a11..5a4c579496 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp +++ b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.cpp @@ -1,121 +1,121 @@ -/* Visual Inference Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "InferenceSession.h" -#include "InferenceRoutines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -int wait_until( - VideoStream& stream, CancellableScope& scope, - WallClock deadline, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -){ - CancellableHolder subscope(scope); - InferenceSession session( - subscope, stream, - callbacks, - default_video_period, default_audio_period - ); - - try{ - subscope.wait_until(deadline); - }catch (OperationCancelledException&){} - - subscope.throw_if_cancelled_with_exception(); - scope.throw_if_cancelled(); - - return session.triggered_index(); -} - - - - -int run_until( - VideoStream& stream, CancellableScope& scope, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -){ - CancellableHolder subscope(scope); - InferenceSession session( - subscope, stream, - callbacks, - default_video_period, default_audio_period - ); - - try{ - command(subscope); - }catch (OperationCancelledException&){} - - subscope.throw_if_cancelled_with_exception(); - scope.throw_if_cancelled(); - - return session.triggered_index(); -} - - - -#if 1 -int run_until_with_time_limit( - ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, - WallClock deadline, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -){ - CancellableHolder subscope(scope); - InferenceSession session( - subscope, stream, - callbacks, - default_video_period, default_audio_period - ); - - bool timed_out = false; - std::unique_ptr timer = env.realtime_dispatcher().dispatch([&]{ - subscope.wait_until(deadline); - timed_out = true; - subscope.cancel(nullptr); - }); - - try{ - if (command){ - command(subscope); - } -// subscope.wait_for_all_requests(); - }catch (OperationCancelledException&){} - - timer->wait_and_rethrow_exceptions(); - subscope.throw_if_cancelled_with_exception(); - scope.throw_if_cancelled(); - - return timed_out ? -2 : session.triggered_index(); -} -#endif - - - - - - -} - - - +/* Visual Inference Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "InferenceSession.h" +#include "InferenceRoutines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +int wait_until( + VideoStream& stream, CancellableScope& scope, + WallClock deadline, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +){ + CancellableHolder subscope(scope); + InferenceSession session( + subscope, stream, + callbacks, + default_video_period, default_audio_period + ); + + try{ + subscope.wait_until(deadline); + }catch (OperationCancelledException&){} + + subscope.throw_if_cancelled_with_exception(); + scope.throw_if_cancelled(); + + return session.triggered_index(); +} + + + + +int run_until( + VideoStream& stream, CancellableScope& scope, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +){ + CancellableHolder subscope(scope); + InferenceSession session( + subscope, stream, + callbacks, + default_video_period, default_audio_period + ); + + try{ + command(subscope); + }catch (OperationCancelledException&){} + + subscope.throw_if_cancelled_with_exception(); + scope.throw_if_cancelled(); + + return session.triggered_index(); +} + + + +#if 1 +int run_until_with_time_limit( + ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, + WallClock deadline, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +){ + CancellableHolder subscope(scope); + InferenceSession session( + subscope, stream, + callbacks, + default_video_period, default_audio_period + ); + + bool timed_out = false; + std::unique_ptr timer = env.realtime_dispatcher().dispatch([&]{ + subscope.wait_until(deadline); + timed_out = true; + subscope.cancel(nullptr); + }); + + try{ + if (command){ + command(subscope); + } +// subscope.wait_for_all_requests(); + }catch (OperationCancelledException&){} + + timer->wait_and_rethrow_exceptions(); + subscope.throw_if_cancelled_with_exception(); + scope.throw_if_cancelled(); + + return timed_out ? -2 : session.triggered_index(); +} +#endif + + + + + + +} + + + diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h index d13cbfcb27..07be1d9c62 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h +++ b/SerialPrograms/Source/CommonTools/Async/InferenceRoutines.h @@ -1,119 +1,119 @@ -/* Inference Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceRoutines_H -#define PokemonAutomation_CommonTools_InferenceRoutines_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/InferenceCallback.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -class ProgramEnvironment; - - -// Wait until one of the "callbacks" are triggered or it times out. -// -// Returns: -// - The index of the trigger if that's what stopped it. -// - -1 if nothing triggered before timeout. -// -// Exceptions thrown in either the commands or the callbacks will stop -// everything and will be propagated out of this function. -int wait_until( - VideoStream& stream, CancellableScope& scope, - WallClock deadline, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -); -inline int wait_until( - VideoStream& stream, CancellableScope& scope, - std::chrono::milliseconds timeout, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - return wait_until( - stream, scope, - current_time() + timeout, - callbacks, - default_video_period, default_audio_period - ); -} - - -// Run the specified "command" until either it finishes or one of the -// "callbacks" are triggered. -// -// Returns: -// - The index of the trigger if that's what stopped it. -// - -1 if nothing triggered before command finished. -// -// Exceptions thrown in either the commands or the callbacks will stop -// everything and will be propagated out of this function. -int run_until( - VideoStream& stream, CancellableScope& scope, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -); -template -int run_until( - VideoStream& stream, ControllerContext& context, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - return run_until( - stream, context, - [&](CancellableScope& scope){ - ControllerContext subcontext(scope, context); - command(subcontext); - subcontext.wait_for_all_requests(); - }, - callbacks, - default_video_period, - default_audio_period - ); -} - - -#if 1 -// Same as "run_until()", but will cancel the commands and return if a timeout -// is reached. -// -// Returns: -// - The index of the trigger if that's what stopped it. -// - -1 if nothing triggered before command finished. -// - -2 if timed out. Nothing triggered, and command did not finish. -// -int run_until_with_time_limit( - ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, - WallClock deadline, - std::function&& command, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -); -#endif - - - - - -} -#endif +/* Inference Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceRoutines_H +#define PokemonAutomation_CommonTools_InferenceRoutines_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/InferenceCallback.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +class ProgramEnvironment; + + +// Wait until one of the "callbacks" are triggered or it times out. +// +// Returns: +// - The index of the trigger if that's what stopped it. +// - -1 if nothing triggered before timeout. +// +// Exceptions thrown in either the commands or the callbacks will stop +// everything and will be propagated out of this function. +int wait_until( + VideoStream& stream, CancellableScope& scope, + WallClock deadline, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +); +inline int wait_until( + VideoStream& stream, CancellableScope& scope, + std::chrono::milliseconds timeout, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + return wait_until( + stream, scope, + current_time() + timeout, + callbacks, + default_video_period, default_audio_period + ); +} + + +// Run the specified "command" until either it finishes or one of the +// "callbacks" are triggered. +// +// Returns: +// - The index of the trigger if that's what stopped it. +// - -1 if nothing triggered before command finished. +// +// Exceptions thrown in either the commands or the callbacks will stop +// everything and will be propagated out of this function. +int run_until( + VideoStream& stream, CancellableScope& scope, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +); +template +int run_until( + VideoStream& stream, ControllerContext& context, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + return run_until( + stream, context, + [&](CancellableScope& scope){ + ControllerContext subcontext(scope, context); + command(subcontext); + subcontext.wait_for_all_requests(); + }, + callbacks, + default_video_period, + default_audio_period + ); +} + + +#if 1 +// Same as "run_until()", but will cancel the commands and return if a timeout +// is reached. +// +// Returns: +// - The index of the trigger if that's what stopped it. +// - -1 if nothing triggered before command finished. +// - -2 if timed out. Nothing triggered, and command did not finish. +// +int run_until_with_time_limit( + ProgramEnvironment& env, VideoStream& stream, CancellableScope& scope, + WallClock deadline, + std::function&& command, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +); +#endif + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp b/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp index d71afe517b..08bd9cc774 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp +++ b/SerialPrograms/Source/CommonTools/Async/InferenceSession.cpp @@ -1,105 +1,105 @@ -/* Inference Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" -#include "CommonTools/InferencePivots/VisualInferencePivot.h" -#include "CommonTools/InferencePivots/AudioInferencePivot.h" -#include "InferenceSession.h" - -namespace PokemonAutomation{ - - -InferenceSession::InferenceSession( - Cancellable& scope, VideoStream& stream, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period, - std::chrono::milliseconds default_audio_period -) - : m_stream(stream) - , m_overlays(stream.overlay()) - , m_triggered(nullptr) -{ - try{ - for (size_t c = 0; c < callbacks.size(); c++){ - const PeriodicInferenceCallback& callback = callbacks[c]; - if (callback.callback == nullptr){ - continue; - } - if (!m_map.emplace(callback.callback, c).second){ - throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); - } - switch (callback.callback->type()){ - case InferenceType::VISUAL:{ - VisualInferenceCallback& visual_callback = static_cast(*callback.callback); - stream.video_inference_pivot().add_callback( - scope, &m_triggered, - visual_callback, - callback.period > std::chrono::milliseconds(0) ? callback.period : default_video_period - ); - visual_callback.make_overlays(m_overlays); - break; - } - case InferenceType::AUDIO: - stream.audio_inference_pivot().add_callback( - scope, &m_triggered, - static_cast(*callback.callback), - callback.period > std::chrono::milliseconds(0) ? callback.period : default_audio_period - ); - break; - } - } - }catch (...){ - clear(); - throw; - } -} -InferenceSession::~InferenceSession(){ - clear(); -} - - -InferenceCallback* InferenceSession::triggered_ptr() const{ - return m_triggered.load(std::memory_order_acquire); -} -int InferenceSession::triggered_index() const{ - auto iter = m_map.find(m_triggered.load(std::memory_order_acquire)); - if (iter != m_map.end()){ - return (int)iter->second; - } - return -1; -} - - -void InferenceSession::clear() noexcept{ - const double DIVIDER = (double)(std::chrono::milliseconds(1) / std::chrono::microseconds(1)); - const char* UNITS = " ms"; - for (auto& item : m_map){ - switch (item.first->type()){ - case InferenceType::VISUAL:{ - StatAccumulatorI32 stats = m_stream.video_inference_pivot().remove_callback(static_cast(*item.first)); - try{ - stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); - }catch (...){} - break; - } - case InferenceType::AUDIO:{ - StatAccumulatorI32 stats = m_stream.audio_inference_pivot().remove_callback(static_cast(*item.first)); - try{ - stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); - }catch (...){} - break; - } - } - } -} - - - - -} +/* Inference Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" +#include "CommonTools/InferencePivots/VisualInferencePivot.h" +#include "CommonTools/InferencePivots/AudioInferencePivot.h" +#include "InferenceSession.h" + +namespace PokemonAutomation{ + + +InferenceSession::InferenceSession( + Cancellable& scope, VideoStream& stream, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period, + std::chrono::milliseconds default_audio_period +) + : m_stream(stream) + , m_overlays(stream.overlay()) + , m_triggered(nullptr) +{ + try{ + for (size_t c = 0; c < callbacks.size(); c++){ + const PeriodicInferenceCallback& callback = callbacks[c]; + if (callback.callback == nullptr){ + continue; + } + if (!m_map.emplace(callback.callback, c).second){ + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); + } + switch (callback.callback->type()){ + case InferenceType::VISUAL:{ + VisualInferenceCallback& visual_callback = static_cast(*callback.callback); + stream.video_inference_pivot().add_callback( + scope, &m_triggered, + visual_callback, + callback.period > std::chrono::milliseconds(0) ? callback.period : default_video_period + ); + visual_callback.make_overlays(m_overlays); + break; + } + case InferenceType::AUDIO: + stream.audio_inference_pivot().add_callback( + scope, &m_triggered, + static_cast(*callback.callback), + callback.period > std::chrono::milliseconds(0) ? callback.period : default_audio_period + ); + break; + } + } + }catch (...){ + clear(); + throw; + } +} +InferenceSession::~InferenceSession(){ + clear(); +} + + +InferenceCallback* InferenceSession::triggered_ptr() const{ + return m_triggered.load(std::memory_order_acquire); +} +int InferenceSession::triggered_index() const{ + auto iter = m_map.find(m_triggered.load(std::memory_order_acquire)); + if (iter != m_map.end()){ + return (int)iter->second; + } + return -1; +} + + +void InferenceSession::clear() noexcept{ + const double DIVIDER = (double)(std::chrono::milliseconds(1) / std::chrono::microseconds(1)); + const char* UNITS = " ms"; + for (auto& item : m_map){ + switch (item.first->type()){ + case InferenceType::VISUAL:{ + StatAccumulatorI32 stats = m_stream.video_inference_pivot().remove_callback(static_cast(*item.first)); + try{ + stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); + }catch (...){} + break; + } + case InferenceType::AUDIO:{ + StatAccumulatorI32 stats = m_stream.audio_inference_pivot().remove_callback(static_cast(*item.first)); + try{ + stats.log(m_stream.logger(), item.first->label(), UNITS, DIVIDER); + }catch (...){} + break; + } + } + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Async/InferenceSession.h b/SerialPrograms/Source/CommonTools/Async/InferenceSession.h index 5b512953b3..13946d9fef 100644 --- a/SerialPrograms/Source/CommonTools/Async/InferenceSession.h +++ b/SerialPrograms/Source/CommonTools/Async/InferenceSession.h @@ -1,71 +1,71 @@ -/* Inference Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceSession_H -#define PokemonAutomation_CommonTools_InferenceSession_H - -#include -#include -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/InferenceCallback.h" - -namespace PokemonAutomation{ - -class Cancellable; -class VideoStream; - - - -// -// On construction, all the callbacks are attached to inference threads and -// begin running at their specified period. -// -// Upon destruction, all callbacks are removed from the inference threads and -// stop running. -// -// When a callback returns true or throws an exception, "scope.cancel()" will -// be called. -// -// "triggered_ptr()/triggered_index()" gives the first callback that -// returned true. If nothing has returned true, it is null or -1 respectively. -// -// Note that the callbacks will continue running even if one of them has -// returned true. So it is expected that the object will be destructed soon -// after "scope.cancel()" is called. -// -class InferenceSession{ -public: - InferenceSession( - Cancellable& scope, VideoStream& stream, - const std::vector& callbacks, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) - ); - ~InferenceSession(); - - InferenceCallback* triggered_ptr() const; - int triggered_index() const; - - -private: - void clear() noexcept; - - -private: - VideoStream& m_stream; - VideoOverlaySet m_overlays; - std::map m_map; - std::atomic m_triggered; -}; - - - - - -} -#endif +/* Inference Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceSession_H +#define PokemonAutomation_CommonTools_InferenceSession_H + +#include +#include +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/InferenceCallback.h" + +namespace PokemonAutomation{ + +class Cancellable; +class VideoStream; + + + +// +// On construction, all the callbacks are attached to inference threads and +// begin running at their specified period. +// +// Upon destruction, all callbacks are removed from the inference threads and +// stop running. +// +// When a callback returns true or throws an exception, "scope.cancel()" will +// be called. +// +// "triggered_ptr()/triggered_index()" gives the first callback that +// returned true. If nothing has returned true, it is null or -1 respectively. +// +// Note that the callbacks will continue running even if one of them has +// returned true. So it is expected that the object will be destructed soon +// after "scope.cancel()" is called. +// +class InferenceSession{ +public: + InferenceSession( + Cancellable& scope, VideoStream& stream, + const std::vector& callbacks, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) + ); + ~InferenceSession(); + + InferenceCallback* triggered_ptr() const; + int triggered_index() const; + + +private: + void clear() noexcept; + + +private: + VideoStream& m_stream; + VideoOverlaySet m_overlays; + std::map m_map; + std::atomic m_triggered; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h index 892be246af..be6e6cd9cf 100644 --- a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h +++ b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.h @@ -1,87 +1,87 @@ -/* Interruptable Commands - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InterruptableCommands_H -#define PokemonAutomation_CommonTools_InterruptableCommands_H - -#include -#include -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" - - -namespace PokemonAutomation{ - -class Logger; -class ProgramEnvironment; - - -template -class AsyncCommandSession final : private Cancellable{ - using ControllerContextType = typename ControllerType::ContextType; - -public: - AsyncCommandSession( - CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, - ControllerType& controller - ); - virtual ~AsyncCommandSession(); - - bool command_is_running(); - - // Stop the entire session. If an exception was thrown from the command - // thread, it will be rethrown here. - // - // It is important that exceptions in the command thread be passed up - // since it is how cancellations are implemented. Therefore you MUST - // call this prior to all natural* destruction points. - // - // *Do not call this during a stack-unwind as it's UB to throw while - // unwinding. In such cases, the exception from the command thread will be - // silently dropped in favor of the exception that's causing the current - // unwind. - void stop_session_and_rethrow(); - - -public: - // Stop the currently running command. - void stop_command(); - - // Dispath the following lambda. If something is already running, it will be - // stopped and replaced with this one. - void dispatch(std::function&& lambda); - - // Wait for currently running command to finish. - void wait(); - - -private: - virtual bool cancel(std::exception_ptr exception) noexcept override; - void thread_loop(); - - -private: - struct CommandSet; - - Logger& m_logger; - ControllerType& m_controller; - std::unique_ptr m_current; - - std::mutex m_lock; - std::condition_variable m_cv; - std::unique_ptr m_thread; - - LifetimeSanitizer m_sanitizer; -}; - - - - - - - -} -#endif +/* Interruptable Commands + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InterruptableCommands_H +#define PokemonAutomation_CommonTools_InterruptableCommands_H + +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" + + +namespace PokemonAutomation{ + +class Logger; +class ProgramEnvironment; + + +template +class AsyncCommandSession final : private Cancellable{ + using ControllerContextType = typename ControllerType::ContextType; + +public: + AsyncCommandSession( + CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, + ControllerType& controller + ); + virtual ~AsyncCommandSession(); + + bool command_is_running(); + + // Stop the entire session. If an exception was thrown from the command + // thread, it will be rethrown here. + // + // It is important that exceptions in the command thread be passed up + // since it is how cancellations are implemented. Therefore you MUST + // call this prior to all natural* destruction points. + // + // *Do not call this during a stack-unwind as it's UB to throw while + // unwinding. In such cases, the exception from the command thread will be + // silently dropped in favor of the exception that's causing the current + // unwind. + void stop_session_and_rethrow(); + + +public: + // Stop the currently running command. + void stop_command(); + + // Dispath the following lambda. If something is already running, it will be + // stopped and replaced with this one. + void dispatch(std::function&& lambda); + + // Wait for currently running command to finish. + void wait(); + + +private: + virtual bool cancel(std::exception_ptr exception) noexcept override; + void thread_loop(); + + +private: + struct CommandSet; + + Logger& m_logger; + ControllerType& m_controller; + std::unique_ptr m_current; + + std::mutex m_lock; + std::condition_variable m_cv; + std::unique_ptr m_thread; + + LifetimeSanitizer m_sanitizer; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp index c495909b76..95632ecad6 100644 --- a/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp +++ b/SerialPrograms/Source/CommonTools/Async/InterruptableCommands.tpp @@ -1,205 +1,205 @@ -/* Async Command Set - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "InterruptableCommands.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -template -struct AsyncCommandSession::CommandSet{ - CommandSet( - CancellableScope& parent, ControllerType& controller, - std::function&& lambda - ); - CancellableHolder scope; - ControllerContextType context; - std::function commands; -}; - - - -template -AsyncCommandSession::CommandSet::CommandSet( - CancellableScope& parent, ControllerType& controller, - std::function&& lambda -) - : scope(parent) - , context(scope, controller) - , commands(std::move(lambda)) -{} - - - -template -AsyncCommandSession::AsyncCommandSession( - CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, - ControllerType& controller -) - : m_logger(logger) - , m_controller(controller) -{ - // Attach first. If scope is already cancelled, we exit here with nothing - // to clean up. - attach(scope); - - // Now start the thread. Destructor is guaranteed to run if this succeeds. - m_thread = dispatcher.dispatch([this]{ thread_loop(); }); -} -template -AsyncCommandSession::~AsyncCommandSession(){ -// cout << "~AsyncCommandSession()" << endl; - if (!cancelled() && std::uncaught_exceptions() == 0){ - m_logger.log("AsyncCommandSession::stop_session() not called before normal destruction.", COLOR_RED); - } - detach(); - AsyncCommandSession::cancel(nullptr); - - // Join the thread. - m_thread.reset(); -} - -template -bool AsyncCommandSession::command_is_running(){ - auto scope_check = m_sanitizer.check_scope(); - std::lock_guard lg(m_lock); - return m_current != nullptr; -} - -template -void AsyncCommandSession::stop_command(){ - auto scope_check = m_sanitizer.check_scope(); - - std::unique_lock lg(m_lock); - if (cancelled()){ - return; - } - - if (m_current){ - // Already a task running. Cancel it. - m_current->context.cancel_now(); - m_cv.wait(lg, [this]{ - return cancelled() || m_current == nullptr; - }); - } -} -template -void AsyncCommandSession::dispatch(std::function&& lambda){ - auto scope_check = m_sanitizer.check_scope(); - - // Construct the CommandSet outside the lock. - // If a cancellation comes from above while we are holding the lock, - // it will deadlock. - std::unique_ptr pending(new CommandSet( - *this->scope(), - m_controller, std::move(lambda) - )); - - std::unique_lock lg(m_lock); - if (cancelled()){ - return; - } - - if (m_current){ - // Already a task running. Cancel it. - m_current->context.cancel_lazy(); - m_cv.wait(lg, [this]{ - return cancelled() || m_current == nullptr; - }); - if (cancelled()){ - return; - } - } - - m_current = std::move(pending); - m_cv.notify_all(); -} - - -template -bool AsyncCommandSession::cancel(std::exception_ptr exception) noexcept{ -// cout << "AsyncCommandSession::cancel()" << endl; - if (Cancellable::cancel(exception)){ - return true; - } - std::lock_guard lg(m_lock); - if (m_current != nullptr){ - m_current->context.cancel(std::move(exception)); - } - m_cv.notify_all(); - return false; -} -template -void AsyncCommandSession::thread_loop(){ - while (true){ - CommandSet* current; - { - std::unique_lock lg(m_lock); - m_cv.wait(lg, [this]{ - return cancelled() || m_current != nullptr; - }); - if (cancelled()){ - break; - } - current = m_current.get(); - } - try{ - current->commands(current->context); - current->context.wait_for_all_requests(); - }catch (OperationCancelledException&){} - - // Destroy the CommandSet outside the lock. - // If a cancellation comes from above while we are holding the lock, - // it will deadlock. - std::unique_ptr done; - { - std::lock_guard lg(m_lock); - done = std::move(m_current); - m_cv.notify_all(); - } - } - - auto scope_check = m_sanitizer.check_scope(); -} - - - -#if 0 -template -void AsyncCommandSession::stop_commands(){ - std::lock_guard lg(m_lock); - if (m_current){ - m_current->context.cancel_now(); - } -} -#endif -template -void AsyncCommandSession::wait(){ - std::unique_lock lg(m_lock); -// cout << "wait() - start" << endl; - m_cv.wait(lg, [this]{ - return m_current == nullptr; - }); -// cout << "wait() - done" << endl; -} -template -void AsyncCommandSession::stop_session_and_rethrow(){ - cancel(nullptr); - m_thread->wait_and_rethrow_exceptions(); - throw_if_cancelled_with_exception(); -} - - - - -} - +/* Async Command Set + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "InterruptableCommands.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +template +struct AsyncCommandSession::CommandSet{ + CommandSet( + CancellableScope& parent, ControllerType& controller, + std::function&& lambda + ); + CancellableHolder scope; + ControllerContextType context; + std::function commands; +}; + + + +template +AsyncCommandSession::CommandSet::CommandSet( + CancellableScope& parent, ControllerType& controller, + std::function&& lambda +) + : scope(parent) + , context(scope, controller) + , commands(std::move(lambda)) +{} + + + +template +AsyncCommandSession::AsyncCommandSession( + CancellableScope& scope, Logger& logger, AsyncDispatcher& dispatcher, + ControllerType& controller +) + : m_logger(logger) + , m_controller(controller) +{ + // Attach first. If scope is already cancelled, we exit here with nothing + // to clean up. + attach(scope); + + // Now start the thread. Destructor is guaranteed to run if this succeeds. + m_thread = dispatcher.dispatch([this]{ thread_loop(); }); +} +template +AsyncCommandSession::~AsyncCommandSession(){ +// cout << "~AsyncCommandSession()" << endl; + if (!cancelled() && std::uncaught_exceptions() == 0){ + m_logger.log("AsyncCommandSession::stop_session() not called before normal destruction.", COLOR_RED); + } + detach(); + AsyncCommandSession::cancel(nullptr); + + // Join the thread. + m_thread.reset(); +} + +template +bool AsyncCommandSession::command_is_running(){ + auto scope_check = m_sanitizer.check_scope(); + std::lock_guard lg(m_lock); + return m_current != nullptr; +} + +template +void AsyncCommandSession::stop_command(){ + auto scope_check = m_sanitizer.check_scope(); + + std::unique_lock lg(m_lock); + if (cancelled()){ + return; + } + + if (m_current){ + // Already a task running. Cancel it. + m_current->context.cancel_now(); + m_cv.wait(lg, [this]{ + return cancelled() || m_current == nullptr; + }); + } +} +template +void AsyncCommandSession::dispatch(std::function&& lambda){ + auto scope_check = m_sanitizer.check_scope(); + + // Construct the CommandSet outside the lock. + // If a cancellation comes from above while we are holding the lock, + // it will deadlock. + std::unique_ptr pending(new CommandSet( + *this->scope(), + m_controller, std::move(lambda) + )); + + std::unique_lock lg(m_lock); + if (cancelled()){ + return; + } + + if (m_current){ + // Already a task running. Cancel it. + m_current->context.cancel_lazy(); + m_cv.wait(lg, [this]{ + return cancelled() || m_current == nullptr; + }); + if (cancelled()){ + return; + } + } + + m_current = std::move(pending); + m_cv.notify_all(); +} + + +template +bool AsyncCommandSession::cancel(std::exception_ptr exception) noexcept{ +// cout << "AsyncCommandSession::cancel()" << endl; + if (Cancellable::cancel(exception)){ + return true; + } + std::lock_guard lg(m_lock); + if (m_current != nullptr){ + m_current->context.cancel(std::move(exception)); + } + m_cv.notify_all(); + return false; +} +template +void AsyncCommandSession::thread_loop(){ + while (true){ + CommandSet* current; + { + std::unique_lock lg(m_lock); + m_cv.wait(lg, [this]{ + return cancelled() || m_current != nullptr; + }); + if (cancelled()){ + break; + } + current = m_current.get(); + } + try{ + current->commands(current->context); + current->context.wait_for_all_requests(); + }catch (OperationCancelledException&){} + + // Destroy the CommandSet outside the lock. + // If a cancellation comes from above while we are holding the lock, + // it will deadlock. + std::unique_ptr done; + { + std::lock_guard lg(m_lock); + done = std::move(m_current); + m_cv.notify_all(); + } + } + + auto scope_check = m_sanitizer.check_scope(); +} + + + +#if 0 +template +void AsyncCommandSession::stop_commands(){ + std::lock_guard lg(m_lock); + if (m_current){ + m_current->context.cancel_now(); + } +} +#endif +template +void AsyncCommandSession::wait(){ + std::unique_lock lg(m_lock); +// cout << "wait() - start" << endl; + m_cv.wait(lg, [this]{ + return m_current == nullptr; + }); +// cout << "wait() - done" << endl; +} +template +void AsyncCommandSession::stop_session_and_rethrow(){ + cancel(nullptr); + m_thread->wait_and_rethrow_exceptions(); + throw_if_cancelled_with_exception(); +} + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h index 62d5ec99e3..fa2ec02867 100644 --- a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h +++ b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.h @@ -1,106 +1,106 @@ -/* Super-Control Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SuperControlSession_H -#define PokemonAutomation_CommonTools_SuperControlSession_H - -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - -class ProgramEnvironment; -class VideoStream; -template class AsyncCommandSession; -class AudioInferenceCallback; -class VisualInferenceCallback; - - - -// -// Although this class asynchronously runs inference and commands, none of the -// public methods are actually thread-safe with each other. -// -// You must fully construct the class (register all the callbacks and actions) -// prior to calling "run_session()". -// -// "run_session()" will run the state machine which will periodically call -// "run_state()" at the user-specified period. -// -// Inside the child class' "run_state()" function, it will call "run_state_action()" -// with a registered enum/action. -// - -template -class SuperControlSession{ - using ControllerContextType = typename ControllerType::ContextType; - -public: - ~SuperControlSession(); - void run_session(); - -protected: - // Construction - SuperControlSession( - ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, - std::chrono::milliseconds state_period = std::chrono::milliseconds(100), - std::chrono::milliseconds visual_period = std::chrono::milliseconds(50), - std::chrono::milliseconds audio_period = std::chrono::milliseconds(20) - ); - - void operator+=(VisualInferenceCallback& callback); - void operator+=(AudioInferenceCallback& callback); - - void register_state_command(size_t state, std::function&& action); - - -protected: - WallClock start_time() const{ return m_start_time; } - - size_t last_state() const{ return m_last_state; } - WallClock last_state_change() const{ return m_last_state_change; } - - // Return true if we should stop. - virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) = 0; - - // Run the specified state. This is debounced such that the registered - // command will only run if we're not already in the state and the command - // session is still running. - bool run_state_action(size_t state); - - -protected: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ControllerContextType& m_context; - std::unique_ptr> m_active_command; - -private: - const std::chrono::milliseconds m_state_period; - const std::chrono::milliseconds m_visual_period; - const std::chrono::milliseconds m_audio_period; - - std::vector m_visual_callbacks; - std::vector m_audio_callbacks; - - // These are actions - std::map> m_state_actions; - -private: - // Run-time state. - WallClock m_start_time; - size_t m_last_state; - WallClock m_last_state_change; -}; - - - -} -#endif +/* Super-Control Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SuperControlSession_H +#define PokemonAutomation_CommonTools_SuperControlSession_H + +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + +class ProgramEnvironment; +class VideoStream; +template class AsyncCommandSession; +class AudioInferenceCallback; +class VisualInferenceCallback; + + + +// +// Although this class asynchronously runs inference and commands, none of the +// public methods are actually thread-safe with each other. +// +// You must fully construct the class (register all the callbacks and actions) +// prior to calling "run_session()". +// +// "run_session()" will run the state machine which will periodically call +// "run_state()" at the user-specified period. +// +// Inside the child class' "run_state()" function, it will call "run_state_action()" +// with a registered enum/action. +// + +template +class SuperControlSession{ + using ControllerContextType = typename ControllerType::ContextType; + +public: + ~SuperControlSession(); + void run_session(); + +protected: + // Construction + SuperControlSession( + ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, + std::chrono::milliseconds state_period = std::chrono::milliseconds(100), + std::chrono::milliseconds visual_period = std::chrono::milliseconds(50), + std::chrono::milliseconds audio_period = std::chrono::milliseconds(20) + ); + + void operator+=(VisualInferenceCallback& callback); + void operator+=(AudioInferenceCallback& callback); + + void register_state_command(size_t state, std::function&& action); + + +protected: + WallClock start_time() const{ return m_start_time; } + + size_t last_state() const{ return m_last_state; } + WallClock last_state_change() const{ return m_last_state_change; } + + // Return true if we should stop. + virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) = 0; + + // Run the specified state. This is debounced such that the registered + // command will only run if we're not already in the state and the command + // session is still running. + bool run_state_action(size_t state); + + +protected: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ControllerContextType& m_context; + std::unique_ptr> m_active_command; + +private: + const std::chrono::milliseconds m_state_period; + const std::chrono::milliseconds m_visual_period; + const std::chrono::milliseconds m_audio_period; + + std::vector m_visual_callbacks; + std::vector m_audio_callbacks; + + // These are actions + std::map> m_state_actions; + +private: + // Run-time state. + WallClock m_start_time; + size_t m_last_state; + WallClock m_last_state_change; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp index 717a559ddb..b5713e4bc4 100644 --- a/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp +++ b/SerialPrograms/Source/CommonTools/Async/SuperControlSession.tpp @@ -1,137 +1,137 @@ -/* Super-Control Session - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" -#include "InterruptableCommands.h" -#include "InferenceSession.h" -#include "SuperControlSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -template -SuperControlSession::~SuperControlSession() = default; - -template -SuperControlSession::SuperControlSession( - ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, - std::chrono::milliseconds state_period, - std::chrono::milliseconds visual_period, - std::chrono::milliseconds audio_period -) - : m_env(env) - , m_stream(stream) - , m_context(context) - , m_state_period(state_period) - , m_visual_period(visual_period) - , m_audio_period(audio_period) - , m_last_state(0) - , m_last_state_change(current_time()) -{} - -template -void SuperControlSession::operator+=(VisualInferenceCallback& callback){ - m_visual_callbacks.emplace_back(&callback); -} -template -void SuperControlSession::operator+=(AudioInferenceCallback& callback){ - m_audio_callbacks.emplace_back(&callback); -} -template -void SuperControlSession::register_state_command(size_t state, std::function&& action){ - auto iter = m_state_actions.find(state); - if (iter != m_state_actions.end()){ - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Duplicate State Enum: " + std::to_string(state)); - } - m_state_actions.emplace(state, std::move(action)); -} -template -bool SuperControlSession::run_state_action(size_t state){ - auto iter = m_state_actions.find(state); - if (iter == m_state_actions.end()){ - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Unknown State Enum: " + std::to_string(state)); - } - - // Session isn't even active. - if (!m_active_command){ - return false; - } - - // If we're already in the state and a command is running, don't overwrite it. - if (state == m_last_state && m_active_command->command_is_running()){ - return false; - } - - // Run the state. - m_last_state = state; - m_last_state_change = current_time(); - return iter->second(); -} - -template -void SuperControlSession::run_session(){ - m_start_time = current_time(); - - m_active_command.reset( - new AsyncCommandSession( - m_context, m_env.logger(), m_env.realtime_dispatcher(), - m_context.controller() - ) - ); - - std::vector callbacks; - for (VisualInferenceCallback* callback : m_visual_callbacks){ - callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_visual_period}); - } - for (AudioInferenceCallback* callback : m_audio_callbacks){ - callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_audio_period}); - } - InferenceSession session( - m_context, m_stream, - callbacks, - m_visual_period - ); - - WallClock now = current_time(); - WallClock next_tick = now + m_state_period; - - m_last_state = 0; - - while (true){ - // Check stop conditions. - m_context.throw_if_cancelled(); - - if (run_state(*m_active_command, current_time())){ - break; - } - - now = current_time(); - if (now >= next_tick){ - next_tick = now + m_state_period; - }else{ - m_context.wait_until(next_tick); - next_tick += m_state_period; - } - } - m_context.throw_if_cancelled(); - - m_active_command->stop_session_and_rethrow(); -} - - - - - - -} +/* Super-Control Session + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" +#include "InterruptableCommands.h" +#include "InferenceSession.h" +#include "SuperControlSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +template +SuperControlSession::~SuperControlSession() = default; + +template +SuperControlSession::SuperControlSession( + ProgramEnvironment& env, VideoStream& stream, ControllerContextType& context, + std::chrono::milliseconds state_period, + std::chrono::milliseconds visual_period, + std::chrono::milliseconds audio_period +) + : m_env(env) + , m_stream(stream) + , m_context(context) + , m_state_period(state_period) + , m_visual_period(visual_period) + , m_audio_period(audio_period) + , m_last_state(0) + , m_last_state_change(current_time()) +{} + +template +void SuperControlSession::operator+=(VisualInferenceCallback& callback){ + m_visual_callbacks.emplace_back(&callback); +} +template +void SuperControlSession::operator+=(AudioInferenceCallback& callback){ + m_audio_callbacks.emplace_back(&callback); +} +template +void SuperControlSession::register_state_command(size_t state, std::function&& action){ + auto iter = m_state_actions.find(state); + if (iter != m_state_actions.end()){ + throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Duplicate State Enum: " + std::to_string(state)); + } + m_state_actions.emplace(state, std::move(action)); +} +template +bool SuperControlSession::run_state_action(size_t state){ + auto iter = m_state_actions.find(state); + if (iter == m_state_actions.end()){ + throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Unknown State Enum: " + std::to_string(state)); + } + + // Session isn't even active. + if (!m_active_command){ + return false; + } + + // If we're already in the state and a command is running, don't overwrite it. + if (state == m_last_state && m_active_command->command_is_running()){ + return false; + } + + // Run the state. + m_last_state = state; + m_last_state_change = current_time(); + return iter->second(); +} + +template +void SuperControlSession::run_session(){ + m_start_time = current_time(); + + m_active_command.reset( + new AsyncCommandSession( + m_context, m_env.logger(), m_env.realtime_dispatcher(), + m_context.controller() + ) + ); + + std::vector callbacks; + for (VisualInferenceCallback* callback : m_visual_callbacks){ + callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_visual_period}); + } + for (AudioInferenceCallback* callback : m_audio_callbacks){ + callbacks.emplace_back(PeriodicInferenceCallback{*callback, m_audio_period}); + } + InferenceSession session( + m_context, m_stream, + callbacks, + m_visual_period + ); + + WallClock now = current_time(); + WallClock next_tick = now + m_state_period; + + m_last_state = 0; + + while (true){ + // Check stop conditions. + m_context.throw_if_cancelled(); + + if (run_state(*m_active_command, current_time())){ + break; + } + + now = current_time(); + if (now >= next_tick){ + next_tick = now + m_state_period; + }else{ + m_context.wait_until(next_tick); + next_tick += m_state_period; + } + } + m_context.throw_if_cancelled(); + + m_active_command->stop_session_and_rethrow(); +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp index f79fe406f9..a0c2a35614 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp +++ b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.cpp @@ -1,219 +1,219 @@ -/* Audio Template Cache - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "SpectrogramMatcher.h" -#include "AudioPerSpectrumDetectorBase.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -//std::atomic force_detected(false); - - - -AudioPerSpectrumDetectorBase::AudioPerSpectrumDetectorBase( - Logger& logger, - std::string label, - std::string audio_name, - Color detection_color, - DetectedCallback detected_callback -) - : AudioInferenceCallback(std::move(label)) - , m_audio_name(std::move(audio_name)) - , m_detection_color(detection_color) - , m_logger(logger) - , m_detected_callback(std::move(detected_callback)) - , m_start_timestamp(current_time()) - , m_spectrums_processed(0) -{} -AudioPerSpectrumDetectorBase::~AudioPerSpectrumDetectorBase(){ - try{ - log_results(); - }catch (...){} -} -void AudioPerSpectrumDetectorBase::throw_if_no_sound(std::chrono::milliseconds min_duration) const{ - if (m_start_timestamp + min_duration > current_time()){ - return; - } - if (m_lowest_error < 1.0){ - return; - } - if (m_spectrums_processed > 0){ - return; - } - throw UserSetupError(m_logger, "No sound detected."); -} - -void AudioPerSpectrumDetectorBase::log_results(){ - if (m_last_timestamp != WallClock::min()){ - m_logger.log(m_audio_name + " detected! Error Coefficient = " + tostr_default(m_lowest_error), COLOR_BLUE); - }else{ - m_logger.log(m_audio_name + " not detected. Error Coefficient = " + tostr_default(m_lowest_error), COLOR_PURPLE); - } - -#if 0 - if (m_lowest_error >= 1){ - std::stringstream ss; - ss << "AudioPerSpectrumDetectorBase ended with error of 1.0: " << endl; - ss << "Elapsed Time: "<< std::chrono::duration_cast(current_time() - m_start_timestamp).count() << endl; - ss << "m_spectrums_processed = "<< m_spectrums_processed << endl; - for (const auto& error : m_errors){ - ss << "[" << error.first << ":" << error.second << "]"; - } -// m_logger.log(ss.str(), COLOR_RED); - cout << ss.str() << endl; - } - #endif -} - -bool AudioPerSpectrumDetectorBase::process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed -){ -// cout << m_audio_name << ": " << new_spectrums.size() << endl; - if (new_spectrums.empty()){ -// cout << "No new spectrums" << endl; - return false; - } -// cout << "New spectrums - " << new_spectrums.size() << endl; - - WallClock now = current_time(); - m_spectrums_processed += new_spectrums.size(); - - // Clear last detection. - if (m_last_timestamp + std::chrono::milliseconds(1000) <= now){ - m_last_error = 1.0; - m_last_reported = false; - } - - const size_t sample_rate = new_spectrums[0].sample_rate; - // Lazy initialization of the spectrogram matcher. - if (m_matcher == nullptr || m_matcher->sample_rate() != sample_rate){ - m_logger.log("Loading spectrogram..."); - m_matcher = build_spectrogram_matcher(sample_rate); - } - - // Feed spectrum one by one to the matcher: - // new_spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp). - // To feed the spectrum from old to new, we need to go through the vector in the reverse order: - - -//#define PA_DEBUG_FORCE_PLA_SOUND - -#ifdef PA_DEBUG_FORCE_PLA_SOUND - static int debug_count = 0; - debug_count++; - cout << "debug_count = " << debug_count << endl; -#endif - - bool found = false; - const float threshold = get_score_threshold(); - for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ - std::vector single_spectrum = {*it}; - const float matcher_score = m_matcher->match(single_spectrum); - // std::cout << "error: " << matcherScore << std::endl; - - if (m_lowest_error < 1.0){ - m_errors.clear(); - }else{ - m_errors.emplace_back(matcher_score, now_to_filestring()); - } - - if (matcher_score == FLT_MAX){ -// cout << "Not enough history: " << m_lowest_error << endl; - continue; // error or not enough spectrum history - } -// cout << "Matcher Score: " << matcher_score << endl; - - // Record the lowest error found during the run - m_lowest_error = std::min(m_lowest_error, matcher_score); - - found = matcher_score <= threshold; - - uint64_t curStamp = m_matcher->latestTimestamp(); - -#ifdef PA_DEBUG_FORCE_PLA_SOUND - if (debug_count % 300 > 300 - 5){ - found = true; - } -#endif - - if (found){ - // Record the time of this match - // To avoid detect the same audio multiple times, use m_last_error >= 1.0 to - // make sure m_last_timestamp is only updated at the first match of the same audio. - if (m_last_error >= 1.0){ - m_last_timestamp = now; - } - // m_last_error tracks the lowest error found by the current match. - m_last_error = std::min(m_last_error, matcher_score); - - std::ostringstream os; - os << m_audio_name << " found, score " << matcher_score << "/" << threshold << ", scale: " << m_matcher->lastMatchedScale(); - m_logger.log(os.str(), COLOR_BLUE); - audio_feed.add_overlay(curStamp+1-m_matcher->numMatchedWindows(), curStamp+1, m_detection_color); - - // Since the target audio is found, no need to check detection on the rest of the spectrums in `new_spectrums`. - - // Tell m_matcher to skip the remaining spectrums so that if `process_spectrums()` gets - // called again on a newer batch of spectrums, m_matcher is happy. - m_matcher->skip(std::vector( - new_spectrums.begin(), - new_spectrums.begin() + std::distance(it + 1, new_spectrums.rend()) - )); - - // Skip the remaining spectrums. - break; - } - } - -// if (force_detected){ -// return true; -// } - - // No shiny detected. - if (m_last_error >= 1.0){ - return false; - } - - // Shiny detected, but haven't waited long enough to measure its magnitude. - if (m_last_timestamp + std::chrono::milliseconds(200) > now){ - return false; - } - - // Already reported a target match within one second. Defer reporting anything. - if (m_last_reported){ - return false; - } - - // No callback. Can't report. - if (m_detected_callback == nullptr){ - return false; - } - - m_last_reported = true; - return m_detected_callback(m_last_error); -} - -void AudioPerSpectrumDetectorBase::clear(){ - m_matcher->clear(); -} - - - - - - -} +/* Audio Template Cache + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "SpectrogramMatcher.h" +#include "AudioPerSpectrumDetectorBase.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +//std::atomic force_detected(false); + + + +AudioPerSpectrumDetectorBase::AudioPerSpectrumDetectorBase( + Logger& logger, + std::string label, + std::string audio_name, + Color detection_color, + DetectedCallback detected_callback +) + : AudioInferenceCallback(std::move(label)) + , m_audio_name(std::move(audio_name)) + , m_detection_color(detection_color) + , m_logger(logger) + , m_detected_callback(std::move(detected_callback)) + , m_start_timestamp(current_time()) + , m_spectrums_processed(0) +{} +AudioPerSpectrumDetectorBase::~AudioPerSpectrumDetectorBase(){ + try{ + log_results(); + }catch (...){} +} +void AudioPerSpectrumDetectorBase::throw_if_no_sound(std::chrono::milliseconds min_duration) const{ + if (m_start_timestamp + min_duration > current_time()){ + return; + } + if (m_lowest_error < 1.0){ + return; + } + if (m_spectrums_processed > 0){ + return; + } + throw UserSetupError(m_logger, "No sound detected."); +} + +void AudioPerSpectrumDetectorBase::log_results(){ + if (m_last_timestamp != WallClock::min()){ + m_logger.log(m_audio_name + " detected! Error Coefficient = " + tostr_default(m_lowest_error), COLOR_BLUE); + }else{ + m_logger.log(m_audio_name + " not detected. Error Coefficient = " + tostr_default(m_lowest_error), COLOR_PURPLE); + } + +#if 0 + if (m_lowest_error >= 1){ + std::stringstream ss; + ss << "AudioPerSpectrumDetectorBase ended with error of 1.0: " << endl; + ss << "Elapsed Time: "<< std::chrono::duration_cast(current_time() - m_start_timestamp).count() << endl; + ss << "m_spectrums_processed = "<< m_spectrums_processed << endl; + for (const auto& error : m_errors){ + ss << "[" << error.first << ":" << error.second << "]"; + } +// m_logger.log(ss.str(), COLOR_RED); + cout << ss.str() << endl; + } + #endif +} + +bool AudioPerSpectrumDetectorBase::process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed +){ +// cout << m_audio_name << ": " << new_spectrums.size() << endl; + if (new_spectrums.empty()){ +// cout << "No new spectrums" << endl; + return false; + } +// cout << "New spectrums - " << new_spectrums.size() << endl; + + WallClock now = current_time(); + m_spectrums_processed += new_spectrums.size(); + + // Clear last detection. + if (m_last_timestamp + std::chrono::milliseconds(1000) <= now){ + m_last_error = 1.0; + m_last_reported = false; + } + + const size_t sample_rate = new_spectrums[0].sample_rate; + // Lazy initialization of the spectrogram matcher. + if (m_matcher == nullptr || m_matcher->sample_rate() != sample_rate){ + m_logger.log("Loading spectrogram..."); + m_matcher = build_spectrogram_matcher(sample_rate); + } + + // Feed spectrum one by one to the matcher: + // new_spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp). + // To feed the spectrum from old to new, we need to go through the vector in the reverse order: + + +//#define PA_DEBUG_FORCE_PLA_SOUND + +#ifdef PA_DEBUG_FORCE_PLA_SOUND + static int debug_count = 0; + debug_count++; + cout << "debug_count = " << debug_count << endl; +#endif + + bool found = false; + const float threshold = get_score_threshold(); + for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ + std::vector single_spectrum = {*it}; + const float matcher_score = m_matcher->match(single_spectrum); + // std::cout << "error: " << matcherScore << std::endl; + + if (m_lowest_error < 1.0){ + m_errors.clear(); + }else{ + m_errors.emplace_back(matcher_score, now_to_filestring()); + } + + if (matcher_score == FLT_MAX){ +// cout << "Not enough history: " << m_lowest_error << endl; + continue; // error or not enough spectrum history + } +// cout << "Matcher Score: " << matcher_score << endl; + + // Record the lowest error found during the run + m_lowest_error = std::min(m_lowest_error, matcher_score); + + found = matcher_score <= threshold; + + uint64_t curStamp = m_matcher->latestTimestamp(); + +#ifdef PA_DEBUG_FORCE_PLA_SOUND + if (debug_count % 300 > 300 - 5){ + found = true; + } +#endif + + if (found){ + // Record the time of this match + // To avoid detect the same audio multiple times, use m_last_error >= 1.0 to + // make sure m_last_timestamp is only updated at the first match of the same audio. + if (m_last_error >= 1.0){ + m_last_timestamp = now; + } + // m_last_error tracks the lowest error found by the current match. + m_last_error = std::min(m_last_error, matcher_score); + + std::ostringstream os; + os << m_audio_name << " found, score " << matcher_score << "/" << threshold << ", scale: " << m_matcher->lastMatchedScale(); + m_logger.log(os.str(), COLOR_BLUE); + audio_feed.add_overlay(curStamp+1-m_matcher->numMatchedWindows(), curStamp+1, m_detection_color); + + // Since the target audio is found, no need to check detection on the rest of the spectrums in `new_spectrums`. + + // Tell m_matcher to skip the remaining spectrums so that if `process_spectrums()` gets + // called again on a newer batch of spectrums, m_matcher is happy. + m_matcher->skip(std::vector( + new_spectrums.begin(), + new_spectrums.begin() + std::distance(it + 1, new_spectrums.rend()) + )); + + // Skip the remaining spectrums. + break; + } + } + +// if (force_detected){ +// return true; +// } + + // No shiny detected. + if (m_last_error >= 1.0){ + return false; + } + + // Shiny detected, but haven't waited long enough to measure its magnitude. + if (m_last_timestamp + std::chrono::milliseconds(200) > now){ + return false; + } + + // Already reported a target match within one second. Defer reporting anything. + if (m_last_reported){ + return false; + } + + // No callback. Can't report. + if (m_detected_callback == nullptr){ + return false; + } + + m_last_reported = true; + return m_detected_callback(m_last_error); +} + +void AudioPerSpectrumDetectorBase::clear(){ + m_matcher->clear(); +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h index 4b395f0265..7fa2e21a3a 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h +++ b/SerialPrograms/Source/CommonTools/Audio/AudioPerSpectrumDetectorBase.h @@ -1,134 +1,134 @@ -/* Audio Per-Spectrum Detector Base - * - * From: https://github.com/PokemonAutomation/ - * - * A base class for audio detectors. - * - * It implements AudioInferenceCallback so that it can hook to an inference session - * and stop the session when a target audio is detected. - * The inference session calls process_spectrums(...) periodically and stops when - * the function returns true. - * This base class implements this function. - * - * This base class is called "PerSpectrum" because it tries to match the audio template starting at - * each incoming spectrum in the audio stream. - * For example, if called with three newest unseen spectrums from the audio feed, (i.e `new_spectrums` - * contains three spectrums when passed to AudioPerSpectrumDetectorBase::process_spectrums(...)) - * the detector will check whether the audio template matches the part of audio starting at the first - * of the three spectrums, then check starting at the second, and finally the third. - * Basically, it will try to match the audio template to any possible location in the current audio - * stream. So it will not miss any match even if the audio template is short in duration and the matching - * algorithm needs to be very precise. - * - * This is opposite to the other design choice that only matches the audio starting at the newest - * spectrum in `new_spectrums` when called. That design choice is better suited to non-time-critical - * audio matching and the matching algorithm can tolerate a few spectrums off on time axis. - */ - -#ifndef PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H -#define PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Time.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" - -namespace PokemonAutomation{ - - -class Logger; -class SpectrogramMatcher; - -// A virtual base class for audio detectors to match an audio template starting at each incoming -// spectrum in the audio stream. -// The derived classes need to implement two functions: -// - float get_score_threshold() const -// - std::unique_ptr build_spectrogram_matcher(size_t sample_rate) -class AudioPerSpectrumDetectorBase : public AudioInferenceCallback{ -public: - using DetectedCallback = std::function; - // label: a name for this detector. Used for logging and profiling. - // audio_name: the name of the audio to be detected (shiny sound etc). Capitalize first letter. - // detection_color: the color to visualize the detection on audio spectrogram UI. - // on_shiny_callback(float error_coefficient) -> bool: - // when the detector finds a match, it calls this callback function to decide whether to stop - // the inference session. The error coefficient of the found audio is passed to the callback - // function. If it returns true, the inference session will stop (by returning true from - // AudioPerSpectrumDetectorBase::process_spectrums()). - AudioPerSpectrumDetectorBase( - Logger& logger, - std::string label, - std::string audio_name, - Color detection_color, - DetectedCallback detected_callback - ); - - virtual ~AudioPerSpectrumDetectorBase(); - - WallClock last_detection() const{ - return m_last_timestamp; - } - - void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(5000)) const; - - // To be implemented by derived classes: - // The match threshold for the target audio. - virtual float get_score_threshold() const = 0; - - // Implement AudioInferenceCallback::process_spectrums() - virtual bool process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed - ) override; - - // Clear internal data to be used on another audio stream. - void clear(); - - // Log whether the target audio is detected or not during the runtime of this detector. - // This function will always be called when the detector is destructed. - void log_results(); - - float lowest_error() const{ return m_lowest_error; } - -protected: - // To be implemented by derived classes: - // build the actual spectrogram matcher for the target audio. - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) = 0; - - // Name of the target audio to be detected. Used for logging. - std::string m_audio_name; - // Color of the box to visualize the detection in the audio spectrogram UI. - Color m_detection_color; - - Logger& m_logger; - // Callback function to determine whether to stop the inference session when the target audio - // is detected. - DetectedCallback m_detected_callback; - - WallClock m_start_timestamp; - uint64_t m_spectrums_processed; - - // Record lowest error coefficient (i.e best match) during the runtime of this detector. - float m_lowest_error = 1.0f; - // Record the last timestamp when the target audio is detected. - // If no detection throughout the runtime, this will remain WallClock::min(). - WallClock m_last_timestamp = WallClock::min(); - // Record the last match error coefficient when the target audio is detected. - // It will be reset to 1.0f when one second has passed since the last detection. - float m_last_error = 1.0f; - // This is set to true when a match is found. It will remain true for one second - // so that the detector will not count the same detected audio multiple times. - bool m_last_reported = false; - - std::unique_ptr m_matcher; - - std::vector> m_errors; -}; - - - - - -} -#endif +/* Audio Per-Spectrum Detector Base + * + * From: https://github.com/PokemonAutomation/ + * + * A base class for audio detectors. + * + * It implements AudioInferenceCallback so that it can hook to an inference session + * and stop the session when a target audio is detected. + * The inference session calls process_spectrums(...) periodically and stops when + * the function returns true. + * This base class implements this function. + * + * This base class is called "PerSpectrum" because it tries to match the audio template starting at + * each incoming spectrum in the audio stream. + * For example, if called with three newest unseen spectrums from the audio feed, (i.e `new_spectrums` + * contains three spectrums when passed to AudioPerSpectrumDetectorBase::process_spectrums(...)) + * the detector will check whether the audio template matches the part of audio starting at the first + * of the three spectrums, then check starting at the second, and finally the third. + * Basically, it will try to match the audio template to any possible location in the current audio + * stream. So it will not miss any match even if the audio template is short in duration and the matching + * algorithm needs to be very precise. + * + * This is opposite to the other design choice that only matches the audio starting at the newest + * spectrum in `new_spectrums` when called. That design choice is better suited to non-time-critical + * audio matching and the matching algorithm can tolerate a few spectrums off on time axis. + */ + +#ifndef PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H +#define PokemonAutomation_CommonTools_AudioPerSpectrumDetectorBase_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Time.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" + +namespace PokemonAutomation{ + + +class Logger; +class SpectrogramMatcher; + +// A virtual base class for audio detectors to match an audio template starting at each incoming +// spectrum in the audio stream. +// The derived classes need to implement two functions: +// - float get_score_threshold() const +// - std::unique_ptr build_spectrogram_matcher(size_t sample_rate) +class AudioPerSpectrumDetectorBase : public AudioInferenceCallback{ +public: + using DetectedCallback = std::function; + // label: a name for this detector. Used for logging and profiling. + // audio_name: the name of the audio to be detected (shiny sound etc). Capitalize first letter. + // detection_color: the color to visualize the detection on audio spectrogram UI. + // on_shiny_callback(float error_coefficient) -> bool: + // when the detector finds a match, it calls this callback function to decide whether to stop + // the inference session. The error coefficient of the found audio is passed to the callback + // function. If it returns true, the inference session will stop (by returning true from + // AudioPerSpectrumDetectorBase::process_spectrums()). + AudioPerSpectrumDetectorBase( + Logger& logger, + std::string label, + std::string audio_name, + Color detection_color, + DetectedCallback detected_callback + ); + + virtual ~AudioPerSpectrumDetectorBase(); + + WallClock last_detection() const{ + return m_last_timestamp; + } + + void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(5000)) const; + + // To be implemented by derived classes: + // The match threshold for the target audio. + virtual float get_score_threshold() const = 0; + + // Implement AudioInferenceCallback::process_spectrums() + virtual bool process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed + ) override; + + // Clear internal data to be used on another audio stream. + void clear(); + + // Log whether the target audio is detected or not during the runtime of this detector. + // This function will always be called when the detector is destructed. + void log_results(); + + float lowest_error() const{ return m_lowest_error; } + +protected: + // To be implemented by derived classes: + // build the actual spectrogram matcher for the target audio. + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) = 0; + + // Name of the target audio to be detected. Used for logging. + std::string m_audio_name; + // Color of the box to visualize the detection in the audio spectrogram UI. + Color m_detection_color; + + Logger& m_logger; + // Callback function to determine whether to stop the inference session when the target audio + // is detected. + DetectedCallback m_detected_callback; + + WallClock m_start_timestamp; + uint64_t m_spectrums_processed; + + // Record lowest error coefficient (i.e best match) during the runtime of this detector. + float m_lowest_error = 1.0f; + // Record the last timestamp when the target audio is detected. + // If no detection throughout the runtime, this will remain WallClock::min(). + WallClock m_last_timestamp = WallClock::min(); + // Record the last match error coefficient when the target audio is detected. + // It will be reset to 1.0f when one second has passed since the last detection. + float m_last_error = 1.0f; + // This is set to true when a match is found. It will remain true for one second + // so that the detector will not count the same detected audio multiple times. + bool m_last_reported = false; + + std::unique_ptr m_matcher; + + std::vector> m_errors; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp index 448a6ff377..06eb4c133d 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp +++ b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.cpp @@ -1,75 +1,75 @@ -/* Audio Template Cache - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/Globals.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "AudioTemplateCache.h" - - -namespace PokemonAutomation{ - - -AudioTemplateCache::~AudioTemplateCache(){} -AudioTemplateCache::AudioTemplateCache(){} - -AudioTemplateCache& AudioTemplateCache::instance(){ - static AudioTemplateCache cache; - return cache; -} - - -const AudioTemplate* AudioTemplateCache::get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate){ - WriteSpinLock lg(m_lock); - auto iter = m_cache.find(full_path_no_ext); - if (iter != m_cache.end()){ - return &iter->second; - } - - std::string full_path = full_path_no_ext + ".wav"; - if (!QFileInfo::exists(QString::fromStdString(full_path))){ - full_path = full_path_no_ext + ".mp3"; - } - - AudioTemplate audio_template = loadAudioTemplate(full_path, (int)sample_rate); - if (audio_template.numFrequencies() == 0){ - return nullptr; - } - - iter = m_cache.emplace( - std::move(full_path_no_ext), - std::move(audio_template) - ).first; - - return &iter->second; -} - - - -const AudioTemplate* AudioTemplateCache::get_nothrow(const std::string& path, size_t sample_rate){ - std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); - return get_nothrow_internal(full_path_no_ext, sample_rate); -} -const AudioTemplate& AudioTemplateCache::get_throw(const std::string& path, size_t sample_rate){ - std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); - const AudioTemplate* audio_template = get_nothrow_internal(full_path_no_ext, sample_rate); - if (audio_template == nullptr){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Unable to open audio template file. (Sample Rate = " + std::to_string(sample_rate) + ")", - full_path_no_ext + ".(wav or mp3)" - ); - } - return *audio_template; -} - - - - -} +/* Audio Template Cache + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/Globals.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "AudioTemplateCache.h" + + +namespace PokemonAutomation{ + + +AudioTemplateCache::~AudioTemplateCache(){} +AudioTemplateCache::AudioTemplateCache(){} + +AudioTemplateCache& AudioTemplateCache::instance(){ + static AudioTemplateCache cache; + return cache; +} + + +const AudioTemplate* AudioTemplateCache::get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate){ + WriteSpinLock lg(m_lock); + auto iter = m_cache.find(full_path_no_ext); + if (iter != m_cache.end()){ + return &iter->second; + } + + std::string full_path = full_path_no_ext + ".wav"; + if (!QFileInfo::exists(QString::fromStdString(full_path))){ + full_path = full_path_no_ext + ".mp3"; + } + + AudioTemplate audio_template = loadAudioTemplate(full_path, (int)sample_rate); + if (audio_template.numFrequencies() == 0){ + return nullptr; + } + + iter = m_cache.emplace( + std::move(full_path_no_ext), + std::move(audio_template) + ).first; + + return &iter->second; +} + + + +const AudioTemplate* AudioTemplateCache::get_nothrow(const std::string& path, size_t sample_rate){ + std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); + return get_nothrow_internal(full_path_no_ext, sample_rate); +} +const AudioTemplate& AudioTemplateCache::get_throw(const std::string& path, size_t sample_rate){ + std::string full_path_no_ext = RESOURCE_PATH() + path + "-" + std::to_string(sample_rate); + const AudioTemplate* audio_template = get_nothrow_internal(full_path_no_ext, sample_rate); + if (audio_template == nullptr){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Unable to open audio template file. (Sample Rate = " + std::to_string(sample_rate) + ")", + full_path_no_ext + ".(wav or mp3)" + ); + } + return *audio_template; +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h index ebdc8b4bac..5c98194d03 100644 --- a/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h +++ b/SerialPrograms/Source/CommonTools/Audio/AudioTemplateCache.h @@ -1,55 +1,55 @@ -/* Audio Template Cache - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_AudioTemplateCache_H -#define PokemonAutomation_CommonTools_AudioTemplateCache_H - -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - -class AudioTemplate; - - - -class AudioTemplateCache{ -public: - // path: the path of the basename of the audio template file relative to RESOURCE_PATH(). - // sample_rate: target sample rate. Used to locate the audio template file with the desired sample rate. - // - // The function will first try to load the file using .wav extension. If .wav not available, load .mp3. - // e.g. if `path` is "PokemonLA/ShinySound" and `sample_rate` is 48000, it will load - // RESOURCE_PATH/PokemonLA/ShinySound-48000.wav if it exists. If not, it will load - // RESOURCE_PATH/PokemonLA/ShinySound-48000.mp3 instead. - // Won't throw if cannot read or parse the template file. Return nullptr in this case. - const AudioTemplate* get_nothrow(const std::string& path, size_t sample_rate); - // See comment of AudioTemplateCache::get_nothrow(). - // Throw a FileException if cannot read or parse the template file. - const AudioTemplate& get_throw(const std::string& path, size_t sample_rate); - - static AudioTemplateCache& instance(); - -private: - ~AudioTemplateCache(); - AudioTemplateCache(); - - const AudioTemplate* get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate); - - -private: - SpinLock m_lock; - std::map m_cache; -}; - - - - - - -} -#endif +/* Audio Template Cache + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_AudioTemplateCache_H +#define PokemonAutomation_CommonTools_AudioTemplateCache_H + +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + +class AudioTemplate; + + + +class AudioTemplateCache{ +public: + // path: the path of the basename of the audio template file relative to RESOURCE_PATH(). + // sample_rate: target sample rate. Used to locate the audio template file with the desired sample rate. + // + // The function will first try to load the file using .wav extension. If .wav not available, load .mp3. + // e.g. if `path` is "PokemonLA/ShinySound" and `sample_rate` is 48000, it will load + // RESOURCE_PATH/PokemonLA/ShinySound-48000.wav if it exists. If not, it will load + // RESOURCE_PATH/PokemonLA/ShinySound-48000.mp3 instead. + // Won't throw if cannot read or parse the template file. Return nullptr in this case. + const AudioTemplate* get_nothrow(const std::string& path, size_t sample_rate); + // See comment of AudioTemplateCache::get_nothrow(). + // Throw a FileException if cannot read or parse the template file. + const AudioTemplate& get_throw(const std::string& path, size_t sample_rate); + + static AudioTemplateCache& instance(); + +private: + ~AudioTemplateCache(); + AudioTemplateCache(); + + const AudioTemplate* get_nothrow_internal(const std::string& full_path_no_ext, size_t sample_rate); + + +private: + SpinLock m_lock; + std::map m_cache; +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp index 2f435426e6..dab4efe558 100644 --- a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.cpp @@ -1,404 +1,404 @@ - - -#include -#include -#include -#include -//#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h" -#include "Kernels/SpikeConvolution/Kernels_SpikeConvolution.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "SpectrogramMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -std::vector buildSpikeKernel(size_t numFrequencies, size_t halfSampleRate){ - std::vector kernel; - // We find a good kernel when sample rate is 48K and numFrequencies is 2048: - // [-4.f, -3.f, -2.f, -1.f, 0.f, 1.f, 2.f, 3.f, 4.f, 4.f, 3.f, 2.f, 1.f, 0.f, -1.f, -2.f, -3.f, -4.f] - // This spans frenquency range of 17 * halfSampleRate / numFrequencies = 199.21875Hz, where 17 is the number of intervals in the above series. - // For another sample rate and numFrequencies combination, the number of intervals is - // 199.21875 * numFrequencies / halfSampleRate - size_t numKernelIntervals = int(199.21875 * numFrequencies / halfSampleRate + 0.5); - size_t slopeLen = numKernelIntervals / 2; - for(size_t i = 0; i <= slopeLen; i++){ - kernel.push_back(-4.0f + 8.f * i / (float)slopeLen); - } - for(size_t i = ((numKernelIntervals+1) % 2); i <= slopeLen; i++){ - kernel.push_back(-4.0f + 8.f * (slopeLen-i)/(float)slopeLen); - } - return kernel; -} - -// std::vector buildSmoothKernel(size_t numFrequencies, size_t halfSampleRate){ -// std::vector kernel; -// // We find a good kernel when sample rate is 48K and numFrequencies is 2048: -// // [0.0111, 0.135, 0.606, 1.0, 0.606, 0.135, 0.0111], built as Gaussian distribution with sigma(stddev) as 1.0 -// // The equation for Gaussian is exp(-x^2/(2 sigma^2)) -// // We can think sigma value as 1.0 * frequency_gap = 1.0 * halfSampleRate / numFrequencies = 11.71875 Hz -// } - - -SpectrogramMatcher::SpectrogramMatcher( - std::string name, - AudioTemplate audioTemplate, Mode mode, size_t sample_rate, - double low_frequency_filter, size_t templateSubdivision -) - : m_name(std::move(name)) - , m_template(std::move(audioTemplate)) - , m_sample_rate(sample_rate) - , m_mode(mode) -{ - const size_t numTemplateWindows = m_template.numWindows(); -// cout << "numTemplateWindows = " << numTemplateWindows << endl; - m_numOriginalFrequencies = m_template.numFrequencies(); - if (m_template.numFrequencies() == 0){ // Error case, failed to load template - std::cout << "Error: load audio template failed" << std::endl; - return; -// throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to load audio template file.", templateFilename.toStdString()); - } - - const size_t halfSampleRate = sample_rate / 2; - - // The frequency range from [0.0, halfSampleRate / numFrequencies, 2.0 halfSampleRate / numFrequencies, ... (numFrequencies-1) halfSampleRate / numFrequencies] - // Since human can only hear as high as 20KHz sound, matching on frequencies >= 20KHz is meaningless. - // So the index i of the max frequency we should be matching is the one with - // i * halfSampleRate/numFrequencies <= 20KHz - // i <= numFrequencies * 20K / halfSampleRate - // We also have a cut-off threshold to remove lower frequencies. We set it to be at frequency index 5 when sample rate is 48K and numFrequencies is 2048. - // So 5.0 24K / 2048 = 58.59375Hz. For other sample rate and numFrequencies combinations, - // j * halfSampleRate/numFrequencies >= 58.59375 -> j >= 58.59375 * numFrequnecies / halfSampleRate - - m_originalFreqStart = int(low_frequency_filter * m_numOriginalFrequencies / halfSampleRate + 0.5); - m_originalFreqEnd = 20000 * m_numOriginalFrequencies / halfSampleRate + 1; - - // Initialize the spike convolution kernel: - m_convKernel = buildSpikeKernel(m_numOriginalFrequencies, halfSampleRate); - - switch(m_mode){ - case Mode::SPIKE_CONV: - { - // Do convolution on audio template - const size_t numConvedFrequencies = (m_originalFreqEnd - m_originalFreqStart) - m_convKernel.size() + 1; - - AudioTemplate audio_template(numConvedFrequencies, numTemplateWindows); - for (size_t i = 0; i < numTemplateWindows; i++){ - conv( - m_template.getWindow(i) + m_originalFreqStart, m_originalFreqEnd - m_originalFreqStart, - audio_template.getWindow(i) - ); - } - - m_template = std::move(audio_template); - m_freqStart = 0; - m_freqEnd = numConvedFrequencies; - break; - } - case Mode::AVERAGE_5: - { - // Avereage every 5 frequencies - const size_t numNewFreq = (m_originalFreqEnd - m_originalFreqStart) / 5; - - AudioTemplate audio_template(numNewFreq, numTemplateWindows); - for (size_t i = 0; i < numTemplateWindows; i++){ - for (size_t j = 0; j < numNewFreq; j++){ - const float * rawFreqMag = m_template.getWindow(i) + m_originalFreqStart + j*5; - const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; - audio_template.getWindow(i)[j] = newMag; - } - } - - m_template = std::move(audio_template); - m_freqStart = 0; - m_freqEnd = numNewFreq; - break; - } - case Mode::RAW: - m_freqStart = m_originalFreqStart; - m_freqEnd = m_originalFreqEnd; - break; - } - - if (templateSubdivision <= 1){ - m_templateRange.emplace_back(0, numTemplateWindows); - m_numSpectrumsNeeded = numTemplateWindows; - }else{ - // Number of subdivision cannot exceed number of windows in the template. - templateSubdivision = std::min(templateSubdivision, numTemplateWindows); - // num windows of each subdivided template - const size_t num_subWindows = numTemplateWindows / templateSubdivision; - m_numSpectrumsNeeded = num_subWindows; - for(size_t i = 0; i < templateSubdivision; i++){ - const size_t windowStart = i * num_subWindows; - const size_t windowEnd = (i+1) * num_subWindows; - m_templateRange.emplace_back(windowStart, windowEnd); - } - } -// cout << "m_templateRange = " << m_templateRange.size() << endl; -// cout << "m_numSpectrumsNeeded = " << m_numSpectrumsNeeded << endl; - - m_templateNorm = buildTemplateNorm(); -} - -uint64_t SpectrogramMatcher::latestTimestamp() const{ - if (m_spectrums.size() == 0){ - return SIZE_MAX; - } - return m_spectrums.front().stamp; -} - -void SpectrogramMatcher::conv(const float* src, size_t num, float* dst){ -// cout << (size_t)dst % 64 << endl; - - const size_t numConvedFrequencies = num - m_convKernel.size() + 1; - if (num < m_convKernel.size()){ - memset(dst, 0, numConvedFrequencies * sizeof(float)); - return; - } - -#if 0 - for (size_t i = 0; i < num-m_convKernel.size()+1; i++){ - dst[i] = 0.0f; - for (size_t j = 0; j < m_convKernel.size(); j++){ - dst[i] += src[i+j] * m_convKernel[j]; - } - } -#else - Kernels::SpikeConvolution::compute_spike_kernel( - dst, src, num, m_convKernel.data(), m_convKernel.size() - ); -#endif -} - -std::vector SpectrogramMatcher::buildTemplateNorm() const{ - std::vector ret(m_templateRange.size()); - - for (size_t sub_index = 0; sub_index < m_templateRange.size(); sub_index++){ - float sumSqr = 0.0f; - for (size_t i = m_templateRange[sub_index].first; i < m_templateRange[sub_index].second; i++){ - for(size_t j = m_freqStart; j < m_freqEnd; j++){ - const float v = m_template.getWindow(i)[j]; - sumSqr += v * v; - } - } - ret[sub_index] = std::sqrt(sumSqr); - } - - return ret; -} - -bool SpectrogramMatcher::update_to_new_spectrum(AudioSpectrum spectrum){ - if (m_numOriginalFrequencies != spectrum.magnitudes->size()){ - std::cout << "Error: number of frequencies don't match in SpectrogramMatcher::match() " << - m_numOriginalFrequencies << " " << spectrum.magnitudes->size() << std::endl; - return false; - } - - switch(m_mode){ - case Mode::SPIKE_CONV: - { - // Do the conv on new spectrum too. - AlignedVector convedSpectrum(m_template.bufferSize()); - conv(spectrum.magnitudes->data() + m_originalFreqStart, - m_originalFreqEnd - m_originalFreqStart, convedSpectrum.data()); - - spectrum.magnitudes = std::make_unique>(std::move(convedSpectrum)); - break; - } - case Mode::AVERAGE_5: - { - AlignedVector avgedSpectrum(m_template.bufferSize()); - for(size_t j = 0; j < m_template.numFrequencies(); j++){ - const float * rawFreqMag = spectrum.magnitudes->data() + m_originalFreqStart + j*5; - const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; - avgedSpectrum[j] = newMag; - } - spectrum.magnitudes = std::make_unique>(std::move(avgedSpectrum)); - break; - } - case Mode::RAW: - break; - } - - // Compute the norm square (= sum squares) of the spectrum, used for matching: - // TODO: if there will be multiple SpectrogramMatcher running on the same audio stream, can - // move this per-spectrum computation to a shared struct for those matchers to save computation. - float spectrumNormSqr = 0.0f; - for (size_t i = m_freqStart; i < m_freqEnd; i++){ - float mag = (*spectrum.magnitudes)[i]; - spectrumNormSqr += mag * mag; - } - m_spectrumNormSqrs.push_front(spectrumNormSqr); - - m_spectrums.emplace_front(std::move(spectrum)); - - return true; -} - -bool SpectrogramMatcher::update_to_new_spectrums(const std::vector& new_spectrums){ - for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ - if(!update_to_new_spectrum(*it)){ - return false; - } - } - - // pop out too old spectrums - while (m_spectrums.size() > m_numSpectrumsNeeded){ - m_spectrums.pop_back(); - m_spectrumNormSqrs.pop_back(); - } - - return true; -} - -std::pair SpectrogramMatcher::match_sub_template(size_t sub_index) const{ -#if 0 - auto iter = m_spectrums.begin(); - auto iter2 = m_spectrumNormSqrs.begin(); - float streamSumSqr = 0.0f; - float sumMulti = 0.0f; - - const size_t template_start = m_templateRange[sub_index].first; - const size_t template_end = m_templateRange[sub_index].second; - for(size_t i = template_start; i < template_end; i++, iter++, iter2++){ - // match in order from latest window to oldest - const float* templateData = m_template.getWindow(template_end-1-i); - const float* streamData = iter->magnitudes->data(); - streamSumSqr += *iter2; - for(size_t j = m_freqStart; j < m_freqEnd; j++){ - sumMulti += templateData[j] * streamData[j]; - } - } -// cout << "sumMulti = " << sumMulti << ", streamSumSqr = " << streamSumSqr << endl; - const float scale = (streamSumSqr < 1e-6f ? 1.0f : sumMulti / streamSumSqr); - - iter = m_spectrums.begin(); - float sum = 0.0f; - for(size_t i = template_start; i < template_end; i++, iter++){ - // match in order from latest window to oldest - const float* templateData = m_template.getWindow(template_end-1-i); - const float* streamData = iter->magnitudes->data(); - for(size_t j = m_freqStart; j < m_freqEnd; j++){ - float d = templateData[j] - scale * streamData[j]; - sum += d * d; - } - } -#else - // Build matrix. - auto iter = m_spectrums.begin(); - const size_t template_start = m_templateRange[sub_index].first; - const size_t template_end = m_templateRange[sub_index].second; - size_t windows = template_end - template_start; -// cout << windows << endl; -// cout << m_spectrums.size() << " / " << windows << endl; - size_t freqs = m_freqEnd - m_freqStart; - std::vector matrixA(windows); - std::vector matrixT(windows); - for (size_t i = 0; i < windows; i++, iter++){ -// cout << "Template: " << ((size_t)m_template.getWindow(template_end - 1 - i) % 64) << endl; -// cout << "Samples: " << ((size_t)iter->magnitudes->data() % 64) << endl; - matrixT[i] = m_freqStart + m_template.getWindow(windows - 1 - i); - matrixA[i] = m_freqStart + iter->magnitudes->data(); -// cout << matrixT[i] << " : " << matrixA[i] << endl; - } - - // Compute scale. - float scale = Kernels::ScaleInvariantMatrixMatch::compute_scale( - freqs, windows, - matrixA.data(), matrixT.data() - ); - scale = std::min(scale, 1000000); - - // Compute error. - float sum = Kernels::ScaleInvariantMatrixMatch::compute_error( - freqs, windows, - scale, - matrixA.data(), matrixT.data() - ); -#endif - - - float score = sqrt(sum) / m_templateNorm[0]; -// cout << "score = " << score << endl; - score = std::min(score, 1.0); - - return std::make_pair(score, scale); -} - -float SpectrogramMatcher::match(const std::vector& new_spectrums){ - if (!update_to_new_spectrums(new_spectrums)){ - return FLT_MAX; - } - - if (m_spectrums.size() < m_numSpectrumsNeeded){ - return FLT_MAX; - } - - // Check whether the stored spectrums' timestamps are continuous: - size_t curStamp = m_spectrums.front().stamp; - size_t lastStamp = curStamp + 1; - for (const auto& s : m_spectrums){ - if (s.stamp != lastStamp - 1){ - std::cout << "Error: SpectrogramMatcher (" + m_name + ") spectrum timestamps are not continuous:" << std::endl; - - for(const auto& sp : m_spectrums){ - std::cout << sp.stamp << ", "; - } - std::cout << std::endl; - return FLT_MAX; - } - lastStamp--; - } - - if (m_lastStampTested != SIZE_MAX && curStamp <= m_lastStampTested){ - return FLT_MAX; - } - m_lastStampTested = curStamp; - - // Do the match: - float score = FLT_MAX; // the lower the score, the better the match - if (m_templateRange.size() == 1){ - // Match the full template - std::tie(score, m_lastScale) = match_sub_template(0); - }else{ - // Match each individual sub-template - for (size_t sub_template = 0; sub_template < m_templateRange.size(); sub_template++){ - float sub_template_score = FLT_MAX; - float sub_template_scale = 1.0f; - std::tie(sub_template_score, sub_template_scale) = match_sub_template(sub_template); - if (sub_template_score < score){ - score = sub_template_score; - m_lastScale = sub_template_scale; - } - } - } - - return score; -} - -bool SpectrogramMatcher::skip(const std::vector& new_spectrums){ - // Note: ideally we don't want to have any computation while skipping. - // But update_to_new_spectrums() may still do some filtering and vector norm computation. - // Since the computation is relatively small and we won't be skipping lots of frames anyway, - // this should be fine for now. - // We can improve this later. - return update_to_new_spectrums(new_spectrums); -} - -void SpectrogramMatcher::clear(){ - m_spectrums.clear(); - m_spectrumNormSqrs.clear(); - m_lastStampTested = SIZE_MAX; -} - - - - -} + + +#include +#include +#include +#include +//#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h" +#include "Kernels/SpikeConvolution/Kernels_SpikeConvolution.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "SpectrogramMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +std::vector buildSpikeKernel(size_t numFrequencies, size_t halfSampleRate){ + std::vector kernel; + // We find a good kernel when sample rate is 48K and numFrequencies is 2048: + // [-4.f, -3.f, -2.f, -1.f, 0.f, 1.f, 2.f, 3.f, 4.f, 4.f, 3.f, 2.f, 1.f, 0.f, -1.f, -2.f, -3.f, -4.f] + // This spans frenquency range of 17 * halfSampleRate / numFrequencies = 199.21875Hz, where 17 is the number of intervals in the above series. + // For another sample rate and numFrequencies combination, the number of intervals is + // 199.21875 * numFrequencies / halfSampleRate + size_t numKernelIntervals = int(199.21875 * numFrequencies / halfSampleRate + 0.5); + size_t slopeLen = numKernelIntervals / 2; + for(size_t i = 0; i <= slopeLen; i++){ + kernel.push_back(-4.0f + 8.f * i / (float)slopeLen); + } + for(size_t i = ((numKernelIntervals+1) % 2); i <= slopeLen; i++){ + kernel.push_back(-4.0f + 8.f * (slopeLen-i)/(float)slopeLen); + } + return kernel; +} + +// std::vector buildSmoothKernel(size_t numFrequencies, size_t halfSampleRate){ +// std::vector kernel; +// // We find a good kernel when sample rate is 48K and numFrequencies is 2048: +// // [0.0111, 0.135, 0.606, 1.0, 0.606, 0.135, 0.0111], built as Gaussian distribution with sigma(stddev) as 1.0 +// // The equation for Gaussian is exp(-x^2/(2 sigma^2)) +// // We can think sigma value as 1.0 * frequency_gap = 1.0 * halfSampleRate / numFrequencies = 11.71875 Hz +// } + + +SpectrogramMatcher::SpectrogramMatcher( + std::string name, + AudioTemplate audioTemplate, Mode mode, size_t sample_rate, + double low_frequency_filter, size_t templateSubdivision +) + : m_name(std::move(name)) + , m_template(std::move(audioTemplate)) + , m_sample_rate(sample_rate) + , m_mode(mode) +{ + const size_t numTemplateWindows = m_template.numWindows(); +// cout << "numTemplateWindows = " << numTemplateWindows << endl; + m_numOriginalFrequencies = m_template.numFrequencies(); + if (m_template.numFrequencies() == 0){ // Error case, failed to load template + std::cout << "Error: load audio template failed" << std::endl; + return; +// throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to load audio template file.", templateFilename.toStdString()); + } + + const size_t halfSampleRate = sample_rate / 2; + + // The frequency range from [0.0, halfSampleRate / numFrequencies, 2.0 halfSampleRate / numFrequencies, ... (numFrequencies-1) halfSampleRate / numFrequencies] + // Since human can only hear as high as 20KHz sound, matching on frequencies >= 20KHz is meaningless. + // So the index i of the max frequency we should be matching is the one with + // i * halfSampleRate/numFrequencies <= 20KHz + // i <= numFrequencies * 20K / halfSampleRate + // We also have a cut-off threshold to remove lower frequencies. We set it to be at frequency index 5 when sample rate is 48K and numFrequencies is 2048. + // So 5.0 24K / 2048 = 58.59375Hz. For other sample rate and numFrequencies combinations, + // j * halfSampleRate/numFrequencies >= 58.59375 -> j >= 58.59375 * numFrequnecies / halfSampleRate + + m_originalFreqStart = int(low_frequency_filter * m_numOriginalFrequencies / halfSampleRate + 0.5); + m_originalFreqEnd = 20000 * m_numOriginalFrequencies / halfSampleRate + 1; + + // Initialize the spike convolution kernel: + m_convKernel = buildSpikeKernel(m_numOriginalFrequencies, halfSampleRate); + + switch(m_mode){ + case Mode::SPIKE_CONV: + { + // Do convolution on audio template + const size_t numConvedFrequencies = (m_originalFreqEnd - m_originalFreqStart) - m_convKernel.size() + 1; + + AudioTemplate audio_template(numConvedFrequencies, numTemplateWindows); + for (size_t i = 0; i < numTemplateWindows; i++){ + conv( + m_template.getWindow(i) + m_originalFreqStart, m_originalFreqEnd - m_originalFreqStart, + audio_template.getWindow(i) + ); + } + + m_template = std::move(audio_template); + m_freqStart = 0; + m_freqEnd = numConvedFrequencies; + break; + } + case Mode::AVERAGE_5: + { + // Avereage every 5 frequencies + const size_t numNewFreq = (m_originalFreqEnd - m_originalFreqStart) / 5; + + AudioTemplate audio_template(numNewFreq, numTemplateWindows); + for (size_t i = 0; i < numTemplateWindows; i++){ + for (size_t j = 0; j < numNewFreq; j++){ + const float * rawFreqMag = m_template.getWindow(i) + m_originalFreqStart + j*5; + const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; + audio_template.getWindow(i)[j] = newMag; + } + } + + m_template = std::move(audio_template); + m_freqStart = 0; + m_freqEnd = numNewFreq; + break; + } + case Mode::RAW: + m_freqStart = m_originalFreqStart; + m_freqEnd = m_originalFreqEnd; + break; + } + + if (templateSubdivision <= 1){ + m_templateRange.emplace_back(0, numTemplateWindows); + m_numSpectrumsNeeded = numTemplateWindows; + }else{ + // Number of subdivision cannot exceed number of windows in the template. + templateSubdivision = std::min(templateSubdivision, numTemplateWindows); + // num windows of each subdivided template + const size_t num_subWindows = numTemplateWindows / templateSubdivision; + m_numSpectrumsNeeded = num_subWindows; + for(size_t i = 0; i < templateSubdivision; i++){ + const size_t windowStart = i * num_subWindows; + const size_t windowEnd = (i+1) * num_subWindows; + m_templateRange.emplace_back(windowStart, windowEnd); + } + } +// cout << "m_templateRange = " << m_templateRange.size() << endl; +// cout << "m_numSpectrumsNeeded = " << m_numSpectrumsNeeded << endl; + + m_templateNorm = buildTemplateNorm(); +} + +uint64_t SpectrogramMatcher::latestTimestamp() const{ + if (m_spectrums.size() == 0){ + return SIZE_MAX; + } + return m_spectrums.front().stamp; +} + +void SpectrogramMatcher::conv(const float* src, size_t num, float* dst){ +// cout << (size_t)dst % 64 << endl; + + const size_t numConvedFrequencies = num - m_convKernel.size() + 1; + if (num < m_convKernel.size()){ + memset(dst, 0, numConvedFrequencies * sizeof(float)); + return; + } + +#if 0 + for (size_t i = 0; i < num-m_convKernel.size()+1; i++){ + dst[i] = 0.0f; + for (size_t j = 0; j < m_convKernel.size(); j++){ + dst[i] += src[i+j] * m_convKernel[j]; + } + } +#else + Kernels::SpikeConvolution::compute_spike_kernel( + dst, src, num, m_convKernel.data(), m_convKernel.size() + ); +#endif +} + +std::vector SpectrogramMatcher::buildTemplateNorm() const{ + std::vector ret(m_templateRange.size()); + + for (size_t sub_index = 0; sub_index < m_templateRange.size(); sub_index++){ + float sumSqr = 0.0f; + for (size_t i = m_templateRange[sub_index].first; i < m_templateRange[sub_index].second; i++){ + for(size_t j = m_freqStart; j < m_freqEnd; j++){ + const float v = m_template.getWindow(i)[j]; + sumSqr += v * v; + } + } + ret[sub_index] = std::sqrt(sumSqr); + } + + return ret; +} + +bool SpectrogramMatcher::update_to_new_spectrum(AudioSpectrum spectrum){ + if (m_numOriginalFrequencies != spectrum.magnitudes->size()){ + std::cout << "Error: number of frequencies don't match in SpectrogramMatcher::match() " << + m_numOriginalFrequencies << " " << spectrum.magnitudes->size() << std::endl; + return false; + } + + switch(m_mode){ + case Mode::SPIKE_CONV: + { + // Do the conv on new spectrum too. + AlignedVector convedSpectrum(m_template.bufferSize()); + conv(spectrum.magnitudes->data() + m_originalFreqStart, + m_originalFreqEnd - m_originalFreqStart, convedSpectrum.data()); + + spectrum.magnitudes = std::make_unique>(std::move(convedSpectrum)); + break; + } + case Mode::AVERAGE_5: + { + AlignedVector avgedSpectrum(m_template.bufferSize()); + for(size_t j = 0; j < m_template.numFrequencies(); j++){ + const float * rawFreqMag = spectrum.magnitudes->data() + m_originalFreqStart + j*5; + const float newMag = (rawFreqMag[0] + rawFreqMag[1] + rawFreqMag[2] + rawFreqMag[3] + rawFreqMag[4]) / 5.0f; + avgedSpectrum[j] = newMag; + } + spectrum.magnitudes = std::make_unique>(std::move(avgedSpectrum)); + break; + } + case Mode::RAW: + break; + } + + // Compute the norm square (= sum squares) of the spectrum, used for matching: + // TODO: if there will be multiple SpectrogramMatcher running on the same audio stream, can + // move this per-spectrum computation to a shared struct for those matchers to save computation. + float spectrumNormSqr = 0.0f; + for (size_t i = m_freqStart; i < m_freqEnd; i++){ + float mag = (*spectrum.magnitudes)[i]; + spectrumNormSqr += mag * mag; + } + m_spectrumNormSqrs.push_front(spectrumNormSqr); + + m_spectrums.emplace_front(std::move(spectrum)); + + return true; +} + +bool SpectrogramMatcher::update_to_new_spectrums(const std::vector& new_spectrums){ + for (auto it = new_spectrums.rbegin(); it != new_spectrums.rend(); it++){ + if(!update_to_new_spectrum(*it)){ + return false; + } + } + + // pop out too old spectrums + while (m_spectrums.size() > m_numSpectrumsNeeded){ + m_spectrums.pop_back(); + m_spectrumNormSqrs.pop_back(); + } + + return true; +} + +std::pair SpectrogramMatcher::match_sub_template(size_t sub_index) const{ +#if 0 + auto iter = m_spectrums.begin(); + auto iter2 = m_spectrumNormSqrs.begin(); + float streamSumSqr = 0.0f; + float sumMulti = 0.0f; + + const size_t template_start = m_templateRange[sub_index].first; + const size_t template_end = m_templateRange[sub_index].second; + for(size_t i = template_start; i < template_end; i++, iter++, iter2++){ + // match in order from latest window to oldest + const float* templateData = m_template.getWindow(template_end-1-i); + const float* streamData = iter->magnitudes->data(); + streamSumSqr += *iter2; + for(size_t j = m_freqStart; j < m_freqEnd; j++){ + sumMulti += templateData[j] * streamData[j]; + } + } +// cout << "sumMulti = " << sumMulti << ", streamSumSqr = " << streamSumSqr << endl; + const float scale = (streamSumSqr < 1e-6f ? 1.0f : sumMulti / streamSumSqr); + + iter = m_spectrums.begin(); + float sum = 0.0f; + for(size_t i = template_start; i < template_end; i++, iter++){ + // match in order from latest window to oldest + const float* templateData = m_template.getWindow(template_end-1-i); + const float* streamData = iter->magnitudes->data(); + for(size_t j = m_freqStart; j < m_freqEnd; j++){ + float d = templateData[j] - scale * streamData[j]; + sum += d * d; + } + } +#else + // Build matrix. + auto iter = m_spectrums.begin(); + const size_t template_start = m_templateRange[sub_index].first; + const size_t template_end = m_templateRange[sub_index].second; + size_t windows = template_end - template_start; +// cout << windows << endl; +// cout << m_spectrums.size() << " / " << windows << endl; + size_t freqs = m_freqEnd - m_freqStart; + std::vector matrixA(windows); + std::vector matrixT(windows); + for (size_t i = 0; i < windows; i++, iter++){ +// cout << "Template: " << ((size_t)m_template.getWindow(template_end - 1 - i) % 64) << endl; +// cout << "Samples: " << ((size_t)iter->magnitudes->data() % 64) << endl; + matrixT[i] = m_freqStart + m_template.getWindow(windows - 1 - i); + matrixA[i] = m_freqStart + iter->magnitudes->data(); +// cout << matrixT[i] << " : " << matrixA[i] << endl; + } + + // Compute scale. + float scale = Kernels::ScaleInvariantMatrixMatch::compute_scale( + freqs, windows, + matrixA.data(), matrixT.data() + ); + scale = std::min(scale, 1000000); + + // Compute error. + float sum = Kernels::ScaleInvariantMatrixMatch::compute_error( + freqs, windows, + scale, + matrixA.data(), matrixT.data() + ); +#endif + + + float score = sqrt(sum) / m_templateNorm[0]; +// cout << "score = " << score << endl; + score = std::min(score, 1.0); + + return std::make_pair(score, scale); +} + +float SpectrogramMatcher::match(const std::vector& new_spectrums){ + if (!update_to_new_spectrums(new_spectrums)){ + return FLT_MAX; + } + + if (m_spectrums.size() < m_numSpectrumsNeeded){ + return FLT_MAX; + } + + // Check whether the stored spectrums' timestamps are continuous: + size_t curStamp = m_spectrums.front().stamp; + size_t lastStamp = curStamp + 1; + for (const auto& s : m_spectrums){ + if (s.stamp != lastStamp - 1){ + std::cout << "Error: SpectrogramMatcher (" + m_name + ") spectrum timestamps are not continuous:" << std::endl; + + for(const auto& sp : m_spectrums){ + std::cout << sp.stamp << ", "; + } + std::cout << std::endl; + return FLT_MAX; + } + lastStamp--; + } + + if (m_lastStampTested != SIZE_MAX && curStamp <= m_lastStampTested){ + return FLT_MAX; + } + m_lastStampTested = curStamp; + + // Do the match: + float score = FLT_MAX; // the lower the score, the better the match + if (m_templateRange.size() == 1){ + // Match the full template + std::tie(score, m_lastScale) = match_sub_template(0); + }else{ + // Match each individual sub-template + for (size_t sub_template = 0; sub_template < m_templateRange.size(); sub_template++){ + float sub_template_score = FLT_MAX; + float sub_template_scale = 1.0f; + std::tie(sub_template_score, sub_template_scale) = match_sub_template(sub_template); + if (sub_template_score < score){ + score = sub_template_score; + m_lastScale = sub_template_scale; + } + } + } + + return score; +} + +bool SpectrogramMatcher::skip(const std::vector& new_spectrums){ + // Note: ideally we don't want to have any computation while skipping. + // But update_to_new_spectrums() may still do some filtering and vector norm computation. + // Since the computation is relatively small and we won't be skipping lots of frames anyway, + // this should be fine for now. + // We can improve this later. + return update_to_new_spectrums(new_spectrums); +} + +void SpectrogramMatcher::clear(){ + m_spectrums.clear(); + m_spectrumNormSqrs.clear(); + m_lastStampTested = SIZE_MAX; +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h index e077e2fbea..499e15f904 100644 --- a/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h +++ b/SerialPrograms/Source/CommonTools/Audio/SpectrogramMatcher.h @@ -1,134 +1,134 @@ -/* Spectrogram Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SpectrogramMatcher_H -#define PokemonAutomation_CommonTools_SpectrogramMatcher_H - -#include -#include -#include -#include -#include -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" - -namespace PokemonAutomation{ - -class AudioSpectrum; - -// Load an audio template from disk and use its spectrogram to match the -// spectrogram of the incoming audio stream. -class SpectrogramMatcher{ -public: - enum class Mode{ - // Don't do any processing on each window of spectrum, matching raw spectrums. - RAW, - // Do convolution on each window of spectrum with a peak detection kernel, before matching spectrums. - SPIKE_CONV, - // Do convolution on each window of spectrum with a Gaussian smooth kernel, before matching spectrums. - // GAUSSIAN_CONV, - // Average every 5 frequencies to reduce computation. - AVERAGE_5, - }; - - // audioTemplate: the audio template for the audio stream to match against. - // Use AudioTemplate::loadAudioTemplate() to load a template from disk, or - // use AudioTemplateCache::instance().get_throw(audioResourceRelativePath, sample_rate) to get one from cache. - // mode: which type of spectrogram filtering to use before the actual match. - // sample_rate: audio sample rate. - // low_frequency_filter: only match the frequencies above this threshold. - // templateSubdivision: divide the template into how many sub-templates to match. <= 1 means no subdivision. - SpectrogramMatcher( - std::string name, - AudioTemplate audioTemplate, Mode mode, size_t sample_rate, - double low_frequency_filter, size_t templateSubdivision = 0 - ); - - size_t sample_rate() const{ return m_sample_rate; } - - // Match the newest spectrums and return a match score. - // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller - // timestamp) spectrums at the end. - // In invalid cases (internal error or not enough windows), return FLT_MAX - float match(const std::vector& new_spectrums); - - // Pass some spectrums in but don't run match on them. - // Used for skipping some spectrums to avoid unnecessary matching. - // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller - // timestamp) spectrums at the end. - // Return true if there is no error. - bool skip(const std::vector& new_spectrums); - - // Clear internal data to be used on another audio stream. - void clear(); - - // How many windows are used for matching. - size_t numMatchedWindows() const { return m_numSpectrumsNeeded; } - - // Return latest timestamp from the stored audio spectrum stream. - // Return SIZE_MAX if there is no stored spectrum yet. - uint64_t latestTimestamp() const; - - // Return the scale found by the matcher to scale the input audio stream to best - // match the template in the last `match()`. - // Return 0.0f if the last scale is not available. - float lastMatchedScale() const { return m_lastScale; } - -private: - void conv(const float* src, size_t num, float* dst); - - // The function to build `m_templateNorm` - std::vector buildTemplateNorm() const; - - // For a given sub-template, return its match score and scaling factor - std::pair match_sub_template(size_t sub_index) const; - - // Update internal data for the next new spectrum. Called by `update_to_new_spectrums()`. - // Return true if there is no error. - bool update_to_new_spectrum(AudioSpectrum newSpectrum); - - // Update internal data for the new specttrums. - // Return true if there is no error. - bool update_to_new_spectrums(const std::vector& new_spectrums); - - - -private: - std::string m_name; - AudioTemplate m_template; - - size_t m_sample_rate; - - size_t m_numOriginalFrequencies = 0; - size_t m_originalFreqStart = 0; - size_t m_originalFreqEnd = 0; - - size_t m_freqStart = 0; - size_t m_freqEnd = 0; - // Temporal ranges of the template to match with. Used when matching a subdivided template. - // If there is no subdivision, it will store only one pair: <0, m_template.numWindows()> - std::vector> m_templateRange; - // For each subdivided template, store its sepctrogram matrix norm - std::vector m_templateNorm; - - Mode m_mode = Mode::RAW; - - std::vector m_convKernel; - - // Spectrums from audio feed. They will be matched against the template. - std::list m_spectrums; - // Norm squares of each spectrum in `m_spectrums`. - std::list m_spectrumNormSqrs; - // How many spectrums needed to store. - size_t m_numSpectrumsNeeded = 0; - - size_t m_lastStampTested = SIZE_MAX; - float m_lastScale = 0.0f; -}; - - -} -#endif +/* Spectrogram Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SpectrogramMatcher_H +#define PokemonAutomation_CommonTools_SpectrogramMatcher_H + +#include +#include +#include +#include +#include +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" + +namespace PokemonAutomation{ + +class AudioSpectrum; + +// Load an audio template from disk and use its spectrogram to match the +// spectrogram of the incoming audio stream. +class SpectrogramMatcher{ +public: + enum class Mode{ + // Don't do any processing on each window of spectrum, matching raw spectrums. + RAW, + // Do convolution on each window of spectrum with a peak detection kernel, before matching spectrums. + SPIKE_CONV, + // Do convolution on each window of spectrum with a Gaussian smooth kernel, before matching spectrums. + // GAUSSIAN_CONV, + // Average every 5 frequencies to reduce computation. + AVERAGE_5, + }; + + // audioTemplate: the audio template for the audio stream to match against. + // Use AudioTemplate::loadAudioTemplate() to load a template from disk, or + // use AudioTemplateCache::instance().get_throw(audioResourceRelativePath, sample_rate) to get one from cache. + // mode: which type of spectrogram filtering to use before the actual match. + // sample_rate: audio sample rate. + // low_frequency_filter: only match the frequencies above this threshold. + // templateSubdivision: divide the template into how many sub-templates to match. <= 1 means no subdivision. + SpectrogramMatcher( + std::string name, + AudioTemplate audioTemplate, Mode mode, size_t sample_rate, + double low_frequency_filter, size_t templateSubdivision = 0 + ); + + size_t sample_rate() const{ return m_sample_rate; } + + // Match the newest spectrums and return a match score. + // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller + // timestamp) spectrums at the end. + // In invalid cases (internal error or not enough windows), return FLT_MAX + float match(const std::vector& new_spectrums); + + // Pass some spectrums in but don't run match on them. + // Used for skipping some spectrums to avoid unnecessary matching. + // Newer (larger timestamp) spectrums at beginning of `new_spectrums` while older (smaller + // timestamp) spectrums at the end. + // Return true if there is no error. + bool skip(const std::vector& new_spectrums); + + // Clear internal data to be used on another audio stream. + void clear(); + + // How many windows are used for matching. + size_t numMatchedWindows() const { return m_numSpectrumsNeeded; } + + // Return latest timestamp from the stored audio spectrum stream. + // Return SIZE_MAX if there is no stored spectrum yet. + uint64_t latestTimestamp() const; + + // Return the scale found by the matcher to scale the input audio stream to best + // match the template in the last `match()`. + // Return 0.0f if the last scale is not available. + float lastMatchedScale() const { return m_lastScale; } + +private: + void conv(const float* src, size_t num, float* dst); + + // The function to build `m_templateNorm` + std::vector buildTemplateNorm() const; + + // For a given sub-template, return its match score and scaling factor + std::pair match_sub_template(size_t sub_index) const; + + // Update internal data for the next new spectrum. Called by `update_to_new_spectrums()`. + // Return true if there is no error. + bool update_to_new_spectrum(AudioSpectrum newSpectrum); + + // Update internal data for the new specttrums. + // Return true if there is no error. + bool update_to_new_spectrums(const std::vector& new_spectrums); + + + +private: + std::string m_name; + AudioTemplate m_template; + + size_t m_sample_rate; + + size_t m_numOriginalFrequencies = 0; + size_t m_originalFreqStart = 0; + size_t m_originalFreqEnd = 0; + + size_t m_freqStart = 0; + size_t m_freqEnd = 0; + // Temporal ranges of the template to match with. Used when matching a subdivided template. + // If there is no subdivision, it will store only one pair: <0, m_template.numWindows()> + std::vector> m_templateRange; + // For each subdivided template, store its sepctrogram matrix norm + std::vector m_templateNorm; + + Mode m_mode = Mode::RAW; + + std::vector m_convKernel; + + // Spectrums from audio feed. They will be matched against the template. + std::list m_spectrums; + // Norm squares of each spectrum in `m_spectrums`. + std::list m_spectrumNormSqrs; + // How many spectrums needed to store. + size_t m_numSpectrumsNeeded = 0; + + size_t m_lastStampTested = SIZE_MAX; + float m_lastScale = 0.0f; +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/DetectionDebouncer.h b/SerialPrograms/Source/CommonTools/DetectionDebouncer.h index ee4f41cf24..d451d9cb9a 100644 --- a/SerialPrograms/Source/CommonTools/DetectionDebouncer.h +++ b/SerialPrograms/Source/CommonTools/DetectionDebouncer.h @@ -1,70 +1,70 @@ -/* Detection Debouncer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_DetectionDebouncer_H -#define PokemonAutomation_CommonTools_DetectionDebouncer_H - -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -template -class DetectionDebouncer{ -public: - DetectionDebouncer( - Type initial_state, - std::chrono::milliseconds min_streak, - std::function&& state_reporter - ) - : m_min_streak(min_streak) - , m_state_reporter(std::move(state_reporter)) - , m_current_reported(initial_state) - , m_last_match(current_time()) - {} - - // This is fully thread-safe. - Type get() const{ - return m_current_reported.load(std::memory_order_acquire); - } - - // Only one thread at a time is allowed to call this. - Type push_value(Type value, WallClock timestamp){ - Type current_reported = get(); - - // No change. - if (value == current_reported){ - m_last_match = timestamp; - return current_reported; - } - - // Not long enough. - if (m_last_match + m_min_streak > timestamp){ - return current_reported; - } - - m_state_reporter(value); - m_last_match = timestamp; - m_current_reported.store(value, std::memory_order_release); - return value; - } - - -private: - std::chrono::milliseconds m_min_streak; - std::function m_state_reporter; - - std::atomic m_current_reported; - WallClock m_last_match; -}; - - - - -} -#endif +/* Detection Debouncer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_DetectionDebouncer_H +#define PokemonAutomation_CommonTools_DetectionDebouncer_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +template +class DetectionDebouncer{ +public: + DetectionDebouncer( + Type initial_state, + std::chrono::milliseconds min_streak, + std::function&& state_reporter + ) + : m_min_streak(min_streak) + , m_state_reporter(std::move(state_reporter)) + , m_current_reported(initial_state) + , m_last_match(current_time()) + {} + + // This is fully thread-safe. + Type get() const{ + return m_current_reported.load(std::memory_order_acquire); + } + + // Only one thread at a time is allowed to call this. + Type push_value(Type value, WallClock timestamp){ + Type current_reported = get(); + + // No change. + if (value == current_reported){ + m_last_match = timestamp; + return current_reported; + } + + // Not long enough. + if (m_last_match + m_min_streak > timestamp){ + return current_reported; + } + + m_state_reporter(value); + m_last_match = timestamp; + m_current_reported.store(value, std::memory_order_release); + return value; + } + + +private: + std::chrono::milliseconds m_min_streak; + std::function m_state_reporter; + + std::atomic m_current_reported; + WallClock m_last_match; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/FailureWatchdog.h b/SerialPrograms/Source/CommonTools/FailureWatchdog.h index 05f330cdf2..c1ef88cf7d 100644 --- a/SerialPrograms/Source/CommonTools/FailureWatchdog.h +++ b/SerialPrograms/Source/CommonTools/FailureWatchdog.h @@ -1,112 +1,112 @@ -/* Failure Watchdog - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_FailureWatchdog_H -#define PokemonAutomation_CommonTools_FailureWatchdog_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ - - - - - -class FailureWatchdog{ -public: - FailureWatchdog( - Logger& logger, - std::string failure_message, - uint64_t min_count = 5, - double min_success_rate = 0.5, - std::chrono::seconds time_limit = std::chrono::seconds(120) - ) - : m_logger(logger) - , m_failure_message(std::move(failure_message)) - , m_min_count(min_count) - , m_min_success_rate(min_success_rate) - , m_time_limit(time_limit) - { - restart(); - } - void restart(){ - m_expiration = current_time() + m_time_limit; - m_expired = false; - m_successes = 0; - m_total = 0; - } - - void push_result(bool success){ - m_successes += success ? 1 : 0; - m_total++; - if (success || m_expired){ - return; - } - - WallClock current = current_time(); - if (current >= m_expiration){ - m_expired = true; - } - - if (m_total < m_min_count){ - return; - } - - double threshold = (double)m_total * m_min_success_rate; - if ((double)m_successes >= threshold){ - return; - } - - - throw UserSetupError(m_logger, m_failure_message); - } - - -private: - Logger& m_logger; - std::string m_failure_message; - uint64_t m_min_count; - double m_min_success_rate; - WallDuration m_time_limit; - WallClock m_expiration; - bool m_expired; - - uint64_t m_successes; - uint64_t m_total; -}; - - - - - -class OcrFailureWatchdog : public FailureWatchdog{ -public: - OcrFailureWatchdog( - Logger& logger, - std::string failure_message = "Too many text recognition errors. Did you set the correct language?", - uint64_t min_count = 5, - double min_success_rate = 0.5, - std::chrono::seconds time_limit = std::chrono::seconds(120) - ) - : FailureWatchdog( - logger, - std::move(failure_message), - min_count, - min_success_rate, - time_limit - ) - {} -}; - - - - - - -} -#endif +/* Failure Watchdog + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_FailureWatchdog_H +#define PokemonAutomation_CommonTools_FailureWatchdog_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ + + + + + +class FailureWatchdog{ +public: + FailureWatchdog( + Logger& logger, + std::string failure_message, + uint64_t min_count = 5, + double min_success_rate = 0.5, + std::chrono::seconds time_limit = std::chrono::seconds(120) + ) + : m_logger(logger) + , m_failure_message(std::move(failure_message)) + , m_min_count(min_count) + , m_min_success_rate(min_success_rate) + , m_time_limit(time_limit) + { + restart(); + } + void restart(){ + m_expiration = current_time() + m_time_limit; + m_expired = false; + m_successes = 0; + m_total = 0; + } + + void push_result(bool success){ + m_successes += success ? 1 : 0; + m_total++; + if (success || m_expired){ + return; + } + + WallClock current = current_time(); + if (current >= m_expiration){ + m_expired = true; + } + + if (m_total < m_min_count){ + return; + } + + double threshold = (double)m_total * m_min_success_rate; + if ((double)m_successes >= threshold){ + return; + } + + + throw UserSetupError(m_logger, m_failure_message); + } + + +private: + Logger& m_logger; + std::string m_failure_message; + uint64_t m_min_count; + double m_min_success_rate; + WallDuration m_time_limit; + WallClock m_expiration; + bool m_expired; + + uint64_t m_successes; + uint64_t m_total; +}; + + + + + +class OcrFailureWatchdog : public FailureWatchdog{ +public: + OcrFailureWatchdog( + Logger& logger, + std::string failure_message = "Too many text recognition errors. Did you set the correct language?", + uint64_t min_count = 5, + double min_success_rate = 0.5, + std::chrono::seconds time_limit = std::chrono::seconds(120) + ) + : FailureWatchdog( + logger, + std::move(failure_message), + min_count, + min_success_rate, + time_limit + ) + {} +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp b/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp index a46c5f9615..4b9c28c83f 100644 --- a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp +++ b/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.cpp @@ -1,27 +1,27 @@ -/* Global Inference Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "GlobalInferenceRunner.h" - -namespace PokemonAutomation{ - - - -ParallelTaskRunner& global_inference_runner(){ - static ParallelTaskRunner runner( - [](){ - GlobalSettings::instance().PERFORMANCE->NORMAL_INFERENCE_PRIORITY.set_on_this_thread(); - }, - 0, std::thread::hardware_concurrency() - ); - return runner; -} - - - -} +/* Global Inference Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "GlobalInferenceRunner.h" + +namespace PokemonAutomation{ + + + +ParallelTaskRunner& global_inference_runner(){ + static ParallelTaskRunner runner( + [](){ + GlobalSettings::instance().PERFORMANCE->NORMAL_INFERENCE_PRIORITY.set_on_this_thread(); + }, + 0, std::thread::hardware_concurrency() + ); + return runner; +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h b/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h index 3621586301..98364e798b 100644 --- a/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h +++ b/SerialPrograms/Source/CommonTools/GlobalInferenceRunner.h @@ -1,21 +1,21 @@ -/* Global Inference Runner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_GlobalInferenceRunner_H -#define PokemonAutomation_CommonTools_GlobalInferenceRunner_H - -#include "Common/Cpp/Concurrency/ParallelTaskRunner.h" - -namespace PokemonAutomation{ - - - -ParallelTaskRunner& global_inference_runner(); - - - -} -#endif +/* Global Inference Runner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_GlobalInferenceRunner_H +#define PokemonAutomation_CommonTools_GlobalInferenceRunner_H + +#include "Common/Cpp/Concurrency/ParallelTaskRunner.h" + +namespace PokemonAutomation{ + + + +ParallelTaskRunner& global_inference_runner(); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp index 40dd4daa72..a638556fa2 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.cpp @@ -1,138 +1,138 @@ -/* Cropped Image Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "ImageCropper.h" -//#include "ImageDiff.h" -#include "CroppedImageDictionaryMatcher.h" - -#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - -CroppedImageDictionaryMatcher::CroppedImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) - : m_weight(weight) -{} -void CroppedImageDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); - } - auto iter = m_database.find(slug); - if (iter != m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); - } - - ImageViewRGB32 cropped = trim_image_alpha(image); - -#if 0 - if (slug == "hamburger"){ - image.save("matcher-original.png"); - cropped.save("matcher-cropped.png"); - } -#endif - - iter = m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple(cropped.copy(), m_weight) - ).first; -// cout << iter->first << ": " << iter->second.stats().stddev.sum() << endl; -} - - - -ImageMatchResult CroppedImageDictionaryMatcher::match( - const ImageViewRGB32& image, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ - std::cout << "CroppedImageDictionaryMatcher: match input image: " << std::endl; - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input", image); - } - - std::vector crops = get_crop_candidates(image); - - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ -// size_t c = 0; - for (const ImageViewRGB32& crop : crops){ -// std::cout << "CroppedImageDictionaryMatcher: process input" << c << "image with background " << crop.background.to_string() << std::endl; - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", crop); -// c++; - } - } - - - - for (const auto& item : m_database){ - for (const ImageViewRGB32& crop : crops){ - double alpha = item.second.diff(crop); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } - } - - - -#if 0 - Color background; - ImageViewRGB32 processed = cropped[0].image; - background = cropped[0].background; - -// ImageRGB32 processed = process_image(image, background); - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ - std::cout << "CroppedImageDictionaryMatcher: process input image with background " << background.to_string() << std::endl; - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", processed); - } - - processed.save("processed.png"); - - for (const auto& item : m_database){ -#if 0 - if (item.first != "onion"){ - continue; - } -#endif - double alpha = item.second.diff(processed); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } -#endif - - if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ - std::cout << "CroppedImageDictionaryMatcher: results: " << std::endl; - size_t count = 0; - for(const auto& result : results.results){ - std::cout << "alpha=" << result.first << ", " << result.second << std::endl; - const auto& image_template = m_database.find(result.second)->second.image_template(); - dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_result_" + std::to_string(count) + "_" + result.second, image_template); - ++count; - } - } - return results; -} - - - - - - -} -} +/* Cropped Image Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "ImageCropper.h" +//#include "ImageDiff.h" +#include "CroppedImageDictionaryMatcher.h" + +#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + +CroppedImageDictionaryMatcher::CroppedImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) + : m_weight(weight) +{} +void CroppedImageDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); + } + auto iter = m_database.find(slug); + if (iter != m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); + } + + ImageViewRGB32 cropped = trim_image_alpha(image); + +#if 0 + if (slug == "hamburger"){ + image.save("matcher-original.png"); + cropped.save("matcher-cropped.png"); + } +#endif + + iter = m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple(cropped.copy(), m_weight) + ).first; +// cout << iter->first << ": " << iter->second.stats().stddev.sum() << endl; +} + + + +ImageMatchResult CroppedImageDictionaryMatcher::match( + const ImageViewRGB32& image, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ + std::cout << "CroppedImageDictionaryMatcher: match input image: " << std::endl; + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input", image); + } + + std::vector crops = get_crop_candidates(image); + + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ +// size_t c = 0; + for (const ImageViewRGB32& crop : crops){ +// std::cout << "CroppedImageDictionaryMatcher: process input" << c << "image with background " << crop.background.to_string() << std::endl; + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", crop); +// c++; + } + } + + + + for (const auto& item : m_database){ + for (const ImageViewRGB32& crop : crops){ + double alpha = item.second.diff(crop); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } + } + + + +#if 0 + Color background; + ImageViewRGB32 processed = cropped[0].image; + background = cropped[0].background; + +// ImageRGB32 processed = process_image(image, background); + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ + std::cout << "CroppedImageDictionaryMatcher: process input image with background " << background.to_string() << std::endl; + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_input_processed", processed); + } + + processed.save("processed.png"); + + for (const auto& item : m_database){ +#if 0 + if (item.first != "onion"){ + continue; + } +#endif + double alpha = item.second.diff(processed); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } +#endif + + if (PreloadSettings::debug().IMAGE_DICTIONARY_MATCHING){ + std::cout << "CroppedImageDictionaryMatcher: results: " << std::endl; + size_t count = 0; + for(const auto& result : results.results){ + std::cout << "alpha=" << result.first << ", " << result.second << std::endl; + const auto& image_template = m_database.find(result.second)->second.image_template(); + dump_debug_image(global_logger_command_line(), "CommonFramework/CroppedImageDictionaryMatcher", "match_result_" + std::to_string(count) + "_" + result.second, image_template); + ++count; + } + } + return results; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h index 575dfaca5d..0c2b21119f 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h @@ -1,43 +1,43 @@ -/* Cropped Image Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H -#define PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H - -#include -#include "ImageMatchResult.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - -// Similar to `ExactImageDictionaryMatcher` but will crop the image based on background pixel colors before matching. -class CroppedImageDictionaryMatcher{ -public: - CroppedImageDictionaryMatcher( - const WeightedExactImageMatcher::InverseStddevWeight& weight = WeightedExactImageMatcher::InverseStddevWeight() - ); - virtual ~CroppedImageDictionaryMatcher() = default; - - void add(const std::string& slug, const ImageViewRGB32& image); - - ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; - - -protected: - // Return potential crops for this image. - virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const = 0; - - -private: - WeightedExactImageMatcher::InverseStddevWeight m_weight; - std::map m_database; -}; - - -} -} -#endif +/* Cropped Image Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H +#define PokemonAutomation_CommonTools_CroppedImageDictionaryMatcher_H + +#include +#include "ImageMatchResult.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + +// Similar to `ExactImageDictionaryMatcher` but will crop the image based on background pixel colors before matching. +class CroppedImageDictionaryMatcher{ +public: + CroppedImageDictionaryMatcher( + const WeightedExactImageMatcher::InverseStddevWeight& weight = WeightedExactImageMatcher::InverseStddevWeight() + ); + virtual ~CroppedImageDictionaryMatcher() = default; + + void add(const std::string& slug, const ImageViewRGB32& image); + + ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; + + +protected: + // Return potential crops for this image. + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const = 0; + + +private: + WeightedExactImageMatcher::InverseStddevWeight m_weight; + std::map m_database; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp index a77a8793a9..014d273a2a 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.cpp @@ -1,196 +1,196 @@ -/* Exact Image Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "ExactImageDictionaryMatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - -// Generate candidate images to be matched against by translating the input image area -// (`box` on `screen`) around. -// The returned candidate images are scaled to match template shape `dimension`. -// `tolerance`: how much translation variances to produce. -// e.g. tolerance of 1 means translating the candidate images around so that it can match -// the template with at most 1 pixel off on the template image. -std::vector make_image_set( - const ImageViewRGB32& screen, - const ImageFloatBox& box, - size_t width, size_t height, - size_t tolerance -){ - double num_template_pixels = (double)width * height; - double num_image_pixels = screen.width() * box.width * screen.height() * box.height; -// cout << std::sqrt(image / num_template_pixels) << endl; - // scale: roughly the relative size between the input image and the template. - // e.g. if the input image is 10 x 6 and template is 5 x 3, then `scale` is 2. - ptrdiff_t scale = (ptrdiff_t)(std::sqrt(num_image_pixels / num_template_pixels) + 0.5); - scale = std::max(scale, 1); - - std::vector ret; - ptrdiff_t limit = (ptrdiff_t)tolerance; - for (ptrdiff_t y = -limit; y <= limit; y++){ - for (ptrdiff_t x = -limit; x <= limit; x++){ -// if (x != 0 || y != -4){ -// continue; -// } - - ret.emplace_back( - extract_box_reference(screen, box, x * scale, y * scale).scale_to(width, height) - ); -// cout << "make_image_set(): image = " << ret.back().width() << " x " << ret.back().height() << endl; -// if (x == 0 && y == 0){ -// ret.back().save("image.png"); -// } - } - } -// cout << "size = " << ret.size() << endl; - return ret; -} - - - -ExactImageDictionaryMatcher::ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) - : m_weight(weight) -{} -void ExactImageDictionaryMatcher::add(const std::string& slug, ImageRGB32 image){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); - } - if (m_width != 0){ - if (image.width() != m_width || image.height() != m_height){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); - } - }else{ - m_width = image.width(); - m_height = image.height(); - } - auto iter = m_database.find(slug); - if (iter != m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); - } - - m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple(std::move(image), m_weight) - ); -// if (slug == "linoone-galar" || slug == "coalossal"){ -// cout << slug << " = " << m_database.find(slug)->second.stats().stddev.sum() << endl; -// } -} - - -#if 0 -void ExactImageDictionaryMatcher::scale_to_dimensions(ImageRGB32& image) const{ - if (image.width() != m_width || image.height() != m_height){ - image = image.scale_to(m_width, m_height); - } - } -} -#endif - - -double ExactImageDictionaryMatcher::compare( - const WeightedExactImageMatcher& sprite, - const std::vector& images -){ -// sprite.m_image.save("sprite.png"); -// images[0].save("image.png"); - - double best = 10000; - for (const ImageRGB32& image : images){ - double rmsd_alpha = sprite.diff(image); -// cout << rmsd_alpha << endl; -// if (rmsd_alpha < 0.38){ -// sprite.m_image.save("sprite.png"); -// image.save("image.png"); -// } - best = std::min(best, rmsd_alpha); - } -// cout << best << endl; - return best; -} - -ImageMatchResult ExactImageDictionaryMatcher::match( - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - // Translate the input image area a bit to careate matching candidates. - std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); - for (const auto& item : m_database){ -// if (item.first != "linoone-galar"){ -// continue; -// } - double alpha = compare(item.second, image_set); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } - - return results; -} - -ImageMatchResult ExactImageDictionaryMatcher::subset_match( - const std::vector& subset, - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - // Translate the input image area a bit to careate matching candidates. - std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); - for (const auto& slug : subset){ - const auto& matcher = image_matcher(slug); - double alpha = compare(matcher, image_set); - results.add(alpha, slug); - results.clear_beyond_spread(alpha_spread); - } - - return results; -} - -ImageViewRGB32 ExactImageDictionaryMatcher::image_template(const std::string& slug) const{ - auto it = m_database.find(slug); - if (it == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); - } - - return it->second.image_template(); -} - -const WeightedExactImageMatcher& ExactImageDictionaryMatcher::image_matcher(const std::string& slug) const{ - auto it = m_database.find(slug); - if (it == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); - } - - return it->second; -} - - -} -} +/* Exact Image Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "ExactImageDictionaryMatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + +// Generate candidate images to be matched against by translating the input image area +// (`box` on `screen`) around. +// The returned candidate images are scaled to match template shape `dimension`. +// `tolerance`: how much translation variances to produce. +// e.g. tolerance of 1 means translating the candidate images around so that it can match +// the template with at most 1 pixel off on the template image. +std::vector make_image_set( + const ImageViewRGB32& screen, + const ImageFloatBox& box, + size_t width, size_t height, + size_t tolerance +){ + double num_template_pixels = (double)width * height; + double num_image_pixels = screen.width() * box.width * screen.height() * box.height; +// cout << std::sqrt(image / num_template_pixels) << endl; + // scale: roughly the relative size between the input image and the template. + // e.g. if the input image is 10 x 6 and template is 5 x 3, then `scale` is 2. + ptrdiff_t scale = (ptrdiff_t)(std::sqrt(num_image_pixels / num_template_pixels) + 0.5); + scale = std::max(scale, 1); + + std::vector ret; + ptrdiff_t limit = (ptrdiff_t)tolerance; + for (ptrdiff_t y = -limit; y <= limit; y++){ + for (ptrdiff_t x = -limit; x <= limit; x++){ +// if (x != 0 || y != -4){ +// continue; +// } + + ret.emplace_back( + extract_box_reference(screen, box, x * scale, y * scale).scale_to(width, height) + ); +// cout << "make_image_set(): image = " << ret.back().width() << " x " << ret.back().height() << endl; +// if (x == 0 && y == 0){ +// ret.back().save("image.png"); +// } + } + } +// cout << "size = " << ret.size() << endl; + return ret; +} + + + +ExactImageDictionaryMatcher::ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight) + : m_weight(weight) +{} +void ExactImageDictionaryMatcher::add(const std::string& slug, ImageRGB32 image){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); + } + if (m_width != 0){ + if (image.width() != m_width || image.height() != m_height){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); + } + }else{ + m_width = image.width(); + m_height = image.height(); + } + auto iter = m_database.find(slug); + if (iter != m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); + } + + m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple(std::move(image), m_weight) + ); +// if (slug == "linoone-galar" || slug == "coalossal"){ +// cout << slug << " = " << m_database.find(slug)->second.stats().stddev.sum() << endl; +// } +} + + +#if 0 +void ExactImageDictionaryMatcher::scale_to_dimensions(ImageRGB32& image) const{ + if (image.width() != m_width || image.height() != m_height){ + image = image.scale_to(m_width, m_height); + } + } +} +#endif + + +double ExactImageDictionaryMatcher::compare( + const WeightedExactImageMatcher& sprite, + const std::vector& images +){ +// sprite.m_image.save("sprite.png"); +// images[0].save("image.png"); + + double best = 10000; + for (const ImageRGB32& image : images){ + double rmsd_alpha = sprite.diff(image); +// cout << rmsd_alpha << endl; +// if (rmsd_alpha < 0.38){ +// sprite.m_image.save("sprite.png"); +// image.save("image.png"); +// } + best = std::min(best, rmsd_alpha); + } +// cout << best << endl; + return best; +} + +ImageMatchResult ExactImageDictionaryMatcher::match( + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + // Translate the input image area a bit to careate matching candidates. + std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); + for (const auto& item : m_database){ +// if (item.first != "linoone-galar"){ +// continue; +// } + double alpha = compare(item.second, image_set); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } + + return results; +} + +ImageMatchResult ExactImageDictionaryMatcher::subset_match( + const std::vector& subset, + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + // Translate the input image area a bit to careate matching candidates. + std::vector image_set = make_image_set(image, box, m_width, m_height, tolerance); + for (const auto& slug : subset){ + const auto& matcher = image_matcher(slug); + double alpha = compare(matcher, image_set); + results.add(alpha, slug); + results.clear_beyond_spread(alpha_spread); + } + + return results; +} + +ImageViewRGB32 ExactImageDictionaryMatcher::image_template(const std::string& slug) const{ + auto it = m_database.find(slug); + if (it == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); + } + + return it->second.image_template(); +} + +const WeightedExactImageMatcher& ExactImageDictionaryMatcher::image_matcher(const std::string& slug) const{ + auto it = m_database.find(slug); + if (it == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown slug: " + slug); + } + + return it->second; +} + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h index 94e1658d88..7e72f7e272 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageDictionaryMatcher.h @@ -1,89 +1,89 @@ -/* Exact Image Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H -#define PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H - -#include -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "ImageMatchResult.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; - struct ImageFloatBox; -namespace ImageMatch{ - - -// Build a dictionary of image templates and use them to match against images. -// All the image templates must have the same image shape. -class ExactImageDictionaryMatcher{ -public: - ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight); - - // Add an image template. - // Do not allow one slug to have more than one template. - void add(const std::string& slug, ImageRGB32 image_template); - -// QSize dimensions() const{ return m_dimensions; } - - // Scale image to match the size of the templates. -// void scale_to_dimensions(ImageRGB32& image) const; - - // Match the `box` area on `image` against the stored template dictionary. - // `tolerance`: how much translation noise to tolerate. tolerance of 1 means to allow 1 pixel - // off on the template when matching. - // `alpha_spread`: only retain match results that no larger than the best match score + - // `max_alpha_spread`. - // - // Note: the dictionary must contain at least one template. - // The input image area will be scaled to the template shape before matching. - // The brightness of the input image and the stddev of the template is compensated during - // matching. - ImageMatchResult match( - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread - ) const; - - // Match on a subset of the templates. - // See match() for deatils on how the matching is done against a template. - ImageMatchResult subset_match( - const std::vector& subset, - const ImageViewRGB32& image, const ImageFloatBox& box, - size_t tolerance, - double alpha_spread - ) const; - - ImageViewRGB32 image_template(const std::string& slug) const; - - const WeightedExactImageMatcher& image_matcher(const std::string& slug) const; - - -private: - static double compare( - const WeightedExactImageMatcher& sprite, - const std::vector& images - ); - - -private: - WeightedExactImageMatcher::InverseStddevWeight m_weight; - // The size of the image templates. - // Each template must have the same size. -// QSize m_dimensions; - size_t m_width = 0; - size_t m_height = 0; - std::map m_database; -}; - - - -} -} -#endif +/* Exact Image Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H +#define PokemonAutomation_CommonTools_ExactImageDictionaryMatcher_H + +#include +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "ImageMatchResult.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; + struct ImageFloatBox; +namespace ImageMatch{ + + +// Build a dictionary of image templates and use them to match against images. +// All the image templates must have the same image shape. +class ExactImageDictionaryMatcher{ +public: + ExactImageDictionaryMatcher(const WeightedExactImageMatcher::InverseStddevWeight& weight); + + // Add an image template. + // Do not allow one slug to have more than one template. + void add(const std::string& slug, ImageRGB32 image_template); + +// QSize dimensions() const{ return m_dimensions; } + + // Scale image to match the size of the templates. +// void scale_to_dimensions(ImageRGB32& image) const; + + // Match the `box` area on `image` against the stored template dictionary. + // `tolerance`: how much translation noise to tolerate. tolerance of 1 means to allow 1 pixel + // off on the template when matching. + // `alpha_spread`: only retain match results that no larger than the best match score + + // `max_alpha_spread`. + // + // Note: the dictionary must contain at least one template. + // The input image area will be scaled to the template shape before matching. + // The brightness of the input image and the stddev of the template is compensated during + // matching. + ImageMatchResult match( + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread + ) const; + + // Match on a subset of the templates. + // See match() for deatils on how the matching is done against a template. + ImageMatchResult subset_match( + const std::vector& subset, + const ImageViewRGB32& image, const ImageFloatBox& box, + size_t tolerance, + double alpha_spread + ) const; + + ImageViewRGB32 image_template(const std::string& slug) const; + + const WeightedExactImageMatcher& image_matcher(const std::string& slug) const; + + +private: + static double compare( + const WeightedExactImageMatcher& sprite, + const std::vector& images + ); + + +private: + WeightedExactImageMatcher::InverseStddevWeight m_weight; + // The size of the image templates. + // Each template must have the same size. +// QSize m_dimensions; + size_t m_width = 0; + size_t m_height = 0; + std::map m_database; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp index fc101bff81..f08a44d16d 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.cpp @@ -1,140 +1,140 @@ -/* Image Match Preprocessed Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "ExactImageMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -ExactImageMatcher::ExactImageMatcher(ImageRGB32 image) - : m_image(std::move(image)) - , m_stats(image_stats(m_image)) -{ - if (!m_image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is null."); - } -// cout << m_stats.stddev.sum() << endl; -} - -ImageRGB32 ExactImageMatcher::scale_template_brightness(const ImageViewRGB32& image) const{ - FloatPixel image_brightness = pixel_average(image, m_image); - FloatPixel scale = image_brightness / m_stats.average; - - if (std::isnan(scale.r)) scale.r = 1.0; - if (std::isnan(scale.g)) scale.g = 1.0; - if (std::isnan(scale.b)) scale.b = 1.0; - scale.bound(0.85, 1.15); - - ImageRGB32 ret = m_image.copy(); - scale_brightness(ret, scale); -// ret.save("test.png"); - return ret; -} - - -double ExactImageMatcher::rmsd(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - -// image.save("test.png"); - -// cout << "ExactImageMatcher::rmsd(): image = " << image.width() << " x " << image.height() << endl; - ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); -// cout << "ExactImageMatcher::rmsd(): scaled = " << scaled.width() << " x " << scaled.height() << endl; - ImageRGB32 reference = scale_template_brightness(scaled); - -#if 0 - static int c = 0; - image.save("test-" + std::to_string(c) + "-image.png"); - reference.save("test-" + std::to_string(c) + "-sprite.png"); - c++; -#endif - - double rmsd = pixel_RMSD(reference, scaled); -// cout << "rmsd = " << rmsd << endl; - return rmsd; -} -double ExactImageMatcher::rmsd(const ImageViewRGB32& image, Color background) const{ - if (!image){ - return 1000.; - } - ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); - ImageRGB32 reference = scale_template_brightness(scaled); - -#if 0 - static int c = 0; - scaled.save("test-" + std::to_string(c) + "-image.png"); - reference.save("test-" + std::to_string(c) + "-sprite.png"); - c++; -#endif - - return pixel_RMSD(reference, scaled, background); -} -double ExactImageMatcher::rmsd_masked(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); - ImageRGB32 reference = scale_template_brightness(scaled); - return pixel_RMSD_masked(reference, scaled); -} - - - - -WeightedExactImageMatcher::WeightedExactImageMatcher(ImageRGB32 image, const InverseStddevWeight& weight) - : ExactImageMatcher(std::move(image)) - , m_multiplier(1. / (m_stats.stddev.sum() * weight.stddev_coefficient + weight.offset)) -{} - - -double WeightedExactImageMatcher::diff(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - return rmsd(image) * m_multiplier; -} -double WeightedExactImageMatcher::diff(const ImageViewRGB32& image, Color background) const{ - if (!image){ - return 1000.; - } - return rmsd(image, background) * m_multiplier; -} -double WeightedExactImageMatcher::diff_masked(const ImageViewRGB32& image) const{ - if (!image){ - return 1000.; - } - return rmsd_masked(image) * m_multiplier; -} - - - - - - - - - - - - - - - - - - -} -} +/* Image Match Preprocessed Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "ExactImageMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +ExactImageMatcher::ExactImageMatcher(ImageRGB32 image) + : m_image(std::move(image)) + , m_stats(image_stats(m_image)) +{ + if (!m_image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is null."); + } +// cout << m_stats.stddev.sum() << endl; +} + +ImageRGB32 ExactImageMatcher::scale_template_brightness(const ImageViewRGB32& image) const{ + FloatPixel image_brightness = pixel_average(image, m_image); + FloatPixel scale = image_brightness / m_stats.average; + + if (std::isnan(scale.r)) scale.r = 1.0; + if (std::isnan(scale.g)) scale.g = 1.0; + if (std::isnan(scale.b)) scale.b = 1.0; + scale.bound(0.85, 1.15); + + ImageRGB32 ret = m_image.copy(); + scale_brightness(ret, scale); +// ret.save("test.png"); + return ret; +} + + +double ExactImageMatcher::rmsd(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + +// image.save("test.png"); + +// cout << "ExactImageMatcher::rmsd(): image = " << image.width() << " x " << image.height() << endl; + ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); +// cout << "ExactImageMatcher::rmsd(): scaled = " << scaled.width() << " x " << scaled.height() << endl; + ImageRGB32 reference = scale_template_brightness(scaled); + +#if 0 + static int c = 0; + image.save("test-" + std::to_string(c) + "-image.png"); + reference.save("test-" + std::to_string(c) + "-sprite.png"); + c++; +#endif + + double rmsd = pixel_RMSD(reference, scaled); +// cout << "rmsd = " << rmsd << endl; + return rmsd; +} +double ExactImageMatcher::rmsd(const ImageViewRGB32& image, Color background) const{ + if (!image){ + return 1000.; + } + ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); + ImageRGB32 reference = scale_template_brightness(scaled); + +#if 0 + static int c = 0; + scaled.save("test-" + std::to_string(c) + "-image.png"); + reference.save("test-" + std::to_string(c) + "-sprite.png"); + c++; +#endif + + return pixel_RMSD(reference, scaled, background); +} +double ExactImageMatcher::rmsd_masked(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + ImageRGB32 scaled = image.scale_to(m_image.width(), m_image.height()); + ImageRGB32 reference = scale_template_brightness(scaled); + return pixel_RMSD_masked(reference, scaled); +} + + + + +WeightedExactImageMatcher::WeightedExactImageMatcher(ImageRGB32 image, const InverseStddevWeight& weight) + : ExactImageMatcher(std::move(image)) + , m_multiplier(1. / (m_stats.stddev.sum() * weight.stddev_coefficient + weight.offset)) +{} + + +double WeightedExactImageMatcher::diff(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + return rmsd(image) * m_multiplier; +} +double WeightedExactImageMatcher::diff(const ImageViewRGB32& image, Color background) const{ + if (!image){ + return 1000.; + } + return rmsd(image, background) * m_multiplier; +} +double WeightedExactImageMatcher::diff_masked(const ImageViewRGB32& image) const{ + if (!image){ + return 1000.; + } + return rmsd_masked(image) * m_multiplier; +} + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h index 5288a03376..c05ec2fc71 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ExactImageMatcher.h @@ -1,100 +1,100 @@ -/* Exact Image Match Preprocessed Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ExactImageMatcher_H -#define PokemonAutomation_CommonTools_ExactImageMatcher_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Match images against a template. -// Before matching, resize the input image to the template shape and scale template brightness to -// match the input image. Alpha channels as used as masks in matching. -// No other treatment like tolerating translation or scaling based on stddevs, hence the name "Exact". -class ExactImageMatcher{ - ExactImageMatcher(ExactImageMatcher&&) = default; - ExactImageMatcher& operator=(ExactImageMatcher&&) = default; - ExactImageMatcher(const ExactImageMatcher&) = delete; - void operator=(const ExactImageMatcher&) = delete; - -public: - ExactImageMatcher(const std::string& image_template) - : ExactImageMatcher(ImageRGB32(image_template)) - {} - ExactImageMatcher(ImageRGB32 image_template); - - const ImageStats& stats() const{ return m_stats; } - - // Resize image to match the shape of the image template, scale the template brightness to match - // the input image, then compute their RMSD (root mean square deviation). - // The part of the image template where alpha is 0 is not used to compare with the corresponding - // part in the input image. - double rmsd(const ImageViewRGB32& image) const; - // Resize image to match the shape of the image template, scale the template brightness to match - // the input image, then compute their RMSD (root mean square deviation). - // The part of the image template where alpha is 0 is replace with `background` color when comparing - // against the corresponding part in the input image. - double rmsd(const ImageViewRGB32& image, Color background) const; - // Resize image to match the shape of the image template, scale the template brightness to match - // the input image, then compute their RMSD (root mean square deviation). - // Alpha channels from both the template and the input image are considered when computing RMSD. - // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel - // distance. - // If both two images have alpha==0 on one pixel, that pixel is ignored. - double rmsd_masked(const ImageViewRGB32& image) const; - - const ImageRGB32& image_template() const { return m_image; } - -private: - // scale stored image template according to the brightness of `image`, assign - // the scaled template to `reference`. - ImageRGB32 scale_template_brightness(const ImageViewRGB32& image) const; - -protected: - ImageRGB32 m_image; - ImageStats m_stats; -}; - - -// Based on ExactImageMatcher, adds new stddev scaling. -// An image template with higher stddev tends to have lots of detail. RMSD against an input image tends to -// be high because high details will be skewered by stuff like compression artifacts and translational shifts. -// So a template with high stddev tends to give higher RMSD than one with low stddev. -// To compensate for this, when calling WeightedExactImageMatcher::diff...(), it scales the computed RMSD -// based on template stddev, tunable by additional parameters defined in -// WeightedExactImageMatcher::InverseStddevWeight. -class WeightedExactImageMatcher : public ExactImageMatcher{ -public: - // Used to tune RMSD based on stddev of the template - // Equation: - // RMSD_scaled = RMSD_original / (template_stddev * `stddev_coefficient` + `offset`) - // where template_stddev is the sum of the stddev on all three channels (RGB) of the template. - struct InverseStddevWeight{ - double stddev_coefficient = 0.0; - double offset = 1.0; - }; - - WeightedExactImageMatcher(ImageRGB32 image_template, const InverseStddevWeight& weight); - - // Like ExactImageMatcher::rmsd(image) but scale based on template stddev. - double diff(const ImageViewRGB32& image) const; - // Like ExactImageMatcher::rmsd(image, background) but scale based on template stddev. - double diff(const ImageViewRGB32& image, Color background) const; - // Like ExactImageMatcher::rmsd_masked(image) but scale based on template stddev. - double diff_masked(const ImageViewRGB32& image) const; - -public: - double m_multiplier; -}; - - -} -} -#endif +/* Exact Image Match Preprocessed Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ExactImageMatcher_H +#define PokemonAutomation_CommonTools_ExactImageMatcher_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Match images against a template. +// Before matching, resize the input image to the template shape and scale template brightness to +// match the input image. Alpha channels as used as masks in matching. +// No other treatment like tolerating translation or scaling based on stddevs, hence the name "Exact". +class ExactImageMatcher{ + ExactImageMatcher(ExactImageMatcher&&) = default; + ExactImageMatcher& operator=(ExactImageMatcher&&) = default; + ExactImageMatcher(const ExactImageMatcher&) = delete; + void operator=(const ExactImageMatcher&) = delete; + +public: + ExactImageMatcher(const std::string& image_template) + : ExactImageMatcher(ImageRGB32(image_template)) + {} + ExactImageMatcher(ImageRGB32 image_template); + + const ImageStats& stats() const{ return m_stats; } + + // Resize image to match the shape of the image template, scale the template brightness to match + // the input image, then compute their RMSD (root mean square deviation). + // The part of the image template where alpha is 0 is not used to compare with the corresponding + // part in the input image. + double rmsd(const ImageViewRGB32& image) const; + // Resize image to match the shape of the image template, scale the template brightness to match + // the input image, then compute their RMSD (root mean square deviation). + // The part of the image template where alpha is 0 is replace with `background` color when comparing + // against the corresponding part in the input image. + double rmsd(const ImageViewRGB32& image, Color background) const; + // Resize image to match the shape of the image template, scale the template brightness to match + // the input image, then compute their RMSD (root mean square deviation). + // Alpha channels from both the template and the input image are considered when computing RMSD. + // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel + // distance. + // If both two images have alpha==0 on one pixel, that pixel is ignored. + double rmsd_masked(const ImageViewRGB32& image) const; + + const ImageRGB32& image_template() const { return m_image; } + +private: + // scale stored image template according to the brightness of `image`, assign + // the scaled template to `reference`. + ImageRGB32 scale_template_brightness(const ImageViewRGB32& image) const; + +protected: + ImageRGB32 m_image; + ImageStats m_stats; +}; + + +// Based on ExactImageMatcher, adds new stddev scaling. +// An image template with higher stddev tends to have lots of detail. RMSD against an input image tends to +// be high because high details will be skewered by stuff like compression artifacts and translational shifts. +// So a template with high stddev tends to give higher RMSD than one with low stddev. +// To compensate for this, when calling WeightedExactImageMatcher::diff...(), it scales the computed RMSD +// based on template stddev, tunable by additional parameters defined in +// WeightedExactImageMatcher::InverseStddevWeight. +class WeightedExactImageMatcher : public ExactImageMatcher{ +public: + // Used to tune RMSD based on stddev of the template + // Equation: + // RMSD_scaled = RMSD_original / (template_stddev * `stddev_coefficient` + `offset`) + // where template_stddev is the sum of the stddev on all three channels (RGB) of the template. + struct InverseStddevWeight{ + double stddev_coefficient = 0.0; + double offset = 1.0; + }; + + WeightedExactImageMatcher(ImageRGB32 image_template, const InverseStddevWeight& weight); + + // Like ExactImageMatcher::rmsd(image) but scale based on template stddev. + double diff(const ImageViewRGB32& image) const; + // Like ExactImageMatcher::rmsd(image, background) but scale based on template stddev. + double diff(const ImageViewRGB32& image, Color background) const; + // Like ExactImageMatcher::rmsd_masked(image) but scale based on template stddev. + double diff_masked(const ImageViewRGB32& image) const; + +public: + double m_multiplier; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp index 682bd1ffd9..57b29674bd 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.cpp @@ -1,78 +1,78 @@ -/* Filter to Alpha - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "FilterToAlpha.h" - -#ifdef PA_ARCH_x86 -#include -#endif - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - -void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum){ - size_t words = image.bytes_per_row() / sizeof(uint32_t); - uint32_t* data = image.data(); - - size_t width = image.width(); - size_t height = image.height(); - -#ifdef PA_ARCH_x86 - __m128i threshold = _mm_set1_epi32(max_rgb_sum); -#endif - - uint32_t* row = data; - for (size_t r = 0; r < height; r++){ - size_t c = 0; -#ifdef PA_ARCH_x86 - while (c + 3 < width){ - __m128i pixel = _mm_loadu_si128((__m128i*)(row + c)); -// print8(pixel); cout << " ====> "; - - pixel = _mm_andnot_si128(_mm_set1_epi32(0xff000000), pixel); - - __m128i sum = _mm_and_si128(pixel, _mm_set1_epi32(0x000000ff)); - sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 8), _mm_set1_epi32(0x000000ff))); - sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 16), _mm_set1_epi32(0x000000ff))); - sum = _mm_cmpgt_epi32(sum, threshold); - sum = _mm_andnot_si128(sum, _mm_set1_epi32(0xff000000)); - pixel = _mm_or_si128(pixel, sum); - -// print8(pixel); cout << endl; - - _mm_storeu_si128((__m128i*)(row + c), pixel); - c += 4; - } -#endif - while (c < width){ - uint32_t pixel = row[c]; - // Set alpha channel to 0. - pixel &= 0x00ffffff; - - uint32_t sum = pixel & 0xff; - sum += (pixel >> 8) & 0xff; - sum += (pixel >> 16) & 0xff; - if (sum <= max_rgb_sum){ - // If dark, set alpha channel to 255. - pixel |= 0xff000000; - } - row[c] = pixel; - c++; - } - - - row += words; - } -} - - - -} -} +/* Filter to Alpha + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "FilterToAlpha.h" + +#ifdef PA_ARCH_x86 +#include +#endif + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + +void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum){ + size_t words = image.bytes_per_row() / sizeof(uint32_t); + uint32_t* data = image.data(); + + size_t width = image.width(); + size_t height = image.height(); + +#ifdef PA_ARCH_x86 + __m128i threshold = _mm_set1_epi32(max_rgb_sum); +#endif + + uint32_t* row = data; + for (size_t r = 0; r < height; r++){ + size_t c = 0; +#ifdef PA_ARCH_x86 + while (c + 3 < width){ + __m128i pixel = _mm_loadu_si128((__m128i*)(row + c)); +// print8(pixel); cout << " ====> "; + + pixel = _mm_andnot_si128(_mm_set1_epi32(0xff000000), pixel); + + __m128i sum = _mm_and_si128(pixel, _mm_set1_epi32(0x000000ff)); + sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 8), _mm_set1_epi32(0x000000ff))); + sum = _mm_add_epi32(sum, _mm_and_si128(_mm_srli_epi32(pixel, 16), _mm_set1_epi32(0x000000ff))); + sum = _mm_cmpgt_epi32(sum, threshold); + sum = _mm_andnot_si128(sum, _mm_set1_epi32(0xff000000)); + pixel = _mm_or_si128(pixel, sum); + +// print8(pixel); cout << endl; + + _mm_storeu_si128((__m128i*)(row + c), pixel); + c += 4; + } +#endif + while (c < width){ + uint32_t pixel = row[c]; + // Set alpha channel to 0. + pixel &= 0x00ffffff; + + uint32_t sum = pixel & 0xff; + sum += (pixel >> 8) & 0xff; + sum += (pixel >> 16) & 0xff; + if (sum <= max_rgb_sum){ + // If dark, set alpha channel to 255. + pixel |= 0xff000000; + } + row[c] = pixel; + c++; + } + + + row += words; + } +} + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h index 4e7611ca45..4ef660198d 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/FilterToAlpha.h @@ -1,26 +1,26 @@ -/* Filter to Alpha - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_FilterToAlpha_H -#define PokemonAutomation_CommonTools_FilterToAlpha_H - -#include - -namespace PokemonAutomation{ - class ImageRGB32; -namespace ImageMatch{ - - - -// For each pixel, set the alpha channel to 255 if the RGB sum is no greater than "max_rgb_sum". -// The rest pixels are set to 0 alpha. -// This function is fast. -void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum = 100); - - -} -} -#endif +/* Filter to Alpha + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_FilterToAlpha_H +#define PokemonAutomation_CommonTools_FilterToAlpha_H + +#include + +namespace PokemonAutomation{ + class ImageRGB32; +namespace ImageMatch{ + + + +// For each pixel, set the alpha channel to 255 if the RGB sum is no greater than "max_rgb_sum". +// The rest pixels are set to 0 alpha. +// This function is fast. +void set_alpha_black(ImageRGB32& image, uint32_t max_rgb_sum = 100); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp index 7e3c66ea91..0ddcf9eebd 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.cpp @@ -1,75 +1,75 @@ -/* Image Cropper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ImageCropper.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Scan one row to find if all pixels in the row are from background -bool is_background_row(const ImageViewRGB32& image, size_t row, const std::function& is_foreground){ - for (size_t c = 0; c < image.width(); c++){ - Color pixel(image.pixel(c, row)); - if (is_foreground(pixel)){ -// cout << "{" << c << "," << row << "}" << endl; - return false; - } - } - return true; -} - -// Scan one col to find if all pixels in the col are from background -bool is_background_col(const ImageViewRGB32& image, size_t col, const std::function& is_foreground){ - for (size_t r = 0; r < image.height(); r++){ - Color pixel(image.pixel(col, r)); - if (is_foreground(pixel)){ -// cout << "{" << col << "," << r << "}" << endl; - return false; - } - } - return true; -} - -ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold){ - auto is_foreground = [=](Color pixel){ - return pixel.alpha() >= alpha_threshold; - }; - const auto box = enclosing_rectangle_with_pixel_filter(image, is_foreground); - - return extract_box_reference(image, box); -} - -ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_foreground){ - size_t rs = 0; - size_t re = image.height(); - size_t cs = 0; - size_t ce = image.width(); - -// cout << "Before: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; - - // If we cannot find a foreground (aka, alpha != 0) pixel on one row or column, we trim it, until hitting a foreground pixel. - while (rs < re && is_background_row(image, rs , is_foreground)) rs++; - while (re > rs && is_background_row(image, re - 1, is_foreground)) re--; - while (cs < ce && is_background_col(image, cs , is_foreground)) cs++; - while (ce > cs && is_background_col(image, ce - 1, is_foreground)) ce--; - -// cout << "After: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; - - return ImagePixelBox(cs, rs, ce, re); -} - - - - - - -} -} +/* Image Cropper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ImageCropper.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Scan one row to find if all pixels in the row are from background +bool is_background_row(const ImageViewRGB32& image, size_t row, const std::function& is_foreground){ + for (size_t c = 0; c < image.width(); c++){ + Color pixel(image.pixel(c, row)); + if (is_foreground(pixel)){ +// cout << "{" << c << "," << row << "}" << endl; + return false; + } + } + return true; +} + +// Scan one col to find if all pixels in the col are from background +bool is_background_col(const ImageViewRGB32& image, size_t col, const std::function& is_foreground){ + for (size_t r = 0; r < image.height(); r++){ + Color pixel(image.pixel(col, r)); + if (is_foreground(pixel)){ +// cout << "{" << col << "," << r << "}" << endl; + return false; + } + } + return true; +} + +ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold){ + auto is_foreground = [=](Color pixel){ + return pixel.alpha() >= alpha_threshold; + }; + const auto box = enclosing_rectangle_with_pixel_filter(image, is_foreground); + + return extract_box_reference(image, box); +} + +ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_foreground){ + size_t rs = 0; + size_t re = image.height(); + size_t cs = 0; + size_t ce = image.width(); + +// cout << "Before: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; + + // If we cannot find a foreground (aka, alpha != 0) pixel on one row or column, we trim it, until hitting a foreground pixel. + while (rs < re && is_background_row(image, rs , is_foreground)) rs++; + while (re > rs && is_background_row(image, re - 1, is_foreground)) re--; + while (cs < ce && is_background_col(image, cs , is_foreground)) cs++; + while (ce > cs && is_background_col(image, ce - 1, is_foreground)) ce--; + +// cout << "After: rs = " << rs << ", re = " << re << ", cs = " << cs << ", ce = " << ce << endl; + + return ImagePixelBox(cs, rs, ce, re); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h index 843196d107..bb3a92077e 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageCropper.h @@ -1,34 +1,34 @@ -/* Image Cropper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageCropper_H -#define PokemonAutomation_CommonTools_ImageCropper_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Shrink image so that it perfectly fits the object. -// The alpha channel is used to determine what is object vs. background. -// background is defined as alpha < alpha_threshold. -ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold = 128); - - -// Find a crop of the object based on background color. -// The pixels of the object are defined as is_object(pixel_color) == true. -// Return the rectangle enclosing the object. -ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_object); - - - -} -} -#endif +/* Image Cropper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageCropper_H +#define PokemonAutomation_CommonTools_ImageCropper_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Shrink image so that it perfectly fits the object. +// The alpha channel is used to determine what is object vs. background. +// background is defined as alpha < alpha_threshold. +ImageViewRGB32 trim_image_alpha(const ImageViewRGB32& image, uint8_t alpha_threshold = 128); + + +// Find a crop of the object based on background color. +// The pixels of the object are defined as is_object(pixel_color) == true. +// Return the rectangle enclosing the object. +ImagePixelBox enclosing_rectangle_with_pixel_filter(const ImageViewRGB32& image, const std::function& is_object); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp index a84a8ba519..dc3668fcd2 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.cpp @@ -1,17 +1,17 @@ -/* Image Match Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ImageMatchOption.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - - - -} -} +/* Image Match Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ImageMatchOption.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h index cbca6c1648..9028dda0e8 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchOption.h @@ -1,21 +1,21 @@ -/* Image Match Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageMatchOption_H -#define PokemonAutomation_CommonTools_ImageMatchOption_H - -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - - - - -} -} -#endif +/* Image Match Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageMatchOption_H +#define PokemonAutomation_CommonTools_ImageMatchOption_H + +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp index a271140405..a41fbe0997 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.cpp @@ -1,84 +1,84 @@ -/* Image Match Result - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ImageMatchResult.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -void ImageMatchResult::log(Logger& logger, double max_alpha) const{ - std::string str = "Image Match Result: "; - - if (results.empty()){ - str += "no matches"; - logger.log(str, COLOR_RED); - return; - } - - double best = results.begin()->first; - Color color = best <= max_alpha - ? COLOR_BLUE - : COLOR_RED; - - if (results.size() == 1){ - auto iter = results.begin(); - str += iter->second; - str += " (alpha = "; - str += std::to_string(iter->first); - str += ")"; - logger.log(str, color); - return; - } - - str += "Multiple Candidates =>\n"; - size_t printed = 0; - for (const auto& item : results){ - if (printed == 10){ - str += " (" + std::to_string(results.size() - 10) + " more...)\n"; - break; - } - str += " "; - str += std::to_string(item.first); - str += " : "; - str += item.second; - str += "\n"; - printed++; - } - - logger.log(str, color); -} - -void ImageMatchResult::add(double alpha, std::string slug){ - results.emplace(alpha, std::move(slug)); -} -void ImageMatchResult::clear_beyond_spread(double max_alpha_spread){ - auto best = results.begin(); - while (results.size() > 1){ - auto back = results.end(); - --back; - if (back->first <= best->first + max_alpha_spread){ - break; - } - results.erase(back); - } -} -void ImageMatchResult::clear_beyond_alpha(double max_alpha){ - while (!results.empty()){ - auto iter = results.end(); - --iter; - if (iter->first <= max_alpha){ - break; - } - results.erase(iter); - } -} - - - - -} -} +/* Image Match Result + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ImageMatchResult.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +void ImageMatchResult::log(Logger& logger, double max_alpha) const{ + std::string str = "Image Match Result: "; + + if (results.empty()){ + str += "no matches"; + logger.log(str, COLOR_RED); + return; + } + + double best = results.begin()->first; + Color color = best <= max_alpha + ? COLOR_BLUE + : COLOR_RED; + + if (results.size() == 1){ + auto iter = results.begin(); + str += iter->second; + str += " (alpha = "; + str += std::to_string(iter->first); + str += ")"; + logger.log(str, color); + return; + } + + str += "Multiple Candidates =>\n"; + size_t printed = 0; + for (const auto& item : results){ + if (printed == 10){ + str += " (" + std::to_string(results.size() - 10) + " more...)\n"; + break; + } + str += " "; + str += std::to_string(item.first); + str += " : "; + str += item.second; + str += "\n"; + printed++; + } + + logger.log(str, color); +} + +void ImageMatchResult::add(double alpha, std::string slug){ + results.emplace(alpha, std::move(slug)); +} +void ImageMatchResult::clear_beyond_spread(double max_alpha_spread){ + auto best = results.begin(); + while (results.size() > 1){ + auto back = results.end(); + --back; + if (back->first <= best->first + max_alpha_spread){ + break; + } + results.erase(back); + } +} +void ImageMatchResult::clear_beyond_alpha(double max_alpha){ + while (!results.empty()){ + auto iter = results.end(); + --iter; + if (iter->first <= max_alpha){ + break; + } + results.erase(iter); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h index f8a744fb45..4766f3f28b 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/ImageMatchResult.h @@ -1,41 +1,41 @@ -/* Image Match Result - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageMatchResult_H -#define PokemonAutomation_CommonTools_ImageMatchResult_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -struct ImageMatchResult{ - // Stored match score (the lower the closer the match) -> slug of the image template that gives the score. - std::multimap results; - - // Write to log the current matching results stored in `results`. - // Use `max_alpha` to determine whether matches are found. - void log(Logger& logger, double max_alpha) const; - - // Add to `results`. - // alpha: the match score, the lower the closer the match. - // slug: slug of the image template that gives the score. - void add(double alpha, std::string slug); - - // Assume there is at least one result in `results`: - // Remove other weaker match results that have a score that's larger than the best match score + `max_alpha_spread`. - void clear_beyond_spread(double max_alpha_spread); - // Remove match results with scores > `max_alpha`. - void clear_beyond_alpha(double max_alpha); -}; - - -} -} -#endif +/* Image Match Result + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageMatchResult_H +#define PokemonAutomation_CommonTools_ImageMatchResult_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +struct ImageMatchResult{ + // Stored match score (the lower the closer the match) -> slug of the image template that gives the score. + std::multimap results; + + // Write to log the current matching results stored in `results`. + // Use `max_alpha` to determine whether matches are found. + void log(Logger& logger, double max_alpha) const; + + // Add to `results`. + // alpha: the match score, the lower the closer the match. + // slug: slug of the image template that gives the score. + void add(double alpha, std::string slug); + + // Assume there is at least one result in `results`: + // Remove other weaker match results that have a score that's larger than the best match score + `max_alpha_spread`. + void clear_beyond_spread(double max_alpha_spread); + // Remove match results with scores > `max_alpha`. + void clear_beyond_alpha(double max_alpha); +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp index 3fc6fe8a6f..2a59cb760a 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.cpp @@ -1,86 +1,86 @@ -/* Cropped Silhouette Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonTools/GlobalInferenceRunner.h" -#include "ImageCropper.h" -#include "SilhouetteDictionaryMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -void SilhouetteDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ - if (!image){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); - } - auto iter = m_database.find(slug); - if (iter != m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); - } - - iter = m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple(trim_image_alpha(image).copy()) - ).first; - m_database_vector.emplace_back(&*iter); -} - - - -ImageMatchResult SilhouetteDictionaryMatcher::match( - const ImageViewRGB32& image, - double alpha_spread -) const{ - ImageMatchResult results; - if (!image){ - return results; - } - - SpinLock lock; - global_inference_runner().run_in_parallel( - [&](size_t index){ - const auto& matcher = *m_database_vector[index]; - double alpha = matcher.second.rmsd_masked(image); - WriteSpinLock lg(lock); - results.add(alpha, matcher.first); - results.clear_beyond_spread(alpha_spread); - }, - 0, m_database_vector.size(), - 100 - ); - - -#if 0 - for (const auto& item : m_database){ -// if (item.first != "solosis"){ -// continue; -// } - double alpha = item.second.rmsd_masked(image); -// WriteSpinLock lg(lock); - results.add(alpha, item.first); - results.clear_beyond_spread(alpha_spread); - } -#endif - - return results; -} - - - - - - -} -} +/* Cropped Silhouette Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonTools/GlobalInferenceRunner.h" +#include "ImageCropper.h" +#include "SilhouetteDictionaryMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +void SilhouetteDictionaryMatcher::add(const std::string& slug, const ImageViewRGB32& image){ + if (!image){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Null image."); + } + auto iter = m_database.find(slug); + if (iter != m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate slug: " + slug); + } + + iter = m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple(trim_image_alpha(image).copy()) + ).first; + m_database_vector.emplace_back(&*iter); +} + + + +ImageMatchResult SilhouetteDictionaryMatcher::match( + const ImageViewRGB32& image, + double alpha_spread +) const{ + ImageMatchResult results; + if (!image){ + return results; + } + + SpinLock lock; + global_inference_runner().run_in_parallel( + [&](size_t index){ + const auto& matcher = *m_database_vector[index]; + double alpha = matcher.second.rmsd_masked(image); + WriteSpinLock lg(lock); + results.add(alpha, matcher.first); + results.clear_beyond_spread(alpha_spread); + }, + 0, m_database_vector.size(), + 100 + ); + + +#if 0 + for (const auto& item : m_database){ +// if (item.first != "solosis"){ +// continue; +// } + double alpha = item.second.rmsd_masked(image); +// WriteSpinLock lg(lock); + results.add(alpha, item.first); + results.clear_beyond_spread(alpha_spread); + } +#endif + + return results; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h index f44b4a377e..1368fe5b75 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h @@ -1,56 +1,56 @@ -/* Silhouette Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H -#define PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H - -//#include "Common/Compiler.h" -//#include "CommonFramework/ImageTools/FloatPixel.h" -#include "ImageMatchResult.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace ImageMatch{ - - -// Match silhouette to several templates. -class SilhouetteDictionaryMatcher{ -public: - SilhouetteDictionaryMatcher(SilhouetteDictionaryMatcher&&) = default; - SilhouetteDictionaryMatcher& operator=(SilhouetteDictionaryMatcher&&) = default; - SilhouetteDictionaryMatcher(const SilhouetteDictionaryMatcher&) = delete; - void operator=(const SilhouetteDictionaryMatcher&) = delete; - -public: - SilhouetteDictionaryMatcher() = default; - virtual ~SilhouetteDictionaryMatcher() = default; - - // Add a silhouette template. The alpha==0 boundaries in the image will be trimmed when added. - void add(const std::string& slug, const ImageViewRGB32& image); - - // Match the input image with the templates. - // alpha_spread: used as tolerance for multiple match results. - // Apart from the best march result, other weaker match results are also returned in `ImageMatchResult` if - // their scores are not larger than the best match score + `alpha_spread`. - // Details of the match algorithm: - // Resize image first to match the shape of the image template. Then scale the template brightness to match - // the input image. Finally compute their RMSD (root mean square deviation). - // Alpha channels from both the template and the input image are considered when computing RMSD. - // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel distance. - // If both two images have alpha==0 on one pixel, that pixel is ignored. - ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; - - -private: - std::map m_database; - std::vector*> m_database_vector; -}; - - -} -} -#endif +/* Silhouette Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H +#define PokemonAutomation_CommonTools_SilhouetteDictionaryMatcher_H + +//#include "Common/Compiler.h" +//#include "CommonFramework/ImageTools/FloatPixel.h" +#include "ImageMatchResult.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace ImageMatch{ + + +// Match silhouette to several templates. +class SilhouetteDictionaryMatcher{ +public: + SilhouetteDictionaryMatcher(SilhouetteDictionaryMatcher&&) = default; + SilhouetteDictionaryMatcher& operator=(SilhouetteDictionaryMatcher&&) = default; + SilhouetteDictionaryMatcher(const SilhouetteDictionaryMatcher&) = delete; + void operator=(const SilhouetteDictionaryMatcher&) = delete; + +public: + SilhouetteDictionaryMatcher() = default; + virtual ~SilhouetteDictionaryMatcher() = default; + + // Add a silhouette template. The alpha==0 boundaries in the image will be trimmed when added. + void add(const std::string& slug, const ImageViewRGB32& image); + + // Match the input image with the templates. + // alpha_spread: used as tolerance for multiple match results. + // Apart from the best march result, other weaker match results are also returned in `ImageMatchResult` if + // their scores are not larger than the best match score + `alpha_spread`. + // Details of the match algorithm: + // Resize image first to match the shape of the image template. Then scale the template brightness to match + // the input image. Finally compute their RMSD (root mean square deviation). + // Alpha channels from both the template and the input image are considered when computing RMSD. + // If only one of the two has alpha==255 on one pixel, that the deviation on that pixel is the max pixel distance. + // If both two images have alpha==0 on one pixel, that pixel is ignored. + ImageMatchResult match(const ImageViewRGB32& image, double alpha_spread) const; + + +private: + std::map m_database; + std::vector*> m_database_vector; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp index de2887edc9..8792a0ee79 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.cpp @@ -1,166 +1,166 @@ -/* Sub-Object Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/Globals.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "SubObjectTemplateMatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, double max_rmsd) - : m_path(RESOURCE_PATH() + path) - , m_max_rmsd(max_rmsd) - , m_matcher(m_path) - , m_subobject_area_ratio(0) -{} - -SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd) - : SubObjectTemplateMatcher(path, max_rmsd) -{ - m_background_replacement = background_replacement; -} - -ImagePixelBox SubObjectTemplateMatcher::object_from_subobject( - size_t width, size_t height, - const ImagePixelBox& subobject_in_image -) const{ - return extract_object_from_inner_feature( - width, height, - subobject_in_image, m_subobject_in_object_f - ); -} - -double SubObjectTemplateMatcher::rmsd( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image -) const{ - object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); -// cout << object_box.min_x << ", " -// << object_box.min_y << ", " -// << object_box.max_x << ", " -// << object_box.max_y << endl; - ImageViewRGB32 object = extract_box_reference(image, object_box); - -// object.save("test.png"); - - - if (!object || !check_image(object)){ - return 99999.; - } - - return m_matcher.rmsd(object); -} -double SubObjectTemplateMatcher::rmsd_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const ImagePixelBox& subobject_in_image -) const{ - object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); - ImageRGB32 object = extract_box_reference(image, object_box).copy(); - if (!object || !check_image(object)){ - return 99999.; - } - -// size_t width = binary_image.width(); -// size_t height = binary_image.height(); -// cout << width << " x " << height -// << ": " << object_box.min_x << "-" << object_box.width() -// << " " << object_box.min_y << "-" << object_box.height() << endl; - - filter_by_mask( - binary_image.submatrix( - object_box.min_x, object_box.min_y, - object_box.width(), object_box.height() - ), - object, - m_background_replacement, - true - ); - - return m_matcher.rmsd(object); -} - - -void SubObjectTemplateMatcher::set_subobject(const WaterfillObject& subobject_in_object){ - m_subobject_in_object_p = subobject_in_object; - m_subobject_in_object_f = pixelbox_to_floatbox(m_matcher.image_template(), m_subobject_in_object_p); - m_subobject_area_ratio = subobject_in_object.area_ratio(); -} -bool SubObjectTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ -// double expected_aspect_ratio = (double)m_subobject_in_object_p.width() / m_subobject_in_object_p.height(); -// double actual_aspect_ratio = (double)width / height; -// double error = actual_aspect_ratio / expected_aspect_ratio; - -// cout << "expected_aspect_ratio = " << expected_aspect_ratio << endl; -// cout << "actual_aspect_ratio = " << actual_aspect_ratio << endl; - - double error = (double)m_subobject_in_object_p.width() * candidate_height; - error /= (double)m_subobject_in_object_p.height() * candidate_width; -// cout << "ratio = " << error << endl; - return m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; -} -bool SubObjectTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ - if (m_subobject_area_ratio == 0){ - return true; - } - double error = candidate_area_ratio / m_subobject_area_ratio; - return m_area_ratio_lower <= error && error <= m_area_ratio_upper; -} - -bool SubObjectTemplateMatcher::matches( - ImagePixelBox& object_box, - const ImageViewRGB32& image, - const WaterfillObject& subobject_in_image -) const{ - if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ - return false; - } - if (!check_area_ratio(subobject_in_image.area_ratio())){ - return false; - } - -// static int c = 0; -// cout << c++ << endl; - - double rmsd = this->rmsd(object_box, image, subobject_in_image); - -// cout << "rmsd = " << rmsd << endl; - -// if (rmsd <= m_max_rmsd){ -// static int c = 0; -// extract_box(image, object_box).save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); -// } - - return rmsd <= m_max_rmsd; -} -bool SubObjectTemplateMatcher::matches_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const WaterfillObject& subobject_in_image -) const{ - if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ - return false; - } - if (!check_area_ratio(subobject_in_image.area_ratio())){ - return false; - } - - double rmsd = this->rmsd_with_background_replace(object_box, image, binary_image, subobject_in_image); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= m_max_rmsd; -} - - - -} -} +/* Sub-Object Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/Globals.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "SubObjectTemplateMatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, double max_rmsd) + : m_path(RESOURCE_PATH() + path) + , m_max_rmsd(max_rmsd) + , m_matcher(m_path) + , m_subobject_area_ratio(0) +{} + +SubObjectTemplateMatcher::SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd) + : SubObjectTemplateMatcher(path, max_rmsd) +{ + m_background_replacement = background_replacement; +} + +ImagePixelBox SubObjectTemplateMatcher::object_from_subobject( + size_t width, size_t height, + const ImagePixelBox& subobject_in_image +) const{ + return extract_object_from_inner_feature( + width, height, + subobject_in_image, m_subobject_in_object_f + ); +} + +double SubObjectTemplateMatcher::rmsd( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image +) const{ + object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); +// cout << object_box.min_x << ", " +// << object_box.min_y << ", " +// << object_box.max_x << ", " +// << object_box.max_y << endl; + ImageViewRGB32 object = extract_box_reference(image, object_box); + +// object.save("test.png"); + + + if (!object || !check_image(object)){ + return 99999.; + } + + return m_matcher.rmsd(object); +} +double SubObjectTemplateMatcher::rmsd_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const ImagePixelBox& subobject_in_image +) const{ + object_box = object_from_subobject(image.width(), image.height(), subobject_in_image); + ImageRGB32 object = extract_box_reference(image, object_box).copy(); + if (!object || !check_image(object)){ + return 99999.; + } + +// size_t width = binary_image.width(); +// size_t height = binary_image.height(); +// cout << width << " x " << height +// << ": " << object_box.min_x << "-" << object_box.width() +// << " " << object_box.min_y << "-" << object_box.height() << endl; + + filter_by_mask( + binary_image.submatrix( + object_box.min_x, object_box.min_y, + object_box.width(), object_box.height() + ), + object, + m_background_replacement, + true + ); + + return m_matcher.rmsd(object); +} + + +void SubObjectTemplateMatcher::set_subobject(const WaterfillObject& subobject_in_object){ + m_subobject_in_object_p = subobject_in_object; + m_subobject_in_object_f = pixelbox_to_floatbox(m_matcher.image_template(), m_subobject_in_object_p); + m_subobject_area_ratio = subobject_in_object.area_ratio(); +} +bool SubObjectTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ +// double expected_aspect_ratio = (double)m_subobject_in_object_p.width() / m_subobject_in_object_p.height(); +// double actual_aspect_ratio = (double)width / height; +// double error = actual_aspect_ratio / expected_aspect_ratio; + +// cout << "expected_aspect_ratio = " << expected_aspect_ratio << endl; +// cout << "actual_aspect_ratio = " << actual_aspect_ratio << endl; + + double error = (double)m_subobject_in_object_p.width() * candidate_height; + error /= (double)m_subobject_in_object_p.height() * candidate_width; +// cout << "ratio = " << error << endl; + return m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; +} +bool SubObjectTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ + if (m_subobject_area_ratio == 0){ + return true; + } + double error = candidate_area_ratio / m_subobject_area_ratio; + return m_area_ratio_lower <= error && error <= m_area_ratio_upper; +} + +bool SubObjectTemplateMatcher::matches( + ImagePixelBox& object_box, + const ImageViewRGB32& image, + const WaterfillObject& subobject_in_image +) const{ + if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ + return false; + } + if (!check_area_ratio(subobject_in_image.area_ratio())){ + return false; + } + +// static int c = 0; +// cout << c++ << endl; + + double rmsd = this->rmsd(object_box, image, subobject_in_image); + +// cout << "rmsd = " << rmsd << endl; + +// if (rmsd <= m_max_rmsd){ +// static int c = 0; +// extract_box(image, object_box).save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); +// } + + return rmsd <= m_max_rmsd; +} +bool SubObjectTemplateMatcher::matches_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const WaterfillObject& subobject_in_image +) const{ + if (!check_aspect_ratio(subobject_in_image.width(), subobject_in_image.height())){ + return false; + } + if (!check_area_ratio(subobject_in_image.area_ratio())){ + return false; + } + + double rmsd = this->rmsd_with_background_replace(object_box, image, binary_image, subobject_in_image); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= m_max_rmsd; +} + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h index aa16c21b1d..46345e7465 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/SubObjectTemplateMatcher.h @@ -1,99 +1,99 @@ -/* Sub-Object Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - * Suppose we have an object with a distinctive sub-feature. - * - * We want to find this object in an image. But instead of searching for the - * entire object as a whole, we search for that distinctive sub-feature. - * - * Once we've found that sub-feature and have it's bounding box, we want to - * verify that the rest of the object matches the template. - * - */ - -#ifndef PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H -#define PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "ExactImageMatcher.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -class SubObjectTemplateMatcher{ -protected: - using WaterfillObject = Kernels::Waterfill::WaterfillObject; - -public: - virtual ~SubObjectTemplateMatcher() = default; - SubObjectTemplateMatcher(const char* path, double max_rmsd); - SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd); - - ImagePixelBox object_from_subobject( - size_t width, size_t height, - const ImagePixelBox& subobject_in_image - ) const; - - // Compute RMSD of current object against the template as-is. - double rmsd( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image - ) const; - - // Replace the background of the image with the "m_background_replacement". - // Then compute RMSD of it against the template. - // The background is defined by zero-bits in the binary matrix in "binary_image". - double rmsd_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const ImagePixelBox& subobject_in_image - ) const; - - virtual bool matches( - ImagePixelBox& object_box, - const ImageViewRGB32& image, - const WaterfillObject& subobject_in_image - ) const; - virtual bool matches_with_background_replace( - ImagePixelBox& object_box, - const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, - const WaterfillObject& subobject_in_image - ) const; - - -protected: - virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; - - void set_subobject(const WaterfillObject& subobject_in_object); - bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; - bool check_area_ratio(double candidate_area_ratio) const; - -protected: - std::string m_path; - Color m_background_replacement; - - double m_max_rmsd; - double m_aspect_ratio_lower = 0.80; - double m_aspect_ratio_upper = 1.25; - double m_area_ratio_lower = 0.80; - double m_area_ratio_upper = 1.25; - - ExactImageMatcher m_matcher; - ImagePixelBox m_subobject_in_object_p; - ImageFloatBox m_subobject_in_object_f; - double m_subobject_area_ratio; -}; - - - - - - - -} -} -#endif +/* Sub-Object Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + * Suppose we have an object with a distinctive sub-feature. + * + * We want to find this object in an image. But instead of searching for the + * entire object as a whole, we search for that distinctive sub-feature. + * + * Once we've found that sub-feature and have it's bounding box, we want to + * verify that the rest of the object matches the template. + * + */ + +#ifndef PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H +#define PokemonAutomation_CommonTools_SubObjectTemplateMatcher_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "ExactImageMatcher.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +class SubObjectTemplateMatcher{ +protected: + using WaterfillObject = Kernels::Waterfill::WaterfillObject; + +public: + virtual ~SubObjectTemplateMatcher() = default; + SubObjectTemplateMatcher(const char* path, double max_rmsd); + SubObjectTemplateMatcher(const char* path, Color background_replacement, double max_rmsd); + + ImagePixelBox object_from_subobject( + size_t width, size_t height, + const ImagePixelBox& subobject_in_image + ) const; + + // Compute RMSD of current object against the template as-is. + double rmsd( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const ImagePixelBox& subobject_in_image + ) const; + + // Replace the background of the image with the "m_background_replacement". + // Then compute RMSD of it against the template. + // The background is defined by zero-bits in the binary matrix in "binary_image". + double rmsd_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const ImagePixelBox& subobject_in_image + ) const; + + virtual bool matches( + ImagePixelBox& object_box, + const ImageViewRGB32& image, + const WaterfillObject& subobject_in_image + ) const; + virtual bool matches_with_background_replace( + ImagePixelBox& object_box, + const ImageViewRGB32& image, const PackedBinaryMatrix& binary_image, + const WaterfillObject& subobject_in_image + ) const; + + +protected: + virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; + + void set_subobject(const WaterfillObject& subobject_in_object); + bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; + bool check_area_ratio(double candidate_area_ratio) const; + +protected: + std::string m_path; + Color m_background_replacement; + + double m_max_rmsd; + double m_aspect_ratio_lower = 0.80; + double m_aspect_ratio_upper = 1.25; + double m_area_ratio_lower = 0.80; + double m_area_ratio_upper = 1.25; + + ExactImageMatcher m_matcher; + ImagePixelBox m_subobject_in_object_p; + ImageFloatBox m_subobject_in_object_f; + double m_subobject_area_ratio; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp index fa87444d7b..33816ad9ba 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.cpp @@ -1,187 +1,187 @@ -/* Waterfill Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "WaterfillTemplateMatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ImageMatch{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -WaterfillTemplateMatcher::WaterfillTemplateMatcher( - const char* path, - Color min_color, Color max_color, - size_t min_area -){ - std::string full_path = RESOURCE_PATH() + path; - ImageRGB32 reference(full_path); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - reference, - (uint32_t)min_color, (uint32_t)max_color - ); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - ImageRGB32 binaryImage = reference.copy(); - filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); - //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "waterfill_template_image_black_background", - binaryImage); - } - std::vector objects = find_objects_inplace(matrix, min_area); - if (objects.empty()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find any waterfill objects in resource template file.", - std::move(full_path) - ); - } - - const WaterfillObject* best = &objects[0]; - for (const WaterfillObject& object : objects){ - if (best->area < object.area){ - best = &object; - } - } - - m_matcher.reset(new ExactImageMatcher(extract_box_reference(reference, *best).copy())); - m_area_ratio = best->area_ratio(); - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - const auto exact_image = extract_box_reference(reference, *best); - cout << "Build waterfil template matcher from " << full_path << ", W x H: " << exact_image.width() - << " x " << exact_image.height() << ", area ratio: " << m_area_ratio << ", Object area: " << best->area << endl; - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "waterfill_template_matcher_reference_image", - exact_image); - } -} - -double WaterfillTemplateMatcher::rmsd(const ImageViewRGB32& image) const{ - if (!image || !check_image(image)){ - return 99999.; - } - return m_matcher->rmsd(image); -} -bool WaterfillTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ - ImageViewRGB32 image_template = m_matcher->image_template(); - - double error = (double)image_template.width() * candidate_height; - error /= (double)image_template.height() * candidate_width; - - bool pass = m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - if (!pass){ - cout << "Failed to pass WaterfillTemplateMatcher aspect ratio check (W/H): "; - }else{ - cout << "Passed WaterfillTemplateMatcher aspect ratio check (W/H): "; - } - cout << "expected: " << image_template.width() << " : " << image_template.height() - << " (" << (double)image_template.width()/image_template.height() << "), " - << "actual: " << candidate_width << " : " << candidate_height - << " (" << (double)candidate_width/candidate_height << ") " - << "error: " << error << " bound [" << m_aspect_ratio_lower << ", " << m_aspect_ratio_upper << "]" << endl; - } - - return pass; -} -bool WaterfillTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ - if (m_area_ratio == 0){ - return true; - } - double error = candidate_area_ratio / m_area_ratio; - bool pass = m_area_ratio_lower <= error && error <= m_area_ratio_upper; - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - if (!pass){ - cout << "Failed to pass WaterfillTemplateMatcher area ratio check: "; - }else{ - cout << "Passed WaterfillTemplateMatcher area ratio check: "; - } - cout << "Expected: " << m_area_ratio << ", actual: " << candidate_area_ratio << ", " - << "error: " << error << " bound [" << m_area_ratio_lower << ", " << m_area_ratio_upper << "]" << endl; - } - - return pass; -} -double WaterfillTemplateMatcher::rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const{ - - // XXX - // dump_debug_image(global_logger_command_line(), "CommonFramework/WaterfillTemplateMatcher", "rmsd_precropped_input", cropped_image); - - if (!check_aspect_ratio(object.width(), object.height())){ - // cout << "bad aspect ratio" << endl; - return 99999.; - } - if (!check_area_ratio(object.area_ratio())){ - // cout << "bad area ratio" << endl; - return 99999.; - } - -// static int c = 0; -// cout << c << endl; - - double rmsd = this->rmsd(cropped_image); - -// cout << "rmsd = " << rmsd << endl; - -// if (rmsd <= m_max_rmsd){ -// static int c = 0; -// cropped_image.save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); -// } - - return rmsd; -} -double WaterfillTemplateMatcher::rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const{ - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - cout << "rmsd_original()" << endl; - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "waterfill_template_matcher_rmsd_original_input", - extract_box_reference(original_image, object) - ); - } - - if (!check_aspect_ratio(object.width(), object.height())){ - return 99999.; - } - if (!check_area_ratio(object.area_ratio())){ - return 99999.; - } - - double rmsd = this->rmsd(extract_box_reference(original_image, object)); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - cout << "Passed aspect and area ratio check, rmsd = " << rmsd << endl; - } - - return rmsd; -} - - - - -} -} +/* Waterfill Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "WaterfillTemplateMatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ImageMatch{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +WaterfillTemplateMatcher::WaterfillTemplateMatcher( + const char* path, + Color min_color, Color max_color, + size_t min_area +){ + std::string full_path = RESOURCE_PATH() + path; + ImageRGB32 reference(full_path); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + reference, + (uint32_t)min_color, (uint32_t)max_color + ); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + ImageRGB32 binaryImage = reference.copy(); + filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); + //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "waterfill_template_image_black_background", + binaryImage); + } + std::vector objects = find_objects_inplace(matrix, min_area); + if (objects.empty()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find any waterfill objects in resource template file.", + std::move(full_path) + ); + } + + const WaterfillObject* best = &objects[0]; + for (const WaterfillObject& object : objects){ + if (best->area < object.area){ + best = &object; + } + } + + m_matcher.reset(new ExactImageMatcher(extract_box_reference(reference, *best).copy())); + m_area_ratio = best->area_ratio(); + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + const auto exact_image = extract_box_reference(reference, *best); + cout << "Build waterfil template matcher from " << full_path << ", W x H: " << exact_image.width() + << " x " << exact_image.height() << ", area ratio: " << m_area_ratio << ", Object area: " << best->area << endl; + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "waterfill_template_matcher_reference_image", + exact_image); + } +} + +double WaterfillTemplateMatcher::rmsd(const ImageViewRGB32& image) const{ + if (!image || !check_image(image)){ + return 99999.; + } + return m_matcher->rmsd(image); +} +bool WaterfillTemplateMatcher::check_aspect_ratio(size_t candidate_width, size_t candidate_height) const{ + ImageViewRGB32 image_template = m_matcher->image_template(); + + double error = (double)image_template.width() * candidate_height; + error /= (double)image_template.height() * candidate_width; + + bool pass = m_aspect_ratio_lower <= error && error <= m_aspect_ratio_upper; + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + if (!pass){ + cout << "Failed to pass WaterfillTemplateMatcher aspect ratio check (W/H): "; + }else{ + cout << "Passed WaterfillTemplateMatcher aspect ratio check (W/H): "; + } + cout << "expected: " << image_template.width() << " : " << image_template.height() + << " (" << (double)image_template.width()/image_template.height() << "), " + << "actual: " << candidate_width << " : " << candidate_height + << " (" << (double)candidate_width/candidate_height << ") " + << "error: " << error << " bound [" << m_aspect_ratio_lower << ", " << m_aspect_ratio_upper << "]" << endl; + } + + return pass; +} +bool WaterfillTemplateMatcher::check_area_ratio(double candidate_area_ratio) const{ + if (m_area_ratio == 0){ + return true; + } + double error = candidate_area_ratio / m_area_ratio; + bool pass = m_area_ratio_lower <= error && error <= m_area_ratio_upper; + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + if (!pass){ + cout << "Failed to pass WaterfillTemplateMatcher area ratio check: "; + }else{ + cout << "Passed WaterfillTemplateMatcher area ratio check: "; + } + cout << "Expected: " << m_area_ratio << ", actual: " << candidate_area_ratio << ", " + << "error: " << error << " bound [" << m_area_ratio_lower << ", " << m_area_ratio_upper << "]" << endl; + } + + return pass; +} +double WaterfillTemplateMatcher::rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const{ + + // XXX + // dump_debug_image(global_logger_command_line(), "CommonFramework/WaterfillTemplateMatcher", "rmsd_precropped_input", cropped_image); + + if (!check_aspect_ratio(object.width(), object.height())){ + // cout << "bad aspect ratio" << endl; + return 99999.; + } + if (!check_area_ratio(object.area_ratio())){ + // cout << "bad area ratio" << endl; + return 99999.; + } + +// static int c = 0; +// cout << c << endl; + + double rmsd = this->rmsd(cropped_image); + +// cout << "rmsd = " << rmsd << endl; + +// if (rmsd <= m_max_rmsd){ +// static int c = 0; +// cropped_image.save("test-" + std::to_string(c++) + "-" + std::to_string(rmsd) + ".png"); +// } + + return rmsd; +} +double WaterfillTemplateMatcher::rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const{ + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + cout << "rmsd_original()" << endl; + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "waterfill_template_matcher_rmsd_original_input", + extract_box_reference(original_image, object) + ); + } + + if (!check_aspect_ratio(object.width(), object.height())){ + return 99999.; + } + if (!check_area_ratio(object.area_ratio())){ + return 99999.; + } + + double rmsd = this->rmsd(extract_box_reference(original_image, object)); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + cout << "Passed aspect and area ratio check, rmsd = " << rmsd << endl; + } + + return rmsd; +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h index 120e652989..61342d48db 100644 --- a/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h +++ b/SerialPrograms/Source/CommonTools/ImageMatch/WaterfillTemplateMatcher.h @@ -1,96 +1,96 @@ -/* Waterfill Template Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H -#define PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" - -namespace PokemonAutomation{ -namespace ImageMatch{ - - -// Used to match an image or a waterfill object against a template object. -class WaterfillTemplateMatcher{ -protected: - using WaterfillObject = Kernels::Waterfill::WaterfillObject; - -public: - WaterfillTemplateMatcher(WaterfillTemplateMatcher&&) = default; - virtual ~WaterfillTemplateMatcher() = default; - - -public: - // Load a template image from disk, min_color and max_color denote the color range of the object - // displayed in the image file while min_area is the minimum number of pixels required for the - // object in the template to be loaded. - // - // The portion of the image holding the found object will get cropped and saved as the actual template image. - // So if someone changes the template image by padding it to make it larger, as long as the padded color - // does not fall into [min_color and max_color] range, it will not affect the template matching outcome - // in any way. - // - // Throw FileException when there is no object meeting the requirement in the template. - // If there are more than one objects meeting the requirement in the template, pick the one - // with the largest area (largest number of pixels). - WaterfillTemplateMatcher( - const char* path, - Color min_color, Color max_color, - size_t min_area - ); - - // Compute RMSD of the current image against the template as-is, using `ExactImageMatcher`. - // `ExactImageMatcher` will resize the image to match template size and scale template brightness to match the image - // before computing RMSD. - // In case the image is invalid, return a large value. - // It also calls the virtual function `check_image()` on the image. - // If the function returns false, then return a large value. - double rmsd(const ImageViewRGB32& image) const; - - // Compute RMSD of the object on the image against the template. - // The input `cropped_image` is already cropped from a full image using the bounding box of the input waterfill `object`. - // This cropped image is compared against the template as-is. - // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value - // if the check fails. - // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. - virtual double rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const; - - // Compute RMSD of the object on the image against the template. - // It will crop the original image using the bounding box of the waterfill object, then compare the cropped - // image against the template as-is. - // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value - // if the check fails. - // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. - virtual double rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const; - - // Return the image template mesh - const ImageRGB32& image_template() const { return m_matcher->image_template(); } - -protected: - virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; - bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; - bool check_area_ratio(double candidate_area_ratio) const; - -protected: - // Below are thresholds of aspect ratio and area ratio to reject a candidate. - // They are ususally set by the derived class of `WaterfillTemplateMatcher`. - double m_aspect_ratio_lower = 0.80; - double m_aspect_ratio_upper = 1.25; - double m_area_ratio_lower = 0.80; - double m_area_ratio_upper = 1.25; - - std::unique_ptr m_matcher; - double m_area_ratio; -}; - - - -} -} -#endif +/* Waterfill Template Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H +#define PokemonAutomation_CommonTools_WaterfillTemplateMatcher_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" + +namespace PokemonAutomation{ +namespace ImageMatch{ + + +// Used to match an image or a waterfill object against a template object. +class WaterfillTemplateMatcher{ +protected: + using WaterfillObject = Kernels::Waterfill::WaterfillObject; + +public: + WaterfillTemplateMatcher(WaterfillTemplateMatcher&&) = default; + virtual ~WaterfillTemplateMatcher() = default; + + +public: + // Load a template image from disk, min_color and max_color denote the color range of the object + // displayed in the image file while min_area is the minimum number of pixels required for the + // object in the template to be loaded. + // + // The portion of the image holding the found object will get cropped and saved as the actual template image. + // So if someone changes the template image by padding it to make it larger, as long as the padded color + // does not fall into [min_color and max_color] range, it will not affect the template matching outcome + // in any way. + // + // Throw FileException when there is no object meeting the requirement in the template. + // If there are more than one objects meeting the requirement in the template, pick the one + // with the largest area (largest number of pixels). + WaterfillTemplateMatcher( + const char* path, + Color min_color, Color max_color, + size_t min_area + ); + + // Compute RMSD of the current image against the template as-is, using `ExactImageMatcher`. + // `ExactImageMatcher` will resize the image to match template size and scale template brightness to match the image + // before computing RMSD. + // In case the image is invalid, return a large value. + // It also calls the virtual function `check_image()` on the image. + // If the function returns false, then return a large value. + double rmsd(const ImageViewRGB32& image) const; + + // Compute RMSD of the object on the image against the template. + // The input `cropped_image` is already cropped from a full image using the bounding box of the input waterfill `object`. + // This cropped image is compared against the template as-is. + // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value + // if the check fails. + // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. + virtual double rmsd_precropped(const ImageViewRGB32& cropped_image, const WaterfillObject& object) const; + + // Compute RMSD of the object on the image against the template. + // It will crop the original image using the bounding box of the waterfill object, then compare the cropped + // image against the template as-is. + // The waterfill object's aspect ratio and area ratio are checked against template's. Return a large value + // if the check fails. + // See `double rmsd(const ImageViewRGB32& image) const` on the details of comparing the image against the template. + virtual double rmsd_original(const ImageViewRGB32& original_image, const WaterfillObject& object) const; + + // Return the image template mesh + const ImageRGB32& image_template() const { return m_matcher->image_template(); } + +protected: + virtual bool check_image(const ImageViewRGB32& image) const{ return true; }; + bool check_aspect_ratio(size_t candidate_width, size_t candidate_height) const; + bool check_area_ratio(double candidate_area_ratio) const; + +protected: + // Below are thresholds of aspect ratio and area ratio to reject a candidate. + // They are ususally set by the derived class of `WaterfillTemplateMatcher`. + double m_aspect_ratio_lower = 0.80; + double m_aspect_ratio_upper = 1.25; + double m_area_ratio_lower = 0.80; + double m_area_ratio_upper = 1.25; + + std::unique_ptr m_matcher; + double m_area_ratio; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp index a0d3cb2239..284548a10c 100644 --- a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp +++ b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.cpp @@ -1,217 +1,217 @@ -/* Binary Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "BinaryImage_FilterRgb32.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, - Color replacement_color, - bool replace_zero_bits -){ - if (matrix.width() > image.width()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); - } - if (matrix.height() > image.height()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); - } - Kernels::filter_by_mask( - matrix, - image.data(), image.bytes_per_row(), - (uint32_t)replacement_color, replace_zero_bits - ); -} -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, size_t offset_x, size_t offset_y, - Color replacement_color, - bool replace_zero_bits -){ - if (matrix.width() > image.width()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); - } - if (matrix.height() > image.height()){ - dump_image( - global_logger_tagged(), ProgramInfo(), - "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), - image - ); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); - } - size_t bytes_per_row = image.bytes_per_row(); - Kernels::filter_by_mask( - matrix, - (uint32_t*)((char*)image.data() + bytes_per_row * offset_y + offset_x * sizeof(uint32_t)), - bytes_per_row, - (uint32_t)replacement_color, replace_zero_bits - ); -} - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_min( - const ImageViewRGB32& image, - uint8_t min_red, - uint8_t min_green, - uint8_t min_blue -){ - return compress_rgb32_to_binary_range( - image, - 255, 255, - min_red, 255, - min_green, 255, - min_blue, 255 - ); -} -PackedBinaryMatrix compress_rgb32_to_binary_max( - const ImageViewRGB32& image, - uint8_t max_red, - uint8_t max_green, - uint8_t max_blue -){ - return compress_rgb32_to_binary_range( - image, - 255, 255, - 0, max_red, - 0, max_green, - 0, max_blue - ); -} -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -){ - return compress_rgb32_to_binary_range( - image, - 255, 255, - min_red, max_red, - min_green, max_green, - min_blue, max_blue - ); -} -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_alpha, uint8_t max_alpha, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -){ - PackedBinaryMatrix ret(image.width(), image.height()); - Kernels::compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), ret, - ((uint32_t)min_alpha << 24) | ((uint32_t)min_red << 16) | ((uint32_t)min_green << 8) | (uint32_t)min_blue, - ((uint32_t)max_alpha << 24) | ((uint32_t)max_red << 16) | ((uint32_t)max_green << 8) | (uint32_t)max_blue - ); - return ret; -} -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs -){ - PackedBinaryMatrix ret(image.width(), image.height()); - Kernels::compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), - ret, mins, maxs - ); - return ret; -} -std::vector compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - const std::vector>& filters -){ - std::vector ret; - FixedLimitVector vec(filters.size()); - for (size_t c = 0; c < filters.size(); c++){ - ret.emplace_back(image.width(), image.height()); - vec.emplace_back(ret[c], filters[c].first, filters[c].second); - } - compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), - vec.data(), vec.size() - ); - return ret; -} - - - -PackedBinaryMatrix compress_rgb32_to_binary_multirange( - const ImageViewRGB32& image, - const std::vector>& filters -){ - if (filters.empty()){ - PackedBinaryMatrix ret(image.width(), image.height()); - ret.set_zero(); - return ret; - } - PackedBinaryMatrix ret = compress_rgb32_to_binary_range(image, filters[0].first, filters[0].second); - for (size_t c = 1; c < filters.size(); c++){ - ret |= compress_rgb32_to_binary_range(image, filters[c].first, filters[c].second); - } - return ret; -} - - - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_euclidean( - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance -){ - PackedBinaryMatrix ret(image.width(), image.height()); - Kernels::compress_rgb32_to_binary_euclidean( - image.data(), image.bytes_per_row(), - ret, expected, max_euclidean_distance - ); - return ret; -} - - - - - - - - - - -} +/* Binary Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "BinaryImage_FilterRgb32.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, + Color replacement_color, + bool replace_zero_bits +){ + if (matrix.width() > image.width()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); + } + if (matrix.height() > image.height()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); + } + Kernels::filter_by_mask( + matrix, + image.data(), image.bytes_per_row(), + (uint32_t)replacement_color, replace_zero_bits + ); +} +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, size_t offset_x, size_t offset_y, + Color replacement_color, + bool replace_zero_bits +){ + if (matrix.width() > image.width()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image width is too small."); + } + if (matrix.height() > image.height()){ + dump_image( + global_logger_tagged(), ProgramInfo(), + "filter_by_mask-width-matrix" + std::to_string(matrix.width()) + "x" + std::to_string(matrix.height()), + image + ); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image height is too small."); + } + size_t bytes_per_row = image.bytes_per_row(); + Kernels::filter_by_mask( + matrix, + (uint32_t*)((char*)image.data() + bytes_per_row * offset_y + offset_x * sizeof(uint32_t)), + bytes_per_row, + (uint32_t)replacement_color, replace_zero_bits + ); +} + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_min( + const ImageViewRGB32& image, + uint8_t min_red, + uint8_t min_green, + uint8_t min_blue +){ + return compress_rgb32_to_binary_range( + image, + 255, 255, + min_red, 255, + min_green, 255, + min_blue, 255 + ); +} +PackedBinaryMatrix compress_rgb32_to_binary_max( + const ImageViewRGB32& image, + uint8_t max_red, + uint8_t max_green, + uint8_t max_blue +){ + return compress_rgb32_to_binary_range( + image, + 255, 255, + 0, max_red, + 0, max_green, + 0, max_blue + ); +} +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +){ + return compress_rgb32_to_binary_range( + image, + 255, 255, + min_red, max_red, + min_green, max_green, + min_blue, max_blue + ); +} +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_alpha, uint8_t max_alpha, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +){ + PackedBinaryMatrix ret(image.width(), image.height()); + Kernels::compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), ret, + ((uint32_t)min_alpha << 24) | ((uint32_t)min_red << 16) | ((uint32_t)min_green << 8) | (uint32_t)min_blue, + ((uint32_t)max_alpha << 24) | ((uint32_t)max_red << 16) | ((uint32_t)max_green << 8) | (uint32_t)max_blue + ); + return ret; +} +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs +){ + PackedBinaryMatrix ret(image.width(), image.height()); + Kernels::compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), + ret, mins, maxs + ); + return ret; +} +std::vector compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + const std::vector>& filters +){ + std::vector ret; + FixedLimitVector vec(filters.size()); + for (size_t c = 0; c < filters.size(); c++){ + ret.emplace_back(image.width(), image.height()); + vec.emplace_back(ret[c], filters[c].first, filters[c].second); + } + compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), + vec.data(), vec.size() + ); + return ret; +} + + + +PackedBinaryMatrix compress_rgb32_to_binary_multirange( + const ImageViewRGB32& image, + const std::vector>& filters +){ + if (filters.empty()){ + PackedBinaryMatrix ret(image.width(), image.height()); + ret.set_zero(); + return ret; + } + PackedBinaryMatrix ret = compress_rgb32_to_binary_range(image, filters[0].first, filters[0].second); + for (size_t c = 1; c < filters.size(); c++){ + ret |= compress_rgb32_to_binary_range(image, filters[c].first, filters[c].second); + } + return ret; +} + + + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_euclidean( + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance +){ + PackedBinaryMatrix ret(image.width(), image.height()); + Kernels::compress_rgb32_to_binary_euclidean( + image.data(), image.bytes_per_row(), + ret, expected, max_euclidean_distance + ); + return ret; +} + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h index 79cb8873a9..4e0f67f80e 100644 --- a/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h +++ b/SerialPrograms/Source/CommonTools/Images/BinaryImage_FilterRgb32.h @@ -1,110 +1,110 @@ -/* Binary Image Filter RGB32 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H -#define PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" -#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" - -namespace PokemonAutomation{ - - -// Selectively replace pixels in `image` with the replacement color -// according to the respective bits in the binary matrix. -// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. -// Else, replace those with the one bits. -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, - Color replacement_color, - bool replace_zero_bits -); -// Selectively replace pixels in an area of the `image` with the replacement color -// according to the respective bits in the binary matrix. -// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. -// Else, replace those with the one bits. -// The image area starts at (offset_x, offset_y) with the same (width, height) as -// the matrix. -void filter_by_mask( - const PackedBinaryMatrix& matrix, - ImageRGB32& image, size_t offset_x, size_t offset_y, - Color replacement_color, - bool replace_zero_bits -); - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_min( - const ImageViewRGB32& image, - uint8_t min_red, - uint8_t min_green, - uint8_t min_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_max( - const ImageViewRGB32& image, - uint8_t max_red, - uint8_t max_green, - uint8_t max_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint8_t min_alpha, uint8_t max_alpha, - uint8_t min_red, uint8_t max_red, - uint8_t min_green, uint8_t max_green, - uint8_t min_blue, uint8_t max_blue -); -PackedBinaryMatrix compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs -); - - - -// Run multiple filters at once. This is more memory efficient than making -// multiple calls to one filter at a time. -// Pixels Within filter color ranges are marked as 1 in the corresponding binary matrices, -// while those output of range are 0. -std::vector compress_rgb32_to_binary_range( - const ImageViewRGB32& image, - const std::vector>& filters -); - - - -// Run multiple filters and OR them all together. (experimental) -PackedBinaryMatrix compress_rgb32_to_binary_multirange( - const ImageViewRGB32& image, - const std::vector>& filters -); - - - - - -PackedBinaryMatrix compress_rgb32_to_binary_euclidean( - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance -); - - - - -} -#endif +/* Binary Image Filter RGB32 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H +#define PokemonAutomation_CommonTools_BinaryImage_FilterRgb32_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" +#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" + +namespace PokemonAutomation{ + + +// Selectively replace pixels in `image` with the replacement color +// according to the respective bits in the binary matrix. +// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. +// Else, replace those with the one bits. +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, + Color replacement_color, + bool replace_zero_bits +); +// Selectively replace pixels in an area of the `image` with the replacement color +// according to the respective bits in the binary matrix. +// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. +// Else, replace those with the one bits. +// The image area starts at (offset_x, offset_y) with the same (width, height) as +// the matrix. +void filter_by_mask( + const PackedBinaryMatrix& matrix, + ImageRGB32& image, size_t offset_x, size_t offset_y, + Color replacement_color, + bool replace_zero_bits +); + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_min( + const ImageViewRGB32& image, + uint8_t min_red, + uint8_t min_green, + uint8_t min_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_max( + const ImageViewRGB32& image, + uint8_t max_red, + uint8_t max_green, + uint8_t max_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint8_t min_alpha, uint8_t max_alpha, + uint8_t min_red, uint8_t max_red, + uint8_t min_green, uint8_t max_green, + uint8_t min_blue, uint8_t max_blue +); +PackedBinaryMatrix compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs +); + + + +// Run multiple filters at once. This is more memory efficient than making +// multiple calls to one filter at a time. +// Pixels Within filter color ranges are marked as 1 in the corresponding binary matrices, +// while those output of range are 0. +std::vector compress_rgb32_to_binary_range( + const ImageViewRGB32& image, + const std::vector>& filters +); + + + +// Run multiple filters and OR them all together. (experimental) +PackedBinaryMatrix compress_rgb32_to_binary_multirange( + const ImageViewRGB32& image, + const std::vector>& filters +); + + + + + +PackedBinaryMatrix compress_rgb32_to_binary_euclidean( + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance +); + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp b/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp index b9ace1f81a..bd27390d14 100644 --- a/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ColorClustering.cpp @@ -1,183 +1,183 @@ -/* Color Clustering - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "ColorClustering.h" - -#include -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -void PixelEuclideanStatAccumulator::clear(){ - m_count = 0; - m_sum_x = 0; - m_sum_y = 0; - m_sum_z = 0; - m_sqr_x = 0; - m_sqr_y = 0; - m_sqr_z = 0; -} -void PixelEuclideanStatAccumulator::operator+=(FloatPixel pixel){ - m_count++; - m_sum_x += pixel.r; - m_sum_y += pixel.g; - m_sum_z += pixel.b; - m_sqr_x += pixel.r * pixel.r; - m_sqr_y += pixel.g * pixel.g; - m_sqr_z += pixel.b * pixel.b; -} -uint64_t PixelEuclideanStatAccumulator::count() const{ - return m_count; -} -FloatPixel PixelEuclideanStatAccumulator::center() const{ - return FloatPixel(m_sum_x / m_count, m_sum_y / m_count, m_sum_z / m_count); -} -double PixelEuclideanStatAccumulator::deviation() const{ - if (m_count < 1){ - return 0; - } - double variance = m_sqr_x + m_sqr_y + m_sqr_z; - variance -= (m_sum_x*m_sum_x + m_sum_y*m_sum_y + m_sum_z*m_sum_z) / m_count; - return std::sqrt(variance / (m_count - 1)); -} - - -double cluster_fit_2( - const ImageViewRGB32& image, - Color color0, PixelEuclideanStatAccumulator& cluster0, - Color color1, PixelEuclideanStatAccumulator& cluster1 -){ - size_t width = image.width(); - size_t height = image.height(); - - FloatPixel f0(color0); - FloatPixel f1(color1); - - PixelEuclideanStatAccumulator stats0; - PixelEuclideanStatAccumulator stats1; - -// image.save("points.png"); -// std::fstream ss("points.txt", std::fstream::out); - - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - Color pixel(image.pixel(c, r)); -// ss << "{" << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << "}," << endl; - FloatPixel p0 = f0 - pixel; - FloatPixel p1 = f1 - pixel; - double distance0 = (p0 * p0).sum(); - double distance1 = (p1 * p1).sum(); - if (distance0 < distance1){ - stats0 += pixel; -// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance0) << endl; - }else{ - stats1 += pixel; -// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance1) << endl; -// cout << "stats = " << stats1.center() << endl; - } - } - } - -#if 0 - cout << "color0 = " << stats0.count() << ": " << stats0.center() << ", " << stats0.deviation() << endl; - cout << "color1 = " << stats1.count() << ": " << stats1.center() << ", " << stats1.deviation() << endl; -#endif - - cluster0 = stats0; - cluster1 = stats1; - -// cout << "stats = " << stats1.center() << endl; - - return (stats0.deviation() * stats0.count() + stats1.deviation() * stats1.count()) / (stats0.count() + stats1.count()); -} - -bool cluster_fit_2( - const ImageViewRGB32& image, - Color color0, double ratio0, - Color color1, double ratio1, - double ratio_threshold, - double deviation_threshold, - double distance_threshold -){ - const size_t NUM_CLUSTERS = 2; - - if (!image){ - return false; - } - size_t total = image.width() * image.height(); - - FloatPixel center_desired[NUM_CLUSTERS] = {color0, color1}; - double count_ratio_desired[NUM_CLUSTERS] = {ratio0, ratio1}; - - PixelEuclideanStatAccumulator cluster[NUM_CLUSTERS]; - cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); - color0 = cluster[0].center().round(); - color1 = cluster[1].center().round(); - double deviation = cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); -// cout << "deviation = " << deviation << ", threshold = " << deviation_threshold << endl; -// cout << cluster[0].count() << " / " << cluster[1].count() << endl; - if (deviation > deviation_threshold){ -// cout << "deviation out" << endl; -// image.save("test.png"); - return false; - } - - FloatPixel center_actual[NUM_CLUSTERS]; - double count_ratio_actual[NUM_CLUSTERS]; - - double ratio_sum = 0; - for (size_t c = 0; c < NUM_CLUSTERS; c++){ - ratio_sum += count_ratio_desired[c]; - center_actual[c] = cluster[c].center(); - } -// cout << "---------------" << endl; - for (size_t c = 0; c < NUM_CLUSTERS; c++){ -// cout << cluster[c].count() << ": " << cluster[c].center() << ", " << cluster[c].deviation() << endl; - - count_ratio_desired[c] /= ratio_sum; - count_ratio_actual[c] = (double)cluster[c].count() / total; - double diff = std::abs(count_ratio_actual[c] - count_ratio_desired[c]); -// cout << "Color Ratio Diff: " << diff << endl; - if (diff > ratio_threshold){ -// cout << "Color Ratio Diff is Too Large: " << diff << endl; -// cout << "desired = " << count_ratio_desired[c] << endl; -// cout << "actual = " << count_ratio_actual[c] << endl; - return false; - } - - if (center_desired[c].sum() < 50){ -// cout << "Black" << endl; - double distance = euclidean_distance(center_desired[c], center_actual[c]) * count_ratio_desired[c]; - if (distance > 40){ -// cout << "Black Distance is Too Large: " << distance << endl; - return false; - } - }else{ -// cout << "Not Black" << endl; - FloatPixel ratio_desired = center_desired[c] / center_desired[c].sum(); - FloatPixel ratio_actual = center_actual[c] / center_actual[c].sum(); - double distance = euclidean_distance(ratio_desired, ratio_actual); -// cout << ratio_desired << " / " << ratio_actual << " = " << distance << endl; - if (distance > distance_threshold){ -// cout << distance << " > " << distance_threshold << endl; - return false; - } - } - } - -// cout << "match" << endl; - return true; -} - - - - -} - +/* Color Clustering + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "ColorClustering.h" + +#include +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +void PixelEuclideanStatAccumulator::clear(){ + m_count = 0; + m_sum_x = 0; + m_sum_y = 0; + m_sum_z = 0; + m_sqr_x = 0; + m_sqr_y = 0; + m_sqr_z = 0; +} +void PixelEuclideanStatAccumulator::operator+=(FloatPixel pixel){ + m_count++; + m_sum_x += pixel.r; + m_sum_y += pixel.g; + m_sum_z += pixel.b; + m_sqr_x += pixel.r * pixel.r; + m_sqr_y += pixel.g * pixel.g; + m_sqr_z += pixel.b * pixel.b; +} +uint64_t PixelEuclideanStatAccumulator::count() const{ + return m_count; +} +FloatPixel PixelEuclideanStatAccumulator::center() const{ + return FloatPixel(m_sum_x / m_count, m_sum_y / m_count, m_sum_z / m_count); +} +double PixelEuclideanStatAccumulator::deviation() const{ + if (m_count < 1){ + return 0; + } + double variance = m_sqr_x + m_sqr_y + m_sqr_z; + variance -= (m_sum_x*m_sum_x + m_sum_y*m_sum_y + m_sum_z*m_sum_z) / m_count; + return std::sqrt(variance / (m_count - 1)); +} + + +double cluster_fit_2( + const ImageViewRGB32& image, + Color color0, PixelEuclideanStatAccumulator& cluster0, + Color color1, PixelEuclideanStatAccumulator& cluster1 +){ + size_t width = image.width(); + size_t height = image.height(); + + FloatPixel f0(color0); + FloatPixel f1(color1); + + PixelEuclideanStatAccumulator stats0; + PixelEuclideanStatAccumulator stats1; + +// image.save("points.png"); +// std::fstream ss("points.txt", std::fstream::out); + + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + Color pixel(image.pixel(c, r)); +// ss << "{" << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << "}," << endl; + FloatPixel p0 = f0 - pixel; + FloatPixel p1 = f1 - pixel; + double distance0 = (p0 * p0).sum(); + double distance1 = (p1 * p1).sum(); + if (distance0 < distance1){ + stats0 += pixel; +// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance0) << endl; + }else{ + stats1 += pixel; +// cout << (int)pixel.red() << ", " << (int)pixel.green() << ", " << (int)pixel.blue() << ": " << std::sqrt(distance1) << endl; +// cout << "stats = " << stats1.center() << endl; + } + } + } + +#if 0 + cout << "color0 = " << stats0.count() << ": " << stats0.center() << ", " << stats0.deviation() << endl; + cout << "color1 = " << stats1.count() << ": " << stats1.center() << ", " << stats1.deviation() << endl; +#endif + + cluster0 = stats0; + cluster1 = stats1; + +// cout << "stats = " << stats1.center() << endl; + + return (stats0.deviation() * stats0.count() + stats1.deviation() * stats1.count()) / (stats0.count() + stats1.count()); +} + +bool cluster_fit_2( + const ImageViewRGB32& image, + Color color0, double ratio0, + Color color1, double ratio1, + double ratio_threshold, + double deviation_threshold, + double distance_threshold +){ + const size_t NUM_CLUSTERS = 2; + + if (!image){ + return false; + } + size_t total = image.width() * image.height(); + + FloatPixel center_desired[NUM_CLUSTERS] = {color0, color1}; + double count_ratio_desired[NUM_CLUSTERS] = {ratio0, ratio1}; + + PixelEuclideanStatAccumulator cluster[NUM_CLUSTERS]; + cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); + color0 = cluster[0].center().round(); + color1 = cluster[1].center().round(); + double deviation = cluster_fit_2(image, color0, cluster[0], color1, cluster[1]); +// cout << "deviation = " << deviation << ", threshold = " << deviation_threshold << endl; +// cout << cluster[0].count() << " / " << cluster[1].count() << endl; + if (deviation > deviation_threshold){ +// cout << "deviation out" << endl; +// image.save("test.png"); + return false; + } + + FloatPixel center_actual[NUM_CLUSTERS]; + double count_ratio_actual[NUM_CLUSTERS]; + + double ratio_sum = 0; + for (size_t c = 0; c < NUM_CLUSTERS; c++){ + ratio_sum += count_ratio_desired[c]; + center_actual[c] = cluster[c].center(); + } +// cout << "---------------" << endl; + for (size_t c = 0; c < NUM_CLUSTERS; c++){ +// cout << cluster[c].count() << ": " << cluster[c].center() << ", " << cluster[c].deviation() << endl; + + count_ratio_desired[c] /= ratio_sum; + count_ratio_actual[c] = (double)cluster[c].count() / total; + double diff = std::abs(count_ratio_actual[c] - count_ratio_desired[c]); +// cout << "Color Ratio Diff: " << diff << endl; + if (diff > ratio_threshold){ +// cout << "Color Ratio Diff is Too Large: " << diff << endl; +// cout << "desired = " << count_ratio_desired[c] << endl; +// cout << "actual = " << count_ratio_actual[c] << endl; + return false; + } + + if (center_desired[c].sum() < 50){ +// cout << "Black" << endl; + double distance = euclidean_distance(center_desired[c], center_actual[c]) * count_ratio_desired[c]; + if (distance > 40){ +// cout << "Black Distance is Too Large: " << distance << endl; + return false; + } + }else{ +// cout << "Not Black" << endl; + FloatPixel ratio_desired = center_desired[c] / center_desired[c].sum(); + FloatPixel ratio_actual = center_actual[c] / center_actual[c].sum(); + double distance = euclidean_distance(ratio_desired, ratio_actual); +// cout << ratio_desired << " / " << ratio_actual << " = " << distance << endl; + if (distance > distance_threshold){ +// cout << distance << " > " << distance_threshold << endl; + return false; + } + } + } + +// cout << "match" << endl; + return true; +} + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Images/ColorClustering.h b/SerialPrograms/Source/CommonTools/Images/ColorClustering.h index 4035dce92c..54d49d062a 100644 --- a/SerialPrograms/Source/CommonTools/Images/ColorClustering.h +++ b/SerialPrograms/Source/CommonTools/Images/ColorClustering.h @@ -1,52 +1,52 @@ -/* Color Clustering - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ColorClustering_H -#define PokemonAutomation_CommonTools_ColorClustering_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/FloatPixel.h" - -namespace PokemonAutomation{ - - -class PixelEuclideanStatAccumulator{ -public: - void clear(); - void operator+=(FloatPixel pixel); - - uint64_t count() const; - FloatPixel center() const; - double deviation() const; - -private: - uint64_t m_count = 0; - double m_sum_x = 0; - double m_sum_y = 0; - double m_sum_z = 0; - double m_sqr_x = 0; - double m_sqr_y = 0; - double m_sqr_z = 0; -}; - -double cluster_fit_2( - const ImageViewRGB32& image, - Color color0, PixelEuclideanStatAccumulator& cluster0, - Color color1, PixelEuclideanStatAccumulator& cluster1 -); - -bool cluster_fit_2( - const ImageViewRGB32& image, - Color color0, double ratio0, - Color color1, double ratio1, - double ratio_threshold = 0.2, - double deviation_threshold = 50, - double distance_threshold = 0.25 -); - - -} -#endif +/* Color Clustering + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ColorClustering_H +#define PokemonAutomation_CommonTools_ColorClustering_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/FloatPixel.h" + +namespace PokemonAutomation{ + + +class PixelEuclideanStatAccumulator{ +public: + void clear(); + void operator+=(FloatPixel pixel); + + uint64_t count() const; + FloatPixel center() const; + double deviation() const; + +private: + uint64_t m_count = 0; + double m_sum_x = 0; + double m_sum_y = 0; + double m_sum_z = 0; + double m_sqr_x = 0; + double m_sqr_y = 0; + double m_sqr_z = 0; +}; + +double cluster_fit_2( + const ImageViewRGB32& image, + Color color0, PixelEuclideanStatAccumulator& cluster0, + Color color1, PixelEuclideanStatAccumulator& cluster1 +); + +bool cluster_fit_2( + const ImageViewRGB32& image, + Color color0, double ratio0, + Color color1, double ratio1, + double ratio_threshold = 0.2, + double deviation_threshold = 50, + double distance_threshold = 0.25 +); + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h b/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h index 8e56981674..83e3085372 100644 --- a/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h +++ b/SerialPrograms/Source/CommonTools/Images/DistanceToLine.h @@ -1,58 +1,58 @@ -/* Distance to Line - * - * From: https://github.com/PokemonAutomation/ - * - * - * Return a set of connected clusters. - * - */ - -#ifndef PokemonAutomation_CommonTools_DistanceToLine_H -#define PokemonAutomation_CommonTools_DistanceToLine_H - -#include - -namespace PokemonAutomation{ - - -class DistanceToLine{ -public: - DistanceToLine( - ptrdiff_t vertex0_x, ptrdiff_t vertex0_y, - ptrdiff_t vertex1_x, ptrdiff_t vertex1_y - ) - : m_vertical(vertex0_x == vertex1_x) - , m_vertex0_x(vertex0_x) - , m_vertex0_y(vertex0_y) -// , m_vertex1_x(vertex1_x) -// , m_vertex1_y(vertex1_y) - , m_slope((double)(vertex1_y - vertex0_y) / (vertex1_x - vertex0_x)) - , m_inverse(1 / (m_slope*m_slope + 1)) - {} - - double distance_squared(ptrdiff_t x, ptrdiff_t y) const{ - if (m_vertical){ - ptrdiff_t distance = x - m_vertex0_x; - return (double)(distance * distance); - } - ptrdiff_t dx = x - m_vertex0_x; - ptrdiff_t dy = y - m_vertex0_y; - double top = m_slope * dx - dy; - double distance_sqr = top * top * m_inverse; - return distance_sqr; - } - -private: - bool m_vertical; - ptrdiff_t m_vertex0_x; - ptrdiff_t m_vertex0_y; -// ptrdiff_t m_vertex1_x; -// ptrdiff_t m_vertex1_y; - double m_slope; - double m_inverse; -}; - - - -} -#endif +/* Distance to Line + * + * From: https://github.com/PokemonAutomation/ + * + * + * Return a set of connected clusters. + * + */ + +#ifndef PokemonAutomation_CommonTools_DistanceToLine_H +#define PokemonAutomation_CommonTools_DistanceToLine_H + +#include + +namespace PokemonAutomation{ + + +class DistanceToLine{ +public: + DistanceToLine( + ptrdiff_t vertex0_x, ptrdiff_t vertex0_y, + ptrdiff_t vertex1_x, ptrdiff_t vertex1_y + ) + : m_vertical(vertex0_x == vertex1_x) + , m_vertex0_x(vertex0_x) + , m_vertex0_y(vertex0_y) +// , m_vertex1_x(vertex1_x) +// , m_vertex1_y(vertex1_y) + , m_slope((double)(vertex1_y - vertex0_y) / (vertex1_x - vertex0_x)) + , m_inverse(1 / (m_slope*m_slope + 1)) + {} + + double distance_squared(ptrdiff_t x, ptrdiff_t y) const{ + if (m_vertical){ + ptrdiff_t distance = x - m_vertex0_x; + return (double)(distance * distance); + } + ptrdiff_t dx = x - m_vertex0_x; + ptrdiff_t dy = y - m_vertex0_y; + double top = m_slope * dx - dy; + double distance_sqr = top * top * m_inverse; + return distance_sqr; + } + +private: + bool m_vertical; + ptrdiff_t m_vertex0_x; + ptrdiff_t m_vertex0_y; +// ptrdiff_t m_vertex1_x; +// ptrdiff_t m_vertex1_y; + double m_slope; + double m_inverse; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp b/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp index 2c0c0033e4..0a201560e6 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageFilter.cpp @@ -1,223 +1,223 @@ -/* Image Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h" -#include "Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h" -#include "Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h" -#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageFilter.h" - -namespace PokemonAutomation{ - - - -ImageRGB32 filter_rgb32_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - mins, maxs - ); - return ret; -} -ImageRGB32 filter_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - pixels_in_range = Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - mins, maxs - ); - return ret; -} -std::vector> filter_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -){ - std::vector> ret(filters.size()); - FixedLimitVector subfilters(filters.size()); - for (size_t c = 0; c < filters.size(); c++){ - ImageRGB32& out = ret[c].first; - out = ImageRGB32(image.width(), image.height()); - subfilters.emplace_back( - out.data(), out.bytes_per_row(), - (uint32_t)filters[c].replacement_color, filters[c].replace_color_within_range, - filters[c].mins, filters[c].maxs - ); - } - Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - subfilters.data(), subfilters.size() - ); - for (size_t c = 0; c < filters.size(); c++){ - ret[c].second = subfilters[c].pixels_in_range; - } - return ret; -} - - - -ImageRGB32 to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - in_range_black, - mins, maxs - ); - return ret; -} -ImageRGB32 to_blackwhite_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - ImageRGB32 ret(image.width(), image.height()); - pixels_in_range = Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - in_range_black, - mins, maxs - ); - return ret; -} -std::vector> to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -){ - std::vector> ret(filters.size()); - FixedLimitVector subfilters(filters.size()); - for (size_t c = 0; c < filters.size(); c++){ - ImageRGB32& out = ret[c].first; - out = ImageRGB32(image.width(), image.height()); - subfilters.emplace_back( - out.data(), out.bytes_per_row(), - filters[c].mins, filters[c].maxs, (uint32_t)filters[c].in_range_black - ); - } - Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - subfilters.data(), subfilters.size() - ); - for (size_t c = 0; c < filters.size(); c++){ - ret[c].second = subfilters[c].pixels_in_range; - } - return ret; -} - - - - - - - - - -ImageRGB32 filter_rgb32_euclidean( - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance, - Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - expected, max_euclidean_distance - ); - return ret; -} -ImageRGB32 filter_rgb32_euclidean( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t expected, double max_euclidean_distance, - Color replace_with, bool replace_color_within_range -){ - ImageRGB32 ret(image.width(), image.height()); - pixels_in_range = Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replace_with, replace_color_within_range, - expected, max_euclidean_distance - ); - return ret; -} - - - - - - - - - -ImageRGB32 filter_rgb32_brightness( - const ImageViewRGB32& image, - Color replacement_color, bool replace_color_within_range, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_rgb32_brightness( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - (uint32_t)replacement_color, replace_color_within_range, - weights, - min_brightness, max_brightness - ); - return ret; -} -ImageRGB32 to_blackwhite_rgb32_brightness( - const ImageViewRGB32& image, - bool in_range_black, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::to_blackwhite_rgb32_brightness( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), - in_range_black, - weights, - min_brightness, max_brightness - ); - return ret; -} - - - -ImageRGB32 filter_green( - const ImageViewRGB32& image, - Color replace_with, - uint8_t rgb_gap -){ - ImageRGB32 ret(image.width(), image.height()); - Kernels::filter_green( - image.data(), image.bytes_per_row(), image.width(), image.height(), - ret.data(), ret.bytes_per_row(), (uint32_t)replace_with, rgb_gap - ); - return ret; -} - - - -} +/* Image Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h" +#include "Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h" +#include "Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h" +#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageFilter.h" + +namespace PokemonAutomation{ + + + +ImageRGB32 filter_rgb32_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + mins, maxs + ); + return ret; +} +ImageRGB32 filter_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + pixels_in_range = Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + mins, maxs + ); + return ret; +} +std::vector> filter_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +){ + std::vector> ret(filters.size()); + FixedLimitVector subfilters(filters.size()); + for (size_t c = 0; c < filters.size(); c++){ + ImageRGB32& out = ret[c].first; + out = ImageRGB32(image.width(), image.height()); + subfilters.emplace_back( + out.data(), out.bytes_per_row(), + (uint32_t)filters[c].replacement_color, filters[c].replace_color_within_range, + filters[c].mins, filters[c].maxs + ); + } + Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + subfilters.data(), subfilters.size() + ); + for (size_t c = 0; c < filters.size(); c++){ + ret[c].second = subfilters[c].pixels_in_range; + } + return ret; +} + + + +ImageRGB32 to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + in_range_black, + mins, maxs + ); + return ret; +} +ImageRGB32 to_blackwhite_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + ImageRGB32 ret(image.width(), image.height()); + pixels_in_range = Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + in_range_black, + mins, maxs + ); + return ret; +} +std::vector> to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +){ + std::vector> ret(filters.size()); + FixedLimitVector subfilters(filters.size()); + for (size_t c = 0; c < filters.size(); c++){ + ImageRGB32& out = ret[c].first; + out = ImageRGB32(image.width(), image.height()); + subfilters.emplace_back( + out.data(), out.bytes_per_row(), + filters[c].mins, filters[c].maxs, (uint32_t)filters[c].in_range_black + ); + } + Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + subfilters.data(), subfilters.size() + ); + for (size_t c = 0; c < filters.size(); c++){ + ret[c].second = subfilters[c].pixels_in_range; + } + return ret; +} + + + + + + + + + +ImageRGB32 filter_rgb32_euclidean( + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance, + Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + expected, max_euclidean_distance + ); + return ret; +} +ImageRGB32 filter_rgb32_euclidean( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t expected, double max_euclidean_distance, + Color replace_with, bool replace_color_within_range +){ + ImageRGB32 ret(image.width(), image.height()); + pixels_in_range = Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replace_with, replace_color_within_range, + expected, max_euclidean_distance + ); + return ret; +} + + + + + + + + + +ImageRGB32 filter_rgb32_brightness( + const ImageViewRGB32& image, + Color replacement_color, bool replace_color_within_range, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_rgb32_brightness( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + (uint32_t)replacement_color, replace_color_within_range, + weights, + min_brightness, max_brightness + ); + return ret; +} +ImageRGB32 to_blackwhite_rgb32_brightness( + const ImageViewRGB32& image, + bool in_range_black, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::to_blackwhite_rgb32_brightness( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), + in_range_black, + weights, + min_brightness, max_brightness + ); + return ret; +} + + + +ImageRGB32 filter_green( + const ImageViewRGB32& image, + Color replace_with, + uint8_t rgb_gap +){ + ImageRGB32 ret(image.width(), image.height()); + Kernels::filter_green( + image.data(), image.bytes_per_row(), image.width(), image.height(), + ret.data(), ret.bytes_per_row(), (uint32_t)replace_with, rgb_gap + ); + return ret; +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/ImageFilter.h b/SerialPrograms/Source/CommonTools/Images/ImageFilter.h index 5536dbac72..149dbebe9c 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageFilter.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageFilter.h @@ -1,166 +1,166 @@ -/* Image Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageFilter_H -#define PokemonAutomation_CommonTools_ImageFilter_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; - - -// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color -// `replacement_color`. -ImageRGB32 filter_rgb32_range( - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, - Color replacement_color, bool replace_color_within_range -); -// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color -// `replacement_color`. -// Returns the # of pixels inside the range [mins, maxs] as `pixels_in_range` -ImageRGB32 filter_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t mins, uint32_t maxs, - Color replacement_color, bool replace_color_within_range -); -// Run multiple filters at once. This is more memory efficient than making -// multiple calls to one filter at a time. -// For each filter: -// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color -// `replacement_color`. -// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. -struct FilterRgb32Range{ - Color replacement_color; - bool replace_color_within_range; - uint32_t mins; - uint32_t maxs; -}; -std::vector> filter_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -); - - - -// Convert the image to black and white. -// Inside [mins, maxs] is white, otherwise it's black. -// Set "in_range_black" to true to invert the colors. -// Both white and black colors have alpha=255. -ImageRGB32 to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -// Convert the image to black and white. -// Inside [mins, maxs] is white, otherwise it's black. -// Set "in_range_black" to true to invert the colors. -// Both white and black colors have alpha=255. -// Returns the # of pixels inside the distance as `pixels_in_range`. -ImageRGB32 to_blackwhite_rgb32_range( - size_t& pixels_in_range, - const ImageViewRGB32& image, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -// Run multiple filters at once. This is more memory efficient than making -// multiple calls to one filter at a time. -// For each filter: -// If `in_range_black` is true, replace the color range [mins, maxs] with color black while the rest white. -// If `in_range_black` is false, replace the color range [mins, maxs] with color white while the rest black. -// Both white and black colors have alpha=255. -// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. -struct BlackWhiteRgb32Range{ - bool in_range_black; - uint32_t mins; - uint32_t maxs; -}; -std::vector> to_blackwhite_rgb32_range( - const ImageViewRGB32& image, - const std::vector& filters -); - - - - - - - - - -// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the -// `expected_color` with `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. -ImageRGB32 filter_rgb32_euclidean( - const ImageViewRGB32& image, - uint32_t expected_color, double max_euclidean_distance, - Color replacement_color, bool replace_color_within_range -); -// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the -// `expected_color` with `replacement_color`. -// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. -// Returns the # of pixels inside the distance as `pixels_in_range`. -// Note: the alpha channel of `image` and `expected_color` are ignored during computation. -ImageRGB32 filter_rgb32_euclidean( - size_t& pixels_in_range, - const ImageViewRGB32& image, - uint32_t expected_color, double max_euclidean_distance, - Color replacement_color, bool replace_color_within_range -); - - - - - - - - -// Similar to "filter_rgb32_range()". But instead of checking if each of -// the RGB components are within a range, we check if the dot product of the -// components and a set of weights is within a range. By selecting the weights, -// you can pick which components to check the brightness of. -ImageRGB32 filter_rgb32_brightness( - const ImageViewRGB32& image, - Color replacement_color, bool replace_color_within_range, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -// Similar to "to_blackwhite_rgb32_range()". But instead of checking if each of -// the RGB components are within a range, we check if the dot product of the -// components and a set of weights is within a range. By selecting the weights, -// you can pick which components to check the brightness of. -ImageRGB32 to_blackwhite_rgb32_brightness( - const ImageViewRGB32& image, - bool in_range_black, - Kernels::Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); - - - - -// keep all pixels where green is the dominant RGB value. otherwise, replace the pixel with `replace_with` -// `rgb_gap` is the amount that green has to exceed the red or blue value, in order to keep the pixel. -ImageRGB32 filter_green( - const ImageViewRGB32& image, - Color replace_with, - uint8_t rgb_gap = 0 -); - - - -} -#endif +/* Image Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageFilter_H +#define PokemonAutomation_CommonTools_ImageFilter_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; + + +// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color +// `replacement_color`. +ImageRGB32 filter_rgb32_range( + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, + Color replacement_color, bool replace_color_within_range +); +// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color +// `replacement_color`. +// Returns the # of pixels inside the range [mins, maxs] as `pixels_in_range` +ImageRGB32 filter_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t mins, uint32_t maxs, + Color replacement_color, bool replace_color_within_range +); +// Run multiple filters at once. This is more memory efficient than making +// multiple calls to one filter at a time. +// For each filter: +// If `replace_color_within_range` is true, replace the color range [mins, maxs] with the color `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the range [mins, maxs] with the color +// `replacement_color`. +// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. +struct FilterRgb32Range{ + Color replacement_color; + bool replace_color_within_range; + uint32_t mins; + uint32_t maxs; +}; +std::vector> filter_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +); + + + +// Convert the image to black and white. +// Inside [mins, maxs] is white, otherwise it's black. +// Set "in_range_black" to true to invert the colors. +// Both white and black colors have alpha=255. +ImageRGB32 to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +// Convert the image to black and white. +// Inside [mins, maxs] is white, otherwise it's black. +// Set "in_range_black" to true to invert the colors. +// Both white and black colors have alpha=255. +// Returns the # of pixels inside the distance as `pixels_in_range`. +ImageRGB32 to_blackwhite_rgb32_range( + size_t& pixels_in_range, + const ImageViewRGB32& image, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +// Run multiple filters at once. This is more memory efficient than making +// multiple calls to one filter at a time. +// For each filter: +// If `in_range_black` is true, replace the color range [mins, maxs] with color black while the rest white. +// If `in_range_black` is false, replace the color range [mins, maxs] with color white while the rest black. +// Both white and black colors have alpha=255. +// For each filter, return the filtered image and the # of pixels inside the [mins, maxs] range of the filter. +struct BlackWhiteRgb32Range{ + bool in_range_black; + uint32_t mins; + uint32_t maxs; +}; +std::vector> to_blackwhite_rgb32_range( + const ImageViewRGB32& image, + const std::vector& filters +); + + + + + + + + + +// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the +// `expected_color` with `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. +ImageRGB32 filter_rgb32_euclidean( + const ImageViewRGB32& image, + uint32_t expected_color, double max_euclidean_distance, + Color replacement_color, bool replace_color_within_range +); +// If `replace_color_within_range` is true, replace the colors within (<=) `max_euclidean_distance` of the +// `expected_color` with `replacement_color`. +// If `replace_color_within_range` is false, replace the color outside of the distance with the color `replacement_color`. +// Returns the # of pixels inside the distance as `pixels_in_range`. +// Note: the alpha channel of `image` and `expected_color` are ignored during computation. +ImageRGB32 filter_rgb32_euclidean( + size_t& pixels_in_range, + const ImageViewRGB32& image, + uint32_t expected_color, double max_euclidean_distance, + Color replacement_color, bool replace_color_within_range +); + + + + + + + + +// Similar to "filter_rgb32_range()". But instead of checking if each of +// the RGB components are within a range, we check if the dot product of the +// components and a set of weights is within a range. By selecting the weights, +// you can pick which components to check the brightness of. +ImageRGB32 filter_rgb32_brightness( + const ImageViewRGB32& image, + Color replacement_color, bool replace_color_within_range, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +// Similar to "to_blackwhite_rgb32_range()". But instead of checking if each of +// the RGB components are within a range, we check if the dot product of the +// components and a set of weights is within a range. By selecting the weights, +// you can pick which components to check the brightness of. +ImageRGB32 to_blackwhite_rgb32_brightness( + const ImageViewRGB32& image, + bool in_range_black, + Kernels::Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); + + + + +// keep all pixels where green is the dominant RGB value. otherwise, replace the pixel with `replace_with` +// `rgb_gap` is the amount that green has to exceed the red or blue value, in order to keep the pixel. +ImageRGB32 filter_green( + const ImageViewRGB32& image, + Color replace_with, + uint8_t rgb_gap = 0 +); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp b/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp index 84d3685ba2..b8d3be835b 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageGradient.cpp @@ -1,160 +1,160 @@ -/* Image Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "ImageGradient.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top){ - // Gradient on each color channel at each pixel in one row - std::vector gradients(image.width() * 3, 0); - // Whether a color channel is zero for each pixel in one row - std::vector is_zero(image.width() * 3, false); - - if (image.height() == 0 || image.width() == 0){ - return 0; - } - - size_t num_rows = image.height() - 1; - for(size_t row_index = 0; row_index < num_rows; row_index++){ - for(size_t x = 0; x < image.width(); x++){ - uint32_t p_above = image.pixel(x, row_index); - uint32_t p_below = image.pixel(x, row_index+1); - - // If both two pixels are black, then we skip this case - if (p_above == 0 && p_below == 0){ - continue; - } - - // c1 may be darker, while c2 is not yet covered by the dark translucent region - Color c1(dark_top ? p_above : p_below); - Color c2(dark_top ? p_below : p_above); - if (c1.red() == 0){ - is_zero[3*x] = true; - } - if (c1.green() == 0){ - is_zero[3*x+1] = true; - } - if (c1.blue() == 0){ - is_zero[3*x+2] = true; - } - gradients[3*x] = std::max(gradients[3*x], int16_t((int)c2.red() - (int) c1.red())); - gradients[3*x+1] = std::max(gradients[3*x+1], int16_t((int)c2.green() - (int) c1.green())); - gradients[3*x+2] = std::max(gradients[3*x+2], int16_t((int)c2.blue() - (int) c1.blue())); - - - } - } - - int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; - - size_t num_border_pixels = 0; - for(size_t x = 0; x < image.width(); x++){ - bool has_non_border_channel = false; - for(int c = 0; c < 3; c++){ - if (is_zero[3*x+c] == false && gradients[3*x+c] < thres_c[c]){ - has_non_border_channel = true; - break; - } - } - - num_border_pixels += !has_non_border_channel; - } - - // int16_t min_color[3] = {255, 255, 255}; - // for(size_t i = 0; i < image.width(); i++){ - // if (is_zero[3*i] == false || is_zero[3*i+1] == false || is_zero[3*i+2] == false){ - // cout << i << ": (" << gradients[3*i] << (is_zero[3*i] ? "*" : ""); - // cout << ", " << gradients[3*i+1] << (is_zero[3*i+1] ? "*" : ""); - // cout << ", " << gradients[3*i+2] << (is_zero[3*i+2] ? "*" : "") << ")\n"; - // for(int j = 0; j < 3; j++){ - // if (is_zero[3*i+j] == false){ - // min_color[j] = std::min(min_color[j], gradients[3*i + j]); - // } - // } - // } - // } - // cout << "min non-0 color " << min_color[0] << " " << min_color[1] << " " << min_color[2] << endl; - // cout << "num border pixels proportion: " << num_border_pixels / (float)image.width() << endl; - - return num_border_pixels; -} - - -size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left){ - if (image.height() == 0 || image.width() == 0){ - return 0; - } - - size_t num_border_pixels = 0; - int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; - - size_t num_cols = image.width() - 1; - // Go through each row in the image - for(size_t y = 0; y < image.height(); y++){ - // Record the border gradient of this row: - bool is_zero[3] = {false}; - int16_t gradients[3] = {0}; - for(size_t col_index = 0; col_index < num_cols; col_index++){ - uint32_t p_left = image.pixel(col_index, y); - uint32_t p_right = image.pixel(col_index+1, y); - - // If both two pixels are black, then we skip this case - if (p_left == 0 && p_right == 0){ - continue; - } - - // c1 may be darker, while c2 is not yet covered by the dark translucent region - Color c1(dark_left ? p_left : p_right); - Color c2(dark_left ? p_right : p_left); - - if (c1.red() == 0){ - is_zero[0] = true; - } - if (c1.green() == 0){ - is_zero[1] = true; - } - if (c1.blue() == 0){ - is_zero[2] = true; - } - - gradients[0] = std::max(gradients[0], int16_t((int)c2.red() - (int) c1.red())); - gradients[1] = std::max(gradients[1], int16_t((int)c2.green() - (int) c1.green())); - gradients[2] = std::max(gradients[2], int16_t((int)c2.blue() - (int) c1.blue())); - } - - bool has_non_border_channel = false; - for(int c = 0; c < 3; c++){ - if (is_zero[c] == false && gradients[c] < thres_c[c]){ - has_non_border_channel = true; - break; - } - } - num_border_pixels += !has_non_border_channel; - - // cout << y << ": (" << gradients[0] << (is_zero[0] ? "*" : ""); - // cout << ", " << gradients[1] << (is_zero[1] ? "*" : ""); - // cout << ", " << gradients[2] << (is_zero[2] ? "*" : "") << ")\n"; - // cout << "has_non_border_channel " << has_non_border_channel << endl; - } - - // cout << "num border pixels proportion: " << num_border_pixels / (float)image.height() << endl; - - return num_border_pixels; -} - - - - - -} +/* Image Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "ImageGradient.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top){ + // Gradient on each color channel at each pixel in one row + std::vector gradients(image.width() * 3, 0); + // Whether a color channel is zero for each pixel in one row + std::vector is_zero(image.width() * 3, false); + + if (image.height() == 0 || image.width() == 0){ + return 0; + } + + size_t num_rows = image.height() - 1; + for(size_t row_index = 0; row_index < num_rows; row_index++){ + for(size_t x = 0; x < image.width(); x++){ + uint32_t p_above = image.pixel(x, row_index); + uint32_t p_below = image.pixel(x, row_index+1); + + // If both two pixels are black, then we skip this case + if (p_above == 0 && p_below == 0){ + continue; + } + + // c1 may be darker, while c2 is not yet covered by the dark translucent region + Color c1(dark_top ? p_above : p_below); + Color c2(dark_top ? p_below : p_above); + if (c1.red() == 0){ + is_zero[3*x] = true; + } + if (c1.green() == 0){ + is_zero[3*x+1] = true; + } + if (c1.blue() == 0){ + is_zero[3*x+2] = true; + } + gradients[3*x] = std::max(gradients[3*x], int16_t((int)c2.red() - (int) c1.red())); + gradients[3*x+1] = std::max(gradients[3*x+1], int16_t((int)c2.green() - (int) c1.green())); + gradients[3*x+2] = std::max(gradients[3*x+2], int16_t((int)c2.blue() - (int) c1.blue())); + + + } + } + + int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; + + size_t num_border_pixels = 0; + for(size_t x = 0; x < image.width(); x++){ + bool has_non_border_channel = false; + for(int c = 0; c < 3; c++){ + if (is_zero[3*x+c] == false && gradients[3*x+c] < thres_c[c]){ + has_non_border_channel = true; + break; + } + } + + num_border_pixels += !has_non_border_channel; + } + + // int16_t min_color[3] = {255, 255, 255}; + // for(size_t i = 0; i < image.width(); i++){ + // if (is_zero[3*i] == false || is_zero[3*i+1] == false || is_zero[3*i+2] == false){ + // cout << i << ": (" << gradients[3*i] << (is_zero[3*i] ? "*" : ""); + // cout << ", " << gradients[3*i+1] << (is_zero[3*i+1] ? "*" : ""); + // cout << ", " << gradients[3*i+2] << (is_zero[3*i+2] ? "*" : "") << ")\n"; + // for(int j = 0; j < 3; j++){ + // if (is_zero[3*i+j] == false){ + // min_color[j] = std::min(min_color[j], gradients[3*i + j]); + // } + // } + // } + // } + // cout << "min non-0 color " << min_color[0] << " " << min_color[1] << " " << min_color[2] << endl; + // cout << "num border pixels proportion: " << num_border_pixels / (float)image.width() << endl; + + return num_border_pixels; +} + + +size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left){ + if (image.height() == 0 || image.width() == 0){ + return 0; + } + + size_t num_border_pixels = 0; + int16_t thres_c[3] = {threshold.red(), threshold.green(), threshold.blue()}; + + size_t num_cols = image.width() - 1; + // Go through each row in the image + for(size_t y = 0; y < image.height(); y++){ + // Record the border gradient of this row: + bool is_zero[3] = {false}; + int16_t gradients[3] = {0}; + for(size_t col_index = 0; col_index < num_cols; col_index++){ + uint32_t p_left = image.pixel(col_index, y); + uint32_t p_right = image.pixel(col_index+1, y); + + // If both two pixels are black, then we skip this case + if (p_left == 0 && p_right == 0){ + continue; + } + + // c1 may be darker, while c2 is not yet covered by the dark translucent region + Color c1(dark_left ? p_left : p_right); + Color c2(dark_left ? p_right : p_left); + + if (c1.red() == 0){ + is_zero[0] = true; + } + if (c1.green() == 0){ + is_zero[1] = true; + } + if (c1.blue() == 0){ + is_zero[2] = true; + } + + gradients[0] = std::max(gradients[0], int16_t((int)c2.red() - (int) c1.red())); + gradients[1] = std::max(gradients[1], int16_t((int)c2.green() - (int) c1.green())); + gradients[2] = std::max(gradients[2], int16_t((int)c2.blue() - (int) c1.blue())); + } + + bool has_non_border_channel = false; + for(int c = 0; c < 3; c++){ + if (is_zero[c] == false && gradients[c] < thres_c[c]){ + has_non_border_channel = true; + break; + } + } + num_border_pixels += !has_non_border_channel; + + // cout << y << ": (" << gradients[0] << (is_zero[0] ? "*" : ""); + // cout << ", " << gradients[1] << (is_zero[1] ? "*" : ""); + // cout << ", " << gradients[2] << (is_zero[2] ? "*" : "") << ")\n"; + // cout << "has_non_border_channel " << has_non_border_channel << endl; + } + + // cout << "num border pixels proportion: " << num_border_pixels / (float)image.height() << endl; + + return num_border_pixels; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/ImageGradient.h b/SerialPrograms/Source/CommonTools/Images/ImageGradient.h index fd9981e96f..1bb639f420 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageGradient.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageGradient.h @@ -1,41 +1,41 @@ -/* Image Gradient - * - * From: https://github.com/PokemonAutomation/ - * - * Header for various image gradient related functions, mostly for visual inferences - */ - -#ifndef PokemonAutomation_CommonTools_ImageGradient_H -#define PokemonAutomation_CommonTools_ImageGradient_H - -#include -#include -#include "Common/Cpp/Color.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; - -// Used to detect a horizontal border line across an image. -// The border is defined as: -// If `dark_top` is true, the upper side of the border line is darker than the lower side. -// If `dark_top` is false, the lower side of the border line is darker than the upper side. -// It returns how many pixels on the border that are darker by the other side by at least `threshold` -// If it returns the same number as `image.width()`, then there is a clear horizontal border across the image. -// -// The image is supposed to have a very small height, as it only holds a horizontal border line. -size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top); - -// Used to detect a vertical border line across an image. -// The border is defined as: -// If `dark_left` is true, the left side of the border line is darker than the right side. -// If `dark_left` is false, the right side of the border line is darker than the left side. -// It returns how many pixels on the border that are darker by the other side by at least `threshold` -// If it returns the same number as `image.height()`, then there is a clear vertical border across the image. -// -// The image is supposed to have a very small width, as it only holds a vertical border line. -size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left); - -} -#endif +/* Image Gradient + * + * From: https://github.com/PokemonAutomation/ + * + * Header for various image gradient related functions, mostly for visual inferences + */ + +#ifndef PokemonAutomation_CommonTools_ImageGradient_H +#define PokemonAutomation_CommonTools_ImageGradient_H + +#include +#include +#include "Common/Cpp/Color.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; + +// Used to detect a horizontal border line across an image. +// The border is defined as: +// If `dark_top` is true, the upper side of the border line is darker than the lower side. +// If `dark_top` is false, the lower side of the border line is darker than the upper side. +// It returns how many pixels on the border that are darker by the other side by at least `threshold` +// If it returns the same number as `image.width()`, then there is a clear horizontal border across the image. +// +// The image is supposed to have a very small height, as it only holds a horizontal border line. +size_t count_horizontal_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_top); + +// Used to detect a vertical border line across an image. +// The border is defined as: +// If `dark_left` is true, the left side of the border line is darker than the right side. +// If `dark_left` is false, the right side of the border line is darker than the left side. +// It returns how many pixels on the border that are darker by the other side by at least `threshold` +// If it returns the same number as `image.height()`, then there is a clear vertical border across the image. +// +// The image is supposed to have a very small width, as it only holds a vertical border line. +size_t count_vertical_translucent_border_pixels(const ImageViewRGB32& image, const Color& threshold, bool dark_left); + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp b/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp index 1fdd51b8c2..8b1beb6355 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageManip.cpp @@ -1,28 +1,28 @@ -/* Image Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ImageManip.h" - -namespace PokemonAutomation{ - - -ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel){ - size_t width = image.width(); - size_t height = image.height(); - ImageRGB32 ret(image.width() + 2*pixels_on_each_side, image.height() + 2*pixels_on_each_side); - ret.fill(pixel); - for (size_t r = 0; r < height; r++){ - size_t out_row = r + pixels_on_each_side; - uint32_t* out = (uint32_t*)((char*)ret.data() + ret.bytes_per_row() * out_row) + pixels_on_each_side; - const uint32_t* in = (const uint32_t*)((char*)image.data() + image.bytes_per_row() * r); - memcpy(out, in, width * sizeof(uint32_t)); - } - return ret; -} - - -} +/* Image Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ImageManip.h" + +namespace PokemonAutomation{ + + +ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel){ + size_t width = image.width(); + size_t height = image.height(); + ImageRGB32 ret(image.width() + 2*pixels_on_each_side, image.height() + 2*pixels_on_each_side); + ret.fill(pixel); + for (size_t r = 0; r < height; r++){ + size_t out_row = r + pixels_on_each_side; + uint32_t* out = (uint32_t*)((char*)ret.data() + ret.bytes_per_row() * out_row) + pixels_on_each_side; + const uint32_t* in = (const uint32_t*)((char*)image.data() + image.bytes_per_row() * r); + memcpy(out, in, width * sizeof(uint32_t)); + } + return ret; +} + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/ImageManip.h b/SerialPrograms/Source/CommonTools/Images/ImageManip.h index 2d7894f820..d4bd836118 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageManip.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageManip.h @@ -1,19 +1,19 @@ -/* Image Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageManip_H -#define PokemonAutomation_CommonTools_ImageManip_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - -ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel); - - -} -#endif +/* Image Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageManip_H +#define PokemonAutomation_CommonTools_ImageManip_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + +ImageRGB32 pad_image(const ImageViewRGB32& image, size_t pixels_on_each_side, uint32_t pixel); + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp b/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp index bcea4fb53d..7cd5a755e2 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp +++ b/SerialPrograms/Source/CommonTools/Images/ImageTools.cpp @@ -1,60 +1,60 @@ -/* Image Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/FloatPixel.h" -#include "ImageTools.h" - -namespace PokemonAutomation{ - - - -ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y){ - if (!x || !y){ - return ImageRGB32(); - } - if (x.width() != y.width()){ - return ImageRGB32(); - } - if (x.height() != y.height()){ - return ImageRGB32(); - } - - ImageRGB32 image(x.width(), x.height()); - size_t width = x.width(); - size_t height = x.height(); - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - Color px(x.pixel(c, r)); - Color py(y.pixel(c, r)); - if (px.alpha() == 0 || py.alpha() == 0){ - image.pixel(c, r) = 0xff000000; - }else{ - double distance = euclidean_distance(px, py); - distance *= 0.57735026918962576451; // 1 / sqrt(3) - uint32_t dist_int = std::min((uint32_t)distance, 255); - image.pixel(c, r) = 0xff000000 + dist_int * 0x010101; - } - } - } - return image; -} - - - - - - - - - - - - -} - +/* Image Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "ImageTools.h" + +namespace PokemonAutomation{ + + + +ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y){ + if (!x || !y){ + return ImageRGB32(); + } + if (x.width() != y.width()){ + return ImageRGB32(); + } + if (x.height() != y.height()){ + return ImageRGB32(); + } + + ImageRGB32 image(x.width(), x.height()); + size_t width = x.width(); + size_t height = x.height(); + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + Color px(x.pixel(c, r)); + Color py(y.pixel(c, r)); + if (px.alpha() == 0 || py.alpha() == 0){ + image.pixel(c, r) = 0xff000000; + }else{ + double distance = euclidean_distance(px, py); + distance *= 0.57735026918962576451; // 1 / sqrt(3) + uint32_t dist_int = std::min((uint32_t)distance, 255); + image.pixel(c, r) = 0xff000000 + dist_int * 0x010101; + } + } + } + return image; +} + + + + + + + + + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Images/ImageTools.h b/SerialPrograms/Source/CommonTools/Images/ImageTools.h index 00a574fd11..c5c90adb13 100644 --- a/SerialPrograms/Source/CommonTools/Images/ImageTools.h +++ b/SerialPrograms/Source/CommonTools/Images/ImageTools.h @@ -1,26 +1,26 @@ -/* Image Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageTools_H -#define PokemonAutomation_CommonTools_ImageTools_H - - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; - - -// Deprecated -ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y); - - - - - -} -#endif - +/* Image Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageTools_H +#define PokemonAutomation_CommonTools_ImageTools_H + + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; + + +// Deprecated +ImageRGB32 image_diff_greyscale(const ImageViewRGB32& x, const ImageViewRGB32& y); + + + + + +} +#endif + diff --git a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp index b4c4e10235..33ee860b9f 100644 --- a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp +++ b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.cpp @@ -1,112 +1,112 @@ -/* Solid Color Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "SolidColorTest.h" - -#include -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -bool is_white( - const ImageStats& stats, - double min_rgb_sum, - double max_stddev_sum -){ - if (stats.average.sum() < min_rgb_sum){ - return false; - } - return is_solid(stats, {0.333333, 0.333333, 0.333333}, 0.08, max_stddev_sum); -} -bool is_black( - const ImageStats& stats, - double max_rgb_sum, - double max_stddev_sum -){ - double average = stats.average.sum(); - double stddev = stats.stddev.sum(); - if (PreloadSettings::debug().COLOR_CHECK){ - cout << "is_black(): stats.average " << stats.average.to_string() << "(sum " << average << ") stats.stddev " << stats.stddev.to_string() - << "(sum " << stddev << ") max_rgb_sum " << max_rgb_sum << " max_stddev_sum " << max_stddev_sum << endl; - } -// cout << stats.average << stats.stddev << endl; - return average <= max_rgb_sum && stddev <= max_stddev_sum; -} -bool is_grey( - const ImageStats& stats, - double min_rgb_sum, double max_rgb_sum, - double max_stddev_sum -){ - double average = stats.average.sum(); - if (average < min_rgb_sum || average > max_rgb_sum){ - return false; - } - - double stddev = stats.stddev.sum(); - if (stddev > max_stddev_sum){ -// cout << "bad stddev = " << stddev << endl; - return false; - } - - // If it's too dark, color ratios will be unstable. - if (average < 100){ - return true; - } - - FloatPixel actual = stats.average / average; - double distance = euclidean_distance(actual, {0.333333, 0.333333, 0.333333}); - return distance <= 0.1; -} -bool is_solid( - const ImageStats& stats, - const FloatPixel& expected_color_ratio, - double max_euclidean_distance, - double max_stddev_sum -){ - double stddev = stats.stddev.sum(); - if (stddev > max_stddev_sum){ -// cout << "bad stddev = " << stddev << endl; - return false; - } - - double average = stats.average.sum(); - FloatPixel actual = stats.average / average; - double distance = euclidean_distance(actual, expected_color_ratio); -// cout << "actual color ratio " << actual << endl; -// cout << "distance = " << distance << endl; - - return distance <= max_euclidean_distance; -} - -bool ImageSolidCheck::check(const ImageViewRGB32& frame) const{ - ImageStats stats = image_stats(extract_box_reference(frame, box)); - return is_solid(stats, expected_color_ratio, max_euclidean_distance, max_stddev_sum); -} - -std::string ImageSolidCheck::debug_string(const ImageViewRGB32& frame) const{ - std::ostringstream oss; - ImageStats stats = image_stats(extract_box_reference(frame, box)); - oss << "Box (" << box.x << ", " << box.y << ", " << box.width << ", " << box.height << ") "; - - double average = stats.average.sum(); - FloatPixel actual_ratio = stats.average / average; - oss << "expected color ratio: " << expected_color_ratio.to_string() << " "; - oss << "actual color ratio: " << actual_ratio.to_string() << " "; - oss << "dist: " << euclidean_distance(actual_ratio, expected_color_ratio) << " "; - - double actual_stddev = stats.stddev.sum(); - oss << "max stddev sum: " << max_stddev_sum << " actual stddev sum: " << actual_stddev; - - return oss.str(); -} - - -} +/* Solid Color Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "SolidColorTest.h" + +#include +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +bool is_white( + const ImageStats& stats, + double min_rgb_sum, + double max_stddev_sum +){ + if (stats.average.sum() < min_rgb_sum){ + return false; + } + return is_solid(stats, {0.333333, 0.333333, 0.333333}, 0.08, max_stddev_sum); +} +bool is_black( + const ImageStats& stats, + double max_rgb_sum, + double max_stddev_sum +){ + double average = stats.average.sum(); + double stddev = stats.stddev.sum(); + if (PreloadSettings::debug().COLOR_CHECK){ + cout << "is_black(): stats.average " << stats.average.to_string() << "(sum " << average << ") stats.stddev " << stats.stddev.to_string() + << "(sum " << stddev << ") max_rgb_sum " << max_rgb_sum << " max_stddev_sum " << max_stddev_sum << endl; + } +// cout << stats.average << stats.stddev << endl; + return average <= max_rgb_sum && stddev <= max_stddev_sum; +} +bool is_grey( + const ImageStats& stats, + double min_rgb_sum, double max_rgb_sum, + double max_stddev_sum +){ + double average = stats.average.sum(); + if (average < min_rgb_sum || average > max_rgb_sum){ + return false; + } + + double stddev = stats.stddev.sum(); + if (stddev > max_stddev_sum){ +// cout << "bad stddev = " << stddev << endl; + return false; + } + + // If it's too dark, color ratios will be unstable. + if (average < 100){ + return true; + } + + FloatPixel actual = stats.average / average; + double distance = euclidean_distance(actual, {0.333333, 0.333333, 0.333333}); + return distance <= 0.1; +} +bool is_solid( + const ImageStats& stats, + const FloatPixel& expected_color_ratio, + double max_euclidean_distance, + double max_stddev_sum +){ + double stddev = stats.stddev.sum(); + if (stddev > max_stddev_sum){ +// cout << "bad stddev = " << stddev << endl; + return false; + } + + double average = stats.average.sum(); + FloatPixel actual = stats.average / average; + double distance = euclidean_distance(actual, expected_color_ratio); +// cout << "actual color ratio " << actual << endl; +// cout << "distance = " << distance << endl; + + return distance <= max_euclidean_distance; +} + +bool ImageSolidCheck::check(const ImageViewRGB32& frame) const{ + ImageStats stats = image_stats(extract_box_reference(frame, box)); + return is_solid(stats, expected_color_ratio, max_euclidean_distance, max_stddev_sum); +} + +std::string ImageSolidCheck::debug_string(const ImageViewRGB32& frame) const{ + std::ostringstream oss; + ImageStats stats = image_stats(extract_box_reference(frame, box)); + oss << "Box (" << box.x << ", " << box.y << ", " << box.width << ", " << box.height << ") "; + + double average = stats.average.sum(); + FloatPixel actual_ratio = stats.average / average; + oss << "expected color ratio: " << expected_color_ratio.to_string() << " "; + oss << "actual color ratio: " << actual_ratio.to_string() << " "; + oss << "dist: " << euclidean_distance(actual_ratio, expected_color_ratio) << " "; + + double actual_stddev = stats.stddev.sum(); + oss << "max stddev sum: " << max_stddev_sum << " actual stddev sum: " << actual_stddev; + + return oss.str(); +} + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h index cd8fd76d92..56840617b3 100644 --- a/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h +++ b/SerialPrograms/Source/CommonTools/Images/SolidColorTest.h @@ -1,106 +1,106 @@ -/* Solid Color Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_SolidColorTest_H -#define PokemonAutomation_CommonTools_SolidColorTest_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" - -namespace PokemonAutomation{ - - -bool is_white( - const ImageStats& stats, - double min_rgb_sum = 500, - double max_stddev_sum = 10 -); -bool is_black( - const ImageStats& stats, - double max_rgb_sum = 100, - double max_stddev_sum = 10 -); -bool is_grey( - const ImageStats& stats, - double min_rgb_sum, double max_rgb_sum, - double max_stddev_sum = 10 -); - -// expected_color_ratio: ratio of color channels to match, -// for a color {r, g, b}: the color ratio is {r/(r+g+b), g/(r+g+b), b/(r+g+b)} -// the sum of the ratios should add up to 1.0. -// e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) -bool is_solid( - const ImageStats& stats, - const FloatPixel& expected_color_ratio, - double max_euclidean_distance = 0.15, - double max_stddev_sum = 10 -); - - -inline bool is_white( - const ImageViewRGB32& image, - double min_rgb_sum = 500, - double max_stddev_sum = 10 -){ - return is_white(image_stats(image), min_rgb_sum, max_stddev_sum); -} -inline bool is_black( - const ImageViewRGB32& image, - double max_rgb_sum = 100, - double max_stddev_sum = 10 -){ - ImageStats stats = image_stats(image); -// cout << stats.average << stats.stddev << endl; - return is_black(stats, max_rgb_sum, max_stddev_sum); -} -inline bool is_grey( - const ImageViewRGB32& image, - double min_rgb_sum, double max_rgb_sum, - double max_stddev_sum = 10 -){ - return is_grey(image_stats(image), min_rgb_sum, max_rgb_sum, max_stddev_sum); -} - -// expected_color_ratio: ratio of color channels to match, e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) -inline bool is_solid( - const ImageViewRGB32& image, - const FloatPixel& expected_color_ratio, - double max_euclidean_distance = 0.15, - double max_stddev_sum = 10 -){ - return is_solid(image_stats(image), expected_color_ratio, max_euclidean_distance, max_stddev_sum); -} - -// A convenience struct to do solid checks on images. -struct ImageSolidCheck{ - ImageFloatBox box; - FloatPixel expected_color_ratio; - double max_euclidean_distance = 0.15; - double max_stddev_sum = 10; - - ImageSolidCheck( - double x, double y, double width, double height, - double r, double g, double b, - double max_distance = 0.15, double max_stddev_sum = 10) - : box(x, y, width, height) - , expected_color_ratio(r, g, b) - , max_euclidean_distance(max_distance) - , max_stddev_sum(max_stddev_sum) {} - - // Check if the area on the image is a solid color. - bool check(const ImageViewRGB32& image) const; - - // Return a debug string on the checks performed on the image. - std::string debug_string(const ImageViewRGB32& image) const; -}; - - - - -} -#endif +/* Solid Color Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_SolidColorTest_H +#define PokemonAutomation_CommonTools_SolidColorTest_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" + +namespace PokemonAutomation{ + + +bool is_white( + const ImageStats& stats, + double min_rgb_sum = 500, + double max_stddev_sum = 10 +); +bool is_black( + const ImageStats& stats, + double max_rgb_sum = 100, + double max_stddev_sum = 10 +); +bool is_grey( + const ImageStats& stats, + double min_rgb_sum, double max_rgb_sum, + double max_stddev_sum = 10 +); + +// expected_color_ratio: ratio of color channels to match, +// for a color {r, g, b}: the color ratio is {r/(r+g+b), g/(r+g+b), b/(r+g+b)} +// the sum of the ratios should add up to 1.0. +// e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) +bool is_solid( + const ImageStats& stats, + const FloatPixel& expected_color_ratio, + double max_euclidean_distance = 0.15, + double max_stddev_sum = 10 +); + + +inline bool is_white( + const ImageViewRGB32& image, + double min_rgb_sum = 500, + double max_stddev_sum = 10 +){ + return is_white(image_stats(image), min_rgb_sum, max_stddev_sum); +} +inline bool is_black( + const ImageViewRGB32& image, + double max_rgb_sum = 100, + double max_stddev_sum = 10 +){ + ImageStats stats = image_stats(image); +// cout << stats.average << stats.stddev << endl; + return is_black(stats, max_rgb_sum, max_stddev_sum); +} +inline bool is_grey( + const ImageViewRGB32& image, + double min_rgb_sum, double max_rgb_sum, + double max_stddev_sum = 10 +){ + return is_grey(image_stats(image), min_rgb_sum, max_rgb_sum, max_stddev_sum); +} + +// expected_color_ratio: ratio of color channels to match, e.g. if a color is (127, 127, 254), it's color ratio is (0.25, 0.25, 0.5) +inline bool is_solid( + const ImageViewRGB32& image, + const FloatPixel& expected_color_ratio, + double max_euclidean_distance = 0.15, + double max_stddev_sum = 10 +){ + return is_solid(image_stats(image), expected_color_ratio, max_euclidean_distance, max_stddev_sum); +} + +// A convenience struct to do solid checks on images. +struct ImageSolidCheck{ + ImageFloatBox box; + FloatPixel expected_color_ratio; + double max_euclidean_distance = 0.15; + double max_stddev_sum = 10; + + ImageSolidCheck( + double x, double y, double width, double height, + double r, double g, double b, + double max_distance = 0.15, double max_stddev_sum = 10) + : box(x, y, width, height) + , expected_color_ratio(r, g, b) + , max_euclidean_distance(max_distance) + , max_stddev_sum(max_stddev_sum) {} + + // Check if the area on the image is a solid color. + bool check(const ImageViewRGB32& image) const; + + // Return a debug string on the checks performed on the image. + std::string debug_string(const ImageViewRGB32& image) const; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp index 046d171722..430c74e15a 100644 --- a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp +++ b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.cpp @@ -1,188 +1,188 @@ -/* Waterfill Process - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Color.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "WaterfillUtilities.h" - -#include - - -namespace PokemonAutomation{ - - -std::pair remove_center_pixels( - const Kernels::Waterfill::WaterfillObject& object, - size_t num_pixels_to_remove -){ - PackedBinaryMatrix matrix = object.packed_matrix(); - size_t width = matrix.width(); - size_t height = matrix.height(); -// cout << matrix.dump() << endl; - - // Sort all pixels by distance from center. - size_t center_x = (size_t)(object.center_of_gravity_x() - object.min_x); - size_t center_y = (size_t)(object.center_of_gravity_y() - object.min_y); - std::map distances; - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - if (matrix.get(c, r)){ - size_t dist_x = c - center_x; - size_t dist_y = r - center_y; - uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; - distances[distance_sqr]++; - } - } - } - - // Filter out pixels close to center - size_t count = 0; - uint64_t distance_sqr_th = 0; - for (auto& item : distances){ - count += item.second; - if (count >= num_pixels_to_remove){ - distance_sqr_th = item.first; - break; - } - } - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - size_t dist_x = c - center_x; - size_t dist_y = r - center_y; - uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; - if (distance_sqr < distance_sqr_th){ - matrix.set(c, r, false); - } - } - } - - return std::pair(std::move(matrix), distance_sqr_th); -} - -bool match_template_by_waterfill( - const ImageViewRGB32 &image, - const ImageMatch::WaterfillTemplateMatcher &matcher, - const std::vector> &filters, - const std::pair &area_thresholds, - double rmsd_threshold, - std::function check_matched_object) -{ - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "match_template_by_waterfill_input_image", - image - ); - std::cout << "Match template by waterfill, " << filters.size() << " filter(s), size range (" - << area_thresholds.first << ", "; - if (area_thresholds.second == SIZE_MAX){ - std::cout << "SIZE_MAX"; - }else{ - std::cout << area_thresholds.second; - } - std::cout << ")" << std::endl; - } - std::vector matrices = compress_rgb32_to_binary_range(image, filters); - - bool detected = false; - bool stop_match = false; - for (size_t i_matrix = 0; i_matrix < matrices.size(); i_matrix++){ - PackedBinaryMatrix& matrix = matrices[i_matrix]; - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - ImageRGB32 binaryImage = image.copy(); - filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); - //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); - dump_debug_image( - global_logger_command_line(), - "CommonFramework/WaterfillTemplateMatcher", - "match_template_by_waterfill_filtered_image_" + std::to_string(i_matrix), - binaryImage - ); - } - - std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); - Kernels::Waterfill::WaterfillObject object; - const size_t min_area = area_thresholds.first; - session->set_source(matrix); - auto finder = session->make_iterator(min_area); - const bool keep_object_matrix = false; - while (finder->find_next(object, keep_object_matrix)){ - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "------------" << std::endl; - std::cout << "Object area: " << object.area << std::endl; - } - - if (object.area > area_thresholds.second){ - continue; - } - double rmsd = matcher.rmsd_original(image, object); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "Object rmsd: " << rmsd << std::endl; - } - - if (rmsd < rmsd_threshold){ - detected = true; - - if (check_matched_object(object)){ - stop_match = true; - break; - } - } - } - - if (stop_match){ - break; - } - } - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "End match template by waterfill" << std::endl; - } - return detected; -} - - -void draw_matrix_on_image( - const PackedBinaryMatrix& matrix, - uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y -){ - for (size_t x = 0; x < matrix.width(); x++){ - for (size_t y = 0; y < matrix.height(); y++){ - if (matrix.get(x, y)){ - image.pixel(offset_x + x, offset_y + y) = (uint32_t)color; - } - } - } -} - - -void draw_object_on_image( - const Kernels::Waterfill::WaterfillObject& obj, - const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y -){ - for (size_t x = 0; x < obj.width(); x++){ - for (size_t y = 0; y < obj.height(); y++){ - if (obj.object->get(obj.min_x + x, obj.min_y + y)){ - image.pixel(offset_x + obj.min_x + x, offset_y + obj.min_y + y) = color; - // cout << "Set color at " << offset_x + object.min_x + obj.min_x + x << ", " << offset_y + object.min_y + obj.min_y + y << endl; - } - } - } -} - - - - -} +/* Waterfill Process + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Color.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "WaterfillUtilities.h" + +#include + + +namespace PokemonAutomation{ + + +std::pair remove_center_pixels( + const Kernels::Waterfill::WaterfillObject& object, + size_t num_pixels_to_remove +){ + PackedBinaryMatrix matrix = object.packed_matrix(); + size_t width = matrix.width(); + size_t height = matrix.height(); +// cout << matrix.dump() << endl; + + // Sort all pixels by distance from center. + size_t center_x = (size_t)(object.center_of_gravity_x() - object.min_x); + size_t center_y = (size_t)(object.center_of_gravity_y() - object.min_y); + std::map distances; + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + if (matrix.get(c, r)){ + size_t dist_x = c - center_x; + size_t dist_y = r - center_y; + uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; + distances[distance_sqr]++; + } + } + } + + // Filter out pixels close to center + size_t count = 0; + uint64_t distance_sqr_th = 0; + for (auto& item : distances){ + count += item.second; + if (count >= num_pixels_to_remove){ + distance_sqr_th = item.first; + break; + } + } + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + size_t dist_x = c - center_x; + size_t dist_y = r - center_y; + uint64_t distance_sqr = (uint64_t)dist_x*dist_x + (uint64_t)dist_y*dist_y; + if (distance_sqr < distance_sqr_th){ + matrix.set(c, r, false); + } + } + } + + return std::pair(std::move(matrix), distance_sqr_th); +} + +bool match_template_by_waterfill( + const ImageViewRGB32 &image, + const ImageMatch::WaterfillTemplateMatcher &matcher, + const std::vector> &filters, + const std::pair &area_thresholds, + double rmsd_threshold, + std::function check_matched_object) +{ + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "match_template_by_waterfill_input_image", + image + ); + std::cout << "Match template by waterfill, " << filters.size() << " filter(s), size range (" + << area_thresholds.first << ", "; + if (area_thresholds.second == SIZE_MAX){ + std::cout << "SIZE_MAX"; + }else{ + std::cout << area_thresholds.second; + } + std::cout << ")" << std::endl; + } + std::vector matrices = compress_rgb32_to_binary_range(image, filters); + + bool detected = false; + bool stop_match = false; + for (size_t i_matrix = 0; i_matrix < matrices.size(); i_matrix++){ + PackedBinaryMatrix& matrix = matrices[i_matrix]; + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + ImageRGB32 binaryImage = image.copy(); + filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); + //filter_by_mask(matrix, binaryImage, Color(COLOR_WHITE), true); + dump_debug_image( + global_logger_command_line(), + "CommonFramework/WaterfillTemplateMatcher", + "match_template_by_waterfill_filtered_image_" + std::to_string(i_matrix), + binaryImage + ); + } + + std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); + Kernels::Waterfill::WaterfillObject object; + const size_t min_area = area_thresholds.first; + session->set_source(matrix); + auto finder = session->make_iterator(min_area); + const bool keep_object_matrix = false; + while (finder->find_next(object, keep_object_matrix)){ + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "------------" << std::endl; + std::cout << "Object area: " << object.area << std::endl; + } + + if (object.area > area_thresholds.second){ + continue; + } + double rmsd = matcher.rmsd_original(image, object); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "Object rmsd: " << rmsd << std::endl; + } + + if (rmsd < rmsd_threshold){ + detected = true; + + if (check_matched_object(object)){ + stop_match = true; + break; + } + } + } + + if (stop_match){ + break; + } + } + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "End match template by waterfill" << std::endl; + } + return detected; +} + + +void draw_matrix_on_image( + const PackedBinaryMatrix& matrix, + uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y +){ + for (size_t x = 0; x < matrix.width(); x++){ + for (size_t y = 0; y < matrix.height(); y++){ + if (matrix.get(x, y)){ + image.pixel(offset_x + x, offset_y + y) = (uint32_t)color; + } + } + } +} + + +void draw_object_on_image( + const Kernels::Waterfill::WaterfillObject& obj, + const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y +){ + for (size_t x = 0; x < obj.width(); x++){ + for (size_t y = 0; y < obj.height(); y++){ + if (obj.object->get(obj.min_x + x, obj.min_y + y)){ + image.pixel(offset_x + obj.min_x + x, offset_y + obj.min_y + y) = color; + // cout << "Set color at " << offset_x + object.min_x + obj.min_x + x << ", " << offset_y + object.min_y + obj.min_y + y << endl; + } + } + } +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h index 40c05bc048..dfe53bf4cc 100644 --- a/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h +++ b/SerialPrograms/Source/CommonTools/Images/WaterfillUtilities.h @@ -1,82 +1,82 @@ -/* Waterfill Utilities - * - * From: https://github.com/PokemonAutomation/ - * - * Util functions that process waterfill objects and matrices. - */ - -#ifndef PokemonAutomation_CommonTools_WaterfillUtilities_H -#define PokemonAutomation_CommonTools_WaterfillUtilities_H - -#include -#include -#include "CommonFramework/ImageTypes/BinaryImage.h" - -namespace PokemonAutomation{ - class ImageRGB32; - class ImageViewRGB32; -namespace Kernels{ -namespace Waterfill{ - class WaterfillObject; -} -} - -namespace ImageMatch{ - class WaterfillTemplateMatcher; -} - -// Remove pixels close to center of mass of the water fill object. -// Pixels are removed based on the distance to the center of mass. The code will choose a distance threshold as large as possible -// while the number of the removed pixels is smaller than `num_removed_pixels_threshold`. -// Return a binary matrix representing the remaining pixels and the distance threshold which is defined as the minimum distance of -// the remaining pixels towards the original center of mass. -// Note: `object.object` must be constructed before calling this function. -// Example usage for analyzing the shape of the object: -// auto std::tie(matrix, distance) = remove_center_pixels(object, (size_t)(0.85 * object.area)); -// auto session = make_WaterfillSession(matrix); -// ... -std::pair remove_center_pixels( - const Kernels::Waterfill::WaterfillObject& object, - size_t num_removed_pixels_threshold -); - -// Given an image first run waterfill (aka use a color filter) on it to detect pixels of a color range. Then for each connected -// componet of the detected pixel region (aka waterfill object), we check if the object is close to an image template by -// checking aspect ratio thresholds, area thresholds and RMSD threshold. -// If a template match is found, call the function `check_matched_object()` on it. -// -// image: the image. -// matcher: the template matcher holding the template. It is also responsible for checking aspect ratio thresholds. -// filters: each filter is parameterized by min and max color thresholds for detected pixels. For each filter, the function checks -// the waterfill objects formed by the detected pixels. -// area_thresholds: min, max thresholds for number of pixels of a waterfill object. -// rmsd_threshold: RMSD threshold. If RMSD of the waterfill object and template is smaller than this threshold, consider it a match. -// check_matched_object: if a matcher is found, pass the matched object to this function. If the function returns true, stop the -// entire template matching operation. -bool match_template_by_waterfill( - const ImageViewRGB32 &image, - const ImageMatch::WaterfillTemplateMatcher &matcher, - const std::vector> &filters, - const std::pair &area_thresholds, - double rmsd_threshold, - std::function check_matched_object); - -// Draw matrix on an image. Used for debugging the matrix. -// color: color of the pixels from the matrix to render on the image. -// offset_x, offset_y: the offset of the matrix when rendered on the image. -void draw_matrix_on_image( - const PackedBinaryMatrix& matrix, - uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y -); - -// Draw waterfill object on an image. Used for debugging the waterfill object. -// Note: the object must have WaterfillObject.object computed. -// color: color of the pixels from the object to render on the image. -// offset_x, offset_y: the offset of the object when rendered on the image. -void draw_object_on_image( - const Kernels::Waterfill::WaterfillObject& object, - const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y -); - -} -#endif +/* Waterfill Utilities + * + * From: https://github.com/PokemonAutomation/ + * + * Util functions that process waterfill objects and matrices. + */ + +#ifndef PokemonAutomation_CommonTools_WaterfillUtilities_H +#define PokemonAutomation_CommonTools_WaterfillUtilities_H + +#include +#include +#include "CommonFramework/ImageTypes/BinaryImage.h" + +namespace PokemonAutomation{ + class ImageRGB32; + class ImageViewRGB32; +namespace Kernels{ +namespace Waterfill{ + class WaterfillObject; +} +} + +namespace ImageMatch{ + class WaterfillTemplateMatcher; +} + +// Remove pixels close to center of mass of the water fill object. +// Pixels are removed based on the distance to the center of mass. The code will choose a distance threshold as large as possible +// while the number of the removed pixels is smaller than `num_removed_pixels_threshold`. +// Return a binary matrix representing the remaining pixels and the distance threshold which is defined as the minimum distance of +// the remaining pixels towards the original center of mass. +// Note: `object.object` must be constructed before calling this function. +// Example usage for analyzing the shape of the object: +// auto std::tie(matrix, distance) = remove_center_pixels(object, (size_t)(0.85 * object.area)); +// auto session = make_WaterfillSession(matrix); +// ... +std::pair remove_center_pixels( + const Kernels::Waterfill::WaterfillObject& object, + size_t num_removed_pixels_threshold +); + +// Given an image first run waterfill (aka use a color filter) on it to detect pixels of a color range. Then for each connected +// componet of the detected pixel region (aka waterfill object), we check if the object is close to an image template by +// checking aspect ratio thresholds, area thresholds and RMSD threshold. +// If a template match is found, call the function `check_matched_object()` on it. +// +// image: the image. +// matcher: the template matcher holding the template. It is also responsible for checking aspect ratio thresholds. +// filters: each filter is parameterized by min and max color thresholds for detected pixels. For each filter, the function checks +// the waterfill objects formed by the detected pixels. +// area_thresholds: min, max thresholds for number of pixels of a waterfill object. +// rmsd_threshold: RMSD threshold. If RMSD of the waterfill object and template is smaller than this threshold, consider it a match. +// check_matched_object: if a matcher is found, pass the matched object to this function. If the function returns true, stop the +// entire template matching operation. +bool match_template_by_waterfill( + const ImageViewRGB32 &image, + const ImageMatch::WaterfillTemplateMatcher &matcher, + const std::vector> &filters, + const std::pair &area_thresholds, + double rmsd_threshold, + std::function check_matched_object); + +// Draw matrix on an image. Used for debugging the matrix. +// color: color of the pixels from the matrix to render on the image. +// offset_x, offset_y: the offset of the matrix when rendered on the image. +void draw_matrix_on_image( + const PackedBinaryMatrix& matrix, + uint32_t color, ImageRGB32& image, size_t offset_x, size_t offset_y +); + +// Draw waterfill object on an image. Used for debugging the waterfill object. +// Note: the object must have WaterfillObject.object computed. +// color: color of the pixels from the object to render on the image. +// offset_x, offset_y: the offset of the object when rendered on the image. +void draw_object_on_image( + const Kernels::Waterfill::WaterfillObject& object, + const uint32_t& color, ImageRGB32& image, size_t offset_x, size_t offset_y +); + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h b/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h index 281498e4dd..6f0ca78b18 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/AudioInferenceCallback.h @@ -1,42 +1,42 @@ -/* Audio Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_AudioInferenceCallback_H -#define PokemonAutomation_CommonTools_AudioInferenceCallback_H - -#include -#include -#include "InferenceCallback.h" - -namespace PokemonAutomation{ - -class AudioSpectrum; -class AudioFeed; - -// Base class for an audio inference object to be called perioridically by -// inference routines in InferenceRoutines.h. -class AudioInferenceCallback : public InferenceCallback{ -public: - AudioInferenceCallback(std::string label) - : InferenceCallback(InferenceType::AUDIO, std::move(label)) - {} - - // Process new spectrums and do inferences on them. - // Return true if the inference session should stop. - // Input spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. - // If needed, access to `audioFeed` to render inference boxes. - virtual bool process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed - ) = 0; - -}; - - - - -} -#endif +/* Audio Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_AudioInferenceCallback_H +#define PokemonAutomation_CommonTools_AudioInferenceCallback_H + +#include +#include +#include "InferenceCallback.h" + +namespace PokemonAutomation{ + +class AudioSpectrum; +class AudioFeed; + +// Base class for an audio inference object to be called perioridically by +// inference routines in InferenceRoutines.h. +class AudioInferenceCallback : public InferenceCallback{ +public: + AudioInferenceCallback(std::string label) + : InferenceCallback(InferenceType::AUDIO, std::move(label)) + {} + + // Process new spectrums and do inferences on them. + // Return true if the inference session should stop. + // Input spectrums are ordered from newest (largest timestamp) to oldest (smallest timestamp) in the vector. + // If needed, access to `audioFeed` to render inference boxes. + virtual bool process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed + ) = 0; + +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h b/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h index f99261d248..4afe67f4f5 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/InferenceCallback.h @@ -1,91 +1,91 @@ -/* Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceCallback_H -#define PokemonAutomation_CommonTools_InferenceCallback_H - -#include -#include - -namespace PokemonAutomation{ - -enum class InferenceType{ - VISUAL, - AUDIO, -}; - -// Base class for an inference object to be called perioridically by -// inference routines in InferenceRoutines.h. -class InferenceCallback{ - // Disable these to prevent accidental copying/slicing. - InferenceCallback(const InferenceCallback&) = delete; - void operator=(const InferenceCallback&) = delete; - -public: - virtual ~InferenceCallback() = default; - - // Is it a visual or audio inference. - InferenceType type() const{ return m_type; } - // Name of the inference object. - const std::string& label() const{ return m_label; } - - -protected: - InferenceCallback(InferenceType type, std::string label) - : m_type(type) - , m_label(label) - {} - - -private: - InferenceType m_type; - std::string m_label; -}; - - - -// Used by inference routines in InferenceRoutines.h. -// The struct contains an inference callback and its inference period: how -// long should an inference routine wait before calling the callback object -// again. -struct PeriodicInferenceCallback{ - InferenceCallback* callback; - // inference period. 0 value means the inference routine should use the - // default inference period, which is set as a parameter to the inference - // routine. - std::chrono::milliseconds period; - - PeriodicInferenceCallback() - : callback(nullptr) - , period(std::chrono::milliseconds(0)) - {} - PeriodicInferenceCallback( - InferenceCallback& p_callback, - std::chrono::milliseconds p_period = std::chrono::milliseconds(0) - ) - : callback(&p_callback) - , period(p_period) - { -#if 0 - if (period > std::chrono::milliseconds(0)){ - return; - } - switch (callback->type()){ - case InferenceType::VISUAL: - period = std::chrono::milliseconds(50); - break; - case InferenceType::AUDIO: - period = std::chrono::milliseconds(20); - break; - } -#endif - } -}; - - - -} -#endif +/* Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceCallback_H +#define PokemonAutomation_CommonTools_InferenceCallback_H + +#include +#include + +namespace PokemonAutomation{ + +enum class InferenceType{ + VISUAL, + AUDIO, +}; + +// Base class for an inference object to be called perioridically by +// inference routines in InferenceRoutines.h. +class InferenceCallback{ + // Disable these to prevent accidental copying/slicing. + InferenceCallback(const InferenceCallback&) = delete; + void operator=(const InferenceCallback&) = delete; + +public: + virtual ~InferenceCallback() = default; + + // Is it a visual or audio inference. + InferenceType type() const{ return m_type; } + // Name of the inference object. + const std::string& label() const{ return m_label; } + + +protected: + InferenceCallback(InferenceType type, std::string label) + : m_type(type) + , m_label(label) + {} + + +private: + InferenceType m_type; + std::string m_label; +}; + + + +// Used by inference routines in InferenceRoutines.h. +// The struct contains an inference callback and its inference period: how +// long should an inference routine wait before calling the callback object +// again. +struct PeriodicInferenceCallback{ + InferenceCallback* callback; + // inference period. 0 value means the inference routine should use the + // default inference period, which is set as a parameter to the inference + // routine. + std::chrono::milliseconds period; + + PeriodicInferenceCallback() + : callback(nullptr) + , period(std::chrono::milliseconds(0)) + {} + PeriodicInferenceCallback( + InferenceCallback& p_callback, + std::chrono::milliseconds p_period = std::chrono::milliseconds(0) + ) + : callback(&p_callback) + , period(p_period) + { +#if 0 + if (period > std::chrono::milliseconds(0)){ + return; + } + switch (callback->type()){ + case InferenceType::VISUAL: + period = std::chrono::milliseconds(50); + break; + case InferenceType::AUDIO: + period = std::chrono::milliseconds(20); + break; + } +#endif + } +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp index f96ad19989..5b8e4e91a2 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.cpp @@ -1,26 +1,26 @@ -/* Visual Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "VisualInferenceCallback.h" - -namespace PokemonAutomation{ - - -bool VisualInferenceCallback::process_frame(const VideoSnapshot& frame){ - return process_frame(*frame.frame, frame.timestamp); -} -bool VisualInferenceCallback::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "You must override one of the two process_frame() functions."); -} - - - - - -} +/* Visual Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VisualInferenceCallback.h" + +namespace PokemonAutomation{ + + +bool VisualInferenceCallback::process_frame(const VideoSnapshot& frame){ + return process_frame(*frame.frame, frame.timestamp); +} +bool VisualInferenceCallback::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "You must override one of the two process_frame() functions."); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h index 4e42e056b8..a6cee16fdb 100644 --- a/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h +++ b/SerialPrograms/Source/CommonTools/InferenceCallbacks/VisualInferenceCallback.h @@ -1,46 +1,46 @@ -/* Visual Inference Callback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VisualInferenceCallback_H -#define PokemonAutomation_CommonTools_VisualInferenceCallback_H - -#include -#include "Common/Cpp/Time.h" -#include "InferenceCallback.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class ImageRGB32; -struct VideoSnapshot; -class VideoOverlaySet; - -// Base class for a visual inference object to be called perioridically by -// inference routines in InferenceRoutines.h. -class VisualInferenceCallback : public InferenceCallback{ -public: - VisualInferenceCallback(std::string label) - : InferenceCallback(InferenceType::VISUAL, std::move(label)) - {} - - // The inference routines call this function to create video overlays to visualize - // regions of interest of the inference callback. - virtual void make_overlays(VideoOverlaySet& items) const = 0; - - // Return true if the inference session should stop. - // You must override at least one of the overloaded `process_frame()`. - virtual bool process_frame(const VideoSnapshot& frame); - // Return true if the inference session should stop. - // You must override at least one of the overloaded `process_frame()`. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp); - -}; - - - - -} -#endif +/* Visual Inference Callback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VisualInferenceCallback_H +#define PokemonAutomation_CommonTools_VisualInferenceCallback_H + +#include +#include "Common/Cpp/Time.h" +#include "InferenceCallback.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class ImageRGB32; +struct VideoSnapshot; +class VideoOverlaySet; + +// Base class for a visual inference object to be called perioridically by +// inference routines in InferenceRoutines.h. +class VisualInferenceCallback : public InferenceCallback{ +public: + VisualInferenceCallback(std::string label) + : InferenceCallback(InferenceType::VISUAL, std::move(label)) + {} + + // The inference routines call this function to create video overlays to visualize + // regions of interest of the inference callback. + virtual void make_overlays(VideoOverlaySet& items) const = 0; + + // Return true if the inference session should stop. + // You must override at least one of the overloaded `process_frame()`. + virtual bool process_frame(const VideoSnapshot& frame); + // Return true if the inference session should stop. + // You must override at least one of the overloaded `process_frame()`. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp); + +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp index 294ac3e912..b088207650 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp +++ b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.cpp @@ -1,130 +1,130 @@ -/* Audio Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "AudioInferencePivot.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -struct AudioInferencePivot::PeriodicCallback{ - Cancellable& scope; - std::atomic* set_when_triggered; - AudioInferenceCallback& callback; - std::chrono::milliseconds period; - - uint64_t last_seqnum = ~(uint64_t)0; - - StatAccumulatorI32 stats; - - PeriodicCallback( - Cancellable& p_scope, - std::atomic* p_set_when_triggered, - AudioInferenceCallback& p_callback, - std::chrono::milliseconds p_period - ) - : scope(p_scope) - , set_when_triggered(p_set_when_triggered) - , callback(p_callback) - , period(p_period) - {} -}; - - -AudioInferencePivot::AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher) - : PeriodicRunner(dispatcher) - , m_feed(feed) -{ - attach(scope); -} -AudioInferencePivot::~AudioInferencePivot(){ - detach(); - stop_thread(); -} -void AudioInferencePivot::add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - AudioInferenceCallback& callback, - std::chrono::milliseconds period -){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter != m_map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); - } - iter = m_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(&callback), - std::forward_as_tuple(scope, set_when_triggered, callback, period) - ).first; - try{ - PeriodicRunner::add_event(&iter->second, period); - }catch (...){ - m_map.erase(iter); - throw; - } -} -StatAccumulatorI32 AudioInferencePivot::remove_callback(AudioInferenceCallback& callback){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter == m_map.end()){ - return StatAccumulatorI32(); - } - StatAccumulatorI32 stats = iter->second.stats; - PeriodicRunner::remove_event(&iter->second); - m_map.erase(iter); - return stats; -} -void AudioInferencePivot::run(void* event, bool is_back_to_back) noexcept{ - PeriodicCallback& callback = *(PeriodicCallback*)event; - try{ - std::vector spectrums; - - if (callback.last_seqnum == ~(uint64_t)0){ -// cout << "m_last_timestamp == SIZE_MAX" << endl; - spectrums = m_feed.spectrums_latest(1); - }else{ -// cout << "(m_last_timestamp != SIZE_MAX" << endl; - // Note: in this file we never consider the case that stamp may overflow. - // It requires on the order of 1e10 years to overflow if we have about 25ms per stamp. - spectrums = m_feed.spectrums_since(callback.last_seqnum + 1); - } - if (spectrums.size() > 0){ - // spectrums[0] has the newest spectrum with the largest stamp: - callback.last_seqnum = spectrums[0].stamp; - } - - WallClock time0 = current_time(); - bool stop = callback.callback.process_spectrums(spectrums, m_feed); - WallClock time1 = current_time(); - callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); - if (stop){ - if (callback.set_when_triggered){ - InferenceCallback* expected = nullptr; - callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); - } - callback.scope.cancel(nullptr); - } - }catch (...){ - callback.scope.cancel(std::current_exception()); - } -} - - -OverlayStatSnapshot AudioInferencePivot::get_current(){ - return m_printer.get_snapshot("Audio Pivot Utilization:", this->current_utilization()); -} - - - - -} +/* Audio Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "AudioInferencePivot.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +struct AudioInferencePivot::PeriodicCallback{ + Cancellable& scope; + std::atomic* set_when_triggered; + AudioInferenceCallback& callback; + std::chrono::milliseconds period; + + uint64_t last_seqnum = ~(uint64_t)0; + + StatAccumulatorI32 stats; + + PeriodicCallback( + Cancellable& p_scope, + std::atomic* p_set_when_triggered, + AudioInferenceCallback& p_callback, + std::chrono::milliseconds p_period + ) + : scope(p_scope) + , set_when_triggered(p_set_when_triggered) + , callback(p_callback) + , period(p_period) + {} +}; + + +AudioInferencePivot::AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher) + : PeriodicRunner(dispatcher) + , m_feed(feed) +{ + attach(scope); +} +AudioInferencePivot::~AudioInferencePivot(){ + detach(); + stop_thread(); +} +void AudioInferencePivot::add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + AudioInferenceCallback& callback, + std::chrono::milliseconds period +){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter != m_map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); + } + iter = m_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(&callback), + std::forward_as_tuple(scope, set_when_triggered, callback, period) + ).first; + try{ + PeriodicRunner::add_event(&iter->second, period); + }catch (...){ + m_map.erase(iter); + throw; + } +} +StatAccumulatorI32 AudioInferencePivot::remove_callback(AudioInferenceCallback& callback){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter == m_map.end()){ + return StatAccumulatorI32(); + } + StatAccumulatorI32 stats = iter->second.stats; + PeriodicRunner::remove_event(&iter->second); + m_map.erase(iter); + return stats; +} +void AudioInferencePivot::run(void* event, bool is_back_to_back) noexcept{ + PeriodicCallback& callback = *(PeriodicCallback*)event; + try{ + std::vector spectrums; + + if (callback.last_seqnum == ~(uint64_t)0){ +// cout << "m_last_timestamp == SIZE_MAX" << endl; + spectrums = m_feed.spectrums_latest(1); + }else{ +// cout << "(m_last_timestamp != SIZE_MAX" << endl; + // Note: in this file we never consider the case that stamp may overflow. + // It requires on the order of 1e10 years to overflow if we have about 25ms per stamp. + spectrums = m_feed.spectrums_since(callback.last_seqnum + 1); + } + if (spectrums.size() > 0){ + // spectrums[0] has the newest spectrum with the largest stamp: + callback.last_seqnum = spectrums[0].stamp; + } + + WallClock time0 = current_time(); + bool stop = callback.callback.process_spectrums(spectrums, m_feed); + WallClock time1 = current_time(); + callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); + if (stop){ + if (callback.set_when_triggered){ + InferenceCallback* expected = nullptr; + callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); + } + callback.scope.cancel(nullptr); + } + }catch (...){ + callback.scope.cancel(std::current_exception()); + } +} + + +OverlayStatSnapshot AudioInferencePivot::get_current(){ + return m_printer.get_snapshot("Audio Pivot Utilization:", this->current_utilization()); +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h index ff6fd0b8bd..145266e9b1 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h +++ b/SerialPrograms/Source/CommonTools/InferencePivots/AudioInferencePivot.h @@ -1,60 +1,60 @@ -/* Audio Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_AudioInferencePivot_H -#define PokemonAutomation_CommonTools_AudioInferencePivot_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/PeriodicScheduler.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" -#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" - -namespace PokemonAutomation{ - -class AudioFeed; - - - -class AudioInferencePivot final : public PeriodicRunner, public OverlayStat{ -public: - AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher); - virtual ~AudioInferencePivot(); - - // If this callback returns true: - // 1. Cancel "scope". - // 2. Set "set_when_triggered" to the callback. - // If the callback throws an exception, "scope" will be cancelled with that exception. - void add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - AudioInferenceCallback& callback, - std::chrono::milliseconds period - ); - - // Returns the latency stats for the callback. Units are microseconds. - StatAccumulatorI32 remove_callback(AudioInferenceCallback& callback); - -private: - virtual void run(void* event, bool is_back_to_back) noexcept override; - virtual OverlayStatSnapshot get_current() override; - -private: - struct PeriodicCallback; - - AudioFeed& m_feed; - SpinLock m_lock; - std::map m_map; - -// uint64_t m_last_seqnum = ~(uint64_t)0; - - OverlayStatUtilizationPrinter m_printer; -}; - - - -} -#endif +/* Audio Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_AudioInferencePivot_H +#define PokemonAutomation_CommonTools_AudioInferencePivot_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/PeriodicScheduler.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" +#include "CommonTools/InferenceCallbacks/AudioInferenceCallback.h" + +namespace PokemonAutomation{ + +class AudioFeed; + + + +class AudioInferencePivot final : public PeriodicRunner, public OverlayStat{ +public: + AudioInferencePivot(CancellableScope& scope, AudioFeed& feed, AsyncDispatcher& dispatcher); + virtual ~AudioInferencePivot(); + + // If this callback returns true: + // 1. Cancel "scope". + // 2. Set "set_when_triggered" to the callback. + // If the callback throws an exception, "scope" will be cancelled with that exception. + void add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + AudioInferenceCallback& callback, + std::chrono::milliseconds period + ); + + // Returns the latency stats for the callback. Units are microseconds. + StatAccumulatorI32 remove_callback(AudioInferenceCallback& callback); + +private: + virtual void run(void* event, bool is_back_to_back) noexcept override; + virtual OverlayStatSnapshot get_current() override; + +private: + struct PeriodicCallback; + + AudioFeed& m_feed; + SpinLock m_lock; + std::map m_map; + +// uint64_t m_last_seqnum = ~(uint64_t)0; + + OverlayStatUtilizationPrinter m_printer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp index 9c6c778b2a..0e8867fab9 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp +++ b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.cpp @@ -1,122 +1,122 @@ -/* Visual Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "VisualInferencePivot.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -struct VisualInferencePivot::PeriodicCallback{ - Cancellable& scope; - std::atomic* set_when_triggered; - VisualInferenceCallback& callback; - std::chrono::milliseconds period; - StatAccumulatorI32 stats; - uint64_t last_seqnum; - - PeriodicCallback( - Cancellable& p_scope, - std::atomic* p_set_when_triggered, - VisualInferenceCallback& p_callback, - std::chrono::milliseconds p_period - ) - : scope(p_scope) - , set_when_triggered(p_set_when_triggered) - , callback(p_callback) - , period(p_period) - , last_seqnum(0) - {} -}; - - - -VisualInferencePivot::VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher) - : PeriodicRunner(dispatcher) - , m_feed(feed) -{ - attach(scope); -} -VisualInferencePivot::~VisualInferencePivot(){ - detach(); - stop_thread(); -} -void VisualInferencePivot::add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - VisualInferenceCallback& callback, - std::chrono::milliseconds period -){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter != m_map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); - } - iter = m_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(&callback), - std::forward_as_tuple(scope, set_when_triggered, callback, period) - ).first; - try{ - PeriodicRunner::add_event(&iter->second, period); - }catch (...){ - m_map.erase(iter); - throw; - } -} -StatAccumulatorI32 VisualInferencePivot::remove_callback(VisualInferenceCallback& callback){ - WriteSpinLock lg(m_lock); - auto iter = m_map.find(&callback); - if (iter == m_map.end()){ - return StatAccumulatorI32(); - } - StatAccumulatorI32 stats = iter->second.stats; - PeriodicRunner::remove_event(&iter->second); - m_map.erase(iter); - return stats; -} -void VisualInferencePivot::run(void* event, bool is_back_to_back) noexcept{ - PeriodicCallback& callback = *(PeriodicCallback*)event; - try{ - // Reuse the cached screenshot. - if (!is_back_to_back || callback.last_seqnum == m_seqnum){ -// cout << "back-to-back" << endl; - m_last = m_feed.snapshot(); - m_seqnum++; - } - - WallClock time0 = current_time(); - bool stop = callback.callback.process_frame(m_last); - WallClock time1 = current_time(); - callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); - callback.last_seqnum = m_seqnum; - if (stop){ - if (callback.set_when_triggered){ - InferenceCallback* expected = nullptr; - callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); - } - callback.scope.cancel(nullptr); - } - }catch (...){ - callback.scope.cancel(std::current_exception()); - } -} - - -OverlayStatSnapshot VisualInferencePivot::get_current(){ - return m_printer.get_snapshot("Video Pivot Utilization:", this->current_utilization()); -} - - - - -} +/* Visual Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VisualInferencePivot.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +struct VisualInferencePivot::PeriodicCallback{ + Cancellable& scope; + std::atomic* set_when_triggered; + VisualInferenceCallback& callback; + std::chrono::milliseconds period; + StatAccumulatorI32 stats; + uint64_t last_seqnum; + + PeriodicCallback( + Cancellable& p_scope, + std::atomic* p_set_when_triggered, + VisualInferenceCallback& p_callback, + std::chrono::milliseconds p_period + ) + : scope(p_scope) + , set_when_triggered(p_set_when_triggered) + , callback(p_callback) + , period(p_period) + , last_seqnum(0) + {} +}; + + + +VisualInferencePivot::VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher) + : PeriodicRunner(dispatcher) + , m_feed(feed) +{ + attach(scope); +} +VisualInferencePivot::~VisualInferencePivot(){ + detach(); + stop_thread(); +} +void VisualInferencePivot::add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + VisualInferenceCallback& callback, + std::chrono::milliseconds period +){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter != m_map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add the same callback twice."); + } + iter = m_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(&callback), + std::forward_as_tuple(scope, set_when_triggered, callback, period) + ).first; + try{ + PeriodicRunner::add_event(&iter->second, period); + }catch (...){ + m_map.erase(iter); + throw; + } +} +StatAccumulatorI32 VisualInferencePivot::remove_callback(VisualInferenceCallback& callback){ + WriteSpinLock lg(m_lock); + auto iter = m_map.find(&callback); + if (iter == m_map.end()){ + return StatAccumulatorI32(); + } + StatAccumulatorI32 stats = iter->second.stats; + PeriodicRunner::remove_event(&iter->second); + m_map.erase(iter); + return stats; +} +void VisualInferencePivot::run(void* event, bool is_back_to_back) noexcept{ + PeriodicCallback& callback = *(PeriodicCallback*)event; + try{ + // Reuse the cached screenshot. + if (!is_back_to_back || callback.last_seqnum == m_seqnum){ +// cout << "back-to-back" << endl; + m_last = m_feed.snapshot(); + m_seqnum++; + } + + WallClock time0 = current_time(); + bool stop = callback.callback.process_frame(m_last); + WallClock time1 = current_time(); + callback.stats += (uint32_t)std::chrono::duration_cast(time1 - time0).count(); + callback.last_seqnum = m_seqnum; + if (stop){ + if (callback.set_when_triggered){ + InferenceCallback* expected = nullptr; + callback.set_when_triggered->compare_exchange_strong(expected, &callback.callback); + } + callback.scope.cancel(nullptr); + } + }catch (...){ + callback.scope.cancel(std::current_exception()); + } +} + + +OverlayStatSnapshot VisualInferencePivot::get_current(){ + return m_printer.get_snapshot("Video Pivot Utilization:", this->current_utilization()); +} + + + + +} diff --git a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h index 74da017ad5..796495b9ae 100644 --- a/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h +++ b/SerialPrograms/Source/CommonTools/InferencePivots/VisualInferencePivot.h @@ -1,61 +1,61 @@ -/* Visual Inference Pivot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VisualInferencePivot_H -#define PokemonAutomation_CommonTools_VisualInferencePivot_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/PeriodicScheduler.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - -class VideoFeed; - - - -class VisualInferencePivot final : public PeriodicRunner, public OverlayStat{ -public: - VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher); - virtual ~VisualInferencePivot(); - - // If this callback returns true: - // 1. Cancel "scope". - // 2. Set "set_when_triggered" to the callback. - // If the callback throws an exception, "scope" will be cancelled with that exception. - void add_callback( - Cancellable& scope, - std::atomic* set_when_triggered, - VisualInferenceCallback& callback, - std::chrono::milliseconds period - ); - - // Returns the latency stats for the callback. Units are microseconds. - StatAccumulatorI32 remove_callback(VisualInferenceCallback& callback); - -private: - virtual void run(void* event, bool is_back_to_back) noexcept override; - virtual OverlayStatSnapshot get_current() override; - -private: - struct PeriodicCallback; - - VideoFeed& m_feed; - SpinLock m_lock; - std::map m_map; - VideoSnapshot m_last; - uint64_t m_seqnum = 0; - - OverlayStatUtilizationPrinter m_printer; -}; - - - -} -#endif +/* Visual Inference Pivot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VisualInferencePivot_H +#define PokemonAutomation_CommonTools_VisualInferencePivot_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/PeriodicScheduler.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + +class VideoFeed; + + + +class VisualInferencePivot final : public PeriodicRunner, public OverlayStat{ +public: + VisualInferencePivot(CancellableScope& scope, VideoFeed& feed, AsyncDispatcher& dispatcher); + virtual ~VisualInferencePivot(); + + // If this callback returns true: + // 1. Cancel "scope". + // 2. Set "set_when_triggered" to the callback. + // If the callback throws an exception, "scope" will be cancelled with that exception. + void add_callback( + Cancellable& scope, + std::atomic* set_when_triggered, + VisualInferenceCallback& callback, + std::chrono::milliseconds period + ); + + // Returns the latency stats for the callback. Units are microseconds. + StatAccumulatorI32 remove_callback(VisualInferenceCallback& callback); + +private: + virtual void run(void* event, bool is_back_to_back) noexcept override; + virtual OverlayStatSnapshot get_current() override; + +private: + struct PeriodicCallback; + + VideoFeed& m_feed; + SpinLock m_lock; + std::map m_map; + VideoSnapshot m_last; + uint64_t m_seqnum = 0; + + OverlayStatUtilizationPrinter m_printer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/InferenceThrottler.h b/SerialPrograms/Source/CommonTools/InferenceThrottler.h index d549d3edc3..a1ff066167 100644 --- a/SerialPrograms/Source/CommonTools/InferenceThrottler.h +++ b/SerialPrograms/Source/CommonTools/InferenceThrottler.h @@ -1,61 +1,61 @@ -/* Inference Throttler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_InferenceThrottler_H -#define PokemonAutomation_CommonTools_InferenceThrottler_H - -#include -#include "Common/Cpp/CancellableScope.h" - -namespace PokemonAutomation{ - -class InferenceThrottler{ -public: - InferenceThrottler( - std::chrono::milliseconds timeout, - std::chrono::milliseconds period = std::chrono::milliseconds(50) - ) - : m_timeout(timeout) - , m_period(period) - , m_start(current_time()) - , m_wait_until(m_start + period) - {} - - // Call at the end of each loop iteration. This will wait until the - // time since the previous iteration has reached the specified period. - // - // Returns true if this loop has timed out. - bool end_iteration(CancellableScope& scope){ - auto now = current_time(); - if (m_timeout != std::chrono::milliseconds(0) && now - m_start >= m_timeout){ - return true; - } - - std::chrono::milliseconds wait = std::chrono::duration_cast(m_wait_until - now); - if (wait <= std::chrono::milliseconds(0)){ - m_wait_until = now + m_period; - }else{ - m_wait_until += m_period; - scope.wait_for(wait); - } - return false; - } - - void set_period(std::chrono::milliseconds period){ - m_period = period; - } - -private: - std::chrono::milliseconds m_timeout; - std::chrono::milliseconds m_period; - WallClock m_start; - WallClock m_wait_until; -}; - - - -} -#endif +/* Inference Throttler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_InferenceThrottler_H +#define PokemonAutomation_CommonTools_InferenceThrottler_H + +#include +#include "Common/Cpp/CancellableScope.h" + +namespace PokemonAutomation{ + +class InferenceThrottler{ +public: + InferenceThrottler( + std::chrono::milliseconds timeout, + std::chrono::milliseconds period = std::chrono::milliseconds(50) + ) + : m_timeout(timeout) + , m_period(period) + , m_start(current_time()) + , m_wait_until(m_start + period) + {} + + // Call at the end of each loop iteration. This will wait until the + // time since the previous iteration has reached the specified period. + // + // Returns true if this loop has timed out. + bool end_iteration(CancellableScope& scope){ + auto now = current_time(); + if (m_timeout != std::chrono::milliseconds(0) && now - m_start >= m_timeout){ + return true; + } + + std::chrono::milliseconds wait = std::chrono::duration_cast(m_wait_until - now); + if (wait <= std::chrono::milliseconds(0)){ + m_wait_until = now + m_period; + }else{ + m_wait_until += m_period; + scope.wait_for(wait); + } + return false; + } + + void set_period(std::chrono::milliseconds period){ + m_period = period; + } + +private: + std::chrono::milliseconds m_timeout; + std::chrono::milliseconds m_period; + WallClock m_start; + WallClock m_wait_until; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp index 393d08e1fe..cbf4bc64ce 100644 --- a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp +++ b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.cpp @@ -1,31 +1,31 @@ -/* Multi-Console Errors - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "MultiConsoleErrors.h" - -namespace PokemonAutomation{ - - - -void MultiConsoleErrorState::report_unrecoverable_error(VideoStream& stream, std::string msg){ - stream.log(msg, COLOR_RED); - bool expected = false; - if (m_unrecoverable_error.compare_exchange_strong(expected, true)){ - m_message = msg; - } - OperationFailedException::fire(ErrorReport::SEND_ERROR_REPORT, std::move(msg), stream); -} -void MultiConsoleErrorState::check_unrecoverable_error(Logger& logger){ - if (m_unrecoverable_error.load(std::memory_order_acquire)){ - logger.log("Unrecoverable error reported from a different console. Breaking out.", COLOR_RED); - throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, m_message); - } -} - - - -} +/* Multi-Console Errors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "MultiConsoleErrors.h" + +namespace PokemonAutomation{ + + + +void MultiConsoleErrorState::report_unrecoverable_error(VideoStream& stream, std::string msg){ + stream.log(msg, COLOR_RED); + bool expected = false; + if (m_unrecoverable_error.compare_exchange_strong(expected, true)){ + m_message = msg; + } + OperationFailedException::fire(ErrorReport::SEND_ERROR_REPORT, std::move(msg), stream); +} +void MultiConsoleErrorState::check_unrecoverable_error(Logger& logger){ + if (m_unrecoverable_error.load(std::memory_order_acquire)){ + logger.log("Unrecoverable error reported from a different console. Breaking out.", COLOR_RED); + throw_and_log(logger, ErrorReport::NO_ERROR_REPORT, m_message); + } +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h index 573de98bb2..c00362fcf2 100644 --- a/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h +++ b/SerialPrograms/Source/CommonTools/MultiConsoleErrors.h @@ -1,33 +1,33 @@ -/* Multi-Console Errors - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_MultiConsoleErrors_H -#define PokemonAutomation_CommonTools_MultiConsoleErrors_H - -#include -#include - -namespace PokemonAutomation{ - -class Logger; -class VideoStream; - - -class MultiConsoleErrorState{ -public: - void report_unrecoverable_error(VideoStream& stream, std::string msg); - void check_unrecoverable_error(Logger& logger); - -private: - std::atomic m_unrecoverable_error; - std::string m_message; -}; - - - - -} -#endif +/* Multi-Console Errors + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_MultiConsoleErrors_H +#define PokemonAutomation_CommonTools_MultiConsoleErrors_H + +#include +#include + +namespace PokemonAutomation{ + +class Logger; +class VideoStream; + + +class MultiConsoleErrorState{ +public: + void report_unrecoverable_error(VideoStream& stream, std::string msg); + void check_unrecoverable_error(Logger& logger); + +private: + std::atomic m_unrecoverable_error; + std::string m_message; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp index 2c274a41d2..3123bbe9f2 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.cpp @@ -1,65 +1,65 @@ -/* Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "OCR_DictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -const DictionaryOCR& DictionaryMatcher::dictionary(Language language) const{ - auto iter = m_database.find(language); - if (iter == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); - } - return iter->second; -} -DictionaryOCR& DictionaryMatcher::dictionary(Language language){ - ReadSpinLock lg(m_lock, "LargeDictionaryMatcher::dictionary()"); - auto iter = m_database.find(language); - if (iter == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); - } - return iter->second; -} - - -StringMatchResult DictionaryMatcher::match_substring( - Language language, - const std::string& text, - double log10p_spread -) const{ - return dictionary(language).match_substring(text, log10p_spread); -} - -OCR::StringMatchResult DictionaryMatcher::match_substring_from_image_multifiltered( - Logger* logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio, double max_text_ratio -) const{ - OCR::StringMatchResult ret = OCR::multifiltered_OCR( - language, *this, image, - text_color_ranges, - log10p_spread, min_text_ratio, max_text_ratio - ); - if (logger){ - ret.log(*logger, max_log10p); - } - ret.clear_beyond_log10p(max_log10p); - return ret; -} - -void DictionaryMatcher::add_candidate(Language language, std::string token, const std::u32string& candidate){ - dictionary(language).add_candidate(std::move(token), candidate); -} - - -} -} +/* Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "OCR_DictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +const DictionaryOCR& DictionaryMatcher::dictionary(Language language) const{ + auto iter = m_database.find(language); + if (iter == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); + } + return iter->second; +} +DictionaryOCR& DictionaryMatcher::dictionary(Language language){ + ReadSpinLock lg(m_lock, "LargeDictionaryMatcher::dictionary()"); + auto iter = m_database.find(language); + if (iter == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Language not loaded."); + } + return iter->second; +} + + +StringMatchResult DictionaryMatcher::match_substring( + Language language, + const std::string& text, + double log10p_spread +) const{ + return dictionary(language).match_substring(text, log10p_spread); +} + +OCR::StringMatchResult DictionaryMatcher::match_substring_from_image_multifiltered( + Logger* logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio, double max_text_ratio +) const{ + OCR::StringMatchResult ret = OCR::multifiltered_OCR( + language, *this, image, + text_color_ranges, + log10p_spread, min_text_ratio, max_text_ratio + ); + if (logger){ + ret.log(*logger, max_log10p); + } + ret.clear_beyond_log10p(max_log10p); + return ret; +} + +void DictionaryMatcher::add_candidate(Language language, std::string token, const std::u32string& candidate){ + dictionary(language).add_candidate(std::move(token), candidate); +} + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h index 6890b7499b..179e557a38 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryMatcher.h @@ -1,79 +1,79 @@ -/* Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H -#define PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Language.h" -#include "OCR_Routines.h" -#include "OCR_DictionaryOCR.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace OCR{ - -// Base class for an OCR matcher. It matches a sub-string from a dictionary. -// The construction of the dictionary is left to the derived class. -class DictionaryMatcher{ -public: - const LanguageSet& languages() const{ return m_languages; } - - -public: - const DictionaryOCR& dictionary(Language language) const; - - - StringMatchResult match_substring( - Language language, - const std::string& text, double log10p_spread = 0.50 - ) const; - - // Match a substring from `image`. - // text_color_ranges: the function will try multiple attempts of separating - // text color and background color, and do OCR on the text with background color - // removed. The text color range of attempt is specified by each element in - // `text_color_ranges`. - // max_log10p: Threshold for finding any valid match. - // The raw OCR result gives a probability for each dictionary key. The probility p - // is that if this key is matched by accident. The lower this value, the closer - // the match. Apply log10() to it to get log10p. - // If all keys' log10p is above this `max_log10p`, there will be no match. - // log10p_spread: threshold for considering ambiguous match. - // It specifies the minimum separation between the best candidate and - // 2nd best candidate's log10p for it to not be considered ambiguous. - // min/max_text_ratio: min/max_text_ratio is the range where the ratio of text color - // pixel count to background color pixel count must fall into before the matcher - // even attempts to OCR. This is useful for pruning images with no appearant texts to - // reduce expensive OCR computation. - OCR::StringMatchResult match_substring_from_image_multifiltered( - Logger* logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread = 0.5, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - - -public: - // These functions are thread-safe with themselves, but not with any other - // functions in this class. - DictionaryOCR& dictionary(Language language); - void add_candidate(Language language, std::string token, const std::u32string& candidate); - - -protected: - LanguageSet m_languages; - std::map m_database; - SpinLock m_lock; -}; - - -} -} -#endif +/* Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H +#define PokemonAutomation_CommonTools_OCR_DictionaryMatcher_H + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Language.h" +#include "OCR_Routines.h" +#include "OCR_DictionaryOCR.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace OCR{ + +// Base class for an OCR matcher. It matches a sub-string from a dictionary. +// The construction of the dictionary is left to the derived class. +class DictionaryMatcher{ +public: + const LanguageSet& languages() const{ return m_languages; } + + +public: + const DictionaryOCR& dictionary(Language language) const; + + + StringMatchResult match_substring( + Language language, + const std::string& text, double log10p_spread = 0.50 + ) const; + + // Match a substring from `image`. + // text_color_ranges: the function will try multiple attempts of separating + // text color and background color, and do OCR on the text with background color + // removed. The text color range of attempt is specified by each element in + // `text_color_ranges`. + // max_log10p: Threshold for finding any valid match. + // The raw OCR result gives a probability for each dictionary key. The probility p + // is that if this key is matched by accident. The lower this value, the closer + // the match. Apply log10() to it to get log10p. + // If all keys' log10p is above this `max_log10p`, there will be no match. + // log10p_spread: threshold for considering ambiguous match. + // It specifies the minimum separation between the best candidate and + // 2nd best candidate's log10p for it to not be considered ambiguous. + // min/max_text_ratio: min/max_text_ratio is the range where the ratio of text color + // pixel count to background color pixel count must fall into before the matcher + // even attempts to OCR. This is useful for pruning images with no appearant texts to + // reduce expensive OCR computation. + OCR::StringMatchResult match_substring_from_image_multifiltered( + Logger* logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread = 0.5, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + + +public: + // These functions are thread-safe with themselves, but not with any other + // functions in this class. + DictionaryOCR& dictionary(Language language); + void add_candidate(Language language, std::string token, const std::u32string& candidate); + + +protected: + LanguageSet m_languages; + std::map m_database; + SpinLock m_lock; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp index b658a94688..f5752076b6 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.cpp @@ -1,131 +1,131 @@ -/* Dictionary OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Logging/Logger.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" -#include "OCR_DictionaryOCR.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -DictionaryOCR::DictionaryOCR( - const JsonObject& json, - const std::set* subset, - double random_match_chance, - bool first_only -) - : m_random_match_chance(random_match_chance) -{ - for (const auto& item0 : json){ - const std::string& token = item0.first; - if (subset != nullptr && subset->find(token) == subset->end()){ - continue; - } - std::vector& candidates = m_database[token]; - for (const auto& item1 : item0.second.to_array_throw()){ - const std::string& candidate = item1.to_string_throw(); - std::u32string normalized = normalize_utf32(candidate); - std::set& set = m_candidate_to_token[normalized]; - if (!set.empty()){ - global_logger_tagged().log("DictionaryOCR - Duplicate Candidate: " + token + " (" + to_utf8(normalized) + ")"); -// cout << "Duplicate Candidate: " << candidate << endl; - } - set.insert(token); - candidates.emplace_back(candidate); - if (first_only){ - break; - } - } - } - global_logger_tagged().log( - "DictionaryOCR - Tokens: " + std::to_string(m_database.size()) + - ", Match Candidates: " + std::to_string(m_candidate_to_token.size()) - ); -// cout << "Tokens: " << m_database.size() << ", Match Candidates: " << m_candidate_to_token.size() << endl; -} -DictionaryOCR::DictionaryOCR( - const std::string& json_path, - const std::set* subset, - double random_match_chance, - bool first_only -) - : DictionaryOCR( - load_json_file(json_path).to_object_throw(json_path), - subset, - random_match_chance, - first_only - ) -{} - -JsonObject DictionaryOCR::to_json() const{ - JsonObject obj; - for (const auto& item : m_database){ - JsonArray list; - for (const std::string& candidate : item.second){ - list.push_back(candidate); - } - obj[item.first] = std::move(list); - } - return obj; -} -void DictionaryOCR::save_json(const std::string& json_path) const{ - to_json().dump(json_path); -} - - - -StringMatchResult DictionaryOCR::match_substring( - const std::string& text, - double log10p_spread -) const{ - return OCR::match_substring( - m_candidate_to_token, m_random_match_chance, - text, log10p_spread - ); -} -void DictionaryOCR::add_candidate(std::string token, const std::u32string& candidate){ - if (candidate.size() < 2){ - return; - } - - WriteSpinLock lg(m_lock, "DictionaryOCR::add_candidate()"); - - auto iter = m_candidate_to_token.find(candidate); - if (iter == m_candidate_to_token.end()){ - // New candidate. Add it to both maps. - m_database[token].emplace_back(to_utf8(candidate)); - m_candidate_to_token[candidate].insert(std::move(token)); - return; - } - - // Candidate already exists in table. - std::set& tokens = iter->second; - if (tokens.find(token) == tokens.end()){ - // Add to database only if it isn't already there. - m_database[token].emplace_back(to_utf8(candidate)); - } - - tokens.insert(std::move(token)); -} - - - - - - -} -} +/* Dictionary OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Logging/Logger.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" +#include "OCR_DictionaryOCR.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +DictionaryOCR::DictionaryOCR( + const JsonObject& json, + const std::set* subset, + double random_match_chance, + bool first_only +) + : m_random_match_chance(random_match_chance) +{ + for (const auto& item0 : json){ + const std::string& token = item0.first; + if (subset != nullptr && subset->find(token) == subset->end()){ + continue; + } + std::vector& candidates = m_database[token]; + for (const auto& item1 : item0.second.to_array_throw()){ + const std::string& candidate = item1.to_string_throw(); + std::u32string normalized = normalize_utf32(candidate); + std::set& set = m_candidate_to_token[normalized]; + if (!set.empty()){ + global_logger_tagged().log("DictionaryOCR - Duplicate Candidate: " + token + " (" + to_utf8(normalized) + ")"); +// cout << "Duplicate Candidate: " << candidate << endl; + } + set.insert(token); + candidates.emplace_back(candidate); + if (first_only){ + break; + } + } + } + global_logger_tagged().log( + "DictionaryOCR - Tokens: " + std::to_string(m_database.size()) + + ", Match Candidates: " + std::to_string(m_candidate_to_token.size()) + ); +// cout << "Tokens: " << m_database.size() << ", Match Candidates: " << m_candidate_to_token.size() << endl; +} +DictionaryOCR::DictionaryOCR( + const std::string& json_path, + const std::set* subset, + double random_match_chance, + bool first_only +) + : DictionaryOCR( + load_json_file(json_path).to_object_throw(json_path), + subset, + random_match_chance, + first_only + ) +{} + +JsonObject DictionaryOCR::to_json() const{ + JsonObject obj; + for (const auto& item : m_database){ + JsonArray list; + for (const std::string& candidate : item.second){ + list.push_back(candidate); + } + obj[item.first] = std::move(list); + } + return obj; +} +void DictionaryOCR::save_json(const std::string& json_path) const{ + to_json().dump(json_path); +} + + + +StringMatchResult DictionaryOCR::match_substring( + const std::string& text, + double log10p_spread +) const{ + return OCR::match_substring( + m_candidate_to_token, m_random_match_chance, + text, log10p_spread + ); +} +void DictionaryOCR::add_candidate(std::string token, const std::u32string& candidate){ + if (candidate.size() < 2){ + return; + } + + WriteSpinLock lg(m_lock, "DictionaryOCR::add_candidate()"); + + auto iter = m_candidate_to_token.find(candidate); + if (iter == m_candidate_to_token.end()){ + // New candidate. Add it to both maps. + m_database[token].emplace_back(to_utf8(candidate)); + m_candidate_to_token[candidate].insert(std::move(token)); + return; + } + + // Candidate already exists in table. + std::set& tokens = iter->second; + if (tokens.find(token) == tokens.end()){ + // Add to database only if it isn't already there. + m_database[token].emplace_back(to_utf8(candidate)); + } + + tokens.insert(std::move(token)); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h index b95e796fbb..7db1038743 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_DictionaryOCR.h @@ -1,61 +1,61 @@ -/* Dictionary OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_DictionaryOCR_H -#define PokemonAutomation_CommonTools_OCR_DictionaryOCR_H - -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "OCR_StringMatchResult.h" - -namespace PokemonAutomation{ - class JsonObject; -namespace OCR{ - - -class DictionaryOCR{ -public: - DictionaryOCR( - const JsonObject& json, - const std::set* subset, - double random_match_chance, - bool first_only - ); - DictionaryOCR( - const std::string& json_path, - const std::set* subset, - double random_match_chance, - bool first_only - ); - - JsonObject to_json() const; - void save_json(const std::string& json_path) const; - - StringMatchResult match_substring(const std::string& text, double log10p_spread = 0.50) const; - - -public: - // This function is thread-safe with itself, but not with any other - // function in this class. - - void add_candidate(std::string token, const std::u32string& candidate); - - -private: - SpinLock m_lock; - double m_random_match_chance; - std::map> m_database; - std::map> m_candidate_to_token; -}; - - - - -} -} -#endif +/* Dictionary OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_DictionaryOCR_H +#define PokemonAutomation_CommonTools_OCR_DictionaryOCR_H + +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "OCR_StringMatchResult.h" + +namespace PokemonAutomation{ + class JsonObject; +namespace OCR{ + + +class DictionaryOCR{ +public: + DictionaryOCR( + const JsonObject& json, + const std::set* subset, + double random_match_chance, + bool first_only + ); + DictionaryOCR( + const std::string& json_path, + const std::set* subset, + double random_match_chance, + bool first_only + ); + + JsonObject to_json() const; + void save_json(const std::string& json_path) const; + + StringMatchResult match_substring(const std::string& text, double log10p_spread = 0.50) const; + + +public: + // This function is thread-safe with itself, but not with any other + // function in this class. + + void add_candidate(std::string token, const std::u32string& candidate); + + +private: + SpinLock m_lock; + double m_random_match_chance; + std::map> m_database; + std::map> m_candidate_to_token; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp index f14f9a76bc..43c1513aff 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.cpp @@ -1,49 +1,49 @@ -/* Large Database Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Globals.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" -#include "OCR_LargeDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - - - -LargeDictionaryMatcher::LargeDictionaryMatcher( - const std::string& json_file_prefix, - const std::set* subset, - bool first_only -){ - std::string prefix = RESOURCE_PATH() + json_file_prefix; - for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ - Language language = (Language)c; - const LanguageData& data = language_data(language); - const std::string& code = data.code; - try{ - m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(language), - std::forward_as_tuple(prefix + code + ".json", subset, data.random_match_chance, first_only) - ); - m_languages += language; - }catch (FileException&){} - } -} - -void LargeDictionaryMatcher::save(Language language, const std::string& json_path) const{ - dictionary(language).save_json(json_path); -} - - - - - - -} -} +/* Large Database Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Globals.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" +#include "OCR_LargeDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + + + +LargeDictionaryMatcher::LargeDictionaryMatcher( + const std::string& json_file_prefix, + const std::set* subset, + bool first_only +){ + std::string prefix = RESOURCE_PATH() + json_file_prefix; + for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ + Language language = (Language)c; + const LanguageData& data = language_data(language); + const std::string& code = data.code; + try{ + m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(language), + std::forward_as_tuple(prefix + code + ".json", subset, data.random_match_chance, first_only) + ); + m_languages += language; + }catch (FileException&){} + } +} + +void LargeDictionaryMatcher::save(Language language, const std::string& json_path) const{ + dictionary(language).save_json(json_path); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h index 94eaac1ea2..850c0a0d09 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_LargeDictionaryMatcher.h @@ -1,47 +1,47 @@ -/* Large Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H -#define PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H - -#include "OCR_DictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - -// An OCR matcher with a small dictionary. -// Since the dictionary is large, each languages of the dictionary is stored as a -// separate JSON file. -class LargeDictionaryMatcher : public DictionaryMatcher{ -public: - // Load the JSON file to build the dictionary for all languages stored in each - // language JSON file. - // json_file_prefix: the file path prefix for all the language JSON files. - // subset: if not nullptr, only add keys in this `subset` to the dictionary. - // otherwise, add all keys found in the JSON to the dictionary. - // first_only: whether to use only the first value for each slug. - // This parameter is only useful for training the OCR. - // During inference, we set `first_only` to false so that each slug corresponds to - // all the values in that dictionary entry. - // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, - // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], - // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. - // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. - LargeDictionaryMatcher( - const std::string& json_file_prefix, - const std::set* subset, - bool first_only - ); - - void save(Language language, const std::string& json_path) const; - -private: -}; - - -} -} -#endif +/* Large Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H +#define PokemonAutomation_CommonTools_OCR_LargeDictionaryMatcher_H + +#include "OCR_DictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + +// An OCR matcher with a small dictionary. +// Since the dictionary is large, each languages of the dictionary is stored as a +// separate JSON file. +class LargeDictionaryMatcher : public DictionaryMatcher{ +public: + // Load the JSON file to build the dictionary for all languages stored in each + // language JSON file. + // json_file_prefix: the file path prefix for all the language JSON files. + // subset: if not nullptr, only add keys in this `subset` to the dictionary. + // otherwise, add all keys found in the JSON to the dictionary. + // first_only: whether to use only the first value for each slug. + // This parameter is only useful for training the OCR. + // During inference, we set `first_only` to false so that each slug corresponds to + // all the values in that dictionary entry. + // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, + // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], + // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. + // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. + LargeDictionaryMatcher( + const std::string& json_file_prefix, + const std::set* subset, + bool first_only + ); + + void save(Language language, const std::string& json_path) const; + +private: +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp index 670fcef568..9291112345 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.cpp @@ -1,252 +1,252 @@ -/* OCR Number Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Qt/StringToolsQt.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/ImageManip.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "OCR_RawOCR.h" -#include "OCR_NumberReader.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - -std::string run_number_normalization(const std::string& input){ - static const std::map SUBSTITUTION_TABLE{ - {'0', '0'}, - {'1', '1'}, - {'2', '2'}, - {'3', '3'}, - {'4', '4'}, - {'5', '5'}, - {'6', '6'}, - {'7', '7'}, - {'8', '8'}, - {'9', '9'}, - - // Common misreads. - {'|', '1'}, - {']', '1'}, - {'l', '1'}, - {'i', '1'}, - {'A', '4'}, - {'a', '4'}, - {'S', '5'}, - {'s', '5'}, - {'/', '7'}, - {'g', '9'}, - - // Japanese OCR likes to do this. - {U'🄋', '0'}, - {U'①', '1'}, - {U'②', '2'}, - {U'③', '3'}, - {U'④', '4'}, - {U'⑤', '5'}, - {U'⑥', '6'}, - {U'⑦', '7'}, - {U'⑧', '8'}, - {U'⑨', '9'}, - }; - - std::string normalized; - for (char32_t ch : to_utf32(input)){ - auto iter = SUBSTITUTION_TABLE.find(ch); - if (iter == SUBSTITUTION_TABLE.end()){ - continue; - } - normalized += iter->second; - } - - return normalized; -} - - -int read_number(Logger& logger, const ImageViewRGB32& image, Language language){ - std::string ocr_text = OCR::ocr_read(language, image); - std::string normalized = run_number_normalization(ocr_text); - - std::string str; - for (char ch : ocr_text){ - if (ch != '\r' && ch != '\n'){ - str += ch; - } - } - - if (normalized.empty()){ - logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); - return -1; - } - - int number = std::atoi(normalized.c_str()); - logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); - - return number; -} - -int read_number_waterfill( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range, - int8_t line_index -){ - std::string ocr_text = read_number_waterfill_no_normalization(logger, image, rgb32_min, rgb32_max, text_inside_range, UINT32_MAX, false); - - std::string normalized = run_number_normalization(ocr_text); - - std::string line_index_str = ""; - if (line_index != -1){ - line_index_str = "Line " + std::to_string(line_index) + ": "; - } - if (normalized.empty()){ - logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); - return -1; - } - - int number = std::atoi(normalized.c_str()); - logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); - - return number; -} - - -std::string read_number_waterfill_no_normalization( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range, - uint32_t width_max, - bool check_empty_string -){ - using namespace Kernels::Waterfill; - - // Direct OCR is unreliable. Instead, we will waterfill each character - // to isolate them, then OCR them individually. - - ImageRGB32 filtered = to_blackwhite_rgb32_range( - image, - text_inside_range, - rgb32_min, rgb32_max - ); - -// static int c = 0; -// filtered.save("zztest-" + std::to_string(c++) + ".png"); -// int i = 0; - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(filtered, 0xff000000, 0xff7f7f7f); - - std::map map; - { - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (map.size() < 16 && iter->find_next(object, true)){ - if (object.width() > width_max){ - logger.log("OCR fail: one of characters exceeded max width.", COLOR_RED); - return ""; - } - map.emplace(object.min_x, std::move(object)); - } - } - - std::string ocr_text; - for (const auto& item : map){ - const WaterfillObject& object = item.second; - ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); - PackedBinaryMatrix tmp(object.packed_matrix()); - filter_by_mask(tmp, cropped, Color(0xffffffff), true); - ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); - std::string ocr = OCR::ocr_read(Language::English, padded); - // padded.save("zztest-cropped" + std::to_string(c) + "-" + std::to_string(i++) + ".png"); - // std::cout << ocr[0] << std::endl; - if (!ocr.empty()){ - ocr_text += ocr[0]; - }else{ - if (check_empty_string){ - logger.log("OCR fail: one of characters read as empty string.", COLOR_RED); - return ""; - } - } - } - - return ocr_text; - -} - -bool is_digits(const std::string &str) -{ - return std::all_of(str.begin(), str.end(), ::isdigit); -} - -int read_number_waterfill_multifilter( - Logger& logger, const ImageViewRGB32& image, - std::vector> filters, - uint32_t width_max, - bool text_inside_range, - bool prioritize_numeric_only_results, - int8_t line_index -){ - std::string line_index_str = ""; - if (line_index != -1){ - line_index_str = "Line " + std::to_string(line_index) + ": "; - } - - std::map candidates; - for (std::pair filter : filters){ - - uint32_t rgb32_min = filter.first; - uint32_t rgb32_max = filter.second; - std::string ocr_text = read_number_waterfill_no_normalization(logger, image, rgb32_min, rgb32_max, text_inside_range, width_max, true); - - std::string normalized = run_number_normalization(ocr_text); - if (normalized.empty()){ - // logger.log("OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); - continue; - } - - int candidate = std::atoi(normalized.c_str()); - logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(candidate)); - - if (prioritize_numeric_only_results && is_digits(ocr_text)){ - candidates[candidate] += 2; - }else{ - candidates[candidate]++; - } - } - - if (candidates.empty()){ - logger.log(line_index_str + "No valid OCR candidates. Unable to read number.", COLOR_ORANGE); - return -1; - } - - std::pair best; - for (const auto& item : candidates){ - logger.log(line_index_str + "Candidate " + std::to_string(item.first) + ": " + std::to_string(item.second) + " votes"); - if (item.second > best.second){ - best = item; - } - } - - logger.log(line_index_str + "Best candidate: --------------------------> " + std::to_string(best.first)); - return best.first; -} - - - - -} -} +/* OCR Number Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Qt/StringToolsQt.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/ImageManip.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "OCR_RawOCR.h" +#include "OCR_NumberReader.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + +std::string run_number_normalization(const std::string& input){ + static const std::map SUBSTITUTION_TABLE{ + {'0', '0'}, + {'1', '1'}, + {'2', '2'}, + {'3', '3'}, + {'4', '4'}, + {'5', '5'}, + {'6', '6'}, + {'7', '7'}, + {'8', '8'}, + {'9', '9'}, + + // Common misreads. + {'|', '1'}, + {']', '1'}, + {'l', '1'}, + {'i', '1'}, + {'A', '4'}, + {'a', '4'}, + {'S', '5'}, + {'s', '5'}, + {'/', '7'}, + {'g', '9'}, + + // Japanese OCR likes to do this. + {U'🄋', '0'}, + {U'①', '1'}, + {U'②', '2'}, + {U'③', '3'}, + {U'④', '4'}, + {U'⑤', '5'}, + {U'⑥', '6'}, + {U'⑦', '7'}, + {U'⑧', '8'}, + {U'⑨', '9'}, + }; + + std::string normalized; + for (char32_t ch : to_utf32(input)){ + auto iter = SUBSTITUTION_TABLE.find(ch); + if (iter == SUBSTITUTION_TABLE.end()){ + continue; + } + normalized += iter->second; + } + + return normalized; +} + + +int read_number(Logger& logger, const ImageViewRGB32& image, Language language){ + std::string ocr_text = OCR::ocr_read(language, image); + std::string normalized = run_number_normalization(ocr_text); + + std::string str; + for (char ch : ocr_text){ + if (ch != '\r' && ch != '\n'){ + str += ch; + } + } + + if (normalized.empty()){ + logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); + return -1; + } + + int number = std::atoi(normalized.c_str()); + logger.log("OCR Text: \"" + str + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); + + return number; +} + +int read_number_waterfill( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range, + int8_t line_index +){ + std::string ocr_text = read_number_waterfill_no_normalization(logger, image, rgb32_min, rgb32_max, text_inside_range, UINT32_MAX, false); + + std::string normalized = run_number_normalization(ocr_text); + + std::string line_index_str = ""; + if (line_index != -1){ + line_index_str = "Line " + std::to_string(line_index) + ": "; + } + if (normalized.empty()){ + logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); + return -1; + } + + int number = std::atoi(normalized.c_str()); + logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(number)); + + return number; +} + + +std::string read_number_waterfill_no_normalization( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range, + uint32_t width_max, + bool check_empty_string +){ + using namespace Kernels::Waterfill; + + // Direct OCR is unreliable. Instead, we will waterfill each character + // to isolate them, then OCR them individually. + + ImageRGB32 filtered = to_blackwhite_rgb32_range( + image, + text_inside_range, + rgb32_min, rgb32_max + ); + +// static int c = 0; +// filtered.save("zztest-" + std::to_string(c++) + ".png"); +// int i = 0; + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(filtered, 0xff000000, 0xff7f7f7f); + + std::map map; + { + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (map.size() < 16 && iter->find_next(object, true)){ + if (object.width() > width_max){ + logger.log("OCR fail: one of characters exceeded max width.", COLOR_RED); + return ""; + } + map.emplace(object.min_x, std::move(object)); + } + } + + std::string ocr_text; + for (const auto& item : map){ + const WaterfillObject& object = item.second; + ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); + PackedBinaryMatrix tmp(object.packed_matrix()); + filter_by_mask(tmp, cropped, Color(0xffffffff), true); + ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); + std::string ocr = OCR::ocr_read(Language::English, padded); + // padded.save("zztest-cropped" + std::to_string(c) + "-" + std::to_string(i++) + ".png"); + // std::cout << ocr[0] << std::endl; + if (!ocr.empty()){ + ocr_text += ocr[0]; + }else{ + if (check_empty_string){ + logger.log("OCR fail: one of characters read as empty string.", COLOR_RED); + return ""; + } + } + } + + return ocr_text; + +} + +bool is_digits(const std::string &str) +{ + return std::all_of(str.begin(), str.end(), ::isdigit); +} + +int read_number_waterfill_multifilter( + Logger& logger, const ImageViewRGB32& image, + std::vector> filters, + uint32_t width_max, + bool text_inside_range, + bool prioritize_numeric_only_results, + int8_t line_index +){ + std::string line_index_str = ""; + if (line_index != -1){ + line_index_str = "Line " + std::to_string(line_index) + ": "; + } + + std::map candidates; + for (std::pair filter : filters){ + + uint32_t rgb32_min = filter.first; + uint32_t rgb32_max = filter.second; + std::string ocr_text = read_number_waterfill_no_normalization(logger, image, rgb32_min, rgb32_max, text_inside_range, width_max, true); + + std::string normalized = run_number_normalization(ocr_text); + if (normalized.empty()){ + // logger.log("OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> Unable to read.", COLOR_RED); + continue; + } + + int candidate = std::atoi(normalized.c_str()); + logger.log(line_index_str + "OCR Text: \"" + ocr_text + "\" -> \"" + normalized + "\" -> " + std::to_string(candidate)); + + if (prioritize_numeric_only_results && is_digits(ocr_text)){ + candidates[candidate] += 2; + }else{ + candidates[candidate]++; + } + } + + if (candidates.empty()){ + logger.log(line_index_str + "No valid OCR candidates. Unable to read number.", COLOR_ORANGE); + return -1; + } + + std::pair best; + for (const auto& item : candidates){ + logger.log(line_index_str + "Candidate " + std::to_string(item.first) + ": " + std::to_string(item.second) + " votes"); + if (item.second > best.second){ + best = item; + } + } + + logger.log(line_index_str + "Best candidate: --------------------------> " + std::to_string(best.first)); + return best.first; +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h index af9de2981e..bc22ce6b2f 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_NumberReader.h @@ -1,73 +1,73 @@ -/* OCR Number Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_NumberReader_H -#define PokemonAutomation_CommonTools_OCR_NumberReader_H - -#include -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ - class Logger; - class ImageViewRGB32; -namespace OCR{ - - -// Returns -1 if no number is found. -// No processing is done on the image. It is OCR'ed directly. -// The best way to use read_number() is to not give Language as a parameter. -// This is because the default language is English, since it works best for OCR for numbers. -int read_number(Logger& logger, const ImageViewRGB32& image, Language language = Language::English); - - -// This version attempts to improve reliability by first isolating each number -// via waterfill. Then it OCRs each number by itself and recombines them at the -// end. This requires specifying the color range for the text. -// -// line_index: specifies the current number's row. for logging purposes, when multithreaded. -int read_number_waterfill( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range = true, - int8_t line_index = -1 - ); - -// run OCR on each individual character in the string of numbers. -// return empty string if OCR fails -// -// text_inside_range: binary filter is applied to the image so that any pixels within the color range will be turned black, and everything else will be white -// width_max: return empty string if any character's width is greater than width_max (likely means that two characters are touching, and so are treated as one large character) -// check_empty_string: if set to true, return empty string (and stop evaluation) if any character returns an empty string from OCR - std::string read_number_waterfill_no_normalization( - Logger& logger, const ImageViewRGB32& image, - uint32_t rgb32_min, uint32_t rgb32_max, - bool text_inside_range = true, - uint32_t width_max = UINT32_MAX, - bool check_empty_string = false - ); - -// Try OCR with all the given color filters. still running OCR on each individual character -// Return the best majority candidate. return -1 if failed to read. -// -// prioritize_numeric_only_results: -// - if true: if OCR reads only numeric characters, the candidate gets 2 votes. If OCR reads non-numeric characters, the candidate gets only 1 vote. -// - if false: all reads only get 1 vote -// -// line_index: specifies the current number's row. for logging purposes, when multithreaded. -int read_number_waterfill_multifilter( - Logger& logger, const ImageViewRGB32& image, - std::vector> filters, - uint32_t width_max, - bool text_inside_range = true, - bool prioritize_numeric_only_results = true, - int8_t line_index = -1 - ); - - -} -} -#endif +/* OCR Number Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_NumberReader_H +#define PokemonAutomation_CommonTools_OCR_NumberReader_H + +#include +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ + class Logger; + class ImageViewRGB32; +namespace OCR{ + + +// Returns -1 if no number is found. +// No processing is done on the image. It is OCR'ed directly. +// The best way to use read_number() is to not give Language as a parameter. +// This is because the default language is English, since it works best for OCR for numbers. +int read_number(Logger& logger, const ImageViewRGB32& image, Language language = Language::English); + + +// This version attempts to improve reliability by first isolating each number +// via waterfill. Then it OCRs each number by itself and recombines them at the +// end. This requires specifying the color range for the text. +// +// line_index: specifies the current number's row. for logging purposes, when multithreaded. +int read_number_waterfill( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range = true, + int8_t line_index = -1 + ); + +// run OCR on each individual character in the string of numbers. +// return empty string if OCR fails +// +// text_inside_range: binary filter is applied to the image so that any pixels within the color range will be turned black, and everything else will be white +// width_max: return empty string if any character's width is greater than width_max (likely means that two characters are touching, and so are treated as one large character) +// check_empty_string: if set to true, return empty string (and stop evaluation) if any character returns an empty string from OCR + std::string read_number_waterfill_no_normalization( + Logger& logger, const ImageViewRGB32& image, + uint32_t rgb32_min, uint32_t rgb32_max, + bool text_inside_range = true, + uint32_t width_max = UINT32_MAX, + bool check_empty_string = false + ); + +// Try OCR with all the given color filters. still running OCR on each individual character +// Return the best majority candidate. return -1 if failed to read. +// +// prioritize_numeric_only_results: +// - if true: if OCR reads only numeric characters, the candidate gets 2 votes. If OCR reads non-numeric characters, the candidate gets only 1 vote. +// - if false: all reads only get 1 vote +// +// line_index: specifies the current number's row. for logging purposes, when multithreaded. +int read_number_waterfill_multifilter( + Logger& logger, const ImageViewRGB32& image, + std::vector> filters, + uint32_t width_max, + bool text_inside_range = true, + bool prioritize_numeric_only_results = true, + int8_t line_index = -1 + ); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp index bb3a72505b..95cc5bf17d 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.cpp @@ -1,205 +1,205 @@ -/* Raw Text Recognition - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "3rdParty/TesseractPA/TesseractPA.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "OCR_RawOCR.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - - -bool language_available(Language language){ - std::string path = RESOURCE_PATH(); - path += "Tesseract/"; - path += language_data(language).code; - path += ".traineddata"; - QFile file(QString::fromStdString(path)); - return file.exists(); -} - - - -class TesseractPool{ -public: - TesseractPool(Language language) - : m_language_code(language_data(language).code) - , m_training_data_path( - QDir::current().relativeFilePath(QString::fromStdString(RESOURCE_PATH() + "Tesseract/")).toStdString() - ) - {} - - std::string run(const ImageViewRGB32& image){ - TesseractAPI* instance; - while (true){ - { - WriteSpinLock lg(m_lock, "TesseractPool::run()"); - if (!m_idle.empty()){ - instance = m_idle.back(); - m_idle.pop_back(); - break; - } - } - add_instance(); - } - -// auto start = current_time(); - TesseractString str = instance->read32( - (const unsigned char*)image.data(), - image.width(), - image.height(), - image.bytes_per_row() - ); -// auto end = current_time(); -// cout << std::chrono::duration_cast(end - start).count() << endl; - - { - WriteSpinLock lg(m_lock, "TesseractPool::run()"); - m_idle.emplace_back(instance); - } - - return str.c_str() == nullptr - ? std::string() - : str.c_str(); - } - - void add_instance(){ - // Check for non-ascii characters in path. - for (char ch : m_training_data_path){ - if (ch < 0){ - throw InternalSystemError( - nullptr, PA_CURRENT_FUNCTION, - "Detected non-ASCII character in Tesseract path. Please move the program to a path with only ASCII characters." - ); - } - } - - global_logger_tagged().log( - "Initializing TesseractAPI (" + m_language_code + "): " + m_training_data_path - ); - std::unique_ptr api( - new TesseractAPI(m_training_data_path.c_str(), m_language_code.c_str()) - ); - if (!api->valid()){ - throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Could not initialize TesseractAPI."); - } - - WriteSpinLock lg(m_lock, "TesseractPool::run()"); - - m_instances.emplace_back(std::move(api)); - try{ - m_idle.emplace_back(m_instances.back().get()); - }catch (...){ - m_instances.pop_back(); - throw; - } - } - - void ensure_instances(size_t instances){ - size_t current_instances; - while (true){ - { - ReadSpinLock lg(m_lock, "TesseractPool::run()"); - current_instances = m_instances.size(); - } - if (current_instances >= instances){ - break; - } - add_instance(); - } - } - -#ifdef __APPLE__ -#ifdef UNIX_LINK_TESSERACT - ~TesseractPool(){ - // As of Feb 05, 2022, the newest Tesseract (5.0.1) installed by HomeBrew on macOS - // has a bug that will crash the program when deleting internal Tesseract API instances, - // giving error: - // libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument - // A similar issue is posted on Tesseract Github: https://github.com/tesseract-ocr/tesseract/issues/3655 - // There is no way of using HomeBrew to reinstall the older version. - // Fortunately this class TesseractPool will not get built and destroyed repeatedly in - // runtime. It will only get initialized once for each supported language. So I am able - // to use this ugly workaround by not deleting the Tesseract API instances. - std::cout << "Warning: not release Tesseract API instance due to mutex bug similar to https://github.com/tesseract-ocr/tesseract/issues/3655" << std::endl; - for(auto& api : m_instances){ - api.release(); - } - } -#endif -#endif - -private: - const std::string& m_language_code; - const std::string m_training_data_path; - - SpinLock m_lock; - std::vector> m_instances; - std::vector m_idle; -}; - -SpinLock ocr_pool_lock; -std::map ocr_pool; - - -std::string ocr_read(Language language, const ImageViewRGB32& image){ -// static size_t c = 0; -// image.save("ocr-" + std::to_string(c++) + ".png"); - - if (language == Language::None){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); - } - - std::map::iterator iter; - { - WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); - iter = ocr_pool.find(language); - if (iter == ocr_pool.end()){ - iter = ocr_pool.emplace(language, language).first; - } - } - return iter->second.run(image); -} -void ensure_instances(Language language, size_t instances){ - if (language == Language::None){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); - } - - std::map::iterator iter; - { - WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); - iter = ocr_pool.find(language); - if (iter == ocr_pool.end()){ - iter = ocr_pool.emplace(language, language).first; - } - } - iter->second.ensure_instances(instances); -} - - - - - -} -} - - - - +/* Raw Text Recognition + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "3rdParty/TesseractPA/TesseractPA.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "OCR_RawOCR.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + + +bool language_available(Language language){ + std::string path = RESOURCE_PATH(); + path += "Tesseract/"; + path += language_data(language).code; + path += ".traineddata"; + QFile file(QString::fromStdString(path)); + return file.exists(); +} + + + +class TesseractPool{ +public: + TesseractPool(Language language) + : m_language_code(language_data(language).code) + , m_training_data_path( + QDir::current().relativeFilePath(QString::fromStdString(RESOURCE_PATH() + "Tesseract/")).toStdString() + ) + {} + + std::string run(const ImageViewRGB32& image){ + TesseractAPI* instance; + while (true){ + { + WriteSpinLock lg(m_lock, "TesseractPool::run()"); + if (!m_idle.empty()){ + instance = m_idle.back(); + m_idle.pop_back(); + break; + } + } + add_instance(); + } + +// auto start = current_time(); + TesseractString str = instance->read32( + (const unsigned char*)image.data(), + image.width(), + image.height(), + image.bytes_per_row() + ); +// auto end = current_time(); +// cout << std::chrono::duration_cast(end - start).count() << endl; + + { + WriteSpinLock lg(m_lock, "TesseractPool::run()"); + m_idle.emplace_back(instance); + } + + return str.c_str() == nullptr + ? std::string() + : str.c_str(); + } + + void add_instance(){ + // Check for non-ascii characters in path. + for (char ch : m_training_data_path){ + if (ch < 0){ + throw InternalSystemError( + nullptr, PA_CURRENT_FUNCTION, + "Detected non-ASCII character in Tesseract path. Please move the program to a path with only ASCII characters." + ); + } + } + + global_logger_tagged().log( + "Initializing TesseractAPI (" + m_language_code + "): " + m_training_data_path + ); + std::unique_ptr api( + new TesseractAPI(m_training_data_path.c_str(), m_language_code.c_str()) + ); + if (!api->valid()){ + throw InternalSystemError(nullptr, PA_CURRENT_FUNCTION, "Could not initialize TesseractAPI."); + } + + WriteSpinLock lg(m_lock, "TesseractPool::run()"); + + m_instances.emplace_back(std::move(api)); + try{ + m_idle.emplace_back(m_instances.back().get()); + }catch (...){ + m_instances.pop_back(); + throw; + } + } + + void ensure_instances(size_t instances){ + size_t current_instances; + while (true){ + { + ReadSpinLock lg(m_lock, "TesseractPool::run()"); + current_instances = m_instances.size(); + } + if (current_instances >= instances){ + break; + } + add_instance(); + } + } + +#ifdef __APPLE__ +#ifdef UNIX_LINK_TESSERACT + ~TesseractPool(){ + // As of Feb 05, 2022, the newest Tesseract (5.0.1) installed by HomeBrew on macOS + // has a bug that will crash the program when deleting internal Tesseract API instances, + // giving error: + // libc++abi.dylib: terminating with uncaught exception of type std::__1::system_error: mutex lock failed: Invalid argument + // A similar issue is posted on Tesseract Github: https://github.com/tesseract-ocr/tesseract/issues/3655 + // There is no way of using HomeBrew to reinstall the older version. + // Fortunately this class TesseractPool will not get built and destroyed repeatedly in + // runtime. It will only get initialized once for each supported language. So I am able + // to use this ugly workaround by not deleting the Tesseract API instances. + std::cout << "Warning: not release Tesseract API instance due to mutex bug similar to https://github.com/tesseract-ocr/tesseract/issues/3655" << std::endl; + for(auto& api : m_instances){ + api.release(); + } + } +#endif +#endif + +private: + const std::string& m_language_code; + const std::string m_training_data_path; + + SpinLock m_lock; + std::vector> m_instances; + std::vector m_idle; +}; + +SpinLock ocr_pool_lock; +std::map ocr_pool; + + +std::string ocr_read(Language language, const ImageViewRGB32& image){ +// static size_t c = 0; +// image.save("ocr-" + std::to_string(c++) + ".png"); + + if (language == Language::None){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); + } + + std::map::iterator iter; + { + WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); + iter = ocr_pool.find(language); + if (iter == ocr_pool.end()){ + iter = ocr_pool.emplace(language, language).first; + } + } + return iter->second.run(image); +} +void ensure_instances(Language language, size_t instances){ + if (language == Language::None){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to call OCR without a language."); + } + + std::map::iterator iter; + { + WriteSpinLock lg(ocr_pool_lock, "ocr_read()"); + iter = ocr_pool.find(language); + if (iter == ocr_pool.end()){ + iter = ocr_pool.emplace(language, language).first; + } + } + iter->second.ensure_instances(instances); +} + + + + + +} +} + + + + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h index 4f1d2421a6..1ab62f7ec1 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_RawOCR.h @@ -1,32 +1,32 @@ -/* Raw Text Recognition - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_RawOCR_H -#define PokemonAutomation_CommonTools_OCR_RawOCR_H - -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace OCR{ - - -bool language_available(Language language); - - -// OCR the image in the specified language. -std::string ocr_read(Language language, const ImageViewRGB32& image); - -// Ensure that there are this many parallel instances for this language. -// Call this if you expect to need to do many OCR instances in parallel and you -// want to preload the OCR instances. -void ensure_instances(Language language, size_t instances); - - -} -} -#endif +/* Raw Text Recognition + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_RawOCR_H +#define PokemonAutomation_CommonTools_OCR_RawOCR_H + +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace OCR{ + + +bool language_available(Language language); + + +// OCR the image in the specified language. +std::string ocr_read(Language language, const ImageViewRGB32& image); + +// Ensure that there are this many parallel instances for this language. +// Call this if you expect to need to do many OCR instances in parallel and you +// want to preload the OCR instances. +void ensure_instances(Language language, size_t instances); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp index 6ffe424c69..24b8b05ac6 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.cpp @@ -1,119 +1,119 @@ -/* OCR Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonTools/Images/ImageFilter.h" -#include "OCR_RawOCR.h" -#include "OCR_DictionaryMatcher.h" -#include "OCR_Routines.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -StringMatchResult multifiltered_OCR( - Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double log10p_spread, - double min_text_ratio, double max_text_ratio -){ - if (image.width() == 0 || image.height() == 0){ - return StringMatchResult(); - } - - std::vector bw_filters; - for (const auto& range : text_color_ranges){ - bw_filters.emplace_back( - BlackWhiteRgb32Range{true, range.mins, range.maxs} - ); - } - std::vector> filtered_images = to_blackwhite_rgb32_range(image, bw_filters); - - double pixels_inv = 1. / (image.width() * image.height()); - - // Run all the filters. - StringMatchResult ret; -// int c = 0; - for (const auto& filtered : filtered_images){ - std::string text = ocr_read(language, filtered.first); -// cout << text.toStdString() << endl; -// filtered.first.save("test" + QString::number(c++) + ".png"); - - // Compute ratio of image that matches text color. Skip if it's out of range. - double ratio = filtered.second * pixels_inv; -// cout << "ratio = " << ratio << endl; - if (ratio < min_text_ratio || ratio > max_text_ratio){ - continue; - } - - StringMatchResult current = dictionary.match_substring(language, text, log10p_spread); - ret.exact_match |= current.exact_match; - ret.results.insert(current.results.begin(), current.results.end()); - } - -// ret.log(global_logger_tagged(), -1.5); - - // Prune duplicates. - std::set tokens; - for (auto iter = ret.results.begin(); iter != ret.results.end();){ - if (tokens.find(iter->second.token) == tokens.end()){ - tokens.insert(iter->second.token); - ++iter; - }else{ - iter = ret.results.erase(iter); - } - } - - ret.clear_beyond_spread(log10p_spread); - return ret; -} - - - -const std::vector& BLACK_TEXT_FILTERS(){ - static std::vector filters{ - {0xff000000, 0xff404040}, - {0xff000000, 0xff606060}, - {0xff000000, 0xff808080}, - }; - return filters; -} -const std::vector& WHITE_TEXT_FILTERS(){ - static std::vector filters{ - {0xff808080, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - {0xffc0c0c0, 0xffffffff}, - }; - return filters; -} -const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(){ - static std::vector filters{ - {0xff000000, 0xff404040}, - {0xff000000, 0xff606060}, - {0xff000000, 0xff808080}, - {0xff808080, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - }; - return filters; -} -const std::vector& BLUE_TEXT_FILTERS(){ - static std::vector filters{ - {0xFF3287A2, 0xFFA7F4FF}, - {0xFF2283A2, 0xFF8EF1FF}, - {0xFF428BA2, 0xFFC1F7FF}, - }; - return filters; -} - - - - - - - - -} -} +/* OCR Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonTools/Images/ImageFilter.h" +#include "OCR_RawOCR.h" +#include "OCR_DictionaryMatcher.h" +#include "OCR_Routines.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +StringMatchResult multifiltered_OCR( + Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double log10p_spread, + double min_text_ratio, double max_text_ratio +){ + if (image.width() == 0 || image.height() == 0){ + return StringMatchResult(); + } + + std::vector bw_filters; + for (const auto& range : text_color_ranges){ + bw_filters.emplace_back( + BlackWhiteRgb32Range{true, range.mins, range.maxs} + ); + } + std::vector> filtered_images = to_blackwhite_rgb32_range(image, bw_filters); + + double pixels_inv = 1. / (image.width() * image.height()); + + // Run all the filters. + StringMatchResult ret; +// int c = 0; + for (const auto& filtered : filtered_images){ + std::string text = ocr_read(language, filtered.first); +// cout << text.toStdString() << endl; +// filtered.first.save("test" + QString::number(c++) + ".png"); + + // Compute ratio of image that matches text color. Skip if it's out of range. + double ratio = filtered.second * pixels_inv; +// cout << "ratio = " << ratio << endl; + if (ratio < min_text_ratio || ratio > max_text_ratio){ + continue; + } + + StringMatchResult current = dictionary.match_substring(language, text, log10p_spread); + ret.exact_match |= current.exact_match; + ret.results.insert(current.results.begin(), current.results.end()); + } + +// ret.log(global_logger_tagged(), -1.5); + + // Prune duplicates. + std::set tokens; + for (auto iter = ret.results.begin(); iter != ret.results.end();){ + if (tokens.find(iter->second.token) == tokens.end()){ + tokens.insert(iter->second.token); + ++iter; + }else{ + iter = ret.results.erase(iter); + } + } + + ret.clear_beyond_spread(log10p_spread); + return ret; +} + + + +const std::vector& BLACK_TEXT_FILTERS(){ + static std::vector filters{ + {0xff000000, 0xff404040}, + {0xff000000, 0xff606060}, + {0xff000000, 0xff808080}, + }; + return filters; +} +const std::vector& WHITE_TEXT_FILTERS(){ + static std::vector filters{ + {0xff808080, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + {0xffc0c0c0, 0xffffffff}, + }; + return filters; +} +const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(){ + static std::vector filters{ + {0xff000000, 0xff404040}, + {0xff000000, 0xff606060}, + {0xff000000, 0xff808080}, + {0xff808080, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + }; + return filters; +} +const std::vector& BLUE_TEXT_FILTERS(){ + static std::vector filters{ + {0xFF3287A2, 0xFFA7F4FF}, + {0xFF2283A2, 0xFF8EF1FF}, + {0xFF428BA2, 0xFFC1F7FF}, + }; + return filters; +} + + + + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h index 6023598883..60c7ba851e 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_Routines.h @@ -1,51 +1,51 @@ -/* OCR Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_Routines_H -#define PokemonAutomation_CommonTools_OCR_Routines_H - -#include -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace OCR{ - -struct StringMatchResult; -class DictionaryMatcher; - - - -struct TextColorRange{ - uint32_t mins; - uint32_t maxs; - - TextColorRange(uint32_t p_mins, uint32_t p_maxs) - : mins(p_mins) - , maxs(p_maxs) - {} -}; - - -StringMatchResult multifiltered_OCR( - Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double log10p_spread, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 -); - - -const std::vector& BLACK_TEXT_FILTERS(); -const std::vector& WHITE_TEXT_FILTERS(); -const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(); -const std::vector& BLUE_TEXT_FILTERS(); - - - -} -} -#endif +/* OCR Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_Routines_H +#define PokemonAutomation_CommonTools_OCR_Routines_H + +#include +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace OCR{ + +struct StringMatchResult; +class DictionaryMatcher; + + + +struct TextColorRange{ + uint32_t mins; + uint32_t maxs; + + TextColorRange(uint32_t p_mins, uint32_t p_maxs) + : mins(p_mins) + , maxs(p_maxs) + {} +}; + + +StringMatchResult multifiltered_OCR( + Language language, const DictionaryMatcher& dictionary, const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double log10p_spread, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 +); + + +const std::vector& BLACK_TEXT_FILTERS(); +const std::vector& WHITE_TEXT_FILTERS(); +const std::vector& BLACK_OR_WHITE_TEXT_FILTERS(); +const std::vector& BLUE_TEXT_FILTERS(); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp index b077808809..b78760aa4e 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.cpp @@ -1,51 +1,51 @@ -/* Small Database Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" -#include "OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace OCR{ - - - -SmallDictionaryMatcher::SmallDictionaryMatcher(const std::string& json_path, bool first_only) - : SmallDictionaryMatcher( - load_json_file(RESOURCE_PATH() + json_path).to_object_throw(), - first_only - ) -{} -SmallDictionaryMatcher::SmallDictionaryMatcher(const JsonObject& json, bool first_only){ - for (const auto& item : json){ - Language language = language_code_to_enum(item.first); - const LanguageData& data = language_data(language); - m_database.emplace( - std::piecewise_construct, - std::forward_as_tuple(language), - std::forward_as_tuple(item.second.to_object_throw(), nullptr, data.random_match_chance, first_only) - ); - m_languages += language; - } -} - - -void SmallDictionaryMatcher::save(const std::string& json_path) const{ - JsonObject root; - for (const auto& item : m_database){ - root[language_data(item.first).code] = item.second.to_json(); - } - root.dump(json_path); -} - - - -} -} +/* Small Database Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" +#include "OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace OCR{ + + + +SmallDictionaryMatcher::SmallDictionaryMatcher(const std::string& json_path, bool first_only) + : SmallDictionaryMatcher( + load_json_file(RESOURCE_PATH() + json_path).to_object_throw(), + first_only + ) +{} +SmallDictionaryMatcher::SmallDictionaryMatcher(const JsonObject& json, bool first_only){ + for (const auto& item : json){ + Language language = language_code_to_enum(item.first); + const LanguageData& data = language_data(language); + m_database.emplace( + std::piecewise_construct, + std::forward_as_tuple(language), + std::forward_as_tuple(item.second.to_object_throw(), nullptr, data.random_match_chance, first_only) + ); + m_languages += language; + } +} + + +void SmallDictionaryMatcher::save(const std::string& json_path) const{ + JsonObject root; + for (const auto& item : m_database){ + root[language_data(item.first).code] = item.second.to_json(); + } + root.dump(json_path); +} + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h index 05ceebfdfd..3dbb7b1d6a 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_SmallDictionaryMatcher.h @@ -1,43 +1,43 @@ -/* Small Dictionary Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H -#define PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H - -#include "OCR_DictionaryMatcher.h" - -namespace PokemonAutomation{ - class JsonObject; -namespace OCR{ - -// An OCR matcher with a small dictionary. -// Since the dictionary is small, all languages of this dictionary are stored in -// the same JSON file. -class SmallDictionaryMatcher : public DictionaryMatcher{ -public: - // Load the JSON file to build the dictionary for all languages stored in the JSON. - // first_only: whether to use only the first value for each slug. - // This parameter is only useful for training the OCR. - // During inference, we set `first_only` to false so that each slug corresponds to - // all the values in that dictionary entry. - // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, - // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], - // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. - // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. - SmallDictionaryMatcher(const std::string& json_path, bool first_only = false); - // Load JSON object to build the dictionary for all languages stored in the JSON. - // See the comments of - // `SmallDictionaryMatcher(const std::string& json_path, bool first_only = false)` - // to konw the usage of `first_only`. - SmallDictionaryMatcher(const JsonObject& json, bool first_only = false); - - void save(const std::string& json_path) const; -}; - - -} -} -#endif +/* Small Dictionary Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H +#define PokemonAutomation_CommonTools_OCR_SmallDictionaryMatcher_H + +#include "OCR_DictionaryMatcher.h" + +namespace PokemonAutomation{ + class JsonObject; +namespace OCR{ + +// An OCR matcher with a small dictionary. +// Since the dictionary is small, all languages of this dictionary are stored in +// the same JSON file. +class SmallDictionaryMatcher : public DictionaryMatcher{ +public: + // Load the JSON file to build the dictionary for all languages stored in the JSON. + // first_only: whether to use only the first value for each slug. + // This parameter is only useful for training the OCR. + // During inference, we set `first_only` to false so that each slug corresponds to + // all the values in that dictionary entry. + // e.g. if `first_only` is false, when loading Pokemon Abomasnow for traditional Chinese, + // "abomasnow": ["暴雪王", "繁霎王", "鬘粘王"], + // when OCR detects any of "暴雪王", "繁霎王" or "鬘粘王", the matcher returns Abomasnow. + // if 'first_only' is true, only when OCR detects "暴雪王" do the matcher return Abomasnow. + SmallDictionaryMatcher(const std::string& json_path, bool first_only = false); + // Load JSON object to build the dictionary for all languages stored in the JSON. + // See the comments of + // `SmallDictionaryMatcher(const std::string& json_path, bool first_only = false)` + // to konw the usage of `first_only`. + SmallDictionaryMatcher(const JsonObject& json, bool first_only = false); + + void save(const std::string& json_path) const; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp index e1936376b1..ff7a986b6d 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.cpp @@ -1,114 +1,114 @@ -/* String Match Results - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Qt/StringToolsQt.h" -#include "OCR_StringMatchResult.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -std::string StringMatchData::to_str() const{ - std::string str; - - str += "\""; - for (char ch : original_text){ - if (ch != '\r' && ch != '\n'){ - str += ch; - } - } - str += "\" -> "; - str += "\"" + to_utf8(normalized_text) + "\" -> "; - - str += "(" + to_utf8(target) + "): "; - str += "(" + token + ")"; - return str; -} - -void StringMatchResult::log(Logger& logger, double max_log10p, const std::string& extra) const{ - std::string str = "String Match Result: "; - -#if 0 - if (!expected_token.empty()){ - str += "Expected ("; - str += QString::fromStdString(expected_token); - str += "): "; - } -#endif - - Color color; - if (results.empty()){ - str += "no matches"; - color = COLOR_RED; - }else{ - double best = results.begin()->first; - color = exact_match || best <= max_log10p - ? COLOR_BLUE - : COLOR_RED; - - if (results.size() == 1){ - auto iter = results.begin(); - str += iter->second.to_str(); - str += " (log10p = " + tostr_default(iter->first) +")"; - }else{ - str += "Multiple Candidates =>\n"; - size_t printed = 0; - for (const auto& item : results){ - if (printed == 10){ - str += " (" + std::to_string(results.size() - 10) + " more...)\n"; - break; - } - str += " " + tostr_default(item.first) + " : " + item.second.to_str() + "\n"; - printed++; - } - } - } - - if (!extra.empty()){ - str += " ===> "; - str += extra; - } - logger.log(str, color); -} - -void StringMatchResult::add(double log10p, StringMatchData data){ - results.emplace(log10p, std::move(data)); -} -void StringMatchResult::clear_beyond_spread(double log10p_spread){ - auto best = results.begin(); - while (results.size() > 1){ - auto back = results.rbegin(); - if (back->first <= best->first + log10p_spread){ - break; - } - results.erase(back->first); - } -} -void StringMatchResult::clear_beyond_log10p(double max_log10p){ - while (!results.empty()){ - auto iter = results.end(); - --iter; - if (iter->first <= max_log10p){ - break; - } - results.erase(iter); - } -} - - -void StringMatchResult::operator+=(const StringMatchResult& result){ - exact_match |= result.exact_match; - for (auto& item : result.results){ - results.insert(item); - } -} - - - - -} -} +/* String Match Results + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Qt/StringToolsQt.h" +#include "OCR_StringMatchResult.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +std::string StringMatchData::to_str() const{ + std::string str; + + str += "\""; + for (char ch : original_text){ + if (ch != '\r' && ch != '\n'){ + str += ch; + } + } + str += "\" -> "; + str += "\"" + to_utf8(normalized_text) + "\" -> "; + + str += "(" + to_utf8(target) + "): "; + str += "(" + token + ")"; + return str; +} + +void StringMatchResult::log(Logger& logger, double max_log10p, const std::string& extra) const{ + std::string str = "String Match Result: "; + +#if 0 + if (!expected_token.empty()){ + str += "Expected ("; + str += QString::fromStdString(expected_token); + str += "): "; + } +#endif + + Color color; + if (results.empty()){ + str += "no matches"; + color = COLOR_RED; + }else{ + double best = results.begin()->first; + color = exact_match || best <= max_log10p + ? COLOR_BLUE + : COLOR_RED; + + if (results.size() == 1){ + auto iter = results.begin(); + str += iter->second.to_str(); + str += " (log10p = " + tostr_default(iter->first) +")"; + }else{ + str += "Multiple Candidates =>\n"; + size_t printed = 0; + for (const auto& item : results){ + if (printed == 10){ + str += " (" + std::to_string(results.size() - 10) + " more...)\n"; + break; + } + str += " " + tostr_default(item.first) + " : " + item.second.to_str() + "\n"; + printed++; + } + } + } + + if (!extra.empty()){ + str += " ===> "; + str += extra; + } + logger.log(str, color); +} + +void StringMatchResult::add(double log10p, StringMatchData data){ + results.emplace(log10p, std::move(data)); +} +void StringMatchResult::clear_beyond_spread(double log10p_spread){ + auto best = results.begin(); + while (results.size() > 1){ + auto back = results.rbegin(); + if (back->first <= best->first + log10p_spread){ + break; + } + results.erase(back->first); + } +} +void StringMatchResult::clear_beyond_log10p(double max_log10p){ + while (!results.empty()){ + auto iter = results.end(); + --iter; + if (iter->first <= max_log10p){ + break; + } + results.erase(iter); + } +} + + +void StringMatchResult::operator+=(const StringMatchResult& result){ + exact_match |= result.exact_match; + for (auto& item : result.results){ + results.insert(item); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h index a324fbfe15..96f37683d6 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringMatchResult.h @@ -1,50 +1,50 @@ -/* String Match Results - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_StringMatchResult_H -#define PokemonAutomation_CommonTools_OCR_StringMatchResult_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -struct StringMatchData{ - std::string original_text; - std::u32string normalized_text; - - std::u32string target; - std::string token; - - std::string to_str() const; -}; - -struct StringMatchResult{ - bool exact_match = false; - std::multimap results; - - void clear(){ - exact_match = false; - results.clear(); - } - void log(Logger& logger, double max_log10p, const std::string& extra = std::string()) const; - - void add(double log10p, StringMatchData data); - void clear_beyond_spread(double log10p_spread); - void clear_beyond_log10p(double max_log10p); - - void operator+=(const StringMatchResult& result); -}; - - - - -} -} -#endif +/* String Match Results + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_StringMatchResult_H +#define PokemonAutomation_CommonTools_OCR_StringMatchResult_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +struct StringMatchData{ + std::string original_text; + std::u32string normalized_text; + + std::u32string target; + std::string token; + + std::string to_str() const; +}; + +struct StringMatchResult{ + bool exact_match = false; + std::multimap results; + + void clear(){ + exact_match = false; + results.clear(); + } + void log(Logger& logger, double max_log10p, const std::string& extra = std::string()) const; + + void add(double log10p, StringMatchData data); + void clear_beyond_spread(double log10p_spread); + void clear_beyond_log10p(double max_log10p); + + void operator+=(const StringMatchResult& result); +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp index 06bfa4d35c..a6cab538e1 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.cpp @@ -1,93 +1,93 @@ -/* String Normalization - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Globals.h" -#include "OCR_StringNormalization.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -std::u32string normalize_utf32(const std::string& text){ - QString qstr = QString::fromStdString(text); - qstr = qstr.normalized(QString::NormalizationForm_KD); - std::u32string u32 = remove_non_alphanumeric(qstr.toStdU32String()); - u32 = run_character_reductions(u32); - to_lower(u32); - return u32; -} - - - -std::u32string remove_non_alphanumeric(const std::u32string& text){ - std::u32string str; - for (char32_t ch : text){ - if (QChar::isLetterOrNumber(ch)){ - str += ch; - continue; - } - } - return str; -} - - - -std::map make_substitution_map32(){ - std::string path = RESOURCE_PATH() + "Tesseract/CharacterReductions.json"; - JsonValue json = load_json_file(path); - JsonObject& obj = json.to_object_throw(path); - - std::map map; - for (auto& item : obj){ - const std::string& target = item.first; - std::string& sources = item.second.to_string_throw(path); - for (char32_t ch : to_utf32(sources)){ - auto iter = map.find(ch); - if (iter != map.end()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - to_utf8(to_utf32("Duplicate character reduction: ") + ch), - std::move(path) - ); - } - map[ch] = to_utf32(target); - } - } - return map; -} -const std::map& SUBSTITUTION_MAP32(){ - static std::map map = make_substitution_map32(); - return map; -} -std::u32string run_character_reductions(const std::u32string& text){ - const std::map& map = SUBSTITUTION_MAP32(); - std::u32string str; - for (char32_t ch : text){ - auto iter = map.find(ch); - if (iter == map.end()){ - str += ch; - }else{ - str += iter->second; - } - } - return str; -} - - - - - - - -} -} - +/* String Normalization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Globals.h" +#include "OCR_StringNormalization.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +std::u32string normalize_utf32(const std::string& text){ + QString qstr = QString::fromStdString(text); + qstr = qstr.normalized(QString::NormalizationForm_KD); + std::u32string u32 = remove_non_alphanumeric(qstr.toStdU32String()); + u32 = run_character_reductions(u32); + to_lower(u32); + return u32; +} + + + +std::u32string remove_non_alphanumeric(const std::u32string& text){ + std::u32string str; + for (char32_t ch : text){ + if (QChar::isLetterOrNumber(ch)){ + str += ch; + continue; + } + } + return str; +} + + + +std::map make_substitution_map32(){ + std::string path = RESOURCE_PATH() + "Tesseract/CharacterReductions.json"; + JsonValue json = load_json_file(path); + JsonObject& obj = json.to_object_throw(path); + + std::map map; + for (auto& item : obj){ + const std::string& target = item.first; + std::string& sources = item.second.to_string_throw(path); + for (char32_t ch : to_utf32(sources)){ + auto iter = map.find(ch); + if (iter != map.end()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + to_utf8(to_utf32("Duplicate character reduction: ") + ch), + std::move(path) + ); + } + map[ch] = to_utf32(target); + } + } + return map; +} +const std::map& SUBSTITUTION_MAP32(){ + static std::map map = make_substitution_map32(); + return map; +} +std::u32string run_character_reductions(const std::u32string& text){ + const std::map& map = SUBSTITUTION_MAP32(); + std::u32string str; + for (char32_t ch : text){ + auto iter = map.find(ch); + if (iter == map.end()){ + str += ch; + }else{ + str += iter->second; + } + } + return str; +} + + + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h index 3265b8db55..7e69aa1ac6 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_StringNormalization.h @@ -1,25 +1,25 @@ -/* String Normalization - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_StringNormalization_H -#define PokemonAutomation_CommonTools_OCR_StringNormalization_H - -#include - -namespace PokemonAutomation{ -namespace OCR{ - - -std::u32string remove_non_alphanumeric(const std::u32string& text); -std::u32string run_character_reductions(const std::u32string& text); - -std::u32string normalize_utf32(const std::string& text); - - - -} -} -#endif +/* String Normalization + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_StringNormalization_H +#define PokemonAutomation_CommonTools_OCR_StringNormalization_H + +#include + +namespace PokemonAutomation{ +namespace OCR{ + + +std::u32string remove_non_alphanumeric(const std::u32string& text); +std::u32string run_character_reductions(const std::u32string& text); + +std::u32string normalize_utf32(const std::string& text); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp index e7d2be2d22..cc2f56514b 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.cpp @@ -1,311 +1,311 @@ -/* Text Inference Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Qt/StringToolsQt.h" -#include "OCR_StringNormalization.h" -#include "OCR_TextMatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - -void print(const std::vector& v){ - std::string str = "{"; - bool first = true; - for (size_t x : v){ - if (!first){ - str += ", "; - } - first = false; - str += std::to_string(x); - } - str += "}"; - cout << str << endl; -} - - -size_t levenshtein_distance(const QString& x, const QString& y){ - size_t xlen = x.size(); - size_t ylen = y.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } - - for (size_t i = 0; i < xlen; i++){ - v1[0] = i + 1; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (x[(int)i] != y[(int)j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - } - - return v0[ylen]; -} -size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring){ - size_t xlen = fullstring.size(); - size_t ylen = substring.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } -// print(v0); - - size_t min = ylen; - - for (size_t i = 0; i < xlen; i++){ - v1[0] = 0; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (fullstring[(int)i] != substring[(int)j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - - min = std::min(min, v0[ylen]); -// print(v0); - } - - return min; -} - -template -size_t levenshtein_distance(const StringType& x, const StringType& y){ - size_t xlen = x.size(); - size_t ylen = y.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } - - for (size_t i = 0; i < xlen; i++){ - v1[0] = i + 1; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (x[i] != y[j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - } - - return v0[ylen]; -} -template -size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring){ - size_t xlen = fullstring.size(); - size_t ylen = substring.size(); - - std::vector v0(ylen + 1); - std::vector v1(ylen + 1); - - for (size_t i = 0; i <= ylen; i++){ - v0[i] = i; - } -// print(v0); - - size_t min = ylen; - - for (size_t i = 0; i < xlen; i++){ - v1[0] = 0; - - for (size_t j = 0; j < ylen; j++){ - size_t delete_cost = v0[j + 1] + 1; - size_t insert_cost = v1[j] + 1; - size_t sub_cost = v0[j]; - if (fullstring[i] != substring[j]){ - sub_cost += 1; - } - v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); - } - - std::swap(v0, v1); - - min = std::min(min, v0[ylen]); -// print(v0); - } - - return min; -} -template size_t levenshtein_distance(const std::u32string& x, const std::u32string& y); -template size_t levenshtein_distance_substring(const std::u32string& x, const std::u32string& y); - - -std::map> binomial_table; -SpinLock binomial_lock; -std::vector binomial_row_u64(size_t degree){ - std::vector row; - - uint64_t a = (uint64_t)degree; - uint64_t b = 1; - { - row.emplace_back(1); - } - { - row.emplace_back(a); - a--; - b++; - } - while (a > b){ - row.emplace_back(row.back() * a / b); - a--; - b++; - } - - return row; -} -double binomial_coefficient_double(size_t degree, size_t index){ - if (degree > 1000){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); - } - - WriteSpinLock lg(binomial_lock, "binomial_coefficient_double()"); - - auto iter = binomial_table.find(degree); - std::vector& row = iter != binomial_table.end() - ? iter->second - : binomial_table[degree] = binomial_row_u64(degree); - - if (index > degree / 2){ - index = degree - index; - } - - return row[index]; -} - - -double random_match_probability(size_t total, size_t matched, double random_match_chance){ - if (total > 1000){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); - } - - double c_match = 1 - random_match_chance; - - double misses[62]; - { - double miss = 1; - misses[0] = miss; - for (size_t c = 1; c <= total - matched; c++){ - miss *= c_match; - misses[c] = miss; - } - } - - double hits = 1; - - size_t m = 0; - for (; m < matched; m++){ - hits *= random_match_chance; - } - - double probability = 0; - for (; m < total; m++){ - double binomial = (double)binomial_coefficient_double(total, m); - probability += hits * binomial * misses[total - m]; - hits *= random_match_chance; - } - probability += hits; - return probability; -} - - - -StringMatchResult match_substring( - const std::map>& database, double random_match_chance, - const std::string& text, double log10p_spread -){ - StringMatchResult results; -// result.original_text = text; -// result.normalized_text = normalize(text); - - std::u32string normalized = normalize_utf32(text); - - // Search for exact match of candidate. - auto iter = database.find(normalized); - if (iter != database.end()){ - results.exact_match = true; - double probability = random_match_probability(normalized.size(), normalized.size(), random_match_chance); - double log10p = std::log10(probability); - for (const auto& target : iter->second){ - results.add( - log10p, - StringMatchData{text, normalized, normalized, target} - ); - } - return results; - } - - - for (const auto& item : database){ - double token_length = item.first.size(); - - size_t distance = levenshtein_distance_substring(item.first, normalized); - size_t matched = token_length - distance; - if (matched == 0){ - continue; - } - - double probability = random_match_probability(token_length, matched, random_match_chance); - double log10p = std::log10(probability); - - if (distance == 0){ - results.exact_match = true; - } - - for (const auto& slug : item.second){ - results.add(log10p, StringMatchData{text, normalized, item.first, slug}); - results.clear_beyond_spread(log10p_spread); - } - } - - return results; -} - - - - - - - - -} -} - +/* Text Inference Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Qt/StringToolsQt.h" +#include "OCR_StringNormalization.h" +#include "OCR_TextMatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + +void print(const std::vector& v){ + std::string str = "{"; + bool first = true; + for (size_t x : v){ + if (!first){ + str += ", "; + } + first = false; + str += std::to_string(x); + } + str += "}"; + cout << str << endl; +} + + +size_t levenshtein_distance(const QString& x, const QString& y){ + size_t xlen = x.size(); + size_t ylen = y.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } + + for (size_t i = 0; i < xlen; i++){ + v1[0] = i + 1; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (x[(int)i] != y[(int)j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + } + + return v0[ylen]; +} +size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring){ + size_t xlen = fullstring.size(); + size_t ylen = substring.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } +// print(v0); + + size_t min = ylen; + + for (size_t i = 0; i < xlen; i++){ + v1[0] = 0; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (fullstring[(int)i] != substring[(int)j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + + min = std::min(min, v0[ylen]); +// print(v0); + } + + return min; +} + +template +size_t levenshtein_distance(const StringType& x, const StringType& y){ + size_t xlen = x.size(); + size_t ylen = y.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } + + for (size_t i = 0; i < xlen; i++){ + v1[0] = i + 1; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (x[i] != y[j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + } + + return v0[ylen]; +} +template +size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring){ + size_t xlen = fullstring.size(); + size_t ylen = substring.size(); + + std::vector v0(ylen + 1); + std::vector v1(ylen + 1); + + for (size_t i = 0; i <= ylen; i++){ + v0[i] = i; + } +// print(v0); + + size_t min = ylen; + + for (size_t i = 0; i < xlen; i++){ + v1[0] = 0; + + for (size_t j = 0; j < ylen; j++){ + size_t delete_cost = v0[j + 1] + 1; + size_t insert_cost = v1[j] + 1; + size_t sub_cost = v0[j]; + if (fullstring[i] != substring[j]){ + sub_cost += 1; + } + v1[j + 1] = std::min({delete_cost, insert_cost, sub_cost}); + } + + std::swap(v0, v1); + + min = std::min(min, v0[ylen]); +// print(v0); + } + + return min; +} +template size_t levenshtein_distance(const std::u32string& x, const std::u32string& y); +template size_t levenshtein_distance_substring(const std::u32string& x, const std::u32string& y); + + +std::map> binomial_table; +SpinLock binomial_lock; +std::vector binomial_row_u64(size_t degree){ + std::vector row; + + uint64_t a = (uint64_t)degree; + uint64_t b = 1; + { + row.emplace_back(1); + } + { + row.emplace_back(a); + a--; + b++; + } + while (a > b){ + row.emplace_back(row.back() * a / b); + a--; + b++; + } + + return row; +} +double binomial_coefficient_double(size_t degree, size_t index){ + if (degree > 1000){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); + } + + WriteSpinLock lg(binomial_lock, "binomial_coefficient_double()"); + + auto iter = binomial_table.find(degree); + std::vector& row = iter != binomial_table.end() + ? iter->second + : binomial_table[degree] = binomial_row_u64(degree); + + if (index > degree / 2){ + index = degree - index; + } + + return row[index]; +} + + +double random_match_probability(size_t total, size_t matched, double random_match_chance){ + if (total > 1000){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot go beyond degree 1000."); + } + + double c_match = 1 - random_match_chance; + + double misses[62]; + { + double miss = 1; + misses[0] = miss; + for (size_t c = 1; c <= total - matched; c++){ + miss *= c_match; + misses[c] = miss; + } + } + + double hits = 1; + + size_t m = 0; + for (; m < matched; m++){ + hits *= random_match_chance; + } + + double probability = 0; + for (; m < total; m++){ + double binomial = (double)binomial_coefficient_double(total, m); + probability += hits * binomial * misses[total - m]; + hits *= random_match_chance; + } + probability += hits; + return probability; +} + + + +StringMatchResult match_substring( + const std::map>& database, double random_match_chance, + const std::string& text, double log10p_spread +){ + StringMatchResult results; +// result.original_text = text; +// result.normalized_text = normalize(text); + + std::u32string normalized = normalize_utf32(text); + + // Search for exact match of candidate. + auto iter = database.find(normalized); + if (iter != database.end()){ + results.exact_match = true; + double probability = random_match_probability(normalized.size(), normalized.size(), random_match_chance); + double log10p = std::log10(probability); + for (const auto& target : iter->second){ + results.add( + log10p, + StringMatchData{text, normalized, normalized, target} + ); + } + return results; + } + + + for (const auto& item : database){ + double token_length = item.first.size(); + + size_t distance = levenshtein_distance_substring(item.first, normalized); + size_t matched = token_length - distance; + if (matched == 0){ + continue; + } + + double probability = random_match_probability(token_length, matched, random_match_chance); + double log10p = std::log10(probability); + + if (distance == 0){ + results.exact_match = true; + } + + for (const auto& slug : item.second){ + results.add(log10p, StringMatchData{text, normalized, item.first, slug}); + results.clear_beyond_spread(log10p_spread); + } + } + + return results; +} + + + + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h index 0d721615f1..cddfa9ba77 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TextMatcher.h @@ -1,44 +1,44 @@ -/* Text Matcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_TextMatcher_H -#define PokemonAutomation_CommonTools_OCR_TextMatcher_H - -#include -#include -#include -#include -#include "OCR_StringMatchResult.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -size_t levenshtein_distance(const QString& x, const QString& y); -size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring); - -template -size_t levenshtein_distance(const StringType& x, const StringType& y); -template -size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring); - -// Mathematically equivalent to: -// BinomialCDF[total, 1 - random_match_chance, total - matched] -double random_match_probability(size_t total, size_t matched, double random_match_chance); - - - -StringMatchResult match_substring( - const std::map>& database, double random_match_chance, - const std::string& text, double log10p_spread -); - - - - -} -} -#endif +/* Text Matcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_TextMatcher_H +#define PokemonAutomation_CommonTools_OCR_TextMatcher_H + +#include +#include +#include +#include +#include "OCR_StringMatchResult.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +size_t levenshtein_distance(const QString& x, const QString& y); +size_t levenshtein_distance_substring(const QString& substring, const QString& fullstring); + +template +size_t levenshtein_distance(const StringType& x, const StringType& y); +template +size_t levenshtein_distance_substring(const StringType& substring, const StringType& fullstring); + +// Mathematically equivalent to: +// BinomialCDF[total, 1 - random_match_chance, total - matched] +double random_match_probability(size_t total, size_t matched, double random_match_chance); + + + +StringMatchResult match_substring( + const std::map>& database, double random_match_chance, + const std::string& text, double log10p_spread +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp index 28cb3a269e..88f8203d55 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.cpp @@ -1,271 +1,271 @@ -/* Training Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/ParallelTaskRunner.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "OCR_SmallDictionaryMatcher.h" -#include "OCR_LargeDictionaryMatcher.h" -#include "OCR_TrainingTools.h" - -namespace PokemonAutomation{ -namespace OCR{ - - - -std::string extract_name(const std::string& filename){ - std::string name = filename; - while (!name.empty()){ - char ch = name.back(); - name.pop_back(); - if (ch == '.'){ - break; - } - } - while (!name.empty()){ - char ch = name.back(); - name.pop_back(); - if (ch == '-'){ - break; - } - } - while (!name.empty()){ - char ch = name.back(); - name.pop_back(); - if (ch == '-'){ - break; - } - } - return name; -} - - - -TrainingSession::TrainingSession( - Logger& logger, CancellableScope& scope, - const std::string& training_data_directory -) - : m_logger(logger) - , m_scope(scope) - , m_directory(TRAINING_PATH() + training_data_directory) - , m_total_samples(0) -{ - if (!m_directory.empty() && m_directory.back() != '/' && m_directory.back() != '\\'){ - m_directory += "/"; - } - - logger.log("Parsing training data in: " + m_directory); - - QDirIterator iter(QString::fromStdString(m_directory), QDir::AllDirs); - while (iter.hasNext()){ - iter.next(); - QString sample_directory = iter.fileName() + "/"; - for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ - Language language = (Language)c; - const std::string& code = language_data(language).code; - QString folder = sample_directory + QString::fromStdString(code) + "/"; - QDirIterator iter1(QString::fromStdString(m_directory) + folder, QStringList() << "*.png", QDir::Files); - while (iter1.hasNext()){ - iter1.next(); -// QString file = iter.next(); - m_samples[language].emplace_back( - TrainingSample{ - OCR::extract_name(iter1.fileName().toStdString()), - (folder + iter1.fileName()).toStdString() - } - ); - m_total_samples++; - - scope.throw_if_cancelled(); - } - } - scope.throw_if_cancelled(); - } - - logger.log( - "Parsing Complete: Languages = " + tostr_u_commas(m_samples.size()) + - ", Samples = " + tostr_u_commas(m_total_samples) - ); -} - - -void TrainingSession::generate_small_dictionary( - const std::string& ocr_json_file, - const std::string& output_json_file, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio, double max_text_ratio -){ - m_logger.log("Generating OCR Data..."); - - OCR::SmallDictionaryMatcher baseline(ocr_json_file, !incremental); - OCR::SmallDictionaryMatcher trained(ocr_json_file, !incremental); - - ParallelTaskRunner task_runner( - [](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(); }, - 0, threads - ); - - std::atomic matched(0); - std::atomic failed(0); - for (const auto& language : m_samples){ - const LanguageData& language_info = language_data(language.first); - m_logger.log("Starting Language: " + language_info.name); -// cout << (int)item.first << " : " << item.second.size() << endl; - for (const TrainingSample& sample : language.second){ - task_runner.dispatch([&]{ - ImageRGB32 image(m_directory + sample.filepath); - if (!image){ - m_logger.log("Skipping: " + sample.filepath); - return; - } - - OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( - nullptr, language.first, image, - text_color_ranges, - 0, log10p_spread, - min_text_ratio, max_text_ratio - ); - - OCR::StringMatchResult result0 = result; - result.clear_beyond_log10p(max_log10p); - - if (result.results.empty()){ - failed++; - result0.log(m_logger, max_log10p, sample.filepath); - if (!result0.results.empty()){ - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - } - return; - } - - for (const auto& item : result.results){ - if (item.second.token == sample.token){ - matched++; - return; - } - } - - result.log(m_logger, -99999, sample.filepath); - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - }); - m_scope.throw_if_cancelled(); - } - task_runner.wait_for_everything(); - m_scope.throw_if_cancelled(); - } - - m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); - m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); - m_logger.log("Matched: " + tostr_u_commas(matched)); - m_logger.log("Missed: " + tostr_u_commas(failed)); - - trained.save(output_json_file); -} - -void TrainingSession::generate_large_dictionary( - const std::string& ocr_json_directory, - const std::string& output_prefix, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio, double max_text_ratio -) const{ - m_logger.log("Generating OCR Data..."); - - OCR::LargeDictionaryMatcher baseline(ocr_json_directory + output_prefix, nullptr, !incremental); - OCR::LargeDictionaryMatcher trained(ocr_json_directory + output_prefix, nullptr, !incremental); - - ParallelTaskRunner task_runner( - [](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(); }, - 0, threads - ); - - std::atomic matched(0); - std::atomic failed(0); - for (const auto& language : m_samples){ - const LanguageData& language_info = language_data(language.first); - m_logger.log("Starting Language: " + language_info.name); -// cout << (int)item.first << " : " << item.second.size() << endl; - for (const TrainingSample& sample : language.second){ - task_runner.dispatch([&]{ - ImageRGB32 image(m_directory + sample.filepath); - if (!image){ - m_logger.log("Skipping: " + sample.filepath); - return; - } - - OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( - nullptr, language.first, image, - text_color_ranges, - 0, log10p_spread, - min_text_ratio, max_text_ratio - ); - - OCR::StringMatchResult result0 = result; - result.clear_beyond_log10p(max_log10p); - - if (result.results.empty()){ - failed++; - result0.log(m_logger, max_log10p, sample.filepath); - if (!result0.results.empty()){ - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - } - return; - } - - for (const auto& item : result.results){ - if (item.second.token == sample.token){ - matched++; - return; - } - } - - result.log(m_logger, -99999, sample.filepath); - trained.add_candidate( - language.first, sample.token, - result0.results.begin()->second.normalized_text - ); - }); - m_scope.throw_if_cancelled(); - } - task_runner.wait_for_everything(); - - std::string json = output_prefix + language_info.code + ".json"; - trained.save(language.first, json); - m_scope.throw_if_cancelled(); - } - - m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); - m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); - m_logger.log("Matched: " + tostr_u_commas(matched)); - m_logger.log("Missed: " + tostr_u_commas(failed)); -} - - - - - - -} -} - +/* Training Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/ParallelTaskRunner.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "OCR_SmallDictionaryMatcher.h" +#include "OCR_LargeDictionaryMatcher.h" +#include "OCR_TrainingTools.h" + +namespace PokemonAutomation{ +namespace OCR{ + + + +std::string extract_name(const std::string& filename){ + std::string name = filename; + while (!name.empty()){ + char ch = name.back(); + name.pop_back(); + if (ch == '.'){ + break; + } + } + while (!name.empty()){ + char ch = name.back(); + name.pop_back(); + if (ch == '-'){ + break; + } + } + while (!name.empty()){ + char ch = name.back(); + name.pop_back(); + if (ch == '-'){ + break; + } + } + return name; +} + + + +TrainingSession::TrainingSession( + Logger& logger, CancellableScope& scope, + const std::string& training_data_directory +) + : m_logger(logger) + , m_scope(scope) + , m_directory(TRAINING_PATH() + training_data_directory) + , m_total_samples(0) +{ + if (!m_directory.empty() && m_directory.back() != '/' && m_directory.back() != '\\'){ + m_directory += "/"; + } + + logger.log("Parsing training data in: " + m_directory); + + QDirIterator iter(QString::fromStdString(m_directory), QDir::AllDirs); + while (iter.hasNext()){ + iter.next(); + QString sample_directory = iter.fileName() + "/"; + for (size_t c = 1; c < (size_t)Language::EndOfList; c++){ + Language language = (Language)c; + const std::string& code = language_data(language).code; + QString folder = sample_directory + QString::fromStdString(code) + "/"; + QDirIterator iter1(QString::fromStdString(m_directory) + folder, QStringList() << "*.png", QDir::Files); + while (iter1.hasNext()){ + iter1.next(); +// QString file = iter.next(); + m_samples[language].emplace_back( + TrainingSample{ + OCR::extract_name(iter1.fileName().toStdString()), + (folder + iter1.fileName()).toStdString() + } + ); + m_total_samples++; + + scope.throw_if_cancelled(); + } + } + scope.throw_if_cancelled(); + } + + logger.log( + "Parsing Complete: Languages = " + tostr_u_commas(m_samples.size()) + + ", Samples = " + tostr_u_commas(m_total_samples) + ); +} + + +void TrainingSession::generate_small_dictionary( + const std::string& ocr_json_file, + const std::string& output_json_file, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio, double max_text_ratio +){ + m_logger.log("Generating OCR Data..."); + + OCR::SmallDictionaryMatcher baseline(ocr_json_file, !incremental); + OCR::SmallDictionaryMatcher trained(ocr_json_file, !incremental); + + ParallelTaskRunner task_runner( + [](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(); }, + 0, threads + ); + + std::atomic matched(0); + std::atomic failed(0); + for (const auto& language : m_samples){ + const LanguageData& language_info = language_data(language.first); + m_logger.log("Starting Language: " + language_info.name); +// cout << (int)item.first << " : " << item.second.size() << endl; + for (const TrainingSample& sample : language.second){ + task_runner.dispatch([&]{ + ImageRGB32 image(m_directory + sample.filepath); + if (!image){ + m_logger.log("Skipping: " + sample.filepath); + return; + } + + OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( + nullptr, language.first, image, + text_color_ranges, + 0, log10p_spread, + min_text_ratio, max_text_ratio + ); + + OCR::StringMatchResult result0 = result; + result.clear_beyond_log10p(max_log10p); + + if (result.results.empty()){ + failed++; + result0.log(m_logger, max_log10p, sample.filepath); + if (!result0.results.empty()){ + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + } + return; + } + + for (const auto& item : result.results){ + if (item.second.token == sample.token){ + matched++; + return; + } + } + + result.log(m_logger, -99999, sample.filepath); + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + }); + m_scope.throw_if_cancelled(); + } + task_runner.wait_for_everything(); + m_scope.throw_if_cancelled(); + } + + m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); + m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); + m_logger.log("Matched: " + tostr_u_commas(matched)); + m_logger.log("Missed: " + tostr_u_commas(failed)); + + trained.save(output_json_file); +} + +void TrainingSession::generate_large_dictionary( + const std::string& ocr_json_directory, + const std::string& output_prefix, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio, double max_text_ratio +) const{ + m_logger.log("Generating OCR Data..."); + + OCR::LargeDictionaryMatcher baseline(ocr_json_directory + output_prefix, nullptr, !incremental); + OCR::LargeDictionaryMatcher trained(ocr_json_directory + output_prefix, nullptr, !incremental); + + ParallelTaskRunner task_runner( + [](){ GlobalSettings::instance().PERFORMANCE->COMPUTE_PRIORITY.set_on_this_thread(); }, + 0, threads + ); + + std::atomic matched(0); + std::atomic failed(0); + for (const auto& language : m_samples){ + const LanguageData& language_info = language_data(language.first); + m_logger.log("Starting Language: " + language_info.name); +// cout << (int)item.first << " : " << item.second.size() << endl; + for (const TrainingSample& sample : language.second){ + task_runner.dispatch([&]{ + ImageRGB32 image(m_directory + sample.filepath); + if (!image){ + m_logger.log("Skipping: " + sample.filepath); + return; + } + + OCR::StringMatchResult result = baseline.match_substring_from_image_multifiltered( + nullptr, language.first, image, + text_color_ranges, + 0, log10p_spread, + min_text_ratio, max_text_ratio + ); + + OCR::StringMatchResult result0 = result; + result.clear_beyond_log10p(max_log10p); + + if (result.results.empty()){ + failed++; + result0.log(m_logger, max_log10p, sample.filepath); + if (!result0.results.empty()){ + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + } + return; + } + + for (const auto& item : result.results){ + if (item.second.token == sample.token){ + matched++; + return; + } + } + + result.log(m_logger, -99999, sample.filepath); + trained.add_candidate( + language.first, sample.token, + result0.results.begin()->second.normalized_text + ); + }); + m_scope.throw_if_cancelled(); + } + task_runner.wait_for_everything(); + + std::string json = output_prefix + language_info.code + ".json"; + trained.save(language.first, json); + m_scope.throw_if_cancelled(); + } + + m_logger.log("Languages: " + tostr_u_commas(m_samples.size())); + m_logger.log("Samples: " + tostr_u_commas(m_total_samples)); + m_logger.log("Matched: " + tostr_u_commas(matched)); + m_logger.log("Missed: " + tostr_u_commas(failed)); +} + + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h index dc4d84d5e6..542b6704b1 100644 --- a/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h +++ b/SerialPrograms/Source/CommonTools/OCR/OCR_TrainingTools.h @@ -1,73 +1,73 @@ -/* Training Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_OCR_TrainingTools_H -#define PokemonAutomation_CommonTools_OCR_TrainingTools_H - -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/CancellableScope.h" -#include "CommonFramework/Language.h" -#include "OCR_Routines.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -struct TrainingSample{ - std::string token; - std::string filepath; -}; - - -class TrainingSession{ - static constexpr double MAX_LOG10P = -1.90; - static constexpr double LOG10P_SPREAD = 0.10; - -public: - TrainingSession( - Logger& logger, CancellableScope& scope, - const std::string& training_data_directory - ); - - void generate_small_dictionary( - const std::string& ocr_json_file, - const std::string& output_json_file, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ); - void generate_large_dictionary( - const std::string& ocr_json_directory, - const std::string& output_prefix, - bool incremental, - size_t threads, - const std::vector& text_color_ranges, - double max_log10p, double log10p_spread, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -private: - Logger& m_logger; - CancellableScope& m_scope; - std::string m_directory; - size_t m_total_samples; - std::map> m_samples; -}; - - - - -std::string extract_name(const std::string& filename); - - -} -} -#endif +/* Training Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_OCR_TrainingTools_H +#define PokemonAutomation_CommonTools_OCR_TrainingTools_H + +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/CancellableScope.h" +#include "CommonFramework/Language.h" +#include "OCR_Routines.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +struct TrainingSample{ + std::string token; + std::string filepath; +}; + + +class TrainingSession{ + static constexpr double MAX_LOG10P = -1.90; + static constexpr double LOG10P_SPREAD = 0.10; + +public: + TrainingSession( + Logger& logger, CancellableScope& scope, + const std::string& training_data_directory + ); + + void generate_small_dictionary( + const std::string& ocr_json_file, + const std::string& output_json_file, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ); + void generate_large_dictionary( + const std::string& ocr_json_directory, + const std::string& output_prefix, + bool incremental, + size_t threads, + const std::vector& text_color_ranges, + double max_log10p, double log10p_spread, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +private: + Logger& m_logger; + CancellableScope& m_scope; + std::string m_directory; + size_t m_total_samples; + std::map> m_samples; +}; + + + + +std::string extract_name(const std::string& filename); + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp index fea4c71118..4cad788249 100644 --- a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp +++ b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.cpp @@ -1,133 +1,133 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "LanguageOCROption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -LanguageOCRCell::LanguageOCRCell( - const LanguageSet& languages, - LockMode lock_while_running, - bool required -) - : ConfigOption(lock_while_running) - , m_default(0) - , m_current(0) -{ - size_t index = 0; - if (!required && !languages[Language::None]){ - m_case_list.emplace_back( - Language::None, - true - ); - m_case_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(Language::None), - std::forward_as_tuple(index) - ); - index++; - } - for (Language language : languages){ - m_case_list.emplace_back( - language, - language == Language::None || OCR::language_available(language) - ); - m_case_map.emplace( - std::piecewise_construct, - std::forward_as_tuple(language), - std::forward_as_tuple(index) - ); - index++; - } -} - - -void LanguageOCRCell::set(Language language){ - auto iter = m_case_map.find(language); - if (iter == m_case_map.end()){ - return; - } - if (iter->second != m_current.exchange(iter->second, std::memory_order_relaxed)){ - report_value_changed(this); - } -} - - -void LanguageOCRCell::load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return; - } - Language language; - try{ - language = language_code_to_enum(*str); - }catch (const InternalProgramError& e){ - global_logger_tagged().log("Error loading json for language OCR option: " + e.message(), COLOR_RED); - return; - } - - auto iter = m_case_map.find(language); - if (iter == m_case_map.end()){ - const auto& lan_data = language_data(language); - global_logger_tagged().log( - "Warning: no language data for loaded language option " + lan_data.name + " (" + lan_data.code + ").", - COLOR_RED - ); - return; - } - m_current.store(iter->second, std::memory_order_relaxed); - report_value_changed(this); -} -JsonValue LanguageOCRCell::to_json() const{ - return language_data((Language)*this).code; -} - -std::string LanguageOCRCell::check_validity() const{ - return m_case_list[m_current.load(std::memory_order_relaxed)].second ? std::string() : "Language data is not available."; -} -void LanguageOCRCell::restore_defaults(){ - m_current.store(m_default, std::memory_order_relaxed); - report_value_changed(this); -} - - - - - - - - - - - -LanguageOCROption::LanguageOCROption( - std::string label, - const LanguageSet& languages, - LockMode lock_while_running, - bool required -) - : LanguageOCRCell(languages, lock_while_running, required) - , m_label(std::move(label)) -{} - - - - - -} -} - +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "LanguageOCROption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +LanguageOCRCell::LanguageOCRCell( + const LanguageSet& languages, + LockMode lock_while_running, + bool required +) + : ConfigOption(lock_while_running) + , m_default(0) + , m_current(0) +{ + size_t index = 0; + if (!required && !languages[Language::None]){ + m_case_list.emplace_back( + Language::None, + true + ); + m_case_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(Language::None), + std::forward_as_tuple(index) + ); + index++; + } + for (Language language : languages){ + m_case_list.emplace_back( + language, + language == Language::None || OCR::language_available(language) + ); + m_case_map.emplace( + std::piecewise_construct, + std::forward_as_tuple(language), + std::forward_as_tuple(index) + ); + index++; + } +} + + +void LanguageOCRCell::set(Language language){ + auto iter = m_case_map.find(language); + if (iter == m_case_map.end()){ + return; + } + if (iter->second != m_current.exchange(iter->second, std::memory_order_relaxed)){ + report_value_changed(this); + } +} + + +void LanguageOCRCell::load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return; + } + Language language; + try{ + language = language_code_to_enum(*str); + }catch (const InternalProgramError& e){ + global_logger_tagged().log("Error loading json for language OCR option: " + e.message(), COLOR_RED); + return; + } + + auto iter = m_case_map.find(language); + if (iter == m_case_map.end()){ + const auto& lan_data = language_data(language); + global_logger_tagged().log( + "Warning: no language data for loaded language option " + lan_data.name + " (" + lan_data.code + ").", + COLOR_RED + ); + return; + } + m_current.store(iter->second, std::memory_order_relaxed); + report_value_changed(this); +} +JsonValue LanguageOCRCell::to_json() const{ + return language_data((Language)*this).code; +} + +std::string LanguageOCRCell::check_validity() const{ + return m_case_list[m_current.load(std::memory_order_relaxed)].second ? std::string() : "Language data is not available."; +} +void LanguageOCRCell::restore_defaults(){ + m_current.store(m_default, std::memory_order_relaxed); + report_value_changed(this); +} + + + + + + + + + + + +LanguageOCROption::LanguageOCROption( + std::string label, + const LanguageSet& languages, + LockMode lock_while_running, + bool required +) + : LanguageOCRCell(languages, lock_while_running, required) + , m_label(std::move(label)) +{} + + + + + +} +} + diff --git a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h index c63fabca98..413d036a3c 100644 --- a/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h +++ b/SerialPrograms/Source/CommonTools/Options/LanguageOCROption.h @@ -1,79 +1,79 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_LanguageOCROption_H -#define PokemonAutomation_CommonTools_Options_LanguageOCROption_H - -#include -#include -#include -#include "Common/Cpp/Options/ConfigOption.h" -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ -namespace OCR{ - - -class LanguageOCRCell : public ConfigOption{ -public: - LanguageOCRCell( - const LanguageSet& languages, - LockMode lock_while_running, - bool required = true - ); - -// explicit operator bool() const{ return m_case_list[m_current].first != Language::None && m_case_list[m_current].second; } - - operator size_t() const{ return m_current; } - operator Language() const{ return m_case_list[m_current.load(std::memory_order_relaxed)].first; } - void set(Language language); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::string check_validity() const override; - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class LanguageOCRCellWidget; - - std::vector> m_case_list; - std::map m_case_map; - const size_t m_default; - - std::atomic m_current; -}; - - - - -class LanguageOCROption : public LanguageOCRCell{ -public: - LanguageOCROption( - std::string label, - const LanguageSet& languages, - LockMode lock_while_running, - bool required = true - ); - - const std::string& label() const{ return m_label; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class LanguageOCROptionWidget; - - const std::string m_label; -}; - - - - -} -} -#endif +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_LanguageOCROption_H +#define PokemonAutomation_CommonTools_Options_LanguageOCROption_H + +#include +#include +#include +#include "Common/Cpp/Options/ConfigOption.h" +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ +namespace OCR{ + + +class LanguageOCRCell : public ConfigOption{ +public: + LanguageOCRCell( + const LanguageSet& languages, + LockMode lock_while_running, + bool required = true + ); + +// explicit operator bool() const{ return m_case_list[m_current].first != Language::None && m_case_list[m_current].second; } + + operator size_t() const{ return m_current; } + operator Language() const{ return m_case_list[m_current.load(std::memory_order_relaxed)].first; } + void set(Language language); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::string check_validity() const override; + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class LanguageOCRCellWidget; + + std::vector> m_case_list; + std::map m_case_map; + const size_t m_default; + + std::atomic m_current; +}; + + + + +class LanguageOCROption : public LanguageOCRCell{ +public: + LanguageOCROption( + std::string label, + const LanguageSet& languages, + LockMode lock_while_running, + bool required = true + ); + + const std::string& label() const{ return m_label; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class LanguageOCROptionWidget; + + const std::string m_label; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp index c9df0bac7b..1f590e5c89 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.cpp @@ -1,148 +1,148 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "Common/Qt/NoWheelComboBox.h" -#include "LanguageOCRWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -ConfigWidget* LanguageOCRCell::make_QtWidget(QWidget& parent){ - return new LanguageOCRCellWidget(parent, *this); -} -ConfigWidget* LanguageOCROption::make_QtWidget(QWidget& parent){ - return new LanguageOCROptionWidget(parent, *this); -} - - - - -LanguageOCRCellWidget::LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* vbox = new QVBoxLayout(this); - vbox->setContentsMargins(0, 0, 0, 0); - m_box = new NoWheelComboBox(&parent); - - for (const auto& item : m_value.m_case_list){ -// m_enum_to_index[item.first] = (int)m_index_to_enum.size(); - m_index_to_enum.emplace_back(item.first); - m_box->addItem(QString::fromStdString(language_data(item.first).name)); - auto* model = qobject_cast(m_box->model()); - if (model == nullptr){ - continue; - } - QStandardItem* line_handle = model->item(m_box->count() - 1); - if (line_handle != nullptr){ -// line_handle->setEnabled(item.second); - if (!item.second){ - QFont font = line_handle->font(); - font.setStrikeOut(true); - line_handle->setFont(font); - - QBrush brush = line_handle->foreground(); - brush.setColor(Qt::red); - line_handle->setForeground(brush); - } - } - } - vbox->addWidget(m_box); - - m_status = new QLabel(this); - m_status->setTextFormat(Qt::RichText); - m_status->setTextInteractionFlags(Qt::TextBrowserInteraction); - m_status->setOpenExternalLinks(true); - vbox->addWidget(m_status); - - LanguageOCRCellWidget::update_value(); - - connect( - m_box, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0){ - m_value.restore_defaults(); - return; - } - m_value.set(m_index_to_enum[index]); - } - ); -} - - -void LanguageOCRCellWidget::update_value(){ - size_t index = m_value; - m_box->setCurrentIndex((int)index); - - const std::pair& item = m_value.m_case_list[index]; - const LanguageData& language = language_data(item.first); - if (item.second){ - m_status->setVisible(false); - }else{ - m_status->setText( - QString::fromStdString( - "No text recognition data found for " + language.name + ".\n" + - "Download from here." - ) - ); - m_status->setVisible(true); - } -} -void LanguageOCRCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - - -LanguageOCROptionWidget::~LanguageOCROptionWidget(){ - m_value.remove_listener(*this); -} -LanguageOCROptionWidget::LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_cell(new LanguageOCRCellWidget(*this, value)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - layout->addWidget(m_cell, 1); - value.add_listener(*this); -} - - -void LanguageOCROptionWidget::update_value(){ - m_cell->update_value(); -} -void LanguageOCROptionWidget::on_config_value_changed(void* object){ - m_cell->on_config_value_changed(object); -} - - - - - -} -} +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "Common/Qt/NoWheelComboBox.h" +#include "LanguageOCRWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +ConfigWidget* LanguageOCRCell::make_QtWidget(QWidget& parent){ + return new LanguageOCRCellWidget(parent, *this); +} +ConfigWidget* LanguageOCROption::make_QtWidget(QWidget& parent){ + return new LanguageOCROptionWidget(parent, *this); +} + + + + +LanguageOCRCellWidget::LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* vbox = new QVBoxLayout(this); + vbox->setContentsMargins(0, 0, 0, 0); + m_box = new NoWheelComboBox(&parent); + + for (const auto& item : m_value.m_case_list){ +// m_enum_to_index[item.first] = (int)m_index_to_enum.size(); + m_index_to_enum.emplace_back(item.first); + m_box->addItem(QString::fromStdString(language_data(item.first).name)); + auto* model = qobject_cast(m_box->model()); + if (model == nullptr){ + continue; + } + QStandardItem* line_handle = model->item(m_box->count() - 1); + if (line_handle != nullptr){ +// line_handle->setEnabled(item.second); + if (!item.second){ + QFont font = line_handle->font(); + font.setStrikeOut(true); + line_handle->setFont(font); + + QBrush brush = line_handle->foreground(); + brush.setColor(Qt::red); + line_handle->setForeground(brush); + } + } + } + vbox->addWidget(m_box); + + m_status = new QLabel(this); + m_status->setTextFormat(Qt::RichText); + m_status->setTextInteractionFlags(Qt::TextBrowserInteraction); + m_status->setOpenExternalLinks(true); + vbox->addWidget(m_status); + + LanguageOCRCellWidget::update_value(); + + connect( + m_box, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0){ + m_value.restore_defaults(); + return; + } + m_value.set(m_index_to_enum[index]); + } + ); +} + + +void LanguageOCRCellWidget::update_value(){ + size_t index = m_value; + m_box->setCurrentIndex((int)index); + + const std::pair& item = m_value.m_case_list[index]; + const LanguageData& language = language_data(item.first); + if (item.second){ + m_status->setVisible(false); + }else{ + m_status->setText( + QString::fromStdString( + "No text recognition data found for " + language.name + ".\n" + + "Download from here." + ) + ); + m_status->setVisible(true); + } +} +void LanguageOCRCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + + +LanguageOCROptionWidget::~LanguageOCROptionWidget(){ + m_value.remove_listener(*this); +} +LanguageOCROptionWidget::LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_cell(new LanguageOCRCellWidget(*this, value)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + layout->addWidget(m_cell, 1); + value.add_listener(*this); +} + + +void LanguageOCROptionWidget::update_value(){ + m_cell->update_value(); +} +void LanguageOCROptionWidget::on_config_value_changed(void* object){ + m_cell->on_config_value_changed(object); +} + + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h index 28118eb0e6..c32130c599 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/LanguageOCRWidget.h @@ -1,54 +1,54 @@ -/* Language OCR Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H -#define PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonTools/Options/LanguageOCROption.h" - -class QLabel; -class QComboBox; - -namespace PokemonAutomation{ -namespace OCR{ - - -class LanguageOCRCellWidget : public QWidget, public ConfigWidget{ -public: - LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - LanguageOCRCell& m_value; - QComboBox* m_box; - QLabel* m_status; - std::vector m_index_to_enum; -// std::map m_enum_to_index; -}; - - - -class LanguageOCROptionWidget : public QWidget, public ConfigWidget{ -public: - ~LanguageOCROptionWidget(); - LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - LanguageOCRCellWidget* m_cell; -}; - - - -} -} -#endif +/* Language OCR Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H +#define PokemonAutomation_CommonTools_Options_LanguageOCRWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonTools/Options/LanguageOCROption.h" + +class QLabel; +class QComboBox; + +namespace PokemonAutomation{ +namespace OCR{ + + +class LanguageOCRCellWidget : public QWidget, public ConfigWidget{ +public: + LanguageOCRCellWidget(QWidget& parent, LanguageOCRCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + LanguageOCRCell& m_value; + QComboBox* m_box; + QLabel* m_status; + std::vector m_index_to_enum; +// std::map m_enum_to_index; +}; + + + +class LanguageOCROptionWidget : public QWidget, public ConfigWidget{ +public: + ~LanguageOCROptionWidget(); + LanguageOCROptionWidget(QWidget& parent, LanguageOCROption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + LanguageOCRCellWidget* m_cell; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp index 3680f64bbf..7b3d7ce48c 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.cpp @@ -1,235 +1,235 @@ -/* Screen Watch Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "ScreenWatchWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -ConfigWidget* ScreenWatchDisplay::make_QtWidget(QWidget& parent){ - return new ScreenWatchWidget(*this, parent); -} -ConfigWidget* ScreenWatchButtons::make_QtWidget(QWidget& parent){ - return new ScreenWatchButtonWidget(m_option, parent); -} - - -ScreenWatchDisplayWidget::ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent) - : QWidget(&parent) - , m_holder(parent) - , m_option(option) - , m_stop(false) - , m_updater(&ScreenWatchDisplayWidget::thread_loop, this) -{} -ScreenWatchDisplayWidget::~ScreenWatchDisplayWidget(){ - { - std::lock_guard lg(m_lock); - m_stop = true; - m_cv.notify_all(); - } - m_updater.join(); -} -void ScreenWatchDisplayWidget::paintEvent(QPaintEvent* event){ -// cout << "ScreenWatchDisplayWidget::paintEvent: " << m_holder.width() << " x " << m_holder.height() << endl; - QWidget::paintEvent(event); - - VideoSnapshot snapshot = m_last_frame; - if (!snapshot){ - return; - } - - double aspect_ratio = (double)snapshot.frame->width() / snapshot.frame->height(); - if (aspect_ratio < 2.0){ -// cout << "ScreenWatchDisplayWidget::paintEvent: box " << m_holder.width() << " x " << m_holder.height() << endl; - m_holder.set_all(WidgetStackFixedAspectRatio::EXPAND_TO_BOX, aspect_ratio); - m_holder.setFixedHeight(m_holder.width() / 2); - }else{ -// cout << "ScreenWatchDisplayWidget::paintEvent: adjust " << m_holder.width() << " x " << m_holder.height() << endl; - m_holder.set_all(WidgetStackFixedAspectRatio::ADJUST_HEIGHT_TO_WIDTH, aspect_ratio); - } - - QRect rect(0, 0, this->width(), this->height()); - QPainter painter(this); - painter.drawImage(rect, snapshot.frame->to_QImage_ref()); -} - - -void ScreenWatchDisplayWidget::thread_loop(){ - std::unique_lock lg(m_lock); - while (!m_stop){ - m_last_frame = m_option.screenshot(); - QMetaObject::invokeMethod(this, [&]{ - this->update(); - }, Qt::QueuedConnection); - m_cv.wait_for(lg, std::chrono::milliseconds(100)); - } -} - -ScreenWatchWidget::ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent) - : WidgetStackFixedAspectRatio(parent, ADJUST_HEIGHT_TO_WIDTH) - , ConfigWidget(option, *this) -{ - m_widget = new ScreenWatchDisplayWidget(option.m_option, *this); - add_widget(*m_widget); - m_overlay = new VideoOverlayWidget(*this, option.m_option.overlay()); - add_widget(*m_overlay); -} - - - -class SelectorOverlay : public QDialog{ -public: - SelectorOverlay(ScreenWatchOption& option, QWidget& parent, QScreen& screen) - : QDialog(&parent, Qt::FramelessWindowHint) - , m_screen(screen.size()) - { - setAttribute(Qt::WA_TranslucentBackground); - setGeometry(screen.geometry()); - } - - virtual void keyPressEvent(QKeyEvent* event) override{ -// cout << event->key() << endl; - switch (event->key()){ - case Qt::Key_Return: - case Qt::Key_Enter: - case Qt::Key_Escape: - this->accept(); - break; - default: - QDialog::keyPressEvent(event); - } - } - virtual void mousePressEvent(QMouseEvent* event) override{ -// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; - m_mouse_down = true; - m_selected_rect = QRect(); - m_selected_rect.setTopLeft(event->pos()); - m_selected_rect.setWidth(0); - m_selected_rect.setHeight(0); - } - virtual void mouseReleaseEvent(QMouseEvent* event) override{ - m_mouse_down = false; - } - virtual void mouseMoveEvent(QMouseEvent* event) override{ -// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; - if (m_mouse_down){ - m_selected_rect.setBottomRight(event->pos()); - } - update(); - } - virtual void paintEvent(QPaintEvent* event) override{ - QRect rect(0, 0, this->width(), this->height()); - QPainter painter(this); - painter.fillRect(rect, QColor::fromRgb(255, 255, 255, 128)); - - painter.setPen(Qt::red); - painter.fillRect(m_selected_rect, QColor::fromRgb(255, 255, 0, 192)); -// cout << m_selected_rect.x() << ", " << m_selected_rect.y() << " - " << m_selected_rect.width() << ", " << m_selected_rect.height() << endl; - } - - ImageFloatBox get_box() const{ - int x = m_selected_rect.x(); - int y = m_selected_rect.y(); - int w = m_selected_rect.width(); - int h = m_selected_rect.height(); - if (w < 0){ - x += w; - w = -w; - } - if (h < 0){ - y += h; - h = -h; - } - double inv_width = 1 / (double)m_screen.width(); - double inv_height = 1 / (double)m_screen.height(); - return { - x * inv_width, - y * inv_height, - w * inv_width, - h * inv_height, - }; - } - -private: - QSize m_screen; - bool m_mouse_down = false; - QRect m_selected_rect; -}; - - - - -ScreenWatchButtonWidget::ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent) - : QWidget(&parent) - , ConfigWidget(option, *this) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - - QPushButton* draw_box = new QPushButton("Draw Box", this); - QPushButton* reset_button = new QPushButton("Reset to Full Screen", this); - - QHBoxLayout* buttons = new QHBoxLayout(); - layout->addLayout(buttons); - buttons->addWidget(draw_box); - buttons->addWidget(reset_button); - - layout->addWidget(new QLabel("Click on \"Draw Box\" and click+drag to select a region on the target monitor. Press ESC when done.")); - - connect( - draw_box, &QPushButton::clicked, - this, [&](bool){ - qsizetype index = (qsizetype)option.MONITOR_INDEX; - auto screens = QGuiApplication::screens(); - if (screens.size() <= index){ - return; - } - - SelectorOverlay w(option, *this, *screens[index]); - w.exec(); - - ImageFloatBox box = w.get_box(); - if (box.width == 0 || box.height == 0){ - return; - } - - option.X.set(box.x); - option.Y.set(box.y); - option.WIDTH.set(box.width); - option.HEIGHT.set(box.height); - } - ); - - connect( - reset_button, &QPushButton::clicked, - this, [&](bool){ - option.X.set(0.0); - option.Y.set(0.0); - option.WIDTH.set(1.0); - option.HEIGHT.set(1.0); - } - ); -} - - - - - - -} - +/* Screen Watch Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ScreenWatchWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +ConfigWidget* ScreenWatchDisplay::make_QtWidget(QWidget& parent){ + return new ScreenWatchWidget(*this, parent); +} +ConfigWidget* ScreenWatchButtons::make_QtWidget(QWidget& parent){ + return new ScreenWatchButtonWidget(m_option, parent); +} + + +ScreenWatchDisplayWidget::ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent) + : QWidget(&parent) + , m_holder(parent) + , m_option(option) + , m_stop(false) + , m_updater(&ScreenWatchDisplayWidget::thread_loop, this) +{} +ScreenWatchDisplayWidget::~ScreenWatchDisplayWidget(){ + { + std::lock_guard lg(m_lock); + m_stop = true; + m_cv.notify_all(); + } + m_updater.join(); +} +void ScreenWatchDisplayWidget::paintEvent(QPaintEvent* event){ +// cout << "ScreenWatchDisplayWidget::paintEvent: " << m_holder.width() << " x " << m_holder.height() << endl; + QWidget::paintEvent(event); + + VideoSnapshot snapshot = m_last_frame; + if (!snapshot){ + return; + } + + double aspect_ratio = (double)snapshot.frame->width() / snapshot.frame->height(); + if (aspect_ratio < 2.0){ +// cout << "ScreenWatchDisplayWidget::paintEvent: box " << m_holder.width() << " x " << m_holder.height() << endl; + m_holder.set_all(WidgetStackFixedAspectRatio::EXPAND_TO_BOX, aspect_ratio); + m_holder.setFixedHeight(m_holder.width() / 2); + }else{ +// cout << "ScreenWatchDisplayWidget::paintEvent: adjust " << m_holder.width() << " x " << m_holder.height() << endl; + m_holder.set_all(WidgetStackFixedAspectRatio::ADJUST_HEIGHT_TO_WIDTH, aspect_ratio); + } + + QRect rect(0, 0, this->width(), this->height()); + QPainter painter(this); + painter.drawImage(rect, snapshot.frame->to_QImage_ref()); +} + + +void ScreenWatchDisplayWidget::thread_loop(){ + std::unique_lock lg(m_lock); + while (!m_stop){ + m_last_frame = m_option.screenshot(); + QMetaObject::invokeMethod(this, [&]{ + this->update(); + }, Qt::QueuedConnection); + m_cv.wait_for(lg, std::chrono::milliseconds(100)); + } +} + +ScreenWatchWidget::ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent) + : WidgetStackFixedAspectRatio(parent, ADJUST_HEIGHT_TO_WIDTH) + , ConfigWidget(option, *this) +{ + m_widget = new ScreenWatchDisplayWidget(option.m_option, *this); + add_widget(*m_widget); + m_overlay = new VideoOverlayWidget(*this, option.m_option.overlay()); + add_widget(*m_overlay); +} + + + +class SelectorOverlay : public QDialog{ +public: + SelectorOverlay(ScreenWatchOption& option, QWidget& parent, QScreen& screen) + : QDialog(&parent, Qt::FramelessWindowHint) + , m_screen(screen.size()) + { + setAttribute(Qt::WA_TranslucentBackground); + setGeometry(screen.geometry()); + } + + virtual void keyPressEvent(QKeyEvent* event) override{ +// cout << event->key() << endl; + switch (event->key()){ + case Qt::Key_Return: + case Qt::Key_Enter: + case Qt::Key_Escape: + this->accept(); + break; + default: + QDialog::keyPressEvent(event); + } + } + virtual void mousePressEvent(QMouseEvent* event) override{ +// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; + m_mouse_down = true; + m_selected_rect = QRect(); + m_selected_rect.setTopLeft(event->pos()); + m_selected_rect.setWidth(0); + m_selected_rect.setHeight(0); + } + virtual void mouseReleaseEvent(QMouseEvent* event) override{ + m_mouse_down = false; + } + virtual void mouseMoveEvent(QMouseEvent* event) override{ +// cout << event->globalPos().x() << ", " << event->globalPos().y() << endl; + if (m_mouse_down){ + m_selected_rect.setBottomRight(event->pos()); + } + update(); + } + virtual void paintEvent(QPaintEvent* event) override{ + QRect rect(0, 0, this->width(), this->height()); + QPainter painter(this); + painter.fillRect(rect, QColor::fromRgb(255, 255, 255, 128)); + + painter.setPen(Qt::red); + painter.fillRect(m_selected_rect, QColor::fromRgb(255, 255, 0, 192)); +// cout << m_selected_rect.x() << ", " << m_selected_rect.y() << " - " << m_selected_rect.width() << ", " << m_selected_rect.height() << endl; + } + + ImageFloatBox get_box() const{ + int x = m_selected_rect.x(); + int y = m_selected_rect.y(); + int w = m_selected_rect.width(); + int h = m_selected_rect.height(); + if (w < 0){ + x += w; + w = -w; + } + if (h < 0){ + y += h; + h = -h; + } + double inv_width = 1 / (double)m_screen.width(); + double inv_height = 1 / (double)m_screen.height(); + return { + x * inv_width, + y * inv_height, + w * inv_width, + h * inv_height, + }; + } + +private: + QSize m_screen; + bool m_mouse_down = false; + QRect m_selected_rect; +}; + + + + +ScreenWatchButtonWidget::ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent) + : QWidget(&parent) + , ConfigWidget(option, *this) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + + QPushButton* draw_box = new QPushButton("Draw Box", this); + QPushButton* reset_button = new QPushButton("Reset to Full Screen", this); + + QHBoxLayout* buttons = new QHBoxLayout(); + layout->addLayout(buttons); + buttons->addWidget(draw_box); + buttons->addWidget(reset_button); + + layout->addWidget(new QLabel("Click on \"Draw Box\" and click+drag to select a region on the target monitor. Press ESC when done.")); + + connect( + draw_box, &QPushButton::clicked, + this, [&](bool){ + qsizetype index = (qsizetype)option.MONITOR_INDEX; + auto screens = QGuiApplication::screens(); + if (screens.size() <= index){ + return; + } + + SelectorOverlay w(option, *this, *screens[index]); + w.exec(); + + ImageFloatBox box = w.get_box(); + if (box.width == 0 || box.height == 0){ + return; + } + + option.X.set(box.x); + option.Y.set(box.y); + option.WIDTH.set(box.width); + option.HEIGHT.set(box.height); + } + ); + + connect( + reset_button, &QPushButton::clicked, + this, [&](bool){ + option.X.set(0.0); + option.Y.set(0.0); + option.WIDTH.set(1.0); + option.HEIGHT.set(1.0); + } + ); +} + + + + + + +} + diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h index 8a567fbf4b..e7166a3f98 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/ScreenWatchWidget.h @@ -1,60 +1,60 @@ -/* Screen Watch Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H -#define PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H - -#include -#include -#include -#include -#include "Common/Qt/WidgetStackFixedAspectRatio.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h" -#include "CommonTools/Options/ScreenWatchOption.h" - -namespace PokemonAutomation{ - -class ScreenWatchWidget; - - -class ScreenWatchDisplayWidget : public QWidget{ -public: - ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent); - ~ScreenWatchDisplayWidget(); - void paintEvent(QPaintEvent* event) override; - -private: - void thread_loop(); - -private: - ScreenWatchWidget& m_holder; - ScreenWatchOption& m_option; - std::mutex m_lock; - std::condition_variable m_cv; - bool m_stop; - VideoSnapshot m_last_frame; - std::thread m_updater; -}; - -class ScreenWatchWidget : public WidgetStackFixedAspectRatio, public ConfigWidget{ -public: - ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent); - -private: - QWidget* m_widget; - VideoOverlayWidget* m_overlay; -}; - -class ScreenWatchButtonWidget : public QWidget, public ConfigWidget{ -public: - ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent); -}; - - -} -#endif +/* Screen Watch Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H +#define PokemonAutomation_CommonTools_Options_ScreenWatchWidget_H + +#include +#include +#include +#include +#include "Common/Qt/WidgetStackFixedAspectRatio.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/UI/VideoOverlayWidget.h" +#include "CommonTools/Options/ScreenWatchOption.h" + +namespace PokemonAutomation{ + +class ScreenWatchWidget; + + +class ScreenWatchDisplayWidget : public QWidget{ +public: + ScreenWatchDisplayWidget(ScreenWatchOption& option, ScreenWatchWidget& parent); + ~ScreenWatchDisplayWidget(); + void paintEvent(QPaintEvent* event) override; + +private: + void thread_loop(); + +private: + ScreenWatchWidget& m_holder; + ScreenWatchOption& m_option; + std::mutex m_lock; + std::condition_variable m_cv; + bool m_stop; + VideoSnapshot m_last_frame; + std::thread m_updater; +}; + +class ScreenWatchWidget : public WidgetStackFixedAspectRatio, public ConfigWidget{ +public: + ScreenWatchWidget(ScreenWatchDisplay& option, QWidget& parent); + +private: + QWidget* m_widget; + VideoOverlayWidget* m_overlay; +}; + +class ScreenWatchButtonWidget : public QWidget, public ConfigWidget{ +public: + ScreenWatchButtonWidget(ScreenWatchOption& option, QWidget& parent); +}; + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp index 01a4385768..03138f60e6 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.cpp @@ -1,192 +1,192 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Logging/Logger.h" -#include "StringSelectWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - - -ConfigWidget* StringSelectCell::make_QtWidget(QWidget& parent){ - return new StringSelectCellWidget(parent, *this); -} -ConfigWidget* StringSelectOption::make_QtWidget(QWidget& parent){ - return new StringSelectOptionWidget(parent, *this); -} - - - - -StringSelectCellWidget::~StringSelectCellWidget(){ - m_value.remove_listener(*this); -} -StringSelectCellWidget::StringSelectCellWidget(QWidget& parent, StringSelectCell& value) - : NoWheelComboBox(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - this->setEditable(true); - this->setInsertPolicy(QComboBox::NoInsert); - this->completer()->setCompletionMode(QCompleter::PopupCompletion); - this->completer()->setFilterMode(Qt::MatchContains); - this->setIconSize(QSize(25, 25)); -// this->setFrame(false); - - const StringSelectEntry& entry = value.entry(); - QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); - this->addItem(pixmap, QString::fromStdString(entry.display_name)); - this->setCurrentIndex(0); -// this->setMinimumContentsLength((int)value.database().longest_text_length()); - - StringSelectCellWidget::update_value(); - - QPalette palette; - palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); - this->lineEdit()->setPalette(palette); - - connect( - this, static_cast(&QComboBox::activated), - this, [this](int index){ - if (index < 0){ - m_value.restore_defaults(); - return; - } - m_value.set_by_name(this->itemText(index).toStdString()); -// cout << "index = " << index << endl; - } - ); - - value.add_listener(*this); -} - -void StringSelectCellWidget::load_options(){ -// cout << "load_options()" << endl; - const std::vector& cases = m_value.database().case_list(); - if (this->count() <= 1){ - global_logger_tagged().log("Loading dropdown with " + tostr_u_commas(cases.size()) + " elements."); - this->clear(); - for (const StringSelectEntry& item : cases){ - QPixmap pixmap = QPixmap::fromImage(item.icon.to_QImage_ref()); - this->addItem(pixmap, QString::fromStdString(item.display_name)); - if (item.text_color){ - this->setItemData(this->count() - 1, QBrush(QColor((uint32_t)item.text_color)), Qt::ForegroundRole); - } - } - } - size_t index = m_value.index(); - this->setCurrentIndex((int)index); - - QPalette palette; - palette.setColor(QPalette::Text, QColor((uint32_t)cases[index].text_color)); -// palette.setColor(QPalette::Text, Qt::red); - this->lineEdit()->setPalette(palette); - - update_size_cache(); -} -void StringSelectCellWidget::hide_options(){ -// cout << "hide_options()" << endl; - do{ - // All options shown. - if (this->count() > 1){ - break; - } - - // No valid index. - int ui_index = this->currentIndex(); - if (ui_index < 0){ - break; - } - - // Mismatching selection. - std::string name = this->itemText(ui_index).toStdString(); - if (name != m_value.display_name()){ - break; - } - - return; - }while (false); - - // Remove all elements and add the one that is selected. - this->clear(); - const StringSelectEntry& entry = m_value.entry(); - QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); - this->addItem(pixmap, QString::fromStdString(entry.display_name)); - this->setCurrentIndex(0); - - QPalette palette; - palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); -// palette.setColor(QPalette::Text, Qt::red); - this->lineEdit()->setPalette(palette); - -} -QSize StringSelectCellWidget::sizeHint() const{ - QSize ret = NoWheelComboBox::sizeHint(); -// cout << ret.width() << " x " << ret.height() << endl; - - double width = ret.width(); - double height = ret.height(); - - width *= 1.25; - height *= 1.25; - - return QSize((int)width, (int)height); -} -void StringSelectCellWidget::focusInEvent(QFocusEvent* event){ -// cout << "focusInEvent()" << endl; - update_value(); - NoWheelComboBox::focusInEvent(event); -} -void StringSelectCellWidget::focusOutEvent(QFocusEvent* event){ -// cout << "focusOutEvent()" << endl; - NoWheelComboBox::focusOutEvent(event); -// update_value(); -} -void StringSelectCellWidget::update_value(){ - if (hasFocus()){ - load_options(); - }else{ - hide_options(); - } -} -void StringSelectCellWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(this, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -StringSelectOptionWidget::StringSelectOptionWidget(QWidget& parent, StringSelectOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_cell(new StringSelectCellWidget(parent, value)) -{ - QHBoxLayout* layout = new QHBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - QLabel* text = new QLabel(QString::fromStdString(value.label()), this); - text->setWordWrap(true); - layout->addWidget(text, 1); - layout->addWidget(m_cell, 1); -} - - - - - -} +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Logging/Logger.h" +#include "StringSelectWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + + +ConfigWidget* StringSelectCell::make_QtWidget(QWidget& parent){ + return new StringSelectCellWidget(parent, *this); +} +ConfigWidget* StringSelectOption::make_QtWidget(QWidget& parent){ + return new StringSelectOptionWidget(parent, *this); +} + + + + +StringSelectCellWidget::~StringSelectCellWidget(){ + m_value.remove_listener(*this); +} +StringSelectCellWidget::StringSelectCellWidget(QWidget& parent, StringSelectCell& value) + : NoWheelComboBox(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + this->setEditable(true); + this->setInsertPolicy(QComboBox::NoInsert); + this->completer()->setCompletionMode(QCompleter::PopupCompletion); + this->completer()->setFilterMode(Qt::MatchContains); + this->setIconSize(QSize(25, 25)); +// this->setFrame(false); + + const StringSelectEntry& entry = value.entry(); + QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); + this->addItem(pixmap, QString::fromStdString(entry.display_name)); + this->setCurrentIndex(0); +// this->setMinimumContentsLength((int)value.database().longest_text_length()); + + StringSelectCellWidget::update_value(); + + QPalette palette; + palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); + this->lineEdit()->setPalette(palette); + + connect( + this, static_cast(&QComboBox::activated), + this, [this](int index){ + if (index < 0){ + m_value.restore_defaults(); + return; + } + m_value.set_by_name(this->itemText(index).toStdString()); +// cout << "index = " << index << endl; + } + ); + + value.add_listener(*this); +} + +void StringSelectCellWidget::load_options(){ +// cout << "load_options()" << endl; + const std::vector& cases = m_value.database().case_list(); + if (this->count() <= 1){ + global_logger_tagged().log("Loading dropdown with " + tostr_u_commas(cases.size()) + " elements."); + this->clear(); + for (const StringSelectEntry& item : cases){ + QPixmap pixmap = QPixmap::fromImage(item.icon.to_QImage_ref()); + this->addItem(pixmap, QString::fromStdString(item.display_name)); + if (item.text_color){ + this->setItemData(this->count() - 1, QBrush(QColor((uint32_t)item.text_color)), Qt::ForegroundRole); + } + } + } + size_t index = m_value.index(); + this->setCurrentIndex((int)index); + + QPalette palette; + palette.setColor(QPalette::Text, QColor((uint32_t)cases[index].text_color)); +// palette.setColor(QPalette::Text, Qt::red); + this->lineEdit()->setPalette(palette); + + update_size_cache(); +} +void StringSelectCellWidget::hide_options(){ +// cout << "hide_options()" << endl; + do{ + // All options shown. + if (this->count() > 1){ + break; + } + + // No valid index. + int ui_index = this->currentIndex(); + if (ui_index < 0){ + break; + } + + // Mismatching selection. + std::string name = this->itemText(ui_index).toStdString(); + if (name != m_value.display_name()){ + break; + } + + return; + }while (false); + + // Remove all elements and add the one that is selected. + this->clear(); + const StringSelectEntry& entry = m_value.entry(); + QPixmap pixmap = QPixmap::fromImage(entry.icon.to_QImage_ref()); + this->addItem(pixmap, QString::fromStdString(entry.display_name)); + this->setCurrentIndex(0); + + QPalette palette; + palette.setColor(QPalette::Text, QColor((uint32_t)entry.text_color)); +// palette.setColor(QPalette::Text, Qt::red); + this->lineEdit()->setPalette(palette); + +} +QSize StringSelectCellWidget::sizeHint() const{ + QSize ret = NoWheelComboBox::sizeHint(); +// cout << ret.width() << " x " << ret.height() << endl; + + double width = ret.width(); + double height = ret.height(); + + width *= 1.25; + height *= 1.25; + + return QSize((int)width, (int)height); +} +void StringSelectCellWidget::focusInEvent(QFocusEvent* event){ +// cout << "focusInEvent()" << endl; + update_value(); + NoWheelComboBox::focusInEvent(event); +} +void StringSelectCellWidget::focusOutEvent(QFocusEvent* event){ +// cout << "focusOutEvent()" << endl; + NoWheelComboBox::focusOutEvent(event); +// update_value(); +} +void StringSelectCellWidget::update_value(){ + if (hasFocus()){ + load_options(); + }else{ + hide_options(); + } +} +void StringSelectCellWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(this, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +StringSelectOptionWidget::StringSelectOptionWidget(QWidget& parent, StringSelectOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_cell(new StringSelectCellWidget(parent, value)) +{ + QHBoxLayout* layout = new QHBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + QLabel* text = new QLabel(QString::fromStdString(value.label()), this); + text->setWordWrap(true); + layout->addWidget(text, 1); + layout->addWidget(m_cell, 1); +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h index e97469dbe3..90d5a9c3c5 100644 --- a/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h +++ b/SerialPrograms/Source/CommonTools/Options/QtWidgets/StringSelectWidget.h @@ -1,51 +1,51 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_StringSelectWidget_H -#define PokemonAutomation_CommonTools_Options_StringSelectWidget_H - -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ - - -class StringSelectCellWidget : public NoWheelComboBox, public ConfigWidget{ -public: - ~StringSelectCellWidget(); - StringSelectCellWidget(QWidget& parent, StringSelectCell& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - void load_options(); - void hide_options(); - - virtual QSize sizeHint() const override; - virtual void focusInEvent(QFocusEvent* event) override; - virtual void focusOutEvent(QFocusEvent* event) override; - -private: - StringSelectCell& m_value; -}; - - - -class StringSelectOptionWidget : public QWidget, public ConfigWidget{ -public: - StringSelectOptionWidget(QWidget& parent, StringSelectOption& value); - -private: - StringSelectCellWidget* m_cell; -}; - - - -} -#endif +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_StringSelectWidget_H +#define PokemonAutomation_CommonTools_Options_StringSelectWidget_H + +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ + + +class StringSelectCellWidget : public NoWheelComboBox, public ConfigWidget{ +public: + ~StringSelectCellWidget(); + StringSelectCellWidget(QWidget& parent, StringSelectCell& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + void load_options(); + void hide_options(); + + virtual QSize sizeHint() const override; + virtual void focusInEvent(QFocusEvent* event) override; + virtual void focusOutEvent(QFocusEvent* event) override; + +private: + StringSelectCell& m_value; +}; + + + +class StringSelectOptionWidget : public QWidget, public ConfigWidget{ +public: + StringSelectOptionWidget(QWidget& parent, StringSelectOption& value); + +private: + StringSelectCellWidget* m_cell; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp index f85fc31d69..0f8fa01944 100644 --- a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp +++ b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.cpp @@ -1,120 +1,120 @@ -/* Screen Watch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "ScreenWatchOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - -ScreenWatchOption::~ScreenWatchOption() = default; -ScreenWatchOption::ScreenWatchOption( - std::string label, - double default_x, double default_y, - double default_width, double default_height -) - : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) - , MONITOR_INDEX( - "Monitor Index: For multi-monitor setups, this lets you choose which monitor to watch.", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , X( - "X Coordinate: The left edge of the box to watch.
" - "0.0 is the left edge of the monitor. 1.0 is the right edge of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_x, 0.0, 1.0 - ) - , Y( - "Y Coordinate: The top edge of the box to watch.
" - "0.0 is the top edge of the monitor. 1.0 is the bottom edge of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_y, 0.0, 1.0 - ) - , WIDTH( - "Width: The width of the box to watch.
" - "The number is between 0 and 1 and is the proportion of the full width of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_width, 0.0, 1.0 - ) - , HEIGHT( - "Height: The height of the box to watch.
" - "The number is between 0 and 1 and is the proportion of the full height of the monitor.", - LockMode::UNLOCK_WHILE_RUNNING, - default_height, 0.0, 1.0 - ) - , m_display(*this) - , m_buttons(*this) - , m_overlay(m_overlay_option) -{ - PA_ADD_OPTION(m_display); - PA_ADD_OPTION(MONITOR_INDEX); - PA_ADD_OPTION(X); - PA_ADD_OPTION(Y); - PA_ADD_OPTION(WIDTH); - PA_ADD_OPTION(HEIGHT); - PA_ADD_OPTION(m_buttons); -} - - -double ScreenWatchOption::aspect_ratio(){ - qsizetype index = (qsizetype)MONITOR_INDEX; - auto screens = QGuiApplication::screens(); - if (screens.size() <= index){ - return 0; - } - - QScreen& screen = *screens[index]; - - QSize size = screen.size(); - int width = (int)(size.width() * WIDTH + 0.5); - int height = (int)(size.height() * HEIGHT + 0.5); - return (double)width / height; -} -VideoSnapshot ScreenWatchOption::screenshot(){ - qsizetype index = (qsizetype)MONITOR_INDEX; - auto screens = QGuiApplication::screens(); - if (screens.size() <= index){ - return VideoSnapshot(); - } - - QScreen& screen = *screens[index]; - - QSize size = screen.size(); -// int width = screen.size().width(); -// int height = screen.size().height(); - - int min_x = (int)(size.width() * X + 0.5); - int min_y = (int)(size.height() * Y + 0.5); - int width = (int)(size.width() * WIDTH + 0.5); - int height = (int)(size.height() * HEIGHT + 0.5); - WallClock now = current_time(); - QPixmap pm = screen.grabWindow(0, min_x, min_y, width, height); - return VideoSnapshot(pm.toImage(), now); -} - - -VideoOverlaySession& ScreenWatchOption::overlay(){ - return m_overlay; -} - - - - - -} +/* Screen Watch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "ScreenWatchOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +ScreenWatchOption::~ScreenWatchOption() = default; +ScreenWatchOption::ScreenWatchOption( + std::string label, + double default_x, double default_y, + double default_width, double default_height +) + : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) + , MONITOR_INDEX( + "Monitor Index: For multi-monitor setups, this lets you choose which monitor to watch.", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , X( + "X Coordinate: The left edge of the box to watch.
" + "0.0 is the left edge of the monitor. 1.0 is the right edge of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_x, 0.0, 1.0 + ) + , Y( + "Y Coordinate: The top edge of the box to watch.
" + "0.0 is the top edge of the monitor. 1.0 is the bottom edge of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_y, 0.0, 1.0 + ) + , WIDTH( + "Width: The width of the box to watch.
" + "The number is between 0 and 1 and is the proportion of the full width of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_width, 0.0, 1.0 + ) + , HEIGHT( + "Height: The height of the box to watch.
" + "The number is between 0 and 1 and is the proportion of the full height of the monitor.", + LockMode::UNLOCK_WHILE_RUNNING, + default_height, 0.0, 1.0 + ) + , m_display(*this) + , m_buttons(*this) + , m_overlay(m_overlay_option) +{ + PA_ADD_OPTION(m_display); + PA_ADD_OPTION(MONITOR_INDEX); + PA_ADD_OPTION(X); + PA_ADD_OPTION(Y); + PA_ADD_OPTION(WIDTH); + PA_ADD_OPTION(HEIGHT); + PA_ADD_OPTION(m_buttons); +} + + +double ScreenWatchOption::aspect_ratio(){ + qsizetype index = (qsizetype)MONITOR_INDEX; + auto screens = QGuiApplication::screens(); + if (screens.size() <= index){ + return 0; + } + + QScreen& screen = *screens[index]; + + QSize size = screen.size(); + int width = (int)(size.width() * WIDTH + 0.5); + int height = (int)(size.height() * HEIGHT + 0.5); + return (double)width / height; +} +VideoSnapshot ScreenWatchOption::screenshot(){ + qsizetype index = (qsizetype)MONITOR_INDEX; + auto screens = QGuiApplication::screens(); + if (screens.size() <= index){ + return VideoSnapshot(); + } + + QScreen& screen = *screens[index]; + + QSize size = screen.size(); +// int width = screen.size().width(); +// int height = screen.size().height(); + + int min_x = (int)(size.width() * X + 0.5); + int min_y = (int)(size.height() * Y + 0.5); + int width = (int)(size.width() * WIDTH + 0.5); + int height = (int)(size.height() * HEIGHT + 0.5); + WallClock now = current_time(); + QPixmap pm = screen.grabWindow(0, min_x, min_y, width, height); + return VideoSnapshot(pm.toImage(), now); +} + + +VideoOverlaySession& ScreenWatchOption::overlay(){ + return m_overlay; +} + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h index 9fcf0ab5de..4778a690e7 100644 --- a/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h +++ b/SerialPrograms/Source/CommonTools/Options/ScreenWatchOption.h @@ -1,86 +1,86 @@ -/* Screen Watch Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchOption_H -#define PokemonAutomation_CommonTools_Options_ScreenWatchOption_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" - -namespace PokemonAutomation{ - -struct VideoSnapshot; -class ScreenWatchOption; - - -class ScreenWatchDisplay : public ConfigOption{ -public: - ScreenWatchDisplay(ScreenWatchOption& option) - : m_option(option) - {} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - ScreenWatchOption& m_option; -}; -class ScreenWatchButtons : public ConfigOption{ -public: - ScreenWatchButtons(ScreenWatchOption& option) - : m_option(option) - {} - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - ScreenWatchOption& m_option; -}; - - - -class ScreenWatchOption : public GroupOption{ -public: - ~ScreenWatchOption(); - ScreenWatchOption( - std::string label, - double default_x = 0, double default_y = 0, - double default_width = 1, double default_height = 1 - ); - -// virtual void load_json(const JsonValue& json) override; -// virtual JsonValue to_json() const override; - -// virtual void restore_defaults() override; - -// virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - double aspect_ratio(); - VideoSnapshot screenshot(); - - VideoOverlaySession& overlay(); - -public: - SimpleIntegerOption MONITOR_INDEX; - FloatingPointOption X; - FloatingPointOption Y; - FloatingPointOption WIDTH; - FloatingPointOption HEIGHT; - -private: - ScreenWatchDisplay m_display; - ScreenWatchButtons m_buttons; - - VideoOverlayOption m_overlay_option; - VideoOverlaySession m_overlay; -}; - - - - - - -} -#endif +/* Screen Watch Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_ScreenWatchOption_H +#define PokemonAutomation_CommonTools_Options_ScreenWatchOption_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" + +namespace PokemonAutomation{ + +struct VideoSnapshot; +class ScreenWatchOption; + + +class ScreenWatchDisplay : public ConfigOption{ +public: + ScreenWatchDisplay(ScreenWatchOption& option) + : m_option(option) + {} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + ScreenWatchOption& m_option; +}; +class ScreenWatchButtons : public ConfigOption{ +public: + ScreenWatchButtons(ScreenWatchOption& option) + : m_option(option) + {} + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + ScreenWatchOption& m_option; +}; + + + +class ScreenWatchOption : public GroupOption{ +public: + ~ScreenWatchOption(); + ScreenWatchOption( + std::string label, + double default_x = 0, double default_y = 0, + double default_width = 1, double default_height = 1 + ); + +// virtual void load_json(const JsonValue& json) override; +// virtual JsonValue to_json() const override; + +// virtual void restore_defaults() override; + +// virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + double aspect_ratio(); + VideoSnapshot screenshot(); + + VideoOverlaySession& overlay(); + +public: + SimpleIntegerOption MONITOR_INDEX; + FloatingPointOption X; + FloatingPointOption Y; + FloatingPointOption WIDTH; + FloatingPointOption HEIGHT; + +private: + ScreenWatchDisplay m_display; + ScreenWatchButtons m_buttons; + + VideoOverlayOption m_overlay_option; + VideoOverlaySession m_overlay; +}; + + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp index 8f96468bfa..53456ac0ca 100644 --- a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp +++ b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.cpp @@ -1,259 +1,259 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "StringSelectOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -struct StringSelectDatabase::Data{ - size_t m_longest_text_length = 0; - std::vector m_list; - std::map m_slug_to_entry; - std::map m_display_name_to_entry; - - size_t search_index_by_slug(const std::string& slug) const{ - auto iter = m_slug_to_entry.find(slug); - if (iter == m_slug_to_entry.end()){ - return (size_t)0 - 1; - } - return iter->second; - } - size_t search_index_by_name(const std::string& display_name) const{ - auto iter = m_display_name_to_entry.find(display_name); - if (iter == m_display_name_to_entry.end()){ - return (size_t)0 - 1; - } - return iter->second; - } - void add_entry(StringSelectEntry entry){ - size_t index = m_list.size(); - StringSelectEntry& item = m_list.emplace_back(std::move(entry)); - - std::map::const_iterator iter0 = m_slug_to_entry.end(); - std::map::const_iterator iter1 = m_display_name_to_entry.end(); - - try{ - auto ret0 = m_slug_to_entry.emplace(item.slug, index); - if (ret0.second){ - iter0 = ret0.first; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + item.slug); - } - auto ret1 = m_display_name_to_entry.emplace(item.display_name, index); - if (ret1.second){ - iter1 = ret1.first; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Display Name: " + item.display_name); - } - }catch (...){ - m_list.pop_back(); - if (iter0 != m_slug_to_entry.end()){ - m_slug_to_entry.erase(iter0); - } - if (iter1 != m_display_name_to_entry.end()){ - m_slug_to_entry.erase(iter1); - } - throw; - } - - m_longest_text_length = std::max(m_longest_text_length, item.display_name.size()); - } -}; - - - -StringSelectDatabase::~StringSelectDatabase() = default; -StringSelectDatabase::StringSelectDatabase(StringSelectDatabase&&) = default; -StringSelectDatabase& StringSelectDatabase::operator=(StringSelectDatabase&&) = default; -StringSelectDatabase::StringSelectDatabase(const StringSelectDatabase&) = default; -StringSelectDatabase& StringSelectDatabase::operator=(const StringSelectDatabase&) = default; -StringSelectDatabase::StringSelectDatabase() - : m_data(CONSTRUCT_TOKEN) -{} - -size_t StringSelectDatabase::longest_text_length() const{ - return m_data->m_longest_text_length; -} -const std::vector& StringSelectDatabase::case_list() const{ - return m_data->m_list; -} -const StringSelectEntry& StringSelectDatabase::operator[](size_t index) const{ - return m_data->m_list[index]; -} -size_t StringSelectDatabase::search_index_by_slug(const std::string& slug) const{ - return m_data->search_index_by_slug(slug); -} -size_t StringSelectDatabase::search_index_by_name(const std::string& display_name) const{ - return m_data->search_index_by_name(display_name); -} -void StringSelectDatabase::add_entry(StringSelectEntry entry){ - m_data->add_entry(std::move(entry)); -} - - - - - -struct StringSelectCell::Data{ - const StringSelectDatabase& m_database; - const size_t m_default; - std::atomic m_index; - - Data(const StringSelectDatabase& database, size_t default_index) - : m_database(database) - , m_default(default_index) - , m_index(default_index) - { - if (default_index >= database.case_list().size()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Index: " + std::to_string(default_index)); - } - } - Data(const StringSelectDatabase& database, const std::string& default_slug) - : m_database(database) - , m_default(default_slug == "" ? 0 : database.search_index_by_slug(default_slug)) - , m_index(m_default) - { - if (m_default == (size_t)0 - 1){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Slug: " + default_slug); - } - } - - bool load_json(const JsonValue& json){ - const std::string* str = json.to_string(); - if (str == nullptr){ - return false; - } - size_t index = m_database.search_index_by_slug(*str); - if (index == (size_t)0 - 1){ - return false; - } - m_index.store(index, std::memory_order_relaxed); - return true; - } - JsonValue to_json() const{ - return m_database.case_list()[m_index.load(std::memory_order_relaxed)].slug; - } - void restore_defaults(){ - m_index.store(m_default, std::memory_order_relaxed); - } -}; - - - - - -StringSelectCell::~StringSelectCell() = default; - - -StringSelectCell::StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - size_t default_index -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, database, default_index) -{} -StringSelectCell::StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - const std::string& default_slug -) - : ConfigOption(lock_while_running) - , m_data(CONSTRUCT_TOKEN, database, default_slug) -{} - - -size_t StringSelectCell::default_index() const{ - return m_data->m_default; -} -const std::string& StringSelectCell::default_slug() const{ - return m_data->m_database.case_list()[m_data->m_default].slug; -} - -size_t StringSelectCell::index() const{ - return m_data->m_index.load(std::memory_order_relaxed); -} - -void StringSelectCell::set_by_index(size_t index){ - if (index >= m_data->m_database.case_list().size()){ - index = m_data->m_default; - } - if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ - report_value_changed(this); - } -} -std::string StringSelectCell::set_by_slug(const std::string& slug){ - size_t index = m_data->m_database.search_index_by_slug(slug); - if (index == (size_t)0 - 1){ - return "Invalid Slug: " + slug; - } - if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ - report_value_changed(this); - } - return ""; -} -std::string StringSelectCell::set_by_name(const std::string& display_name){ - size_t index = m_data->m_database.search_index_by_name(display_name); - if (index == (size_t)0 - 1){ - return "Invalid Name: " + display_name; - } - if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ - report_value_changed(this); - } - return ""; -} - -const StringSelectDatabase& StringSelectCell::database() const{ - return m_data->m_database; -} - -void StringSelectCell::load_json(const JsonValue& json){ - if (m_data->load_json(json)){ - report_value_changed(this); - } -} -JsonValue StringSelectCell::to_json() const{ - return m_data->to_json(); -} -void StringSelectCell::restore_defaults(){ - m_data->restore_defaults(); - report_value_changed(this); -} - - - - - - - - - - - - - - - - - - - - - -} +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "StringSelectOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +struct StringSelectDatabase::Data{ + size_t m_longest_text_length = 0; + std::vector m_list; + std::map m_slug_to_entry; + std::map m_display_name_to_entry; + + size_t search_index_by_slug(const std::string& slug) const{ + auto iter = m_slug_to_entry.find(slug); + if (iter == m_slug_to_entry.end()){ + return (size_t)0 - 1; + } + return iter->second; + } + size_t search_index_by_name(const std::string& display_name) const{ + auto iter = m_display_name_to_entry.find(display_name); + if (iter == m_display_name_to_entry.end()){ + return (size_t)0 - 1; + } + return iter->second; + } + void add_entry(StringSelectEntry entry){ + size_t index = m_list.size(); + StringSelectEntry& item = m_list.emplace_back(std::move(entry)); + + std::map::const_iterator iter0 = m_slug_to_entry.end(); + std::map::const_iterator iter1 = m_display_name_to_entry.end(); + + try{ + auto ret0 = m_slug_to_entry.emplace(item.slug, index); + if (ret0.second){ + iter0 = ret0.first; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Slug: " + item.slug); + } + auto ret1 = m_display_name_to_entry.emplace(item.display_name, index); + if (ret1.second){ + iter1 = ret1.first; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Display Name: " + item.display_name); + } + }catch (...){ + m_list.pop_back(); + if (iter0 != m_slug_to_entry.end()){ + m_slug_to_entry.erase(iter0); + } + if (iter1 != m_display_name_to_entry.end()){ + m_slug_to_entry.erase(iter1); + } + throw; + } + + m_longest_text_length = std::max(m_longest_text_length, item.display_name.size()); + } +}; + + + +StringSelectDatabase::~StringSelectDatabase() = default; +StringSelectDatabase::StringSelectDatabase(StringSelectDatabase&&) = default; +StringSelectDatabase& StringSelectDatabase::operator=(StringSelectDatabase&&) = default; +StringSelectDatabase::StringSelectDatabase(const StringSelectDatabase&) = default; +StringSelectDatabase& StringSelectDatabase::operator=(const StringSelectDatabase&) = default; +StringSelectDatabase::StringSelectDatabase() + : m_data(CONSTRUCT_TOKEN) +{} + +size_t StringSelectDatabase::longest_text_length() const{ + return m_data->m_longest_text_length; +} +const std::vector& StringSelectDatabase::case_list() const{ + return m_data->m_list; +} +const StringSelectEntry& StringSelectDatabase::operator[](size_t index) const{ + return m_data->m_list[index]; +} +size_t StringSelectDatabase::search_index_by_slug(const std::string& slug) const{ + return m_data->search_index_by_slug(slug); +} +size_t StringSelectDatabase::search_index_by_name(const std::string& display_name) const{ + return m_data->search_index_by_name(display_name); +} +void StringSelectDatabase::add_entry(StringSelectEntry entry){ + m_data->add_entry(std::move(entry)); +} + + + + + +struct StringSelectCell::Data{ + const StringSelectDatabase& m_database; + const size_t m_default; + std::atomic m_index; + + Data(const StringSelectDatabase& database, size_t default_index) + : m_database(database) + , m_default(default_index) + , m_index(default_index) + { + if (default_index >= database.case_list().size()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Index: " + std::to_string(default_index)); + } + } + Data(const StringSelectDatabase& database, const std::string& default_slug) + : m_database(database) + , m_default(default_slug == "" ? 0 : database.search_index_by_slug(default_slug)) + , m_index(m_default) + { + if (m_default == (size_t)0 - 1){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Default Slug: " + default_slug); + } + } + + bool load_json(const JsonValue& json){ + const std::string* str = json.to_string(); + if (str == nullptr){ + return false; + } + size_t index = m_database.search_index_by_slug(*str); + if (index == (size_t)0 - 1){ + return false; + } + m_index.store(index, std::memory_order_relaxed); + return true; + } + JsonValue to_json() const{ + return m_database.case_list()[m_index.load(std::memory_order_relaxed)].slug; + } + void restore_defaults(){ + m_index.store(m_default, std::memory_order_relaxed); + } +}; + + + + + +StringSelectCell::~StringSelectCell() = default; + + +StringSelectCell::StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + size_t default_index +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, database, default_index) +{} +StringSelectCell::StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + const std::string& default_slug +) + : ConfigOption(lock_while_running) + , m_data(CONSTRUCT_TOKEN, database, default_slug) +{} + + +size_t StringSelectCell::default_index() const{ + return m_data->m_default; +} +const std::string& StringSelectCell::default_slug() const{ + return m_data->m_database.case_list()[m_data->m_default].slug; +} + +size_t StringSelectCell::index() const{ + return m_data->m_index.load(std::memory_order_relaxed); +} + +void StringSelectCell::set_by_index(size_t index){ + if (index >= m_data->m_database.case_list().size()){ + index = m_data->m_default; + } + if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ + report_value_changed(this); + } +} +std::string StringSelectCell::set_by_slug(const std::string& slug){ + size_t index = m_data->m_database.search_index_by_slug(slug); + if (index == (size_t)0 - 1){ + return "Invalid Slug: " + slug; + } + if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ + report_value_changed(this); + } + return ""; +} +std::string StringSelectCell::set_by_name(const std::string& display_name){ + size_t index = m_data->m_database.search_index_by_name(display_name); + if (index == (size_t)0 - 1){ + return "Invalid Name: " + display_name; + } + if (index != m_data->m_index.exchange(index, std::memory_order_relaxed)){ + report_value_changed(this); + } + return ""; +} + +const StringSelectDatabase& StringSelectCell::database() const{ + return m_data->m_database; +} + +void StringSelectCell::load_json(const JsonValue& json){ + if (m_data->load_json(json)){ + report_value_changed(this); + } +} +JsonValue StringSelectCell::to_json() const{ + return m_data->to_json(); +} +void StringSelectCell::restore_defaults(){ + m_data->restore_defaults(); + report_value_changed(this); +} + + + + + + + + + + + + + + + + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h index c709b4ece5..58c9c446ab 100644 --- a/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h +++ b/SerialPrograms/Source/CommonTools/Options/StringSelectOption.h @@ -1,154 +1,154 @@ -/* String Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_StringSelectOption_H -#define PokemonAutomation_CommonTools_Options_StringSelectOption_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/Pimpl.h" -#include "Common/Cpp/Options/ConfigOption.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ - - - - -struct StringSelectEntry{ - std::string slug; - std::string display_name; - ImageViewRGB32 icon; - Color text_color; - - StringSelectEntry( - std::string p_slug, - std::string p_display_name, - ImageViewRGB32 p_icon = ImageViewRGB32(), - Color p_text_color = Color() - ) - : slug(std::move(p_slug)) - , display_name(std::move(p_display_name)) - , icon(std::move(p_icon)) - , text_color(p_text_color) - {} -}; - - - -class StringSelectDatabase{ -public: - ~StringSelectDatabase(); - StringSelectDatabase(StringSelectDatabase&&); - StringSelectDatabase& operator=(StringSelectDatabase&&); - StringSelectDatabase(const StringSelectDatabase&); - StringSelectDatabase& operator=(const StringSelectDatabase&); - -public: - StringSelectDatabase(); - void add_entry(StringSelectEntry entry); - -public: - const std::vector& case_list() const; - size_t longest_text_length() const; - - const StringSelectEntry& operator[](size_t index) const; - size_t search_index_by_slug(const std::string& slug) const; - size_t search_index_by_name(const std::string& display_name) const; - -private: - struct Data; - Pimpl m_data; -}; - - - -class StringSelectCell : public ConfigOption{ -public: - ~StringSelectCell(); - StringSelectCell(const StringSelectCell&) = delete; - void operator=(const StringSelectCell&) = delete; - -public: - StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - size_t default_index - ); - StringSelectCell( - const StringSelectDatabase& database, - LockMode lock_while_running, - const std::string& default_slug - ); - - size_t default_index() const; - const std::string& default_slug() const; - - size_t index() const; - const std::string& slug() const{ - return entry().slug; - } - const std::string& display_name() const{ - return entry().display_name; - } - const StringSelectEntry& entry() const{ - return database()[index()]; - } - - void set_by_index(size_t index); - std::string set_by_slug(const std::string& slug); - std::string set_by_name(const std::string& display_name); - - const StringSelectDatabase& database() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - struct Data; - Pimpl m_data; -}; - - - -class StringSelectOption : public StringSelectCell{ -public: - StringSelectOption( - std::string label, - const StringSelectDatabase& database, - LockMode lock_while_running, - size_t default_index - ) - : StringSelectCell(database, lock_while_running, default_index) - , m_label(std::move(label)) - {} - StringSelectOption( - std::string label, - const StringSelectDatabase& database, - LockMode lock_while_running, - const std::string& default_slug - ) - : StringSelectCell(database, lock_while_running, default_slug) - , m_label(std::move(label)) - {} - - const std::string& label() const{ return m_label; } - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - std::string m_label; -}; - - - - - -} -#endif +/* String Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_StringSelectOption_H +#define PokemonAutomation_CommonTools_Options_StringSelectOption_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/Pimpl.h" +#include "Common/Cpp/Options/ConfigOption.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ + + + + +struct StringSelectEntry{ + std::string slug; + std::string display_name; + ImageViewRGB32 icon; + Color text_color; + + StringSelectEntry( + std::string p_slug, + std::string p_display_name, + ImageViewRGB32 p_icon = ImageViewRGB32(), + Color p_text_color = Color() + ) + : slug(std::move(p_slug)) + , display_name(std::move(p_display_name)) + , icon(std::move(p_icon)) + , text_color(p_text_color) + {} +}; + + + +class StringSelectDatabase{ +public: + ~StringSelectDatabase(); + StringSelectDatabase(StringSelectDatabase&&); + StringSelectDatabase& operator=(StringSelectDatabase&&); + StringSelectDatabase(const StringSelectDatabase&); + StringSelectDatabase& operator=(const StringSelectDatabase&); + +public: + StringSelectDatabase(); + void add_entry(StringSelectEntry entry); + +public: + const std::vector& case_list() const; + size_t longest_text_length() const; + + const StringSelectEntry& operator[](size_t index) const; + size_t search_index_by_slug(const std::string& slug) const; + size_t search_index_by_name(const std::string& display_name) const; + +private: + struct Data; + Pimpl m_data; +}; + + + +class StringSelectCell : public ConfigOption{ +public: + ~StringSelectCell(); + StringSelectCell(const StringSelectCell&) = delete; + void operator=(const StringSelectCell&) = delete; + +public: + StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + size_t default_index + ); + StringSelectCell( + const StringSelectDatabase& database, + LockMode lock_while_running, + const std::string& default_slug + ); + + size_t default_index() const; + const std::string& default_slug() const; + + size_t index() const; + const std::string& slug() const{ + return entry().slug; + } + const std::string& display_name() const{ + return entry().display_name; + } + const StringSelectEntry& entry() const{ + return database()[index()]; + } + + void set_by_index(size_t index); + std::string set_by_slug(const std::string& slug); + std::string set_by_name(const std::string& display_name); + + const StringSelectDatabase& database() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + struct Data; + Pimpl m_data; +}; + + + +class StringSelectOption : public StringSelectCell{ +public: + StringSelectOption( + std::string label, + const StringSelectDatabase& database, + LockMode lock_while_running, + size_t default_index + ) + : StringSelectCell(database, lock_while_running, default_index) + , m_label(std::move(label)) + {} + StringSelectOption( + std::string label, + const StringSelectDatabase& database, + LockMode lock_while_running, + const std::string& default_slug + ) + : StringSelectCell(database, lock_while_running, default_slug) + , m_label(std::move(label)) + {} + + const std::string& label() const{ return m_label; } + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + std::string m_label; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h b/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h index 8363afad12..cafeb26de1 100644 --- a/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h +++ b/SerialPrograms/Source/CommonTools/Options/StringSelectTableOption.h @@ -1,76 +1,76 @@ -/* String Select Table - * - * From: https://github.com/PokemonAutomation/ - * - * A simple editable table of StringSelect options. - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_StringSelectTableOption_H -#define PokemonAutomation_CommonTools_Options_StringSelectTableOption_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "StringSelectOption.h" - -namespace PokemonAutomation{ - - -class StringSelectTableRow : public EditableTableRow{ -public: - StringSelectTableRow( - EditableTableOption& parent_table, - const StringSelectDatabase& database, const std::string& default_slug - ) - : EditableTableRow(parent_table) - , cell(database, LockMode::LOCK_WHILE_RUNNING, default_slug) - { - PA_ADD_OPTION(cell); - } - virtual std::unique_ptr clone() const{ - std::unique_ptr ret(new StringSelectTableRow(parent(), cell.database(), cell.default_slug())); - ret->cell.set_by_index(cell.index()); - return ret; - } - -public: - StringSelectCell cell; -}; - - -class StringSelectTableOption : public EditableTableOption{ -public: - StringSelectTableOption( - std::string label, - std::string header, const StringSelectDatabase& database, std::string default_slug - ) - : EditableTableOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) - , m_header(std::move(header)) - , m_database(database) - , m_default_slug(std::move(default_slug)) - {} - - std::vector all_slugs() const{ - std::vector slugs; - for (const auto& item : copy_snapshot()){ - slugs.emplace_back(item->cell.slug()); - } - return slugs; - } - - virtual std::vector make_header() const{ - return {m_header}; - } - virtual std::unique_ptr make_row(){ - return std::make_unique(*this, m_database, m_default_slug); - } - -private: - const std::string m_header; - const StringSelectDatabase& m_database; - const std::string m_default_slug; -}; - - - -} -#endif +/* String Select Table + * + * From: https://github.com/PokemonAutomation/ + * + * A simple editable table of StringSelect options. + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_StringSelectTableOption_H +#define PokemonAutomation_CommonTools_Options_StringSelectTableOption_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "StringSelectOption.h" + +namespace PokemonAutomation{ + + +class StringSelectTableRow : public EditableTableRow{ +public: + StringSelectTableRow( + EditableTableOption& parent_table, + const StringSelectDatabase& database, const std::string& default_slug + ) + : EditableTableRow(parent_table) + , cell(database, LockMode::LOCK_WHILE_RUNNING, default_slug) + { + PA_ADD_OPTION(cell); + } + virtual std::unique_ptr clone() const{ + std::unique_ptr ret(new StringSelectTableRow(parent(), cell.database(), cell.default_slug())); + ret->cell.set_by_index(cell.index()); + return ret; + } + +public: + StringSelectCell cell; +}; + + +class StringSelectTableOption : public EditableTableOption{ +public: + StringSelectTableOption( + std::string label, + std::string header, const StringSelectDatabase& database, std::string default_slug + ) + : EditableTableOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , m_header(std::move(header)) + , m_database(database) + , m_default_slug(std::move(default_slug)) + {} + + std::vector all_slugs() const{ + std::vector slugs; + for (const auto& item : copy_snapshot()){ + slugs.emplace_back(item->cell.slug()); + } + return slugs; + } + + virtual std::vector make_header() const{ + return {m_header}; + } + virtual std::unique_ptr make_row(){ + return std::make_unique(*this, m_database, m_default_slug); + } + +private: + const std::string m_header; + const StringSelectDatabase& m_database; + const std::string m_default_slug; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h b/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h index 17294fe038..3044ca9145 100644 --- a/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h +++ b/SerialPrograms/Source/CommonTools/Options/TrainOCRModeOption.h @@ -1,39 +1,39 @@ -/* Train OCR Mode Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H -#define PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ - -enum class TrainOCRMode{ - GENERATE_BASELINE, - START_FRESH, - INCREMENTAL, -}; - -class TrainOCRModeOption : public EnumDropdownOption{ -public: - TrainOCRModeOption() - : EnumDropdownOption( - "Mode:", - { - {TrainOCRMode::GENERATE_BASELINE, "baseline", "Generate Baseline: Generate baseline data using display names."}, - {TrainOCRMode::START_FRESH, "start-fresh", "Start Fresh: Use only baseline strings. (1st candidate of each entry in above path)"}, - {TrainOCRMode::INCREMENTAL, "incremental", "Incremental: Build off of the existing training data in the above path."}, - }, - LockMode::LOCK_WHILE_RUNNING, - TrainOCRMode::GENERATE_BASELINE - ) - {} -}; - - - -} -#endif +/* Train OCR Mode Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H +#define PokemonAutomation_CommonTools_Options_TrainOCRModeOption_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ + +enum class TrainOCRMode{ + GENERATE_BASELINE, + START_FRESH, + INCREMENTAL, +}; + +class TrainOCRModeOption : public EnumDropdownOption{ +public: + TrainOCRModeOption() + : EnumDropdownOption( + "Mode:", + { + {TrainOCRMode::GENERATE_BASELINE, "baseline", "Generate Baseline: Generate baseline data using display names."}, + {TrainOCRMode::START_FRESH, "start-fresh", "Start Fresh: Use only baseline strings. (1st candidate of each entry in above path)"}, + {TrainOCRMode::INCREMENTAL, "incremental", "Incremental: Build off of the existing training data in the above path."}, + }, + LockMode::LOCK_WHILE_RUNNING, + TrainOCRMode::GENERATE_BASELINE + ) + {} +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp index c8a04f5f78..fadd2fee7b 100644 --- a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp +++ b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.cpp @@ -1,66 +1,66 @@ -/* Sprite Composite Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "SpriteDatabase.h" - -namespace PokemonAutomation{ - - - -SpriteDatabase::SpriteDatabase(const char* sprite_path, const char* json_path) - : m_backing_image(RESOURCE_PATH() + sprite_path) -{ - std::string path = RESOURCE_PATH() + json_path; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - int64_t width = root.get_integer_throw("spriteWidth", path); - int64_t height = root.get_integer_throw("spriteHeight", path); - if (width <= 0){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid width.", path); - } - if (height <= 0){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid height.", path); - } - - JsonObject& locations = root.get_object_throw("spriteLocations", path); - for (auto& item : locations){ - const std::string& slug = item.first; - JsonObject& obj = item.second.to_object_throw(path); - int y = (int)obj.get_integer_throw("top", path); - int x = (int)obj.get_integer_throw("left", path); - - ImageViewRGB32 sprite = extract_box_reference(m_backing_image, ImagePixelBox(x, y, x + width, y + height)); - m_database.emplace( - slug, - Sprite{sprite, ImageMatch::trim_image_alpha(sprite)} - ); - } -} - -const SpriteDatabase::Sprite& SpriteDatabase::get_throw(const std::string& slug) const{ - auto iter = m_database.find(slug); - if (iter == m_database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found in database: " + slug); - } - return iter->second; -} -const SpriteDatabase::Sprite* SpriteDatabase::get_nothrow(const std::string& slug) const{ - auto iter = m_database.find(slug); - if (iter == m_database.end()){ - return nullptr; - } - return &iter->second; -} - - - -} +/* Sprite Composite Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "SpriteDatabase.h" + +namespace PokemonAutomation{ + + + +SpriteDatabase::SpriteDatabase(const char* sprite_path, const char* json_path) + : m_backing_image(RESOURCE_PATH() + sprite_path) +{ + std::string path = RESOURCE_PATH() + json_path; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + int64_t width = root.get_integer_throw("spriteWidth", path); + int64_t height = root.get_integer_throw("spriteHeight", path); + if (width <= 0){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid width.", path); + } + if (height <= 0){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Invalid height.", path); + } + + JsonObject& locations = root.get_object_throw("spriteLocations", path); + for (auto& item : locations){ + const std::string& slug = item.first; + JsonObject& obj = item.second.to_object_throw(path); + int y = (int)obj.get_integer_throw("top", path); + int x = (int)obj.get_integer_throw("left", path); + + ImageViewRGB32 sprite = extract_box_reference(m_backing_image, ImagePixelBox(x, y, x + width, y + height)); + m_database.emplace( + slug, + Sprite{sprite, ImageMatch::trim_image_alpha(sprite)} + ); + } +} + +const SpriteDatabase::Sprite& SpriteDatabase::get_throw(const std::string& slug) const{ + auto iter = m_database.find(slug); + if (iter == m_database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found in database: " + slug); + } + return iter->second; +} +const SpriteDatabase::Sprite* SpriteDatabase::get_nothrow(const std::string& slug) const{ + auto iter = m_database.find(slug); + if (iter == m_database.end()){ + return nullptr; + } + return &iter->second; +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h index 3136ffd6ec..66b9420832 100644 --- a/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h +++ b/SerialPrograms/Source/CommonTools/Resources/SpriteDatabase.h @@ -1,64 +1,64 @@ -/* Sprite Composite Image - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H -#define PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ - - -class SpriteDatabase{ -public: - // Build from a composite image. - // - // The location of each sprite on the image is specified by a json file. - // Return a map of pokemon slug name for each sprite -> QIcon of the sprite. - // - // The json file must have the following format: - // { - // "spriteWidth": , - // "spriteHeight": , - // "spriteLocations": { - // "" : { - // "top": , - // "left": - // }, - // (next pokemon) ... - // } - // } - SpriteDatabase(const char* sprite_path, const char* json_path); - -public: - struct Sprite{ - ImageViewRGB32 sprite; // The original sprite. - ImageViewRGB32 icon; // Sprite with 0-alpha boundaries cropped for better viewing. - }; - const Sprite& get_throw(const std::string& slug) const; - const Sprite* get_nothrow(const std::string& slug) const; - -public: - using const_iterator = std::map::const_iterator; - using iterator = std::map::iterator; - - const_iterator cbegin () const{ return m_database.cbegin(); } - const_iterator begin () const{ return m_database.begin(); } - iterator begin (){ return m_database.begin(); } - const_iterator cend () const{ return m_database.cend(); } - const_iterator end () const{ return m_database.end(); } - iterator end (){ return m_database.end(); } - -private: - std::map m_database; - ImageRGB32 m_backing_image; -}; - - - -} -#endif +/* Sprite Composite Image + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H +#define PokemonAutomation_CommonTools_Resources_SpriteCompositeImage_H + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ + + +class SpriteDatabase{ +public: + // Build from a composite image. + // + // The location of each sprite on the image is specified by a json file. + // Return a map of pokemon slug name for each sprite -> QIcon of the sprite. + // + // The json file must have the following format: + // { + // "spriteWidth": , + // "spriteHeight": , + // "spriteLocations": { + // "" : { + // "top": , + // "left": + // }, + // (next pokemon) ... + // } + // } + SpriteDatabase(const char* sprite_path, const char* json_path); + +public: + struct Sprite{ + ImageViewRGB32 sprite; // The original sprite. + ImageViewRGB32 icon; // Sprite with 0-alpha boundaries cropped for better viewing. + }; + const Sprite& get_throw(const std::string& slug) const; + const Sprite* get_nothrow(const std::string& slug) const; + +public: + using const_iterator = std::map::const_iterator; + using iterator = std::map::iterator; + + const_iterator cbegin () const{ return m_database.cbegin(); } + const_iterator begin () const{ return m_database.begin(); } + iterator begin (){ return m_database.begin(); } + const_iterator cend () const{ return m_database.cend(); } + const_iterator end () const{ return m_database.end(); } + iterator end (){ return m_database.end(); } + +private: + std::map m_database; + ImageRGB32 m_backing_image; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp index 0acac28aa4..ae55cf465f 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp +++ b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.cpp @@ -1,71 +1,71 @@ -/* Start Program Checks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -//#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetectors/BlackBorderDetector.h" -#include "Controllers/ControllerCapability.h" -#include "StartProgramChecks.h" - -namespace PokemonAutomation{ -namespace StartProgramChecks{ - - -void check_feedback(VideoStream& stream, FeedbackType feedback){ - if (feedback == FeedbackType::NONE){ - return; - } - VideoSnapshot screen = stream.video().snapshot(); - if (screen){ - return; - } - if (feedback == FeedbackType::REQUIRED || feedback == FeedbackType::VIDEO_AUDIO){ - throw UserSetupError( - stream.logger(), - "This program requires video feedback. Please make sure the video is working." - ); - } -} - -void check_border(VideoStream& stream){ - BlackBorderDetector detector; - VideoOverlaySet set(stream.overlay()); - detector.make_overlays(set); - VideoSnapshot screen = stream.video().snapshot(); - if (!detector.detect(screen)){ - return; - } - throw UserSetupError( - stream.logger(), - "Black border detected! Please set your screen size to 100% in the TV Settings on your Nintendo Switch." - ); -} - - - -void check_controller_features( - Logger& logger, - const ControllerFeatures& capabilities, - const ControllerFeatures& required_features -){ - std::string missing_feature = capabilities.contains_all(required_features); - if (missing_feature.empty()){ - return; - } - throw UserSetupError( - logger, - "Cannot start program. The controller is missing the feature: " + missing_feature - ); -} - - - - -} -} +/* Start Program Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +//#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetectors/BlackBorderDetector.h" +#include "Controllers/ControllerCapability.h" +#include "StartProgramChecks.h" + +namespace PokemonAutomation{ +namespace StartProgramChecks{ + + +void check_feedback(VideoStream& stream, FeedbackType feedback){ + if (feedback == FeedbackType::NONE){ + return; + } + VideoSnapshot screen = stream.video().snapshot(); + if (screen){ + return; + } + if (feedback == FeedbackType::REQUIRED || feedback == FeedbackType::VIDEO_AUDIO){ + throw UserSetupError( + stream.logger(), + "This program requires video feedback. Please make sure the video is working." + ); + } +} + +void check_border(VideoStream& stream){ + BlackBorderDetector detector; + VideoOverlaySet set(stream.overlay()); + detector.make_overlays(set); + VideoSnapshot screen = stream.video().snapshot(); + if (!detector.detect(screen)){ + return; + } + throw UserSetupError( + stream.logger(), + "Black border detected! Please set your screen size to 100% in the TV Settings on your Nintendo Switch." + ); +} + + + +void check_controller_features( + Logger& logger, + const ControllerFeatures& capabilities, + const ControllerFeatures& required_features +){ + std::string missing_feature = capabilities.contains_all(required_features); + if (missing_feature.empty()){ + return; + } + throw UserSetupError( + logger, + "Cannot start program. The controller is missing the feature: " + missing_feature + ); +} + + + + +} +} diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h index 65153c7d99..847fa27b54 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h +++ b/SerialPrograms/Source/CommonTools/StartupChecks/StartProgramChecks.h @@ -1,34 +1,34 @@ -/* Start Program Checks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_StartProgramChecks_H -#define PokemonAutomation_CommonTools_StartProgramChecks_H - -#include -#include "CommonFramework/Globals.h" - -namespace PokemonAutomation{ - class Logger; - class VideoStream; - class ControllerFeatures; -namespace StartProgramChecks{ - - - -void check_feedback(VideoStream& stream, FeedbackType feedback); -void check_border(VideoStream& stream); - -void check_controller_features( - Logger& logger, - const ControllerFeatures& capabilities, - const ControllerFeatures& required_features -); - - - -} -} -#endif +/* Start Program Checks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_StartProgramChecks_H +#define PokemonAutomation_CommonTools_StartProgramChecks_H + +#include +#include "CommonFramework/Globals.h" + +namespace PokemonAutomation{ + class Logger; + class VideoStream; + class ControllerFeatures; +namespace StartProgramChecks{ + + + +void check_feedback(VideoStream& stream, FeedbackType feedback); +void check_border(VideoStream& stream); + +void check_controller_features( + Logger& logger, + const ControllerFeatures& capabilities, + const ControllerFeatures& required_features +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp index cb01c5ee7e..1ca277e443 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp +++ b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.cpp @@ -1,49 +1,49 @@ -/* Video Resolution Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "VideoResolutionCheck.h" - -namespace PokemonAutomation{ - - -void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame){ - if (!frame){ - throw UserSetupError(logger, "No video detected."); - } - if (frame.height() < 720){ - throw UserSetupError(logger, "Video resolution must be at least 720p."); - } - double aspect_ratio = (double)frame.width() / frame.height(); - if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ - throw UserSetupError(logger, "Video aspect ratio must be 16:9."); - } -} -void assert_16_9_720p_min(Logger& logger, VideoFeed& video){ - assert_16_9_720p_min(logger, video.snapshot()); -} - -void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame){ - if (!frame){ - throw UserSetupError(logger, "No video detected."); - } - if (frame.height() < 1080){ - throw UserSetupError(logger, "Video resolution must be at least 1080p."); - } - double aspect_ratio = (double)frame.width() / frame.height(); - if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ - throw UserSetupError(logger, "Video aspect ratio must be 16:9."); - } -} -void assert_16_9_1080p_min(Logger& logger, VideoFeed& video){ - assert_16_9_1080p_min(logger, video.snapshot()); -} - - - -} +/* Video Resolution Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "VideoResolutionCheck.h" + +namespace PokemonAutomation{ + + +void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame){ + if (!frame){ + throw UserSetupError(logger, "No video detected."); + } + if (frame.height() < 720){ + throw UserSetupError(logger, "Video resolution must be at least 720p."); + } + double aspect_ratio = (double)frame.width() / frame.height(); + if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ + throw UserSetupError(logger, "Video aspect ratio must be 16:9."); + } +} +void assert_16_9_720p_min(Logger& logger, VideoFeed& video){ + assert_16_9_720p_min(logger, video.snapshot()); +} + +void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame){ + if (!frame){ + throw UserSetupError(logger, "No video detected."); + } + if (frame.height() < 1080){ + throw UserSetupError(logger, "Video resolution must be at least 1080p."); + } + double aspect_ratio = (double)frame.width() / frame.height(); + if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ + throw UserSetupError(logger, "Video aspect ratio must be 16:9."); + } +} +void assert_16_9_1080p_min(Logger& logger, VideoFeed& video){ + assert_16_9_1080p_min(logger, video.snapshot()); +} + + + +} diff --git a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h index edf898e525..7fe0836426 100644 --- a/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h +++ b/SerialPrograms/Source/CommonTools/StartupChecks/VideoResolutionCheck.h @@ -1,26 +1,26 @@ -/* Video Resolution Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VideoResolutionCheck_H -#define PokemonAutomation_CommonTools_VideoResolutionCheck_H - -namespace PokemonAutomation{ - -class Logger; -class ImageViewRGB32; -class VideoFeed; - - -void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame); -void assert_16_9_720p_min(Logger& logger, VideoFeed& video); - -void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame); -void assert_16_9_1080p_min(Logger& logger, VideoFeed& video); - - - -} -#endif +/* Video Resolution Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VideoResolutionCheck_H +#define PokemonAutomation_CommonTools_VideoResolutionCheck_H + +namespace PokemonAutomation{ + +class Logger; +class ImageViewRGB32; +class VideoFeed; + + +void assert_16_9_720p_min(Logger& logger, const ImageViewRGB32& frame); +void assert_16_9_720p_min(Logger& logger, VideoFeed& video); + +void assert_16_9_1080p_min(Logger& logger, const ImageViewRGB32& frame); +void assert_16_9_1080p_min(Logger& logger, VideoFeed& video); + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp index 5a3f17828f..9dca5e0996 100644 --- a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp +++ b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.cpp @@ -1,125 +1,125 @@ -/* Differential Anomaly Detector_H - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "AnomalyDetector.h" - -namespace PokemonAutomation{ - - -AnomalyDetector::AnomalyDetector(size_t window_size, double min_value, double max_value) - : m_window_size(window_size) - , m_min_value(min_value) - , m_max_value(max_value) - , m_sum(0) - , m_sum_sqr(0) -{ - double range = max_value - min_value; - double max_size = range * range * window_size; - m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); - m_scale_to_double = 1. / m_scale_to_fixedpoint; -} -double AnomalyDetector::push(double x){ - if (m_window.size() >= m_window_size){ - uint32_t fixed = m_window.front(); - m_window.pop_front(); - m_sum -= fixed; - m_sum_sqr -= (uint64_t)fixed * fixed; - } - - x -= m_min_value; - x = std::max(x, 0.); - x = std::min(x, m_max_value - m_min_value); - - uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); - m_window.emplace_back(fixed); - m_sum += fixed; - m_sum_sqr += (uint64_t)fixed * fixed; - - return sigma(x); -} -double AnomalyDetector::mean() const{ - size_t count = m_window.size(); - return m_sum / (double)count * m_scale_to_double + m_min_value; -} -double AnomalyDetector::stddev() const{ - size_t count = m_window.size(); - return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; -} -double AnomalyDetector::sigma(double x) const{ - return std::abs((x - mean()) / stddev()); -} - - - -TimeNormalizedDeltaAnomalyDetector::TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value) - : m_window_size(window_size) - , m_max_value(max_value) - , m_sum(0) - , m_sum_sqr(0) -{ - double max_size = max_value * max_value * window_size; - m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); - m_scale_to_double = 1. / m_scale_to_fixedpoint; -} -double TimeNormalizedDeltaAnomalyDetector::push( - double x, - std::chrono::time_point timestamp -){ - if (m_window.size() >= m_window_size){ - uint32_t fixed = m_window.front().fixed_point_value; - m_window.pop_front(); - m_sum -= fixed; - m_sum_sqr -= (uint64_t)fixed * fixed; - } - - if (m_window.empty()){ - m_window.emplace_back(); - Frame& frame = m_window.back(); - frame.timestamp = timestamp; - frame.fixed_point_value = 0; - return 0; - } - - auto time_diff = timestamp - m_window.back().timestamp; - uint32_t millis = (uint32_t)std::chrono::duration_cast(time_diff).count(); - x /= millis; - x = std::min(x, m_max_value); - - uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); - - m_window.emplace_back(); - Frame& frame = m_window.back(); - frame.timestamp = timestamp; - frame.fixed_point_value = fixed; - m_sum += fixed; - m_sum_sqr += (uint64_t)fixed * fixed; - - -// cout << x << " / " << stddev() << " = " << sigma(x) << endl; -// cout << "count = " << m_window.size() << endl; -// cout << "sum = " << m_sum << endl; -// cout << "m_sum_sqr = " << m_sum_sqr << endl; - return sigma(x); -} - -double TimeNormalizedDeltaAnomalyDetector::mean() const{ - size_t count = m_window.size(); - return m_sum / (double)count * m_scale_to_double; -} -double TimeNormalizedDeltaAnomalyDetector::stddev() const{ - size_t count = m_window.size(); - return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; -} -double TimeNormalizedDeltaAnomalyDetector::sigma(double x) const{ - return std::abs((x - mean()) / stddev()); -} - - - -} - +/* Differential Anomaly Detector_H + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "AnomalyDetector.h" + +namespace PokemonAutomation{ + + +AnomalyDetector::AnomalyDetector(size_t window_size, double min_value, double max_value) + : m_window_size(window_size) + , m_min_value(min_value) + , m_max_value(max_value) + , m_sum(0) + , m_sum_sqr(0) +{ + double range = max_value - min_value; + double max_size = range * range * window_size; + m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); + m_scale_to_double = 1. / m_scale_to_fixedpoint; +} +double AnomalyDetector::push(double x){ + if (m_window.size() >= m_window_size){ + uint32_t fixed = m_window.front(); + m_window.pop_front(); + m_sum -= fixed; + m_sum_sqr -= (uint64_t)fixed * fixed; + } + + x -= m_min_value; + x = std::max(x, 0.); + x = std::min(x, m_max_value - m_min_value); + + uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); + m_window.emplace_back(fixed); + m_sum += fixed; + m_sum_sqr += (uint64_t)fixed * fixed; + + return sigma(x); +} +double AnomalyDetector::mean() const{ + size_t count = m_window.size(); + return m_sum / (double)count * m_scale_to_double + m_min_value; +} +double AnomalyDetector::stddev() const{ + size_t count = m_window.size(); + return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; +} +double AnomalyDetector::sigma(double x) const{ + return std::abs((x - mean()) / stddev()); +} + + + +TimeNormalizedDeltaAnomalyDetector::TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value) + : m_window_size(window_size) + , m_max_value(max_value) + , m_sum(0) + , m_sum_sqr(0) +{ + double max_size = max_value * max_value * window_size; + m_scale_to_fixedpoint = std::sqrt(((uint64_t)1 << 63) / max_size); + m_scale_to_double = 1. / m_scale_to_fixedpoint; +} +double TimeNormalizedDeltaAnomalyDetector::push( + double x, + std::chrono::time_point timestamp +){ + if (m_window.size() >= m_window_size){ + uint32_t fixed = m_window.front().fixed_point_value; + m_window.pop_front(); + m_sum -= fixed; + m_sum_sqr -= (uint64_t)fixed * fixed; + } + + if (m_window.empty()){ + m_window.emplace_back(); + Frame& frame = m_window.back(); + frame.timestamp = timestamp; + frame.fixed_point_value = 0; + return 0; + } + + auto time_diff = timestamp - m_window.back().timestamp; + uint32_t millis = (uint32_t)std::chrono::duration_cast(time_diff).count(); + x /= millis; + x = std::min(x, m_max_value); + + uint32_t fixed = (uint32_t)(x * m_scale_to_fixedpoint); + + m_window.emplace_back(); + Frame& frame = m_window.back(); + frame.timestamp = timestamp; + frame.fixed_point_value = fixed; + m_sum += fixed; + m_sum_sqr += (uint64_t)fixed * fixed; + + +// cout << x << " / " << stddev() << " = " << sigma(x) << endl; +// cout << "count = " << m_window.size() << endl; +// cout << "sum = " << m_sum << endl; +// cout << "m_sum_sqr = " << m_sum_sqr << endl; + return sigma(x); +} + +double TimeNormalizedDeltaAnomalyDetector::mean() const{ + size_t count = m_window.size(); + return m_sum / (double)count * m_scale_to_double; +} +double TimeNormalizedDeltaAnomalyDetector::stddev() const{ + size_t count = m_window.size(); + return std::sqrt((m_sum_sqr - m_sum*m_sum / (double)count) / (count - 1)) * m_scale_to_double; +} +double TimeNormalizedDeltaAnomalyDetector::sigma(double x) const{ + return std::abs((x - mean()) / stddev()); +} + + + +} + diff --git a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h index f631c1481b..2dffd4b1a9 100644 --- a/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h +++ b/SerialPrograms/Source/CommonTools/TrendInference/AnomalyDetector.h @@ -1,67 +1,67 @@ -/* Differential Anomaly Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H -#define PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H - -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - -class AnomalyDetector{ -public: - AnomalyDetector(size_t window_size, double min_value, double max_value); - double push(double x); - - double mean() const; - double stddev() const; - double sigma(double x) const; - -private: - size_t m_window_size; - double m_min_value; - double m_max_value; - double m_scale_to_fixedpoint; - double m_scale_to_double; - uint64_t m_sum; - uint64_t m_sum_sqr; - std::deque m_window; -}; - - -class TimeNormalizedDeltaAnomalyDetector{ -public: - TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value); - double push(double x, WallClock timestamp = current_time()); - - double mean() const; - double stddev() const; - double sigma(double x) const; - -private: - struct Frame{ - WallClock timestamp; - uint32_t fixed_point_value; - }; - - size_t m_window_size; - double m_max_value; - double m_scale_to_fixedpoint; - double m_scale_to_double; - uint64_t m_sum; - uint64_t m_sum_sqr; - std::deque m_window; -}; - - - - - -} - -#endif +/* Differential Anomaly Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H +#define PokemonAutomation_CommonTools_DifferentialAnomalyDetector_H + +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + +class AnomalyDetector{ +public: + AnomalyDetector(size_t window_size, double min_value, double max_value); + double push(double x); + + double mean() const; + double stddev() const; + double sigma(double x) const; + +private: + size_t m_window_size; + double m_min_value; + double m_max_value; + double m_scale_to_fixedpoint; + double m_scale_to_double; + uint64_t m_sum; + uint64_t m_sum_sqr; + std::deque m_window; +}; + + +class TimeNormalizedDeltaAnomalyDetector{ +public: + TimeNormalizedDeltaAnomalyDetector(size_t window_size, double max_value); + double push(double x, WallClock timestamp = current_time()); + + double mean() const; + double stddev() const; + double sigma(double x) const; + +private: + struct Frame{ + WallClock timestamp; + uint32_t fixed_point_value; + }; + + size_t m_window_size; + double m_max_value; + double m_scale_to_fixedpoint; + double m_scale_to_double; + uint64_t m_sum; + uint64_t m_sum_sqr; + std::deque m_window; +}; + + + + + +} + +#endif diff --git a/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h b/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h index a7fe560a39..20679adb1f 100644 --- a/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h +++ b/SerialPrograms/Source/CommonTools/TrendInference/TimeWindowStatTracker.h @@ -1,142 +1,142 @@ -/* Time Window Stat Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_TimeWindowStatTracker_H -#define PokemonAutomation_CommonTools_TimeWindowStatTracker_H - -#include -#include - -namespace PokemonAutomation{ - - -template -class TimeWindowStatTracker{ - using milliseconds = std::chrono::milliseconds; - using system_clock = std::chrono::system_clock; - using StatObject = typename StatAccumulator::StatObject; - -public: - TimeWindowStatTracker(milliseconds window) - : m_window(window) - {} - - milliseconds window() const{ - return m_window; - } - - const StatObject& oldest() const{ - return m_history.begin()->second; - } - const StatObject& newest() const{ - return m_history.rbegin()->second; - } - - system_clock::time_point push( - const StatObject& stats, - system_clock::time_point timestamp = system_clock::now() - ){ - m_history.emplace( - std::piecewise_construct, - std::forward_as_tuple(timestamp), - std::forward_as_tuple(stats) - ); - - system_clock::time_point tail = timestamp - m_window; - while (!m_history.empty() && m_history.begin()->first < tail){ - m_history.erase(m_history.begin()); - } - - return timestamp; - } - system_clock::time_point push( - StatObject&& stats, - system_clock::time_point timestamp = system_clock::now() - ){ - m_history.emplace( - std::piecewise_construct, - std::forward_as_tuple(timestamp), - std::forward_as_tuple(std::move(stats)) - ); - - system_clock::time_point tail = timestamp - m_window; - while (!m_history.empty() && m_history.begin()->first < tail){ - m_history.erase(m_history.begin()); - } - - return timestamp; - } - - // Accumulate entire history. - StatAccumulator accumulate_all() const{ - return accumulate(m_history.begin(), m_history.end()); - } - - // Accumulate [latest - duration, latest]. - StatAccumulator accumulate_last( - milliseconds duration - ) const{ - return accumulate( - m_history.empty() - ? m_history.end() - : m_history.lower_bound(m_history.rbegin()->first - duration), - m_history.end() - ); - } - - // Accumulate [oldest, point]. - StatAccumulator accumulate_start_to_point( - system_clock::time_point point - ) const{ - return accumulate(m_history.begin, m_history.upper_bound(point)); - } - - // Accumulate [oldest, latest - time_behind_latest]. - StatAccumulator accumulate_start_to_point( - milliseconds time_behind_latest - ) const{ - return accumulate( - m_history.begin(), - m_history.empty() - ? m_history.end() - : m_history.upper_bound(m_history.rbegin()->first - time_behind_latest) - ); - } - - // Accumulate [start, end]. - StatAccumulator accumulate( - system_clock::time_point start, - system_clock::time_point end - ) const{ - return accumulate(m_history.lower_bound(start), m_history.upper_bound(end)); - } - - -private: - using const_iterator_type = typename std::map::const_iterator; - - StatAccumulator accumulate( - const_iterator_type start, - const_iterator_type end - ) const{ - StatAccumulator accumulator; - for (; start != end; ++start){ - accumulator += start->second; - } - return accumulator; - } - - -private: - milliseconds m_window; - std::map m_history; - -}; - - - -} -#endif +/* Time Window Stat Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_TimeWindowStatTracker_H +#define PokemonAutomation_CommonTools_TimeWindowStatTracker_H + +#include +#include + +namespace PokemonAutomation{ + + +template +class TimeWindowStatTracker{ + using milliseconds = std::chrono::milliseconds; + using system_clock = std::chrono::system_clock; + using StatObject = typename StatAccumulator::StatObject; + +public: + TimeWindowStatTracker(milliseconds window) + : m_window(window) + {} + + milliseconds window() const{ + return m_window; + } + + const StatObject& oldest() const{ + return m_history.begin()->second; + } + const StatObject& newest() const{ + return m_history.rbegin()->second; + } + + system_clock::time_point push( + const StatObject& stats, + system_clock::time_point timestamp = system_clock::now() + ){ + m_history.emplace( + std::piecewise_construct, + std::forward_as_tuple(timestamp), + std::forward_as_tuple(stats) + ); + + system_clock::time_point tail = timestamp - m_window; + while (!m_history.empty() && m_history.begin()->first < tail){ + m_history.erase(m_history.begin()); + } + + return timestamp; + } + system_clock::time_point push( + StatObject&& stats, + system_clock::time_point timestamp = system_clock::now() + ){ + m_history.emplace( + std::piecewise_construct, + std::forward_as_tuple(timestamp), + std::forward_as_tuple(std::move(stats)) + ); + + system_clock::time_point tail = timestamp - m_window; + while (!m_history.empty() && m_history.begin()->first < tail){ + m_history.erase(m_history.begin()); + } + + return timestamp; + } + + // Accumulate entire history. + StatAccumulator accumulate_all() const{ + return accumulate(m_history.begin(), m_history.end()); + } + + // Accumulate [latest - duration, latest]. + StatAccumulator accumulate_last( + milliseconds duration + ) const{ + return accumulate( + m_history.empty() + ? m_history.end() + : m_history.lower_bound(m_history.rbegin()->first - duration), + m_history.end() + ); + } + + // Accumulate [oldest, point]. + StatAccumulator accumulate_start_to_point( + system_clock::time_point point + ) const{ + return accumulate(m_history.begin, m_history.upper_bound(point)); + } + + // Accumulate [oldest, latest - time_behind_latest]. + StatAccumulator accumulate_start_to_point( + milliseconds time_behind_latest + ) const{ + return accumulate( + m_history.begin(), + m_history.empty() + ? m_history.end() + : m_history.upper_bound(m_history.rbegin()->first - time_behind_latest) + ); + } + + // Accumulate [start, end]. + StatAccumulator accumulate( + system_clock::time_point start, + system_clock::time_point end + ) const{ + return accumulate(m_history.lower_bound(start), m_history.upper_bound(end)); + } + + +private: + using const_iterator_type = typename std::map::const_iterator; + + StatAccumulator accumulate( + const_iterator_type start, + const_iterator_type end + ) const{ + StatAccumulator accumulator; + for (; start != end; ++start){ + accumulator += start->second; + } + return accumulator; + } + + +private: + milliseconds m_window; + std::map m_history; + +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetector.h b/SerialPrograms/Source/CommonTools/VisualDetector.h index 22aa8bcec2..660fe6e68d 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetector.h @@ -1,130 +1,130 @@ -/* Visual Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_VisualDetector_H -#define PokemonAutomation_CommonTools_VisualDetector_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class VideoOverlaySet; - - -class StaticScreenDetector{ -public: - virtual ~StaticScreenDetector() = default; - virtual void make_overlays(VideoOverlaySet& items) const = 0; - - // This is not const so that detectors can save/cache state. - virtual bool detect(const ImageViewRGB32& screen) = 0; -}; - - - -// Wrap a detector into a finder. -// This one requires the detector to return the same result consecutively for X time -// before returning true from process_frame(). -template -class DetectorToFinder : public Detector, public VisualInferenceCallback{ -public: - // Whether a finder is to find an object is detected by the detector or find - // that it's no longer detected. - enum class FinderType{ - PRESENT, // process_frame() returns true only when detected consecutively - GONE, // process_frame() returns true only when not detected consecutively - CONSISTENT, // process_frame() returns true when detected consecutively or not detected consecutively - }; - - template - DetectorToFinder( - std::string label, - std::chrono::milliseconds duration, - Args&&... args - ) - : Detector(std::forward(args)...) - , VisualInferenceCallback(std::move(label)) - , m_duration(duration) - , m_finder_type(FinderType::PRESENT) - {} - - - template - DetectorToFinder( - std::string label, - FinderType finder_type, - std::chrono::milliseconds duration, - Args&&... args - ) - : Detector(std::forward(args)...) - , VisualInferenceCallback(std::move(label)) - , m_duration(duration) - , m_finder_type(finder_type) - {} - - virtual void make_overlays(VideoOverlaySet& items) const override{ - Detector::make_overlays(items); - } - - // If m_finder_type is PRESENT, return true only when it is consecutively detected. - // If m_finder_type is GONE, return true only when it is consecutively not detected. - // if m_finder_type is CONSISTENT, return true when it is consecutively detected, or consecutively not detected. - using VisualInferenceCallback::process_frame; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - switch (m_finder_type){ - case FinderType::PRESENT: - case FinderType::GONE: - if (this->detect(frame) == (m_finder_type == FinderType::GONE)){ - m_start_of_detection = WallClock::min(); - return false; - } - if (m_start_of_detection == WallClock::min()){ - m_start_of_detection = timestamp; - } - return timestamp - m_start_of_detection >= m_duration; - case FinderType::CONSISTENT:{ - const bool result = this->detect(frame); - const bool result_changed = (result && m_last_detected < 0) || (!result && m_last_detected > 0); - - m_last_detected = (result ? 1 : -1); - - if (result_changed){ - m_start_of_detection = WallClock::min(); - return false; - } - if (m_start_of_detection == WallClock::min()){ - m_start_of_detection = timestamp; - } - - const bool enough_time = timestamp - m_start_of_detection >= m_duration; - if (enough_time){ - m_consistent_result = m_last_detected > 0; - } - return enough_time; - } - default:; - } - return false; - } - - // If m_finder_type is CONSISTENT and process_frame() returns true, - // whether it is consecutively detected , or consecutively not detected. - bool consistent_result() const { return m_consistent_result; } - -private: - std::chrono::milliseconds m_duration; - FinderType m_finder_type; - WallClock m_start_of_detection = WallClock::min(); - int8_t m_last_detected = 0; // 0: no prior detection, 1: last detected positive, -1: last detected negative - bool m_consistent_result = false; -}; - - - - -} -#endif +/* Visual Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_VisualDetector_H +#define PokemonAutomation_CommonTools_VisualDetector_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class VideoOverlaySet; + + +class StaticScreenDetector{ +public: + virtual ~StaticScreenDetector() = default; + virtual void make_overlays(VideoOverlaySet& items) const = 0; + + // This is not const so that detectors can save/cache state. + virtual bool detect(const ImageViewRGB32& screen) = 0; +}; + + + +// Wrap a detector into a finder. +// This one requires the detector to return the same result consecutively for X time +// before returning true from process_frame(). +template +class DetectorToFinder : public Detector, public VisualInferenceCallback{ +public: + // Whether a finder is to find an object is detected by the detector or find + // that it's no longer detected. + enum class FinderType{ + PRESENT, // process_frame() returns true only when detected consecutively + GONE, // process_frame() returns true only when not detected consecutively + CONSISTENT, // process_frame() returns true when detected consecutively or not detected consecutively + }; + + template + DetectorToFinder( + std::string label, + std::chrono::milliseconds duration, + Args&&... args + ) + : Detector(std::forward(args)...) + , VisualInferenceCallback(std::move(label)) + , m_duration(duration) + , m_finder_type(FinderType::PRESENT) + {} + + + template + DetectorToFinder( + std::string label, + FinderType finder_type, + std::chrono::milliseconds duration, + Args&&... args + ) + : Detector(std::forward(args)...) + , VisualInferenceCallback(std::move(label)) + , m_duration(duration) + , m_finder_type(finder_type) + {} + + virtual void make_overlays(VideoOverlaySet& items) const override{ + Detector::make_overlays(items); + } + + // If m_finder_type is PRESENT, return true only when it is consecutively detected. + // If m_finder_type is GONE, return true only when it is consecutively not detected. + // if m_finder_type is CONSISTENT, return true when it is consecutively detected, or consecutively not detected. + using VisualInferenceCallback::process_frame; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + switch (m_finder_type){ + case FinderType::PRESENT: + case FinderType::GONE: + if (this->detect(frame) == (m_finder_type == FinderType::GONE)){ + m_start_of_detection = WallClock::min(); + return false; + } + if (m_start_of_detection == WallClock::min()){ + m_start_of_detection = timestamp; + } + return timestamp - m_start_of_detection >= m_duration; + case FinderType::CONSISTENT:{ + const bool result = this->detect(frame); + const bool result_changed = (result && m_last_detected < 0) || (!result && m_last_detected > 0); + + m_last_detected = (result ? 1 : -1); + + if (result_changed){ + m_start_of_detection = WallClock::min(); + return false; + } + if (m_start_of_detection == WallClock::min()){ + m_start_of_detection = timestamp; + } + + const bool enough_time = timestamp - m_start_of_detection >= m_duration; + if (enough_time){ + m_consistent_result = m_last_detected > 0; + } + return enough_time; + } + default:; + } + return false; + } + + // If m_finder_type is CONSISTENT and process_frame() returns true, + // whether it is consecutively detected , or consecutively not detected. + bool consistent_result() const { return m_consistent_result; } + +private: + std::chrono::milliseconds m_duration; + FinderType m_finder_type; + WallClock m_start_of_detection = WallClock::min(); + int8_t m_last_detected = 0; // 0: no prior detection, 1: last detected positive, -1: last detected negative + bool m_consistent_result = false; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp index f48304e8c7..b89e20514c 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.cpp @@ -1,75 +1,75 @@ -/* Black Border Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "BlackBorderDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - - -BlackBorderDetector::BlackBorderDetector() - : m_top(0.001, 0.001, 0.997, 0.002) - , m_bottom(0.001, 0.997, 0.997, 0.002) - , m_left(0.001, 0.001, 0.002, 0.997) - , m_right(0.997, 0.001, 0.002, 0.997) -// , m_body(0.100, 0.100, 0.800, 0.800) -{} - -void BlackBorderDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_top); - items.add(COLOR_RED, m_bottom); - items.add(COLOR_RED, m_left); - items.add(COLOR_RED, m_right); -// items.add(COLOR_RED, m_body); -} -bool BlackBorderDetector::detect(const ImageViewRGB32& screen){ - const double MAX_SUM = 50; - const double MAX_STDDEV = 20; - - ImageStats top = image_stats(extract_box_reference(screen, m_top)); -// cout << "top = " << top.average << top.stddev << endl; -// extract_box(screen, m_top).save("top.png"); - if (!is_black(top, MAX_SUM, MAX_STDDEV)){ - return false; - } - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << "bottom = " << bottom.average << bottom.stddev << endl; - if (!is_black(bottom, MAX_SUM, MAX_STDDEV)){ - return false; - } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << "left = " << left.average << left.stddev << endl; - if (!is_black(left, MAX_SUM, MAX_STDDEV)){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// cout << "right = " << right.average << right.stddev << endl; - if (!is_black(right, MAX_SUM, MAX_STDDEV)){ - return false; - } -// ImageStats body = image_stats(extract_box_reference(screen, m_body)); -// cout << "body = " << body.average << body.stddev << endl; -// if (is_black(right, 30, 30)){ -// return false; -// } - - -// for (int c = 0; c < screen.width(); c++){ -// QRgb pixel = screen.pixel(c, 0); -// cout << "(" << qRed(pixel) << "," << qGreen(pixel) << "," << qBlue(pixel) << ")"; -// } - - return true; -} - - -} +/* Black Border Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "BlackBorderDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + + +BlackBorderDetector::BlackBorderDetector() + : m_top(0.001, 0.001, 0.997, 0.002) + , m_bottom(0.001, 0.997, 0.997, 0.002) + , m_left(0.001, 0.001, 0.002, 0.997) + , m_right(0.997, 0.001, 0.002, 0.997) +// , m_body(0.100, 0.100, 0.800, 0.800) +{} + +void BlackBorderDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_top); + items.add(COLOR_RED, m_bottom); + items.add(COLOR_RED, m_left); + items.add(COLOR_RED, m_right); +// items.add(COLOR_RED, m_body); +} +bool BlackBorderDetector::detect(const ImageViewRGB32& screen){ + const double MAX_SUM = 50; + const double MAX_STDDEV = 20; + + ImageStats top = image_stats(extract_box_reference(screen, m_top)); +// cout << "top = " << top.average << top.stddev << endl; +// extract_box(screen, m_top).save("top.png"); + if (!is_black(top, MAX_SUM, MAX_STDDEV)){ + return false; + } + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << "bottom = " << bottom.average << bottom.stddev << endl; + if (!is_black(bottom, MAX_SUM, MAX_STDDEV)){ + return false; + } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << "left = " << left.average << left.stddev << endl; + if (!is_black(left, MAX_SUM, MAX_STDDEV)){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// cout << "right = " << right.average << right.stddev << endl; + if (!is_black(right, MAX_SUM, MAX_STDDEV)){ + return false; + } +// ImageStats body = image_stats(extract_box_reference(screen, m_body)); +// cout << "body = " << body.average << body.stddev << endl; +// if (is_black(right, 30, 30)){ +// return false; +// } + + +// for (int c = 0; c < screen.width(); c++){ +// QRgb pixel = screen.pixel(c, 0); +// cout << "(" << qRed(pixel) << "," << qGreen(pixel) << "," << qBlue(pixel) << ")"; +// } + + return true; +} + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h index 623310733f..17e631dd3e 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackBorderDetector.h @@ -1,34 +1,34 @@ -/* Black Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_BlackBorderDetector_H -#define PokemonAutomation_CommonTools_BlackBorderDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - - -class BlackBorderDetector : public StaticScreenDetector{ -public: - BlackBorderDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_top; - ImageFloatBox m_bottom; - ImageFloatBox m_left; - ImageFloatBox m_right; -// ImageFloatBox m_body; -}; - - - -} -#endif +/* Black Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_BlackBorderDetector_H +#define PokemonAutomation_CommonTools_BlackBorderDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + + +class BlackBorderDetector : public StaticScreenDetector{ +public: + BlackBorderDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_top; + ImageFloatBox m_bottom; + ImageFloatBox m_left; + ImageFloatBox m_right; +// ImageFloatBox m_body; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp index 774fae59b2..a3fa6178c0 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.cpp @@ -1,128 +1,128 @@ -/* Black Border Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Returns true after a black screen has been detected and - * the black screen has ended. - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "BlackScreenDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -BlackScreenDetector::BlackScreenDetector( - Color color, const ImageFloatBox& box, - double max_rgb_sum, - double max_stddev_sum -) - : m_color(color) - , m_box(box) - , m_max_rgb_sum(max_rgb_sum) - , m_max_stddev_sum(max_stddev_sum) -{} -void BlackScreenDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool BlackScreenDetector::detect(const ImageViewRGB32& screen){ - return is_black(extract_box_reference(screen, m_box), m_max_rgb_sum, m_max_stddev_sum); -} - - - -WhiteScreenDetector::WhiteScreenDetector( - Color color, const ImageFloatBox& box, - double min_rgb_sum, - double max_stddev_sum -) - : m_color(color) - , m_box(box) - , m_min_rgb_sum(min_rgb_sum) - , m_max_stddev_sum(max_stddev_sum) -{} -void WhiteScreenDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool WhiteScreenDetector::detect(const ImageViewRGB32& screen){ - return is_white(extract_box_reference(screen, m_box), m_min_rgb_sum, m_max_stddev_sum); -} - - - - - - -BlackScreenOverWatcher::BlackScreenOverWatcher( - Color color, const ImageFloatBox& box, - double max_rgb_sum, - double max_stddev_sum, - std::chrono::milliseconds hold_duration, - std::chrono::milliseconds release_duration -) - : VisualInferenceCallback("BlackScreenOverWatcher") - , m_on(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::PRESENT, hold_duration) - , m_off(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::GONE, release_duration) -{} -void BlackScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ - m_on.make_overlays(items); -} -bool BlackScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - if (m_black_is_over.load(std::memory_order_acquire)){ - return true; - } - if (!m_has_been_black){ - m_has_been_black = m_on.process_frame(frame, timestamp); - return false; - } - - bool is_over = m_off.process_frame(frame, timestamp); - if (!is_over){ - return false; - } - m_black_is_over.store(true, std::memory_order_release); - return true; -} -bool BlackScreenOverWatcher::black_is_over(const ImageViewRGB32& frame){ - return m_black_is_over.load(std::memory_order_acquire); -} - - - - -WhiteScreenOverWatcher::WhiteScreenOverWatcher( - Color color, const ImageFloatBox& box, - double min_rgb_sum, - double max_stddev_sum -) - : VisualInferenceCallback("BlackScreenOverWatcher") - , m_detector(color, box, min_rgb_sum, max_stddev_sum) -{} -void WhiteScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool WhiteScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return white_is_over(frame); -} -bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ - if (m_detector.detect(frame)){ - m_has_been_white = true; - return false; - } - return m_has_been_white; -} - - - - - - -} +/* Black Border Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Returns true after a black screen has been detected and + * the black screen has ended. + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "BlackScreenDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +BlackScreenDetector::BlackScreenDetector( + Color color, const ImageFloatBox& box, + double max_rgb_sum, + double max_stddev_sum +) + : m_color(color) + , m_box(box) + , m_max_rgb_sum(max_rgb_sum) + , m_max_stddev_sum(max_stddev_sum) +{} +void BlackScreenDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool BlackScreenDetector::detect(const ImageViewRGB32& screen){ + return is_black(extract_box_reference(screen, m_box), m_max_rgb_sum, m_max_stddev_sum); +} + + + +WhiteScreenDetector::WhiteScreenDetector( + Color color, const ImageFloatBox& box, + double min_rgb_sum, + double max_stddev_sum +) + : m_color(color) + , m_box(box) + , m_min_rgb_sum(min_rgb_sum) + , m_max_stddev_sum(max_stddev_sum) +{} +void WhiteScreenDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool WhiteScreenDetector::detect(const ImageViewRGB32& screen){ + return is_white(extract_box_reference(screen, m_box), m_min_rgb_sum, m_max_stddev_sum); +} + + + + + + +BlackScreenOverWatcher::BlackScreenOverWatcher( + Color color, const ImageFloatBox& box, + double max_rgb_sum, + double max_stddev_sum, + std::chrono::milliseconds hold_duration, + std::chrono::milliseconds release_duration +) + : VisualInferenceCallback("BlackScreenOverWatcher") + , m_on(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::PRESENT, hold_duration) + , m_off(color, box, max_rgb_sum, max_stddev_sum, BlackScreenWatcher::FinderType::GONE, release_duration) +{} +void BlackScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ + m_on.make_overlays(items); +} +bool BlackScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (m_black_is_over.load(std::memory_order_acquire)){ + return true; + } + if (!m_has_been_black){ + m_has_been_black = m_on.process_frame(frame, timestamp); + return false; + } + + bool is_over = m_off.process_frame(frame, timestamp); + if (!is_over){ + return false; + } + m_black_is_over.store(true, std::memory_order_release); + return true; +} +bool BlackScreenOverWatcher::black_is_over(const ImageViewRGB32& frame){ + return m_black_is_over.load(std::memory_order_acquire); +} + + + + +WhiteScreenOverWatcher::WhiteScreenOverWatcher( + Color color, const ImageFloatBox& box, + double min_rgb_sum, + double max_stddev_sum +) + : VisualInferenceCallback("BlackScreenOverWatcher") + , m_detector(color, box, min_rgb_sum, max_stddev_sum) +{} +void WhiteScreenOverWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool WhiteScreenOverWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return white_is_over(frame); +} +bool WhiteScreenOverWatcher::white_is_over(const ImageViewRGB32& frame){ + if (m_detector.detect(frame)){ + m_has_been_white = true; + return false; + } + return m_has_been_white; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h index 12c99b2a01..e1b385a7ac 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/BlackScreenDetector.h @@ -1,126 +1,126 @@ -/* Black Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Returns true after a black screen has been detected and - * the black screen has ended. - * - */ - -#ifndef PokemonAutomation_CommonTools_BlackScreenDetector_H -#define PokemonAutomation_CommonTools_BlackScreenDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - - -class BlackScreenDetector : public StaticScreenDetector{ -public: - BlackScreenDetector( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10 - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; - double m_max_rgb_sum; - double m_max_stddev_sum; -}; -class WhiteScreenDetector : public StaticScreenDetector{ -public: - WhiteScreenDetector( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double min_rgb_sum = 500, - double max_stddev_sum = 10 - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; - double m_min_rgb_sum; - double m_max_stddev_sum; -}; - - -class BlackScreenWatcher : public DetectorToFinder{ -public: - BlackScreenWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10, - FinderType finder_type = FinderType::PRESENT, - std::chrono::milliseconds duration = std::chrono::milliseconds(100) - ) - : DetectorToFinder("BlackScreenWatcher", finder_type, duration, color, box, max_rgb_sum, max_stddev_sum) - {} -}; - -// Detect when a period of black screen is over -class BlackScreenOverWatcher : public VisualInferenceCallback{ -public: - BlackScreenOverWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double max_rgb_sum = 100, - double max_stddev_sum = 10, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(100), - std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) - ); - - bool black_is_over(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - BlackScreenWatcher m_on; - BlackScreenWatcher m_off; - bool m_has_been_black = false; - std::atomic m_black_is_over = false; -}; - - - - -class WhiteScreenOverWatcher : public VisualInferenceCallback{ -public: - WhiteScreenOverWatcher( - Color color = COLOR_RED, - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - double min_rgb_sum = 500, - double max_stddev_sum = 10 - ); - - bool white_is_over(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - WhiteScreenDetector m_detector; - bool m_has_been_white = false; -}; - - - -} -#endif +/* Black Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Returns true after a black screen has been detected and + * the black screen has ended. + * + */ + +#ifndef PokemonAutomation_CommonTools_BlackScreenDetector_H +#define PokemonAutomation_CommonTools_BlackScreenDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + + +class BlackScreenDetector : public StaticScreenDetector{ +public: + BlackScreenDetector( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10 + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; + double m_max_rgb_sum; + double m_max_stddev_sum; +}; +class WhiteScreenDetector : public StaticScreenDetector{ +public: + WhiteScreenDetector( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double min_rgb_sum = 500, + double max_stddev_sum = 10 + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; + double m_min_rgb_sum; + double m_max_stddev_sum; +}; + + +class BlackScreenWatcher : public DetectorToFinder{ +public: + BlackScreenWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10, + FinderType finder_type = FinderType::PRESENT, + std::chrono::milliseconds duration = std::chrono::milliseconds(100) + ) + : DetectorToFinder("BlackScreenWatcher", finder_type, duration, color, box, max_rgb_sum, max_stddev_sum) + {} +}; + +// Detect when a period of black screen is over +class BlackScreenOverWatcher : public VisualInferenceCallback{ +public: + BlackScreenOverWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double max_rgb_sum = 100, + double max_stddev_sum = 10, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(100), + std::chrono::milliseconds release_duration = std::chrono::milliseconds(100) + ); + + bool black_is_over(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + BlackScreenWatcher m_on; + BlackScreenWatcher m_off; + bool m_has_been_black = false; + std::atomic m_black_is_over = false; +}; + + + + +class WhiteScreenOverWatcher : public VisualInferenceCallback{ +public: + WhiteScreenOverWatcher( + Color color = COLOR_RED, + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + double min_rgb_sum = 500, + double max_stddev_sum = 10 + ); + + bool white_is_over(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + WhiteScreenDetector m_detector; + bool m_has_been_white = false; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp index d3d07d81b7..f9609adb80 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.cpp @@ -1,63 +1,63 @@ -/* Frozen Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "FrozenImageDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -FrozenImageDetector::FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold) - : VisualInferenceCallback("FrozenImageDetector") - , m_color(COLOR_CYAN) - , m_box(0.0, 0.0, 1.0, 1.0) - , m_timeout(timeout) - , m_rmsd_threshold(rmsd_threshold) -{} -FrozenImageDetector::FrozenImageDetector( - Color color, const ImageFloatBox& box, - std::chrono::milliseconds timeout, double rmsd_threshold -) - : VisualInferenceCallback("FrozenImageDetector") - , m_color(color) - , m_box(box) - , m_timeout(timeout) - , m_rmsd_threshold(rmsd_threshold) -{} -void FrozenImageDetector::make_overlays(VideoOverlaySet& set) const{ - set.add(m_color, m_box); -} -bool FrozenImageDetector::process_frame(const VideoSnapshot& frame){ - if (m_previous->width() != frame->width() || m_previous->height() != frame->height()){ - m_previous = frame; - return false; - } - - double rmsd = ImageMatch::pixel_RMSD( - extract_box_reference(m_previous, m_box), - extract_box_reference(frame, m_box) - ); -// cout << "rmsd = " << rmsd << endl; - if (rmsd > m_rmsd_threshold){ - m_previous = frame; - return false; - } - - return frame.timestamp - m_previous.timestamp > m_timeout; -// return false; -} -bool FrozenImageDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return process_frame(VideoSnapshot(frame.copy(), timestamp)); -} - - -} +/* Frozen Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "FrozenImageDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +FrozenImageDetector::FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold) + : VisualInferenceCallback("FrozenImageDetector") + , m_color(COLOR_CYAN) + , m_box(0.0, 0.0, 1.0, 1.0) + , m_timeout(timeout) + , m_rmsd_threshold(rmsd_threshold) +{} +FrozenImageDetector::FrozenImageDetector( + Color color, const ImageFloatBox& box, + std::chrono::milliseconds timeout, double rmsd_threshold +) + : VisualInferenceCallback("FrozenImageDetector") + , m_color(color) + , m_box(box) + , m_timeout(timeout) + , m_rmsd_threshold(rmsd_threshold) +{} +void FrozenImageDetector::make_overlays(VideoOverlaySet& set) const{ + set.add(m_color, m_box); +} +bool FrozenImageDetector::process_frame(const VideoSnapshot& frame){ + if (m_previous->width() != frame->width() || m_previous->height() != frame->height()){ + m_previous = frame; + return false; + } + + double rmsd = ImageMatch::pixel_RMSD( + extract_box_reference(m_previous, m_box), + extract_box_reference(frame, m_box) + ); +// cout << "rmsd = " << rmsd << endl; + if (rmsd > m_rmsd_threshold){ + m_previous = frame; + return false; + } + + return frame.timestamp - m_previous.timestamp > m_timeout; +// return false; +} +bool FrozenImageDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return process_frame(VideoSnapshot(frame.copy(), timestamp)); +} + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h index 8b14c133dd..ae01bf41a9 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/FrozenImageDetector.h @@ -1,43 +1,43 @@ -/* Frozen Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect if the entire screen is frozen. - */ - -#ifndef PokemonAutomation_CommonTools_FrozenImageDetector_H -#define PokemonAutomation_CommonTools_FrozenImageDetector_H - -#include "Common/Cpp/Color.h" -//#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - - -class FrozenImageDetector : public VisualInferenceCallback{ -public: - FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold); - FrozenImageDetector( - Color color, const ImageFloatBox& box, - std::chrono::milliseconds timeout, double rmsd_threshold - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Color m_color; - ImageFloatBox m_box; - std::chrono::milliseconds m_timeout; - double m_rmsd_threshold; - VideoSnapshot m_previous; -}; - - - -} -#endif +/* Frozen Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect if the entire screen is frozen. + */ + +#ifndef PokemonAutomation_CommonTools_FrozenImageDetector_H +#define PokemonAutomation_CommonTools_FrozenImageDetector_H + +#include "Common/Cpp/Color.h" +//#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + + +class FrozenImageDetector : public VisualInferenceCallback{ +public: + FrozenImageDetector(std::chrono::milliseconds timeout, double rmsd_threshold); + FrozenImageDetector( + Color color, const ImageFloatBox& box, + std::chrono::milliseconds timeout, double rmsd_threshold + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Color m_color; + ImageFloatBox m_box; + std::chrono::milliseconds m_timeout; + double m_rmsd_threshold; + VideoSnapshot m_previous; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp index f9c9544e59..a2819c9d7b 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.cpp @@ -1,111 +1,111 @@ -/* Image Match Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "ImageMatchDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -ImageMatchDetector::ImageMatchDetector( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness, - Color color -) - : m_reference_image(std::move(reference_image)) - , m_reference_image_cropped(extract_box_reference(*m_reference_image, box)) - , m_average_brightness(image_stats(m_reference_image_cropped).average) - , m_max_rmsd(max_rmsd) - , m_scale_brightness(scale_brightness) - , m_color(color) - , m_box(box) -{} - -double ImageMatchDetector::rmsd(const ImageViewRGB32& frame) const{ - if (!frame){ - return 1000; - } - ImageViewRGB32 image = extract_box_reference(frame, m_box); - ImageRGB32 scaled = image.scale_to(m_reference_image_cropped.width(), m_reference_image_cropped.height()); - -#if 0 - if (image.width() != (size_t)scaled.width() || image.height() != (size_t)scaled.height()){ - cout << image.width() << " x " << image.height() << " - " << scaled.width() << " x " << scaled.height() << endl; - dump_image(global_logger_tagged(), ProgramInfo(), "ImageMatchDetector-rmsd", frame); - } -#endif - - if (m_scale_brightness){ - FloatPixel image_brightness = ImageMatch::pixel_average(scaled, m_reference_image_cropped); - FloatPixel scale = m_average_brightness / image_brightness; - if (std::isnan(scale.r)) scale.r = 1.0; - if (std::isnan(scale.g)) scale.g = 1.0; - if (std::isnan(scale.b)) scale.b = 1.0; - scale.bound(0.8, 1.2); - ImageMatch::scale_brightness(scaled, scale); - } - -// cout << "asdf" << endl; - double ret = ImageMatch::pixel_RMSD(m_reference_image_cropped, scaled); -// cout << "rmsd = " << ret << endl; - return ret; -} - -void ImageMatchDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool ImageMatchDetector::detect(const ImageViewRGB32& screen){ - return rmsd(screen) <= m_max_rmsd; -} - - - -ImageMatchWatcher::ImageMatchWatcher( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness, - std::chrono::milliseconds hold_duration, - Color color -) - : ImageMatchDetector(std::move(reference_image), box, max_rmsd, scale_brightness, color) - , VisualInferenceCallback("ImageMatchWatcher") - , m_hold_duration(hold_duration) - , m_last_match(false) - , m_start_of_match(WallClock::min()) -{} - -void ImageMatchWatcher::make_overlays(VideoOverlaySet& items) const{ - ImageMatchDetector::make_overlays(items); -} -bool ImageMatchWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ - if (!detect(frame)){ - m_last_match = false; - return false; - } - auto now = current_time(); - if (!m_last_match){ - m_last_match = true; - m_start_of_match = now; - return false; - } - return now - m_start_of_match >= m_hold_duration; -} - - - - - - -} +/* Image Match Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "ImageMatchDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +ImageMatchDetector::ImageMatchDetector( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness, + Color color +) + : m_reference_image(std::move(reference_image)) + , m_reference_image_cropped(extract_box_reference(*m_reference_image, box)) + , m_average_brightness(image_stats(m_reference_image_cropped).average) + , m_max_rmsd(max_rmsd) + , m_scale_brightness(scale_brightness) + , m_color(color) + , m_box(box) +{} + +double ImageMatchDetector::rmsd(const ImageViewRGB32& frame) const{ + if (!frame){ + return 1000; + } + ImageViewRGB32 image = extract_box_reference(frame, m_box); + ImageRGB32 scaled = image.scale_to(m_reference_image_cropped.width(), m_reference_image_cropped.height()); + +#if 0 + if (image.width() != (size_t)scaled.width() || image.height() != (size_t)scaled.height()){ + cout << image.width() << " x " << image.height() << " - " << scaled.width() << " x " << scaled.height() << endl; + dump_image(global_logger_tagged(), ProgramInfo(), "ImageMatchDetector-rmsd", frame); + } +#endif + + if (m_scale_brightness){ + FloatPixel image_brightness = ImageMatch::pixel_average(scaled, m_reference_image_cropped); + FloatPixel scale = m_average_brightness / image_brightness; + if (std::isnan(scale.r)) scale.r = 1.0; + if (std::isnan(scale.g)) scale.g = 1.0; + if (std::isnan(scale.b)) scale.b = 1.0; + scale.bound(0.8, 1.2); + ImageMatch::scale_brightness(scaled, scale); + } + +// cout << "asdf" << endl; + double ret = ImageMatch::pixel_RMSD(m_reference_image_cropped, scaled); +// cout << "rmsd = " << ret << endl; + return ret; +} + +void ImageMatchDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool ImageMatchDetector::detect(const ImageViewRGB32& screen){ + return rmsd(screen) <= m_max_rmsd; +} + + + +ImageMatchWatcher::ImageMatchWatcher( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness, + std::chrono::milliseconds hold_duration, + Color color +) + : ImageMatchDetector(std::move(reference_image), box, max_rmsd, scale_brightness, color) + , VisualInferenceCallback("ImageMatchWatcher") + , m_hold_duration(hold_duration) + , m_last_match(false) + , m_start_of_match(WallClock::min()) +{} + +void ImageMatchWatcher::make_overlays(VideoOverlaySet& items) const{ + ImageMatchDetector::make_overlays(items); +} +bool ImageMatchWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ + if (!detect(frame)){ + m_last_match = false; + return false; + } + auto now = current_time(); + if (!m_last_match){ + m_last_match = true; + m_start_of_match = now; + return false; + } + return now - m_start_of_match >= m_hold_duration; +} + + + + + + +} diff --git a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h index 099b582078..8eea66e608 100644 --- a/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h +++ b/SerialPrograms/Source/CommonTools/VisualDetectors/ImageMatchDetector.h @@ -1,68 +1,68 @@ -/* Image Match Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_CommonTools_ImageMatchDetector_H -#define PokemonAutomation_CommonTools_ImageMatchDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/FloatPixel.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class ImageMatchDetector : public StaticScreenDetector{ -public: - ImageMatchDetector( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness = false, - Color color = COLOR_RED - ); - - double rmsd(const ImageViewRGB32& frame) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - std::shared_ptr m_reference_image; - ImageViewRGB32 m_reference_image_cropped; - FloatPixel m_average_brightness; - - double m_max_rmsd; - bool m_scale_brightness; - - Color m_color; - ImageFloatBox m_box; -}; - - -class ImageMatchWatcher : public ImageMatchDetector, public VisualInferenceCallback{ -public: - ImageMatchWatcher( - std::shared_ptr reference_image, const ImageFloatBox& box, - double max_rmsd, bool scale_brightness = false, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(0), - Color color = COLOR_RED - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - std::chrono::milliseconds m_hold_duration; - - bool m_last_match; - WallClock m_start_of_match; -}; - - - - -} -#endif +/* Image Match Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_CommonTools_ImageMatchDetector_H +#define PokemonAutomation_CommonTools_ImageMatchDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class ImageMatchDetector : public StaticScreenDetector{ +public: + ImageMatchDetector( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness = false, + Color color = COLOR_RED + ); + + double rmsd(const ImageViewRGB32& frame) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + std::shared_ptr m_reference_image; + ImageViewRGB32 m_reference_image_cropped; + FloatPixel m_average_brightness; + + double m_max_rmsd; + bool m_scale_brightness; + + Color m_color; + ImageFloatBox m_box; +}; + + +class ImageMatchWatcher : public ImageMatchDetector, public VisualInferenceCallback{ +public: + ImageMatchWatcher( + std::shared_ptr reference_image, const ImageFloatBox& box, + double max_rmsd, bool scale_brightness = false, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(0), + Color color = COLOR_RED + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + std::chrono::milliseconds m_hold_duration; + + bool m_last_match; + WallClock m_start_of_match; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerProgram.cpp b/SerialPrograms/Source/ComputerPrograms/ComputerProgram.cpp index a6f32d3b2d..e1ac82ba38 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerProgram.cpp +++ b/SerialPrograms/Source/ComputerPrograms/ComputerProgram.cpp @@ -1,78 +1,78 @@ -/* Runnable Computer Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonObject.h" -#include "ComputerProgram.h" -#include "ComputerPrograms/Framework/ComputerProgramOption.h" - -namespace PokemonAutomation{ - - -ComputerProgramDescriptor::ComputerProgramDescriptor( - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description -) - : ProgramDescriptor( - COLOR_DARKCYAN, - std::move(identifier), - std::move(category), std::move(display_name), - std::move(doc_link), - std::move(description) - ) -{} -std::unique_ptr ComputerProgramDescriptor::make_panel() const{ - return std::unique_ptr(new ComputerProgramOption(*this)); -} - - - - - -ComputerProgramInstance::ComputerProgramInstance() - : m_options(LockMode::LOCK_WHILE_RUNNING) - , NOTIFICATION_PROGRAM_FINISH( - "Program Finished", - true, true, - ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_ERROR_RECOVERABLE( - "Program Error (Recoverable)", - true, false, - ImageAttachmentMode::PNG, - {"Notifs"} - ) - , NOTIFICATION_ERROR_FATAL( - "Program Error (Fatal)", - true, true, - ImageAttachmentMode::PNG, - {"Notifs"} - ) -{} -void ComputerProgramInstance::add_option(ConfigOption& option, std::string serialization_string){ - m_options.add_option(option, std::move(serialization_string)); -} -void ComputerProgramInstance::from_json(const JsonValue& json){ - m_options.load_json(json); -} -JsonValue ComputerProgramInstance::to_json() const{ - return m_options.to_json(); -} -std::string ComputerProgramInstance::check_validity() const{ - return m_options.check_validity(); -} -void ComputerProgramInstance::restore_defaults(){ - return m_options.restore_defaults(); -} - - - - - - -} +/* Runnable Computer Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonObject.h" +#include "ComputerProgram.h" +#include "ComputerPrograms/Framework/ComputerProgramOption.h" + +namespace PokemonAutomation{ + + +ComputerProgramDescriptor::ComputerProgramDescriptor( + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description +) + : ProgramDescriptor( + COLOR_DARKCYAN, + std::move(identifier), + std::move(category), std::move(display_name), + std::move(doc_link), + std::move(description) + ) +{} +std::unique_ptr ComputerProgramDescriptor::make_panel() const{ + return std::unique_ptr(new ComputerProgramOption(*this)); +} + + + + + +ComputerProgramInstance::ComputerProgramInstance() + : m_options(LockMode::LOCK_WHILE_RUNNING) + , NOTIFICATION_PROGRAM_FINISH( + "Program Finished", + true, true, + ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_ERROR_RECOVERABLE( + "Program Error (Recoverable)", + true, false, + ImageAttachmentMode::PNG, + {"Notifs"} + ) + , NOTIFICATION_ERROR_FATAL( + "Program Error (Fatal)", + true, true, + ImageAttachmentMode::PNG, + {"Notifs"} + ) +{} +void ComputerProgramInstance::add_option(ConfigOption& option, std::string serialization_string){ + m_options.add_option(option, std::move(serialization_string)); +} +void ComputerProgramInstance::from_json(const JsonValue& json){ + m_options.load_json(json); +} +JsonValue ComputerProgramInstance::to_json() const{ + return m_options.to_json(); +} +std::string ComputerProgramInstance::check_validity() const{ + return m_options.check_validity(); +} +void ComputerProgramInstance::restore_defaults(){ + return m_options.restore_defaults(); +} + + + + + + +} diff --git a/SerialPrograms/Source/ComputerPrograms/ComputerProgram.h b/SerialPrograms/Source/ComputerPrograms/ComputerProgram.h index 7e67328dac..32cef5c617 100644 --- a/SerialPrograms/Source/ComputerPrograms/ComputerProgram.h +++ b/SerialPrograms/Source/ComputerPrograms/ComputerProgram.h @@ -1,110 +1,110 @@ -/* Runnable Computer Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_RunnableComputerProgram_H -#define PokemonAutomation_RunnableComputerProgram_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Panels/ProgramDescriptor.h" - -namespace PokemonAutomation{ - -class CancellableScope; -class ComputerProgramInstance; - - -class ComputerProgramDescriptor : public ProgramDescriptor{ -public: - ComputerProgramDescriptor( - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description - ); - - virtual std::unique_ptr make_panel() const override; - virtual std::unique_ptr make_instance() const = 0; -}; - - - - - -// -// As of this writing, this class will never be called in a manner where -// thread-safety is of concern. However, this may change in the future. -// -// Here is the curent status: -// -// Called from UI thread: -// - Construction/destruction -// - from/to_json() -// - restore_defaults() -// -// Called from program thread: -// - program() -// -// Called from both UI and program threads: -// - check_validity() -// -// Calls to this class will never be concurrent from different threads. -// -class ComputerProgramInstance{ -public: - virtual ~ComputerProgramInstance() = default; - ComputerProgramInstance(const ComputerProgramInstance&) = delete; - void operator=(const ComputerProgramInstance&) = delete; - - ComputerProgramInstance(); - - virtual void program(ProgramEnvironment& env, CancellableScope& scope) = 0; - - -public: - // Settings - - virtual void from_json(const JsonValue& json); - virtual JsonValue to_json() const; - - virtual std::string check_validity() const; - virtual void restore_defaults(); - - -protected: - friend class ComputerProgramOption; - - BatchOption m_options; - void add_option(ConfigOption& option, std::string serialization_string); - - -public: - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationOption NOTIFICATION_ERROR_RECOVERABLE; - EventNotificationOption NOTIFICATION_ERROR_FATAL; -}; - - - -template -class ComputerProgramWrapper : public Descriptor{ -public: - virtual std::unique_ptr make_instance() const override{ - return std::unique_ptr(new Instance()); - } -}; - -template -std::unique_ptr make_computer_program(){ - return std::make_unique>(); -} - - - - -} -#endif +/* Runnable Computer Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_RunnableComputerProgram_H +#define PokemonAutomation_RunnableComputerProgram_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Panels/ProgramDescriptor.h" + +namespace PokemonAutomation{ + +class CancellableScope; +class ComputerProgramInstance; + + +class ComputerProgramDescriptor : public ProgramDescriptor{ +public: + ComputerProgramDescriptor( + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description + ); + + virtual std::unique_ptr make_panel() const override; + virtual std::unique_ptr make_instance() const = 0; +}; + + + + + +// +// As of this writing, this class will never be called in a manner where +// thread-safety is of concern. However, this may change in the future. +// +// Here is the curent status: +// +// Called from UI thread: +// - Construction/destruction +// - from/to_json() +// - restore_defaults() +// +// Called from program thread: +// - program() +// +// Called from both UI and program threads: +// - check_validity() +// +// Calls to this class will never be concurrent from different threads. +// +class ComputerProgramInstance{ +public: + virtual ~ComputerProgramInstance() = default; + ComputerProgramInstance(const ComputerProgramInstance&) = delete; + void operator=(const ComputerProgramInstance&) = delete; + + ComputerProgramInstance(); + + virtual void program(ProgramEnvironment& env, CancellableScope& scope) = 0; + + +public: + // Settings + + virtual void from_json(const JsonValue& json); + virtual JsonValue to_json() const; + + virtual std::string check_validity() const; + virtual void restore_defaults(); + + +protected: + friend class ComputerProgramOption; + + BatchOption m_options; + void add_option(ConfigOption& option, std::string serialization_string); + + +public: + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationOption NOTIFICATION_ERROR_RECOVERABLE; + EventNotificationOption NOTIFICATION_ERROR_FATAL; +}; + + + +template +class ComputerProgramWrapper : public Descriptor{ +public: + virtual std::unique_ptr make_instance() const override{ + return std::unique_ptr(new Instance()); + } +}; + +template +std::unique_ptr make_computer_program(){ + return std::make_unique>(); +} + + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.cpp b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.cpp index 5aba8adf65..2f222c8a12 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.cpp +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.cpp @@ -1,48 +1,48 @@ -/* Computer Program Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "ComputerProgramOption.h" -#include "ComputerProgramWidget.h" - -namespace PokemonAutomation{ - - - - -ComputerProgramOption::ComputerProgramOption(const ComputerProgramDescriptor& descriptor) - : PanelInstance(descriptor) - , m_descriptor(descriptor) - , m_instance(descriptor.make_instance()) -{} - -void ComputerProgramOption::from_json(const JsonValue& json){ - m_instance->from_json(json); -} -JsonValue ComputerProgramOption::to_json() const{ - return m_instance->to_json(); -} - -ConfigOption& ComputerProgramOption::options(){ - return m_instance->m_options; -} - -std::string ComputerProgramOption::check_validity() const{ - return m_instance->check_validity(); -} -void ComputerProgramOption::restore_defaults(){ - m_instance->restore_defaults(); -} - - -QWidget* ComputerProgramOption::make_widget(QWidget& parent, PanelHolder& holder){ - return new ComputerProgramWidget(parent, *this, holder); -} - - - -} +/* Computer Program Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "ComputerProgramOption.h" +#include "ComputerProgramWidget.h" + +namespace PokemonAutomation{ + + + + +ComputerProgramOption::ComputerProgramOption(const ComputerProgramDescriptor& descriptor) + : PanelInstance(descriptor) + , m_descriptor(descriptor) + , m_instance(descriptor.make_instance()) +{} + +void ComputerProgramOption::from_json(const JsonValue& json){ + m_instance->from_json(json); +} +JsonValue ComputerProgramOption::to_json() const{ + return m_instance->to_json(); +} + +ConfigOption& ComputerProgramOption::options(){ + return m_instance->m_options; +} + +std::string ComputerProgramOption::check_validity() const{ + return m_instance->check_validity(); +} +void ComputerProgramOption::restore_defaults(){ + m_instance->restore_defaults(); +} + + +QWidget* ComputerProgramOption::make_widget(QWidget& parent, PanelHolder& holder){ + return new ComputerProgramWidget(parent, *this, holder); +} + + + +} diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.h b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.h index 19edaa005f..aa17dde26b 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.h +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramOption.h @@ -1,55 +1,55 @@ -/* Computer Program Option - * - * From: https://github.com/PokemonAutomation/ - * - * This class represents the serializable state of a computer program. - * This class maintains no UI and is not thread-safe. - * - * Note that this class does own the "ComputerProgramInstance", object - * which is controlled by the individual program itself. There the running - * program can do whatever it wants - including keeping run-time state. - * - */ - -#ifndef PokemonAutomation_ComputerPrograms_ComputerProgramOption_H -#define PokemonAutomation_ComputerPrograms_ComputerProgramOption_H - -#include "CommonFramework/Panels/PanelInstance.h" -#include "ComputerPrograms/ComputerProgram.h" - -namespace PokemonAutomation{ - -class ConfigOption; -class ComputerProgramDescriptor; -class ComputerProgramInstance; - - - -class ComputerProgramOption final : public PanelInstance{ -public: - ComputerProgramOption(const ComputerProgramDescriptor& descriptor); - - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - const ComputerProgramDescriptor& descriptor() const{ return m_descriptor; } - ComputerProgramInstance& instance(){ return *m_instance; } - ConfigOption& options(); - - std::string check_validity() const; - void restore_defaults(); - -private: - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -private: - const ComputerProgramDescriptor& m_descriptor; - std::unique_ptr m_instance; -}; - - - - -} -#endif +/* Computer Program Option + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents the serializable state of a computer program. + * This class maintains no UI and is not thread-safe. + * + * Note that this class does own the "ComputerProgramInstance", object + * which is controlled by the individual program itself. There the running + * program can do whatever it wants - including keeping run-time state. + * + */ + +#ifndef PokemonAutomation_ComputerPrograms_ComputerProgramOption_H +#define PokemonAutomation_ComputerPrograms_ComputerProgramOption_H + +#include "CommonFramework/Panels/PanelInstance.h" +#include "ComputerPrograms/ComputerProgram.h" + +namespace PokemonAutomation{ + +class ConfigOption; +class ComputerProgramDescriptor; +class ComputerProgramInstance; + + + +class ComputerProgramOption final : public PanelInstance{ +public: + ComputerProgramOption(const ComputerProgramDescriptor& descriptor); + + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + const ComputerProgramDescriptor& descriptor() const{ return m_descriptor; } + ComputerProgramInstance& instance(){ return *m_instance; } + ConfigOption& options(); + + std::string check_validity() const; + void restore_defaults(); + +private: + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +private: + const ComputerProgramDescriptor& m_descriptor; + std::unique_ptr m_instance; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp index 129ddfe76f..c83d7fc91e 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.cpp @@ -1,153 +1,153 @@ -/* Computer Program Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CancellableScope.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "ComputerProgramOption.h" -#include "ComputerProgramSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -ComputerProgramSession::ComputerProgramSession(ComputerProgramOption& option) - : ProgramSession(option.descriptor()) - , m_option(option) -{} - -ComputerProgramSession::~ComputerProgramSession(){ - ComputerProgramSession::internal_stop_program(); - join_program_thread(); -} - - -void ComputerProgramSession::restore_defaults(){ - std::lock_guard lg(program_lock()); - if (current_state() != ProgramState::STOPPED){ - logger().log("Cannot change settings while program is running.", COLOR_RED); - return; - } - logger().log("Restoring settings to defaults..."); - m_option.restore_defaults(); -} -std::string ComputerProgramSession::check_validity() const{ - return m_option.check_validity(); -} - - - - - -void ComputerProgramSession::run_program_instance(ProgramEnvironment& env, CancellableScope& scope){ - { - std::lock_guard lg(program_lock()); - std::string error = check_validity(); - if (!error.empty()){ - throw UserSetupError(logger(), std::move(error)); - } - } - - { - WriteSpinLock lg(m_lock); - m_scope = &scope; - } - - try{ - m_option.instance().program(env, scope); - }catch (...){ - WriteSpinLock lg(m_lock); - m_scope = nullptr; - throw; - } - WriteSpinLock lg(m_lock); - m_scope = nullptr; -} -void ComputerProgramSession::internal_stop_program(){ - WriteSpinLock lg(m_lock); - if (m_scope != nullptr){ - m_scope->cancel(std::make_exception_ptr(ProgramCancelledException())); - } -} -void ComputerProgramSession::internal_run_program(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - m_option.options().reset_state(); - - ProgramInfo program_info( - identifier(), - m_option.descriptor().category(), - m_option.descriptor().display_name(), - timestamp() - ); - CancellableHolder scope; - ProgramEnvironment env( - program_info, - *this, - current_stats_tracker(), historical_stats_tracker() - ); - - try{ - logger().log("Starting Program: " + identifier() + ""); - run_program_instance(env, scope); -// m_setup->wait_for_all_requests(); - logger().log("Program finished normally!", COLOR_BLUE); - }catch (OperationCancelledException&){ - }catch (ProgramCancelledException&){ - }catch (ProgramFinishedException& e){ - logger().log("Program finished early!", COLOR_BLUE); - e.send_notification(env, m_option.instance().NOTIFICATION_PROGRAM_FINISH); - }catch (InvalidConnectionStateException&){ - }catch (OperationFailedException& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - e.send_notification(env, m_option.instance().NOTIFICATION_ERROR_FATAL); - }catch (Exception& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - message - ); - }catch (std::exception& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - std::string message = e.what(); - if (message.empty()){ - message = "Unknown std::exception."; - } - report_error(message); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - message - ); - }catch (...){ - logger().log("Program stopped with an exception!", COLOR_RED); - report_error("Unknown error."); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - "Unknown error." - ); - } -} - - - -} +/* Computer Program Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CancellableScope.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "ComputerProgramOption.h" +#include "ComputerProgramSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +ComputerProgramSession::ComputerProgramSession(ComputerProgramOption& option) + : ProgramSession(option.descriptor()) + , m_option(option) +{} + +ComputerProgramSession::~ComputerProgramSession(){ + ComputerProgramSession::internal_stop_program(); + join_program_thread(); +} + + +void ComputerProgramSession::restore_defaults(){ + std::lock_guard lg(program_lock()); + if (current_state() != ProgramState::STOPPED){ + logger().log("Cannot change settings while program is running.", COLOR_RED); + return; + } + logger().log("Restoring settings to defaults..."); + m_option.restore_defaults(); +} +std::string ComputerProgramSession::check_validity() const{ + return m_option.check_validity(); +} + + + + + +void ComputerProgramSession::run_program_instance(ProgramEnvironment& env, CancellableScope& scope){ + { + std::lock_guard lg(program_lock()); + std::string error = check_validity(); + if (!error.empty()){ + throw UserSetupError(logger(), std::move(error)); + } + } + + { + WriteSpinLock lg(m_lock); + m_scope = &scope; + } + + try{ + m_option.instance().program(env, scope); + }catch (...){ + WriteSpinLock lg(m_lock); + m_scope = nullptr; + throw; + } + WriteSpinLock lg(m_lock); + m_scope = nullptr; +} +void ComputerProgramSession::internal_stop_program(){ + WriteSpinLock lg(m_lock); + if (m_scope != nullptr){ + m_scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + } +} +void ComputerProgramSession::internal_run_program(){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + m_option.options().reset_state(); + + ProgramInfo program_info( + identifier(), + m_option.descriptor().category(), + m_option.descriptor().display_name(), + timestamp() + ); + CancellableHolder scope; + ProgramEnvironment env( + program_info, + *this, + current_stats_tracker(), historical_stats_tracker() + ); + + try{ + logger().log("Starting Program: " + identifier() + ""); + run_program_instance(env, scope); +// m_setup->wait_for_all_requests(); + logger().log("Program finished normally!", COLOR_BLUE); + }catch (OperationCancelledException&){ + }catch (ProgramCancelledException&){ + }catch (ProgramFinishedException& e){ + logger().log("Program finished early!", COLOR_BLUE); + e.send_notification(env, m_option.instance().NOTIFICATION_PROGRAM_FINISH); + }catch (InvalidConnectionStateException&){ + }catch (OperationFailedException& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + e.send_notification(env, m_option.instance().NOTIFICATION_ERROR_FATAL); + }catch (Exception& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + message + ); + }catch (std::exception& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + std::string message = e.what(); + if (message.empty()){ + message = "Unknown std::exception."; + } + report_error(message); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + message + ); + }catch (...){ + logger().log("Program stopped with an exception!", COLOR_RED); + report_error("Unknown error."); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + "Unknown error." + ); + } +} + + + +} diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.h b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.h index aa9c898509..6aae83f5b8 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.h +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramSession.h @@ -1,58 +1,58 @@ -/* Computer Program Session - * - * From: https://github.com/PokemonAutomation/ - * - * This class holds the run-time state of a computer program. - * - * This class is fully thread-safe. You can call any functions from anywhere at - * anytime. - * - * Warning: Constructing this class requires an "option" parameter. It is not - * safe to modify this "option" parameter during the lifetime of this class. - * - */ - -#ifndef PokemonAutomation_ComputerPrograms_ComputerProgramSession_H -#define PokemonAutomation_ComputerPrograms_ComputerProgramSession_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/ProgramSession.h" -#include "ComputerPrograms/ComputerProgram.h" - -namespace PokemonAutomation{ - -struct ProgramInfo; -class ComputerProgramOption; -class ProgramEnvironment; - - -class ComputerProgramSession final : public ProgramSession{ -public: - virtual ~ComputerProgramSession(); - ComputerProgramSession(ComputerProgramOption& option); - - void restore_defaults(); - -private: - virtual std::string check_validity() const override; - - virtual void internal_run_program() override; - virtual void internal_stop_program() override; - - -private: - void run_program_instance(ProgramEnvironment& env, CancellableScope& scope); - -private: - ComputerProgramOption& m_option; - - SpinLock m_lock; - CancellableScope* m_scope = nullptr; -}; - - - - - -} -#endif +/* Computer Program Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the run-time state of a computer program. + * + * This class is fully thread-safe. You can call any functions from anywhere at + * anytime. + * + * Warning: Constructing this class requires an "option" parameter. It is not + * safe to modify this "option" parameter during the lifetime of this class. + * + */ + +#ifndef PokemonAutomation_ComputerPrograms_ComputerProgramSession_H +#define PokemonAutomation_ComputerPrograms_ComputerProgramSession_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/ProgramSession.h" +#include "ComputerPrograms/ComputerProgram.h" + +namespace PokemonAutomation{ + +struct ProgramInfo; +class ComputerProgramOption; +class ProgramEnvironment; + + +class ComputerProgramSession final : public ProgramSession{ +public: + virtual ~ComputerProgramSession(); + ComputerProgramSession(ComputerProgramOption& option); + + void restore_defaults(); + +private: + virtual std::string check_validity() const override; + + virtual void internal_run_program() override; + virtual void internal_stop_program() override; + + +private: + void run_program_instance(ProgramEnvironment& env, CancellableScope& scope); + +private: + ComputerProgramOption& m_option; + + SpinLock m_lock; + CancellableScope* m_scope = nullptr; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.cpp b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.cpp index ff19527857..26338902da 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.cpp +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.cpp @@ -1,136 +1,136 @@ -/* Computer Program Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Qt/CollapsibleGroupBox.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/Panels/PanelTools.h" -#include "CommonFramework/Panels/UI/PanelElements.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "ComputerPrograms/ComputerProgram.h" -#include "ComputerPrograms/Framework/ComputerProgramOption.h" -#include "ComputerProgramWidget.h" - -namespace PokemonAutomation{ - - -ComputerProgramWidget::~ComputerProgramWidget(){ - m_session.remove_listener(*this); - delete m_actions_bar; - delete m_stats_bar; - delete m_options; -} -ComputerProgramWidget::ComputerProgramWidget( - QWidget& parent, - ComputerProgramOption& option, - PanelHolder& holder -) - : QWidget(&parent) - , m_holder(holder) - , m_session(option) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - const ComputerProgramDescriptor& descriptor = option.descriptor(); - - CollapsibleGroupBox* header = make_panel_header( - *this, - descriptor.display_name(), - descriptor.doc_link(), - descriptor.description() - ); - layout->addWidget(header); - - - { - QScrollArea* scroll_outer = new QScrollArea(this); - layout->addWidget(scroll_outer); - scroll_outer->setWidgetResizable(true); - - QWidget* scroll_inner = new QWidget(scroll_outer); - scroll_outer->setWidget(scroll_inner); - QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); - scroll_layout->setAlignment(Qt::AlignTop); - - m_options = option.options().make_QtWidget(*this); - scroll_layout->addWidget(&m_options->widget()); - - scroll_layout->addStretch(1); - } - - m_stats_bar = new StatsBar(*this); - m_stats_bar->set_stats("", m_session.historical_stats()); - layout->addWidget(m_stats_bar); - - m_actions_bar = new RunnablePanelActionBar(*this, m_session.current_state()); - layout->addWidget(m_actions_bar); - - connect( - m_actions_bar, &RunnablePanelActionBar::start_clicked, - this, [&](ProgramState state){ - std::string error; - switch (state){ - case ProgramState::STOPPED: - error = m_session.start_program(); - break; - case ProgramState::RUNNING: - error = m_session.stop_program(); - break; - default:; - } - if (!error.empty()){ - this->error(error); - } - } - ); - connect( - m_actions_bar, &RunnablePanelActionBar::defaults_clicked, - this, [&]{ - std::lock_guard lg(m_session.program_lock()); - option.restore_defaults(); - m_options->update_all(false); - } - ); - - m_session.add_listener(*this); -} - -void ComputerProgramWidget::state_change(ProgramState state){ - QMetaObject::invokeMethod(this, [this, state]{ - m_options->widget().setEnabled(state == ProgramState::STOPPED); - m_actions_bar->set_state(state); - if (state == ProgramState::STOPPED){ - m_holder.on_idle(); - }else{ - m_holder.on_busy(); - } - }); -} -void ComputerProgramWidget::stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats){ - QMetaObject::invokeMethod(this, [this, current_stats, historical_stats]{ - m_stats_bar->set_stats( - current_stats == nullptr ? "" : current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN), - historical_stats == nullptr ? "" : historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) - ); - }); -} -void ComputerProgramWidget::error(const std::string& message){ - QMetaObject::invokeMethod(this, [message]{ - QMessageBox box; - box.critical(nullptr, "Error", QString::fromStdString(message)); - }); -} - - - - - - -} +/* Computer Program Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Qt/CollapsibleGroupBox.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/Panels/PanelTools.h" +#include "CommonFramework/Panels/UI/PanelElements.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "ComputerPrograms/ComputerProgram.h" +#include "ComputerPrograms/Framework/ComputerProgramOption.h" +#include "ComputerProgramWidget.h" + +namespace PokemonAutomation{ + + +ComputerProgramWidget::~ComputerProgramWidget(){ + m_session.remove_listener(*this); + delete m_actions_bar; + delete m_stats_bar; + delete m_options; +} +ComputerProgramWidget::ComputerProgramWidget( + QWidget& parent, + ComputerProgramOption& option, + PanelHolder& holder +) + : QWidget(&parent) + , m_holder(holder) + , m_session(option) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + const ComputerProgramDescriptor& descriptor = option.descriptor(); + + CollapsibleGroupBox* header = make_panel_header( + *this, + descriptor.display_name(), + descriptor.doc_link(), + descriptor.description() + ); + layout->addWidget(header); + + + { + QScrollArea* scroll_outer = new QScrollArea(this); + layout->addWidget(scroll_outer); + scroll_outer->setWidgetResizable(true); + + QWidget* scroll_inner = new QWidget(scroll_outer); + scroll_outer->setWidget(scroll_inner); + QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); + scroll_layout->setAlignment(Qt::AlignTop); + + m_options = option.options().make_QtWidget(*this); + scroll_layout->addWidget(&m_options->widget()); + + scroll_layout->addStretch(1); + } + + m_stats_bar = new StatsBar(*this); + m_stats_bar->set_stats("", m_session.historical_stats()); + layout->addWidget(m_stats_bar); + + m_actions_bar = new RunnablePanelActionBar(*this, m_session.current_state()); + layout->addWidget(m_actions_bar); + + connect( + m_actions_bar, &RunnablePanelActionBar::start_clicked, + this, [&](ProgramState state){ + std::string error; + switch (state){ + case ProgramState::STOPPED: + error = m_session.start_program(); + break; + case ProgramState::RUNNING: + error = m_session.stop_program(); + break; + default:; + } + if (!error.empty()){ + this->error(error); + } + } + ); + connect( + m_actions_bar, &RunnablePanelActionBar::defaults_clicked, + this, [&]{ + std::lock_guard lg(m_session.program_lock()); + option.restore_defaults(); + m_options->update_all(false); + } + ); + + m_session.add_listener(*this); +} + +void ComputerProgramWidget::state_change(ProgramState state){ + QMetaObject::invokeMethod(this, [this, state]{ + m_options->widget().setEnabled(state == ProgramState::STOPPED); + m_actions_bar->set_state(state); + if (state == ProgramState::STOPPED){ + m_holder.on_idle(); + }else{ + m_holder.on_busy(); + } + }); +} +void ComputerProgramWidget::stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats){ + QMetaObject::invokeMethod(this, [this, current_stats, historical_stats]{ + m_stats_bar->set_stats( + current_stats == nullptr ? "" : current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN), + historical_stats == nullptr ? "" : historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) + ); + }); +} +void ComputerProgramWidget::error(const std::string& message){ + QMetaObject::invokeMethod(this, [message]{ + QMessageBox box; + box.critical(nullptr, "Error", QString::fromStdString(message)); + }); +} + + + + + + +} diff --git a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.h b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.h index 35d2d61943..43f985e951 100644 --- a/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.h +++ b/SerialPrograms/Source/ComputerPrograms/Framework/ComputerProgramWidget.h @@ -1,55 +1,55 @@ -/* Computer Program Widget - * - * From: https://github.com/PokemonAutomation/ - * - * This is the Qt Widget implementation of the UI for ComputerProgramSession. - * - * On construction, this class attaches itself to the session it is constructed - * with and automatically detaches on destruction. Therefore, this class must - * not outlive the session it is constructed with. While not useful, it is also - * safe to construct multiple UI classes attached to the same session. - * - * Modifications directly to the session object will automatically update this - * UI class. For example, if you use Discord to change the volume of the - * audio playback, it will move the slider as shown by this UI. - * - */ - -#ifndef PokemonAutomation_ComputerPrograms_ComputerProgramWidget_H -#define PokemonAutomation_ComputerPrograms_ComputerProgramWidget_H - -#include "CommonFramework/Panels/UI/PanelElements.h" -#include "ComputerPrograms/ComputerProgram.h" -#include "ComputerPrograms/Framework/ComputerProgramSession.h" -#include "ComputerProgramSession.h" - -namespace PokemonAutomation{ - - - -class ComputerProgramWidget : public QWidget, private ProgramSession::Listener{ -public: - ~ComputerProgramWidget(); - ComputerProgramWidget( - QWidget& parent, - ComputerProgramOption& option, - PanelHolder& holder - ); - -private: - virtual void state_change(ProgramState state) override; - virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) override; - virtual void error(const std::string& message) override; - -private: - PanelHolder& m_holder; - ComputerProgramSession m_session; - ConfigWidget* m_options; - StatsBar* m_stats_bar; - RunnablePanelActionBar* m_actions_bar; -}; - - - -} -#endif +/* Computer Program Widget + * + * From: https://github.com/PokemonAutomation/ + * + * This is the Qt Widget implementation of the UI for ComputerProgramSession. + * + * On construction, this class attaches itself to the session it is constructed + * with and automatically detaches on destruction. Therefore, this class must + * not outlive the session it is constructed with. While not useful, it is also + * safe to construct multiple UI classes attached to the same session. + * + * Modifications directly to the session object will automatically update this + * UI class. For example, if you use Discord to change the volume of the + * audio playback, it will move the slider as shown by this UI. + * + */ + +#ifndef PokemonAutomation_ComputerPrograms_ComputerProgramWidget_H +#define PokemonAutomation_ComputerPrograms_ComputerProgramWidget_H + +#include "CommonFramework/Panels/UI/PanelElements.h" +#include "ComputerPrograms/ComputerProgram.h" +#include "ComputerPrograms/Framework/ComputerProgramSession.h" +#include "ComputerProgramSession.h" + +namespace PokemonAutomation{ + + + +class ComputerProgramWidget : public QWidget, private ProgramSession::Listener{ +public: + ~ComputerProgramWidget(); + ComputerProgramWidget( + QWidget& parent, + ComputerProgramOption& option, + PanelHolder& holder + ); + +private: + virtual void state_change(ProgramState state) override; + virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) override; + virtual void error(const std::string& message) override; + +private: + PanelHolder& m_holder; + ComputerProgramSession m_session; + ConfigWidget* m_options; + StatsBar* m_stats_bar; + RunnablePanelActionBar* m_actions_bar; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/Controller.h b/SerialPrograms/Source/Controllers/Controller.h index a154508a92..937537177d 100644 --- a/SerialPrograms/Source/Controllers/Controller.h +++ b/SerialPrograms/Source/Controllers/Controller.h @@ -1,270 +1,270 @@ -/* Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_Controller_H -#define PokemonAutomation_Controllers_Controller_H - -#include "Common/Compiler.h" -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Time.h" -#include "Common/Cpp/CancellableScope.h" - -class QKeyEvent; - -namespace PokemonAutomation{ - -class RecursiveThrottler; -enum class ControllerType; -enum class ControllerPerformanceClass; -class ControllerFeatures; - - - -inline Milliseconds round_up_to_ticksize(Milliseconds ticksize, Milliseconds duration){ - if (ticksize == Milliseconds::zero()){ - return duration; - } - return (duration + ticksize - Milliseconds(1)) / ticksize * ticksize; -} - - - - -class AbstractController{ -public: - virtual ~AbstractController() = default; - - virtual Logger& logger() = 0; - virtual RecursiveThrottler& logging_throttler() = 0; - - -public: - // Static Information - - virtual ControllerType controller_type() const = 0; - virtual const ControllerFeatures& controller_features() const = 0; - virtual ControllerPerformanceClass performance_class() const = 0; - - // If the controller is polled at a fixed interval, this is that interval. - // Otherwise, returns zero. - virtual Milliseconds ticksize() const = 0; - - // The minimum amount of time between two state reports. This effectively - // limits how quickly you can change states. - // Controllers with non-zero ticksize will have (ticksize == cooldown). - virtual Milliseconds cooldown() const = 0; - - // Some controllers are imprecise. This returns the variation. - // Zero means "tick precise". - virtual Milliseconds timing_variation() const = 0; - - // If the controller can atomically press/release multiple buttons - // return true. This means that if the program presses A and B - // simultaneously, the console will never see an intermediate state where - // either A or B is pressed by itself before the other is pressed as well. - virtual bool atomic_multibutton() const = 0; - - -public: - // Status - - virtual bool is_ready() const = 0; - - -public: - // - // Cancellation - // - // These functions will return immediately and are thread-safe with - // everything. The intended use-case is for an inference thread to cancel - // a running sequence of commands on a program thread. - // - - // Cancel all commands. This returns the controller to the neutral button - // state and clears the command queue. - // This does not wait for the commands to finish cancelling. This is an - // asynchronous function that merely initiates the cancellation process. - virtual void cancel_all_commands() = 0; - - // Same as "cancel_all_commands()", but instead of cancelling the stream, - // it lets it keep running. Then on the next command issued after this - // cancel, it will atomically replace the stream without gapping. - // This lets you do stuff like suddenly change joystick movement in - // response to inference while simultaneously holding a button without - // ever releasing it during the transition. - virtual void replace_on_next_command() = 0; - - -public: - // - // Commands - // - // Commands are actions like button presses or joystick movements that are - // eventually sent to the console. - // - // All commands are prefixed with "issue_". - // Commands are not thread-safe with other commands. - // Commands are thread-safe with the cancellation functions above. - // - // Commands are asynchronous. When you call a command function on this, - // class it gets enqueued into a FIFO and immediately returns. It will only - // block if the FIFO is full. - // - // If a command is called with a cancelled "cancellable" parameter, it will - // throw an OperationCancelledException. - // If a cancellation happens while you are inside a command function, it - // will immediately stop and throw an OperationCancelledException. - // - - -public: - // - // Superscalar Commands (the "ssf" framework) - // - - // - // delay Time to wait before moving onto the next command. - // hold Time to hold the button/stick down for. - // cooldown After the button has been released, prevent it from being - // used again for this much time. - // - // For "normal" use, you should always set (delay == hold + cooldown). - // This is the easiest case to understand and is what the "pbf" interface - // exposes. - // - // If the button is busy (due to still being held down or is waiting out - // the cooldown), the command will wait until the button is ready. - // - // By setting (delay < hold), the command will "return" early and move onto - // the next command while the button is still being held down. - // - // If a command returns before it is finished (delay < hold + cooldown), - // it is considered a "hanging" command. - // - // This allows you to overlap buttons. But is confusing to use because it - // implies a non-trivial controller state with pending button presses that - // are scheduled to be released at a later time. - // - // Each button/stick has its own independent timeline/schedule. - // Users are responsible for understanding the controller state and - // managing the timeline/scheduling. - // - // It is important to remember that the "timeline" here is the timeline - // being fed to the Switch. Thus the timing parameters written in the C++ - // code here is what you will get on the console (or as close as possible). - // - // The actual calls to the methods in the class will return or block in an - // unspecified manner as they merely enqueue into a FIFO which is then - // "replayed" to the Switch in an implementation-dependent manner. - // - - // Wait for all unfinished commands to finish. This will also wait out - // hanging commands including their cooldown periods. - // This is not a true command function as it waits for the entire queue to - // empty out rather than entering itself into the queue. - // If a cancellation happens inside this function, it will immediately - // throw an OperationCancelledException. - virtual void wait_for_all(const Cancellable* cancellable) = 0; - - // Tell the scheduler to wait for all pending commands to finish - // (including cooldowns) before executing further instructions. - // This is used to prevent hanging commands from overlapping with new - // commands issued after this barrier. - virtual void issue_barrier(const Cancellable* cancellable) = 0; - - // Do nothing for this much time. - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) = 0; - - -public: - // Keyboard Controls - - virtual void keyboard_release_all(){} - virtual void keyboard_press(const QKeyEvent& event){} - virtual void keyboard_release(const QKeyEvent& event){} -}; - - - - -// -// The context wrapper to support asynchronous cancel. -// -template -class ControllerContext final : public CancellableScope{ -public: - using ControllerType = Type; - -public: - ControllerContext(ControllerType& controller) - : m_controller(controller) - {} - ControllerContext(CancellableScope& parent, ControllerType& controller) - : m_controller(controller) - { - attach(parent); - } - virtual ~ControllerContext(){ - detach(); - } - - ControllerType* operator->(){ - m_lifetime_sanitizer.check_usage(); - return &m_controller; - } - - operator ControllerType&() const{ return m_controller; } - ControllerType& controller() const{ return m_controller; } - - void wait_for_all_requests() const{ - auto scope = m_lifetime_sanitizer.check_scope(); - m_controller.wait_for_all(this); - } - - // Stop all commands in this context now. - void cancel_now(){ - auto scope = m_lifetime_sanitizer.check_scope(); - CancellableScope::cancel(nullptr); - m_controller.cancel_all_commands(); - } - - // Stop the commands in this context, but do it lazily. - // - // 1. Stop new commands from being issued to the device from this context. - // 2. Tell the device that the next command that is issued should replace - // the command queue. - // - // This cancel is used when you need continuity from an ongoing - // sequence. - void cancel_lazy(){ - auto scope = m_lifetime_sanitizer.check_scope(); - CancellableScope::cancel(nullptr); - m_controller.replace_on_next_command(); - } - - virtual bool cancel(std::exception_ptr exception) noexcept override{ - auto scope = m_lifetime_sanitizer.check_scope(); - if (CancellableScope::cancel(std::move(exception))){ - return true; - } - try{ - m_controller.cancel_all_commands(); - }catch (...){} - return false; - } - - -private: - ControllerType& m_controller; - LifetimeSanitizer m_lifetime_sanitizer; -}; - - - - - -} -#endif +/* Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_Controller_H +#define PokemonAutomation_Controllers_Controller_H + +#include "Common/Compiler.h" +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "Common/Cpp/CancellableScope.h" + +class QKeyEvent; + +namespace PokemonAutomation{ + +class RecursiveThrottler; +enum class ControllerType; +enum class ControllerPerformanceClass; +class ControllerFeatures; + + + +inline Milliseconds round_up_to_ticksize(Milliseconds ticksize, Milliseconds duration){ + if (ticksize == Milliseconds::zero()){ + return duration; + } + return (duration + ticksize - Milliseconds(1)) / ticksize * ticksize; +} + + + + +class AbstractController{ +public: + virtual ~AbstractController() = default; + + virtual Logger& logger() = 0; + virtual RecursiveThrottler& logging_throttler() = 0; + + +public: + // Static Information + + virtual ControllerType controller_type() const = 0; + virtual const ControllerFeatures& controller_features() const = 0; + virtual ControllerPerformanceClass performance_class() const = 0; + + // If the controller is polled at a fixed interval, this is that interval. + // Otherwise, returns zero. + virtual Milliseconds ticksize() const = 0; + + // The minimum amount of time between two state reports. This effectively + // limits how quickly you can change states. + // Controllers with non-zero ticksize will have (ticksize == cooldown). + virtual Milliseconds cooldown() const = 0; + + // Some controllers are imprecise. This returns the variation. + // Zero means "tick precise". + virtual Milliseconds timing_variation() const = 0; + + // If the controller can atomically press/release multiple buttons + // return true. This means that if the program presses A and B + // simultaneously, the console will never see an intermediate state where + // either A or B is pressed by itself before the other is pressed as well. + virtual bool atomic_multibutton() const = 0; + + +public: + // Status + + virtual bool is_ready() const = 0; + + +public: + // + // Cancellation + // + // These functions will return immediately and are thread-safe with + // everything. The intended use-case is for an inference thread to cancel + // a running sequence of commands on a program thread. + // + + // Cancel all commands. This returns the controller to the neutral button + // state and clears the command queue. + // This does not wait for the commands to finish cancelling. This is an + // asynchronous function that merely initiates the cancellation process. + virtual void cancel_all_commands() = 0; + + // Same as "cancel_all_commands()", but instead of cancelling the stream, + // it lets it keep running. Then on the next command issued after this + // cancel, it will atomically replace the stream without gapping. + // This lets you do stuff like suddenly change joystick movement in + // response to inference while simultaneously holding a button without + // ever releasing it during the transition. + virtual void replace_on_next_command() = 0; + + +public: + // + // Commands + // + // Commands are actions like button presses or joystick movements that are + // eventually sent to the console. + // + // All commands are prefixed with "issue_". + // Commands are not thread-safe with other commands. + // Commands are thread-safe with the cancellation functions above. + // + // Commands are asynchronous. When you call a command function on this, + // class it gets enqueued into a FIFO and immediately returns. It will only + // block if the FIFO is full. + // + // If a command is called with a cancelled "cancellable" parameter, it will + // throw an OperationCancelledException. + // If a cancellation happens while you are inside a command function, it + // will immediately stop and throw an OperationCancelledException. + // + + +public: + // + // Superscalar Commands (the "ssf" framework) + // + + // + // delay Time to wait before moving onto the next command. + // hold Time to hold the button/stick down for. + // cooldown After the button has been released, prevent it from being + // used again for this much time. + // + // For "normal" use, you should always set (delay == hold + cooldown). + // This is the easiest case to understand and is what the "pbf" interface + // exposes. + // + // If the button is busy (due to still being held down or is waiting out + // the cooldown), the command will wait until the button is ready. + // + // By setting (delay < hold), the command will "return" early and move onto + // the next command while the button is still being held down. + // + // If a command returns before it is finished (delay < hold + cooldown), + // it is considered a "hanging" command. + // + // This allows you to overlap buttons. But is confusing to use because it + // implies a non-trivial controller state with pending button presses that + // are scheduled to be released at a later time. + // + // Each button/stick has its own independent timeline/schedule. + // Users are responsible for understanding the controller state and + // managing the timeline/scheduling. + // + // It is important to remember that the "timeline" here is the timeline + // being fed to the Switch. Thus the timing parameters written in the C++ + // code here is what you will get on the console (or as close as possible). + // + // The actual calls to the methods in the class will return or block in an + // unspecified manner as they merely enqueue into a FIFO which is then + // "replayed" to the Switch in an implementation-dependent manner. + // + + // Wait for all unfinished commands to finish. This will also wait out + // hanging commands including their cooldown periods. + // This is not a true command function as it waits for the entire queue to + // empty out rather than entering itself into the queue. + // If a cancellation happens inside this function, it will immediately + // throw an OperationCancelledException. + virtual void wait_for_all(const Cancellable* cancellable) = 0; + + // Tell the scheduler to wait for all pending commands to finish + // (including cooldowns) before executing further instructions. + // This is used to prevent hanging commands from overlapping with new + // commands issued after this barrier. + virtual void issue_barrier(const Cancellable* cancellable) = 0; + + // Do nothing for this much time. + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) = 0; + + +public: + // Keyboard Controls + + virtual void keyboard_release_all(){} + virtual void keyboard_press(const QKeyEvent& event){} + virtual void keyboard_release(const QKeyEvent& event){} +}; + + + + +// +// The context wrapper to support asynchronous cancel. +// +template +class ControllerContext final : public CancellableScope{ +public: + using ControllerType = Type; + +public: + ControllerContext(ControllerType& controller) + : m_controller(controller) + {} + ControllerContext(CancellableScope& parent, ControllerType& controller) + : m_controller(controller) + { + attach(parent); + } + virtual ~ControllerContext(){ + detach(); + } + + ControllerType* operator->(){ + m_lifetime_sanitizer.check_usage(); + return &m_controller; + } + + operator ControllerType&() const{ return m_controller; } + ControllerType& controller() const{ return m_controller; } + + void wait_for_all_requests() const{ + auto scope = m_lifetime_sanitizer.check_scope(); + m_controller.wait_for_all(this); + } + + // Stop all commands in this context now. + void cancel_now(){ + auto scope = m_lifetime_sanitizer.check_scope(); + CancellableScope::cancel(nullptr); + m_controller.cancel_all_commands(); + } + + // Stop the commands in this context, but do it lazily. + // + // 1. Stop new commands from being issued to the device from this context. + // 2. Tell the device that the next command that is issued should replace + // the command queue. + // + // This cancel is used when you need continuity from an ongoing + // sequence. + void cancel_lazy(){ + auto scope = m_lifetime_sanitizer.check_scope(); + CancellableScope::cancel(nullptr); + m_controller.replace_on_next_command(); + } + + virtual bool cancel(std::exception_ptr exception) noexcept override{ + auto scope = m_lifetime_sanitizer.check_scope(); + if (CancellableScope::cancel(std::move(exception))){ + return true; + } + try{ + m_controller.cancel_all_commands(); + }catch (...){} + return false; + } + + +private: + ControllerType& m_controller; + LifetimeSanitizer m_lifetime_sanitizer; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerCapability.cpp b/SerialPrograms/Source/Controllers/ControllerCapability.cpp index 11ebc61b03..5eba57e452 100644 --- a/SerialPrograms/Source/Controllers/ControllerCapability.cpp +++ b/SerialPrograms/Source/Controllers/ControllerCapability.cpp @@ -1,28 +1,28 @@ -/* Controller Capabilities - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ControllerTypeStrings.h" -#include "ControllerCapability.h" - -namespace PokemonAutomation{ - - - -std::string ControllerFeatures::contains_all(const ControllerFeatures& features) const{ - auto scope_check = m_sanitizer.check_scope(); - for (ControllerFeature feature : features.m_features){ - if (!contains(feature)){ - return CONTROLLER_FEATURE_STRINGS.get_string(feature); - } - } - return ""; -} - - - - - -} +/* Controller Capabilities + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ControllerTypeStrings.h" +#include "ControllerCapability.h" + +namespace PokemonAutomation{ + + + +std::string ControllerFeatures::contains_all(const ControllerFeatures& features) const{ + auto scope_check = m_sanitizer.check_scope(); + for (ControllerFeature feature : features.m_features){ + if (!contains(feature)){ + return CONTROLLER_FEATURE_STRINGS.get_string(feature); + } + } + return ""; +} + + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerCapability.h b/SerialPrograms/Source/Controllers/ControllerCapability.h index 105ee73822..689ec2866c 100644 --- a/SerialPrograms/Source/Controllers/ControllerCapability.h +++ b/SerialPrograms/Source/Controllers/ControllerCapability.h @@ -1,57 +1,57 @@ -/* Controller Capabilities - * - * From: https://github.com/PokemonAutomation/ - * - * Represents optional features that each controller - * interface may have. - * - * For example, PABotBase has 3 different levels: - * - Not PABotBase (protocol only, no commands) - * - PABotBase-12KB (basic commands only) - * - PABotBase-31KB (basic commands + advanced RPC) - * - * This class allows programs to declare required features so that the - * controller interface can error if it lacks them. - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerCapabilities_H -#define PokemonAutomation_Controllers_ControllerCapabilities_H - -#include -#include -#include -#include "Common/Cpp/LifetimeSanitizer.h" -#include "ControllerTypes.h" - -namespace PokemonAutomation{ - - -class ControllerFeatures{ -public: - ControllerFeatures() - : m_sanitizer("ControllerFeatures") - {} - ControllerFeatures(std::initializer_list list) - : m_features(std::move(list)) - , m_sanitizer("ControllerFeatures") - {} - - bool contains(ControllerFeature feature) const{ - return m_features.contains(feature); - } - - // Returns empty string if this class contains everything in "features". - // Otherwise, returns the name of one of the missing features. - std::string contains_all(const ControllerFeatures& features) const; - -private: - std::set m_features; - - LifetimeSanitizer m_sanitizer; -}; - - - -} -#endif +/* Controller Capabilities + * + * From: https://github.com/PokemonAutomation/ + * + * Represents optional features that each controller + * interface may have. + * + * For example, PABotBase has 3 different levels: + * - Not PABotBase (protocol only, no commands) + * - PABotBase-12KB (basic commands only) + * - PABotBase-31KB (basic commands + advanced RPC) + * + * This class allows programs to declare required features so that the + * controller interface can error if it lacks them. + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerCapabilities_H +#define PokemonAutomation_Controllers_ControllerCapabilities_H + +#include +#include +#include +#include "Common/Cpp/LifetimeSanitizer.h" +#include "ControllerTypes.h" + +namespace PokemonAutomation{ + + +class ControllerFeatures{ +public: + ControllerFeatures() + : m_sanitizer("ControllerFeatures") + {} + ControllerFeatures(std::initializer_list list) + : m_features(std::move(list)) + , m_sanitizer("ControllerFeatures") + {} + + bool contains(ControllerFeature feature) const{ + return m_features.contains(feature); + } + + // Returns empty string if this class contains everything in "features". + // Otherwise, returns the name of one of the missing features. + std::string contains_all(const ControllerFeatures& features) const; + +private: + std::set m_features; + + LifetimeSanitizer m_sanitizer; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerConnection.cpp b/SerialPrograms/Source/Controllers/ControllerConnection.cpp index aca0b96f72..f0ff7eedeb 100644 --- a/SerialPrograms/Source/Controllers/ControllerConnection.cpp +++ b/SerialPrograms/Source/Controllers/ControllerConnection.cpp @@ -1,77 +1,77 @@ -/* Controller Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "ControllerConnection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - -void ControllerConnection::add_status_listener(StatusListener& listener){ - m_status_listeners.add(listener); - if (m_ready.load(std::memory_order_acquire)){ - listener.post_connection_ready(*this, controller_mode_status()); - } -} -void ControllerConnection::remove_status_listener(StatusListener& listener){ - m_status_listeners.remove(listener); -} - -std::string ControllerConnection::status_text() const{ - SpinLockGuard lg(m_status_text_lock); - std::string str = m_status_line0; - if (!str.empty() && !m_status_line1.empty()){ - str += "
"; - str += m_status_line1; - } - return str; -} - - - -void ControllerConnection::set_status_line0(const std::string& text, Color color){ - { - WriteSpinLock lg(m_status_text_lock); - m_status_line0 = html_color_text(text, color); - } - signal_status_text_changed(status_text()); -} -void ControllerConnection::set_status_line1(const std::string& text, Color color){ - { - WriteSpinLock lg(m_status_text_lock); - m_status_line1 = html_color_text(text, color); - } - signal_status_text_changed(status_text()); -} -void ControllerConnection::declare_ready(const ControllerModeStatus& mode_status){ - m_ready.store(true, std::memory_order_release); - signal_post_ready(mode_status); -} - - -//void ControllerConnection::signal_pre_not_ready(){ -// m_status_listeners.run_method_unique(&StatusListener::pre_connection_not_ready, *this); -//} -void ControllerConnection::signal_post_ready(const ControllerModeStatus& mode_status){ - m_status_listeners.run_method_unique(&StatusListener::post_connection_ready, *this, mode_status); -} -void ControllerConnection::signal_status_text_changed(const std::string& text){ -// cout << "m_status_listeners.size() = " << m_status_listeners.count_unique() << endl; - m_status_listeners.run_method_unique(&StatusListener::status_text_changed, *this, text); -} -void ControllerConnection::signal_error(const std::string& text){ - m_status_listeners.run_method_unique(&StatusListener::on_error, *this, text); -} - - - - -} +/* Controller Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "ControllerConnection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + +void ControllerConnection::add_status_listener(StatusListener& listener){ + m_status_listeners.add(listener); + if (m_ready.load(std::memory_order_acquire)){ + listener.post_connection_ready(*this, controller_mode_status()); + } +} +void ControllerConnection::remove_status_listener(StatusListener& listener){ + m_status_listeners.remove(listener); +} + +std::string ControllerConnection::status_text() const{ + SpinLockGuard lg(m_status_text_lock); + std::string str = m_status_line0; + if (!str.empty() && !m_status_line1.empty()){ + str += "
"; + str += m_status_line1; + } + return str; +} + + + +void ControllerConnection::set_status_line0(const std::string& text, Color color){ + { + WriteSpinLock lg(m_status_text_lock); + m_status_line0 = html_color_text(text, color); + } + signal_status_text_changed(status_text()); +} +void ControllerConnection::set_status_line1(const std::string& text, Color color){ + { + WriteSpinLock lg(m_status_text_lock); + m_status_line1 = html_color_text(text, color); + } + signal_status_text_changed(status_text()); +} +void ControllerConnection::declare_ready(const ControllerModeStatus& mode_status){ + m_ready.store(true, std::memory_order_release); + signal_post_ready(mode_status); +} + + +//void ControllerConnection::signal_pre_not_ready(){ +// m_status_listeners.run_method_unique(&StatusListener::pre_connection_not_ready, *this); +//} +void ControllerConnection::signal_post_ready(const ControllerModeStatus& mode_status){ + m_status_listeners.run_method_unique(&StatusListener::post_connection_ready, *this, mode_status); +} +void ControllerConnection::signal_status_text_changed(const std::string& text){ +// cout << "m_status_listeners.size() = " << m_status_listeners.count_unique() << endl; + m_status_listeners.run_method_unique(&StatusListener::status_text_changed, *this, text); +} +void ControllerConnection::signal_error(const std::string& text){ + m_status_listeners.run_method_unique(&StatusListener::on_error, *this, text); +} + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerConnection.h b/SerialPrograms/Source/Controllers/ControllerConnection.h index 052929aa3c..252fb97cc5 100644 --- a/SerialPrograms/Source/Controllers/ControllerConnection.h +++ b/SerialPrograms/Source/Controllers/ControllerConnection.h @@ -1,87 +1,87 @@ -/* Controller Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerConnection_H -#define PokemonAutomation_Controllers_ControllerConnection_H - -#include "Common/Cpp/ListenerSet.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "ControllerDescriptor.h" - -namespace PokemonAutomation{ - - - -struct ControllerModeStatus{ - ControllerType current_controller = ControllerType::None; - std::map supported_controllers; -}; - - - -class ControllerConnection{ -public: - struct StatusListener{ -// virtual void pre_connection_not_ready(ControllerConnection& connection){} - virtual void post_connection_ready( - ControllerConnection& connection, - const ControllerModeStatus& mode_status - ){} - virtual void status_text_changed( - ControllerConnection& connection, const std::string& text - ){} - virtual void on_error( - ControllerConnection& connection, const std::string& text - ){}; - }; - - void add_status_listener(StatusListener& listener); - void remove_status_listener(StatusListener& listener); - - -public: - virtual ~ControllerConnection() = default; - - bool is_ready() const{ return m_ready.load(std::memory_order_acquire); } - std::string status_text() const; - - // Returns the current controller type and the list of supported controllers. - // The current controller may be "None" if there is only one supported - // controller since it is implied to be that. - virtual ControllerModeStatus controller_mode_status() const = 0; - - -public: - void set_status_line0(const std::string& text, Color color = Color()); - void set_status_line1(const std::string& text, Color color = Color()); - - -protected: - void declare_ready(const ControllerModeStatus& mode_status); - - -private: -// void signal_pre_not_ready(); - void signal_post_ready(const ControllerModeStatus& mode_status); - void signal_status_text_changed(const std::string& text); - void signal_error(const std::string& text); - - -protected: - std::atomic m_ready; - -private: - mutable SpinLock m_status_text_lock; - std::string m_status_line0; - std::string m_status_line1; - ListenerSet m_status_listeners; -}; - - - - -} -#endif +/* Controller Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerConnection_H +#define PokemonAutomation_Controllers_ControllerConnection_H + +#include "Common/Cpp/ListenerSet.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "ControllerDescriptor.h" + +namespace PokemonAutomation{ + + + +struct ControllerModeStatus{ + ControllerType current_controller = ControllerType::None; + std::map supported_controllers; +}; + + + +class ControllerConnection{ +public: + struct StatusListener{ +// virtual void pre_connection_not_ready(ControllerConnection& connection){} + virtual void post_connection_ready( + ControllerConnection& connection, + const ControllerModeStatus& mode_status + ){} + virtual void status_text_changed( + ControllerConnection& connection, const std::string& text + ){} + virtual void on_error( + ControllerConnection& connection, const std::string& text + ){}; + }; + + void add_status_listener(StatusListener& listener); + void remove_status_listener(StatusListener& listener); + + +public: + virtual ~ControllerConnection() = default; + + bool is_ready() const{ return m_ready.load(std::memory_order_acquire); } + std::string status_text() const; + + // Returns the current controller type and the list of supported controllers. + // The current controller may be "None" if there is only one supported + // controller since it is implied to be that. + virtual ControllerModeStatus controller_mode_status() const = 0; + + +public: + void set_status_line0(const std::string& text, Color color = Color()); + void set_status_line1(const std::string& text, Color color = Color()); + + +protected: + void declare_ready(const ControllerModeStatus& mode_status); + + +private: +// void signal_pre_not_ready(); + void signal_post_ready(const ControllerModeStatus& mode_status); + void signal_status_text_changed(const std::string& text); + void signal_error(const std::string& text); + + +protected: + std::atomic m_ready; + +private: + mutable SpinLock m_status_text_lock; + std::string m_status_line0; + std::string m_status_line1; + ListenerSet m_status_listeners; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp b/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp index e06b431e2c..2f1ff68378 100644 --- a/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp +++ b/SerialPrograms/Source/Controllers/ControllerDescriptor.cpp @@ -1,123 +1,123 @@ -/* Controller Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "ControllerTypeStrings.h" -#include "ControllerDescriptor.h" -#include "NullController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -// -// Here we store a map of all controller types in the program. -// -std::map> ALL_CONTROLLER_INTERFACES; - - -void InterfaceType::register_factory( - ControllerInterface controller_interface, - std::unique_ptr factory -){ - auto ret = ALL_CONTROLLER_INTERFACES.emplace(controller_interface, std::move(factory)); - if (!ret.second){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Duplicate Factory Name: " + CONTROLLER_INTERFACE_STRINGS.get_string(controller_interface) - ); - } -} - - - - -ControllerOption::ControllerOption() - : m_descriptor(new NullControllerDescriptor()) -{} - - -void ControllerOption::set_descriptor(std::shared_ptr descriptor){ - m_descriptor_cache[descriptor->interface_type] = descriptor; - m_descriptor = std::move(descriptor); -} - -std::shared_ptr ControllerOption::get_descriptor_from_cache(ControllerInterface interface_type) const{ - auto iter = m_descriptor_cache.find(interface_type); - if (iter == m_descriptor_cache.end()){ - return nullptr; - } - return iter->second; -} - - - -void ControllerOption::load_json(const JsonValue& json){ - std::shared_ptr descriptor; - do{ - if (json.is_null()){ - break; - } - - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - break; - } - const std::string* type = obj->get_string("Interface"); - if (type == nullptr){ - break; - } - - for (const auto& item : ALL_CONTROLLER_INTERFACES){ - const JsonValue* params = obj->get_value(CONTROLLER_INTERFACE_STRINGS.get_string(item.first)); - if (params == nullptr){ - continue; - } - m_descriptor_cache[item.first] = item.second->make(*params); - } - - auto iter = m_descriptor_cache.find(CONTROLLER_INTERFACE_STRINGS.get_enum(*type, ControllerInterface::None)); - if (iter == m_descriptor_cache.end()){ - break; - } - - descriptor = iter->second; - }while (false); - - if (descriptor == nullptr){ - descriptor.reset(new NullControllerDescriptor()); - } - - m_descriptor = std::move(descriptor); -} -JsonValue ControllerOption::to_json() const{ - if (!m_descriptor){ - return JsonValue(); - } - JsonObject obj; - obj["Interface"] = CONTROLLER_INTERFACE_STRINGS.get_string(m_descriptor->interface_type); - - for (const auto& item : m_descriptor_cache){ - obj[CONTROLLER_INTERFACE_STRINGS.get_string(item.first)] = item.second->to_json(); - } - - return obj; -} - - - - - - - - - -} +/* Controller Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "ControllerTypeStrings.h" +#include "ControllerDescriptor.h" +#include "NullController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +// +// Here we store a map of all controller types in the program. +// +std::map> ALL_CONTROLLER_INTERFACES; + + +void InterfaceType::register_factory( + ControllerInterface controller_interface, + std::unique_ptr factory +){ + auto ret = ALL_CONTROLLER_INTERFACES.emplace(controller_interface, std::move(factory)); + if (!ret.second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Duplicate Factory Name: " + CONTROLLER_INTERFACE_STRINGS.get_string(controller_interface) + ); + } +} + + + + +ControllerOption::ControllerOption() + : m_descriptor(new NullControllerDescriptor()) +{} + + +void ControllerOption::set_descriptor(std::shared_ptr descriptor){ + m_descriptor_cache[descriptor->interface_type] = descriptor; + m_descriptor = std::move(descriptor); +} + +std::shared_ptr ControllerOption::get_descriptor_from_cache(ControllerInterface interface_type) const{ + auto iter = m_descriptor_cache.find(interface_type); + if (iter == m_descriptor_cache.end()){ + return nullptr; + } + return iter->second; +} + + + +void ControllerOption::load_json(const JsonValue& json){ + std::shared_ptr descriptor; + do{ + if (json.is_null()){ + break; + } + + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + break; + } + const std::string* type = obj->get_string("Interface"); + if (type == nullptr){ + break; + } + + for (const auto& item : ALL_CONTROLLER_INTERFACES){ + const JsonValue* params = obj->get_value(CONTROLLER_INTERFACE_STRINGS.get_string(item.first)); + if (params == nullptr){ + continue; + } + m_descriptor_cache[item.first] = item.second->make(*params); + } + + auto iter = m_descriptor_cache.find(CONTROLLER_INTERFACE_STRINGS.get_enum(*type, ControllerInterface::None)); + if (iter == m_descriptor_cache.end()){ + break; + } + + descriptor = iter->second; + }while (false); + + if (descriptor == nullptr){ + descriptor.reset(new NullControllerDescriptor()); + } + + m_descriptor = std::move(descriptor); +} +JsonValue ControllerOption::to_json() const{ + if (!m_descriptor){ + return JsonValue(); + } + JsonObject obj; + obj["Interface"] = CONTROLLER_INTERFACE_STRINGS.get_string(m_descriptor->interface_type); + + for (const auto& item : m_descriptor_cache){ + obj[CONTROLLER_INTERFACE_STRINGS.get_string(item.first)] = item.second->to_json(); + } + + return obj; +} + + + + + + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerDescriptor.h b/SerialPrograms/Source/Controllers/ControllerDescriptor.h index 497572e7b5..8fcbb64ed5 100644 --- a/SerialPrograms/Source/Controllers/ControllerDescriptor.h +++ b/SerialPrograms/Source/Controllers/ControllerDescriptor.h @@ -1,162 +1,162 @@ -/* Controller Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerDescriptor_H -#define PokemonAutomation_Controllers_ControllerDescriptor_H - -#include -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -//#include "Common/Cpp/Json/JsonObject.h" -#include "ControllerCapability.h" -#include "Controller.h" - -class QWidget; - -namespace PokemonAutomation{ - -class JsonValue; -class InterfaceType; -class ControllerDescriptor; -class ControllerConnection; -class ControllerSelectorWidget; - - -// -// Represents an entire controller interface. -// -// For example: -// - Serial PABotBase -// - Direct USB to X (hypothetical) -// - Emulator IPC (hypothetical) -// -// One instance of this class exists for each interface. -// -class InterfaceType{ -public: - virtual ~InterfaceType() = default; - - // Construct a descriptor from a JSON config. (reloading saved controller settings) - virtual std::unique_ptr make(const JsonValue& json) const = 0; - -protected: - static void register_factory( - ControllerInterface controller_interface, - std::unique_ptr factory - ); -}; - - -// -// Subclass helper for ControllerType. -// -template -class InterfaceType_t : public InterfaceType{ -public: - virtual std::unique_ptr make(const JsonValue& json) const override{ - std::unique_ptr ptr(new DescriptorType()); - ptr->load_json(json); - return ptr; - } - -private: - static int register_class(){ - InterfaceType::register_factory( - DescriptorType::INTERFACE_NAME, - std::make_unique>() - ); - return 0; - } - static int initializer; -}; -template -int InterfaceType_t::initializer = register_class(); - - - - -// -// Represents a user-selectable controller. When the user clicks on the -// "Controller" dropdown, every item in that list corresponds to an instance -// of this class. -// -class ControllerDescriptor{ -public: - const ControllerInterface interface_type; - - ControllerDescriptor(ControllerInterface p_interface_type) - : interface_type(p_interface_type) - {} - virtual ~ControllerDescriptor() = default; - -public: - virtual bool operator==(const ControllerDescriptor& x) const = 0; - virtual std::string display_name() const = 0; - -public: - virtual void load_json(const JsonValue& json) = 0; - virtual JsonValue to_json() const = 0; - -public: - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const = 0; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const = 0; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const = 0; -}; - - - - - - - - -// -// A configurable option type for the descriptor. -// -class ControllerOption{ -public: - ControllerOption(); - - std::shared_ptr descriptor() const{ - return m_descriptor; - } - void set_descriptor(std::shared_ptr descriptor); - - // Remember the last used descriptor for each interface type. That way when - // the user switches back-and-forth between two interfaces, it will reload - // the previous one. - std::shared_ptr get_descriptor_from_cache(ControllerInterface interface_type) const; - - -public: - void load_json(const JsonValue& json); - JsonValue to_json() const; - - -private: - std::shared_ptr m_descriptor; - std::map> m_descriptor_cache; -}; - - - - - - - - -} -#endif +/* Controller Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerDescriptor_H +#define PokemonAutomation_Controllers_ControllerDescriptor_H + +#include +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +//#include "Common/Cpp/Json/JsonObject.h" +#include "ControllerCapability.h" +#include "Controller.h" + +class QWidget; + +namespace PokemonAutomation{ + +class JsonValue; +class InterfaceType; +class ControllerDescriptor; +class ControllerConnection; +class ControllerSelectorWidget; + + +// +// Represents an entire controller interface. +// +// For example: +// - Serial PABotBase +// - Direct USB to X (hypothetical) +// - Emulator IPC (hypothetical) +// +// One instance of this class exists for each interface. +// +class InterfaceType{ +public: + virtual ~InterfaceType() = default; + + // Construct a descriptor from a JSON config. (reloading saved controller settings) + virtual std::unique_ptr make(const JsonValue& json) const = 0; + +protected: + static void register_factory( + ControllerInterface controller_interface, + std::unique_ptr factory + ); +}; + + +// +// Subclass helper for ControllerType. +// +template +class InterfaceType_t : public InterfaceType{ +public: + virtual std::unique_ptr make(const JsonValue& json) const override{ + std::unique_ptr ptr(new DescriptorType()); + ptr->load_json(json); + return ptr; + } + +private: + static int register_class(){ + InterfaceType::register_factory( + DescriptorType::INTERFACE_NAME, + std::make_unique>() + ); + return 0; + } + static int initializer; +}; +template +int InterfaceType_t::initializer = register_class(); + + + + +// +// Represents a user-selectable controller. When the user clicks on the +// "Controller" dropdown, every item in that list corresponds to an instance +// of this class. +// +class ControllerDescriptor{ +public: + const ControllerInterface interface_type; + + ControllerDescriptor(ControllerInterface p_interface_type) + : interface_type(p_interface_type) + {} + virtual ~ControllerDescriptor() = default; + +public: + virtual bool operator==(const ControllerDescriptor& x) const = 0; + virtual std::string display_name() const = 0; + +public: + virtual void load_json(const JsonValue& json) = 0; + virtual JsonValue to_json() const = 0; + +public: + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const = 0; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const = 0; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const = 0; +}; + + + + + + + + +// +// A configurable option type for the descriptor. +// +class ControllerOption{ +public: + ControllerOption(); + + std::shared_ptr descriptor() const{ + return m_descriptor; + } + void set_descriptor(std::shared_ptr descriptor); + + // Remember the last used descriptor for each interface type. That way when + // the user switches back-and-forth between two interfaces, it will reload + // the previous one. + std::shared_ptr get_descriptor_from_cache(ControllerInterface interface_type) const; + + +public: + void load_json(const JsonValue& json); + JsonValue to_json() const; + + +private: + std::shared_ptr m_descriptor; + std::map> m_descriptor_cache; +}; + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp index 6800886a75..54dc01365a 100644 --- a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp +++ b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.cpp @@ -1,216 +1,216 @@ -/* Controller Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Controllers/ControllerTypeStrings.h" -#include "ControllerSelectorWidget.h" - -#include "SerialPABotBase/SerialPABotBase_SelectorWidget.h" -#include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - - - -ControllerSelectorWidget::~ControllerSelectorWidget(){ - m_session.remove_listener(*this); -} -ControllerSelectorWidget::ControllerSelectorWidget(QWidget& parent, ControllerSession& session) - : QWidget(&parent) - , m_session(session) -{ - QHBoxLayout* serial_row = new QHBoxLayout(this); - serial_row->setContentsMargins(0, 0, 0, 0); - - serial_row->addWidget(new QLabel("Controller:", this), 1); - serial_row->addSpacing(5); - - m_dropdowns = new QHBoxLayout(); - serial_row->addLayout(m_dropdowns, 5); - serial_row->addSpacing(5); - - interface_dropdown = new NoWheelComboBox(this); - m_dropdowns->addWidget(interface_dropdown, 2); - - interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::SerialPABotBase))); - interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::TcpSysbotBase))); -// interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::UsbSysbotBase))); - -// interface_dropdown->setHidden(true); - - auto current = session.descriptor(); - if (current == nullptr || current->interface_type == ControllerInterface::None){ - current.reset(new SerialPABotBase::SerialPABotBase_Descriptor()); - session.set_device(std::move(current)); - } - interface_dropdown->setCurrentIndex((int)current->interface_type - 1); - m_selector = current->make_selector_QtWidget(*this); - m_dropdowns->addWidget(m_selector); - - - m_dropdowns->addSpacing(5); - m_controllers_dropdown = new NoWheelComboBox(this); - m_dropdowns->addWidget(m_controllers_dropdown, 3); - refresh_controllers(session.controller_type(), session.available_controllers()); - - m_status_text = new QLabel(this); - serial_row->addWidget(m_status_text, 3); - serial_row->addSpacing(5); - - m_status_text->setText(QString::fromStdString(session.status_text())); - - m_reset_button = new QPushButton("Reset Ctrl.", this); - serial_row->addWidget(m_reset_button, 1); - - bool options_locked = session.options_locked(); - if (m_selector){ - m_selector->setEnabled(!options_locked); - } - m_reset_button->setEnabled(!options_locked); - - connect( - interface_dropdown, static_cast(&QComboBox::activated), - this, [this](int index){ - index = std::max(index, 0); -// index = std::min(index, (int)m_device_list.size() - 1); - - ControllerInterface incoming = (ControllerInterface)(index + 1); - ControllerInterface existing = m_session.descriptor()->interface_type; -// cout << "incoming = " << (int)incoming << endl; -// cout << "existing = " << (int)existing << endl; - if (incoming == existing){ - return; - } - - refresh_selection(incoming); - } - ); - connect( - m_controllers_dropdown, static_cast(&QComboBox::activated), - this, [this](int index){ - index = std::max(index, 0); - ControllerType new_value = CONTROLLER_TYPE_STRINGS.get_enum( - m_controllers_dropdown->itemText(index).toStdString(), - ControllerType::None - ); - if (new_value == m_session.controller_type()){ - return; - } - m_session.set_controller(new_value); - } - ); - connect( - m_reset_button, &QPushButton::clicked, - this, [this](bool){ - m_session.reset(); - } - ); - - session.add_listener(*this); -} - - - - -void ControllerSelectorWidget::refresh_selection(ControllerInterface interface_type){ -// cout << "refresh_selection(): "<< endl; - - if (interface_type == ControllerInterface::None){ - interface_type = ControllerInterface::SerialPABotBase; - } - interface_dropdown->setCurrentIndex((int)interface_type - 1); - - delete m_selector; - m_selector = nullptr; - -// m_status_text->setText(QString::fromStdString(html_color_text("Not Connected", COLOR_RED))); - - switch (interface_type){ - case ControllerInterface::SerialPABotBase: - m_selector = new SerialPABotBase::SerialPABotBase_SelectorWidget(*this, m_session.descriptor().get()); - m_dropdowns->insertWidget(1, m_selector); - break; - - case ControllerInterface::TcpSysbotBase: - m_selector = new SysbotBase::TcpSysbotBase_SelectorWidget(*this, m_session.descriptor().get()); - m_dropdowns->insertWidget(1, m_selector); - break; - - default:; - } - - -} - -void ControllerSelectorWidget::refresh_controllers( - ControllerType controller_type, - const std::vector& available_controllers -){ - if (m_controllers_dropdown == nullptr){ - return; - } -// cout << "refresh_controllers()" << endl; - - m_controllers_dropdown->clear(); - - size_t index = 0; - for (size_t c = 0; c < available_controllers.size(); c++){ - const std::string& name = CONTROLLER_TYPE_STRINGS.get_string(available_controllers[c]); - m_controllers_dropdown->addItem(QString::fromStdString(name)); - if (controller_type == available_controllers[c]){ - index = c; - } - } - m_controllers_dropdown->setCurrentIndex((int)index); -} - - - -void ControllerSelectorWidget::descriptor_changed( - const std::shared_ptr& descriptor -){ -// cout << "descriptor_changed()" << endl; - QMetaObject::invokeMethod(this, [=, this]{ - refresh_selection(descriptor->interface_type); - refresh_controllers(ControllerType::None, {}); - }, Qt::QueuedConnection); -} -void ControllerSelectorWidget::controller_changed( - ControllerType controller_type, - const std::vector& available_controllers -){ -// cout << "ControllerSelectorWidget::controller_changed()" << endl; - QMetaObject::invokeMethod(this, [=, this]{ - refresh_controllers(controller_type, available_controllers); - }, Qt::QueuedConnection); -} -void ControllerSelectorWidget::post_status_text_changed(const std::string& text){ -// cout << "ControllerSelectorWidget::status_text_changed(): " << text << endl; - QMetaObject::invokeMethod(this, [this, text]{ - m_status_text->setText(QString::fromStdString(text)); - }); -} -void ControllerSelectorWidget::options_locked(bool locked){ - QMetaObject::invokeMethod(this, [this, locked]{ - m_selector->setEnabled(!locked); - interface_dropdown->setEnabled(!locked); - m_controllers_dropdown->setEnabled(!locked); - m_reset_button->setEnabled(!locked); - }); -} - - - - - -} +/* Controller Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Controllers/ControllerTypeStrings.h" +#include "ControllerSelectorWidget.h" + +#include "SerialPABotBase/SerialPABotBase_SelectorWidget.h" +#include "NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + + + +ControllerSelectorWidget::~ControllerSelectorWidget(){ + m_session.remove_listener(*this); +} +ControllerSelectorWidget::ControllerSelectorWidget(QWidget& parent, ControllerSession& session) + : QWidget(&parent) + , m_session(session) +{ + QHBoxLayout* serial_row = new QHBoxLayout(this); + serial_row->setContentsMargins(0, 0, 0, 0); + + serial_row->addWidget(new QLabel("Controller:", this), 1); + serial_row->addSpacing(5); + + m_dropdowns = new QHBoxLayout(); + serial_row->addLayout(m_dropdowns, 5); + serial_row->addSpacing(5); + + interface_dropdown = new NoWheelComboBox(this); + m_dropdowns->addWidget(interface_dropdown, 2); + + interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::SerialPABotBase))); + interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::TcpSysbotBase))); +// interface_dropdown->addItem(QString::fromStdString(CONTROLLER_INTERFACE_STRINGS.get_string(ControllerInterface::UsbSysbotBase))); + +// interface_dropdown->setHidden(true); + + auto current = session.descriptor(); + if (current == nullptr || current->interface_type == ControllerInterface::None){ + current.reset(new SerialPABotBase::SerialPABotBase_Descriptor()); + session.set_device(std::move(current)); + } + interface_dropdown->setCurrentIndex((int)current->interface_type - 1); + m_selector = current->make_selector_QtWidget(*this); + m_dropdowns->addWidget(m_selector); + + + m_dropdowns->addSpacing(5); + m_controllers_dropdown = new NoWheelComboBox(this); + m_dropdowns->addWidget(m_controllers_dropdown, 3); + refresh_controllers(session.controller_type(), session.available_controllers()); + + m_status_text = new QLabel(this); + serial_row->addWidget(m_status_text, 3); + serial_row->addSpacing(5); + + m_status_text->setText(QString::fromStdString(session.status_text())); + + m_reset_button = new QPushButton("Reset Ctrl.", this); + serial_row->addWidget(m_reset_button, 1); + + bool options_locked = session.options_locked(); + if (m_selector){ + m_selector->setEnabled(!options_locked); + } + m_reset_button->setEnabled(!options_locked); + + connect( + interface_dropdown, static_cast(&QComboBox::activated), + this, [this](int index){ + index = std::max(index, 0); +// index = std::min(index, (int)m_device_list.size() - 1); + + ControllerInterface incoming = (ControllerInterface)(index + 1); + ControllerInterface existing = m_session.descriptor()->interface_type; +// cout << "incoming = " << (int)incoming << endl; +// cout << "existing = " << (int)existing << endl; + if (incoming == existing){ + return; + } + + refresh_selection(incoming); + } + ); + connect( + m_controllers_dropdown, static_cast(&QComboBox::activated), + this, [this](int index){ + index = std::max(index, 0); + ControllerType new_value = CONTROLLER_TYPE_STRINGS.get_enum( + m_controllers_dropdown->itemText(index).toStdString(), + ControllerType::None + ); + if (new_value == m_session.controller_type()){ + return; + } + m_session.set_controller(new_value); + } + ); + connect( + m_reset_button, &QPushButton::clicked, + this, [this](bool){ + m_session.reset(); + } + ); + + session.add_listener(*this); +} + + + + +void ControllerSelectorWidget::refresh_selection(ControllerInterface interface_type){ +// cout << "refresh_selection(): "<< endl; + + if (interface_type == ControllerInterface::None){ + interface_type = ControllerInterface::SerialPABotBase; + } + interface_dropdown->setCurrentIndex((int)interface_type - 1); + + delete m_selector; + m_selector = nullptr; + +// m_status_text->setText(QString::fromStdString(html_color_text("Not Connected", COLOR_RED))); + + switch (interface_type){ + case ControllerInterface::SerialPABotBase: + m_selector = new SerialPABotBase::SerialPABotBase_SelectorWidget(*this, m_session.descriptor().get()); + m_dropdowns->insertWidget(1, m_selector); + break; + + case ControllerInterface::TcpSysbotBase: + m_selector = new SysbotBase::TcpSysbotBase_SelectorWidget(*this, m_session.descriptor().get()); + m_dropdowns->insertWidget(1, m_selector); + break; + + default:; + } + + +} + +void ControllerSelectorWidget::refresh_controllers( + ControllerType controller_type, + const std::vector& available_controllers +){ + if (m_controllers_dropdown == nullptr){ + return; + } +// cout << "refresh_controllers()" << endl; + + m_controllers_dropdown->clear(); + + size_t index = 0; + for (size_t c = 0; c < available_controllers.size(); c++){ + const std::string& name = CONTROLLER_TYPE_STRINGS.get_string(available_controllers[c]); + m_controllers_dropdown->addItem(QString::fromStdString(name)); + if (controller_type == available_controllers[c]){ + index = c; + } + } + m_controllers_dropdown->setCurrentIndex((int)index); +} + + + +void ControllerSelectorWidget::descriptor_changed( + const std::shared_ptr& descriptor +){ +// cout << "descriptor_changed()" << endl; + QMetaObject::invokeMethod(this, [=, this]{ + refresh_selection(descriptor->interface_type); + refresh_controllers(ControllerType::None, {}); + }, Qt::QueuedConnection); +} +void ControllerSelectorWidget::controller_changed( + ControllerType controller_type, + const std::vector& available_controllers +){ +// cout << "ControllerSelectorWidget::controller_changed()" << endl; + QMetaObject::invokeMethod(this, [=, this]{ + refresh_controllers(controller_type, available_controllers); + }, Qt::QueuedConnection); +} +void ControllerSelectorWidget::post_status_text_changed(const std::string& text){ +// cout << "ControllerSelectorWidget::status_text_changed(): " << text << endl; + QMetaObject::invokeMethod(this, [this, text]{ + m_status_text->setText(QString::fromStdString(text)); + }); +} +void ControllerSelectorWidget::options_locked(bool locked){ + QMetaObject::invokeMethod(this, [this, locked]{ + m_selector->setEnabled(!locked); + interface_dropdown->setEnabled(!locked); + m_controllers_dropdown->setEnabled(!locked); + m_reset_button->setEnabled(!locked); + }); +} + + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h index d062d44f2c..8534eca212 100644 --- a/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h +++ b/SerialPrograms/Source/Controllers/ControllerSelectorWidget.h @@ -1,64 +1,64 @@ -/* Controller Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerWidget_H -#define PokemonAutomation_Controllers_ControllerWidget_H - -#include -#include -#include -#include -#include -#include "ControllerSession.h" - -namespace PokemonAutomation{ - - - - -class ControllerSelectorWidget : public QWidget, private ControllerSession::Listener{ -public: - ~ControllerSelectorWidget(); - ControllerSelectorWidget(QWidget& parent, ControllerSession& session); - - ControllerSession& session(){ - return m_session; - } - -public: - virtual void descriptor_changed( - const std::shared_ptr& descriptor - ) override; - virtual void controller_changed( - ControllerType controller_type, - const std::vector& available_controllers - ) override; - virtual void post_status_text_changed(const std::string& text) override; - virtual void options_locked(bool locked) override; - -private: - void refresh_selection(ControllerInterface interface_type); - void refresh_controllers( - ControllerType controller_type, - const std::vector& available_controllers - ); - -private: - ControllerSession& m_session; - - QHBoxLayout* m_dropdowns; - QWidget* m_selector = nullptr; - QComboBox* interface_dropdown = nullptr; - QComboBox* m_controllers_dropdown = nullptr; - QLabel* m_status_text = nullptr; - QPushButton* m_reset_button = nullptr; - - std::vector> m_device_list; -}; - - -} -#endif +/* Controller Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerWidget_H +#define PokemonAutomation_Controllers_ControllerWidget_H + +#include +#include +#include +#include +#include +#include "ControllerSession.h" + +namespace PokemonAutomation{ + + + + +class ControllerSelectorWidget : public QWidget, private ControllerSession::Listener{ +public: + ~ControllerSelectorWidget(); + ControllerSelectorWidget(QWidget& parent, ControllerSession& session); + + ControllerSession& session(){ + return m_session; + } + +public: + virtual void descriptor_changed( + const std::shared_ptr& descriptor + ) override; + virtual void controller_changed( + ControllerType controller_type, + const std::vector& available_controllers + ) override; + virtual void post_status_text_changed(const std::string& text) override; + virtual void options_locked(bool locked) override; + +private: + void refresh_selection(ControllerInterface interface_type); + void refresh_controllers( + ControllerType controller_type, + const std::vector& available_controllers + ); + +private: + ControllerSession& m_session; + + QHBoxLayout* m_dropdowns; + QWidget* m_selector = nullptr; + QComboBox* interface_dropdown = nullptr; + QComboBox* m_controllers_dropdown = nullptr; + QLabel* m_status_text = nullptr; + QPushButton* m_reset_button = nullptr; + + std::vector> m_device_list; +}; + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerSession.cpp b/SerialPrograms/Source/Controllers/ControllerSession.cpp index 20ee18f964..459fc311b3 100644 --- a/SerialPrograms/Source/Controllers/ControllerSession.cpp +++ b/SerialPrograms/Source/Controllers/ControllerSession.cpp @@ -1,436 +1,436 @@ -/* Controller Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ControllerSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -void ControllerSession::add_listener(Listener& listener){ - std::lock_guard lg(m_state_lock); - m_listeners.add(listener); -// if (m_connection && m_connection->is_ready()){ -// signal_controller_changed(m_option.m_controller_type, m_available_controllers); -// } -} -void ControllerSession::remove_listener(Listener& listener){ - std::lock_guard lg(m_state_lock); - m_listeners.remove(listener); -} - - - -ControllerSession::~ControllerSession(){ - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg(m_state_lock); - controller = std::move(m_controller); - connection = std::move(m_connection); - } - controller.reset(); - connection.reset(); -} -ControllerSession::ControllerSession( - Logger& logger, - ControllerOption& option, - const ControllerFeatures& required_features -) - : m_logger(logger) - , m_required_features(required_features) - , m_option(option) - , m_controller_type(ControllerType::None) - , m_options_locked(false) - , m_descriptor(option.descriptor()) - , m_connection(m_descriptor->open_connection(logger, {})) -{ - if (!m_connection){ - return; - } - - // Add listener first so we don't miss the ready signal. - m_connection->add_status_listener(*this); - try{ - // If we already missed it, run it ourselves. - if (m_connection->is_ready()){ - ControllerSession::post_connection_ready( - *m_connection, - m_connection->controller_mode_status() - ); - } - }catch (...){ - m_connection->remove_status_listener(*this); - throw; - } -} - - -std::vector ControllerSession::available_controllers() const{ - std::lock_guard lg(m_state_lock); - return m_available_controllers; -} - -void ControllerSession::get(ControllerOption& option){ - std::lock_guard lg(m_state_lock); - option = m_option; -} -void ControllerSession::set(const ControllerOption& option){ - set_device(option.descriptor()); -} - - - -bool ControllerSession::ready() const{ - std::lock_guard lg(m_state_lock); - if (!m_controller){ - return false; - } - return m_controller->is_ready(); -} -std::shared_ptr ControllerSession::descriptor() const{ - std::lock_guard lg(m_state_lock); - return m_descriptor; -} -ControllerType ControllerSession::controller_type() const{ - std::lock_guard lg(m_state_lock); - return m_controller_type; -} -std::string ControllerSession::status_text() const{ - std::lock_guard lg(m_state_lock); - if (!m_connection){ - return "No controller selected."; - } - return m_connection->status_text(); -} -ControllerConnection& ControllerSession::connection() const{ - if (m_connection){ - return *m_connection; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Connection is null."); -} -AbstractController* ControllerSession::controller() const{ - return m_controller.get(); -} - - - - -std::string ControllerSession::user_input_blocked() const{ - std::lock_guard lg(m_state_lock); - if (!m_connection){ - return "No controller selected."; - } - if (!m_connection->is_ready()){ - return "Connection is not ready."; - } - if (!m_controller->is_ready()){ - return "Controller is not ready."; - } - return m_user_input_disallow_reason; -} -void ControllerSession::set_user_input_blocked(std::string disallow_reason){ - std::lock_guard lg(m_state_lock); -// cout << "set_user_input_blocked() = " << disallow_reason << endl; - m_user_input_disallow_reason = std::move(disallow_reason); -} - -bool ControllerSession::options_locked() const{ - std::lock_guard lg(m_state_lock); - return m_options_locked; -} -void ControllerSession::set_options_locked(bool locked){ - bool original_value; - { - std::lock_guard lg(m_state_lock); - original_value = m_options_locked; - m_options_locked = locked; - } - if (original_value != locked){ - signal_options_locked(locked); - } -} - - -void ControllerSession::make_controller(std::optional change_controller){ - // Must be called under "m_reset_lock". - - bool ready = false; - { - std::lock_guard lg(m_state_lock); - m_connection = m_descriptor->open_connection(m_logger, change_controller); - if (m_connection){ - m_connection->add_status_listener(*this); - ready = m_connection->is_ready(); - } - } - - // If we already missed it, run it ourselves. - if (ready){ - ControllerSession::post_connection_ready( - *m_connection, - m_connection->controller_mode_status() - ); - } - - signal_descriptor_changed(m_descriptor); -} - - - -bool ControllerSession::set_device(const std::shared_ptr& device){ -// cout << "set_device() = " << device->display_name() << endl; - { - std::lock_guard lg0(m_reset_lock); - - // Destroy the current connection+controller. - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg1(m_state_lock); - if (m_options_locked){ - return false; - } - if (*m_descriptor == *device){ - return true; - } - - // Move these out to indicate that we should no longer access them. - controller = std::move(m_controller); - connection = std::move(m_connection); - -// cout << "setting..." << endl; - m_option.set_descriptor(device); - m_descriptor = device; - } - - // With the lock released, it is now safe to destroy them. - // We cannot destroy these under (m_state_lock) due to their asynchronous - // callbacks into this class which will also acquire the same lock. - controller.reset(); - connection.reset(); - - make_controller({}); - } - signal_descriptor_changed(device); - signal_status_text_changed(status_text()); - return true; -} -bool ControllerSession::set_controller(ControllerType controller_type){ -// cout << "set_controller()" << endl; - std::shared_ptr device; - { - std::lock_guard lg0(m_reset_lock); - - // Destroy the current connection+controller. - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg1(m_state_lock); - if (m_options_locked){ - return false; - } - if (m_controller_type == controller_type){ - return true; - } - - // Move these out to indicate that we should no longer access them. - controller = std::move(m_controller); - connection = std::move(m_connection); - - m_controller_type = controller_type; - } - - // With the lock released, it is now safe to destroy them. - // We cannot destroy these under (m_state_lock) due to their asynchronous - // callbacks into this class which will also acquire the same lock. - controller.reset(); - connection.reset(); - - make_controller(controller_type); - device = m_descriptor; - } - signal_descriptor_changed(device); - signal_status_text_changed(status_text()); - return true; -} - - - -std::string ControllerSession::reset(){ -// cout << "ControllerSession::reset()" << endl; - - { - std::lock_guard lg0(m_reset_lock); - - // Destroy the current connection+controller. - std::unique_ptr controller; - std::unique_ptr connection; - { - std::lock_guard lg1(m_state_lock); - if (m_options_locked){ - return "Options are locked."; - } -// if (!m_connection){ -// cout << "ControllerSession::reset() - early return" << endl; -// return "No connection set."; -// } - - // Move these out to indicate that we should no longer access them. - controller = std::move(m_controller); - connection = std::move(m_connection); - } - - // With the lock released, it is now safe to destroy them. - // We cannot destroy these under (m_state_lock) due to their asynchronous - // callbacks into this class which will also acquire the same lock. - controller.reset(); - connection.reset(); - - make_controller(m_controller_type); - } - signal_status_text_changed(status_text()); - return ""; -} - - -//void ControllerSession::pre_connection_not_ready(ControllerConnection& connection){ -// m_listeners.run_method_unique(&Listener::pre_connection_not_ready, connection); -//} -void ControllerSession::post_connection_ready( - ControllerConnection& connection, - const ControllerModeStatus& mode_status -){ - const std::map& supported_controllers = mode_status.supported_controllers; - if (supported_controllers.empty()){ - return; - } - - ControllerType current_controller = mode_status.current_controller; - -// cout << "sleeping" << endl; -// Sleep(10000); - - - std::vector available_controllers; -// ControllerType selected_controller = ControllerType::None; - bool ready; - { - std::lock_guard lg(m_state_lock); - - // Connection has already been closed. - if (m_connection == nullptr){ - return; - } - - // Controller already constructed. - if (m_controller){ - return; - } - - // We only show the "none" option when there are multiple controllers - // to choose from. - if (supported_controllers.size() > 1){ - available_controllers.emplace_back(ControllerType::None); - } - for (const auto& item : supported_controllers){ - available_controllers.emplace_back(item.first); - } - - // Copy the list. One will be moved into "m_available_controllers". - // The other will be stored locally for the callbacks. - m_available_controllers = available_controllers; - - -#if 0 - auto iter = supported_controllers.begin(); - if (supported_controllers.size() == 1){ - // Only one controller available. Force the option to it. - current_controller = iter->first; - }else{ - // Keep the current controller only if it exists. - iter = supported_controllers.find(m_option.m_controller_type); - if (iter != supported_controllers.end()){ - current_controller = m_option.m_controller_type; - } - } -#endif - - // Construct the controller. - if (current_controller != ControllerType::None){ - m_controller = m_descriptor->make_controller( - m_logger, - *m_connection, - current_controller - ); - } - - // Commit all changes. -// cout << "current_controller = " << CONTROLLER_TYPE_STRINGS.get_string(current_controller) << endl; - m_controller_type = current_controller; - ready = m_controller && m_controller->is_ready(); - } - - signal_controller_changed(current_controller, available_controllers); - signal_ready_changed(ready); - signal_status_text_changed(status_text()); -} -void ControllerSession::status_text_changed( - ControllerConnection& connection, - const std::string& text -){ -// cout << "ControllerSession::status_text_changed() = " << text << endl; - std::string controller_error; - { - WriteSpinLock lg(m_message_lock); - controller_error = m_controller_error; - } -// cout << "ControllerSession::status_text_changed(): controller_error = " << controller_error << endl; - if (controller_error.empty()){ - m_listeners.run_method_unique(&Listener::post_status_text_changed, text); - }else{ - m_listeners.run_method_unique(&Listener::post_status_text_changed, controller_error); - } -} -void ControllerSession::on_error( - ControllerConnection& connection, - const std::string& text -){ - WriteSpinLock lg(m_message_lock); - m_controller_error = text; -} - - - - -void ControllerSession::signal_ready_changed(bool ready){ - m_listeners.run_method_unique(&Listener::ready_changed, ready); -} -void ControllerSession::signal_descriptor_changed( - const std::shared_ptr& descriptor -){ - m_listeners.run_method_unique(&Listener::descriptor_changed, descriptor); -} -void ControllerSession::signal_controller_changed( - ControllerType controller_type, - const std::vector& available_controllers -){ - m_listeners.run_method_unique(&Listener::controller_changed, controller_type, available_controllers); -} -void ControllerSession::signal_status_text_changed(const std::string& text){ -// cout << text << endl; - m_listeners.run_method_unique(&Listener::post_status_text_changed, text); -} -void ControllerSession::signal_options_locked(bool locked){ - m_listeners.run_method_unique(&Listener::options_locked, locked); -} - - -} +/* Controller Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ControllerSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +void ControllerSession::add_listener(Listener& listener){ + std::lock_guard lg(m_state_lock); + m_listeners.add(listener); +// if (m_connection && m_connection->is_ready()){ +// signal_controller_changed(m_option.m_controller_type, m_available_controllers); +// } +} +void ControllerSession::remove_listener(Listener& listener){ + std::lock_guard lg(m_state_lock); + m_listeners.remove(listener); +} + + + +ControllerSession::~ControllerSession(){ + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg(m_state_lock); + controller = std::move(m_controller); + connection = std::move(m_connection); + } + controller.reset(); + connection.reset(); +} +ControllerSession::ControllerSession( + Logger& logger, + ControllerOption& option, + const ControllerFeatures& required_features +) + : m_logger(logger) + , m_required_features(required_features) + , m_option(option) + , m_controller_type(ControllerType::None) + , m_options_locked(false) + , m_descriptor(option.descriptor()) + , m_connection(m_descriptor->open_connection(logger, {})) +{ + if (!m_connection){ + return; + } + + // Add listener first so we don't miss the ready signal. + m_connection->add_status_listener(*this); + try{ + // If we already missed it, run it ourselves. + if (m_connection->is_ready()){ + ControllerSession::post_connection_ready( + *m_connection, + m_connection->controller_mode_status() + ); + } + }catch (...){ + m_connection->remove_status_listener(*this); + throw; + } +} + + +std::vector ControllerSession::available_controllers() const{ + std::lock_guard lg(m_state_lock); + return m_available_controllers; +} + +void ControllerSession::get(ControllerOption& option){ + std::lock_guard lg(m_state_lock); + option = m_option; +} +void ControllerSession::set(const ControllerOption& option){ + set_device(option.descriptor()); +} + + + +bool ControllerSession::ready() const{ + std::lock_guard lg(m_state_lock); + if (!m_controller){ + return false; + } + return m_controller->is_ready(); +} +std::shared_ptr ControllerSession::descriptor() const{ + std::lock_guard lg(m_state_lock); + return m_descriptor; +} +ControllerType ControllerSession::controller_type() const{ + std::lock_guard lg(m_state_lock); + return m_controller_type; +} +std::string ControllerSession::status_text() const{ + std::lock_guard lg(m_state_lock); + if (!m_connection){ + return "No controller selected."; + } + return m_connection->status_text(); +} +ControllerConnection& ControllerSession::connection() const{ + if (m_connection){ + return *m_connection; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Connection is null."); +} +AbstractController* ControllerSession::controller() const{ + return m_controller.get(); +} + + + + +std::string ControllerSession::user_input_blocked() const{ + std::lock_guard lg(m_state_lock); + if (!m_connection){ + return "No controller selected."; + } + if (!m_connection->is_ready()){ + return "Connection is not ready."; + } + if (!m_controller->is_ready()){ + return "Controller is not ready."; + } + return m_user_input_disallow_reason; +} +void ControllerSession::set_user_input_blocked(std::string disallow_reason){ + std::lock_guard lg(m_state_lock); +// cout << "set_user_input_blocked() = " << disallow_reason << endl; + m_user_input_disallow_reason = std::move(disallow_reason); +} + +bool ControllerSession::options_locked() const{ + std::lock_guard lg(m_state_lock); + return m_options_locked; +} +void ControllerSession::set_options_locked(bool locked){ + bool original_value; + { + std::lock_guard lg(m_state_lock); + original_value = m_options_locked; + m_options_locked = locked; + } + if (original_value != locked){ + signal_options_locked(locked); + } +} + + +void ControllerSession::make_controller(std::optional change_controller){ + // Must be called under "m_reset_lock". + + bool ready = false; + { + std::lock_guard lg(m_state_lock); + m_connection = m_descriptor->open_connection(m_logger, change_controller); + if (m_connection){ + m_connection->add_status_listener(*this); + ready = m_connection->is_ready(); + } + } + + // If we already missed it, run it ourselves. + if (ready){ + ControllerSession::post_connection_ready( + *m_connection, + m_connection->controller_mode_status() + ); + } + + signal_descriptor_changed(m_descriptor); +} + + + +bool ControllerSession::set_device(const std::shared_ptr& device){ +// cout << "set_device() = " << device->display_name() << endl; + { + std::lock_guard lg0(m_reset_lock); + + // Destroy the current connection+controller. + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg1(m_state_lock); + if (m_options_locked){ + return false; + } + if (*m_descriptor == *device){ + return true; + } + + // Move these out to indicate that we should no longer access them. + controller = std::move(m_controller); + connection = std::move(m_connection); + +// cout << "setting..." << endl; + m_option.set_descriptor(device); + m_descriptor = device; + } + + // With the lock released, it is now safe to destroy them. + // We cannot destroy these under (m_state_lock) due to their asynchronous + // callbacks into this class which will also acquire the same lock. + controller.reset(); + connection.reset(); + + make_controller({}); + } + signal_descriptor_changed(device); + signal_status_text_changed(status_text()); + return true; +} +bool ControllerSession::set_controller(ControllerType controller_type){ +// cout << "set_controller()" << endl; + std::shared_ptr device; + { + std::lock_guard lg0(m_reset_lock); + + // Destroy the current connection+controller. + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg1(m_state_lock); + if (m_options_locked){ + return false; + } + if (m_controller_type == controller_type){ + return true; + } + + // Move these out to indicate that we should no longer access them. + controller = std::move(m_controller); + connection = std::move(m_connection); + + m_controller_type = controller_type; + } + + // With the lock released, it is now safe to destroy them. + // We cannot destroy these under (m_state_lock) due to their asynchronous + // callbacks into this class which will also acquire the same lock. + controller.reset(); + connection.reset(); + + make_controller(controller_type); + device = m_descriptor; + } + signal_descriptor_changed(device); + signal_status_text_changed(status_text()); + return true; +} + + + +std::string ControllerSession::reset(){ +// cout << "ControllerSession::reset()" << endl; + + { + std::lock_guard lg0(m_reset_lock); + + // Destroy the current connection+controller. + std::unique_ptr controller; + std::unique_ptr connection; + { + std::lock_guard lg1(m_state_lock); + if (m_options_locked){ + return "Options are locked."; + } +// if (!m_connection){ +// cout << "ControllerSession::reset() - early return" << endl; +// return "No connection set."; +// } + + // Move these out to indicate that we should no longer access them. + controller = std::move(m_controller); + connection = std::move(m_connection); + } + + // With the lock released, it is now safe to destroy them. + // We cannot destroy these under (m_state_lock) due to their asynchronous + // callbacks into this class which will also acquire the same lock. + controller.reset(); + connection.reset(); + + make_controller(m_controller_type); + } + signal_status_text_changed(status_text()); + return ""; +} + + +//void ControllerSession::pre_connection_not_ready(ControllerConnection& connection){ +// m_listeners.run_method_unique(&Listener::pre_connection_not_ready, connection); +//} +void ControllerSession::post_connection_ready( + ControllerConnection& connection, + const ControllerModeStatus& mode_status +){ + const std::map& supported_controllers = mode_status.supported_controllers; + if (supported_controllers.empty()){ + return; + } + + ControllerType current_controller = mode_status.current_controller; + +// cout << "sleeping" << endl; +// Sleep(10000); + + + std::vector available_controllers; +// ControllerType selected_controller = ControllerType::None; + bool ready; + { + std::lock_guard lg(m_state_lock); + + // Connection has already been closed. + if (m_connection == nullptr){ + return; + } + + // Controller already constructed. + if (m_controller){ + return; + } + + // We only show the "none" option when there are multiple controllers + // to choose from. + if (supported_controllers.size() > 1){ + available_controllers.emplace_back(ControllerType::None); + } + for (const auto& item : supported_controllers){ + available_controllers.emplace_back(item.first); + } + + // Copy the list. One will be moved into "m_available_controllers". + // The other will be stored locally for the callbacks. + m_available_controllers = available_controllers; + + +#if 0 + auto iter = supported_controllers.begin(); + if (supported_controllers.size() == 1){ + // Only one controller available. Force the option to it. + current_controller = iter->first; + }else{ + // Keep the current controller only if it exists. + iter = supported_controllers.find(m_option.m_controller_type); + if (iter != supported_controllers.end()){ + current_controller = m_option.m_controller_type; + } + } +#endif + + // Construct the controller. + if (current_controller != ControllerType::None){ + m_controller = m_descriptor->make_controller( + m_logger, + *m_connection, + current_controller + ); + } + + // Commit all changes. +// cout << "current_controller = " << CONTROLLER_TYPE_STRINGS.get_string(current_controller) << endl; + m_controller_type = current_controller; + ready = m_controller && m_controller->is_ready(); + } + + signal_controller_changed(current_controller, available_controllers); + signal_ready_changed(ready); + signal_status_text_changed(status_text()); +} +void ControllerSession::status_text_changed( + ControllerConnection& connection, + const std::string& text +){ +// cout << "ControllerSession::status_text_changed() = " << text << endl; + std::string controller_error; + { + WriteSpinLock lg(m_message_lock); + controller_error = m_controller_error; + } +// cout << "ControllerSession::status_text_changed(): controller_error = " << controller_error << endl; + if (controller_error.empty()){ + m_listeners.run_method_unique(&Listener::post_status_text_changed, text); + }else{ + m_listeners.run_method_unique(&Listener::post_status_text_changed, controller_error); + } +} +void ControllerSession::on_error( + ControllerConnection& connection, + const std::string& text +){ + WriteSpinLock lg(m_message_lock); + m_controller_error = text; +} + + + + +void ControllerSession::signal_ready_changed(bool ready){ + m_listeners.run_method_unique(&Listener::ready_changed, ready); +} +void ControllerSession::signal_descriptor_changed( + const std::shared_ptr& descriptor +){ + m_listeners.run_method_unique(&Listener::descriptor_changed, descriptor); +} +void ControllerSession::signal_controller_changed( + ControllerType controller_type, + const std::vector& available_controllers +){ + m_listeners.run_method_unique(&Listener::controller_changed, controller_type, available_controllers); +} +void ControllerSession::signal_status_text_changed(const std::string& text){ +// cout << text << endl; + m_listeners.run_method_unique(&Listener::post_status_text_changed, text); +} +void ControllerSession::signal_options_locked(bool locked){ + m_listeners.run_method_unique(&Listener::options_locked, locked); +} + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerSession.h b/SerialPrograms/Source/Controllers/ControllerSession.h index dda2d28abd..d97a4537f8 100644 --- a/SerialPrograms/Source/Controllers/ControllerSession.h +++ b/SerialPrograms/Source/Controllers/ControllerSession.h @@ -1,177 +1,177 @@ -/* Controller Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerSession_H -#define PokemonAutomation_Controllers_ControllerSession_H - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/ListenerSet.h" -//#include "Common/Cpp/Exceptions.h" -#include "Controller.h" -#include "ControllerDescriptor.h" -#include "ControllerConnection.h" - -namespace PokemonAutomation{ - - - - -class ControllerSession : private ControllerConnection::StatusListener{ -public: - struct Listener{ - virtual void ready_changed(bool ready){} - virtual void descriptor_changed( - const std::shared_ptr& descriptor - ){} - virtual void controller_changed( - ControllerType controller_type, - const std::vector& available_controllers - ){} - virtual void post_status_text_changed(const std::string& text){} - virtual void options_locked(bool locked){} - }; - - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - - -public: - ~ControllerSession(); - ControllerSession( - Logger& logger, - ControllerOption& option, - const ControllerFeatures& required_features - ); - - Logger& logger(){ - return m_logger; - } - const ControllerFeatures& required_features(){ - return m_required_features; - } - std::vector available_controllers() const; - - void get(ControllerOption& option); - void set(const ControllerOption& option); - - bool ready() const; - std::shared_ptr descriptor() const; - ControllerType controller_type() const; - std::string status_text() const; - - const ControllerOption& option() const{ - return m_option; - } - ControllerConnection& connection() const; - AbstractController* controller() const; - - -public: - // Empty String: User input is allowed. - // Non-empty String: User input is blocked. The string is the reason. - std::string user_input_blocked() const; - void set_user_input_blocked(std::string disallow_reason); - - bool options_locked() const; - void set_options_locked(bool locked); - - -public: - bool set_device(const std::shared_ptr& device); - bool set_controller(ControllerType controller_type); - - -public: - // Returns empty string on success. Otherwise returns error message. - std::string reset(); - - // Try to run the following lambda on the underlying controller type. - // Returns empty string if successful. Otherwise returns error message. - template - std::string try_run(Lambda&& function) noexcept{ - std::lock_guard lg(m_state_lock); - if (!m_controller){ - return "Controller is null."; - } - try{ - // This will be a cross-cast in most cases. - ControllerType* child = dynamic_cast(m_controller.get()); - if (child == nullptr){ - m_logger.log("ControllerSession::try_run(): Incompatible controller type cast.", COLOR_RED); - return "Incompatible controller type cast."; - } - if (!m_user_input_disallow_reason.empty()){ - return m_user_input_disallow_reason; - } - function(*child); - }catch (Exception& e){ - return e.to_str(); - }catch (...){ - return "Unknown exception."; - } - return ""; - } - - -private: - void make_controller(std::optional change_controller); - -// virtual void pre_connection_not_ready(ControllerConnection& connection) override; - virtual void post_connection_ready( - ControllerConnection& connection, - const ControllerModeStatus& mode_status - ) override; - virtual void status_text_changed( - ControllerConnection& connection, - const std::string& text - ) override; - virtual void on_error( - ControllerConnection& connection, - const std::string& text - ) override; - - void signal_ready_changed(bool ready); - void signal_descriptor_changed( - const std::shared_ptr& descriptor - ); - void signal_controller_changed( - ControllerType controller_type, - const std::vector& available_controllers - ); - void signal_status_text_changed(const std::string& text); - void signal_options_locked(bool locked); - - -private: - Logger& m_logger; - const ControllerFeatures& m_required_features; - ControllerOption& m_option; - ControllerType m_controller_type; - - std::mutex m_reset_lock; - mutable std::mutex m_state_lock; - - bool m_options_locked; - std::string m_user_input_disallow_reason; - - SpinLock m_message_lock; - std::string m_controller_error; - - std::vector m_available_controllers; - - std::shared_ptr m_descriptor; - std::unique_ptr m_connection; - std::unique_ptr m_controller; - - ListenerSet m_listeners; -}; - - - - -} -#endif +/* Controller Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerSession_H +#define PokemonAutomation_Controllers_ControllerSession_H + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/ListenerSet.h" +//#include "Common/Cpp/Exceptions.h" +#include "Controller.h" +#include "ControllerDescriptor.h" +#include "ControllerConnection.h" + +namespace PokemonAutomation{ + + + + +class ControllerSession : private ControllerConnection::StatusListener{ +public: + struct Listener{ + virtual void ready_changed(bool ready){} + virtual void descriptor_changed( + const std::shared_ptr& descriptor + ){} + virtual void controller_changed( + ControllerType controller_type, + const std::vector& available_controllers + ){} + virtual void post_status_text_changed(const std::string& text){} + virtual void options_locked(bool locked){} + }; + + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + + +public: + ~ControllerSession(); + ControllerSession( + Logger& logger, + ControllerOption& option, + const ControllerFeatures& required_features + ); + + Logger& logger(){ + return m_logger; + } + const ControllerFeatures& required_features(){ + return m_required_features; + } + std::vector available_controllers() const; + + void get(ControllerOption& option); + void set(const ControllerOption& option); + + bool ready() const; + std::shared_ptr descriptor() const; + ControllerType controller_type() const; + std::string status_text() const; + + const ControllerOption& option() const{ + return m_option; + } + ControllerConnection& connection() const; + AbstractController* controller() const; + + +public: + // Empty String: User input is allowed. + // Non-empty String: User input is blocked. The string is the reason. + std::string user_input_blocked() const; + void set_user_input_blocked(std::string disallow_reason); + + bool options_locked() const; + void set_options_locked(bool locked); + + +public: + bool set_device(const std::shared_ptr& device); + bool set_controller(ControllerType controller_type); + + +public: + // Returns empty string on success. Otherwise returns error message. + std::string reset(); + + // Try to run the following lambda on the underlying controller type. + // Returns empty string if successful. Otherwise returns error message. + template + std::string try_run(Lambda&& function) noexcept{ + std::lock_guard lg(m_state_lock); + if (!m_controller){ + return "Controller is null."; + } + try{ + // This will be a cross-cast in most cases. + ControllerType* child = dynamic_cast(m_controller.get()); + if (child == nullptr){ + m_logger.log("ControllerSession::try_run(): Incompatible controller type cast.", COLOR_RED); + return "Incompatible controller type cast."; + } + if (!m_user_input_disallow_reason.empty()){ + return m_user_input_disallow_reason; + } + function(*child); + }catch (Exception& e){ + return e.to_str(); + }catch (...){ + return "Unknown exception."; + } + return ""; + } + + +private: + void make_controller(std::optional change_controller); + +// virtual void pre_connection_not_ready(ControllerConnection& connection) override; + virtual void post_connection_ready( + ControllerConnection& connection, + const ControllerModeStatus& mode_status + ) override; + virtual void status_text_changed( + ControllerConnection& connection, + const std::string& text + ) override; + virtual void on_error( + ControllerConnection& connection, + const std::string& text + ) override; + + void signal_ready_changed(bool ready); + void signal_descriptor_changed( + const std::shared_ptr& descriptor + ); + void signal_controller_changed( + ControllerType controller_type, + const std::vector& available_controllers + ); + void signal_status_text_changed(const std::string& text); + void signal_options_locked(bool locked); + + +private: + Logger& m_logger; + const ControllerFeatures& m_required_features; + ControllerOption& m_option; + ControllerType m_controller_type; + + std::mutex m_reset_lock; + mutable std::mutex m_state_lock; + + bool m_options_locked; + std::string m_user_input_disallow_reason; + + SpinLock m_message_lock; + std::string m_controller_error; + + std::vector m_available_controllers; + + std::shared_ptr m_descriptor; + std::unique_ptr m_connection; + std::unique_ptr m_controller; + + ListenerSet m_listeners; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp b/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp index 029749116c..98c3c4547f 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp +++ b/SerialPrograms/Source/Controllers/ControllerTypeStrings.cpp @@ -1,39 +1,39 @@ -/* Controller Type Strings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ControllerTypeStrings.h" - -namespace PokemonAutomation{ - - - -const EnumStringMap CONTROLLER_INTERFACE_STRINGS{ - {ControllerInterface::None, "None"}, - {ControllerInterface::SerialPABotBase, "Serial: PABotBase"}, - {ControllerInterface::TcpSysbotBase, "TCP: sys-botbase"}, - {ControllerInterface::UsbSysbotBase, "USB: sys-botbase"}, -}; - -const EnumStringMap CONTROLLER_TYPE_STRINGS{ - {ControllerType::None, "None"}, - {ControllerType::NintendoSwitch_WiredProController, "NS: Wired Pro Controller"}, - {ControllerType::NintendoSwitch_WirelessProController, "NS: Wireless Pro Controller"}, - {ControllerType::NintendoSwitch_LeftJoycon, "NS: Left Joycon"}, - {ControllerType::NintendoSwitch_RightJoycon, "NS: Right Joycon"}, -}; - -const EnumStringMap CONTROLLER_FEATURE_STRINGS{ - {ControllerFeature::TickPrecise, "TickPrecise"}, - {ControllerFeature::NintendoSwitch_ProController, "NintendoSwitch_ProController"}, - {ControllerFeature::NintendoSwitch_LeftJoycon, "NintendoSwitch_LeftJoycon"}, - {ControllerFeature::NintendoSwitch_RightJoycon, "NintendoSwitch_RightJoycon"}, - {ControllerFeature::NintendoSwitch_DateSkip, "NintendoSwitch_DateSkip"}, -}; - - - - -} +/* Controller Type Strings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ControllerTypeStrings.h" + +namespace PokemonAutomation{ + + + +const EnumStringMap CONTROLLER_INTERFACE_STRINGS{ + {ControllerInterface::None, "None"}, + {ControllerInterface::SerialPABotBase, "Serial: PABotBase"}, + {ControllerInterface::TcpSysbotBase, "TCP: sys-botbase"}, + {ControllerInterface::UsbSysbotBase, "USB: sys-botbase"}, +}; + +const EnumStringMap CONTROLLER_TYPE_STRINGS{ + {ControllerType::None, "None"}, + {ControllerType::NintendoSwitch_WiredProController, "NS: Wired Pro Controller"}, + {ControllerType::NintendoSwitch_WirelessProController, "NS: Wireless Pro Controller"}, + {ControllerType::NintendoSwitch_LeftJoycon, "NS: Left Joycon"}, + {ControllerType::NintendoSwitch_RightJoycon, "NS: Right Joycon"}, +}; + +const EnumStringMap CONTROLLER_FEATURE_STRINGS{ + {ControllerFeature::TickPrecise, "TickPrecise"}, + {ControllerFeature::NintendoSwitch_ProController, "NintendoSwitch_ProController"}, + {ControllerFeature::NintendoSwitch_LeftJoycon, "NintendoSwitch_LeftJoycon"}, + {ControllerFeature::NintendoSwitch_RightJoycon, "NintendoSwitch_RightJoycon"}, + {ControllerFeature::NintendoSwitch_DateSkip, "NintendoSwitch_DateSkip"}, +}; + + + + +} diff --git a/SerialPrograms/Source/Controllers/ControllerTypeStrings.h b/SerialPrograms/Source/Controllers/ControllerTypeStrings.h index b78ae099e4..406aeeb64a 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypeStrings.h +++ b/SerialPrograms/Source/Controllers/ControllerTypeStrings.h @@ -1,24 +1,24 @@ -/* Controller Type Strings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerTypeStrings_H -#define PokemonAutomation_Controllers_ControllerTypeStrings_H - -#include "Common/Cpp/EnumStringMap.h" -#include "ControllerTypes.h" - -namespace PokemonAutomation{ - - - -extern const EnumStringMap CONTROLLER_INTERFACE_STRINGS; -extern const EnumStringMap CONTROLLER_TYPE_STRINGS; -extern const EnumStringMap CONTROLLER_FEATURE_STRINGS; - - - -} -#endif +/* Controller Type Strings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerTypeStrings_H +#define PokemonAutomation_Controllers_ControllerTypeStrings_H + +#include "Common/Cpp/EnumStringMap.h" +#include "ControllerTypes.h" + +namespace PokemonAutomation{ + + + +extern const EnumStringMap CONTROLLER_INTERFACE_STRINGS; +extern const EnumStringMap CONTROLLER_TYPE_STRINGS; +extern const EnumStringMap CONTROLLER_FEATURE_STRINGS; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/ControllerTypes.h b/SerialPrograms/Source/Controllers/ControllerTypes.h index 2f0c650ce1..8e413f2fd9 100644 --- a/SerialPrograms/Source/Controllers/ControllerTypes.h +++ b/SerialPrograms/Source/Controllers/ControllerTypes.h @@ -1,72 +1,72 @@ -/* Controller Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_ControllerTypes_H -#define PokemonAutomation_Controllers_ControllerTypes_H - -namespace PokemonAutomation{ - - -// This is used only for the UI to indicate if a program may be faster on -// tick-precise controllers. There is no functional effect. -enum class FasterIfTickPrecise{ - NOT_FASTER, - FASTER, - MUCH_FASTER, -}; - - -enum class ControllerInterface{ - None, - SerialPABotBase, - TcpSysbotBase, - UsbSysbotBase, -}; - - -enum class ControllerType{ - None, - - // There's a difference between the generic 3rd party wired controllers and - // a pro controller connected over USB. If/when we support the latter, we - // will need to split this controller type. - NintendoSwitch_WiredProController, - - NintendoSwitch_WirelessProController, - NintendoSwitch_LeftJoycon, - NintendoSwitch_RightJoycon, -}; - - -enum class ControllerFeature{ - TickPrecise, - TimingFlexibleMilliseconds, - - // If we add support gyro or rumble, we will need to split this feature - // since the Pokken controller doesn't support those. - NintendoSwitch_ProController, - - NintendoSwitch_LeftJoycon, - NintendoSwitch_RightJoycon, - - // This is leftover from the days of RPCs. But we keep it here as a hack to - // lock ESP32 out of the day skippers since it's too unstable to run those. - NintendoSwitch_DateSkip, -}; - - -enum class ControllerPerformanceClass{ - Unknown, - SerialPABotBase_Wired_125Hz, - SerialPABotBase_Wireless_ESP32, - SysbotBase, -}; - - - - -} -#endif +/* Controller Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_ControllerTypes_H +#define PokemonAutomation_Controllers_ControllerTypes_H + +namespace PokemonAutomation{ + + +// This is used only for the UI to indicate if a program may be faster on +// tick-precise controllers. There is no functional effect. +enum class FasterIfTickPrecise{ + NOT_FASTER, + FASTER, + MUCH_FASTER, +}; + + +enum class ControllerInterface{ + None, + SerialPABotBase, + TcpSysbotBase, + UsbSysbotBase, +}; + + +enum class ControllerType{ + None, + + // There's a difference between the generic 3rd party wired controllers and + // a pro controller connected over USB. If/when we support the latter, we + // will need to split this controller type. + NintendoSwitch_WiredProController, + + NintendoSwitch_WirelessProController, + NintendoSwitch_LeftJoycon, + NintendoSwitch_RightJoycon, +}; + + +enum class ControllerFeature{ + TickPrecise, + TimingFlexibleMilliseconds, + + // If we add support gyro or rumble, we will need to split this feature + // since the Pokken controller doesn't support those. + NintendoSwitch_ProController, + + NintendoSwitch_LeftJoycon, + NintendoSwitch_RightJoycon, + + // This is leftover from the days of RPCs. But we keep it here as a hack to + // lock ESP32 out of the day skippers since it's too unstable to run those. + NintendoSwitch_DateSkip, +}; + + +enum class ControllerPerformanceClass{ + Unknown, + SerialPABotBase_Wired_125Hz, + SerialPABotBase_Wireless_ESP32, + SysbotBase, +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/JoystickTools.h b/SerialPrograms/Source/Controllers/JoystickTools.h index baa03864f2..27df31b64e 100644 --- a/SerialPrograms/Source/Controllers/JoystickTools.h +++ b/SerialPrograms/Source/Controllers/JoystickTools.h @@ -1,111 +1,111 @@ -/* Joystick Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_JoystickTools_H -#define PokemonAutomation_Controllers_JoystickTools_H - -#include -#include - -namespace PokemonAutomation{ -namespace JoystickTools{ - - -inline void max_out_magnitude(double& x, double& y){ - double mag = x*x + y*y; - if (mag == 0){ - return; - } - - double abs_x = std::abs(x); - double abs_y = std::abs(y); - - if (abs_x < abs_y){ - x /= abs_y; - y = y < 0 ? -1 : 1; - }else{ - y /= abs_x; - x = x < 0 ? -1 : 1; - } -} -inline double project_to_range(double x, double lo, double hi){ - if (x <= -1){ - return -1; - } - if (x >= 1){ - return 1; - } - return x * (hi - lo) + lo; -} - - - - -inline double linear_u8_to_float(uint8_t x){ - if (x <= 128){ - return (x - 128) * (1. / 128); - }else{ - return (x - 128) * (1. / 127); - } -} -inline uint8_t linear_float_to_u8(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 128 + 128; - return (uint8_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 127 + 128; - return (uint8_t)(f + 0.5); - } -} -inline int16_t linear_float_to_s16(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 32768; - return (int16_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 32767; - return (int16_t)(f + 0.5); - } -} -inline uint16_t linear_float_to_u16(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 32768 + 32768; - return (uint16_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 32767 + 32768; - return (uint16_t)(f + 0.5); - } -} - - - -inline uint16_t linear_float_to_u12(double f){ - if (f <= 0){ - f = std::max(f, -1); - f = f * 2048 + 2048; - return (uint16_t)(f + 0.5); - }else{ - f = std::min(f, +1); - f = f * 2047 + 2048; - return (uint16_t)(f + 0.5); - } -} - - - - - - - - -} -} -#endif +/* Joystick Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_JoystickTools_H +#define PokemonAutomation_Controllers_JoystickTools_H + +#include +#include + +namespace PokemonAutomation{ +namespace JoystickTools{ + + +inline void max_out_magnitude(double& x, double& y){ + double mag = x*x + y*y; + if (mag == 0){ + return; + } + + double abs_x = std::abs(x); + double abs_y = std::abs(y); + + if (abs_x < abs_y){ + x /= abs_y; + y = y < 0 ? -1 : 1; + }else{ + y /= abs_x; + x = x < 0 ? -1 : 1; + } +} +inline double project_to_range(double x, double lo, double hi){ + if (x <= -1){ + return -1; + } + if (x >= 1){ + return 1; + } + return x * (hi - lo) + lo; +} + + + + +inline double linear_u8_to_float(uint8_t x){ + if (x <= 128){ + return (x - 128) * (1. / 128); + }else{ + return (x - 128) * (1. / 127); + } +} +inline uint8_t linear_float_to_u8(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 128 + 128; + return (uint8_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 127 + 128; + return (uint8_t)(f + 0.5); + } +} +inline int16_t linear_float_to_s16(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 32768; + return (int16_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 32767; + return (int16_t)(f + 0.5); + } +} +inline uint16_t linear_float_to_u16(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 32768 + 32768; + return (uint16_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 32767 + 32768; + return (uint16_t)(f + 0.5); + } +} + + + +inline uint16_t linear_float_to_u12(double f){ + if (f <= 0){ + f = std::max(f, -1); + f = f * 2048 + 2048; + return (uint16_t)(f + 0.5); + }else{ + f = std::min(f, +1); + f = f * 2047 + 2048; + return (uint16_t)(f + 0.5); + } +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp index 8778f9f580..32c8f1173e 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp +++ b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.cpp @@ -1,40 +1,40 @@ -/* Global Qt Key Map - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "GlobalQtKeyMap.h" - -namespace PokemonAutomation{ - - - -void QtKeyMap::record(const QKeyEvent& event){ - int qt_key = event.key(); - uint32_t native_key = event.nativeVirtualKey(); - if (native_key == 0 && (qt_key == 0 || qt_key == Qt::Key_unknown)){ - // both native key and Qt key event is 0 or unknown, meaning we really don't know - // what key event it is. Skip - return; - } - - Qt::Key qkey = (Qt::Key)qt_key; - WriteSpinLock lg(m_lock); - m_map[native_key].insert(qkey); -} - -std::set QtKeyMap::get_QtKeys(uint32_t native_key) const{ - ReadSpinLock lg(m_lock); - auto iter = m_map.find(native_key); - if (iter != m_map.end()){ - return iter->second; - } - return {}; -} - - - -} +/* Global Qt Key Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "GlobalQtKeyMap.h" + +namespace PokemonAutomation{ + + + +void QtKeyMap::record(const QKeyEvent& event){ + int qt_key = event.key(); + uint32_t native_key = event.nativeVirtualKey(); + if (native_key == 0 && (qt_key == 0 || qt_key == Qt::Key_unknown)){ + // both native key and Qt key event is 0 or unknown, meaning we really don't know + // what key event it is. Skip + return; + } + + Qt::Key qkey = (Qt::Key)qt_key; + WriteSpinLock lg(m_lock); + m_map[native_key].insert(qkey); +} + +std::set QtKeyMap::get_QtKeys(uint32_t native_key) const{ + ReadSpinLock lg(m_lock); + auto iter = m_map.find(native_key); + if (iter != m_map.end()){ + return iter->second; + } + return {}; +} + + + +} diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h index c2b75d6070..109a938215 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h +++ b/SerialPrograms/Source/Controllers/KeyboardInput/GlobalQtKeyMap.h @@ -1,45 +1,45 @@ -/* Global Qt Key Map - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_GlobalQtKeyMap_H -#define PokemonAutomation_Controllers_GlobalQtKeyMap_H - -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" - -namespace PokemonAutomation{ - - - - -class QtKeyMap{ -public: - static QtKeyMap& instance(){ - static QtKeyMap map; - return map; - } - - void record(const QKeyEvent& event); - - std::set get_QtKeys(uint32_t native_key) const; - - -private: - QtKeyMap() = default; - - -private: - mutable SpinLock m_lock; - // Map of native key to Qt's key ID. - std::map> m_map; -}; - - - -} -#endif +/* Global Qt Key Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_GlobalQtKeyMap_H +#define PokemonAutomation_Controllers_GlobalQtKeyMap_H + +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" + +namespace PokemonAutomation{ + + + + +class QtKeyMap{ +public: + static QtKeyMap& instance(){ + static QtKeyMap map; + return map; + } + + void record(const QKeyEvent& event); + + std::set get_QtKeys(uint32_t native_key) const; + + +private: + QtKeyMap() = default; + + +private: + mutable SpinLock m_lock; + // Map of native key to Qt's key ID. + std::map> m_map; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp index 66df3280c6..c3cc5489ad 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.cpp @@ -1,186 +1,186 @@ -/* Keyboard Input - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" -#include "KeyboardInput.h" - -namespace PokemonAutomation{ - - - -KeyboardInputController::~KeyboardInputController() = default; -KeyboardInputController::KeyboardInputController(bool enabled) - : m_stop(false) -{} - -void KeyboardInputController::start(){ - m_thread = std::thread( - run_with_catch, - "KeyboardInputController::thread_loop()", - [this]{ thread_loop(); } - ); -} -void KeyboardInputController::stop() noexcept{ - bool expected = false; - if (!m_stop.compare_exchange_strong(expected, true)){ - // Already stopped. - return; - } - { - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); - } - m_thread.join(); -} - -void KeyboardInputController::clear_state(){ - { - WriteSpinLock lg(m_state_lock); - m_state_tracker.clear(); - } - - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); -} -void KeyboardInputController::on_key_press(const QKeyEvent& key){ -// cout << "press: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; - -// QKeySequence seq((Qt::Key)key.key()); -// cout << "button: " << seq.toString().toStdString() << endl; - - QtKeyMap::instance().record(key); - { - WriteSpinLock lg(m_state_lock); - m_state_tracker.press(key.nativeVirtualKey()); - } - - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); -} -void KeyboardInputController::on_key_release(const QKeyEvent& key){ -// cout << "release: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; - QtKeyMap::instance().record(key); - { - WriteSpinLock lg(m_state_lock); - m_state_tracker.release(key.nativeVirtualKey()); - } - - std::lock_guard lg(m_sleep_lock); - m_cv.notify_all(); -} - - - -void KeyboardInputController::thread_loop(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - - std::unique_ptr last = make_state(); - std::unique_ptr current = make_state(); - - bool last_neutral = true; - WallClock last_press = current_time(); - while (true){ - if (m_stop.load(std::memory_order_acquire)){ - return; - } - -#if 0 - // Not accepting commands. - if (!m_enabled){ - last->clear(); - std::unique_lock lg(m_sleep_lock); - if (m_stop.load(std::memory_order_acquire)){ - return; - } - m_cv.wait(lg); - continue; - } -#endif - - // Get the raw keyboard state. - std::set pressed_native_keys; - WallClock next_wake; - { - ReadSpinLock lg(m_state_lock); - pressed_native_keys = m_state_tracker.get_currently_pressed(); - next_wake = m_state_tracker.next_state_change(); - } - - update_state(*current, pressed_native_keys); - bool neutral = current->is_neutral(); - - - // Send the command. - WallClock now; - do{ - now = current_time(); - if (neutral && last_neutral){ - continue; - } - try{ -// current.print(); - if (*current == *last && last_press + std::chrono::milliseconds(1000) > now){ -// cout << "No state change." << endl; - break; - } - - // If state is neutral, just issue a stop. - if (neutral){ - cancel_all_commands(); - last->clear(); - last_neutral = true; - last_press = now; - break; - } - - // If the new state is different, set next interrupt so the new - // new command can replace the current one without gaps. - if (!last_neutral && current != last){ - replace_on_next_command(); - } - - // Send the command. - send_state(*current); - - std::swap(last, current); - last_neutral = false; - last_press = now; - }catch (Exception& e){ - e.log(global_logger_tagged()); - } - }while (false); - - - // Wait for next event. - std::unique_lock lg(m_sleep_lock); - if (m_stop.load(std::memory_order_acquire)){ - return; - } - - // Nothing held down. - if (last_neutral && next_wake == WallClock::max()){ -// cout << "wait - long" << endl; - m_cv.wait(lg); - }else{ -// cout << "wait - short" << endl; - m_cv.wait_until(lg, std::min(next_wake, now + std::chrono::milliseconds(1000))); - } - } -} - - - - - - - - -} +/* Keyboard Input + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" +#include "KeyboardInput.h" + +namespace PokemonAutomation{ + + + +KeyboardInputController::~KeyboardInputController() = default; +KeyboardInputController::KeyboardInputController(bool enabled) + : m_stop(false) +{} + +void KeyboardInputController::start(){ + m_thread = std::thread( + run_with_catch, + "KeyboardInputController::thread_loop()", + [this]{ thread_loop(); } + ); +} +void KeyboardInputController::stop() noexcept{ + bool expected = false; + if (!m_stop.compare_exchange_strong(expected, true)){ + // Already stopped. + return; + } + { + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); + } + m_thread.join(); +} + +void KeyboardInputController::clear_state(){ + { + WriteSpinLock lg(m_state_lock); + m_state_tracker.clear(); + } + + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); +} +void KeyboardInputController::on_key_press(const QKeyEvent& key){ +// cout << "press: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; + +// QKeySequence seq((Qt::Key)key.key()); +// cout << "button: " << seq.toString().toStdString() << endl; + + QtKeyMap::instance().record(key); + { + WriteSpinLock lg(m_state_lock); + m_state_tracker.press(key.nativeVirtualKey()); + } + + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); +} +void KeyboardInputController::on_key_release(const QKeyEvent& key){ +// cout << "release: " << key.key() << ", native = " << key.nativeVirtualKey() << endl; + QtKeyMap::instance().record(key); + { + WriteSpinLock lg(m_state_lock); + m_state_tracker.release(key.nativeVirtualKey()); + } + + std::lock_guard lg(m_sleep_lock); + m_cv.notify_all(); +} + + + +void KeyboardInputController::thread_loop(){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + + std::unique_ptr last = make_state(); + std::unique_ptr current = make_state(); + + bool last_neutral = true; + WallClock last_press = current_time(); + while (true){ + if (m_stop.load(std::memory_order_acquire)){ + return; + } + +#if 0 + // Not accepting commands. + if (!m_enabled){ + last->clear(); + std::unique_lock lg(m_sleep_lock); + if (m_stop.load(std::memory_order_acquire)){ + return; + } + m_cv.wait(lg); + continue; + } +#endif + + // Get the raw keyboard state. + std::set pressed_native_keys; + WallClock next_wake; + { + ReadSpinLock lg(m_state_lock); + pressed_native_keys = m_state_tracker.get_currently_pressed(); + next_wake = m_state_tracker.next_state_change(); + } + + update_state(*current, pressed_native_keys); + bool neutral = current->is_neutral(); + + + // Send the command. + WallClock now; + do{ + now = current_time(); + if (neutral && last_neutral){ + continue; + } + try{ +// current.print(); + if (*current == *last && last_press + std::chrono::milliseconds(1000) > now){ +// cout << "No state change." << endl; + break; + } + + // If state is neutral, just issue a stop. + if (neutral){ + cancel_all_commands(); + last->clear(); + last_neutral = true; + last_press = now; + break; + } + + // If the new state is different, set next interrupt so the new + // new command can replace the current one without gaps. + if (!last_neutral && current != last){ + replace_on_next_command(); + } + + // Send the command. + send_state(*current); + + std::swap(last, current); + last_neutral = false; + last_press = now; + }catch (Exception& e){ + e.log(global_logger_tagged()); + } + }while (false); + + + // Wait for next event. + std::unique_lock lg(m_sleep_lock); + if (m_stop.load(std::memory_order_acquire)){ + return; + } + + // Nothing held down. + if (last_neutral && next_wake == WallClock::max()){ +// cout << "wait - long" << endl; + m_cv.wait(lg); + }else{ +// cout << "wait - short" << endl; + m_cv.wait_until(lg, std::min(next_wake, now + std::chrono::milliseconds(1000))); + } + } +} + + + + + + + + +} diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h index 8560456c7e..c327fe3c82 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardInput.h @@ -1,148 +1,148 @@ -/* Keyboard Input - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_KeyboardInput_H -#define PokemonAutomation_Controllers_KeyboardInput_H - -#include -#include -#include -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Controllers/Controller.h" -#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" -#include "KeyboardStateTracker.h" - -class QKeyEvent; - -namespace PokemonAutomation{ - - -class ControllerSession; - - - - -class ControllerState{ -public: - virtual ~ControllerState() = default; - - virtual void clear() = 0; - - virtual bool operator==(const ControllerState& x) const = 0; - virtual bool operator!=(const ControllerState& x) const{ return !(*this == x); } - - virtual bool is_neutral() const = 0; -}; - - - - -class KeyboardInputController{ -public: - KeyboardInputController(bool enabled); - virtual ~KeyboardInputController(); - - -public: - void clear_state(); - - void on_key_press(const QKeyEvent& key); - void on_key_release(const QKeyEvent& key); - - -protected: - void start(); // Child class must call this at end of constructor. - void stop() noexcept; // Child class must call this at start of destructor. - - virtual std::unique_ptr make_state() const = 0; - virtual void update_state(ControllerState& state, const std::set& pressed_keys) = 0; - virtual void cancel_all_commands() = 0; - virtual void replace_on_next_command() = 0; - virtual void send_state(const ControllerState& state) = 0; - -private: - void thread_loop(); - - -private: - // Controller State - SpinLock m_state_lock; - KeyboardStateTracker m_state_tracker; - - std::atomic m_stop; - - std::mutex m_sleep_lock; - std::condition_variable m_cv; - std::thread m_thread; -}; - - - - -template -class KeyboardManager : public KeyboardInputController{ -public: - KeyboardManager(AbstractController& controller) - : KeyboardInputController(true) - , m_controller(&controller) - {} - void stop() noexcept{ - { - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - m_controller = nullptr; - } - KeyboardInputController::stop(); - } - - virtual std::unique_ptr make_state() const override{ - return std::make_unique(); - } - virtual void update_state(ControllerState& state, const std::set& pressed_keys) override{ - DeltaType deltas; - const QtKeyMap& qkey_map = QtKeyMap::instance(); - for (uint32_t native_key : pressed_keys){ - std::set qkeys = qkey_map.get_QtKeys(native_key); - for (Qt::Key qkey : qkeys){ - auto iter = m_mapping.find(qkey); - if (iter != m_mapping.end()){ - deltas += iter->second; - break; - } - } - } - deltas.to_state(static_cast(state)); - } - virtual void cancel_all_commands() override{ - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - m_controller->cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - m_controller->replace_on_next_command(); - } - - -protected: - SpinLock m_lock; - AbstractController* m_controller; - std::map m_mapping; -}; - - - - -} -#endif +/* Keyboard Input + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_KeyboardInput_H +#define PokemonAutomation_Controllers_KeyboardInput_H + +#include +#include +#include +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Controllers/Controller.h" +#include "Controllers/KeyboardInput/GlobalQtKeyMap.h" +#include "KeyboardStateTracker.h" + +class QKeyEvent; + +namespace PokemonAutomation{ + + +class ControllerSession; + + + + +class ControllerState{ +public: + virtual ~ControllerState() = default; + + virtual void clear() = 0; + + virtual bool operator==(const ControllerState& x) const = 0; + virtual bool operator!=(const ControllerState& x) const{ return !(*this == x); } + + virtual bool is_neutral() const = 0; +}; + + + + +class KeyboardInputController{ +public: + KeyboardInputController(bool enabled); + virtual ~KeyboardInputController(); + + +public: + void clear_state(); + + void on_key_press(const QKeyEvent& key); + void on_key_release(const QKeyEvent& key); + + +protected: + void start(); // Child class must call this at end of constructor. + void stop() noexcept; // Child class must call this at start of destructor. + + virtual std::unique_ptr make_state() const = 0; + virtual void update_state(ControllerState& state, const std::set& pressed_keys) = 0; + virtual void cancel_all_commands() = 0; + virtual void replace_on_next_command() = 0; + virtual void send_state(const ControllerState& state) = 0; + +private: + void thread_loop(); + + +private: + // Controller State + SpinLock m_state_lock; + KeyboardStateTracker m_state_tracker; + + std::atomic m_stop; + + std::mutex m_sleep_lock; + std::condition_variable m_cv; + std::thread m_thread; +}; + + + + +template +class KeyboardManager : public KeyboardInputController{ +public: + KeyboardManager(AbstractController& controller) + : KeyboardInputController(true) + , m_controller(&controller) + {} + void stop() noexcept{ + { + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + m_controller = nullptr; + } + KeyboardInputController::stop(); + } + + virtual std::unique_ptr make_state() const override{ + return std::make_unique(); + } + virtual void update_state(ControllerState& state, const std::set& pressed_keys) override{ + DeltaType deltas; + const QtKeyMap& qkey_map = QtKeyMap::instance(); + for (uint32_t native_key : pressed_keys){ + std::set qkeys = qkey_map.get_QtKeys(native_key); + for (Qt::Key qkey : qkeys){ + auto iter = m_mapping.find(qkey); + if (iter != m_mapping.end()){ + deltas += iter->second; + break; + } + } + } + deltas.to_state(static_cast(state)); + } + virtual void cancel_all_commands() override{ + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + m_controller->cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + m_controller->replace_on_next_command(); + } + + +protected: + SpinLock m_lock; + AbstractController* m_controller; + std::map m_mapping; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp index 57bda53d09..552ac3ee53 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.cpp @@ -1,85 +1,85 @@ -/* Keyboard State Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "KeyboardStateTracker.h" - -namespace PokemonAutomation{ - - - -KeyboardStateTracker::KeyboardStateTracker(std::chrono::milliseconds debounce_period) - : m_debounce_period(debounce_period) -{} - - - -void KeyboardStateTracker::clear(){ - m_committed.clear(); - m_pending.clear(); -} -void KeyboardStateTracker::press(uint32_t key){ - WallClock now = current_time(); - m_pending.emplace_back(Event{now, true, key}); - move_old_events_unprotected(now); -} -void KeyboardStateTracker::release(uint32_t key){ - WallClock now = current_time(); - m_pending.emplace_back(Event{now, false, key}); - move_old_events_unprotected(now); -} - - - -WallClock KeyboardStateTracker::next_state_change() const{ - return m_pending.empty() - ? WallClock::max() - : m_pending.begin()->timestamp + m_debounce_period; -} -std::set KeyboardStateTracker::get_currently_pressed(){ - WallClock now = current_time(); - move_old_events_unprotected(now); - - // Copy the current committed set. - std::set ret = m_committed; - - // Now process all the pending ones - ignoring the release events. - for (const Event& event : m_pending){ - if (event.press){ - ret.insert(event.key); - } - } - - return ret; -} -void KeyboardStateTracker::move_old_events_unprotected(WallClock now){ - WallClock threshold = now - m_debounce_period; - while (!m_pending.empty()){ - Event& event = m_pending.front(); - - // Always commit presses. - if (event.press){ - m_committed.insert(event.key); - m_pending.pop_front(); - continue; - } - - // Release is old enough. Commit it. - if (event.timestamp < threshold){ - m_committed.erase(event.key); - m_pending.pop_front(); - continue; - } - - // We've hit an uncommittable release. We're done. - break; - } -} - - - - - -} +/* Keyboard State Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "KeyboardStateTracker.h" + +namespace PokemonAutomation{ + + + +KeyboardStateTracker::KeyboardStateTracker(std::chrono::milliseconds debounce_period) + : m_debounce_period(debounce_period) +{} + + + +void KeyboardStateTracker::clear(){ + m_committed.clear(); + m_pending.clear(); +} +void KeyboardStateTracker::press(uint32_t key){ + WallClock now = current_time(); + m_pending.emplace_back(Event{now, true, key}); + move_old_events_unprotected(now); +} +void KeyboardStateTracker::release(uint32_t key){ + WallClock now = current_time(); + m_pending.emplace_back(Event{now, false, key}); + move_old_events_unprotected(now); +} + + + +WallClock KeyboardStateTracker::next_state_change() const{ + return m_pending.empty() + ? WallClock::max() + : m_pending.begin()->timestamp + m_debounce_period; +} +std::set KeyboardStateTracker::get_currently_pressed(){ + WallClock now = current_time(); + move_old_events_unprotected(now); + + // Copy the current committed set. + std::set ret = m_committed; + + // Now process all the pending ones - ignoring the release events. + for (const Event& event : m_pending){ + if (event.press){ + ret.insert(event.key); + } + } + + return ret; +} +void KeyboardStateTracker::move_old_events_unprotected(WallClock now){ + WallClock threshold = now - m_debounce_period; + while (!m_pending.empty()){ + Event& event = m_pending.front(); + + // Always commit presses. + if (event.press){ + m_committed.insert(event.key); + m_pending.pop_front(); + continue; + } + + // Release is old enough. Commit it. + if (event.timestamp < threshold){ + m_committed.erase(event.key); + m_pending.pop_front(); + continue; + } + + // We've hit an uncommittable release. We're done. + break; + } +} + + + + + +} diff --git a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h index 8ffdbd274e..698c6c6461 100644 --- a/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h +++ b/SerialPrograms/Source/Controllers/KeyboardInput/KeyboardStateTracker.h @@ -1,58 +1,58 @@ -/* Keyboard State Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_KeyboardStateTracker_H -#define PokemonAutomation_Controllers_KeyboardStateTracker_H - -#include -#include -#include "Common/Cpp/Time.h" - -namespace PokemonAutomation{ - - - -class KeyboardStateTracker{ -public: - KeyboardStateTracker(std::chrono::milliseconds debounce_period = std::chrono::milliseconds(10)); - - -public: - void clear(); - void press(uint32_t key); - void release(uint32_t key); - - -public: - WallClock next_state_change() const; - std::set get_currently_pressed(); - - -private: - // Move all pending events that are old enough to the committed set. - void move_old_events_unprotected(WallClock now); - - -private: - struct Event{ - WallClock timestamp; - bool press; - uint32_t key; - }; - const std::chrono::milliseconds m_debounce_period; - - std::set m_committed; - std::deque m_pending; -}; - - - - - - - -} -#endif +/* Keyboard State Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_KeyboardStateTracker_H +#define PokemonAutomation_Controllers_KeyboardStateTracker_H + +#include +#include +#include "Common/Cpp/Time.h" + +namespace PokemonAutomation{ + + + +class KeyboardStateTracker{ +public: + KeyboardStateTracker(std::chrono::milliseconds debounce_period = std::chrono::milliseconds(10)); + + +public: + void clear(); + void press(uint32_t key); + void release(uint32_t key); + + +public: + WallClock next_state_change() const; + std::set get_currently_pressed(); + + +private: + // Move all pending events that are old enough to the committed set. + void move_old_events_unprotected(WallClock now); + + +private: + struct Event{ + WallClock timestamp; + bool press; + uint32_t key; + }; + const std::chrono::milliseconds m_debounce_period; + + std::set m_committed; + std::deque m_pending; +}; + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/NullController.cpp b/SerialPrograms/Source/Controllers/NullController.cpp index 570e305bc5..03c7fa7483 100644 --- a/SerialPrograms/Source/Controllers/NullController.cpp +++ b/SerialPrograms/Source/Controllers/NullController.cpp @@ -1,51 +1,51 @@ -/* Null Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "ControllerConnection.h" -#include "ControllerSelectorWidget.h" -#include "NullController.h" - -namespace PokemonAutomation{ - - -template class InterfaceType_t; - - -bool NullControllerDescriptor::operator==(const ControllerDescriptor& x) const{ - return typeid(*this) == typeid(x); -} -std::string NullControllerDescriptor::display_name() const{ - return "(none)"; -} -void NullControllerDescriptor::load_json(const JsonValue& json){ - -} -JsonValue NullControllerDescriptor::to_json() const{ - return JsonValue(); -} -std::unique_ptr NullControllerDescriptor::open_connection( - Logger& logger, - std::optional change_controller -) const{ - return nullptr; -} -std::unique_ptr NullControllerDescriptor::make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type -) const{ - return nullptr; -} -QWidget* NullControllerDescriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ - return new QWidget(&parent); -} - - - - -} +/* Null Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "ControllerConnection.h" +#include "ControllerSelectorWidget.h" +#include "NullController.h" + +namespace PokemonAutomation{ + + +template class InterfaceType_t; + + +bool NullControllerDescriptor::operator==(const ControllerDescriptor& x) const{ + return typeid(*this) == typeid(x); +} +std::string NullControllerDescriptor::display_name() const{ + return "(none)"; +} +void NullControllerDescriptor::load_json(const JsonValue& json){ + +} +JsonValue NullControllerDescriptor::to_json() const{ + return JsonValue(); +} +std::unique_ptr NullControllerDescriptor::open_connection( + Logger& logger, + std::optional change_controller +) const{ + return nullptr; +} +std::unique_ptr NullControllerDescriptor::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type +) const{ + return nullptr; +} +QWidget* NullControllerDescriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ + return new QWidget(&parent); +} + + + + +} diff --git a/SerialPrograms/Source/Controllers/NullController.h b/SerialPrograms/Source/Controllers/NullController.h index 7e68ae4d2a..5d409dd473 100644 --- a/SerialPrograms/Source/Controllers/NullController.h +++ b/SerialPrograms/Source/Controllers/NullController.h @@ -1,45 +1,45 @@ -/* Null Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_NullController_H -#define PokemonAutomation_Controllers_NullController_H - -#include "ControllerDescriptor.h" - -namespace PokemonAutomation{ - - - -class NullControllerDescriptor : public ControllerDescriptor{ -public: - static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::None; - -public: - NullControllerDescriptor() - : ControllerDescriptor(ControllerInterface::None) - {} - virtual bool operator==(const ControllerDescriptor& x) const override; - virtual std::string display_name() const override; - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const override; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const override; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; -}; - - - -} -#endif +/* Null Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_NullController_H +#define PokemonAutomation_Controllers_NullController_H + +#include "ControllerDescriptor.h" + +namespace PokemonAutomation{ + + + +class NullControllerDescriptor : public ControllerDescriptor{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::None; + +public: + NullControllerDescriptor() + : ControllerDescriptor(ControllerInterface::None) + {} + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp index 8ae9fec0ff..9f37216859 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.cpp @@ -1,178 +1,178 @@ -/* Serial Port (PABotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "SerialPABotBase.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - -// Defaults -const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS{ - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, -}; - - - - -std::string program_name(uint8_t id){ - switch (id){ - case PABB_PID_UNSPECIFIED: return "Microcontroller Program"; - - // Old (fat) PABotBase with scheduler. - case PABB_PID_PABOTBASE_12KB: return "PABotBase-AVR8-12KB"; - case PABB_PID_PABOTBASE_31KB: return "PABotBase-AVR8-31KB"; - - // New (slim) PABotBase. - case PABB_PID_PABOTBASE_ArduinoUnoR3: return "PABotBase-UnoR3"; - case PABB_PID_PABOTBASE_ArduinoLeonardo: return "PABotBase-Leonardo"; - case PABB_PID_PABOTBASE_ProMicro: return "PABotBase-ProMicro"; - case PABB_PID_PABOTBASE_Teensy2: return "PABotBase-Teensy2.0"; - case PABB_PID_PABOTBASE_TeensyPP2: return "PABotBase-Teensy++2.0"; - - case PABB_PID_PABOTBASE_CH552: return "PABotBase-CH552"; - - case PABB_PID_PABOTBASE_ESP32: return "PABotBase-ESP32"; - case PABB_PID_PABOTBASE_ESP32S3: return "PABotBase-ESP32-S3"; - - default: return "Unknown ID"; - } -} -ControllerType id_to_controller_type(uint32_t id){ - switch (id){ - case PABB_CID_NONE: - return ControllerType::None; - case PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER: - return ControllerType::NintendoSwitch_WiredProController; - case PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER: - return ControllerType::NintendoSwitch_WirelessProController; - case PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON: - return ControllerType::NintendoSwitch_LeftJoycon; - case PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON: - return ControllerType::NintendoSwitch_RightJoycon; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Controller ID: " + std::to_string(id) - ); -} -uint32_t controller_type_to_id(ControllerType controller_type){ - switch (controller_type){ - case ControllerType::None: - return PABB_CID_NONE; - case ControllerType::NintendoSwitch_WiredProController: - return PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER; - case ControllerType::NintendoSwitch_WirelessProController: - return PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; - case ControllerType::NintendoSwitch_LeftJoycon: - return PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; - case ControllerType::NintendoSwitch_RightJoycon: - return PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid Controller Enum: " + std::to_string((int)controller_type) - ); -} - - - -const std::map< - uint32_t, // Protocol Version - std::map< - uint32_t, // Program ID - std::map - > -> SUPPORTED_VERSIONS{ - {2025061202, { - {PABB_PID_PABOTBASE_ESP32, { - {ControllerType::NintendoSwitch_WirelessProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - }}, - {ControllerType::NintendoSwitch_LeftJoycon, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_LeftJoycon, - }}, - {ControllerType::NintendoSwitch_RightJoycon, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_RightJoycon, - }}, - }}, - }}, - {2025061303, { - {PABB_PID_PABOTBASE_ESP32S3, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - }}, - {2025061403, { - {PABB_PID_PABOTBASE_ArduinoUnoR3, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_ArduinoLeonardo, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_ProMicro, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_Teensy2, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - {PABB_PID_PABOTBASE_TeensyPP2, { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }}, - }}, - }}, -}; - - - - - - - - - - -} -} +/* Serial Port (PABotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "SerialPABotBase.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + +// Defaults +const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS{ + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, +}; + + + + +std::string program_name(uint8_t id){ + switch (id){ + case PABB_PID_UNSPECIFIED: return "Microcontroller Program"; + + // Old (fat) PABotBase with scheduler. + case PABB_PID_PABOTBASE_12KB: return "PABotBase-AVR8-12KB"; + case PABB_PID_PABOTBASE_31KB: return "PABotBase-AVR8-31KB"; + + // New (slim) PABotBase. + case PABB_PID_PABOTBASE_ArduinoUnoR3: return "PABotBase-UnoR3"; + case PABB_PID_PABOTBASE_ArduinoLeonardo: return "PABotBase-Leonardo"; + case PABB_PID_PABOTBASE_ProMicro: return "PABotBase-ProMicro"; + case PABB_PID_PABOTBASE_Teensy2: return "PABotBase-Teensy2.0"; + case PABB_PID_PABOTBASE_TeensyPP2: return "PABotBase-Teensy++2.0"; + + case PABB_PID_PABOTBASE_CH552: return "PABotBase-CH552"; + + case PABB_PID_PABOTBASE_ESP32: return "PABotBase-ESP32"; + case PABB_PID_PABOTBASE_ESP32S3: return "PABotBase-ESP32-S3"; + + default: return "Unknown ID"; + } +} +ControllerType id_to_controller_type(uint32_t id){ + switch (id){ + case PABB_CID_NONE: + return ControllerType::None; + case PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER: + return ControllerType::NintendoSwitch_WiredProController; + case PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER: + return ControllerType::NintendoSwitch_WirelessProController; + case PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON: + return ControllerType::NintendoSwitch_LeftJoycon; + case PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON: + return ControllerType::NintendoSwitch_RightJoycon; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Controller ID: " + std::to_string(id) + ); +} +uint32_t controller_type_to_id(ControllerType controller_type){ + switch (controller_type){ + case ControllerType::None: + return PABB_CID_NONE; + case ControllerType::NintendoSwitch_WiredProController: + return PABB_CID_NINTENDO_SWITCH_WIRED_PRO_CONTROLLER; + case ControllerType::NintendoSwitch_WirelessProController: + return PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; + case ControllerType::NintendoSwitch_LeftJoycon: + return PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; + case ControllerType::NintendoSwitch_RightJoycon: + return PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid Controller Enum: " + std::to_string((int)controller_type) + ); +} + + + +const std::map< + uint32_t, // Protocol Version + std::map< + uint32_t, // Program ID + std::map + > +> SUPPORTED_VERSIONS{ + {2025061202, { + {PABB_PID_PABOTBASE_ESP32, { + {ControllerType::NintendoSwitch_WirelessProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + }}, + {ControllerType::NintendoSwitch_LeftJoycon, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_LeftJoycon, + }}, + {ControllerType::NintendoSwitch_RightJoycon, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_RightJoycon, + }}, + }}, + }}, + {2025061303, { + {PABB_PID_PABOTBASE_ESP32S3, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + }}, + {2025061403, { + {PABB_PID_PABOTBASE_ArduinoUnoR3, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_ArduinoLeonardo, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_ProMicro, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_Teensy2, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + {PABB_PID_PABOTBASE_TeensyPP2, { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }}, + }}, + }}, +}; + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h index e4aa6abf5a..0e789cb3c8 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase.h @@ -1,44 +1,44 @@ -/* Serial Port (PABotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_H -#define PokemonAutomation_Controllers_SerialPABotBase_H - -#include -#include -#include -#include "Controllers/ControllerCapability.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -// Defaults -extern const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS; - - - -std::string program_name(uint8_t id); -ControllerType id_to_controller_type(uint32_t id); -uint32_t controller_type_to_id(ControllerType controller_type); - - - -extern const std::map< - uint32_t, // Protocol Version - std::map< - uint32_t, // Program ID - std::map - > -> SUPPORTED_VERSIONS; - - - - -} -} -#endif +/* Serial Port (PABotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_H +#define PokemonAutomation_Controllers_SerialPABotBase_H + +#include +#include +#include +#include "Controllers/ControllerCapability.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +// Defaults +extern const ControllerFeatures OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS; + + + +std::string program_name(uint8_t id); +ControllerType id_to_controller_type(uint32_t id); +uint32_t controller_type_to_id(ControllerType controller_type); + + + +extern const std::map< + uint32_t, // Protocol Version + std::map< + uint32_t, // Program ID + std::map + > +> SUPPORTED_VERSIONS; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp index f199b69646..a6623bc29b 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.cpp @@ -1,304 +1,304 @@ -/* Serial Port (PABotBase) Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PanicDump.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "ClientSource/Connection/SerialConnection.h" -#include "ClientSource/Connection/PABotBase.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/ControllerTypeStrings.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "SerialPABotBase.h" -#include "SerialPABotBase_PostConnectActions.h" -#include "SerialPABotBase_Connection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - - -SerialPABotBase_Connection::SerialPABotBase_Connection( - Logger& logger, - const QSerialPortInfo* port, - std::optional change_controller -) - : m_logger(logger, GlobalSettings::instance().LOG_EVERYTHING) -{ - set_status_line0("Not Connected", COLOR_RED); - - // No port selected. - if (port == nullptr || port->isNull()){ - return; - } - - // Prolific is banned. - if (port->description().indexOf("Prolific") != -1){ - QMessageBox box; - box.critical( - nullptr, - "Error", - "Cannot select Prolific controller.

" - "Prolific controllers do not work for Arduino and similar microcontrollers.
" - "You were warned of this in the setup instructions. Please buy a CP210x controller instead." - ); - std::string text = "Cannot connect to Prolific controller."; - m_logger.log(text, COLOR_RED); - set_status_line0(text, COLOR_RED); - return; - } - - m_device_name = port->portName().toStdString(); - std::string error; - try{ - set_status_line0("Connecting...", COLOR_DARKGREEN); - std::unique_ptr connection(new SerialConnection(port->systemLocation().toStdString(), PABB_BAUD_RATE)); - m_botbase.reset(new PABotBase(m_logger, std::move(connection), nullptr)); - }catch (const ConnectionException& e){ - error = e.message(); - }catch (const SerialProtocolException& e){ - error = e.message(); - }catch (const ProgramCancelledException& e){ - error = e.message(); - } - if (!error.empty()){ - set_status_line0("Unable to open port.", COLOR_RED); - return; - } - - m_status_thread = std::thread( - run_with_catch, - "SerialPABotBase_Connection::thread_body()", - [=, this]{ thread_body(change_controller); } - ); -} -SerialPABotBase_Connection::~SerialPABotBase_Connection(){ - m_ready.store(false, std::memory_order_release); -// signal_pre_not_ready(); - if (m_botbase == nullptr){ - return; - } - m_botbase->stop(); - { - std::lock_guard lg(m_lock); - m_cv.notify_all(); - } - if (m_status_thread.joinable()){ - m_status_thread.join(); - } - m_botbase.reset(); -} - - - -BotBaseController* SerialPABotBase_Connection::botbase(){ - BotBaseController* ret = m_botbase.get(); - if (ret == nullptr){ - m_logger.log("SerialPABotBase_Connection::botbase() called with null botbase...", COLOR_RED); - } - return ret; -} - - - -ControllerModeStatus SerialPABotBase_Connection::controller_mode_status() const{ - std::lock_guard lg(m_lock); - return m_mode_status; -} - - - -const std::map>& -SerialPABotBase_Connection::get_programs_for_protocol(uint32_t protocol){ - // (protocol_requested / 100) == (protocol_device / 100) - // (protocol_requested % 100) <= (protocol_device % 100) - auto iter = SUPPORTED_VERSIONS.upper_bound(protocol); - if (iter == SUPPORTED_VERSIONS.begin()){ - throw SerialProtocolException( - m_logger, PA_CURRENT_FUNCTION, - "Incompatible protocol. Device: " + std::to_string(protocol) + "
" - "Please flash the .hex/.bin that came with this version of the program." - ); - } - --iter; - if (iter->first < protocol / 100 * 100){ - throw SerialProtocolException( - m_logger, PA_CURRENT_FUNCTION, - "Incompatible protocol. Device: " + std::to_string(protocol) + "
" - "Please flash the .hex/.bin that came with this version of the program." - ); - } - - return iter->second; -} - -const std::map& -SerialPABotBase_Connection::get_controllers_for_program( - const std::map>& available_programs, - uint32_t program_id -){ - auto iter = available_programs.find(program_id); - if (iter == available_programs.end()){ - throw SerialProtocolException( - m_logger, PA_CURRENT_FUNCTION, - "Unrecognized Program ID: " + std::to_string(program_id) + "
" - "Please install the firmware that came with this version of the program." - ); - } - return iter->second; -} - -void SerialPABotBase_Connection::process_queue_size(){ - m_logger.log("Requesting queue size..."); - uint8_t queue_size = device_queue_size(*m_botbase); - m_logger.Logger::log("Requesting queue size... Queue Size = " + std::to_string(queue_size)); - - // For now we don't need to use that much queue size. - queue_size = std::min(queue_size, 32); - - m_logger.Logger::log("Setting queue size to: " + std::to_string(queue_size)); - m_botbase->set_queue_limit(queue_size); -} -ControllerType SerialPABotBase_Connection::get_controller_type( - const std::map& available_controllers -){ - m_logger.log("Reading Controller Mode..."); - ControllerType current_controller = ControllerType::None; - if (available_controllers.size() == 1){ - current_controller = available_controllers.begin()->first; - }else if (available_controllers.size() > 1){ - uint32_t type_id = read_controller_mode(*m_botbase); - current_controller = id_to_controller_type(type_id); - } - m_logger.Logger::log("Reading Controller Mode... Mode = " + CONTROLLER_TYPE_STRINGS.get_string(current_controller)); - return current_controller; -} - - - -ControllerModeStatus SerialPABotBase_Connection::read_device_specs( - std::optional change_controller -){ - // Protocol - { - m_logger.Logger::log("Checking Protocol Version..."); - m_protocol = protocol_version(*m_botbase); - m_logger.Logger::log("Checking Protocol Version... Protocol = " + std::to_string(m_protocol)); - } - const std::map>& PROGRAMS = - get_programs_for_protocol(m_protocol); - - - // Program ID - { - m_logger.Logger::log("Checking Program ID..."); - m_program_id = program_id(*m_botbase); - m_logger.Logger::log("Checking Program ID... Program ID = " + std::to_string(m_program_id)); - } - const std::map& CONTROLLERS = - get_controllers_for_program(PROGRAMS, m_program_id); - - // Firmware Version - { - m_logger.Logger::log("Checking Firmware Version..."); - m_version = program_version(*m_botbase); - m_logger.Logger::log("Checking Firmware Version... Version = " + std::to_string(m_version)); - } - - // Queue Size - process_queue_size(); - - // Controller Type - ControllerType current_controller = get_controller_type(CONTROLLERS); - - // Run any post-connection actions specific to this program. - ControllerModeStatus ret{current_controller, CONTROLLERS}; - run_post_connect_actions( - ret, - m_program_id, m_device_name, - *m_botbase, - change_controller - ); - return ret; -} - - - -void SerialPABotBase_Connection::thread_body( - std::optional change_controller -){ - using namespace PokemonAutomation; - - m_botbase->set_sniffer(&m_logger); - - // Connect - { - std::string error; - try{ - m_botbase->connect(); - }catch (InvalidConnectionStateException&){ - m_botbase->stop(); - set_status_line0(""); - return; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - } - if (!error.empty()){ - m_botbase->stop(); - set_status_line0(error, COLOR_RED); - return; - } - } - - // Check protocol and version. - { - ControllerModeStatus mode_status; - std::string error; - try{ - mode_status = read_device_specs(change_controller); - std::lock_guard lg(m_lock); - m_mode_status = mode_status; - - // Stop pending commands. - m_botbase->stop_all_commands(); - }catch (InvalidConnectionStateException&){ - return; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - } - if (error.empty()){ -// std::string text = "Program: " + program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; - std::string text = program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; - set_status_line0(text, theme_friendly_darkblue()); - declare_ready(mode_status); - }else{ - m_ready.store(false, std::memory_order_relaxed); - set_status_line0(error, COLOR_RED); -// signal_pre_not_ready(); - m_botbase->stop(); - return; - } - } -} - - - -} -} +/* Serial Port (PABotBase) Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PanicDump.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "ClientSource/Connection/SerialConnection.h" +#include "ClientSource/Connection/PABotBase.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/ControllerTypeStrings.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "SerialPABotBase.h" +#include "SerialPABotBase_PostConnectActions.h" +#include "SerialPABotBase_Connection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + + +SerialPABotBase_Connection::SerialPABotBase_Connection( + Logger& logger, + const QSerialPortInfo* port, + std::optional change_controller +) + : m_logger(logger, GlobalSettings::instance().LOG_EVERYTHING) +{ + set_status_line0("Not Connected", COLOR_RED); + + // No port selected. + if (port == nullptr || port->isNull()){ + return; + } + + // Prolific is banned. + if (port->description().indexOf("Prolific") != -1){ + QMessageBox box; + box.critical( + nullptr, + "Error", + "Cannot select Prolific controller.

" + "Prolific controllers do not work for Arduino and similar microcontrollers.
" + "You were warned of this in the setup instructions. Please buy a CP210x controller instead." + ); + std::string text = "Cannot connect to Prolific controller."; + m_logger.log(text, COLOR_RED); + set_status_line0(text, COLOR_RED); + return; + } + + m_device_name = port->portName().toStdString(); + std::string error; + try{ + set_status_line0("Connecting...", COLOR_DARKGREEN); + std::unique_ptr connection(new SerialConnection(port->systemLocation().toStdString(), PABB_BAUD_RATE)); + m_botbase.reset(new PABotBase(m_logger, std::move(connection), nullptr)); + }catch (const ConnectionException& e){ + error = e.message(); + }catch (const SerialProtocolException& e){ + error = e.message(); + }catch (const ProgramCancelledException& e){ + error = e.message(); + } + if (!error.empty()){ + set_status_line0("Unable to open port.", COLOR_RED); + return; + } + + m_status_thread = std::thread( + run_with_catch, + "SerialPABotBase_Connection::thread_body()", + [=, this]{ thread_body(change_controller); } + ); +} +SerialPABotBase_Connection::~SerialPABotBase_Connection(){ + m_ready.store(false, std::memory_order_release); +// signal_pre_not_ready(); + if (m_botbase == nullptr){ + return; + } + m_botbase->stop(); + { + std::lock_guard lg(m_lock); + m_cv.notify_all(); + } + if (m_status_thread.joinable()){ + m_status_thread.join(); + } + m_botbase.reset(); +} + + + +BotBaseController* SerialPABotBase_Connection::botbase(){ + BotBaseController* ret = m_botbase.get(); + if (ret == nullptr){ + m_logger.log("SerialPABotBase_Connection::botbase() called with null botbase...", COLOR_RED); + } + return ret; +} + + + +ControllerModeStatus SerialPABotBase_Connection::controller_mode_status() const{ + std::lock_guard lg(m_lock); + return m_mode_status; +} + + + +const std::map>& +SerialPABotBase_Connection::get_programs_for_protocol(uint32_t protocol){ + // (protocol_requested / 100) == (protocol_device / 100) + // (protocol_requested % 100) <= (protocol_device % 100) + auto iter = SUPPORTED_VERSIONS.upper_bound(protocol); + if (iter == SUPPORTED_VERSIONS.begin()){ + throw SerialProtocolException( + m_logger, PA_CURRENT_FUNCTION, + "Incompatible protocol. Device: " + std::to_string(protocol) + "
" + "Please flash the .hex/.bin that came with this version of the program." + ); + } + --iter; + if (iter->first < protocol / 100 * 100){ + throw SerialProtocolException( + m_logger, PA_CURRENT_FUNCTION, + "Incompatible protocol. Device: " + std::to_string(protocol) + "
" + "Please flash the .hex/.bin that came with this version of the program." + ); + } + + return iter->second; +} + +const std::map& +SerialPABotBase_Connection::get_controllers_for_program( + const std::map>& available_programs, + uint32_t program_id +){ + auto iter = available_programs.find(program_id); + if (iter == available_programs.end()){ + throw SerialProtocolException( + m_logger, PA_CURRENT_FUNCTION, + "Unrecognized Program ID: " + std::to_string(program_id) + "
" + "Please install the firmware that came with this version of the program." + ); + } + return iter->second; +} + +void SerialPABotBase_Connection::process_queue_size(){ + m_logger.log("Requesting queue size..."); + uint8_t queue_size = device_queue_size(*m_botbase); + m_logger.Logger::log("Requesting queue size... Queue Size = " + std::to_string(queue_size)); + + // For now we don't need to use that much queue size. + queue_size = std::min(queue_size, 32); + + m_logger.Logger::log("Setting queue size to: " + std::to_string(queue_size)); + m_botbase->set_queue_limit(queue_size); +} +ControllerType SerialPABotBase_Connection::get_controller_type( + const std::map& available_controllers +){ + m_logger.log("Reading Controller Mode..."); + ControllerType current_controller = ControllerType::None; + if (available_controllers.size() == 1){ + current_controller = available_controllers.begin()->first; + }else if (available_controllers.size() > 1){ + uint32_t type_id = read_controller_mode(*m_botbase); + current_controller = id_to_controller_type(type_id); + } + m_logger.Logger::log("Reading Controller Mode... Mode = " + CONTROLLER_TYPE_STRINGS.get_string(current_controller)); + return current_controller; +} + + + +ControllerModeStatus SerialPABotBase_Connection::read_device_specs( + std::optional change_controller +){ + // Protocol + { + m_logger.Logger::log("Checking Protocol Version..."); + m_protocol = protocol_version(*m_botbase); + m_logger.Logger::log("Checking Protocol Version... Protocol = " + std::to_string(m_protocol)); + } + const std::map>& PROGRAMS = + get_programs_for_protocol(m_protocol); + + + // Program ID + { + m_logger.Logger::log("Checking Program ID..."); + m_program_id = program_id(*m_botbase); + m_logger.Logger::log("Checking Program ID... Program ID = " + std::to_string(m_program_id)); + } + const std::map& CONTROLLERS = + get_controllers_for_program(PROGRAMS, m_program_id); + + // Firmware Version + { + m_logger.Logger::log("Checking Firmware Version..."); + m_version = program_version(*m_botbase); + m_logger.Logger::log("Checking Firmware Version... Version = " + std::to_string(m_version)); + } + + // Queue Size + process_queue_size(); + + // Controller Type + ControllerType current_controller = get_controller_type(CONTROLLERS); + + // Run any post-connection actions specific to this program. + ControllerModeStatus ret{current_controller, CONTROLLERS}; + run_post_connect_actions( + ret, + m_program_id, m_device_name, + *m_botbase, + change_controller + ); + return ret; +} + + + +void SerialPABotBase_Connection::thread_body( + std::optional change_controller +){ + using namespace PokemonAutomation; + + m_botbase->set_sniffer(&m_logger); + + // Connect + { + std::string error; + try{ + m_botbase->connect(); + }catch (InvalidConnectionStateException&){ + m_botbase->stop(); + set_status_line0(""); + return; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + } + if (!error.empty()){ + m_botbase->stop(); + set_status_line0(error, COLOR_RED); + return; + } + } + + // Check protocol and version. + { + ControllerModeStatus mode_status; + std::string error; + try{ + mode_status = read_device_specs(change_controller); + std::lock_guard lg(m_lock); + m_mode_status = mode_status; + + // Stop pending commands. + m_botbase->stop_all_commands(); + }catch (InvalidConnectionStateException&){ + return; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + } + if (error.empty()){ +// std::string text = "Program: " + program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; + std::string text = program_name(m_program_id) + " (" + std::to_string(m_version) + ")"; + set_status_line0(text, theme_friendly_darkblue()); + declare_ready(mode_status); + }else{ + m_ready.store(false, std::memory_order_relaxed); + set_status_line0(error, COLOR_RED); +// signal_pre_not_ready(); + m_botbase->stop(); + return; + } + } +} + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h index d868014235..71b7dbbfc4 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Connection.h @@ -1,89 +1,89 @@ -/* Serial Port (PABotBase) Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_Connection_H -#define PokemonAutomation_Controllers_SerialPABotBase_Connection_H - -#include -#include -#include -#include -#include "ClientSource/Connection/BotBase.h" -#include "ClientSource/Connection/MessageLogger.h" -#include "Controllers/ControllerConnection.h" - -class QSerialPortInfo; - -namespace PokemonAutomation{ - class PABotBase; -namespace SerialPABotBase{ - - -class SerialPABotBase_Connection : public ControllerConnection{ -public: - SerialPABotBase_Connection( - Logger& logger, - const QSerialPortInfo* port, - std::optional change_controller - ); - ~SerialPABotBase_Connection(); - - -public: -// uint8_t program_id() const{ -// return m_program_id; -// } - BotBaseController* botbase(); - -public: - virtual ControllerModeStatus controller_mode_status() const override; - - -private: - const std::map>& - get_programs_for_protocol(uint32_t protocol); - - const std::map& - get_controllers_for_program( - const std::map>& available_programs, - uint32_t program_id - ); - - void process_queue_size(); - ControllerType get_controller_type( - const std::map& available_controllers - ); - - ControllerModeStatus read_device_specs( - std::optional change_controller - ); - - void thread_body( - std::optional change_controller - ); - - -private: - SerialLogger m_logger; - std::string m_device_name; - - uint32_t m_protocol = 0; - uint32_t m_version = 0; - uint8_t m_program_id = 0; - ControllerModeStatus m_mode_status; - - std::thread m_status_thread; - std::unique_ptr m_botbase; - mutable std::mutex m_lock; - std::mutex m_sleep_lock; - std::condition_variable m_cv; -}; - - - -} -} -#endif +/* Serial Port (PABotBase) Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_Connection_H +#define PokemonAutomation_Controllers_SerialPABotBase_Connection_H + +#include +#include +#include +#include +#include "ClientSource/Connection/BotBase.h" +#include "ClientSource/Connection/MessageLogger.h" +#include "Controllers/ControllerConnection.h" + +class QSerialPortInfo; + +namespace PokemonAutomation{ + class PABotBase; +namespace SerialPABotBase{ + + +class SerialPABotBase_Connection : public ControllerConnection{ +public: + SerialPABotBase_Connection( + Logger& logger, + const QSerialPortInfo* port, + std::optional change_controller + ); + ~SerialPABotBase_Connection(); + + +public: +// uint8_t program_id() const{ +// return m_program_id; +// } + BotBaseController* botbase(); + +public: + virtual ControllerModeStatus controller_mode_status() const override; + + +private: + const std::map>& + get_programs_for_protocol(uint32_t protocol); + + const std::map& + get_controllers_for_program( + const std::map>& available_programs, + uint32_t program_id + ); + + void process_queue_size(); + ControllerType get_controller_type( + const std::map& available_controllers + ); + + ControllerModeStatus read_device_specs( + std::optional change_controller + ); + + void thread_body( + std::optional change_controller + ); + + +private: + SerialLogger m_logger; + std::string m_device_name; + + uint32_t m_protocol = 0; + uint32_t m_version = 0; + uint8_t m_program_id = 0; + ControllerModeStatus m_mode_status; + + std::thread m_status_thread; + std::unique_ptr m_botbase; + mutable std::mutex m_lock; + std::mutex m_sleep_lock; + std::condition_variable m_cv; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp index ef26168061..aefa687f28 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.cpp @@ -1,118 +1,118 @@ -/* Serial Port (PABotBase) Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Controllers/ControllerTypeStrings.h" -#include "SerialPABotBase_Descriptor.h" -#include "SerialPABotBase_SelectorWidget.h" - -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -template class InterfaceType_t; - -namespace SerialPABotBase{ - - - - -bool SerialPABotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_port.portName() == static_cast(x).m_port.portName(); -} - - -std::string SerialPABotBase_Descriptor::display_name() const{ - if (m_port.isNull()){ - return ""; - } -// if (PreloadSettings::instance().DEVELOPER_MODE){ - return m_port.portName().toStdString(); -// } -// return m_port.portName().toStdString() + " - " + m_port.description().toStdString(); -} -void SerialPABotBase_Descriptor::load_json(const JsonValue& json){ - const std::string* name = json.to_string(); - if (name == nullptr || name->empty()){ - return; - } - m_port = (QSerialPortInfo(QString::fromStdString(*name))); -} -JsonValue SerialPABotBase_Descriptor::to_json() const{ - return m_port.isNull() ? "" : m_port.portName().toStdString(); -} - -std::unique_ptr SerialPABotBase_Descriptor::open_connection( - Logger& logger, - std::optional change_controller -) const{ - return std::unique_ptr( - new SerialPABotBase_Connection(logger, &m_port, change_controller) - ); -} -std::unique_ptr SerialPABotBase_Descriptor::make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type -) const{ - switch (controller_type){ - case ControllerType::NintendoSwitch_WiredProController: - return std::unique_ptr( - new PokemonAutomation::NintendoSwitch::SerialPABotBase_PokkenController( - logger, - static_cast(connection) - ) - ); - - case ControllerType::NintendoSwitch_WirelessProController: - return std::unique_ptr( - new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessProController( - logger, - static_cast(connection) - ) - ); - - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon: - return std::unique_ptr( - new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessJoycon( - logger, - static_cast(connection), - controller_type - ) - ); - - default:; - } - - logger.log( - std::string("Unsupported Controller Type: ") + CONTROLLER_TYPE_STRINGS.get_string(controller_type), - COLOR_RED - ); - return nullptr; -} - - - -QWidget* SerialPABotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ - return new SerialPABotBase_SelectorWidget(parent, this); -} - - - - -} -} +/* Serial Port (PABotBase) Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Controllers/ControllerTypeStrings.h" +#include "SerialPABotBase_Descriptor.h" +#include "SerialPABotBase_SelectorWidget.h" + +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h" +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +template class InterfaceType_t; + +namespace SerialPABotBase{ + + + + +bool SerialPABotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_port.portName() == static_cast(x).m_port.portName(); +} + + +std::string SerialPABotBase_Descriptor::display_name() const{ + if (m_port.isNull()){ + return ""; + } +// if (PreloadSettings::instance().DEVELOPER_MODE){ + return m_port.portName().toStdString(); +// } +// return m_port.portName().toStdString() + " - " + m_port.description().toStdString(); +} +void SerialPABotBase_Descriptor::load_json(const JsonValue& json){ + const std::string* name = json.to_string(); + if (name == nullptr || name->empty()){ + return; + } + m_port = (QSerialPortInfo(QString::fromStdString(*name))); +} +JsonValue SerialPABotBase_Descriptor::to_json() const{ + return m_port.isNull() ? "" : m_port.portName().toStdString(); +} + +std::unique_ptr SerialPABotBase_Descriptor::open_connection( + Logger& logger, + std::optional change_controller +) const{ + return std::unique_ptr( + new SerialPABotBase_Connection(logger, &m_port, change_controller) + ); +} +std::unique_ptr SerialPABotBase_Descriptor::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type +) const{ + switch (controller_type){ + case ControllerType::NintendoSwitch_WiredProController: + return std::unique_ptr( + new PokemonAutomation::NintendoSwitch::SerialPABotBase_PokkenController( + logger, + static_cast(connection) + ) + ); + + case ControllerType::NintendoSwitch_WirelessProController: + return std::unique_ptr( + new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessProController( + logger, + static_cast(connection) + ) + ); + + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon: + return std::unique_ptr( + new PokemonAutomation::NintendoSwitch::SerialPABotBase_WirelessJoycon( + logger, + static_cast(connection), + controller_type + ) + ); + + default:; + } + + logger.log( + std::string("Unsupported Controller Type: ") + CONTROLLER_TYPE_STRINGS.get_string(controller_type), + COLOR_RED + ); + return nullptr; +} + + + +QWidget* SerialPABotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ + return new SerialPABotBase_SelectorWidget(parent, this); +} + + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h index 694e8e26bc..10a9d70805 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Descriptor.h @@ -1,62 +1,62 @@ -/* Serial Port (PABotBase) Interface - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H -#define PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H - -#include -#include "Controllers/ControllerDescriptor.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -class SerialPABotBase_Descriptor : public ControllerDescriptor{ -public: - static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::SerialPABotBase; - - -public: - SerialPABotBase_Descriptor() - : ControllerDescriptor(INTERFACE_NAME) - {} - SerialPABotBase_Descriptor(const QSerialPortInfo& info) - : ControllerDescriptor(INTERFACE_NAME) - , m_port(info) - {} - - const QSerialPortInfo& port() const{ - return m_port; - } - - virtual bool operator==(const ControllerDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const override; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const override; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; - -private: - QSerialPortInfo m_port; -}; - - - -} -} -#endif +/* Serial Port (PABotBase) Interface + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H +#define PokemonAutomation_Controllers_SerialPABotBase_Descriptor_H + +#include +#include "Controllers/ControllerDescriptor.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +class SerialPABotBase_Descriptor : public ControllerDescriptor{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::SerialPABotBase; + + +public: + SerialPABotBase_Descriptor() + : ControllerDescriptor(INTERFACE_NAME) + {} + SerialPABotBase_Descriptor(const QSerialPortInfo& info) + : ControllerDescriptor(INTERFACE_NAME) + , m_port(info) + {} + + const QSerialPortInfo& port() const{ + return m_port; + } + + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; + +private: + QSerialPortInfo m_port; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp index e010c576df..4402953122 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.cpp @@ -1,144 +1,144 @@ -/* Serial Port (PABotBase) Post-Connect Actinos - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "ClientSource/Connection/PABotBase.h" -#include "Controllers/ControllerTypeStrings.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "SerialPABotBase_Routines_Protocol.h" -#include "SerialPABotBase_Routines_ESP32.h" -#include "SerialPABotBase.h" -#include "SerialPABotBase_PostConnectActions.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -void run_post_connect_actions_ESP32( - ControllerModeStatus& status, - const std::string& device_name, - PABotBase& botbase, - std::optional change_controller -){ - if (!change_controller){ - return; - } - - Logger& logger = botbase.logger(); - - ControllerType desired_controller = change_controller.value(); - switch (desired_controller){ - case ControllerType::NintendoSwitch_WiredProController: - case ControllerType::NintendoSwitch_WirelessProController: - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon:{ - uint8_t controller_mac_address[6] = {}; - { - BotBaseMessage response = botbase.issue_request_and_wait( - MessageControllerReadSpi( - desired_controller, - 0x80000000, sizeof(controller_mac_address) - ), - nullptr - ); - if (response.body.size() == sizeof(seqnum_t) + sizeof(controller_mac_address)){ - memcpy( - controller_mac_address, - response.body.data() + sizeof(seqnum_t), - sizeof(controller_mac_address) - ); - }else{ - logger.log( - "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), - COLOR_RED - ); - } - } - - NintendoSwitch::ControllerProfile profile = - PokemonAutomation::NintendoSwitch::ConsoleSettings::instance().CONTROLLER_SETTINGS.get_or_make_profile( - controller_mac_address, - device_name, - desired_controller - ); - - PABB_NintendoSwitch_ControllerColors colors; - { - Color color(profile.body_color); - colors.body[0] = color.red(); - colors.body[1] = color.green(); - colors.body[2] = color.blue(); - } - { - Color color(profile.button_color); - colors.buttons[0] = color.red(); - colors.buttons[1] = color.green(); - colors.buttons[2] = color.blue(); - } - { - Color color(profile.left_grip); - colors.left_grip[0] = color.red(); - colors.left_grip[1] = color.green(); - colors.left_grip[2] = color.blue(); - } - { - Color color(profile.right_grip); - colors.right_grip[0] = color.red(); - colors.right_grip[1] = color.green(); - colors.right_grip[2] = color.blue(); - } - - botbase.issue_request_and_wait( - MessageControllerWriteSpi( - desired_controller, - 0x00006050, sizeof(PABB_NintendoSwitch_ControllerColors), - &colors - ), - nullptr - ); - } - default:; - } - - - uint32_t native_controller_id = controller_type_to_id(desired_controller); - botbase.issue_request_and_wait( - DeviceRequest_change_controller_mode(native_controller_id), - nullptr - ); - - // Re-read the controller. - logger.log("Reading Controller Mode..."); - uint32_t type_id = read_controller_mode(botbase); - status.current_controller = id_to_controller_type(type_id); - logger.log( - "Reading Controller Mode... Mode = " + - CONTROLLER_TYPE_STRINGS.get_string(status.current_controller) - ); -} - - - - -void run_post_connect_actions( - ControllerModeStatus& status, - uint32_t program_id, const std::string& device_name, - PABotBase& botbase, - std::optional change_controller -){ - switch (program_id){ - case PABB_PID_PABOTBASE_ESP32: - run_post_connect_actions_ESP32(status, device_name, botbase, change_controller); - return; - } -} - - - - -} -} +/* Serial Port (PABotBase) Post-Connect Actinos + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "ClientSource/Connection/PABotBase.h" +#include "Controllers/ControllerTypeStrings.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "SerialPABotBase_Routines_Protocol.h" +#include "SerialPABotBase_Routines_ESP32.h" +#include "SerialPABotBase.h" +#include "SerialPABotBase_PostConnectActions.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +void run_post_connect_actions_ESP32( + ControllerModeStatus& status, + const std::string& device_name, + PABotBase& botbase, + std::optional change_controller +){ + if (!change_controller){ + return; + } + + Logger& logger = botbase.logger(); + + ControllerType desired_controller = change_controller.value(); + switch (desired_controller){ + case ControllerType::NintendoSwitch_WiredProController: + case ControllerType::NintendoSwitch_WirelessProController: + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon:{ + uint8_t controller_mac_address[6] = {}; + { + BotBaseMessage response = botbase.issue_request_and_wait( + MessageControllerReadSpi( + desired_controller, + 0x80000000, sizeof(controller_mac_address) + ), + nullptr + ); + if (response.body.size() == sizeof(seqnum_t) + sizeof(controller_mac_address)){ + memcpy( + controller_mac_address, + response.body.data() + sizeof(seqnum_t), + sizeof(controller_mac_address) + ); + }else{ + logger.log( + "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), + COLOR_RED + ); + } + } + + NintendoSwitch::ControllerProfile profile = + PokemonAutomation::NintendoSwitch::ConsoleSettings::instance().CONTROLLER_SETTINGS.get_or_make_profile( + controller_mac_address, + device_name, + desired_controller + ); + + PABB_NintendoSwitch_ControllerColors colors; + { + Color color(profile.body_color); + colors.body[0] = color.red(); + colors.body[1] = color.green(); + colors.body[2] = color.blue(); + } + { + Color color(profile.button_color); + colors.buttons[0] = color.red(); + colors.buttons[1] = color.green(); + colors.buttons[2] = color.blue(); + } + { + Color color(profile.left_grip); + colors.left_grip[0] = color.red(); + colors.left_grip[1] = color.green(); + colors.left_grip[2] = color.blue(); + } + { + Color color(profile.right_grip); + colors.right_grip[0] = color.red(); + colors.right_grip[1] = color.green(); + colors.right_grip[2] = color.blue(); + } + + botbase.issue_request_and_wait( + MessageControllerWriteSpi( + desired_controller, + 0x00006050, sizeof(PABB_NintendoSwitch_ControllerColors), + &colors + ), + nullptr + ); + } + default:; + } + + + uint32_t native_controller_id = controller_type_to_id(desired_controller); + botbase.issue_request_and_wait( + DeviceRequest_change_controller_mode(native_controller_id), + nullptr + ); + + // Re-read the controller. + logger.log("Reading Controller Mode..."); + uint32_t type_id = read_controller_mode(botbase); + status.current_controller = id_to_controller_type(type_id); + logger.log( + "Reading Controller Mode... Mode = " + + CONTROLLER_TYPE_STRINGS.get_string(status.current_controller) + ); +} + + + + +void run_post_connect_actions( + ControllerModeStatus& status, + uint32_t program_id, const std::string& device_name, + PABotBase& botbase, + std::optional change_controller +){ + switch (program_id){ + case PABB_PID_PABOTBASE_ESP32: + run_post_connect_actions_ESP32(status, device_name, botbase, change_controller); + return; + } +} + + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h index f62dc9f308..326cb19be5 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_PostConnectActions.h @@ -1,29 +1,29 @@ -/* Serial Port (PABotBase) Post-Connect Actinos - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H -#define PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H - -#include "Controllers/ControllerConnection.h" - -namespace PokemonAutomation{ - class PABotBase; -namespace SerialPABotBase{ - - -void run_post_connect_actions( - ControllerModeStatus& status, - uint32_t program_id, const std::string& device_name, - PABotBase& botbase, - std::optional change_controller -); - - - - -} -} -#endif +/* Serial Port (PABotBase) Post-Connect Actinos + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H +#define PokemonAutomation_Controllers_SerialPABotBase_PostConnectActions_H + +#include "Controllers/ControllerConnection.h" + +namespace PokemonAutomation{ + class PABotBase; +namespace SerialPABotBase{ + + +void run_post_connect_actions( + ControllerModeStatus& status, + uint32_t program_id, const std::string& device_name, + PABotBase& botbase, + std::optional change_controller +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp index 971602e548..cabfb85022 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.cpp @@ -1,145 +1,145 @@ -/* SerialPABotBase ESP32 Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -int register_message_converters_ESP32(){ - register_message_converter( - PABB_MSG_REQUEST_STATUS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "PABB_MSG_REQUEST_STATUS() - "; - if (body.size() != sizeof(pabb_Message_RequestStatus)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_RequestStatus*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_REQUEST_READ_SPI, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_READ_SPI() - "; - if (body.size() != sizeof(pabb_Message_ESP32_ReadSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_ReadSpi*)body.c_str(); - ss << "seqnum = " << params->seqnum; - ss << ", controller = " << params->controller_type; - ss << ", address = 0x" << tostr_hex(params->address); - ss << ", bytes = " << (size_t)params->bytes; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_REQUEST_WRITE_SPI, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_WRITE_SPI() - "; - if (body.size() <= sizeof(pabb_Message_ESP32_WriteSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_WriteSpi*)body.c_str(); - ss << "seqnum = " << params->seqnum; - ss << ", controller = " << params->controller_type; - ss << ", address = 0x" << tostr_hex(params->address); - ss << ", bytes = " << (size_t)params->bytes; - return ss.str(); - } - ); -#if 0 - register_message_converter( - PABB_MSG_ESP32_REQUEST_GET_COLORS, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_GET_COLORS() - "; - if (body.size() != sizeof(pabb_Message_ESP32_GetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_GetColors*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", controller = " << (uint64_t)params->controller_type; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_REQUEST_SET_COLORS, - [](const std::string& body){ - std::ostringstream ss; - ss << "PABB_MSG_ESP32_REQUEST_SET_COLORS() - "; - if (body.size() != sizeof(pabb_Message_ESP32_SetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_SetColors*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - return ss.str(); - } - ); -#endif - register_message_converter( - PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS() - "; - if (body.size() != sizeof(pabb_Message_ESP32_CommandButtonState)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_CommandButtonState*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", milliseconds = " << params->milliseconds; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_ESP32_CONTROLLER_STATE_FULL, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "PABB_MSG_ESP32_CONTROLLER_STATE_FULL() - "; - if (body.size() != sizeof(pabb_Message_ESP32_CommandFullState)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_ESP32_CommandFullState*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", milliseconds = " << params->milliseconds; - return ss.str(); - } - ); -#if 0 - register_message_converter( - PABB_MSG_ESP32_REPORT, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "ESP32_controller_state() - "; - if (body.size() != sizeof(pabb_esp32_report30)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_esp32_report30*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", ticks = " << (int)params->ticks; - ss << ", active = " << (int)params->active; - return ss.str(); - } - ); -#endif - return 0; -} -int init_Messages_ESP32 = register_message_converters_ESP32(); - - - -} -} +/* SerialPABotBase ESP32 Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +int register_message_converters_ESP32(){ + register_message_converter( + PABB_MSG_REQUEST_STATUS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "PABB_MSG_REQUEST_STATUS() - "; + if (body.size() != sizeof(pabb_Message_RequestStatus)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_RequestStatus*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_REQUEST_READ_SPI, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_READ_SPI() - "; + if (body.size() != sizeof(pabb_Message_ESP32_ReadSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_ReadSpi*)body.c_str(); + ss << "seqnum = " << params->seqnum; + ss << ", controller = " << params->controller_type; + ss << ", address = 0x" << tostr_hex(params->address); + ss << ", bytes = " << (size_t)params->bytes; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_REQUEST_WRITE_SPI, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_WRITE_SPI() - "; + if (body.size() <= sizeof(pabb_Message_ESP32_WriteSpi)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_WriteSpi*)body.c_str(); + ss << "seqnum = " << params->seqnum; + ss << ", controller = " << params->controller_type; + ss << ", address = 0x" << tostr_hex(params->address); + ss << ", bytes = " << (size_t)params->bytes; + return ss.str(); + } + ); +#if 0 + register_message_converter( + PABB_MSG_ESP32_REQUEST_GET_COLORS, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_GET_COLORS() - "; + if (body.size() != sizeof(pabb_Message_ESP32_GetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_GetColors*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", controller = " << (uint64_t)params->controller_type; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_REQUEST_SET_COLORS, + [](const std::string& body){ + std::ostringstream ss; + ss << "PABB_MSG_ESP32_REQUEST_SET_COLORS() - "; + if (body.size() != sizeof(pabb_Message_ESP32_SetColors)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_SetColors*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + return ss.str(); + } + ); +#endif + register_message_converter( + PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS() - "; + if (body.size() != sizeof(pabb_Message_ESP32_CommandButtonState)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_CommandButtonState*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", milliseconds = " << params->milliseconds; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_ESP32_CONTROLLER_STATE_FULL, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "PABB_MSG_ESP32_CONTROLLER_STATE_FULL() - "; + if (body.size() != sizeof(pabb_Message_ESP32_CommandFullState)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_ESP32_CommandFullState*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", milliseconds = " << params->milliseconds; + return ss.str(); + } + ); +#if 0 + register_message_converter( + PABB_MSG_ESP32_REPORT, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "ESP32_controller_state() - "; + if (body.size() != sizeof(pabb_esp32_report30)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_esp32_report30*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", ticks = " << (int)params->ticks; + ss << ", active = " << (int)params->active; + return ss.str(); + } + ); +#endif + return 0; +} +int init_Messages_ESP32 = register_message_converters_ESP32(); + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h index 64e6d04e98..7bce06a7e9 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h @@ -1,122 +1,122 @@ -/* SerialPABotBase ESP32 Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_ESP32_Routines_H -#define PokemonAutomation_SerialPABotBase_ESP32_Routines_H - -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "ClientSource/Connection/BotBaseMessage.h" -#include "Controllers/ControllerTypes.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - -class MessageControllerReadSpi : public BotBaseRequest{ -public: - pabb_Message_ESP32_ReadSpi params; - MessageControllerReadSpi(ControllerType controller_type, uint32_t address, uint8_t bytes) - : BotBaseRequest(false) - { - uint32_t controller_id = PABB_CID_NONE; - switch (controller_type){ - case ControllerType::NintendoSwitch_WirelessProController: - controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; - break; - case ControllerType::NintendoSwitch_LeftJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; - break; - case ControllerType::NintendoSwitch_RightJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; - break; - default:; - } - params.seqnum = 0; - params.controller_type = controller_id; - params.address = address; - params.bytes = bytes; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_REQUEST_READ_SPI, params); - } -}; -class MessageControllerWriteSpi : public BotBaseRequest{ -public: - std::string data; - MessageControllerWriteSpi( - ControllerType controller_type, - uint32_t address, uint8_t bytes, - const void* p_data - ) - : BotBaseRequest(false) - { - uint32_t controller_id = PABB_CID_NONE; - switch (controller_type){ - case ControllerType::NintendoSwitch_WirelessProController: - controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; - break; - case ControllerType::NintendoSwitch_LeftJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; - break; - case ControllerType::NintendoSwitch_RightJoycon: - controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; - break; - default:; - } - pabb_Message_ESP32_WriteSpi params; - params.seqnum = 0; - params.controller_type = controller_id; - params.address = address; - params.bytes = bytes; - data = std::string((char*)¶ms, sizeof(params)); - data += std::string((const char*)p_data, bytes); - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_REQUEST_WRITE_SPI, data); - } -}; -class MessageControllerStateButtons : public BotBaseRequest{ -public: - pabb_Message_ESP32_CommandButtonState params; - MessageControllerStateButtons(uint16_t milliseconds, const PABB_NintendoSwitch_ButtonState& state) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.milliseconds = milliseconds; - params.buttons = state; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, params); - } -}; -class MessageControllerStateFull : public BotBaseRequest{ -public: - pabb_Message_ESP32_CommandFullState params; - MessageControllerStateFull( - uint16_t milliseconds, - const PABB_NintendoSwitch_ButtonState& buttons, - const PABB_NintendoSwitch_GyroStateX3& gyro - ) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.milliseconds = milliseconds; - params.buttons = buttons; - params.gyro = gyro; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_FULL, params); - } -}; - - - -} -} -#endif +/* SerialPABotBase ESP32 Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_ESP32_Routines_H +#define PokemonAutomation_SerialPABotBase_ESP32_Routines_H + +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "ClientSource/Connection/BotBaseMessage.h" +#include "Controllers/ControllerTypes.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + +class MessageControllerReadSpi : public BotBaseRequest{ +public: + pabb_Message_ESP32_ReadSpi params; + MessageControllerReadSpi(ControllerType controller_type, uint32_t address, uint8_t bytes) + : BotBaseRequest(false) + { + uint32_t controller_id = PABB_CID_NONE; + switch (controller_type){ + case ControllerType::NintendoSwitch_WirelessProController: + controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; + break; + case ControllerType::NintendoSwitch_LeftJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; + break; + case ControllerType::NintendoSwitch_RightJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; + break; + default:; + } + params.seqnum = 0; + params.controller_type = controller_id; + params.address = address; + params.bytes = bytes; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_REQUEST_READ_SPI, params); + } +}; +class MessageControllerWriteSpi : public BotBaseRequest{ +public: + std::string data; + MessageControllerWriteSpi( + ControllerType controller_type, + uint32_t address, uint8_t bytes, + const void* p_data + ) + : BotBaseRequest(false) + { + uint32_t controller_id = PABB_CID_NONE; + switch (controller_type){ + case ControllerType::NintendoSwitch_WirelessProController: + controller_id = PABB_CID_NINTENDO_SWITCH_WIRELESS_PRO_CONTROLLER; + break; + case ControllerType::NintendoSwitch_LeftJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_LEFT_JOYCON; + break; + case ControllerType::NintendoSwitch_RightJoycon: + controller_id = PABB_CID_NINTENDO_SWITCH_RIGHT_JOYCON; + break; + default:; + } + pabb_Message_ESP32_WriteSpi params; + params.seqnum = 0; + params.controller_type = controller_id; + params.address = address; + params.bytes = bytes; + data = std::string((char*)¶ms, sizeof(params)); + data += std::string((const char*)p_data, bytes); + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_REQUEST_WRITE_SPI, data); + } +}; +class MessageControllerStateButtons : public BotBaseRequest{ +public: + pabb_Message_ESP32_CommandButtonState params; + MessageControllerStateButtons(uint16_t milliseconds, const PABB_NintendoSwitch_ButtonState& state) + : BotBaseRequest(true) + { + params.seqnum = 0; + params.milliseconds = milliseconds; + params.buttons = state; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_BUTTONS, params); + } +}; +class MessageControllerStateFull : public BotBaseRequest{ +public: + pabb_Message_ESP32_CommandFullState params; + MessageControllerStateFull( + uint16_t milliseconds, + const PABB_NintendoSwitch_ButtonState& buttons, + const PABB_NintendoSwitch_GyroStateX3& gyro + ) + : BotBaseRequest(true) + { + params.seqnum = 0; + params.milliseconds = milliseconds; + params.buttons = buttons; + params.gyro = gyro; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_ESP32_CONTROLLER_STATE_FULL, params); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp index 3fbd791346..848ac1dc16 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.cpp @@ -1,66 +1,66 @@ -/* SerialPABotBase AVR8 Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -int register_message_converters_push_button_framework(){ - register_message_converter( - PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "controller_state_ticks() - "; - if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateTicks)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_NS_Generic_ControllerStateTicks*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", buttons = " << params->buttons << "(" << button_to_string((NintendoSwitch::Button)params->buttons) << ")"; - ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->dpad); - ss << ", LJ = (" << (int)params->left_joystick_x << "," << (int)params->left_joystick_y << ")"; - ss << ", RJ = (" << (int)params->right_joystick_x << "," << (int)params->right_joystick_y << ")"; - ss << ", ticks = " << (int)params->ticks; - return ss.str(); - } - ); - register_message_converter( - PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, - [](const std::string& body){ - // Disable this by default since it's very spammy. - if (!GlobalSettings::instance().LOG_EVERYTHING){ - return std::string(); - } - std::ostringstream ss; - ss << "controller_state_ms() - "; - if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateMs)){ ss << "(invalid size)" << std::endl; return ss.str(); } - const auto* params = (const pabb_Message_NS_Generic_ControllerStateMs*)body.c_str(); - ss << "seqnum = " << (uint64_t)params->seqnum; - ss << ", buttons = " << params->buttons << "(" << button_to_string((NintendoSwitch::Button)params->buttons) << ")"; - ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->dpad); - ss << ", LJ = (" << (int)params->left_joystick_x << "," << (int)params->left_joystick_y << ")"; - ss << ", RJ = (" << (int)params->right_joystick_x << "," << (int)params->right_joystick_y << ")"; - ss << ", milliseconds = " << params->milliseconds; - return ss.str(); - } - ); - return 0; -} -int init_PushButtonFramework = register_message_converters_push_button_framework(); - - - -} -} +/* SerialPABotBase AVR8 Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +int register_message_converters_push_button_framework(){ + register_message_converter( + PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "controller_state_ticks() - "; + if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateTicks)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_NS_Generic_ControllerStateTicks*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", buttons = " << params->buttons << "(" << button_to_string((NintendoSwitch::Button)params->buttons) << ")"; + ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->dpad); + ss << ", LJ = (" << (int)params->left_joystick_x << "," << (int)params->left_joystick_y << ")"; + ss << ", RJ = (" << (int)params->right_joystick_x << "," << (int)params->right_joystick_y << ")"; + ss << ", ticks = " << (int)params->ticks; + return ss.str(); + } + ); + register_message_converter( + PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, + [](const std::string& body){ + // Disable this by default since it's very spammy. + if (!GlobalSettings::instance().LOG_EVERYTHING){ + return std::string(); + } + std::ostringstream ss; + ss << "controller_state_ms() - "; + if (body.size() != sizeof(pabb_Message_NS_Generic_ControllerStateMs)){ ss << "(invalid size)" << std::endl; return ss.str(); } + const auto* params = (const pabb_Message_NS_Generic_ControllerStateMs*)body.c_str(); + ss << "seqnum = " << (uint64_t)params->seqnum; + ss << ", buttons = " << params->buttons << "(" << button_to_string((NintendoSwitch::Button)params->buttons) << ")"; + ss << ", dpad = " << dpad_to_string((NintendoSwitch::DpadPosition)params->dpad); + ss << ", LJ = (" << (int)params->left_joystick_x << "," << (int)params->left_joystick_y << ")"; + ss << ", RJ = (" << (int)params->right_joystick_x << "," << (int)params->right_joystick_y << ")"; + ss << ", milliseconds = " << params->milliseconds; + return ss.str(); + } + ); + return 0; +} +int init_PushButtonFramework = register_message_converters_push_button_framework(); + + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h index d384f4c222..ccca96b5de 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h @@ -1,80 +1,80 @@ -/* SerialPABotBase (Nintendo Switch Generic Wired Controller) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_NS_Generic_H -#define PokemonAutomation_SerialPABotBase_NS_Generic_H - -#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" -#include "ClientSource/Connection/BotBaseMessage.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - -class DeviceRequest_NS_Generic_ControllerStateTicks : public BotBaseRequest{ -public: - pabb_Message_NS_Generic_ControllerStateTicks params; - DeviceRequest_NS_Generic_ControllerStateTicks( - uint16_t buttons, - uint8_t dpad, - uint8_t left_joystick_x, - uint8_t left_joystick_y, - uint8_t right_joystick_x, - uint8_t right_joystick_y, - uint8_t ticks - ) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.buttons = buttons; - params.dpad = dpad; - params.left_joystick_x = left_joystick_x; - params.left_joystick_y = left_joystick_y; - params.right_joystick_x = right_joystick_x; - params.right_joystick_y = right_joystick_y; - params.ticks = ticks; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS, params); - } -}; - - - -class DeviceRequest_NS_Generic_ControllerStateMs : public BotBaseRequest{ -public: - pabb_Message_NS_Generic_ControllerStateMs params; - DeviceRequest_NS_Generic_ControllerStateMs( - uint16_t milliseconds, - uint16_t buttons, - uint8_t dpad, - uint8_t left_joystick_x, - uint8_t left_joystick_y, - uint8_t right_joystick_x, - uint8_t right_joystick_y - ) - : BotBaseRequest(true) - { - params.seqnum = 0; - params.milliseconds = milliseconds; - params.buttons = buttons; - params.dpad = dpad; - params.left_joystick_x = left_joystick_x; - params.left_joystick_y = left_joystick_y; - params.right_joystick_x = right_joystick_x; - params.right_joystick_y = right_joystick_y; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, params); - } -}; - - - -} -} -#endif +/* SerialPABotBase (Nintendo Switch Generic Wired Controller) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_NS_Generic_H +#define PokemonAutomation_SerialPABotBase_NS_Generic_H + +#include "Common/SerialPABotBase/SerialPABotBase_Messages_NS_Generic.h" +#include "ClientSource/Connection/BotBaseMessage.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + +class DeviceRequest_NS_Generic_ControllerStateTicks : public BotBaseRequest{ +public: + pabb_Message_NS_Generic_ControllerStateTicks params; + DeviceRequest_NS_Generic_ControllerStateTicks( + uint16_t buttons, + uint8_t dpad, + uint8_t left_joystick_x, + uint8_t left_joystick_y, + uint8_t right_joystick_x, + uint8_t right_joystick_y, + uint8_t ticks + ) + : BotBaseRequest(true) + { + params.seqnum = 0; + params.buttons = buttons; + params.dpad = dpad; + params.left_joystick_x = left_joystick_x; + params.left_joystick_y = left_joystick_y; + params.right_joystick_x = right_joystick_x; + params.right_joystick_y = right_joystick_y; + params.ticks = ticks; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_TICKS, params); + } +}; + + + +class DeviceRequest_NS_Generic_ControllerStateMs : public BotBaseRequest{ +public: + pabb_Message_NS_Generic_ControllerStateMs params; + DeviceRequest_NS_Generic_ControllerStateMs( + uint16_t milliseconds, + uint16_t buttons, + uint8_t dpad, + uint8_t left_joystick_x, + uint8_t left_joystick_y, + uint8_t right_joystick_x, + uint8_t right_joystick_y + ) + : BotBaseRequest(true) + { + params.seqnum = 0; + params.milliseconds = milliseconds; + params.buttons = buttons; + params.dpad = dpad; + params.left_joystick_x = left_joystick_x; + params.left_joystick_y = left_joystick_y; + params.right_joystick_x = right_joystick_x; + params.right_joystick_y = right_joystick_y; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_NS_GENERIC_CONTROLLER_STATE_MS, params); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp index b8b9c992fe..fd8aeeab73 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.cpp @@ -1,59 +1,59 @@ -/* SerialPABotBase Routines (Protocol) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "SerialPABotBase_Routines_Protocol.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - -uint32_t protocol_version(BotBaseController& botbase){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_protocol_version() - ).convert(botbase.logger(), response); - return response.data; -} -uint32_t program_version(BotBaseController& botbase){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_program_version() - ).convert(botbase.logger(), response); - return response.data; -} -uint8_t device_queue_size(BotBaseController& botbase){ - pabb_MsgAckRequestI8 response; - botbase.issue_request_and_wait( - DeviceRequest_queue_size() - ).convert(botbase.logger(), response); - return response.data; - -} -uint8_t program_id(BotBaseController& botbase){ - pabb_MsgAckRequestI8 response; - botbase.issue_request_and_wait( - DeviceRequest_program_id() - ).convert(botbase.logger(), response); - return response.data; -} -uint32_t read_controller_mode(BotBaseController& botbase){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_read_controller_mode() - ).convert(botbase.logger(), response); - return response.data; -} -uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode){ - pabb_MsgAckRequestI32 response; - botbase.issue_request_and_wait( - DeviceRequest_change_controller_mode(mode) - ).convert(botbase.logger(), response); - return response.data; -} - - -} -} +/* SerialPABotBase Routines (Protocol) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "SerialPABotBase_Routines_Protocol.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + +uint32_t protocol_version(BotBaseController& botbase){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_protocol_version() + ).convert(botbase.logger(), response); + return response.data; +} +uint32_t program_version(BotBaseController& botbase){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_program_version() + ).convert(botbase.logger(), response); + return response.data; +} +uint8_t device_queue_size(BotBaseController& botbase){ + pabb_MsgAckRequestI8 response; + botbase.issue_request_and_wait( + DeviceRequest_queue_size() + ).convert(botbase.logger(), response); + return response.data; + +} +uint8_t program_id(BotBaseController& botbase){ + pabb_MsgAckRequestI8 response; + botbase.issue_request_and_wait( + DeviceRequest_program_id() + ).convert(botbase.logger(), response); + return response.data; +} +uint32_t read_controller_mode(BotBaseController& botbase){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_read_controller_mode() + ).convert(botbase.logger(), response); + return response.data; +} +uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode){ + pabb_MsgAckRequestI32 response; + botbase.issue_request_and_wait( + DeviceRequest_change_controller_mode(mode) + ).convert(botbase.logger(), response); + return response.data; +} + + +} +} diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h index 637aa8455b..e7f443f2a1 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h @@ -1,146 +1,146 @@ -/* SerialPABotBase Routines (Protocol) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_SerialPABotBase_Routines_Protocol_H -#define PokemonAutomation_SerialPABotBase_Routines_Protocol_H - -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -#include "ClientSource/Connection/BotBase.h" -#include "ClientSource/Connection/BotBaseMessage.h" - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - -uint32_t protocol_version(BotBaseController& botbase); -uint32_t program_version(BotBaseController& botbase); -uint8_t device_queue_size(BotBaseController& botbase); -uint8_t program_id(BotBaseController& botbase); -uint32_t read_controller_mode(BotBaseController& botbase); -uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode); - - -class DeviceRequest_seqnum_reset : public BotBaseRequest{ -public: - pabb_MsgInfoSeqnumReset params; - DeviceRequest_seqnum_reset() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_SEQNUM_RESET, params); - } -}; -class DeviceRequest_request_stop : public BotBaseRequest{ -public: - pabb_MsgRequestProtocolVersion params; - DeviceRequest_request_stop() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_STOP, params); - } -}; -class DeviceRequest_next_command_interrupt : public BotBaseRequest{ -public: - pabb_MsgRequestNextCmdInterrupt params; - DeviceRequest_next_command_interrupt() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT, params); - } -}; -class DeviceRequest_protocol_version : public BotBaseRequest{ -public: - pabb_MsgRequestProtocolVersion params; - DeviceRequest_protocol_version() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_PROTOCOL_VERSION, params); - } -}; -class DeviceRequest_program_version : public BotBaseRequest{ -public: - pabb_MsgRequestProgramVersion params; - DeviceRequest_program_version() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_VERSION, params); - } -}; -class DeviceRequest_queue_size : public BotBaseRequest{ -public: - pabb_MsgRequestProgramVersion params; - DeviceRequest_queue_size() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_QUEUE_SIZE, params); - } -}; -class DeviceRequest_system_clock : public BotBaseRequest{ -public: - pabb_system_clock params; - DeviceRequest_system_clock() - : BotBaseRequest(false) - { - params.seqnum = 0; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_CLOCK, params); - } -}; -class DeviceRequest_program_id : public BotBaseRequest{ -public: - pabb_MsgRequestProgramID params; - DeviceRequest_program_id() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_ID, params); - } -}; -class DeviceRequest_read_controller_mode : public BotBaseRequest{ -public: - pabb_MsgRequestReadControllerMode params; - DeviceRequest_read_controller_mode() - : BotBaseRequest(false) - {} - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_READ_CONTROLLER_MODE, params); - } -}; -class DeviceRequest_change_controller_mode : public BotBaseRequest{ -public: - pabb_MsgRequestChangeControllerMode params; - DeviceRequest_change_controller_mode(uint32_t mode) - : BotBaseRequest(false) - { - params.mode = mode; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE, params); - } -}; -class MessageControllerStatus : public BotBaseRequest{ -public: - pabb_Message_RequestStatus params; - MessageControllerStatus() - : BotBaseRequest(false) - { - params.seqnum = 0; - } - virtual BotBaseMessage message() const override{ - return BotBaseMessage(PABB_MSG_REQUEST_STATUS, params); - } -}; - - - -} -} -#endif +/* SerialPABotBase Routines (Protocol) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_SerialPABotBase_Routines_Protocol_H +#define PokemonAutomation_SerialPABotBase_Routines_Protocol_H + +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +#include "ClientSource/Connection/BotBase.h" +#include "ClientSource/Connection/BotBaseMessage.h" + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + +uint32_t protocol_version(BotBaseController& botbase); +uint32_t program_version(BotBaseController& botbase); +uint8_t device_queue_size(BotBaseController& botbase); +uint8_t program_id(BotBaseController& botbase); +uint32_t read_controller_mode(BotBaseController& botbase); +uint32_t change_controller_mode(BotBaseController& botbase, uint32_t mode); + + +class DeviceRequest_seqnum_reset : public BotBaseRequest{ +public: + pabb_MsgInfoSeqnumReset params; + DeviceRequest_seqnum_reset() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_SEQNUM_RESET, params); + } +}; +class DeviceRequest_request_stop : public BotBaseRequest{ +public: + pabb_MsgRequestProtocolVersion params; + DeviceRequest_request_stop() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_STOP, params); + } +}; +class DeviceRequest_next_command_interrupt : public BotBaseRequest{ +public: + pabb_MsgRequestNextCmdInterrupt params; + DeviceRequest_next_command_interrupt() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_NEXT_CMD_INTERRUPT, params); + } +}; +class DeviceRequest_protocol_version : public BotBaseRequest{ +public: + pabb_MsgRequestProtocolVersion params; + DeviceRequest_protocol_version() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_PROTOCOL_VERSION, params); + } +}; +class DeviceRequest_program_version : public BotBaseRequest{ +public: + pabb_MsgRequestProgramVersion params; + DeviceRequest_program_version() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_VERSION, params); + } +}; +class DeviceRequest_queue_size : public BotBaseRequest{ +public: + pabb_MsgRequestProgramVersion params; + DeviceRequest_queue_size() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_QUEUE_SIZE, params); + } +}; +class DeviceRequest_system_clock : public BotBaseRequest{ +public: + pabb_system_clock params; + DeviceRequest_system_clock() + : BotBaseRequest(false) + { + params.seqnum = 0; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_CLOCK, params); + } +}; +class DeviceRequest_program_id : public BotBaseRequest{ +public: + pabb_MsgRequestProgramID params; + DeviceRequest_program_id() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_PROGRAM_ID, params); + } +}; +class DeviceRequest_read_controller_mode : public BotBaseRequest{ +public: + pabb_MsgRequestReadControllerMode params; + DeviceRequest_read_controller_mode() + : BotBaseRequest(false) + {} + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_READ_CONTROLLER_MODE, params); + } +}; +class DeviceRequest_change_controller_mode : public BotBaseRequest{ +public: + pabb_MsgRequestChangeControllerMode params; + DeviceRequest_change_controller_mode(uint32_t mode) + : BotBaseRequest(false) + { + params.mode = mode; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_CHANGE_CONTROLLER_MODE, params); + } +}; +class MessageControllerStatus : public BotBaseRequest{ +public: + pabb_Message_RequestStatus params; + MessageControllerStatus() + : BotBaseRequest(false) + { + params.seqnum = 0; + } + virtual BotBaseMessage message() const override{ + return BotBaseMessage(PABB_MSG_REQUEST_STATUS, params); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h index 9e9f33428c..34168cc479 100644 --- a/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h +++ b/SerialPrograms/Source/Controllers/SerialPABotBase/SerialPABotBase_SelectorWidget.h @@ -1,127 +1,127 @@ -/* SerialPABotBase Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H -#define PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H - -#include "Common/Qt/NoWheelComboBox.h" -#include "Controllers/ControllerDescriptor.h" -#include "Controllers/ControllerSelectorWidget.h" -#include "Controllers/NullController.h" -#include "SerialPABotBase_Descriptor.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SerialPABotBase{ - - - - -class SerialPABotBase_SelectorWidget : public NoWheelComboBox{ -public: - SerialPABotBase_SelectorWidget( - ControllerSelectorWidget& parent, - const ControllerDescriptor* current - ) - : NoWheelComboBox(&parent) - , m_parent(parent) - { -// cout << "SerialPABotBase(): " << current << endl; - this->setMaxVisibleItems(32); - - if (current == nullptr || ( - current->interface_type != ControllerInterface::None && - current->interface_type != ControllerInterface::SerialPABotBase - ) - ){ - std::shared_ptr descriptor = - parent.session().option().get_descriptor_from_cache(ControllerInterface::SerialPABotBase); - if (!descriptor){ - descriptor.reset(new SerialPABotBase_Descriptor()); - } - parent.session().set_device(descriptor); - } - - refresh_devices(); - - connect( - this, static_cast(&QComboBox::activated), - &parent, [this, &parent](int index){ - if (index < 0){ - return; - } - index = std::min(index, (int)m_ports.size() - 1); - std::shared_ptr& selected = m_ports[index]; - - std::shared_ptr current = parent.session().descriptor(); - if (*current == *selected){ - return; - } - - parent.session().set_device(selected); - refresh_devices(); - } - ); - } - - void refresh_devices(){ -// cout << "Current = " << width() << " x " << height() << endl; -// cout << "sizeHint = " << sizeHint().width() << " x " << sizeHint().height() << endl; -// cout << "minimumContentsLength = " << this->minimumContentsLength() << endl; - - m_ports.clear(); - this->clear(); - -// cout << "SerialPABotBase_SelectorWidget::refresh_devices()" << endl; - - - m_ports.emplace_back(new NullControllerDescriptor()); - for (QSerialPortInfo& port : QSerialPortInfo::availablePorts()){ -#ifdef _WIN32 - // COM1 is never the correct port on Windows. - if (port.portName() == "COM1"){ - continue; - } -#endif - m_ports.emplace_back(new SerialPABotBase_Descriptor(port)); - } - - size_t width = 6; - int index = 0; - int c = 0; - for (const auto& port : m_ports){ - QString display_name = QString::fromStdString(port->display_name()); - width = std::max(width, display_name.size()); - this->addItem(display_name); - if (*m_parent.session().descriptor() == *m_ports[c]){ - index = c; - } - c++; - } - - if (this->count() > this->maxVisibleItems()){ - width++; - } - setMinimumContentsLength((int)width); - setCurrentIndex(index); - } - - -private: - ControllerSelectorWidget& m_parent; - std::vector> m_ports; -}; - - - - - -} -} -#endif +/* SerialPABotBase Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H +#define PokemonAutomation_Controllers_SerialPABotBase_SelectorWidget_H + +#include "Common/Qt/NoWheelComboBox.h" +#include "Controllers/ControllerDescriptor.h" +#include "Controllers/ControllerSelectorWidget.h" +#include "Controllers/NullController.h" +#include "SerialPABotBase_Descriptor.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SerialPABotBase{ + + + + +class SerialPABotBase_SelectorWidget : public NoWheelComboBox{ +public: + SerialPABotBase_SelectorWidget( + ControllerSelectorWidget& parent, + const ControllerDescriptor* current + ) + : NoWheelComboBox(&parent) + , m_parent(parent) + { +// cout << "SerialPABotBase(): " << current << endl; + this->setMaxVisibleItems(32); + + if (current == nullptr || ( + current->interface_type != ControllerInterface::None && + current->interface_type != ControllerInterface::SerialPABotBase + ) + ){ + std::shared_ptr descriptor = + parent.session().option().get_descriptor_from_cache(ControllerInterface::SerialPABotBase); + if (!descriptor){ + descriptor.reset(new SerialPABotBase_Descriptor()); + } + parent.session().set_device(descriptor); + } + + refresh_devices(); + + connect( + this, static_cast(&QComboBox::activated), + &parent, [this, &parent](int index){ + if (index < 0){ + return; + } + index = std::min(index, (int)m_ports.size() - 1); + std::shared_ptr& selected = m_ports[index]; + + std::shared_ptr current = parent.session().descriptor(); + if (*current == *selected){ + return; + } + + parent.session().set_device(selected); + refresh_devices(); + } + ); + } + + void refresh_devices(){ +// cout << "Current = " << width() << " x " << height() << endl; +// cout << "sizeHint = " << sizeHint().width() << " x " << sizeHint().height() << endl; +// cout << "minimumContentsLength = " << this->minimumContentsLength() << endl; + + m_ports.clear(); + this->clear(); + +// cout << "SerialPABotBase_SelectorWidget::refresh_devices()" << endl; + + + m_ports.emplace_back(new NullControllerDescriptor()); + for (QSerialPortInfo& port : QSerialPortInfo::availablePorts()){ +#ifdef _WIN32 + // COM1 is never the correct port on Windows. + if (port.portName() == "COM1"){ + continue; + } +#endif + m_ports.emplace_back(new SerialPABotBase_Descriptor(port)); + } + + size_t width = 6; + int index = 0; + int c = 0; + for (const auto& port : m_ports){ + QString display_name = QString::fromStdString(port->display_name()); + width = std::max(width, display_name.size()); + this->addItem(display_name); + if (*m_parent.session().descriptor() == *m_ports[c]){ + index = c; + } + c++; + } + + if (this->count() > this->maxVisibleItems()){ + width++; + } + setMinimumContentsLength((int)width); + setCurrentIndex(index); + } + + +private: + ControllerSelectorWidget& m_parent; + std::vector> m_ports; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp b/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp index 32d4b07796..d154ac5f21 100644 --- a/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp +++ b/SerialPrograms/Source/Controllers/SuperscalarScheduler.cpp @@ -1,259 +1,259 @@ -/* Superscalar Scheduler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Time.h" -#include "SuperscalarScheduler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - - -SuperscalarScheduler::SuperscalarScheduler( - Logger& logger, - WallDuration flush_threshold, - std::vector resources -) - : m_logger(logger) - , m_flush_threshold(flush_threshold) - , m_resources(std::move(resources)) -{ - clear(); -} - - -void SuperscalarScheduler::clear() noexcept{ -// SpinLockGuard lg(m_lock); -// m_logger.log("Clearing schedule..."); - WallClock now = current_time(); - m_local_start = now; - m_local_last_activity = now; - m_device_issue_time = now; - m_device_sent_time = now; - m_max_free_time = now; - m_state_changes.clear(); - for (ExecutionResource* resource : m_resources){ - resource->m_is_busy = false; - resource->m_busy_time = now; - resource->m_done_time = now; - resource->m_free_time = now; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", free_time = " << std::chrono::duration_cast((resource->m_free_time - m_local_start)).count() -// << endl; - } - m_pending_clear.store(false, std::memory_order_release); -} - -bool SuperscalarScheduler::iterate_schedule(const Cancellable* cancellable){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - if (m_state_changes.empty()){ -// cout << "State is empty." << endl; - m_device_sent_time = m_device_issue_time; - return false; - } - - auto iter = m_state_changes.begin(); - - WallClock next_state_change; - if (m_device_sent_time < *iter){ - next_state_change = *iter; - }else{ - auto next = iter; - ++next; - next_state_change = next == m_state_changes.end() - ? m_device_issue_time - : *next; - } - - // Things get complicated if we overshoot the issue time. - if (next_state_change > m_device_issue_time){ -// m_logger.log("SuperscalarScheduler: Overshoot due to unfinished early return.", COLOR_RED); - next_state_change = m_device_issue_time; - } - - WallDuration duration = next_state_change - m_device_sent_time; - if (duration == WallDuration::zero()){ - // This happens when the command has a delay of zero. A delay of zero - // is almost always immediately followed by another command that is - // intended to execute simultaneously. Thus we do not attempt to - // execute the schedule any further. -// m_logger.log("SuperscalarScheduler: Scheduler is stalled.", COLOR_RED); - return false; - } - - // Compute the resource state at this timestamp. - for (ExecutionResource* resource : m_resources){ - resource->m_is_busy = resource->m_busy_time <= m_device_sent_time && m_device_sent_time < resource->m_done_time; - } - - m_device_sent_time = next_state_change; - if (next_state_change >= *iter){ - m_state_changes.erase(iter); - } - - this->push_state(cancellable, duration); - -// SpinLockGuard lg(m_lock); - - WallClock now = current_time(); - m_local_last_activity = now; - - // If we are not dangling anything, we can return now. - if (m_device_sent_time >= m_device_issue_time){ - return true; - } - -#if 1 - // - // We are currently dangling a command. We don't know whether the current - // ongoing commands will run out, or if something new will join them in the - // near future. - // - // If it's been long enough since the last issue, we can assume that - // nothing will join and thus can gap. (We do require that dangling - // commands be resolved promptly or they may run out.) - // - // Thus we can fast forward whatever is scheduled into the future. - // - WallDuration time_since_last_activity = now - m_local_last_activity; - if (time_since_last_activity > m_flush_threshold){ - m_logger.log("SuperscalarScheduler: A dangling early-return issue has gapped.", COLOR_RED); - m_device_issue_time += time_since_last_activity; - - // Since we're gapping, we might as well gap a bit more to we don't - // re-enter here so quickly. - m_device_issue_time += m_flush_threshold; - - m_max_free_time = std::max(m_max_free_time, m_device_issue_time); - } - -#endif - - return true; -} -void SuperscalarScheduler::process_schedule(const Cancellable* cancellable){ - // Any exception is either an unrecoverable error, or an async-cancel. - // Both cases should clear the scheduler. - try{ - while (iterate_schedule(cancellable)); - }catch (...){ - clear(); - throw; - } -} - -void SuperscalarScheduler::issue_wait_for_all(const Cancellable* cancellable){ - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - return; - } -// m_logger.log("issue_wait_for_all(): states = " + std::to_string(m_state_changes.size()), COLOR_DARKGREEN); -// cout << "issue_wait_for_all(): " << m_state_changes.size() << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() -// << endl; - m_device_issue_time = std::max(m_device_issue_time, m_max_free_time); - m_max_free_time = m_device_issue_time; - process_schedule(cancellable); -} -void SuperscalarScheduler::issue_nop(const Cancellable* cancellable, WallDuration delay){ - if (delay <= WallDuration::zero()){ - return; - } - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - } -// cout << "issue_nop(): " << m_state_changes.size() << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() -// << endl; - WallClock next_issue_time = m_device_issue_time + delay; - m_state_changes.insert(next_issue_time); - m_device_issue_time = next_issue_time; - m_max_free_time = std::max(m_max_free_time, m_device_issue_time); - m_local_last_activity = current_time(); - process_schedule(cancellable); -} -void SuperscalarScheduler::issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource){ - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - return; - } -// cout << "wait_for_resource()" << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << ", free_time = " << std::chrono::duration_cast((resource.m_free_time - m_local_start)).count() -// << endl; - // Resource is not ready yet. Stall until it is. - if (resource.m_free_time > m_device_sent_time){ -// cout << "stall = " << std::chrono::duration_cast(resource.m_free_time - m_device_sent_time).count() << endl; - m_device_issue_time = resource.m_free_time; - m_local_last_activity = current_time(); - } - process_schedule(cancellable); -} -void SuperscalarScheduler::issue_to_resource( - const Cancellable* cancellable, ExecutionResource& resource, - WallDuration delay, WallDuration hold, WallDuration cooldown -){ - if (m_pending_clear.load(std::memory_order_acquire)){ - clear(); - } - - // Resource is busy. - if (m_device_sent_time < resource.m_free_time){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Attempted to issue resource that isn't ready." - ); - } - - delay = std::max(delay, WallDuration::zero()); - hold = std::max(hold, WallDuration::zero()); - cooldown = std::max(cooldown, WallDuration::zero()); - -// cout << "issue_to_resource(): delay = " << std::chrono::duration_cast(delay).count() -// << ", hold = " << std::chrono::duration_cast(hold).count() -// << ", cooldown = " << std::chrono::duration_cast(cooldown).count() -// << endl; -// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() -// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() -// << endl; - - WallClock release_time = m_device_issue_time + hold; - WallClock free_time = release_time + cooldown; - - m_state_changes.insert(m_device_issue_time); - m_state_changes.insert(release_time); - - resource.m_busy_time = m_device_issue_time; - resource.m_done_time = release_time; - resource.m_free_time = free_time; - - m_device_issue_time += delay; - m_max_free_time = std::max(m_max_free_time, free_time); - m_max_free_time = std::max(m_max_free_time, m_device_issue_time); - m_local_last_activity = current_time(); - - process_schedule(cancellable); -} - - - - - - -} - +/* Superscalar Scheduler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Time.h" +#include "SuperscalarScheduler.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + + +SuperscalarScheduler::SuperscalarScheduler( + Logger& logger, + WallDuration flush_threshold, + std::vector resources +) + : m_logger(logger) + , m_flush_threshold(flush_threshold) + , m_resources(std::move(resources)) +{ + clear(); +} + + +void SuperscalarScheduler::clear() noexcept{ +// SpinLockGuard lg(m_lock); +// m_logger.log("Clearing schedule..."); + WallClock now = current_time(); + m_local_start = now; + m_local_last_activity = now; + m_device_issue_time = now; + m_device_sent_time = now; + m_max_free_time = now; + m_state_changes.clear(); + for (ExecutionResource* resource : m_resources){ + resource->m_is_busy = false; + resource->m_busy_time = now; + resource->m_done_time = now; + resource->m_free_time = now; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", free_time = " << std::chrono::duration_cast((resource->m_free_time - m_local_start)).count() +// << endl; + } + m_pending_clear.store(false, std::memory_order_release); +} + +bool SuperscalarScheduler::iterate_schedule(const Cancellable* cancellable){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + if (m_state_changes.empty()){ +// cout << "State is empty." << endl; + m_device_sent_time = m_device_issue_time; + return false; + } + + auto iter = m_state_changes.begin(); + + WallClock next_state_change; + if (m_device_sent_time < *iter){ + next_state_change = *iter; + }else{ + auto next = iter; + ++next; + next_state_change = next == m_state_changes.end() + ? m_device_issue_time + : *next; + } + + // Things get complicated if we overshoot the issue time. + if (next_state_change > m_device_issue_time){ +// m_logger.log("SuperscalarScheduler: Overshoot due to unfinished early return.", COLOR_RED); + next_state_change = m_device_issue_time; + } + + WallDuration duration = next_state_change - m_device_sent_time; + if (duration == WallDuration::zero()){ + // This happens when the command has a delay of zero. A delay of zero + // is almost always immediately followed by another command that is + // intended to execute simultaneously. Thus we do not attempt to + // execute the schedule any further. +// m_logger.log("SuperscalarScheduler: Scheduler is stalled.", COLOR_RED); + return false; + } + + // Compute the resource state at this timestamp. + for (ExecutionResource* resource : m_resources){ + resource->m_is_busy = resource->m_busy_time <= m_device_sent_time && m_device_sent_time < resource->m_done_time; + } + + m_device_sent_time = next_state_change; + if (next_state_change >= *iter){ + m_state_changes.erase(iter); + } + + this->push_state(cancellable, duration); + +// SpinLockGuard lg(m_lock); + + WallClock now = current_time(); + m_local_last_activity = now; + + // If we are not dangling anything, we can return now. + if (m_device_sent_time >= m_device_issue_time){ + return true; + } + +#if 1 + // + // We are currently dangling a command. We don't know whether the current + // ongoing commands will run out, or if something new will join them in the + // near future. + // + // If it's been long enough since the last issue, we can assume that + // nothing will join and thus can gap. (We do require that dangling + // commands be resolved promptly or they may run out.) + // + // Thus we can fast forward whatever is scheduled into the future. + // + WallDuration time_since_last_activity = now - m_local_last_activity; + if (time_since_last_activity > m_flush_threshold){ + m_logger.log("SuperscalarScheduler: A dangling early-return issue has gapped.", COLOR_RED); + m_device_issue_time += time_since_last_activity; + + // Since we're gapping, we might as well gap a bit more to we don't + // re-enter here so quickly. + m_device_issue_time += m_flush_threshold; + + m_max_free_time = std::max(m_max_free_time, m_device_issue_time); + } + +#endif + + return true; +} +void SuperscalarScheduler::process_schedule(const Cancellable* cancellable){ + // Any exception is either an unrecoverable error, or an async-cancel. + // Both cases should clear the scheduler. + try{ + while (iterate_schedule(cancellable)); + }catch (...){ + clear(); + throw; + } +} + +void SuperscalarScheduler::issue_wait_for_all(const Cancellable* cancellable){ + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + return; + } +// m_logger.log("issue_wait_for_all(): states = " + std::to_string(m_state_changes.size()), COLOR_DARKGREEN); +// cout << "issue_wait_for_all(): " << m_state_changes.size() << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() +// << endl; + m_device_issue_time = std::max(m_device_issue_time, m_max_free_time); + m_max_free_time = m_device_issue_time; + process_schedule(cancellable); +} +void SuperscalarScheduler::issue_nop(const Cancellable* cancellable, WallDuration delay){ + if (delay <= WallDuration::zero()){ + return; + } + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + } +// cout << "issue_nop(): " << m_state_changes.size() << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", max_free_time = " << std::chrono::duration_cast((m_max_free_time - m_local_start)).count() +// << endl; + WallClock next_issue_time = m_device_issue_time + delay; + m_state_changes.insert(next_issue_time); + m_device_issue_time = next_issue_time; + m_max_free_time = std::max(m_max_free_time, m_device_issue_time); + m_local_last_activity = current_time(); + process_schedule(cancellable); +} +void SuperscalarScheduler::issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource){ + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + return; + } +// cout << "wait_for_resource()" << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << ", free_time = " << std::chrono::duration_cast((resource.m_free_time - m_local_start)).count() +// << endl; + // Resource is not ready yet. Stall until it is. + if (resource.m_free_time > m_device_sent_time){ +// cout << "stall = " << std::chrono::duration_cast(resource.m_free_time - m_device_sent_time).count() << endl; + m_device_issue_time = resource.m_free_time; + m_local_last_activity = current_time(); + } + process_schedule(cancellable); +} +void SuperscalarScheduler::issue_to_resource( + const Cancellable* cancellable, ExecutionResource& resource, + WallDuration delay, WallDuration hold, WallDuration cooldown +){ + if (m_pending_clear.load(std::memory_order_acquire)){ + clear(); + } + + // Resource is busy. + if (m_device_sent_time < resource.m_free_time){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Attempted to issue resource that isn't ready." + ); + } + + delay = std::max(delay, WallDuration::zero()); + hold = std::max(hold, WallDuration::zero()); + cooldown = std::max(cooldown, WallDuration::zero()); + +// cout << "issue_to_resource(): delay = " << std::chrono::duration_cast(delay).count() +// << ", hold = " << std::chrono::duration_cast(hold).count() +// << ", cooldown = " << std::chrono::duration_cast(cooldown).count() +// << endl; +// cout << "issue_time = " << std::chrono::duration_cast((m_device_issue_time - m_local_start)).count() +// << ", sent_time = " << std::chrono::duration_cast((m_device_sent_time - m_local_start)).count() +// << endl; + + WallClock release_time = m_device_issue_time + hold; + WallClock free_time = release_time + cooldown; + + m_state_changes.insert(m_device_issue_time); + m_state_changes.insert(release_time); + + resource.m_busy_time = m_device_issue_time; + resource.m_done_time = release_time; + resource.m_free_time = free_time; + + m_device_issue_time += delay; + m_max_free_time = std::max(m_max_free_time, free_time); + m_max_free_time = std::max(m_max_free_time, m_device_issue_time); + m_local_last_activity = current_time(); + + process_schedule(cancellable); +} + + + + + + +} + diff --git a/SerialPrograms/Source/Controllers/SuperscalarScheduler.h b/SerialPrograms/Source/Controllers/SuperscalarScheduler.h index 9593c17fd0..cd5dd5343d 100644 --- a/SerialPrograms/Source/Controllers/SuperscalarScheduler.h +++ b/SerialPrograms/Source/Controllers/SuperscalarScheduler.h @@ -1,152 +1,152 @@ -/* Superscalar Scheduler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SuperscalarScheduler_H -#define PokemonAutomation_Controllers_SuperscalarScheduler_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/CancellableScope.h" - -namespace PokemonAutomation{ - -class SuperscalarScheduler; - - -class ExecutionResource{ -public: - virtual ~ExecutionResource() = default; - ExecutionResource() - : m_busy_time(WallClock::min()) - , m_done_time(WallClock::min()) - , m_free_time(WallClock::min()) - {} - - bool is_busy() const{ - return m_is_busy; - } - WallClock free_time() const{ - return m_free_time; - } - -private: - friend class SuperscalarScheduler; - bool m_is_busy = false; - WallClock m_busy_time; // Timestamp of when resource will be become busy. - WallClock m_done_time; // Timestamp of when resource will be done being busy. - WallClock m_free_time; // Timestamp of when resource can be used again. -}; - - - - - -class SuperscalarScheduler{ -public: - SuperscalarScheduler( - Logger& logger, - WallDuration flush_threshold, - std::vector resources - ); - - -public: - // This is intended to be run on a different thread from the functions in - // the next section. So it is safe to run from anywhere. - - void clear_on_next(){ - m_pending_clear.store(true, std::memory_order_release); - } - - -public: - // These are the standard "issue" commands. - // - // These functions may or may not block. - // These are not thread-safe with each other. - // - - // Wait until the pipeline has completely cleared and all resources have - // returned to the ready state. - void issue_wait_for_all(const Cancellable* cancellable); - - // Issue a do-nothing command for the specified delay. - // This will advance the issue timestamp. - void issue_nop(const Cancellable* cancellable, WallDuration delay); - - // Wait until the specified resource is ready to be used. - // This will advance the issue timestamp until the resource is ready. - void issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource); - - // Issue a resource with the specified timing parameters. - // The resource must be ready to be used. - void issue_to_resource( - const Cancellable* cancellable, ExecutionResource& resource, - WallDuration delay, WallDuration hold, WallDuration cooldown - ); - - -protected: - // - // This class will automatically call "push_state()" when a state is ready. - // The child class should send/queue this state to the device/Switch. - // - // This function is allowed to block. In other words, it can wait until - // there is space in the queue before returning. - // - // This will always be called inside one of the above "issue_XXX()" - // functions. Implementations of this method should be aware of this - // re-entrancy when this gets called on them with respect to locking. - // - virtual void push_state(const Cancellable* cancellable, WallDuration duration) = 0; - - -private: - void clear() noexcept; - bool iterate_schedule(const Cancellable* cancellable); - void process_schedule(const Cancellable* cancellable); - - -private: - Logger& m_logger; - - // We are allowed to gap the timeline if nothing has been issued in this - // much time. - const WallDuration m_flush_threshold; - - std::atomic m_pending_clear; - - // The construction time of this object. This is only used for debugging - // purposes since it lets you print wall times relative to this. - WallClock m_local_start; - - // Wall clock of the last time "m_device_issue_time" was last updated. - // This is used to decide when to gap the timeline. - WallClock m_local_last_activity; - - // The current timestamp of what has been issued to the scheduler. - WallClock m_device_issue_time; - - // The current timestamp of what has been sent to the device. - WallClock m_device_sent_time; - - // Maximum of: m_resources[]->m_free_time - WallClock m_max_free_time; - - // A set of all the scheduled state changes that will happen. Between - // timestamps in this set, the state is constant. - std::set m_state_changes; - - std::vector m_resources; -}; - - - - - -} -#endif +/* Superscalar Scheduler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SuperscalarScheduler_H +#define PokemonAutomation_Controllers_SuperscalarScheduler_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/CancellableScope.h" + +namespace PokemonAutomation{ + +class SuperscalarScheduler; + + +class ExecutionResource{ +public: + virtual ~ExecutionResource() = default; + ExecutionResource() + : m_busy_time(WallClock::min()) + , m_done_time(WallClock::min()) + , m_free_time(WallClock::min()) + {} + + bool is_busy() const{ + return m_is_busy; + } + WallClock free_time() const{ + return m_free_time; + } + +private: + friend class SuperscalarScheduler; + bool m_is_busy = false; + WallClock m_busy_time; // Timestamp of when resource will be become busy. + WallClock m_done_time; // Timestamp of when resource will be done being busy. + WallClock m_free_time; // Timestamp of when resource can be used again. +}; + + + + + +class SuperscalarScheduler{ +public: + SuperscalarScheduler( + Logger& logger, + WallDuration flush_threshold, + std::vector resources + ); + + +public: + // This is intended to be run on a different thread from the functions in + // the next section. So it is safe to run from anywhere. + + void clear_on_next(){ + m_pending_clear.store(true, std::memory_order_release); + } + + +public: + // These are the standard "issue" commands. + // + // These functions may or may not block. + // These are not thread-safe with each other. + // + + // Wait until the pipeline has completely cleared and all resources have + // returned to the ready state. + void issue_wait_for_all(const Cancellable* cancellable); + + // Issue a do-nothing command for the specified delay. + // This will advance the issue timestamp. + void issue_nop(const Cancellable* cancellable, WallDuration delay); + + // Wait until the specified resource is ready to be used. + // This will advance the issue timestamp until the resource is ready. + void issue_wait_for_resource(const Cancellable* cancellable, ExecutionResource& resource); + + // Issue a resource with the specified timing parameters. + // The resource must be ready to be used. + void issue_to_resource( + const Cancellable* cancellable, ExecutionResource& resource, + WallDuration delay, WallDuration hold, WallDuration cooldown + ); + + +protected: + // + // This class will automatically call "push_state()" when a state is ready. + // The child class should send/queue this state to the device/Switch. + // + // This function is allowed to block. In other words, it can wait until + // there is space in the queue before returning. + // + // This will always be called inside one of the above "issue_XXX()" + // functions. Implementations of this method should be aware of this + // re-entrancy when this gets called on them with respect to locking. + // + virtual void push_state(const Cancellable* cancellable, WallDuration duration) = 0; + + +private: + void clear() noexcept; + bool iterate_schedule(const Cancellable* cancellable); + void process_schedule(const Cancellable* cancellable); + + +private: + Logger& m_logger; + + // We are allowed to gap the timeline if nothing has been issued in this + // much time. + const WallDuration m_flush_threshold; + + std::atomic m_pending_clear; + + // The construction time of this object. This is only used for debugging + // purposes since it lets you print wall times relative to this. + WallClock m_local_start; + + // Wall clock of the last time "m_device_issue_time" was last updated. + // This is used to decide when to gap the timeline. + WallClock m_local_last_activity; + + // The current timestamp of what has been issued to the scheduler. + WallClock m_device_issue_time; + + // The current timestamp of what has been sent to the device. + WallClock m_device_sent_time; + + // Maximum of: m_resources[]->m_free_time + WallClock m_max_free_time; + + // A set of all the scheduled state changes that will happen. Between + // timestamps in this set, the state is constant. + std::set m_state_changes; + + std::vector m_resources; +}; + + + + + +} +#endif diff --git a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp index 4ed3c7223c..fd06a136b6 100644 --- a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp +++ b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.cpp @@ -1,337 +1,337 @@ -/* Discord Integration Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Qt/StringToolsQt.h" -//#include "CommonFramework/Globals.h" -//#include "CommonFramework/GlobalSettingsPanel.h" -#include "DppIntegration/DppClient.h" -#include "SleepyDiscordRunner.h" -#include "DiscordIntegrationSettings.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Integration{ - - -DiscordIntegrationSettingsOption::~DiscordIntegrationSettingsOption(){ - library0.remove_listener(*this); - this->remove_listener(*this); -} -DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() - : GroupOption( - "Discord Integration Settings", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_DISABLED - ) -// , m_integration_enabled(integration_enabled) - , run_on_start( - "Run Discord Integration on Launch:
Automatically connect to Discord as soon as the program is launched.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , library0( - "Discord Integration Library:
Restart the program for this to take effect.", - { - {Library::SleepyDiscord, "sleepy", "Sleepy Discord (normal commands, deprecated)"}, - {Library::DPP, "dpp", "D++ (slash commands and normal commands)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Library::DPP - ) - , command_type( - "Discord Integration Command Type:
Restart the program for this to take effect.", - { - {CommandType::SlashCommands, "slash", "Slash commands"}, - {CommandType::MessageCommands, "message", "Message (prefix) commands"}, - }, - LockMode::LOCK_WHILE_RUNNING, - CommandType::SlashCommands - ) - , token( - true, - "Discord Token:
Enter your Discord bot's token. Keep it safe and don't share it with anyone.", - LockMode::LOCK_WHILE_RUNNING, - "", "0123456789abcdefghijklmnopqrstuvwxyzABCDEGFHIJKLMNOPQRSTUVWXYZ" - ) - , command_prefix( - false, - "Discord Command Prefix:
Enter a command prefix for your bot.", - LockMode::LOCK_WHILE_RUNNING, - "^", "^" - ) - , use_suffix( - "Use Suffix (Sleepy):
Use a suffix instead of a prefix for commands.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , game_status( - false, - "Discord Game Status:
Enter a status message your bot would display.", - LockMode::LOCK_WHILE_RUNNING, - "", "Controlling your Switch. :)" - ) - , hello_message( - false, - "Discord Hello Message:
Enter a message you'd like the bot to respond with to the \"$hi\" command.", - LockMode::LOCK_WHILE_RUNNING, - "", "Automation at your service!" - ) - , sudo( - false, - "Discord Sudo (Sleepy):
Enter user ID(s) to grant sudo access to.", - LockMode::LOCK_WHILE_RUNNING, - "", "123456789012345678" - ) - , owner( - false, - "Discord Owner (Sleepy):
Enter the bot owner's ID (your own ID).", - LockMode::LOCK_WHILE_RUNNING, - "", "123456789012345678" - ) - , allow_buttons_from_users( - "Allow Buttons from Users:
Allow other users to issue button presses.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(run_on_start); - PA_ADD_OPTION(library0); - PA_ADD_OPTION(command_type); - PA_ADD_OPTION(token); - PA_ADD_OPTION(command_prefix); - PA_ADD_OPTION(use_suffix); - PA_ADD_OPTION(game_status); - PA_ADD_OPTION(hello_message); - PA_ADD_OPTION(sudo); - PA_ADD_OPTION(owner); - PA_ADD_OPTION(allow_buttons_from_users); - PA_ADD_OPTION(channels); - - DiscordIntegrationSettingsOption::on_config_value_changed(this); - - this->add_listener(*this); - library0.add_listener(*this); -} -void DiscordIntegrationSettingsOption::on_config_value_changed([[maybe_unused]] void* object){ -// cout << this->enabled() << endl; -#if (defined PA_SLEEPY || defined PA_DPP) - bool options_enabled = this->enabled(); - switch (library0){ -#ifdef PA_SLEEPY - case Library::SleepyDiscord:{ - options_enabled &= !SleepyDiscordRunner::is_running(); - ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; - - library0.set_visibility(state); - command_type.set_visibility(ConfigOptionState::HIDDEN); - token.set_visibility(state); - game_status.set_visibility(state); - hello_message.set_visibility(state); - - command_prefix.set_visibility(state); - use_suffix.set_visibility(state); - sudo.set_visibility(state); - owner.set_visibility(state); - allow_buttons_from_users.set_visibility(ConfigOptionState::HIDDEN); - break; - } -#endif -#ifdef PA_DPP - case Library::DPP:{ - options_enabled &= !DppClient::Client::instance().is_initialized(); - ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; - - library0.set_visibility(state); - command_type.set_visibility(state); - token.set_visibility(state); - game_status.set_visibility(state); - hello_message.set_visibility(state); - allow_buttons_from_users.set_visibility(state); - - command_prefix.set_visibility(state); - use_suffix.set_visibility(ConfigOptionState::HIDDEN); - sudo.set_visibility(ConfigOptionState::HIDDEN); - owner.set_visibility(ConfigOptionState::HIDDEN); - break; - } -#endif - default:; - } -#endif -} - - -class DiscordIntegrationSettingsWidget : public GroupWidget{ -public: - DiscordIntegrationSettingsWidget(QWidget& parent, DiscordIntegrationSettingsOption& value); -}; -ConfigWidget* DiscordIntegrationSettingsOption::make_QtWidget(QWidget& parent){ - return new DiscordIntegrationSettingsWidget(parent, *this); -} - -DiscordIntegrationSettingsWidget::DiscordIntegrationSettingsWidget(QWidget& parent, DiscordIntegrationSettingsOption& value) - : GroupWidget(parent, value) -{ -#if (defined PA_SLEEPY || defined PA_DPP) - - QWidget* control_buttons = new QWidget(this); - m_options_layout->insertWidget(0, control_buttons); - - QHBoxLayout* layout = new QHBoxLayout(control_buttons); - layout->setContentsMargins(5, 5, 5, 5); - - QLabel* text = new QLabel("Bot Control:", control_buttons); - layout->addWidget(text, 2); - text->setWordWrap(true); - - QPushButton* button_start = new QPushButton("Start Bot", this); - layout->addWidget(button_start, 1); - - QPushButton* button_stop = new QPushButton("Stop Bot", this); - layout->addWidget(button_stop, 1); - - QFont font = button_start->font(); - font.setBold(true); - button_start->setFont(font); - button_stop->setFont(font); - - connect( - button_start, &QPushButton::clicked, - this, [this, &value](bool){ - switch (value.library0){ -#ifdef PA_SLEEPY - case DiscordIntegrationSettingsOption::Library::SleepyDiscord: - SleepyDiscordRunner::sleepy_connect(); - break; -#endif -#ifdef PA_DPP - case DiscordIntegrationSettingsOption::Library::DPP: - DppClient::Client::instance().connect(); - break; -#endif - default:; - } - value.on_config_value_changed(this); - } - ); - connect( - button_stop, &QPushButton::clicked, - this, [this, &value](bool){ - switch (value.library0){ -#ifdef PA_SLEEPY - case DiscordIntegrationSettingsOption::Library::SleepyDiscord: - SleepyDiscordRunner::sleepy_terminate(); - break; -#endif -#ifdef PA_DPP - case DiscordIntegrationSettingsOption::Library::DPP: - DppClient::Client::instance().disconnect(); - break; -#endif - default:; - } - value.on_config_value_changed(this); - } - ); - -#endif -} - - - - - - -std::string convert(const std::string& message){ - std::u32string ret; - std::u32string block; - for (char32_t ch : to_utf32(message)){ - switch (ch){ - case 38: - if (block.empty() || block.back() != 64){ - break; - } - continue; - case 64: - block += ch; - continue; - } - ret += ch; - block.clear(); - } - - return to_utf8(ret); -} - - -MessageBuilder::MessageBuilder(const std::vector& message_tags){ - for (const std::string& tag : message_tags){ - m_message_tags.insert(to_lower(tag)); - } -} -bool MessageBuilder::should_send(const std::vector& channel_tags) const{ - for (const std::string& tag : channel_tags){ - auto iter = m_message_tags.find(to_lower(tag)); - if (iter != m_message_tags.end()){ - return true; - } - } - return false; -} -std::string MessageBuilder::build_message( - std::chrono::seconds delay, - bool ping, const std::string& user_id, - const std::string& message -) const{ - if (std::atoll(user_id.c_str()) == 0){ - ping = false; - } - - std::string str; - if (ping){ - str += ""; - str[1]++; - } - - if (!message.empty()){ - if (!str.empty()){ - str += " "; - } - str += convert(message); - } - - auto delay_seconds = delay.count(); - if (delay_seconds != 0){ - if (!str.empty()){ - str += "\n"; - } - str += "*("; - str += "Message "; - str += "delay"; - str += "ed "; - str += "by " + std::to_string(delay_seconds); - str += delay_seconds == 1 - ? " second" - : " seconds"; - str += ".)*"; - } - - return str; -} - - - - - - -} -} +/* Discord Integration Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Qt/StringToolsQt.h" +//#include "CommonFramework/Globals.h" +//#include "CommonFramework/GlobalSettingsPanel.h" +#include "DppIntegration/DppClient.h" +#include "SleepyDiscordRunner.h" +#include "DiscordIntegrationSettings.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Integration{ + + +DiscordIntegrationSettingsOption::~DiscordIntegrationSettingsOption(){ + library0.remove_listener(*this); + this->remove_listener(*this); +} +DiscordIntegrationSettingsOption::DiscordIntegrationSettingsOption() + : GroupOption( + "Discord Integration Settings", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_DISABLED + ) +// , m_integration_enabled(integration_enabled) + , run_on_start( + "Run Discord Integration on Launch:
Automatically connect to Discord as soon as the program is launched.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , library0( + "Discord Integration Library:
Restart the program for this to take effect.", + { + {Library::SleepyDiscord, "sleepy", "Sleepy Discord (normal commands, deprecated)"}, + {Library::DPP, "dpp", "D++ (slash commands and normal commands)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Library::DPP + ) + , command_type( + "Discord Integration Command Type:
Restart the program for this to take effect.", + { + {CommandType::SlashCommands, "slash", "Slash commands"}, + {CommandType::MessageCommands, "message", "Message (prefix) commands"}, + }, + LockMode::LOCK_WHILE_RUNNING, + CommandType::SlashCommands + ) + , token( + true, + "Discord Token:
Enter your Discord bot's token. Keep it safe and don't share it with anyone.", + LockMode::LOCK_WHILE_RUNNING, + "", "0123456789abcdefghijklmnopqrstuvwxyzABCDEGFHIJKLMNOPQRSTUVWXYZ" + ) + , command_prefix( + false, + "Discord Command Prefix:
Enter a command prefix for your bot.", + LockMode::LOCK_WHILE_RUNNING, + "^", "^" + ) + , use_suffix( + "Use Suffix (Sleepy):
Use a suffix instead of a prefix for commands.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , game_status( + false, + "Discord Game Status:
Enter a status message your bot would display.", + LockMode::LOCK_WHILE_RUNNING, + "", "Controlling your Switch. :)" + ) + , hello_message( + false, + "Discord Hello Message:
Enter a message you'd like the bot to respond with to the \"$hi\" command.", + LockMode::LOCK_WHILE_RUNNING, + "", "Automation at your service!" + ) + , sudo( + false, + "Discord Sudo (Sleepy):
Enter user ID(s) to grant sudo access to.", + LockMode::LOCK_WHILE_RUNNING, + "", "123456789012345678" + ) + , owner( + false, + "Discord Owner (Sleepy):
Enter the bot owner's ID (your own ID).", + LockMode::LOCK_WHILE_RUNNING, + "", "123456789012345678" + ) + , allow_buttons_from_users( + "Allow Buttons from Users:
Allow other users to issue button presses.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(run_on_start); + PA_ADD_OPTION(library0); + PA_ADD_OPTION(command_type); + PA_ADD_OPTION(token); + PA_ADD_OPTION(command_prefix); + PA_ADD_OPTION(use_suffix); + PA_ADD_OPTION(game_status); + PA_ADD_OPTION(hello_message); + PA_ADD_OPTION(sudo); + PA_ADD_OPTION(owner); + PA_ADD_OPTION(allow_buttons_from_users); + PA_ADD_OPTION(channels); + + DiscordIntegrationSettingsOption::on_config_value_changed(this); + + this->add_listener(*this); + library0.add_listener(*this); +} +void DiscordIntegrationSettingsOption::on_config_value_changed([[maybe_unused]] void* object){ +// cout << this->enabled() << endl; +#if (defined PA_SLEEPY || defined PA_DPP) + bool options_enabled = this->enabled(); + switch (library0){ +#ifdef PA_SLEEPY + case Library::SleepyDiscord:{ + options_enabled &= !SleepyDiscordRunner::is_running(); + ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; + + library0.set_visibility(state); + command_type.set_visibility(ConfigOptionState::HIDDEN); + token.set_visibility(state); + game_status.set_visibility(state); + hello_message.set_visibility(state); + + command_prefix.set_visibility(state); + use_suffix.set_visibility(state); + sudo.set_visibility(state); + owner.set_visibility(state); + allow_buttons_from_users.set_visibility(ConfigOptionState::HIDDEN); + break; + } +#endif +#ifdef PA_DPP + case Library::DPP:{ + options_enabled &= !DppClient::Client::instance().is_initialized(); + ConfigOptionState state = options_enabled ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED; + + library0.set_visibility(state); + command_type.set_visibility(state); + token.set_visibility(state); + game_status.set_visibility(state); + hello_message.set_visibility(state); + allow_buttons_from_users.set_visibility(state); + + command_prefix.set_visibility(state); + use_suffix.set_visibility(ConfigOptionState::HIDDEN); + sudo.set_visibility(ConfigOptionState::HIDDEN); + owner.set_visibility(ConfigOptionState::HIDDEN); + break; + } +#endif + default:; + } +#endif +} + + +class DiscordIntegrationSettingsWidget : public GroupWidget{ +public: + DiscordIntegrationSettingsWidget(QWidget& parent, DiscordIntegrationSettingsOption& value); +}; +ConfigWidget* DiscordIntegrationSettingsOption::make_QtWidget(QWidget& parent){ + return new DiscordIntegrationSettingsWidget(parent, *this); +} + +DiscordIntegrationSettingsWidget::DiscordIntegrationSettingsWidget(QWidget& parent, DiscordIntegrationSettingsOption& value) + : GroupWidget(parent, value) +{ +#if (defined PA_SLEEPY || defined PA_DPP) + + QWidget* control_buttons = new QWidget(this); + m_options_layout->insertWidget(0, control_buttons); + + QHBoxLayout* layout = new QHBoxLayout(control_buttons); + layout->setContentsMargins(5, 5, 5, 5); + + QLabel* text = new QLabel("Bot Control:", control_buttons); + layout->addWidget(text, 2); + text->setWordWrap(true); + + QPushButton* button_start = new QPushButton("Start Bot", this); + layout->addWidget(button_start, 1); + + QPushButton* button_stop = new QPushButton("Stop Bot", this); + layout->addWidget(button_stop, 1); + + QFont font = button_start->font(); + font.setBold(true); + button_start->setFont(font); + button_stop->setFont(font); + + connect( + button_start, &QPushButton::clicked, + this, [this, &value](bool){ + switch (value.library0){ +#ifdef PA_SLEEPY + case DiscordIntegrationSettingsOption::Library::SleepyDiscord: + SleepyDiscordRunner::sleepy_connect(); + break; +#endif +#ifdef PA_DPP + case DiscordIntegrationSettingsOption::Library::DPP: + DppClient::Client::instance().connect(); + break; +#endif + default:; + } + value.on_config_value_changed(this); + } + ); + connect( + button_stop, &QPushButton::clicked, + this, [this, &value](bool){ + switch (value.library0){ +#ifdef PA_SLEEPY + case DiscordIntegrationSettingsOption::Library::SleepyDiscord: + SleepyDiscordRunner::sleepy_terminate(); + break; +#endif +#ifdef PA_DPP + case DiscordIntegrationSettingsOption::Library::DPP: + DppClient::Client::instance().disconnect(); + break; +#endif + default:; + } + value.on_config_value_changed(this); + } + ); + +#endif +} + + + + + + +std::string convert(const std::string& message){ + std::u32string ret; + std::u32string block; + for (char32_t ch : to_utf32(message)){ + switch (ch){ + case 38: + if (block.empty() || block.back() != 64){ + break; + } + continue; + case 64: + block += ch; + continue; + } + ret += ch; + block.clear(); + } + + return to_utf8(ret); +} + + +MessageBuilder::MessageBuilder(const std::vector& message_tags){ + for (const std::string& tag : message_tags){ + m_message_tags.insert(to_lower(tag)); + } +} +bool MessageBuilder::should_send(const std::vector& channel_tags) const{ + for (const std::string& tag : channel_tags){ + auto iter = m_message_tags.find(to_lower(tag)); + if (iter != m_message_tags.end()){ + return true; + } + } + return false; +} +std::string MessageBuilder::build_message( + std::chrono::seconds delay, + bool ping, const std::string& user_id, + const std::string& message +) const{ + if (std::atoll(user_id.c_str()) == 0){ + ping = false; + } + + std::string str; + if (ping){ + str += ""; + str[1]++; + } + + if (!message.empty()){ + if (!str.empty()){ + str += " "; + } + str += convert(message); + } + + auto delay_seconds = delay.count(); + if (delay_seconds != 0){ + if (!str.empty()){ + str += "\n"; + } + str += "*("; + str += "Message "; + str += "delay"; + str += "ed "; + str += "by " + std::to_string(delay_seconds); + str += delay_seconds == 1 + ? " second" + : " seconds"; + str += ".)*"; + } + + return str; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h index d488952e1b..48d63ae865 100644 --- a/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h +++ b/SerialPrograms/Source/Integrations/DiscordIntegrationSettings.h @@ -1,78 +1,78 @@ -/* Discord Integration Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DiscordIntegrationSettings_H -#define PokemonAutomation_DiscordIntegrationSettings_H - -#include -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Qt/Options/GroupWidget.h" -#include "DiscordIntegrationTable.h" - -namespace PokemonAutomation{ -namespace Integration{ - - -class DiscordIntegrationSettingsOption : public GroupOption, private ConfigOption::Listener{ -public: - ~DiscordIntegrationSettingsOption(); - DiscordIntegrationSettingsOption(); - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - virtual void on_config_value_changed(void* object) override; - - BooleanCheckBoxOption run_on_start; - - enum class Library{ - SleepyDiscord, - DPP, - }; - EnumDropdownOption library0; - - enum class CommandType{ - SlashCommands, - MessageCommands, - }; - EnumDropdownOption command_type; - - StringOption token; - StringOption command_prefix; - BooleanCheckBoxOption use_suffix; - StringOption game_status; - StringOption hello_message; - StringOption sudo; - StringOption owner; - BooleanCheckBoxOption allow_buttons_from_users; - DiscordIntegrationTable channels; -}; - - - -class MessageBuilder{ -public: - MessageBuilder(const std::vector& message_tags); - - bool should_send(const std::vector& channel_tags) const; - std::string build_message( - std::chrono::seconds delay, - bool ping, const std::string& user_id, - const std::string& message - ) const; - -private: - std::set m_message_tags; -}; - - - - - -} -} -#endif +/* Discord Integration Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DiscordIntegrationSettings_H +#define PokemonAutomation_DiscordIntegrationSettings_H + +#include +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Qt/Options/GroupWidget.h" +#include "DiscordIntegrationTable.h" + +namespace PokemonAutomation{ +namespace Integration{ + + +class DiscordIntegrationSettingsOption : public GroupOption, private ConfigOption::Listener{ +public: + ~DiscordIntegrationSettingsOption(); + DiscordIntegrationSettingsOption(); + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + virtual void on_config_value_changed(void* object) override; + + BooleanCheckBoxOption run_on_start; + + enum class Library{ + SleepyDiscord, + DPP, + }; + EnumDropdownOption library0; + + enum class CommandType{ + SlashCommands, + MessageCommands, + }; + EnumDropdownOption command_type; + + StringOption token; + StringOption command_prefix; + BooleanCheckBoxOption use_suffix; + StringOption game_status; + StringOption hello_message; + StringOption sudo; + StringOption owner; + BooleanCheckBoxOption allow_buttons_from_users; + DiscordIntegrationTable channels; +}; + + + +class MessageBuilder{ +public: + MessageBuilder(const std::vector& message_tags); + + bool should_send(const std::vector& channel_tags) const; + std::string build_message( + std::chrono::seconds delay, + bool ping, const std::string& user_id, + const std::string& message + ) const; + +private: + std::set m_message_tags; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DiscordIntegrationTable.cpp b/SerialPrograms/Source/Integrations/DiscordIntegrationTable.cpp index 42aba863c4..773fb8f6dd 100644 --- a/SerialPrograms/Source/Integrations/DiscordIntegrationTable.cpp +++ b/SerialPrograms/Source/Integrations/DiscordIntegrationTable.cpp @@ -1,115 +1,115 @@ -/* Discord Integration Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "DiscordIntegrationTable.h" - -namespace PokemonAutomation{ -namespace Integration{ - - - -DiscordIntegrationChannel::DiscordIntegrationChannel(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , enabled(LockMode::UNLOCK_WHILE_RUNNING, true) - , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "My test server") - , ping(LockMode::UNLOCK_WHILE_RUNNING, true) - , tags_text(false, LockMode::UNLOCK_WHILE_RUNNING, "Notifs, Showcase, LiveHost", "") - , allow_commands(LockMode::UNLOCK_WHILE_RUNNING, true) - , delay(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, 10) - , channel_id(false, LockMode::UNLOCK_WHILE_RUNNING, "", "123456789012345678") -{ - // Keep the old JSON tags for backwards compatibility. - add_option(enabled, "Enabled"); - add_option(label, "Label"); - add_option(ping, "Ping"); - add_option(tags_text, "Tags"); - add_option(allow_commands, "Commands"); - add_option(delay, "Delay"); - add_option(channel_id, "Channel"); -} -std::unique_ptr DiscordIntegrationChannel::clone() const{ - std::unique_ptr ret(new DiscordIntegrationChannel(parent())); - ret->enabled = (bool)enabled; - ret->label.set(label); - ret->ping = (bool)ping; - ret->tags_text.set(tags_text); - ret->allow_commands = (bool)allow_commands; - ret->delay.set(delay); - ret->channel_id.set(channel_id); - return ret; -} -void DiscordIntegrationChannel::load_json(const JsonValue& json){ - EditableTableRow::load_json(json); - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - // Load the old tags format. - const JsonArray* array = obj->get_array("Tags"); - if (array){ - std::string tags; - for (const auto& tag : *array){ - const std::string* str = tag.to_string(); - if (str == nullptr){ - continue; - } - std::string token = EventNotificationOption::sanitize_tag(*str); - if (!token.empty()){ - if (!tags.empty()){ - tags += ", "; - } - tags += token; - } - } - tags_text.set(std::move(tags)); - } -} - - - -DiscordIntegrationTable::DiscordIntegrationTable() - : EditableTableOption_t( - "Discord Channels: Configure which channels to send notifications and accept commands in.", - LockMode::UNLOCK_WHILE_RUNNING - ) -{} -std::vector DiscordIntegrationTable::make_header() const{ - return std::vector{ - "Enabled", - "Description", - "Allow Pings", - "Tags", - "Allow Commands", - "Delay (seconds)", - "Channel ID", - }; -} -std::vector DiscordIntegrationTable::command_channels() const{ - std::vector> table = copy_snapshot(); - std::vector ret; - for (const auto& channel : table){ - if (channel->enabled && channel->allow_commands){ - ret.emplace_back(channel->channel_id); - } - } - return ret; -} - - - - - - - - - -} -} +/* Discord Integration Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "DiscordIntegrationTable.h" + +namespace PokemonAutomation{ +namespace Integration{ + + + +DiscordIntegrationChannel::DiscordIntegrationChannel(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , enabled(LockMode::UNLOCK_WHILE_RUNNING, true) + , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "My test server") + , ping(LockMode::UNLOCK_WHILE_RUNNING, true) + , tags_text(false, LockMode::UNLOCK_WHILE_RUNNING, "Notifs, Showcase, LiveHost", "") + , allow_commands(LockMode::UNLOCK_WHILE_RUNNING, true) + , delay(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, 10) + , channel_id(false, LockMode::UNLOCK_WHILE_RUNNING, "", "123456789012345678") +{ + // Keep the old JSON tags for backwards compatibility. + add_option(enabled, "Enabled"); + add_option(label, "Label"); + add_option(ping, "Ping"); + add_option(tags_text, "Tags"); + add_option(allow_commands, "Commands"); + add_option(delay, "Delay"); + add_option(channel_id, "Channel"); +} +std::unique_ptr DiscordIntegrationChannel::clone() const{ + std::unique_ptr ret(new DiscordIntegrationChannel(parent())); + ret->enabled = (bool)enabled; + ret->label.set(label); + ret->ping = (bool)ping; + ret->tags_text.set(tags_text); + ret->allow_commands = (bool)allow_commands; + ret->delay.set(delay); + ret->channel_id.set(channel_id); + return ret; +} +void DiscordIntegrationChannel::load_json(const JsonValue& json){ + EditableTableRow::load_json(json); + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + // Load the old tags format. + const JsonArray* array = obj->get_array("Tags"); + if (array){ + std::string tags; + for (const auto& tag : *array){ + const std::string* str = tag.to_string(); + if (str == nullptr){ + continue; + } + std::string token = EventNotificationOption::sanitize_tag(*str); + if (!token.empty()){ + if (!tags.empty()){ + tags += ", "; + } + tags += token; + } + } + tags_text.set(std::move(tags)); + } +} + + + +DiscordIntegrationTable::DiscordIntegrationTable() + : EditableTableOption_t( + "Discord Channels: Configure which channels to send notifications and accept commands in.", + LockMode::UNLOCK_WHILE_RUNNING + ) +{} +std::vector DiscordIntegrationTable::make_header() const{ + return std::vector{ + "Enabled", + "Description", + "Allow Pings", + "Tags", + "Allow Commands", + "Delay (seconds)", + "Channel ID", + }; +} +std::vector DiscordIntegrationTable::command_channels() const{ + std::vector> table = copy_snapshot(); + std::vector ret; + for (const auto& channel : table){ + if (channel->enabled && channel->allow_commands){ + ret.emplace_back(channel->channel_id); + } + } + return ret; +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Integrations/DiscordIntegrationTable.h b/SerialPrograms/Source/Integrations/DiscordIntegrationTable.h index 651a530488..287b53ac7f 100644 --- a/SerialPrograms/Source/Integrations/DiscordIntegrationTable.h +++ b/SerialPrograms/Source/Integrations/DiscordIntegrationTable.h @@ -1,51 +1,51 @@ -/* Discord Integration Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DiscordIntegrationTable_H -#define PokemonAutomation_DiscordIntegrationTable_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace Integration{ - -class DiscordIntegrationTable; - - -class DiscordIntegrationChannel : public EditableTableRow{ -public: - DiscordIntegrationChannel(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - virtual void load_json(const JsonValue& json) override; - -public: - BooleanCheckBoxCell enabled; - StringCell label; - BooleanCheckBoxCell ping; - StringCell tags_text; - BooleanCheckBoxCell allow_commands; - SimpleIntegerCell delay; - StringCell channel_id; -}; - -class DiscordIntegrationTable : public EditableTableOption_t{ -public: - DiscordIntegrationTable(); - virtual std::vector make_header() const override; - std::vector command_channels() const; -}; - - - - - - -} -} -#endif +/* Discord Integration Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DiscordIntegrationTable_H +#define PokemonAutomation_DiscordIntegrationTable_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace Integration{ + +class DiscordIntegrationTable; + + +class DiscordIntegrationChannel : public EditableTableRow{ +public: + DiscordIntegrationChannel(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + virtual void load_json(const JsonValue& json) override; + +public: + BooleanCheckBoxCell enabled; + StringCell label; + BooleanCheckBoxCell ping; + StringCell tags_text; + BooleanCheckBoxCell allow_commands; + SimpleIntegerCell delay; + StringCell channel_id; +}; + +class DiscordIntegrationTable : public EditableTableOption_t{ +public: + DiscordIntegrationTable(); + virtual std::vector make_header() const override; + std::vector command_channels() const; +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp b/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp index 5106f542c5..be2d0438ac 100644 --- a/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp +++ b/SerialPrograms/Source/Integrations/DiscordSettingsOption.cpp @@ -1,84 +1,84 @@ -/* Discord Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/Options/BatchWidget.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "DiscordSettingsOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Integration{ - - - - - -DiscordMessageSettingsOption::DiscordMessageSettingsOption() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , instance_name( - false, - "Instance Name:
If you are running multiple instances of this program, give it a name to distinguish them in notifications.", - LockMode::LOCK_WHILE_RUNNING, - "", - "(e.g. Living Room Switch)" - ) - , user_id( - false, - "Discord User ID:
Set this to your discord user ID to receive pings. Your ID is a number.", - LockMode::LOCK_WHILE_RUNNING, - "", - "123456789012345678" - ) - , message( - false, - "Discord Message:
Message to put on every discord notification.", - LockMode::LOCK_WHILE_RUNNING, - "", - "(e.g. Kim's Shiny Hunt)" - ) -{ - PA_ADD_OPTION(instance_name); - PA_ADD_OPTION(user_id); -// if (PreloadSettings::instance().DEVELOPER_MODE){ -// PA_ADD_OPTION(message); -// } -} -class DiscordMessageSettingsOptionUI : public BatchWidget{ -public: - DiscordMessageSettingsOptionUI(QWidget& parent, DiscordMessageSettingsOption& value); -}; -DiscordMessageSettingsOptionUI::DiscordMessageSettingsOptionUI(QWidget& parent, DiscordMessageSettingsOption& value) - : BatchWidget(parent, value) -{} -ConfigWidget* DiscordMessageSettingsOption::make_QtWidget(QWidget& parent){ - return new DiscordMessageSettingsOptionUI(parent, *this); -} - - - - - - -DiscordSettingsOption::DiscordSettingsOption() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) -{ - PA_ADD_OPTION(message); - PA_ADD_OPTION(webhooks); -#if defined PA_SLEEPY || defined PA_DPP - PA_ADD_OPTION(integration); -#endif -} - - - - - -} -} - +/* Discord Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/Options/BatchWidget.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "DiscordSettingsOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Integration{ + + + + + +DiscordMessageSettingsOption::DiscordMessageSettingsOption() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , instance_name( + false, + "Instance Name:
If you are running multiple instances of this program, give it a name to distinguish them in notifications.", + LockMode::LOCK_WHILE_RUNNING, + "", + "(e.g. Living Room Switch)" + ) + , user_id( + false, + "Discord User ID:
Set this to your discord user ID to receive pings. Your ID is a number.", + LockMode::LOCK_WHILE_RUNNING, + "", + "123456789012345678" + ) + , message( + false, + "Discord Message:
Message to put on every discord notification.", + LockMode::LOCK_WHILE_RUNNING, + "", + "(e.g. Kim's Shiny Hunt)" + ) +{ + PA_ADD_OPTION(instance_name); + PA_ADD_OPTION(user_id); +// if (PreloadSettings::instance().DEVELOPER_MODE){ +// PA_ADD_OPTION(message); +// } +} +class DiscordMessageSettingsOptionUI : public BatchWidget{ +public: + DiscordMessageSettingsOptionUI(QWidget& parent, DiscordMessageSettingsOption& value); +}; +DiscordMessageSettingsOptionUI::DiscordMessageSettingsOptionUI(QWidget& parent, DiscordMessageSettingsOption& value) + : BatchWidget(parent, value) +{} +ConfigWidget* DiscordMessageSettingsOption::make_QtWidget(QWidget& parent){ + return new DiscordMessageSettingsOptionUI(parent, *this); +} + + + + + + +DiscordSettingsOption::DiscordSettingsOption() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) +{ + PA_ADD_OPTION(message); + PA_ADD_OPTION(webhooks); +#if defined PA_SLEEPY || defined PA_DPP + PA_ADD_OPTION(integration); +#endif +} + + + + + +} +} + diff --git a/SerialPrograms/Source/Integrations/DiscordSettingsOption.h b/SerialPrograms/Source/Integrations/DiscordSettingsOption.h index 10f902e629..b7b0753a76 100644 --- a/SerialPrograms/Source/Integrations/DiscordSettingsOption.h +++ b/SerialPrograms/Source/Integrations/DiscordSettingsOption.h @@ -1,48 +1,48 @@ -/* Discord Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DiscordSettings_H -#define PokemonAutomation_DiscordSettings_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "DiscordWebhookSettings.h" -#include "DiscordIntegrationSettings.h" - -namespace PokemonAutomation{ -namespace Integration{ - - -class DiscordMessageSettingsOption : public BatchOption{ -public: - DiscordMessageSettingsOption(); - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - StringOption instance_name; - StringOption user_id; - StringOption message; -}; - - - - - - -class DiscordSettingsOption : public BatchOption{ -public: - DiscordSettingsOption(); - - DiscordMessageSettingsOption message; - DiscordWebhookSettingsOption webhooks; - DiscordIntegrationSettingsOption integration; -}; - - - - -} -} -#endif +/* Discord Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DiscordSettings_H +#define PokemonAutomation_DiscordSettings_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "DiscordWebhookSettings.h" +#include "DiscordIntegrationSettings.h" + +namespace PokemonAutomation{ +namespace Integration{ + + +class DiscordMessageSettingsOption : public BatchOption{ +public: + DiscordMessageSettingsOption(); + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + StringOption instance_name; + StringOption user_id; + StringOption message; +}; + + + + + + +class DiscordSettingsOption : public BatchOption{ +public: + DiscordSettingsOption(); + + DiscordMessageSettingsOption message; + DiscordWebhookSettingsOption webhooks; + DiscordIntegrationSettingsOption integration; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DiscordWebhook.cpp b/SerialPrograms/Source/Integrations/DiscordWebhook.cpp index 89a8c77cae..ce9bf9ddfb 100644 --- a/SerialPrograms/Source/Integrations/DiscordWebhook.cpp +++ b/SerialPrograms/Source/Integrations/DiscordWebhook.cpp @@ -1,367 +1,367 @@ -/* Discord Webhook - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -//#include "Common/Cpp/PanicDump.h" -//#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "DiscordSettingsOption.h" -#include "DiscordWebhook.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Integration{ -namespace DiscordWebhook{ - - - -DiscordWebhookSender::DiscordWebhookSender() - : m_logger(global_logger_raw(), "DiscordWebhookSender") - , m_stopping(false) - , m_dispatcher(nullptr, 1) - , m_queue(m_dispatcher) -{} - -DiscordWebhookSender::~DiscordWebhookSender(){ - m_stopping.store(true, std::memory_order_release); - { - std::lock_guard lg(m_lock); - m_cv.notify_all(); - } - std::lock_guard lg(m_send_lock); - if (m_event_loop){ - m_event_loop->exit(); - } -} - -DiscordWebhookSender& DiscordWebhookSender::instance(){ - static DiscordWebhookSender sender; - return sender; -} - -void DiscordWebhookSender::send( - Logger& logger, - const QUrl& url, std::chrono::milliseconds delay, - const JsonObject& obj, - std::shared_ptr file, - std::function finish_callback -){ - cleanup_stuck_requests(); - std::shared_ptr json(new JsonValue(obj.clone())); -// cout << "Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")" << endl; - logger.log("Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); - m_queue.add_event( - delay, - [ - this, url, - json = std::move(json), - file = std::move(file), - finish_callback = std::move(finish_callback) - ]{ - throttle(); - std::vector attachments; - if (file){ - attachments.emplace_back( - DiscordFileAttachment{file->filename(), file->filepath()} - ); - } - internal_send(url, *json, attachments); - if (finish_callback){ - finish_callback(); - } - } - ); -} -void DiscordWebhookSender::send( - Logger& logger, - const QUrl& url, std::chrono::milliseconds delay, - const JsonObject& obj, - std::vector> files, - std::function finish_callback -){ - cleanup_stuck_requests(); - std::shared_ptr json(new JsonValue(obj.clone())); -// cout << "Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")" << endl; - logger.log("Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); - m_queue.add_event( - delay, - [ - this, url, - json = std::move(json), - files = std::move(files), - finish_callback = std::move(finish_callback) - ]{ - throttle(); - std::vector attachments; - for (auto& file : files){ - attachments.emplace_back( - DiscordFileAttachment{file->filename(), file->filepath()} - ); - } - internal_send(url, *json, attachments); - if (finish_callback){ - finish_callback(); - } - } - ); -} - -void DiscordWebhookSender::cleanup_stuck_requests(){ - { - std::lock_guard lg(m_lock); - WallClock next = m_queue.next_event(); - if (next == WallClock::max()){ - return; - } - - WallClock now = current_time(); - WallClock threshold = now - std::chrono::seconds(60); - if (next >= threshold){ - return; - } - } - - m_logger.log("Purging request that appears to be stuck.", COLOR_RED); - std::lock_guard lg(m_send_lock); - if (m_event_loop){ - m_event_loop->exit(); - } -} -void DiscordWebhookSender::throttle(){ - // Throttle the messages. - auto duration = THROTTLE_DURATION; - auto now = current_time(); - while (!m_sent.empty() && m_sent[0] + duration < now){ - m_sent.pop_front(); - } - if (!m_sent.empty() && m_sent.size() >= GlobalSettings::instance().DISCORD->webhooks.sends_per_second){ - m_logger.log("Throttling webhook messages due to rate limit...", COLOR_RED); - std::unique_lock lg(m_lock); - m_cv.wait_for( - lg, duration, - [&]{ return m_stopping.load(std::memory_order_relaxed) || m_sent.empty() || m_sent[0] + duration < now; } - ); - if (m_stopping.load(std::memory_order_relaxed)){ - return; - } - m_sent.clear(); - } - m_sent.push_back(now); -} - - -void DiscordWebhookSender::process_reply(QNetworkReply* reply){ - if (!reply){ - m_logger.log("QNetworkReply is null.", COLOR_RED); - }else if (reply->error() == QNetworkReply::NoError){ -// QString contents = QString::fromUtf8(reply->readAll()); -// qDebug() << contents; - }else{ - QString error_string = reply->errorString(); - QString url = reply->url().toString(); - qsizetype index = error_string.indexOf(url); - if (index >= 0){ - error_string.replace(index, url.size(), "****************"); - } - m_logger.log("Discord Request Response: " + error_string.toStdString(), COLOR_RED); -// QString err = reply->errorString(); -// qDebug() << err; - } -} - -void DiscordWebhookSender::internal_send( - const QUrl& url, const JsonValue& json, - const std::vector& files -){ - if (m_stopping.load(std::memory_order_acquire)){ - return; - } - - { - std::lock_guard lg(m_send_lock); - m_event_loop.reset(new QEventLoop); - } - - try{ - QHttpMultiPart multiPart(QHttpMultiPart::FormDataType); - if (!json.is_null()){ - QHttpPart json_part; - json_part.setHeader( - QNetworkRequest::ContentDispositionHeader, - QVariant("form-data; name=payload_json") - ); - json_part.setBody(QByteArray::fromStdString(json.dump())); - multiPart.append(json_part); - } - - std::vector file_parts; - std::deque file_readers; - file_parts.reserve(files.size()); - size_t c = 0; - for (const auto& file : files){ - QFile& reader = file_readers.emplace_back(QString::fromStdString(file.filepath)); - if (!reader.open(QIODevice::ReadOnly)){ - m_logger.log("File doesn't exist: " + file.filepath, COLOR_RED); - continue; - } - QHttpPart& part = file_parts.emplace_back(); - part.setHeader( - QNetworkRequest::ContentDispositionHeader, - QVariant(QString::fromStdString("application/octet-stream; name=file" + std::to_string(c) + "; filename=" + file.name)) - ); - part.setBodyDevice(&reader); - multiPart.append(part); - c++; - } - - QNetworkRequest request(url); - QNetworkAccessManager manager; - m_event_loop->connect(&manager, SIGNAL(finished(QNetworkReply*)), SLOT(quit())); -// cout << "Sending Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")" << endl; - m_logger.log("Sending Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_BLUE); - std::unique_ptr reply(manager.post(request, &multiPart)); - - if (!m_stopping.load(std::memory_order_acquire)){ -// cout << "internal_send() - exec" << endl; - - m_event_loop->exec(); - process_reply(reply.get()); - -// cout << "internal_send() - end" << endl; - } - }catch (...){ - std::lock_guard lg(m_send_lock); - m_event_loop.reset(); - throw; - } - - std::lock_guard lg(m_send_lock); - m_event_loop.reset(); -} - - - -void send_embed( - Logger& logger, - bool should_ping, - const std::vector& tags, - const JsonArray& embeds, - std::shared_ptr file -){ - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!settings.webhooks.enabled()){ - return; - } - - MessageBuilder builder(tags); - - std::vector> list = settings.webhooks.urls.copy_snapshot(); - for (size_t c = 0; c < list.size(); c++){ - const DiscordWebhookUrl& url = *list[c]; - if (!url.enabled || ((std::string)url.url).empty()){ - continue; - } - if (!builder.should_send(EventNotificationOption::parse_tags(url.tags_text))){ - continue; - } - - std::chrono::seconds delay(url.delay); - - JsonObject json; - json["content"] = builder.build_message( - delay, - should_ping && url.ping, - settings.message.user_id, - settings.message.message - ); - if (!embeds.empty()){ - json["embeds"] = embeds.clone(); - } - - DiscordWebhookSender::instance().send( - logger, - QString::fromStdString(url.url), - delay, - std::move(json), - file - ); - } -} - -void send_embed( - Logger& logger, - bool should_ping, - const std::vector& tags, - const JsonArray& embeds, - const std::vector>& files -){ - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!settings.webhooks.enabled()){ - return; - } - - MessageBuilder builder(tags); - - std::vector> list = settings.webhooks.urls.copy_snapshot(); - for (size_t c = 0; c < list.size(); c++){ - const DiscordWebhookUrl& url = *list[c]; - if (!url.enabled || ((std::string)url.url).empty()){ - continue; - } - if (!builder.should_send(EventNotificationOption::parse_tags(url.tags_text))){ - continue; - } - - std::chrono::seconds delay(url.delay); - - JsonObject json; - json["content"] = builder.build_message( - delay, - should_ping && url.ping, - settings.message.user_id, - settings.message.message - ); - if (!embeds.empty()){ - json["embeds"] = embeds.clone(); - } - - DiscordWebhookSender::instance().send( - logger, - QString::fromStdString(url.url), - delay, - std::move(json), - files - ); - } -} - - - -} -} -} - - - - - - - - +/* Discord Webhook + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +//#include "Common/Cpp/PanicDump.h" +//#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "DiscordSettingsOption.h" +#include "DiscordWebhook.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Integration{ +namespace DiscordWebhook{ + + + +DiscordWebhookSender::DiscordWebhookSender() + : m_logger(global_logger_raw(), "DiscordWebhookSender") + , m_stopping(false) + , m_dispatcher(nullptr, 1) + , m_queue(m_dispatcher) +{} + +DiscordWebhookSender::~DiscordWebhookSender(){ + m_stopping.store(true, std::memory_order_release); + { + std::lock_guard lg(m_lock); + m_cv.notify_all(); + } + std::lock_guard lg(m_send_lock); + if (m_event_loop){ + m_event_loop->exit(); + } +} + +DiscordWebhookSender& DiscordWebhookSender::instance(){ + static DiscordWebhookSender sender; + return sender; +} + +void DiscordWebhookSender::send( + Logger& logger, + const QUrl& url, std::chrono::milliseconds delay, + const JsonObject& obj, + std::shared_ptr file, + std::function finish_callback +){ + cleanup_stuck_requests(); + std::shared_ptr json(new JsonValue(obj.clone())); +// cout << "Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")" << endl; + logger.log("Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); + m_queue.add_event( + delay, + [ + this, url, + json = std::move(json), + file = std::move(file), + finish_callback = std::move(finish_callback) + ]{ + throttle(); + std::vector attachments; + if (file){ + attachments.emplace_back( + DiscordFileAttachment{file->filename(), file->filepath()} + ); + } + internal_send(url, *json, attachments); + if (finish_callback){ + finish_callback(); + } + } + ); +} +void DiscordWebhookSender::send( + Logger& logger, + const QUrl& url, std::chrono::milliseconds delay, + const JsonObject& obj, + std::vector> files, + std::function finish_callback +){ + cleanup_stuck_requests(); + std::shared_ptr json(new JsonValue(obj.clone())); +// cout << "Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")" << endl; + logger.log("Scheduling Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); + m_queue.add_event( + delay, + [ + this, url, + json = std::move(json), + files = std::move(files), + finish_callback = std::move(finish_callback) + ]{ + throttle(); + std::vector attachments; + for (auto& file : files){ + attachments.emplace_back( + DiscordFileAttachment{file->filename(), file->filepath()} + ); + } + internal_send(url, *json, attachments); + if (finish_callback){ + finish_callback(); + } + } + ); +} + +void DiscordWebhookSender::cleanup_stuck_requests(){ + { + std::lock_guard lg(m_lock); + WallClock next = m_queue.next_event(); + if (next == WallClock::max()){ + return; + } + + WallClock now = current_time(); + WallClock threshold = now - std::chrono::seconds(60); + if (next >= threshold){ + return; + } + } + + m_logger.log("Purging request that appears to be stuck.", COLOR_RED); + std::lock_guard lg(m_send_lock); + if (m_event_loop){ + m_event_loop->exit(); + } +} +void DiscordWebhookSender::throttle(){ + // Throttle the messages. + auto duration = THROTTLE_DURATION; + auto now = current_time(); + while (!m_sent.empty() && m_sent[0] + duration < now){ + m_sent.pop_front(); + } + if (!m_sent.empty() && m_sent.size() >= GlobalSettings::instance().DISCORD->webhooks.sends_per_second){ + m_logger.log("Throttling webhook messages due to rate limit...", COLOR_RED); + std::unique_lock lg(m_lock); + m_cv.wait_for( + lg, duration, + [&]{ return m_stopping.load(std::memory_order_relaxed) || m_sent.empty() || m_sent[0] + duration < now; } + ); + if (m_stopping.load(std::memory_order_relaxed)){ + return; + } + m_sent.clear(); + } + m_sent.push_back(now); +} + + +void DiscordWebhookSender::process_reply(QNetworkReply* reply){ + if (!reply){ + m_logger.log("QNetworkReply is null.", COLOR_RED); + }else if (reply->error() == QNetworkReply::NoError){ +// QString contents = QString::fromUtf8(reply->readAll()); +// qDebug() << contents; + }else{ + QString error_string = reply->errorString(); + QString url = reply->url().toString(); + qsizetype index = error_string.indexOf(url); + if (index >= 0){ + error_string.replace(index, url.size(), "****************"); + } + m_logger.log("Discord Request Response: " + error_string.toStdString(), COLOR_RED); +// QString err = reply->errorString(); +// qDebug() << err; + } +} + +void DiscordWebhookSender::internal_send( + const QUrl& url, const JsonValue& json, + const std::vector& files +){ + if (m_stopping.load(std::memory_order_acquire)){ + return; + } + + { + std::lock_guard lg(m_send_lock); + m_event_loop.reset(new QEventLoop); + } + + try{ + QHttpMultiPart multiPart(QHttpMultiPart::FormDataType); + if (!json.is_null()){ + QHttpPart json_part; + json_part.setHeader( + QNetworkRequest::ContentDispositionHeader, + QVariant("form-data; name=payload_json") + ); + json_part.setBody(QByteArray::fromStdString(json.dump())); + multiPart.append(json_part); + } + + std::vector file_parts; + std::deque file_readers; + file_parts.reserve(files.size()); + size_t c = 0; + for (const auto& file : files){ + QFile& reader = file_readers.emplace_back(QString::fromStdString(file.filepath)); + if (!reader.open(QIODevice::ReadOnly)){ + m_logger.log("File doesn't exist: " + file.filepath, COLOR_RED); + continue; + } + QHttpPart& part = file_parts.emplace_back(); + part.setHeader( + QNetworkRequest::ContentDispositionHeader, + QVariant(QString::fromStdString("application/octet-stream; name=file" + std::to_string(c) + "; filename=" + file.name)) + ); + part.setBodyDevice(&reader); + multiPart.append(part); + c++; + } + + QNetworkRequest request(url); + QNetworkAccessManager manager; + m_event_loop->connect(&manager, SIGNAL(finished(QNetworkReply*)), SLOT(quit())); +// cout << "Sending Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")" << endl; + m_logger.log("Sending Webhook Message... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_BLUE); + std::unique_ptr reply(manager.post(request, &multiPart)); + + if (!m_stopping.load(std::memory_order_acquire)){ +// cout << "internal_send() - exec" << endl; + + m_event_loop->exec(); + process_reply(reply.get()); + +// cout << "internal_send() - end" << endl; + } + }catch (...){ + std::lock_guard lg(m_send_lock); + m_event_loop.reset(); + throw; + } + + std::lock_guard lg(m_send_lock); + m_event_loop.reset(); +} + + + +void send_embed( + Logger& logger, + bool should_ping, + const std::vector& tags, + const JsonArray& embeds, + std::shared_ptr file +){ + DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; + if (!settings.webhooks.enabled()){ + return; + } + + MessageBuilder builder(tags); + + std::vector> list = settings.webhooks.urls.copy_snapshot(); + for (size_t c = 0; c < list.size(); c++){ + const DiscordWebhookUrl& url = *list[c]; + if (!url.enabled || ((std::string)url.url).empty()){ + continue; + } + if (!builder.should_send(EventNotificationOption::parse_tags(url.tags_text))){ + continue; + } + + std::chrono::seconds delay(url.delay); + + JsonObject json; + json["content"] = builder.build_message( + delay, + should_ping && url.ping, + settings.message.user_id, + settings.message.message + ); + if (!embeds.empty()){ + json["embeds"] = embeds.clone(); + } + + DiscordWebhookSender::instance().send( + logger, + QString::fromStdString(url.url), + delay, + std::move(json), + file + ); + } +} + +void send_embed( + Logger& logger, + bool should_ping, + const std::vector& tags, + const JsonArray& embeds, + const std::vector>& files +){ + DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; + if (!settings.webhooks.enabled()){ + return; + } + + MessageBuilder builder(tags); + + std::vector> list = settings.webhooks.urls.copy_snapshot(); + for (size_t c = 0; c < list.size(); c++){ + const DiscordWebhookUrl& url = *list[c]; + if (!url.enabled || ((std::string)url.url).empty()){ + continue; + } + if (!builder.should_send(EventNotificationOption::parse_tags(url.tags_text))){ + continue; + } + + std::chrono::seconds delay(url.delay); + + JsonObject json; + json["content"] = builder.build_message( + delay, + should_ping && url.ping, + settings.message.user_id, + settings.message.message + ); + if (!embeds.empty()){ + json["embeds"] = embeds.clone(); + } + + DiscordWebhookSender::instance().send( + logger, + QString::fromStdString(url.url), + delay, + std::move(json), + files + ); + } +} + + + +} +} +} + + + + + + + + diff --git a/SerialPrograms/Source/Integrations/DiscordWebhook.h b/SerialPrograms/Source/Integrations/DiscordWebhook.h index a11993677d..faf4b9c6b9 100644 --- a/SerialPrograms/Source/Integrations/DiscordWebhook.h +++ b/SerialPrograms/Source/Integrations/DiscordWebhook.h @@ -1,112 +1,112 @@ -/* Discord Webhook - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DiscordWebhook_H -#define PokemonAutomation_DiscordWebhook_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Options/ScreenshotFormatOption.h" -#include "CommonFramework/Notifications/MessageAttachment.h" - -class QEventLoop; - -namespace PokemonAutomation{ - class JsonArray; - class JsonObject; -namespace Integration{ -namespace DiscordWebhook{ - - -struct DiscordFileAttachment{ - std::string name; - std::string filepath; -}; - - -class DiscordWebhookSender : public QObject{ - Q_OBJECT - - static constexpr auto THROTTLE_DURATION = std::chrono::seconds(1); -// static constexpr size_t MAX_IN_WINDOW = 2; - -private: - DiscordWebhookSender(); - ~DiscordWebhookSender(); - - -public: - void send( - Logger& logger, - const QUrl& url, std::chrono::milliseconds delay, - const JsonObject& obj, - std::shared_ptr file, - std::function finish_callback = nullptr - ); - void send( - Logger& logger, - const QUrl& url, std::chrono::milliseconds delay, - const JsonObject& obj, - std::vector> files, - std::function finish_callback = nullptr - ); - - static DiscordWebhookSender& instance(); - - -private: - void cleanup_stuck_requests(); -// void thread_loop(); - void throttle(); - - void process_reply(QNetworkReply* reply); - void internal_send( - const QUrl& url, const JsonValue& json, - const std::vector& files - ); - -private: - TaggedLogger m_logger; - std::atomic m_stopping; - std::mutex m_lock; - std::condition_variable m_cv; - - std::mutex m_send_lock; - std::unique_ptr m_event_loop; - - std::deque m_sent; - AsyncDispatcher m_dispatcher; - ScheduledTaskRunner m_queue; -}; - - - - -void send_embed( - Logger& logger, - bool should_ping, - const std::vector& tags, - const JsonArray& embeds, - std::shared_ptr file -); -void send_embed( - Logger& logger, - bool should_ping, - const std::vector& tags, - const JsonArray& embeds, - const std::vector>& files -); - - - -} -} -} -#endif +/* Discord Webhook + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DiscordWebhook_H +#define PokemonAutomation_DiscordWebhook_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Options/ScreenshotFormatOption.h" +#include "CommonFramework/Notifications/MessageAttachment.h" + +class QEventLoop; + +namespace PokemonAutomation{ + class JsonArray; + class JsonObject; +namespace Integration{ +namespace DiscordWebhook{ + + +struct DiscordFileAttachment{ + std::string name; + std::string filepath; +}; + + +class DiscordWebhookSender : public QObject{ + Q_OBJECT + + static constexpr auto THROTTLE_DURATION = std::chrono::seconds(1); +// static constexpr size_t MAX_IN_WINDOW = 2; + +private: + DiscordWebhookSender(); + ~DiscordWebhookSender(); + + +public: + void send( + Logger& logger, + const QUrl& url, std::chrono::milliseconds delay, + const JsonObject& obj, + std::shared_ptr file, + std::function finish_callback = nullptr + ); + void send( + Logger& logger, + const QUrl& url, std::chrono::milliseconds delay, + const JsonObject& obj, + std::vector> files, + std::function finish_callback = nullptr + ); + + static DiscordWebhookSender& instance(); + + +private: + void cleanup_stuck_requests(); +// void thread_loop(); + void throttle(); + + void process_reply(QNetworkReply* reply); + void internal_send( + const QUrl& url, const JsonValue& json, + const std::vector& files + ); + +private: + TaggedLogger m_logger; + std::atomic m_stopping; + std::mutex m_lock; + std::condition_variable m_cv; + + std::mutex m_send_lock; + std::unique_ptr m_event_loop; + + std::deque m_sent; + AsyncDispatcher m_dispatcher; + ScheduledTaskRunner m_queue; +}; + + + + +void send_embed( + Logger& logger, + bool should_ping, + const std::vector& tags, + const JsonArray& embeds, + std::shared_ptr file +); +void send_embed( + Logger& logger, + bool should_ping, + const std::vector& tags, + const JsonArray& embeds, + const std::vector>& files +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DiscordWebhookSettings.cpp b/SerialPrograms/Source/Integrations/DiscordWebhookSettings.cpp index 5bca0687d3..ae0e98eedf 100644 --- a/SerialPrograms/Source/Integrations/DiscordWebhookSettings.cpp +++ b/SerialPrograms/Source/Integrations/DiscordWebhookSettings.cpp @@ -1,113 +1,113 @@ -/* Discord Webhook Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "DiscordWebhookSettings.h" - -namespace PokemonAutomation{ -namespace Integration{ - - - -DiscordWebhookUrl::DiscordWebhookUrl(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , enabled(LockMode::LOCK_WHILE_RUNNING, true) - , label(false, LockMode::LOCK_WHILE_RUNNING, "", "My test server") - , ping(LockMode::LOCK_WHILE_RUNNING, true) - , tags_text(false, LockMode::LOCK_WHILE_RUNNING, "Notifs, Showcase, LiveHost", "") - , delay(LockMode::LOCK_WHILE_RUNNING, 0, 0, 10) - , url(true, LockMode::LOCK_WHILE_RUNNING, "", "https://discord.com/api/webhooks/123456789012345678/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") -{ - // Keep the old JSON tags for backwards compatibility. - add_option(enabled, "Enabled"); - add_option(label, "Label"); - add_option(ping, "Ping"); - add_option(tags_text, "Tags"); - add_option(delay, "Delay"); - add_option(url, "URL"); -} -std::unique_ptr DiscordWebhookUrl::clone() const{ - std::unique_ptr ret(new DiscordWebhookUrl(parent())); - ret->enabled = (bool)enabled; - ret->label.set(label); - ret->ping = (bool)ping; - ret->tags_text.set(tags_text); - ret->delay.set(delay); - ret->url.set(url); - return ret; -} -void DiscordWebhookUrl::load_json(const JsonValue& json){ - EditableTableRow::load_json(json); - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - // Load the old tags format. - const JsonArray* array = obj->get_array("Tags"); - if (array){ - std::string tags; - for (const auto& tag : *array){ - const std::string* str = tag.to_string(); - if (str == nullptr){ - continue; - } - std::string token = EventNotificationOption::sanitize_tag(*str); - if (!token.empty()){ - if (!tags.empty()){ - tags += ", "; - } - tags += token; - } - } - tags_text.set(std::move(tags)); - } -} - - - -DiscordWebhookSettingsTable::DiscordWebhookSettingsTable() - : EditableTableOption_t( - "Discord Webhook URLs: Notifications are sent to all enabled URLs that share a tag with the event.", - LockMode::LOCK_WHILE_RUNNING - ) -{} -std::vector DiscordWebhookSettingsTable::make_header() const{ - return std::vector{ - "Enabled", - "Description", - "Allow Pings", - "Tags", - "Delay (seconds)", - "Webhook URL", - }; -} - - - - -DiscordWebhookSettingsOption::DiscordWebhookSettingsOption() - : GroupOption( - "Discord Webhook Settings", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_ENABLED, false - ) - , sends_per_second( - "Rate Limit:
Maximum number of sends per second.", - LockMode::LOCK_WHILE_RUNNING, 2, 1 - ) -{ - PA_ADD_OPTION(urls); - PA_ADD_OPTION(sends_per_second); -} - - - -} -} +/* Discord Webhook Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "DiscordWebhookSettings.h" + +namespace PokemonAutomation{ +namespace Integration{ + + + +DiscordWebhookUrl::DiscordWebhookUrl(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , enabled(LockMode::LOCK_WHILE_RUNNING, true) + , label(false, LockMode::LOCK_WHILE_RUNNING, "", "My test server") + , ping(LockMode::LOCK_WHILE_RUNNING, true) + , tags_text(false, LockMode::LOCK_WHILE_RUNNING, "Notifs, Showcase, LiveHost", "") + , delay(LockMode::LOCK_WHILE_RUNNING, 0, 0, 10) + , url(true, LockMode::LOCK_WHILE_RUNNING, "", "https://discord.com/api/webhooks/123456789012345678/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") +{ + // Keep the old JSON tags for backwards compatibility. + add_option(enabled, "Enabled"); + add_option(label, "Label"); + add_option(ping, "Ping"); + add_option(tags_text, "Tags"); + add_option(delay, "Delay"); + add_option(url, "URL"); +} +std::unique_ptr DiscordWebhookUrl::clone() const{ + std::unique_ptr ret(new DiscordWebhookUrl(parent())); + ret->enabled = (bool)enabled; + ret->label.set(label); + ret->ping = (bool)ping; + ret->tags_text.set(tags_text); + ret->delay.set(delay); + ret->url.set(url); + return ret; +} +void DiscordWebhookUrl::load_json(const JsonValue& json){ + EditableTableRow::load_json(json); + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + // Load the old tags format. + const JsonArray* array = obj->get_array("Tags"); + if (array){ + std::string tags; + for (const auto& tag : *array){ + const std::string* str = tag.to_string(); + if (str == nullptr){ + continue; + } + std::string token = EventNotificationOption::sanitize_tag(*str); + if (!token.empty()){ + if (!tags.empty()){ + tags += ", "; + } + tags += token; + } + } + tags_text.set(std::move(tags)); + } +} + + + +DiscordWebhookSettingsTable::DiscordWebhookSettingsTable() + : EditableTableOption_t( + "Discord Webhook URLs: Notifications are sent to all enabled URLs that share a tag with the event.", + LockMode::LOCK_WHILE_RUNNING + ) +{} +std::vector DiscordWebhookSettingsTable::make_header() const{ + return std::vector{ + "Enabled", + "Description", + "Allow Pings", + "Tags", + "Delay (seconds)", + "Webhook URL", + }; +} + + + + +DiscordWebhookSettingsOption::DiscordWebhookSettingsOption() + : GroupOption( + "Discord Webhook Settings", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_ENABLED, false + ) + , sends_per_second( + "Rate Limit:
Maximum number of sends per second.", + LockMode::LOCK_WHILE_RUNNING, 2, 1 + ) +{ + PA_ADD_OPTION(urls); + PA_ADD_OPTION(sends_per_second); +} + + + +} +} diff --git a/SerialPrograms/Source/Integrations/DiscordWebhookSettings.h b/SerialPrograms/Source/Integrations/DiscordWebhookSettings.h index 466f61db65..41cf838554 100644 --- a/SerialPrograms/Source/Integrations/DiscordWebhookSettings.h +++ b/SerialPrograms/Source/Integrations/DiscordWebhookSettings.h @@ -1,57 +1,57 @@ -/* Discord Webhook Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DiscordWebhookSettings_H -#define PokemonAutomation_DiscordWebhookSettings_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/GroupOption.h" - -namespace PokemonAutomation{ -namespace Integration{ - - -class DiscordWebhookUrl : public EditableTableRow{ -public: - DiscordWebhookUrl(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - virtual void load_json(const JsonValue& json) override; - -public: - BooleanCheckBoxCell enabled; - StringCell label; - BooleanCheckBoxCell ping; - StringCell tags_text; - SimpleIntegerCell delay; - StringCell url; -}; - -class DiscordWebhookSettingsTable : public EditableTableOption_t{ -public: - DiscordWebhookSettingsTable(); - virtual std::vector make_header() const override; -}; - - - - - -class DiscordWebhookSettingsOption : public GroupOption{ -public: - DiscordWebhookSettingsOption(); - - DiscordWebhookSettingsTable urls; - SimpleIntegerOption sends_per_second; -}; - - - -} -} -#endif +/* Discord Webhook Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DiscordWebhookSettings_H +#define PokemonAutomation_DiscordWebhookSettings_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/GroupOption.h" + +namespace PokemonAutomation{ +namespace Integration{ + + +class DiscordWebhookUrl : public EditableTableRow{ +public: + DiscordWebhookUrl(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + virtual void load_json(const JsonValue& json) override; + +public: + BooleanCheckBoxCell enabled; + StringCell label; + BooleanCheckBoxCell ping; + StringCell tags_text; + SimpleIntegerCell delay; + StringCell url; +}; + +class DiscordWebhookSettingsTable : public EditableTableOption_t{ +public: + DiscordWebhookSettingsTable(); + virtual std::vector make_header() const override; +}; + + + + + +class DiscordWebhookSettingsOption : public GroupOption{ +public: + DiscordWebhookSettingsOption(); + + DiscordWebhookSettingsTable urls; + SimpleIntegerOption sends_per_second; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DppIntegration/DppClient.cpp b/SerialPrograms/Source/Integrations/DppIntegration/DppClient.cpp index 8b3e0329c0..95006a994d 100644 --- a/SerialPrograms/Source/Integrations/DppIntegration/DppClient.cpp +++ b/SerialPrograms/Source/Integrations/DppIntegration/DppClient.cpp @@ -1,159 +1,159 @@ -#ifdef PA_DPP - -#include -#include -#include -#include -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" - -using namespace dpp; -namespace PokemonAutomation{ -namespace Integration{ -namespace DppClient{ - - -Client& Client::instance(){ - static Client client; - return client; -} - -bool Client::is_initialized(){ - std::lock_guard lg(m_client_lock); - return m_bot != nullptr; -} -bool Client::is_running(){ - return m_is_connected.load(std::memory_order_acquire); -} - -void Client::connect(){ - std::lock_guard lg(m_client_lock); - if (m_bot == nullptr && !m_is_connected.load(std::memory_order_relaxed)){ - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!Handler::check_if_empty(settings)) - return; - - std::string token = settings.integration.token; - uint32_t intents = intents::i_default_intents | intents::i_guild_members | intents::i_message_content; - try{ - m_bot = std::make_unique(token, intents); - m_handler = std::make_unique(m_bot.get(), false); - m_bot->cache_policy = { cache_policy_setting_t::cp_lazy, cache_policy_setting_t::cp_lazy, cache_policy_setting_t::cp_aggressive }; - std::thread(&Client::run, this, token).detach(); - }catch (std::exception& e){ - Handler::log_dpp("DPP thew an exception: " + (std::string)e.what(), "connect()", ll_critical); - } - } -} - -void Client::disconnect(){ - std::lock_guard lg(m_client_lock); - if (m_bot != nullptr && m_is_connected.load(std::memory_order_relaxed)){ - try{ - m_bot->shutdown(); - m_handler.reset(); - m_bot.reset(); - m_is_connected.store(false, std::memory_order_release); - }catch (std::exception& e){ - Handler::log_dpp("DPP thew an exception: " + (std::string)e.what(), "disconnect()", ll_critical); - } - } -} - -void Client::send_embed_dpp( - bool should_ping, - const Color& color, - const std::vector& tags, - const JsonObject& json_obj, - std::shared_ptr file -){ - std::lock_guard lg(m_client_lock); - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!settings.integration.enabled()){ - return; - } - if (!m_is_connected.load(std::memory_order_relaxed)){ - return; - } - - - embed embed; - { - embed.set_title(*json_obj.get_string("title")); - embed.set_color((int)((uint32_t)color & 0xffffff)); - - auto fields = json_obj.get_array("fields"); - for (auto& field : *fields){ - auto obj = field.to_object(); - embed.add_field(*obj->get_string("name"), *obj->get_string("value")); - } - } - - std::set tag_set; - for (const std::string& tag : tags){ - tag_set.insert(to_lower(tag)); - } - - MessageBuilder builder(tags); - const DiscordIntegrationTable& channels = settings.integration.channels; - - auto table = channels.copy_snapshot(); - for (auto& ch : table){ - const Integration::DiscordIntegrationChannel& channel = *ch; - if (((std::string)channel.tags_text).empty() || !channel.enabled){ - continue; - } - if (!builder.should_send(EventNotificationOption::parse_tags(channel.tags_text))){ - continue; - } - - std::chrono::seconds delay(channel.delay); - Handler::send_message( - *m_bot.get(), embed, - channel.channel_id, - delay, - builder.build_message( - delay, - should_ping && channel.ping, - settings.message.user_id, - settings.message.message - ), - file - ); - } -} - -void Client::run(const std::string& token){ - std::lock_guard lg(m_client_lock); - if (!m_bot){ - Handler::log_dpp("DPP has been disconnected.", "run()", ll_warning); - return; - } - try{ - Handler::initialize(*m_bot.get(), *m_handler.get()); - m_bot->set_websocket_protocol(websocket_protocol_t::ws_etf); - m_bot->start(st_return); - m_bot->set_presence( - presence( - presence_status::ps_online, - activity_type::at_game, - (std::string)GlobalSettings::instance().DISCORD->integration.game_status - ) - ); - m_is_connected.store(true, std::memory_order_release); - }catch (std::exception& e){ - Handler::log_dpp("DPP thew an exception: " + (std::string)e.what(), "run()", ll_critical); - m_handler.reset(); - m_bot.reset(); - m_is_connected.store(false, std::memory_order_release); - } -} - - -} -} -} -#endif +#ifdef PA_DPP + +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" + +using namespace dpp; +namespace PokemonAutomation{ +namespace Integration{ +namespace DppClient{ + + +Client& Client::instance(){ + static Client client; + return client; +} + +bool Client::is_initialized(){ + std::lock_guard lg(m_client_lock); + return m_bot != nullptr; +} +bool Client::is_running(){ + return m_is_connected.load(std::memory_order_acquire); +} + +void Client::connect(){ + std::lock_guard lg(m_client_lock); + if (m_bot == nullptr && !m_is_connected.load(std::memory_order_relaxed)){ + DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; + if (!Handler::check_if_empty(settings)) + return; + + std::string token = settings.integration.token; + uint32_t intents = intents::i_default_intents | intents::i_guild_members | intents::i_message_content; + try{ + m_bot = std::make_unique(token, intents); + m_handler = std::make_unique(m_bot.get(), false); + m_bot->cache_policy = { cache_policy_setting_t::cp_lazy, cache_policy_setting_t::cp_lazy, cache_policy_setting_t::cp_aggressive }; + std::thread(&Client::run, this, token).detach(); + }catch (std::exception& e){ + Handler::log_dpp("DPP thew an exception: " + (std::string)e.what(), "connect()", ll_critical); + } + } +} + +void Client::disconnect(){ + std::lock_guard lg(m_client_lock); + if (m_bot != nullptr && m_is_connected.load(std::memory_order_relaxed)){ + try{ + m_bot->shutdown(); + m_handler.reset(); + m_bot.reset(); + m_is_connected.store(false, std::memory_order_release); + }catch (std::exception& e){ + Handler::log_dpp("DPP thew an exception: " + (std::string)e.what(), "disconnect()", ll_critical); + } + } +} + +void Client::send_embed_dpp( + bool should_ping, + const Color& color, + const std::vector& tags, + const JsonObject& json_obj, + std::shared_ptr file +){ + std::lock_guard lg(m_client_lock); + DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; + if (!settings.integration.enabled()){ + return; + } + if (!m_is_connected.load(std::memory_order_relaxed)){ + return; + } + + + embed embed; + { + embed.set_title(*json_obj.get_string("title")); + embed.set_color((int)((uint32_t)color & 0xffffff)); + + auto fields = json_obj.get_array("fields"); + for (auto& field : *fields){ + auto obj = field.to_object(); + embed.add_field(*obj->get_string("name"), *obj->get_string("value")); + } + } + + std::set tag_set; + for (const std::string& tag : tags){ + tag_set.insert(to_lower(tag)); + } + + MessageBuilder builder(tags); + const DiscordIntegrationTable& channels = settings.integration.channels; + + auto table = channels.copy_snapshot(); + for (auto& ch : table){ + const Integration::DiscordIntegrationChannel& channel = *ch; + if (((std::string)channel.tags_text).empty() || !channel.enabled){ + continue; + } + if (!builder.should_send(EventNotificationOption::parse_tags(channel.tags_text))){ + continue; + } + + std::chrono::seconds delay(channel.delay); + Handler::send_message( + *m_bot.get(), embed, + channel.channel_id, + delay, + builder.build_message( + delay, + should_ping && channel.ping, + settings.message.user_id, + settings.message.message + ), + file + ); + } +} + +void Client::run(const std::string& token){ + std::lock_guard lg(m_client_lock); + if (!m_bot){ + Handler::log_dpp("DPP has been disconnected.", "run()", ll_warning); + return; + } + try{ + Handler::initialize(*m_bot.get(), *m_handler.get()); + m_bot->set_websocket_protocol(websocket_protocol_t::ws_etf); + m_bot->start(st_return); + m_bot->set_presence( + presence( + presence_status::ps_online, + activity_type::at_game, + (std::string)GlobalSettings::instance().DISCORD->integration.game_status + ) + ); + m_is_connected.store(true, std::memory_order_release); + }catch (std::exception& e){ + Handler::log_dpp("DPP thew an exception: " + (std::string)e.what(), "run()", ll_critical); + m_handler.reset(); + m_bot.reset(); + m_is_connected.store(false, std::memory_order_release); + } +} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DppIntegration/DppClient.h b/SerialPrograms/Source/Integrations/DppIntegration/DppClient.h index f0b830f923..6aa01de36b 100644 --- a/SerialPrograms/Source/Integrations/DppIntegration/DppClient.h +++ b/SerialPrograms/Source/Integrations/DppIntegration/DppClient.h @@ -1,51 +1,51 @@ -#pragma once -#ifndef DPP_CLIENT_H -#define DPP_CLIENT_H - -#include -#include -#include -#include "CommonFramework/Notifications/MessageAttachment.h" - -namespace PokemonAutomation{ - class JsonObject; -namespace Integration{ -namespace DppClient{ - - - -class Client : protected DppCommandHandler::Handler{ -public: - Client() : m_is_connected(false) {} - static Client& instance(); - -public: - bool is_initialized(); - bool is_running(); - - void connect(); - void disconnect(); - void send_embed_dpp( - bool should_ping, - const Color& color, - const std::vector& tags, - const JsonObject& json_obj, - std::shared_ptr file - ); - -private: - void run(const std::string& token); - -private: - std::unique_ptr m_bot = nullptr; - std::unique_ptr m_handler = nullptr; - std::atomic m_is_connected; - std::mutex m_client_lock; -}; - - - -} -} -} -#endif +#pragma once +#ifndef DPP_CLIENT_H +#define DPP_CLIENT_H + +#include +#include +#include +#include "CommonFramework/Notifications/MessageAttachment.h" + +namespace PokemonAutomation{ + class JsonObject; +namespace Integration{ +namespace DppClient{ + + + +class Client : protected DppCommandHandler::Handler{ +public: + Client() : m_is_connected(false) {} + static Client& instance(); + +public: + bool is_initialized(); + bool is_running(); + + void connect(); + void disconnect(); + void send_embed_dpp( + bool should_ping, + const Color& color, + const std::vector& tags, + const JsonObject& json_obj, + std::shared_ptr file + ); + +private: + void run(const std::string& token); + +private: + std::unique_ptr m_bot = nullptr; + std::unique_ptr m_handler = nullptr; + std::atomic m_is_connected; + std::mutex m_client_lock; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.cpp b/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.cpp index 5169e477a8..fd3276b9d0 100644 --- a/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.cpp +++ b/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.cpp @@ -1,629 +1,629 @@ -#ifdef PA_DPP - -#include -#include -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Notifications/MessageAttachment.h" -#include "Integrations/IntegrationsAPI.h" -#include "Integrations/DiscordSettingsOption.h" -#include "DppUtility.h" -#include "DppCommandHandler.h" - -using namespace dpp; -namespace PokemonAutomation{ -namespace Integration{ -namespace DppCommandHandler{ - -user Handler::owner; -Color Handler::color = COLOR_WHITE; - -void Handler::initialize(cluster& bot, commandhandler& handler){ - global_logger_tagged().log("Initializing DPP..."); - - bot.on_log([this](const log_t& log){ - log_dpp(log.message, "Internal Log", log.severity); - }); - - owner = bot.current_application_get_sync().owner; - auto cmd_type = GlobalSettings::instance().DISCORD->integration.command_type.get(); - std::string prefix = GlobalSettings::instance().DISCORD->integration.command_prefix; - - if (cmd_type == DiscordIntegrationSettingsOption::CommandType::MessageCommands && !prefix.empty()){ - handler.add_prefix(prefix); - }else{ - handler.add_prefix("/").add_prefix("_cmd "); - } - - bot.on_ready([&bot, &handler, this](const ready_t&){ - log_dpp("Logged in as: " + bot.current_user_get_sync().format_username() + ".", "Ready", ll_info); - Handler::create_unified_commands(handler); - }); - - bot.on_guild_create([&bot, this](const guild_create_t& event){ - try{ - std::string id = std::to_string(event.created->id); - log_dpp("Loaded guild: " + event.created->name + " (" + id + ").", "Guild Create", ll_info); - std::lock_guard lg(m_count_lock); - Utility::get_user_counts(bot, event); - }catch (std::exception& e){ - log_dpp("Failed to get user counts: " + (std::string)e.what(), "Guild Create", ll_error); - } - }); - - bot.on_guild_member_add([this](const guild_member_add_t& event){ - std::string id = std::to_string(event.adding_guild->id); - if (!user_counts.empty() && user_counts.count(id)){ - log_dpp("New member joined " + event.adding_guild->name + ". Incrementing member count.", "Guild Member Add", ll_info); - user_counts.at(id)++; - } - }); - - bot.on_guild_member_remove([this](const guild_member_remove_t& event){ - std::string id = std::to_string(event.removing_guild->id); - if (!user_counts.empty() && user_counts.count(id)){ - log_dpp("Member left " + event.removing_guild->name + ". Decrementing member count.", "Guild Member Remove", ll_info); - user_counts.at(id)--; - } - }); - - bot.on_message_create([&handler](const message_create_t& event){ - std::string content = event.msg.content; - if (!event.msg.author.is_bot() && handler.string_has_prefix(content)){ - auto channels = GlobalSettings::instance().DISCORD->integration.channels.command_channels(); - auto channel = std::find(channels.begin(), channels.end(), std::to_string(event.msg.channel_id)); - if (channel != channels.end()){ - handler.route(event); - } - } - }); - - bot.on_slashcommand([&handler](const slashcommand_t& event){ - if (!event.command.usr.is_bot() && handler.slash_commands_enabled){ - auto channels = GlobalSettings::instance().DISCORD->integration.channels.command_channels(); - auto channel = std::find(channels.begin(), channels.end(), std::to_string(event.command.channel_id)); - if (channel != channels.end()){ - handler.route(event); - } - } - }); -} - -void Handler::send_message(cluster& bot, embed& embed, const std::string& channel, std::chrono::milliseconds delay, const std::string& msg, std::shared_ptr file){ - Handler::m_queue.add_event(delay > std::chrono::milliseconds(10000) ? std::chrono::milliseconds(0) : delay, - [&bot, this, embed = std::move(embed), channel = channel, msg = msg, file = std::move(file)]() mutable { - message m; - if (file != nullptr && !file->filepath().empty() && !file->filename().empty()){ - std::string data; - std::string path = file->filepath(); - try{ - data = utility::read_file(path); - m.add_file(file->filename(), data); - if (path.find(".txt") == std::string::npos){ - embed.set_image("attachment://" + file->filename()); - } - }catch (dpp::exception e){ - log_dpp("Exception thrown while reading screenshot data: " + (std::string)e.what(), "send_message()", ll_error); - } - } - - if (!msg.empty() && msg != ""){ - m.content = msg; - } - - m.allowed_mentions.parse_users = true; - m.channel_id = channel; - m.add_embed(embed); - bot.message_create(m); - }); - log_dpp("Sending message...", "send_message()", ll_info); -} - -void Handler::update_response(const dpp::command_source& src, dpp::embed& embed, const std::string& msg, std::shared_ptr file){ - message m; - if (file != nullptr && !file->filepath().empty() && !file->filename().empty()){ - std::string data; - try{ - data = utility::read_file(file->filepath()); - m.add_file(file->filename(), data); - embed.set_image("attachment://" + file->filename()); - }catch (dpp::exception e){ - log_dpp("Exception thrown while reading screenshot data: " + (std::string)e.what(), "send_message()", ll_error); - } - } - - if (!msg.empty() && msg != ""){ - m.content = msg; - } - - m.add_embed(embed); - if (src.interaction_event.has_value()){ - src.interaction_event.value().edit_response(m); - }else{ - src.message_event.value().reply(m); - } -} - -void Handler::log_dpp(const std::string& message, const std::string& identity, const dpp::loglevel& ll){ - Utility::log(message, identity, ll); -} - -bool Handler::check_if_empty(const DiscordSettingsOption& settings){ - if (!settings.integration.enabled()){ - return false; - } - if (((std::string)settings.integration.token).empty()){ - log_dpp("\"Token\" must not be empty. Stopping...", "check_if_empty()", loglevel::ll_error); - return false; - }else if (((std::string)settings.integration.token).find(",") != std::string::npos){ - log_dpp("\"Token\" must only contain one token. Stopping...", "check_if_empty()", loglevel::ll_error); - return false; - } - return true; -} - -void Handler::create_unified_commands(commandhandler& handler){ - handler - .add_command( - "ping", - {}, - [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - handler.reply(message("Pong! :ping_pong:"), src); - }, - "Ping pong!") - - .add_command( - "about", - {}, - [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - embed embed; - embed.set_color((uint32_t)color).set_title("Here's a little bit about me!"); - - int counts = 0; - if (!Utility::user_counts.empty()){ - for (auto& count : Utility::user_counts){ - counts += count.second; - } - } - - embed.add_field("Owner", owner.format_username() + "(" + std::to_string(owner.id) + ")"); - embed.add_field("Guilds", std::to_string(Utility::user_counts.size())); - embed.add_field("Users", std::to_string(counts)); - embed.add_field("Uptime", handler.owner->uptime().to_string()); - embed.add_field( - "Powered By", - PROGRAM_NAME + " " + PROGRAM_VERSION + " ([GitHub](" + GITHUB_LINK_URL + ")/[Discord](" + DISCORD_LINK_URL_EMBED + "))" - ); - - message message; - message.add_embed(embed); - handler.reply(message, src); - }, - "Some info about me!") - - .add_command( - "hi", - {}, - [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - message message; - message.set_content((std::string)GlobalSettings::instance().DISCORD->integration.hello_message); - if (src.message_event.has_value()){ - message.set_reference(src.message_event.value().msg.id); - } - handler.reply(message, src); - }, - "Hi!") - - .add_command( - "resetserial", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command Response"); - - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string response = Integration::reset_serial(id); - if (!response.empty()){ - embed.set_description(response); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - embed.set_description("Reset the serial connection for console ID " + std::to_string(id) + "."); - message.add_embed(embed); - handler.reply(message, src); - }, - "Reset the serial connection.") - - .add_command( - "resetcamera", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command Response"); - - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string response = Integration::reset_camera(id); - if (!response.empty()){ - embed.set_description(response); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - embed.set_description("Reset the camera for console ID " + std::to_string(id) + "."); - message.add_embed(embed); - handler.reply(message, src); - }, - "Reset the camera.") - - .add_command( - "start", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command Response"); - - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string response = Integration::start_program(id); - if (!response.empty()){ - embed.set_description(response); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - embed.set_description("Started the program for console ID " + std::to_string(id) + "."); - message.add_embed(embed); - handler.reply(message, src); - }, - "Start the currently selected program.") - - .add_command( - "stop", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command Response"); - - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string response = Integration::stop_program(id); - if (!response.empty()){ - embed.set_description(response); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - embed.set_description("Stopped the program for console ID " + std::to_string(id) + "."); - message.add_embed(embed); - handler.reply(message, src); - }, - "Stop the currently running program.") - - .add_command( - "status", - {}, - [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - message message; - embed embed; - embed.set_color((uint32_t)color).set_description(Integration::status()).set_title("Program Status"); - message.add_embed(embed); - handler.reply(message, src); - }, - "View program status.") - - .add_command( - "click", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")}, - {"button", param_info(pt_string, false, "Switch console button.", - {{"0", "Y"}, - {"1", "B"}, - {"2", "A"}, - {"3", "X"}, - {"4", "L"}, - {"5", "R"}, - {"6", "ZL"}, - {"7", "ZR"}, - {"8", "Minus"}, - {"9", "Plus"}, - {"10", "LStick"}, - {"11", "RStick"}, - {"12", "Home"}, - {"13", "Capture"}, - {"14", "DUP"}, - {"15", "DDOWN"}, - {"16", "DLEFT"}, - {"17", "DRIGHT"},} - )}, - {"ticks", param_info(pt_integer, false, "How long to hold the button for, in ticks.")}, - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command Response"); - - if (params.size() < 3){ - embed.set_description("Missing command arguments."); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string button_input = std::get(params[1].second); - - std::string name = "None"; - int64_t button = Utility::get_value_from_input(handler, command, button_input, name); - int64_t ticks = Utility::sanitize_integer_input(params, 2); - - if (button < 0){ - embed.set_description("No such button found: " + button_input); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - std::string response; - if (button > 13){ - response = Integration::press_dpad(id, Utility::get_button(button), ticks); - }else{ - response = Integration::press_button(id, Utility::get_button(button), ticks); - } - - if (!response.empty()){ - embed.set_description(response); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - embed.set_description("Console ID " + std::to_string(id) + " pressed button " + name + "."); - message.add_embed(embed); - handler.reply(message, src); - }, - "Click a button for the specified console.") - - .add_command( - "joystick", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")}, - {"stick", param_info(pt_string, false, "Switch console joystick.", - {{"0", "LStick"}, - {"1", "RStick"},} - )}, - {"magnitude_x", param_info(pt_integer, false, "Movement amount in the horizontal direction. \"Left\" is 0, \"right\" is 255, \"neutral\" is 127.")}, - {"magnitude_y", param_info(pt_integer, false, "Movement amount in the vertical direction. \"Down\" is 0, \"up\" is 255, \"neutral\" is 127.")}, - {"ticks", param_info(pt_integer, false, "How long to hold the stick for, in ticks.")}, - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command Response"); - - if (params.size() < 5){ - embed.set_description("Missing command arguments."); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - std::string name = "None"; - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string stick_input = std::get(params[1].second); - int64_t stick = Utility::get_value_from_input(handler, command, stick_input, name); - - if (stick < 0){ - embed.set_description("No such joystick found: " + stick_input); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - int64_t x = Utility::sanitize_integer_input(params, 2); - int64_t y = Utility::sanitize_integer_input(params, 3); - int64_t ticks = Utility::sanitize_integer_input(params, 4); - - std::string response; - if (stick == 0){ - response = Integration::press_left_joystick(id, x, y, ticks); - }else{ - response = Integration::press_right_joystick(id, x, y, ticks); - } - - if (!response.empty()){ - embed.set_description(response); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - embed.set_description("Console ID " + std::to_string(id) + " moved " + name + " (X: " + std::to_string(x) + ", Y: " + std::to_string(y) + ") for " + std::to_string(ticks) + " ticks."); - message.add_embed(embed); - handler.reply(message, src); - }, - "Click a button for the specified console.") - - .add_command( - "screenshot", - { - {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")}, - {"format", param_info(pt_string, false, "Image format.", - {{"0", "png"}, - {"1", "jpg"},} - )}, - }, - [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Program Screenshot"); - - if (params.size() < 2){ - embed.set_description("Missing command arguments."); - message.add_embed(embed); - handler.reply(message, src); - return; - } - - handler.thinking(src); - std::string name = "None"; - int64_t id = Utility::sanitize_integer_input(params, 0); - std::string button_input = std::get(params[1].second); - int64_t format = Utility::get_value_from_input(handler, command, button_input, name); - - std::string path; - if (format == 0){ - path = "screenshot_slash.png"; - }else{ - path = "screenshot_slash.jpg"; - } - - std::string response = Integration::screenshot(id, path.c_str()); - if (!response.empty()){ - embed.set_description(response); - Handler::update_response(src, embed, "", nullptr); - return; - } - - std::shared_ptr file(new PendingFileSend(path, true)); - embed_footer footer; - footer.set_text("Console ID: " + std::to_string(id) + " (" + name + ")"); - - embed.set_footer(footer); - Handler::update_response(src, embed, "", std::move(file)); - }, - "Take and upload a screenshot from the specified console.") - - .add_command( - "help", - {}, - [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - message message; - embed embed; - embed.set_color((uint32_t)color).set_title("Command List"); - - auto& commands = handler.commands; - for (auto& cmd : commands){ - std::string name = cmd.first; - log_dpp(name, "help command", ll_info); - if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && - src.issuer.id != owner.id && name != "hi" && name != "ping" && name != "about" && name != "status" && name != "help" - ){ - continue; - } - - std::string param_info; - for (auto& param : cmd.second.parameters){ - param_info += ("\n**- " + param.first + "** - " + param.second.description); - if (!param.second.choices.empty()){ - param_info += " ("; - for (auto& choice : param.second.choices){ - param_info += (choice.second + ", "); - } - param_info = param_info.substr(0, param_info.size() - 2); - param_info += ")"; - } - } - embed.add_field(name, param_info); - } - embed_footer footer; - footer.set_text("Commands are case-sensitive!"); - embed.set_footer(footer); - message.add_embed(embed); - handler.reply(message, src); - }, - "View the command list.") - - .add_command( - "register", - {}, - [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ - log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); - if (src.issuer.id != owner.id){ - handler.reply(message("You do not have permission to use this command."), src); - return; - } - - if (handler.slash_commands_enabled){ - handler.thinking(src); - log_dpp("Registering commands.", "Command Registration", ll_info); - handler.register_commands(); - - embed embed; - std::string desc = "Slash commands registered! Restart your Discord client or wait a few minutes for them to show up!"; - embed.set_color((uint32_t)color).set_description(desc).set_title("Slash Command Registration"); - Handler::update_response(src, embed, "", nullptr); - }else{ - handler.reply(message("Enable slash commands before registering them."), src); - } - }, - "Register global slash commands. For first-time slash command use and for updating commands."); -} - - -} -} -} -#endif +#ifdef PA_DPP + +#include +#include +#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Notifications/MessageAttachment.h" +#include "Integrations/IntegrationsAPI.h" +#include "Integrations/DiscordSettingsOption.h" +#include "DppUtility.h" +#include "DppCommandHandler.h" + +using namespace dpp; +namespace PokemonAutomation{ +namespace Integration{ +namespace DppCommandHandler{ + +user Handler::owner; +Color Handler::color = COLOR_WHITE; + +void Handler::initialize(cluster& bot, commandhandler& handler){ + global_logger_tagged().log("Initializing DPP..."); + + bot.on_log([this](const log_t& log){ + log_dpp(log.message, "Internal Log", log.severity); + }); + + owner = bot.current_application_get_sync().owner; + auto cmd_type = GlobalSettings::instance().DISCORD->integration.command_type.get(); + std::string prefix = GlobalSettings::instance().DISCORD->integration.command_prefix; + + if (cmd_type == DiscordIntegrationSettingsOption::CommandType::MessageCommands && !prefix.empty()){ + handler.add_prefix(prefix); + }else{ + handler.add_prefix("/").add_prefix("_cmd "); + } + + bot.on_ready([&bot, &handler, this](const ready_t&){ + log_dpp("Logged in as: " + bot.current_user_get_sync().format_username() + ".", "Ready", ll_info); + Handler::create_unified_commands(handler); + }); + + bot.on_guild_create([&bot, this](const guild_create_t& event){ + try{ + std::string id = std::to_string(event.created->id); + log_dpp("Loaded guild: " + event.created->name + " (" + id + ").", "Guild Create", ll_info); + std::lock_guard lg(m_count_lock); + Utility::get_user_counts(bot, event); + }catch (std::exception& e){ + log_dpp("Failed to get user counts: " + (std::string)e.what(), "Guild Create", ll_error); + } + }); + + bot.on_guild_member_add([this](const guild_member_add_t& event){ + std::string id = std::to_string(event.adding_guild->id); + if (!user_counts.empty() && user_counts.count(id)){ + log_dpp("New member joined " + event.adding_guild->name + ". Incrementing member count.", "Guild Member Add", ll_info); + user_counts.at(id)++; + } + }); + + bot.on_guild_member_remove([this](const guild_member_remove_t& event){ + std::string id = std::to_string(event.removing_guild->id); + if (!user_counts.empty() && user_counts.count(id)){ + log_dpp("Member left " + event.removing_guild->name + ". Decrementing member count.", "Guild Member Remove", ll_info); + user_counts.at(id)--; + } + }); + + bot.on_message_create([&handler](const message_create_t& event){ + std::string content = event.msg.content; + if (!event.msg.author.is_bot() && handler.string_has_prefix(content)){ + auto channels = GlobalSettings::instance().DISCORD->integration.channels.command_channels(); + auto channel = std::find(channels.begin(), channels.end(), std::to_string(event.msg.channel_id)); + if (channel != channels.end()){ + handler.route(event); + } + } + }); + + bot.on_slashcommand([&handler](const slashcommand_t& event){ + if (!event.command.usr.is_bot() && handler.slash_commands_enabled){ + auto channels = GlobalSettings::instance().DISCORD->integration.channels.command_channels(); + auto channel = std::find(channels.begin(), channels.end(), std::to_string(event.command.channel_id)); + if (channel != channels.end()){ + handler.route(event); + } + } + }); +} + +void Handler::send_message(cluster& bot, embed& embed, const std::string& channel, std::chrono::milliseconds delay, const std::string& msg, std::shared_ptr file){ + Handler::m_queue.add_event(delay > std::chrono::milliseconds(10000) ? std::chrono::milliseconds(0) : delay, + [&bot, this, embed = std::move(embed), channel = channel, msg = msg, file = std::move(file)]() mutable { + message m; + if (file != nullptr && !file->filepath().empty() && !file->filename().empty()){ + std::string data; + std::string path = file->filepath(); + try{ + data = utility::read_file(path); + m.add_file(file->filename(), data); + if (path.find(".txt") == std::string::npos){ + embed.set_image("attachment://" + file->filename()); + } + }catch (dpp::exception e){ + log_dpp("Exception thrown while reading screenshot data: " + (std::string)e.what(), "send_message()", ll_error); + } + } + + if (!msg.empty() && msg != ""){ + m.content = msg; + } + + m.allowed_mentions.parse_users = true; + m.channel_id = channel; + m.add_embed(embed); + bot.message_create(m); + }); + log_dpp("Sending message...", "send_message()", ll_info); +} + +void Handler::update_response(const dpp::command_source& src, dpp::embed& embed, const std::string& msg, std::shared_ptr file){ + message m; + if (file != nullptr && !file->filepath().empty() && !file->filename().empty()){ + std::string data; + try{ + data = utility::read_file(file->filepath()); + m.add_file(file->filename(), data); + embed.set_image("attachment://" + file->filename()); + }catch (dpp::exception e){ + log_dpp("Exception thrown while reading screenshot data: " + (std::string)e.what(), "send_message()", ll_error); + } + } + + if (!msg.empty() && msg != ""){ + m.content = msg; + } + + m.add_embed(embed); + if (src.interaction_event.has_value()){ + src.interaction_event.value().edit_response(m); + }else{ + src.message_event.value().reply(m); + } +} + +void Handler::log_dpp(const std::string& message, const std::string& identity, const dpp::loglevel& ll){ + Utility::log(message, identity, ll); +} + +bool Handler::check_if_empty(const DiscordSettingsOption& settings){ + if (!settings.integration.enabled()){ + return false; + } + if (((std::string)settings.integration.token).empty()){ + log_dpp("\"Token\" must not be empty. Stopping...", "check_if_empty()", loglevel::ll_error); + return false; + }else if (((std::string)settings.integration.token).find(",") != std::string::npos){ + log_dpp("\"Token\" must only contain one token. Stopping...", "check_if_empty()", loglevel::ll_error); + return false; + } + return true; +} + +void Handler::create_unified_commands(commandhandler& handler){ + handler + .add_command( + "ping", + {}, + [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + handler.reply(message("Pong! :ping_pong:"), src); + }, + "Ping pong!") + + .add_command( + "about", + {}, + [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + embed embed; + embed.set_color((uint32_t)color).set_title("Here's a little bit about me!"); + + int counts = 0; + if (!Utility::user_counts.empty()){ + for (auto& count : Utility::user_counts){ + counts += count.second; + } + } + + embed.add_field("Owner", owner.format_username() + "(" + std::to_string(owner.id) + ")"); + embed.add_field("Guilds", std::to_string(Utility::user_counts.size())); + embed.add_field("Users", std::to_string(counts)); + embed.add_field("Uptime", handler.owner->uptime().to_string()); + embed.add_field( + "Powered By", + PROGRAM_NAME + " " + PROGRAM_VERSION + " ([GitHub](" + GITHUB_LINK_URL + ")/[Discord](" + DISCORD_LINK_URL_EMBED + "))" + ); + + message message; + message.add_embed(embed); + handler.reply(message, src); + }, + "Some info about me!") + + .add_command( + "hi", + {}, + [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + message message; + message.set_content((std::string)GlobalSettings::instance().DISCORD->integration.hello_message); + if (src.message_event.has_value()){ + message.set_reference(src.message_event.value().msg.id); + } + handler.reply(message, src); + }, + "Hi!") + + .add_command( + "resetserial", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command Response"); + + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string response = Integration::reset_serial(id); + if (!response.empty()){ + embed.set_description(response); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + embed.set_description("Reset the serial connection for console ID " + std::to_string(id) + "."); + message.add_embed(embed); + handler.reply(message, src); + }, + "Reset the serial connection.") + + .add_command( + "resetcamera", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command Response"); + + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string response = Integration::reset_camera(id); + if (!response.empty()){ + embed.set_description(response); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + embed.set_description("Reset the camera for console ID " + std::to_string(id) + "."); + message.add_embed(embed); + handler.reply(message, src); + }, + "Reset the camera.") + + .add_command( + "start", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command Response"); + + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string response = Integration::start_program(id); + if (!response.empty()){ + embed.set_description(response); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + embed.set_description("Started the program for console ID " + std::to_string(id) + "."); + message.add_embed(embed); + handler.reply(message, src); + }, + "Start the currently selected program.") + + .add_command( + "stop", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")} + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command Response"); + + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string response = Integration::stop_program(id); + if (!response.empty()){ + embed.set_description(response); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + embed.set_description("Stopped the program for console ID " + std::to_string(id) + "."); + message.add_embed(embed); + handler.reply(message, src); + }, + "Stop the currently running program.") + + .add_command( + "status", + {}, + [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + message message; + embed embed; + embed.set_color((uint32_t)color).set_description(Integration::status()).set_title("Program Status"); + message.add_embed(embed); + handler.reply(message, src); + }, + "View program status.") + + .add_command( + "click", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")}, + {"button", param_info(pt_string, false, "Switch console button.", + {{"0", "Y"}, + {"1", "B"}, + {"2", "A"}, + {"3", "X"}, + {"4", "L"}, + {"5", "R"}, + {"6", "ZL"}, + {"7", "ZR"}, + {"8", "Minus"}, + {"9", "Plus"}, + {"10", "LStick"}, + {"11", "RStick"}, + {"12", "Home"}, + {"13", "Capture"}, + {"14", "DUP"}, + {"15", "DDOWN"}, + {"16", "DLEFT"}, + {"17", "DRIGHT"},} + )}, + {"ticks", param_info(pt_integer, false, "How long to hold the button for, in ticks.")}, + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command Response"); + + if (params.size() < 3){ + embed.set_description("Missing command arguments."); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string button_input = std::get(params[1].second); + + std::string name = "None"; + int64_t button = Utility::get_value_from_input(handler, command, button_input, name); + int64_t ticks = Utility::sanitize_integer_input(params, 2); + + if (button < 0){ + embed.set_description("No such button found: " + button_input); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + std::string response; + if (button > 13){ + response = Integration::press_dpad(id, Utility::get_button(button), ticks); + }else{ + response = Integration::press_button(id, Utility::get_button(button), ticks); + } + + if (!response.empty()){ + embed.set_description(response); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + embed.set_description("Console ID " + std::to_string(id) + " pressed button " + name + "."); + message.add_embed(embed); + handler.reply(message, src); + }, + "Click a button for the specified console.") + + .add_command( + "joystick", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")}, + {"stick", param_info(pt_string, false, "Switch console joystick.", + {{"0", "LStick"}, + {"1", "RStick"},} + )}, + {"magnitude_x", param_info(pt_integer, false, "Movement amount in the horizontal direction. \"Left\" is 0, \"right\" is 255, \"neutral\" is 127.")}, + {"magnitude_y", param_info(pt_integer, false, "Movement amount in the vertical direction. \"Down\" is 0, \"up\" is 255, \"neutral\" is 127.")}, + {"ticks", param_info(pt_integer, false, "How long to hold the stick for, in ticks.")}, + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command Response"); + + if (params.size() < 5){ + embed.set_description("Missing command arguments."); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + std::string name = "None"; + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string stick_input = std::get(params[1].second); + int64_t stick = Utility::get_value_from_input(handler, command, stick_input, name); + + if (stick < 0){ + embed.set_description("No such joystick found: " + stick_input); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + int64_t x = Utility::sanitize_integer_input(params, 2); + int64_t y = Utility::sanitize_integer_input(params, 3); + int64_t ticks = Utility::sanitize_integer_input(params, 4); + + std::string response; + if (stick == 0){ + response = Integration::press_left_joystick(id, x, y, ticks); + }else{ + response = Integration::press_right_joystick(id, x, y, ticks); + } + + if (!response.empty()){ + embed.set_description(response); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + embed.set_description("Console ID " + std::to_string(id) + " moved " + name + " (X: " + std::to_string(x) + ", Y: " + std::to_string(y) + ") for " + std::to_string(ticks) + " ticks."); + message.add_embed(embed); + handler.reply(message, src); + }, + "Click a button for the specified console.") + + .add_command( + "screenshot", + { + {"id", param_info(pt_integer, false, "Console ID. Find yours by using the \"status\" command.")}, + {"format", param_info(pt_string, false, "Image format.", + {{"0", "png"}, + {"1", "jpg"},} + )}, + }, + [&handler, this](const std::string& command, const parameter_list_t& params, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Program Screenshot"); + + if (params.size() < 2){ + embed.set_description("Missing command arguments."); + message.add_embed(embed); + handler.reply(message, src); + return; + } + + handler.thinking(src); + std::string name = "None"; + int64_t id = Utility::sanitize_integer_input(params, 0); + std::string button_input = std::get(params[1].second); + int64_t format = Utility::get_value_from_input(handler, command, button_input, name); + + std::string path; + if (format == 0){ + path = "screenshot_slash.png"; + }else{ + path = "screenshot_slash.jpg"; + } + + std::string response = Integration::screenshot(id, path.c_str()); + if (!response.empty()){ + embed.set_description(response); + Handler::update_response(src, embed, "", nullptr); + return; + } + + std::shared_ptr file(new PendingFileSend(path, true)); + embed_footer footer; + footer.set_text("Console ID: " + std::to_string(id) + " (" + name + ")"); + + embed.set_footer(footer); + Handler::update_response(src, embed, "", std::move(file)); + }, + "Take and upload a screenshot from the specified console.") + + .add_command( + "help", + {}, + [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + message message; + embed embed; + embed.set_color((uint32_t)color).set_title("Command List"); + + auto& commands = handler.commands; + for (auto& cmd : commands){ + std::string name = cmd.first; + log_dpp(name, "help command", ll_info); + if (!GlobalSettings::instance().DISCORD->integration.allow_buttons_from_users && + src.issuer.id != owner.id && name != "hi" && name != "ping" && name != "about" && name != "status" && name != "help" + ){ + continue; + } + + std::string param_info; + for (auto& param : cmd.second.parameters){ + param_info += ("\n**- " + param.first + "** - " + param.second.description); + if (!param.second.choices.empty()){ + param_info += " ("; + for (auto& choice : param.second.choices){ + param_info += (choice.second + ", "); + } + param_info = param_info.substr(0, param_info.size() - 2); + param_info += ")"; + } + } + embed.add_field(name, param_info); + } + embed_footer footer; + footer.set_text("Commands are case-sensitive!"); + embed.set_footer(footer); + message.add_embed(embed); + handler.reply(message, src); + }, + "View the command list.") + + .add_command( + "register", + {}, + [&handler, this](const std::string& command, const parameter_list_t&, command_source src){ + log_dpp("Executing " + command + "...", "Unified Command Handler", ll_info); + if (src.issuer.id != owner.id){ + handler.reply(message("You do not have permission to use this command."), src); + return; + } + + if (handler.slash_commands_enabled){ + handler.thinking(src); + log_dpp("Registering commands.", "Command Registration", ll_info); + handler.register_commands(); + + embed embed; + std::string desc = "Slash commands registered! Restart your Discord client or wait a few minutes for them to show up!"; + embed.set_color((uint32_t)color).set_description(desc).set_title("Slash Command Registration"); + Handler::update_response(src, embed, "", nullptr); + }else{ + handler.reply(message("Enable slash commands before registering them."), src); + } + }, + "Register global slash commands. For first-time slash command use and for updating commands."); +} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.h b/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.h index 56669e0121..2258c842e7 100644 --- a/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.h +++ b/SerialPrograms/Source/Integrations/DppIntegration/DppCommandHandler.h @@ -1,62 +1,62 @@ -#pragma once -#ifndef DPP_HANDLER_H -#define DPP_HANDLER_H - -#include -#include -#include "CommonFramework/Notifications/MessageAttachment.h" -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "Integrations/DiscordSettingsOption.h" - -namespace PokemonAutomation{ -namespace Integration{ -namespace DppCommandHandler{ - - - -class Handler : DppUtility::Utility{ -public: - Handler() {} - -private: - struct SlashCommand{ - dpp::slashcommand command; - std::function func; - }; - - AsyncDispatcher m_dispatcher = AsyncDispatcher(nullptr, 1); - ScheduledTaskRunner m_queue = ScheduledTaskRunner(m_dispatcher); - std::mutex m_count_lock; - static dpp::user owner; - static Color color; - -protected: - void initialize(dpp::cluster& bot, dpp::commandhandler& handler); - bool check_if_empty(const DiscordSettingsOption& settings); - void log_dpp(const std::string& message, const std::string& identity, const dpp::loglevel& ll); - void send_message( - dpp::cluster& bot, - dpp::embed& embed, - const std::string& channel, - std::chrono::milliseconds delay, - const std::string& msg, - std::shared_ptr file - ); - -private: - void create_unified_commands(dpp::commandhandler& handler); - void update_response( - const dpp::command_source& src, - dpp::embed& embed, - const std::string& msg, - std::shared_ptr file - ); -}; - - - - -} -} -} -#endif +#pragma once +#ifndef DPP_HANDLER_H +#define DPP_HANDLER_H + +#include +#include +#include "CommonFramework/Notifications/MessageAttachment.h" +#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" +#include "Integrations/DiscordSettingsOption.h" + +namespace PokemonAutomation{ +namespace Integration{ +namespace DppCommandHandler{ + + + +class Handler : DppUtility::Utility{ +public: + Handler() {} + +private: + struct SlashCommand{ + dpp::slashcommand command; + std::function func; + }; + + AsyncDispatcher m_dispatcher = AsyncDispatcher(nullptr, 1); + ScheduledTaskRunner m_queue = ScheduledTaskRunner(m_dispatcher); + std::mutex m_count_lock; + static dpp::user owner; + static Color color; + +protected: + void initialize(dpp::cluster& bot, dpp::commandhandler& handler); + bool check_if_empty(const DiscordSettingsOption& settings); + void log_dpp(const std::string& message, const std::string& identity, const dpp::loglevel& ll); + void send_message( + dpp::cluster& bot, + dpp::embed& embed, + const std::string& channel, + std::chrono::milliseconds delay, + const std::string& msg, + std::shared_ptr file + ); + +private: + void create_unified_commands(dpp::commandhandler& handler); + void update_response( + const dpp::command_source& src, + dpp::embed& embed, + const std::string& msg, + std::shared_ptr file + ); +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.cpp b/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.cpp index 17ca8153da..ee7eb17ffe 100644 --- a/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.cpp +++ b/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.cpp @@ -1,87 +1,87 @@ -#ifdef PA_DPP - -#include -#include -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" - -using namespace dpp; -namespace PokemonAutomation{ -namespace Integration{ -namespace DppUtility{ - -std::map Utility::user_counts; - -Logger& Utility::dpp_logger(){ - static TaggedLogger logger(global_logger_raw(), "DPP"); - return logger; -} - -void Utility::log(const std::string& message, const std::string& identity, const loglevel& ll){ - std::string log = identity + (std::string)": " + message; - Color color; - switch (ll){ - case ll_debug: color = COLOR_CYAN; break; - case ll_error: color = COLOR_RED; break; - case ll_critical: color = COLOR_MAGENTA; break; - default: color = COLOR_PURPLE; break; - }; - - dpp_logger().log(log, color); -} - -void Utility::get_user_counts(cluster& bot, const guild_create_t& event){ - // Retrieve ID and exit early if we have already pulled members for this guild. - auto id = std::to_string(event.created->id); - if (!user_counts.empty() && user_counts.count(id)){ - log("Users for " + event.created->name + " already initialized.", "get_user_counts()", ll_info); - return; - } - - uint32_t count = event.created->member_count; - user_counts.emplace(id, count); - log("User count: " + std::to_string(count) + " (" + event.created->name + ")", "get_user_counts()", ll_info); -} - -uint16_t Utility::get_button(const uint16_t& bt){ - if (bt > 13){ - uint8_t dpad = 0; - switch (bt){ - case 14: dpad = 0; break; // DUP - case 15: dpad = 4; break; // DDown - case 16: dpad = 6; break; // DLeft - case 17: dpad = 2; break; // DRight - default: dpad = 0; break; - }; - return dpad; - } - return 1 << bt; -} - -int64_t Utility::get_value_from_input(const commandhandler& handler, const std::string& command_name, const std::string& input, std::string& out){ - auto cmd = handler.commands.find(command_name); - auto& choices = cmd->second.parameters[1].second.choices; - for (auto& choice : choices){ - std::string val = std::get(choice.first); - if (val == input || choice.second == input){ - out = choice.second; - return std::stoi(val); - } - } - return -1; -} - -int64_t Utility::sanitize_integer_input(const parameter_list_t& params, const uint8_t& index){ - int64_t val = std::get(params[index].second); - if (val < 0){ - return 0; - } - return val; -} - - - -} -} -} -#endif +#ifdef PA_DPP + +#include +#include +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" + +using namespace dpp; +namespace PokemonAutomation{ +namespace Integration{ +namespace DppUtility{ + +std::map Utility::user_counts; + +Logger& Utility::dpp_logger(){ + static TaggedLogger logger(global_logger_raw(), "DPP"); + return logger; +} + +void Utility::log(const std::string& message, const std::string& identity, const loglevel& ll){ + std::string log = identity + (std::string)": " + message; + Color color; + switch (ll){ + case ll_debug: color = COLOR_CYAN; break; + case ll_error: color = COLOR_RED; break; + case ll_critical: color = COLOR_MAGENTA; break; + default: color = COLOR_PURPLE; break; + }; + + dpp_logger().log(log, color); +} + +void Utility::get_user_counts(cluster& bot, const guild_create_t& event){ + // Retrieve ID and exit early if we have already pulled members for this guild. + auto id = std::to_string(event.created->id); + if (!user_counts.empty() && user_counts.count(id)){ + log("Users for " + event.created->name + " already initialized.", "get_user_counts()", ll_info); + return; + } + + uint32_t count = event.created->member_count; + user_counts.emplace(id, count); + log("User count: " + std::to_string(count) + " (" + event.created->name + ")", "get_user_counts()", ll_info); +} + +uint16_t Utility::get_button(const uint16_t& bt){ + if (bt > 13){ + uint8_t dpad = 0; + switch (bt){ + case 14: dpad = 0; break; // DUP + case 15: dpad = 4; break; // DDown + case 16: dpad = 6; break; // DLeft + case 17: dpad = 2; break; // DRight + default: dpad = 0; break; + }; + return dpad; + } + return 1 << bt; +} + +int64_t Utility::get_value_from_input(const commandhandler& handler, const std::string& command_name, const std::string& input, std::string& out){ + auto cmd = handler.commands.find(command_name); + auto& choices = cmd->second.parameters[1].second.choices; + for (auto& choice : choices){ + std::string val = std::get(choice.first); + if (val == input || choice.second == input){ + out = choice.second; + return std::stoi(val); + } + } + return -1; +} + +int64_t Utility::sanitize_integer_input(const parameter_list_t& params, const uint8_t& index){ + int64_t val = std::get(params[index].second); + if (val < 0){ + return 0; + } + return val; +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.h b/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.h index eee926c7cf..6e84479e9f 100644 --- a/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.h +++ b/SerialPrograms/Source/Integrations/DppIntegration/DppUtility.h @@ -1,37 +1,37 @@ -#pragma once -#ifndef DPP_UTILITY_H -#define DPP_UTILITY_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" - -namespace PokemonAutomation{ -namespace Integration{ -namespace DppUtility{ - - -class Utility{ -public: - Utility(){} - -protected: - static std::map user_counts; - -protected: - void log(const std::string& message, const std::string& identity, const dpp::loglevel& ll); - void get_user_counts(dpp::cluster& bot, const dpp::guild_create_t& event); - int64_t get_value_from_input(const dpp::commandhandler& handler, const std::string& cmd, const std::string& input, std::string& out); - int64_t sanitize_integer_input(const dpp::parameter_list_t& params, const uint8_t& index); - uint16_t get_button(const uint16_t& bt); - -private: - Logger& dpp_logger(); -}; - - - -} -} -} -#endif +#pragma once +#ifndef DPP_UTILITY_H +#define DPP_UTILITY_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" + +namespace PokemonAutomation{ +namespace Integration{ +namespace DppUtility{ + + +class Utility{ +public: + Utility(){} + +protected: + static std::map user_counts; + +protected: + void log(const std::string& message, const std::string& identity, const dpp::loglevel& ll); + void get_user_counts(dpp::cluster& bot, const dpp::guild_create_t& event); + int64_t get_value_from_input(const dpp::commandhandler& handler, const std::string& cmd, const std::string& input, std::string& out); + int64_t sanitize_integer_input(const dpp::parameter_list_t& params, const uint8_t& index); + uint16_t get_button(const uint16_t& bt); + +private: + Logger& dpp_logger(); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/IntegrationsAPI.cpp b/SerialPrograms/Source/Integrations/IntegrationsAPI.cpp index faad07f407..21514b655f 100644 --- a/SerialPrograms/Source/Integrations/IntegrationsAPI.cpp +++ b/SerialPrograms/Source/Integrations/IntegrationsAPI.cpp @@ -1,126 +1,126 @@ -/* Integrations API - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "Integrations/ProgramTracker.h" -#include "IntegrationsAPI.h" - -namespace PokemonAutomation{ -namespace Integration{ - - -void pai_run_command(DllSafeString& error, const char* commands){ - error = "Not supported yet."; - -#if 0 - // Split string into tokens. - std::vector tokens; - std::istringstream stream(commands); - std::string str; - while (std::getline(stream, str, ' ')){ - if (!str.empty()){ - tokens.emplace_back(std::move(str)); - } - } -#endif -} - -void pai_status(DllSafeString& description){ - std::string str; - for (const auto& item : ProgramTracker::instance().all_programs()){ - str += "__**Program " + std::to_string(item.first) + "**__\n"; - str += "* **Name:** " + item.second.program_name + "\n"; - str += "* **State:** "; - WallClock now = current_time(); - switch (item.second.state){ - case ProgramState::NOT_READY: - str += "Not Ready"; - break; - case ProgramState::STOPPED: - str += "Stopped"; - break; - case ProgramState::RUNNING: - str += "Running"; - str += " ("; - str += duration_to_string(std::chrono::duration_cast(now - item.second.start_time)); - str += ")"; - break; - case ProgramState::STOPPING: - str += "Stopping"; - break; - } - str += "\n"; - if (!item.second.stats.empty()){ - str += "* **Stats:** " + item.second.stats + "\n"; - } - str += "* **Console ID(s):** "; - bool first = true; - if (item.second.console_ids.empty()){ - str += "No consoles enabled."; - } - for (uint64_t console_id : item.second.console_ids){ - if (!first){ - str += ", "; - } - first = false; - str += std::to_string(console_id); - } - str += "\n\n"; - } - if (str.empty()){ - str = "No programs running."; - } - description = str; -} -void pai_screenshot(DllSafeString& error, uint64_t console_id, const char* path){ - std::shared_ptr image; - std::string err = ProgramTracker::instance().grab_screenshot(console_id, image); - if (!err.empty()){ - error = err; - return; - } - if (image->save(path)){ - error = DllSafeString(); - }else{ - error = std::string("Failed to save image to: ") + path; - } -} - -void pai_reset_camera(DllSafeString& error, uint64_t console_id){ - error = ProgramTracker::instance().reset_camera(console_id); -} -void pai_reset_serial(DllSafeString& error, uint64_t console_id){ - error = ProgramTracker::instance().reset_serial(console_id); -} - -void pai_start_program(DllSafeString& error, uint64_t program_id){ - error = ProgramTracker::instance().start_program(program_id); -} -void pai_stop_program(DllSafeString& error, uint64_t program_id){ - error = ProgramTracker::instance().stop_program(program_id); -} - -void pai_nsw_press_button(DllSafeString& error, uint64_t console_id, uint16_t button, uint16_t ticks){ - error = ProgramTracker::instance().nsw_press_button(console_id, (NintendoSwitch::Button)button, ticks); -} -void pai_nsw_press_dpad(DllSafeString& error, uint64_t console_id, uint8_t position, uint16_t ticks){ - error = ProgramTracker::instance().nsw_press_dpad(console_id, (NintendoSwitch::DpadPosition)position, ticks); -} -void pai_nsw_press_left_joystick(DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ - error = ProgramTracker::instance().nsw_press_left_joystick(console_id, x, y, ticks); -} -void pai_nsw_press_right_joystick(DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ - error = ProgramTracker::instance().nsw_press_right_joystick(console_id, x, y, ticks); -} - - - - - -} -} +/* Integrations API + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "Integrations/ProgramTracker.h" +#include "IntegrationsAPI.h" + +namespace PokemonAutomation{ +namespace Integration{ + + +void pai_run_command(DllSafeString& error, const char* commands){ + error = "Not supported yet."; + +#if 0 + // Split string into tokens. + std::vector tokens; + std::istringstream stream(commands); + std::string str; + while (std::getline(stream, str, ' ')){ + if (!str.empty()){ + tokens.emplace_back(std::move(str)); + } + } +#endif +} + +void pai_status(DllSafeString& description){ + std::string str; + for (const auto& item : ProgramTracker::instance().all_programs()){ + str += "__**Program " + std::to_string(item.first) + "**__\n"; + str += "* **Name:** " + item.second.program_name + "\n"; + str += "* **State:** "; + WallClock now = current_time(); + switch (item.second.state){ + case ProgramState::NOT_READY: + str += "Not Ready"; + break; + case ProgramState::STOPPED: + str += "Stopped"; + break; + case ProgramState::RUNNING: + str += "Running"; + str += " ("; + str += duration_to_string(std::chrono::duration_cast(now - item.second.start_time)); + str += ")"; + break; + case ProgramState::STOPPING: + str += "Stopping"; + break; + } + str += "\n"; + if (!item.second.stats.empty()){ + str += "* **Stats:** " + item.second.stats + "\n"; + } + str += "* **Console ID(s):** "; + bool first = true; + if (item.second.console_ids.empty()){ + str += "No consoles enabled."; + } + for (uint64_t console_id : item.second.console_ids){ + if (!first){ + str += ", "; + } + first = false; + str += std::to_string(console_id); + } + str += "\n\n"; + } + if (str.empty()){ + str = "No programs running."; + } + description = str; +} +void pai_screenshot(DllSafeString& error, uint64_t console_id, const char* path){ + std::shared_ptr image; + std::string err = ProgramTracker::instance().grab_screenshot(console_id, image); + if (!err.empty()){ + error = err; + return; + } + if (image->save(path)){ + error = DllSafeString(); + }else{ + error = std::string("Failed to save image to: ") + path; + } +} + +void pai_reset_camera(DllSafeString& error, uint64_t console_id){ + error = ProgramTracker::instance().reset_camera(console_id); +} +void pai_reset_serial(DllSafeString& error, uint64_t console_id){ + error = ProgramTracker::instance().reset_serial(console_id); +} + +void pai_start_program(DllSafeString& error, uint64_t program_id){ + error = ProgramTracker::instance().start_program(program_id); +} +void pai_stop_program(DllSafeString& error, uint64_t program_id){ + error = ProgramTracker::instance().stop_program(program_id); +} + +void pai_nsw_press_button(DllSafeString& error, uint64_t console_id, uint16_t button, uint16_t ticks){ + error = ProgramTracker::instance().nsw_press_button(console_id, (NintendoSwitch::Button)button, ticks); +} +void pai_nsw_press_dpad(DllSafeString& error, uint64_t console_id, uint8_t position, uint16_t ticks){ + error = ProgramTracker::instance().nsw_press_dpad(console_id, (NintendoSwitch::DpadPosition)position, ticks); +} +void pai_nsw_press_left_joystick(DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ + error = ProgramTracker::instance().nsw_press_left_joystick(console_id, x, y, ticks); +} +void pai_nsw_press_right_joystick(DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ + error = ProgramTracker::instance().nsw_press_right_joystick(console_id, x, y, ticks); +} + + + + + +} +} diff --git a/SerialPrograms/Source/Integrations/IntegrationsAPI.h b/SerialPrograms/Source/Integrations/IntegrationsAPI.h index 1cf861a4e8..5fb6b0aec5 100644 --- a/SerialPrograms/Source/Integrations/IntegrationsAPI.h +++ b/SerialPrograms/Source/Integrations/IntegrationsAPI.h @@ -1,98 +1,98 @@ -/* Integrations API - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_IntegrationsAPI_H -#define PokemonAutomation_IntegrationsAPI_H - -#include -#include "Common/Cpp/Containers/DllSafeString.h" - -namespace PokemonAutomation{ -namespace Integration{ -extern "C" { - - -// Empty error means no error. - -void pai_run_command (DllSafeString& error, const char* commands); - -void pai_status (DllSafeString& description); -void pai_screenshot (DllSafeString& error, uint64_t console_id, const char* path); - -void pai_reset_camera (DllSafeString& error, uint64_t console_id); -void pai_reset_serial (DllSafeString& error, uint64_t console_id); - -void pai_start_program (DllSafeString& error, uint64_t program_id); -void pai_stop_program (DllSafeString& error, uint64_t program_id); - -void pai_nsw_press_button (DllSafeString& error, uint64_t console_id, uint16_t button, uint16_t ticks); -void pai_nsw_press_dpad (DllSafeString& error, uint64_t console_id, uint8_t position, uint16_t ticks); -void pai_nsw_press_left_joystick (DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); -void pai_nsw_press_right_joystick (DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); - - -} - - - -inline std::string status(){ - DllSafeString description; - pai_status(description); - return description; -} -inline std::string screenshot(uint64_t console_id, const char* path){ - DllSafeString error; - pai_screenshot(error, console_id, path); - return error; -} -inline std::string reset_camera(uint64_t console_id){ - DllSafeString error; - pai_reset_camera(error, console_id); - return error; -} -inline std::string reset_serial(uint64_t console_id){ - DllSafeString error; - pai_reset_serial(error, console_id); - return error; -} -inline std::string start_program(uint64_t program_id){ - DllSafeString error; - pai_start_program(error, program_id); - return error; -} -inline std::string stop_program(uint64_t program_id){ - DllSafeString error; - pai_stop_program(error, program_id); - return error; -} -inline std::string press_button(uint64_t console_id, uint16_t button, uint16_t ticks){ - DllSafeString error; - pai_nsw_press_button(error, console_id, button, ticks); - return error; -} -inline std::string press_dpad(uint64_t console_id, uint8_t position, uint16_t ticks){ - DllSafeString error; - pai_nsw_press_dpad(error, console_id, position, ticks); - return error; -} -inline std::string press_left_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ - DllSafeString error; - pai_nsw_press_left_joystick(error, console_id, x, y, ticks); - return error; -} -inline std::string press_right_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ - DllSafeString error; - pai_nsw_press_right_joystick(error, console_id, x, y, ticks); - return error; -} - - - -} -} -#endif - - +/* Integrations API + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_IntegrationsAPI_H +#define PokemonAutomation_IntegrationsAPI_H + +#include +#include "Common/Cpp/Containers/DllSafeString.h" + +namespace PokemonAutomation{ +namespace Integration{ +extern "C" { + + +// Empty error means no error. + +void pai_run_command (DllSafeString& error, const char* commands); + +void pai_status (DllSafeString& description); +void pai_screenshot (DllSafeString& error, uint64_t console_id, const char* path); + +void pai_reset_camera (DllSafeString& error, uint64_t console_id); +void pai_reset_serial (DllSafeString& error, uint64_t console_id); + +void pai_start_program (DllSafeString& error, uint64_t program_id); +void pai_stop_program (DllSafeString& error, uint64_t program_id); + +void pai_nsw_press_button (DllSafeString& error, uint64_t console_id, uint16_t button, uint16_t ticks); +void pai_nsw_press_dpad (DllSafeString& error, uint64_t console_id, uint8_t position, uint16_t ticks); +void pai_nsw_press_left_joystick (DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); +void pai_nsw_press_right_joystick (DllSafeString& error, uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); + + +} + + + +inline std::string status(){ + DllSafeString description; + pai_status(description); + return description; +} +inline std::string screenshot(uint64_t console_id, const char* path){ + DllSafeString error; + pai_screenshot(error, console_id, path); + return error; +} +inline std::string reset_camera(uint64_t console_id){ + DllSafeString error; + pai_reset_camera(error, console_id); + return error; +} +inline std::string reset_serial(uint64_t console_id){ + DllSafeString error; + pai_reset_serial(error, console_id); + return error; +} +inline std::string start_program(uint64_t program_id){ + DllSafeString error; + pai_start_program(error, program_id); + return error; +} +inline std::string stop_program(uint64_t program_id){ + DllSafeString error; + pai_stop_program(error, program_id); + return error; +} +inline std::string press_button(uint64_t console_id, uint16_t button, uint16_t ticks){ + DllSafeString error; + pai_nsw_press_button(error, console_id, button, ticks); + return error; +} +inline std::string press_dpad(uint64_t console_id, uint8_t position, uint16_t ticks){ + DllSafeString error; + pai_nsw_press_dpad(error, console_id, position, ticks); + return error; +} +inline std::string press_left_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ + DllSafeString error; + pai_nsw_press_left_joystick(error, console_id, x, y, ticks); + return error; +} +inline std::string press_right_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ + DllSafeString error; + pai_nsw_press_right_joystick(error, console_id, x, y, ticks); + return error; +} + + + +} +} +#endif + + diff --git a/SerialPrograms/Source/Integrations/ProgramTracker.cpp b/SerialPrograms/Source/Integrations/ProgramTracker.cpp index f06b6db430..b5ad97331f 100644 --- a/SerialPrograms/Source/Integrations/ProgramTracker.cpp +++ b/SerialPrograms/Source/Integrations/ProgramTracker.cpp @@ -1,292 +1,292 @@ -/* Panel Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Controllers/ControllerSession.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "ProgramTracker.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -using namespace std::chrono_literals; - - -ProgramTracker& ProgramTracker::instance(){ - static ProgramTracker obj; - return obj; -} - - - -struct ProgramTracker::ProgramData{ - size_t system_count; - TrackableProgram& program; - std::vector console_ids; - - ProgramData(size_t p_system_count, TrackableProgram& p_program) - : system_count(p_system_count) - , program(p_program) - {} -}; - - -std::map ProgramTracker::all_programs(){ - std::lock_guard lg(m_lock); - std::map info; - for (const auto& item : m_programs){ - info[item.first] = ProgramTrackingState{ - item.second->program.identifier(), - item.second->console_ids, - item.second->program.timestamp(), - item.second->program.current_state(), - item.second->program.current_stats() - }; - } - return info; -} - -std::string ProgramTracker::grab_screenshot(uint64_t console_id, std::shared_ptr& image){ - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = "grab_screenshot(" + std::to_string(console_id) + ") - ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - VideoSnapshot snapshot = iter->second.first->video().snapshot(); - image = std::move(snapshot.frame); - return ""; -} -std::string ProgramTracker::reset_camera(uint64_t console_id){ - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = "reset_camera(" + std::to_string(console_id) + ") - ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - iter->second.first->video().reset(); - return ""; -} -std::string ProgramTracker::reset_serial(uint64_t console_id){ - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = "reset_serial(" + std::to_string(console_id) + ") - ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - std::string error = iter->second.first->controller().reset(); - return error.empty() ? "Serial connection was reset." : error; -} -std::string ProgramTracker::start_program(uint64_t program_id){ - std::lock_guard lg(m_lock); - auto iter = m_programs.find(program_id); - if (iter == m_programs.end()){ - std::string error = "start_program(ID = " + std::to_string(program_id) + ") - ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - iter->second->program.async_start(); - return ""; -} -std::string ProgramTracker::stop_program(uint64_t program_id){ - std::lock_guard lg(m_lock); - auto iter = m_programs.find(program_id); - if (iter == m_programs.end()){ - std::string error = "stop_program(ID = " + std::to_string(program_id) + ") - ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - iter->second->program.async_stop(); - return ""; -} -std::string ProgramTracker::nsw_press_button(uint64_t console_id, NintendoSwitch::Button button, uint16_t ticks){ - using namespace NintendoSwitch; - std::string header = "press_button(ID = " + std::to_string(console_id) + ")"; - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = header + ": ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - Milliseconds duration = ticks * 8ms; - std::string err; - try{ - err = iter->second.first->controller().try_run( - [=](ProController& controller){ - controller.issue_buttons(nullptr, duration, duration, 0ms, button); - } - ); - }catch (Exception& e){ - e.log(global_logger_tagged()); - err = e.to_str(); - } - if (err.empty()){ - global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); - return ""; - }else{ - global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); - return err; - } -} -std::string ProgramTracker::nsw_press_dpad(uint64_t console_id, NintendoSwitch::DpadPosition position, uint16_t ticks){ - using namespace NintendoSwitch; - std::string header = "press_dpad(ID = " + std::to_string(console_id) + ")"; - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = header + ": ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - Milliseconds duration = ticks * 8ms; - std::string err; - try{ - err = iter->second.first->controller().try_run( - [=](ProController& controller){ - controller.issue_dpad(nullptr, duration, duration, 0ms, position); - } - ); - }catch (Exception& e){ - e.log(global_logger_tagged()); - err = e.to_str(); - } - if (err.empty()){ - global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); - return ""; - }else{ - global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); - return err; - } -} -std::string ProgramTracker::nsw_press_left_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ - using namespace NintendoSwitch; - std::string header = "press_left_joystick(ID = " + std::to_string(console_id) + ")"; - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = header + ": ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - Milliseconds duration = ticks * 8ms; - std::string err; - try{ - err = iter->second.first->controller().try_run( - [=](ProController& controller){ - controller.issue_left_joystick(nullptr, duration, duration, 0ms, x, y); - } - ); - }catch (Exception& e){ - e.log(global_logger_tagged()); - err = e.to_str(); - } - if (err.empty()){ - global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); - return ""; - }else{ - global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); - return err; - } -} -std::string ProgramTracker::nsw_press_right_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ - using namespace NintendoSwitch; - std::string header = "press_right_joystick(ID = " + std::to_string(console_id) + ")"; - std::lock_guard lg(m_lock); - auto iter = m_consoles.find(console_id); - if (iter == m_consoles.end()){ - std::string error = header + ": ID not found."; - global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); - return error; - } - Milliseconds duration = ticks * 8ms; - std::string err; - try{ - err = iter->second.first->controller().try_run( - [=](ProController& controller){ - controller.issue_right_joystick(nullptr, duration, duration, 0ms, x, y); - } - ); - }catch (Exception& e){ - e.log(global_logger_tagged()); - err = e.to_str(); - } - if (err.empty()){ - global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); - return ""; - }else{ - global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); - return err; - } -} - - - - - -uint64_t ProgramTracker::add_program(TrackableProgram& program){ - std::lock_guard lg(m_lock); - m_program_instance_counter++; - m_programs.emplace( - m_program_instance_counter, - std::unique_ptr(new ProgramData(0, program)) - ); - return m_program_instance_counter; -} -void ProgramTracker::remove_program(uint64_t program_id){ - std::lock_guard lg(m_lock); - m_programs.erase(program_id); -} -uint64_t ProgramTracker::add_console(uint64_t program_id, TrackableConsole& console){ - std::lock_guard lg(m_lock); - m_console_instance_counter++; - m_consoles.emplace( - std::piecewise_construct, - std::forward_as_tuple(m_console_instance_counter), - std::forward_as_tuple(&console, program_id) - ); - auto iter = m_programs.find(program_id); - if (iter != m_programs.end()){ - iter->second->console_ids.emplace_back(m_console_instance_counter); - } - return m_console_instance_counter; -} -void ProgramTracker::remove_console(uint64_t console_id){ - std::lock_guard lg(m_lock); - auto iter0 = m_consoles.find(console_id); - if (iter0 == m_consoles.end()){ - return; - } - uint64_t program_id = iter0->second.second; - m_consoles.erase(iter0); - auto iter1 = m_programs.find(program_id); - if (iter1 == m_programs.end()){ - return; - } - std::vector& consoles = iter1->second->console_ids; - for (auto iter = consoles.begin(); iter != consoles.end(); ++iter){ - if (*iter == console_id){ - consoles.erase(iter); - break; - } - } -} - - - - - - - -} +/* Panel Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Controllers/ControllerSession.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "ProgramTracker.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +using namespace std::chrono_literals; + + +ProgramTracker& ProgramTracker::instance(){ + static ProgramTracker obj; + return obj; +} + + + +struct ProgramTracker::ProgramData{ + size_t system_count; + TrackableProgram& program; + std::vector console_ids; + + ProgramData(size_t p_system_count, TrackableProgram& p_program) + : system_count(p_system_count) + , program(p_program) + {} +}; + + +std::map ProgramTracker::all_programs(){ + std::lock_guard lg(m_lock); + std::map info; + for (const auto& item : m_programs){ + info[item.first] = ProgramTrackingState{ + item.second->program.identifier(), + item.second->console_ids, + item.second->program.timestamp(), + item.second->program.current_state(), + item.second->program.current_stats() + }; + } + return info; +} + +std::string ProgramTracker::grab_screenshot(uint64_t console_id, std::shared_ptr& image){ + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = "grab_screenshot(" + std::to_string(console_id) + ") - ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + VideoSnapshot snapshot = iter->second.first->video().snapshot(); + image = std::move(snapshot.frame); + return ""; +} +std::string ProgramTracker::reset_camera(uint64_t console_id){ + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = "reset_camera(" + std::to_string(console_id) + ") - ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + iter->second.first->video().reset(); + return ""; +} +std::string ProgramTracker::reset_serial(uint64_t console_id){ + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = "reset_serial(" + std::to_string(console_id) + ") - ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + std::string error = iter->second.first->controller().reset(); + return error.empty() ? "Serial connection was reset." : error; +} +std::string ProgramTracker::start_program(uint64_t program_id){ + std::lock_guard lg(m_lock); + auto iter = m_programs.find(program_id); + if (iter == m_programs.end()){ + std::string error = "start_program(ID = " + std::to_string(program_id) + ") - ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + iter->second->program.async_start(); + return ""; +} +std::string ProgramTracker::stop_program(uint64_t program_id){ + std::lock_guard lg(m_lock); + auto iter = m_programs.find(program_id); + if (iter == m_programs.end()){ + std::string error = "stop_program(ID = " + std::to_string(program_id) + ") - ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + iter->second->program.async_stop(); + return ""; +} +std::string ProgramTracker::nsw_press_button(uint64_t console_id, NintendoSwitch::Button button, uint16_t ticks){ + using namespace NintendoSwitch; + std::string header = "press_button(ID = " + std::to_string(console_id) + ")"; + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = header + ": ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + Milliseconds duration = ticks * 8ms; + std::string err; + try{ + err = iter->second.first->controller().try_run( + [=](ProController& controller){ + controller.issue_buttons(nullptr, duration, duration, 0ms, button); + } + ); + }catch (Exception& e){ + e.log(global_logger_tagged()); + err = e.to_str(); + } + if (err.empty()){ + global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); + return ""; + }else{ + global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); + return err; + } +} +std::string ProgramTracker::nsw_press_dpad(uint64_t console_id, NintendoSwitch::DpadPosition position, uint16_t ticks){ + using namespace NintendoSwitch; + std::string header = "press_dpad(ID = " + std::to_string(console_id) + ")"; + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = header + ": ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + Milliseconds duration = ticks * 8ms; + std::string err; + try{ + err = iter->second.first->controller().try_run( + [=](ProController& controller){ + controller.issue_dpad(nullptr, duration, duration, 0ms, position); + } + ); + }catch (Exception& e){ + e.log(global_logger_tagged()); + err = e.to_str(); + } + if (err.empty()){ + global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); + return ""; + }else{ + global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); + return err; + } +} +std::string ProgramTracker::nsw_press_left_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ + using namespace NintendoSwitch; + std::string header = "press_left_joystick(ID = " + std::to_string(console_id) + ")"; + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = header + ": ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + Milliseconds duration = ticks * 8ms; + std::string err; + try{ + err = iter->second.first->controller().try_run( + [=](ProController& controller){ + controller.issue_left_joystick(nullptr, duration, duration, 0ms, x, y); + } + ); + }catch (Exception& e){ + e.log(global_logger_tagged()); + err = e.to_str(); + } + if (err.empty()){ + global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); + return ""; + }else{ + global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); + return err; + } +} +std::string ProgramTracker::nsw_press_right_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks){ + using namespace NintendoSwitch; + std::string header = "press_right_joystick(ID = " + std::to_string(console_id) + ")"; + std::lock_guard lg(m_lock); + auto iter = m_consoles.find(console_id); + if (iter == m_consoles.end()){ + std::string error = header + ": ID not found."; + global_logger_tagged().log("SwitchProgramTracker::" + error, COLOR_RED); + return error; + } + Milliseconds duration = ticks * 8ms; + std::string err; + try{ + err = iter->second.first->controller().try_run( + [=](ProController& controller){ + controller.issue_right_joystick(nullptr, duration, duration, 0ms, x, y); + } + ); + }catch (Exception& e){ + e.log(global_logger_tagged()); + err = e.to_str(); + } + if (err.empty()){ + global_logger_tagged().log("SwitchProgramTracker::" + header, COLOR_BLUE); + return ""; + }else{ + global_logger_tagged().log("SwitchProgramTracker::" + header + ": " + err, COLOR_RED); + return err; + } +} + + + + + +uint64_t ProgramTracker::add_program(TrackableProgram& program){ + std::lock_guard lg(m_lock); + m_program_instance_counter++; + m_programs.emplace( + m_program_instance_counter, + std::unique_ptr(new ProgramData(0, program)) + ); + return m_program_instance_counter; +} +void ProgramTracker::remove_program(uint64_t program_id){ + std::lock_guard lg(m_lock); + m_programs.erase(program_id); +} +uint64_t ProgramTracker::add_console(uint64_t program_id, TrackableConsole& console){ + std::lock_guard lg(m_lock); + m_console_instance_counter++; + m_consoles.emplace( + std::piecewise_construct, + std::forward_as_tuple(m_console_instance_counter), + std::forward_as_tuple(&console, program_id) + ); + auto iter = m_programs.find(program_id); + if (iter != m_programs.end()){ + iter->second->console_ids.emplace_back(m_console_instance_counter); + } + return m_console_instance_counter; +} +void ProgramTracker::remove_console(uint64_t console_id){ + std::lock_guard lg(m_lock); + auto iter0 = m_consoles.find(console_id); + if (iter0 == m_consoles.end()){ + return; + } + uint64_t program_id = iter0->second.second; + m_consoles.erase(iter0); + auto iter1 = m_programs.find(program_id); + if (iter1 == m_programs.end()){ + return; + } + std::vector& consoles = iter1->second->console_ids; + for (auto iter = consoles.begin(); iter != consoles.end(); ++iter){ + if (*iter == console_id){ + consoles.erase(iter); + break; + } + } +} + + + + + + + +} diff --git a/SerialPrograms/Source/Integrations/ProgramTracker.h b/SerialPrograms/Source/Integrations/ProgramTracker.h index e3d8679aa6..af5e5e337d 100644 --- a/SerialPrograms/Source/Integrations/ProgramTracker.h +++ b/SerialPrograms/Source/Integrations/ProgramTracker.h @@ -1,92 +1,92 @@ -/* Program Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * A singleton class that keeps track of all live programs and handles. - * This allows Discord integration to safely interface with programs. - * - */ - -#ifndef PokemonAutomation_ProgramTracker_H -#define PokemonAutomation_ProgramTracker_H - -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" -#include "ProgramTrackerInterfaces.h" - -namespace PokemonAutomation{ - -class ImageRGB32; -class VideoFeed; -class AudioFeed; - - - -struct ProgramTrackingState{ - std::string program_name; - std::vector console_ids; - WallClock start_time; - ProgramState state; - std::string stats; -}; - - - -class ProgramTracker{ -public: - static ProgramTracker& instance(); - - std::map all_programs(); - - std::string grab_screenshot (uint64_t console_id, std::shared_ptr& image); - std::string reset_camera (uint64_t console_id); - std::string reset_serial (uint64_t console_id); -// void change_program (uint64_t program_id, std::string program_identifier); - std::string start_program (uint64_t program_id); - std::string stop_program (uint64_t program_id); - - -public: - // Nintendo Switch - std::string nsw_press_button (uint64_t console_id, NintendoSwitch::Button button, uint16_t ticks); - std::string nsw_press_dpad (uint64_t console_id, NintendoSwitch::DpadPosition position, uint16_t ticks); - std::string nsw_press_left_joystick (uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); - std::string nsw_press_right_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); - - -private: - ProgramTracker() = default; - ProgramTracker(const ProgramTracker&) = delete; - void operator=(const ProgramTracker&) = delete; - -public: - uint64_t add_program(TrackableProgram& program); - void remove_program(uint64_t program_id); - - uint64_t add_console(uint64_t program_id, TrackableConsole& console); - void remove_console(uint64_t console_id); - - -private: - struct ProgramData; - - std::mutex m_lock; - uint64_t m_program_instance_counter = 0; - uint64_t m_console_instance_counter = 0; - std::map> m_programs; - std::map> m_consoles; -}; - - - - - - - - - -} -#endif +/* Program Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * A singleton class that keeps track of all live programs and handles. + * This allows Discord integration to safely interface with programs. + * + */ + +#ifndef PokemonAutomation_ProgramTracker_H +#define PokemonAutomation_ProgramTracker_H + +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" +#include "ProgramTrackerInterfaces.h" + +namespace PokemonAutomation{ + +class ImageRGB32; +class VideoFeed; +class AudioFeed; + + + +struct ProgramTrackingState{ + std::string program_name; + std::vector console_ids; + WallClock start_time; + ProgramState state; + std::string stats; +}; + + + +class ProgramTracker{ +public: + static ProgramTracker& instance(); + + std::map all_programs(); + + std::string grab_screenshot (uint64_t console_id, std::shared_ptr& image); + std::string reset_camera (uint64_t console_id); + std::string reset_serial (uint64_t console_id); +// void change_program (uint64_t program_id, std::string program_identifier); + std::string start_program (uint64_t program_id); + std::string stop_program (uint64_t program_id); + + +public: + // Nintendo Switch + std::string nsw_press_button (uint64_t console_id, NintendoSwitch::Button button, uint16_t ticks); + std::string nsw_press_dpad (uint64_t console_id, NintendoSwitch::DpadPosition position, uint16_t ticks); + std::string nsw_press_left_joystick (uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); + std::string nsw_press_right_joystick(uint64_t console_id, uint8_t x, uint8_t y, uint16_t ticks); + + +private: + ProgramTracker() = default; + ProgramTracker(const ProgramTracker&) = delete; + void operator=(const ProgramTracker&) = delete; + +public: + uint64_t add_program(TrackableProgram& program); + void remove_program(uint64_t program_id); + + uint64_t add_console(uint64_t program_id, TrackableConsole& console); + void remove_console(uint64_t console_id); + + +private: + struct ProgramData; + + std::mutex m_lock; + uint64_t m_program_instance_counter = 0; + uint64_t m_console_instance_counter = 0; + std::map> m_programs; + std::map> m_consoles; +}; + + + + + + + + + +} +#endif diff --git a/SerialPrograms/Source/Integrations/ProgramTrackerInterfaces.h b/SerialPrograms/Source/Integrations/ProgramTrackerInterfaces.h index bbfd2502f6..1d57fa7721 100644 --- a/SerialPrograms/Source/Integrations/ProgramTrackerInterfaces.h +++ b/SerialPrograms/Source/Integrations/ProgramTrackerInterfaces.h @@ -1,46 +1,46 @@ -/* Program Tracker - * - * From: https://github.com/PokemonAutomation/ - * - * A singleton class that keeps track of all live programs and handles. - * This allows Discord integration to safely interface with programs. - * - */ - -#ifndef PokemonAutomation_ProgramTrackerInterfaces_H -#define PokemonAutomation_ProgramTrackerInterfaces_H - -#include "Common/Cpp/Time.h" -#include "CommonFramework/Globals.h" - -namespace PokemonAutomation{ - -class VideoFeed; -class AudioFeed; -class ControllerSession; -class BotBaseHandle; - - -class TrackableConsole{ -public: - virtual VideoFeed& video() = 0; - virtual AudioFeed& audio() = 0; - virtual ControllerSession& controller() = 0; -}; - -class TrackableProgram{ -public: - virtual const std::string& identifier() const = 0; - virtual WallClock timestamp() const = 0; - virtual ProgramState current_state() const = 0; - virtual std::string current_stats() const = 0; - - virtual void async_start() = 0; - virtual void async_stop() = 0; -}; - - - - -} -#endif +/* Program Tracker + * + * From: https://github.com/PokemonAutomation/ + * + * A singleton class that keeps track of all live programs and handles. + * This allows Discord integration to safely interface with programs. + * + */ + +#ifndef PokemonAutomation_ProgramTrackerInterfaces_H +#define PokemonAutomation_ProgramTrackerInterfaces_H + +#include "Common/Cpp/Time.h" +#include "CommonFramework/Globals.h" + +namespace PokemonAutomation{ + +class VideoFeed; +class AudioFeed; +class ControllerSession; +class BotBaseHandle; + + +class TrackableConsole{ +public: + virtual VideoFeed& video() = 0; + virtual AudioFeed& audio() = 0; + virtual ControllerSession& controller() = 0; +}; + +class TrackableProgram{ +public: + virtual const std::string& identifier() const = 0; + virtual WallClock timestamp() const = 0; + virtual ProgramState current_state() const = 0; + virtual std::string current_stats() const = 0; + + virtual void async_start() = 0; + virtual void async_stop() = 0; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp b/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp index 2e3203f0ef..c9053adf40 100644 --- a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp +++ b/SerialPrograms/Source/Integrations/SleepyDiscordRunner.cpp @@ -1,634 +1,634 @@ - -#ifdef PA_SLEEPY - -#include -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/StringTools.h" -#include "Common/Cpp/PanicDump.h" -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "IntegrationsAPI.h" -#include "SleepyDiscordRunner.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Integration{ -namespace SleepyDiscordRunner{ - -using namespace SleepyDiscord; -const char* enum_str_callback[] = { - "Fault", - "API", - "Disconnected", - "Connected", - "Settings Initialized", - "Settings Updated", - "Commands Initialized", - "Callbacks Set", - "Invalid Command", - "Terminating", - "Remove File", -}; - -const char* enum_str_command[] = { - "Click", - "Click DPad", - - "Left Stick", - "Right Stick", - - "Screenshot JPG", - "Screenshot PNG", - "Start", - "Stop", - "Shutdown", - "Get Connected Bots", - "Reload Settings", - "Reset Camera", - "Reset Serial", - "Terminate", - - "Hi", - "Ping", - "About", - "Help", -}; - -const char* enum_str_state[] = { - "STOPPED", - "RUNNING", - "FINISHED", - "STOPPING", -}; - -std::unordered_map str_buttons = { - { 1, "Y" }, - { 2, "B" }, - { 4, "A" }, - { 8, "X" }, - { 16, "L" }, - { 32, "R" }, - { 64, "ZL" }, - { 128, "ZR" }, - { 256, "MINUS" }, - { 512, "PLUS" }, - { 1024, "LStick" }, - { 2048, "RStick" }, - { 4096, "HOME" }, - { 8192, "Capture" }, -}; - -std::unordered_map str_dpad = { - { 0, "DUp" }, - { 2, "DRight" }, - { 4, "DDown" }, - { 6, "DLeft" }, -}; - - -Logger& sleepy_logger(){ - static TaggedLogger logger(global_logger_raw(), "SleepyDiscord"); - return logger; -} - - -struct SleepyDiscordRequest{ - SleepyDiscordRequest() = default; - SleepyDiscordRequest(std::string embed, std::string channels, std::string messages, std::shared_ptr file) : - embed(std::move(embed)), - channels(std::move(channels)), - messages(std::move(messages)), - file(std::move(file)) {} - - std::string embed; - std::string channels; - std::string messages; - std::shared_ptr file; -}; - -class SleepyDiscordSender{ -private: - SleepyDiscordSender() -// : m_stopping(false) -// , m_thread(run_with_catch, "SleepyDiscordSender::thread_loop()", [this]{ thread_loop(); }) - : m_dispatcher(nullptr, 1) - , m_queue(m_dispatcher) - {} - ~SleepyDiscordSender(){ -// { -// std::lock_guard lg(m_lock); -// m_stopping = true; -// m_cv.notify_all(); -// } -// m_thread.join(); - } - -public: - static SleepyDiscordSender& instance(){ - static SleepyDiscordSender sender; - return sender; - } - - void send( - std::string embed, - std::string channels, - std::chrono::milliseconds delay, - std::string messages, - std::shared_ptr file - ){ -// std::lock_guard lg(m_lock); - m_queue.add_event( - delay > std::chrono::milliseconds(10000) ? std::chrono::milliseconds(0) : delay, - [embed = std::move(embed), channels = std::move(channels), messages = std::move(messages), file = std::move(file)]() mutable { - if (file == nullptr || file->filepath().empty()){ - sendMessage(&channels[0], &messages[0], &embed[0], nullptr); - }else{ - std::string filepath = file->filepath(); - sendMessage(&channels[0], &messages[0], &embed[0], &filepath[0]); - } - } - ); - sleepy_logger().log("Sending notification... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); -// m_queue.emplace_back(embed, channels, messages, std::move(file)); -// m_cv.notify_all(); - - } - -private: -#if 0 - void thread_loop(){ - while (true){ - SleepyDiscordRequest item; - { - std::unique_lock lg(m_lock); - if (m_stopping){ - break; - } - if (m_queue.empty()){ - m_cv.wait(lg); - continue; - } - - item = std::move(m_queue.front()); - m_queue.pop_front(); - } - - if (item.file != nullptr && !item.file->filepath().empty()){ - std::string filepath = item.file->filepath(); - sendMessage(&item.channels[0], &item.messages[0], &item.embed[0], &filepath[0]); - }else sendMessage(&item.channels[0], &item.messages[0], &item.embed[0], nullptr); - } - } -#endif - -private: -// bool m_stopping; -// std::mutex m_lock; -// std::condition_variable m_cv; -// std::deque m_queue; -// std::thread m_thread; - AsyncDispatcher m_dispatcher; - ScheduledTaskRunner m_queue; -}; - -class SleepyDiscordClient; -std::unique_ptr m_sleepy_client; - -std::mutex m_connect_lock; -std::mutex m_client_lock; - - - - - -struct CommandArgs{ - uint64_t id; - uint16_t button; - uint16_t hold_ticks; - uint8_t x; - uint8_t y; -}; - - -class SleepyDiscordClient{ -public: - bool m_connected = false; - -public: - void send( - std::string embed, - std::string channels, - std::chrono::milliseconds delay, - std::string messages, - std::shared_ptr file - ){ - if (m_sleepy_client != nullptr){ - if (file){ -// cout << "Sending: " << file->filepath().toStdString() << endl; - m_active_list.emplace(file->filepath(), file); - } - SleepyDiscordSender::instance().send(embed, channels, delay, messages, std::move(file)); - }else{ - sleepy_logger().log("SleepyDiscordClient::send(): Not connected.", COLOR_RED); - } - } - - void callback(int response, const char* message){ - if (m_sleepy_client == nullptr){ - return; - } - - std::string msg = (std::string)message + " (Callback: " + (std::string)enum_str_callback[response] + ")"; - Color color = response == SleepyResponse::Disconnected || response == SleepyResponse::Fault ? COLOR_RED : COLOR_PURPLE; - - switch (response){ - case SleepyResponse::Connected: m_connected = true; break; - case SleepyResponse::Disconnected: m_connected = false; break; - case SleepyResponse::RemoveFile:{ -#if 1 - auto iter = m_active_list.find(message); -// cout << "Removing: " << message << endl; -// cout << "m_active_list = " << m_active_list.size() << endl; - if (iter != m_active_list.end()){ - msg = "Marking sent file as done. (Callback: " + (std::string)enum_str_callback[response] + ")"; - m_active_list.erase(iter); - }else{ - msg = "Unknown sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; -// color = COLOR_RED; - } - m_active_list.erase(message); -#else - bool success = QFile(message).remove(); - if (success){ - msg = "Removed sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; - }else{ - msg = "Failed to remove sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; - color = COLOR_RED; - } -#endif - break; - } - } - - sleepy_logger().log(msg, color); - } - - void cmd_callback(SleepyRequest request, char* channel, uint64_t id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y){ - if (m_sleepy_client == nullptr){ - return; - } - - cout << "cmd_callback(): " << request << endl; - - std::string cmd = "Received command: " + (std::string)enum_str_command[request] + "."; - sleepy_logger().log(cmd, COLOR_PURPLE); - - switch (request){ - case SleepyRequest::Click: - run_Click(channel, id, hold_ticks, button); - break; - case SleepyRequest::DPad: - run_DPad(channel, id, hold_ticks, button); - break; - case SleepyRequest::SetLStick: - run_SetLStick(channel, id, hold_ticks, x, y); - return; - case SleepyRequest::SetRStick: - run_SetRStick(channel, id, hold_ticks, x, y); - return; - case SleepyRequest::ScreenshotJpg: - run_ScreenshotJpg(channel, id); - return; - case SleepyRequest::ScreenshotPng: - run_ScreenshotPng(channel, id); - return; - case SleepyRequest::Start: - run_start(channel, id); - break; - case SleepyRequest::Stop: - run_stop(channel, id); - break; - case SleepyRequest::Shutdown: - run_Shutdown(); - return; - case SleepyRequest::GetConnectedBots: - run_GetConnectedBots(channel); - return; - case SleepyRequest::ReloadSettings: - run_ReloadSettings(channel); - return; - case SleepyRequest::ResetCamera: - run_ResetCamera(channel, id); - return; - case SleepyRequest::ResetSerial: - run_ResetSerial(channel, id); - return; - } - } - - - -private: - void send_response(SleepyRequest request, char* channel, std::string message, std::shared_ptr file = nullptr){ - std::string filename = file == nullptr ? "" : file->filepath(); - if ((int)request <= 11){ - program_response(request, channel, &message[0], &filename[0]); - }else{ - send("", channel, std::chrono::milliseconds(0), &message[0], std::move(file)); - } - } - - void run_Click(char* channel, uint64_t id, uint16_t hold_ticks, uint16_t button){ - std::string message; - auto it = str_buttons.find(button); - if (it == str_buttons.end()){ - message = "Unrecognized button input"; - }else{ - message = Integration::press_button(id, button, hold_ticks); - } - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " clicked " + it->second + "."; - } - send_response(SleepyRequest::Click, channel, message); - } - void run_DPad(char* channel, uint64_t id, uint16_t hold_ticks, uint16_t button){ - std::string message; - auto it = str_dpad.find(button); - if (it == str_dpad.end()){ - message = "Unrecognized button input"; - }else{ - message = Integration::press_dpad(id, button, hold_ticks); - } - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " clicked " + it->second + "."; - } - send_response(SleepyRequest::DPad, channel, message); - } - void run_SetLStick(char* channel, uint64_t id, uint16_t hold_ticks, uint8_t x, uint8_t y){ - std::string message = Integration::press_left_joystick(id, x, y, hold_ticks); - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " moved the left joystick."; - } - send_response(SleepyRequest::SetLStick, channel, message); - } - void run_SetRStick(char* channel, uint64_t id, uint16_t hold_ticks, uint8_t x, uint8_t y){ - std::string message = Integration::press_right_joystick(id, x, y, hold_ticks); - if (message.empty()){ - message = "Console ID " + std::to_string(id) + " moved the right joystick."; - } - send_response(SleepyRequest::SetRStick, channel, message); - } - void run_ScreenshotPng(char* channel, uint64_t id){ - std::string filepath = "capture.png"; - std::string message = Integration::screenshot(id, filepath.c_str()); - if (!message.empty()){ - send_response(SleepyRequest::ScreenshotPng, channel, message); - return; - }else{ - message = "Captured image from console ID " + std::to_string(id) + "."; - } - - std::shared_ptr file(new PendingFileSend(filepath, true)); - send_response(SleepyRequest::ScreenshotPng, channel, message, std::move(file)); - } - void run_ScreenshotJpg(char* channel, uint64_t id){ - std::string filepath = "capture.jpg"; - std::string message = Integration::screenshot(id, filepath.c_str()); - if (!message.empty()){ - send_response(SleepyRequest::ScreenshotJpg, channel, message); - return; - }else{ - message = "Captured image from console ID " + std::to_string(id) + "."; - } - - std::shared_ptr file(new PendingFileSend(filepath, true)); - send_response(SleepyRequest::ScreenshotJpg, channel, message, std::move(file)); - } - void run_start(char* channel, uint64_t id){ - std::string message = Integration::start_program(id); - if (!message.empty()){ - send_response(SleepyRequest::Start, channel, message); - return; - }else{ - message = "Console ID " + std::to_string(id) + " started the program."; - } - send_response(SleepyRequest::Start, channel, message); - } - void run_stop(char* channel, uint64_t id){ - std::string message = Integration::stop_program(id); - if (!message.empty()){ - send_response(SleepyRequest::Stop, channel, message); - return; - }else{ - message = "Console ID " + std::to_string(id) + " stopped the program."; - } - send_response(SleepyRequest::Stop, channel, message); - } - void run_Shutdown(){ - program_response(SleepyRequest::Terminate); - m_sleepy_client.reset(); - - // TODO: Can't do this since it skips all the shutdown sequence from all the other threads. - exit(0); - } - void run_GetConnectedBots(char* channel){ - std::string message = Integration::status(); - send_response(SleepyRequest::GetConnectedBots, channel, message); - } - void run_ReloadSettings(char* channel){ - std::string message = initialize_sleepy_settings() - ? "Successfully reloaded Discord settings." - : "Failed to reload Discord settings."; - send_response(SleepyRequest::ReloadSettings, channel, message); - } - void run_ResetCamera(char* channel, uint64_t id){ - std::string message = Integration::reset_camera(id); - send_response(SleepyRequest::ResetCamera, channel, message.empty() ? "Camera was reset." : message); - } - void run_ResetSerial(char* channel, uint64_t id){ - std::string message = Integration::reset_serial(id); - send_response(SleepyRequest::ResetSerial, channel, message); - } - - std::map> m_active_list; -}; - - - - - - - -bool is_running(){ - std::lock_guard lg(m_connect_lock); - return m_sleepy_client != nullptr; -} - -bool is_connected(){ - std::lock_guard lg(m_connect_lock); - return m_sleepy_client != nullptr && m_sleepy_client->m_connected; -} - -void sleepy_connect(){ - std::lock_guard lg(m_connect_lock); - { -// std::lock_guard lg(m_client_lock); -// if (!PreloadSettings::instance().DEVELOPER_MODE){ -// return; -// } - if (m_sleepy_client != nullptr){ - sleepy_logger().log("sleepy_connect(): Already initialized!", COLOR_PURPLE); - return; - } - if (!initialize_sleepy_settings()){ - sleepy_logger().log("sleepy_connect(): initialize_sleepy_settings() failed.", COLOR_RED); - return; - } - sleepy_logger().log("Connecting...", COLOR_PURPLE); - } - client_connect(); - sleepy_logger().log("Finished Connecting...", COLOR_PURPLE); -} - -void sleepy_terminate(){ - std::lock_guard lg(m_client_lock); - program_response(SleepyRequest::Terminate); - if (m_sleepy_client != nullptr){ - m_sleepy_client.reset(); - } -} - -void sleepy_response(int response, char* message){ - //std::lock_guard lg(m_client_lock); - if (m_sleepy_client != nullptr){ - return m_sleepy_client->callback(response, message); - } -} - -void sleepy_cmd_response(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y){ - std::lock_guard lg(m_client_lock); - if (m_sleepy_client != nullptr){ - return m_sleepy_client->cmd_callback((SleepyRequest)request, channel, console_id, button, hold_ticks, x, y); - } -} - -void send_embed_sleepy( - bool should_ping, - const std::vector& tags, - const JsonObject& embed, - std::shared_ptr file -){ - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!settings.integration.enabled()){ - return; - } - - std::lock_guard lg(m_client_lock); - if (m_sleepy_client == nullptr){ - return; - } - - MessageBuilder builder(tags); - const DiscordIntegrationTable& channels = settings.integration.channels; - - std::vector> table = channels.copy_snapshot(); - for (size_t i = 0; i < table.size(); i++){ - const Integration::DiscordIntegrationChannel& channel = *table[i]; - if (((std::string)channel.tags_text).empty() || !channel.enabled){ - continue; - } - if (!builder.should_send(EventNotificationOption::parse_tags(channel.tags_text))){ - continue; - } - - sleepy_logger().log("send_message_sleepy(): Sending...", COLOR_PURPLE); - std::chrono::seconds delay(channel.delay); - m_sleepy_client->send( - embed.dump(), - channel.channel_id, - std::chrono::seconds(delay), - builder.build_message( - std::chrono::seconds(delay), - should_ping && channel.ping, - settings.message.user_id, - settings.message.message - ), - file == nullptr ? nullptr : file - ); - } -} - - -bool initialize_sleepy_settings(){ - // Must be called inside lock. -// std::lock_guard lg(m_client_lock); - DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; - if (!check_if_empty(settings)){ - return false; - } - - bool suffix = settings.integration.use_suffix; - std::string param_string; - param_string += StringTools::replace(settings.integration.token, " ", "") + "|"; - param_string += (std::string)settings.integration.command_prefix + "|"; - param_string += StringTools::replace(settings.integration.owner, " ", "") + "|"; - param_string += (std::string)settings.integration.game_status + "|"; - param_string += StringTools::replace(settings.integration.hello_message, "@", "") + "|"; - param_string += PROGRAM_VERSION + "|"; - param_string += PROJECT_SOURCE_URL; - - std::string sudo = StringTools::replace(settings.integration.sudo, " ", ""); - -// std::string w_channels = StringTools::replace(settings.integration.channels_whitelist.get(), " ", ""); - std::string w_channels; - for (const std::string& channel_id : settings.integration.channels.command_channels()){ - if (!w_channels.empty()){ - w_channels += ","; - } - w_channels += channel_id; - } - - m_sleepy_client = std::unique_ptr(new SleepyDiscordClient()); - apply_settings(sleepy_response, sleepy_cmd_response, &w_channels[0], &sudo[0], ¶m_string[0], suffix); - return true; -} - -bool check_if_empty(const DiscordSettingsOption& settings){ - - if (!settings.integration.enabled()){ - return false; - } - if (((std::string)settings.integration.token).empty()){ - return false; - }else if (((std::string)settings.integration.token).find(",") != std::string::npos){ - sleepy_logger().log("\"Token\" must only contain one token. Stopping...", COLOR_RED); - return false; - }else if (((std::string)settings.integration.owner).find(",") != std::string::npos){ - sleepy_logger().log("\"Owner\" must only contain one Discord ID (yours). Stopping...", COLOR_RED); - return false; - }else if (((std::string)settings.integration.command_prefix).empty()){ - sleepy_logger().log("Please enter a Discord command prefix. Stopping...", COLOR_RED); - return false; - } - return true; -} - - - - - -} -} -} -#endif + +#ifdef PA_SLEEPY + +#include +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/StringTools.h" +#include "Common/Cpp/PanicDump.h" +#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "IntegrationsAPI.h" +#include "SleepyDiscordRunner.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Integration{ +namespace SleepyDiscordRunner{ + +using namespace SleepyDiscord; +const char* enum_str_callback[] = { + "Fault", + "API", + "Disconnected", + "Connected", + "Settings Initialized", + "Settings Updated", + "Commands Initialized", + "Callbacks Set", + "Invalid Command", + "Terminating", + "Remove File", +}; + +const char* enum_str_command[] = { + "Click", + "Click DPad", + + "Left Stick", + "Right Stick", + + "Screenshot JPG", + "Screenshot PNG", + "Start", + "Stop", + "Shutdown", + "Get Connected Bots", + "Reload Settings", + "Reset Camera", + "Reset Serial", + "Terminate", + + "Hi", + "Ping", + "About", + "Help", +}; + +const char* enum_str_state[] = { + "STOPPED", + "RUNNING", + "FINISHED", + "STOPPING", +}; + +std::unordered_map str_buttons = { + { 1, "Y" }, + { 2, "B" }, + { 4, "A" }, + { 8, "X" }, + { 16, "L" }, + { 32, "R" }, + { 64, "ZL" }, + { 128, "ZR" }, + { 256, "MINUS" }, + { 512, "PLUS" }, + { 1024, "LStick" }, + { 2048, "RStick" }, + { 4096, "HOME" }, + { 8192, "Capture" }, +}; + +std::unordered_map str_dpad = { + { 0, "DUp" }, + { 2, "DRight" }, + { 4, "DDown" }, + { 6, "DLeft" }, +}; + + +Logger& sleepy_logger(){ + static TaggedLogger logger(global_logger_raw(), "SleepyDiscord"); + return logger; +} + + +struct SleepyDiscordRequest{ + SleepyDiscordRequest() = default; + SleepyDiscordRequest(std::string embed, std::string channels, std::string messages, std::shared_ptr file) : + embed(std::move(embed)), + channels(std::move(channels)), + messages(std::move(messages)), + file(std::move(file)) {} + + std::string embed; + std::string channels; + std::string messages; + std::shared_ptr file; +}; + +class SleepyDiscordSender{ +private: + SleepyDiscordSender() +// : m_stopping(false) +// , m_thread(run_with_catch, "SleepyDiscordSender::thread_loop()", [this]{ thread_loop(); }) + : m_dispatcher(nullptr, 1) + , m_queue(m_dispatcher) + {} + ~SleepyDiscordSender(){ +// { +// std::lock_guard lg(m_lock); +// m_stopping = true; +// m_cv.notify_all(); +// } +// m_thread.join(); + } + +public: + static SleepyDiscordSender& instance(){ + static SleepyDiscordSender sender; + return sender; + } + + void send( + std::string embed, + std::string channels, + std::chrono::milliseconds delay, + std::string messages, + std::shared_ptr file + ){ +// std::lock_guard lg(m_lock); + m_queue.add_event( + delay > std::chrono::milliseconds(10000) ? std::chrono::milliseconds(0) : delay, + [embed = std::move(embed), channels = std::move(channels), messages = std::move(messages), file = std::move(file)]() mutable { + if (file == nullptr || file->filepath().empty()){ + sendMessage(&channels[0], &messages[0], &embed[0], nullptr); + }else{ + std::string filepath = file->filepath(); + sendMessage(&channels[0], &messages[0], &embed[0], &filepath[0]); + } + } + ); + sleepy_logger().log("Sending notification... (queue = " + tostr_u_commas(m_queue.size()) + ")", COLOR_PURPLE); +// m_queue.emplace_back(embed, channels, messages, std::move(file)); +// m_cv.notify_all(); + + } + +private: +#if 0 + void thread_loop(){ + while (true){ + SleepyDiscordRequest item; + { + std::unique_lock lg(m_lock); + if (m_stopping){ + break; + } + if (m_queue.empty()){ + m_cv.wait(lg); + continue; + } + + item = std::move(m_queue.front()); + m_queue.pop_front(); + } + + if (item.file != nullptr && !item.file->filepath().empty()){ + std::string filepath = item.file->filepath(); + sendMessage(&item.channels[0], &item.messages[0], &item.embed[0], &filepath[0]); + }else sendMessage(&item.channels[0], &item.messages[0], &item.embed[0], nullptr); + } + } +#endif + +private: +// bool m_stopping; +// std::mutex m_lock; +// std::condition_variable m_cv; +// std::deque m_queue; +// std::thread m_thread; + AsyncDispatcher m_dispatcher; + ScheduledTaskRunner m_queue; +}; + +class SleepyDiscordClient; +std::unique_ptr m_sleepy_client; + +std::mutex m_connect_lock; +std::mutex m_client_lock; + + + + + +struct CommandArgs{ + uint64_t id; + uint16_t button; + uint16_t hold_ticks; + uint8_t x; + uint8_t y; +}; + + +class SleepyDiscordClient{ +public: + bool m_connected = false; + +public: + void send( + std::string embed, + std::string channels, + std::chrono::milliseconds delay, + std::string messages, + std::shared_ptr file + ){ + if (m_sleepy_client != nullptr){ + if (file){ +// cout << "Sending: " << file->filepath().toStdString() << endl; + m_active_list.emplace(file->filepath(), file); + } + SleepyDiscordSender::instance().send(embed, channels, delay, messages, std::move(file)); + }else{ + sleepy_logger().log("SleepyDiscordClient::send(): Not connected.", COLOR_RED); + } + } + + void callback(int response, const char* message){ + if (m_sleepy_client == nullptr){ + return; + } + + std::string msg = (std::string)message + " (Callback: " + (std::string)enum_str_callback[response] + ")"; + Color color = response == SleepyResponse::Disconnected || response == SleepyResponse::Fault ? COLOR_RED : COLOR_PURPLE; + + switch (response){ + case SleepyResponse::Connected: m_connected = true; break; + case SleepyResponse::Disconnected: m_connected = false; break; + case SleepyResponse::RemoveFile:{ +#if 1 + auto iter = m_active_list.find(message); +// cout << "Removing: " << message << endl; +// cout << "m_active_list = " << m_active_list.size() << endl; + if (iter != m_active_list.end()){ + msg = "Marking sent file as done. (Callback: " + (std::string)enum_str_callback[response] + ")"; + m_active_list.erase(iter); + }else{ + msg = "Unknown sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; +// color = COLOR_RED; + } + m_active_list.erase(message); +#else + bool success = QFile(message).remove(); + if (success){ + msg = "Removed sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; + }else{ + msg = "Failed to remove sent file. (Callback: " + (std::string)enum_str_callback[response] + ")"; + color = COLOR_RED; + } +#endif + break; + } + } + + sleepy_logger().log(msg, color); + } + + void cmd_callback(SleepyRequest request, char* channel, uint64_t id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y){ + if (m_sleepy_client == nullptr){ + return; + } + + cout << "cmd_callback(): " << request << endl; + + std::string cmd = "Received command: " + (std::string)enum_str_command[request] + "."; + sleepy_logger().log(cmd, COLOR_PURPLE); + + switch (request){ + case SleepyRequest::Click: + run_Click(channel, id, hold_ticks, button); + break; + case SleepyRequest::DPad: + run_DPad(channel, id, hold_ticks, button); + break; + case SleepyRequest::SetLStick: + run_SetLStick(channel, id, hold_ticks, x, y); + return; + case SleepyRequest::SetRStick: + run_SetRStick(channel, id, hold_ticks, x, y); + return; + case SleepyRequest::ScreenshotJpg: + run_ScreenshotJpg(channel, id); + return; + case SleepyRequest::ScreenshotPng: + run_ScreenshotPng(channel, id); + return; + case SleepyRequest::Start: + run_start(channel, id); + break; + case SleepyRequest::Stop: + run_stop(channel, id); + break; + case SleepyRequest::Shutdown: + run_Shutdown(); + return; + case SleepyRequest::GetConnectedBots: + run_GetConnectedBots(channel); + return; + case SleepyRequest::ReloadSettings: + run_ReloadSettings(channel); + return; + case SleepyRequest::ResetCamera: + run_ResetCamera(channel, id); + return; + case SleepyRequest::ResetSerial: + run_ResetSerial(channel, id); + return; + } + } + + + +private: + void send_response(SleepyRequest request, char* channel, std::string message, std::shared_ptr file = nullptr){ + std::string filename = file == nullptr ? "" : file->filepath(); + if ((int)request <= 11){ + program_response(request, channel, &message[0], &filename[0]); + }else{ + send("", channel, std::chrono::milliseconds(0), &message[0], std::move(file)); + } + } + + void run_Click(char* channel, uint64_t id, uint16_t hold_ticks, uint16_t button){ + std::string message; + auto it = str_buttons.find(button); + if (it == str_buttons.end()){ + message = "Unrecognized button input"; + }else{ + message = Integration::press_button(id, button, hold_ticks); + } + if (message.empty()){ + message = "Console ID " + std::to_string(id) + " clicked " + it->second + "."; + } + send_response(SleepyRequest::Click, channel, message); + } + void run_DPad(char* channel, uint64_t id, uint16_t hold_ticks, uint16_t button){ + std::string message; + auto it = str_dpad.find(button); + if (it == str_dpad.end()){ + message = "Unrecognized button input"; + }else{ + message = Integration::press_dpad(id, button, hold_ticks); + } + if (message.empty()){ + message = "Console ID " + std::to_string(id) + " clicked " + it->second + "."; + } + send_response(SleepyRequest::DPad, channel, message); + } + void run_SetLStick(char* channel, uint64_t id, uint16_t hold_ticks, uint8_t x, uint8_t y){ + std::string message = Integration::press_left_joystick(id, x, y, hold_ticks); + if (message.empty()){ + message = "Console ID " + std::to_string(id) + " moved the left joystick."; + } + send_response(SleepyRequest::SetLStick, channel, message); + } + void run_SetRStick(char* channel, uint64_t id, uint16_t hold_ticks, uint8_t x, uint8_t y){ + std::string message = Integration::press_right_joystick(id, x, y, hold_ticks); + if (message.empty()){ + message = "Console ID " + std::to_string(id) + " moved the right joystick."; + } + send_response(SleepyRequest::SetRStick, channel, message); + } + void run_ScreenshotPng(char* channel, uint64_t id){ + std::string filepath = "capture.png"; + std::string message = Integration::screenshot(id, filepath.c_str()); + if (!message.empty()){ + send_response(SleepyRequest::ScreenshotPng, channel, message); + return; + }else{ + message = "Captured image from console ID " + std::to_string(id) + "."; + } + + std::shared_ptr file(new PendingFileSend(filepath, true)); + send_response(SleepyRequest::ScreenshotPng, channel, message, std::move(file)); + } + void run_ScreenshotJpg(char* channel, uint64_t id){ + std::string filepath = "capture.jpg"; + std::string message = Integration::screenshot(id, filepath.c_str()); + if (!message.empty()){ + send_response(SleepyRequest::ScreenshotJpg, channel, message); + return; + }else{ + message = "Captured image from console ID " + std::to_string(id) + "."; + } + + std::shared_ptr file(new PendingFileSend(filepath, true)); + send_response(SleepyRequest::ScreenshotJpg, channel, message, std::move(file)); + } + void run_start(char* channel, uint64_t id){ + std::string message = Integration::start_program(id); + if (!message.empty()){ + send_response(SleepyRequest::Start, channel, message); + return; + }else{ + message = "Console ID " + std::to_string(id) + " started the program."; + } + send_response(SleepyRequest::Start, channel, message); + } + void run_stop(char* channel, uint64_t id){ + std::string message = Integration::stop_program(id); + if (!message.empty()){ + send_response(SleepyRequest::Stop, channel, message); + return; + }else{ + message = "Console ID " + std::to_string(id) + " stopped the program."; + } + send_response(SleepyRequest::Stop, channel, message); + } + void run_Shutdown(){ + program_response(SleepyRequest::Terminate); + m_sleepy_client.reset(); + + // TODO: Can't do this since it skips all the shutdown sequence from all the other threads. + exit(0); + } + void run_GetConnectedBots(char* channel){ + std::string message = Integration::status(); + send_response(SleepyRequest::GetConnectedBots, channel, message); + } + void run_ReloadSettings(char* channel){ + std::string message = initialize_sleepy_settings() + ? "Successfully reloaded Discord settings." + : "Failed to reload Discord settings."; + send_response(SleepyRequest::ReloadSettings, channel, message); + } + void run_ResetCamera(char* channel, uint64_t id){ + std::string message = Integration::reset_camera(id); + send_response(SleepyRequest::ResetCamera, channel, message.empty() ? "Camera was reset." : message); + } + void run_ResetSerial(char* channel, uint64_t id){ + std::string message = Integration::reset_serial(id); + send_response(SleepyRequest::ResetSerial, channel, message); + } + + std::map> m_active_list; +}; + + + + + + + +bool is_running(){ + std::lock_guard lg(m_connect_lock); + return m_sleepy_client != nullptr; +} + +bool is_connected(){ + std::lock_guard lg(m_connect_lock); + return m_sleepy_client != nullptr && m_sleepy_client->m_connected; +} + +void sleepy_connect(){ + std::lock_guard lg(m_connect_lock); + { +// std::lock_guard lg(m_client_lock); +// if (!PreloadSettings::instance().DEVELOPER_MODE){ +// return; +// } + if (m_sleepy_client != nullptr){ + sleepy_logger().log("sleepy_connect(): Already initialized!", COLOR_PURPLE); + return; + } + if (!initialize_sleepy_settings()){ + sleepy_logger().log("sleepy_connect(): initialize_sleepy_settings() failed.", COLOR_RED); + return; + } + sleepy_logger().log("Connecting...", COLOR_PURPLE); + } + client_connect(); + sleepy_logger().log("Finished Connecting...", COLOR_PURPLE); +} + +void sleepy_terminate(){ + std::lock_guard lg(m_client_lock); + program_response(SleepyRequest::Terminate); + if (m_sleepy_client != nullptr){ + m_sleepy_client.reset(); + } +} + +void sleepy_response(int response, char* message){ + //std::lock_guard lg(m_client_lock); + if (m_sleepy_client != nullptr){ + return m_sleepy_client->callback(response, message); + } +} + +void sleepy_cmd_response(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y){ + std::lock_guard lg(m_client_lock); + if (m_sleepy_client != nullptr){ + return m_sleepy_client->cmd_callback((SleepyRequest)request, channel, console_id, button, hold_ticks, x, y); + } +} + +void send_embed_sleepy( + bool should_ping, + const std::vector& tags, + const JsonObject& embed, + std::shared_ptr file +){ + DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; + if (!settings.integration.enabled()){ + return; + } + + std::lock_guard lg(m_client_lock); + if (m_sleepy_client == nullptr){ + return; + } + + MessageBuilder builder(tags); + const DiscordIntegrationTable& channels = settings.integration.channels; + + std::vector> table = channels.copy_snapshot(); + for (size_t i = 0; i < table.size(); i++){ + const Integration::DiscordIntegrationChannel& channel = *table[i]; + if (((std::string)channel.tags_text).empty() || !channel.enabled){ + continue; + } + if (!builder.should_send(EventNotificationOption::parse_tags(channel.tags_text))){ + continue; + } + + sleepy_logger().log("send_message_sleepy(): Sending...", COLOR_PURPLE); + std::chrono::seconds delay(channel.delay); + m_sleepy_client->send( + embed.dump(), + channel.channel_id, + std::chrono::seconds(delay), + builder.build_message( + std::chrono::seconds(delay), + should_ping && channel.ping, + settings.message.user_id, + settings.message.message + ), + file == nullptr ? nullptr : file + ); + } +} + + +bool initialize_sleepy_settings(){ + // Must be called inside lock. +// std::lock_guard lg(m_client_lock); + DiscordSettingsOption& settings = GlobalSettings::instance().DISCORD; + if (!check_if_empty(settings)){ + return false; + } + + bool suffix = settings.integration.use_suffix; + std::string param_string; + param_string += StringTools::replace(settings.integration.token, " ", "") + "|"; + param_string += (std::string)settings.integration.command_prefix + "|"; + param_string += StringTools::replace(settings.integration.owner, " ", "") + "|"; + param_string += (std::string)settings.integration.game_status + "|"; + param_string += StringTools::replace(settings.integration.hello_message, "@", "") + "|"; + param_string += PROGRAM_VERSION + "|"; + param_string += PROJECT_SOURCE_URL; + + std::string sudo = StringTools::replace(settings.integration.sudo, " ", ""); + +// std::string w_channels = StringTools::replace(settings.integration.channels_whitelist.get(), " ", ""); + std::string w_channels; + for (const std::string& channel_id : settings.integration.channels.command_channels()){ + if (!w_channels.empty()){ + w_channels += ","; + } + w_channels += channel_id; + } + + m_sleepy_client = std::unique_ptr(new SleepyDiscordClient()); + apply_settings(sleepy_response, sleepy_cmd_response, &w_channels[0], &sudo[0], ¶m_string[0], suffix); + return true; +} + +bool check_if_empty(const DiscordSettingsOption& settings){ + + if (!settings.integration.enabled()){ + return false; + } + if (((std::string)settings.integration.token).empty()){ + return false; + }else if (((std::string)settings.integration.token).find(",") != std::string::npos){ + sleepy_logger().log("\"Token\" must only contain one token. Stopping...", COLOR_RED); + return false; + }else if (((std::string)settings.integration.owner).find(",") != std::string::npos){ + sleepy_logger().log("\"Owner\" must only contain one Discord ID (yours). Stopping...", COLOR_RED); + return false; + }else if (((std::string)settings.integration.command_prefix).empty()){ + sleepy_logger().log("Please enter a Discord command prefix. Stopping...", COLOR_RED); + return false; + } + return true; +} + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h b/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h index 4c85fd79e0..2497d28200 100644 --- a/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h +++ b/SerialPrograms/Source/Integrations/SleepyDiscordRunner.h @@ -1,105 +1,105 @@ -#ifndef PokemonAutomation_SleepyPA_H -#define PokemonAutomation_SleepyPA_H - -#include -#include "CommonFramework/PersistentSettings.h" -#include "CommonFramework/Options/ScreenshotFormatOption.h" -#include "CommonFramework/Notifications/MessageAttachment.h" -#include "Integrations/DiscordSettingsOption.h" - -#ifdef SLEEPY_STATIC - #define SLEEPY_EXPORT -#else - -#ifdef _WIN32 -#ifdef _WINDLL - #define SLEEPY_EXPORT __declspec(dllexport) -#else - #define SLEEPY_EXPORT __declspec(dllimport) -#endif - -#else - #define SLEEPY_EXPORT __attribute__((visibility("default"))) -#endif -#endif - -#ifdef __cplusplus -extern "C" { -#endif - -namespace SleepyDiscord{ - typedef void (*SleepyCallback)(int response, char* message); - typedef void (*SleepyCommandCallback)(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y); - SLEEPY_EXPORT void client_connect(); - SLEEPY_EXPORT void client_disconnect(); - SLEEPY_EXPORT void apply_settings(SleepyCallback callback, SleepyCommandCallback cmd_callback, char* w_channels, char* sudo, char* params, bool suffix); - SLEEPY_EXPORT void program_response(int response, char* channel = nullptr, char* message = nullptr, char* filepath = nullptr); - SLEEPY_EXPORT void sendMessage(char* channels, char* messages = nullptr, char* json = nullptr, char* filePath = nullptr); - void client_run(); - -enum SleepyResponse{ - Fault = 0, - API = 1, - Disconnected = 2, - Connected = 3, - SettingsInitialized = 4, - SettingsUpdated = 5, - CommandsInitialized = 6, - CallbacksSet = 7, - InvalidCommand = 8, - Terminating = 9, - RemoveFile = 10, -}; - -enum SleepyRequest{ - Click = 0, - DPad = 1, - - SetLStick = 2, - SetRStick = 3, - - ScreenshotJpg = 4, - ScreenshotPng = 5, - Start = 6, - Stop = 7, - Shutdown = 8, - GetConnectedBots = 9, - ReloadSettings = 10, - ResetCamera = 11, - ResetSerial = 12, - Terminate = 13, - - Hi = 14, - Ping = 15, - About = 16, - Help = 17, -}; -} - -#ifdef __cplusplus -} - -namespace PokemonAutomation{ -namespace Integration{ -namespace SleepyDiscordRunner{ - - bool is_running(); - bool is_connected(); - void send_embed_sleepy( - bool should_ping, - const std::vector& tags, - const JsonObject& embed, - std::shared_ptr file - ); - void sleepy_response(int response, char* message); - void sleepy_cmd_response(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y); - void sleepy_connect(); - void sleepy_terminate(); - bool initialize_sleepy_settings(); - bool check_if_empty(const DiscordSettingsOption& settings); -} -} -} - -#endif -#endif +#ifndef PokemonAutomation_SleepyPA_H +#define PokemonAutomation_SleepyPA_H + +#include +#include "CommonFramework/PersistentSettings.h" +#include "CommonFramework/Options/ScreenshotFormatOption.h" +#include "CommonFramework/Notifications/MessageAttachment.h" +#include "Integrations/DiscordSettingsOption.h" + +#ifdef SLEEPY_STATIC + #define SLEEPY_EXPORT +#else + +#ifdef _WIN32 +#ifdef _WINDLL + #define SLEEPY_EXPORT __declspec(dllexport) +#else + #define SLEEPY_EXPORT __declspec(dllimport) +#endif + +#else + #define SLEEPY_EXPORT __attribute__((visibility("default"))) +#endif +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +namespace SleepyDiscord{ + typedef void (*SleepyCallback)(int response, char* message); + typedef void (*SleepyCommandCallback)(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y); + SLEEPY_EXPORT void client_connect(); + SLEEPY_EXPORT void client_disconnect(); + SLEEPY_EXPORT void apply_settings(SleepyCallback callback, SleepyCommandCallback cmd_callback, char* w_channels, char* sudo, char* params, bool suffix); + SLEEPY_EXPORT void program_response(int response, char* channel = nullptr, char* message = nullptr, char* filepath = nullptr); + SLEEPY_EXPORT void sendMessage(char* channels, char* messages = nullptr, char* json = nullptr, char* filePath = nullptr); + void client_run(); + +enum SleepyResponse{ + Fault = 0, + API = 1, + Disconnected = 2, + Connected = 3, + SettingsInitialized = 4, + SettingsUpdated = 5, + CommandsInitialized = 6, + CallbacksSet = 7, + InvalidCommand = 8, + Terminating = 9, + RemoveFile = 10, +}; + +enum SleepyRequest{ + Click = 0, + DPad = 1, + + SetLStick = 2, + SetRStick = 3, + + ScreenshotJpg = 4, + ScreenshotPng = 5, + Start = 6, + Stop = 7, + Shutdown = 8, + GetConnectedBots = 9, + ReloadSettings = 10, + ResetCamera = 11, + ResetSerial = 12, + Terminate = 13, + + Hi = 14, + Ping = 15, + About = 16, + Help = 17, +}; +} + +#ifdef __cplusplus +} + +namespace PokemonAutomation{ +namespace Integration{ +namespace SleepyDiscordRunner{ + + bool is_running(); + bool is_connected(); + void send_embed_sleepy( + bool should_ping, + const std::vector& tags, + const JsonObject& embed, + std::shared_ptr file + ); + void sleepy_response(int response, char* message); + void sleepy_cmd_response(int request, char* channel, uint64_t console_id, uint16_t button, uint16_t hold_ticks, uint8_t x, uint8_t y); + void sleepy_connect(); + void sleepy_terminate(); + bool initialize_sleepy_settings(); + bool check_if_empty(const DiscordSettingsOption& settings); +} +} +} + +#endif +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp index 03e44fa80f..01038adf01 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.cpp @@ -1,52 +1,52 @@ -/* ABS FFT - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_AbsFFT.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -void fft_abs_Default(int k, float* abs, float* real); -void fft_abs_x86_SSE41(int k, float* abs, float* real); -void fft_abs_x86_AVX2(int k, float* abs, float* real); - - -void fft_abs(int k, float* abs, float* real){ - if (k <= 0){ - throw "FFT length must be at least 2^1."; - } - if ((size_t)abs & 63){ - throw "abs must be aligned to 64 bytes."; - } - if ((size_t)real & 63){ - throw "real must be aligned to 64 bytes."; - } - -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - fft_abs_x86_AVX2(k, abs, real); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - fft_abs_x86_SSE41(k, abs, real); - return; - } -#endif - fft_abs_Default(k, abs, real); -} - - - -} -} -} +/* ABS FFT + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_AbsFFT.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +void fft_abs_Default(int k, float* abs, float* real); +void fft_abs_x86_SSE41(int k, float* abs, float* real); +void fft_abs_x86_AVX2(int k, float* abs, float* real); + + +void fft_abs(int k, float* abs, float* real){ + if (k <= 0){ + throw "FFT length must be at least 2^1."; + } + if ((size_t)abs & 63){ + throw "abs must be aligned to 64 bytes."; + } + if ((size_t)real & 63){ + throw "real must be aligned to 64 bytes."; + } + +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + fft_abs_x86_AVX2(k, abs, real); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + fft_abs_x86_SSE41(k, abs, real); + return; + } +#endif + fft_abs_Default(k, abs, real); +} + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.h index 2b50954f93..463d7e766d 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT.h @@ -1,33 +1,33 @@ -/* ABS FFT - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_H -#define PokemonAutomation_Kernels_AbsFFT_H - - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - -// -// Compute the FFT of "real" and store the absolute values of the -// lower half into "abs". -// -// - 2^k is the transform length. -// - "real" is the input time domain. It has length 2^k. -// - "abs" is the absolute values of the frequency domain. It has length 2^(k-1). -// - Both "real" and "abs" must be aligned to 64 bytes. -// -// This operation is destructive on "real" even though it is an input. -// -void fft_abs(int k, float* abs, float* real); - - - -} -} -} -#endif +/* ABS FFT + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_H +#define PokemonAutomation_Kernels_AbsFFT_H + + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + +// +// Compute the FFT of "real" and store the absolute values of the +// lower half into "abs". +// +// - 2^k is the transform length. +// - "real" is the input time domain. It has length 2^k. +// - "abs" is the absolute values of the frequency domain. It has length 2^(k-1). +// - Both "real" and "abs" must be aligned to 64 bytes. +// +// This operation is destructive on "real" even though it is an input. +// +void fft_abs(int k, float* abs, float* real); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h index 7179e72336..8d5eb1c06d 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch.h @@ -1,78 +1,78 @@ -/* ABS FFT Arch - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_H -#define PokemonAutomation_Kernels_AbsFFT_Arch_H - -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - -const float TW8_1 = 0.70710678118654752440f; - -#if 0 -PA_FORCE_INLINE void cmul_pp( - float& Or, float& Oi, - float Xr, float Xi, - float Wr, float Wi -){ - Or = Xr*Wr - Xi*Wi; - Oi = Xr*Wi + Xi*Wr; -} - -struct scomplex{ - float r; - float i; - - friend PA_FORCE_INLINE scomplex operator+(const scomplex& x, const scomplex& y){ - return scomplex{x.r + y.r, x.i + y.i}; - } - friend PA_FORCE_INLINE scomplex operator-(const scomplex& x, const scomplex& y){ - return scomplex{x.r - y.r, x.i - y.i}; - } - friend PA_FORCE_INLINE scomplex operator*(const scomplex& x, const scomplex& y){ - return scomplex{x.r*y.r - x.i*y.i, x.r*y.i + x.i*y.r}; - } - - scomplex mul_by_i() const{ - return scomplex{-i, r}; - } -}; -#endif - - -template -struct vcomplex{ - using vtype = typename Context::vtype; - - vtype r; - vtype i; - - // Suppress compiler memset/memcpy optimization. - PA_FORCE_INLINE vcomplex() = default; - PA_FORCE_INLINE vcomplex(const vcomplex& x) - : r(x.r) - , i(x.i) - {} - PA_FORCE_INLINE void operator=(const vcomplex& x){ - r = x.r; - i = x.i; - } - - float real(size_t index) const{ return ((const float*)&r)[index]; } - float& real(size_t index) { return (( float*)&r)[index]; } - float imag(size_t index) const{ return ((const float*)&i)[index]; } - float& imag(size_t index) { return (( float*)&i)[index]; } -}; - - -} -} -} -#endif +/* ABS FFT Arch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_H +#define PokemonAutomation_Kernels_AbsFFT_Arch_H + +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + +const float TW8_1 = 0.70710678118654752440f; + +#if 0 +PA_FORCE_INLINE void cmul_pp( + float& Or, float& Oi, + float Xr, float Xi, + float Wr, float Wi +){ + Or = Xr*Wr - Xi*Wi; + Oi = Xr*Wi + Xi*Wr; +} + +struct scomplex{ + float r; + float i; + + friend PA_FORCE_INLINE scomplex operator+(const scomplex& x, const scomplex& y){ + return scomplex{x.r + y.r, x.i + y.i}; + } + friend PA_FORCE_INLINE scomplex operator-(const scomplex& x, const scomplex& y){ + return scomplex{x.r - y.r, x.i - y.i}; + } + friend PA_FORCE_INLINE scomplex operator*(const scomplex& x, const scomplex& y){ + return scomplex{x.r*y.r - x.i*y.i, x.r*y.i + x.i*y.r}; + } + + scomplex mul_by_i() const{ + return scomplex{-i, r}; + } +}; +#endif + + +template +struct vcomplex{ + using vtype = typename Context::vtype; + + vtype r; + vtype i; + + // Suppress compiler memset/memcpy optimization. + PA_FORCE_INLINE vcomplex() = default; + PA_FORCE_INLINE vcomplex(const vcomplex& x) + : r(x.r) + , i(x.i) + {} + PA_FORCE_INLINE void operator=(const vcomplex& x){ + r = x.r; + i = x.i; + } + + float real(size_t index) const{ return ((const float*)&r)[index]; } + float& real(size_t index) { return (( float*)&r)[index]; } + float imag(size_t index) const{ return ((const float*)&i)[index]; } + float& imag(size_t index) { return (( float*)&i)[index]; } +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_Default.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_Default.h index 1ae3867e45..b03688fc4e 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_Default.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_Default.h @@ -1,78 +1,78 @@ -/* ABS FFT Arch (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_Default_H -#define PokemonAutomation_Kernels_AbsFFT_Arch_Default_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ -struct Context_Default{ - - -using vtype = float; -static const int VECTOR_K = 0; -static const size_t VECTOR_LENGTH = (size_t)1 << VECTOR_K; - -static const int BASE_COMPLEX_TRANSFORM_K = 4; -static const size_t MIN_TABLE_WIDTH = 1; - - -static PA_FORCE_INLINE vtype vset1(float x){ - return x; -} -static PA_FORCE_INLINE vtype vneg(vtype x){ - return -x; -} -static PA_FORCE_INLINE vtype vadd(vtype x, vtype y){ - return x + y; -} -static PA_FORCE_INLINE vtype vsub(vtype x, vtype y){ - return x - y; -} -static PA_FORCE_INLINE vtype vmul(vtype x, vtype y){ - return x * y; -} -static PA_FORCE_INLINE void cmul_pp( - vtype& Xr, vtype& Xi, - vtype Wr, vtype Wi -){ - vtype t0 = Xi * Wi; - vtype t1 = Xr * Wi; - Xr = (Xr * Wr) - t0; - Xi = (Xi * Wr) + t1; -} -static PA_FORCE_INLINE vtype abs(vtype r, vtype i){ - return std::sqrt(r*r + i*i); -} -static PA_FORCE_INLINE void swap_odd(vtype& L, vtype& H){ -} - -static PA_FORCE_INLINE void interleave_v0( - vtype& out0, vtype& out1, - vtype lo, vtype hi -){ - out0 = lo; - out1 = hi; -} -static PA_FORCE_INLINE void interleave_v1( - vtype& out0, vtype& out1, - vtype lo, vtype hi -){ - out0 = lo; - out1 = hi; -} - - - -}; -} -} -} -#endif +/* ABS FFT Arch (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_Default_H +#define PokemonAutomation_Kernels_AbsFFT_Arch_Default_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ +struct Context_Default{ + + +using vtype = float; +static const int VECTOR_K = 0; +static const size_t VECTOR_LENGTH = (size_t)1 << VECTOR_K; + +static const int BASE_COMPLEX_TRANSFORM_K = 4; +static const size_t MIN_TABLE_WIDTH = 1; + + +static PA_FORCE_INLINE vtype vset1(float x){ + return x; +} +static PA_FORCE_INLINE vtype vneg(vtype x){ + return -x; +} +static PA_FORCE_INLINE vtype vadd(vtype x, vtype y){ + return x + y; +} +static PA_FORCE_INLINE vtype vsub(vtype x, vtype y){ + return x - y; +} +static PA_FORCE_INLINE vtype vmul(vtype x, vtype y){ + return x * y; +} +static PA_FORCE_INLINE void cmul_pp( + vtype& Xr, vtype& Xi, + vtype Wr, vtype Wi +){ + vtype t0 = Xi * Wi; + vtype t1 = Xr * Wi; + Xr = (Xr * Wr) - t0; + Xi = (Xi * Wr) + t1; +} +static PA_FORCE_INLINE vtype abs(vtype r, vtype i){ + return std::sqrt(r*r + i*i); +} +static PA_FORCE_INLINE void swap_odd(vtype& L, vtype& H){ +} + +static PA_FORCE_INLINE void interleave_v0( + vtype& out0, vtype& out1, + vtype lo, vtype hi +){ + out0 = lo; + out1 = hi; +} +static PA_FORCE_INLINE void interleave_v1( + vtype& out0, vtype& out1, + vtype lo, vtype hi +){ + out0 = lo; + out1 = hi; +} + + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_AVX2.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_AVX2.h index 1412b1afa3..8474622cc6 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_AVX2.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_AVX2.h @@ -1,89 +1,89 @@ -/* ABS FFT Arch (AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_x86_AVX2_H -#define PokemonAutomation_Kernels_AbsFFT_Arch_x86_AVX2_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ -struct Context_x86_AVX2{ - - -using vtype = __m256; -static const int VECTOR_K = 3; -static const size_t VECTOR_LENGTH = (size_t)1 << VECTOR_K; - -static const int BASE_COMPLEX_TRANSFORM_K = 6; -static const size_t MIN_TABLE_WIDTH = 4; - - -static PA_FORCE_INLINE vtype vset1(float x){ - return _mm256_set1_ps(x); -} -static PA_FORCE_INLINE vtype vneg(vtype x){ - return _mm256_xor_ps(x, _mm256_set1_ps(-0.0)); -} -static PA_FORCE_INLINE vtype vadd(vtype x, vtype y){ - return _mm256_add_ps(x, y); -} -static PA_FORCE_INLINE vtype vsub(vtype x, vtype y){ - return _mm256_sub_ps(x, y); -} -static PA_FORCE_INLINE vtype vmul(vtype x, vtype y){ - return _mm256_mul_ps(x, y); -} -static PA_FORCE_INLINE void cmul_pp( - vtype& Xr, vtype& Xi, - vtype Wr, vtype Wi -){ - vtype t0 = _mm256_mul_ps(Xi, Wi); - vtype t1 = _mm256_mul_ps(Xr, Wi); - Xr = _mm256_fmsub_ps(Xr, Wr, t0); - Xi = _mm256_fmadd_ps(Xi, Wr, t1); -} - - -static PA_FORCE_INLINE vtype abs(vtype r, vtype i){ - vtype r0 = _mm256_fmadd_ps(r, r, _mm256_mul_ps(i, i)); - return _mm256_sqrt_ps(r0); -} -static PA_FORCE_INLINE void swap_odd(vtype& L, vtype& H){ - vtype r0 = _mm256_permutevar8x32_ps(L, _mm256_setr_epi32(0, 7, 2, 5, 4, 3, 6, 1)); - vtype r1 = _mm256_permutevar8x32_ps(H, _mm256_setr_epi32(0, 7, 2, 5, 4, 3, 6, 1)); - L = _mm256_blend_ps(L, r1, 170); - H = _mm256_blend_ps(H, r0, 170); -} - - -static PA_FORCE_INLINE void interleave_v0( - vtype& out0, vtype& out1, - vtype lo, vtype hi -){ - __m256 a0 = _mm256_permute2f128_ps(lo, hi, 32); - __m256 a1 = _mm256_permute2f128_ps(lo, hi, 49); - out0 = _mm256_permutevar8x32_ps(a0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); - out1 = _mm256_permutevar8x32_ps(a1, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); -} -static PA_FORCE_INLINE void interleave_v1( - vtype& out0, vtype& out1, - vtype lo, vtype hi -){ - __m256 a0 = _mm256_permute2f128_ps(lo, hi, 32); - __m256 a1 = _mm256_permute2f128_ps(lo, hi, 49); - out0 = _mm256_castpd_ps(_mm256_permute4x64_pd(_mm256_castps_pd(a0), 216)); - out1 = _mm256_castpd_ps(_mm256_permute4x64_pd(_mm256_castps_pd(a1), 216)); -} - - -}; -} -} -} -#endif +/* ABS FFT Arch (AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_x86_AVX2_H +#define PokemonAutomation_Kernels_AbsFFT_Arch_x86_AVX2_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ +struct Context_x86_AVX2{ + + +using vtype = __m256; +static const int VECTOR_K = 3; +static const size_t VECTOR_LENGTH = (size_t)1 << VECTOR_K; + +static const int BASE_COMPLEX_TRANSFORM_K = 6; +static const size_t MIN_TABLE_WIDTH = 4; + + +static PA_FORCE_INLINE vtype vset1(float x){ + return _mm256_set1_ps(x); +} +static PA_FORCE_INLINE vtype vneg(vtype x){ + return _mm256_xor_ps(x, _mm256_set1_ps(-0.0)); +} +static PA_FORCE_INLINE vtype vadd(vtype x, vtype y){ + return _mm256_add_ps(x, y); +} +static PA_FORCE_INLINE vtype vsub(vtype x, vtype y){ + return _mm256_sub_ps(x, y); +} +static PA_FORCE_INLINE vtype vmul(vtype x, vtype y){ + return _mm256_mul_ps(x, y); +} +static PA_FORCE_INLINE void cmul_pp( + vtype& Xr, vtype& Xi, + vtype Wr, vtype Wi +){ + vtype t0 = _mm256_mul_ps(Xi, Wi); + vtype t1 = _mm256_mul_ps(Xr, Wi); + Xr = _mm256_fmsub_ps(Xr, Wr, t0); + Xi = _mm256_fmadd_ps(Xi, Wr, t1); +} + + +static PA_FORCE_INLINE vtype abs(vtype r, vtype i){ + vtype r0 = _mm256_fmadd_ps(r, r, _mm256_mul_ps(i, i)); + return _mm256_sqrt_ps(r0); +} +static PA_FORCE_INLINE void swap_odd(vtype& L, vtype& H){ + vtype r0 = _mm256_permutevar8x32_ps(L, _mm256_setr_epi32(0, 7, 2, 5, 4, 3, 6, 1)); + vtype r1 = _mm256_permutevar8x32_ps(H, _mm256_setr_epi32(0, 7, 2, 5, 4, 3, 6, 1)); + L = _mm256_blend_ps(L, r1, 170); + H = _mm256_blend_ps(H, r0, 170); +} + + +static PA_FORCE_INLINE void interleave_v0( + vtype& out0, vtype& out1, + vtype lo, vtype hi +){ + __m256 a0 = _mm256_permute2f128_ps(lo, hi, 32); + __m256 a1 = _mm256_permute2f128_ps(lo, hi, 49); + out0 = _mm256_permutevar8x32_ps(a0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); + out1 = _mm256_permutevar8x32_ps(a1, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7)); +} +static PA_FORCE_INLINE void interleave_v1( + vtype& out0, vtype& out1, + vtype lo, vtype hi +){ + __m256 a0 = _mm256_permute2f128_ps(lo, hi, 32); + __m256 a1 = _mm256_permute2f128_ps(lo, hi, 49); + out0 = _mm256_castpd_ps(_mm256_permute4x64_pd(_mm256_castps_pd(a0), 216)); + out1 = _mm256_castpd_ps(_mm256_permute4x64_pd(_mm256_castps_pd(a1), 216)); +} + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_SSE41.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_SSE41.h index 20726e666c..047ebd56cf 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_SSE41.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Arch_x86_SSE41.h @@ -1,89 +1,89 @@ -/* ABS FFT Arch (SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_x86_SSE41_H -#define PokemonAutomation_Kernels_AbsFFT_Arch_x86_SSE41_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ -struct Context_x86_SSE41{ - - -using vtype = __m128; - -static const int VECTOR_K = 2; -static const size_t VECTOR_LENGTH = (size_t)1 << VECTOR_K; - -static const int BASE_COMPLEX_TRANSFORM_K = 4; -static const size_t MIN_TABLE_WIDTH = 1; - - -static PA_FORCE_INLINE vtype vset1(float x){ - return _mm_set1_ps(x); -} -static PA_FORCE_INLINE vtype vneg(vtype x){ - return _mm_xor_ps(x, _mm_set1_ps(-0.0)); -} -static PA_FORCE_INLINE vtype vadd(vtype x, vtype y){ - return _mm_add_ps(x, y); -} -static PA_FORCE_INLINE vtype vsub(vtype x, vtype y){ - return _mm_sub_ps(x, y); -} -static PA_FORCE_INLINE vtype vmul(vtype x, vtype y){ - return _mm_mul_ps(x, y); -} -static PA_FORCE_INLINE void cmul_pp( - vtype& Xr, vtype& Xi, - vtype Wr, vtype Wi -){ - vtype t0 = _mm_mul_ps(Xi, Wi); - vtype t1 = _mm_mul_ps(Xr, Wi); - Xr = _mm_mul_ps(Xr, Wr); - Xr = _mm_sub_ps(Xr, t0); - Xi = _mm_mul_ps(Xi, Wr); - Xi = _mm_add_ps(Xi, t1); -} - - -static PA_FORCE_INLINE vtype abs(vtype r, vtype i){ - vtype r0 = _mm_add_ps(_mm_mul_ps(r, r), _mm_mul_ps(i, i)); - return _mm_sqrt_ps(r0); -} -static PA_FORCE_INLINE void swap_odd(vtype& L, vtype& H){ - vtype r0 = _mm_shuffle_ps(L, L, 108); - vtype r1 = _mm_shuffle_ps(H, H, 108); - L = _mm_blend_ps(L, r1, 10); - H = _mm_blend_ps(H, r0, 10); -} - - -static PA_FORCE_INLINE void interleave_v0( - vtype& out0, vtype& out1, - vtype lo, vtype hi -){ - out0 = _mm_unpacklo_ps(lo, hi); - out1 = _mm_unpackhi_ps(lo, hi); -} -static PA_FORCE_INLINE void interleave_v1( - vtype& out0, vtype& out1, - vtype lo, vtype hi -){ - out0 = _mm_shuffle_ps(lo, hi, 68); - out1 = _mm_shuffle_ps(lo, hi, 238); -} - - - -}; -} -} -} -#endif +/* ABS FFT Arch (SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_Arch_x86_SSE41_H +#define PokemonAutomation_Kernels_AbsFFT_Arch_x86_SSE41_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ +struct Context_x86_SSE41{ + + +using vtype = __m128; + +static const int VECTOR_K = 2; +static const size_t VECTOR_LENGTH = (size_t)1 << VECTOR_K; + +static const int BASE_COMPLEX_TRANSFORM_K = 4; +static const size_t MIN_TABLE_WIDTH = 1; + + +static PA_FORCE_INLINE vtype vset1(float x){ + return _mm_set1_ps(x); +} +static PA_FORCE_INLINE vtype vneg(vtype x){ + return _mm_xor_ps(x, _mm_set1_ps(-0.0)); +} +static PA_FORCE_INLINE vtype vadd(vtype x, vtype y){ + return _mm_add_ps(x, y); +} +static PA_FORCE_INLINE vtype vsub(vtype x, vtype y){ + return _mm_sub_ps(x, y); +} +static PA_FORCE_INLINE vtype vmul(vtype x, vtype y){ + return _mm_mul_ps(x, y); +} +static PA_FORCE_INLINE void cmul_pp( + vtype& Xr, vtype& Xi, + vtype Wr, vtype Wi +){ + vtype t0 = _mm_mul_ps(Xi, Wi); + vtype t1 = _mm_mul_ps(Xr, Wi); + Xr = _mm_mul_ps(Xr, Wr); + Xr = _mm_sub_ps(Xr, t0); + Xi = _mm_mul_ps(Xi, Wr); + Xi = _mm_add_ps(Xi, t1); +} + + +static PA_FORCE_INLINE vtype abs(vtype r, vtype i){ + vtype r0 = _mm_add_ps(_mm_mul_ps(r, r), _mm_mul_ps(i, i)); + return _mm_sqrt_ps(r0); +} +static PA_FORCE_INLINE void swap_odd(vtype& L, vtype& H){ + vtype r0 = _mm_shuffle_ps(L, L, 108); + vtype r1 = _mm_shuffle_ps(H, H, 108); + L = _mm_blend_ps(L, r1, 10); + H = _mm_blend_ps(H, r0, 10); +} + + +static PA_FORCE_INLINE void interleave_v0( + vtype& out0, vtype& out1, + vtype lo, vtype hi +){ + out0 = _mm_unpacklo_ps(lo, hi); + out1 = _mm_unpackhi_ps(lo, hi); +} +static PA_FORCE_INLINE void interleave_v1( + vtype& out0, vtype& out1, + vtype lo, vtype hi +){ + out0 = _mm_shuffle_ps(lo, hi, 68); + out1 = _mm_shuffle_ps(lo, hi, 238); +} + + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_AVX2.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_AVX2.h index 990d78abbf..ae0454d44c 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_AVX2.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_AVX2.h @@ -1,146 +1,146 @@ -/* ABS FFT Base Transform (x86 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_AVX2_H -#define PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_AVX2_H - -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels_AbsFFT_Arch_x86_AVX2.h" -#include "Kernels_AbsFFT_Butterflies.h" -#include "Kernels_AbsFFT_ComplexVector.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - -PA_FORCE_INLINE void vtranspose( - __m256& r0, __m256& r1, __m256& r2, __m256& r3, - __m256& r4, __m256& r5, __m256& r6, __m256& r7 -){ - __m256 a0, a1, a2, a3, a4, a5, a6, a7; - __m256 b0, b1, b2, b3, b4, b5, b6, b7; - - a0 = _mm256_unpacklo_ps(r0, r1); - a1 = _mm256_unpackhi_ps(r0, r1); - a2 = _mm256_unpacklo_ps(r2, r3); - a3 = _mm256_unpackhi_ps(r2, r3); - a4 = _mm256_unpacklo_ps(r4, r5); - a5 = _mm256_unpackhi_ps(r4, r5); - a6 = _mm256_unpacklo_ps(r6, r7); - a7 = _mm256_unpackhi_ps(r6, r7); - - b0 = _mm256_shuffle_ps(a0, a2, 68); - b1 = _mm256_shuffle_ps(a0, a2, 238); - b2 = _mm256_shuffle_ps(a1, a3, 68); - b3 = _mm256_shuffle_ps(a1, a3, 238); - b4 = _mm256_shuffle_ps(a4, a6, 68); - b5 = _mm256_shuffle_ps(a4, a6, 238); - b6 = _mm256_shuffle_ps(a5, a7, 68); - b7 = _mm256_shuffle_ps(a5, a7, 238); - - r0 = _mm256_permute2f128_ps(b0, b4, 32); - r4 = _mm256_permute2f128_ps(b0, b4, 49); - r1 = _mm256_permute2f128_ps(b1, b5, 32); - r5 = _mm256_permute2f128_ps(b1, b5, 49); - r2 = _mm256_permute2f128_ps(b2, b6, 32); - r6 = _mm256_permute2f128_ps(b2, b6, 49); - r3 = _mm256_permute2f128_ps(b3, b7, 32); - r7 = _mm256_permute2f128_ps(b3, b7, 49); -} - -template <> -void base_transform(const TwiddleTable& table, Context_x86_AVX2::vtype* T){ - __m256 r0, r1, r2, r3, r4, r5, r6, r7; - __m256 i0, i1, i2, i3, i4, i5, i6, i7; - - r0 = T[ 0]; - i0 = T[ 1]; - r1 = T[ 2]; - i1 = T[ 3]; - r2 = T[ 4]; - i2 = T[ 5]; - r3 = T[ 6]; - i3 = T[ 7]; - r4 = T[ 8]; - i4 = T[ 9]; - r5 = T[10]; - i5 = T[11]; - r6 = T[12]; - i6 = T[13]; - r7 = T[14]; - i7 = T[15]; - - { - const vcomplex* w1 = table[6].w1.data(); - Butterflies::butterfly2(r0, i0, r4, i4, w1[0].r, w1[0].i); - Butterflies::butterfly2(r1, i1, r5, i5, w1[1].r, w1[1].i); - Butterflies::butterfly2(r2, i2, r6, i6, w1[2].r, w1[2].i); - Butterflies::butterfly2(r3, i3, r7, i7, w1[3].r, w1[3].i); - } - { - const vcomplex* w1 = table[4].w1.data(); - const vcomplex* w2 = table[5].w1.data(); - const vcomplex* w3 = table[5].w3.data(); - Butterflies::butterfly4( - r0, i0, - r1, i1, w1[0].r, w1[0].i, - r2, i2, w2[0].r, w2[0].i, - r3, i3, w3[0].r, w3[0].i - ); - Butterflies::butterfly4( - r4, i4, - r5, i5, w1[0].r, w1[0].i, - r6, i6, w2[0].r, w2[0].i, - r7, i7, w3[0].r, w3[0].i - ); - } - - vtranspose(r0, r1, r2, r3, r4, r5, r6, r7); - vtranspose(i0, i1, i2, i3, i4, i5, i6, i7); - - Butterflies::butterfly2(r0, i0, r4, i4); - Butterflies::butterfly2(r1, i1, r5, i5, Context_x86_AVX2::vset1(TW8_1), Context_x86_AVX2::vset1(TW8_1)); - Butterflies::butterfly2(r2, i2, r6, i6, Context_x86_AVX2::vset1(0), Context_x86_AVX2::vset1(1)); - Butterflies::butterfly2(r3, i3, r7, i7, Context_x86_AVX2::vset1(-TW8_1), Context_x86_AVX2::vset1(TW8_1)); - Butterflies::butterfly4( - r0, i0, - r1, i1, - r2, i2, - r3, i3 - ); - Butterflies::butterfly4( - r4, i4, - r5, i5, - r6, i6, - r7, i7 - ); - - vtranspose(r0, r1, r2, r3, r4, r5, r6, r7); - T[ 0] = r0; - T[ 2] = r1; - T[ 4] = r2; - T[ 6] = r3; - T[ 8] = r4; - T[10] = r5; - T[12] = r6; - T[14] = r7; - vtranspose(i0, i1, i2, i3, i4, i5, i6, i7); - T[ 1] = i0; - T[ 3] = i1; - T[ 5] = i2; - T[ 7] = i3; - T[ 9] = i4; - T[11] = i5; - T[13] = i6; - T[15] = i7; -} - - - -} -} -} -#endif +/* ABS FFT Base Transform (x86 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_AVX2_H +#define PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_AVX2_H + +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels_AbsFFT_Arch_x86_AVX2.h" +#include "Kernels_AbsFFT_Butterflies.h" +#include "Kernels_AbsFFT_ComplexVector.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + +PA_FORCE_INLINE void vtranspose( + __m256& r0, __m256& r1, __m256& r2, __m256& r3, + __m256& r4, __m256& r5, __m256& r6, __m256& r7 +){ + __m256 a0, a1, a2, a3, a4, a5, a6, a7; + __m256 b0, b1, b2, b3, b4, b5, b6, b7; + + a0 = _mm256_unpacklo_ps(r0, r1); + a1 = _mm256_unpackhi_ps(r0, r1); + a2 = _mm256_unpacklo_ps(r2, r3); + a3 = _mm256_unpackhi_ps(r2, r3); + a4 = _mm256_unpacklo_ps(r4, r5); + a5 = _mm256_unpackhi_ps(r4, r5); + a6 = _mm256_unpacklo_ps(r6, r7); + a7 = _mm256_unpackhi_ps(r6, r7); + + b0 = _mm256_shuffle_ps(a0, a2, 68); + b1 = _mm256_shuffle_ps(a0, a2, 238); + b2 = _mm256_shuffle_ps(a1, a3, 68); + b3 = _mm256_shuffle_ps(a1, a3, 238); + b4 = _mm256_shuffle_ps(a4, a6, 68); + b5 = _mm256_shuffle_ps(a4, a6, 238); + b6 = _mm256_shuffle_ps(a5, a7, 68); + b7 = _mm256_shuffle_ps(a5, a7, 238); + + r0 = _mm256_permute2f128_ps(b0, b4, 32); + r4 = _mm256_permute2f128_ps(b0, b4, 49); + r1 = _mm256_permute2f128_ps(b1, b5, 32); + r5 = _mm256_permute2f128_ps(b1, b5, 49); + r2 = _mm256_permute2f128_ps(b2, b6, 32); + r6 = _mm256_permute2f128_ps(b2, b6, 49); + r3 = _mm256_permute2f128_ps(b3, b7, 32); + r7 = _mm256_permute2f128_ps(b3, b7, 49); +} + +template <> +void base_transform(const TwiddleTable& table, Context_x86_AVX2::vtype* T){ + __m256 r0, r1, r2, r3, r4, r5, r6, r7; + __m256 i0, i1, i2, i3, i4, i5, i6, i7; + + r0 = T[ 0]; + i0 = T[ 1]; + r1 = T[ 2]; + i1 = T[ 3]; + r2 = T[ 4]; + i2 = T[ 5]; + r3 = T[ 6]; + i3 = T[ 7]; + r4 = T[ 8]; + i4 = T[ 9]; + r5 = T[10]; + i5 = T[11]; + r6 = T[12]; + i6 = T[13]; + r7 = T[14]; + i7 = T[15]; + + { + const vcomplex* w1 = table[6].w1.data(); + Butterflies::butterfly2(r0, i0, r4, i4, w1[0].r, w1[0].i); + Butterflies::butterfly2(r1, i1, r5, i5, w1[1].r, w1[1].i); + Butterflies::butterfly2(r2, i2, r6, i6, w1[2].r, w1[2].i); + Butterflies::butterfly2(r3, i3, r7, i7, w1[3].r, w1[3].i); + } + { + const vcomplex* w1 = table[4].w1.data(); + const vcomplex* w2 = table[5].w1.data(); + const vcomplex* w3 = table[5].w3.data(); + Butterflies::butterfly4( + r0, i0, + r1, i1, w1[0].r, w1[0].i, + r2, i2, w2[0].r, w2[0].i, + r3, i3, w3[0].r, w3[0].i + ); + Butterflies::butterfly4( + r4, i4, + r5, i5, w1[0].r, w1[0].i, + r6, i6, w2[0].r, w2[0].i, + r7, i7, w3[0].r, w3[0].i + ); + } + + vtranspose(r0, r1, r2, r3, r4, r5, r6, r7); + vtranspose(i0, i1, i2, i3, i4, i5, i6, i7); + + Butterflies::butterfly2(r0, i0, r4, i4); + Butterflies::butterfly2(r1, i1, r5, i5, Context_x86_AVX2::vset1(TW8_1), Context_x86_AVX2::vset1(TW8_1)); + Butterflies::butterfly2(r2, i2, r6, i6, Context_x86_AVX2::vset1(0), Context_x86_AVX2::vset1(1)); + Butterflies::butterfly2(r3, i3, r7, i7, Context_x86_AVX2::vset1(-TW8_1), Context_x86_AVX2::vset1(TW8_1)); + Butterflies::butterfly4( + r0, i0, + r1, i1, + r2, i2, + r3, i3 + ); + Butterflies::butterfly4( + r4, i4, + r5, i5, + r6, i6, + r7, i7 + ); + + vtranspose(r0, r1, r2, r3, r4, r5, r6, r7); + T[ 0] = r0; + T[ 2] = r1; + T[ 4] = r2; + T[ 6] = r3; + T[ 8] = r4; + T[10] = r5; + T[12] = r6; + T[14] = r7; + vtranspose(i0, i1, i2, i3, i4, i5, i6, i7); + T[ 1] = i0; + T[ 3] = i1; + T[ 5] = i2; + T[ 7] = i3; + T[ 9] = i4; + T[11] = i5; + T[13] = i6; + T[15] = i7; +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_SSE41.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_SSE41.h index 694432f73a..07d719737b 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_SSE41.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BaseTransform_x86_SSE41.h @@ -1,82 +1,82 @@ -/* ABS FFT Base Transform (x86 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_SSE41_H -#define PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_SSE41_H - -#include "Kernels_AbsFFT_Arch_x86_SSE41.h" -#include "Kernels_AbsFFT_Butterflies.h" -#include "Kernels_AbsFFT_ComplexVector.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - -PA_FORCE_INLINE void vtranspose(__m128& r0, __m128& r1, __m128& r2, __m128& r3){ - __m128 a0, a1, a2, a3; - a0 = _mm_unpacklo_ps(r0, r1); - a1 = _mm_unpackhi_ps(r0, r1); - a2 = _mm_unpacklo_ps(r2, r3); - a3 = _mm_unpackhi_ps(r2, r3); - r0 = _mm_shuffle_ps(a0, a2, 68); - r1 = _mm_shuffle_ps(a0, a2, 238); - r2 = _mm_shuffle_ps(a1, a3, 68); - r3 = _mm_shuffle_ps(a1, a3, 238); -} - - -template <> -void base_transform(const TwiddleTable& table, Context_x86_SSE41::vtype* T){ - __m128 r0, r1, r2, r3; - __m128 i0, i1, i2, i3; - - r0 = T[0]; - i0 = T[1]; - r1 = T[2]; - i1 = T[3]; - r2 = T[4]; - r3 = T[6]; - i2 = T[5]; - i3 = T[7]; - - const vcomplex* w1 = table[3].w1.data(); - const vcomplex* w2 = table[4].w1.data(); - const vcomplex* w3 = table[4].w3.data(); - Butterflies::butterfly4( - r0, i0, - r1, i1, w1[0].r, w1[0].i, - r2, i2, w2[0].r, w2[0].i, - r3, i3, w3[0].r, w3[0].i - ); - - vtranspose(r0, r1, r2, r3); - vtranspose(i0, i1, i2, i3); - - Butterflies::butterfly4( - r0, i0, - r1, i1, - r2, i2, - r3, i3 - ); - - vtranspose(r0, r1, r2, r3); - T[0] = r0; - T[2] = r1; - T[4] = r2; - T[6] = r3; - vtranspose(i0, i1, i2, i3); - T[1] = i0; - T[3] = i1; - T[5] = i2; - T[7] = i3; -} - - - -} -} -} -#endif +/* ABS FFT Base Transform (x86 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_SSE41_H +#define PokemonAutomation_Kernels_AbsFFT_BaseTransform_x86_SSE41_H + +#include "Kernels_AbsFFT_Arch_x86_SSE41.h" +#include "Kernels_AbsFFT_Butterflies.h" +#include "Kernels_AbsFFT_ComplexVector.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + +PA_FORCE_INLINE void vtranspose(__m128& r0, __m128& r1, __m128& r2, __m128& r3){ + __m128 a0, a1, a2, a3; + a0 = _mm_unpacklo_ps(r0, r1); + a1 = _mm_unpackhi_ps(r0, r1); + a2 = _mm_unpacklo_ps(r2, r3); + a3 = _mm_unpackhi_ps(r2, r3); + r0 = _mm_shuffle_ps(a0, a2, 68); + r1 = _mm_shuffle_ps(a0, a2, 238); + r2 = _mm_shuffle_ps(a1, a3, 68); + r3 = _mm_shuffle_ps(a1, a3, 238); +} + + +template <> +void base_transform(const TwiddleTable& table, Context_x86_SSE41::vtype* T){ + __m128 r0, r1, r2, r3; + __m128 i0, i1, i2, i3; + + r0 = T[0]; + i0 = T[1]; + r1 = T[2]; + i1 = T[3]; + r2 = T[4]; + r3 = T[6]; + i2 = T[5]; + i3 = T[7]; + + const vcomplex* w1 = table[3].w1.data(); + const vcomplex* w2 = table[4].w1.data(); + const vcomplex* w3 = table[4].w3.data(); + Butterflies::butterfly4( + r0, i0, + r1, i1, w1[0].r, w1[0].i, + r2, i2, w2[0].r, w2[0].i, + r3, i3, w3[0].r, w3[0].i + ); + + vtranspose(r0, r1, r2, r3); + vtranspose(i0, i1, i2, i3); + + Butterflies::butterfly4( + r0, i0, + r1, i1, + r2, i2, + r3, i3 + ); + + vtranspose(r0, r1, r2, r3); + T[0] = r0; + T[2] = r1; + T[4] = r2; + T[6] = r3; + vtranspose(i0, i1, i2, i3); + T[1] = i0; + T[3] = i1; + T[5] = i2; + T[7] = i3; +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BitReverse.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BitReverse.h index a3f06ee6c0..d60ebbaf01 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BitReverse.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_BitReverse.h @@ -1,195 +1,195 @@ -/* ABS FFT Bit Reverse - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_BitReverse_H -#define PokemonAutomation_Kernels_AbsFFT_BitReverse_H - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - -template -struct BitReverse{ - - -using vtype = typename Context::vtype; - - -static PA_FORCE_INLINE void interleave_f32_scalar(int len_k, float* out, const float* in){ - size_t stride = (size_t)1 << (len_k - 1); - const float* in0 = in; - const float* in1 = in + stride; - size_t lc = stride; - do{ - float r0 = in0[0]; - float r1 = in1[0]; - out[0] = r0; - out[1] = r1; - in0 += 1; - in1 += 1; - out += 2; - }while (--lc); -} -static PA_FORCE_INLINE void interleave_u64_scalar(int len_k, uint64_t* out, const uint64_t* in){ - size_t stride = (size_t)1 << (len_k - 1); - const uint64_t* in0 = in; - const uint64_t* in1 = in + stride; - size_t lc = stride; - do{ - uint64_t r0 = in0[0]; - uint64_t r1 = in1[0]; - out[0] = r0; - out[1] = r1; - in0++; - in1++; - out += 2; - }while (--lc); -} -static PA_FORCE_INLINE void interleave_u64(int len_k, uint64_t* out, const uint64_t* in){ - if ((size_t)len_k < Context::VECTOR_K || Context::VECTOR_K == 0){ - interleave_u64_scalar(len_k, out, in); - return; - } - size_t vstride = (size_t)1 << (len_k - Context::VECTOR_K); - const vtype* in0 = (const vtype*)in; - const vtype* in1 = in0 + vstride; - vtype* out0 = (vtype*)out; - size_t lc = vstride; - do{ - vtype r0, r1; - Context::interleave_v1(r0, r1, in0[0], in1[0]); - out0[0] = r0; - out0[1] = r1; - in0 += 1; - in1 += 1; - out0 += 2; - }while (--lc); -} - - - - -// 32-bit Granular -static void interleave_f32(int len_k, float* out, const float* in){ - using vtype = typename Context::vtype; - - if ((size_t)len_k < Context::VECTOR_K + 1){ - interleave_f32_scalar(len_k, (float*)out, (const float*)in); - return; - } - size_t vstride = (size_t)1 << (len_k - 1 - Context::VECTOR_K); - const vtype* in0 = (const vtype*)in; - const vtype* in1 = in0 + vstride; - vtype* out0 = (vtype*)out; - size_t lc = vstride; - do{ - vtype r0, r1; - Context::interleave_v0(r0, r1, in0[0], in1[0]); - out0[0] = r0; - out0[1] = r1; - in0 += 1; - in1 += 1; - out0 += 2; - }while (--lc); -} - - -// 64-bit Granular - -// in-place -static void bitreverse_u64_ip(int len_k, uint64_t* data, uint64_t* temp){ - if (len_k <= 1){ - return; - } - if (len_k == 2){ - uint64_t r1 = data[1]; - uint64_t r2 = data[2]; - data[1] = r2; - data[2] = r1; - return; - } - if (len_k == 3){ - uint64_t r1 = data[1]; - uint64_t r3 = data[3]; - uint64_t r4 = data[4]; - uint64_t r6 = data[6]; - data[1] = r4; - data[3] = r6; - data[4] = r1; - data[6] = r3; - return; - } - - len_k--; - size_t stride = (size_t)1 << len_k; - bitreverse_u64_np(len_k, temp + 0*stride, data + 0*stride); - bitreverse_u64_np(len_k, temp + 1*stride, data + 1*stride); - interleave_u64(len_k + 1, data, temp); -} - -// out-of-place -static void bitreverse_u64_np(int len_k, uint64_t* out, uint64_t* in){ - if (len_k == 0){ - out[0] = in[0]; - return; - } - if (len_k == 1){ - out[0] = in[0]; - out[1] = in[1]; - return; - } - if (len_k == 2){ - uint64_t r0 = in[0]; - uint64_t r1 = in[1]; - uint64_t r2 = in[2]; - uint64_t r3 = in[3]; - out[0] = r0; - out[1] = r2; - out[2] = r1; - out[0] = r3; - return; - } - if (len_k == 3){ - uint64_t r0 = in[0]; - uint64_t r1 = in[1]; - uint64_t r2 = in[2]; - uint64_t r3 = in[3]; - uint64_t r4 = in[4]; - uint64_t r5 = in[5]; - uint64_t r6 = in[6]; - uint64_t r7 = in[7]; - out[0] = r0; - out[1] = r4; - out[2] = r2; - out[3] = r6; - out[4] = r1; - out[5] = r5; - out[6] = r3; - out[7] = r7; - return; - } - - len_k--; - size_t stride = (size_t)1 << len_k; - bitreverse_u64_ip(len_k, in + 0*stride, out + 0*stride); - bitreverse_u64_ip(len_k, in + 1*stride, out + 1*stride); - interleave_u64(len_k + 1, out, in); -} - -static inline void bitreverse_f32v1_ip(int len_k, float* data, float* temp){ - bitreverse_u64_ip(len_k - 1, (uint64_t*)data, (uint64_t*)temp); -} - - -}; -} -} -} -#endif +/* ABS FFT Bit Reverse + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_BitReverse_H +#define PokemonAutomation_Kernels_AbsFFT_BitReverse_H + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + +template +struct BitReverse{ + + +using vtype = typename Context::vtype; + + +static PA_FORCE_INLINE void interleave_f32_scalar(int len_k, float* out, const float* in){ + size_t stride = (size_t)1 << (len_k - 1); + const float* in0 = in; + const float* in1 = in + stride; + size_t lc = stride; + do{ + float r0 = in0[0]; + float r1 = in1[0]; + out[0] = r0; + out[1] = r1; + in0 += 1; + in1 += 1; + out += 2; + }while (--lc); +} +static PA_FORCE_INLINE void interleave_u64_scalar(int len_k, uint64_t* out, const uint64_t* in){ + size_t stride = (size_t)1 << (len_k - 1); + const uint64_t* in0 = in; + const uint64_t* in1 = in + stride; + size_t lc = stride; + do{ + uint64_t r0 = in0[0]; + uint64_t r1 = in1[0]; + out[0] = r0; + out[1] = r1; + in0++; + in1++; + out += 2; + }while (--lc); +} +static PA_FORCE_INLINE void interleave_u64(int len_k, uint64_t* out, const uint64_t* in){ + if ((size_t)len_k < Context::VECTOR_K || Context::VECTOR_K == 0){ + interleave_u64_scalar(len_k, out, in); + return; + } + size_t vstride = (size_t)1 << (len_k - Context::VECTOR_K); + const vtype* in0 = (const vtype*)in; + const vtype* in1 = in0 + vstride; + vtype* out0 = (vtype*)out; + size_t lc = vstride; + do{ + vtype r0, r1; + Context::interleave_v1(r0, r1, in0[0], in1[0]); + out0[0] = r0; + out0[1] = r1; + in0 += 1; + in1 += 1; + out0 += 2; + }while (--lc); +} + + + + +// 32-bit Granular +static void interleave_f32(int len_k, float* out, const float* in){ + using vtype = typename Context::vtype; + + if ((size_t)len_k < Context::VECTOR_K + 1){ + interleave_f32_scalar(len_k, (float*)out, (const float*)in); + return; + } + size_t vstride = (size_t)1 << (len_k - 1 - Context::VECTOR_K); + const vtype* in0 = (const vtype*)in; + const vtype* in1 = in0 + vstride; + vtype* out0 = (vtype*)out; + size_t lc = vstride; + do{ + vtype r0, r1; + Context::interleave_v0(r0, r1, in0[0], in1[0]); + out0[0] = r0; + out0[1] = r1; + in0 += 1; + in1 += 1; + out0 += 2; + }while (--lc); +} + + +// 64-bit Granular + +// in-place +static void bitreverse_u64_ip(int len_k, uint64_t* data, uint64_t* temp){ + if (len_k <= 1){ + return; + } + if (len_k == 2){ + uint64_t r1 = data[1]; + uint64_t r2 = data[2]; + data[1] = r2; + data[2] = r1; + return; + } + if (len_k == 3){ + uint64_t r1 = data[1]; + uint64_t r3 = data[3]; + uint64_t r4 = data[4]; + uint64_t r6 = data[6]; + data[1] = r4; + data[3] = r6; + data[4] = r1; + data[6] = r3; + return; + } + + len_k--; + size_t stride = (size_t)1 << len_k; + bitreverse_u64_np(len_k, temp + 0*stride, data + 0*stride); + bitreverse_u64_np(len_k, temp + 1*stride, data + 1*stride); + interleave_u64(len_k + 1, data, temp); +} + +// out-of-place +static void bitreverse_u64_np(int len_k, uint64_t* out, uint64_t* in){ + if (len_k == 0){ + out[0] = in[0]; + return; + } + if (len_k == 1){ + out[0] = in[0]; + out[1] = in[1]; + return; + } + if (len_k == 2){ + uint64_t r0 = in[0]; + uint64_t r1 = in[1]; + uint64_t r2 = in[2]; + uint64_t r3 = in[3]; + out[0] = r0; + out[1] = r2; + out[2] = r1; + out[0] = r3; + return; + } + if (len_k == 3){ + uint64_t r0 = in[0]; + uint64_t r1 = in[1]; + uint64_t r2 = in[2]; + uint64_t r3 = in[3]; + uint64_t r4 = in[4]; + uint64_t r5 = in[5]; + uint64_t r6 = in[6]; + uint64_t r7 = in[7]; + out[0] = r0; + out[1] = r4; + out[2] = r2; + out[3] = r6; + out[4] = r1; + out[5] = r5; + out[6] = r3; + out[7] = r7; + return; + } + + len_k--; + size_t stride = (size_t)1 << len_k; + bitreverse_u64_ip(len_k, in + 0*stride, out + 0*stride); + bitreverse_u64_ip(len_k, in + 1*stride, out + 1*stride); + interleave_u64(len_k + 1, out, in); +} + +static inline void bitreverse_f32v1_ip(int len_k, float* data, float* temp){ + bitreverse_u64_ip(len_k - 1, (uint64_t*)data, (uint64_t*)temp); +} + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Butterflies.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Butterflies.h index dc602b9ef1..95a8a0ce45 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Butterflies.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Butterflies.h @@ -1,165 +1,165 @@ -/* ABS FFT Butterflies - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_Butterflies_H -#define PokemonAutomation_Kernels_AbsFFT_Butterflies_H - -#include "Common/Compiler.h" -#include "Kernels_AbsFFT_TwiddleTable.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ -template -struct Butterflies{ - -using vtype = typename Context::vtype; - - -static PA_FORCE_INLINE void butterfly2( - vtype& R0, vtype& I0, - vtype& R1, vtype& I1 -){ - vtype r1 = R1; - vtype i1 = I1; - R1 = Context::vsub(R0, r1); - I1 = Context::vsub(I0, i1); - R0 = Context::vadd(R0, r1); - I0 = Context::vadd(I0, i1); -} -static PA_FORCE_INLINE void butterfly2( - vtype& R0, vtype& I0, - vtype& R1, vtype& I1, vtype W1r, vtype W1i -){ - butterfly2(R0, I0, R1, I1); - Context::cmul_pp(R1, I1, W1r, W1i); -} - -static PA_FORCE_INLINE void butterfly4( - vtype& R0, vtype& I0, - vtype& R1, vtype& I1, - vtype& R2, vtype& I2, - vtype& R3, vtype& I3 -){ - vtype r0, r1, r2, r3; - vtype i0, i1, i2, i3; - - r0 = Context::vadd(R0, R2); - r2 = Context::vsub(R0, R2); - r1 = Context::vadd(R1, R3); - r3 = Context::vsub(R1, R3); - i0 = Context::vadd(I0, I2); - i2 = Context::vsub(I0, I2); - i1 = Context::vadd(I1, I3); - i3 = Context::vsub(I1, I3); - - R0 = Context::vadd(r0, r1); - R1 = Context::vsub(r0, r1); - I0 = Context::vadd(i0, i1); - I1 = Context::vsub(i0, i1); - R2 = Context::vsub(r2, i3); - R3 = Context::vadd(r2, i3); - I2 = Context::vadd(i2, r3); - I3 = Context::vsub(i2, r3); -} -static PA_FORCE_INLINE void butterfly4( - vtype& R0, vtype& I0, - vtype& R1, vtype& I1, vtype W1r, vtype W1i, - vtype& R2, vtype& I2, vtype W2r, vtype W2i, - vtype& R3, vtype& I3, vtype W3r, vtype W3i -){ - butterfly4(R0, I0, R1, I1, R2, I2, R3, I3); - Context::cmul_pp(R1, I1, W1r, W1i); - Context::cmul_pp(R2, I2, W2r, W2i); - Context::cmul_pp(R3, I3, W3r, W3i); -} - - -static PA_FORCE_INLINE void reduce2(const TwiddleTable& table, int k, vtype* T){ - size_t stride = (size_t)1 << (k - 1 - Context::VECTOR_K); - vtype* T0 = T; - vtype* T1 = T0 + 2*stride; - const vcomplex* w1 = table[k].w1.data(); - size_t lc = stride; - do{ - vtype r0, r1; - vtype i0, i1; - - r0 = T0[0]; - i0 = T0[1]; - r1 = T1[0]; - i1 = T1[1]; - Butterflies::butterfly2( - r0, i0, - r1, i1, w1[0].r, w1[0].i - ); - T0[0] = r0; - T0[1] = i0; - T1[0] = r1; - T1[1] = i1; - - T0 += 2; - T1 += 2; - w1++; - }while (--lc); -} -static PA_FORCE_INLINE void reduce4(const TwiddleTable& table, int k, vtype* T){ - size_t stride = (size_t)1 << (k - 2 - Context::VECTOR_K); - vtype* T0 = T; - vtype* T1 = T0 + 2*stride; - vtype* T2 = T1 + 2*stride; - vtype* T3 = T2 + 2*stride; - const vcomplex* w1 = table[k - 1].w1.data(); - const vcomplex* w2 = table[k].w1.data(); - const vcomplex* w3 = table[k].w3.data(); - size_t lc = stride; - do{ - vtype r0, r1, r2, r3; - vtype i0, i1, i2, i3; - - r0 = T0[0]; - i0 = T0[1]; - r1 = T1[0]; - i1 = T1[1]; - r2 = T2[0]; - i2 = T2[1]; - r3 = T3[0]; - i3 = T3[1]; - Butterflies::butterfly4( - r0, i0, - r1, i1, w1[0].r, w1[0].i, - r2, i2, w2[0].r, w2[0].i, - r3, i3, w3[0].r, w3[0].i - ); - T0[0] = r0; - T0[1] = i0; - T1[0] = r1; - T1[1] = i1; - T2[0] = r2; - T2[1] = i2; - T3[0] = r3; - T3[1] = i3; - - T0 += 2; - T1 += 2; - T2 += 2; - T3 += 2; - w1++; - w2++; - w3++; - }while (--lc); -} - - - - - - -}; -} -} -} -#endif +/* ABS FFT Butterflies + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_Butterflies_H +#define PokemonAutomation_Kernels_AbsFFT_Butterflies_H + +#include "Common/Compiler.h" +#include "Kernels_AbsFFT_TwiddleTable.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ +template +struct Butterflies{ + +using vtype = typename Context::vtype; + + +static PA_FORCE_INLINE void butterfly2( + vtype& R0, vtype& I0, + vtype& R1, vtype& I1 +){ + vtype r1 = R1; + vtype i1 = I1; + R1 = Context::vsub(R0, r1); + I1 = Context::vsub(I0, i1); + R0 = Context::vadd(R0, r1); + I0 = Context::vadd(I0, i1); +} +static PA_FORCE_INLINE void butterfly2( + vtype& R0, vtype& I0, + vtype& R1, vtype& I1, vtype W1r, vtype W1i +){ + butterfly2(R0, I0, R1, I1); + Context::cmul_pp(R1, I1, W1r, W1i); +} + +static PA_FORCE_INLINE void butterfly4( + vtype& R0, vtype& I0, + vtype& R1, vtype& I1, + vtype& R2, vtype& I2, + vtype& R3, vtype& I3 +){ + vtype r0, r1, r2, r3; + vtype i0, i1, i2, i3; + + r0 = Context::vadd(R0, R2); + r2 = Context::vsub(R0, R2); + r1 = Context::vadd(R1, R3); + r3 = Context::vsub(R1, R3); + i0 = Context::vadd(I0, I2); + i2 = Context::vsub(I0, I2); + i1 = Context::vadd(I1, I3); + i3 = Context::vsub(I1, I3); + + R0 = Context::vadd(r0, r1); + R1 = Context::vsub(r0, r1); + I0 = Context::vadd(i0, i1); + I1 = Context::vsub(i0, i1); + R2 = Context::vsub(r2, i3); + R3 = Context::vadd(r2, i3); + I2 = Context::vadd(i2, r3); + I3 = Context::vsub(i2, r3); +} +static PA_FORCE_INLINE void butterfly4( + vtype& R0, vtype& I0, + vtype& R1, vtype& I1, vtype W1r, vtype W1i, + vtype& R2, vtype& I2, vtype W2r, vtype W2i, + vtype& R3, vtype& I3, vtype W3r, vtype W3i +){ + butterfly4(R0, I0, R1, I1, R2, I2, R3, I3); + Context::cmul_pp(R1, I1, W1r, W1i); + Context::cmul_pp(R2, I2, W2r, W2i); + Context::cmul_pp(R3, I3, W3r, W3i); +} + + +static PA_FORCE_INLINE void reduce2(const TwiddleTable& table, int k, vtype* T){ + size_t stride = (size_t)1 << (k - 1 - Context::VECTOR_K); + vtype* T0 = T; + vtype* T1 = T0 + 2*stride; + const vcomplex* w1 = table[k].w1.data(); + size_t lc = stride; + do{ + vtype r0, r1; + vtype i0, i1; + + r0 = T0[0]; + i0 = T0[1]; + r1 = T1[0]; + i1 = T1[1]; + Butterflies::butterfly2( + r0, i0, + r1, i1, w1[0].r, w1[0].i + ); + T0[0] = r0; + T0[1] = i0; + T1[0] = r1; + T1[1] = i1; + + T0 += 2; + T1 += 2; + w1++; + }while (--lc); +} +static PA_FORCE_INLINE void reduce4(const TwiddleTable& table, int k, vtype* T){ + size_t stride = (size_t)1 << (k - 2 - Context::VECTOR_K); + vtype* T0 = T; + vtype* T1 = T0 + 2*stride; + vtype* T2 = T1 + 2*stride; + vtype* T3 = T2 + 2*stride; + const vcomplex* w1 = table[k - 1].w1.data(); + const vcomplex* w2 = table[k].w1.data(); + const vcomplex* w3 = table[k].w3.data(); + size_t lc = stride; + do{ + vtype r0, r1, r2, r3; + vtype i0, i1, i2, i3; + + r0 = T0[0]; + i0 = T0[1]; + r1 = T1[0]; + i1 = T1[1]; + r2 = T2[0]; + i2 = T2[1]; + r3 = T3[0]; + i3 = T3[1]; + Butterflies::butterfly4( + r0, i0, + r1, i1, w1[0].r, w1[0].i, + r2, i2, w2[0].r, w2[0].i, + r3, i3, w3[0].r, w3[0].i + ); + T0[0] = r0; + T0[1] = i0; + T1[0] = r1; + T1[1] = i1; + T2[0] = r2; + T2[1] = i2; + T3[0] = r3; + T3[1] = i3; + + T0 += 2; + T1 += 2; + T2 += 2; + T3 += 2; + w1++; + w2++; + w3++; + }while (--lc); +} + + + + + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexScalar.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexScalar.h index a37cbab96d..8f814f0370 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexScalar.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexScalar.h @@ -1,201 +1,201 @@ -/* ABS FFT Complex Scalar - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_ComplexScalar_H -#define PokemonAutomation_Kernels_AbsFFT_ComplexScalar_H - -#include "Kernels_AbsFFT_Arch_Default.h" -#include "Kernels_AbsFFT_TwiddleTable.h" -#include "Kernels_AbsFFT_Butterflies.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -inline void fft_complex_t1_scalar(float T[4]){ - float r0, r1; - float i0, i1; - r0 = T[0]; - i0 = T[1]; - r1 = T[2]; - i1 = T[3]; - Butterflies::butterfly2(r0, i0, r1, i1); - T[0] = r0; - T[1] = i0; - T[2] = r1; - T[3] = i1; -} -inline void fft_complex_t2_scalar(float T[8]){ - float r0, r1, r2, r3; - float i0, i1, i2, i3; - r0 = T[0]; - i0 = T[1]; - r1 = T[2]; - i1 = T[3]; - r2 = T[4]; - i2 = T[5]; - r3 = T[6]; - i3 = T[7]; - Butterflies::butterfly4( - r0, i0, - r1, i1, - r2, i2, - r3, i3 - ); - T[0] = r0; - T[1] = i0; - T[2] = r1; - T[3] = i1; - T[4] = r2; - T[5] = i2; - T[6] = r3; - T[7] = i3; -} -inline void fft_complex_t3_scalar(float T[16]){ - { - float r0, r1, r2, r3; - float i0, i1, i2, i3; - r0 = T[ 0]; - i0 = T[ 1]; - r1 = T[ 4]; - i1 = T[ 5]; - r2 = T[ 8]; - i2 = T[ 9]; - r3 = T[12]; - i3 = T[13]; - Butterflies::butterfly4( - r0, i0, - r1, i1, - r2, i2, - r3, i3 - ); - T[ 0] = r0; - T[ 1] = i0; - T[ 4] = r1; - T[ 5] = i1; - T[ 8] = r2; - T[ 9] = i2; - T[12] = r3; - T[13] = i3; - } - { - float r0, r1, r2, r3; - float i0, i1, i2, i3; - r0 = T[ 2]; - i0 = T[ 3]; - r1 = T[ 6]; - i1 = T[ 7]; - r2 = T[10]; - i2 = T[11]; - r3 = T[14]; - i3 = T[15]; - Butterflies::butterfly4( - r0, i0, - r1, i1, 0, 1, - r2, i2, TW8_1, TW8_1, - r3, i3, -TW8_1, TW8_1 - ); - T[ 2] = r0; - T[ 3] = i0; - T[ 6] = r1; - T[ 7] = i1; - T[10] = r2; - T[11] = i2; - T[14] = r3; - T[15] = i3; - } - fft_complex_t1_scalar(T + 0); - fft_complex_t1_scalar(T + 4); - fft_complex_t1_scalar(T + 8); - fft_complex_t1_scalar(T + 12); -} - - - - -template -void reduce4_scalar(const TwiddleTable& table, int k, float* T){ - size_t stride = (size_t)1 << (k - 2); - float* T0 = T; - float* T1 = T0 + 2*stride; - float* T2 = T1 + 2*stride; - float* T3 = T2 + 2*stride; - TableRowReader w1(table[k - 1].w1.data()); - TableRowReader w2(table[k].w1.data()); - TableRowReader w3(table[k].w3.data()); - size_t c = 0; - do{ - float r0, r1, r2, r3; - float i0, i1, i2, i3; - r0 = T0[0]; - i0 = T0[1]; - r1 = T1[0]; - i1 = T1[1]; - r2 = T2[0]; - i2 = T2[1]; - r3 = T3[0]; - i3 = T3[1]; - float w1r, w1i, w2r, w2i, w3r, w3i; - w1.get(w1r, w1i, c); - w2.get(w2r, w2i, c); - w3.get(w3r, w3i, c); - Butterflies::butterfly4( - r0, i0, - r1, i1, w1r, w1i, - r2, i2, w2r, w2i, - r3, i3, w3r, w3i - ); - T0[0] = r0; - T0[1] = i0; - T1[0] = r1; - T1[1] = i1; - T2[0] = r2; - T2[1] = i2; - T3[0] = r3; - T3[1] = i3; - - T0 += 2; - T1 += 2; - T2 += 2; - T3 += 2; - c++; - }while (c < stride); -} - - -template -void fft_complex_tk_scalar(const TwiddleTable& table, int k, float* T){ - if (k == 1){ - fft_complex_t1_scalar(T); - return; - } - if (k == 2){ - fft_complex_t2_scalar(T); - return; - } - if (k == 3){ - fft_complex_t3_scalar(T); - return; - } - - reduce4_scalar(table, k, T); - - k -= 2; - size_t stride = (size_t)2 << k; - fft_complex_tk_scalar(table, k, T + 0*stride); - fft_complex_tk_scalar(table, k, T + 1*stride); - fft_complex_tk_scalar(table, k, T + 2*stride); - fft_complex_tk_scalar(table, k, T + 3*stride); -} - - - -} -} -} -#endif +/* ABS FFT Complex Scalar + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_ComplexScalar_H +#define PokemonAutomation_Kernels_AbsFFT_ComplexScalar_H + +#include "Kernels_AbsFFT_Arch_Default.h" +#include "Kernels_AbsFFT_TwiddleTable.h" +#include "Kernels_AbsFFT_Butterflies.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +inline void fft_complex_t1_scalar(float T[4]){ + float r0, r1; + float i0, i1; + r0 = T[0]; + i0 = T[1]; + r1 = T[2]; + i1 = T[3]; + Butterflies::butterfly2(r0, i0, r1, i1); + T[0] = r0; + T[1] = i0; + T[2] = r1; + T[3] = i1; +} +inline void fft_complex_t2_scalar(float T[8]){ + float r0, r1, r2, r3; + float i0, i1, i2, i3; + r0 = T[0]; + i0 = T[1]; + r1 = T[2]; + i1 = T[3]; + r2 = T[4]; + i2 = T[5]; + r3 = T[6]; + i3 = T[7]; + Butterflies::butterfly4( + r0, i0, + r1, i1, + r2, i2, + r3, i3 + ); + T[0] = r0; + T[1] = i0; + T[2] = r1; + T[3] = i1; + T[4] = r2; + T[5] = i2; + T[6] = r3; + T[7] = i3; +} +inline void fft_complex_t3_scalar(float T[16]){ + { + float r0, r1, r2, r3; + float i0, i1, i2, i3; + r0 = T[ 0]; + i0 = T[ 1]; + r1 = T[ 4]; + i1 = T[ 5]; + r2 = T[ 8]; + i2 = T[ 9]; + r3 = T[12]; + i3 = T[13]; + Butterflies::butterfly4( + r0, i0, + r1, i1, + r2, i2, + r3, i3 + ); + T[ 0] = r0; + T[ 1] = i0; + T[ 4] = r1; + T[ 5] = i1; + T[ 8] = r2; + T[ 9] = i2; + T[12] = r3; + T[13] = i3; + } + { + float r0, r1, r2, r3; + float i0, i1, i2, i3; + r0 = T[ 2]; + i0 = T[ 3]; + r1 = T[ 6]; + i1 = T[ 7]; + r2 = T[10]; + i2 = T[11]; + r3 = T[14]; + i3 = T[15]; + Butterflies::butterfly4( + r0, i0, + r1, i1, 0, 1, + r2, i2, TW8_1, TW8_1, + r3, i3, -TW8_1, TW8_1 + ); + T[ 2] = r0; + T[ 3] = i0; + T[ 6] = r1; + T[ 7] = i1; + T[10] = r2; + T[11] = i2; + T[14] = r3; + T[15] = i3; + } + fft_complex_t1_scalar(T + 0); + fft_complex_t1_scalar(T + 4); + fft_complex_t1_scalar(T + 8); + fft_complex_t1_scalar(T + 12); +} + + + + +template +void reduce4_scalar(const TwiddleTable& table, int k, float* T){ + size_t stride = (size_t)1 << (k - 2); + float* T0 = T; + float* T1 = T0 + 2*stride; + float* T2 = T1 + 2*stride; + float* T3 = T2 + 2*stride; + TableRowReader w1(table[k - 1].w1.data()); + TableRowReader w2(table[k].w1.data()); + TableRowReader w3(table[k].w3.data()); + size_t c = 0; + do{ + float r0, r1, r2, r3; + float i0, i1, i2, i3; + r0 = T0[0]; + i0 = T0[1]; + r1 = T1[0]; + i1 = T1[1]; + r2 = T2[0]; + i2 = T2[1]; + r3 = T3[0]; + i3 = T3[1]; + float w1r, w1i, w2r, w2i, w3r, w3i; + w1.get(w1r, w1i, c); + w2.get(w2r, w2i, c); + w3.get(w3r, w3i, c); + Butterflies::butterfly4( + r0, i0, + r1, i1, w1r, w1i, + r2, i2, w2r, w2i, + r3, i3, w3r, w3i + ); + T0[0] = r0; + T0[1] = i0; + T1[0] = r1; + T1[1] = i1; + T2[0] = r2; + T2[1] = i2; + T3[0] = r3; + T3[1] = i3; + + T0 += 2; + T1 += 2; + T2 += 2; + T3 += 2; + c++; + }while (c < stride); +} + + +template +void fft_complex_tk_scalar(const TwiddleTable& table, int k, float* T){ + if (k == 1){ + fft_complex_t1_scalar(T); + return; + } + if (k == 2){ + fft_complex_t2_scalar(T); + return; + } + if (k == 3){ + fft_complex_t3_scalar(T); + return; + } + + reduce4_scalar(table, k, T); + + k -= 2; + size_t stride = (size_t)2 << k; + fft_complex_tk_scalar(table, k, T + 0*stride); + fft_complex_tk_scalar(table, k, T + 1*stride); + fft_complex_tk_scalar(table, k, T + 2*stride); + fft_complex_tk_scalar(table, k, T + 3*stride); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexToAbs.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexToAbs.h index 97c499032e..13b9495c33 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexToAbs.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexToAbs.h @@ -1,78 +1,78 @@ -/* ABS FFT Complex to Abs - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_ComplexToAbs_H -#define PokemonAutomation_Kernels_AbsFFT_ComplexToAbs_H - -#include "Kernels_AbsFFT_Arch.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ -template -struct MiscRoutines{ - -using vtype = typename Context::vtype; - - -static PA_FORCE_INLINE void complex_to_abs(vtype* abs, const vtype* data, size_t vlength){ - do{ - abs[0] = Context::abs(data[0], data[1]); - abs++; - data += 2; - }while (--vlength); -} -static PA_FORCE_INLINE void complex_to_abs_swap_odd(vtype* abs, const vtype* data, size_t vlength){ - vtype* absL = abs; - vtype* absH = abs + vlength; - const vtype* dataL = data; - const vtype* dataH = data + 2*vlength; - - if (Context::VECTOR_K == 0){ - size_t lc = vlength / 4; - do{ - absH -= 2; - dataH -= 4; - - vtype L0 = Context::abs(dataL[0], dataL[1]); - vtype L1 = Context::abs(dataL[2], dataL[3]); - vtype H0 = Context::abs(dataH[0], dataH[1]); - vtype H1 = Context::abs(dataH[2], dataH[3]); - - absL[0] = L0; - absL[1] = H1; - absH[0] = H0; - absH[1] = L1; - - absL += 2; - dataL += 4; - }while (--lc); - }else{ - size_t lc = vlength / 2; - do{ - absH -= 1; - dataH -= 2; - - vtype L0 = Context::abs(dataL[0], dataL[1]); - vtype H0 = Context::abs(dataH[0], dataH[1]); - - Context::swap_odd(L0, H0); - - absL[0] = L0; - absH[0] = H0; - - absL += 1; - dataL += 2; - }while (--lc); - } -} - - -}; -} -} -} -#endif +/* ABS FFT Complex to Abs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_ComplexToAbs_H +#define PokemonAutomation_Kernels_AbsFFT_ComplexToAbs_H + +#include "Kernels_AbsFFT_Arch.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ +template +struct MiscRoutines{ + +using vtype = typename Context::vtype; + + +static PA_FORCE_INLINE void complex_to_abs(vtype* abs, const vtype* data, size_t vlength){ + do{ + abs[0] = Context::abs(data[0], data[1]); + abs++; + data += 2; + }while (--vlength); +} +static PA_FORCE_INLINE void complex_to_abs_swap_odd(vtype* abs, const vtype* data, size_t vlength){ + vtype* absL = abs; + vtype* absH = abs + vlength; + const vtype* dataL = data; + const vtype* dataH = data + 2*vlength; + + if (Context::VECTOR_K == 0){ + size_t lc = vlength / 4; + do{ + absH -= 2; + dataH -= 4; + + vtype L0 = Context::abs(dataL[0], dataL[1]); + vtype L1 = Context::abs(dataL[2], dataL[3]); + vtype H0 = Context::abs(dataH[0], dataH[1]); + vtype H1 = Context::abs(dataH[2], dataH[3]); + + absL[0] = L0; + absL[1] = H1; + absH[0] = H0; + absH[1] = L1; + + absL += 2; + dataL += 4; + }while (--lc); + }else{ + size_t lc = vlength / 2; + do{ + absH -= 1; + dataH -= 2; + + vtype L0 = Context::abs(dataL[0], dataL[1]); + vtype H0 = Context::abs(dataH[0], dataH[1]); + + Context::swap_odd(L0, H0); + + absL[0] = L0; + absH[0] = H0; + + absL += 1; + dataL += 2; + }while (--lc); + } +} + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexVector.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexVector.h index 0b9c7e696b..fe3de6ceb9 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexVector.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_ComplexVector.h @@ -1,49 +1,49 @@ -/* ABS FFT Complex Transform (Vector) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_ComplexVector_H -#define PokemonAutomation_Kernels_AbsFFT_ComplexVector_H - -#include "Kernels_AbsFFT_TwiddleTable.h" -#include "Kernels_AbsFFT_Butterflies.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - -template -void base_transform(const TwiddleTable& table, typename Context::vtype* T); - - -template -void fft_complex_tk(const TwiddleTable& table, int k, typename Context::vtype* T){ - if (k == Context::BASE_COMPLEX_TRANSFORM_K){ - base_transform(table, T); - return; - } - if (k == Context::BASE_COMPLEX_TRANSFORM_K + 1){ - Butterflies::reduce2(table, k, T); - size_t stride = 2 << (k - 1 - Context::VECTOR_K); - base_transform(table, T + 0*stride); - base_transform(table, T + 1*stride); - return; - } - - Butterflies::reduce4(table, k, T); - k -= 2; - size_t stride = 2 << (k - Context::VECTOR_K); - fft_complex_tk(table, k, T + 0*stride); - fft_complex_tk(table, k, T + 1*stride); - fft_complex_tk(table, k, T + 2*stride); - fft_complex_tk(table, k, T + 3*stride); -} - - -} -} -} -#endif +/* ABS FFT Complex Transform (Vector) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_ComplexVector_H +#define PokemonAutomation_Kernels_AbsFFT_ComplexVector_H + +#include "Kernels_AbsFFT_TwiddleTable.h" +#include "Kernels_AbsFFT_Butterflies.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + +template +void base_transform(const TwiddleTable& table, typename Context::vtype* T); + + +template +void fft_complex_tk(const TwiddleTable& table, int k, typename Context::vtype* T){ + if (k == Context::BASE_COMPLEX_TRANSFORM_K){ + base_transform(table, T); + return; + } + if (k == Context::BASE_COMPLEX_TRANSFORM_K + 1){ + Butterflies::reduce2(table, k, T); + size_t stride = 2 << (k - 1 - Context::VECTOR_K); + base_transform(table, T + 0*stride); + base_transform(table, T + 1*stride); + return; + } + + Butterflies::reduce4(table, k, T); + k -= 2; + size_t stride = 2 << (k - Context::VECTOR_K); + fft_complex_tk(table, k, T + 0*stride); + fft_complex_tk(table, k, T + 1*stride); + fft_complex_tk(table, k, T + 2*stride); + fft_complex_tk(table, k, T + 3*stride); +} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_Default.cpp b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_Default.cpp index 6f8bbcee11..5e45836227 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_Default.cpp +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_Default.cpp @@ -1,39 +1,39 @@ -/* ABS FFT (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels_AbsFFT_Arch_Default.h" -#include "Kernels_AbsFFT_TwiddleTable.tpp" -#include "Kernels_AbsFFT_FullTransform.tpp" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -template <> -void base_transform(const TwiddleTable& table, Context_Default::vtype* T){ - fft_complex_tk_scalar(table, Context_Default::BASE_COMPLEX_TRANSFORM_K, T); -} - - - -TwiddleTable& global_table_Default(){ - static TwiddleTable table(14); - return table; -} -void fft_abs_Default(int k, float* abs, float* real){ - TwiddleTable& table = global_table_Default(); - table.ensure(k); - fft_abs(table, k, abs, real); -} - - - - -} -} -} +/* ABS FFT (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels_AbsFFT_Arch_Default.h" +#include "Kernels_AbsFFT_TwiddleTable.tpp" +#include "Kernels_AbsFFT_FullTransform.tpp" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +template <> +void base_transform(const TwiddleTable& table, Context_Default::vtype* T){ + fft_complex_tk_scalar(table, Context_Default::BASE_COMPLEX_TRANSFORM_K, T); +} + + + +TwiddleTable& global_table_Default(){ + static TwiddleTable table(14); + return table; +} +void fft_abs_Default(int k, float* abs, float* real){ + TwiddleTable& table = global_table_Default(); + table.ensure(k); + fft_abs(table, k, abs, real); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp index 2fb196f929..316829b3e7 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_AVX2.cpp @@ -1,35 +1,35 @@ -/* ABS FFT (x86 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include "Kernels_AbsFFT_Arch_x86_AVX2.h" -#include "Kernels_AbsFFT_BaseTransform_x86_AVX2.h" -#include "Kernels_AbsFFT_TwiddleTable.tpp" -#include "Kernels_AbsFFT_FullTransform.tpp" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -TwiddleTable& global_table_x86_AVX2(){ - static TwiddleTable table(14); - return table; -} -void fft_abs_x86_AVX2(int k, float* abs, float* real){ - TwiddleTable& table = global_table_x86_AVX2(); - table.ensure(k); - fft_abs(table, k, abs, real); -} - - - -} -} -} -#endif +/* ABS FFT (x86 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include "Kernels_AbsFFT_Arch_x86_AVX2.h" +#include "Kernels_AbsFFT_BaseTransform_x86_AVX2.h" +#include "Kernels_AbsFFT_TwiddleTable.tpp" +#include "Kernels_AbsFFT_FullTransform.tpp" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +TwiddleTable& global_table_x86_AVX2(){ + static TwiddleTable table(14); + return table; +} +void fft_abs_x86_AVX2(int k, float* abs, float* real){ + TwiddleTable& table = global_table_x86_AVX2(); + table.ensure(k); + fft_abs(table, k, abs, real); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp index 73700171ac..688cd0459a 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Core_x86_SSE41.cpp @@ -1,35 +1,35 @@ -/* ABS FFT (x86 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include "Kernels_AbsFFT_Arch_x86_SSE41.h" -#include "Kernels_AbsFFT_BaseTransform_x86_SSE41.h" -#include "Kernels_AbsFFT_TwiddleTable.tpp" -#include "Kernels_AbsFFT_FullTransform.tpp" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -TwiddleTable& global_table_x86_SSE41(){ - static TwiddleTable table(14); - return table; -} -void fft_abs_x86_SSE41(int k, float* abs, float* real){ - TwiddleTable& table = global_table_x86_SSE41(); - table.ensure(k); - fft_abs(table, k, abs, real); -} - - - -} -} -} -#endif +/* ABS FFT (x86 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include "Kernels_AbsFFT_Arch_x86_SSE41.h" +#include "Kernels_AbsFFT_BaseTransform_x86_SSE41.h" +#include "Kernels_AbsFFT_TwiddleTable.tpp" +#include "Kernels_AbsFFT_FullTransform.tpp" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +TwiddleTable& global_table_x86_SSE41(){ + static TwiddleTable table(14); + return table; +} +void fft_abs_x86_SSE41(int k, float* abs, float* real){ + TwiddleTable& table = global_table_x86_SSE41(); + table.ensure(k); + fft_abs(table, k, abs, real); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.h index fab3212d13..2328ffc120 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.h @@ -1,28 +1,28 @@ -/* ABS FFT Full Transform - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_FullTransform_H -#define PokemonAutomation_Kernels_AbsFFT_FullTransform_H - -#include "Kernels_AbsFFT_TwiddleTable.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - -template -void fft_abs_scalar(const TwiddleTable& table, int k, float* abs, float* real); - -template -void fft_abs(const TwiddleTable& table, int k, float* abs, float* real); - - - -} -} -} -#endif +/* ABS FFT Full Transform + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_FullTransform_H +#define PokemonAutomation_Kernels_AbsFFT_FullTransform_H + +#include "Kernels_AbsFFT_TwiddleTable.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + +template +void fft_abs_scalar(const TwiddleTable& table, int k, float* abs, float* real); + +template +void fft_abs(const TwiddleTable& table, int k, float* abs, float* real); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.tpp b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.tpp index 2ac81118fe..454b4d5922 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.tpp +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_FullTransform.tpp @@ -1,142 +1,142 @@ -/* ABS FFT Full Transform - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include "Kernels_AbsFFT_BitReverse.h" -#include "Kernels_AbsFFT_ComplexToAbs.h" -#include "Kernels_AbsFFT_Reductions.h" -#include "Kernels_AbsFFT_ComplexScalar.h" -#include "Kernels_AbsFFT_ComplexVector.h" -#include "Kernels_AbsFFT_FullTransform.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -inline void fft_abs_k1(float abs[1], float real[2]){ - abs[0] = std::abs(real[0] + real[1]); -} -inline void fft_abs_k2(float abs[2], float real[4]){ - float t0, t1, t2, t3; - t0 = real[0] + real[2]; - t2 = real[0] - real[2]; - t1 = real[1] + real[3]; - t3 = real[1] - real[3]; - t0 += t1; - abs[0] = std::abs(t0); - abs[1] = std::sqrt(t2*t2 + t3*t3); -} -template -void fft_abs_k3(const TwiddleTable& table, float abs[4], float real[8]){ - const int k = 3; - const size_t block = (size_t)1 << (k - 2); - - // Initial split-radix reduction. - Reductions::fft_real_split_reduce_scalar(table, k, real, abs); - - // Transform complex upper-half. - fft_complex_tk_scalar(table, k - 2, abs); - - // Compute abs and reverse order of odd terms. - MiscRoutines::complex_to_abs(real + 3*block, abs, block); - - // Recurse into lower-half. - fft_abs_k2(real + 2*block, real); - - // Fix ordering. - real += 2*block; - - abs[0] = real[0]; - abs[1] = real[2]; - abs[2] = real[1]; - abs[3] = real[3]; -} - -template -void fft_abs_scalar(const TwiddleTable& table, int k, float* abs, float* real){ - if (k == 1){ - fft_abs_k1(abs, real); - return; - } - if (k == 2){ - fft_abs_k2(abs, real); - return; - } - if (k == 3){ - fft_abs_k3(table, abs, real); - return; - } - - size_t block = (size_t)1 << (k - 2); - - // Initial split-radix reduction. - Reductions::fft_real_split_reduce_scalar(table, k, real, abs); - - // Transform complex upper-half. - fft_complex_tk_scalar(table, k - 2, abs); - - // Compute abs and reverse order of odd terms. - MiscRoutines::complex_to_abs_swap_odd(real + 3*block, abs, block); - - // Recurse into lower-half. - fft_abs_scalar(table, k - 1, real + 2*block, real); - - // Fix ordering. - real += 2*block; - BitReverse::bitreverse_f32v1_ip(k - 2, real + block, abs); - BitReverse::interleave_f32(k - 1, abs, real); -} - - -template -void fft_abs(const TwiddleTable& table, int k, float* abs, float* real){ - using vtype = typename Context::vtype; - - if (k - 2 < Context::BASE_COMPLEX_TRANSFORM_K){ - fft_abs_scalar(table, k, abs, real); - return; - } - - size_t block = (size_t)1 << (k - 2); - - // Initial split-radix reduction. - Reductions::fft_real_split_reduce(table, k, (vtype*)real, (vtype*)abs); - - // Transform complex upper-half. - fft_complex_tk(table, k - 2, (vtype*)abs); - - // Compute abs and reverse order of odd terms. - MiscRoutines::complex_to_abs_swap_odd( - (vtype*)(real + 3*block), - (vtype*)(abs), - block >> Context::VECTOR_K - ); - - // Recurse into lower-half. - fft_abs(table, k - 1, real + 2*block, real); - - // Fix ordering. - real += 2*block; - BitReverse::bitreverse_f32v1_ip(k - 2, real + block, abs); - BitReverse::interleave_f32(k - 1, abs, real); -} - - - - - - - - -} -} -} +/* ABS FFT Full Transform + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include "Kernels_AbsFFT_BitReverse.h" +#include "Kernels_AbsFFT_ComplexToAbs.h" +#include "Kernels_AbsFFT_Reductions.h" +#include "Kernels_AbsFFT_ComplexScalar.h" +#include "Kernels_AbsFFT_ComplexVector.h" +#include "Kernels_AbsFFT_FullTransform.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +inline void fft_abs_k1(float abs[1], float real[2]){ + abs[0] = std::abs(real[0] + real[1]); +} +inline void fft_abs_k2(float abs[2], float real[4]){ + float t0, t1, t2, t3; + t0 = real[0] + real[2]; + t2 = real[0] - real[2]; + t1 = real[1] + real[3]; + t3 = real[1] - real[3]; + t0 += t1; + abs[0] = std::abs(t0); + abs[1] = std::sqrt(t2*t2 + t3*t3); +} +template +void fft_abs_k3(const TwiddleTable& table, float abs[4], float real[8]){ + const int k = 3; + const size_t block = (size_t)1 << (k - 2); + + // Initial split-radix reduction. + Reductions::fft_real_split_reduce_scalar(table, k, real, abs); + + // Transform complex upper-half. + fft_complex_tk_scalar(table, k - 2, abs); + + // Compute abs and reverse order of odd terms. + MiscRoutines::complex_to_abs(real + 3*block, abs, block); + + // Recurse into lower-half. + fft_abs_k2(real + 2*block, real); + + // Fix ordering. + real += 2*block; + + abs[0] = real[0]; + abs[1] = real[2]; + abs[2] = real[1]; + abs[3] = real[3]; +} + +template +void fft_abs_scalar(const TwiddleTable& table, int k, float* abs, float* real){ + if (k == 1){ + fft_abs_k1(abs, real); + return; + } + if (k == 2){ + fft_abs_k2(abs, real); + return; + } + if (k == 3){ + fft_abs_k3(table, abs, real); + return; + } + + size_t block = (size_t)1 << (k - 2); + + // Initial split-radix reduction. + Reductions::fft_real_split_reduce_scalar(table, k, real, abs); + + // Transform complex upper-half. + fft_complex_tk_scalar(table, k - 2, abs); + + // Compute abs and reverse order of odd terms. + MiscRoutines::complex_to_abs_swap_odd(real + 3*block, abs, block); + + // Recurse into lower-half. + fft_abs_scalar(table, k - 1, real + 2*block, real); + + // Fix ordering. + real += 2*block; + BitReverse::bitreverse_f32v1_ip(k - 2, real + block, abs); + BitReverse::interleave_f32(k - 1, abs, real); +} + + +template +void fft_abs(const TwiddleTable& table, int k, float* abs, float* real){ + using vtype = typename Context::vtype; + + if (k - 2 < Context::BASE_COMPLEX_TRANSFORM_K){ + fft_abs_scalar(table, k, abs, real); + return; + } + + size_t block = (size_t)1 << (k - 2); + + // Initial split-radix reduction. + Reductions::fft_real_split_reduce(table, k, (vtype*)real, (vtype*)abs); + + // Transform complex upper-half. + fft_complex_tk(table, k - 2, (vtype*)abs); + + // Compute abs and reverse order of odd terms. + MiscRoutines::complex_to_abs_swap_odd( + (vtype*)(real + 3*block), + (vtype*)(abs), + block >> Context::VECTOR_K + ); + + // Recurse into lower-half. + fft_abs(table, k - 1, real + 2*block, real); + + // Fix ordering. + real += 2*block; + BitReverse::bitreverse_f32v1_ip(k - 2, real + block, abs); + BitReverse::interleave_f32(k - 1, abs, real); +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Reductions.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Reductions.h index 66d2e6fa55..ea3b5c53e2 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Reductions.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_Reductions.h @@ -1,86 +1,86 @@ -/* ABS FFT Reductions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_Reductions_H -#define PokemonAutomation_Kernels_AbsFFT_Reductions_H - -#include "Kernels_AbsFFT_Arch_Default.h" -#include "Kernels_AbsFFT_TwiddleTable.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ -template -struct Reductions{ - -using vtype = typename Context::vtype; - - -static PA_FORCE_INLINE void fft_real_split_reduce_scalar(const TwiddleTable& table, int k, float* real, float* upper_complex){ - size_t stride = (size_t)1 << (k - 2); - for (size_t c = 0; c < stride; c++){ - float r0 = real[c + 0*stride]; - float r1 = real[c + 1*stride]; - float r2 = real[c + 2*stride]; - float r3 = real[c + 3*stride]; - real[c + 0*stride] = r0 + r2; - real[c + 1*stride] = r1 + r3; - - r0 -= r2; - r1 -= r3; - - const vcomplex& vec = table[k].w1[c / Context::VECTOR_LENGTH]; - size_t sindex = c % Context::VECTOR_LENGTH; - - Context_Default::cmul_pp( - r0, r1, - vec.real(sindex), vec.imag(sindex) - ); - upper_complex[2*c + 0] = r0; - upper_complex[2*c + 1] = r1; - } -} - -static PA_FORCE_INLINE void fft_real_split_reduce(const TwiddleTable& table, int k, vtype* real, vtype* upper_complex){ - size_t vstride = (size_t)1 << (k - 2 - Context::VECTOR_K); - vtype* R0 = real; - vtype* R1 = R0 + vstride; - vtype* R2 = R1 + vstride; - vtype* R3 = R2 + vstride; - const vcomplex* w = table[k].w1.data(); - size_t lc = vstride; - do{ - vtype r0 = R0[0]; - vtype r1 = R1[0]; - vtype r2 = R2[0]; - vtype r3 = R3[0]; - - R0[0] = Context::vadd(r0, r2); - R1[0] = Context::vadd(r1, r3); - - r0 = Context::vsub(r0, r2); - r1 = Context::vsub(r1, r3); - Context::cmul_pp(r0, r1, w[0].r, w[0].i); - - upper_complex[0] = r0; - upper_complex[1] = r1; - - R0++; - R1++; - R2++; - R3++; - upper_complex += 2; - w++; - }while (--lc); -} - - - -}; -} -} -} -#endif +/* ABS FFT Reductions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_Reductions_H +#define PokemonAutomation_Kernels_AbsFFT_Reductions_H + +#include "Kernels_AbsFFT_Arch_Default.h" +#include "Kernels_AbsFFT_TwiddleTable.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ +template +struct Reductions{ + +using vtype = typename Context::vtype; + + +static PA_FORCE_INLINE void fft_real_split_reduce_scalar(const TwiddleTable& table, int k, float* real, float* upper_complex){ + size_t stride = (size_t)1 << (k - 2); + for (size_t c = 0; c < stride; c++){ + float r0 = real[c + 0*stride]; + float r1 = real[c + 1*stride]; + float r2 = real[c + 2*stride]; + float r3 = real[c + 3*stride]; + real[c + 0*stride] = r0 + r2; + real[c + 1*stride] = r1 + r3; + + r0 -= r2; + r1 -= r3; + + const vcomplex& vec = table[k].w1[c / Context::VECTOR_LENGTH]; + size_t sindex = c % Context::VECTOR_LENGTH; + + Context_Default::cmul_pp( + r0, r1, + vec.real(sindex), vec.imag(sindex) + ); + upper_complex[2*c + 0] = r0; + upper_complex[2*c + 1] = r1; + } +} + +static PA_FORCE_INLINE void fft_real_split_reduce(const TwiddleTable& table, int k, vtype* real, vtype* upper_complex){ + size_t vstride = (size_t)1 << (k - 2 - Context::VECTOR_K); + vtype* R0 = real; + vtype* R1 = R0 + vstride; + vtype* R2 = R1 + vstride; + vtype* R3 = R2 + vstride; + const vcomplex* w = table[k].w1.data(); + size_t lc = vstride; + do{ + vtype r0 = R0[0]; + vtype r1 = R1[0]; + vtype r2 = R2[0]; + vtype r3 = R3[0]; + + R0[0] = Context::vadd(r0, r2); + R1[0] = Context::vadd(r1, r3); + + r0 = Context::vsub(r0, r2); + r1 = Context::vsub(r1, r3); + Context::cmul_pp(r0, r1, w[0].r, w[0].i); + + upper_complex[0] = r0; + upper_complex[1] = r1; + + R0++; + R1++; + R2++; + R3++; + upper_complex += 2; + w++; + }while (--lc); +} + + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.h b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.h index 3ad922440c..ff3f4f55fb 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.h +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.h @@ -1,84 +1,84 @@ -/* ABS FFT Twiddle Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AbsFFT_TwiddleTable_H -#define PokemonAutomation_Kernels_AbsFFT_TwiddleTable_H - -#include -#include "Common/Cpp/Containers/AlignedVector.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Kernels_AbsFFT_Arch.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - - -template -AlignedVector> make_table_row(int k, double angle_multiplier, size_t length_multipler); - - -template -struct PerSizeTables{ - AlignedVector> w1; - AlignedVector> w3; -}; - - -template -class TwiddleTable{ -public: - ~TwiddleTable(); - TwiddleTable(int initial_size = 14); - - const PerSizeTables& operator[](int k) const; - void ensure(int k); - -private: - void expand(int k); - -private: - std::atomic m_size_k; - SpinLock m_resize_lock; - PerSizeTables m_tables[32]; -}; - - - -template -struct TableRowReader{ - using vtype = typename Context::vtype; - - const vcomplex* data; - - TableRowReader(const vcomplex* p_data) - : data(p_data) - {} - - - PA_FORCE_INLINE void get(float& real, float& imag, size_t index) const{ - const vcomplex& point = data[index / Context::VECTOR_LENGTH]; - size_t sindex = index % Context::VECTOR_LENGTH; - real = point.real(sindex); - imag = point.imag(sindex); - } -#if 0 - PA_FORCE_INLINE void get(vtype& real, vtype& imag, size_t index) const{ - const vcomplex& point = data[index]; - real = point.r; - imag = point.i; - } -#endif - -}; - - - -} -} -} -#endif +/* ABS FFT Twiddle Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AbsFFT_TwiddleTable_H +#define PokemonAutomation_Kernels_AbsFFT_TwiddleTable_H + +#include +#include "Common/Cpp/Containers/AlignedVector.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Kernels_AbsFFT_Arch.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + + +template +AlignedVector> make_table_row(int k, double angle_multiplier, size_t length_multipler); + + +template +struct PerSizeTables{ + AlignedVector> w1; + AlignedVector> w3; +}; + + +template +class TwiddleTable{ +public: + ~TwiddleTable(); + TwiddleTable(int initial_size = 14); + + const PerSizeTables& operator[](int k) const; + void ensure(int k); + +private: + void expand(int k); + +private: + std::atomic m_size_k; + SpinLock m_resize_lock; + PerSizeTables m_tables[32]; +}; + + + +template +struct TableRowReader{ + using vtype = typename Context::vtype; + + const vcomplex* data; + + TableRowReader(const vcomplex* p_data) + : data(p_data) + {} + + + PA_FORCE_INLINE void get(float& real, float& imag, size_t index) const{ + const vcomplex& point = data[index / Context::VECTOR_LENGTH]; + size_t sindex = index % Context::VECTOR_LENGTH; + real = point.real(sindex); + imag = point.imag(sindex); + } +#if 0 + PA_FORCE_INLINE void get(vtype& real, vtype& imag, size_t index) const{ + const vcomplex& point = data[index]; + real = point.r; + imag = point.i; + } +#endif + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.tpp b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.tpp index 77be0ec5aa..5cb033704b 100644 --- a/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.tpp +++ b/SerialPrograms/Source/Kernels/AbsFFT/Kernels_AbsFFT_TwiddleTable.tpp @@ -1,95 +1,95 @@ -/* ABS FFT Twiddle Table - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "Kernels_AbsFFT_TwiddleTable.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AbsFFT{ - - -template -AlignedVector> make_table_row(int k, double angle_multiplier, size_t length_multipler){ - if (k < 2){ - return AlignedVector>(); - } - size_t length = (size_t)1 << (k - 2); - size_t vlen = length * length_multipler / Context::VECTOR_LENGTH; - if (vlen < Context::MIN_TABLE_WIDTH){ - vlen = Context::MIN_TABLE_WIDTH; - } - AlignedVector> row(vlen); - - double w = 1.5707963267948966192 * angle_multiplier / length; - - for (size_t v = 0; v < vlen; v++){ - vcomplex& vec = row[v]; - for (size_t i = 0; i < Context::VECTOR_LENGTH; i++){ - double angle = (double)(v * Context::VECTOR_LENGTH + i) * w; - vec.real(i) = (float)std::cos(angle); - vec.imag(i) = (float)std::sin(angle); - } - } - - return row; -} - - - -template -TwiddleTable::~TwiddleTable(){} -template -TwiddleTable::TwiddleTable(int initial_size) - : m_size_k(0) -{ - expand(initial_size); -} - -template -const PerSizeTables& TwiddleTable::operator[](int k) const{ - int size_k = m_size_k.load(std::memory_order_acquire); - if (k > size_k){ - throw "Twiddle table is too small."; - } - return m_tables[k]; -} - -template -void TwiddleTable::ensure(int k){ - int size_k = m_size_k.load(std::memory_order_acquire); - if (size_k >= k){ - return; - } - expand(k); -} -template -void TwiddleTable::expand(int k){ - WriteSpinLock lg(m_resize_lock); - int size_k = m_size_k.load(std::memory_order_acquire); - if (size_k >= k){ - return; - } - if (k > 31){ - throw "Transform length limit exceeded."; - } - for (; size_k < k;){ - size_k++; - m_tables[size_k].w1 = make_table_row(size_k, 1, 2); - m_tables[size_k].w3 = make_table_row(size_k, 3, 1); - m_size_k.store(size_k, std::memory_order_release); - } -} - - - - - - -} -} -} +/* ABS FFT Twiddle Table + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "Kernels_AbsFFT_TwiddleTable.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AbsFFT{ + + +template +AlignedVector> make_table_row(int k, double angle_multiplier, size_t length_multipler){ + if (k < 2){ + return AlignedVector>(); + } + size_t length = (size_t)1 << (k - 2); + size_t vlen = length * length_multipler / Context::VECTOR_LENGTH; + if (vlen < Context::MIN_TABLE_WIDTH){ + vlen = Context::MIN_TABLE_WIDTH; + } + AlignedVector> row(vlen); + + double w = 1.5707963267948966192 * angle_multiplier / length; + + for (size_t v = 0; v < vlen; v++){ + vcomplex& vec = row[v]; + for (size_t i = 0; i < Context::VECTOR_LENGTH; i++){ + double angle = (double)(v * Context::VECTOR_LENGTH + i) * w; + vec.real(i) = (float)std::cos(angle); + vec.imag(i) = (float)std::sin(angle); + } + } + + return row; +} + + + +template +TwiddleTable::~TwiddleTable(){} +template +TwiddleTable::TwiddleTable(int initial_size) + : m_size_k(0) +{ + expand(initial_size); +} + +template +const PerSizeTables& TwiddleTable::operator[](int k) const{ + int size_k = m_size_k.load(std::memory_order_acquire); + if (k > size_k){ + throw "Twiddle table is too small."; + } + return m_tables[k]; +} + +template +void TwiddleTable::ensure(int k){ + int size_k = m_size_k.load(std::memory_order_acquire); + if (size_k >= k){ + return; + } + expand(k); +} +template +void TwiddleTable::expand(int k){ + WriteSpinLock lg(m_resize_lock); + int size_k = m_size_k.load(std::memory_order_acquire); + if (size_k >= k){ + return; + } + if (k > 31){ + throw "Transform length limit exceeded."; + } + for (; size_k < k;){ + size_k++; + m_tables[size_k].w1 = make_table_row(size_k, 1, 2); + m_tables[size_k].w3 = make_table_row(size_k, 3, 1); + m_size_k.store(size_k, std::memory_order_release); + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.cpp b/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.cpp index 68d63bc03f..2e09f6cf13 100644 --- a/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.cpp +++ b/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.cpp @@ -1,52 +1,52 @@ -/* Disjoint Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include - -#include "Kernels_Algorithm_DisjointSet.h" - -namespace PokemonAutomation{ -namespace Kernels{ - -DisjointSet::DisjointSet(size_t size) : m_parent(size), m_size(size, 1){ - std::iota(m_parent.begin(), m_parent.end(), 0); -} - -size_t DisjointSet::find(size_t x){ - // while x is not root - while (m_parent[x] != x){ - m_parent[x] = m_parent[m_parent[x]]; - x = m_parent[x]; - } - return x; -} - -void DisjointSet::merge(size_t x, size_t y){ - x = find(x); - y = find(y); - - if (x == y){ - // input parameter x and y are from the same set: - return; - } - - // make sure size(x) >= size(y) - if (m_size[x] < m_size[y]){ - std::swap(x, y); - } - - m_parent[y] = x; - m_size[x] += m_size[y]; -} - -size_t DisjointSet::set_size(size_t x){ - x = find(x); // find root - return m_size[x]; -} - -} -} +/* Disjoint Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include + +#include "Kernels_Algorithm_DisjointSet.h" + +namespace PokemonAutomation{ +namespace Kernels{ + +DisjointSet::DisjointSet(size_t size) : m_parent(size), m_size(size, 1){ + std::iota(m_parent.begin(), m_parent.end(), 0); +} + +size_t DisjointSet::find(size_t x){ + // while x is not root + while (m_parent[x] != x){ + m_parent[x] = m_parent[m_parent[x]]; + x = m_parent[x]; + } + return x; +} + +void DisjointSet::merge(size_t x, size_t y){ + x = find(x); + y = find(y); + + if (x == y){ + // input parameter x and y are from the same set: + return; + } + + // make sure size(x) >= size(y) + if (m_size[x] < m_size[y]){ + std::swap(x, y); + } + + m_parent[y] = x; + m_size[x] += m_size[y]; +} + +size_t DisjointSet::set_size(size_t x){ + x = find(x); // find root + return m_size[x]; +} + +} +} diff --git a/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h b/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h index 604e3725a2..e94de6cf03 100644 --- a/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h +++ b/SerialPrograms/Source/Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h @@ -1,43 +1,43 @@ -/* Disjoint Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Algorithm_DisjointSet_H -#define PokemonAutomation_Kernels_Algorithm_DisjointSet_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - -// https://en.wikipedia.org/wiki/Disjoint-set_data_structure -class DisjointSet{ -public: - // size: num elements - DisjointSet(size_t size); - - // Find the representative element of the set x belongs to - // x range: [0, size) - size_t find(size_t x); - - // Merge the two sets x and y belong to - // x, y range: [0, size) - void merge(size_t x, size_t y); - - // Size of the set where element x belongs to. - // x range: [0, size) - size_t set_size(size_t x); - - -private: - std::vector m_parent; - std::vector m_size; -}; - - -} -} -#endif +/* Disjoint Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Algorithm_DisjointSet_H +#define PokemonAutomation_Kernels_Algorithm_DisjointSet_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + +// https://en.wikipedia.org/wiki/Disjoint-set_data_structure +class DisjointSet{ +public: + // size: num elements + DisjointSet(size_t size); + + // Find the representative element of the set x belongs to + // x range: [0, size) + size_t find(size_t x); + + // Merge the two sets x and y belong to + // x, y range: [0, size) + void merge(size_t x, size_t y); + + // Size of the set where element x belongs to. + // x range: [0, size) + size_t set_size(size_t x); + + +private: + std::vector m_parent; + std::vector m_size; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.cpp b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.cpp index 4e5c2d7fe9..b73bbeb3fa 100644 --- a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.cpp +++ b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.cpp @@ -1,92 +1,92 @@ -/* Audio Stream Conversion - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "AudioStreamConversion.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AudioStreamConversion{ - - - -void convert_audio_uint8_to_float_Default(float* f, const uint8_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_uint8_Default(uint8_t* i, const float* f, size_t length); -void convert_audio_sint16_to_float_Default(float* f, const int16_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_sint16_Default(int16_t* i, const float* f, size_t length); -void convert_audio_sint32_to_float_Default(float* f, const int32_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_sint32_Default(int32_t* i, const float* f, size_t length); - -void convert_audio_uint8_to_float_x86_SSE41(float* f, const uint8_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_uint8_x86_SSE41(uint8_t* i, const float* f, size_t length); -void convert_audio_sint16_to_float_x86_SSE41(float* f, const int16_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_sint16_x86_SSE41(int16_t* i, const float* f, size_t length); -void convert_audio_sint32_to_float_x86_SSE2(float* f, const int32_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_sint32_x86_SSE2(int32_t* i, const float* f, size_t length); - - - - -void convert_audio_uint8_to_float(float* f, const uint8_t* i, size_t length, float output_multiplier){ -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - convert_audio_uint8_to_float_x86_SSE41(f, i, length, output_multiplier); - return; - } -#endif - convert_audio_uint8_to_float_Default(f, i, length, output_multiplier); -} -void convert_audio_float_to_uint8(uint8_t* i, const float* f, size_t length){ -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - convert_audio_float_to_uint8_x86_SSE41(i, f, length); - return; - } -#endif - convert_audio_float_to_uint8_Default(i, f, length); -} -void convert_audio_sint16_to_float(float* f, const int16_t* i, size_t length, float output_multiplier){ -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - convert_audio_sint16_to_float_x86_SSE41(f, i, length, output_multiplier); - return; - } -#endif - convert_audio_sint16_to_float_Default(f, i, length, output_multiplier); -} -void convert_audio_float_to_sint16(int16_t* i, const float* f, size_t length){ -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - convert_audio_float_to_sint16_x86_SSE41(i, f, length); - return; - } -#endif - convert_audio_float_to_sint16_Default(i, f, length); -} -void convert_audio_sint32_to_float(float* f, const int32_t* i, size_t length, float output_multiplier){ -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - convert_audio_sint32_to_float_x86_SSE2(f, i, length, output_multiplier); - return; - } -#endif - convert_audio_sint32_to_float_Default(f, i, length, output_multiplier); -} -void convert_audio_float_to_sint32(int32_t* i, const float* f, size_t length){ -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - convert_audio_float_to_sint32_x86_SSE2(i, f, length); - return; - } -#endif - convert_audio_float_to_sint32_Default(i, f, length); -} - - - -} -} -} +/* Audio Stream Conversion + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "AudioStreamConversion.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AudioStreamConversion{ + + + +void convert_audio_uint8_to_float_Default(float* f, const uint8_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_uint8_Default(uint8_t* i, const float* f, size_t length); +void convert_audio_sint16_to_float_Default(float* f, const int16_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_sint16_Default(int16_t* i, const float* f, size_t length); +void convert_audio_sint32_to_float_Default(float* f, const int32_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_sint32_Default(int32_t* i, const float* f, size_t length); + +void convert_audio_uint8_to_float_x86_SSE41(float* f, const uint8_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_uint8_x86_SSE41(uint8_t* i, const float* f, size_t length); +void convert_audio_sint16_to_float_x86_SSE41(float* f, const int16_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_sint16_x86_SSE41(int16_t* i, const float* f, size_t length); +void convert_audio_sint32_to_float_x86_SSE2(float* f, const int32_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_sint32_x86_SSE2(int32_t* i, const float* f, size_t length); + + + + +void convert_audio_uint8_to_float(float* f, const uint8_t* i, size_t length, float output_multiplier){ +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + convert_audio_uint8_to_float_x86_SSE41(f, i, length, output_multiplier); + return; + } +#endif + convert_audio_uint8_to_float_Default(f, i, length, output_multiplier); +} +void convert_audio_float_to_uint8(uint8_t* i, const float* f, size_t length){ +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + convert_audio_float_to_uint8_x86_SSE41(i, f, length); + return; + } +#endif + convert_audio_float_to_uint8_Default(i, f, length); +} +void convert_audio_sint16_to_float(float* f, const int16_t* i, size_t length, float output_multiplier){ +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + convert_audio_sint16_to_float_x86_SSE41(f, i, length, output_multiplier); + return; + } +#endif + convert_audio_sint16_to_float_Default(f, i, length, output_multiplier); +} +void convert_audio_float_to_sint16(int16_t* i, const float* f, size_t length){ +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + convert_audio_float_to_sint16_x86_SSE41(i, f, length); + return; + } +#endif + convert_audio_float_to_sint16_Default(i, f, length); +} +void convert_audio_sint32_to_float(float* f, const int32_t* i, size_t length, float output_multiplier){ +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + convert_audio_sint32_to_float_x86_SSE2(f, i, length, output_multiplier); + return; + } +#endif + convert_audio_sint32_to_float_Default(f, i, length, output_multiplier); +} +void convert_audio_float_to_sint32(int32_t* i, const float* f, size_t length){ +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + convert_audio_float_to_sint32_x86_SSE2(i, f, length); + return; + } +#endif + convert_audio_float_to_sint32_Default(i, f, length); +} + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.h b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.h index 410abe41b5..040a1cd853 100644 --- a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.h +++ b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion.h @@ -1,33 +1,33 @@ -/* Audio Stream Conversion - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AudioStreamConversion_H -#define PokemonAutomation_Kernels_AudioStreamConversion_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AudioStreamConversion{ - - -void convert_audio_uint8_to_float(float* f, const uint8_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_uint8(uint8_t* i, const float* f, size_t length); - -void convert_audio_sint16_to_float(float* f, const int16_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_sint16(int16_t* i, const float* f, size_t length); - -void convert_audio_sint32_to_float(float* f, const int32_t* i, size_t length, float output_multiplier); -void convert_audio_float_to_sint32(int32_t* i, const float* f, size_t length); - - - - -} -} -} -#endif +/* Audio Stream Conversion + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AudioStreamConversion_H +#define PokemonAutomation_Kernels_AudioStreamConversion_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AudioStreamConversion{ + + +void convert_audio_uint8_to_float(float* f, const uint8_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_uint8(uint8_t* i, const float* f, size_t length); + +void convert_audio_sint16_to_float(float* f, const int16_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_sint16(int16_t* i, const float* f, size_t length); + +void convert_audio_sint32_to_float(float* f, const int32_t* i, size_t length, float output_multiplier); +void convert_audio_float_to_sint32(int32_t* i, const float* f, size_t length); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_Default.cpp b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_Default.cpp index b5e6e1e383..d97306af6b 100644 --- a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_Default.cpp +++ b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_Default.cpp @@ -1,78 +1,78 @@ -/* Audio Stream Conversion (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "AudioStreamConversion.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AudioStreamConversion{ - - - -void convert_audio_uint8_to_float_Default(float* f, const uint8_t* i, size_t length, float output_multiplier){ - const float SCALE = output_multiplier / 127.f; - for (size_t c = 0; c < length; c++){ - float x = (float)i[c] * SCALE - output_multiplier; - x = std::max(x, -1.0f); - x = std::min(x, 1.0f); - f[c] = x; - } -} -void convert_audio_float_to_uint8_Default(uint8_t* i, const float* f, size_t length){ - for (size_t c = 0; c < length; c++){ - float r = (f[c] + 1.0f) * 127.f; - r = std::min(r, 255.f); - r = std::max(r, 0.f); - r += 0.5; - i[c] = (uint8_t)r; - } -} - -void convert_audio_sint16_to_float_Default(float* f, const int16_t* i, size_t length, float output_multiplier){ - const float SCALE = output_multiplier / 32767.f; - for (size_t c = 0; c < length; c++){ - float x = (float)i[c] * SCALE; - x = std::max(x, -1.0f); - x = std::min(x, 1.0f); - f[c] = x; - } -} -void convert_audio_float_to_sint16_Default(int16_t* i, const float* f, size_t length){ - for (size_t c = 0; c < length; c++){ - float r = f[c] * 32767.f; - r = std::min(r, 32767.f); - r = std::max(r, -32768.f); - r += r > 0 ? 0.5f : -0.5f; - i[c] = (int16_t)r; - } -} - -void convert_audio_sint32_to_float_Default(float* f, const int32_t* i, size_t length, float output_multiplier){ - const float SCALE = output_multiplier / 2147483647.f; - for (size_t c = 0; c < length; c++){ - float x = (float)i[c] * SCALE; - x = std::max(x, -1.0f); - x = std::min(x, 1.0f); - f[c] = x; - } -} -void convert_audio_float_to_sint32_Default(int32_t* i, const float* f, size_t length){ - for (size_t c = 0; c < length; c++){ - double r = f[c] * 2147483647.; - r = std::min(r, 2147483647.); - r = std::max(r, -2147483648.); - r += r > 0 ? 0.5 : -0.5; - i[c] = (int32_t)r; - } -} - - - - -} -} -} +/* Audio Stream Conversion (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "AudioStreamConversion.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AudioStreamConversion{ + + + +void convert_audio_uint8_to_float_Default(float* f, const uint8_t* i, size_t length, float output_multiplier){ + const float SCALE = output_multiplier / 127.f; + for (size_t c = 0; c < length; c++){ + float x = (float)i[c] * SCALE - output_multiplier; + x = std::max(x, -1.0f); + x = std::min(x, 1.0f); + f[c] = x; + } +} +void convert_audio_float_to_uint8_Default(uint8_t* i, const float* f, size_t length){ + for (size_t c = 0; c < length; c++){ + float r = (f[c] + 1.0f) * 127.f; + r = std::min(r, 255.f); + r = std::max(r, 0.f); + r += 0.5; + i[c] = (uint8_t)r; + } +} + +void convert_audio_sint16_to_float_Default(float* f, const int16_t* i, size_t length, float output_multiplier){ + const float SCALE = output_multiplier / 32767.f; + for (size_t c = 0; c < length; c++){ + float x = (float)i[c] * SCALE; + x = std::max(x, -1.0f); + x = std::min(x, 1.0f); + f[c] = x; + } +} +void convert_audio_float_to_sint16_Default(int16_t* i, const float* f, size_t length){ + for (size_t c = 0; c < length; c++){ + float r = f[c] * 32767.f; + r = std::min(r, 32767.f); + r = std::max(r, -32768.f); + r += r > 0 ? 0.5f : -0.5f; + i[c] = (int16_t)r; + } +} + +void convert_audio_sint32_to_float_Default(float* f, const int32_t* i, size_t length, float output_multiplier){ + const float SCALE = output_multiplier / 2147483647.f; + for (size_t c = 0; c < length; c++){ + float x = (float)i[c] * SCALE; + x = std::max(x, -1.0f); + x = std::min(x, 1.0f); + f[c] = x; + } +} +void convert_audio_float_to_sint32_Default(int32_t* i, const float* f, size_t length){ + for (size_t c = 0; c < length; c++){ + double r = f[c] * 2147483647.; + r = std::min(r, 2147483647.); + r = std::max(r, -2147483648.); + r += r > 0 ? 0.5 : -0.5; + i[c] = (int32_t)r; + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp index e96c1ea7aa..48b059d824 100644 --- a/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp +++ b/SerialPrograms/Source/Kernels/AudioStreamConversion/AudioStreamConversion_Core_x86_SSE41.cpp @@ -1,190 +1,190 @@ -/* Audio Stream Conversion (x86 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include -#include "AudioStreamConversion.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace AudioStreamConversion{ - - - -void convert_audio_uint8_to_float_x86_SSE41(float* f, const uint8_t* i, size_t length, float output_multiplier){ - const __m128 SCALE = _mm_set1_ps(output_multiplier / 127.f); - const __m128 SUB = _mm_set1_ps(output_multiplier); - size_t lc = length / 4; - while (lc--){ -#if __GNUC__ - __m128i i0 = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(*(int32_t*)i)); -#else - __m128i i0 = _mm_cvtepu8_epi32(_mm_loadu_si32(i)); -#endif - __m128 f0 = _mm_cvtepi32_ps(i0); - f0 = _mm_mul_ps(f0, SCALE); - f0 = _mm_sub_ps(f0, SUB); - f0 = _mm_max_ps(f0, _mm_set1_ps(-1.0f)); - f0 = _mm_min_ps(f0, _mm_set1_ps(1.0f)); - _mm_storeu_ps(f, f0); - f += 4; - i += 4; - } - - length %= 4; - while (length--){ - __m128 f0 = _mm_cvtsi32_ss(_mm_setzero_ps(), i[0]); - f0 = _mm_mul_ss(f0, SCALE); - f0 = _mm_sub_ss(f0, SUB); - f0 = _mm_max_ss(f0, _mm_set1_ps(-1.0f)); - f0 = _mm_min_ss(f0, _mm_set1_ps(1.0f)); - _mm_store_ss(f, f0); - f += 1; - i += 1; - } -} -void convert_audio_float_to_uint8_x86_SSE41(uint8_t* i, const float* f, size_t length){ - size_t lc = length / 4; - while (lc--){ - __m128 f0 = _mm_loadu_ps(f); - f0 = _mm_add_ps(f0, _mm_set1_ps(1.0f)); - f0 = _mm_mul_ps(f0, _mm_set1_ps(127.f)); - f0 = _mm_min_ps(f0, _mm_set1_ps(255.f)); - f0 = _mm_max_ps(f0, _mm_set1_ps(0.f)); - __m128i i0 = _mm_cvtps_epi32(f0); - i0 = _mm_shuffle_epi8(i0, _mm_setr_epi8(0, 4, 8, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); -#if __GNUC__ && __GNUC__ < 9 - *(int32_t*)i = _mm_cvtsi128_si32(i0); -#else - _mm_storeu_si32((__m128i*)i, i0); -#endif - f += 4; - i += 4; - } - - length %= 4; - while (length--){ - __m128 f0 = _mm_load_ss(f); - f0 = _mm_add_ss(f0, _mm_set1_ps(1.0f)); - f0 = _mm_mul_ss(f0, _mm_set1_ps(127.f)); - f0 = _mm_min_ss(f0, _mm_set1_ps(255.f)); - f0 = _mm_max_ss(f0, _mm_set1_ps(0.f)); - i[0] = (uint8_t)_mm_cvt_ss2si(f0); - f += 1; - i += 1; - } -} - -void convert_audio_sint16_to_float_x86_SSE41(float* f, const int16_t* i, size_t length, float output_multiplier){ - const __m128 SCALE = _mm_set1_ps(output_multiplier / 32767.f); - size_t lc = length / 4; - while (lc--){ - __m128i i0 = _mm_cvtepi16_epi32(_mm_loadl_epi64((const __m128i*)i)); - __m128 f0 = _mm_cvtepi32_ps(i0); - f0 = _mm_mul_ps(f0, SCALE); - f0 = _mm_max_ps(f0, _mm_set1_ps(-1.0f)); - f0 = _mm_min_ps(f0, _mm_set1_ps(1.0f)); - _mm_storeu_ps(f, f0); - f += 4; - i += 4; - } - - length %= 4; - while (length--){ - __m128 f0 = _mm_cvtsi32_ss(_mm_setzero_ps(), i[0]); - f0 = _mm_mul_ss(f0, SCALE); - f0 = _mm_max_ss(f0, _mm_set1_ps(-1.0f)); - f0 = _mm_min_ss(f0, _mm_set1_ps(1.0f)); - _mm_store_ss(f, f0); - f += 1; - i += 1; - } -} -void convert_audio_float_to_sint16_x86_SSE41(int16_t* i, const float* f, size_t length){ - size_t lc = length / 4; - while (lc--){ - __m128 f0 = _mm_loadu_ps(f); - f0 = _mm_mul_ps(f0, _mm_set1_ps(32767.f)); - f0 = _mm_min_ps(f0, _mm_set1_ps(32767.f)); - f0 = _mm_max_ps(f0, _mm_set1_ps(-32768.f)); - __m128i i0 = _mm_cvtps_epi32(f0); - i0 = _mm_shuffle_epi8(i0, _mm_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1)); - _mm_storel_epi64((__m128i*)i, i0); - f += 4; - i += 4; - } - - length %= 4; - while (length--){ - __m128 f0 = _mm_load_ss(f); - f0 = _mm_mul_ss(f0, _mm_set1_ps(32767.f)); - f0 = _mm_min_ss(f0, _mm_set1_ps(32767.f)); - f0 = _mm_max_ss(f0, _mm_set1_ps(-32768.f)); - i[0] = (int16_t)_mm_cvt_ss2si(f0); - f += 1; - i += 1; - } -} - -void convert_audio_sint32_to_float_x86_SSE2(float* f, const int32_t* i, size_t length, float output_multiplier){ - const __m128 SCALE = _mm_set1_ps(output_multiplier / 2147483647.f); - size_t lc = length / 4; - while (lc--){ - __m128i i0 = _mm_loadu_si128((const __m128i*)i); - __m128 f0 = _mm_cvtepi32_ps(i0); - f0 = _mm_mul_ps(f0, SCALE); - f0 = _mm_max_ps(f0, _mm_set1_ps(-1.0f)); - f0 = _mm_min_ps(f0, _mm_set1_ps(1.0f)); - _mm_storeu_ps(f, f0); - f += 4; - i += 4; - } - - length %= 4; - while (length--){ - __m128 f0 = _mm_cvtsi32_ss(_mm_setzero_ps(), i[0]); - f0 = _mm_mul_ss(f0, SCALE); - f0 = _mm_min_ss(f0, _mm_set1_ps(32767.f)); - f0 = _mm_max_ss(f0, _mm_set1_ps(-32768.f)); - _mm_store_ss(f, f0); - f += 1; - i += 1; - } -} -void convert_audio_float_to_sint32_x86_SSE2(int32_t* i, const float* f, size_t length){ - size_t lc = length / 4; - while (lc--){ - __m128 f0 = _mm_loadu_ps(f); - f0 = _mm_mul_ps(f0, _mm_set1_ps(2147483647.f)); - f0 = _mm_min_ps(f0, _mm_set1_ps(2147483520.f)); // 2^31 - 2^6 - f0 = _mm_max_ps(f0, _mm_set1_ps(-2147483648.f)); - __m128i i0 = _mm_cvtps_epi32(f0); - _mm_storeu_si128((__m128i*)i, i0); - f += 4; - i += 4; - } - - length %= 4; - while (length--){ - __m128 f0 = _mm_load_ss(f); - f0 = _mm_mul_ss(f0, _mm_set1_ps(2147483647.f)); - f0 = _mm_min_ss(f0, _mm_set1_ps(2147483520.f)); // 2^31 - 2^6 - f0 = _mm_max_ss(f0, _mm_set1_ps(-2147483648.f)); - i[0] = _mm_cvt_ss2si(f0); - f += 1; - i += 1; - } -} - - - - -} -} -} -#endif +/* Audio Stream Conversion (x86 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include +#include "AudioStreamConversion.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace AudioStreamConversion{ + + + +void convert_audio_uint8_to_float_x86_SSE41(float* f, const uint8_t* i, size_t length, float output_multiplier){ + const __m128 SCALE = _mm_set1_ps(output_multiplier / 127.f); + const __m128 SUB = _mm_set1_ps(output_multiplier); + size_t lc = length / 4; + while (lc--){ +#if __GNUC__ + __m128i i0 = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(*(int32_t*)i)); +#else + __m128i i0 = _mm_cvtepu8_epi32(_mm_loadu_si32(i)); +#endif + __m128 f0 = _mm_cvtepi32_ps(i0); + f0 = _mm_mul_ps(f0, SCALE); + f0 = _mm_sub_ps(f0, SUB); + f0 = _mm_max_ps(f0, _mm_set1_ps(-1.0f)); + f0 = _mm_min_ps(f0, _mm_set1_ps(1.0f)); + _mm_storeu_ps(f, f0); + f += 4; + i += 4; + } + + length %= 4; + while (length--){ + __m128 f0 = _mm_cvtsi32_ss(_mm_setzero_ps(), i[0]); + f0 = _mm_mul_ss(f0, SCALE); + f0 = _mm_sub_ss(f0, SUB); + f0 = _mm_max_ss(f0, _mm_set1_ps(-1.0f)); + f0 = _mm_min_ss(f0, _mm_set1_ps(1.0f)); + _mm_store_ss(f, f0); + f += 1; + i += 1; + } +} +void convert_audio_float_to_uint8_x86_SSE41(uint8_t* i, const float* f, size_t length){ + size_t lc = length / 4; + while (lc--){ + __m128 f0 = _mm_loadu_ps(f); + f0 = _mm_add_ps(f0, _mm_set1_ps(1.0f)); + f0 = _mm_mul_ps(f0, _mm_set1_ps(127.f)); + f0 = _mm_min_ps(f0, _mm_set1_ps(255.f)); + f0 = _mm_max_ps(f0, _mm_set1_ps(0.f)); + __m128i i0 = _mm_cvtps_epi32(f0); + i0 = _mm_shuffle_epi8(i0, _mm_setr_epi8(0, 4, 8, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); +#if __GNUC__ && __GNUC__ < 9 + *(int32_t*)i = _mm_cvtsi128_si32(i0); +#else + _mm_storeu_si32((__m128i*)i, i0); +#endif + f += 4; + i += 4; + } + + length %= 4; + while (length--){ + __m128 f0 = _mm_load_ss(f); + f0 = _mm_add_ss(f0, _mm_set1_ps(1.0f)); + f0 = _mm_mul_ss(f0, _mm_set1_ps(127.f)); + f0 = _mm_min_ss(f0, _mm_set1_ps(255.f)); + f0 = _mm_max_ss(f0, _mm_set1_ps(0.f)); + i[0] = (uint8_t)_mm_cvt_ss2si(f0); + f += 1; + i += 1; + } +} + +void convert_audio_sint16_to_float_x86_SSE41(float* f, const int16_t* i, size_t length, float output_multiplier){ + const __m128 SCALE = _mm_set1_ps(output_multiplier / 32767.f); + size_t lc = length / 4; + while (lc--){ + __m128i i0 = _mm_cvtepi16_epi32(_mm_loadl_epi64((const __m128i*)i)); + __m128 f0 = _mm_cvtepi32_ps(i0); + f0 = _mm_mul_ps(f0, SCALE); + f0 = _mm_max_ps(f0, _mm_set1_ps(-1.0f)); + f0 = _mm_min_ps(f0, _mm_set1_ps(1.0f)); + _mm_storeu_ps(f, f0); + f += 4; + i += 4; + } + + length %= 4; + while (length--){ + __m128 f0 = _mm_cvtsi32_ss(_mm_setzero_ps(), i[0]); + f0 = _mm_mul_ss(f0, SCALE); + f0 = _mm_max_ss(f0, _mm_set1_ps(-1.0f)); + f0 = _mm_min_ss(f0, _mm_set1_ps(1.0f)); + _mm_store_ss(f, f0); + f += 1; + i += 1; + } +} +void convert_audio_float_to_sint16_x86_SSE41(int16_t* i, const float* f, size_t length){ + size_t lc = length / 4; + while (lc--){ + __m128 f0 = _mm_loadu_ps(f); + f0 = _mm_mul_ps(f0, _mm_set1_ps(32767.f)); + f0 = _mm_min_ps(f0, _mm_set1_ps(32767.f)); + f0 = _mm_max_ps(f0, _mm_set1_ps(-32768.f)); + __m128i i0 = _mm_cvtps_epi32(f0); + i0 = _mm_shuffle_epi8(i0, _mm_setr_epi8(0, 1, 4, 5, 8, 9, 12, 13, -1, -1, -1, -1, -1, -1, -1, -1)); + _mm_storel_epi64((__m128i*)i, i0); + f += 4; + i += 4; + } + + length %= 4; + while (length--){ + __m128 f0 = _mm_load_ss(f); + f0 = _mm_mul_ss(f0, _mm_set1_ps(32767.f)); + f0 = _mm_min_ss(f0, _mm_set1_ps(32767.f)); + f0 = _mm_max_ss(f0, _mm_set1_ps(-32768.f)); + i[0] = (int16_t)_mm_cvt_ss2si(f0); + f += 1; + i += 1; + } +} + +void convert_audio_sint32_to_float_x86_SSE2(float* f, const int32_t* i, size_t length, float output_multiplier){ + const __m128 SCALE = _mm_set1_ps(output_multiplier / 2147483647.f); + size_t lc = length / 4; + while (lc--){ + __m128i i0 = _mm_loadu_si128((const __m128i*)i); + __m128 f0 = _mm_cvtepi32_ps(i0); + f0 = _mm_mul_ps(f0, SCALE); + f0 = _mm_max_ps(f0, _mm_set1_ps(-1.0f)); + f0 = _mm_min_ps(f0, _mm_set1_ps(1.0f)); + _mm_storeu_ps(f, f0); + f += 4; + i += 4; + } + + length %= 4; + while (length--){ + __m128 f0 = _mm_cvtsi32_ss(_mm_setzero_ps(), i[0]); + f0 = _mm_mul_ss(f0, SCALE); + f0 = _mm_min_ss(f0, _mm_set1_ps(32767.f)); + f0 = _mm_max_ss(f0, _mm_set1_ps(-32768.f)); + _mm_store_ss(f, f0); + f += 1; + i += 1; + } +} +void convert_audio_float_to_sint32_x86_SSE2(int32_t* i, const float* f, size_t length){ + size_t lc = length / 4; + while (lc--){ + __m128 f0 = _mm_loadu_ps(f); + f0 = _mm_mul_ps(f0, _mm_set1_ps(2147483647.f)); + f0 = _mm_min_ps(f0, _mm_set1_ps(2147483520.f)); // 2^31 - 2^6 + f0 = _mm_max_ps(f0, _mm_set1_ps(-2147483648.f)); + __m128i i0 = _mm_cvtps_epi32(f0); + _mm_storeu_si128((__m128i*)i, i0); + f += 4; + i += 4; + } + + length %= 4; + while (length--){ + __m128 f0 = _mm_load_ss(f); + f0 = _mm_mul_ss(f0, _mm_set1_ps(2147483647.f)); + f0 = _mm_min_ss(f0, _mm_set1_ps(2147483520.f)); // 2^31 - 2^6 + f0 = _mm_max_ss(f0, _mm_set1_ps(-2147483648.f)); + i[0] = _mm_cvt_ss2si(f0); + f += 1; + i += 1; + } +} + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.cpp index a4ed4584d5..2663c2668d 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.cpp @@ -1,283 +1,283 @@ -/* Binary Image Basic Filters - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -void filter_by_mask_64x4_Default (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); -void filter_by_mask_64x8_x64_SSE42 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); -void filter_by_mask_64x16_x64_AVX2 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); -void filter_by_mask_64x32_x64_AVX512 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); -void filter_by_mask_64x64_x64_AVX512 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); -void filter_by_mask_64x8_arm64_NEON (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); - -void filter_by_mask( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replace_with, - bool replace_if_zero // If false, replace if one. -){ - switch (matrix.type()){ -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - filter_by_mask_64x64_x64_AVX512(matrix, image, bytes_per_row, replace_with, replace_if_zero); - return; - case BinaryMatrixType::i64x32_x64_AVX512: - filter_by_mask_64x32_x64_AVX512(matrix, image, bytes_per_row, replace_with, replace_if_zero); - return; -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - filter_by_mask_64x16_x64_AVX2(matrix, image, bytes_per_row, replace_with, replace_if_zero); - return; -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - filter_by_mask_64x8_x64_SSE42(matrix, image, bytes_per_row, replace_with, replace_if_zero); - return; -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - filter_by_mask_64x8_arm64_NEON(matrix, image, bytes_per_row, replace_with, replace_if_zero); - return; -#endif - case BinaryMatrixType::i64x4_Default: - filter_by_mask_64x4_Default(matrix, image, bytes_per_row, replace_with, replace_if_zero); - return; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format in filter_by_mask()."); - } -} - - - -void compress_rgb32_to_binary_range_64x4_Default( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -); -void compress_rgb32_to_binary_range_64x4_Default( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - -void compress_rgb32_to_binary_range_64x8_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -); -void compress_rgb32_to_binary_range_64x8_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - -void compress_rgb32_to_binary_range_64x16_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -); -void compress_rgb32_to_binary_range_64x16_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - -void compress_rgb32_to_binary_range_64x32_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -); -void compress_rgb32_to_binary_range_64x32_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - -void compress_rgb32_to_binary_range_64x64_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -); -void compress_rgb32_to_binary_range_64x64_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - -void compress_rgb32_to_binary_range_64x8_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 -); -void compress_rgb32_to_binary_range_64x8_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - -void compress_rgb32_to_binary_range( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -){ - switch (matrix.type()){ -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - compress_rgb32_to_binary_range_64x64_x64_AVX512(image, bytes_per_row, matrix, mins, maxs); - return; - case BinaryMatrixType::i64x32_x64_AVX512: - compress_rgb32_to_binary_range_64x32_x64_AVX512(image, bytes_per_row, matrix, mins, maxs); - return; -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - compress_rgb32_to_binary_range_64x16_x64_AVX2(image, bytes_per_row, matrix, mins, maxs); - return; -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - compress_rgb32_to_binary_range_64x8_x64_SSE42(image, bytes_per_row, matrix, mins, maxs); - return; -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - compress_rgb32_to_binary_range_64x8_arm64_NEON(image, bytes_per_row, matrix, mins, maxs); - return; -#endif - case BinaryMatrixType::i64x4_Default: - compress_rgb32_to_binary_range_64x4_Default(image, bytes_per_row, matrix, mins, maxs); - return; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format."); - } -} -void compress_rgb32_to_binary_range( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - if (filter_count == 0){ - return; - } - BinaryMatrixType type = filters[0].matrix.type(); - for (size_t c = 1; c < filter_count; c++){ - if (type != filters[c].matrix.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix formats."); - } - } - switch (type){ -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - compress_rgb32_to_binary_range_64x64_x64_AVX512(image, bytes_per_row, filters, filter_count); - return; - case BinaryMatrixType::i64x32_x64_AVX512: - compress_rgb32_to_binary_range_64x32_x64_AVX512(image, bytes_per_row, filters, filter_count); - return; -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - compress_rgb32_to_binary_range_64x16_x64_AVX2(image, bytes_per_row, filters, filter_count); - return; -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - compress_rgb32_to_binary_range_64x8_x64_SSE42(image, bytes_per_row, filters, filter_count); - return; -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - compress_rgb32_to_binary_range_64x8_arm64_NEON(image, bytes_per_row, filters, filter_count); - return; -#endif - case BinaryMatrixType::i64x4_Default: - compress_rgb32_to_binary_range_64x4_Default(image, bytes_per_row, filters, filter_count); - return; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format."); - } -} - - -void compress_rgb32_to_binary_euclidean_64x64_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -); -void compress_rgb32_to_binary_euclidean_64x32_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -); -void compress_rgb32_to_binary_euclidean_64x16_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -); -void compress_rgb32_to_binary_euclidean_64x8_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -); -void compress_rgb32_to_binary_euclidean_64x8_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -); -void compress_rgb32_to_binary_euclidean_64x4_Default( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -); -void compress_rgb32_to_binary_euclidean( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - switch (matrix.type()){ -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - compress_rgb32_to_binary_euclidean_64x64_x64_AVX512(image, bytes_per_row, matrix, expected, max_euclidean_distance); - return; - case BinaryMatrixType::i64x32_x64_AVX512: - compress_rgb32_to_binary_euclidean_64x32_x64_AVX512(image, bytes_per_row, matrix, expected, max_euclidean_distance); - return; -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - compress_rgb32_to_binary_euclidean_64x16_x64_AVX2(image, bytes_per_row, matrix, expected, max_euclidean_distance); - return; -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - compress_rgb32_to_binary_euclidean_64x8_x64_SSE42(image, bytes_per_row, matrix, expected, max_euclidean_distance); - return; -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - compress_rgb32_to_binary_euclidean_64x8_arm64_NEON(image, bytes_per_row, matrix, expected, max_euclidean_distance); - return; -#endif - case BinaryMatrixType::i64x4_Default: - compress_rgb32_to_binary_euclidean_64x4_Default(image, bytes_per_row, matrix, expected, max_euclidean_distance); - return; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format."); - } -} - - - - - - - - -} -} +/* Binary Image Basic Filters + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +void filter_by_mask_64x4_Default (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); +void filter_by_mask_64x8_x64_SSE42 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); +void filter_by_mask_64x16_x64_AVX2 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); +void filter_by_mask_64x32_x64_AVX512 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); +void filter_by_mask_64x64_x64_AVX512 (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); +void filter_by_mask_64x8_arm64_NEON (const PackedBinaryMatrix_IB& matrix, uint32_t* image, size_t bytes_per_row, uint32_t replace_with, bool replace_if_zero); + +void filter_by_mask( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replace_with, + bool replace_if_zero // If false, replace if one. +){ + switch (matrix.type()){ +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + filter_by_mask_64x64_x64_AVX512(matrix, image, bytes_per_row, replace_with, replace_if_zero); + return; + case BinaryMatrixType::i64x32_x64_AVX512: + filter_by_mask_64x32_x64_AVX512(matrix, image, bytes_per_row, replace_with, replace_if_zero); + return; +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + filter_by_mask_64x16_x64_AVX2(matrix, image, bytes_per_row, replace_with, replace_if_zero); + return; +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + filter_by_mask_64x8_x64_SSE42(matrix, image, bytes_per_row, replace_with, replace_if_zero); + return; +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + filter_by_mask_64x8_arm64_NEON(matrix, image, bytes_per_row, replace_with, replace_if_zero); + return; +#endif + case BinaryMatrixType::i64x4_Default: + filter_by_mask_64x4_Default(matrix, image, bytes_per_row, replace_with, replace_if_zero); + return; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format in filter_by_mask()."); + } +} + + + +void compress_rgb32_to_binary_range_64x4_Default( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +); +void compress_rgb32_to_binary_range_64x4_Default( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + +void compress_rgb32_to_binary_range_64x8_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +); +void compress_rgb32_to_binary_range_64x8_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + +void compress_rgb32_to_binary_range_64x16_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +); +void compress_rgb32_to_binary_range_64x16_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + +void compress_rgb32_to_binary_range_64x32_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +); +void compress_rgb32_to_binary_range_64x32_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + +void compress_rgb32_to_binary_range_64x64_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +); +void compress_rgb32_to_binary_range_64x64_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + +void compress_rgb32_to_binary_range_64x8_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 +); +void compress_rgb32_to_binary_range_64x8_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + +void compress_rgb32_to_binary_range( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +){ + switch (matrix.type()){ +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + compress_rgb32_to_binary_range_64x64_x64_AVX512(image, bytes_per_row, matrix, mins, maxs); + return; + case BinaryMatrixType::i64x32_x64_AVX512: + compress_rgb32_to_binary_range_64x32_x64_AVX512(image, bytes_per_row, matrix, mins, maxs); + return; +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + compress_rgb32_to_binary_range_64x16_x64_AVX2(image, bytes_per_row, matrix, mins, maxs); + return; +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + compress_rgb32_to_binary_range_64x8_x64_SSE42(image, bytes_per_row, matrix, mins, maxs); + return; +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + compress_rgb32_to_binary_range_64x8_arm64_NEON(image, bytes_per_row, matrix, mins, maxs); + return; +#endif + case BinaryMatrixType::i64x4_Default: + compress_rgb32_to_binary_range_64x4_Default(image, bytes_per_row, matrix, mins, maxs); + return; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format."); + } +} +void compress_rgb32_to_binary_range( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + if (filter_count == 0){ + return; + } + BinaryMatrixType type = filters[0].matrix.type(); + for (size_t c = 1; c < filter_count; c++){ + if (type != filters[c].matrix.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix formats."); + } + } + switch (type){ +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + compress_rgb32_to_binary_range_64x64_x64_AVX512(image, bytes_per_row, filters, filter_count); + return; + case BinaryMatrixType::i64x32_x64_AVX512: + compress_rgb32_to_binary_range_64x32_x64_AVX512(image, bytes_per_row, filters, filter_count); + return; +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + compress_rgb32_to_binary_range_64x16_x64_AVX2(image, bytes_per_row, filters, filter_count); + return; +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + compress_rgb32_to_binary_range_64x8_x64_SSE42(image, bytes_per_row, filters, filter_count); + return; +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + compress_rgb32_to_binary_range_64x8_arm64_NEON(image, bytes_per_row, filters, filter_count); + return; +#endif + case BinaryMatrixType::i64x4_Default: + compress_rgb32_to_binary_range_64x4_Default(image, bytes_per_row, filters, filter_count); + return; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format."); + } +} + + +void compress_rgb32_to_binary_euclidean_64x64_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +); +void compress_rgb32_to_binary_euclidean_64x32_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +); +void compress_rgb32_to_binary_euclidean_64x16_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +); +void compress_rgb32_to_binary_euclidean_64x8_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +); +void compress_rgb32_to_binary_euclidean_64x8_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +); +void compress_rgb32_to_binary_euclidean_64x4_Default( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +); +void compress_rgb32_to_binary_euclidean( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + switch (matrix.type()){ +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + compress_rgb32_to_binary_euclidean_64x64_x64_AVX512(image, bytes_per_row, matrix, expected, max_euclidean_distance); + return; + case BinaryMatrixType::i64x32_x64_AVX512: + compress_rgb32_to_binary_euclidean_64x32_x64_AVX512(image, bytes_per_row, matrix, expected, max_euclidean_distance); + return; +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + compress_rgb32_to_binary_euclidean_64x16_x64_AVX2(image, bytes_per_row, matrix, expected, max_euclidean_distance); + return; +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + compress_rgb32_to_binary_euclidean_64x8_x64_SSE42(image, bytes_per_row, matrix, expected, max_euclidean_distance); + return; +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + compress_rgb32_to_binary_euclidean_64x8_arm64_NEON(image, bytes_per_row, matrix, expected, max_euclidean_distance); + return; +#endif + case BinaryMatrixType::i64x4_Default: + compress_rgb32_to_binary_euclidean_64x4_Default(image, bytes_per_row, matrix, expected, max_euclidean_distance); + return; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported matrix format."); + } +} + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h index c16748db7b..776ad17abf 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h @@ -1,96 +1,96 @@ -/* Binary Image Basic Filters - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and store the results in a binary image. - * - * The parameter "binary_image" specifies the dimensions of the image. - * The parameter itself is overwritten by result. - * - * Example Usage: - * - * BinaryImage binary_image(1280, 720); - * - * filter_min_rgb32( - * binary_image, - * image, bytes_per_row, - * 0xff, 0x80, 0x80, 0x80 - * ); - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_H - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -// Selectively replace pixels in an image with the replacement color -// according to the respective bits in the binary matrix. -// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. -// Else, replace those with the one bits. -void filter_by_mask( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replacement_color, - bool replace_zero_bits -); - - - -// Compress (image, bytes_per_row) into a binary_image represented as the binary matrix `matrix` -// Pixels in the specified RGB ranges [`mins`, `maxs`] are assigned 1 in the binary matrix, -// otherwise 0. -void compress_rgb32_to_binary_range( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t mins, uint32_t maxs -); - -// Helper struct to store filtering related data for the multi-filter overload of `compress_rgb32_to_binary_range()`. -// It stores `matrix`, the filtering result: a binary matrix, where 1-bits are the pixels that are in the filter RGB -// range [`mins`, `maxs`], and 0-bits are otherwise. -struct CompressRgb32ToBinaryRangeFilter{ - PackedBinaryMatrix_IB& matrix; - uint32_t mins; - uint32_t maxs; - - CompressRgb32ToBinaryRangeFilter(PackedBinaryMatrix_IB& p_matrix, uint32_t p_mins, uint32_t p_maxs) - : matrix(p_matrix) - , mins(p_mins) - , maxs(p_maxs) - {} -}; - -// Compress (image, bytes_per_row) into multiple binary_images represented as binary matrices stored in -// `CompressRgb32ToBinaryRangeFilter.matrix` for each `filters`. -// For each filter, pixels in the specified RGB ranges [`Filter.mins`, `Filter.maxs`] are assigned 1 in `Filter.matrix`, -// otherwise 0. -// This function is like multiple calls to the single-filter overload of `compress_rgb32_to_binary_range()`, but -// with the benefit of reducing passes over the entire image. -// All matrices in `filters` must have the same dimensions. -void compress_rgb32_to_binary_range( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -); - - - - -// Compress (image, bytes_per_row) into a binary_image. -// For each pixel, set to 1 if the Euclidean distance of the pixel color to the expected color <= max distance. -void compress_rgb32_to_binary_euclidean( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected_color, double max_euclidean_distance -); - - - - -} -} -#endif +/* Binary Image Basic Filters + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and store the results in a binary image. + * + * The parameter "binary_image" specifies the dimensions of the image. + * The parameter itself is overwritten by result. + * + * Example Usage: + * + * BinaryImage binary_image(1280, 720); + * + * filter_min_rgb32( + * binary_image, + * image, bytes_per_row, + * 0xff, 0x80, 0x80, 0x80 + * ); + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_H + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +// Selectively replace pixels in an image with the replacement color +// according to the respective bits in the binary matrix. +// If `replace_zero_bits` is true, replace pixels corresponding to the zero bits. +// Else, replace those with the one bits. +void filter_by_mask( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replacement_color, + bool replace_zero_bits +); + + + +// Compress (image, bytes_per_row) into a binary_image represented as the binary matrix `matrix` +// Pixels in the specified RGB ranges [`mins`, `maxs`] are assigned 1 in the binary matrix, +// otherwise 0. +void compress_rgb32_to_binary_range( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t mins, uint32_t maxs +); + +// Helper struct to store filtering related data for the multi-filter overload of `compress_rgb32_to_binary_range()`. +// It stores `matrix`, the filtering result: a binary matrix, where 1-bits are the pixels that are in the filter RGB +// range [`mins`, `maxs`], and 0-bits are otherwise. +struct CompressRgb32ToBinaryRangeFilter{ + PackedBinaryMatrix_IB& matrix; + uint32_t mins; + uint32_t maxs; + + CompressRgb32ToBinaryRangeFilter(PackedBinaryMatrix_IB& p_matrix, uint32_t p_mins, uint32_t p_maxs) + : matrix(p_matrix) + , mins(p_mins) + , maxs(p_maxs) + {} +}; + +// Compress (image, bytes_per_row) into multiple binary_images represented as binary matrices stored in +// `CompressRgb32ToBinaryRangeFilter.matrix` for each `filters`. +// For each filter, pixels in the specified RGB ranges [`Filter.mins`, `Filter.maxs`] are assigned 1 in `Filter.matrix`, +// otherwise 0. +// This function is like multiple calls to the single-filter overload of `compress_rgb32_to_binary_range()`, but +// with the benefit of reducing passes over the entire image. +// All matrices in `filters` must have the same dimensions. +void compress_rgb32_to_binary_range( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +); + + + + +// Compress (image, bytes_per_row) into a binary_image. +// For each pixel, set to 1 if the Euclidean distance of the pixel color to the expected color <= max distance. +void compress_rgb32_to_binary_euclidean( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected_color, double max_euclidean_distance +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp index 52e18e415c..e2534942fc 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x16_x64_AVX2.cpp @@ -1,67 +1,67 @@ -/* Binary Image Basic Filters (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -void filter_by_mask_64x16_x64_AVX2( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replace_with, bool replace_if_zero -){ - FilterByMask_x64_AVX2 filter(replace_with, replace_if_zero); - filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); -} - - - -void compress_rgb32_to_binary_range_64x16_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 -){ - Compressor_RgbRange_x64_AVX2 compressor0(mins0, maxs0); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix0).get(), compressor0 - ); -} -void compress_rgb32_to_binary_range_64x16_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - compress_rgb32_to_binary( - image, bytes_per_row, filters, filter_count - ); -} - - - -void compress_rgb32_to_binary_euclidean_64x16_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - Compressor_RgbEuclidean_x64_AVX2 compressor(expected, max_euclidean_distance); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} - - - - -} -} -#endif +/* Binary Image Basic Filters (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +void filter_by_mask_64x16_x64_AVX2( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replace_with, bool replace_if_zero +){ + FilterByMask_x64_AVX2 filter(replace_with, replace_if_zero); + filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); +} + + + +void compress_rgb32_to_binary_range_64x16_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 +){ + Compressor_RgbRange_x64_AVX2 compressor0(mins0, maxs0); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix0).get(), compressor0 + ); +} +void compress_rgb32_to_binary_range_64x16_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + compress_rgb32_to_binary( + image, bytes_per_row, filters, filter_count + ); +} + + + +void compress_rgb32_to_binary_euclidean_64x16_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + Compressor_RgbEuclidean_x64_AVX2 compressor(expected, max_euclidean_distance); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp index 341d945ba9..01510410ec 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x32_x64_AVX512.cpp @@ -1,69 +1,69 @@ -/* Binary Image Basic Filters (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -void filter_by_mask_64x32_x64_AVX512( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replace_with, bool replace_if_zero -){ - FilterByMask_x64_AVX512 filter(replace_with, replace_if_zero); - filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); -} - - - -void compress_rgb32_to_binary_range_64x32_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 -){ - Compressor_RgbRange_x64_AVX512 compressor0(mins0, maxs0); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix0).get(), compressor0 - ); -} -void compress_rgb32_to_binary_range_64x32_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - compress_rgb32_to_binary( - image, bytes_per_row, filters, filter_count - ); -} - - - -void compress_rgb32_to_binary_euclidean_64x32_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - Compressor_RgbEuclidean_x64_AVX512 compressor(expected, max_euclidean_distance); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} - - - - - -} -} -#endif +/* Binary Image Basic Filters (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +void filter_by_mask_64x32_x64_AVX512( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replace_with, bool replace_if_zero +){ + FilterByMask_x64_AVX512 filter(replace_with, replace_if_zero); + filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); +} + + + +void compress_rgb32_to_binary_range_64x32_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 +){ + Compressor_RgbRange_x64_AVX512 compressor0(mins0, maxs0); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix0).get(), compressor0 + ); +} +void compress_rgb32_to_binary_range_64x32_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + compress_rgb32_to_binary( + image, bytes_per_row, filters, filter_count + ); +} + + + +void compress_rgb32_to_binary_euclidean_64x32_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + Compressor_RgbEuclidean_x64_AVX512 compressor(expected, max_euclidean_distance); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x4_Default.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x4_Default.cpp index 58345678cb..8a4fb52d61 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x4_Default.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x4_Default.cpp @@ -1,63 +1,63 @@ -/* Binary Image Basic Filters (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters_Default.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -void filter_by_mask_64x4_Default( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replace_with, bool replace_if_zero -){ - FilterByMask_Default filter(replace_with, replace_if_zero); - filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); -} - - - -void compress_rgb32_to_binary_range_64x4_Default( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, uint32_t mins, uint32_t maxs -){ - Compressor_RgbRange_Default compressor(mins, maxs); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} -void compress_rgb32_to_binary_range_64x4_Default( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - compress_rgb32_to_binary( - image, bytes_per_row, filters, filter_count - ); -} - - - -void compress_rgb32_to_binary_euclidean_64x4_Default( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - Compressor_RgbEuclidean_Default compressor(expected, max_euclidean_distance); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} - - - -} -} +/* Binary Image Basic Filters (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters_Default.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +void filter_by_mask_64x4_Default( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replace_with, bool replace_if_zero +){ + FilterByMask_Default filter(replace_with, replace_if_zero); + filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); +} + + + +void compress_rgb32_to_binary_range_64x4_Default( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, uint32_t mins, uint32_t maxs +){ + Compressor_RgbRange_Default compressor(mins, maxs); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} +void compress_rgb32_to_binary_range_64x4_Default( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + compress_rgb32_to_binary( + image, bytes_per_row, filters, filter_count + ); +} + + + +void compress_rgb32_to_binary_euclidean_64x4_Default( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + Compressor_RgbEuclidean_Default compressor(expected, max_euclidean_distance); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp index a051eea35a..7582810f33 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x64_x64_AVX512.cpp @@ -1,69 +1,69 @@ -/* Binary Image Basic Filters (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -void filter_by_mask_64x64_x64_AVX512( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replace_with, bool replace_if_zero -){ - FilterByMask_x64_AVX512 filter(replace_with, replace_if_zero); - filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); -} - - - -void compress_rgb32_to_binary_range_64x64_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 -){ - Compressor_RgbRange_x64_AVX512 compressor0(mins0, maxs0); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix0).get(), compressor0 - ); -} -void compress_rgb32_to_binary_range_64x64_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - compress_rgb32_to_binary( - image, bytes_per_row, filters, filter_count - ); -} - - - -void compress_rgb32_to_binary_euclidean_64x64_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - Compressor_RgbEuclidean_x64_AVX512 compressor(expected, max_euclidean_distance); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} - - - - - -} -} -#endif +/* Binary Image Basic Filters (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +void filter_by_mask_64x64_x64_AVX512( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replace_with, bool replace_if_zero +){ + FilterByMask_x64_AVX512 filter(replace_with, replace_if_zero); + filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); +} + + + +void compress_rgb32_to_binary_range_64x64_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 +){ + Compressor_RgbRange_x64_AVX512 compressor0(mins0, maxs0); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix0).get(), compressor0 + ); +} +void compress_rgb32_to_binary_range_64x64_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + compress_rgb32_to_binary( + image, bytes_per_row, filters, filter_count + ); +} + + + +void compress_rgb32_to_binary_euclidean_64x64_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + Compressor_RgbEuclidean_x64_AVX512 compressor(expected, max_euclidean_distance); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_arm64_NEON.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_arm64_NEON.cpp index 45675ca4f8..ddc82207b5 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_arm64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_arm64_NEON.cpp @@ -1,66 +1,66 @@ -/* Binary Image Basic Filters (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters_arm64_NEON.h" - - -namespace PokemonAutomation{ -namespace Kernels{ - - -void filter_by_mask_64x8_arm64_NEON( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replacement_color, bool replace_zero_bits -){ - FilterByMask_arm64_NEON filter(replacement_color, replace_zero_bits); - filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); -} - - - - -void compress_rgb32_to_binary_range_64x8_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 -){ - Compressor_RgbRange_arm64_NEON compressor0(mins0, maxs0); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix0).get(), compressor0 - ); -} -void compress_rgb32_to_binary_range_64x8_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - compress_rgb32_to_binary( - image, bytes_per_row, filters, filter_count - ); -} - - -void compress_rgb32_to_binary_euclidean_64x8_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - Compressor_RgbEuclidean_arm64_NEON compressor(expected, max_euclidean_distance); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} - - - -} -} -#endif +/* Binary Image Basic Filters (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters_arm64_NEON.h" + + +namespace PokemonAutomation{ +namespace Kernels{ + + +void filter_by_mask_64x8_arm64_NEON( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replacement_color, bool replace_zero_bits +){ + FilterByMask_arm64_NEON filter(replacement_color, replace_zero_bits); + filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); +} + + + + +void compress_rgb32_to_binary_range_64x8_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 +){ + Compressor_RgbRange_arm64_NEON compressor0(mins0, maxs0); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix0).get(), compressor0 + ); +} +void compress_rgb32_to_binary_range_64x8_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + compress_rgb32_to_binary( + image, bytes_per_row, filters, filter_count + ); +} + + +void compress_rgb32_to_binary_euclidean_64x8_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + Compressor_RgbEuclidean_arm64_NEON compressor(expected, max_euclidean_distance); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp index 621c61bede..67117eed38 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Core_64x8_x64_SSE42.cpp @@ -1,67 +1,67 @@ -/* Binary Image Basic Filters (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h" -#include "Kernels_BinaryImage_BasicFilters_Routines.h" -#include "Kernels_BinaryImage_BasicFilters_x64_SSE42.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -void filter_by_mask_64x8_x64_SSE42( - const PackedBinaryMatrix_IB& matrix, - uint32_t* image, size_t bytes_per_row, - uint32_t replace_with, bool replace_if_zero -){ - FilterByMask_x64_SSE41 filter(replace_with, replace_if_zero); - filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); -} - - - -void compress_rgb32_to_binary_range_64x8_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 -){ - Compressor_RgbRange_x64_SSE41 compressor0(mins0, maxs0); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix0).get(), compressor0 - ); -} -void compress_rgb32_to_binary_range_64x8_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count -){ - compress_rgb32_to_binary( - image, bytes_per_row, filters, filter_count - ); -} - - - -void compress_rgb32_to_binary_euclidean_64x8_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, - PackedBinaryMatrix_IB& matrix, - uint32_t expected, double max_euclidean_distance -){ - Compressor_RgbEuclidean_x64_SSE41 compressor(expected, max_euclidean_distance); - compress_rgb32_to_binary( - image, bytes_per_row, - static_cast(matrix).get(), compressor - ); -} - - - - -} -} -#endif +/* Binary Image Basic Filters (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h" +#include "Kernels_BinaryImage_BasicFilters_Routines.h" +#include "Kernels_BinaryImage_BasicFilters_x64_SSE42.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +void filter_by_mask_64x8_x64_SSE42( + const PackedBinaryMatrix_IB& matrix, + uint32_t* image, size_t bytes_per_row, + uint32_t replace_with, bool replace_if_zero +){ + FilterByMask_x64_SSE41 filter(replace_with, replace_if_zero); + filter_by_mask(static_cast(matrix).get(), image, bytes_per_row, filter); +} + + + +void compress_rgb32_to_binary_range_64x8_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix0, uint32_t mins0, uint32_t maxs0 +){ + Compressor_RgbRange_x64_SSE41 compressor0(mins0, maxs0); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix0).get(), compressor0 + ); +} +void compress_rgb32_to_binary_range_64x8_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filters, size_t filter_count +){ + compress_rgb32_to_binary( + image, bytes_per_row, filters, filter_count + ); +} + + + +void compress_rgb32_to_binary_euclidean_64x8_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, + PackedBinaryMatrix_IB& matrix, + uint32_t expected, double max_euclidean_distance +){ + Compressor_RgbEuclidean_x64_SSE41 compressor(expected, max_euclidean_distance); + compress_rgb32_to_binary( + image, bytes_per_row, + static_cast(matrix).get(), compressor + ); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h index 07c2334e5c..a1463e2a0a 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Default.h @@ -1,182 +1,182 @@ -/* Binary Image Basic Filters (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_Default_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_Default_H - -#include -#include -#include "Common/Compiler.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class FilterByMask_Default{ -public: - FilterByMask_Default(uint32_t replacement, bool replace_if_zero) - : m_replacement(replacement) - , m_replace_if_zero(replace_if_zero ? 1 : 0) - {} - - PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ - size_t c = 0; - while (c < count){ - pixels[c] = filter1(bits & 1, pixels[c]); - bits >>= 1; - c++; - } - } - -private: - PA_FORCE_INLINE uint32_t filter1(uint64_t bit, uint32_t pixel) const{ - return (bit ^ m_replace_if_zero) ? m_replacement : pixel; - } - -private: - uint32_t m_replacement; - uint64_t m_replace_if_zero; -}; - - - -class Compressor_RgbRange_Default{ -public: - Compressor_RgbRange_Default(uint32_t mins, uint32_t maxs) - : m_minB(mins & 0x000000ff) - , m_maxB(maxs & 0x000000ff) - , m_minG(mins & 0x0000ff00) - , m_maxG(maxs & 0x0000ff00) - , m_minR(mins & 0x00ff0000) - , m_maxR(maxs & 0x00ff0000) - , m_minA(mins & 0xff000000) - , m_maxA(maxs & 0xff000000) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count = 64) const{ - uint64_t bits = 0; - size_t c = 0; - while (c < count){ - bits |= convert1(pixels[c]) << c; - c++; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert1(uint32_t pixel) const{ - uint64_t ret = 1; - { - uint32_t p = pixel & 0xff000000; - ret &= p >= m_minA; - ret &= p <= m_maxA; - } - { - uint32_t p = pixel & 0x00ff0000; - ret &= p >= m_minR; - ret &= p <= m_maxR; - } - { - uint32_t p = pixel & 0x0000ff00; - ret &= p >= m_minG; - ret &= p <= m_maxG; - } - { - uint32_t p = pixel & 0x000000ff; - ret &= p >= m_minB; - ret &= p <= m_maxB; - } - return ret; - } - -private: - uint32_t m_minB; - uint32_t m_maxB; - uint32_t m_minG; - uint32_t m_maxG; - uint32_t m_minR; - uint32_t m_maxR; - uint32_t m_minA; - uint32_t m_maxA; -}; - - - -class Compressor_RgbEuclidean_Default{ -public: - Compressor_RgbEuclidean_Default(uint32_t expected, double max_euclidean_distance) - : m_expected_r((expected & 0x00ff0000) >> 16) - , m_expected_g((expected & 0x0000ff00) >> 8) - , m_expected_b(expected & 0x000000ff) - , m_distance_squared((uint32_t)(max_euclidean_distance * max_euclidean_distance)) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count = 64) const{ - uint64_t bits = 0; - size_t c = 0; - while (c < count){ - bits |= convert1(pixels[c]) << c; - c++; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert1(uint32_t pixel) const{ - uint32_t sum_sqr = 0; - { - uint32_t p = (pixel & 0x00ff0000) >> 16; - p -= m_expected_r; - sum_sqr += p * p; - } - { - uint32_t p = (pixel & 0x0000ff00) >> 8; - p -= m_expected_g; - sum_sqr += p * p; - } - { - uint32_t p = pixel & 0x000000ff; - p -= m_expected_b; - sum_sqr += p * p; - } - return sum_sqr <= m_distance_squared; - } - -private: - uint32_t m_expected_r; - uint32_t m_expected_g; - uint32_t m_expected_b; - uint32_t m_distance_squared; -}; - - - - - - - - - - - - - - - - - - - - - -} -} -#endif +/* Binary Image Basic Filters (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_Default_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_Default_H + +#include +#include +#include "Common/Compiler.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class FilterByMask_Default{ +public: + FilterByMask_Default(uint32_t replacement, bool replace_if_zero) + : m_replacement(replacement) + , m_replace_if_zero(replace_if_zero ? 1 : 0) + {} + + PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ + size_t c = 0; + while (c < count){ + pixels[c] = filter1(bits & 1, pixels[c]); + bits >>= 1; + c++; + } + } + +private: + PA_FORCE_INLINE uint32_t filter1(uint64_t bit, uint32_t pixel) const{ + return (bit ^ m_replace_if_zero) ? m_replacement : pixel; + } + +private: + uint32_t m_replacement; + uint64_t m_replace_if_zero; +}; + + + +class Compressor_RgbRange_Default{ +public: + Compressor_RgbRange_Default(uint32_t mins, uint32_t maxs) + : m_minB(mins & 0x000000ff) + , m_maxB(maxs & 0x000000ff) + , m_minG(mins & 0x0000ff00) + , m_maxG(maxs & 0x0000ff00) + , m_minR(mins & 0x00ff0000) + , m_maxR(maxs & 0x00ff0000) + , m_minA(mins & 0xff000000) + , m_maxA(maxs & 0xff000000) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count = 64) const{ + uint64_t bits = 0; + size_t c = 0; + while (c < count){ + bits |= convert1(pixels[c]) << c; + c++; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert1(uint32_t pixel) const{ + uint64_t ret = 1; + { + uint32_t p = pixel & 0xff000000; + ret &= p >= m_minA; + ret &= p <= m_maxA; + } + { + uint32_t p = pixel & 0x00ff0000; + ret &= p >= m_minR; + ret &= p <= m_maxR; + } + { + uint32_t p = pixel & 0x0000ff00; + ret &= p >= m_minG; + ret &= p <= m_maxG; + } + { + uint32_t p = pixel & 0x000000ff; + ret &= p >= m_minB; + ret &= p <= m_maxB; + } + return ret; + } + +private: + uint32_t m_minB; + uint32_t m_maxB; + uint32_t m_minG; + uint32_t m_maxG; + uint32_t m_minR; + uint32_t m_maxR; + uint32_t m_minA; + uint32_t m_maxA; +}; + + + +class Compressor_RgbEuclidean_Default{ +public: + Compressor_RgbEuclidean_Default(uint32_t expected, double max_euclidean_distance) + : m_expected_r((expected & 0x00ff0000) >> 16) + , m_expected_g((expected & 0x0000ff00) >> 8) + , m_expected_b(expected & 0x000000ff) + , m_distance_squared((uint32_t)(max_euclidean_distance * max_euclidean_distance)) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count = 64) const{ + uint64_t bits = 0; + size_t c = 0; + while (c < count){ + bits |= convert1(pixels[c]) << c; + c++; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert1(uint32_t pixel) const{ + uint32_t sum_sqr = 0; + { + uint32_t p = (pixel & 0x00ff0000) >> 16; + p -= m_expected_r; + sum_sqr += p * p; + } + { + uint32_t p = (pixel & 0x0000ff00) >> 8; + p -= m_expected_g; + sum_sqr += p * p; + } + { + uint32_t p = pixel & 0x000000ff; + p -= m_expected_b; + sum_sqr += p * p; + } + return sum_sqr <= m_distance_squared; + } + +private: + uint32_t m_expected_r; + uint32_t m_expected_g; + uint32_t m_expected_b; + uint32_t m_distance_squared; +}; + + + + + + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Routines.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Routines.h index 3aaa373d74..6bb7b46887 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Routines.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_Routines.h @@ -1,163 +1,163 @@ -/* Binary Image Basic Filters - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_Routines_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_Routines_H - -#include -#include -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels_BinaryImage_BasicFilters.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -template -void filter_by_mask( - const BinaryMatrixType& matrix, - uint32_t* image, size_t bytes_per_row, - const Filter& filter -){ - size_t bit_width = matrix.width(); -// size_t bit_height = binary_image.height(); -// size_t word_width = binary_image.word64_width(); - size_t word_height = matrix.word64_height(); - for (size_t r = 0; r < word_height; r++){ - uint32_t* img = image; - size_t c = 0; - size_t left = bit_width; - while (left >= 64){ - filter.filter64(matrix.word64(c, r), img); - c++; - img += 64; - left -= 64; - } - if (left > 0){ - filter.filter64(matrix.word64(c, r), img, left); - } - image = (uint32_t*)((const char*)image + bytes_per_row); - } -} - - - -template -void compress_rgb32_to_binary( - const uint32_t* image, size_t bytes_per_row, - BinaryMatrixType& matrix, const Compressor& compressor -){ - size_t bit_width = matrix.width(); -// size_t bit_height = binary_image.height(); -// size_t word_width = binary_image.word64_width(); - size_t word_height = matrix.word64_height(); - for (size_t r = 0; r < word_height; r++){ - const uint32_t* img = image; - size_t c = 0; - size_t left = bit_width; - while (left >= 64){ - matrix.word64(c, r) = compressor.convert64(img); - c++; - img += 64; - left -= 64; - } - if (left > 0){ - matrix.word64(c, r) = compressor.convert64(img, left); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - } -} - - -template -struct CompressRgb32ToBinaryRangeEntry{ - BinaryMatrixType& matrix; - Compressor compressor; - - CompressRgb32ToBinaryRangeEntry(BinaryMatrixType& p_matrix, uint32_t mins, uint32_t maxs) - : matrix(p_matrix) - , compressor(mins, maxs) - {} -}; -template -void compress_rgb32_to_binary( - const uint32_t* image, size_t bytes_per_row, - CompressRgb32ToBinaryRangeFilter* filter, size_t filter_count -){ - using Entry = CompressRgb32ToBinaryRangeEntry; - FixedLimitVector entries(filter_count); - for (size_t c = 0; c < filter_count; c++){ - entries.emplace_back(static_cast(filter[c].matrix), filter[c].mins, filter[c].maxs); - } - - size_t bit_width = entries[0].matrix.get().width(); - size_t word_height = entries[0].matrix.get().word64_height(); - for (size_t r = 0; r < word_height; r++){ - const uint32_t* img = image; - size_t c = 0; - size_t left = bit_width; - while (left >= 64){ - for (Entry& entry : entries){ - entry.matrix.get().word64(c, r) = entry.compressor.convert64(img); - } - c++; - img += 64; - left -= 64; - } - if (left > 0){ - for (Entry& entry : entries){ - entry.matrix.get().word64(c, r) = entry.compressor.convert64(img, left); - } - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - } -} - - -// Change pixel (as uint32_t) color of image based on bits in a binary matrix -// If `filter` is constructed with `replace_if_zero` being true, image pixels corresponding to 0-bits in `matrix` -// are replaced with color `replace_with` which is provided by the filter. -// If `filter` is constructed with `replace_if_zero` being false, image pixels corresponding to 1-bits in `matrix` -// are replaced with color `replace_with`. -// `BinaryMatrixType` is a PackedBinaryMatrixCore, -// where BinaryMatrixTileType is an implementation of a tile, defined for every simd architecture. -template -void filter_rgb32( - const BinaryMatrixType& matrix, - uint32_t* image, size_t bytes_per_row, - const Filter& filter -){ - size_t bit_width = matrix.width(); -// size_t bit_height = binary_image.height(); -// size_t word_width = binary_image.word64_width(); - - // How many words in a row. Each word is 64-bit long - size_t word_height = matrix.word64_height(); - for (size_t r = 0; r < word_height; r++){ // For each row - uint32_t* img = image; - // c: current index of the word. One word has 64-bit wide - size_t c = 0; - size_t left = bit_width; - while (left >= 64){ - // Modify some pixels in the 64-pixel-long area of the image, - // starting at pointr `img` - filter.filter64(matrix.word64(c, r), img); - c++; - img += 64; - left -= 64; - } - if (left > 0){ - filter.filter64(matrix.word64(c, r), img, left); - } - image = (uint32_t*)((const char*)image + bytes_per_row); - } -} - - -} -} -#endif +/* Binary Image Basic Filters + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_Routines_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_Routines_H + +#include +#include +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels_BinaryImage_BasicFilters.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +template +void filter_by_mask( + const BinaryMatrixType& matrix, + uint32_t* image, size_t bytes_per_row, + const Filter& filter +){ + size_t bit_width = matrix.width(); +// size_t bit_height = binary_image.height(); +// size_t word_width = binary_image.word64_width(); + size_t word_height = matrix.word64_height(); + for (size_t r = 0; r < word_height; r++){ + uint32_t* img = image; + size_t c = 0; + size_t left = bit_width; + while (left >= 64){ + filter.filter64(matrix.word64(c, r), img); + c++; + img += 64; + left -= 64; + } + if (left > 0){ + filter.filter64(matrix.word64(c, r), img, left); + } + image = (uint32_t*)((const char*)image + bytes_per_row); + } +} + + + +template +void compress_rgb32_to_binary( + const uint32_t* image, size_t bytes_per_row, + BinaryMatrixType& matrix, const Compressor& compressor +){ + size_t bit_width = matrix.width(); +// size_t bit_height = binary_image.height(); +// size_t word_width = binary_image.word64_width(); + size_t word_height = matrix.word64_height(); + for (size_t r = 0; r < word_height; r++){ + const uint32_t* img = image; + size_t c = 0; + size_t left = bit_width; + while (left >= 64){ + matrix.word64(c, r) = compressor.convert64(img); + c++; + img += 64; + left -= 64; + } + if (left > 0){ + matrix.word64(c, r) = compressor.convert64(img, left); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + } +} + + +template +struct CompressRgb32ToBinaryRangeEntry{ + BinaryMatrixType& matrix; + Compressor compressor; + + CompressRgb32ToBinaryRangeEntry(BinaryMatrixType& p_matrix, uint32_t mins, uint32_t maxs) + : matrix(p_matrix) + , compressor(mins, maxs) + {} +}; +template +void compress_rgb32_to_binary( + const uint32_t* image, size_t bytes_per_row, + CompressRgb32ToBinaryRangeFilter* filter, size_t filter_count +){ + using Entry = CompressRgb32ToBinaryRangeEntry; + FixedLimitVector entries(filter_count); + for (size_t c = 0; c < filter_count; c++){ + entries.emplace_back(static_cast(filter[c].matrix), filter[c].mins, filter[c].maxs); + } + + size_t bit_width = entries[0].matrix.get().width(); + size_t word_height = entries[0].matrix.get().word64_height(); + for (size_t r = 0; r < word_height; r++){ + const uint32_t* img = image; + size_t c = 0; + size_t left = bit_width; + while (left >= 64){ + for (Entry& entry : entries){ + entry.matrix.get().word64(c, r) = entry.compressor.convert64(img); + } + c++; + img += 64; + left -= 64; + } + if (left > 0){ + for (Entry& entry : entries){ + entry.matrix.get().word64(c, r) = entry.compressor.convert64(img, left); + } + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + } +} + + +// Change pixel (as uint32_t) color of image based on bits in a binary matrix +// If `filter` is constructed with `replace_if_zero` being true, image pixels corresponding to 0-bits in `matrix` +// are replaced with color `replace_with` which is provided by the filter. +// If `filter` is constructed with `replace_if_zero` being false, image pixels corresponding to 1-bits in `matrix` +// are replaced with color `replace_with`. +// `BinaryMatrixType` is a PackedBinaryMatrixCore, +// where BinaryMatrixTileType is an implementation of a tile, defined for every simd architecture. +template +void filter_rgb32( + const BinaryMatrixType& matrix, + uint32_t* image, size_t bytes_per_row, + const Filter& filter +){ + size_t bit_width = matrix.width(); +// size_t bit_height = binary_image.height(); +// size_t word_width = binary_image.word64_width(); + + // How many words in a row. Each word is 64-bit long + size_t word_height = matrix.word64_height(); + for (size_t r = 0; r < word_height; r++){ // For each row + uint32_t* img = image; + // c: current index of the word. One word has 64-bit wide + size_t c = 0; + size_t left = bit_width; + while (left >= 64){ + // Modify some pixels in the 64-pixel-long area of the image, + // starting at pointr `img` + filter.filter64(matrix.word64(c, r), img); + c++; + img += 64; + left -= 64; + } + if (left > 0){ + filter.filter64(matrix.word64(c, r), img, left); + } + image = (uint32_t*)((const char*)image + bytes_per_row); + } +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h index e9adbdf134..6b65086ce0 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h @@ -1,324 +1,324 @@ -/* Binary Image Basic Filters (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_arm64_NEON_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_arm64_NEON_H - -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - -// Change color of an array of pixels based on values from a bitmap that corresponds to the pixel array. -// If `replace_zero_bits` is true, change color of pixels that correspond to 0 bits. -// Otherwise, chagne color of pixels that correspond to 1 bits. -class FilterByMask_arm64_NEON{ -public: - FilterByMask_arm64_NEON(uint32_t replacement, bool replace_zero_bits) - : m_replacement_u32(vdupq_n_u32(replacement)) - , m_replace_if_zero(replace_zero_bits) - , m_zeros(vreinterpretq_u32_u8(vdupq_n_u8(0))) - {} - - // Given 64 bits stored in `uint64_t`, use it to set colors to 64 pixels in `pixels`. - // If filter constructor parameter `replace_zero_bits` is true, the pixels corresponding to - // 0-bits are set to color `replacement` (another filter constructor parameter). - // Otherwise, pixels corresponding to 1-bits are set to the color. - PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels) const{ - for(int i = 0; i < 64; i+=16){ - filter16((bits >> i) & 0xFFFF, pixels + i); - } - } - - // partial version of filter64(bits, pixels): instead of setting colors to 64 pixels, - // only setting `count` (count <= 64) pixels. - PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count) const{ - const size_t count_round_4 = (count / 4) * 4; - for(size_t i = 0; i < count_round_4; i+=4){ - filter4((bits >> i) & 0xF, pixels + i); - } - - size_t left = count % 4; - if (left){ - uint32_t buffer[4]; - memcpy(buffer, pixels + count_round_4, sizeof(uint32_t) * left); - filter4((bits >> count_round_4) & 0xF, buffer); - memcpy(pixels + count_round_4, buffer, sizeof(uint32_t) * left); - } - } - -private: - // Change color in the 8 pixels according to the lowest 4 bits in `bits` - PA_FORCE_INLINE void filter4(uint64_t bits64, uint32_t* pixels) const{ - // Duplicate 4-bit pattern into four uint16_t places in `bits` - bits64 *= 0x0001000100010001; - // convert each uint16_t to be one bit from the lowest four bits in input `bits` - bits64 &= 0x0008000400020001; - - uint32x4_t pixels_u32 = vld1q_u32(pixels); - - // Load `bits` into simd 64-bit vector register - uint16x4_t mask_u16 = vcreate_u16(bits64); - // Expand mask to cover each pixel (uint32_t) - uint32x4_t mask_u32 = vmovl_u16(mask_u16); - // Expand mask to be all-1 or all-0 mask for each pixel - mask_u32 = vcgtq_u32(mask_u32, m_zeros); - - uint32x4_t out_u32; - if (m_replace_if_zero){ - // bit select intrinsic: - // vbslq_u32(a, b, c), for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(mask_u32, pixels_u32, m_replacement_u32); - }else{ - out_u32 = vbslq_u32(mask_u32, m_replacement_u32, pixels_u32); - } - vst1q_u32(pixels, out_u32); - } - - PA_FORCE_INLINE void filter16(uint64_t bits64, uint32_t* pixels) const{ - uint64_t bits_0 = bits64 & 0xF; - uint64_t bits_1 = (bits64 >> 4) & 0xF; - uint64_t bits_2 = (bits64 >> 8) & 0xF; - uint64_t bits_3 = bits64 >> 12; - - // Duplicate 4-bit pattern into four uint16_t places in `bits` - bits_0 *= 0x0001000100010001; - // convert each uint16_t to be one bit from the lowest four bits in input `bits` - bits_0 &= 0x0008000400020001; - - bits_1 *= 0x0001000100010001; - bits_1 &= 0x0008000400020001; - - bits_2 *= 0x0001000100010001; - bits_2 &= 0x0008000400020001; - - bits_3 *= 0x0001000100010001; - bits_3 &= 0x0008000400020001; - - uint32x4_t pixels_0_u32 = vld1q_u32(pixels); - uint32x4_t pixels_1_u32 = vld1q_u32(pixels + 4); - uint32x4_t pixels_2_u32 = vld1q_u32(pixels + 8); - uint32x4_t pixels_3_u32 = vld1q_u32(pixels + 12); - - // Load `bits` into simd 64-bit vector register - uint16x4_t mask_0_u16x4 = vcreate_u16(bits_0); - uint16x4_t mask_1_u16x4 = vcreate_u16(bits_1); - uint16x4_t mask_2_u16x4 = vcreate_u16(bits_2); - uint16x4_t mask_3_u16x4 = vcreate_u16(bits_3); - // Expand mask to cover each pixel (uint32_t) - uint32x4_t mask_0_u32 = vmovl_u16(mask_0_u16x4); - uint32x4_t mask_1_u32 = vmovl_u16(mask_1_u16x4); - uint32x4_t mask_2_u32 = vmovl_u16(mask_2_u16x4); - uint32x4_t mask_3_u32 = vmovl_u16(mask_3_u16x4); - // Expand mask to be all-1 or all-0 mask for each pixel - mask_0_u32 = vcgtq_u32(mask_0_u32, m_zeros); - mask_1_u32 = vcgtq_u32(mask_1_u32, m_zeros); - mask_2_u32 = vcgtq_u32(mask_2_u32, m_zeros); - mask_3_u32 = vcgtq_u32(mask_3_u32, m_zeros); - - uint32x4_t out_0_u32, out_1_u32, out_2_u32, out_3_u32; - if (m_replace_if_zero){ - // bit select intrinsic: - // vbslq_u32(a, b, c), for 1 bits in a, choose b; for 0 bits in a, choose c - out_0_u32 = vbslq_u32(mask_0_u32, pixels_0_u32, m_replacement_u32); - out_1_u32 = vbslq_u32(mask_1_u32, pixels_1_u32, m_replacement_u32); - out_2_u32 = vbslq_u32(mask_2_u32, pixels_2_u32, m_replacement_u32); - out_3_u32 = vbslq_u32(mask_3_u32, pixels_3_u32, m_replacement_u32); - }else{ - out_0_u32 = vbslq_u32(mask_0_u32, m_replacement_u32, pixels_0_u32); - out_1_u32 = vbslq_u32(mask_1_u32, m_replacement_u32, pixels_1_u32); - out_2_u32 = vbslq_u32(mask_2_u32, m_replacement_u32, pixels_2_u32); - out_3_u32 = vbslq_u32(mask_3_u32, m_replacement_u32, pixels_3_u32); - } - vst1q_u32(pixels, out_0_u32); - vst1q_u32(pixels + 4, out_1_u32); - vst1q_u32(pixels + 8, out_2_u32); - vst1q_u32(pixels + 12, out_3_u32); - } - -private: - const uint32x4_t m_replacement_u32; - const bool m_replace_if_zero; - const uint32x4_t m_zeros; -}; - -// Compress given pixels buffer (of up to 64-pixel long) into bit map and store in one uint64_t. -class Compressor_RgbRange_arm64_NEON{ -public: - Compressor_RgbRange_arm64_NEON(uint32_t mins, uint32_t maxs) - : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(mins))) - , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(maxs))) - , m_zeros(vreinterpretq_u32_u8(vdupq_n_u8(0))) - {} - - // Convert a row of 64 pixels to bit map fit into uint64_t - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - for(size_t c = 0; c < 64; c += 16){ - bits |= convert16(pixels + c) << c; - } - return bits; - } - // Convert a row of `count` pixels to bit map fit into uint64_t - // count <= 64 - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - - for(size_t i = 0; i < count / 16; i++){ - bits |= convert16(pixels + c) << c; - c += 16; - } - - count %= 16; - for(size_t i = 0; i < count / 4; i++, c+=4){ - const uint8x16_t pixel = vld1q_u8((const uint8_t*)(pixels + c)); - bits |= convert4(pixel) << c; - } - count %= 4; - if (count){ - PartialWordAccess_arm64_NEON loader(count * sizeof(uint32_t)); - const uint8x16_t pixel = loader.load(pixels + c); - const uint64_t mask = ((uint64_t)1 << count) - 1; - bits |= (convert4(pixel) & mask) << c; - } - return bits; - } - -private: - // Convert four pixels to four 0/1 bits according to RGB color range - // Return a uint64_t where the lowest four bits contain the converted bits for each pixel. - PA_FORCE_INLINE uint64_t convert4(const uint8x16_t& pixel) const{ - // Check if mins > pixel per color channel - uint8x16_t cmp0 = vcgtq_u8(m_mins_u8, pixel); - // Check if pixel > maxs per color channel - uint8x16_t cmp1 = vcgtq_u8(pixel, m_maxs_u8); - // cmp: if mins > pixel or pixel > maxs per color channel - uint8x16_t cmp = vorrq_u8(cmp0, cmp1); - // cmp_32x4: if each pixel is within the range - // If a pixel is within range, its uint32_t in `cmp_32x4` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp), m_zeros); - return (cmp_32x4[0] & 0x1) | (cmp_32x4[1] & 0x2) | (cmp_32x4[2] & 0x4) | (cmp_32x4[3] & 0x8); - } - - // Convert 16 pixels to 16 0/1 bits according to RGB color range - // Return a uint64_t where the lowest bits contain the converted bits for each pixel. - PA_FORCE_INLINE uint64_t convert16(const uint32_t* pixels) const{ - uint8x16x4_t pixelx4 = vld1q_u8_x4((const uint8_t*)pixels); - - // cmpx_min: Check if mins > pixel per color channel - // cmpx_max: Check if pixel > maxs per color channel - uint8x16_t cmp0_min = vcgtq_u8(m_mins_u8, pixelx4.val[0]); - uint8x16_t cmp0_max = vcgtq_u8(pixelx4.val[0], m_maxs_u8); - uint8x16_t cmp1_min = vcgtq_u8(m_mins_u8, pixelx4.val[1]); - uint8x16_t cmp1_max = vcgtq_u8(pixelx4.val[1], m_maxs_u8); - uint8x16_t cmp2_min = vcgtq_u8(m_mins_u8, pixelx4.val[2]); - uint8x16_t cmp2_max = vcgtq_u8(pixelx4.val[2], m_maxs_u8); - uint8x16_t cmp3_min = vcgtq_u8(m_mins_u8, pixelx4.val[3]); - uint8x16_t cmp3_max = vcgtq_u8(pixelx4.val[3], m_maxs_u8); - - // cmp: if mins > pixel or pixel > maxs per color channel - uint8x16_t cmp0 = vorrq_u8(cmp0_min, cmp0_max); - uint8x16_t cmp1 = vorrq_u8(cmp1_min, cmp1_max); - uint8x16_t cmp2 = vorrq_u8(cmp2_min, cmp2_max); - uint8x16_t cmp3 = vorrq_u8(cmp3_min, cmp3_max); - - // cmp_32x4: if each pixel is within the range - // If a pixel is within range, its uint32_t in `cmp_32x4` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp0_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp0), m_zeros); - uint32x4_t cmp1_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp1), m_zeros); - uint32x4_t cmp2_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp2), m_zeros); - uint32x4_t cmp3_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp3), m_zeros); - - // Combine pixel bits together - return (cmp0_32x4[0] & 0x01) | (cmp0_32x4[1] & 0x02) | (cmp0_32x4[2] & 0x04) | (cmp0_32x4[3] & 0x08) - | (cmp1_32x4[0] & 0x10) | (cmp1_32x4[1] & 0x20) | (cmp1_32x4[2] & 0x40) | (cmp1_32x4[3] & 0x80) - | (cmp2_32x4[0] & 0x100) | (cmp2_32x4[1] & 0x200) | (cmp2_32x4[2] & 0x400) | (cmp2_32x4[3] & 0x800) - | (cmp3_32x4[0] & 0x1000) | (cmp3_32x4[1] & 0x2000) | (cmp3_32x4[2] & 0x4000) | (cmp3_32x4[3] & 0x8000); - } - -private: - uint8x16_t m_mins_u8; - uint8x16_t m_maxs_u8; - const uint32x4_t m_zeros; -}; - - -class Compressor_RgbEuclidean_arm64_NEON{ -public: - Compressor_RgbEuclidean_arm64_NEON(uint32_t expected_color, double max_euclidean_distance) - : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) - , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - for(size_t c = 0; c < 64; c += 4){ - bits |= convert4(pixels + c) << c; - } - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - - for(size_t i = 0; i < count / 4; i++, c+=4){ - bits |= convert4(pixels + c) << c; - } - count %= 4; - if (count){ - PartialWordAccess_arm64_NEON loader(count * sizeof(uint32_t)); - const uint8x16_t pixel = loader.load(pixels + c); - const uint64_t mask = ((uint64_t)1 << count) - 1; - bits |= (convert4(pixel) & mask) << c; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert4(const uint32_t* pixel) const{ - uint32x4_t in_u32 = vld1q_u32(pixel); - return convert4(vreinterpretq_u8_u32(in_u32)); - } - PA_FORCE_INLINE uint64_t convert4(const uint32x4_t& in_u32) const{ - // subtract the expected values - uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); - - // Get green channel - uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); - // Move green channel to the lower end of the 16-bit regions - uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); - // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region - uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); - - // Square operation - uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); - uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); - - uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); - // Use pairwise addition and accumulate to add r2, g2, and b2 together - uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); - - // cmp_u32: if each pixel is within range (sum_sqr <= max_distance_squared), its uint32_t in `cmp_u32` is all 1 bits, - // otherwise, all 0 bits - uint32x4_t cmp_u32 = vcleq_u32(sum_sqr_u32, m_distance_squared_u32); - return (cmp_u32[0] & 0x01) | (cmp_u32[1] & 0x02) | (cmp_u32[2] & 0x04) | (cmp_u32[3] & 0x08); - } - -private: - uint8x16_t m_expected_color_rgb_u8; - uint32x4_t m_distance_squared_u32; -}; - - - -} -} -#endif +/* Binary Image Basic Filters (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_arm64_NEON_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_arm64_NEON_H + +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + +// Change color of an array of pixels based on values from a bitmap that corresponds to the pixel array. +// If `replace_zero_bits` is true, change color of pixels that correspond to 0 bits. +// Otherwise, chagne color of pixels that correspond to 1 bits. +class FilterByMask_arm64_NEON{ +public: + FilterByMask_arm64_NEON(uint32_t replacement, bool replace_zero_bits) + : m_replacement_u32(vdupq_n_u32(replacement)) + , m_replace_if_zero(replace_zero_bits) + , m_zeros(vreinterpretq_u32_u8(vdupq_n_u8(0))) + {} + + // Given 64 bits stored in `uint64_t`, use it to set colors to 64 pixels in `pixels`. + // If filter constructor parameter `replace_zero_bits` is true, the pixels corresponding to + // 0-bits are set to color `replacement` (another filter constructor parameter). + // Otherwise, pixels corresponding to 1-bits are set to the color. + PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels) const{ + for(int i = 0; i < 64; i+=16){ + filter16((bits >> i) & 0xFFFF, pixels + i); + } + } + + // partial version of filter64(bits, pixels): instead of setting colors to 64 pixels, + // only setting `count` (count <= 64) pixels. + PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count) const{ + const size_t count_round_4 = (count / 4) * 4; + for(size_t i = 0; i < count_round_4; i+=4){ + filter4((bits >> i) & 0xF, pixels + i); + } + + size_t left = count % 4; + if (left){ + uint32_t buffer[4]; + memcpy(buffer, pixels + count_round_4, sizeof(uint32_t) * left); + filter4((bits >> count_round_4) & 0xF, buffer); + memcpy(pixels + count_round_4, buffer, sizeof(uint32_t) * left); + } + } + +private: + // Change color in the 8 pixels according to the lowest 4 bits in `bits` + PA_FORCE_INLINE void filter4(uint64_t bits64, uint32_t* pixels) const{ + // Duplicate 4-bit pattern into four uint16_t places in `bits` + bits64 *= 0x0001000100010001; + // convert each uint16_t to be one bit from the lowest four bits in input `bits` + bits64 &= 0x0008000400020001; + + uint32x4_t pixels_u32 = vld1q_u32(pixels); + + // Load `bits` into simd 64-bit vector register + uint16x4_t mask_u16 = vcreate_u16(bits64); + // Expand mask to cover each pixel (uint32_t) + uint32x4_t mask_u32 = vmovl_u16(mask_u16); + // Expand mask to be all-1 or all-0 mask for each pixel + mask_u32 = vcgtq_u32(mask_u32, m_zeros); + + uint32x4_t out_u32; + if (m_replace_if_zero){ + // bit select intrinsic: + // vbslq_u32(a, b, c), for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(mask_u32, pixels_u32, m_replacement_u32); + }else{ + out_u32 = vbslq_u32(mask_u32, m_replacement_u32, pixels_u32); + } + vst1q_u32(pixels, out_u32); + } + + PA_FORCE_INLINE void filter16(uint64_t bits64, uint32_t* pixels) const{ + uint64_t bits_0 = bits64 & 0xF; + uint64_t bits_1 = (bits64 >> 4) & 0xF; + uint64_t bits_2 = (bits64 >> 8) & 0xF; + uint64_t bits_3 = bits64 >> 12; + + // Duplicate 4-bit pattern into four uint16_t places in `bits` + bits_0 *= 0x0001000100010001; + // convert each uint16_t to be one bit from the lowest four bits in input `bits` + bits_0 &= 0x0008000400020001; + + bits_1 *= 0x0001000100010001; + bits_1 &= 0x0008000400020001; + + bits_2 *= 0x0001000100010001; + bits_2 &= 0x0008000400020001; + + bits_3 *= 0x0001000100010001; + bits_3 &= 0x0008000400020001; + + uint32x4_t pixels_0_u32 = vld1q_u32(pixels); + uint32x4_t pixels_1_u32 = vld1q_u32(pixels + 4); + uint32x4_t pixels_2_u32 = vld1q_u32(pixels + 8); + uint32x4_t pixels_3_u32 = vld1q_u32(pixels + 12); + + // Load `bits` into simd 64-bit vector register + uint16x4_t mask_0_u16x4 = vcreate_u16(bits_0); + uint16x4_t mask_1_u16x4 = vcreate_u16(bits_1); + uint16x4_t mask_2_u16x4 = vcreate_u16(bits_2); + uint16x4_t mask_3_u16x4 = vcreate_u16(bits_3); + // Expand mask to cover each pixel (uint32_t) + uint32x4_t mask_0_u32 = vmovl_u16(mask_0_u16x4); + uint32x4_t mask_1_u32 = vmovl_u16(mask_1_u16x4); + uint32x4_t mask_2_u32 = vmovl_u16(mask_2_u16x4); + uint32x4_t mask_3_u32 = vmovl_u16(mask_3_u16x4); + // Expand mask to be all-1 or all-0 mask for each pixel + mask_0_u32 = vcgtq_u32(mask_0_u32, m_zeros); + mask_1_u32 = vcgtq_u32(mask_1_u32, m_zeros); + mask_2_u32 = vcgtq_u32(mask_2_u32, m_zeros); + mask_3_u32 = vcgtq_u32(mask_3_u32, m_zeros); + + uint32x4_t out_0_u32, out_1_u32, out_2_u32, out_3_u32; + if (m_replace_if_zero){ + // bit select intrinsic: + // vbslq_u32(a, b, c), for 1 bits in a, choose b; for 0 bits in a, choose c + out_0_u32 = vbslq_u32(mask_0_u32, pixels_0_u32, m_replacement_u32); + out_1_u32 = vbslq_u32(mask_1_u32, pixels_1_u32, m_replacement_u32); + out_2_u32 = vbslq_u32(mask_2_u32, pixels_2_u32, m_replacement_u32); + out_3_u32 = vbslq_u32(mask_3_u32, pixels_3_u32, m_replacement_u32); + }else{ + out_0_u32 = vbslq_u32(mask_0_u32, m_replacement_u32, pixels_0_u32); + out_1_u32 = vbslq_u32(mask_1_u32, m_replacement_u32, pixels_1_u32); + out_2_u32 = vbslq_u32(mask_2_u32, m_replacement_u32, pixels_2_u32); + out_3_u32 = vbslq_u32(mask_3_u32, m_replacement_u32, pixels_3_u32); + } + vst1q_u32(pixels, out_0_u32); + vst1q_u32(pixels + 4, out_1_u32); + vst1q_u32(pixels + 8, out_2_u32); + vst1q_u32(pixels + 12, out_3_u32); + } + +private: + const uint32x4_t m_replacement_u32; + const bool m_replace_if_zero; + const uint32x4_t m_zeros; +}; + +// Compress given pixels buffer (of up to 64-pixel long) into bit map and store in one uint64_t. +class Compressor_RgbRange_arm64_NEON{ +public: + Compressor_RgbRange_arm64_NEON(uint32_t mins, uint32_t maxs) + : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(mins))) + , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(maxs))) + , m_zeros(vreinterpretq_u32_u8(vdupq_n_u8(0))) + {} + + // Convert a row of 64 pixels to bit map fit into uint64_t + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + for(size_t c = 0; c < 64; c += 16){ + bits |= convert16(pixels + c) << c; + } + return bits; + } + // Convert a row of `count` pixels to bit map fit into uint64_t + // count <= 64 + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + + for(size_t i = 0; i < count / 16; i++){ + bits |= convert16(pixels + c) << c; + c += 16; + } + + count %= 16; + for(size_t i = 0; i < count / 4; i++, c+=4){ + const uint8x16_t pixel = vld1q_u8((const uint8_t*)(pixels + c)); + bits |= convert4(pixel) << c; + } + count %= 4; + if (count){ + PartialWordAccess_arm64_NEON loader(count * sizeof(uint32_t)); + const uint8x16_t pixel = loader.load(pixels + c); + const uint64_t mask = ((uint64_t)1 << count) - 1; + bits |= (convert4(pixel) & mask) << c; + } + return bits; + } + +private: + // Convert four pixels to four 0/1 bits according to RGB color range + // Return a uint64_t where the lowest four bits contain the converted bits for each pixel. + PA_FORCE_INLINE uint64_t convert4(const uint8x16_t& pixel) const{ + // Check if mins > pixel per color channel + uint8x16_t cmp0 = vcgtq_u8(m_mins_u8, pixel); + // Check if pixel > maxs per color channel + uint8x16_t cmp1 = vcgtq_u8(pixel, m_maxs_u8); + // cmp: if mins > pixel or pixel > maxs per color channel + uint8x16_t cmp = vorrq_u8(cmp0, cmp1); + // cmp_32x4: if each pixel is within the range + // If a pixel is within range, its uint32_t in `cmp_32x4` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp), m_zeros); + return (cmp_32x4[0] & 0x1) | (cmp_32x4[1] & 0x2) | (cmp_32x4[2] & 0x4) | (cmp_32x4[3] & 0x8); + } + + // Convert 16 pixels to 16 0/1 bits according to RGB color range + // Return a uint64_t where the lowest bits contain the converted bits for each pixel. + PA_FORCE_INLINE uint64_t convert16(const uint32_t* pixels) const{ + uint8x16x4_t pixelx4 = vld1q_u8_x4((const uint8_t*)pixels); + + // cmpx_min: Check if mins > pixel per color channel + // cmpx_max: Check if pixel > maxs per color channel + uint8x16_t cmp0_min = vcgtq_u8(m_mins_u8, pixelx4.val[0]); + uint8x16_t cmp0_max = vcgtq_u8(pixelx4.val[0], m_maxs_u8); + uint8x16_t cmp1_min = vcgtq_u8(m_mins_u8, pixelx4.val[1]); + uint8x16_t cmp1_max = vcgtq_u8(pixelx4.val[1], m_maxs_u8); + uint8x16_t cmp2_min = vcgtq_u8(m_mins_u8, pixelx4.val[2]); + uint8x16_t cmp2_max = vcgtq_u8(pixelx4.val[2], m_maxs_u8); + uint8x16_t cmp3_min = vcgtq_u8(m_mins_u8, pixelx4.val[3]); + uint8x16_t cmp3_max = vcgtq_u8(pixelx4.val[3], m_maxs_u8); + + // cmp: if mins > pixel or pixel > maxs per color channel + uint8x16_t cmp0 = vorrq_u8(cmp0_min, cmp0_max); + uint8x16_t cmp1 = vorrq_u8(cmp1_min, cmp1_max); + uint8x16_t cmp2 = vorrq_u8(cmp2_min, cmp2_max); + uint8x16_t cmp3 = vorrq_u8(cmp3_min, cmp3_max); + + // cmp_32x4: if each pixel is within the range + // If a pixel is within range, its uint32_t in `cmp_32x4` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp0_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp0), m_zeros); + uint32x4_t cmp1_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp1), m_zeros); + uint32x4_t cmp2_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp2), m_zeros); + uint32x4_t cmp3_32x4 = vceqq_u32(vreinterpretq_u32_u8(cmp3), m_zeros); + + // Combine pixel bits together + return (cmp0_32x4[0] & 0x01) | (cmp0_32x4[1] & 0x02) | (cmp0_32x4[2] & 0x04) | (cmp0_32x4[3] & 0x08) + | (cmp1_32x4[0] & 0x10) | (cmp1_32x4[1] & 0x20) | (cmp1_32x4[2] & 0x40) | (cmp1_32x4[3] & 0x80) + | (cmp2_32x4[0] & 0x100) | (cmp2_32x4[1] & 0x200) | (cmp2_32x4[2] & 0x400) | (cmp2_32x4[3] & 0x800) + | (cmp3_32x4[0] & 0x1000) | (cmp3_32x4[1] & 0x2000) | (cmp3_32x4[2] & 0x4000) | (cmp3_32x4[3] & 0x8000); + } + +private: + uint8x16_t m_mins_u8; + uint8x16_t m_maxs_u8; + const uint32x4_t m_zeros; +}; + + +class Compressor_RgbEuclidean_arm64_NEON{ +public: + Compressor_RgbEuclidean_arm64_NEON(uint32_t expected_color, double max_euclidean_distance) + : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) + , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + for(size_t c = 0; c < 64; c += 4){ + bits |= convert4(pixels + c) << c; + } + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + + for(size_t i = 0; i < count / 4; i++, c+=4){ + bits |= convert4(pixels + c) << c; + } + count %= 4; + if (count){ + PartialWordAccess_arm64_NEON loader(count * sizeof(uint32_t)); + const uint8x16_t pixel = loader.load(pixels + c); + const uint64_t mask = ((uint64_t)1 << count) - 1; + bits |= (convert4(pixel) & mask) << c; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert4(const uint32_t* pixel) const{ + uint32x4_t in_u32 = vld1q_u32(pixel); + return convert4(vreinterpretq_u8_u32(in_u32)); + } + PA_FORCE_INLINE uint64_t convert4(const uint32x4_t& in_u32) const{ + // subtract the expected values + uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); + + // Get green channel + uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); + // Move green channel to the lower end of the 16-bit regions + uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); + // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region + uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); + + // Square operation + uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); + uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); + + uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); + // Use pairwise addition and accumulate to add r2, g2, and b2 together + uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); + + // cmp_u32: if each pixel is within range (sum_sqr <= max_distance_squared), its uint32_t in `cmp_u32` is all 1 bits, + // otherwise, all 0 bits + uint32x4_t cmp_u32 = vcleq_u32(sum_sqr_u32, m_distance_squared_u32); + return (cmp_u32[0] & 0x01) | (cmp_u32[1] & 0x02) | (cmp_u32[2] & 0x04) | (cmp_u32[3] & 0x08); + } + +private: + uint8x16_t m_expected_color_rgb_u8; + uint32x4_t m_distance_squared_u32; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h index 61d10801e2..9a5be6f89d 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX2.h @@ -1,186 +1,186 @@ -/* Binary Image Basic Filters (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX2_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX2_H - -#include -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class FilterByMask_x64_AVX2{ -public: - FilterByMask_x64_AVX2(uint32_t replacement, bool replace_if_zero) - : m_replacement(_mm256_set1_epi32(replacement)) - , m_replace_if_zero(_mm256_set1_epi32(replace_if_zero ? 0 : 0xffffffff)) - {} - - PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ - size_t lc = count / 8; - while (lc--){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)pixels); - pixel = filter8(bits & 255, pixel); - _mm256_storeu_si256((__m256i*)pixels, pixel); - pixels += 8; - bits >>= 8; - } - count %= 8; - if (count){ - PartialWordAccess32_x64_AVX2 loader(count); - __m256i pixel = loader.load_i32(pixels); - pixel = filter8(bits & 255, pixel); - loader.store(pixels, pixel); - } - } - -private: - PA_FORCE_INLINE __m256i filter8(uint64_t bits, __m256i pixel) const{ - bits *= 0x0101010101010101; - bits &= 0x8040201008040201; - __m256i mask = _mm256_cvtepu8_epi32(_mm_cvtsi64_si128(bits)); - mask = _mm256_cmpeq_epi32(mask, _mm256_setzero_si256()); - mask = _mm256_xor_si256(mask, m_replace_if_zero); - return _mm256_blendv_epi8(pixel, m_replacement, mask); - } - -private: - __m256i m_replacement; - __m256i m_replace_if_zero; -}; - - - -class Compressor_RgbRange_x64_AVX2{ -public: - Compressor_RgbRange_x64_AVX2(uint32_t mins, uint32_t maxs) - : m_mins(_mm256_set1_epi32(mins ^ 0x80808080)) - , m_maxs(_mm256_set1_epi32(maxs ^ 0x80808080)) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 0))) << 0; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 8))) << 8; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 16))) << 16; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 24))) << 24; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 32))) << 32; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 40))) << 40; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 48))) << 48; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 56))) << 56; - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - size_t lc = count / 8; - while (lc--){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)pixels); - bits |= convert8(pixel) << c; - pixels += 8; - c += 8; - } - count %= 8; - if (count){ - PartialWordAccess32_x64_AVX2 loader(count); - __m256i pixel = loader.load_i32(pixels); - uint64_t mask = ((uint64_t)1 << count) - 1; - bits |= (convert8(pixel) & mask) << c; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert8(__m256i pixel) const{ - pixel = _mm256_xor_si256(pixel, _mm256_set1_epi8((uint8_t)0x80)); - __m256i cmp0 = _mm256_cmpgt_epi8(m_mins, pixel); - __m256i cmp1 = _mm256_cmpgt_epi8(pixel, m_maxs); - cmp0 = _mm256_or_si256(cmp0, cmp1); - cmp0 = _mm256_cmpeq_epi32(cmp0, _mm256_setzero_si256()); - return _mm256_movemask_ps(_mm256_castsi256_ps(cmp0)); - } - -private: - __m256i m_mins; - __m256i m_maxs; -}; - - - -class Compressor_RgbEuclidean_x64_AVX2{ -public: - Compressor_RgbEuclidean_x64_AVX2(uint32_t expected, double max_euclidean_distance) - : m_expected_ag(_mm256_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm256_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm256_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 0))) << 0; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 8))) << 8; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 16))) << 16; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 24))) << 24; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 32))) << 32; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 40))) << 40; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 48))) << 48; - bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 56))) << 56; - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - size_t lc = count / 8; - while (lc--){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)pixels); - bits |= convert8(pixel) << c; - pixels += 8; - c += 8; - } - count %= 8; - if (count){ - PartialWordAccess32_x64_AVX2 loader(count); - __m256i pixel = loader.load_i32(pixels); - uint64_t mask = ((uint64_t)1 << count) - 1; - bits |= (convert8(pixel) & mask) << c; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert8(__m256i pixel) const{ - __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x000000ff)); - __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); - - ag = _mm256_sub_epi16(ag, m_expected_ag); - rb = _mm256_sub_epi16(rb, m_expected_rb); - - __m256i g = _mm256_mullo_epi16(ag, ag); - rb = _mm256_mullo_epi16(rb, rb); - __m256i r = _mm256_srli_epi32(rb, 16); - __m256i b = _mm256_and_si256(rb, _mm256_set1_epi32(0x0000ffff)); - - __m256i sum_sqr = _mm256_add_epi32(r, g); - sum_sqr = _mm256_add_epi32(sum_sqr, b); - - __m256i cmp = _mm256_cmpgt_epi32(m_distance_squared, sum_sqr); - return _mm256_movemask_ps(_mm256_castsi256_ps(cmp)); - } - -private: - const __m256i m_expected_ag; - const __m256i m_expected_rb; - const __m256i m_distance_squared; -}; - - - -} -} -#endif +/* Binary Image Basic Filters (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX2_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX2_H + +#include +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class FilterByMask_x64_AVX2{ +public: + FilterByMask_x64_AVX2(uint32_t replacement, bool replace_if_zero) + : m_replacement(_mm256_set1_epi32(replacement)) + , m_replace_if_zero(_mm256_set1_epi32(replace_if_zero ? 0 : 0xffffffff)) + {} + + PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ + size_t lc = count / 8; + while (lc--){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)pixels); + pixel = filter8(bits & 255, pixel); + _mm256_storeu_si256((__m256i*)pixels, pixel); + pixels += 8; + bits >>= 8; + } + count %= 8; + if (count){ + PartialWordAccess32_x64_AVX2 loader(count); + __m256i pixel = loader.load_i32(pixels); + pixel = filter8(bits & 255, pixel); + loader.store(pixels, pixel); + } + } + +private: + PA_FORCE_INLINE __m256i filter8(uint64_t bits, __m256i pixel) const{ + bits *= 0x0101010101010101; + bits &= 0x8040201008040201; + __m256i mask = _mm256_cvtepu8_epi32(_mm_cvtsi64_si128(bits)); + mask = _mm256_cmpeq_epi32(mask, _mm256_setzero_si256()); + mask = _mm256_xor_si256(mask, m_replace_if_zero); + return _mm256_blendv_epi8(pixel, m_replacement, mask); + } + +private: + __m256i m_replacement; + __m256i m_replace_if_zero; +}; + + + +class Compressor_RgbRange_x64_AVX2{ +public: + Compressor_RgbRange_x64_AVX2(uint32_t mins, uint32_t maxs) + : m_mins(_mm256_set1_epi32(mins ^ 0x80808080)) + , m_maxs(_mm256_set1_epi32(maxs ^ 0x80808080)) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 0))) << 0; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 8))) << 8; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 16))) << 16; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 24))) << 24; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 32))) << 32; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 40))) << 40; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 48))) << 48; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 56))) << 56; + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + size_t lc = count / 8; + while (lc--){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)pixels); + bits |= convert8(pixel) << c; + pixels += 8; + c += 8; + } + count %= 8; + if (count){ + PartialWordAccess32_x64_AVX2 loader(count); + __m256i pixel = loader.load_i32(pixels); + uint64_t mask = ((uint64_t)1 << count) - 1; + bits |= (convert8(pixel) & mask) << c; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert8(__m256i pixel) const{ + pixel = _mm256_xor_si256(pixel, _mm256_set1_epi8((uint8_t)0x80)); + __m256i cmp0 = _mm256_cmpgt_epi8(m_mins, pixel); + __m256i cmp1 = _mm256_cmpgt_epi8(pixel, m_maxs); + cmp0 = _mm256_or_si256(cmp0, cmp1); + cmp0 = _mm256_cmpeq_epi32(cmp0, _mm256_setzero_si256()); + return _mm256_movemask_ps(_mm256_castsi256_ps(cmp0)); + } + +private: + __m256i m_mins; + __m256i m_maxs; +}; + + + +class Compressor_RgbEuclidean_x64_AVX2{ +public: + Compressor_RgbEuclidean_x64_AVX2(uint32_t expected, double max_euclidean_distance) + : m_expected_ag(_mm256_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm256_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm256_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 0))) << 0; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 8))) << 8; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 16))) << 16; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 24))) << 24; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 32))) << 32; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 40))) << 40; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 48))) << 48; + bits |= convert8(_mm256_loadu_si256((const __m256i*)(pixels + 56))) << 56; + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + size_t lc = count / 8; + while (lc--){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)pixels); + bits |= convert8(pixel) << c; + pixels += 8; + c += 8; + } + count %= 8; + if (count){ + PartialWordAccess32_x64_AVX2 loader(count); + __m256i pixel = loader.load_i32(pixels); + uint64_t mask = ((uint64_t)1 << count) - 1; + bits |= (convert8(pixel) & mask) << c; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert8(__m256i pixel) const{ + __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x000000ff)); + __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); + + ag = _mm256_sub_epi16(ag, m_expected_ag); + rb = _mm256_sub_epi16(rb, m_expected_rb); + + __m256i g = _mm256_mullo_epi16(ag, ag); + rb = _mm256_mullo_epi16(rb, rb); + __m256i r = _mm256_srli_epi32(rb, 16); + __m256i b = _mm256_and_si256(rb, _mm256_set1_epi32(0x0000ffff)); + + __m256i sum_sqr = _mm256_add_epi32(r, g); + sum_sqr = _mm256_add_epi32(sum_sqr, b); + + __m256i cmp = _mm256_cmpgt_epi32(m_distance_squared, sum_sqr); + return _mm256_movemask_ps(_mm256_castsi256_ps(cmp)); + } + +private: + const __m256i m_expected_ag; + const __m256i m_expected_rb; + const __m256i m_distance_squared; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h index a86b23ce6f..1e34b4ef0c 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_AVX512.h @@ -1,186 +1,186 @@ -/* Binary Image Basic Filters (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX512_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX512_H - -#include -#include -#include "Common/Compiler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class FilterByMask_x64_AVX512{ -public: - FilterByMask_x64_AVX512(uint32_t replacement, bool replace_if_zero) - : m_replacement(_mm512_set1_epi32(replacement)) - , m_replace_if_zero(replace_if_zero ? 0xffff : 0) - {} - - PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ - size_t lc = count / 16; - while (lc--){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)pixels); - pixel = filter16(bits, pixel); - _mm512_storeu_si512((__m512i*)pixels, pixel); - pixels += 16; - bits >>= 16; - } - count %= 16; - if (count){ - uint64_t mask = ((uint64_t)1 << count) - 1; - __m512i pixel = _mm512_maskz_loadu_epi32((__mmask16)mask, pixels); - pixel = filter16(bits, pixel); - _mm512_mask_storeu_epi32(pixels, (__mmask16)mask, pixel); - } - } - -private: - PA_FORCE_INLINE __m512i filter16(uint64_t mask, __m512i pixel) const{ - mask ^= m_replace_if_zero; - return _mm512_mask_blend_epi32((__mmask16)mask, pixel, m_replacement); - } - -private: - __m512i m_replacement; - uint32_t m_replace_if_zero; -}; - - - -class Compressor_RgbRange_x64_AVX512{ -public: - Compressor_RgbRange_x64_AVX512(uint32_t mins, uint32_t maxs) - : m_mins(_mm512_set1_epi32(mins)) - , m_maxs(_mm512_set1_epi32(maxs)) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 0))) << 0; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 16))) << 16; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 32))) << 32; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 48))) << 48; - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - size_t lc = count / 16; - while (lc--){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)pixels); - bits |= convert16(pixel) << c; - pixels += 16; - c += 16; - } - count %= 16; - if (count){ - uint64_t mask = ((uint64_t)1 << count) - 1; - __m512i pixel = _mm512_maskz_loadu_epi32((__mmask16)mask, pixels); - bits |= (convert16(pixel) & mask) << c; - } -// cout << "bits = " << bits << endl; - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert16(__m512i pixel) const{ -#if 0 - __mmask64 cmp64A = _mm512_cmpgt_epu8_mask(m_mins, pixel); - __mmask64 cmp64B = _mm512_cmpgt_epu8_mask(pixel, m_maxs); - pixel = _mm512_movm_epi8(cmp64A | cmp64B); - __mmask16 cmp16 = _mm512_cmpeq_epi32_mask(pixel, _mm512_setzero_si512()); -#else - __mmask64 cmp64A = _mm512_cmple_epu8_mask(m_mins, pixel); - __mmask64 cmp64B = _mm512_mask_cmple_epu8_mask(cmp64A, pixel, m_maxs); - pixel = _mm512_movm_epi8(cmp64B); - __mmask16 cmp16 = _mm512_cmpeq_epi32_mask(pixel, _mm512_set1_epi32(-1)); -#endif - return cmp16; - } - -private: - __m512i m_mins; - __m512i m_maxs; -}; - - - -class Compressor_RgbEuclidean_x64_AVX512{ -public: - Compressor_RgbEuclidean_x64_AVX512(uint32_t expected, double max_euclidean_distance) - : m_expected_ag(_mm512_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm512_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm512_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 0))) << 0; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 16))) << 16; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 32))) << 32; - bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 48))) << 48; - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - size_t lc = count / 16; - while (lc--){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)pixels); - bits |= convert16(pixel) << c; - pixels += 16; - c += 16; - } - count %= 16; - if (count){ - uint64_t mask = ((uint64_t)1 << count) - 1; - __m512i pixel = _mm512_maskz_loadu_epi32((__mmask16)mask, pixels); - bits |= (convert16(pixel) & mask) << c; - } -// cout << "bits = " << bits << endl; - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert16(__m512i pixel) const{ - __m512i ag = _mm512_and_si512(_mm512_srli_epi16(pixel, 8), _mm512_set1_epi32(0x000000ff)); - __m512i rb = _mm512_and_si512(pixel, _mm512_set1_epi32(0x00ff00ff)); - - ag = _mm512_sub_epi16(ag, m_expected_ag); - rb = _mm512_sub_epi16(rb, m_expected_rb); - - __m512i g = _mm512_mullo_epi16(ag, ag); - rb = _mm512_mullo_epi16(rb, rb); - __m512i r = _mm512_srli_epi32(rb, 16); - __m512i b = _mm512_and_si512(rb, _mm512_set1_epi32(0x0000ffff)); - - __m512i sum_sqr = _mm512_add_epi32(r, g); - sum_sqr = _mm512_add_epi32(sum_sqr, b); - - __mmask16 cmp = _mm512_cmpgt_epi32_mask(m_distance_squared, sum_sqr); - return cmp; - } - -private: - const __m512i m_expected_ag; - const __m512i m_expected_rb; - const __m512i m_distance_squared; -}; - - - - -} -} -#endif +/* Binary Image Basic Filters (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX512_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_AVX512_H + +#include +#include +#include "Common/Compiler.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class FilterByMask_x64_AVX512{ +public: + FilterByMask_x64_AVX512(uint32_t replacement, bool replace_if_zero) + : m_replacement(_mm512_set1_epi32(replacement)) + , m_replace_if_zero(replace_if_zero ? 0xffff : 0) + {} + + PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ + size_t lc = count / 16; + while (lc--){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)pixels); + pixel = filter16(bits, pixel); + _mm512_storeu_si512((__m512i*)pixels, pixel); + pixels += 16; + bits >>= 16; + } + count %= 16; + if (count){ + uint64_t mask = ((uint64_t)1 << count) - 1; + __m512i pixel = _mm512_maskz_loadu_epi32((__mmask16)mask, pixels); + pixel = filter16(bits, pixel); + _mm512_mask_storeu_epi32(pixels, (__mmask16)mask, pixel); + } + } + +private: + PA_FORCE_INLINE __m512i filter16(uint64_t mask, __m512i pixel) const{ + mask ^= m_replace_if_zero; + return _mm512_mask_blend_epi32((__mmask16)mask, pixel, m_replacement); + } + +private: + __m512i m_replacement; + uint32_t m_replace_if_zero; +}; + + + +class Compressor_RgbRange_x64_AVX512{ +public: + Compressor_RgbRange_x64_AVX512(uint32_t mins, uint32_t maxs) + : m_mins(_mm512_set1_epi32(mins)) + , m_maxs(_mm512_set1_epi32(maxs)) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 0))) << 0; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 16))) << 16; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 32))) << 32; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 48))) << 48; + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + size_t lc = count / 16; + while (lc--){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)pixels); + bits |= convert16(pixel) << c; + pixels += 16; + c += 16; + } + count %= 16; + if (count){ + uint64_t mask = ((uint64_t)1 << count) - 1; + __m512i pixel = _mm512_maskz_loadu_epi32((__mmask16)mask, pixels); + bits |= (convert16(pixel) & mask) << c; + } +// cout << "bits = " << bits << endl; + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert16(__m512i pixel) const{ +#if 0 + __mmask64 cmp64A = _mm512_cmpgt_epu8_mask(m_mins, pixel); + __mmask64 cmp64B = _mm512_cmpgt_epu8_mask(pixel, m_maxs); + pixel = _mm512_movm_epi8(cmp64A | cmp64B); + __mmask16 cmp16 = _mm512_cmpeq_epi32_mask(pixel, _mm512_setzero_si512()); +#else + __mmask64 cmp64A = _mm512_cmple_epu8_mask(m_mins, pixel); + __mmask64 cmp64B = _mm512_mask_cmple_epu8_mask(cmp64A, pixel, m_maxs); + pixel = _mm512_movm_epi8(cmp64B); + __mmask16 cmp16 = _mm512_cmpeq_epi32_mask(pixel, _mm512_set1_epi32(-1)); +#endif + return cmp16; + } + +private: + __m512i m_mins; + __m512i m_maxs; +}; + + + +class Compressor_RgbEuclidean_x64_AVX512{ +public: + Compressor_RgbEuclidean_x64_AVX512(uint32_t expected, double max_euclidean_distance) + : m_expected_ag(_mm512_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm512_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm512_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 0))) << 0; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 16))) << 16; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 32))) << 32; + bits |= convert16(_mm512_loadu_si512((const __m512i*)(pixels + 48))) << 48; + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + size_t lc = count / 16; + while (lc--){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)pixels); + bits |= convert16(pixel) << c; + pixels += 16; + c += 16; + } + count %= 16; + if (count){ + uint64_t mask = ((uint64_t)1 << count) - 1; + __m512i pixel = _mm512_maskz_loadu_epi32((__mmask16)mask, pixels); + bits |= (convert16(pixel) & mask) << c; + } +// cout << "bits = " << bits << endl; + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert16(__m512i pixel) const{ + __m512i ag = _mm512_and_si512(_mm512_srli_epi16(pixel, 8), _mm512_set1_epi32(0x000000ff)); + __m512i rb = _mm512_and_si512(pixel, _mm512_set1_epi32(0x00ff00ff)); + + ag = _mm512_sub_epi16(ag, m_expected_ag); + rb = _mm512_sub_epi16(rb, m_expected_rb); + + __m512i g = _mm512_mullo_epi16(ag, ag); + rb = _mm512_mullo_epi16(rb, rb); + __m512i r = _mm512_srli_epi32(rb, 16); + __m512i b = _mm512_and_si512(rb, _mm512_set1_epi32(0x0000ffff)); + + __m512i sum_sqr = _mm512_add_epi32(r, g); + sum_sqr = _mm512_add_epi32(sum_sqr, b); + + __mmask16 cmp = _mm512_cmpgt_epi32_mask(m_distance_squared, sum_sqr); + return cmp; + } + +private: + const __m512i m_expected_ag; + const __m512i m_expected_rb; + const __m512i m_distance_squared; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h index 8e1ff3a117..ce1a1ad15b 100644 --- a/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h +++ b/SerialPrograms/Source/Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h @@ -1,206 +1,206 @@ -/* Binary Image Basic Filters (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_SSE41_H -#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_SSE41_H - -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class FilterByMask_x64_SSE41{ -public: - FilterByMask_x64_SSE41(uint32_t replacement, bool replace_if_zero) - : m_replacement(_mm_set1_epi32(replacement)) - , m_replace_if_zero(_mm_set1_epi32(replace_if_zero ? 0 : 0xffffffff)) - {} - - PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ - size_t lc = count / 4; - while (lc--){ - __m128i pixel = _mm_loadu_si128((const __m128i*)pixels); - pixel = filter4((uint32_t)bits & 15, pixel); - _mm_storeu_si128((__m128i*)pixels, pixel); - pixels += 4; - bits >>= 4; - } - count %= 4; - if (count){ - PartialWordAccess_x64_SSE41 loader(count * sizeof(uint32_t)); - __m128i pixel = loader.load(pixels); - pixel = filter4((uint32_t)bits & 15, pixel); - do{ - pixels[0] = _mm_cvtsi128_si32(pixel); - pixel = _mm_srli_si128(pixel, 4); - pixels++; - }while(--count); - } - } - -private: - // Change color in the four pixels according to the lowest four bits in `bits` - PA_FORCE_INLINE __m128i filter4(uint32_t bits, __m128i pixel) const{ - // Duplicate 4-bit pattern into four uint8_t places in `bits` - bits *= 0x01010101; - // convert each uint8_t to be one bit from the lowest four bits in input `bits` - bits &= 0x08040201; - // Load uint32_t `bits` into a 128-bit simd register - __m128i mask = _mm_cvtsi32_si128(bits); - // Expand uint8 values into uint32 values - // So now each pixel (uint32) corresponds to a mask value in `mask` - mask = _mm_cvtepu8_epi32(mask); - // set a pixel in mask to 1 if original mask for the pixel is 0 - mask = _mm_cmpeq_epi32(mask, _mm_setzero_si128()); - // If constructor `replace_if_zero` is true: `m_replace_if_zero` is all 0-bits - // then XOR it, mask becomes the same, so it's the inverse of the original mask - // ---- - // If constructor `replace_if_zero` is false: `m_replace_if_zero` is all 1-bits - // then XOR it, masks becomes the inverse, so it's the same as the original maask - mask = _mm_xor_si128(mask, m_replace_if_zero); - // If constructor `replace_if_zero` is true, - // If mask is non-zero, which means if original mask is zero, use m_replacement - // Otherwise, remain the old pixel color - // --- - // If constructor `replace_if_zero` is false, - // If mask is non-zero, which means the original mask non-zero, use m_replacement - // Otherwise, remain the old pixel color - return _mm_blendv_epi8(pixel, m_replacement, mask); - } - -private: - __m128i m_replacement; - __m128i m_replace_if_zero; -}; - - - -class Compressor_RgbRange_x64_SSE41{ -public: - Compressor_RgbRange_x64_SSE41(uint32_t mins, uint32_t maxs) - : m_mins(_mm_set1_epi32(mins ^ 0x80808080)) - , m_maxs(_mm_set1_epi32(maxs ^ 0x80808080)) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - size_t c = 0; - do{ - __m128i pixel = _mm_loadu_si128((const __m128i*)(pixels + c)); - bits |= convert4(pixel) << c; - c += 4; - }while (c < 64); - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - size_t lc = count / 4; - while (lc--){ - __m128i pixel = _mm_loadu_si128((const __m128i*)pixels); - bits |= convert4(pixel) << c; - pixels += 4; - c += 4; - } - count %= 4; - if (count){ - PartialWordAccess_x64_SSE41 loader(count * sizeof(uint32_t)); - __m128i pixel = loader.load(pixels); - uint64_t mask = ((uint64_t)1 << count) - 1; - bits |= (convert4(pixel) & mask) << c; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert4(__m128i pixel) const{ - pixel = _mm_xor_si128(pixel, _mm_set1_epi8((uint8_t)0x80)); - __m128i cmp0 = _mm_cmpgt_epi8(m_mins, pixel); - __m128i cmp1 = _mm_cmpgt_epi8(pixel, m_maxs); - cmp0 = _mm_or_si128(cmp0, cmp1); - cmp0 = _mm_cmpeq_epi32(cmp0, _mm_setzero_si128()); - return _mm_movemask_ps(_mm_castsi128_ps(cmp0)); - } - -private: - __m128i m_mins; - __m128i m_maxs; -}; - - - -class Compressor_RgbEuclidean_x64_SSE41{ -public: - Compressor_RgbEuclidean_x64_SSE41(uint32_t expected, double max_euclidean_distance) - : m_expected_ag(_mm_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ - uint64_t bits = 0; - size_t c = 0; - do{ - __m128i pixel = _mm_loadu_si128((const __m128i*)(pixels + c)); - bits |= convert4(pixel) << c; - c += 4; - }while (c < 64); - return bits; - } - PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ - uint64_t bits = 0; - size_t c = 0; - size_t lc = count / 4; - while (lc--){ - __m128i pixel = _mm_loadu_si128((const __m128i*)pixels); - bits |= convert4(pixel) << c; - pixels += 4; - c += 4; - } - count %= 4; - if (count){ - PartialWordAccess_x64_SSE41 loader(count * sizeof(uint32_t)); - __m128i pixel = loader.load(pixels); - uint64_t mask = ((uint64_t)1 << count) - 1; - bits |= (convert4(pixel) & mask) << c; - } - return bits; - } - -private: - PA_FORCE_INLINE uint64_t convert4(__m128i pixel) const{ - __m128i ag = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x000000ff)); - __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); - - ag = _mm_sub_epi16(ag, m_expected_ag); - rb = _mm_sub_epi16(rb, m_expected_rb); - - __m128i g = _mm_mullo_epi16(ag, ag); - rb = _mm_mullo_epi16(rb, rb); - __m128i r = _mm_srli_epi32(rb, 16); - __m128i b = _mm_and_si128(rb, _mm_set1_epi32(0x0000ffff)); - - __m128i sum_sqr = _mm_add_epi32(r, g); - sum_sqr = _mm_add_epi32(sum_sqr, b); - - __m128i cmp = _mm_cmpgt_epi32(m_distance_squared, sum_sqr); - return _mm_movemask_ps(_mm_castsi128_ps(cmp)); - } - -private: - const __m128i m_expected_ag; - const __m128i m_expected_rb; - const __m128i m_distance_squared; -}; - - - - -} -} -#endif +/* Binary Image Basic Filters (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_SSE41_H +#define PokemonAutomation_Kernels_BinaryImage_BasicFilters_x64_SSE41_H + +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class FilterByMask_x64_SSE41{ +public: + FilterByMask_x64_SSE41(uint32_t replacement, bool replace_if_zero) + : m_replacement(_mm_set1_epi32(replacement)) + , m_replace_if_zero(_mm_set1_epi32(replace_if_zero ? 0 : 0xffffffff)) + {} + + PA_FORCE_INLINE void filter64(uint64_t bits, uint32_t* pixels, size_t count = 64) const{ + size_t lc = count / 4; + while (lc--){ + __m128i pixel = _mm_loadu_si128((const __m128i*)pixels); + pixel = filter4((uint32_t)bits & 15, pixel); + _mm_storeu_si128((__m128i*)pixels, pixel); + pixels += 4; + bits >>= 4; + } + count %= 4; + if (count){ + PartialWordAccess_x64_SSE41 loader(count * sizeof(uint32_t)); + __m128i pixel = loader.load(pixels); + pixel = filter4((uint32_t)bits & 15, pixel); + do{ + pixels[0] = _mm_cvtsi128_si32(pixel); + pixel = _mm_srli_si128(pixel, 4); + pixels++; + }while(--count); + } + } + +private: + // Change color in the four pixels according to the lowest four bits in `bits` + PA_FORCE_INLINE __m128i filter4(uint32_t bits, __m128i pixel) const{ + // Duplicate 4-bit pattern into four uint8_t places in `bits` + bits *= 0x01010101; + // convert each uint8_t to be one bit from the lowest four bits in input `bits` + bits &= 0x08040201; + // Load uint32_t `bits` into a 128-bit simd register + __m128i mask = _mm_cvtsi32_si128(bits); + // Expand uint8 values into uint32 values + // So now each pixel (uint32) corresponds to a mask value in `mask` + mask = _mm_cvtepu8_epi32(mask); + // set a pixel in mask to 1 if original mask for the pixel is 0 + mask = _mm_cmpeq_epi32(mask, _mm_setzero_si128()); + // If constructor `replace_if_zero` is true: `m_replace_if_zero` is all 0-bits + // then XOR it, mask becomes the same, so it's the inverse of the original mask + // ---- + // If constructor `replace_if_zero` is false: `m_replace_if_zero` is all 1-bits + // then XOR it, masks becomes the inverse, so it's the same as the original maask + mask = _mm_xor_si128(mask, m_replace_if_zero); + // If constructor `replace_if_zero` is true, + // If mask is non-zero, which means if original mask is zero, use m_replacement + // Otherwise, remain the old pixel color + // --- + // If constructor `replace_if_zero` is false, + // If mask is non-zero, which means the original mask non-zero, use m_replacement + // Otherwise, remain the old pixel color + return _mm_blendv_epi8(pixel, m_replacement, mask); + } + +private: + __m128i m_replacement; + __m128i m_replace_if_zero; +}; + + + +class Compressor_RgbRange_x64_SSE41{ +public: + Compressor_RgbRange_x64_SSE41(uint32_t mins, uint32_t maxs) + : m_mins(_mm_set1_epi32(mins ^ 0x80808080)) + , m_maxs(_mm_set1_epi32(maxs ^ 0x80808080)) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + size_t c = 0; + do{ + __m128i pixel = _mm_loadu_si128((const __m128i*)(pixels + c)); + bits |= convert4(pixel) << c; + c += 4; + }while (c < 64); + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + size_t lc = count / 4; + while (lc--){ + __m128i pixel = _mm_loadu_si128((const __m128i*)pixels); + bits |= convert4(pixel) << c; + pixels += 4; + c += 4; + } + count %= 4; + if (count){ + PartialWordAccess_x64_SSE41 loader(count * sizeof(uint32_t)); + __m128i pixel = loader.load(pixels); + uint64_t mask = ((uint64_t)1 << count) - 1; + bits |= (convert4(pixel) & mask) << c; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert4(__m128i pixel) const{ + pixel = _mm_xor_si128(pixel, _mm_set1_epi8((uint8_t)0x80)); + __m128i cmp0 = _mm_cmpgt_epi8(m_mins, pixel); + __m128i cmp1 = _mm_cmpgt_epi8(pixel, m_maxs); + cmp0 = _mm_or_si128(cmp0, cmp1); + cmp0 = _mm_cmpeq_epi32(cmp0, _mm_setzero_si128()); + return _mm_movemask_ps(_mm_castsi128_ps(cmp0)); + } + +private: + __m128i m_mins; + __m128i m_maxs; +}; + + + +class Compressor_RgbEuclidean_x64_SSE41{ +public: + Compressor_RgbEuclidean_x64_SSE41(uint32_t expected, double max_euclidean_distance) + : m_expected_ag(_mm_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels) const{ + uint64_t bits = 0; + size_t c = 0; + do{ + __m128i pixel = _mm_loadu_si128((const __m128i*)(pixels + c)); + bits |= convert4(pixel) << c; + c += 4; + }while (c < 64); + return bits; + } + PA_FORCE_INLINE uint64_t convert64(const uint32_t* pixels, size_t count) const{ + uint64_t bits = 0; + size_t c = 0; + size_t lc = count / 4; + while (lc--){ + __m128i pixel = _mm_loadu_si128((const __m128i*)pixels); + bits |= convert4(pixel) << c; + pixels += 4; + c += 4; + } + count %= 4; + if (count){ + PartialWordAccess_x64_SSE41 loader(count * sizeof(uint32_t)); + __m128i pixel = loader.load(pixels); + uint64_t mask = ((uint64_t)1 << count) - 1; + bits |= (convert4(pixel) & mask) << c; + } + return bits; + } + +private: + PA_FORCE_INLINE uint64_t convert4(__m128i pixel) const{ + __m128i ag = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x000000ff)); + __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); + + ag = _mm_sub_epi16(ag, m_expected_ag); + rb = _mm_sub_epi16(rb, m_expected_rb); + + __m128i g = _mm_mullo_epi16(ag, ag); + rb = _mm_mullo_epi16(rb, rb); + __m128i r = _mm_srli_epi32(rb, 16); + __m128i b = _mm_and_si128(rb, _mm_set1_epi32(0x0000ffff)); + + __m128i sum_sqr = _mm_add_epi32(r, g); + sum_sqr = _mm_add_epi32(sum_sqr, b); + + __m128i cmp = _mm_cmpgt_epi32(m_distance_squared, sum_sqr); + return _mm_movemask_ps(_mm_castsi128_ps(cmp)); + } + +private: + const __m128i m_expected_ag; + const __m128i m_expected_rb; + const __m128i m_distance_squared; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.cpp index 5fb4f5f45b..23fed2bb27 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.cpp @@ -1,217 +1,217 @@ -/* Binary Matrix - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -BinaryMatrixType get_BinaryMatrixType(){ - -#ifdef PA_ARCH_x86 -// if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ -// return BinaryMatrixType::i64x32_x64_AVX512; -// } - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return BinaryMatrixType::i64x32_x64_AVX512; - } - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return BinaryMatrixType::i64x16_x64_AVX2; - } - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return BinaryMatrixType::i64x8_x64_SSE42; - } -#elif PA_ARCH_arm64 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return BinaryMatrixType::arm64x8_x64_NEON; - } -#endif - -// return BinaryMatrixType::i64x8_Default; - return BinaryMatrixType::i64x4_Default; -} - - -std::unique_ptr make_PackedBinaryMatrix_64x4_Default(); -std::unique_ptr make_PackedBinaryMatrix_64x4_Default(size_t width, size_t height); -std::unique_ptr make_PackedBinaryMatrix_64x8_Default(); -std::unique_ptr make_PackedBinaryMatrix_64x8_Default(size_t width, size_t height); - -std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(); -std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height); -std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(); -std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height); -std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(); -std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height); -std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(); -std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height); - -std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(); -std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height); - -std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type){ - switch (type){ - -#ifdef PA_ARCH_x86 -#ifdef PA_AutoDispatch_x64_19_IceLake - case BinaryMatrixType::i64x32_x64_AVX512: - return make_PackedBinaryMatrix_64x32_x64_AVX512(); -#endif -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - return make_PackedBinaryMatrix_64x64_x64_AVX512(); -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return make_PackedBinaryMatrix_64x16_x64_AVX2(); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return make_PackedBinaryMatrix_64x8_x64_SSE42(); -#endif -#elif PA_ARCH_arm64 -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return make_PackedBinaryMatrix_64x8_arm64_NEON(); -#endif -#endif - - case BinaryMatrixType::i64x8_Default: - return make_PackedBinaryMatrix_64x8_Default(); - case BinaryMatrixType::i64x4_Default: - return make_PackedBinaryMatrix_64x4_Default(); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} -std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type, size_t width, size_t height){ - switch (type){ - -#ifdef PA_ARCH_x86 -#ifdef PA_AutoDispatch_x64_19_IceLake - case BinaryMatrixType::i64x32_x64_AVX512: - return make_PackedBinaryMatrix_64x32_x64_AVX512(width, height); -#endif -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - return make_PackedBinaryMatrix_64x64_x64_AVX512(width, height); -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return make_PackedBinaryMatrix_64x16_x64_AVX2(width, height); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return make_PackedBinaryMatrix_64x8_x64_SSE42(width, height); -#endif -#elif PA_ARCH_arm64 -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return make_PackedBinaryMatrix_64x8_arm64_NEON(width, height); -#endif -#endif - - case BinaryMatrixType::i64x8_Default: - return make_PackedBinaryMatrix_64x8_Default(width, height); - case BinaryMatrixType::i64x4_Default: - return make_PackedBinaryMatrix_64x4_Default(width, height); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} - - -std::unique_ptr make_SparseBinaryMatrix_64x4_Default(); -std::unique_ptr make_SparseBinaryMatrix_64x4_Default(size_t width, size_t height); -std::unique_ptr make_SparseBinaryMatrix_64x8_Default(); -std::unique_ptr make_SparseBinaryMatrix_64x8_Default(size_t width, size_t height); - -std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(); -std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height); -std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(); -std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height); -std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(); -std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height); -std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(); -std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height); - -std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(); -std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height); - -std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type){ - switch (type){ - -#ifdef PA_ARCH_x86 -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - return make_SparseBinaryMatrix_64x64_x64_AVX512(); -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return make_SparseBinaryMatrix_64x16_x64_AVX2(); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return make_SparseBinaryMatrix_64x8_x64_SSE42(); -#endif -#elif PA_ARCH_arm64 -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return make_SparseBinaryMatrix_64x8_arm64_NEON(); -#endif -#endif - - case BinaryMatrixType::i64x8_Default: - return make_SparseBinaryMatrix_64x8_Default(); - case BinaryMatrixType::i64x4_Default: - return make_SparseBinaryMatrix_64x4_Default(); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} -std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type, size_t width, size_t height){ - switch (type){ - -#ifdef PA_ARCH_x86 -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - return make_SparseBinaryMatrix_64x64_x64_AVX512(width, height); -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return make_SparseBinaryMatrix_64x16_x64_AVX2(width, height); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return make_SparseBinaryMatrix_64x8_x64_SSE42(width, height); -#endif -#elif PA_ARCH_arm64 -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return make_SparseBinaryMatrix_64x8_arm64_NEON(width, height); -#endif -#endif - - case BinaryMatrixType::i64x8_Default: - return make_SparseBinaryMatrix_64x8_Default(width, height); - case BinaryMatrixType::i64x4_Default: - return make_SparseBinaryMatrix_64x4_Default(width, height); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} - - - - -} -} +/* Binary Matrix + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +BinaryMatrixType get_BinaryMatrixType(){ + +#ifdef PA_ARCH_x86 +// if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ +// return BinaryMatrixType::i64x32_x64_AVX512; +// } + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return BinaryMatrixType::i64x32_x64_AVX512; + } + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return BinaryMatrixType::i64x16_x64_AVX2; + } + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return BinaryMatrixType::i64x8_x64_SSE42; + } +#elif PA_ARCH_arm64 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return BinaryMatrixType::arm64x8_x64_NEON; + } +#endif + +// return BinaryMatrixType::i64x8_Default; + return BinaryMatrixType::i64x4_Default; +} + + +std::unique_ptr make_PackedBinaryMatrix_64x4_Default(); +std::unique_ptr make_PackedBinaryMatrix_64x4_Default(size_t width, size_t height); +std::unique_ptr make_PackedBinaryMatrix_64x8_Default(); +std::unique_ptr make_PackedBinaryMatrix_64x8_Default(size_t width, size_t height); + +std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(); +std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height); +std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(); +std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height); +std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(); +std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height); +std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(); +std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height); + +std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(); +std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height); + +std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type){ + switch (type){ + +#ifdef PA_ARCH_x86 +#ifdef PA_AutoDispatch_x64_19_IceLake + case BinaryMatrixType::i64x32_x64_AVX512: + return make_PackedBinaryMatrix_64x32_x64_AVX512(); +#endif +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + return make_PackedBinaryMatrix_64x64_x64_AVX512(); +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return make_PackedBinaryMatrix_64x16_x64_AVX2(); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return make_PackedBinaryMatrix_64x8_x64_SSE42(); +#endif +#elif PA_ARCH_arm64 +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return make_PackedBinaryMatrix_64x8_arm64_NEON(); +#endif +#endif + + case BinaryMatrixType::i64x8_Default: + return make_PackedBinaryMatrix_64x8_Default(); + case BinaryMatrixType::i64x4_Default: + return make_PackedBinaryMatrix_64x4_Default(); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} +std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type, size_t width, size_t height){ + switch (type){ + +#ifdef PA_ARCH_x86 +#ifdef PA_AutoDispatch_x64_19_IceLake + case BinaryMatrixType::i64x32_x64_AVX512: + return make_PackedBinaryMatrix_64x32_x64_AVX512(width, height); +#endif +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + return make_PackedBinaryMatrix_64x64_x64_AVX512(width, height); +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return make_PackedBinaryMatrix_64x16_x64_AVX2(width, height); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return make_PackedBinaryMatrix_64x8_x64_SSE42(width, height); +#endif +#elif PA_ARCH_arm64 +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return make_PackedBinaryMatrix_64x8_arm64_NEON(width, height); +#endif +#endif + + case BinaryMatrixType::i64x8_Default: + return make_PackedBinaryMatrix_64x8_Default(width, height); + case BinaryMatrixType::i64x4_Default: + return make_PackedBinaryMatrix_64x4_Default(width, height); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} + + +std::unique_ptr make_SparseBinaryMatrix_64x4_Default(); +std::unique_ptr make_SparseBinaryMatrix_64x4_Default(size_t width, size_t height); +std::unique_ptr make_SparseBinaryMatrix_64x8_Default(); +std::unique_ptr make_SparseBinaryMatrix_64x8_Default(size_t width, size_t height); + +std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(); +std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height); +std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(); +std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height); +std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(); +std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height); +std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(); +std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height); + +std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(); +std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height); + +std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type){ + switch (type){ + +#ifdef PA_ARCH_x86 +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + return make_SparseBinaryMatrix_64x64_x64_AVX512(); +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return make_SparseBinaryMatrix_64x16_x64_AVX2(); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return make_SparseBinaryMatrix_64x8_x64_SSE42(); +#endif +#elif PA_ARCH_arm64 +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return make_SparseBinaryMatrix_64x8_arm64_NEON(); +#endif +#endif + + case BinaryMatrixType::i64x8_Default: + return make_SparseBinaryMatrix_64x8_Default(); + case BinaryMatrixType::i64x4_Default: + return make_SparseBinaryMatrix_64x4_Default(); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} +std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type, size_t width, size_t height){ + switch (type){ + +#ifdef PA_ARCH_x86 +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + return make_SparseBinaryMatrix_64x64_x64_AVX512(width, height); +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return make_SparseBinaryMatrix_64x16_x64_AVX2(width, height); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return make_SparseBinaryMatrix_64x8_x64_SSE42(width, height); +#endif +#elif PA_ARCH_arm64 +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return make_SparseBinaryMatrix_64x8_arm64_NEON(width, height); +#endif +#endif + + case BinaryMatrixType::i64x8_Default: + return make_SparseBinaryMatrix_64x8_Default(width, height); + case BinaryMatrixType::i64x4_Default: + return make_SparseBinaryMatrix_64x4_Default(width, height); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.h index 10d09affbe..91979842c9 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix.h @@ -1,189 +1,189 @@ -/* Binary Matrix - * - * From: https://github.com/PokemonAutomation/ - * - * This class represents a memory-efficient binary matrix where each bit - * is stored as just one bit in memory. - * - * The representation uses "tiles". So instead of having each row contiguous - * in memory, the space is broken up into "tiles" that provide some vertical - * spatial locality. - * - * This class is mainly used by the Waterfill algorithm which needs vertical - * locality in memory. - * - */ - -// Folder structure: -// - Kernels_BinaryMatrix.h: -// Defines BinaryMatrixType, PackedBinaryMatrix_IB, SparseBinaryMatrix_IB and declares the basic functions to get/create them. -// PackedBinaryMatrix_IB and SparseBinaryMatrix_IB are abstract base classes (ABCs) with no function definitions. -// -// - Kernels_BinaryMatrix.cpp: -// Defines the basic functions to create BinaryMatrixType and the two matrices. -// Note the matrix creation functions are large switch-case code based on CPU architecture. In each case, it calls the -// functinos like make_PackedBinaryMatrix_>x_() which do the actual work. Those architecture-specific -// functions are defined in Kernels_BinaryMatrix_Core_.cpp. -// -// - Kernels_BinaryMatrix_t.h: -// Defines PackedBinaryMatrix_t and SparseBinaryMatrix_t: template classes that implement the ABCs defined in -// Kernels_BinaryMatrix.h. -// The template parameter is Tile, an architecture-specific class that handles SIMD operations on a tile of the matrix content. -// The template classes are just wrappers of PackedBinaryMatrixCore and SparseBinaryMatrixCore defined in -// Kernels_PackedBinaryMatrixCore.h and Kernels_SparseBinaryMatrixCore.h, which host the actual implementation of matrix -// functions. -// -// - Kernels_PackedBinaryMatrixCore.h: -// Defines PackedBinaryMatrixCore wrapped by PackedBinaryMatrix_t. The native code in PackedBinaryMatrixCore is -// architecture-agnostic. It relies on the template parameter Tile for architecture-specific code. -// The Tiles are difined in Kernels_BinaryMatrix_Tile_x_.h. -// -// - Kernels_PackedBinaryMatrixCore.tpp: -// Defines the functions in PackedBinaryMatrixCore. -// -// - Kernels_SparseBinaryMatrixCore.h, Kernels_SparseBinaryMatrixCore.tpp: -// Same to Kernels_PackedBinaryMatrixCore.h and Kernels_PackedBinaryMatrixCore.tpp but for SparseBinaryMatrixCore. -// -// - Kernels_BinaryMatrix_Arch_x_.h: -// Defines aliases for PackedBinaryMatrix_t and PackedBinaryMatrixCore so they are easier to use. -// e.g. PackedBinaryMatrix_tx_> is defined as PackedBinaryMatrix_x_. -// -// - Kernels_BinaryMatrix_Core_.cpp: -// Defines the boiler-plate functions of creating architecture-specific matrices, needed by Kernels_BinaryMatrix.cpp. -// Those functions just call the constructors of the architecture-specific template classes e.g. -// PackedBinaryMatrix_x_. -// -// - Kernels_BinaryMatrixTile_x_.h: -// The implementation of the architecture-specific tile class BinaryTile_x_ used as template parameter -// of Kernels_Packed/SparseBinaryMatrixCore<> and Packed/SparseBinaryMatrix_t<> - -#ifndef PokemonAutomation_Kernels_PackedBinaryMatrix_H -#define PokemonAutomation_Kernels_PackedBinaryMatrix_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - -// The binary matrix type, which is just what tile shape the matrix uses. -// The shape of the tile is associated with what CPU feature to use. -// For example, for AVX2 feature, the optimized shape is 64x16. -enum class BinaryMatrixType{ - // Default impl. with no SIMD intrinsics, tile size 64-bit width x 4-bit height - i64x4_Default, - // Default impl. with no SIMD intrinsics, tile size 64-bit width x 8-bit height - i64x8_Default, - // Use Intel SSE4.2, tile size 64-bit width x 8-bit height - i64x8_x64_SSE42, - // Use Intel AVX 2, tile size 64-bit width x 16-bit height - i64x16_x64_AVX2, - // Use Intel AVX 512, tile size 64-bit width x 64-bit height - i64x64_x64_AVX512, - // Use Intel AVX 512, tile size 64-bit width x 32-bit height - i64x32_x64_AVX512, - // Use Arm NEON, tile size 64-bit width x 8-bit height - arm64x8_x64_NEON, -}; - -// Get the current active binary matrix type that will be used or is being used -// by waterfill functions and others. -BinaryMatrixType get_BinaryMatrixType(); - -// Abstract class for all implmentations of packed binary matrices. -// Those binary matrices are memory-efficient: each binary element is stored as just one bit in memory. -// The representation uses "tiles". So instead of having each row contiguous in memory, the space is -// broken up into "tiles" that provide some vertical spatial locality. -// This class is mainly used by the Waterfill algorithm which needs vertical locality in memory. -// -// Different implmenetations differ by using different shapes/sizes of tiles. -// To avoid propagating header info of all the implementations and tiles to the code that calls the -// matrices, we use this abstract base class to have minimum exposure to the caller code. -// See "Kernels_BinaryMatrix_t.h" for its derived class, `PackedBinaryMatrix_t`, which is a template -// (with the tile class as the template parameter) and implements some boilerplate matrix-related logic. -// The tile-specific logic is written in each final derived classes, further derived from `PackedBinaryMatrix_t`. -// -// Suffix _IB stands for "internal base (class)". -// Internal means inside the kernel namespace and Kernel/BinaryMatrix folder. -class PackedBinaryMatrix_IB{ -public: - virtual ~PackedBinaryMatrix_IB() = default; - -public: - virtual BinaryMatrixType type() const = 0; - virtual std::unique_ptr clone() const = 0; - - virtual void clear() = 0; - - virtual void set_zero() = 0; // Zero the entire matrix. - virtual void set_ones() = 0; // Set entire matrix to ones. - virtual void invert() = 0; // Invert all bits. - - // Matrix must have same dimensions. - virtual void operator^=(const PackedBinaryMatrix_IB& x) = 0; - virtual void operator|=(const PackedBinaryMatrix_IB& x) = 0; - virtual void operator&=(const PackedBinaryMatrix_IB& x) = 0; - - // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". - virtual std::string dump() const = 0; - // Print part of max as 0s and 1s. Rows are ended with "\n". - virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const = 0; - // Print all the underlying tiles that form this binary matrix. The result is a matrix that may be larger - // than the original matrix. - virtual std::string dump_tiles() const = 0; - -public: - virtual size_t width() const = 0; - virtual size_t height() const = 0; - - // These are slow. - virtual bool get(size_t x, size_t y) const = 0; - virtual void set(size_t x, size_t y, bool set) = 0; - - virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const = 0; -}; -std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type); -std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type, size_t width, size_t height); - - - -class SparseBinaryMatrix_IB{ -public: - virtual ~SparseBinaryMatrix_IB() = default; - -public: - virtual BinaryMatrixType type() const = 0; - virtual std::unique_ptr clone() const = 0; - - virtual void clear() = 0; - - virtual void operator^=(const SparseBinaryMatrix_IB& x) = 0; - virtual void operator|=(const SparseBinaryMatrix_IB& x) = 0; - virtual void operator&=(const SparseBinaryMatrix_IB& x) = 0; - -public: - virtual size_t width() const = 0; - virtual size_t height() const = 0; - - // These are slow. - virtual bool get(size_t x, size_t y) const = 0; - virtual void set(size_t x, size_t y, bool set) = 0; - - virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const = 0; - - virtual std::string dump() const = 0; - virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const = 0; -}; -std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type); -std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type, size_t width, size_t height); - - - - - - - - -} -} -#endif +/* Binary Matrix + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents a memory-efficient binary matrix where each bit + * is stored as just one bit in memory. + * + * The representation uses "tiles". So instead of having each row contiguous + * in memory, the space is broken up into "tiles" that provide some vertical + * spatial locality. + * + * This class is mainly used by the Waterfill algorithm which needs vertical + * locality in memory. + * + */ + +// Folder structure: +// - Kernels_BinaryMatrix.h: +// Defines BinaryMatrixType, PackedBinaryMatrix_IB, SparseBinaryMatrix_IB and declares the basic functions to get/create them. +// PackedBinaryMatrix_IB and SparseBinaryMatrix_IB are abstract base classes (ABCs) with no function definitions. +// +// - Kernels_BinaryMatrix.cpp: +// Defines the basic functions to create BinaryMatrixType and the two matrices. +// Note the matrix creation functions are large switch-case code based on CPU architecture. In each case, it calls the +// functinos like make_PackedBinaryMatrix_>x_() which do the actual work. Those architecture-specific +// functions are defined in Kernels_BinaryMatrix_Core_.cpp. +// +// - Kernels_BinaryMatrix_t.h: +// Defines PackedBinaryMatrix_t and SparseBinaryMatrix_t: template classes that implement the ABCs defined in +// Kernels_BinaryMatrix.h. +// The template parameter is Tile, an architecture-specific class that handles SIMD operations on a tile of the matrix content. +// The template classes are just wrappers of PackedBinaryMatrixCore and SparseBinaryMatrixCore defined in +// Kernels_PackedBinaryMatrixCore.h and Kernels_SparseBinaryMatrixCore.h, which host the actual implementation of matrix +// functions. +// +// - Kernels_PackedBinaryMatrixCore.h: +// Defines PackedBinaryMatrixCore wrapped by PackedBinaryMatrix_t. The native code in PackedBinaryMatrixCore is +// architecture-agnostic. It relies on the template parameter Tile for architecture-specific code. +// The Tiles are difined in Kernels_BinaryMatrix_Tile_x_.h. +// +// - Kernels_PackedBinaryMatrixCore.tpp: +// Defines the functions in PackedBinaryMatrixCore. +// +// - Kernels_SparseBinaryMatrixCore.h, Kernels_SparseBinaryMatrixCore.tpp: +// Same to Kernels_PackedBinaryMatrixCore.h and Kernels_PackedBinaryMatrixCore.tpp but for SparseBinaryMatrixCore. +// +// - Kernels_BinaryMatrix_Arch_x_.h: +// Defines aliases for PackedBinaryMatrix_t and PackedBinaryMatrixCore so they are easier to use. +// e.g. PackedBinaryMatrix_tx_> is defined as PackedBinaryMatrix_x_. +// +// - Kernels_BinaryMatrix_Core_.cpp: +// Defines the boiler-plate functions of creating architecture-specific matrices, needed by Kernels_BinaryMatrix.cpp. +// Those functions just call the constructors of the architecture-specific template classes e.g. +// PackedBinaryMatrix_x_. +// +// - Kernels_BinaryMatrixTile_x_.h: +// The implementation of the architecture-specific tile class BinaryTile_x_ used as template parameter +// of Kernels_Packed/SparseBinaryMatrixCore<> and Packed/SparseBinaryMatrix_t<> + +#ifndef PokemonAutomation_Kernels_PackedBinaryMatrix_H +#define PokemonAutomation_Kernels_PackedBinaryMatrix_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + +// The binary matrix type, which is just what tile shape the matrix uses. +// The shape of the tile is associated with what CPU feature to use. +// For example, for AVX2 feature, the optimized shape is 64x16. +enum class BinaryMatrixType{ + // Default impl. with no SIMD intrinsics, tile size 64-bit width x 4-bit height + i64x4_Default, + // Default impl. with no SIMD intrinsics, tile size 64-bit width x 8-bit height + i64x8_Default, + // Use Intel SSE4.2, tile size 64-bit width x 8-bit height + i64x8_x64_SSE42, + // Use Intel AVX 2, tile size 64-bit width x 16-bit height + i64x16_x64_AVX2, + // Use Intel AVX 512, tile size 64-bit width x 64-bit height + i64x64_x64_AVX512, + // Use Intel AVX 512, tile size 64-bit width x 32-bit height + i64x32_x64_AVX512, + // Use Arm NEON, tile size 64-bit width x 8-bit height + arm64x8_x64_NEON, +}; + +// Get the current active binary matrix type that will be used or is being used +// by waterfill functions and others. +BinaryMatrixType get_BinaryMatrixType(); + +// Abstract class for all implmentations of packed binary matrices. +// Those binary matrices are memory-efficient: each binary element is stored as just one bit in memory. +// The representation uses "tiles". So instead of having each row contiguous in memory, the space is +// broken up into "tiles" that provide some vertical spatial locality. +// This class is mainly used by the Waterfill algorithm which needs vertical locality in memory. +// +// Different implmenetations differ by using different shapes/sizes of tiles. +// To avoid propagating header info of all the implementations and tiles to the code that calls the +// matrices, we use this abstract base class to have minimum exposure to the caller code. +// See "Kernels_BinaryMatrix_t.h" for its derived class, `PackedBinaryMatrix_t`, which is a template +// (with the tile class as the template parameter) and implements some boilerplate matrix-related logic. +// The tile-specific logic is written in each final derived classes, further derived from `PackedBinaryMatrix_t`. +// +// Suffix _IB stands for "internal base (class)". +// Internal means inside the kernel namespace and Kernel/BinaryMatrix folder. +class PackedBinaryMatrix_IB{ +public: + virtual ~PackedBinaryMatrix_IB() = default; + +public: + virtual BinaryMatrixType type() const = 0; + virtual std::unique_ptr clone() const = 0; + + virtual void clear() = 0; + + virtual void set_zero() = 0; // Zero the entire matrix. + virtual void set_ones() = 0; // Set entire matrix to ones. + virtual void invert() = 0; // Invert all bits. + + // Matrix must have same dimensions. + virtual void operator^=(const PackedBinaryMatrix_IB& x) = 0; + virtual void operator|=(const PackedBinaryMatrix_IB& x) = 0; + virtual void operator&=(const PackedBinaryMatrix_IB& x) = 0; + + // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". + virtual std::string dump() const = 0; + // Print part of max as 0s and 1s. Rows are ended with "\n". + virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const = 0; + // Print all the underlying tiles that form this binary matrix. The result is a matrix that may be larger + // than the original matrix. + virtual std::string dump_tiles() const = 0; + +public: + virtual size_t width() const = 0; + virtual size_t height() const = 0; + + // These are slow. + virtual bool get(size_t x, size_t y) const = 0; + virtual void set(size_t x, size_t y, bool set) = 0; + + virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const = 0; +}; +std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type); +std::unique_ptr make_PackedBinaryMatrix(BinaryMatrixType type, size_t width, size_t height); + + + +class SparseBinaryMatrix_IB{ +public: + virtual ~SparseBinaryMatrix_IB() = default; + +public: + virtual BinaryMatrixType type() const = 0; + virtual std::unique_ptr clone() const = 0; + + virtual void clear() = 0; + + virtual void operator^=(const SparseBinaryMatrix_IB& x) = 0; + virtual void operator|=(const SparseBinaryMatrix_IB& x) = 0; + virtual void operator&=(const SparseBinaryMatrix_IB& x) = 0; + +public: + virtual size_t width() const = 0; + virtual size_t height() const = 0; + + // These are slow. + virtual bool get(size_t x, size_t y) const = 0; + virtual void set(size_t x, size_t y, bool set) = 0; + + virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const = 0; + + virtual std::string dump() const = 0; + virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const = 0; +}; +std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type); +std::unique_ptr make_SparseBinaryMatrix(BinaryMatrixType type, size_t width, size_t height); + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x16_x64_AVX2.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x16_x64_AVX2.h index 26938619d0..de42a0b760 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x16_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x16_x64_AVX2.h @@ -1,274 +1,274 @@ -/* Binary Matrix Tile (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x16_x64_AVX2_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64x16_x64_AVX2_H - -#include -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct BinaryTile_64x16_x64_AVX2{ - static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x16_x64_AVX2; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = 16; - - __m256i vec[4]; - - -public: - PA_FORCE_INLINE BinaryTile_64x16_x64_AVX2(){ - set_zero(); - } - PA_FORCE_INLINE BinaryTile_64x16_x64_AVX2(const BinaryTile_64x16_x64_AVX2& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - } - PA_FORCE_INLINE void operator=(const BinaryTile_64x16_x64_AVX2& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - } - - -public: - PA_FORCE_INLINE void set_zero(){ - vec[0] = _mm256_setzero_si256(); - vec[1] = _mm256_setzero_si256(); - vec[2] = _mm256_setzero_si256(); - vec[3] = _mm256_setzero_si256(); - } - PA_FORCE_INLINE void set_ones(){ - vec[0] = _mm256_set1_epi32(0xffffffff); - vec[1] = _mm256_set1_epi32(0xffffffff); - vec[2] = _mm256_set1_epi32(0xffffffff); - vec[3] = _mm256_set1_epi32(0xffffffff); - } - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - __m256i word = _mm256_set1_epi64x( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m256i vheight = _mm256_set1_epi64x(height); - __m256i index = _mm256_setr_epi64x(0, 1, 2, 3); - for (size_t c = 0; c < 4; c++){ - __m256i mask = _mm256_cmpgt_epi64(vheight, index); - vec[c] = _mm256_and_si256(mask, word); - index = _mm256_add_epi64(index, _mm256_set1_epi64x(4)); - } - } - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - __m256i word = _mm256_set1_epi64x( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m256i vheight = _mm256_set1_epi64x(height); - __m256i index = _mm256_setr_epi64x(0, 1, 2, 3); - for (size_t c = 0; c < 4; c++){ - __m256i mask = _mm256_cmpgt_epi64(vheight, index); - mask = _mm256_and_si256(mask, word); - vec[c] = _mm256_and_si256(vec[c], mask); - index = _mm256_add_epi64(index, _mm256_set1_epi64x(4)); - } - } - PA_FORCE_INLINE void invert(){ - vec[0] = _mm256_xor_si256(vec[0], _mm256_set1_epi32(0xffffffff)); - vec[1] = _mm256_xor_si256(vec[1], _mm256_set1_epi32(0xffffffff)); - vec[2] = _mm256_xor_si256(vec[2], _mm256_set1_epi32(0xffffffff)); - vec[3] = _mm256_xor_si256(vec[3], _mm256_set1_epi32(0xffffffff)); - } - PA_FORCE_INLINE void operator^=(const BinaryTile_64x16_x64_AVX2& x){ - vec[0] = _mm256_xor_si256(vec[0], x.vec[0]); - vec[1] = _mm256_xor_si256(vec[1], x.vec[1]); - vec[2] = _mm256_xor_si256(vec[2], x.vec[2]); - vec[3] = _mm256_xor_si256(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void operator|=(const BinaryTile_64x16_x64_AVX2& x){ - vec[0] = _mm256_or_si256(vec[0], x.vec[0]); - vec[1] = _mm256_or_si256(vec[1], x.vec[1]); - vec[2] = _mm256_or_si256(vec[2], x.vec[2]); - vec[3] = _mm256_or_si256(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void operator&=(const BinaryTile_64x16_x64_AVX2& x){ - vec[0] = _mm256_and_si256(vec[0], x.vec[0]); - vec[1] = _mm256_and_si256(vec[1], x.vec[1]); - vec[2] = _mm256_and_si256(vec[2], x.vec[2]); - vec[3] = _mm256_and_si256(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void andnot(const BinaryTile_64x16_x64_AVX2& x){ - vec[0] = _mm256_andnot_si256(x.vec[0], vec[0]); - vec[1] = _mm256_andnot_si256(x.vec[1], vec[1]); - vec[2] = _mm256_andnot_si256(x.vec[2], vec[2]); - vec[3] = _mm256_andnot_si256(x.vec[3], vec[3]); - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return ((const uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return ((uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return ((const uint64_t*)vec)[15]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return ((uint64_t*)vec)[15]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return ((const uint64_t*)vec)[index]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return ((uint64_t*)vec)[index]; - } - - // These are slow. - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < 16; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy the current tile into "tile" while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may of arbitrary shift and alignment. - - void copy_to_shift_pp(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ - // (+x, +y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 13){ - __m256i r0 = _mm256_loadu_si256((const __m256i*)(src + shift_y)); - r0 = _mm256_srl_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); - _mm256_store_si256((__m256i*)dest, r0); - dest += 4; - shift_y += 4; - } - if (shift_y < 16){ - __m256i mask = _mm256_set1_epi64x(shift_y); - mask = _mm256_cmpgt_epi64(_mm256_setr_epi64x(16, 15, 14, 13), mask); - __m256i r0 = _mm256_maskload_epi64((const long long*)(src + shift_y), mask); - r0 = _mm256_srl_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); - _mm256_store_si256((__m256i*)dest, r0); - } - } - void copy_to_shift_np(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ - // (-x, +y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 13){ - __m256i r0 = _mm256_loadu_si256((const __m256i*)(src + shift_y)); - r0 = _mm256_sll_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); - _mm256_store_si256((__m256i*)dest, r0); - dest += 4; - shift_y += 4; - } - if (shift_y < 16){ - __m256i mask = _mm256_set1_epi64x(shift_y); - mask = _mm256_cmpgt_epi64(_mm256_setr_epi64x(16, 15, 14, 13), mask); - __m256i r0 = _mm256_maskload_epi64((const long long*)(src + shift_y), mask); - r0 = _mm256_sll_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); - _mm256_store_si256((__m256i*)dest, r0); - } - } - void copy_to_shift_pn(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ - // (+x, -y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - size_t align = (16 - shift_y) & 3; - if (align){ - src += align - 4; - shift_y += align - 4; - __m256i mask = _mm256_set1_epi64x(align); - mask = _mm256_cmpgt_epi64(mask, _mm256_setr_epi64x(3, 2, 1, 0)); - __m256i r0 = _mm256_maskload_epi64((const long long*)src, mask); - r0 = _mm256_srl_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); - _mm256_store_si256((__m256i*)(dest + shift_y), r0); - src += 4; - shift_y += 4; - } - while (shift_y < 16){ - __m256i r0 = _mm256_loadu_si256((const __m256i*)src); - r0 = _mm256_srl_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); - _mm256_store_si256((__m256i*)(dest + shift_y), r0); - src += 4; - shift_y += 4; - } - } - void copy_to_shift_nn(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ - // (-x, -y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - size_t align = (16 - shift_y) & 3; - if (align){ - src += align - 4; - shift_y += align - 4; - __m256i mask = _mm256_set1_epi64x(align); - mask = _mm256_cmpgt_epi64(mask, _mm256_setr_epi64x(3, 2, 1, 0)); - __m256i r0 = _mm256_maskload_epi64((const long long*)src, mask); - r0 = _mm256_sll_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); - _mm256_store_si256((__m256i*)(dest + shift_y), r0); - src += 4; - shift_y += 4; - } - while (shift_y < 16){ - __m256i r0 = _mm256_loadu_si256((const __m256i*)src); - r0 = _mm256_sll_epi64(r0, shift); - r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); - _mm256_store_si256((__m256i*)(dest + shift_y), r0); - src += 4; - shift_y += 4; - } - } -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x16_x64_AVX2_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64x16_x64_AVX2_H + +#include +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct BinaryTile_64x16_x64_AVX2{ + static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x16_x64_AVX2; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = 16; + + __m256i vec[4]; + + +public: + PA_FORCE_INLINE BinaryTile_64x16_x64_AVX2(){ + set_zero(); + } + PA_FORCE_INLINE BinaryTile_64x16_x64_AVX2(const BinaryTile_64x16_x64_AVX2& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + } + PA_FORCE_INLINE void operator=(const BinaryTile_64x16_x64_AVX2& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + } + + +public: + PA_FORCE_INLINE void set_zero(){ + vec[0] = _mm256_setzero_si256(); + vec[1] = _mm256_setzero_si256(); + vec[2] = _mm256_setzero_si256(); + vec[3] = _mm256_setzero_si256(); + } + PA_FORCE_INLINE void set_ones(){ + vec[0] = _mm256_set1_epi32(0xffffffff); + vec[1] = _mm256_set1_epi32(0xffffffff); + vec[2] = _mm256_set1_epi32(0xffffffff); + vec[3] = _mm256_set1_epi32(0xffffffff); + } + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + __m256i word = _mm256_set1_epi64x( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m256i vheight = _mm256_set1_epi64x(height); + __m256i index = _mm256_setr_epi64x(0, 1, 2, 3); + for (size_t c = 0; c < 4; c++){ + __m256i mask = _mm256_cmpgt_epi64(vheight, index); + vec[c] = _mm256_and_si256(mask, word); + index = _mm256_add_epi64(index, _mm256_set1_epi64x(4)); + } + } + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + __m256i word = _mm256_set1_epi64x( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m256i vheight = _mm256_set1_epi64x(height); + __m256i index = _mm256_setr_epi64x(0, 1, 2, 3); + for (size_t c = 0; c < 4; c++){ + __m256i mask = _mm256_cmpgt_epi64(vheight, index); + mask = _mm256_and_si256(mask, word); + vec[c] = _mm256_and_si256(vec[c], mask); + index = _mm256_add_epi64(index, _mm256_set1_epi64x(4)); + } + } + PA_FORCE_INLINE void invert(){ + vec[0] = _mm256_xor_si256(vec[0], _mm256_set1_epi32(0xffffffff)); + vec[1] = _mm256_xor_si256(vec[1], _mm256_set1_epi32(0xffffffff)); + vec[2] = _mm256_xor_si256(vec[2], _mm256_set1_epi32(0xffffffff)); + vec[3] = _mm256_xor_si256(vec[3], _mm256_set1_epi32(0xffffffff)); + } + PA_FORCE_INLINE void operator^=(const BinaryTile_64x16_x64_AVX2& x){ + vec[0] = _mm256_xor_si256(vec[0], x.vec[0]); + vec[1] = _mm256_xor_si256(vec[1], x.vec[1]); + vec[2] = _mm256_xor_si256(vec[2], x.vec[2]); + vec[3] = _mm256_xor_si256(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void operator|=(const BinaryTile_64x16_x64_AVX2& x){ + vec[0] = _mm256_or_si256(vec[0], x.vec[0]); + vec[1] = _mm256_or_si256(vec[1], x.vec[1]); + vec[2] = _mm256_or_si256(vec[2], x.vec[2]); + vec[3] = _mm256_or_si256(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void operator&=(const BinaryTile_64x16_x64_AVX2& x){ + vec[0] = _mm256_and_si256(vec[0], x.vec[0]); + vec[1] = _mm256_and_si256(vec[1], x.vec[1]); + vec[2] = _mm256_and_si256(vec[2], x.vec[2]); + vec[3] = _mm256_and_si256(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void andnot(const BinaryTile_64x16_x64_AVX2& x){ + vec[0] = _mm256_andnot_si256(x.vec[0], vec[0]); + vec[1] = _mm256_andnot_si256(x.vec[1], vec[1]); + vec[2] = _mm256_andnot_si256(x.vec[2], vec[2]); + vec[3] = _mm256_andnot_si256(x.vec[3], vec[3]); + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return ((const uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return ((uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return ((const uint64_t*)vec)[15]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return ((uint64_t*)vec)[15]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return ((const uint64_t*)vec)[index]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return ((uint64_t*)vec)[index]; + } + + // These are slow. + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < 16; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy the current tile into "tile" while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may of arbitrary shift and alignment. + + void copy_to_shift_pp(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ + // (+x, +y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 13){ + __m256i r0 = _mm256_loadu_si256((const __m256i*)(src + shift_y)); + r0 = _mm256_srl_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); + _mm256_store_si256((__m256i*)dest, r0); + dest += 4; + shift_y += 4; + } + if (shift_y < 16){ + __m256i mask = _mm256_set1_epi64x(shift_y); + mask = _mm256_cmpgt_epi64(_mm256_setr_epi64x(16, 15, 14, 13), mask); + __m256i r0 = _mm256_maskload_epi64((const long long*)(src + shift_y), mask); + r0 = _mm256_srl_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); + _mm256_store_si256((__m256i*)dest, r0); + } + } + void copy_to_shift_np(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ + // (-x, +y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 13){ + __m256i r0 = _mm256_loadu_si256((const __m256i*)(src + shift_y)); + r0 = _mm256_sll_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); + _mm256_store_si256((__m256i*)dest, r0); + dest += 4; + shift_y += 4; + } + if (shift_y < 16){ + __m256i mask = _mm256_set1_epi64x(shift_y); + mask = _mm256_cmpgt_epi64(_mm256_setr_epi64x(16, 15, 14, 13), mask); + __m256i r0 = _mm256_maskload_epi64((const long long*)(src + shift_y), mask); + r0 = _mm256_sll_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)dest)); + _mm256_store_si256((__m256i*)dest, r0); + } + } + void copy_to_shift_pn(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ + // (+x, -y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + size_t align = (16 - shift_y) & 3; + if (align){ + src += align - 4; + shift_y += align - 4; + __m256i mask = _mm256_set1_epi64x(align); + mask = _mm256_cmpgt_epi64(mask, _mm256_setr_epi64x(3, 2, 1, 0)); + __m256i r0 = _mm256_maskload_epi64((const long long*)src, mask); + r0 = _mm256_srl_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); + _mm256_store_si256((__m256i*)(dest + shift_y), r0); + src += 4; + shift_y += 4; + } + while (shift_y < 16){ + __m256i r0 = _mm256_loadu_si256((const __m256i*)src); + r0 = _mm256_srl_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); + _mm256_store_si256((__m256i*)(dest + shift_y), r0); + src += 4; + shift_y += 4; + } + } + void copy_to_shift_nn(BinaryTile_64x16_x64_AVX2& tile, size_t shift_x, size_t shift_y) const{ + // (-x, -y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + size_t align = (16 - shift_y) & 3; + if (align){ + src += align - 4; + shift_y += align - 4; + __m256i mask = _mm256_set1_epi64x(align); + mask = _mm256_cmpgt_epi64(mask, _mm256_setr_epi64x(3, 2, 1, 0)); + __m256i r0 = _mm256_maskload_epi64((const long long*)src, mask); + r0 = _mm256_sll_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); + _mm256_store_si256((__m256i*)(dest + shift_y), r0); + src += 4; + shift_y += 4; + } + while (shift_y < 16){ + __m256i r0 = _mm256_loadu_si256((const __m256i*)src); + r0 = _mm256_sll_epi64(r0, shift); + r0 = _mm256_or_si256(r0, _mm256_load_si256((__m256i*)(dest + shift_y))); + _mm256_store_si256((__m256i*)(dest + shift_y), r0); + src += 4; + shift_y += 4; + } + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x32_x64_AVX512.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x32_x64_AVX512.h index 4d332b5b02..4e0868d2af 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x32_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x32_x64_AVX512.h @@ -1,281 +1,281 @@ -/* Binary Matrix Tile (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x32_x64_AVX512_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64x32_x64_AVX512_H - -#include -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct BinaryTile_64x32_x64_AVX512{ - static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x32_x64_AVX512; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = 32; - - __m512i vec[4]; - -public: - PA_FORCE_INLINE BinaryTile_64x32_x64_AVX512(){ - set_zero(); - } - PA_FORCE_INLINE BinaryTile_64x32_x64_AVX512(const BinaryTile_64x32_x64_AVX512& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - } - PA_FORCE_INLINE void operator=(const BinaryTile_64x32_x64_AVX512& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - } - - -public: - PA_FORCE_INLINE void set_zero(){ - vec[0] = _mm512_setzero_si512(); - vec[1] = _mm512_setzero_si512(); - vec[2] = _mm512_setzero_si512(); - vec[3] = _mm512_setzero_si512(); - } - PA_FORCE_INLINE void set_ones(){ - vec[0] = _mm512_set1_epi32(0xffffffff); - vec[1] = _mm512_set1_epi32(0xffffffff); - vec[2] = _mm512_set1_epi32(0xffffffff); - vec[3] = _mm512_set1_epi32(0xffffffff); - } - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - __m512i word = _mm512_set1_epi64( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m512i vheight = _mm512_set1_epi64(height); - __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 4; c++){ - __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); - vec[c] = _mm512_maskz_mov_epi64(mask, word); - index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); - } - } - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - __m512i word = _mm512_set1_epi64( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m512i vheight = _mm512_set1_epi64(height); - __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 4; c++){ - __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); - __m512i maskv = _mm512_maskz_mov_epi64(mask, word); - vec[c] = _mm512_and_si512(vec[c], maskv); - index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); - } - } - PA_FORCE_INLINE void invert(){ - vec[0] = _mm512_xor_si512(vec[0], _mm512_set1_epi32(0xffffffff)); - vec[1] = _mm512_xor_si512(vec[1], _mm512_set1_epi32(0xffffffff)); - vec[2] = _mm512_xor_si512(vec[2], _mm512_set1_epi32(0xffffffff)); - vec[3] = _mm512_xor_si512(vec[3], _mm512_set1_epi32(0xffffffff)); - } - PA_FORCE_INLINE void operator^=(const BinaryTile_64x32_x64_AVX512& x){ - vec[0] = _mm512_xor_si512(vec[0], x.vec[0]); - vec[1] = _mm512_xor_si512(vec[1], x.vec[1]); - vec[2] = _mm512_xor_si512(vec[2], x.vec[2]); - vec[3] = _mm512_xor_si512(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void operator|=(const BinaryTile_64x32_x64_AVX512& x){ - vec[0] = _mm512_or_si512(vec[0], x.vec[0]); - vec[1] = _mm512_or_si512(vec[1], x.vec[1]); - vec[2] = _mm512_or_si512(vec[2], x.vec[2]); - vec[3] = _mm512_or_si512(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void operator&=(const BinaryTile_64x32_x64_AVX512& x){ - vec[0] = _mm512_and_si512(vec[0], x.vec[0]); - vec[1] = _mm512_and_si512(vec[1], x.vec[1]); - vec[2] = _mm512_and_si512(vec[2], x.vec[2]); - vec[3] = _mm512_and_si512(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void andnot(const BinaryTile_64x32_x64_AVX512& x){ - vec[0] = _mm512_andnot_si512(x.vec[0], vec[0]); - vec[1] = _mm512_andnot_si512(x.vec[1], vec[1]); - vec[2] = _mm512_andnot_si512(x.vec[2], vec[2]); - vec[3] = _mm512_andnot_si512(x.vec[3], vec[3]); - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return ((const uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return ((uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return ((const uint64_t*)vec)[31]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return ((uint64_t*)vec)[31]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return ((const uint64_t*)vec)[index]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return ((uint64_t*)vec)[index]; - } - - // These are slow. - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < 32; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy the current tile into "tile" while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may of arbitrary shift and alignment. - - void copy_to_shift_pp(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (+x, +y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 25){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); - _mm512_store_si512((__m512i*)dest, r0); - dest += 8; - shift_y += 8; - } - if (shift_y < 32){ - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_setr_epi64(32, 31, 30, 29, 28, 27, 26, 25), - _mm512_set1_epi64(shift_y) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); - _mm512_store_si512((__m256i*)dest, r0); - } - } - void copy_to_shift_np(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (-x, +y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 25){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); - _mm512_store_si512((__m512i*)dest, r0); - dest += 8; - shift_y += 8; - } - if (shift_y < 32){ - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_setr_epi64(32, 31, 30, 29, 28, 27, 26, 25), - _mm512_set1_epi64(shift_y) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); - _mm512_store_si512((__m256i*)dest, r0); - } - } - void copy_to_shift_pn(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (+x, -y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - size_t align = (32 - shift_y) & 7; - if (align){ - src += align - 8; - shift_y += align - 8; - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_set1_epi64(align), - _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - while (shift_y < 32){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)src); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - } - void copy_to_shift_nn(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (-x, -y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - size_t align = (32 - shift_y) & 7; - if (align){ - src += align - 8; - shift_y += align - 8; - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_set1_epi64(align), - _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - while (shift_y < 32){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)src); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - } -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x32_x64_AVX512_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64x32_x64_AVX512_H + +#include +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct BinaryTile_64x32_x64_AVX512{ + static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x32_x64_AVX512; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = 32; + + __m512i vec[4]; + +public: + PA_FORCE_INLINE BinaryTile_64x32_x64_AVX512(){ + set_zero(); + } + PA_FORCE_INLINE BinaryTile_64x32_x64_AVX512(const BinaryTile_64x32_x64_AVX512& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + } + PA_FORCE_INLINE void operator=(const BinaryTile_64x32_x64_AVX512& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + } + + +public: + PA_FORCE_INLINE void set_zero(){ + vec[0] = _mm512_setzero_si512(); + vec[1] = _mm512_setzero_si512(); + vec[2] = _mm512_setzero_si512(); + vec[3] = _mm512_setzero_si512(); + } + PA_FORCE_INLINE void set_ones(){ + vec[0] = _mm512_set1_epi32(0xffffffff); + vec[1] = _mm512_set1_epi32(0xffffffff); + vec[2] = _mm512_set1_epi32(0xffffffff); + vec[3] = _mm512_set1_epi32(0xffffffff); + } + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + __m512i word = _mm512_set1_epi64( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m512i vheight = _mm512_set1_epi64(height); + __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 4; c++){ + __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); + vec[c] = _mm512_maskz_mov_epi64(mask, word); + index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); + } + } + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + __m512i word = _mm512_set1_epi64( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m512i vheight = _mm512_set1_epi64(height); + __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 4; c++){ + __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); + __m512i maskv = _mm512_maskz_mov_epi64(mask, word); + vec[c] = _mm512_and_si512(vec[c], maskv); + index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); + } + } + PA_FORCE_INLINE void invert(){ + vec[0] = _mm512_xor_si512(vec[0], _mm512_set1_epi32(0xffffffff)); + vec[1] = _mm512_xor_si512(vec[1], _mm512_set1_epi32(0xffffffff)); + vec[2] = _mm512_xor_si512(vec[2], _mm512_set1_epi32(0xffffffff)); + vec[3] = _mm512_xor_si512(vec[3], _mm512_set1_epi32(0xffffffff)); + } + PA_FORCE_INLINE void operator^=(const BinaryTile_64x32_x64_AVX512& x){ + vec[0] = _mm512_xor_si512(vec[0], x.vec[0]); + vec[1] = _mm512_xor_si512(vec[1], x.vec[1]); + vec[2] = _mm512_xor_si512(vec[2], x.vec[2]); + vec[3] = _mm512_xor_si512(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void operator|=(const BinaryTile_64x32_x64_AVX512& x){ + vec[0] = _mm512_or_si512(vec[0], x.vec[0]); + vec[1] = _mm512_or_si512(vec[1], x.vec[1]); + vec[2] = _mm512_or_si512(vec[2], x.vec[2]); + vec[3] = _mm512_or_si512(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void operator&=(const BinaryTile_64x32_x64_AVX512& x){ + vec[0] = _mm512_and_si512(vec[0], x.vec[0]); + vec[1] = _mm512_and_si512(vec[1], x.vec[1]); + vec[2] = _mm512_and_si512(vec[2], x.vec[2]); + vec[3] = _mm512_and_si512(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void andnot(const BinaryTile_64x32_x64_AVX512& x){ + vec[0] = _mm512_andnot_si512(x.vec[0], vec[0]); + vec[1] = _mm512_andnot_si512(x.vec[1], vec[1]); + vec[2] = _mm512_andnot_si512(x.vec[2], vec[2]); + vec[3] = _mm512_andnot_si512(x.vec[3], vec[3]); + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return ((const uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return ((uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return ((const uint64_t*)vec)[31]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return ((uint64_t*)vec)[31]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return ((const uint64_t*)vec)[index]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return ((uint64_t*)vec)[index]; + } + + // These are slow. + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < 32; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy the current tile into "tile" while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may of arbitrary shift and alignment. + + void copy_to_shift_pp(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (+x, +y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 25){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); + _mm512_store_si512((__m512i*)dest, r0); + dest += 8; + shift_y += 8; + } + if (shift_y < 32){ + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_setr_epi64(32, 31, 30, 29, 28, 27, 26, 25), + _mm512_set1_epi64(shift_y) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); + _mm512_store_si512((__m256i*)dest, r0); + } + } + void copy_to_shift_np(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (-x, +y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 25){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); + _mm512_store_si512((__m512i*)dest, r0); + dest += 8; + shift_y += 8; + } + if (shift_y < 32){ + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_setr_epi64(32, 31, 30, 29, 28, 27, 26, 25), + _mm512_set1_epi64(shift_y) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); + _mm512_store_si512((__m256i*)dest, r0); + } + } + void copy_to_shift_pn(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (+x, -y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + size_t align = (32 - shift_y) & 7; + if (align){ + src += align - 8; + shift_y += align - 8; + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_set1_epi64(align), + _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + while (shift_y < 32){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)src); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + } + void copy_to_shift_nn(BinaryTile_64x32_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (-x, -y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + size_t align = (32 - shift_y) & 7; + if (align){ + src += align - 8; + shift_y += align - 8; + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_set1_epi64(align), + _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + while (shift_y < 32){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)src); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h index cc8f16e0d0..2fd7e8b343 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h @@ -1,183 +1,183 @@ -/* Binary Matrix Tile (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x4_Default_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64x4_Default_H - -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct BinaryTile_64x4_Default{ - static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x4_Default; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = 4; - - uint64_t vec[4]; - - -public: - PA_FORCE_INLINE BinaryTile_64x4_Default(){ - set_zero(); - } - - -public: - PA_FORCE_INLINE void set_zero(){ - vec[0] = 0; - vec[1] = 0; - vec[2] = 0; - vec[3] = 0; - } - PA_FORCE_INLINE void set_ones(){ - vec[0] = 0xffffffffffffffff; - vec[1] = 0xffffffffffffffff; - vec[2] = 0xffffffffffffffff; - vec[3] = 0xffffffffffffffff; - } - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - uint64_t word = width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff; - size_t c = 0; - for (; c < height; c++){ - vec[c] = word; - } - for (; c < 4; c++){ - vec[c] = 0; - } - } - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - uint64_t word = width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff; - size_t c = 0; - for (; c < height; c++){ - vec[c] &= word; - } - for (; c < 4; c++){ - vec[c] = 0; - } - } - PA_FORCE_INLINE void invert(){ - vec[0] = ~vec[0]; - vec[1] = ~vec[1]; - vec[2] = ~vec[2]; - vec[3] = ~vec[3]; - } - PA_FORCE_INLINE void operator^=(const BinaryTile_64x4_Default& x){ - vec[0] ^= x.vec[0]; - vec[1] ^= x.vec[1]; - vec[2] ^= x.vec[2]; - vec[3] ^= x.vec[3]; - } - PA_FORCE_INLINE void operator|=(const BinaryTile_64x4_Default& x){ - vec[0] |= x.vec[0]; - vec[1] |= x.vec[1]; - vec[2] |= x.vec[2]; - vec[3] |= x.vec[3]; - } - PA_FORCE_INLINE void operator&=(const BinaryTile_64x4_Default& x){ - vec[0] &= x.vec[0]; - vec[1] &= x.vec[1]; - vec[2] &= x.vec[2]; - vec[3] &= x.vec[3]; - } - PA_FORCE_INLINE void andnot(const BinaryTile_64x4_Default& x){ - vec[0] &= ~x.vec[0]; - vec[1] &= ~x.vec[1]; - vec[2] &= ~x.vec[2]; - vec[3] &= ~x.vec[3]; - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return vec[0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return vec[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return vec[3]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return vec[3]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return vec[index]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return vec[index]; - } - - // These are slow. - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < 4; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy the current tile into "tile" while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may of arbitrary shift and alignment. - - void copy_to_shift_pp(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ - // (+x, +y) - for (size_t c = 0; shift_y < 4; shift_y++, c++){ - tile.vec[c] |= vec[shift_y] >> shift_x; - } - } - void copy_to_shift_np(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ - // (-x, +y) - for (size_t c = 0; shift_y < 4; shift_y++, c++){ - tile.vec[c] |= vec[shift_y] << shift_x; - } - } - void copy_to_shift_pn(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ - // (+x, -y) - for (size_t c = 0; shift_y < 4; shift_y++, c++){ - tile.vec[shift_y] |= vec[c] >> shift_x; - } - } - void copy_to_shift_nn(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ - // (-x, -y) - for (size_t c = 0; shift_y < 4; shift_y++, c++){ - tile.vec[shift_y] |= vec[c] << shift_x; - } - } - -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x4_Default_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64x4_Default_H + +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct BinaryTile_64x4_Default{ + static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x4_Default; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = 4; + + uint64_t vec[4]; + + +public: + PA_FORCE_INLINE BinaryTile_64x4_Default(){ + set_zero(); + } + + +public: + PA_FORCE_INLINE void set_zero(){ + vec[0] = 0; + vec[1] = 0; + vec[2] = 0; + vec[3] = 0; + } + PA_FORCE_INLINE void set_ones(){ + vec[0] = 0xffffffffffffffff; + vec[1] = 0xffffffffffffffff; + vec[2] = 0xffffffffffffffff; + vec[3] = 0xffffffffffffffff; + } + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + uint64_t word = width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff; + size_t c = 0; + for (; c < height; c++){ + vec[c] = word; + } + for (; c < 4; c++){ + vec[c] = 0; + } + } + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + uint64_t word = width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff; + size_t c = 0; + for (; c < height; c++){ + vec[c] &= word; + } + for (; c < 4; c++){ + vec[c] = 0; + } + } + PA_FORCE_INLINE void invert(){ + vec[0] = ~vec[0]; + vec[1] = ~vec[1]; + vec[2] = ~vec[2]; + vec[3] = ~vec[3]; + } + PA_FORCE_INLINE void operator^=(const BinaryTile_64x4_Default& x){ + vec[0] ^= x.vec[0]; + vec[1] ^= x.vec[1]; + vec[2] ^= x.vec[2]; + vec[3] ^= x.vec[3]; + } + PA_FORCE_INLINE void operator|=(const BinaryTile_64x4_Default& x){ + vec[0] |= x.vec[0]; + vec[1] |= x.vec[1]; + vec[2] |= x.vec[2]; + vec[3] |= x.vec[3]; + } + PA_FORCE_INLINE void operator&=(const BinaryTile_64x4_Default& x){ + vec[0] &= x.vec[0]; + vec[1] &= x.vec[1]; + vec[2] &= x.vec[2]; + vec[3] &= x.vec[3]; + } + PA_FORCE_INLINE void andnot(const BinaryTile_64x4_Default& x){ + vec[0] &= ~x.vec[0]; + vec[1] &= ~x.vec[1]; + vec[2] &= ~x.vec[2]; + vec[3] &= ~x.vec[3]; + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return vec[0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return vec[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return vec[3]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return vec[3]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return vec[index]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return vec[index]; + } + + // These are slow. + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < 4; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy the current tile into "tile" while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may of arbitrary shift and alignment. + + void copy_to_shift_pp(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ + // (+x, +y) + for (size_t c = 0; shift_y < 4; shift_y++, c++){ + tile.vec[c] |= vec[shift_y] >> shift_x; + } + } + void copy_to_shift_np(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ + // (-x, +y) + for (size_t c = 0; shift_y < 4; shift_y++, c++){ + tile.vec[c] |= vec[shift_y] << shift_x; + } + } + void copy_to_shift_pn(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ + // (+x, -y) + for (size_t c = 0; shift_y < 4; shift_y++, c++){ + tile.vec[shift_y] |= vec[c] >> shift_x; + } + } + void copy_to_shift_nn(BinaryTile_64x4_Default& tile, size_t shift_x, size_t shift_y) const{ + // (-x, -y) + for (size_t c = 0; shift_y < 4; shift_y++, c++){ + tile.vec[shift_y] |= vec[c] << shift_x; + } + } + +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x64_x64_AVX512.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x64_x64_AVX512.h index ffb935abfc..c44a2de38d 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x64_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x64_x64_AVX512.h @@ -1,317 +1,317 @@ -/* Binary Matrix Tile (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x64_x64_AVX512_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64x64_x64_AVX512_H - -#include -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct BinaryTile_64x64_x64_AVX512{ - static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x64_x64_AVX512; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = 64; - - __m512i vec[8]; - -public: - PA_FORCE_INLINE BinaryTile_64x64_x64_AVX512(){ - set_zero(); - } - PA_FORCE_INLINE BinaryTile_64x64_x64_AVX512(const BinaryTile_64x64_x64_AVX512& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - vec[4] = x.vec[4]; - vec[5] = x.vec[5]; - vec[6] = x.vec[6]; - vec[7] = x.vec[7]; - } - PA_FORCE_INLINE void operator=(const BinaryTile_64x64_x64_AVX512& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - vec[4] = x.vec[4]; - vec[5] = x.vec[5]; - vec[6] = x.vec[6]; - vec[7] = x.vec[7]; - } - - -public: - PA_FORCE_INLINE void set_zero(){ - vec[0] = _mm512_setzero_si512(); - vec[1] = _mm512_setzero_si512(); - vec[2] = _mm512_setzero_si512(); - vec[3] = _mm512_setzero_si512(); - vec[4] = _mm512_setzero_si512(); - vec[5] = _mm512_setzero_si512(); - vec[6] = _mm512_setzero_si512(); - vec[7] = _mm512_setzero_si512(); - } - PA_FORCE_INLINE void set_ones(){ - vec[0] = _mm512_set1_epi32(0xffffffff); - vec[1] = _mm512_set1_epi32(0xffffffff); - vec[2] = _mm512_set1_epi32(0xffffffff); - vec[3] = _mm512_set1_epi32(0xffffffff); - vec[4] = _mm512_set1_epi32(0xffffffff); - vec[5] = _mm512_set1_epi32(0xffffffff); - vec[6] = _mm512_set1_epi32(0xffffffff); - vec[7] = _mm512_set1_epi32(0xffffffff); - } - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - __m512i word = _mm512_set1_epi64( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m512i vheight = _mm512_set1_epi64(height); - __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 8; c++){ - __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); - vec[c] = _mm512_maskz_mov_epi64(mask, word); - index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); - } - } - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - __m512i word = _mm512_set1_epi64( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m512i vheight = _mm512_set1_epi64(height); - __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 8; c++){ - __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); - __m512i maskv = _mm512_maskz_mov_epi64(mask, word); - vec[c] = _mm512_and_si512(vec[c], maskv); - index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); - } - } - PA_FORCE_INLINE void invert(){ - vec[0] = _mm512_xor_si512(vec[0], _mm512_set1_epi32(0xffffffff)); - vec[1] = _mm512_xor_si512(vec[1], _mm512_set1_epi32(0xffffffff)); - vec[2] = _mm512_xor_si512(vec[2], _mm512_set1_epi32(0xffffffff)); - vec[3] = _mm512_xor_si512(vec[3], _mm512_set1_epi32(0xffffffff)); - vec[4] = _mm512_xor_si512(vec[4], _mm512_set1_epi32(0xffffffff)); - vec[5] = _mm512_xor_si512(vec[5], _mm512_set1_epi32(0xffffffff)); - vec[6] = _mm512_xor_si512(vec[6], _mm512_set1_epi32(0xffffffff)); - vec[7] = _mm512_xor_si512(vec[7], _mm512_set1_epi32(0xffffffff)); - } - PA_FORCE_INLINE void operator^=(const BinaryTile_64x64_x64_AVX512& x){ - vec[0] = _mm512_xor_si512(vec[0], x.vec[0]); - vec[1] = _mm512_xor_si512(vec[1], x.vec[1]); - vec[2] = _mm512_xor_si512(vec[2], x.vec[2]); - vec[3] = _mm512_xor_si512(vec[3], x.vec[3]); - vec[4] = _mm512_xor_si512(vec[4], x.vec[4]); - vec[5] = _mm512_xor_si512(vec[5], x.vec[5]); - vec[6] = _mm512_xor_si512(vec[6], x.vec[6]); - vec[7] = _mm512_xor_si512(vec[7], x.vec[7]); - } - PA_FORCE_INLINE void operator|=(const BinaryTile_64x64_x64_AVX512& x){ - vec[0] = _mm512_or_si512(vec[0], x.vec[0]); - vec[1] = _mm512_or_si512(vec[1], x.vec[1]); - vec[2] = _mm512_or_si512(vec[2], x.vec[2]); - vec[3] = _mm512_or_si512(vec[3], x.vec[3]); - vec[4] = _mm512_or_si512(vec[4], x.vec[4]); - vec[5] = _mm512_or_si512(vec[5], x.vec[5]); - vec[6] = _mm512_or_si512(vec[6], x.vec[6]); - vec[7] = _mm512_or_si512(vec[7], x.vec[7]); - } - PA_FORCE_INLINE void operator&=(const BinaryTile_64x64_x64_AVX512& x){ - vec[0] = _mm512_and_si512(vec[0], x.vec[0]); - vec[1] = _mm512_and_si512(vec[1], x.vec[1]); - vec[2] = _mm512_and_si512(vec[2], x.vec[2]); - vec[3] = _mm512_and_si512(vec[3], x.vec[3]); - vec[4] = _mm512_and_si512(vec[4], x.vec[4]); - vec[5] = _mm512_and_si512(vec[5], x.vec[5]); - vec[6] = _mm512_and_si512(vec[6], x.vec[6]); - vec[7] = _mm512_and_si512(vec[7], x.vec[7]); - } - PA_FORCE_INLINE void andnot(const BinaryTile_64x64_x64_AVX512& x){ - vec[0] = _mm512_andnot_si512(x.vec[0], vec[0]); - vec[1] = _mm512_andnot_si512(x.vec[1], vec[1]); - vec[2] = _mm512_andnot_si512(x.vec[2], vec[2]); - vec[3] = _mm512_andnot_si512(x.vec[3], vec[3]); - vec[4] = _mm512_andnot_si512(x.vec[4], vec[4]); - vec[5] = _mm512_andnot_si512(x.vec[5], vec[5]); - vec[6] = _mm512_andnot_si512(x.vec[6], vec[6]); - vec[7] = _mm512_andnot_si512(x.vec[7], vec[7]); - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return ((const uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return ((uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return ((const uint64_t*)vec)[63]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return ((uint64_t*)vec)[63]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return ((const uint64_t*)vec)[index]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return ((uint64_t*)vec)[index]; - } - - // These are slow. - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < 64; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy the current tile into "tile" while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may of arbitrary shift and alignment. - - void copy_to_shift_pp(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (+x, +y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 57){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); - _mm512_store_si512((__m512i*)dest, r0); - dest += 8; - shift_y += 8; - } - if (shift_y < 64){ - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_setr_epi64(64, 63, 62, 61, 60, 59, 58, 57), - _mm512_set1_epi64(shift_y) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); - _mm512_store_si512((__m256i*)dest, r0); - } - } - void copy_to_shift_np(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (-x, +y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 57){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); - _mm512_store_si512((__m512i*)dest, r0); - dest += 8; - shift_y += 8; - } - if (shift_y < 64){ - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_setr_epi64(64, 63, 62, 61, 60, 59, 58, 57), - _mm512_set1_epi64(shift_y) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); - _mm512_store_si512((__m256i*)dest, r0); - } - } - void copy_to_shift_pn(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (+x, -y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - size_t align = (64 - shift_y) & 7; - if (align){ - src += align - 8; - shift_y += align - 8; - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_set1_epi64(align), - _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - while (shift_y < 64){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)src); - r0 = _mm512_srlv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - } - void copy_to_shift_nn(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ - // (-x, -y) - __m512i shift = _mm512_set1_epi64(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - size_t align = (64 - shift_y) & 7; - if (align){ - src += align - 8; - shift_y += align - 8; - __mmask8 mask = _mm512_cmpgt_epu64_mask( - _mm512_set1_epi64(align), - _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) - ); - __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - while (shift_y < 64){ - __m512i r0 = _mm512_loadu_si512((const __m512i*)src); - r0 = _mm512_sllv_epi64(r0, shift); - r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); - _mm512_store_si512((__m512i*)(dest + shift_y), r0); - src += 8; - shift_y += 8; - } - } -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x64_x64_AVX512_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64x64_x64_AVX512_H + +#include +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct BinaryTile_64x64_x64_AVX512{ + static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x64_x64_AVX512; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = 64; + + __m512i vec[8]; + +public: + PA_FORCE_INLINE BinaryTile_64x64_x64_AVX512(){ + set_zero(); + } + PA_FORCE_INLINE BinaryTile_64x64_x64_AVX512(const BinaryTile_64x64_x64_AVX512& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + vec[4] = x.vec[4]; + vec[5] = x.vec[5]; + vec[6] = x.vec[6]; + vec[7] = x.vec[7]; + } + PA_FORCE_INLINE void operator=(const BinaryTile_64x64_x64_AVX512& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + vec[4] = x.vec[4]; + vec[5] = x.vec[5]; + vec[6] = x.vec[6]; + vec[7] = x.vec[7]; + } + + +public: + PA_FORCE_INLINE void set_zero(){ + vec[0] = _mm512_setzero_si512(); + vec[1] = _mm512_setzero_si512(); + vec[2] = _mm512_setzero_si512(); + vec[3] = _mm512_setzero_si512(); + vec[4] = _mm512_setzero_si512(); + vec[5] = _mm512_setzero_si512(); + vec[6] = _mm512_setzero_si512(); + vec[7] = _mm512_setzero_si512(); + } + PA_FORCE_INLINE void set_ones(){ + vec[0] = _mm512_set1_epi32(0xffffffff); + vec[1] = _mm512_set1_epi32(0xffffffff); + vec[2] = _mm512_set1_epi32(0xffffffff); + vec[3] = _mm512_set1_epi32(0xffffffff); + vec[4] = _mm512_set1_epi32(0xffffffff); + vec[5] = _mm512_set1_epi32(0xffffffff); + vec[6] = _mm512_set1_epi32(0xffffffff); + vec[7] = _mm512_set1_epi32(0xffffffff); + } + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + __m512i word = _mm512_set1_epi64( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m512i vheight = _mm512_set1_epi64(height); + __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 8; c++){ + __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); + vec[c] = _mm512_maskz_mov_epi64(mask, word); + index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); + } + } + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + __m512i word = _mm512_set1_epi64( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m512i vheight = _mm512_set1_epi64(height); + __m512i index = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 8; c++){ + __mmask8 mask = _mm512_cmplt_epi64_mask(index, vheight); + __m512i maskv = _mm512_maskz_mov_epi64(mask, word); + vec[c] = _mm512_and_si512(vec[c], maskv); + index = _mm512_add_epi64(index, _mm512_set1_epi64(8)); + } + } + PA_FORCE_INLINE void invert(){ + vec[0] = _mm512_xor_si512(vec[0], _mm512_set1_epi32(0xffffffff)); + vec[1] = _mm512_xor_si512(vec[1], _mm512_set1_epi32(0xffffffff)); + vec[2] = _mm512_xor_si512(vec[2], _mm512_set1_epi32(0xffffffff)); + vec[3] = _mm512_xor_si512(vec[3], _mm512_set1_epi32(0xffffffff)); + vec[4] = _mm512_xor_si512(vec[4], _mm512_set1_epi32(0xffffffff)); + vec[5] = _mm512_xor_si512(vec[5], _mm512_set1_epi32(0xffffffff)); + vec[6] = _mm512_xor_si512(vec[6], _mm512_set1_epi32(0xffffffff)); + vec[7] = _mm512_xor_si512(vec[7], _mm512_set1_epi32(0xffffffff)); + } + PA_FORCE_INLINE void operator^=(const BinaryTile_64x64_x64_AVX512& x){ + vec[0] = _mm512_xor_si512(vec[0], x.vec[0]); + vec[1] = _mm512_xor_si512(vec[1], x.vec[1]); + vec[2] = _mm512_xor_si512(vec[2], x.vec[2]); + vec[3] = _mm512_xor_si512(vec[3], x.vec[3]); + vec[4] = _mm512_xor_si512(vec[4], x.vec[4]); + vec[5] = _mm512_xor_si512(vec[5], x.vec[5]); + vec[6] = _mm512_xor_si512(vec[6], x.vec[6]); + vec[7] = _mm512_xor_si512(vec[7], x.vec[7]); + } + PA_FORCE_INLINE void operator|=(const BinaryTile_64x64_x64_AVX512& x){ + vec[0] = _mm512_or_si512(vec[0], x.vec[0]); + vec[1] = _mm512_or_si512(vec[1], x.vec[1]); + vec[2] = _mm512_or_si512(vec[2], x.vec[2]); + vec[3] = _mm512_or_si512(vec[3], x.vec[3]); + vec[4] = _mm512_or_si512(vec[4], x.vec[4]); + vec[5] = _mm512_or_si512(vec[5], x.vec[5]); + vec[6] = _mm512_or_si512(vec[6], x.vec[6]); + vec[7] = _mm512_or_si512(vec[7], x.vec[7]); + } + PA_FORCE_INLINE void operator&=(const BinaryTile_64x64_x64_AVX512& x){ + vec[0] = _mm512_and_si512(vec[0], x.vec[0]); + vec[1] = _mm512_and_si512(vec[1], x.vec[1]); + vec[2] = _mm512_and_si512(vec[2], x.vec[2]); + vec[3] = _mm512_and_si512(vec[3], x.vec[3]); + vec[4] = _mm512_and_si512(vec[4], x.vec[4]); + vec[5] = _mm512_and_si512(vec[5], x.vec[5]); + vec[6] = _mm512_and_si512(vec[6], x.vec[6]); + vec[7] = _mm512_and_si512(vec[7], x.vec[7]); + } + PA_FORCE_INLINE void andnot(const BinaryTile_64x64_x64_AVX512& x){ + vec[0] = _mm512_andnot_si512(x.vec[0], vec[0]); + vec[1] = _mm512_andnot_si512(x.vec[1], vec[1]); + vec[2] = _mm512_andnot_si512(x.vec[2], vec[2]); + vec[3] = _mm512_andnot_si512(x.vec[3], vec[3]); + vec[4] = _mm512_andnot_si512(x.vec[4], vec[4]); + vec[5] = _mm512_andnot_si512(x.vec[5], vec[5]); + vec[6] = _mm512_andnot_si512(x.vec[6], vec[6]); + vec[7] = _mm512_andnot_si512(x.vec[7], vec[7]); + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return ((const uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return ((uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return ((const uint64_t*)vec)[63]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return ((uint64_t*)vec)[63]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return ((const uint64_t*)vec)[index]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return ((uint64_t*)vec)[index]; + } + + // These are slow. + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < 64; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy the current tile into "tile" while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may of arbitrary shift and alignment. + + void copy_to_shift_pp(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (+x, +y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 57){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); + _mm512_store_si512((__m512i*)dest, r0); + dest += 8; + shift_y += 8; + } + if (shift_y < 64){ + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_setr_epi64(64, 63, 62, 61, 60, 59, 58, 57), + _mm512_set1_epi64(shift_y) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); + _mm512_store_si512((__m256i*)dest, r0); + } + } + void copy_to_shift_np(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (-x, +y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 57){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)(src + shift_y)); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)dest)); + _mm512_store_si512((__m512i*)dest, r0); + dest += 8; + shift_y += 8; + } + if (shift_y < 64){ + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_setr_epi64(64, 63, 62, 61, 60, 59, 58, 57), + _mm512_set1_epi64(shift_y) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)(src + shift_y)); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m256i*)dest)); + _mm512_store_si512((__m256i*)dest, r0); + } + } + void copy_to_shift_pn(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (+x, -y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + size_t align = (64 - shift_y) & 7; + if (align){ + src += align - 8; + shift_y += align - 8; + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_set1_epi64(align), + _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + while (shift_y < 64){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)src); + r0 = _mm512_srlv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + } + void copy_to_shift_nn(BinaryTile_64x64_x64_AVX512& tile, size_t shift_x, size_t shift_y) const{ + // (-x, -y) + __m512i shift = _mm512_set1_epi64(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + size_t align = (64 - shift_y) & 7; + if (align){ + src += align - 8; + shift_y += align - 8; + __mmask8 mask = _mm512_cmpgt_epu64_mask( + _mm512_set1_epi64(align), + _mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0) + ); + __m512i r0 = _mm512_maskz_load_epi64(mask, (const int64_t*)src); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + while (shift_y < 64){ + __m512i r0 = _mm512_loadu_si512((const __m512i*)src); + r0 = _mm512_sllv_epi64(r0, shift); + r0 = _mm512_or_si512(r0, _mm512_load_si512((__m512i*)(dest + shift_y))); + _mm512_store_si512((__m512i*)(dest + shift_y), r0); + src += 8; + shift_y += 8; + } + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h index 3bb1fb50a1..19de121870 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h @@ -1,304 +1,304 @@ -/* Binary Matrix Tile (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x8_arm64_NEON_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64x8_arm64_NEON_H - -#include -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct BinaryTile_64x8_arm64_NEON{ - static constexpr BinaryMatrixType TYPE = BinaryMatrixType::arm64x8_x64_NEON; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = 8; - - uint64x2x4_t vec; - -public: - PA_FORCE_INLINE BinaryTile_64x8_arm64_NEON(){ - set_zero(); - } - PA_FORCE_INLINE BinaryTile_64x8_arm64_NEON(const BinaryTile_64x8_arm64_NEON& x){ - vec.val[0] = x.vec.val[0]; - vec.val[1] = x.vec.val[1]; - vec.val[2] = x.vec.val[2]; - vec.val[3] = x.vec.val[3]; - } - PA_FORCE_INLINE void operator=(const BinaryTile_64x8_arm64_NEON& x){ - vec.val[0] = x.vec.val[0]; - vec.val[1] = x.vec.val[1]; - vec.val[2] = x.vec.val[2]; - vec.val[3] = x.vec.val[3]; - } - - -public: - PA_FORCE_INLINE void set_zero(){ - vec.val[0] = vreinterpretq_u64_u8(vdupq_n_u8(0)); - vec.val[1] = vreinterpretq_u64_u8(vdupq_n_u8(0)); - vec.val[2] = vreinterpretq_u64_u8(vdupq_n_u8(0)); - vec.val[3] = vreinterpretq_u64_u8(vdupq_n_u8(0)); - } - PA_FORCE_INLINE void set_ones(){ - vec.val[0] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); - vec.val[1] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); - vec.val[2] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); - vec.val[3] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); - } - // Set a tile with partial 1 bits. The 1-bits are in a sub-block (0, 0, width, height). - // The rest of the tile is filled with 0 bits. - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - uint64x2_t word = vdupq_n_u64( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - uint64x2_t vheight = vdupq_n_u64(height); - uint64x2_t mask; - // If height > (0, 1) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(0), vcreate_u64(1))); // low, high - vec.val[0] = vandq_u64(mask, word); - // If height > (2, 3) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(2), vcreate_u64(3))); // low, high - vec.val[1] = vandq_u64(mask, word); - // If height > (4, 5) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(4), vcreate_u64(5))); // low, high - vec.val[2] = vandq_u64(mask, word); - // If height > (6, 7) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(6), vcreate_u64(7))); // low, high - vec.val[3] = vandq_u64(mask, word); - } - // Retain the tile content in sub-block (0, 0, width, height), clear the rest with 0 bits. - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - uint64x2_t word = vdupq_n_u64( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - uint64x2_t vheight = vdupq_n_u64(height); - uint64x2_t mask; - // If height > (0, 1) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(0), vcreate_u64(1))); // low, high - vec.val[0] = vandq_u64(vec.val[0], vandq_u64(mask, word)); - // If height > (2, 3) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(2), vcreate_u64(3))); // low, high - vec.val[1] = vandq_u64(vec.val[1], vandq_u64(mask, word)); - // If height > (4, 5) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(4), vcreate_u64(5))); // low, high - vec.val[2] = vandq_u64(vec.val[2], vandq_u64(mask, word)); - // If height > (6, 7) - mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(6), vcreate_u64(7))); // low, high - vec.val[3] = vandq_u64(vec.val[3], vandq_u64(mask, word)); - } - // Invert all bits by logical XOR with all 1 bits - PA_FORCE_INLINE void invert(){ - vec.val[0] = veorq_u64(vec.val[0], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); - vec.val[1] = veorq_u64(vec.val[1], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); - vec.val[2] = veorq_u64(vec.val[2], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); - vec.val[3] = veorq_u64(vec.val[3], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); - } - // logical XOR assign - PA_FORCE_INLINE void operator^=(const BinaryTile_64x8_arm64_NEON& x){ - vec.val[0] = veorq_u64(vec.val[0], x.vec.val[0]); - vec.val[1] = veorq_u64(vec.val[1], x.vec.val[1]); - vec.val[2] = veorq_u64(vec.val[2], x.vec.val[2]); - vec.val[3] = veorq_u64(vec.val[3], x.vec.val[3]); - } - // logical OR assign - PA_FORCE_INLINE void operator|=(const BinaryTile_64x8_arm64_NEON& x){ - vec.val[0] = vorrq_u64(vec.val[0], x.vec.val[0]); - vec.val[1] = vorrq_u64(vec.val[1], x.vec.val[1]); - vec.val[2] = vorrq_u64(vec.val[2], x.vec.val[2]); - vec.val[3] = vorrq_u64(vec.val[3], x.vec.val[3]); - } - // logical AND assign - PA_FORCE_INLINE void operator&=(const BinaryTile_64x8_arm64_NEON& x){ - vec.val[0] = vandq_u64(vec.val[0], x.vec.val[0]); - vec.val[1] = vandq_u64(vec.val[1], x.vec.val[1]); - vec.val[2] = vandq_u64(vec.val[2], x.vec.val[2]); - vec.val[3] = vandq_u64(vec.val[3], x.vec.val[3]); - } - // this = (NOT x) AND this - PA_FORCE_INLINE void andnot(const BinaryTile_64x8_arm64_NEON& x){ - // vbicq_u64(a, b): a AND (NOT b) - vec.val[0] = vbicq_u64(vec.val[0], x.vec.val[0]); - vec.val[1] = vbicq_u64(vec.val[1], x.vec.val[1]); - vec.val[2] = vbicq_u64(vec.val[2], x.vec.val[2]); - vec.val[3] = vbicq_u64(vec.val[3], x.vec.val[3]); - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return vec.val[0][0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return ((uint64_t*)&vec.val[0])[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return vec.val[3][1]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return ((uint64_t*)&vec.val[3])[1]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return vec.val[index/2][index%2]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return ((uint64_t*)&vec.val[index/2])[index%2]; - } - - // Slow function: get bit at coordinate (x, y), x: [0, width), y: [0, height) - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - // Slow function: set bit at coordinate (x, y), x: [0, width), y: [0, height) - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < 8; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy part of this tile into `tile` while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may have arbitrary shift and alignment. - // The area covered by `tile` on the image is (+shift_x, +shift_y) from the area of this tile. - // - // The suffix "_pp" stands for positive (x), positive (y). - // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. - // In this way the operation does not damage other un-assigned regions on `tile`. - void copy_to_shift_pp(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ - int64x2_t neg_shift_x_u64x2 = vmovq_n_s64(-(int64_t)shift_x); - const uint64_t* src = (const uint64_t*)&vec; - uint64_t* dest = (uint64_t*)&tile.vec; - while (shift_y < 7){ - uint64x2_t row_64x2 = vld1q_u64(src + shift_y); - // NEON only has left shift with a variable. So have to left shift by a negative value - // to create right shift. - row_64x2 = vshlq_u64(row_64x2, neg_shift_x_u64x2); - row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest)); - vst1q_u64(dest, row_64x2); - dest += 2; - shift_y += 2; - } - if (shift_y < 8){ - dest[0] |= src[shift_y] >> shift_x; - } - } - // Copy part of this tile into `tile` while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may have arbitrary shift and alignment. - // The area covered by `tile` on the image is (-shift_x, +shift_y) from the area of this tile. - // - // The suffix "_np" stands for negative (x), positive (y). - // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. - // In this way it the operation does not damage other un-assigned regions on `tile`. - void copy_to_shift_np(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ - uint64x2_t shift_x_u64x2 = vdupq_n_u64(shift_x); - const uint64_t* src = (const uint64_t*)&vec; - uint64_t* dest = (uint64_t*)&tile.vec; - while (shift_y < 7){ - uint64x2_t row_64x2 = vld1q_u64(src + shift_y); - // left shift - row_64x2 = vshlq_u64(row_64x2, shift_x_u64x2); - row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest)); - vst1q_u64(dest, row_64x2); - dest += 2; - shift_y += 2; - } - if (shift_y < 8){ - dest[0] |= src[shift_y] << shift_x; - } - } - // Copy part of this tile into `tile` while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may have arbitrary shift and alignment. - // The area covered by `tile` on the image is (+shift_x, -shift_y) from the area of this tile. - // - // The suffix "_pn" stands for positive (x), negative (y). - // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. - // In this way it the operation does not damage other un-assigned regions on `tile`. - void copy_to_shift_pn(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ - int64x2_t neg_shift_x_u64x2 = vmovq_n_s64(-(int64_t)shift_x); - const uint64_t* src = (const uint64_t*)&vec; - uint64_t* dest = (uint64_t*)&tile.vec; - if (shift_y & 1){ - dest[shift_y] |= src[0] >> shift_x; - src++; - shift_y++; - } - while (shift_y < 8){ - uint64x2_t row_64x2 = vld1q_u64(src); - // NEON only has left shift with a variable. So have to left shift by a negative value - // to create right shift. - row_64x2 = vshlq_u64(row_64x2, neg_shift_x_u64x2); - row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest + shift_y)); - vst1q_u64((dest + shift_y), row_64x2); - src += 2; - shift_y += 2; - } - } - // Copy part of this tile into `tile` while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may have arbitrary shift and alignment. - // The area covered by `tile` on the image is (-shift_x, -shift_y) from the area of this tile. - // - // The suffix "_nn" stands for negative (x), negative (y). - // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. - // In this way it the operation does not damage other un-assigned regions on `tile`. - void copy_to_shift_nn(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ - uint64x2_t shift_x_u64x2 = vdupq_n_u64(shift_x); - const uint64_t* src = (const uint64_t*)&vec; - uint64_t* dest = (uint64_t*)&tile.vec; - if (shift_y & 1){ - dest[shift_y] |= src[0] << shift_x; - src++; - shift_y++; - } - while (shift_y < 8){ - uint64x2_t row_64x2 = vld1q_u64(src); - // left shift - row_64x2 = vshlq_u64(row_64x2, shift_x_u64x2); - row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest + shift_y)); - vst1q_u64((dest + shift_y), row_64x2); - src += 2; - shift_y += 2; - } - } -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x8_arm64_NEON_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64x8_arm64_NEON_H + +#include +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct BinaryTile_64x8_arm64_NEON{ + static constexpr BinaryMatrixType TYPE = BinaryMatrixType::arm64x8_x64_NEON; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = 8; + + uint64x2x4_t vec; + +public: + PA_FORCE_INLINE BinaryTile_64x8_arm64_NEON(){ + set_zero(); + } + PA_FORCE_INLINE BinaryTile_64x8_arm64_NEON(const BinaryTile_64x8_arm64_NEON& x){ + vec.val[0] = x.vec.val[0]; + vec.val[1] = x.vec.val[1]; + vec.val[2] = x.vec.val[2]; + vec.val[3] = x.vec.val[3]; + } + PA_FORCE_INLINE void operator=(const BinaryTile_64x8_arm64_NEON& x){ + vec.val[0] = x.vec.val[0]; + vec.val[1] = x.vec.val[1]; + vec.val[2] = x.vec.val[2]; + vec.val[3] = x.vec.val[3]; + } + + +public: + PA_FORCE_INLINE void set_zero(){ + vec.val[0] = vreinterpretq_u64_u8(vdupq_n_u8(0)); + vec.val[1] = vreinterpretq_u64_u8(vdupq_n_u8(0)); + vec.val[2] = vreinterpretq_u64_u8(vdupq_n_u8(0)); + vec.val[3] = vreinterpretq_u64_u8(vdupq_n_u8(0)); + } + PA_FORCE_INLINE void set_ones(){ + vec.val[0] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); + vec.val[1] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); + vec.val[2] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); + vec.val[3] = vreinterpretq_u64_u8(vdupq_n_u8(0xff)); + } + // Set a tile with partial 1 bits. The 1-bits are in a sub-block (0, 0, width, height). + // The rest of the tile is filled with 0 bits. + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + uint64x2_t word = vdupq_n_u64( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + uint64x2_t vheight = vdupq_n_u64(height); + uint64x2_t mask; + // If height > (0, 1) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(0), vcreate_u64(1))); // low, high + vec.val[0] = vandq_u64(mask, word); + // If height > (2, 3) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(2), vcreate_u64(3))); // low, high + vec.val[1] = vandq_u64(mask, word); + // If height > (4, 5) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(4), vcreate_u64(5))); // low, high + vec.val[2] = vandq_u64(mask, word); + // If height > (6, 7) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(6), vcreate_u64(7))); // low, high + vec.val[3] = vandq_u64(mask, word); + } + // Retain the tile content in sub-block (0, 0, width, height), clear the rest with 0 bits. + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + uint64x2_t word = vdupq_n_u64( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + uint64x2_t vheight = vdupq_n_u64(height); + uint64x2_t mask; + // If height > (0, 1) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(0), vcreate_u64(1))); // low, high + vec.val[0] = vandq_u64(vec.val[0], vandq_u64(mask, word)); + // If height > (2, 3) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(2), vcreate_u64(3))); // low, high + vec.val[1] = vandq_u64(vec.val[1], vandq_u64(mask, word)); + // If height > (4, 5) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(4), vcreate_u64(5))); // low, high + vec.val[2] = vandq_u64(vec.val[2], vandq_u64(mask, word)); + // If height > (6, 7) + mask = vcgtq_u64(vheight, vcombine_u64(vcreate_u64(6), vcreate_u64(7))); // low, high + vec.val[3] = vandq_u64(vec.val[3], vandq_u64(mask, word)); + } + // Invert all bits by logical XOR with all 1 bits + PA_FORCE_INLINE void invert(){ + vec.val[0] = veorq_u64(vec.val[0], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); + vec.val[1] = veorq_u64(vec.val[1], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); + vec.val[2] = veorq_u64(vec.val[2], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); + vec.val[3] = veorq_u64(vec.val[3], vreinterpretq_u64_u8(vdupq_n_u8(0xff))); + } + // logical XOR assign + PA_FORCE_INLINE void operator^=(const BinaryTile_64x8_arm64_NEON& x){ + vec.val[0] = veorq_u64(vec.val[0], x.vec.val[0]); + vec.val[1] = veorq_u64(vec.val[1], x.vec.val[1]); + vec.val[2] = veorq_u64(vec.val[2], x.vec.val[2]); + vec.val[3] = veorq_u64(vec.val[3], x.vec.val[3]); + } + // logical OR assign + PA_FORCE_INLINE void operator|=(const BinaryTile_64x8_arm64_NEON& x){ + vec.val[0] = vorrq_u64(vec.val[0], x.vec.val[0]); + vec.val[1] = vorrq_u64(vec.val[1], x.vec.val[1]); + vec.val[2] = vorrq_u64(vec.val[2], x.vec.val[2]); + vec.val[3] = vorrq_u64(vec.val[3], x.vec.val[3]); + } + // logical AND assign + PA_FORCE_INLINE void operator&=(const BinaryTile_64x8_arm64_NEON& x){ + vec.val[0] = vandq_u64(vec.val[0], x.vec.val[0]); + vec.val[1] = vandq_u64(vec.val[1], x.vec.val[1]); + vec.val[2] = vandq_u64(vec.val[2], x.vec.val[2]); + vec.val[3] = vandq_u64(vec.val[3], x.vec.val[3]); + } + // this = (NOT x) AND this + PA_FORCE_INLINE void andnot(const BinaryTile_64x8_arm64_NEON& x){ + // vbicq_u64(a, b): a AND (NOT b) + vec.val[0] = vbicq_u64(vec.val[0], x.vec.val[0]); + vec.val[1] = vbicq_u64(vec.val[1], x.vec.val[1]); + vec.val[2] = vbicq_u64(vec.val[2], x.vec.val[2]); + vec.val[3] = vbicq_u64(vec.val[3], x.vec.val[3]); + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return vec.val[0][0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return ((uint64_t*)&vec.val[0])[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return vec.val[3][1]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return ((uint64_t*)&vec.val[3])[1]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return vec.val[index/2][index%2]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return ((uint64_t*)&vec.val[index/2])[index%2]; + } + + // Slow function: get bit at coordinate (x, y), x: [0, width), y: [0, height) + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + // Slow function: set bit at coordinate (x, y), x: [0, width), y: [0, height) + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < 8; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy part of this tile into `tile` while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may have arbitrary shift and alignment. + // The area covered by `tile` on the image is (+shift_x, +shift_y) from the area of this tile. + // + // The suffix "_pp" stands for positive (x), positive (y). + // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. + // In this way the operation does not damage other un-assigned regions on `tile`. + void copy_to_shift_pp(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ + int64x2_t neg_shift_x_u64x2 = vmovq_n_s64(-(int64_t)shift_x); + const uint64_t* src = (const uint64_t*)&vec; + uint64_t* dest = (uint64_t*)&tile.vec; + while (shift_y < 7){ + uint64x2_t row_64x2 = vld1q_u64(src + shift_y); + // NEON only has left shift with a variable. So have to left shift by a negative value + // to create right shift. + row_64x2 = vshlq_u64(row_64x2, neg_shift_x_u64x2); + row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest)); + vst1q_u64(dest, row_64x2); + dest += 2; + shift_y += 2; + } + if (shift_y < 8){ + dest[0] |= src[shift_y] >> shift_x; + } + } + // Copy part of this tile into `tile` while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may have arbitrary shift and alignment. + // The area covered by `tile` on the image is (-shift_x, +shift_y) from the area of this tile. + // + // The suffix "_np" stands for negative (x), positive (y). + // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. + // In this way it the operation does not damage other un-assigned regions on `tile`. + void copy_to_shift_np(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ + uint64x2_t shift_x_u64x2 = vdupq_n_u64(shift_x); + const uint64_t* src = (const uint64_t*)&vec; + uint64_t* dest = (uint64_t*)&tile.vec; + while (shift_y < 7){ + uint64x2_t row_64x2 = vld1q_u64(src + shift_y); + // left shift + row_64x2 = vshlq_u64(row_64x2, shift_x_u64x2); + row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest)); + vst1q_u64(dest, row_64x2); + dest += 2; + shift_y += 2; + } + if (shift_y < 8){ + dest[0] |= src[shift_y] << shift_x; + } + } + // Copy part of this tile into `tile` while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may have arbitrary shift and alignment. + // The area covered by `tile` on the image is (+shift_x, -shift_y) from the area of this tile. + // + // The suffix "_pn" stands for positive (x), negative (y). + // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. + // In this way it the operation does not damage other un-assigned regions on `tile`. + void copy_to_shift_pn(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ + int64x2_t neg_shift_x_u64x2 = vmovq_n_s64(-(int64_t)shift_x); + const uint64_t* src = (const uint64_t*)&vec; + uint64_t* dest = (uint64_t*)&tile.vec; + if (shift_y & 1){ + dest[shift_y] |= src[0] >> shift_x; + src++; + shift_y++; + } + while (shift_y < 8){ + uint64x2_t row_64x2 = vld1q_u64(src); + // NEON only has left shift with a variable. So have to left shift by a negative value + // to create right shift. + row_64x2 = vshlq_u64(row_64x2, neg_shift_x_u64x2); + row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest + shift_y)); + vst1q_u64((dest + shift_y), row_64x2); + src += 2; + shift_y += 2; + } + } + // Copy part of this tile into `tile` while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may have arbitrary shift and alignment. + // The area covered by `tile` on the image is (-shift_x, -shift_y) from the area of this tile. + // + // The suffix "_nn" stands for negative (x), negative (y). + // The shifted values are first performend a logical OR with the values in `tile` before assigned to `tile`. + // In this way it the operation does not damage other un-assigned regions on `tile`. + void copy_to_shift_nn(BinaryTile_64x8_arm64_NEON& tile, size_t shift_x, size_t shift_y) const{ + uint64x2_t shift_x_u64x2 = vdupq_n_u64(shift_x); + const uint64_t* src = (const uint64_t*)&vec; + uint64_t* dest = (uint64_t*)&tile.vec; + if (shift_y & 1){ + dest[shift_y] |= src[0] << shift_x; + src++; + shift_y++; + } + while (shift_y < 8){ + uint64x2_t row_64x2 = vld1q_u64(src); + // left shift + row_64x2 = vshlq_u64(row_64x2, shift_x_u64x2); + row_64x2 = vorrq_u64(row_64x2, vld1q_u64(dest + shift_y)); + vst1q_u64((dest + shift_y), row_64x2); + src += 2; + shift_y += 2; + } + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_x64_SSE42.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_x64_SSE42.h index a6bf6c28ff..dad03babcf 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_x64_SSE42.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_x64_SSE42.h @@ -1,252 +1,252 @@ -/* Binary Matrix Tile (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x8_x64_SSE42_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64x8_x64_SSE42_H - -#include -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct BinaryTile_64x8_x64_SSE42{ - static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x8_x64_SSE42; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = 8; - - __m128i vec[4]; - -public: - PA_FORCE_INLINE BinaryTile_64x8_x64_SSE42(){ - set_zero(); - } - PA_FORCE_INLINE BinaryTile_64x8_x64_SSE42(const BinaryTile_64x8_x64_SSE42& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - } - PA_FORCE_INLINE void operator=(const BinaryTile_64x8_x64_SSE42& x){ - vec[0] = x.vec[0]; - vec[1] = x.vec[1]; - vec[2] = x.vec[2]; - vec[3] = x.vec[3]; - } - - -public: - PA_FORCE_INLINE void set_zero(){ - vec[0] = _mm_setzero_si128(); - vec[1] = _mm_setzero_si128(); - vec[2] = _mm_setzero_si128(); - vec[3] = _mm_setzero_si128(); - } - PA_FORCE_INLINE void set_ones(){ - vec[0] = _mm_set1_epi32(0xffffffff); - vec[1] = _mm_set1_epi32(0xffffffff); - vec[2] = _mm_set1_epi32(0xffffffff); - vec[3] = _mm_set1_epi32(0xffffffff); - } - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - __m128i word = _mm_set1_epi64x( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m128i vheight = _mm_set1_epi64x(height); - __m128i mask; - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(1, 0)); - vec[0] = _mm_and_si128(mask, word); - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(3, 2)); - vec[1] = _mm_and_si128(mask, word); - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(5, 4)); - vec[2] = _mm_and_si128(mask, word); - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(7, 6)); - vec[3] = _mm_and_si128(mask, word); - } - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - __m128i word = _mm_set1_epi64x( - width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff - ); - __m128i vheight = _mm_set1_epi64x(height); - __m128i mask; - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(1, 0)); - vec[0] = _mm_and_si128(vec[0], _mm_and_si128(mask, word)); - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(3, 2)); - vec[1] = _mm_and_si128(vec[1], _mm_and_si128(mask, word)); - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(5, 4)); - vec[2] = _mm_and_si128(vec[2], _mm_and_si128(mask, word)); - mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(7, 6)); - vec[3] = _mm_and_si128(vec[3], _mm_and_si128(mask, word)); - } - PA_FORCE_INLINE void invert(){ - vec[0] = _mm_xor_si128(vec[0], _mm_set1_epi32(0xffffffff)); - vec[1] = _mm_xor_si128(vec[1], _mm_set1_epi32(0xffffffff)); - vec[2] = _mm_xor_si128(vec[2], _mm_set1_epi32(0xffffffff)); - vec[3] = _mm_xor_si128(vec[3], _mm_set1_epi32(0xffffffff)); - } - PA_FORCE_INLINE void operator^=(const BinaryTile_64x8_x64_SSE42& x){ - vec[0] = _mm_xor_si128(vec[0], x.vec[0]); - vec[1] = _mm_xor_si128(vec[1], x.vec[1]); - vec[2] = _mm_xor_si128(vec[2], x.vec[2]); - vec[3] = _mm_xor_si128(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void operator|=(const BinaryTile_64x8_x64_SSE42& x){ - vec[0] = _mm_or_si128(vec[0], x.vec[0]); - vec[1] = _mm_or_si128(vec[1], x.vec[1]); - vec[2] = _mm_or_si128(vec[2], x.vec[2]); - vec[3] = _mm_or_si128(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void operator&=(const BinaryTile_64x8_x64_SSE42& x){ - vec[0] = _mm_and_si128(vec[0], x.vec[0]); - vec[1] = _mm_and_si128(vec[1], x.vec[1]); - vec[2] = _mm_and_si128(vec[2], x.vec[2]); - vec[3] = _mm_and_si128(vec[3], x.vec[3]); - } - PA_FORCE_INLINE void andnot(const BinaryTile_64x8_x64_SSE42& x){ - vec[0] = _mm_andnot_si128(x.vec[0], vec[0]); - vec[1] = _mm_andnot_si128(x.vec[1], vec[1]); - vec[2] = _mm_andnot_si128(x.vec[2], vec[2]); - vec[3] = _mm_andnot_si128(x.vec[3], vec[3]); - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return ((const uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return ((uint64_t*)vec)[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return ((const uint64_t*)vec)[7]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return ((uint64_t*)vec)[7]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return ((const uint64_t*)vec)[index]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return ((uint64_t*)vec)[index]; - } - - // These are slow. - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < 8; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy the current tile into "tile" while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may of arbitrary shift and alignment. - - void copy_to_shift_pp(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ - // (+x, +y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 7){ - __m128i r0 = _mm_loadu_si128((const __m128i*)(src + shift_y)); - r0 = _mm_srl_epi64(r0, shift); - r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)dest)); - _mm_store_si128((__m128i*)dest, r0); - dest += 2; - shift_y += 2; - } - if (shift_y < 8){ - dest[0] |= src[shift_y] >> shift_x; - } - } - void copy_to_shift_np(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ - // (-x, +y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - while (shift_y < 7){ - __m128i r0 = _mm_loadu_si128((const __m128i*)(src + shift_y)); - r0 = _mm_sll_epi64(r0, shift); - r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)dest)); - _mm_store_si128((__m128i*)dest, r0); - dest += 2; - shift_y += 2; - } - if (shift_y < 8){ - dest[0] |= src[shift_y] << shift_x; - } - } - void copy_to_shift_pn(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ - // (+x, -y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - if (shift_y & 1){ - dest[shift_y] |= src[0] >> shift_x; - src++; - shift_y++; - } - while (shift_y < 8){ - __m128i r0 = _mm_loadu_si128((const __m128i*)src); - r0 = _mm_srl_epi64(r0, shift); - r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)(dest + shift_y))); - _mm_store_si128((__m128i*)(dest + shift_y), r0); - src += 2; - shift_y += 2; - } - } - void copy_to_shift_nn(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ - // (-x, -y) - __m128i shift = _mm_set1_epi64x(shift_x); - const uint64_t* src = (const uint64_t*)vec; - uint64_t* dest = (uint64_t*)tile.vec; - if (shift_y & 1){ - dest[shift_y] |= src[0] << shift_x; - src++; - shift_y++; - } - while (shift_y < 8){ - __m128i r0 = _mm_loadu_si128((const __m128i*)src); - r0 = _mm_sll_epi64(r0, shift); - r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)(dest + shift_y))); - _mm_store_si128((__m128i*)(dest + shift_y), r0); - src += 2; - shift_y += 2; - } - } -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64x8_x64_SSE42_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64x8_x64_SSE42_H + +#include +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct BinaryTile_64x8_x64_SSE42{ + static constexpr BinaryMatrixType TYPE = BinaryMatrixType::i64x8_x64_SSE42; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = 8; + + __m128i vec[4]; + +public: + PA_FORCE_INLINE BinaryTile_64x8_x64_SSE42(){ + set_zero(); + } + PA_FORCE_INLINE BinaryTile_64x8_x64_SSE42(const BinaryTile_64x8_x64_SSE42& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + } + PA_FORCE_INLINE void operator=(const BinaryTile_64x8_x64_SSE42& x){ + vec[0] = x.vec[0]; + vec[1] = x.vec[1]; + vec[2] = x.vec[2]; + vec[3] = x.vec[3]; + } + + +public: + PA_FORCE_INLINE void set_zero(){ + vec[0] = _mm_setzero_si128(); + vec[1] = _mm_setzero_si128(); + vec[2] = _mm_setzero_si128(); + vec[3] = _mm_setzero_si128(); + } + PA_FORCE_INLINE void set_ones(){ + vec[0] = _mm_set1_epi32(0xffffffff); + vec[1] = _mm_set1_epi32(0xffffffff); + vec[2] = _mm_set1_epi32(0xffffffff); + vec[3] = _mm_set1_epi32(0xffffffff); + } + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + __m128i word = _mm_set1_epi64x( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m128i vheight = _mm_set1_epi64x(height); + __m128i mask; + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(1, 0)); + vec[0] = _mm_and_si128(mask, word); + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(3, 2)); + vec[1] = _mm_and_si128(mask, word); + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(5, 4)); + vec[2] = _mm_and_si128(mask, word); + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(7, 6)); + vec[3] = _mm_and_si128(mask, word); + } + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + __m128i word = _mm_set1_epi64x( + width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff + ); + __m128i vheight = _mm_set1_epi64x(height); + __m128i mask; + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(1, 0)); + vec[0] = _mm_and_si128(vec[0], _mm_and_si128(mask, word)); + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(3, 2)); + vec[1] = _mm_and_si128(vec[1], _mm_and_si128(mask, word)); + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(5, 4)); + vec[2] = _mm_and_si128(vec[2], _mm_and_si128(mask, word)); + mask = _mm_cmpgt_epi64(vheight, _mm_set_epi64x(7, 6)); + vec[3] = _mm_and_si128(vec[3], _mm_and_si128(mask, word)); + } + PA_FORCE_INLINE void invert(){ + vec[0] = _mm_xor_si128(vec[0], _mm_set1_epi32(0xffffffff)); + vec[1] = _mm_xor_si128(vec[1], _mm_set1_epi32(0xffffffff)); + vec[2] = _mm_xor_si128(vec[2], _mm_set1_epi32(0xffffffff)); + vec[3] = _mm_xor_si128(vec[3], _mm_set1_epi32(0xffffffff)); + } + PA_FORCE_INLINE void operator^=(const BinaryTile_64x8_x64_SSE42& x){ + vec[0] = _mm_xor_si128(vec[0], x.vec[0]); + vec[1] = _mm_xor_si128(vec[1], x.vec[1]); + vec[2] = _mm_xor_si128(vec[2], x.vec[2]); + vec[3] = _mm_xor_si128(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void operator|=(const BinaryTile_64x8_x64_SSE42& x){ + vec[0] = _mm_or_si128(vec[0], x.vec[0]); + vec[1] = _mm_or_si128(vec[1], x.vec[1]); + vec[2] = _mm_or_si128(vec[2], x.vec[2]); + vec[3] = _mm_or_si128(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void operator&=(const BinaryTile_64x8_x64_SSE42& x){ + vec[0] = _mm_and_si128(vec[0], x.vec[0]); + vec[1] = _mm_and_si128(vec[1], x.vec[1]); + vec[2] = _mm_and_si128(vec[2], x.vec[2]); + vec[3] = _mm_and_si128(vec[3], x.vec[3]); + } + PA_FORCE_INLINE void andnot(const BinaryTile_64x8_x64_SSE42& x){ + vec[0] = _mm_andnot_si128(x.vec[0], vec[0]); + vec[1] = _mm_andnot_si128(x.vec[1], vec[1]); + vec[2] = _mm_andnot_si128(x.vec[2], vec[2]); + vec[3] = _mm_andnot_si128(x.vec[3], vec[3]); + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return ((const uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return ((uint64_t*)vec)[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return ((const uint64_t*)vec)[7]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return ((uint64_t*)vec)[7]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return ((const uint64_t*)vec)[index]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return ((uint64_t*)vec)[index]; + } + + // These are slow. + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < 8; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy the current tile into "tile" while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may of arbitrary shift and alignment. + + void copy_to_shift_pp(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ + // (+x, +y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 7){ + __m128i r0 = _mm_loadu_si128((const __m128i*)(src + shift_y)); + r0 = _mm_srl_epi64(r0, shift); + r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)dest)); + _mm_store_si128((__m128i*)dest, r0); + dest += 2; + shift_y += 2; + } + if (shift_y < 8){ + dest[0] |= src[shift_y] >> shift_x; + } + } + void copy_to_shift_np(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ + // (-x, +y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + while (shift_y < 7){ + __m128i r0 = _mm_loadu_si128((const __m128i*)(src + shift_y)); + r0 = _mm_sll_epi64(r0, shift); + r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)dest)); + _mm_store_si128((__m128i*)dest, r0); + dest += 2; + shift_y += 2; + } + if (shift_y < 8){ + dest[0] |= src[shift_y] << shift_x; + } + } + void copy_to_shift_pn(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ + // (+x, -y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + if (shift_y & 1){ + dest[shift_y] |= src[0] >> shift_x; + src++; + shift_y++; + } + while (shift_y < 8){ + __m128i r0 = _mm_loadu_si128((const __m128i*)src); + r0 = _mm_srl_epi64(r0, shift); + r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)(dest + shift_y))); + _mm_store_si128((__m128i*)(dest + shift_y), r0); + src += 2; + shift_y += 2; + } + } + void copy_to_shift_nn(BinaryTile_64x8_x64_SSE42& tile, size_t shift_x, size_t shift_y) const{ + // (-x, -y) + __m128i shift = _mm_set1_epi64x(shift_x); + const uint64_t* src = (const uint64_t*)vec; + uint64_t* dest = (uint64_t*)tile.vec; + if (shift_y & 1){ + dest[shift_y] |= src[0] << shift_x; + src++; + shift_y++; + } + while (shift_y < 8){ + __m128i r0 = _mm_loadu_si128((const __m128i*)src); + r0 = _mm_sll_epi64(r0, shift); + r0 = _mm_or_si128(r0, _mm_load_si128((__m128i*)(dest + shift_y))); + _mm_store_si128((__m128i*)(dest + shift_y), r0); + src += 2; + shift_y += 2; + } + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h index 5068fa7213..10daca1b07 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h @@ -1,177 +1,177 @@ -/* Binary Matrix Tile (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64xH_Default_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_64xH_Default_H - -#include "Common/Compiler.h" -#include "Kernels_BinaryMatrixTile_Debugging.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -struct BinaryTile_64xH_Default{ - static constexpr BinaryMatrixType TYPE = enum_value; - static constexpr size_t WIDTH = 64; - static constexpr size_t HEIGHT = HEIGHT_; - - uint64_t vec[HEIGHT]; - - -public: - PA_FORCE_INLINE BinaryTile_64xH_Default(){ - set_zero(); - } - - -public: - PA_FORCE_INLINE void set_zero(){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] = 0; - } - } - PA_FORCE_INLINE void set_ones(){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] = 0xffffffffffffffff; - } - } - PA_FORCE_INLINE void set_ones(size_t width, size_t height){ - uint64_t word = width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff; - size_t c = 0; - for (; c < height; c++){ - vec[c] = word; - } - for (; c < HEIGHT; c++){ - vec[c] = 0; - } - } - PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ - uint64_t word = width < 64 - ? ((uint64_t)1 << width) - 1 - : 0xffffffffffffffff; - size_t c = 0; - for (; c < height; c++){ - vec[c] &= word; - } - for (; c < HEIGHT; c++){ - vec[c] = 0; - } - } - PA_FORCE_INLINE void invert(){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] = ~vec[c]; - } - } - PA_FORCE_INLINE void operator^=(const BinaryTile_64xH_Default& x){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] ^= x.vec[c]; - } - } - PA_FORCE_INLINE void operator|=(const BinaryTile_64xH_Default& x){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] |= x.vec[c]; - } - } - PA_FORCE_INLINE void operator&=(const BinaryTile_64xH_Default& x){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] &= x.vec[c]; - } - } - PA_FORCE_INLINE void andnot(const BinaryTile_64xH_Default& x){ - for (size_t c = 0; c < HEIGHT; c++){ - vec[c] &= ~x.vec[c]; - } - } - - -public: - PA_FORCE_INLINE uint64_t top() const{ - return vec[0]; - } - PA_FORCE_INLINE uint64_t& top(){ - return vec[0]; - } - PA_FORCE_INLINE uint64_t bottom() const{ - return vec[HEIGHT - 1]; - } - PA_FORCE_INLINE uint64_t& bottom(){ - return vec[HEIGHT - 1]; - } - - PA_FORCE_INLINE uint64_t row(size_t index) const{ - return vec[index]; - } - PA_FORCE_INLINE uint64_t& row(size_t index){ - return vec[index]; - } - - // These are slow. - bool get_bit(size_t x, size_t y) const{ - return (row(y) >> x) & 1; - } - void set_bit(size_t x, size_t y){ - row(y) |= (uint64_t)1 << x; - } - void set_bit(size_t x, size_t y, bool set){ - uint64_t bit = (uint64_t)(set ? 1 : 0) << x; - uint64_t mask = (uint64_t)1 << x; - uint64_t& word = row(y); - word = (word & ~mask) | bit; - } - - std::string dump() const{ - std::string str; - for (size_t c = 0; c < HEIGHT; c++){ - str += dump64(row(c)) + "\n"; - } - return str; - } - - -public: - // Copy the current tile into "tile" while applying the specified shifts. - // These are used to implement submatrix extraction where the desired - // sub-matrix may of arbitrary shift and alignment. - - void copy_to_shift_pp(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ - // (+x, +y) - for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ - tile.vec[c] |= vec[shift_y] >> shift_x; - } - } - void copy_to_shift_np(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ - // (-x, +y) - for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ - tile.vec[c] |= vec[shift_y] << shift_x; - } - } - void copy_to_shift_pn(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ - // (+x, -y) - for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ - tile.vec[shift_y] |= vec[c] >> shift_x; - } - } - void copy_to_shift_nn(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ - // (-x, -y) - for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ - tile.vec[shift_y] |= vec[c] << shift_x; - } - } - -}; - - - - - -} -} -#endif +/* Binary Matrix Tile (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_64xH_Default_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_64xH_Default_H + +#include "Common/Compiler.h" +#include "Kernels_BinaryMatrixTile_Debugging.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +struct BinaryTile_64xH_Default{ + static constexpr BinaryMatrixType TYPE = enum_value; + static constexpr size_t WIDTH = 64; + static constexpr size_t HEIGHT = HEIGHT_; + + uint64_t vec[HEIGHT]; + + +public: + PA_FORCE_INLINE BinaryTile_64xH_Default(){ + set_zero(); + } + + +public: + PA_FORCE_INLINE void set_zero(){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] = 0; + } + } + PA_FORCE_INLINE void set_ones(){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] = 0xffffffffffffffff; + } + } + PA_FORCE_INLINE void set_ones(size_t width, size_t height){ + uint64_t word = width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff; + size_t c = 0; + for (; c < height; c++){ + vec[c] = word; + } + for (; c < HEIGHT; c++){ + vec[c] = 0; + } + } + PA_FORCE_INLINE void clear_padding(size_t width, size_t height){ + uint64_t word = width < 64 + ? ((uint64_t)1 << width) - 1 + : 0xffffffffffffffff; + size_t c = 0; + for (; c < height; c++){ + vec[c] &= word; + } + for (; c < HEIGHT; c++){ + vec[c] = 0; + } + } + PA_FORCE_INLINE void invert(){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] = ~vec[c]; + } + } + PA_FORCE_INLINE void operator^=(const BinaryTile_64xH_Default& x){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] ^= x.vec[c]; + } + } + PA_FORCE_INLINE void operator|=(const BinaryTile_64xH_Default& x){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] |= x.vec[c]; + } + } + PA_FORCE_INLINE void operator&=(const BinaryTile_64xH_Default& x){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] &= x.vec[c]; + } + } + PA_FORCE_INLINE void andnot(const BinaryTile_64xH_Default& x){ + for (size_t c = 0; c < HEIGHT; c++){ + vec[c] &= ~x.vec[c]; + } + } + + +public: + PA_FORCE_INLINE uint64_t top() const{ + return vec[0]; + } + PA_FORCE_INLINE uint64_t& top(){ + return vec[0]; + } + PA_FORCE_INLINE uint64_t bottom() const{ + return vec[HEIGHT - 1]; + } + PA_FORCE_INLINE uint64_t& bottom(){ + return vec[HEIGHT - 1]; + } + + PA_FORCE_INLINE uint64_t row(size_t index) const{ + return vec[index]; + } + PA_FORCE_INLINE uint64_t& row(size_t index){ + return vec[index]; + } + + // These are slow. + bool get_bit(size_t x, size_t y) const{ + return (row(y) >> x) & 1; + } + void set_bit(size_t x, size_t y){ + row(y) |= (uint64_t)1 << x; + } + void set_bit(size_t x, size_t y, bool set){ + uint64_t bit = (uint64_t)(set ? 1 : 0) << x; + uint64_t mask = (uint64_t)1 << x; + uint64_t& word = row(y); + word = (word & ~mask) | bit; + } + + std::string dump() const{ + std::string str; + for (size_t c = 0; c < HEIGHT; c++){ + str += dump64(row(c)) + "\n"; + } + return str; + } + + +public: + // Copy the current tile into "tile" while applying the specified shifts. + // These are used to implement submatrix extraction where the desired + // sub-matrix may of arbitrary shift and alignment. + + void copy_to_shift_pp(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ + // (+x, +y) + for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ + tile.vec[c] |= vec[shift_y] >> shift_x; + } + } + void copy_to_shift_np(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ + // (-x, +y) + for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ + tile.vec[c] |= vec[shift_y] << shift_x; + } + } + void copy_to_shift_pn(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ + // (+x, -y) + for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ + tile.vec[shift_y] |= vec[c] >> shift_x; + } + } + void copy_to_shift_nn(BinaryTile_64xH_Default& tile, size_t shift_x, size_t shift_y) const{ + // (-x, -y) + for (size_t c = 0; shift_y < HEIGHT; shift_y++, c++){ + tile.vec[shift_y] |= vec[c] << shift_x; + } + } + +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_Debugging.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_Debugging.h index 9379baaf7a..680d37a533 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_Debugging.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_Debugging.h @@ -1,37 +1,37 @@ -/* Binary Matrix Tile Debugging - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_Debugging_H -#define PokemonAutomation_Kernels_BinaryMatrixTile_Debugging_H - -#include -#include - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -inline std::string dump64(uint64_t x){ - std::string str(64, 0); - for (size_t c = 0; c < 64; c++){ - str[c] = ((x >> c) & 1) ? '1' : '0'; - } - return str; -} - -inline void print64(uint64_t x){ - cout << dump64(x) << endl; -} - - - -} -} -#endif +/* Binary Matrix Tile Debugging + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrixTile_Debugging_H +#define PokemonAutomation_Kernels_BinaryMatrixTile_Debugging_H + +#include +#include + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +inline std::string dump64(uint64_t x){ + std::string str(64, 0); + for (size_t c = 0; c < 64; c++){ + str[c] = ((x >> c) & 1) ? '1' : '0'; + } + return str; +} + +inline void print64(uint64_t x){ + cout << dump64(x) << endl; +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h index abba220394..8344534b69 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h @@ -1,29 +1,29 @@ -/* Binary Matrix (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x16_x64_AVX2_H -#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x16_x64_AVX2_H - -#include "Kernels_BinaryMatrixTile_64x16_x64_AVX2.h" -#include "Kernels_BinaryMatrix_t.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -using PackedBinaryMatrixCore_64x16_x64_AVX2 = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x16_x64_AVX2 = SparseBinaryMatrixCore; - -using PackedBinaryMatrix_64x16_x64_AVX2 = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x16_x64_AVX2 = SparseBinaryMatrix_t; - - - -} -} -#endif +/* Binary Matrix (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x16_x64_AVX2_H +#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x16_x64_AVX2_H + +#include "Kernels_BinaryMatrixTile_64x16_x64_AVX2.h" +#include "Kernels_BinaryMatrix_t.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +using PackedBinaryMatrixCore_64x16_x64_AVX2 = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x16_x64_AVX2 = SparseBinaryMatrixCore; + +using PackedBinaryMatrix_64x16_x64_AVX2 = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x16_x64_AVX2 = SparseBinaryMatrix_t; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h index 30c3a75a1b..44b7d128d9 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h @@ -1,30 +1,30 @@ -/* Binary Matrix (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x32_x64_AVX512_H -#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x32_x64_AVX512_H - -#include "Kernels_BinaryMatrixTile_64x32_x64_AVX512.h" -#include "Kernels_BinaryMatrix_t.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -using PackedBinaryMatrixCore_64x32_x64_AVX512 = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x32_x64_AVX512 = SparseBinaryMatrixCore; - -using PackedBinaryMatrix_64x32_x64_AVX512 = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x32_x64_AVX512 = SparseBinaryMatrix_t; - - - - -} -} -#endif +/* Binary Matrix (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x32_x64_AVX512_H +#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x32_x64_AVX512_H + +#include "Kernels_BinaryMatrixTile_64x32_x64_AVX512.h" +#include "Kernels_BinaryMatrix_t.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +using PackedBinaryMatrixCore_64x32_x64_AVX512 = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x32_x64_AVX512 = SparseBinaryMatrixCore; + +using PackedBinaryMatrix_64x32_x64_AVX512 = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x32_x64_AVX512 = SparseBinaryMatrix_t; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h index 510c2c35ca..742d068dd8 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h @@ -1,30 +1,30 @@ -/* Binary Matrix (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x64_x64_AVX512_H -#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x64_x64_AVX512_H - -#include "Kernels_BinaryMatrixTile_64x64_x64_AVX512.h" -#include "Kernels_BinaryMatrix_t.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -using PackedBinaryMatrixCore_64x64_x64_AVX512 = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x64_x64_AVX512 = SparseBinaryMatrixCore; - -using PackedBinaryMatrix_64x64_x64_AVX512 = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x64_x64_AVX512 = SparseBinaryMatrix_t; - - - - -} -} -#endif +/* Binary Matrix (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x64_x64_AVX512_H +#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x64_x64_AVX512_H + +#include "Kernels_BinaryMatrixTile_64x64_x64_AVX512.h" +#include "Kernels_BinaryMatrix_t.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +using PackedBinaryMatrixCore_64x64_x64_AVX512 = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x64_x64_AVX512 = SparseBinaryMatrixCore; + +using PackedBinaryMatrix_64x64_x64_AVX512 = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x64_x64_AVX512 = SparseBinaryMatrix_t; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h index d20344971e..1627f4c233 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h @@ -1,29 +1,29 @@ -/* Binary Matrix (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_arm64_NEON_H -#define PokemonAutomation_Kernels_BinaryMatrix_Arch_arm64_NEON_H - -#include "Kernels_BinaryMatrixTile_64x8_arm64_NEON.h" -#include "Kernels_BinaryMatrix_t.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -using PackedBinaryMatrixCore_64x8_arm64_NEON = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x8_arm64_NEON = SparseBinaryMatrixCore; - -using PackedBinaryMatrix_64x8_arm64_NEON = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x8_arm64_NEON = SparseBinaryMatrix_t; - - - -} -} -#endif +/* Binary Matrix (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_arm64_NEON_H +#define PokemonAutomation_Kernels_BinaryMatrix_Arch_arm64_NEON_H + +#include "Kernels_BinaryMatrixTile_64x8_arm64_NEON.h" +#include "Kernels_BinaryMatrix_t.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +using PackedBinaryMatrixCore_64x8_arm64_NEON = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x8_arm64_NEON = SparseBinaryMatrixCore; + +using PackedBinaryMatrix_64x8_arm64_NEON = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x8_arm64_NEON = SparseBinaryMatrix_t; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h index 1131d14e69..036ccd5e6b 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h @@ -1,29 +1,29 @@ -/* Binary Matrix (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_x64_SSE42_H -#define PokemonAutomation_Kernels_BinaryMatrix_Arch_x64_SSE42_H - -#include "Kernels_BinaryMatrixTile_64x8_x64_SSE42.h" -#include "Kernels_BinaryMatrix_t.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -using PackedBinaryMatrixCore_64x8_x64_SSE42 = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x8_x64_SSE42 = SparseBinaryMatrixCore; - -using PackedBinaryMatrix_64x8_x64_SSE42 = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x8_x64_SSE42 = SparseBinaryMatrix_t; - - - -} -} -#endif +/* Binary Matrix (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_x64_SSE42_H +#define PokemonAutomation_Kernels_BinaryMatrix_Arch_x64_SSE42_H + +#include "Kernels_BinaryMatrixTile_64x8_x64_SSE42.h" +#include "Kernels_BinaryMatrix_t.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +using PackedBinaryMatrixCore_64x8_x64_SSE42 = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x8_x64_SSE42 = SparseBinaryMatrixCore; + +using PackedBinaryMatrix_64x8_x64_SSE42 = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x8_x64_SSE42 = SparseBinaryMatrix_t; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h index 2bc2a9df7f..f6c78e8418 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h @@ -1,35 +1,35 @@ -/* Binary Matrix (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x4_Default_H -#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x4_Default_H - -#include "Kernels_BinaryMatrixTile_64x4_Default.h" -#include "Kernels_BinaryMatrixTile_64xH_Default.h" -#include "Kernels_BinaryMatrix_t.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -using PackedBinaryMatrixCore_64x4_Default = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x4_Default = SparseBinaryMatrixCore; -using PackedBinaryMatrix_64x4_Default = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x4_Default = SparseBinaryMatrix_t; - -using BinaryTile_64x8_Default = BinaryTile_64xH_Default<8, BinaryMatrixType::i64x8_Default>; -using PackedBinaryMatrixCore_64x8_Default = PackedBinaryMatrixCore; -using SparseBinaryMatrixCore_64x8_Default = SparseBinaryMatrixCore; -using PackedBinaryMatrix_64x8_Default = PackedBinaryMatrix_t; -using SparseBinaryMatrix_64x8_Default = SparseBinaryMatrix_t; - - - -} -} -#endif +/* Binary Matrix (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_Arch_64x4_Default_H +#define PokemonAutomation_Kernels_BinaryMatrix_Arch_64x4_Default_H + +#include "Kernels_BinaryMatrixTile_64x4_Default.h" +#include "Kernels_BinaryMatrixTile_64xH_Default.h" +#include "Kernels_BinaryMatrix_t.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +using PackedBinaryMatrixCore_64x4_Default = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x4_Default = SparseBinaryMatrixCore; +using PackedBinaryMatrix_64x4_Default = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x4_Default = SparseBinaryMatrix_t; + +using BinaryTile_64x8_Default = BinaryTile_64xH_Default<8, BinaryMatrixType::i64x8_Default>; +using PackedBinaryMatrixCore_64x8_Default = PackedBinaryMatrixCore; +using SparseBinaryMatrixCore_64x8_Default = SparseBinaryMatrixCore; +using PackedBinaryMatrix_64x8_Default = PackedBinaryMatrix_t; +using SparseBinaryMatrix_64x8_Default = SparseBinaryMatrix_t; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp index 20c9518905..b4917ad594 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x16_x64_AVX2.cpp @@ -1,41 +1,41 @@ -/* Binary Matrix (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height){ - return std::make_unique(width, height); -} - - - -} -} -#endif +/* Binary Matrix (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x16_x64_AVX2(size_t width, size_t height){ + return std::make_unique(width, height); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp index 7120b8128f..85ee212322 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x32_x64_AVX512.cpp @@ -1,39 +1,39 @@ -/* Binary Matrix (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height){ - return std::make_unique(width, height); -} - - -} -} -#endif +/* Binary Matrix (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x32_x64_AVX512(size_t width, size_t height){ + return std::make_unique(width, height); +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp index e3b350a48b..4c6469e745 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x64_x64_AVX512.cpp @@ -1,40 +1,40 @@ -/* Binary Matrix (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height){ - return std::make_unique(width, height); -} - - -} -} -#endif +/* Binary Matrix (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x64_x64_AVX512(size_t width, size_t height){ + return std::make_unique(width, height); +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp index 6361daacc1..592e839c77 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64x8_x64_SSE42.cpp @@ -1,41 +1,41 @@ -/* Binary Matrix (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height){ - return std::make_unique(width, height); -} - - - -} -} -#endif +/* Binary Matrix (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x8_x64_SSE42(size_t width, size_t height){ + return std::make_unique(width, height); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64xH_Default.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64xH_Default.cpp index 89f4ea1b8a..7b5386d910 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64xH_Default.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_64xH_Default.cpp @@ -1,52 +1,52 @@ -/* Binary Matrix (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_64xH_Default.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; -std::unique_ptr make_PackedBinaryMatrix_64x4_Default(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x4_Default(size_t width, size_t height){ - return std::make_unique(width, height); -} -std::unique_ptr make_SparseBinaryMatrix_64x4_Default(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x4_Default(size_t width, size_t height){ - return std::make_unique(width, height); -} - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; -std::unique_ptr make_PackedBinaryMatrix_64x8_Default(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x8_Default(size_t width, size_t height){ - return std::make_unique(width, height); -} -std::unique_ptr make_SparseBinaryMatrix_64x8_Default(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x8_Default(size_t width, size_t height){ - return std::make_unique(width, height); -} - - -} -} +/* Binary Matrix (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_64xH_Default.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; +std::unique_ptr make_PackedBinaryMatrix_64x4_Default(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x4_Default(size_t width, size_t height){ + return std::make_unique(width, height); +} +std::unique_ptr make_SparseBinaryMatrix_64x4_Default(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x4_Default(size_t width, size_t height){ + return std::make_unique(width, height); +} + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; +std::unique_ptr make_PackedBinaryMatrix_64x8_Default(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x8_Default(size_t width, size_t height){ + return std::make_unique(width, height); +} +std::unique_ptr make_SparseBinaryMatrix_64x8_Default(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x8_Default(size_t width, size_t height){ + return std::make_unique(width, height); +} + + +} +} diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_arm64_NEON.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_arm64_NEON.cpp index e544f406cc..e8a8b90029 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_arm64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_arm64_NEON.cpp @@ -1,41 +1,41 @@ -/* Binary Matrix (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height){ - return std::make_unique(width, height); -} - - - -} -} -#endif +/* Binary Matrix (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_64x8_arm64_NEON(size_t width, size_t height){ + return std::make_unique(width, height); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX2.cpp index 3d7e724b5f..6a4b12544d 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX2.cpp @@ -1,41 +1,41 @@ -/* Binary Matrix (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_13_Haswell - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_x64_AVX2(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_x64_AVX2(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_x64_AVX2(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_x64_AVX2(size_t width, size_t height){ - return std::make_unique(width, height); -} - - - -} -} -#endif +/* Binary Matrix (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_13_Haswell + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_x64_AVX2(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_x64_AVX2(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_x64_AVX2(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_x64_AVX2(size_t width, size_t height){ + return std::make_unique(width, height); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX512.cpp index 8f4ac0c384..e4e6cbcbeb 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_AVX512.cpp @@ -1,40 +1,40 @@ -/* Binary Matrix (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_17_Skylake - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_x64_AVX512(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_x64_AVX512(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_x64_AVX512(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_x64_AVX512(size_t width, size_t height){ - return std::make_unique(width, height); -} - - -} -} -#endif +/* Binary Matrix (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_17_Skylake + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_x64_AVX512(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_x64_AVX512(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_x64_AVX512(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_x64_AVX512(size_t width, size_t height){ + return std::make_unique(width, height); +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_SSE42.cpp index b77e53ae1b..1714be2e3e 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_Core_x64_SSE42.cpp @@ -1,41 +1,41 @@ -/* Binary Matrix (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_08_Nehalem - -#include "Kernels_PackedBinaryMatrixCore.tpp" -#include "Kernels_SparseBinaryMatrixCore.tpp" -#include "Kernels_BinaryMatrix_Arch_x64_SSE42.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template class PackedBinaryMatrixCore; -template class SparseBinaryMatrixCore; -template class PackedBinaryMatrix_t; -template class SparseBinaryMatrix_t; - - -std::unique_ptr make_PackedBinaryMatrix_x64_SSE42(){ - return std::make_unique(); -} -std::unique_ptr make_PackedBinaryMatrix_x64_SSE42(size_t width, size_t height){ - return std::make_unique(width, height); -} - -std::unique_ptr make_SparseBinaryMatrix_x64_SSE42(){ - return std::make_unique(); -} -std::unique_ptr make_SparseBinaryMatrix_x64_SSE42(size_t width, size_t height){ - return std::make_unique(width, height); -} - - - -} -} -#endif +/* Binary Matrix (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_08_Nehalem + +#include "Kernels_PackedBinaryMatrixCore.tpp" +#include "Kernels_SparseBinaryMatrixCore.tpp" +#include "Kernels_BinaryMatrix_Arch_x64_SSE42.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template class PackedBinaryMatrixCore; +template class SparseBinaryMatrixCore; +template class PackedBinaryMatrix_t; +template class SparseBinaryMatrix_t; + + +std::unique_ptr make_PackedBinaryMatrix_x64_SSE42(){ + return std::make_unique(); +} +std::unique_ptr make_PackedBinaryMatrix_x64_SSE42(size_t width, size_t height){ + return std::make_unique(width, height); +} + +std::unique_ptr make_SparseBinaryMatrix_x64_SSE42(){ + return std::make_unique(); +} +std::unique_ptr make_SparseBinaryMatrix_x64_SSE42(size_t width, size_t height){ + return std::make_unique(width, height); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h index 1ad0aee238..f1b58571f7 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h @@ -1,167 +1,167 @@ -/* Binary Matrix (internal template) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BinaryMatrix_t_H -#define PokemonAutomation_Kernels_BinaryMatrix_t_H - -#include "Common/Cpp/Exceptions.h" -#include "Kernels_PackedBinaryMatrixCore.h" -#include "Kernels_SparseBinaryMatrixCore.h" -#include "Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -// Templated packed binary matrix for efficient memory usage. -// See base class `PackedBinaryMatrix_IB` for the goal of such matrices. -// Different types of the packed binary matrices is by using different -// template parameter `Tile`. -// The shape of the tile is associated with what CPU feature to use. -// For example, for AVX2 feature, the optimized shape is 64x16. -// See Kernels_BinaryMatrix.h:BinaryMatrixType as enums of different matrix types. -// -// `PackedBinaryMatrix_t` serves as the template class for each different implmenentations -// for each CPU feature set. It uses template class PackedBinaryMatrixCore to -// implement all the actual matrix functions. -// Suffix "_t" stands for "template". -template -class PackedBinaryMatrix_t final : public PackedBinaryMatrix_IB{ -public: - PackedBinaryMatrix_t() = default; - PackedBinaryMatrix_t(size_t width, size_t height) - : m_matrix(width, height) - {} - - const PackedBinaryMatrixCore& get() const{ return m_matrix; } - PackedBinaryMatrixCore& get() { return m_matrix; } - - virtual BinaryMatrixType type() const override{ return Tile::TYPE; } - virtual std::unique_ptr clone() const override{ - auto ret = std::make_unique(); - ret->m_matrix = m_matrix; - return ret; - } - - virtual void clear() override{ m_matrix.clear(); } - - virtual void set_zero() override{ m_matrix.set_zero(); } - virtual void set_ones() override{ m_matrix.set_ones(); } - virtual void invert() override{ m_matrix.invert(); } - - virtual void operator^=(const PackedBinaryMatrix_IB& x) override{ - if (this->type() != x.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); - } - m_matrix ^= static_cast&>(x).m_matrix; - } - virtual void operator|=(const PackedBinaryMatrix_IB& x) override{ - if (this->type() != x.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); - } - m_matrix |= static_cast&>(x).m_matrix; - } - virtual void operator&=(const PackedBinaryMatrix_IB& x) override{ - if (this->type() != x.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); - } - m_matrix &= static_cast&>(x).m_matrix; - } - - // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". - virtual std::string dump() const override{ return m_matrix.dump(); } - // Print part of max as 0s and 1s. Rows are ended with "\n". - virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const override{ return m_matrix.dump(min_x, min_y, max_x, max_y); } - // Print all the underlying tiles that form this binary matrix. The result is a matrix that may be larger - // than the original matrix. - virtual std::string dump_tiles() const override{ return m_matrix.dump_tiles(); } - -public: - virtual size_t width() const override{ return m_matrix.width(); } - virtual size_t height() const override{ return m_matrix.height(); } - - // These are slow. - virtual bool get(size_t x, size_t y) const override{ return m_matrix.get(x, y); } - virtual void set(size_t x, size_t y, bool set) override{ m_matrix.set(x, y, set); } - - virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const override{ - auto ret = std::make_unique(); - ret->m_matrix = m_matrix.submatrix(x, y, width, height); - return ret; - } - -private: - PackedBinaryMatrixCore m_matrix; -}; - - -template -class SparseBinaryMatrix_t final : public SparseBinaryMatrix_IB{ -public: - SparseBinaryMatrix_t() = default; - SparseBinaryMatrix_t(size_t width, size_t height) - : m_matrix(width, height) - {} - - const SparseBinaryMatrixCore& get() const{ return m_matrix; } - SparseBinaryMatrixCore& get() { return m_matrix; } - - virtual BinaryMatrixType type() const override{ return Tile::TYPE; } - virtual std::unique_ptr clone() const override{ - auto ret = std::make_unique(); - ret->m_matrix = m_matrix; - return ret; - } - - virtual void clear() override{ m_matrix.clear(); } - - virtual void operator^=(const SparseBinaryMatrix_IB& x) override{ - if (this->type() != x.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); - } - m_matrix ^= static_cast(x).m_matrix; - } - virtual void operator|=(const SparseBinaryMatrix_IB& x) override{ - if (this->type() != x.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); - } - m_matrix |= static_cast(x).m_matrix; - } - virtual void operator&=(const SparseBinaryMatrix_IB& x) override{ - if (this->type() != x.type()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); - } - m_matrix &= static_cast(x).m_matrix; - } - - virtual std::string dump() const override{ return m_matrix.dump(); } - virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const override{ return m_matrix.dump(min_x, min_y, max_x, max_y); } - -public: - virtual size_t width() const override{ return m_matrix.width(); } - virtual size_t height() const override{ return m_matrix.height(); } - - // These are slow. - virtual bool get(size_t x, size_t y) const override{ return m_matrix.get(x, y); } - virtual void set(size_t x, size_t y, bool set) override{ m_matrix.set(x, y, set); } - - virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const override{ - auto ret = std::make_unique>(); - ret->get() = m_matrix.submatrix(x, y, width, height); - return ret; - } - -private: - SparseBinaryMatrixCore m_matrix; -}; - - - - - -} -} -#endif +/* Binary Matrix (internal template) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BinaryMatrix_t_H +#define PokemonAutomation_Kernels_BinaryMatrix_t_H + +#include "Common/Cpp/Exceptions.h" +#include "Kernels_PackedBinaryMatrixCore.h" +#include "Kernels_SparseBinaryMatrixCore.h" +#include "Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +// Templated packed binary matrix for efficient memory usage. +// See base class `PackedBinaryMatrix_IB` for the goal of such matrices. +// Different types of the packed binary matrices is by using different +// template parameter `Tile`. +// The shape of the tile is associated with what CPU feature to use. +// For example, for AVX2 feature, the optimized shape is 64x16. +// See Kernels_BinaryMatrix.h:BinaryMatrixType as enums of different matrix types. +// +// `PackedBinaryMatrix_t` serves as the template class for each different implmenentations +// for each CPU feature set. It uses template class PackedBinaryMatrixCore to +// implement all the actual matrix functions. +// Suffix "_t" stands for "template". +template +class PackedBinaryMatrix_t final : public PackedBinaryMatrix_IB{ +public: + PackedBinaryMatrix_t() = default; + PackedBinaryMatrix_t(size_t width, size_t height) + : m_matrix(width, height) + {} + + const PackedBinaryMatrixCore& get() const{ return m_matrix; } + PackedBinaryMatrixCore& get() { return m_matrix; } + + virtual BinaryMatrixType type() const override{ return Tile::TYPE; } + virtual std::unique_ptr clone() const override{ + auto ret = std::make_unique(); + ret->m_matrix = m_matrix; + return ret; + } + + virtual void clear() override{ m_matrix.clear(); } + + virtual void set_zero() override{ m_matrix.set_zero(); } + virtual void set_ones() override{ m_matrix.set_ones(); } + virtual void invert() override{ m_matrix.invert(); } + + virtual void operator^=(const PackedBinaryMatrix_IB& x) override{ + if (this->type() != x.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); + } + m_matrix ^= static_cast&>(x).m_matrix; + } + virtual void operator|=(const PackedBinaryMatrix_IB& x) override{ + if (this->type() != x.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); + } + m_matrix |= static_cast&>(x).m_matrix; + } + virtual void operator&=(const PackedBinaryMatrix_IB& x) override{ + if (this->type() != x.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); + } + m_matrix &= static_cast&>(x).m_matrix; + } + + // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". + virtual std::string dump() const override{ return m_matrix.dump(); } + // Print part of max as 0s and 1s. Rows are ended with "\n". + virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const override{ return m_matrix.dump(min_x, min_y, max_x, max_y); } + // Print all the underlying tiles that form this binary matrix. The result is a matrix that may be larger + // than the original matrix. + virtual std::string dump_tiles() const override{ return m_matrix.dump_tiles(); } + +public: + virtual size_t width() const override{ return m_matrix.width(); } + virtual size_t height() const override{ return m_matrix.height(); } + + // These are slow. + virtual bool get(size_t x, size_t y) const override{ return m_matrix.get(x, y); } + virtual void set(size_t x, size_t y, bool set) override{ m_matrix.set(x, y, set); } + + virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const override{ + auto ret = std::make_unique(); + ret->m_matrix = m_matrix.submatrix(x, y, width, height); + return ret; + } + +private: + PackedBinaryMatrixCore m_matrix; +}; + + +template +class SparseBinaryMatrix_t final : public SparseBinaryMatrix_IB{ +public: + SparseBinaryMatrix_t() = default; + SparseBinaryMatrix_t(size_t width, size_t height) + : m_matrix(width, height) + {} + + const SparseBinaryMatrixCore& get() const{ return m_matrix; } + SparseBinaryMatrixCore& get() { return m_matrix; } + + virtual BinaryMatrixType type() const override{ return Tile::TYPE; } + virtual std::unique_ptr clone() const override{ + auto ret = std::make_unique(); + ret->m_matrix = m_matrix; + return ret; + } + + virtual void clear() override{ m_matrix.clear(); } + + virtual void operator^=(const SparseBinaryMatrix_IB& x) override{ + if (this->type() != x.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); + } + m_matrix ^= static_cast(x).m_matrix; + } + virtual void operator|=(const SparseBinaryMatrix_IB& x) override{ + if (this->type() != x.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); + } + m_matrix |= static_cast(x).m_matrix; + } + virtual void operator&=(const SparseBinaryMatrix_IB& x) override{ + if (this->type() != x.type()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix types."); + } + m_matrix &= static_cast(x).m_matrix; + } + + virtual std::string dump() const override{ return m_matrix.dump(); } + virtual std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const override{ return m_matrix.dump(min_x, min_y, max_x, max_y); } + +public: + virtual size_t width() const override{ return m_matrix.width(); } + virtual size_t height() const override{ return m_matrix.height(); } + + // These are slow. + virtual bool get(size_t x, size_t y) const override{ return m_matrix.get(x, y); } + virtual void set(size_t x, size_t y, bool set) override{ m_matrix.set(x, y, set); } + + virtual std::unique_ptr submatrix(size_t x, size_t y, size_t width, size_t height) const override{ + auto ret = std::make_unique>(); + ret->get() = m_matrix.submatrix(x, y, width, height); + return ret; + } + +private: + SparseBinaryMatrixCore m_matrix; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h index e5997c31ab..fab76dbc81 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h @@ -1,200 +1,200 @@ -/* Packed Binary Matrix Base - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_PackedBinaryMatrixCore_H -#define PokemonAutomation_Kernels_PackedBinaryMatrixCore_H - -#include -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Containers/AlignedVector.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -// The 2D index of a tile inside binary matrix `PackedBinaryMatrixCore` -class TileIndex{ -public: - TileIndex(size_t x, size_t y) - : m_index((uint32_t)x | ((uint64_t)y << 32)) - { - if ((x | y) & 0xffffffff00000000){ - std::cerr << "Pixel Overflow: (" << x << "," << y << ")" << std::endl; - } - } - - PA_FORCE_INLINE size_t x() const{ return (uint32_t)m_index; } - PA_FORCE_INLINE size_t y() const{ return (uint32_t)(m_index >> 32); } - - PA_FORCE_INLINE friend bool operator<(const TileIndex& a, const TileIndex& b){ - return a.m_index < b.m_index; - } - -private: - uint64_t m_index; -}; - - - - -template -class PackedBinaryMatrixCore{ -public: - using Tile = TileType; - -public: - // Rule of 5 - ~PackedBinaryMatrixCore(); - PackedBinaryMatrixCore(PackedBinaryMatrixCore&& x); - void operator=(PackedBinaryMatrixCore&& x); - PackedBinaryMatrixCore(const PackedBinaryMatrixCore& x); - void operator=(const PackedBinaryMatrixCore& x); - -public: - // Construction - PackedBinaryMatrixCore(); - PackedBinaryMatrixCore(size_t width, size_t height); - - void clear(); - - void set_zero(); // Zero the entire matrix. - void set_ones(); // Set entire matrix to ones. - void invert(); // Invert all bits. - - // Matrix must have same dimensions. - void operator^=(const PackedBinaryMatrixCore& x); - void operator|=(const PackedBinaryMatrixCore& x); - void operator&=(const PackedBinaryMatrixCore& x); - -public: - // How many pixels in an image row, which is equal to how many bits in a binary matrix row - size_t width() const{ return m_logical_width; } - // How many pixels in an image column, which is equal to how many bits in a binary matrix column - size_t height() const{ return m_logical_height; } - - // These are slow. - bool get(size_t x, size_t y) const; - void set(size_t x, size_t y, bool set); - - PackedBinaryMatrixCore submatrix(size_t x, size_t y, size_t width, size_t height) const; - - // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". - std::string dump() const; - // Print part of max as 0s and 1s. Rows are ended with "\n". - std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const; - // Print all the underlying tiles that form this binary matrix. The result is a matrix that may be larger - // than the original matrix. - std::string dump_tiles() const; - -public: - // How many tiles in a row. - size_t tile_width() const{ return m_tile_width; } - // How many tiles in a column - size_t tile_height() const{ return m_tile_height; } - - // Get (index.x()-th, index.y()-th) tile - const TileType& tile(TileIndex index) const; - TileType& tile(TileIndex index); - // Get (x-th, y-th) tile - const TileType& tile(size_t x, size_t y) const; - TileType& tile(size_t x, size_t y); - -public: - // Word Access. How many words in a row. One word is 8 bytes (aka 64 bits). - // For different simd implementations, every tile is always one word wide. - size_t word64_width() const{ return m_tile_width; } - // Word Access. How many words in a column. One word is 8 bytes (aka 64 bits). - size_t word64_height() const{ return m_logical_height; } - - // Get (x-th, y-th) word. One word is 8 bytes (aka 64 bits), one row in a tile. - uint64_t word64(size_t x, size_t y) const; - // Get (x-th, y-th) word. One word is 8 bytes (aka 64 bits), one row in a tile. - uint64_t& word64(size_t x, size_t y); - -private: - static constexpr size_t TILE_WIDTH = TileType::WIDTH; - static constexpr size_t TILE_HEIGHT = TileType::HEIGHT; - - // How many bits in a row (aka how many pixels in an image row) - size_t m_logical_width; - // How many bits in a column (aka how many pixels in an image column) - size_t m_logical_height; - // How many tiles in a row - size_t m_tile_width; - // How many tiles in a column - size_t m_tile_height; - AlignedVector m_data; -}; - - - - - -// Implementations - - - -// Tile Access - -template PA_FORCE_INLINE -const Tile& PackedBinaryMatrixCore::tile(TileIndex index) const{ - return m_data[index.x() + index.y() * m_tile_width]; -} -template PA_FORCE_INLINE -Tile& PackedBinaryMatrixCore::tile(TileIndex index){ - return m_data[index.x() + index.y() * m_tile_width]; -} -template PA_FORCE_INLINE -const Tile& PackedBinaryMatrixCore::tile(size_t x, size_t y) const{ - return m_data[x + y * m_tile_width]; -} -template PA_FORCE_INLINE -Tile& PackedBinaryMatrixCore::tile(size_t x, size_t y){ - return m_data[x + y * m_tile_width]; -} - - - -// Word Access - -template PA_FORCE_INLINE -uint64_t PackedBinaryMatrixCore::word64(size_t x, size_t y) const{ - static_assert(TILE_WIDTH == 64); - const Tile& tile = this->tile(x, y / TILE_HEIGHT); - return tile.row(y % TILE_HEIGHT); -} -template PA_FORCE_INLINE -uint64_t& PackedBinaryMatrixCore::word64(size_t x, size_t y){ - static_assert(TILE_WIDTH == 64); - Tile& tile = this->tile(x, y / TILE_HEIGHT); - return tile.row(y % TILE_HEIGHT); -} - - - -// Bit Access - -// Get the bit at bit location (x, y) -template -bool PackedBinaryMatrixCore::get(size_t x, size_t y) const{ - const Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); - return tile.get_bit(x % TILE_WIDTH, y % TILE_HEIGHT); -} - -// Set the bit at bit location (x, y) to `set` -template -void PackedBinaryMatrixCore::set(size_t x, size_t y, bool set){ - Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); - tile.set_bit(x % TILE_WIDTH, y % TILE_HEIGHT, set); -} - - - -} -} -#endif +/* Packed Binary Matrix Base + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_PackedBinaryMatrixCore_H +#define PokemonAutomation_Kernels_PackedBinaryMatrixCore_H + +#include +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Containers/AlignedVector.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +// The 2D index of a tile inside binary matrix `PackedBinaryMatrixCore` +class TileIndex{ +public: + TileIndex(size_t x, size_t y) + : m_index((uint32_t)x | ((uint64_t)y << 32)) + { + if ((x | y) & 0xffffffff00000000){ + std::cerr << "Pixel Overflow: (" << x << "," << y << ")" << std::endl; + } + } + + PA_FORCE_INLINE size_t x() const{ return (uint32_t)m_index; } + PA_FORCE_INLINE size_t y() const{ return (uint32_t)(m_index >> 32); } + + PA_FORCE_INLINE friend bool operator<(const TileIndex& a, const TileIndex& b){ + return a.m_index < b.m_index; + } + +private: + uint64_t m_index; +}; + + + + +template +class PackedBinaryMatrixCore{ +public: + using Tile = TileType; + +public: + // Rule of 5 + ~PackedBinaryMatrixCore(); + PackedBinaryMatrixCore(PackedBinaryMatrixCore&& x); + void operator=(PackedBinaryMatrixCore&& x); + PackedBinaryMatrixCore(const PackedBinaryMatrixCore& x); + void operator=(const PackedBinaryMatrixCore& x); + +public: + // Construction + PackedBinaryMatrixCore(); + PackedBinaryMatrixCore(size_t width, size_t height); + + void clear(); + + void set_zero(); // Zero the entire matrix. + void set_ones(); // Set entire matrix to ones. + void invert(); // Invert all bits. + + // Matrix must have same dimensions. + void operator^=(const PackedBinaryMatrixCore& x); + void operator|=(const PackedBinaryMatrixCore& x); + void operator&=(const PackedBinaryMatrixCore& x); + +public: + // How many pixels in an image row, which is equal to how many bits in a binary matrix row + size_t width() const{ return m_logical_width; } + // How many pixels in an image column, which is equal to how many bits in a binary matrix column + size_t height() const{ return m_logical_height; } + + // These are slow. + bool get(size_t x, size_t y) const; + void set(size_t x, size_t y, bool set); + + PackedBinaryMatrixCore submatrix(size_t x, size_t y, size_t width, size_t height) const; + + // Print entire binary matrix as 0s and 1s. Rows are ended with "\n". + std::string dump() const; + // Print part of max as 0s and 1s. Rows are ended with "\n". + std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const; + // Print all the underlying tiles that form this binary matrix. The result is a matrix that may be larger + // than the original matrix. + std::string dump_tiles() const; + +public: + // How many tiles in a row. + size_t tile_width() const{ return m_tile_width; } + // How many tiles in a column + size_t tile_height() const{ return m_tile_height; } + + // Get (index.x()-th, index.y()-th) tile + const TileType& tile(TileIndex index) const; + TileType& tile(TileIndex index); + // Get (x-th, y-th) tile + const TileType& tile(size_t x, size_t y) const; + TileType& tile(size_t x, size_t y); + +public: + // Word Access. How many words in a row. One word is 8 bytes (aka 64 bits). + // For different simd implementations, every tile is always one word wide. + size_t word64_width() const{ return m_tile_width; } + // Word Access. How many words in a column. One word is 8 bytes (aka 64 bits). + size_t word64_height() const{ return m_logical_height; } + + // Get (x-th, y-th) word. One word is 8 bytes (aka 64 bits), one row in a tile. + uint64_t word64(size_t x, size_t y) const; + // Get (x-th, y-th) word. One word is 8 bytes (aka 64 bits), one row in a tile. + uint64_t& word64(size_t x, size_t y); + +private: + static constexpr size_t TILE_WIDTH = TileType::WIDTH; + static constexpr size_t TILE_HEIGHT = TileType::HEIGHT; + + // How many bits in a row (aka how many pixels in an image row) + size_t m_logical_width; + // How many bits in a column (aka how many pixels in an image column) + size_t m_logical_height; + // How many tiles in a row + size_t m_tile_width; + // How many tiles in a column + size_t m_tile_height; + AlignedVector m_data; +}; + + + + + +// Implementations + + + +// Tile Access + +template PA_FORCE_INLINE +const Tile& PackedBinaryMatrixCore::tile(TileIndex index) const{ + return m_data[index.x() + index.y() * m_tile_width]; +} +template PA_FORCE_INLINE +Tile& PackedBinaryMatrixCore::tile(TileIndex index){ + return m_data[index.x() + index.y() * m_tile_width]; +} +template PA_FORCE_INLINE +const Tile& PackedBinaryMatrixCore::tile(size_t x, size_t y) const{ + return m_data[x + y * m_tile_width]; +} +template PA_FORCE_INLINE +Tile& PackedBinaryMatrixCore::tile(size_t x, size_t y){ + return m_data[x + y * m_tile_width]; +} + + + +// Word Access + +template PA_FORCE_INLINE +uint64_t PackedBinaryMatrixCore::word64(size_t x, size_t y) const{ + static_assert(TILE_WIDTH == 64); + const Tile& tile = this->tile(x, y / TILE_HEIGHT); + return tile.row(y % TILE_HEIGHT); +} +template PA_FORCE_INLINE +uint64_t& PackedBinaryMatrixCore::word64(size_t x, size_t y){ + static_assert(TILE_WIDTH == 64); + Tile& tile = this->tile(x, y / TILE_HEIGHT); + return tile.row(y % TILE_HEIGHT); +} + + + +// Bit Access + +// Get the bit at bit location (x, y) +template +bool PackedBinaryMatrixCore::get(size_t x, size_t y) const{ + const Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); + return tile.get_bit(x % TILE_WIDTH, y % TILE_HEIGHT); +} + +// Set the bit at bit location (x, y) to `set` +template +void PackedBinaryMatrixCore::set(size_t x, size_t y, bool set){ + Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); + tile.set_bit(x % TILE_WIDTH, y % TILE_HEIGHT, set); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.tpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.tpp index acef198332..40f26fb9ed 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.tpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.tpp @@ -1,322 +1,322 @@ -/* Packed Binary Matrix Base - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_Kernels_PackedBinaryMatrixCore_TPP -#define PokemonAutomation_Kernels_PackedBinaryMatrixCore_TPP - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "Kernels_PackedBinaryMatrixCore.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -// Rule of 5 - -template -PackedBinaryMatrixCore::~PackedBinaryMatrixCore(){} -template -PackedBinaryMatrixCore::PackedBinaryMatrixCore(PackedBinaryMatrixCore&& x) - : m_logical_width(x.m_logical_width) - , m_logical_height(x.m_logical_height) - , m_tile_width(x.m_tile_width) - , m_tile_height(x.m_tile_height) - , m_data(std::move(x.m_data)) -{ - x.m_logical_width = 0; - x.m_logical_height = 0; - x.m_tile_width = 0; - x.m_tile_height = 0; -} -template -void PackedBinaryMatrixCore::operator=(PackedBinaryMatrixCore&& x){ - m_logical_width = x.m_logical_width; - m_logical_height = x.m_logical_height; - m_tile_width = x.m_tile_width; - m_tile_height = x.m_tile_height; - m_data = std::move(x.m_data); - x.m_logical_width = 0; - x.m_logical_height = 0; - x.m_tile_width = 0; - x.m_tile_height = 0; -} -template -PackedBinaryMatrixCore::PackedBinaryMatrixCore(const PackedBinaryMatrixCore& x) - : m_logical_width(x.m_logical_width) - , m_logical_height(x.m_logical_height) - , m_tile_width(x.m_tile_width) - , m_tile_height(x.m_tile_height) - , m_data(m_tile_width * m_tile_height) -{ - size_t stop = m_tile_width * m_tile_height; - for (size_t c = 0; c < stop; c++){ - m_data[c] = x.m_data[c]; - } -} -template -void PackedBinaryMatrixCore::operator=(const PackedBinaryMatrixCore& x){ - m_logical_width = x.m_logical_width; - m_logical_height = x.m_logical_height; - m_tile_width = x.m_tile_width; - m_tile_height = x.m_tile_height; - m_data = x.m_data; -} - - -// Construction - -template -PackedBinaryMatrixCore::PackedBinaryMatrixCore() - : m_logical_width(0) - , m_logical_height(0) - , m_tile_width(0) - , m_tile_height(0) -{} -template -PackedBinaryMatrixCore::PackedBinaryMatrixCore(size_t width, size_t height) - : m_logical_width(width) - , m_logical_height(height) - , m_tile_width((width + TILE_WIDTH - 1) / TILE_WIDTH) - , m_tile_height((height + TILE_HEIGHT - 1) / TILE_HEIGHT) - , m_data(m_tile_width * m_tile_height) -{} -template -void PackedBinaryMatrixCore::clear(){ - m_logical_width = 0; - m_logical_height = 0; - m_tile_width = 0; - m_tile_height = 0; - m_data.clear(); -} -template -void PackedBinaryMatrixCore::set_zero(){ - size_t stop = m_tile_width * m_tile_height; - for (size_t c = 0; c < stop; c++){ - m_data[c].set_zero(); - } -} -template -void PackedBinaryMatrixCore::set_ones(){ - // This one is more complicated because because we need to leave the - // padding its zero. - size_t r = 0; - size_t r_left = m_logical_height; - while (r_left >= TILE_HEIGHT){ - size_t c = 0; - size_t c_left = m_logical_width; - while (c_left >= TILE_WIDTH){ - this->tile(c, r).set_ones(); - c++; - c_left -= TILE_WIDTH; - } - if (c_left > 0){ - this->tile(c, r).set_ones(c_left, TILE_HEIGHT); - } - r++; - r_left -= TILE_HEIGHT; - } - if (r_left > 0){ - size_t c = 0; - size_t c_left = m_logical_width; - while (c_left >= TILE_WIDTH){ - this->tile(c, r).set_ones(TILE_WIDTH, r_left); - c++; - c_left -= TILE_WIDTH; - } - if (c_left > 0){ - this->tile(c, r).set_ones(c_left, r_left); - } - - } -} -template -void PackedBinaryMatrixCore::invert(){ - // This one is more complicated because because we need to leave the - // padding its zero. - size_t r = 0; - size_t r_left = m_logical_height; - while (r_left >= TILE_HEIGHT){ - size_t c = 0; - size_t c_left = m_logical_width; - while (c_left >= TILE_WIDTH){ - this->tile(c, r).invert(); - c++; - c_left -= TILE_WIDTH; - } - if (c_left > 0){ - Tile& tile = this->tile(c, r); - tile.invert(); - tile.clear_padding(c_left, TILE_HEIGHT); - } - r++; - r_left -= TILE_HEIGHT; - } - if (r_left > 0){ - size_t c = 0; - size_t c_left = m_logical_width; - while (c_left >= TILE_WIDTH){ - Tile& tile = this->tile(c, r); - tile.invert(); - tile.clear_padding(TILE_WIDTH, r_left); - c++; - c_left -= TILE_WIDTH; - } - if (c_left > 0){ - Tile& tile = this->tile(c, r); - tile.invert(); - tile.clear_padding(c_left, r_left); - } - - } -} -template -void PackedBinaryMatrixCore::operator^=(const PackedBinaryMatrixCore& x){ - if (m_logical_width != x.m_logical_width || m_logical_height != x.m_logical_height){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); - } - size_t stop = m_tile_width * m_tile_height; - for (size_t c = 0; c < stop; c++){ - m_data[c] ^= x.m_data[c]; - } -} -template -void PackedBinaryMatrixCore::operator|=(const PackedBinaryMatrixCore& x){ - if (m_logical_width != x.m_logical_width || m_logical_height != x.m_logical_height){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); - } - size_t stop = m_tile_width * m_tile_height; - for (size_t c = 0; c < stop; c++){ - m_data[c] |= x.m_data[c]; - } -} -template -void PackedBinaryMatrixCore::operator&=(const PackedBinaryMatrixCore& x){ - if (m_logical_width != x.m_logical_width || m_logical_height != x.m_logical_height){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); - } - size_t stop = m_tile_width * m_tile_height; - for (size_t c = 0; c < stop; c++){ - m_data[c] &= x.m_data[c]; - } -} - - - -// Debugging - -template -std::string PackedBinaryMatrixCore::dump() const{ - return dump(0, 0, m_logical_width, m_logical_height); -} -template -std::string PackedBinaryMatrixCore::dump( - size_t min_x, size_t min_y, - size_t max_x, size_t max_y -) const{ - std::string str; - for (size_t r = min_y; r < max_y; r++){ - for (size_t c = min_x; c < max_x; c++){ - str += get(c, r) ? '1' : '0'; - } - str += "\n"; - } - return str; -} -template -std::string PackedBinaryMatrixCore::dump_tiles() const{ - return dump(0, 0, m_tile_width * TILE_WIDTH, m_tile_height * TILE_HEIGHT); -} - - - - -template -PackedBinaryMatrixCore PackedBinaryMatrixCore::submatrix( - size_t x, size_t y, - size_t width, size_t height -) const{ - PackedBinaryMatrixCore ret(width, height); - - // Completely out-of-bounds. - if (x >= m_logical_width){ - return ret; - } - if (y >= m_logical_height){ - return ret; - } - - // Partially out-of-bounds. - width = std::min(width, m_logical_width - x); - height = std::min(height, m_logical_height - y); - - size_t tile_width = (width + TILE_WIDTH - 1) / TILE_WIDTH; - size_t tile_height = (height + TILE_HEIGHT - 1) / TILE_HEIGHT; - size_t tile_shift_x = x / TILE_WIDTH; - size_t tile_shift_y = y / TILE_HEIGHT; - size_t bit_shift_x = x % TILE_WIDTH; - size_t bit_shift_y = y % TILE_HEIGHT; - -// cout << "bit_shift_x = " << bit_shift_x << endl; -// cout << "bit_shift_y = " << bit_shift_y << endl; - - for (size_t r = 0; r < tile_height; r++){ - for (size_t c = 0; c < tile_width; c++){ - // For tile in the destination matrix, populate it by extracting - // from the 4 tiles that it overlaps in the source. - size_t src_x = tile_shift_x + c; - size_t src_y = tile_shift_y + r; - Tile& tile = ret.tile(c, r); - - // Upper-left tile is always there. - this->tile(src_x, src_y).copy_to_shift_pp(tile, bit_shift_x, bit_shift_y); - - bool shift_x = src_x + 1 < m_tile_width && bit_shift_x != 0; - bool shift_y = src_y + 1 < m_tile_height && bit_shift_y != 0; - - // Upper-right is there only if horizontally misaligned. - if (shift_x){ - this->tile(src_x + 1, src_y).copy_to_shift_np(tile, TILE_WIDTH - bit_shift_x, bit_shift_y); - } - - // Lower-left is there only if vertically misaligned. - if (shift_y){ - this->tile(src_x, src_y + 1).copy_to_shift_pn(tile, bit_shift_x, TILE_HEIGHT - bit_shift_y); - } - - // Lower-right if both horizontally and vertically misaligned. - if (shift_x && shift_y){ - this->tile(src_x + 1, src_y + 1).copy_to_shift_nn(tile, TILE_WIDTH - bit_shift_x, TILE_HEIGHT - bit_shift_y); - } - } - } - -#if 1 - size_t wbits = width % TILE_WIDTH; - for (size_t r = 0; r < tile_height; r++){ - ret.tile(tile_width - 1, r).clear_padding(wbits, TILE_HEIGHT); - } - size_t hbits = height % TILE_HEIGHT; - for (size_t c = 0; c < tile_width; c++){ - ret.tile(c, tile_height - 1).clear_padding(TILE_WIDTH, hbits); - } -#endif - - return ret; -} - - - - - -} -} -#endif +/* Packed Binary Matrix Base + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_Kernels_PackedBinaryMatrixCore_TPP +#define PokemonAutomation_Kernels_PackedBinaryMatrixCore_TPP + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "Kernels_PackedBinaryMatrixCore.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +// Rule of 5 + +template +PackedBinaryMatrixCore::~PackedBinaryMatrixCore(){} +template +PackedBinaryMatrixCore::PackedBinaryMatrixCore(PackedBinaryMatrixCore&& x) + : m_logical_width(x.m_logical_width) + , m_logical_height(x.m_logical_height) + , m_tile_width(x.m_tile_width) + , m_tile_height(x.m_tile_height) + , m_data(std::move(x.m_data)) +{ + x.m_logical_width = 0; + x.m_logical_height = 0; + x.m_tile_width = 0; + x.m_tile_height = 0; +} +template +void PackedBinaryMatrixCore::operator=(PackedBinaryMatrixCore&& x){ + m_logical_width = x.m_logical_width; + m_logical_height = x.m_logical_height; + m_tile_width = x.m_tile_width; + m_tile_height = x.m_tile_height; + m_data = std::move(x.m_data); + x.m_logical_width = 0; + x.m_logical_height = 0; + x.m_tile_width = 0; + x.m_tile_height = 0; +} +template +PackedBinaryMatrixCore::PackedBinaryMatrixCore(const PackedBinaryMatrixCore& x) + : m_logical_width(x.m_logical_width) + , m_logical_height(x.m_logical_height) + , m_tile_width(x.m_tile_width) + , m_tile_height(x.m_tile_height) + , m_data(m_tile_width * m_tile_height) +{ + size_t stop = m_tile_width * m_tile_height; + for (size_t c = 0; c < stop; c++){ + m_data[c] = x.m_data[c]; + } +} +template +void PackedBinaryMatrixCore::operator=(const PackedBinaryMatrixCore& x){ + m_logical_width = x.m_logical_width; + m_logical_height = x.m_logical_height; + m_tile_width = x.m_tile_width; + m_tile_height = x.m_tile_height; + m_data = x.m_data; +} + + +// Construction + +template +PackedBinaryMatrixCore::PackedBinaryMatrixCore() + : m_logical_width(0) + , m_logical_height(0) + , m_tile_width(0) + , m_tile_height(0) +{} +template +PackedBinaryMatrixCore::PackedBinaryMatrixCore(size_t width, size_t height) + : m_logical_width(width) + , m_logical_height(height) + , m_tile_width((width + TILE_WIDTH - 1) / TILE_WIDTH) + , m_tile_height((height + TILE_HEIGHT - 1) / TILE_HEIGHT) + , m_data(m_tile_width * m_tile_height) +{} +template +void PackedBinaryMatrixCore::clear(){ + m_logical_width = 0; + m_logical_height = 0; + m_tile_width = 0; + m_tile_height = 0; + m_data.clear(); +} +template +void PackedBinaryMatrixCore::set_zero(){ + size_t stop = m_tile_width * m_tile_height; + for (size_t c = 0; c < stop; c++){ + m_data[c].set_zero(); + } +} +template +void PackedBinaryMatrixCore::set_ones(){ + // This one is more complicated because because we need to leave the + // padding its zero. + size_t r = 0; + size_t r_left = m_logical_height; + while (r_left >= TILE_HEIGHT){ + size_t c = 0; + size_t c_left = m_logical_width; + while (c_left >= TILE_WIDTH){ + this->tile(c, r).set_ones(); + c++; + c_left -= TILE_WIDTH; + } + if (c_left > 0){ + this->tile(c, r).set_ones(c_left, TILE_HEIGHT); + } + r++; + r_left -= TILE_HEIGHT; + } + if (r_left > 0){ + size_t c = 0; + size_t c_left = m_logical_width; + while (c_left >= TILE_WIDTH){ + this->tile(c, r).set_ones(TILE_WIDTH, r_left); + c++; + c_left -= TILE_WIDTH; + } + if (c_left > 0){ + this->tile(c, r).set_ones(c_left, r_left); + } + + } +} +template +void PackedBinaryMatrixCore::invert(){ + // This one is more complicated because because we need to leave the + // padding its zero. + size_t r = 0; + size_t r_left = m_logical_height; + while (r_left >= TILE_HEIGHT){ + size_t c = 0; + size_t c_left = m_logical_width; + while (c_left >= TILE_WIDTH){ + this->tile(c, r).invert(); + c++; + c_left -= TILE_WIDTH; + } + if (c_left > 0){ + Tile& tile = this->tile(c, r); + tile.invert(); + tile.clear_padding(c_left, TILE_HEIGHT); + } + r++; + r_left -= TILE_HEIGHT; + } + if (r_left > 0){ + size_t c = 0; + size_t c_left = m_logical_width; + while (c_left >= TILE_WIDTH){ + Tile& tile = this->tile(c, r); + tile.invert(); + tile.clear_padding(TILE_WIDTH, r_left); + c++; + c_left -= TILE_WIDTH; + } + if (c_left > 0){ + Tile& tile = this->tile(c, r); + tile.invert(); + tile.clear_padding(c_left, r_left); + } + + } +} +template +void PackedBinaryMatrixCore::operator^=(const PackedBinaryMatrixCore& x){ + if (m_logical_width != x.m_logical_width || m_logical_height != x.m_logical_height){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); + } + size_t stop = m_tile_width * m_tile_height; + for (size_t c = 0; c < stop; c++){ + m_data[c] ^= x.m_data[c]; + } +} +template +void PackedBinaryMatrixCore::operator|=(const PackedBinaryMatrixCore& x){ + if (m_logical_width != x.m_logical_width || m_logical_height != x.m_logical_height){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); + } + size_t stop = m_tile_width * m_tile_height; + for (size_t c = 0; c < stop; c++){ + m_data[c] |= x.m_data[c]; + } +} +template +void PackedBinaryMatrixCore::operator&=(const PackedBinaryMatrixCore& x){ + if (m_logical_width != x.m_logical_width || m_logical_height != x.m_logical_height){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching dimensions."); + } + size_t stop = m_tile_width * m_tile_height; + for (size_t c = 0; c < stop; c++){ + m_data[c] &= x.m_data[c]; + } +} + + + +// Debugging + +template +std::string PackedBinaryMatrixCore::dump() const{ + return dump(0, 0, m_logical_width, m_logical_height); +} +template +std::string PackedBinaryMatrixCore::dump( + size_t min_x, size_t min_y, + size_t max_x, size_t max_y +) const{ + std::string str; + for (size_t r = min_y; r < max_y; r++){ + for (size_t c = min_x; c < max_x; c++){ + str += get(c, r) ? '1' : '0'; + } + str += "\n"; + } + return str; +} +template +std::string PackedBinaryMatrixCore::dump_tiles() const{ + return dump(0, 0, m_tile_width * TILE_WIDTH, m_tile_height * TILE_HEIGHT); +} + + + + +template +PackedBinaryMatrixCore PackedBinaryMatrixCore::submatrix( + size_t x, size_t y, + size_t width, size_t height +) const{ + PackedBinaryMatrixCore ret(width, height); + + // Completely out-of-bounds. + if (x >= m_logical_width){ + return ret; + } + if (y >= m_logical_height){ + return ret; + } + + // Partially out-of-bounds. + width = std::min(width, m_logical_width - x); + height = std::min(height, m_logical_height - y); + + size_t tile_width = (width + TILE_WIDTH - 1) / TILE_WIDTH; + size_t tile_height = (height + TILE_HEIGHT - 1) / TILE_HEIGHT; + size_t tile_shift_x = x / TILE_WIDTH; + size_t tile_shift_y = y / TILE_HEIGHT; + size_t bit_shift_x = x % TILE_WIDTH; + size_t bit_shift_y = y % TILE_HEIGHT; + +// cout << "bit_shift_x = " << bit_shift_x << endl; +// cout << "bit_shift_y = " << bit_shift_y << endl; + + for (size_t r = 0; r < tile_height; r++){ + for (size_t c = 0; c < tile_width; c++){ + // For tile in the destination matrix, populate it by extracting + // from the 4 tiles that it overlaps in the source. + size_t src_x = tile_shift_x + c; + size_t src_y = tile_shift_y + r; + Tile& tile = ret.tile(c, r); + + // Upper-left tile is always there. + this->tile(src_x, src_y).copy_to_shift_pp(tile, bit_shift_x, bit_shift_y); + + bool shift_x = src_x + 1 < m_tile_width && bit_shift_x != 0; + bool shift_y = src_y + 1 < m_tile_height && bit_shift_y != 0; + + // Upper-right is there only if horizontally misaligned. + if (shift_x){ + this->tile(src_x + 1, src_y).copy_to_shift_np(tile, TILE_WIDTH - bit_shift_x, bit_shift_y); + } + + // Lower-left is there only if vertically misaligned. + if (shift_y){ + this->tile(src_x, src_y + 1).copy_to_shift_pn(tile, bit_shift_x, TILE_HEIGHT - bit_shift_y); + } + + // Lower-right if both horizontally and vertically misaligned. + if (shift_x && shift_y){ + this->tile(src_x + 1, src_y + 1).copy_to_shift_nn(tile, TILE_WIDTH - bit_shift_x, TILE_HEIGHT - bit_shift_y); + } + } + } + +#if 1 + size_t wbits = width % TILE_WIDTH; + for (size_t r = 0; r < tile_height; r++){ + ret.tile(tile_width - 1, r).clear_padding(wbits, TILE_HEIGHT); + } + size_t hbits = height % TILE_HEIGHT; + for (size_t c = 0; c < tile_width; c++){ + ret.tile(c, tile_height - 1).clear_padding(TILE_WIDTH, hbits); + } +#endif + + return ret; +} + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h index 413ef4d7d8..c0a286f2b9 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h @@ -1,157 +1,157 @@ -/* Packed Binary Matrix Base - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_SparseBinaryMatrixCore_H -#define PokemonAutomation_Kernels_SparseBinaryMatrixCore_H - -#include -#include -#include "Kernels_PackedBinaryMatrixCore.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -class SparseBinaryMatrixCore{ -public: - using Tile = TileType; - -public: - // Rule of 5 - ~SparseBinaryMatrixCore(); - SparseBinaryMatrixCore(SparseBinaryMatrixCore&& x); - void operator=(SparseBinaryMatrixCore&& x); - SparseBinaryMatrixCore(const SparseBinaryMatrixCore& x); - void operator=(const SparseBinaryMatrixCore& x); - -public: - // Construction - SparseBinaryMatrixCore(); - SparseBinaryMatrixCore(size_t width, size_t height); - - void clear(); - void set_data(std::map data); - - void operator^=(const SparseBinaryMatrixCore& x); - void operator|=(const SparseBinaryMatrixCore& x); - void operator&=(const SparseBinaryMatrixCore& x); - -public: - size_t width() const{ return m_logical_width; } - size_t height() const{ return m_logical_height; } - - // These are slow. - bool get(size_t x, size_t y) const; - void set(size_t x, size_t y, bool set); - - PackedBinaryMatrixCore submatrix(size_t x, size_t y, size_t width, size_t height) const; - - std::string dump() const; - std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const; - -public: - // Tile Access - size_t tile_width() const{ return m_tile_width; } - size_t tile_height() const{ return m_tile_height; } - - const TileType& tile(TileIndex index) const; - TileType& tile(TileIndex index); - const TileType& tile(size_t x, size_t y) const; - TileType& tile(size_t x, size_t y); - -public: - // Word Access - size_t word64_width() const{ return m_tile_width; } - size_t word64_height() const{ return m_logical_height; } - - uint64_t word64(size_t x, size_t y) const; - uint64_t& word64(size_t x, size_t y); - -private: - static constexpr size_t TILE_WIDTH = TileType::WIDTH; - static constexpr size_t TILE_HEIGHT = TileType::HEIGHT; - - size_t m_logical_width; - size_t m_logical_height; - size_t m_tile_width; - size_t m_tile_height; - std::map m_data; - - - static const TileType& ZERO_TILE(); -}; - - - - - - -// Implementations - - - -// Tile Access - -template PA_FORCE_INLINE -const Tile& SparseBinaryMatrixCore::tile(TileIndex index) const{ - auto iter = m_data.find(index); - if (iter == m_data.end()){ - return ZERO_TILE(); - } - return iter->second; -} -template PA_FORCE_INLINE -Tile& SparseBinaryMatrixCore::tile(TileIndex index){ - return m_data[index]; -} -template PA_FORCE_INLINE -const Tile& SparseBinaryMatrixCore::tile(size_t x, size_t y) const{ - return tile(TileIndex(x, y)); -} -template PA_FORCE_INLINE -Tile& SparseBinaryMatrixCore::tile(size_t x, size_t y){ - return tile(TileIndex(x, y)); -} - - - -// Word Access - -template PA_FORCE_INLINE -uint64_t SparseBinaryMatrixCore::word64(size_t x, size_t y) const{ - static_assert(TILE_WIDTH == 64); - const Tile& tile = this->tile(x, y / TILE_HEIGHT); - return tile.row(y % TILE_HEIGHT); -} -template PA_FORCE_INLINE -uint64_t& SparseBinaryMatrixCore::word64(size_t x, size_t y){ - static_assert(TILE_WIDTH == 64); - Tile& tile = this->tile(x, y / TILE_HEIGHT); - return tile.row(y % TILE_HEIGHT); -} - - - -// Bit Access - -template -bool SparseBinaryMatrixCore::get(size_t x, size_t y) const{ - const Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); - return tile.get_bit(x % TILE_WIDTH, y % TILE_HEIGHT); -} -template -void SparseBinaryMatrixCore::set(size_t x, size_t y, bool set){ - Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); - tile.set_bit(x % TILE_WIDTH, y % TILE_HEIGHT, set); -} - - - - -} -} -#endif +/* Packed Binary Matrix Base + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_SparseBinaryMatrixCore_H +#define PokemonAutomation_Kernels_SparseBinaryMatrixCore_H + +#include +#include +#include "Kernels_PackedBinaryMatrixCore.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +class SparseBinaryMatrixCore{ +public: + using Tile = TileType; + +public: + // Rule of 5 + ~SparseBinaryMatrixCore(); + SparseBinaryMatrixCore(SparseBinaryMatrixCore&& x); + void operator=(SparseBinaryMatrixCore&& x); + SparseBinaryMatrixCore(const SparseBinaryMatrixCore& x); + void operator=(const SparseBinaryMatrixCore& x); + +public: + // Construction + SparseBinaryMatrixCore(); + SparseBinaryMatrixCore(size_t width, size_t height); + + void clear(); + void set_data(std::map data); + + void operator^=(const SparseBinaryMatrixCore& x); + void operator|=(const SparseBinaryMatrixCore& x); + void operator&=(const SparseBinaryMatrixCore& x); + +public: + size_t width() const{ return m_logical_width; } + size_t height() const{ return m_logical_height; } + + // These are slow. + bool get(size_t x, size_t y) const; + void set(size_t x, size_t y, bool set); + + PackedBinaryMatrixCore submatrix(size_t x, size_t y, size_t width, size_t height) const; + + std::string dump() const; + std::string dump(size_t min_x, size_t min_y, size_t max_x, size_t max_y) const; + +public: + // Tile Access + size_t tile_width() const{ return m_tile_width; } + size_t tile_height() const{ return m_tile_height; } + + const TileType& tile(TileIndex index) const; + TileType& tile(TileIndex index); + const TileType& tile(size_t x, size_t y) const; + TileType& tile(size_t x, size_t y); + +public: + // Word Access + size_t word64_width() const{ return m_tile_width; } + size_t word64_height() const{ return m_logical_height; } + + uint64_t word64(size_t x, size_t y) const; + uint64_t& word64(size_t x, size_t y); + +private: + static constexpr size_t TILE_WIDTH = TileType::WIDTH; + static constexpr size_t TILE_HEIGHT = TileType::HEIGHT; + + size_t m_logical_width; + size_t m_logical_height; + size_t m_tile_width; + size_t m_tile_height; + std::map m_data; + + + static const TileType& ZERO_TILE(); +}; + + + + + + +// Implementations + + + +// Tile Access + +template PA_FORCE_INLINE +const Tile& SparseBinaryMatrixCore::tile(TileIndex index) const{ + auto iter = m_data.find(index); + if (iter == m_data.end()){ + return ZERO_TILE(); + } + return iter->second; +} +template PA_FORCE_INLINE +Tile& SparseBinaryMatrixCore::tile(TileIndex index){ + return m_data[index]; +} +template PA_FORCE_INLINE +const Tile& SparseBinaryMatrixCore::tile(size_t x, size_t y) const{ + return tile(TileIndex(x, y)); +} +template PA_FORCE_INLINE +Tile& SparseBinaryMatrixCore::tile(size_t x, size_t y){ + return tile(TileIndex(x, y)); +} + + + +// Word Access + +template PA_FORCE_INLINE +uint64_t SparseBinaryMatrixCore::word64(size_t x, size_t y) const{ + static_assert(TILE_WIDTH == 64); + const Tile& tile = this->tile(x, y / TILE_HEIGHT); + return tile.row(y % TILE_HEIGHT); +} +template PA_FORCE_INLINE +uint64_t& SparseBinaryMatrixCore::word64(size_t x, size_t y){ + static_assert(TILE_WIDTH == 64); + Tile& tile = this->tile(x, y / TILE_HEIGHT); + return tile.row(y % TILE_HEIGHT); +} + + + +// Bit Access + +template +bool SparseBinaryMatrixCore::get(size_t x, size_t y) const{ + const Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); + return tile.get_bit(x % TILE_WIDTH, y % TILE_HEIGHT); +} +template +void SparseBinaryMatrixCore::set(size_t x, size_t y, bool set){ + Tile& tile = this->tile(x / TILE_WIDTH, y / TILE_HEIGHT); + tile.set_bit(x % TILE_WIDTH, y % TILE_HEIGHT, set); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.tpp b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.tpp index 92938fc7d0..10e6952d80 100644 --- a/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.tpp +++ b/SerialPrograms/Source/Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.tpp @@ -1,248 +1,248 @@ -/* Sparse Binary Matrix Base - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_Kernels_SparseBinaryMatrixCore_TPP -#define PokemonAutomation_Kernels_SparseBinaryMatrixCore_TPP - -#include "Kernels_SparseBinaryMatrixCore.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -// Rule of 5 - -template -SparseBinaryMatrixCore::~SparseBinaryMatrixCore(){} -template -SparseBinaryMatrixCore::SparseBinaryMatrixCore(SparseBinaryMatrixCore&& x) - : m_logical_width(x.m_logical_width) - , m_logical_height(x.m_logical_height) - , m_tile_width(x.m_tile_width) - , m_tile_height(x.m_tile_height) - , m_data(std::move(x.m_data)) -{ - x.m_logical_width = 0; - x.m_logical_height = 0; - x.m_tile_width = 0; - x.m_tile_height = 0; -} -template -void SparseBinaryMatrixCore::operator=(SparseBinaryMatrixCore&& x){ - m_logical_width = x.m_logical_width; - m_logical_height = x.m_logical_height; - m_tile_width = x.m_tile_width; - m_tile_height = x.m_tile_height; - m_data = std::move(x.m_data); - x.m_logical_width = 0; - x.m_logical_height = 0; - x.m_tile_width = 0; - x.m_tile_height = 0; -} -template -SparseBinaryMatrixCore::SparseBinaryMatrixCore(const SparseBinaryMatrixCore& x) - : m_logical_width(x.m_logical_width) - , m_logical_height(x.m_logical_height) - , m_tile_width(x.m_tile_width) - , m_tile_height(x.m_tile_height) - , m_data(x.m_data) -{} -template -void SparseBinaryMatrixCore::operator=(const SparseBinaryMatrixCore& x){ - m_logical_width = x.m_logical_width; - m_logical_height = x.m_logical_height; - m_tile_width = x.m_tile_width; - m_tile_height = x.m_tile_height; - m_data = x.m_data; -} - - -// Construction - -template -SparseBinaryMatrixCore::SparseBinaryMatrixCore() - : m_logical_width(0) - , m_logical_height(0) - , m_tile_width(0) - , m_tile_height(0) -{} -template -SparseBinaryMatrixCore::SparseBinaryMatrixCore(size_t width, size_t height) - : m_logical_width(width) - , m_logical_height(height) - , m_tile_width((width + TILE_WIDTH - 1) / TILE_WIDTH) - , m_tile_height((height + TILE_HEIGHT - 1) / TILE_HEIGHT) -{} -template -void SparseBinaryMatrixCore::clear(){ - m_logical_width = 0; - m_logical_height = 0; - m_tile_width = 0; - m_tile_height = 0; - m_data.clear(); -} -template -void SparseBinaryMatrixCore::set_data(std::map data){ - m_data = std::move(data); -} - -template -void SparseBinaryMatrixCore::operator^=(const SparseBinaryMatrixCore& x){ - m_logical_width = std::max(m_logical_width, x.m_logical_width); - m_logical_height = std::max(m_logical_height, x.m_logical_height); - m_tile_width = std::max(m_tile_width, x.m_tile_width); - m_tile_height = std::max(m_tile_height, x.m_tile_height); - for (const auto& tile : x.m_data){ - this->tile(tile.first) ^= tile.second; - } -} -template -void SparseBinaryMatrixCore::operator|=(const SparseBinaryMatrixCore& x){ - m_logical_width = std::max(m_logical_width, x.m_logical_width); - m_logical_height = std::max(m_logical_height, x.m_logical_height); - m_tile_width = std::max(m_tile_width, x.m_tile_width); - m_tile_height = std::max(m_tile_height, x.m_tile_height); - for (const auto& tile : x.m_data){ - this->tile(tile.first) |= tile.second; - } -} -template -void SparseBinaryMatrixCore::operator&=(const SparseBinaryMatrixCore& x){ - m_logical_width = std::max(m_logical_width, x.m_logical_width); - m_logical_height = std::max(m_logical_height, x.m_logical_height); - m_tile_width = std::max(m_tile_width, x.m_tile_width); - m_tile_height = std::max(m_tile_height, x.m_tile_height); - for (const auto& tile : x.m_data){ - this->tile(tile.first) &= tile.second; - } -} - - -template -const Tile& SparseBinaryMatrixCore::ZERO_TILE(){ - static Tile ZERO; - return ZERO; -} - - - - -// Debugging - -template -std::string SparseBinaryMatrixCore::dump() const{ - return dump(0, 0, m_logical_width, m_logical_height); -} -template -std::string SparseBinaryMatrixCore::dump( - size_t min_x, size_t min_y, - size_t max_x, size_t max_y -) const{ - std::string str; - for (size_t r = min_y; r < max_y; r++){ - for (size_t c = min_x; c < max_x; c++){ - str += get(c, r) ? '1' : '0'; - } - str += "\n"; - } - return str; -} - - - - -template -PackedBinaryMatrixCore SparseBinaryMatrixCore::submatrix( - size_t x, size_t y, - size_t width, size_t height -) const{ - PackedBinaryMatrixCore ret(width, height); - - // Completely out-of-bounds. - if (x >= m_logical_width){ - return ret; - } - if (y >= m_logical_height){ - return ret; - } - - // Partially out-of-bounds. - width = std::min(width, m_logical_width - x); - height = std::min(height, m_logical_height - y); - - size_t tile_width = (width + TILE_WIDTH - 1) / TILE_WIDTH; - size_t tile_height = (height + TILE_HEIGHT - 1) / TILE_HEIGHT; - size_t tile_shift_x = x / TILE_WIDTH; - size_t tile_shift_y = y / TILE_HEIGHT; - size_t bit_shift_x = x % TILE_WIDTH; - size_t bit_shift_y = y % TILE_HEIGHT; - -// cout << "bit_shift_x = " << bit_shift_x << endl; -// cout << "bit_shift_y = " << bit_shift_y << endl; - - for (size_t r = 0; r < tile_height; r++){ - for (size_t c = 0; c < tile_width; c++){ - // For tile in the destination matrix, populate it by extracting - // from the 4 tiles that it overlaps in the source. - size_t src_x = tile_shift_x + c; - size_t src_y = tile_shift_y + r; - Tile& tile = ret.tile(c, r); - - // Upper-left tile is always there. - this->tile(src_x, src_y).copy_to_shift_pp(tile, bit_shift_x, bit_shift_y); - - bool shift_x = src_x + 1 < m_tile_width && bit_shift_x != 0; - bool shift_y = src_y + 1 < m_tile_height && bit_shift_y != 0; - - // Upper-right is there only if horizontally misaligned. - if (shift_x){ - this->tile(src_x + 1, src_y).copy_to_shift_np(tile, TILE_WIDTH - bit_shift_x, bit_shift_y); - } - - // Lower-left is there only if vertically misaligned. - if (shift_y){ - this->tile(src_x, src_y + 1).copy_to_shift_pn(tile, bit_shift_x, TILE_HEIGHT - bit_shift_y); - } - - // Lower-right if both horizontally and vertically misaligned. - if (shift_x && shift_y){ - this->tile(src_x + 1, src_y + 1).copy_to_shift_nn(tile, TILE_WIDTH - bit_shift_x, TILE_HEIGHT - bit_shift_y); - } - } - } - -#if 1 - size_t wbits = width % TILE_WIDTH; - if (wbits != 0){ - for (size_t r = 0; r < tile_height; r++){ - ret.tile(tile_width - 1, r).clear_padding(wbits, TILE_HEIGHT); - } - } - size_t hbits = height % TILE_HEIGHT; - if (hbits != 0){ - for (size_t c = 0; c < tile_width; c++){ - ret.tile(c, tile_height - 1).clear_padding(TILE_WIDTH, hbits); - } - } -#endif - - return ret; -} - - - - - - - -} -} -#endif +/* Sparse Binary Matrix Base + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_Kernels_SparseBinaryMatrixCore_TPP +#define PokemonAutomation_Kernels_SparseBinaryMatrixCore_TPP + +#include "Kernels_SparseBinaryMatrixCore.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +// Rule of 5 + +template +SparseBinaryMatrixCore::~SparseBinaryMatrixCore(){} +template +SparseBinaryMatrixCore::SparseBinaryMatrixCore(SparseBinaryMatrixCore&& x) + : m_logical_width(x.m_logical_width) + , m_logical_height(x.m_logical_height) + , m_tile_width(x.m_tile_width) + , m_tile_height(x.m_tile_height) + , m_data(std::move(x.m_data)) +{ + x.m_logical_width = 0; + x.m_logical_height = 0; + x.m_tile_width = 0; + x.m_tile_height = 0; +} +template +void SparseBinaryMatrixCore::operator=(SparseBinaryMatrixCore&& x){ + m_logical_width = x.m_logical_width; + m_logical_height = x.m_logical_height; + m_tile_width = x.m_tile_width; + m_tile_height = x.m_tile_height; + m_data = std::move(x.m_data); + x.m_logical_width = 0; + x.m_logical_height = 0; + x.m_tile_width = 0; + x.m_tile_height = 0; +} +template +SparseBinaryMatrixCore::SparseBinaryMatrixCore(const SparseBinaryMatrixCore& x) + : m_logical_width(x.m_logical_width) + , m_logical_height(x.m_logical_height) + , m_tile_width(x.m_tile_width) + , m_tile_height(x.m_tile_height) + , m_data(x.m_data) +{} +template +void SparseBinaryMatrixCore::operator=(const SparseBinaryMatrixCore& x){ + m_logical_width = x.m_logical_width; + m_logical_height = x.m_logical_height; + m_tile_width = x.m_tile_width; + m_tile_height = x.m_tile_height; + m_data = x.m_data; +} + + +// Construction + +template +SparseBinaryMatrixCore::SparseBinaryMatrixCore() + : m_logical_width(0) + , m_logical_height(0) + , m_tile_width(0) + , m_tile_height(0) +{} +template +SparseBinaryMatrixCore::SparseBinaryMatrixCore(size_t width, size_t height) + : m_logical_width(width) + , m_logical_height(height) + , m_tile_width((width + TILE_WIDTH - 1) / TILE_WIDTH) + , m_tile_height((height + TILE_HEIGHT - 1) / TILE_HEIGHT) +{} +template +void SparseBinaryMatrixCore::clear(){ + m_logical_width = 0; + m_logical_height = 0; + m_tile_width = 0; + m_tile_height = 0; + m_data.clear(); +} +template +void SparseBinaryMatrixCore::set_data(std::map data){ + m_data = std::move(data); +} + +template +void SparseBinaryMatrixCore::operator^=(const SparseBinaryMatrixCore& x){ + m_logical_width = std::max(m_logical_width, x.m_logical_width); + m_logical_height = std::max(m_logical_height, x.m_logical_height); + m_tile_width = std::max(m_tile_width, x.m_tile_width); + m_tile_height = std::max(m_tile_height, x.m_tile_height); + for (const auto& tile : x.m_data){ + this->tile(tile.first) ^= tile.second; + } +} +template +void SparseBinaryMatrixCore::operator|=(const SparseBinaryMatrixCore& x){ + m_logical_width = std::max(m_logical_width, x.m_logical_width); + m_logical_height = std::max(m_logical_height, x.m_logical_height); + m_tile_width = std::max(m_tile_width, x.m_tile_width); + m_tile_height = std::max(m_tile_height, x.m_tile_height); + for (const auto& tile : x.m_data){ + this->tile(tile.first) |= tile.second; + } +} +template +void SparseBinaryMatrixCore::operator&=(const SparseBinaryMatrixCore& x){ + m_logical_width = std::max(m_logical_width, x.m_logical_width); + m_logical_height = std::max(m_logical_height, x.m_logical_height); + m_tile_width = std::max(m_tile_width, x.m_tile_width); + m_tile_height = std::max(m_tile_height, x.m_tile_height); + for (const auto& tile : x.m_data){ + this->tile(tile.first) &= tile.second; + } +} + + +template +const Tile& SparseBinaryMatrixCore::ZERO_TILE(){ + static Tile ZERO; + return ZERO; +} + + + + +// Debugging + +template +std::string SparseBinaryMatrixCore::dump() const{ + return dump(0, 0, m_logical_width, m_logical_height); +} +template +std::string SparseBinaryMatrixCore::dump( + size_t min_x, size_t min_y, + size_t max_x, size_t max_y +) const{ + std::string str; + for (size_t r = min_y; r < max_y; r++){ + for (size_t c = min_x; c < max_x; c++){ + str += get(c, r) ? '1' : '0'; + } + str += "\n"; + } + return str; +} + + + + +template +PackedBinaryMatrixCore SparseBinaryMatrixCore::submatrix( + size_t x, size_t y, + size_t width, size_t height +) const{ + PackedBinaryMatrixCore ret(width, height); + + // Completely out-of-bounds. + if (x >= m_logical_width){ + return ret; + } + if (y >= m_logical_height){ + return ret; + } + + // Partially out-of-bounds. + width = std::min(width, m_logical_width - x); + height = std::min(height, m_logical_height - y); + + size_t tile_width = (width + TILE_WIDTH - 1) / TILE_WIDTH; + size_t tile_height = (height + TILE_HEIGHT - 1) / TILE_HEIGHT; + size_t tile_shift_x = x / TILE_WIDTH; + size_t tile_shift_y = y / TILE_HEIGHT; + size_t bit_shift_x = x % TILE_WIDTH; + size_t bit_shift_y = y % TILE_HEIGHT; + +// cout << "bit_shift_x = " << bit_shift_x << endl; +// cout << "bit_shift_y = " << bit_shift_y << endl; + + for (size_t r = 0; r < tile_height; r++){ + for (size_t c = 0; c < tile_width; c++){ + // For tile in the destination matrix, populate it by extracting + // from the 4 tiles that it overlaps in the source. + size_t src_x = tile_shift_x + c; + size_t src_y = tile_shift_y + r; + Tile& tile = ret.tile(c, r); + + // Upper-left tile is always there. + this->tile(src_x, src_y).copy_to_shift_pp(tile, bit_shift_x, bit_shift_y); + + bool shift_x = src_x + 1 < m_tile_width && bit_shift_x != 0; + bool shift_y = src_y + 1 < m_tile_height && bit_shift_y != 0; + + // Upper-right is there only if horizontally misaligned. + if (shift_x){ + this->tile(src_x + 1, src_y).copy_to_shift_np(tile, TILE_WIDTH - bit_shift_x, bit_shift_y); + } + + // Lower-left is there only if vertically misaligned. + if (shift_y){ + this->tile(src_x, src_y + 1).copy_to_shift_pn(tile, bit_shift_x, TILE_HEIGHT - bit_shift_y); + } + + // Lower-right if both horizontally and vertically misaligned. + if (shift_x && shift_y){ + this->tile(src_x + 1, src_y + 1).copy_to_shift_nn(tile, TILE_WIDTH - bit_shift_x, TILE_HEIGHT - bit_shift_y); + } + } + } + +#if 1 + size_t wbits = width % TILE_WIDTH; + if (wbits != 0){ + for (size_t r = 0; r < tile_height; r++){ + ret.tile(tile_width - 1, r).clear_padding(wbits, TILE_HEIGHT); + } + } + size_t hbits = height % TILE_HEIGHT; + if (hbits != 0){ + for (size_t c = 0; c < tile_width; c++){ + ret.tile(c, tile_height - 1).clear_padding(TILE_WIDTH, hbits); + } + } +#endif + + return ret; +} + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.cpp index 5132e46016..70f86b542b 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.cpp @@ -1,43 +1,43 @@ -/* Image Filters Basic - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -//#include "Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels_ImageFilter_Basic.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -size_t filter_green_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, uint8_t rgb_gap -); - - -size_t filter_green( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, uint8_t rgb_gap -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } - return filter_green_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, replacement, rgb_gap - ); -} - - - -} -} +/* Image Filters Basic + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +//#include "Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels_ImageFilter_Basic.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +size_t filter_green_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, uint8_t rgb_gap +); + + +size_t filter_green( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, uint8_t rgb_gap +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } + return filter_green_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, replacement, rgb_gap + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.h index d9e91ae548..139e12d8f7 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic.h @@ -1,37 +1,37 @@ -/* Image Filters Basic - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_Basic_H -#define PokemonAutomation_Kernels_ImageFilter_Basic_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - - - - - - -size_t filter_green( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, uint8_t rgb_gap -); - - - -} -} -#endif +/* Image Filters Basic + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_Basic_H +#define PokemonAutomation_Kernels_ImageFilter_Basic_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + + + + + + +size_t filter_green( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, uint8_t rgb_gap +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp index b52f699ef7..9372867f7b 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_ARM64_NEON.cpp @@ -1,35 +1,35 @@ -/* Image Filters Basic (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include -#include -#include "Kernels/Kernels_arm64_NEON.h" -// #include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels_ImageFilter_Basic_Routines.h" - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - - - - - - - - - -} -} -#endif +/* Image Filters Basic (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include +#include +#include "Kernels/Kernels_arm64_NEON.h" +// #include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels_ImageFilter_Basic_Routines.h" + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Default.cpp index 16dc8708fb..5dc0f32e45 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Default.cpp @@ -1,44 +1,44 @@ -/* Image Filters Basic (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Kernels_ImageFilter_Basic_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Image Filters Basic (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Kernels_ImageFilter_Basic_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h index 9b65a87a82..3e476f46e0 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h @@ -1,206 +1,206 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_Basic_Routines_H -#define PokemonAutomation_Kernels_ImageFilter_Basic_Routines_H - -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - -// Runner interface: -// - static size_t Runner::VECTOR_SIZE, how many uint32_t in an SIMD vector. Note one pixel is one uint32_t. -// - Runner::process_full(uint32_t* out, const uint32_t* in), process a full vector: replace pixels in -// or out of a specific color range with a particular color. -// - Runner::process_partial(uint32_t* out, const uint32_t* in, size_t left), process a partial vector: -// work only on the first `left` pixels. -template -PA_FORCE_INLINE void filter_per_pixel( - const uint32_t* image, size_t in_bytes_per_row, size_t width, size_t height, - Runner& filter, uint32_t* out, size_t out_bytes_per_row -){ - if (width == 0 || height == 0){ - return; - } - -// cout << "filter_per_pixel(1): " << width << " x " << height << endl; - - const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; - - // Less than vector width. No need for steady-state loop. - if (width < VECTOR_SIZE){ - typename Runner::Mask mask(width); - do{ - const uint32_t* in = image; - uint32_t* o0 = out; - filter.process_partial(o0, in, mask); - image = (const uint32_t*)((const char*)image + in_bytes_per_row); - out = (uint32_t*)((const char*)out + out_bytes_per_row); - }while (--height); - return; - } - - // Divisible by vector width. No need for peel iteration. - size_t left = width % VECTOR_SIZE; - if (left == 0){ - do{ - const uint32_t* in = image; - uint32_t* o0 = out; - size_t lc = width / VECTOR_SIZE; - do{ - filter.process_full(o0, in); - in += VECTOR_SIZE; - o0 += VECTOR_SIZE; - }while (--lc); - image = (const uint32_t*)((const char*)image + in_bytes_per_row); - out = (uint32_t*)((const char*)out + out_bytes_per_row); - }while (--height); - return; - } - - // Need both steady-state and peel iteration. - { - do{ - const uint32_t* in = image; - uint32_t* o0 = out; - size_t lc = width / VECTOR_SIZE; - do{ - filter.process_full(o0, in); - in += VECTOR_SIZE; - o0 += VECTOR_SIZE; - }while (--lc); - filter.process_partial(o0, in, left); - image = (const uint32_t*)((const char*)image + in_bytes_per_row); - out = (uint32_t*)((const char*)out + out_bytes_per_row); - }while (--height); - } -} - - -#if 0 - -template -PA_FORCE_INLINE void filter_per_pixel( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - Filter* filters, size_t filter_count -){ - if (width == 0 || height == 0){ - return; - } - -// cout << "filter_per_pixel(" << filter_count << "): " << width << " x " << height << endl; - - struct Entry{ - Runner runner; - char* current_row; - }; - - - FixedLimitVector entries(filter_count); - for (size_t c = 0; c < filter_count; c++){ - Filter& filter = filters[c]; - entries.emplace_back(Entry{filter, (char*)filter.data}); - } - - const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; - do{ - // Less than vector width. No need for steady-state loop. - if (width < VECTOR_SIZE){ - typename Runner::Mask mask(width); - do{ - const uint32_t* in = image; - for (size_t c = 0; c < filter_count; c++){ - entries[c].runner.process_partial((uint32_t*)entries[c].current_row, in, mask); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - entries[c].current_row += filters[c].bytes_per_row; - } - }while (--height); - break; - } - - // Divisible by vector width. No need for peel loop. - size_t left = width % VECTOR_SIZE; - if (left == 0){ - do{ - const uint32_t* in = image; - size_t shift = 0; - size_t lc = width / VECTOR_SIZE; - do{ - for (size_t c = 0; c < filter_count; c++){ - entries[c].runner.process_full((uint32_t*)entries[c].current_row + shift, in); - } - in += VECTOR_SIZE; - shift += VECTOR_SIZE; - }while (--lc); - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - entries[c].current_row += filters[c].bytes_per_row; - } - }while (--height); - break; - } - - // Need both steady-state and peel loops. - { - typename Runner::Mask mask(left); - do{ - const uint32_t* in = image; - size_t shift = 0; - size_t lc = width / VECTOR_SIZE; - do{ - for (size_t c = 0; c < filter_count; c++){ - entries[c].runner.process_full((uint32_t*)entries[c].current_row + shift, in); - } - in += VECTOR_SIZE; - shift += VECTOR_SIZE; - }while (--lc); - for (size_t c = 0; c < filter_count; c++){ - entries[c].runner.process_partial((uint32_t*)entries[c].current_row + shift, in, mask); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - entries[c].current_row += filters[c].bytes_per_row; - } - }while (--height); - break; - } - }while (false); - - for (size_t c = 0; c < filter_count; c++){ - filters[c].pixels_in_range = entries[c].runner.count(); - } -} - -#endif - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_Basic_Routines_H +#define PokemonAutomation_Kernels_ImageFilter_Basic_Routines_H + +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + +// Runner interface: +// - static size_t Runner::VECTOR_SIZE, how many uint32_t in an SIMD vector. Note one pixel is one uint32_t. +// - Runner::process_full(uint32_t* out, const uint32_t* in), process a full vector: replace pixels in +// or out of a specific color range with a particular color. +// - Runner::process_partial(uint32_t* out, const uint32_t* in, size_t left), process a partial vector: +// work only on the first `left` pixels. +template +PA_FORCE_INLINE void filter_per_pixel( + const uint32_t* image, size_t in_bytes_per_row, size_t width, size_t height, + Runner& filter, uint32_t* out, size_t out_bytes_per_row +){ + if (width == 0 || height == 0){ + return; + } + +// cout << "filter_per_pixel(1): " << width << " x " << height << endl; + + const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; + + // Less than vector width. No need for steady-state loop. + if (width < VECTOR_SIZE){ + typename Runner::Mask mask(width); + do{ + const uint32_t* in = image; + uint32_t* o0 = out; + filter.process_partial(o0, in, mask); + image = (const uint32_t*)((const char*)image + in_bytes_per_row); + out = (uint32_t*)((const char*)out + out_bytes_per_row); + }while (--height); + return; + } + + // Divisible by vector width. No need for peel iteration. + size_t left = width % VECTOR_SIZE; + if (left == 0){ + do{ + const uint32_t* in = image; + uint32_t* o0 = out; + size_t lc = width / VECTOR_SIZE; + do{ + filter.process_full(o0, in); + in += VECTOR_SIZE; + o0 += VECTOR_SIZE; + }while (--lc); + image = (const uint32_t*)((const char*)image + in_bytes_per_row); + out = (uint32_t*)((const char*)out + out_bytes_per_row); + }while (--height); + return; + } + + // Need both steady-state and peel iteration. + { + do{ + const uint32_t* in = image; + uint32_t* o0 = out; + size_t lc = width / VECTOR_SIZE; + do{ + filter.process_full(o0, in); + in += VECTOR_SIZE; + o0 += VECTOR_SIZE; + }while (--lc); + filter.process_partial(o0, in, left); + image = (const uint32_t*)((const char*)image + in_bytes_per_row); + out = (uint32_t*)((const char*)out + out_bytes_per_row); + }while (--height); + } +} + + +#if 0 + +template +PA_FORCE_INLINE void filter_per_pixel( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + Filter* filters, size_t filter_count +){ + if (width == 0 || height == 0){ + return; + } + +// cout << "filter_per_pixel(" << filter_count << "): " << width << " x " << height << endl; + + struct Entry{ + Runner runner; + char* current_row; + }; + + + FixedLimitVector entries(filter_count); + for (size_t c = 0; c < filter_count; c++){ + Filter& filter = filters[c]; + entries.emplace_back(Entry{filter, (char*)filter.data}); + } + + const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; + do{ + // Less than vector width. No need for steady-state loop. + if (width < VECTOR_SIZE){ + typename Runner::Mask mask(width); + do{ + const uint32_t* in = image; + for (size_t c = 0; c < filter_count; c++){ + entries[c].runner.process_partial((uint32_t*)entries[c].current_row, in, mask); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + entries[c].current_row += filters[c].bytes_per_row; + } + }while (--height); + break; + } + + // Divisible by vector width. No need for peel loop. + size_t left = width % VECTOR_SIZE; + if (left == 0){ + do{ + const uint32_t* in = image; + size_t shift = 0; + size_t lc = width / VECTOR_SIZE; + do{ + for (size_t c = 0; c < filter_count; c++){ + entries[c].runner.process_full((uint32_t*)entries[c].current_row + shift, in); + } + in += VECTOR_SIZE; + shift += VECTOR_SIZE; + }while (--lc); + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + entries[c].current_row += filters[c].bytes_per_row; + } + }while (--height); + break; + } + + // Need both steady-state and peel loops. + { + typename Runner::Mask mask(left); + do{ + const uint32_t* in = image; + size_t shift = 0; + size_t lc = width / VECTOR_SIZE; + do{ + for (size_t c = 0; c < filter_count; c++){ + entries[c].runner.process_full((uint32_t*)entries[c].current_row + shift, in); + } + in += VECTOR_SIZE; + shift += VECTOR_SIZE; + }while (--lc); + for (size_t c = 0; c < filter_count; c++){ + entries[c].runner.process_partial((uint32_t*)entries[c].current_row + shift, in, mask); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + entries[c].current_row += filters[c].bytes_per_row; + } + }while (--height); + break; + } + }while (false); + + for (size_t c = 0; c < filter_count; c++){ + filters[c].pixels_in_range = entries[c].runner.count(); + } +} + +#endif + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h index fcaa6ebd36..f3b363d411 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h @@ -1,154 +1,154 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels/Kernels_arm64_NEON.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -template -class FilterImage_Rgb32_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - FilterImage_Rgb32_ARM64_NEON( - const PixelTester& tester, - uint32_t replacement_color, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement_color_u32(vdupq_n_u32(replacement_color)) - , m_replace_color_within_range(replace_color_within_range) - , m_count_u32(vdupq_n_u32(0)) - {} - - PA_FORCE_INLINE size_t count() const{ - // long pairwise add - uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); - return sum_u64[0] + sum_u64[1]; - } - - // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. - // The counts are stored in m_count_u32. - // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. - // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. - // The resulting pixels are saved in out[4] - PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ - uint32x4_t pixel = vld1q_u32(in); - // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_u32 = m_tester.test_word(pixel); - if (cmp_mask_u32) { - cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); - } - // Increase count for each pixel in range. Each uint32 lane is counted separately. - // We achieve +=1 by substracting 0xFFFFFFFF - m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); - // select replacement color or in_u8 based on cmp_u32: - uint32x4_t out_u32; - if (m_replace_color_within_range){ - // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, pixel); - }else{ - out_u32 = vbslq_u32(cmp_u32, pixel, m_replacement_color_u32); - } - vst1q_u32(out, out_u32); - } - // Same as `process_full()` but only process `left` (< 4) pixels - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); - uint32_t buffer_in[4], buffer_out[4]; - memcpy(buffer_in, in, sizeof(uint32_t) * left); - process_full(buffer_out, buffer_in, &cmp_mask_u32); - memcpy(out, buffer_out, sizeof(uint32_t) * left); - } - -private: - const PixelTester m_tester; - uint32x4_t m_replacement_color_u32; - bool m_replace_color_within_range; - uint32x4_t m_count_u32; -}; - - - - - - - -template -class ToBlackWhite_Rgb32_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - ToBlackWhite_Rgb32_ARM64_NEON( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_color_u32(vdupq_n_u32(in_range_black ? 0xFF000000 : 0xFFFFFFFF)) - , m_out_of_range_color_u32(vdupq_n_u32(in_range_black ? 0xFFFFFFFF : 0xFF000000)) - , m_count_u32(vdupq_n_u32(0)) - {} - - PA_FORCE_INLINE size_t count() const{ - uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); - return sum_u64[0] + sum_u64[1]; - } - - // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. - // The counts are stored in m_count_u32. - // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. - // It also changes pixels into black or white depending on whether they are in range. - // The resulting pixels are saved in out[4] - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in, const uint32x4_t* cmp_mask_u32 = nullptr){ - uint32x4_t pixel = vld1q_u32(in); - // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_u32 = m_tester.test_word(pixel); - if (cmp_mask_u32) { - cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); - } - // Increase count for each pixel in range. Each uint32 lane is counted separately. - // We achieve +=1 by substracting 0xFFFFFFFF - m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); - // select replacement color or in_u8 based on cmp_u32: - uint32x4_t out_u32; - // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(cmp_u32, m_in_range_color_u32, m_out_of_range_color_u32); - - vst1q_u32(out, out_u32); - } - - // Same as `process_full()` but only process `left` (< 4) pixels - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); - uint32_t buffer_in[4], buffer_out[4]; - memcpy(buffer_in, in, sizeof(uint32_t) * left); - process_full(buffer_out, buffer_in, &cmp_mask_u32); - memcpy(out, buffer_out, sizeof(uint32_t) * left); - } - -private: - const PixelTester m_tester; - uint32x4_t m_in_range_color_u32; - uint32x4_t m_out_of_range_color_u32; - uint32x4_t m_count_u32; -}; - - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels/Kernels_arm64_NEON.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +template +class FilterImage_Rgb32_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + FilterImage_Rgb32_ARM64_NEON( + const PixelTester& tester, + uint32_t replacement_color, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement_color_u32(vdupq_n_u32(replacement_color)) + , m_replace_color_within_range(replace_color_within_range) + , m_count_u32(vdupq_n_u32(0)) + {} + + PA_FORCE_INLINE size_t count() const{ + // long pairwise add + uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); + return sum_u64[0] + sum_u64[1]; + } + + // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. + // The counts are stored in m_count_u32. + // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. + // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. + // The resulting pixels are saved in out[4] + PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ + uint32x4_t pixel = vld1q_u32(in); + // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_u32 = m_tester.test_word(pixel); + if (cmp_mask_u32) { + cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); + } + // Increase count for each pixel in range. Each uint32 lane is counted separately. + // We achieve +=1 by substracting 0xFFFFFFFF + m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); + // select replacement color or in_u8 based on cmp_u32: + uint32x4_t out_u32; + if (m_replace_color_within_range){ + // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, pixel); + }else{ + out_u32 = vbslq_u32(cmp_u32, pixel, m_replacement_color_u32); + } + vst1q_u32(out, out_u32); + } + // Same as `process_full()` but only process `left` (< 4) pixels + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); + uint32_t buffer_in[4], buffer_out[4]; + memcpy(buffer_in, in, sizeof(uint32_t) * left); + process_full(buffer_out, buffer_in, &cmp_mask_u32); + memcpy(out, buffer_out, sizeof(uint32_t) * left); + } + +private: + const PixelTester m_tester; + uint32x4_t m_replacement_color_u32; + bool m_replace_color_within_range; + uint32x4_t m_count_u32; +}; + + + + + + + +template +class ToBlackWhite_Rgb32_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + ToBlackWhite_Rgb32_ARM64_NEON( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_color_u32(vdupq_n_u32(in_range_black ? 0xFF000000 : 0xFFFFFFFF)) + , m_out_of_range_color_u32(vdupq_n_u32(in_range_black ? 0xFFFFFFFF : 0xFF000000)) + , m_count_u32(vdupq_n_u32(0)) + {} + + PA_FORCE_INLINE size_t count() const{ + uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); + return sum_u64[0] + sum_u64[1]; + } + + // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. + // The counts are stored in m_count_u32. + // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. + // It also changes pixels into black or white depending on whether they are in range. + // The resulting pixels are saved in out[4] + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in, const uint32x4_t* cmp_mask_u32 = nullptr){ + uint32x4_t pixel = vld1q_u32(in); + // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_u32 = m_tester.test_word(pixel); + if (cmp_mask_u32) { + cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); + } + // Increase count for each pixel in range. Each uint32 lane is counted separately. + // We achieve +=1 by substracting 0xFFFFFFFF + m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); + // select replacement color or in_u8 based on cmp_u32: + uint32x4_t out_u32; + // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(cmp_u32, m_in_range_color_u32, m_out_of_range_color_u32); + + vst1q_u32(out, out_u32); + } + + // Same as `process_full()` but only process `left` (< 4) pixels + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); + uint32_t buffer_in[4], buffer_out[4]; + memcpy(buffer_in, in, sizeof(uint32_t) * left); + process_full(buffer_out, buffer_in, &cmp_mask_u32); + memcpy(out, buffer_out, sizeof(uint32_t) * left); + } + +private: + const PixelTester m_tester; + uint32x4_t m_in_range_color_u32; + uint32x4_t m_out_of_range_color_u32; + uint32x4_t m_count_u32; +}; + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h index 94635b245c..b929df98db 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h @@ -1,102 +1,102 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -template -class FilterImage_Rgb32_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - FilterImage_Rgb32_Default( - const PixelTester& tester, - uint32_t replacement_color, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement_color(replacement_color) - , m_replace_color_within_range(replace_color_within_range) - , m_count(0) - {} - - PA_FORCE_INLINE size_t count() const{ - return m_count; - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - uint32_t pixel = in[0]; - bool passed = m_tester.test_word(pixel); - m_count += passed; - passed ^= m_replace_color_within_range; - out[0] = passed ? pixel : m_replacement_color; - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - process_full(out, in); - } - -private: - const PixelTester m_tester; - const uint32_t m_replacement_color; - const bool m_replace_color_within_range; - size_t m_count; -}; - - - - - - -template -class ToBlackWhite_Rgb32_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - ToBlackWhite_Rgb32_Default( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_black(in_range_black ? 1 : 0) - , m_count(0) - {} - - PA_FORCE_INLINE size_t count() const{ - return m_count; - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - uint32_t pixel = in[0]; - bool passed = m_tester.test_word(pixel); - m_count += passed; - passed ^= m_in_range_black; - out[0] = passed ? 0xffffffff : 0xff000000; - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - process_full(out, in); - } - -private: - const PixelTester m_tester; - const bool m_in_range_black; - size_t m_count; -}; - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +template +class FilterImage_Rgb32_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + FilterImage_Rgb32_Default( + const PixelTester& tester, + uint32_t replacement_color, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement_color(replacement_color) + , m_replace_color_within_range(replace_color_within_range) + , m_count(0) + {} + + PA_FORCE_INLINE size_t count() const{ + return m_count; + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + uint32_t pixel = in[0]; + bool passed = m_tester.test_word(pixel); + m_count += passed; + passed ^= m_replace_color_within_range; + out[0] = passed ? pixel : m_replacement_color; + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + process_full(out, in); + } + +private: + const PixelTester m_tester; + const uint32_t m_replacement_color; + const bool m_replace_color_within_range; + size_t m_count; +}; + + + + + + +template +class ToBlackWhite_Rgb32_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + ToBlackWhite_Rgb32_Default( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_black(in_range_black ? 1 : 0) + , m_count(0) + {} + + PA_FORCE_INLINE size_t count() const{ + return m_count; + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + uint32_t pixel = in[0]; + bool passed = m_tester.test_word(pixel); + m_count += passed; + passed ^= m_in_range_black; + out[0] = passed ? 0xffffffff : 0xff000000; + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + process_full(out, in); + } + +private: + const PixelTester m_tester; + const bool m_in_range_black; + size_t m_count; +}; + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h index bd20966008..b4d38f8187 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h @@ -1,132 +1,132 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -template -class FilterImage_Rgb32_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - FilterImage_Rgb32_x64_AVX2( - const PixelTester& tester, - uint32_t replacement, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement(_mm256_set1_epi32(replacement)) - , m_invert(replace_color_within_range ? _mm256_set1_epi32(-1) : _mm256_setzero_si256()) - , m_count(_mm256_setzero_si256()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce_add32_x64_AVX2(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)in); - __m256i in_range_pixels = process_word(pixel); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - _mm256_storeu_si256((__m256i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m256i pixel = mask.load_i32(in); - __m256i in_range_pixels = process_word(pixel); - in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - mask.store(out, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ - __m256i mask = m_tester.test_word(pixel); - pixel = _mm256_blendv_epi8( - m_replacement, - pixel, - _mm256_xor_si256(mask, m_invert) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m256i m_replacement; - const __m256i m_invert; - __m256i m_count; -}; - - - - -template -class ToBlackWhite_Rgb32_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - ToBlackWhite_Rgb32_x64_AVX2( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_black(_mm256_set1_epi32(in_range_black ? -1 : 0)) - , m_count(_mm256_setzero_si256()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce_add32_x64_AVX2(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m256i pixel = _mm256_loadu_si256((const __m256i*)in); - __m256i in_range_pixels = process_word(pixel); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - _mm256_storeu_si256((__m256i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m256i pixel = mask.load_i32(in); - __m256i in_range_pixels = process_word(pixel); - in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); - m_count = _mm256_sub_epi32(m_count, in_range_pixels); - mask.store(out, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ - __m256i mask = m_tester.test_word(pixel); - pixel = _mm256_or_si256( - _mm256_xor_si256(mask, m_in_range_black), - _mm256_set1_epi32(0xff000000) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m256i m_in_range_black; - __m256i m_count; -}; - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +template +class FilterImage_Rgb32_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + FilterImage_Rgb32_x64_AVX2( + const PixelTester& tester, + uint32_t replacement, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement(_mm256_set1_epi32(replacement)) + , m_invert(replace_color_within_range ? _mm256_set1_epi32(-1) : _mm256_setzero_si256()) + , m_count(_mm256_setzero_si256()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce_add32_x64_AVX2(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)in); + __m256i in_range_pixels = process_word(pixel); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + _mm256_storeu_si256((__m256i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m256i pixel = mask.load_i32(in); + __m256i in_range_pixels = process_word(pixel); + in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + mask.store(out, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ + __m256i mask = m_tester.test_word(pixel); + pixel = _mm256_blendv_epi8( + m_replacement, + pixel, + _mm256_xor_si256(mask, m_invert) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m256i m_replacement; + const __m256i m_invert; + __m256i m_count; +}; + + + + +template +class ToBlackWhite_Rgb32_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + ToBlackWhite_Rgb32_x64_AVX2( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_black(_mm256_set1_epi32(in_range_black ? -1 : 0)) + , m_count(_mm256_setzero_si256()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce_add32_x64_AVX2(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m256i pixel = _mm256_loadu_si256((const __m256i*)in); + __m256i in_range_pixels = process_word(pixel); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + _mm256_storeu_si256((__m256i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m256i pixel = mask.load_i32(in); + __m256i in_range_pixels = process_word(pixel); + in_range_pixels = _mm256_and_si256(in_range_pixels, mask.mask()); + m_count = _mm256_sub_epi32(m_count, in_range_pixels); + mask.store(out, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i process_word(__m256i& pixel) const{ + __m256i mask = m_tester.test_word(pixel); + pixel = _mm256_or_si256( + _mm256_xor_si256(mask, m_in_range_black), + _mm256_set1_epi32(0xff000000) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m256i m_in_range_black; + __m256i m_count; +}; + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h index 35071ab3c9..c43c9dbb46 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h @@ -1,147 +1,147 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" - - -namespace PokemonAutomation{ -namespace Kernels{ - - - -struct PartialWordMask{ - __mmask16 m; - - PA_FORCE_INLINE PartialWordMask(size_t left) - : m(((__mmask16)1 << left) - 1) - {} -}; - - - - -template -class FilterImage_Rgb32_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - FilterImage_Rgb32_x64_AVX512( - const PixelTester& tester, - uint32_t replacement, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement(_mm512_set1_epi32(replacement)) - , m_invert(replace_color_within_range ? 0xffff : 0) - , m_count(_mm512_setzero_si512()) - {} - - PA_FORCE_INLINE size_t count() const{ - return _mm512_reduce_add_epi32(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)in); - __mmask16 in_range_pixels = process_word(pixel); - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_storeu_si512((__m512i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); - __mmask16 in_range_pixels = process_word(pixel); - in_range_pixels &= mask.m; - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_mask_storeu_epi32(out, mask.m, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ - __mmask16 mask = m_tester.test_word(pixel); - pixel = _mm512_mask_blend_epi32( - mask ^ m_invert, - m_replacement, - pixel - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m512i m_replacement; - const __mmask16 m_invert; - __m512i m_count; -}; - - - - - -template -class ToBlackWhite_Rgb32_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - ToBlackWhite_Rgb32_x64_AVX512( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_color(_mm512_set1_epi32(in_range_black ? 0xff000000 : 0xffffffff)) - , m_out_range_color(_mm512_set1_epi32(in_range_black ? 0xffffffff : 0xff000000)) - , m_count(_mm512_setzero_si512()) - {} - - PA_FORCE_INLINE size_t count() const{ - return _mm512_reduce_add_epi32(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m512i pixel = _mm512_loadu_si512((const __m512i*)in); - __mmask16 in_range_pixels = process_word(pixel); - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_storeu_si512((__m512i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); - __mmask16 in_range_pixels = process_word(pixel); - in_range_pixels &= mask.m; - m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); - _mm512_mask_storeu_epi32(out, mask.m, pixel); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ - __mmask16 mask = m_tester.test_word(pixel); - pixel = _mm512_mask_blend_epi32( - mask, - m_out_range_color, - m_in_range_color - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m512i m_in_range_color; - const __m512i m_out_range_color; - __m512i m_count; -}; - - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" + + +namespace PokemonAutomation{ +namespace Kernels{ + + + +struct PartialWordMask{ + __mmask16 m; + + PA_FORCE_INLINE PartialWordMask(size_t left) + : m(((__mmask16)1 << left) - 1) + {} +}; + + + + +template +class FilterImage_Rgb32_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + FilterImage_Rgb32_x64_AVX512( + const PixelTester& tester, + uint32_t replacement, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement(_mm512_set1_epi32(replacement)) + , m_invert(replace_color_within_range ? 0xffff : 0) + , m_count(_mm512_setzero_si512()) + {} + + PA_FORCE_INLINE size_t count() const{ + return _mm512_reduce_add_epi32(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)in); + __mmask16 in_range_pixels = process_word(pixel); + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_storeu_si512((__m512i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); + __mmask16 in_range_pixels = process_word(pixel); + in_range_pixels &= mask.m; + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_mask_storeu_epi32(out, mask.m, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ + __mmask16 mask = m_tester.test_word(pixel); + pixel = _mm512_mask_blend_epi32( + mask ^ m_invert, + m_replacement, + pixel + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m512i m_replacement; + const __mmask16 m_invert; + __m512i m_count; +}; + + + + + +template +class ToBlackWhite_Rgb32_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + ToBlackWhite_Rgb32_x64_AVX512( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_color(_mm512_set1_epi32(in_range_black ? 0xff000000 : 0xffffffff)) + , m_out_range_color(_mm512_set1_epi32(in_range_black ? 0xffffffff : 0xff000000)) + , m_count(_mm512_setzero_si512()) + {} + + PA_FORCE_INLINE size_t count() const{ + return _mm512_reduce_add_epi32(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m512i pixel = _mm512_loadu_si512((const __m512i*)in); + __mmask16 in_range_pixels = process_word(pixel); + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_storeu_si512((__m512i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m512i pixel = _mm512_maskz_loadu_epi32(mask.m, in); + __mmask16 in_range_pixels = process_word(pixel); + in_range_pixels &= mask.m; + m_count = _mm512_mask_sub_epi32(m_count, in_range_pixels, m_count, _mm512_set1_epi32(-1)); + _mm512_mask_storeu_epi32(out, mask.m, pixel); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 process_word(__m512i& pixel) const{ + __mmask16 mask = m_tester.test_word(pixel); + pixel = _mm512_mask_blend_epi32( + mask, + m_out_range_color, + m_in_range_color + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m512i m_in_range_color; + const __m512i m_out_range_color; + __m512i m_count; +}; + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h index cef34c66ca..53fed09a76 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h @@ -1,169 +1,169 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -struct PartialWordMask{ - size_t left; - PartialWordAccess_x64_SSE41 loader; - - PA_FORCE_INLINE PartialWordMask(size_t p_left) - : left(p_left) - , loader(left * sizeof(uint32_t)) - {} -}; - - - - - -template -class FilterImage_Rgb32_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - FilterImage_Rgb32_x64_SSE42( - const PixelTester& tester, - uint32_t replacement, bool replace_color_within_range - ) - : m_tester(tester) - , m_replacement(_mm_set1_epi32(replacement)) - , m_invert(replace_color_within_range ? _mm_set1_epi32(-1) : _mm_setzero_si128()) - , m_count(_mm_setzero_si128()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce32_x64_SSE41(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m128i pixel = _mm_loadu_si128((const __m128i*)in); - __m128i in_range_pixels = process_word(pixel); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - _mm_storeu_si128((__m128i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m128i vmask = _mm_cmpgt_epi32( - _mm_set1_epi32((uint32_t)mask.left), - _mm_setr_epi32(0, 1, 2, 3) - ); - - __m128i pixel = mask.loader.load(in); - __m128i in_range_pixels = process_word(pixel); - in_range_pixels = _mm_and_si128(in_range_pixels, vmask); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - size_t left = mask.left; - do{ - out[0] = _mm_cvtsi128_si32(pixel); - pixel = _mm_srli_si128(pixel, 4); - out++; - }while(--left); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ - __m128i mask = m_tester.test_word(pixel); - pixel = _mm_blendv_epi8( - m_replacement, - pixel, - _mm_xor_si128(mask, m_invert) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m128i m_replacement; - const __m128i m_invert; - __m128i m_count; -}; - - - - - - - -template -class ToBlackWhite_Rgb32_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - ToBlackWhite_Rgb32_x64_SSE42( - const PixelTester& tester, - bool in_range_black - ) - : m_tester(tester) - , m_in_range_black(_mm_set1_epi32(in_range_black ? -1 : 0)) - , m_count(_mm_setzero_si128()) - {} - - PA_FORCE_INLINE size_t count() const{ - return reduce32_x64_SSE41(m_count); - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - __m128i pixel = _mm_loadu_si128((const __m128i*)in); - __m128i in_range_pixels = process_word(pixel); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - _mm_storeu_si128((__m128i*)out, pixel); - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ - __m128i vmask = _mm_cmpgt_epi32( - _mm_set1_epi32((uint32_t)mask.left), - _mm_setr_epi32(0, 1, 2, 3) - ); - - __m128i pixel = mask.loader.load(in); - __m128i in_range_pixels = process_word(pixel); - in_range_pixels = _mm_and_si128(in_range_pixels, vmask); - m_count = _mm_sub_epi32(m_count, in_range_pixels); - size_t left = mask.left; - do{ - out[0] = _mm_cvtsi128_si32(pixel); - pixel = _mm_srli_si128(pixel, 4); - out++; - }while(--left); - } - -private: - // Process the pixel in-place. - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ - __m128i mask = m_tester.test_word(pixel); - pixel = _mm_or_si128( - _mm_xor_si128(mask, m_in_range_black), - _mm_set1_epi32(0xff000000) - ); - return mask; - } - -private: - const PixelTester m_tester; - const __m128i m_in_range_black; - __m128i m_count; -}; - - - - -} -} +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +struct PartialWordMask{ + size_t left; + PartialWordAccess_x64_SSE41 loader; + + PA_FORCE_INLINE PartialWordMask(size_t p_left) + : left(p_left) + , loader(left * sizeof(uint32_t)) + {} +}; + + + + + +template +class FilterImage_Rgb32_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + FilterImage_Rgb32_x64_SSE42( + const PixelTester& tester, + uint32_t replacement, bool replace_color_within_range + ) + : m_tester(tester) + , m_replacement(_mm_set1_epi32(replacement)) + , m_invert(replace_color_within_range ? _mm_set1_epi32(-1) : _mm_setzero_si128()) + , m_count(_mm_setzero_si128()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce32_x64_SSE41(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m128i pixel = _mm_loadu_si128((const __m128i*)in); + __m128i in_range_pixels = process_word(pixel); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + _mm_storeu_si128((__m128i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m128i vmask = _mm_cmpgt_epi32( + _mm_set1_epi32((uint32_t)mask.left), + _mm_setr_epi32(0, 1, 2, 3) + ); + + __m128i pixel = mask.loader.load(in); + __m128i in_range_pixels = process_word(pixel); + in_range_pixels = _mm_and_si128(in_range_pixels, vmask); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + size_t left = mask.left; + do{ + out[0] = _mm_cvtsi128_si32(pixel); + pixel = _mm_srli_si128(pixel, 4); + out++; + }while(--left); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ + __m128i mask = m_tester.test_word(pixel); + pixel = _mm_blendv_epi8( + m_replacement, + pixel, + _mm_xor_si128(mask, m_invert) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m128i m_replacement; + const __m128i m_invert; + __m128i m_count; +}; + + + + + + + +template +class ToBlackWhite_Rgb32_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + ToBlackWhite_Rgb32_x64_SSE42( + const PixelTester& tester, + bool in_range_black + ) + : m_tester(tester) + , m_in_range_black(_mm_set1_epi32(in_range_black ? -1 : 0)) + , m_count(_mm_setzero_si128()) + {} + + PA_FORCE_INLINE size_t count() const{ + return reduce32_x64_SSE41(m_count); + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + __m128i pixel = _mm_loadu_si128((const __m128i*)in); + __m128i in_range_pixels = process_word(pixel); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + _mm_storeu_si128((__m128i*)out, pixel); + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, const Mask& mask){ + __m128i vmask = _mm_cmpgt_epi32( + _mm_set1_epi32((uint32_t)mask.left), + _mm_setr_epi32(0, 1, 2, 3) + ); + + __m128i pixel = mask.loader.load(in); + __m128i in_range_pixels = process_word(pixel); + in_range_pixels = _mm_and_si128(in_range_pixels, vmask); + m_count = _mm_sub_epi32(m_count, in_range_pixels); + size_t left = mask.left; + do{ + out[0] = _mm_cvtsi128_si32(pixel); + pixel = _mm_srli_si128(pixel, 4); + out++; + }while(--left); + } + +private: + // Process the pixel in-place. + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i process_word(__m128i& pixel) const{ + __m128i mask = m_tester.test_word(pixel); + pixel = _mm_or_si128( + _mm_xor_si128(mask, m_in_range_black), + _mm_set1_epi32(0xff000000) + ); + return mask; + } + +private: + const PixelTester m_tester; + const __m128i m_in_range_black; + __m128i m_count; +}; + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp index 8b32317086..53f019f05e 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX2.cpp @@ -1,37 +1,37 @@ -/* Image Filters Basic (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include -#include -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels_ImageFilter_Basic_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters Basic (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include +#include +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels_ImageFilter_Basic_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp index f8013cfef6..bc9da11c10 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_AVX512.cpp @@ -1,58 +1,58 @@ -/* Image Filters Basic (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include -#include -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_ImageFilter_Basic_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -#if 0 - -namespace{ - -struct PartialWordMask{ - __mmask16 m; - - PA_FORCE_INLINE PartialWordMask(size_t left) - : m(((__mmask16)1 << left) - 1) - {} -}; - -} - -#endif - - - - - - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters Basic (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include +#include +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_ImageFilter_Basic_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +#if 0 + +namespace{ + +struct PartialWordMask{ + __mmask16 m; + + PA_FORCE_INLINE PartialWordMask(size_t left) + : m(((__mmask16)1 << left) - 1) + {} +}; + +} + +#endif + + + + + + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp index 210056de55..9411d1fa00 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Basic_x64_SSE42.cpp @@ -1,51 +1,51 @@ -/* Image Filters Basic (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include -#include -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels_ImageFilter_Basic_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -#if 0 - -struct PartialWordMask{ - size_t left; - PartialWordAccess_x64_SSE41 loader; - - PA_FORCE_INLINE PartialWordMask(size_t p_left) - : left(p_left) - , loader(left * sizeof(uint32_t)) - {} -}; - -#endif - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters Basic (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include +#include +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels_ImageFilter_Basic_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +#if 0 + +struct PartialWordMask{ + size_t left; + PartialWordAccess_x64_SSE41 loader; + + PA_FORCE_INLINE PartialWordMask(size_t p_left) + : left(p_left) + , loader(left * sizeof(uint32_t)) + {} +}; + +#endif + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp index ce6050377a..0bc498510d 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/Kernels_ImageFilter_Green_Default.cpp @@ -1,91 +1,91 @@ -/* Image Filters Basic (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Kernels_ImageFilter_Basic_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -class ImageFilter_Green_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - ImageFilter_Green_Default(uint32_t replacement_color, uint8_t rgb_gap) - : m_replacement_color(replacement_color) - , m_rgb_gap(rgb_gap) - , m_count(0) - {} - - PA_FORCE_INLINE size_t count() const{ - return m_count; - } - - PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ - uint32_t pixel = in[0]; - uint64_t ret = 1; - - uint16_t red = ((pixel >> 16) & 0xff); - uint16_t green = ((pixel >> 8) & 0xff); - uint16_t blue = ((pixel) & 0xff); - - ret &= (green >= red + m_rgb_gap) && (green >= blue + m_rgb_gap); - - - m_count += ret; - out[0] = ret ? pixel : m_replacement_color; - } - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - process_full(out, in); - } - -private: - const uint32_t m_replacement_color; - const uint16_t m_rgb_gap; - size_t m_count; -}; - - -size_t filter_green_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement_color, uint8_t rgb_gap -){ - ImageFilter_Green_Default filter(replacement_color, rgb_gap); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Image Filters Basic (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Kernels_ImageFilter_Basic_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +class ImageFilter_Green_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + ImageFilter_Green_Default(uint32_t replacement_color, uint8_t rgb_gap) + : m_replacement_color(replacement_color) + , m_rgb_gap(rgb_gap) + , m_count(0) + {} + + PA_FORCE_INLINE size_t count() const{ + return m_count; + } + + PA_FORCE_INLINE void process_full(uint32_t* out, const uint32_t* in){ + uint32_t pixel = in[0]; + uint64_t ret = 1; + + uint16_t red = ((pixel >> 16) & 0xff); + uint16_t green = ((pixel >> 8) & 0xff); + uint16_t blue = ((pixel) & 0xff); + + ret &= (green >= red + m_rgb_gap) && (green >= blue + m_rgb_gap); + + + m_count += ret; + out[0] = ret ? pixel : m_replacement_color; + } + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + process_full(out, in); + } + +private: + const uint32_t m_replacement_color; + const uint16_t m_rgb_gap; + size_t m_count; +}; + + +size_t filter_green_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement_color, uint8_t rgb_gap +){ + ImageFilter_Green_Default filter(replacement_color, rgb_gap); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp index a26aac47bc..6b56f3bfd1 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.cpp @@ -1,174 +1,174 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -size_t filter_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t filter_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_19_IceLake - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return filter_rgb32_brightness_x64_AVX512VNNI( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return filter_rgb32_brightness_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return filter_rgb32_brightness_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); - } -#endif - return filter_rgb32_brightness_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - weights, min_brightness, max_brightness - ); -} - - - -size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); -size_t to_blackwhite_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_19_IceLake - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return to_blackwhite_rgb32_brightness_x64_AVX512VNNI( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return to_blackwhite_rgb32_brightness_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return to_blackwhite_rgb32_brightness_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); - } -#endif - return to_blackwhite_rgb32_brightness_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - weights, min_brightness, max_brightness - ); -} - - - - -} -} +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +size_t filter_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t filter_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_19_IceLake + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return filter_rgb32_brightness_x64_AVX512VNNI( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return filter_rgb32_brightness_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return filter_rgb32_brightness_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); + } +#endif + return filter_rgb32_brightness_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + weights, min_brightness, max_brightness + ); +} + + + +size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); +size_t to_blackwhite_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_19_IceLake + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return to_blackwhite_rgb32_brightness_x64_AVX512VNNI( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return to_blackwhite_rgb32_brightness_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return to_blackwhite_rgb32_brightness_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); + } +#endif + return to_blackwhite_rgb32_brightness_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + weights, min_brightness, max_brightness + ); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h index 46eb9fd967..7aa89cca1d 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness.h @@ -1,70 +1,70 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H - -#include -#include -#include "Common/Cpp/PixelRGB32.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -union Rgb32BrightnessWeights{ - struct{ - int8_t blue; - int8_t green; - int8_t red; - int8_t alpha; - } parts; - uint32_t u32; - - Rgb32BrightnessWeights(uint32_t value) - : u32(value) - {} - Rgb32BrightnessWeights(uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = 0; - parts.red = red; - parts.green = green; - parts.blue = blue; - } - Rgb32BrightnessWeights(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ - parts.alpha = alpha; - parts.red = red; - parts.green = green; - parts.blue = blue; - } -}; - - - -size_t filter_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); - -size_t to_blackwhite_rgb32_brightness( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -); - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Brightness_H + +#include +#include +#include "Common/Cpp/PixelRGB32.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +union Rgb32BrightnessWeights{ + struct{ + int8_t blue; + int8_t green; + int8_t red; + int8_t alpha; + } parts; + uint32_t u32; + + Rgb32BrightnessWeights(uint32_t value) + : u32(value) + {} + Rgb32BrightnessWeights(uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = 0; + parts.red = red; + parts.green = green; + parts.blue = blue; + } + Rgb32BrightnessWeights(uint8_t alpha, uint8_t red, uint8_t green, uint8_t blue){ + parts.alpha = alpha; + parts.red = red; + parts.green = green; + parts.blue = blue; + } +}; + + + +size_t filter_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); + +size_t to_blackwhite_rgb32_brightness( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp index 24ea06a05f..70e9cb3d41 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_Default.cpp @@ -1,94 +1,94 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -class PixelTest_Rgb32Brightness_Default{ -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_Default( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weight_a(weights.parts.alpha) - , m_weight_r(weights.parts.red) - , m_weight_g(weights.parts.green) - , m_weight_b(weights.parts.blue) - , m_shift(min_sum) - , m_threshold(max_sum - min_sum) - {} - PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ - uint32_t brightness = 0; - brightness += ((pixel >> 24) & 0x000000ff) * m_weight_a; - brightness += ((pixel >> 16) & 0x000000ff) * m_weight_r; - brightness += ((pixel >> 8) & 0x000000ff) * m_weight_g; - brightness += ((pixel >> 0) & 0x000000ff) * m_weight_b; - return brightness - m_shift <= m_threshold; - } - -private: - int32_t m_weight_a; - int32_t m_weight_r; - int32_t m_weight_g; - int32_t m_weight_b; - uint32_t m_shift; - uint32_t m_threshold; -}; - - - - - - - -size_t filter_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_Default tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_Default filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_Default tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_Default filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +class PixelTest_Rgb32Brightness_Default{ +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_Default( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weight_a(weights.parts.alpha) + , m_weight_r(weights.parts.red) + , m_weight_g(weights.parts.green) + , m_weight_b(weights.parts.blue) + , m_shift(min_sum) + , m_threshold(max_sum - min_sum) + {} + PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ + uint32_t brightness = 0; + brightness += ((pixel >> 24) & 0x000000ff) * m_weight_a; + brightness += ((pixel >> 16) & 0x000000ff) * m_weight_r; + brightness += ((pixel >> 8) & 0x000000ff) * m_weight_g; + brightness += ((pixel >> 0) & 0x000000ff) * m_weight_b; + return brightness - m_shift <= m_threshold; + } + +private: + int32_t m_weight_a; + int32_t m_weight_r; + int32_t m_weight_g; + int32_t m_weight_b; + uint32_t m_shift; + uint32_t m_threshold; +}; + + + + + + + +size_t filter_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_Default tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_Default filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_Default tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_Default filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp index 9723c610ba..e04b35be3e 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX2.cpp @@ -1,107 +1,107 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Brightness_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX2( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weightsL(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) - , m_weightsH(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) - , m_min(_mm256_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) - , m_max(_mm256_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ - __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); - __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x00ff00ff)); - - rb = _mm256_madd_epi16(rb, m_weightsL); - ag = _mm256_madd_epi16(ag, m_weightsH); - pixel = _mm256_add_epi32(rb, ag); - - __m256i cmp0 = _mm256_cmpgt_epi32(pixel, m_min); - __m256i cmp1 = _mm256_cmpgt_epi32(m_max, pixel); - return _mm256_and_si256(cmp0, cmp1); - } - -private: - const __m256i m_weightsL; - const __m256i m_weightsH; - const __m256i m_min; - const __m256i m_max; -}; - - - - -size_t filter_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX2 tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_x64_AVX2 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX2 tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_x64_AVX2 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Brightness_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX2( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weightsL(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) + , m_weightsH(_mm256_srai_epi16(_mm256_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) + , m_min(_mm256_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) + , m_max(_mm256_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ + __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); + __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x00ff00ff)); + + rb = _mm256_madd_epi16(rb, m_weightsL); + ag = _mm256_madd_epi16(ag, m_weightsH); + pixel = _mm256_add_epi32(rb, ag); + + __m256i cmp0 = _mm256_cmpgt_epi32(pixel, m_min); + __m256i cmp1 = _mm256_cmpgt_epi32(m_max, pixel); + return _mm256_and_si256(cmp0, cmp1); + } + +private: + const __m256i m_weightsL; + const __m256i m_weightsH; + const __m256i m_min; + const __m256i m_max; +}; + + + + +size_t filter_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX2 tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_x64_AVX2 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX2 tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_x64_AVX2 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp index c225c6391e..5aca808826 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_AVX512-VNNI.cpp @@ -1,110 +1,110 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_19_IceLake - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Brightness_x64_AVX512VNNI{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX512VNNI( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weights(_mm512_set1_epi32(weights.u32)) - , m_shift(_mm512_set1_epi32(-min_sum)) - , m_threshold(_mm512_set1_epi32(max_sum - min_sum)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ - pixel = _mm512_dpbusd_epi32(m_shift, pixel, m_weights); - return _mm512_cmple_epu32_mask(pixel, m_threshold); - } - -private: - const __m512i m_weights; - const __m512i m_shift; - const __m512i m_threshold; -}; - - - - - -size_t filter_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_x64_AVX512 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_x64_AVX512 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_19_IceLake + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Brightness_x64_AVX512VNNI{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_AVX512VNNI( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weights(_mm512_set1_epi32(weights.u32)) + , m_shift(_mm512_set1_epi32(-min_sum)) + , m_threshold(_mm512_set1_epi32(max_sum - min_sum)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ + pixel = _mm512_dpbusd_epi32(m_shift, pixel, m_weights); + return _mm512_cmple_epu32_mask(pixel, m_threshold); + } + +private: + const __m512i m_weights; + const __m512i m_shift; + const __m512i m_threshold; +}; + + + + + +size_t filter_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_x64_AVX512 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_x64_AVX512VNNI( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_AVX512VNNI tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_x64_AVX512 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp index fb31879dfa..1f653a5d0f 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Brightness/Kernels_ImageFilter_RGB32_Brightness_x64_SSE42.cpp @@ -1,107 +1,107 @@ -/* Image Filters RGB32 Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" -#include "Kernels_ImageFilter_RGB32_Brightness.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Brightness_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_SSE42( - Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum - ) - : m_weightsL(_mm_srai_epi16(_mm_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) - , m_weightsH(_mm_srai_epi16(_mm_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) - , m_min(_mm_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) - , m_max(_mm_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ - __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); - __m128i ag = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x00ff00ff)); - - rb = _mm_madd_epi16(rb, m_weightsL); - ag = _mm_madd_epi16(ag, m_weightsH); - pixel = _mm_add_epi32(rb, ag); - - __m128i cmp0 = _mm_cmpgt_epi32(pixel, m_min); - __m128i cmp1 = _mm_cmpgt_epi32(m_max, pixel); - return _mm_and_si128(cmp0, cmp1); - } - -private: - const __m128i m_weightsL; - const __m128i m_weightsH; - const __m128i m_min; - const __m128i m_max; -}; - - - - -size_t filter_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_SSE42 tester( - weights, - min_brightness, max_brightness - ); - FilterImage_Rgb32_x64_SSE42 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_brightness_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - Rgb32BrightnessWeights weights, - uint32_t min_brightness, uint32_t max_brightness -){ - PixelTest_Rgb32Brightness_x64_SSE42 tester( - weights, - min_brightness, max_brightness - ); - ToBlackWhite_Rgb32_x64_SSE42 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" +#include "Kernels_ImageFilter_RGB32_Brightness.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Brightness_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Brightness_x64_SSE42( + Rgb32BrightnessWeights weights, int32_t min_sum, int32_t max_sum + ) + : m_weightsL(_mm_srai_epi16(_mm_set1_epi32((weights.u32 << 8) & 0xff00ff00), 8)) + , m_weightsH(_mm_srai_epi16(_mm_set1_epi32((weights.u32 ) & 0xff00ff00), 8)) + , m_min(_mm_set1_epi32(min_sum == std::numeric_limits::min() ? min_sum : min_sum - 1)) + , m_max(_mm_set1_epi32(max_sum == std::numeric_limits::max() ? max_sum : max_sum + 1)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ + __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); + __m128i ag = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x00ff00ff)); + + rb = _mm_madd_epi16(rb, m_weightsL); + ag = _mm_madd_epi16(ag, m_weightsH); + pixel = _mm_add_epi32(rb, ag); + + __m128i cmp0 = _mm_cmpgt_epi32(pixel, m_min); + __m128i cmp1 = _mm_cmpgt_epi32(m_max, pixel); + return _mm_and_si128(cmp0, cmp1); + } + +private: + const __m128i m_weightsL; + const __m128i m_weightsH; + const __m128i m_min; + const __m128i m_max; +}; + + + + +size_t filter_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_SSE42 tester( + weights, + min_brightness, max_brightness + ); + FilterImage_Rgb32_x64_SSE42 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_brightness_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + Rgb32BrightnessWeights weights, + uint32_t min_brightness, uint32_t max_brightness +){ + PixelTest_Rgb32Brightness_x64_SSE42 tester( + weights, + min_brightness, max_brightness + ); + ToBlackWhite_Rgb32_x64_SSE42 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp index 6fe7d5c0ea..0f54d9b325 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.cpp @@ -1,109 +1,109 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -size_t filter_rgb32_euclidean_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean_ARM64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); -size_t filter_rgb32_euclidean( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return filter_rgb32_euclidean_x64_AVX512( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return filter_rgb32_euclidean_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return filter_rgb32_euclidean_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return filter_rgb32_euclidean_ARM64_NEON( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - } -#endif - return filter_rgb32_euclidean_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); -} - - - - - - - -} -} +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +size_t filter_rgb32_euclidean_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean_ARM64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); +size_t filter_rgb32_euclidean( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return filter_rgb32_euclidean_x64_AVX512( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return filter_rgb32_euclidean_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return filter_rgb32_euclidean_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return filter_rgb32_euclidean_ARM64_NEON( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + } +#endif + return filter_rgb32_euclidean_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h index 91125a15a9..284278ddbc 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h @@ -1,32 +1,32 @@ -/* Image Filters RGB32 Euclidean Distance - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - - -size_t filter_rgb32_euclidean( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -); - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean Distance + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Euclidean_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + + +size_t filter_rgb32_euclidean( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp index c29bd73d32..ccd1f887c2 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_ARM64_NEON.cpp @@ -1,204 +1,204 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include "Kernels/Kernels_arm64_NEON.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Euclidean_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_ARM64_NEON( - uint32_t expected_color, double max_euclidean_distance - ) - : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) - , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ - uint32x4_t& in_u32 = pixel; - // subtract the expected values - uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); - - // Get green channel - uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); - // Move green channel to the lower end of the 16-bit regions - uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); - // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region - uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); - - // Square operation - uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); - uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); - - uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); - // Use pairwise addition and accumulate to add r2, g2, and b2 together - uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); - - // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - return vcleq_u32(sum_sqr_u32, m_distance_squared_u32); - } - -private: - uint8x16_t m_expected_color_rgb_u8; - uint32x4_t m_distance_squared_u32; -}; - - - -size_t filter_rgb32_euclidean_ARM64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_ARM64_NEON tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_ARM64_NEON filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_ARM64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_ARM64_NEON tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_ARM64_NEON filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - -#if 0 - -class ImageFilter_RgbEuclidean_arm64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - ImageFilter_RgbEuclidean_arm64_NEON( - uint32_t replacement_color, bool replace_color_within_range, - uint32_t expected_color, double max_euclidean_distance - ) - : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) - , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - , m_replacement_color_u32(vdupq_n_u32(replacement_color)) - , m_replace_color_within_range(replace_color_within_range) - , m_count_u32(vdupq_n_u32(0)) - {} - - PA_FORCE_INLINE size_t count() const{ - uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); - return sum_u64[0] + sum_u64[1]; - } - - // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. - // The counts are stored in m_count_u32. - // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. - // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. - // The resulting pixels are saved in out[4] - PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ - uint32x4_t in_u32 = vld1q_u32(in); - // subtract the expected values - uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); - - // Get green channel - uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); - // Move green channel to the lower end of the 16-bit regions - uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); - // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region - uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); - - // Square operation - uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); - uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); - - uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); - // Use pairwise addition and accumulate to add r2, g2, and b2 together - uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); - - // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - uint32x4_t cmp_u32 = vcleq_u32(sum_sqr_u32, m_distance_squared_u32); - if (cmp_mask_u32) { - cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); - } - // Increase count for each pixel in range. Each uint32 lane is counted separately. - // We achieve +=1 by subtracting 0xFFFFFFFF - m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); - // select replacement color or in_u8 based on cmp_u32: - uint32x4_t out_u32; - if (m_replace_color_within_range){ - // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c - out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, in_u32); - }else{ - out_u32 = vbslq_u32(cmp_u32, in_u32, m_replacement_color_u32); - } - vst1q_u32(out, out_u32); - } - // Same as `process_full()` but only process `left` (< 4) pixels - PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ - uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); - uint32_t buffer_in[4], buffer_out[4]; - memcpy(buffer_in, in, sizeof(uint32_t) * left); - process_full(buffer_out, buffer_in, &cmp_mask_u32); - memcpy(out, buffer_out, sizeof(uint32_t) * left); - } - -private: - uint8x16_t m_expected_color_rgb_u8; - uint32x4_t m_distance_squared_u32; - uint32x4_t m_replacement_color_u32; - bool m_replace_color_within_range; - uint32x4_t m_count_u32; - -private: - -}; -size_t filter_rgb32_euclidean_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - ImageFilter_RgbEuclidean_arm64_NEON filter( - replacement, replace_color_within_range, - expected, max_euclidean_distance - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -#endif - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include "Kernels/Kernels_arm64_NEON.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Euclidean_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_ARM64_NEON( + uint32_t expected_color, double max_euclidean_distance + ) + : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) + , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ + uint32x4_t& in_u32 = pixel; + // subtract the expected values + uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); + + // Get green channel + uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); + // Move green channel to the lower end of the 16-bit regions + uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); + // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region + uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); + + // Square operation + uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); + uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); + + uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); + // Use pairwise addition and accumulate to add r2, g2, and b2 together + uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); + + // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + return vcleq_u32(sum_sqr_u32, m_distance_squared_u32); + } + +private: + uint8x16_t m_expected_color_rgb_u8; + uint32x4_t m_distance_squared_u32; +}; + + + +size_t filter_rgb32_euclidean_ARM64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_ARM64_NEON tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_ARM64_NEON filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_ARM64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_ARM64_NEON tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_ARM64_NEON filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + +#if 0 + +class ImageFilter_RgbEuclidean_arm64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + ImageFilter_RgbEuclidean_arm64_NEON( + uint32_t replacement_color, bool replace_color_within_range, + uint32_t expected_color, double max_euclidean_distance + ) + : m_expected_color_rgb_u8(vreinterpretq_u8_u32(vdupq_n_u32(expected_color & 0x00ffffff))) + , m_distance_squared_u32(vdupq_n_u32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + , m_replacement_color_u32(vdupq_n_u32(replacement_color)) + , m_replace_color_within_range(replace_color_within_range) + , m_count_u32(vdupq_n_u32(0)) + {} + + PA_FORCE_INLINE size_t count() const{ + uint64x2_t sum_u64 = vpaddlq_u32(m_count_u32); + return sum_u64[0] + sum_u64[1]; + } + + // Given 4 pixels from in[4], apply color range comparison and count the pixels that are in range. + // The counts are stored in m_count_u32. + // If a per-pixel mask, cmp_mask_u32 is not nullptr, it only counts the pixels covered by the mask. + // It also changes pixels in or out of the range to have the new color m_replacement_color_u32. + // The resulting pixels are saved in out[4] + PA_FORCE_INLINE void process_full(uint32_t out[4], const uint32_t in[4], const uint32x4_t* cmp_mask_u32 = nullptr){ + uint32x4_t in_u32 = vld1q_u32(in); + // subtract the expected values + uint32x4_t in_dif_u32 = vreinterpretq_u32_u8(vabdq_u8(vreinterpretq_u8_u32(in_u32), m_expected_color_rgb_u8)); + + // Get green channel + uint32x4_t in_g_u32 = vandq_u32(in_dif_u32, vdupq_n_u32(0x0000ff00)); + // Move green channel to the lower end of the 16-bit regions + uint16x8_t in_g_u16 = vshrq_n_u16(vreinterpretq_u16_u32(in_g_u32), 8); + // in_rb_u16 contains the red and blue channels. Each channel occupies a 16-bit region + uint16x8_t in_rb_u16 = vandq_u16(vreinterpretq_u16_u32(in_dif_u32), vdupq_n_u16(0x00ff)); + + // Square operation + uint16x8_t in_g2_u16 = vmulq_u16(in_g_u16, in_g_u16); + uint16x8_t in_r2b2_u16 = vmulq_u16(in_rb_u16, in_rb_u16); + + uint32x4_t in_g2_u32 = vreinterpretq_u32_u16(in_g2_u16); + // Use pairwise addition and accumulate to add r2, g2, and b2 together + uint32x4_t sum_sqr_u32 = vpadalq_u16(in_g2_u32, in_r2b2_u16); + + // cmp_u32: if each pixel is within the range, its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + uint32x4_t cmp_u32 = vcleq_u32(sum_sqr_u32, m_distance_squared_u32); + if (cmp_mask_u32) { + cmp_u32 = vandq_u32(cmp_u32, *cmp_mask_u32); + } + // Increase count for each pixel in range. Each uint32 lane is counted separately. + // We achieve +=1 by subtracting 0xFFFFFFFF + m_count_u32 = vsubq_u32(m_count_u32, cmp_u32); + // select replacement color or in_u8 based on cmp_u32: + uint32x4_t out_u32; + if (m_replace_color_within_range){ + // vbslq_u32(a, b, c) for 1 bits in a, choose b; for 0 bits in a, choose c + out_u32 = vbslq_u32(cmp_u32, m_replacement_color_u32, in_u32); + }else{ + out_u32 = vbslq_u32(cmp_u32, in_u32, m_replacement_color_u32); + } + vst1q_u32(out, out_u32); + } + // Same as `process_full()` but only process `left` (< 4) pixels + PA_FORCE_INLINE void process_partial(uint32_t* out, const uint32_t* in, size_t left){ + uint32x4_t cmp_mask_u32 = vreinterpretq_u32_u8(PartialWordAccess_arm64_NEON::create_front_mask(left * 4)); + uint32_t buffer_in[4], buffer_out[4]; + memcpy(buffer_in, in, sizeof(uint32_t) * left); + process_full(buffer_out, buffer_in, &cmp_mask_u32); + memcpy(out, buffer_out, sizeof(uint32_t) * left); + } + +private: + uint8x16_t m_expected_color_rgb_u8; + uint32x4_t m_distance_squared_u32; + uint32x4_t m_replacement_color_u32; + bool m_replace_color_within_range; + uint32x4_t m_count_u32; + +private: + +}; +size_t filter_rgb32_euclidean_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + ImageFilter_RgbEuclidean_arm64_NEON filter( + replacement, replace_color_within_range, + expected, max_euclidean_distance + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +#endif + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp index cbfb1504d1..11fc35691b 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_Default.cpp @@ -1,100 +1,100 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Euclidean_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_Default( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_r((expected & 0x00ff0000) >> 16) - , m_expected_g((expected & 0x0000ff00) >> 8) - , m_expected_b(expected & 0x000000ff) - , m_max_distance_squared((uint32_t)(max_euclidean_distance * max_euclidean_distance)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ - uint32_t sum_sqr = 0; - { - uint32_t p = (pixel & 0x00ff0000) >> 16; - p -= m_expected_r; - sum_sqr += p * p; - } - { - uint32_t p = (pixel & 0x0000ff00) >> 8; - p -= m_expected_g; - sum_sqr += p * p; - } - { - uint32_t p = pixel & 0x000000ff; - p -= m_expected_b; - sum_sqr += p * p; - } - return sum_sqr <= m_max_distance_squared; - } - -private: - uint32_t m_expected_r; - uint32_t m_expected_g; - uint32_t m_expected_b; - uint32_t m_max_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_Default tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_Default filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_Default tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_Default filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - -} -} +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Euclidean_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_Default( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_r((expected & 0x00ff0000) >> 16) + , m_expected_g((expected & 0x0000ff00) >> 8) + , m_expected_b(expected & 0x000000ff) + , m_max_distance_squared((uint32_t)(max_euclidean_distance * max_euclidean_distance)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ + uint32_t sum_sqr = 0; + { + uint32_t p = (pixel & 0x00ff0000) >> 16; + p -= m_expected_r; + sum_sqr += p * p; + } + { + uint32_t p = (pixel & 0x0000ff00) >> 8; + p -= m_expected_g; + sum_sqr += p * p; + } + { + uint32_t p = pixel & 0x000000ff; + p -= m_expected_b; + sum_sqr += p * p; + } + return sum_sqr <= m_max_distance_squared; + } + +private: + uint32_t m_expected_r; + uint32_t m_expected_g; + uint32_t m_expected_b; + uint32_t m_max_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_Default tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_Default filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_Default tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_Default filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp index dbf9de431f..ea4833d072 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX2.cpp @@ -1,97 +1,97 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Euclidean_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX2( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_ag(_mm256_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm256_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm256_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ - __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x000000ff)); - __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); - - ag = _mm256_sub_epi16(ag, m_expected_ag); - rb = _mm256_sub_epi16(rb, m_expected_rb); - - __m256i g = _mm256_mullo_epi16(ag, ag); - rb = _mm256_mullo_epi16(rb, rb); - __m256i r = _mm256_srli_epi32(rb, 16); - __m256i b = _mm256_and_si256(rb, _mm256_set1_epi32(0x0000ffff)); - - __m256i sum_sqr = _mm256_add_epi32(r, g); - sum_sqr = _mm256_add_epi32(sum_sqr, b); - - return _mm256_cmpgt_epi32(m_distance_squared, sum_sqr); - } - -private: - const __m256i m_expected_ag; - const __m256i m_expected_rb; - const __m256i m_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX2 tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_x64_AVX2 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX2 tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_x64_AVX2 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Euclidean_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX2( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_ag(_mm256_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm256_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm256_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ + __m256i ag = _mm256_and_si256(_mm256_srli_epi16(pixel, 8), _mm256_set1_epi32(0x000000ff)); + __m256i rb = _mm256_and_si256(pixel, _mm256_set1_epi32(0x00ff00ff)); + + ag = _mm256_sub_epi16(ag, m_expected_ag); + rb = _mm256_sub_epi16(rb, m_expected_rb); + + __m256i g = _mm256_mullo_epi16(ag, ag); + rb = _mm256_mullo_epi16(rb, rb); + __m256i r = _mm256_srli_epi32(rb, 16); + __m256i b = _mm256_and_si256(rb, _mm256_set1_epi32(0x0000ffff)); + + __m256i sum_sqr = _mm256_add_epi32(r, g); + sum_sqr = _mm256_add_epi32(sum_sqr, b); + + return _mm256_cmpgt_epi32(m_distance_squared, sum_sqr); + } + +private: + const __m256i m_expected_ag; + const __m256i m_expected_rb; + const __m256i m_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX2 tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_x64_AVX2 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX2 tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_x64_AVX2 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp index fcca03a2d4..1e7be0e457 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_AVX512.cpp @@ -1,97 +1,97 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Euclidean_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX512( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_ag(_mm512_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm512_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm512_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ - __m512i ag = _mm512_and_si512(_mm512_srli_epi16(pixel, 8), _mm512_set1_epi32(0x000000ff)); - __m512i rb = _mm512_and_si512(pixel, _mm512_set1_epi32(0x00ff00ff)); - - ag = _mm512_sub_epi16(ag, m_expected_ag); - rb = _mm512_sub_epi16(rb, m_expected_rb); - - __m512i g = _mm512_mullo_epi16(ag, ag); - rb = _mm512_mullo_epi16(rb, rb); - __m512i r = _mm512_srli_epi32(rb, 16); - __m512i b = _mm512_and_si512(rb, _mm512_set1_epi32(0x0000ffff)); - - __m512i sum_sqr = _mm512_add_epi32(r, g); - sum_sqr = _mm512_add_epi32(sum_sqr, b); - - return _mm512_cmpgt_epi32_mask(m_distance_squared, sum_sqr); - } - -private: - const __m512i m_expected_ag; - const __m512i m_expected_rb; - const __m512i m_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX512 tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_x64_AVX512 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_AVX512 tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_x64_AVX512 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Euclidean_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_AVX512( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_ag(_mm512_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm512_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm512_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ + __m512i ag = _mm512_and_si512(_mm512_srli_epi16(pixel, 8), _mm512_set1_epi32(0x000000ff)); + __m512i rb = _mm512_and_si512(pixel, _mm512_set1_epi32(0x00ff00ff)); + + ag = _mm512_sub_epi16(ag, m_expected_ag); + rb = _mm512_sub_epi16(rb, m_expected_rb); + + __m512i g = _mm512_mullo_epi16(ag, ag); + rb = _mm512_mullo_epi16(rb, rb); + __m512i r = _mm512_srli_epi32(rb, 16); + __m512i b = _mm512_and_si512(rb, _mm512_set1_epi32(0x0000ffff)); + + __m512i sum_sqr = _mm512_add_epi32(r, g); + sum_sqr = _mm512_add_epi32(sum_sqr, b); + + return _mm512_cmpgt_epi32_mask(m_distance_squared, sum_sqr); + } + +private: + const __m512i m_expected_ag; + const __m512i m_expected_rb; + const __m512i m_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX512 tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_x64_AVX512 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_AVX512 tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_x64_AVX512 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp index 447575ed81..cc238db2e9 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean_x64_SSE42.cpp @@ -1,114 +1,114 @@ -/* Image Filters RGB32 Euclidean - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" -#include "Kernels_ImageFilter_RGB32_Euclidean.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Euclidean_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_SSE42( - uint32_t expected, double max_euclidean_distance - ) - : m_expected_g(_mm_set1_epi32((expected >> 8) & 0x000000ff)) - , m_expected_rb(_mm_set1_epi32(expected & 0x00ff00ff)) - , m_distance_squared(_mm_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ - // _mm_srli_epi16: Shift 16-bit integers in pixels right by 8 while shifting in zeros, - // ng: green channels of each pixel, but shifted right by 8 bits - __m128i ng = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x000000ff)); - // rb: the red and blue channels of each pixel - __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); - // g: the difference between input pixel channels and the expected values - ng = _mm_sub_epi16(ng, m_expected_g); - rb = _mm_sub_epi16(rb, m_expected_rb); - // compute square operation: - // now each 16-bit region is a squared channel difference - // here we assume alpha channel from input image is the same as the expected, - // so the alpha channel difference is always 0, therefore: - // g: each 32-bit integer contains the green channel squared difference - __m128i g = _mm_mullo_epi16(ng, ng); - rb = _mm_mullo_epi16(rb, rb); - // r: each 32-bit integer contains the red channel squared difference - __m128i r = _mm_srli_epi32(rb, 16); - // b: each 32-bit integer contains the blue channel squared difference - __m128i b = _mm_and_si128(rb, _mm_set1_epi32(0x0000ffff)); - // compute r^2 + g^2 + b^2 - __m128i sum_sqr = _mm_add_epi32(r, g); - sum_sqr = _mm_add_epi32(sum_sqr, b); - - return _mm_cmpgt_epi32(m_distance_squared, sum_sqr); - } - -private: - const __m128i m_expected_g; - const __m128i m_expected_rb; - const __m128i m_distance_squared; -}; - - - -size_t filter_rgb32_euclidean_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_SSE42 tester( - expected, max_euclidean_distance - ); - FilterImage_Rgb32_x64_SSE42 filter( - tester, replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_euclidean_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t expected, double max_euclidean_distance -){ - PixelTest_Rgb32Euclidean_x64_SSE42 tester( - expected, max_euclidean_distance - ); - ToBlackWhite_Rgb32_x64_SSE42 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Euclidean + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" +#include "Kernels_ImageFilter_RGB32_Euclidean.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Euclidean_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Euclidean_x64_SSE42( + uint32_t expected, double max_euclidean_distance + ) + : m_expected_g(_mm_set1_epi32((expected >> 8) & 0x000000ff)) + , m_expected_rb(_mm_set1_epi32(expected & 0x00ff00ff)) + , m_distance_squared(_mm_set1_epi32((uint32_t)(max_euclidean_distance * max_euclidean_distance))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ + // _mm_srli_epi16: Shift 16-bit integers in pixels right by 8 while shifting in zeros, + // ng: green channels of each pixel, but shifted right by 8 bits + __m128i ng = _mm_and_si128(_mm_srli_epi16(pixel, 8), _mm_set1_epi32(0x000000ff)); + // rb: the red and blue channels of each pixel + __m128i rb = _mm_and_si128(pixel, _mm_set1_epi32(0x00ff00ff)); + // g: the difference between input pixel channels and the expected values + ng = _mm_sub_epi16(ng, m_expected_g); + rb = _mm_sub_epi16(rb, m_expected_rb); + // compute square operation: + // now each 16-bit region is a squared channel difference + // here we assume alpha channel from input image is the same as the expected, + // so the alpha channel difference is always 0, therefore: + // g: each 32-bit integer contains the green channel squared difference + __m128i g = _mm_mullo_epi16(ng, ng); + rb = _mm_mullo_epi16(rb, rb); + // r: each 32-bit integer contains the red channel squared difference + __m128i r = _mm_srli_epi32(rb, 16); + // b: each 32-bit integer contains the blue channel squared difference + __m128i b = _mm_and_si128(rb, _mm_set1_epi32(0x0000ffff)); + // compute r^2 + g^2 + b^2 + __m128i sum_sqr = _mm_add_epi32(r, g); + sum_sqr = _mm_add_epi32(sum_sqr, b); + + return _mm_cmpgt_epi32(m_distance_squared, sum_sqr); + } + +private: + const __m128i m_expected_g; + const __m128i m_expected_rb; + const __m128i m_distance_squared; +}; + + + +size_t filter_rgb32_euclidean_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_SSE42 tester( + expected, max_euclidean_distance + ); + FilterImage_Rgb32_x64_SSE42 filter( + tester, replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_euclidean_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t expected, double max_euclidean_distance +){ + PixelTest_Rgb32Euclidean_x64_SSE42 tester( + expected, max_euclidean_distance + ); + ToBlackWhite_Rgb32_x64_SSE42 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp index 0c5943a5ec..1fab584590 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.cpp @@ -1,349 +1,349 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -size_t filter_rgb32_range_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); -size_t filter_rgb32_range( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return filter_rgb32_range_x64_AVX512( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return filter_rgb32_range_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return filter_rgb32_range_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return filter_rgb32_range_arm64_NEON( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); - } -#endif - return filter_rgb32_range_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - replacement, replace_color_within_range, - mins, maxs - ); -} - - -#if 0 -void filter_rgb32_range_Default( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); -void filter_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - filter_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - filter_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - filter_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - filter_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); - return; - } -#endif - filter_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); -} -#endif - -void filter_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -){ - for (size_t c = 0; c < filter_count; c++){ - filter[c].pixels_in_range = filter_rgb32_range( - image, bytes_per_row, width, height, - filter[c].data, filter[c].bytes_per_row, - filter[c].replacement, - filter[c].pixels_in_range, - filter[c].mins, - filter[c].maxs - ); - } -} - - - - - - -size_t to_blackwhite_rgb32_range_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); -size_t to_blackwhite_rgb32_range( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - if (width * height > 0xffffffff){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); - } -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return to_blackwhite_rgb32_range_x64_AVX512( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return to_blackwhite_rgb32_range_x64_AVX2( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return to_blackwhite_rgb32_range_x64_SSE42( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return to_blackwhite_rgb32_range_arm64_NEON( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); - } -#endif - return to_blackwhite_rgb32_range_Default( - in, in_bytes_per_row, width, height, - out, out_bytes_per_row, - in_range_black, - mins, maxs - ); -} - - - -#if 0 -void to_blackwhite_rgb32_range_Default( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_x64_SSE42( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_x64_AVX2( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_x64_AVX512( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range_arm64_NEON( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); -void to_blackwhite_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return to_blackwhite_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return to_blackwhite_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return to_blackwhite_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - return to_blackwhite_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); - } -#endif - return to_blackwhite_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); -} -#endif - -void to_blackwhite_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -){ - for (size_t c = 0; c < filter_count; c++){ - filter[c].pixels_in_range = to_blackwhite_rgb32_range( - image, bytes_per_row, width, height, - filter[c].data, filter[c].bytes_per_row, - filter[c].in_range_black, - filter[c].mins, - filter[c].maxs - ); - } -} - - - - - - - - - - -} -} +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +size_t filter_rgb32_range_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); +size_t filter_rgb32_range( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return filter_rgb32_range_x64_AVX512( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return filter_rgb32_range_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return filter_rgb32_range_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return filter_rgb32_range_arm64_NEON( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); + } +#endif + return filter_rgb32_range_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + replacement, replace_color_within_range, + mins, maxs + ); +} + + +#if 0 +void filter_rgb32_range_Default( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); +void filter_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + filter_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + filter_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + filter_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + filter_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); + return; + } +#endif + filter_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); +} +#endif + +void filter_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +){ + for (size_t c = 0; c < filter_count; c++){ + filter[c].pixels_in_range = filter_rgb32_range( + image, bytes_per_row, width, height, + filter[c].data, filter[c].bytes_per_row, + filter[c].replacement, + filter[c].pixels_in_range, + filter[c].mins, + filter[c].maxs + ); + } +} + + + + + + +size_t to_blackwhite_rgb32_range_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); +size_t to_blackwhite_rgb32_range( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + if (width * height > 0xffffffff){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Image is too large. more than 2^32 pixels."); + } +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return to_blackwhite_rgb32_range_x64_AVX512( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return to_blackwhite_rgb32_range_x64_AVX2( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return to_blackwhite_rgb32_range_x64_SSE42( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return to_blackwhite_rgb32_range_arm64_NEON( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); + } +#endif + return to_blackwhite_rgb32_range_Default( + in, in_bytes_per_row, width, height, + out, out_bytes_per_row, + in_range_black, + mins, maxs + ); +} + + + +#if 0 +void to_blackwhite_rgb32_range_Default( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_x64_SSE42( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_x64_AVX2( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_x64_AVX512( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range_arm64_NEON( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); +void to_blackwhite_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return to_blackwhite_rgb32_range_x64_AVX512(image, bytes_per_row, width, height, filter, filter_count); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return to_blackwhite_rgb32_range_x64_AVX2(image, bytes_per_row, width, height, filter, filter_count); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return to_blackwhite_rgb32_range_x64_SSE42(image, bytes_per_row, width, height, filter, filter_count); + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + return to_blackwhite_rgb32_range_arm64_NEON(image, bytes_per_row, width, height, filter, filter_count); + } +#endif + return to_blackwhite_rgb32_range_Default(image, bytes_per_row, width, height, filter, filter_count); +} +#endif + +void to_blackwhite_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +){ + for (size_t c = 0; c < filter_count; c++){ + filter[c].pixels_in_range = to_blackwhite_rgb32_range( + image, bytes_per_row, width, height, + filter[c].data, filter[c].bytes_per_row, + filter[c].in_range_black, + filter[c].mins, + filter[c].maxs + ); + } +} + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h index d312e22151..545eca4c35 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h @@ -1,110 +1,110 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - * Perform a filter over an image and replace pixels that match the filter. - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - -// Change certain color in `image_in` and save output to `image_out`. -// If `replace_color_within_range` is true, replace the color within range [mins, maxs] with the color `replacement`. -// If `replace_color_within_range` is false, replace the color outside of the range with the color `replacement`. -// Returns the # of pixels inside the range [mins, maxs]. -size_t filter_rgb32_range( - const uint32_t* image_in, size_t image_in_bytes_per_row, size_t width, size_t height, - uint32_t* image_out, size_t image_out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -); - - -// Same as above, but multiple filters. -// The purpose is to reduce passes over the entire image. -// All matricies must have the same dimensions. -struct FilterRgb32RangeFilter{ - uint32_t* data; // Pointer will be overwritten. - const size_t bytes_per_row; - const uint32_t replacement; - const bool invert; - const uint32_t mins; - const uint32_t maxs; - - size_t pixels_in_range; - - FilterRgb32RangeFilter( - uint32_t* p_data, size_t p_bytes_per_row, - uint32_t p_replacement, bool p_invert, - uint32_t p_mins, uint32_t p_maxs - ) - : data(p_data) - , bytes_per_row(p_bytes_per_row) - , replacement(p_replacement) - , invert(p_invert) - , mins(p_mins) - , maxs(p_maxs) - {} -}; -void filter_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filter, size_t filter_count -); - - - - - - - -size_t to_blackwhite_rgb32_range( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -); - - -// Same as above, but multiple filters. -// The purpose is to reduce passes over the entire image. -// All matricies must have the same dimensions. -struct ToBlackWhiteRgb32RangeFilter{ - uint32_t* const data; - const size_t bytes_per_row; - const uint32_t mins; - const uint32_t maxs; - const bool in_range_black; - - size_t pixels_in_range; - - ToBlackWhiteRgb32RangeFilter( - uint32_t* p_data, size_t p_bytes_per_row, - uint32_t p_mins, uint32_t p_maxs, bool p_in_range_black - ) - : data(p_data) - , bytes_per_row(p_bytes_per_row) - , mins(p_mins) - , maxs(p_maxs) - , in_range_black(p_in_range_black) - {} -}; -void to_blackwhite_rgb32_range( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count -); - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + * Perform a filter over an image and replace pixels that match the filter. + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + +// Change certain color in `image_in` and save output to `image_out`. +// If `replace_color_within_range` is true, replace the color within range [mins, maxs] with the color `replacement`. +// If `replace_color_within_range` is false, replace the color outside of the range with the color `replacement`. +// Returns the # of pixels inside the range [mins, maxs]. +size_t filter_rgb32_range( + const uint32_t* image_in, size_t image_in_bytes_per_row, size_t width, size_t height, + uint32_t* image_out, size_t image_out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +); + + +// Same as above, but multiple filters. +// The purpose is to reduce passes over the entire image. +// All matricies must have the same dimensions. +struct FilterRgb32RangeFilter{ + uint32_t* data; // Pointer will be overwritten. + const size_t bytes_per_row; + const uint32_t replacement; + const bool invert; + const uint32_t mins; + const uint32_t maxs; + + size_t pixels_in_range; + + FilterRgb32RangeFilter( + uint32_t* p_data, size_t p_bytes_per_row, + uint32_t p_replacement, bool p_invert, + uint32_t p_mins, uint32_t p_maxs + ) + : data(p_data) + , bytes_per_row(p_bytes_per_row) + , replacement(p_replacement) + , invert(p_invert) + , mins(p_mins) + , maxs(p_maxs) + {} +}; +void filter_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filter, size_t filter_count +); + + + + + + + +size_t to_blackwhite_rgb32_range( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +); + + +// Same as above, but multiple filters. +// The purpose is to reduce passes over the entire image. +// All matricies must have the same dimensions. +struct ToBlackWhiteRgb32RangeFilter{ + uint32_t* const data; + const size_t bytes_per_row; + const uint32_t mins; + const uint32_t maxs; + const bool in_range_black; + + size_t pixels_in_range; + + ToBlackWhiteRgb32RangeFilter( + uint32_t* p_data, size_t p_bytes_per_row, + uint32_t p_mins, uint32_t p_maxs, bool p_in_range_black + ) + : data(p_data) + , bytes_per_row(p_bytes_per_row) + , mins(p_mins) + , maxs(p_maxs) + , in_range_black(p_in_range_black) + {} +}; +void to_blackwhite_rgb32_range( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + ToBlackWhiteRgb32RangeFilter* filter, size_t filter_count +); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp index 97c070c8d9..c02f5851cf 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_ARM64_NEON.cpp @@ -1,106 +1,106 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include "Kernels/Kernels_arm64_NEON.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" -#include "Kernels_ImageFilter_RGB32_Range_Routines.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - - - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -class PixelTest_Rgb32Range_ARM64_NEON{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( - uint32_t mins, uint32_t maxs - ) - : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(mins))) - , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(maxs))) - , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.mins))) - , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.maxs))) - , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ - uint8x16_t in_u8 = vreinterpretq_u8_u32(pixel); - - // Check if mins > pixel per color channel - uint8x16_t cmp0 = vcgtq_u8(m_mins_u8, in_u8); - // Check if pixel > maxs per color channel - uint8x16_t cmp1 = vcgtq_u8(in_u8, m_maxs_u8); - // cmp: if mins > pixel or pixel > maxs per color channel - uint8x16_t cmp_u8 = vorrq_u8(cmp0, cmp1); - // vceqq_u32: compare bitwise equal - // cmp_u32: if each pixel is within the range - // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits - return vceqq_u32(vreinterpretq_u32_u8(cmp_u8), vreinterpretq_u32_u8(m_zeros_u8)); - } - -private: - uint8x16_t m_mins_u8; - uint8x16_t m_maxs_u8; - uint8x16_t m_zeros_u8; -}; - - - - - -size_t filter_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); - FilterImage_Rgb32_ARM64_NEON filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_arm64_NEON( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); - ToBlackWhite_Rgb32_ARM64_NEON filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include "Kernels/Kernels_arm64_NEON.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_ARM64_NEON.h" +#include "Kernels_ImageFilter_RGB32_Range_Routines.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + + + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +class PixelTest_Rgb32Range_ARM64_NEON{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( + uint32_t mins, uint32_t maxs + ) + : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(mins))) + , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(maxs))) + , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_ARM64_NEON( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_mins_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.mins))) + , m_maxs_u8(vreinterpretq_u8_u32(vdupq_n_u32(filter.maxs))) + , m_zeros_u8(vreinterpretq_u32_u8(vdupq_n_u8(0))) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE uint32x4_t test_word(uint32x4_t& pixel) const{ + uint8x16_t in_u8 = vreinterpretq_u8_u32(pixel); + + // Check if mins > pixel per color channel + uint8x16_t cmp0 = vcgtq_u8(m_mins_u8, in_u8); + // Check if pixel > maxs per color channel + uint8x16_t cmp1 = vcgtq_u8(in_u8, m_maxs_u8); + // cmp: if mins > pixel or pixel > maxs per color channel + uint8x16_t cmp_u8 = vorrq_u8(cmp0, cmp1); + // vceqq_u32: compare bitwise equal + // cmp_u32: if each pixel is within the range + // If a pixel is within [mins, maxs], its uint32_t in `cmp_u32` is all 1 bits, otherwise, all 0 bits + return vceqq_u32(vreinterpretq_u32_u8(cmp_u8), vreinterpretq_u32_u8(m_zeros_u8)); + } + +private: + uint8x16_t m_mins_u8; + uint8x16_t m_maxs_u8; + uint8x16_t m_zeros_u8; +}; + + + + + +size_t filter_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); + FilterImage_Rgb32_ARM64_NEON filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_arm64_NEON( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_ARM64_NEON tester(mins, maxs); + ToBlackWhite_Rgb32_ARM64_NEON filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp index 9a1dfedf36..68ee22dbc9 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Default.cpp @@ -1,109 +1,109 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - -class PixelTest_Rgb32Range_Default{ -public: - static const size_t VECTOR_SIZE = 1; - using Mask = size_t; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_Default( - uint32_t mins, uint32_t maxs - ) - : m_shiftB(mins & 0x000000ff) - , m_shiftG(mins & 0x0000ff00) - , m_shiftR(mins & 0x00ff0000) - , m_shiftA(mins & 0xff000000) - , m_thresholdB((maxs & 0x000000ff) - m_shiftB) - , m_thresholdG((maxs & 0x0000ff00) - m_shiftG) - , m_thresholdR((maxs & 0x00ff0000) - m_shiftR) - , m_thresholdA((maxs & 0xff000000) - m_shiftA) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_Default( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_shiftB(filter.mins & 0x000000ff) - , m_shiftG(filter.mins & 0x0000ff00) - , m_shiftR(filter.mins & 0x00ff0000) - , m_shiftA(filter.mins & 0xff000000) - , m_thresholdB((filter.maxs & 0x000000ff) - m_shiftB) - , m_thresholdG((filter.maxs & 0x0000ff00) - m_shiftG) - , m_thresholdR((filter.maxs & 0x00ff0000) - m_shiftR) - , m_thresholdA((filter.maxs & 0xff000000) - m_shiftA) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ - bool ret = true; - ret &= (pixel & 0x000000ff) - m_shiftB <= m_thresholdB; - ret &= (pixel & 0x0000ff00) - m_shiftG <= m_thresholdG; - ret &= (pixel & 0x00ff0000) - m_shiftR <= m_thresholdR; - ret &= (pixel & 0xff000000) - m_shiftA <= m_thresholdA; - return ret; - } - -private: - const uint32_t m_shiftB; - const uint32_t m_shiftG; - const uint32_t m_shiftR; - const uint32_t m_shiftA; - const uint32_t m_thresholdB; - const uint32_t m_thresholdG; - const uint32_t m_thresholdR; - const uint32_t m_thresholdA; -}; - - - - - - -size_t filter_rgb32_range_Default( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_Default tester(mins, maxs); - FilterImage_Rgb32_Default filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_Default( - const uint32_t* image, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_Default tester(mins, maxs); - ToBlackWhite_Rgb32_Default filter( - tester, in_range_black - ); - filter_per_pixel(image, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_Default.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + +class PixelTest_Rgb32Range_Default{ +public: + static const size_t VECTOR_SIZE = 1; + using Mask = size_t; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_Default( + uint32_t mins, uint32_t maxs + ) + : m_shiftB(mins & 0x000000ff) + , m_shiftG(mins & 0x0000ff00) + , m_shiftR(mins & 0x00ff0000) + , m_shiftA(mins & 0xff000000) + , m_thresholdB((maxs & 0x000000ff) - m_shiftB) + , m_thresholdG((maxs & 0x0000ff00) - m_shiftG) + , m_thresholdR((maxs & 0x00ff0000) - m_shiftR) + , m_thresholdA((maxs & 0xff000000) - m_shiftA) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_Default( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_shiftB(filter.mins & 0x000000ff) + , m_shiftG(filter.mins & 0x0000ff00) + , m_shiftR(filter.mins & 0x00ff0000) + , m_shiftA(filter.mins & 0xff000000) + , m_thresholdB((filter.maxs & 0x000000ff) - m_shiftB) + , m_thresholdG((filter.maxs & 0x0000ff00) - m_shiftG) + , m_thresholdR((filter.maxs & 0x00ff0000) - m_shiftR) + , m_thresholdA((filter.maxs & 0xff000000) - m_shiftA) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE bool test_word(uint32_t pixel) const{ + bool ret = true; + ret &= (pixel & 0x000000ff) - m_shiftB <= m_thresholdB; + ret &= (pixel & 0x0000ff00) - m_shiftG <= m_thresholdG; + ret &= (pixel & 0x00ff0000) - m_shiftR <= m_thresholdR; + ret &= (pixel & 0xff000000) - m_shiftA <= m_thresholdA; + return ret; + } + +private: + const uint32_t m_shiftB; + const uint32_t m_shiftG; + const uint32_t m_shiftR; + const uint32_t m_shiftA; + const uint32_t m_thresholdB; + const uint32_t m_thresholdG; + const uint32_t m_thresholdR; + const uint32_t m_thresholdA; +}; + + + + + + +size_t filter_rgb32_range_Default( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_Default tester(mins, maxs); + FilterImage_Rgb32_Default filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_Default( + const uint32_t* image, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_Default tester(mins, maxs); + ToBlackWhite_Rgb32_Default filter( + tester, in_range_black + ); + filter_per_pixel(image, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h index e215b95764..b37bec2a46 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_Routines.h @@ -1,115 +1,115 @@ -/* Image Filters Basic Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H -#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H - -#include "Common/Compiler.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels_ImageFilter_RGB32_Range.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - - -template -PA_FORCE_INLINE void filter_per_pixel( - const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, - FilterRgb32RangeFilter* filters, size_t filter_count -){ - if (width == 0 || height == 0){ - return; - } - -// cout << "filter_per_pixel(" << filter_count << "): " << width << " x " << height << endl; - - FixedLimitVector entries(filter_count); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - entries.emplace_back(filter); - } - - const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; - do{ - // Less than vector width. No need for steady-state loop. - if (width < VECTOR_SIZE){ - typename Runner::Mask mask(width); - do{ - const uint32_t* in = image; - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_partial(filters[c].data, in, mask); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); - } - }while (--height); - break; - } - - // Divisible by vector width. No need for peel loop. - size_t left = width % VECTOR_SIZE; - if (left == 0){ - do{ - const uint32_t* in = image; - size_t shift = 0; - size_t lc = width / VECTOR_SIZE; - do{ - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_full(filters[c].data + shift, in); - } - in += VECTOR_SIZE; - shift += VECTOR_SIZE; - }while (--lc); - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); - } - }while (--height); - break; - } - - // Need both steady-state and peel loops. - { - typename Runner::Mask mask(left); - do{ - const uint32_t* in = image; - size_t shift = 0; - size_t lc = width / VECTOR_SIZE; - do{ - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_full(filters[c].data + shift, in); - } - in += VECTOR_SIZE; - shift += VECTOR_SIZE; - }while (--lc); - for (size_t c = 0; c < filter_count; c++){ - entries[c].process_partial(filters[c].data + shift, in, mask); - } - image = (const uint32_t*)((const char*)image + bytes_per_row); - for (size_t c = 0; c < filter_count; c++){ - FilterRgb32RangeFilter& filter = filters[c]; - filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); - } - }while (--height); - break; - } - }while (false); - - for (size_t c = 0; c < filter_count; c++){ - filters[c].pixels_in_range = entries[c].count(); - } -} - - - - -} -} -#endif +/* Image Filters Basic Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H +#define PokemonAutomation_Kernels_ImageFilter_RGB32_Range_Routines_H + +#include "Common/Compiler.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels_ImageFilter_RGB32_Range.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + + +template +PA_FORCE_INLINE void filter_per_pixel( + const uint32_t* image, size_t bytes_per_row, size_t width, size_t height, + FilterRgb32RangeFilter* filters, size_t filter_count +){ + if (width == 0 || height == 0){ + return; + } + +// cout << "filter_per_pixel(" << filter_count << "): " << width << " x " << height << endl; + + FixedLimitVector entries(filter_count); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + entries.emplace_back(filter); + } + + const size_t VECTOR_SIZE = Runner::VECTOR_SIZE; + do{ + // Less than vector width. No need for steady-state loop. + if (width < VECTOR_SIZE){ + typename Runner::Mask mask(width); + do{ + const uint32_t* in = image; + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_partial(filters[c].data, in, mask); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); + } + }while (--height); + break; + } + + // Divisible by vector width. No need for peel loop. + size_t left = width % VECTOR_SIZE; + if (left == 0){ + do{ + const uint32_t* in = image; + size_t shift = 0; + size_t lc = width / VECTOR_SIZE; + do{ + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_full(filters[c].data + shift, in); + } + in += VECTOR_SIZE; + shift += VECTOR_SIZE; + }while (--lc); + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); + } + }while (--height); + break; + } + + // Need both steady-state and peel loops. + { + typename Runner::Mask mask(left); + do{ + const uint32_t* in = image; + size_t shift = 0; + size_t lc = width / VECTOR_SIZE; + do{ + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_full(filters[c].data + shift, in); + } + in += VECTOR_SIZE; + shift += VECTOR_SIZE; + }while (--lc); + for (size_t c = 0; c < filter_count; c++){ + entries[c].process_partial(filters[c].data + shift, in, mask); + } + image = (const uint32_t*)((const char*)image + bytes_per_row); + for (size_t c = 0; c < filter_count; c++){ + FilterRgb32RangeFilter& filter = filters[c]; + filter.data = (uint32_t*)((const char*)filter.data + filter.bytes_per_row); + } + }while (--height); + break; + } + }while (false); + + for (size_t c = 0; c < filter_count; c++){ + filters[c].pixels_in_range = entries[c].count(); + } +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp index 4e81e4d6ad..828e3f44d7 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX2.cpp @@ -1,99 +1,99 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -class PixelTest_Rgb32Range_x64_AVX2{ -public: - static const size_t VECTOR_SIZE = 8; - using Mask = PartialWordAccess32_x64_AVX2; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( - uint32_t mins, uint32_t maxs - ) - : m_mins(_mm256_set1_epi32(mins ^ 0x80808080)) - , m_maxs(_mm256_set1_epi32(maxs ^ 0x80808080)) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_mins(_mm256_set1_epi32(filter.mins ^ 0x80808080)) - , m_maxs(_mm256_set1_epi32(filter.maxs ^ 0x80808080)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ - __m256i adj = _mm256_xor_si256(pixel, _mm256_set1_epi8((uint8_t)0x80)); - __m256i cmp0 = _mm256_cmpgt_epi8(m_mins, adj); - __m256i cmp1 = _mm256_cmpgt_epi8(adj, m_maxs); - cmp0 = _mm256_or_si256(cmp0, cmp1); - return _mm256_cmpeq_epi32(cmp0, _mm256_setzero_si256()); - } - -private: - const __m256i m_mins; - const __m256i m_maxs; -}; - - - - - - - -size_t filter_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); - FilterImage_Rgb32_x64_AVX2 filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_x64_AVX2( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); - ToBlackWhite_Rgb32_x64_AVX2 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX2.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +class PixelTest_Rgb32Range_x64_AVX2{ +public: + static const size_t VECTOR_SIZE = 8; + using Mask = PartialWordAccess32_x64_AVX2; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( + uint32_t mins, uint32_t maxs + ) + : m_mins(_mm256_set1_epi32(mins ^ 0x80808080)) + , m_maxs(_mm256_set1_epi32(maxs ^ 0x80808080)) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX2( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_mins(_mm256_set1_epi32(filter.mins ^ 0x80808080)) + , m_maxs(_mm256_set1_epi32(filter.maxs ^ 0x80808080)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m256i test_word(__m256i pixel) const{ + __m256i adj = _mm256_xor_si256(pixel, _mm256_set1_epi8((uint8_t)0x80)); + __m256i cmp0 = _mm256_cmpgt_epi8(m_mins, adj); + __m256i cmp1 = _mm256_cmpgt_epi8(adj, m_maxs); + cmp0 = _mm256_or_si256(cmp0, cmp1); + return _mm256_cmpeq_epi32(cmp0, _mm256_setzero_si256()); + } + +private: + const __m256i m_mins; + const __m256i m_maxs; +}; + + + + + + + +size_t filter_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); + FilterImage_Rgb32_x64_AVX2 filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_x64_AVX2( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX2 tester(mins, maxs); + ToBlackWhite_Rgb32_x64_AVX2 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp index e9c6863678..ca2eb64e09 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_AVX512.cpp @@ -1,106 +1,106 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -class PixelTest_Rgb32Range_x64_AVX512{ -public: - static const size_t VECTOR_SIZE = 16; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( - uint32_t mins, uint32_t maxs - ) - : m_shift(_mm512_set1_epi32(mins)) - , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(maxs), m_shift)) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_shift(_mm512_set1_epi32(filter.mins)) - , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(filter.maxs), m_shift)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ - pixel = _mm512_sub_epi8(pixel, m_shift); - __mmask64 cmp64 = _mm512_cmple_epu8_mask(pixel, m_threshold); - __m512i mask = _mm512_movm_epi8(cmp64); - return _mm512_cmpeq_epi32_mask(mask, _mm512_set1_epi32(-1)); - } - -private: - const __m512i m_shift; - const __m512i m_threshold; -}; - - - - - -size_t filter_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); - FilterImage_Rgb32_x64_AVX512 filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_x64_AVX512( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); - ToBlackWhite_Rgb32_x64_AVX512 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - - - - - - - - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_AVX512.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +class PixelTest_Rgb32Range_x64_AVX512{ +public: + static const size_t VECTOR_SIZE = 16; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( + uint32_t mins, uint32_t maxs + ) + : m_shift(_mm512_set1_epi32(mins)) + , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(maxs), m_shift)) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_AVX512( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_shift(_mm512_set1_epi32(filter.mins)) + , m_threshold(_mm512_sub_epi8(_mm512_set1_epi32(filter.maxs), m_shift)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __mmask16 test_word(__m512i pixel) const{ + pixel = _mm512_sub_epi8(pixel, m_shift); + __mmask64 cmp64 = _mm512_cmple_epu8_mask(pixel, m_threshold); + __m512i mask = _mm512_movm_epi8(cmp64); + return _mm512_cmpeq_epi32_mask(mask, _mm512_set1_epi32(-1)); + } + +private: + const __m512i m_shift; + const __m512i m_threshold; +}; + + + + + +size_t filter_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); + FilterImage_Rgb32_x64_AVX512 filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_x64_AVX512( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_AVX512 tester(mins, maxs); + ToBlackWhite_Rgb32_x64_AVX512 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + + + + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp index a74546c4ae..068842c523 100644 --- a/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range_x64_SSE42.cpp @@ -1,100 +1,100 @@ -/* Image Filters RGB32 Range - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" -#include "Kernels_ImageFilter_RGB32_Range.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - - - - -class PixelTest_Rgb32Range_x64_SSE42{ -public: - static const size_t VECTOR_SIZE = 4; - using Mask = PartialWordMask; - -public: - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( - uint32_t mins, uint32_t maxs - ) - : m_mins(_mm_set1_epi32(mins ^ 0x80808080)) - , m_maxs(_mm_set1_epi32(maxs ^ 0x80808080)) - {} - PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( - const ToBlackWhiteRgb32RangeFilter& filter - ) - : m_mins(_mm_set1_epi32(filter.mins ^ 0x80808080)) - , m_maxs(_mm_set1_epi32(filter.maxs ^ 0x80808080)) - {} - - // Return a mask indicating which lanes are in range. - PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ - __m128i adj = _mm_xor_si128(pixel, _mm_set1_epi8((uint8_t)0x80)); - __m128i cmp0 = _mm_cmpgt_epi8(m_mins, adj); - __m128i cmp1 = _mm_cmpgt_epi8(adj, m_maxs); - cmp0 = _mm_or_si128(cmp0, cmp1); - return _mm_cmpeq_epi32(cmp0, _mm_setzero_si128()); - } - -private: - const __m128i m_mins; - const __m128i m_maxs; -}; - - - - - - - -size_t filter_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - uint32_t replacement, bool replace_color_within_range, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); - FilterImage_Rgb32_x64_SSE42 filter( - tester, - replacement, replace_color_within_range - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} -size_t to_blackwhite_rgb32_range_x64_SSE42( - const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, - uint32_t* out, size_t out_bytes_per_row, - bool in_range_black, - uint32_t mins, uint32_t maxs -){ - PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); - ToBlackWhite_Rgb32_x64_SSE42 filter( - tester, in_range_black - ); - filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); - return filter.count(); -} - - - - - -} -} -#endif +/* Image Filters RGB32 Range + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic_Routines_x64_SSE42.h" +#include "Kernels_ImageFilter_RGB32_Range.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + + + + +class PixelTest_Rgb32Range_x64_SSE42{ +public: + static const size_t VECTOR_SIZE = 4; + using Mask = PartialWordMask; + +public: + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( + uint32_t mins, uint32_t maxs + ) + : m_mins(_mm_set1_epi32(mins ^ 0x80808080)) + , m_maxs(_mm_set1_epi32(maxs ^ 0x80808080)) + {} + PA_FORCE_INLINE PixelTest_Rgb32Range_x64_SSE42( + const ToBlackWhiteRgb32RangeFilter& filter + ) + : m_mins(_mm_set1_epi32(filter.mins ^ 0x80808080)) + , m_maxs(_mm_set1_epi32(filter.maxs ^ 0x80808080)) + {} + + // Return a mask indicating which lanes are in range. + PA_FORCE_INLINE __m128i test_word(__m128i pixel) const{ + __m128i adj = _mm_xor_si128(pixel, _mm_set1_epi8((uint8_t)0x80)); + __m128i cmp0 = _mm_cmpgt_epi8(m_mins, adj); + __m128i cmp1 = _mm_cmpgt_epi8(adj, m_maxs); + cmp0 = _mm_or_si128(cmp0, cmp1); + return _mm_cmpeq_epi32(cmp0, _mm_setzero_si128()); + } + +private: + const __m128i m_mins; + const __m128i m_maxs; +}; + + + + + + + +size_t filter_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + uint32_t replacement, bool replace_color_within_range, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); + FilterImage_Rgb32_x64_SSE42 filter( + tester, + replacement, replace_color_within_range + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} +size_t to_blackwhite_rgb32_range_x64_SSE42( + const uint32_t* in, size_t in_bytes_per_row, size_t width, size_t height, + uint32_t* out, size_t out_bytes_per_row, + bool in_range_black, + uint32_t mins, uint32_t maxs +){ + PixelTest_Rgb32Range_x64_SSE42 tester(mins, maxs); + ToBlackWhite_Rgb32_x64_SSE42 filter( + tester, in_range_black + ); + filter_per_pixel(in, in_bytes_per_row, width, height, filter, out, out_bytes_per_row); + return filter.count(); +} + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.cpp b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.cpp index f2f2afd678..9a5e46ad72 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.cpp +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.cpp @@ -1,78 +1,78 @@ -/* Scale Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImageScaleBrightness.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -void scale_brightness_Default( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -); -void scale_brightness_x64_SSE41( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -); -void scale_brightness_x64_AVX2( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -); -void scale_brightness_x64_AVX512( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -); -void scale_brightness_arm64_NEON( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -); - - - -void scale_brightness( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - scale_brightness_x64_AVX512(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - scale_brightness_x64_AVX2(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - scale_brightness_x64_SSE41(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); - return; - } -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - scale_brightness_arm64_NEON(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); - return; - } -#endif - scale_brightness_Default(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); -} - - - - -} -} +/* Scale Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImageScaleBrightness.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +void scale_brightness_Default( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +); +void scale_brightness_x64_SSE41( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +); +void scale_brightness_x64_AVX2( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +); +void scale_brightness_x64_AVX512( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +); +void scale_brightness_arm64_NEON( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +); + + + +void scale_brightness( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + scale_brightness_x64_AVX512(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + scale_brightness_x64_AVX2(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + scale_brightness_x64_SSE41(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); + return; + } +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + scale_brightness_arm64_NEON(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); + return; + } +#endif + scale_brightness_Default(width, height, image, bytes_per_row, scaleR, scaleG, scaleB); +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h index bac8fc3be3..ba835e88c2 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h @@ -1,28 +1,28 @@ -/* Scale Brightness - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ImageScaleBrightness_H -#define PokemonAutomation_Kernels_ImageScaleBrightness_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - -// Scale the R, G, B channels of every pixel of the image independently, by `scaleR`, `scaleG`, `scaleB`. The alpha channel is left untouched. -// image: each pixel is represented as uint32_t, where each of the 8 bit is used as alpha (highest bits), r, g, b(lowest bits). -// image is row-major; advance to next row by a step size of `bytes_per_row`. -void scale_brightness( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -); - - -} -} -#endif +/* Scale Brightness + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ImageScaleBrightness_H +#define PokemonAutomation_Kernels_ImageScaleBrightness_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + +// Scale the R, G, B channels of every pixel of the image independently, by `scaleR`, `scaleG`, `scaleB`. The alpha channel is left untouched. +// image: each pixel is represented as uint32_t, where each of the 8 bit is used as alpha (highest bits), r, g, b(lowest bits). +// image is row-major; advance to next row by a step size of `bytes_per_row`. +void scale_brightness( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +); + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_Default.cpp b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_Default.cpp index ffa9f98dd5..ea5d11f28e 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_Default.cpp @@ -1,61 +1,61 @@ -/* Scale Brightness (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -PA_FORCE_INLINE void scale_brightness_Default( - size_t width, uint32_t* image, - float scaleR, float scaleG, float scaleB -){ - for (size_t c = 0; c < width; c++){ - uint32_t pixel = image[c]; - float r = (float)((pixel >> 16) & 0x000000ff); - float g = (float)((pixel >> 8) & 0x000000ff); - float b = (float)(pixel & 0x000000ff); - r *= scaleR; - g *= scaleG; - b *= scaleB; - - uint32_t r_u32 = std::min((uint32_t)r, (uint32_t)255); - uint32_t g_u32 = std::min((uint32_t)g, (uint32_t)255); - uint32_t b_u32 = std::min((uint32_t)b, (uint32_t)255); - - pixel &= 0xff000000; - pixel |= r_u32 << 16; - pixel |= g_u32 << 8; - pixel |= b_u32; - - image[c] = pixel; - } -} -void scale_brightness_Default( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -){ - if (width == 0 || height == 0){ - return; - } - scaleR = std::max(scaleR, 0.0f); - scaleG = std::max(scaleG, 0.0f); - scaleB = std::max(scaleB, 0.0f); - for (uint16_t r = 0; r < height; r++){ - scale_brightness_Default(width, image, scaleR, scaleG, scaleB); - image = (uint32_t*)((char*)image + bytes_per_row); - } -} - - - - -} -} +/* Scale Brightness (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +PA_FORCE_INLINE void scale_brightness_Default( + size_t width, uint32_t* image, + float scaleR, float scaleG, float scaleB +){ + for (size_t c = 0; c < width; c++){ + uint32_t pixel = image[c]; + float r = (float)((pixel >> 16) & 0x000000ff); + float g = (float)((pixel >> 8) & 0x000000ff); + float b = (float)(pixel & 0x000000ff); + r *= scaleR; + g *= scaleG; + b *= scaleB; + + uint32_t r_u32 = std::min((uint32_t)r, (uint32_t)255); + uint32_t g_u32 = std::min((uint32_t)g, (uint32_t)255); + uint32_t b_u32 = std::min((uint32_t)b, (uint32_t)255); + + pixel &= 0xff000000; + pixel |= r_u32 << 16; + pixel |= g_u32 << 8; + pixel |= b_u32; + + image[c] = pixel; + } +} +void scale_brightness_Default( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +){ + if (width == 0 || height == 0){ + return; + } + scaleR = std::max(scaleR, 0.0f); + scaleG = std::max(scaleG, 0.0f); + scaleB = std::max(scaleB, 0.0f); + for (uint16_t r = 0; r < height; r++){ + scale_brightness_Default(width, image, scaleR, scaleG, scaleB); + image = (uint32_t*)((char*)image + bytes_per_row); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_arm64_NEON.cpp b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_arm64_NEON.cpp index 5f418091fb..94a281b25f 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_arm64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_arm64_NEON.cpp @@ -1,142 +1,142 @@ -/* Scale Brightness (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -#include -#include -#include -#include -#include "Common/Compiler.h" - -#include -using std::cout, std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - -// #define CHECK_ACCURACY -namespace{ - -PA_FORCE_INLINE void scale_brightness_arm64_NEON_four_pixels_per_channel_scale( - size_t width, uint32_t* image, - float r_scale, float g_scale, float b_scale -){ - #ifdef CHECK_ACCURACY - { - uint32_t pixel = image[0]; - uint32_t r = (pixel >> 16) & 0x000000ff; - uint32_t g = (pixel >> 8) & 0x000000ff; - uint32_t b = pixel & 0x000000ff; - cout << "r g b " << r << " " << g << " " << b << endl; - } - #endif - - const uint32x4_t mask_u32x4 = vmovq_n_u32(0xff); - const uint32x4_t alpha_mask_u32x4 = vmovq_n_u32(0xff000000); - - const uint32x4_t max_brightness_u32x4 = vmovq_n_u32(255); - - const size_t width_aligned = width - width % 4; - for (size_t c = 0; c < width_aligned; c+=4){ - // Load four pixels - uint32x4_t vec_u32x4 = vld1q_u32(&image[c]); - // Extract each color channel of the four pixels - uint32x4_t b_u32x4 = vandq_u32(vec_u32x4, mask_u32x4); - uint32x4_t g_u32x4 = vandq_u32(vshrq_n_u32(vec_u32x4, 8), mask_u32x4); - uint32x4_t r_u32x4 = vandq_u32(vshrq_n_u32(vec_u32x4, 16), mask_u32x4); - uint32x4_t a_u32x4 = vandq_u32(vec_u32x4, alpha_mask_u32x4); - - // Convert them to float32 - float32x4_t b_f32x4 = vcvtq_f32_u32(b_u32x4); - float32x4_t g_f32x4 = vcvtq_f32_u32(g_u32x4); - float32x4_t r_f32x4 = vcvtq_f32_u32(r_u32x4); - - // Scale color channels - b_f32x4 = vmulq_n_f32(b_f32x4, b_scale); - g_f32x4 = vmulq_n_f32(g_f32x4, g_scale); - r_f32x4 = vmulq_n_f32(r_f32x4, r_scale); - - // Convert each float32 back to uint32 - b_u32x4 = vcvtq_u32_f32(b_f32x4); - g_u32x4 = vcvtq_u32_f32(g_f32x4); - r_u32x4 = vcvtq_u32_f32(r_f32x4); - - // Clamp against 255 - b_u32x4 = vminq_u32(b_u32x4, max_brightness_u32x4); - g_u32x4 = vminq_u32(g_u32x4, max_brightness_u32x4); - r_u32x4 = vminq_u32(r_u32x4, max_brightness_u32x4); - - // Add channels back to form four pixels - // shift g channels left by 8, then combine it with b channels - uint32x4_t gb_u32x4 = vsliq_n_u32(b_u32x4, g_u32x4, 8); - // shift r channels left by 16, then combine with gb channels - uint32x4_t rgb_u32x4 = vsliq_n_u32(gb_u32x4, r_u32x4, 16); - vec_u32x4 = vorrq_s32(a_u32x4, rgb_u32x4); - vst1q_u32(&image[c], vec_u32x4); - } - - for(size_t c = width_aligned; c < width; c++){ - uint32_t pixel = image[c]; - float r = (float)((pixel >> 16) & 0x000000ff); - float g = (float)((pixel >> 8) & 0x000000ff); - float b = (float)(pixel & 0x000000ff); - r *= r_scale; - g *= g_scale; - b *= b_scale; - uint32_t r_u32 = std::min((uint32_t)r, (uint32_t)255); - uint32_t g_u32 = std::min((uint32_t)g, (uint32_t)255); - uint32_t b_u32 = std::min((uint32_t)b, (uint32_t)255); - - pixel &= 0xff000000; - pixel |= r_u32 << 16; - pixel |= g_u32 << 8; - pixel |= b_u32; - - image[c] = pixel; - } - - #ifdef CHECK_ACCURACY - { - uint32_t pixel = image[0]; - uint32_t r = (pixel >> 16) & 0x000000ff; - uint32_t g = (pixel >> 8) & 0x000000ff; - uint32_t b = pixel & 0x000000ff; - cout << std::dec << "After: r g b " << r << " " << g << " " << b << endl; - } - #endif - -} - -} - -void scale_brightness_arm64_NEON( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -){ - if (width == 0 || height == 0){ - return; - } - scaleR = std::max(scaleR, 0.0f); - scaleG = std::max(scaleG, 0.0f); - scaleB = std::max(scaleB, 0.0f); - - for (uint16_t r = 0; r < height; r++){ - scale_brightness_arm64_NEON_four_pixels_per_channel_scale(width, image, scaleR, scaleG, scaleB); - image = (uint32_t*)((char*)image + bytes_per_row); - - #ifdef CHECK_ACCURACY - break; - #endif - } -} - - - -} -} -#endif +/* Scale Brightness (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +#include +#include +#include +#include +#include "Common/Compiler.h" + +#include +using std::cout, std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + +// #define CHECK_ACCURACY +namespace{ + +PA_FORCE_INLINE void scale_brightness_arm64_NEON_four_pixels_per_channel_scale( + size_t width, uint32_t* image, + float r_scale, float g_scale, float b_scale +){ + #ifdef CHECK_ACCURACY + { + uint32_t pixel = image[0]; + uint32_t r = (pixel >> 16) & 0x000000ff; + uint32_t g = (pixel >> 8) & 0x000000ff; + uint32_t b = pixel & 0x000000ff; + cout << "r g b " << r << " " << g << " " << b << endl; + } + #endif + + const uint32x4_t mask_u32x4 = vmovq_n_u32(0xff); + const uint32x4_t alpha_mask_u32x4 = vmovq_n_u32(0xff000000); + + const uint32x4_t max_brightness_u32x4 = vmovq_n_u32(255); + + const size_t width_aligned = width - width % 4; + for (size_t c = 0; c < width_aligned; c+=4){ + // Load four pixels + uint32x4_t vec_u32x4 = vld1q_u32(&image[c]); + // Extract each color channel of the four pixels + uint32x4_t b_u32x4 = vandq_u32(vec_u32x4, mask_u32x4); + uint32x4_t g_u32x4 = vandq_u32(vshrq_n_u32(vec_u32x4, 8), mask_u32x4); + uint32x4_t r_u32x4 = vandq_u32(vshrq_n_u32(vec_u32x4, 16), mask_u32x4); + uint32x4_t a_u32x4 = vandq_u32(vec_u32x4, alpha_mask_u32x4); + + // Convert them to float32 + float32x4_t b_f32x4 = vcvtq_f32_u32(b_u32x4); + float32x4_t g_f32x4 = vcvtq_f32_u32(g_u32x4); + float32x4_t r_f32x4 = vcvtq_f32_u32(r_u32x4); + + // Scale color channels + b_f32x4 = vmulq_n_f32(b_f32x4, b_scale); + g_f32x4 = vmulq_n_f32(g_f32x4, g_scale); + r_f32x4 = vmulq_n_f32(r_f32x4, r_scale); + + // Convert each float32 back to uint32 + b_u32x4 = vcvtq_u32_f32(b_f32x4); + g_u32x4 = vcvtq_u32_f32(g_f32x4); + r_u32x4 = vcvtq_u32_f32(r_f32x4); + + // Clamp against 255 + b_u32x4 = vminq_u32(b_u32x4, max_brightness_u32x4); + g_u32x4 = vminq_u32(g_u32x4, max_brightness_u32x4); + r_u32x4 = vminq_u32(r_u32x4, max_brightness_u32x4); + + // Add channels back to form four pixels + // shift g channels left by 8, then combine it with b channels + uint32x4_t gb_u32x4 = vsliq_n_u32(b_u32x4, g_u32x4, 8); + // shift r channels left by 16, then combine with gb channels + uint32x4_t rgb_u32x4 = vsliq_n_u32(gb_u32x4, r_u32x4, 16); + vec_u32x4 = vorrq_s32(a_u32x4, rgb_u32x4); + vst1q_u32(&image[c], vec_u32x4); + } + + for(size_t c = width_aligned; c < width; c++){ + uint32_t pixel = image[c]; + float r = (float)((pixel >> 16) & 0x000000ff); + float g = (float)((pixel >> 8) & 0x000000ff); + float b = (float)(pixel & 0x000000ff); + r *= r_scale; + g *= g_scale; + b *= b_scale; + uint32_t r_u32 = std::min((uint32_t)r, (uint32_t)255); + uint32_t g_u32 = std::min((uint32_t)g, (uint32_t)255); + uint32_t b_u32 = std::min((uint32_t)b, (uint32_t)255); + + pixel &= 0xff000000; + pixel |= r_u32 << 16; + pixel |= g_u32 << 8; + pixel |= b_u32; + + image[c] = pixel; + } + + #ifdef CHECK_ACCURACY + { + uint32_t pixel = image[0]; + uint32_t r = (pixel >> 16) & 0x000000ff; + uint32_t g = (pixel >> 8) & 0x000000ff; + uint32_t b = pixel & 0x000000ff; + cout << std::dec << "After: r g b " << r << " " << g << " " << b << endl; + } + #endif + +} + +} + +void scale_brightness_arm64_NEON( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +){ + if (width == 0 || height == 0){ + return; + } + scaleR = std::max(scaleR, 0.0f); + scaleG = std::max(scaleG, 0.0f); + scaleB = std::max(scaleB, 0.0f); + + for (uint16_t r = 0; r < height; r++){ + scale_brightness_arm64_NEON_four_pixels_per_channel_scale(width, image, scaleR, scaleG, scaleB); + image = (uint32_t*)((char*)image + bytes_per_row); + + #ifdef CHECK_ACCURACY + break; + #endif + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp index 1bd3ffb571..b05a655231 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX2.cpp @@ -1,82 +1,82 @@ -/* Scale Brightness (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include -#include "Common/Compiler.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -PA_FORCE_INLINE void scale_brightness_x64_AVX2( - size_t width, uint32_t* image, - __m256 scale -){ - size_t lc = width / 2; - do{ - __m128i pixel = _mm_loadl_epi64((const __m128i*)image); - - __m256i pi = _mm256_cvtepu8_epi32(pixel); - __m256 pf = _mm256_cvtepi32_ps(pi); - pf = _mm256_mul_ps(pf, scale); - pf = _mm256_min_ps(pf, _mm256_set1_ps(255.)); - pf = _mm256_max_ps(pf, _mm256_set1_ps(0.)); - pi = _mm256_cvtps_epi32(pf); - pi = _mm256_shuffle_epi8(pi, _mm256_setr_epi8( - 0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1 - )); - - pixel = _mm_or_si128( - _mm256_castsi256_si128(pi), - _mm256_extracti128_si256(pi, 1) - ); - - _mm_storel_epi64((__m128i*)image, pixel); - image += 2; - }while (--lc); - - if (width % 2){ - uint32_t pixel = image[0]; - - __m128i pi = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(pixel)); - __m128 pf = _mm_cvtepi32_ps(pi); - pf = _mm_mul_ps(pf, _mm256_castps256_ps128(scale)); - pf = _mm_min_ps(pf, _mm_set1_ps(255.)); - pf = _mm_max_ps(pf, _mm_set1_ps(0.)); - pi = _mm_cvtps_epi32(pf); - pi = _mm_shuffle_epi8(pi, _mm_setr_epi8(0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)); - - image[0] = _mm_cvtsi128_si32(pi); - } -} -void scale_brightness_x64_AVX2( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -){ - if (width == 0 || height == 0){ - return; - } - __m256 scale = _mm256_setr_ps(scaleB, scaleG, scaleR, 1, scaleB, scaleG, scaleR, 1); - for (uint16_t r = 0; r < height; r++){ - scale_brightness_x64_AVX2(width, image, scale); - image = (uint32_t*)((char*)image + bytes_per_row); - } -} - - - -} -} -#endif +/* Scale Brightness (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include +#include "Common/Compiler.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +PA_FORCE_INLINE void scale_brightness_x64_AVX2( + size_t width, uint32_t* image, + __m256 scale +){ + size_t lc = width / 2; + do{ + __m128i pixel = _mm_loadl_epi64((const __m128i*)image); + + __m256i pi = _mm256_cvtepu8_epi32(pixel); + __m256 pf = _mm256_cvtepi32_ps(pi); + pf = _mm256_mul_ps(pf, scale); + pf = _mm256_min_ps(pf, _mm256_set1_ps(255.)); + pf = _mm256_max_ps(pf, _mm256_set1_ps(0.)); + pi = _mm256_cvtps_epi32(pf); + pi = _mm256_shuffle_epi8(pi, _mm256_setr_epi8( + 0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1 + )); + + pixel = _mm_or_si128( + _mm256_castsi256_si128(pi), + _mm256_extracti128_si256(pi, 1) + ); + + _mm_storel_epi64((__m128i*)image, pixel); + image += 2; + }while (--lc); + + if (width % 2){ + uint32_t pixel = image[0]; + + __m128i pi = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(pixel)); + __m128 pf = _mm_cvtepi32_ps(pi); + pf = _mm_mul_ps(pf, _mm256_castps256_ps128(scale)); + pf = _mm_min_ps(pf, _mm_set1_ps(255.)); + pf = _mm_max_ps(pf, _mm_set1_ps(0.)); + pi = _mm_cvtps_epi32(pf); + pi = _mm_shuffle_epi8(pi, _mm_setr_epi8(0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)); + + image[0] = _mm_cvtsi128_si32(pi); + } +} +void scale_brightness_x64_AVX2( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +){ + if (width == 0 || height == 0){ + return; + } + __m256 scale = _mm256_setr_ps(scaleB, scaleG, scaleR, 1, scaleB, scaleG, scaleR, 1); + for (uint16_t r = 0; r < height; r++){ + scale_brightness_x64_AVX2(width, image, scale); + image = (uint32_t*)((char*)image + bytes_per_row); + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp index b8f393baab..425c7d0594 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_AVX512.cpp @@ -1,81 +1,81 @@ -/* Scale Brightness (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include -#include "Common/Compiler.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -PA_FORCE_INLINE void scale_brightness_x64_AVX512( - size_t width, uint32_t* image, - __m512 scale -){ - size_t lc = width / 4; - do{ - __m128i pixel = _mm_loadu_si128((const __m128i*)image); - - __m512i pi = _mm512_cvtepu8_epi32(pixel); - __m512 pf = _mm512_cvtepi32_ps(pi); - pf = _mm512_mul_ps(pf, scale); - pf = _mm512_min_ps(pf, _mm512_set1_ps(255.)); - pf = _mm512_max_ps(pf, _mm512_set1_ps(0.)); - pi = _mm512_cvtps_epi32(pf); - pixel = _mm512_cvtepi32_epi8(pi); - - _mm_storeu_si128((__m128i*)image, pixel); - image += 4; - }while (--lc); - - if (width % 4){ - __mmask8 mask = ((uint32_t)1 << (width % 4)) - 1; - - __m128i pixel = _mm_maskz_loadu_epi32(mask, (const __m128i*)image); - - __m512i pi = _mm512_cvtepu8_epi32(pixel); - __m512 pf = _mm512_cvtepi32_ps(pi); - pf = _mm512_mul_ps(pf, scale); - pf = _mm512_min_ps(pf, _mm512_set1_ps(255.)); - pf = _mm512_max_ps(pf, _mm512_set1_ps(0.)); - pi = _mm512_cvtps_epi32(pf); - pixel = _mm512_cvtepi32_epi8(pi); - - _mm_mask_storeu_epi32((__m128i*)image, mask, pixel); - } -} -void scale_brightness_x64_AVX512( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -){ - if (width == 0 || height == 0){ - return; - } - __m512 scale = _mm512_setr_ps( - scaleB, scaleG, scaleR, 1, - scaleB, scaleG, scaleR, 1, - scaleB, scaleG, scaleR, 1, - scaleB, scaleG, scaleR, 1 - ); - for (uint16_t r = 0; r < height; r++){ - scale_brightness_x64_AVX512(width, image, scale); - image = (uint32_t*)((char*)image + bytes_per_row); - } -} - - - -} -} -#endif +/* Scale Brightness (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include +#include "Common/Compiler.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +PA_FORCE_INLINE void scale_brightness_x64_AVX512( + size_t width, uint32_t* image, + __m512 scale +){ + size_t lc = width / 4; + do{ + __m128i pixel = _mm_loadu_si128((const __m128i*)image); + + __m512i pi = _mm512_cvtepu8_epi32(pixel); + __m512 pf = _mm512_cvtepi32_ps(pi); + pf = _mm512_mul_ps(pf, scale); + pf = _mm512_min_ps(pf, _mm512_set1_ps(255.)); + pf = _mm512_max_ps(pf, _mm512_set1_ps(0.)); + pi = _mm512_cvtps_epi32(pf); + pixel = _mm512_cvtepi32_epi8(pi); + + _mm_storeu_si128((__m128i*)image, pixel); + image += 4; + }while (--lc); + + if (width % 4){ + __mmask8 mask = ((uint32_t)1 << (width % 4)) - 1; + + __m128i pixel = _mm_maskz_loadu_epi32(mask, (const __m128i*)image); + + __m512i pi = _mm512_cvtepu8_epi32(pixel); + __m512 pf = _mm512_cvtepi32_ps(pi); + pf = _mm512_mul_ps(pf, scale); + pf = _mm512_min_ps(pf, _mm512_set1_ps(255.)); + pf = _mm512_max_ps(pf, _mm512_set1_ps(0.)); + pi = _mm512_cvtps_epi32(pf); + pixel = _mm512_cvtepi32_epi8(pi); + + _mm_mask_storeu_epi32((__m128i*)image, mask, pixel); + } +} +void scale_brightness_x64_AVX512( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +){ + if (width == 0 || height == 0){ + return; + } + __m512 scale = _mm512_setr_ps( + scaleB, scaleG, scaleR, 1, + scaleB, scaleG, scaleR, 1, + scaleB, scaleG, scaleR, 1, + scaleB, scaleG, scaleR, 1 + ); + for (uint16_t r = 0; r < height; r++){ + scale_brightness_x64_AVX512(width, image, scale); + image = (uint32_t*)((char*)image + bytes_per_row); + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp index 74ae498958..3065bc9613 100644 --- a/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp +++ b/SerialPrograms/Source/Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness_x64_SSE41.cpp @@ -1,54 +1,54 @@ -/* Scale Brightness (x64 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -PA_FORCE_INLINE void scale_brightness_x64_SSE41( - size_t width, uint32_t* image, - __m128 scale -){ - for (size_t c = 0; c < width; c++){ - uint32_t pixel = image[c]; - - __m128i pi = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(pixel)); - __m128 pf = _mm_cvtepi32_ps(pi); - pf = _mm_mul_ps(pf, scale); - pf = _mm_min_ps(pf, _mm_set1_ps(255.)); - pf = _mm_max_ps(pf, _mm_set1_ps(0.)); - pi = _mm_cvtps_epi32(pf); - pi = _mm_shuffle_epi8(pi, _mm_setr_epi8(0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)); - - image[c] = _mm_cvtsi128_si32(pi); - } -} -void scale_brightness_x64_SSE41( - size_t width, size_t height, - uint32_t* image, size_t bytes_per_row, - float scaleR, float scaleG, float scaleB -){ - if (width == 0 || height == 0){ - return; - } - __m128 scale = _mm_setr_ps(scaleB, scaleG, scaleR, 1); - for (uint16_t r = 0; r < height; r++){ - scale_brightness_x64_SSE41(width, image, scale); - image = (uint32_t*)((char*)image + bytes_per_row); - } -} - - - -} -} -#endif +/* Scale Brightness (x64 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +PA_FORCE_INLINE void scale_brightness_x64_SSE41( + size_t width, uint32_t* image, + __m128 scale +){ + for (size_t c = 0; c < width; c++){ + uint32_t pixel = image[c]; + + __m128i pi = _mm_cvtepu8_epi32(_mm_cvtsi32_si128(pixel)); + __m128 pf = _mm_cvtepi32_ps(pi); + pf = _mm_mul_ps(pf, scale); + pf = _mm_min_ps(pf, _mm_set1_ps(255.)); + pf = _mm_max_ps(pf, _mm_set1_ps(0.)); + pi = _mm_cvtps_epi32(pf); + pi = _mm_shuffle_epi8(pi, _mm_setr_epi8(0, 4, 8, 12, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1)); + + image[c] = _mm_cvtsi128_si32(pi); + } +} +void scale_brightness_x64_SSE41( + size_t width, size_t height, + uint32_t* image, size_t bytes_per_row, + float scaleR, float scaleG, float scaleB +){ + if (width == 0 || height == 0){ + return; + } + __m128 scale = _mm_setr_ps(scaleB, scaleG, scaleR, 1); + for (uint16_t r = 0; r < height; r++){ + scale_brightness_x64_SSE41(width, image, scale); + image = (uint32_t*)((char*)image + bytes_per_row); + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.cpp index e495372ec2..a9941f0e13 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.cpp @@ -1,91 +1,91 @@ -/* Pixel Sum + Sum of Squares - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImagePixelSumSqr.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -void pixel_sum_sqr_Default( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); -void pixel_sum_sqr_x64_SSE41( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); -void pixel_sum_sqr_x64_AVX2( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); -void pixel_sum_sqr_x64_AVX512( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); - - - -void pixel_sum_sqr( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - pixel_sum_sqr_x64_AVX512( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - pixel_sum_sqr_x64_AVX2( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - pixel_sum_sqr_x64_SSE41( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); - return; - } -#endif - pixel_sum_sqr_Default( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); -} - - - -} -} +/* Pixel Sum + Sum of Squares + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImagePixelSumSqr.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +void pixel_sum_sqr_Default( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); +void pixel_sum_sqr_x64_SSE41( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); +void pixel_sum_sqr_x64_AVX2( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); +void pixel_sum_sqr_x64_AVX512( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); + + + +void pixel_sum_sqr( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + pixel_sum_sqr_x64_AVX512( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + pixel_sum_sqr_x64_AVX2( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + pixel_sum_sqr_x64_SSE41( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); + return; + } +#endif + pixel_sum_sqr_Default( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.h b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.h index 8e0e46d40a..585b81c2bf 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.h +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr.h @@ -1,40 +1,40 @@ -/* Pixel Sum + Sum of Squares - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ImagePixelSumSqr_H -#define PokemonAutomation_Kernels_ImagePixelSumSqr_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - -struct PixelSums{ - size_t count = 0; - uint64_t sumR = 0; - uint64_t sumG = 0; - uint64_t sumB = 0; - uint64_t sqrR = 0; - uint64_t sqrG = 0; - uint64_t sqrB = 0; -}; - - -// Alpha on "image" is ignored. All pixels are considered active. -// Pixels on "alpha" are considered active if the alpha is >= 128. -void pixel_sum_sqr( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); - - -} -} -#endif +/* Pixel Sum + Sum of Squares + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ImagePixelSumSqr_H +#define PokemonAutomation_Kernels_ImagePixelSumSqr_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + +struct PixelSums{ + size_t count = 0; + uint64_t sumR = 0; + uint64_t sumG = 0; + uint64_t sumB = 0; + uint64_t sqrR = 0; + uint64_t sqrG = 0; + uint64_t sqrB = 0; +}; + + +// Alpha on "image" is ignored. All pixels are considered active. +// Pixels on "alpha" are considered active if the alpha is >= 128. +void pixel_sum_sqr( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.cpp index c6c3ee461e..56345894a4 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.cpp @@ -1,148 +1,148 @@ -/* Sum of Squares of Deviation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_ImagePixelSumSqrDev.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_SSE41( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_AVX2( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_AVX512( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - -template -void sum_sqr_deviation( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background = 0 -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - sum_sqr_deviation_x64_AVX512( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - sum_sqr_deviation_x64_AVX2( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); - return; - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - sum_sqr_deviation_x64_SSE41( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); - return; - } -#endif - sum_sqr_deviation_Default( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); -} - - -void sum_sqr_deviation( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line -){ - sum_sqr_deviation( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line - ); -} -void sum_sqr_deviation( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -){ - sum_sqr_deviation( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); -} -void sum_sqr_deviation_masked( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line -){ - sum_sqr_deviation( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line - ); -} - - - -} -} +/* Sum of Squares of Deviation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_ImagePixelSumSqrDev.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_SSE41( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_AVX2( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_AVX512( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + +template +void sum_sqr_deviation( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background = 0 +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + sum_sqr_deviation_x64_AVX512( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + sum_sqr_deviation_x64_AVX2( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); + return; + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + sum_sqr_deviation_x64_SSE41( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); + return; + } +#endif + sum_sqr_deviation_Default( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); +} + + +void sum_sqr_deviation( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line +){ + sum_sqr_deviation( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line + ); +} +void sum_sqr_deviation( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +){ + sum_sqr_deviation( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); +} +void sum_sqr_deviation_masked( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line +){ + sum_sqr_deviation( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h index f4ce23a813..a668c55cd9 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev.h @@ -1,69 +1,69 @@ -/* Sum of Squares of Deviation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ImagePixelSumSqrDeviation_H -#define PokemonAutomation_Kernels_ImagePixelSumSqrDeviation_H - -#include -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - - -enum class SumSquareMode{ - REFERENCE_ALPHA, - USE_BACKGROUND, - ARBITRATE_ALPHAS, -}; - - -// -// count = # of non-zero alpha pixels in "ref". -// sumsqrs = Sum of squares of differences between "ref" and "img". -// -void sum_sqr_deviation( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line -); - - -// -// Replace all zero-alpha pixels in "ref" with "background". -// -// count = # of non-zero alpha pixels in "ref" (before background replacement.) -// sumsqrs = Sum of squares of differences between "ref" and "img". -// -void sum_sqr_deviation( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - -// -// count = # of non-zero alpha pixels in "ref". -// sumsqrs = Sum of squares of differences between "ref" and "img". -// -// Pixels where the two images disagree on alpha status are treated as maximum -// possible difference. -// -void sum_sqr_deviation_masked( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line -); - - -} -} -#endif +/* Sum of Squares of Deviation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ImagePixelSumSqrDeviation_H +#define PokemonAutomation_Kernels_ImagePixelSumSqrDeviation_H + +#include +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + + +enum class SumSquareMode{ + REFERENCE_ALPHA, + USE_BACKGROUND, + ARBITRATE_ALPHAS, +}; + + +// +// count = # of non-zero alpha pixels in "ref". +// sumsqrs = Sum of squares of differences between "ref" and "img". +// +void sum_sqr_deviation( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line +); + + +// +// Replace all zero-alpha pixels in "ref" with "background". +// +// count = # of non-zero alpha pixels in "ref" (before background replacement.) +// sumsqrs = Sum of squares of differences between "ref" and "img". +// +void sum_sqr_deviation( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + +// +// count = # of non-zero alpha pixels in "ref". +// sumsqrs = Sum of squares of differences between "ref" and "img". +// +// Pixels where the two images disagree on alpha status are treated as maximum +// possible difference. +// +void sum_sqr_deviation_masked( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line +); + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_Default.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_Default.cpp index 1bb61ff2c9..3a835eeb8c 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_Default.cpp @@ -1,120 +1,120 @@ -/* Sum of Squares of Deviation (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "Kernels_ImagePixelSumSqrDev.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -PA_FORCE_INLINE void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - uint16_t width, - const uint32_t* ref, const uint32_t* img, - uint32_t background -){ - uint32_t total = 0; - for (size_t c = 0; c < width; c++){ - uint32_t r = ref[c]; - uint32_t i = img[c]; - - uint32_t alphaR = (int32_t)r >> 31; - - if (mode == SumSquareMode::REFERENCE_ALPHA){ - r &= alphaR; - i &= alphaR; - } - if (mode == SumSquareMode::USE_BACKGROUND){ - r = alphaR ? r : background; - } - if (mode == SumSquareMode::ARBITRATE_ALPHAS){ - uint32_t alphaI = (int32_t)i >> 31; - r &= alphaR; - i &= alphaI; - alphaI ^= alphaR; - r |= alphaI; - i &= ~alphaI; - } - - uint32_t r0 = r & 0x000000ff; - uint32_t i0 = i & 0x000000ff; - uint32_t r1 = (r >> 8) & 0x000000ff; - uint32_t i1 = (i >> 8) & 0x000000ff; - uint32_t r2 = (r >> 16) & 0x000000ff; - uint32_t i2 = (i >> 16) & 0x000000ff; - - r0 -= i0; - r1 -= i1; - r2 -= i2; - - r0 *= r0; - r1 *= r1; - r2 *= r2; - - total -= alphaR; - r0 += r1; - r0 += r2; - sumsqrs += r0; - } - count += total; -} - -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -){ - if (width > 22017){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - for (size_t r = 0; r < height; r++){ - sum_sqr_deviation_Default( - count, sumsqrs, - (uint16_t)width, ref, img, background - ); - ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); - img = (const uint32_t*)((const char*)img + img_bytes_per_line); - } -} - - -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - - -} -} +/* Sum of Squares of Deviation (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "Kernels_ImagePixelSumSqrDev.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +PA_FORCE_INLINE void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + uint16_t width, + const uint32_t* ref, const uint32_t* img, + uint32_t background +){ + uint32_t total = 0; + for (size_t c = 0; c < width; c++){ + uint32_t r = ref[c]; + uint32_t i = img[c]; + + uint32_t alphaR = (int32_t)r >> 31; + + if (mode == SumSquareMode::REFERENCE_ALPHA){ + r &= alphaR; + i &= alphaR; + } + if (mode == SumSquareMode::USE_BACKGROUND){ + r = alphaR ? r : background; + } + if (mode == SumSquareMode::ARBITRATE_ALPHAS){ + uint32_t alphaI = (int32_t)i >> 31; + r &= alphaR; + i &= alphaI; + alphaI ^= alphaR; + r |= alphaI; + i &= ~alphaI; + } + + uint32_t r0 = r & 0x000000ff; + uint32_t i0 = i & 0x000000ff; + uint32_t r1 = (r >> 8) & 0x000000ff; + uint32_t i1 = (i >> 8) & 0x000000ff; + uint32_t r2 = (r >> 16) & 0x000000ff; + uint32_t i2 = (i >> 16) & 0x000000ff; + + r0 -= i0; + r1 -= i1; + r2 -= i2; + + r0 *= r0; + r1 *= r1; + r2 *= r2; + + total -= alphaR; + r0 += r1; + r0 += r2; + sumsqrs += r0; + } + count += total; +} + +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +){ + if (width > 22017){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + for (size_t r = 0; r < height; r++){ + sum_sqr_deviation_Default( + count, sumsqrs, + (uint16_t)width, ref, img, background + ); + ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); + img = (const uint32_t*)((const char*)img + img_bytes_per_line); + } +} + + +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp index f83bb514dc..bf984fb5d2 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX2.cpp @@ -1,180 +1,180 @@ -/* Sum of Squares of Deviation (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels_ImagePixelSumSqrDev.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - -template -PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX2( - __m256i& total, __m256i& sum, - __m256i r, __m256i i, - __m256i background = _mm256_setzero_si256() -){ - __m256i alphaR = _mm256_srai_epi32(r, 31); - - if (mode == SumSquareMode::REFERENCE_ALPHA){ - r = _mm256_and_si256(r, alphaR); - i = _mm256_and_si256(i, alphaR); - } - if (mode == SumSquareMode::USE_BACKGROUND){ - r = _mm256_blendv_epi8(background, r, alphaR); - } - if (mode == SumSquareMode::ARBITRATE_ALPHAS){ - __m256i alphaI = _mm256_srai_epi32(i, 31); - r = _mm256_and_si256(r, alphaR); - i = _mm256_and_si256(i, alphaI); - alphaI = _mm256_xor_si256(alphaI, alphaR); - r = _mm256_or_si256(r, alphaI); - i = _mm256_andnot_si256(alphaI, i); - } - - __m256i r0 = _mm256_and_si256(r, _mm256_set1_epi32(0x00ff00ff)); - __m256i i0 = _mm256_and_si256(i, _mm256_set1_epi32(0x00ff00ff)); -// __m256i r1 = _mm256_and_si256(_mm256_srli_epi32(r, 8), _mm256_set1_epi32(0x000000ff)); -// __m256i i1 = _mm256_and_si256(_mm256_srli_epi32(i, 8), _mm256_set1_epi32(0x000000ff)); - __m256i r1 = _mm256_shuffle_epi8(r, _mm256_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - __m256i i1 = _mm256_shuffle_epi8(i, _mm256_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - - r0 = _mm256_sub_epi16(r0, i0); - r1 = _mm256_sub_epi16(r1, i1); - - r0 = _mm256_madd_epi16(r0, r0); - r1 = _mm256_madd_epi16(r1, r1); - - total = _mm256_sub_epi32(total, alphaR); - sum = _mm256_add_epi32(sum, r0); - sum = _mm256_add_epi32(sum, r1); -} - -template -PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX2( - uint64_t& count, uint64_t& sumsqrs, - uint16_t width, - const uint32_t* ref, const uint32_t* img, - __m256i background -){ - __m256i total = _mm256_setzero_si256(); - __m256i sum = _mm256_setzero_si256(); - - const __m256i* ptrR = (const __m256i*)ref; - const __m256i* ptrI = (const __m256i*)img; - - size_t lc = width / 8; - do{ - __m256i r = _mm256_loadu_si256(ptrR); - __m256i i = _mm256_loadu_si256(ptrI); - sum_sqr_deviation_x64_AVX2(total, sum, r, i, background); - ptrR++; - ptrI++; - }while (--lc); - - if (width % 8){ - __m256i mask = _mm256_cmpgt_epi32( - _mm256_set1_epi32(width % 8), - _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) - ); - __m256i r = _mm256_maskload_epi32((const int*)ptrR, mask); - __m256i i = _mm256_maskload_epi32((const int*)ptrI, mask); - - background = _mm256_and_si256(background, mask); - sum_sqr_deviation_x64_AVX2(total, sum, r, i, background); - } - - count += reduce_add32_x64_AVX2(total); - sumsqrs += reduce_add32_x64_AVX2(sum); -} - - -template -void sum_sqr_deviation_x64_AVX2( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -){ - if (width < 8){ - sum_sqr_deviation_Default( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); - return; - } - if (width > 22017){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - __m256i vbackground = _mm256_set1_epi32(background); - for (size_t r = 0; r < height; r++){ - sum_sqr_deviation_x64_AVX2( - count, sumsqrs, - (uint16_t)width, ref, img, vbackground - ); - ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); - img = (const uint32_t*)((const char*)img + img_bytes_per_line); - } -} - - -template -void sum_sqr_deviation_x64_AVX2( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_AVX2( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_AVX2( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - - -} -} -#endif +/* Sum of Squares of Deviation (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels_ImagePixelSumSqrDev.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + +template +PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX2( + __m256i& total, __m256i& sum, + __m256i r, __m256i i, + __m256i background = _mm256_setzero_si256() +){ + __m256i alphaR = _mm256_srai_epi32(r, 31); + + if (mode == SumSquareMode::REFERENCE_ALPHA){ + r = _mm256_and_si256(r, alphaR); + i = _mm256_and_si256(i, alphaR); + } + if (mode == SumSquareMode::USE_BACKGROUND){ + r = _mm256_blendv_epi8(background, r, alphaR); + } + if (mode == SumSquareMode::ARBITRATE_ALPHAS){ + __m256i alphaI = _mm256_srai_epi32(i, 31); + r = _mm256_and_si256(r, alphaR); + i = _mm256_and_si256(i, alphaI); + alphaI = _mm256_xor_si256(alphaI, alphaR); + r = _mm256_or_si256(r, alphaI); + i = _mm256_andnot_si256(alphaI, i); + } + + __m256i r0 = _mm256_and_si256(r, _mm256_set1_epi32(0x00ff00ff)); + __m256i i0 = _mm256_and_si256(i, _mm256_set1_epi32(0x00ff00ff)); +// __m256i r1 = _mm256_and_si256(_mm256_srli_epi32(r, 8), _mm256_set1_epi32(0x000000ff)); +// __m256i i1 = _mm256_and_si256(_mm256_srli_epi32(i, 8), _mm256_set1_epi32(0x000000ff)); + __m256i r1 = _mm256_shuffle_epi8(r, _mm256_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + __m256i i1 = _mm256_shuffle_epi8(i, _mm256_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + + r0 = _mm256_sub_epi16(r0, i0); + r1 = _mm256_sub_epi16(r1, i1); + + r0 = _mm256_madd_epi16(r0, r0); + r1 = _mm256_madd_epi16(r1, r1); + + total = _mm256_sub_epi32(total, alphaR); + sum = _mm256_add_epi32(sum, r0); + sum = _mm256_add_epi32(sum, r1); +} + +template +PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX2( + uint64_t& count, uint64_t& sumsqrs, + uint16_t width, + const uint32_t* ref, const uint32_t* img, + __m256i background +){ + __m256i total = _mm256_setzero_si256(); + __m256i sum = _mm256_setzero_si256(); + + const __m256i* ptrR = (const __m256i*)ref; + const __m256i* ptrI = (const __m256i*)img; + + size_t lc = width / 8; + do{ + __m256i r = _mm256_loadu_si256(ptrR); + __m256i i = _mm256_loadu_si256(ptrI); + sum_sqr_deviation_x64_AVX2(total, sum, r, i, background); + ptrR++; + ptrI++; + }while (--lc); + + if (width % 8){ + __m256i mask = _mm256_cmpgt_epi32( + _mm256_set1_epi32(width % 8), + _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) + ); + __m256i r = _mm256_maskload_epi32((const int*)ptrR, mask); + __m256i i = _mm256_maskload_epi32((const int*)ptrI, mask); + + background = _mm256_and_si256(background, mask); + sum_sqr_deviation_x64_AVX2(total, sum, r, i, background); + } + + count += reduce_add32_x64_AVX2(total); + sumsqrs += reduce_add32_x64_AVX2(sum); +} + + +template +void sum_sqr_deviation_x64_AVX2( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +){ + if (width < 8){ + sum_sqr_deviation_Default( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); + return; + } + if (width > 22017){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + __m256i vbackground = _mm256_set1_epi32(background); + for (size_t r = 0; r < height; r++){ + sum_sqr_deviation_x64_AVX2( + count, sumsqrs, + (uint16_t)width, ref, img, vbackground + ); + ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); + img = (const uint32_t*)((const char*)img + img_bytes_per_line); + } +} + + +template +void sum_sqr_deviation_x64_AVX2( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_AVX2( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_AVX2( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp index 3b27c9ac30..8831344af7 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_AVX512.cpp @@ -1,186 +1,186 @@ -/* Sum of Squares of Deviation (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_ImagePixelSumSqrDev.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - -template -PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX512( - __m512i& total, __m512i& sum, - __m512i r, __m512i i, - __m512i background = _mm512_setzero_si512() -){ - __mmask16 alphaR = _mm512_movepi32_mask(r); - __mmask16 alphaI; - - if (mode == SumSquareMode::USE_BACKGROUND){ - r = _mm512_mask_blend_epi32(alphaR, background, r); - } - if (mode == SumSquareMode::ARBITRATE_ALPHAS){ - alphaI = _mm512_movepi32_mask(i); - } - - __m512i r0 = _mm512_and_si512(r, _mm512_set1_epi32(0x00ff00ff)); - __m512i i0 = _mm512_and_si512(i, _mm512_set1_epi32(0x00ff00ff)); -// __m512i r1 = _mm512_and_si512(_mm512_srli_epi32(r, 8), _mm512_set1_epi32(0x000000ff)); -// __m512i i1 = _mm512_and_si512(_mm512_srli_epi32(i, 8), _mm512_set1_epi32(0x000000ff)); - __m512i r1 = _mm512_shuffle_epi8(r, _mm512_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - __m512i i1 = _mm512_shuffle_epi8(i, _mm512_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - - r0 = _mm512_sub_epi16(r0, i0); - r1 = _mm512_sub_epi16(r1, i1); - - r0 = _mm512_madd_epi16(r0, r0); - r1 = _mm512_madd_epi16(r1, r1); - - r0 = _mm512_add_epi32(r0, r1); - - total = _mm512_mask_sub_epi32(total, alphaR, total, _mm512_set1_epi32(-1)); - - if (mode == SumSquareMode::REFERENCE_ALPHA){ - sum = _mm512_mask_add_epi32(sum, alphaR, sum, r0); - } - if (mode == SumSquareMode::USE_BACKGROUND){ - sum = _mm512_add_epi32(sum, r0); - } - if (mode == SumSquareMode::ARBITRATE_ALPHAS){ - r0 = _mm512_mask_mov_epi32(r0, alphaR ^ alphaI, _mm512_set1_epi32(195075)); - sum = _mm512_mask_add_epi32(sum, alphaR | alphaI, sum, r0); - } -} - -template -PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX512( - uint64_t& count, uint64_t& sumsqrs, - uint16_t width, - const uint32_t* ref, const uint32_t* img, - __m512i background -){ - __m512i total = _mm512_setzero_si512(); - __m512i sum = _mm512_setzero_si512(); - - const __m512i* ptrR = (const __m512i*)ref; - const __m512i* ptrI = (const __m512i*)img; - - size_t lc = width / 16; - do{ - __m512i r = _mm512_loadu_si512(ptrR); - __m512i i = _mm512_loadu_si512(ptrI); - sum_sqr_deviation_x64_AVX512(total, sum, r, i, background); - ptrR++; - ptrI++; - }while (--lc); - - if (width % 16){ - __mmask16 mask = (((uint32_t)1 << (width % 16))) - 1; - __m512i r = _mm512_maskz_loadu_epi32(mask, ptrR); - __m512i i = _mm512_maskz_loadu_epi32(mask, ptrI); - background = _mm512_maskz_mov_epi32(mask, background); - sum_sqr_deviation_x64_AVX512(total, sum, r, i, background); - } - - count += _mm512_reduce_add_epi32(total); - sumsqrs += _mm512_reduce_add_epi32(sum); -} - - -template -void sum_sqr_deviation_x64_AVX512( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -){ - if (width < 16){ - sum_sqr_deviation_Default( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); - return; - } - if (width > 22017){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - __m512i vbackground = _mm512_set1_epi32(background); - for (size_t r = 0; r < height; r++){ - sum_sqr_deviation_x64_AVX512( - count, sumsqrs, - (uint16_t)width, ref, img, vbackground - ); - ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); - img = (const uint32_t*)((const char*)img + img_bytes_per_line); - } -} - - -template -void sum_sqr_deviation_x64_AVX512( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_AVX512( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_AVX512( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - - -} -} -#endif +/* Sum of Squares of Deviation (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_ImagePixelSumSqrDev.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + +template +PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX512( + __m512i& total, __m512i& sum, + __m512i r, __m512i i, + __m512i background = _mm512_setzero_si512() +){ + __mmask16 alphaR = _mm512_movepi32_mask(r); + __mmask16 alphaI; + + if (mode == SumSquareMode::USE_BACKGROUND){ + r = _mm512_mask_blend_epi32(alphaR, background, r); + } + if (mode == SumSquareMode::ARBITRATE_ALPHAS){ + alphaI = _mm512_movepi32_mask(i); + } + + __m512i r0 = _mm512_and_si512(r, _mm512_set1_epi32(0x00ff00ff)); + __m512i i0 = _mm512_and_si512(i, _mm512_set1_epi32(0x00ff00ff)); +// __m512i r1 = _mm512_and_si512(_mm512_srli_epi32(r, 8), _mm512_set1_epi32(0x000000ff)); +// __m512i i1 = _mm512_and_si512(_mm512_srli_epi32(i, 8), _mm512_set1_epi32(0x000000ff)); + __m512i r1 = _mm512_shuffle_epi8(r, _mm512_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + __m512i i1 = _mm512_shuffle_epi8(i, _mm512_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + + r0 = _mm512_sub_epi16(r0, i0); + r1 = _mm512_sub_epi16(r1, i1); + + r0 = _mm512_madd_epi16(r0, r0); + r1 = _mm512_madd_epi16(r1, r1); + + r0 = _mm512_add_epi32(r0, r1); + + total = _mm512_mask_sub_epi32(total, alphaR, total, _mm512_set1_epi32(-1)); + + if (mode == SumSquareMode::REFERENCE_ALPHA){ + sum = _mm512_mask_add_epi32(sum, alphaR, sum, r0); + } + if (mode == SumSquareMode::USE_BACKGROUND){ + sum = _mm512_add_epi32(sum, r0); + } + if (mode == SumSquareMode::ARBITRATE_ALPHAS){ + r0 = _mm512_mask_mov_epi32(r0, alphaR ^ alphaI, _mm512_set1_epi32(195075)); + sum = _mm512_mask_add_epi32(sum, alphaR | alphaI, sum, r0); + } +} + +template +PA_FORCE_INLINE void sum_sqr_deviation_x64_AVX512( + uint64_t& count, uint64_t& sumsqrs, + uint16_t width, + const uint32_t* ref, const uint32_t* img, + __m512i background +){ + __m512i total = _mm512_setzero_si512(); + __m512i sum = _mm512_setzero_si512(); + + const __m512i* ptrR = (const __m512i*)ref; + const __m512i* ptrI = (const __m512i*)img; + + size_t lc = width / 16; + do{ + __m512i r = _mm512_loadu_si512(ptrR); + __m512i i = _mm512_loadu_si512(ptrI); + sum_sqr_deviation_x64_AVX512(total, sum, r, i, background); + ptrR++; + ptrI++; + }while (--lc); + + if (width % 16){ + __mmask16 mask = (((uint32_t)1 << (width % 16))) - 1; + __m512i r = _mm512_maskz_loadu_epi32(mask, ptrR); + __m512i i = _mm512_maskz_loadu_epi32(mask, ptrI); + background = _mm512_maskz_mov_epi32(mask, background); + sum_sqr_deviation_x64_AVX512(total, sum, r, i, background); + } + + count += _mm512_reduce_add_epi32(total); + sumsqrs += _mm512_reduce_add_epi32(sum); +} + + +template +void sum_sqr_deviation_x64_AVX512( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +){ + if (width < 16){ + sum_sqr_deviation_Default( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); + return; + } + if (width > 22017){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + __m512i vbackground = _mm512_set1_epi32(background); + for (size_t r = 0; r < height; r++){ + sum_sqr_deviation_x64_AVX512( + count, sumsqrs, + (uint16_t)width, ref, img, vbackground + ); + ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); + img = (const uint32_t*)((const char*)img + img_bytes_per_line); + } +} + + +template +void sum_sqr_deviation_x64_AVX512( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_AVX512( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_AVX512( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp index 84914f24ed..82d7f621c9 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqrDev_x64_SSE41.cpp @@ -1,186 +1,186 @@ -/* Sum of Squares of Deviation (x64 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels_ImagePixelSumSqrDev.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -void sum_sqr_deviation_Default( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - -template -PA_FORCE_INLINE void sum_sqr_deviation_x64_SSE41( - __m128i& total, __m128i& sum, - __m128i r, __m128i i, - __m128i background = _mm_setzero_si128() -){ - __m128i alphaR = _mm_srai_epi32(r, 31); - - if (mode == SumSquareMode::REFERENCE_ALPHA){ - r = _mm_and_si128(r, alphaR); - i = _mm_and_si128(i, alphaR); - } - if (mode == SumSquareMode::USE_BACKGROUND){ - r = _mm_blendv_epi8(background, r, alphaR); - } - if (mode == SumSquareMode::ARBITRATE_ALPHAS){ - __m128i alphaI = _mm_srai_epi32(i, 31); - r = _mm_and_si128(r, alphaR); - i = _mm_and_si128(i, alphaI); - alphaI = _mm_xor_si128(alphaI, alphaR); - r = _mm_or_si128(r, alphaI); - i = _mm_andnot_si128(alphaI, i); - } - - __m128i r0 = _mm_and_si128(r, _mm_set1_epi32(0x00ff00ff)); - __m128i i0 = _mm_and_si128(i, _mm_set1_epi32(0x00ff00ff)); -// __m128i r1 = _mm_and_si128(_mm_srli_epi32(r, 8), _mm_set1_epi32(0x000000ff)); -// __m128i i1 = _mm_and_si128(_mm_srli_epi32(i, 8), _mm_set1_epi32(0x000000ff)); - __m128i r1 = _mm_shuffle_epi8(r, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); - __m128i i1 = _mm_shuffle_epi8(i, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); - - r0 = _mm_sub_epi16(r0, i0); - r1 = _mm_sub_epi16(r1, i1); - - r0 = _mm_madd_epi16(r0, r0); - r1 = _mm_madd_epi16(r1, r1); - - total = _mm_sub_epi32(total, alphaR); - sum = _mm_add_epi32(sum, r0); - sum = _mm_add_epi32(sum, r1); -} - -template -PA_FORCE_INLINE void sum_sqr_deviation_x64_SSE41( - uint64_t& count, uint64_t& sumsqrs, - uint16_t width, - const uint32_t* ref, const uint32_t* img, - __m128i background -){ - __m128i total = _mm_setzero_si128(); - __m128i sum = _mm_setzero_si128(); - - const __m128i* ptrR = (const __m128i*)ref; - const __m128i* ptrI = (const __m128i*)img; - - size_t lc = width / 4; - do{ - __m128i r = _mm_loadu_si128(ptrR); - __m128i i = _mm_loadu_si128(ptrI); - sum_sqr_deviation_x64_SSE41(total, sum, r, i, background); - ptrR++; - ptrI++; - }while (--lc); - - if (width % 4){ -#if 0 - PartialWordLoader_SSE4 loader(width * sizeof(uint32_t) % 16); - - __m128i p = loader.load_no_read_past_end(ptrI); - __m128i m = loader.load_no_read_past_end(ptrA); - -#else - __m128i r = _mm_loadu_si128((const __m128i*)(ref + width - 4)); - __m128i i = _mm_loadu_si128((const __m128i*)(img + width - 4)); - - uint8_t shift = (uint8_t)(ref + width - (const uint32_t*)ptrR); - - __m128i s = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); - s = _mm_add_epi8(s, _mm_set1_epi8(128 - 4*shift)); - - r = _mm_shuffle_epi8(r, s); - i = _mm_shuffle_epi8(i, s); - background = _mm_shuffle_epi8(background, s); -#endif - - sum_sqr_deviation_x64_SSE41(total, sum, r, i, background); - } - - count += reduce32_x64_SSE41(total); - sumsqrs += reduce32_x64_SSE41(sum); -} - - -template -void sum_sqr_deviation_x64_SSE41( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -){ - if (width < 4){ - sum_sqr_deviation_Default( - count, sumsqrs, - width, height, - ref, ref_bytes_per_line, - img, img_bytes_per_line, - background - ); - return; - } - if (width > 22017){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - __m128i vbackground = _mm_set1_epi32(background); - for (size_t r = 0; r < height; r++){ - sum_sqr_deviation_x64_SSE41( - count, sumsqrs, - (uint16_t)width, ref, img, vbackground - ); - ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); - img = (const uint32_t*)((const char*)img + img_bytes_per_line); - } -} - - -template -void sum_sqr_deviation_x64_SSE41( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_SSE41( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); -template -void sum_sqr_deviation_x64_SSE41( - uint64_t& count, uint64_t& sumsqrs, - size_t width, size_t height, - const uint32_t* ref, size_t ref_bytes_per_line, - const uint32_t* img, size_t img_bytes_per_line, - uint32_t background -); - - - - -} -} -#endif +/* Sum of Squares of Deviation (x64 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels_ImagePixelSumSqrDev.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +void sum_sqr_deviation_Default( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + +template +PA_FORCE_INLINE void sum_sqr_deviation_x64_SSE41( + __m128i& total, __m128i& sum, + __m128i r, __m128i i, + __m128i background = _mm_setzero_si128() +){ + __m128i alphaR = _mm_srai_epi32(r, 31); + + if (mode == SumSquareMode::REFERENCE_ALPHA){ + r = _mm_and_si128(r, alphaR); + i = _mm_and_si128(i, alphaR); + } + if (mode == SumSquareMode::USE_BACKGROUND){ + r = _mm_blendv_epi8(background, r, alphaR); + } + if (mode == SumSquareMode::ARBITRATE_ALPHAS){ + __m128i alphaI = _mm_srai_epi32(i, 31); + r = _mm_and_si128(r, alphaR); + i = _mm_and_si128(i, alphaI); + alphaI = _mm_xor_si128(alphaI, alphaR); + r = _mm_or_si128(r, alphaI); + i = _mm_andnot_si128(alphaI, i); + } + + __m128i r0 = _mm_and_si128(r, _mm_set1_epi32(0x00ff00ff)); + __m128i i0 = _mm_and_si128(i, _mm_set1_epi32(0x00ff00ff)); +// __m128i r1 = _mm_and_si128(_mm_srli_epi32(r, 8), _mm_set1_epi32(0x000000ff)); +// __m128i i1 = _mm_and_si128(_mm_srli_epi32(i, 8), _mm_set1_epi32(0x000000ff)); + __m128i r1 = _mm_shuffle_epi8(r, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); + __m128i i1 = _mm_shuffle_epi8(i, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); + + r0 = _mm_sub_epi16(r0, i0); + r1 = _mm_sub_epi16(r1, i1); + + r0 = _mm_madd_epi16(r0, r0); + r1 = _mm_madd_epi16(r1, r1); + + total = _mm_sub_epi32(total, alphaR); + sum = _mm_add_epi32(sum, r0); + sum = _mm_add_epi32(sum, r1); +} + +template +PA_FORCE_INLINE void sum_sqr_deviation_x64_SSE41( + uint64_t& count, uint64_t& sumsqrs, + uint16_t width, + const uint32_t* ref, const uint32_t* img, + __m128i background +){ + __m128i total = _mm_setzero_si128(); + __m128i sum = _mm_setzero_si128(); + + const __m128i* ptrR = (const __m128i*)ref; + const __m128i* ptrI = (const __m128i*)img; + + size_t lc = width / 4; + do{ + __m128i r = _mm_loadu_si128(ptrR); + __m128i i = _mm_loadu_si128(ptrI); + sum_sqr_deviation_x64_SSE41(total, sum, r, i, background); + ptrR++; + ptrI++; + }while (--lc); + + if (width % 4){ +#if 0 + PartialWordLoader_SSE4 loader(width * sizeof(uint32_t) % 16); + + __m128i p = loader.load_no_read_past_end(ptrI); + __m128i m = loader.load_no_read_past_end(ptrA); + +#else + __m128i r = _mm_loadu_si128((const __m128i*)(ref + width - 4)); + __m128i i = _mm_loadu_si128((const __m128i*)(img + width - 4)); + + uint8_t shift = (uint8_t)(ref + width - (const uint32_t*)ptrR); + + __m128i s = _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + s = _mm_add_epi8(s, _mm_set1_epi8(128 - 4*shift)); + + r = _mm_shuffle_epi8(r, s); + i = _mm_shuffle_epi8(i, s); + background = _mm_shuffle_epi8(background, s); +#endif + + sum_sqr_deviation_x64_SSE41(total, sum, r, i, background); + } + + count += reduce32_x64_SSE41(total); + sumsqrs += reduce32_x64_SSE41(sum); +} + + +template +void sum_sqr_deviation_x64_SSE41( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +){ + if (width < 4){ + sum_sqr_deviation_Default( + count, sumsqrs, + width, height, + ref, ref_bytes_per_line, + img, img_bytes_per_line, + background + ); + return; + } + if (width > 22017){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + __m128i vbackground = _mm_set1_epi32(background); + for (size_t r = 0; r < height; r++){ + sum_sqr_deviation_x64_SSE41( + count, sumsqrs, + (uint16_t)width, ref, img, vbackground + ); + ref = (const uint32_t*)((const char*)ref + ref_bytes_per_line); + img = (const uint32_t*)((const char*)img + img_bytes_per_line); + } +} + + +template +void sum_sqr_deviation_x64_SSE41( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_SSE41( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); +template +void sum_sqr_deviation_x64_SSE41( + uint64_t& count, uint64_t& sumsqrs, + size_t width, size_t height, + const uint32_t* ref, size_t ref_bytes_per_line, + const uint32_t* img, size_t img_bytes_per_line, + uint32_t background +); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_Default.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_Default.cpp index 5a813f7de9..5ff9194175 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_Default.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_Default.cpp @@ -1,82 +1,82 @@ -/* Pixel Sum + Sum of Squares (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels_ImagePixelSumSqr.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -PA_FORCE_INLINE void pixel_sum_sqr_Default( - PixelSums& sums, - uint16_t width, - const uint32_t* image, - const uint32_t* alpha -){ - uint32_t sumB = 0; - uint32_t sumG = 0; - uint32_t sumR = 0; - uint32_t sumA = 0; - uint32_t sqrB = 0; - uint32_t sqrG = 0; - uint32_t sqrR = 0; - - for (size_t c = 0; c < width; c++){ - uint32_t p = image[c]; - int32_t m = alpha[c]; - - m = m >> 31; - p &= (uint32_t)m; - - uint32_t r0 = p & 0x000000ff; - uint32_t r1 = (p >> 8) & 0x000000ff; - uint32_t r2 = (p >> 16) & 0x000000ff; - - sumB += r0; - sumG += r1; - sumR += r2; - sumA -= m; - - r0 *= r0; - r1 *= r1; - r2 *= r2; - - sqrB += r0; - sqrG += r1; - sqrR += r2; - } - - sums.count += sumA; - sums.sumR += sumR; - sums.sumG += sumG; - sums.sumB += sumB; - sums.sqrR += sqrR; - sums.sqrG += sqrG; - sums.sqrB += sqrB; -} -void pixel_sum_sqr_Default( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -){ - if (width == 0 || height == 0){ - return; - } - if (width > 65535){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - for (size_t r = 0; r < height; r++){ - pixel_sum_sqr_Default(sums, (uint16_t)width, image, alpha); - image = (const uint32_t*)((const char*)image + image_bytes_per_row); - alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); - } -} - - -} -} +/* Pixel Sum + Sum of Squares (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels_ImagePixelSumSqr.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +PA_FORCE_INLINE void pixel_sum_sqr_Default( + PixelSums& sums, + uint16_t width, + const uint32_t* image, + const uint32_t* alpha +){ + uint32_t sumB = 0; + uint32_t sumG = 0; + uint32_t sumR = 0; + uint32_t sumA = 0; + uint32_t sqrB = 0; + uint32_t sqrG = 0; + uint32_t sqrR = 0; + + for (size_t c = 0; c < width; c++){ + uint32_t p = image[c]; + int32_t m = alpha[c]; + + m = m >> 31; + p &= (uint32_t)m; + + uint32_t r0 = p & 0x000000ff; + uint32_t r1 = (p >> 8) & 0x000000ff; + uint32_t r2 = (p >> 16) & 0x000000ff; + + sumB += r0; + sumG += r1; + sumR += r2; + sumA -= m; + + r0 *= r0; + r1 *= r1; + r2 *= r2; + + sqrB += r0; + sqrG += r1; + sqrR += r2; + } + + sums.count += sumA; + sums.sumR += sumR; + sums.sumG += sumG; + sums.sumB += sumB; + sums.sqrR += sqrR; + sums.sqrG += sqrG; + sums.sqrB += sqrB; +} +void pixel_sum_sqr_Default( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +){ + if (width == 0 || height == 0){ + return; + } + if (width > 65535){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + for (size_t r = 0; r < height; r++){ + pixel_sum_sqr_Default(sums, (uint16_t)width, image, alpha); + image = (const uint32_t*)((const char*)image + image_bytes_per_row); + alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); + } +} + + +} +} diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp index 45841de92e..673b30c724 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX2.cpp @@ -1,158 +1,158 @@ -/* Pixel Sum + Sum of Squares (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels_ImagePixelSumSqr.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -void pixel_sum_sqr_Default( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); - - - -PA_FORCE_INLINE void pixel_sum_sqr_x64_AVX2( - PixelSums& sums, - uint16_t width, - const uint32_t* image, - const uint32_t* alpha -){ - __m256i sumB = _mm256_setzero_si256(); - __m256i sumG = _mm256_setzero_si256(); - __m256i sumR = _mm256_setzero_si256(); - __m256i sumA = _mm256_setzero_si256(); - __m256i sqrB = _mm256_setzero_si256(); - __m256i sqrG = _mm256_setzero_si256(); - __m256i sqrR = _mm256_setzero_si256(); - - const __m256i* ptrI = (const __m256i*)image; - const __m256i* ptrA = (const __m256i*)alpha; - - size_t lc = width / 8; - do{ - __m256i p = _mm256_loadu_si256(ptrI); - __m256i m = _mm256_loadu_si256(ptrA); - - m = _mm256_srai_epi32(m, 31); - p = _mm256_and_si256(p, m); - - __m256i r0 = _mm256_and_si256(p, _mm256_set1_epi32(0x000000ff)); -// __m256i r1 = _mm256_and_si256(_mm256_srli_epi32(p, 8), _mm256_set1_epi32(0x000000ff)); -// __m256i r2 = _mm256_and_si256(_mm256_srli_epi32(p, 16), _mm256_set1_epi32(0x000000ff)); - __m256i r1 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - __m256i r2 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 - )); - - sumB = _mm256_add_epi32(sumB, r0); - sumG = _mm256_add_epi32(sumG, r1); - sumR = _mm256_add_epi32(sumR, r2); - sumA = _mm256_sub_epi32(sumA, m); - - r0 = _mm256_mullo_epi16(r0, r0); - r1 = _mm256_mullo_epi16(r1, r1); - r2 = _mm256_mullo_epi16(r2, r2); - - sqrB = _mm256_add_epi32(sqrB, r0); - sqrG = _mm256_add_epi32(sqrG, r1); - sqrR = _mm256_add_epi32(sqrR, r2); - - ptrI++; - ptrA++; - }while (--lc); - - if (width % 8){ - PartialWordAccess32_x64_AVX2 loader(width % 8); - - __m256i p = loader.load_i32(ptrI); - __m256i m = loader.load_i32(ptrA); - - m = _mm256_srai_epi32(m, 31); - p = _mm256_and_si256(p, m); - - __m256i r0 = _mm256_and_si256(p, _mm256_set1_epi32(0x000000ff)); -// __m256i r1 = _mm256_and_si256(_mm256_srli_epi32(p, 8), _mm256_set1_epi32(0x000000ff)); -// __m256i r2 = _mm256_and_si256(_mm256_srli_epi32(p, 16), _mm256_set1_epi32(0x000000ff)); - __m256i r1 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - __m256i r2 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 - )); - - sumB = _mm256_add_epi32(sumB, r0); - sumG = _mm256_add_epi32(sumG, r1); - sumR = _mm256_add_epi32(sumR, r2); - sumA = _mm256_sub_epi32(sumA, m); - - r0 = _mm256_mullo_epi16(r0, r0); - r1 = _mm256_mullo_epi16(r1, r1); - r2 = _mm256_mullo_epi16(r2, r2); - - sqrB = _mm256_add_epi32(sqrB, r0); - sqrG = _mm256_add_epi32(sqrG, r1); - sqrR = _mm256_add_epi32(sqrR, r2); - } - - sums.count += reduce_add32_x64_AVX2(sumA); - sums.sumR += reduce_add32_x64_AVX2(sumR); - sums.sumG += reduce_add32_x64_AVX2(sumG); - sums.sumB += reduce_add32_x64_AVX2(sumB); - sums.sqrR += reduce_add32_x64_AVX2(sqrR); - sums.sqrG += reduce_add32_x64_AVX2(sqrG); - sums.sqrB += reduce_add32_x64_AVX2(sqrB); -} -void pixel_sum_sqr_x64_AVX2( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -){ - if (width < 8){ - pixel_sum_sqr_Default( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); - return; - } - if (width > 65535){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - for (size_t r = 0; r < height; r++){ - pixel_sum_sqr_x64_AVX2(sums, (uint16_t)width, image, alpha); - image = (const uint32_t*)((const char*)image + image_bytes_per_row); - alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); - } -} - - - -} -} -#endif +/* Pixel Sum + Sum of Squares (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels_ImagePixelSumSqr.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +void pixel_sum_sqr_Default( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); + + + +PA_FORCE_INLINE void pixel_sum_sqr_x64_AVX2( + PixelSums& sums, + uint16_t width, + const uint32_t* image, + const uint32_t* alpha +){ + __m256i sumB = _mm256_setzero_si256(); + __m256i sumG = _mm256_setzero_si256(); + __m256i sumR = _mm256_setzero_si256(); + __m256i sumA = _mm256_setzero_si256(); + __m256i sqrB = _mm256_setzero_si256(); + __m256i sqrG = _mm256_setzero_si256(); + __m256i sqrR = _mm256_setzero_si256(); + + const __m256i* ptrI = (const __m256i*)image; + const __m256i* ptrA = (const __m256i*)alpha; + + size_t lc = width / 8; + do{ + __m256i p = _mm256_loadu_si256(ptrI); + __m256i m = _mm256_loadu_si256(ptrA); + + m = _mm256_srai_epi32(m, 31); + p = _mm256_and_si256(p, m); + + __m256i r0 = _mm256_and_si256(p, _mm256_set1_epi32(0x000000ff)); +// __m256i r1 = _mm256_and_si256(_mm256_srli_epi32(p, 8), _mm256_set1_epi32(0x000000ff)); +// __m256i r2 = _mm256_and_si256(_mm256_srli_epi32(p, 16), _mm256_set1_epi32(0x000000ff)); + __m256i r1 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + __m256i r2 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 + )); + + sumB = _mm256_add_epi32(sumB, r0); + sumG = _mm256_add_epi32(sumG, r1); + sumR = _mm256_add_epi32(sumR, r2); + sumA = _mm256_sub_epi32(sumA, m); + + r0 = _mm256_mullo_epi16(r0, r0); + r1 = _mm256_mullo_epi16(r1, r1); + r2 = _mm256_mullo_epi16(r2, r2); + + sqrB = _mm256_add_epi32(sqrB, r0); + sqrG = _mm256_add_epi32(sqrG, r1); + sqrR = _mm256_add_epi32(sqrR, r2); + + ptrI++; + ptrA++; + }while (--lc); + + if (width % 8){ + PartialWordAccess32_x64_AVX2 loader(width % 8); + + __m256i p = loader.load_i32(ptrI); + __m256i m = loader.load_i32(ptrA); + + m = _mm256_srai_epi32(m, 31); + p = _mm256_and_si256(p, m); + + __m256i r0 = _mm256_and_si256(p, _mm256_set1_epi32(0x000000ff)); +// __m256i r1 = _mm256_and_si256(_mm256_srli_epi32(p, 8), _mm256_set1_epi32(0x000000ff)); +// __m256i r2 = _mm256_and_si256(_mm256_srli_epi32(p, 16), _mm256_set1_epi32(0x000000ff)); + __m256i r1 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + __m256i r2 = _mm256_shuffle_epi8(p, _mm256_setr_epi8( + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 + )); + + sumB = _mm256_add_epi32(sumB, r0); + sumG = _mm256_add_epi32(sumG, r1); + sumR = _mm256_add_epi32(sumR, r2); + sumA = _mm256_sub_epi32(sumA, m); + + r0 = _mm256_mullo_epi16(r0, r0); + r1 = _mm256_mullo_epi16(r1, r1); + r2 = _mm256_mullo_epi16(r2, r2); + + sqrB = _mm256_add_epi32(sqrB, r0); + sqrG = _mm256_add_epi32(sqrG, r1); + sqrR = _mm256_add_epi32(sqrR, r2); + } + + sums.count += reduce_add32_x64_AVX2(sumA); + sums.sumR += reduce_add32_x64_AVX2(sumR); + sums.sumG += reduce_add32_x64_AVX2(sumG); + sums.sumB += reduce_add32_x64_AVX2(sumB); + sums.sqrR += reduce_add32_x64_AVX2(sqrR); + sums.sqrG += reduce_add32_x64_AVX2(sqrG); + sums.sqrB += reduce_add32_x64_AVX2(sqrB); +} +void pixel_sum_sqr_x64_AVX2( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +){ + if (width < 8){ + pixel_sum_sqr_Default( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); + return; + } + if (width > 65535){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + for (size_t r = 0; r < height; r++){ + pixel_sum_sqr_x64_AVX2(sums, (uint16_t)width, image, alpha); + image = (const uint32_t*)((const char*)image + image_bytes_per_row); + alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp index 7ad512bd20..9792801efc 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_AVX512.cpp @@ -1,164 +1,164 @@ -/* Pixel Sum + Sum of Squares (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_ImagePixelSumSqr.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -void pixel_sum_sqr_Default( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); - - - -PA_FORCE_INLINE void pixel_sum_sqr_x64_AVX512( - PixelSums& sums, - uint16_t width, - const uint32_t* image, - const uint32_t* alpha -){ - __m512i sumB = _mm512_setzero_si512(); - __m512i sumG = _mm512_setzero_si512(); - __m512i sumR = _mm512_setzero_si512(); - __m512i sumA = _mm512_setzero_si512(); - __m512i sqrB = _mm512_setzero_si512(); - __m512i sqrG = _mm512_setzero_si512(); - __m512i sqrR = _mm512_setzero_si512(); - - const __m512i* ptrI = (const __m512i*)image; - const __m512i* ptrA = (const __m512i*)alpha; - - size_t lc = width / 16; - do{ - __m512i p = _mm512_loadu_si512(ptrI); - __m512i m = _mm512_loadu_si512(ptrA); - - m = _mm512_srai_epi32(m, 31); - p = _mm512_and_si512(p, m); - - __m512i r0 = _mm512_and_si512(p, _mm512_set1_epi32(0x000000ff)); -// __m512i r1 = _mm512_and_si512(_mm512_srli_epi32(p, 8), _mm512_set1_epi32(0x000000ff)); -// __m512i r2 = _mm512_and_si512(_mm512_srli_epi32(p, 16), _mm512_set1_epi32(0x000000ff)); - __m512i r1 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - __m512i r2 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 - )); - - sumB = _mm512_add_epi32(sumB, r0); - sumG = _mm512_add_epi32(sumG, r1); - sumR = _mm512_add_epi32(sumR, r2); - sumA = _mm512_sub_epi32(sumA, m); - - r0 = _mm512_mullo_epi16(r0, r0); - r1 = _mm512_mullo_epi16(r1, r1); - r2 = _mm512_mullo_epi16(r2, r2); - - sqrB = _mm512_add_epi32(sqrB, r0); - sqrG = _mm512_add_epi32(sqrG, r1); - sqrR = _mm512_add_epi32(sqrR, r2); - - ptrI++; - ptrA++; - }while (--lc); - - if (width % 16){ - __mmask16 mask = (__mmask16)(((uint32_t)1 << (width % 16)) - 1); - __m512i p = _mm512_maskz_loadu_epi32(mask, ptrI); - __m512i m = _mm512_maskz_loadu_epi32(mask, ptrA); - - m = _mm512_srai_epi32(m, 31); - p = _mm512_and_si512(p, m); - - __m512i r0 = _mm512_and_si512(p, _mm512_set1_epi32(0x000000ff)); -// __m512i r1 = _mm512_and_si512(_mm512_srli_epi32(p, 8), _mm512_set1_epi32(0x000000ff)); -// __m512i r2 = _mm512_and_si512(_mm512_srli_epi32(p, 16), _mm512_set1_epi32(0x000000ff)); - __m512i r1 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, - 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 - )); - __m512i r2 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, - 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 - )); - - sumB = _mm512_add_epi32(sumB, r0); - sumG = _mm512_add_epi32(sumG, r1); - sumR = _mm512_add_epi32(sumR, r2); - sumA = _mm512_sub_epi32(sumA, m); - - r0 = _mm512_mullo_epi16(r0, r0); - r1 = _mm512_mullo_epi16(r1, r1); - r2 = _mm512_mullo_epi16(r2, r2); - - sqrB = _mm512_add_epi32(sqrB, r0); - sqrG = _mm512_add_epi32(sqrG, r1); - sqrR = _mm512_add_epi32(sqrR, r2); - } - - sums.count += _mm512_reduce_add_epi32(sumA); - sums.sumR += _mm512_reduce_add_epi32(sumR); - sums.sumG += _mm512_reduce_add_epi32(sumG); - sums.sumB += _mm512_reduce_add_epi32(sumB); - sums.sqrR += _mm512_reduce_add_epi32(sqrR); - sums.sqrG += _mm512_reduce_add_epi32(sqrG); - sums.sqrB += _mm512_reduce_add_epi32(sqrB); -} -void pixel_sum_sqr_x64_AVX512( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -){ - if (width < 16){ - pixel_sum_sqr_Default( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); - return; - } - if (width > 65535){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - for (size_t r = 0; r < height; r++){ - pixel_sum_sqr_x64_AVX512(sums, (uint16_t)width, image, alpha); - image = (const uint32_t*)((const char*)image + image_bytes_per_row); - alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); - } -} - - - -} -} -#endif +/* Pixel Sum + Sum of Squares (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_ImagePixelSumSqr.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +void pixel_sum_sqr_Default( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); + + + +PA_FORCE_INLINE void pixel_sum_sqr_x64_AVX512( + PixelSums& sums, + uint16_t width, + const uint32_t* image, + const uint32_t* alpha +){ + __m512i sumB = _mm512_setzero_si512(); + __m512i sumG = _mm512_setzero_si512(); + __m512i sumR = _mm512_setzero_si512(); + __m512i sumA = _mm512_setzero_si512(); + __m512i sqrB = _mm512_setzero_si512(); + __m512i sqrG = _mm512_setzero_si512(); + __m512i sqrR = _mm512_setzero_si512(); + + const __m512i* ptrI = (const __m512i*)image; + const __m512i* ptrA = (const __m512i*)alpha; + + size_t lc = width / 16; + do{ + __m512i p = _mm512_loadu_si512(ptrI); + __m512i m = _mm512_loadu_si512(ptrA); + + m = _mm512_srai_epi32(m, 31); + p = _mm512_and_si512(p, m); + + __m512i r0 = _mm512_and_si512(p, _mm512_set1_epi32(0x000000ff)); +// __m512i r1 = _mm512_and_si512(_mm512_srli_epi32(p, 8), _mm512_set1_epi32(0x000000ff)); +// __m512i r2 = _mm512_and_si512(_mm512_srli_epi32(p, 16), _mm512_set1_epi32(0x000000ff)); + __m512i r1 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + __m512i r2 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 + )); + + sumB = _mm512_add_epi32(sumB, r0); + sumG = _mm512_add_epi32(sumG, r1); + sumR = _mm512_add_epi32(sumR, r2); + sumA = _mm512_sub_epi32(sumA, m); + + r0 = _mm512_mullo_epi16(r0, r0); + r1 = _mm512_mullo_epi16(r1, r1); + r2 = _mm512_mullo_epi16(r2, r2); + + sqrB = _mm512_add_epi32(sqrB, r0); + sqrG = _mm512_add_epi32(sqrG, r1); + sqrR = _mm512_add_epi32(sqrR, r2); + + ptrI++; + ptrA++; + }while (--lc); + + if (width % 16){ + __mmask16 mask = (__mmask16)(((uint32_t)1 << (width % 16)) - 1); + __m512i p = _mm512_maskz_loadu_epi32(mask, ptrI); + __m512i m = _mm512_maskz_loadu_epi32(mask, ptrA); + + m = _mm512_srai_epi32(m, 31); + p = _mm512_and_si512(p, m); + + __m512i r0 = _mm512_and_si512(p, _mm512_set1_epi32(0x000000ff)); +// __m512i r1 = _mm512_and_si512(_mm512_srli_epi32(p, 8), _mm512_set1_epi32(0x000000ff)); +// __m512i r2 = _mm512_and_si512(_mm512_srli_epi32(p, 16), _mm512_set1_epi32(0x000000ff)); + __m512i r1 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1, + 1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1 + )); + __m512i r2 = _mm512_shuffle_epi8(p, _mm512_setr_epi8( + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1, + 2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1 + )); + + sumB = _mm512_add_epi32(sumB, r0); + sumG = _mm512_add_epi32(sumG, r1); + sumR = _mm512_add_epi32(sumR, r2); + sumA = _mm512_sub_epi32(sumA, m); + + r0 = _mm512_mullo_epi16(r0, r0); + r1 = _mm512_mullo_epi16(r1, r1); + r2 = _mm512_mullo_epi16(r2, r2); + + sqrB = _mm512_add_epi32(sqrB, r0); + sqrG = _mm512_add_epi32(sqrG, r1); + sqrR = _mm512_add_epi32(sqrR, r2); + } + + sums.count += _mm512_reduce_add_epi32(sumA); + sums.sumR += _mm512_reduce_add_epi32(sumR); + sums.sumG += _mm512_reduce_add_epi32(sumG); + sums.sumB += _mm512_reduce_add_epi32(sumB); + sums.sqrR += _mm512_reduce_add_epi32(sqrR); + sums.sqrG += _mm512_reduce_add_epi32(sqrG); + sums.sqrB += _mm512_reduce_add_epi32(sqrB); +} +void pixel_sum_sqr_x64_AVX512( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +){ + if (width < 16){ + pixel_sum_sqr_Default( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); + return; + } + if (width > 65535){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + for (size_t r = 0; r < height; r++){ + pixel_sum_sqr_x64_AVX512(sums, (uint16_t)width, image, alpha); + image = (const uint32_t*)((const char*)image + image_bytes_per_row); + alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp index 6a419a33c9..5d59b977ce 100644 --- a/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp +++ b/SerialPrograms/Source/Kernels/ImageStats/Kernels_ImagePixelSumSqr_x64_SSE41.cpp @@ -1,146 +1,146 @@ -/* Pixel Sum + Sum of Squares (x64 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels_ImagePixelSumSqr.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -void pixel_sum_sqr_Default( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -); - - - -PA_FORCE_INLINE void pixel_sum_sqr_x64_SSE41( - PixelSums& sums, - uint16_t width, - const uint32_t* image, - const uint32_t* alpha -){ - __m128i sumB = _mm_setzero_si128(); - __m128i sumG = _mm_setzero_si128(); - __m128i sumR = _mm_setzero_si128(); - __m128i sumA = _mm_setzero_si128(); - __m128i sqrB = _mm_setzero_si128(); - __m128i sqrG = _mm_setzero_si128(); - __m128i sqrR = _mm_setzero_si128(); - - const __m128i* ptrI = (const __m128i*)image; - const __m128i* ptrA = (const __m128i*)alpha; - - size_t lc = width / 4; - do{ - __m128i p = _mm_loadu_si128(ptrI); - __m128i m = _mm_loadu_si128(ptrA); - - m = _mm_srai_epi32(m, 31); - p = _mm_and_si128(p, m); - - __m128i r0 = _mm_and_si128(p, _mm_set1_epi32(0x000000ff)); -// __m128i r1 = _mm_and_si128(_mm_srli_epi32(p, 8), _mm_set1_epi32(0x000000ff)); -// __m128i r2 = _mm_and_si128(_mm_srli_epi32(p, 16), _mm_set1_epi32(0x000000ff)); - __m128i r1 = _mm_shuffle_epi8(p, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); - __m128i r2 = _mm_shuffle_epi8(p, _mm_setr_epi8(2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1)); - - sumB = _mm_add_epi32(sumB, r0); - sumG = _mm_add_epi32(sumG, r1); - sumR = _mm_add_epi32(sumR, r2); - sumA = _mm_sub_epi32(sumA, m); - - r0 = _mm_mullo_epi16(r0, r0); - r1 = _mm_mullo_epi16(r1, r1); - r2 = _mm_mullo_epi16(r2, r2); - - sqrB = _mm_add_epi32(sqrB, r0); - sqrG = _mm_add_epi32(sqrG, r1); - sqrR = _mm_add_epi32(sqrR, r2); - - ptrI++; - ptrA++; - }while (--lc); - - if (width % 4){ - PartialWordAccess_x64_SSE41 loader(width * sizeof(uint32_t) % 16); - - __m128i p = loader.load_int_no_read_past_end(ptrI); - __m128i m = loader.load_int_no_read_past_end(ptrA); - - m = _mm_srai_epi32(m, 31); - p = _mm_and_si128(p, m); - - __m128i r0 = _mm_and_si128(p, _mm_set1_epi32(0x000000ff)); -// __m128i r1 = _mm_and_si128(_mm_srli_epi32(p, 8), _mm_set1_epi32(0x000000ff)); -// __m128i r2 = _mm_and_si128(_mm_srli_epi32(p, 16), _mm_set1_epi32(0x000000ff)); - __m128i r1 = _mm_shuffle_epi8(p, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); - __m128i r2 = _mm_shuffle_epi8(p, _mm_setr_epi8(2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1)); - - sumB = _mm_add_epi32(sumB, r0); - sumG = _mm_add_epi32(sumG, r1); - sumR = _mm_add_epi32(sumR, r2); - sumA = _mm_sub_epi32(sumA, m); - - r0 = _mm_mullo_epi16(r0, r0); - r1 = _mm_mullo_epi16(r1, r1); - r2 = _mm_mullo_epi16(r2, r2); - - sqrB = _mm_add_epi32(sqrB, r0); - sqrG = _mm_add_epi32(sqrG, r1); - sqrR = _mm_add_epi32(sqrR, r2); - } - - sums.count += reduce32_x64_SSE41(sumA); - sums.sumR += reduce32_x64_SSE41(sumR); - sums.sumG += reduce32_x64_SSE41(sumG); - sums.sumB += reduce32_x64_SSE41(sumB); - sums.sqrR += reduce32_x64_SSE41(sqrR); - sums.sqrG += reduce32_x64_SSE41(sqrG); - sums.sqrB += reduce32_x64_SSE41(sqrB); -} -void pixel_sum_sqr_x64_SSE41( - PixelSums& sums, - size_t width, size_t height, - const uint32_t* image, size_t image_bytes_per_row, - const uint32_t* alpha, size_t alpha_bytes_per_row -){ - if (width < 4){ - pixel_sum_sqr_Default( - sums, - width, height, - image, image_bytes_per_row, - alpha, alpha_bytes_per_row - ); - return; - } - if (width > 65535){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); - } - for (size_t r = 0; r < height; r++){ - pixel_sum_sqr_x64_SSE41(sums, (uint16_t)width, image, alpha); - image = (const uint32_t*)((const char*)image + image_bytes_per_row); - alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); - } -} - - - -} -} -#endif +/* Pixel Sum + Sum of Squares (x64 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels_ImagePixelSumSqr.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +void pixel_sum_sqr_Default( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +); + + + +PA_FORCE_INLINE void pixel_sum_sqr_x64_SSE41( + PixelSums& sums, + uint16_t width, + const uint32_t* image, + const uint32_t* alpha +){ + __m128i sumB = _mm_setzero_si128(); + __m128i sumG = _mm_setzero_si128(); + __m128i sumR = _mm_setzero_si128(); + __m128i sumA = _mm_setzero_si128(); + __m128i sqrB = _mm_setzero_si128(); + __m128i sqrG = _mm_setzero_si128(); + __m128i sqrR = _mm_setzero_si128(); + + const __m128i* ptrI = (const __m128i*)image; + const __m128i* ptrA = (const __m128i*)alpha; + + size_t lc = width / 4; + do{ + __m128i p = _mm_loadu_si128(ptrI); + __m128i m = _mm_loadu_si128(ptrA); + + m = _mm_srai_epi32(m, 31); + p = _mm_and_si128(p, m); + + __m128i r0 = _mm_and_si128(p, _mm_set1_epi32(0x000000ff)); +// __m128i r1 = _mm_and_si128(_mm_srli_epi32(p, 8), _mm_set1_epi32(0x000000ff)); +// __m128i r2 = _mm_and_si128(_mm_srli_epi32(p, 16), _mm_set1_epi32(0x000000ff)); + __m128i r1 = _mm_shuffle_epi8(p, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); + __m128i r2 = _mm_shuffle_epi8(p, _mm_setr_epi8(2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1)); + + sumB = _mm_add_epi32(sumB, r0); + sumG = _mm_add_epi32(sumG, r1); + sumR = _mm_add_epi32(sumR, r2); + sumA = _mm_sub_epi32(sumA, m); + + r0 = _mm_mullo_epi16(r0, r0); + r1 = _mm_mullo_epi16(r1, r1); + r2 = _mm_mullo_epi16(r2, r2); + + sqrB = _mm_add_epi32(sqrB, r0); + sqrG = _mm_add_epi32(sqrG, r1); + sqrR = _mm_add_epi32(sqrR, r2); + + ptrI++; + ptrA++; + }while (--lc); + + if (width % 4){ + PartialWordAccess_x64_SSE41 loader(width * sizeof(uint32_t) % 16); + + __m128i p = loader.load_int_no_read_past_end(ptrI); + __m128i m = loader.load_int_no_read_past_end(ptrA); + + m = _mm_srai_epi32(m, 31); + p = _mm_and_si128(p, m); + + __m128i r0 = _mm_and_si128(p, _mm_set1_epi32(0x000000ff)); +// __m128i r1 = _mm_and_si128(_mm_srli_epi32(p, 8), _mm_set1_epi32(0x000000ff)); +// __m128i r2 = _mm_and_si128(_mm_srli_epi32(p, 16), _mm_set1_epi32(0x000000ff)); + __m128i r1 = _mm_shuffle_epi8(p, _mm_setr_epi8(1, -1, -1, -1, 5, -1, -1, -1, 9, -1, -1, -1, 13, -1, -1, -1)); + __m128i r2 = _mm_shuffle_epi8(p, _mm_setr_epi8(2, -1, -1, -1, 6, -1, -1, -1, 10, -1, -1, -1, 14, -1, -1, -1)); + + sumB = _mm_add_epi32(sumB, r0); + sumG = _mm_add_epi32(sumG, r1); + sumR = _mm_add_epi32(sumR, r2); + sumA = _mm_sub_epi32(sumA, m); + + r0 = _mm_mullo_epi16(r0, r0); + r1 = _mm_mullo_epi16(r1, r1); + r2 = _mm_mullo_epi16(r2, r2); + + sqrB = _mm_add_epi32(sqrB, r0); + sqrG = _mm_add_epi32(sqrG, r1); + sqrR = _mm_add_epi32(sqrR, r2); + } + + sums.count += reduce32_x64_SSE41(sumA); + sums.sumR += reduce32_x64_SSE41(sumR); + sums.sumG += reduce32_x64_SSE41(sumG); + sums.sumB += reduce32_x64_SSE41(sumB); + sums.sqrR += reduce32_x64_SSE41(sqrR); + sums.sqrG += reduce32_x64_SSE41(sqrG); + sums.sqrB += reduce32_x64_SSE41(sqrB); +} +void pixel_sum_sqr_x64_SSE41( + PixelSums& sums, + size_t width, size_t height, + const uint32_t* image, size_t image_bytes_per_row, + const uint32_t* alpha, size_t alpha_bytes_per_row +){ + if (width < 4){ + pixel_sum_sqr_Default( + sums, + width, height, + image, image_bytes_per_row, + alpha, alpha_bytes_per_row + ); + return; + } + if (width > 65535){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Width limit exceeded: " + std::to_string(width)); + } + for (size_t r = 0; r < height; r++){ + pixel_sum_sqr_x64_SSE41(sums, (uint16_t)width, image, alpha); + image = (const uint32_t*)((const char*)image + image_bytes_per_row); + alpha = (const uint32_t*)((const char*)alpha + alpha_bytes_per_row); + } +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_Alignment.h b/SerialPrograms/Source/Kernels/Kernels_Alignment.h index 28d2bf1062..83786596bf 100644 --- a/SerialPrograms/Source/Kernels/Kernels_Alignment.h +++ b/SerialPrograms/Source/Kernels/Kernels_Alignment.h @@ -1,44 +1,44 @@ -/* Alignment Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_AlignmentTools_H -#define PokemonAutomation_Kernels_AlignmentTools_H - -#include -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -template -struct SizeOf{ - static const size_t value = sizeof(T); -}; -template <> -struct SizeOf{ - static const size_t value = 1; -}; -template <> -struct SizeOf{ - static const size_t value = 1; -}; - - - -template -PA_FORCE_INLINE LengthType align_int_up(LengthType x){ - static_assert(std::is_unsigned::value, "Length must be an unsigned integer."); - static_assert((alignment & (alignment - 1)) == 0, "Alignment must be a power-of-two."); - constexpr LengthType MASK = alignment - 1; - return (x + MASK) & ~MASK; -} - - -} -} -#endif +/* Alignment Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_AlignmentTools_H +#define PokemonAutomation_Kernels_AlignmentTools_H + +#include +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +template +struct SizeOf{ + static const size_t value = sizeof(T); +}; +template <> +struct SizeOf{ + static const size_t value = 1; +}; +template <> +struct SizeOf{ + static const size_t value = 1; +}; + + + +template +PA_FORCE_INLINE LengthType align_int_up(LengthType x){ + static_assert(std::is_unsigned::value, "Length must be an unsigned integer."); + static_assert((alignment & (alignment - 1)) == 0, "Alignment must be a power-of-two."); + constexpr LengthType MASK = alignment - 1; + return (x + MASK) & ~MASK; +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_Arch (disabled).h b/SerialPrograms/Source/Kernels/Kernels_Arch (disabled).h index 08f5d52f99..6c85fc6ec1 100644 --- a/SerialPrograms/Source/Kernels/Kernels_Arch (disabled).h +++ b/SerialPrograms/Source/Kernels/Kernels_Arch (disabled).h @@ -1,59 +1,59 @@ -/* Architecture - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Arch_H -#define PokemonAutomation_Kernels_Arch_H - -// Manual ISA Override -//#define PA_Arch_x64_AVX512GF -//#define PA_Arch_x64_AVX512 -//#define PA_Arch_x64_AVX2 -#define PA_Arch_x64_SSE42 - - -// Environment implied ISAs. -#if (defined _WIN64) || (defined __x86_64) -#define PA_Arch_x64 -#endif - - - -// Implied ISAs. - -#ifdef PA_Arch_x64_AVX512GF -#define PA_Arch_x64_AVX512 -#endif - -#ifdef PA_Arch_x64_AVX512 -#define PA_Arch_x64_AVX2 -#endif - -#ifdef PA_Arch_x64_AVX2 -#define PA_Arch_x64_SSE42 -#endif - -#ifdef PA_Arch_x64_SSE42 -#define PA_Arch_x64_SSE41 -#endif - -#ifdef PA_Arch_x64_SSE41 -#define PA_Arch_x64 -#endif - - - - -namespace PokemonAutomation{ -namespace Kernels{ - - - - -} -} - - -#endif +/* Architecture + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Arch_H +#define PokemonAutomation_Kernels_Arch_H + +// Manual ISA Override +//#define PA_Arch_x64_AVX512GF +//#define PA_Arch_x64_AVX512 +//#define PA_Arch_x64_AVX2 +#define PA_Arch_x64_SSE42 + + +// Environment implied ISAs. +#if (defined _WIN64) || (defined __x86_64) +#define PA_Arch_x64 +#endif + + + +// Implied ISAs. + +#ifdef PA_Arch_x64_AVX512GF +#define PA_Arch_x64_AVX512 +#endif + +#ifdef PA_Arch_x64_AVX512 +#define PA_Arch_x64_AVX2 +#endif + +#ifdef PA_Arch_x64_AVX2 +#define PA_Arch_x64_SSE42 +#endif + +#ifdef PA_Arch_x64_SSE42 +#define PA_Arch_x64_SSE41 +#endif + +#ifdef PA_Arch_x64_SSE41 +#define PA_Arch_x64 +#endif + + + + +namespace PokemonAutomation{ +namespace Kernels{ + + + + +} +} + + +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_BitScan.h b/SerialPrograms/Source/Kernels/Kernels_BitScan.h index 0b1b96b73a..bdc96351b2 100644 --- a/SerialPrograms/Source/Kernels/Kernels_BitScan.h +++ b/SerialPrograms/Source/Kernels/Kernels_BitScan.h @@ -1,48 +1,48 @@ -/* Bit Scanning - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BitScaning_H -#define PokemonAutomation_Kernels_BitScaning_H - -#include -#include -#include "Common/Compiler.h" - -#if 0 - -#elif _WIN64 -#include -namespace PokemonAutomation{ -namespace Kernels{ - PA_FORCE_INLINE bool trailing_zeros(size_t& zeros, uint64_t x){ - unsigned long tmp; - char ret = _BitScanForward64(&tmp, x); - zeros = tmp; - return ret != 0; - } - PA_FORCE_INLINE size_t bitlength(uint64_t x){ - unsigned long index; - return _BitScanReverse64(&index, x) ? index + 1 : 0; - } -} -} -#elif __GNUC__ -namespace PokemonAutomation{ -namespace Kernels{ - PA_FORCE_INLINE bool trailing_zeros(size_t& zeros, uint64_t x){ - zeros = __builtin_ctzll(x); - return x != 0; - } - PA_FORCE_INLINE size_t bitlength(uint64_t x){ - return x == 0 ? 0 : 64 - __builtin_clzll(x); - } -} -} -#else -#error "No intrinsic for this compiler." -#endif - -#endif +/* Bit Scanning + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BitScaning_H +#define PokemonAutomation_Kernels_BitScaning_H + +#include +#include +#include "Common/Compiler.h" + +#if 0 + +#elif _WIN64 +#include +namespace PokemonAutomation{ +namespace Kernels{ + PA_FORCE_INLINE bool trailing_zeros(size_t& zeros, uint64_t x){ + unsigned long tmp; + char ret = _BitScanForward64(&tmp, x); + zeros = tmp; + return ret != 0; + } + PA_FORCE_INLINE size_t bitlength(uint64_t x){ + unsigned long index; + return _BitScanReverse64(&index, x) ? index + 1 : 0; + } +} +} +#elif __GNUC__ +namespace PokemonAutomation{ +namespace Kernels{ + PA_FORCE_INLINE bool trailing_zeros(size_t& zeros, uint64_t x){ + zeros = __builtin_ctzll(x); + return x != 0; + } + PA_FORCE_INLINE size_t bitlength(uint64_t x){ + return x == 0 ? 0 : 64 - __builtin_clzll(x); + } +} +} +#else +#error "No intrinsic for this compiler." +#endif + +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_BitSet.h b/SerialPrograms/Source/Kernels/Kernels_BitSet.h index d5ccbec7da..6df4ec2d8b 100644 --- a/SerialPrograms/Source/Kernels/Kernels_BitSet.h +++ b/SerialPrograms/Source/Kernels/Kernels_BitSet.h @@ -1,171 +1,171 @@ -/* Bit Scanning - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_BitSet_H -#define PokemonAutomation_Kernels_BitSet_H - -#include -#include -#include -#include "Common/Compiler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ - - -class BitSet{ - static constexpr size_t WORD_BITS = 32; - using vtype = uint32_t; - -public: - BitSet() = default; - BitSet(size_t bits) - : m_dense((bits + WORD_BITS - 1) / WORD_BITS) - { - memset(m_dense.data(), 0, m_dense.size() * sizeof(uint32_t)); - } - - PA_FORCE_INLINE void clear(){ - for (uint64_t index : m_sparse){ - m_dense[index / WORD_BITS] = 0; - } - m_sparse.clear(); - } - - PA_FORCE_INLINE bool get(size_t index) const{ - size_t word = index / WORD_BITS; - size_t shift = index % WORD_BITS; - uint32_t mask = (uint32_t)1 << shift; - return m_dense[word] & mask; - } - PA_FORCE_INLINE bool set(size_t index){ - size_t word = index / WORD_BITS; - size_t shift = index % WORD_BITS; - uint32_t& ref = m_dense[word]; - uint32_t value = ref; - uint32_t mask = (uint32_t)1 << shift; - if (value & mask){ - return true; - }else{ - ref = value | mask; - m_sparse.emplace_back(index); - return false; - } - } - PA_FORCE_INLINE bool pop(size_t& index){ - while (!m_sparse.empty()){ - size_t current = m_sparse.back(); - m_sparse.pop_back(); - size_t word = current / WORD_BITS; - size_t shift = current % WORD_BITS; - uint32_t& ref = m_dense[word]; - uint32_t value = ref; - uint32_t mask = (uint32_t)1 << shift; - if (value & mask){ - ref = value & ~mask; - index = current; - return true; - } - } - return false; - } - -private: - std::vector m_dense; - std::vector m_sparse; -}; - - - - -// Used in Waterfill/Kernels_Waterfill_Session.tpp to record the tile traversal during waterfill -class BitSet2D{ - static constexpr size_t WORD_BITS = 32; - using vtype = uint32_t; - -public: - BitSet2D() = default; - BitSet2D(size_t width, size_t height) - : m_width(width) - , m_dense((width*height + WORD_BITS - 1) / WORD_BITS) - { -// cout << width << " x " << height << endl; - memset(m_dense.data(), 0, m_dense.size() * sizeof(uint32_t)); - } - - PA_FORCE_INLINE void clear(){ - for (uint64_t i : m_sparse){ - size_t current_x = (uint32_t)i; - size_t current_y = (size_t)(i >> 32); - size_t index = current_x + current_y * m_width; - m_dense[index / WORD_BITS] = 0; - } - m_sparse.clear(); - } - - PA_FORCE_INLINE bool get(size_t x, size_t y) const{ - size_t index = x + y * m_width; - size_t word = index / WORD_BITS; - size_t shift = index % WORD_BITS; - uint32_t mask = (uint32_t)1 << shift; - return m_dense[word] & mask; - } - PA_FORCE_INLINE bool set(size_t x, size_t y){ - size_t index = x + y * m_width; - size_t word = index / WORD_BITS; - size_t shift = index % WORD_BITS; - uint32_t& ref = m_dense[word]; - uint32_t value = ref; - uint32_t mask = (uint32_t)1 << shift; - if (value & mask){ - return true; - }else{ - ref = value | mask; - m_sparse.emplace_back(x | ((uint64_t)y << 32)); - return false; - } - } - PA_FORCE_INLINE bool pop(size_t& x, size_t& y){ - while (!m_sparse.empty()){ - size_t current = m_sparse.back(); - m_sparse.pop_back(); - size_t current_x = (uint32_t)current; - size_t current_y = (size_t)(current >> 32); - size_t index = current_x + current_y * m_width; - size_t word = index / WORD_BITS; - size_t shift = index % WORD_BITS; - uint32_t& ref = m_dense[word]; - uint32_t value = ref; - uint32_t mask = (uint32_t)1 << shift; - if (value & mask){ - ref = value & ~mask; - x = current_x; - y = current_y; - return true; - } - } - return false; - } - - -private: - size_t m_width; - std::vector m_dense; - std::vector m_sparse; -}; - - - - - - -} -} -#endif +/* Bit Scanning + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_BitSet_H +#define PokemonAutomation_Kernels_BitSet_H + +#include +#include +#include +#include "Common/Compiler.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ + + +class BitSet{ + static constexpr size_t WORD_BITS = 32; + using vtype = uint32_t; + +public: + BitSet() = default; + BitSet(size_t bits) + : m_dense((bits + WORD_BITS - 1) / WORD_BITS) + { + memset(m_dense.data(), 0, m_dense.size() * sizeof(uint32_t)); + } + + PA_FORCE_INLINE void clear(){ + for (uint64_t index : m_sparse){ + m_dense[index / WORD_BITS] = 0; + } + m_sparse.clear(); + } + + PA_FORCE_INLINE bool get(size_t index) const{ + size_t word = index / WORD_BITS; + size_t shift = index % WORD_BITS; + uint32_t mask = (uint32_t)1 << shift; + return m_dense[word] & mask; + } + PA_FORCE_INLINE bool set(size_t index){ + size_t word = index / WORD_BITS; + size_t shift = index % WORD_BITS; + uint32_t& ref = m_dense[word]; + uint32_t value = ref; + uint32_t mask = (uint32_t)1 << shift; + if (value & mask){ + return true; + }else{ + ref = value | mask; + m_sparse.emplace_back(index); + return false; + } + } + PA_FORCE_INLINE bool pop(size_t& index){ + while (!m_sparse.empty()){ + size_t current = m_sparse.back(); + m_sparse.pop_back(); + size_t word = current / WORD_BITS; + size_t shift = current % WORD_BITS; + uint32_t& ref = m_dense[word]; + uint32_t value = ref; + uint32_t mask = (uint32_t)1 << shift; + if (value & mask){ + ref = value & ~mask; + index = current; + return true; + } + } + return false; + } + +private: + std::vector m_dense; + std::vector m_sparse; +}; + + + + +// Used in Waterfill/Kernels_Waterfill_Session.tpp to record the tile traversal during waterfill +class BitSet2D{ + static constexpr size_t WORD_BITS = 32; + using vtype = uint32_t; + +public: + BitSet2D() = default; + BitSet2D(size_t width, size_t height) + : m_width(width) + , m_dense((width*height + WORD_BITS - 1) / WORD_BITS) + { +// cout << width << " x " << height << endl; + memset(m_dense.data(), 0, m_dense.size() * sizeof(uint32_t)); + } + + PA_FORCE_INLINE void clear(){ + for (uint64_t i : m_sparse){ + size_t current_x = (uint32_t)i; + size_t current_y = (size_t)(i >> 32); + size_t index = current_x + current_y * m_width; + m_dense[index / WORD_BITS] = 0; + } + m_sparse.clear(); + } + + PA_FORCE_INLINE bool get(size_t x, size_t y) const{ + size_t index = x + y * m_width; + size_t word = index / WORD_BITS; + size_t shift = index % WORD_BITS; + uint32_t mask = (uint32_t)1 << shift; + return m_dense[word] & mask; + } + PA_FORCE_INLINE bool set(size_t x, size_t y){ + size_t index = x + y * m_width; + size_t word = index / WORD_BITS; + size_t shift = index % WORD_BITS; + uint32_t& ref = m_dense[word]; + uint32_t value = ref; + uint32_t mask = (uint32_t)1 << shift; + if (value & mask){ + return true; + }else{ + ref = value | mask; + m_sparse.emplace_back(x | ((uint64_t)y << 32)); + return false; + } + } + PA_FORCE_INLINE bool pop(size_t& x, size_t& y){ + while (!m_sparse.empty()){ + size_t current = m_sparse.back(); + m_sparse.pop_back(); + size_t current_x = (uint32_t)current; + size_t current_y = (size_t)(current >> 32); + size_t index = current_x + current_y * m_width; + size_t word = index / WORD_BITS; + size_t shift = index % WORD_BITS; + uint32_t& ref = m_dense[word]; + uint32_t value = ref; + uint32_t mask = (uint32_t)1 << shift; + if (value & mask){ + ref = value & ~mask; + x = current_x; + y = current_y; + return true; + } + } + return false; + } + + +private: + size_t m_width; + std::vector m_dense; + std::vector m_sparse; +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_arm64_NEON.h b/SerialPrograms/Source/Kernels/Kernels_arm64_NEON.h index ba4d97c963..6ca58da2ba 100644 --- a/SerialPrograms/Source/Kernels/Kernels_arm64_NEON.h +++ b/SerialPrograms/Source/Kernels/Kernels_arm64_NEON.h @@ -1,107 +1,107 @@ -/* Kernels (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_arm64_NEON_H -#define PokemonAutomation_Kernels_arm64_NEON_H - -#include -#include -#include "Common/Compiler.h" - -#include - -namespace PokemonAutomation{ -namespace Kernels{ - -// Cout the four floats in float32x4_t, separated by " " -inline static void print(const float32x4_t& x){ - union{ - float32x4_t v; - float s[4]; - }; - v = x; - for (int i = 0; i < 4; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - -// Cout the 16 uint8 in uint8x16_t, separated by " " -inline static void print_u8(uint8x16_t x){ - for (int i = 0; i < 16; i++){ - std::cout << (int)x[i] << " "; - } - std::cout << std::endl; -} - -// Cout the 8 uint16 in uint16x8_t, separated by " " -inline static void print_u16(const uint16x8_t& x){ - union{ - uint16x8_t v; - uint16_t s[8]; - }; - v = x; - for (int i = 0; i < 8; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - -// Cout the 4 uint32 in uint32x4_t, separated by " " -inline static void print_u32(const uint32x4_t& x){ - union{ - uint32x4_t v; - uint32_t s[4]; - }; - v = x; - for (int i = 0; i < 4; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - -// Cout the 2 uint64 in uint64x2_t, separated by " " -inline static void print_u64(const uint64x2_t& x){ - union{ - uint64x2_t v; - uint64_t s[2]; - }; - v = x; - for (int i = 0; i < 2; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - - -// Add all four uint32 together -PA_FORCE_INLINE uint64_t reduce32_arm64_NEON(uint32x4_t x){ - uint64_t ret = vgetq_lane_u32(x, 0); - ret += vgetq_lane_u32(x, 1); - ret += vgetq_lane_u32(x, 2); - ret += vgetq_lane_u32(x, 3); - return ret; -} - -// Create a new uint64x2_t vector from the lower half of r0 and r1 (r1 portion on higher resulting bits), -// and one new uint64x2_t vector from the upper half of them. -// Assign r0 to the former, r1 to the letter. -PA_FORCE_INLINE void transpose_u64_2x2_NEON(uint64x2_t& r0, uint64x2_t& r1){ - int64x1_t r0_l = vget_low_u64(r0); - int64x1_t r1_l = vget_low_u64(r1); - int64x1_t r0_h = vget_high_u64(r0); - int64x1_t r1_h = vget_high_u64(r1); - - r0 = vcombine_u64(r0_l, r1_l); - r1 = vcombine_u64(r0_h, r1_h); -} - - - - -} -} -#endif +/* Kernels (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_arm64_NEON_H +#define PokemonAutomation_Kernels_arm64_NEON_H + +#include +#include +#include "Common/Compiler.h" + +#include + +namespace PokemonAutomation{ +namespace Kernels{ + +// Cout the four floats in float32x4_t, separated by " " +inline static void print(const float32x4_t& x){ + union{ + float32x4_t v; + float s[4]; + }; + v = x; + for (int i = 0; i < 4; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + +// Cout the 16 uint8 in uint8x16_t, separated by " " +inline static void print_u8(uint8x16_t x){ + for (int i = 0; i < 16; i++){ + std::cout << (int)x[i] << " "; + } + std::cout << std::endl; +} + +// Cout the 8 uint16 in uint16x8_t, separated by " " +inline static void print_u16(const uint16x8_t& x){ + union{ + uint16x8_t v; + uint16_t s[8]; + }; + v = x; + for (int i = 0; i < 8; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + +// Cout the 4 uint32 in uint32x4_t, separated by " " +inline static void print_u32(const uint32x4_t& x){ + union{ + uint32x4_t v; + uint32_t s[4]; + }; + v = x; + for (int i = 0; i < 4; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + +// Cout the 2 uint64 in uint64x2_t, separated by " " +inline static void print_u64(const uint64x2_t& x){ + union{ + uint64x2_t v; + uint64_t s[2]; + }; + v = x; + for (int i = 0; i < 2; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + + +// Add all four uint32 together +PA_FORCE_INLINE uint64_t reduce32_arm64_NEON(uint32x4_t x){ + uint64_t ret = vgetq_lane_u32(x, 0); + ret += vgetq_lane_u32(x, 1); + ret += vgetq_lane_u32(x, 2); + ret += vgetq_lane_u32(x, 3); + return ret; +} + +// Create a new uint64x2_t vector from the lower half of r0 and r1 (r1 portion on higher resulting bits), +// and one new uint64x2_t vector from the upper half of them. +// Assign r0 to the former, r1 to the letter. +PA_FORCE_INLINE void transpose_u64_2x2_NEON(uint64x2_t& r0, uint64x2_t& r1){ + int64x1_t r0_l = vget_low_u64(r0); + int64x1_t r1_l = vget_low_u64(r1); + int64x1_t r0_h = vget_high_u64(r0); + int64x1_t r1_h = vget_high_u64(r1); + + r0 = vcombine_u64(r0_l, r1_l); + r1 = vcombine_u64(r0_h, r1_h); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_x64_AVX2.h b/SerialPrograms/Source/Kernels/Kernels_x64_AVX2.h index f660e698da..13044730b4 100644 --- a/SerialPrograms/Source/Kernels/Kernels_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/Kernels_x64_AVX2.h @@ -1,145 +1,145 @@ -/* Kernels (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_x64_AVX2_H -#define PokemonAutomation_Kernels_x64_AVX2_H - -#include -#include -#include "Common/Compiler.h" -#include "Kernels_x64_SSE41.h" - -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - -inline static void print(const __m256& x){ - union{ - __m256 v; - float s[8]; - }; - v = x; - for (int i = 0; i < 8; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u8(__m256i x){ - for (int i = 0; i < 32; i++){ - std::cout << (int)((const unsigned char*)&x)[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u16(const __m256i& x){ - union{ - __m256i v; - uint16_t s[16]; - }; - v = x; - for (int i = 0; i < 16; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_s16(const __m256i& x){ - union{ - __m256i v; - int16_t s[16]; - }; - v = x; - for (int i = 0; i < 16; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u32(const __m256i& x){ - union{ - __m256i v; - uint32_t s[8]; - }; - v = x; - for (int i = 0; i < 8; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u64(const __m256i& x){ - union{ - __m256i v; - uint64_t s[4]; - }; - v = x; - for (int i = 0; i < 4; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - - - -PA_FORCE_INLINE float reduce32_x64_AVX(__m256 x){ - __m128 v = _mm_add_ps( - _mm256_castps256_ps128(x), - _mm256_extractf128_ps(x, 1) - ); - return reduce32_x64_SSE(v); -} -PA_FORCE_INLINE uint64_t reduce_add32_x64_AVX2(__m256i ymm){ - __m128i xmm = _mm_add_epi32( - _mm256_castsi256_si128(ymm), - _mm256_extracti128_si256(ymm, 1) - ); - return reduce32_x64_SSE41(xmm); -} -PA_FORCE_INLINE uint64_t reduce_add64_x64_AVX2(__m256i y){ - __m128i x = _mm_add_epi64( - _mm256_castsi256_si128(y), - _mm256_extracti128_si256(y, 1) - ); - x = _mm_add_epi64(x, _mm_unpackhi_epi64(x, x)); - return _mm_cvtsi128_si64(x); -} -PA_FORCE_INLINE uint64_t reduce_or64_x64_AVX2(__m256i y){ - __m128i x = _mm_or_si128( - _mm256_castsi256_si128(y), - _mm256_extracti128_si256(y, 1) - ); - x = _mm_or_si128(x, _mm_unpackhi_epi64(x, x)); - return _mm_cvtsi128_si64(x); -} - - -PA_FORCE_INLINE __m256i mm256_permuteaj64_00(__m256i a, __m256i b){ - return _mm256_unpacklo_epi64(a, b); -} -PA_FORCE_INLINE __m256i mm256_permuteaj64_11(__m256i a, __m256i b){ - return _mm256_unpackhi_epi64(a, b); -} -PA_FORCE_INLINE __m256i mm256_permuteaj128_00(__m256i a, __m256i b){ - return _mm256_permute2x128_si256(a, b, 32); -} -PA_FORCE_INLINE __m256i mm256_permuteaj128_11(__m256i a, __m256i b){ - return _mm256_permute2x128_si256(a, b, 49); -} -PA_FORCE_INLINE void transpose_i64_4x4_AVX2(__m256i& r0, __m256i& r1, __m256i& r2, __m256i& r3){ - __m256i a0, a1, a2, a3; - a0 = mm256_permuteaj128_00(r0, r2); - a1 = mm256_permuteaj128_11(r0, r2); - a2 = mm256_permuteaj128_00(r1, r3); - a3 = mm256_permuteaj128_11(r1, r3); - r0 = mm256_permuteaj64_00(a0, a2); - r1 = mm256_permuteaj64_11(a0, a2); - r2 = mm256_permuteaj64_00(a1, a3); - r3 = mm256_permuteaj64_11(a1, a3); -} - - - -} -} -#endif +/* Kernels (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_x64_AVX2_H +#define PokemonAutomation_Kernels_x64_AVX2_H + +#include +#include +#include "Common/Compiler.h" +#include "Kernels_x64_SSE41.h" + +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + +inline static void print(const __m256& x){ + union{ + __m256 v; + float s[8]; + }; + v = x; + for (int i = 0; i < 8; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u8(__m256i x){ + for (int i = 0; i < 32; i++){ + std::cout << (int)((const unsigned char*)&x)[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u16(const __m256i& x){ + union{ + __m256i v; + uint16_t s[16]; + }; + v = x; + for (int i = 0; i < 16; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_s16(const __m256i& x){ + union{ + __m256i v; + int16_t s[16]; + }; + v = x; + for (int i = 0; i < 16; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u32(const __m256i& x){ + union{ + __m256i v; + uint32_t s[8]; + }; + v = x; + for (int i = 0; i < 8; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u64(const __m256i& x){ + union{ + __m256i v; + uint64_t s[4]; + }; + v = x; + for (int i = 0; i < 4; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + + + +PA_FORCE_INLINE float reduce32_x64_AVX(__m256 x){ + __m128 v = _mm_add_ps( + _mm256_castps256_ps128(x), + _mm256_extractf128_ps(x, 1) + ); + return reduce32_x64_SSE(v); +} +PA_FORCE_INLINE uint64_t reduce_add32_x64_AVX2(__m256i ymm){ + __m128i xmm = _mm_add_epi32( + _mm256_castsi256_si128(ymm), + _mm256_extracti128_si256(ymm, 1) + ); + return reduce32_x64_SSE41(xmm); +} +PA_FORCE_INLINE uint64_t reduce_add64_x64_AVX2(__m256i y){ + __m128i x = _mm_add_epi64( + _mm256_castsi256_si128(y), + _mm256_extracti128_si256(y, 1) + ); + x = _mm_add_epi64(x, _mm_unpackhi_epi64(x, x)); + return _mm_cvtsi128_si64(x); +} +PA_FORCE_INLINE uint64_t reduce_or64_x64_AVX2(__m256i y){ + __m128i x = _mm_or_si128( + _mm256_castsi256_si128(y), + _mm256_extracti128_si256(y, 1) + ); + x = _mm_or_si128(x, _mm_unpackhi_epi64(x, x)); + return _mm_cvtsi128_si64(x); +} + + +PA_FORCE_INLINE __m256i mm256_permuteaj64_00(__m256i a, __m256i b){ + return _mm256_unpacklo_epi64(a, b); +} +PA_FORCE_INLINE __m256i mm256_permuteaj64_11(__m256i a, __m256i b){ + return _mm256_unpackhi_epi64(a, b); +} +PA_FORCE_INLINE __m256i mm256_permuteaj128_00(__m256i a, __m256i b){ + return _mm256_permute2x128_si256(a, b, 32); +} +PA_FORCE_INLINE __m256i mm256_permuteaj128_11(__m256i a, __m256i b){ + return _mm256_permute2x128_si256(a, b, 49); +} +PA_FORCE_INLINE void transpose_i64_4x4_AVX2(__m256i& r0, __m256i& r1, __m256i& r2, __m256i& r3){ + __m256i a0, a1, a2, a3; + a0 = mm256_permuteaj128_00(r0, r2); + a1 = mm256_permuteaj128_11(r0, r2); + a2 = mm256_permuteaj128_00(r1, r3); + a3 = mm256_permuteaj128_11(r1, r3); + r0 = mm256_permuteaj64_00(a0, a2); + r1 = mm256_permuteaj64_11(a0, a2); + r2 = mm256_permuteaj64_00(a1, a3); + r3 = mm256_permuteaj64_11(a1, a3); +} + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_x64_AVX512.h b/SerialPrograms/Source/Kernels/Kernels_x64_AVX512.h index 0ea00bc8a8..75d8fd31be 100644 --- a/SerialPrograms/Source/Kernels/Kernels_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/Kernels_x64_AVX512.h @@ -1,134 +1,134 @@ -/* Kernels (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_x64_AVX512_H -#define PokemonAutomation_Kernels_x64_AVX512_H - -#include -#include -#include "Common/Compiler.h" - -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - -inline void print_u8(__m512i x){ - for (int i = 0; i < 64; i++){ - std::cout << (int)((const unsigned char*)&x)[i] << " "; - } - std::cout << std::endl; -} -inline void print_u16(const __m512i& x){ - union{ - __m512i v; - uint16_t s[32]; - }; - v = x; - for (int i = 0; i < 32; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline void print_u32(const __m512i& x){ - union{ - __m512i v; - uint32_t s[16]; - }; - v = x; - for (int i = 0; i < 16; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline void print_u64(const __m512i& x){ - union{ - __m512i v; - uint64_t s[8]; - }; - v = x; - for (int i = 0; i < 8; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - - - -#define _mm512_setr_epi16( \ - e00, e01, e02, e03, e04, e05, e06, e07, \ - e08, e09, e10, e11, e12, e13, e14, e15, \ - e16, e17, e18, e19, e20, e21, e22, e23, \ - e24, e25, e26, e27, e28, e29, e30, e31 \ -) \ - _mm512_setr_epi32( \ - (uint16_t)(e00) | ((uint32_t)(e01) << 16), (uint16_t)(e02) | ((uint32_t)(e03) << 16), (uint16_t)(e04) | ((uint32_t)(e05) << 16), (uint16_t)(e06) | ((uint32_t)(e07) << 16), \ - (uint16_t)(e08) | ((uint32_t)(e09) << 16), (uint16_t)(e10) | ((uint32_t)(e11) << 16), (uint16_t)(e12) | ((uint32_t)(e13) << 16), (uint16_t)(e14) | ((uint32_t)(e15) << 16), \ - (uint16_t)(e16) | ((uint32_t)(e17) << 16), (uint16_t)(e18) | ((uint32_t)(e19) << 16), (uint16_t)(e20) | ((uint32_t)(e21) << 16), (uint16_t)(e22) | ((uint32_t)(e23) << 16), \ - (uint16_t)(e24) | ((uint32_t)(e25) << 16), (uint16_t)(e26) | ((uint32_t)(e27) << 16), (uint16_t)(e28) | ((uint32_t)(e29) << 16), (uint16_t)(e30) | ((uint32_t)(e31) << 16) \ - ) -#define _mm512_setr_epi8( \ - e00, e01, e02, e03, e04, e05, e06, e07, \ - e08, e09, e10, e11, e12, e13, e14, e15, \ - e16, e17, e18, e19, e20, e21, e22, e23, \ - e24, e25, e26, e27, e28, e29, e30, e31, \ - e32, e33, e34, e35, e36, e37, e38, e39, \ - e40, e41, e42, e43, e44, e45, e46, e47, \ - e48, e49, e50, e51, e52, e53, e54, e55, \ - e56, e57, e58, e59, e60, e61, e62, e63 \ -) \ - _mm512_setr_epi16( \ - (uint8_t)(e00) | ((uint8_t)(e01) << 8), (uint8_t)(e02) | ((uint8_t)(e03) << 8), (uint8_t)(e04) | ((uint8_t)(e05) << 8), (uint8_t)(e06) | ((uint8_t)(e07) << 8), \ - (uint8_t)(e08) | ((uint8_t)(e09) << 8), (uint8_t)(e10) | ((uint8_t)(e11) << 8), (uint8_t)(e12) | ((uint8_t)(e13) << 8), (uint8_t)(e14) | ((uint8_t)(e15) << 8), \ - (uint8_t)(e16) | ((uint8_t)(e17) << 8), (uint8_t)(e18) | ((uint8_t)(e19) << 8), (uint8_t)(e20) | ((uint8_t)(e21) << 8), (uint8_t)(e22) | ((uint8_t)(e23) << 8), \ - (uint8_t)(e24) | ((uint8_t)(e25) << 8), (uint8_t)(e26) | ((uint8_t)(e27) << 8), (uint8_t)(e28) | ((uint8_t)(e29) << 8), (uint8_t)(e30) | ((uint8_t)(e31) << 8), \ - (uint8_t)(e32) | ((uint8_t)(e33) << 8), (uint8_t)(e34) | ((uint8_t)(e35) << 8), (uint8_t)(e36) | ((uint8_t)(e37) << 8), (uint8_t)(e38) | ((uint8_t)(e39) << 8), \ - (uint8_t)(e40) | ((uint8_t)(e41) << 8), (uint8_t)(e42) | ((uint8_t)(e43) << 8), (uint8_t)(e44) | ((uint8_t)(e45) << 8), (uint8_t)(e46) | ((uint8_t)(e47) << 8), \ - (uint8_t)(e48) | ((uint8_t)(e49) << 8), (uint8_t)(e50) | ((uint8_t)(e51) << 8), (uint8_t)(e52) | ((uint8_t)(e53) << 8), (uint8_t)(e54) | ((uint8_t)(e55) << 8), \ - (uint8_t)(e56) | ((uint8_t)(e57) << 8), (uint8_t)(e58) | ((uint8_t)(e59) << 8), (uint8_t)(e60) | ((uint8_t)(e61) << 8), (uint8_t)(e62) | ((uint8_t)(e63) << 8) \ - ) - - - -PA_FORCE_INLINE void transpose_i64_8x8_AVX512( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, - __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 -){ - __m512i a0, a1; - - a0 = _mm512_unpackhi_epi64(r0, r1); - r1 = _mm512_unpacklo_epi64(r0, r1); - a1 = _mm512_unpackhi_epi64(r2, r3); - r2 = _mm512_unpacklo_epi64(r2, r3); - r0 = _mm512_unpackhi_epi64(r4, r5); - r4 = _mm512_unpacklo_epi64(r4, r5); - r5 = _mm512_unpacklo_epi64(r6, r7); - r7 = _mm512_unpackhi_epi64(r6, r7); - - r3 = _mm512_shuffle_i64x2(r1, r2, 221); - r1 = _mm512_shuffle_i64x2(r1, r2, 136); - r2 = _mm512_shuffle_i64x2(a0, a1, 136); - a1 = _mm512_shuffle_i64x2(a0, a1, 221); - r6 = _mm512_shuffle_i64x2(r4, r5, 221); - r4 = _mm512_shuffle_i64x2(r4, r5, 136); - r5 = _mm512_shuffle_i64x2(r0, r7, 136); - r7 = _mm512_shuffle_i64x2(r0, r7, 221); - - r0 = _mm512_shuffle_i64x2(r1, r4, 136); - r4 = _mm512_shuffle_i64x2(r1, r4, 221); - r1 = _mm512_shuffle_i64x2(r2, r5, 136); - r5 = _mm512_shuffle_i64x2(r2, r5, 221); - r2 = _mm512_shuffle_i64x2(r3, r6, 136); - r6 = _mm512_shuffle_i64x2(r3, r6, 221); - r3 = _mm512_shuffle_i64x2(a1, r7, 136); - r7 = _mm512_shuffle_i64x2(a1, r7, 221); -} - - -} -} -#endif +/* Kernels (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_x64_AVX512_H +#define PokemonAutomation_Kernels_x64_AVX512_H + +#include +#include +#include "Common/Compiler.h" + +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + +inline void print_u8(__m512i x){ + for (int i = 0; i < 64; i++){ + std::cout << (int)((const unsigned char*)&x)[i] << " "; + } + std::cout << std::endl; +} +inline void print_u16(const __m512i& x){ + union{ + __m512i v; + uint16_t s[32]; + }; + v = x; + for (int i = 0; i < 32; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline void print_u32(const __m512i& x){ + union{ + __m512i v; + uint32_t s[16]; + }; + v = x; + for (int i = 0; i < 16; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline void print_u64(const __m512i& x){ + union{ + __m512i v; + uint64_t s[8]; + }; + v = x; + for (int i = 0; i < 8; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + + + +#define _mm512_setr_epi16( \ + e00, e01, e02, e03, e04, e05, e06, e07, \ + e08, e09, e10, e11, e12, e13, e14, e15, \ + e16, e17, e18, e19, e20, e21, e22, e23, \ + e24, e25, e26, e27, e28, e29, e30, e31 \ +) \ + _mm512_setr_epi32( \ + (uint16_t)(e00) | ((uint32_t)(e01) << 16), (uint16_t)(e02) | ((uint32_t)(e03) << 16), (uint16_t)(e04) | ((uint32_t)(e05) << 16), (uint16_t)(e06) | ((uint32_t)(e07) << 16), \ + (uint16_t)(e08) | ((uint32_t)(e09) << 16), (uint16_t)(e10) | ((uint32_t)(e11) << 16), (uint16_t)(e12) | ((uint32_t)(e13) << 16), (uint16_t)(e14) | ((uint32_t)(e15) << 16), \ + (uint16_t)(e16) | ((uint32_t)(e17) << 16), (uint16_t)(e18) | ((uint32_t)(e19) << 16), (uint16_t)(e20) | ((uint32_t)(e21) << 16), (uint16_t)(e22) | ((uint32_t)(e23) << 16), \ + (uint16_t)(e24) | ((uint32_t)(e25) << 16), (uint16_t)(e26) | ((uint32_t)(e27) << 16), (uint16_t)(e28) | ((uint32_t)(e29) << 16), (uint16_t)(e30) | ((uint32_t)(e31) << 16) \ + ) +#define _mm512_setr_epi8( \ + e00, e01, e02, e03, e04, e05, e06, e07, \ + e08, e09, e10, e11, e12, e13, e14, e15, \ + e16, e17, e18, e19, e20, e21, e22, e23, \ + e24, e25, e26, e27, e28, e29, e30, e31, \ + e32, e33, e34, e35, e36, e37, e38, e39, \ + e40, e41, e42, e43, e44, e45, e46, e47, \ + e48, e49, e50, e51, e52, e53, e54, e55, \ + e56, e57, e58, e59, e60, e61, e62, e63 \ +) \ + _mm512_setr_epi16( \ + (uint8_t)(e00) | ((uint8_t)(e01) << 8), (uint8_t)(e02) | ((uint8_t)(e03) << 8), (uint8_t)(e04) | ((uint8_t)(e05) << 8), (uint8_t)(e06) | ((uint8_t)(e07) << 8), \ + (uint8_t)(e08) | ((uint8_t)(e09) << 8), (uint8_t)(e10) | ((uint8_t)(e11) << 8), (uint8_t)(e12) | ((uint8_t)(e13) << 8), (uint8_t)(e14) | ((uint8_t)(e15) << 8), \ + (uint8_t)(e16) | ((uint8_t)(e17) << 8), (uint8_t)(e18) | ((uint8_t)(e19) << 8), (uint8_t)(e20) | ((uint8_t)(e21) << 8), (uint8_t)(e22) | ((uint8_t)(e23) << 8), \ + (uint8_t)(e24) | ((uint8_t)(e25) << 8), (uint8_t)(e26) | ((uint8_t)(e27) << 8), (uint8_t)(e28) | ((uint8_t)(e29) << 8), (uint8_t)(e30) | ((uint8_t)(e31) << 8), \ + (uint8_t)(e32) | ((uint8_t)(e33) << 8), (uint8_t)(e34) | ((uint8_t)(e35) << 8), (uint8_t)(e36) | ((uint8_t)(e37) << 8), (uint8_t)(e38) | ((uint8_t)(e39) << 8), \ + (uint8_t)(e40) | ((uint8_t)(e41) << 8), (uint8_t)(e42) | ((uint8_t)(e43) << 8), (uint8_t)(e44) | ((uint8_t)(e45) << 8), (uint8_t)(e46) | ((uint8_t)(e47) << 8), \ + (uint8_t)(e48) | ((uint8_t)(e49) << 8), (uint8_t)(e50) | ((uint8_t)(e51) << 8), (uint8_t)(e52) | ((uint8_t)(e53) << 8), (uint8_t)(e54) | ((uint8_t)(e55) << 8), \ + (uint8_t)(e56) | ((uint8_t)(e57) << 8), (uint8_t)(e58) | ((uint8_t)(e59) << 8), (uint8_t)(e60) | ((uint8_t)(e61) << 8), (uint8_t)(e62) | ((uint8_t)(e63) << 8) \ + ) + + + +PA_FORCE_INLINE void transpose_i64_8x8_AVX512( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, + __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 +){ + __m512i a0, a1; + + a0 = _mm512_unpackhi_epi64(r0, r1); + r1 = _mm512_unpacklo_epi64(r0, r1); + a1 = _mm512_unpackhi_epi64(r2, r3); + r2 = _mm512_unpacklo_epi64(r2, r3); + r0 = _mm512_unpackhi_epi64(r4, r5); + r4 = _mm512_unpacklo_epi64(r4, r5); + r5 = _mm512_unpacklo_epi64(r6, r7); + r7 = _mm512_unpackhi_epi64(r6, r7); + + r3 = _mm512_shuffle_i64x2(r1, r2, 221); + r1 = _mm512_shuffle_i64x2(r1, r2, 136); + r2 = _mm512_shuffle_i64x2(a0, a1, 136); + a1 = _mm512_shuffle_i64x2(a0, a1, 221); + r6 = _mm512_shuffle_i64x2(r4, r5, 221); + r4 = _mm512_shuffle_i64x2(r4, r5, 136); + r5 = _mm512_shuffle_i64x2(r0, r7, 136); + r7 = _mm512_shuffle_i64x2(r0, r7, 221); + + r0 = _mm512_shuffle_i64x2(r1, r4, 136); + r4 = _mm512_shuffle_i64x2(r1, r4, 221); + r1 = _mm512_shuffle_i64x2(r2, r5, 136); + r5 = _mm512_shuffle_i64x2(r2, r5, 221); + r2 = _mm512_shuffle_i64x2(r3, r6, 136); + r6 = _mm512_shuffle_i64x2(r3, r6, 221); + r3 = _mm512_shuffle_i64x2(a1, r7, 136); + r7 = _mm512_shuffle_i64x2(a1, r7, 221); +} + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Kernels_x64_SSE41.h b/SerialPrograms/Source/Kernels/Kernels_x64_SSE41.h index 2f8d462952..46954f3214 100644 --- a/SerialPrograms/Source/Kernels/Kernels_x64_SSE41.h +++ b/SerialPrograms/Source/Kernels/Kernels_x64_SSE41.h @@ -1,98 +1,98 @@ -/* Kernels (x64 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_x64_SSE41_H -#define PokemonAutomation_Kernels_x64_SSE41_H - -#include -#include -#include "Common/Compiler.h" - -#include - -namespace PokemonAutomation{ -namespace Kernels{ - - -inline static void print(const __m128& x){ - union{ - __m128 v; - float s[4]; - }; - v = x; - for (int i = 0; i < 4; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u8(__m128i x){ - for (int i = 0; i < 16; i++){ - std::cout << (int)((const unsigned char*)&x)[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u16(const __m128i& x){ - union{ - __m128i v; - uint16_t s[8]; - }; - v = x; - for (int i = 0; i < 8; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u32(const __m128i& x){ - union{ - __m128i v; - uint32_t s[4]; - }; - v = x; - for (int i = 0; i < 4; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} -inline static void print_u64(const __m128i& x){ - union{ - __m128i v; - uint64_t s[2]; - }; - v = x; - for (int i = 0; i < 2; i++){ - std::cout << s[i] << " "; - } - std::cout << std::endl; -} - - - - -PA_FORCE_INLINE float reduce32_x64_SSE(__m128 x){ - x = _mm_add_ps(x, _mm_shuffle_ps(x, x, 78)); - x = _mm_add_ps(x, _mm_shuffle_ps(x, x, 177)); - return _mm_cvtss_f32(x); -} -PA_FORCE_INLINE uint64_t reduce32_x64_SSE41(__m128i x){ - uint64_t ret = _mm_cvtsi128_si32(x); - ret += _mm_extract_epi32(x, 1); - ret += _mm_extract_epi32(x, 2); - ret += _mm_extract_epi32(x, 3); - return ret; -} - -PA_FORCE_INLINE void transpose_i64_2x2_SSE2(__m128i& r0, __m128i& r1){ - __m128i a0 = r0; - r0 = _mm_unpacklo_epi64(r0, r1); - r1 = _mm_unpackhi_epi64(a0, r1); -} - - - - -} -} -#endif +/* Kernels (x64 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_x64_SSE41_H +#define PokemonAutomation_Kernels_x64_SSE41_H + +#include +#include +#include "Common/Compiler.h" + +#include + +namespace PokemonAutomation{ +namespace Kernels{ + + +inline static void print(const __m128& x){ + union{ + __m128 v; + float s[4]; + }; + v = x; + for (int i = 0; i < 4; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u8(__m128i x){ + for (int i = 0; i < 16; i++){ + std::cout << (int)((const unsigned char*)&x)[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u16(const __m128i& x){ + union{ + __m128i v; + uint16_t s[8]; + }; + v = x; + for (int i = 0; i < 8; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u32(const __m128i& x){ + union{ + __m128i v; + uint32_t s[4]; + }; + v = x; + for (int i = 0; i < 4; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} +inline static void print_u64(const __m128i& x){ + union{ + __m128i v; + uint64_t s[2]; + }; + v = x; + for (int i = 0; i < 2; i++){ + std::cout << s[i] << " "; + } + std::cout << std::endl; +} + + + + +PA_FORCE_INLINE float reduce32_x64_SSE(__m128 x){ + x = _mm_add_ps(x, _mm_shuffle_ps(x, x, 78)); + x = _mm_add_ps(x, _mm_shuffle_ps(x, x, 177)); + return _mm_cvtss_f32(x); +} +PA_FORCE_INLINE uint64_t reduce32_x64_SSE41(__m128i x){ + uint64_t ret = _mm_cvtsi128_si32(x); + ret += _mm_extract_epi32(x, 1); + ret += _mm_extract_epi32(x, 2); + ret += _mm_extract_epi32(x, 3); + return ret; +} + +PA_FORCE_INLINE void transpose_i64_2x2_SSE2(__m128i& r0, __m128i& r1){ + __m128i a0 = r0; + r0 = _mm_unpacklo_epi64(r0, r1); + r1 = _mm_unpackhi_epi64(a0, r1); +} + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h b/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h index 8c02db1cf4..dfadfcdb91 100644 --- a/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h +++ b/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h @@ -1,138 +1,138 @@ -/* Partial Word Access (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_PartialWordAccess_arm64_NEON_H -#define PokemonAutomation_Kernels_PartialWordAccess_arm64_NEON_H - -#include -#include -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -// Used to load bytes of data to partially fill a SIMD 128-bit vector -// This is useful for handling leftover bytes of data at the end of a loop. -// Example usage: Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h -// -class PartialWordAccess_arm64_NEON{ -public: - // create a mask with first `bytes` low bytes are all 1s - // If `bytes` is 3, then the returned vector is from low bytes to high bytes: [0xFF, 0xFF, 0xFF, 0, 0, 0, ..., 0] - PA_FORCE_INLINE static uint8x16_t create_front_mask(size_t bytes) { - PA_ALIGN_STRUCT(16) uint8_t bytes_values[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; - const uint8x16_t seq_u8x16 = vld1q_u8(bytes_values); - return vcgtq_u8(vdupq_n_u8((uint8_t)bytes), seq_u8x16); - } - - // How many bytes of data to load. Allow at most 16 bytes. - PA_FORCE_INLINE PartialWordAccess_arm64_NEON(size_t bytes) - : m_shift(16 - bytes) - { - PA_ALIGN_STRUCT(16) uint8_t bytes_values[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; - const uint8x16_t seq_u8x16 = vld1q_u8(bytes_values); - // If `bytes` is 3, then `m_front_mask` is from low bytes to high bytes: [0xFF, 0xFF, 0xFF, 0, 0, 0, ..., 0] - m_front_mask = vcgtq_u8(vdupq_n_u8((uint8_t)bytes), seq_u8x16); - // If `bytes` is 3, then `m_back_mask` is from low bytes to high bytes: [0xFF, 0xFF, 0xFF, ... 0xFF, 0, 0, 0] - m_back_mask = vcgtq_u8(vdupq_n_u8((uint8_t)m_shift), seq_u8x16); - - // If `bytes` is 3, then `m_shift_front` is from low bytes to high bytes: [13, 14, 15, 16, 17, ..., 28] - m_shift_front = vaddq_u8(vdupq_n_u8(uint8_t(m_shift)), seq_u8x16); - - // IF `bytes` is 3, then `m_shift_back` is from low bytes to high bytes: [243, 244, 245,... 0, 1, 2] - m_shift_back = vsubq_u8(seq_u8x16, vdupq_n_u8((uint8_t)m_shift)); - } - - // load() function that does not read past end of buffer - // so it read some in front of `ptr` - // return the loaded partial word data and store at lower bytes of returned uint8x16_t - PA_FORCE_INLINE uint8x16_t load_int_no_read_past_end(const void* ptr) const{ - // In `x` the actual data we want, `ptr` to `ptr + bytes`, is at the higher bits - uint8x16_t x = vld1q_u8((const uint8_t*)ptr - m_shift); - // Use a table lookup command: - // for each uint8 in the result, ret_u8[i], get the index from `m_shift_front`: m_shift_front[i] - // use the value of m_shift_front[i] as an index to get a value in x: - // ret_u8[i] = x[m_shift_front[i]] - // since `m_shift_front` stores [`16-bytes`, `16-bytes+1`, `16-bytes+2`, ...] - // the resulting operation is to shift the bytes in x to the lower bytes by `16-bytes` bytes. - // For the index values >= 16 in m_shift_front[i], `vqtbl1q_u8()` returns 0. - return vqtbl1q_u8(x, m_shift_front); - } - // load() function that reads past end of buffer - // return the loaded partial word data and store at lower bytes of returned uint8x16_t - PA_FORCE_INLINE uint8x16_t load_int_no_read_before_ptr(const void* ptr) const{ - uint8x16_t x = vld1q_u8((const uint8_t*)ptr); - return vandq_u8(x, m_front_mask); - } - // load() function that does not read past end of buffer - // so it read some in front of `ptr` - // return the loaded partial word data and store at lower bytes of returned float32x4_t - PA_FORCE_INLINE float32x4_t load_f32_no_read_past_end(const void* ptr) const{ - return vreinterpretq_f32_u8(load_int_no_read_past_end(ptr)); - } - // load() function that reads past end of buffer - // return the loaded partial word data and store at lower bytes of returned float32x4_t - PA_FORCE_INLINE float32x4_t load_f32_no_read_before_ptr(const void* ptr) const{ - return vreinterpretq_f32_u8(load_int_no_read_past_end(ptr)); - } - - // Load only `bytes` of bytes from `ptr` and place them at the lower end of of the - // returned uint8x16_t. - // `bytes` is defined at the constructor of `PartialWordAccess_arm64_NEON`. - // - // Note: to be efficient, we read an entire 16-byte memory on this partial word. - // This is a hack as it may read outside of the memory we allocate to the buffer of - // `ptr`, but we assume here the buffer is defined inside our pre-allocated - // 4K-bytes-aligned memory block. So as long as we don't read past a 4K byte page, - // we are fine. - // Note OS allocates memory by groups of 4K bytes, too. So it could still work fine - // when not run on our pre-allocated memory block. - PA_FORCE_INLINE uint8x16_t load(const void* ptr) const{ - const void* end = (const char*)ptr + 16; - if (((size_t)end & 4095) < 16){ // if we are about to read past a page - // Call load function that does not read past page - return load_int_no_read_past_end(ptr); - }else{ - // Call load function that reads past end of the data buffer where `ptr` is - // from. - return load_int_no_read_before_ptr(ptr); - } - } - - // store() function that does not read past end of buffer - // so it read some in front of `ptr` and save them back into buffer - PA_FORCE_INLINE void store_int_no_past_end(void* ptr, uint8x16_t x) const{ - uint8x16_t v = vld1q_u8((const uint8_t*)ptr - m_shift); - // use table lookup to shift bytes in x to higher bytes by `bytes` - x = vqtbl1q_u8(x, m_shift_back); - // bit select intrinsic: - // vbslq_u8(a, b, c), for 1-bits in a, choose b; for 0-bits in a, choose c - // Returned `merged` contains the pre-ptr data in the buffer, and partial word in `x`. - uint8x16_t merged = vbslq_u8(m_back_mask, v, x); - vst1q_u8((uint8_t*)ptr - m_shift, merged); - } - // store() function that does not read past end of buffer - // so it read some in front of `ptr` and save them back into buffer - PA_FORCE_INLINE void store_f32_no_past_end(void* ptr, float32x4_t x) const{ - store_int_no_past_end(ptr, vreinterpretq_u8_f32(x)); - } - -private: - size_t m_shift; - // mask of which bytes are occupied by the loaded data - uint8x16_t m_front_mask; - uint8x16_t m_back_mask; - uint8x16_t m_shift_front; - uint8x16_t m_shift_back; -}; - - - -} -} -#endif +/* Partial Word Access (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_PartialWordAccess_arm64_NEON_H +#define PokemonAutomation_Kernels_PartialWordAccess_arm64_NEON_H + +#include +#include +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +// Used to load bytes of data to partially fill a SIMD 128-bit vector +// This is useful for handling leftover bytes of data at the end of a loop. +// Example usage: Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_arm64_NEON.h +// +class PartialWordAccess_arm64_NEON{ +public: + // create a mask with first `bytes` low bytes are all 1s + // If `bytes` is 3, then the returned vector is from low bytes to high bytes: [0xFF, 0xFF, 0xFF, 0, 0, 0, ..., 0] + PA_FORCE_INLINE static uint8x16_t create_front_mask(size_t bytes) { + PA_ALIGN_STRUCT(16) uint8_t bytes_values[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + const uint8x16_t seq_u8x16 = vld1q_u8(bytes_values); + return vcgtq_u8(vdupq_n_u8((uint8_t)bytes), seq_u8x16); + } + + // How many bytes of data to load. Allow at most 16 bytes. + PA_FORCE_INLINE PartialWordAccess_arm64_NEON(size_t bytes) + : m_shift(16 - bytes) + { + PA_ALIGN_STRUCT(16) uint8_t bytes_values[16] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; + const uint8x16_t seq_u8x16 = vld1q_u8(bytes_values); + // If `bytes` is 3, then `m_front_mask` is from low bytes to high bytes: [0xFF, 0xFF, 0xFF, 0, 0, 0, ..., 0] + m_front_mask = vcgtq_u8(vdupq_n_u8((uint8_t)bytes), seq_u8x16); + // If `bytes` is 3, then `m_back_mask` is from low bytes to high bytes: [0xFF, 0xFF, 0xFF, ... 0xFF, 0, 0, 0] + m_back_mask = vcgtq_u8(vdupq_n_u8((uint8_t)m_shift), seq_u8x16); + + // If `bytes` is 3, then `m_shift_front` is from low bytes to high bytes: [13, 14, 15, 16, 17, ..., 28] + m_shift_front = vaddq_u8(vdupq_n_u8(uint8_t(m_shift)), seq_u8x16); + + // IF `bytes` is 3, then `m_shift_back` is from low bytes to high bytes: [243, 244, 245,... 0, 1, 2] + m_shift_back = vsubq_u8(seq_u8x16, vdupq_n_u8((uint8_t)m_shift)); + } + + // load() function that does not read past end of buffer + // so it read some in front of `ptr` + // return the loaded partial word data and store at lower bytes of returned uint8x16_t + PA_FORCE_INLINE uint8x16_t load_int_no_read_past_end(const void* ptr) const{ + // In `x` the actual data we want, `ptr` to `ptr + bytes`, is at the higher bits + uint8x16_t x = vld1q_u8((const uint8_t*)ptr - m_shift); + // Use a table lookup command: + // for each uint8 in the result, ret_u8[i], get the index from `m_shift_front`: m_shift_front[i] + // use the value of m_shift_front[i] as an index to get a value in x: + // ret_u8[i] = x[m_shift_front[i]] + // since `m_shift_front` stores [`16-bytes`, `16-bytes+1`, `16-bytes+2`, ...] + // the resulting operation is to shift the bytes in x to the lower bytes by `16-bytes` bytes. + // For the index values >= 16 in m_shift_front[i], `vqtbl1q_u8()` returns 0. + return vqtbl1q_u8(x, m_shift_front); + } + // load() function that reads past end of buffer + // return the loaded partial word data and store at lower bytes of returned uint8x16_t + PA_FORCE_INLINE uint8x16_t load_int_no_read_before_ptr(const void* ptr) const{ + uint8x16_t x = vld1q_u8((const uint8_t*)ptr); + return vandq_u8(x, m_front_mask); + } + // load() function that does not read past end of buffer + // so it read some in front of `ptr` + // return the loaded partial word data and store at lower bytes of returned float32x4_t + PA_FORCE_INLINE float32x4_t load_f32_no_read_past_end(const void* ptr) const{ + return vreinterpretq_f32_u8(load_int_no_read_past_end(ptr)); + } + // load() function that reads past end of buffer + // return the loaded partial word data and store at lower bytes of returned float32x4_t + PA_FORCE_INLINE float32x4_t load_f32_no_read_before_ptr(const void* ptr) const{ + return vreinterpretq_f32_u8(load_int_no_read_past_end(ptr)); + } + + // Load only `bytes` of bytes from `ptr` and place them at the lower end of of the + // returned uint8x16_t. + // `bytes` is defined at the constructor of `PartialWordAccess_arm64_NEON`. + // + // Note: to be efficient, we read an entire 16-byte memory on this partial word. + // This is a hack as it may read outside of the memory we allocate to the buffer of + // `ptr`, but we assume here the buffer is defined inside our pre-allocated + // 4K-bytes-aligned memory block. So as long as we don't read past a 4K byte page, + // we are fine. + // Note OS allocates memory by groups of 4K bytes, too. So it could still work fine + // when not run on our pre-allocated memory block. + PA_FORCE_INLINE uint8x16_t load(const void* ptr) const{ + const void* end = (const char*)ptr + 16; + if (((size_t)end & 4095) < 16){ // if we are about to read past a page + // Call load function that does not read past page + return load_int_no_read_past_end(ptr); + }else{ + // Call load function that reads past end of the data buffer where `ptr` is + // from. + return load_int_no_read_before_ptr(ptr); + } + } + + // store() function that does not read past end of buffer + // so it read some in front of `ptr` and save them back into buffer + PA_FORCE_INLINE void store_int_no_past_end(void* ptr, uint8x16_t x) const{ + uint8x16_t v = vld1q_u8((const uint8_t*)ptr - m_shift); + // use table lookup to shift bytes in x to higher bytes by `bytes` + x = vqtbl1q_u8(x, m_shift_back); + // bit select intrinsic: + // vbslq_u8(a, b, c), for 1-bits in a, choose b; for 0-bits in a, choose c + // Returned `merged` contains the pre-ptr data in the buffer, and partial word in `x`. + uint8x16_t merged = vbslq_u8(m_back_mask, v, x); + vst1q_u8((uint8_t*)ptr - m_shift, merged); + } + // store() function that does not read past end of buffer + // so it read some in front of `ptr` and save them back into buffer + PA_FORCE_INLINE void store_f32_no_past_end(void* ptr, float32x4_t x) const{ + store_int_no_past_end(ptr, vreinterpretq_u8_f32(x)); + } + +private: + size_t m_shift; + // mask of which bytes are occupied by the loaded data + uint8x16_t m_front_mask; + uint8x16_t m_back_mask; + uint8x16_t m_shift_front; + uint8x16_t m_shift_back; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h b/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h index 602896c001..dff5772c6f 100644 --- a/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h @@ -1,49 +1,49 @@ -/* Partial Word Access (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_PartialWordAccess_x64_AVX2_H -#define PokemonAutomation_Kernels_PartialWordAccess_x64_AVX2_H - -#include -#include -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -class PartialWordAccess32_x64_AVX2{ -public: - PA_FORCE_INLINE PartialWordAccess32_x64_AVX2(size_t words){ - m_mask = _mm256_cmpgt_epi32( - _mm256_set1_epi32((uint32_t)words), - _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) - ); - } - - PA_FORCE_INLINE __m256i mask() const{ - return m_mask; - } - PA_FORCE_INLINE __m256i load_i32(const void* ptr) const{ - return _mm256_maskload_epi32((const int*)ptr, m_mask); - } - PA_FORCE_INLINE __m256 load_f32(const void* ptr) const{ - return _mm256_maskload_ps((const float*)ptr, m_mask); - } - PA_FORCE_INLINE void store(const void* ptr, __m256i x) const{ - _mm256_maskstore_epi32((int*)ptr, m_mask, x); - } - -private: - __m256i m_mask; -}; - - - -} -} -#endif +/* Partial Word Access (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_PartialWordAccess_x64_AVX2_H +#define PokemonAutomation_Kernels_PartialWordAccess_x64_AVX2_H + +#include +#include +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +class PartialWordAccess32_x64_AVX2{ +public: + PA_FORCE_INLINE PartialWordAccess32_x64_AVX2(size_t words){ + m_mask = _mm256_cmpgt_epi32( + _mm256_set1_epi32((uint32_t)words), + _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) + ); + } + + PA_FORCE_INLINE __m256i mask() const{ + return m_mask; + } + PA_FORCE_INLINE __m256i load_i32(const void* ptr) const{ + return _mm256_maskload_epi32((const int*)ptr, m_mask); + } + PA_FORCE_INLINE __m256 load_f32(const void* ptr) const{ + return _mm256_maskload_ps((const float*)ptr, m_mask); + } + PA_FORCE_INLINE void store(const void* ptr, __m256i x) const{ + _mm256_maskstore_epi32((int*)ptr, m_mask, x); + } + +private: + __m256i m_mask; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h b/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h index 01689012fc..8884251d69 100644 --- a/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h +++ b/SerialPrograms/Source/Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h @@ -1,91 +1,91 @@ -/* Partial Word Access (x64 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_PartialWordAccess_x64_SSE41_H -#define PokemonAutomation_Kernels_PartialWordAccess_x64_SSE41_H - -#include -#include -#include -#include "Common/Compiler.h" - -namespace PokemonAutomation{ -namespace Kernels{ - - -class PartialWordAccess_x64_SSE41{ -public: - PA_FORCE_INLINE PartialWordAccess_x64_SSE41(size_t bytes) - : m_shift(16 - bytes) - { - m_front_mask = _mm_cmpgt_epi8( - _mm_set1_epi8((uint8_t)bytes), - _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) - ); - - m_shift_front = _mm_setr_epi8(-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, -113); - m_shift_front = _mm_sub_epi8( - m_shift_front, - _mm_set1_epi8((uint8_t)bytes) - ); - - m_shift_back = _mm_sub_epi8( - _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), - _mm_set1_epi8((uint8_t)m_shift) - ); - } - - PA_FORCE_INLINE __m128i load_int_no_read_past_end(const void* ptr) const{ - __m128i x = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); - return _mm_shuffle_epi8(x, m_shift_front); - } - PA_FORCE_INLINE __m128i load_int_no_read_before_ptr(const void* ptr) const{ - __m128i x = _mm_loadu_si128((const __m128i*)ptr); - return _mm_and_si128(x, m_front_mask); - } - PA_FORCE_INLINE __m128 load_f32_no_read_past_end(const void* ptr) const{ - __m128i x = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); - return _mm_castsi128_ps(_mm_shuffle_epi8(x, m_shift_front)); - } - PA_FORCE_INLINE __m128 load_f32_no_read_before_ptr(const void* ptr) const{ - __m128i x = _mm_loadu_si128((const __m128i*)ptr); - return _mm_castsi128_ps(_mm_and_si128(x, m_front_mask)); - } - PA_FORCE_INLINE __m128i load(const void* ptr) const{ - const void* end = (const char*)ptr + 16; - if (((size_t)end & 4095) < 16){ - return load_int_no_read_past_end(ptr); - }else{ - return load_int_no_read_before_ptr(ptr); - } - } - - PA_FORCE_INLINE void store_int_no_past_end(void* ptr, __m128i x) const{ - __m128i v = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); - x = _mm_shuffle_epi8(x, m_shift_back); - v = _mm_blendv_epi8(x, v, m_shift_back); - _mm_storeu_si128((__m128i*)((char*)ptr - m_shift), v); - } - PA_FORCE_INLINE void store_f32_no_past_end(void* ptr, __m128 x) const{ - __m128i v = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); - __m128i i = _mm_castps_si128(x); - i = _mm_shuffle_epi8(i, m_shift_back); - v = _mm_blendv_epi8(i, v, m_shift_back); - _mm_storeu_si128((__m128i*)((char*)ptr - m_shift), v); - } - -private: - size_t m_shift; - __m128i m_front_mask; - __m128i m_shift_front; - __m128i m_shift_back; -}; - - - -} -} -#endif +/* Partial Word Access (x64 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_PartialWordAccess_x64_SSE41_H +#define PokemonAutomation_Kernels_PartialWordAccess_x64_SSE41_H + +#include +#include +#include +#include "Common/Compiler.h" + +namespace PokemonAutomation{ +namespace Kernels{ + + +class PartialWordAccess_x64_SSE41{ +public: + PA_FORCE_INLINE PartialWordAccess_x64_SSE41(size_t bytes) + : m_shift(16 - bytes) + { + m_front_mask = _mm_cmpgt_epi8( + _mm_set1_epi8((uint8_t)bytes), + _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) + ); + + m_shift_front = _mm_setr_epi8(-128, -127, -126, -125, -124, -123, -122, -121, -120, -119, -118, -117, -116, -115, -114, -113); + m_shift_front = _mm_sub_epi8( + m_shift_front, + _mm_set1_epi8((uint8_t)bytes) + ); + + m_shift_back = _mm_sub_epi8( + _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), + _mm_set1_epi8((uint8_t)m_shift) + ); + } + + PA_FORCE_INLINE __m128i load_int_no_read_past_end(const void* ptr) const{ + __m128i x = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); + return _mm_shuffle_epi8(x, m_shift_front); + } + PA_FORCE_INLINE __m128i load_int_no_read_before_ptr(const void* ptr) const{ + __m128i x = _mm_loadu_si128((const __m128i*)ptr); + return _mm_and_si128(x, m_front_mask); + } + PA_FORCE_INLINE __m128 load_f32_no_read_past_end(const void* ptr) const{ + __m128i x = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); + return _mm_castsi128_ps(_mm_shuffle_epi8(x, m_shift_front)); + } + PA_FORCE_INLINE __m128 load_f32_no_read_before_ptr(const void* ptr) const{ + __m128i x = _mm_loadu_si128((const __m128i*)ptr); + return _mm_castsi128_ps(_mm_and_si128(x, m_front_mask)); + } + PA_FORCE_INLINE __m128i load(const void* ptr) const{ + const void* end = (const char*)ptr + 16; + if (((size_t)end & 4095) < 16){ + return load_int_no_read_past_end(ptr); + }else{ + return load_int_no_read_before_ptr(ptr); + } + } + + PA_FORCE_INLINE void store_int_no_past_end(void* ptr, __m128i x) const{ + __m128i v = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); + x = _mm_shuffle_epi8(x, m_shift_back); + v = _mm_blendv_epi8(x, v, m_shift_back); + _mm_storeu_si128((__m128i*)((char*)ptr - m_shift), v); + } + PA_FORCE_INLINE void store_f32_no_past_end(void* ptr, __m128 x) const{ + __m128i v = _mm_loadu_si128((const __m128i*)((const char*)ptr - m_shift)); + __m128i i = _mm_castps_si128(x); + i = _mm_shuffle_epi8(i, m_shift_back); + v = _mm_blendv_epi8(i, v, m_shift_back); + _mm_storeu_si128((__m128i*)((char*)ptr - m_shift), v); + } + +private: + size_t m_shift; + __m128i m_front_mask; + __m128i m_shift_front; + __m128i m_shift_back; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.cpp b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.cpp index e53d578e5b..2c62fd7bbb 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.cpp +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.cpp @@ -1,141 +1,141 @@ -/* Scale Invariant Matrix Match - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - -float compute_scale_Default (size_t width, size_t height, float const* const* A, float const* const* T); -float compute_scale_min4_x86_SSE (size_t width, size_t height, float const* const* A, float const* const* T); -float compute_scale_min8_x86_AVX2 (size_t width, size_t height, float const* const* A, float const* const* T); -float compute_scale_min16_x86_AVX512(size_t width, size_t height, float const* const* A, float const* const* T); - -float compute_scale_Default (size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); -float compute_scale_min4_x86_SSE (size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); -float compute_scale_min8_x86_AVX2 (size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); -float compute_scale_min16_x86_AVX512(size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); - - -float compute_scale( - size_t width, size_t height, - float const* const* A, - float const* const* T -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return compute_scale_min16_x86_AVX512(width, height, A, T); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return compute_scale_min8_x86_AVX2(width, height, A, T); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return compute_scale_min4_x86_SSE(width, height, A, T); - } -#endif - return compute_scale_Default(width, height, A, T); -} -float compute_scale( - size_t width, size_t height, - float const* const* A, - float const* const* TW, - float const* const* W -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return compute_scale_min16_x86_AVX512(width, height, A, TW, W); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return compute_scale_min8_x86_AVX2(width, height, A, TW, W); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return compute_scale_min4_x86_SSE(width, height, A, TW, W); - } -#endif - return compute_scale_Default(width, height, A, TW, W); -} - - - -float compute_error_Default (size_t width, size_t height, float scale, float const* const* A, float const* const* T); -float compute_error_min4_x86_SSE (size_t width, size_t height, float scale, float const* const* A, float const* const* T); -float compute_error_min8_x86_AVX2 (size_t width, size_t height, float scale, float const* const* A, float const* const* T); -float compute_error_min16_x86_AVX512(size_t width, size_t height, float scale, float const* const* A, float const* const* T); - -float compute_error_Default (size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); -float compute_error_min4_x86_SSE (size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); -float compute_error_min8_x86_AVX2 (size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); -float compute_error_min16_x86_AVX512(size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); - -float compute_error( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return compute_error_min16_x86_AVX512(width, height, scale, A, T); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return compute_error_min8_x86_AVX2(width, height, scale, A, T); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return compute_error_min4_x86_SSE(width, height, scale, A, T); - } -#endif - return compute_error_Default(width, height, scale, A, T); -} -float compute_error( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, - float const* const* W -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return compute_error_min16_x86_AVX512(width, height, scale, A, TW, W); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return compute_error_min8_x86_AVX2(width, height, scale, A, TW, W); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return compute_error_min4_x86_SSE(width, height, scale, A, TW, W); - } -#endif - return compute_error_Default(width, height, scale, A, TW, W); -} - - - - - - - - -} -} -} +/* Scale Invariant Matrix Match + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + +float compute_scale_Default (size_t width, size_t height, float const* const* A, float const* const* T); +float compute_scale_min4_x86_SSE (size_t width, size_t height, float const* const* A, float const* const* T); +float compute_scale_min8_x86_AVX2 (size_t width, size_t height, float const* const* A, float const* const* T); +float compute_scale_min16_x86_AVX512(size_t width, size_t height, float const* const* A, float const* const* T); + +float compute_scale_Default (size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); +float compute_scale_min4_x86_SSE (size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); +float compute_scale_min8_x86_AVX2 (size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); +float compute_scale_min16_x86_AVX512(size_t width, size_t height, float const* const* A, float const* const* TW, float const* const* W); + + +float compute_scale( + size_t width, size_t height, + float const* const* A, + float const* const* T +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return compute_scale_min16_x86_AVX512(width, height, A, T); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return compute_scale_min8_x86_AVX2(width, height, A, T); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return compute_scale_min4_x86_SSE(width, height, A, T); + } +#endif + return compute_scale_Default(width, height, A, T); +} +float compute_scale( + size_t width, size_t height, + float const* const* A, + float const* const* TW, + float const* const* W +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return compute_scale_min16_x86_AVX512(width, height, A, TW, W); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return compute_scale_min8_x86_AVX2(width, height, A, TW, W); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return compute_scale_min4_x86_SSE(width, height, A, TW, W); + } +#endif + return compute_scale_Default(width, height, A, TW, W); +} + + + +float compute_error_Default (size_t width, size_t height, float scale, float const* const* A, float const* const* T); +float compute_error_min4_x86_SSE (size_t width, size_t height, float scale, float const* const* A, float const* const* T); +float compute_error_min8_x86_AVX2 (size_t width, size_t height, float scale, float const* const* A, float const* const* T); +float compute_error_min16_x86_AVX512(size_t width, size_t height, float scale, float const* const* A, float const* const* T); + +float compute_error_Default (size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); +float compute_error_min4_x86_SSE (size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); +float compute_error_min8_x86_AVX2 (size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); +float compute_error_min16_x86_AVX512(size_t width, size_t height, float scale, float const* const* A, float const* const* TW, float const* const* W); + +float compute_error( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return compute_error_min16_x86_AVX512(width, height, scale, A, T); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return compute_error_min8_x86_AVX2(width, height, scale, A, T); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return compute_error_min4_x86_SSE(width, height, scale, A, T); + } +#endif + return compute_error_Default(width, height, scale, A, T); +} +float compute_error( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, + float const* const* W +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (width >= 16 && CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return compute_error_min16_x86_AVX512(width, height, scale, A, TW, W); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (width >= 8 && CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return compute_error_min8_x86_AVX2(width, height, scale, A, TW, W); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (width >= 4 && CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return compute_error_min4_x86_SSE(width, height, scale, A, TW, W); + } +#endif + return compute_error_Default(width, height, scale, A, TW, W); +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h index 4c3936f6b2..e747ff7c6a 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h @@ -1,62 +1,62 @@ -/* Scale Invariant Matrix Match - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_H -#define PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_H - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - -// Compute s that minimizes: |s A - T|^2 -// All pointers must have the same alignment. -float compute_scale( - size_t width, size_t height, - float const* const* A, - float const* const* T -); - - -// Compute s that minimizes: (|s A - T| * W)^2 -// All pointers must have the same alignment. -float compute_scale( - size_t width, size_t height, - float const* const* A, - float const* const* TW, // Precomputed T * W - float const* const* W -); - - - -// Compute: |s A - T|^2 -// All pointers must have the same alignment. -float compute_error( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -); - - -// Compute: |s A w - T|^2 -// All pointers must have the same alignment. -float compute_error( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, // Precomputed T * W - float const* const* W -); - - - - - -} -} -} -#endif +/* Scale Invariant Matrix Match + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_H +#define PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_H + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + +// Compute s that minimizes: |s A - T|^2 +// All pointers must have the same alignment. +float compute_scale( + size_t width, size_t height, + float const* const* A, + float const* const* T +); + + +// Compute s that minimizes: (|s A - T| * W)^2 +// All pointers must have the same alignment. +float compute_scale( + size_t width, size_t height, + float const* const* A, + float const* const* TW, // Precomputed T * W + float const* const* W +); + + + +// Compute: |s A - T|^2 +// All pointers must have the same alignment. +float compute_error( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +); + + +// Compute: |s A w - T|^2 +// All pointers must have the same alignment. +float compute_error( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, // Precomputed T * W + float const* const* W +); + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_Default.cpp b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_Default.cpp index f75952a567..7fb1ee5fb4 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_Default.cpp +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_Default.cpp @@ -1,119 +1,119 @@ -/* Scale Invariant Matrix Match (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - -struct Context_x86_SSE41{ - using vtype = float; - - static PA_FORCE_INLINE vtype vzero(){ - return 0; - } - static PA_FORCE_INLINE vtype vset(float a){ - return a; - } - static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ - return a + b; - } - static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ - return a * b; - } - static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ - return a * b + c; - } - static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ - return a * b - c; - } - static PA_FORCE_INLINE float vreduce(vtype a){ - return a; - } - - static PA_FORCE_INLINE void load2_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - A = *(const float*)ptrA; - B = *(const float*)ptrB; - } - static PA_FORCE_INLINE void load3_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - A = *(const float*)ptrA; - B = *(const float*)ptrB; - C = *(const float*)ptrC; - } - static PA_FORCE_INLINE void load2_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - A = *(const float*)ptrA; - B = *(const float*)ptrB; - } - static PA_FORCE_INLINE void load3_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - A = *(const float*)ptrA; - B = *(const float*)ptrB; - C = *(const float*)ptrC; - } -}; - - - -float compute_scale_Default( - size_t width, size_t height, - float const* const* A, - float const* const* T -){ - return compute_scale>(width, height, A, T); -} -float compute_scale_Default( - size_t width, size_t height, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_scale>(width, height, A, TW, W); -} -float compute_error_Default( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -){ - return compute_error>(width, height, scale, A, T); -} -float compute_error_Default( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_error>(width, height, scale, A, TW, W); -} - - - - - - -} -} -} +/* Scale Invariant Matrix Match (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + +struct Context_x86_SSE41{ + using vtype = float; + + static PA_FORCE_INLINE vtype vzero(){ + return 0; + } + static PA_FORCE_INLINE vtype vset(float a){ + return a; + } + static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ + return a + b; + } + static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ + return a * b; + } + static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ + return a * b + c; + } + static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ + return a * b - c; + } + static PA_FORCE_INLINE float vreduce(vtype a){ + return a; + } + + static PA_FORCE_INLINE void load2_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + A = *(const float*)ptrA; + B = *(const float*)ptrB; + } + static PA_FORCE_INLINE void load3_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + A = *(const float*)ptrA; + B = *(const float*)ptrB; + C = *(const float*)ptrC; + } + static PA_FORCE_INLINE void load2_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + A = *(const float*)ptrA; + B = *(const float*)ptrB; + } + static PA_FORCE_INLINE void load3_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + A = *(const float*)ptrA; + B = *(const float*)ptrB; + C = *(const float*)ptrC; + } +}; + + + +float compute_scale_Default( + size_t width, size_t height, + float const* const* A, + float const* const* T +){ + return compute_scale>(width, height, A, T); +} +float compute_scale_Default( + size_t width, size_t height, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_scale>(width, height, A, TW, W); +} +float compute_error_Default( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +){ + return compute_error>(width, height, scale, A, T); +} +float compute_error_Default( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_error>(width, height, scale, A, TW, W); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp index 88a905f94b..6eeefff1e2 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX2.cpp @@ -1,132 +1,132 @@ -/* Scale Invariant Matrix Match (x86 FMA3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - -struct Context_x86_AVX2{ - using vtype = __m256; - - static PA_FORCE_INLINE vtype vzero(){ - return _mm256_setzero_ps(); - } - static PA_FORCE_INLINE vtype vset(float a){ - return _mm256_set1_ps(a); - } - static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ - return _mm256_add_ps(a, b); - } - static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ - return _mm256_mul_ps(a, b); - } - static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ - return _mm256_fmadd_ps(a, b, c); - } - static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ - return _mm256_fmsub_ps(a, b, c); - } - static PA_FORCE_INLINE float vreduce(vtype a){ - return reduce32_x64_AVX(a); - } - - static PA_FORCE_INLINE void load2_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - __m256i mask = _mm256_cmpgt_epi32( - _mm256_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8), - _mm256_set1_epi32((uint32_t)length) - ); - A = _mm256_maskload_ps((const float*)ptrA, mask); - B = _mm256_maskload_ps((const float*)ptrB, mask); - } - static PA_FORCE_INLINE void load3_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - __m256i mask = _mm256_cmpgt_epi32( - _mm256_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8), - _mm256_set1_epi32((uint32_t)length) - ); - A = _mm256_maskload_ps((const float*)ptrA, mask); - B = _mm256_maskload_ps((const float*)ptrB, mask); - C = _mm256_maskload_ps((const float*)ptrC, mask); - } - static PA_FORCE_INLINE void load2_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - PartialWordAccess32_x64_AVX2 access(length); - A = access.load_f32(ptrA); - B = access.load_f32(ptrB); - } - static PA_FORCE_INLINE void load3_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - PartialWordAccess32_x64_AVX2 access(length); - A = access.load_f32(ptrA); - B = access.load_f32(ptrB); - C = access.load_f32(ptrC); - } -}; - - - -float compute_scale_min8_x86_AVX2( - size_t width, size_t height, - float const* const* A, - float const* const* T -){ - return compute_scale>(width, height, A, T); -} -float compute_scale_min8_x86_AVX2( - size_t width, size_t height, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_scale>(width, height, A, TW, W); -} -float compute_error_min8_x86_AVX2( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -){ - return compute_error>(width, height, scale, A, T); -} -float compute_error_min8_x86_AVX2( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_error>(width, height, scale, A, TW, W); -} - - - -} -} -} -#endif +/* Scale Invariant Matrix Match (x86 FMA3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + +struct Context_x86_AVX2{ + using vtype = __m256; + + static PA_FORCE_INLINE vtype vzero(){ + return _mm256_setzero_ps(); + } + static PA_FORCE_INLINE vtype vset(float a){ + return _mm256_set1_ps(a); + } + static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ + return _mm256_add_ps(a, b); + } + static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ + return _mm256_mul_ps(a, b); + } + static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ + return _mm256_fmadd_ps(a, b, c); + } + static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ + return _mm256_fmsub_ps(a, b, c); + } + static PA_FORCE_INLINE float vreduce(vtype a){ + return reduce32_x64_AVX(a); + } + + static PA_FORCE_INLINE void load2_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + __m256i mask = _mm256_cmpgt_epi32( + _mm256_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8), + _mm256_set1_epi32((uint32_t)length) + ); + A = _mm256_maskload_ps((const float*)ptrA, mask); + B = _mm256_maskload_ps((const float*)ptrB, mask); + } + static PA_FORCE_INLINE void load3_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + __m256i mask = _mm256_cmpgt_epi32( + _mm256_setr_epi32(1, 2, 3, 4, 5, 6, 7, 8), + _mm256_set1_epi32((uint32_t)length) + ); + A = _mm256_maskload_ps((const float*)ptrA, mask); + B = _mm256_maskload_ps((const float*)ptrB, mask); + C = _mm256_maskload_ps((const float*)ptrC, mask); + } + static PA_FORCE_INLINE void load2_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + PartialWordAccess32_x64_AVX2 access(length); + A = access.load_f32(ptrA); + B = access.load_f32(ptrB); + } + static PA_FORCE_INLINE void load3_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + PartialWordAccess32_x64_AVX2 access(length); + A = access.load_f32(ptrA); + B = access.load_f32(ptrB); + C = access.load_f32(ptrC); + } +}; + + + +float compute_scale_min8_x86_AVX2( + size_t width, size_t height, + float const* const* A, + float const* const* T +){ + return compute_scale>(width, height, A, T); +} +float compute_scale_min8_x86_AVX2( + size_t width, size_t height, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_scale>(width, height, A, TW, W); +} +float compute_error_min8_x86_AVX2( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +){ + return compute_error>(width, height, scale, A, T); +} +float compute_error_min8_x86_AVX2( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_error>(width, height, scale, A, TW, W); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp index 4cbeb2f19f..85f6806085 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_AVX512.cpp @@ -1,124 +1,124 @@ -/* Scale Invariant Matrix Match (x86 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include -#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - -struct Context_x86_AVX512{ - using vtype = __m512; - - static PA_FORCE_INLINE vtype vzero(){ - return _mm512_setzero_ps(); - } - static PA_FORCE_INLINE vtype vset(float a){ - return _mm512_set1_ps(a); - } - static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ - return _mm512_add_ps(a, b); - } - static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ - return _mm512_mul_ps(a, b); - } - static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ - return _mm512_fmadd_ps(a, b, c); - } - static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ - return _mm512_fmsub_ps(a, b, c); - } - static PA_FORCE_INLINE float vreduce(vtype a){ - return _mm512_reduce_add_ps(a); - } - - static PA_FORCE_INLINE void load2_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - __mmask16 mask = ~(((uint16_t)1 << length) - 1); - A = _mm512_maskz_load_ps(mask, ptrA); - B = _mm512_maskz_load_ps(mask, ptrB); - } - static PA_FORCE_INLINE void load3_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - __mmask16 mask = ~(((uint16_t)1 << length) - 1); - A = _mm512_maskz_load_ps(mask, ptrA); - B = _mm512_maskz_load_ps(mask, ptrB); - C = _mm512_maskz_load_ps(mask, ptrC); - } - static PA_FORCE_INLINE void load2_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - __mmask16 mask = ((uint16_t)1 << length) - 1; - A = _mm512_maskz_load_ps(mask, ptrA); - B = _mm512_maskz_load_ps(mask, ptrB); - } - static PA_FORCE_INLINE void load3_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - __mmask16 mask = ((uint16_t)1 << length) - 1; - A = _mm512_maskz_load_ps(mask, ptrA); - B = _mm512_maskz_load_ps(mask, ptrB); - C = _mm512_maskz_load_ps(mask, ptrC); - } -}; - - - -float compute_scale_min16_x86_AVX512( - size_t width, size_t height, - float const* const* A, - float const* const* T -){ - return compute_scale>(width, height, A, T); -} -float compute_scale_min16_x86_AVX512( - size_t width, size_t height, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_scale>(width, height, A, TW, W); -} -float compute_error_min16_x86_AVX512( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -){ - return compute_error>(width, height, scale, A, T); -} -float compute_error_min16_x86_AVX512( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_error>(width, height, scale, A, TW, W); -} - - - -} -} -} -#endif +/* Scale Invariant Matrix Match (x86 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include +#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + +struct Context_x86_AVX512{ + using vtype = __m512; + + static PA_FORCE_INLINE vtype vzero(){ + return _mm512_setzero_ps(); + } + static PA_FORCE_INLINE vtype vset(float a){ + return _mm512_set1_ps(a); + } + static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ + return _mm512_add_ps(a, b); + } + static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ + return _mm512_mul_ps(a, b); + } + static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ + return _mm512_fmadd_ps(a, b, c); + } + static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ + return _mm512_fmsub_ps(a, b, c); + } + static PA_FORCE_INLINE float vreduce(vtype a){ + return _mm512_reduce_add_ps(a); + } + + static PA_FORCE_INLINE void load2_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + __mmask16 mask = ~(((uint16_t)1 << length) - 1); + A = _mm512_maskz_load_ps(mask, ptrA); + B = _mm512_maskz_load_ps(mask, ptrB); + } + static PA_FORCE_INLINE void load3_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + __mmask16 mask = ~(((uint16_t)1 << length) - 1); + A = _mm512_maskz_load_ps(mask, ptrA); + B = _mm512_maskz_load_ps(mask, ptrB); + C = _mm512_maskz_load_ps(mask, ptrC); + } + static PA_FORCE_INLINE void load2_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + __mmask16 mask = ((uint16_t)1 << length) - 1; + A = _mm512_maskz_load_ps(mask, ptrA); + B = _mm512_maskz_load_ps(mask, ptrB); + } + static PA_FORCE_INLINE void load3_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + __mmask16 mask = ((uint16_t)1 << length) - 1; + A = _mm512_maskz_load_ps(mask, ptrA); + B = _mm512_maskz_load_ps(mask, ptrB); + C = _mm512_maskz_load_ps(mask, ptrC); + } +}; + + + +float compute_scale_min16_x86_AVX512( + size_t width, size_t height, + float const* const* A, + float const* const* T +){ + return compute_scale>(width, height, A, T); +} +float compute_scale_min16_x86_AVX512( + size_t width, size_t height, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_scale>(width, height, A, TW, W); +} +float compute_error_min16_x86_AVX512( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +){ + return compute_error>(width, height, scale, A, T); +} +float compute_error_min16_x86_AVX512( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_error>(width, height, scale, A, TW, W); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp index 783cbd12a5..a7dd82476f 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Core_x86_SSE.cpp @@ -1,126 +1,126 @@ -/* Scale Invariant Matrix Match (x86 SSE) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - -struct Context_x86_SSE41{ - using vtype = __m128; - - static PA_FORCE_INLINE vtype vzero(){ - return _mm_setzero_ps(); - } - static PA_FORCE_INLINE vtype vset(float a){ - return _mm_set1_ps(a); - } - static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ - return _mm_add_ps(a, b); - } - static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ - return _mm_mul_ps(a, b); - } - static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ - return _mm_add_ps(_mm_mul_ps(a, b), c); - } - static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ - return _mm_sub_ps(_mm_mul_ps(a, b), c); - } - static PA_FORCE_INLINE float vreduce(vtype a){ - return reduce32_x64_SSE(a); - } - - static PA_FORCE_INLINE void load2_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - PartialWordAccess_x64_SSE41 access(16 - length * 4); - A = access.load_f32_no_read_before_ptr((const float*)ptrA + length); - B = access.load_f32_no_read_before_ptr((const float*)ptrB + length); - } - static PA_FORCE_INLINE void load3_partial_back( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - PartialWordAccess_x64_SSE41 access(16 - length * 4); - A = access.load_f32_no_read_before_ptr((const float*)ptrA + length); - B = access.load_f32_no_read_before_ptr((const float*)ptrB + length); - C = access.load_f32_no_read_before_ptr((const float*)ptrC + length); - } - static PA_FORCE_INLINE void load2_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB - ){ - PartialWordAccess_x64_SSE41 access(length * 4); - A = access.load_f32_no_read_past_end(ptrA); - B = access.load_f32_no_read_past_end(ptrB); - } - static PA_FORCE_INLINE void load3_partial_front( - size_t length, - vtype& A, const void* ptrA, - vtype& B, const void* ptrB, - vtype& C, const void* ptrC - ){ - PartialWordAccess_x64_SSE41 access(length * 4); - A = access.load_f32_no_read_past_end(ptrA); - B = access.load_f32_no_read_past_end(ptrB); - C = access.load_f32_no_read_past_end(ptrC); - } -}; - - - -float compute_scale_min4_x86_SSE( - size_t width, size_t height, - float const* const* A, - float const* const* T -){ - return compute_scale>(width, height, A, T); -} -float compute_scale_min4_x86_SSE( - size_t width, size_t height, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_scale>(width, height, A, TW, W); -} -float compute_error_min4_x86_SSE( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -){ - return compute_error>(width, height, scale, A, T); -} -float compute_error_min4_x86_SSE( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, - float const* const* W -){ - return compute_error>(width, height, scale, A, TW, W); -} - - - -} -} -} -#endif +/* Scale Invariant Matrix Match (x86 SSE) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels_ScaleInvariantMatrixMatch_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + +struct Context_x86_SSE41{ + using vtype = __m128; + + static PA_FORCE_INLINE vtype vzero(){ + return _mm_setzero_ps(); + } + static PA_FORCE_INLINE vtype vset(float a){ + return _mm_set1_ps(a); + } + static PA_FORCE_INLINE vtype vadd(vtype a, vtype b){ + return _mm_add_ps(a, b); + } + static PA_FORCE_INLINE vtype vmul(vtype a, vtype b){ + return _mm_mul_ps(a, b); + } + static PA_FORCE_INLINE vtype vpma(vtype a, vtype b, vtype c){ + return _mm_add_ps(_mm_mul_ps(a, b), c); + } + static PA_FORCE_INLINE vtype vpms(vtype a, vtype b, vtype c){ + return _mm_sub_ps(_mm_mul_ps(a, b), c); + } + static PA_FORCE_INLINE float vreduce(vtype a){ + return reduce32_x64_SSE(a); + } + + static PA_FORCE_INLINE void load2_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + PartialWordAccess_x64_SSE41 access(16 - length * 4); + A = access.load_f32_no_read_before_ptr((const float*)ptrA + length); + B = access.load_f32_no_read_before_ptr((const float*)ptrB + length); + } + static PA_FORCE_INLINE void load3_partial_back( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + PartialWordAccess_x64_SSE41 access(16 - length * 4); + A = access.load_f32_no_read_before_ptr((const float*)ptrA + length); + B = access.load_f32_no_read_before_ptr((const float*)ptrB + length); + C = access.load_f32_no_read_before_ptr((const float*)ptrC + length); + } + static PA_FORCE_INLINE void load2_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB + ){ + PartialWordAccess_x64_SSE41 access(length * 4); + A = access.load_f32_no_read_past_end(ptrA); + B = access.load_f32_no_read_past_end(ptrB); + } + static PA_FORCE_INLINE void load3_partial_front( + size_t length, + vtype& A, const void* ptrA, + vtype& B, const void* ptrB, + vtype& C, const void* ptrC + ){ + PartialWordAccess_x64_SSE41 access(length * 4); + A = access.load_f32_no_read_past_end(ptrA); + B = access.load_f32_no_read_past_end(ptrB); + C = access.load_f32_no_read_past_end(ptrC); + } +}; + + + +float compute_scale_min4_x86_SSE( + size_t width, size_t height, + float const* const* A, + float const* const* T +){ + return compute_scale>(width, height, A, T); +} +float compute_scale_min4_x86_SSE( + size_t width, size_t height, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_scale>(width, height, A, TW, W); +} +float compute_error_min4_x86_SSE( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +){ + return compute_error>(width, height, scale, A, T); +} +float compute_error_min4_x86_SSE( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, + float const* const* W +){ + return compute_error>(width, height, scale, A, TW, W); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Routines.h b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Routines.h index da350a2474..a5babba328 100644 --- a/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Routines.h +++ b/SerialPrograms/Source/Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch_Routines.h @@ -1,445 +1,445 @@ -/* Scale Invariant Matrix Match Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_Routines_H -#define PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_Routines_H - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace ScaleInvariantMatrixMatch{ - - - -template -struct SumATA2{ - using vtype = typename Context::vtype; - static constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - vtype sum_AT = Context::vzero(); - vtype sum_A2 = Context::vzero(); - - PA_FORCE_INLINE float scale() const{ - return Context::vreduce(sum_AT) / Context::vreduce(sum_A2); - } - - PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* T){ - vtype sum_as0 = Context::vzero(); - vtype sum_as1 = Context::vzero(); - vtype sum_as2 = Context::vzero(); - vtype sum_as3 = Context::vzero(); - vtype sum_at0 = Context::vzero(); - vtype sum_at1 = Context::vzero(); - vtype sum_at2 = Context::vzero(); - vtype sum_at3 = Context::vzero(); - - if (VECTOR_LENGTH > 1){ - size_t align = (size_t)T % (VECTOR_LENGTH * sizeof(float)); - if (align){ - align /= sizeof(float); - A -= align; - T -= align; - - vtype a0, t0; - Context::load2_partial_back(align, a0, A, t0, T); - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_at0 = Context::vpma(a0, t0, sum_at0); - - A += VECTOR_LENGTH; - T += VECTOR_LENGTH; - length -= VECTOR_LENGTH - align; - } - } - - const vtype* ptrA = (const vtype*)A; - const vtype* ptrT = (const vtype*)T; - - size_t lc = length / (4 * VECTOR_LENGTH); - if (lc){ - do{ - vtype a0 = ptrA[0]; - vtype a1 = ptrA[1]; - vtype a2 = ptrA[2]; - vtype a3 = ptrA[3]; - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_as1 = Context::vpma(a1, a1, sum_as1); - sum_as2 = Context::vpma(a2, a2, sum_as2); - sum_as3 = Context::vpma(a3, a3, sum_as3); - sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); - sum_at1 = Context::vpma(a1, ptrT[1], sum_at1); - sum_at2 = Context::vpma(a2, ptrT[2], sum_at2); - sum_at3 = Context::vpma(a3, ptrT[3], sum_at3); - ptrA += 4; - ptrT += 4; - }while (--lc); - sum_as0 = Context::vadd(sum_as0, sum_as1); - sum_at0 = Context::vadd(sum_at0, sum_at1); - sum_as2 = Context::vadd(sum_as2, sum_as3); - sum_at2 = Context::vadd(sum_at2, sum_at3); - sum_as0 = Context::vadd(sum_as0, sum_as2); - sum_at0 = Context::vadd(sum_at0, sum_at2); - } - - length %= 4 * VECTOR_LENGTH; - while (length >= VECTOR_LENGTH){ - vtype a0 = ptrA[0]; - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); - ptrA += 1; - ptrT += 1; - length -= VECTOR_LENGTH; - } - if (VECTOR_LENGTH > 1 && length){ - vtype a0, t0; - Context::load2_partial_front(length, a0, ptrT, t0, ptrA); - sum_at0 = Context::vpma(a0, t0, sum_at0); - sum_as0 = Context::vpma(a0, a0, sum_as0); - } - - sum_A2 = Context::vadd(sum_A2, sum_as0); - sum_AT = Context::vadd(sum_AT, sum_at0); - } - PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* TW, const float* W){ - vtype sum_as0 = Context::vzero(); - vtype sum_as1 = Context::vzero(); - vtype sum_as2 = Context::vzero(); - vtype sum_as3 = Context::vzero(); - vtype sum_at0 = Context::vzero(); - vtype sum_at1 = Context::vzero(); - vtype sum_at2 = Context::vzero(); - vtype sum_at3 = Context::vzero(); - - if (VECTOR_LENGTH > 1){ - size_t align = (size_t)TW % (VECTOR_LENGTH * sizeof(float)); - if (align){ - align /= sizeof(float); - A -= align; - TW -= align; - W -= align; - - vtype a0, t0, w0; - Context::load3_partial_back(align, a0, A, t0, TW, w0, W); - a0 = Context::vmul(a0, w0); - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_at0 = Context::vpma(a0, t0, sum_at0); - - A += VECTOR_LENGTH; - TW += VECTOR_LENGTH; - W += VECTOR_LENGTH; - length -= VECTOR_LENGTH - align; - } - } - - const vtype* ptrA = (const vtype*)A; - const vtype* ptrT = (const vtype*)TW; - const vtype* ptrW = (const vtype*)W; - - size_t lc = length / (4 * VECTOR_LENGTH); - if (lc){ - do{ - vtype a0 = ptrA[0]; - vtype a1 = ptrA[1]; - vtype a2 = ptrA[2]; - vtype a3 = ptrA[3]; - a0 = Context::vmul(a0, ptrW[0]); - a1 = Context::vmul(a1, ptrW[1]); - a2 = Context::vmul(a2, ptrW[2]); - a3 = Context::vmul(a3, ptrW[3]); - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_as1 = Context::vpma(a1, a1, sum_as1); - sum_as2 = Context::vpma(a2, a2, sum_as2); - sum_as3 = Context::vpma(a3, a3, sum_as3); - sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); - sum_at1 = Context::vpma(a1, ptrT[1], sum_at1); - sum_at2 = Context::vpma(a2, ptrT[2], sum_at2); - sum_at3 = Context::vpma(a3, ptrT[3], sum_at3); - ptrA += 4; - ptrT += 4; - ptrW += 4; - }while (--lc); - sum_as0 = Context::vadd(sum_as0, sum_as1); - sum_at0 = Context::vadd(sum_at0, sum_at1); - sum_as2 = Context::vadd(sum_as2, sum_as3); - sum_at2 = Context::vadd(sum_at2, sum_at3); - sum_as0 = Context::vadd(sum_as0, sum_as2); - sum_at0 = Context::vadd(sum_at0, sum_at2); - } - - length %= 4 * VECTOR_LENGTH; - while (length >= VECTOR_LENGTH){ - vtype a0 = ptrA[0]; - a0 = Context::vmul(a0, ptrW[0]); - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); - ptrA += 1; - ptrT += 1; - ptrW += 1; - length -= VECTOR_LENGTH; - } - if (length){ - vtype a0, t0, w0; - Context::load3_partial_front(length, a0, A, t0, TW, w0, W); - a0 = Context::vmul(a0, w0); - sum_as0 = Context::vpma(a0, a0, sum_as0); - sum_at0 = Context::vpma(a0, t0, sum_at0); - } - - sum_A2 = Context::vadd(sum_A2, sum_as0); - sum_AT = Context::vadd(sum_AT, sum_at0); - } -}; - - - -template -struct SumError{ - using vtype = typename Context::vtype; - static constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - vtype scale; - vtype sum = Context::vzero(); - - PA_FORCE_INLINE SumError(float p_scale) - : scale(Context::vset(p_scale)) - {} - - PA_FORCE_INLINE float sum_sqr() const{ - return Context::vreduce(sum); - } - - PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* T){ - vtype sum0 = Context::vzero(); - vtype sum1 = Context::vzero(); - vtype sum2 = Context::vzero(); - vtype sum3 = Context::vzero(); - - if (VECTOR_LENGTH > 1){ - size_t align = (size_t)T % (VECTOR_LENGTH * sizeof(float)); - if (align){ - align /= sizeof(float); - A -= align; - T -= align; - - vtype a0, t0; - Context::load2_partial_back(align, a0, A, t0, T); - a0 = Context::vpms(scale, a0, t0); - sum0 = Context::vpma(a0, a0, sum0); - - A += VECTOR_LENGTH; - T += VECTOR_LENGTH; - length -= VECTOR_LENGTH - align; - } - } - - const vtype* ptrA = (const vtype*)A; - const vtype* ptrT = (const vtype*)T; - - size_t lc = length / (4 * VECTOR_LENGTH); - if (lc){ - do{ - vtype a0 = Context::vpms(scale, ptrA[0], ptrT[0]); - vtype a1 = Context::vpms(scale, ptrA[1], ptrT[1]); - vtype a2 = Context::vpms(scale, ptrA[2], ptrT[2]); - vtype a3 = Context::vpms(scale, ptrA[3], ptrT[3]); - sum0 = Context::vpma(a0, a0, sum0); - sum1 = Context::vpma(a1, a1, sum1); - sum2 = Context::vpma(a2, a2, sum2); - sum3 = Context::vpma(a3, a3, sum3); - ptrA += 4; - ptrT += 4; - }while (--lc); - sum0 = Context::vadd(sum0, sum1); - sum2 = Context::vadd(sum2, sum3); - sum0 = Context::vadd(sum0, sum2); - } - - length %= 4 * VECTOR_LENGTH; - while (length >= VECTOR_LENGTH){ - vtype a0 = Context::vpms(scale, ptrA[0], ptrT[0]); - sum0 = Context::vpma(a0, a0, sum0); - ptrA += 1; - ptrT += 1; - length -= VECTOR_LENGTH; - } - if (length){ - vtype a0, t0; - Context::load2_partial_front(length, a0, ptrT, t0, ptrA); - a0 = Context::vpms(scale, a0, t0); - sum0 = Context::vpma(a0, a0, sum0); - } - - sum = Context::vadd(sum, sum0); - } - PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* TW, const float* W){ - vtype sum0 = Context::vzero(); - vtype sum1 = Context::vzero(); - vtype sum2 = Context::vzero(); - vtype sum3 = Context::vzero(); - - if (VECTOR_LENGTH > 1){ - size_t align = (size_t)TW % (VECTOR_LENGTH * sizeof(float)); - if (align){ - align /= sizeof(float); - A -= align; - TW -= align; - W -= align; - - vtype a0, t0, w0; - Context::load3_partial_back(align, a0, A, t0, TW, w0, W); - a0 = Context::vmul(scale, a0); - a0 = Context::vpms(a0, w0, t0); - sum0 = Context::vpma(a0, a0, sum0); - - A += VECTOR_LENGTH; - TW += VECTOR_LENGTH; - W += VECTOR_LENGTH; - length -= VECTOR_LENGTH - align; - } - } - - const vtype* ptrA = (const vtype*)A; - const vtype* ptrT = (const vtype*)TW; - const vtype* ptrW = (const vtype*)W; - - size_t lc = length / (4 * VECTOR_LENGTH); - if (lc){ - do{ - vtype a0 = Context::vmul(scale, ptrA[0]); - vtype a1 = Context::vmul(scale, ptrA[1]); - vtype a2 = Context::vmul(scale, ptrA[2]); - vtype a3 = Context::vmul(scale, ptrA[3]); - a0 = Context::vpms(a0, ptrW[0], ptrT[0]); - a1 = Context::vpms(a1, ptrW[1], ptrT[1]); - a2 = Context::vpms(a2, ptrW[2], ptrT[2]); - a3 = Context::vpms(a3, ptrW[3], ptrT[3]); - sum0 = Context::vpma(a0, a0, sum0); - sum1 = Context::vpma(a1, a1, sum1); - sum2 = Context::vpma(a2, a2, sum2); - sum3 = Context::vpma(a3, a3, sum3); - ptrA += 4; - ptrT += 4; - ptrW += 4; - }while (--lc); - sum0 = Context::vadd(sum0, sum1); - sum2 = Context::vadd(sum2, sum3); - sum0 = Context::vadd(sum0, sum2); - } - - length %= 4 * VECTOR_LENGTH; - while (length >= VECTOR_LENGTH){ - vtype a0 = Context::vmul(scale, ptrA[0]); - a0 = Context::vpms(a0, ptrW[0], ptrT[0]); - sum0 = Context::vpma(a0, a0, sum0); - ptrA += 1; - ptrT += 1; - ptrW += 1; - length -= VECTOR_LENGTH; - } - if (length){ - vtype a0, t0, w0; - Context::load3_partial_front(length, a0, A, t0, TW, w0, W); - a0 = Context::vmul(scale, a0); - a0 = Context::vpms(a0, w0, t0); - sum0 = Context::vpma(a0, a0, sum0); - } - - sum = Context::vadd(sum, sum0); - } -}; - - - -template -PA_FORCE_INLINE float compute_scale( - size_t width, size_t height, - float const* const* A, - float const* const* T -){ - constexpr size_t ALIGNMENT = alignof(typename SumATA2::vtype); - SumATA2 sum; - for (size_t r = 0; r < height; r++){ - const float* ptrA = A[r]; - const float* ptrT = T[r]; - if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A and T must have the same alignment."); - } - sum.accumulate(width, ptrA, ptrT); - } - return sum.scale(); -} -template -PA_FORCE_INLINE float compute_scale( - size_t width, size_t height, - float const* const* A, - float const* const* TW, - float const* const* W -){ - constexpr size_t ALIGNMENT = alignof(typename SumATA2::vtype); - SumATA2 sum; - for (size_t r = 0; r < height; r++){ - const float* ptrA = A[r]; - const float* ptrT = TW[r]; - const float* ptrW = W[r]; - if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT || (size_t)ptrA % ALIGNMENT != (size_t)ptrW % ALIGNMENT){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A, TW2, and W2 must have the same alignment."); - } - sum.accumulate(width, ptrA, ptrT, ptrW); - } - return sum.scale(); -} - - -template -PA_FORCE_INLINE float compute_error( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* T -){ - constexpr size_t ALIGNMENT = alignof(typename SumError::vtype); - SumError sum(scale); - for (size_t r = 0; r < height; r++){ - const float* ptrA = A[r]; - const float* ptrT = T[r]; - if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A and T must have the same alignment."); - } - sum.accumulate(width, ptrA, ptrT); - } - return sum.sum_sqr(); -} -template -PA_FORCE_INLINE float compute_error( - size_t width, size_t height, - float scale, - float const* const* A, - float const* const* TW, - float const* const* W -){ - constexpr size_t ALIGNMENT = alignof(typename SumError::vtype); - SumError sum(scale); - for (size_t r = 0; r < height; r++){ - const float* ptrA = A[r]; - const float* ptrT = TW[r]; - const float* ptrW = W[r]; - if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT || (size_t)ptrA % ALIGNMENT != (size_t)ptrW % ALIGNMENT){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A, TW2, and W2 must have the same alignment."); - } - sum.accumulate(width, ptrA, ptrT, ptrW); - } - return sum.sum_sqr(); -} - - - - -} -} -} -#endif +/* Scale Invariant Matrix Match Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_Routines_H +#define PokemonAutomation_Kernels_ScaleInvariantMatrixMatch_Routines_H + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace ScaleInvariantMatrixMatch{ + + + +template +struct SumATA2{ + using vtype = typename Context::vtype; + static constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + vtype sum_AT = Context::vzero(); + vtype sum_A2 = Context::vzero(); + + PA_FORCE_INLINE float scale() const{ + return Context::vreduce(sum_AT) / Context::vreduce(sum_A2); + } + + PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* T){ + vtype sum_as0 = Context::vzero(); + vtype sum_as1 = Context::vzero(); + vtype sum_as2 = Context::vzero(); + vtype sum_as3 = Context::vzero(); + vtype sum_at0 = Context::vzero(); + vtype sum_at1 = Context::vzero(); + vtype sum_at2 = Context::vzero(); + vtype sum_at3 = Context::vzero(); + + if (VECTOR_LENGTH > 1){ + size_t align = (size_t)T % (VECTOR_LENGTH * sizeof(float)); + if (align){ + align /= sizeof(float); + A -= align; + T -= align; + + vtype a0, t0; + Context::load2_partial_back(align, a0, A, t0, T); + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_at0 = Context::vpma(a0, t0, sum_at0); + + A += VECTOR_LENGTH; + T += VECTOR_LENGTH; + length -= VECTOR_LENGTH - align; + } + } + + const vtype* ptrA = (const vtype*)A; + const vtype* ptrT = (const vtype*)T; + + size_t lc = length / (4 * VECTOR_LENGTH); + if (lc){ + do{ + vtype a0 = ptrA[0]; + vtype a1 = ptrA[1]; + vtype a2 = ptrA[2]; + vtype a3 = ptrA[3]; + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_as1 = Context::vpma(a1, a1, sum_as1); + sum_as2 = Context::vpma(a2, a2, sum_as2); + sum_as3 = Context::vpma(a3, a3, sum_as3); + sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); + sum_at1 = Context::vpma(a1, ptrT[1], sum_at1); + sum_at2 = Context::vpma(a2, ptrT[2], sum_at2); + sum_at3 = Context::vpma(a3, ptrT[3], sum_at3); + ptrA += 4; + ptrT += 4; + }while (--lc); + sum_as0 = Context::vadd(sum_as0, sum_as1); + sum_at0 = Context::vadd(sum_at0, sum_at1); + sum_as2 = Context::vadd(sum_as2, sum_as3); + sum_at2 = Context::vadd(sum_at2, sum_at3); + sum_as0 = Context::vadd(sum_as0, sum_as2); + sum_at0 = Context::vadd(sum_at0, sum_at2); + } + + length %= 4 * VECTOR_LENGTH; + while (length >= VECTOR_LENGTH){ + vtype a0 = ptrA[0]; + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); + ptrA += 1; + ptrT += 1; + length -= VECTOR_LENGTH; + } + if (VECTOR_LENGTH > 1 && length){ + vtype a0, t0; + Context::load2_partial_front(length, a0, ptrT, t0, ptrA); + sum_at0 = Context::vpma(a0, t0, sum_at0); + sum_as0 = Context::vpma(a0, a0, sum_as0); + } + + sum_A2 = Context::vadd(sum_A2, sum_as0); + sum_AT = Context::vadd(sum_AT, sum_at0); + } + PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* TW, const float* W){ + vtype sum_as0 = Context::vzero(); + vtype sum_as1 = Context::vzero(); + vtype sum_as2 = Context::vzero(); + vtype sum_as3 = Context::vzero(); + vtype sum_at0 = Context::vzero(); + vtype sum_at1 = Context::vzero(); + vtype sum_at2 = Context::vzero(); + vtype sum_at3 = Context::vzero(); + + if (VECTOR_LENGTH > 1){ + size_t align = (size_t)TW % (VECTOR_LENGTH * sizeof(float)); + if (align){ + align /= sizeof(float); + A -= align; + TW -= align; + W -= align; + + vtype a0, t0, w0; + Context::load3_partial_back(align, a0, A, t0, TW, w0, W); + a0 = Context::vmul(a0, w0); + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_at0 = Context::vpma(a0, t0, sum_at0); + + A += VECTOR_LENGTH; + TW += VECTOR_LENGTH; + W += VECTOR_LENGTH; + length -= VECTOR_LENGTH - align; + } + } + + const vtype* ptrA = (const vtype*)A; + const vtype* ptrT = (const vtype*)TW; + const vtype* ptrW = (const vtype*)W; + + size_t lc = length / (4 * VECTOR_LENGTH); + if (lc){ + do{ + vtype a0 = ptrA[0]; + vtype a1 = ptrA[1]; + vtype a2 = ptrA[2]; + vtype a3 = ptrA[3]; + a0 = Context::vmul(a0, ptrW[0]); + a1 = Context::vmul(a1, ptrW[1]); + a2 = Context::vmul(a2, ptrW[2]); + a3 = Context::vmul(a3, ptrW[3]); + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_as1 = Context::vpma(a1, a1, sum_as1); + sum_as2 = Context::vpma(a2, a2, sum_as2); + sum_as3 = Context::vpma(a3, a3, sum_as3); + sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); + sum_at1 = Context::vpma(a1, ptrT[1], sum_at1); + sum_at2 = Context::vpma(a2, ptrT[2], sum_at2); + sum_at3 = Context::vpma(a3, ptrT[3], sum_at3); + ptrA += 4; + ptrT += 4; + ptrW += 4; + }while (--lc); + sum_as0 = Context::vadd(sum_as0, sum_as1); + sum_at0 = Context::vadd(sum_at0, sum_at1); + sum_as2 = Context::vadd(sum_as2, sum_as3); + sum_at2 = Context::vadd(sum_at2, sum_at3); + sum_as0 = Context::vadd(sum_as0, sum_as2); + sum_at0 = Context::vadd(sum_at0, sum_at2); + } + + length %= 4 * VECTOR_LENGTH; + while (length >= VECTOR_LENGTH){ + vtype a0 = ptrA[0]; + a0 = Context::vmul(a0, ptrW[0]); + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_at0 = Context::vpma(a0, ptrT[0], sum_at0); + ptrA += 1; + ptrT += 1; + ptrW += 1; + length -= VECTOR_LENGTH; + } + if (length){ + vtype a0, t0, w0; + Context::load3_partial_front(length, a0, A, t0, TW, w0, W); + a0 = Context::vmul(a0, w0); + sum_as0 = Context::vpma(a0, a0, sum_as0); + sum_at0 = Context::vpma(a0, t0, sum_at0); + } + + sum_A2 = Context::vadd(sum_A2, sum_as0); + sum_AT = Context::vadd(sum_AT, sum_at0); + } +}; + + + +template +struct SumError{ + using vtype = typename Context::vtype; + static constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + vtype scale; + vtype sum = Context::vzero(); + + PA_FORCE_INLINE SumError(float p_scale) + : scale(Context::vset(p_scale)) + {} + + PA_FORCE_INLINE float sum_sqr() const{ + return Context::vreduce(sum); + } + + PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* T){ + vtype sum0 = Context::vzero(); + vtype sum1 = Context::vzero(); + vtype sum2 = Context::vzero(); + vtype sum3 = Context::vzero(); + + if (VECTOR_LENGTH > 1){ + size_t align = (size_t)T % (VECTOR_LENGTH * sizeof(float)); + if (align){ + align /= sizeof(float); + A -= align; + T -= align; + + vtype a0, t0; + Context::load2_partial_back(align, a0, A, t0, T); + a0 = Context::vpms(scale, a0, t0); + sum0 = Context::vpma(a0, a0, sum0); + + A += VECTOR_LENGTH; + T += VECTOR_LENGTH; + length -= VECTOR_LENGTH - align; + } + } + + const vtype* ptrA = (const vtype*)A; + const vtype* ptrT = (const vtype*)T; + + size_t lc = length / (4 * VECTOR_LENGTH); + if (lc){ + do{ + vtype a0 = Context::vpms(scale, ptrA[0], ptrT[0]); + vtype a1 = Context::vpms(scale, ptrA[1], ptrT[1]); + vtype a2 = Context::vpms(scale, ptrA[2], ptrT[2]); + vtype a3 = Context::vpms(scale, ptrA[3], ptrT[3]); + sum0 = Context::vpma(a0, a0, sum0); + sum1 = Context::vpma(a1, a1, sum1); + sum2 = Context::vpma(a2, a2, sum2); + sum3 = Context::vpma(a3, a3, sum3); + ptrA += 4; + ptrT += 4; + }while (--lc); + sum0 = Context::vadd(sum0, sum1); + sum2 = Context::vadd(sum2, sum3); + sum0 = Context::vadd(sum0, sum2); + } + + length %= 4 * VECTOR_LENGTH; + while (length >= VECTOR_LENGTH){ + vtype a0 = Context::vpms(scale, ptrA[0], ptrT[0]); + sum0 = Context::vpma(a0, a0, sum0); + ptrA += 1; + ptrT += 1; + length -= VECTOR_LENGTH; + } + if (length){ + vtype a0, t0; + Context::load2_partial_front(length, a0, ptrT, t0, ptrA); + a0 = Context::vpms(scale, a0, t0); + sum0 = Context::vpma(a0, a0, sum0); + } + + sum = Context::vadd(sum, sum0); + } + PA_FORCE_INLINE void accumulate(size_t length, const float* A, const float* TW, const float* W){ + vtype sum0 = Context::vzero(); + vtype sum1 = Context::vzero(); + vtype sum2 = Context::vzero(); + vtype sum3 = Context::vzero(); + + if (VECTOR_LENGTH > 1){ + size_t align = (size_t)TW % (VECTOR_LENGTH * sizeof(float)); + if (align){ + align /= sizeof(float); + A -= align; + TW -= align; + W -= align; + + vtype a0, t0, w0; + Context::load3_partial_back(align, a0, A, t0, TW, w0, W); + a0 = Context::vmul(scale, a0); + a0 = Context::vpms(a0, w0, t0); + sum0 = Context::vpma(a0, a0, sum0); + + A += VECTOR_LENGTH; + TW += VECTOR_LENGTH; + W += VECTOR_LENGTH; + length -= VECTOR_LENGTH - align; + } + } + + const vtype* ptrA = (const vtype*)A; + const vtype* ptrT = (const vtype*)TW; + const vtype* ptrW = (const vtype*)W; + + size_t lc = length / (4 * VECTOR_LENGTH); + if (lc){ + do{ + vtype a0 = Context::vmul(scale, ptrA[0]); + vtype a1 = Context::vmul(scale, ptrA[1]); + vtype a2 = Context::vmul(scale, ptrA[2]); + vtype a3 = Context::vmul(scale, ptrA[3]); + a0 = Context::vpms(a0, ptrW[0], ptrT[0]); + a1 = Context::vpms(a1, ptrW[1], ptrT[1]); + a2 = Context::vpms(a2, ptrW[2], ptrT[2]); + a3 = Context::vpms(a3, ptrW[3], ptrT[3]); + sum0 = Context::vpma(a0, a0, sum0); + sum1 = Context::vpma(a1, a1, sum1); + sum2 = Context::vpma(a2, a2, sum2); + sum3 = Context::vpma(a3, a3, sum3); + ptrA += 4; + ptrT += 4; + ptrW += 4; + }while (--lc); + sum0 = Context::vadd(sum0, sum1); + sum2 = Context::vadd(sum2, sum3); + sum0 = Context::vadd(sum0, sum2); + } + + length %= 4 * VECTOR_LENGTH; + while (length >= VECTOR_LENGTH){ + vtype a0 = Context::vmul(scale, ptrA[0]); + a0 = Context::vpms(a0, ptrW[0], ptrT[0]); + sum0 = Context::vpma(a0, a0, sum0); + ptrA += 1; + ptrT += 1; + ptrW += 1; + length -= VECTOR_LENGTH; + } + if (length){ + vtype a0, t0, w0; + Context::load3_partial_front(length, a0, A, t0, TW, w0, W); + a0 = Context::vmul(scale, a0); + a0 = Context::vpms(a0, w0, t0); + sum0 = Context::vpma(a0, a0, sum0); + } + + sum = Context::vadd(sum, sum0); + } +}; + + + +template +PA_FORCE_INLINE float compute_scale( + size_t width, size_t height, + float const* const* A, + float const* const* T +){ + constexpr size_t ALIGNMENT = alignof(typename SumATA2::vtype); + SumATA2 sum; + for (size_t r = 0; r < height; r++){ + const float* ptrA = A[r]; + const float* ptrT = T[r]; + if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A and T must have the same alignment."); + } + sum.accumulate(width, ptrA, ptrT); + } + return sum.scale(); +} +template +PA_FORCE_INLINE float compute_scale( + size_t width, size_t height, + float const* const* A, + float const* const* TW, + float const* const* W +){ + constexpr size_t ALIGNMENT = alignof(typename SumATA2::vtype); + SumATA2 sum; + for (size_t r = 0; r < height; r++){ + const float* ptrA = A[r]; + const float* ptrT = TW[r]; + const float* ptrW = W[r]; + if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT || (size_t)ptrA % ALIGNMENT != (size_t)ptrW % ALIGNMENT){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A, TW2, and W2 must have the same alignment."); + } + sum.accumulate(width, ptrA, ptrT, ptrW); + } + return sum.scale(); +} + + +template +PA_FORCE_INLINE float compute_error( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* T +){ + constexpr size_t ALIGNMENT = alignof(typename SumError::vtype); + SumError sum(scale); + for (size_t r = 0; r < height; r++){ + const float* ptrA = A[r]; + const float* ptrT = T[r]; + if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A and T must have the same alignment."); + } + sum.accumulate(width, ptrA, ptrT); + } + return sum.sum_sqr(); +} +template +PA_FORCE_INLINE float compute_error( + size_t width, size_t height, + float scale, + float const* const* A, + float const* const* TW, + float const* const* W +){ + constexpr size_t ALIGNMENT = alignof(typename SumError::vtype); + SumError sum(scale); + for (size_t r = 0; r < height; r++){ + const float* ptrA = A[r]; + const float* ptrT = TW[r]; + const float* ptrW = W[r]; + if ((size_t)ptrA % ALIGNMENT != (size_t)ptrT % ALIGNMENT || (size_t)ptrA % ALIGNMENT != (size_t)ptrW % ALIGNMENT){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A, TW2, and W2 must have the same alignment."); + } + sum.accumulate(width, ptrA, ptrT, ptrW); + } + return sum.sum_sqr(); +} + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.cpp b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.cpp index 72e7a64e8a..8c7b6f7a49 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.cpp +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.cpp @@ -1,48 +1,48 @@ -/* Spike Convolution - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_SpikeConvolution.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -void compute_spike_kernel_Default (float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); -void compute_spike_kernel_x86_SSE41 (float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); -void compute_spike_kernel_x86_AVX2 (float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); -void compute_spike_kernel_x86_AVX512(float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); - - -void compute_spike_kernel( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -){ -#ifdef PA_AutoDispatch_x64_17_Skylake - if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ - return compute_spike_kernel_x86_AVX512(out, in, lengthI, kernel, lengthK); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ - return compute_spike_kernel_x86_AVX2(out, in, lengthI, kernel, lengthK); - } -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ - return compute_spike_kernel_x86_SSE41(out, in, lengthI, kernel, lengthK); - } -#endif - return compute_spike_kernel_Default(out, in, lengthI, kernel, lengthK); -} - - - - -} -} -} +/* Spike Convolution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_SpikeConvolution.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +void compute_spike_kernel_Default (float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); +void compute_spike_kernel_x86_SSE41 (float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); +void compute_spike_kernel_x86_AVX2 (float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); +void compute_spike_kernel_x86_AVX512(float* out, const float* in, size_t lengthI, const float* kernel, size_t lengthK); + + +void compute_spike_kernel( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +){ +#ifdef PA_AutoDispatch_x64_17_Skylake + if (CPU_CAPABILITY_CURRENT.OK_17_Skylake){ + return compute_spike_kernel_x86_AVX512(out, in, lengthI, kernel, lengthK); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + if (CPU_CAPABILITY_CURRENT.OK_13_Haswell){ + return compute_spike_kernel_x86_AVX2(out, in, lengthI, kernel, lengthK); + } +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + if (CPU_CAPABILITY_CURRENT.OK_08_Nehalem){ + return compute_spike_kernel_x86_SSE41(out, in, lengthI, kernel, lengthK); + } +#endif + return compute_spike_kernel_Default(out, in, lengthI, kernel, lengthK); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.h b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.h index 9ca4feac45..baace2b57a 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.h +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution.h @@ -1,32 +1,32 @@ -/* Spike Convolution - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_SpikeConvolution_H -#define PokemonAutomation_Kernels_SpikeConvolution_H - -#include - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -// Compute the Spike Kernel -// "out" is aligned to "PA_ALIGNMENT" bytes. -// lengthI >= lengthK -// "in" is valid for lengthI -// "out" is valid for (lengthI - lengthK + 1) rounded up to PA_ALIGNMENT/sizeof(float) -void compute_spike_kernel( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -); - - - -} -} -} -#endif +/* Spike Convolution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_SpikeConvolution_H +#define PokemonAutomation_Kernels_SpikeConvolution_H + +#include + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +// Compute the Spike Kernel +// "out" is aligned to "PA_ALIGNMENT" bytes. +// lengthI >= lengthK +// "in" is valid for lengthI +// "out" is valid for (lengthI - lengthK + 1) rounded up to PA_ALIGNMENT/sizeof(float) +void compute_spike_kernel( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_Default.cpp b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_Default.cpp index c074171170..9c34496c8d 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_Default.cpp +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_Default.cpp @@ -1,61 +1,61 @@ -/* Scale Invariant Matrix Match (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels_SpikeConvolution_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -struct Context_Default{ - using vtype = float; - - static PA_FORCE_INLINE float broadcast(float x){ - return x; - } - static PA_FORCE_INLINE float load_partial(const float* ptr, size_t length){ - return ptr[0]; - } - static PA_FORCE_INLINE void store_partial(float* ptr, float x, size_t length){ - ptr[0] = x; - } - - static PA_FORCE_INLINE float multiply(float k0, float in){ - return k0 * in; - } - static PA_FORCE_INLINE void accumulate(float& out0, float k0, float in){ - out0 += k0 * in; - } - - static PA_FORCE_INLINE float multiply(float k0, const float* ptr){ - return k0 * ptr[0]; - } - static PA_FORCE_INLINE void accumulate(float& out0, float k0, const float* ptr){ - out0 += k0 * ptr[0]; - } - - static PA_FORCE_INLINE float multiply_partial(float k0, const float* ptr, size_t length){ - return k0 * ptr[0]; - } - static PA_FORCE_INLINE void accumulate_partial(float& out0, float k0, const float* ptr, size_t length){ - out0 += k0 * ptr[0]; - } -}; - - -void compute_spike_kernel_Default( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -){ - compute_spike_kernel(out, in, lengthI, kernel, lengthK); -} - - - -} -} -} +/* Scale Invariant Matrix Match (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels_SpikeConvolution_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +struct Context_Default{ + using vtype = float; + + static PA_FORCE_INLINE float broadcast(float x){ + return x; + } + static PA_FORCE_INLINE float load_partial(const float* ptr, size_t length){ + return ptr[0]; + } + static PA_FORCE_INLINE void store_partial(float* ptr, float x, size_t length){ + ptr[0] = x; + } + + static PA_FORCE_INLINE float multiply(float k0, float in){ + return k0 * in; + } + static PA_FORCE_INLINE void accumulate(float& out0, float k0, float in){ + out0 += k0 * in; + } + + static PA_FORCE_INLINE float multiply(float k0, const float* ptr){ + return k0 * ptr[0]; + } + static PA_FORCE_INLINE void accumulate(float& out0, float k0, const float* ptr){ + out0 += k0 * ptr[0]; + } + + static PA_FORCE_INLINE float multiply_partial(float k0, const float* ptr, size_t length){ + return k0 * ptr[0]; + } + static PA_FORCE_INLINE void accumulate_partial(float& out0, float k0, const float* ptr, size_t length){ + out0 += k0 * ptr[0]; + } +}; + + +void compute_spike_kernel_Default( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +){ + compute_spike_kernel(out, in, lengthI, kernel, lengthK); +} + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp index 5828c90ef1..a798407fbf 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX2.cpp @@ -1,73 +1,73 @@ -/* Scale Invariant Matrix Match (x86 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels_SpikeConvolution_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -struct Context_x86_AVX2{ - using vtype = __m256; - - static PA_FORCE_INLINE __m256 broadcast(float x){ - return _mm256_set1_ps(x); - } - static PA_FORCE_INLINE __m256 load_partial(const float* ptr, size_t length){ - __m256i mask = _mm256_cmpgt_epi32( - _mm256_set1_epi32((uint32_t)length), - _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) - ); - return _mm256_maskload_ps((const float*)ptr, mask); - } - static PA_FORCE_INLINE void store_partial(float* ptr, __m256 x, size_t length){ - __m256i mask = _mm256_cmpgt_epi32( - _mm256_set1_epi32((uint32_t)length), - _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) - ); - _mm256_maskstore_ps((float*)ptr, mask, x); - } - - static PA_FORCE_INLINE __m256 multiply(__m256 k0, __m256 in){ - return _mm256_mul_ps(k0, in); - } - static PA_FORCE_INLINE void accumulate(__m256& out0, __m256 k0, __m256 in){ - out0 = _mm256_fmadd_ps(k0, in, out0); - } - - static PA_FORCE_INLINE __m256 multiply(__m256 k0, const float* ptr){ - return multiply(k0, _mm256_loadu_ps(ptr)); - } - static PA_FORCE_INLINE void accumulate(__m256& out0, __m256 k0, const float* ptr){ - accumulate(out0, k0, _mm256_loadu_ps(ptr)); - } - - static PA_FORCE_INLINE __m256 multiply_partial(__m256 k0, const float* ptr, size_t length){ - return multiply(k0, load_partial(ptr, length)); - } - static PA_FORCE_INLINE void accumulate_partial(__m256& out0, __m256 k0, const float* ptr, size_t length){ - accumulate(out0, k0, load_partial(ptr, length)); - } -}; - - -void compute_spike_kernel_x86_AVX2( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -){ - compute_spike_kernel(out, in, lengthI, kernel, lengthK); -} - - - -} -} -} -#endif +/* Scale Invariant Matrix Match (x86 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels_SpikeConvolution_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +struct Context_x86_AVX2{ + using vtype = __m256; + + static PA_FORCE_INLINE __m256 broadcast(float x){ + return _mm256_set1_ps(x); + } + static PA_FORCE_INLINE __m256 load_partial(const float* ptr, size_t length){ + __m256i mask = _mm256_cmpgt_epi32( + _mm256_set1_epi32((uint32_t)length), + _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) + ); + return _mm256_maskload_ps((const float*)ptr, mask); + } + static PA_FORCE_INLINE void store_partial(float* ptr, __m256 x, size_t length){ + __m256i mask = _mm256_cmpgt_epi32( + _mm256_set1_epi32((uint32_t)length), + _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7) + ); + _mm256_maskstore_ps((float*)ptr, mask, x); + } + + static PA_FORCE_INLINE __m256 multiply(__m256 k0, __m256 in){ + return _mm256_mul_ps(k0, in); + } + static PA_FORCE_INLINE void accumulate(__m256& out0, __m256 k0, __m256 in){ + out0 = _mm256_fmadd_ps(k0, in, out0); + } + + static PA_FORCE_INLINE __m256 multiply(__m256 k0, const float* ptr){ + return multiply(k0, _mm256_loadu_ps(ptr)); + } + static PA_FORCE_INLINE void accumulate(__m256& out0, __m256 k0, const float* ptr){ + accumulate(out0, k0, _mm256_loadu_ps(ptr)); + } + + static PA_FORCE_INLINE __m256 multiply_partial(__m256 k0, const float* ptr, size_t length){ + return multiply(k0, load_partial(ptr, length)); + } + static PA_FORCE_INLINE void accumulate_partial(__m256& out0, __m256 k0, const float* ptr, size_t length){ + accumulate(out0, k0, load_partial(ptr, length)); + } +}; + + +void compute_spike_kernel_x86_AVX2( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +){ + compute_spike_kernel(out, in, lengthI, kernel, lengthK); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp index 8773997fac..f3f4c4eeb3 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_AVX512.cpp @@ -1,67 +1,67 @@ -/* Scale Invariant Matrix Match (x86 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -#include "Kernels_SpikeConvolution_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -struct Context_x86_AVX512{ - using vtype = __m512; - - static PA_FORCE_INLINE __m512 broadcast(float x){ - return _mm512_set1_ps(x); - } - static PA_FORCE_INLINE __m512 load_partial(const float* ptr, size_t length){ - __mmask16 mask = ((uint16_t)1 << length) - 1; - return _mm512_maskz_load_ps(mask, ptr); - } - static PA_FORCE_INLINE void store_partial(float* ptr, __m512 x, size_t length){ - __mmask16 mask = ((uint16_t)1 << length) - 1; - _mm512_mask_store_ps(ptr, mask, x); - } - - static PA_FORCE_INLINE __m512 multiply(__m512 k0, __m512 in){ - return _mm512_mul_ps(k0, in); - } - static PA_FORCE_INLINE void accumulate(__m512& out0, __m512 k0, __m512 in){ - out0 = _mm512_fmadd_ps(k0, in, out0); - } - - static PA_FORCE_INLINE __m512 multiply(__m512 k0, const float* ptr){ - return multiply(k0, _mm512_loadu_ps(ptr)); - } - static PA_FORCE_INLINE void accumulate(__m512& out0, __m512 k0, const float* ptr){ - accumulate(out0, k0, _mm512_loadu_ps(ptr)); - } - - static PA_FORCE_INLINE __m512 multiply_partial(__m512 k0, const float* ptr, size_t length){ - return multiply(k0, load_partial(ptr, length)); - } - static PA_FORCE_INLINE void accumulate_partial(__m512& out0, __m512 k0, const float* ptr, size_t length){ - accumulate(out0, k0, load_partial(ptr, length)); - } -}; - - -void compute_spike_kernel_x86_AVX512( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -){ - compute_spike_kernel(out, in, lengthI, kernel, lengthK); -} - - - -} -} -} -#endif +/* Scale Invariant Matrix Match (x86 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +#include "Kernels_SpikeConvolution_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +struct Context_x86_AVX512{ + using vtype = __m512; + + static PA_FORCE_INLINE __m512 broadcast(float x){ + return _mm512_set1_ps(x); + } + static PA_FORCE_INLINE __m512 load_partial(const float* ptr, size_t length){ + __mmask16 mask = ((uint16_t)1 << length) - 1; + return _mm512_maskz_load_ps(mask, ptr); + } + static PA_FORCE_INLINE void store_partial(float* ptr, __m512 x, size_t length){ + __mmask16 mask = ((uint16_t)1 << length) - 1; + _mm512_mask_store_ps(ptr, mask, x); + } + + static PA_FORCE_INLINE __m512 multiply(__m512 k0, __m512 in){ + return _mm512_mul_ps(k0, in); + } + static PA_FORCE_INLINE void accumulate(__m512& out0, __m512 k0, __m512 in){ + out0 = _mm512_fmadd_ps(k0, in, out0); + } + + static PA_FORCE_INLINE __m512 multiply(__m512 k0, const float* ptr){ + return multiply(k0, _mm512_loadu_ps(ptr)); + } + static PA_FORCE_INLINE void accumulate(__m512& out0, __m512 k0, const float* ptr){ + accumulate(out0, k0, _mm512_loadu_ps(ptr)); + } + + static PA_FORCE_INLINE __m512 multiply_partial(__m512 k0, const float* ptr, size_t length){ + return multiply(k0, load_partial(ptr, length)); + } + static PA_FORCE_INLINE void accumulate_partial(__m512& out0, __m512 k0, const float* ptr, size_t length){ + accumulate(out0, k0, load_partial(ptr, length)); + } +}; + + +void compute_spike_kernel_x86_AVX512( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +){ + compute_spike_kernel(out, in, lengthI, kernel, lengthK); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp index 1f8b748568..650fdcc6b8 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Core_x86_SSE41.cpp @@ -1,67 +1,67 @@ -/* Scale Invariant Matrix Match (x86 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -#include "Kernels_SpikeConvolution_Routines.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -struct Context_x86_SSE41{ - using vtype = __m128; - - static PA_FORCE_INLINE __m128 broadcast(float x){ - return _mm_set1_ps(x); - } - static PA_FORCE_INLINE __m128 load_partial(const float* ptr, size_t length){ - PartialWordAccess_x64_SSE41 access(length * sizeof(float)); - return access.load_f32_no_read_past_end(ptr); - } - static PA_FORCE_INLINE void store_partial(float* ptr, __m128 x, size_t length){ - PartialWordAccess_x64_SSE41 access(length * sizeof(float)); - return access.store_f32_no_past_end(ptr, x); - } - - static PA_FORCE_INLINE __m128 multiply(__m128 k0, __m128 in){ - return _mm_mul_ps(k0, in); - } - static PA_FORCE_INLINE void accumulate(__m128& out0, __m128 k0, __m128 in){ - out0 = _mm_add_ps(out0, _mm_mul_ps(k0, in)); - } - - static PA_FORCE_INLINE __m128 multiply(__m128 k0, const float* ptr){ - return multiply(k0, _mm_loadu_ps(ptr)); - } - static PA_FORCE_INLINE void accumulate(__m128& out0, __m128 k0, const float* ptr){ - accumulate(out0, k0, _mm_loadu_ps(ptr)); - } - - static PA_FORCE_INLINE __m128 multiply_partial(__m128 k0, const float* ptr, size_t length){ - return multiply(k0, load_partial(ptr, length)); - } - static PA_FORCE_INLINE void accumulate_partial(__m128& out0, __m128 k0, const float* ptr, size_t length){ - accumulate(out0, k0, load_partial(ptr, length)); - } -}; - - -void compute_spike_kernel_x86_SSE41( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -){ - compute_spike_kernel(out, in, lengthI, kernel, lengthK); -} - - - -} -} -} -#endif +/* Scale Invariant Matrix Match (x86 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +#include "Kernels_SpikeConvolution_Routines.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +struct Context_x86_SSE41{ + using vtype = __m128; + + static PA_FORCE_INLINE __m128 broadcast(float x){ + return _mm_set1_ps(x); + } + static PA_FORCE_INLINE __m128 load_partial(const float* ptr, size_t length){ + PartialWordAccess_x64_SSE41 access(length * sizeof(float)); + return access.load_f32_no_read_past_end(ptr); + } + static PA_FORCE_INLINE void store_partial(float* ptr, __m128 x, size_t length){ + PartialWordAccess_x64_SSE41 access(length * sizeof(float)); + return access.store_f32_no_past_end(ptr, x); + } + + static PA_FORCE_INLINE __m128 multiply(__m128 k0, __m128 in){ + return _mm_mul_ps(k0, in); + } + static PA_FORCE_INLINE void accumulate(__m128& out0, __m128 k0, __m128 in){ + out0 = _mm_add_ps(out0, _mm_mul_ps(k0, in)); + } + + static PA_FORCE_INLINE __m128 multiply(__m128 k0, const float* ptr){ + return multiply(k0, _mm_loadu_ps(ptr)); + } + static PA_FORCE_INLINE void accumulate(__m128& out0, __m128 k0, const float* ptr){ + accumulate(out0, k0, _mm_loadu_ps(ptr)); + } + + static PA_FORCE_INLINE __m128 multiply_partial(__m128 k0, const float* ptr, size_t length){ + return multiply(k0, load_partial(ptr, length)); + } + static PA_FORCE_INLINE void accumulate_partial(__m128& out0, __m128 k0, const float* ptr, size_t length){ + accumulate(out0, k0, load_partial(ptr, length)); + } +}; + + +void compute_spike_kernel_x86_SSE41( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +){ + compute_spike_kernel(out, in, lengthI, kernel, lengthK); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Routines.h b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Routines.h index f62037c24e..6ae28347ea 100644 --- a/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Routines.h +++ b/SerialPrograms/Source/Kernels/SpikeConvolution/Kernels_SpikeConvolution_Routines.h @@ -1,386 +1,386 @@ -/* Spike Convolution - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_SpikeConvolution_Routines_H -#define PokemonAutomation_Kernels_SpikeConvolution_Routines_H - -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ -namespace SpikeConvolution{ - - -template -PA_FORCE_INLINE void accumulate_k1( - typename Context::vtype* out, const float* in, size_t lengthI, - typename Context::vtype k0 -){ - using vtype = typename Context::vtype; - constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - size_t lc = lengthI / (4 * VECTOR_LENGTH); - while (lc--){ - vtype out0, out1, out2, out3; - if (addto){ - out0 = out[0]; - out1 = out[1]; - out2 = out[2]; - out3 = out[3]; - Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); - Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); - Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); - Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); - }else{ - out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); - out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); - out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); - out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); - } - out[0] = out0; - out[1] = out1; - out[2] = out2; - out[3] = out3; - in += 4 * VECTOR_LENGTH; - out += 4; - } - lengthI %= 4 * VECTOR_LENGTH; - while (lengthI >= VECTOR_LENGTH){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); - }else{ - out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); - } - out[0] = out0; - in += VECTOR_LENGTH; - out += 1; - lengthI -= VECTOR_LENGTH; - } - if (lengthI){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate_partial(out0, k0, in, lengthI); - }else{ - out0 = Context::multiply_partial(k0, in, lengthI); - } -// Context::store_partial((float*)out, out0, lengthI); - out[0] = out0; - } -} -template -PA_FORCE_INLINE void accumulate_k2( - typename Context::vtype* out, const float* in, size_t lengthI, - typename Context::vtype k0, - typename Context::vtype k1 -){ - using vtype = typename Context::vtype; - constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - size_t lc = lengthI / (4 * VECTOR_LENGTH); - while (lc--){ - vtype out0, out1, out2, out3; - if (addto){ - out0 = out[0]; - out1 = out[1]; - out2 = out[2]; - out3 = out[3]; - Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); - Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); - Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); - Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); - }else{ - out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); - out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); - out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); - out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); - } - Context::accumulate(out0, k1, in + 0 * VECTOR_LENGTH + 1); - Context::accumulate(out1, k1, in + 1 * VECTOR_LENGTH + 1); - Context::accumulate(out2, k1, in + 2 * VECTOR_LENGTH + 1); - Context::accumulate(out3, k1, in + 3 * VECTOR_LENGTH + 1); - out[0] = out0; - out[1] = out1; - out[2] = out2; - out[3] = out3; - in += 4 * VECTOR_LENGTH; - out += 4; - } - lengthI %= 4 * VECTOR_LENGTH; - while (lengthI >= VECTOR_LENGTH){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate(out0, k0, in); - }else{ - out0 = Context::multiply(k0, in); - } - Context::accumulate(out0, k1, in + 1); - out[0] = out0; - in += VECTOR_LENGTH; - out += 1; - lengthI -= VECTOR_LENGTH; - } - if (lengthI){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate_partial(out0, k0, in, lengthI); - }else{ - out0 = Context::multiply_partial(k0, in, lengthI); - } - Context::accumulate_partial(out0, k1, in + 1, lengthI); -// Context::store_partial((float*)out, out0, lengthI); - out[0] = out0; - } -} -template -PA_FORCE_INLINE void accumulate_k3( - typename Context::vtype* out, const float* in, size_t lengthI, - typename Context::vtype k0, - typename Context::vtype k1, - typename Context::vtype k2 -){ - using vtype = typename Context::vtype; - constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - size_t lc = lengthI / (4 * VECTOR_LENGTH); - while (lc--){ - vtype out0, out1, out2, out3; - if (addto){ - out0 = out[0]; - out1 = out[1]; - out2 = out[2]; - out3 = out[3]; - Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); - Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); - Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); - Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); - }else{ - out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); - out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); - out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); - out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); - } - Context::accumulate(out0, k1, in + 0 * VECTOR_LENGTH + 1); - Context::accumulate(out1, k1, in + 1 * VECTOR_LENGTH + 1); - Context::accumulate(out2, k1, in + 2 * VECTOR_LENGTH + 1); - Context::accumulate(out3, k1, in + 3 * VECTOR_LENGTH + 1); - Context::accumulate(out0, k2, in + 0 * VECTOR_LENGTH + 2); - Context::accumulate(out1, k2, in + 1 * VECTOR_LENGTH + 2); - Context::accumulate(out2, k2, in + 2 * VECTOR_LENGTH + 2); - Context::accumulate(out3, k2, in + 3 * VECTOR_LENGTH + 2); - out[0] = out0; - out[1] = out1; - out[2] = out2; - out[3] = out3; - in += 4 * VECTOR_LENGTH; - out += 4; - } - lengthI %= 4 * VECTOR_LENGTH; - while (lengthI >= VECTOR_LENGTH){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate(out0, k0, in); - }else{ - out0 = Context::multiply(k0, in); - } - Context::accumulate(out0, k1, in + 1); - Context::accumulate(out0, k2, in + 2); - out[0] = out0; - in += VECTOR_LENGTH; - out += 1; - lengthI -= VECTOR_LENGTH; - } - if (lengthI){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate_partial(out0, k0, in, lengthI); - }else{ - out0 = Context::multiply_partial(k0, in, lengthI); - } - Context::accumulate_partial(out0, k1, in + 1, lengthI); - Context::accumulate_partial(out0, k2, in + 2, lengthI); -// Context::store_partial((float*)out, out0, lengthI); - out[0] = out0; - } -} -template -PA_FORCE_INLINE void accumulate_k4( - typename Context::vtype* out, const float* in, size_t lengthI, - typename Context::vtype k0, - typename Context::vtype k1, - typename Context::vtype k2, - typename Context::vtype k3 -){ - using vtype = typename Context::vtype; - constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - size_t lc = lengthI / (4 * VECTOR_LENGTH); - while (lc--){ - vtype out0, out1, out2, out3; - if (addto){ - out0 = out[0]; - out1 = out[1]; - out2 = out[2]; - out3 = out[3]; - Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); - Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); - Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); - Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); - }else{ - out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); - out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); - out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); - out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); - } - Context::accumulate(out0, k1, in + 0 * VECTOR_LENGTH + 1); - Context::accumulate(out1, k1, in + 1 * VECTOR_LENGTH + 1); - Context::accumulate(out2, k1, in + 2 * VECTOR_LENGTH + 1); - Context::accumulate(out3, k1, in + 3 * VECTOR_LENGTH + 1); - Context::accumulate(out0, k2, in + 0 * VECTOR_LENGTH + 2); - Context::accumulate(out1, k2, in + 1 * VECTOR_LENGTH + 2); - Context::accumulate(out2, k2, in + 2 * VECTOR_LENGTH + 2); - Context::accumulate(out3, k2, in + 3 * VECTOR_LENGTH + 2); - Context::accumulate(out0, k3, in + 0 * VECTOR_LENGTH + 3); - Context::accumulate(out1, k3, in + 1 * VECTOR_LENGTH + 3); - Context::accumulate(out2, k3, in + 2 * VECTOR_LENGTH + 3); - Context::accumulate(out3, k3, in + 3 * VECTOR_LENGTH + 3); - out[0] = out0; - out[1] = out1; - out[2] = out2; - out[3] = out3; - in += 4 * VECTOR_LENGTH; - out += 4; - } - lengthI %= 4 * VECTOR_LENGTH; - while (lengthI >= VECTOR_LENGTH){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate(out0, k0, in); - }else{ - out0 = Context::multiply(k0, in); - } - Context::accumulate(out0, k1, in + 1); - Context::accumulate(out0, k2, in + 2); - Context::accumulate(out0, k3, in + 3); - out[0] = out0; - in += VECTOR_LENGTH; - out += 1; - lengthI -= VECTOR_LENGTH; - } - if (lengthI){ - vtype out0; - if (addto){ - out0 = out[0]; - Context::accumulate_partial(out0, k0, in, lengthI); - }else{ - out0 = Context::multiply_partial(k0, in, lengthI); - } - Context::accumulate_partial(out0, k1, in + 1, lengthI); - Context::accumulate_partial(out0, k2, in + 2, lengthI); - Context::accumulate_partial(out0, k3, in + 3, lengthI); -// Context::store_partial((float*)out, out0, lengthI); - out[0] = out0; - } -} - - - -// Compute the Spike Kernel -// "out" is aligned to "PA_ALIGNMENT" bytes. -// lengthI >= lengthK -// "in" is valid for lengthI -// "out" is valid for (lengthI - lengthK + 1) rounded up to PA_ALIGNMENT/sizeof(float) -template -PA_FORCE_INLINE void compute_spike_kernel( - float* out, const float* in, size_t lengthI, - const float* kernel, size_t lengthK -){ -// constexpr size_t FLOAT_ALIGNMENT = PA_ALIGNMENT / sizeof(float); - using vtype = typename Context::vtype; -// constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); - - if ((size_t)out % PA_ALIGNMENT){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "\"out\" is misaligned."); - } -// if (lengthI % FLOAT_ALIGNMENT){ -// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "lengthI is misaligned."); -// } - if (lengthI < lengthK){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "lengthK < lengthI"); - } - - lengthI = lengthI - lengthK + 1; -// size_t lengthO = (lengthI + VECTOR_LENGTH - 1) / VECTOR_LENGTH; -// cout << "lengthI = " << lengthI << endl; -// cout << "lengthO = " << lengthO << endl; - - bool first = true; - - while (lengthK >= 4){ - vtype k0 = Context::broadcast(kernel[0]); - vtype k1 = Context::broadcast(kernel[1]); - vtype k2 = Context::broadcast(kernel[2]); - vtype k3 = Context::broadcast(kernel[3]); - if (first){ - accumulate_k4((vtype*)out, in, lengthI, k0, k1, k2, k3); - first = false; - }else{ - accumulate_k4((vtype*)out, in, lengthI, k0, k1, k2, k3); - } - in += 4; - kernel += 4; - lengthK -= 4; - } - if (lengthK == 3){ - vtype k0 = Context::broadcast(kernel[0]); - vtype k1 = Context::broadcast(kernel[1]); - vtype k2 = Context::broadcast(kernel[2]); - if (first){ - accumulate_k3((vtype*)out, in, lengthI, k0, k1, k2); - }else{ - accumulate_k3((vtype*)out, in, lengthI, k0, k1, k2); - } - return; - } - if (lengthK == 2){ - vtype k0 = Context::broadcast(kernel[0]); - vtype k1 = Context::broadcast(kernel[1]); - if (first){ - accumulate_k2((vtype*)out, in, lengthI, k0, k1); - }else{ - accumulate_k2((vtype*)out, in, lengthI, k0, k1); - } - return; - } - if (lengthK == 1){ - vtype k0 = Context::broadcast(kernel[0]); - if (first){ - accumulate_k1((vtype*)out, in, lengthI, k0); - }else{ - accumulate_k1((vtype*)out, in, lengthI, k0); - } - return; - } -} - - - -} -} -} -#endif +/* Spike Convolution + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_SpikeConvolution_Routines_H +#define PokemonAutomation_Kernels_SpikeConvolution_Routines_H + +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ +namespace SpikeConvolution{ + + +template +PA_FORCE_INLINE void accumulate_k1( + typename Context::vtype* out, const float* in, size_t lengthI, + typename Context::vtype k0 +){ + using vtype = typename Context::vtype; + constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + size_t lc = lengthI / (4 * VECTOR_LENGTH); + while (lc--){ + vtype out0, out1, out2, out3; + if (addto){ + out0 = out[0]; + out1 = out[1]; + out2 = out[2]; + out3 = out[3]; + Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); + Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); + Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); + Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); + }else{ + out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); + out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); + out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); + out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); + } + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = out3; + in += 4 * VECTOR_LENGTH; + out += 4; + } + lengthI %= 4 * VECTOR_LENGTH; + while (lengthI >= VECTOR_LENGTH){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); + }else{ + out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); + } + out[0] = out0; + in += VECTOR_LENGTH; + out += 1; + lengthI -= VECTOR_LENGTH; + } + if (lengthI){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate_partial(out0, k0, in, lengthI); + }else{ + out0 = Context::multiply_partial(k0, in, lengthI); + } +// Context::store_partial((float*)out, out0, lengthI); + out[0] = out0; + } +} +template +PA_FORCE_INLINE void accumulate_k2( + typename Context::vtype* out, const float* in, size_t lengthI, + typename Context::vtype k0, + typename Context::vtype k1 +){ + using vtype = typename Context::vtype; + constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + size_t lc = lengthI / (4 * VECTOR_LENGTH); + while (lc--){ + vtype out0, out1, out2, out3; + if (addto){ + out0 = out[0]; + out1 = out[1]; + out2 = out[2]; + out3 = out[3]; + Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); + Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); + Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); + Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); + }else{ + out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); + out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); + out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); + out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); + } + Context::accumulate(out0, k1, in + 0 * VECTOR_LENGTH + 1); + Context::accumulate(out1, k1, in + 1 * VECTOR_LENGTH + 1); + Context::accumulate(out2, k1, in + 2 * VECTOR_LENGTH + 1); + Context::accumulate(out3, k1, in + 3 * VECTOR_LENGTH + 1); + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = out3; + in += 4 * VECTOR_LENGTH; + out += 4; + } + lengthI %= 4 * VECTOR_LENGTH; + while (lengthI >= VECTOR_LENGTH){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate(out0, k0, in); + }else{ + out0 = Context::multiply(k0, in); + } + Context::accumulate(out0, k1, in + 1); + out[0] = out0; + in += VECTOR_LENGTH; + out += 1; + lengthI -= VECTOR_LENGTH; + } + if (lengthI){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate_partial(out0, k0, in, lengthI); + }else{ + out0 = Context::multiply_partial(k0, in, lengthI); + } + Context::accumulate_partial(out0, k1, in + 1, lengthI); +// Context::store_partial((float*)out, out0, lengthI); + out[0] = out0; + } +} +template +PA_FORCE_INLINE void accumulate_k3( + typename Context::vtype* out, const float* in, size_t lengthI, + typename Context::vtype k0, + typename Context::vtype k1, + typename Context::vtype k2 +){ + using vtype = typename Context::vtype; + constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + size_t lc = lengthI / (4 * VECTOR_LENGTH); + while (lc--){ + vtype out0, out1, out2, out3; + if (addto){ + out0 = out[0]; + out1 = out[1]; + out2 = out[2]; + out3 = out[3]; + Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); + Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); + Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); + Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); + }else{ + out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); + out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); + out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); + out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); + } + Context::accumulate(out0, k1, in + 0 * VECTOR_LENGTH + 1); + Context::accumulate(out1, k1, in + 1 * VECTOR_LENGTH + 1); + Context::accumulate(out2, k1, in + 2 * VECTOR_LENGTH + 1); + Context::accumulate(out3, k1, in + 3 * VECTOR_LENGTH + 1); + Context::accumulate(out0, k2, in + 0 * VECTOR_LENGTH + 2); + Context::accumulate(out1, k2, in + 1 * VECTOR_LENGTH + 2); + Context::accumulate(out2, k2, in + 2 * VECTOR_LENGTH + 2); + Context::accumulate(out3, k2, in + 3 * VECTOR_LENGTH + 2); + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = out3; + in += 4 * VECTOR_LENGTH; + out += 4; + } + lengthI %= 4 * VECTOR_LENGTH; + while (lengthI >= VECTOR_LENGTH){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate(out0, k0, in); + }else{ + out0 = Context::multiply(k0, in); + } + Context::accumulate(out0, k1, in + 1); + Context::accumulate(out0, k2, in + 2); + out[0] = out0; + in += VECTOR_LENGTH; + out += 1; + lengthI -= VECTOR_LENGTH; + } + if (lengthI){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate_partial(out0, k0, in, lengthI); + }else{ + out0 = Context::multiply_partial(k0, in, lengthI); + } + Context::accumulate_partial(out0, k1, in + 1, lengthI); + Context::accumulate_partial(out0, k2, in + 2, lengthI); +// Context::store_partial((float*)out, out0, lengthI); + out[0] = out0; + } +} +template +PA_FORCE_INLINE void accumulate_k4( + typename Context::vtype* out, const float* in, size_t lengthI, + typename Context::vtype k0, + typename Context::vtype k1, + typename Context::vtype k2, + typename Context::vtype k3 +){ + using vtype = typename Context::vtype; + constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + size_t lc = lengthI / (4 * VECTOR_LENGTH); + while (lc--){ + vtype out0, out1, out2, out3; + if (addto){ + out0 = out[0]; + out1 = out[1]; + out2 = out[2]; + out3 = out[3]; + Context::accumulate(out0, k0, in + 0 * VECTOR_LENGTH); + Context::accumulate(out1, k0, in + 1 * VECTOR_LENGTH); + Context::accumulate(out2, k0, in + 2 * VECTOR_LENGTH); + Context::accumulate(out3, k0, in + 3 * VECTOR_LENGTH); + }else{ + out0 = Context::multiply(k0, in + 0 * VECTOR_LENGTH); + out1 = Context::multiply(k0, in + 1 * VECTOR_LENGTH); + out2 = Context::multiply(k0, in + 2 * VECTOR_LENGTH); + out3 = Context::multiply(k0, in + 3 * VECTOR_LENGTH); + } + Context::accumulate(out0, k1, in + 0 * VECTOR_LENGTH + 1); + Context::accumulate(out1, k1, in + 1 * VECTOR_LENGTH + 1); + Context::accumulate(out2, k1, in + 2 * VECTOR_LENGTH + 1); + Context::accumulate(out3, k1, in + 3 * VECTOR_LENGTH + 1); + Context::accumulate(out0, k2, in + 0 * VECTOR_LENGTH + 2); + Context::accumulate(out1, k2, in + 1 * VECTOR_LENGTH + 2); + Context::accumulate(out2, k2, in + 2 * VECTOR_LENGTH + 2); + Context::accumulate(out3, k2, in + 3 * VECTOR_LENGTH + 2); + Context::accumulate(out0, k3, in + 0 * VECTOR_LENGTH + 3); + Context::accumulate(out1, k3, in + 1 * VECTOR_LENGTH + 3); + Context::accumulate(out2, k3, in + 2 * VECTOR_LENGTH + 3); + Context::accumulate(out3, k3, in + 3 * VECTOR_LENGTH + 3); + out[0] = out0; + out[1] = out1; + out[2] = out2; + out[3] = out3; + in += 4 * VECTOR_LENGTH; + out += 4; + } + lengthI %= 4 * VECTOR_LENGTH; + while (lengthI >= VECTOR_LENGTH){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate(out0, k0, in); + }else{ + out0 = Context::multiply(k0, in); + } + Context::accumulate(out0, k1, in + 1); + Context::accumulate(out0, k2, in + 2); + Context::accumulate(out0, k3, in + 3); + out[0] = out0; + in += VECTOR_LENGTH; + out += 1; + lengthI -= VECTOR_LENGTH; + } + if (lengthI){ + vtype out0; + if (addto){ + out0 = out[0]; + Context::accumulate_partial(out0, k0, in, lengthI); + }else{ + out0 = Context::multiply_partial(k0, in, lengthI); + } + Context::accumulate_partial(out0, k1, in + 1, lengthI); + Context::accumulate_partial(out0, k2, in + 2, lengthI); + Context::accumulate_partial(out0, k3, in + 3, lengthI); +// Context::store_partial((float*)out, out0, lengthI); + out[0] = out0; + } +} + + + +// Compute the Spike Kernel +// "out" is aligned to "PA_ALIGNMENT" bytes. +// lengthI >= lengthK +// "in" is valid for lengthI +// "out" is valid for (lengthI - lengthK + 1) rounded up to PA_ALIGNMENT/sizeof(float) +template +PA_FORCE_INLINE void compute_spike_kernel( + float* out, const float* in, size_t lengthI, + const float* kernel, size_t lengthK +){ +// constexpr size_t FLOAT_ALIGNMENT = PA_ALIGNMENT / sizeof(float); + using vtype = typename Context::vtype; +// constexpr size_t VECTOR_LENGTH = sizeof(vtype) / sizeof(float); + + if ((size_t)out % PA_ALIGNMENT){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "\"out\" is misaligned."); + } +// if (lengthI % FLOAT_ALIGNMENT){ +// throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "lengthI is misaligned."); +// } + if (lengthI < lengthK){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "lengthK < lengthI"); + } + + lengthI = lengthI - lengthK + 1; +// size_t lengthO = (lengthI + VECTOR_LENGTH - 1) / VECTOR_LENGTH; +// cout << "lengthI = " << lengthI << endl; +// cout << "lengthO = " << lengthO << endl; + + bool first = true; + + while (lengthK >= 4){ + vtype k0 = Context::broadcast(kernel[0]); + vtype k1 = Context::broadcast(kernel[1]); + vtype k2 = Context::broadcast(kernel[2]); + vtype k3 = Context::broadcast(kernel[3]); + if (first){ + accumulate_k4((vtype*)out, in, lengthI, k0, k1, k2, k3); + first = false; + }else{ + accumulate_k4((vtype*)out, in, lengthI, k0, k1, k2, k3); + } + in += 4; + kernel += 4; + lengthK -= 4; + } + if (lengthK == 3){ + vtype k0 = Context::broadcast(kernel[0]); + vtype k1 = Context::broadcast(kernel[1]); + vtype k2 = Context::broadcast(kernel[2]); + if (first){ + accumulate_k3((vtype*)out, in, lengthI, k0, k1, k2); + }else{ + accumulate_k3((vtype*)out, in, lengthI, k0, k1, k2); + } + return; + } + if (lengthK == 2){ + vtype k0 = Context::broadcast(kernel[0]); + vtype k1 = Context::broadcast(kernel[1]); + if (first){ + accumulate_k2((vtype*)out, in, lengthI, k0, k1); + }else{ + accumulate_k2((vtype*)out, in, lengthI, k0, k1); + } + return; + } + if (lengthK == 1){ + vtype k0 = Context::broadcast(kernel[0]); + if (first){ + accumulate_k1((vtype*)out, in, lengthI, k0); + }else{ + accumulate_k1((vtype*)out, in, lengthI, k0); + } + return; + } +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.cpp index 21ec7ab310..e5c20f945c 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.cpp @@ -1,82 +1,82 @@ -/* Waterfill Algorithm - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_Waterfill.h" -#include "Kernels_Waterfill_Session.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - - -std::vector find_objects_inplace_64x4_Default (PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x8_Default (PackedBinaryMatrix_IB& matrix, size_t min_area); - -std::vector find_objects_inplace_64x8_x64_SSE42 (PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x16_x64_AVX2 (PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x32_x64_AVX512 (PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x64_x64_AVX512 (PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x32_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x64_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area); -std::vector find_objects_inplace_64x8_arm64_NEON (PackedBinaryMatrix_IB& matrix, size_t min_area); - -std::vector find_objects_inplace(PackedBinaryMatrix_IB& matrix, size_t min_area){ -// cout << "find_objects_inplace" << endl; - - switch (matrix.type()){ - -#ifdef PA_ARCH_x86 -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return find_objects_inplace_64x64_x64_AVX512GF(matrix, min_area); - }else{ - return find_objects_inplace_64x64_x64_AVX512(matrix, min_area); - } - case BinaryMatrixType::i64x32_x64_AVX512: - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return find_objects_inplace_64x32_x64_AVX512GF(matrix, min_area); - }else{ - return find_objects_inplace_64x32_x64_AVX512(matrix, min_area); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return find_objects_inplace_64x16_x64_AVX2(matrix, min_area); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return find_objects_inplace_64x8_x64_SSE42(matrix, min_area); -#endif -#elif PA_ARCH_arm64 -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return find_objects_inplace_64x8_arm64_NEON(matrix, min_area); -#endif -#endif - - case BinaryMatrixType::i64x8_Default: - return find_objects_inplace_64x8_Default(matrix, min_area); - case BinaryMatrixType::i64x4_Default: - return find_objects_inplace_64x4_Default(matrix, min_area); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} - - - - -} -} -} +/* Waterfill Algorithm + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_Waterfill.h" +#include "Kernels_Waterfill_Session.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + + +std::vector find_objects_inplace_64x4_Default (PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x8_Default (PackedBinaryMatrix_IB& matrix, size_t min_area); + +std::vector find_objects_inplace_64x8_x64_SSE42 (PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x16_x64_AVX2 (PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x32_x64_AVX512 (PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x64_x64_AVX512 (PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x32_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x64_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area); +std::vector find_objects_inplace_64x8_arm64_NEON (PackedBinaryMatrix_IB& matrix, size_t min_area); + +std::vector find_objects_inplace(PackedBinaryMatrix_IB& matrix, size_t min_area){ +// cout << "find_objects_inplace" << endl; + + switch (matrix.type()){ + +#ifdef PA_ARCH_x86 +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return find_objects_inplace_64x64_x64_AVX512GF(matrix, min_area); + }else{ + return find_objects_inplace_64x64_x64_AVX512(matrix, min_area); + } + case BinaryMatrixType::i64x32_x64_AVX512: + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return find_objects_inplace_64x32_x64_AVX512GF(matrix, min_area); + }else{ + return find_objects_inplace_64x32_x64_AVX512(matrix, min_area); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return find_objects_inplace_64x16_x64_AVX2(matrix, min_area); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return find_objects_inplace_64x8_x64_SSE42(matrix, min_area); +#endif +#elif PA_ARCH_arm64 +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return find_objects_inplace_64x8_arm64_NEON(matrix, min_area); +#endif +#endif + + case BinaryMatrixType::i64x8_Default: + return find_objects_inplace_64x8_Default(matrix, min_area); + case BinaryMatrixType::i64x4_Default: + return find_objects_inplace_64x4_Default(matrix, min_area); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.h index 7b64e264bf..2027c3fb44 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill.h @@ -1,29 +1,29 @@ -/* Waterfill Algorithm - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_H -#define PokemonAutomation_Kernels_Waterfill_H - -#include -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" -#include "Kernels_Waterfill_Types.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - - -// Find all the objects in the matrix. This will destroy "matrix". -std::vector find_objects_inplace(PackedBinaryMatrix_IB& matrix, size_t min_area); - - - - -} -} -} -#endif +/* Waterfill Algorithm + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_H +#define PokemonAutomation_Kernels_Waterfill_H + +#include +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" +#include "Kernels_Waterfill_Types.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + + +// Find all the objects in the matrix. This will destroy "matrix". +std::vector find_objects_inplace(PackedBinaryMatrix_IB& matrix, size_t min_area); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp index e410af2c49..0e88706fb9 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.cpp @@ -1,37 +1,37 @@ -/* Waterfill Core (AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_13_Haswell - -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x16_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::vector find_objects_inplace_64x16_x64_AVX2(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x16_x64_AVX2(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - - - - -} -} -} -#endif +/* Waterfill Core (AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_13_Haswell + +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x16_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::vector find_objects_inplace_64x16_x64_AVX2(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x16_x64_AVX2(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.h index 23d43ab97c..584e6f920f 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x16_x64_AVX2.h @@ -1,469 +1,469 @@ -/* Waterfill Core (x64 AVX2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x16_x64_AVX2_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x16_x64_AVX2_H - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX2.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -PA_FORCE_INLINE __m256i bit_reverse(__m256i x){ - __m256i r0, r1; - - x = _mm256_shuffle_epi8( - x, - _mm256_setr_epi8( - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 - ) - ); - - r0 = _mm256_srli_epi32(x, 4); - r1 = _mm256_slli_epi32(x, 4); - r0 = _mm256_and_si256(r0, _mm256_set1_epi8((uint8_t)0x0f)); - r1 = _mm256_and_si256(r1, _mm256_set1_epi8((uint8_t)0xf0)); - r1 = _mm256_or_si256(r0, r1); - - r0 = _mm256_srli_epi32(r1, 2); - r1 = _mm256_slli_epi32(r1, 2); - r0 = _mm256_and_si256(r0, _mm256_set1_epi8((uint8_t)0x33)); - r1 = _mm256_and_si256(r1, _mm256_set1_epi8((uint8_t)0xcc)); - r1 = _mm256_or_si256(r0, r1); - - r0 = _mm256_srli_epi32(r1, 1); - r1 = _mm256_slli_epi32(r1, 1); - r0 = _mm256_and_si256(r0, _mm256_set1_epi8((uint8_t)0x55)); - r1 = _mm256_and_si256(r1, _mm256_set1_epi8((uint8_t)0xaa)); - r1 = _mm256_or_si256(r0, r1); - - return r1; -} - - -struct Waterfill_64x16_x64_AVX2_ProcessedMask{ - __m256i m0, m1, m2, m3; // Copy of the masks. - __m256i b0, b1, b2, b3; // Bit-reversed copy of the masks. - __m256i t0, t1, t2, t3; // Transposed masks. - __m256i f1, f2, f3; // Forward-carry mask. - __m256i r0, r1, r2; // Reverse-carry mask. - - PA_FORCE_INLINE Waterfill_64x16_x64_AVX2_ProcessedMask( - const BinaryTile_64x16_x64_AVX2& m, - __m256i x0, __m256i x1, __m256i x2, __m256i x3 - ){ - m0 = _mm256_or_si256(x0, m.vec[0]); - m1 = _mm256_or_si256(x1, m.vec[1]); - m2 = _mm256_or_si256(x2, m.vec[2]); - m3 = _mm256_or_si256(x3, m.vec[3]); - - b0 = bit_reverse(m0); - b1 = bit_reverse(m1); - b2 = bit_reverse(m2); - b3 = bit_reverse(m3); - - t0 = m0; - t1 = m1; - t2 = m2; - t3 = m3; - transpose_i64_4x4_AVX2(t0, t1, t2, t3); - - // Forward carry - __m256i f0 = t0; - f1 = _mm256_and_si256(f0, t1); - f2 = _mm256_and_si256(f1, t2); - f3 = _mm256_and_si256(f2, t3); - transpose_i64_4x4_AVX2(f0, f1, f2, f3); - - // Reverse carry - __m256i r3 = t3; - r2 = _mm256_and_si256(r3, t2); - r1 = _mm256_and_si256(r2, t1); - r0 = _mm256_and_si256(r1, t0); - transpose_i64_4x4_AVX2(r0, r1, r2, r3); - } -}; - - - -PA_FORCE_INLINE bool keep_going( - const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, - __m256i& m0, __m256i& m1, __m256i& m2, __m256i& m3, - __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 -){ - m0 = _mm256_andnot_si256(x0, mask.m0); - m1 = _mm256_andnot_si256(x1, mask.m1); - m2 = _mm256_andnot_si256(x2, mask.m2); - m3 = _mm256_andnot_si256(x3, mask.m3); - - __m256i f0 = _mm256_permute4x64_epi64(m0, 57); - __m256i f1 = _mm256_permute4x64_epi64(m1, 57); - __m256i i0 = _mm256_permute4x64_epi64(m0, 147); - f0 = _mm256_or_si256(_mm256_blend_epi32(f0, f1, 0xc0), _mm256_blend_epi32(_mm256_setzero_si256(), i0, 0xfc)); - f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m0, 1)); - __m256i changed = _mm256_and_si256(f0, x0); - - __m256i f2 = _mm256_permute4x64_epi64(m2, 57); - __m256i i1 = _mm256_permute4x64_epi64(m1, 147); - f0 = _mm256_or_si256(_mm256_blend_epi32(f1, f2, 0xc0), _mm256_blend_epi32(i0, i1, 0xfc)); - f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m1, 1)); - f0 = _mm256_and_si256(f0, x1); - changed = _mm256_or_si256(changed, f0); - - __m256i f3 = _mm256_permute4x64_epi64(m3, 57); - __m256i i2 = _mm256_permute4x64_epi64(m2, 147); - f0 = _mm256_or_si256(_mm256_blend_epi32(f2, f3, 0xc0), _mm256_blend_epi32(i1, i2, 0xfc)); - f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m2, 1)); - f0 = _mm256_and_si256(f0, x2); - changed = _mm256_or_si256(changed, f0); - - __m256i i3 = _mm256_permute4x64_epi64(m3, 147); - f0 = _mm256_or_si256(_mm256_blend_epi32(f3, _mm256_setzero_si256(), 0xc0), _mm256_blend_epi32(i2, i3, 0xfc)); - f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m3, 1)); - f0 = _mm256_and_si256(f0, x3); - changed = _mm256_or_si256(changed, f0); - - return !_mm256_testz_si256(changed, changed); -} - - - -PA_FORCE_INLINE void expand_forward( - const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, - __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 -){ - __m256i s0 = _mm256_add_epi64(x0, mask.m0); - __m256i s1 = _mm256_add_epi64(x1, mask.m1); - __m256i s2 = _mm256_add_epi64(x2, mask.m2); - __m256i s3 = _mm256_add_epi64(x3, mask.m3); - - s0 = _mm256_andnot_si256(s0, mask.m0); - s1 = _mm256_andnot_si256(s1, mask.m1); - s2 = _mm256_andnot_si256(s2, mask.m2); - s3 = _mm256_andnot_si256(s3, mask.m3); - - x0 = _mm256_or_si256(x0, s0); - x1 = _mm256_or_si256(x1, s1); - x2 = _mm256_or_si256(x2, s2); - x3 = _mm256_or_si256(x3, s3); -} -PA_FORCE_INLINE void expand_reverse(__m256i m, __m256i b, __m256i& x){ - __m256i s = bit_reverse(_mm256_add_epi64(bit_reverse(x), b)); - s = _mm256_andnot_si256(s, m); - x = _mm256_or_si256(x, s); -} -PA_FORCE_INLINE void expand_reverse( - const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, - __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 -){ - expand_reverse(mask.m0, mask.b0, x0); - expand_reverse(mask.m1, mask.b1, x1); - expand_reverse(mask.m2, mask.b2, x2); - expand_reverse(mask.m3, mask.b3, x3); -} -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, - __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 -){ - // Carry across adjacent rows. - transpose_i64_4x4_AVX2(x0, x1, x2, x3); - x1 = _mm256_or_si256(x1, _mm256_and_si256(x0, mask.t1)); - x2 = _mm256_or_si256(x2, _mm256_and_si256(x3, mask.t2)); - x2 = _mm256_or_si256(x2, _mm256_and_si256(x1, mask.t2)); - x1 = _mm256_or_si256(x1, _mm256_and_si256(x2, mask.t1)); - x3 = _mm256_or_si256(x3, _mm256_and_si256(x2, mask.t3)); - x0 = _mm256_or_si256(x0, _mm256_and_si256(x1, mask.t0)); - transpose_i64_4x4_AVX2(x0, x1, x2, x3); - - // Carry across groups of 4 rows. - x1 = _mm256_or_si256(x1, _mm256_and_si256(_mm256_permute4x64_epi64(x0, 255), mask.f1)); - x2 = _mm256_or_si256(x2, _mm256_and_si256(_mm256_permute4x64_epi64(x3, 0), mask.r2)); - x2 = _mm256_or_si256(x2, _mm256_and_si256(_mm256_permute4x64_epi64(x1, 255), mask.f2)); - x1 = _mm256_or_si256(x1, _mm256_and_si256(_mm256_permute4x64_epi64(x2, 0), mask.r1)); - x3 = _mm256_or_si256(x3, _mm256_and_si256(_mm256_permute4x64_epi64(x2, 255), mask.f3)); - x0 = _mm256_or_si256(x0, _mm256_and_si256(_mm256_permute4x64_epi64(x1, 0), mask.r0)); -} - - - - - - - - -struct Waterfill_64x16_x64_AVX2{ - - - -static PA_FORCE_INLINE __m256i vec_or(const BinaryTile_64x16_x64_AVX2& tile){ - __m256i v0 = _mm256_or_si256(tile.vec[0], tile.vec[1]); - __m256i v1 = _mm256_or_si256(tile.vec[2], tile.vec[3]); - v0 = _mm256_or_si256(v0, v1); - return v0; -} -static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x16_x64_AVX2& tile){ - return reduce_or64_x64_AVX2(vec_or(tile)); -} - - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x16_x64_AVX2& tile){ - __m256i anything = vec_or(tile); - if (_mm256_testz_si256(anything, anything)){ - return false; - } - for (size_t c = 0; c < 16; c++){ - size_t pos; - if (trailing_zeros(pos, tile.row(c))){ - x = pos; - y = c; - return true; - } - } - return false; -} - - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const BinaryTile_64x16_x64_AVX2& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - __m256i row = _mm256_setr_epi64x(0, 1, 2, 3); - __m256i min = _mm256_set1_epi64x(15); - __m256i max = _mm256_setzero_si256(); - for (size_t c = 0; c < 4; c++){ - __m256i vec = tile.vec[c]; - __m256i mask = _mm256_cmpeq_epi64(vec, _mm256_setzero_si256()); - __m256i minr = _mm256_or_si256(row, _mm256_and_si256(mask, _mm256_set1_epi64x(15))); - __m256i maxr = _mm256_andnot_si256(mask, row); - min = _mm256_min_epi32(min, minr); - max = _mm256_max_epi32(max, maxr); - row = _mm256_add_epi64(row, _mm256_set1_epi64x(4)); - } - { - __m128i x = _mm_min_epi32( - _mm256_castsi256_si128(min), - _mm256_extracti128_si256(min, 1) - ); - x = _mm_min_epi32(x, _mm_unpackhi_epi64(x, x)); - min_y = _mm_cvtsi128_si64(x); - } - { - __m128i x = _mm_max_epi32( - _mm256_castsi256_si128(max), - _mm256_extracti128_si256(max, 1) - ); - x = _mm_max_epi32(x, _mm_unpackhi_epi64(x, x)); - max_y = _mm_cvtsi128_si64(x) + 1; - } -} - - - -// Area + Center of Gravity: -// Compute the sum of the index of each set bit. -// Returns the popcount. -static PA_FORCE_INLINE __m256i popcount_indexsum(__m256i& sum_index, __m256i x){ - // 1 -> 2 - __m256i sum_high; - __m256i pop_high = _mm256_and_si256(_mm256_srli_epi16(x, 1), _mm256_set1_epi8(0x55)); - __m256i sumxaxis = pop_high; - __m256i popcount = _mm256_add_epi8(_mm256_and_si256(x, _mm256_set1_epi8(0x55)), pop_high); - - // 2 -> 4 - sum_high = _mm256_and_si256(_mm256_srli_epi16(sumxaxis, 2), _mm256_set1_epi8(0x33)); - pop_high = _mm256_and_si256(_mm256_srli_epi16(popcount, 2), _mm256_set1_epi8(0x33)); - sumxaxis = _mm256_add_epi8(_mm256_and_si256(sumxaxis, _mm256_set1_epi8(0x33)), sum_high); - sumxaxis = _mm256_add_epi8(sumxaxis, _mm256_slli_epi16(pop_high, 1)); - popcount = _mm256_add_epi8(_mm256_and_si256(popcount, _mm256_set1_epi8(0x33)), pop_high); - - // 4 -> 8 - sum_high = _mm256_and_si256(_mm256_srli_epi16(sumxaxis, 4), _mm256_set1_epi8(0x0f)); - pop_high = _mm256_and_si256(_mm256_srli_epi16(popcount, 4), _mm256_set1_epi8(0x0f)); - sumxaxis = _mm256_add_epi8(_mm256_and_si256(sumxaxis, _mm256_set1_epi8(0x0f)), sum_high); - sumxaxis = _mm256_add_epi8(sumxaxis, _mm256_slli_epi16(pop_high, 2)); - popcount = _mm256_add_epi8(_mm256_and_si256(popcount, _mm256_set1_epi8(0x0f)), pop_high); - - // 8 -> 16 - sum_high = _mm256_srli_epi16(sumxaxis, 8); - pop_high = _mm256_srli_epi16(popcount, 8); - sumxaxis = _mm256_add_epi16(_mm256_and_si256(sumxaxis, _mm256_set1_epi16(0x00ff)), sum_high); - sumxaxis = _mm256_add_epi16(sumxaxis, _mm256_slli_epi16(pop_high, 3)); - popcount = _mm256_add_epi16(_mm256_and_si256(popcount, _mm256_set1_epi16(0x00ff)), pop_high); - - // 16 -> 32 - sum_high = _mm256_srli_epi32(sumxaxis, 16); - pop_high = _mm256_srli_epi32(popcount, 16); - sumxaxis = _mm256_add_epi32(sumxaxis, sum_high); - sumxaxis = _mm256_add_epi32(sumxaxis, _mm256_slli_epi32(pop_high, 4)); - popcount = _mm256_add_epi32(popcount, pop_high); - - // 32 -> 64 - sum_high = _mm256_srli_epi64(sumxaxis, 32); - pop_high = _mm256_srli_epi64(popcount, 32); - sumxaxis = _mm256_add_epi64(sumxaxis, sum_high); - sumxaxis = _mm256_add_epi64(sumxaxis, _mm256_slli_epi64(pop_high, 5)); - popcount = _mm256_add_epi64(popcount, pop_high); - - sum_index = _mm256_and_si256(sumxaxis, _mm256_set1_epi64x(0x000000000000ffff)); - return _mm256_and_si256(popcount, _mm256_set1_epi64x(0x000000000000ffff)); -} -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const BinaryTile_64x16_x64_AVX2& tile -){ - __m256i sum_p, sum_x, sum_y; - { - __m256i pop, sum; - pop = popcount_indexsum(sum, tile.vec[0]); - sum_p = pop; - sum_x = sum; - sum_y = _mm256_mul_epu32(pop, _mm256_setr_epi64x(0, 1, 2, 3)); - } - { - __m256i pop, sum; - pop = popcount_indexsum(sum, tile.vec[1]); - sum_p = _mm256_add_epi64(sum_p, pop); - sum_x = _mm256_add_epi64(sum_x, sum); - sum_y = _mm256_add_epi64(sum_y, _mm256_mul_epu32(pop, _mm256_setr_epi64x(4, 5, 6, 7))); - } - { - __m256i pop, sum; - pop = popcount_indexsum(sum, tile.vec[2]); - sum_p = _mm256_add_epi64(sum_p, pop); - sum_x = _mm256_add_epi64(sum_x, sum); - sum_y = _mm256_add_epi64(sum_y, _mm256_mul_epu32(pop, _mm256_setr_epi64x(8, 9, 10, 11))); - } - { - __m256i pop, sum; - pop = popcount_indexsum(sum, tile.vec[3]); - sum_p = _mm256_add_epi64(sum_p, pop); - sum_x = _mm256_add_epi64(sum_x, sum); - sum_y = _mm256_add_epi64(sum_y, _mm256_mul_epu32(pop, _mm256_setr_epi64x(12, 13, 14, 15))); - } - sum_xcoord = reduce_add64_x64_AVX2(sum_x); - sum_ycoord = reduce_add64_x64_AVX2(sum_y); - return reduce_add64_x64_AVX2(sum_p); -} - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x16_x64_AVX2& m, BinaryTile_64x16_x64_AVX2& x){ - __m256i x0 = x.vec[0]; - __m256i x1 = x.vec[1]; - __m256i x2 = x.vec[2]; - __m256i x3 = x.vec[3]; - - Waterfill_64x16_x64_AVX2_ProcessedMask mask(m, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - - __m256i m0, m1, m2, m3; - do{ - expand_vertical(mask, x0, x1, x2, x3); - expand_reverse(mask, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - }while (keep_going( - mask, - m0, m1, m2, m3, - x0, x1, x2, x3 - )); - x.vec[0] = x0; - x.vec[1] = x1; - x.vec[2] = x2; - x.vec[3] = x3; - m.vec[0] = m0; - m.vec[1] = m1; - m.vec[2] = m2; - m.vec[3] = m3; -} - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const BinaryTile_64x16_x64_AVX2& mask, - BinaryTile_64x16_x64_AVX2& tile, - const BinaryTile_64x16_x64_AVX2& border -){ - uint64_t available = mask.top() & ~tile.top(); - uint64_t new_bits = available & border.bottom(); - if (new_bits == 0){ - return false; - } - tile.top() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const BinaryTile_64x16_x64_AVX2& mask, - BinaryTile_64x16_x64_AVX2& tile, - const BinaryTile_64x16_x64_AVX2& border -){ - uint64_t available = mask.bottom() & ~tile.bottom(); - uint64_t new_bits = available & border.top(); - if (new_bits == 0){ - return false; - } - tile.bottom() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const BinaryTile_64x16_x64_AVX2& mask, - BinaryTile_64x16_x64_AVX2& tile, - const BinaryTile_64x16_x64_AVX2& border -){ - __m256i changed = _mm256_setzero_si256(); - for (size_t c = 0; c < 4; c++){ - __m256i available = _mm256_andnot_si256(tile.vec[c], mask.vec[c]); - __m256i new_bits = _mm256_and_si256(available, _mm256_srli_epi64(border.vec[c], 63)); - changed = _mm256_or_si256(changed, new_bits); - tile.vec[c] = _mm256_or_si256(tile.vec[c], new_bits); - } - return !_mm256_testz_si256(changed, changed); -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const BinaryTile_64x16_x64_AVX2& mask, - BinaryTile_64x16_x64_AVX2& tile, - const BinaryTile_64x16_x64_AVX2& border -){ - __m256i changed = _mm256_setzero_si256(); - for (size_t c = 0; c < 4; c++){ - __m256i available = _mm256_andnot_si256(tile.vec[c], mask.vec[c]); - __m256i new_bits = _mm256_and_si256(available, _mm256_slli_epi64(border.vec[c], 63)); - changed = _mm256_or_si256(changed, new_bits); - tile.vec[c] = _mm256_or_si256(tile.vec[c], new_bits); - } - return !_mm256_testz_si256(changed, changed); -} - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x16_x64_AVX2_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x16_x64_AVX2_H + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX2.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x16_x64_AVX2.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +PA_FORCE_INLINE __m256i bit_reverse(__m256i x){ + __m256i r0, r1; + + x = _mm256_shuffle_epi8( + x, + _mm256_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 + ) + ); + + r0 = _mm256_srli_epi32(x, 4); + r1 = _mm256_slli_epi32(x, 4); + r0 = _mm256_and_si256(r0, _mm256_set1_epi8((uint8_t)0x0f)); + r1 = _mm256_and_si256(r1, _mm256_set1_epi8((uint8_t)0xf0)); + r1 = _mm256_or_si256(r0, r1); + + r0 = _mm256_srli_epi32(r1, 2); + r1 = _mm256_slli_epi32(r1, 2); + r0 = _mm256_and_si256(r0, _mm256_set1_epi8((uint8_t)0x33)); + r1 = _mm256_and_si256(r1, _mm256_set1_epi8((uint8_t)0xcc)); + r1 = _mm256_or_si256(r0, r1); + + r0 = _mm256_srli_epi32(r1, 1); + r1 = _mm256_slli_epi32(r1, 1); + r0 = _mm256_and_si256(r0, _mm256_set1_epi8((uint8_t)0x55)); + r1 = _mm256_and_si256(r1, _mm256_set1_epi8((uint8_t)0xaa)); + r1 = _mm256_or_si256(r0, r1); + + return r1; +} + + +struct Waterfill_64x16_x64_AVX2_ProcessedMask{ + __m256i m0, m1, m2, m3; // Copy of the masks. + __m256i b0, b1, b2, b3; // Bit-reversed copy of the masks. + __m256i t0, t1, t2, t3; // Transposed masks. + __m256i f1, f2, f3; // Forward-carry mask. + __m256i r0, r1, r2; // Reverse-carry mask. + + PA_FORCE_INLINE Waterfill_64x16_x64_AVX2_ProcessedMask( + const BinaryTile_64x16_x64_AVX2& m, + __m256i x0, __m256i x1, __m256i x2, __m256i x3 + ){ + m0 = _mm256_or_si256(x0, m.vec[0]); + m1 = _mm256_or_si256(x1, m.vec[1]); + m2 = _mm256_or_si256(x2, m.vec[2]); + m3 = _mm256_or_si256(x3, m.vec[3]); + + b0 = bit_reverse(m0); + b1 = bit_reverse(m1); + b2 = bit_reverse(m2); + b3 = bit_reverse(m3); + + t0 = m0; + t1 = m1; + t2 = m2; + t3 = m3; + transpose_i64_4x4_AVX2(t0, t1, t2, t3); + + // Forward carry + __m256i f0 = t0; + f1 = _mm256_and_si256(f0, t1); + f2 = _mm256_and_si256(f1, t2); + f3 = _mm256_and_si256(f2, t3); + transpose_i64_4x4_AVX2(f0, f1, f2, f3); + + // Reverse carry + __m256i r3 = t3; + r2 = _mm256_and_si256(r3, t2); + r1 = _mm256_and_si256(r2, t1); + r0 = _mm256_and_si256(r1, t0); + transpose_i64_4x4_AVX2(r0, r1, r2, r3); + } +}; + + + +PA_FORCE_INLINE bool keep_going( + const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, + __m256i& m0, __m256i& m1, __m256i& m2, __m256i& m3, + __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 +){ + m0 = _mm256_andnot_si256(x0, mask.m0); + m1 = _mm256_andnot_si256(x1, mask.m1); + m2 = _mm256_andnot_si256(x2, mask.m2); + m3 = _mm256_andnot_si256(x3, mask.m3); + + __m256i f0 = _mm256_permute4x64_epi64(m0, 57); + __m256i f1 = _mm256_permute4x64_epi64(m1, 57); + __m256i i0 = _mm256_permute4x64_epi64(m0, 147); + f0 = _mm256_or_si256(_mm256_blend_epi32(f0, f1, 0xc0), _mm256_blend_epi32(_mm256_setzero_si256(), i0, 0xfc)); + f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m0, 1)); + __m256i changed = _mm256_and_si256(f0, x0); + + __m256i f2 = _mm256_permute4x64_epi64(m2, 57); + __m256i i1 = _mm256_permute4x64_epi64(m1, 147); + f0 = _mm256_or_si256(_mm256_blend_epi32(f1, f2, 0xc0), _mm256_blend_epi32(i0, i1, 0xfc)); + f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m1, 1)); + f0 = _mm256_and_si256(f0, x1); + changed = _mm256_or_si256(changed, f0); + + __m256i f3 = _mm256_permute4x64_epi64(m3, 57); + __m256i i2 = _mm256_permute4x64_epi64(m2, 147); + f0 = _mm256_or_si256(_mm256_blend_epi32(f2, f3, 0xc0), _mm256_blend_epi32(i1, i2, 0xfc)); + f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m2, 1)); + f0 = _mm256_and_si256(f0, x2); + changed = _mm256_or_si256(changed, f0); + + __m256i i3 = _mm256_permute4x64_epi64(m3, 147); + f0 = _mm256_or_si256(_mm256_blend_epi32(f3, _mm256_setzero_si256(), 0xc0), _mm256_blend_epi32(i2, i3, 0xfc)); + f0 = _mm256_or_si256(f0, _mm256_slli_epi64(m3, 1)); + f0 = _mm256_and_si256(f0, x3); + changed = _mm256_or_si256(changed, f0); + + return !_mm256_testz_si256(changed, changed); +} + + + +PA_FORCE_INLINE void expand_forward( + const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, + __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 +){ + __m256i s0 = _mm256_add_epi64(x0, mask.m0); + __m256i s1 = _mm256_add_epi64(x1, mask.m1); + __m256i s2 = _mm256_add_epi64(x2, mask.m2); + __m256i s3 = _mm256_add_epi64(x3, mask.m3); + + s0 = _mm256_andnot_si256(s0, mask.m0); + s1 = _mm256_andnot_si256(s1, mask.m1); + s2 = _mm256_andnot_si256(s2, mask.m2); + s3 = _mm256_andnot_si256(s3, mask.m3); + + x0 = _mm256_or_si256(x0, s0); + x1 = _mm256_or_si256(x1, s1); + x2 = _mm256_or_si256(x2, s2); + x3 = _mm256_or_si256(x3, s3); +} +PA_FORCE_INLINE void expand_reverse(__m256i m, __m256i b, __m256i& x){ + __m256i s = bit_reverse(_mm256_add_epi64(bit_reverse(x), b)); + s = _mm256_andnot_si256(s, m); + x = _mm256_or_si256(x, s); +} +PA_FORCE_INLINE void expand_reverse( + const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, + __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 +){ + expand_reverse(mask.m0, mask.b0, x0); + expand_reverse(mask.m1, mask.b1, x1); + expand_reverse(mask.m2, mask.b2, x2); + expand_reverse(mask.m3, mask.b3, x3); +} +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x16_x64_AVX2_ProcessedMask& mask, + __m256i& x0, __m256i& x1, __m256i& x2, __m256i& x3 +){ + // Carry across adjacent rows. + transpose_i64_4x4_AVX2(x0, x1, x2, x3); + x1 = _mm256_or_si256(x1, _mm256_and_si256(x0, mask.t1)); + x2 = _mm256_or_si256(x2, _mm256_and_si256(x3, mask.t2)); + x2 = _mm256_or_si256(x2, _mm256_and_si256(x1, mask.t2)); + x1 = _mm256_or_si256(x1, _mm256_and_si256(x2, mask.t1)); + x3 = _mm256_or_si256(x3, _mm256_and_si256(x2, mask.t3)); + x0 = _mm256_or_si256(x0, _mm256_and_si256(x1, mask.t0)); + transpose_i64_4x4_AVX2(x0, x1, x2, x3); + + // Carry across groups of 4 rows. + x1 = _mm256_or_si256(x1, _mm256_and_si256(_mm256_permute4x64_epi64(x0, 255), mask.f1)); + x2 = _mm256_or_si256(x2, _mm256_and_si256(_mm256_permute4x64_epi64(x3, 0), mask.r2)); + x2 = _mm256_or_si256(x2, _mm256_and_si256(_mm256_permute4x64_epi64(x1, 255), mask.f2)); + x1 = _mm256_or_si256(x1, _mm256_and_si256(_mm256_permute4x64_epi64(x2, 0), mask.r1)); + x3 = _mm256_or_si256(x3, _mm256_and_si256(_mm256_permute4x64_epi64(x2, 255), mask.f3)); + x0 = _mm256_or_si256(x0, _mm256_and_si256(_mm256_permute4x64_epi64(x1, 0), mask.r0)); +} + + + + + + + + +struct Waterfill_64x16_x64_AVX2{ + + + +static PA_FORCE_INLINE __m256i vec_or(const BinaryTile_64x16_x64_AVX2& tile){ + __m256i v0 = _mm256_or_si256(tile.vec[0], tile.vec[1]); + __m256i v1 = _mm256_or_si256(tile.vec[2], tile.vec[3]); + v0 = _mm256_or_si256(v0, v1); + return v0; +} +static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x16_x64_AVX2& tile){ + return reduce_or64_x64_AVX2(vec_or(tile)); +} + + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x16_x64_AVX2& tile){ + __m256i anything = vec_or(tile); + if (_mm256_testz_si256(anything, anything)){ + return false; + } + for (size_t c = 0; c < 16; c++){ + size_t pos; + if (trailing_zeros(pos, tile.row(c))){ + x = pos; + y = c; + return true; + } + } + return false; +} + + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const BinaryTile_64x16_x64_AVX2& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + __m256i row = _mm256_setr_epi64x(0, 1, 2, 3); + __m256i min = _mm256_set1_epi64x(15); + __m256i max = _mm256_setzero_si256(); + for (size_t c = 0; c < 4; c++){ + __m256i vec = tile.vec[c]; + __m256i mask = _mm256_cmpeq_epi64(vec, _mm256_setzero_si256()); + __m256i minr = _mm256_or_si256(row, _mm256_and_si256(mask, _mm256_set1_epi64x(15))); + __m256i maxr = _mm256_andnot_si256(mask, row); + min = _mm256_min_epi32(min, minr); + max = _mm256_max_epi32(max, maxr); + row = _mm256_add_epi64(row, _mm256_set1_epi64x(4)); + } + { + __m128i x = _mm_min_epi32( + _mm256_castsi256_si128(min), + _mm256_extracti128_si256(min, 1) + ); + x = _mm_min_epi32(x, _mm_unpackhi_epi64(x, x)); + min_y = _mm_cvtsi128_si64(x); + } + { + __m128i x = _mm_max_epi32( + _mm256_castsi256_si128(max), + _mm256_extracti128_si256(max, 1) + ); + x = _mm_max_epi32(x, _mm_unpackhi_epi64(x, x)); + max_y = _mm_cvtsi128_si64(x) + 1; + } +} + + + +// Area + Center of Gravity: +// Compute the sum of the index of each set bit. +// Returns the popcount. +static PA_FORCE_INLINE __m256i popcount_indexsum(__m256i& sum_index, __m256i x){ + // 1 -> 2 + __m256i sum_high; + __m256i pop_high = _mm256_and_si256(_mm256_srli_epi16(x, 1), _mm256_set1_epi8(0x55)); + __m256i sumxaxis = pop_high; + __m256i popcount = _mm256_add_epi8(_mm256_and_si256(x, _mm256_set1_epi8(0x55)), pop_high); + + // 2 -> 4 + sum_high = _mm256_and_si256(_mm256_srli_epi16(sumxaxis, 2), _mm256_set1_epi8(0x33)); + pop_high = _mm256_and_si256(_mm256_srli_epi16(popcount, 2), _mm256_set1_epi8(0x33)); + sumxaxis = _mm256_add_epi8(_mm256_and_si256(sumxaxis, _mm256_set1_epi8(0x33)), sum_high); + sumxaxis = _mm256_add_epi8(sumxaxis, _mm256_slli_epi16(pop_high, 1)); + popcount = _mm256_add_epi8(_mm256_and_si256(popcount, _mm256_set1_epi8(0x33)), pop_high); + + // 4 -> 8 + sum_high = _mm256_and_si256(_mm256_srli_epi16(sumxaxis, 4), _mm256_set1_epi8(0x0f)); + pop_high = _mm256_and_si256(_mm256_srli_epi16(popcount, 4), _mm256_set1_epi8(0x0f)); + sumxaxis = _mm256_add_epi8(_mm256_and_si256(sumxaxis, _mm256_set1_epi8(0x0f)), sum_high); + sumxaxis = _mm256_add_epi8(sumxaxis, _mm256_slli_epi16(pop_high, 2)); + popcount = _mm256_add_epi8(_mm256_and_si256(popcount, _mm256_set1_epi8(0x0f)), pop_high); + + // 8 -> 16 + sum_high = _mm256_srli_epi16(sumxaxis, 8); + pop_high = _mm256_srli_epi16(popcount, 8); + sumxaxis = _mm256_add_epi16(_mm256_and_si256(sumxaxis, _mm256_set1_epi16(0x00ff)), sum_high); + sumxaxis = _mm256_add_epi16(sumxaxis, _mm256_slli_epi16(pop_high, 3)); + popcount = _mm256_add_epi16(_mm256_and_si256(popcount, _mm256_set1_epi16(0x00ff)), pop_high); + + // 16 -> 32 + sum_high = _mm256_srli_epi32(sumxaxis, 16); + pop_high = _mm256_srli_epi32(popcount, 16); + sumxaxis = _mm256_add_epi32(sumxaxis, sum_high); + sumxaxis = _mm256_add_epi32(sumxaxis, _mm256_slli_epi32(pop_high, 4)); + popcount = _mm256_add_epi32(popcount, pop_high); + + // 32 -> 64 + sum_high = _mm256_srli_epi64(sumxaxis, 32); + pop_high = _mm256_srli_epi64(popcount, 32); + sumxaxis = _mm256_add_epi64(sumxaxis, sum_high); + sumxaxis = _mm256_add_epi64(sumxaxis, _mm256_slli_epi64(pop_high, 5)); + popcount = _mm256_add_epi64(popcount, pop_high); + + sum_index = _mm256_and_si256(sumxaxis, _mm256_set1_epi64x(0x000000000000ffff)); + return _mm256_and_si256(popcount, _mm256_set1_epi64x(0x000000000000ffff)); +} +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const BinaryTile_64x16_x64_AVX2& tile +){ + __m256i sum_p, sum_x, sum_y; + { + __m256i pop, sum; + pop = popcount_indexsum(sum, tile.vec[0]); + sum_p = pop; + sum_x = sum; + sum_y = _mm256_mul_epu32(pop, _mm256_setr_epi64x(0, 1, 2, 3)); + } + { + __m256i pop, sum; + pop = popcount_indexsum(sum, tile.vec[1]); + sum_p = _mm256_add_epi64(sum_p, pop); + sum_x = _mm256_add_epi64(sum_x, sum); + sum_y = _mm256_add_epi64(sum_y, _mm256_mul_epu32(pop, _mm256_setr_epi64x(4, 5, 6, 7))); + } + { + __m256i pop, sum; + pop = popcount_indexsum(sum, tile.vec[2]); + sum_p = _mm256_add_epi64(sum_p, pop); + sum_x = _mm256_add_epi64(sum_x, sum); + sum_y = _mm256_add_epi64(sum_y, _mm256_mul_epu32(pop, _mm256_setr_epi64x(8, 9, 10, 11))); + } + { + __m256i pop, sum; + pop = popcount_indexsum(sum, tile.vec[3]); + sum_p = _mm256_add_epi64(sum_p, pop); + sum_x = _mm256_add_epi64(sum_x, sum); + sum_y = _mm256_add_epi64(sum_y, _mm256_mul_epu32(pop, _mm256_setr_epi64x(12, 13, 14, 15))); + } + sum_xcoord = reduce_add64_x64_AVX2(sum_x); + sum_ycoord = reduce_add64_x64_AVX2(sum_y); + return reduce_add64_x64_AVX2(sum_p); +} + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x16_x64_AVX2& m, BinaryTile_64x16_x64_AVX2& x){ + __m256i x0 = x.vec[0]; + __m256i x1 = x.vec[1]; + __m256i x2 = x.vec[2]; + __m256i x3 = x.vec[3]; + + Waterfill_64x16_x64_AVX2_ProcessedMask mask(m, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + + __m256i m0, m1, m2, m3; + do{ + expand_vertical(mask, x0, x1, x2, x3); + expand_reverse(mask, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + }while (keep_going( + mask, + m0, m1, m2, m3, + x0, x1, x2, x3 + )); + x.vec[0] = x0; + x.vec[1] = x1; + x.vec[2] = x2; + x.vec[3] = x3; + m.vec[0] = m0; + m.vec[1] = m1; + m.vec[2] = m2; + m.vec[3] = m3; +} + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const BinaryTile_64x16_x64_AVX2& mask, + BinaryTile_64x16_x64_AVX2& tile, + const BinaryTile_64x16_x64_AVX2& border +){ + uint64_t available = mask.top() & ~tile.top(); + uint64_t new_bits = available & border.bottom(); + if (new_bits == 0){ + return false; + } + tile.top() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const BinaryTile_64x16_x64_AVX2& mask, + BinaryTile_64x16_x64_AVX2& tile, + const BinaryTile_64x16_x64_AVX2& border +){ + uint64_t available = mask.bottom() & ~tile.bottom(); + uint64_t new_bits = available & border.top(); + if (new_bits == 0){ + return false; + } + tile.bottom() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const BinaryTile_64x16_x64_AVX2& mask, + BinaryTile_64x16_x64_AVX2& tile, + const BinaryTile_64x16_x64_AVX2& border +){ + __m256i changed = _mm256_setzero_si256(); + for (size_t c = 0; c < 4; c++){ + __m256i available = _mm256_andnot_si256(tile.vec[c], mask.vec[c]); + __m256i new_bits = _mm256_and_si256(available, _mm256_srli_epi64(border.vec[c], 63)); + changed = _mm256_or_si256(changed, new_bits); + tile.vec[c] = _mm256_or_si256(tile.vec[c], new_bits); + } + return !_mm256_testz_si256(changed, changed); +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const BinaryTile_64x16_x64_AVX2& mask, + BinaryTile_64x16_x64_AVX2& tile, + const BinaryTile_64x16_x64_AVX2& border +){ + __m256i changed = _mm256_setzero_si256(); + for (size_t c = 0; c < 4; c++){ + __m256i available = _mm256_andnot_si256(tile.vec[c], mask.vec[c]); + __m256i new_bits = _mm256_and_si256(available, _mm256_slli_epi64(border.vec[c], 63)); + changed = _mm256_or_si256(changed, new_bits); + tile.vec[c] = _mm256_or_si256(tile.vec[c], new_bits); + } + return !_mm256_testz_si256(changed, changed); +} + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp index 5ba7a2cf06..6ddcd1489c 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.cpp @@ -1,38 +1,38 @@ -/* Waterfill Core (x64 AVX512-GF) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_19_IceLake - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::vector find_objects_inplace_64x32_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x32_x64_AVX512GF(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512-GF) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_19_IceLake + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::vector find_objects_inplace_64x32_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x32_x64_AVX512GF(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h index 846aa9d54a..c0ba71ace2 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h @@ -1,283 +1,283 @@ -/* Waterfill Core (x64 AVX512-GF) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512GF_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512GF_H - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -struct Waterfill_64x32_x64_AVX512GF_ProcessedMask{ - __m512i m0, m1, m2, m3; // Copy of the masks. - __m512i b0, b1, b2, b3; // Bit-reversed copy of the masks. - __m512i f0, f1, f2, f3; // Forward transposed. - __m512i r0, r1, r2, r3; // Reverse transposed. - - PA_FORCE_INLINE Waterfill_64x32_x64_AVX512GF_ProcessedMask( - const BinaryTile_64x32_x64_AVX512& m, - __m512i x0, __m512i x1, __m512i x2, __m512i x3 - ){ - m0 = _mm512_or_si512(x0, m.vec[0]); - m1 = _mm512_or_si512(x1, m.vec[1]); - m2 = _mm512_or_si512(x2, m.vec[2]); - m3 = _mm512_or_si512(x3, m.vec[3]); - - b0 = Intrinsics_x64_AVX512GF::bit_reverse(m0); - b1 = Intrinsics_x64_AVX512GF::bit_reverse(m1); - b2 = Intrinsics_x64_AVX512GF::bit_reverse(m2); - b3 = Intrinsics_x64_AVX512GF::bit_reverse(m3); - - f0 = m0; - f1 = m1; - f2 = m2; - f3 = m3; - Intrinsics_x64_AVX512GF::transpose_1x64x32(f0, f1, f2, f3); - r0 = Intrinsics_x64_AVX512GF::bit_reverse(f0); - r1 = Intrinsics_x64_AVX512GF::bit_reverse(f1); - r2 = Intrinsics_x64_AVX512GF::bit_reverse(f2); - r3 = Intrinsics_x64_AVX512GF::bit_reverse(f3); - } -}; - - - -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x32_x64_AVX512GF_ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - Intrinsics_x64_AVX512GF::transpose_1x64x32(x0, x1, x2, x3); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.f0), mask.f0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.f1), mask.f1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.f2), mask.f2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.f3), mask.f3, 0b11110010); - x0 = Intrinsics_x64_AVX512GF::bit_reverse(x0); - x1 = Intrinsics_x64_AVX512GF::bit_reverse(x1); - x2 = Intrinsics_x64_AVX512GF::bit_reverse(x2); - x3 = Intrinsics_x64_AVX512GF::bit_reverse(x3); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.r0), mask.r0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.r1), mask.r1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.r2), mask.r2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.r3), mask.r3, 0b11110010); - Intrinsics_x64_AVX512GF::transpose_1x64x32_bitreverse_in(x0, x1, x2, x3); -} - - - - - - - -struct Waterfill_64x32_x64_AVX512GF{ - - - -static PA_FORCE_INLINE __m512i vec_or(const BinaryTile_64x32_x64_AVX512& tile){ - __m512i v0 = _mm512_or_si512(tile.vec[0], tile.vec[1]); - __m512i v1 = _mm512_or_si512(tile.vec[2], tile.vec[3]); - v0 = _mm512_or_si512(v0, v1); - return v0; -} -static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x32_x64_AVX512& tile){ - return _mm512_reduce_or_epi64(vec_or(tile)); -} - - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x32_x64_AVX512& tile){ - __m512i anything = vec_or(tile); - if (!_mm512_test_epi64_mask(anything, anything)){ - return false; - } - __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 4; c++){ - __m512i vec = tile.vec[c]; - __mmask8 mask = _mm512_test_epi64_mask(vec, vec); - if (mask){ - vec = _mm512_maskz_compress_epi64(mask, vec); - row = _mm512_maskz_compress_epi64(mask, row); - uint64_t word = _mm_cvtsi128_si64(_mm512_castsi512_si128(vec)); - y = _mm_cvtsi128_si64(_mm512_castsi512_si128(row)); - trailing_zeros(x, word); - return true; - } - row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); - } - return false; -} - - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const BinaryTile_64x32_x64_AVX512& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - __m512i min = _mm512_set1_epi64(-1); - __m512i max = _mm512_setzero_si512(); - for (size_t c = 0; c < 4; c++){ - __m512i vec = tile.vec[c]; - __mmask8 mask = _mm512_cmpneq_epu64_mask(vec, _mm512_setzero_si512()); - min = _mm512_mask_min_epu64(min, mask, min, row); - max = _mm512_mask_max_epu64(max, mask, max, row); - row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); - } - min_y = _mm512_reduce_min_epu64(min); - max_y = _mm512_reduce_max_epu64(max) + 1; -} - - - -// Area + Center of Gravity: -// Compute the sum of the index of each set bit. -// Returns the popcount. -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const BinaryTile_64x32_x64_AVX512& tile -){ - __m512i sum_p, sum_x, sum_y; - __m512i offsets = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - { - __m512i pop, sum; - pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[0]); - sum_p = pop; - sum_x = sum; - sum_y = _mm512_mul_epu32(pop, offsets); - } - for (size_t c = 1; c < 4; c++){ - __m512i pop, sum; - pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[c]); - sum_p = _mm512_add_epi64(sum_p, pop); - sum_x = _mm512_add_epi64(sum_x, sum); - offsets = _mm512_add_epi64(offsets, _mm512_set1_epi64(8)); - sum_y = _mm512_add_epi64(sum_y, _mm512_mul_epu32(pop, offsets)); - } - sum_xcoord = _mm512_reduce_add_epi64(sum_x); - sum_ycoord = _mm512_reduce_add_epi64(sum_y); - return _mm512_reduce_add_epi64(sum_p); -} - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". -PA_FORCE_INLINE static void waterfill_expand(BinaryTile_64x32_x64_AVX512& m, BinaryTile_64x32_x64_AVX512& x){ - __m512i x0 = x.vec[0]; - __m512i x1 = x.vec[1]; - __m512i x2 = x.vec[2]; - __m512i x3 = x.vec[3]; - - Waterfill_64x32_x64_AVX512GF_ProcessedMask mask(m, x0, x1, x2, x3); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); - - __m512i m0, m1, m2, m3; - do{ - expand_vertical(mask, x0, x1, x2, x3); - Intrinsics_x64_AVX512GF::expand_reverse(mask, x0, x1, x2, x3); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); - }while (Intrinsics_x64_AVX512::keep_going( - mask, - m0, m1, m2, m3, - x0, x1, x2, x3 - )); - x.vec[0] = x0; - x.vec[1] = x1; - x.vec[2] = x2; - x.vec[3] = x3; - m.vec[0] = m0; - m.vec[1] = m1; - m.vec[2] = m2; - m.vec[3] = m3; -} - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - uint64_t available = mask.top() & ~tile.top(); - uint64_t new_bits = available & border.bottom(); - if (new_bits == 0){ - return false; - } - tile.top() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - uint64_t available = mask.bottom() & ~tile.bottom(); - uint64_t new_bits = available & border.top(); - if (new_bits == 0){ - return false; - } - tile.bottom() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - __m512i changed = _mm512_setzero_si512(); - for (size_t c = 0; c < 4; c++){ - __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); - __m512i new_bits = _mm512_and_si512(available, _mm512_srli_epi64(border.vec[c], 63)); - changed = _mm512_or_si512(changed, new_bits); - tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); - } - return _mm512_test_epi64_mask(changed, changed); -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - __m512i changed = _mm512_setzero_si512(); - for (size_t c = 0; c < 4; c++){ - __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); - __m512i new_bits = _mm512_and_si512(available, _mm512_slli_epi64(border.vec[c], 63)); - changed = _mm512_or_si512(changed, new_bits); - tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); - } - return _mm512_test_epi64_mask(changed, changed); -} - - - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512-GF) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512GF_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512GF_H + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +struct Waterfill_64x32_x64_AVX512GF_ProcessedMask{ + __m512i m0, m1, m2, m3; // Copy of the masks. + __m512i b0, b1, b2, b3; // Bit-reversed copy of the masks. + __m512i f0, f1, f2, f3; // Forward transposed. + __m512i r0, r1, r2, r3; // Reverse transposed. + + PA_FORCE_INLINE Waterfill_64x32_x64_AVX512GF_ProcessedMask( + const BinaryTile_64x32_x64_AVX512& m, + __m512i x0, __m512i x1, __m512i x2, __m512i x3 + ){ + m0 = _mm512_or_si512(x0, m.vec[0]); + m1 = _mm512_or_si512(x1, m.vec[1]); + m2 = _mm512_or_si512(x2, m.vec[2]); + m3 = _mm512_or_si512(x3, m.vec[3]); + + b0 = Intrinsics_x64_AVX512GF::bit_reverse(m0); + b1 = Intrinsics_x64_AVX512GF::bit_reverse(m1); + b2 = Intrinsics_x64_AVX512GF::bit_reverse(m2); + b3 = Intrinsics_x64_AVX512GF::bit_reverse(m3); + + f0 = m0; + f1 = m1; + f2 = m2; + f3 = m3; + Intrinsics_x64_AVX512GF::transpose_1x64x32(f0, f1, f2, f3); + r0 = Intrinsics_x64_AVX512GF::bit_reverse(f0); + r1 = Intrinsics_x64_AVX512GF::bit_reverse(f1); + r2 = Intrinsics_x64_AVX512GF::bit_reverse(f2); + r3 = Intrinsics_x64_AVX512GF::bit_reverse(f3); + } +}; + + + +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x32_x64_AVX512GF_ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + Intrinsics_x64_AVX512GF::transpose_1x64x32(x0, x1, x2, x3); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.f0), mask.f0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.f1), mask.f1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.f2), mask.f2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.f3), mask.f3, 0b11110010); + x0 = Intrinsics_x64_AVX512GF::bit_reverse(x0); + x1 = Intrinsics_x64_AVX512GF::bit_reverse(x1); + x2 = Intrinsics_x64_AVX512GF::bit_reverse(x2); + x3 = Intrinsics_x64_AVX512GF::bit_reverse(x3); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.r0), mask.r0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.r1), mask.r1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.r2), mask.r2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.r3), mask.r3, 0b11110010); + Intrinsics_x64_AVX512GF::transpose_1x64x32_bitreverse_in(x0, x1, x2, x3); +} + + + + + + + +struct Waterfill_64x32_x64_AVX512GF{ + + + +static PA_FORCE_INLINE __m512i vec_or(const BinaryTile_64x32_x64_AVX512& tile){ + __m512i v0 = _mm512_or_si512(tile.vec[0], tile.vec[1]); + __m512i v1 = _mm512_or_si512(tile.vec[2], tile.vec[3]); + v0 = _mm512_or_si512(v0, v1); + return v0; +} +static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x32_x64_AVX512& tile){ + return _mm512_reduce_or_epi64(vec_or(tile)); +} + + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x32_x64_AVX512& tile){ + __m512i anything = vec_or(tile); + if (!_mm512_test_epi64_mask(anything, anything)){ + return false; + } + __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 4; c++){ + __m512i vec = tile.vec[c]; + __mmask8 mask = _mm512_test_epi64_mask(vec, vec); + if (mask){ + vec = _mm512_maskz_compress_epi64(mask, vec); + row = _mm512_maskz_compress_epi64(mask, row); + uint64_t word = _mm_cvtsi128_si64(_mm512_castsi512_si128(vec)); + y = _mm_cvtsi128_si64(_mm512_castsi512_si128(row)); + trailing_zeros(x, word); + return true; + } + row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); + } + return false; +} + + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const BinaryTile_64x32_x64_AVX512& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + __m512i min = _mm512_set1_epi64(-1); + __m512i max = _mm512_setzero_si512(); + for (size_t c = 0; c < 4; c++){ + __m512i vec = tile.vec[c]; + __mmask8 mask = _mm512_cmpneq_epu64_mask(vec, _mm512_setzero_si512()); + min = _mm512_mask_min_epu64(min, mask, min, row); + max = _mm512_mask_max_epu64(max, mask, max, row); + row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); + } + min_y = _mm512_reduce_min_epu64(min); + max_y = _mm512_reduce_max_epu64(max) + 1; +} + + + +// Area + Center of Gravity: +// Compute the sum of the index of each set bit. +// Returns the popcount. +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const BinaryTile_64x32_x64_AVX512& tile +){ + __m512i sum_p, sum_x, sum_y; + __m512i offsets = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + { + __m512i pop, sum; + pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[0]); + sum_p = pop; + sum_x = sum; + sum_y = _mm512_mul_epu32(pop, offsets); + } + for (size_t c = 1; c < 4; c++){ + __m512i pop, sum; + pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[c]); + sum_p = _mm512_add_epi64(sum_p, pop); + sum_x = _mm512_add_epi64(sum_x, sum); + offsets = _mm512_add_epi64(offsets, _mm512_set1_epi64(8)); + sum_y = _mm512_add_epi64(sum_y, _mm512_mul_epu32(pop, offsets)); + } + sum_xcoord = _mm512_reduce_add_epi64(sum_x); + sum_ycoord = _mm512_reduce_add_epi64(sum_y); + return _mm512_reduce_add_epi64(sum_p); +} + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". +PA_FORCE_INLINE static void waterfill_expand(BinaryTile_64x32_x64_AVX512& m, BinaryTile_64x32_x64_AVX512& x){ + __m512i x0 = x.vec[0]; + __m512i x1 = x.vec[1]; + __m512i x2 = x.vec[2]; + __m512i x3 = x.vec[3]; + + Waterfill_64x32_x64_AVX512GF_ProcessedMask mask(m, x0, x1, x2, x3); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); + + __m512i m0, m1, m2, m3; + do{ + expand_vertical(mask, x0, x1, x2, x3); + Intrinsics_x64_AVX512GF::expand_reverse(mask, x0, x1, x2, x3); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); + }while (Intrinsics_x64_AVX512::keep_going( + mask, + m0, m1, m2, m3, + x0, x1, x2, x3 + )); + x.vec[0] = x0; + x.vec[1] = x1; + x.vec[2] = x2; + x.vec[3] = x3; + m.vec[0] = m0; + m.vec[1] = m1; + m.vec[2] = m2; + m.vec[3] = m3; +} + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + uint64_t available = mask.top() & ~tile.top(); + uint64_t new_bits = available & border.bottom(); + if (new_bits == 0){ + return false; + } + tile.top() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + uint64_t available = mask.bottom() & ~tile.bottom(); + uint64_t new_bits = available & border.top(); + if (new_bits == 0){ + return false; + } + tile.bottom() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + __m512i changed = _mm512_setzero_si512(); + for (size_t c = 0; c < 4; c++){ + __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); + __m512i new_bits = _mm512_and_si512(available, _mm512_srli_epi64(border.vec[c], 63)); + changed = _mm512_or_si512(changed, new_bits); + tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); + } + return _mm512_test_epi64_mask(changed, changed); +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + __m512i changed = _mm512_setzero_si512(); + for (size_t c = 0; c < 4; c++){ + __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); + __m512i new_bits = _mm512_and_si512(available, _mm512_slli_epi64(border.vec[c], 63)); + changed = _mm512_or_si512(changed, new_bits); + tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); + } + return _mm512_test_epi64_mask(changed, changed); +} + + + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp index b6e1bf6d32..64dea5ee8c 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.cpp @@ -1,38 +1,38 @@ -/* Waterfill Core (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x32_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::vector find_objects_inplace_64x32_x64_AVX512(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x32_x64_AVX512(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x32_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::vector find_objects_inplace_64x32_x64_AVX512(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x32_x64_AVX512(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.h index d09ded8a70..d0bee50262 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512.h @@ -1,372 +1,372 @@ -/* Waterfill Core (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512_H - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -#if 0 -struct Waterfill_64x32_x64_AVX512_ProcessedMask{ - __m512i m0, m1, m2, m3; // Copy of the masks. - __m512i b0, b1, b2, b3; // Bit-reversed copy of the masks. - __m512i f0, f1, f2, f3; // Forward transposed. - __m512i r0, r1, r2, r3; // Reverse transposed. - - PA_FORCE_INLINE Waterfill_64x32_x64_AVX512_ProcessedMask( - const BinaryTile_64x32_x64_AVX512& m, - __m512i x0, __m512i x1, __m512i x2, __m512i x3 - ){ - m0 = _mm512_or_si512(x0, m.vec[0]); - m1 = _mm512_or_si512(x1, m.vec[1]); - m2 = _mm512_or_si512(x2, m.vec[2]); - m3 = _mm512_or_si512(x3, m.vec[3]); - - b0 = Intrinsics_x64_AVX512::bit_reverse(m0); - b1 = Intrinsics_x64_AVX512::bit_reverse(m1); - b2 = Intrinsics_x64_AVX512::bit_reverse(m2); - b3 = Intrinsics_x64_AVX512::bit_reverse(m3); - - f0 = m0; - f1 = m1; - f2 = m2; - f3 = m3; - Intrinsics_x64_AVX512::transpose_1x64x32(f0, f1, f2, f3); - r0 = Intrinsics_x64_AVX512::bit_reverse(f0); - r1 = Intrinsics_x64_AVX512::bit_reverse(f1); - r2 = Intrinsics_x64_AVX512::bit_reverse(f2); - r3 = Intrinsics_x64_AVX512::bit_reverse(f3); - } -}; - - - -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x32_x64_AVX512_ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - Intrinsics_x64_AVX512::transpose_1x64x32(x0, x1, x2, x3); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.f0), mask.f0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.f1), mask.f1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.f2), mask.f2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.f3), mask.f3, 0b11110010); - x0 = Intrinsics_x64_AVX512::bit_reverse(x0); - x1 = Intrinsics_x64_AVX512::bit_reverse(x1); - x2 = Intrinsics_x64_AVX512::bit_reverse(x2); - x3 = Intrinsics_x64_AVX512::bit_reverse(x3); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.r0), mask.r0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.r1), mask.r1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.r2), mask.r2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.r3), mask.r3, 0b11110010); - Intrinsics_x64_AVX512::transpose_1x64x32_bitreverse_in(x0, x1, x2, x3); -} -#else -struct Waterfill_64x32_x64_AVX512_ProcessedMask{ - __m512i m0, m1, m2, m3; // Copy of the masks. - __m512i b0, b1, b2, b3; // Bit-reversed copy of the masks. - __m256i t0, t1, t2, t3, t4, t5, t6, t7; // Transposed masks. - __m512i f1, f2, f3; // Forward-carry mask. - __m512i r0, r1, r2; // Reverse-carry mask. - - PA_FORCE_INLINE Waterfill_64x32_x64_AVX512_ProcessedMask( - const BinaryTile_64x32_x64_AVX512& m, - __m512i x0, __m512i x1, __m512i x2, __m512i x3 - ){ - m0 = _mm512_or_si512(x0, m.vec[0]); - m1 = _mm512_or_si512(x1, m.vec[1]); - m2 = _mm512_or_si512(x2, m.vec[2]); - m3 = _mm512_or_si512(x3, m.vec[3]); - - b0 = Intrinsics_x64_AVX512::bit_reverse(m0); - b1 = Intrinsics_x64_AVX512::bit_reverse(m1); - b2 = Intrinsics_x64_AVX512::bit_reverse(m2); - b3 = Intrinsics_x64_AVX512::bit_reverse(m3); - - Intrinsics_x64_AVX512::transpose_64x8x4_forward( - m0, m1, m2, m3, - t0, t1, t2, t3, t4, t5, t6, t7 - ); - - __m256i q0, q1, q2, q3, q4, q5, q6, q7; - __m512i qx; - - // Forward carry - q0 = t0; - q1 = _mm256_and_si256(q0, t1); - q2 = _mm256_and_si256(q1, t2); - q3 = _mm256_and_si256(q2, t3); - q4 = _mm256_and_si256(q3, t4); - q5 = _mm256_and_si256(q4, t5); - q6 = _mm256_and_si256(q5, t6); - q7 = _mm256_and_si256(q6, t7); - Intrinsics_x64_AVX512::transpose_64x8x4_inverse(qx, f1, f2, f3, q0, q1, q2, q3, q4, q5, q6, q7); - - // Reverse carry - q7 = t7; - q6 = _mm256_and_si256(q7, t6); - q5 = _mm256_and_si256(q6, t5); - q4 = _mm256_and_si256(q5, t4); - q3 = _mm256_and_si256(q4, t3); - q2 = _mm256_and_si256(q3, t2); - q1 = _mm256_and_si256(q2, t1); - q0 = _mm256_and_si256(q1, t0); - Intrinsics_x64_AVX512::transpose_64x8x4_inverse(r0, r1, r2, qx, q0, q1, q2, q3, q4, q5, q6, q7); - } -}; - - - -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x32_x64_AVX512_ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - // Carry across adjacent rows. - __m256i y0, y1, y2, y3, y4, y5, y6, y7; - Intrinsics_x64_AVX512::transpose_64x8x4_forward(x0, x1, x2, x3, y0, y1, y2, y3, y4, y5, y6, y7); - y1 = _mm256_ternarylogic_epi64(y1, y0, mask.t1, 0b11111000); - y6 = _mm256_ternarylogic_epi64(y6, y7, mask.t6, 0b11111000); - y2 = _mm256_ternarylogic_epi64(y2, y1, mask.t2, 0b11111000); - y5 = _mm256_ternarylogic_epi64(y5, y6, mask.t5, 0b11111000); - y3 = _mm256_ternarylogic_epi64(y3, y2, mask.t3, 0b11111000); - y4 = _mm256_ternarylogic_epi64(y4, y5, mask.t4, 0b11111000); - y4 = _mm256_ternarylogic_epi64(y4, y3, mask.t4, 0b11111000); - y3 = _mm256_ternarylogic_epi64(y3, y4, mask.t3, 0b11111000); - y5 = _mm256_ternarylogic_epi64(y5, y4, mask.t5, 0b11111000); - y2 = _mm256_ternarylogic_epi64(y2, y3, mask.t2, 0b11111000); - y6 = _mm256_ternarylogic_epi64(y6, y5, mask.t6, 0b11111000); - y1 = _mm256_ternarylogic_epi64(y1, y2, mask.t1, 0b11111000); - y7 = _mm256_ternarylogic_epi64(y7, y6, mask.t7, 0b11111000); - y0 = _mm256_ternarylogic_epi64(y0, y1, mask.t0, 0b11111000); - Intrinsics_x64_AVX512::transpose_64x8x4_inverse(x0, x1, x2, x3, y0, y1, y2, y3, y4, y5, y6, y7); - - // Carry across groups of 4 rows. - x1 = _mm512_ternarylogic_epi64(x1, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x0), mask.f1, 0b11111000); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x3)), mask.r2, 0b11111000); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x1), mask.f2, 0b11111000); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x2)), mask.r1, 0b11111000); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x2), mask.f3, 0b11111000); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x1)), mask.r0, 0b11111000); -} -#endif - - - - - - - -struct Waterfill_64x32_x64_AVX512{ - - - -static PA_FORCE_INLINE __m512i vec_or(const BinaryTile_64x32_x64_AVX512& tile){ - __m512i v0 = _mm512_or_si512(tile.vec[0], tile.vec[1]); - __m512i v1 = _mm512_or_si512(tile.vec[2], tile.vec[3]); - v0 = _mm512_or_si512(v0, v1); - return v0; -} -static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x32_x64_AVX512& tile){ - return _mm512_reduce_or_epi64(vec_or(tile)); -} - - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x32_x64_AVX512& tile){ - __m512i anything = vec_or(tile); - if (!_mm512_test_epi64_mask(anything, anything)){ - return false; - } - __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 4; c++){ - __m512i vec = tile.vec[c]; - __mmask8 mask = _mm512_test_epi64_mask(vec, vec); - if (mask){ - vec = _mm512_maskz_compress_epi64(mask, vec); - row = _mm512_maskz_compress_epi64(mask, row); - uint64_t word = _mm_cvtsi128_si64(_mm512_castsi512_si128(vec)); - y = _mm_cvtsi128_si64(_mm512_castsi512_si128(row)); - trailing_zeros(x, word); - return true; - } - row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); - } - return false; -} - - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const BinaryTile_64x32_x64_AVX512& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - __m512i min = _mm512_set1_epi64(-1); - __m512i max = _mm512_setzero_si512(); - for (size_t c = 0; c < 4; c++){ - __m512i vec = tile.vec[c]; - __mmask8 mask = _mm512_cmpneq_epu64_mask(vec, _mm512_setzero_si512()); - min = _mm512_mask_min_epu64(min, mask, min, row); - max = _mm512_mask_max_epu64(max, mask, max, row); - row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); - } - min_y = _mm512_reduce_min_epu64(min); - max_y = _mm512_reduce_max_epu64(max) + 1; -} - - - -// Area + Center of Gravity: -// Compute the sum of the index of each set bit. -// Returns the popcount. -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const BinaryTile_64x32_x64_AVX512& tile -){ - __m512i sum_p, sum_x, sum_y; - __m512i offsets = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - { - __m512i pop, sum; - pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[0]); - sum_p = pop; - sum_x = sum; - sum_y = _mm512_mul_epu32(pop, offsets); - } - for (size_t c = 1; c < 4; c++){ - __m512i pop, sum; - pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[c]); - sum_p = _mm512_add_epi64(sum_p, pop); - sum_x = _mm512_add_epi64(sum_x, sum); - offsets = _mm512_add_epi64(offsets, _mm512_set1_epi64(8)); - sum_y = _mm512_add_epi64(sum_y, _mm512_mul_epu32(pop, offsets)); - } - sum_xcoord = _mm512_reduce_add_epi64(sum_x); - sum_ycoord = _mm512_reduce_add_epi64(sum_y); - return _mm512_reduce_add_epi64(sum_p); -} - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -PA_FORCE_INLINE static void waterfill_expand(BinaryTile_64x32_x64_AVX512& m, BinaryTile_64x32_x64_AVX512& x){ - __m512i x0 = x.vec[0]; - __m512i x1 = x.vec[1]; - __m512i x2 = x.vec[2]; - __m512i x3 = x.vec[3]; - - Waterfill_64x32_x64_AVX512_ProcessedMask mask(m, x0, x1, x2, x3); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); - - __m512i m0, m1, m2, m3; - do{ - expand_vertical(mask, x0, x1, x2, x3); - Intrinsics_x64_AVX512::expand_reverse(mask, x0, x1, x2, x3); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); - }while (Intrinsics_x64_AVX512::keep_going( - mask, - m0, m1, m2, m3, - x0, x1, x2, x3 - )); - x.vec[0] = x0; - x.vec[1] = x1; - x.vec[2] = x2; - x.vec[3] = x3; - m.vec[0] = m0; - m.vec[1] = m1; - m.vec[2] = m2; - m.vec[3] = m3; -} - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - uint64_t available = mask.top() & ~tile.top(); - uint64_t new_bits = available & border.bottom(); - if (new_bits == 0){ - return false; - } - tile.top() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - uint64_t available = mask.bottom() & ~tile.bottom(); - uint64_t new_bits = available & border.top(); - if (new_bits == 0){ - return false; - } - tile.bottom() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - __m512i changed = _mm512_setzero_si512(); - for (size_t c = 0; c < 4; c++){ - __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); - __m512i new_bits = _mm512_and_si512(available, _mm512_srli_epi64(border.vec[c], 63)); - changed = _mm512_or_si512(changed, new_bits); - tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); - } - return _mm512_test_epi64_mask(changed, changed); -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const BinaryTile_64x32_x64_AVX512& mask, - BinaryTile_64x32_x64_AVX512& tile, - const BinaryTile_64x32_x64_AVX512& border -){ - __m512i changed = _mm512_setzero_si512(); - for (size_t c = 0; c < 4; c++){ - __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); - __m512i new_bits = _mm512_and_si512(available, _mm512_slli_epi64(border.vec[c], 63)); - changed = _mm512_or_si512(changed, new_bits); - tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); - } - return _mm512_test_epi64_mask(changed, changed); -} - - - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x32_x64_AVX512_H + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x32_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +#if 0 +struct Waterfill_64x32_x64_AVX512_ProcessedMask{ + __m512i m0, m1, m2, m3; // Copy of the masks. + __m512i b0, b1, b2, b3; // Bit-reversed copy of the masks. + __m512i f0, f1, f2, f3; // Forward transposed. + __m512i r0, r1, r2, r3; // Reverse transposed. + + PA_FORCE_INLINE Waterfill_64x32_x64_AVX512_ProcessedMask( + const BinaryTile_64x32_x64_AVX512& m, + __m512i x0, __m512i x1, __m512i x2, __m512i x3 + ){ + m0 = _mm512_or_si512(x0, m.vec[0]); + m1 = _mm512_or_si512(x1, m.vec[1]); + m2 = _mm512_or_si512(x2, m.vec[2]); + m3 = _mm512_or_si512(x3, m.vec[3]); + + b0 = Intrinsics_x64_AVX512::bit_reverse(m0); + b1 = Intrinsics_x64_AVX512::bit_reverse(m1); + b2 = Intrinsics_x64_AVX512::bit_reverse(m2); + b3 = Intrinsics_x64_AVX512::bit_reverse(m3); + + f0 = m0; + f1 = m1; + f2 = m2; + f3 = m3; + Intrinsics_x64_AVX512::transpose_1x64x32(f0, f1, f2, f3); + r0 = Intrinsics_x64_AVX512::bit_reverse(f0); + r1 = Intrinsics_x64_AVX512::bit_reverse(f1); + r2 = Intrinsics_x64_AVX512::bit_reverse(f2); + r3 = Intrinsics_x64_AVX512::bit_reverse(f3); + } +}; + + + +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x32_x64_AVX512_ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + Intrinsics_x64_AVX512::transpose_1x64x32(x0, x1, x2, x3); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.f0), mask.f0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.f1), mask.f1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.f2), mask.f2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.f3), mask.f3, 0b11110010); + x0 = Intrinsics_x64_AVX512::bit_reverse(x0); + x1 = Intrinsics_x64_AVX512::bit_reverse(x1); + x2 = Intrinsics_x64_AVX512::bit_reverse(x2); + x3 = Intrinsics_x64_AVX512::bit_reverse(x3); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi32(x0, mask.r0), mask.r0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi32(x1, mask.r1), mask.r1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi32(x2, mask.r2), mask.r2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi32(x3, mask.r3), mask.r3, 0b11110010); + Intrinsics_x64_AVX512::transpose_1x64x32_bitreverse_in(x0, x1, x2, x3); +} +#else +struct Waterfill_64x32_x64_AVX512_ProcessedMask{ + __m512i m0, m1, m2, m3; // Copy of the masks. + __m512i b0, b1, b2, b3; // Bit-reversed copy of the masks. + __m256i t0, t1, t2, t3, t4, t5, t6, t7; // Transposed masks. + __m512i f1, f2, f3; // Forward-carry mask. + __m512i r0, r1, r2; // Reverse-carry mask. + + PA_FORCE_INLINE Waterfill_64x32_x64_AVX512_ProcessedMask( + const BinaryTile_64x32_x64_AVX512& m, + __m512i x0, __m512i x1, __m512i x2, __m512i x3 + ){ + m0 = _mm512_or_si512(x0, m.vec[0]); + m1 = _mm512_or_si512(x1, m.vec[1]); + m2 = _mm512_or_si512(x2, m.vec[2]); + m3 = _mm512_or_si512(x3, m.vec[3]); + + b0 = Intrinsics_x64_AVX512::bit_reverse(m0); + b1 = Intrinsics_x64_AVX512::bit_reverse(m1); + b2 = Intrinsics_x64_AVX512::bit_reverse(m2); + b3 = Intrinsics_x64_AVX512::bit_reverse(m3); + + Intrinsics_x64_AVX512::transpose_64x8x4_forward( + m0, m1, m2, m3, + t0, t1, t2, t3, t4, t5, t6, t7 + ); + + __m256i q0, q1, q2, q3, q4, q5, q6, q7; + __m512i qx; + + // Forward carry + q0 = t0; + q1 = _mm256_and_si256(q0, t1); + q2 = _mm256_and_si256(q1, t2); + q3 = _mm256_and_si256(q2, t3); + q4 = _mm256_and_si256(q3, t4); + q5 = _mm256_and_si256(q4, t5); + q6 = _mm256_and_si256(q5, t6); + q7 = _mm256_and_si256(q6, t7); + Intrinsics_x64_AVX512::transpose_64x8x4_inverse(qx, f1, f2, f3, q0, q1, q2, q3, q4, q5, q6, q7); + + // Reverse carry + q7 = t7; + q6 = _mm256_and_si256(q7, t6); + q5 = _mm256_and_si256(q6, t5); + q4 = _mm256_and_si256(q5, t4); + q3 = _mm256_and_si256(q4, t3); + q2 = _mm256_and_si256(q3, t2); + q1 = _mm256_and_si256(q2, t1); + q0 = _mm256_and_si256(q1, t0); + Intrinsics_x64_AVX512::transpose_64x8x4_inverse(r0, r1, r2, qx, q0, q1, q2, q3, q4, q5, q6, q7); + } +}; + + + +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x32_x64_AVX512_ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + // Carry across adjacent rows. + __m256i y0, y1, y2, y3, y4, y5, y6, y7; + Intrinsics_x64_AVX512::transpose_64x8x4_forward(x0, x1, x2, x3, y0, y1, y2, y3, y4, y5, y6, y7); + y1 = _mm256_ternarylogic_epi64(y1, y0, mask.t1, 0b11111000); + y6 = _mm256_ternarylogic_epi64(y6, y7, mask.t6, 0b11111000); + y2 = _mm256_ternarylogic_epi64(y2, y1, mask.t2, 0b11111000); + y5 = _mm256_ternarylogic_epi64(y5, y6, mask.t5, 0b11111000); + y3 = _mm256_ternarylogic_epi64(y3, y2, mask.t3, 0b11111000); + y4 = _mm256_ternarylogic_epi64(y4, y5, mask.t4, 0b11111000); + y4 = _mm256_ternarylogic_epi64(y4, y3, mask.t4, 0b11111000); + y3 = _mm256_ternarylogic_epi64(y3, y4, mask.t3, 0b11111000); + y5 = _mm256_ternarylogic_epi64(y5, y4, mask.t5, 0b11111000); + y2 = _mm256_ternarylogic_epi64(y2, y3, mask.t2, 0b11111000); + y6 = _mm256_ternarylogic_epi64(y6, y5, mask.t6, 0b11111000); + y1 = _mm256_ternarylogic_epi64(y1, y2, mask.t1, 0b11111000); + y7 = _mm256_ternarylogic_epi64(y7, y6, mask.t7, 0b11111000); + y0 = _mm256_ternarylogic_epi64(y0, y1, mask.t0, 0b11111000); + Intrinsics_x64_AVX512::transpose_64x8x4_inverse(x0, x1, x2, x3, y0, y1, y2, y3, y4, y5, y6, y7); + + // Carry across groups of 4 rows. + x1 = _mm512_ternarylogic_epi64(x1, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x0), mask.f1, 0b11111000); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x3)), mask.r2, 0b11111000); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x1), mask.f2, 0b11111000); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x2)), mask.r1, 0b11111000); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x2), mask.f3, 0b11111000); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x1)), mask.r0, 0b11111000); +} +#endif + + + + + + + +struct Waterfill_64x32_x64_AVX512{ + + + +static PA_FORCE_INLINE __m512i vec_or(const BinaryTile_64x32_x64_AVX512& tile){ + __m512i v0 = _mm512_or_si512(tile.vec[0], tile.vec[1]); + __m512i v1 = _mm512_or_si512(tile.vec[2], tile.vec[3]); + v0 = _mm512_or_si512(v0, v1); + return v0; +} +static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x32_x64_AVX512& tile){ + return _mm512_reduce_or_epi64(vec_or(tile)); +} + + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x32_x64_AVX512& tile){ + __m512i anything = vec_or(tile); + if (!_mm512_test_epi64_mask(anything, anything)){ + return false; + } + __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 4; c++){ + __m512i vec = tile.vec[c]; + __mmask8 mask = _mm512_test_epi64_mask(vec, vec); + if (mask){ + vec = _mm512_maskz_compress_epi64(mask, vec); + row = _mm512_maskz_compress_epi64(mask, row); + uint64_t word = _mm_cvtsi128_si64(_mm512_castsi512_si128(vec)); + y = _mm_cvtsi128_si64(_mm512_castsi512_si128(row)); + trailing_zeros(x, word); + return true; + } + row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); + } + return false; +} + + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const BinaryTile_64x32_x64_AVX512& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + __m512i min = _mm512_set1_epi64(-1); + __m512i max = _mm512_setzero_si512(); + for (size_t c = 0; c < 4; c++){ + __m512i vec = tile.vec[c]; + __mmask8 mask = _mm512_cmpneq_epu64_mask(vec, _mm512_setzero_si512()); + min = _mm512_mask_min_epu64(min, mask, min, row); + max = _mm512_mask_max_epu64(max, mask, max, row); + row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); + } + min_y = _mm512_reduce_min_epu64(min); + max_y = _mm512_reduce_max_epu64(max) + 1; +} + + + +// Area + Center of Gravity: +// Compute the sum of the index of each set bit. +// Returns the popcount. +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const BinaryTile_64x32_x64_AVX512& tile +){ + __m512i sum_p, sum_x, sum_y; + __m512i offsets = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + { + __m512i pop, sum; + pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[0]); + sum_p = pop; + sum_x = sum; + sum_y = _mm512_mul_epu32(pop, offsets); + } + for (size_t c = 1; c < 4; c++){ + __m512i pop, sum; + pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[c]); + sum_p = _mm512_add_epi64(sum_p, pop); + sum_x = _mm512_add_epi64(sum_x, sum); + offsets = _mm512_add_epi64(offsets, _mm512_set1_epi64(8)); + sum_y = _mm512_add_epi64(sum_y, _mm512_mul_epu32(pop, offsets)); + } + sum_xcoord = _mm512_reduce_add_epi64(sum_x); + sum_ycoord = _mm512_reduce_add_epi64(sum_y); + return _mm512_reduce_add_epi64(sum_p); +} + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +PA_FORCE_INLINE static void waterfill_expand(BinaryTile_64x32_x64_AVX512& m, BinaryTile_64x32_x64_AVX512& x){ + __m512i x0 = x.vec[0]; + __m512i x1 = x.vec[1]; + __m512i x2 = x.vec[2]; + __m512i x3 = x.vec[3]; + + Waterfill_64x32_x64_AVX512_ProcessedMask mask(m, x0, x1, x2, x3); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); + + __m512i m0, m1, m2, m3; + do{ + expand_vertical(mask, x0, x1, x2, x3); + Intrinsics_x64_AVX512::expand_reverse(mask, x0, x1, x2, x3); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3); + }while (Intrinsics_x64_AVX512::keep_going( + mask, + m0, m1, m2, m3, + x0, x1, x2, x3 + )); + x.vec[0] = x0; + x.vec[1] = x1; + x.vec[2] = x2; + x.vec[3] = x3; + m.vec[0] = m0; + m.vec[1] = m1; + m.vec[2] = m2; + m.vec[3] = m3; +} + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + uint64_t available = mask.top() & ~tile.top(); + uint64_t new_bits = available & border.bottom(); + if (new_bits == 0){ + return false; + } + tile.top() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + uint64_t available = mask.bottom() & ~tile.bottom(); + uint64_t new_bits = available & border.top(); + if (new_bits == 0){ + return false; + } + tile.bottom() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + __m512i changed = _mm512_setzero_si512(); + for (size_t c = 0; c < 4; c++){ + __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); + __m512i new_bits = _mm512_and_si512(available, _mm512_srli_epi64(border.vec[c], 63)); + changed = _mm512_or_si512(changed, new_bits); + tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); + } + return _mm512_test_epi64_mask(changed, changed); +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const BinaryTile_64x32_x64_AVX512& mask, + BinaryTile_64x32_x64_AVX512& tile, + const BinaryTile_64x32_x64_AVX512& border +){ + __m512i changed = _mm512_setzero_si512(); + for (size_t c = 0; c < 4; c++){ + __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); + __m512i new_bits = _mm512_and_si512(available, _mm512_slli_epi64(border.vec[c], 63)); + changed = _mm512_or_si512(changed, new_bits); + tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); + } + return _mm512_test_epi64_mask(changed, changed); +} + + + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h index 7b4eac3ed0..4fbe0636b3 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h @@ -1,171 +1,171 @@ -/* Waterfill Core (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x4_Default_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x4_Default_H - -#include "Kernels_Waterfill_Core_64xH_Default.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -template -struct Waterfill_64x4_Default_ProcessedMask{ - static_assert(Tile::WIDTH == 64); - static_assert(Tile::HEIGHT == 4); - - uint64_t m0, m1, m2, m3; // Copy of the masks. - uint64_t b0, b1, b2, b3; // Bit-reversed copy of the masks. - - PA_FORCE_INLINE Waterfill_64x4_Default_ProcessedMask( - const Tile& m, - uint64_t x0, uint64_t x1, uint64_t x2, uint64_t x3 - ){ - m0 = x0 | m.row(0); - m1 = x1 | m.row(1); - m2 = x2 | m.row(2); - m3 = x3 | m.row(3); - - b0 = bitreverse64(m0); - b1 = bitreverse64(m1); - b2 = bitreverse64(m2); - b3 = bitreverse64(m3); - } -}; - - - - -template -PA_FORCE_INLINE bool keep_going( - const Waterfill_64x4_Default_ProcessedMask& mask, - uint64_t& m0, uint64_t& m1, uint64_t& m2, uint64_t& m3, - uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 -){ - m0 = ~x0 & mask.m0; - m1 = ~x1 & mask.m1; - m2 = ~x2 & mask.m2; - m3 = ~x3 & mask.m3; - - uint64_t changed = - x0 & ((m0 << 1) | m1); - changed |= x1 & ((m1 << 1) | m0 | m2); - changed |= x2 & ((m2 << 1) | m1 | m3); - changed |= x3 & ((m3 << 1) | m2); - - return changed; -} - - - -template -PA_FORCE_INLINE void expand_forward( - const Waterfill_64x4_Default_ProcessedMask& mask, - uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 -){ - uint64_t s0 = x0 + mask.m0; - uint64_t s1 = x1 + mask.m1; - uint64_t s2 = x2 + mask.m2; - uint64_t s3 = x3 + mask.m3; - - s0 ^= mask.m0; - s1 ^= mask.m1; - s2 ^= mask.m2; - s3 ^= mask.m3; - - s0 &= mask.m0; - s1 &= mask.m1; - s2 &= mask.m2; - s3 &= mask.m3; - - x0 |= s0; - x1 |= s1; - x2 |= s2; - x3 |= s3; -} - -PA_FORCE_INLINE void expand_reverse(uint64_t m, uint64_t b, uint64_t& x){ - uint64_t s = bitreverse64(bitreverse64(x) + b); - s ^= m; - s &= m; - x |= s; -} - -template -PA_FORCE_INLINE void expand_reverse( - const Waterfill_64x4_Default_ProcessedMask& mask, - uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 -){ - expand_reverse(mask.m0, mask.b0, x0); - expand_reverse(mask.m1, mask.b1, x1); - expand_reverse(mask.m2, mask.b2, x2); - expand_reverse(mask.m3, mask.b3, x3); -} - -template -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x4_Default_ProcessedMask& mask, - uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 -){ - x1 |= x0 & mask.m1; - x2 |= x3 & mask.m2; - x2 |= x1 & mask.m2; - x1 |= x2 & mask.m1; - x3 |= x2 & mask.m3; - x0 |= x1 & mask.m0; -} - - - - - -template -struct Waterfill_64x4_Default : public Waterfill_64xH_Default{ - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -static PA_FORCE_INLINE void waterfill_expand(Tile& m, Tile& x){ - uint64_t x0 = x.row(0); - uint64_t x1 = x.row(1); - uint64_t x2 = x.row(2); - uint64_t x3 = x.row(3); - - Waterfill_64x4_Default_ProcessedMask mask(m, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - - uint64_t m0, m1, m2, m3; - do{ - expand_vertical(mask, x0, x1, x2, x3); - expand_reverse(mask, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - }while (keep_going( - mask, - m0, m1, m2, m3, - x0, x1, x2, x3 - )); - x.row(0) = x0; - x.row(1) = x1; - x.row(2) = x2; - x.row(3) = x3; - m.row(0) = m0; - m.row(1) = m1; - m.row(2) = m2; - m.row(3) = m3; -} - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x4_Default_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x4_Default_H + +#include "Kernels_Waterfill_Core_64xH_Default.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +template +struct Waterfill_64x4_Default_ProcessedMask{ + static_assert(Tile::WIDTH == 64); + static_assert(Tile::HEIGHT == 4); + + uint64_t m0, m1, m2, m3; // Copy of the masks. + uint64_t b0, b1, b2, b3; // Bit-reversed copy of the masks. + + PA_FORCE_INLINE Waterfill_64x4_Default_ProcessedMask( + const Tile& m, + uint64_t x0, uint64_t x1, uint64_t x2, uint64_t x3 + ){ + m0 = x0 | m.row(0); + m1 = x1 | m.row(1); + m2 = x2 | m.row(2); + m3 = x3 | m.row(3); + + b0 = bitreverse64(m0); + b1 = bitreverse64(m1); + b2 = bitreverse64(m2); + b3 = bitreverse64(m3); + } +}; + + + + +template +PA_FORCE_INLINE bool keep_going( + const Waterfill_64x4_Default_ProcessedMask& mask, + uint64_t& m0, uint64_t& m1, uint64_t& m2, uint64_t& m3, + uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 +){ + m0 = ~x0 & mask.m0; + m1 = ~x1 & mask.m1; + m2 = ~x2 & mask.m2; + m3 = ~x3 & mask.m3; + + uint64_t changed = + x0 & ((m0 << 1) | m1); + changed |= x1 & ((m1 << 1) | m0 | m2); + changed |= x2 & ((m2 << 1) | m1 | m3); + changed |= x3 & ((m3 << 1) | m2); + + return changed; +} + + + +template +PA_FORCE_INLINE void expand_forward( + const Waterfill_64x4_Default_ProcessedMask& mask, + uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 +){ + uint64_t s0 = x0 + mask.m0; + uint64_t s1 = x1 + mask.m1; + uint64_t s2 = x2 + mask.m2; + uint64_t s3 = x3 + mask.m3; + + s0 ^= mask.m0; + s1 ^= mask.m1; + s2 ^= mask.m2; + s3 ^= mask.m3; + + s0 &= mask.m0; + s1 &= mask.m1; + s2 &= mask.m2; + s3 &= mask.m3; + + x0 |= s0; + x1 |= s1; + x2 |= s2; + x3 |= s3; +} + +PA_FORCE_INLINE void expand_reverse(uint64_t m, uint64_t b, uint64_t& x){ + uint64_t s = bitreverse64(bitreverse64(x) + b); + s ^= m; + s &= m; + x |= s; +} + +template +PA_FORCE_INLINE void expand_reverse( + const Waterfill_64x4_Default_ProcessedMask& mask, + uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 +){ + expand_reverse(mask.m0, mask.b0, x0); + expand_reverse(mask.m1, mask.b1, x1); + expand_reverse(mask.m2, mask.b2, x2); + expand_reverse(mask.m3, mask.b3, x3); +} + +template +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x4_Default_ProcessedMask& mask, + uint64_t& x0, uint64_t& x1, uint64_t& x2, uint64_t& x3 +){ + x1 |= x0 & mask.m1; + x2 |= x3 & mask.m2; + x2 |= x1 & mask.m2; + x1 |= x2 & mask.m1; + x3 |= x2 & mask.m3; + x0 |= x1 & mask.m0; +} + + + + + +template +struct Waterfill_64x4_Default : public Waterfill_64xH_Default{ + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +static PA_FORCE_INLINE void waterfill_expand(Tile& m, Tile& x){ + uint64_t x0 = x.row(0); + uint64_t x1 = x.row(1); + uint64_t x2 = x.row(2); + uint64_t x3 = x.row(3); + + Waterfill_64x4_Default_ProcessedMask mask(m, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + + uint64_t m0, m1, m2, m3; + do{ + expand_vertical(mask, x0, x1, x2, x3); + expand_reverse(mask, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + }while (keep_going( + mask, + m0, m1, m2, m3, + x0, x1, x2, x3 + )); + x.row(0) = x0; + x.row(1) = x1; + x.row(2) = x2; + x.row(3) = x3; + m.row(0) = m0; + m.row(1) = m1; + m.row(2) = m2; + m.row(3) = m3; +} + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp index c804190361..a9fb8283bb 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.cpp @@ -1,38 +1,38 @@ -/* Waterfill Core (x64 AVX512-GF) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_19_IceLake - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::vector find_objects_inplace_64x64_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x64_x64_AVX512GF(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512-GF) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_19_IceLake + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::vector find_objects_inplace_64x64_x64_AVX512GF(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x64_x64_AVX512GF(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h index 57e7a56e89..a4181449ad 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512-GF.h @@ -1,166 +1,166 @@ -/* Waterfill Core (x64 AVX512-GF) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512GF_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512GF_H - -#include "Kernels_Waterfill_Core_64x64_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -struct Waterfill_64x64_x64_AVX512GF_ProcessedMask{ - __m512i m0, m1, m2, m3, m4, m5, m6, m7; // Copy of the masks. - __m512i b0, b1, b2, b3, b4, b5, b6, b7; // Bit-reversed copy of the masks. - __m512i f0, f1, f2, f3, f4, f5, f6, f7; // Forward transposed. - __m512i r0, r1, r2, r3, r4, r5, r6, r7; // Reverse transposed. - - PA_FORCE_INLINE Waterfill_64x64_x64_AVX512GF_ProcessedMask( - const BinaryTile_64x64_x64_AVX512& m, - __m512i x0, __m512i x1, __m512i x2, __m512i x3, - __m512i x4, __m512i x5, __m512i x6, __m512i x7 - ){ - m0 = _mm512_or_si512(x0, m.vec[0]); - m1 = _mm512_or_si512(x1, m.vec[1]); - m2 = _mm512_or_si512(x2, m.vec[2]); - m3 = _mm512_or_si512(x3, m.vec[3]); - m4 = _mm512_or_si512(x4, m.vec[4]); - m5 = _mm512_or_si512(x5, m.vec[5]); - m6 = _mm512_or_si512(x6, m.vec[6]); - m7 = _mm512_or_si512(x7, m.vec[7]); - - b0 = Intrinsics_x64_AVX512GF::bit_reverse(m0); - b1 = Intrinsics_x64_AVX512GF::bit_reverse(m1); - b2 = Intrinsics_x64_AVX512GF::bit_reverse(m2); - b3 = Intrinsics_x64_AVX512GF::bit_reverse(m3); - b4 = Intrinsics_x64_AVX512GF::bit_reverse(m4); - b5 = Intrinsics_x64_AVX512GF::bit_reverse(m5); - b6 = Intrinsics_x64_AVX512GF::bit_reverse(m6); - b7 = Intrinsics_x64_AVX512GF::bit_reverse(m7); - - f0 = m0; - f1 = m1; - f2 = m2; - f3 = m3; - f4 = m4; - f5 = m5; - f6 = m6; - f7 = m7; - Intrinsics_x64_AVX512GF::transpose_1x64x64(f0, f1, f2, f3, f4, f5, f6, f7); - r0 = Intrinsics_x64_AVX512GF::bit_reverse(f0); - r1 = Intrinsics_x64_AVX512GF::bit_reverse(f1); - r2 = Intrinsics_x64_AVX512GF::bit_reverse(f2); - r3 = Intrinsics_x64_AVX512GF::bit_reverse(f3); - r4 = Intrinsics_x64_AVX512GF::bit_reverse(f4); - r5 = Intrinsics_x64_AVX512GF::bit_reverse(f5); - r6 = Intrinsics_x64_AVX512GF::bit_reverse(f6); - r7 = Intrinsics_x64_AVX512GF::bit_reverse(f7); - } -}; - - - -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x64_x64_AVX512GF_ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, - __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 -){ - Intrinsics_x64_AVX512GF::transpose_1x64x64(x0, x1, x2, x3, x4, x5, x6, x7); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.f0), mask.f0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.f1), mask.f1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.f2), mask.f2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.f3), mask.f3, 0b11110010); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.f4), mask.f4, 0b11110010); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.f5), mask.f5, 0b11110010); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.f6), mask.f6, 0b11110010); - x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.f7), mask.f7, 0b11110010); - x0 = Intrinsics_x64_AVX512GF::bit_reverse(x0); - x1 = Intrinsics_x64_AVX512GF::bit_reverse(x1); - x2 = Intrinsics_x64_AVX512GF::bit_reverse(x2); - x3 = Intrinsics_x64_AVX512GF::bit_reverse(x3); - x4 = Intrinsics_x64_AVX512GF::bit_reverse(x4); - x5 = Intrinsics_x64_AVX512GF::bit_reverse(x5); - x6 = Intrinsics_x64_AVX512GF::bit_reverse(x6); - x7 = Intrinsics_x64_AVX512GF::bit_reverse(x7); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.r0), mask.r0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.r1), mask.r1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.r2), mask.r2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.r3), mask.r3, 0b11110010); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.r4), mask.r4, 0b11110010); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.r5), mask.r5, 0b11110010); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.r6), mask.r6, 0b11110010); - x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.r7), mask.r7, 0b11110010); - Intrinsics_x64_AVX512GF::transpose_1x64x64_bitreverse_in(x0, x1, x2, x3, x4, x5, x6, x7); -} - - - - - - - -struct Waterfill_64x64_x64_AVX512GF : public Waterfill_64x64_x64_AVX512{ - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". -PA_FORCE_INLINE static void waterfill_expand(BinaryTile_64x64_x64_AVX512& m, BinaryTile_64x64_x64_AVX512& x){ - __m512i x0 = x.vec[0]; - __m512i x1 = x.vec[1]; - __m512i x2 = x.vec[2]; - __m512i x3 = x.vec[3]; - __m512i x4 = x.vec[4]; - __m512i x5 = x.vec[5]; - __m512i x6 = x.vec[6]; - __m512i x7 = x.vec[7]; - - Waterfill_64x64_x64_AVX512GF_ProcessedMask mask(m, x0, x1, x2, x3, x4, x5, x6, x7); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); - - __m512i m0, m1, m2, m3, m4, m5, m6, m7; - do{ - expand_vertical(mask, x0, x1, x2, x3, x4, x5, x6, x7); - Intrinsics_x64_AVX512GF::expand_reverse(mask, x0, x1, x2, x3, x4, x5, x6, x7); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); - }while (Intrinsics_x64_AVX512::keep_going( - mask, - m0, m1, m2, m3, m4, m5, m6, m7, - x0, x1, x2, x3, x4, x5, x6, x7 - )); - x.vec[0] = x0; - x.vec[1] = x1; - x.vec[2] = x2; - x.vec[3] = x3; - x.vec[4] = x4; - x.vec[5] = x5; - x.vec[6] = x6; - x.vec[7] = x7; - m.vec[0] = m0; - m.vec[1] = m1; - m.vec[2] = m2; - m.vec[3] = m3; - m.vec[4] = m4; - m.vec[5] = m5; - m.vec[6] = m6; - m.vec[7] = m7; -} - - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512-GF) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512GF_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512GF_H + +#include "Kernels_Waterfill_Core_64x64_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +struct Waterfill_64x64_x64_AVX512GF_ProcessedMask{ + __m512i m0, m1, m2, m3, m4, m5, m6, m7; // Copy of the masks. + __m512i b0, b1, b2, b3, b4, b5, b6, b7; // Bit-reversed copy of the masks. + __m512i f0, f1, f2, f3, f4, f5, f6, f7; // Forward transposed. + __m512i r0, r1, r2, r3, r4, r5, r6, r7; // Reverse transposed. + + PA_FORCE_INLINE Waterfill_64x64_x64_AVX512GF_ProcessedMask( + const BinaryTile_64x64_x64_AVX512& m, + __m512i x0, __m512i x1, __m512i x2, __m512i x3, + __m512i x4, __m512i x5, __m512i x6, __m512i x7 + ){ + m0 = _mm512_or_si512(x0, m.vec[0]); + m1 = _mm512_or_si512(x1, m.vec[1]); + m2 = _mm512_or_si512(x2, m.vec[2]); + m3 = _mm512_or_si512(x3, m.vec[3]); + m4 = _mm512_or_si512(x4, m.vec[4]); + m5 = _mm512_or_si512(x5, m.vec[5]); + m6 = _mm512_or_si512(x6, m.vec[6]); + m7 = _mm512_or_si512(x7, m.vec[7]); + + b0 = Intrinsics_x64_AVX512GF::bit_reverse(m0); + b1 = Intrinsics_x64_AVX512GF::bit_reverse(m1); + b2 = Intrinsics_x64_AVX512GF::bit_reverse(m2); + b3 = Intrinsics_x64_AVX512GF::bit_reverse(m3); + b4 = Intrinsics_x64_AVX512GF::bit_reverse(m4); + b5 = Intrinsics_x64_AVX512GF::bit_reverse(m5); + b6 = Intrinsics_x64_AVX512GF::bit_reverse(m6); + b7 = Intrinsics_x64_AVX512GF::bit_reverse(m7); + + f0 = m0; + f1 = m1; + f2 = m2; + f3 = m3; + f4 = m4; + f5 = m5; + f6 = m6; + f7 = m7; + Intrinsics_x64_AVX512GF::transpose_1x64x64(f0, f1, f2, f3, f4, f5, f6, f7); + r0 = Intrinsics_x64_AVX512GF::bit_reverse(f0); + r1 = Intrinsics_x64_AVX512GF::bit_reverse(f1); + r2 = Intrinsics_x64_AVX512GF::bit_reverse(f2); + r3 = Intrinsics_x64_AVX512GF::bit_reverse(f3); + r4 = Intrinsics_x64_AVX512GF::bit_reverse(f4); + r5 = Intrinsics_x64_AVX512GF::bit_reverse(f5); + r6 = Intrinsics_x64_AVX512GF::bit_reverse(f6); + r7 = Intrinsics_x64_AVX512GF::bit_reverse(f7); + } +}; + + + +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x64_x64_AVX512GF_ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, + __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 +){ + Intrinsics_x64_AVX512GF::transpose_1x64x64(x0, x1, x2, x3, x4, x5, x6, x7); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.f0), mask.f0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.f1), mask.f1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.f2), mask.f2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.f3), mask.f3, 0b11110010); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.f4), mask.f4, 0b11110010); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.f5), mask.f5, 0b11110010); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.f6), mask.f6, 0b11110010); + x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.f7), mask.f7, 0b11110010); + x0 = Intrinsics_x64_AVX512GF::bit_reverse(x0); + x1 = Intrinsics_x64_AVX512GF::bit_reverse(x1); + x2 = Intrinsics_x64_AVX512GF::bit_reverse(x2); + x3 = Intrinsics_x64_AVX512GF::bit_reverse(x3); + x4 = Intrinsics_x64_AVX512GF::bit_reverse(x4); + x5 = Intrinsics_x64_AVX512GF::bit_reverse(x5); + x6 = Intrinsics_x64_AVX512GF::bit_reverse(x6); + x7 = Intrinsics_x64_AVX512GF::bit_reverse(x7); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.r0), mask.r0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.r1), mask.r1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.r2), mask.r2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.r3), mask.r3, 0b11110010); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.r4), mask.r4, 0b11110010); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.r5), mask.r5, 0b11110010); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.r6), mask.r6, 0b11110010); + x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.r7), mask.r7, 0b11110010); + Intrinsics_x64_AVX512GF::transpose_1x64x64_bitreverse_in(x0, x1, x2, x3, x4, x5, x6, x7); +} + + + + + + + +struct Waterfill_64x64_x64_AVX512GF : public Waterfill_64x64_x64_AVX512{ + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". +PA_FORCE_INLINE static void waterfill_expand(BinaryTile_64x64_x64_AVX512& m, BinaryTile_64x64_x64_AVX512& x){ + __m512i x0 = x.vec[0]; + __m512i x1 = x.vec[1]; + __m512i x2 = x.vec[2]; + __m512i x3 = x.vec[3]; + __m512i x4 = x.vec[4]; + __m512i x5 = x.vec[5]; + __m512i x6 = x.vec[6]; + __m512i x7 = x.vec[7]; + + Waterfill_64x64_x64_AVX512GF_ProcessedMask mask(m, x0, x1, x2, x3, x4, x5, x6, x7); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); + + __m512i m0, m1, m2, m3, m4, m5, m6, m7; + do{ + expand_vertical(mask, x0, x1, x2, x3, x4, x5, x6, x7); + Intrinsics_x64_AVX512GF::expand_reverse(mask, x0, x1, x2, x3, x4, x5, x6, x7); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); + }while (Intrinsics_x64_AVX512::keep_going( + mask, + m0, m1, m2, m3, m4, m5, m6, m7, + x0, x1, x2, x3, x4, x5, x6, x7 + )); + x.vec[0] = x0; + x.vec[1] = x1; + x.vec[2] = x2; + x.vec[3] = x3; + x.vec[4] = x4; + x.vec[5] = x5; + x.vec[6] = x6; + x.vec[7] = x7; + m.vec[0] = m0; + m.vec[1] = m1; + m.vec[2] = m2; + m.vec[3] = m3; + m.vec[4] = m4; + m.vec[5] = m5; + m.vec[6] = m6; + m.vec[7] = m7; +} + + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp index e33e82b67a..3267fb0455 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.cpp @@ -1,37 +1,37 @@ -/* Waterfill Core (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_17_Skylake - -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x64_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::vector find_objects_inplace_64x64_x64_AVX512(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x64_x64_AVX512(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_17_Skylake + +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x64_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::vector find_objects_inplace_64x64_x64_AVX512(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x64_x64_AVX512(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.h index bec944ca13..3e7594b9eb 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x64_x64_AVX512.h @@ -1,350 +1,350 @@ -/* Waterfill Core (x64 AVX512) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512_H - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - - -struct Waterfill_64x64_x64_AVX512_ProcessedMask{ - __m512i m0, m1, m2, m3, m4, m5, m6, m7; // Copy of the masks. - __m512i b0, b1, b2, b3, b4, b5, b6, b7; // Bit-reversed copy of the masks. - __m512i t0, t1, t2, t3, t4, t5, t6, t7; // Transposed masks. - __m512i f1, f2, f3, f4, f5, f6, f7; // Forward-carry mask. - __m512i r0, r1, r2, r3, r4, r5, r6; // Reverse-carry mask. - - PA_FORCE_INLINE Waterfill_64x64_x64_AVX512_ProcessedMask( - const BinaryTile_64x64_x64_AVX512& m, - __m512i x0, __m512i x1, __m512i x2, __m512i x3, - __m512i x4, __m512i x5, __m512i x6, __m512i x7 - ){ - m0 = _mm512_or_si512(x0, m.vec[0]); - m1 = _mm512_or_si512(x1, m.vec[1]); - m2 = _mm512_or_si512(x2, m.vec[2]); - m3 = _mm512_or_si512(x3, m.vec[3]); - m4 = _mm512_or_si512(x4, m.vec[4]); - m5 = _mm512_or_si512(x5, m.vec[5]); - m6 = _mm512_or_si512(x6, m.vec[6]); - m7 = _mm512_or_si512(x7, m.vec[7]); - - b0 = Intrinsics_x64_AVX512::bit_reverse(m0); - b1 = Intrinsics_x64_AVX512::bit_reverse(m1); - b2 = Intrinsics_x64_AVX512::bit_reverse(m2); - b3 = Intrinsics_x64_AVX512::bit_reverse(m3); - b4 = Intrinsics_x64_AVX512::bit_reverse(m4); - b5 = Intrinsics_x64_AVX512::bit_reverse(m5); - b6 = Intrinsics_x64_AVX512::bit_reverse(m6); - b7 = Intrinsics_x64_AVX512::bit_reverse(m7); - - t0 = m0; - t1 = m1; - t2 = m2; - t3 = m3; - t4 = m4; - t5 = m5; - t6 = m6; - t7 = m7; - transpose_i64_8x8_AVX512(t0, t1, t2, t3, t4, t5, t6, t7); - - // Forward carry - __m512i f0 = t0; - f1 = _mm512_and_si512(f0, t1); - f2 = _mm512_and_si512(f1, t2); - f3 = _mm512_and_si512(f2, t3); - f4 = _mm512_and_si512(f3, t4); - f5 = _mm512_and_si512(f4, t5); - f6 = _mm512_and_si512(f5, t6); - f7 = _mm512_and_si512(f6, t7); - transpose_i64_8x8_AVX512(f0, f1, f2, f3, f4, f5, f6, f7); - - // Reverse carry - __m512i r7 = t7; - r6 = _mm512_and_si512(r7, t6); - r5 = _mm512_and_si512(r6, t5); - r4 = _mm512_and_si512(r5, t4); - r3 = _mm512_and_si512(r4, t3); - r2 = _mm512_and_si512(r3, t2); - r1 = _mm512_and_si512(r2, t1); - r0 = _mm512_and_si512(r1, t0); - transpose_i64_8x8_AVX512(r0, r1, r2, r3, r4, r5, r6, r7); - } -}; - - - -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x64_x64_AVX512_ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, - __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 -){ - // Carry across adjacent rows. - transpose_i64_8x8_AVX512(x0, x1, x2, x3, x4, x5, x6, x7); - x1 = _mm512_ternarylogic_epi64(x1, x0, mask.t1, 0b11111000); - x6 = _mm512_ternarylogic_epi64(x6, x7, mask.t6, 0b11111000); - x2 = _mm512_ternarylogic_epi64(x2, x1, mask.t2, 0b11111000); - x5 = _mm512_ternarylogic_epi64(x5, x6, mask.t5, 0b11111000); - x3 = _mm512_ternarylogic_epi64(x3, x2, mask.t3, 0b11111000); - x4 = _mm512_ternarylogic_epi64(x4, x5, mask.t4, 0b11111000); - x4 = _mm512_ternarylogic_epi64(x4, x3, mask.t4, 0b11111000); - x3 = _mm512_ternarylogic_epi64(x3, x4, mask.t3, 0b11111000); - x5 = _mm512_ternarylogic_epi64(x5, x4, mask.t5, 0b11111000); - x2 = _mm512_ternarylogic_epi64(x2, x3, mask.t2, 0b11111000); - x6 = _mm512_ternarylogic_epi64(x6, x5, mask.t6, 0b11111000); - x1 = _mm512_ternarylogic_epi64(x1, x2, mask.t1, 0b11111000); - x7 = _mm512_ternarylogic_epi64(x7, x6, mask.t7, 0b11111000); - x0 = _mm512_ternarylogic_epi64(x0, x1, mask.t0, 0b11111000); - transpose_i64_8x8_AVX512(x0, x1, x2, x3, x4, x5, x6, x7); - - // Carry across groups of 8 rows. - x1 = _mm512_ternarylogic_epi64(x1, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x0), mask.f1, 0b11111000); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x7)), mask.r6, 0b11111000); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x1), mask.f2, 0b11111000); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x6)), mask.r5, 0b11111000); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x2), mask.f3, 0b11111000); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x5)), mask.r4, 0b11111000); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x3), mask.f4, 0b11111000); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x4)), mask.r3, 0b11111000); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x4), mask.f5, 0b11111000); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x3)), mask.r2, 0b11111000); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x5), mask.f6, 0b11111000); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x2)), mask.r1, 0b11111000); - x7 = _mm512_ternarylogic_epi64(x7, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x6), mask.f7, 0b11111000); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x1)), mask.r0, 0b11111000); -} - - - - - - -struct Waterfill_64x64_x64_AVX512{ - - - -static PA_FORCE_INLINE __m512i vec_or(const BinaryTile_64x64_x64_AVX512& tile){ - __m512i v0 = _mm512_or_si512(tile.vec[0], tile.vec[1]); - __m512i v1 = _mm512_or_si512(tile.vec[2], tile.vec[3]); - __m512i v2 = _mm512_or_si512(tile.vec[4], tile.vec[5]); - __m512i v3 = _mm512_or_si512(tile.vec[6], tile.vec[7]); - v0 = _mm512_or_si512(v0, v1); - v2 = _mm512_or_si512(v2, v3); - v0 = _mm512_or_si512(v0, v2); - return v0; -} -static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x64_x64_AVX512& tile){ - return _mm512_reduce_or_epi64(vec_or(tile)); -} - - - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x64_x64_AVX512& tile){ - __m512i anything = vec_or(tile); - if (!_mm512_test_epi64_mask(anything, anything)){ - return false; - } - __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - for (size_t c = 0; c < 8; c++){ - __m512i vec = tile.vec[c]; - __mmask8 mask = _mm512_test_epi64_mask(vec, vec); - if (mask){ - vec = _mm512_maskz_compress_epi64(mask, vec); - row = _mm512_maskz_compress_epi64(mask, row); - uint64_t word = _mm_cvtsi128_si64(_mm512_castsi512_si128(vec)); - y = _mm_cvtsi128_si64(_mm512_castsi512_si128(row)); - trailing_zeros(x, word); - return true; - } - row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); - } - return false; -} - - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const BinaryTile_64x64_x64_AVX512& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - __m512i min = _mm512_set1_epi64(-1); - __m512i max = _mm512_setzero_si512(); - for (size_t c = 0; c < 8; c++){ - __m512i vec = tile.vec[c]; - __mmask8 mask = _mm512_cmpneq_epu64_mask(vec, _mm512_setzero_si512()); - min = _mm512_mask_min_epu64(min, mask, min, row); - max = _mm512_mask_max_epu64(max, mask, max, row); - row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); - } - min_y = _mm512_reduce_min_epu64(min); - max_y = _mm512_reduce_max_epu64(max) + 1; -} - - - -// Area + Center of Gravity: -// Compute the sum of the index of each set bit. -// Returns the popcount. -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const BinaryTile_64x64_x64_AVX512& tile -){ - __m512i sum_p, sum_x, sum_y; - __m512i offsets = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); - { - __m512i pop, sum; - pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[0]); - sum_p = pop; - sum_x = sum; - sum_y = _mm512_mul_epu32(pop, offsets); - } - for (size_t c = 1; c < 8; c++){ - __m512i pop, sum; - pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[c]); - sum_p = _mm512_add_epi64(sum_p, pop); - sum_x = _mm512_add_epi64(sum_x, sum); - offsets = _mm512_add_epi64(offsets, _mm512_set1_epi64(8)); - sum_y = _mm512_add_epi64(sum_y, _mm512_mul_epu32(pop, offsets)); - } - sum_xcoord = _mm512_reduce_add_epi64(sum_x); - sum_ycoord = _mm512_reduce_add_epi64(sum_y); - return _mm512_reduce_add_epi64(sum_p); -} - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x64_x64_AVX512& m, BinaryTile_64x64_x64_AVX512& x){ - __m512i x0 = x.vec[0]; - __m512i x1 = x.vec[1]; - __m512i x2 = x.vec[2]; - __m512i x3 = x.vec[3]; - __m512i x4 = x.vec[4]; - __m512i x5 = x.vec[5]; - __m512i x6 = x.vec[6]; - __m512i x7 = x.vec[7]; - - Waterfill_64x64_x64_AVX512_ProcessedMask mask(m, x0, x1, x2, x3, x4, x5, x6, x7); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); - - __m512i m0, m1, m2, m3, m4, m5, m6, m7; - do{ - expand_vertical(mask, x0, x1, x2, x3, x4, x5, x6, x7); - Intrinsics_x64_AVX512::expand_reverse(mask, x0, x1, x2, x3, x4, x5, x6, x7); - Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); - }while (Intrinsics_x64_AVX512::keep_going( - mask, - m0, m1, m2, m3, m4, m5, m6, m7, - x0, x1, x2, x3, x4, x5, x6, x7 - )); - x.vec[0] = x0; - x.vec[1] = x1; - x.vec[2] = x2; - x.vec[3] = x3; - x.vec[4] = x4; - x.vec[5] = x5; - x.vec[6] = x6; - x.vec[7] = x7; - m.vec[0] = m0; - m.vec[1] = m1; - m.vec[2] = m2; - m.vec[3] = m3; - m.vec[4] = m4; - m.vec[5] = m5; - m.vec[6] = m6; - m.vec[7] = m7; -} - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const BinaryTile_64x64_x64_AVX512& mask, - BinaryTile_64x64_x64_AVX512& tile, - const BinaryTile_64x64_x64_AVX512& border -){ - uint64_t available = mask.top() & ~tile.top(); - uint64_t new_bits = available & border.bottom(); - if (new_bits == 0){ - return false; - } - tile.top() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const BinaryTile_64x64_x64_AVX512& mask, - BinaryTile_64x64_x64_AVX512& tile, - const BinaryTile_64x64_x64_AVX512& border -){ - uint64_t available = mask.bottom() & ~tile.bottom(); - uint64_t new_bits = available & border.top(); - if (new_bits == 0){ - return false; - } - tile.bottom() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const BinaryTile_64x64_x64_AVX512& mask, - BinaryTile_64x64_x64_AVX512& tile, - const BinaryTile_64x64_x64_AVX512& border -){ - __m512i changed = _mm512_setzero_si512(); - for (size_t c = 0; c < 8; c++){ - __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); - __m512i new_bits = _mm512_and_si512(available, _mm512_srli_epi64(border.vec[c], 63)); - changed = _mm512_or_si512(changed, new_bits); - tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); - } - return _mm512_test_epi64_mask(changed, changed); -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const BinaryTile_64x64_x64_AVX512& mask, - BinaryTile_64x64_x64_AVX512& tile, - const BinaryTile_64x64_x64_AVX512& border -){ - __m512i changed = _mm512_setzero_si512(); - for (size_t c = 0; c < 8; c++){ - __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); - __m512i new_bits = _mm512_and_si512(available, _mm512_slli_epi64(border.vec[c], 63)); - changed = _mm512_or_si512(changed, new_bits); - tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); - } - return _mm512_test_epi64_mask(changed, changed); -} - - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (x64 AVX512) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x64_x64_AVX512_H + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x64_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + + +struct Waterfill_64x64_x64_AVX512_ProcessedMask{ + __m512i m0, m1, m2, m3, m4, m5, m6, m7; // Copy of the masks. + __m512i b0, b1, b2, b3, b4, b5, b6, b7; // Bit-reversed copy of the masks. + __m512i t0, t1, t2, t3, t4, t5, t6, t7; // Transposed masks. + __m512i f1, f2, f3, f4, f5, f6, f7; // Forward-carry mask. + __m512i r0, r1, r2, r3, r4, r5, r6; // Reverse-carry mask. + + PA_FORCE_INLINE Waterfill_64x64_x64_AVX512_ProcessedMask( + const BinaryTile_64x64_x64_AVX512& m, + __m512i x0, __m512i x1, __m512i x2, __m512i x3, + __m512i x4, __m512i x5, __m512i x6, __m512i x7 + ){ + m0 = _mm512_or_si512(x0, m.vec[0]); + m1 = _mm512_or_si512(x1, m.vec[1]); + m2 = _mm512_or_si512(x2, m.vec[2]); + m3 = _mm512_or_si512(x3, m.vec[3]); + m4 = _mm512_or_si512(x4, m.vec[4]); + m5 = _mm512_or_si512(x5, m.vec[5]); + m6 = _mm512_or_si512(x6, m.vec[6]); + m7 = _mm512_or_si512(x7, m.vec[7]); + + b0 = Intrinsics_x64_AVX512::bit_reverse(m0); + b1 = Intrinsics_x64_AVX512::bit_reverse(m1); + b2 = Intrinsics_x64_AVX512::bit_reverse(m2); + b3 = Intrinsics_x64_AVX512::bit_reverse(m3); + b4 = Intrinsics_x64_AVX512::bit_reverse(m4); + b5 = Intrinsics_x64_AVX512::bit_reverse(m5); + b6 = Intrinsics_x64_AVX512::bit_reverse(m6); + b7 = Intrinsics_x64_AVX512::bit_reverse(m7); + + t0 = m0; + t1 = m1; + t2 = m2; + t3 = m3; + t4 = m4; + t5 = m5; + t6 = m6; + t7 = m7; + transpose_i64_8x8_AVX512(t0, t1, t2, t3, t4, t5, t6, t7); + + // Forward carry + __m512i f0 = t0; + f1 = _mm512_and_si512(f0, t1); + f2 = _mm512_and_si512(f1, t2); + f3 = _mm512_and_si512(f2, t3); + f4 = _mm512_and_si512(f3, t4); + f5 = _mm512_and_si512(f4, t5); + f6 = _mm512_and_si512(f5, t6); + f7 = _mm512_and_si512(f6, t7); + transpose_i64_8x8_AVX512(f0, f1, f2, f3, f4, f5, f6, f7); + + // Reverse carry + __m512i r7 = t7; + r6 = _mm512_and_si512(r7, t6); + r5 = _mm512_and_si512(r6, t5); + r4 = _mm512_and_si512(r5, t4); + r3 = _mm512_and_si512(r4, t3); + r2 = _mm512_and_si512(r3, t2); + r1 = _mm512_and_si512(r2, t1); + r0 = _mm512_and_si512(r1, t0); + transpose_i64_8x8_AVX512(r0, r1, r2, r3, r4, r5, r6, r7); + } +}; + + + +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x64_x64_AVX512_ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, + __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 +){ + // Carry across adjacent rows. + transpose_i64_8x8_AVX512(x0, x1, x2, x3, x4, x5, x6, x7); + x1 = _mm512_ternarylogic_epi64(x1, x0, mask.t1, 0b11111000); + x6 = _mm512_ternarylogic_epi64(x6, x7, mask.t6, 0b11111000); + x2 = _mm512_ternarylogic_epi64(x2, x1, mask.t2, 0b11111000); + x5 = _mm512_ternarylogic_epi64(x5, x6, mask.t5, 0b11111000); + x3 = _mm512_ternarylogic_epi64(x3, x2, mask.t3, 0b11111000); + x4 = _mm512_ternarylogic_epi64(x4, x5, mask.t4, 0b11111000); + x4 = _mm512_ternarylogic_epi64(x4, x3, mask.t4, 0b11111000); + x3 = _mm512_ternarylogic_epi64(x3, x4, mask.t3, 0b11111000); + x5 = _mm512_ternarylogic_epi64(x5, x4, mask.t5, 0b11111000); + x2 = _mm512_ternarylogic_epi64(x2, x3, mask.t2, 0b11111000); + x6 = _mm512_ternarylogic_epi64(x6, x5, mask.t6, 0b11111000); + x1 = _mm512_ternarylogic_epi64(x1, x2, mask.t1, 0b11111000); + x7 = _mm512_ternarylogic_epi64(x7, x6, mask.t7, 0b11111000); + x0 = _mm512_ternarylogic_epi64(x0, x1, mask.t0, 0b11111000); + transpose_i64_8x8_AVX512(x0, x1, x2, x3, x4, x5, x6, x7); + + // Carry across groups of 8 rows. + x1 = _mm512_ternarylogic_epi64(x1, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x0), mask.f1, 0b11111000); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x7)), mask.r6, 0b11111000); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x1), mask.f2, 0b11111000); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x6)), mask.r5, 0b11111000); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x2), mask.f3, 0b11111000); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x5)), mask.r4, 0b11111000); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x3), mask.f4, 0b11111000); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x4)), mask.r3, 0b11111000); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x4), mask.f5, 0b11111000); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x3)), mask.r2, 0b11111000); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x5), mask.f6, 0b11111000); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x2)), mask.r1, 0b11111000); + x7 = _mm512_ternarylogic_epi64(x7, _mm512_permutexvar_epi64(_mm512_set1_epi64(7), x6), mask.f7, 0b11111000); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_broadcastq_epi64(_mm512_castsi512_si128(x1)), mask.r0, 0b11111000); +} + + + + + + +struct Waterfill_64x64_x64_AVX512{ + + + +static PA_FORCE_INLINE __m512i vec_or(const BinaryTile_64x64_x64_AVX512& tile){ + __m512i v0 = _mm512_or_si512(tile.vec[0], tile.vec[1]); + __m512i v1 = _mm512_or_si512(tile.vec[2], tile.vec[3]); + __m512i v2 = _mm512_or_si512(tile.vec[4], tile.vec[5]); + __m512i v3 = _mm512_or_si512(tile.vec[6], tile.vec[7]); + v0 = _mm512_or_si512(v0, v1); + v2 = _mm512_or_si512(v2, v3); + v0 = _mm512_or_si512(v0, v2); + return v0; +} +static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x64_x64_AVX512& tile){ + return _mm512_reduce_or_epi64(vec_or(tile)); +} + + + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x64_x64_AVX512& tile){ + __m512i anything = vec_or(tile); + if (!_mm512_test_epi64_mask(anything, anything)){ + return false; + } + __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + for (size_t c = 0; c < 8; c++){ + __m512i vec = tile.vec[c]; + __mmask8 mask = _mm512_test_epi64_mask(vec, vec); + if (mask){ + vec = _mm512_maskz_compress_epi64(mask, vec); + row = _mm512_maskz_compress_epi64(mask, row); + uint64_t word = _mm_cvtsi128_si64(_mm512_castsi512_si128(vec)); + y = _mm_cvtsi128_si64(_mm512_castsi512_si128(row)); + trailing_zeros(x, word); + return true; + } + row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); + } + return false; +} + + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const BinaryTile_64x64_x64_AVX512& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + __m512i row = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + __m512i min = _mm512_set1_epi64(-1); + __m512i max = _mm512_setzero_si512(); + for (size_t c = 0; c < 8; c++){ + __m512i vec = tile.vec[c]; + __mmask8 mask = _mm512_cmpneq_epu64_mask(vec, _mm512_setzero_si512()); + min = _mm512_mask_min_epu64(min, mask, min, row); + max = _mm512_mask_max_epu64(max, mask, max, row); + row = _mm512_add_epi64(row, _mm512_set1_epi64(8)); + } + min_y = _mm512_reduce_min_epu64(min); + max_y = _mm512_reduce_max_epu64(max) + 1; +} + + + +// Area + Center of Gravity: +// Compute the sum of the index of each set bit. +// Returns the popcount. +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const BinaryTile_64x64_x64_AVX512& tile +){ + __m512i sum_p, sum_x, sum_y; + __m512i offsets = _mm512_setr_epi64(0, 1, 2, 3, 4, 5, 6, 7); + { + __m512i pop, sum; + pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[0]); + sum_p = pop; + sum_x = sum; + sum_y = _mm512_mul_epu32(pop, offsets); + } + for (size_t c = 1; c < 8; c++){ + __m512i pop, sum; + pop = Intrinsics_x64_AVX512::popcount_indexsum(sum, tile.vec[c]); + sum_p = _mm512_add_epi64(sum_p, pop); + sum_x = _mm512_add_epi64(sum_x, sum); + offsets = _mm512_add_epi64(offsets, _mm512_set1_epi64(8)); + sum_y = _mm512_add_epi64(sum_y, _mm512_mul_epu32(pop, offsets)); + } + sum_xcoord = _mm512_reduce_add_epi64(sum_x); + sum_ycoord = _mm512_reduce_add_epi64(sum_y); + return _mm512_reduce_add_epi64(sum_p); +} + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x64_x64_AVX512& m, BinaryTile_64x64_x64_AVX512& x){ + __m512i x0 = x.vec[0]; + __m512i x1 = x.vec[1]; + __m512i x2 = x.vec[2]; + __m512i x3 = x.vec[3]; + __m512i x4 = x.vec[4]; + __m512i x5 = x.vec[5]; + __m512i x6 = x.vec[6]; + __m512i x7 = x.vec[7]; + + Waterfill_64x64_x64_AVX512_ProcessedMask mask(m, x0, x1, x2, x3, x4, x5, x6, x7); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); + + __m512i m0, m1, m2, m3, m4, m5, m6, m7; + do{ + expand_vertical(mask, x0, x1, x2, x3, x4, x5, x6, x7); + Intrinsics_x64_AVX512::expand_reverse(mask, x0, x1, x2, x3, x4, x5, x6, x7); + Intrinsics_x64_AVX512::expand_forward(mask, x0, x1, x2, x3, x4, x5, x6, x7); + }while (Intrinsics_x64_AVX512::keep_going( + mask, + m0, m1, m2, m3, m4, m5, m6, m7, + x0, x1, x2, x3, x4, x5, x6, x7 + )); + x.vec[0] = x0; + x.vec[1] = x1; + x.vec[2] = x2; + x.vec[3] = x3; + x.vec[4] = x4; + x.vec[5] = x5; + x.vec[6] = x6; + x.vec[7] = x7; + m.vec[0] = m0; + m.vec[1] = m1; + m.vec[2] = m2; + m.vec[3] = m3; + m.vec[4] = m4; + m.vec[5] = m5; + m.vec[6] = m6; + m.vec[7] = m7; +} + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const BinaryTile_64x64_x64_AVX512& mask, + BinaryTile_64x64_x64_AVX512& tile, + const BinaryTile_64x64_x64_AVX512& border +){ + uint64_t available = mask.top() & ~tile.top(); + uint64_t new_bits = available & border.bottom(); + if (new_bits == 0){ + return false; + } + tile.top() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const BinaryTile_64x64_x64_AVX512& mask, + BinaryTile_64x64_x64_AVX512& tile, + const BinaryTile_64x64_x64_AVX512& border +){ + uint64_t available = mask.bottom() & ~tile.bottom(); + uint64_t new_bits = available & border.top(); + if (new_bits == 0){ + return false; + } + tile.bottom() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const BinaryTile_64x64_x64_AVX512& mask, + BinaryTile_64x64_x64_AVX512& tile, + const BinaryTile_64x64_x64_AVX512& border +){ + __m512i changed = _mm512_setzero_si512(); + for (size_t c = 0; c < 8; c++){ + __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); + __m512i new_bits = _mm512_and_si512(available, _mm512_srli_epi64(border.vec[c], 63)); + changed = _mm512_or_si512(changed, new_bits); + tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); + } + return _mm512_test_epi64_mask(changed, changed); +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const BinaryTile_64x64_x64_AVX512& mask, + BinaryTile_64x64_x64_AVX512& tile, + const BinaryTile_64x64_x64_AVX512& border +){ + __m512i changed = _mm512_setzero_si512(); + for (size_t c = 0; c < 8; c++){ + __m512i available = _mm512_andnot_si512(tile.vec[c], mask.vec[c]); + __m512i new_bits = _mm512_and_si512(available, _mm512_slli_epi64(border.vec[c], 63)); + changed = _mm512_or_si512(changed, new_bits); + tile.vec[c] = _mm512_or_si512(tile.vec[c], new_bits); + } + return _mm512_test_epi64_mask(changed, changed); +} + + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.cpp index 826c2a52a4..a5e6ef965b 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.cpp @@ -1,62 +1,62 @@ -/* Waterfill Core (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_arm64_20_M1 - -// #define USE_CPP_TEMPLATE_IMPL - -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x8_arm64_NEON.h" - -#ifdef USE_CPP_TEMPLATE_IMPL -#include "Kernels_Waterfill_Core_64xH_Default.h" -#endif - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - -#ifdef USE_CPP_TEMPLATE_IMPL - -using Waterfill_64x8_Default = Waterfill_64xH_Default; - -std::vector find_objects_inplace_64x8_arm64_NEON(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x8_arm64_NEON(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - -#else - -std::vector find_objects_inplace_64x8_arm64_NEON(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x8_arm64_NEON(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -} - -#endif - - -} -} -} -#endif +/* Waterfill Core (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_arm64_20_M1 + +// #define USE_CPP_TEMPLATE_IMPL + +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x8_arm64_NEON.h" + +#ifdef USE_CPP_TEMPLATE_IMPL +#include "Kernels_Waterfill_Core_64xH_Default.h" +#endif + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + +#ifdef USE_CPP_TEMPLATE_IMPL + +using Waterfill_64x8_Default = Waterfill_64xH_Default; + +std::vector find_objects_inplace_64x8_arm64_NEON(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x8_arm64_NEON(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + +#else + +std::vector find_objects_inplace_64x8_arm64_NEON(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x8_arm64_NEON(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +} + +#endif + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h index 97749af917..9b7ff9e4c8 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h @@ -1,530 +1,530 @@ -/* Waterfill Core (arm64 NEON) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x8_arm64_NEON_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x8_arm64_NEON_H - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_arm64_NEON.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -PA_FORCE_INLINE uint64x2_t bit_reverse(uint64x2_t x){ - uint8x16_t r0, r1; - - // Use byte table lookup to swap the endianness of the two uint64_t - uint8x16_t x_shuffled = vqtbl1q_u8(vreinterpretq_u8_u64(x), uint8x16_t{7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8}); - - // If originaly one byte in `x` has the order (high to low) h, g, f, e, d, c, b, a: - // right shift each byte by 4, r0 has (high to low) 0, 0, 0, 0, h, g, f, e - r0 = vshrq_n_u8(x_shuffled, 4); - // left shift each byte by 4, r1 has (high to low) d, c, b, a, 0, 0, 0, 0 - r1 = vshlq_n_u8(x_shuffled, 4); - // after this logical OR in `r1` it is now (high to low) d, c, b, a, h, g, f, e - r1 = vorrq_u8(r0, r1); - - // after right shift, r0 now has 0, 0, d, c, b, a, h, g - r0 = vshrq_n_u8(r1, 2); - // after left shif,t r1 now has b, a, h, g, f, e, 0, 0 - r1 = vshlq_n_u8(r1, 2); - - // After logical AND with 0x00110011, r0 has 0, 0, d, c, 0, 0, h, g - r0 = vandq_u8(r0, vdupq_n_u8(0x33)); - // After logical AND with 0x11001100, r0 has b, a, 0, 0, f, e, 0, 0 - r1 = vandq_u8(r1, vdupq_n_u8(0xcc)); - // after logical OR r1 has b, a, d, c, f, e, h, g - r1 = vorrq_u8(r0, r1); - - r0 = vshrq_n_u8(r1, 1); // 0, b, a, d, c, f, e, h - r1 = vshlq_n_u8(r1, 1); // a, d, c, f, e, h, g, 0 - // logical AND with 0x01010101, r0 has 0, b, 0, d, 0, f, 0, h - r0 = vandq_u8(r0, vdupq_n_u8(0x55)); - // logical AND with 0x10101010, r1 has a, 0, c, 0, e, 0, g, 0 - r1 = vandq_u8(r1, vdupq_n_u8(0xaa)); - r1 = vorrq_u8(r0, r1); // a, b, c, d, e, f, g, h - - return r1; -} - - - -struct Waterfill_64x8_arm64_NEON_ProcessedMask{ - uint64x2_t m0, m1, m2, m3; // Copy of logical OR of the mask `m` and recorded tile `x` bits - uint64x2_t b0, b1, b2, b3; // Bit-reversed copy of m0, m1, m2, m3. - uint64x2_t t0, t1, t2, t3; // Transposed masks. - uint64x2_t f1, f2, f3; // Forward-carry mask. - uint64x2_t r0, r1, r2; // Reverse-carry mask. - - PA_FORCE_INLINE Waterfill_64x8_arm64_NEON_ProcessedMask( - const BinaryTile_64x8_arm64_NEON& m, - uint64x2_t x0, uint64x2_t x1, uint64x2_t x2, uint64x2_t x3 - ){ - m0 = vorrq_u64(x0, m.vec.val[0]); - m1 = vorrq_u64(x1, m.vec.val[1]); - m2 = vorrq_u64(x2, m.vec.val[2]); - m3 = vorrq_u64(x3, m.vec.val[3]); - - b0 = bit_reverse(m0); - b1 = bit_reverse(m1); - b2 = bit_reverse(m2); - b3 = bit_reverse(m3); - - t0 = m0; - t1 = m1; - t2 = m2; - t3 = m3; - transpose_u64_2x2_NEON(t0, t1); - transpose_u64_2x2_NEON(t2, t3); - - // Forward carry - uint64x2_t f0 = t0; - f1 = vandq_u64(f0, t1); - transpose_u64_2x2_NEON(f0, f1); - f2 = t2; - f3 = vandq_u64(f2, t3); - transpose_u64_2x2_NEON(f2, f3); - - // Reverse carry - uint64x2_t r3 = t3; - r2 = vandq_u64(r3, t2); - transpose_u64_2x2_NEON(r2, r3); - r1 = t1; - r0 = vandq_u64(r1, t0); - transpose_u64_2x2_NEON(r0, r1); - } -}; - - - -PA_FORCE_INLINE bool keep_going( - const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, - uint64x2_t& m0, uint64x2_t& m1, uint64x2_t& m2, uint64x2_t& m3, - uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 -){ - m0 = vbicq_u64(mask.m0, x0); - m1 = vbicq_u64(mask.m1, x1); - m2 = vbicq_u64(mask.m2, x2); - m3 = vbicq_u64(mask.m3, x3); - - uint64x2_t r0; - - r0 = vshlq_n_u64(m0, 1); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m0), vget_low_u64(m1))); - r0 = vorrq_u64(r0, vcombine_u64(vcreate_u64(0), vget_low_u64(m0))); - uint64x2_t changed = vandq_u64(r0, x0); - - r0 = vshlq_n_u64(m1, 1); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m1), vget_low_u64(m2))); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m0), vget_low_u64(m1))); - r0 = vandq_u64(r0, x1); - changed = vorrq_u64(changed, r0); - - r0 = vshlq_n_u64(m2, 1); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m2), vget_low_u64(m3))); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m1), vget_low_u64(m2))); - r0 = vandq_u64(r0, x2); - changed = vorrq_u64(changed, r0); - - r0 = vshlq_n_u64(m3, 1); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m3), vcreate_u64(0))); - r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m2), vget_low_u64(m3))); - r0 = vandq_u64(r0, x3); - changed = vorrq_u64(changed, r0); - - // Test if there is 1 bit in `changed` - return vgetq_lane_u64(changed, 0) | vgetq_lane_u64(changed, 1); -} - - - -PA_FORCE_INLINE void expand_forward( - const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, - uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 -){ - uint64x2_t s0 = vaddq_u64(x0, mask.m0); - uint64x2_t s1 = vaddq_u64(x1, mask.m1); - uint64x2_t s2 = vaddq_u64(x2, mask.m2); - uint64x2_t s3 = vaddq_u64(x3, mask.m3); - - s0 = vbicq_u64(mask.m0, s0); - s1 = vbicq_u64(mask.m1, s1); - s2 = vbicq_u64(mask.m2, s2); - s3 = vbicq_u64(mask.m3, s3); - - x0 = vorrq_u64(x0, s0); - x1 = vorrq_u64(x1, s1); - x2 = vorrq_u64(x2, s2); - x3 = vorrq_u64(x3, s3); -} -PA_FORCE_INLINE void expand_reverse(uint64x2_t m, uint64x2_t b, uint64x2_t& x){ - uint64x2_t s = bit_reverse(vaddq_u64(bit_reverse(x), b)); - s = veorq_u64(s, m); - s = vandq_u64(s, m); - x = vorrq_u64(x, s); -} -PA_FORCE_INLINE void expand_reverse( - const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, - uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 -){ - expand_reverse(mask.m0, mask.b0, x0); - expand_reverse(mask.m1, mask.b1, x1); - expand_reverse(mask.m2, mask.b2, x2); - expand_reverse(mask.m3, mask.b3, x3); -} -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, - uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 -){ - // Carry across adjacent rows. - transpose_u64_2x2_NEON(x0, x1); - transpose_u64_2x2_NEON(x2, x3); - x0 = vorrq_u64(x0, vandq_u64(x1, mask.t0)); - x1 = vorrq_u64(x1, vandq_u64(x0, mask.t1)); - x2 = vorrq_u64(x2, vandq_u64(x3, mask.t2)); - x3 = vorrq_u64(x3, vandq_u64(x2, mask.t3)); - transpose_u64_2x2_NEON(x0, x1); - transpose_u64_2x2_NEON(x2, x3); - - // Carry across groups of 2 rows. - uint64x1_t x0h = vget_high_u64(x0); - x1 = vorrq_u64(x1, vandq_u64(vcombine_u64(x0h, x0h), mask.f1)); - uint64x1_t x3l = vget_low_u64(x3); - x2 = vorrq_u64(x2, vandq_u64(vcombine_u64(x3l, x3l), mask.r2)); - uint64x1_t x1h = vget_high_u64(x1); - x2 = vorrq_u64(x2, vandq_u64(vcombine_u64(x1h, x1h), mask.f2)); - uint64x1_t x2l = vget_low_u64(x2); - x1 = vorrq_u64(x1, vandq_u64(vcombine_u64(x2l, x2l), mask.r1)); - uint64x1_t x2h = vget_high_u64(x2); - x3 = vorrq_u64(x3, vandq_u64(vcombine_u64(x2h, x2h), mask.f3)); - uint64x1_t x1l = vget_low_u64(x1); - x0 = vorrq_u64(x0, vandq_u64(vcombine_u64(x1l, x1l), mask.r0)); -} - - - -struct Waterfill_64x8_arm64_NEON{ - - - -// Do vector-wise logical OR among each SIMD vector -static PA_FORCE_INLINE uint64x2_t vec_or(const BinaryTile_64x8_arm64_NEON& tile){ - uint64x2_t v0 = vorrq_u64(tile.vec.val[0], tile.vec.val[1]); - uint64x2_t v1 = vorrq_u64(tile.vec.val[2], tile.vec.val[3]); - return vorrq_u64(v0, v1); -} -// Do a in-tile row-wise logical OR among each row -static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x8_arm64_NEON& tile){ - uint64x2_t v = vec_or(tile); - return vgetq_lane_u64(v, 0) | vgetq_lane_u64(v, 1); -} - - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x8_arm64_NEON& tile){ - // Check whether thera are any 1-bits in the tile: - uint64x2_t anything = vec_or(tile); - if ((vgetq_lane_u64(anything, 0) | vgetq_lane_u64(anything, 1)) == 0){ - return false; - } - // Check each tile row: - for (size_t r = 0; r < 8; r++){ - size_t pos; - if (trailing_zeros(pos, tile.row(r))){ - x = pos; - y = r; - return true; - } - } - return false; -} - - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const BinaryTile_64x8_arm64_NEON& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - min_y = 0; - for (size_t c = 0; c < 8; c++){ - if (tile.row(c) != 0){ - min_y = c; - break; - } - } - max_y = 0; - for (size_t c = 8; c > 0; c--){ - if (tile.row(c - 1) != 0){ - max_y = c; - break; - } - } -} - - - -// Compute the sum of the indices of 1 bits in `x` and store in `sum_index`, and compute -// counts of 1 bits (aka popcount) of `x` and return it as the function return. -// Note: `sum_index` is useful for computing center of gravity of bitmap objects. -// Example of index sum of a bitmap: -// 0b0001 is 0 -// 0b0100 is 2 -// 0b1010 is 1 + 3 = 4 -static PA_FORCE_INLINE uint64x2_t popcount_indexsum(uint64x2_t& sum_index, uint64x2_t x){ - // 1 -> 2 - // Get the bits in the original [0, 2, 4, 6, ...] bit positions by right shifting by one, then - // logical AND with 0b ... 0101 0101 - uint8x16_t pop_high = vandq_u8(vshrq_n_u8(vreinterpretq_u8_u64(x), 1), vdupq_n_u8(0x55)); - // Get the bits in the original [1, 3, 5, 7, ...] bit positions by logical AND with 0b ... 0101 0101 - uint8x16_t pop_low = vandq_u8(vreinterpretq_u8_u64(x), vdupq_n_u8(0x55)); - // Add them to get the bit-pair-wise addition - // Each nbring pair of bits is added in the pair and the result is stored in a 2-bit-wide space. - // The result can only be 0b00, 0b01 or 0b10 so it won't overflow the 2-bit storage. - // You can think `popcount` as storing the bit count of each 2-bit-wide space of the original bitmap - uint8x16_t popcount = vaddq_u8(pop_low, pop_high); - - uint8x16_t sum_high, sum_low; - // think `sumaxis` as containing the index sum of the bits of the 2-bit-wide space in the original bitmap, - // For each 2-bit wide space in the original bitmap: - // if it's 0b00, then index sum is 0 - // if it's 0b01, then index sum is 0 (the 1 is at 0-th index, so the index sum is still 0) - // if it's 0b10, then index sum is 1 - // if it's 0b11, then index sum is 1 - uint8x16_t sumxaxis = pop_high; - - // 2 -> 4 - // Right shift `sumxaxis` by 2, then logical AND with 0b ... 0011 0011 - // This means we get the 0b1100 part of `sumxaxis` into sum_high - sum_high = vandq_u8(vshrq_n_u8(sumxaxis, 2), vdupq_n_u8(0x33)); - // Right shift `popcount` by 2, then logical AND with 0b ... 0011 0011 - // This means we get the 0b1100 part of `popcount` into `pop_high` - pop_high = vandq_u8(vshrq_n_u8(popcount, 2), vdupq_n_u8(0x33)); - // logical AND of `sumxaxis` and 0b ... 0011 0011 - // This means we get the 0b0011 part of `sumxaxis` into `sum_low` - sum_low = vandq_u8(sumxaxis, vdupq_n_u8(0x33)); - // Add sum_low and sum_high together for each 4-bit-wide space - // Then add the count from `pop_high` shifted. - // You can think index sum is made by "lower part" of a 4-bit-wide space and "higher part" of the space. - // According to the physics reasoning that computes the combined center of gravity of a collection of objects, - // 4-bit index sum = 2-bit index sum of the lower part + 2-bit index sum of the higher part - // + bit count of the higher part * 2 - // `sumxaxis` value for each 4-bit-wide space ranges [0, 6] - sumxaxis = vaddq_u8(sum_low, sum_high); - sumxaxis = vaddq_u8(sumxaxis, vshlq_n_u8(pop_high, 1)); - - // Get the 0b0011 part of `popcount` into `pop_low` - pop_low = vandq_u8(popcount, vdupq_n_u8(0x33)); - // Add `pop_low` and `pop_high` together to count the bits in 4-bit-wide nbrhood in the original bitmap - // The max value possible is 4 (aka 0b0100), so won't overflow 4-bit-wide space - // You can think `popcount` as storing the bit count of each 4-bit-wide space of the original bitmap - // You can think `pop_low` is the bit count of the "lower part" (in this block of compuattion, the lower - // part of the 4-bit-wide space), while `pop_high` is the bit count of the "higher part". - // `popcount` value for each 4-bit-wide space ranges [0, 4] - popcount = vaddq_u8(pop_low, pop_high); - - // 4 -> 8 - // `sum_high`: higher part of the 8-bit-wide space in `sumxaxis` - sum_high = vandq_u8(vshrq_n_u8(sumxaxis, 4), vdupq_n_u8(0x0f)); - // `pip_high`: higher part of the 8-bit-wide space in `popcount` - pop_high = vandq_u8(vshrq_n_u8(popcount, 4), vdupq_n_u8(0x0f)); - // `sum_low`: lower part of the 8-bit-wide space in `sumxaxis` - sum_low = vandq_u8(sumxaxis, vdupq_n_u8(0x0f)); - // `sumxaxis`: index sum for each 8-bit-wide space, value range: [0, 28] - sumxaxis = vaddq_u8(sum_low, sum_high); - sumxaxis = vaddq_u8(sumxaxis, vshlq_n_u8(pop_high, 2)); - // `pop_low`: lower part of the 8-bit-wide space in `popcount` - pop_low = vandq_u8(popcount, vdupq_n_u8(0x0f)); - // `popcount` of the 8-bit-wide space, range [0, 8] - popcount = vaddq_u8(pop_low, pop_high); - - // 8 -> 16 - // Get higher part of 16-bit-wide space in `popcount` - uint16x8_t pop_high_u16x8 = vshrq_n_u16(vreinterpretq_u16_u8(popcount), 8); - // Get the index sum for each 16-bit-wise space - // vpadalq_u8(a, b): pair-wise add in `b`, then add to `a` - // index sum range: [0, 120] - uint16x8_t sumxaxis_u16x8 = vpadalq_u8(vshlq_n_u16(pop_high_u16x8, 3), sumxaxis); - // Get popcount of each 16-bit-wise space - // popcount value: [0, 16] - uint16x8_t popcount_u16x8 = vpaddlq_u8(popcount); - - // 16 -> 32 - uint32x4_t pop_high_u32x4 = vshrq_n_u32(vreinterpretq_u32_u16(popcount_u16x8), 16); - // Get the index sum for each 32-bit-wise space - // index sum range: [0, 496] - uint32x4_t sumxaxis_u32x4 = vpadalq_u16(vshlq_n_u32(pop_high_u32x4, 4), sumxaxis_u16x8); - // Get popcount of each 32-bit-wise space - // popcount value: [0, 32] - uint32x4_t popcount_u32x4 = vpaddlq_u16(popcount_u16x8); - - // 32 -> 64 - uint64x2_t pop_high_u64x2 = vshrq_n_u64(vreinterpretq_u64_u32(popcount_u32x4), 32); - // Get the index sum for each 64-bit-wise space - uint64x2_t sumxaxis_u64x2 = vpadalq_u32(vshlq_n_u64(pop_high_u64x2, 5), sumxaxis_u32x4); - // Get popcount of each 64-bit-wise space - uint64x2_t popcount_u64x2 = vpaddlq_u32(popcount_u32x4); - - // TODO: The above vpadxlq_uxx() operations are horizontal, may be slow. - // Can try to compare with SSE42 impl. - - sum_index = sumxaxis_u64x2; - return popcount_u64x2; -} - -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const BinaryTile_64x8_arm64_NEON& tile -){ - uint64x2_t sum_p, sum_x, sum_y; - { - uint64x2_t pop, sum; - pop = popcount_indexsum(sum, tile.vec.val[0]); - sum_p = pop; - sum_x = sum; - sum_y = vmull_u32(vmovn_u64(pop), uint32x2_t{0, 1}); - } - { - uint64x2_t pop, sum; - pop = popcount_indexsum(sum, tile.vec.val[1]); - sum_p = vaddq_u64(sum_p, pop); - sum_x = vaddq_u64(sum_x, sum); - sum_y = vaddq_u64(sum_y, vmull_u32(vmovn_u64(pop), uint32x2_t{2, 3})); - } - { - uint64x2_t pop, sum; - pop = popcount_indexsum(sum, tile.vec.val[2]); - sum_p = vaddq_u64(sum_p, pop); - sum_x = vaddq_u64(sum_x, sum); - sum_y = vaddq_u64(sum_y, vmull_u32(vmovn_u64(pop), uint32x2_t{4, 5})); - } - { - uint64x2_t pop, sum; - pop = popcount_indexsum(sum, tile.vec.val[3]); - sum_p = vaddq_u64(sum_p, pop); - sum_x = vaddq_u64(sum_x, sum); - sum_y = vaddq_u64(sum_y, vmull_u32(vmovn_u64(pop), uint32x2_t{6, 7})); - } - sum_xcoord = vgetq_lane_u64(sum_x, 0) + vgetq_lane_u64(sum_x, 1); - sum_ycoord = vgetq_lane_u64(sum_y, 0) + vgetq_lane_u64(sum_y, 1); - return vgetq_lane_u64(sum_p, 0) + vgetq_lane_u64(sum_p, 1); -} - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x8_arm64_NEON& m, BinaryTile_64x8_arm64_NEON& x){ - uint64x2_t x0 = x.vec.val[0]; - uint64x2_t x1 = x.vec.val[1]; - uint64x2_t x2 = x.vec.val[2]; - uint64x2_t x3 = x.vec.val[3]; - - Waterfill_64x8_arm64_NEON_ProcessedMask mask(m, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - - uint64x2_t m0, m1, m2, m3; - do{ - expand_vertical(mask, x0, x1, x2, x3); - expand_reverse(mask, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - }while (keep_going( - mask, - m0, m1, m2, m3, - x0, x1, x2, x3 - )); - x.vec.val[0] = x0; - x.vec.val[1] = x1; - x.vec.val[2] = x2; - x.vec.val[3] = x3; - m.vec.val[0] = m0; - m.vec.val[1] = m1; - m.vec.val[2] = m2; - m.vec.val[3] = m3; -} - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const BinaryTile_64x8_arm64_NEON& mask, - BinaryTile_64x8_arm64_NEON& tile, - const BinaryTile_64x8_arm64_NEON& border -){ - uint64_t available = mask.top() & ~tile.top(); - uint64_t new_bits = available & border.bottom(); - if (new_bits == 0){ - return false; - } - tile.top() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const BinaryTile_64x8_arm64_NEON& mask, - BinaryTile_64x8_arm64_NEON& tile, - const BinaryTile_64x8_arm64_NEON& border -){ - uint64_t available = mask.bottom() & ~tile.bottom(); - uint64_t new_bits = available & border.top(); - if (new_bits == 0){ - return false; - } - tile.bottom() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const BinaryTile_64x8_arm64_NEON& mask, - BinaryTile_64x8_arm64_NEON& tile, - const BinaryTile_64x8_arm64_NEON& border -){ - uint64x2_t changed = vreinterpretq_u64_u8(vdupq_n_u8(0)); - for (size_t c = 0; c < 4; c++){ - uint64x2_t available = vbicq_u64(mask.vec.val[c], tile.vec.val[c]); - uint64x2_t new_bits = vandq_u64(available, vshrq_n_u64(border.vec.val[c], 63)); - changed = vorrq_u64(changed, new_bits); - tile.vec.val[c] = vorrq_u64(tile.vec.val[c], new_bits); - } - // Test if there is 1 bit in `changed` - return vgetq_lane_u64(changed, 0) | vgetq_lane_u64(changed, 1); -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const BinaryTile_64x8_arm64_NEON& mask, - BinaryTile_64x8_arm64_NEON& tile, - const BinaryTile_64x8_arm64_NEON& border -){ - uint64x2_t changed = vreinterpretq_u64_u8(vdupq_n_u8(0)); - for (size_t c = 0; c < 4; c++){ - uint64x2_t available = vbicq_u64(mask.vec.val[c], tile.vec.val[c]); - uint64x2_t new_bits = vandq_u64(available, vshlq_n_u64(border.vec.val[c], 63)); - changed = vorrq_u64(changed, new_bits); - tile.vec.val[c] = vorrq_u64(tile.vec.val[c], new_bits); - } - // Test if there is 1 bit in `changed` - return vgetq_lane_u64(changed, 0) | vgetq_lane_u64(changed, 1); -} - - -}; - - - -} -} -} -#endif +/* Waterfill Core (arm64 NEON) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x8_arm64_NEON_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x8_arm64_NEON_H + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_arm64_NEON.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_arm64_NEON.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +PA_FORCE_INLINE uint64x2_t bit_reverse(uint64x2_t x){ + uint8x16_t r0, r1; + + // Use byte table lookup to swap the endianness of the two uint64_t + uint8x16_t x_shuffled = vqtbl1q_u8(vreinterpretq_u8_u64(x), uint8x16_t{7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8}); + + // If originaly one byte in `x` has the order (high to low) h, g, f, e, d, c, b, a: + // right shift each byte by 4, r0 has (high to low) 0, 0, 0, 0, h, g, f, e + r0 = vshrq_n_u8(x_shuffled, 4); + // left shift each byte by 4, r1 has (high to low) d, c, b, a, 0, 0, 0, 0 + r1 = vshlq_n_u8(x_shuffled, 4); + // after this logical OR in `r1` it is now (high to low) d, c, b, a, h, g, f, e + r1 = vorrq_u8(r0, r1); + + // after right shift, r0 now has 0, 0, d, c, b, a, h, g + r0 = vshrq_n_u8(r1, 2); + // after left shif,t r1 now has b, a, h, g, f, e, 0, 0 + r1 = vshlq_n_u8(r1, 2); + + // After logical AND with 0x00110011, r0 has 0, 0, d, c, 0, 0, h, g + r0 = vandq_u8(r0, vdupq_n_u8(0x33)); + // After logical AND with 0x11001100, r0 has b, a, 0, 0, f, e, 0, 0 + r1 = vandq_u8(r1, vdupq_n_u8(0xcc)); + // after logical OR r1 has b, a, d, c, f, e, h, g + r1 = vorrq_u8(r0, r1); + + r0 = vshrq_n_u8(r1, 1); // 0, b, a, d, c, f, e, h + r1 = vshlq_n_u8(r1, 1); // a, d, c, f, e, h, g, 0 + // logical AND with 0x01010101, r0 has 0, b, 0, d, 0, f, 0, h + r0 = vandq_u8(r0, vdupq_n_u8(0x55)); + // logical AND with 0x10101010, r1 has a, 0, c, 0, e, 0, g, 0 + r1 = vandq_u8(r1, vdupq_n_u8(0xaa)); + r1 = vorrq_u8(r0, r1); // a, b, c, d, e, f, g, h + + return r1; +} + + + +struct Waterfill_64x8_arm64_NEON_ProcessedMask{ + uint64x2_t m0, m1, m2, m3; // Copy of logical OR of the mask `m` and recorded tile `x` bits + uint64x2_t b0, b1, b2, b3; // Bit-reversed copy of m0, m1, m2, m3. + uint64x2_t t0, t1, t2, t3; // Transposed masks. + uint64x2_t f1, f2, f3; // Forward-carry mask. + uint64x2_t r0, r1, r2; // Reverse-carry mask. + + PA_FORCE_INLINE Waterfill_64x8_arm64_NEON_ProcessedMask( + const BinaryTile_64x8_arm64_NEON& m, + uint64x2_t x0, uint64x2_t x1, uint64x2_t x2, uint64x2_t x3 + ){ + m0 = vorrq_u64(x0, m.vec.val[0]); + m1 = vorrq_u64(x1, m.vec.val[1]); + m2 = vorrq_u64(x2, m.vec.val[2]); + m3 = vorrq_u64(x3, m.vec.val[3]); + + b0 = bit_reverse(m0); + b1 = bit_reverse(m1); + b2 = bit_reverse(m2); + b3 = bit_reverse(m3); + + t0 = m0; + t1 = m1; + t2 = m2; + t3 = m3; + transpose_u64_2x2_NEON(t0, t1); + transpose_u64_2x2_NEON(t2, t3); + + // Forward carry + uint64x2_t f0 = t0; + f1 = vandq_u64(f0, t1); + transpose_u64_2x2_NEON(f0, f1); + f2 = t2; + f3 = vandq_u64(f2, t3); + transpose_u64_2x2_NEON(f2, f3); + + // Reverse carry + uint64x2_t r3 = t3; + r2 = vandq_u64(r3, t2); + transpose_u64_2x2_NEON(r2, r3); + r1 = t1; + r0 = vandq_u64(r1, t0); + transpose_u64_2x2_NEON(r0, r1); + } +}; + + + +PA_FORCE_INLINE bool keep_going( + const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, + uint64x2_t& m0, uint64x2_t& m1, uint64x2_t& m2, uint64x2_t& m3, + uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 +){ + m0 = vbicq_u64(mask.m0, x0); + m1 = vbicq_u64(mask.m1, x1); + m2 = vbicq_u64(mask.m2, x2); + m3 = vbicq_u64(mask.m3, x3); + + uint64x2_t r0; + + r0 = vshlq_n_u64(m0, 1); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m0), vget_low_u64(m1))); + r0 = vorrq_u64(r0, vcombine_u64(vcreate_u64(0), vget_low_u64(m0))); + uint64x2_t changed = vandq_u64(r0, x0); + + r0 = vshlq_n_u64(m1, 1); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m1), vget_low_u64(m2))); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m0), vget_low_u64(m1))); + r0 = vandq_u64(r0, x1); + changed = vorrq_u64(changed, r0); + + r0 = vshlq_n_u64(m2, 1); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m2), vget_low_u64(m3))); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m1), vget_low_u64(m2))); + r0 = vandq_u64(r0, x2); + changed = vorrq_u64(changed, r0); + + r0 = vshlq_n_u64(m3, 1); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m3), vcreate_u64(0))); + r0 = vorrq_u64(r0, vcombine_u64(vget_high_u64(m2), vget_low_u64(m3))); + r0 = vandq_u64(r0, x3); + changed = vorrq_u64(changed, r0); + + // Test if there is 1 bit in `changed` + return vgetq_lane_u64(changed, 0) | vgetq_lane_u64(changed, 1); +} + + + +PA_FORCE_INLINE void expand_forward( + const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, + uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 +){ + uint64x2_t s0 = vaddq_u64(x0, mask.m0); + uint64x2_t s1 = vaddq_u64(x1, mask.m1); + uint64x2_t s2 = vaddq_u64(x2, mask.m2); + uint64x2_t s3 = vaddq_u64(x3, mask.m3); + + s0 = vbicq_u64(mask.m0, s0); + s1 = vbicq_u64(mask.m1, s1); + s2 = vbicq_u64(mask.m2, s2); + s3 = vbicq_u64(mask.m3, s3); + + x0 = vorrq_u64(x0, s0); + x1 = vorrq_u64(x1, s1); + x2 = vorrq_u64(x2, s2); + x3 = vorrq_u64(x3, s3); +} +PA_FORCE_INLINE void expand_reverse(uint64x2_t m, uint64x2_t b, uint64x2_t& x){ + uint64x2_t s = bit_reverse(vaddq_u64(bit_reverse(x), b)); + s = veorq_u64(s, m); + s = vandq_u64(s, m); + x = vorrq_u64(x, s); +} +PA_FORCE_INLINE void expand_reverse( + const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, + uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 +){ + expand_reverse(mask.m0, mask.b0, x0); + expand_reverse(mask.m1, mask.b1, x1); + expand_reverse(mask.m2, mask.b2, x2); + expand_reverse(mask.m3, mask.b3, x3); +} +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x8_arm64_NEON_ProcessedMask& mask, + uint64x2_t& x0, uint64x2_t& x1, uint64x2_t& x2, uint64x2_t& x3 +){ + // Carry across adjacent rows. + transpose_u64_2x2_NEON(x0, x1); + transpose_u64_2x2_NEON(x2, x3); + x0 = vorrq_u64(x0, vandq_u64(x1, mask.t0)); + x1 = vorrq_u64(x1, vandq_u64(x0, mask.t1)); + x2 = vorrq_u64(x2, vandq_u64(x3, mask.t2)); + x3 = vorrq_u64(x3, vandq_u64(x2, mask.t3)); + transpose_u64_2x2_NEON(x0, x1); + transpose_u64_2x2_NEON(x2, x3); + + // Carry across groups of 2 rows. + uint64x1_t x0h = vget_high_u64(x0); + x1 = vorrq_u64(x1, vandq_u64(vcombine_u64(x0h, x0h), mask.f1)); + uint64x1_t x3l = vget_low_u64(x3); + x2 = vorrq_u64(x2, vandq_u64(vcombine_u64(x3l, x3l), mask.r2)); + uint64x1_t x1h = vget_high_u64(x1); + x2 = vorrq_u64(x2, vandq_u64(vcombine_u64(x1h, x1h), mask.f2)); + uint64x1_t x2l = vget_low_u64(x2); + x1 = vorrq_u64(x1, vandq_u64(vcombine_u64(x2l, x2l), mask.r1)); + uint64x1_t x2h = vget_high_u64(x2); + x3 = vorrq_u64(x3, vandq_u64(vcombine_u64(x2h, x2h), mask.f3)); + uint64x1_t x1l = vget_low_u64(x1); + x0 = vorrq_u64(x0, vandq_u64(vcombine_u64(x1l, x1l), mask.r0)); +} + + + +struct Waterfill_64x8_arm64_NEON{ + + + +// Do vector-wise logical OR among each SIMD vector +static PA_FORCE_INLINE uint64x2_t vec_or(const BinaryTile_64x8_arm64_NEON& tile){ + uint64x2_t v0 = vorrq_u64(tile.vec.val[0], tile.vec.val[1]); + uint64x2_t v1 = vorrq_u64(tile.vec.val[2], tile.vec.val[3]); + return vorrq_u64(v0, v1); +} +// Do a in-tile row-wise logical OR among each row +static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x8_arm64_NEON& tile){ + uint64x2_t v = vec_or(tile); + return vgetq_lane_u64(v, 0) | vgetq_lane_u64(v, 1); +} + + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x8_arm64_NEON& tile){ + // Check whether thera are any 1-bits in the tile: + uint64x2_t anything = vec_or(tile); + if ((vgetq_lane_u64(anything, 0) | vgetq_lane_u64(anything, 1)) == 0){ + return false; + } + // Check each tile row: + for (size_t r = 0; r < 8; r++){ + size_t pos; + if (trailing_zeros(pos, tile.row(r))){ + x = pos; + y = r; + return true; + } + } + return false; +} + + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const BinaryTile_64x8_arm64_NEON& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + min_y = 0; + for (size_t c = 0; c < 8; c++){ + if (tile.row(c) != 0){ + min_y = c; + break; + } + } + max_y = 0; + for (size_t c = 8; c > 0; c--){ + if (tile.row(c - 1) != 0){ + max_y = c; + break; + } + } +} + + + +// Compute the sum of the indices of 1 bits in `x` and store in `sum_index`, and compute +// counts of 1 bits (aka popcount) of `x` and return it as the function return. +// Note: `sum_index` is useful for computing center of gravity of bitmap objects. +// Example of index sum of a bitmap: +// 0b0001 is 0 +// 0b0100 is 2 +// 0b1010 is 1 + 3 = 4 +static PA_FORCE_INLINE uint64x2_t popcount_indexsum(uint64x2_t& sum_index, uint64x2_t x){ + // 1 -> 2 + // Get the bits in the original [0, 2, 4, 6, ...] bit positions by right shifting by one, then + // logical AND with 0b ... 0101 0101 + uint8x16_t pop_high = vandq_u8(vshrq_n_u8(vreinterpretq_u8_u64(x), 1), vdupq_n_u8(0x55)); + // Get the bits in the original [1, 3, 5, 7, ...] bit positions by logical AND with 0b ... 0101 0101 + uint8x16_t pop_low = vandq_u8(vreinterpretq_u8_u64(x), vdupq_n_u8(0x55)); + // Add them to get the bit-pair-wise addition + // Each nbring pair of bits is added in the pair and the result is stored in a 2-bit-wide space. + // The result can only be 0b00, 0b01 or 0b10 so it won't overflow the 2-bit storage. + // You can think `popcount` as storing the bit count of each 2-bit-wide space of the original bitmap + uint8x16_t popcount = vaddq_u8(pop_low, pop_high); + + uint8x16_t sum_high, sum_low; + // think `sumaxis` as containing the index sum of the bits of the 2-bit-wide space in the original bitmap, + // For each 2-bit wide space in the original bitmap: + // if it's 0b00, then index sum is 0 + // if it's 0b01, then index sum is 0 (the 1 is at 0-th index, so the index sum is still 0) + // if it's 0b10, then index sum is 1 + // if it's 0b11, then index sum is 1 + uint8x16_t sumxaxis = pop_high; + + // 2 -> 4 + // Right shift `sumxaxis` by 2, then logical AND with 0b ... 0011 0011 + // This means we get the 0b1100 part of `sumxaxis` into sum_high + sum_high = vandq_u8(vshrq_n_u8(sumxaxis, 2), vdupq_n_u8(0x33)); + // Right shift `popcount` by 2, then logical AND with 0b ... 0011 0011 + // This means we get the 0b1100 part of `popcount` into `pop_high` + pop_high = vandq_u8(vshrq_n_u8(popcount, 2), vdupq_n_u8(0x33)); + // logical AND of `sumxaxis` and 0b ... 0011 0011 + // This means we get the 0b0011 part of `sumxaxis` into `sum_low` + sum_low = vandq_u8(sumxaxis, vdupq_n_u8(0x33)); + // Add sum_low and sum_high together for each 4-bit-wide space + // Then add the count from `pop_high` shifted. + // You can think index sum is made by "lower part" of a 4-bit-wide space and "higher part" of the space. + // According to the physics reasoning that computes the combined center of gravity of a collection of objects, + // 4-bit index sum = 2-bit index sum of the lower part + 2-bit index sum of the higher part + // + bit count of the higher part * 2 + // `sumxaxis` value for each 4-bit-wide space ranges [0, 6] + sumxaxis = vaddq_u8(sum_low, sum_high); + sumxaxis = vaddq_u8(sumxaxis, vshlq_n_u8(pop_high, 1)); + + // Get the 0b0011 part of `popcount` into `pop_low` + pop_low = vandq_u8(popcount, vdupq_n_u8(0x33)); + // Add `pop_low` and `pop_high` together to count the bits in 4-bit-wide nbrhood in the original bitmap + // The max value possible is 4 (aka 0b0100), so won't overflow 4-bit-wide space + // You can think `popcount` as storing the bit count of each 4-bit-wide space of the original bitmap + // You can think `pop_low` is the bit count of the "lower part" (in this block of compuattion, the lower + // part of the 4-bit-wide space), while `pop_high` is the bit count of the "higher part". + // `popcount` value for each 4-bit-wide space ranges [0, 4] + popcount = vaddq_u8(pop_low, pop_high); + + // 4 -> 8 + // `sum_high`: higher part of the 8-bit-wide space in `sumxaxis` + sum_high = vandq_u8(vshrq_n_u8(sumxaxis, 4), vdupq_n_u8(0x0f)); + // `pip_high`: higher part of the 8-bit-wide space in `popcount` + pop_high = vandq_u8(vshrq_n_u8(popcount, 4), vdupq_n_u8(0x0f)); + // `sum_low`: lower part of the 8-bit-wide space in `sumxaxis` + sum_low = vandq_u8(sumxaxis, vdupq_n_u8(0x0f)); + // `sumxaxis`: index sum for each 8-bit-wide space, value range: [0, 28] + sumxaxis = vaddq_u8(sum_low, sum_high); + sumxaxis = vaddq_u8(sumxaxis, vshlq_n_u8(pop_high, 2)); + // `pop_low`: lower part of the 8-bit-wide space in `popcount` + pop_low = vandq_u8(popcount, vdupq_n_u8(0x0f)); + // `popcount` of the 8-bit-wide space, range [0, 8] + popcount = vaddq_u8(pop_low, pop_high); + + // 8 -> 16 + // Get higher part of 16-bit-wide space in `popcount` + uint16x8_t pop_high_u16x8 = vshrq_n_u16(vreinterpretq_u16_u8(popcount), 8); + // Get the index sum for each 16-bit-wise space + // vpadalq_u8(a, b): pair-wise add in `b`, then add to `a` + // index sum range: [0, 120] + uint16x8_t sumxaxis_u16x8 = vpadalq_u8(vshlq_n_u16(pop_high_u16x8, 3), sumxaxis); + // Get popcount of each 16-bit-wise space + // popcount value: [0, 16] + uint16x8_t popcount_u16x8 = vpaddlq_u8(popcount); + + // 16 -> 32 + uint32x4_t pop_high_u32x4 = vshrq_n_u32(vreinterpretq_u32_u16(popcount_u16x8), 16); + // Get the index sum for each 32-bit-wise space + // index sum range: [0, 496] + uint32x4_t sumxaxis_u32x4 = vpadalq_u16(vshlq_n_u32(pop_high_u32x4, 4), sumxaxis_u16x8); + // Get popcount of each 32-bit-wise space + // popcount value: [0, 32] + uint32x4_t popcount_u32x4 = vpaddlq_u16(popcount_u16x8); + + // 32 -> 64 + uint64x2_t pop_high_u64x2 = vshrq_n_u64(vreinterpretq_u64_u32(popcount_u32x4), 32); + // Get the index sum for each 64-bit-wise space + uint64x2_t sumxaxis_u64x2 = vpadalq_u32(vshlq_n_u64(pop_high_u64x2, 5), sumxaxis_u32x4); + // Get popcount of each 64-bit-wise space + uint64x2_t popcount_u64x2 = vpaddlq_u32(popcount_u32x4); + + // TODO: The above vpadxlq_uxx() operations are horizontal, may be slow. + // Can try to compare with SSE42 impl. + + sum_index = sumxaxis_u64x2; + return popcount_u64x2; +} + +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const BinaryTile_64x8_arm64_NEON& tile +){ + uint64x2_t sum_p, sum_x, sum_y; + { + uint64x2_t pop, sum; + pop = popcount_indexsum(sum, tile.vec.val[0]); + sum_p = pop; + sum_x = sum; + sum_y = vmull_u32(vmovn_u64(pop), uint32x2_t{0, 1}); + } + { + uint64x2_t pop, sum; + pop = popcount_indexsum(sum, tile.vec.val[1]); + sum_p = vaddq_u64(sum_p, pop); + sum_x = vaddq_u64(sum_x, sum); + sum_y = vaddq_u64(sum_y, vmull_u32(vmovn_u64(pop), uint32x2_t{2, 3})); + } + { + uint64x2_t pop, sum; + pop = popcount_indexsum(sum, tile.vec.val[2]); + sum_p = vaddq_u64(sum_p, pop); + sum_x = vaddq_u64(sum_x, sum); + sum_y = vaddq_u64(sum_y, vmull_u32(vmovn_u64(pop), uint32x2_t{4, 5})); + } + { + uint64x2_t pop, sum; + pop = popcount_indexsum(sum, tile.vec.val[3]); + sum_p = vaddq_u64(sum_p, pop); + sum_x = vaddq_u64(sum_x, sum); + sum_y = vaddq_u64(sum_y, vmull_u32(vmovn_u64(pop), uint32x2_t{6, 7})); + } + sum_xcoord = vgetq_lane_u64(sum_x, 0) + vgetq_lane_u64(sum_x, 1); + sum_ycoord = vgetq_lane_u64(sum_y, 0) + vgetq_lane_u64(sum_y, 1); + return vgetq_lane_u64(sum_p, 0) + vgetq_lane_u64(sum_p, 1); +} + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x8_arm64_NEON& m, BinaryTile_64x8_arm64_NEON& x){ + uint64x2_t x0 = x.vec.val[0]; + uint64x2_t x1 = x.vec.val[1]; + uint64x2_t x2 = x.vec.val[2]; + uint64x2_t x3 = x.vec.val[3]; + + Waterfill_64x8_arm64_NEON_ProcessedMask mask(m, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + + uint64x2_t m0, m1, m2, m3; + do{ + expand_vertical(mask, x0, x1, x2, x3); + expand_reverse(mask, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + }while (keep_going( + mask, + m0, m1, m2, m3, + x0, x1, x2, x3 + )); + x.vec.val[0] = x0; + x.vec.val[1] = x1; + x.vec.val[2] = x2; + x.vec.val[3] = x3; + m.vec.val[0] = m0; + m.vec.val[1] = m1; + m.vec.val[2] = m2; + m.vec.val[3] = m3; +} + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const BinaryTile_64x8_arm64_NEON& mask, + BinaryTile_64x8_arm64_NEON& tile, + const BinaryTile_64x8_arm64_NEON& border +){ + uint64_t available = mask.top() & ~tile.top(); + uint64_t new_bits = available & border.bottom(); + if (new_bits == 0){ + return false; + } + tile.top() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const BinaryTile_64x8_arm64_NEON& mask, + BinaryTile_64x8_arm64_NEON& tile, + const BinaryTile_64x8_arm64_NEON& border +){ + uint64_t available = mask.bottom() & ~tile.bottom(); + uint64_t new_bits = available & border.top(); + if (new_bits == 0){ + return false; + } + tile.bottom() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const BinaryTile_64x8_arm64_NEON& mask, + BinaryTile_64x8_arm64_NEON& tile, + const BinaryTile_64x8_arm64_NEON& border +){ + uint64x2_t changed = vreinterpretq_u64_u8(vdupq_n_u8(0)); + for (size_t c = 0; c < 4; c++){ + uint64x2_t available = vbicq_u64(mask.vec.val[c], tile.vec.val[c]); + uint64x2_t new_bits = vandq_u64(available, vshrq_n_u64(border.vec.val[c], 63)); + changed = vorrq_u64(changed, new_bits); + tile.vec.val[c] = vorrq_u64(tile.vec.val[c], new_bits); + } + // Test if there is 1 bit in `changed` + return vgetq_lane_u64(changed, 0) | vgetq_lane_u64(changed, 1); +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const BinaryTile_64x8_arm64_NEON& mask, + BinaryTile_64x8_arm64_NEON& tile, + const BinaryTile_64x8_arm64_NEON& border +){ + uint64x2_t changed = vreinterpretq_u64_u8(vdupq_n_u8(0)); + for (size_t c = 0; c < 4; c++){ + uint64x2_t available = vbicq_u64(mask.vec.val[c], tile.vec.val[c]); + uint64x2_t new_bits = vandq_u64(available, vshlq_n_u64(border.vec.val[c], 63)); + changed = vorrq_u64(changed, new_bits); + tile.vec.val[c] = vorrq_u64(tile.vec.val[c], new_bits); + } + // Test if there is 1 bit in `changed` + return vgetq_lane_u64(changed, 0) | vgetq_lane_u64(changed, 1); +} + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp index 255093c9fb..5eca307216 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.cpp @@ -1,47 +1,47 @@ -/* Waterfill Core (x64 SSE4.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_AutoDispatch_x64_08_Nehalem - -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64xH_Default.h" -#include "Kernels_Waterfill_Core_64x8_x64_SSE42.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::vector find_objects_inplace_64x8_x64_SSE42(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x8_x64_SSE42(PackedBinaryMatrix_IB* matrix){ -// cout << "make_WaterfillSession_64x8_x64_SSE42()" << endl; -#if 0 - return matrix == nullptr - ? std::make_unique>>() - : std::make_unique>>( - static_cast(matrix)->get() - ); -#else - return matrix == nullptr - ? std::make_unique>() - : std::make_unique>( - static_cast(matrix)->get() - ); -#endif -} - - - - -} -} -} -#endif +/* Waterfill Core (x64 SSE4.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_AutoDispatch_x64_08_Nehalem + +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64xH_Default.h" +#include "Kernels_Waterfill_Core_64x8_x64_SSE42.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::vector find_objects_inplace_64x8_x64_SSE42(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x8_x64_SSE42(PackedBinaryMatrix_IB* matrix){ +// cout << "make_WaterfillSession_64x8_x64_SSE42()" << endl; +#if 0 + return matrix == nullptr + ? std::make_unique>>() + : std::make_unique>>( + static_cast(matrix)->get() + ); +#else + return matrix == nullptr + ? std::make_unique>() + : std::make_unique>( + static_cast(matrix)->get() + ); +#endif +} + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h index a76f7f6f9f..05e12b388e 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h @@ -1,447 +1,447 @@ -/* Waterfill Core (x64 SSE4.1) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x8_x64_SSE41_H -#define PokemonAutomation_Kernels_Waterfill_Core_64x8_x64_SSE41_H - -#include "Kernels/Kernels_BitScan.h" -#include "Kernels/Kernels_x64_SSE41.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -PA_FORCE_INLINE __m128i bit_reverse(__m128i x){ - __m128i r0, r1; - - x = _mm_shuffle_epi8(x, _mm_setr_epi8(7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8)); - - r0 = _mm_srli_epi32(x, 4); - r1 = _mm_slli_epi32(x, 4); - r0 = _mm_and_si128(r0, _mm_set1_epi8((uint8_t)0x0f)); - r1 = _mm_and_si128(r1, _mm_set1_epi8((uint8_t)0xf0)); - r1 = _mm_or_si128(r0, r1); - - r0 = _mm_srli_epi32(r1, 2); - r1 = _mm_slli_epi32(r1, 2); - r0 = _mm_and_si128(r0, _mm_set1_epi8((uint8_t)0x33)); - r1 = _mm_and_si128(r1, _mm_set1_epi8((uint8_t)0xcc)); - r1 = _mm_or_si128(r0, r1); - - r0 = _mm_srli_epi32(r1, 1); - r1 = _mm_slli_epi32(r1, 1); - r0 = _mm_and_si128(r0, _mm_set1_epi8((uint8_t)0x55)); - r1 = _mm_and_si128(r1, _mm_set1_epi8((uint8_t)0xaa)); - r1 = _mm_or_si128(r0, r1); - - return r1; -} - - - -struct Waterfill_64x8_x64_SSE42_ProcessedMask{ - __m128i m0, m1, m2, m3; // Copy of the masks. - __m128i b0, b1, b2, b3; // Bit-reversed copy of the masks. - __m128i t0, t1, t2, t3; // Transposed masks. - __m128i f1, f2, f3; // Forward-carry mask. - __m128i r0, r1, r2; // Reverse-carry mask. - - PA_FORCE_INLINE Waterfill_64x8_x64_SSE42_ProcessedMask( - const BinaryTile_64x8_x64_SSE42& m, - __m128i x0, __m128i x1, __m128i x2, __m128i x3 - ){ - m0 = _mm_or_si128(x0, m.vec[0]); - m1 = _mm_or_si128(x1, m.vec[1]); - m2 = _mm_or_si128(x2, m.vec[2]); - m3 = _mm_or_si128(x3, m.vec[3]); - - b0 = bit_reverse(m0); - b1 = bit_reverse(m1); - b2 = bit_reverse(m2); - b3 = bit_reverse(m3); - - t0 = m0; - t1 = m1; - t2 = m2; - t3 = m3; - transpose_i64_2x2_SSE2(t0, t1); - transpose_i64_2x2_SSE2(t2, t3); - - // Forward carry - __m128i f0 = t0; - f1 = _mm_and_si128(f0, t1); - transpose_i64_2x2_SSE2(f0, f1); - f2 = t2; - f3 = _mm_and_si128(f2, t3); - transpose_i64_2x2_SSE2(f2, f3); - - // Reverse carry - __m128i r3 = t3; - r2 = _mm_and_si128(r3, t2); - transpose_i64_2x2_SSE2(r2, r3); - r1 = t1; - r0 = _mm_and_si128(r1, t0); - transpose_i64_2x2_SSE2(r0, r1); - } -}; - - - -PA_FORCE_INLINE bool keep_going( - const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, - __m128i& m0, __m128i& m1, __m128i& m2, __m128i& m3, - __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 -){ - m0 = _mm_andnot_si128(x0, mask.m0); - m1 = _mm_andnot_si128(x1, mask.m1); - m2 = _mm_andnot_si128(x2, mask.m2); - m3 = _mm_andnot_si128(x3, mask.m3); - - __m128i r0; - - r0 = _mm_slli_epi64(m0, 1); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m0), _mm_castsi128_pd(m1), 1))); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_setzero_pd(), _mm_castsi128_pd(m0), 1))); - __m128i changed = _mm_and_si128(r0, x0); - - r0 = _mm_slli_epi64(m1, 1); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m1), _mm_castsi128_pd(m2), 1))); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m0), _mm_castsi128_pd(m1), 1))); - r0 = _mm_and_si128(r0, x1); - changed = _mm_or_si128(changed, r0); - - r0 = _mm_slli_epi64(m2, 1); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m2), _mm_castsi128_pd(m3), 1))); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m1), _mm_castsi128_pd(m2), 1))); - r0 = _mm_and_si128(r0, x2); - changed = _mm_or_si128(changed, r0); - - r0 = _mm_slli_epi64(m3, 1); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m3), _mm_setzero_pd(), 1))); - r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m2), _mm_castsi128_pd(m3), 1))); - r0 = _mm_and_si128(r0, x3); - changed = _mm_or_si128(changed, r0); - - return !_mm_test_all_zeros(changed, changed); -} - - - -PA_FORCE_INLINE void expand_forward( - const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, - __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 -){ - __m128i s0 = _mm_add_epi64(x0, mask.m0); - __m128i s1 = _mm_add_epi64(x1, mask.m1); - __m128i s2 = _mm_add_epi64(x2, mask.m2); - __m128i s3 = _mm_add_epi64(x3, mask.m3); - - s0 = _mm_andnot_si128(s0, mask.m0); - s1 = _mm_andnot_si128(s1, mask.m1); - s2 = _mm_andnot_si128(s2, mask.m2); - s3 = _mm_andnot_si128(s3, mask.m3); - - x0 = _mm_or_si128(x0, s0); - x1 = _mm_or_si128(x1, s1); - x2 = _mm_or_si128(x2, s2); - x3 = _mm_or_si128(x3, s3); -} -PA_FORCE_INLINE void expand_reverse(__m128i m, __m128i b, __m128i& x){ - __m128i s = bit_reverse(_mm_add_epi64(bit_reverse(x), b)); - s = _mm_xor_si128(s, m); - s = _mm_and_si128(s, m); - x = _mm_or_si128(x, s); -} -PA_FORCE_INLINE void expand_reverse( - const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, - __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 -){ - expand_reverse(mask.m0, mask.b0, x0); - expand_reverse(mask.m1, mask.b1, x1); - expand_reverse(mask.m2, mask.b2, x2); - expand_reverse(mask.m3, mask.b3, x3); -} -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, - __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 -){ - // Carry across adjacent rows. - transpose_i64_2x2_SSE2(x0, x1); - transpose_i64_2x2_SSE2(x2, x3); - x0 = _mm_or_si128(x0, _mm_and_si128(x1, mask.t0)); - x1 = _mm_or_si128(x1, _mm_and_si128(x0, mask.t1)); - x2 = _mm_or_si128(x2, _mm_and_si128(x3, mask.t2)); - x3 = _mm_or_si128(x3, _mm_and_si128(x2, mask.t3)); - transpose_i64_2x2_SSE2(x0, x1); - transpose_i64_2x2_SSE2(x2, x3); - - // Carry across groups of 2 rows. - x1 = _mm_or_si128(x1, _mm_and_si128(_mm_unpackhi_epi64(x0, x0), mask.f1)); - x2 = _mm_or_si128(x2, _mm_and_si128(_mm_unpacklo_epi64(x3, x3), mask.r2)); - x2 = _mm_or_si128(x2, _mm_and_si128(_mm_unpackhi_epi64(x1, x1), mask.f2)); - x1 = _mm_or_si128(x1, _mm_and_si128(_mm_unpacklo_epi64(x2, x2), mask.r1)); - x3 = _mm_or_si128(x3, _mm_and_si128(_mm_unpackhi_epi64(x2, x2), mask.f3)); - x0 = _mm_or_si128(x0, _mm_and_si128(_mm_unpacklo_epi64(x1, x1), mask.r0)); -} - - - -struct Waterfill_64x8_x64_SSE42{ - - - -static PA_FORCE_INLINE __m128i vec_or(const BinaryTile_64x8_x64_SSE42& tile){ - __m128i v0 = _mm_or_si128(tile.vec[0], tile.vec[1]); - __m128i v1 = _mm_or_si128(tile.vec[2], tile.vec[3]); - v0 = _mm_or_si128(v0, v1); - return v0; -} -static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x8_x64_SSE42& tile){ - __m128i v = vec_or(tile); - return _mm_cvtsi128_si64(v) | _mm_extract_epi64(v, 1); -} - - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x8_x64_SSE42& tile){ - __m128i anything = vec_or(tile); - if (_mm_test_all_zeros(anything, anything)){ - return false; - } - for (size_t c = 0; c < 8; c++){ - size_t pos; - if (trailing_zeros(pos, tile.row(c))){ - x = pos; - y = c; - return true; - } - } - return false; -} - - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const BinaryTile_64x8_x64_SSE42& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - min_y = 0; - for (size_t c = 0; c < 8; c++){ - if (tile.row(c) != 0){ - min_y = c; - break; - } - } - max_y = 0; - for (size_t c = 8; c > 0; c--){ - if (tile.row(c - 1) != 0){ - max_y = c; - break; - } - } -} - - - -// Area + Center of Gravity: -// Compute the sum of the index of each set bit. -// Returns the popcount. -static PA_FORCE_INLINE __m128i popcount_indexsum(__m128i& sum_index, __m128i x){ - // 1 -> 2 - __m128i sum_high; - __m128i pop_high = _mm_and_si128(_mm_srli_epi16(x, 1), _mm_set1_epi8(0x55)); - __m128i sumxaxis = pop_high; - __m128i popcount = _mm_add_epi8(_mm_and_si128(x, _mm_set1_epi8(0x55)), pop_high); - - // 2 -> 4 - sum_high = _mm_and_si128(_mm_srli_epi16(sumxaxis, 2), _mm_set1_epi8(0x33)); - pop_high = _mm_and_si128(_mm_srli_epi16(popcount, 2), _mm_set1_epi8(0x33)); - sumxaxis = _mm_add_epi8(_mm_and_si128(sumxaxis, _mm_set1_epi8(0x33)), sum_high); - sumxaxis = _mm_add_epi8(sumxaxis, _mm_slli_epi16(pop_high, 1)); - popcount = _mm_add_epi8(_mm_and_si128(popcount, _mm_set1_epi8(0x33)), pop_high); - - // 4 -> 8 - sum_high = _mm_and_si128(_mm_srli_epi16(sumxaxis, 4), _mm_set1_epi8(0x0f)); - pop_high = _mm_and_si128(_mm_srli_epi16(popcount, 4), _mm_set1_epi8(0x0f)); - sumxaxis = _mm_add_epi8(_mm_and_si128(sumxaxis, _mm_set1_epi8(0x0f)), sum_high); - sumxaxis = _mm_add_epi8(sumxaxis, _mm_slli_epi16(pop_high, 2)); - popcount = _mm_add_epi8(_mm_and_si128(popcount, _mm_set1_epi8(0x0f)), pop_high); - - // 8 -> 16 - sum_high = _mm_srli_epi16(sumxaxis, 8); - pop_high = _mm_srli_epi16(popcount, 8); - sumxaxis = _mm_add_epi16(_mm_and_si128(sumxaxis, _mm_set1_epi16(0x00ff)), sum_high); - sumxaxis = _mm_add_epi16(sumxaxis, _mm_slli_epi16(pop_high, 3)); - popcount = _mm_add_epi16(_mm_and_si128(popcount, _mm_set1_epi16(0x00ff)), pop_high); - - // 16 -> 32 - sum_high = _mm_srli_epi32(sumxaxis, 16); - pop_high = _mm_srli_epi32(popcount, 16); - sumxaxis = _mm_add_epi32(sumxaxis, sum_high); - sumxaxis = _mm_add_epi32(sumxaxis, _mm_slli_epi32(pop_high, 4)); - popcount = _mm_add_epi32(popcount, pop_high); - - // 32 -> 64 - sum_high = _mm_srli_epi64(sumxaxis, 32); - pop_high = _mm_srli_epi64(popcount, 32); - sumxaxis = _mm_add_epi64(sumxaxis, sum_high); - sumxaxis = _mm_add_epi64(sumxaxis, _mm_slli_epi64(pop_high, 5)); - popcount = _mm_add_epi64(popcount, pop_high); - - sum_index = _mm_and_si128(sumxaxis, _mm_set1_epi64x(0x000000000000ffff)); - return _mm_and_si128(popcount, _mm_set1_epi64x(0x000000000000ffff)); -} -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const BinaryTile_64x8_x64_SSE42& tile -){ - __m128i sum_p, sum_x, sum_y; - { - __m128i pop, sum; - pop = popcount_indexsum(sum, tile.vec[0]); - sum_p = pop; - sum_x = sum; - sum_y = _mm_mul_epu32(pop, _mm_set_epi64x(1, 0)); - } - { - __m128i pop, sum; - pop = popcount_indexsum(sum, tile.vec[1]); - sum_p = _mm_add_epi64(sum_p, pop); - sum_x = _mm_add_epi64(sum_x, sum); - sum_y = _mm_add_epi64(sum_y, _mm_mul_epu32(pop, _mm_set_epi64x(3, 2))); - } - { - __m128i pop, sum; - pop = popcount_indexsum(sum, tile.vec[2]); - sum_p = _mm_add_epi64(sum_p, pop); - sum_x = _mm_add_epi64(sum_x, sum); - sum_y = _mm_add_epi64(sum_y, _mm_mul_epu32(pop, _mm_set_epi64x(5, 4))); - } - { - __m128i pop, sum; - pop = popcount_indexsum(sum, tile.vec[3]); - sum_p = _mm_add_epi64(sum_p, pop); - sum_x = _mm_add_epi64(sum_x, sum); - sum_y = _mm_add_epi64(sum_y, _mm_mul_epu32(pop, _mm_set_epi64x(7, 6))); - } - sum_xcoord = _mm_cvtsi128_si64(sum_x) + _mm_extract_epi64(sum_x, 1); - sum_ycoord = _mm_cvtsi128_si64(sum_y) + _mm_extract_epi64(sum_y, 1); - return _mm_cvtsi128_si64(sum_p) + _mm_extract_epi64(sum_p, 1); -} - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x8_x64_SSE42& m, BinaryTile_64x8_x64_SSE42& x){ - __m128i x0 = x.vec[0]; - __m128i x1 = x.vec[1]; - __m128i x2 = x.vec[2]; - __m128i x3 = x.vec[3]; - - Waterfill_64x8_x64_SSE42_ProcessedMask mask(m, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - - __m128i m0, m1, m2, m3; - do{ - expand_vertical(mask, x0, x1, x2, x3); - expand_reverse(mask, x0, x1, x2, x3); - expand_forward(mask, x0, x1, x2, x3); - }while (keep_going( - mask, - m0, m1, m2, m3, - x0, x1, x2, x3 - )); - x.vec[0] = x0; - x.vec[1] = x1; - x.vec[2] = x2; - x.vec[3] = x3; - m.vec[0] = m0; - m.vec[1] = m1; - m.vec[2] = m2; - m.vec[3] = m3; -} - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const BinaryTile_64x8_x64_SSE42& mask, - BinaryTile_64x8_x64_SSE42& tile, - const BinaryTile_64x8_x64_SSE42& border -){ - uint64_t available = mask.top() & ~tile.top(); - uint64_t new_bits = available & border.bottom(); - if (new_bits == 0){ - return false; - } - tile.top() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const BinaryTile_64x8_x64_SSE42& mask, - BinaryTile_64x8_x64_SSE42& tile, - const BinaryTile_64x8_x64_SSE42& border -){ - uint64_t available = mask.bottom() & ~tile.bottom(); - uint64_t new_bits = available & border.top(); - if (new_bits == 0){ - return false; - } - tile.bottom() |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const BinaryTile_64x8_x64_SSE42& mask, - BinaryTile_64x8_x64_SSE42& tile, - const BinaryTile_64x8_x64_SSE42& border -){ - __m128i changed = _mm_setzero_si128(); - for (size_t c = 0; c < 4; c++){ - __m128i available = _mm_andnot_si128(tile.vec[c], mask.vec[c]); - __m128i new_bits = _mm_and_si128(available, _mm_srli_epi64(border.vec[c], 63)); - changed = _mm_or_si128(changed, new_bits); - tile.vec[c] = _mm_or_si128(tile.vec[c], new_bits); - } - return !_mm_test_all_zeros(changed, changed); -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const BinaryTile_64x8_x64_SSE42& mask, - BinaryTile_64x8_x64_SSE42& tile, - const BinaryTile_64x8_x64_SSE42& border -){ - __m128i changed = _mm_setzero_si128(); - for (size_t c = 0; c < 4; c++){ - __m128i available = _mm_andnot_si128(tile.vec[c], mask.vec[c]); - __m128i new_bits = _mm_and_si128(available, _mm_slli_epi64(border.vec[c], 63)); - changed = _mm_or_si128(changed, new_bits); - tile.vec[c] = _mm_or_si128(tile.vec[c], new_bits); - } - return !_mm_test_all_zeros(changed, changed); -} - - -}; - - - -} -} -} -#endif +/* Waterfill Core (x64 SSE4.1) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64x8_x64_SSE41_H +#define PokemonAutomation_Kernels_Waterfill_Core_64x8_x64_SSE41_H + +#include "Kernels/Kernels_BitScan.h" +#include "Kernels/Kernels_x64_SSE41.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64x8_x64_SSE42.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +PA_FORCE_INLINE __m128i bit_reverse(__m128i x){ + __m128i r0, r1; + + x = _mm_shuffle_epi8(x, _mm_setr_epi8(7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8)); + + r0 = _mm_srli_epi32(x, 4); + r1 = _mm_slli_epi32(x, 4); + r0 = _mm_and_si128(r0, _mm_set1_epi8((uint8_t)0x0f)); + r1 = _mm_and_si128(r1, _mm_set1_epi8((uint8_t)0xf0)); + r1 = _mm_or_si128(r0, r1); + + r0 = _mm_srli_epi32(r1, 2); + r1 = _mm_slli_epi32(r1, 2); + r0 = _mm_and_si128(r0, _mm_set1_epi8((uint8_t)0x33)); + r1 = _mm_and_si128(r1, _mm_set1_epi8((uint8_t)0xcc)); + r1 = _mm_or_si128(r0, r1); + + r0 = _mm_srli_epi32(r1, 1); + r1 = _mm_slli_epi32(r1, 1); + r0 = _mm_and_si128(r0, _mm_set1_epi8((uint8_t)0x55)); + r1 = _mm_and_si128(r1, _mm_set1_epi8((uint8_t)0xaa)); + r1 = _mm_or_si128(r0, r1); + + return r1; +} + + + +struct Waterfill_64x8_x64_SSE42_ProcessedMask{ + __m128i m0, m1, m2, m3; // Copy of the masks. + __m128i b0, b1, b2, b3; // Bit-reversed copy of the masks. + __m128i t0, t1, t2, t3; // Transposed masks. + __m128i f1, f2, f3; // Forward-carry mask. + __m128i r0, r1, r2; // Reverse-carry mask. + + PA_FORCE_INLINE Waterfill_64x8_x64_SSE42_ProcessedMask( + const BinaryTile_64x8_x64_SSE42& m, + __m128i x0, __m128i x1, __m128i x2, __m128i x3 + ){ + m0 = _mm_or_si128(x0, m.vec[0]); + m1 = _mm_or_si128(x1, m.vec[1]); + m2 = _mm_or_si128(x2, m.vec[2]); + m3 = _mm_or_si128(x3, m.vec[3]); + + b0 = bit_reverse(m0); + b1 = bit_reverse(m1); + b2 = bit_reverse(m2); + b3 = bit_reverse(m3); + + t0 = m0; + t1 = m1; + t2 = m2; + t3 = m3; + transpose_i64_2x2_SSE2(t0, t1); + transpose_i64_2x2_SSE2(t2, t3); + + // Forward carry + __m128i f0 = t0; + f1 = _mm_and_si128(f0, t1); + transpose_i64_2x2_SSE2(f0, f1); + f2 = t2; + f3 = _mm_and_si128(f2, t3); + transpose_i64_2x2_SSE2(f2, f3); + + // Reverse carry + __m128i r3 = t3; + r2 = _mm_and_si128(r3, t2); + transpose_i64_2x2_SSE2(r2, r3); + r1 = t1; + r0 = _mm_and_si128(r1, t0); + transpose_i64_2x2_SSE2(r0, r1); + } +}; + + + +PA_FORCE_INLINE bool keep_going( + const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, + __m128i& m0, __m128i& m1, __m128i& m2, __m128i& m3, + __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 +){ + m0 = _mm_andnot_si128(x0, mask.m0); + m1 = _mm_andnot_si128(x1, mask.m1); + m2 = _mm_andnot_si128(x2, mask.m2); + m3 = _mm_andnot_si128(x3, mask.m3); + + __m128i r0; + + r0 = _mm_slli_epi64(m0, 1); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m0), _mm_castsi128_pd(m1), 1))); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_setzero_pd(), _mm_castsi128_pd(m0), 1))); + __m128i changed = _mm_and_si128(r0, x0); + + r0 = _mm_slli_epi64(m1, 1); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m1), _mm_castsi128_pd(m2), 1))); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m0), _mm_castsi128_pd(m1), 1))); + r0 = _mm_and_si128(r0, x1); + changed = _mm_or_si128(changed, r0); + + r0 = _mm_slli_epi64(m2, 1); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m2), _mm_castsi128_pd(m3), 1))); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m1), _mm_castsi128_pd(m2), 1))); + r0 = _mm_and_si128(r0, x2); + changed = _mm_or_si128(changed, r0); + + r0 = _mm_slli_epi64(m3, 1); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m3), _mm_setzero_pd(), 1))); + r0 = _mm_or_si128(r0, _mm_castpd_si128(_mm_shuffle_pd(_mm_castsi128_pd(m2), _mm_castsi128_pd(m3), 1))); + r0 = _mm_and_si128(r0, x3); + changed = _mm_or_si128(changed, r0); + + return !_mm_test_all_zeros(changed, changed); +} + + + +PA_FORCE_INLINE void expand_forward( + const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, + __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 +){ + __m128i s0 = _mm_add_epi64(x0, mask.m0); + __m128i s1 = _mm_add_epi64(x1, mask.m1); + __m128i s2 = _mm_add_epi64(x2, mask.m2); + __m128i s3 = _mm_add_epi64(x3, mask.m3); + + s0 = _mm_andnot_si128(s0, mask.m0); + s1 = _mm_andnot_si128(s1, mask.m1); + s2 = _mm_andnot_si128(s2, mask.m2); + s3 = _mm_andnot_si128(s3, mask.m3); + + x0 = _mm_or_si128(x0, s0); + x1 = _mm_or_si128(x1, s1); + x2 = _mm_or_si128(x2, s2); + x3 = _mm_or_si128(x3, s3); +} +PA_FORCE_INLINE void expand_reverse(__m128i m, __m128i b, __m128i& x){ + __m128i s = bit_reverse(_mm_add_epi64(bit_reverse(x), b)); + s = _mm_xor_si128(s, m); + s = _mm_and_si128(s, m); + x = _mm_or_si128(x, s); +} +PA_FORCE_INLINE void expand_reverse( + const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, + __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 +){ + expand_reverse(mask.m0, mask.b0, x0); + expand_reverse(mask.m1, mask.b1, x1); + expand_reverse(mask.m2, mask.b2, x2); + expand_reverse(mask.m3, mask.b3, x3); +} +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64x8_x64_SSE42_ProcessedMask& mask, + __m128i& x0, __m128i& x1, __m128i& x2, __m128i& x3 +){ + // Carry across adjacent rows. + transpose_i64_2x2_SSE2(x0, x1); + transpose_i64_2x2_SSE2(x2, x3); + x0 = _mm_or_si128(x0, _mm_and_si128(x1, mask.t0)); + x1 = _mm_or_si128(x1, _mm_and_si128(x0, mask.t1)); + x2 = _mm_or_si128(x2, _mm_and_si128(x3, mask.t2)); + x3 = _mm_or_si128(x3, _mm_and_si128(x2, mask.t3)); + transpose_i64_2x2_SSE2(x0, x1); + transpose_i64_2x2_SSE2(x2, x3); + + // Carry across groups of 2 rows. + x1 = _mm_or_si128(x1, _mm_and_si128(_mm_unpackhi_epi64(x0, x0), mask.f1)); + x2 = _mm_or_si128(x2, _mm_and_si128(_mm_unpacklo_epi64(x3, x3), mask.r2)); + x2 = _mm_or_si128(x2, _mm_and_si128(_mm_unpackhi_epi64(x1, x1), mask.f2)); + x1 = _mm_or_si128(x1, _mm_and_si128(_mm_unpacklo_epi64(x2, x2), mask.r1)); + x3 = _mm_or_si128(x3, _mm_and_si128(_mm_unpackhi_epi64(x2, x2), mask.f3)); + x0 = _mm_or_si128(x0, _mm_and_si128(_mm_unpacklo_epi64(x1, x1), mask.r0)); +} + + + +struct Waterfill_64x8_x64_SSE42{ + + + +static PA_FORCE_INLINE __m128i vec_or(const BinaryTile_64x8_x64_SSE42& tile){ + __m128i v0 = _mm_or_si128(tile.vec[0], tile.vec[1]); + __m128i v1 = _mm_or_si128(tile.vec[2], tile.vec[3]); + v0 = _mm_or_si128(v0, v1); + return v0; +} +static PA_FORCE_INLINE uint64_t row_or(const BinaryTile_64x8_x64_SSE42& tile){ + __m128i v = vec_or(tile); + return _mm_cvtsi128_si64(v) | _mm_extract_epi64(v, 1); +} + + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const BinaryTile_64x8_x64_SSE42& tile){ + __m128i anything = vec_or(tile); + if (_mm_test_all_zeros(anything, anything)){ + return false; + } + for (size_t c = 0; c < 8; c++){ + size_t pos; + if (trailing_zeros(pos, tile.row(c))){ + x = pos; + y = c; + return true; + } + } + return false; +} + + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const BinaryTile_64x8_x64_SSE42& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + min_y = 0; + for (size_t c = 0; c < 8; c++){ + if (tile.row(c) != 0){ + min_y = c; + break; + } + } + max_y = 0; + for (size_t c = 8; c > 0; c--){ + if (tile.row(c - 1) != 0){ + max_y = c; + break; + } + } +} + + + +// Area + Center of Gravity: +// Compute the sum of the index of each set bit. +// Returns the popcount. +static PA_FORCE_INLINE __m128i popcount_indexsum(__m128i& sum_index, __m128i x){ + // 1 -> 2 + __m128i sum_high; + __m128i pop_high = _mm_and_si128(_mm_srli_epi16(x, 1), _mm_set1_epi8(0x55)); + __m128i sumxaxis = pop_high; + __m128i popcount = _mm_add_epi8(_mm_and_si128(x, _mm_set1_epi8(0x55)), pop_high); + + // 2 -> 4 + sum_high = _mm_and_si128(_mm_srli_epi16(sumxaxis, 2), _mm_set1_epi8(0x33)); + pop_high = _mm_and_si128(_mm_srli_epi16(popcount, 2), _mm_set1_epi8(0x33)); + sumxaxis = _mm_add_epi8(_mm_and_si128(sumxaxis, _mm_set1_epi8(0x33)), sum_high); + sumxaxis = _mm_add_epi8(sumxaxis, _mm_slli_epi16(pop_high, 1)); + popcount = _mm_add_epi8(_mm_and_si128(popcount, _mm_set1_epi8(0x33)), pop_high); + + // 4 -> 8 + sum_high = _mm_and_si128(_mm_srli_epi16(sumxaxis, 4), _mm_set1_epi8(0x0f)); + pop_high = _mm_and_si128(_mm_srli_epi16(popcount, 4), _mm_set1_epi8(0x0f)); + sumxaxis = _mm_add_epi8(_mm_and_si128(sumxaxis, _mm_set1_epi8(0x0f)), sum_high); + sumxaxis = _mm_add_epi8(sumxaxis, _mm_slli_epi16(pop_high, 2)); + popcount = _mm_add_epi8(_mm_and_si128(popcount, _mm_set1_epi8(0x0f)), pop_high); + + // 8 -> 16 + sum_high = _mm_srli_epi16(sumxaxis, 8); + pop_high = _mm_srli_epi16(popcount, 8); + sumxaxis = _mm_add_epi16(_mm_and_si128(sumxaxis, _mm_set1_epi16(0x00ff)), sum_high); + sumxaxis = _mm_add_epi16(sumxaxis, _mm_slli_epi16(pop_high, 3)); + popcount = _mm_add_epi16(_mm_and_si128(popcount, _mm_set1_epi16(0x00ff)), pop_high); + + // 16 -> 32 + sum_high = _mm_srli_epi32(sumxaxis, 16); + pop_high = _mm_srli_epi32(popcount, 16); + sumxaxis = _mm_add_epi32(sumxaxis, sum_high); + sumxaxis = _mm_add_epi32(sumxaxis, _mm_slli_epi32(pop_high, 4)); + popcount = _mm_add_epi32(popcount, pop_high); + + // 32 -> 64 + sum_high = _mm_srli_epi64(sumxaxis, 32); + pop_high = _mm_srli_epi64(popcount, 32); + sumxaxis = _mm_add_epi64(sumxaxis, sum_high); + sumxaxis = _mm_add_epi64(sumxaxis, _mm_slli_epi64(pop_high, 5)); + popcount = _mm_add_epi64(popcount, pop_high); + + sum_index = _mm_and_si128(sumxaxis, _mm_set1_epi64x(0x000000000000ffff)); + return _mm_and_si128(popcount, _mm_set1_epi64x(0x000000000000ffff)); +} +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const BinaryTile_64x8_x64_SSE42& tile +){ + __m128i sum_p, sum_x, sum_y; + { + __m128i pop, sum; + pop = popcount_indexsum(sum, tile.vec[0]); + sum_p = pop; + sum_x = sum; + sum_y = _mm_mul_epu32(pop, _mm_set_epi64x(1, 0)); + } + { + __m128i pop, sum; + pop = popcount_indexsum(sum, tile.vec[1]); + sum_p = _mm_add_epi64(sum_p, pop); + sum_x = _mm_add_epi64(sum_x, sum); + sum_y = _mm_add_epi64(sum_y, _mm_mul_epu32(pop, _mm_set_epi64x(3, 2))); + } + { + __m128i pop, sum; + pop = popcount_indexsum(sum, tile.vec[2]); + sum_p = _mm_add_epi64(sum_p, pop); + sum_x = _mm_add_epi64(sum_x, sum); + sum_y = _mm_add_epi64(sum_y, _mm_mul_epu32(pop, _mm_set_epi64x(5, 4))); + } + { + __m128i pop, sum; + pop = popcount_indexsum(sum, tile.vec[3]); + sum_p = _mm_add_epi64(sum_p, pop); + sum_x = _mm_add_epi64(sum_x, sum); + sum_y = _mm_add_epi64(sum_y, _mm_mul_epu32(pop, _mm_set_epi64x(7, 6))); + } + sum_xcoord = _mm_cvtsi128_si64(sum_x) + _mm_extract_epi64(sum_x, 1); + sum_ycoord = _mm_cvtsi128_si64(sum_y) + _mm_extract_epi64(sum_y, 1); + return _mm_cvtsi128_si64(sum_p) + _mm_extract_epi64(sum_p, 1); +} + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +static PA_FORCE_INLINE void waterfill_expand(BinaryTile_64x8_x64_SSE42& m, BinaryTile_64x8_x64_SSE42& x){ + __m128i x0 = x.vec[0]; + __m128i x1 = x.vec[1]; + __m128i x2 = x.vec[2]; + __m128i x3 = x.vec[3]; + + Waterfill_64x8_x64_SSE42_ProcessedMask mask(m, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + + __m128i m0, m1, m2, m3; + do{ + expand_vertical(mask, x0, x1, x2, x3); + expand_reverse(mask, x0, x1, x2, x3); + expand_forward(mask, x0, x1, x2, x3); + }while (keep_going( + mask, + m0, m1, m2, m3, + x0, x1, x2, x3 + )); + x.vec[0] = x0; + x.vec[1] = x1; + x.vec[2] = x2; + x.vec[3] = x3; + m.vec[0] = m0; + m.vec[1] = m1; + m.vec[2] = m2; + m.vec[3] = m3; +} + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const BinaryTile_64x8_x64_SSE42& mask, + BinaryTile_64x8_x64_SSE42& tile, + const BinaryTile_64x8_x64_SSE42& border +){ + uint64_t available = mask.top() & ~tile.top(); + uint64_t new_bits = available & border.bottom(); + if (new_bits == 0){ + return false; + } + tile.top() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const BinaryTile_64x8_x64_SSE42& mask, + BinaryTile_64x8_x64_SSE42& tile, + const BinaryTile_64x8_x64_SSE42& border +){ + uint64_t available = mask.bottom() & ~tile.bottom(); + uint64_t new_bits = available & border.top(); + if (new_bits == 0){ + return false; + } + tile.bottom() |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const BinaryTile_64x8_x64_SSE42& mask, + BinaryTile_64x8_x64_SSE42& tile, + const BinaryTile_64x8_x64_SSE42& border +){ + __m128i changed = _mm_setzero_si128(); + for (size_t c = 0; c < 4; c++){ + __m128i available = _mm_andnot_si128(tile.vec[c], mask.vec[c]); + __m128i new_bits = _mm_and_si128(available, _mm_srli_epi64(border.vec[c], 63)); + changed = _mm_or_si128(changed, new_bits); + tile.vec[c] = _mm_or_si128(tile.vec[c], new_bits); + } + return !_mm_test_all_zeros(changed, changed); +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const BinaryTile_64x8_x64_SSE42& mask, + BinaryTile_64x8_x64_SSE42& tile, + const BinaryTile_64x8_x64_SSE42& border +){ + __m128i changed = _mm_setzero_si128(); + for (size_t c = 0; c < 4; c++){ + __m128i available = _mm_andnot_si128(tile.vec[c], mask.vec[c]); + __m128i new_bits = _mm_and_si128(available, _mm_slli_epi64(border.vec[c], 63)); + changed = _mm_or_si128(changed, new_bits); + tile.vec[c] = _mm_or_si128(tile.vec[c], new_bits); + } + return !_mm_test_all_zeros(changed, changed); +} + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.cpp index 5671b8bf79..5bd4a94a71 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.cpp @@ -1,56 +1,56 @@ -/* Waterfill Core (64-bit integer) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h" -#include "Kernels_Waterfill_Session.tpp" -#include "Kernels_Waterfill_Routines.h" -#include "Kernels_Waterfill_Core_64x4_Default.h" -#include "Kernels_Waterfill_Core_64xH_Default.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - - - -std::vector find_objects_inplace_64x4_Default(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace>( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x4_Default(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>>() - : std::make_unique>>( - static_cast(matrix)->get() - ); -} - -std::vector find_objects_inplace_64x8_Default(PackedBinaryMatrix_IB& matrix, size_t min_area){ - return find_objects_inplace>( - static_cast(matrix).get(), - min_area - ); -} -std::unique_ptr make_WaterfillSession_64x8_Default(PackedBinaryMatrix_IB* matrix){ - return matrix == nullptr - ? std::make_unique>>() - : std::make_unique>>( - static_cast(matrix)->get() - ); -} - - - - - - - -} -} -} +/* Waterfill Core (64-bit integer) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h" +#include "Kernels_Waterfill_Session.tpp" +#include "Kernels_Waterfill_Routines.h" +#include "Kernels_Waterfill_Core_64x4_Default.h" +#include "Kernels_Waterfill_Core_64xH_Default.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + + + +std::vector find_objects_inplace_64x4_Default(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace>( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x4_Default(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>>() + : std::make_unique>>( + static_cast(matrix)->get() + ); +} + +std::vector find_objects_inplace_64x8_Default(PackedBinaryMatrix_IB& matrix, size_t min_area){ + return find_objects_inplace>( + static_cast(matrix).get(), + min_area + ); +} +std::unique_ptr make_WaterfillSession_64x8_Default(PackedBinaryMatrix_IB* matrix){ + return matrix == nullptr + ? std::make_unique>>() + : std::make_unique>>( + static_cast(matrix)->get() + ); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h index ef93bf7cb2..6c640ae115 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h @@ -1,373 +1,373 @@ -/* Waterfill Core (Default) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Core_64xH_Default_H -#define PokemonAutomation_Kernels_Waterfill_Core_64xH_Default_H - -#include "Kernels/Kernels_BitScan.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -PA_FORCE_INLINE uint64_t bitreverse64(uint64_t x){ - uint64_t r0, r1; - -#if 0 -#elif __GNUC__ - r0 = __builtin_bswap64(x); -#elif __INTEL_COMPILER - r0 = _bswap64(x); -#elif _MSC_VER - r0 = _byteswap_uint64(x); -#else -#error "No byte-swap for this compiler." -#endif - - r1 = r0 >> 4; - r0 = r0 << 4; - r1 &= 0x0f0f0f0f0f0f0f0full; - r0 &= 0xf0f0f0f0f0f0f0f0ull; - r0 |= r1; - - r1 = r0 >> 2; - r0 = r0 << 2; - r1 &= 0x3333333333333333ull; - r0 &= 0xccccccccccccccccull; - r0 |= r1; - - r1 = r0 >> 1; - r0 = r0 << 1; - r1 &= 0x5555555555555555ull; - r0 &= 0xaaaaaaaaaaaaaaaaull; - r0 |= r1; - - return r0; -} - - - - -template -struct Waterfill_64xH_Default_ProcessedMask{ - static_assert(Tile::WIDTH == 64); - - uint64_t m[Tile::HEIGHT]; // Copy of the masks. - uint64_t b[Tile::HEIGHT]; // Bit-reversed copy of the masks. - - PA_FORCE_INLINE Waterfill_64xH_Default_ProcessedMask( - const Tile& mask, - uint64_t x[Tile::HEIGHT] - ){ - for (size_t c = 0; c < Tile::HEIGHT; c++){ - m[c] = x[c] | mask.row(c); - b[c] = bitreverse64(m[c]); - } - } -}; - -template -PA_FORCE_INLINE bool keep_going( - const Waterfill_64xH_Default_ProcessedMask& mask, - uint64_t m[Tile::HEIGHT], uint64_t x[Tile::HEIGHT] -){ - for (size_t c = 0; c < Tile::HEIGHT; c++){ - m[c] = ~x[c] & mask.m[c]; - } - - uint64_t changed = x[0] & ((m[0] << 1) | m[1]); - - size_t c = 1; - for (; c < Tile::HEIGHT - 1; c++){ - changed |= x[c] & ((m[c] << 1) | m[c - 1] | m[c + 1]); - } - - changed |= x[c] & ((m[c] << 1) | m[c - 1]); - - return changed; -} - -template -PA_FORCE_INLINE void expand_forward( - const Waterfill_64xH_Default_ProcessedMask& mask, - uint64_t x[Tile::HEIGHT] -){ - for (size_t c = 0; c < Tile::HEIGHT; c++){ - uint64_t m = mask.m[c]; - uint64_t s = x[c] + m; - s ^= m; - s &= m; - x[c] |= s; - } -} - -template -PA_FORCE_INLINE void expand_reverse( - const Waterfill_64xH_Default_ProcessedMask& mask, - uint64_t x[Tile::HEIGHT] -){ - for (size_t c = 0; c < Tile::HEIGHT; c++){ - uint64_t m = mask.m[c]; - uint64_t s = bitreverse64(bitreverse64(x[c]) + mask.b[c]); - s ^= m; - s &= m; - x[c] |= s; - } -} - - - -template -PA_FORCE_INLINE void expand_vertical( - const Waterfill_64xH_Default_ProcessedMask& mask, - uint64_t x[Tile::HEIGHT] -){ - size_t dn = 0; - size_t up = Tile::HEIGHT - 1; - for (; dn < Tile::HEIGHT - 1;){ - x[dn + 1] |= x[dn] & mask.m[dn + 1]; - x[up - 1] |= x[up] & mask.m[up - 1]; - dn++; - up--; - } -} - - - - - -template -struct Waterfill_64xH_Default{ - - -static PA_FORCE_INLINE uint64_t row_or(const Tile& tile){ - static_assert(Tile::WIDTH == 64); - - uint64_t v0 = 0; - for (size_t c = 0; c < Tile::HEIGHT; c++){ - v0 |= tile.row(c); - } - - return v0; -} - -// Find a one bit in the specified tile. -// If found, (x, y) are set to its coordinates and returns true. -// If entire tile is zero, returns false. -static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const Tile& tile){ - uint64_t anything = row_or(tile); - if (!anything){ - return false; - } - for (size_t c = 0; c < Tile::HEIGHT; c++){ - size_t pos; - if (trailing_zeros(pos, tile.row(c))){ - x = pos; - y = c; - return true; - } - } - return false; -} - - -// Finds the boundaries of the one-bits inside the tile. -// Max values are one past the end. -// Behavior is undefined if tile is zero. -static PA_FORCE_INLINE void boundaries( - const Tile& tile, - size_t& min_x, size_t& max_x, - size_t& min_y, size_t& max_y -){ - uint64_t all_or = row_or(tile); - trailing_zeros(min_x, all_or); - max_x = bitlength(all_or); - - min_y = 0; - for (size_t c = 0; c < Tile::HEIGHT; c++){ - if (tile.row(c) != 0){ - min_y = c; - break; - } - } - max_y = 0; - for (size_t c = Tile::HEIGHT; c > 0; c--){ - if (tile.row(c - 1) != 0){ - max_y = c; - break; - } - } -} - - - -// Area + Center of Gravity: -// Compute the sum of the index of each set bit. -// Returns the popcount. -static PA_FORCE_INLINE uint64_t popcount_indexsum(uint64_t& sum_index, uint64_t x){ - // 1 -> 2 - uint64_t sum_high; - uint64_t pop_high = (x >> 1) & 0x5555555555555555; - uint64_t sumxaxis = pop_high; - uint64_t popcount = (x & 0x5555555555555555) + pop_high; - - // 2 -> 4 - sum_high = (sumxaxis >> 2) & 0x3333333333333333; - pop_high = (popcount >> 2) & 0x3333333333333333; - sumxaxis = (sumxaxis & 0x3333333333333333) + sum_high; - sumxaxis += pop_high << 1; - popcount = (popcount & 0x3333333333333333) + pop_high; - - // 4 -> 8 - sum_high = (sumxaxis >> 4) & 0x0f0f0f0f0f0f0f0f; - pop_high = (popcount >> 4) & 0x0f0f0f0f0f0f0f0f; - sumxaxis = (sumxaxis & 0x0f0f0f0f0f0f0f0f) + sum_high; - sumxaxis += pop_high << 2; - popcount = (popcount & 0x0f0f0f0f0f0f0f0f) + pop_high; - - // 8 -> 16 - sum_high = (sumxaxis >> 8) & 0x00ff00ff00ff00ff; - pop_high = (popcount >> 8) & 0x00ff00ff00ff00ff; - sumxaxis = (sumxaxis & 0x00ff00ff00ff00ff) + sum_high; - sumxaxis += pop_high << 3; - popcount = (popcount & 0x00ff00ff00ff00ff) + pop_high; - - // 16 -> 32 - sum_high = (sumxaxis >> 16) & 0x0000ffff0000ffff; - pop_high = (popcount >> 16) & 0x0000ffff0000ffff; - sumxaxis = (sumxaxis & 0x0000ffff0000ffff) + sum_high; - sumxaxis += pop_high << 4; - popcount = (popcount & 0x0000ffff0000ffff) + pop_high; - - // 32 -> 64 - sum_high = sumxaxis >> 32; - pop_high = popcount >> 32; - sumxaxis += sum_high; - sumxaxis += pop_high << 5; - popcount += pop_high; - - sum_index = (uint32_t)sumxaxis; - return (uint32_t)popcount; -} - -static PA_FORCE_INLINE uint64_t popcount_sumcoord( - uint64_t& sum_xcoord, uint64_t& sum_ycoord, - const Tile& tile -){ - static_assert(Tile::WIDTH == 64); - - uint64_t sum_p = 0; - uint64_t sum_x = 0; - uint64_t sum_y = 0; - { - uint64_t sum; - sum_p += popcount_indexsum(sum, tile.row(0)); - sum_x += sum; - } - for (size_t c = 1; c < Tile::HEIGHT; c++){ - uint64_t pop, sum; - pop = popcount_indexsum(sum, tile.row(c)); - sum_p += pop; - sum_x += sum; - sum_y += pop * c; - } - sum_xcoord = sum_x; - sum_ycoord = sum_y; - return sum_p; -} - - - - -// Touch the edge of "tile" with the specified border. -// Returns true if "tile" has changed and needs to be updated. -static PA_FORCE_INLINE bool waterfill_touch_top( - const Tile& mask, Tile& tile, const Tile& border -){ - uint64_t available = mask.row(0) & ~tile.row(0); - uint64_t new_bits = available & border.row(Tile::HEIGHT - 1); - if (new_bits == 0){ - return false; - } - tile.row(0) |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_bottom( - const Tile& mask, Tile& tile, const Tile& border -){ - uint64_t available = mask.row(Tile::HEIGHT - 1) & ~tile.row(Tile::HEIGHT - 1); - uint64_t new_bits = available & border.row(0); - if (new_bits == 0){ - return false; - } - tile.row(Tile::HEIGHT - 1) |= new_bits; - return true; -} -static PA_FORCE_INLINE bool waterfill_touch_left( - const Tile& mask, Tile& tile, const Tile& border -){ - bool changed = false; - for (size_t c = 0; c < Tile::HEIGHT; c++){ - uint64_t available = mask.row(c) & ~tile.row(c); - uint64_t new_bits = available & (border.row(c) >> 63); - changed |= new_bits != 0; - tile.row(c) |= new_bits; - } - return changed; -} -static PA_FORCE_INLINE bool waterfill_touch_right( - const Tile& mask, Tile& tile, const Tile& border -){ - bool changed = false; - for (size_t c = 0; c < Tile::HEIGHT; c++){ - uint64_t available = mask.row(c) & ~tile.row(c); - uint64_t new_bits = available & (border.row(c) << 63); - changed |= new_bits != 0; - tile.row(c) |= new_bits; - } - return changed; -} - - - - - -// Run Waterfill algorithm on mask "m" with starting point "x". -// Save result back into "x". Clear bits of object from "m". -static PA_FORCE_INLINE void waterfill_expand(Tile& m, Tile& x){ - uint64_t xs[Tile::HEIGHT]; - for (size_t c = 0; c < Tile::HEIGHT; c++){ - xs[c] = x.row(c); - } - - Waterfill_64xH_Default_ProcessedMask mask(m, xs); - expand_forward(mask, xs); - - uint64_t ms[Tile::HEIGHT]; - do{ - expand_vertical(mask, xs); - expand_reverse(mask, xs); - expand_forward(mask, xs); - }while (keep_going(mask, ms, xs)); - - for (size_t c = 0; c < Tile::HEIGHT; c++){ - x.row(c) = xs[c]; - m.row(c) = ms[c]; - } -} - - - - -}; - - - -} -} -} -#endif +/* Waterfill Core (Default) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Core_64xH_Default_H +#define PokemonAutomation_Kernels_Waterfill_Core_64xH_Default_H + +#include "Kernels/Kernels_BitScan.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +PA_FORCE_INLINE uint64_t bitreverse64(uint64_t x){ + uint64_t r0, r1; + +#if 0 +#elif __GNUC__ + r0 = __builtin_bswap64(x); +#elif __INTEL_COMPILER + r0 = _bswap64(x); +#elif _MSC_VER + r0 = _byteswap_uint64(x); +#else +#error "No byte-swap for this compiler." +#endif + + r1 = r0 >> 4; + r0 = r0 << 4; + r1 &= 0x0f0f0f0f0f0f0f0full; + r0 &= 0xf0f0f0f0f0f0f0f0ull; + r0 |= r1; + + r1 = r0 >> 2; + r0 = r0 << 2; + r1 &= 0x3333333333333333ull; + r0 &= 0xccccccccccccccccull; + r0 |= r1; + + r1 = r0 >> 1; + r0 = r0 << 1; + r1 &= 0x5555555555555555ull; + r0 &= 0xaaaaaaaaaaaaaaaaull; + r0 |= r1; + + return r0; +} + + + + +template +struct Waterfill_64xH_Default_ProcessedMask{ + static_assert(Tile::WIDTH == 64); + + uint64_t m[Tile::HEIGHT]; // Copy of the masks. + uint64_t b[Tile::HEIGHT]; // Bit-reversed copy of the masks. + + PA_FORCE_INLINE Waterfill_64xH_Default_ProcessedMask( + const Tile& mask, + uint64_t x[Tile::HEIGHT] + ){ + for (size_t c = 0; c < Tile::HEIGHT; c++){ + m[c] = x[c] | mask.row(c); + b[c] = bitreverse64(m[c]); + } + } +}; + +template +PA_FORCE_INLINE bool keep_going( + const Waterfill_64xH_Default_ProcessedMask& mask, + uint64_t m[Tile::HEIGHT], uint64_t x[Tile::HEIGHT] +){ + for (size_t c = 0; c < Tile::HEIGHT; c++){ + m[c] = ~x[c] & mask.m[c]; + } + + uint64_t changed = x[0] & ((m[0] << 1) | m[1]); + + size_t c = 1; + for (; c < Tile::HEIGHT - 1; c++){ + changed |= x[c] & ((m[c] << 1) | m[c - 1] | m[c + 1]); + } + + changed |= x[c] & ((m[c] << 1) | m[c - 1]); + + return changed; +} + +template +PA_FORCE_INLINE void expand_forward( + const Waterfill_64xH_Default_ProcessedMask& mask, + uint64_t x[Tile::HEIGHT] +){ + for (size_t c = 0; c < Tile::HEIGHT; c++){ + uint64_t m = mask.m[c]; + uint64_t s = x[c] + m; + s ^= m; + s &= m; + x[c] |= s; + } +} + +template +PA_FORCE_INLINE void expand_reverse( + const Waterfill_64xH_Default_ProcessedMask& mask, + uint64_t x[Tile::HEIGHT] +){ + for (size_t c = 0; c < Tile::HEIGHT; c++){ + uint64_t m = mask.m[c]; + uint64_t s = bitreverse64(bitreverse64(x[c]) + mask.b[c]); + s ^= m; + s &= m; + x[c] |= s; + } +} + + + +template +PA_FORCE_INLINE void expand_vertical( + const Waterfill_64xH_Default_ProcessedMask& mask, + uint64_t x[Tile::HEIGHT] +){ + size_t dn = 0; + size_t up = Tile::HEIGHT - 1; + for (; dn < Tile::HEIGHT - 1;){ + x[dn + 1] |= x[dn] & mask.m[dn + 1]; + x[up - 1] |= x[up] & mask.m[up - 1]; + dn++; + up--; + } +} + + + + + +template +struct Waterfill_64xH_Default{ + + +static PA_FORCE_INLINE uint64_t row_or(const Tile& tile){ + static_assert(Tile::WIDTH == 64); + + uint64_t v0 = 0; + for (size_t c = 0; c < Tile::HEIGHT; c++){ + v0 |= tile.row(c); + } + + return v0; +} + +// Find a one bit in the specified tile. +// If found, (x, y) are set to its coordinates and returns true. +// If entire tile is zero, returns false. +static PA_FORCE_INLINE bool find_bit(size_t& x, size_t& y, const Tile& tile){ + uint64_t anything = row_or(tile); + if (!anything){ + return false; + } + for (size_t c = 0; c < Tile::HEIGHT; c++){ + size_t pos; + if (trailing_zeros(pos, tile.row(c))){ + x = pos; + y = c; + return true; + } + } + return false; +} + + +// Finds the boundaries of the one-bits inside the tile. +// Max values are one past the end. +// Behavior is undefined if tile is zero. +static PA_FORCE_INLINE void boundaries( + const Tile& tile, + size_t& min_x, size_t& max_x, + size_t& min_y, size_t& max_y +){ + uint64_t all_or = row_or(tile); + trailing_zeros(min_x, all_or); + max_x = bitlength(all_or); + + min_y = 0; + for (size_t c = 0; c < Tile::HEIGHT; c++){ + if (tile.row(c) != 0){ + min_y = c; + break; + } + } + max_y = 0; + for (size_t c = Tile::HEIGHT; c > 0; c--){ + if (tile.row(c - 1) != 0){ + max_y = c; + break; + } + } +} + + + +// Area + Center of Gravity: +// Compute the sum of the index of each set bit. +// Returns the popcount. +static PA_FORCE_INLINE uint64_t popcount_indexsum(uint64_t& sum_index, uint64_t x){ + // 1 -> 2 + uint64_t sum_high; + uint64_t pop_high = (x >> 1) & 0x5555555555555555; + uint64_t sumxaxis = pop_high; + uint64_t popcount = (x & 0x5555555555555555) + pop_high; + + // 2 -> 4 + sum_high = (sumxaxis >> 2) & 0x3333333333333333; + pop_high = (popcount >> 2) & 0x3333333333333333; + sumxaxis = (sumxaxis & 0x3333333333333333) + sum_high; + sumxaxis += pop_high << 1; + popcount = (popcount & 0x3333333333333333) + pop_high; + + // 4 -> 8 + sum_high = (sumxaxis >> 4) & 0x0f0f0f0f0f0f0f0f; + pop_high = (popcount >> 4) & 0x0f0f0f0f0f0f0f0f; + sumxaxis = (sumxaxis & 0x0f0f0f0f0f0f0f0f) + sum_high; + sumxaxis += pop_high << 2; + popcount = (popcount & 0x0f0f0f0f0f0f0f0f) + pop_high; + + // 8 -> 16 + sum_high = (sumxaxis >> 8) & 0x00ff00ff00ff00ff; + pop_high = (popcount >> 8) & 0x00ff00ff00ff00ff; + sumxaxis = (sumxaxis & 0x00ff00ff00ff00ff) + sum_high; + sumxaxis += pop_high << 3; + popcount = (popcount & 0x00ff00ff00ff00ff) + pop_high; + + // 16 -> 32 + sum_high = (sumxaxis >> 16) & 0x0000ffff0000ffff; + pop_high = (popcount >> 16) & 0x0000ffff0000ffff; + sumxaxis = (sumxaxis & 0x0000ffff0000ffff) + sum_high; + sumxaxis += pop_high << 4; + popcount = (popcount & 0x0000ffff0000ffff) + pop_high; + + // 32 -> 64 + sum_high = sumxaxis >> 32; + pop_high = popcount >> 32; + sumxaxis += sum_high; + sumxaxis += pop_high << 5; + popcount += pop_high; + + sum_index = (uint32_t)sumxaxis; + return (uint32_t)popcount; +} + +static PA_FORCE_INLINE uint64_t popcount_sumcoord( + uint64_t& sum_xcoord, uint64_t& sum_ycoord, + const Tile& tile +){ + static_assert(Tile::WIDTH == 64); + + uint64_t sum_p = 0; + uint64_t sum_x = 0; + uint64_t sum_y = 0; + { + uint64_t sum; + sum_p += popcount_indexsum(sum, tile.row(0)); + sum_x += sum; + } + for (size_t c = 1; c < Tile::HEIGHT; c++){ + uint64_t pop, sum; + pop = popcount_indexsum(sum, tile.row(c)); + sum_p += pop; + sum_x += sum; + sum_y += pop * c; + } + sum_xcoord = sum_x; + sum_ycoord = sum_y; + return sum_p; +} + + + + +// Touch the edge of "tile" with the specified border. +// Returns true if "tile" has changed and needs to be updated. +static PA_FORCE_INLINE bool waterfill_touch_top( + const Tile& mask, Tile& tile, const Tile& border +){ + uint64_t available = mask.row(0) & ~tile.row(0); + uint64_t new_bits = available & border.row(Tile::HEIGHT - 1); + if (new_bits == 0){ + return false; + } + tile.row(0) |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_bottom( + const Tile& mask, Tile& tile, const Tile& border +){ + uint64_t available = mask.row(Tile::HEIGHT - 1) & ~tile.row(Tile::HEIGHT - 1); + uint64_t new_bits = available & border.row(0); + if (new_bits == 0){ + return false; + } + tile.row(Tile::HEIGHT - 1) |= new_bits; + return true; +} +static PA_FORCE_INLINE bool waterfill_touch_left( + const Tile& mask, Tile& tile, const Tile& border +){ + bool changed = false; + for (size_t c = 0; c < Tile::HEIGHT; c++){ + uint64_t available = mask.row(c) & ~tile.row(c); + uint64_t new_bits = available & (border.row(c) >> 63); + changed |= new_bits != 0; + tile.row(c) |= new_bits; + } + return changed; +} +static PA_FORCE_INLINE bool waterfill_touch_right( + const Tile& mask, Tile& tile, const Tile& border +){ + bool changed = false; + for (size_t c = 0; c < Tile::HEIGHT; c++){ + uint64_t available = mask.row(c) & ~tile.row(c); + uint64_t new_bits = available & (border.row(c) << 63); + changed |= new_bits != 0; + tile.row(c) |= new_bits; + } + return changed; +} + + + + + +// Run Waterfill algorithm on mask "m" with starting point "x". +// Save result back into "x". Clear bits of object from "m". +static PA_FORCE_INLINE void waterfill_expand(Tile& m, Tile& x){ + uint64_t xs[Tile::HEIGHT]; + for (size_t c = 0; c < Tile::HEIGHT; c++){ + xs[c] = x.row(c); + } + + Waterfill_64xH_Default_ProcessedMask mask(m, xs); + expand_forward(mask, xs); + + uint64_t ms[Tile::HEIGHT]; + do{ + expand_vertical(mask, xs); + expand_reverse(mask, xs); + expand_forward(mask, xs); + }while (keep_going(mask, ms, xs)); + + for (size_t c = 0; c < Tile::HEIGHT; c++){ + x.row(c) = xs[c]; + m.row(c) = ms[c]; + } +} + + + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h index bb1f3331b1..a3252fa194 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512-GF.h @@ -1,433 +1,433 @@ -/* Waterfill Intrinsics (x64 AVX512-GF) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512GF_H -#define PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512GF_H - -#include -#include "Common/Compiler.h" -#include "Kernels/Kernels_x64_AVX512.h" -#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ -namespace Intrinsics_x64_AVX512GF{ - - - -PA_FORCE_INLINE __m512i bit_reverse(__m512i x){ - x = _mm512_shuffle_epi8( - x, - _mm512_setr_epi8( - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 - ) - ); - return _mm512_gf2p8affine_epi64_epi8(x, _mm512_set1_epi64(0x8040201008040201), 0); -} - - -#if 0 -PA_FORCE_INLINE __m512i transpose_forward(__m512i x){ - const __m512i INDEX = _mm512_setr_epi8( - 56, 48, 40, 32, 24, 16, 8, 0, - 57, 49, 41, 33, 25, 17, 9, 1, - 58, 50, 42, 34, 26, 18, 10, 2, - 59, 51, 43, 35, 27, 19, 11, 3, - 60, 52, 44, 36, 28, 20, 12, 4, - 61, 53, 45, 37, 29, 21, 13, 5, - 62, 54, 46, 38, 30, 22, 14, 6, - 63, 55, 47, 39, 31, 23, 15, 7 - ); - x = _mm512_permutexvar_epi8(INDEX, x); - x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); - return x; -} -PA_FORCE_INLINE __m512i transpose_inverse(__m512i x){ - const __m512i INDEX = _mm512_setr_epi8( - 7, 15, 23, 31, 39, 47, 55, 63, - 6, 14, 22, 30, 38, 46, 54, 62, - 5, 13, 21, 29, 37, 45, 53, 61, - 4, 12, 20, 28, 36, 44, 52, 60, - 3, 11, 19, 27, 35, 43, 51, 59, - 2, 10, 18, 26, 34, 42, 50, 58, - 1, 9, 17, 25, 33, 41, 49, 57, - 0, 8, 16, 24, 32, 40, 48, 56 - ); - x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x0102040810204080), x, 0); - x = _mm512_gf2p8affine_epi64_epi8(x, _mm512_set1_epi64(0x8040201008040201), 0); - x = _mm512_permutexvar_epi8(INDEX, x); - return x; -} -PA_FORCE_INLINE __m512i transpose_inverse_reversed(__m512i x){ - const __m512i INDEX = _mm512_setr_epi8( - 7, 15, 23, 31, 39, 47, 55, 63, - 6, 14, 22, 30, 38, 46, 54, 62, - 5, 13, 21, 29, 37, 45, 53, 61, - 4, 12, 20, 28, 36, 44, 52, 60, - 3, 11, 19, 27, 35, 43, 51, 59, - 2, 10, 18, 26, 34, 42, 50, 58, - 1, 9, 17, 25, 33, 41, 49, 57, - 0, 8, 16, 24, 32, 40, 48, 56 - ); - x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); - x = _mm512_gf2p8affine_epi64_epi8(x, _mm512_set1_epi64(0x8040201008040201), 0); - x = _mm512_permutexvar_epi8(INDEX, x); - return x; -} -#endif - -#if 0 -PA_FORCE_INLINE __m512i transpose_1x8x8x8(__m512i x){ - const __m512i INDEX0 = _mm512_setr_epi8( - 56, 48, 40, 32, 24, 16, 8, 0, - 57, 49, 41, 33, 25, 17, 9, 1, - 58, 50, 42, 34, 26, 18, 10, 2, - 59, 51, 43, 35, 27, 19, 11, 3, - 60, 52, 44, 36, 28, 20, 12, 4, - 61, 53, 45, 37, 29, 21, 13, 5, - 62, 54, 46, 38, 30, 22, 14, 6, - 63, 55, 47, 39, 31, 23, 15, 7 - ); - const __m512i INDEX1 = _mm512_setr_epi8( - 0, 8, 16, 24, 32, 40, 48, 56, - 1, 9, 17, 25, 33, 41, 49, 57, - 2, 10, 18, 26, 34, 42, 50, 58, - 3, 11, 19, 27, 35, 43, 51, 59, - 4, 12, 20, 28, 36, 44, 52, 60, - 5, 13, 21, 29, 37, 45, 53, 61, - 6, 14, 22, 30, 38, 46, 54, 62, - 7, 15, 23, 31, 39, 47, 55, 63 - ); - x = _mm512_permutexvar_epi8(INDEX0, x); - x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); - x = _mm512_permutexvar_epi8(INDEX1, x); - return x; -} -PA_FORCE_INLINE __m512i transpose_1x8x8x8_bitreverse_in(__m512i x){ - const __m512i INDEX0 = _mm512_setr_epi8( - 63, 55, 47, 39, 31, 23, 15, 7, - 62, 54, 46, 38, 30, 22, 14, 6, - 61, 53, 45, 37, 29, 21, 13, 5, - 60, 52, 44, 36, 28, 20, 12, 4, - 59, 51, 43, 35, 27, 19, 11, 3, - 58, 50, 42, 34, 26, 18, 10, 2, - 57, 49, 41, 33, 25, 17, 9, 1, - 56, 48, 40, 32, 24, 16, 8, 0 - ); - const __m512i INDEX1 = _mm512_setr_epi8( - 7, 15, 23, 31, 39, 47, 55, 63, - 6, 14, 22, 30, 38, 46, 54, 62, - 5, 13, 21, 29, 37, 45, 53, 61, - 4, 12, 20, 28, 36, 44, 52, 60, - 3, 11, 19, 27, 35, 43, 51, 59, - 2, 10, 18, 26, 34, 42, 50, 58, - 1, 9, 17, 25, 33, 41, 49, 57, - 0, 8, 16, 24, 32, 40, 48, 56 - ); - x = _mm512_permutexvar_epi8(INDEX0, x); - x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); - x = _mm512_permutexvar_epi8(INDEX1, x); - return x; -} -#endif - -PA_FORCE_INLINE void transpose_1x16x16x4(__m512i& r0, __m512i& r1){ - const __m512i INDEX = _mm512_setr_epi8( - 56, 48, 40, 32, 24, 16, 8, 0, - 57, 49, 41, 33, 25, 17, 9, 1, - 58, 50, 42, 34, 26, 18, 10, 2, - 59, 51, 43, 35, 27, 19, 11, 3, - 60, 52, 44, 36, 28, 20, 12, 4, - 61, 53, 45, 37, 29, 21, 13, 5, - 62, 54, 46, 38, 30, 22, 14, 6, - 63, 55, 47, 39, 31, 23, 15, 7 - ); - __m512i s0, s1; - r0 = _mm512_permutexvar_epi8(INDEX, r0); - r1 = _mm512_permutexvar_epi8(INDEX, r1); - s0 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r0, 0); - s1 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r1, 0); -#if 0 - const __m512i INDEX0 = _mm512_setr_epi8( - 0, 64, 16, 80, 32, 96, 48,112, - 1, 65, 17, 81, 33, 97, 49,113, - 2, 66, 18, 82, 34, 98, 50,114, - 3, 67, 19, 83, 35, 99, 51,115, - 4, 68, 20, 84, 36,100, 52,116, - 5, 69, 21, 85, 37,101, 53,117, - 6, 70, 22, 86, 38,102, 54,118, - 7, 71, 23, 87, 39,103, 55,119 - ); - const __m512i INDEX1 = _mm512_setr_epi8( - 8, 72, 24, 88, 40,104, 56,120, - 9, 73, 25, 89, 41,105, 57,121, - 10, 74, 26, 90, 42,106, 58,122, - 11, 75, 27, 91, 43,107, 59,123, - 12, 76, 28, 92, 44,108, 60,124, - 13, 77, 29, 93, 45,109, 61,125, - 14, 78, 30, 94, 46,110, 62,126, - 15, 79, 31, 95, 47,111, 63,127 - ); - r0 = _mm512_permutex2var_epi8(s0, INDEX0, s1); - r1 = _mm512_permutex2var_epi8(s0, INDEX1, s1); -#else - const __m512i INDEX0 = _mm512_setr_epi8( - 0, 8, 16, 24, 32, 40, 48, 56, - 1, 9, 17, 25, 33, 41, 49, 57, - 2, 10, 18, 26, 34, 42, 50, 58, - 3, 11, 19, 27, 35, 43, 51, 59, - 4, 12, 20, 28, 36, 44, 52, 60, - 5, 13, 21, 29, 37, 45, 53, 61, - 6, 14, 22, 30, 38, 46, 54, 62, - 7, 15, 23, 31, 39, 47, 55, 63 - ); - const __m512i INDEX1 = _mm512_setr_epi8( - 8, 0, 24, 16, 40, 32, 56, 48, - 9, 1, 25, 17, 41, 33, 57, 49, - 10, 2, 26, 18, 42, 34, 58, 50, - 11, 3, 27, 19, 43, 35, 59, 51, - 12, 4, 28, 20, 44, 36, 60, 52, - 13, 5, 29, 21, 45, 37, 61, 53, - 14, 6, 30, 22, 46, 38, 62, 54, - 15, 7, 31, 23, 47, 39, 63, 55 - ); - s0 = _mm512_permutexvar_epi8(INDEX0, s0); - s1 = _mm512_permutexvar_epi8(INDEX1, s1); - r0 = _mm512_ternarylogic_epi64(s0, s1, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); - r1 = _mm512_ternarylogic_epi64(s1, s0, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); - r1 = _mm512_shuffle_epi8(r1, _mm512_setr_epi8( - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 - )); -#endif -} -PA_FORCE_INLINE void transpose_1x16x16x4_bitreverse_in(__m512i& r0, __m512i& r1){ - const __m512i INDEX = _mm512_setr_epi8( - 63, 55, 47, 39, 31, 23, 15, 7, - 62, 54, 46, 38, 30, 22, 14, 6, - 61, 53, 45, 37, 29, 21, 13, 5, - 60, 52, 44, 36, 28, 20, 12, 4, - 59, 51, 43, 35, 27, 19, 11, 3, - 58, 50, 42, 34, 26, 18, 10, 2, - 57, 49, 41, 33, 25, 17, 9, 1, - 56, 48, 40, 32, 24, 16, 8, 0 - ); - __m512i s0, s1; - r0 = _mm512_permutexvar_epi8(INDEX, r0); - r1 = _mm512_permutexvar_epi8(INDEX, r1); - s0 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r0, 0); - s1 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r1, 0); -#if 0 - const __m512i INDEX0 = _mm512_setr_epi8( - 7, 71, 23, 87, 39,103, 55,119, - 6, 70, 22, 86, 38,102, 54,118, - 5, 69, 21, 85, 37,101, 53,117, - 4, 68, 20, 84, 36,100, 52,116, - 3, 67, 19, 83, 35, 99, 51,115, - 2, 66, 18, 82, 34, 98, 50,114, - 1, 65, 17, 81, 33, 97, 49,113, - 0, 64, 16, 80, 32, 96, 48,112 - ); - const __m512i INDEX1 = _mm512_setr_epi8( - 15, 79, 31, 95, 47,111, 63,127, - 14, 78, 30, 94, 46,110, 62,126, - 13, 77, 29, 93, 45,109, 61,125, - 12, 76, 28, 92, 44,108, 60,124, - 11, 75, 27, 91, 43,107, 59,123, - 10, 74, 26, 90, 42,106, 58,122, - 9, 73, 25, 89, 41,105, 57,121, - 8, 72, 24, 88, 40,104, 56,120 - ); - r0 = _mm512_permutex2var_epi8(s0, INDEX0, s1); - r1 = _mm512_permutex2var_epi8(s0, INDEX1, s1); -#else - const __m512i INDEX0 = _mm512_setr_epi8( - 7, 15, 23, 31, 39, 47, 55, 63, - 6, 14, 22, 30, 38, 46, 54, 62, - 5, 13, 21, 29, 37, 45, 53, 61, - 4, 12, 20, 28, 36, 44, 52, 60, - 3, 11, 19, 27, 35, 43, 51, 59, - 2, 10, 18, 26, 34, 42, 50, 58, - 1, 9, 17, 25, 33, 41, 49, 57, - 0, 8, 16, 24, 32, 40, 48, 56 - ); - const __m512i INDEX1 = _mm512_setr_epi8( - 15, 7, 31, 23, 47, 39, 63, 55, - 14, 6, 30, 22, 46, 38, 62, 54, - 13, 5, 29, 21, 45, 37, 61, 53, - 12, 4, 28, 20, 44, 36, 60, 52, - 11, 3, 27, 19, 43, 35, 59, 51, - 10, 2, 26, 18, 42, 34, 58, 50, - 9, 1, 25, 17, 41, 33, 57, 49, - 8, 0, 24, 16, 40, 32, 56, 48 - ); - s0 = _mm512_permutexvar_epi8(INDEX0, s0); - s1 = _mm512_permutexvar_epi8(INDEX1, s1); - r0 = _mm512_ternarylogic_epi64(s0, s1, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); - r1 = _mm512_ternarylogic_epi64(s1, s0, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); - r1 = _mm512_shuffle_epi8(r1, _mm512_setr_epi8( - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, - 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 - )); -#endif -} - -PA_FORCE_INLINE void transpose_1x64x32( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 -){ - transpose_1x16x16x4(r0, r1); - transpose_1x16x16x4(r2, r3); - Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); -} -PA_FORCE_INLINE void transpose_1x64x32_bitreverse_in( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 -){ - transpose_1x16x16x4_bitreverse_in(r0, r1); - transpose_1x16x16x4_bitreverse_in(r2, r3); - Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); -} - -PA_FORCE_INLINE void transpose_32x2x2( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, - __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 -){ - const __m512i INDEX0 = _mm512_setr_epi32( - 0, 16, - 2, 18, - 4, 20, - 6, 22, - 8, 24, - 10, 26, - 12, 28, - 14, 30 - ); - const __m512i INDEX1 = _mm512_setr_epi32( - 1, 17, - 3, 19, - 5, 21, - 7, 23, - 9, 25, - 11, 27, - 13, 29, - 15, 31 - ); - __m512i s0, s1, s2, s3, s4, s5, s6, s7; - s0 = r0; - s1 = r1; - s2 = r2; - s3 = r3; - s4 = r4; - s5 = r5; - s6 = r6; - s7 = r7; - r0 = _mm512_permutex2var_epi32(s0, INDEX0, s4); - r1 = _mm512_permutex2var_epi32(s1, INDEX0, s5); - r2 = _mm512_permutex2var_epi32(s2, INDEX0, s6); - r3 = _mm512_permutex2var_epi32(s3, INDEX0, s7); - r4 = _mm512_permutex2var_epi32(s0, INDEX1, s4); - r5 = _mm512_permutex2var_epi32(s1, INDEX1, s5); - r6 = _mm512_permutex2var_epi32(s2, INDEX1, s6); - r7 = _mm512_permutex2var_epi32(s3, INDEX1, s7); -} - -PA_FORCE_INLINE void transpose_1x64x64( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, - __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 -){ - transpose_1x16x16x4(r0, r1); - transpose_1x16x16x4(r2, r3); - transpose_1x16x16x4(r4, r5); - transpose_1x16x16x4(r6, r7); - Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); - Intrinsics_x64_AVX512::transpose_16x2x2x2(r4, r5, r6, r7); - transpose_32x2x2(r0, r1, r2, r3, r4, r5, r6, r7); -} -PA_FORCE_INLINE void transpose_1x64x64_bitreverse_in( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, - __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 -){ - transpose_1x16x16x4_bitreverse_in(r0, r1); - transpose_1x16x16x4_bitreverse_in(r2, r3); - transpose_1x16x16x4_bitreverse_in(r4, r5); - transpose_1x16x16x4_bitreverse_in(r6, r7); - Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); - Intrinsics_x64_AVX512::transpose_16x2x2x2(r4, r5, r6, r7); - transpose_32x2x2(r0, r1, r2, r3, r4, r5, r6, r7); -} - - - - - - -template -PA_FORCE_INLINE void expand_reverse( - const ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); -} -template -PA_FORCE_INLINE void expand_reverse( - const ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, - __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 -){ - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); - x4 = bit_reverse(x4); - x5 = bit_reverse(x5); - x6 = bit_reverse(x6); - x7 = bit_reverse(x7); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.b4), mask.b4, 0b11110010); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.b5), mask.b5, 0b11110010); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.b6), mask.b6, 0b11110010); - x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.b7), mask.b7, 0b11110010); - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); - x4 = bit_reverse(x4); - x5 = bit_reverse(x5); - x6 = bit_reverse(x6); - x7 = bit_reverse(x7); -} - - - - - - -} -} -} -} -#endif +/* Waterfill Intrinsics (x64 AVX512-GF) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512GF_H +#define PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512GF_H + +#include +#include "Common/Compiler.h" +#include "Kernels/Kernels_x64_AVX512.h" +#include "Kernels_Waterfill_Intrinsics_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ +namespace Intrinsics_x64_AVX512GF{ + + + +PA_FORCE_INLINE __m512i bit_reverse(__m512i x){ + x = _mm512_shuffle_epi8( + x, + _mm512_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 + ) + ); + return _mm512_gf2p8affine_epi64_epi8(x, _mm512_set1_epi64(0x8040201008040201), 0); +} + + +#if 0 +PA_FORCE_INLINE __m512i transpose_forward(__m512i x){ + const __m512i INDEX = _mm512_setr_epi8( + 56, 48, 40, 32, 24, 16, 8, 0, + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 28, 20, 12, 4, + 61, 53, 45, 37, 29, 21, 13, 5, + 62, 54, 46, 38, 30, 22, 14, 6, + 63, 55, 47, 39, 31, 23, 15, 7 + ); + x = _mm512_permutexvar_epi8(INDEX, x); + x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); + return x; +} +PA_FORCE_INLINE __m512i transpose_inverse(__m512i x){ + const __m512i INDEX = _mm512_setr_epi8( + 7, 15, 23, 31, 39, 47, 55, 63, + 6, 14, 22, 30, 38, 46, 54, 62, + 5, 13, 21, 29, 37, 45, 53, 61, + 4, 12, 20, 28, 36, 44, 52, 60, + 3, 11, 19, 27, 35, 43, 51, 59, + 2, 10, 18, 26, 34, 42, 50, 58, + 1, 9, 17, 25, 33, 41, 49, 57, + 0, 8, 16, 24, 32, 40, 48, 56 + ); + x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x0102040810204080), x, 0); + x = _mm512_gf2p8affine_epi64_epi8(x, _mm512_set1_epi64(0x8040201008040201), 0); + x = _mm512_permutexvar_epi8(INDEX, x); + return x; +} +PA_FORCE_INLINE __m512i transpose_inverse_reversed(__m512i x){ + const __m512i INDEX = _mm512_setr_epi8( + 7, 15, 23, 31, 39, 47, 55, 63, + 6, 14, 22, 30, 38, 46, 54, 62, + 5, 13, 21, 29, 37, 45, 53, 61, + 4, 12, 20, 28, 36, 44, 52, 60, + 3, 11, 19, 27, 35, 43, 51, 59, + 2, 10, 18, 26, 34, 42, 50, 58, + 1, 9, 17, 25, 33, 41, 49, 57, + 0, 8, 16, 24, 32, 40, 48, 56 + ); + x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); + x = _mm512_gf2p8affine_epi64_epi8(x, _mm512_set1_epi64(0x8040201008040201), 0); + x = _mm512_permutexvar_epi8(INDEX, x); + return x; +} +#endif + +#if 0 +PA_FORCE_INLINE __m512i transpose_1x8x8x8(__m512i x){ + const __m512i INDEX0 = _mm512_setr_epi8( + 56, 48, 40, 32, 24, 16, 8, 0, + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 28, 20, 12, 4, + 61, 53, 45, 37, 29, 21, 13, 5, + 62, 54, 46, 38, 30, 22, 14, 6, + 63, 55, 47, 39, 31, 23, 15, 7 + ); + const __m512i INDEX1 = _mm512_setr_epi8( + 0, 8, 16, 24, 32, 40, 48, 56, + 1, 9, 17, 25, 33, 41, 49, 57, + 2, 10, 18, 26, 34, 42, 50, 58, + 3, 11, 19, 27, 35, 43, 51, 59, + 4, 12, 20, 28, 36, 44, 52, 60, + 5, 13, 21, 29, 37, 45, 53, 61, + 6, 14, 22, 30, 38, 46, 54, 62, + 7, 15, 23, 31, 39, 47, 55, 63 + ); + x = _mm512_permutexvar_epi8(INDEX0, x); + x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); + x = _mm512_permutexvar_epi8(INDEX1, x); + return x; +} +PA_FORCE_INLINE __m512i transpose_1x8x8x8_bitreverse_in(__m512i x){ + const __m512i INDEX0 = _mm512_setr_epi8( + 63, 55, 47, 39, 31, 23, 15, 7, + 62, 54, 46, 38, 30, 22, 14, 6, + 61, 53, 45, 37, 29, 21, 13, 5, + 60, 52, 44, 36, 28, 20, 12, 4, + 59, 51, 43, 35, 27, 19, 11, 3, + 58, 50, 42, 34, 26, 18, 10, 2, + 57, 49, 41, 33, 25, 17, 9, 1, + 56, 48, 40, 32, 24, 16, 8, 0 + ); + const __m512i INDEX1 = _mm512_setr_epi8( + 7, 15, 23, 31, 39, 47, 55, 63, + 6, 14, 22, 30, 38, 46, 54, 62, + 5, 13, 21, 29, 37, 45, 53, 61, + 4, 12, 20, 28, 36, 44, 52, 60, + 3, 11, 19, 27, 35, 43, 51, 59, + 2, 10, 18, 26, 34, 42, 50, 58, + 1, 9, 17, 25, 33, 41, 49, 57, + 0, 8, 16, 24, 32, 40, 48, 56 + ); + x = _mm512_permutexvar_epi8(INDEX0, x); + x = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), x, 0); + x = _mm512_permutexvar_epi8(INDEX1, x); + return x; +} +#endif + +PA_FORCE_INLINE void transpose_1x16x16x4(__m512i& r0, __m512i& r1){ + const __m512i INDEX = _mm512_setr_epi8( + 56, 48, 40, 32, 24, 16, 8, 0, + 57, 49, 41, 33, 25, 17, 9, 1, + 58, 50, 42, 34, 26, 18, 10, 2, + 59, 51, 43, 35, 27, 19, 11, 3, + 60, 52, 44, 36, 28, 20, 12, 4, + 61, 53, 45, 37, 29, 21, 13, 5, + 62, 54, 46, 38, 30, 22, 14, 6, + 63, 55, 47, 39, 31, 23, 15, 7 + ); + __m512i s0, s1; + r0 = _mm512_permutexvar_epi8(INDEX, r0); + r1 = _mm512_permutexvar_epi8(INDEX, r1); + s0 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r0, 0); + s1 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r1, 0); +#if 0 + const __m512i INDEX0 = _mm512_setr_epi8( + 0, 64, 16, 80, 32, 96, 48,112, + 1, 65, 17, 81, 33, 97, 49,113, + 2, 66, 18, 82, 34, 98, 50,114, + 3, 67, 19, 83, 35, 99, 51,115, + 4, 68, 20, 84, 36,100, 52,116, + 5, 69, 21, 85, 37,101, 53,117, + 6, 70, 22, 86, 38,102, 54,118, + 7, 71, 23, 87, 39,103, 55,119 + ); + const __m512i INDEX1 = _mm512_setr_epi8( + 8, 72, 24, 88, 40,104, 56,120, + 9, 73, 25, 89, 41,105, 57,121, + 10, 74, 26, 90, 42,106, 58,122, + 11, 75, 27, 91, 43,107, 59,123, + 12, 76, 28, 92, 44,108, 60,124, + 13, 77, 29, 93, 45,109, 61,125, + 14, 78, 30, 94, 46,110, 62,126, + 15, 79, 31, 95, 47,111, 63,127 + ); + r0 = _mm512_permutex2var_epi8(s0, INDEX0, s1); + r1 = _mm512_permutex2var_epi8(s0, INDEX1, s1); +#else + const __m512i INDEX0 = _mm512_setr_epi8( + 0, 8, 16, 24, 32, 40, 48, 56, + 1, 9, 17, 25, 33, 41, 49, 57, + 2, 10, 18, 26, 34, 42, 50, 58, + 3, 11, 19, 27, 35, 43, 51, 59, + 4, 12, 20, 28, 36, 44, 52, 60, + 5, 13, 21, 29, 37, 45, 53, 61, + 6, 14, 22, 30, 38, 46, 54, 62, + 7, 15, 23, 31, 39, 47, 55, 63 + ); + const __m512i INDEX1 = _mm512_setr_epi8( + 8, 0, 24, 16, 40, 32, 56, 48, + 9, 1, 25, 17, 41, 33, 57, 49, + 10, 2, 26, 18, 42, 34, 58, 50, + 11, 3, 27, 19, 43, 35, 59, 51, + 12, 4, 28, 20, 44, 36, 60, 52, + 13, 5, 29, 21, 45, 37, 61, 53, + 14, 6, 30, 22, 46, 38, 62, 54, + 15, 7, 31, 23, 47, 39, 63, 55 + ); + s0 = _mm512_permutexvar_epi8(INDEX0, s0); + s1 = _mm512_permutexvar_epi8(INDEX1, s1); + r0 = _mm512_ternarylogic_epi64(s0, s1, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); + r1 = _mm512_ternarylogic_epi64(s1, s0, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); + r1 = _mm512_shuffle_epi8(r1, _mm512_setr_epi8( + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 + )); +#endif +} +PA_FORCE_INLINE void transpose_1x16x16x4_bitreverse_in(__m512i& r0, __m512i& r1){ + const __m512i INDEX = _mm512_setr_epi8( + 63, 55, 47, 39, 31, 23, 15, 7, + 62, 54, 46, 38, 30, 22, 14, 6, + 61, 53, 45, 37, 29, 21, 13, 5, + 60, 52, 44, 36, 28, 20, 12, 4, + 59, 51, 43, 35, 27, 19, 11, 3, + 58, 50, 42, 34, 26, 18, 10, 2, + 57, 49, 41, 33, 25, 17, 9, 1, + 56, 48, 40, 32, 24, 16, 8, 0 + ); + __m512i s0, s1; + r0 = _mm512_permutexvar_epi8(INDEX, r0); + r1 = _mm512_permutexvar_epi8(INDEX, r1); + s0 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r0, 0); + s1 = _mm512_gf2p8affine_epi64_epi8(_mm512_set1_epi64(0x8040201008040201), r1, 0); +#if 0 + const __m512i INDEX0 = _mm512_setr_epi8( + 7, 71, 23, 87, 39,103, 55,119, + 6, 70, 22, 86, 38,102, 54,118, + 5, 69, 21, 85, 37,101, 53,117, + 4, 68, 20, 84, 36,100, 52,116, + 3, 67, 19, 83, 35, 99, 51,115, + 2, 66, 18, 82, 34, 98, 50,114, + 1, 65, 17, 81, 33, 97, 49,113, + 0, 64, 16, 80, 32, 96, 48,112 + ); + const __m512i INDEX1 = _mm512_setr_epi8( + 15, 79, 31, 95, 47,111, 63,127, + 14, 78, 30, 94, 46,110, 62,126, + 13, 77, 29, 93, 45,109, 61,125, + 12, 76, 28, 92, 44,108, 60,124, + 11, 75, 27, 91, 43,107, 59,123, + 10, 74, 26, 90, 42,106, 58,122, + 9, 73, 25, 89, 41,105, 57,121, + 8, 72, 24, 88, 40,104, 56,120 + ); + r0 = _mm512_permutex2var_epi8(s0, INDEX0, s1); + r1 = _mm512_permutex2var_epi8(s0, INDEX1, s1); +#else + const __m512i INDEX0 = _mm512_setr_epi8( + 7, 15, 23, 31, 39, 47, 55, 63, + 6, 14, 22, 30, 38, 46, 54, 62, + 5, 13, 21, 29, 37, 45, 53, 61, + 4, 12, 20, 28, 36, 44, 52, 60, + 3, 11, 19, 27, 35, 43, 51, 59, + 2, 10, 18, 26, 34, 42, 50, 58, + 1, 9, 17, 25, 33, 41, 49, 57, + 0, 8, 16, 24, 32, 40, 48, 56 + ); + const __m512i INDEX1 = _mm512_setr_epi8( + 15, 7, 31, 23, 47, 39, 63, 55, + 14, 6, 30, 22, 46, 38, 62, 54, + 13, 5, 29, 21, 45, 37, 61, 53, + 12, 4, 28, 20, 44, 36, 60, 52, + 11, 3, 27, 19, 43, 35, 59, 51, + 10, 2, 26, 18, 42, 34, 58, 50, + 9, 1, 25, 17, 41, 33, 57, 49, + 8, 0, 24, 16, 40, 32, 56, 48 + ); + s0 = _mm512_permutexvar_epi8(INDEX0, s0); + s1 = _mm512_permutexvar_epi8(INDEX1, s1); + r0 = _mm512_ternarylogic_epi64(s0, s1, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); + r1 = _mm512_ternarylogic_epi64(s1, s0, _mm512_set1_epi16((uint16_t)0xff00), 0xd8); + r1 = _mm512_shuffle_epi8(r1, _mm512_setr_epi8( + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, + 1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14 + )); +#endif +} + +PA_FORCE_INLINE void transpose_1x64x32( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 +){ + transpose_1x16x16x4(r0, r1); + transpose_1x16x16x4(r2, r3); + Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); +} +PA_FORCE_INLINE void transpose_1x64x32_bitreverse_in( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 +){ + transpose_1x16x16x4_bitreverse_in(r0, r1); + transpose_1x16x16x4_bitreverse_in(r2, r3); + Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); +} + +PA_FORCE_INLINE void transpose_32x2x2( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, + __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 +){ + const __m512i INDEX0 = _mm512_setr_epi32( + 0, 16, + 2, 18, + 4, 20, + 6, 22, + 8, 24, + 10, 26, + 12, 28, + 14, 30 + ); + const __m512i INDEX1 = _mm512_setr_epi32( + 1, 17, + 3, 19, + 5, 21, + 7, 23, + 9, 25, + 11, 27, + 13, 29, + 15, 31 + ); + __m512i s0, s1, s2, s3, s4, s5, s6, s7; + s0 = r0; + s1 = r1; + s2 = r2; + s3 = r3; + s4 = r4; + s5 = r5; + s6 = r6; + s7 = r7; + r0 = _mm512_permutex2var_epi32(s0, INDEX0, s4); + r1 = _mm512_permutex2var_epi32(s1, INDEX0, s5); + r2 = _mm512_permutex2var_epi32(s2, INDEX0, s6); + r3 = _mm512_permutex2var_epi32(s3, INDEX0, s7); + r4 = _mm512_permutex2var_epi32(s0, INDEX1, s4); + r5 = _mm512_permutex2var_epi32(s1, INDEX1, s5); + r6 = _mm512_permutex2var_epi32(s2, INDEX1, s6); + r7 = _mm512_permutex2var_epi32(s3, INDEX1, s7); +} + +PA_FORCE_INLINE void transpose_1x64x64( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, + __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 +){ + transpose_1x16x16x4(r0, r1); + transpose_1x16x16x4(r2, r3); + transpose_1x16x16x4(r4, r5); + transpose_1x16x16x4(r6, r7); + Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); + Intrinsics_x64_AVX512::transpose_16x2x2x2(r4, r5, r6, r7); + transpose_32x2x2(r0, r1, r2, r3, r4, r5, r6, r7); +} +PA_FORCE_INLINE void transpose_1x64x64_bitreverse_in( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3, + __m512i& r4, __m512i& r5, __m512i& r6, __m512i& r7 +){ + transpose_1x16x16x4_bitreverse_in(r0, r1); + transpose_1x16x16x4_bitreverse_in(r2, r3); + transpose_1x16x16x4_bitreverse_in(r4, r5); + transpose_1x16x16x4_bitreverse_in(r6, r7); + Intrinsics_x64_AVX512::transpose_16x2x2x2(r0, r1, r2, r3); + Intrinsics_x64_AVX512::transpose_16x2x2x2(r4, r5, r6, r7); + transpose_32x2x2(r0, r1, r2, r3, r4, r5, r6, r7); +} + + + + + + +template +PA_FORCE_INLINE void expand_reverse( + const ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); +} +template +PA_FORCE_INLINE void expand_reverse( + const ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, + __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 +){ + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); + x4 = bit_reverse(x4); + x5 = bit_reverse(x5); + x6 = bit_reverse(x6); + x7 = bit_reverse(x7); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.b4), mask.b4, 0b11110010); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.b5), mask.b5, 0b11110010); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.b6), mask.b6, 0b11110010); + x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.b7), mask.b7, 0b11110010); + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); + x4 = bit_reverse(x4); + x5 = bit_reverse(x5); + x6 = bit_reverse(x6); + x7 = bit_reverse(x7); +} + + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h index 8a5f9e6013..339aed38ee 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h @@ -1,366 +1,366 @@ -/* Waterfill Intrinsics (x64 AVX512-GF) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512_H -#define PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512_H - -#include -#include "Common/Compiler.h" -#include "Kernels/Kernels_x64_AVX512.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ -namespace Intrinsics_x64_AVX512{ - - -PA_FORCE_INLINE __m512i popcount_indexsum(__m512i& sum_index, __m512i x){ - // 1 -> 2 - __m512i sum_high; - __m512i pop_high = _mm512_and_si512(_mm512_srli_epi16(x, 1), _mm512_set1_epi8(0x55)); - __m512i sumxaxis = pop_high; - __m512i popcount = _mm512_add_epi8(_mm512_and_si512(x, _mm512_set1_epi8(0x55)), pop_high); - - // 2 -> 4 - sum_high = _mm512_and_si512(_mm512_srli_epi16(sumxaxis, 2), _mm512_set1_epi8(0x33)); - pop_high = _mm512_and_si512(_mm512_srli_epi16(popcount, 2), _mm512_set1_epi8(0x33)); - sumxaxis = _mm512_add_epi8(_mm512_and_si512(sumxaxis, _mm512_set1_epi8(0x33)), sum_high); - sumxaxis = _mm512_add_epi8(sumxaxis, _mm512_slli_epi16(pop_high, 1)); - popcount = _mm512_add_epi8(_mm512_and_si512(popcount, _mm512_set1_epi8(0x33)), pop_high); - - // 4 -> 8 - sum_high = _mm512_and_si512(_mm512_srli_epi16(sumxaxis, 4), _mm512_set1_epi8(0x0f)); - pop_high = _mm512_and_si512(_mm512_srli_epi16(popcount, 4), _mm512_set1_epi8(0x0f)); - sumxaxis = _mm512_add_epi8(_mm512_and_si512(sumxaxis, _mm512_set1_epi8(0x0f)), sum_high); - sumxaxis = _mm512_add_epi8(sumxaxis, _mm512_slli_epi16(pop_high, 2)); - popcount = _mm512_add_epi8(_mm512_and_si512(popcount, _mm512_set1_epi8(0x0f)), pop_high); - - // 8 -> 16 - sum_high = _mm512_srli_epi16(sumxaxis, 8); - pop_high = _mm512_srli_epi16(popcount, 8); - sumxaxis = _mm512_add_epi16(_mm512_and_si512(sumxaxis, _mm512_set1_epi16(0x00ff)), sum_high); - sumxaxis = _mm512_add_epi16(sumxaxis, _mm512_slli_epi16(pop_high, 3)); - popcount = _mm512_add_epi16(_mm512_and_si512(popcount, _mm512_set1_epi16(0x00ff)), pop_high); - - // 16 -> 32 - sum_high = _mm512_srli_epi32(sumxaxis, 16); - pop_high = _mm512_srli_epi32(popcount, 16); - sumxaxis = _mm512_add_epi32(sumxaxis, sum_high); - sumxaxis = _mm512_add_epi32(sumxaxis, _mm512_slli_epi32(pop_high, 4)); - popcount = _mm512_add_epi32(popcount, pop_high); - - // 32 -> 64 - sum_high = _mm512_srli_epi64(sumxaxis, 32); - pop_high = _mm512_srli_epi64(popcount, 32); - sumxaxis = _mm512_add_epi64(sumxaxis, sum_high); - sumxaxis = _mm512_add_epi64(sumxaxis, _mm512_slli_epi64(pop_high, 5)); - popcount = _mm512_add_epi64(popcount, pop_high); - - sum_index = _mm512_and_si512(sumxaxis, _mm512_set1_epi64(0x000000000000ffff)); - return _mm512_and_si512(popcount, _mm512_set1_epi64(0x000000000000ffff)); -} - - - -PA_FORCE_INLINE __m512i bit_reverse(__m512i x){ - x = _mm512_shuffle_epi8( - x, - _mm512_setr_epi8( - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 - ) - ); - - __m512i r0, r1; - r0 = _mm512_srli_epi32(x, 4); - r1 = _mm512_slli_epi32(x, 4); - r1 = _mm512_ternarylogic_epi64(r1, r0, _mm512_set1_epi8((uint8_t)0x0f), 0b11011000); - - r0 = _mm512_srli_epi32(r1, 2); - r1 = _mm512_slli_epi32(r1, 2); - r1 = _mm512_ternarylogic_epi64(r1, r0, _mm512_set1_epi8((uint8_t)0x33), 0b11011000); - - r0 = _mm512_srli_epi32(r1, 1); - r1 = _mm512_slli_epi32(r1, 1); - r1 = _mm512_ternarylogic_epi64(r1, r0, _mm512_set1_epi8((uint8_t)0x55), 0b11011000); - - return r1; -} - - - -PA_FORCE_INLINE void transpose_64x8x4_forward( - __m512i z0, __m512i z1, __m512i z2, __m512i z3, - __m256i& y0, __m256i& y1, __m256i& y2, __m256i& y3, __m256i& y4, __m256i& y5, __m256i& y6, __m256i& y7 -){ - __m512i s0, s1, s2, s3; - s0 = _mm512_unpacklo_epi64(z0, z1); - s1 = _mm512_unpackhi_epi64(z0, z1); - s2 = _mm512_unpacklo_epi64(z2, z3); - s3 = _mm512_unpackhi_epi64(z2, z3); - z0 = _mm512_mask_permutex_epi64(s0, 0xcc, s2, 78); - z1 = _mm512_mask_permutex_epi64(s1, 0xcc, s3, 78); - z2 = _mm512_mask_permutex_epi64(s2, 0x33, s0, 78); - z3 = _mm512_mask_permutex_epi64(s3, 0x33, s1, 78); - y0 = _mm512_castsi512_si256(z0); - y1 = _mm512_castsi512_si256(z1); - y2 = _mm512_castsi512_si256(z2); - y3 = _mm512_castsi512_si256(z3); - y4 = _mm512_extracti64x4_epi64(z0, 1); - y5 = _mm512_extracti64x4_epi64(z1, 1); - y6 = _mm512_extracti64x4_epi64(z2, 1); - y7 = _mm512_extracti64x4_epi64(z3, 1); -} -PA_FORCE_INLINE void transpose_64x8x4_inverse( - __m512i& z0, __m512i& z1, __m512i& z2, __m512i& z3, - __m256i y0, __m256i y1, __m256i y2, __m256i y3, __m256i y4, __m256i y5, __m256i y6, __m256i y7 -){ - __m512i s0, s1, s2, s3; - z0 = _mm512_inserti64x4(_mm512_castsi256_si512(y0), y4, 1); - z1 = _mm512_inserti64x4(_mm512_castsi256_si512(y1), y5, 1); - z2 = _mm512_inserti64x4(_mm512_castsi256_si512(y2), y6, 1); - z3 = _mm512_inserti64x4(_mm512_castsi256_si512(y3), y7, 1); - s0 = _mm512_mask_permutex_epi64(z0, 0xcc, z2, 78); - s1 = _mm512_mask_permutex_epi64(z1, 0xcc, z3, 78); - s2 = _mm512_mask_permutex_epi64(z2, 0x33, z0, 78); - s3 = _mm512_mask_permutex_epi64(z3, 0x33, z1, 78); - z0 = _mm512_unpacklo_epi64(s0, s1); - z1 = _mm512_unpackhi_epi64(s0, s1); - z2 = _mm512_unpacklo_epi64(s2, s3); - z3 = _mm512_unpackhi_epi64(s2, s3); -} - - - -PA_FORCE_INLINE __m512i transpose_1x8x8x8(__m512i x){ - __m512i r, L, H; - -// r = _mm512_shuffle_epi32(x, 78); - r = _mm512_shuffle_epi32(x, _MM_PERM_BADC); - L = _mm512_slli_epi64(r, 1); - H = _mm512_srli_epi64(r, 1); - r = _mm512_ternarylogic_epi64(L, H, _mm512_set1_epi8(0x55), 0xd8); - x = _mm512_ternarylogic_epi64(x, r, _mm512_setr_epi64(0xaaaaaaaaaaaaaaaa, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0x5555555555555555), 0xd8); - - r = _mm512_shuffle_i64x2(x, x, 177); - L = _mm512_slli_epi64(r, 2); - H = _mm512_srli_epi64(r, 2); - r = _mm512_ternarylogic_epi64(L, H, _mm512_set1_epi8(0x33), 0xd8); - x = _mm512_ternarylogic_epi64(x, r, _mm512_setr_epi64(0xcccccccccccccccc, 0xcccccccccccccccc, 0x3333333333333333, 0x3333333333333333, 0xcccccccccccccccc, 0xcccccccccccccccc, 0x3333333333333333, 0x3333333333333333), 0xd8); - - r = _mm512_shuffle_i64x2(x, x, 78); - L = _mm512_slli_epi64(r, 4); - H = _mm512_srli_epi64(r, 4); - r = _mm512_ternarylogic_epi64(L, H, _mm512_set1_epi8(0x0f), 0xd8); - x = _mm512_ternarylogic_epi64(x, r, _mm512_setr_epi64(0xf0f0f0f0f0f0f0f0, 0xf0f0f0f0f0f0f0f0, 0xf0f0f0f0f0f0f0f0, 0xf0f0f0f0f0f0f0f0, 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f), 0xd8); - - return x; -} -PA_FORCE_INLINE __m512i transpose_1x8x8x8_bitreverse_in(__m512i x){ - const __m512i INDEX = _mm512_setr_epi8( - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, - 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 - ); - x = _mm512_shuffle_epi8(x, INDEX); - x = transpose_1x8x8x8(x); - x = _mm512_permutexvar_epi64(_mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0), x); - return x; -} - -PA_FORCE_INLINE void transpose_8x2x2x4(__m512i& r0, __m512i& r1){ - __m512i s0 = r0; - r0 = _mm512_mask_alignr_epi8(r0, 0xaaaaaaaaaaaaaaaa, r1, r1, 15); - r1 = _mm512_mask_alignr_epi8(r1, 0x5555555555555555, s0, s0, 1); -} - -PA_FORCE_INLINE void transpose_16x2x2x2(__m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3){ - __m512i s0, s1; - s0 = r0; - s1 = r1; - r0 = _mm512_mask_alignr_epi8(s0, 0xcccccccccccccccc, r2, r2, 14); - r1 = _mm512_mask_alignr_epi8(s1, 0xcccccccccccccccc, r3, r3, 14); - r2 = _mm512_mask_alignr_epi8(r2, 0x3333333333333333, s0, s0, 2); - r3 = _mm512_mask_alignr_epi8(r3, 0x3333333333333333, s1, s1, 2); -} - -PA_FORCE_INLINE void transpose_1x64x32( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 -){ - r0 = transpose_1x8x8x8(r0); - r1 = transpose_1x8x8x8(r1); - r2 = transpose_1x8x8x8(r2); - r3 = transpose_1x8x8x8(r3); - transpose_8x2x2x4(r0, r1); - transpose_8x2x2x4(r2, r3); - transpose_16x2x2x2(r0, r1, r2, r3); -} -PA_FORCE_INLINE void transpose_1x64x32_bitreverse_in( - __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 -){ - r0 = transpose_1x8x8x8_bitreverse_in(r0); - r1 = transpose_1x8x8x8_bitreverse_in(r1); - r2 = transpose_1x8x8x8_bitreverse_in(r2); - r3 = transpose_1x8x8x8_bitreverse_in(r3); - transpose_8x2x2x4(r0, r1); - transpose_8x2x2x4(r2, r3); - transpose_16x2x2x2(r0, r1, r2, r3); -} - - - -PA_FORCE_INLINE void has_neighbors(__m512i& t, __m512i x, __m512i m, __m512i mH){ - m = _mm512_ternarylogic_epi64( - _mm512_slli_epi64(m, 1), - _mm512_alignr_epi64(m, _mm512_setzero_si512(), 7), - _mm512_alignr_epi64(mH, m, 1), - 254 - ); - t = _mm512_and_si512(m, x); -} -PA_FORCE_INLINE void has_neighbors(__m512i& t, __m512i x, __m512i mL, __m512i m, __m512i mH){ - m = _mm512_ternarylogic_epi64( - _mm512_slli_epi64(m, 1), - _mm512_alignr_epi64(m, mL, 7), - _mm512_alignr_epi64(mH, m, 1), - 254 - ); -// t = _mm512_or_si512(t, _mm512_and_si512(m, x)); - t = _mm512_ternarylogic_epi64(t, m, x, 0b11111000); -} -template -PA_FORCE_INLINE bool keep_going( - const ProcessedMask& mask, - __m512i& m0, __m512i& m1, __m512i& m2, __m512i& m3, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - m0 = _mm512_andnot_si512(x0, mask.m0); - m1 = _mm512_andnot_si512(x1, mask.m1); - m2 = _mm512_andnot_si512(x2, mask.m2); - m3 = _mm512_andnot_si512(x3, mask.m3); - __m512i changed; - has_neighbors(changed, x0, m0, m1); - has_neighbors(changed, x1, m0, m1, m2); - has_neighbors(changed, x2, m1, m2, m3); - has_neighbors(changed, x3, m2, m3, _mm512_setzero_si512()); - return _mm512_test_epi64_mask(changed, changed); -} -template -PA_FORCE_INLINE bool keep_going( - const ProcessedMask& mask, - __m512i& m0, __m512i& m1, __m512i& m2, __m512i& m3, __m512i& m4, __m512i& m5, __m512i& m6, __m512i& m7, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 -){ - m0 = _mm512_andnot_si512(x0, mask.m0); - m1 = _mm512_andnot_si512(x1, mask.m1); - m2 = _mm512_andnot_si512(x2, mask.m2); - m3 = _mm512_andnot_si512(x3, mask.m3); - m4 = _mm512_andnot_si512(x4, mask.m4); - m5 = _mm512_andnot_si512(x5, mask.m5); - m6 = _mm512_andnot_si512(x6, mask.m6); - m7 = _mm512_andnot_si512(x7, mask.m7); - __m512i changed; - has_neighbors(changed, x0, m0, m1); - has_neighbors(changed, x1, m0, m1, m2); - has_neighbors(changed, x2, m1, m2, m3); - has_neighbors(changed, x3, m2, m3, m4); - has_neighbors(changed, x4, m3, m4, m5); - has_neighbors(changed, x5, m4, m5, m6); - has_neighbors(changed, x6, m5, m6, m7); - has_neighbors(changed, x7, m6, m7, _mm512_setzero_si512()); - return _mm512_test_epi64_mask(changed, changed); -} - - - -template -PA_FORCE_INLINE void expand_forward( - const ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.m0), mask.m0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.m1), mask.m1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.m2), mask.m2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.m3), mask.m3, 0b11110010); -} -template -PA_FORCE_INLINE void expand_forward( - const ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, - __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 -){ - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.m0), mask.m0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.m1), mask.m1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.m2), mask.m2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.m3), mask.m3, 0b11110010); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.m4), mask.m4, 0b11110010); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.m5), mask.m5, 0b11110010); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.m6), mask.m6, 0b11110010); - x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.m7), mask.m7, 0b11110010); -} - - -template -PA_FORCE_INLINE void expand_reverse( - const ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 -){ - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); -} -template -PA_FORCE_INLINE void expand_reverse( - const ProcessedMask& mask, - __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, - __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 -){ - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); - x4 = bit_reverse(x4); - x5 = bit_reverse(x5); - x6 = bit_reverse(x6); - x7 = bit_reverse(x7); - x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); - x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); - x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); - x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); - x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.b4), mask.b4, 0b11110010); - x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.b5), mask.b5, 0b11110010); - x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.b6), mask.b6, 0b11110010); - x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.b7), mask.b7, 0b11110010); - x0 = bit_reverse(x0); - x1 = bit_reverse(x1); - x2 = bit_reverse(x2); - x3 = bit_reverse(x3); - x4 = bit_reverse(x4); - x5 = bit_reverse(x5); - x6 = bit_reverse(x6); - x7 = bit_reverse(x7); -} - - - - -} -} -} -} -#endif +/* Waterfill Intrinsics (x64 AVX512-GF) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512_H +#define PokemonAutomation_Kernels_Waterfill_Intrinsics_x64_AVX512_H + +#include +#include "Common/Compiler.h" +#include "Kernels/Kernels_x64_AVX512.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ +namespace Intrinsics_x64_AVX512{ + + +PA_FORCE_INLINE __m512i popcount_indexsum(__m512i& sum_index, __m512i x){ + // 1 -> 2 + __m512i sum_high; + __m512i pop_high = _mm512_and_si512(_mm512_srli_epi16(x, 1), _mm512_set1_epi8(0x55)); + __m512i sumxaxis = pop_high; + __m512i popcount = _mm512_add_epi8(_mm512_and_si512(x, _mm512_set1_epi8(0x55)), pop_high); + + // 2 -> 4 + sum_high = _mm512_and_si512(_mm512_srli_epi16(sumxaxis, 2), _mm512_set1_epi8(0x33)); + pop_high = _mm512_and_si512(_mm512_srli_epi16(popcount, 2), _mm512_set1_epi8(0x33)); + sumxaxis = _mm512_add_epi8(_mm512_and_si512(sumxaxis, _mm512_set1_epi8(0x33)), sum_high); + sumxaxis = _mm512_add_epi8(sumxaxis, _mm512_slli_epi16(pop_high, 1)); + popcount = _mm512_add_epi8(_mm512_and_si512(popcount, _mm512_set1_epi8(0x33)), pop_high); + + // 4 -> 8 + sum_high = _mm512_and_si512(_mm512_srli_epi16(sumxaxis, 4), _mm512_set1_epi8(0x0f)); + pop_high = _mm512_and_si512(_mm512_srli_epi16(popcount, 4), _mm512_set1_epi8(0x0f)); + sumxaxis = _mm512_add_epi8(_mm512_and_si512(sumxaxis, _mm512_set1_epi8(0x0f)), sum_high); + sumxaxis = _mm512_add_epi8(sumxaxis, _mm512_slli_epi16(pop_high, 2)); + popcount = _mm512_add_epi8(_mm512_and_si512(popcount, _mm512_set1_epi8(0x0f)), pop_high); + + // 8 -> 16 + sum_high = _mm512_srli_epi16(sumxaxis, 8); + pop_high = _mm512_srli_epi16(popcount, 8); + sumxaxis = _mm512_add_epi16(_mm512_and_si512(sumxaxis, _mm512_set1_epi16(0x00ff)), sum_high); + sumxaxis = _mm512_add_epi16(sumxaxis, _mm512_slli_epi16(pop_high, 3)); + popcount = _mm512_add_epi16(_mm512_and_si512(popcount, _mm512_set1_epi16(0x00ff)), pop_high); + + // 16 -> 32 + sum_high = _mm512_srli_epi32(sumxaxis, 16); + pop_high = _mm512_srli_epi32(popcount, 16); + sumxaxis = _mm512_add_epi32(sumxaxis, sum_high); + sumxaxis = _mm512_add_epi32(sumxaxis, _mm512_slli_epi32(pop_high, 4)); + popcount = _mm512_add_epi32(popcount, pop_high); + + // 32 -> 64 + sum_high = _mm512_srli_epi64(sumxaxis, 32); + pop_high = _mm512_srli_epi64(popcount, 32); + sumxaxis = _mm512_add_epi64(sumxaxis, sum_high); + sumxaxis = _mm512_add_epi64(sumxaxis, _mm512_slli_epi64(pop_high, 5)); + popcount = _mm512_add_epi64(popcount, pop_high); + + sum_index = _mm512_and_si512(sumxaxis, _mm512_set1_epi64(0x000000000000ffff)); + return _mm512_and_si512(popcount, _mm512_set1_epi64(0x000000000000ffff)); +} + + + +PA_FORCE_INLINE __m512i bit_reverse(__m512i x){ + x = _mm512_shuffle_epi8( + x, + _mm512_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 + ) + ); + + __m512i r0, r1; + r0 = _mm512_srli_epi32(x, 4); + r1 = _mm512_slli_epi32(x, 4); + r1 = _mm512_ternarylogic_epi64(r1, r0, _mm512_set1_epi8((uint8_t)0x0f), 0b11011000); + + r0 = _mm512_srli_epi32(r1, 2); + r1 = _mm512_slli_epi32(r1, 2); + r1 = _mm512_ternarylogic_epi64(r1, r0, _mm512_set1_epi8((uint8_t)0x33), 0b11011000); + + r0 = _mm512_srli_epi32(r1, 1); + r1 = _mm512_slli_epi32(r1, 1); + r1 = _mm512_ternarylogic_epi64(r1, r0, _mm512_set1_epi8((uint8_t)0x55), 0b11011000); + + return r1; +} + + + +PA_FORCE_INLINE void transpose_64x8x4_forward( + __m512i z0, __m512i z1, __m512i z2, __m512i z3, + __m256i& y0, __m256i& y1, __m256i& y2, __m256i& y3, __m256i& y4, __m256i& y5, __m256i& y6, __m256i& y7 +){ + __m512i s0, s1, s2, s3; + s0 = _mm512_unpacklo_epi64(z0, z1); + s1 = _mm512_unpackhi_epi64(z0, z1); + s2 = _mm512_unpacklo_epi64(z2, z3); + s3 = _mm512_unpackhi_epi64(z2, z3); + z0 = _mm512_mask_permutex_epi64(s0, 0xcc, s2, 78); + z1 = _mm512_mask_permutex_epi64(s1, 0xcc, s3, 78); + z2 = _mm512_mask_permutex_epi64(s2, 0x33, s0, 78); + z3 = _mm512_mask_permutex_epi64(s3, 0x33, s1, 78); + y0 = _mm512_castsi512_si256(z0); + y1 = _mm512_castsi512_si256(z1); + y2 = _mm512_castsi512_si256(z2); + y3 = _mm512_castsi512_si256(z3); + y4 = _mm512_extracti64x4_epi64(z0, 1); + y5 = _mm512_extracti64x4_epi64(z1, 1); + y6 = _mm512_extracti64x4_epi64(z2, 1); + y7 = _mm512_extracti64x4_epi64(z3, 1); +} +PA_FORCE_INLINE void transpose_64x8x4_inverse( + __m512i& z0, __m512i& z1, __m512i& z2, __m512i& z3, + __m256i y0, __m256i y1, __m256i y2, __m256i y3, __m256i y4, __m256i y5, __m256i y6, __m256i y7 +){ + __m512i s0, s1, s2, s3; + z0 = _mm512_inserti64x4(_mm512_castsi256_si512(y0), y4, 1); + z1 = _mm512_inserti64x4(_mm512_castsi256_si512(y1), y5, 1); + z2 = _mm512_inserti64x4(_mm512_castsi256_si512(y2), y6, 1); + z3 = _mm512_inserti64x4(_mm512_castsi256_si512(y3), y7, 1); + s0 = _mm512_mask_permutex_epi64(z0, 0xcc, z2, 78); + s1 = _mm512_mask_permutex_epi64(z1, 0xcc, z3, 78); + s2 = _mm512_mask_permutex_epi64(z2, 0x33, z0, 78); + s3 = _mm512_mask_permutex_epi64(z3, 0x33, z1, 78); + z0 = _mm512_unpacklo_epi64(s0, s1); + z1 = _mm512_unpackhi_epi64(s0, s1); + z2 = _mm512_unpacklo_epi64(s2, s3); + z3 = _mm512_unpackhi_epi64(s2, s3); +} + + + +PA_FORCE_INLINE __m512i transpose_1x8x8x8(__m512i x){ + __m512i r, L, H; + +// r = _mm512_shuffle_epi32(x, 78); + r = _mm512_shuffle_epi32(x, _MM_PERM_BADC); + L = _mm512_slli_epi64(r, 1); + H = _mm512_srli_epi64(r, 1); + r = _mm512_ternarylogic_epi64(L, H, _mm512_set1_epi8(0x55), 0xd8); + x = _mm512_ternarylogic_epi64(x, r, _mm512_setr_epi64(0xaaaaaaaaaaaaaaaa, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0x5555555555555555, 0xaaaaaaaaaaaaaaaa, 0x5555555555555555), 0xd8); + + r = _mm512_shuffle_i64x2(x, x, 177); + L = _mm512_slli_epi64(r, 2); + H = _mm512_srli_epi64(r, 2); + r = _mm512_ternarylogic_epi64(L, H, _mm512_set1_epi8(0x33), 0xd8); + x = _mm512_ternarylogic_epi64(x, r, _mm512_setr_epi64(0xcccccccccccccccc, 0xcccccccccccccccc, 0x3333333333333333, 0x3333333333333333, 0xcccccccccccccccc, 0xcccccccccccccccc, 0x3333333333333333, 0x3333333333333333), 0xd8); + + r = _mm512_shuffle_i64x2(x, x, 78); + L = _mm512_slli_epi64(r, 4); + H = _mm512_srli_epi64(r, 4); + r = _mm512_ternarylogic_epi64(L, H, _mm512_set1_epi8(0x0f), 0xd8); + x = _mm512_ternarylogic_epi64(x, r, _mm512_setr_epi64(0xf0f0f0f0f0f0f0f0, 0xf0f0f0f0f0f0f0f0, 0xf0f0f0f0f0f0f0f0, 0xf0f0f0f0f0f0f0f0, 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f), 0xd8); + + return x; +} +PA_FORCE_INLINE __m512i transpose_1x8x8x8_bitreverse_in(__m512i x){ + const __m512i INDEX = _mm512_setr_epi8( + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, + 7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8 + ); + x = _mm512_shuffle_epi8(x, INDEX); + x = transpose_1x8x8x8(x); + x = _mm512_permutexvar_epi64(_mm512_setr_epi64(7, 6, 5, 4, 3, 2, 1, 0), x); + return x; +} + +PA_FORCE_INLINE void transpose_8x2x2x4(__m512i& r0, __m512i& r1){ + __m512i s0 = r0; + r0 = _mm512_mask_alignr_epi8(r0, 0xaaaaaaaaaaaaaaaa, r1, r1, 15); + r1 = _mm512_mask_alignr_epi8(r1, 0x5555555555555555, s0, s0, 1); +} + +PA_FORCE_INLINE void transpose_16x2x2x2(__m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3){ + __m512i s0, s1; + s0 = r0; + s1 = r1; + r0 = _mm512_mask_alignr_epi8(s0, 0xcccccccccccccccc, r2, r2, 14); + r1 = _mm512_mask_alignr_epi8(s1, 0xcccccccccccccccc, r3, r3, 14); + r2 = _mm512_mask_alignr_epi8(r2, 0x3333333333333333, s0, s0, 2); + r3 = _mm512_mask_alignr_epi8(r3, 0x3333333333333333, s1, s1, 2); +} + +PA_FORCE_INLINE void transpose_1x64x32( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 +){ + r0 = transpose_1x8x8x8(r0); + r1 = transpose_1x8x8x8(r1); + r2 = transpose_1x8x8x8(r2); + r3 = transpose_1x8x8x8(r3); + transpose_8x2x2x4(r0, r1); + transpose_8x2x2x4(r2, r3); + transpose_16x2x2x2(r0, r1, r2, r3); +} +PA_FORCE_INLINE void transpose_1x64x32_bitreverse_in( + __m512i& r0, __m512i& r1, __m512i& r2, __m512i& r3 +){ + r0 = transpose_1x8x8x8_bitreverse_in(r0); + r1 = transpose_1x8x8x8_bitreverse_in(r1); + r2 = transpose_1x8x8x8_bitreverse_in(r2); + r3 = transpose_1x8x8x8_bitreverse_in(r3); + transpose_8x2x2x4(r0, r1); + transpose_8x2x2x4(r2, r3); + transpose_16x2x2x2(r0, r1, r2, r3); +} + + + +PA_FORCE_INLINE void has_neighbors(__m512i& t, __m512i x, __m512i m, __m512i mH){ + m = _mm512_ternarylogic_epi64( + _mm512_slli_epi64(m, 1), + _mm512_alignr_epi64(m, _mm512_setzero_si512(), 7), + _mm512_alignr_epi64(mH, m, 1), + 254 + ); + t = _mm512_and_si512(m, x); +} +PA_FORCE_INLINE void has_neighbors(__m512i& t, __m512i x, __m512i mL, __m512i m, __m512i mH){ + m = _mm512_ternarylogic_epi64( + _mm512_slli_epi64(m, 1), + _mm512_alignr_epi64(m, mL, 7), + _mm512_alignr_epi64(mH, m, 1), + 254 + ); +// t = _mm512_or_si512(t, _mm512_and_si512(m, x)); + t = _mm512_ternarylogic_epi64(t, m, x, 0b11111000); +} +template +PA_FORCE_INLINE bool keep_going( + const ProcessedMask& mask, + __m512i& m0, __m512i& m1, __m512i& m2, __m512i& m3, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + m0 = _mm512_andnot_si512(x0, mask.m0); + m1 = _mm512_andnot_si512(x1, mask.m1); + m2 = _mm512_andnot_si512(x2, mask.m2); + m3 = _mm512_andnot_si512(x3, mask.m3); + __m512i changed; + has_neighbors(changed, x0, m0, m1); + has_neighbors(changed, x1, m0, m1, m2); + has_neighbors(changed, x2, m1, m2, m3); + has_neighbors(changed, x3, m2, m3, _mm512_setzero_si512()); + return _mm512_test_epi64_mask(changed, changed); +} +template +PA_FORCE_INLINE bool keep_going( + const ProcessedMask& mask, + __m512i& m0, __m512i& m1, __m512i& m2, __m512i& m3, __m512i& m4, __m512i& m5, __m512i& m6, __m512i& m7, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 +){ + m0 = _mm512_andnot_si512(x0, mask.m0); + m1 = _mm512_andnot_si512(x1, mask.m1); + m2 = _mm512_andnot_si512(x2, mask.m2); + m3 = _mm512_andnot_si512(x3, mask.m3); + m4 = _mm512_andnot_si512(x4, mask.m4); + m5 = _mm512_andnot_si512(x5, mask.m5); + m6 = _mm512_andnot_si512(x6, mask.m6); + m7 = _mm512_andnot_si512(x7, mask.m7); + __m512i changed; + has_neighbors(changed, x0, m0, m1); + has_neighbors(changed, x1, m0, m1, m2); + has_neighbors(changed, x2, m1, m2, m3); + has_neighbors(changed, x3, m2, m3, m4); + has_neighbors(changed, x4, m3, m4, m5); + has_neighbors(changed, x5, m4, m5, m6); + has_neighbors(changed, x6, m5, m6, m7); + has_neighbors(changed, x7, m6, m7, _mm512_setzero_si512()); + return _mm512_test_epi64_mask(changed, changed); +} + + + +template +PA_FORCE_INLINE void expand_forward( + const ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.m0), mask.m0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.m1), mask.m1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.m2), mask.m2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.m3), mask.m3, 0b11110010); +} +template +PA_FORCE_INLINE void expand_forward( + const ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, + __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 +){ + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.m0), mask.m0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.m1), mask.m1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.m2), mask.m2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.m3), mask.m3, 0b11110010); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.m4), mask.m4, 0b11110010); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.m5), mask.m5, 0b11110010); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.m6), mask.m6, 0b11110010); + x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.m7), mask.m7, 0b11110010); +} + + +template +PA_FORCE_INLINE void expand_reverse( + const ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3 +){ + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); +} +template +PA_FORCE_INLINE void expand_reverse( + const ProcessedMask& mask, + __m512i& x0, __m512i& x1, __m512i& x2, __m512i& x3, + __m512i& x4, __m512i& x5, __m512i& x6, __m512i& x7 +){ + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); + x4 = bit_reverse(x4); + x5 = bit_reverse(x5); + x6 = bit_reverse(x6); + x7 = bit_reverse(x7); + x0 = _mm512_ternarylogic_epi64(x0, _mm512_add_epi64(x0, mask.b0), mask.b0, 0b11110010); + x1 = _mm512_ternarylogic_epi64(x1, _mm512_add_epi64(x1, mask.b1), mask.b1, 0b11110010); + x2 = _mm512_ternarylogic_epi64(x2, _mm512_add_epi64(x2, mask.b2), mask.b2, 0b11110010); + x3 = _mm512_ternarylogic_epi64(x3, _mm512_add_epi64(x3, mask.b3), mask.b3, 0b11110010); + x4 = _mm512_ternarylogic_epi64(x4, _mm512_add_epi64(x4, mask.b4), mask.b4, 0b11110010); + x5 = _mm512_ternarylogic_epi64(x5, _mm512_add_epi64(x5, mask.b5), mask.b5, 0b11110010); + x6 = _mm512_ternarylogic_epi64(x6, _mm512_add_epi64(x6, mask.b6), mask.b6, 0b11110010); + x7 = _mm512_ternarylogic_epi64(x7, _mm512_add_epi64(x7, mask.b7), mask.b7, 0b11110010); + x0 = bit_reverse(x0); + x1 = bit_reverse(x1); + x2 = bit_reverse(x2); + x3 = bit_reverse(x3); + x4 = bit_reverse(x4); + x5 = bit_reverse(x5); + x6 = bit_reverse(x6); + x7 = bit_reverse(x7); +} + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Routines.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Routines.h index 68b44c2919..44c8792d0a 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Routines.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Routines.h @@ -1,57 +1,57 @@ -/* Waterfill Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Routines_H -#define PokemonAutomation_Kernels_Waterfill_Routines_H - -#include -#include -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h" -#include "Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h" -#include "Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h" -#include "Kernels_Waterfill_Types.h" -#include "Kernels_Waterfill_Session.tpp" -#include "Kernels_Waterfill.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - - - -// Find all the objects in the matrix. This will destroy "matrix". -template -std::vector find_objects_inplace(PackedBinaryMatrixCore& matrix, size_t min_area){ - std::vector ret; - WaterfillSession_t session(matrix); - for (size_t r = 0; r < matrix.tile_height(); r++){ - for (size_t c = 0; c < matrix.tile_width(); c++){ - while (true){ - WaterfillObject object; - if (!session.find_object_in_tile(object, false, c, r)){ - break; - } - object.object.reset(); - if (object.area >= min_area){ - ret.emplace_back(object); - } - } - } - } - return ret; -} - - - - - - - -} -} -} -#endif +/* Waterfill Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Routines_H +#define PokemonAutomation_Kernels_Waterfill_Routines_H + +#include +#include +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h" +#include "Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h" +#include "Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h" +#include "Kernels_Waterfill_Types.h" +#include "Kernels_Waterfill_Session.tpp" +#include "Kernels_Waterfill.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + + + +// Find all the objects in the matrix. This will destroy "matrix". +template +std::vector find_objects_inplace(PackedBinaryMatrixCore& matrix, size_t min_area){ + std::vector ret; + WaterfillSession_t session(matrix); + for (size_t r = 0; r < matrix.tile_height(); r++){ + for (size_t c = 0; c < matrix.tile_width(); c++){ + while (true){ + WaterfillObject object; + if (!session.find_object_in_tile(object, false, c, r)){ + break; + } + object.object.reset(); + if (object.area >= min_area){ + ret.emplace_back(object); + } + } + } + } + return ret; +} + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.cpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.cpp index b82c70f589..6f512cf977 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.cpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.cpp @@ -1,113 +1,113 @@ -/* Waterfill Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Kernels_Waterfill_Routines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -std::unique_ptr make_WaterfillSession_64x4_Default (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x8_Default (PackedBinaryMatrix_IB* matrix); - -std::unique_ptr make_WaterfillSession_64x8_x64_SSE42 (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x16_x64_AVX2 (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x32_x64_AVX512 (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x32_x64_AVX512GF (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x64_x64_AVX512 (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x64_x64_AVX512GF (PackedBinaryMatrix_IB* matrix); -std::unique_ptr make_WaterfillSession_64x8_arm64_NEON (PackedBinaryMatrix_IB* matrix); - -std::unique_ptr make_WaterfillSession(){ -// cout << "make_WaterfillSession()" << endl; - - BinaryMatrixType type = get_BinaryMatrixType(); - switch (type){ -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return make_WaterfillSession_64x64_x64_AVX512GF(nullptr); - }else{ - return make_WaterfillSession_64x64_x64_AVX512(nullptr); - } - case BinaryMatrixType::i64x32_x64_AVX512: - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return make_WaterfillSession_64x32_x64_AVX512GF(nullptr); - }else{ - return make_WaterfillSession_64x32_x64_AVX512(nullptr); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return make_WaterfillSession_64x16_x64_AVX2(nullptr); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return make_WaterfillSession_64x8_x64_SSE42(nullptr); -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return make_WaterfillSession_64x8_arm64_NEON(nullptr); -#endif - case BinaryMatrixType::i64x8_Default: - return make_WaterfillSession_64x8_Default(nullptr); - case BinaryMatrixType::i64x4_Default: - return make_WaterfillSession_64x4_Default(nullptr); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} -std::unique_ptr make_WaterfillSession(PackedBinaryMatrix_IB& matrix){ -// cout << "make_WaterfillSession(PackedBinaryMatrix_IB& matrix)" << endl; - - switch (matrix.type()){ -#ifdef PA_AutoDispatch_x64_17_Skylake - case BinaryMatrixType::i64x64_x64_AVX512: - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return make_WaterfillSession_64x64_x64_AVX512GF(&matrix); - }else{ - return make_WaterfillSession_64x64_x64_AVX512(&matrix); - } - case BinaryMatrixType::i64x32_x64_AVX512: - if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ - return make_WaterfillSession_64x32_x64_AVX512GF(&matrix); - }else{ - return make_WaterfillSession_64x32_x64_AVX512(&matrix); - } -#endif -#ifdef PA_AutoDispatch_x64_13_Haswell - case BinaryMatrixType::i64x16_x64_AVX2: - return make_WaterfillSession_64x16_x64_AVX2(&matrix); -#endif -#ifdef PA_AutoDispatch_x64_08_Nehalem - case BinaryMatrixType::i64x8_x64_SSE42: - return make_WaterfillSession_64x8_x64_SSE42(&matrix); -#endif -#ifdef PA_AutoDispatch_arm64_20_M1 - case BinaryMatrixType::arm64x8_x64_NEON: - return make_WaterfillSession_64x8_arm64_NEON(&matrix); -#endif - case BinaryMatrixType::i64x8_Default: - return make_WaterfillSession_64x8_Default(&matrix); - case BinaryMatrixType::i64x4_Default: - return make_WaterfillSession_64x4_Default(&matrix); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); - } -} - - - -} -} -} +/* Waterfill Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Kernels_Waterfill_Routines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +std::unique_ptr make_WaterfillSession_64x4_Default (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x8_Default (PackedBinaryMatrix_IB* matrix); + +std::unique_ptr make_WaterfillSession_64x8_x64_SSE42 (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x16_x64_AVX2 (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x32_x64_AVX512 (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x32_x64_AVX512GF (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x64_x64_AVX512 (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x64_x64_AVX512GF (PackedBinaryMatrix_IB* matrix); +std::unique_ptr make_WaterfillSession_64x8_arm64_NEON (PackedBinaryMatrix_IB* matrix); + +std::unique_ptr make_WaterfillSession(){ +// cout << "make_WaterfillSession()" << endl; + + BinaryMatrixType type = get_BinaryMatrixType(); + switch (type){ +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return make_WaterfillSession_64x64_x64_AVX512GF(nullptr); + }else{ + return make_WaterfillSession_64x64_x64_AVX512(nullptr); + } + case BinaryMatrixType::i64x32_x64_AVX512: + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return make_WaterfillSession_64x32_x64_AVX512GF(nullptr); + }else{ + return make_WaterfillSession_64x32_x64_AVX512(nullptr); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return make_WaterfillSession_64x16_x64_AVX2(nullptr); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return make_WaterfillSession_64x8_x64_SSE42(nullptr); +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return make_WaterfillSession_64x8_arm64_NEON(nullptr); +#endif + case BinaryMatrixType::i64x8_Default: + return make_WaterfillSession_64x8_Default(nullptr); + case BinaryMatrixType::i64x4_Default: + return make_WaterfillSession_64x4_Default(nullptr); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} +std::unique_ptr make_WaterfillSession(PackedBinaryMatrix_IB& matrix){ +// cout << "make_WaterfillSession(PackedBinaryMatrix_IB& matrix)" << endl; + + switch (matrix.type()){ +#ifdef PA_AutoDispatch_x64_17_Skylake + case BinaryMatrixType::i64x64_x64_AVX512: + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return make_WaterfillSession_64x64_x64_AVX512GF(&matrix); + }else{ + return make_WaterfillSession_64x64_x64_AVX512(&matrix); + } + case BinaryMatrixType::i64x32_x64_AVX512: + if (CPU_CAPABILITY_CURRENT.OK_19_IceLake){ + return make_WaterfillSession_64x32_x64_AVX512GF(&matrix); + }else{ + return make_WaterfillSession_64x32_x64_AVX512(&matrix); + } +#endif +#ifdef PA_AutoDispatch_x64_13_Haswell + case BinaryMatrixType::i64x16_x64_AVX2: + return make_WaterfillSession_64x16_x64_AVX2(&matrix); +#endif +#ifdef PA_AutoDispatch_x64_08_Nehalem + case BinaryMatrixType::i64x8_x64_SSE42: + return make_WaterfillSession_64x8_x64_SSE42(&matrix); +#endif +#ifdef PA_AutoDispatch_arm64_20_M1 + case BinaryMatrixType::arm64x8_x64_NEON: + return make_WaterfillSession_64x8_arm64_NEON(&matrix); +#endif + case BinaryMatrixType::i64x8_Default: + return make_WaterfillSession_64x8_Default(&matrix); + case BinaryMatrixType::i64x4_Default: + return make_WaterfillSession_64x4_Default(&matrix); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unsupported tile type."); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.h index 7da54b64ed..43f8912704 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.h @@ -1,60 +1,60 @@ -/* Waterfill Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Session_H -#define PokemonAutomation_Kernels_Waterfill_Session_H - -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" -#include "Kernels_Waterfill_Types.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -class WaterfillIterator; - -// Abstract base class for doing waterfill operations -// Waterfill is finding connected components on in a binary matrix. -// The implementation is in template derived class `WaterfillSession_t`. -// It is templated to allow different implementations of SIMD code. -class WaterfillSession{ -public: - virtual ~WaterfillSession() = default; - virtual void set_source(PackedBinaryMatrix_IB& source) = 0; - - virtual std::unique_ptr make_iterator(size_t min_area) = 0; - - // Get the object at the specific bit position. - // The object will be removed from the input matrix. - // Return true if there is an object at the bit (x, y); false otherwise. - // If keep_object is true, object.object is constructed. - virtual bool find_object_on_bit( - WaterfillObject& object, bool keep_object, - size_t x, size_t y - ) = 0; - -}; -std::unique_ptr make_WaterfillSession(); -std::unique_ptr make_WaterfillSession(PackedBinaryMatrix_IB& matrix); - - - -class WaterfillIterator{ -public: - virtual ~WaterfillIterator() = default; - - // Returns false is nothing is left. - virtual bool find_next(WaterfillObject& object, bool keep_object) = 0; -}; - - - - -} -} -} -#endif +/* Waterfill Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Session_H +#define PokemonAutomation_Kernels_Waterfill_Session_H + +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" +#include "Kernels_Waterfill_Types.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +class WaterfillIterator; + +// Abstract base class for doing waterfill operations +// Waterfill is finding connected components on in a binary matrix. +// The implementation is in template derived class `WaterfillSession_t`. +// It is templated to allow different implementations of SIMD code. +class WaterfillSession{ +public: + virtual ~WaterfillSession() = default; + virtual void set_source(PackedBinaryMatrix_IB& source) = 0; + + virtual std::unique_ptr make_iterator(size_t min_area) = 0; + + // Get the object at the specific bit position. + // The object will be removed from the input matrix. + // Return true if there is an object at the bit (x, y); false otherwise. + // If keep_object is true, object.object is constructed. + virtual bool find_object_on_bit( + WaterfillObject& object, bool keep_object, + size_t x, size_t y + ) = 0; + +}; +std::unique_ptr make_WaterfillSession(); +std::unique_ptr make_WaterfillSession(PackedBinaryMatrix_IB& matrix); + + + +class WaterfillIterator{ +public: + virtual ~WaterfillIterator() = default; + + // Returns false is nothing is left. + virtual bool find_next(WaterfillObject& object, bool keep_object) = 0; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp index 2c48779819..d1780a5a81 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Session.tpp @@ -1,410 +1,410 @@ -/* Waterfill Session - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Session_TPP -#define PokemonAutomation_Kernels_Waterfill_Session_TPP - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Kernels_BitSet.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h" -#include "Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h" -#include "Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h" -#include "Kernels_Waterfill_Session.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - - -// Template that implements the waterfill algorithm. -// See abstract base class WaterfillSession for more details. -// -// Tile: the implementation of a tile made by bits. Tile width is always 64 bits (or called a word64). -// Tile is defined as struct `BinaryTile___`, e.g. `BinaryTile_64x8_x64_SSE42`. -// For each SIMD implementation, there is this tile struct defined in header file -// BinaryMatrix/Kernels_BinaryMatrixTile___.h -// -// TileRoutines: the implmentation of tile specific waterfill routines include: -// - TileRoutines::find_bit(bit_x, bit_y, tile) -// - TileRoutines::waterfill_expand(mask, tile) -// - TileRoutines::waterfill_touch_bottom(mask, tile, border) -// - TileRoutines::waterfill_touch_top(mask, tile, border) -// - TileRoutines::waterfill_touch_left(mask, tile, border) -// - TileRoutines::waterfill_touch_right(mask, tile, border) -// - TileRoutines::row_or(tile) -// - TileRoutines::popcount_sumcoord(sum_x, sum_y, tile) -// - TileRoutines::boundaries(tile, min_x, max_x, min_y, max_y) -// TileRoutines are defined as struct `Waterfill___`, e.g. `Waterfill_64x8_x64_SSE42`. -// For each SIMD implementation, there is this waterfill routine struct defined in header file -// Waterfill/Kernels_Waterfill_Core___.h -template -class WaterfillSession_t final : public WaterfillSession{ -public: - WaterfillSession_t() = default; - WaterfillSession_t(PackedBinaryMatrixCore& source) - : m_source(&source) - , m_object(source.width(), source.height()) - , m_busy_tiles(source.tile_width(), source.tile_height()) - , m_object_tiles(source.tile_width(), source.tile_height()) - {} - - void set_source(PackedBinaryMatrixCore& source){ - m_source = &source; - if (m_object.width() < source.width() || m_object.height() < source.height()){ - m_object = PackedBinaryMatrixCore(source.width(), source.height()); - m_busy_tiles = BitSet2D(source.width(), source.height()); - m_object_tiles = BitSet2D(source.width(), source.height()); - } - } - virtual void set_source(PackedBinaryMatrix_IB& source) override{ - if (source.type() != Tile::TYPE){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix format."); - } - set_source(static_cast&>(source).get()); - } - - // In matrix, how many tiles in a row - size_t tile_width() const{ return m_source->tile_width(); } - // In matrix, how many tiles in a column - size_t tile_height() const{ return m_source->tile_height(); } - - virtual std::unique_ptr make_iterator(size_t min_area) override; - - // Get the object at the specific bit position. - // The object will be removed from the input matrix. - // Return true if there is an object at the bit (x, y); false otherwise. - // If keep_object is true, object.object is constructed. - virtual bool find_object_on_bit( - WaterfillObject& object, bool keep_object, - size_t x, size_t y - ) override; - // Get the object at the specific tile (tile_x, tile_y). - // The object will be removed from the input matrix. - // Return true if there is an object at the tile; false otherwise. - // If keep_object is true, object.object is constructed. - bool find_object_in_tile( - WaterfillObject& object, bool keep_object, - size_t tile_x, size_t tile_y - ); - - -private: - // Called by both find_object_on_bit() and find_object_in_tile() - // Find the object at tile indexed as (tile_x, tile_y) and at in-tile location (bit_x, bit_y) - bool find_object( - WaterfillObject& object, bool keep_object, - size_t tile_x, size_t tile_y, - size_t bit_x, size_t bit_y - ); -#if 0 - void clear_dirty_tiles(){ - for (auto tile : m_dirty_tiles){ - m_object.tile(tile.first, tile.second).set_zero(); - } - m_dirty_tiles.clear(); - } -#endif - - -private: - // Source matrix. This is zeroed as objects are found. - PackedBinaryMatrixCore* m_source = nullptr; - - // Current object. - PackedBinaryMatrixCore m_object; -// std::vector> m_dirty_tiles; - - // Reused scratch buffers. Only used inside "find_object()". - BitSet2D m_busy_tiles; - BitSet2D m_object_tiles; -}; - - - - -template -class WaterfillIterator_t final : public WaterfillIterator{ -public: - WaterfillIterator_t(WaterfillSession_t& session, size_t min_area) - : m_session(session) - , m_min_area(min_area) - {} - virtual bool find_next(WaterfillObject& object, bool keep_object) override; - -private: - WaterfillSession_t& m_session; - size_t m_min_area; - size_t m_tile_row = 0; - size_t m_tile_col = 0; -}; - - - - - -template -std::unique_ptr WaterfillSession_t::make_iterator(size_t min_area){ - return std::make_unique>(*this, min_area); -} - - -template -bool WaterfillSession_t::find_object_on_bit( - WaterfillObject& object, bool keep_object, - size_t x, size_t y -){ - // If (x,y) is 0, no object - if (!m_source->get(x, y)){ - return false; - } - - std::set busy; - std::map obj; - - size_t tile_x = x / PackedBinaryMatrixCore::Tile::WIDTH; - size_t tile_y = y / PackedBinaryMatrixCore::Tile::HEIGHT; - size_t bit_x = x % PackedBinaryMatrixCore::Tile::WIDTH; - size_t bit_y = y % PackedBinaryMatrixCore::Tile::HEIGHT; - - return find_object(object, keep_object, tile_x, tile_y, bit_x, bit_y); -} - -template -bool WaterfillSession_t::find_object_in_tile( - WaterfillObject& object, bool keep_object, - size_t tile_x, size_t tile_y -){ - Tile& start = m_source->tile(tile_x, tile_y); - - size_t bit_x, bit_y; - if (!TileRoutines::find_bit(bit_x, bit_y, start)){ - return false; - } - - return find_object(object, keep_object, tile_x, tile_y, bit_x, bit_y); -} - - -template -bool WaterfillSession_t::find_object( - WaterfillObject& object, bool keep_object, - size_t tile_x, size_t tile_y, - size_t bit_x, size_t bit_y -){ -// clear_dirty_tiles(); - - // How many tiles in a row - size_t tile_width = m_source->tile_width(); - // How many tiles in a column - size_t tile_height = m_source->tile_height(); - - // Set first tile. - size_t x = tile_x; - size_t y = tile_y; - m_busy_tiles.set(x, y); - m_object_tiles.set(x, y); - m_object.tile(x, y).set_bit(bit_x, bit_y); - - // Special case for isolated bit. - // `first_expand` is set to true if there are 4-nbring 1-bits next to the starting bit, i.e the - // starting bit is not isolated. - bool first_expand = true; -#if 1 - { - // top edge: whether the starting bit (bit_x, bit_y) is at the top edge of the tile - bool top_edge = bit_y == 0; - bool bottom_edge = bit_y == Tile::HEIGHT - 1; -// bool left_edge = bit_x == 0; -// bool right_edge = bit_x == Tile::WIDTH - 1; - - Tile& tile = m_source->tile(x, y); - uint64_t rowC = tile.row(bit_y); // row "C"urrent - uint64_t rowA = top_edge ? 0 : tile.row(bit_y - 1); // row "A"bove - uint64_t rowB = bottom_edge ? 0 : tile.row(bit_y + 1); // row "B"elow - // Find that within this tile, whether thera are any 4-nbring bits that are also 1. - uint64_t test = rowA | rowB | (rowC << 1) | (rowC >> 1); - test &= (uint64_t)1 << bit_x; - - first_expand = test; - } -#endif - - // Iterate Waterfill... - while (m_busy_tiles.pop(x, y)){ - // Get the next tile at index (x, y) - Tile& source_mask = m_source->tile(x, y); - Tile& recorded_tile = m_object.tile(x, y); - - // Expand current tile. - if (first_expand){ - // expand found object `recorded_tile`'s bits according to source tile `source_mask` - TileRoutines::waterfill_expand(source_mask, recorded_tile); - }else{ - // source_mask = (NOT tile) AND source_mask - // Delete the bits on source tile `source_mask` that are already found (and recorded in `recorded_tile`) - // In this way we won't enter an infinite loop of discovering old visited bits from `source_mask`. - source_mask.andnot(recorded_tile); - } - first_expand = true; - - size_t current_x, current_y; - // If we have a top nbr tile and the current found bits reach the top row of the current tile - // waterfill into the top nbr tile - if (y > 0 && recorded_tile.top() != 0){ - current_y = y - 1; - const Tile& neighbor_mask = m_source->tile(x, current_y); - if (TileRoutines::waterfill_touch_bottom(neighbor_mask, m_object.tile(x, current_y), recorded_tile)){ - m_busy_tiles.set(x, current_y); - m_object_tiles.set(x, current_y); - } - } - // If we have a bottom nbr tile and the current found bits reach the bottom row of the current tile - // waterfill into the bottom nbr tile - current_y = y + 1; - if (current_y < tile_height && recorded_tile.bottom() != 0){ - const Tile& neighbor_mask = m_source->tile(x, current_y); - if (TileRoutines::waterfill_touch_top(neighbor_mask, m_object.tile(x, current_y), recorded_tile)){ - m_busy_tiles.set(x, current_y); - m_object_tiles.set(x, current_y); - } - } - // logical OR each row in `recorded_tile` together - uint64_t row_or = TileRoutines::row_or(recorded_tile); - // If we have a left nbr tile and the current found bits reach the left-most column of the current tile - // waterfill into the left nbr tile - if (x > 0 && (row_or & 1)){ - current_x = x - 1; - const Tile& neighbor_mask = m_source->tile(current_x, y); - if (TileRoutines::waterfill_touch_right(neighbor_mask, m_object.tile(current_x, y), recorded_tile)){ - m_busy_tiles.set(current_x, y); - m_object_tiles.set(current_x, y); - } - } - // If we have a right nbr tile and the current found bits reach the right-most column of the current tile - // waterfill into the right nbr tile - current_x = x + 1; - const uint64_t MASK = (uint64_t)1 << (Tile::WIDTH - 1); - if (current_x < tile_width && (row_or & MASK)){ - const Tile& neighbor_mask = m_source->tile(current_x, y); - if (TileRoutines::waterfill_touch_left(neighbor_mask, m_object.tile(current_x, y), recorded_tile)){ - m_busy_tiles.set(current_x, y); - m_object_tiles.set(current_x, y); - } - } - } - - // Compute stats. - size_t tile_min_x = SIZE_MAX; // (size_t)0 - 1 - size_t tile_min_y = SIZE_MAX; - size_t tile_max_x = 0; - size_t tile_max_y = 0; - - WaterfillObject stats; - stats.body_x = tile_x * Tile::WIDTH + bit_x; - stats.body_y = tile_y * Tile::HEIGHT + bit_y; - - std::unique_ptr> sparse_set; - if (keep_object){ - sparse_set = std::make_unique>(); - } - - while (m_object_tiles.pop(x, y)){ -// m_dirty_tiles.emplace_back(x, y); - Tile& recorded_tile = m_object.tile(x, y); - - if (sparse_set){ - (*sparse_set)[TileIndex{x, y}] = recorded_tile; - } - - // Get sum of (x,y) location of the 1-bits in the tile into (sum_x, sum_y) - // and get the count of 1-bits in the tile into `popcount`. - uint64_t popcount, sum_x, sum_y; - popcount = TileRoutines::popcount_sumcoord(sum_x, sum_y, recorded_tile); -// if (popcount == 7 && tile_x == 16 && tile_y == 73){ -// cout << popcount << ", " << sum_x << ", " << sum_y << endl; -// cout << item.second.dump() << endl; -// } - stats.accumulate_body( - x * Tile::WIDTH, y * Tile::HEIGHT, - popcount, sum_x, sum_y - ); - if (!(tile_min_x < x && x < tile_max_x && tile_min_y < y && y < tile_max_y)){ - // Get the min max of the 1-bits locations in the tile - size_t cmin_x, cmax_x, cmin_y, cmax_y; - TileRoutines::boundaries(recorded_tile, cmin_x, cmax_x, cmin_y, cmax_y); - stats.accumulate_boundary( - x * Tile::WIDTH, y * Tile::HEIGHT, - cmin_x, cmax_x, cmin_y, cmax_y - ); - } - tile_min_x = std::min(tile_min_x, x); - tile_max_x = std::max(tile_max_x, x); - tile_min_y = std::min(tile_min_y, y); - tile_max_y = std::max(tile_max_y, y); - - recorded_tile.set_zero(); - } - -#if 0 - cout << "x = (" << stats.m_min_x << "," << stats.m_max_x << ")" << endl; - cout << "y = (" << stats.m_min_y << "," << stats.m_max_y << ")" << endl; - cout << "area = " << stats.m_area << endl; - cout << "sum x = " << stats.m_sum_x << endl; - cout << "sum y = " << stats.m_sum_y << endl; -#endif - - object = stats; - - if (sparse_set){ - auto ptr = std::make_unique>(m_source->width(), m_source->height()); - ptr->get().set_data(std::move(*sparse_set)); - object.object = std::move(ptr); - } - - return true; -} - - - - -template -bool WaterfillIterator_t::find_next(WaterfillObject& object, bool keep_object){ - while (m_tile_row < m_session.tile_height()){ - while (m_tile_col < m_session.tile_width()){ - while (true){ - // Not object found. Move to next tile. - if (!m_session.find_object_in_tile(object, keep_object, m_tile_col, m_tile_row)){ - break; - } - // Object too small. Skip it. - if (object.area < m_min_area){ - continue; - } - return true; - } - m_tile_col++; - } - m_tile_col = 0; - m_tile_row++; - } - return false; -} - - - - - -} -} -} -#endif +/* Waterfill Session + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Session_TPP +#define PokemonAutomation_Kernels_Waterfill_Session_TPP + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Kernels_BitSet.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_t.h" +#include "Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h" +#include "Kernels/BinaryMatrix/Kernels_SparseBinaryMatrixCore.h" +#include "Kernels_Waterfill_Session.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + + +// Template that implements the waterfill algorithm. +// See abstract base class WaterfillSession for more details. +// +// Tile: the implementation of a tile made by bits. Tile width is always 64 bits (or called a word64). +// Tile is defined as struct `BinaryTile___`, e.g. `BinaryTile_64x8_x64_SSE42`. +// For each SIMD implementation, there is this tile struct defined in header file +// BinaryMatrix/Kernels_BinaryMatrixTile___.h +// +// TileRoutines: the implmentation of tile specific waterfill routines include: +// - TileRoutines::find_bit(bit_x, bit_y, tile) +// - TileRoutines::waterfill_expand(mask, tile) +// - TileRoutines::waterfill_touch_bottom(mask, tile, border) +// - TileRoutines::waterfill_touch_top(mask, tile, border) +// - TileRoutines::waterfill_touch_left(mask, tile, border) +// - TileRoutines::waterfill_touch_right(mask, tile, border) +// - TileRoutines::row_or(tile) +// - TileRoutines::popcount_sumcoord(sum_x, sum_y, tile) +// - TileRoutines::boundaries(tile, min_x, max_x, min_y, max_y) +// TileRoutines are defined as struct `Waterfill___`, e.g. `Waterfill_64x8_x64_SSE42`. +// For each SIMD implementation, there is this waterfill routine struct defined in header file +// Waterfill/Kernels_Waterfill_Core___.h +template +class WaterfillSession_t final : public WaterfillSession{ +public: + WaterfillSession_t() = default; + WaterfillSession_t(PackedBinaryMatrixCore& source) + : m_source(&source) + , m_object(source.width(), source.height()) + , m_busy_tiles(source.tile_width(), source.tile_height()) + , m_object_tiles(source.tile_width(), source.tile_height()) + {} + + void set_source(PackedBinaryMatrixCore& source){ + m_source = &source; + if (m_object.width() < source.width() || m_object.height() < source.height()){ + m_object = PackedBinaryMatrixCore(source.width(), source.height()); + m_busy_tiles = BitSet2D(source.width(), source.height()); + m_object_tiles = BitSet2D(source.width(), source.height()); + } + } + virtual void set_source(PackedBinaryMatrix_IB& source) override{ + if (source.type() != Tile::TYPE){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Mismatching matrix format."); + } + set_source(static_cast&>(source).get()); + } + + // In matrix, how many tiles in a row + size_t tile_width() const{ return m_source->tile_width(); } + // In matrix, how many tiles in a column + size_t tile_height() const{ return m_source->tile_height(); } + + virtual std::unique_ptr make_iterator(size_t min_area) override; + + // Get the object at the specific bit position. + // The object will be removed from the input matrix. + // Return true if there is an object at the bit (x, y); false otherwise. + // If keep_object is true, object.object is constructed. + virtual bool find_object_on_bit( + WaterfillObject& object, bool keep_object, + size_t x, size_t y + ) override; + // Get the object at the specific tile (tile_x, tile_y). + // The object will be removed from the input matrix. + // Return true if there is an object at the tile; false otherwise. + // If keep_object is true, object.object is constructed. + bool find_object_in_tile( + WaterfillObject& object, bool keep_object, + size_t tile_x, size_t tile_y + ); + + +private: + // Called by both find_object_on_bit() and find_object_in_tile() + // Find the object at tile indexed as (tile_x, tile_y) and at in-tile location (bit_x, bit_y) + bool find_object( + WaterfillObject& object, bool keep_object, + size_t tile_x, size_t tile_y, + size_t bit_x, size_t bit_y + ); +#if 0 + void clear_dirty_tiles(){ + for (auto tile : m_dirty_tiles){ + m_object.tile(tile.first, tile.second).set_zero(); + } + m_dirty_tiles.clear(); + } +#endif + + +private: + // Source matrix. This is zeroed as objects are found. + PackedBinaryMatrixCore* m_source = nullptr; + + // Current object. + PackedBinaryMatrixCore m_object; +// std::vector> m_dirty_tiles; + + // Reused scratch buffers. Only used inside "find_object()". + BitSet2D m_busy_tiles; + BitSet2D m_object_tiles; +}; + + + + +template +class WaterfillIterator_t final : public WaterfillIterator{ +public: + WaterfillIterator_t(WaterfillSession_t& session, size_t min_area) + : m_session(session) + , m_min_area(min_area) + {} + virtual bool find_next(WaterfillObject& object, bool keep_object) override; + +private: + WaterfillSession_t& m_session; + size_t m_min_area; + size_t m_tile_row = 0; + size_t m_tile_col = 0; +}; + + + + + +template +std::unique_ptr WaterfillSession_t::make_iterator(size_t min_area){ + return std::make_unique>(*this, min_area); +} + + +template +bool WaterfillSession_t::find_object_on_bit( + WaterfillObject& object, bool keep_object, + size_t x, size_t y +){ + // If (x,y) is 0, no object + if (!m_source->get(x, y)){ + return false; + } + + std::set busy; + std::map obj; + + size_t tile_x = x / PackedBinaryMatrixCore::Tile::WIDTH; + size_t tile_y = y / PackedBinaryMatrixCore::Tile::HEIGHT; + size_t bit_x = x % PackedBinaryMatrixCore::Tile::WIDTH; + size_t bit_y = y % PackedBinaryMatrixCore::Tile::HEIGHT; + + return find_object(object, keep_object, tile_x, tile_y, bit_x, bit_y); +} + +template +bool WaterfillSession_t::find_object_in_tile( + WaterfillObject& object, bool keep_object, + size_t tile_x, size_t tile_y +){ + Tile& start = m_source->tile(tile_x, tile_y); + + size_t bit_x, bit_y; + if (!TileRoutines::find_bit(bit_x, bit_y, start)){ + return false; + } + + return find_object(object, keep_object, tile_x, tile_y, bit_x, bit_y); +} + + +template +bool WaterfillSession_t::find_object( + WaterfillObject& object, bool keep_object, + size_t tile_x, size_t tile_y, + size_t bit_x, size_t bit_y +){ +// clear_dirty_tiles(); + + // How many tiles in a row + size_t tile_width = m_source->tile_width(); + // How many tiles in a column + size_t tile_height = m_source->tile_height(); + + // Set first tile. + size_t x = tile_x; + size_t y = tile_y; + m_busy_tiles.set(x, y); + m_object_tiles.set(x, y); + m_object.tile(x, y).set_bit(bit_x, bit_y); + + // Special case for isolated bit. + // `first_expand` is set to true if there are 4-nbring 1-bits next to the starting bit, i.e the + // starting bit is not isolated. + bool first_expand = true; +#if 1 + { + // top edge: whether the starting bit (bit_x, bit_y) is at the top edge of the tile + bool top_edge = bit_y == 0; + bool bottom_edge = bit_y == Tile::HEIGHT - 1; +// bool left_edge = bit_x == 0; +// bool right_edge = bit_x == Tile::WIDTH - 1; + + Tile& tile = m_source->tile(x, y); + uint64_t rowC = tile.row(bit_y); // row "C"urrent + uint64_t rowA = top_edge ? 0 : tile.row(bit_y - 1); // row "A"bove + uint64_t rowB = bottom_edge ? 0 : tile.row(bit_y + 1); // row "B"elow + // Find that within this tile, whether thera are any 4-nbring bits that are also 1. + uint64_t test = rowA | rowB | (rowC << 1) | (rowC >> 1); + test &= (uint64_t)1 << bit_x; + + first_expand = test; + } +#endif + + // Iterate Waterfill... + while (m_busy_tiles.pop(x, y)){ + // Get the next tile at index (x, y) + Tile& source_mask = m_source->tile(x, y); + Tile& recorded_tile = m_object.tile(x, y); + + // Expand current tile. + if (first_expand){ + // expand found object `recorded_tile`'s bits according to source tile `source_mask` + TileRoutines::waterfill_expand(source_mask, recorded_tile); + }else{ + // source_mask = (NOT tile) AND source_mask + // Delete the bits on source tile `source_mask` that are already found (and recorded in `recorded_tile`) + // In this way we won't enter an infinite loop of discovering old visited bits from `source_mask`. + source_mask.andnot(recorded_tile); + } + first_expand = true; + + size_t current_x, current_y; + // If we have a top nbr tile and the current found bits reach the top row of the current tile + // waterfill into the top nbr tile + if (y > 0 && recorded_tile.top() != 0){ + current_y = y - 1; + const Tile& neighbor_mask = m_source->tile(x, current_y); + if (TileRoutines::waterfill_touch_bottom(neighbor_mask, m_object.tile(x, current_y), recorded_tile)){ + m_busy_tiles.set(x, current_y); + m_object_tiles.set(x, current_y); + } + } + // If we have a bottom nbr tile and the current found bits reach the bottom row of the current tile + // waterfill into the bottom nbr tile + current_y = y + 1; + if (current_y < tile_height && recorded_tile.bottom() != 0){ + const Tile& neighbor_mask = m_source->tile(x, current_y); + if (TileRoutines::waterfill_touch_top(neighbor_mask, m_object.tile(x, current_y), recorded_tile)){ + m_busy_tiles.set(x, current_y); + m_object_tiles.set(x, current_y); + } + } + // logical OR each row in `recorded_tile` together + uint64_t row_or = TileRoutines::row_or(recorded_tile); + // If we have a left nbr tile and the current found bits reach the left-most column of the current tile + // waterfill into the left nbr tile + if (x > 0 && (row_or & 1)){ + current_x = x - 1; + const Tile& neighbor_mask = m_source->tile(current_x, y); + if (TileRoutines::waterfill_touch_right(neighbor_mask, m_object.tile(current_x, y), recorded_tile)){ + m_busy_tiles.set(current_x, y); + m_object_tiles.set(current_x, y); + } + } + // If we have a right nbr tile and the current found bits reach the right-most column of the current tile + // waterfill into the right nbr tile + current_x = x + 1; + const uint64_t MASK = (uint64_t)1 << (Tile::WIDTH - 1); + if (current_x < tile_width && (row_or & MASK)){ + const Tile& neighbor_mask = m_source->tile(current_x, y); + if (TileRoutines::waterfill_touch_left(neighbor_mask, m_object.tile(current_x, y), recorded_tile)){ + m_busy_tiles.set(current_x, y); + m_object_tiles.set(current_x, y); + } + } + } + + // Compute stats. + size_t tile_min_x = SIZE_MAX; // (size_t)0 - 1 + size_t tile_min_y = SIZE_MAX; + size_t tile_max_x = 0; + size_t tile_max_y = 0; + + WaterfillObject stats; + stats.body_x = tile_x * Tile::WIDTH + bit_x; + stats.body_y = tile_y * Tile::HEIGHT + bit_y; + + std::unique_ptr> sparse_set; + if (keep_object){ + sparse_set = std::make_unique>(); + } + + while (m_object_tiles.pop(x, y)){ +// m_dirty_tiles.emplace_back(x, y); + Tile& recorded_tile = m_object.tile(x, y); + + if (sparse_set){ + (*sparse_set)[TileIndex{x, y}] = recorded_tile; + } + + // Get sum of (x,y) location of the 1-bits in the tile into (sum_x, sum_y) + // and get the count of 1-bits in the tile into `popcount`. + uint64_t popcount, sum_x, sum_y; + popcount = TileRoutines::popcount_sumcoord(sum_x, sum_y, recorded_tile); +// if (popcount == 7 && tile_x == 16 && tile_y == 73){ +// cout << popcount << ", " << sum_x << ", " << sum_y << endl; +// cout << item.second.dump() << endl; +// } + stats.accumulate_body( + x * Tile::WIDTH, y * Tile::HEIGHT, + popcount, sum_x, sum_y + ); + if (!(tile_min_x < x && x < tile_max_x && tile_min_y < y && y < tile_max_y)){ + // Get the min max of the 1-bits locations in the tile + size_t cmin_x, cmax_x, cmin_y, cmax_y; + TileRoutines::boundaries(recorded_tile, cmin_x, cmax_x, cmin_y, cmax_y); + stats.accumulate_boundary( + x * Tile::WIDTH, y * Tile::HEIGHT, + cmin_x, cmax_x, cmin_y, cmax_y + ); + } + tile_min_x = std::min(tile_min_x, x); + tile_max_x = std::max(tile_max_x, x); + tile_min_y = std::min(tile_min_y, y); + tile_max_y = std::max(tile_max_y, y); + + recorded_tile.set_zero(); + } + +#if 0 + cout << "x = (" << stats.m_min_x << "," << stats.m_max_x << ")" << endl; + cout << "y = (" << stats.m_min_y << "," << stats.m_max_y << ")" << endl; + cout << "area = " << stats.m_area << endl; + cout << "sum x = " << stats.m_sum_x << endl; + cout << "sum y = " << stats.m_sum_y << endl; +#endif + + object = stats; + + if (sparse_set){ + auto ptr = std::make_unique>(m_source->width(), m_source->height()); + ptr->get().set_data(std::move(*sparse_set)); + object.object = std::move(ptr); + } + + return true; +} + + + + +template +bool WaterfillIterator_t::find_next(WaterfillObject& object, bool keep_object){ + while (m_tile_row < m_session.tile_height()){ + while (m_tile_col < m_session.tile_width()){ + while (true){ + // Not object found. Move to next tile. + if (!m_session.find_object_in_tile(object, keep_object, m_tile_col, m_tile_row)){ + break; + } + // Object too small. Skip it. + if (object.area < m_min_area){ + continue; + } + return true; + } + m_tile_col++; + } + m_tile_col = 0; + m_tile_row++; + } + return false; +} + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Types.h b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Types.h index a40e85efc5..f842ebb712 100644 --- a/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Types.h +++ b/SerialPrograms/Source/Kernels/Waterfill/Kernels_Waterfill_Types.h @@ -1,137 +1,137 @@ -/* Waterfill Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Kernels_Waterfill_Types_H -#define PokemonAutomation_Kernels_Waterfill_Types_H - -#include -#include -#include "Common/Cpp/Rectangle.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - - -class WaterfillIterator; - -// An object in the waterfill session. -// Objects are represented as non-zero bits on the size of an image. -class WaterfillObject{ -public: - WaterfillObject(WaterfillObject&& x) = default; - WaterfillObject& operator=(WaterfillObject&& x) = default; - WaterfillObject(const WaterfillObject& x){ - *this = x; - } - void operator=(const WaterfillObject& x){ - body_x = x.body_x; - body_y = x.body_y; - min_x = x.min_x; - min_y = x.min_y; - max_x = x.max_x; - max_y = x.max_y; - area = x.area; - sum_x = x.sum_x; - sum_y = x.sum_y; - if (x.object){ - object = x.object->clone(); - } - } - -public: - WaterfillObject() = default; - - size_t width() const{ return max_x - min_x; } - size_t height() const{ return max_y - min_y; } - - double center_of_gravity_x() const{ return (double)sum_x / area; } - double center_of_gravity_y() const{ return (double)sum_y / area; } - - double aspect_ratio() const{ return (double)width() / height(); } - double area_ratio() const{ return (double)area / (width() * height()); } - - Rectangle rectangle() const{ - return Rectangle(min_x, min_y, max_x, max_y); - } - - // Note: `object` must be constructed before calling this function. - std::unique_ptr packed_matrix() const{ - return object->submatrix(min_x, min_y, max_x - min_x, max_y - min_y); - } - - void merge_assume_no_overlap(const WaterfillObject& obj){ - if (obj.area == 0){ - return; - } - if (area == 0){ - *this = obj; - return; - } - min_x = std::min(min_x, obj.min_x); - min_y = std::min(min_y, obj.min_y); - max_x = std::max(max_x, obj.max_x); - max_y = std::max(max_y, obj.max_y); - area += obj.area; - sum_x += obj.sum_x; - sum_y += obj.sum_y; - if (object && obj.object){ - *object |= *obj.object; - } - } - - -public: - void accumulate_body( - size_t offset_x, size_t offset_y, - size_t popcount, - uint64_t tile_sum_x, uint64_t tile_sum_y - ){ - area += popcount; - sum_x += (uint64_t)offset_x * popcount + tile_sum_x; - sum_y += (uint64_t)offset_y * popcount + tile_sum_y; - } - void accumulate_boundary( - size_t offset_x, size_t offset_y, - size_t tile_min_x, size_t tile_max_x, - size_t tile_min_y, size_t tile_max_y - ){ - min_x = std::min(min_x, offset_x + tile_min_x); - min_y = std::min(min_y, offset_y + tile_min_y); - max_x = std::max(max_x, offset_x + tile_max_x); - max_y = std::max(max_y, offset_y + tile_max_y); - } - - -public: - // The coordinates of any part of the body of this object. - size_t body_x = 0; - size_t body_y = 0; - - // Enclosing rectangle. (max is one past the end) - size_t min_x = (size_t)0 - 1; - size_t min_y = (size_t)0 - 1; - size_t max_x = 0; - size_t max_y = 0; - - // Number of bits in this object. (the popcount) - size_t area = 0; - - // These divided by "m_area" is the center of gravity. - uint64_t sum_x = 0; - uint64_t sum_y = 0; - - std::unique_ptr object; -}; - - - - -} -} -} -#endif +/* Waterfill Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Kernels_Waterfill_Types_H +#define PokemonAutomation_Kernels_Waterfill_Types_H + +#include +#include +#include "Common/Cpp/Rectangle.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + + +class WaterfillIterator; + +// An object in the waterfill session. +// Objects are represented as non-zero bits on the size of an image. +class WaterfillObject{ +public: + WaterfillObject(WaterfillObject&& x) = default; + WaterfillObject& operator=(WaterfillObject&& x) = default; + WaterfillObject(const WaterfillObject& x){ + *this = x; + } + void operator=(const WaterfillObject& x){ + body_x = x.body_x; + body_y = x.body_y; + min_x = x.min_x; + min_y = x.min_y; + max_x = x.max_x; + max_y = x.max_y; + area = x.area; + sum_x = x.sum_x; + sum_y = x.sum_y; + if (x.object){ + object = x.object->clone(); + } + } + +public: + WaterfillObject() = default; + + size_t width() const{ return max_x - min_x; } + size_t height() const{ return max_y - min_y; } + + double center_of_gravity_x() const{ return (double)sum_x / area; } + double center_of_gravity_y() const{ return (double)sum_y / area; } + + double aspect_ratio() const{ return (double)width() / height(); } + double area_ratio() const{ return (double)area / (width() * height()); } + + Rectangle rectangle() const{ + return Rectangle(min_x, min_y, max_x, max_y); + } + + // Note: `object` must be constructed before calling this function. + std::unique_ptr packed_matrix() const{ + return object->submatrix(min_x, min_y, max_x - min_x, max_y - min_y); + } + + void merge_assume_no_overlap(const WaterfillObject& obj){ + if (obj.area == 0){ + return; + } + if (area == 0){ + *this = obj; + return; + } + min_x = std::min(min_x, obj.min_x); + min_y = std::min(min_y, obj.min_y); + max_x = std::max(max_x, obj.max_x); + max_y = std::max(max_y, obj.max_y); + area += obj.area; + sum_x += obj.sum_x; + sum_y += obj.sum_y; + if (object && obj.object){ + *object |= *obj.object; + } + } + + +public: + void accumulate_body( + size_t offset_x, size_t offset_y, + size_t popcount, + uint64_t tile_sum_x, uint64_t tile_sum_y + ){ + area += popcount; + sum_x += (uint64_t)offset_x * popcount + tile_sum_x; + sum_y += (uint64_t)offset_y * popcount + tile_sum_y; + } + void accumulate_boundary( + size_t offset_x, size_t offset_y, + size_t tile_min_x, size_t tile_max_x, + size_t tile_min_y, size_t tile_max_y + ){ + min_x = std::min(min_x, offset_x + tile_min_x); + min_y = std::min(min_y, offset_y + tile_min_y); + max_x = std::max(max_x, offset_x + tile_max_x); + max_y = std::max(max_y, offset_y + tile_max_y); + } + + +public: + // The coordinates of any part of the body of this object. + size_t body_x = 0; + size_t body_y = 0; + + // Enclosing rectangle. (max is one past the end) + size_t min_x = (size_t)0 - 1; + size_t min_y = (size_t)0 - 1; + size_t max_x = 0; + size_t max_y = 0; + + // Number of bits in this object. (the popcount) + size_t area = 0; + + // These divided by "m_area" is the center of gravity. + uint64_t sum_x = 0; + uint64_t sum_y = 0; + + std::unique_ptr object; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp b/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp index 3ea6bed00d..7b6777b5ba 100644 --- a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp +++ b/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.cpp @@ -1,250 +1,250 @@ -/* ML Segment Anything Model - * - * From: https://github.com/PokemonAutomation/ - * - * Run Segment Anything Model (SAM) to segment objects on images - */ - -#include -#include -#include -#include -#include "3rdParty/ONNX/OnnxToolsPA.h" -#include "SegmentAnythingModel.h" - -namespace PokemonAutomation{ -namespace ML{ - - - - -const int SAM_EMBEDDER_INPUT_IMAGE_WIDTH = 1024; -const int SAM_EMBEDDER_INPUT_IMAGE_HEIGHT = 576; -const int SAM_EMBEDDER_OUTPUT_N_CHANNELS = 256; -const int SAM_EMBEDDER_OUTPUT_IMAGE_SIZE = 64; - -const int SAM_EMBEDDER_INPUT_SIZE = SAM_EMBEDDER_INPUT_IMAGE_HEIGHT * SAM_EMBEDDER_INPUT_IMAGE_WIDTH * 3; -const int SAM_EMBEDDER_OUTPUT_SIZE = SAM_EMBEDDER_OUTPUT_N_CHANNELS * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE; - -const int SAM_N_INPUT_TENSORS = 6; -const int SAM_N_OUTPUT_TENSORS = 3; -const int SAM_LOW_RES_MASK_SIZE = 256; -const float SAM_OUTPUT_MASK_THRESHOLD = 0.0; - - -Ort::SessionOptions create_session_option(){ - return Ort::SessionOptions{}; - - // create session using Apple ML - - // Ort::SessionOptions so; - // std::unordered_map provider_options; - // provider_options["ModelFormat"] = "NeuralNetwork"; - // so.AppendExecutionProvider("CoreML", provider_options); - // return so; -} - - -template Ort::Value create_tensor(const OrtMemoryInfo* memory_info, Buffer& buffer, const Shape& shape){ - return Ort::Value::CreateTensor(memory_info, buffer.data(), buffer.size(), - shape.data(), shape.size()); -} - - -SAMEmbedderSession::SAMEmbedderSession(const std::string& model_path) - : session_options(create_session_option()) - , session{env, str_to_onnx_str(model_path).c_str(), session_options} - , memory_info{Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU)} - , input_names{session.GetInputNames()} - , output_names{session.GetOutputNames()} - , input_shape{1, SAM_EMBEDDER_INPUT_IMAGE_HEIGHT, SAM_EMBEDDER_INPUT_IMAGE_WIDTH, 3} - , output_shape{1, SAM_EMBEDDER_OUTPUT_N_CHANNELS, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE} - , model_input(SAM_EMBEDDER_INPUT_SIZE) -{ - std::cout << "Built SAM embedder session" << std::endl; -} - -void SAMEmbedderSession::run(cv::Mat& input_image, std::vector& model_output){ - assert(input_image.rows == SAM_EMBEDDER_INPUT_IMAGE_HEIGHT); - assert(input_image.cols == SAM_EMBEDDER_INPUT_IMAGE_WIDTH); - - model_output.resize(SAM_EMBEDDER_OUTPUT_SIZE); - auto input_tensor = create_tensor(memory_info, model_input, input_shape); - auto output_tensor = create_tensor(memory_info, model_output, output_shape); - - for (int row = 0, p_loc=0; row < SAM_EMBEDDER_INPUT_IMAGE_HEIGHT; row++){ - for(int col = 0; col < SAM_EMBEDDER_INPUT_IMAGE_WIDTH; col++){ - cv::Vec3b p = input_image.at(row, col); - model_input[p_loc++] = p[0]; - model_input[p_loc++] = p[1]; - model_input[p_loc++] = p[2]; - } - } - - const char* input_name_c = input_names[0].data(); - const char* output_name_c = output_names[0].data(); - auto start = std::chrono::steady_clock::now(); - session.Run(run_options, &input_name_c, &input_tensor, 1, &output_name_c, &output_tensor, 1); - auto end = std::chrono::steady_clock::now(); - auto milliseconds = std::chrono::duration_cast(end - start).count(); - std::cout << "Embedder inference time: " << milliseconds << " ms" << std::endl; -} - - -SAMSession::SAMSession(const std::string& model_path) - : session_options(create_session_option()) - , session{env, str_to_onnx_str(model_path).c_str(), session_options} - , memory_info{Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU)} - , input_names{session.GetInputNames()} - , output_names{session.GetOutputNames()} - , input_image_embedding_shape{1, SAM_EMBEDDER_OUTPUT_N_CHANNELS, - SAM_EMBEDDER_OUTPUT_IMAGE_SIZE, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE} - , input_mask_shape{1, 1, SAM_LOW_RES_MASK_SIZE, SAM_LOW_RES_MASK_SIZE} - , output_low_res_mask_shape{1, 1, SAM_LOW_RES_MASK_SIZE, SAM_LOW_RES_MASK_SIZE} - , input_mask_buffer(SAM_LOW_RES_MASK_SIZE * SAM_LOW_RES_MASK_SIZE, 0.0) - , output_low_res_mask_buffer(SAM_LOW_RES_MASK_SIZE * SAM_LOW_RES_MASK_SIZE, 0.0) -{ - std::cout << "Built SAM session" << std::endl; -} - -void SAMSession::run( - std::vector& image_embedding, - int original_image_height, int original_image_width, - const std::vector& input_points, - const std::vector& input_point_labels, - const std::vector& input_box, - std::vector& output_boolean_mask -){ - assert(image_embedding.size() == SAM_EMBEDDER_OUTPUT_SIZE); - assert(input_points.size() % 2 == 0); - assert(input_point_labels.size() == input_points.size()/2); - assert(input_box.size() == 0 || input_box.size() == 4); // 4 is x_min, y_min, x_max, y_max - assert(input_points.size() > 0 || input_box.size() > 0); - - size_t num_points = input_points.size() / 2; - if(input_box.size() > 0){ - num_points += 2; // add the bounding box two corners - } - else{ - num_points += 1; // add a padding point where there is no bounding box - } - - input_point_coords_shape[1] = num_points; - input_point_coords_buffer.clear(); - // padding point coords are 0.0 - input_point_coords_buffer.resize(num_points * 2, 0.0); - - input_point_labels_shape[1] = num_points; - input_point_labels_buffer.clear(); - // `point_labels`: Labels for the sparse input prompts. 0 is a negative input point, 1 is a positive input point, - // 2 is a top-left box corner, 3 is a bottom-right box corner, and -1 is a padding point. - // If there is no box input, a single padding point with label -1 and coordinates (0.0, 0.0) should be concatenated. - input_point_labels_buffer.resize(num_points, -1.0); - input_orig_im_size_buffer[0] = float(original_image_height); - input_orig_im_size_buffer[1] = float(original_image_width); - - // assign input coordinates and boxes: - const float scale_x = SAM_EMBEDDER_INPUT_IMAGE_WIDTH / float(original_image_width); - const float scale_y = SAM_EMBEDDER_INPUT_IMAGE_HEIGHT / float(original_image_height); - for(size_t i = 0; i < input_point_labels.size(); i++){ - input_point_coords_buffer[2*i] = input_points[2*i] * scale_x; - input_point_coords_buffer[2*i+1] = input_points[2*i+1] * scale_y; - - input_point_labels_buffer[i] = float(input_point_labels[i]); - } - if (input_box.size() > 0){ - // assign input box label - input_point_coords_buffer[2*input_point_labels.size()] = input_box[0] * scale_x; - input_point_coords_buffer[2*input_point_labels.size()+1] = input_box[1] * scale_y; - input_point_coords_buffer[2*input_point_labels.size()+2] = input_box[2] * scale_x; - input_point_coords_buffer[2*input_point_labels.size()+3] = input_box[3] * scale_y; - - input_point_labels_buffer[input_point_labels.size()] = 2; - input_point_labels_buffer[input_point_labels.size()+1] = 3; - } - - output_mask_shape[2] = original_image_height; - output_mask_shape[3] = original_image_width; - output_mask_buffer.clear(); - output_mask_buffer.resize(original_image_height * original_image_width, 0.0); - - std::array input_tensors; - input_tensors[0] = create_tensor(memory_info, image_embedding, input_image_embedding_shape); - input_tensors[1] = create_tensor(memory_info, input_point_coords_buffer, input_point_coords_shape); - input_tensors[2] = create_tensor(memory_info, input_point_labels_buffer, input_point_labels_shape); - input_tensors[3] = create_tensor(memory_info, input_mask_buffer, input_mask_shape); - input_tensors[4] = create_tensor(memory_info, input_has_mask_buffer, input_has_mask_shape); - input_tensors[5] = create_tensor(memory_info, input_orig_im_size_buffer, input_orig_im_size_shape); - std::array output_tensors; - output_tensors[0] = create_tensor(memory_info, output_mask_buffer, output_mask_shape); - output_tensors[1] = create_tensor(memory_info, output_iou_prediction_buffer, output_iou_prediction_shape); - output_tensors[2] = create_tensor(memory_info, output_low_res_mask_buffer, output_low_res_mask_shape); - - std::array input_names_c; - for(int i = 0; i < SAM_N_INPUT_TENSORS; i++){ - input_names_c[i] = input_names[i].data(); - } - std::array output_names_c; - for(int i = 0; i < SAM_N_OUTPUT_TENSORS; i++){ - output_names_c[i] = output_names[i].data(); - } - - auto start = std::chrono::steady_clock::now(); - session.Run(run_options, input_names_c.data(), input_tensors.data(), SAM_N_INPUT_TENSORS, - output_names_c.data(), output_tensors.data(), SAM_N_OUTPUT_TENSORS); - auto end = std::chrono::steady_clock::now(); - auto milliseconds = std::chrono::duration_cast(end - start).count(); - std::cout << "SAM inference time: " << milliseconds << " ms" << std::endl; - - output_boolean_mask.resize(original_image_height * original_image_width, false); - for(size_t i = 0; i < output_mask_buffer.size(); i++){ - output_boolean_mask[i] = output_mask_buffer[i] > SAM_OUTPUT_MASK_THRESHOLD; - } -} - - -// save the image embedding as a file with path .embedding -void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding){ - std::string embedding_path = image_filepath + ".embedding"; - std::ofstream fout(embedding_path, std::ios::binary); - // write embedding shape - fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_N_CHANNELS), sizeof(SAM_EMBEDDER_OUTPUT_N_CHANNELS)); - fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); - fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); - fout.write(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); - fout.close(); - std::cout << "Saved image embedding as " << embedding_path << std::endl; -} - - -bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding){ - std::string emebdding_path = image_filepath + ".embedding"; - std::ifstream fin(emebdding_path, std::ios::binary); - if (!fin.is_open()){ - std::cout << "No embedding for image " << image_filepath << std::endl; - return false; - } - - int embedding_n_channels = 0, embedding_height = 0, emebedding_width = 0; - fin.read(reinterpret_cast(&embedding_n_channels), sizeof(int)); - fin.read(reinterpret_cast(&embedding_height), sizeof(int)); - fin.read(reinterpret_cast(&emebedding_width), sizeof(int)); - - std::cout << "Image embedding shape [" << embedding_n_channels << ", " << embedding_height - << ", " << emebedding_width << "]" << std::endl; - if (embedding_n_channels <= 0 || embedding_height <= 0 || emebedding_width <= 0){ - std::string err_msg = "Image embedding wrong dimension from " + emebdding_path; - std::cerr << err_msg << std::endl; - throw std::runtime_error(err_msg); - } - - const int size = embedding_n_channels * embedding_height * emebedding_width; - image_embedding.resize(size); - fin.read(reinterpret_cast(image_embedding.data()), sizeof(float) * size); - std::cout << "Loaded image embedding from " << emebdding_path << std::endl; - return true; -} - - -} -} +/* ML Segment Anything Model + * + * From: https://github.com/PokemonAutomation/ + * + * Run Segment Anything Model (SAM) to segment objects on images + */ + +#include +#include +#include +#include +#include "3rdParty/ONNX/OnnxToolsPA.h" +#include "SegmentAnythingModel.h" + +namespace PokemonAutomation{ +namespace ML{ + + + + +const int SAM_EMBEDDER_INPUT_IMAGE_WIDTH = 1024; +const int SAM_EMBEDDER_INPUT_IMAGE_HEIGHT = 576; +const int SAM_EMBEDDER_OUTPUT_N_CHANNELS = 256; +const int SAM_EMBEDDER_OUTPUT_IMAGE_SIZE = 64; + +const int SAM_EMBEDDER_INPUT_SIZE = SAM_EMBEDDER_INPUT_IMAGE_HEIGHT * SAM_EMBEDDER_INPUT_IMAGE_WIDTH * 3; +const int SAM_EMBEDDER_OUTPUT_SIZE = SAM_EMBEDDER_OUTPUT_N_CHANNELS * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE * SAM_EMBEDDER_OUTPUT_IMAGE_SIZE; + +const int SAM_N_INPUT_TENSORS = 6; +const int SAM_N_OUTPUT_TENSORS = 3; +const int SAM_LOW_RES_MASK_SIZE = 256; +const float SAM_OUTPUT_MASK_THRESHOLD = 0.0; + + +Ort::SessionOptions create_session_option(){ + return Ort::SessionOptions{}; + + // create session using Apple ML + + // Ort::SessionOptions so; + // std::unordered_map provider_options; + // provider_options["ModelFormat"] = "NeuralNetwork"; + // so.AppendExecutionProvider("CoreML", provider_options); + // return so; +} + + +template Ort::Value create_tensor(const OrtMemoryInfo* memory_info, Buffer& buffer, const Shape& shape){ + return Ort::Value::CreateTensor(memory_info, buffer.data(), buffer.size(), + shape.data(), shape.size()); +} + + +SAMEmbedderSession::SAMEmbedderSession(const std::string& model_path) + : session_options(create_session_option()) + , session{env, str_to_onnx_str(model_path).c_str(), session_options} + , memory_info{Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU)} + , input_names{session.GetInputNames()} + , output_names{session.GetOutputNames()} + , input_shape{1, SAM_EMBEDDER_INPUT_IMAGE_HEIGHT, SAM_EMBEDDER_INPUT_IMAGE_WIDTH, 3} + , output_shape{1, SAM_EMBEDDER_OUTPUT_N_CHANNELS, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE} + , model_input(SAM_EMBEDDER_INPUT_SIZE) +{ + std::cout << "Built SAM embedder session" << std::endl; +} + +void SAMEmbedderSession::run(cv::Mat& input_image, std::vector& model_output){ + assert(input_image.rows == SAM_EMBEDDER_INPUT_IMAGE_HEIGHT); + assert(input_image.cols == SAM_EMBEDDER_INPUT_IMAGE_WIDTH); + + model_output.resize(SAM_EMBEDDER_OUTPUT_SIZE); + auto input_tensor = create_tensor(memory_info, model_input, input_shape); + auto output_tensor = create_tensor(memory_info, model_output, output_shape); + + for (int row = 0, p_loc=0; row < SAM_EMBEDDER_INPUT_IMAGE_HEIGHT; row++){ + for(int col = 0; col < SAM_EMBEDDER_INPUT_IMAGE_WIDTH; col++){ + cv::Vec3b p = input_image.at(row, col); + model_input[p_loc++] = p[0]; + model_input[p_loc++] = p[1]; + model_input[p_loc++] = p[2]; + } + } + + const char* input_name_c = input_names[0].data(); + const char* output_name_c = output_names[0].data(); + auto start = std::chrono::steady_clock::now(); + session.Run(run_options, &input_name_c, &input_tensor, 1, &output_name_c, &output_tensor, 1); + auto end = std::chrono::steady_clock::now(); + auto milliseconds = std::chrono::duration_cast(end - start).count(); + std::cout << "Embedder inference time: " << milliseconds << " ms" << std::endl; +} + + +SAMSession::SAMSession(const std::string& model_path) + : session_options(create_session_option()) + , session{env, str_to_onnx_str(model_path).c_str(), session_options} + , memory_info{Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU)} + , input_names{session.GetInputNames()} + , output_names{session.GetOutputNames()} + , input_image_embedding_shape{1, SAM_EMBEDDER_OUTPUT_N_CHANNELS, + SAM_EMBEDDER_OUTPUT_IMAGE_SIZE, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE} + , input_mask_shape{1, 1, SAM_LOW_RES_MASK_SIZE, SAM_LOW_RES_MASK_SIZE} + , output_low_res_mask_shape{1, 1, SAM_LOW_RES_MASK_SIZE, SAM_LOW_RES_MASK_SIZE} + , input_mask_buffer(SAM_LOW_RES_MASK_SIZE * SAM_LOW_RES_MASK_SIZE, 0.0) + , output_low_res_mask_buffer(SAM_LOW_RES_MASK_SIZE * SAM_LOW_RES_MASK_SIZE, 0.0) +{ + std::cout << "Built SAM session" << std::endl; +} + +void SAMSession::run( + std::vector& image_embedding, + int original_image_height, int original_image_width, + const std::vector& input_points, + const std::vector& input_point_labels, + const std::vector& input_box, + std::vector& output_boolean_mask +){ + assert(image_embedding.size() == SAM_EMBEDDER_OUTPUT_SIZE); + assert(input_points.size() % 2 == 0); + assert(input_point_labels.size() == input_points.size()/2); + assert(input_box.size() == 0 || input_box.size() == 4); // 4 is x_min, y_min, x_max, y_max + assert(input_points.size() > 0 || input_box.size() > 0); + + size_t num_points = input_points.size() / 2; + if(input_box.size() > 0){ + num_points += 2; // add the bounding box two corners + } + else{ + num_points += 1; // add a padding point where there is no bounding box + } + + input_point_coords_shape[1] = num_points; + input_point_coords_buffer.clear(); + // padding point coords are 0.0 + input_point_coords_buffer.resize(num_points * 2, 0.0); + + input_point_labels_shape[1] = num_points; + input_point_labels_buffer.clear(); + // `point_labels`: Labels for the sparse input prompts. 0 is a negative input point, 1 is a positive input point, + // 2 is a top-left box corner, 3 is a bottom-right box corner, and -1 is a padding point. + // If there is no box input, a single padding point with label -1 and coordinates (0.0, 0.0) should be concatenated. + input_point_labels_buffer.resize(num_points, -1.0); + input_orig_im_size_buffer[0] = float(original_image_height); + input_orig_im_size_buffer[1] = float(original_image_width); + + // assign input coordinates and boxes: + const float scale_x = SAM_EMBEDDER_INPUT_IMAGE_WIDTH / float(original_image_width); + const float scale_y = SAM_EMBEDDER_INPUT_IMAGE_HEIGHT / float(original_image_height); + for(size_t i = 0; i < input_point_labels.size(); i++){ + input_point_coords_buffer[2*i] = input_points[2*i] * scale_x; + input_point_coords_buffer[2*i+1] = input_points[2*i+1] * scale_y; + + input_point_labels_buffer[i] = float(input_point_labels[i]); + } + if (input_box.size() > 0){ + // assign input box label + input_point_coords_buffer[2*input_point_labels.size()] = input_box[0] * scale_x; + input_point_coords_buffer[2*input_point_labels.size()+1] = input_box[1] * scale_y; + input_point_coords_buffer[2*input_point_labels.size()+2] = input_box[2] * scale_x; + input_point_coords_buffer[2*input_point_labels.size()+3] = input_box[3] * scale_y; + + input_point_labels_buffer[input_point_labels.size()] = 2; + input_point_labels_buffer[input_point_labels.size()+1] = 3; + } + + output_mask_shape[2] = original_image_height; + output_mask_shape[3] = original_image_width; + output_mask_buffer.clear(); + output_mask_buffer.resize(original_image_height * original_image_width, 0.0); + + std::array input_tensors; + input_tensors[0] = create_tensor(memory_info, image_embedding, input_image_embedding_shape); + input_tensors[1] = create_tensor(memory_info, input_point_coords_buffer, input_point_coords_shape); + input_tensors[2] = create_tensor(memory_info, input_point_labels_buffer, input_point_labels_shape); + input_tensors[3] = create_tensor(memory_info, input_mask_buffer, input_mask_shape); + input_tensors[4] = create_tensor(memory_info, input_has_mask_buffer, input_has_mask_shape); + input_tensors[5] = create_tensor(memory_info, input_orig_im_size_buffer, input_orig_im_size_shape); + std::array output_tensors; + output_tensors[0] = create_tensor(memory_info, output_mask_buffer, output_mask_shape); + output_tensors[1] = create_tensor(memory_info, output_iou_prediction_buffer, output_iou_prediction_shape); + output_tensors[2] = create_tensor(memory_info, output_low_res_mask_buffer, output_low_res_mask_shape); + + std::array input_names_c; + for(int i = 0; i < SAM_N_INPUT_TENSORS; i++){ + input_names_c[i] = input_names[i].data(); + } + std::array output_names_c; + for(int i = 0; i < SAM_N_OUTPUT_TENSORS; i++){ + output_names_c[i] = output_names[i].data(); + } + + auto start = std::chrono::steady_clock::now(); + session.Run(run_options, input_names_c.data(), input_tensors.data(), SAM_N_INPUT_TENSORS, + output_names_c.data(), output_tensors.data(), SAM_N_OUTPUT_TENSORS); + auto end = std::chrono::steady_clock::now(); + auto milliseconds = std::chrono::duration_cast(end - start).count(); + std::cout << "SAM inference time: " << milliseconds << " ms" << std::endl; + + output_boolean_mask.resize(original_image_height * original_image_width, false); + for(size_t i = 0; i < output_mask_buffer.size(); i++){ + output_boolean_mask[i] = output_mask_buffer[i] > SAM_OUTPUT_MASK_THRESHOLD; + } +} + + +// save the image embedding as a file with path .embedding +void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding){ + std::string embedding_path = image_filepath + ".embedding"; + std::ofstream fout(embedding_path, std::ios::binary); + // write embedding shape + fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_N_CHANNELS), sizeof(SAM_EMBEDDER_OUTPUT_N_CHANNELS)); + fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); + fout.write(reinterpret_cast(&SAM_EMBEDDER_OUTPUT_IMAGE_SIZE), sizeof(SAM_EMBEDDER_OUTPUT_IMAGE_SIZE)); + fout.write(reinterpret_cast(embedding.data()), sizeof(float) * embedding.size()); + fout.close(); + std::cout << "Saved image embedding as " << embedding_path << std::endl; +} + + +bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding){ + std::string emebdding_path = image_filepath + ".embedding"; + std::ifstream fin(emebdding_path, std::ios::binary); + if (!fin.is_open()){ + std::cout << "No embedding for image " << image_filepath << std::endl; + return false; + } + + int embedding_n_channels = 0, embedding_height = 0, emebedding_width = 0; + fin.read(reinterpret_cast(&embedding_n_channels), sizeof(int)); + fin.read(reinterpret_cast(&embedding_height), sizeof(int)); + fin.read(reinterpret_cast(&emebedding_width), sizeof(int)); + + std::cout << "Image embedding shape [" << embedding_n_channels << ", " << embedding_height + << ", " << emebedding_width << "]" << std::endl; + if (embedding_n_channels <= 0 || embedding_height <= 0 || emebedding_width <= 0){ + std::string err_msg = "Image embedding wrong dimension from " + emebdding_path; + std::cerr << err_msg << std::endl; + throw std::runtime_error(err_msg); + } + + const int size = embedding_n_channels * embedding_height * emebedding_width; + image_embedding.resize(size); + fin.read(reinterpret_cast(image_embedding.data()), sizeof(float) * size); + std::cout << "Loaded image embedding from " << emebdding_path << std::endl; + return true; +} + + +} +} diff --git a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h b/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h index 0f71c07632..540218846c 100644 --- a/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h +++ b/SerialPrograms/Source/ML/DataLabeling/SegmentAnythingModel.h @@ -1,108 +1,108 @@ -/* ML Segment Anything Model - * - * From: https://github.com/PokemonAutomation/ - * - * Run Segment Anything Model (SAM) to segment objects on images - */ - -#ifndef PokemonAutomation_ML_SEGMENTANYTHINGMODEL_H -#define PokemonAutomation_ML_SEGMENTANYTHINGMODEL_H - - -#include -#include -#include - -namespace cv{ - class Mat; -} - -namespace PokemonAutomation{ -namespace ML{ - - -// load pre-computed image embedding from disk -// return true if there is the embedding file -bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding); - -// save the image embedding as a file with path .embedding -void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding); - - -class SAMEmbedderSession{ -public: - SAMEmbedderSession(const std::string& model_path); - - // Given an image of shape SAM_EMBEDDER_INPUT_IMAGE_WIDTH x SAM_EMBEDDER_INPUT_IMAGE_HEIGHT, RGB channel order, - // compute its image embedding as a vector of size [SAM_EMBEDDER_OUTPUT_SIZE] - // it has shape [1, SAM_EMBEDDER_OUTPUT_N_CHANNELS, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE] - void run(cv::Mat& input_image, std::vector& output_image_embedding); - -private: - Ort::Env env; - Ort::SessionOptions session_options; - Ort::Session session; - Ort::MemoryInfo memory_info; - Ort::RunOptions run_options; - std::vector input_names, output_names; - - const std::array input_shape; - const std::array output_shape; - - std::vector model_input; -}; - -// Run Segment Anything Model in an ONNX session. -class SAMSession{ -public: - SAMSession(const std::string& model_path); - - // embedding: input embedding - // input_points: input point coordinates (x, y) in pixel units. [p0_x, p0_y, p1_x, p1_y, p2_x, ...]. - // Vector size: 2*num_points - // input_point_labels: if a point is part of the object to segment, its corresponding label value is 1. - // if a point is outside of the object, value is 0. Vector size: num_points. - // input_box: if not empty, the two corner points (in pixel units) of a bounding box for the object to segment. - // [p0_x, p0_y, p1_x, p1_y], where p0 is the top-left corner and p1 is the lower right corner. - // output_boolean_mask: output mask in the shape of [original_image_height x original_image_width]. - // Vector size: original_image_height * original_image_width. - void run( - std::vector& embedding, - int original_image_height, int original_image_width, - const std::vector& input_points, - const std::vector& input_point_labels, - const std::vector& input_box, - std::vector& output_boolean_mask); -private: - Ort::Env env; - Ort::SessionOptions session_options; - Ort::Session session; - Ort::MemoryInfo memory_info; - Ort::RunOptions run_options; - std::vector input_names, output_names; - - const std::array input_image_embedding_shape; - std::array input_point_coords_shape{1, -1, 2}; - std::array input_point_labels_shape{1, -1}; - const std::array input_mask_shape; - const std::array input_has_mask_shape{1}; - const std::array input_orig_im_size_shape{2}; - std::array output_mask_shape{1, 1, -1, -1}; - const std::array output_iou_prediction_shape{1, 1}; - const std::array output_low_res_mask_shape; - - std::vector input_point_coords_buffer; - std::vector input_point_labels_buffer; - std::vector input_mask_buffer; - std::array input_has_mask_buffer{0.0}; - std::array input_orig_im_size_buffer; - std::vector output_mask_buffer; - std::array output_iou_prediction_buffer{0.0}; - std::vector output_low_res_mask_buffer; -}; - - - -} -} +/* ML Segment Anything Model + * + * From: https://github.com/PokemonAutomation/ + * + * Run Segment Anything Model (SAM) to segment objects on images + */ + +#ifndef PokemonAutomation_ML_SEGMENTANYTHINGMODEL_H +#define PokemonAutomation_ML_SEGMENTANYTHINGMODEL_H + + +#include +#include +#include + +namespace cv{ + class Mat; +} + +namespace PokemonAutomation{ +namespace ML{ + + +// load pre-computed image embedding from disk +// return true if there is the embedding file +bool load_image_embedding(const std::string& image_filepath, std::vector& image_embedding); + +// save the image embedding as a file with path .embedding +void save_image_embedding_to_disk(const std::string& image_filepath, const std::vector& embedding); + + +class SAMEmbedderSession{ +public: + SAMEmbedderSession(const std::string& model_path); + + // Given an image of shape SAM_EMBEDDER_INPUT_IMAGE_WIDTH x SAM_EMBEDDER_INPUT_IMAGE_HEIGHT, RGB channel order, + // compute its image embedding as a vector of size [SAM_EMBEDDER_OUTPUT_SIZE] + // it has shape [1, SAM_EMBEDDER_OUTPUT_N_CHANNELS, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE, SAM_EMBEDDER_OUTPUT_IMAGE_SIZE] + void run(cv::Mat& input_image, std::vector& output_image_embedding); + +private: + Ort::Env env; + Ort::SessionOptions session_options; + Ort::Session session; + Ort::MemoryInfo memory_info; + Ort::RunOptions run_options; + std::vector input_names, output_names; + + const std::array input_shape; + const std::array output_shape; + + std::vector model_input; +}; + +// Run Segment Anything Model in an ONNX session. +class SAMSession{ +public: + SAMSession(const std::string& model_path); + + // embedding: input embedding + // input_points: input point coordinates (x, y) in pixel units. [p0_x, p0_y, p1_x, p1_y, p2_x, ...]. + // Vector size: 2*num_points + // input_point_labels: if a point is part of the object to segment, its corresponding label value is 1. + // if a point is outside of the object, value is 0. Vector size: num_points. + // input_box: if not empty, the two corner points (in pixel units) of a bounding box for the object to segment. + // [p0_x, p0_y, p1_x, p1_y], where p0 is the top-left corner and p1 is the lower right corner. + // output_boolean_mask: output mask in the shape of [original_image_height x original_image_width]. + // Vector size: original_image_height * original_image_width. + void run( + std::vector& embedding, + int original_image_height, int original_image_width, + const std::vector& input_points, + const std::vector& input_point_labels, + const std::vector& input_box, + std::vector& output_boolean_mask); +private: + Ort::Env env; + Ort::SessionOptions session_options; + Ort::Session session; + Ort::MemoryInfo memory_info; + Ort::RunOptions run_options; + std::vector input_names, output_names; + + const std::array input_image_embedding_shape; + std::array input_point_coords_shape{1, -1, 2}; + std::array input_point_labels_shape{1, -1}; + const std::array input_mask_shape; + const std::array input_has_mask_shape{1}; + const std::array input_orig_im_size_shape{2}; + std::array output_mask_shape{1, 1, -1, -1}; + const std::array output_iou_prediction_shape{1, 1}; + const std::array output_low_res_mask_shape; + + std::vector input_point_coords_buffer; + std::vector input_point_labels_buffer; + std::vector input_mask_buffer; + std::array input_has_mask_buffer{0.0}; + std::array input_orig_im_size_buffer; + std::vector output_mask_buffer; + std::array output_iou_prediction_buffer{0.0}; + std::vector output_low_res_mask_buffer; +}; + + + +} +} #endif \ No newline at end of file diff --git a/SerialPrograms/Source/ML/ML_Panels.cpp b/SerialPrograms/Source/ML/ML_Panels.cpp index 3128d36502..e9a7eadae6 100644 --- a/SerialPrograms/Source/ML/ML_Panels.cpp +++ b/SerialPrograms/Source/ML/ML_Panels.cpp @@ -1,39 +1,39 @@ -/* ML Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Panels/PanelTools.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Programs/ML_LabelImages.h" - -#include "ML_Panels.h" - - -namespace PokemonAutomation{ -namespace ML{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor("ML") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_panel()); - // ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} +/* ML Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Panels/PanelTools.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Programs/ML_LabelImages.h" + +#include "ML_Panels.h" + + +namespace PokemonAutomation{ +namespace ML{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor("ML") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_panel()); + // ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} diff --git a/SerialPrograms/Source/ML/ML_Panels.h b/SerialPrograms/Source/ML/ML_Panels.h index b30657025f..105b72eb46 100644 --- a/SerialPrograms/Source/ML/ML_Panels.h +++ b/SerialPrograms/Source/ML/ML_Panels.h @@ -1,28 +1,28 @@ -/* ML Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ML_Panels_H -#define PokemonAutomation_ML_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace ML{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -#endif +/* ML Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ML_Panels_H +#define PokemonAutomation_ML_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace ML{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp b/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp index 908b4cf0e3..2529ba423b 100644 --- a/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp +++ b/SerialPrograms/Source/ML/Programs/ML_LabelImages.cpp @@ -1,483 +1,483 @@ -/* ML Label Images - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonTools.h" -#include "Common/Qt/CollapsibleGroupBox.h" -#include "Pokemon/Resources/Pokemon_PokemonForms.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h" -#include "CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h" -#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h" -#include "ML_LabelImages.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "ML/DataLabeling/SegmentAnythingModel.h" - - - -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace ML{ - - -ObjectAnnotation::ObjectAnnotation(): user_box(0,0,0,0), mask_box(0,0,0,0) {} - -// if failed to pass, will throw JsonParseException -ObjectAnnotation json_to_object_annotation(const JsonValue& value){ - ObjectAnnotation anno_obj; - - const JsonObject& json_obj = value.to_object_throw(); - const JsonArray& user_box_array = json_obj.get_array_throw("UserBox"); - anno_obj.user_box = ImagePixelBox( - size_t(user_box_array[0].to_integer_throw()), - size_t(user_box_array[1].to_integer_throw()), - size_t(user_box_array[2].to_integer_throw()), - size_t(user_box_array[3].to_integer_throw()) - ); - const JsonArray& mask_box_array = json_obj.get_array_throw("MaskBox"); - anno_obj.mask_box = ImagePixelBox( - size_t(mask_box_array[0].to_integer_throw()), - size_t(mask_box_array[1].to_integer_throw()), - size_t(mask_box_array[2].to_integer_throw()), - size_t(mask_box_array[3].to_integer_throw()) - ); - size_t mask_width = anno_obj.mask_box.width(), mask_height = anno_obj.mask_box.height(); - anno_obj.mask.resize(mask_width * mask_height); - const JsonArray& mask_values = json_obj.get_array_throw("Mask"); - for(size_t i = 0; i < anno_obj.mask.size(); i++){ - anno_obj.mask[i] = bool(mask_values[i].to_integer_throw()); - } - - anno_obj.label = json_obj.get_string_throw("Label"); - - return anno_obj; -} - -JsonObject object_annotation_to_json(const ObjectAnnotation& object_annotation){ - JsonObject json_obj; - JsonArray user_box_arr; - user_box_arr.push_back(int64_t(object_annotation.user_box.min_x)); - user_box_arr.push_back(int64_t(object_annotation.user_box.min_y)); - user_box_arr.push_back(int64_t(object_annotation.user_box.max_x)); - user_box_arr.push_back(int64_t(object_annotation.user_box.max_y)); - json_obj["UserBox"] = std::move(user_box_arr); - - JsonArray mask_box_arr; - mask_box_arr.push_back(int64_t(object_annotation.mask_box.min_x)); - mask_box_arr.push_back(int64_t(object_annotation.mask_box.min_y)); - mask_box_arr.push_back(int64_t(object_annotation.mask_box.max_x)); - mask_box_arr.push_back(int64_t(object_annotation.mask_box.max_y)); - json_obj["MaskBox"] = std::move(mask_box_arr); - - JsonArray mask_arr; - for(size_t i = 0; i < object_annotation.mask.size(); i++){ - mask_arr.push_back(int64_t(object_annotation.mask[i])); - } - json_obj["Mask"] = std::move(mask_arr); - - json_obj["Label"] = object_annotation.label; - - return json_obj; -} - - -DrawnBoundingBox::DrawnBoundingBox(LabelImages_Widget& widget, VideoOverlay& overlay) - : m_widget(widget) - , m_overlay(overlay) -{ - auto& program = m_widget.m_program; - program.X.add_listener(*this); - program.Y.add_listener(*this); - program.WIDTH.add_listener(*this); - program.HEIGHT.add_listener(*this); - overlay.add_listener(*this); -} - -DrawnBoundingBox::~DrawnBoundingBox(){ - detach(); -} - -// called when drawn bounding box changed -void DrawnBoundingBox::on_config_value_changed(void* object){ - auto& program = m_widget.m_program; - std::lock_guard lg(m_lock); - program.update_rendered_objects(m_widget.m_overlay_set); -} -void DrawnBoundingBox::on_mouse_press(double x, double y){ - auto& program = m_widget.m_program; - program.WIDTH.set(0); - program.HEIGHT.set(0); - program.X.set(x); - program.Y.set(y); - m_mouse_start.emplace(); - m_mouse_start->first = x; - m_mouse_start->second = y; -} -void DrawnBoundingBox::on_mouse_release(double, double){ - m_mouse_start.reset(); - auto& m_program = m_widget.m_program; - auto& m_overlay_set = m_widget.m_overlay_set; - - m_program.compute_mask(m_overlay_set); -} - -void DrawnBoundingBox::on_mouse_move(double x, double y){ - auto& program = m_widget.m_program; - if (!m_mouse_start){ - return; - } - - double xl = m_mouse_start->first; - double xh = x; - double yl = m_mouse_start->second; - double yh = y; - - if (xl > xh){ - std::swap(xl, xh); - } - if (yl > yh){ - std::swap(yl, yh); - } - - program.X.set(xl); - program.Y.set(yl); - program.WIDTH.set(xh - xl); - program.HEIGHT.set(yh - yl); -} - -void DrawnBoundingBox::detach(){ - auto& program = m_widget.m_program; - m_overlay.remove_listener(*this); - program.X.remove_listener(*this); - program.Y.remove_listener(*this); - program.WIDTH.remove_listener(*this); - program.HEIGHT.remove_listener(*this); -} - - -LabelImages_Descriptor::LabelImages_Descriptor() - : PanelDescriptor( - Color(), - "ML:LabelImages", - "ML", "Label Images", - "", // "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/LabelImages.md", - "Label " + Pokemon::STRING_POKEMON + " on images" - ) -{} - - - -#define ADD_OPTION(x) m_options.add_option(x, #x) - -LabelImages::LabelImages(const LabelImages_Descriptor& descriptor) - : PanelInstance(descriptor) - , m_switch_control_option({}, false) - , m_options(LockMode::UNLOCK_WHILE_RUNNING) - , X("X Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) - , Y("Y Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) - , WIDTH("Width:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) - , HEIGHT("Height:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) - , FORM_LABEL("bulbasaur") - , m_sam_session{RESOURCE_PATH() + "ML/sam_cpu.onnx"} -{ - ADD_OPTION(X); - ADD_OPTION(Y); - ADD_OPTION(WIDTH); - ADD_OPTION(HEIGHT); - ADD_OPTION(FORM_LABEL); -} -void LabelImages::from_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - const JsonValue* value = obj->get_value("SwitchSetup"); - if (value){ - m_switch_control_option.load_json(*value); - } - m_options.load_json(json); -} -JsonValue LabelImages::to_json() const{ - JsonObject obj = std::move(*m_options.to_json().to_object()); - obj["SwitchSetup"] = m_switch_control_option.to_json(); - - // m_annotation_file_path - if (m_annotation_file_path.size() > 0 && !m_fail_to_load_annotation_file){ - JsonArray anno_json_arr; - for(const auto& anno_obj: m_annotated_objects){ - anno_json_arr.push_back(object_annotation_to_json(anno_obj)); - } - cout << "Saving annotation to " << m_annotation_file_path << endl; - anno_json_arr.dump(m_annotation_file_path); - } - return obj; -} -QWidget* LabelImages::make_widget(QWidget& parent, PanelHolder& holder){ - return new LabelImages_Widget(parent, *this, holder); -} - -void LabelImages::load_image_related_data(const std::string& image_path, size_t source_image_width, size_t source_image_height){ - this->source_image_height = source_image_height; - this->source_image_width = source_image_width; - - m_mask_image = ImageRGB32(source_image_width, source_image_height); - cout << "Image source: " << image_path << ", " << source_image_width << " x " << source_image_height << endl; - // if no such embedding file, m_iamge_embedding will be empty - const bool embedding_loaded = load_image_embedding(image_path, m_image_embedding); - if (!embedding_loaded){ - return; // no embedding, then no way for us to annotate - } - // see if we can load the previously created labels - const std::string anno_filename = std::filesystem::path(image_path).filename().replace_extension(".json").string(); - - // ensure the folder exists - std::filesystem::create_directory(ML_ANNOTATION_PATH()); - m_annotation_file_path = ML_ANNOTATION_PATH() + anno_filename; - if (!std::filesystem::exists(m_annotation_file_path)){ - cout << "Annotataion output path, " << m_annotation_file_path << " does not exist yet" << endl; - return; - } - std::string json_content; - const bool anno_loaded = file_to_string(m_annotation_file_path, json_content); - if (!anno_loaded){ - m_fail_to_load_annotation_file = true; - QMessageBox box; - box.warning(nullptr, "Unable to Load Annotation", - QString::fromStdString("Cannot open annotation file " + m_annotation_file_path + ". Probably wrong permission?")); - return; - } - - JsonValue loaded_json = parse_json(json_content); - const JsonArray* json_array = loaded_json.to_array(); - if (json_array == nullptr){ - m_fail_to_load_annotation_file = true; - QMessageBox box; - box.warning(nullptr, "Unable to Load Annotation", - QString::fromStdString("Cannot load annotation file " + m_annotation_file_path + ". Loaded json is not an array")); - return; - } - - for(size_t i = 0; i < json_array->size(); i++){ - try{ - ObjectAnnotation anno_obj = json_to_object_annotation((*json_array)[i]); - m_annotated_objects.emplace_back(std::move(anno_obj)); - } catch(JsonParseException&){ - m_fail_to_load_annotation_file = true; - QMessageBox box; - box.warning(nullptr, "Unable to Load Annotation", - QString::fromStdString( - "Cannot load annotation file " + m_annotation_file_path + - ". Parsing object " + std::to_string(i) + " failed." - ) - ); - } - } - m_last_object_idx = m_annotated_objects.size(); - cout << "Loaded existing annotation file " << m_annotation_file_path << endl; -} - -void LabelImages::update_rendered_objects(VideoOverlaySet& overlay_set){ - overlay_set.clear(); - overlay_set.add(COLOR_RED, {X, Y, WIDTH, HEIGHT}); - - for(size_t i_obj = 0; i_obj < m_annotated_objects.size(); i_obj++){ - const auto& obj = m_annotated_objects[i_obj]; - // overlayset.add(COLOR_RED, pixelbox_to_floatbox(source_image_width, source_image_height, obj.user_box)); - const auto mask_float_box = pixelbox_to_floatbox(source_image_width, source_image_height, obj.mask_box); - std::string label = obj.label; - const Pokemon::PokemonForm* form = Pokemon::get_pokemon_form(label); - if (form != nullptr){ - label = form->display_name(); - } - Color mask_box_color = (i_obj == m_last_object_idx) ? COLOR_BLACK : COLOR_BLUE; - overlay_set.add(mask_box_color, mask_float_box, label); - size_t mask_width = obj.mask_box.width(); - size_t mask_height = obj.mask_box.height(); - ImageRGB32 mask_image(mask_width, mask_height); - // cout << "in render, mask_box " << obj.mask_box.min_x << " " << obj.mask_box.min_y << " " << obj.mask_box.max_x << " " << obj.mask_box.max_y << endl; - - for (size_t y = 0; y < mask_height; y++){ - for (size_t x = 0; x < mask_width; x++){ - const bool mask = obj.mask[y*mask_width + x]; - uint32_t& pixel = mask_image.pixel(x, y); - // if the pixel's mask value is true, set a semi-transparent 45-degree blue strip color - // otherwise: fully transparent (alpha = 0) - uint32_t color = 0; - if (mask){ - color = (std::abs(int(x) - int(y)) % 4 <= 1) ? combine_argb(150, 30, 144, 255) : combine_argb(150, 0, 0, 60); - } - pixel = color; - } - } - // cout << " count " << count << endl; - overlay_set.add(std::move(mask_image), mask_float_box); - } -} - -void LabelImages::compute_mask(VideoOverlaySet& overlay_set){ - const size_t source_width = source_image_width; - const size_t source_height = source_image_height; - - const int box_x = int(X * source_width + 0.5); - const int box_y = int(Y * source_height + 0.5); - const int box_width = int(WIDTH * source_width + 0.5); - const int box_height = int(HEIGHT * source_height + 0.5); - if (box_width == 0 || box_height == 0){ - return; - } - - if (m_image_embedding.size() == 0){ - // no embedding file loaded - return; - } - m_sam_session.run( - m_image_embedding, - (int)source_height, (int)source_width, {}, {}, - {box_x, box_y, box_x + box_width, box_y + box_height}, - m_output_boolean_mask - ); - - size_t min_mask_x = INT_MAX, max_mask_x = 0; - size_t min_mask_y = INT_MAX, max_mask_y = 0; - for (size_t y = 0; y < source_height; y++){ - for (size_t x = 0; x < source_width; x++){ - bool mask = m_output_boolean_mask[y*source_width + x]; - uint32_t& pixel = m_mask_image.pixel(x, y); - // if the pixel's mask value is true, set a semi-transparent 45-degree blue strip color - // otherwise: fully transparent (alpha = 0) - uint32_t color = 0; - if (mask){ - color = (std::abs(int(x) - int(y)) % 4 <= 1) ? combine_argb(150, 30, 144, 255) : combine_argb(150, 0, 0, 60); - min_mask_x = std::min(x, min_mask_x); - max_mask_x = std::max(x, max_mask_x); - min_mask_y = std::min(y, min_mask_y); - max_mask_y = std::max(y, max_mask_y); - } - pixel = color; - } - } - if (min_mask_x < INT_MAX && max_mask_x > min_mask_x && min_mask_y < INT_MAX && max_mask_y > min_mask_y){ - const size_t mask_width = max_mask_x - min_mask_x + 1; - const size_t mask_height = max_mask_y - min_mask_y + 1; - ImageFloatBox mask_box( - min_mask_x/double(source_width), min_mask_y/double(source_height), - mask_width/double(source_width), mask_height/double(source_height)); - const std::string label = FORM_LABEL.slug(); - - - ObjectAnnotation annotation; - annotation.user_box = ImagePixelBox(box_x, box_y, box_x + box_width + 1, box_y + box_height + 1); - annotation.mask_box = ImagePixelBox(min_mask_x, min_mask_y, max_mask_x+1, max_mask_y+1); - annotation.mask.resize(mask_width * mask_height); - for(size_t row = 0; row < mask_height; row++){ - auto it = m_output_boolean_mask.begin() + (min_mask_y + row) * source_width + min_mask_x; - auto it2 = annotation.mask.begin() + row * mask_width; - std::copy(it, it + mask_width, it2); - } - - annotation.label = label; - m_last_object_idx = m_annotated_objects.size(); - m_annotated_objects.emplace_back(std::move(annotation)); - - update_rendered_objects(overlay_set); - } -} - -LabelImages_Widget::~LabelImages_Widget(){ - m_program.FORM_LABEL.remove_listener(*this); - delete m_switch_widget; -} -LabelImages_Widget::LabelImages_Widget( - QWidget& parent, - LabelImages& instance, - PanelHolder& holder -) - : PanelWidget(parent, instance, holder) - , m_program(instance) - , m_session(instance.m_switch_control_option, 0, 0) - , m_overlay_set(m_session.overlay()) - , m_drawn_box(*this, m_session.overlay()) -{ - m_program.FORM_LABEL.add_listener(*this); - - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(make_header(*this)); - - QScrollArea* scroll_outer = new QScrollArea(this); - layout->addWidget(scroll_outer); - scroll_outer->setWidgetResizable(true); - - QWidget* scroll_inner = new QWidget(scroll_outer); - scroll_outer->setWidget(scroll_inner); - QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); - scroll_layout->setAlignment(Qt::AlignTop); - - m_switch_widget = new NintendoSwitch::SwitchSystemWidget(*this, m_session, 0); - scroll_layout->addWidget(m_switch_widget); - - QPushButton* button = new QPushButton("Delete Last Mask", scroll_inner); - scroll_layout->addWidget(button); - connect(button, &QPushButton::clicked, this, [this](bool){ - auto& program = this->m_program; - if (program.m_annotated_objects.size() > 0){ - program.m_annotated_objects.pop_back(); - } - if (program.m_annotated_objects.size() > 0){ - program.m_last_object_idx = program.m_annotated_objects.size() - 1; - } - program.update_rendered_objects(this->m_overlay_set); - }); - - m_option_widget = instance.m_options.make_QtWidget(*scroll_inner); - scroll_layout->addWidget(&m_option_widget->widget()); - - const VideoSourceDescriptor* video_source_desc = instance.m_switch_control_option.m_video.descriptor().get(); - auto image_source_desc = dynamic_cast(video_source_desc); - if (image_source_desc != nullptr){ - const std::string image_path = image_source_desc->path(); - const size_t source_image_height = image_source_desc->source_image_height(); - const size_t source_image_width = image_source_desc->source_image_width(); - m_program.load_image_related_data(image_path, source_image_width, source_image_height); - m_program.update_rendered_objects(m_overlay_set); - } - - cout << "LabelImages_Widget built" << endl; -} - -void LabelImages_Widget::on_config_value_changed(void* object){ - if (m_program.m_annotated_objects.size() > 0 && m_program.m_last_object_idx < m_program.m_annotated_objects.size()){ - std::string& cur_label = m_program.m_annotated_objects[m_program.m_last_object_idx].label; - cur_label = m_program.FORM_LABEL.slug(); - m_program.update_rendered_objects(m_overlay_set); - } -} - - - -} -} - +/* ML Label Images + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonTools.h" +#include "Common/Qt/CollapsibleGroupBox.h" +#include "Pokemon/Resources/Pokemon_PokemonForms.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h" +#include "CommonFramework/VideoPipeline/Backends/CameraWidgetQt6.5.h" +#include "CommonFramework/VideoPipeline/VideoSources/VideoSource_StillImage.h" +#include "ML_LabelImages.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "ML/DataLabeling/SegmentAnythingModel.h" + + + +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace ML{ + + +ObjectAnnotation::ObjectAnnotation(): user_box(0,0,0,0), mask_box(0,0,0,0) {} + +// if failed to pass, will throw JsonParseException +ObjectAnnotation json_to_object_annotation(const JsonValue& value){ + ObjectAnnotation anno_obj; + + const JsonObject& json_obj = value.to_object_throw(); + const JsonArray& user_box_array = json_obj.get_array_throw("UserBox"); + anno_obj.user_box = ImagePixelBox( + size_t(user_box_array[0].to_integer_throw()), + size_t(user_box_array[1].to_integer_throw()), + size_t(user_box_array[2].to_integer_throw()), + size_t(user_box_array[3].to_integer_throw()) + ); + const JsonArray& mask_box_array = json_obj.get_array_throw("MaskBox"); + anno_obj.mask_box = ImagePixelBox( + size_t(mask_box_array[0].to_integer_throw()), + size_t(mask_box_array[1].to_integer_throw()), + size_t(mask_box_array[2].to_integer_throw()), + size_t(mask_box_array[3].to_integer_throw()) + ); + size_t mask_width = anno_obj.mask_box.width(), mask_height = anno_obj.mask_box.height(); + anno_obj.mask.resize(mask_width * mask_height); + const JsonArray& mask_values = json_obj.get_array_throw("Mask"); + for(size_t i = 0; i < anno_obj.mask.size(); i++){ + anno_obj.mask[i] = bool(mask_values[i].to_integer_throw()); + } + + anno_obj.label = json_obj.get_string_throw("Label"); + + return anno_obj; +} + +JsonObject object_annotation_to_json(const ObjectAnnotation& object_annotation){ + JsonObject json_obj; + JsonArray user_box_arr; + user_box_arr.push_back(int64_t(object_annotation.user_box.min_x)); + user_box_arr.push_back(int64_t(object_annotation.user_box.min_y)); + user_box_arr.push_back(int64_t(object_annotation.user_box.max_x)); + user_box_arr.push_back(int64_t(object_annotation.user_box.max_y)); + json_obj["UserBox"] = std::move(user_box_arr); + + JsonArray mask_box_arr; + mask_box_arr.push_back(int64_t(object_annotation.mask_box.min_x)); + mask_box_arr.push_back(int64_t(object_annotation.mask_box.min_y)); + mask_box_arr.push_back(int64_t(object_annotation.mask_box.max_x)); + mask_box_arr.push_back(int64_t(object_annotation.mask_box.max_y)); + json_obj["MaskBox"] = std::move(mask_box_arr); + + JsonArray mask_arr; + for(size_t i = 0; i < object_annotation.mask.size(); i++){ + mask_arr.push_back(int64_t(object_annotation.mask[i])); + } + json_obj["Mask"] = std::move(mask_arr); + + json_obj["Label"] = object_annotation.label; + + return json_obj; +} + + +DrawnBoundingBox::DrawnBoundingBox(LabelImages_Widget& widget, VideoOverlay& overlay) + : m_widget(widget) + , m_overlay(overlay) +{ + auto& program = m_widget.m_program; + program.X.add_listener(*this); + program.Y.add_listener(*this); + program.WIDTH.add_listener(*this); + program.HEIGHT.add_listener(*this); + overlay.add_listener(*this); +} + +DrawnBoundingBox::~DrawnBoundingBox(){ + detach(); +} + +// called when drawn bounding box changed +void DrawnBoundingBox::on_config_value_changed(void* object){ + auto& program = m_widget.m_program; + std::lock_guard lg(m_lock); + program.update_rendered_objects(m_widget.m_overlay_set); +} +void DrawnBoundingBox::on_mouse_press(double x, double y){ + auto& program = m_widget.m_program; + program.WIDTH.set(0); + program.HEIGHT.set(0); + program.X.set(x); + program.Y.set(y); + m_mouse_start.emplace(); + m_mouse_start->first = x; + m_mouse_start->second = y; +} +void DrawnBoundingBox::on_mouse_release(double, double){ + m_mouse_start.reset(); + auto& m_program = m_widget.m_program; + auto& m_overlay_set = m_widget.m_overlay_set; + + m_program.compute_mask(m_overlay_set); +} + +void DrawnBoundingBox::on_mouse_move(double x, double y){ + auto& program = m_widget.m_program; + if (!m_mouse_start){ + return; + } + + double xl = m_mouse_start->first; + double xh = x; + double yl = m_mouse_start->second; + double yh = y; + + if (xl > xh){ + std::swap(xl, xh); + } + if (yl > yh){ + std::swap(yl, yh); + } + + program.X.set(xl); + program.Y.set(yl); + program.WIDTH.set(xh - xl); + program.HEIGHT.set(yh - yl); +} + +void DrawnBoundingBox::detach(){ + auto& program = m_widget.m_program; + m_overlay.remove_listener(*this); + program.X.remove_listener(*this); + program.Y.remove_listener(*this); + program.WIDTH.remove_listener(*this); + program.HEIGHT.remove_listener(*this); +} + + +LabelImages_Descriptor::LabelImages_Descriptor() + : PanelDescriptor( + Color(), + "ML:LabelImages", + "ML", "Label Images", + "", // "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/LabelImages.md", + "Label " + Pokemon::STRING_POKEMON + " on images" + ) +{} + + + +#define ADD_OPTION(x) m_options.add_option(x, #x) + +LabelImages::LabelImages(const LabelImages_Descriptor& descriptor) + : PanelInstance(descriptor) + , m_switch_control_option({}, false) + , m_options(LockMode::UNLOCK_WHILE_RUNNING) + , X("X Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) + , Y("Y Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) + , WIDTH("Width:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) + , HEIGHT("Height:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) + , FORM_LABEL("bulbasaur") + , m_sam_session{RESOURCE_PATH() + "ML/sam_cpu.onnx"} +{ + ADD_OPTION(X); + ADD_OPTION(Y); + ADD_OPTION(WIDTH); + ADD_OPTION(HEIGHT); + ADD_OPTION(FORM_LABEL); +} +void LabelImages::from_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + const JsonValue* value = obj->get_value("SwitchSetup"); + if (value){ + m_switch_control_option.load_json(*value); + } + m_options.load_json(json); +} +JsonValue LabelImages::to_json() const{ + JsonObject obj = std::move(*m_options.to_json().to_object()); + obj["SwitchSetup"] = m_switch_control_option.to_json(); + + // m_annotation_file_path + if (m_annotation_file_path.size() > 0 && !m_fail_to_load_annotation_file){ + JsonArray anno_json_arr; + for(const auto& anno_obj: m_annotated_objects){ + anno_json_arr.push_back(object_annotation_to_json(anno_obj)); + } + cout << "Saving annotation to " << m_annotation_file_path << endl; + anno_json_arr.dump(m_annotation_file_path); + } + return obj; +} +QWidget* LabelImages::make_widget(QWidget& parent, PanelHolder& holder){ + return new LabelImages_Widget(parent, *this, holder); +} + +void LabelImages::load_image_related_data(const std::string& image_path, size_t source_image_width, size_t source_image_height){ + this->source_image_height = source_image_height; + this->source_image_width = source_image_width; + + m_mask_image = ImageRGB32(source_image_width, source_image_height); + cout << "Image source: " << image_path << ", " << source_image_width << " x " << source_image_height << endl; + // if no such embedding file, m_iamge_embedding will be empty + const bool embedding_loaded = load_image_embedding(image_path, m_image_embedding); + if (!embedding_loaded){ + return; // no embedding, then no way for us to annotate + } + // see if we can load the previously created labels + const std::string anno_filename = std::filesystem::path(image_path).filename().replace_extension(".json").string(); + + // ensure the folder exists + std::filesystem::create_directory(ML_ANNOTATION_PATH()); + m_annotation_file_path = ML_ANNOTATION_PATH() + anno_filename; + if (!std::filesystem::exists(m_annotation_file_path)){ + cout << "Annotataion output path, " << m_annotation_file_path << " does not exist yet" << endl; + return; + } + std::string json_content; + const bool anno_loaded = file_to_string(m_annotation_file_path, json_content); + if (!anno_loaded){ + m_fail_to_load_annotation_file = true; + QMessageBox box; + box.warning(nullptr, "Unable to Load Annotation", + QString::fromStdString("Cannot open annotation file " + m_annotation_file_path + ". Probably wrong permission?")); + return; + } + + JsonValue loaded_json = parse_json(json_content); + const JsonArray* json_array = loaded_json.to_array(); + if (json_array == nullptr){ + m_fail_to_load_annotation_file = true; + QMessageBox box; + box.warning(nullptr, "Unable to Load Annotation", + QString::fromStdString("Cannot load annotation file " + m_annotation_file_path + ". Loaded json is not an array")); + return; + } + + for(size_t i = 0; i < json_array->size(); i++){ + try{ + ObjectAnnotation anno_obj = json_to_object_annotation((*json_array)[i]); + m_annotated_objects.emplace_back(std::move(anno_obj)); + } catch(JsonParseException&){ + m_fail_to_load_annotation_file = true; + QMessageBox box; + box.warning(nullptr, "Unable to Load Annotation", + QString::fromStdString( + "Cannot load annotation file " + m_annotation_file_path + + ". Parsing object " + std::to_string(i) + " failed." + ) + ); + } + } + m_last_object_idx = m_annotated_objects.size(); + cout << "Loaded existing annotation file " << m_annotation_file_path << endl; +} + +void LabelImages::update_rendered_objects(VideoOverlaySet& overlay_set){ + overlay_set.clear(); + overlay_set.add(COLOR_RED, {X, Y, WIDTH, HEIGHT}); + + for(size_t i_obj = 0; i_obj < m_annotated_objects.size(); i_obj++){ + const auto& obj = m_annotated_objects[i_obj]; + // overlayset.add(COLOR_RED, pixelbox_to_floatbox(source_image_width, source_image_height, obj.user_box)); + const auto mask_float_box = pixelbox_to_floatbox(source_image_width, source_image_height, obj.mask_box); + std::string label = obj.label; + const Pokemon::PokemonForm* form = Pokemon::get_pokemon_form(label); + if (form != nullptr){ + label = form->display_name(); + } + Color mask_box_color = (i_obj == m_last_object_idx) ? COLOR_BLACK : COLOR_BLUE; + overlay_set.add(mask_box_color, mask_float_box, label); + size_t mask_width = obj.mask_box.width(); + size_t mask_height = obj.mask_box.height(); + ImageRGB32 mask_image(mask_width, mask_height); + // cout << "in render, mask_box " << obj.mask_box.min_x << " " << obj.mask_box.min_y << " " << obj.mask_box.max_x << " " << obj.mask_box.max_y << endl; + + for (size_t y = 0; y < mask_height; y++){ + for (size_t x = 0; x < mask_width; x++){ + const bool mask = obj.mask[y*mask_width + x]; + uint32_t& pixel = mask_image.pixel(x, y); + // if the pixel's mask value is true, set a semi-transparent 45-degree blue strip color + // otherwise: fully transparent (alpha = 0) + uint32_t color = 0; + if (mask){ + color = (std::abs(int(x) - int(y)) % 4 <= 1) ? combine_argb(150, 30, 144, 255) : combine_argb(150, 0, 0, 60); + } + pixel = color; + } + } + // cout << " count " << count << endl; + overlay_set.add(std::move(mask_image), mask_float_box); + } +} + +void LabelImages::compute_mask(VideoOverlaySet& overlay_set){ + const size_t source_width = source_image_width; + const size_t source_height = source_image_height; + + const int box_x = int(X * source_width + 0.5); + const int box_y = int(Y * source_height + 0.5); + const int box_width = int(WIDTH * source_width + 0.5); + const int box_height = int(HEIGHT * source_height + 0.5); + if (box_width == 0 || box_height == 0){ + return; + } + + if (m_image_embedding.size() == 0){ + // no embedding file loaded + return; + } + m_sam_session.run( + m_image_embedding, + (int)source_height, (int)source_width, {}, {}, + {box_x, box_y, box_x + box_width, box_y + box_height}, + m_output_boolean_mask + ); + + size_t min_mask_x = INT_MAX, max_mask_x = 0; + size_t min_mask_y = INT_MAX, max_mask_y = 0; + for (size_t y = 0; y < source_height; y++){ + for (size_t x = 0; x < source_width; x++){ + bool mask = m_output_boolean_mask[y*source_width + x]; + uint32_t& pixel = m_mask_image.pixel(x, y); + // if the pixel's mask value is true, set a semi-transparent 45-degree blue strip color + // otherwise: fully transparent (alpha = 0) + uint32_t color = 0; + if (mask){ + color = (std::abs(int(x) - int(y)) % 4 <= 1) ? combine_argb(150, 30, 144, 255) : combine_argb(150, 0, 0, 60); + min_mask_x = std::min(x, min_mask_x); + max_mask_x = std::max(x, max_mask_x); + min_mask_y = std::min(y, min_mask_y); + max_mask_y = std::max(y, max_mask_y); + } + pixel = color; + } + } + if (min_mask_x < INT_MAX && max_mask_x > min_mask_x && min_mask_y < INT_MAX && max_mask_y > min_mask_y){ + const size_t mask_width = max_mask_x - min_mask_x + 1; + const size_t mask_height = max_mask_y - min_mask_y + 1; + ImageFloatBox mask_box( + min_mask_x/double(source_width), min_mask_y/double(source_height), + mask_width/double(source_width), mask_height/double(source_height)); + const std::string label = FORM_LABEL.slug(); + + + ObjectAnnotation annotation; + annotation.user_box = ImagePixelBox(box_x, box_y, box_x + box_width + 1, box_y + box_height + 1); + annotation.mask_box = ImagePixelBox(min_mask_x, min_mask_y, max_mask_x+1, max_mask_y+1); + annotation.mask.resize(mask_width * mask_height); + for(size_t row = 0; row < mask_height; row++){ + auto it = m_output_boolean_mask.begin() + (min_mask_y + row) * source_width + min_mask_x; + auto it2 = annotation.mask.begin() + row * mask_width; + std::copy(it, it + mask_width, it2); + } + + annotation.label = label; + m_last_object_idx = m_annotated_objects.size(); + m_annotated_objects.emplace_back(std::move(annotation)); + + update_rendered_objects(overlay_set); + } +} + +LabelImages_Widget::~LabelImages_Widget(){ + m_program.FORM_LABEL.remove_listener(*this); + delete m_switch_widget; +} +LabelImages_Widget::LabelImages_Widget( + QWidget& parent, + LabelImages& instance, + PanelHolder& holder +) + : PanelWidget(parent, instance, holder) + , m_program(instance) + , m_session(instance.m_switch_control_option, 0, 0) + , m_overlay_set(m_session.overlay()) + , m_drawn_box(*this, m_session.overlay()) +{ + m_program.FORM_LABEL.add_listener(*this); + + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(make_header(*this)); + + QScrollArea* scroll_outer = new QScrollArea(this); + layout->addWidget(scroll_outer); + scroll_outer->setWidgetResizable(true); + + QWidget* scroll_inner = new QWidget(scroll_outer); + scroll_outer->setWidget(scroll_inner); + QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); + scroll_layout->setAlignment(Qt::AlignTop); + + m_switch_widget = new NintendoSwitch::SwitchSystemWidget(*this, m_session, 0); + scroll_layout->addWidget(m_switch_widget); + + QPushButton* button = new QPushButton("Delete Last Mask", scroll_inner); + scroll_layout->addWidget(button); + connect(button, &QPushButton::clicked, this, [this](bool){ + auto& program = this->m_program; + if (program.m_annotated_objects.size() > 0){ + program.m_annotated_objects.pop_back(); + } + if (program.m_annotated_objects.size() > 0){ + program.m_last_object_idx = program.m_annotated_objects.size() - 1; + } + program.update_rendered_objects(this->m_overlay_set); + }); + + m_option_widget = instance.m_options.make_QtWidget(*scroll_inner); + scroll_layout->addWidget(&m_option_widget->widget()); + + const VideoSourceDescriptor* video_source_desc = instance.m_switch_control_option.m_video.descriptor().get(); + auto image_source_desc = dynamic_cast(video_source_desc); + if (image_source_desc != nullptr){ + const std::string image_path = image_source_desc->path(); + const size_t source_image_height = image_source_desc->source_image_height(); + const size_t source_image_width = image_source_desc->source_image_width(); + m_program.load_image_related_data(image_path, source_image_width, source_image_height); + m_program.update_rendered_objects(m_overlay_set); + } + + cout << "LabelImages_Widget built" << endl; +} + +void LabelImages_Widget::on_config_value_changed(void* object){ + if (m_program.m_annotated_objects.size() > 0 && m_program.m_last_object_idx < m_program.m_annotated_objects.size()){ + std::string& cur_label = m_program.m_annotated_objects[m_program.m_last_object_idx].label; + cur_label = m_program.FORM_LABEL.slug(); + m_program.update_rendered_objects(m_overlay_set); + } +} + + + +} +} + diff --git a/SerialPrograms/Source/ML/Programs/ML_LabelImages.h b/SerialPrograms/Source/ML/Programs/ML_LabelImages.h index 57002fbb8c..543105419f 100644 --- a/SerialPrograms/Source/ML/Programs/ML_LabelImages.h +++ b/SerialPrograms/Source/ML/Programs/ML_LabelImages.h @@ -1,162 +1,162 @@ -/* ML Label Images - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ML_LabelImages_H -#define PokemonAutomation_ML_LabelImages_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/Panels/PanelInstance.h" -#include "CommonFramework/Panels/UI/PanelWidget.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" -#include "Pokemon/Options/Pokemon_HomeSpriteSelectOption.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include -#include "ML/DataLabeling/SegmentAnythingModel.h" - -class QGraphicsView; -class QGraphicsPixmapItem; - -namespace PokemonAutomation{ - - -class ConfigWidget; -namespace NintendoSwitch{ - class SwitchSystemWidget; -} - - -namespace ML{ - - -class LabelImages_Widget; - - -// Store annotation generated by user and ML model on one object -// also include the related overlay rendering. -// Since it owns rendering objects and the rendering framework needs -// the address of the rendering objects to keep track of them, -// never copy or move this ObjectAnnotation object! -struct ObjectAnnotation{ - ImagePixelBox user_box; // user drawn loose bounding box - ImagePixelBox mask_box; - std::vector mask; - std::string label = "unknown"; - - ObjectAnnotation(); -}; - - -class LabelImages_Descriptor : public PanelDescriptor{ -public: - LabelImages_Descriptor(); -}; - -// label image program -class LabelImages : public PanelInstance{ -public: - LabelImages(const LabelImages_Descriptor& descriptor); - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -public: - // Serialization - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - void load_image_related_data(const std::string& image_path, const size_t source_image_width, const size_t source_image_height); - - void update_rendered_objects(VideoOverlaySet& overlayset); - - void compute_mask(VideoOverlaySet& overlay_set); - -private: - friend class LabelImages_Widget; - friend class DrawnBoundingBox; - // switch control options like what micro-controller - // and what video source to use - NintendoSwitch::SwitchSystemOption m_switch_control_option; - // the group option that holds rest of the options defined below: - BatchOption m_options; - - FloatingPointOption X; - FloatingPointOption Y; - FloatingPointOption WIDTH; - FloatingPointOption HEIGHT; - Pokemon::HomeSpriteSelectCell FORM_LABEL; - - size_t source_image_height = 0; - size_t source_image_width = 0; - std::vector m_image_embedding; - std::vector m_output_boolean_mask; - - // buffer to compute SAM mask on - ImageRGB32 m_mask_image; - - SAMSession m_sam_session; - std::vector m_annotated_objects; - size_t m_last_object_idx = 0; - std::string m_annotation_file_path; - // if we find an annotation file that is supposed to be created by user in a previous session, but - // we fail to load it, then we shouldn't overwrite this file to possibly erase the previous work. - // so this flag is used to denote if we fail to load an annotation file - bool m_fail_to_load_annotation_file = false; -}; - - -class DrawnBoundingBox : public ConfigOption::Listener, public VideoOverlay::MouseListener{ -public: - ~DrawnBoundingBox(); - DrawnBoundingBox(LabelImages_Widget& widget, VideoOverlay& overlay); - virtual void on_config_value_changed(void* object) override; - virtual void on_mouse_press(double x, double y) override; - virtual void on_mouse_release(double x, double y) override; - virtual void on_mouse_move(double x, double y) override; - -private: - void detach(); - -private: - LabelImages_Widget& m_widget; - VideoOverlay& m_overlay; - std::mutex m_lock; - - std::optional> m_mouse_start; -}; - - -class LabelImages_Widget : public PanelWidget, public ConfigOption::Listener{ -public: - ~LabelImages_Widget(); - LabelImages_Widget( - QWidget& parent, - LabelImages& instance, - PanelHolder& holder - ); - - virtual void on_config_value_changed(void* object) override; - -private: - LabelImages& m_program; - NintendoSwitch::SwitchSystemSession m_session; - NintendoSwitch::SwitchSystemWidget* m_switch_widget; - VideoOverlaySet m_overlay_set; - DrawnBoundingBox m_drawn_box; - ConfigWidget* m_option_widget; - - friend class DrawnBoundingBox; -}; - - - - -} -} -#endif - +/* ML Label Images + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ML_LabelImages_H +#define PokemonAutomation_ML_LabelImages_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/Panels/PanelInstance.h" +#include "CommonFramework/Panels/UI/PanelWidget.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayTypes.h" +#include "Pokemon/Options/Pokemon_HomeSpriteSelectOption.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include +#include "ML/DataLabeling/SegmentAnythingModel.h" + +class QGraphicsView; +class QGraphicsPixmapItem; + +namespace PokemonAutomation{ + + +class ConfigWidget; +namespace NintendoSwitch{ + class SwitchSystemWidget; +} + + +namespace ML{ + + +class LabelImages_Widget; + + +// Store annotation generated by user and ML model on one object +// also include the related overlay rendering. +// Since it owns rendering objects and the rendering framework needs +// the address of the rendering objects to keep track of them, +// never copy or move this ObjectAnnotation object! +struct ObjectAnnotation{ + ImagePixelBox user_box; // user drawn loose bounding box + ImagePixelBox mask_box; + std::vector mask; + std::string label = "unknown"; + + ObjectAnnotation(); +}; + + +class LabelImages_Descriptor : public PanelDescriptor{ +public: + LabelImages_Descriptor(); +}; + +// label image program +class LabelImages : public PanelInstance{ +public: + LabelImages(const LabelImages_Descriptor& descriptor); + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +public: + // Serialization + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + void load_image_related_data(const std::string& image_path, const size_t source_image_width, const size_t source_image_height); + + void update_rendered_objects(VideoOverlaySet& overlayset); + + void compute_mask(VideoOverlaySet& overlay_set); + +private: + friend class LabelImages_Widget; + friend class DrawnBoundingBox; + // switch control options like what micro-controller + // and what video source to use + NintendoSwitch::SwitchSystemOption m_switch_control_option; + // the group option that holds rest of the options defined below: + BatchOption m_options; + + FloatingPointOption X; + FloatingPointOption Y; + FloatingPointOption WIDTH; + FloatingPointOption HEIGHT; + Pokemon::HomeSpriteSelectCell FORM_LABEL; + + size_t source_image_height = 0; + size_t source_image_width = 0; + std::vector m_image_embedding; + std::vector m_output_boolean_mask; + + // buffer to compute SAM mask on + ImageRGB32 m_mask_image; + + SAMSession m_sam_session; + std::vector m_annotated_objects; + size_t m_last_object_idx = 0; + std::string m_annotation_file_path; + // if we find an annotation file that is supposed to be created by user in a previous session, but + // we fail to load it, then we shouldn't overwrite this file to possibly erase the previous work. + // so this flag is used to denote if we fail to load an annotation file + bool m_fail_to_load_annotation_file = false; +}; + + +class DrawnBoundingBox : public ConfigOption::Listener, public VideoOverlay::MouseListener{ +public: + ~DrawnBoundingBox(); + DrawnBoundingBox(LabelImages_Widget& widget, VideoOverlay& overlay); + virtual void on_config_value_changed(void* object) override; + virtual void on_mouse_press(double x, double y) override; + virtual void on_mouse_release(double x, double y) override; + virtual void on_mouse_move(double x, double y) override; + +private: + void detach(); + +private: + LabelImages_Widget& m_widget; + VideoOverlay& m_overlay; + std::mutex m_lock; + + std::optional> m_mouse_start; +}; + + +class LabelImages_Widget : public PanelWidget, public ConfigOption::Listener{ +public: + ~LabelImages_Widget(); + LabelImages_Widget( + QWidget& parent, + LabelImages& instance, + PanelHolder& holder + ); + + virtual void on_config_value_changed(void* object) override; + +private: + LabelImages& m_program; + NintendoSwitch::SwitchSystemSession m_session; + NintendoSwitch::SwitchSystemWidget* m_switch_widget; + VideoOverlaySet m_overlay_set; + DrawnBoundingBox m_drawn_box; + ConfigWidget* m_option_widget; + + friend class DrawnBoundingBox; +}; + + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp index 4622fdebf4..011389b6cb 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.cpp @@ -1,151 +1,151 @@ -/* Push Button Framework - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch_Commands_Superscalar.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void pbf_wait(ProControllerContext& context, uint16_t ticks){ - ssf_do_nothing(context, ticks); -} -void pbf_wait(ProControllerContext& context, Milliseconds duration){ - ssf_do_nothing(context, duration); -} -void pbf_press_button(ProControllerContext& context, Button button, uint16_t hold_ticks, uint16_t release_ticks){ - ssf_press_button(context, button, (hold_ticks + release_ticks) * 8ms, hold_ticks * 8ms, 0ms); -} -void pbf_press_button(ProControllerContext& context, Button button, Milliseconds hold, Milliseconds release){ - ssf_press_button(context, button, hold + release, hold, 0ms); -} -void pbf_press_dpad(ProControllerContext& context, DpadPosition position, uint16_t hold_ticks, uint16_t release_ticks){ - ssf_press_dpad(context, position, (hold_ticks + release_ticks) * 8ms, hold_ticks * 8ms, 0ms); -} -void pbf_press_dpad(ProControllerContext& context, DpadPosition position, Milliseconds hold, Milliseconds release){ - ssf_press_dpad(context, position, hold + release, hold, 0ms); -} -void pbf_move_left_joystick(ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks){ - uint32_t delay = (uint32_t)hold_ticks + release_ticks; - if ((uint16_t)delay == delay){ - ssf_press_left_joystick(context, x, y, (uint16_t)delay, hold_ticks, 0); - }else{ - ssf_press_left_joystick(context, x, y, hold_ticks, hold_ticks, 0); - ssf_do_nothing(context, release_ticks); - } -} -void pbf_move_left_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release){ - ssf_press_left_joystick(context, x, y, hold + release, hold, 0ms); -} -void pbf_move_right_joystick(ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks){ - uint32_t delay = (uint32_t)hold_ticks + release_ticks; - if ((uint16_t)delay == delay){ - ssf_press_right_joystick(context, x, y, (uint16_t)delay, hold_ticks, 0); - }else{ - ssf_press_right_joystick(context, x, y, hold_ticks, hold_ticks, 0); - ssf_do_nothing(context, release_ticks); - } -} -void pbf_move_right_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release){ - ssf_press_right_joystick(context, x, y, hold + release, hold, 0ms); -} -void pbf_mash_button(ProControllerContext& context, Button button, uint16_t ticks){ - ssf_mash1_button(context, button, ticks); -} -void pbf_mash_button(ProControllerContext& context, Button button, Milliseconds duration){ - ssf_mash1_button(context, button, duration); -} - -void grip_menu_connect_go_home(ProControllerContext& context){ - pbf_press_button(context, BUTTON_L | BUTTON_R, 10, 40); - pbf_press_button(context, BUTTON_A, 10, 140); - pbf_press_button(context, BUTTON_HOME, 80ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); -} - - -void pbf_controller_state( - ProControllerContext& context, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y, - uint16_t ticks -){ - context->issue_full_controller_state( - &context, - ticks*8ms, - button, position, - left_x, left_y, - right_x, right_y - ); -} -void pbf_controller_state( - ProControllerContext& context, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y, - Milliseconds duration -){ - context->issue_full_controller_state( - &context, - duration, - button, position, - left_x, left_y, - right_x, right_y - ); -} - - - - -void pbf_wait(JoyconContext& context, Milliseconds duration){ - ssf_do_nothing(context, duration); -} -void pbf_press_button(JoyconContext& context, Button button, Milliseconds hold, Milliseconds release){ - ssf_press_button(context, button, hold + release, hold, 0ms); -} -void pbf_move_joystick(JoyconContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release){ - ssf_press_joystick(context, x, y, hold + release, hold, 0ms); -} -void pbf_mash_button(JoyconContext& context, Button button, Milliseconds duration){ - ssf_mash1_button(context, button, duration); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} - - +/* Push Button Framework + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch_Commands_Superscalar.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void pbf_wait(ProControllerContext& context, uint16_t ticks){ + ssf_do_nothing(context, ticks); +} +void pbf_wait(ProControllerContext& context, Milliseconds duration){ + ssf_do_nothing(context, duration); +} +void pbf_press_button(ProControllerContext& context, Button button, uint16_t hold_ticks, uint16_t release_ticks){ + ssf_press_button(context, button, (hold_ticks + release_ticks) * 8ms, hold_ticks * 8ms, 0ms); +} +void pbf_press_button(ProControllerContext& context, Button button, Milliseconds hold, Milliseconds release){ + ssf_press_button(context, button, hold + release, hold, 0ms); +} +void pbf_press_dpad(ProControllerContext& context, DpadPosition position, uint16_t hold_ticks, uint16_t release_ticks){ + ssf_press_dpad(context, position, (hold_ticks + release_ticks) * 8ms, hold_ticks * 8ms, 0ms); +} +void pbf_press_dpad(ProControllerContext& context, DpadPosition position, Milliseconds hold, Milliseconds release){ + ssf_press_dpad(context, position, hold + release, hold, 0ms); +} +void pbf_move_left_joystick(ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks){ + uint32_t delay = (uint32_t)hold_ticks + release_ticks; + if ((uint16_t)delay == delay){ + ssf_press_left_joystick(context, x, y, (uint16_t)delay, hold_ticks, 0); + }else{ + ssf_press_left_joystick(context, x, y, hold_ticks, hold_ticks, 0); + ssf_do_nothing(context, release_ticks); + } +} +void pbf_move_left_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release){ + ssf_press_left_joystick(context, x, y, hold + release, hold, 0ms); +} +void pbf_move_right_joystick(ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks){ + uint32_t delay = (uint32_t)hold_ticks + release_ticks; + if ((uint16_t)delay == delay){ + ssf_press_right_joystick(context, x, y, (uint16_t)delay, hold_ticks, 0); + }else{ + ssf_press_right_joystick(context, x, y, hold_ticks, hold_ticks, 0); + ssf_do_nothing(context, release_ticks); + } +} +void pbf_move_right_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release){ + ssf_press_right_joystick(context, x, y, hold + release, hold, 0ms); +} +void pbf_mash_button(ProControllerContext& context, Button button, uint16_t ticks){ + ssf_mash1_button(context, button, ticks); +} +void pbf_mash_button(ProControllerContext& context, Button button, Milliseconds duration){ + ssf_mash1_button(context, button, duration); +} + +void grip_menu_connect_go_home(ProControllerContext& context){ + pbf_press_button(context, BUTTON_L | BUTTON_R, 10, 40); + pbf_press_button(context, BUTTON_A, 10, 140); + pbf_press_button(context, BUTTON_HOME, 80ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); +} + + +void pbf_controller_state( + ProControllerContext& context, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y, + uint16_t ticks +){ + context->issue_full_controller_state( + &context, + ticks*8ms, + button, position, + left_x, left_y, + right_x, right_y + ); +} +void pbf_controller_state( + ProControllerContext& context, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y, + Milliseconds duration +){ + context->issue_full_controller_state( + &context, + duration, + button, position, + left_x, left_y, + right_x, right_y + ); +} + + + + +void pbf_wait(JoyconContext& context, Milliseconds duration){ + ssf_do_nothing(context, duration); +} +void pbf_press_button(JoyconContext& context, Button button, Milliseconds hold, Milliseconds release){ + ssf_press_button(context, button, hold + release, hold, 0ms); +} +void pbf_move_joystick(JoyconContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release){ + ssf_press_joystick(context, x, y, hold + release, hold, 0ms); +} +void pbf_mash_button(JoyconContext& context, Button button, Milliseconds duration){ + ssf_mash1_button(context, button, duration); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} + + diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h index 72cfbef749..ddeef514a1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h @@ -1,129 +1,129 @@ -/* Push Button Framework (pbf_*) - * - * From: https://github.com/PokemonAutomation/ - * - * The functions to send Switch commands to the micro controller. - * The timing of the commands are measured in ticks. One second is 125 ticks. - * - * **New** Overloads have been added that use milliseconds instead of ticks. - * If the underlying controller doesn't support millisecond precision, it will - * be rounded up to whatever granularity it does support. - * - * You should use these functions (instead of ssf_*) whenever possible since - * these are cleaner and easier to use/understand. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Commands_PushButtons_H -#define PokemonAutomation_NintendoSwitch_Commands_PushButtons_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -using namespace std::chrono_literals; - - -// Wait for this many ticks on the Switch. -void pbf_wait (ProControllerContext& context, uint16_t ticks); -void pbf_wait (ProControllerContext& context, Milliseconds duration); - -// Press a Switch controller button (excluding D-Pad). Hold the button for `hold_ticks`, then release it for `release_ticks`. -// The buttons are defined in Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h. Examples include BUTTON_A, BUTTON_ZL. -// The buttons also include clicking joysticks: BUTTON_LCLICK, BUTTON_RCLICK. -// D-Pad buttons and directional movements of joysticks are controlled by separate functions. -void pbf_press_button (ProControllerContext& context, Button button, uint16_t hold_ticks, uint16_t release_ticks); -void pbf_press_button (ProControllerContext& context, Button button, Milliseconds hold, Milliseconds release); - -// Press a Switch controller D-Pad button. Hold the button for `hold_ticks`, then release it for `release_ticks`. -// The buttons are defined in Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h. Examples include DPAD_DOWN, DPAD_UP_RIGHT. -void pbf_press_dpad (ProControllerContext& context, DpadPosition position, uint16_t hold_ticks, uint16_t release_ticks); -void pbf_press_dpad (ProControllerContext& context, DpadPosition position, Milliseconds hold, Milliseconds release); - -// Move left joystick towards a 2D direction. Hold the direction for `hold_ticks`, then release it for `release_ticks`. -// The direction is specified by (x, y): -// x = 0 : left -// x = 128 : neutral -// x = 255 : right -// y = 0 : up -// y = 128 : neutral -// y = 255 : down -// Example: move the joystick fully left: (x, y) = (0, 128) -// move the joystick upper-right: (x, y) = (255, 0) -void pbf_move_left_joystick (ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks); -void pbf_move_left_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release); - -// Move right joystick towards a 2D direction. Hold the direction for `hold_ticks`, then release it for `release_ticks`. -// The direction is specified by (x, y): -// x = 0 : left -// x = 128 : neutral -// x = 255 : right -// y = 0 : up -// y = 128 : neutral -// y = 255 : down -// Example: move the joystick fully left: (x, y) = (0, 128) -// move the joystick upper-right: (x, y) = (255, 0) -void pbf_move_right_joystick (ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks); -void pbf_move_right_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release); - -// Mash a Switch controller button (excluding D-Pad) repeatedly for `ticks` ticks. -// The buttons are defined in Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h. Examples include BUTTON_A, BUTTON_ZL. -// The buttons also include clicking joysticks: BUTTON_LCLICK, BUTTON_RCLICK. -void pbf_mash_button (ProControllerContext& context, Button button, uint16_t ticks); -void pbf_mash_button (ProControllerContext& context, Button button, Milliseconds duration); - -//void start_program_flash (ProControllerContext& context, uint16_t ticks); -void grip_menu_connect_go_home (ProControllerContext& context); - - - -// -// Press all the following buttons/joysticks simultaneously for the specified -// duration. No wait is added at the end. Thus you can issue these back-to-back -// to simulate buttons being pressed and released concurrently with other -// buttons being held down the whole time. -// -// Note that this function does not play well with unfinished ssf_* functions. -// If there is a pending ssf_* function, a conflicting button press by this -// function (and possibly more) will be delayed - thus causing the buttons in -// this function call to not issue simultaneously. The exact behavior is -// undefined so you should never do this. -// -// The sole purpose of this function is for keyboard commands. For in-program -// button overlapping, you should use ssf_* directly. (though lots of existing -// programs already use this for overlapping) -// -void pbf_controller_state( - ProControllerContext& context, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y, - uint16_t ticks -); -void pbf_controller_state( - ProControllerContext& context, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y, - Milliseconds duration -); - - - - -void pbf_wait (JoyconContext& context, Milliseconds duration); -void pbf_press_button (JoyconContext& context, Button button, Milliseconds hold, Milliseconds release); -void pbf_move_joystick (JoyconContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release); -void pbf_mash_button (JoyconContext& context, Button button, Milliseconds duration); - - - - -} -} -#endif +/* Push Button Framework (pbf_*) + * + * From: https://github.com/PokemonAutomation/ + * + * The functions to send Switch commands to the micro controller. + * The timing of the commands are measured in ticks. One second is 125 ticks. + * + * **New** Overloads have been added that use milliseconds instead of ticks. + * If the underlying controller doesn't support millisecond precision, it will + * be rounded up to whatever granularity it does support. + * + * You should use these functions (instead of ssf_*) whenever possible since + * these are cleaner and easier to use/understand. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Commands_PushButtons_H +#define PokemonAutomation_NintendoSwitch_Commands_PushButtons_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +using namespace std::chrono_literals; + + +// Wait for this many ticks on the Switch. +void pbf_wait (ProControllerContext& context, uint16_t ticks); +void pbf_wait (ProControllerContext& context, Milliseconds duration); + +// Press a Switch controller button (excluding D-Pad). Hold the button for `hold_ticks`, then release it for `release_ticks`. +// The buttons are defined in Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h. Examples include BUTTON_A, BUTTON_ZL. +// The buttons also include clicking joysticks: BUTTON_LCLICK, BUTTON_RCLICK. +// D-Pad buttons and directional movements of joysticks are controlled by separate functions. +void pbf_press_button (ProControllerContext& context, Button button, uint16_t hold_ticks, uint16_t release_ticks); +void pbf_press_button (ProControllerContext& context, Button button, Milliseconds hold, Milliseconds release); + +// Press a Switch controller D-Pad button. Hold the button for `hold_ticks`, then release it for `release_ticks`. +// The buttons are defined in Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h. Examples include DPAD_DOWN, DPAD_UP_RIGHT. +void pbf_press_dpad (ProControllerContext& context, DpadPosition position, uint16_t hold_ticks, uint16_t release_ticks); +void pbf_press_dpad (ProControllerContext& context, DpadPosition position, Milliseconds hold, Milliseconds release); + +// Move left joystick towards a 2D direction. Hold the direction for `hold_ticks`, then release it for `release_ticks`. +// The direction is specified by (x, y): +// x = 0 : left +// x = 128 : neutral +// x = 255 : right +// y = 0 : up +// y = 128 : neutral +// y = 255 : down +// Example: move the joystick fully left: (x, y) = (0, 128) +// move the joystick upper-right: (x, y) = (255, 0) +void pbf_move_left_joystick (ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks); +void pbf_move_left_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release); + +// Move right joystick towards a 2D direction. Hold the direction for `hold_ticks`, then release it for `release_ticks`. +// The direction is specified by (x, y): +// x = 0 : left +// x = 128 : neutral +// x = 255 : right +// y = 0 : up +// y = 128 : neutral +// y = 255 : down +// Example: move the joystick fully left: (x, y) = (0, 128) +// move the joystick upper-right: (x, y) = (255, 0) +void pbf_move_right_joystick (ProControllerContext& context, uint8_t x, uint8_t y, uint16_t hold_ticks, uint16_t release_ticks); +void pbf_move_right_joystick (ProControllerContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release); + +// Mash a Switch controller button (excluding D-Pad) repeatedly for `ticks` ticks. +// The buttons are defined in Common/NintendoSwitch/NintendoSwitch_ControllerDefs.h. Examples include BUTTON_A, BUTTON_ZL. +// The buttons also include clicking joysticks: BUTTON_LCLICK, BUTTON_RCLICK. +void pbf_mash_button (ProControllerContext& context, Button button, uint16_t ticks); +void pbf_mash_button (ProControllerContext& context, Button button, Milliseconds duration); + +//void start_program_flash (ProControllerContext& context, uint16_t ticks); +void grip_menu_connect_go_home (ProControllerContext& context); + + + +// +// Press all the following buttons/joysticks simultaneously for the specified +// duration. No wait is added at the end. Thus you can issue these back-to-back +// to simulate buttons being pressed and released concurrently with other +// buttons being held down the whole time. +// +// Note that this function does not play well with unfinished ssf_* functions. +// If there is a pending ssf_* function, a conflicting button press by this +// function (and possibly more) will be delayed - thus causing the buttons in +// this function call to not issue simultaneously. The exact behavior is +// undefined so you should never do this. +// +// The sole purpose of this function is for keyboard commands. For in-program +// button overlapping, you should use ssf_* directly. (though lots of existing +// programs already use this for overlapping) +// +void pbf_controller_state( + ProControllerContext& context, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y, + uint16_t ticks +); +void pbf_controller_state( + ProControllerContext& context, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y, + Milliseconds duration +); + + + + +void pbf_wait (JoyconContext& context, Milliseconds duration); +void pbf_press_button (JoyconContext& context, Button button, Milliseconds hold, Milliseconds release); +void pbf_move_joystick (JoyconContext& context, uint8_t x, uint8_t y, Milliseconds hold, Milliseconds release); +void pbf_mash_button (JoyconContext& context, Button button, Milliseconds duration); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp index 15ec2fb54f..27ee2d875e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.cpp @@ -1,112 +1,112 @@ -/* General Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include -#include "ClientSource/Libraries/MessageConverter.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -//#include "NintendoSwitch_Messages_Routines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void close_game(ConsoleHandle& console, ProControllerContext& context){ - // Use mashing to ensure that the X press succeeds. If it fails, the SR - // will fail and can kill a den for the autohosts. - - // this sequence will close the game from the home screen, - // regardless of whether the game is initially open or closed. - - // if game initially open. | if game initially closed - pbf_mash_button(context, BUTTON_X, 100); // - Close game. | - does nothing - ssf_press_dpad_ptv(context, DPAD_DOWN); // - Does nothing. | - moves selector away from the closed game to avoid opening it. - ssf_press_dpad_ptv(context, DPAD_DOWN); // - Does nothing. | - Press Down a second time in case we drop one. - pbf_mash_button(context, BUTTON_A, 50); // - Confirm close game. | - opens an app on the home screen (e.g. Online) - // - Does nothing. | - goes back to home screen. - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - context.wait_for_all_requests(); - -// cout << "waiting..." << endl; -// context.wait_for(10s); - - // send a second Home button press, if the first one is dropped - bool video_available = (bool)console.video().snapshot(); - if (video_available){ - HomeMenuWatcher detector(console); - int ret = wait_until( - console, context, - std::chrono::milliseconds(5000), - { detector } - ); - if (ret == 0){ - console.log("Detected Home screen."); - }else{ // if game initially open. | if game initially closed - // initial Home button press was dropped - // - Does nothing. | - goes back to home screen, from opened app - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - } - }else{ - // - wait some time after first Home button press - // to avoid triggering zoom - context.wait_for(std::chrono::milliseconds(1000)); - // - Does nothing. | - Press Home a second time in case we drop one. - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - } - - - // fail-safe against button drops and unexpected error messages. - pbf_mash_button(context, BUTTON_X, 50); - pbf_mash_button(context, BUTTON_B, 350); -} - -void close_game(ConsoleHandle& console, JoyconContext& context){ - // Use mashing to ensure that the X press succeeds. If it fails, the SR - // will fail and can kill a den for the autohosts. - - // this sequence will close the game from the home screen, - // regardless of whether the game is initially open or closed. - - // if game initially open. | if game initially closed - pbf_mash_button(context, BUTTON_X, 800ms); // - Close game. | - does nothing - pbf_move_joystick(context, 128, 255, 100ms, 10ms); // - Does nothing. | - moves selector away from the closed game to avoid opening it. - pbf_move_joystick(context, 128, 255, 100ms, 10ms); // - Does nothing. | - Press Down a second time in case we drop one. - pbf_mash_button(context, BUTTON_A, 400ms); // - Confirm close game. | - opens an app on the home screen (e.g. Online) - // - Does nothing. | - goes back to home screen. - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - context.wait_for_all_requests(); - - HomeMenuWatcher detector(console); - int ret = wait_until( - console, context, - std::chrono::milliseconds(5000), - { detector } - ); - if (ret == 0){ - console.log("Detected Home screen."); - }else{ // if game initially open. | if game initially closed - // initial Home button press was dropped - // - Does nothing. | - goes back to home screen, from opened app - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - } - - // fail-safe against button drops and unexpected error messages. - pbf_mash_button(context, BUTTON_X, 400ms); - pbf_mash_button(context, BUTTON_B, 2000ms); -} - - -} -} +/* General Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include +#include "ClientSource/Libraries/MessageConverter.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +//#include "NintendoSwitch_Messages_Routines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void close_game(ConsoleHandle& console, ProControllerContext& context){ + // Use mashing to ensure that the X press succeeds. If it fails, the SR + // will fail and can kill a den for the autohosts. + + // this sequence will close the game from the home screen, + // regardless of whether the game is initially open or closed. + + // if game initially open. | if game initially closed + pbf_mash_button(context, BUTTON_X, 100); // - Close game. | - does nothing + ssf_press_dpad_ptv(context, DPAD_DOWN); // - Does nothing. | - moves selector away from the closed game to avoid opening it. + ssf_press_dpad_ptv(context, DPAD_DOWN); // - Does nothing. | - Press Down a second time in case we drop one. + pbf_mash_button(context, BUTTON_A, 50); // - Confirm close game. | - opens an app on the home screen (e.g. Online) + // - Does nothing. | - goes back to home screen. + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + context.wait_for_all_requests(); + +// cout << "waiting..." << endl; +// context.wait_for(10s); + + // send a second Home button press, if the first one is dropped + bool video_available = (bool)console.video().snapshot(); + if (video_available){ + HomeMenuWatcher detector(console); + int ret = wait_until( + console, context, + std::chrono::milliseconds(5000), + { detector } + ); + if (ret == 0){ + console.log("Detected Home screen."); + }else{ // if game initially open. | if game initially closed + // initial Home button press was dropped + // - Does nothing. | - goes back to home screen, from opened app + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + } + }else{ + // - wait some time after first Home button press + // to avoid triggering zoom + context.wait_for(std::chrono::milliseconds(1000)); + // - Does nothing. | - Press Home a second time in case we drop one. + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + } + + + // fail-safe against button drops and unexpected error messages. + pbf_mash_button(context, BUTTON_X, 50); + pbf_mash_button(context, BUTTON_B, 350); +} + +void close_game(ConsoleHandle& console, JoyconContext& context){ + // Use mashing to ensure that the X press succeeds. If it fails, the SR + // will fail and can kill a den for the autohosts. + + // this sequence will close the game from the home screen, + // regardless of whether the game is initially open or closed. + + // if game initially open. | if game initially closed + pbf_mash_button(context, BUTTON_X, 800ms); // - Close game. | - does nothing + pbf_move_joystick(context, 128, 255, 100ms, 10ms); // - Does nothing. | - moves selector away from the closed game to avoid opening it. + pbf_move_joystick(context, 128, 255, 100ms, 10ms); // - Does nothing. | - Press Down a second time in case we drop one. + pbf_mash_button(context, BUTTON_A, 400ms); // - Confirm close game. | - opens an app on the home screen (e.g. Online) + // - Does nothing. | - goes back to home screen. + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + context.wait_for_all_requests(); + + HomeMenuWatcher detector(console); + int ret = wait_until( + console, context, + std::chrono::milliseconds(5000), + { detector } + ); + if (ret == 0){ + console.log("Detected Home screen."); + }else{ // if game initially open. | if game initially closed + // initial Home button press was dropped + // - Does nothing. | - goes back to home screen, from opened app + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + } + + // fail-safe against button drops and unexpected error messages. + pbf_mash_button(context, BUTTON_X, 400ms); + pbf_mash_button(context, BUTTON_B, 2000ms); +} + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h index d584d2a163..8f0b8b3b80 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h @@ -1,28 +1,28 @@ -/* General Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Commands_Routines_H -#define PokemonAutomation_NintendoSwitch_Commands_Routines_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void close_game(ConsoleHandle& console, ProControllerContext& device); - -void close_game(ConsoleHandle& console, JoyconContext& device); - - - - -} -} -#endif +/* General Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Commands_Routines_H +#define PokemonAutomation_NintendoSwitch_Commands_Routines_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void close_game(ConsoleHandle& console, ProControllerContext& device); + +void close_game(ConsoleHandle& console, JoyconContext& device); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp index 016c04b292..1d0fd18457 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.cpp @@ -1,182 +1,182 @@ -/* Superscalar Framework - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch_Commands_Superscalar.h" -//#include "NintendoSwitch_Messages_Superscalar.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void ssf_flush_pipeline(ProControllerContext& context){ - context->issue_barrier(&context); -} -void ssf_do_nothing(ProControllerContext& context, uint16_t ticks){ - context->issue_nop(&context, ticks*8ms); -} -void ssf_do_nothing(ProControllerContext& context, Milliseconds duration){ - context->issue_nop(&context, duration); -} - - -void ssf_press_button( - ProControllerContext& context, - Button button, - uint16_t delay, uint16_t hold, uint8_t cool -){ - context->issue_buttons( - &context, - delay*8ms, hold*8ms, cool*8ms, - button - ); -} -void ssf_press_button( - ProControllerContext& context, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_buttons(&context, delay, hold, cool, button); -} - -void ssf_press_dpad( - ProControllerContext& context, - DpadPosition position, - uint16_t delay, uint16_t hold, uint8_t cool -){ - context->issue_dpad( - &context, - delay*8ms, hold*8ms, cool*8ms, - position - ); -} -void ssf_press_dpad( - ProControllerContext& context, - DpadPosition position, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_dpad(&context, delay, hold, cool, position); -} - -void ssf_press_left_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - uint16_t delay, uint16_t hold, uint8_t cool -){ - context->issue_left_joystick( - &context, - delay*8ms, hold*8ms, cool*8ms, - x, y - ); -} -void ssf_press_left_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_left_joystick(&context, delay, hold, cool, x, y); -} -void ssf_press_right_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - uint16_t delay, uint16_t hold, uint8_t cool -){ - context->issue_right_joystick( - &context, - delay*8ms, hold*8ms, cool*8ms, - x, y - ); -} -void ssf_press_right_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_right_joystick(&context, delay, hold, cool, x, y); -} - - - -void ssf_mash1_button(ProControllerContext& context, Button button, uint16_t ticks){ - context->issue_mash_button(&context, ticks*8ms, button); -} -void ssf_mash1_button(ProControllerContext& context, Button button, Milliseconds duration){ - context->issue_mash_button(&context, duration, button); -} -void ssf_mash2_button(ProControllerContext& context, Button button0, Button button1, uint16_t ticks){ - context->issue_mash_button(&context, ticks*8ms, button0, button1); -} -void ssf_mash2_button(ProControllerContext& context, Button button0, Button button1, Milliseconds duration){ - context->issue_mash_button(&context, duration, button0, button1); -} -void ssf_mash_AZs(ProControllerContext& context, uint16_t ticks){ - context->issue_mash_AZs(&context, ticks*8ms); -} -void ssf_mash_AZs(ProControllerContext& context, Milliseconds duration){ - context->issue_mash_AZs(&context, duration); -} -void ssf_issue_scroll( - ProControllerContext& context, - DpadPosition direction, - uint16_t delay, uint16_t hold, uint8_t cool -){ - context->issue_system_scroll( - &context, - delay*8ms, hold*8ms, cool*8ms, - direction - ); -} -void ssf_issue_scroll( - ProControllerContext& context, - DpadPosition direction, - Milliseconds delay -){ - context->issue_system_scroll(&context, delay, 2*delay, delay, direction); -} -void ssf_issue_scroll( - ProControllerContext& context, - DpadPosition direction, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_system_scroll(&context, delay, hold, cool, direction); -} - - - - -void ssf_flush_pipeline(JoyconContext& context){ - context->issue_barrier(&context); -} -void ssf_do_nothing(JoyconContext& context, Milliseconds duration){ - context->issue_nop(&context, duration); -} -void ssf_press_button( - JoyconContext& context, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_buttons(&context, button, delay, hold, cool); -} -void ssf_press_joystick( - JoyconContext& context, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cool -){ - context->issue_joystick(&context, x, y, delay, hold, cool); -} -void ssf_mash1_button(JoyconContext& context, Button button, Milliseconds duration){ - context->issue_mash_button(&context, button, duration); -} - - - - - - - -} -} +/* Superscalar Framework + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch_Commands_Superscalar.h" +//#include "NintendoSwitch_Messages_Superscalar.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void ssf_flush_pipeline(ProControllerContext& context){ + context->issue_barrier(&context); +} +void ssf_do_nothing(ProControllerContext& context, uint16_t ticks){ + context->issue_nop(&context, ticks*8ms); +} +void ssf_do_nothing(ProControllerContext& context, Milliseconds duration){ + context->issue_nop(&context, duration); +} + + +void ssf_press_button( + ProControllerContext& context, + Button button, + uint16_t delay, uint16_t hold, uint8_t cool +){ + context->issue_buttons( + &context, + delay*8ms, hold*8ms, cool*8ms, + button + ); +} +void ssf_press_button( + ProControllerContext& context, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_buttons(&context, delay, hold, cool, button); +} + +void ssf_press_dpad( + ProControllerContext& context, + DpadPosition position, + uint16_t delay, uint16_t hold, uint8_t cool +){ + context->issue_dpad( + &context, + delay*8ms, hold*8ms, cool*8ms, + position + ); +} +void ssf_press_dpad( + ProControllerContext& context, + DpadPosition position, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_dpad(&context, delay, hold, cool, position); +} + +void ssf_press_left_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + uint16_t delay, uint16_t hold, uint8_t cool +){ + context->issue_left_joystick( + &context, + delay*8ms, hold*8ms, cool*8ms, + x, y + ); +} +void ssf_press_left_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_left_joystick(&context, delay, hold, cool, x, y); +} +void ssf_press_right_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + uint16_t delay, uint16_t hold, uint8_t cool +){ + context->issue_right_joystick( + &context, + delay*8ms, hold*8ms, cool*8ms, + x, y + ); +} +void ssf_press_right_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_right_joystick(&context, delay, hold, cool, x, y); +} + + + +void ssf_mash1_button(ProControllerContext& context, Button button, uint16_t ticks){ + context->issue_mash_button(&context, ticks*8ms, button); +} +void ssf_mash1_button(ProControllerContext& context, Button button, Milliseconds duration){ + context->issue_mash_button(&context, duration, button); +} +void ssf_mash2_button(ProControllerContext& context, Button button0, Button button1, uint16_t ticks){ + context->issue_mash_button(&context, ticks*8ms, button0, button1); +} +void ssf_mash2_button(ProControllerContext& context, Button button0, Button button1, Milliseconds duration){ + context->issue_mash_button(&context, duration, button0, button1); +} +void ssf_mash_AZs(ProControllerContext& context, uint16_t ticks){ + context->issue_mash_AZs(&context, ticks*8ms); +} +void ssf_mash_AZs(ProControllerContext& context, Milliseconds duration){ + context->issue_mash_AZs(&context, duration); +} +void ssf_issue_scroll( + ProControllerContext& context, + DpadPosition direction, + uint16_t delay, uint16_t hold, uint8_t cool +){ + context->issue_system_scroll( + &context, + delay*8ms, hold*8ms, cool*8ms, + direction + ); +} +void ssf_issue_scroll( + ProControllerContext& context, + DpadPosition direction, + Milliseconds delay +){ + context->issue_system_scroll(&context, delay, 2*delay, delay, direction); +} +void ssf_issue_scroll( + ProControllerContext& context, + DpadPosition direction, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_system_scroll(&context, delay, hold, cool, direction); +} + + + + +void ssf_flush_pipeline(JoyconContext& context){ + context->issue_barrier(&context); +} +void ssf_do_nothing(JoyconContext& context, Milliseconds duration){ + context->issue_nop(&context, duration); +} +void ssf_press_button( + JoyconContext& context, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_buttons(&context, button, delay, hold, cool); +} +void ssf_press_joystick( + JoyconContext& context, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cool +){ + context->issue_joystick(&context, x, y, delay, hold, cool); +} +void ssf_mash1_button(JoyconContext& context, Button button, Milliseconds duration){ + context->issue_mash_button(&context, button, duration); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h index e71c4029e9..510b8c8df0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h +++ b/SerialPrograms/Source/NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h @@ -1,196 +1,196 @@ -/* Superscalar Framework (ssf_*) - * - * From: https://github.com/PokemonAutomation/ - * - * Don't use these unless you know what you're doing and you really need to. - * - * If you don't understand how the state machine works, you will not be able - * to properly use these functions. - * - * Since the functionality here used to be internal-only, documentation remains - * sparse for now and slated to be expanded in the future. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Commands_Superscalar_H -#define PokemonAutomation_NintendoSwitch_Commands_Superscalar_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - -void ssf_flush_pipeline (ProControllerContext& context); -void ssf_do_nothing (ProControllerContext& context, uint16_t ticks); -void ssf_do_nothing (ProControllerContext& context, Milliseconds duration); - - -void ssf_press_button( - ProControllerContext& context, - Button button, - Milliseconds delay = 24ms, Milliseconds hold = 48ms, Milliseconds cool = 24ms -); -void ssf_press_dpad( - ProControllerContext& context, - DpadPosition position, - Milliseconds delay, Milliseconds hold = 48ms, Milliseconds cool = 24ms -); - - -void ssf_press_left_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - uint16_t delay, uint16_t hold, uint8_t cool = 0 -); -void ssf_press_left_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms -); -void ssf_press_right_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - uint16_t delay, uint16_t hold, uint8_t cool = 0 -); -void ssf_press_right_joystick( - ProControllerContext& context, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms -); - - -void ssf_mash1_button (ProControllerContext& context, Button button, uint16_t ticks); -void ssf_mash1_button (ProControllerContext& context, Button button, Milliseconds duration); - -void ssf_mash2_button (ProControllerContext& context, Button button0, Button button1, uint16_t ticks); -void ssf_mash2_button (ProControllerContext& context, Button button0, Button button1, Milliseconds duration); - -void ssf_mash_AZs (ProControllerContext& context, uint16_t ticks); -void ssf_mash_AZs (ProControllerContext& context, Milliseconds duration); - - -// Diagonal scrolling seems to count as seperate events for each direction. -// In other words, they don't work. -#define SSF_SCROLL_UP DPAD_UP -#define SSF_SCROLL_RIGHT DPAD_RIGHT -#define SSF_SCROLL_DOWN DPAD_DOWN -#define SSF_SCROLL_LEFT DPAD_LEFT -void ssf_issue_scroll( - ProControllerContext& context, - DpadPosition direction, - Milliseconds delay -); -void ssf_issue_scroll( - ProControllerContext& context, - DpadPosition direction, - Milliseconds delay, Milliseconds hold, Milliseconds cool -); - - - - - -// -// ptv = plus timing variation -// -// These are simple wrappers that add "context->timing_variation()" to -// every timing. Mostly intended for Switch menu navigation where we usually -// attempt fast movements. -// -inline void ssf_press_button_ptv( - ProControllerContext& context, - Button button, - Milliseconds delay = 24ms -){ - Milliseconds tv = context->timing_variation(); - if (delay > 0ms) delay += tv; - ssf_press_button(context, button, delay); -} -inline void ssf_press_button_ptv( - ProControllerContext& context, - Button button, - Milliseconds delay, - Milliseconds hold, - Milliseconds cool = 24ms -){ - Milliseconds tv = context->timing_variation(); - if (delay > 0ms) delay += tv; - if (hold > 0ms) hold += tv; - if (cool > 0ms) cool += tv; - ssf_press_button(context, button, delay, hold, cool); -} -inline void ssf_press_dpad_ptv( - ProControllerContext& context, - DpadPosition position, - Milliseconds delay = 24ms -){ - Milliseconds tv = context->timing_variation(); - if (delay > 0ms) delay += tv; - ssf_press_dpad(context, position, delay); -} -inline void ssf_press_dpad_ptv( - ProControllerContext& context, - DpadPosition position, - Milliseconds delay, - Milliseconds hold, - Milliseconds cool = 24ms -){ - Milliseconds tv = context->timing_variation(); - if (delay > 0ms) delay += tv; - if (hold > 0ms) hold += tv; - if (cool > 0ms) cool += tv; - ssf_press_dpad(context, position, delay, hold, cool); -} -inline void ssf_issue_scroll_ptv( - ProControllerContext& context, - DpadPosition direction, - Milliseconds delay = 24ms -){ - Milliseconds tv = context->timing_variation(); - if (delay > 0ms) delay += tv; - ssf_issue_scroll(context, direction, delay); -} -inline void ssf_issue_scroll_ptv( - ProControllerContext& context, - DpadPosition direction, - Milliseconds delay, - Milliseconds hold, - Milliseconds cool = 24ms -){ - Milliseconds tv = context->timing_variation(); - if (delay > 0ms) delay += tv; - if (hold > 0ms) hold += tv; - ssf_issue_scroll(context, direction, delay, hold, cool); -} - - - - - - -void ssf_flush_pipeline (JoyconContext& context); -void ssf_do_nothing (JoyconContext& context, Milliseconds duration); -void ssf_press_button( - JoyconContext& context, - Button button, - Milliseconds delay, Milliseconds hold = 48ms, Milliseconds cool = 24ms -); -void ssf_press_joystick( - JoyconContext& context, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms -); -void ssf_mash1_button (JoyconContext& context, Button button, Milliseconds duration); - - - - - - -} -} -#endif +/* Superscalar Framework (ssf_*) + * + * From: https://github.com/PokemonAutomation/ + * + * Don't use these unless you know what you're doing and you really need to. + * + * If you don't understand how the state machine works, you will not be able + * to properly use these functions. + * + * Since the functionality here used to be internal-only, documentation remains + * sparse for now and slated to be expanded in the future. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Commands_Superscalar_H +#define PokemonAutomation_NintendoSwitch_Commands_Superscalar_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + +void ssf_flush_pipeline (ProControllerContext& context); +void ssf_do_nothing (ProControllerContext& context, uint16_t ticks); +void ssf_do_nothing (ProControllerContext& context, Milliseconds duration); + + +void ssf_press_button( + ProControllerContext& context, + Button button, + Milliseconds delay = 24ms, Milliseconds hold = 48ms, Milliseconds cool = 24ms +); +void ssf_press_dpad( + ProControllerContext& context, + DpadPosition position, + Milliseconds delay, Milliseconds hold = 48ms, Milliseconds cool = 24ms +); + + +void ssf_press_left_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + uint16_t delay, uint16_t hold, uint8_t cool = 0 +); +void ssf_press_left_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms +); +void ssf_press_right_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + uint16_t delay, uint16_t hold, uint8_t cool = 0 +); +void ssf_press_right_joystick( + ProControllerContext& context, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms +); + + +void ssf_mash1_button (ProControllerContext& context, Button button, uint16_t ticks); +void ssf_mash1_button (ProControllerContext& context, Button button, Milliseconds duration); + +void ssf_mash2_button (ProControllerContext& context, Button button0, Button button1, uint16_t ticks); +void ssf_mash2_button (ProControllerContext& context, Button button0, Button button1, Milliseconds duration); + +void ssf_mash_AZs (ProControllerContext& context, uint16_t ticks); +void ssf_mash_AZs (ProControllerContext& context, Milliseconds duration); + + +// Diagonal scrolling seems to count as seperate events for each direction. +// In other words, they don't work. +#define SSF_SCROLL_UP DPAD_UP +#define SSF_SCROLL_RIGHT DPAD_RIGHT +#define SSF_SCROLL_DOWN DPAD_DOWN +#define SSF_SCROLL_LEFT DPAD_LEFT +void ssf_issue_scroll( + ProControllerContext& context, + DpadPosition direction, + Milliseconds delay +); +void ssf_issue_scroll( + ProControllerContext& context, + DpadPosition direction, + Milliseconds delay, Milliseconds hold, Milliseconds cool +); + + + + + +// +// ptv = plus timing variation +// +// These are simple wrappers that add "context->timing_variation()" to +// every timing. Mostly intended for Switch menu navigation where we usually +// attempt fast movements. +// +inline void ssf_press_button_ptv( + ProControllerContext& context, + Button button, + Milliseconds delay = 24ms +){ + Milliseconds tv = context->timing_variation(); + if (delay > 0ms) delay += tv; + ssf_press_button(context, button, delay); +} +inline void ssf_press_button_ptv( + ProControllerContext& context, + Button button, + Milliseconds delay, + Milliseconds hold, + Milliseconds cool = 24ms +){ + Milliseconds tv = context->timing_variation(); + if (delay > 0ms) delay += tv; + if (hold > 0ms) hold += tv; + if (cool > 0ms) cool += tv; + ssf_press_button(context, button, delay, hold, cool); +} +inline void ssf_press_dpad_ptv( + ProControllerContext& context, + DpadPosition position, + Milliseconds delay = 24ms +){ + Milliseconds tv = context->timing_variation(); + if (delay > 0ms) delay += tv; + ssf_press_dpad(context, position, delay); +} +inline void ssf_press_dpad_ptv( + ProControllerContext& context, + DpadPosition position, + Milliseconds delay, + Milliseconds hold, + Milliseconds cool = 24ms +){ + Milliseconds tv = context->timing_variation(); + if (delay > 0ms) delay += tv; + if (hold > 0ms) hold += tv; + if (cool > 0ms) cool += tv; + ssf_press_dpad(context, position, delay, hold, cool); +} +inline void ssf_issue_scroll_ptv( + ProControllerContext& context, + DpadPosition direction, + Milliseconds delay = 24ms +){ + Milliseconds tv = context->timing_variation(); + if (delay > 0ms) delay += tv; + ssf_issue_scroll(context, direction, delay); +} +inline void ssf_issue_scroll_ptv( + ProControllerContext& context, + DpadPosition direction, + Milliseconds delay, + Milliseconds hold, + Milliseconds cool = 24ms +){ + Milliseconds tv = context->timing_variation(); + if (delay > 0ms) delay += tv; + if (hold > 0ms) hold += tv; + ssf_issue_scroll(context, direction, delay, hold, cool); +} + + + + + + +void ssf_flush_pipeline (JoyconContext& context); +void ssf_do_nothing (JoyconContext& context, Milliseconds duration); +void ssf_press_button( + JoyconContext& context, + Button button, + Milliseconds delay, Milliseconds hold = 48ms, Milliseconds cool = 24ms +); +void ssf_press_joystick( + JoyconContext& context, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cool = 0ms +); +void ssf_mash1_button (JoyconContext& context, Button button, Milliseconds duration); + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp index 0f72328a21..05da722c84 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.cpp @@ -1,364 +1,364 @@ -/* Nintendo Switch Controller Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/CRC32.h" -#include "NintendoSwitch_ControllerSettings.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -uint32_t average_colors(uint32_t x, uint32_t y){ - // Average the two button colors. - uint32_t red = ((x >> 16) & 0xff) + ((y >> 16) & 0xff); - uint32_t green = ((x >> 8) & 0xff) + ((y >> 8) & 0xff); - uint32_t blue = ((x >> 0) & 0xff) + ((y >> 0) & 0xff); - red /= 2; - green /= 2; - blue /= 2; - return (red << 16) | (green << 8) | (blue << 0); -} - - -struct OfficialJoyconColors{ - std::string name; - uint32_t left_body; - uint32_t left_buttons; - uint32_t right_body; - uint32_t right_buttons; - - void write_to_profile(ControllerProfile& profile, ControllerType controller) const{ - profile.official_name = name; - switch (controller){ - case ControllerType::NintendoSwitch_WirelessProController:{ - // Set the grips to the joycon colors. - profile.left_grip = left_body; - profile.right_grip = right_body; - profile.body_color = average_colors(left_buttons, right_buttons); - profile.button_color = average_colors(left_body, right_body); - break; - } - case ControllerType::NintendoSwitch_LeftJoycon: - profile.button_color = left_buttons; - profile.body_color = left_body; - break; - case ControllerType::NintendoSwitch_RightJoycon: - profile.button_color = right_buttons; - profile.body_color = right_body; - break; - default:; - } - - } -}; - -const std::vector& OFFICIAL_JOYCON_COLORS(){ - // From: https://switchbrew.org/wiki/Joy-Con#Colors - const static std::vector database{ - {"Developer Black", 0x313131, 0x0F0F0F, 0x313131, 0x0F0F0F}, - - {"Stock: Grey / Grey", 0x828282, 0x0F0F0F, 0x828282, 0x0F0F0F}, - {"Stock: Neon Blue / Neon Red", 0x0AB9E6, 0x001E1E, 0xFF3C28, 0x1E0A0A}, - {"Stock: OLED White", 0xE6E6E6, 0x323232, 0xE6E6E6, 0x323232}, - - {"Neon Red / Neon Blue", 0xFF3C28, 0x1E0A0A, 0x0AB9E6, 0x001E1E}, - {"Blue / Neon Yellow", 0x4655F5, 0x00000A, 0xE6FF00, 0x142800}, - {"Neon Pink / Green Pink", 0xFF3278, 0x28001E, 0x1EDC00, 0x002800}, - {"Neon Green / Neon Pink", 0x1EDC00, 0x002800, 0xFF3278, 0x28001E}, - {"Neon Purple / Neon Orange", 0xB400E6, 0x140014, 0xFAA005, 0x0F0A00}, - {"Pastel Pink / Pastel Pink", 0xFFAFAF, 0x372D2D, 0xFFAFAF, 0x372D2D}, - {"Pastel Pink / Pastel Yellow", 0xFFAFAF, 0x372D2D, 0xF5FF82, 0x32332D}, - {"Pastel Purple / Pastel Green", 0xF0CBEB, 0x373037, 0xBCFFC8, 0x2D322D}, - - {"Super Mario Odyssey Edition Red", 0xE10F00, 0x280A0A, 0xE10F00, 0x280A0A}, - {"Let's Go! Pikachu and Eevee", 0xC88C32, 0x281900, 0xFFDC00, 0x322800}, - {"Nintendo Labo Creators Contest Edition", 0xD7AA73, 0x1E1914, 0xD7AA73, 0x1E1914}, - {"Dragon Quest XI S Lotto Edition", 0x1473FA, 0x00000F, 0x1473FA, 0x00000F}, -// {"Disney Tsum Tsum Festival Edition", 0xB400E6, 0x140014, 0xFF3278, 0x28001E}, - {"Animal Crossing: New Horizons Edition", 0x82FF96, 0x0A1E0A, 0x96F5F5, 0x0A1E28}, - {"Fortnite Wildcat Edition", 0xFFCC00, 0x1A1100, 0x0084FF, 0x000F1E}, - {"Mario Red x Blue Edition", 0xF04614, 0x1E1914, 0xF04614, 0x1E1914}, - {"Fortnite Fleet Force Edition", 0x0084FF, 0x000F1E, 0xFFCC00, 0x1A1100}, - {"Legend of Zelda: Skyward Sword Edition", 0x2D50F0, 0x1E0F46, 0x500FC8, 0x00051E}, - {"Splatoon 3 OLED Edition", 0x6455F5, 0x28282D, 0xC3FA05, 0x1E1E28}, - {"Pokémon: Scarlet x Violet OLED Edition", 0xF07341, 0x322D1E, 0x9650AA, 0x32322D}, - {"Legend of Zelda: Tears of the Kingdom Edition", 0xD2BE69, 0x32322D, 0xD2BE69, 0x32322D}, - }; - return database; -} - - -StringSelectDatabase make_JOYCON_DATABASE(){ - StringSelectDatabase database; - database.add_entry(StringSelectEntry("Custom", "Custom")); - for (const OfficialJoyconColors& item : OFFICIAL_JOYCON_COLORS()){ - database.add_entry( - StringSelectEntry(item.name, item.name) - ); - } - return database; -} -const StringSelectDatabase& JOYCON_DATABASE(){ - static const StringSelectDatabase database = make_JOYCON_DATABASE(); - return database; -} - - - - - -const EnumDropdownDatabase& ControllerSettingsType_Database(){ - static const EnumDropdownDatabase database({ - {ControllerType::NintendoSwitch_WirelessProController, "pro-controller", "Pro Controller"}, - {ControllerType::NintendoSwitch_LeftJoycon, "left-joycon", "Left Joycon"}, - {ControllerType::NintendoSwitch_RightJoycon, "right-joycon", "Right Joycon"}, - }); - return database; -} - - - -ControllerSettingsRow::~ControllerSettingsRow(){ - official_color.remove_listener(*this); -#if 1 - right_grip.remove_listener(*this); - left_grip.remove_listener(*this); -// body_color.remove_listener(*this); - button_color.remove_listener(*this); -#endif - controller.remove_listener(*this); -} -ControllerSettingsRow::ControllerSettingsRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , name(false, LockMode::UNLOCK_WHILE_RUNNING, "", "COM3") - , controller_mac_address(LockMode::UNLOCK_WHILE_RUNNING, 6, nullptr) - , controller( - ControllerSettingsType_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ControllerType::NintendoSwitch_WirelessProController - ) - , button_color( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x0A1E19, 0x0A1E19 - ) - , body_color( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0xd0d0d0, 0xd0d0d0 - ) - , left_grip( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x82FF96, 0x82FF96 - ) - , right_grip( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x96F5F5, 0x96F5F5 - ) - , official_color( - JOYCON_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , m_pending_official_load(0) -{ - add_option(name, "Name"); - add_option(controller_mac_address, "Controller MAC Address"); - add_option(controller, "Controller"); - add_option(button_color, "Button"); - add_option(body_color, "Body"); - add_option(left_grip, "Left Grip"); - add_option(right_grip, "Right Grip"); - add_option(official_color, "Official Color"); - - set_profile(ControllerSettingsTable::random_profile(controller)); - - controller.add_listener(*this); -#if 1 - button_color.add_listener(*this); -// body_color.add_listener(*this); - left_grip.add_listener(*this); - right_grip.add_listener(*this); -#endif - official_color.add_listener(*this); -} -std::unique_ptr ControllerSettingsRow::clone() const{ - std::unique_ptr ret(new ControllerSettingsRow(parent())); - ret->name.set((std::string)name); - ret->controller_mac_address = controller_mac_address; - ret->controller.set(controller); - ret->button_color.set(button_color); - ret->body_color.set(body_color); - ret->left_grip.set(left_grip); - ret->right_grip.set(right_grip); - ret->official_color.set_by_index(official_color.index()); - return ret; -} -void ControllerSettingsRow::on_config_value_changed(void* object){ - if (object == &button_color || -// object == &body_color || - object == &left_grip || - object == &right_grip - ){ - if (m_pending_official_load.load(std::memory_order_relaxed) == 0){ - official_color.set_by_index(0); - } - return; - } - - if (object == &controller){ - ConfigOptionState state = controller == ControllerType::NintendoSwitch_WirelessProController - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN; - left_grip.set_visibility(state); - right_grip.set_visibility(state); - - // Force an update on the chosen theme. - object = &official_color; - } - - if (object != &official_color){ - return; - } - - size_t index = official_color.index(); - if (index == 0){ - return; - } - - try{ - m_pending_official_load++; - - ControllerProfile profile{}; - OFFICIAL_JOYCON_COLORS()[index - 1].write_to_profile(profile, controller); - this->set_profile(profile); - - m_pending_official_load--; - }catch (...){ - m_pending_official_load--; - throw; - } - -} - - - - -ControllerSettingsTable::ControllerSettingsTable() - : EditableTableOption_t( - "Wireless Controller Settings:
Changes take effect after resetting the device.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -{} -std::vector ControllerSettingsTable::make_header() const{ - return std::vector{ - "Name", - "MAC Address", - "Controller", - "Button", - "Body", - "Left Grip", - "Right Grip", - "Quick Select", - }; -} - - - -ControllerProfile ControllerSettingsTable::random_profile(ControllerType controller){ - const std::vector& DATABASE = OFFICIAL_JOYCON_COLORS(); - - ControllerProfile profile; - - uint64_t seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); - seed = pabb_crc32(0, &seed, sizeof(seed)); - seed %= DATABASE.size(); - - DATABASE[(size_t)seed].write_to_profile(profile, controller); - return profile; -} -ControllerProfile ControllerSettingsTable::get_or_make_profile( - const uint8_t mac_address[6], - const std::string& name, - ControllerType controller -){ -// cout << "ControllerSettingsTable::get_or_make_profile(): " << this << endl; - - ControllerProfile profile{}; - - // Only relevant to Switch controllers. - switch (controller){ - case ControllerType::NintendoSwitch_WiredProController: - case ControllerType::NintendoSwitch_WirelessProController: - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon: - break; - default: - return profile; - } - - bool found = false; - this->run_on_all_rows([&, controller](ControllerSettingsRow& row){ - if (row.controller_mac_address == mac_address){ -// row.name.set(name); - row.controller_mac_address.set(mac_address); - row.controller.set(controller); - found = true; - profile = row; - return true; - } - if ((std::string)row.name != name){ - return false; - } - if (row.controller != controller){ - return false; - } - - row.controller_mac_address.set(mac_address); - found = true; - profile = row; - return true; - }); - - if (found){ - return profile; - } - - profile = random_profile(controller); - - std::unique_ptr row(new ControllerSettingsRow(*this)); - row->name.set(name); - row->controller_mac_address.set(mac_address); - row->controller.set(controller); - row->set_profile(profile); - - this->append_row(std::move(row)); - - return profile; -} - - - - - - - - - - - - - -} -} +/* Nintendo Switch Controller Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/CRC32.h" +#include "NintendoSwitch_ControllerSettings.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +uint32_t average_colors(uint32_t x, uint32_t y){ + // Average the two button colors. + uint32_t red = ((x >> 16) & 0xff) + ((y >> 16) & 0xff); + uint32_t green = ((x >> 8) & 0xff) + ((y >> 8) & 0xff); + uint32_t blue = ((x >> 0) & 0xff) + ((y >> 0) & 0xff); + red /= 2; + green /= 2; + blue /= 2; + return (red << 16) | (green << 8) | (blue << 0); +} + + +struct OfficialJoyconColors{ + std::string name; + uint32_t left_body; + uint32_t left_buttons; + uint32_t right_body; + uint32_t right_buttons; + + void write_to_profile(ControllerProfile& profile, ControllerType controller) const{ + profile.official_name = name; + switch (controller){ + case ControllerType::NintendoSwitch_WirelessProController:{ + // Set the grips to the joycon colors. + profile.left_grip = left_body; + profile.right_grip = right_body; + profile.body_color = average_colors(left_buttons, right_buttons); + profile.button_color = average_colors(left_body, right_body); + break; + } + case ControllerType::NintendoSwitch_LeftJoycon: + profile.button_color = left_buttons; + profile.body_color = left_body; + break; + case ControllerType::NintendoSwitch_RightJoycon: + profile.button_color = right_buttons; + profile.body_color = right_body; + break; + default:; + } + + } +}; + +const std::vector& OFFICIAL_JOYCON_COLORS(){ + // From: https://switchbrew.org/wiki/Joy-Con#Colors + const static std::vector database{ + {"Developer Black", 0x313131, 0x0F0F0F, 0x313131, 0x0F0F0F}, + + {"Stock: Grey / Grey", 0x828282, 0x0F0F0F, 0x828282, 0x0F0F0F}, + {"Stock: Neon Blue / Neon Red", 0x0AB9E6, 0x001E1E, 0xFF3C28, 0x1E0A0A}, + {"Stock: OLED White", 0xE6E6E6, 0x323232, 0xE6E6E6, 0x323232}, + + {"Neon Red / Neon Blue", 0xFF3C28, 0x1E0A0A, 0x0AB9E6, 0x001E1E}, + {"Blue / Neon Yellow", 0x4655F5, 0x00000A, 0xE6FF00, 0x142800}, + {"Neon Pink / Green Pink", 0xFF3278, 0x28001E, 0x1EDC00, 0x002800}, + {"Neon Green / Neon Pink", 0x1EDC00, 0x002800, 0xFF3278, 0x28001E}, + {"Neon Purple / Neon Orange", 0xB400E6, 0x140014, 0xFAA005, 0x0F0A00}, + {"Pastel Pink / Pastel Pink", 0xFFAFAF, 0x372D2D, 0xFFAFAF, 0x372D2D}, + {"Pastel Pink / Pastel Yellow", 0xFFAFAF, 0x372D2D, 0xF5FF82, 0x32332D}, + {"Pastel Purple / Pastel Green", 0xF0CBEB, 0x373037, 0xBCFFC8, 0x2D322D}, + + {"Super Mario Odyssey Edition Red", 0xE10F00, 0x280A0A, 0xE10F00, 0x280A0A}, + {"Let's Go! Pikachu and Eevee", 0xC88C32, 0x281900, 0xFFDC00, 0x322800}, + {"Nintendo Labo Creators Contest Edition", 0xD7AA73, 0x1E1914, 0xD7AA73, 0x1E1914}, + {"Dragon Quest XI S Lotto Edition", 0x1473FA, 0x00000F, 0x1473FA, 0x00000F}, +// {"Disney Tsum Tsum Festival Edition", 0xB400E6, 0x140014, 0xFF3278, 0x28001E}, + {"Animal Crossing: New Horizons Edition", 0x82FF96, 0x0A1E0A, 0x96F5F5, 0x0A1E28}, + {"Fortnite Wildcat Edition", 0xFFCC00, 0x1A1100, 0x0084FF, 0x000F1E}, + {"Mario Red x Blue Edition", 0xF04614, 0x1E1914, 0xF04614, 0x1E1914}, + {"Fortnite Fleet Force Edition", 0x0084FF, 0x000F1E, 0xFFCC00, 0x1A1100}, + {"Legend of Zelda: Skyward Sword Edition", 0x2D50F0, 0x1E0F46, 0x500FC8, 0x00051E}, + {"Splatoon 3 OLED Edition", 0x6455F5, 0x28282D, 0xC3FA05, 0x1E1E28}, + {"Pokémon: Scarlet x Violet OLED Edition", 0xF07341, 0x322D1E, 0x9650AA, 0x32322D}, + {"Legend of Zelda: Tears of the Kingdom Edition", 0xD2BE69, 0x32322D, 0xD2BE69, 0x32322D}, + }; + return database; +} + + +StringSelectDatabase make_JOYCON_DATABASE(){ + StringSelectDatabase database; + database.add_entry(StringSelectEntry("Custom", "Custom")); + for (const OfficialJoyconColors& item : OFFICIAL_JOYCON_COLORS()){ + database.add_entry( + StringSelectEntry(item.name, item.name) + ); + } + return database; +} +const StringSelectDatabase& JOYCON_DATABASE(){ + static const StringSelectDatabase database = make_JOYCON_DATABASE(); + return database; +} + + + + + +const EnumDropdownDatabase& ControllerSettingsType_Database(){ + static const EnumDropdownDatabase database({ + {ControllerType::NintendoSwitch_WirelessProController, "pro-controller", "Pro Controller"}, + {ControllerType::NintendoSwitch_LeftJoycon, "left-joycon", "Left Joycon"}, + {ControllerType::NintendoSwitch_RightJoycon, "right-joycon", "Right Joycon"}, + }); + return database; +} + + + +ControllerSettingsRow::~ControllerSettingsRow(){ + official_color.remove_listener(*this); +#if 1 + right_grip.remove_listener(*this); + left_grip.remove_listener(*this); +// body_color.remove_listener(*this); + button_color.remove_listener(*this); +#endif + controller.remove_listener(*this); +} +ControllerSettingsRow::ControllerSettingsRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , name(false, LockMode::UNLOCK_WHILE_RUNNING, "", "COM3") + , controller_mac_address(LockMode::UNLOCK_WHILE_RUNNING, 6, nullptr) + , controller( + ControllerSettingsType_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ControllerType::NintendoSwitch_WirelessProController + ) + , button_color( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x0A1E19, 0x0A1E19 + ) + , body_color( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0xd0d0d0, 0xd0d0d0 + ) + , left_grip( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x82FF96, 0x82FF96 + ) + , right_grip( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x96F5F5, 0x96F5F5 + ) + , official_color( + JOYCON_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , m_pending_official_load(0) +{ + add_option(name, "Name"); + add_option(controller_mac_address, "Controller MAC Address"); + add_option(controller, "Controller"); + add_option(button_color, "Button"); + add_option(body_color, "Body"); + add_option(left_grip, "Left Grip"); + add_option(right_grip, "Right Grip"); + add_option(official_color, "Official Color"); + + set_profile(ControllerSettingsTable::random_profile(controller)); + + controller.add_listener(*this); +#if 1 + button_color.add_listener(*this); +// body_color.add_listener(*this); + left_grip.add_listener(*this); + right_grip.add_listener(*this); +#endif + official_color.add_listener(*this); +} +std::unique_ptr ControllerSettingsRow::clone() const{ + std::unique_ptr ret(new ControllerSettingsRow(parent())); + ret->name.set((std::string)name); + ret->controller_mac_address = controller_mac_address; + ret->controller.set(controller); + ret->button_color.set(button_color); + ret->body_color.set(body_color); + ret->left_grip.set(left_grip); + ret->right_grip.set(right_grip); + ret->official_color.set_by_index(official_color.index()); + return ret; +} +void ControllerSettingsRow::on_config_value_changed(void* object){ + if (object == &button_color || +// object == &body_color || + object == &left_grip || + object == &right_grip + ){ + if (m_pending_official_load.load(std::memory_order_relaxed) == 0){ + official_color.set_by_index(0); + } + return; + } + + if (object == &controller){ + ConfigOptionState state = controller == ControllerType::NintendoSwitch_WirelessProController + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN; + left_grip.set_visibility(state); + right_grip.set_visibility(state); + + // Force an update on the chosen theme. + object = &official_color; + } + + if (object != &official_color){ + return; + } + + size_t index = official_color.index(); + if (index == 0){ + return; + } + + try{ + m_pending_official_load++; + + ControllerProfile profile{}; + OFFICIAL_JOYCON_COLORS()[index - 1].write_to_profile(profile, controller); + this->set_profile(profile); + + m_pending_official_load--; + }catch (...){ + m_pending_official_load--; + throw; + } + +} + + + + +ControllerSettingsTable::ControllerSettingsTable() + : EditableTableOption_t( + "Wireless Controller Settings:
Changes take effect after resetting the device.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +{} +std::vector ControllerSettingsTable::make_header() const{ + return std::vector{ + "Name", + "MAC Address", + "Controller", + "Button", + "Body", + "Left Grip", + "Right Grip", + "Quick Select", + }; +} + + + +ControllerProfile ControllerSettingsTable::random_profile(ControllerType controller){ + const std::vector& DATABASE = OFFICIAL_JOYCON_COLORS(); + + ControllerProfile profile; + + uint64_t seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); + seed = pabb_crc32(0, &seed, sizeof(seed)); + seed %= DATABASE.size(); + + DATABASE[(size_t)seed].write_to_profile(profile, controller); + return profile; +} +ControllerProfile ControllerSettingsTable::get_or_make_profile( + const uint8_t mac_address[6], + const std::string& name, + ControllerType controller +){ +// cout << "ControllerSettingsTable::get_or_make_profile(): " << this << endl; + + ControllerProfile profile{}; + + // Only relevant to Switch controllers. + switch (controller){ + case ControllerType::NintendoSwitch_WiredProController: + case ControllerType::NintendoSwitch_WirelessProController: + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon: + break; + default: + return profile; + } + + bool found = false; + this->run_on_all_rows([&, controller](ControllerSettingsRow& row){ + if (row.controller_mac_address == mac_address){ +// row.name.set(name); + row.controller_mac_address.set(mac_address); + row.controller.set(controller); + found = true; + profile = row; + return true; + } + if ((std::string)row.name != name){ + return false; + } + if (row.controller != controller){ + return false; + } + + row.controller_mac_address.set(mac_address); + found = true; + profile = row; + return true; + }); + + if (found){ + return profile; + } + + profile = random_profile(controller); + + std::unique_ptr row(new ControllerSettingsRow(*this)); + row->name.set(name); + row->controller_mac_address.set(mac_address); + row->controller.set(controller); + row->set_profile(profile); + + this->append_row(std::move(row)); + + return profile; +} + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h index 9d5ba89665..1cb8cb94d3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h @@ -1,87 +1,87 @@ -/* Nintendo Switch Controller Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerSettings_H -#define PokemonAutomation_NintendoSwitch_ControllerSettings_H - -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/ColorOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/MacAddressOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "Controllers/ControllerTypes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -struct ControllerProfile{ - uint32_t button_color; - uint32_t body_color; - uint32_t left_grip; - uint32_t right_grip; - std::string official_name; -}; - -class ControllerSettingsRow : public EditableTableRow, public ConfigOption::Listener{ -public: - ~ControllerSettingsRow(); - ControllerSettingsRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - virtual void on_config_value_changed(void* object) override; - - operator ControllerProfile() const{ - return { - button_color, - body_color, - left_grip, - right_grip, - official_color.slug(), - }; - } - void set_profile(const ControllerProfile& profile){ - button_color.set(profile.button_color); - body_color.set(profile.body_color); - left_grip.set(profile.left_grip); - right_grip.set(profile.right_grip); - official_color.set_by_slug(profile.official_name); - } - -public: - StringCell name; - MacAddressCell controller_mac_address; - EnumDropdownCell controller; - ColorCell button_color; - ColorCell body_color; - ColorCell left_grip; - ColorCell right_grip; - StringSelectCell official_color; - -private: - std::atomic m_pending_official_load; -}; - - -class ControllerSettingsTable : public EditableTableOption_t{ -public: - ControllerSettingsTable(); - virtual std::vector make_header() const override; - - static ControllerProfile random_profile(ControllerType controller); - ControllerProfile get_or_make_profile( - const uint8_t mac_address[6], - const std::string& name, - ControllerType controller - ); - -}; - - -} -} -#endif +/* Nintendo Switch Controller Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerSettings_H +#define PokemonAutomation_NintendoSwitch_ControllerSettings_H + +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/ColorOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/MacAddressOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "Controllers/ControllerTypes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +struct ControllerProfile{ + uint32_t button_color; + uint32_t body_color; + uint32_t left_grip; + uint32_t right_grip; + std::string official_name; +}; + +class ControllerSettingsRow : public EditableTableRow, public ConfigOption::Listener{ +public: + ~ControllerSettingsRow(); + ControllerSettingsRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + virtual void on_config_value_changed(void* object) override; + + operator ControllerProfile() const{ + return { + button_color, + body_color, + left_grip, + right_grip, + official_color.slug(), + }; + } + void set_profile(const ControllerProfile& profile){ + button_color.set(profile.button_color); + body_color.set(profile.body_color); + left_grip.set(profile.left_grip); + right_grip.set(profile.right_grip); + official_color.set_by_slug(profile.official_name); + } + +public: + StringCell name; + MacAddressCell controller_mac_address; + EnumDropdownCell controller; + ColorCell button_color; + ColorCell body_color; + ColorCell left_grip; + ColorCell right_grip; + StringSelectCell official_color; + +private: + std::atomic m_pending_official_load; +}; + + +class ControllerSettingsTable : public EditableTableOption_t{ +public: + ControllerSettingsTable(); + virtual std::vector make_header() const override; + + static ControllerProfile random_profile(ControllerType controller); + ControllerProfile get_or_make_profile( + const uint8_t mac_address[6], + const std::string& name, + ControllerType controller + ); + +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp index 1996232d8c..85b0133214 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.cpp @@ -1,63 +1,63 @@ -/* Nintendo Switch Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -std::string button_to_string(Button button){ - std::string str; - if (button & BUTTON_Y) str += "Y "; - if (button & BUTTON_B) str += "B "; - if (button & BUTTON_A) str += "A "; - if (button & BUTTON_X) str += "X "; - if (button & BUTTON_L) str += "L "; - if (button & BUTTON_R) str += "R "; - if (button & BUTTON_ZL) str += "ZL "; - if (button & BUTTON_ZR) str += "ZR "; - if (button & BUTTON_MINUS) str += "- "; - if (button & BUTTON_PLUS) str += "+ "; - if (button & BUTTON_LCLICK) str += "LJ "; - if (button & BUTTON_RCLICK) str += "RJ "; - if (button & BUTTON_HOME) str += "HOME "; - if (button & BUTTON_CAPTURE) str += "CAPTURE "; - if (button & BUTTON_UP) str += "Up "; - if (button & BUTTON_RIGHT) str += "Right "; - if (button & BUTTON_DOWN) str += "Down "; - if (button & BUTTON_LEFT) str += "Left "; - if (button & BUTTON_LEFT_SL) str += "Left-SL"; - if (button & BUTTON_LEFT_SR) str += "Left-SR"; - if (button & BUTTON_RIGHT_SL) str += "Right-SL"; - if (button & BUTTON_RIGHT_SR) str += "Right-SR"; - if (str.empty()){ - str = "none"; - } - if (str.back() == ' '){ - str.pop_back(); - } - return str; -} -std::string dpad_to_string(DpadPosition dpad){ - switch (dpad){ - case DPAD_UP : return "up"; - case DPAD_UP_RIGHT : return "up-right"; - case DPAD_RIGHT : return "right"; - case DPAD_DOWN_RIGHT : return "down-right"; - case DPAD_DOWN : return "down"; - case DPAD_DOWN_LEFT : return "down-left"; - case DPAD_LEFT : return "left"; - case DPAD_UP_LEFT : return "up-left"; - case DPAD_NONE : return "none"; - } - return "unknown"; -} - - - -} -} +/* Nintendo Switch Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +std::string button_to_string(Button button){ + std::string str; + if (button & BUTTON_Y) str += "Y "; + if (button & BUTTON_B) str += "B "; + if (button & BUTTON_A) str += "A "; + if (button & BUTTON_X) str += "X "; + if (button & BUTTON_L) str += "L "; + if (button & BUTTON_R) str += "R "; + if (button & BUTTON_ZL) str += "ZL "; + if (button & BUTTON_ZR) str += "ZR "; + if (button & BUTTON_MINUS) str += "- "; + if (button & BUTTON_PLUS) str += "+ "; + if (button & BUTTON_LCLICK) str += "LJ "; + if (button & BUTTON_RCLICK) str += "RJ "; + if (button & BUTTON_HOME) str += "HOME "; + if (button & BUTTON_CAPTURE) str += "CAPTURE "; + if (button & BUTTON_UP) str += "Up "; + if (button & BUTTON_RIGHT) str += "Right "; + if (button & BUTTON_DOWN) str += "Down "; + if (button & BUTTON_LEFT) str += "Left "; + if (button & BUTTON_LEFT_SL) str += "Left-SL"; + if (button & BUTTON_LEFT_SR) str += "Left-SR"; + if (button & BUTTON_RIGHT_SL) str += "Right-SL"; + if (button & BUTTON_RIGHT_SR) str += "Right-SR"; + if (str.empty()){ + str = "none"; + } + if (str.back() == ' '){ + str.pop_back(); + } + return str; +} +std::string dpad_to_string(DpadPosition dpad){ + switch (dpad){ + case DPAD_UP : return "up"; + case DPAD_UP_RIGHT : return "up-right"; + case DPAD_RIGHT : return "right"; + case DPAD_DOWN_RIGHT : return "down-right"; + case DPAD_DOWN : return "down"; + case DPAD_DOWN_LEFT : return "down-left"; + case DPAD_LEFT : return "left"; + case DPAD_UP_LEFT : return "up-left"; + case DPAD_NONE : return "none"; + } + return "unknown"; +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h index 8a7420cc05..21fd95f6db 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h @@ -1,94 +1,94 @@ -/* Nintendo Switch Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerState_H -#define PokemonAutomation_NintendoSwitch_ControllerState_H - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -// Legacy tick type. This comes from the refresh rate of the wired controller. -// One second = 125 ticks. Thus each tick is 8 milliseconds. -constexpr uint16_t TICKS_PER_SECOND = 125; - - -// Buttons -constexpr size_t TOTAL_BUTTONS = 22; -using ButtonFlagType = uint32_t; -enum Button : ButtonFlagType{ - BUTTON_NONE = 0, - BUTTON_Y = ((uint32_t)1 << 0), - BUTTON_B = ((uint32_t)1 << 1), - BUTTON_A = ((uint32_t)1 << 2), - BUTTON_X = ((uint32_t)1 << 3), - BUTTON_L = ((uint32_t)1 << 4), - BUTTON_R = ((uint32_t)1 << 5), - BUTTON_ZL = ((uint32_t)1 << 6), - BUTTON_ZR = ((uint32_t)1 << 7), - BUTTON_MINUS = ((uint32_t)1 << 8), - BUTTON_PLUS = ((uint32_t)1 << 9), - BUTTON_LCLICK = ((uint32_t)1 << 10), - BUTTON_RCLICK = ((uint32_t)1 << 11), - BUTTON_HOME = ((uint32_t)1 << 12), - BUTTON_CAPTURE = ((uint32_t)1 << 13), - BUTTON_UP = ((uint32_t)1 << 14), - BUTTON_RIGHT = ((uint32_t)1 << 15), - BUTTON_DOWN = ((uint32_t)1 << 16), - BUTTON_LEFT = ((uint32_t)1 << 17), - BUTTON_LEFT_SL = ((uint32_t)1 << 18), - BUTTON_LEFT_SR = ((uint32_t)1 << 19), - BUTTON_RIGHT_SL = ((uint32_t)1 << 20), - BUTTON_RIGHT_SR = ((uint32_t)1 << 21), -}; -inline constexpr Button operator|(Button x, Button y){ - return (Button)((ButtonFlagType)x | (ButtonFlagType)y); -} -inline constexpr void operator|=(Button& x, Button y){ - x = (Button)((ButtonFlagType)x | (ButtonFlagType)y); -} -inline constexpr Button operator&(Button x, Button y){ - return (Button)((ButtonFlagType)x & (ButtonFlagType)y); -} -inline constexpr void operator&=(Button& x, Button y){ - x = (Button)((ButtonFlagType)x & (ButtonFlagType)y); -} - -std::string button_to_string(Button button); - - - - -// Dpad -enum DpadPosition : uint8_t{ - DPAD_UP = 0, - DPAD_UP_RIGHT = 1, - DPAD_RIGHT = 2, - DPAD_DOWN_RIGHT = 3, - DPAD_DOWN = 4, - DPAD_DOWN_LEFT = 5, - DPAD_LEFT = 6, - DPAD_UP_LEFT = 7, - DPAD_NONE = 8, -}; - -std::string dpad_to_string(DpadPosition dpad); - - - -// Joysticks -constexpr uint8_t STICK_MIN = 0x00; -constexpr uint8_t STICK_CENTER = 0x80; -constexpr uint8_t STICK_MAX = 0xff; - - - -} -} -#endif +/* Nintendo Switch Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerState_H +#define PokemonAutomation_NintendoSwitch_ControllerState_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// Legacy tick type. This comes from the refresh rate of the wired controller. +// One second = 125 ticks. Thus each tick is 8 milliseconds. +constexpr uint16_t TICKS_PER_SECOND = 125; + + +// Buttons +constexpr size_t TOTAL_BUTTONS = 22; +using ButtonFlagType = uint32_t; +enum Button : ButtonFlagType{ + BUTTON_NONE = 0, + BUTTON_Y = ((uint32_t)1 << 0), + BUTTON_B = ((uint32_t)1 << 1), + BUTTON_A = ((uint32_t)1 << 2), + BUTTON_X = ((uint32_t)1 << 3), + BUTTON_L = ((uint32_t)1 << 4), + BUTTON_R = ((uint32_t)1 << 5), + BUTTON_ZL = ((uint32_t)1 << 6), + BUTTON_ZR = ((uint32_t)1 << 7), + BUTTON_MINUS = ((uint32_t)1 << 8), + BUTTON_PLUS = ((uint32_t)1 << 9), + BUTTON_LCLICK = ((uint32_t)1 << 10), + BUTTON_RCLICK = ((uint32_t)1 << 11), + BUTTON_HOME = ((uint32_t)1 << 12), + BUTTON_CAPTURE = ((uint32_t)1 << 13), + BUTTON_UP = ((uint32_t)1 << 14), + BUTTON_RIGHT = ((uint32_t)1 << 15), + BUTTON_DOWN = ((uint32_t)1 << 16), + BUTTON_LEFT = ((uint32_t)1 << 17), + BUTTON_LEFT_SL = ((uint32_t)1 << 18), + BUTTON_LEFT_SR = ((uint32_t)1 << 19), + BUTTON_RIGHT_SL = ((uint32_t)1 << 20), + BUTTON_RIGHT_SR = ((uint32_t)1 << 21), +}; +inline constexpr Button operator|(Button x, Button y){ + return (Button)((ButtonFlagType)x | (ButtonFlagType)y); +} +inline constexpr void operator|=(Button& x, Button y){ + x = (Button)((ButtonFlagType)x | (ButtonFlagType)y); +} +inline constexpr Button operator&(Button x, Button y){ + return (Button)((ButtonFlagType)x & (ButtonFlagType)y); +} +inline constexpr void operator&=(Button& x, Button y){ + x = (Button)((ButtonFlagType)x & (ButtonFlagType)y); +} + +std::string button_to_string(Button button); + + + + +// Dpad +enum DpadPosition : uint8_t{ + DPAD_UP = 0, + DPAD_UP_RIGHT = 1, + DPAD_RIGHT = 2, + DPAD_DOWN_RIGHT = 3, + DPAD_DOWN = 4, + DPAD_DOWN_LEFT = 5, + DPAD_LEFT = 6, + DPAD_UP_LEFT = 7, + DPAD_NONE = 8, +}; + +std::string dpad_to_string(DpadPosition dpad); + + + +// Joysticks +constexpr uint8_t STICK_MIN = 0x00; +constexpr uint8_t STICK_CENTER = 0x80; +constexpr uint8_t STICK_MAX = 0xff; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp index 2cbddd645f..a4d44659f3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.cpp @@ -1,458 +1,458 @@ -/* Nintendo Switch Controller (With Scheduler) - * - * From: https://github.com/PokemonAutomation/ - * - * This implements most of the SwitchController API using only the controller - * state function. It uses SuperscalarScheduler to do this. - * - */ - -#include "NintendoSwitch_ControllerWithScheduler.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - -ControllerWithScheduler::ControllerWithScheduler(Logger& logger) - : SuperscalarScheduler( - logger, Milliseconds(4), - make_resource_list() - ) - , m_logger(logger) -// , m_logging_suppress(0) -{} - - - -void ControllerWithScheduler::issue_barrier(const Cancellable* cancellable){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - this->issue_wait_for_all(cancellable); - if (m_logging_throttler){ - m_logger.log("issue_barrier()", COLOR_DARKGREEN); - } -} -void ControllerWithScheduler::issue_nop(const Cancellable* cancellable, Milliseconds duration){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - this->SuperscalarScheduler::issue_nop(cancellable, WallDuration(duration)); - if (m_logging_throttler){ - m_logger.log( - "issue_nop(): duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_wait_for_resource(cancellable, m_buttons[c]); - } - } - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_to_resource( - cancellable, m_buttons[c], - WallDuration::zero(), hold, cooldown - ); - } - } - this->SuperscalarScheduler::issue_nop(cancellable, delay); - - if (m_logging_throttler){ - m_logger.log( - "issue_buttons(): " + button_to_string(button) + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, m_dpad); - m_dpad.position = position; - this->issue_to_resource(cancellable, m_dpad, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - "issue_dpad(): " + dpad_to_string(position) + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, m_left_joystick); - m_left_joystick.x = x; - m_left_joystick.y = y; - this->issue_to_resource(cancellable, m_left_joystick, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - "issue_left_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} -void ControllerWithScheduler::issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, m_right_joystick); - m_right_joystick.x = x; - m_right_joystick.y = y; - this->issue_to_resource(cancellable, m_right_joystick, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - "issue_right_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} - - - -void ControllerWithScheduler::issue_gyro( - const Cancellable* cancellable, - SwitchGyro& gyro, const char* name, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - this->issue_wait_for_resource(cancellable, gyro); - gyro.value = value; - this->issue_to_resource(cancellable, gyro, delay, hold, cooldown); - - if (m_logging_throttler){ - m_logger.log( - std::string(name) + "(): (" + std::to_string(value) + ")" + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } -} - - - -void ControllerWithScheduler::issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y -){ - std::lock_guard lg0(m_issue_lock); - std::lock_guard lg1(m_state_lock); - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_wait_for_resource(cancellable, m_buttons[c]); - } - } - this->issue_wait_for_resource(cancellable, m_dpad); - this->issue_wait_for_resource(cancellable, m_left_joystick); - this->issue_wait_for_resource(cancellable, m_right_joystick); - - m_dpad.position = position; - m_left_joystick.x = left_x; - m_left_joystick.y = left_y; - m_right_joystick.x = right_x; - m_right_joystick.y = right_y; - - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ButtonFlagType mask = (ButtonFlagType)1 << c; - if (button & mask){ - this->issue_to_resource( - cancellable, m_buttons[c], - WallDuration::zero(), hold, WallDuration::zero() - ); - } - } - this->issue_to_resource( - cancellable, m_dpad, - WallDuration::zero(), hold, WallDuration::zero() - ); - this->issue_to_resource( - cancellable, m_left_joystick, - WallDuration::zero(), hold, WallDuration::zero() - ); - this->issue_to_resource( - cancellable, m_right_joystick, - hold, hold, WallDuration::zero() - ); - - if (m_logging_throttler){ - m_logger.log( - "issue_controller_state(): (" + button_to_string(button) + - "), dpad(" + dpad_to_string(position) + - "), LJ(" + std::to_string(left_x) + "," + std::to_string(left_y) + - "), RJ(" + std::to_string(right_x) + "," + std::to_string(right_y) + - "), hold = " + std::to_string(hold.count()) + "ms", - COLOR_DARKGREEN - ); - } -} - - -void ControllerWithScheduler::issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - ThrottleScope scope(m_logging_throttler); - bool log = true; - while (duration > Milliseconds::zero()){ - issue_buttons(cancellable, 8*8ms, 5*8ms, 3*8ms, button); - - // We never log before the first issue to avoid delaying the critical path. - // But we do want to log before the mash spam. So we log after the first - // issue, but before the second. - if (log && scope){ - m_logger.log( - "issue_mash_button(): " + button_to_string(button) + - ", duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } - log = false; - - duration = duration >= 8*8ms - ? duration - 8*8ms - : Milliseconds::zero(); - } -} -void ControllerWithScheduler::issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - ThrottleScope scope(m_logging_throttler); - bool log = true; - while (duration > Milliseconds::zero()){ - issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button0); - issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button1); - - // We never log before the first issue to avoid delaying the critical path. - // But we do want to log before the mash spam. So we log after the first - // issue, but before the second. - if (log && scope){ - m_logger.log( - "issue_mash_button(): (" + button_to_string(button0) + - "), (" + button_to_string(button1) + - "), duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } - log = false; - - duration -= std::min(8*8ms, duration); - } -} -void ControllerWithScheduler::issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - ThrottleScope scope(m_logging_throttler); - bool log = true; - while (true){ - if (duration <= Milliseconds::zero()){ - break; - } - issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_A); - - // We never log before the first issue to avoid delaying the critical path. - // But we do want to log before the mash spam. So we log after the first - // issue, but before the second. - if (log && scope){ - m_logger.log( - "issue_mash_AZs(): duration = " + std::to_string(duration.count()) + "ms", - COLOR_DARKGREEN - ); - } - log = false; - - duration -= std::min(3*8ms, duration); - if (duration <= Milliseconds::zero()){ - break; - } - issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZL); - duration -= std::min(3*8ms, duration); - - if (duration <= Milliseconds::zero()){ - break; - } - issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZR); - duration -= std::min(3*8ms, duration); - } -} -void ControllerWithScheduler::issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. -){ - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - ThrottleScope scope(m_logging_throttler); - - WallClock dpad = m_dpad.free_time(); - WallClock left_joystick = m_left_joystick.free_time(); - WallClock right_joystick = m_right_joystick.free_time(); - - do{ - if (dpad <= left_joystick && dpad <= right_joystick){ - issue_dpad( - cancellable, - delay, hold, cooldown, - direction - ); - break; - } - - uint8_t x = 128; - uint8_t y = 128; - switch (direction){ - case DPAD_NONE: - x = 128; - y = 128; - break; - case DPAD_UP: - x = 128; - y = 0; - break; - case DPAD_RIGHT: - x = 255; - y = 128; - break; - case DPAD_DOWN: - x = 128; - y = 255; - break; - case DPAD_LEFT: - x = 0; - y = 128; - break; - - // These diagonal ones probably don't work. - case DPAD_UP_RIGHT: - x = 255; - y = 0; - break; - case DPAD_DOWN_RIGHT: - x = 255; - y = 255; - break; - case DPAD_DOWN_LEFT: - x = 0; - y = 255; - break; - case DPAD_UP_LEFT: - x = 0; - y = 0; - break; - } - - if (left_joystick <= dpad && left_joystick <= right_joystick){ - issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - }else{ - issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - }while (false); - - if (scope){ - m_logger.log( - "issue_system_scroll(): " + dpad_to_string(direction) + - ", delay = " + std::to_string(delay.count()) + "ms" + - ", hold = " + std::to_string(hold.count()) + "ms" + - ", cooldown = " + std::to_string(cooldown.count()) + "ms", - COLOR_DARKGREEN - ); - } - -} - - - - - -} -} +/* Nintendo Switch Controller (With Scheduler) + * + * From: https://github.com/PokemonAutomation/ + * + * This implements most of the SwitchController API using only the controller + * state function. It uses SuperscalarScheduler to do this. + * + */ + +#include "NintendoSwitch_ControllerWithScheduler.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + +ControllerWithScheduler::ControllerWithScheduler(Logger& logger) + : SuperscalarScheduler( + logger, Milliseconds(4), + make_resource_list() + ) + , m_logger(logger) +// , m_logging_suppress(0) +{} + + + +void ControllerWithScheduler::issue_barrier(const Cancellable* cancellable){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + this->issue_wait_for_all(cancellable); + if (m_logging_throttler){ + m_logger.log("issue_barrier()", COLOR_DARKGREEN); + } +} +void ControllerWithScheduler::issue_nop(const Cancellable* cancellable, Milliseconds duration){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + this->SuperscalarScheduler::issue_nop(cancellable, WallDuration(duration)); + if (m_logging_throttler){ + m_logger.log( + "issue_nop(): duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_wait_for_resource(cancellable, m_buttons[c]); + } + } + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_to_resource( + cancellable, m_buttons[c], + WallDuration::zero(), hold, cooldown + ); + } + } + this->SuperscalarScheduler::issue_nop(cancellable, delay); + + if (m_logging_throttler){ + m_logger.log( + "issue_buttons(): " + button_to_string(button) + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, m_dpad); + m_dpad.position = position; + this->issue_to_resource(cancellable, m_dpad, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + "issue_dpad(): " + dpad_to_string(position) + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, m_left_joystick); + m_left_joystick.x = x; + m_left_joystick.y = y; + this->issue_to_resource(cancellable, m_left_joystick, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + "issue_left_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} +void ControllerWithScheduler::issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, m_right_joystick); + m_right_joystick.x = x; + m_right_joystick.y = y; + this->issue_to_resource(cancellable, m_right_joystick, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + "issue_right_joystick(): (" + std::to_string(x) + "," + std::to_string(y) + ")" + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} + + + +void ControllerWithScheduler::issue_gyro( + const Cancellable* cancellable, + SwitchGyro& gyro, const char* name, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + this->issue_wait_for_resource(cancellable, gyro); + gyro.value = value; + this->issue_to_resource(cancellable, gyro, delay, hold, cooldown); + + if (m_logging_throttler){ + m_logger.log( + std::string(name) + "(): (" + std::to_string(value) + ")" + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } +} + + + +void ControllerWithScheduler::issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y +){ + std::lock_guard lg0(m_issue_lock); + std::lock_guard lg1(m_state_lock); + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_wait_for_resource(cancellable, m_buttons[c]); + } + } + this->issue_wait_for_resource(cancellable, m_dpad); + this->issue_wait_for_resource(cancellable, m_left_joystick); + this->issue_wait_for_resource(cancellable, m_right_joystick); + + m_dpad.position = position; + m_left_joystick.x = left_x; + m_left_joystick.y = left_y; + m_right_joystick.x = right_x; + m_right_joystick.y = right_y; + + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ButtonFlagType mask = (ButtonFlagType)1 << c; + if (button & mask){ + this->issue_to_resource( + cancellable, m_buttons[c], + WallDuration::zero(), hold, WallDuration::zero() + ); + } + } + this->issue_to_resource( + cancellable, m_dpad, + WallDuration::zero(), hold, WallDuration::zero() + ); + this->issue_to_resource( + cancellable, m_left_joystick, + WallDuration::zero(), hold, WallDuration::zero() + ); + this->issue_to_resource( + cancellable, m_right_joystick, + hold, hold, WallDuration::zero() + ); + + if (m_logging_throttler){ + m_logger.log( + "issue_controller_state(): (" + button_to_string(button) + + "), dpad(" + dpad_to_string(position) + + "), LJ(" + std::to_string(left_x) + "," + std::to_string(left_y) + + "), RJ(" + std::to_string(right_x) + "," + std::to_string(right_y) + + "), hold = " + std::to_string(hold.count()) + "ms", + COLOR_DARKGREEN + ); + } +} + + +void ControllerWithScheduler::issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + ThrottleScope scope(m_logging_throttler); + bool log = true; + while (duration > Milliseconds::zero()){ + issue_buttons(cancellable, 8*8ms, 5*8ms, 3*8ms, button); + + // We never log before the first issue to avoid delaying the critical path. + // But we do want to log before the mash spam. So we log after the first + // issue, but before the second. + if (log && scope){ + m_logger.log( + "issue_mash_button(): " + button_to_string(button) + + ", duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } + log = false; + + duration = duration >= 8*8ms + ? duration - 8*8ms + : Milliseconds::zero(); + } +} +void ControllerWithScheduler::issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + ThrottleScope scope(m_logging_throttler); + bool log = true; + while (duration > Milliseconds::zero()){ + issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button0); + issue_buttons(cancellable, 4*8ms, 5*8ms, 3*8ms, button1); + + // We never log before the first issue to avoid delaying the critical path. + // But we do want to log before the mash spam. So we log after the first + // issue, but before the second. + if (log && scope){ + m_logger.log( + "issue_mash_button(): (" + button_to_string(button0) + + "), (" + button_to_string(button1) + + "), duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } + log = false; + + duration -= std::min(8*8ms, duration); + } +} +void ControllerWithScheduler::issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + ThrottleScope scope(m_logging_throttler); + bool log = true; + while (true){ + if (duration <= Milliseconds::zero()){ + break; + } + issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_A); + + // We never log before the first issue to avoid delaying the critical path. + // But we do want to log before the mash spam. So we log after the first + // issue, but before the second. + if (log && scope){ + m_logger.log( + "issue_mash_AZs(): duration = " + std::to_string(duration.count()) + "ms", + COLOR_DARKGREEN + ); + } + log = false; + + duration -= std::min(3*8ms, duration); + if (duration <= Milliseconds::zero()){ + break; + } + issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZL); + duration -= std::min(3*8ms, duration); + + if (duration <= Milliseconds::zero()){ + break; + } + issue_buttons(cancellable, 3*8ms, 6*8ms, 3*8ms, BUTTON_ZR); + duration -= std::min(3*8ms, duration); + } +} +void ControllerWithScheduler::issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. +){ + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + ThrottleScope scope(m_logging_throttler); + + WallClock dpad = m_dpad.free_time(); + WallClock left_joystick = m_left_joystick.free_time(); + WallClock right_joystick = m_right_joystick.free_time(); + + do{ + if (dpad <= left_joystick && dpad <= right_joystick){ + issue_dpad( + cancellable, + delay, hold, cooldown, + direction + ); + break; + } + + uint8_t x = 128; + uint8_t y = 128; + switch (direction){ + case DPAD_NONE: + x = 128; + y = 128; + break; + case DPAD_UP: + x = 128; + y = 0; + break; + case DPAD_RIGHT: + x = 255; + y = 128; + break; + case DPAD_DOWN: + x = 128; + y = 255; + break; + case DPAD_LEFT: + x = 0; + y = 128; + break; + + // These diagonal ones probably don't work. + case DPAD_UP_RIGHT: + x = 255; + y = 0; + break; + case DPAD_DOWN_RIGHT: + x = 255; + y = 255; + break; + case DPAD_DOWN_LEFT: + x = 0; + y = 255; + break; + case DPAD_UP_LEFT: + x = 0; + y = 0; + break; + } + + if (left_joystick <= dpad && left_joystick <= right_joystick){ + issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + }else{ + issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + }while (false); + + if (scope){ + m_logger.log( + "issue_system_scroll(): " + dpad_to_string(direction) + + ", delay = " + std::to_string(delay.count()) + "ms" + + ", hold = " + std::to_string(hold.count()) + "ms" + + ", cooldown = " + std::to_string(cooldown.count()) + "ms", + COLOR_DARKGREEN + ); + } + +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h index 2121239917..59a6f2860a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h @@ -1,280 +1,280 @@ -/* Nintendo Switch Controller (With Scheduler) - * - * From: https://github.com/PokemonAutomation/ - * - * This implements most of the SwitchController API using only the controller - * state function. It uses SuperscalarScheduler to do this. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H -#define PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H - -#include -#include "Common/Cpp/RecursiveThrottler.h" -#include "Controllers/SuperscalarScheduler.h" -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -struct SwitchButton_Dpad : public ExecutionResource{ - DpadPosition position; -}; -struct SwitchButton_Joystick : public ExecutionResource{ - uint8_t x; - uint8_t y; -}; -struct SwitchGyro : public ExecutionResource{ - int16_t value; -}; -struct ControllerSchedulerState{ - ExecutionResource m_buttons[TOTAL_BUTTONS]; - SwitchButton_Dpad m_dpad; - SwitchButton_Joystick m_left_joystick; - SwitchButton_Joystick m_right_joystick; - - SwitchGyro m_accel_x; - SwitchGyro m_accel_y; - SwitchGyro m_accel_z; - SwitchGyro m_rotation_x; - SwitchGyro m_rotation_y; - SwitchGyro m_rotation_z; - - bool is_active() const{ - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - if (m_buttons[c].is_busy()){ - return true; - } - } - if (m_dpad.is_busy()) return true; - if (m_left_joystick.is_busy()) return true; - if (m_right_joystick.is_busy()) return true; - - if (m_accel_x.is_busy()) return true; - if (m_accel_y.is_busy()) return true; - if (m_accel_z.is_busy()) return true; - if (m_rotation_x.is_busy()) return true; - if (m_rotation_y.is_busy()) return true; - if (m_rotation_z.is_busy()) return true; - - return false; - } - - std::vector make_resource_list(){ - std::vector ret; - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - ret.emplace_back(m_buttons + c); - } - ret.emplace_back(&m_dpad); - ret.emplace_back(&m_left_joystick); - ret.emplace_back(&m_right_joystick); - ret.emplace_back(&m_accel_x); - ret.emplace_back(&m_accel_y); - ret.emplace_back(&m_accel_z); - ret.emplace_back(&m_rotation_x); - ret.emplace_back(&m_rotation_y); - ret.emplace_back(&m_rotation_z); - return ret; - } -}; - - -struct SplitDpad{ - bool up = false; - bool right = false; - bool down = false; - bool left = false; -}; -inline SplitDpad convert_unified_to_split_dpad(DpadPosition dpad){ - switch (dpad){ - case DpadPosition::DPAD_UP: - return {true, false, false, false}; - case DpadPosition::DPAD_UP_RIGHT: - return {true, true, false, false}; - case DpadPosition::DPAD_RIGHT: - return {false, true, false, false}; - case DpadPosition::DPAD_DOWN_RIGHT: - return {false, true, true, false}; - case DpadPosition::DPAD_DOWN: - return {false, false, true, false}; - case DpadPosition::DPAD_DOWN_LEFT: - return {false, false, true, true}; - case DpadPosition::DPAD_LEFT: - return {false, false, false, true}; - case DpadPosition::DPAD_UP_LEFT: - return {true, false, false, true}; - default: - return {false, false, false, false}; - } -} - - - - - -class ControllerWithScheduler : - protected ControllerSchedulerState, - protected SuperscalarScheduler -{ -public: - ControllerWithScheduler(Logger& logger); - - RecursiveThrottler& logging_throttler(){ - return m_logging_throttler; - } - - -public: - // Superscalar Commands (the "ssf" framework) - - void issue_barrier(const Cancellable* cancellable); - void issue_nop(const Cancellable* cancellable, Milliseconds duration); - void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ); - void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ); - void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ); - void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ); - - void issue_gyro( - const Cancellable* cancellable, - SwitchGyro& gyro, const char* name, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ); - void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_accel_x, "issue_gyro_accel_x", delay, hold, cooldown, value); - } - void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_accel_y, "issue_gyro_accel_y", delay, hold, cooldown, value); - } - void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_accel_z, "issue_gyro_accel_z", delay, hold, cooldown, value); - } - void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_rotation_x, "issue_gyro_rotate_x", delay, hold, cooldown, value); - } - void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_rotation_y, "issue_gyro_rotate_y", delay, hold, cooldown, value); - } - void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ){ - issue_gyro(cancellable, m_rotation_z, "issue_gyro_rotate_z", delay, hold, cooldown, value); - } - - void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ); - - -public: - // High speed RPCs. - - void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ); - void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ); - void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ); - void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ); - - -protected: -#if 0 - class LoggingSuppressScope{ - public: - LoggingSuppressScope(std::atomic& counter) - : m_counter(counter) - { - m_counter++; - } - ~LoggingSuppressScope(){ - m_counter--; - } - private: - std::atomic& m_counter; - }; -#endif - -// virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - -protected: - Logger& m_logger; -// std::atomic m_logging_suppress; - RecursiveThrottler m_logging_throttler; - - // If you need both of these locks, always acquire "m_issue_lock" first. - - // This lock makes sure that only one command is issued at a time. It can - // be held for long periods of time if the command queue is full. - std::mutex m_issue_lock; - - // This lock protects the state/fields of this class and subclasses. - // This lock is never held for a long time. - std::mutex m_state_lock; -}; - - - - -} -} -#endif +/* Nintendo Switch Controller (With Scheduler) + * + * From: https://github.com/PokemonAutomation/ + * + * This implements most of the SwitchController API using only the controller + * state function. It uses SuperscalarScheduler to do this. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H +#define PokemonAutomation_NintendoSwitch_ControllerWithScheduler_H + +#include +#include "Common/Cpp/RecursiveThrottler.h" +#include "Controllers/SuperscalarScheduler.h" +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +struct SwitchButton_Dpad : public ExecutionResource{ + DpadPosition position; +}; +struct SwitchButton_Joystick : public ExecutionResource{ + uint8_t x; + uint8_t y; +}; +struct SwitchGyro : public ExecutionResource{ + int16_t value; +}; +struct ControllerSchedulerState{ + ExecutionResource m_buttons[TOTAL_BUTTONS]; + SwitchButton_Dpad m_dpad; + SwitchButton_Joystick m_left_joystick; + SwitchButton_Joystick m_right_joystick; + + SwitchGyro m_accel_x; + SwitchGyro m_accel_y; + SwitchGyro m_accel_z; + SwitchGyro m_rotation_x; + SwitchGyro m_rotation_y; + SwitchGyro m_rotation_z; + + bool is_active() const{ + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + if (m_buttons[c].is_busy()){ + return true; + } + } + if (m_dpad.is_busy()) return true; + if (m_left_joystick.is_busy()) return true; + if (m_right_joystick.is_busy()) return true; + + if (m_accel_x.is_busy()) return true; + if (m_accel_y.is_busy()) return true; + if (m_accel_z.is_busy()) return true; + if (m_rotation_x.is_busy()) return true; + if (m_rotation_y.is_busy()) return true; + if (m_rotation_z.is_busy()) return true; + + return false; + } + + std::vector make_resource_list(){ + std::vector ret; + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + ret.emplace_back(m_buttons + c); + } + ret.emplace_back(&m_dpad); + ret.emplace_back(&m_left_joystick); + ret.emplace_back(&m_right_joystick); + ret.emplace_back(&m_accel_x); + ret.emplace_back(&m_accel_y); + ret.emplace_back(&m_accel_z); + ret.emplace_back(&m_rotation_x); + ret.emplace_back(&m_rotation_y); + ret.emplace_back(&m_rotation_z); + return ret; + } +}; + + +struct SplitDpad{ + bool up = false; + bool right = false; + bool down = false; + bool left = false; +}; +inline SplitDpad convert_unified_to_split_dpad(DpadPosition dpad){ + switch (dpad){ + case DpadPosition::DPAD_UP: + return {true, false, false, false}; + case DpadPosition::DPAD_UP_RIGHT: + return {true, true, false, false}; + case DpadPosition::DPAD_RIGHT: + return {false, true, false, false}; + case DpadPosition::DPAD_DOWN_RIGHT: + return {false, true, true, false}; + case DpadPosition::DPAD_DOWN: + return {false, false, true, false}; + case DpadPosition::DPAD_DOWN_LEFT: + return {false, false, true, true}; + case DpadPosition::DPAD_LEFT: + return {false, false, false, true}; + case DpadPosition::DPAD_UP_LEFT: + return {true, false, false, true}; + default: + return {false, false, false, false}; + } +} + + + + + +class ControllerWithScheduler : + protected ControllerSchedulerState, + protected SuperscalarScheduler +{ +public: + ControllerWithScheduler(Logger& logger); + + RecursiveThrottler& logging_throttler(){ + return m_logging_throttler; + } + + +public: + // Superscalar Commands (the "ssf" framework) + + void issue_barrier(const Cancellable* cancellable); + void issue_nop(const Cancellable* cancellable, Milliseconds duration); + void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ); + void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ); + void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ); + void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ); + + void issue_gyro( + const Cancellable* cancellable, + SwitchGyro& gyro, const char* name, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ); + void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_accel_x, "issue_gyro_accel_x", delay, hold, cooldown, value); + } + void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_accel_y, "issue_gyro_accel_y", delay, hold, cooldown, value); + } + void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_accel_z, "issue_gyro_accel_z", delay, hold, cooldown, value); + } + void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_rotation_x, "issue_gyro_rotate_x", delay, hold, cooldown, value); + } + void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_rotation_y, "issue_gyro_rotate_y", delay, hold, cooldown, value); + } + void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ){ + issue_gyro(cancellable, m_rotation_z, "issue_gyro_rotate_z", delay, hold, cooldown, value); + } + + void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ); + + +public: + // High speed RPCs. + + void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ); + void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ); + void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ); + void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ); + + +protected: +#if 0 + class LoggingSuppressScope{ + public: + LoggingSuppressScope(std::atomic& counter) + : m_counter(counter) + { + m_counter++; + } + ~LoggingSuppressScope(){ + m_counter--; + } + private: + std::atomic& m_counter; + }; +#endif + +// virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + +protected: + Logger& m_logger; +// std::atomic m_logging_suppress; + RecursiveThrottler m_logging_throttler; + + // If you need both of these locks, always acquire "m_issue_lock" first. + + // This lock makes sure that only one command is issued at a time. It can + // be held for long periods of time if the command queue is full. + std::mutex m_issue_lock; + + // This lock protects the state/fields of this class and subclasses. + // This lock is never held for a long time. + std::mutex m_state_lock; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp index dbcc73ad74..829494e00c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.cpp @@ -1,111 +1,111 @@ -/* Nintendo Switch Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonTools/Async/InterruptableCommands.tpp" -#include "CommonTools/Async/SuperControlSession.tpp" -#include "Controllers/ControllerTypes.h" -#include "Controllers/KeyboardInput/KeyboardInput.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch_Joycon.h" - -namespace PokemonAutomation{ - -// Instantiate some template helper classes. -template class AsyncCommandSession; -template class SuperControlSession; - -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - -class JoyconController::KeyboardManager final : - public PokemonAutomation::KeyboardManager -{ -public: - KeyboardManager(JoyconController& controller, ControllerType controller_type) - : PokemonAutomation::KeyboardManager(controller) - { - std::vector> mapping; - switch (controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.LEFT_JOYCON.current_refs(); - break; - case ControllerType::NintendoSwitch_RightJoycon: - mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.RIGHT_JOYCON.current_refs(); - break; - default:; - } - for (const auto& deltas : mapping){ - const JoyconKeyMapTableRow& row = static_cast(*deltas); - m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); - } - start(); - } - ~KeyboardManager(){ - stop(); - } - virtual void send_state(const ControllerState& state) override{ - const JoyconState& switch_state = static_cast(state); -#if 0 - m_controller->logger().log( - "VirtualController: (" + button_to_string(switch_state.buttons) + - "), LJ(" + std::to_string(switch_state.joystick_x) + "," + std::to_string(switch_state.joystick_y) + - ")", - COLOR_DARKGREEN - ); -#endif - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - Milliseconds ticksize = m_controller->ticksize(); - static_cast(m_controller)->issue_full_controller_state( - nullptr, - switch_state.buttons, - switch_state.joystick_x, - switch_state.joystick_y, - ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255 - ); - } -}; - - - -JoyconController::JoyconController(ControllerType controller_type) - : m_keyboard_manager(CONSTRUCT_TOKEN, *this, controller_type) -{ - -} -JoyconController::~JoyconController(){ - -} -void JoyconController::stop() noexcept{ - m_keyboard_manager->stop(); -} - - -void JoyconController::keyboard_release_all(){ - m_keyboard_manager->clear_state(); -} -void JoyconController::keyboard_press(const QKeyEvent& event){ - m_keyboard_manager->on_key_press(event); -} -void JoyconController::keyboard_release(const QKeyEvent& event){ - m_keyboard_manager->on_key_release(event); -} - - - - - - - -} -} +/* Nintendo Switch Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonTools/Async/InterruptableCommands.tpp" +#include "CommonTools/Async/SuperControlSession.tpp" +#include "Controllers/ControllerTypes.h" +#include "Controllers/KeyboardInput/KeyboardInput.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch_Joycon.h" + +namespace PokemonAutomation{ + +// Instantiate some template helper classes. +template class AsyncCommandSession; +template class SuperControlSession; + +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + +class JoyconController::KeyboardManager final : + public PokemonAutomation::KeyboardManager +{ +public: + KeyboardManager(JoyconController& controller, ControllerType controller_type) + : PokemonAutomation::KeyboardManager(controller) + { + std::vector> mapping; + switch (controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.LEFT_JOYCON.current_refs(); + break; + case ControllerType::NintendoSwitch_RightJoycon: + mapping = ConsoleSettings::instance().KEYBOARD_MAPPINGS.RIGHT_JOYCON.current_refs(); + break; + default:; + } + for (const auto& deltas : mapping){ + const JoyconKeyMapTableRow& row = static_cast(*deltas); + m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); + } + start(); + } + ~KeyboardManager(){ + stop(); + } + virtual void send_state(const ControllerState& state) override{ + const JoyconState& switch_state = static_cast(state); +#if 0 + m_controller->logger().log( + "VirtualController: (" + button_to_string(switch_state.buttons) + + "), LJ(" + std::to_string(switch_state.joystick_x) + "," + std::to_string(switch_state.joystick_y) + + ")", + COLOR_DARKGREEN + ); +#endif + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + Milliseconds ticksize = m_controller->ticksize(); + static_cast(m_controller)->issue_full_controller_state( + nullptr, + switch_state.buttons, + switch_state.joystick_x, + switch_state.joystick_y, + ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255 + ); + } +}; + + + +JoyconController::JoyconController(ControllerType controller_type) + : m_keyboard_manager(CONSTRUCT_TOKEN, *this, controller_type) +{ + +} +JoyconController::~JoyconController(){ + +} +void JoyconController::stop() noexcept{ + m_keyboard_manager->stop(); +} + + +void JoyconController::keyboard_release_all(){ + m_keyboard_manager->clear_state(); +} +void JoyconController::keyboard_press(const QKeyEvent& event){ + m_keyboard_manager->on_key_press(event); +} +void JoyconController::keyboard_release(const QKeyEvent& event){ + m_keyboard_manager->on_key_release(event); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h index 50b6346424..50722c8bcf 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_Joycon.h @@ -1,178 +1,178 @@ -/* Nintendo Switch Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Joycon_H -#define PokemonAutomation_NintendoSwitch_Joycon_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "NintendoSwitch_ControllerState.h" -#include "Controllers/Controller.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class JoyconController; -using JoyconContext = ControllerContext; - - - -constexpr Button VALID_LEFT_JOYCON_BUTTONS = - BUTTON_DOWN | - BUTTON_UP | - BUTTON_RIGHT | - BUTTON_LEFT | - BUTTON_LEFT_SR | - BUTTON_LEFT_SL | - BUTTON_L | - BUTTON_ZL | - BUTTON_MINUS | - BUTTON_LCLICK | - BUTTON_CAPTURE; - -constexpr Button VALID_RIGHT_JOYCON_BUTTONS = - BUTTON_Y | - BUTTON_X | - BUTTON_B | - BUTTON_A | - BUTTON_RIGHT_SR | - BUTTON_RIGHT_SL | - BUTTON_R | - BUTTON_ZR | - BUTTON_PLUS | - BUTTON_RCLICK | - BUTTON_HOME; - - - -class JoyconController : public AbstractController{ -public: - using ContextType = JoyconContext; - - JoyconController(ControllerType controller_type); - virtual ~JoyconController(); - - // Must call before destruction begins. - void stop() noexcept; - - -public: - // Press all the buttons set in the bitfield simultaneously. - // This command will wait until all the selected buttons are ready to - // ensure that they are all dispatched simultaneously. - virtual void issue_buttons( - const Cancellable* cancellable, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) = 0; - - virtual void issue_joystick( - const Cancellable* cancellable, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) = 0; - - // Gyro: Accelerometer (experimental - API subject to change) - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - - // - // Press all the following buttons/joysticks simultaneously for the - // specified duration. No wait is added at the end. Thus you can issue - // these back-to-back to simulate buttons being pressed and released - // concurrently with other buttons being held down the whole time. - // - // This command will wait until the controller is fully idle (including - // cooldowns) before it starts. This ensures that everything is issued - // simultaneously. In other words, there is an implied call to - // "issue_barrier()" before executing the state. - // - // The sole purpose of this function is for keyboard commands. - // For programs, it is easier to use the individual button/joystick - // functions above. - // - // If we need to support new Switch controller functionality - // (such as Joycon gyro or new stuff in Switch 2), we can simply add - // overloads to this and gate them behind features. - // - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Button button, - uint8_t joystick_x, uint8_t joystick_y, - Milliseconds hold - ) = 0; - - -public: - // - // High speed Macros - // - // Be mindful when calling these mashing functions on a tick imprecise - // controller. You can guarantee that some (most) of them will be dropped. - // - // Even if you are on a tick-precise controller, it is not advised to call - // these if you are micromanaging with tick-level granularity. The exact - // timing characteristics and button selection is not specified and may be - // context and implementation-dependent. - // - - // Mash a button as quickly as possible. - virtual void issue_mash_button( - const Cancellable* cancellable, - Button button, Milliseconds duration - ) = 0; - - -public: - // Keyboard Input - - virtual void keyboard_release_all() override; - virtual void keyboard_press(const QKeyEvent& event) override; - virtual void keyboard_release(const QKeyEvent& event) override; - - -private: - class KeyboardManager; - Pimpl m_keyboard_manager; -}; - - - - - - - -} -} -#endif +/* Nintendo Switch Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Joycon_H +#define PokemonAutomation_NintendoSwitch_Joycon_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "NintendoSwitch_ControllerState.h" +#include "Controllers/Controller.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class JoyconController; +using JoyconContext = ControllerContext; + + + +constexpr Button VALID_LEFT_JOYCON_BUTTONS = + BUTTON_DOWN | + BUTTON_UP | + BUTTON_RIGHT | + BUTTON_LEFT | + BUTTON_LEFT_SR | + BUTTON_LEFT_SL | + BUTTON_L | + BUTTON_ZL | + BUTTON_MINUS | + BUTTON_LCLICK | + BUTTON_CAPTURE; + +constexpr Button VALID_RIGHT_JOYCON_BUTTONS = + BUTTON_Y | + BUTTON_X | + BUTTON_B | + BUTTON_A | + BUTTON_RIGHT_SR | + BUTTON_RIGHT_SL | + BUTTON_R | + BUTTON_ZR | + BUTTON_PLUS | + BUTTON_RCLICK | + BUTTON_HOME; + + + +class JoyconController : public AbstractController{ +public: + using ContextType = JoyconContext; + + JoyconController(ControllerType controller_type); + virtual ~JoyconController(); + + // Must call before destruction begins. + void stop() noexcept; + + +public: + // Press all the buttons set in the bitfield simultaneously. + // This command will wait until all the selected buttons are ready to + // ensure that they are all dispatched simultaneously. + virtual void issue_buttons( + const Cancellable* cancellable, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) = 0; + + virtual void issue_joystick( + const Cancellable* cancellable, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) = 0; + + // Gyro: Accelerometer (experimental - API subject to change) + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + + // + // Press all the following buttons/joysticks simultaneously for the + // specified duration. No wait is added at the end. Thus you can issue + // these back-to-back to simulate buttons being pressed and released + // concurrently with other buttons being held down the whole time. + // + // This command will wait until the controller is fully idle (including + // cooldowns) before it starts. This ensures that everything is issued + // simultaneously. In other words, there is an implied call to + // "issue_barrier()" before executing the state. + // + // The sole purpose of this function is for keyboard commands. + // For programs, it is easier to use the individual button/joystick + // functions above. + // + // If we need to support new Switch controller functionality + // (such as Joycon gyro or new stuff in Switch 2), we can simply add + // overloads to this and gate them behind features. + // + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Button button, + uint8_t joystick_x, uint8_t joystick_y, + Milliseconds hold + ) = 0; + + +public: + // + // High speed Macros + // + // Be mindful when calling these mashing functions on a tick imprecise + // controller. You can guarantee that some (most) of them will be dropped. + // + // Even if you are on a tick-precise controller, it is not advised to call + // these if you are micromanaging with tick-level granularity. The exact + // timing characteristics and button selection is not specified and may be + // context and implementation-dependent. + // + + // Mash a button as quickly as possible. + virtual void issue_mash_button( + const Cancellable* cancellable, + Button button, Milliseconds duration + ) = 0; + + +public: + // Keyboard Input + + virtual void keyboard_release_all() override; + virtual void keyboard_press(const QKeyEvent& event) override; + virtual void keyboard_release(const QKeyEvent& event) override; + + +private: + class KeyboardManager; + Pimpl m_keyboard_manager; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp index b86530efb3..f0c7a2e494 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.cpp @@ -1,503 +1,503 @@ -/* Nintendo Keyboard Mapping - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch_KeyboardMapping.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -ProControllerKeyMapTableRow::ProControllerKeyMapTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") - , key(LockMode::UNLOCK_WHILE_RUNNING) - , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) - , dpad_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , dpad_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , left_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , left_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , right_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , right_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) -{ - add_option(label, "Description"); - add_option(key, "Key"); - add_option(buttons, "Button Bit-Field"); - add_option(dpad_x, "Dpad x"); - add_option(dpad_y, "Dpad y"); - add_option(left_stick_x, "Left-Stick x"); - add_option(left_stick_y, "Left-Stick y"); - add_option(right_stick_x, "Right-Stick x"); - add_option(right_stick_y, "Right-Stick y"); - set_advanced_mode(static_cast(parent_table).advanced_mode()); -} -ProControllerKeyMapTableRow::ProControllerKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas -) - : ProControllerKeyMapTableRow(parent_table) -{ - label.set(std::move(description)); - this->key.set(key); - buttons.set(deltas.buttons); - dpad_x.set(deltas.dpad_x); - dpad_y.set(deltas.dpad_y); - left_stick_x.set(deltas.left_x); - left_stick_y.set(deltas.left_y); - right_stick_x.set(deltas.right_x); - right_stick_y.set(deltas.right_y); - set_advanced_mode(advanced_mode); -} -std::unique_ptr ProControllerKeyMapTableRow::clone() const{ - std::unique_ptr ret(new ProControllerKeyMapTableRow(parent())); - ret->label.set(label); - ret->key.set((uint32_t)key); - ret->buttons.set(buttons); - ret->dpad_x.set(dpad_x); - ret->dpad_y.set(dpad_y); - ret->left_stick_x.set(left_stick_x); - ret->left_stick_y.set(left_stick_y); - ret->right_stick_x.set(right_stick_x); - ret->right_stick_y.set(right_stick_y); - ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); - return ret; -} -ProControllerDeltas ProControllerKeyMapTableRow::snapshot() const{ - return { - .buttons = (Button)buttons.current_value(), - .dpad_x = dpad_x, - .dpad_y = dpad_y, - .left_x = left_stick_x, - .left_y = left_stick_y, - .right_x = right_stick_x, - .right_y = right_stick_y, - }; -} -void ProControllerKeyMapTableRow::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - if (enabled){ - label.set_locked(false); - buttons.set_visibility(ConfigOptionState::ENABLED); - dpad_x.set_visibility(ConfigOptionState::ENABLED); - dpad_y.set_visibility(ConfigOptionState::ENABLED); - left_stick_x.set_visibility(ConfigOptionState::ENABLED); - left_stick_y.set_visibility(ConfigOptionState::ENABLED); - right_stick_x.set_visibility(ConfigOptionState::ENABLED); - right_stick_y.set_visibility(ConfigOptionState::ENABLED); - }else{ - label.set_locked(true); - buttons.set_visibility(ConfigOptionState::DISABLED); - dpad_x.set_visibility(ConfigOptionState::DISABLED); - dpad_y.set_visibility(ConfigOptionState::DISABLED); - left_stick_x.set_visibility(ConfigOptionState::DISABLED); - left_stick_y.set_visibility(ConfigOptionState::DISABLED); - right_stick_x.set_visibility(ConfigOptionState::DISABLED); - right_stick_y.set_visibility(ConfigOptionState::DISABLED); - } -} - - - - - -ProControllerKeyboardMappingTable::ProControllerKeyboardMappingTable() - : EditableTableOption_t( - "Pro Controller:", - LockMode::UNLOCK_WHILE_RUNNING, - true, - make_defaults() - ) - , m_advanced_mode(false) -{} -std::vector ProControllerKeyboardMappingTable::make_header() const{ - return std::vector{ - "Description", - "Key", - "Button Bit-Field", - "Dpad x", - "Dpad y", - "Left-Stick x", - "Left-Stick y", - "Right-Stick x", - "Right-Stick y", - }; -} -void ProControllerKeyboardMappingTable::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - run_on_all_rows([enabled](ProControllerKeyMapTableRow& row){ - row.set_advanced_mode(enabled); - return false; - }); -} - - -std::unique_ptr ProControllerKeyboardMappingTable::make_mapping( - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas -){ - return std::make_unique( - *this, - m_advanced_mode.load(std::memory_order_relaxed), - std::move(description), - key, - deltas - ); -} -std::vector> ProControllerKeyboardMappingTable::make_defaults(){ - std::vector> ret; - - ret.emplace_back(make_mapping("Dpad Up", Qt::Key::Key_8, ProControllerDeltas{.dpad_x = 0, .dpad_y = -1})); - ret.emplace_back(make_mapping("Dpad Up+Right", Qt::Key::Key_9, ProControllerDeltas{.dpad_x = +1, .dpad_y = -1})); - ret.emplace_back(make_mapping("Dpad Right", Qt::Key::Key_6, ProControllerDeltas{.dpad_x = +1, .dpad_y = 0})); - ret.emplace_back(make_mapping("Dpad Down+Right", Qt::Key::Key_3, ProControllerDeltas{.dpad_x = +1, .dpad_y = +1})); - ret.emplace_back(make_mapping("Dpad Down", Qt::Key::Key_2, ProControllerDeltas{.dpad_x = 0, .dpad_y = +1})); - ret.emplace_back(make_mapping("Dpad Down+Left", Qt::Key::Key_1, ProControllerDeltas{.dpad_x = -1, .dpad_y = +1})); - ret.emplace_back(make_mapping("Dpad Left", Qt::Key::Key_4, ProControllerDeltas{.dpad_x = -1, .dpad_y = 0})); - ret.emplace_back(make_mapping("Dpad Up+Left", Qt::Key::Key_7, ProControllerDeltas{.dpad_x = -1, .dpad_y = -1})); - - ret.emplace_back(make_mapping("Left-Stick Up", Qt::Key::Key_W, ProControllerDeltas{.left_x = 0, .left_y = -1})); - ret.emplace_back(make_mapping("Left-Stick Left", Qt::Key::Key_A, ProControllerDeltas{.left_x = -1, .left_y = 0})); - ret.emplace_back(make_mapping("Left-Stick Down", Qt::Key::Key_S, ProControllerDeltas{.left_x = 0, .left_y = +1})); - ret.emplace_back(make_mapping("Left-Stick Right", Qt::Key::Key_D, ProControllerDeltas{.left_x = +1, .left_y = 0})); - ret.emplace_back(make_mapping("Right-Stick Up", Qt::Key::Key_Up, ProControllerDeltas{.right_x = 0, .right_y = -1})); - ret.emplace_back(make_mapping("Right-Stick Right", Qt::Key::Key_Right, ProControllerDeltas{.right_x = +1, .right_y = 0})); - ret.emplace_back(make_mapping("Right-Stick Down", Qt::Key::Key_Down, ProControllerDeltas{.right_x = 0, .right_y = +1})); - ret.emplace_back(make_mapping("Right-Stick Left", Qt::Key::Key_Left, ProControllerDeltas{.right_x = -1, .right_y = 0})); - - ret.emplace_back(make_mapping("Y", Qt::Key::Key_Slash, ProControllerDeltas{.buttons = BUTTON_Y})); - ret.emplace_back(make_mapping("Y", Qt::Key::Key_Question, ProControllerDeltas{.buttons = BUTTON_Y})); - - ret.emplace_back(make_mapping("B", Qt::Key::Key_Shift, ProControllerDeltas{.buttons = BUTTON_B})); - ret.emplace_back(make_mapping("B", Qt::Key::Key_Control, ProControllerDeltas{.buttons = BUTTON_B})); - - ret.emplace_back(make_mapping("A", Qt::Key::Key_Enter, ProControllerDeltas{.buttons = BUTTON_A})); - ret.emplace_back(make_mapping("A", Qt::Key::Key_Return, ProControllerDeltas{.buttons = BUTTON_A})); - - ret.emplace_back(make_mapping("X", Qt::Key::Key_Apostrophe,ProControllerDeltas{.buttons = BUTTON_X})); - ret.emplace_back(make_mapping("X", Qt::Key::Key_QuoteDbl, ProControllerDeltas{.buttons = BUTTON_X})); - - ret.emplace_back(make_mapping("L", Qt::Key::Key_Q, ProControllerDeltas{.buttons = BUTTON_L})); - ret.emplace_back(make_mapping("R", Qt::Key::Key_E, ProControllerDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("ZL", Qt::Key::Key_R, ProControllerDeltas{.buttons = BUTTON_ZL})); - ret.emplace_back(make_mapping("R", Qt::Key::Key_BraceRight, ProControllerDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("R", Qt::Key::Key_BracketRight, ProControllerDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Backslash, ProControllerDeltas{.buttons = BUTTON_ZR})); - ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Bar, ProControllerDeltas{.buttons = BUTTON_ZR})); - - ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, ProControllerDeltas{.buttons = BUTTON_MINUS})); - ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore, ProControllerDeltas{.buttons = BUTTON_MINUS})); - ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, ProControllerDeltas{.buttons = BUTTON_PLUS})); - ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, ProControllerDeltas{.buttons = BUTTON_PLUS})); - - ret.emplace_back(make_mapping("L-Click", Qt::Key::Key_C, ProControllerDeltas{.buttons = BUTTON_LCLICK})); - ret.emplace_back(make_mapping("R-Click", Qt::Key::Key_0, ProControllerDeltas{.buttons = BUTTON_RCLICK})); - - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, ProControllerDeltas{.buttons = BUTTON_HOME})); - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, ProControllerDeltas{.buttons = BUTTON_HOME})); - ret.emplace_back(make_mapping("Home", Qt::Key::Key_H, ProControllerDeltas{.buttons = BUTTON_HOME})); - - ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, ProControllerDeltas{.buttons = BUTTON_CAPTURE})); - - ret.emplace_back(make_mapping("A+R (for CFW)", Qt::Key::Key_Y, ProControllerDeltas{.buttons = BUTTON_A | BUTTON_R})); - - return ret; -} - - - - -JoyconKeyMapTableRow::JoyconKeyMapTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") - , key(LockMode::UNLOCK_WHILE_RUNNING) - , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) - , joystick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) - , joystick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) -{ - add_option(label, "Description"); - add_option(key, "Key"); - add_option(buttons, "Button Bit-Field"); - add_option(joystick_x, "Joystick x"); - add_option(joystick_y, "Joystick y"); - set_advanced_mode(static_cast(parent_table).advanced_mode()); -} -JoyconKeyMapTableRow::JoyconKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const JoyconDeltas& deltas -) - : JoyconKeyMapTableRow(parent_table) -{ - label.set(std::move(description)); - this->key.set(key); - buttons.set(deltas.buttons); - joystick_x.set(deltas.joystick_x); - joystick_y.set(deltas.joystick_y); - set_advanced_mode(advanced_mode); -} -std::unique_ptr JoyconKeyMapTableRow::clone() const{ - std::unique_ptr ret(new JoyconKeyMapTableRow(parent())); - ret->label.set(label); - ret->key.set((uint32_t)key); - ret->buttons.set(buttons); - ret->joystick_x.set(joystick_x); - ret->joystick_y.set(joystick_y); - ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); - return ret; -} -JoyconDeltas JoyconKeyMapTableRow::snapshot() const{ - return { - .buttons = (Button)buttons.current_value(), - .joystick_x = joystick_x, - .joystick_y = joystick_y, - }; -} -void JoyconKeyMapTableRow::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - if (enabled){ - label.set_locked(false); - buttons.set_visibility(ConfigOptionState::ENABLED); - joystick_x.set_visibility(ConfigOptionState::ENABLED); - joystick_y.set_visibility(ConfigOptionState::ENABLED); - }else{ - label.set_locked(true); - buttons.set_visibility(ConfigOptionState::DISABLED); - joystick_x.set_visibility(ConfigOptionState::DISABLED); - joystick_y.set_visibility(ConfigOptionState::DISABLED); - } -} - - - -JoyconKeyboardMappingTable::JoyconKeyboardMappingTable(bool left) - : EditableTableOption_t( - left ? "Left Joycon:" : "Right Joycon:", - LockMode::UNLOCK_WHILE_RUNNING, - true, - make_defaults(left) - ) - , m_advanced_mode(false) -{} -std::vector JoyconKeyboardMappingTable::make_header() const{ - return std::vector{ - "Description", - "Key", - "Button Bit-Field", - "Joystick x", - "Joystick y", - }; -} -void JoyconKeyboardMappingTable::set_advanced_mode(bool enabled){ - m_advanced_mode.store(enabled, std::memory_order_relaxed); - run_on_all_rows([enabled](JoyconKeyMapTableRow& row){ - row.set_advanced_mode(enabled); - return false; - }); -} - - -std::unique_ptr JoyconKeyboardMappingTable::make_mapping( - std::string description, - Qt::Key key, - const JoyconDeltas& deltas -){ - return std::make_unique( - *this, - m_advanced_mode.load(std::memory_order_relaxed), - std::move(description), - key, - deltas - ); -} -std::vector> JoyconKeyboardMappingTable::make_defaults(bool left){ - std::vector> ret; - - if (left){ - ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - - ret.emplace_back(make_mapping("Vertical: Up", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_UP})); - ret.emplace_back(make_mapping("Vertical: Right", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_RIGHT})); - ret.emplace_back(make_mapping("Vertical: Down", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_DOWN})); - ret.emplace_back(make_mapping("Vertical: Left", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_LEFT})); - - ret.emplace_back(make_mapping("Vertical: L", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_L})); - ret.emplace_back(make_mapping("Vertical: ZL", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZL})); - ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_LCLICK})); - - ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - - ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_RIGHT})); - ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_RIGHT})); - ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_DOWN})); - ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_DOWN})); - ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_LEFT})); - ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_LEFT})); - ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_UP})); - ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_UP})); - - ret.emplace_back(make_mapping("Sideways: L", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_L})); - ret.emplace_back(make_mapping("Sideways: ZL", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZL})); - ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_LCLICK})); - - // Other - ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, JoyconDeltas{.buttons = BUTTON_MINUS})); - ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore,JoyconDeltas{.buttons = BUTTON_MINUS})); - - ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, JoyconDeltas{.buttons = BUTTON_CAPTURE})); - - ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_LEFT_SL})); - ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_LEFT_SR})); - }else{ - ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - - ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_X})); - ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_X})); - - ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_A})); - ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_A})); - - ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_B})); - ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_B})); - - ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_Y})); - ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_Y})); - - ret.emplace_back(make_mapping("Vertical: R", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("Vertical: ZR", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZR})); - ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_RCLICK})); - - ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); - ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); - ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); - - ret.emplace_back(make_mapping("Sideways: X", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_Y})); - ret.emplace_back(make_mapping("Sideways: A", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_X})); - ret.emplace_back(make_mapping("Sideways: B", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_A})); - ret.emplace_back(make_mapping("Sideways: Y", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_B})); - - ret.emplace_back(make_mapping("Sideways: R", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_R})); - ret.emplace_back(make_mapping("Sideways: ZR", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZR})); - ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_RCLICK})); - - // Other - ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, JoyconDeltas{.buttons = BUTTON_PLUS})); - ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, JoyconDeltas{.buttons = BUTTON_PLUS})); - - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, JoyconDeltas{.buttons = BUTTON_HOME})); - ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, JoyconDeltas{.buttons = BUTTON_HOME})); - - ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_RIGHT_SL})); - ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_RIGHT_SR})); - } - - return ret; -} - - - - - - - - - - - - - - - - - - - - - - - -KeyboardMappingOption::~KeyboardMappingOption(){ - ADVANCED_MODE.remove_listener(*this); -} -KeyboardMappingOption::KeyboardMappingOption() - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , DESCRIPTION( - "The following table is the mapping of keyboard keys to Switch controller presses. " - "If you wish to remap a key, click on the cell in the \"Key\" column and press the desired key. " - "You do not need to edit any of the other columns.

" - "Note for keys that change behavior when combined with " - "SHIFT or CTRL, you should include all of those combinations as well. " - "For example, the default mapping for the Y button is both '/' and '?' " - "because they are treated as different keys depending on whether SHIFT " - "is held down. Letters are exempt from this as both lower and upper case " - "letters are considered the same." - "

" - "Advanced users are free to edit the rest of the table. You can create " - "new mappings or mappings that result in multiple buttons. " - "For example, there is a special mapping for pressing A + R " - "simultaneously that is useful for CFW users who are remotely " - "controlling the program over Team Viewer." - ) - , ADVANCED_MODE( - "Unlock entire table (Advanced Mode):", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , LEFT_JOYCON(true) - , RIGHT_JOYCON(false) -{ - PA_ADD_STATIC(DESCRIPTION); - PA_ADD_OPTION(ADVANCED_MODE); - PA_ADD_OPTION(PRO_CONTROLLER); - PA_ADD_OPTION(LEFT_JOYCON); - PA_ADD_OPTION(RIGHT_JOYCON); - ADVANCED_MODE.add_listener(*this); -} - - -void KeyboardMappingOption::load_json(const JsonValue& json){ - BatchOption::load_json(json); - KeyboardMappingOption::on_config_value_changed(this); -} -void KeyboardMappingOption::on_config_value_changed(void* object){ - PRO_CONTROLLER.set_advanced_mode(ADVANCED_MODE); - LEFT_JOYCON.set_advanced_mode(ADVANCED_MODE); - RIGHT_JOYCON.set_advanced_mode(ADVANCED_MODE); -} - - - - - - - - - - - - -} -} +/* Nintendo Keyboard Mapping + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch_KeyboardMapping.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +ProControllerKeyMapTableRow::ProControllerKeyMapTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") + , key(LockMode::UNLOCK_WHILE_RUNNING) + , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) + , dpad_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , dpad_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , left_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , left_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , right_stick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , right_stick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) +{ + add_option(label, "Description"); + add_option(key, "Key"); + add_option(buttons, "Button Bit-Field"); + add_option(dpad_x, "Dpad x"); + add_option(dpad_y, "Dpad y"); + add_option(left_stick_x, "Left-Stick x"); + add_option(left_stick_y, "Left-Stick y"); + add_option(right_stick_x, "Right-Stick x"); + add_option(right_stick_y, "Right-Stick y"); + set_advanced_mode(static_cast(parent_table).advanced_mode()); +} +ProControllerKeyMapTableRow::ProControllerKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas +) + : ProControllerKeyMapTableRow(parent_table) +{ + label.set(std::move(description)); + this->key.set(key); + buttons.set(deltas.buttons); + dpad_x.set(deltas.dpad_x); + dpad_y.set(deltas.dpad_y); + left_stick_x.set(deltas.left_x); + left_stick_y.set(deltas.left_y); + right_stick_x.set(deltas.right_x); + right_stick_y.set(deltas.right_y); + set_advanced_mode(advanced_mode); +} +std::unique_ptr ProControllerKeyMapTableRow::clone() const{ + std::unique_ptr ret(new ProControllerKeyMapTableRow(parent())); + ret->label.set(label); + ret->key.set((uint32_t)key); + ret->buttons.set(buttons); + ret->dpad_x.set(dpad_x); + ret->dpad_y.set(dpad_y); + ret->left_stick_x.set(left_stick_x); + ret->left_stick_y.set(left_stick_y); + ret->right_stick_x.set(right_stick_x); + ret->right_stick_y.set(right_stick_y); + ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); + return ret; +} +ProControllerDeltas ProControllerKeyMapTableRow::snapshot() const{ + return { + .buttons = (Button)buttons.current_value(), + .dpad_x = dpad_x, + .dpad_y = dpad_y, + .left_x = left_stick_x, + .left_y = left_stick_y, + .right_x = right_stick_x, + .right_y = right_stick_y, + }; +} +void ProControllerKeyMapTableRow::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + if (enabled){ + label.set_locked(false); + buttons.set_visibility(ConfigOptionState::ENABLED); + dpad_x.set_visibility(ConfigOptionState::ENABLED); + dpad_y.set_visibility(ConfigOptionState::ENABLED); + left_stick_x.set_visibility(ConfigOptionState::ENABLED); + left_stick_y.set_visibility(ConfigOptionState::ENABLED); + right_stick_x.set_visibility(ConfigOptionState::ENABLED); + right_stick_y.set_visibility(ConfigOptionState::ENABLED); + }else{ + label.set_locked(true); + buttons.set_visibility(ConfigOptionState::DISABLED); + dpad_x.set_visibility(ConfigOptionState::DISABLED); + dpad_y.set_visibility(ConfigOptionState::DISABLED); + left_stick_x.set_visibility(ConfigOptionState::DISABLED); + left_stick_y.set_visibility(ConfigOptionState::DISABLED); + right_stick_x.set_visibility(ConfigOptionState::DISABLED); + right_stick_y.set_visibility(ConfigOptionState::DISABLED); + } +} + + + + + +ProControllerKeyboardMappingTable::ProControllerKeyboardMappingTable() + : EditableTableOption_t( + "Pro Controller:", + LockMode::UNLOCK_WHILE_RUNNING, + true, + make_defaults() + ) + , m_advanced_mode(false) +{} +std::vector ProControllerKeyboardMappingTable::make_header() const{ + return std::vector{ + "Description", + "Key", + "Button Bit-Field", + "Dpad x", + "Dpad y", + "Left-Stick x", + "Left-Stick y", + "Right-Stick x", + "Right-Stick y", + }; +} +void ProControllerKeyboardMappingTable::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + run_on_all_rows([enabled](ProControllerKeyMapTableRow& row){ + row.set_advanced_mode(enabled); + return false; + }); +} + + +std::unique_ptr ProControllerKeyboardMappingTable::make_mapping( + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas +){ + return std::make_unique( + *this, + m_advanced_mode.load(std::memory_order_relaxed), + std::move(description), + key, + deltas + ); +} +std::vector> ProControllerKeyboardMappingTable::make_defaults(){ + std::vector> ret; + + ret.emplace_back(make_mapping("Dpad Up", Qt::Key::Key_8, ProControllerDeltas{.dpad_x = 0, .dpad_y = -1})); + ret.emplace_back(make_mapping("Dpad Up+Right", Qt::Key::Key_9, ProControllerDeltas{.dpad_x = +1, .dpad_y = -1})); + ret.emplace_back(make_mapping("Dpad Right", Qt::Key::Key_6, ProControllerDeltas{.dpad_x = +1, .dpad_y = 0})); + ret.emplace_back(make_mapping("Dpad Down+Right", Qt::Key::Key_3, ProControllerDeltas{.dpad_x = +1, .dpad_y = +1})); + ret.emplace_back(make_mapping("Dpad Down", Qt::Key::Key_2, ProControllerDeltas{.dpad_x = 0, .dpad_y = +1})); + ret.emplace_back(make_mapping("Dpad Down+Left", Qt::Key::Key_1, ProControllerDeltas{.dpad_x = -1, .dpad_y = +1})); + ret.emplace_back(make_mapping("Dpad Left", Qt::Key::Key_4, ProControllerDeltas{.dpad_x = -1, .dpad_y = 0})); + ret.emplace_back(make_mapping("Dpad Up+Left", Qt::Key::Key_7, ProControllerDeltas{.dpad_x = -1, .dpad_y = -1})); + + ret.emplace_back(make_mapping("Left-Stick Up", Qt::Key::Key_W, ProControllerDeltas{.left_x = 0, .left_y = -1})); + ret.emplace_back(make_mapping("Left-Stick Left", Qt::Key::Key_A, ProControllerDeltas{.left_x = -1, .left_y = 0})); + ret.emplace_back(make_mapping("Left-Stick Down", Qt::Key::Key_S, ProControllerDeltas{.left_x = 0, .left_y = +1})); + ret.emplace_back(make_mapping("Left-Stick Right", Qt::Key::Key_D, ProControllerDeltas{.left_x = +1, .left_y = 0})); + ret.emplace_back(make_mapping("Right-Stick Up", Qt::Key::Key_Up, ProControllerDeltas{.right_x = 0, .right_y = -1})); + ret.emplace_back(make_mapping("Right-Stick Right", Qt::Key::Key_Right, ProControllerDeltas{.right_x = +1, .right_y = 0})); + ret.emplace_back(make_mapping("Right-Stick Down", Qt::Key::Key_Down, ProControllerDeltas{.right_x = 0, .right_y = +1})); + ret.emplace_back(make_mapping("Right-Stick Left", Qt::Key::Key_Left, ProControllerDeltas{.right_x = -1, .right_y = 0})); + + ret.emplace_back(make_mapping("Y", Qt::Key::Key_Slash, ProControllerDeltas{.buttons = BUTTON_Y})); + ret.emplace_back(make_mapping("Y", Qt::Key::Key_Question, ProControllerDeltas{.buttons = BUTTON_Y})); + + ret.emplace_back(make_mapping("B", Qt::Key::Key_Shift, ProControllerDeltas{.buttons = BUTTON_B})); + ret.emplace_back(make_mapping("B", Qt::Key::Key_Control, ProControllerDeltas{.buttons = BUTTON_B})); + + ret.emplace_back(make_mapping("A", Qt::Key::Key_Enter, ProControllerDeltas{.buttons = BUTTON_A})); + ret.emplace_back(make_mapping("A", Qt::Key::Key_Return, ProControllerDeltas{.buttons = BUTTON_A})); + + ret.emplace_back(make_mapping("X", Qt::Key::Key_Apostrophe,ProControllerDeltas{.buttons = BUTTON_X})); + ret.emplace_back(make_mapping("X", Qt::Key::Key_QuoteDbl, ProControllerDeltas{.buttons = BUTTON_X})); + + ret.emplace_back(make_mapping("L", Qt::Key::Key_Q, ProControllerDeltas{.buttons = BUTTON_L})); + ret.emplace_back(make_mapping("R", Qt::Key::Key_E, ProControllerDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("ZL", Qt::Key::Key_R, ProControllerDeltas{.buttons = BUTTON_ZL})); + ret.emplace_back(make_mapping("R", Qt::Key::Key_BraceRight, ProControllerDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("R", Qt::Key::Key_BracketRight, ProControllerDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Backslash, ProControllerDeltas{.buttons = BUTTON_ZR})); + ret.emplace_back(make_mapping("ZR", Qt::Key::Key_Bar, ProControllerDeltas{.buttons = BUTTON_ZR})); + + ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, ProControllerDeltas{.buttons = BUTTON_MINUS})); + ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore, ProControllerDeltas{.buttons = BUTTON_MINUS})); + ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, ProControllerDeltas{.buttons = BUTTON_PLUS})); + ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, ProControllerDeltas{.buttons = BUTTON_PLUS})); + + ret.emplace_back(make_mapping("L-Click", Qt::Key::Key_C, ProControllerDeltas{.buttons = BUTTON_LCLICK})); + ret.emplace_back(make_mapping("R-Click", Qt::Key::Key_0, ProControllerDeltas{.buttons = BUTTON_RCLICK})); + + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, ProControllerDeltas{.buttons = BUTTON_HOME})); + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, ProControllerDeltas{.buttons = BUTTON_HOME})); + ret.emplace_back(make_mapping("Home", Qt::Key::Key_H, ProControllerDeltas{.buttons = BUTTON_HOME})); + + ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, ProControllerDeltas{.buttons = BUTTON_CAPTURE})); + + ret.emplace_back(make_mapping("A+R (for CFW)", Qt::Key::Key_Y, ProControllerDeltas{.buttons = BUTTON_A | BUTTON_R})); + + return ret; +} + + + + +JoyconKeyMapTableRow::JoyconKeyMapTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , label(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") + , key(LockMode::UNLOCK_WHILE_RUNNING) + , buttons(LockMode::UNLOCK_WHILE_RUNNING, 0, 0, ((uint32_t)1 << TOTAL_BUTTONS) - 1) + , joystick_x(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) + , joystick_y(LockMode::UNLOCK_WHILE_RUNNING, 0, -1, 1) +{ + add_option(label, "Description"); + add_option(key, "Key"); + add_option(buttons, "Button Bit-Field"); + add_option(joystick_x, "Joystick x"); + add_option(joystick_y, "Joystick y"); + set_advanced_mode(static_cast(parent_table).advanced_mode()); +} +JoyconKeyMapTableRow::JoyconKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const JoyconDeltas& deltas +) + : JoyconKeyMapTableRow(parent_table) +{ + label.set(std::move(description)); + this->key.set(key); + buttons.set(deltas.buttons); + joystick_x.set(deltas.joystick_x); + joystick_y.set(deltas.joystick_y); + set_advanced_mode(advanced_mode); +} +std::unique_ptr JoyconKeyMapTableRow::clone() const{ + std::unique_ptr ret(new JoyconKeyMapTableRow(parent())); + ret->label.set(label); + ret->key.set((uint32_t)key); + ret->buttons.set(buttons); + ret->joystick_x.set(joystick_x); + ret->joystick_y.set(joystick_y); + ret->set_advanced_mode(m_advanced_mode.load(std::memory_order_relaxed)); + return ret; +} +JoyconDeltas JoyconKeyMapTableRow::snapshot() const{ + return { + .buttons = (Button)buttons.current_value(), + .joystick_x = joystick_x, + .joystick_y = joystick_y, + }; +} +void JoyconKeyMapTableRow::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + if (enabled){ + label.set_locked(false); + buttons.set_visibility(ConfigOptionState::ENABLED); + joystick_x.set_visibility(ConfigOptionState::ENABLED); + joystick_y.set_visibility(ConfigOptionState::ENABLED); + }else{ + label.set_locked(true); + buttons.set_visibility(ConfigOptionState::DISABLED); + joystick_x.set_visibility(ConfigOptionState::DISABLED); + joystick_y.set_visibility(ConfigOptionState::DISABLED); + } +} + + + +JoyconKeyboardMappingTable::JoyconKeyboardMappingTable(bool left) + : EditableTableOption_t( + left ? "Left Joycon:" : "Right Joycon:", + LockMode::UNLOCK_WHILE_RUNNING, + true, + make_defaults(left) + ) + , m_advanced_mode(false) +{} +std::vector JoyconKeyboardMappingTable::make_header() const{ + return std::vector{ + "Description", + "Key", + "Button Bit-Field", + "Joystick x", + "Joystick y", + }; +} +void JoyconKeyboardMappingTable::set_advanced_mode(bool enabled){ + m_advanced_mode.store(enabled, std::memory_order_relaxed); + run_on_all_rows([enabled](JoyconKeyMapTableRow& row){ + row.set_advanced_mode(enabled); + return false; + }); +} + + +std::unique_ptr JoyconKeyboardMappingTable::make_mapping( + std::string description, + Qt::Key key, + const JoyconDeltas& deltas +){ + return std::make_unique( + *this, + m_advanced_mode.load(std::memory_order_relaxed), + std::move(description), + key, + deltas + ); +} +std::vector> JoyconKeyboardMappingTable::make_defaults(bool left){ + std::vector> ret; + + if (left){ + ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + + ret.emplace_back(make_mapping("Vertical: Up", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_UP})); + ret.emplace_back(make_mapping("Vertical: Right", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_RIGHT})); + ret.emplace_back(make_mapping("Vertical: Down", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_DOWN})); + ret.emplace_back(make_mapping("Vertical: Left", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_LEFT})); + + ret.emplace_back(make_mapping("Vertical: L", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_L})); + ret.emplace_back(make_mapping("Vertical: ZL", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZL})); + ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_LCLICK})); + + ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + + ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_RIGHT})); + ret.emplace_back(make_mapping("Sideways: Up", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_RIGHT})); + ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_DOWN})); + ret.emplace_back(make_mapping("Sideways: Right", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_DOWN})); + ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_LEFT})); + ret.emplace_back(make_mapping("Sideways: Down", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_LEFT})); + ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_UP})); + ret.emplace_back(make_mapping("Sideways: Left", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_UP})); + + ret.emplace_back(make_mapping("Sideways: L", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_L})); + ret.emplace_back(make_mapping("Sideways: ZL", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZL})); + ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_LCLICK})); + + // Other + ret.emplace_back(make_mapping("-", Qt::Key::Key_Minus, JoyconDeltas{.buttons = BUTTON_MINUS})); + ret.emplace_back(make_mapping("-", Qt::Key::Key_Underscore,JoyconDeltas{.buttons = BUTTON_MINUS})); + + ret.emplace_back(make_mapping("Capture", Qt::Key::Key_Insert, JoyconDeltas{.buttons = BUTTON_CAPTURE})); + + ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_LEFT_SL})); + ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_LEFT_SR})); + }else{ + ret.emplace_back(make_mapping("Vertical: JS Up", Qt::Key::Key_W, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + ret.emplace_back(make_mapping("Vertical: JS Left", Qt::Key::Key_A, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Vertical: JS Down", Qt::Key::Key_S, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + ret.emplace_back(make_mapping("Vertical: JS Right", Qt::Key::Key_D, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + + ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_Apostrophe,JoyconDeltas{.buttons = BUTTON_X})); + ret.emplace_back(make_mapping("Vertical: X", Qt::Key::Key_QuoteDbl, JoyconDeltas{.buttons = BUTTON_X})); + + ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Enter, JoyconDeltas{.buttons = BUTTON_A})); + ret.emplace_back(make_mapping("Vertical: A", Qt::Key::Key_Return, JoyconDeltas{.buttons = BUTTON_A})); + + ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Shift, JoyconDeltas{.buttons = BUTTON_B})); + ret.emplace_back(make_mapping("Vertical: B", Qt::Key::Key_Control, JoyconDeltas{.buttons = BUTTON_B})); + + ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Slash, JoyconDeltas{.buttons = BUTTON_Y})); + ret.emplace_back(make_mapping("Vertical: Y", Qt::Key::Key_Question, JoyconDeltas{.buttons = BUTTON_Y})); + + ret.emplace_back(make_mapping("Vertical: R", Qt::Key::Key_Q, JoyconDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("Vertical: ZR", Qt::Key::Key_E, JoyconDeltas{.buttons = BUTTON_ZR})); + ret.emplace_back(make_mapping("Vertical: JS-Click", Qt::Key::Key_C, JoyconDeltas{.buttons = BUTTON_RCLICK})); + + ret.emplace_back(make_mapping("Sideways: JS Up", Qt::Key::Key_T, JoyconDeltas{.joystick_x = -1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Left", Qt::Key::Key_F, JoyconDeltas{.joystick_x = 0, .joystick_y = +1})); + ret.emplace_back(make_mapping("Sideways: JS Down", Qt::Key::Key_G, JoyconDeltas{.joystick_x = +1, .joystick_y = 0})); + ret.emplace_back(make_mapping("Sideways: JS Right", Qt::Key::Key_H, JoyconDeltas{.joystick_x = 0, .joystick_y = -1})); + + ret.emplace_back(make_mapping("Sideways: X", Qt::Key::Key_Up, JoyconDeltas{.buttons = BUTTON_Y})); + ret.emplace_back(make_mapping("Sideways: A", Qt::Key::Key_Right, JoyconDeltas{.buttons = BUTTON_X})); + ret.emplace_back(make_mapping("Sideways: B", Qt::Key::Key_Down, JoyconDeltas{.buttons = BUTTON_A})); + ret.emplace_back(make_mapping("Sideways: Y", Qt::Key::Key_Left, JoyconDeltas{.buttons = BUTTON_B})); + + ret.emplace_back(make_mapping("Sideways: R", Qt::Key::Key_R, JoyconDeltas{.buttons = BUTTON_R})); + ret.emplace_back(make_mapping("Sideways: ZR", Qt::Key::Key_Y, JoyconDeltas{.buttons = BUTTON_ZR})); + ret.emplace_back(make_mapping("Sideways: JS-Click", Qt::Key::Key_N, JoyconDeltas{.buttons = BUTTON_RCLICK})); + + // Other + ret.emplace_back(make_mapping("+", Qt::Key::Key_Plus, JoyconDeltas{.buttons = BUTTON_PLUS})); + ret.emplace_back(make_mapping("+", Qt::Key::Key_Equal, JoyconDeltas{.buttons = BUTTON_PLUS})); + + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Home, JoyconDeltas{.buttons = BUTTON_HOME})); + ret.emplace_back(make_mapping("Home", Qt::Key::Key_Escape, JoyconDeltas{.buttons = BUTTON_HOME})); + + ret.emplace_back(make_mapping("SL", Qt::Key::Key_F1, JoyconDeltas{.buttons = BUTTON_RIGHT_SL})); + ret.emplace_back(make_mapping("SR", Qt::Key::Key_F3, JoyconDeltas{.buttons = BUTTON_RIGHT_SR})); + } + + return ret; +} + + + + + + + + + + + + + + + + + + + + + + + +KeyboardMappingOption::~KeyboardMappingOption(){ + ADVANCED_MODE.remove_listener(*this); +} +KeyboardMappingOption::KeyboardMappingOption() + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , DESCRIPTION( + "The following table is the mapping of keyboard keys to Switch controller presses. " + "If you wish to remap a key, click on the cell in the \"Key\" column and press the desired key. " + "You do not need to edit any of the other columns.

" + "Note for keys that change behavior when combined with " + "SHIFT or CTRL, you should include all of those combinations as well. " + "For example, the default mapping for the Y button is both '/' and '?' " + "because they are treated as different keys depending on whether SHIFT " + "is held down. Letters are exempt from this as both lower and upper case " + "letters are considered the same." + "

" + "Advanced users are free to edit the rest of the table. You can create " + "new mappings or mappings that result in multiple buttons. " + "For example, there is a special mapping for pressing A + R " + "simultaneously that is useful for CFW users who are remotely " + "controlling the program over Team Viewer." + ) + , ADVANCED_MODE( + "Unlock entire table (Advanced Mode):", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , LEFT_JOYCON(true) + , RIGHT_JOYCON(false) +{ + PA_ADD_STATIC(DESCRIPTION); + PA_ADD_OPTION(ADVANCED_MODE); + PA_ADD_OPTION(PRO_CONTROLLER); + PA_ADD_OPTION(LEFT_JOYCON); + PA_ADD_OPTION(RIGHT_JOYCON); + ADVANCED_MODE.add_listener(*this); +} + + +void KeyboardMappingOption::load_json(const JsonValue& json){ + BatchOption::load_json(json); + KeyboardMappingOption::on_config_value_changed(this); +} +void KeyboardMappingOption::on_config_value_changed(void* object){ + PRO_CONTROLLER.set_advanced_mode(ADVANCED_MODE); + LEFT_JOYCON.set_advanced_mode(ADVANCED_MODE); + RIGHT_JOYCON.set_advanced_mode(ADVANCED_MODE); +} + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h index 14d1ffdfb1..cfbe23153a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_KeyboardMapping.h @@ -1,154 +1,154 @@ -/* Nintendo Keyboard Mapping - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_KeyboardMapping_H -#define PokemonAutomation_NintendoSwitch_KeyboardMapping_H - -#include -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/KeyBindingOption.h" -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -struct ProControllerDeltas; -struct JoyconDeltas; - - - -class ProControllerKeyMapTableRow : public EditableTableRow{ -public: - ProControllerKeyMapTableRow(EditableTableOption& parent_table); - ProControllerKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas - ); - virtual std::unique_ptr clone() const override; - ProControllerDeltas snapshot() const; - - void set_advanced_mode(bool enabled); - -private: - std::atomic m_advanced_mode; - -public: - StringCell label; - KeyBindingCell key; - SimpleIntegerCell buttons; - SimpleIntegerCell dpad_x; - SimpleIntegerCell dpad_y; - SimpleIntegerCell left_stick_x; - SimpleIntegerCell left_stick_y; - SimpleIntegerCell right_stick_x; - SimpleIntegerCell right_stick_y; -}; - -class ProControllerKeyboardMappingTable : public EditableTableOption_t{ -public: - ProControllerKeyboardMappingTable(); - virtual std::vector make_header() const override; - - bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } - void set_advanced_mode(bool enabled); - - std::unique_ptr make_mapping( - std::string description, - Qt::Key key, - const ProControllerDeltas& deltas - ); - std::vector> make_defaults(); - -private: - std::atomic m_advanced_mode; -}; - - - - -class JoyconKeyMapTableRow : public EditableTableRow{ -public: - JoyconKeyMapTableRow(EditableTableOption& parent_table); - JoyconKeyMapTableRow( - EditableTableOption& parent_table, - bool advanced_mode, - std::string description, - Qt::Key key, - const JoyconDeltas& deltas - ); - virtual std::unique_ptr clone() const override; - JoyconDeltas snapshot() const; - - void set_advanced_mode(bool enabled); - -private: - std::atomic m_advanced_mode; - -public: - StringCell label; - KeyBindingCell key; - SimpleIntegerCell buttons; - SimpleIntegerCell joystick_x; - SimpleIntegerCell joystick_y; -}; - -class JoyconKeyboardMappingTable : public EditableTableOption_t{ -public: - JoyconKeyboardMappingTable(bool left); - virtual std::vector make_header() const override; - - bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } - void set_advanced_mode(bool enabled); - - std::unique_ptr make_mapping( - std::string description, - Qt::Key key, - const JoyconDeltas& deltas - ); - std::vector> make_defaults(bool left); - -private: - std::atomic m_advanced_mode; -}; - - - - - - - - -class KeyboardMappingOption : public BatchOption, private ConfigOption::Listener{ -public: - ~KeyboardMappingOption(); - KeyboardMappingOption(); - -private: - virtual void load_json(const JsonValue& json) override; - virtual void on_config_value_changed(void* object) override; - -public: - StaticTextOption DESCRIPTION; - BooleanCheckBoxOption ADVANCED_MODE; - ProControllerKeyboardMappingTable PRO_CONTROLLER; - JoyconKeyboardMappingTable LEFT_JOYCON; - JoyconKeyboardMappingTable RIGHT_JOYCON; -}; - - - -} -} -#endif +/* Nintendo Keyboard Mapping + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_KeyboardMapping_H +#define PokemonAutomation_NintendoSwitch_KeyboardMapping_H + +#include +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/KeyBindingOption.h" +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +struct ProControllerDeltas; +struct JoyconDeltas; + + + +class ProControllerKeyMapTableRow : public EditableTableRow{ +public: + ProControllerKeyMapTableRow(EditableTableOption& parent_table); + ProControllerKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas + ); + virtual std::unique_ptr clone() const override; + ProControllerDeltas snapshot() const; + + void set_advanced_mode(bool enabled); + +private: + std::atomic m_advanced_mode; + +public: + StringCell label; + KeyBindingCell key; + SimpleIntegerCell buttons; + SimpleIntegerCell dpad_x; + SimpleIntegerCell dpad_y; + SimpleIntegerCell left_stick_x; + SimpleIntegerCell left_stick_y; + SimpleIntegerCell right_stick_x; + SimpleIntegerCell right_stick_y; +}; + +class ProControllerKeyboardMappingTable : public EditableTableOption_t{ +public: + ProControllerKeyboardMappingTable(); + virtual std::vector make_header() const override; + + bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } + void set_advanced_mode(bool enabled); + + std::unique_ptr make_mapping( + std::string description, + Qt::Key key, + const ProControllerDeltas& deltas + ); + std::vector> make_defaults(); + +private: + std::atomic m_advanced_mode; +}; + + + + +class JoyconKeyMapTableRow : public EditableTableRow{ +public: + JoyconKeyMapTableRow(EditableTableOption& parent_table); + JoyconKeyMapTableRow( + EditableTableOption& parent_table, + bool advanced_mode, + std::string description, + Qt::Key key, + const JoyconDeltas& deltas + ); + virtual std::unique_ptr clone() const override; + JoyconDeltas snapshot() const; + + void set_advanced_mode(bool enabled); + +private: + std::atomic m_advanced_mode; + +public: + StringCell label; + KeyBindingCell key; + SimpleIntegerCell buttons; + SimpleIntegerCell joystick_x; + SimpleIntegerCell joystick_y; +}; + +class JoyconKeyboardMappingTable : public EditableTableOption_t{ +public: + JoyconKeyboardMappingTable(bool left); + virtual std::vector make_header() const override; + + bool advanced_mode() const{ return m_advanced_mode.load(std::memory_order_relaxed); } + void set_advanced_mode(bool enabled); + + std::unique_ptr make_mapping( + std::string description, + Qt::Key key, + const JoyconDeltas& deltas + ); + std::vector> make_defaults(bool left); + +private: + std::atomic m_advanced_mode; +}; + + + + + + + + +class KeyboardMappingOption : public BatchOption, private ConfigOption::Listener{ +public: + ~KeyboardMappingOption(); + KeyboardMappingOption(); + +private: + virtual void load_json(const JsonValue& json) override; + virtual void on_config_value_changed(void* object) override; + +public: + StaticTextOption DESCRIPTION; + BooleanCheckBoxOption ADVANCED_MODE; + ProControllerKeyboardMappingTable PRO_CONTROLLER; + JoyconKeyboardMappingTable LEFT_JOYCON; + JoyconKeyboardMappingTable RIGHT_JOYCON; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp index fcef8ec911..20a97aef13 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.cpp @@ -1,110 +1,110 @@ -/* Nintendo Switch Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "CommonTools/Async/InterruptableCommands.tpp" -#include "CommonTools/Async/SuperControlSession.tpp" -#include "Controllers/KeyboardInput/KeyboardInput.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - -// Instantiate some template helper classes. -template class AsyncCommandSession; -template class SuperControlSession; - -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - - - -class ProController::KeyboardManager final : - public PokemonAutomation::KeyboardManager -{ -public: - KeyboardManager(ProController& controller) - : PokemonAutomation::KeyboardManager(controller) - { - std::vector> mapping = - ConsoleSettings::instance().KEYBOARD_MAPPINGS.PRO_CONTROLLER.current_refs(); - for (const auto& deltas : mapping){ - const ProControllerKeyMapTableRow& row = static_cast(*deltas); - m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); - } - start(); - } - ~KeyboardManager(){ - stop(); - } - virtual void send_state(const ControllerState& state) override{ - const ProControllerState& switch_state = static_cast(state); -#if 0 - m_controller.logger().log( - "VirtualController: (" + button_to_string(switch_state.buttons) + - "), dpad(" + dpad_to_string(switch_state.dpad) + - "), LJ(" + std::to_string(switch_state.left_x) + "," + std::to_string(switch_state.left_y) + - "), RJ(" + std::to_string(switch_state.right_x) + "," + std::to_string(switch_state.right_y) + - ")", - COLOR_DARKGREEN - ); -#endif - WriteSpinLock lg(m_lock); - if (m_controller == nullptr){ - return; - } - Milliseconds ticksize = m_controller->ticksize(); - static_cast(m_controller)->issue_full_controller_state( - nullptr, - ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255, - switch_state.buttons, - switch_state.dpad, - switch_state.left_x, - switch_state.left_y, - switch_state.right_x, - switch_state.right_y - ); - } -}; - - - -ProController::ProController() - : m_keyboard_manager(CONSTRUCT_TOKEN, *this) -{ - -} -ProController::~ProController(){ - -} -void ProController::stop() noexcept{ - m_keyboard_manager->stop(); -} - - -void ProController::keyboard_release_all(){ - m_keyboard_manager->clear_state(); -} -void ProController::keyboard_press(const QKeyEvent& event){ - m_keyboard_manager->on_key_press(event); -} -void ProController::keyboard_release(const QKeyEvent& event){ - m_keyboard_manager->on_key_release(event); -} - - - - - - - -} -} +/* Nintendo Switch Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "CommonTools/Async/InterruptableCommands.tpp" +#include "CommonTools/Async/SuperControlSession.tpp" +#include "Controllers/KeyboardInput/KeyboardInput.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + +// Instantiate some template helper classes. +template class AsyncCommandSession; +template class SuperControlSession; + +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + + + +class ProController::KeyboardManager final : + public PokemonAutomation::KeyboardManager +{ +public: + KeyboardManager(ProController& controller) + : PokemonAutomation::KeyboardManager(controller) + { + std::vector> mapping = + ConsoleSettings::instance().KEYBOARD_MAPPINGS.PRO_CONTROLLER.current_refs(); + for (const auto& deltas : mapping){ + const ProControllerKeyMapTableRow& row = static_cast(*deltas); + m_mapping[(Qt::Key)(uint32_t)row.key] += row.snapshot(); + } + start(); + } + ~KeyboardManager(){ + stop(); + } + virtual void send_state(const ControllerState& state) override{ + const ProControllerState& switch_state = static_cast(state); +#if 0 + m_controller.logger().log( + "VirtualController: (" + button_to_string(switch_state.buttons) + + "), dpad(" + dpad_to_string(switch_state.dpad) + + "), LJ(" + std::to_string(switch_state.left_x) + "," + std::to_string(switch_state.left_y) + + "), RJ(" + std::to_string(switch_state.right_x) + "," + std::to_string(switch_state.right_y) + + ")", + COLOR_DARKGREEN + ); +#endif + WriteSpinLock lg(m_lock); + if (m_controller == nullptr){ + return; + } + Milliseconds ticksize = m_controller->ticksize(); + static_cast(m_controller)->issue_full_controller_state( + nullptr, + ticksize == Milliseconds::zero() ? 2000ms : ticksize * 255, + switch_state.buttons, + switch_state.dpad, + switch_state.left_x, + switch_state.left_y, + switch_state.right_x, + switch_state.right_y + ); + } +}; + + + +ProController::ProController() + : m_keyboard_manager(CONSTRUCT_TOKEN, *this) +{ + +} +ProController::~ProController(){ + +} +void ProController::stop() noexcept{ + m_keyboard_manager->stop(); +} + + +void ProController::keyboard_release_all(){ + m_keyboard_manager->clear_state(); +} +void ProController::keyboard_press(const QKeyEvent& event){ + m_keyboard_manager->on_key_press(event); +} +void ProController::keyboard_release(const QKeyEvent& event){ + m_keyboard_manager->on_key_release(event); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h index 4f4a89eb57..16c6724d89 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_ProController.h @@ -1,233 +1,233 @@ -/* Nintendo Switch Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - * This is the raw (full) controller API that is exposed to programs. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Controller_H -#define PokemonAutomation_NintendoSwitch_Controller_H - -#include "Common/Cpp/Containers/Pimpl.h" -#include "NintendoSwitch_ControllerState.h" -#include "Controllers/Controller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class ProController; -using ProControllerContext = ControllerContext; - - -constexpr Button VALID_PRO_CONTROLLER_BUTTONS = - BUTTON_Y | - BUTTON_B | - BUTTON_A | - BUTTON_X | - BUTTON_L | - BUTTON_R | - BUTTON_ZL | - BUTTON_ZR | - BUTTON_MINUS | - BUTTON_PLUS | - BUTTON_LCLICK | - BUTTON_RCLICK | - BUTTON_HOME | - BUTTON_CAPTURE | - BUTTON_UP | - BUTTON_RIGHT | - BUTTON_DOWN | - BUTTON_LEFT; - - - -// -// This is the generic interface to a Switch pro controller. -// -class ProController : public AbstractController{ -public: - using ContextType = ProControllerContext; - - ProController(); - virtual ~ProController(); - - // Must call before destruction begins. - void stop() noexcept; - - -public: - // Standard Commands - - // Press all the buttons set in the bitfield simultaneously. - // This command will wait until all the selected buttons are ready to - // ensure that they are all dispatched simultaneously. - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) = 0; - - // Dpad - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) = 0; - - // Joysticks - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) = 0; - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) = 0; - - // Gyro: Accelerometer (experimental - API subject to change) - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) = 0; - - // - // Press all the following buttons/joysticks simultaneously for the - // specified duration. No wait is added at the end. Thus you can issue - // these back-to-back to simulate buttons being pressed and released - // concurrently with other buttons being held down the whole time. - // - // This command will wait until the controller is fully idle (including - // cooldowns) before it starts. This ensures that everything is issued - // simultaneously. In other words, there is an implied call to - // "issue_barrier()" before executing the state. - // - // The sole purpose of this function is for keyboard commands. - // For programs, it is easier to use the individual button/joystick - // functions above. - // - // If we need to support new Switch controller functionality - // (such as Joycon gyro or new stuff in Switch 2), we can simply add - // overloads to this and gate them behind features. - // - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds duration, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) = 0; - - -public: - // - // High speed Macros - // - // Be mindful when calling these mashing functions on a tick imprecise - // controller. You can guarantee that some (most) of them will be dropped. - // - // Even if you are on a tick-precise controller, it is not advised to call - // these if you are micromanaging with tick-level granularity. The exact - // timing characteristics and button selection is not specified and may be - // context and implementation-dependent. - // - - // Mash a button as quickly as possible. - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) = 0; - - // Alternate pressing "button0" and "button1" as quickly as possible. - // "button0" will always be pressed first. - // Both buttons will be pressed at least once. - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds dutation, - Button button0, Button button1 - ) = 0; - - // In situations where A, ZL, and RL all do the same thing, use all 3 of - // them to logically mash A much faster than is possible with just one - // button. - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) = 0; - - // - // Send a scroll command in the specified direction. - // - // This will use either the dpad or either joystick - whichever is - // available first in the pipeline. - // - // The intended use-case of this for fast scrolling in the system menu - // where all 3 buttons have the same effect and can be used at the same - // time. - // - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) = 0; - - -public: - // Keyboard Input - - virtual void keyboard_release_all() override; - virtual void keyboard_press(const QKeyEvent& event) override; - virtual void keyboard_release(const QKeyEvent& event) override; - - -private: - class KeyboardManager; - Pimpl m_keyboard_manager; -}; - - - - - - - - - -} -} -#endif +/* Nintendo Switch Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + * This is the raw (full) controller API that is exposed to programs. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Controller_H +#define PokemonAutomation_NintendoSwitch_Controller_H + +#include "Common/Cpp/Containers/Pimpl.h" +#include "NintendoSwitch_ControllerState.h" +#include "Controllers/Controller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class ProController; +using ProControllerContext = ControllerContext; + + +constexpr Button VALID_PRO_CONTROLLER_BUTTONS = + BUTTON_Y | + BUTTON_B | + BUTTON_A | + BUTTON_X | + BUTTON_L | + BUTTON_R | + BUTTON_ZL | + BUTTON_ZR | + BUTTON_MINUS | + BUTTON_PLUS | + BUTTON_LCLICK | + BUTTON_RCLICK | + BUTTON_HOME | + BUTTON_CAPTURE | + BUTTON_UP | + BUTTON_RIGHT | + BUTTON_DOWN | + BUTTON_LEFT; + + + +// +// This is the generic interface to a Switch pro controller. +// +class ProController : public AbstractController{ +public: + using ContextType = ProControllerContext; + + ProController(); + virtual ~ProController(); + + // Must call before destruction begins. + void stop() noexcept; + + +public: + // Standard Commands + + // Press all the buttons set in the bitfield simultaneously. + // This command will wait until all the selected buttons are ready to + // ensure that they are all dispatched simultaneously. + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) = 0; + + // Dpad + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) = 0; + + // Joysticks + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) = 0; + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) = 0; + + // Gyro: Accelerometer (experimental - API subject to change) + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) = 0; + + // + // Press all the following buttons/joysticks simultaneously for the + // specified duration. No wait is added at the end. Thus you can issue + // these back-to-back to simulate buttons being pressed and released + // concurrently with other buttons being held down the whole time. + // + // This command will wait until the controller is fully idle (including + // cooldowns) before it starts. This ensures that everything is issued + // simultaneously. In other words, there is an implied call to + // "issue_barrier()" before executing the state. + // + // The sole purpose of this function is for keyboard commands. + // For programs, it is easier to use the individual button/joystick + // functions above. + // + // If we need to support new Switch controller functionality + // (such as Joycon gyro or new stuff in Switch 2), we can simply add + // overloads to this and gate them behind features. + // + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds duration, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) = 0; + + +public: + // + // High speed Macros + // + // Be mindful when calling these mashing functions on a tick imprecise + // controller. You can guarantee that some (most) of them will be dropped. + // + // Even if you are on a tick-precise controller, it is not advised to call + // these if you are micromanaging with tick-level granularity. The exact + // timing characteristics and button selection is not specified and may be + // context and implementation-dependent. + // + + // Mash a button as quickly as possible. + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) = 0; + + // Alternate pressing "button0" and "button1" as quickly as possible. + // "button0" will always be pressed first. + // Both buttons will be pressed at least once. + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds dutation, + Button button0, Button button1 + ) = 0; + + // In situations where A, ZL, and RL all do the same thing, use all 3 of + // them to logically mash A much faster than is possible with just one + // button. + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) = 0; + + // + // Send a scroll command in the specified direction. + // + // This will use either the dpad or either joystick - whichever is + // available first in the pipeline. + // + // The intended use-case of this for fast scrolling in the system menu + // where all 3 buttons have the same effect and can be used at the same + // time. + // + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) = 0; + + +public: + // Keyboard Input + + virtual void keyboard_release_all() override; + virtual void keyboard_press(const QKeyEvent& event) override; + virtual void keyboard_release(const QKeyEvent& event) override; + + +private: + class KeyboardManager; + Pimpl m_keyboard_manager; +}; + + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp index 6a82c41331..2af3cb9758 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.cpp @@ -1,209 +1,209 @@ -/* Virtual Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch_VirtualControllerState.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - - -void ProControllerState::clear(){ - buttons = BUTTON_NONE; - dpad = DPAD_NONE; - left_x = 128; - left_y = 128; - right_x = 128; - right_y = 128; -} -bool ProControllerState::operator==(const ControllerState& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - - const ProControllerState& r = static_cast(x); - - if (buttons != r.buttons){ - return false; - } - if (dpad != r.dpad){ - return false; - } - if (left_x != r.left_x){ - return false; - } - if (left_y != r.left_y){ - return false; - } - if (right_x != r.right_x){ - return false; - } - if (right_y != r.right_y){ - return false; - } - return true; -} -bool ProControllerState::is_neutral() const{ - return buttons == 0 - && dpad == DPAD_NONE - && left_x == 128 - && left_y == 128 - && right_x == 128 - && right_y == 128; -} - - -void ProControllerDeltas::operator+=(const ProControllerDeltas& x){ - buttons |= x.buttons; - dpad_x += x.dpad_x; - dpad_y += x.dpad_y; - left_x += x.left_x; - left_y += x.left_y; - right_x += x.right_x; - right_y += x.right_y; -} -bool ProControllerDeltas::to_state(ProControllerState& state) const{ - bool neutral; - - state.buttons = buttons; - neutral = buttons == 0; - - state.dpad = DPAD_NONE; - if (dpad_x != 0 || dpad_y != 0){ - neutral = false; - do{ - if (dpad_x == 0){ - state.dpad = dpad_y > 0 ? DPAD_DOWN : DPAD_UP; - break; - } - if (dpad_y == 0){ - state.dpad = dpad_x > 0 ? DPAD_RIGHT : DPAD_LEFT; - break; - } - if (dpad_x < 0 && dpad_y < 0){ - state.dpad = DPAD_UP_LEFT; - break; - } - if (dpad_x < 0 && dpad_y > 0){ - state.dpad = DPAD_DOWN_LEFT; - break; - } - if (dpad_x > 0 && dpad_y > 0){ - state.dpad = DPAD_DOWN_RIGHT; - break; - } - if (dpad_x > 0 && dpad_y < 0){ - state.dpad = DPAD_UP_RIGHT; - break; - } - }while (false); - } - - state.left_x = 128; - state.left_y = 128; - if (left_x != 0 || left_y != 0){ - neutral = false; - int mag = std::abs(left_x) > std::abs(left_y) - ? std::abs(left_x) - : std::abs(left_y); - state.left_x = (uint8_t)std::min(128 * left_x / mag + 128, 255); - state.left_y = (uint8_t)std::min(128 * left_y / mag + 128, 255); - } - - state.right_x = 128; - state.right_y = 128; - if (right_x != 0 || right_y != 0){ - neutral = false; - int mag = std::abs(right_x) > std::abs(right_y) - ? std::abs(right_x) - : std::abs(right_y); - state.right_x = (uint8_t)std::min(128 * right_x / mag + 128, 255); - state.right_y = (uint8_t)std::min(128 * right_y / mag + 128, 255); - } - - return neutral; -} - - - - - - -void JoyconState::clear(){ - buttons = BUTTON_NONE; - joystick_x = 128; - joystick_y = 128; -} -bool JoyconState::operator==(const ControllerState& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - - const JoyconState& r = static_cast(x); - - if (buttons != r.buttons){ - return false; - } - if (joystick_x != r.joystick_x){ - return false; - } - if (joystick_y != r.joystick_y){ - return false; - } - return true; -} -bool JoyconState::is_neutral() const{ - return buttons == 0 - && joystick_x == 128 - && joystick_y == 128; -} - - -void JoyconDeltas::operator+=(const JoyconDeltas& x){ - buttons |= x.buttons; - joystick_x += x.joystick_x; - joystick_y += x.joystick_y; -} -bool JoyconDeltas::to_state(JoyconState& state) const{ - bool neutral; - - state.buttons = buttons; - neutral = buttons == 0; - - state.joystick_x = 128; - state.joystick_y = 128; - if (joystick_x != 0 || joystick_y != 0){ - neutral = false; - int mag = std::abs(joystick_x) > std::abs(joystick_y) - ? std::abs(joystick_x) - : std::abs(joystick_y); - state.joystick_x = (uint8_t)std::min(128 * joystick_x / mag + 128, 255); - state.joystick_y = (uint8_t)std::min(128 * joystick_y / mag + 128, 255); - } - - return neutral; -} - - - - - - - - - - - -} -} +/* Virtual Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch_VirtualControllerState.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + + +void ProControllerState::clear(){ + buttons = BUTTON_NONE; + dpad = DPAD_NONE; + left_x = 128; + left_y = 128; + right_x = 128; + right_y = 128; +} +bool ProControllerState::operator==(const ControllerState& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + + const ProControllerState& r = static_cast(x); + + if (buttons != r.buttons){ + return false; + } + if (dpad != r.dpad){ + return false; + } + if (left_x != r.left_x){ + return false; + } + if (left_y != r.left_y){ + return false; + } + if (right_x != r.right_x){ + return false; + } + if (right_y != r.right_y){ + return false; + } + return true; +} +bool ProControllerState::is_neutral() const{ + return buttons == 0 + && dpad == DPAD_NONE + && left_x == 128 + && left_y == 128 + && right_x == 128 + && right_y == 128; +} + + +void ProControllerDeltas::operator+=(const ProControllerDeltas& x){ + buttons |= x.buttons; + dpad_x += x.dpad_x; + dpad_y += x.dpad_y; + left_x += x.left_x; + left_y += x.left_y; + right_x += x.right_x; + right_y += x.right_y; +} +bool ProControllerDeltas::to_state(ProControllerState& state) const{ + bool neutral; + + state.buttons = buttons; + neutral = buttons == 0; + + state.dpad = DPAD_NONE; + if (dpad_x != 0 || dpad_y != 0){ + neutral = false; + do{ + if (dpad_x == 0){ + state.dpad = dpad_y > 0 ? DPAD_DOWN : DPAD_UP; + break; + } + if (dpad_y == 0){ + state.dpad = dpad_x > 0 ? DPAD_RIGHT : DPAD_LEFT; + break; + } + if (dpad_x < 0 && dpad_y < 0){ + state.dpad = DPAD_UP_LEFT; + break; + } + if (dpad_x < 0 && dpad_y > 0){ + state.dpad = DPAD_DOWN_LEFT; + break; + } + if (dpad_x > 0 && dpad_y > 0){ + state.dpad = DPAD_DOWN_RIGHT; + break; + } + if (dpad_x > 0 && dpad_y < 0){ + state.dpad = DPAD_UP_RIGHT; + break; + } + }while (false); + } + + state.left_x = 128; + state.left_y = 128; + if (left_x != 0 || left_y != 0){ + neutral = false; + int mag = std::abs(left_x) > std::abs(left_y) + ? std::abs(left_x) + : std::abs(left_y); + state.left_x = (uint8_t)std::min(128 * left_x / mag + 128, 255); + state.left_y = (uint8_t)std::min(128 * left_y / mag + 128, 255); + } + + state.right_x = 128; + state.right_y = 128; + if (right_x != 0 || right_y != 0){ + neutral = false; + int mag = std::abs(right_x) > std::abs(right_y) + ? std::abs(right_x) + : std::abs(right_y); + state.right_x = (uint8_t)std::min(128 * right_x / mag + 128, 255); + state.right_y = (uint8_t)std::min(128 * right_y / mag + 128, 255); + } + + return neutral; +} + + + + + + +void JoyconState::clear(){ + buttons = BUTTON_NONE; + joystick_x = 128; + joystick_y = 128; +} +bool JoyconState::operator==(const ControllerState& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + + const JoyconState& r = static_cast(x); + + if (buttons != r.buttons){ + return false; + } + if (joystick_x != r.joystick_x){ + return false; + } + if (joystick_y != r.joystick_y){ + return false; + } + return true; +} +bool JoyconState::is_neutral() const{ + return buttons == 0 + && joystick_x == 128 + && joystick_y == 128; +} + + +void JoyconDeltas::operator+=(const JoyconDeltas& x){ + buttons |= x.buttons; + joystick_x += x.joystick_x; + joystick_y += x.joystick_y; +} +bool JoyconDeltas::to_state(JoyconState& state) const{ + bool neutral; + + state.buttons = buttons; + neutral = buttons == 0; + + state.joystick_x = 128; + state.joystick_y = 128; + if (joystick_x != 0 || joystick_y != 0){ + neutral = false; + int mag = std::abs(joystick_x) > std::abs(joystick_y) + ? std::abs(joystick_x) + : std::abs(joystick_y); + state.joystick_x = (uint8_t)std::min(128 * joystick_x / mag + 128, 255); + state.joystick_y = (uint8_t)std::min(128 * joystick_y / mag + 128, 255); + } + + return neutral; +} + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h index 01b07f25a0..92358bb845 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h @@ -1,79 +1,79 @@ -/* Virtual Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_VirtualControllerState_H -#define PokemonAutomation_NintendoSwitch_VirtualControllerState_H - -#include "Controllers/KeyboardInput/KeyboardInput.h" -#include "NintendoSwitch_ControllerState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class ProControllerState : public ControllerState{ -public: - virtual void clear() override; - virtual bool operator==(const ControllerState& x) const override; - virtual bool is_neutral() const override; - -public: - Button buttons = BUTTON_NONE; - DpadPosition dpad = DPAD_NONE; - uint8_t left_x = 128; - uint8_t left_y = 128; - uint8_t right_x = 128; - uint8_t right_y = 128; -}; - -struct ProControllerDeltas{ - Button buttons = BUTTON_NONE; - int dpad_x = 0; - int dpad_y = 0; - int left_x = 0; - int left_y = 0; - int right_x = 0; - int right_y = 0; - - void operator+=(const ProControllerDeltas& x); - - // Returns true if neutral. - bool to_state(ProControllerState& state) const; -}; - - - -class JoyconState : public ControllerState{ -public: - virtual void clear() override; - virtual bool operator==(const ControllerState& x) const override; - virtual bool is_neutral() const override; - -public: - Button buttons = BUTTON_NONE; - uint8_t joystick_x = 128; - uint8_t joystick_y = 128; -}; - -struct JoyconDeltas{ - Button buttons = BUTTON_NONE; - int joystick_x = 0; - int joystick_y = 0; - - void operator+=(const JoyconDeltas& x); - - // Returns true if neutral. - bool to_state(JoyconState& state) const; -}; - - - - - - -} -} -#endif +/* Virtual Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_VirtualControllerState_H +#define PokemonAutomation_NintendoSwitch_VirtualControllerState_H + +#include "Controllers/KeyboardInput/KeyboardInput.h" +#include "NintendoSwitch_ControllerState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class ProControllerState : public ControllerState{ +public: + virtual void clear() override; + virtual bool operator==(const ControllerState& x) const override; + virtual bool is_neutral() const override; + +public: + Button buttons = BUTTON_NONE; + DpadPosition dpad = DPAD_NONE; + uint8_t left_x = 128; + uint8_t left_y = 128; + uint8_t right_x = 128; + uint8_t right_y = 128; +}; + +struct ProControllerDeltas{ + Button buttons = BUTTON_NONE; + int dpad_x = 0; + int dpad_y = 0; + int left_x = 0; + int left_y = 0; + int right_x = 0; + int right_y = 0; + + void operator+=(const ProControllerDeltas& x); + + // Returns true if neutral. + bool to_state(ProControllerState& state) const; +}; + + + +class JoyconState : public ControllerState{ +public: + virtual void clear() override; + virtual bool operator==(const ControllerState& x) const override; + virtual bool is_neutral() const override; + +public: + Button buttons = BUTTON_NONE; + uint8_t joystick_x = 128; + uint8_t joystick_y = 128; +}; + +struct JoyconDeltas{ + Button buttons = BUTTON_NONE; + int joystick_x = 0; + int joystick_y = 0; + + void operator+=(const JoyconDeltas& x); + + // Returns true if neutral. + bool to_state(JoyconState& state) const; +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp index 6dee96bfad..9e44ef6d34 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.cpp @@ -1,106 +1,106 @@ -/* SerialPABotBase: Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ClientSource/Connection/BotBaseMessage.h" -#include "Controllers/ControllerTypeStrings.h" -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - -SerialPABotBase_Controller::SerialPABotBase_Controller( - Logger& logger, - ControllerType controller_type, - SerialPABotBase::SerialPABotBase_Connection& connection -) - : ControllerWithScheduler(logger) - , m_handle(connection) - , m_serial(connection.botbase()) -{ - if (!connection.is_ready()){ - return; - } - - // Check compatibility. - - ControllerModeStatus mode_status = connection.controller_mode_status(); - logger.log( - "SerialPABotBase_Controller(): ControllerType = " + - CONTROLLER_TYPE_STRINGS.get_string(mode_status.current_controller) - ); - - std::map& controllers = mode_status.supported_controllers; - auto iter = controllers.find(controller_type); - if (iter != controllers.end()){ - m_supported_features = std::move(iter->second); - } -} - - - - -void SerialPABotBase_Controller::cancel_all_commands(){ - std::lock_guard lg(m_state_lock); - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - m_serial->stop_all_commands(); - this->clear_on_next(); -} -void SerialPABotBase_Controller::replace_on_next_command(){ - std::lock_guard lg(m_state_lock); - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - m_serial->next_command_interrupt(); - this->clear_on_next(); -} - - -void SerialPABotBase_Controller::wait_for_all(const Cancellable* cancellable){ - std::lock_guard lg0(m_issue_lock); - { - std::lock_guard lg1(m_state_lock); - - ThrottleScope scope(m_logging_throttler); - if (scope){ - m_logger.log("wait_for_all()", COLOR_DARKGREEN); - } - - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - - this->issue_wait_for_all(cancellable); - } - m_serial->wait_for_all_requests(cancellable); -} - - - - - - - - - - - - - -} -} +/* SerialPABotBase: Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ClientSource/Connection/BotBaseMessage.h" +#include "Controllers/ControllerTypeStrings.h" +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + +SerialPABotBase_Controller::SerialPABotBase_Controller( + Logger& logger, + ControllerType controller_type, + SerialPABotBase::SerialPABotBase_Connection& connection +) + : ControllerWithScheduler(logger) + , m_handle(connection) + , m_serial(connection.botbase()) +{ + if (!connection.is_ready()){ + return; + } + + // Check compatibility. + + ControllerModeStatus mode_status = connection.controller_mode_status(); + logger.log( + "SerialPABotBase_Controller(): ControllerType = " + + CONTROLLER_TYPE_STRINGS.get_string(mode_status.current_controller) + ); + + std::map& controllers = mode_status.supported_controllers; + auto iter = controllers.find(controller_type); + if (iter != controllers.end()){ + m_supported_features = std::move(iter->second); + } +} + + + + +void SerialPABotBase_Controller::cancel_all_commands(){ + std::lock_guard lg(m_state_lock); + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + m_serial->stop_all_commands(); + this->clear_on_next(); +} +void SerialPABotBase_Controller::replace_on_next_command(){ + std::lock_guard lg(m_state_lock); + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + m_serial->next_command_interrupt(); + this->clear_on_next(); +} + + +void SerialPABotBase_Controller::wait_for_all(const Cancellable* cancellable){ + std::lock_guard lg0(m_issue_lock); + { + std::lock_guard lg1(m_state_lock); + + ThrottleScope scope(m_logging_throttler); + if (scope){ + m_logger.log("wait_for_all()", COLOR_DARKGREEN); + } + + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + + this->issue_wait_for_all(cancellable); + } + m_serial->wait_for_all_requests(cancellable); +} + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h index 4e0d9d884d..953e73c3c2 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_Controller.h @@ -1,68 +1,68 @@ -/* SerialPABotBase: Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H - -#include "ClientSource/Connection/BotBase.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Connection.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_Controller : public ControllerWithScheduler{ -public: - SerialPABotBase_Controller( - Logger& logger, - ControllerType controller_type, - SerialPABotBase::SerialPABotBase_Connection& connection - ); - - void stop_with_error(std::string error_message){ - { - WriteSpinLock lg(m_error_lock); - m_error_string = error_message; - } - m_serial->stop(std::move(error_message)); - } - - bool is_ready() const{ - return m_serial - && m_serial->state() == BotBaseController::State::RUNNING - && m_handle.is_ready(); - } - std::string error_string() const{ - ReadSpinLock lg(m_error_lock); - return m_error_string; - } - - -public: - void cancel_all_commands(); - void replace_on_next_command(); - - void wait_for_all(const Cancellable* cancellable); - - -protected: - // These are set on construction and never changed again. So it is safe to - // access these asynchronously. - SerialPABotBase::SerialPABotBase_Connection& m_handle; - BotBaseController* m_serial; - ControllerFeatures m_supported_features; - - mutable SpinLock m_error_lock; - std::string m_error_string; -}; - - - - -} -} -#endif +/* SerialPABotBase: Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_Controller_H + +#include "ClientSource/Connection/BotBase.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Connection.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_Controller : public ControllerWithScheduler{ +public: + SerialPABotBase_Controller( + Logger& logger, + ControllerType controller_type, + SerialPABotBase::SerialPABotBase_Connection& connection + ); + + void stop_with_error(std::string error_message){ + { + WriteSpinLock lg(m_error_lock); + m_error_string = error_message; + } + m_serial->stop(std::move(error_message)); + } + + bool is_ready() const{ + return m_serial + && m_serial->state() == BotBaseController::State::RUNNING + && m_handle.is_ready(); + } + std::string error_string() const{ + ReadSpinLock lg(m_error_lock); + return m_error_string; + } + + +public: + void cancel_all_commands(); + void replace_on_next_command(); + + void wait_for_all(const Cancellable* cancellable); + + +protected: + // These are set on construction and never changed again. So it is safe to + // access these asynchronously. + SerialPABotBase::SerialPABotBase_Connection& m_handle; + BotBaseController* m_serial; + ControllerFeatures m_supported_features; + + mutable SpinLock m_error_lock; + std::string m_error_string; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp index 150012b7ab..417cd004f8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.cpp @@ -1,445 +1,445 @@ -/* SerialPABotBase: Pokken Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/ReverseLockGuard.h" -#include "Common/Cpp/Options/TimeExpressionOption.h" -#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h" -#include "NintendoSwitch_SerialPABotBase_PokkenController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - -SerialPABotBase_PokkenController::SerialPABotBase_PokkenController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection -) - : SerialPABotBase_Controller( - logger, - ControllerType::NintendoSwitch_WiredProController, - connection - ) - , m_use_milliseconds(m_supported_features.contains(ControllerFeature::TimingFlexibleMilliseconds)) - , m_stopping(false) - , m_status_thread(&SerialPABotBase_PokkenController::status_thread, this) -{} -SerialPABotBase_PokkenController::~SerialPABotBase_PokkenController(){ - stop(); - m_status_thread.join(); -} -void SerialPABotBase_PokkenController::stop(){ - if (m_stopping.exchange(true)){ - return; - } - ProController::stop(); - m_scope.cancel(nullptr); - { - std::unique_lock lg(m_sleep_lock); - if (m_serial){ - m_serial->notify_all(); - } - m_cv.notify_all(); - } -} - - - - - -void SerialPABotBase_PokkenController::push_state(const Cancellable* cancellable, WallDuration duration){ - // Must be called inside "m_state_lock". - - if (!is_ready()){ - throw InvalidConnectionStateException(error_string()); - } - - int dpad_x = 0; - int dpad_y = 0; - uint16_t buttons = 0; - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - if (!m_buttons[c].is_busy()){ - continue; - } - Button button = (Button)((ButtonFlagType)1 << c); - switch (button){ - case BUTTON_Y: buttons |= 1 << 0; break; - case BUTTON_B: buttons |= 1 << 1; break; - case BUTTON_A: buttons |= 1 << 2; break; - case BUTTON_X: buttons |= 1 << 3; break; - case BUTTON_L: buttons |= 1 << 4; break; - case BUTTON_R: buttons |= 1 << 5; break; - case BUTTON_ZL: buttons |= 1 << 6; break; - case BUTTON_ZR: buttons |= 1 << 7; break; - case BUTTON_MINUS: buttons |= 1 << 8; break; - case BUTTON_PLUS: buttons |= 1 << 9; break; - case BUTTON_LCLICK: buttons |= 1 << 10; break; - case BUTTON_RCLICK: buttons |= 1 << 11; break; - case BUTTON_HOME: buttons |= 1 << 12; break; - case BUTTON_CAPTURE: buttons |= 1 << 13; break; - case BUTTON_UP: dpad_y--; break; - case BUTTON_RIGHT: dpad_x++; break; - case BUTTON_DOWN: dpad_y++; break; - case BUTTON_LEFT: dpad_x--; break; - default:; - } - } - - - // Merge the dpad states. - DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; - { - switch (dpad){ - case DpadPosition::DPAD_UP: - dpad_y--; - break; - case DpadPosition::DPAD_UP_RIGHT: - dpad_x++; - dpad_y--; - break; - case DpadPosition::DPAD_RIGHT: - dpad_x++; - break; - case DpadPosition::DPAD_DOWN_RIGHT: - dpad_x++; - dpad_y++; - break; - case DpadPosition::DPAD_DOWN: - dpad_y++; - break; - case DpadPosition::DPAD_DOWN_LEFT: - dpad_x--; - dpad_y++; - break; - case DpadPosition::DPAD_LEFT: - dpad_x--; - break; - case DpadPosition::DPAD_UP_LEFT: - dpad_x--; - dpad_y--; - break; - default:; - } - - if (dpad_x < 0){ - if (dpad_y < 0){ - dpad = DpadPosition::DPAD_UP_LEFT; - }else if (dpad_y > 0){ - dpad = DpadPosition::DPAD_DOWN_LEFT; - }else{ - dpad = DpadPosition::DPAD_LEFT; - } - }else if (dpad_x > 0){ - if (dpad_y < 0){ - dpad = DpadPosition::DPAD_UP_RIGHT; - }else if (dpad_y > 0){ - dpad = DpadPosition::DPAD_DOWN_RIGHT; - }else{ - dpad = DpadPosition::DPAD_RIGHT; - } - }else{ - if (dpad_y < 0){ - dpad = DpadPosition::DPAD_UP; - }else if (dpad_y > 0){ - dpad = DpadPosition::DPAD_DOWN; - }else{ - dpad = DPAD_NONE; - } - } - } - - - - uint8_t left_x = 128; - uint8_t left_y = 128; - uint8_t right_x = 128; - uint8_t right_y = 128; - if (m_left_joystick.is_busy()){ - left_x = m_left_joystick.x; - left_y = m_left_joystick.y; - } - if (m_right_joystick.is_busy()){ - right_x = m_right_joystick.x; - right_y = m_right_joystick.y; - } - - - // Release the state lock since we are no longer touching state. - // This loop can block indefinitely if the command queue is full. - ReverseLockGuard lg(m_state_lock); - - // Divide the controller state into smaller chunks that fit into the report - // duration. - Milliseconds time_left = std::chrono::duration_cast(duration); - - if (m_use_milliseconds){ - while (time_left > Milliseconds::zero()){ - Milliseconds current = std::min(time_left, 65535ms); - m_serial->issue_request( - SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateMs( - (uint16_t)current.count(), - buttons, - dpad, - left_x, left_y, - right_x, right_y - ), - cancellable - ); - time_left -= current; - } - }else{ - while (time_left > Milliseconds::zero()){ - Milliseconds current_ms = std::min(time_left, 255 * 8ms); - uint8_t current_ticks = (uint8_t)milliseconds_to_ticks_8ms(current_ms.count()); - m_serial->issue_request( - SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateTicks( - buttons, - dpad, - left_x, left_y, - right_x, right_y, - current_ticks - ), - cancellable - ); - time_left -= current_ms; - } - } -} - - -// -// Given a regularly reported 32-bit counter that wraps around, infer its true -// 64-bit value. -// -class ExtendedLengthCounter{ -public: - ExtendedLengthCounter() - : m_high_bits(0) - , m_last_received(0) - {} - - uint64_t push_short_value(uint32_t counter){ - if (counter < m_last_received && counter - m_last_received < 0x40000000){ - m_high_bits++; - } - m_last_received = counter; - return ((uint64_t)m_high_bits << 32) | counter; - } - -private: - uint32_t m_high_bits; - uint32_t m_last_received; -}; - - -#if 0 -class TickRateTracker{ -public: - TickRateTracker(double expected_ticks_per_second) - : m_expected_ticks_per_second(expected_ticks_per_second) -// , m_history(10) - {} - - - double push_ticks(uint64_t ticks){ - WallClock now = current_time(); - -// if (m_history.full()){ -// m_history.pop_front(); -// } - - if (ticks <= m_last_ticks){ - m_last_push = WallClock::min(); - m_last_ticks = 0; - m_consecutive_off = 0; - } - - double ticks_per_second = 0; - - if (m_last_push != WallClock::min()){ - uint64_t elapsed_ticks = ticks - m_last_ticks; - double elapsed_seconds = std::chrono::duration_cast(now - m_last_push).count() * 0.000001; - ticks_per_second = elapsed_ticks / elapsed_seconds; -// m_history.push_back(ticks_per_second); - - double rate_error = std::abs(ticks_per_second - m_expected_ticks_per_second) / m_expected_ticks_per_second; - if (rate_error > 0.1){ - m_consecutive_off++; - }else{ - m_consecutive_off = 0; - } - - } - - m_last_push = now; - m_last_ticks = ticks; - - return ticks_per_second; - } - - size_t consecutive_off_readings() const{ - return m_consecutive_off; - } - - -private: - double m_expected_ticks_per_second; - WallClock m_last_push = WallClock::min(); - uint64_t m_last_ticks = 0; - - size_t m_consecutive_off = 0; - -// CircularBuffer m_history; -}; -#endif - - -void SerialPABotBase_PokkenController::status_thread(){ - constexpr std::chrono::milliseconds PERIOD(1000); - std::atomic last_ack(current_time()); - - std::thread watchdog([&, this]{ - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - auto last = current_time() - last_ack.load(std::memory_order_relaxed); - std::chrono::duration seconds = last; - if (last > 2 * PERIOD && is_ready()){ - std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; - m_handle.set_status_line1(text, COLOR_RED); -// m_logger.log("Connection issue detected. Turning on all logging..."); -// settings.log_everything.store(true, std::memory_order_release); - } - - std::unique_lock lg(m_sleep_lock); - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - }); - - - ExtendedLengthCounter clock_tracker; -// TickRateTracker tick_rate_tracker(m_use_milliseconds ? 1000 : TICKS_PER_SECOND); - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - std::string error; - try{ - pabb_MsgAckRequestI32 response; - m_serial->issue_request_and_wait( - SerialPABotBase::MessageControllerStatus(), - &m_scope - ).convert(m_logger, response); - last_ack.store(current_time(), std::memory_order_relaxed); - - uint32_t status = response.data; - bool status_connected = status & 1; - bool status_ready = status & 2; - - std::string str; - str += "Connected: " + (status_connected - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - str += " - Ready: " + (status_ready - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - - m_handle.set_status_line1(str); - - -#if 0 - pabb_MsgAckRequestI32 response; - m_serial->issue_request_and_wait( - SerialPABotBase::DeviceRequest_system_clock(), - &m_scope - ).convert(logger(), response); - last_ack.store(current_time(), std::memory_order_relaxed); - - uint64_t wallclock = clock_tracker.push_short_value(response.data); -// double ticks_per_second = tick_rate_tracker.push_ticks(wallclock); - m_handle.set_status_line1( - "Device Clock: " + tostr_u_commas(wallclock), - theme_friendly_darkblue() - ); -#endif - -// if (tick_rate_tracker.consecutive_off_readings() >= 10){ -// error = "Tick rate is erratic. Arduino/Teensy is not reliable on Switch 2."; -// } - - }catch (OperationCancelledException&){ - break; - }catch (InvalidConnectionStateException&){ - break; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - }catch (...){ - error = "Unknown error."; - } - if (!error.empty()){ - m_handle.set_status_line1(error, COLOR_RED); - stop_with_error(std::move(error)); - } - -// cout << "lock()" << endl; - std::unique_lock lg(m_sleep_lock); -// cout << "lock() - done" << endl; - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - - { - std::unique_lock lg(m_sleep_lock); - m_cv.notify_all(); - } - watchdog.join(); -} - - - - - - -} -} +/* SerialPABotBase: Pokken Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "Common/Cpp/Options/TimeExpressionOption.h" +#include "Common/SerialPABotBase/SerialPABotBase_Protocol_IDs.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_NS_Generic.h" +#include "NintendoSwitch_SerialPABotBase_PokkenController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + +SerialPABotBase_PokkenController::SerialPABotBase_PokkenController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection +) + : SerialPABotBase_Controller( + logger, + ControllerType::NintendoSwitch_WiredProController, + connection + ) + , m_use_milliseconds(m_supported_features.contains(ControllerFeature::TimingFlexibleMilliseconds)) + , m_stopping(false) + , m_status_thread(&SerialPABotBase_PokkenController::status_thread, this) +{} +SerialPABotBase_PokkenController::~SerialPABotBase_PokkenController(){ + stop(); + m_status_thread.join(); +} +void SerialPABotBase_PokkenController::stop(){ + if (m_stopping.exchange(true)){ + return; + } + ProController::stop(); + m_scope.cancel(nullptr); + { + std::unique_lock lg(m_sleep_lock); + if (m_serial){ + m_serial->notify_all(); + } + m_cv.notify_all(); + } +} + + + + + +void SerialPABotBase_PokkenController::push_state(const Cancellable* cancellable, WallDuration duration){ + // Must be called inside "m_state_lock". + + if (!is_ready()){ + throw InvalidConnectionStateException(error_string()); + } + + int dpad_x = 0; + int dpad_y = 0; + uint16_t buttons = 0; + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + if (!m_buttons[c].is_busy()){ + continue; + } + Button button = (Button)((ButtonFlagType)1 << c); + switch (button){ + case BUTTON_Y: buttons |= 1 << 0; break; + case BUTTON_B: buttons |= 1 << 1; break; + case BUTTON_A: buttons |= 1 << 2; break; + case BUTTON_X: buttons |= 1 << 3; break; + case BUTTON_L: buttons |= 1 << 4; break; + case BUTTON_R: buttons |= 1 << 5; break; + case BUTTON_ZL: buttons |= 1 << 6; break; + case BUTTON_ZR: buttons |= 1 << 7; break; + case BUTTON_MINUS: buttons |= 1 << 8; break; + case BUTTON_PLUS: buttons |= 1 << 9; break; + case BUTTON_LCLICK: buttons |= 1 << 10; break; + case BUTTON_RCLICK: buttons |= 1 << 11; break; + case BUTTON_HOME: buttons |= 1 << 12; break; + case BUTTON_CAPTURE: buttons |= 1 << 13; break; + case BUTTON_UP: dpad_y--; break; + case BUTTON_RIGHT: dpad_x++; break; + case BUTTON_DOWN: dpad_y++; break; + case BUTTON_LEFT: dpad_x--; break; + default:; + } + } + + + // Merge the dpad states. + DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; + { + switch (dpad){ + case DpadPosition::DPAD_UP: + dpad_y--; + break; + case DpadPosition::DPAD_UP_RIGHT: + dpad_x++; + dpad_y--; + break; + case DpadPosition::DPAD_RIGHT: + dpad_x++; + break; + case DpadPosition::DPAD_DOWN_RIGHT: + dpad_x++; + dpad_y++; + break; + case DpadPosition::DPAD_DOWN: + dpad_y++; + break; + case DpadPosition::DPAD_DOWN_LEFT: + dpad_x--; + dpad_y++; + break; + case DpadPosition::DPAD_LEFT: + dpad_x--; + break; + case DpadPosition::DPAD_UP_LEFT: + dpad_x--; + dpad_y--; + break; + default:; + } + + if (dpad_x < 0){ + if (dpad_y < 0){ + dpad = DpadPosition::DPAD_UP_LEFT; + }else if (dpad_y > 0){ + dpad = DpadPosition::DPAD_DOWN_LEFT; + }else{ + dpad = DpadPosition::DPAD_LEFT; + } + }else if (dpad_x > 0){ + if (dpad_y < 0){ + dpad = DpadPosition::DPAD_UP_RIGHT; + }else if (dpad_y > 0){ + dpad = DpadPosition::DPAD_DOWN_RIGHT; + }else{ + dpad = DpadPosition::DPAD_RIGHT; + } + }else{ + if (dpad_y < 0){ + dpad = DpadPosition::DPAD_UP; + }else if (dpad_y > 0){ + dpad = DpadPosition::DPAD_DOWN; + }else{ + dpad = DPAD_NONE; + } + } + } + + + + uint8_t left_x = 128; + uint8_t left_y = 128; + uint8_t right_x = 128; + uint8_t right_y = 128; + if (m_left_joystick.is_busy()){ + left_x = m_left_joystick.x; + left_y = m_left_joystick.y; + } + if (m_right_joystick.is_busy()){ + right_x = m_right_joystick.x; + right_y = m_right_joystick.y; + } + + + // Release the state lock since we are no longer touching state. + // This loop can block indefinitely if the command queue is full. + ReverseLockGuard lg(m_state_lock); + + // Divide the controller state into smaller chunks that fit into the report + // duration. + Milliseconds time_left = std::chrono::duration_cast(duration); + + if (m_use_milliseconds){ + while (time_left > Milliseconds::zero()){ + Milliseconds current = std::min(time_left, 65535ms); + m_serial->issue_request( + SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateMs( + (uint16_t)current.count(), + buttons, + dpad, + left_x, left_y, + right_x, right_y + ), + cancellable + ); + time_left -= current; + } + }else{ + while (time_left > Milliseconds::zero()){ + Milliseconds current_ms = std::min(time_left, 255 * 8ms); + uint8_t current_ticks = (uint8_t)milliseconds_to_ticks_8ms(current_ms.count()); + m_serial->issue_request( + SerialPABotBase::DeviceRequest_NS_Generic_ControllerStateTicks( + buttons, + dpad, + left_x, left_y, + right_x, right_y, + current_ticks + ), + cancellable + ); + time_left -= current_ms; + } + } +} + + +// +// Given a regularly reported 32-bit counter that wraps around, infer its true +// 64-bit value. +// +class ExtendedLengthCounter{ +public: + ExtendedLengthCounter() + : m_high_bits(0) + , m_last_received(0) + {} + + uint64_t push_short_value(uint32_t counter){ + if (counter < m_last_received && counter - m_last_received < 0x40000000){ + m_high_bits++; + } + m_last_received = counter; + return ((uint64_t)m_high_bits << 32) | counter; + } + +private: + uint32_t m_high_bits; + uint32_t m_last_received; +}; + + +#if 0 +class TickRateTracker{ +public: + TickRateTracker(double expected_ticks_per_second) + : m_expected_ticks_per_second(expected_ticks_per_second) +// , m_history(10) + {} + + + double push_ticks(uint64_t ticks){ + WallClock now = current_time(); + +// if (m_history.full()){ +// m_history.pop_front(); +// } + + if (ticks <= m_last_ticks){ + m_last_push = WallClock::min(); + m_last_ticks = 0; + m_consecutive_off = 0; + } + + double ticks_per_second = 0; + + if (m_last_push != WallClock::min()){ + uint64_t elapsed_ticks = ticks - m_last_ticks; + double elapsed_seconds = std::chrono::duration_cast(now - m_last_push).count() * 0.000001; + ticks_per_second = elapsed_ticks / elapsed_seconds; +// m_history.push_back(ticks_per_second); + + double rate_error = std::abs(ticks_per_second - m_expected_ticks_per_second) / m_expected_ticks_per_second; + if (rate_error > 0.1){ + m_consecutive_off++; + }else{ + m_consecutive_off = 0; + } + + } + + m_last_push = now; + m_last_ticks = ticks; + + return ticks_per_second; + } + + size_t consecutive_off_readings() const{ + return m_consecutive_off; + } + + +private: + double m_expected_ticks_per_second; + WallClock m_last_push = WallClock::min(); + uint64_t m_last_ticks = 0; + + size_t m_consecutive_off = 0; + +// CircularBuffer m_history; +}; +#endif + + +void SerialPABotBase_PokkenController::status_thread(){ + constexpr std::chrono::milliseconds PERIOD(1000); + std::atomic last_ack(current_time()); + + std::thread watchdog([&, this]{ + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + auto last = current_time() - last_ack.load(std::memory_order_relaxed); + std::chrono::duration seconds = last; + if (last > 2 * PERIOD && is_ready()){ + std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; + m_handle.set_status_line1(text, COLOR_RED); +// m_logger.log("Connection issue detected. Turning on all logging..."); +// settings.log_everything.store(true, std::memory_order_release); + } + + std::unique_lock lg(m_sleep_lock); + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + }); + + + ExtendedLengthCounter clock_tracker; +// TickRateTracker tick_rate_tracker(m_use_milliseconds ? 1000 : TICKS_PER_SECOND); + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + std::string error; + try{ + pabb_MsgAckRequestI32 response; + m_serial->issue_request_and_wait( + SerialPABotBase::MessageControllerStatus(), + &m_scope + ).convert(m_logger, response); + last_ack.store(current_time(), std::memory_order_relaxed); + + uint32_t status = response.data; + bool status_connected = status & 1; + bool status_ready = status & 2; + + std::string str; + str += "Connected: " + (status_connected + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + str += " - Ready: " + (status_ready + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + + m_handle.set_status_line1(str); + + +#if 0 + pabb_MsgAckRequestI32 response; + m_serial->issue_request_and_wait( + SerialPABotBase::DeviceRequest_system_clock(), + &m_scope + ).convert(logger(), response); + last_ack.store(current_time(), std::memory_order_relaxed); + + uint64_t wallclock = clock_tracker.push_short_value(response.data); +// double ticks_per_second = tick_rate_tracker.push_ticks(wallclock); + m_handle.set_status_line1( + "Device Clock: " + tostr_u_commas(wallclock), + theme_friendly_darkblue() + ); +#endif + +// if (tick_rate_tracker.consecutive_off_readings() >= 10){ +// error = "Tick rate is erratic. Arduino/Teensy is not reliable on Switch 2."; +// } + + }catch (OperationCancelledException&){ + break; + }catch (InvalidConnectionStateException&){ + break; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + }catch (...){ + error = "Unknown error."; + } + if (!error.empty()){ + m_handle.set_status_line1(error, COLOR_RED); + stop_with_error(std::move(error)); + } + +// cout << "lock()" << endl; + std::unique_lock lg(m_sleep_lock); +// cout << "lock() - done" << endl; + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + + { + std::unique_lock lg(m_sleep_lock); + m_cv.notify_all(); + } + watchdog.join(); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h index dd757acc0e..2191bfdcd0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h @@ -1,244 +1,244 @@ -/* SerialPABotBase: Pokken Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H - -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_PokkenController final : - public ProController, - public SerialPABotBase_Controller -{ -public: - using ContextType = ProControllerContext; - - -public: - SerialPABotBase_PokkenController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection - ); - ~SerialPABotBase_PokkenController(); - void stop(); - - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return SerialPABotBase_Controller::is_ready(); - } - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WiredProController; - } - virtual const ControllerFeatures& controller_features() const override{ - return m_supported_features; - } - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; - } - - virtual Milliseconds ticksize() const override{ - return m_use_milliseconds ? Milliseconds(0) : Milliseconds(8); - } - virtual Milliseconds cooldown() const override{ - return Milliseconds(8); - } - virtual Milliseconds timing_variation() const override{ - return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override{ - SerialPABotBase_Controller::cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - SerialPABotBase_Controller::replace_on_next_command(); - } - - virtual void wait_for_all(const Cancellable* cancellable) override{ - SerialPABotBase_Controller::wait_for_all(cancellable); - } - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - button &= VALID_PRO_CONTROLLER_BUTTONS; - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - button &= VALID_PRO_CONTROLLER_BUTTONS; - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - button0 &= VALID_PRO_CONTROLLER_BUTTONS; - button1 &= VALID_PRO_CONTROLLER_BUTTONS; - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -private: - template - PA_FORCE_INLINE Type milliseconds_to_ticks_8ms(Type milliseconds){ - return milliseconds / 8 + (milliseconds % 8 + 7) / 8; - } - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - void status_thread(); - - -private: - bool m_use_milliseconds; - CancellableHolder m_scope; - std::atomic m_stopping; - std::mutex m_sleep_lock; - std::condition_variable m_cv; - std::thread m_status_thread; -}; - - - - -} -} -#endif +/* SerialPABotBase: Pokken Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_PokkenController_H + +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_PokkenController final : + public ProController, + public SerialPABotBase_Controller +{ +public: + using ContextType = ProControllerContext; + + +public: + SerialPABotBase_PokkenController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection + ); + ~SerialPABotBase_PokkenController(); + void stop(); + + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return SerialPABotBase_Controller::is_ready(); + } + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WiredProController; + } + virtual const ControllerFeatures& controller_features() const override{ + return m_supported_features; + } + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + } + + virtual Milliseconds ticksize() const override{ + return m_use_milliseconds ? Milliseconds(0) : Milliseconds(8); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(8); + } + virtual Milliseconds timing_variation() const override{ + return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override{ + SerialPABotBase_Controller::cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + SerialPABotBase_Controller::replace_on_next_command(); + } + + virtual void wait_for_all(const Cancellable* cancellable) override{ + SerialPABotBase_Controller::wait_for_all(cancellable); + } + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + button &= VALID_PRO_CONTROLLER_BUTTONS; + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + button &= VALID_PRO_CONTROLLER_BUTTONS; + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + button0 &= VALID_PRO_CONTROLLER_BUTTONS; + button1 &= VALID_PRO_CONTROLLER_BUTTONS; + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + template + PA_FORCE_INLINE Type milliseconds_to_ticks_8ms(Type milliseconds){ + return milliseconds / 8 + (milliseconds % 8 + 7) / 8; + } + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + void status_thread(); + + +private: + bool m_use_milliseconds; + CancellableHolder m_scope; + std::atomic m_stopping; + std::mutex m_sleep_lock; + std::condition_variable m_cv; + std::thread m_status_thread; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp index c751318703..41787d2833 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.cpp @@ -1,405 +1,405 @@ -/* SerialPABotBase: Wireless Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/ReverseLockGuard.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" -#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_SerialPABotBase_WirelessController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - - - - - -SerialPABotBase_WirelessController::SerialPABotBase_WirelessController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type -) - : SerialPABotBase_Controller( - logger, - controller_type, - connection - ) - , m_controller_type(controller_type) - , m_timing_variation(ConsoleSettings::instance().TIMING_OPTIONS.WIRELESS_ESP32) - , m_stopping(false) - , m_status_thread(&SerialPABotBase_WirelessController::status_thread, this) -{} -SerialPABotBase_WirelessController::~SerialPABotBase_WirelessController(){ - stop(); - m_status_thread.join(); -} -void SerialPABotBase_WirelessController::stop(){ - if (m_stopping.exchange(true)){ - return; - } - m_scope.cancel(nullptr); - { - std::unique_lock lg(m_sleep_lock); - if (m_serial){ - m_serial->notify_all(); - } - m_cv.notify_all(); - } -} - - - - - -Button SerialPABotBase_WirelessController::populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons){ - // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md - - Button all_buttons = BUTTON_NONE; - for (size_t c = 0; c < TOTAL_BUTTONS; c++){ - if (!m_buttons[c].is_busy()){ - continue; - } - Button button = (Button)((ButtonFlagType)1 << c); - all_buttons |= button; - switch (button){ - // Right - case BUTTON_Y: buttons.button3 |= 1 << 0; break; - case BUTTON_X: buttons.button3 |= 1 << 1; break; - case BUTTON_B: buttons.button3 |= 1 << 2; break; - case BUTTON_A: buttons.button3 |= 1 << 3; break; - case BUTTON_RIGHT_SR: buttons.button3 |= 1 << 4; break; - case BUTTON_RIGHT_SL: buttons.button3 |= 1 << 5; break; - case BUTTON_R: buttons.button3 |= 1 << 6; break; - case BUTTON_ZR: buttons.button3 |= 1 << 7; break; - - // Shared - case BUTTON_MINUS: buttons.button4 |= 1 << 0; break; - case BUTTON_PLUS: buttons.button4 |= 1 << 1; break; - case BUTTON_RCLICK: buttons.button4 |= 1 << 2; break; - case BUTTON_LCLICK: buttons.button4 |= 1 << 3; break; - case BUTTON_HOME: buttons.button4 |= 1 << 4; break; - case BUTTON_CAPTURE: buttons.button4 |= 1 << 5; break; - - // Left - case BUTTON_DOWN: buttons.button5 |= 1 << 0; break; - case BUTTON_UP: buttons.button5 |= 1 << 1; break; - case BUTTON_RIGHT: buttons.button5 |= 1 << 2; break; - case BUTTON_LEFT: buttons.button5 |= 1 << 3; break; - case BUTTON_LEFT_SR: buttons.button5 |= 1 << 4; break; - case BUTTON_LEFT_SL: buttons.button5 |= 1 << 5; break; - case BUTTON_L: buttons.button5 |= 1 << 6; break; - case BUTTON_ZL: buttons.button5 |= 1 << 7; break; - - default:; - } - } - return all_buttons; -} -bool SerialPABotBase_WirelessController::populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro){ - bool gyro_active = false; - { - if (m_accel_x.is_busy()){ - gyro.accel_x = m_accel_x.value; - gyro_active = true; - } - if (m_accel_y.is_busy()){ - gyro.accel_y = m_accel_y.value; - gyro_active = true; - } - if (m_accel_z.is_busy()){ - gyro.accel_z = m_accel_z.value; - gyro_active = true; - } - if (m_rotation_x.is_busy()){ - gyro.rotation_x = m_rotation_x.value; - gyro_active = true; - } - if (m_rotation_y.is_busy()){ - gyro.rotation_y = m_rotation_y.value; - gyro_active = true; - } - if (m_rotation_z.is_busy()){ - gyro.rotation_z = m_rotation_z.value; - gyro_active = true; - } - } - return gyro_active; -} - - -void SerialPABotBase_WirelessController::issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons -){ - // Release the state lock since we are no longer touching state. - // This loop can block indefinitely if the command queue is full. - ReverseLockGuard lg(m_state_lock); - - // We will not do any throttling or timing adjustments here. We'll defer - // to the microcontroller to do that for us. - - // Divide the controller state into smaller chunks of 65535 milliseconds. - Milliseconds time_left = std::chrono::duration_cast(duration); - - while (time_left > Milliseconds::zero()){ - Milliseconds current = std::min(time_left, 65535ms); - m_serial->issue_request( - SerialPABotBase::MessageControllerStateButtons( - (uint16_t)current.count(), - buttons - ), - cancellable - ); - time_left -= current; - } -} -void SerialPABotBase_WirelessController::issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons, - const PABB_NintendoSwitch_GyroState& gyro -){ - // Release the state lock since we are no longer touching state. - // This loop can block indefinitely if the command queue is full. - ReverseLockGuard lg(m_state_lock); - - // TODO: For now we duplicate the gyro data to all 3 5ms segments. - PABB_NintendoSwitch_GyroStateX3 gyro3{ - gyro, gyro, gyro - }; - -#if 0 - // Purturb results to show the Switch that they are not stuck. - if (gyro3.time1.accel_x > 0){ - gyro3.time0.accel_x--; - gyro3.time2.accel_x--; - }else if (gyro3.time1.accel_x < 0){ - gyro3.time0.accel_x++; - gyro3.time2.accel_x++; - }else{ - gyro3.time0.accel_x--; - gyro3.time2.accel_x++; - } - if (gyro3.time1.accel_y > 0){ - gyro3.time0.accel_y--; - gyro3.time2.accel_y--; - }else if (gyro3.time1.accel_y < 0){ - gyro3.time0.accel_y++; - gyro3.time2.accel_y++; - }else{ - gyro3.time0.accel_y--; - gyro3.time2.accel_y++; - } - if (gyro3.time1.accel_z > 0){ - gyro3.time0.accel_z--; - gyro3.time2.accel_z--; - }else if (gyro3.time1.accel_z < 0){ - gyro3.time0.accel_z++; - gyro3.time2.accel_z++; - }else{ - gyro3.time0.accel_z--; - gyro3.time2.accel_z++; - } -#endif - - // We will not do any throttling or timing adjustments here. We'll defer - // to the microcontroller to do that for us. - - // Divide the controller state into smaller chunks of 65535 milliseconds. - Milliseconds time_left = std::chrono::duration_cast(duration); - - while (time_left > Milliseconds::zero()){ - Milliseconds current = std::min(time_left, 65535ms); - m_serial->issue_request( - SerialPABotBase::MessageControllerStateFull( - (uint16_t)current.count(), - buttons, gyro3 - ), - cancellable - ); - time_left -= current; - } -} - - - - -void SerialPABotBase_WirelessController::status_thread(){ - constexpr std::chrono::milliseconds PERIOD(1000); - std::atomic last_ack(current_time()); - - // Read controller colors. - std::string color_html; -#if 1 - try{ - m_logger.log("Reading Controller Colors..."); - - using ControllerColors = PABB_NintendoSwitch_ControllerColors; - - BotBaseMessage response = m_serial->issue_request_and_wait( - SerialPABotBase::MessageControllerReadSpi( - m_controller_type, - 0x00006050, sizeof(ControllerColors) - ), - &m_scope - ); - - ControllerColors colors{}; - if (response.body.size() == sizeof(seqnum_t) + sizeof(ControllerColors)){ - memcpy(&colors, response.body.data() + sizeof(seqnum_t), sizeof(ControllerColors)); - }else{ - m_logger.log( - "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), - COLOR_RED - ); - m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); - return; - } - m_logger.log("Reading Controller Colors... Done"); - - switch (m_controller_type){ - case ControllerType::NintendoSwitch_WirelessProController:{ - Color left(colors.left_grip[0], colors.left_grip[1], colors.left_grip[2]); - Color body(colors.body[0], colors.body[1], colors.body[2]); - Color right(colors.right_grip[0], colors.right_grip[1], colors.right_grip[2]); - color_html += html_color_text("⬤", left); - color_html += " " + html_color_text("⬤", body); - color_html += " " + html_color_text("⬤", right); - break; - } - case ControllerType::NintendoSwitch_LeftJoycon: - case ControllerType::NintendoSwitch_RightJoycon:{ - Color body(colors.body[0], colors.body[1], colors.body[2]); - color_html = html_color_text("⬤", body); - break; - } - default:; - } - - }catch (Exception& e){ - e.log(m_logger); - m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); - return; - } -#endif - - - std::thread watchdog([&, this]{ - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - auto last = current_time() - last_ack.load(std::memory_order_relaxed); - std::chrono::duration seconds = last; - if (last > 2 * PERIOD){ - std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; - m_handle.set_status_line1(text, COLOR_RED); -// m_logger.log("Connection issue detected. Turning on all logging..."); -// settings.log_everything.store(true, std::memory_order_release); - } - - std::unique_lock lg(m_sleep_lock); - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - }); - - WallClock next_ping = current_time(); - while (true){ - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - std::string error; - try{ - pabb_MsgAckRequestI32 response; - m_serial->issue_request_and_wait( - SerialPABotBase::MessageControllerStatus(), - &m_scope - ).convert(m_logger, response); - last_ack.store(current_time(), std::memory_order_relaxed); - - uint32_t status = response.data; - bool status_connected = status & 1; - bool status_ready = status & 2; - - std::string str; - str += "Connected: " + (status_connected - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - str += " - Ready: " + (status_ready - ? html_color_text("Yes", theme_friendly_darkblue()) - : html_color_text("No", COLOR_RED) - ); - str += " - " + color_html; - - m_handle.set_status_line1(str); - }catch (OperationCancelledException&){ - break; - }catch (InvalidConnectionStateException&){ - break; - }catch (SerialProtocolException& e){ - error = e.message(); - }catch (ConnectionException& e){ - error = e.message(); - }catch (...){ - error = "Unknown error."; - } - if (!error.empty()){ - stop(); - m_handle.set_status_line1(error, COLOR_RED); - break; - } - -// cout << "lock()" << endl; - std::unique_lock lg(m_sleep_lock); -// cout << "lock() - done" << endl; - if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ - break; - } - - WallClock now = current_time(); - next_ping += PERIOD; - if (now + PERIOD < next_ping){ - next_ping = now + PERIOD; - } - m_cv.wait_until(lg, next_ping); - } - - { - std::unique_lock lg(m_sleep_lock); - m_cv.notify_all(); - } - watchdog.join(); -} - - - - -} -} +/* SerialPABotBase: Wireless Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_Protocol.h" +#include "Controllers/SerialPABotBase/SerialPABotBase_Routines_ESP32.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_SerialPABotBase_WirelessController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + + + + + +SerialPABotBase_WirelessController::SerialPABotBase_WirelessController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type +) + : SerialPABotBase_Controller( + logger, + controller_type, + connection + ) + , m_controller_type(controller_type) + , m_timing_variation(ConsoleSettings::instance().TIMING_OPTIONS.WIRELESS_ESP32) + , m_stopping(false) + , m_status_thread(&SerialPABotBase_WirelessController::status_thread, this) +{} +SerialPABotBase_WirelessController::~SerialPABotBase_WirelessController(){ + stop(); + m_status_thread.join(); +} +void SerialPABotBase_WirelessController::stop(){ + if (m_stopping.exchange(true)){ + return; + } + m_scope.cancel(nullptr); + { + std::unique_lock lg(m_sleep_lock); + if (m_serial){ + m_serial->notify_all(); + } + m_cv.notify_all(); + } +} + + + + + +Button SerialPABotBase_WirelessController::populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons){ + // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md + + Button all_buttons = BUTTON_NONE; + for (size_t c = 0; c < TOTAL_BUTTONS; c++){ + if (!m_buttons[c].is_busy()){ + continue; + } + Button button = (Button)((ButtonFlagType)1 << c); + all_buttons |= button; + switch (button){ + // Right + case BUTTON_Y: buttons.button3 |= 1 << 0; break; + case BUTTON_X: buttons.button3 |= 1 << 1; break; + case BUTTON_B: buttons.button3 |= 1 << 2; break; + case BUTTON_A: buttons.button3 |= 1 << 3; break; + case BUTTON_RIGHT_SR: buttons.button3 |= 1 << 4; break; + case BUTTON_RIGHT_SL: buttons.button3 |= 1 << 5; break; + case BUTTON_R: buttons.button3 |= 1 << 6; break; + case BUTTON_ZR: buttons.button3 |= 1 << 7; break; + + // Shared + case BUTTON_MINUS: buttons.button4 |= 1 << 0; break; + case BUTTON_PLUS: buttons.button4 |= 1 << 1; break; + case BUTTON_RCLICK: buttons.button4 |= 1 << 2; break; + case BUTTON_LCLICK: buttons.button4 |= 1 << 3; break; + case BUTTON_HOME: buttons.button4 |= 1 << 4; break; + case BUTTON_CAPTURE: buttons.button4 |= 1 << 5; break; + + // Left + case BUTTON_DOWN: buttons.button5 |= 1 << 0; break; + case BUTTON_UP: buttons.button5 |= 1 << 1; break; + case BUTTON_RIGHT: buttons.button5 |= 1 << 2; break; + case BUTTON_LEFT: buttons.button5 |= 1 << 3; break; + case BUTTON_LEFT_SR: buttons.button5 |= 1 << 4; break; + case BUTTON_LEFT_SL: buttons.button5 |= 1 << 5; break; + case BUTTON_L: buttons.button5 |= 1 << 6; break; + case BUTTON_ZL: buttons.button5 |= 1 << 7; break; + + default:; + } + } + return all_buttons; +} +bool SerialPABotBase_WirelessController::populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro){ + bool gyro_active = false; + { + if (m_accel_x.is_busy()){ + gyro.accel_x = m_accel_x.value; + gyro_active = true; + } + if (m_accel_y.is_busy()){ + gyro.accel_y = m_accel_y.value; + gyro_active = true; + } + if (m_accel_z.is_busy()){ + gyro.accel_z = m_accel_z.value; + gyro_active = true; + } + if (m_rotation_x.is_busy()){ + gyro.rotation_x = m_rotation_x.value; + gyro_active = true; + } + if (m_rotation_y.is_busy()){ + gyro.rotation_y = m_rotation_y.value; + gyro_active = true; + } + if (m_rotation_z.is_busy()){ + gyro.rotation_z = m_rotation_z.value; + gyro_active = true; + } + } + return gyro_active; +} + + +void SerialPABotBase_WirelessController::issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons +){ + // Release the state lock since we are no longer touching state. + // This loop can block indefinitely if the command queue is full. + ReverseLockGuard lg(m_state_lock); + + // We will not do any throttling or timing adjustments here. We'll defer + // to the microcontroller to do that for us. + + // Divide the controller state into smaller chunks of 65535 milliseconds. + Milliseconds time_left = std::chrono::duration_cast(duration); + + while (time_left > Milliseconds::zero()){ + Milliseconds current = std::min(time_left, 65535ms); + m_serial->issue_request( + SerialPABotBase::MessageControllerStateButtons( + (uint16_t)current.count(), + buttons + ), + cancellable + ); + time_left -= current; + } +} +void SerialPABotBase_WirelessController::issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons, + const PABB_NintendoSwitch_GyroState& gyro +){ + // Release the state lock since we are no longer touching state. + // This loop can block indefinitely if the command queue is full. + ReverseLockGuard lg(m_state_lock); + + // TODO: For now we duplicate the gyro data to all 3 5ms segments. + PABB_NintendoSwitch_GyroStateX3 gyro3{ + gyro, gyro, gyro + }; + +#if 0 + // Purturb results to show the Switch that they are not stuck. + if (gyro3.time1.accel_x > 0){ + gyro3.time0.accel_x--; + gyro3.time2.accel_x--; + }else if (gyro3.time1.accel_x < 0){ + gyro3.time0.accel_x++; + gyro3.time2.accel_x++; + }else{ + gyro3.time0.accel_x--; + gyro3.time2.accel_x++; + } + if (gyro3.time1.accel_y > 0){ + gyro3.time0.accel_y--; + gyro3.time2.accel_y--; + }else if (gyro3.time1.accel_y < 0){ + gyro3.time0.accel_y++; + gyro3.time2.accel_y++; + }else{ + gyro3.time0.accel_y--; + gyro3.time2.accel_y++; + } + if (gyro3.time1.accel_z > 0){ + gyro3.time0.accel_z--; + gyro3.time2.accel_z--; + }else if (gyro3.time1.accel_z < 0){ + gyro3.time0.accel_z++; + gyro3.time2.accel_z++; + }else{ + gyro3.time0.accel_z--; + gyro3.time2.accel_z++; + } +#endif + + // We will not do any throttling or timing adjustments here. We'll defer + // to the microcontroller to do that for us. + + // Divide the controller state into smaller chunks of 65535 milliseconds. + Milliseconds time_left = std::chrono::duration_cast(duration); + + while (time_left > Milliseconds::zero()){ + Milliseconds current = std::min(time_left, 65535ms); + m_serial->issue_request( + SerialPABotBase::MessageControllerStateFull( + (uint16_t)current.count(), + buttons, gyro3 + ), + cancellable + ); + time_left -= current; + } +} + + + + +void SerialPABotBase_WirelessController::status_thread(){ + constexpr std::chrono::milliseconds PERIOD(1000); + std::atomic last_ack(current_time()); + + // Read controller colors. + std::string color_html; +#if 1 + try{ + m_logger.log("Reading Controller Colors..."); + + using ControllerColors = PABB_NintendoSwitch_ControllerColors; + + BotBaseMessage response = m_serial->issue_request_and_wait( + SerialPABotBase::MessageControllerReadSpi( + m_controller_type, + 0x00006050, sizeof(ControllerColors) + ), + &m_scope + ); + + ControllerColors colors{}; + if (response.body.size() == sizeof(seqnum_t) + sizeof(ControllerColors)){ + memcpy(&colors, response.body.data() + sizeof(seqnum_t), sizeof(ControllerColors)); + }else{ + m_logger.log( + "Invalid response size to PABB_MSG_ESP32_REQUEST_READ_SPI: body = " + std::to_string(response.body.size()), + COLOR_RED + ); + m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); + return; + } + m_logger.log("Reading Controller Colors... Done"); + + switch (m_controller_type){ + case ControllerType::NintendoSwitch_WirelessProController:{ + Color left(colors.left_grip[0], colors.left_grip[1], colors.left_grip[2]); + Color body(colors.body[0], colors.body[1], colors.body[2]); + Color right(colors.right_grip[0], colors.right_grip[1], colors.right_grip[2]); + color_html += html_color_text("⬤", left); + color_html += " " + html_color_text("⬤", body); + color_html += " " + html_color_text("⬤", right); + break; + } + case ControllerType::NintendoSwitch_LeftJoycon: + case ControllerType::NintendoSwitch_RightJoycon:{ + Color body(colors.body[0], colors.body[1], colors.body[2]); + color_html = html_color_text("⬤", body); + break; + } + default:; + } + + }catch (Exception& e){ + e.log(m_logger); + m_handle.set_status_line1("Error: See log for more information.", COLOR_RED); + return; + } +#endif + + + std::thread watchdog([&, this]{ + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + auto last = current_time() - last_ack.load(std::memory_order_relaxed); + std::chrono::duration seconds = last; + if (last > 2 * PERIOD){ + std::string text = "Last Ack: " + tostr_fixed(seconds.count(), 3) + " seconds ago"; + m_handle.set_status_line1(text, COLOR_RED); +// m_logger.log("Connection issue detected. Turning on all logging..."); +// settings.log_everything.store(true, std::memory_order_release); + } + + std::unique_lock lg(m_sleep_lock); + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + }); + + WallClock next_ping = current_time(); + while (true){ + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + std::string error; + try{ + pabb_MsgAckRequestI32 response; + m_serial->issue_request_and_wait( + SerialPABotBase::MessageControllerStatus(), + &m_scope + ).convert(m_logger, response); + last_ack.store(current_time(), std::memory_order_relaxed); + + uint32_t status = response.data; + bool status_connected = status & 1; + bool status_ready = status & 2; + + std::string str; + str += "Connected: " + (status_connected + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + str += " - Ready: " + (status_ready + ? html_color_text("Yes", theme_friendly_darkblue()) + : html_color_text("No", COLOR_RED) + ); + str += " - " + color_html; + + m_handle.set_status_line1(str); + }catch (OperationCancelledException&){ + break; + }catch (InvalidConnectionStateException&){ + break; + }catch (SerialProtocolException& e){ + error = e.message(); + }catch (ConnectionException& e){ + error = e.message(); + }catch (...){ + error = "Unknown error."; + } + if (!error.empty()){ + stop(); + m_handle.set_status_line1(error, COLOR_RED); + break; + } + +// cout << "lock()" << endl; + std::unique_lock lg(m_sleep_lock); +// cout << "lock() - done" << endl; + if (m_stopping.load(std::memory_order_relaxed) || !m_handle.is_ready()){ + break; + } + + WallClock now = current_time(); + next_ping += PERIOD; + if (now + PERIOD < next_ping){ + next_ping = now + PERIOD; + } + m_cv.wait_until(lg, next_ping); + } + + { + std::unique_lock lg(m_sleep_lock); + m_cv.notify_all(); + } + watchdog.join(); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h index 1cf6222c82..367d09a4ba 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessController.h @@ -1,143 +1,143 @@ -/* SerialPABotBase: Wireless Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H - -#include -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "Controllers/JoystickTools.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class SerialPABotBase_WirelessController : public SerialPABotBase_Controller{ -public: - SerialPABotBase_WirelessController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type - ); - ~SerialPABotBase_WirelessController(); - void stop(); - - -public: - Milliseconds ticksize() const{ - return Milliseconds(0); - } - Milliseconds cooldown() const{ - return Milliseconds(15); - } - Milliseconds timing_variation() const{ - return m_timing_variation; - } - - -protected: - template - void encode_joystick(uint8_t data[3], uint8_t x, uint8_t y){ - // 2048 is the neutral position. - // - // 1897 is the point where the joystick calibrator will register it as - // off-center. - // - // ~320 is where it reaches the maximum value. - // - // If we linearly interpolate between 1897 and 320, we seem to match - // the wired controller's behavior. - // - // I suspect the need to offset by 151 from 2048 -> 1897 is Nintendo's - // way to alleviate the joycon drift problem. - // - // The values 320 and 1897 are for the pro controller. Joycons are - // slightly different. - // - - double fx = JoystickTools::linear_u8_to_float(x); - double fy = -JoystickTools::linear_u8_to_float(y); -// cout << "fx = " << fx << ", fy = " << fy << endl; - double mag_squared = fx*fx + fy*fy; - - uint16_t wx, wy; - if (mag_squared == 0){ - wx = 2048; - wy = 2048; - }else if (mag_squared >= 1){ - JoystickTools::max_out_magnitude(fx, fy); - wx = JoystickTools::linear_float_to_u12(fx); - wy = JoystickTools::linear_float_to_u12(fy); - }else{ - constexpr double lo = 1 - min_threshold / 2048.; - constexpr double hi = 1 - max_threshold / 2048.; - - double true_mag = std::sqrt(mag_squared); - double report_mag = JoystickTools::project_to_range(true_mag, lo, hi); - double scale = report_mag / true_mag; - wx = JoystickTools::linear_float_to_u12(fx * scale); - wy = JoystickTools::linear_float_to_u12(fy * scale); - } - -// cout << "wx = " << wx << ", wy = " << wy << endl; -// wy = 2048; -// wx = 1874; -// wx = 320; - - data[0] = (uint8_t)wx; - data[1] = (uint8_t)(wx >> 8 | wy << 4); - data[2] = (uint8_t)(wy >> 4); - } - - Button populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons); - bool populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro); - - void issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons - ); - void issue_report( - const Cancellable* cancellable, - WallDuration duration, - const PABB_NintendoSwitch_ButtonState& buttons, - const PABB_NintendoSwitch_GyroState& gyro - ); - - -private: -#if 0 - template - PA_FORCE_INLINE Type milliseconds_to_ticks_15ms(Type milliseconds){ - return milliseconds / 15 + (milliseconds % 15 + 14) / 15; - } -#endif - - void status_thread(); - - -protected: - const ControllerType m_controller_type; - Milliseconds m_timing_variation; -private: - CancellableHolder m_scope; - std::atomic m_stopping; - std::mutex m_sleep_lock; - std::condition_variable m_cv; - std::thread m_status_thread; -}; - - - -} -} -#endif +/* SerialPABotBase: Wireless Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessController_H + +#include +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "Controllers/JoystickTools.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class SerialPABotBase_WirelessController : public SerialPABotBase_Controller{ +public: + SerialPABotBase_WirelessController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type + ); + ~SerialPABotBase_WirelessController(); + void stop(); + + +public: + Milliseconds ticksize() const{ + return Milliseconds(0); + } + Milliseconds cooldown() const{ + return Milliseconds(15); + } + Milliseconds timing_variation() const{ + return m_timing_variation; + } + + +protected: + template + void encode_joystick(uint8_t data[3], uint8_t x, uint8_t y){ + // 2048 is the neutral position. + // + // 1897 is the point where the joystick calibrator will register it as + // off-center. + // + // ~320 is where it reaches the maximum value. + // + // If we linearly interpolate between 1897 and 320, we seem to match + // the wired controller's behavior. + // + // I suspect the need to offset by 151 from 2048 -> 1897 is Nintendo's + // way to alleviate the joycon drift problem. + // + // The values 320 and 1897 are for the pro controller. Joycons are + // slightly different. + // + + double fx = JoystickTools::linear_u8_to_float(x); + double fy = -JoystickTools::linear_u8_to_float(y); +// cout << "fx = " << fx << ", fy = " << fy << endl; + double mag_squared = fx*fx + fy*fy; + + uint16_t wx, wy; + if (mag_squared == 0){ + wx = 2048; + wy = 2048; + }else if (mag_squared >= 1){ + JoystickTools::max_out_magnitude(fx, fy); + wx = JoystickTools::linear_float_to_u12(fx); + wy = JoystickTools::linear_float_to_u12(fy); + }else{ + constexpr double lo = 1 - min_threshold / 2048.; + constexpr double hi = 1 - max_threshold / 2048.; + + double true_mag = std::sqrt(mag_squared); + double report_mag = JoystickTools::project_to_range(true_mag, lo, hi); + double scale = report_mag / true_mag; + wx = JoystickTools::linear_float_to_u12(fx * scale); + wy = JoystickTools::linear_float_to_u12(fy * scale); + } + +// cout << "wx = " << wx << ", wy = " << wy << endl; +// wy = 2048; +// wx = 1874; +// wx = 320; + + data[0] = (uint8_t)wx; + data[1] = (uint8_t)(wx >> 8 | wy << 4); + data[2] = (uint8_t)(wy >> 4); + } + + Button populate_report_buttons(PABB_NintendoSwitch_ButtonState& buttons); + bool populate_report_gyro(PABB_NintendoSwitch_GyroState& gyro); + + void issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons + ); + void issue_report( + const Cancellable* cancellable, + WallDuration duration, + const PABB_NintendoSwitch_ButtonState& buttons, + const PABB_NintendoSwitch_GyroState& gyro + ); + + +private: +#if 0 + template + PA_FORCE_INLINE Type milliseconds_to_ticks_15ms(Type milliseconds){ + return milliseconds / 15 + (milliseconds % 15 + 14) / 15; + } +#endif + + void status_thread(); + + +protected: + const ControllerType m_controller_type; + Milliseconds m_timing_variation; +private: + CancellableHolder m_scope; + std::atomic m_stopping; + std::mutex m_sleep_lock; + std::condition_variable m_cv; + std::thread m_status_thread; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp index 87dde1734e..77574ddc9f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.cpp @@ -1,205 +1,205 @@ -/* SerialPABotBase: Wireless Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch_SerialPABotBase_WirelessJoycon.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SerialPABotBase_WirelessJoycon::SerialPABotBase_WirelessJoycon( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type -) - : JoyconController(controller_type) - , SerialPABotBase_WirelessController( - logger, - connection, - controller_type - ) - , m_controller_type(controller_type) -{ - switch (controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - m_valid_buttons = VALID_LEFT_JOYCON_BUTTONS; - break; - case ControllerType::NintendoSwitch_RightJoycon: - m_valid_buttons = VALID_RIGHT_JOYCON_BUTTONS; - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} -SerialPABotBase_WirelessJoycon::~SerialPABotBase_WirelessJoycon(){ - JoyconController::stop(); - SerialPABotBase_WirelessController::stop(); -} - - - -void SerialPABotBase_WirelessJoycon::issue_buttons( - const Cancellable* cancellable, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown -){ - button &= m_valid_buttons; - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - break; - case ControllerType::NintendoSwitch_RightJoycon: - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} -void SerialPABotBase_WirelessJoycon::issue_joystick( - const Cancellable* cancellable, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown -){ - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - break; - case ControllerType::NintendoSwitch_RightJoycon: - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} -void SerialPABotBase_WirelessJoycon::issue_full_controller_state( - const Cancellable* cancellable, - Button button, - uint8_t joystick_x, uint8_t joystick_y, - Milliseconds hold -){ - button &= m_valid_buttons; - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - DPAD_NONE, - joystick_x, joystick_y, - 0x80, 0x80 - ); - break; - case ControllerType::NintendoSwitch_RightJoycon: - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - DPAD_NONE, - 0x80, 0x80, - joystick_x, joystick_y - ); - break; - default:; - } -} - - - -void SerialPABotBase_WirelessJoycon::issue_mash_button( - const Cancellable* cancellable, - Button button, Milliseconds duration -){ - button &= m_valid_buttons; - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); -} - - - - -void SerialPABotBase_WirelessJoycon::push_state_left_joycon(const Cancellable* cancellable, WallDuration duration){ - PABB_NintendoSwitch_ButtonState buttons{ - .button3 = 0, - .button4 = 0, - .button5 = 0, - .left_joystick = {0x00, 0x08, 0x80}, - .right_joystick = {0x00, 0x08, 0x80}, - .vibrator = 0x00, - }; - - populate_report_buttons(buttons); - - // Left Stick - if (m_left_joystick.is_busy()){ - encode_joystick( - buttons.left_joystick, - m_left_joystick.x, m_left_joystick.y - ); - } - - PABB_NintendoSwitch_GyroState gyro{}; - bool gyro_active = populate_report_gyro(gyro); - - if (!gyro_active){ - issue_report(cancellable, duration, buttons); - }else{ - issue_report(cancellable, duration, buttons, gyro); - } -} -void SerialPABotBase_WirelessJoycon::push_state_right_joycon(const Cancellable* cancellable, WallDuration duration){ - PABB_NintendoSwitch_ButtonState buttons{ - .button3 = 0, - .button4 = 0, - .button5 = 0, - .left_joystick = {0x00, 0x08, 0x80}, - .right_joystick = {0x00, 0x08, 0x80}, - .vibrator = 0x00, - }; - - populate_report_buttons(buttons); - - // Right Stick - if (m_right_joystick.is_busy()){ - encode_joystick( - buttons.right_joystick, - m_right_joystick.x, m_right_joystick.y - ); - } - - PABB_NintendoSwitch_GyroState gyro{}; - bool gyro_active = populate_report_gyro(gyro); - - if (!gyro_active){ - issue_report(cancellable, duration, buttons); - }else{ - issue_report(cancellable, duration, buttons, gyro); - } -} -void SerialPABotBase_WirelessJoycon::push_state(const Cancellable* cancellable, WallDuration duration){ - switch (m_controller_type){ - case ControllerType::NintendoSwitch_LeftJoycon: - push_state_left_joycon(cancellable, duration); - break; - case ControllerType::NintendoSwitch_RightJoycon: - push_state_right_joycon(cancellable, duration); - break; - default: - throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); - } -} - - - - - -} -} +/* SerialPABotBase: Wireless Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch_SerialPABotBase_WirelessJoycon.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SerialPABotBase_WirelessJoycon::SerialPABotBase_WirelessJoycon( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type +) + : JoyconController(controller_type) + , SerialPABotBase_WirelessController( + logger, + connection, + controller_type + ) + , m_controller_type(controller_type) +{ + switch (controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + m_valid_buttons = VALID_LEFT_JOYCON_BUTTONS; + break; + case ControllerType::NintendoSwitch_RightJoycon: + m_valid_buttons = VALID_RIGHT_JOYCON_BUTTONS; + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} +SerialPABotBase_WirelessJoycon::~SerialPABotBase_WirelessJoycon(){ + JoyconController::stop(); + SerialPABotBase_WirelessController::stop(); +} + + + +void SerialPABotBase_WirelessJoycon::issue_buttons( + const Cancellable* cancellable, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown +){ + button &= m_valid_buttons; + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + break; + case ControllerType::NintendoSwitch_RightJoycon: + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} +void SerialPABotBase_WirelessJoycon::issue_joystick( + const Cancellable* cancellable, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown +){ + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + break; + case ControllerType::NintendoSwitch_RightJoycon: + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} +void SerialPABotBase_WirelessJoycon::issue_full_controller_state( + const Cancellable* cancellable, + Button button, + uint8_t joystick_x, uint8_t joystick_y, + Milliseconds hold +){ + button &= m_valid_buttons; + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + DPAD_NONE, + joystick_x, joystick_y, + 0x80, 0x80 + ); + break; + case ControllerType::NintendoSwitch_RightJoycon: + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + DPAD_NONE, + 0x80, 0x80, + joystick_x, joystick_y + ); + break; + default:; + } +} + + + +void SerialPABotBase_WirelessJoycon::issue_mash_button( + const Cancellable* cancellable, + Button button, Milliseconds duration +){ + button &= m_valid_buttons; + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); +} + + + + +void SerialPABotBase_WirelessJoycon::push_state_left_joycon(const Cancellable* cancellable, WallDuration duration){ + PABB_NintendoSwitch_ButtonState buttons{ + .button3 = 0, + .button4 = 0, + .button5 = 0, + .left_joystick = {0x00, 0x08, 0x80}, + .right_joystick = {0x00, 0x08, 0x80}, + .vibrator = 0x00, + }; + + populate_report_buttons(buttons); + + // Left Stick + if (m_left_joystick.is_busy()){ + encode_joystick( + buttons.left_joystick, + m_left_joystick.x, m_left_joystick.y + ); + } + + PABB_NintendoSwitch_GyroState gyro{}; + bool gyro_active = populate_report_gyro(gyro); + + if (!gyro_active){ + issue_report(cancellable, duration, buttons); + }else{ + issue_report(cancellable, duration, buttons, gyro); + } +} +void SerialPABotBase_WirelessJoycon::push_state_right_joycon(const Cancellable* cancellable, WallDuration duration){ + PABB_NintendoSwitch_ButtonState buttons{ + .button3 = 0, + .button4 = 0, + .button5 = 0, + .left_joystick = {0x00, 0x08, 0x80}, + .right_joystick = {0x00, 0x08, 0x80}, + .vibrator = 0x00, + }; + + populate_report_buttons(buttons); + + // Right Stick + if (m_right_joystick.is_busy()){ + encode_joystick( + buttons.right_joystick, + m_right_joystick.x, m_right_joystick.y + ); + } + + PABB_NintendoSwitch_GyroState gyro{}; + bool gyro_active = populate_report_gyro(gyro); + + if (!gyro_active){ + issue_report(cancellable, duration, buttons); + }else{ + issue_report(cancellable, duration, buttons, gyro); + } +} +void SerialPABotBase_WirelessJoycon::push_state(const Cancellable* cancellable, WallDuration duration){ + switch (m_controller_type){ + case ControllerType::NintendoSwitch_LeftJoycon: + push_state_left_joycon(cancellable, duration); + break; + case ControllerType::NintendoSwitch_RightJoycon: + push_state_right_joycon(cancellable, duration); + break; + default: + throw InternalProgramError(&m_logger, PA_CURRENT_FUNCTION, "Invalid joycon type."); + } +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h index ce0d7b268a..a6dba0d875 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessJoycon.h @@ -1,176 +1,176 @@ -/* SerialPABotBase: Wireless Joycon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" -#include "NintendoSwitch_SerialPABotBase_WirelessController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_WirelessJoycon final : - public JoyconController, - public SerialPABotBase_WirelessController -{ - static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; - static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 260; - -public: - SerialPABotBase_WirelessJoycon( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection, - ControllerType controller_type - ); - ~SerialPABotBase_WirelessJoycon(); - - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return SerialPABotBase_Controller::is_ready(); - } - - -public: - virtual ControllerType controller_type() const override{ - return m_controller_type; - } - virtual const ControllerFeatures& controller_features() const override{ - return m_supported_features; - } - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32; - } - - virtual Milliseconds ticksize() const override{ - return SerialPABotBase_WirelessController::ticksize(); - } - virtual Milliseconds cooldown() const override{ - return SerialPABotBase_WirelessController::cooldown(); - } - virtual Milliseconds timing_variation() const override{ - return SerialPABotBase_WirelessController::timing_variation(); - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override{ - SerialPABotBase_Controller::cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - SerialPABotBase_Controller::replace_on_next_command(); - } - - virtual void wait_for_all(const Cancellable* cancellable) override{ - SerialPABotBase_Controller::wait_for_all(cancellable); - } - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Button button, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) override; - virtual void issue_joystick( - const Cancellable* cancellable, - uint8_t x, uint8_t y, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown - ) override; - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Button button, - uint8_t joystick_x, uint8_t joystick_y, - Milliseconds hold - ) override; - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Button button, Milliseconds duration - ) override; - - -private: - void push_state_left_joycon(const Cancellable* cancellable, WallDuration duration); - void push_state_right_joycon(const Cancellable* cancellable, WallDuration duration); - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - ControllerType m_controller_type; - Button m_valid_buttons; -}; - - - -} -} -#endif +/* SerialPABotBase: Wireless Joycon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessJoycon_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" +#include "NintendoSwitch_SerialPABotBase_WirelessController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_WirelessJoycon final : + public JoyconController, + public SerialPABotBase_WirelessController +{ + static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; + static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 260; + +public: + SerialPABotBase_WirelessJoycon( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection, + ControllerType controller_type + ); + ~SerialPABotBase_WirelessJoycon(); + + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return SerialPABotBase_Controller::is_ready(); + } + + +public: + virtual ControllerType controller_type() const override{ + return m_controller_type; + } + virtual const ControllerFeatures& controller_features() const override{ + return m_supported_features; + } + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32; + } + + virtual Milliseconds ticksize() const override{ + return SerialPABotBase_WirelessController::ticksize(); + } + virtual Milliseconds cooldown() const override{ + return SerialPABotBase_WirelessController::cooldown(); + } + virtual Milliseconds timing_variation() const override{ + return SerialPABotBase_WirelessController::timing_variation(); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override{ + SerialPABotBase_Controller::cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + SerialPABotBase_Controller::replace_on_next_command(); + } + + virtual void wait_for_all(const Cancellable* cancellable) override{ + SerialPABotBase_Controller::wait_for_all(cancellable); + } + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Button button, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) override; + virtual void issue_joystick( + const Cancellable* cancellable, + uint8_t x, uint8_t y, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown + ) override; + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Button button, + uint8_t joystick_x, uint8_t joystick_y, + Milliseconds hold + ) override; + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Button button, Milliseconds duration + ) override; + + +private: + void push_state_left_joycon(const Cancellable* cancellable, WallDuration duration); + void push_state_right_joycon(const Cancellable* cancellable, WallDuration duration); + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + ControllerType m_controller_type; + Button m_valid_buttons; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp index d2efe44986..a541a3d403 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.cpp @@ -1,112 +1,112 @@ -/* SerialPABotBase: Wireless Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch_SerialPABotBase_WirelessProController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SerialPABotBase_WirelessProController::SerialPABotBase_WirelessProController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection -) - : SerialPABotBase_WirelessController( - logger, - connection, - ControllerType::NintendoSwitch_WirelessProController - ) -{} -SerialPABotBase_WirelessProController::~SerialPABotBase_WirelessProController(){ - ProController::stop(); - SerialPABotBase_WirelessController::stop(); -} - - -void SerialPABotBase_WirelessProController::push_state(const Cancellable* cancellable, WallDuration duration){ - // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md - - PABB_NintendoSwitch_ButtonState buttons{ - .button3 = 0, - .button4 = 0, - .button5 = 0, - .left_joystick = {0x00, 0x08, 0x80}, - .right_joystick = {0x00, 0x08, 0x80}, - .vibrator = 0x00, - }; - -// Button all_buttons = - populate_report_buttons(buttons); - - if (m_dpad.is_busy()){ - SplitDpad dpad = convert_unified_to_split_dpad(m_dpad.position); - buttons.button5 |= (dpad.down ? 1 : 0) << 0; - buttons.button5 |= (dpad.up ? 1 : 0) << 1; - buttons.button5 |= (dpad.right ? 1 : 0) << 2; - buttons.button5 |= (dpad.left ? 1 : 0) << 3; - } - - // Left Stick - if (m_left_joystick.is_busy()){ - encode_joystick( - buttons.left_joystick, - m_left_joystick.x, m_left_joystick.y - ); - } - - // Right Stick - if (m_right_joystick.is_busy()){ - encode_joystick( - buttons.right_joystick, - m_right_joystick.x, m_right_joystick.y - ); - } - - PABB_NintendoSwitch_GyroState gyro{ - 0x0000, - 0x0000, - 0x0000, - 0x0000, - 0x0000, - 0x0000, - }; - bool gyro_active = populate_report_gyro(gyro); - -// gyro_active = true; -// gyro.rotation_y = 0x00ff; -// gyro.rotation_z = 0x000f; - - if (!gyro_active){ - issue_report(cancellable, duration, buttons); - }else{ - issue_report(cancellable, duration, buttons, gyro); - } - -#if 0 - m_logger.log( - "push_state(): (" + button_to_string(all_buttons) + - "), dpad(" + dpad_to_string(m_dpad.position) + - "), LJ(" + std::to_string(m_left_joystick.x) + "," + std::to_string(m_left_joystick.y) + - "), RJ(" + std::to_string(m_right_joystick.x) + "," + std::to_string(m_right_joystick.y) + - "), hold = " + std::to_string(std::chrono::duration_cast(duration).count()) + "ms", - COLOR_DARKGREEN - ); -#endif -} - - - - - -} -} +/* SerialPABotBase: Wireless Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/SerialPABotBase/SerialPABotBase_Messages_ESP32.h" +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch_SerialPABotBase_WirelessProController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SerialPABotBase_WirelessProController::SerialPABotBase_WirelessProController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection +) + : SerialPABotBase_WirelessController( + logger, + connection, + ControllerType::NintendoSwitch_WirelessProController + ) +{} +SerialPABotBase_WirelessProController::~SerialPABotBase_WirelessProController(){ + ProController::stop(); + SerialPABotBase_WirelessController::stop(); +} + + +void SerialPABotBase_WirelessProController::push_state(const Cancellable* cancellable, WallDuration duration){ + // https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/bluetooth_hid_notes.md + + PABB_NintendoSwitch_ButtonState buttons{ + .button3 = 0, + .button4 = 0, + .button5 = 0, + .left_joystick = {0x00, 0x08, 0x80}, + .right_joystick = {0x00, 0x08, 0x80}, + .vibrator = 0x00, + }; + +// Button all_buttons = + populate_report_buttons(buttons); + + if (m_dpad.is_busy()){ + SplitDpad dpad = convert_unified_to_split_dpad(m_dpad.position); + buttons.button5 |= (dpad.down ? 1 : 0) << 0; + buttons.button5 |= (dpad.up ? 1 : 0) << 1; + buttons.button5 |= (dpad.right ? 1 : 0) << 2; + buttons.button5 |= (dpad.left ? 1 : 0) << 3; + } + + // Left Stick + if (m_left_joystick.is_busy()){ + encode_joystick( + buttons.left_joystick, + m_left_joystick.x, m_left_joystick.y + ); + } + + // Right Stick + if (m_right_joystick.is_busy()){ + encode_joystick( + buttons.right_joystick, + m_right_joystick.x, m_right_joystick.y + ); + } + + PABB_NintendoSwitch_GyroState gyro{ + 0x0000, + 0x0000, + 0x0000, + 0x0000, + 0x0000, + 0x0000, + }; + bool gyro_active = populate_report_gyro(gyro); + +// gyro_active = true; +// gyro.rotation_y = 0x00ff; +// gyro.rotation_z = 0x000f; + + if (!gyro_active){ + issue_report(cancellable, duration, buttons); + }else{ + issue_report(cancellable, duration, buttons, gyro); + } + +#if 0 + m_logger.log( + "push_state(): (" + button_to_string(all_buttons) + + "), dpad(" + dpad_to_string(m_dpad.position) + + "), LJ(" + std::to_string(m_left_joystick.x) + "," + std::to_string(m_left_joystick.y) + + "), RJ(" + std::to_string(m_right_joystick.x) + "," + std::to_string(m_right_joystick.y) + + "), hold = " + std::to_string(std::chrono::duration_cast(duration).count()) + "ms", + COLOR_DARKGREEN + ); +#endif +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h index 4f0e120b97..c09ec9808f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_WirelessProController.h @@ -1,222 +1,222 @@ -/* SerialPABotBase: Wireless Pro Controller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H -#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_SerialPABotBase_Controller.h" -#include "NintendoSwitch_SerialPABotBase_WirelessController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SerialPABotBase_WirelessProController final : - public ProController, - public SerialPABotBase_WirelessController -{ - static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; - static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 320; - -public: - SerialPABotBase_WirelessProController( - Logger& logger, - SerialPABotBase::SerialPABotBase_Connection& connection - ); - ~SerialPABotBase_WirelessProController(); - - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return SerialPABotBase_Controller::is_ready(); - } - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WirelessProController; - } - virtual const ControllerFeatures& controller_features() const override{ - return m_supported_features; - } - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32; - } - - virtual Milliseconds ticksize() const override{ - return SerialPABotBase_WirelessController::ticksize(); - } - virtual Milliseconds cooldown() const override{ - return SerialPABotBase_WirelessController::cooldown(); - } - virtual Milliseconds timing_variation() const override{ - return SerialPABotBase_WirelessController::timing_variation(); - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override{ - SerialPABotBase_Controller::cancel_all_commands(); - } - virtual void replace_on_next_command() override{ - SerialPABotBase_Controller::replace_on_next_command(); - } - - virtual void wait_for_all(const Cancellable* cancellable) override{ - SerialPABotBase_Controller::wait_for_all(cancellable); - } - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -private: - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; -}; - - - -} -} -#endif +/* SerialPABotBase: Wireless Pro Controller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H +#define PokemonAutomation_NintendoSwitch_SerialPABotBase_WirelessProController_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_SerialPABotBase_Controller.h" +#include "NintendoSwitch_SerialPABotBase_WirelessController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SerialPABotBase_WirelessProController final : + public ProController, + public SerialPABotBase_WirelessController +{ + static constexpr uint16_t JOYSTICK_MIN_THRESHOLD = 1874; + static constexpr uint16_t JOYSTICK_MAX_THRESHOLD = 320; + +public: + SerialPABotBase_WirelessProController( + Logger& logger, + SerialPABotBase::SerialPABotBase_Connection& connection + ); + ~SerialPABotBase_WirelessProController(); + + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return SerialPABotBase_Controller::is_ready(); + } + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WirelessProController; + } + virtual const ControllerFeatures& controller_features() const override{ + return m_supported_features; + } + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32; + } + + virtual Milliseconds ticksize() const override{ + return SerialPABotBase_WirelessController::ticksize(); + } + virtual Milliseconds cooldown() const override{ + return SerialPABotBase_WirelessController::cooldown(); + } + virtual Milliseconds timing_variation() const override{ + return SerialPABotBase_WirelessController::timing_variation(); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override{ + SerialPABotBase_Controller::cancel_all_commands(); + } + virtual void replace_on_next_command() override{ + SerialPABotBase_Controller::replace_on_next_command(); + } + + virtual void wait_for_all(const Cancellable* cancellable) override{ + SerialPABotBase_Controller::wait_for_all(cancellable); + } + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h index 5ad91e8461..e1e3502e07 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ControllerState.h @@ -1,76 +1,76 @@ -/* Controller State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Sysbotbase3_ControllerState_H -#define PokemonAutomation_Sysbotbase3_ControllerState_H - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -struct Sysbotbase3_ControllerState{ - uint64_t buttons = 0; - int16_t left_joystick_x = 0; - int16_t left_joystick_y = 0; - int16_t right_joystick_x = 0; - int16_t right_joystick_y = 0; - - bool is_neutral() const{ - return buttons == 0 - && left_joystick_x == 0 - && left_joystick_y == 0 - && right_joystick_x == 0 - && right_joystick_y == 0; - } - void clear(){ - buttons = 0; - left_joystick_x = 0; - left_joystick_y = 0; - right_joystick_x = 0; - right_joystick_y = 0; - } -}; - - - -struct Sysbotbase3_ControllerCommand{ - uint64_t seqnum; - uint64_t milliseconds; - Sysbotbase3_ControllerState state; - - void write_to_hex(char str[64]) const{ - const char HEX_DIGITS[] = "0123456789abcdef"; - const char* ptr = (const char*)this; - for (size_t c = 0; c < 64; c += 2){ - uint8_t hi = (uint8_t)ptr[0] >> 4; - uint8_t lo = (uint8_t)ptr[0] & 0x0f; - str[c + 0] = HEX_DIGITS[hi]; - str[c + 1] = HEX_DIGITS[lo]; - ptr++; - } - } - void parse_from_hex(const char str[64]){ - char* ptr = (char*)this; - for (size_t c = 0; c < 64; c += 2){ - char hi = str[c + 0]; - char lo = str[c + 1]; - hi = hi < 'a' ? hi - '0' : hi - 'a' + 10; - lo = lo < 'a' ? lo - '0' : lo - 'a' + 10; - ptr[0] = hi << 4 | lo; - ptr++; - } - } -}; - - - - -} -} -#endif +/* Controller State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Sysbotbase3_ControllerState_H +#define PokemonAutomation_Sysbotbase3_ControllerState_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +struct Sysbotbase3_ControllerState{ + uint64_t buttons = 0; + int16_t left_joystick_x = 0; + int16_t left_joystick_y = 0; + int16_t right_joystick_x = 0; + int16_t right_joystick_y = 0; + + bool is_neutral() const{ + return buttons == 0 + && left_joystick_x == 0 + && left_joystick_y == 0 + && right_joystick_x == 0 + && right_joystick_y == 0; + } + void clear(){ + buttons = 0; + left_joystick_x = 0; + left_joystick_y = 0; + right_joystick_x = 0; + right_joystick_y = 0; + } +}; + + + +struct Sysbotbase3_ControllerCommand{ + uint64_t seqnum; + uint64_t milliseconds; + Sysbotbase3_ControllerState state; + + void write_to_hex(char str[64]) const{ + const char HEX_DIGITS[] = "0123456789abcdef"; + const char* ptr = (const char*)this; + for (size_t c = 0; c < 64; c += 2){ + uint8_t hi = (uint8_t)ptr[0] >> 4; + uint8_t lo = (uint8_t)ptr[0] & 0x0f; + str[c + 0] = HEX_DIGITS[hi]; + str[c + 1] = HEX_DIGITS[lo]; + ptr++; + } + } + void parse_from_hex(const char str[64]){ + char* ptr = (char*)this; + for (size_t c = 0; c < 64; c += 2){ + char hi = str[c + 0]; + char lo = str[c + 1]; + hi = hi < 'a' ? hi - '0' : hi - 'a' + 10; + lo = lo < 'a' ? lo - '0' : lo - 'a' + 10; + ptr[0] = hi << 4 | lo; + ptr++; + } + } +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp index 73ad5d6c31..a0113d041d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.cpp @@ -1,260 +1,260 @@ -/* Nintendo Switch Pro Controller (SysbotBase 3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -//#include "Common/Cpp/Concurrency/ReverseLockGuard.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Controllers/JoystickTools.h" -#include "SysbotBase3_ControllerState.h" -#include "SysbotBase3_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -ProController_SysbotBase3::ProController_SysbotBase3( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection -) - : ControllerWithScheduler(logger) - , m_connection(connection) - , m_stopping(false) - , m_next_seqnum(1) - , m_next_expected_seqnum_ack(1) -{ - if (!connection.is_ready()){ - return; - } - connection.add_listener(*this); -} -ProController_SysbotBase3::~ProController_SysbotBase3(){ - m_connection.remove_listener(*this); -} - -const ControllerFeatures& ProController_SysbotBase3::controller_features() const{ - static const ControllerFeatures features{ - ControllerFeature::TickPrecise, - ControllerFeature::TimingFlexibleMilliseconds, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - }; - return features; -} - -void ProController_SysbotBase3::cancel_all_commands(){ - std::lock_guard lg(m_state_lock); - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - - uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; - m_next_expected_seqnum_ack = m_next_seqnum; - - m_connection.write_data("cqCancel\r\n"); - - this->clear_on_next(); - m_cv.notify_all(); - m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); -} -void ProController_SysbotBase3::replace_on_next_command(){ - std::lock_guard lg(m_state_lock); - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - - uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; - m_next_expected_seqnum_ack = m_next_seqnum; - - m_connection.write_data("cqReplaceOnNext\r\n"); - - this->clear_on_next(); - m_cv.notify_all(); - m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); -} -void ProController_SysbotBase3::wait_for_all(const Cancellable* cancellable){ - std::unique_lock lg(m_state_lock); - while (true){ - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - if (cancellable){ - cancellable->throw_if_cancelled(); - } - if (m_next_seqnum == m_next_expected_seqnum_ack){ - break; - } - m_cv.wait(lg); - } -} - - -void ProController_SysbotBase3::on_message(const std::string& message){ - const std::string TOKEN = "cqCommandFinished"; - auto pos = message.find(TOKEN); - if (pos == std::string::npos){ - return; - } - - const char* ptr = message.c_str(); - ptr += pos; - ptr += TOKEN.size(); - uint64_t parsed; - while (true){ - char ch = *ptr; - switch (ch){ - case '\0': - return; - case ' ': - case '\t': - ptr++; - continue; - } - parsed = std::atoll(ptr); - break; - } - - std::lock_guard lg(m_state_lock); - - if (GlobalSettings::instance().LOG_EVERYTHING){ - m_logger.log( - "Command Finished: " + std::to_string(parsed) + - " (queue size = " + std::to_string(m_next_seqnum - m_next_expected_seqnum_ack) + ")" - ); - } - - // Old ack - if (parsed < m_next_expected_seqnum_ack){ - m_logger.log( - "Received Old Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + - ", Actual = " + std::to_string(parsed), - COLOR_RED - ); - return; - } - - // Ack is ahead of what has been dispatched. - if (parsed >= m_next_seqnum){ - m_logger.log( - "Received Future Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + - ", Actual = " + std::to_string(parsed), - COLOR_RED - ); - return; - } - - m_next_expected_seqnum_ack = parsed + 1; - m_cv.notify_all(); -} - -void ProController_SysbotBase3::push_state(const Cancellable* cancellable, WallDuration duration){ - // Must be called inside "m_state_lock". - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - if (m_stopping){ - throw InvalidConnectionStateException(""); - } - - // Flags map to: https://github.com/switchbrew/libnx/blob/master/nx/include/switch/services/hid.h#L584 - uint64_t nx_button = 0; - if (m_buttons[ 0].is_busy()) nx_button |= (uint64_t)1 << 3; // Y - if (m_buttons[ 1].is_busy()) nx_button |= (uint64_t)1 << 1; // B - if (m_buttons[ 2].is_busy()) nx_button |= (uint64_t)1 << 0; // A - if (m_buttons[ 3].is_busy()) nx_button |= (uint64_t)1 << 2; // X - if (m_buttons[ 4].is_busy()) nx_button |= (uint64_t)1 << 6; // L - if (m_buttons[ 5].is_busy()) nx_button |= (uint64_t)1 << 7; // R - if (m_buttons[ 6].is_busy()) nx_button |= (uint64_t)1 << 8; // ZL - if (m_buttons[ 7].is_busy()) nx_button |= (uint64_t)1 << 9; // ZR - if (m_buttons[ 8].is_busy()) nx_button |= (uint64_t)1 << 11; // - - if (m_buttons[ 9].is_busy()) nx_button |= (uint64_t)1 << 10; // + - if (m_buttons[10].is_busy()) nx_button |= (uint64_t)1 << 4; // L-click - if (m_buttons[11].is_busy()) nx_button |= (uint64_t)1 << 5; // R-click - if (m_buttons[12].is_busy()) nx_button |= (uint64_t)1 << 18; // Home - if (m_buttons[13].is_busy()) nx_button |= (uint64_t)1 << 19; // Capture - if (m_buttons[14].is_busy()) nx_button |= (uint64_t)1 << 13; // Up - if (m_buttons[15].is_busy()) nx_button |= (uint64_t)1 << 14; // Right - if (m_buttons[16].is_busy()) nx_button |= (uint64_t)1 << 15; // Down - if (m_buttons[17].is_busy()) nx_button |= (uint64_t)1 << 12; // Left -#if 0 // Don't exist on pro controller. - if (m_buttons[18].is_busy()) nx_button |= (uint64_t)1 << 24; // Left SL - if (m_buttons[19].is_busy()) nx_button |= (uint64_t)1 << 25; // Left SR - if (m_buttons[20].is_busy()) nx_button |= (uint64_t)1 << 26; // Right SL - if (m_buttons[21].is_busy()) nx_button |= (uint64_t)1 << 27; // Right SR -#endif - - { - DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; - SplitDpad split_dpad = convert_unified_to_split_dpad(dpad); - if (split_dpad.up) nx_button |= (uint64_t)1 << 13; - if (split_dpad.right) nx_button |= (uint64_t)1 << 14; - if (split_dpad.down) nx_button |= (uint64_t)1 << 15; - if (split_dpad.left) nx_button |= (uint64_t)1 << 12; - } - - int16_t left_x = 0; - int16_t left_y = 0; - int16_t right_x = 0; - int16_t right_y = 0; - if (m_left_joystick.is_busy()){ - double fx = JoystickTools::linear_u8_to_float(m_left_joystick.x); - double fy = -JoystickTools::linear_u8_to_float(m_left_joystick.y); - left_x = JoystickTools::linear_float_to_s16(fx); - left_y = JoystickTools::linear_float_to_s16(fy); - } - if (m_right_joystick.is_busy()){ - double fx = JoystickTools::linear_u8_to_float(m_right_joystick.x); - double fy = -JoystickTools::linear_u8_to_float(m_right_joystick.y); - right_x = JoystickTools::linear_float_to_s16(fx); - right_y = JoystickTools::linear_float_to_s16(fy); - } - - std::unique_lock lg(m_state_lock, std::adopt_lock_t()); - - // Wait until there is space. - m_cv.wait(lg, [this, cancellable]{ - if (cancellable && cancellable->cancelled()){ - return true; - } - return m_stopping || m_next_seqnum - m_next_expected_seqnum_ack < QUEUE_SIZE; - }); - - lg.release(); - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - Sysbotbase3_ControllerCommand command; - command.milliseconds = std::chrono::duration_cast(duration).count(); - command.seqnum = m_next_seqnum++; - command.state.buttons = nx_button; - command.state.left_joystick_x = left_x; - command.state.left_joystick_y = left_y; - command.state.right_joystick_x = right_x; - command.state.right_joystick_y = right_y; - - std::string message; - message.resize(64); - command.write_to_hex(message.data()); - message = "cqControllerState " + message + "\r\n"; - - m_connection.write_data(message); - - if (GlobalSettings::instance().LOG_EVERYTHING){ - m_logger.log("sys-botbase3: " + message); - } -} - - - - - - - -} -} +/* Nintendo Switch Pro Controller (SysbotBase 3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +//#include "Common/Cpp/Concurrency/ReverseLockGuard.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Controllers/JoystickTools.h" +#include "SysbotBase3_ControllerState.h" +#include "SysbotBase3_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +ProController_SysbotBase3::ProController_SysbotBase3( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection +) + : ControllerWithScheduler(logger) + , m_connection(connection) + , m_stopping(false) + , m_next_seqnum(1) + , m_next_expected_seqnum_ack(1) +{ + if (!connection.is_ready()){ + return; + } + connection.add_listener(*this); +} +ProController_SysbotBase3::~ProController_SysbotBase3(){ + m_connection.remove_listener(*this); +} + +const ControllerFeatures& ProController_SysbotBase3::controller_features() const{ + static const ControllerFeatures features{ + ControllerFeature::TickPrecise, + ControllerFeature::TimingFlexibleMilliseconds, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + }; + return features; +} + +void ProController_SysbotBase3::cancel_all_commands(){ + std::lock_guard lg(m_state_lock); + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + + uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; + m_next_expected_seqnum_ack = m_next_seqnum; + + m_connection.write_data("cqCancel\r\n"); + + this->clear_on_next(); + m_cv.notify_all(); + m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); +} +void ProController_SysbotBase3::replace_on_next_command(){ + std::lock_guard lg(m_state_lock); + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + + uint64_t queued = m_next_seqnum - m_next_expected_seqnum_ack; + m_next_expected_seqnum_ack = m_next_seqnum; + + m_connection.write_data("cqReplaceOnNext\r\n"); + + this->clear_on_next(); + m_cv.notify_all(); + m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(queued), COLOR_DARKGREEN); +} +void ProController_SysbotBase3::wait_for_all(const Cancellable* cancellable){ + std::unique_lock lg(m_state_lock); + while (true){ + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + if (cancellable){ + cancellable->throw_if_cancelled(); + } + if (m_next_seqnum == m_next_expected_seqnum_ack){ + break; + } + m_cv.wait(lg); + } +} + + +void ProController_SysbotBase3::on_message(const std::string& message){ + const std::string TOKEN = "cqCommandFinished"; + auto pos = message.find(TOKEN); + if (pos == std::string::npos){ + return; + } + + const char* ptr = message.c_str(); + ptr += pos; + ptr += TOKEN.size(); + uint64_t parsed; + while (true){ + char ch = *ptr; + switch (ch){ + case '\0': + return; + case ' ': + case '\t': + ptr++; + continue; + } + parsed = std::atoll(ptr); + break; + } + + std::lock_guard lg(m_state_lock); + + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log( + "Command Finished: " + std::to_string(parsed) + + " (queue size = " + std::to_string(m_next_seqnum - m_next_expected_seqnum_ack) + ")" + ); + } + + // Old ack + if (parsed < m_next_expected_seqnum_ack){ + m_logger.log( + "Received Old Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + + ", Actual = " + std::to_string(parsed), + COLOR_RED + ); + return; + } + + // Ack is ahead of what has been dispatched. + if (parsed >= m_next_seqnum){ + m_logger.log( + "Received Future Ack: Expected = " + std::to_string(m_next_expected_seqnum_ack) + + ", Actual = " + std::to_string(parsed), + COLOR_RED + ); + return; + } + + m_next_expected_seqnum_ack = parsed + 1; + m_cv.notify_all(); +} + +void ProController_SysbotBase3::push_state(const Cancellable* cancellable, WallDuration duration){ + // Must be called inside "m_state_lock". + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + if (m_stopping){ + throw InvalidConnectionStateException(""); + } + + // Flags map to: https://github.com/switchbrew/libnx/blob/master/nx/include/switch/services/hid.h#L584 + uint64_t nx_button = 0; + if (m_buttons[ 0].is_busy()) nx_button |= (uint64_t)1 << 3; // Y + if (m_buttons[ 1].is_busy()) nx_button |= (uint64_t)1 << 1; // B + if (m_buttons[ 2].is_busy()) nx_button |= (uint64_t)1 << 0; // A + if (m_buttons[ 3].is_busy()) nx_button |= (uint64_t)1 << 2; // X + if (m_buttons[ 4].is_busy()) nx_button |= (uint64_t)1 << 6; // L + if (m_buttons[ 5].is_busy()) nx_button |= (uint64_t)1 << 7; // R + if (m_buttons[ 6].is_busy()) nx_button |= (uint64_t)1 << 8; // ZL + if (m_buttons[ 7].is_busy()) nx_button |= (uint64_t)1 << 9; // ZR + if (m_buttons[ 8].is_busy()) nx_button |= (uint64_t)1 << 11; // - + if (m_buttons[ 9].is_busy()) nx_button |= (uint64_t)1 << 10; // + + if (m_buttons[10].is_busy()) nx_button |= (uint64_t)1 << 4; // L-click + if (m_buttons[11].is_busy()) nx_button |= (uint64_t)1 << 5; // R-click + if (m_buttons[12].is_busy()) nx_button |= (uint64_t)1 << 18; // Home + if (m_buttons[13].is_busy()) nx_button |= (uint64_t)1 << 19; // Capture + if (m_buttons[14].is_busy()) nx_button |= (uint64_t)1 << 13; // Up + if (m_buttons[15].is_busy()) nx_button |= (uint64_t)1 << 14; // Right + if (m_buttons[16].is_busy()) nx_button |= (uint64_t)1 << 15; // Down + if (m_buttons[17].is_busy()) nx_button |= (uint64_t)1 << 12; // Left +#if 0 // Don't exist on pro controller. + if (m_buttons[18].is_busy()) nx_button |= (uint64_t)1 << 24; // Left SL + if (m_buttons[19].is_busy()) nx_button |= (uint64_t)1 << 25; // Left SR + if (m_buttons[20].is_busy()) nx_button |= (uint64_t)1 << 26; // Right SL + if (m_buttons[21].is_busy()) nx_button |= (uint64_t)1 << 27; // Right SR +#endif + + { + DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; + SplitDpad split_dpad = convert_unified_to_split_dpad(dpad); + if (split_dpad.up) nx_button |= (uint64_t)1 << 13; + if (split_dpad.right) nx_button |= (uint64_t)1 << 14; + if (split_dpad.down) nx_button |= (uint64_t)1 << 15; + if (split_dpad.left) nx_button |= (uint64_t)1 << 12; + } + + int16_t left_x = 0; + int16_t left_y = 0; + int16_t right_x = 0; + int16_t right_y = 0; + if (m_left_joystick.is_busy()){ + double fx = JoystickTools::linear_u8_to_float(m_left_joystick.x); + double fy = -JoystickTools::linear_u8_to_float(m_left_joystick.y); + left_x = JoystickTools::linear_float_to_s16(fx); + left_y = JoystickTools::linear_float_to_s16(fy); + } + if (m_right_joystick.is_busy()){ + double fx = JoystickTools::linear_u8_to_float(m_right_joystick.x); + double fy = -JoystickTools::linear_u8_to_float(m_right_joystick.y); + right_x = JoystickTools::linear_float_to_s16(fx); + right_y = JoystickTools::linear_float_to_s16(fy); + } + + std::unique_lock lg(m_state_lock, std::adopt_lock_t()); + + // Wait until there is space. + m_cv.wait(lg, [this, cancellable]{ + if (cancellable && cancellable->cancelled()){ + return true; + } + return m_stopping || m_next_seqnum - m_next_expected_seqnum_ack < QUEUE_SIZE; + }); + + lg.release(); + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + Sysbotbase3_ControllerCommand command; + command.milliseconds = std::chrono::duration_cast(duration).count(); + command.seqnum = m_next_seqnum++; + command.state.buttons = nx_button; + command.state.left_joystick_x = left_x; + command.state.left_joystick_y = left_y; + command.state.right_joystick_x = right_x; + command.state.right_joystick_y = right_y; + + std::string message; + message.resize(64); + command.write_to_hex(message.data()); + message = "cqControllerState " + message + "\r\n"; + + m_connection.write_data(message); + + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("sys-botbase3: " + message); + } +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h index 55d1fd1961..25f1f12b4c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase3_ProController.h @@ -1,240 +1,240 @@ -/* Nintendo Switch Pro Controller (SysbotBase 3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H -#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H - -#include "NintendoSwitch/NintendoSwitch_Settings.h" -//#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" -#include "SysbotBase_Connection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class ProController_SysbotBase3 final : - public ProController, - public ControllerWithScheduler, - private SysbotBase::TcpSysbotBase_Connection::Listener -{ -public: - using ContextType = ProControllerContext; - - static constexpr size_t QUEUE_SIZE = 256; - - -public: - ProController_SysbotBase3( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection - ); - ~ProController_SysbotBase3(); - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WiredProController; - } - virtual const ControllerFeatures& controller_features() const override; - virtual ControllerPerformanceClass performance_class() const override{ - // TODO: Change to SerialPABotBase_Wired_125Hz when we prove it is stable. - return ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; -// return ControllerPerformanceClass::SysbotBase; - } - - virtual Milliseconds ticksize() const override{ - return Milliseconds::zero(); - } - virtual Milliseconds cooldown() const override{ - return Milliseconds(8); - } - virtual Milliseconds timing_variation() const override{ - // TODO: Verify it is actually this stable. - return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; -// return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; -// return Milliseconds(8); - } - virtual bool atomic_multibutton() const override{ - return true; - } - - -public: - virtual void cancel_all_commands() override; - virtual void replace_on_next_command() override; - - virtual void wait_for_all(const Cancellable* cancellable) override; - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -public: - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return m_connection.is_ready(); - } - - -private: - virtual void on_message(const std::string& message) override; - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - -private: - SysbotBase::TcpSysbotBase_Connection& m_connection; - - bool m_stopping; - uint64_t m_next_seqnum; - uint64_t m_next_expected_seqnum_ack; - - std::condition_variable m_cv; -}; - - - -} -} -#endif +/* Nintendo Switch Pro Controller (SysbotBase 3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H +#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase3_H + +#include "NintendoSwitch/NintendoSwitch_Settings.h" +//#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" +#include "SysbotBase_Connection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class ProController_SysbotBase3 final : + public ProController, + public ControllerWithScheduler, + private SysbotBase::TcpSysbotBase_Connection::Listener +{ +public: + using ContextType = ProControllerContext; + + static constexpr size_t QUEUE_SIZE = 256; + + +public: + ProController_SysbotBase3( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection + ); + ~ProController_SysbotBase3(); + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WiredProController; + } + virtual const ControllerFeatures& controller_features() const override; + virtual ControllerPerformanceClass performance_class() const override{ + // TODO: Change to SerialPABotBase_Wired_125Hz when we prove it is stable. + return ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; +// return ControllerPerformanceClass::SysbotBase; + } + + virtual Milliseconds ticksize() const override{ + return Milliseconds::zero(); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(8); + } + virtual Milliseconds timing_variation() const override{ + // TODO: Verify it is actually this stable. + return ConsoleSettings::instance().TIMING_OPTIONS.WIRED_MICROCONTROLLER; +// return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; +// return Milliseconds(8); + } + virtual bool atomic_multibutton() const override{ + return true; + } + + +public: + virtual void cancel_all_commands() override; + virtual void replace_on_next_command() override; + + virtual void wait_for_all(const Cancellable* cancellable) override; + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +public: + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return m_connection.is_ready(); + } + + +private: + virtual void on_message(const std::string& message) override; + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + +private: + SysbotBase::TcpSysbotBase_Connection& m_connection; + + bool m_stopping; + uint64_t m_next_seqnum; + uint64_t m_next_expected_seqnum_ack; + + std::condition_variable m_cv; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp index a1e3404295..af66c5420f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.cpp @@ -1,263 +1,263 @@ -/* sys-botbase Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Time.h" -//#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "SysbotBase_Connection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SysbotBase{ - -using namespace std::chrono_literals; - - - -bool parse_ip_and_port(const std::string& str, QHostAddress& address, int& port){ - // IPv4 - QStringList parts = QString::fromStdString(str).split(":"); - if (parts.size() != 2){ - return false; - } - address = QHostAddress(parts[0]); - bool ok; - port = parts[1].toUInt(&ok); - if (!ok){ - return false; - } - - // TODO: IPv6 - - return true; -} - - - - -TcpSysbotBase_Connection::TcpSysbotBase_Connection( - Logger& logger, - const std::string& url -) - : m_logger(logger) - , m_supports_command_queue(false) - , m_last_receive(WallClock::min()) -{ - QHostAddress address; - int port; - if (!parse_ip_and_port(url, address, port)){ - set_status_line0(html_color_text("Invalid IP address + port.", COLOR_RED)); - return; - } - - set_status_line0(html_color_text("Connecting...", COLOR_DARKGREEN)); - - m_connecting_message = - "Connecting To: " + address.toString().toStdString() + - " - Port: " + std::to_string(port); - m_logger.log(m_connecting_message); - - // Attach ourselves as listener first since it might immediately return as - // connected. - m_socket.add_listener(*this); - - try{ - m_socket.connect(address.toString().toStdString(), port); - }catch (...){ - m_socket.remove_listener(*this); - throw; - } -} - -TcpSysbotBase_Connection::~TcpSysbotBase_Connection(){ - try{ - write_data("detachController\r\n"); - }catch (...){} - m_socket.remove_listener(*this); - m_socket.close(); - { - std::lock_guard lg(m_lock); - m_cv.notify_all(); - } - if (m_thread.joinable()){ - m_thread.join(); - } -} - - -ControllerModeStatus TcpSysbotBase_Connection::controller_mode_status() const{ - return { - ControllerType::NintendoSwitch_WiredProController, - { - {ControllerType::NintendoSwitch_WiredProController, { - ControllerFeature::NintendoSwitch_ProController - }}, - } - }; -} - -void TcpSysbotBase_Connection::write_data(const std::string& data){ - WriteSpinLock lg(m_send_lock); -// cout << "Sending: " << data << endl; - m_socket.blocking_send(data.data(), data.size()); -} - - -std::string pretty_print(uint64_t x){ - auto ms = x / 1000; - auto us = x - ms * 1000; - std::string str_ms = std::to_string(ms); - std::string str_us = std::to_string(us); - return str_ms + "." + std::string(3 - str_us.size(), '0') + str_us; -} - - -void TcpSysbotBase_Connection::thread_loop(){ - std::unique_lock lg(m_lock); - WallClock send_time = current_time(); - while (true){ - ClientSocket::State state = m_socket.state(); - if (state == ClientSocket::State::DESTRUCTING || state == ClientSocket::State::NOT_RUNNING){ - break; - } - - WallClock now = current_time(); - - if (m_last_receive == WallClock::min()){ - send_time = now; - write_data("getVersion\r\n"); - }else if (send_time < m_last_receive && now - m_last_receive < std::chrono::seconds(1)){ - std::chrono::microseconds latency = std::chrono::duration_cast(m_last_receive - send_time); - std::string str = "Response Time: " + pretty_print(latency.count()) + " ms"; - if (latency < 10ms){ - set_status_line1(str, COLOR_BLUE); - }else if (latency < 50ms){ - set_status_line1(str, COLOR_DARKGREEN); - }else{ - set_status_line1(str, COLOR_ORANGE); - } - send_time = current_time(); - write_data("getVersion\r\n"); -// cout << std::chrono::duration_cast(current_time() - send_time) << endl; - }else{ - std::chrono::milliseconds time_since = std::chrono::duration_cast(now - m_last_receive); - std::string str = "Last Ack: " + pretty_print(time_since.count()) + " seconds ago"; - set_status_line1(str, COLOR_RED); - send_time = current_time(); - write_data("getVersion\r\n"); -// cout << std::chrono::duration_cast(current_time() - send_time) << endl; - } - m_cv.wait_for(lg, std::chrono::seconds(1)); - } -} - - - -void TcpSysbotBase_Connection::on_connect_finished(const std::string& error_message){ - try{ - if (!error_message.empty()){ - m_logger.log(m_connecting_message, COLOR_RED); - set_status_line0(m_connecting_message, COLOR_RED); - return; - } - - m_logger.log(m_connecting_message + " (Success)", COLOR_BLUE); - - write_data("configure echoCommands 0\r\n"); - write_data("getVersion\r\n"); - -// m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); - -// set_status_line0(m_version); - -// declare_ready(controller_mode_status()); - }catch (...){} -} -void TcpSysbotBase_Connection::on_receive_data(const void* data, size_t bytes){ -// cout << "on_receive_data(): " << std::string((const char*)data, bytes - 2) << endl; - - WallClock now = current_time(); - { - std::lock_guard lg(m_lock); - m_last_receive = now; - } - - - try{ - const char* ptr = (const char*)data; - for (size_t c = 0; c < bytes; c++){ - char ch = ptr[c]; - if (ch == '\r'){ - continue; - } - if (ch != '\n'){ - m_receive_buffer.emplace_back(ch); - continue; - } - process_message( - std::string( - m_receive_buffer.begin(), - m_receive_buffer.end() - ) - ); - m_receive_buffer.clear(); - } - -// m_listeners.run_method_unique(&Listener::on_receive_data, data, bytes); - - }catch (...){} -} -void TcpSysbotBase_Connection::process_message(const std::string& message){ -// cout << "sys-botbase Response: " << message << endl; - - m_listeners.run_method_unique(&Listener::on_message, message); - - // Version # - std::string str = message; - if (str.find('.') != std::string::npos){ - while (!str.empty() && str.back() <= 32){ - str.pop_back(); - } - set_status_line0("sys-botbase: Version " + str, COLOR_BLUE); - - std::lock_guard lg(m_lock); - if (!m_thread.joinable()){ - set_mode(str); - } - } - -} -void TcpSysbotBase_Connection::set_mode(const std::string& sbb_version){ - if (sbb_version.rfind("2.", 0) == 0){ - m_logger.log("Detected sbb2. Using old (slow) command set.", COLOR_ORANGE); - write_data("configure mainLoopSleepTime 0\r\n"); - m_supports_command_queue = false; - }else if (PreloadSettings::instance().DEVELOPER_MODE && sbb_version.rfind("3.", 0) == 0){ - m_logger.log("Detected sbb3. Using CC command queue.", COLOR_BLUE); - write_data("configure enablePA 1\r\n"); - m_supports_command_queue = true; - }else{ - m_logger.log("Unrecognized sbb version: " + sbb_version, COLOR_RED); - return; - } - - m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); - declare_ready(controller_mode_status()); -} - - - - - - - -} -} +/* sys-botbase Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Time.h" +//#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "SysbotBase_Connection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SysbotBase{ + +using namespace std::chrono_literals; + + + +bool parse_ip_and_port(const std::string& str, QHostAddress& address, int& port){ + // IPv4 + QStringList parts = QString::fromStdString(str).split(":"); + if (parts.size() != 2){ + return false; + } + address = QHostAddress(parts[0]); + bool ok; + port = parts[1].toUInt(&ok); + if (!ok){ + return false; + } + + // TODO: IPv6 + + return true; +} + + + + +TcpSysbotBase_Connection::TcpSysbotBase_Connection( + Logger& logger, + const std::string& url +) + : m_logger(logger) + , m_supports_command_queue(false) + , m_last_receive(WallClock::min()) +{ + QHostAddress address; + int port; + if (!parse_ip_and_port(url, address, port)){ + set_status_line0(html_color_text("Invalid IP address + port.", COLOR_RED)); + return; + } + + set_status_line0(html_color_text("Connecting...", COLOR_DARKGREEN)); + + m_connecting_message = + "Connecting To: " + address.toString().toStdString() + + " - Port: " + std::to_string(port); + m_logger.log(m_connecting_message); + + // Attach ourselves as listener first since it might immediately return as + // connected. + m_socket.add_listener(*this); + + try{ + m_socket.connect(address.toString().toStdString(), port); + }catch (...){ + m_socket.remove_listener(*this); + throw; + } +} + +TcpSysbotBase_Connection::~TcpSysbotBase_Connection(){ + try{ + write_data("detachController\r\n"); + }catch (...){} + m_socket.remove_listener(*this); + m_socket.close(); + { + std::lock_guard lg(m_lock); + m_cv.notify_all(); + } + if (m_thread.joinable()){ + m_thread.join(); + } +} + + +ControllerModeStatus TcpSysbotBase_Connection::controller_mode_status() const{ + return { + ControllerType::NintendoSwitch_WiredProController, + { + {ControllerType::NintendoSwitch_WiredProController, { + ControllerFeature::NintendoSwitch_ProController + }}, + } + }; +} + +void TcpSysbotBase_Connection::write_data(const std::string& data){ + WriteSpinLock lg(m_send_lock); +// cout << "Sending: " << data << endl; + m_socket.blocking_send(data.data(), data.size()); +} + + +std::string pretty_print(uint64_t x){ + auto ms = x / 1000; + auto us = x - ms * 1000; + std::string str_ms = std::to_string(ms); + std::string str_us = std::to_string(us); + return str_ms + "." + std::string(3 - str_us.size(), '0') + str_us; +} + + +void TcpSysbotBase_Connection::thread_loop(){ + std::unique_lock lg(m_lock); + WallClock send_time = current_time(); + while (true){ + ClientSocket::State state = m_socket.state(); + if (state == ClientSocket::State::DESTRUCTING || state == ClientSocket::State::NOT_RUNNING){ + break; + } + + WallClock now = current_time(); + + if (m_last_receive == WallClock::min()){ + send_time = now; + write_data("getVersion\r\n"); + }else if (send_time < m_last_receive && now - m_last_receive < std::chrono::seconds(1)){ + std::chrono::microseconds latency = std::chrono::duration_cast(m_last_receive - send_time); + std::string str = "Response Time: " + pretty_print(latency.count()) + " ms"; + if (latency < 10ms){ + set_status_line1(str, COLOR_BLUE); + }else if (latency < 50ms){ + set_status_line1(str, COLOR_DARKGREEN); + }else{ + set_status_line1(str, COLOR_ORANGE); + } + send_time = current_time(); + write_data("getVersion\r\n"); +// cout << std::chrono::duration_cast(current_time() - send_time) << endl; + }else{ + std::chrono::milliseconds time_since = std::chrono::duration_cast(now - m_last_receive); + std::string str = "Last Ack: " + pretty_print(time_since.count()) + " seconds ago"; + set_status_line1(str, COLOR_RED); + send_time = current_time(); + write_data("getVersion\r\n"); +// cout << std::chrono::duration_cast(current_time() - send_time) << endl; + } + m_cv.wait_for(lg, std::chrono::seconds(1)); + } +} + + + +void TcpSysbotBase_Connection::on_connect_finished(const std::string& error_message){ + try{ + if (!error_message.empty()){ + m_logger.log(m_connecting_message, COLOR_RED); + set_status_line0(m_connecting_message, COLOR_RED); + return; + } + + m_logger.log(m_connecting_message + " (Success)", COLOR_BLUE); + + write_data("configure echoCommands 0\r\n"); + write_data("getVersion\r\n"); + +// m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); + +// set_status_line0(m_version); + +// declare_ready(controller_mode_status()); + }catch (...){} +} +void TcpSysbotBase_Connection::on_receive_data(const void* data, size_t bytes){ +// cout << "on_receive_data(): " << std::string((const char*)data, bytes - 2) << endl; + + WallClock now = current_time(); + { + std::lock_guard lg(m_lock); + m_last_receive = now; + } + + + try{ + const char* ptr = (const char*)data; + for (size_t c = 0; c < bytes; c++){ + char ch = ptr[c]; + if (ch == '\r'){ + continue; + } + if (ch != '\n'){ + m_receive_buffer.emplace_back(ch); + continue; + } + process_message( + std::string( + m_receive_buffer.begin(), + m_receive_buffer.end() + ) + ); + m_receive_buffer.clear(); + } + +// m_listeners.run_method_unique(&Listener::on_receive_data, data, bytes); + + }catch (...){} +} +void TcpSysbotBase_Connection::process_message(const std::string& message){ +// cout << "sys-botbase Response: " << message << endl; + + m_listeners.run_method_unique(&Listener::on_message, message); + + // Version # + std::string str = message; + if (str.find('.') != std::string::npos){ + while (!str.empty() && str.back() <= 32){ + str.pop_back(); + } + set_status_line0("sys-botbase: Version " + str, COLOR_BLUE); + + std::lock_guard lg(m_lock); + if (!m_thread.joinable()){ + set_mode(str); + } + } + +} +void TcpSysbotBase_Connection::set_mode(const std::string& sbb_version){ + if (sbb_version.rfind("2.", 0) == 0){ + m_logger.log("Detected sbb2. Using old (slow) command set.", COLOR_ORANGE); + write_data("configure mainLoopSleepTime 0\r\n"); + m_supports_command_queue = false; + }else if (PreloadSettings::instance().DEVELOPER_MODE && sbb_version.rfind("3.", 0) == 0){ + m_logger.log("Detected sbb3. Using CC command queue.", COLOR_BLUE); + write_data("configure enablePA 1\r\n"); + m_supports_command_queue = true; + }else{ + m_logger.log("Unrecognized sbb version: " + sbb_version, COLOR_RED); + return; + } + + m_thread = std::thread(&TcpSysbotBase_Connection::thread_loop, this); + declare_ready(controller_mode_status()); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h index ad4aab1263..1dc2f99008 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Connection.h @@ -1,84 +1,84 @@ -/* sys-botbase Connection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SysbotBase_Connection_H -#define PokemonAutomation_Controllers_SysbotBase_Connection_H - -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Sockets/ClientSocket.h" -#include "Controllers/ControllerConnection.h" - -namespace PokemonAutomation{ -namespace SysbotBase{ - - -class TcpSysbotBase_Connection : public ControllerConnection, private ClientSocket::Listener{ -public: - struct Listener{ - virtual void on_message(const std::string& message) = 0; - }; - - void add_listener(Listener& listener){ - m_listeners.add(listener); - } - void remove_listener(Listener& listener){ - m_listeners.add(listener); - } - -public: - TcpSysbotBase_Connection( - Logger& logger, - const std::string& url - ); - ~TcpSysbotBase_Connection(); - - virtual ControllerModeStatus controller_mode_status() const override; - bool supports_command_queue() const{ - return m_supports_command_queue; - } - - void write_data(const std::string& data); - -private: - void thread_loop(); - - virtual void on_connect_finished(const std::string& error_message) override; - virtual void on_receive_data(const void* data, size_t bytes) override; - - void process_message(const std::string& message); - void set_mode(const std::string& sbb_version); - -private: - Logger& m_logger; - ClientSocket m_socket; - - bool m_supports_command_queue; - - std::string m_connecting_message; -// std::string m_version; - WallClock m_last_receive; - std::deque m_receive_buffer; - - SpinLock m_send_lock; - std::mutex m_lock; - std::condition_variable m_cv; - std::thread m_thread; - - ListenerSet m_listeners; -}; - - - -} -} -#endif +/* sys-botbase Connection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SysbotBase_Connection_H +#define PokemonAutomation_Controllers_SysbotBase_Connection_H + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Sockets/ClientSocket.h" +#include "Controllers/ControllerConnection.h" + +namespace PokemonAutomation{ +namespace SysbotBase{ + + +class TcpSysbotBase_Connection : public ControllerConnection, private ClientSocket::Listener{ +public: + struct Listener{ + virtual void on_message(const std::string& message) = 0; + }; + + void add_listener(Listener& listener){ + m_listeners.add(listener); + } + void remove_listener(Listener& listener){ + m_listeners.add(listener); + } + +public: + TcpSysbotBase_Connection( + Logger& logger, + const std::string& url + ); + ~TcpSysbotBase_Connection(); + + virtual ControllerModeStatus controller_mode_status() const override; + bool supports_command_queue() const{ + return m_supports_command_queue; + } + + void write_data(const std::string& data); + +private: + void thread_loop(); + + virtual void on_connect_finished(const std::string& error_message) override; + virtual void on_receive_data(const void* data, size_t bytes) override; + + void process_message(const std::string& message); + void set_mode(const std::string& sbb_version); + +private: + Logger& m_logger; + ClientSocket m_socket; + + bool m_supports_command_queue; + + std::string m_connecting_message; +// std::string m_version; + WallClock m_last_receive; + std::deque m_receive_buffer; + + SpinLock m_send_lock; + std::mutex m_lock; + std::condition_variable m_cv; + std::thread m_thread; + + ListenerSet m_listeners; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp index 21173acd68..6306503989 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.cpp @@ -1,85 +1,85 @@ -/* sys-botbase Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "SysbotBase_Descriptor.h" -#include "SysbotBase_Connection.h" -#include "SysbotBase_ProController.h" -#include "SysbotBase3_ProController.h" -#include "SysbotBase_SelectorWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -template class InterfaceType_t; - -namespace SysbotBase{ - - - -bool TcpSysbotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ - if (typeid(*this) != typeid(x)){ - return false; - } - return m_url == static_cast(x).m_url; -} - -std::string TcpSysbotBase_Descriptor::display_name() const{ - return m_url; -} - -void TcpSysbotBase_Descriptor::load_json(const JsonValue& json){ - const std::string* url = json.to_string(); - if (url == nullptr || url->empty()){ - return; - } - m_url = *url; -} -JsonValue TcpSysbotBase_Descriptor::to_json() const{ - return m_url; -} - - - -std::unique_ptr TcpSysbotBase_Descriptor::open_connection( - Logger& logger, - std::optional change_controller -) const{ - return std::unique_ptr( - new TcpSysbotBase_Connection(logger, m_url) - ); -} -std::unique_ptr TcpSysbotBase_Descriptor::make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type -) const{ - TcpSysbotBase_Connection& sbb_connection = static_cast(connection); - if (sbb_connection.supports_command_queue()){ - return std::unique_ptr( - new NintendoSwitch::ProController_SysbotBase3(logger, sbb_connection) - ); - }else{ - return std::unique_ptr( - new NintendoSwitch::ProController_SysbotBase(logger, sbb_connection) - ); - } -} - - - -QWidget* TcpSysbotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ - return new TcpSysbotBase_SelectorWidget(parent, this); -} - - - - -} -} +/* sys-botbase Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "SysbotBase_Descriptor.h" +#include "SysbotBase_Connection.h" +#include "SysbotBase_ProController.h" +#include "SysbotBase3_ProController.h" +#include "SysbotBase_SelectorWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +template class InterfaceType_t; + +namespace SysbotBase{ + + + +bool TcpSysbotBase_Descriptor::operator==(const ControllerDescriptor& x) const{ + if (typeid(*this) != typeid(x)){ + return false; + } + return m_url == static_cast(x).m_url; +} + +std::string TcpSysbotBase_Descriptor::display_name() const{ + return m_url; +} + +void TcpSysbotBase_Descriptor::load_json(const JsonValue& json){ + const std::string* url = json.to_string(); + if (url == nullptr || url->empty()){ + return; + } + m_url = *url; +} +JsonValue TcpSysbotBase_Descriptor::to_json() const{ + return m_url; +} + + + +std::unique_ptr TcpSysbotBase_Descriptor::open_connection( + Logger& logger, + std::optional change_controller +) const{ + return std::unique_ptr( + new TcpSysbotBase_Connection(logger, m_url) + ); +} +std::unique_ptr TcpSysbotBase_Descriptor::make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type +) const{ + TcpSysbotBase_Connection& sbb_connection = static_cast(connection); + if (sbb_connection.supports_command_queue()){ + return std::unique_ptr( + new NintendoSwitch::ProController_SysbotBase3(logger, sbb_connection) + ); + }else{ + return std::unique_ptr( + new NintendoSwitch::ProController_SysbotBase(logger, sbb_connection) + ); + } +} + + + +QWidget* TcpSysbotBase_Descriptor::make_selector_QtWidget(ControllerSelectorWidget& parent) const{ + return new TcpSysbotBase_SelectorWidget(parent, this); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h index 2a70cb4599..d1c8beac39 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_Descriptor.h @@ -1,65 +1,65 @@ -/* sys-botbase Descriptor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SysbotBase_Descriptor_H -#define PokemonAutomation_Controllers_SysbotBase_Descriptor_H - -#include "Controllers/ControllerDescriptor.h" - -namespace PokemonAutomation{ -namespace SysbotBase{ - - - -class TcpSysbotBase_Descriptor : public ControllerDescriptor{ -public: - static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::TcpSysbotBase; - - -public: - TcpSysbotBase_Descriptor() - : ControllerDescriptor(INTERFACE_NAME) - {} - TcpSysbotBase_Descriptor(std::string url) - : ControllerDescriptor(INTERFACE_NAME) - , m_url(std::move(url)) - {} - - const std::string& url() const{ - return m_url; - } - - virtual bool operator==(const ControllerDescriptor& x) const override; - virtual std::string display_name() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual std::unique_ptr open_connection( - Logger& logger, - std::optional change_controller - ) const override; - virtual std::unique_ptr make_controller( - Logger& logger, - ControllerConnection& connection, - ControllerType controller_type - ) const override; - - virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; - -private: - std::string m_url; -}; - - - - - - - -} -} -#endif +/* sys-botbase Descriptor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SysbotBase_Descriptor_H +#define PokemonAutomation_Controllers_SysbotBase_Descriptor_H + +#include "Controllers/ControllerDescriptor.h" + +namespace PokemonAutomation{ +namespace SysbotBase{ + + + +class TcpSysbotBase_Descriptor : public ControllerDescriptor{ +public: + static constexpr ControllerInterface INTERFACE_NAME = ControllerInterface::TcpSysbotBase; + + +public: + TcpSysbotBase_Descriptor() + : ControllerDescriptor(INTERFACE_NAME) + {} + TcpSysbotBase_Descriptor(std::string url) + : ControllerDescriptor(INTERFACE_NAME) + , m_url(std::move(url)) + {} + + const std::string& url() const{ + return m_url; + } + + virtual bool operator==(const ControllerDescriptor& x) const override; + virtual std::string display_name() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual std::unique_ptr open_connection( + Logger& logger, + std::optional change_controller + ) const override; + virtual std::unique_ptr make_controller( + Logger& logger, + ControllerConnection& connection, + ControllerType controller_type + ) const override; + + virtual QWidget* make_selector_QtWidget(ControllerSelectorWidget& parent) const override; + +private: + std::string m_url; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp index 2660e60ba8..6834f24400 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.cpp @@ -1,365 +1,365 @@ -/* Nintendo Switch Pro Controller (SysbotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "Controllers/JoystickTools.h" -#include "SysbotBase_ProController.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -ProController_SysbotBase::ProController_SysbotBase( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection -) - : ControllerWithScheduler(logger) - , m_connection(connection) - , m_stopping(false) - , m_replace_on_next(false) - , m_command_queue(QUEUE_SIZE) - , m_next_state_change(WallClock::max()) -{ - if (!connection.is_ready()){ - return; - } - - // Check compatibility. - - ControllerModeStatus mode_status = connection.controller_mode_status(); - auto iter = mode_status.supported_controllers.find(ControllerType::NintendoSwitch_WiredProController); - if (iter != mode_status.supported_controllers.end()){ - m_dispatch_thread = std::thread(&ProController_SysbotBase::thread_body, this); - } -} -ProController_SysbotBase::~ProController_SysbotBase(){ - stop(); - if (m_dispatch_thread.joinable()){ - m_dispatch_thread.join(); - } -} -void ProController_SysbotBase::stop(){ - if (m_stopping.exchange(true)){ - return; - } - ProController::stop(); - { - std::lock_guard lg(m_state_lock); - m_cv.notify_all(); - } -} - - -const ControllerFeatures& ProController_SysbotBase::controller_features() const{ - static const ControllerFeatures features{ - ControllerFeature::NintendoSwitch_ProController, - }; - return features; -} - - - -void ProController_SysbotBase::cancel_all_commands(){ -// cout << "ProController_SysbotBase::cancel_all_commands()" << endl; - std::lock_guard lg(m_state_lock); - size_t queue_size = m_command_queue.size(); - m_next_state_change = WallClock::min(); - m_command_queue.clear(); - m_cv.notify_all(); - this->clear_on_next(); - m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queue_size), COLOR_DARKGREEN); -} -void ProController_SysbotBase::replace_on_next_command(){ -// cout << "ProController_SysbotBase::replace_on_next_command - Enter()" << endl; - std::lock_guard lg(m_state_lock); - m_cv.notify_all(); - m_replace_on_next = true; - this->clear_on_next(); - m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); -} - - -void ProController_SysbotBase::wait_for_all(const Cancellable* cancellable){ -// cout << "ProController_SysbotBase::wait_for_all - Enter()" << endl; - std::lock_guard lg0(m_issue_lock); - std::unique_lock lg1(m_state_lock); - m_logger.log("wait_for_all(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); - this->issue_wait_for_all(cancellable); - m_cv.wait(lg1, [this]{ - return m_next_state_change == WallClock::max() || m_replace_on_next; - }); - if (cancellable){ - cancellable->throw_if_cancelled(); - } -// cout << "ProController_SysbotBase::wait_for_all - Exit()" << endl; -} -void ProController_SysbotBase::push_state(const Cancellable* cancellable, WallDuration duration){ - // Must be called inside "m_state_lock". - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - if (!is_ready()){ - throw InvalidConnectionStateException(""); - } - - Button buttons = BUTTON_NONE; - for (size_t c = 0; c < 14; c++){ - buttons |= m_buttons[c].is_busy() - ? (Button)((uint16_t)1 << c) - : BUTTON_NONE; - } - - DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; - - uint8_t left_x = 128; - uint8_t left_y = 128; - uint8_t right_x = 128; - uint8_t right_y = 128; - if (m_left_joystick.is_busy()){ - left_x = m_left_joystick.x; - left_y = m_left_joystick.y; - } - if (m_right_joystick.is_busy()){ - right_x = m_right_joystick.x; - right_y = m_right_joystick.y; - } - - std::unique_lock lg(m_state_lock, std::adopt_lock_t()); - - m_cv.wait(lg, [this]{ - return m_command_queue.size() < QUEUE_SIZE || m_replace_on_next; - }); - - lg.release(); - - if (cancellable){ - cancellable->throw_if_cancelled(); - } - - if (m_replace_on_next){ -// cout << "executing replace" << endl; - m_replace_on_next = false; - m_command_queue.clear(); - m_next_state_change = WallClock::min(); - m_cv.notify_all(); - } - - // Enqueuing into empty+idle queue. - if (m_next_state_change == WallClock::max()){ - m_next_state_change = WallClock::min(); - m_cv.notify_all(); - } - - Command& command = m_command_queue.push_back(); - - command.state.buttons = buttons; - command.state.dpad = dpad; - command.state.left_x = left_x; - command.state.left_y = left_y; - command.state.right_x = right_x; - command.state.right_y = right_y; - - command.duration = std::chrono::duration_cast(duration); -} - - - -void ProController_SysbotBase::send_diff( - const ProControllerState& old_state, - const ProControllerState& new_state -){ -#if 0 - m_logger.log( - "send_diff(): (" + button_to_string(new_state.buttons) + - "), dpad(" + dpad_to_string(new_state.dpad) + - "), LJ(" + std::to_string(new_state.left_x) + "," + std::to_string(new_state.left_y) + - "), RJ(" + std::to_string(new_state.right_x) + "," + std::to_string(new_state.right_y) + - ")", - COLOR_DARKGREEN - ); -#endif - - // These need to match: - // https://github.com/olliz0r/sys-botbase/blob/master/sys-botbase/source/util.c#L145 - static const std::vector> BUTTON_MAP{ - {BUTTON_Y, "Y"}, - {BUTTON_B, "B"}, - {BUTTON_A, "A"}, - {BUTTON_X, "X"}, - {BUTTON_L, "L"}, - {BUTTON_R, "R"}, - {BUTTON_ZL, "ZL"}, - {BUTTON_ZR, "ZR"}, - {BUTTON_MINUS, "MINUS"}, - {BUTTON_PLUS, "PLUS"}, - {BUTTON_LCLICK, "LSTICK"}, - {BUTTON_RCLICK, "RSTICK"}, - {BUTTON_HOME, "HOME"}, - {BUTTON_CAPTURE, "CAPTURE"}, - {BUTTON_UP, "DU"}, - {BUTTON_RIGHT, "DR"}, - {BUTTON_DOWN, "DD"}, - {BUTTON_LEFT, "DL"}, - }; - - std::string message; - - - // Merge the dpad states. - ButtonFlagType old_buttons = old_state.buttons; - ButtonFlagType new_buttons = new_state.buttons; - - SplitDpad old_dpad = convert_unified_to_split_dpad(old_state.dpad); - if (old_dpad.up) old_buttons |= BUTTON_UP; - if (old_dpad.right) old_buttons |= BUTTON_RIGHT; - if (old_dpad.down) old_buttons |= BUTTON_DOWN; - if (old_dpad.left) old_buttons |= BUTTON_LEFT; - - SplitDpad new_dpad = convert_unified_to_split_dpad(new_state.dpad); - if (new_dpad.up) new_buttons |= BUTTON_UP; - if (new_dpad.right) new_buttons |= BUTTON_RIGHT; - if (new_dpad.down) new_buttons |= BUTTON_DOWN; - if (new_dpad.left) new_buttons |= BUTTON_LEFT; - - - if (old_buttons != new_buttons){ - for (const auto& button : BUTTON_MAP){ - ButtonFlagType mask = (ButtonFlagType)button.first; - bool before = (ButtonFlagType)old_buttons & mask; - bool after = (ButtonFlagType)new_buttons & mask; - if (before == after){ - continue; - } - if (after){ - message += "press " + button.second + "\r\n"; - }else{ - message += "release " + button.second + "\r\n"; - } - } - } - - if (old_state.left_x != new_state.left_x || - old_state.left_y != new_state.left_y - ){ - double fx = JoystickTools::linear_u8_to_float(new_state.left_x); - double fy = -JoystickTools::linear_u8_to_float(new_state.left_y); -// cout << "fx = " << fx << ", fy = " << fy << endl; - int16_t ix = JoystickTools::linear_float_to_s16(fx); - int16_t iy = JoystickTools::linear_float_to_s16(fy); -// cout << "ix = " << ix << ", iy = " << iy << endl; - message += "setStick LEFT "; - message += std::to_string(ix); - message += " "; - message += std::to_string(iy); - message += "\r\n"; - } - if (old_state.right_x != new_state.right_x || - old_state.right_y != new_state.right_y - ){ - double fx = JoystickTools::linear_u8_to_float(new_state.right_x); - double fy = -JoystickTools::linear_u8_to_float(new_state.right_y); - int16_t ix = JoystickTools::linear_float_to_s16(fx); - int16_t iy = JoystickTools::linear_float_to_s16(fy); - message += "setStick RIGHT "; - message += std::to_string(ix); - message += " "; - message += std::to_string(iy); - message += "\r\n"; - } - - if (message.empty()){ - return; - } - -// cout << message << endl; - m_connection.write_data(message); - - if (GlobalSettings::instance().LOG_EVERYTHING){ - m_logger.log("sys-botbase: " + message); - } -} - - -void ProController_SysbotBase::thread_body(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - std::chrono::microseconds EARLY_WAKE = GlobalSettings::instance().PERFORMANCE->PRECISE_WAKE_MARGIN; - - ProControllerState current_state; - - std::unique_lock lg(m_state_lock); - while (!m_stopping.load(std::memory_order_relaxed)){ - WallClock now = current_time(); - - // State change. - if (now >= m_next_state_change){ - if (m_command_queue.empty()){ - send_diff(current_state, ProControllerState()); - current_state.clear(); - m_next_state_change = WallClock::max(); - }else{ - Command& command = m_command_queue.front(); - send_diff(current_state, command.state); - current_state = command.state; - if (m_next_state_change == WallClock::min()){ - m_next_state_change = now; - } - m_next_state_change += command.duration; - m_command_queue.pop_front(); - } - m_cv.notify_all(); - continue; - } - - if (now + EARLY_WAKE >= m_next_state_change){ - pause(); - continue; - } - - m_cv.wait_until(lg, m_next_state_change - EARLY_WAKE); - - // Check how much we shot passed the expiration time. -// WallDuration delay = now - expiration; - -// cout << "Delay = " << std::chrono::duration_cast(delay) << endl; - } - - ProControllerState neutral_state; - send_diff(current_state, neutral_state); -} - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Nintendo Switch Pro Controller (SysbotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "Controllers/JoystickTools.h" +#include "SysbotBase_ProController.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +ProController_SysbotBase::ProController_SysbotBase( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection +) + : ControllerWithScheduler(logger) + , m_connection(connection) + , m_stopping(false) + , m_replace_on_next(false) + , m_command_queue(QUEUE_SIZE) + , m_next_state_change(WallClock::max()) +{ + if (!connection.is_ready()){ + return; + } + + // Check compatibility. + + ControllerModeStatus mode_status = connection.controller_mode_status(); + auto iter = mode_status.supported_controllers.find(ControllerType::NintendoSwitch_WiredProController); + if (iter != mode_status.supported_controllers.end()){ + m_dispatch_thread = std::thread(&ProController_SysbotBase::thread_body, this); + } +} +ProController_SysbotBase::~ProController_SysbotBase(){ + stop(); + if (m_dispatch_thread.joinable()){ + m_dispatch_thread.join(); + } +} +void ProController_SysbotBase::stop(){ + if (m_stopping.exchange(true)){ + return; + } + ProController::stop(); + { + std::lock_guard lg(m_state_lock); + m_cv.notify_all(); + } +} + + +const ControllerFeatures& ProController_SysbotBase::controller_features() const{ + static const ControllerFeatures features{ + ControllerFeature::NintendoSwitch_ProController, + }; + return features; +} + + + +void ProController_SysbotBase::cancel_all_commands(){ +// cout << "ProController_SysbotBase::cancel_all_commands()" << endl; + std::lock_guard lg(m_state_lock); + size_t queue_size = m_command_queue.size(); + m_next_state_change = WallClock::min(); + m_command_queue.clear(); + m_cv.notify_all(); + this->clear_on_next(); + m_logger.log("cancel_all_commands(): Command Queue Size = " + std::to_string(queue_size), COLOR_DARKGREEN); +} +void ProController_SysbotBase::replace_on_next_command(){ +// cout << "ProController_SysbotBase::replace_on_next_command - Enter()" << endl; + std::lock_guard lg(m_state_lock); + m_cv.notify_all(); + m_replace_on_next = true; + this->clear_on_next(); + m_logger.log("replace_on_next_command(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); +} + + +void ProController_SysbotBase::wait_for_all(const Cancellable* cancellable){ +// cout << "ProController_SysbotBase::wait_for_all - Enter()" << endl; + std::lock_guard lg0(m_issue_lock); + std::unique_lock lg1(m_state_lock); + m_logger.log("wait_for_all(): Command Queue Size = " + std::to_string(m_command_queue.size()), COLOR_DARKGREEN); + this->issue_wait_for_all(cancellable); + m_cv.wait(lg1, [this]{ + return m_next_state_change == WallClock::max() || m_replace_on_next; + }); + if (cancellable){ + cancellable->throw_if_cancelled(); + } +// cout << "ProController_SysbotBase::wait_for_all - Exit()" << endl; +} +void ProController_SysbotBase::push_state(const Cancellable* cancellable, WallDuration duration){ + // Must be called inside "m_state_lock". + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + if (!is_ready()){ + throw InvalidConnectionStateException(""); + } + + Button buttons = BUTTON_NONE; + for (size_t c = 0; c < 14; c++){ + buttons |= m_buttons[c].is_busy() + ? (Button)((uint16_t)1 << c) + : BUTTON_NONE; + } + + DpadPosition dpad = m_dpad.is_busy() ? m_dpad.position : DPAD_NONE; + + uint8_t left_x = 128; + uint8_t left_y = 128; + uint8_t right_x = 128; + uint8_t right_y = 128; + if (m_left_joystick.is_busy()){ + left_x = m_left_joystick.x; + left_y = m_left_joystick.y; + } + if (m_right_joystick.is_busy()){ + right_x = m_right_joystick.x; + right_y = m_right_joystick.y; + } + + std::unique_lock lg(m_state_lock, std::adopt_lock_t()); + + m_cv.wait(lg, [this]{ + return m_command_queue.size() < QUEUE_SIZE || m_replace_on_next; + }); + + lg.release(); + + if (cancellable){ + cancellable->throw_if_cancelled(); + } + + if (m_replace_on_next){ +// cout << "executing replace" << endl; + m_replace_on_next = false; + m_command_queue.clear(); + m_next_state_change = WallClock::min(); + m_cv.notify_all(); + } + + // Enqueuing into empty+idle queue. + if (m_next_state_change == WallClock::max()){ + m_next_state_change = WallClock::min(); + m_cv.notify_all(); + } + + Command& command = m_command_queue.push_back(); + + command.state.buttons = buttons; + command.state.dpad = dpad; + command.state.left_x = left_x; + command.state.left_y = left_y; + command.state.right_x = right_x; + command.state.right_y = right_y; + + command.duration = std::chrono::duration_cast(duration); +} + + + +void ProController_SysbotBase::send_diff( + const ProControllerState& old_state, + const ProControllerState& new_state +){ +#if 0 + m_logger.log( + "send_diff(): (" + button_to_string(new_state.buttons) + + "), dpad(" + dpad_to_string(new_state.dpad) + + "), LJ(" + std::to_string(new_state.left_x) + "," + std::to_string(new_state.left_y) + + "), RJ(" + std::to_string(new_state.right_x) + "," + std::to_string(new_state.right_y) + + ")", + COLOR_DARKGREEN + ); +#endif + + // These need to match: + // https://github.com/olliz0r/sys-botbase/blob/master/sys-botbase/source/util.c#L145 + static const std::vector> BUTTON_MAP{ + {BUTTON_Y, "Y"}, + {BUTTON_B, "B"}, + {BUTTON_A, "A"}, + {BUTTON_X, "X"}, + {BUTTON_L, "L"}, + {BUTTON_R, "R"}, + {BUTTON_ZL, "ZL"}, + {BUTTON_ZR, "ZR"}, + {BUTTON_MINUS, "MINUS"}, + {BUTTON_PLUS, "PLUS"}, + {BUTTON_LCLICK, "LSTICK"}, + {BUTTON_RCLICK, "RSTICK"}, + {BUTTON_HOME, "HOME"}, + {BUTTON_CAPTURE, "CAPTURE"}, + {BUTTON_UP, "DU"}, + {BUTTON_RIGHT, "DR"}, + {BUTTON_DOWN, "DD"}, + {BUTTON_LEFT, "DL"}, + }; + + std::string message; + + + // Merge the dpad states. + ButtonFlagType old_buttons = old_state.buttons; + ButtonFlagType new_buttons = new_state.buttons; + + SplitDpad old_dpad = convert_unified_to_split_dpad(old_state.dpad); + if (old_dpad.up) old_buttons |= BUTTON_UP; + if (old_dpad.right) old_buttons |= BUTTON_RIGHT; + if (old_dpad.down) old_buttons |= BUTTON_DOWN; + if (old_dpad.left) old_buttons |= BUTTON_LEFT; + + SplitDpad new_dpad = convert_unified_to_split_dpad(new_state.dpad); + if (new_dpad.up) new_buttons |= BUTTON_UP; + if (new_dpad.right) new_buttons |= BUTTON_RIGHT; + if (new_dpad.down) new_buttons |= BUTTON_DOWN; + if (new_dpad.left) new_buttons |= BUTTON_LEFT; + + + if (old_buttons != new_buttons){ + for (const auto& button : BUTTON_MAP){ + ButtonFlagType mask = (ButtonFlagType)button.first; + bool before = (ButtonFlagType)old_buttons & mask; + bool after = (ButtonFlagType)new_buttons & mask; + if (before == after){ + continue; + } + if (after){ + message += "press " + button.second + "\r\n"; + }else{ + message += "release " + button.second + "\r\n"; + } + } + } + + if (old_state.left_x != new_state.left_x || + old_state.left_y != new_state.left_y + ){ + double fx = JoystickTools::linear_u8_to_float(new_state.left_x); + double fy = -JoystickTools::linear_u8_to_float(new_state.left_y); +// cout << "fx = " << fx << ", fy = " << fy << endl; + int16_t ix = JoystickTools::linear_float_to_s16(fx); + int16_t iy = JoystickTools::linear_float_to_s16(fy); +// cout << "ix = " << ix << ", iy = " << iy << endl; + message += "setStick LEFT "; + message += std::to_string(ix); + message += " "; + message += std::to_string(iy); + message += "\r\n"; + } + if (old_state.right_x != new_state.right_x || + old_state.right_y != new_state.right_y + ){ + double fx = JoystickTools::linear_u8_to_float(new_state.right_x); + double fy = -JoystickTools::linear_u8_to_float(new_state.right_y); + int16_t ix = JoystickTools::linear_float_to_s16(fx); + int16_t iy = JoystickTools::linear_float_to_s16(fy); + message += "setStick RIGHT "; + message += std::to_string(ix); + message += " "; + message += std::to_string(iy); + message += "\r\n"; + } + + if (message.empty()){ + return; + } + +// cout << message << endl; + m_connection.write_data(message); + + if (GlobalSettings::instance().LOG_EVERYTHING){ + m_logger.log("sys-botbase: " + message); + } +} + + +void ProController_SysbotBase::thread_body(){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + std::chrono::microseconds EARLY_WAKE = GlobalSettings::instance().PERFORMANCE->PRECISE_WAKE_MARGIN; + + ProControllerState current_state; + + std::unique_lock lg(m_state_lock); + while (!m_stopping.load(std::memory_order_relaxed)){ + WallClock now = current_time(); + + // State change. + if (now >= m_next_state_change){ + if (m_command_queue.empty()){ + send_diff(current_state, ProControllerState()); + current_state.clear(); + m_next_state_change = WallClock::max(); + }else{ + Command& command = m_command_queue.front(); + send_diff(current_state, command.state); + current_state = command.state; + if (m_next_state_change == WallClock::min()){ + m_next_state_change = now; + } + m_next_state_change += command.duration; + m_command_queue.pop_front(); + } + m_cv.notify_all(); + continue; + } + + if (now + EARLY_WAKE >= m_next_state_change){ + pause(); + continue; + } + + m_cv.wait_until(lg, m_next_state_change - EARLY_WAKE); + + // Check how much we shot passed the expiration time. +// WallDuration delay = now - expiration; + +// cout << "Delay = " << std::chrono::duration_cast(delay) << endl; + } + + ProControllerState neutral_state; + send_diff(current_state, neutral_state); +} + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h index a5d4f25bcb..ecaacf8e3c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_ProController.h @@ -1,253 +1,253 @@ -/* Nintendo Switch Pro Controller (SysbotBase) - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H -#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H - -#include -#include "Common/Cpp/Containers/CircularBuffer.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" -#include "SysbotBase_Connection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class ProController_SysbotBase final : - public ProController, - public ControllerWithScheduler -{ -public: - using ContextType = ProControllerContext; - - static constexpr size_t QUEUE_SIZE = 4; - - -public: - ProController_SysbotBase( - Logger& logger, - SysbotBase::TcpSysbotBase_Connection& connection - ); - ~ProController_SysbotBase(); - void stop(); - - -public: - virtual ControllerType controller_type() const override{ - return ControllerType::NintendoSwitch_WiredProController; - } - virtual const ControllerFeatures& controller_features() const override; - virtual ControllerPerformanceClass performance_class() const override{ - return ControllerPerformanceClass::SysbotBase; - } - - virtual Milliseconds ticksize() const override{ - return Milliseconds::zero(); - } - virtual Milliseconds cooldown() const override{ - return Milliseconds(150); - } - virtual Milliseconds timing_variation() const override{ - return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; - } - virtual bool atomic_multibutton() const override{ - return false; - } - - -public: - virtual Logger& logger() override{ - return m_logger; - } - virtual RecursiveThrottler& logging_throttler() override{ - return m_logging_throttler; - } - virtual bool is_ready() const override{ - return m_connection.is_ready(); - } - - -public: - virtual void cancel_all_commands() override; - virtual void replace_on_next_command() override; - - virtual void wait_for_all(const Cancellable* cancellable) override; - - -public: - // Superscalar Commands (the "ssf" framework) - - virtual void issue_barrier(const Cancellable* cancellable) override{ - ControllerWithScheduler::issue_barrier(cancellable); - } - virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ - ControllerWithScheduler::issue_nop(cancellable, duration); - } - - virtual void issue_buttons( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - Button button - ) override{ - ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); - } - virtual void issue_dpad( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition position - ) override{ - ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); - } - virtual void issue_left_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); - } - virtual void issue_right_joystick( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - uint8_t x, uint8_t y - ) override{ - ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); - } - - virtual void issue_gyro_accel_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_accel_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_x( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_y( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); - } - virtual void issue_gyro_rotate_z( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - int16_t value - ) override{ - ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); - } - - virtual void issue_full_controller_state( - const Cancellable* cancellable, - Milliseconds hold, - Button button, - DpadPosition position, - uint8_t left_x, uint8_t left_y, - uint8_t right_x, uint8_t right_y - ) override{ - ControllerWithScheduler::issue_full_controller_state( - cancellable, - hold, - button, - position, - left_x, left_y, - right_x, right_y - ); - } - - -public: - // High speed RPCs. - - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button); - } - virtual void issue_mash_button( - const Cancellable* cancellable, - Milliseconds duration, - Button button0, Button button1 - ) override{ - ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); - } - virtual void issue_mash_AZs( - const Cancellable* cancellable, - Milliseconds duration - ) override{ - ControllerWithScheduler::issue_mash_AZs(cancellable, duration); - } - virtual void issue_system_scroll( - const Cancellable* cancellable, - Milliseconds delay, Milliseconds hold, Milliseconds cooldown, - DpadPosition direction // Diagonals not allowed. - ) override{ - ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); - } - - -private: - virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; - - void send_diff( - const ProControllerState& old_state, - const ProControllerState& new_state - ); - void thread_body(); - - -private: - SysbotBase::TcpSysbotBase_Connection& m_connection; - - std::atomic m_stopping; - bool m_replace_on_next; - - struct Command{ - ProControllerState state; - Milliseconds duration; - }; - CircularBuffer m_command_queue; - - // WallClock::max() means the queue is empty. - // WallClock::min() means the state has suddently changed. - WallClock m_next_state_change; - - std::condition_variable m_cv; - std::thread m_dispatch_thread; -}; - - - - -} -} -#endif +/* Nintendo Switch Pro Controller (SysbotBase) + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H +#define PokemonAutomation_NintendoSwitch_ProController_SysbotBase_H + +#include +#include "Common/Cpp/Containers/CircularBuffer.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_VirtualControllerState.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerWithScheduler.h" +#include "SysbotBase_Connection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class ProController_SysbotBase final : + public ProController, + public ControllerWithScheduler +{ +public: + using ContextType = ProControllerContext; + + static constexpr size_t QUEUE_SIZE = 4; + + +public: + ProController_SysbotBase( + Logger& logger, + SysbotBase::TcpSysbotBase_Connection& connection + ); + ~ProController_SysbotBase(); + void stop(); + + +public: + virtual ControllerType controller_type() const override{ + return ControllerType::NintendoSwitch_WiredProController; + } + virtual const ControllerFeatures& controller_features() const override; + virtual ControllerPerformanceClass performance_class() const override{ + return ControllerPerformanceClass::SysbotBase; + } + + virtual Milliseconds ticksize() const override{ + return Milliseconds::zero(); + } + virtual Milliseconds cooldown() const override{ + return Milliseconds(150); + } + virtual Milliseconds timing_variation() const override{ + return ConsoleSettings::instance().TIMING_OPTIONS.SYSBOTBASE; + } + virtual bool atomic_multibutton() const override{ + return false; + } + + +public: + virtual Logger& logger() override{ + return m_logger; + } + virtual RecursiveThrottler& logging_throttler() override{ + return m_logging_throttler; + } + virtual bool is_ready() const override{ + return m_connection.is_ready(); + } + + +public: + virtual void cancel_all_commands() override; + virtual void replace_on_next_command() override; + + virtual void wait_for_all(const Cancellable* cancellable) override; + + +public: + // Superscalar Commands (the "ssf" framework) + + virtual void issue_barrier(const Cancellable* cancellable) override{ + ControllerWithScheduler::issue_barrier(cancellable); + } + virtual void issue_nop(const Cancellable* cancellable, Milliseconds duration) override{ + ControllerWithScheduler::issue_nop(cancellable, duration); + } + + virtual void issue_buttons( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + Button button + ) override{ + ControllerWithScheduler::issue_buttons(cancellable, delay, hold, cooldown, button); + } + virtual void issue_dpad( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition position + ) override{ + ControllerWithScheduler::issue_dpad(cancellable, delay, hold, cooldown, position); + } + virtual void issue_left_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_left_joystick(cancellable, delay, hold, cooldown, x, y); + } + virtual void issue_right_joystick( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + uint8_t x, uint8_t y + ) override{ + ControllerWithScheduler::issue_right_joystick(cancellable, delay, hold, cooldown, x, y); + } + + virtual void issue_gyro_accel_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_accel_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_accel_z(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_x( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_x(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_y( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_y(cancellable, delay, hold, cooldown, value); + } + virtual void issue_gyro_rotate_z( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + int16_t value + ) override{ + ControllerWithScheduler::issue_gyro_rotate_z(cancellable, delay, hold, cooldown, value); + } + + virtual void issue_full_controller_state( + const Cancellable* cancellable, + Milliseconds hold, + Button button, + DpadPosition position, + uint8_t left_x, uint8_t left_y, + uint8_t right_x, uint8_t right_y + ) override{ + ControllerWithScheduler::issue_full_controller_state( + cancellable, + hold, + button, + position, + left_x, left_y, + right_x, right_y + ); + } + + +public: + // High speed RPCs. + + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button); + } + virtual void issue_mash_button( + const Cancellable* cancellable, + Milliseconds duration, + Button button0, Button button1 + ) override{ + ControllerWithScheduler::issue_mash_button(cancellable, duration, button0, button1); + } + virtual void issue_mash_AZs( + const Cancellable* cancellable, + Milliseconds duration + ) override{ + ControllerWithScheduler::issue_mash_AZs(cancellable, duration); + } + virtual void issue_system_scroll( + const Cancellable* cancellable, + Milliseconds delay, Milliseconds hold, Milliseconds cooldown, + DpadPosition direction // Diagonals not allowed. + ) override{ + ControllerWithScheduler::issue_system_scroll(cancellable, delay, hold, cooldown, direction); + } + + +private: + virtual void push_state(const Cancellable* cancellable, WallDuration duration) override; + + void send_diff( + const ProControllerState& old_state, + const ProControllerState& new_state + ); + void thread_body(); + + +private: + SysbotBase::TcpSysbotBase_Connection& m_connection; + + std::atomic m_stopping; + bool m_replace_on_next; + + struct Command{ + ProControllerState state; + Milliseconds duration; + }; + CircularBuffer m_command_queue; + + // WallClock::max() means the queue is empty. + // WallClock::min() means the state has suddently changed. + WallClock m_next_state_change; + + std::condition_variable m_cv; + std::thread m_dispatch_thread; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h index b841d28805..85dd1cb350 100644 --- a/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Controllers/SysbotBase/SysbotBase_SelectorWidget.h @@ -1,72 +1,72 @@ -/* sys-botbase Selector Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H -#define PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H - -#include -#include "Controllers/ControllerDescriptor.h" -#include "Controllers/ControllerSelectorWidget.h" -#include "SysbotBase_Descriptor.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace SysbotBase{ - - - -class TcpSysbotBase_SelectorWidget : public QLineEdit{ -public: - TcpSysbotBase_SelectorWidget( - ControllerSelectorWidget& parent, - const ControllerDescriptor* current - ) - : QLineEdit(&parent) - { -// cout << "TcpSysbotBase()" << endl; - - QSizePolicy policy; - policy.setHorizontalStretch(3); - this->setSizePolicy(policy); - - this->setPlaceholderText("192.168.0.100:6000"); - - if (current == nullptr || current->interface_type != ControllerInterface::TcpSysbotBase){ - std::shared_ptr descriptor = - parent.session().option().get_descriptor_from_cache(ControllerInterface::TcpSysbotBase); - if (!descriptor){ - descriptor.reset(new TcpSysbotBase_Descriptor()); - } - parent.session().set_device(descriptor); - } - this->setText(QString::fromStdString(parent.session().descriptor()->display_name())); - - connect( - this, &QLineEdit::editingFinished, - &parent, [this, &parent](){ - std::shared_ptr selected(new TcpSysbotBase_Descriptor( - this->text().toStdString() - )); - - std::shared_ptr current = parent.session().descriptor(); - if (*current == *selected){ - return; - } - - parent.session().set_device(std::move(selected)); - } - ); - } -}; - - - -} -} -#endif +/* sys-botbase Selector Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H +#define PokemonAutomation_Controllers_SysbotBase_SelectorWidget_H + +#include +#include "Controllers/ControllerDescriptor.h" +#include "Controllers/ControllerSelectorWidget.h" +#include "SysbotBase_Descriptor.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace SysbotBase{ + + + +class TcpSysbotBase_SelectorWidget : public QLineEdit{ +public: + TcpSysbotBase_SelectorWidget( + ControllerSelectorWidget& parent, + const ControllerDescriptor* current + ) + : QLineEdit(&parent) + { +// cout << "TcpSysbotBase()" << endl; + + QSizePolicy policy; + policy.setHorizontalStretch(3); + this->setSizePolicy(policy); + + this->setPlaceholderText("192.168.0.100:6000"); + + if (current == nullptr || current->interface_type != ControllerInterface::TcpSysbotBase){ + std::shared_ptr descriptor = + parent.session().option().get_descriptor_from_cache(ControllerInterface::TcpSysbotBase); + if (!descriptor){ + descriptor.reset(new TcpSysbotBase_Descriptor()); + } + parent.session().set_device(descriptor); + } + this->setText(QString::fromStdString(parent.session().descriptor()->display_name())); + + connect( + this, &QLineEdit::editingFinished, + &parent, [this, &parent](){ + std::shared_ptr selected(new TcpSysbotBase_Descriptor( + this->text().toStdString() + )); + + std::shared_ptr current = parent.session().descriptor(); + if (*current == *selected){ + return; + } + + parent.session().set_device(std::move(selected)); + } + ); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.cpp index a325edf98a..d3195ac75f 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.cpp @@ -1,198 +1,198 @@ -/* Box Draw - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "BoxDraw.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -BoxDraw_Descriptor::BoxDraw_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:BoxDraw", - "Nintendo Switch", "Box Draw", - "", - "Test box coordinates for development.", - FeedbackType::NONE, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -BoxDraw::BoxDraw() - : X("X Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) - , Y("Y Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) - , WIDTH("Width:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) - , HEIGHT("Height:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) - , BOX_COORDINATES(false, "ImageFloatBox coordinates", LockMode::UNLOCK_WHILE_RUNNING, "0.3, 0.3, 0.4, 0.4", "0.3, 0.3, 0.4, 0.4") -{ - PA_ADD_OPTION(X); - PA_ADD_OPTION(Y); - PA_ADD_OPTION(WIDTH); - PA_ADD_OPTION(HEIGHT); - PA_ADD_OPTION(BOX_COORDINATES); -} - -class BoxDraw::DrawnBox : public ConfigOption::Listener, public VideoOverlay::MouseListener{ -public: - ~DrawnBox(){ - detach(); - } - DrawnBox(BoxDraw& parent, VideoOverlay& overlay) - : m_parent(parent) - , m_overlay(overlay) - , m_overlay_set(overlay) - { - // DrawnBox listens to changes in the config option (X, Y, WIDTH, HEIGHT) - // and mouse events on the video overlay layer. - try{ - m_parent.X.add_listener(*this); - m_parent.Y.add_listener(*this); - m_parent.WIDTH.add_listener(*this); - m_parent.HEIGHT.add_listener(*this); - m_parent.BOX_COORDINATES.add_listener(*this); - overlay.add_listener(*this); - }catch (...){ - detach(); - throw; - } - } - virtual void on_config_value_changed(void* object) override{ - { - std::lock_guard lg(m_lock); - m_overlay_set.clear(); - m_overlay_set.add(COLOR_RED, {m_parent.X, m_parent.Y, m_parent.WIDTH, m_parent.HEIGHT}); - } - - if (object == &m_parent.X || object == &m_parent.Y || object == &m_parent.WIDTH || object == &m_parent.HEIGHT){ - m_parent.update_box_coordinates(); - } - else if(object == &m_parent.BOX_COORDINATES){ - m_parent.update_individual_coordinates(); - } - - - } - virtual void on_mouse_press(double x, double y) override{ - // m_parent.WIDTH.set(0); - // m_parent.HEIGHT.set(0); - // m_parent.X.set(x); - // m_parent.Y.set(y); - m_mouse_start.emplace(); - m_mouse_start->first = x; - m_mouse_start->second = y; - } - virtual void on_mouse_release(double x, double y) override{ - m_mouse_start.reset(); - } - virtual void on_mouse_move(double x, double y) override{ - if (!m_mouse_start){ - return; - } - - double xl = m_mouse_start->first; - double xh = x; - double yl = m_mouse_start->second; - double yh = y; - - if (xl > xh){ - std::swap(xl, xh); - } - if (yl > yh){ - std::swap(yl, yh); - } - - m_parent.X.set(xl); - m_parent.Y.set(yl); - m_parent.WIDTH.set(xh - xl); - m_parent.HEIGHT.set(yh - yl); - // m_parent.update_box_coordinates(); - } - -private: - void detach(){ - m_overlay.remove_listener(*this); - m_parent.X.remove_listener(*this); - m_parent.Y.remove_listener(*this); - m_parent.WIDTH.remove_listener(*this); - m_parent.HEIGHT.remove_listener(*this); - m_parent.BOX_COORDINATES.remove_listener(*this); - } - -private: - BoxDraw& m_parent; - VideoOverlay& m_overlay; - VideoOverlaySet m_overlay_set; - std::mutex m_lock; - - std::optional> m_mouse_start; -}; - -void BoxDraw::update_box_coordinates(){ - std::string box_coord_string = std::to_string(X) + ", " + std::to_string(Y) + ", " + std::to_string(WIDTH) + ", " + std::to_string(HEIGHT); - BOX_COORDINATES.set(box_coord_string); -} - -std::vector split(const std::string& str, const std::string& delimiter) { - std::vector tokens; - size_t start = 0; - size_t end = str.find(delimiter); - - while (end != std::string::npos) { - tokens.push_back(str.substr(start, end - start)); - start = end + delimiter.length(); - end = str.find(delimiter, start); - } - - tokens.push_back(str.substr(start)); - return tokens; -} - - -void BoxDraw::update_individual_coordinates(){ - std::string box_coord_string = BOX_COORDINATES; - std::vector all_coords = split(box_coord_string, ", "); - - std::string x_string = all_coords[0]; - std::string y_string = all_coords[1]; - std::string width_string = all_coords[2]; - std::string height_string = all_coords[3]; - - double x_coord = std::stod(x_string); - double y_coord = std::stod(y_string); - double width_coord = std::stod(width_string); - double height_coord = std::stod(height_string); - - // cout << box_coord_string << endl; - // cout << std::to_string(x_coord) << endl; - // cout << std::to_string(y_coord) << endl; - // cout << std::to_string(width_coord) << endl; - // cout << std::to_string(height_coord) << endl; - - X.set(x_coord); - Y.set(y_coord); - WIDTH.set(width_coord); - HEIGHT.set(height_coord); -} - -void BoxDraw::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - update_individual_coordinates(); - DrawnBox drawn_box(*this, env.console.overlay()); - drawn_box.on_config_value_changed(this); - context.wait_until_cancel(); -} - - - - -} -} +/* Box Draw + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "BoxDraw.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +BoxDraw_Descriptor::BoxDraw_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:BoxDraw", + "Nintendo Switch", "Box Draw", + "", + "Test box coordinates for development.", + FeedbackType::NONE, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +BoxDraw::BoxDraw() + : X("X Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) + , Y("Y Coordinate:", LockMode::UNLOCK_WHILE_RUNNING, 0.3, 0.0, 1.0) + , WIDTH("Width:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) + , HEIGHT("Height:", LockMode::UNLOCK_WHILE_RUNNING, 0.4, 0.0, 1.0) + , BOX_COORDINATES(false, "ImageFloatBox coordinates", LockMode::UNLOCK_WHILE_RUNNING, "0.3, 0.3, 0.4, 0.4", "0.3, 0.3, 0.4, 0.4") +{ + PA_ADD_OPTION(X); + PA_ADD_OPTION(Y); + PA_ADD_OPTION(WIDTH); + PA_ADD_OPTION(HEIGHT); + PA_ADD_OPTION(BOX_COORDINATES); +} + +class BoxDraw::DrawnBox : public ConfigOption::Listener, public VideoOverlay::MouseListener{ +public: + ~DrawnBox(){ + detach(); + } + DrawnBox(BoxDraw& parent, VideoOverlay& overlay) + : m_parent(parent) + , m_overlay(overlay) + , m_overlay_set(overlay) + { + // DrawnBox listens to changes in the config option (X, Y, WIDTH, HEIGHT) + // and mouse events on the video overlay layer. + try{ + m_parent.X.add_listener(*this); + m_parent.Y.add_listener(*this); + m_parent.WIDTH.add_listener(*this); + m_parent.HEIGHT.add_listener(*this); + m_parent.BOX_COORDINATES.add_listener(*this); + overlay.add_listener(*this); + }catch (...){ + detach(); + throw; + } + } + virtual void on_config_value_changed(void* object) override{ + { + std::lock_guard lg(m_lock); + m_overlay_set.clear(); + m_overlay_set.add(COLOR_RED, {m_parent.X, m_parent.Y, m_parent.WIDTH, m_parent.HEIGHT}); + } + + if (object == &m_parent.X || object == &m_parent.Y || object == &m_parent.WIDTH || object == &m_parent.HEIGHT){ + m_parent.update_box_coordinates(); + } + else if(object == &m_parent.BOX_COORDINATES){ + m_parent.update_individual_coordinates(); + } + + + } + virtual void on_mouse_press(double x, double y) override{ + // m_parent.WIDTH.set(0); + // m_parent.HEIGHT.set(0); + // m_parent.X.set(x); + // m_parent.Y.set(y); + m_mouse_start.emplace(); + m_mouse_start->first = x; + m_mouse_start->second = y; + } + virtual void on_mouse_release(double x, double y) override{ + m_mouse_start.reset(); + } + virtual void on_mouse_move(double x, double y) override{ + if (!m_mouse_start){ + return; + } + + double xl = m_mouse_start->first; + double xh = x; + double yl = m_mouse_start->second; + double yh = y; + + if (xl > xh){ + std::swap(xl, xh); + } + if (yl > yh){ + std::swap(yl, yh); + } + + m_parent.X.set(xl); + m_parent.Y.set(yl); + m_parent.WIDTH.set(xh - xl); + m_parent.HEIGHT.set(yh - yl); + // m_parent.update_box_coordinates(); + } + +private: + void detach(){ + m_overlay.remove_listener(*this); + m_parent.X.remove_listener(*this); + m_parent.Y.remove_listener(*this); + m_parent.WIDTH.remove_listener(*this); + m_parent.HEIGHT.remove_listener(*this); + m_parent.BOX_COORDINATES.remove_listener(*this); + } + +private: + BoxDraw& m_parent; + VideoOverlay& m_overlay; + VideoOverlaySet m_overlay_set; + std::mutex m_lock; + + std::optional> m_mouse_start; +}; + +void BoxDraw::update_box_coordinates(){ + std::string box_coord_string = std::to_string(X) + ", " + std::to_string(Y) + ", " + std::to_string(WIDTH) + ", " + std::to_string(HEIGHT); + BOX_COORDINATES.set(box_coord_string); +} + +std::vector split(const std::string& str, const std::string& delimiter) { + std::vector tokens; + size_t start = 0; + size_t end = str.find(delimiter); + + while (end != std::string::npos) { + tokens.push_back(str.substr(start, end - start)); + start = end + delimiter.length(); + end = str.find(delimiter, start); + } + + tokens.push_back(str.substr(start)); + return tokens; +} + + +void BoxDraw::update_individual_coordinates(){ + std::string box_coord_string = BOX_COORDINATES; + std::vector all_coords = split(box_coord_string, ", "); + + std::string x_string = all_coords[0]; + std::string y_string = all_coords[1]; + std::string width_string = all_coords[2]; + std::string height_string = all_coords[3]; + + double x_coord = std::stod(x_string); + double y_coord = std::stod(y_string); + double width_coord = std::stod(width_string); + double height_coord = std::stod(height_string); + + // cout << box_coord_string << endl; + // cout << std::to_string(x_coord) << endl; + // cout << std::to_string(y_coord) << endl; + // cout << std::to_string(width_coord) << endl; + // cout << std::to_string(height_coord) << endl; + + X.set(x_coord); + Y.set(y_coord); + WIDTH.set(width_coord); + HEIGHT.set(height_coord); +} + +void BoxDraw::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + update_individual_coordinates(); + DrawnBox drawn_box(*this, env.console.overlay()); + drawn_box.on_config_value_changed(this); + context.wait_until_cancel(); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.h index 372fa9bc4d..c0f31f7d6b 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/BoxDraw.h @@ -1,52 +1,52 @@ -/* Box Draw - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_BoxDraw_H -#define PokemonAutomation_NintendoSwitch_BoxDraw_H - -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class BoxDraw_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BoxDraw_Descriptor(); -}; - - -// Draw box on the video stream -class BoxDraw : public SingleSwitchProgramInstance{ -public: - BoxDraw(); - - void update_box_coordinates(); - void update_individual_coordinates(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - class DrawnBox; - -private: - FloatingPointOption X; - FloatingPointOption Y; - FloatingPointOption WIDTH; - FloatingPointOption HEIGHT; - StringOption BOX_COORDINATES; -}; - - - - - -} -} -#endif +/* Box Draw + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_BoxDraw_H +#define PokemonAutomation_NintendoSwitch_BoxDraw_H + +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class BoxDraw_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BoxDraw_Descriptor(); +}; + + +// Draw box on the video stream +class BoxDraw : public SingleSwitchProgramInstance{ +public: + BoxDraw(); + + void update_box_coordinates(); + void update_individual_coordinates(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + class DrawnBox; + +private: + FloatingPointOption X; + FloatingPointOption Y; + FloatingPointOption WIDTH; + FloatingPointOption HEIGHT; + StringOption BOX_COORDINATES; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp index ca2bb5ba9f..fca1451ca7 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.cpp @@ -1,68 +1,68 @@ -/* Joycon Test Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "JoyconProgram.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -JoyconProgram_Descriptor::JoyconProgram_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:JoyconProgram", - "Nintendo Switch", "Joycon Program", - "", - "Template for a joycon program.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -JoyconProgram::JoyconProgram(){} -void JoyconProgram::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - - // - // Sample joycon program. - // - // This will start from the grip menu and enter the system settings. - // Note that the joycon is horizontal. - // - // You can press any button, but if it doesn't exist, it won't do anything. - // - // No support for gyro yet. That's coming later. - // - - pbf_move_joystick(context, 64, 64, 10000ms, 0ms); - -#if 0 - pbf_press_button(context, BUTTON_A, 200ms, 2000ms); - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_press_button(context, BUTTON_X, 200ms, 2000ms); -#endif - -} - - - - - - -} -} +/* Joycon Test Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "JoyconProgram.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +JoyconProgram_Descriptor::JoyconProgram_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:JoyconProgram", + "Nintendo Switch", "Joycon Program", + "", + "Template for a joycon program.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +JoyconProgram::JoyconProgram(){} +void JoyconProgram::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + + // + // Sample joycon program. + // + // This will start from the grip menu and enter the system settings. + // Note that the joycon is horizontal. + // + // You can press any button, but if it doesn't exist, it won't do anything. + // + // No support for gyro yet. That's coming later. + // + + pbf_move_joystick(context, 64, 64, 10000ms, 0ms); + +#if 0 + pbf_press_button(context, BUTTON_A, 200ms, 2000ms); + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_press_button(context, BUTTON_X, 200ms, 2000ms); +#endif + +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h index 2df094aa33..5d0c860c23 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/JoyconProgram.h @@ -1,38 +1,38 @@ -/* Joycon Test Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_JoyconProgram_H -#define PokemonAutomation_NintendoSwitch_JoyconProgram_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class JoyconProgram_Descriptor : public SingleSwitchProgramDescriptor{ -public: - JoyconProgram_Descriptor(); -}; - - - -class JoyconProgram : public SingleSwitchProgramInstance{ -public: - JoyconProgram(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -}; - - - - -} -} -#endif - - - +/* Joycon Test Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_JoyconProgram_H +#define PokemonAutomation_NintendoSwitch_JoyconProgram_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class JoyconProgram_Descriptor : public SingleSwitchProgramDescriptor{ +public: + JoyconProgram_Descriptor(); +}; + + + +class JoyconProgram : public SingleSwitchProgramInstance{ +public: + JoyconProgram(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +}; + + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp index 537318b1c6..05fc562ce1 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.cpp @@ -1,184 +1,184 @@ -/* Test Dudunsparce Form Detector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "3rdParty/ONNX/OnnxToolsPA.h" -#include "Common/Cpp/Time.h" -#include "ClientSource/Connection/BotBase.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/Async/InferenceSession.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "TestDudunsparceFormDetector.h" - -#include -#include - -#include - -#include -#include -#include -using std::cout, std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class DudunsparceFormDetector : public VisualInferenceCallback{ -public: - DudunsparceFormDetector(VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - std::string get_label() const { - int detected_label_id = m_detected.load(std::memory_order_acquire); - return labels[detected_label_id]; - } - -private: - VideoOverlaySet m_overlay_set; - std::string model_path; - ImagePixelBox m_pixel_box_1080p; - ImageFloatBox m_float_box; - std::atomic m_detected; - - Ort::Env env; - Ort::RunOptions runOptions; - Ort::Session session; - - const char* labels[3]{"none", "three", "two"}; -}; - - -DudunsparceFormDetector::DudunsparceFormDetector(VideoOverlay& overlay) - : VisualInferenceCallback("DudunsparceFormDetector") - , m_overlay_set(overlay) - , model_path("../../PAMLExperiments/dudunsparce/dudunsparce_form_detector.onnx") - , m_detected(0) - , session(nullptr) -{ - // The input data for the ML model is created by cropping an 1080P frame from Switch - // The crop is at image[500:750, 1500:1750]. - m_pixel_box_1080p = ImagePixelBox(1500, 500, 1750, 750); - m_float_box = pixelbox_to_floatbox(1920, 1080, m_pixel_box_1080p); - - // learned from ONN Runtime example: https://github.com/cassiebreviu/cpp-onnxruntime-resnet-console-app/blob/main/OnnxRuntimeResNet/OnnxRuntimeResNet.cpp - session = Ort::Session(env, str_to_onnx_str(model_path).c_str(), Ort::SessionOptions{nullptr}); -} - -void DudunsparceFormDetector::make_overlays(VideoOverlaySet& items) const {} - -bool DudunsparceFormDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_overlay_set.clear(); - - ImageViewRGB32 cropped_frame = (frame.height() == 1080) ? extract_box_reference(frame, m_pixel_box_1080p) - : extract_box_reference(frame, m_float_box); - cv::Mat cropped_mat = cropped_frame.to_opencv_Mat(); - cv::Mat resized_mat; // resize to the shape for the ML model input - cv::resize(cropped_mat, resized_mat, cv::Size(25, 25)); - cv::Mat resized_mat_gray; - cv::cvtColor(resized_mat, resized_mat_gray, cv::COLOR_BGRA2GRAY); - - // cv::imwrite("./model_input.png", resized_mat_gray); - - cv::Mat float_mat; - resized_mat_gray.convertTo(float_mat, CV_32F, 1./255); - - // ML stuff: prepare ML model input and output - const std::array inputShape = {1, 25, 25}; - const std::array outputShape = {1, 3}; - - std::array modelInput; - std::array modelOutput; - auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU); - auto inputTensor = Ort::Value::CreateTensor(memoryInfo, modelInput.data(), modelInput.size(), inputShape.data(), inputShape.size()); - auto outputTensor = Ort::Value::CreateTensor(memoryInfo, modelOutput.data(), modelOutput.size(), outputShape.data(), outputShape.size()); - - for (int row = 0, p_loc=0; row < 25; row++){ - for(int col = 0; col < 25; col++){ - float p = float_mat.at(row, col); - modelInput[p_loc++] = p; - } - } - - Ort::AllocatorWithDefaultOptions ort_alloc; - Ort::AllocatedStringPtr inputName = session.GetInputNameAllocated(0, ort_alloc); - Ort::AllocatedStringPtr outputName = session.GetOutputNameAllocated(0, ort_alloc); - const std::array inputNames = {inputName.get()}; - const std::array outputNames = {outputName.get()}; - - session.Run(runOptions, inputNames.data(), &inputTensor, 1, outputNames.data(), &outputTensor, 1); - - float max_value = -std::numeric_limits::max(); - int max_value_label = 0; - for (int i = 0; i < 3; i++){ - // cout << labels[i] << ": " << modelOutput[i] << ", "; - if (modelOutput[i] > max_value){ - max_value = modelOutput[i]; - max_value_label = i; - } - } - cout << "Detector dudunsparce form: " << labels[max_value_label] << endl; - m_detected.store(max_value_label); - - return false; -} - - -TestDudunsparceFormDetector_Descriptor::TestDudunsparceFormDetector_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:DudunsparceFormDetector", - "Nintendo Switch", "Test Dudunsparce Form Detector", - "", - "Test ML model on Dudunsparce form in SV box system", - FeedbackType::NONE, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -TestDudunsparceFormDetector::TestDudunsparceFormDetector(){} - - -void TestDudunsparceFormDetector::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - DudunsparceFormDetector detector(env.console.overlay()); - - // ImageRGB32 test_image("../../datasets/Bidoof/images/test/im0005.png"); - // detector.process_frame(test_image, current_time()); - - // return; - // InferenceSession session( - // context, env.console, - // {{detector, std::chrono::milliseconds(100)}} - // ); - // context.wait_until_cancel(); - - std::string last_label = ""; - run_until( - env.console, context, [&](ProControllerContext& context){ - while (true){ - std::string cur_label = detector.get_label(); - if (cur_label != last_label){ - last_label = cur_label; - env.console.overlay().add_log("Detected " + last_label); - } - context.wait_for(std::chrono::milliseconds(100)); - } - }, - {detector}, - std::chrono::milliseconds(100) - ); - - - std::cout << "ML detection test program finished." << std::endl; -} - - -} -} +/* Test Dudunsparce Form Detector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "3rdParty/ONNX/OnnxToolsPA.h" +#include "Common/Cpp/Time.h" +#include "ClientSource/Connection/BotBase.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/Async/InferenceSession.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "TestDudunsparceFormDetector.h" + +#include +#include + +#include + +#include +#include +#include +using std::cout, std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class DudunsparceFormDetector : public VisualInferenceCallback{ +public: + DudunsparceFormDetector(VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + std::string get_label() const { + int detected_label_id = m_detected.load(std::memory_order_acquire); + return labels[detected_label_id]; + } + +private: + VideoOverlaySet m_overlay_set; + std::string model_path; + ImagePixelBox m_pixel_box_1080p; + ImageFloatBox m_float_box; + std::atomic m_detected; + + Ort::Env env; + Ort::RunOptions runOptions; + Ort::Session session; + + const char* labels[3]{"none", "three", "two"}; +}; + + +DudunsparceFormDetector::DudunsparceFormDetector(VideoOverlay& overlay) + : VisualInferenceCallback("DudunsparceFormDetector") + , m_overlay_set(overlay) + , model_path("../../PAMLExperiments/dudunsparce/dudunsparce_form_detector.onnx") + , m_detected(0) + , session(nullptr) +{ + // The input data for the ML model is created by cropping an 1080P frame from Switch + // The crop is at image[500:750, 1500:1750]. + m_pixel_box_1080p = ImagePixelBox(1500, 500, 1750, 750); + m_float_box = pixelbox_to_floatbox(1920, 1080, m_pixel_box_1080p); + + // learned from ONN Runtime example: https://github.com/cassiebreviu/cpp-onnxruntime-resnet-console-app/blob/main/OnnxRuntimeResNet/OnnxRuntimeResNet.cpp + session = Ort::Session(env, str_to_onnx_str(model_path).c_str(), Ort::SessionOptions{nullptr}); +} + +void DudunsparceFormDetector::make_overlays(VideoOverlaySet& items) const {} + +bool DudunsparceFormDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_overlay_set.clear(); + + ImageViewRGB32 cropped_frame = (frame.height() == 1080) ? extract_box_reference(frame, m_pixel_box_1080p) + : extract_box_reference(frame, m_float_box); + cv::Mat cropped_mat = cropped_frame.to_opencv_Mat(); + cv::Mat resized_mat; // resize to the shape for the ML model input + cv::resize(cropped_mat, resized_mat, cv::Size(25, 25)); + cv::Mat resized_mat_gray; + cv::cvtColor(resized_mat, resized_mat_gray, cv::COLOR_BGRA2GRAY); + + // cv::imwrite("./model_input.png", resized_mat_gray); + + cv::Mat float_mat; + resized_mat_gray.convertTo(float_mat, CV_32F, 1./255); + + // ML stuff: prepare ML model input and output + const std::array inputShape = {1, 25, 25}; + const std::array outputShape = {1, 3}; + + std::array modelInput; + std::array modelOutput; + auto memoryInfo = Ort::MemoryInfo::CreateCpu(OrtDeviceAllocator, OrtMemTypeCPU); + auto inputTensor = Ort::Value::CreateTensor(memoryInfo, modelInput.data(), modelInput.size(), inputShape.data(), inputShape.size()); + auto outputTensor = Ort::Value::CreateTensor(memoryInfo, modelOutput.data(), modelOutput.size(), outputShape.data(), outputShape.size()); + + for (int row = 0, p_loc=0; row < 25; row++){ + for(int col = 0; col < 25; col++){ + float p = float_mat.at(row, col); + modelInput[p_loc++] = p; + } + } + + Ort::AllocatorWithDefaultOptions ort_alloc; + Ort::AllocatedStringPtr inputName = session.GetInputNameAllocated(0, ort_alloc); + Ort::AllocatedStringPtr outputName = session.GetOutputNameAllocated(0, ort_alloc); + const std::array inputNames = {inputName.get()}; + const std::array outputNames = {outputName.get()}; + + session.Run(runOptions, inputNames.data(), &inputTensor, 1, outputNames.data(), &outputTensor, 1); + + float max_value = -std::numeric_limits::max(); + int max_value_label = 0; + for (int i = 0; i < 3; i++){ + // cout << labels[i] << ": " << modelOutput[i] << ", "; + if (modelOutput[i] > max_value){ + max_value = modelOutput[i]; + max_value_label = i; + } + } + cout << "Detector dudunsparce form: " << labels[max_value_label] << endl; + m_detected.store(max_value_label); + + return false; +} + + +TestDudunsparceFormDetector_Descriptor::TestDudunsparceFormDetector_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:DudunsparceFormDetector", + "Nintendo Switch", "Test Dudunsparce Form Detector", + "", + "Test ML model on Dudunsparce form in SV box system", + FeedbackType::NONE, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +TestDudunsparceFormDetector::TestDudunsparceFormDetector(){} + + +void TestDudunsparceFormDetector::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + DudunsparceFormDetector detector(env.console.overlay()); + + // ImageRGB32 test_image("../../datasets/Bidoof/images/test/im0005.png"); + // detector.process_frame(test_image, current_time()); + + // return; + // InferenceSession session( + // context, env.console, + // {{detector, std::chrono::milliseconds(100)}} + // ); + // context.wait_until_cancel(); + + std::string last_label = ""; + run_until( + env.console, context, [&](ProControllerContext& context){ + while (true){ + std::string cur_label = detector.get_label(); + if (cur_label != last_label){ + last_label = cur_label; + env.console.overlay().add_log("Detected " + last_label); + } + context.wait_for(std::chrono::milliseconds(100)); + } + }, + {detector}, + std::chrono::milliseconds(100) + ); + + + std::cout << "ML detection test program finished." << std::endl; +} + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h index edef834e82..6946b6be2a 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestDudunsparceFormDetector.h @@ -1,36 +1,36 @@ -/* Test Dudunsparce Form Detector - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - - #ifndef PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H - #define PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H - - #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - - namespace PokemonAutomation{ - namespace NintendoSwitch{ - - - class TestDudunsparceFormDetector_Descriptor : public SingleSwitchProgramDescriptor{ - public: - TestDudunsparceFormDetector_Descriptor(); - }; - - - class TestDudunsparceFormDetector : public SingleSwitchProgramInstance{ - public: - TestDudunsparceFormDetector(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - private: - }; - - - - } - } - #endif // TESTPATHMAKER_H +/* Test Dudunsparce Form Detector + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + + #ifndef PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H + #define PokemonAutomation_NintendoSwitch_TestDudunsparceFormDetector_H + + #include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + + namespace PokemonAutomation{ + namespace NintendoSwitch{ + + + class TestDudunsparceFormDetector_Descriptor : public SingleSwitchProgramDescriptor{ + public: + TestDudunsparceFormDetector_Descriptor(); + }; + + + class TestDudunsparceFormDetector : public SingleSwitchProgramInstance{ + public: + TestDudunsparceFormDetector(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + private: + }; + + + + } + } + #endif // TESTPATHMAKER_H \ No newline at end of file diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp index c92df45383..cd43d49bba 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.cpp @@ -1,1632 +1,1632 @@ -/* Test Program (Computer) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef _WIN64 -#include -#elif defined(__linux) || defined(__APPLE__) -#include -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "CommonTools/OCR/OCR_Routines.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "TestProgramComputer.h" -#include "ClientSource/Libraries/Logging.h" -#include "Common/Cpp/Containers/Pimpl.tpp" - -#include "Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" -#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/Tools/FileDownloader.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "Common/Cpp/Concurrency/PeriodicScheduler.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" -#include "Kernels/Kernels_Alignment.h" -#include "Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h" -#include "Kernels/SpikeConvolution/Kernels_SpikeConvolution.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "Kernels/AudioStreamConversion/AudioStreamConversion.h" -#include "Common/Cpp/StreamConverters.h" -#include "CommonFramework/AudioPipeline/AudioConstants.h" -#include "CommonFramework/AudioPipeline/AudioStream.h" -#include "3rdParty/nlohmann/json.hpp" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageHSV32.h" -#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" -#include "Common/Cpp/StringTools.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" -#include "Common/Cpp/Options/EnumDropdownDatabase.h" -#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" - -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "Common/Cpp/Containers/BoxSet.h" -#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "Integrations/DiscordWebhook.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "CommonFramework/Environment/Environment.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Qt/TimeQt.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Environment/Environment.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" -#include "PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" -#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "Common/Cpp/Concurrency/Watchdog.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -//#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "Pokemon/Pokemon_StatsCalculation.h" -#include "PokemonSV/Inference/PokemonSV_StatHexagonReader.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h" -#include "PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h" -#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" -#include "Common/Cpp/Containers/CircularBuffer.h" -#include "Common/Cpp/Sockets/ClientSocket.h" -#include "Common/Cpp/Containers/SparseArray.h" - -#ifdef PA_ARCH_x86 -//#include "Kernels/Kernels_x64_SSE41.h" -//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -// #include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h" -// #include "Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h" -//#include "Kernels/Kernels_x64_SSE41.h" -//#include "Kernels/Kernels_x64_AVX2.h" -//#include "Kernels/Kernels_x64_AVX512.h" -//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" -//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" -//#include "Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h" -//#include "Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h" -//#include "Common/Cpp/CpuId/CpuId_x86.h" -//#include "Kernels/ImageScaling/Kernels_ImageScaling_Default.h" -//#include "Kernels/ImageScaling/Kernels_ImageScaling_x64_SSE41.h" -#endif -#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" -//#include "Common/SerialPABotBase/LightweightWallClock_StdChrono.h" -#include "Common/Cpp/Options/MacAddressOption.h" -#include "CommonTools/Images/ImageFilter.h" - - -//#include -#include -#include - - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -using namespace Kernels; -using namespace Kernels::Waterfill; -using namespace Pokemon; - - -TestProgramComputer_Descriptor::TestProgramComputer_Descriptor() - : ComputerProgramDescriptor( - "Computer:TestProgram", - "Computer", "Test Program (Computer)", - "", - "Test Program" - ) -{} -TestProgramComputer::TestProgramComputer() - : STATIC_TEXT("test text") - , SCREEN_WATCHER("Capture Box", 0, 0, 1, 1) - , MAC_ADDRESS(LockMode::UNLOCK_WHILE_RUNNING, 6, nullptr) -{ - PA_ADD_OPTION(STATIC_TEXT); -// PA_ADD_OPTION(SCREEN_WATCHER); - PA_ADD_OPTION(MAC_ADDRESS); -} - -WallClock REFERENCE = current_time(); - - -using namespace Kernels; - -template -void print(const Type* ptr, size_t len){ - cout << "{"; - bool first = true; - for (size_t c = 0; c < len; c++){ - if (!first){ - cout << ", "; - } - first = false; - if (sizeof(Type) == 1){ - cout << (uint32_t)ptr[c]; - }else{ - cout << ptr[c]; - } - } - cout << "}" << endl; -} - - - - - -class WatchdogTest0 : public WatchdogCallback{ - virtual void on_watchdog_timeout(){ - cout << "run() - start" << endl; -#if defined(__linux) || defined(__APPLE__) - sleep(10); -#else - Sleep(10000); -#endif - cout << "run() - end" << endl; - } -}; -class WatchdogTest1 : public WatchdogCallback{ - virtual void on_watchdog_timeout(){ - cout << "run()" << endl; - } -}; - - - - -template -class CheckedObject{ -public: - template - CheckedObject(Args&&... args) - : m_object(std::forward(args)...) - { - m_instances++; - } - ~CheckedObject(){ - m_instances--; - } - - operator const Type&() const{ - return m_object; - } - operator Type&(){ - return m_object; - } - - static size_t instances(){ - return m_instances.load(std::memory_order_relaxed); - } - - friend std::ostream& operator<<(std::ostream& stream, const CheckedObject& x){ - return stream << (const Type&)x; - } - -private: - static std::atomic m_instances; - Type m_object; - LifetimeSanitizer m_lifetime_santizer; -}; - -template -std::atomic CheckedObject::m_instances(0); - - - - - -#if 0 -struct RequestManagerConfig{ - using ClockType = LightweightWallClock_StdChrono; - using ClockDuration = LightweightDuration_StdChrono; - using SeqnumType = seqnum_t; - using MessageSizeType = uint8_t; - static constexpr size_t MAX_MESSAGE_SIZE = 64; - static constexpr size_t QUEUE_SIZE = 64; -}; -#endif - - - - - - - - -void TestProgramComputer::program(ProgramEnvironment& env, CancellableScope& scope){ - using namespace Kernels; - using namespace NintendoSwitch; -// using namespace NintendoSwitch::PokemonSwSh; - using namespace NintendoSwitch::PokemonSV; - using namespace Pokemon; - using namespace NintendoSwitch::PokemonSwSh::MaxLairInternal; - - using namespace std::chrono_literals; - - - - - - -#if 0 - { - CommandQueue queue; - - queue.enqueue_command(ControllerCommand{ - .seqnum = 10, - .milliseconds = 1000, - .state = ControllerState{ - .buttons = 123, - } - }); - queue.enqueue_command(ControllerCommand{ - .seqnum = 11, - .milliseconds = 2000, - .state = ControllerState{ - .buttons = 456, - } - }); - - scope.wait_for(60s); - } -#endif - -#if 0 - HeapCircularBuffer buffer(10); - - buffer.try_push_back("asdf"); - buffer.try_push_back("qwer"); - buffer.try_push_back("zxcv"); - - cout << buffer[0] << endl; - cout << buffer[1] << endl; - cout << buffer[2] << endl; - cout << "--------------------" << endl; - buffer.pop_front(); - cout << buffer[0] << endl; - cout << buffer[1] << endl; -#endif - -#if 0 - Command command{ - 123, - 100, - 512, - 2000, 3000, - 4000, 5000 - }; - - char str[65] = {}; - command.write_to_hex(str); - cout << str << endl; - memset(&command, 0, sizeof(Command)); - - command.parse_from_hex(str); - - cout << command.milliseconds << endl; - cout << command.buttons << endl; - cout << command.left_joystick_x << endl; - cout << command.left_joystick_y << endl; - cout << command.right_joystick_x << endl; - cout << command.right_joystick_y << endl; -#endif - -#if 0 - ImageRGB32 image("20250503-121259857603.png"); - - image = filter_rgb32_euclidean(image, (uint32_t)COLOR_PURPLE, 100, COLOR_RED, true); - image.save("temp.png"); -#endif - - - - -#if 0 - uint8_t address[] = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}; - - std::string str = write_MAC_address(6, address); - cout << str << endl; - - parse_MAC_address(6, address, str); - str = write_MAC_address(6, address); - cout << str << endl; -#endif - -#if 0 - SparseArray data{ - {100, "0123456789"}, - {120, {'a', 0x20, 'd'}}, - }; -// data.set_data(100, "0123456789", 10); -// data.set_data(120, "asdfzxcv", 8); - - cout << data.dump() << endl; -// data.set_data(110, 12, "qwerqwerqwer"); - - std::string read(12, '?'); - data.read(109, 12, read.data()); - - cout << "read = " << read << endl; - -// data.print(); - - -#if 0 - ClientSocket socket; - socket.connect("192.168.1.66", 6000); -// socket.connect("192.168.1.66", 6000); - - scope.wait_for(std::chrono::seconds(60)); -#endif - -#endif - - -#if 0 - int* ptr = nullptr; - cout << ptr[0] << endl; -#endif - -#if 0 - { - CircularBuffer> buffer(4); - - cout << "Dumping:" << endl; - for (size_t c = 0; c < buffer.size(); c++){ - cout << " " << buffer[c] << endl; - } - - buffer.push_back("123"); - buffer.push_back("456"); - buffer.push_back("789"); - - - cout << "Dumping:" << endl; - for (size_t c = 0; c < buffer.size(); c++){ - cout << " " << buffer[c] << endl; - } - - buffer.pop_front(); - - cout << "Dumping:" << endl; - for (size_t c = 0; c < buffer.size(); c++){ - cout << " " << buffer[c] << endl; - } - - buffer.push_back("asd"); - buffer.push_back("sdf"); - - cout << "Dumping:" << endl; - for (size_t c = 0; c < buffer.size(); c++){ - cout << " " << buffer[c] << endl; - } - - cout << "Instances = " << CheckedObject::instances() << endl; - } - cout << "Instances = " << CheckedObject::instances() << endl; -#endif - - - -#if 0 - send_program_notification_with_file( - env, NOTIFICATION_PROGRAM_FINISH, COLOR_BLUE, - "test notification", - {}, - "", - "test.txt" - ); -#endif - - -// ImageRGB32 image("Screenshots/20241128-152424608121.png"); -#if 0 - send_error_report( - env.logger(), - env.program_info(), - "testtest", - {{"title", "message"}}, - image, -// ImageRGB32(), - {"test.txt", "test2.txt"} - ); -#endif - - -#if 0 - std::random_device rndsource; - std::minstd_rand rndgen(rndsource()); - std::uniform_real_distribution dist(0, 1.0); - - cout << dist(rndgen) << endl; - cout << dist(rndgen) << endl; - cout << dist(rndgen) << endl; - cout << dist(rndgen) << endl; -#endif - -#if 0 - PokemonSV::DateSeed data = PokemonSV::ItemPrinter::calculate_seed_prizes(2346161588); - - cout << "Regular:" << endl; - for (auto& item : data.regular){ - cout << " " << item << endl; - } - - cout << "Item Bonus:" << endl; - for (auto& item : data.item_bonus){ - cout << " " << item << endl; - } - - cout << "Ball Bonus:" << endl; - for (auto& item : data.ball_bonus){ - cout << " " << item << endl; - } -#endif - - -// make_item_prize_table(); -// make_ball_prize_table(); - -#if 0 - { - std::string path = "PokemonSV/ItemPrinterItems.json"; - JsonValue json = load_json_file(RESOURCE_PATH() + path); - const JsonArray& array = json - .to_object_throw(path) - .get_array_throw("Table", path); - make_prize_table(array, path, 10001); - } -#endif - -// make_prize_table(, 10001); - - -#if 0 - JsonValue json = load_json_file("ItemPrinterOCR.json"); - JsonObject& obj = json.get_object_throw(); - JsonObject& jpn0 = obj.get_object_throw("jpn"); - JsonObject& jpn1 = obj.get_object_throw("jpn-t"); - - for (auto& item : jpn0){ - cout << "testing: " << item.first << endl; - auto iter = jpn1.find(item.first); - if (iter == jpn1.end()){ - throw "missing name"; - } - JsonArray& arr0 = item.second.get_array_throw(); - JsonArray& arr1 = iter->second.get_array_throw(); - if (arr0[0].get_string_throw() != arr1[0].get_string_throw()){ - cout << "mismatch found: " << arr0[0].get_string_throw() << " : " << arr1[0].get_string_throw() << endl; - } - } - #endif - - - -#if 0 - ImageRGB32 image("screenshot-20240605-000823122811.png"); - - PokemonSwSh::MaxLairInternal::PokemonSelectMenuDetector detector(false); - cout << detector.detect(image) << endl; - -// BattleMenuDetector detector; -// cout << detector.detect(image) << endl; -#endif - - -#if 0 - ImageRGB32 image("20231120-221849973351.png"); - - - PokemonBDSP::ShinySparkleSetBDSP detector; - - ImageViewRGB32 wild = extract_box_reference(image, ImageFloatBox{0.4, 0.02, 0.60, 0.93}); - ImageViewRGB32 self = extract_box_reference(image, ImageFloatBox{0.0, 0.1, 0.8, 0.8}); - - wild.save("wild.png"); - wild.save("self.png"); - - detector.read_from_image(wild); - cout << detector.to_str() << endl; - - detector.read_from_image(self); - cout << detector.to_str() << endl; -#endif - - -// ImageRGB32 image("screenshot-20231016-130205783594.png"); -// PokemonSummaryDetector detector; -// cout << detector.detect(image) << endl; - - - -#if 0 - ImageRGB32 image("screenshot-20231005-203932147068.png"); - SummaryStatsReader reader; -// cout << detector.detect(image) << endl; - auto nature = reader.read_nature(env.logger(), image); - - cout << (int)nature.attack << endl; - cout << (int)nature.defense << endl; - cout << (int)nature.spatk << endl; - cout << (int)nature.spdef << endl; - cout << (int)nature.speed << endl; -#endif - - - -#if 0 - uint8_t low_iv; - uint8_t high_iv; - - bool ok = calc_iv_range( - low_iv, high_iv, - false, 55, 100, 0, - 126, NatureAdjustment::NEGATIVE - ); - - cout << "ok = " << ok << endl; - cout << "low = " << (int)low_iv << endl; - cout << "high = " << (int)high_iv << endl; -#endif - - - - -// ImageRGB32 image("screenshot-20230912-194941389243.png"); -// NintendoSwitch::PokemonSV::PokemonSummaryDetector detector; -// cout << detector.detect(image) << endl; - - -#if 0 - ImageRGB32 image("20230726-213101330270-ProgramHang.png"); - NintendoSwitch::PokemonSwSh::MaxLairInternal::BattleMenuDetector detector; - cout << detector.detect(image) << endl; -#endif - -// SandwichRecipeNumberDetector detector(env.logger()); -// size_t recipe_IDs[6]; -// detector.detect_recipes(image, recipe_IDs); - -#if 0 - { - ImageRGB32 image("20230630-084354220241.jpg"); - TeraLobbyReader reader(env.logger(), env.inference_dispatcher()); - reader.read_names(env.logger(), {Language::Japanese}, image); - } - { - ImageRGB32 image("name1.png"); - cout << OCR::ocr_read(Language::Japanese, image) << endl; - } -#endif - - -// ImageRGB32 image("20230427-200550386826-OperationFailedException.png"); - -// NintendoSwitch::HomeMenuDetector detector; -// cout << detector.detect(image) << endl; - - -#if 0 - ImageRGB32 image("20230323-082240823181-OperationFailedException.png"); - - TeraCatchDetector detector(COLOR_RED); - cout << detector.detect(image) << endl; -#endif - - - -#if 0 - WatchdogTest0 callback0; - WatchdogTest1 callback1; - - Watchdog watchdog; - watchdog.add(callback0, std::chrono::seconds(20)); - watchdog.add(callback1, std::chrono::seconds(2)); - - watchdog.delay(callback0, current_time()); - for (size_t c = 0; c < 5; c++){ - scope.wait_for(std::chrono::seconds(1)); - cout << "delaying..." << endl; - watchdog.delay(callback0); - } - - cout << "removing 0 start" << endl; - watchdog.remove(callback1); - cout << "removing 0... end" << endl; - - cout << "removing 1... start" << endl; - watchdog.remove(callback0); - cout << "removing 1... end" << endl; - - scope.wait_for(std::chrono::seconds(60)); -#endif -#if 0 - ImageRGB32 image("screenshot-20230303-225044564794.png"); - - BlackBorderDetector detector; - cout << detector.detect(image) << endl; -#endif - - -// send_program_telemetry(env.logger(), true, COLOR_RED, env.program_info(), "test", {}, ""); - - - - - -#if 0 - ImageRGB32 image("Screenshots/screenshot-20230228-050626316922.png"); - - NewsDetector detector; - cout << detector.detect(image) << endl; -#endif - - - - - - -#if 0 - ImageRGB32 image("test-0-image.png"); - - Color background(4294954240); - - for (size_t c = 0; c < 5; c++){ - ImageRGB32 sprite("test-" + std::to_string(c) + "-sprite.png"); - PixelSums sums; - pixel_sum_sqr( - sums, image.width(), image.height(), - image.data(), image.bytes_per_row(), - sprite.data(), sprite.bytes_per_row() - ); - cout << sums.count << endl; - cout << ImageMatch::pixel_RMSD(sprite, image, background) << endl; - } -#endif - - - - -// cout << get_ingredient_name("green-bell-pepper").display_name() << endl; - -#if 0 - ImageFloatBox ore_quantity(0.945, 0.010, 0.0525, 0.050); - - ImageRGB32 image("screenshot-20230220-232711115537.png"); - ImageRGB32 filtered = to_blackwhite_rgb32_range( - extract_box_reference(image, ore_quantity), - 0xff808080, 0xffffffff, true - ); - - filtered = pad_image(filtered, 10, 0xffffffff); - - filtered.save("test.png"); - - OCR::read_number(env.logger(), filtered); -#endif - -// OperationFailedException::fire(env.logger(), "asdf"); -// OperationFailedException::fire(env.logger(), "asdf", std::make_shared("20221118-024539201323.jpg")); -// throw ProgramFinishedException(); -// throw FatalProgramException(env.logger(), "test"); - - -// send_program_telemetry(env.logger(), true, COLOR_RED, env.program_info(), "Test", {}, ""); - -// throw ProgramFinishedException(env.logger(), "", std::make_shared("TeraCode-S-chi-original.png")); - - -// load_pokemon_slug_json_list(); - - - -#if 0 - WallClock now = current_time(); - - - DiscontiguousTimeTracker tracker; - tracker.add_block(now - Seconds(30), now - Seconds(19)); - tracker.add_block(now - Seconds(10), now - Seconds(5)); - - auto duration = tracker.last_window_in_realtime(now, Seconds(10)); - - cout << std::chrono::duration_cast(duration).count() << endl; -#endif - - -#if 0 - ImageRGB32 image("20230219-200200879508-OperationFailedException.png"); - OverworldDetector detector(COLOR_RED); - cout << detector.detect(image) << endl; -#endif - - -#if 0 - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - env.logger(), Language::Korean, - ImageRGB32("../../TrainingData/PokemonNameOCR/PokemonNameOCR (Kim-SwShPokedex-1)/kor/joltik-20210618-212232.png"), - OCR::BLACK_OR_WHITE_TEXT_FILTERS() - ); - - for (auto& item : result.results){ - cout << item.first << ": " << item.second.token << endl; - } -#endif - -#if 0 - for (int c = (int)Language::English; c < (int)Language::EndOfList; c++){ - Language language = (Language)c; - - JsonObject json; - - for (const std::string& slug : NATIONAL_DEX_SLUGS()){ - JsonArray array; - array.push_back(get_pokemon_name(slug).display_name(language)); - json[slug] = std::move(array); - } - - json.dump("PokemonOCR-" + language_data(language).code + ".json"); - } -#endif - - -#if 0 - ImageRGB32 image("screenshot-20230211-223602354229.png"); - SweatBubbleDetector detector(COLOR_RED, {0, 0, 1, 1}); - cout << detector.detect(image) << endl; -#endif - - -#if 0 - ImageRGB32 image("test-0.png"); -// ImageRGB32 filtered = filter_rgb32_range(image, 0xff000000, 0xffffff90, Color(0x00000000), true); -// filtered.save("filtered.png"); - - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - if (9 < r && r < 50 && 19 < c && c < 57){ - continue; - } - uint32_t pixel = image.pixel(c, r); - uint32_t red = (pixel >> 16) & 0xff; - uint32_t green = (pixel >> 8) & 0xff; - uint32_t blue = (pixel >> 0) & 0xff; - uint32_t total = red + green + blue; - if (total < 720){ - image.pixel(c, r) = 0; - }else{ - image.pixel(c, r) = 0xffffffff; - } - } - } - image.save("filtered.png"); -#endif - -#if 0 - ImageRGB32 image("screenshot-20230211-223602354229.png"); - auto matrix = compress_rgb32_to_binary_range(image, 0xffc0c0c0, 0xffffffff); - - std::vector objects = Waterfill::find_objects_inplace(matrix, 100); - cout << objects.size() << endl; - - for (size_t c = 0; c < objects.size(); c++){ - extract_box_reference(image, objects[c]).save("test-" + std::to_string(c) + ".png"); - } -#endif - - -#if 0 - ImageRGB32 image("Screenshots/screenshot-20230209-061452037331.png"); - - ImageRGB32 filtered = filter_rgb32_range(image, 0xff000040, 0xff8080ff, Color(0xffff0000), true); - filtered.save("test.png"); -#endif - -#if 0 - ImageRGB32 image("Screenshots/screenshot-20230208-012850704172.png"); - - OverworldDetector detector; - cout << detector.detect(image) << endl; -#endif - - -#if 0 -// ImageRGB32 image("Screenshots/screenshot-20230206-023520852521.png"); - ImageRGB32 image("Screenshots/screenshot-20230206-022329387691.png"); -// ImageRGB32 image("LetsGoKill.png"); - - LetsGoKillDetector detector(COLOR_RED); -// LetsGoKillDetector detector(COLOR_RED, {0, 0, 1, 1}); - detector.detect(image); -#endif - - -#if 0 - send_program_notification_with_file( - env, - NOTIFICATION_ERROR_RECOVERABLE, - Color(0), - "Join Report", - {}, "", - "name-of-text-file.txt" - ); - - - - ImageRGB32 image("screenshot-20230130-150721112888.png"); - SomethingInBoxSlotDetector detector(COLOR_RED); - - cout << detector.detect(image) << endl; -#endif - -#if 0 - FILETIME idle_time, kernel_time, user_time; - GetSystemTimes(&idle_time, &kernel_time, &user_time); -// cout << << endl; -// cout << << endl; -// cout << << endl; - - uint64_t start_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); - uint64_t start_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); - uint64_t start_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); - - scope.wait_for(std::chrono::seconds(4)); - - GetSystemTimes(&idle_time, &kernel_time, &user_time); -// cout << << endl; -// cout << << endl; -// cout << << endl; - - uint64_t end_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); - uint64_t end_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); - uint64_t end_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); - - cout << (end_idle - start_idle) * 100 / 1000000000. << endl; - cout << (end_kernel - start_kernel) * 100 / 1000000000. << endl; - cout << (end_user - start_user) * 100 / 1000000000. << endl; -#endif - -#if 0 - uint32_t src[4 * 4] = { - 0xff0a0a0a, 0xff141414, 0xff1e1e1e, 0xff282828, - 0xff646464, 0xff646464, 0xff646464, 0xff646464, - 0xff646464, 0xff646464, 0xff646464, 0xff646464, - 0xff646464, 0xff646464, 0xff646464, 0xff646464, - }; - uint32_t dst[4 * 4] = {}; - - print((uint8_t*)src + 0*16, 16); - print((uint8_t*)src + 1*16, 16); - print((uint8_t*)src + 2*16, 16); - print((uint8_t*)src + 3*16, 16); - -#if 0 - TileBuilder builder( - dst, 3 * sizeof(uint32_t), 3, 3, - src, 4 * sizeof(uint32_t), 4, 4 - ); - - FloatPixelTile tile; - size_t dst_col = 0; - size_t src_col = 0; - builder.build_tile(tile, dst_col, 0, src_col); - cout << tile << endl; - - FloatPixelWord accumulator; - size_t row = 0; - builder.write_tile(accumulator, row, 0, tile, 0); -#endif - - scale_image_Default( - dst, 4 * sizeof(uint32_t), 4, 4, - src, 4 * sizeof(uint32_t), 4, 4 - ); - - - print((uint8_t*)dst + 0*16, 16); - print((uint8_t*)dst + 1*16, 16); - print((uint8_t*)dst + 2*16, 16); - print((uint8_t*)dst + 3*16, 16); - -// print((uint8_t*)dst + 0*12, 12); -// print((uint8_t*)dst + 1*12, 12); -// print((uint8_t*)dst + 2*12, 12); - - -#if 0 - float dst[10]; - float src[6] = {1, 2, 3, 4, 5}; - - - scale_row(dst, 8, src, 5); - print(dst, 8); -#endif -#endif - - -// env.log("crash coming...", COLOR_RED); -// cout << *(char*)nullptr << endl; - - -#if 0 - StatAccumulatorI32 stats; - - for (size_t c = 0; c < 1000; c++){ - scope.throw_if_cancelled(); - - auto start = current_time(); - env.log(std::to_string(c)); - auto end = current_time(); - stats += std::chrono::duration_cast(end - start).count(); - } - cout << stats.dump("us", 1) << endl; -#endif - - -#if 0 - ImageRGB32 image("TeraCode-S-chi-original.png"); - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - uint32_t pixel = image.pixel(c, r); - uint32_t sum = pixel & 0xff; - sum += (pixel >> 16) & 0xff; - sum += (pixel >> 8) & 0xff; - if (sum > 400){ - image.pixel(c, r) = 0; - } - } - } - image.save("TeraCode-S-chi.png"); -#endif - - - -#if 0 - { - ImageRGB32 image("TeraCodeTest-50.png"); - TeraLobbyReader reader; - reader.raid_code(env.logger(), image); - } - { - ImageRGB32 image("TeraCodeTest-S0.png"); - TeraLobbyReader reader; - reader.raid_code(env.logger(), image); - } - { - ImageRGB32 image("TeraCodeTest-S1.png"); - TeraLobbyReader reader; - reader.raid_code(env.logger(), image); - } -#endif - - - - - - -#if 0 - ImageRGB32 image("20230107-053814058280-FREESandwichHandNotDetected.png"); - - SandwichHandLocator detector(SandwichHandType::FREE, {0, 0, 1, 1}); - auto ret = detector.detect(image); - cout << ret.first << " " << ret.second << endl; -#endif - - - -#if 0 -// cout << current_time() << endl; - - std::string str = to_utc_time_str(current_time()); - cout << str << endl; - - WallClock time = parse_utc_time_str(str); - cout << to_utc_time_str(time) << endl; - -// parse_utc_time_str(str); -#endif - -#if 0 - ThreadHandle handle = current_thread_handle(); - cout << thread_cpu_time(handle).count() << endl; - - WallClock start = current_time(); - while (current_time() - start < std::chrono::seconds(1)); - - cout << thread_cpu_time(handle).count() << endl; -#endif - - -#if 0 - ImageRGB32 image("20221230-232826566125-BoxSystemNotDetected.png"); - BoxDetector detector; -// cout << detector.detect(image) << endl; - - auto ret = detector.detect_location(image); - cout << (int)ret.first << " : " << (int)ret.second.row << ", " << (int)ret.second.col << endl; - - GradientArrowDetector arrow(COLOR_RED, GradientArrowType::DOWN, {0.240, 0.160, 0.380, 0.550}); - cout << arrow.detect(image) << endl; -#endif - - -#if 0 - ImageRGB32 image("20221230-075353892425-BoxSystemNotDetected.png"); - BoxDetector detector; -// cout << detector.detect(image) << endl; - - auto ret = detector.detect_location(image); - cout << (int)ret.first << " : " << (int)ret.second.row << ", " << (int)ret.second.col << endl; - - GradientArrowDetector arrow(COLOR_RED, GradientArrowType::DOWN, {0.140, 0.150, 0.050, 0.700}); - cout << arrow.detect(image) << endl; -#endif - - - -#if 0 - ImageRGB32 image("ZeroGateNightBike_2_True.png"); - OverworldDetector detector; - cout << detector.detect(image) << endl; -#endif - -#if 0 - ImageRGB32 image("screenshot-20221219-201912436404.png"); - PromptDialogDetector prompt(COLOR_RED, {0.623, 0.530, 0.243, 0.119}); - cout << prompt.detect(image) << endl; -#endif - - -#if 0 - ImageRGB32 image("20221219-140347621956.jpg"); - TeraLobbyReader reader; - auto names = reader.read_names(env.logger(), {Language::English}, true, image); -#endif -#if 0 - for (size_t row = 0; row < image.height(); row++){ - for (size_t col = 0; col < image.width(); col++){ - uint32_t pixel = image.pixel(col, row); - uint32_t r = (pixel >> 16) & 0xff; - uint32_t g = (pixel >> 8) & 0xff; - uint32_t b = (pixel >> 0) & 0xff; -#if 0 - if (b > 2*r + 10 || b > 2*g + 10){ - pixel = 0xffffffff; - } -#endif -#if 1 - if (r + g + b < 150){ - pixel = 0xffffffff; - } -#endif - image.pixel(col, row) = pixel; - } - } - image.save("test.png"); -#endif - - -#if 0 - MultiLanguageJoinTracker tracker; - tracker.add(Language::English, "Alice", "RNS308"); - tracker.add(Language::English, "Alice", "RNS308"); - tracker.add(Language::English, "Alice", "RNS308"); - tracker.add(Language::English, "Dhruv", "UCCJ9H"); - tracker.add(Language::English, "Dhruv", "EKNQY9"); - tracker.add(Language::English, "Gael", "X89986"); - tracker.add(Language::English, "Gael", "X89986"); - tracker.add(Language::ChineseSimplified, "Gael", "X89986"); - tracker.add(Language::ChineseSimplified, "Gael", "X89986"); - - tracker.dump("test.txt"); -#endif - -#if 0 - cout << tracker.dump() << endl; - - std::ofstream file("test.txt"); - file << tracker.dump(); - file.close(); -#endif - -#if 0 - Integration::DiscordWebhook::send_message( - env.logger(), false, - {"Notifs"}, - "Test Join Tracker output...", - JsonArray(), - std::make_shared("test.txt", false) - ); -#endif - - -#if 0 - ImageRGB32 image("BadArrow.png"); - TeraCatchDetector detector(COLOR_RED); - cout << detector.detect(image) << endl; - - -// extract_box_reference(image, ImageFloatBox{0.95, 0.81, 0.02, 0.06}).save("test.png"); -#endif - - -#if 0 - { - std::string json = FileDownloader::download_file(env.logger(), "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json"); - cout << "Done loading..." << endl; - - std::ofstream file("test.txt"); - file << json; - } -#if 1 - { - JsonValue json = FileDownloader::download_json_file(env.logger(), "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json"); - cout << "Done loading..." << endl; - cout << json.dump() << endl; - } -#endif -#endif - -#if 0 - ScheduledTaskRunner scheduler(env.inference_dispatcher()); - - scheduler.add_event(std::chrono::seconds(5), []{ cout << "5 seconds" << endl; }); - scheduler.add_event(std::chrono::seconds(2), []{ cout << "2 seconds" << endl; }); - scheduler.add_event(std::chrono::seconds(7), []{ cout << "7 seconds" << endl; }); - - scope.wait_for(std::chrono::seconds(100)); -#endif - -#if 0 - BoxSet set; - cout << set.dump() << endl; - - set.insert({10, 20, 15, 25}); - set.insert({11, 19, 13, 27}); - set.insert({12, 18, 13, 27}); - cout << set.dump() << endl; - - auto iter = set.lower_bound_min_y(11); - for (; iter != set.end_min_y(); ++iter){ - cout << iter->first << endl; - } -#endif - -// ImageRGB32 image("SV-Buttons2.png"); -// WhiteButtonDetector detector(WhiteButton::ButtonB, ImageFloatBox{0, 0, 1, 1}); -// detector.detect(image); - - -#if 0 - ImageRGB32 image("SV-Buttons2.png"); - - ImageFloatBox box(0.027, 0.922, .02, .035); - ImageViewRGB32 region = extract_box_reference(image, box); - - region.save("tmp.png"); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff808080, 0xffffffff); - auto objects = Waterfill::find_objects_inplace(matrix, 20); - extract_box_reference(region, objects[0]).save("cropped.png"); -#endif - -// DialogArrowDetector detector({0.45, 0.9, .1, .05}); -// detector.detect(image); - -#if 0 - ImageFloatBox box(0.72, 0.85, 0.02, 0.035); - - ImageViewRGB32 region = extract_box_reference(image, box); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff000000, 0xff7f7fbf); - - cout << matrix.dump() << endl; - - auto arrow = Waterfill::find_objects_inplace(matrix, 20); - extract_box_reference(region, arrow[0]).save("cropped.png"); -#endif - -#if 0 - ImageRGB32 image("SV-BattleMenu.png"); - image.scale_to(1920, 1080); - - GradientArrowDetector detector({0.75, 0.63, 0.05, 0.1}); - detector.detect(image); -#endif - - -#if 0 - ImageRGB32 image("Arrow-Alpha.png"); - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - uint32_t& pixel = image.pixel(c, r); - if (pixel == 0xffffffff){ - pixel = 0; - } - } - } - image.save("Arrow-Alpha2.png"); -#endif - - - - -#if 0 - ImageRGB32 image("SV-BattleMenu.png"); - image.scale_to(1920, 1080); - - ImageViewRGB32 box = extract_box_reference(image, ImageFloatBox({0.75, 0.63, 0.05, 0.1})); - - - PackedBinaryMatrix yellow = compress_rgb32_to_binary_range(box, 0xff808000, 0xffffff7f); - PackedBinaryMatrix blue = compress_rgb32_to_binary_range(box, 0xff004080, 0xff8fffff); - - cout << yellow.dump() << endl; - cout << blue.dump() << endl; - -// auto session = make_WaterfillSession(yellow); -// session. - - auto yellows = Waterfill::find_objects_inplace(yellow, 100); - auto blues = Waterfill::find_objects_inplace(blue, 100); - cout << yellows.size() << endl; - cout << blues.size() << endl; - - size_t c = 0; - for (auto& item : yellows){ - extract_box_reference(box, item).save("yellow-" + std::to_string(c++) + ".png"); - } - c = 0; - for (auto& item : blues){ - extract_box_reference(box, item).save("blue-" + std::to_string(c++) + ".png"); - } - - Waterfill::WaterfillObject obj = yellows[1]; - obj.merge_assume_no_overlap(blues[0]); - - extract_box_reference(box, obj).save("Arrow.png"); -#endif - - -// cout << "\u274c\u2705" << endl; - - -// SummaryShinySymbolDetector detector; - - -#if 0 - BattleMenuDetector detector; - cout << detector.detect(image) << endl; -#endif - -#if 0 - ImageRGB32 image("screenshot-20220814-144223026390.png"); - - StandardBattleMenuDetector detector(false); - cout << detector.detect(image) << endl; -#endif - - -// STATIC_TEXT.set_text("123456789"); - - - -// cv::Mat image; - - -// env.log(QString(QChar(0x2728))); -// env.log("\u2728\u2733"); - - -// throw UserSetupError(env.logger(), "Can't find any shinies? Join our Discord server and DM Elvis for FREE SHINIES!"); - - - -// ImageRGB32 image("20220806-151454864146-rmsd_precropped_input.png"); - -// image = filter_rgb32_range(image, 0xffb0b0b0, 0xffffffff, Color(0xffff0000), true); - -// image.save("test.png"); - - -// cout << StringTools::replace("asdf asdf adsf", "123", "---") << endl; - - - -#if 0 - ImageRGB32 image("screenshot-20220725-170822724101.png"); - ImageHSV32 hsv(image); -#endif - - -#if 0 - ImageRGB32 image(100, 100); - image.fill(0xffff0000); - image.save("test.png"); -#endif - -#if 0 - ImageRGB32 image0("Avermedia-Qt5.png"); - ImageRGB32 image1(std::move(image0)); - - image1.sub_image(100, 100, 100, 100).save("test.png"); -#endif - - -#if 0 -// QImage image("20220714-114859147833-connect_to_internet_with_inference.png"); -// QImage image("MyPin-Qt6.png"); - - YCommMenuDetector detector(true); - cout << detector.detect(QImage("MiraBox-Qt5.png")) << endl; - cout << detector.detect(QImage("MiraBox-Qt5.png")) << endl; - cout << detector.detect(QImage("MyPin-Qt5.png")) << endl; - cout << detector.detect(QImage("MyPin-Qt6.png")) << endl; - cout << detector.detect(QImage("NoBrand-Qt6.png")) << endl; - cout << detector.detect(QImage("ShadowCast-Qt6.png")) << endl; - #endif - - - -#if 0 - GlobalState state; - state.boss = "dialga"; - state.players[0].pokemon = "cradily"; - state.players[1].console_id = 0; - state.players[1].pokemon = "heatmor"; - state.players[2].pokemon = "crawdaunt"; - state.players[3].pokemon = "marowak-alola"; - state.opponent = {"flareon"}; - - - select_move(env.logger(), state, 1); -#endif - -#if 0 - using namespace nlohmann; - - json j2 = { - {"pi", 3.141}, - {"happy", true}, - {"name", "Niels"}, - {"nothing", nullptr}, - {"answer", { - {"everything", 42} - }}, - {"list", {1, 0, 2}}, - {"object", { - {"currency", "USD"}, - {"value", 42.99} - }} - }; - -// cout << "str = " << 123 << endl; -// std::string str = j2.get(); -// cout << "str = " << str << endl; - - cout << json((int8_t)1).dump() << endl; - cout << json((int16_t)1).dump() << endl; - cout << json((int32_t)1).dump() << endl; - cout << json((int64_t)1).dump() << endl; - - { - cout << j2.dump() << endl; - JsonValue2 value = from_nlohmann(j2); - json j3 = to_nlohmann(value); - cout << j3.dump() << endl; - } - QJsonObject obj = QJsonDocument::fromJson(j2.dump().c_str()).object(); - { - cout << j2.dump() << endl; - JsonValue2 value = from_QJson(obj); - QJsonValue obj2 = to_QJson(value); -// cout << QJson_to_nlohmann(obj2).dump() << endl; - } - -// cout << QDir::current().relativeFilePath(RESOURCE_PATH()).toStdString() << endl; -#endif - -#if 0 - std::string str; - - - cout << j2.dump(4) << endl; - - json j3 = "asdf"; - cout << j3.dump(4) << endl; - - QJsonDocument doc(QJsonDocument::fromJson("asdf")); - cout << doc.toJson().data() << endl; -#endif - -#if 0 - int16_t in[4] = {1, 1, 2, -2}; - print_u8((uint8_t*)in, 8); - - - - AudioSourceReader reader(AudioSampleFormat::SINT16, 1, false); - AudioListener listener(1); - reader += listener; - - -// reader.push_bytes(in, 8); - reader.push_bytes((char*)in + 0, 5); - reader.push_bytes((char*)in + 5, 3); -#endif - - - -// AudioStreamReader2 reader(2, AudioSampleFormat::SINT16); - - - -#if 0 - char buffer[17] = {}; - for (size_t c = 0; c < 16; c++){ - buffer[c] = '='; - } - - StreamReader reader(8); - cout << reader.dump() << endl; - - reader.push_back("asdf", 4); - reader.pop_to(2); - reader.push_back("qwerzx", 6); - cout << reader.dump() << endl; - - reader.push_back("sdfg", 4); - cout << reader.dump() << endl; - -// reader.read(buffer, 4, 7); -// cout << buffer << endl; -// cout << reader.dump() << endl; -#endif - -#if 0 - float f[10]; - uint8_t i[10] = {}; - i[0] = 1; - i[1] = 255; - i[2] = 0; - i[3] = 123; - i[9] = 123; - - Kernels::AudioStreamConversion::convert_audio_uint8_to_float(f, i, 10); - print(f, 10); - memset(i, 0, sizeof(i)); - Kernels::AudioStreamConversion::convert_audio_float_to_uint8(i, f, 10); - print_u8(i, 10); -#endif - - -#if 0 - union{ - float f32; - int32_t i32; - }; - f32 = 12582912.; - cout << i32 << endl; -#endif - - -// cout << _mm_cvt_ss2si() << endl; - -#if 0 - CircularBuffer buffer(8); - - char data[21] = {}; - - buffer.push_back("asdfqwer", 8); - - cout << buffer.pop_front(data, 4) << endl; - cout << data << endl; - -// cout << buffer.dump() << endl; - - buffer.push_back("zxcvsdfg", 8); - - cout << buffer.pop_front(data, 20) << endl; - cout << data << endl; -#endif - - -// __m256 k0 = _mm256_set1_ps(-4.); -// __m256 k1 = _mm256_set1_ps(-3.); -// __m256 k2 = _mm256_set1_ps(-2.); -// __m256 k3 = _mm256_set1_ps(-1.); - - - - - - -} - - - - - -inline std::string dump8(uint8_t x){ - std::string str; - for (size_t c = 0; c < 8; c++){ - str += ((x >> c) & 1) ? "1" : "0"; - } - return str; -} - - -void print(const uint64_t* ptr, size_t len){ - cout << "{"; - bool first = true; - for (size_t c = 0; c < len; c++){ - if (!first){ - cout << ", "; - } - first = false; - cout << ptr[c]; - } - cout << "}" << endl; -} - - - - - - - - - -} +/* Test Program (Computer) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef _WIN64 +#include +#elif defined(__linux) || defined(__APPLE__) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "TestProgramComputer.h" +#include "ClientSource/Libraries/Logging.h" +#include "Common/Cpp/Containers/Pimpl.tpp" + +#include "Kernels/BinaryMatrix/Kernels_PackedBinaryMatrixCore.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Core_64x4_Default.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" +#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/Tools/FileDownloader.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "Common/Cpp/Concurrency/PeriodicScheduler.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" +#include "Kernels/Kernels_Alignment.h" +#include "Kernels/ScaleInvariantMatrixMatch/Kernels_ScaleInvariantMatrixMatch.h" +#include "Kernels/SpikeConvolution/Kernels_SpikeConvolution.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "Kernels/AudioStreamConversion/AudioStreamConversion.h" +#include "Common/Cpp/StreamConverters.h" +#include "CommonFramework/AudioPipeline/AudioConstants.h" +#include "CommonFramework/AudioPipeline/AudioStream.h" +#include "3rdParty/nlohmann/json.hpp" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageHSV32.h" +#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" +#include "Common/Cpp/StringTools.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" + +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "Common/Cpp/Containers/BoxSet.h" +#include "Common/Cpp/Concurrency/ScheduledTaskRunner.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "Integrations/DiscordWebhook.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "CommonFramework/Environment/Environment.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Qt/TimeQt.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Environment/Environment.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" +#include "PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" +#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "Kernels/ImageStats/Kernels_ImagePixelSumSqr.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "Common/Cpp/Concurrency/Watchdog.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +//#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "PokemonSV/Inference/PokemonSV_StatHexagonReader.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h" +#include "PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h" +#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" +#include "Common/Cpp/Containers/CircularBuffer.h" +#include "Common/Cpp/Sockets/ClientSocket.h" +#include "Common/Cpp/Containers/SparseArray.h" + +#ifdef PA_ARCH_x86 +//#include "Kernels/Kernels_x64_SSE41.h" +//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +// #include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters_x64_SSE42.h" +// #include "Kernels/Waterfill/Kernels_Waterfill_Core_64x8_x64_SSE42.h" +//#include "Kernels/Kernels_x64_SSE41.h" +//#include "Kernels/Kernels_x64_AVX2.h" +//#include "Kernels/Kernels_x64_AVX512.h" +//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_SSE41.h" +//#include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_x64_AVX2.h" +//#include "Kernels/Waterfill/Kernels_Waterfill_Intrinsics_x64_AVX512.h" +//#include "Kernels/Waterfill/Kernels_Waterfill_Core_64x32_x64_AVX512-GF.h" +//#include "Common/Cpp/CpuId/CpuId_x86.h" +//#include "Kernels/ImageScaling/Kernels_ImageScaling_Default.h" +//#include "Kernels/ImageScaling/Kernels_ImageScaling_x64_SSE41.h" +#endif +#include "Common/SerialPABotBase/SerialPABotBase_Protocol.h" +//#include "Common/SerialPABotBase/LightweightWallClock_StdChrono.h" +#include "Common/Cpp/Options/MacAddressOption.h" +#include "CommonTools/Images/ImageFilter.h" + + +//#include +#include +#include + + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +using namespace Kernels; +using namespace Kernels::Waterfill; +using namespace Pokemon; + + +TestProgramComputer_Descriptor::TestProgramComputer_Descriptor() + : ComputerProgramDescriptor( + "Computer:TestProgram", + "Computer", "Test Program (Computer)", + "", + "Test Program" + ) +{} +TestProgramComputer::TestProgramComputer() + : STATIC_TEXT("test text") + , SCREEN_WATCHER("Capture Box", 0, 0, 1, 1) + , MAC_ADDRESS(LockMode::UNLOCK_WHILE_RUNNING, 6, nullptr) +{ + PA_ADD_OPTION(STATIC_TEXT); +// PA_ADD_OPTION(SCREEN_WATCHER); + PA_ADD_OPTION(MAC_ADDRESS); +} + +WallClock REFERENCE = current_time(); + + +using namespace Kernels; + +template +void print(const Type* ptr, size_t len){ + cout << "{"; + bool first = true; + for (size_t c = 0; c < len; c++){ + if (!first){ + cout << ", "; + } + first = false; + if (sizeof(Type) == 1){ + cout << (uint32_t)ptr[c]; + }else{ + cout << ptr[c]; + } + } + cout << "}" << endl; +} + + + + + +class WatchdogTest0 : public WatchdogCallback{ + virtual void on_watchdog_timeout(){ + cout << "run() - start" << endl; +#if defined(__linux) || defined(__APPLE__) + sleep(10); +#else + Sleep(10000); +#endif + cout << "run() - end" << endl; + } +}; +class WatchdogTest1 : public WatchdogCallback{ + virtual void on_watchdog_timeout(){ + cout << "run()" << endl; + } +}; + + + + +template +class CheckedObject{ +public: + template + CheckedObject(Args&&... args) + : m_object(std::forward(args)...) + { + m_instances++; + } + ~CheckedObject(){ + m_instances--; + } + + operator const Type&() const{ + return m_object; + } + operator Type&(){ + return m_object; + } + + static size_t instances(){ + return m_instances.load(std::memory_order_relaxed); + } + + friend std::ostream& operator<<(std::ostream& stream, const CheckedObject& x){ + return stream << (const Type&)x; + } + +private: + static std::atomic m_instances; + Type m_object; + LifetimeSanitizer m_lifetime_santizer; +}; + +template +std::atomic CheckedObject::m_instances(0); + + + + + +#if 0 +struct RequestManagerConfig{ + using ClockType = LightweightWallClock_StdChrono; + using ClockDuration = LightweightDuration_StdChrono; + using SeqnumType = seqnum_t; + using MessageSizeType = uint8_t; + static constexpr size_t MAX_MESSAGE_SIZE = 64; + static constexpr size_t QUEUE_SIZE = 64; +}; +#endif + + + + + + + + +void TestProgramComputer::program(ProgramEnvironment& env, CancellableScope& scope){ + using namespace Kernels; + using namespace NintendoSwitch; +// using namespace NintendoSwitch::PokemonSwSh; + using namespace NintendoSwitch::PokemonSV; + using namespace Pokemon; + using namespace NintendoSwitch::PokemonSwSh::MaxLairInternal; + + using namespace std::chrono_literals; + + + + + + +#if 0 + { + CommandQueue queue; + + queue.enqueue_command(ControllerCommand{ + .seqnum = 10, + .milliseconds = 1000, + .state = ControllerState{ + .buttons = 123, + } + }); + queue.enqueue_command(ControllerCommand{ + .seqnum = 11, + .milliseconds = 2000, + .state = ControllerState{ + .buttons = 456, + } + }); + + scope.wait_for(60s); + } +#endif + +#if 0 + HeapCircularBuffer buffer(10); + + buffer.try_push_back("asdf"); + buffer.try_push_back("qwer"); + buffer.try_push_back("zxcv"); + + cout << buffer[0] << endl; + cout << buffer[1] << endl; + cout << buffer[2] << endl; + cout << "--------------------" << endl; + buffer.pop_front(); + cout << buffer[0] << endl; + cout << buffer[1] << endl; +#endif + +#if 0 + Command command{ + 123, + 100, + 512, + 2000, 3000, + 4000, 5000 + }; + + char str[65] = {}; + command.write_to_hex(str); + cout << str << endl; + memset(&command, 0, sizeof(Command)); + + command.parse_from_hex(str); + + cout << command.milliseconds << endl; + cout << command.buttons << endl; + cout << command.left_joystick_x << endl; + cout << command.left_joystick_y << endl; + cout << command.right_joystick_x << endl; + cout << command.right_joystick_y << endl; +#endif + +#if 0 + ImageRGB32 image("20250503-121259857603.png"); + + image = filter_rgb32_euclidean(image, (uint32_t)COLOR_PURPLE, 100, COLOR_RED, true); + image.save("temp.png"); +#endif + + + + +#if 0 + uint8_t address[] = {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc}; + + std::string str = write_MAC_address(6, address); + cout << str << endl; + + parse_MAC_address(6, address, str); + str = write_MAC_address(6, address); + cout << str << endl; +#endif + +#if 0 + SparseArray data{ + {100, "0123456789"}, + {120, {'a', 0x20, 'd'}}, + }; +// data.set_data(100, "0123456789", 10); +// data.set_data(120, "asdfzxcv", 8); + + cout << data.dump() << endl; +// data.set_data(110, 12, "qwerqwerqwer"); + + std::string read(12, '?'); + data.read(109, 12, read.data()); + + cout << "read = " << read << endl; + +// data.print(); + + +#if 0 + ClientSocket socket; + socket.connect("192.168.1.66", 6000); +// socket.connect("192.168.1.66", 6000); + + scope.wait_for(std::chrono::seconds(60)); +#endif + +#endif + + +#if 0 + int* ptr = nullptr; + cout << ptr[0] << endl; +#endif + +#if 0 + { + CircularBuffer> buffer(4); + + cout << "Dumping:" << endl; + for (size_t c = 0; c < buffer.size(); c++){ + cout << " " << buffer[c] << endl; + } + + buffer.push_back("123"); + buffer.push_back("456"); + buffer.push_back("789"); + + + cout << "Dumping:" << endl; + for (size_t c = 0; c < buffer.size(); c++){ + cout << " " << buffer[c] << endl; + } + + buffer.pop_front(); + + cout << "Dumping:" << endl; + for (size_t c = 0; c < buffer.size(); c++){ + cout << " " << buffer[c] << endl; + } + + buffer.push_back("asd"); + buffer.push_back("sdf"); + + cout << "Dumping:" << endl; + for (size_t c = 0; c < buffer.size(); c++){ + cout << " " << buffer[c] << endl; + } + + cout << "Instances = " << CheckedObject::instances() << endl; + } + cout << "Instances = " << CheckedObject::instances() << endl; +#endif + + + +#if 0 + send_program_notification_with_file( + env, NOTIFICATION_PROGRAM_FINISH, COLOR_BLUE, + "test notification", + {}, + "", + "test.txt" + ); +#endif + + +// ImageRGB32 image("Screenshots/20241128-152424608121.png"); +#if 0 + send_error_report( + env.logger(), + env.program_info(), + "testtest", + {{"title", "message"}}, + image, +// ImageRGB32(), + {"test.txt", "test2.txt"} + ); +#endif + + +#if 0 + std::random_device rndsource; + std::minstd_rand rndgen(rndsource()); + std::uniform_real_distribution dist(0, 1.0); + + cout << dist(rndgen) << endl; + cout << dist(rndgen) << endl; + cout << dist(rndgen) << endl; + cout << dist(rndgen) << endl; +#endif + +#if 0 + PokemonSV::DateSeed data = PokemonSV::ItemPrinter::calculate_seed_prizes(2346161588); + + cout << "Regular:" << endl; + for (auto& item : data.regular){ + cout << " " << item << endl; + } + + cout << "Item Bonus:" << endl; + for (auto& item : data.item_bonus){ + cout << " " << item << endl; + } + + cout << "Ball Bonus:" << endl; + for (auto& item : data.ball_bonus){ + cout << " " << item << endl; + } +#endif + + +// make_item_prize_table(); +// make_ball_prize_table(); + +#if 0 + { + std::string path = "PokemonSV/ItemPrinterItems.json"; + JsonValue json = load_json_file(RESOURCE_PATH() + path); + const JsonArray& array = json + .to_object_throw(path) + .get_array_throw("Table", path); + make_prize_table(array, path, 10001); + } +#endif + +// make_prize_table(, 10001); + + +#if 0 + JsonValue json = load_json_file("ItemPrinterOCR.json"); + JsonObject& obj = json.get_object_throw(); + JsonObject& jpn0 = obj.get_object_throw("jpn"); + JsonObject& jpn1 = obj.get_object_throw("jpn-t"); + + for (auto& item : jpn0){ + cout << "testing: " << item.first << endl; + auto iter = jpn1.find(item.first); + if (iter == jpn1.end()){ + throw "missing name"; + } + JsonArray& arr0 = item.second.get_array_throw(); + JsonArray& arr1 = iter->second.get_array_throw(); + if (arr0[0].get_string_throw() != arr1[0].get_string_throw()){ + cout << "mismatch found: " << arr0[0].get_string_throw() << " : " << arr1[0].get_string_throw() << endl; + } + } + #endif + + + +#if 0 + ImageRGB32 image("screenshot-20240605-000823122811.png"); + + PokemonSwSh::MaxLairInternal::PokemonSelectMenuDetector detector(false); + cout << detector.detect(image) << endl; + +// BattleMenuDetector detector; +// cout << detector.detect(image) << endl; +#endif + + +#if 0 + ImageRGB32 image("20231120-221849973351.png"); + + + PokemonBDSP::ShinySparkleSetBDSP detector; + + ImageViewRGB32 wild = extract_box_reference(image, ImageFloatBox{0.4, 0.02, 0.60, 0.93}); + ImageViewRGB32 self = extract_box_reference(image, ImageFloatBox{0.0, 0.1, 0.8, 0.8}); + + wild.save("wild.png"); + wild.save("self.png"); + + detector.read_from_image(wild); + cout << detector.to_str() << endl; + + detector.read_from_image(self); + cout << detector.to_str() << endl; +#endif + + +// ImageRGB32 image("screenshot-20231016-130205783594.png"); +// PokemonSummaryDetector detector; +// cout << detector.detect(image) << endl; + + + +#if 0 + ImageRGB32 image("screenshot-20231005-203932147068.png"); + SummaryStatsReader reader; +// cout << detector.detect(image) << endl; + auto nature = reader.read_nature(env.logger(), image); + + cout << (int)nature.attack << endl; + cout << (int)nature.defense << endl; + cout << (int)nature.spatk << endl; + cout << (int)nature.spdef << endl; + cout << (int)nature.speed << endl; +#endif + + + +#if 0 + uint8_t low_iv; + uint8_t high_iv; + + bool ok = calc_iv_range( + low_iv, high_iv, + false, 55, 100, 0, + 126, NatureAdjustment::NEGATIVE + ); + + cout << "ok = " << ok << endl; + cout << "low = " << (int)low_iv << endl; + cout << "high = " << (int)high_iv << endl; +#endif + + + + +// ImageRGB32 image("screenshot-20230912-194941389243.png"); +// NintendoSwitch::PokemonSV::PokemonSummaryDetector detector; +// cout << detector.detect(image) << endl; + + +#if 0 + ImageRGB32 image("20230726-213101330270-ProgramHang.png"); + NintendoSwitch::PokemonSwSh::MaxLairInternal::BattleMenuDetector detector; + cout << detector.detect(image) << endl; +#endif + +// SandwichRecipeNumberDetector detector(env.logger()); +// size_t recipe_IDs[6]; +// detector.detect_recipes(image, recipe_IDs); + +#if 0 + { + ImageRGB32 image("20230630-084354220241.jpg"); + TeraLobbyReader reader(env.logger(), env.inference_dispatcher()); + reader.read_names(env.logger(), {Language::Japanese}, image); + } + { + ImageRGB32 image("name1.png"); + cout << OCR::ocr_read(Language::Japanese, image) << endl; + } +#endif + + +// ImageRGB32 image("20230427-200550386826-OperationFailedException.png"); + +// NintendoSwitch::HomeMenuDetector detector; +// cout << detector.detect(image) << endl; + + +#if 0 + ImageRGB32 image("20230323-082240823181-OperationFailedException.png"); + + TeraCatchDetector detector(COLOR_RED); + cout << detector.detect(image) << endl; +#endif + + + +#if 0 + WatchdogTest0 callback0; + WatchdogTest1 callback1; + + Watchdog watchdog; + watchdog.add(callback0, std::chrono::seconds(20)); + watchdog.add(callback1, std::chrono::seconds(2)); + + watchdog.delay(callback0, current_time()); + for (size_t c = 0; c < 5; c++){ + scope.wait_for(std::chrono::seconds(1)); + cout << "delaying..." << endl; + watchdog.delay(callback0); + } + + cout << "removing 0 start" << endl; + watchdog.remove(callback1); + cout << "removing 0... end" << endl; + + cout << "removing 1... start" << endl; + watchdog.remove(callback0); + cout << "removing 1... end" << endl; + + scope.wait_for(std::chrono::seconds(60)); +#endif +#if 0 + ImageRGB32 image("screenshot-20230303-225044564794.png"); + + BlackBorderDetector detector; + cout << detector.detect(image) << endl; +#endif + + +// send_program_telemetry(env.logger(), true, COLOR_RED, env.program_info(), "test", {}, ""); + + + + + +#if 0 + ImageRGB32 image("Screenshots/screenshot-20230228-050626316922.png"); + + NewsDetector detector; + cout << detector.detect(image) << endl; +#endif + + + + + + +#if 0 + ImageRGB32 image("test-0-image.png"); + + Color background(4294954240); + + for (size_t c = 0; c < 5; c++){ + ImageRGB32 sprite("test-" + std::to_string(c) + "-sprite.png"); + PixelSums sums; + pixel_sum_sqr( + sums, image.width(), image.height(), + image.data(), image.bytes_per_row(), + sprite.data(), sprite.bytes_per_row() + ); + cout << sums.count << endl; + cout << ImageMatch::pixel_RMSD(sprite, image, background) << endl; + } +#endif + + + + +// cout << get_ingredient_name("green-bell-pepper").display_name() << endl; + +#if 0 + ImageFloatBox ore_quantity(0.945, 0.010, 0.0525, 0.050); + + ImageRGB32 image("screenshot-20230220-232711115537.png"); + ImageRGB32 filtered = to_blackwhite_rgb32_range( + extract_box_reference(image, ore_quantity), + 0xff808080, 0xffffffff, true + ); + + filtered = pad_image(filtered, 10, 0xffffffff); + + filtered.save("test.png"); + + OCR::read_number(env.logger(), filtered); +#endif + +// OperationFailedException::fire(env.logger(), "asdf"); +// OperationFailedException::fire(env.logger(), "asdf", std::make_shared("20221118-024539201323.jpg")); +// throw ProgramFinishedException(); +// throw FatalProgramException(env.logger(), "test"); + + +// send_program_telemetry(env.logger(), true, COLOR_RED, env.program_info(), "Test", {}, ""); + +// throw ProgramFinishedException(env.logger(), "", std::make_shared("TeraCode-S-chi-original.png")); + + +// load_pokemon_slug_json_list(); + + + +#if 0 + WallClock now = current_time(); + + + DiscontiguousTimeTracker tracker; + tracker.add_block(now - Seconds(30), now - Seconds(19)); + tracker.add_block(now - Seconds(10), now - Seconds(5)); + + auto duration = tracker.last_window_in_realtime(now, Seconds(10)); + + cout << std::chrono::duration_cast(duration).count() << endl; +#endif + + +#if 0 + ImageRGB32 image("20230219-200200879508-OperationFailedException.png"); + OverworldDetector detector(COLOR_RED); + cout << detector.detect(image) << endl; +#endif + + +#if 0 + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + env.logger(), Language::Korean, + ImageRGB32("../../TrainingData/PokemonNameOCR/PokemonNameOCR (Kim-SwShPokedex-1)/kor/joltik-20210618-212232.png"), + OCR::BLACK_OR_WHITE_TEXT_FILTERS() + ); + + for (auto& item : result.results){ + cout << item.first << ": " << item.second.token << endl; + } +#endif + +#if 0 + for (int c = (int)Language::English; c < (int)Language::EndOfList; c++){ + Language language = (Language)c; + + JsonObject json; + + for (const std::string& slug : NATIONAL_DEX_SLUGS()){ + JsonArray array; + array.push_back(get_pokemon_name(slug).display_name(language)); + json[slug] = std::move(array); + } + + json.dump("PokemonOCR-" + language_data(language).code + ".json"); + } +#endif + + +#if 0 + ImageRGB32 image("screenshot-20230211-223602354229.png"); + SweatBubbleDetector detector(COLOR_RED, {0, 0, 1, 1}); + cout << detector.detect(image) << endl; +#endif + + +#if 0 + ImageRGB32 image("test-0.png"); +// ImageRGB32 filtered = filter_rgb32_range(image, 0xff000000, 0xffffff90, Color(0x00000000), true); +// filtered.save("filtered.png"); + + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + if (9 < r && r < 50 && 19 < c && c < 57){ + continue; + } + uint32_t pixel = image.pixel(c, r); + uint32_t red = (pixel >> 16) & 0xff; + uint32_t green = (pixel >> 8) & 0xff; + uint32_t blue = (pixel >> 0) & 0xff; + uint32_t total = red + green + blue; + if (total < 720){ + image.pixel(c, r) = 0; + }else{ + image.pixel(c, r) = 0xffffffff; + } + } + } + image.save("filtered.png"); +#endif + +#if 0 + ImageRGB32 image("screenshot-20230211-223602354229.png"); + auto matrix = compress_rgb32_to_binary_range(image, 0xffc0c0c0, 0xffffffff); + + std::vector objects = Waterfill::find_objects_inplace(matrix, 100); + cout << objects.size() << endl; + + for (size_t c = 0; c < objects.size(); c++){ + extract_box_reference(image, objects[c]).save("test-" + std::to_string(c) + ".png"); + } +#endif + + +#if 0 + ImageRGB32 image("Screenshots/screenshot-20230209-061452037331.png"); + + ImageRGB32 filtered = filter_rgb32_range(image, 0xff000040, 0xff8080ff, Color(0xffff0000), true); + filtered.save("test.png"); +#endif + +#if 0 + ImageRGB32 image("Screenshots/screenshot-20230208-012850704172.png"); + + OverworldDetector detector; + cout << detector.detect(image) << endl; +#endif + + +#if 0 +// ImageRGB32 image("Screenshots/screenshot-20230206-023520852521.png"); + ImageRGB32 image("Screenshots/screenshot-20230206-022329387691.png"); +// ImageRGB32 image("LetsGoKill.png"); + + LetsGoKillDetector detector(COLOR_RED); +// LetsGoKillDetector detector(COLOR_RED, {0, 0, 1, 1}); + detector.detect(image); +#endif + + +#if 0 + send_program_notification_with_file( + env, + NOTIFICATION_ERROR_RECOVERABLE, + Color(0), + "Join Report", + {}, "", + "name-of-text-file.txt" + ); + + + + ImageRGB32 image("screenshot-20230130-150721112888.png"); + SomethingInBoxSlotDetector detector(COLOR_RED); + + cout << detector.detect(image) << endl; +#endif + +#if 0 + FILETIME idle_time, kernel_time, user_time; + GetSystemTimes(&idle_time, &kernel_time, &user_time); +// cout << << endl; +// cout << << endl; +// cout << << endl; + + uint64_t start_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); + uint64_t start_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); + uint64_t start_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); + + scope.wait_for(std::chrono::seconds(4)); + + GetSystemTimes(&idle_time, &kernel_time, &user_time); +// cout << << endl; +// cout << << endl; +// cout << << endl; + + uint64_t end_idle = idle_time.dwLowDateTime + ((uint64_t)idle_time.dwHighDateTime << 32); + uint64_t end_kernel = kernel_time.dwLowDateTime + ((uint64_t)kernel_time.dwHighDateTime << 32); + uint64_t end_user = user_time.dwLowDateTime + ((uint64_t)user_time.dwHighDateTime << 32); + + cout << (end_idle - start_idle) * 100 / 1000000000. << endl; + cout << (end_kernel - start_kernel) * 100 / 1000000000. << endl; + cout << (end_user - start_user) * 100 / 1000000000. << endl; +#endif + +#if 0 + uint32_t src[4 * 4] = { + 0xff0a0a0a, 0xff141414, 0xff1e1e1e, 0xff282828, + 0xff646464, 0xff646464, 0xff646464, 0xff646464, + 0xff646464, 0xff646464, 0xff646464, 0xff646464, + 0xff646464, 0xff646464, 0xff646464, 0xff646464, + }; + uint32_t dst[4 * 4] = {}; + + print((uint8_t*)src + 0*16, 16); + print((uint8_t*)src + 1*16, 16); + print((uint8_t*)src + 2*16, 16); + print((uint8_t*)src + 3*16, 16); + +#if 0 + TileBuilder builder( + dst, 3 * sizeof(uint32_t), 3, 3, + src, 4 * sizeof(uint32_t), 4, 4 + ); + + FloatPixelTile tile; + size_t dst_col = 0; + size_t src_col = 0; + builder.build_tile(tile, dst_col, 0, src_col); + cout << tile << endl; + + FloatPixelWord accumulator; + size_t row = 0; + builder.write_tile(accumulator, row, 0, tile, 0); +#endif + + scale_image_Default( + dst, 4 * sizeof(uint32_t), 4, 4, + src, 4 * sizeof(uint32_t), 4, 4 + ); + + + print((uint8_t*)dst + 0*16, 16); + print((uint8_t*)dst + 1*16, 16); + print((uint8_t*)dst + 2*16, 16); + print((uint8_t*)dst + 3*16, 16); + +// print((uint8_t*)dst + 0*12, 12); +// print((uint8_t*)dst + 1*12, 12); +// print((uint8_t*)dst + 2*12, 12); + + +#if 0 + float dst[10]; + float src[6] = {1, 2, 3, 4, 5}; + + + scale_row(dst, 8, src, 5); + print(dst, 8); +#endif +#endif + + +// env.log("crash coming...", COLOR_RED); +// cout << *(char*)nullptr << endl; + + +#if 0 + StatAccumulatorI32 stats; + + for (size_t c = 0; c < 1000; c++){ + scope.throw_if_cancelled(); + + auto start = current_time(); + env.log(std::to_string(c)); + auto end = current_time(); + stats += std::chrono::duration_cast(end - start).count(); + } + cout << stats.dump("us", 1) << endl; +#endif + + +#if 0 + ImageRGB32 image("TeraCode-S-chi-original.png"); + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + uint32_t pixel = image.pixel(c, r); + uint32_t sum = pixel & 0xff; + sum += (pixel >> 16) & 0xff; + sum += (pixel >> 8) & 0xff; + if (sum > 400){ + image.pixel(c, r) = 0; + } + } + } + image.save("TeraCode-S-chi.png"); +#endif + + + +#if 0 + { + ImageRGB32 image("TeraCodeTest-50.png"); + TeraLobbyReader reader; + reader.raid_code(env.logger(), image); + } + { + ImageRGB32 image("TeraCodeTest-S0.png"); + TeraLobbyReader reader; + reader.raid_code(env.logger(), image); + } + { + ImageRGB32 image("TeraCodeTest-S1.png"); + TeraLobbyReader reader; + reader.raid_code(env.logger(), image); + } +#endif + + + + + + +#if 0 + ImageRGB32 image("20230107-053814058280-FREESandwichHandNotDetected.png"); + + SandwichHandLocator detector(SandwichHandType::FREE, {0, 0, 1, 1}); + auto ret = detector.detect(image); + cout << ret.first << " " << ret.second << endl; +#endif + + + +#if 0 +// cout << current_time() << endl; + + std::string str = to_utc_time_str(current_time()); + cout << str << endl; + + WallClock time = parse_utc_time_str(str); + cout << to_utc_time_str(time) << endl; + +// parse_utc_time_str(str); +#endif + +#if 0 + ThreadHandle handle = current_thread_handle(); + cout << thread_cpu_time(handle).count() << endl; + + WallClock start = current_time(); + while (current_time() - start < std::chrono::seconds(1)); + + cout << thread_cpu_time(handle).count() << endl; +#endif + + +#if 0 + ImageRGB32 image("20221230-232826566125-BoxSystemNotDetected.png"); + BoxDetector detector; +// cout << detector.detect(image) << endl; + + auto ret = detector.detect_location(image); + cout << (int)ret.first << " : " << (int)ret.second.row << ", " << (int)ret.second.col << endl; + + GradientArrowDetector arrow(COLOR_RED, GradientArrowType::DOWN, {0.240, 0.160, 0.380, 0.550}); + cout << arrow.detect(image) << endl; +#endif + + +#if 0 + ImageRGB32 image("20221230-075353892425-BoxSystemNotDetected.png"); + BoxDetector detector; +// cout << detector.detect(image) << endl; + + auto ret = detector.detect_location(image); + cout << (int)ret.first << " : " << (int)ret.second.row << ", " << (int)ret.second.col << endl; + + GradientArrowDetector arrow(COLOR_RED, GradientArrowType::DOWN, {0.140, 0.150, 0.050, 0.700}); + cout << arrow.detect(image) << endl; +#endif + + + +#if 0 + ImageRGB32 image("ZeroGateNightBike_2_True.png"); + OverworldDetector detector; + cout << detector.detect(image) << endl; +#endif + +#if 0 + ImageRGB32 image("screenshot-20221219-201912436404.png"); + PromptDialogDetector prompt(COLOR_RED, {0.623, 0.530, 0.243, 0.119}); + cout << prompt.detect(image) << endl; +#endif + + +#if 0 + ImageRGB32 image("20221219-140347621956.jpg"); + TeraLobbyReader reader; + auto names = reader.read_names(env.logger(), {Language::English}, true, image); +#endif +#if 0 + for (size_t row = 0; row < image.height(); row++){ + for (size_t col = 0; col < image.width(); col++){ + uint32_t pixel = image.pixel(col, row); + uint32_t r = (pixel >> 16) & 0xff; + uint32_t g = (pixel >> 8) & 0xff; + uint32_t b = (pixel >> 0) & 0xff; +#if 0 + if (b > 2*r + 10 || b > 2*g + 10){ + pixel = 0xffffffff; + } +#endif +#if 1 + if (r + g + b < 150){ + pixel = 0xffffffff; + } +#endif + image.pixel(col, row) = pixel; + } + } + image.save("test.png"); +#endif + + +#if 0 + MultiLanguageJoinTracker tracker; + tracker.add(Language::English, "Alice", "RNS308"); + tracker.add(Language::English, "Alice", "RNS308"); + tracker.add(Language::English, "Alice", "RNS308"); + tracker.add(Language::English, "Dhruv", "UCCJ9H"); + tracker.add(Language::English, "Dhruv", "EKNQY9"); + tracker.add(Language::English, "Gael", "X89986"); + tracker.add(Language::English, "Gael", "X89986"); + tracker.add(Language::ChineseSimplified, "Gael", "X89986"); + tracker.add(Language::ChineseSimplified, "Gael", "X89986"); + + tracker.dump("test.txt"); +#endif + +#if 0 + cout << tracker.dump() << endl; + + std::ofstream file("test.txt"); + file << tracker.dump(); + file.close(); +#endif + +#if 0 + Integration::DiscordWebhook::send_message( + env.logger(), false, + {"Notifs"}, + "Test Join Tracker output...", + JsonArray(), + std::make_shared("test.txt", false) + ); +#endif + + +#if 0 + ImageRGB32 image("BadArrow.png"); + TeraCatchDetector detector(COLOR_RED); + cout << detector.detect(image) << endl; + + +// extract_box_reference(image, ImageFloatBox{0.95, 0.81, 0.02, 0.06}).save("test.png"); +#endif + + +#if 0 + { + std::string json = FileDownloader::download_file(env.logger(), "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json"); + cout << "Done loading..." << endl; + + std::ofstream file("test.txt"); + file << json; + } +#if 1 + { + JsonValue json = FileDownloader::download_json_file(env.logger(), "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json"); + cout << "Done loading..." << endl; + cout << json.dump() << endl; + } +#endif +#endif + +#if 0 + ScheduledTaskRunner scheduler(env.inference_dispatcher()); + + scheduler.add_event(std::chrono::seconds(5), []{ cout << "5 seconds" << endl; }); + scheduler.add_event(std::chrono::seconds(2), []{ cout << "2 seconds" << endl; }); + scheduler.add_event(std::chrono::seconds(7), []{ cout << "7 seconds" << endl; }); + + scope.wait_for(std::chrono::seconds(100)); +#endif + +#if 0 + BoxSet set; + cout << set.dump() << endl; + + set.insert({10, 20, 15, 25}); + set.insert({11, 19, 13, 27}); + set.insert({12, 18, 13, 27}); + cout << set.dump() << endl; + + auto iter = set.lower_bound_min_y(11); + for (; iter != set.end_min_y(); ++iter){ + cout << iter->first << endl; + } +#endif + +// ImageRGB32 image("SV-Buttons2.png"); +// WhiteButtonDetector detector(WhiteButton::ButtonB, ImageFloatBox{0, 0, 1, 1}); +// detector.detect(image); + + +#if 0 + ImageRGB32 image("SV-Buttons2.png"); + + ImageFloatBox box(0.027, 0.922, .02, .035); + ImageViewRGB32 region = extract_box_reference(image, box); + + region.save("tmp.png"); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff808080, 0xffffffff); + auto objects = Waterfill::find_objects_inplace(matrix, 20); + extract_box_reference(region, objects[0]).save("cropped.png"); +#endif + +// DialogArrowDetector detector({0.45, 0.9, .1, .05}); +// detector.detect(image); + +#if 0 + ImageFloatBox box(0.72, 0.85, 0.02, 0.035); + + ImageViewRGB32 region = extract_box_reference(image, box); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff000000, 0xff7f7fbf); + + cout << matrix.dump() << endl; + + auto arrow = Waterfill::find_objects_inplace(matrix, 20); + extract_box_reference(region, arrow[0]).save("cropped.png"); +#endif + +#if 0 + ImageRGB32 image("SV-BattleMenu.png"); + image.scale_to(1920, 1080); + + GradientArrowDetector detector({0.75, 0.63, 0.05, 0.1}); + detector.detect(image); +#endif + + +#if 0 + ImageRGB32 image("Arrow-Alpha.png"); + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + uint32_t& pixel = image.pixel(c, r); + if (pixel == 0xffffffff){ + pixel = 0; + } + } + } + image.save("Arrow-Alpha2.png"); +#endif + + + + +#if 0 + ImageRGB32 image("SV-BattleMenu.png"); + image.scale_to(1920, 1080); + + ImageViewRGB32 box = extract_box_reference(image, ImageFloatBox({0.75, 0.63, 0.05, 0.1})); + + + PackedBinaryMatrix yellow = compress_rgb32_to_binary_range(box, 0xff808000, 0xffffff7f); + PackedBinaryMatrix blue = compress_rgb32_to_binary_range(box, 0xff004080, 0xff8fffff); + + cout << yellow.dump() << endl; + cout << blue.dump() << endl; + +// auto session = make_WaterfillSession(yellow); +// session. + + auto yellows = Waterfill::find_objects_inplace(yellow, 100); + auto blues = Waterfill::find_objects_inplace(blue, 100); + cout << yellows.size() << endl; + cout << blues.size() << endl; + + size_t c = 0; + for (auto& item : yellows){ + extract_box_reference(box, item).save("yellow-" + std::to_string(c++) + ".png"); + } + c = 0; + for (auto& item : blues){ + extract_box_reference(box, item).save("blue-" + std::to_string(c++) + ".png"); + } + + Waterfill::WaterfillObject obj = yellows[1]; + obj.merge_assume_no_overlap(blues[0]); + + extract_box_reference(box, obj).save("Arrow.png"); +#endif + + +// cout << "\u274c\u2705" << endl; + + +// SummaryShinySymbolDetector detector; + + +#if 0 + BattleMenuDetector detector; + cout << detector.detect(image) << endl; +#endif + +#if 0 + ImageRGB32 image("screenshot-20220814-144223026390.png"); + + StandardBattleMenuDetector detector(false); + cout << detector.detect(image) << endl; +#endif + + +// STATIC_TEXT.set_text("123456789"); + + + +// cv::Mat image; + + +// env.log(QString(QChar(0x2728))); +// env.log("\u2728\u2733"); + + +// throw UserSetupError(env.logger(), "Can't find any shinies? Join our Discord server and DM Elvis for FREE SHINIES!"); + + + +// ImageRGB32 image("20220806-151454864146-rmsd_precropped_input.png"); + +// image = filter_rgb32_range(image, 0xffb0b0b0, 0xffffffff, Color(0xffff0000), true); + +// image.save("test.png"); + + +// cout << StringTools::replace("asdf asdf adsf", "123", "---") << endl; + + + +#if 0 + ImageRGB32 image("screenshot-20220725-170822724101.png"); + ImageHSV32 hsv(image); +#endif + + +#if 0 + ImageRGB32 image(100, 100); + image.fill(0xffff0000); + image.save("test.png"); +#endif + +#if 0 + ImageRGB32 image0("Avermedia-Qt5.png"); + ImageRGB32 image1(std::move(image0)); + + image1.sub_image(100, 100, 100, 100).save("test.png"); +#endif + + +#if 0 +// QImage image("20220714-114859147833-connect_to_internet_with_inference.png"); +// QImage image("MyPin-Qt6.png"); + + YCommMenuDetector detector(true); + cout << detector.detect(QImage("MiraBox-Qt5.png")) << endl; + cout << detector.detect(QImage("MiraBox-Qt5.png")) << endl; + cout << detector.detect(QImage("MyPin-Qt5.png")) << endl; + cout << detector.detect(QImage("MyPin-Qt6.png")) << endl; + cout << detector.detect(QImage("NoBrand-Qt6.png")) << endl; + cout << detector.detect(QImage("ShadowCast-Qt6.png")) << endl; + #endif + + + +#if 0 + GlobalState state; + state.boss = "dialga"; + state.players[0].pokemon = "cradily"; + state.players[1].console_id = 0; + state.players[1].pokemon = "heatmor"; + state.players[2].pokemon = "crawdaunt"; + state.players[3].pokemon = "marowak-alola"; + state.opponent = {"flareon"}; + + + select_move(env.logger(), state, 1); +#endif + +#if 0 + using namespace nlohmann; + + json j2 = { + {"pi", 3.141}, + {"happy", true}, + {"name", "Niels"}, + {"nothing", nullptr}, + {"answer", { + {"everything", 42} + }}, + {"list", {1, 0, 2}}, + {"object", { + {"currency", "USD"}, + {"value", 42.99} + }} + }; + +// cout << "str = " << 123 << endl; +// std::string str = j2.get(); +// cout << "str = " << str << endl; + + cout << json((int8_t)1).dump() << endl; + cout << json((int16_t)1).dump() << endl; + cout << json((int32_t)1).dump() << endl; + cout << json((int64_t)1).dump() << endl; + + { + cout << j2.dump() << endl; + JsonValue2 value = from_nlohmann(j2); + json j3 = to_nlohmann(value); + cout << j3.dump() << endl; + } + QJsonObject obj = QJsonDocument::fromJson(j2.dump().c_str()).object(); + { + cout << j2.dump() << endl; + JsonValue2 value = from_QJson(obj); + QJsonValue obj2 = to_QJson(value); +// cout << QJson_to_nlohmann(obj2).dump() << endl; + } + +// cout << QDir::current().relativeFilePath(RESOURCE_PATH()).toStdString() << endl; +#endif + +#if 0 + std::string str; + + + cout << j2.dump(4) << endl; + + json j3 = "asdf"; + cout << j3.dump(4) << endl; + + QJsonDocument doc(QJsonDocument::fromJson("asdf")); + cout << doc.toJson().data() << endl; +#endif + +#if 0 + int16_t in[4] = {1, 1, 2, -2}; + print_u8((uint8_t*)in, 8); + + + + AudioSourceReader reader(AudioSampleFormat::SINT16, 1, false); + AudioListener listener(1); + reader += listener; + + +// reader.push_bytes(in, 8); + reader.push_bytes((char*)in + 0, 5); + reader.push_bytes((char*)in + 5, 3); +#endif + + + +// AudioStreamReader2 reader(2, AudioSampleFormat::SINT16); + + + +#if 0 + char buffer[17] = {}; + for (size_t c = 0; c < 16; c++){ + buffer[c] = '='; + } + + StreamReader reader(8); + cout << reader.dump() << endl; + + reader.push_back("asdf", 4); + reader.pop_to(2); + reader.push_back("qwerzx", 6); + cout << reader.dump() << endl; + + reader.push_back("sdfg", 4); + cout << reader.dump() << endl; + +// reader.read(buffer, 4, 7); +// cout << buffer << endl; +// cout << reader.dump() << endl; +#endif + +#if 0 + float f[10]; + uint8_t i[10] = {}; + i[0] = 1; + i[1] = 255; + i[2] = 0; + i[3] = 123; + i[9] = 123; + + Kernels::AudioStreamConversion::convert_audio_uint8_to_float(f, i, 10); + print(f, 10); + memset(i, 0, sizeof(i)); + Kernels::AudioStreamConversion::convert_audio_float_to_uint8(i, f, 10); + print_u8(i, 10); +#endif + + +#if 0 + union{ + float f32; + int32_t i32; + }; + f32 = 12582912.; + cout << i32 << endl; +#endif + + +// cout << _mm_cvt_ss2si() << endl; + +#if 0 + CircularBuffer buffer(8); + + char data[21] = {}; + + buffer.push_back("asdfqwer", 8); + + cout << buffer.pop_front(data, 4) << endl; + cout << data << endl; + +// cout << buffer.dump() << endl; + + buffer.push_back("zxcvsdfg", 8); + + cout << buffer.pop_front(data, 20) << endl; + cout << data << endl; +#endif + + +// __m256 k0 = _mm256_set1_ps(-4.); +// __m256 k1 = _mm256_set1_ps(-3.); +// __m256 k2 = _mm256_set1_ps(-2.); +// __m256 k3 = _mm256_set1_ps(-1.); + + + + + + +} + + + + + +inline std::string dump8(uint8_t x){ + std::string str; + for (size_t c = 0; c < 8; c++){ + str += ((x >> c) & 1) ? "1" : "0"; + } + return str; +} + + +void print(const uint64_t* ptr, size_t len){ + cout << "{"; + bool first = true; + for (size_t c = 0; c < len; c++){ + if (!first){ + cout << ", "; + } + first = false; + cout << ptr[c]; + } + cout << "}" << endl; +} + + + + + + + + + +} diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.h index 88dac6a54c..26128a7177 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramComputer.h @@ -1,41 +1,41 @@ -/* Test Program (Computer) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Computer_TestProgram_H -#define PokemonAutomation_Computer_TestProgram_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/MacAddressOption.h" -#include "CommonTools/Options/ScreenWatchOption.h" -#include "ComputerPrograms/ComputerProgram.h" - -namespace PokemonAutomation{ - - -class TestProgramComputer_Descriptor : public ComputerProgramDescriptor{ -public: - TestProgramComputer_Descriptor(); -}; - - - -class TestProgramComputer : public ComputerProgramInstance{ -public: - TestProgramComputer(); - - virtual void program(ProgramEnvironment& env, CancellableScope& scope) override; - -private: - StaticTextOption STATIC_TEXT; - ScreenWatchOption SCREEN_WATCHER; - MacAddressCell MAC_ADDRESS; -}; - - - - -} -#endif +/* Test Program (Computer) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Computer_TestProgram_H +#define PokemonAutomation_Computer_TestProgram_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/MacAddressOption.h" +#include "CommonTools/Options/ScreenWatchOption.h" +#include "ComputerPrograms/ComputerProgram.h" + +namespace PokemonAutomation{ + + +class TestProgramComputer_Descriptor : public ComputerProgramDescriptor{ +public: + TestProgramComputer_Descriptor(); +}; + + + +class TestProgramComputer : public ComputerProgramInstance{ +public: + TestProgramComputer(); + + virtual void program(ProgramEnvironment& env, CancellableScope& scope) override; + +private: + StaticTextOption STATIC_TEXT; + ScreenWatchOption SCREEN_WATCHER; + MacAddressCell MAC_ADDRESS; +}; + + + + +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp index 829723945e..e500d36e92 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.cpp @@ -1,2694 +1,2694 @@ -/* Test Program (Switch) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "TestProgramSwitch.h" - -//#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "Common/Cpp/Concurrency/PeriodicScheduler.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h" -#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" -#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" -#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "PokemonSV/Inference/PokemonSV_PokePortalDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h" -#include "PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" -#include "PokemonSV/Programs/PokemonSV_AreaZero.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h" -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameSave.h" -#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" -#include "PokemonSV/Inference/PokemonSV_BagDetector.h" -#include -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" -#include "PokemonSV/Inference/PokemonSV_StatHexagonReader.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -//#include "CommonFramework/Environment/SystemSleep.h" -#include "CommonFramework/ErrorReports/ErrorReports.h" -#include "PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h" -#include "PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h" -#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" -//#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" -#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" -#include "PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h" -#include "PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" -#include "CommonTools/Images/ImageFilter.h" -#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h" -#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" - -#include -#include - -//#include -#include -using std::cout; -using std::endl; - - -using namespace PokemonAutomation::Kernels; -using namespace PokemonAutomation::Kernels::Waterfill; - - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - - - -TestProgram_Descriptor::TestProgram_Descriptor() - : MultiSwitchProgramDescriptor( - "NintendoSwitch:TestProgram", - "Nintendo Switch", "Test Program (Switch)", - "", - "Test Program (Switch)", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::ENABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, - FasterIfTickPrecise::NOT_FASTER, - 1, 4, 1 - ) -{} - - -TestProgram::~TestProgram(){ - BUTTON1.remove_listener(*this); - BUTTON0.remove_listener(*this); -} -TestProgram::TestProgram() - : BUTTON0( - "Button Text 0", 0, 16 - ) - , BUTTON1( - "Button Label:
asdfasdfasdf", - "Button Text 1", 0, 16 - ) - , LANGUAGE( - "OCR Language:", - PokemonSwSh::IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - false - ) - , IMAGE_PATH(false, "Path to image for testing", LockMode::UNLOCK_WHILE_RUNNING, "default.png", "default.png") - , STATIC_TEXT("Test text...") -// , PLAYER_LIST("Test Table", LockMode::UNLOCK_WHILE_RUNNING, "Notes") - , DATE0( - "Date", - LockMode::UNLOCK_WHILE_RUNNING, - DateTimeOption::DATE_HOUR_MIN, - DateTime{2000, 1, 1, 0, 0, 0}, - DateTime{2060, 12, 31, 23, 59, 59}, - DateTime{2024, 4, 12, 2, 16, 30} - ) - , DATE1( - "Date", - LockMode::UNLOCK_WHILE_RUNNING, - DateTimeOption::DATE_HOUR_MIN, - DateTime{2000, 1, 1, 0, 0, 0}, - DateTime{2060, 12, 31, 23, 59, 59}, - DateTime{2048, 1, 13, 20, 48} - ) - , DURATION( - "Duration", - LockMode::UNLOCK_WHILE_RUNNING, - "100" - ) - , COLOR( - LockMode::UNLOCK_WHILE_RUNNING, - false, - 0x000000, 0x000000 - ) - , NOTIFICATION_TEST("Test", true, true, ImageAttachmentMode::JPG) - , NOTIFICATIONS({ - &NOTIFICATION_TEST, -// &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(BUTTON0); - PA_ADD_OPTION(BUTTON1); - PA_ADD_OPTION(LANGUAGE); -// PA_ADD_OPTION(CONSOLE_MODEL); - PA_ADD_OPTION(IMAGE_PATH); - PA_ADD_OPTION(STATIC_TEXT); -// PA_ADD_OPTION(PLAYER_LIST); -// PA_ADD_OPTION(battle_AI); - PA_ADD_OPTION(DATE0); - PA_ADD_OPTION(DATE1); - PA_ADD_OPTION(DURATION); - PA_ADD_OPTION(COLOR); - PA_ADD_OPTION(CONTROLLER_TABLE); - PA_ADD_OPTION(NOTIFICATIONS); - BUTTON0.add_listener(*this); - BUTTON1.add_listener(*this); -} - - -//using namespace Kernels; -using namespace Kernels::Waterfill; - -using namespace PokemonSV; - - -void TestProgram::on_press(){ - global_logger_tagged().log("Button Pressed"); -// BUTTON.set_enabled(false); - BUTTON0.set_text("Button Pressed"); - BUTTON1.set_text("Button Pressed"); -} - - - - - - - - - - -void TestProgram::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - using namespace Kernels; - using namespace Kernels::Waterfill; - using namespace OCR; - using namespace NintendoSwitch; - using namespace Pokemon; - using namespace PokemonSwSh; -// using namespace PokemonBDSP; - using namespace PokemonLA; -// using namespace PokemonSV; - - [[maybe_unused]] Logger& logger = env.logger(); - [[maybe_unused]] ConsoleHandle& console = env.consoles[0]; -// [[maybe_unused]] BotBase& botbase = env.consoles[0]; - [[maybe_unused]] VideoFeed& feed = env.consoles[0]; - [[maybe_unused]] VideoOverlay& overlay = env.consoles[0]; - ProControllerContext context(scope, console.pro_controller()); - VideoOverlaySet overlays(overlay); - - - - -#if 1 - HomeMenuDetector detector0(console); - StartGameUserSelectDetector detector1(console); - UpdatePopupDetector detector2(console); - detector0.make_overlays(overlays); - detector1.make_overlays(overlays); - detector2.make_overlays(overlays); - cout << detector0.detect(feed.snapshot()) << endl; - cout << detector1.detect(feed.snapshot()) << endl; - cout << detector2.detect(feed.snapshot()) << endl; -#endif - - - -// ImageRGB32 image0("menu-light.png"); -// ImageRGB32 image1("menu-dark.png"); -// ImageRGB32 image2("menu-jpn.png"); - -#if 0 - env.log("Touching date to prevent rollover."); - pbf_press_button(context, BUTTON_HOME, 160ms, PokemonSwSh::GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); -#endif - - - -#if 0 - auto screenshot = feed.snapshot(); - - - BinarySliderDetector detector(COLOR_RED, {0.831784, 0.140496, 0.088290, 0.671074}); - auto sliders = detector.detect(screenshot); - - for (auto& item : sliders){ - cout << item.first << " : " << item.second.min_y << endl; - } -#endif - -#if 0 - ImageFloatBox box(0.842007, 0.626446, 0.050186, 0.049587); - ImageViewRGB32 cropped = extract_box_reference(screenshot, box); - - cropped.save("temp.png"); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - cropped, 0xffc0c0c0, 0xffffffff - ); - - cout << matrix.dump() << endl; - - std::vector objects = find_objects_inplace(matrix, 200); - cout << "objects.size() = " << objects.size() << endl; - for (auto& item : objects){ - extract_box_reference(cropped, item).save("test.png"); - } -#endif - - - -// FastCodeEntry::numberpad_enter_code(console, context, "708538991006", true); - - - -#if 0 -// ssf_issue_scroll(context, DPAD_LEFT, 48ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 96ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_L, 0ms, 48ms, 24ms); - ssf_issue_scroll(context, DPAD_LEFT, 48ms, 48ms, 24ms); -#endif - -#if 0 - DateReader reader; - reader.make_overlays(overlays); - auto date = reader.read_date(logger, feed.snapshot()); - - cout << "date format = " << (int)date.first << endl; -// cout << "date = " << (int)date.second << endl; -#endif - - - -#if 0 -// DateReader_Switch2_US reader(COLOR_RED); - DateReader_Switch2_JP reader(COLOR_RED); - reader.make_overlays(overlays); - DateTime date = reader.read_date(logger, feed.snapshot()); - - cout << "Month = " << (int)date.month << endl; - cout << "Day = " << (int)date.day << endl; - cout << "Year = " << (int)date.year << endl; - cout << "Hour = " << (int)date.hour << endl; - cout << "Minute = " << (int)date.minute << endl; -#endif - - -#if 0 - DateChangeDetector_Switch2 detector(COLOR_RED); - detector.make_overlays(overlays); - cout << detector.detect(feed.snapshot()) << endl; -#endif - - -#if 0 - DateReader reader(console); - reader.make_overlays(overlays); - DateTime date = reader.read_date(logger, feed.snapshot()).second; - - cout << "Month = " << (int)date.month << endl; - cout << "Day = " << (int)date.day << endl; - cout << "Year = " << (int)date.year << endl; - cout << "Hour = " << (int)date.hour << endl; - cout << "Minute = " << (int)date.minute << endl; - - while (true){ - reader.set_date(env.program_info(), console, context, DATE0); - for (int c = 0; c < 7; c++){ - ssf_issue_scroll_ptv(context, DPAD_LEFT); - } - reader.set_date(env.program_info(), console, context, DATE1); - for (int c = 0; c < 7; c++){ - ssf_issue_scroll_ptv(context, DPAD_LEFT); - } - } -#endif - - - -// rollback_hours_from_home(console, context, 3, 500ms); - - - -#if 0 - while (true){ - roll_date_backward_N_Switch2_wired(context, 60); - for (size_t c = 0; c < 60; c++){ - roll_date_forward_1(console, context, true); - } - } -#endif - - - -#if 0 - while (true){ - home_to_date_time(console, context, true); -// home_to_date_time_Switch2_wired_blind(context, true); - ssf_do_nothing(context, 1000ms); - pbf_press_button(context, BUTTON_HOME, 200ms, 1800ms); - } -#endif - - - - -#if 0 - ConsoleTypeDetector_Home detector(console); - detector.make_overlays(overlays); - - cout << (int)detector.detect(feed.snapshot()) << endl; -#endif - - - -#if 0 - UpdatePopupDetector detector; - detector.make_overlays(overlays); - - cout << detector.detect(feed.snapshot()) << endl; -#endif - - - - - -#if 0 - home_to_date_time(console, context, false); -#endif - -#if 0 -// std::terminate(); - ImageRGB32 image("20250503-121259857603.png"); - - image = filter_rgb32_brightness(image, COLOR_RED, false, 0x00ffff01, 0, 200); - image.save("temp.png"); -#endif - - -#if 0 - ImageRGB32 image("20250503-121259857603.png"); - - { - TeraTypeReader reader; - ImageMatch::ImageMatchResult results = reader.read(image); - results.log(logger, 120); - } - { - TeraSilhouetteReader reader; - ImageMatch::ImageMatchResult results = reader.read(image); - results.log(logger, 120); - } -#endif - -#if 0 - Milliseconds unit = 24ms; - - ssf_issue_scroll(context, DPAD_DOWN, 2*unit, 2*unit, unit); - ssf_issue_scroll(context, DPAD_LEFT, unit, 2*unit, unit); - ssf_issue_scroll(context, DPAD_LEFT, unit, 2*unit, unit); - ssf_issue_scroll(context, DPAD_LEFT, unit, 2*unit, unit); - - -#endif - - - -#if 0 - ssf_press_button(context, Button::BUTTON_ZR, 1s, 60h, 0ms); -// context->issue_gyro_rotate_x(&scope, 0s, 60h, 0ms, 0x1000); -// context->issue_gyro_rotate_y(&scope, 0s, 60h, 0ms, 0x0000); -// context->issue_gyro_rotate_z(&scope, 0s, 60h, 0ms, 0x1000); - -// auto duration = 10s; - -// context->issue_gyro_rotate_x(&scope, duration, duration, 0s, 0x1000); -// context->issue_nop(&scope, 60h); - -#if 1 - auto duration = 15ms; - for (size_t c = 0; c < 65536; c += 1){ - context->issue_gyro_accel_x(&scope, 0s, duration, 0s, (uint16_t)(688 + 0*c % 2)); - context->issue_gyro_accel_y(&scope, 0s, duration, 0s, (uint16_t)(1*c % 2)); - context->issue_gyro_accel_z(&scope, 0s, duration, 0s, (uint16_t)(-4038 + 0*c % 2)); - context->issue_gyro_rotate_x(&scope, 0s, duration, 0s, (uint16_t)(0x0000 + 1*c)); - context->issue_gyro_rotate_y(&scope, 0s, duration, 0s, (uint16_t)(0x0000 + 1*c)); - context->issue_gyro_rotate_z(&scope, 0s, duration, 0s, (uint16_t)(0x0000 + 0*c)); - context->issue_nop(&scope, duration); - } -#endif -#endif - - -#if 0 - ImageRGB32 image("20250420-043111395281.png"); - - OcrFailureWatchdog watchdog(logger); - - PokemonSwSh::MaxLairInternal::PokemonSwapMenuReader reader(logger, overlay, Language::Korean, watchdog); - - double hp[4]; - reader.read_hp(image, hp); -#endif - -#if 0 - ImageRGB32 image("20250404-154507236508.png"); - - ArcPhoneDetector phone(logger, overlay, std::chrono::milliseconds(250), true); - - while (true){ - cout << phone.process_frame(image, current_time()) << endl; - scope.wait_for(100ms); - } - -#if 0 - wait_until( - console, context, - 10000ms, - {phone} - ); -#endif -#endif - -#if 0 - // ImageRGB32 image(IMAGE_PATH); - auto image = feed.snapshot(); -#if 1 - ImageRGB32 image(IMAGE_PATH); - // auto image = feed.snapshot(); - - SandwichHandLocator hand(SandwichHandType::FREE, {0, 0, 1, 1}); - std::pair location = hand.locate_sandwich_hand(image, {0,0,1,1}); - cout << location.first << ", " << location.second << endl; -#endif - -#if 0 - ImageRGB32 image(IMAGE_PATH); - // auto image = feed.snapshot(); - - ItemPrinterMaterialDetector detector(COLOR_RED, Language::English); - - std::vector boxes = { - // {0.485,0.176758,0.037,0.05}, {0.485,0.250977,0.037,0.05}, {0.485,0.325196,0.037,0.05}, {0.485,0.399415,0.037,0.05}, {0.485,0.473634,0.037,0.05}, {0.485,0.547853,0.037,0.05}, {0.485,0.622072,0.037,0.05}, {0.485,0.696291,0.037,0.05}, {0.485,0.77051,0.037,0.05}, {0.485,0.844729,0.037,0.05}, - {0.39,0.176758,0.025,0.05}, {0.39,0.250977,0.025,0.05}, {0.39,0.325196,0.025,0.05}, {0.39,0.399415,0.025,0.05}, {0.39,0.473634,0.025,0.05}, {0.39,0.547853,0.025,0.05}, {0.39,0.622072,0.025,0.05}, {0.39,0.696291,0.025,0.05}, {0.39,0.77051,0.025,0.05}, {0.39,0.844729,0.025,0.05}, - }; - for (ImageFloatBox box : boxes){ - detector.read_number(console.logger(), env.inference_dispatcher(), image, box); - } - -#endif -#endif - -#if 0 - - ImageRGB32 image("20250323-011605651979.png"); - - DialogBoxDetector detector; - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; - -#endif - - -#if 0 - auto image = feed.snapshot(); - - ItemPrinterMenuDetector detector(COLOR_GREEN); - cout << detector.detect(image) << endl; -#endif - - -// numberpad_enter_code(logger, context, "708538991006", false); - - - -#if 0 - for (size_t i = 0; i < 100; i++){ - for (size_t c = 0; c < 4; c++){ - ssf_issue_scroll(context, DPAD_RIGHT, 17ms); - } - for (size_t c = 0; c < 4; c++){ - ssf_issue_scroll(context, DPAD_LEFT, 17ms); - } - } -#endif - - - -#if 0 - while (true){ - for (size_t c = 0; c < 60; c++){ - ssf_issue_scroll(context, DPAD_DOWN, 24ms); - } - ssf_do_nothing(context, 1000ms); - for (size_t c = 0; c < 60; c++){ - ssf_issue_scroll(context, DPAD_UP, 24ms); - } - ssf_do_nothing(context, 1000ms); - } -#endif - -// pbf_move_left_joystick(context, 38, 38, 10000, 0); - - -// ssf_issue_scroll(context, DPAD_LEFT, 0); -// ssf_press_button(context, BUTTON_A | BUTTON_L, 3); -// ssf_press_button(context, BUTTON_L, 0); - -#if 0 - numberpad_enter_code( - logger, context, - "708538991006", - false - ); -#endif - -#if 0 - codeboard_enter_digits( - logger, context, KeyboardLayout::QWERTY, - "JRH5T9", - true, - CodeboardDelays{ - .hold = 5 * 8ms, - .cool = 3 * 8ms, - .press_delay = 4 * 8ms * 1, - .move_delay = 5 * 8ms * 1, - .wrap_delay = 6 * 8ms * 1, - } - ); -#endif - -// ssf_flush_pipeline(context); - - -// return_to_academy_after_loss(env, console, context); - - - - -// fly_from_paldea_to_blueberry_entrance(env.program_info(), console, context); - - - -#if 0 - ssf_press_button(context, BUTTON_A, 0); - ssf_do_nothing(context, 4); - ssf_press_button(context, BUTTON_A, 0); - ssf_do_nothing(context, 4); - ssf_press_button(context, BUTTON_A, 0); - ssf_do_nothing(context, 4); - ssf_press_button(context, BUTTON_A, 0); - ssf_do_nothing(context, 4); -#endif - - - -// enter_digits(context, 8, (const uint8_t*)"56685459"); - -#if 0 - for (int c = 0; c < 10; c++){ - scroll_to(context, 1, 9, true); - scroll_to(context, 9, 1, true); - } -// pbf_wait(context, 100); -#endif - - -#if 0 - ImageRGB32 image("20250131-170450792229.png"); - - PokemonSwSh::BattleBallReader reader(console, Language::Korean); - reader.read_ball(image); -#endif - - -#if 0 - { - TeraTypeReader reader; - ImageMatch::ImageMatchResult results = reader.read(image); - results.log(logger, 100); - } -#endif - - -#if 0 - ImageRGB32 image("20250125-224044294692.png"); - MaxLairInternal::BattleMenuReader reader(overlay, Language::English); - std::set slugs = reader.read_opponent_in_summary(logger, image); - - cout << set_to_str(slugs) << endl; -#endif - -// ssf_press_button(context, BUTTON_A, 0, 1000, 0); -// pbf_move_left_joystick(context, 0, 0, 20, 0); - - - -#if 0 - ImageRGB32 image("20250218-003554940153.png"); -// ImageRGB32 image("raidecho1.jpg"); -// auto image = feed.snapshot(); - -// MaxLairInternal::BattleMenuReader reader(overlay, Language::English); -// reader.read_opponent_in_summary(logger, image); - - TeraCardReader reader; - cout << reader.detect(image) << endl; - reader.pokemon_slug(logger, env.program_info(), image); -// cout << (int)reader.stars(logger, env.program_info(), image) << endl; -#endif - - - - - -#if 0 - ImageRGB32 image("20250112-194339635973.png"); - - PokemonBDSP::SelectionArrowFinder detector0(console, {0.50, 0.58, 0.40, 0.10}, COLOR_RED); - PokemonBDSP::SelectionArrowFinder detector1(console, {0.50, 0.52, 0.40, 0.10}, COLOR_RED); - - cout << detector0.detect(image) << endl; - cout << detector1.detect(image) << endl; -#endif - - - -#if 0 - PokemonSwSh::MaxLairInternal::PokemonSwapMenuReader reader(console, overlay, Language::English); - - ImageRGB32 image("20241221-123730238930.png"); - - double hp[4]; - reader.read_hp(image, hp); -#endif - -// reader.read_opponent_in_summary(logger, image); - -// PokemonSwSh::find_selection_arrows(image, 10); - - -// LifetimeSanitizer::terminate_with_dump(); - -// PokemonSV::AuctionFarmer farmer; -// farmer.check_offers(env); -// std::terminate(); - -#if 0 - ImageRGB32 image("screenshot-20241210-110029984325.png"); -// auto image = feed.snapshot(); - - MMOQuestionMarkDetector question_mark_detector(logger); - question_mark_detector.detect_MMO_on_hisui_map(image); -#endif - - -#if 0 - PokemonLA::OutbreakReader reader(logger, Language::English, overlay); - reader.make_overlays(overlays); - - ImageRGB32 image("screenshot-20241124-135028529403.png"); -#endif - -// reader.read(feed.snapshot()); - - -// PokemonLA::ButtonDetector detector(logger, PokemonLA::ButtonType::ButtonA,); - -// while (true){ -// SystemSleepController::instance().push_screen_on(); -// scope.wait_for(std::chrono::seconds(10)); -// } - -// SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED); - -// console.save_stream_history("video.mp4"); - -#if 0 - VideoSnapshot image = feed.snapshot(); - report_error( - &env.logger(), - env.program_info(), - "testtest", - {{"title", "message"}}, - image, - {"test.txt"} - ); -#endif - -#if 0 - VideoSnapshot image = feed.snapshot(); -// ImageRGB32 image("20250108-151305644248.png"); - - DateReader date_reader; - date_reader.make_overlays(overlays); - auto date = date_reader.read_date(logger, image); -// auto date = date_reader.read_date(logger, std::make_shared(std::move(image))); - cout << "year = " << (int)date.second.year << endl; - cout << "month = " << (int)date.second.month << endl; - cout << "day = " << (int)date.second.day << endl; - cout << "hour = " << (int)date.second.hour << endl; - cout << "min = " << (int)date.second.minute << endl; - cout << "secs = " << (int)date.second.second << endl; -#endif - -#if 0 - - VideoSnapshot image = feed.snapshot(); - DirectionDetector detector; - - // ImageRGB32 image("MaterialFarmer-1.png"); - // ImageRGB32 image("dark-capture-card_1.png"); - // DirectionDetector detector(COLOR_BLUE, ImageFloatBox(0,0,1,1)); - - // std::pair north_location = detector.locate_north(image); - // detector.current_direction(image); - detector.change_direction(env.program_info(), console, context, 3.14); - -#endif - -#if 0 - ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); - detector.make_overlays(overlays); - // cout << (int)detector.find_happiny_dust_row_index(env.inference_dispatcher(), console, context) << endl; - // cout << (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2) << endl; - - // test OCR for number 1 -> 999. for black text on light background. - // increasing quantity of materials to sell. - for (int i = 1; i < 1000; i++){ - context.wait_for_all_requests(); - if (i != (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - console, - "OCR didn't match expected value." - ); - } - pbf_press_dpad(context, DPAD_UP, 20, 30); - } - - // test OCR for number 1 -> 999. for white text on dark background - // decreasing quantity of current materials by selling. - // for (int i = 999; i > 0; i--){ - // context.wait_for_all_requests(); - // if (i != (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2)){ - // OperationFailedException::fire( - // ErrorReport::SEND_ERROR_REPORT, - // console, - // "OCR didn't match expected value." - // ); - // } - // pbf_press_button(context, BUTTON_A, 30, 150); - // pbf_press_button(context, BUTTON_A, 30, 150); - // pbf_press_button(context, BUTTON_A, 30, 150); - // pbf_press_button(context, BUTTON_A, 30, 150); - // } - - -#endif - -#if 0 - ImageRGB32 image("screenshot-20240701-165012250266.png"); - - BattleBallReader reader(console, Language::English); - cout << reader.read_quantity(image) << endl; -#endif - -#if 0 - // ImageRGB32 image("screenshot-20240701-165012250266.png"); - - // BattleBallReader reader(console, Language::English); - // cout << reader.read_quantity(image) << endl; - - VideoSnapshot image = feed.snapshot(); - // IngredientSession session(env.inference_dispatcher(), console, context, Language::English, SandwichIngredientType::CONDIMENT); - // session.read_ingredient_quantity(console, context, 8); - - SandwichIngredientReader reader(SandwichIngredientType::FILLING); - // ImageMatch::ImageMatchResult image_result = reader.read_with_icon_matcher(image, ImageFloatBox(0.508, 0.820, 0.032, 0.057)); - for (int i = 0; i < 6; i++){ - ImageMatch::ImageMatchResult image_result = reader.read_with_icon_matcher(image, ImageFloatBox(0.508781 + 0.0468*i, 0.820, 0.032, 0.057)); - image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); - image_result.log(console, SandwichIngredientReader::MAX_ALPHA); - image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); - } -#endif - - -#if 0 - ImageRGB32 image("screenshot-20240630-183016042676.png"); - - ButtonTracker tracker(ButtonType::ButtonA); - WhiteObjectWatcher watcher(overlay, {0.55, 0.40, 0.20, 0.40}, { {tracker, false} }); - watcher.process_frame(image, current_time()); -#endif - -#if 0 - VideoSnapshot screen = console.video().snapshot(); - ItemPrinterJobsDetector detector(COLOR_RED); - cout << (int)detector.detect_jobs(logger, env.inference_dispatcher(), screen) << endl; -#endif - -#if 0 - ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); - detector.make_overlays(overlays); - // cout << (int)detector.find_happiny_dust_row_index(env.inference_dispatcher(), console, context) << endl; - cout << (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2) << endl; -#endif - -#if 0 - VideoSnapshot screen = console.video().snapshot(); - ItemPrinterJobsDetector detector(COLOR_RED); - cout << (int)detector.detect_jobs(logger, env.inference_dispatcher(), screen) << endl; -#endif - -#if 0 - VideoSnapshot screen = console.video().snapshot(); - - OverworldDetector detector; - cout << detector.detect(screen) << endl; -#endif - -#if 0 - ItemPrinterJobsDetector detector(COLOR_RED, LANGUAGE); - detector.make_overlays(overlays); - - detector.set_print_jobs(console, context, 5); -#endif - - -#if 0 - ItemPrinterPrizeReader reader(Language::English); - reader.make_overlays(overlays); - - reader.read(logger, env.inference_dispatcher(), feed.snapshot()); -#endif - - -// SinglesAIOption battle_AI; -// run_singles_battle(env, console, context, battle_AI, false); - - - - -// pbf_press_button(context, BUTTON_HOME, 20, GameSettings::instance().GAME_TO_HOME_DELAY); -// reset_game_from_home(env.program_info(), console, context, 5 * TICKS_PER_SECOND); - - -#if 0 - VideoSnapshot screen = console.video().snapshot(); - - PokemonSummaryDetector summary; - cout << summary.detect(screen) << endl; -#endif - - -#if 0 - ImageViewRGB32 box = extract_box_reference(screen, ImageFloatBox(0.28, 0.20, 0.03, 0.055)); - ImageStats stats = image_stats(box); - cout << stats.average << stats.stddev << endl; - - bool item_held = !is_solid(stats, {0.550405, 0.449595, 0.}, 0.20); - cout << "item_held = " << item_held << endl; -#endif - -#if 0 - run_pokemon( - console, context, - { - {SinglesMoveType::Move1, false}, - {SinglesMoveType::Move2, false}, - {SinglesMoveType::Move4, true}, - {SinglesMoveType::Run, false}, - } - ); -#endif - - - -#if 0 - auto snapshot = console.video().snapshot(); - - PokemonSummaryDetector detector; - detector.make_overlays(overlays); - cout << detector.detect(snapshot) << endl; -#endif - - -#if 0 - auto snapshot = console.video().snapshot(); - ImageViewRGB32 box0 = extract_box_reference(snapshot, ImageFloatBox{0.415, 0.085, 0.035, 0.057}); - ImageViewRGB32 box1 = extract_box_reference(snapshot, ImageFloatBox{0.553, 0.085, 0.035, 0.057}); - - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(box1, 0xff808080, 0xffffffff); - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (iter->find_next(object, false)){ - extract_box_reference(box1, object).save("test.png"); - } - } - #endif - - - -// PokemonSwSh::ReceivePokemonDetector caught_detector(true); -// caught_detector.process_frame(); - - -#if 0 - start_game_from_home( - console, context, - true, 0, 0, - 10 - ); -#endif - -#if 0 -// UpdateMenuWatcher update_menu(false); - CheckOnlineDetector update_menu(false); - update_menu.make_overlays(overlays); - - auto snapshot = console.video().snapshot(); - cout << update_menu.detect(snapshot) << endl; -#endif - -#if 0 - -// ImageRGB32 image("screenshot-20231003-202430049819.png"); - auto snapshot = console.video().snapshot(); - - PokemonSummaryDetector detector; - cout << detector.detect(snapshot) << endl; -#endif - -#if 0 - SummaryStatsReader reader; - reader.make_overlays(overlays); - - auto snapshot = console.video().snapshot(); - - NatureAdjustments nature = reader.read_nature(logger, snapshot); - cout << "attack = " << (int)nature.attack << endl; - cout << "defense = " << (int)nature.defense << endl; - cout << "spatk = " << (int)nature.spatk << endl; - cout << "spdef = " << (int)nature.spdef << endl; - cout << "speed = " << (int)nature.speed << endl; - - StatReads stats = reader.read_stats(logger, snapshot); - cout << "hp = " << stats.hp << endl; - cout << "attack = " << stats.attack << endl; - cout << "defense = " << stats.defense << endl; - cout << "spatk = " << stats.spatk << endl; - cout << "spdef = " << stats.spdef << endl; - cout << "speed = " << stats.speed << endl; - - BaseStats base_stats{113, 70, 120, 135, 65, 52}; - EVs evs{0, 0, 0, 0, 0, 0}; - IvRanges ivs = reader.calc_ivs(logger, snapshot, base_stats, evs); - cout << "hp = " << (int)ivs.hp.low << " - " << (int)ivs.hp.high << endl; - cout << "attack = " << (int)ivs.attack.low << " - " << (int)ivs.attack.high << endl; - cout << "defense = " << (int)ivs.defense.low << " - " << (int)ivs.defense.high << endl; - cout << "spatk = " << (int)ivs.spatk.low << " - " << (int)ivs.spatk.high << endl; - cout << "spdef = " << (int)ivs.spdef.low << " - " << (int)ivs.spdef.high << endl; - cout << "speed = " << (int)ivs.speed.low << " - " << (int)ivs.speed.high << endl; -#endif - - -#if 0 - cout << "attack: "; - reader.read_stat_adjustment({0.874, 0.293, 0.014, 0.024}, snapshot); - cout << "spatk: "; - reader.read_stat_adjustment({0.770, 0.293, 0.014, 0.024}, snapshot); - cout << "speed: "; - reader.read_stat_adjustment({0.822, 0.452, 0.014, 0.024}, snapshot); -#endif - - -#if 0 - ImageFloatBox hp (0.823, 0.244, 0.012, 0.022); - ImageFloatBox atk (0.875, 0.294, 0.012, 0.022); - ImageFloatBox def (0.875, 0.402, 0.012, 0.022); - ImageFloatBox spatk (0.771, 0.294, 0.012, 0.022); - ImageFloatBox spdef (0.771, 0.402, 0.012, 0.022); - ImageFloatBox spd (0.823, 0.453, 0.012, 0.022); - - overlays.add(COLOR_RED, hp); - overlays.add(COLOR_RED, atk); - overlays.add(COLOR_RED, def); - overlays.add(COLOR_RED, spatk); - overlays.add(COLOR_RED, spdef); - overlays.add(COLOR_RED, spd); -#endif - - - -#if 0 - PokemonSwSh::MaxLairInternal::LobbyJoinedDetector detector(2, false); - - auto snapshot = console.video().snapshot(); -// detector.VisualInferenceCallback::process_frame(snapshot); - detector.joined(snapshot, snapshot.timestamp); -#endif - -// size_t errors = 0; -// attach_item_from_bag(env.program_info(), console, context, errors); -// attach_item_from_box(env.program_info(), console, context, 1, errors); - -// BagDetector detector; -// detector.make_overlays(overlays); -// auto snapshot = console.video().snapshot(); -// cout << detector.detect(snapshot) << endl; - - -#if 0 - TeraCatchDetector detector(COLOR_RED); - detector.make_overlays(overlays); - - auto snapshot = console.video().snapshot(); - cout << detector.detect(snapshot) << endl; - - detector.move_to_slot(console, context, 1); -#endif - -// std::shared_ptr screen(new ImageRGB32("20230920-123043559137-OperationFailedException.png")); - -// IngredientSession session(env.inference_dispatcher(), console, context, Language::English, SandwichIngredientType::FILLING); -// session.read_screen(screen); - - - - -// pbf_press_dpad(context, DPAD_RIGHT, 160, 0); -// pbf_press_dpad(context, DPAD_DOWN, 40, 0); - - - - -// PokemonLA::save_game_from_overworld(env, console, context); - - - - - -#if 0 - TeraCardReader reader; - - auto snapshot = console.video().snapshot(); - cout << reader.detect(snapshot) << endl; -#endif - -#if 0 - NormalDialogDetector detector(logger, overlay, true); - - detector.make_overlays(overlays); - - auto snapshot = console.video().snapshot(); - cout << detector.process_frame(snapshot, snapshot.timestamp) << endl; -#endif - -// PokemonLA::open_travel_map_from_jubilife(env, console, context); - - - - - - -#if 0 - FrozenImageDetector detector(std::chrono::seconds(5), 10); - - int ret = wait_until( - console, scope, std::chrono::seconds(10), - {detector} - ); - if (ret >= 0){ - console.log("triggered"); - }else{ - console.log("timed out"); - } -#endif - -// NewsDetector detector; -// detector.make_overlays(overlays); - - - -// VideoSnapshot image = feed.snapshot(); - -// BoxSelectionBoxModeWatcher watcher; -// watcher.process_frame(image, image.timestamp); - -// connect_to_internet_from_overworld(env.program_info(), console, context); - - - -#if 0 - MainMenuDetector detector; - detector.make_overlays(overlays); - detector.move_cursor(env.program_info(), console, context, MenuSide::RIGHT, 6, true); -#endif - -#if 0 - ImageRGB32 image("20230226-042613391191-PathPartyReader-ReadSprites.png"); - - PokemonSwSh::MaxLairInternal::GlobalState state; - PokemonSwSh::MaxLairInternal::PathReader reader(overlay, 0); - reader.read_sprites(logger, state, image); -#endif - -// NintendoSwitch::PokemonSwSh::BattleBallReader reader(console, Language::English); -// reader.read_ball(image); - - - -// basic_catcher(console, context, Language::English, "beast-ball", true); - -#if 0 - VideoSnapshot image = feed.snapshot(); - IngredientSession session(env.inference_dispatcher(), console, context, Language::English); - session.read_current_page(); -#endif - - - -#if 0 - add_sandwich_ingredients( - env.inference_dispatcher(), console, context, Language::English, - { - {"pickle", 1}, - {"cucumber", 1}, - {"tomato", 3}, - }, - { - {"sour-herba-mystica", 1}, - {"spicy-herba-mystica", 1}, - } - ); -#endif - - -#if 0 - IngredientSession session(env.inference_dispatcher(), console, context, Language::English); -// basic_catcher(console, context, Language::English, "poke-ball", true); - - -#if 0 - PageIngredients page = session.read_current_page(); - for (size_t c = 0; c < 10; c++){ - cout << set_to_str(page.item[c]) << endl; - } -#endif - -// cout << "Found: " << session.move_to_ingredient({"tomato"}) << endl; - session.add_ingredients(console, context, { - {"pickle", 1}, - {"cucumber", 1}, - {"tomato", 3}, - }); - pbf_press_button(context, BUTTON_PLUS, 20, 230); - - pbf_press_dpad(context, DPAD_UP, 20, 105); - session.add_ingredients(console, context, { - {"sour-herba-mystica", 1}, - {"spicy-herba-mystica", 1}, - }); - pbf_press_button(context, BUTTON_PLUS, 20, 230); -#endif - - -#if 0 - auto image = feed.snapshot(); - - NormalBattleMenuDetector detector(COLOR_RED); - detector.detect_slot(image); - detector.move_to_slot(console, context, 0); -#endif - - - -// save_game_from_menu_or_overworld(env.program_info(), console, context, true); - - - -// auto_heal_from_menu(env.program_info(), console, context, 0, true); - - - -// return_to_inside_zero_gate(env.program_info(), console, context); -// inside_zero_gate_to_secret_cave_entrance(env.program_info(), console, context); - - -// inside_zero_gate_to_station(env.program_info(), console, context, 1, false); -// ssf_press_left_joystick(context, 144, 0, 0, 5 * TICKS_PER_SECOND); -// pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); - -// pbf_move_left_joystick(context, 96, 255, 5 * TICKS_PER_SECOND, 0); - - -#if 0 - auto image = feed.snapshot(); - - NewsDetector detector; - cout << detector.detect(image) << endl; -#endif - - - -// pbf_mash_button(context, BUTTON_ZR, 3 * TICKS_PER_SECOND); - -#if 0 - auto image = feed.snapshot(); - SweatBubbleDetector detector(COLOR_RED, {0.11, 0.81, 0.06, 0.10}); - cout << detector.detect(image) << endl; -#endif - - -#if 0 - NavigatePlatformSettings settings; - - return_to_inside_zero_gate(env.program_info(), console, context); - inside_zero_gate_to_platform(env.program_info(), console, context, settings); -#endif - -#if 0 - auto image = feed.snapshot(); - - ImageRGB32 filtered = filter_rgb32_range(image, 0xff000040, 0xff8080ff, Color(0xffff0000), true); - filtered.save("test.png"); - - using namespace Kernels::Waterfill; - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000040, 0xff8080ff); - -// size_t min_width = screen.width() / 4; -// size_t min_height = screen.height() / 4; - - WaterfillObject biggest; - WaterfillObject object; - - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(10000); - while (iter->find_next(object, false)){ -// if (object.min_y != 0){ -// continue; -// } - if (biggest.area < object.area){ - biggest = std::move(object); - } - } - - cout << biggest.center_of_gravity_x() / image->width() << ", " << biggest.center_of_gravity_y() / image->height() << endl; -#endif - - -#if 0 -// pbf_controller_state(context, 0, DPAD_NONE, 192, 255, 116, 128, 3 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 192, 0, 20, 105); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - ssf_press_button(context, BUTTON_LCLICK, 0, 500); - ssf_press_joystick(context, true, 128, 0, 125, 1250); - - // Jump - ssf_press_button(context, BUTTON_B, 125, 100); - - // Fly - ssf_press_button(context, BUTTON_B, 0, 50); - - pbf_move_left_joystick(context, 144, 0, 750, 0); - pbf_move_left_joystick(context, 128, 0, 1000, 0); -#endif - -#if 0 - ZeroGateWarpPromptDetector detector; - auto image = feed.snapshot(); - detector.detect(image); -#endif - - -// zero_gate_to_platform(env.program_info(), console, context); - - -#if 0 - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 128, 0, 625, 0); - ssf_press_button(context, BUTTON_B, 0, 50); - pbf_move_left_joystick(context, 128, 0, 250, 0); - pbf_move_left_joystick(context, 160, 0, 600, 0); - pbf_move_left_joystick(context, 128, 0, 1875, 0); -#endif - - -#if 0 - EncounterWatcher encounter(console, COLOR_RED); - - throw ProgramFinishedException( - console, - "test", - encounter.shiny_screenshot() - ); -#endif - - -#if 0 - LetsGoKillWatcher watcher(logger, COLOR_RED, false); - - wait_until( - console, scope, std::chrono::seconds(600), - { - watcher, - } - ); -#endif - -#if 0 - LetsGoKillDetector detector(COLOR_RED, {0.71, 0.15, 0.04, 0.30}); - detector.make_overlays(overlays); - while (true){ - detector.detect(feed.snapshot()); - scope.wait_for(std::chrono::milliseconds(100)); - } -#endif - -#if 0 -// ImageRGB32 image("Screenshots/screenshot-20230205-141319486902.png"); - ImageRGB32 image("LetsGoKill.png"); - -// LetsGoKillDetector detector(COLOR_RED, {0.5, 0, 0.5, 0.5}); - LetsGoKillDetector detector(COLOR_RED, {0, 0, 1, 1}); - detector.detect(image); -#endif - - -#if 0 - EncounterWatcher encounter(console); - int ret = wait_until( - console, scope, std::chrono::seconds(600), - { - static_cast(encounter), - static_cast(encounter), - } - ); - encounter.throw_if_no_sound(); - - if (ret == 0){ - logger.log("Found battle menu!"); - } - - if (encounter.shiny_screenshot()){ - encounter.shiny_screenshot()->save("test.png"); - } -#endif - - -#if 0 - pbf_move_left_joystick(context, 128, 255, 300, 0); - pbf_move_left_joystick(context, 128, 0, 50, 0); - pbf_press_button(context, BUTTON_R, 20, 0); - pbf_move_left_joystick(context, 128, 0, 350, 0); -#endif -#if 0 - size_t count = 0; - while (true){ - NormalBattleMenuWatcher battle_menu(COLOR_RED); - AreaZeroSkyTracker sky_tracker(overlay); - context.wait_for_all_requests(); - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - while (true){ - switch (count++ % 2){ - case 0: - run_overworld(env, console, context, sky_tracker, 0.50); - break; - case 1: - run_overworld(env, console, context, sky_tracker, 0.70); - break; - } - } - }, - {battle_menu, sky_tracker} - ); - context.wait_for(std::chrono::milliseconds(200)); - if (ret == 0){ - console.log("Detected battle encounter."); - pbf_press_dpad(context, DPAD_DOWN, 250, 0); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); - } - } -#endif - - - - - - -#if 0 - auto image = feed.snapshot(); - - ImageRGB32 filtered = filter_rgb32_range(image, 0xffe0e000, 0xffffffff, Color(0xff000000), false); - filtered.save("test.png"); -#endif - -// change_view_to_stats_or_judge(console, context); -// change_view_to_judge(console, context, Language::English); - - - - -#if 0 - auto image = feed.snapshot(); - - ImageRGB32 filtered = filter_rgb32_range(image, 0xff808000, 0xffffffff, Color(0xff000000), false); - filtered.save("test.png"); -#endif - -#if 0 - TeraBattleMenuDetector battle_menu(COLOR_RED); - MoveSelectDetector move_select(COLOR_YELLOW); - CheerSelectDetector cheer_select(COLOR_GREEN); - battle_menu.make_overlays(overlays); - move_select.make_overlays(overlays); - cheer_select.make_overlays(overlays); - - auto image = feed.snapshot(); - cheer_select.detect_slot(image); -#endif - - -#if 0 - auto image = feed.snapshot(); - CodeEntryDetector detector; - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; -#endif - - -// enter_tera_search(env.program_info(), console, context, false); -// open_hosting_lobby(env.program_info(), console, context, HostingMode::ONLINE_CODED); - -#if 0 - auto image = feed.snapshot(); - TeraLobbyReader detector(console.logger(), env.realtime_dispatcher()); - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; -#endif - -#if 0 - size_t host_index = 1; - ConsoleHandle& host = env.consoles[host_index]; - BotBaseContext host_context(scope, host.botbase()); - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - if (console.index() == host_index){ - open_raid(console, context); - }else{ - enter_tera_search(env.program_info(), console, context, true); - } - }); - open_hosting_lobby(env.program_info(), host, host_context, HostingMode::ONLINE_CODED); - - TeraLobbyReader lobby_reader; - std::string code = lobby_reader.raid_code(env.logger(), env.realtime_dispatcher(), host.video().snapshot()); - std::string normalized_code; - const char* error = normalize_code(normalized_code, code); - if (error){ -// pbf_press_button(host_context, BUTTON_B, 20, 230); -// pbf_press_button(host_context, BUTTON_A, 20, 230); - OperationFailedException::fire(env.logger(), "Unable to read raid code."); - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - if (console.index() == host_index){ - return; - } - enter_code(console, context, FastCodeEntrySettings(), normalized_code, false); - }); -#endif - - - -#if 0 - TeraRaidSearchDetector detector(COLOR_YELLOW); - - auto image = feed.snapshot(); - cout << detector.detect(image) << endl; - detector.move_cursor_to_search(env.program_info(), console, context); -#endif - -#if 0 - auto image = feed.snapshot(); - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000000, 0xff808080); - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - - size_t c = 0; - while (iter->find_next(object, false)){ -// cout << "yellow = " << object.area << endl; - extract_box_reference(image, object).save("object-" + std::to_string(c++) + ".png"); -// yellows.emplace_back(std::move(object)); - } -#endif - - - - - - - -#if 0 - PokePortalDetector detector(COLOR_YELLOW); - - auto image = feed.snapshot(); - cout << detector.detect_location(image) << endl; - - detector.move_cursor(env.program_info(), console, context, 2); -#endif - - -// size_t errors; -// release_box(env.program_info(), console, context, errors, 1); - - - -#if 0 -// TeraCatchWatcher catch_menu(COLOR_BLUE); -#if 0 - WhiteButtonWatcher next_button( - COLOR_CYAN, - WhiteButton::ButtonA, - {0.8, 0.93, 0.2, 0.07}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::seconds(1) - ); -#endif -// AdvanceDialogWatcher advance(COLOR_YELLOW); - PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); - PromptDialogWatcher view_summary(COLOR_PURPLE, {0.500, 0.470, 0.400, 0.100}); - PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); -// PokemonSummaryWatcher summary(COLOR_MAGENTA); - MainMenuWatcher main_menu(COLOR_BLUE); -// OverworldWatcher overworld(COLOR_RED); - -// catch_menu.make_overlays(overlays); -// next_button.make_overlays(overlays); -// advance.make_overlays(overlays); - add_to_party.make_overlays(overlays); - view_summary.make_overlays(overlays); - nickname.make_overlays(overlays); -// summary.make_overlays(overlays); - main_menu.make_overlays(overlays); -// overworld.make_overlays(overlays); -#endif - - -#if 0 - OverworldWatcher overworld; - int ret = wait_until( - console, context, std::chrono::seconds(5), - {overworld} - ); - cout << ret << endl; -#endif - -#if 0 - ImageRGB32 image("BadArrow.png"); - - TeraBattleMenuDetector battle_menu(COLOR_RED); - MoveSelectDetector move_select(COLOR_GREEN); - TargetSelectDetector target_select(COLOR_CYAN); - TeraCatchDetector tera_catch(COLOR_BLUE); -// battle_menu.make_overlays(overlays); -// move_select.make_overlays(overlays); -// target_select.make_overlays(overlays); -// tera_catch.make_overlays(overlays); - cout << (int)battle_menu.detect_slot(image) << endl; - -// battle_menu.move_to_slot(console, context, 0); -// move_select.move_to_slot(console, context, 1); -// target_select.move_to_slot(console, context, 2); -#endif - - -// change_stats_view_to_judge(env.program_info(), console, context); - - -#if 0 - auto image = feed.snapshot(); - ImageFloatBox box(0.66, 0.08, 0.52, 0.04); - ImageStats stats = image_stats(extract_box_reference(image, box)); - cout << stats.average << stats.stddev << endl; -#endif - - - -#if 0 - auto image = feed.snapshot(); - - TeraLobbyReader detector; -// cout << detector.seconds_left(env.logger(), image) << endl; - cout << detector.raid_code(env.logger(), image) << endl; -#endif - - - -#if 0 - QClipboard* clipboard = QApplication::clipboard(); - cout << clipboard->supportsSelection() << endl; - - while (true){ - std::string code = clipboard->text(QClipboard::Selection).toStdString(); - cout << code << endl; - scope.wait_for(std::chrono::milliseconds(1000)); - } -#endif - - -// while (true){ - -// } - -#if 0 - pbf_move_left_joystick(context, 0, 128, 40, 40); - // Move forward to pass table - pbf_move_left_joystick(context, 128, 0, 80, 40); // old value: 80 - // Move right - pbf_move_left_joystick(context, 255, 128, 40, 40); - // Move back to face basket - pbf_move_left_joystick(context, 128, 255, 10, 40); -#endif - - -#if 0 -// ImageFloatBox box(0.02, ); - auto image = feed.snapshot(); - WhiteButtonDetector detector(COLOR_RED, WhiteButton::ButtonA, {0.020, 0.590, 0.035, 0.060}); - cout << detector.detect(image) << endl; -#endif - - -// auto image = feed.snapshot(); -// TeraCatchDetector detector(COLOR_RED); -// cout << detector.detect(image) << endl; - -// size_t errors; -// release_one_pokemon(env.program_info(), console, context, errors); - - -#if 0 - auto image = feed.snapshot(); - - TeraLobbyReader detector; - detector.make_overlays(overlays); - detector.ready_players(image); -#endif - -#if 0 - MainMenuDetector detector; - detector.move_cursor(env.program_info(), console, context, MenuSide::RIGHT, 1); - cout << "done" << endl; -#endif - - -#if 0 - size_t eggs_collected = 0; - check_basket_to_collect_eggs( - env.program_info(), console, context, - 1, eggs_collected - ); -#endif - - -#if 0 - auto image = feed.snapshot(); - DialogBoxDetector detector; - cout << detector.detect(image) << endl; -#endif - -#if 0 - BattleMenuDetector detector(COLOR_RED); - while (true){ - scope.wait_for(std::chrono::milliseconds(50)); - auto image = feed.snapshot(); - cout << detector.detect(image) << endl; - } -#endif - - -#if 0 - auto image = feed.snapshot(); - TeraCatchWatcher detector(COLOR_RED); - bool ok = detector.detect(image); - cout << ok << endl; - if (!ok){ - image.frame->save("tmp.png"); - } - -#if 0 - int ret = wait_until( - console, context, std::chrono::seconds(60), - {detector} - ); - cout << "ret = " << ret << endl; -#endif -#endif - - -#if 0 - auto image = feed.snapshot(); - - BoxDetector detector; - cout << detector.detect(image) << endl; - - while (true){ - scope.wait_for(std::chrono::milliseconds(50)); - image = feed.snapshot(); - std::pair location = detector.detect_location(image); - cout << (int)location.first << ": " << (int)location.second.row << "," << (int)location.second.col << endl; - } -#endif - - -#if 0 - GradientArrowDetector party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); - auto image = feed.snapshot(); - cout << party_select_top.detect(image) << endl; -#endif - -#if 0 - auto image = feed.snapshot(); - SomethingInBoxSlotDetector detector(COLOR_RED, true); - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; -#endif - -#if 0 - AsyncCommandSession session(scope, logger, env.realtime_dispatcher(), context.botbase()); - session.dispatch([](ProControllerContext& context){ -// pbf_controller_state(context, 0, DPAD_NONE, 128, 0, 128, 128, 255); - pbf_press_button(context, BUTTON_A, 255, 0); - }); - context.wait_for(std::chrono::seconds(2)); - session.dispatch([](ProControllerContext& context){ -// pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 255); - pbf_press_button(context, BUTTON_B, 255, 0); - }); - -#else -#if 0 - pbf_controller_state(context, 0, DPAD_NONE, 128, 0, 128, 128, 500); - context.wait_for_all_requests(); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 500); -#endif -#endif - -// pbf_press_button(context, BUTTON_B, 500, 10); -// pbf_controller_state(context, 0, DPAD_NONE, 128, 0, 128, 128, 500); -// context.wait_for_all_requests(); -// pbf_wait(context, 1); -// pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 500); - - - -#if 0 - KeyboardEntryPosition point0{1, 0}; - KeyboardEntryPosition point1{1, 10}; -// uint16_t scroll_delay = 3; -// uint16_t A_delay = 3; - - auto path0 = get_codeboard_digit_path(point0, point1); - auto path1 = get_codeboard_digit_path(point1, point0); - - while (true){ - move_codeboard(context, path0, true); - move_codeboard(context, path1, true); - } -#endif -#if 0 - while (true){ - ssf_issue_scroll(context, DPAD_LEFT, 10, 6); - ssf_issue_scroll(context, DPAD_LEFT, 4, 6); - ssf_issue_scroll(context, DPAD_LEFT, 4, 6); - ssf_issue_scroll(context, DPAD_LEFT, 10, 6); - ssf_issue_scroll(context, DPAD_RIGHT, 10, 6); - ssf_issue_scroll(context, DPAD_RIGHT, 4, 6); - ssf_issue_scroll(context, DPAD_RIGHT, 4, 6); - ssf_issue_scroll(context, DPAD_RIGHT, 10, 6); - } -#endif - -#if 0 - ImageRGB32 image("20221206-225502975702-NoState.png"); - -// OverlayBoxScope ore_box(console, {0.930, 0.050, 0.065, 0.010}); -// extract_box_reference(image, ore_box).save("test.png"); - - AdvanceDialogDetector detector; - cout << detector.detect(image) << endl; -#endif - -#if 0 - while (true){ - pbf_press_button(context, BUTTON_HOME, 20, GameSettings::instance().GAME_TO_HOME_DELAY); - set_time_to_12am_from_home(console, context); - reset_game_from_home(env, console, context, 5 * TICKS_PER_SECOND); - } -#endif - - -#if 0 - ImageRGB32 image("screenshot-20221204-232949766645.png"); - - MainMenuDetector detector; - auto detection = detector.detect_location(image); - cout << (int)detection.first << " : " << detection.second << endl; - -// GradientArrowDetector party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); -// bool detected = party_select_top.detect(image); -// cout << detected << endl; -#endif - - - - - -#if 0 -// GradientArrowDetector party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); - MainMenuDetector detector; - while (true){ - VideoSnapshot snapshot = feed.snapshot(); - auto detection = detector.detect_location(snapshot); -// bool detected = party_select_top.detect(snapshot); - cout << (int)detection.first << " : " << detection.second << endl; -// if (!detected){ -// snapshot.frame->save("test.png"); -// } - scope.wait_for(std::chrono::milliseconds(100)); - } -#endif - -#if 0 - send_program_notification( - env.logger(), NOTIFICATION_TEST, - COLOR_GREEN, env.program_info(), - "Test Title", - { - { - "", - "[TestTest](https://discordtips.com/how-to-hyperlink-in-discord/)" - }, - } - ); -#endif - - -// pbf_move_left_joystick(context, 129, 128, 10000, 0); -// pbf_move_left_joystick(context, 128, 0, 90, 0); - - -// ImageRGB32 image("screenshot-20221128-084818449677.png"); -// PromptDialogDetector detector(COLOR_RED); -// cout << detector.detect(image) << endl; - - -// ssf_press_button(context, BUTTON_A, 8, 20); -// pbf_press_button(context, BUTTON_B, 20, 105); - - - - -#if 0 - ImageRGB32 image("20221206-035546876682.jpg"); -// auto image = feed.snapshot(); - - TeraLobbyReader reader; - reader.make_overlays(overlays); -#if 0 - reader.check_ban_list( - { - {Language::English, "Halazea"}, - }, - image, - true - ); -#endif - reader.raid_code(logger, env.program_info(), image); -// cout << (int)reader.total_players(image) << endl; -#endif - - - -// connect_to_internet_from_overworld(console, context); -// day_skip_from_overworld(console, context); - - - -// save_game_from_overworld(console, context); - - -#if 0 - OverworldDetector overworld; - overworld.make_overlays(overlays); - - auto image = feed.snapshot(); -// overworld.detect(image); - cout << overworld.detect_ball(image) << endl; -#endif - -// wait_until(); - -// ImageRGB32 image("ball-1-new.png"); - -// filter_rgb32_range(image, 0xffc0c000, 0xffffff3f, Color(0), false).save("ball-template.png"); - - -// ImageFloatBox ball(0.890, 0.790, 0.030, 0.070); -// ImageFloatBox radar(0.815, 0.680, 0.180, 0.310); - - - -// save_game_from_menu(console, context); - -// enter_alphanumeric_code(logger, context, "2VL4EP"); - -// run_path(context, get_path({0, 0}, {2, 6})); -// run_path(context, get_path({2, 6}, {0, 9})); -// run_path(context, get_path({0, 9}, {3, 8})); - - - -#if 0 - auto image = feed.snapshot(); - - DateReader reader; - reader.make_overlays(overlays); - cout << reader.detect(image) << endl; - cout << (int)reader.read_hours(logger, image) << endl; - reader.set_hours(console, context, 1); -#endif - - -// auto image = feed.snapshot(); -// DateReader reader; -// reader.detect(image); - - - -// TradeStats stats; -// trade_current_box(env, scope, NOTIFICATION_TEST, stats); - - -// BoxDetector detector; -// detector.move_cursor(console, context, BoxCursorLocation::SLOTS, 3, 3); - -// MainMenuDetector detector; -// detector.move_cursor(console, context, MenuSide::RIGHT, 4); - -#if 0 - auto image = feed.snapshot(); - BoxDetector detector; - auto ret = detector.detect_location(image); - cout << (int)ret.first << " | " << (int)ret.second.row << ", " << (int)ret.second.col << endl; -#endif - -#if 0 - MultiConsoleErrorState state; - TradeStats stats; - env.run_in_parallel( - scope, - [&](ConsoleHandle& console, ProControllerContext& context){ - trade_current_pokemon(console, context, state, stats); - } - ); -#endif - - -#if 0 - auto image = feed.snapshot(); - TeraLobbyReader detector(COLOR_RED); - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; - cout << detector.total_players(image) << endl; -#endif - - -#if 0 -// ImageRGB32 image("NoCardDetection.png"); - auto image = feed.snapshot(); - TeraCardReader detector(COLOR_RED); - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; - cout << detector.stars(image) << endl; -#endif - - -#if 0 - ImageRGB32 image("ArrowFail.png"); -// auto image = feed.snapshot(); - - AdvanceDialogDetector detector; - cout << detector.detect(image) << endl; -// image.frame->save("test.png"); -#endif - - -#if 0 - BattleBallReader reader(console, LANGUAGE); - - pbf_press_button(context, BUTTON_A, 20, 105); - context.wait_for_all_requests(); - - int quantity = move_to_ball(reader, console, context, "poke-ball"); - cout << "quantity = " << quantity << endl; -#endif - - -#if 0 - BattleBallReader reader(console, Language::English); - auto image = feed.snapshot(); - cout << reader.read_quantity(image) << endl; - cout << reader.read_ball(image) << endl; -#endif - -#if 0 -// ImageRGB32 image("screenshot-20221120-001408323077.png"); - ImageRGB32 image("screenshot-20221118-160757832016.png"); - PokemonSummaryDetector detector; - cout << detector.detect(image) << endl; -#endif - -// auto image = feed.snapshot(); -// PokemonSummaryDetector detector; -// cout << detector.detect(image) << endl; - - -#if 0 - auto image = feed.snapshot(); - ImageStats stats = image_stats(extract_box_reference(image, ImageFloatBox{0.30, 0.33, 0.40, 0.02})); - cout << stats.average << stats.stddev << endl; -#endif - -#if 0 - ImageRGB32 image("cursor_basic_00q.png"); - GradientArrowDetector detector({0, 0, 1, 1}); - - auto hits = detector.detect_all(image); - cout << "hits = " << hits.size() << endl; - for (auto& item : hits){ - extract_box_reference(image, item).save("test.png"); - } -#endif - - -#if 0 - ImageRGB32 image("screenshot-20221121-070043212515.png"); - - WhiteButtonDetector next_button(WhiteButton::ButtonA, {0.8, 0.9, 0.2, 0.1}, COLOR_RED); - cout << next_button.detect(image) << endl; -#endif - -#if 0 - ImageRGB32 image("screenshot-20221118-211428612196.png"); - - TeraCardReader detector; - cout << detector.detect(image) << endl; -#endif - -#if 0 - ImageRGB32 image("screenshot-20221122-022035906115.png"); - - MoveSelectDetector detector; - cout << detector.detect(image) << endl; -#endif - - -#if 0 - AddToPartyDetector detector; - cout << detector.detect(feed.snapshot()) << endl; -#endif - - - -// home_to_date_time(context, false, false); - -// save_game_from_overworld(console, context); - - -#if 0 - auto image = feed.snapshot(); - - PokemonSummaryDetector detector; - cout << detector.detect(image) << endl; - cout << detector.is_shiny(image) << endl; -#endif - -#if 0 - RaidShinyStarDetector detector(overlay); - wait_until( - console, context, - WallClock::max(), - {detector} - ); -#endif - - - -#if 0 - ImageRGB32 image("ShinyRaid.png"); - - ImageViewRGB32 cropped = extract_box_reference(image, ImageFloatBox{0.5, 0.1, 0.4, 0.7}); - cropped.save("test-cropped.png"); - - - ImageRGB32 filtered = filter_rgb32_range(cropped, 0xff804040, 0xffffffff, Color(0xffffff00), true); - filtered.save("test-filtered.png"); -#endif - -#if 0 - uint8_t year = MAX_YEAR; - while (true){ - pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY); - home_roll_date_enter_game_autorollback(console, context, year); - pbf_mash_button(context, BUTTON_A, 250); - } -#endif - -#if 0 - ImageRGB32 image("GradientArrowHorizontal-Template.png"); - - ImageRGB32 rotated(image.height(), image.width()); - - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - rotated.pixel(r, c) = image.pixel(c, r); - } - } - rotated.save("GradientArrowVertical-Template.png"); -#endif - - -#if 0 - auto image = feed.snapshot(); - ImageViewRGB32 cropped = extract_box_reference(image, ImageFloatBox{0.500, 0.555, 0.310, 0.070}); - PackedBinaryMatrix matrix = compress_rgb32_to_binary_euclidean(cropped, 0xff757f9c, 100); -// cout << matrix.dump() << endl; - - matrix.invert(); - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - while (iter->find_next(object, false)){ -// extract_box_reference(image, object).save("Arrow-Template.png"); - cout << object.area << endl; - } -#endif - - -#if 0 - auto image = feed.snapshot(); - - ImageViewRGB32 cropped = extract_box_reference(image, ImageFloatBox{0.500, 0.555, 0.310, 0.070}); -// ImageRGB32 filtered = filter_rgb32_range(cropped, 0xffc00000, 0xffffffff, Color(0x00000000), true); - size_t pixels; - ImageRGB32 filtered = filter_rgb32_euclidean(pixels, cropped, 0xff757f9c, 100, Color(0x00000000), true); - cout << "pixels = " << pixels << endl; - filtered.save("test.png"); -#endif - - -#if 0 - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808000, 0xffffff80); - - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - while (iter->find_next(object, false)){ - extract_box_reference(image, object).save("Arrow-Template.png"); - } -#endif - -#if 0 - ImageRGB32 image("WhiteButtonA.png"); - ImageRGB32 filtered = filter_rgb32_range(image, 0xff000000, 0xff7f7f7f, Color(0x00000000), true); - - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - if (8 < c && c < 30 && 8 < r && r < 30){ - filtered.pixel(c, r) = image.pixel(c, r); - } - } - } - filtered.save("WhiteButtonA-processed.png"); -#endif - -#if 0 - WhiteButtonFinder next_button(WhiteButton::ButtonA, console.overlay(), {0.9, 0.9, 0.1, 0.1}); - wait_until( - console, context, - std::chrono::seconds(60), - {next_button} - ); -#endif - - -#if 0 - TeraCardReader reader; -// auto image = ImageRGB32("ErrorDumps/20221115-234552197119-ReadStarsFailed.png"); - auto image = feed.snapshot(); - cout << reader.detect(image) << endl; - cout << "stars = " << reader.stars(image) << endl; - -// BattleMenuDetector battle_menu; -// cout << battle_menu.detect(image) << endl; -#endif - -// OverlayBoxScope box(overlay, COLOR_RED, {0.4, 0.4, 0.2, 0.2}, "asdf qwer sdfg"); - - -// reset_game_to_gamemenu(console, context); - - -#if 0 - ImageRGB32 image("Arrow.png"); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff); - - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (iter->find_next(object, false)){ - extract_box_reference(image, object).save("Arrow-Template.png"); - } -#endif - - -// YCommMenuDetector detector(true); -// HomeMenuDetector detector; -// cout << detector.detect(image) << endl; -// cout << detector.detect(feed.snapshot()) << endl; - - - -#if 0 - while (true){ - pbf_press_button(context, BUTTON_HOME, 20, GameSettings::instance().GAME_TO_HOME_DELAY); - reset_game_from_home(env, console, context); - } -#endif - - - -#if 0 - overlay.add_log("asdfasdf", COLOR_RED); - - for (int c = 0; c < 20; c++){ - overlay.add_log("qwerqwer", COLOR_GREEN); - scope.wait_for(std::chrono::milliseconds(1000)); - } - - scope.wait_for(std::chrono::milliseconds(5000)); - cout << "clear" << endl; - overlay.clear_log(); -#endif - -#if 0 - OverlayTextScope text(overlay, "hello world", 0.5, 0.5, 10, COLOR_WHITE); - - overlay.add_log_text("asdfasdf", COLOR_RED); - - OverlayStat stat0; - OverlayStat stat1; - OverlayStat stat2; - overlay.add_stat(stat0); - overlay.add_stat(stat1); - overlay.add_stat(stat2); - - for (size_t c = 0;; c++){ - stat2.set_text(std::to_string(c)); - scope.wait_for(std::chrono::milliseconds(100)); - } -#endif - - -#if 0 - ImageFloatBox box(0.21, 0.80, 0.53, 0.17); - - VideoSnapshot frame = feed.snapshot(); - ImageViewRGB32 image = extract_box_reference(frame, box); - - ImageRGB32 filtered = to_blackwhite_rgb32_range(image, 0xff007f7f, 0xffc0ffff, false); - filtered.save("test.png"); - - PokeballNameReader::instance().read_substring( - logger, Language::English, - image, - {{0xff007f7f, 0xff80ffff}}, 0 - ); -#endif - - -#if 0 - ImageRGB32 image("screenshot-20221107-210754107968.png"); -// auto image = feed.snapshot(); - HomeMenuDetector detector; -// UpdatePopupDetector detector; - VideoOverlaySet overlays(overlay); - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; -#endif - -// ImageRGB32 image("ExclamationFalsePositive.png"); -// find_exclamation_marks(image); - -// HomeMenuDetector detector; -// cout << detector.detect(image) << endl; - - -#if 0 - InferenceBoxScope left_mon_white(console, {0.708, 0.070, 0.005, 0.028}); - InferenceBoxScope left_mon_hp(console, {0.500, 0.120, 0.18, 0.005}); - InferenceBoxScope left_name(console, {0.467, 0.06, 0.16, 0.050}); - InferenceBoxScope right_name(console, {0.740, 0.06, 0.16, 0.050}); -#endif - -// ImageRGB32 image("Paralyzed.png"); - -#if 0 - BattleMenuDetector detector(BattleType::STANDARD); - VideoOverlaySet overlays(overlay); - detector.make_overlays(overlays); - cout << detector.detect(image) << endl; -#endif - -#if 0 - BattleMenuWatcher watcher(BattleType::STANDARD); - BotBaseContext context(scope, console.botbase()); - wait_until( - console, context, std::chrono::seconds(60), - { - {watcher} - } - ); -#endif - - -#if 0 -// ImageRGB32 image("SV-BattleMenu.png"); -// ImageRGB32 image("SV-Hair.png"); -// image = image.scale_to(1920, 1080); - - -// extract_box_reference(image, ImageFloatBox({0.7, 0.6, 0.2, 0.1})).save("tmp.png"); - -// ImageFloatBox box(0.5, 0.5, 0.4, 0.5); - ImageFloatBox box(0.0, 0.0, 1.0, 1.0); - - - VideoOverlaySet set(overlay); - WhiteButtonFinder white_button_detector0(WhiteButton::ButtonA, overlay, box); - WhiteButtonFinder white_button_detector1(WhiteButton::ButtonB, overlay, box); - WhiteButtonFinder white_button_detector2(WhiteButton::ButtonY, overlay, box); - WhiteButtonFinder white_button_detector3(WhiteButton::ButtonMinus, overlay, box); - DialogArrowFinder dialog_arrow_detector(overlay, box); - GradientArrowFinder gradient_arrow_detector(overlay, box); - dialog_arrow_detector.make_overlays(set); - gradient_arrow_detector.make_overlays(set); - BattleMenuFinder battle_menu; - battle_menu.make_overlays(set); - - while (true){ - scope.wait_for(std::chrono::milliseconds(50)); - VideoSnapshot snapshot = feed.snapshot(); - - white_button_detector0.process_frame(snapshot, current_time()); - white_button_detector1.process_frame(snapshot, current_time()); - white_button_detector2.process_frame(snapshot, current_time()); - white_button_detector3.process_frame(snapshot, current_time()); - dialog_arrow_detector.process_frame(snapshot, current_time()); - gradient_arrow_detector.process_frame(snapshot, current_time()); - battle_menu.process_frame(snapshot, current_time()); - } -#endif - -#if 0 - BotBaseContext context(scope, console.botbase()); - wait_until( - console, context, std::chrono::seconds(60), - { - {detector} - }, - std::chrono::seconds(50) - ); -#endif - - - - - - - scope.wait_for(std::chrono::seconds(60)); - - -} - - - - -#if 0 -struct RaidShinyStar{ - double alpha; - WaterfillObject object; -}; - - -class RaidShinyStarDetector : public VisualInferenceCallback{ - static constexpr double ALPHA_THRESHOLD = 1.0; - -public: - RaidShinyStarDetector(VideoOverlay& overlay) - : VisualInferenceCallback("RaidShinyStarDetector") - , m_overlay(overlay) - , m_box(overlay, {0.5, 0.1, 0.4, 0.7}) - {} - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - std::vector process_frame(const ImageViewRGB32& frame); - -private: - double test_object(const ImageViewRGB32& image, const WaterfillObject& object); - - -private: - VideoOverlay& m_overlay; - OverlayBoxScope m_box; - std::deque m_stars; -}; - - -void RaidShinyStarDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool RaidShinyStarDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - process_frame(frame); - return false; -} - -double RaidShinyStarDetector::test_object(const ImageViewRGB32& image, const WaterfillObject& object){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 0.9 || aspect_ratio > 1.1){ - return 0; - } - - double area_ratio = object.area_ratio(); - if (area_ratio < 0.5 || area_ratio > 0.8){ - return 0; - } - - // Check that center of gravity is centered. - double center_of_gravity_x = object.center_of_gravity_x(); - double center_of_gravity_y = object.center_of_gravity_y(); - double center_x = object.min_x + object.width() * 0.5; - double center_y = object.min_y + object.height() * 0.5; - - double center_shift_x = center_x - center_of_gravity_x; - double center_shift_y = center_y - center_of_gravity_y; - center_shift_x *= center_shift_x; - center_shift_y *= center_shift_y; - - double max_x_sqr = object.width() * 0.1; - double max_y_sqr = object.height() * 0.1; - max_x_sqr *= max_x_sqr; - max_y_sqr *= max_y_sqr; - - if (center_shift_x > max_x_sqr){ - return 0; - } - if (center_shift_y > max_y_sqr){ - return 0; - } - - return 1.0; -} - - -std::vector RaidShinyStarDetector::process_frame(const ImageViewRGB32& frame){ - - ImageViewRGB32 cropped = extract_box_reference(frame, m_box); - - std::vector matrices = compress_rgb32_to_binary_range(cropped, { - {0xff808080, 0xffffffff}, - {0xff909090, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - {0xffb0b0b0, 0xffffffff}, - {0xffc0c0c0, 0xffffffff}, - {0xffd0d0d0, 0xffffffff}, - {0xffe0e0e0, 0xffffffff}, - - {0xff804040, 0xffffffff}, - {0xff905050, 0xffffffff}, - {0xffa06060, 0xffffffff}, - - {0xff408040, 0xffffffff}, - {0xff509050, 0xffffffff}, - {0xff60a060, 0xffffffff}, - - {0xff404080, 0xffffffff}, - {0xff505090, 0xffffffff}, - {0xff6060a0, 0xffffffff}, - }); - -// std::vector - std::vector stars; - - std::unique_ptr session = make_WaterfillSession(); - WaterfillObject object; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - auto iter = session->make_iterator(10); - while (iter->find_next(object, false)){ - double alpha = test_object(cropped, object); - if (alpha >= ALPHA_THRESHOLD){ - stars.emplace_back(RaidShinyStar{alpha, object}); - } - } - } - - - - - - - // Redraw the boxes. - m_stars.clear(); - for (const RaidShinyStar& star : stars){ - m_stars.emplace_back(m_overlay, translate_to_parent(frame, m_box, star.object), COLOR_BLUE); - } - return stars; -} - -#endif - - - - -} -} - - - - +/* Test Program (Switch) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "TestProgramSwitch.h" + +//#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "Common/Cpp/Concurrency/PeriodicScheduler.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h" +#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" +#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" +#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "PokemonSV/Inference/PokemonSV_PokePortalDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h" +#include "PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" +#include "PokemonSV/Programs/PokemonSV_AreaZero.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h" +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameSave.h" +#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" +#include "PokemonSV/Inference/PokemonSV_BagDetector.h" +#include +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" +#include "PokemonSV/Inference/PokemonSV_StatHexagonReader.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +//#include "CommonFramework/Environment/SystemSleep.h" +#include "CommonFramework/ErrorReports/ErrorReports.h" +#include "PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h" +#include "PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h" +#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" +//#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h" +#include "PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" +#include "CommonTools/Images/ImageFilter.h" +#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" + +#include +#include + +//#include +#include +using std::cout; +using std::endl; + + +using namespace PokemonAutomation::Kernels; +using namespace PokemonAutomation::Kernels::Waterfill; + + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + + + +TestProgram_Descriptor::TestProgram_Descriptor() + : MultiSwitchProgramDescriptor( + "NintendoSwitch:TestProgram", + "Nintendo Switch", "Test Program (Switch)", + "", + "Test Program (Switch)", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::ENABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + 1, 4, 1 + ) +{} + + +TestProgram::~TestProgram(){ + BUTTON1.remove_listener(*this); + BUTTON0.remove_listener(*this); +} +TestProgram::TestProgram() + : BUTTON0( + "Button Text 0", 0, 16 + ) + , BUTTON1( + "Button Label:
asdfasdfasdf", + "Button Text 1", 0, 16 + ) + , LANGUAGE( + "OCR Language:", + PokemonSwSh::IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + false + ) + , IMAGE_PATH(false, "Path to image for testing", LockMode::UNLOCK_WHILE_RUNNING, "default.png", "default.png") + , STATIC_TEXT("Test text...") +// , PLAYER_LIST("Test Table", LockMode::UNLOCK_WHILE_RUNNING, "Notes") + , DATE0( + "Date", + LockMode::UNLOCK_WHILE_RUNNING, + DateTimeOption::DATE_HOUR_MIN, + DateTime{2000, 1, 1, 0, 0, 0}, + DateTime{2060, 12, 31, 23, 59, 59}, + DateTime{2024, 4, 12, 2, 16, 30} + ) + , DATE1( + "Date", + LockMode::UNLOCK_WHILE_RUNNING, + DateTimeOption::DATE_HOUR_MIN, + DateTime{2000, 1, 1, 0, 0, 0}, + DateTime{2060, 12, 31, 23, 59, 59}, + DateTime{2048, 1, 13, 20, 48} + ) + , DURATION( + "Duration", + LockMode::UNLOCK_WHILE_RUNNING, + "100" + ) + , COLOR( + LockMode::UNLOCK_WHILE_RUNNING, + false, + 0x000000, 0x000000 + ) + , NOTIFICATION_TEST("Test", true, true, ImageAttachmentMode::JPG) + , NOTIFICATIONS({ + &NOTIFICATION_TEST, +// &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(BUTTON0); + PA_ADD_OPTION(BUTTON1); + PA_ADD_OPTION(LANGUAGE); +// PA_ADD_OPTION(CONSOLE_MODEL); + PA_ADD_OPTION(IMAGE_PATH); + PA_ADD_OPTION(STATIC_TEXT); +// PA_ADD_OPTION(PLAYER_LIST); +// PA_ADD_OPTION(battle_AI); + PA_ADD_OPTION(DATE0); + PA_ADD_OPTION(DATE1); + PA_ADD_OPTION(DURATION); + PA_ADD_OPTION(COLOR); + PA_ADD_OPTION(CONTROLLER_TABLE); + PA_ADD_OPTION(NOTIFICATIONS); + BUTTON0.add_listener(*this); + BUTTON1.add_listener(*this); +} + + +//using namespace Kernels; +using namespace Kernels::Waterfill; + +using namespace PokemonSV; + + +void TestProgram::on_press(){ + global_logger_tagged().log("Button Pressed"); +// BUTTON.set_enabled(false); + BUTTON0.set_text("Button Pressed"); + BUTTON1.set_text("Button Pressed"); +} + + + + + + + + + + +void TestProgram::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + using namespace Kernels; + using namespace Kernels::Waterfill; + using namespace OCR; + using namespace NintendoSwitch; + using namespace Pokemon; + using namespace PokemonSwSh; +// using namespace PokemonBDSP; + using namespace PokemonLA; +// using namespace PokemonSV; + + [[maybe_unused]] Logger& logger = env.logger(); + [[maybe_unused]] ConsoleHandle& console = env.consoles[0]; +// [[maybe_unused]] BotBase& botbase = env.consoles[0]; + [[maybe_unused]] VideoFeed& feed = env.consoles[0]; + [[maybe_unused]] VideoOverlay& overlay = env.consoles[0]; + ProControllerContext context(scope, console.pro_controller()); + VideoOverlaySet overlays(overlay); + + + + +#if 1 + HomeMenuDetector detector0(console); + StartGameUserSelectDetector detector1(console); + UpdatePopupDetector detector2(console); + detector0.make_overlays(overlays); + detector1.make_overlays(overlays); + detector2.make_overlays(overlays); + cout << detector0.detect(feed.snapshot()) << endl; + cout << detector1.detect(feed.snapshot()) << endl; + cout << detector2.detect(feed.snapshot()) << endl; +#endif + + + +// ImageRGB32 image0("menu-light.png"); +// ImageRGB32 image1("menu-dark.png"); +// ImageRGB32 image2("menu-jpn.png"); + +#if 0 + env.log("Touching date to prevent rollover."); + pbf_press_button(context, BUTTON_HOME, 160ms, PokemonSwSh::GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); +#endif + + + +#if 0 + auto screenshot = feed.snapshot(); + + + BinarySliderDetector detector(COLOR_RED, {0.831784, 0.140496, 0.088290, 0.671074}); + auto sliders = detector.detect(screenshot); + + for (auto& item : sliders){ + cout << item.first << " : " << item.second.min_y << endl; + } +#endif + +#if 0 + ImageFloatBox box(0.842007, 0.626446, 0.050186, 0.049587); + ImageViewRGB32 cropped = extract_box_reference(screenshot, box); + + cropped.save("temp.png"); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + cropped, 0xffc0c0c0, 0xffffffff + ); + + cout << matrix.dump() << endl; + + std::vector objects = find_objects_inplace(matrix, 200); + cout << "objects.size() = " << objects.size() << endl; + for (auto& item : objects){ + extract_box_reference(cropped, item).save("test.png"); + } +#endif + + + +// FastCodeEntry::numberpad_enter_code(console, context, "708538991006", true); + + + +#if 0 +// ssf_issue_scroll(context, DPAD_LEFT, 48ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 96ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_L, 0ms, 48ms, 24ms); + ssf_issue_scroll(context, DPAD_LEFT, 48ms, 48ms, 24ms); +#endif + +#if 0 + DateReader reader; + reader.make_overlays(overlays); + auto date = reader.read_date(logger, feed.snapshot()); + + cout << "date format = " << (int)date.first << endl; +// cout << "date = " << (int)date.second << endl; +#endif + + + +#if 0 +// DateReader_Switch2_US reader(COLOR_RED); + DateReader_Switch2_JP reader(COLOR_RED); + reader.make_overlays(overlays); + DateTime date = reader.read_date(logger, feed.snapshot()); + + cout << "Month = " << (int)date.month << endl; + cout << "Day = " << (int)date.day << endl; + cout << "Year = " << (int)date.year << endl; + cout << "Hour = " << (int)date.hour << endl; + cout << "Minute = " << (int)date.minute << endl; +#endif + + +#if 0 + DateChangeDetector_Switch2 detector(COLOR_RED); + detector.make_overlays(overlays); + cout << detector.detect(feed.snapshot()) << endl; +#endif + + +#if 0 + DateReader reader(console); + reader.make_overlays(overlays); + DateTime date = reader.read_date(logger, feed.snapshot()).second; + + cout << "Month = " << (int)date.month << endl; + cout << "Day = " << (int)date.day << endl; + cout << "Year = " << (int)date.year << endl; + cout << "Hour = " << (int)date.hour << endl; + cout << "Minute = " << (int)date.minute << endl; + + while (true){ + reader.set_date(env.program_info(), console, context, DATE0); + for (int c = 0; c < 7; c++){ + ssf_issue_scroll_ptv(context, DPAD_LEFT); + } + reader.set_date(env.program_info(), console, context, DATE1); + for (int c = 0; c < 7; c++){ + ssf_issue_scroll_ptv(context, DPAD_LEFT); + } + } +#endif + + + +// rollback_hours_from_home(console, context, 3, 500ms); + + + +#if 0 + while (true){ + roll_date_backward_N_Switch2_wired(context, 60); + for (size_t c = 0; c < 60; c++){ + roll_date_forward_1(console, context, true); + } + } +#endif + + + +#if 0 + while (true){ + home_to_date_time(console, context, true); +// home_to_date_time_Switch2_wired_blind(context, true); + ssf_do_nothing(context, 1000ms); + pbf_press_button(context, BUTTON_HOME, 200ms, 1800ms); + } +#endif + + + + +#if 0 + ConsoleTypeDetector_Home detector(console); + detector.make_overlays(overlays); + + cout << (int)detector.detect(feed.snapshot()) << endl; +#endif + + + +#if 0 + UpdatePopupDetector detector; + detector.make_overlays(overlays); + + cout << detector.detect(feed.snapshot()) << endl; +#endif + + + + + +#if 0 + home_to_date_time(console, context, false); +#endif + +#if 0 +// std::terminate(); + ImageRGB32 image("20250503-121259857603.png"); + + image = filter_rgb32_brightness(image, COLOR_RED, false, 0x00ffff01, 0, 200); + image.save("temp.png"); +#endif + + +#if 0 + ImageRGB32 image("20250503-121259857603.png"); + + { + TeraTypeReader reader; + ImageMatch::ImageMatchResult results = reader.read(image); + results.log(logger, 120); + } + { + TeraSilhouetteReader reader; + ImageMatch::ImageMatchResult results = reader.read(image); + results.log(logger, 120); + } +#endif + +#if 0 + Milliseconds unit = 24ms; + + ssf_issue_scroll(context, DPAD_DOWN, 2*unit, 2*unit, unit); + ssf_issue_scroll(context, DPAD_LEFT, unit, 2*unit, unit); + ssf_issue_scroll(context, DPAD_LEFT, unit, 2*unit, unit); + ssf_issue_scroll(context, DPAD_LEFT, unit, 2*unit, unit); + + +#endif + + + +#if 0 + ssf_press_button(context, Button::BUTTON_ZR, 1s, 60h, 0ms); +// context->issue_gyro_rotate_x(&scope, 0s, 60h, 0ms, 0x1000); +// context->issue_gyro_rotate_y(&scope, 0s, 60h, 0ms, 0x0000); +// context->issue_gyro_rotate_z(&scope, 0s, 60h, 0ms, 0x1000); + +// auto duration = 10s; + +// context->issue_gyro_rotate_x(&scope, duration, duration, 0s, 0x1000); +// context->issue_nop(&scope, 60h); + +#if 1 + auto duration = 15ms; + for (size_t c = 0; c < 65536; c += 1){ + context->issue_gyro_accel_x(&scope, 0s, duration, 0s, (uint16_t)(688 + 0*c % 2)); + context->issue_gyro_accel_y(&scope, 0s, duration, 0s, (uint16_t)(1*c % 2)); + context->issue_gyro_accel_z(&scope, 0s, duration, 0s, (uint16_t)(-4038 + 0*c % 2)); + context->issue_gyro_rotate_x(&scope, 0s, duration, 0s, (uint16_t)(0x0000 + 1*c)); + context->issue_gyro_rotate_y(&scope, 0s, duration, 0s, (uint16_t)(0x0000 + 1*c)); + context->issue_gyro_rotate_z(&scope, 0s, duration, 0s, (uint16_t)(0x0000 + 0*c)); + context->issue_nop(&scope, duration); + } +#endif +#endif + + +#if 0 + ImageRGB32 image("20250420-043111395281.png"); + + OcrFailureWatchdog watchdog(logger); + + PokemonSwSh::MaxLairInternal::PokemonSwapMenuReader reader(logger, overlay, Language::Korean, watchdog); + + double hp[4]; + reader.read_hp(image, hp); +#endif + +#if 0 + ImageRGB32 image("20250404-154507236508.png"); + + ArcPhoneDetector phone(logger, overlay, std::chrono::milliseconds(250), true); + + while (true){ + cout << phone.process_frame(image, current_time()) << endl; + scope.wait_for(100ms); + } + +#if 0 + wait_until( + console, context, + 10000ms, + {phone} + ); +#endif +#endif + +#if 0 + // ImageRGB32 image(IMAGE_PATH); + auto image = feed.snapshot(); +#if 1 + ImageRGB32 image(IMAGE_PATH); + // auto image = feed.snapshot(); + + SandwichHandLocator hand(SandwichHandType::FREE, {0, 0, 1, 1}); + std::pair location = hand.locate_sandwich_hand(image, {0,0,1,1}); + cout << location.first << ", " << location.second << endl; +#endif + +#if 0 + ImageRGB32 image(IMAGE_PATH); + // auto image = feed.snapshot(); + + ItemPrinterMaterialDetector detector(COLOR_RED, Language::English); + + std::vector boxes = { + // {0.485,0.176758,0.037,0.05}, {0.485,0.250977,0.037,0.05}, {0.485,0.325196,0.037,0.05}, {0.485,0.399415,0.037,0.05}, {0.485,0.473634,0.037,0.05}, {0.485,0.547853,0.037,0.05}, {0.485,0.622072,0.037,0.05}, {0.485,0.696291,0.037,0.05}, {0.485,0.77051,0.037,0.05}, {0.485,0.844729,0.037,0.05}, + {0.39,0.176758,0.025,0.05}, {0.39,0.250977,0.025,0.05}, {0.39,0.325196,0.025,0.05}, {0.39,0.399415,0.025,0.05}, {0.39,0.473634,0.025,0.05}, {0.39,0.547853,0.025,0.05}, {0.39,0.622072,0.025,0.05}, {0.39,0.696291,0.025,0.05}, {0.39,0.77051,0.025,0.05}, {0.39,0.844729,0.025,0.05}, + }; + for (ImageFloatBox box : boxes){ + detector.read_number(console.logger(), env.inference_dispatcher(), image, box); + } + +#endif +#endif + +#if 0 + + ImageRGB32 image("20250323-011605651979.png"); + + DialogBoxDetector detector; + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; + +#endif + + +#if 0 + auto image = feed.snapshot(); + + ItemPrinterMenuDetector detector(COLOR_GREEN); + cout << detector.detect(image) << endl; +#endif + + +// numberpad_enter_code(logger, context, "708538991006", false); + + + +#if 0 + for (size_t i = 0; i < 100; i++){ + for (size_t c = 0; c < 4; c++){ + ssf_issue_scroll(context, DPAD_RIGHT, 17ms); + } + for (size_t c = 0; c < 4; c++){ + ssf_issue_scroll(context, DPAD_LEFT, 17ms); + } + } +#endif + + + +#if 0 + while (true){ + for (size_t c = 0; c < 60; c++){ + ssf_issue_scroll(context, DPAD_DOWN, 24ms); + } + ssf_do_nothing(context, 1000ms); + for (size_t c = 0; c < 60; c++){ + ssf_issue_scroll(context, DPAD_UP, 24ms); + } + ssf_do_nothing(context, 1000ms); + } +#endif + +// pbf_move_left_joystick(context, 38, 38, 10000, 0); + + +// ssf_issue_scroll(context, DPAD_LEFT, 0); +// ssf_press_button(context, BUTTON_A | BUTTON_L, 3); +// ssf_press_button(context, BUTTON_L, 0); + +#if 0 + numberpad_enter_code( + logger, context, + "708538991006", + false + ); +#endif + +#if 0 + codeboard_enter_digits( + logger, context, KeyboardLayout::QWERTY, + "JRH5T9", + true, + CodeboardDelays{ + .hold = 5 * 8ms, + .cool = 3 * 8ms, + .press_delay = 4 * 8ms * 1, + .move_delay = 5 * 8ms * 1, + .wrap_delay = 6 * 8ms * 1, + } + ); +#endif + +// ssf_flush_pipeline(context); + + +// return_to_academy_after_loss(env, console, context); + + + + +// fly_from_paldea_to_blueberry_entrance(env.program_info(), console, context); + + + +#if 0 + ssf_press_button(context, BUTTON_A, 0); + ssf_do_nothing(context, 4); + ssf_press_button(context, BUTTON_A, 0); + ssf_do_nothing(context, 4); + ssf_press_button(context, BUTTON_A, 0); + ssf_do_nothing(context, 4); + ssf_press_button(context, BUTTON_A, 0); + ssf_do_nothing(context, 4); +#endif + + + +// enter_digits(context, 8, (const uint8_t*)"56685459"); + +#if 0 + for (int c = 0; c < 10; c++){ + scroll_to(context, 1, 9, true); + scroll_to(context, 9, 1, true); + } +// pbf_wait(context, 100); +#endif + + +#if 0 + ImageRGB32 image("20250131-170450792229.png"); + + PokemonSwSh::BattleBallReader reader(console, Language::Korean); + reader.read_ball(image); +#endif + + +#if 0 + { + TeraTypeReader reader; + ImageMatch::ImageMatchResult results = reader.read(image); + results.log(logger, 100); + } +#endif + + +#if 0 + ImageRGB32 image("20250125-224044294692.png"); + MaxLairInternal::BattleMenuReader reader(overlay, Language::English); + std::set slugs = reader.read_opponent_in_summary(logger, image); + + cout << set_to_str(slugs) << endl; +#endif + +// ssf_press_button(context, BUTTON_A, 0, 1000, 0); +// pbf_move_left_joystick(context, 0, 0, 20, 0); + + + +#if 0 + ImageRGB32 image("20250218-003554940153.png"); +// ImageRGB32 image("raidecho1.jpg"); +// auto image = feed.snapshot(); + +// MaxLairInternal::BattleMenuReader reader(overlay, Language::English); +// reader.read_opponent_in_summary(logger, image); + + TeraCardReader reader; + cout << reader.detect(image) << endl; + reader.pokemon_slug(logger, env.program_info(), image); +// cout << (int)reader.stars(logger, env.program_info(), image) << endl; +#endif + + + + + +#if 0 + ImageRGB32 image("20250112-194339635973.png"); + + PokemonBDSP::SelectionArrowFinder detector0(console, {0.50, 0.58, 0.40, 0.10}, COLOR_RED); + PokemonBDSP::SelectionArrowFinder detector1(console, {0.50, 0.52, 0.40, 0.10}, COLOR_RED); + + cout << detector0.detect(image) << endl; + cout << detector1.detect(image) << endl; +#endif + + + +#if 0 + PokemonSwSh::MaxLairInternal::PokemonSwapMenuReader reader(console, overlay, Language::English); + + ImageRGB32 image("20241221-123730238930.png"); + + double hp[4]; + reader.read_hp(image, hp); +#endif + +// reader.read_opponent_in_summary(logger, image); + +// PokemonSwSh::find_selection_arrows(image, 10); + + +// LifetimeSanitizer::terminate_with_dump(); + +// PokemonSV::AuctionFarmer farmer; +// farmer.check_offers(env); +// std::terminate(); + +#if 0 + ImageRGB32 image("screenshot-20241210-110029984325.png"); +// auto image = feed.snapshot(); + + MMOQuestionMarkDetector question_mark_detector(logger); + question_mark_detector.detect_MMO_on_hisui_map(image); +#endif + + +#if 0 + PokemonLA::OutbreakReader reader(logger, Language::English, overlay); + reader.make_overlays(overlays); + + ImageRGB32 image("screenshot-20241124-135028529403.png"); +#endif + +// reader.read(feed.snapshot()); + + +// PokemonLA::ButtonDetector detector(logger, PokemonLA::ButtonType::ButtonA,); + +// while (true){ +// SystemSleepController::instance().push_screen_on(); +// scope.wait_for(std::chrono::seconds(10)); +// } + +// SetThreadExecutionState(ES_CONTINUOUS | ES_DISPLAY_REQUIRED); + +// console.save_stream_history("video.mp4"); + +#if 0 + VideoSnapshot image = feed.snapshot(); + report_error( + &env.logger(), + env.program_info(), + "testtest", + {{"title", "message"}}, + image, + {"test.txt"} + ); +#endif + +#if 0 + VideoSnapshot image = feed.snapshot(); +// ImageRGB32 image("20250108-151305644248.png"); + + DateReader date_reader; + date_reader.make_overlays(overlays); + auto date = date_reader.read_date(logger, image); +// auto date = date_reader.read_date(logger, std::make_shared(std::move(image))); + cout << "year = " << (int)date.second.year << endl; + cout << "month = " << (int)date.second.month << endl; + cout << "day = " << (int)date.second.day << endl; + cout << "hour = " << (int)date.second.hour << endl; + cout << "min = " << (int)date.second.minute << endl; + cout << "secs = " << (int)date.second.second << endl; +#endif + +#if 0 + + VideoSnapshot image = feed.snapshot(); + DirectionDetector detector; + + // ImageRGB32 image("MaterialFarmer-1.png"); + // ImageRGB32 image("dark-capture-card_1.png"); + // DirectionDetector detector(COLOR_BLUE, ImageFloatBox(0,0,1,1)); + + // std::pair north_location = detector.locate_north(image); + // detector.current_direction(image); + detector.change_direction(env.program_info(), console, context, 3.14); + +#endif + +#if 0 + ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); + detector.make_overlays(overlays); + // cout << (int)detector.find_happiny_dust_row_index(env.inference_dispatcher(), console, context) << endl; + // cout << (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2) << endl; + + // test OCR for number 1 -> 999. for black text on light background. + // increasing quantity of materials to sell. + for (int i = 1; i < 1000; i++){ + context.wait_for_all_requests(); + if (i != (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + console, + "OCR didn't match expected value." + ); + } + pbf_press_dpad(context, DPAD_UP, 20, 30); + } + + // test OCR for number 1 -> 999. for white text on dark background + // decreasing quantity of current materials by selling. + // for (int i = 999; i > 0; i--){ + // context.wait_for_all_requests(); + // if (i != (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2)){ + // OperationFailedException::fire( + // ErrorReport::SEND_ERROR_REPORT, + // console, + // "OCR didn't match expected value." + // ); + // } + // pbf_press_button(context, BUTTON_A, 30, 150); + // pbf_press_button(context, BUTTON_A, 30, 150); + // pbf_press_button(context, BUTTON_A, 30, 150); + // pbf_press_button(context, BUTTON_A, 30, 150); + // } + + +#endif + +#if 0 + ImageRGB32 image("screenshot-20240701-165012250266.png"); + + BattleBallReader reader(console, Language::English); + cout << reader.read_quantity(image) << endl; +#endif + +#if 0 + // ImageRGB32 image("screenshot-20240701-165012250266.png"); + + // BattleBallReader reader(console, Language::English); + // cout << reader.read_quantity(image) << endl; + + VideoSnapshot image = feed.snapshot(); + // IngredientSession session(env.inference_dispatcher(), console, context, Language::English, SandwichIngredientType::CONDIMENT); + // session.read_ingredient_quantity(console, context, 8); + + SandwichIngredientReader reader(SandwichIngredientType::FILLING); + // ImageMatch::ImageMatchResult image_result = reader.read_with_icon_matcher(image, ImageFloatBox(0.508, 0.820, 0.032, 0.057)); + for (int i = 0; i < 6; i++){ + ImageMatch::ImageMatchResult image_result = reader.read_with_icon_matcher(image, ImageFloatBox(0.508781 + 0.0468*i, 0.820, 0.032, 0.057)); + image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); + image_result.log(console, SandwichIngredientReader::MAX_ALPHA); + image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); + } +#endif + + +#if 0 + ImageRGB32 image("screenshot-20240630-183016042676.png"); + + ButtonTracker tracker(ButtonType::ButtonA); + WhiteObjectWatcher watcher(overlay, {0.55, 0.40, 0.20, 0.40}, { {tracker, false} }); + watcher.process_frame(image, current_time()); +#endif + +#if 0 + VideoSnapshot screen = console.video().snapshot(); + ItemPrinterJobsDetector detector(COLOR_RED); + cout << (int)detector.detect_jobs(logger, env.inference_dispatcher(), screen) << endl; +#endif + +#if 0 + ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); + detector.make_overlays(overlays); + // cout << (int)detector.find_happiny_dust_row_index(env.inference_dispatcher(), console, context) << endl; + cout << (int)detector.detect_material_quantity(env.inference_dispatcher(), console, context, 2) << endl; +#endif + +#if 0 + VideoSnapshot screen = console.video().snapshot(); + ItemPrinterJobsDetector detector(COLOR_RED); + cout << (int)detector.detect_jobs(logger, env.inference_dispatcher(), screen) << endl; +#endif + +#if 0 + VideoSnapshot screen = console.video().snapshot(); + + OverworldDetector detector; + cout << detector.detect(screen) << endl; +#endif + +#if 0 + ItemPrinterJobsDetector detector(COLOR_RED, LANGUAGE); + detector.make_overlays(overlays); + + detector.set_print_jobs(console, context, 5); +#endif + + +#if 0 + ItemPrinterPrizeReader reader(Language::English); + reader.make_overlays(overlays); + + reader.read(logger, env.inference_dispatcher(), feed.snapshot()); +#endif + + +// SinglesAIOption battle_AI; +// run_singles_battle(env, console, context, battle_AI, false); + + + + +// pbf_press_button(context, BUTTON_HOME, 20, GameSettings::instance().GAME_TO_HOME_DELAY); +// reset_game_from_home(env.program_info(), console, context, 5 * TICKS_PER_SECOND); + + +#if 0 + VideoSnapshot screen = console.video().snapshot(); + + PokemonSummaryDetector summary; + cout << summary.detect(screen) << endl; +#endif + + +#if 0 + ImageViewRGB32 box = extract_box_reference(screen, ImageFloatBox(0.28, 0.20, 0.03, 0.055)); + ImageStats stats = image_stats(box); + cout << stats.average << stats.stddev << endl; + + bool item_held = !is_solid(stats, {0.550405, 0.449595, 0.}, 0.20); + cout << "item_held = " << item_held << endl; +#endif + +#if 0 + run_pokemon( + console, context, + { + {SinglesMoveType::Move1, false}, + {SinglesMoveType::Move2, false}, + {SinglesMoveType::Move4, true}, + {SinglesMoveType::Run, false}, + } + ); +#endif + + + +#if 0 + auto snapshot = console.video().snapshot(); + + PokemonSummaryDetector detector; + detector.make_overlays(overlays); + cout << detector.detect(snapshot) << endl; +#endif + + +#if 0 + auto snapshot = console.video().snapshot(); + ImageViewRGB32 box0 = extract_box_reference(snapshot, ImageFloatBox{0.415, 0.085, 0.035, 0.057}); + ImageViewRGB32 box1 = extract_box_reference(snapshot, ImageFloatBox{0.553, 0.085, 0.035, 0.057}); + + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(box1, 0xff808080, 0xffffffff); + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (iter->find_next(object, false)){ + extract_box_reference(box1, object).save("test.png"); + } + } + #endif + + + +// PokemonSwSh::ReceivePokemonDetector caught_detector(true); +// caught_detector.process_frame(); + + +#if 0 + start_game_from_home( + console, context, + true, 0, 0, + 10 + ); +#endif + +#if 0 +// UpdateMenuWatcher update_menu(false); + CheckOnlineDetector update_menu(false); + update_menu.make_overlays(overlays); + + auto snapshot = console.video().snapshot(); + cout << update_menu.detect(snapshot) << endl; +#endif + +#if 0 + +// ImageRGB32 image("screenshot-20231003-202430049819.png"); + auto snapshot = console.video().snapshot(); + + PokemonSummaryDetector detector; + cout << detector.detect(snapshot) << endl; +#endif + +#if 0 + SummaryStatsReader reader; + reader.make_overlays(overlays); + + auto snapshot = console.video().snapshot(); + + NatureAdjustments nature = reader.read_nature(logger, snapshot); + cout << "attack = " << (int)nature.attack << endl; + cout << "defense = " << (int)nature.defense << endl; + cout << "spatk = " << (int)nature.spatk << endl; + cout << "spdef = " << (int)nature.spdef << endl; + cout << "speed = " << (int)nature.speed << endl; + + StatReads stats = reader.read_stats(logger, snapshot); + cout << "hp = " << stats.hp << endl; + cout << "attack = " << stats.attack << endl; + cout << "defense = " << stats.defense << endl; + cout << "spatk = " << stats.spatk << endl; + cout << "spdef = " << stats.spdef << endl; + cout << "speed = " << stats.speed << endl; + + BaseStats base_stats{113, 70, 120, 135, 65, 52}; + EVs evs{0, 0, 0, 0, 0, 0}; + IvRanges ivs = reader.calc_ivs(logger, snapshot, base_stats, evs); + cout << "hp = " << (int)ivs.hp.low << " - " << (int)ivs.hp.high << endl; + cout << "attack = " << (int)ivs.attack.low << " - " << (int)ivs.attack.high << endl; + cout << "defense = " << (int)ivs.defense.low << " - " << (int)ivs.defense.high << endl; + cout << "spatk = " << (int)ivs.spatk.low << " - " << (int)ivs.spatk.high << endl; + cout << "spdef = " << (int)ivs.spdef.low << " - " << (int)ivs.spdef.high << endl; + cout << "speed = " << (int)ivs.speed.low << " - " << (int)ivs.speed.high << endl; +#endif + + +#if 0 + cout << "attack: "; + reader.read_stat_adjustment({0.874, 0.293, 0.014, 0.024}, snapshot); + cout << "spatk: "; + reader.read_stat_adjustment({0.770, 0.293, 0.014, 0.024}, snapshot); + cout << "speed: "; + reader.read_stat_adjustment({0.822, 0.452, 0.014, 0.024}, snapshot); +#endif + + +#if 0 + ImageFloatBox hp (0.823, 0.244, 0.012, 0.022); + ImageFloatBox atk (0.875, 0.294, 0.012, 0.022); + ImageFloatBox def (0.875, 0.402, 0.012, 0.022); + ImageFloatBox spatk (0.771, 0.294, 0.012, 0.022); + ImageFloatBox spdef (0.771, 0.402, 0.012, 0.022); + ImageFloatBox spd (0.823, 0.453, 0.012, 0.022); + + overlays.add(COLOR_RED, hp); + overlays.add(COLOR_RED, atk); + overlays.add(COLOR_RED, def); + overlays.add(COLOR_RED, spatk); + overlays.add(COLOR_RED, spdef); + overlays.add(COLOR_RED, spd); +#endif + + + +#if 0 + PokemonSwSh::MaxLairInternal::LobbyJoinedDetector detector(2, false); + + auto snapshot = console.video().snapshot(); +// detector.VisualInferenceCallback::process_frame(snapshot); + detector.joined(snapshot, snapshot.timestamp); +#endif + +// size_t errors = 0; +// attach_item_from_bag(env.program_info(), console, context, errors); +// attach_item_from_box(env.program_info(), console, context, 1, errors); + +// BagDetector detector; +// detector.make_overlays(overlays); +// auto snapshot = console.video().snapshot(); +// cout << detector.detect(snapshot) << endl; + + +#if 0 + TeraCatchDetector detector(COLOR_RED); + detector.make_overlays(overlays); + + auto snapshot = console.video().snapshot(); + cout << detector.detect(snapshot) << endl; + + detector.move_to_slot(console, context, 1); +#endif + +// std::shared_ptr screen(new ImageRGB32("20230920-123043559137-OperationFailedException.png")); + +// IngredientSession session(env.inference_dispatcher(), console, context, Language::English, SandwichIngredientType::FILLING); +// session.read_screen(screen); + + + + +// pbf_press_dpad(context, DPAD_RIGHT, 160, 0); +// pbf_press_dpad(context, DPAD_DOWN, 40, 0); + + + + +// PokemonLA::save_game_from_overworld(env, console, context); + + + + + +#if 0 + TeraCardReader reader; + + auto snapshot = console.video().snapshot(); + cout << reader.detect(snapshot) << endl; +#endif + +#if 0 + NormalDialogDetector detector(logger, overlay, true); + + detector.make_overlays(overlays); + + auto snapshot = console.video().snapshot(); + cout << detector.process_frame(snapshot, snapshot.timestamp) << endl; +#endif + +// PokemonLA::open_travel_map_from_jubilife(env, console, context); + + + + + + +#if 0 + FrozenImageDetector detector(std::chrono::seconds(5), 10); + + int ret = wait_until( + console, scope, std::chrono::seconds(10), + {detector} + ); + if (ret >= 0){ + console.log("triggered"); + }else{ + console.log("timed out"); + } +#endif + +// NewsDetector detector; +// detector.make_overlays(overlays); + + + +// VideoSnapshot image = feed.snapshot(); + +// BoxSelectionBoxModeWatcher watcher; +// watcher.process_frame(image, image.timestamp); + +// connect_to_internet_from_overworld(env.program_info(), console, context); + + + +#if 0 + MainMenuDetector detector; + detector.make_overlays(overlays); + detector.move_cursor(env.program_info(), console, context, MenuSide::RIGHT, 6, true); +#endif + +#if 0 + ImageRGB32 image("20230226-042613391191-PathPartyReader-ReadSprites.png"); + + PokemonSwSh::MaxLairInternal::GlobalState state; + PokemonSwSh::MaxLairInternal::PathReader reader(overlay, 0); + reader.read_sprites(logger, state, image); +#endif + +// NintendoSwitch::PokemonSwSh::BattleBallReader reader(console, Language::English); +// reader.read_ball(image); + + + +// basic_catcher(console, context, Language::English, "beast-ball", true); + +#if 0 + VideoSnapshot image = feed.snapshot(); + IngredientSession session(env.inference_dispatcher(), console, context, Language::English); + session.read_current_page(); +#endif + + + +#if 0 + add_sandwich_ingredients( + env.inference_dispatcher(), console, context, Language::English, + { + {"pickle", 1}, + {"cucumber", 1}, + {"tomato", 3}, + }, + { + {"sour-herba-mystica", 1}, + {"spicy-herba-mystica", 1}, + } + ); +#endif + + +#if 0 + IngredientSession session(env.inference_dispatcher(), console, context, Language::English); +// basic_catcher(console, context, Language::English, "poke-ball", true); + + +#if 0 + PageIngredients page = session.read_current_page(); + for (size_t c = 0; c < 10; c++){ + cout << set_to_str(page.item[c]) << endl; + } +#endif + +// cout << "Found: " << session.move_to_ingredient({"tomato"}) << endl; + session.add_ingredients(console, context, { + {"pickle", 1}, + {"cucumber", 1}, + {"tomato", 3}, + }); + pbf_press_button(context, BUTTON_PLUS, 20, 230); + + pbf_press_dpad(context, DPAD_UP, 20, 105); + session.add_ingredients(console, context, { + {"sour-herba-mystica", 1}, + {"spicy-herba-mystica", 1}, + }); + pbf_press_button(context, BUTTON_PLUS, 20, 230); +#endif + + +#if 0 + auto image = feed.snapshot(); + + NormalBattleMenuDetector detector(COLOR_RED); + detector.detect_slot(image); + detector.move_to_slot(console, context, 0); +#endif + + + +// save_game_from_menu_or_overworld(env.program_info(), console, context, true); + + + +// auto_heal_from_menu(env.program_info(), console, context, 0, true); + + + +// return_to_inside_zero_gate(env.program_info(), console, context); +// inside_zero_gate_to_secret_cave_entrance(env.program_info(), console, context); + + +// inside_zero_gate_to_station(env.program_info(), console, context, 1, false); +// ssf_press_left_joystick(context, 144, 0, 0, 5 * TICKS_PER_SECOND); +// pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); + +// pbf_move_left_joystick(context, 96, 255, 5 * TICKS_PER_SECOND, 0); + + +#if 0 + auto image = feed.snapshot(); + + NewsDetector detector; + cout << detector.detect(image) << endl; +#endif + + + +// pbf_mash_button(context, BUTTON_ZR, 3 * TICKS_PER_SECOND); + +#if 0 + auto image = feed.snapshot(); + SweatBubbleDetector detector(COLOR_RED, {0.11, 0.81, 0.06, 0.10}); + cout << detector.detect(image) << endl; +#endif + + +#if 0 + NavigatePlatformSettings settings; + + return_to_inside_zero_gate(env.program_info(), console, context); + inside_zero_gate_to_platform(env.program_info(), console, context, settings); +#endif + +#if 0 + auto image = feed.snapshot(); + + ImageRGB32 filtered = filter_rgb32_range(image, 0xff000040, 0xff8080ff, Color(0xffff0000), true); + filtered.save("test.png"); + + using namespace Kernels::Waterfill; + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000040, 0xff8080ff); + +// size_t min_width = screen.width() / 4; +// size_t min_height = screen.height() / 4; + + WaterfillObject biggest; + WaterfillObject object; + + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(10000); + while (iter->find_next(object, false)){ +// if (object.min_y != 0){ +// continue; +// } + if (biggest.area < object.area){ + biggest = std::move(object); + } + } + + cout << biggest.center_of_gravity_x() / image->width() << ", " << biggest.center_of_gravity_y() / image->height() << endl; +#endif + + +#if 0 +// pbf_controller_state(context, 0, DPAD_NONE, 192, 255, 116, 128, 3 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 192, 0, 20, 105); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + ssf_press_button(context, BUTTON_LCLICK, 0, 500); + ssf_press_joystick(context, true, 128, 0, 125, 1250); + + // Jump + ssf_press_button(context, BUTTON_B, 125, 100); + + // Fly + ssf_press_button(context, BUTTON_B, 0, 50); + + pbf_move_left_joystick(context, 144, 0, 750, 0); + pbf_move_left_joystick(context, 128, 0, 1000, 0); +#endif + +#if 0 + ZeroGateWarpPromptDetector detector; + auto image = feed.snapshot(); + detector.detect(image); +#endif + + +// zero_gate_to_platform(env.program_info(), console, context); + + +#if 0 + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 128, 0, 625, 0); + ssf_press_button(context, BUTTON_B, 0, 50); + pbf_move_left_joystick(context, 128, 0, 250, 0); + pbf_move_left_joystick(context, 160, 0, 600, 0); + pbf_move_left_joystick(context, 128, 0, 1875, 0); +#endif + + +#if 0 + EncounterWatcher encounter(console, COLOR_RED); + + throw ProgramFinishedException( + console, + "test", + encounter.shiny_screenshot() + ); +#endif + + +#if 0 + LetsGoKillWatcher watcher(logger, COLOR_RED, false); + + wait_until( + console, scope, std::chrono::seconds(600), + { + watcher, + } + ); +#endif + +#if 0 + LetsGoKillDetector detector(COLOR_RED, {0.71, 0.15, 0.04, 0.30}); + detector.make_overlays(overlays); + while (true){ + detector.detect(feed.snapshot()); + scope.wait_for(std::chrono::milliseconds(100)); + } +#endif + +#if 0 +// ImageRGB32 image("Screenshots/screenshot-20230205-141319486902.png"); + ImageRGB32 image("LetsGoKill.png"); + +// LetsGoKillDetector detector(COLOR_RED, {0.5, 0, 0.5, 0.5}); + LetsGoKillDetector detector(COLOR_RED, {0, 0, 1, 1}); + detector.detect(image); +#endif + + +#if 0 + EncounterWatcher encounter(console); + int ret = wait_until( + console, scope, std::chrono::seconds(600), + { + static_cast(encounter), + static_cast(encounter), + } + ); + encounter.throw_if_no_sound(); + + if (ret == 0){ + logger.log("Found battle menu!"); + } + + if (encounter.shiny_screenshot()){ + encounter.shiny_screenshot()->save("test.png"); + } +#endif + + +#if 0 + pbf_move_left_joystick(context, 128, 255, 300, 0); + pbf_move_left_joystick(context, 128, 0, 50, 0); + pbf_press_button(context, BUTTON_R, 20, 0); + pbf_move_left_joystick(context, 128, 0, 350, 0); +#endif +#if 0 + size_t count = 0; + while (true){ + NormalBattleMenuWatcher battle_menu(COLOR_RED); + AreaZeroSkyTracker sky_tracker(overlay); + context.wait_for_all_requests(); + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + while (true){ + switch (count++ % 2){ + case 0: + run_overworld(env, console, context, sky_tracker, 0.50); + break; + case 1: + run_overworld(env, console, context, sky_tracker, 0.70); + break; + } + } + }, + {battle_menu, sky_tracker} + ); + context.wait_for(std::chrono::milliseconds(200)); + if (ret == 0){ + console.log("Detected battle encounter."); + pbf_press_dpad(context, DPAD_DOWN, 250, 0); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); + } + } +#endif + + + + + + +#if 0 + auto image = feed.snapshot(); + + ImageRGB32 filtered = filter_rgb32_range(image, 0xffe0e000, 0xffffffff, Color(0xff000000), false); + filtered.save("test.png"); +#endif + +// change_view_to_stats_or_judge(console, context); +// change_view_to_judge(console, context, Language::English); + + + + +#if 0 + auto image = feed.snapshot(); + + ImageRGB32 filtered = filter_rgb32_range(image, 0xff808000, 0xffffffff, Color(0xff000000), false); + filtered.save("test.png"); +#endif + +#if 0 + TeraBattleMenuDetector battle_menu(COLOR_RED); + MoveSelectDetector move_select(COLOR_YELLOW); + CheerSelectDetector cheer_select(COLOR_GREEN); + battle_menu.make_overlays(overlays); + move_select.make_overlays(overlays); + cheer_select.make_overlays(overlays); + + auto image = feed.snapshot(); + cheer_select.detect_slot(image); +#endif + + +#if 0 + auto image = feed.snapshot(); + CodeEntryDetector detector; + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; +#endif + + +// enter_tera_search(env.program_info(), console, context, false); +// open_hosting_lobby(env.program_info(), console, context, HostingMode::ONLINE_CODED); + +#if 0 + auto image = feed.snapshot(); + TeraLobbyReader detector(console.logger(), env.realtime_dispatcher()); + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; +#endif + +#if 0 + size_t host_index = 1; + ConsoleHandle& host = env.consoles[host_index]; + BotBaseContext host_context(scope, host.botbase()); + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + if (console.index() == host_index){ + open_raid(console, context); + }else{ + enter_tera_search(env.program_info(), console, context, true); + } + }); + open_hosting_lobby(env.program_info(), host, host_context, HostingMode::ONLINE_CODED); + + TeraLobbyReader lobby_reader; + std::string code = lobby_reader.raid_code(env.logger(), env.realtime_dispatcher(), host.video().snapshot()); + std::string normalized_code; + const char* error = normalize_code(normalized_code, code); + if (error){ +// pbf_press_button(host_context, BUTTON_B, 20, 230); +// pbf_press_button(host_context, BUTTON_A, 20, 230); + OperationFailedException::fire(env.logger(), "Unable to read raid code."); + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + if (console.index() == host_index){ + return; + } + enter_code(console, context, FastCodeEntrySettings(), normalized_code, false); + }); +#endif + + + +#if 0 + TeraRaidSearchDetector detector(COLOR_YELLOW); + + auto image = feed.snapshot(); + cout << detector.detect(image) << endl; + detector.move_cursor_to_search(env.program_info(), console, context); +#endif + +#if 0 + auto image = feed.snapshot(); + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000000, 0xff808080); + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + + size_t c = 0; + while (iter->find_next(object, false)){ +// cout << "yellow = " << object.area << endl; + extract_box_reference(image, object).save("object-" + std::to_string(c++) + ".png"); +// yellows.emplace_back(std::move(object)); + } +#endif + + + + + + + +#if 0 + PokePortalDetector detector(COLOR_YELLOW); + + auto image = feed.snapshot(); + cout << detector.detect_location(image) << endl; + + detector.move_cursor(env.program_info(), console, context, 2); +#endif + + +// size_t errors; +// release_box(env.program_info(), console, context, errors, 1); + + + +#if 0 +// TeraCatchWatcher catch_menu(COLOR_BLUE); +#if 0 + WhiteButtonWatcher next_button( + COLOR_CYAN, + WhiteButton::ButtonA, + {0.8, 0.93, 0.2, 0.07}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::seconds(1) + ); +#endif +// AdvanceDialogWatcher advance(COLOR_YELLOW); + PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); + PromptDialogWatcher view_summary(COLOR_PURPLE, {0.500, 0.470, 0.400, 0.100}); + PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); +// PokemonSummaryWatcher summary(COLOR_MAGENTA); + MainMenuWatcher main_menu(COLOR_BLUE); +// OverworldWatcher overworld(COLOR_RED); + +// catch_menu.make_overlays(overlays); +// next_button.make_overlays(overlays); +// advance.make_overlays(overlays); + add_to_party.make_overlays(overlays); + view_summary.make_overlays(overlays); + nickname.make_overlays(overlays); +// summary.make_overlays(overlays); + main_menu.make_overlays(overlays); +// overworld.make_overlays(overlays); +#endif + + +#if 0 + OverworldWatcher overworld; + int ret = wait_until( + console, context, std::chrono::seconds(5), + {overworld} + ); + cout << ret << endl; +#endif + +#if 0 + ImageRGB32 image("BadArrow.png"); + + TeraBattleMenuDetector battle_menu(COLOR_RED); + MoveSelectDetector move_select(COLOR_GREEN); + TargetSelectDetector target_select(COLOR_CYAN); + TeraCatchDetector tera_catch(COLOR_BLUE); +// battle_menu.make_overlays(overlays); +// move_select.make_overlays(overlays); +// target_select.make_overlays(overlays); +// tera_catch.make_overlays(overlays); + cout << (int)battle_menu.detect_slot(image) << endl; + +// battle_menu.move_to_slot(console, context, 0); +// move_select.move_to_slot(console, context, 1); +// target_select.move_to_slot(console, context, 2); +#endif + + +// change_stats_view_to_judge(env.program_info(), console, context); + + +#if 0 + auto image = feed.snapshot(); + ImageFloatBox box(0.66, 0.08, 0.52, 0.04); + ImageStats stats = image_stats(extract_box_reference(image, box)); + cout << stats.average << stats.stddev << endl; +#endif + + + +#if 0 + auto image = feed.snapshot(); + + TeraLobbyReader detector; +// cout << detector.seconds_left(env.logger(), image) << endl; + cout << detector.raid_code(env.logger(), image) << endl; +#endif + + + +#if 0 + QClipboard* clipboard = QApplication::clipboard(); + cout << clipboard->supportsSelection() << endl; + + while (true){ + std::string code = clipboard->text(QClipboard::Selection).toStdString(); + cout << code << endl; + scope.wait_for(std::chrono::milliseconds(1000)); + } +#endif + + +// while (true){ + +// } + +#if 0 + pbf_move_left_joystick(context, 0, 128, 40, 40); + // Move forward to pass table + pbf_move_left_joystick(context, 128, 0, 80, 40); // old value: 80 + // Move right + pbf_move_left_joystick(context, 255, 128, 40, 40); + // Move back to face basket + pbf_move_left_joystick(context, 128, 255, 10, 40); +#endif + + +#if 0 +// ImageFloatBox box(0.02, ); + auto image = feed.snapshot(); + WhiteButtonDetector detector(COLOR_RED, WhiteButton::ButtonA, {0.020, 0.590, 0.035, 0.060}); + cout << detector.detect(image) << endl; +#endif + + +// auto image = feed.snapshot(); +// TeraCatchDetector detector(COLOR_RED); +// cout << detector.detect(image) << endl; + +// size_t errors; +// release_one_pokemon(env.program_info(), console, context, errors); + + +#if 0 + auto image = feed.snapshot(); + + TeraLobbyReader detector; + detector.make_overlays(overlays); + detector.ready_players(image); +#endif + +#if 0 + MainMenuDetector detector; + detector.move_cursor(env.program_info(), console, context, MenuSide::RIGHT, 1); + cout << "done" << endl; +#endif + + +#if 0 + size_t eggs_collected = 0; + check_basket_to_collect_eggs( + env.program_info(), console, context, + 1, eggs_collected + ); +#endif + + +#if 0 + auto image = feed.snapshot(); + DialogBoxDetector detector; + cout << detector.detect(image) << endl; +#endif + +#if 0 + BattleMenuDetector detector(COLOR_RED); + while (true){ + scope.wait_for(std::chrono::milliseconds(50)); + auto image = feed.snapshot(); + cout << detector.detect(image) << endl; + } +#endif + + +#if 0 + auto image = feed.snapshot(); + TeraCatchWatcher detector(COLOR_RED); + bool ok = detector.detect(image); + cout << ok << endl; + if (!ok){ + image.frame->save("tmp.png"); + } + +#if 0 + int ret = wait_until( + console, context, std::chrono::seconds(60), + {detector} + ); + cout << "ret = " << ret << endl; +#endif +#endif + + +#if 0 + auto image = feed.snapshot(); + + BoxDetector detector; + cout << detector.detect(image) << endl; + + while (true){ + scope.wait_for(std::chrono::milliseconds(50)); + image = feed.snapshot(); + std::pair location = detector.detect_location(image); + cout << (int)location.first << ": " << (int)location.second.row << "," << (int)location.second.col << endl; + } +#endif + + +#if 0 + GradientArrowDetector party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); + auto image = feed.snapshot(); + cout << party_select_top.detect(image) << endl; +#endif + +#if 0 + auto image = feed.snapshot(); + SomethingInBoxSlotDetector detector(COLOR_RED, true); + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; +#endif + +#if 0 + AsyncCommandSession session(scope, logger, env.realtime_dispatcher(), context.botbase()); + session.dispatch([](ProControllerContext& context){ +// pbf_controller_state(context, 0, DPAD_NONE, 128, 0, 128, 128, 255); + pbf_press_button(context, BUTTON_A, 255, 0); + }); + context.wait_for(std::chrono::seconds(2)); + session.dispatch([](ProControllerContext& context){ +// pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 255); + pbf_press_button(context, BUTTON_B, 255, 0); + }); + +#else +#if 0 + pbf_controller_state(context, 0, DPAD_NONE, 128, 0, 128, 128, 500); + context.wait_for_all_requests(); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 500); +#endif +#endif + +// pbf_press_button(context, BUTTON_B, 500, 10); +// pbf_controller_state(context, 0, DPAD_NONE, 128, 0, 128, 128, 500); +// context.wait_for_all_requests(); +// pbf_wait(context, 1); +// pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 500); + + + +#if 0 + KeyboardEntryPosition point0{1, 0}; + KeyboardEntryPosition point1{1, 10}; +// uint16_t scroll_delay = 3; +// uint16_t A_delay = 3; + + auto path0 = get_codeboard_digit_path(point0, point1); + auto path1 = get_codeboard_digit_path(point1, point0); + + while (true){ + move_codeboard(context, path0, true); + move_codeboard(context, path1, true); + } +#endif +#if 0 + while (true){ + ssf_issue_scroll(context, DPAD_LEFT, 10, 6); + ssf_issue_scroll(context, DPAD_LEFT, 4, 6); + ssf_issue_scroll(context, DPAD_LEFT, 4, 6); + ssf_issue_scroll(context, DPAD_LEFT, 10, 6); + ssf_issue_scroll(context, DPAD_RIGHT, 10, 6); + ssf_issue_scroll(context, DPAD_RIGHT, 4, 6); + ssf_issue_scroll(context, DPAD_RIGHT, 4, 6); + ssf_issue_scroll(context, DPAD_RIGHT, 10, 6); + } +#endif + +#if 0 + ImageRGB32 image("20221206-225502975702-NoState.png"); + +// OverlayBoxScope ore_box(console, {0.930, 0.050, 0.065, 0.010}); +// extract_box_reference(image, ore_box).save("test.png"); + + AdvanceDialogDetector detector; + cout << detector.detect(image) << endl; +#endif + +#if 0 + while (true){ + pbf_press_button(context, BUTTON_HOME, 20, GameSettings::instance().GAME_TO_HOME_DELAY); + set_time_to_12am_from_home(console, context); + reset_game_from_home(env, console, context, 5 * TICKS_PER_SECOND); + } +#endif + + +#if 0 + ImageRGB32 image("screenshot-20221204-232949766645.png"); + + MainMenuDetector detector; + auto detection = detector.detect_location(image); + cout << (int)detection.first << " : " << detection.second << endl; + +// GradientArrowDetector party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); +// bool detected = party_select_top.detect(image); +// cout << detected << endl; +#endif + + + + + +#if 0 +// GradientArrowDetector party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); + MainMenuDetector detector; + while (true){ + VideoSnapshot snapshot = feed.snapshot(); + auto detection = detector.detect_location(snapshot); +// bool detected = party_select_top.detect(snapshot); + cout << (int)detection.first << " : " << detection.second << endl; +// if (!detected){ +// snapshot.frame->save("test.png"); +// } + scope.wait_for(std::chrono::milliseconds(100)); + } +#endif + +#if 0 + send_program_notification( + env.logger(), NOTIFICATION_TEST, + COLOR_GREEN, env.program_info(), + "Test Title", + { + { + "", + "[TestTest](https://discordtips.com/how-to-hyperlink-in-discord/)" + }, + } + ); +#endif + + +// pbf_move_left_joystick(context, 129, 128, 10000, 0); +// pbf_move_left_joystick(context, 128, 0, 90, 0); + + +// ImageRGB32 image("screenshot-20221128-084818449677.png"); +// PromptDialogDetector detector(COLOR_RED); +// cout << detector.detect(image) << endl; + + +// ssf_press_button(context, BUTTON_A, 8, 20); +// pbf_press_button(context, BUTTON_B, 20, 105); + + + + +#if 0 + ImageRGB32 image("20221206-035546876682.jpg"); +// auto image = feed.snapshot(); + + TeraLobbyReader reader; + reader.make_overlays(overlays); +#if 0 + reader.check_ban_list( + { + {Language::English, "Halazea"}, + }, + image, + true + ); +#endif + reader.raid_code(logger, env.program_info(), image); +// cout << (int)reader.total_players(image) << endl; +#endif + + + +// connect_to_internet_from_overworld(console, context); +// day_skip_from_overworld(console, context); + + + +// save_game_from_overworld(console, context); + + +#if 0 + OverworldDetector overworld; + overworld.make_overlays(overlays); + + auto image = feed.snapshot(); +// overworld.detect(image); + cout << overworld.detect_ball(image) << endl; +#endif + +// wait_until(); + +// ImageRGB32 image("ball-1-new.png"); + +// filter_rgb32_range(image, 0xffc0c000, 0xffffff3f, Color(0), false).save("ball-template.png"); + + +// ImageFloatBox ball(0.890, 0.790, 0.030, 0.070); +// ImageFloatBox radar(0.815, 0.680, 0.180, 0.310); + + + +// save_game_from_menu(console, context); + +// enter_alphanumeric_code(logger, context, "2VL4EP"); + +// run_path(context, get_path({0, 0}, {2, 6})); +// run_path(context, get_path({2, 6}, {0, 9})); +// run_path(context, get_path({0, 9}, {3, 8})); + + + +#if 0 + auto image = feed.snapshot(); + + DateReader reader; + reader.make_overlays(overlays); + cout << reader.detect(image) << endl; + cout << (int)reader.read_hours(logger, image) << endl; + reader.set_hours(console, context, 1); +#endif + + +// auto image = feed.snapshot(); +// DateReader reader; +// reader.detect(image); + + + +// TradeStats stats; +// trade_current_box(env, scope, NOTIFICATION_TEST, stats); + + +// BoxDetector detector; +// detector.move_cursor(console, context, BoxCursorLocation::SLOTS, 3, 3); + +// MainMenuDetector detector; +// detector.move_cursor(console, context, MenuSide::RIGHT, 4); + +#if 0 + auto image = feed.snapshot(); + BoxDetector detector; + auto ret = detector.detect_location(image); + cout << (int)ret.first << " | " << (int)ret.second.row << ", " << (int)ret.second.col << endl; +#endif + +#if 0 + MultiConsoleErrorState state; + TradeStats stats; + env.run_in_parallel( + scope, + [&](ConsoleHandle& console, ProControllerContext& context){ + trade_current_pokemon(console, context, state, stats); + } + ); +#endif + + +#if 0 + auto image = feed.snapshot(); + TeraLobbyReader detector(COLOR_RED); + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; + cout << detector.total_players(image) << endl; +#endif + + +#if 0 +// ImageRGB32 image("NoCardDetection.png"); + auto image = feed.snapshot(); + TeraCardReader detector(COLOR_RED); + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; + cout << detector.stars(image) << endl; +#endif + + +#if 0 + ImageRGB32 image("ArrowFail.png"); +// auto image = feed.snapshot(); + + AdvanceDialogDetector detector; + cout << detector.detect(image) << endl; +// image.frame->save("test.png"); +#endif + + +#if 0 + BattleBallReader reader(console, LANGUAGE); + + pbf_press_button(context, BUTTON_A, 20, 105); + context.wait_for_all_requests(); + + int quantity = move_to_ball(reader, console, context, "poke-ball"); + cout << "quantity = " << quantity << endl; +#endif + + +#if 0 + BattleBallReader reader(console, Language::English); + auto image = feed.snapshot(); + cout << reader.read_quantity(image) << endl; + cout << reader.read_ball(image) << endl; +#endif + +#if 0 +// ImageRGB32 image("screenshot-20221120-001408323077.png"); + ImageRGB32 image("screenshot-20221118-160757832016.png"); + PokemonSummaryDetector detector; + cout << detector.detect(image) << endl; +#endif + +// auto image = feed.snapshot(); +// PokemonSummaryDetector detector; +// cout << detector.detect(image) << endl; + + +#if 0 + auto image = feed.snapshot(); + ImageStats stats = image_stats(extract_box_reference(image, ImageFloatBox{0.30, 0.33, 0.40, 0.02})); + cout << stats.average << stats.stddev << endl; +#endif + +#if 0 + ImageRGB32 image("cursor_basic_00q.png"); + GradientArrowDetector detector({0, 0, 1, 1}); + + auto hits = detector.detect_all(image); + cout << "hits = " << hits.size() << endl; + for (auto& item : hits){ + extract_box_reference(image, item).save("test.png"); + } +#endif + + +#if 0 + ImageRGB32 image("screenshot-20221121-070043212515.png"); + + WhiteButtonDetector next_button(WhiteButton::ButtonA, {0.8, 0.9, 0.2, 0.1}, COLOR_RED); + cout << next_button.detect(image) << endl; +#endif + +#if 0 + ImageRGB32 image("screenshot-20221118-211428612196.png"); + + TeraCardReader detector; + cout << detector.detect(image) << endl; +#endif + +#if 0 + ImageRGB32 image("screenshot-20221122-022035906115.png"); + + MoveSelectDetector detector; + cout << detector.detect(image) << endl; +#endif + + +#if 0 + AddToPartyDetector detector; + cout << detector.detect(feed.snapshot()) << endl; +#endif + + + +// home_to_date_time(context, false, false); + +// save_game_from_overworld(console, context); + + +#if 0 + auto image = feed.snapshot(); + + PokemonSummaryDetector detector; + cout << detector.detect(image) << endl; + cout << detector.is_shiny(image) << endl; +#endif + +#if 0 + RaidShinyStarDetector detector(overlay); + wait_until( + console, context, + WallClock::max(), + {detector} + ); +#endif + + + +#if 0 + ImageRGB32 image("ShinyRaid.png"); + + ImageViewRGB32 cropped = extract_box_reference(image, ImageFloatBox{0.5, 0.1, 0.4, 0.7}); + cropped.save("test-cropped.png"); + + + ImageRGB32 filtered = filter_rgb32_range(cropped, 0xff804040, 0xffffffff, Color(0xffffff00), true); + filtered.save("test-filtered.png"); +#endif + +#if 0 + uint8_t year = MAX_YEAR; + while (true){ + pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY); + home_roll_date_enter_game_autorollback(console, context, year); + pbf_mash_button(context, BUTTON_A, 250); + } +#endif + +#if 0 + ImageRGB32 image("GradientArrowHorizontal-Template.png"); + + ImageRGB32 rotated(image.height(), image.width()); + + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + rotated.pixel(r, c) = image.pixel(c, r); + } + } + rotated.save("GradientArrowVertical-Template.png"); +#endif + + +#if 0 + auto image = feed.snapshot(); + ImageViewRGB32 cropped = extract_box_reference(image, ImageFloatBox{0.500, 0.555, 0.310, 0.070}); + PackedBinaryMatrix matrix = compress_rgb32_to_binary_euclidean(cropped, 0xff757f9c, 100); +// cout << matrix.dump() << endl; + + matrix.invert(); + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + while (iter->find_next(object, false)){ +// extract_box_reference(image, object).save("Arrow-Template.png"); + cout << object.area << endl; + } +#endif + + +#if 0 + auto image = feed.snapshot(); + + ImageViewRGB32 cropped = extract_box_reference(image, ImageFloatBox{0.500, 0.555, 0.310, 0.070}); +// ImageRGB32 filtered = filter_rgb32_range(cropped, 0xffc00000, 0xffffffff, Color(0x00000000), true); + size_t pixels; + ImageRGB32 filtered = filter_rgb32_euclidean(pixels, cropped, 0xff757f9c, 100, Color(0x00000000), true); + cout << "pixels = " << pixels << endl; + filtered.save("test.png"); +#endif + + +#if 0 + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808000, 0xffffff80); + + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + while (iter->find_next(object, false)){ + extract_box_reference(image, object).save("Arrow-Template.png"); + } +#endif + +#if 0 + ImageRGB32 image("WhiteButtonA.png"); + ImageRGB32 filtered = filter_rgb32_range(image, 0xff000000, 0xff7f7f7f, Color(0x00000000), true); + + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + if (8 < c && c < 30 && 8 < r && r < 30){ + filtered.pixel(c, r) = image.pixel(c, r); + } + } + } + filtered.save("WhiteButtonA-processed.png"); +#endif + +#if 0 + WhiteButtonFinder next_button(WhiteButton::ButtonA, console.overlay(), {0.9, 0.9, 0.1, 0.1}); + wait_until( + console, context, + std::chrono::seconds(60), + {next_button} + ); +#endif + + +#if 0 + TeraCardReader reader; +// auto image = ImageRGB32("ErrorDumps/20221115-234552197119-ReadStarsFailed.png"); + auto image = feed.snapshot(); + cout << reader.detect(image) << endl; + cout << "stars = " << reader.stars(image) << endl; + +// BattleMenuDetector battle_menu; +// cout << battle_menu.detect(image) << endl; +#endif + +// OverlayBoxScope box(overlay, COLOR_RED, {0.4, 0.4, 0.2, 0.2}, "asdf qwer sdfg"); + + +// reset_game_to_gamemenu(console, context); + + +#if 0 + ImageRGB32 image("Arrow.png"); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff); + + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (iter->find_next(object, false)){ + extract_box_reference(image, object).save("Arrow-Template.png"); + } +#endif + + +// YCommMenuDetector detector(true); +// HomeMenuDetector detector; +// cout << detector.detect(image) << endl; +// cout << detector.detect(feed.snapshot()) << endl; + + + +#if 0 + while (true){ + pbf_press_button(context, BUTTON_HOME, 20, GameSettings::instance().GAME_TO_HOME_DELAY); + reset_game_from_home(env, console, context); + } +#endif + + + +#if 0 + overlay.add_log("asdfasdf", COLOR_RED); + + for (int c = 0; c < 20; c++){ + overlay.add_log("qwerqwer", COLOR_GREEN); + scope.wait_for(std::chrono::milliseconds(1000)); + } + + scope.wait_for(std::chrono::milliseconds(5000)); + cout << "clear" << endl; + overlay.clear_log(); +#endif + +#if 0 + OverlayTextScope text(overlay, "hello world", 0.5, 0.5, 10, COLOR_WHITE); + + overlay.add_log_text("asdfasdf", COLOR_RED); + + OverlayStat stat0; + OverlayStat stat1; + OverlayStat stat2; + overlay.add_stat(stat0); + overlay.add_stat(stat1); + overlay.add_stat(stat2); + + for (size_t c = 0;; c++){ + stat2.set_text(std::to_string(c)); + scope.wait_for(std::chrono::milliseconds(100)); + } +#endif + + +#if 0 + ImageFloatBox box(0.21, 0.80, 0.53, 0.17); + + VideoSnapshot frame = feed.snapshot(); + ImageViewRGB32 image = extract_box_reference(frame, box); + + ImageRGB32 filtered = to_blackwhite_rgb32_range(image, 0xff007f7f, 0xffc0ffff, false); + filtered.save("test.png"); + + PokeballNameReader::instance().read_substring( + logger, Language::English, + image, + {{0xff007f7f, 0xff80ffff}}, 0 + ); +#endif + + +#if 0 + ImageRGB32 image("screenshot-20221107-210754107968.png"); +// auto image = feed.snapshot(); + HomeMenuDetector detector; +// UpdatePopupDetector detector; + VideoOverlaySet overlays(overlay); + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; +#endif + +// ImageRGB32 image("ExclamationFalsePositive.png"); +// find_exclamation_marks(image); + +// HomeMenuDetector detector; +// cout << detector.detect(image) << endl; + + +#if 0 + InferenceBoxScope left_mon_white(console, {0.708, 0.070, 0.005, 0.028}); + InferenceBoxScope left_mon_hp(console, {0.500, 0.120, 0.18, 0.005}); + InferenceBoxScope left_name(console, {0.467, 0.06, 0.16, 0.050}); + InferenceBoxScope right_name(console, {0.740, 0.06, 0.16, 0.050}); +#endif + +// ImageRGB32 image("Paralyzed.png"); + +#if 0 + BattleMenuDetector detector(BattleType::STANDARD); + VideoOverlaySet overlays(overlay); + detector.make_overlays(overlays); + cout << detector.detect(image) << endl; +#endif + +#if 0 + BattleMenuWatcher watcher(BattleType::STANDARD); + BotBaseContext context(scope, console.botbase()); + wait_until( + console, context, std::chrono::seconds(60), + { + {watcher} + } + ); +#endif + + +#if 0 +// ImageRGB32 image("SV-BattleMenu.png"); +// ImageRGB32 image("SV-Hair.png"); +// image = image.scale_to(1920, 1080); + + +// extract_box_reference(image, ImageFloatBox({0.7, 0.6, 0.2, 0.1})).save("tmp.png"); + +// ImageFloatBox box(0.5, 0.5, 0.4, 0.5); + ImageFloatBox box(0.0, 0.0, 1.0, 1.0); + + + VideoOverlaySet set(overlay); + WhiteButtonFinder white_button_detector0(WhiteButton::ButtonA, overlay, box); + WhiteButtonFinder white_button_detector1(WhiteButton::ButtonB, overlay, box); + WhiteButtonFinder white_button_detector2(WhiteButton::ButtonY, overlay, box); + WhiteButtonFinder white_button_detector3(WhiteButton::ButtonMinus, overlay, box); + DialogArrowFinder dialog_arrow_detector(overlay, box); + GradientArrowFinder gradient_arrow_detector(overlay, box); + dialog_arrow_detector.make_overlays(set); + gradient_arrow_detector.make_overlays(set); + BattleMenuFinder battle_menu; + battle_menu.make_overlays(set); + + while (true){ + scope.wait_for(std::chrono::milliseconds(50)); + VideoSnapshot snapshot = feed.snapshot(); + + white_button_detector0.process_frame(snapshot, current_time()); + white_button_detector1.process_frame(snapshot, current_time()); + white_button_detector2.process_frame(snapshot, current_time()); + white_button_detector3.process_frame(snapshot, current_time()); + dialog_arrow_detector.process_frame(snapshot, current_time()); + gradient_arrow_detector.process_frame(snapshot, current_time()); + battle_menu.process_frame(snapshot, current_time()); + } +#endif + +#if 0 + BotBaseContext context(scope, console.botbase()); + wait_until( + console, context, std::chrono::seconds(60), + { + {detector} + }, + std::chrono::seconds(50) + ); +#endif + + + + + + + scope.wait_for(std::chrono::seconds(60)); + + +} + + + + +#if 0 +struct RaidShinyStar{ + double alpha; + WaterfillObject object; +}; + + +class RaidShinyStarDetector : public VisualInferenceCallback{ + static constexpr double ALPHA_THRESHOLD = 1.0; + +public: + RaidShinyStarDetector(VideoOverlay& overlay) + : VisualInferenceCallback("RaidShinyStarDetector") + , m_overlay(overlay) + , m_box(overlay, {0.5, 0.1, 0.4, 0.7}) + {} + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + std::vector process_frame(const ImageViewRGB32& frame); + +private: + double test_object(const ImageViewRGB32& image, const WaterfillObject& object); + + +private: + VideoOverlay& m_overlay; + OverlayBoxScope m_box; + std::deque m_stars; +}; + + +void RaidShinyStarDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool RaidShinyStarDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + process_frame(frame); + return false; +} + +double RaidShinyStarDetector::test_object(const ImageViewRGB32& image, const WaterfillObject& object){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 0.9 || aspect_ratio > 1.1){ + return 0; + } + + double area_ratio = object.area_ratio(); + if (area_ratio < 0.5 || area_ratio > 0.8){ + return 0; + } + + // Check that center of gravity is centered. + double center_of_gravity_x = object.center_of_gravity_x(); + double center_of_gravity_y = object.center_of_gravity_y(); + double center_x = object.min_x + object.width() * 0.5; + double center_y = object.min_y + object.height() * 0.5; + + double center_shift_x = center_x - center_of_gravity_x; + double center_shift_y = center_y - center_of_gravity_y; + center_shift_x *= center_shift_x; + center_shift_y *= center_shift_y; + + double max_x_sqr = object.width() * 0.1; + double max_y_sqr = object.height() * 0.1; + max_x_sqr *= max_x_sqr; + max_y_sqr *= max_y_sqr; + + if (center_shift_x > max_x_sqr){ + return 0; + } + if (center_shift_y > max_y_sqr){ + return 0; + } + + return 1.0; +} + + +std::vector RaidShinyStarDetector::process_frame(const ImageViewRGB32& frame){ + + ImageViewRGB32 cropped = extract_box_reference(frame, m_box); + + std::vector matrices = compress_rgb32_to_binary_range(cropped, { + {0xff808080, 0xffffffff}, + {0xff909090, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + {0xffb0b0b0, 0xffffffff}, + {0xffc0c0c0, 0xffffffff}, + {0xffd0d0d0, 0xffffffff}, + {0xffe0e0e0, 0xffffffff}, + + {0xff804040, 0xffffffff}, + {0xff905050, 0xffffffff}, + {0xffa06060, 0xffffffff}, + + {0xff408040, 0xffffffff}, + {0xff509050, 0xffffffff}, + {0xff60a060, 0xffffffff}, + + {0xff404080, 0xffffffff}, + {0xff505090, 0xffffffff}, + {0xff6060a0, 0xffffffff}, + }); + +// std::vector + std::vector stars; + + std::unique_ptr session = make_WaterfillSession(); + WaterfillObject object; + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + auto iter = session->make_iterator(10); + while (iter->find_next(object, false)){ + double alpha = test_object(cropped, object); + if (alpha >= ALPHA_THRESHOLD){ + stars.emplace_back(RaidShinyStar{alpha, object}); + } + } + } + + + + + + + // Redraw the boxes. + m_stars.clear(); + for (const RaidShinyStar& star : stars){ + m_stars.emplace_back(m_overlay, translate_to_parent(frame, m_box, star.object), COLOR_BLUE); + } + return stars; +} + +#endif + + + + +} +} + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h index 530d975661..22d749dafd 100644 --- a/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h +++ b/SerialPrograms/Source/NintendoSwitch/DevPrograms/TestProgramSwitch.h @@ -1,97 +1,97 @@ -/* Test Program (Switch) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_TestProgram_H -#define PokemonAutomation_NintendoSwitch_TestProgram_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/ButtonOption.h" -#include "Common/Cpp/Options/DateOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h" -#include "PokemonSV/Options/PokemonSV_PlayerList.h" -#include "PokemonSV/Options/PokemonSV_SinglesAIOption.h" -#include "Common/Cpp/Options/ColorOption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h" -#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -//using namespace PokemonSwSh; - - - - - -class TestProgram_Descriptor : public MultiSwitchProgramDescriptor{ -public: - TestProgram_Descriptor(); -}; - - -class TestProgram : public MultiSwitchProgramInstance, public ButtonListener{ -public: - ~TestProgram(); - TestProgram(); - -// std::unique_ptr make_stats() const override{ -// return std::unique_ptr(new StatsTracker()); -// } - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - - virtual void on_press() override; - -private: - struct Stats : public StatsTracker{ - Stats() - : m_resets(m_stats["Resets"]) - { - m_display_order.emplace_back("Resets"); - } - std::atomic& m_resets; - }; - -private: - ButtonCell BUTTON0; - ButtonOption BUTTON1; - - OCR::LanguageOCROption LANGUAGE; - - StringOption IMAGE_PATH; - - StaticTextOption STATIC_TEXT; - -// PokemonSV::PlayerListTable PLAYER_LIST; - DateTimeOption DATE0; - DateTimeOption DATE1; -// ConsoleModelOption CONSOLE_MODEL; - - MillisecondsOption DURATION; - ColorCell COLOR; - ControllerSettingsTable CONTROLLER_TABLE; - - -// PokemonSV::SinglesAIOption battle_AI; - - EventNotificationOption NOTIFICATION_TEST; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -#endif - +/* Test Program (Switch) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_TestProgram_H +#define PokemonAutomation_NintendoSwitch_TestProgram_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/ButtonOption.h" +#include "Common/Cpp/Options/DateOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h" +#include "PokemonSV/Options/PokemonSV_PlayerList.h" +#include "PokemonSV/Options/PokemonSV_SinglesAIOption.h" +#include "Common/Cpp/Options/ColorOption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerSettings.h" +#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +//using namespace PokemonSwSh; + + + + + +class TestProgram_Descriptor : public MultiSwitchProgramDescriptor{ +public: + TestProgram_Descriptor(); +}; + + +class TestProgram : public MultiSwitchProgramInstance, public ButtonListener{ +public: + ~TestProgram(); + TestProgram(); + +// std::unique_ptr make_stats() const override{ +// return std::unique_ptr(new StatsTracker()); +// } + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + + virtual void on_press() override; + +private: + struct Stats : public StatsTracker{ + Stats() + : m_resets(m_stats["Resets"]) + { + m_display_order.emplace_back("Resets"); + } + std::atomic& m_resets; + }; + +private: + ButtonCell BUTTON0; + ButtonOption BUTTON1; + + OCR::LanguageOCROption LANGUAGE; + + StringOption IMAGE_PATH; + + StaticTextOption STATIC_TEXT; + +// PokemonSV::PlayerListTable PLAYER_LIST; + DateTimeOption DATE0; + DateTimeOption DATE1; +// ConsoleModelOption CONSOLE_MODEL; + + MillisecondsOption DURATION; + ColorCell COLOR; + ControllerSettingsTable CONTROLLER_TABLE; + + +// PokemonSV::SinglesAIOption battle_AI; + + EventNotificationOption NOTIFICATION_TEST; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.cpp index 6987aa5f65..8a0edaf31a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.cpp @@ -1,71 +1,71 @@ -/* Multi-Switch Program Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "NintendoSwitch_MultiSwitchProgramOption.h" -#include "UI/NintendoSwitch_MultiSwitchProgramWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -MultiSwitchProgramOption::~MultiSwitchProgramOption() = default; -MultiSwitchProgramOption::MultiSwitchProgramOption(const MultiSwitchProgramDescriptor& descriptor) - : PanelInstance(descriptor) - , m_descriptor(descriptor) - , m_system( - descriptor.required_features(), - descriptor.feedback(), - descriptor.allow_commands_while_running() - ? AllowCommandsWhenRunning::ENABLE_COMMANDS - : AllowCommandsWhenRunning::DISABLE_COMMANDS, - descriptor.min_switches(), - descriptor.max_switches(), - descriptor.default_switches() - ) - , m_instance(descriptor.make_instance()) -{} - -void MultiSwitchProgramOption::from_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - const JsonValue* value = obj->get_value("SwitchSetup"); - if (value){ - m_system.load_json(*value); - } - m_instance->from_json(json); -} -JsonValue MultiSwitchProgramOption::to_json() const{ - JsonObject obj = std::move(*m_instance->to_json().to_object()); - obj["SwitchSetup"] = m_system.to_json(); - return obj; -} - -ConfigOption& MultiSwitchProgramOption::options(){ - return m_instance->m_options; -} - -std::string MultiSwitchProgramOption::check_validity() const{ - return m_instance->check_validity(); -} -void MultiSwitchProgramOption::restore_defaults(){ - m_instance->restore_defaults(); -} - - -QWidget* MultiSwitchProgramOption::make_widget(QWidget& parent, PanelHolder& holder){ - return new MultiSwitchProgramWidget2(parent, *this, holder); -} - - - - -} -} +/* Multi-Switch Program Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "NintendoSwitch_MultiSwitchProgramOption.h" +#include "UI/NintendoSwitch_MultiSwitchProgramWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +MultiSwitchProgramOption::~MultiSwitchProgramOption() = default; +MultiSwitchProgramOption::MultiSwitchProgramOption(const MultiSwitchProgramDescriptor& descriptor) + : PanelInstance(descriptor) + , m_descriptor(descriptor) + , m_system( + descriptor.required_features(), + descriptor.feedback(), + descriptor.allow_commands_while_running() + ? AllowCommandsWhenRunning::ENABLE_COMMANDS + : AllowCommandsWhenRunning::DISABLE_COMMANDS, + descriptor.min_switches(), + descriptor.max_switches(), + descriptor.default_switches() + ) + , m_instance(descriptor.make_instance()) +{} + +void MultiSwitchProgramOption::from_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + const JsonValue* value = obj->get_value("SwitchSetup"); + if (value){ + m_system.load_json(*value); + } + m_instance->from_json(json); +} +JsonValue MultiSwitchProgramOption::to_json() const{ + JsonObject obj = std::move(*m_instance->to_json().to_object()); + obj["SwitchSetup"] = m_system.to_json(); + return obj; +} + +ConfigOption& MultiSwitchProgramOption::options(){ + return m_instance->m_options; +} + +std::string MultiSwitchProgramOption::check_validity() const{ + return m_instance->check_validity(); +} +void MultiSwitchProgramOption::restore_defaults(){ + m_instance->restore_defaults(); +} + + +QWidget* MultiSwitchProgramOption::make_widget(QWidget& parent, PanelHolder& holder){ + return new MultiSwitchProgramWidget2(parent, *this, holder); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h index fdeb76a828..8d325330a8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h @@ -1,60 +1,60 @@ -/* Multi-Switch Program Option - * - * From: https://github.com/PokemonAutomation/ - * - * This class represents the serializable state of a Switch program. - * This class maintains no UI and is not thread-safe. - * - * Note that this class does own the "MultiSwitchProgramInstance", object - * which is controlled by the individual program itself. There the running - * program can do whatever it wants - including keeping run-time state. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgramOption_H -#define PokemonAutomation_NintendoSwitch_MultiSwitchProgramOption_H - -#include "CommonFramework/Panels/PanelInstance.h" -#include "NintendoSwitch_MultiSwitchSystemOption.h" - -namespace PokemonAutomation{ - class ConfigOption; -namespace NintendoSwitch{ - -class MultiSwitchProgramDescriptor; -class MultiSwitchProgramInstance; - - -class MultiSwitchProgramOption final : public PanelInstance{ -public: - ~MultiSwitchProgramOption(); - MultiSwitchProgramOption(const MultiSwitchProgramDescriptor& descriptor); - - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - const MultiSwitchProgramDescriptor& descriptor() const{ return m_descriptor; } - MultiSwitchSystemOption& system(){ return m_system; } - MultiSwitchProgramInstance& instance(){ return *m_instance; } - ConfigOption& options(); - - std::string check_validity() const; - void restore_defaults(); - -private: - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -private: - const MultiSwitchProgramDescriptor& m_descriptor; - MultiSwitchSystemOption m_system; - std::unique_ptr m_instance; -}; - - - - - -} -} -#endif +/* Multi-Switch Program Option + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents the serializable state of a Switch program. + * This class maintains no UI and is not thread-safe. + * + * Note that this class does own the "MultiSwitchProgramInstance", object + * which is controlled by the individual program itself. There the running + * program can do whatever it wants - including keeping run-time state. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgramOption_H +#define PokemonAutomation_NintendoSwitch_MultiSwitchProgramOption_H + +#include "CommonFramework/Panels/PanelInstance.h" +#include "NintendoSwitch_MultiSwitchSystemOption.h" + +namespace PokemonAutomation{ + class ConfigOption; +namespace NintendoSwitch{ + +class MultiSwitchProgramDescriptor; +class MultiSwitchProgramInstance; + + +class MultiSwitchProgramOption final : public PanelInstance{ +public: + ~MultiSwitchProgramOption(); + MultiSwitchProgramOption(const MultiSwitchProgramDescriptor& descriptor); + + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + const MultiSwitchProgramDescriptor& descriptor() const{ return m_descriptor; } + MultiSwitchSystemOption& system(){ return m_system; } + MultiSwitchProgramInstance& instance(){ return *m_instance; } + ConfigOption& options(); + + std::string check_validity() const; + void restore_defaults(); + +private: + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +private: + const MultiSwitchProgramDescriptor& m_descriptor; + MultiSwitchSystemOption m_system; + std::unique_ptr m_instance; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp index 4076518718..945780f88f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.cpp @@ -1,289 +1,289 @@ -/* Multi-Switch Program Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Options/Environment/SleepSuppressOption.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_MultiSwitchProgramOption.h" -#include "NintendoSwitch_MultiSwitchProgramSession.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void MultiSwitchProgramSession::add_listener(Listener& listener){ - auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_listeners.insert(&listener); -} -void MultiSwitchProgramSession::remove_listener(Listener& listener){ - auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_listeners.erase(&listener); -} - - - - -MultiSwitchProgramSession::MultiSwitchProgramSession(MultiSwitchProgramOption& option) - : ProgramSession(option.descriptor()) - , m_option(option) - , m_system(option.system(), instance_id()) - , m_scope(nullptr) - , m_sanitizer("MultiSwitchProgramSession") -{ -// WriteSpinLock lg(m_lock); - m_option.instance().update_active_consoles(option.system().count()); - m_system.add_listener(*this); -} - -MultiSwitchProgramSession::~MultiSwitchProgramSession(){ - MultiSwitchProgramSession::internal_stop_program(); - m_system.remove_listener(*this); - join_program_thread(); -} - - - -void MultiSwitchProgramSession::restore_defaults(){ - auto ScopeCheck = m_sanitizer.check_scope(); - std::lock_guard lg(program_lock()); - if (current_state() != ProgramState::STOPPED){ - logger().log("Cannot change settings while program is running.", COLOR_RED); - return; - } - logger().log("Restoring settings to defaults..."); - m_option.restore_defaults(); -} -std::string MultiSwitchProgramSession::check_validity() const{ - auto ScopeCheck = m_sanitizer.check_scope(); - return m_option.check_validity(); -} - - - -void MultiSwitchProgramSession::run_program_instance(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - auto ScopeCheck = m_sanitizer.check_scope(); - { - std::lock_guard lg(program_lock()); - std::string error = check_validity(); - if (!error.empty()){ - throw UserSetupError(logger(), std::move(error)); - } - } - - // Startup Checks - size_t consoles = m_system.count(); - for (size_t c = 0; c < consoles; c++){ - m_option.instance().start_program_controller_check( - m_system[c].controller_session(), c - ); - m_option.instance().start_program_feedback_check( - env.consoles[c], c, - m_option.descriptor().feedback() - ); - m_option.instance().start_program_border_check( - env.consoles[c], c, - m_option.descriptor().feedback() - ); - } - - m_scope.store(&scope, std::memory_order_release); - - try{ - m_option.instance().program(env, scope); - for (size_t c = 0; c < consoles; c++){ - ControllerContext context(scope, env.consoles[c].controller()); - context.wait_for_all_requests(); - } - }catch (...){ - for (size_t c = 0; c < consoles; c++){ - try{ - env.consoles[c].controller().cancel_all_commands(); - }catch (...){} - } - m_scope.store(nullptr, std::memory_order_release); - throw; - } - m_scope.store(nullptr, std::memory_order_release); -} -void MultiSwitchProgramSession::internal_stop_program(){ - auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); -// size_t consoles = m_system.count(); -// for (size_t c = 0; c < consoles; c++){ -// m_system[c].serial_session().stop(); -// } - CancellableScope* scope = m_scope.load(std::memory_order_acquire); - if (scope != nullptr){ - scope->cancel(std::make_exception_ptr(ProgramCancelledException())); - } - - // Wait for program thread to finish. - while (m_scope.load(std::memory_order_acquire) != nullptr){ - pause(); - } - -// for (size_t c = 0; c < consoles; c++){ -// m_system[c].serial_session().reset(); -// } -} -void MultiSwitchProgramSession::internal_run_program(){ - auto ScopeCheck = m_sanitizer.check_scope(); - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - m_option.options().reset_state(); - - SleepSuppressScope sleep_scope(GlobalSettings::instance().SLEEP_SUPPRESS->PROGRAM_RUNNING); - - // Lock the system to prevent the # of Switches from changing. - std::lock_guard lg(m_system); - - ProgramInfo program_info( - identifier(), - m_option.descriptor().category(), - m_option.descriptor().display_name(), - timestamp() - ); - - size_t consoles = m_system.count(); - FixedLimitVector handles(consoles); - for (size_t c = 0; c < consoles; c++){ - SwitchSystemSession& session = m_system[c]; - if (!session.controller_session().ready()){ - report_error("Cannot Start: The controller is not ready."); - return; - } - AbstractController* controller = session.controller_session().controller(); - handles.emplace_back( - c, - session.logger(), - *controller, - session.video(), - session.overlay(), - session.audio(), - session.stream_history() - ); - - ConsoleState& state = handles.back().state(); - if (ConsoleSettings::instance().TRUST_USER_CONSOLE_SELECTION){ - state.set_console_type(handles.back().logger(), session.console_type()); - }else{ - state.set_console_type_user(session.console_type()); - } - } - - - - CancellableHolder scope; - MultiSwitchProgramEnvironment env( - program_info, - scope, - *this, - current_stats_tracker(), historical_stats_tracker(), - std::move(handles) - ); - - try{ - logger().log("Starting Program: " + identifier() + ""); - env.add_overlay_log_to_all_consoles("- Starting Program -"); - run_program_instance(env, scope); -// m_setup->wait_for_all_requests(); - env.add_overlay_log_to_all_consoles("- Program Finished -"); - logger().log("Program finished normally!", COLOR_BLUE); - }catch (OperationCancelledException&){ - env.add_overlay_log_to_all_consoles("- Program Stopped -"); - }catch (ProgramCancelledException&){ - env.add_overlay_log_to_all_consoles("- Program Stopped -"); - }catch (ProgramFinishedException& e){ - logger().log("Program finished early!", COLOR_BLUE); - env.add_overlay_log_to_all_consoles("- Program Finished -"); - e.send_notification(env, m_option.instance().NOTIFICATION_PROGRAM_FINISH); - }catch (InvalidConnectionStateException& e){ - logger().log("Program stopped due to connection issue.", COLOR_RED); - env.add_overlay_log_to_all_consoles("- Invalid Connection -", COLOR_RED); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - }catch (ScreenshotException& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.add_overlay_log_to_all_consoles("- Program Error -", COLOR_RED); - // If the exception doesn't already have console information, - // attach the 1st console here. - e.add_stream_if_needed(env.consoles[0]); - - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - e.send_notification(env, m_option.instance().NOTIFICATION_ERROR_FATAL); - }catch (Exception& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.add_overlay_log_to_all_consoles("- Program Error -", COLOR_RED); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - message - ); - }catch (std::exception& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.add_overlay_log_to_all_consoles("- Program Error -", COLOR_RED); - std::string message = e.what(); - if (message.empty()){ - message = "Unknown std::exception."; - } - report_error(message); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - message - ); - }catch (...){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.add_overlay_log_to_all_consoles("- Unknown Error -", COLOR_RED); - report_error("Unknown error."); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - "Unknown error." - ); - } -} - - -void MultiSwitchProgramSession::shutdown(){ - auto ScopeCheck = m_sanitizer.check_scope(); - internal_stop_program(); -} -void MultiSwitchProgramSession::startup(size_t switch_count){ - auto ScopeCheck = m_sanitizer.check_scope(); - WriteSpinLock lg(m_lock); - m_option.instance().update_active_consoles(switch_count); - for (Listener* listener : m_listeners){ - listener->redraw_options(); - } -} - - - - - - -} -} +/* Multi-Switch Program Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Options/Environment/SleepSuppressOption.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_MultiSwitchProgramOption.h" +#include "NintendoSwitch_MultiSwitchProgramSession.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void MultiSwitchProgramSession::add_listener(Listener& listener){ + auto ScopeCheck = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_listeners.insert(&listener); +} +void MultiSwitchProgramSession::remove_listener(Listener& listener){ + auto ScopeCheck = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_listeners.erase(&listener); +} + + + + +MultiSwitchProgramSession::MultiSwitchProgramSession(MultiSwitchProgramOption& option) + : ProgramSession(option.descriptor()) + , m_option(option) + , m_system(option.system(), instance_id()) + , m_scope(nullptr) + , m_sanitizer("MultiSwitchProgramSession") +{ +// WriteSpinLock lg(m_lock); + m_option.instance().update_active_consoles(option.system().count()); + m_system.add_listener(*this); +} + +MultiSwitchProgramSession::~MultiSwitchProgramSession(){ + MultiSwitchProgramSession::internal_stop_program(); + m_system.remove_listener(*this); + join_program_thread(); +} + + + +void MultiSwitchProgramSession::restore_defaults(){ + auto ScopeCheck = m_sanitizer.check_scope(); + std::lock_guard lg(program_lock()); + if (current_state() != ProgramState::STOPPED){ + logger().log("Cannot change settings while program is running.", COLOR_RED); + return; + } + logger().log("Restoring settings to defaults..."); + m_option.restore_defaults(); +} +std::string MultiSwitchProgramSession::check_validity() const{ + auto ScopeCheck = m_sanitizer.check_scope(); + return m_option.check_validity(); +} + + + +void MultiSwitchProgramSession::run_program_instance(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + auto ScopeCheck = m_sanitizer.check_scope(); + { + std::lock_guard lg(program_lock()); + std::string error = check_validity(); + if (!error.empty()){ + throw UserSetupError(logger(), std::move(error)); + } + } + + // Startup Checks + size_t consoles = m_system.count(); + for (size_t c = 0; c < consoles; c++){ + m_option.instance().start_program_controller_check( + m_system[c].controller_session(), c + ); + m_option.instance().start_program_feedback_check( + env.consoles[c], c, + m_option.descriptor().feedback() + ); + m_option.instance().start_program_border_check( + env.consoles[c], c, + m_option.descriptor().feedback() + ); + } + + m_scope.store(&scope, std::memory_order_release); + + try{ + m_option.instance().program(env, scope); + for (size_t c = 0; c < consoles; c++){ + ControllerContext context(scope, env.consoles[c].controller()); + context.wait_for_all_requests(); + } + }catch (...){ + for (size_t c = 0; c < consoles; c++){ + try{ + env.consoles[c].controller().cancel_all_commands(); + }catch (...){} + } + m_scope.store(nullptr, std::memory_order_release); + throw; + } + m_scope.store(nullptr, std::memory_order_release); +} +void MultiSwitchProgramSession::internal_stop_program(){ + auto ScopeCheck = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); +// size_t consoles = m_system.count(); +// for (size_t c = 0; c < consoles; c++){ +// m_system[c].serial_session().stop(); +// } + CancellableScope* scope = m_scope.load(std::memory_order_acquire); + if (scope != nullptr){ + scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + } + + // Wait for program thread to finish. + while (m_scope.load(std::memory_order_acquire) != nullptr){ + pause(); + } + +// for (size_t c = 0; c < consoles; c++){ +// m_system[c].serial_session().reset(); +// } +} +void MultiSwitchProgramSession::internal_run_program(){ + auto ScopeCheck = m_sanitizer.check_scope(); + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + m_option.options().reset_state(); + + SleepSuppressScope sleep_scope(GlobalSettings::instance().SLEEP_SUPPRESS->PROGRAM_RUNNING); + + // Lock the system to prevent the # of Switches from changing. + std::lock_guard lg(m_system); + + ProgramInfo program_info( + identifier(), + m_option.descriptor().category(), + m_option.descriptor().display_name(), + timestamp() + ); + + size_t consoles = m_system.count(); + FixedLimitVector handles(consoles); + for (size_t c = 0; c < consoles; c++){ + SwitchSystemSession& session = m_system[c]; + if (!session.controller_session().ready()){ + report_error("Cannot Start: The controller is not ready."); + return; + } + AbstractController* controller = session.controller_session().controller(); + handles.emplace_back( + c, + session.logger(), + *controller, + session.video(), + session.overlay(), + session.audio(), + session.stream_history() + ); + + ConsoleState& state = handles.back().state(); + if (ConsoleSettings::instance().TRUST_USER_CONSOLE_SELECTION){ + state.set_console_type(handles.back().logger(), session.console_type()); + }else{ + state.set_console_type_user(session.console_type()); + } + } + + + + CancellableHolder scope; + MultiSwitchProgramEnvironment env( + program_info, + scope, + *this, + current_stats_tracker(), historical_stats_tracker(), + std::move(handles) + ); + + try{ + logger().log("Starting Program: " + identifier() + ""); + env.add_overlay_log_to_all_consoles("- Starting Program -"); + run_program_instance(env, scope); +// m_setup->wait_for_all_requests(); + env.add_overlay_log_to_all_consoles("- Program Finished -"); + logger().log("Program finished normally!", COLOR_BLUE); + }catch (OperationCancelledException&){ + env.add_overlay_log_to_all_consoles("- Program Stopped -"); + }catch (ProgramCancelledException&){ + env.add_overlay_log_to_all_consoles("- Program Stopped -"); + }catch (ProgramFinishedException& e){ + logger().log("Program finished early!", COLOR_BLUE); + env.add_overlay_log_to_all_consoles("- Program Finished -"); + e.send_notification(env, m_option.instance().NOTIFICATION_PROGRAM_FINISH); + }catch (InvalidConnectionStateException& e){ + logger().log("Program stopped due to connection issue.", COLOR_RED); + env.add_overlay_log_to_all_consoles("- Invalid Connection -", COLOR_RED); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + }catch (ScreenshotException& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.add_overlay_log_to_all_consoles("- Program Error -", COLOR_RED); + // If the exception doesn't already have console information, + // attach the 1st console here. + e.add_stream_if_needed(env.consoles[0]); + + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + e.send_notification(env, m_option.instance().NOTIFICATION_ERROR_FATAL); + }catch (Exception& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.add_overlay_log_to_all_consoles("- Program Error -", COLOR_RED); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + message + ); + }catch (std::exception& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.add_overlay_log_to_all_consoles("- Program Error -", COLOR_RED); + std::string message = e.what(); + if (message.empty()){ + message = "Unknown std::exception."; + } + report_error(message); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + message + ); + }catch (...){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.add_overlay_log_to_all_consoles("- Unknown Error -", COLOR_RED); + report_error("Unknown error."); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + "Unknown error." + ); + } +} + + +void MultiSwitchProgramSession::shutdown(){ + auto ScopeCheck = m_sanitizer.check_scope(); + internal_stop_program(); +} +void MultiSwitchProgramSession::startup(size_t switch_count){ + auto ScopeCheck = m_sanitizer.check_scope(); + WriteSpinLock lg(m_lock); + m_option.instance().update_active_consoles(switch_count); + for (Listener* listener : m_listeners){ + listener->redraw_options(); + } +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h index 0110c71a27..e6dc4778fc 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h @@ -1,76 +1,76 @@ -/* Multi-Switch Program Session - * - * From: https://github.com/PokemonAutomation/ - * - * This class holds the run-time state of a Switch program. - * - * This class is fully thread-safe. You can call any functions from anywhere at - * anytime. - * - * Warning: Constructing this class requires an "option" parameter. It is not - * safe to modify this "option" parameter during the lifetime of this class. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgramSession_H -#define PokemonAutomation_NintendoSwitch_MultiSwitchProgramSession_H - -#include "CommonFramework/ProgramSession.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "NintendoSwitch_MultiSwitchSystemSession.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class MultiSwitchProgramOption; - - -class MultiSwitchProgramSession final : public ProgramSession, private MultiSwitchSystemSession::Listener{ -public: - // This is temporary. Remove once configs have push notifications. - struct Listener{ - virtual void redraw_options() = 0; - }; - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - -public: - virtual ~MultiSwitchProgramSession(); - MultiSwitchProgramSession(MultiSwitchProgramOption& option); - - void restore_defaults(); - -public: - MultiSwitchSystemSession& system(){ return m_system; } - -private: - virtual std::string check_validity() const override; - - virtual void internal_run_program() override; - virtual void internal_stop_program() override; - - virtual void shutdown() override; - virtual void startup(size_t switch_count) override; - -private: - void run_program_instance(MultiSwitchProgramEnvironment& env, CancellableScope& scope); - -private: - MultiSwitchProgramOption& m_option; - MultiSwitchSystemSession m_system; - - SpinLock m_lock; - std::atomic m_scope; - - std::set m_listeners; - - LifetimeSanitizer m_sanitizer; -}; - - - - - -} -} -#endif +/* Multi-Switch Program Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the run-time state of a Switch program. + * + * This class is fully thread-safe. You can call any functions from anywhere at + * anytime. + * + * Warning: Constructing this class requires an "option" parameter. It is not + * safe to modify this "option" parameter during the lifetime of this class. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgramSession_H +#define PokemonAutomation_NintendoSwitch_MultiSwitchProgramSession_H + +#include "CommonFramework/ProgramSession.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "NintendoSwitch_MultiSwitchSystemSession.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class MultiSwitchProgramOption; + + +class MultiSwitchProgramSession final : public ProgramSession, private MultiSwitchSystemSession::Listener{ +public: + // This is temporary. Remove once configs have push notifications. + struct Listener{ + virtual void redraw_options() = 0; + }; + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + +public: + virtual ~MultiSwitchProgramSession(); + MultiSwitchProgramSession(MultiSwitchProgramOption& option); + + void restore_defaults(); + +public: + MultiSwitchSystemSession& system(){ return m_system; } + +private: + virtual std::string check_validity() const override; + + virtual void internal_run_program() override; + virtual void internal_stop_program() override; + + virtual void shutdown() override; + virtual void startup(size_t switch_count) override; + +private: + void run_program_instance(MultiSwitchProgramEnvironment& env, CancellableScope& scope); + +private: + MultiSwitchProgramOption& m_option; + MultiSwitchSystemSession m_system; + + SpinLock m_lock; + std::atomic m_scope; + + std::set m_listeners; + + LifetimeSanitizer m_sanitizer; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.cpp index eb179f6954..3aacd9fea1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.cpp @@ -1,106 +1,106 @@ -/* Multi-Switch System Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "NintendoSwitch_MultiSwitchSystemOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -MultiSwitchSystemOption::MultiSwitchSystemOption( - const ControllerFeatures& required_features, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - size_t min_switches, - size_t max_switches, - size_t switches -) - : m_required_features(required_features) - , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) - , m_min_switches(std::max(min_switches, (size_t)1)) - , m_max_switches(std::min(max_switches, (size_t)MAX_SWITCHES)) - , m_active_switches(0) -{ - switches = std::max(switches, m_min_switches); - switches = std::min(switches, m_max_switches); - resize(switches); -} -MultiSwitchSystemOption::MultiSwitchSystemOption( - const ControllerFeatures& required_features, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - size_t min_switches, - size_t max_switches, - const JsonValue& json -) - : m_required_features(required_features) - , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) - , m_min_switches(std::max(min_switches, (size_t)1)) - , m_max_switches(std::min(max_switches, (size_t)MAX_SWITCHES)) - , m_active_switches(0) -{ - MultiSwitchSystemOption::load_json(json); - if (m_switches.size() < m_min_switches){ - resize(m_min_switches); - } -} -void MultiSwitchSystemOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - const JsonArray* array = obj->get_array("DeviceList"); - if (array != nullptr && !array->empty() && array->size() <= MAX_SWITCHES){ - m_switches.clear(); - size_t items = array->size(); - for (size_t c = 0; c < items; c++){ - m_switches.emplace_back( - new SwitchSystemOption( - m_required_features, - m_allow_commands_while_running, - (*array)[c] - ) - ); - } - } - obj->read_integer(m_active_switches, "ActiveDevices", m_min_switches, m_max_switches); -} -JsonValue MultiSwitchSystemOption::to_json() const{ - JsonObject obj; - obj["ActiveDevices"] = m_active_switches; - JsonArray array; - for (const auto& item : m_switches){ - array.push_back(item->to_json()); - } - obj["DeviceList"] = std::move(array); - return obj; -} -void MultiSwitchSystemOption::resize(size_t count){ - while (m_switches.size() < count){ - m_switches.emplace_back( - new SwitchSystemOption( - m_required_features, - m_allow_commands_while_running - ) - ); - } - m_active_switches = count; -} - - - - - -} -} - - - - - +/* Multi-Switch System Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "NintendoSwitch_MultiSwitchSystemOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +MultiSwitchSystemOption::MultiSwitchSystemOption( + const ControllerFeatures& required_features, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + size_t min_switches, + size_t max_switches, + size_t switches +) + : m_required_features(required_features) + , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) + , m_min_switches(std::max(min_switches, (size_t)1)) + , m_max_switches(std::min(max_switches, (size_t)MAX_SWITCHES)) + , m_active_switches(0) +{ + switches = std::max(switches, m_min_switches); + switches = std::min(switches, m_max_switches); + resize(switches); +} +MultiSwitchSystemOption::MultiSwitchSystemOption( + const ControllerFeatures& required_features, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + size_t min_switches, + size_t max_switches, + const JsonValue& json +) + : m_required_features(required_features) + , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) + , m_min_switches(std::max(min_switches, (size_t)1)) + , m_max_switches(std::min(max_switches, (size_t)MAX_SWITCHES)) + , m_active_switches(0) +{ + MultiSwitchSystemOption::load_json(json); + if (m_switches.size() < m_min_switches){ + resize(m_min_switches); + } +} +void MultiSwitchSystemOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + const JsonArray* array = obj->get_array("DeviceList"); + if (array != nullptr && !array->empty() && array->size() <= MAX_SWITCHES){ + m_switches.clear(); + size_t items = array->size(); + for (size_t c = 0; c < items; c++){ + m_switches.emplace_back( + new SwitchSystemOption( + m_required_features, + m_allow_commands_while_running, + (*array)[c] + ) + ); + } + } + obj->read_integer(m_active_switches, "ActiveDevices", m_min_switches, m_max_switches); +} +JsonValue MultiSwitchSystemOption::to_json() const{ + JsonObject obj; + obj["ActiveDevices"] = m_active_switches; + JsonArray array; + for (const auto& item : m_switches){ + array.push_back(item->to_json()); + } + obj["DeviceList"] = std::move(array); + return obj; +} +void MultiSwitchSystemOption::resize(size_t count){ + while (m_switches.size() < count){ + m_switches.emplace_back( + new SwitchSystemOption( + m_required_features, + m_allow_commands_while_running + ) + ); + } + m_active_switches = count; +} + + + + + +} +} + + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h index 01711f8f66..4b769e4551 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h @@ -1,79 +1,79 @@ -/* Multi-Switch System Option - * - * From: https://github.com/PokemonAutomation/ - * - * This class represents the serializable state of a set of Switch. - * consoles. Specifically, it holds a SwitchSystemOption for each of the - * consoles it represents. - * - * This class maintains no runtime state or UI and is not thread-safe. - * - */ - -#ifndef PokemonAutomationn_NintendoSwitch_MultiSwitchSystemOption_H -#define PokemonAutomationn_NintendoSwitch_MultiSwitchSystemOption_H - -#include -#include -#include "CommonFramework/Globals.h" -#include "CommonFramework/Panels/ProgramDescriptor.h" -#include "NintendoSwitch_SwitchSystemOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class MultiSwitchSystemWidget; - -class MultiSwitchSystemOption{ -public: - static const size_t MAX_SWITCHES = 4; - -public: - MultiSwitchSystemOption( - const ControllerFeatures& required_features, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - size_t min_switches, - size_t max_switches, - size_t switches - ); - MultiSwitchSystemOption( - const ControllerFeatures& required_features, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - size_t min_switches, - size_t max_switches, - const JsonValue& json - ); - void load_json(const JsonValue& json); - JsonValue to_json() const; - - void resize(size_t count); - -public: - size_t min_switches() const{ return m_min_switches; } - size_t max_switches() const{ return m_max_switches; } - - size_t count() const{ return m_active_switches; } - SwitchSystemOption& operator[](size_t index){ return *m_switches[index]; } - - -private: - friend class MultiSwitchSystemWidget; - - const ControllerFeatures& m_required_features; - const bool m_allow_commands_while_running; - - const size_t m_min_switches; - const size_t m_max_switches; - size_t m_active_switches; - std::vector> m_switches; -}; - - - - -} -} -#endif +/* Multi-Switch System Option + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents the serializable state of a set of Switch. + * consoles. Specifically, it holds a SwitchSystemOption for each of the + * consoles it represents. + * + * This class maintains no runtime state or UI and is not thread-safe. + * + */ + +#ifndef PokemonAutomationn_NintendoSwitch_MultiSwitchSystemOption_H +#define PokemonAutomationn_NintendoSwitch_MultiSwitchSystemOption_H + +#include +#include +#include "CommonFramework/Globals.h" +#include "CommonFramework/Panels/ProgramDescriptor.h" +#include "NintendoSwitch_SwitchSystemOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class MultiSwitchSystemWidget; + +class MultiSwitchSystemOption{ +public: + static const size_t MAX_SWITCHES = 4; + +public: + MultiSwitchSystemOption( + const ControllerFeatures& required_features, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + size_t min_switches, + size_t max_switches, + size_t switches + ); + MultiSwitchSystemOption( + const ControllerFeatures& required_features, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + size_t min_switches, + size_t max_switches, + const JsonValue& json + ); + void load_json(const JsonValue& json); + JsonValue to_json() const; + + void resize(size_t count); + +public: + size_t min_switches() const{ return m_min_switches; } + size_t max_switches() const{ return m_max_switches; } + + size_t count() const{ return m_active_switches; } + SwitchSystemOption& operator[](size_t index){ return *m_switches[index]; } + + +private: + friend class MultiSwitchSystemWidget; + + const ControllerFeatures& m_required_features; + const bool m_allow_commands_while_running; + + const size_t m_min_switches; + const size_t m_max_switches; + size_t m_active_switches; + std::vector> m_switches; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.cpp index a7dd454229..29ec96f47c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.cpp @@ -1,76 +1,76 @@ -/* Multi-Switch System Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "NintendoSwitch_MultiSwitchSystemSession.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void MultiSwitchSystemSession::add_listener(Listener& listener){ - std::lock_guard lg(m_lock); - m_listeners.insert(&listener); - listener.startup(m_consoles.size()); -} -void MultiSwitchSystemSession::remove_listener(Listener& listener){ - std::lock_guard lg(m_lock); - m_listeners.erase(&listener); -} - - -MultiSwitchSystemSession::~MultiSwitchSystemSession() = default; -MultiSwitchSystemSession::MultiSwitchSystemSession( - MultiSwitchSystemOption& option, - uint64_t program_id -) - : m_option(option) - , m_program_id(program_id) - , m_switch_count_locked(false) - , m_consoles(option.count()) -{ - size_t count = option.count(); - for (size_t c = 0; c < count; c++){ - m_consoles.emplace_back(option[c], program_id, c); - } -} - -void MultiSwitchSystemSession::lock(){ - std::lock_guard lg(m_lock); - m_switch_count_locked = true; -} -void MultiSwitchSystemSession::unlock(){ - std::lock_guard lg(m_lock); - m_switch_count_locked = false; -} -bool MultiSwitchSystemSession::set_switch_count(size_t count){ - std::lock_guard lg(m_lock); - if (m_switch_count_locked){ - return false; - } - - for (Listener* listener : m_listeners){ - listener->shutdown(); - } - m_consoles.reset(count); - m_option.resize(count); - for (size_t c = 0; c < count; c++){ - m_consoles.emplace_back(m_option[c], m_program_id, c); - } - for (Listener* listener : m_listeners){ - listener->startup(count); - } - - return true; -} - - - - - -} -} +/* Multi-Switch System Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "NintendoSwitch_MultiSwitchSystemSession.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void MultiSwitchSystemSession::add_listener(Listener& listener){ + std::lock_guard lg(m_lock); + m_listeners.insert(&listener); + listener.startup(m_consoles.size()); +} +void MultiSwitchSystemSession::remove_listener(Listener& listener){ + std::lock_guard lg(m_lock); + m_listeners.erase(&listener); +} + + +MultiSwitchSystemSession::~MultiSwitchSystemSession() = default; +MultiSwitchSystemSession::MultiSwitchSystemSession( + MultiSwitchSystemOption& option, + uint64_t program_id +) + : m_option(option) + , m_program_id(program_id) + , m_switch_count_locked(false) + , m_consoles(option.count()) +{ + size_t count = option.count(); + for (size_t c = 0; c < count; c++){ + m_consoles.emplace_back(option[c], program_id, c); + } +} + +void MultiSwitchSystemSession::lock(){ + std::lock_guard lg(m_lock); + m_switch_count_locked = true; +} +void MultiSwitchSystemSession::unlock(){ + std::lock_guard lg(m_lock); + m_switch_count_locked = false; +} +bool MultiSwitchSystemSession::set_switch_count(size_t count){ + std::lock_guard lg(m_lock); + if (m_switch_count_locked){ + return false; + } + + for (Listener* listener : m_listeners){ + listener->shutdown(); + } + m_consoles.reset(count); + m_option.resize(count); + for (size_t c = 0; c < count; c++){ + m_consoles.emplace_back(m_option[c], m_program_id, c); + } + for (Listener* listener : m_listeners){ + listener->startup(count); + } + + return true; +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h index 89a7b2b1b1..c584c450ff 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h @@ -1,81 +1,81 @@ -/* Multi-Switch System Session - * - * From: https://github.com/PokemonAutomation/ - * - * This class holds the run-time state for multiple Switch systems. - * - * This class is fully thread-safe. You can call any functions from anywhere at - * anytime. - * - * Warning: Constructing this class requires an "option" parameter. It is not - * safe to modify this "option" parameter during the lifetime of this class. - * - */ - -#ifndef PokemonAutomationn_NintendoSwitch_MultiSwitchSystemSession_H -#define PokemonAutomationn_NintendoSwitch_MultiSwitchSystemSession_H - -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "NintendoSwitch_SwitchSystemSession.h" -#include "NintendoSwitch_MultiSwitchSystemOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class MultiSwitchSystemSession{ -public: - struct Listener{ - // Sent before the Switch sessions are destroyed. Listeners should - // their references to them before returning. - virtual void shutdown() = 0; - - // Sent after new Switches are started up. - // This is called immediately when attaching a listener to give the - // current switch count. The listener must drop all references to the - // switch sessions before detaching. - virtual void startup(size_t switch_count) = 0; - }; - void add_listener(Listener& listener); - void remove_listener(Listener& listener); - - -public: - ~MultiSwitchSystemSession(); - MultiSwitchSystemSession( - MultiSwitchSystemOption& option, - uint64_t program_id - ); - - // Lock/unlock the Switch count. - void lock(); - void unlock(); - - // Returns true only on success. - bool set_switch_count(size_t count); - - size_t min_switches() const{ return m_option.min_switches(); } - size_t max_switches() const{ return m_option.max_switches(); } - -public: - // Note that these are not thread-safe with changing the # of switches. - size_t count() const{ return m_consoles.size(); } - SwitchSystemSession& operator[](size_t index){ return m_consoles[index]; } - - -private: - MultiSwitchSystemOption& m_option; - const uint64_t m_program_id; - - std::mutex m_lock; - bool m_switch_count_locked; - FixedLimitVector m_consoles; - std::set m_listeners; -}; - - - - -} -} -#endif +/* Multi-Switch System Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the run-time state for multiple Switch systems. + * + * This class is fully thread-safe. You can call any functions from anywhere at + * anytime. + * + * Warning: Constructing this class requires an "option" parameter. It is not + * safe to modify this "option" parameter during the lifetime of this class. + * + */ + +#ifndef PokemonAutomationn_NintendoSwitch_MultiSwitchSystemSession_H +#define PokemonAutomationn_NintendoSwitch_MultiSwitchSystemSession_H + +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "NintendoSwitch_SwitchSystemSession.h" +#include "NintendoSwitch_MultiSwitchSystemOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class MultiSwitchSystemSession{ +public: + struct Listener{ + // Sent before the Switch sessions are destroyed. Listeners should + // their references to them before returning. + virtual void shutdown() = 0; + + // Sent after new Switches are started up. + // This is called immediately when attaching a listener to give the + // current switch count. The listener must drop all references to the + // switch sessions before detaching. + virtual void startup(size_t switch_count) = 0; + }; + void add_listener(Listener& listener); + void remove_listener(Listener& listener); + + +public: + ~MultiSwitchSystemSession(); + MultiSwitchSystemSession( + MultiSwitchSystemOption& option, + uint64_t program_id + ); + + // Lock/unlock the Switch count. + void lock(); + void unlock(); + + // Returns true only on success. + bool set_switch_count(size_t count); + + size_t min_switches() const{ return m_option.min_switches(); } + size_t max_switches() const{ return m_option.max_switches(); } + +public: + // Note that these are not thread-safe with changing the # of switches. + size_t count() const{ return m_consoles.size(); } + SwitchSystemSession& operator[](size_t index){ return m_consoles[index]; } + + +private: + MultiSwitchSystemOption& m_option; + const uint64_t m_program_id; + + std::mutex m_lock; + bool m_switch_count_locked; + FixedLimitVector m_consoles; + std::set m_listeners; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.cpp index bf3006a4dc..b8b005c19d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.cpp @@ -1,65 +1,65 @@ -/* Single Switch Program Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "NintendoSwitch_SingleSwitchProgramOption.h" -#include "UI/NintendoSwitch_SingleSwitchProgramWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -SingleSwitchProgramOption::~SingleSwitchProgramOption() = default; -SingleSwitchProgramOption::SingleSwitchProgramOption(const SingleSwitchProgramDescriptor& descriptor) - : PanelInstance(descriptor) - , m_descriptor(descriptor) - , m_system( - descriptor.required_features(), - descriptor.allow_commands_while_running() - ) - , m_instance(descriptor.make_instance()) -{} - -void SingleSwitchProgramOption::from_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - const JsonValue* value = obj->get_value("SwitchSetup"); - if (value){ - m_system.load_json(*value); - } - m_instance->from_json(json); -} -JsonValue SingleSwitchProgramOption::to_json() const{ - JsonObject obj = std::move(*m_instance->to_json().to_object()); - obj["SwitchSetup"] = m_system.to_json(); - return obj; -} - -ConfigOption& SingleSwitchProgramOption::options(){ - return m_instance->m_options; -} - -std::string SingleSwitchProgramOption::check_validity() const{ - return m_instance->check_validity(); -} -void SingleSwitchProgramOption::restore_defaults(){ - m_instance->restore_defaults(); -} - - -QWidget* SingleSwitchProgramOption::make_widget(QWidget& parent, PanelHolder& holder){ - return new SingleSwitchProgramWidget2(parent, *this, holder); -} - - - - - -} -} +/* Single Switch Program Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "NintendoSwitch_SingleSwitchProgramOption.h" +#include "UI/NintendoSwitch_SingleSwitchProgramWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +SingleSwitchProgramOption::~SingleSwitchProgramOption() = default; +SingleSwitchProgramOption::SingleSwitchProgramOption(const SingleSwitchProgramDescriptor& descriptor) + : PanelInstance(descriptor) + , m_descriptor(descriptor) + , m_system( + descriptor.required_features(), + descriptor.allow_commands_while_running() + ) + , m_instance(descriptor.make_instance()) +{} + +void SingleSwitchProgramOption::from_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + const JsonValue* value = obj->get_value("SwitchSetup"); + if (value){ + m_system.load_json(*value); + } + m_instance->from_json(json); +} +JsonValue SingleSwitchProgramOption::to_json() const{ + JsonObject obj = std::move(*m_instance->to_json().to_object()); + obj["SwitchSetup"] = m_system.to_json(); + return obj; +} + +ConfigOption& SingleSwitchProgramOption::options(){ + return m_instance->m_options; +} + +std::string SingleSwitchProgramOption::check_validity() const{ + return m_instance->check_validity(); +} +void SingleSwitchProgramOption::restore_defaults(){ + m_instance->restore_defaults(); +} + + +QWidget* SingleSwitchProgramOption::make_widget(QWidget& parent, PanelHolder& holder){ + return new SingleSwitchProgramWidget2(parent, *this, holder); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h index d273ea2fa4..458a5bfc30 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h @@ -1,63 +1,63 @@ -/* Single Switch Program Option - * - * From: https://github.com/PokemonAutomation/ - * - * This class represents the serializable state of a Switch program. - * This class maintains no UI and is not thread-safe. - * - * Note that this class does own the "SingleSwitchProgramInstance", object - * which is controlled by the individual program itself. There the running - * program can do whatever it wants - including keeping run-time state. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramOption_H -#define PokemonAutomation_NintendoSwitch_SingleSwitchProgramOption_H - -#include "CommonFramework/Panels/PanelInstance.h" -#include "NintendoSwitch_SwitchSystemOption.h" - -namespace PokemonAutomation{ - class ConfigOption; -namespace NintendoSwitch{ - -class SingleSwitchProgramDescriptor; -class SingleSwitchProgramInstance; - - -class SingleSwitchProgramOption final : public PanelInstance{ -public: - ~SingleSwitchProgramOption(); - SingleSwitchProgramOption(const SingleSwitchProgramDescriptor& descriptor); - - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - const SingleSwitchProgramDescriptor& descriptor() const{ return m_descriptor; } - SwitchSystemOption& system(){ return m_system; } - SingleSwitchProgramInstance& instance(){ return *m_instance; } - ConfigOption& options(); - - std::string check_validity() const; - void restore_defaults(); - -private: - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -private: - const SingleSwitchProgramDescriptor& m_descriptor; - SwitchSystemOption m_system; - std::unique_ptr m_instance; -}; - - - - - - - - -} -} -#endif +/* Single Switch Program Option + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents the serializable state of a Switch program. + * This class maintains no UI and is not thread-safe. + * + * Note that this class does own the "SingleSwitchProgramInstance", object + * which is controlled by the individual program itself. There the running + * program can do whatever it wants - including keeping run-time state. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramOption_H +#define PokemonAutomation_NintendoSwitch_SingleSwitchProgramOption_H + +#include "CommonFramework/Panels/PanelInstance.h" +#include "NintendoSwitch_SwitchSystemOption.h" + +namespace PokemonAutomation{ + class ConfigOption; +namespace NintendoSwitch{ + +class SingleSwitchProgramDescriptor; +class SingleSwitchProgramInstance; + + +class SingleSwitchProgramOption final : public PanelInstance{ +public: + ~SingleSwitchProgramOption(); + SingleSwitchProgramOption(const SingleSwitchProgramDescriptor& descriptor); + + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + const SingleSwitchProgramDescriptor& descriptor() const{ return m_descriptor; } + SwitchSystemOption& system(){ return m_system; } + SingleSwitchProgramInstance& instance(){ return *m_instance; } + ConfigOption& options(); + + std::string check_validity() const; + void restore_defaults(); + +private: + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +private: + const SingleSwitchProgramDescriptor& m_descriptor; + SwitchSystemOption m_system; + std::unique_ptr m_instance; +}; + + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp index 2803426aee..08a92a17a2 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.cpp @@ -1,229 +1,229 @@ -/* Single Switch Program Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/SpinPause.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Options/Environment/SleepSuppressOption.h" -#include "CommonFramework/Options/Environment/PerformanceOptions.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_SingleSwitchProgramOption.h" -#include "NintendoSwitch_SingleSwitchProgramSession.h" - -#define PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS - -//#include -//using std::cout; -//using std::endl; - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SingleSwitchProgramSession::SingleSwitchProgramSession(SingleSwitchProgramOption& option, size_t console_number) - : ProgramSession(option.descriptor()) - , m_option(option) - , m_system(option.system(), instance_id(), console_number) - , m_scope(nullptr) -{} - -SingleSwitchProgramSession::~SingleSwitchProgramSession(){ - SingleSwitchProgramSession::internal_stop_program(); - join_program_thread(); -} - - -void SingleSwitchProgramSession::restore_defaults(){ - std::lock_guard lg(program_lock()); - if (current_state() != ProgramState::STOPPED){ - logger().log("Cannot change settings while program is running.", COLOR_RED); - return; - } - logger().log("Restoring settings to defaults..."); - m_option.restore_defaults(); -} -std::string SingleSwitchProgramSession::check_validity() const{ - return m_option.check_validity(); -} - - - -void SingleSwitchProgramSession::run_program_instance(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - { - std::lock_guard lg(program_lock()); - std::string error = check_validity(); - if (!error.empty()){ - throw UserSetupError(logger(), std::move(error)); - } - } - - // Startup Checks - m_option.instance().start_program_controller_check( - m_system.controller_session() - ); - m_option.instance().start_program_feedback_check( - env.console, - m_option.descriptor().feedback() - ); - m_option.instance().start_program_border_check( - env.console, - m_option.descriptor().feedback() - ); - - ControllerContext context(scope, env.console.controller()); - m_scope.store(&context, std::memory_order_release); - -#ifdef PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS - try{ - m_option.instance().program(env, context); - context.wait_for_all_requests(); - }catch (...){ - try{ - env.console.controller().cancel_all_commands(); - }catch (...){} - m_scope.store(nullptr, std::memory_order_release); - throw; - } -#else - { - m_option.instance().program(env, scope); - env.console.controller().wait_for_all(&scope); - } -#endif - m_scope.store(nullptr, std::memory_order_release); -} -void SingleSwitchProgramSession::internal_stop_program(){ - WriteSpinLock lg(m_lock); - - CancellableScope* scope = m_scope.load(std::memory_order_acquire); - if (scope != nullptr){ - scope->cancel(std::make_exception_ptr(ProgramCancelledException())); - } - - // Wait for program thread to finish. - while (m_scope.load(std::memory_order_acquire) != nullptr){ - pause(); - } -} -void SingleSwitchProgramSession::internal_run_program(){ - GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); - m_option.options().reset_state(); - - if (!m_system.controller_session().ready()){ - report_error("Cannot Start: The controller is not ready."); - return; - } - - SleepSuppressScope sleep_scope(GlobalSettings::instance().SLEEP_SUPPRESS->PROGRAM_RUNNING); - - ProgramInfo program_info( - identifier(), - m_option.descriptor().category(), - m_option.descriptor().display_name(), - timestamp() - ); - AbstractController* controller = m_system.controller_session().controller(); - ControllerContext context(*controller); - SingleSwitchProgramEnvironment env( - program_info, - context, - *this, - current_stats_tracker(), historical_stats_tracker(), - m_system.logger(), - *controller, - m_system.video(), - m_system.overlay(), - m_system.audio(), - m_system.stream_history() - ); - - if (ConsoleSettings::instance().TRUST_USER_CONSOLE_SELECTION){ - env.console.state().set_console_type(m_system.logger(), m_system.console_type()); - }else{ - env.console.state().set_console_type_user(m_system.console_type()); - } - - - try{ - logger().log("Starting Program: " + identifier() + ""); - env.console.overlay().clear_log(); - env.console.overlay().add_log("- Starting Program -"); - run_program_instance(env, context); - env.console.overlay().add_log("- Program Finished -"); - logger().log("Program finished normally!", COLOR_BLUE); - }catch (OperationCancelledException&){ - env.console.overlay().add_log("- Program Stopped -"); - }catch (ProgramCancelledException&){ - env.console.overlay().add_log("- Program Stopped -"); - }catch (ProgramFinishedException& e){ - logger().log("Program finished early!", COLOR_BLUE); - env.console.overlay().add_log("- Program Finished -"); - e.send_notification(env, m_option.instance().NOTIFICATION_PROGRAM_FINISH); - }catch (InvalidConnectionStateException& e){ - logger().log("Program stopped due to connection issue.", COLOR_RED); - env.console.overlay().add_log("- Invalid Connection -", COLOR_RED); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - }catch (ScreenshotException& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.console.overlay().add_log("- Program Error -", COLOR_RED); - e.add_stream_if_needed(env.console); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - e.send_notification(env, m_option.instance().NOTIFICATION_ERROR_FATAL); - }catch (Exception& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.console.overlay().add_log("- Program Error -", COLOR_RED); - std::string message = e.message(); - if (message.empty()){ - message = e.name(); - } - report_error(message); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - message - ); - } -#ifdef PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS - catch (std::exception& e){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.console.overlay().add_log("- Program Error -", COLOR_RED); - std::string message = e.what(); - if (message.empty()){ - message = "Unknown std::exception."; - } - report_error(message); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - message - ); - }catch (...){ - logger().log("Program stopped with an exception!", COLOR_RED); - env.console.overlay().add_log("- Unknown Error -", COLOR_RED); - report_error("Unknown error."); - send_program_fatal_error_notification( - env, m_option.instance().NOTIFICATION_ERROR_FATAL, - "Unknown error." - ); - } -#endif -} - - - -} -} +/* Single Switch Program Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/SpinPause.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Options/Environment/SleepSuppressOption.h" +#include "CommonFramework/Options/Environment/PerformanceOptions.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_SingleSwitchProgramOption.h" +#include "NintendoSwitch_SingleSwitchProgramSession.h" + +#define PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS + +//#include +//using std::cout; +//using std::endl; + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SingleSwitchProgramSession::SingleSwitchProgramSession(SingleSwitchProgramOption& option, size_t console_number) + : ProgramSession(option.descriptor()) + , m_option(option) + , m_system(option.system(), instance_id(), console_number) + , m_scope(nullptr) +{} + +SingleSwitchProgramSession::~SingleSwitchProgramSession(){ + SingleSwitchProgramSession::internal_stop_program(); + join_program_thread(); +} + + +void SingleSwitchProgramSession::restore_defaults(){ + std::lock_guard lg(program_lock()); + if (current_state() != ProgramState::STOPPED){ + logger().log("Cannot change settings while program is running.", COLOR_RED); + return; + } + logger().log("Restoring settings to defaults..."); + m_option.restore_defaults(); +} +std::string SingleSwitchProgramSession::check_validity() const{ + return m_option.check_validity(); +} + + + +void SingleSwitchProgramSession::run_program_instance(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + { + std::lock_guard lg(program_lock()); + std::string error = check_validity(); + if (!error.empty()){ + throw UserSetupError(logger(), std::move(error)); + } + } + + // Startup Checks + m_option.instance().start_program_controller_check( + m_system.controller_session() + ); + m_option.instance().start_program_feedback_check( + env.console, + m_option.descriptor().feedback() + ); + m_option.instance().start_program_border_check( + env.console, + m_option.descriptor().feedback() + ); + + ControllerContext context(scope, env.console.controller()); + m_scope.store(&context, std::memory_order_release); + +#ifdef PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS + try{ + m_option.instance().program(env, context); + context.wait_for_all_requests(); + }catch (...){ + try{ + env.console.controller().cancel_all_commands(); + }catch (...){} + m_scope.store(nullptr, std::memory_order_release); + throw; + } +#else + { + m_option.instance().program(env, scope); + env.console.controller().wait_for_all(&scope); + } +#endif + m_scope.store(nullptr, std::memory_order_release); +} +void SingleSwitchProgramSession::internal_stop_program(){ + WriteSpinLock lg(m_lock); + + CancellableScope* scope = m_scope.load(std::memory_order_acquire); + if (scope != nullptr){ + scope->cancel(std::make_exception_ptr(ProgramCancelledException())); + } + + // Wait for program thread to finish. + while (m_scope.load(std::memory_order_acquire) != nullptr){ + pause(); + } +} +void SingleSwitchProgramSession::internal_run_program(){ + GlobalSettings::instance().PERFORMANCE->REALTIME_THREAD_PRIORITY.set_on_this_thread(); + m_option.options().reset_state(); + + if (!m_system.controller_session().ready()){ + report_error("Cannot Start: The controller is not ready."); + return; + } + + SleepSuppressScope sleep_scope(GlobalSettings::instance().SLEEP_SUPPRESS->PROGRAM_RUNNING); + + ProgramInfo program_info( + identifier(), + m_option.descriptor().category(), + m_option.descriptor().display_name(), + timestamp() + ); + AbstractController* controller = m_system.controller_session().controller(); + ControllerContext context(*controller); + SingleSwitchProgramEnvironment env( + program_info, + context, + *this, + current_stats_tracker(), historical_stats_tracker(), + m_system.logger(), + *controller, + m_system.video(), + m_system.overlay(), + m_system.audio(), + m_system.stream_history() + ); + + if (ConsoleSettings::instance().TRUST_USER_CONSOLE_SELECTION){ + env.console.state().set_console_type(m_system.logger(), m_system.console_type()); + }else{ + env.console.state().set_console_type_user(m_system.console_type()); + } + + + try{ + logger().log("Starting Program: " + identifier() + ""); + env.console.overlay().clear_log(); + env.console.overlay().add_log("- Starting Program -"); + run_program_instance(env, context); + env.console.overlay().add_log("- Program Finished -"); + logger().log("Program finished normally!", COLOR_BLUE); + }catch (OperationCancelledException&){ + env.console.overlay().add_log("- Program Stopped -"); + }catch (ProgramCancelledException&){ + env.console.overlay().add_log("- Program Stopped -"); + }catch (ProgramFinishedException& e){ + logger().log("Program finished early!", COLOR_BLUE); + env.console.overlay().add_log("- Program Finished -"); + e.send_notification(env, m_option.instance().NOTIFICATION_PROGRAM_FINISH); + }catch (InvalidConnectionStateException& e){ + logger().log("Program stopped due to connection issue.", COLOR_RED); + env.console.overlay().add_log("- Invalid Connection -", COLOR_RED); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + }catch (ScreenshotException& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.console.overlay().add_log("- Program Error -", COLOR_RED); + e.add_stream_if_needed(env.console); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + e.send_notification(env, m_option.instance().NOTIFICATION_ERROR_FATAL); + }catch (Exception& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.console.overlay().add_log("- Program Error -", COLOR_RED); + std::string message = e.message(); + if (message.empty()){ + message = e.name(); + } + report_error(message); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + message + ); + } +#ifdef PA_CATCH_PROGRAM_SYSTEM_EXCEPTIONS + catch (std::exception& e){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.console.overlay().add_log("- Program Error -", COLOR_RED); + std::string message = e.what(); + if (message.empty()){ + message = "Unknown std::exception."; + } + report_error(message); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + message + ); + }catch (...){ + logger().log("Program stopped with an exception!", COLOR_RED); + env.console.overlay().add_log("- Unknown Error -", COLOR_RED); + report_error("Unknown error."); + send_program_fatal_error_notification( + env, m_option.instance().NOTIFICATION_ERROR_FATAL, + "Unknown error." + ); + } +#endif +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h index 4545b0026b..07c08f786b 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h @@ -1,62 +1,62 @@ -/* Single Switch Program Session - * - * From: https://github.com/PokemonAutomation/ - * - * This class holds the run-time state of a Switch program. - * - * This class is fully thread-safe. You can call any functions from anywhere at - * anytime. - * - * Warning: Constructing this class requires an "option" parameter. It is not - * safe to modify this "option" parameter during the lifetime of this class. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramSession_H -#define PokemonAutomation_NintendoSwitch_SingleSwitchProgramSession_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/ProgramSession.h" -#include "NintendoSwitch_SwitchSystemSession.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class SingleSwitchProgramOption; - - -class SingleSwitchProgramSession final : public ProgramSession{ -public: - virtual ~SingleSwitchProgramSession(); - SingleSwitchProgramSession(SingleSwitchProgramOption& option, size_t console_number); - - void restore_defaults(); - -public: - SwitchSystemSession& system(){ return m_system; } - -private: - virtual std::string check_validity() const override; - - virtual void internal_run_program() override; - virtual void internal_stop_program() override; - - -private: - void run_program_instance(SingleSwitchProgramEnvironment& env, CancellableScope& scope); - -private: - SingleSwitchProgramOption& m_option; - SwitchSystemSession m_system; - - SpinLock m_lock; - std::atomic m_scope; -}; - - - - -} -} -#endif +/* Single Switch Program Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the run-time state of a Switch program. + * + * This class is fully thread-safe. You can call any functions from anywhere at + * anytime. + * + * Warning: Constructing this class requires an "option" parameter. It is not + * safe to modify this "option" parameter during the lifetime of this class. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramSession_H +#define PokemonAutomation_NintendoSwitch_SingleSwitchProgramSession_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/ProgramSession.h" +#include "NintendoSwitch_SwitchSystemSession.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class SingleSwitchProgramOption; + + +class SingleSwitchProgramSession final : public ProgramSession{ +public: + virtual ~SingleSwitchProgramSession(); + SingleSwitchProgramSession(SingleSwitchProgramOption& option, size_t console_number); + + void restore_defaults(); + +public: + SwitchSystemSession& system(){ return m_system; } + +private: + virtual std::string check_validity() const override; + + virtual void internal_run_program() override; + virtual void internal_stop_program() override; + + +private: + void run_program_instance(SingleSwitchProgramEnvironment& env, CancellableScope& scope); + +private: + SingleSwitchProgramOption& m_option; + SwitchSystemSession m_system; + + SpinLock m_lock; + std::atomic m_scope; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.cpp index 7e35a8aa4c..3671d65cf1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.cpp @@ -1,132 +1,132 @@ -/* Switch System - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_SwitchSystemOption.h" -//#include "UI/NintendoSwitch_SwitchSystemWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -// constexpr Color COLOR_GREEN2(0xff00aa00); - -#if 0 -Color pick_color(FeedbackType feedback){ - switch (feedback){ - case FeedbackType::NONE: - return COLOR_BLUE; - case FeedbackType::OPTIONAL_: - return COLOR_PURPLE; - case FeedbackType::REQUIRED: - return COLOR_DARKGREEN; - case FeedbackType::VIDEO_AUDIO: - return COLOR_RED; - } - return Color(); -} -#endif -Color pick_color( - const ControllerFeatures& required_features, - FasterIfTickPrecise faster_if_tick_precise -){ - if (required_features.contains(ControllerFeature::NintendoSwitch_DateSkip)){ - return COLOR_RED; - } - if (required_features.contains(ControllerFeature::NintendoSwitch_LeftJoycon) || - required_features.contains(ControllerFeature::NintendoSwitch_RightJoycon) - ){ - return COLOR_MAGENTA; - } - if (required_features.contains(ControllerFeature::TickPrecise)){ - return COLOR_PURPLE; - } - switch (faster_if_tick_precise){ - case FasterIfTickPrecise::MUCH_FASTER: - case FasterIfTickPrecise::FASTER: - return COLOR_DARKGREEN; - case FasterIfTickPrecise::NOT_FASTER: - return COLOR_BLUE; - } - - return COLOR_BLUE; -} - - -const std::string SwitchSystemOption::JSON_CONTROLLER = "Controller"; -const std::string SwitchSystemOption::JSON_CAMERA = "Camera"; -const std::string SwitchSystemOption::JSON_VIDEO = "Video"; -const std::string SwitchSystemOption::JSON_AUDIO = "Audio"; -const std::string SwitchSystemOption::JSON_OVERLAY = "Overlay"; -const std::string SwitchSystemOption::JSON_CONSOLE_TYPE = "ConsoleType"; - - -SwitchSystemOption::SwitchSystemOption( - const ControllerFeatures& required_features, - bool allow_commands_while_running -) - : m_required_features(required_features) - , m_allow_commands_while_running(allow_commands_while_running) -{} -SwitchSystemOption::SwitchSystemOption( - const ControllerFeatures& required_features, - bool allow_commands_while_running, - const JsonValue& json -) - : SwitchSystemOption(required_features, allow_commands_while_running) -{ - load_json(json); -} -void SwitchSystemOption::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } -// json_get_bool(m_settings_visible, obj, "SettingsVisible"); - const JsonValue* value; - value = obj->get_value(JSON_CONTROLLER); - if (value){ - m_controller.load_json(*value); - } - value = obj->get_value(JSON_VIDEO); - if (value){ - m_video.load_json(*value); - } - value = obj->get_value(JSON_AUDIO); - if (value){ - m_audio.load_json(*value); - } - value = obj->get_value(JSON_OVERLAY); - if (value){ - m_overlay.load_json(*value); - } - value = obj->get_value(JSON_CONSOLE_TYPE); - if (value){ - m_console_type.load_json(*value); - } -} -JsonValue SwitchSystemOption::to_json() const{ - JsonObject root; -// root.insert("SettingsVisible", m_settings_visible); - root[JSON_CONTROLLER] = m_controller.to_json(); - root[JSON_VIDEO] = m_video.to_json(); - root[JSON_AUDIO] = m_audio.to_json(); - root[JSON_OVERLAY] = m_overlay.to_json(); - root[JSON_CONSOLE_TYPE] = m_console_type.to_json(); - - return root; -} - - - - - - - -} -} - +/* Switch System + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_SwitchSystemOption.h" +//#include "UI/NintendoSwitch_SwitchSystemWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +// constexpr Color COLOR_GREEN2(0xff00aa00); + +#if 0 +Color pick_color(FeedbackType feedback){ + switch (feedback){ + case FeedbackType::NONE: + return COLOR_BLUE; + case FeedbackType::OPTIONAL_: + return COLOR_PURPLE; + case FeedbackType::REQUIRED: + return COLOR_DARKGREEN; + case FeedbackType::VIDEO_AUDIO: + return COLOR_RED; + } + return Color(); +} +#endif +Color pick_color( + const ControllerFeatures& required_features, + FasterIfTickPrecise faster_if_tick_precise +){ + if (required_features.contains(ControllerFeature::NintendoSwitch_DateSkip)){ + return COLOR_RED; + } + if (required_features.contains(ControllerFeature::NintendoSwitch_LeftJoycon) || + required_features.contains(ControllerFeature::NintendoSwitch_RightJoycon) + ){ + return COLOR_MAGENTA; + } + if (required_features.contains(ControllerFeature::TickPrecise)){ + return COLOR_PURPLE; + } + switch (faster_if_tick_precise){ + case FasterIfTickPrecise::MUCH_FASTER: + case FasterIfTickPrecise::FASTER: + return COLOR_DARKGREEN; + case FasterIfTickPrecise::NOT_FASTER: + return COLOR_BLUE; + } + + return COLOR_BLUE; +} + + +const std::string SwitchSystemOption::JSON_CONTROLLER = "Controller"; +const std::string SwitchSystemOption::JSON_CAMERA = "Camera"; +const std::string SwitchSystemOption::JSON_VIDEO = "Video"; +const std::string SwitchSystemOption::JSON_AUDIO = "Audio"; +const std::string SwitchSystemOption::JSON_OVERLAY = "Overlay"; +const std::string SwitchSystemOption::JSON_CONSOLE_TYPE = "ConsoleType"; + + +SwitchSystemOption::SwitchSystemOption( + const ControllerFeatures& required_features, + bool allow_commands_while_running +) + : m_required_features(required_features) + , m_allow_commands_while_running(allow_commands_while_running) +{} +SwitchSystemOption::SwitchSystemOption( + const ControllerFeatures& required_features, + bool allow_commands_while_running, + const JsonValue& json +) + : SwitchSystemOption(required_features, allow_commands_while_running) +{ + load_json(json); +} +void SwitchSystemOption::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } +// json_get_bool(m_settings_visible, obj, "SettingsVisible"); + const JsonValue* value; + value = obj->get_value(JSON_CONTROLLER); + if (value){ + m_controller.load_json(*value); + } + value = obj->get_value(JSON_VIDEO); + if (value){ + m_video.load_json(*value); + } + value = obj->get_value(JSON_AUDIO); + if (value){ + m_audio.load_json(*value); + } + value = obj->get_value(JSON_OVERLAY); + if (value){ + m_overlay.load_json(*value); + } + value = obj->get_value(JSON_CONSOLE_TYPE); + if (value){ + m_console_type.load_json(*value); + } +} +JsonValue SwitchSystemOption::to_json() const{ + JsonObject root; +// root.insert("SettingsVisible", m_settings_visible); + root[JSON_CONTROLLER] = m_controller.to_json(); + root[JSON_VIDEO] = m_video.to_json(); + root[JSON_AUDIO] = m_audio.to_json(); + root[JSON_OVERLAY] = m_overlay.to_json(); + root[JSON_CONSOLE_TYPE] = m_console_type.to_json(); + + return root; +} + + + + + + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h index 195f62a674..d4f926d01a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h @@ -1,81 +1,81 @@ -/* Switch System Option - * - * From: https://github.com/PokemonAutomation/ - * - * This class represents the serializable state of a Switch console. - * Specifially, holds the settings of: - * - Serial Port - * - Camera - * - Audio - * - * This class maintains no runtime state or UI and is not thread-safe. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SwitchSystemOption_H -#define PokemonAutomation_NintendoSwitch_SwitchSystemOption_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/AudioPipeline/AudioOption.h" -#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" -#include "CommonFramework/VideoPipeline/VideoOverlayOption.h" -#include "Controllers/ControllerCapability.h" -#include "Controllers/ControllerDescriptor.h" -#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" - -namespace PokemonAutomation{ - class ControllerRequirements; -namespace NintendoSwitch{ - - -//Color pick_color(FeedbackType feedback); -Color pick_color( - const ControllerFeatures& required_features, - FasterIfTickPrecise faster_if_tick_precise -); - - -// options to control and monitor a Switch. It inlcudes -// what micro-controller and what video source to use and -// what video overlay display option to set. -class SwitchSystemOption{ - static const std::string JSON_CONTROLLER; - static const std::string JSON_CAMERA; - static const std::string JSON_VIDEO; - static const std::string JSON_AUDIO; - static const std::string JSON_OVERLAY; - static const std::string JSON_CONSOLE_TYPE; - -public: - SwitchSystemOption( - const ControllerFeatures& required_features, - bool allow_commands_while_running - ); - SwitchSystemOption( - const ControllerFeatures& required_features, - bool allow_commands_while_running, - const JsonValue& json - ); - - void load_json(const JsonValue& json); - JsonValue to_json() const; - - -public: - const ControllerFeatures& m_required_features; - const bool m_allow_commands_while_running; - - ControllerOption m_controller; - VideoSourceOption m_video; - AudioOption m_audio; - VideoOverlayOption m_overlay; - ConsoleModelCell m_console_type; -}; - - - - - -} -} -#endif +/* Switch System Option + * + * From: https://github.com/PokemonAutomation/ + * + * This class represents the serializable state of a Switch console. + * Specifially, holds the settings of: + * - Serial Port + * - Camera + * - Audio + * + * This class maintains no runtime state or UI and is not thread-safe. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SwitchSystemOption_H +#define PokemonAutomation_NintendoSwitch_SwitchSystemOption_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/AudioPipeline/AudioOption.h" +#include "CommonFramework/VideoPipeline/VideoSourceDescriptor.h" +#include "CommonFramework/VideoPipeline/VideoOverlayOption.h" +#include "Controllers/ControllerCapability.h" +#include "Controllers/ControllerDescriptor.h" +#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" + +namespace PokemonAutomation{ + class ControllerRequirements; +namespace NintendoSwitch{ + + +//Color pick_color(FeedbackType feedback); +Color pick_color( + const ControllerFeatures& required_features, + FasterIfTickPrecise faster_if_tick_precise +); + + +// options to control and monitor a Switch. It inlcudes +// what micro-controller and what video source to use and +// what video overlay display option to set. +class SwitchSystemOption{ + static const std::string JSON_CONTROLLER; + static const std::string JSON_CAMERA; + static const std::string JSON_VIDEO; + static const std::string JSON_AUDIO; + static const std::string JSON_OVERLAY; + static const std::string JSON_CONSOLE_TYPE; + +public: + SwitchSystemOption( + const ControllerFeatures& required_features, + bool allow_commands_while_running + ); + SwitchSystemOption( + const ControllerFeatures& required_features, + bool allow_commands_while_running, + const JsonValue& json + ); + + void load_json(const JsonValue& json); + JsonValue to_json() const; + + +public: + const ControllerFeatures& m_required_features; + const bool m_allow_commands_while_running; + + ControllerOption m_controller; + VideoSourceOption m_video; + AudioOption m_audio; + VideoOverlayOption m_overlay; + ConsoleModelCell m_console_type; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.cpp index 3d0cabeadf..5a4669b6c0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.cpp @@ -1,91 +1,91 @@ -/* Switch System Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h" -#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" -#include "Integrations/ProgramTracker.h" -#include "NintendoSwitch_SwitchSystemOption.h" -#include "NintendoSwitch_SwitchSystemSession.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SwitchSystemSession::~SwitchSystemSession(){ - try{ - m_logger.log("Shutting down SwitchSystemSession..."); - }catch (...){} - - m_video.remove_state_listener(m_history); - m_video.add_frame_listener(m_history); - m_audio.remove_stream_listener(m_history); - m_audio.remove_state_listener(m_history); - - ProgramTracker::instance().remove_console(m_console_id); - m_overlay.remove_stat(*m_main_thread_utilization); - m_overlay.remove_stat(*m_cpu_utilization); -} -SwitchSystemSession::SwitchSystemSession( - SwitchSystemOption& option, - uint64_t program_id, - size_t console_number -) - : m_console_number(console_number) - , m_logger(global_logger_raw(), "Console " + std::to_string(console_number)) - , m_option(option) - , m_controller(m_logger, option.m_controller, option.m_required_features) - , m_video(m_logger, option.m_video) - , m_audio(m_logger, option.m_audio) - , m_overlay(option.m_overlay) - , m_history(m_logger) - , m_cpu_utilization(new CpuUtilizationStat()) - , m_main_thread_utilization(new ThreadUtilizationStat(current_thread_handle(), "Main Qt Thread:")) -{ - m_console_id = ProgramTracker::instance().add_console(program_id, *this); - m_overlay.add_stat(*m_cpu_utilization); - m_overlay.add_stat(*m_main_thread_utilization); - - m_history.start(m_audio.input_format(), m_video.current_source() != nullptr); - - m_audio.add_state_listener(m_history); - m_audio.add_stream_listener(m_history); - m_video.add_state_listener(m_history); - m_video.add_frame_listener(m_history); -} - - -void SwitchSystemSession::get(SwitchSystemOption& option){ - m_controller.get(option.m_controller); - m_video.get(option.m_video); - m_audio.get(option.m_audio); - m_overlay.get(option.m_overlay); -} -void SwitchSystemSession::set(const SwitchSystemOption& option){ - m_controller.set(option.m_controller); - m_video.set(option.m_video); - m_audio.set(option.m_audio); - m_overlay.set(option.m_overlay); -} - -void SwitchSystemSession::set_allow_user_commands(std::string disallow_reason){ - m_controller.set_user_input_blocked(std::move(disallow_reason)); -} -void SwitchSystemSession::save_history(const std::string& filename){ - m_history.save(filename); -} - - - - - - -} -} +/* Switch System Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/Stats/CpuUtilizationStats.h" +#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" +#include "Integrations/ProgramTracker.h" +#include "NintendoSwitch_SwitchSystemOption.h" +#include "NintendoSwitch_SwitchSystemSession.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SwitchSystemSession::~SwitchSystemSession(){ + try{ + m_logger.log("Shutting down SwitchSystemSession..."); + }catch (...){} + + m_video.remove_state_listener(m_history); + m_video.add_frame_listener(m_history); + m_audio.remove_stream_listener(m_history); + m_audio.remove_state_listener(m_history); + + ProgramTracker::instance().remove_console(m_console_id); + m_overlay.remove_stat(*m_main_thread_utilization); + m_overlay.remove_stat(*m_cpu_utilization); +} +SwitchSystemSession::SwitchSystemSession( + SwitchSystemOption& option, + uint64_t program_id, + size_t console_number +) + : m_console_number(console_number) + , m_logger(global_logger_raw(), "Console " + std::to_string(console_number)) + , m_option(option) + , m_controller(m_logger, option.m_controller, option.m_required_features) + , m_video(m_logger, option.m_video) + , m_audio(m_logger, option.m_audio) + , m_overlay(option.m_overlay) + , m_history(m_logger) + , m_cpu_utilization(new CpuUtilizationStat()) + , m_main_thread_utilization(new ThreadUtilizationStat(current_thread_handle(), "Main Qt Thread:")) +{ + m_console_id = ProgramTracker::instance().add_console(program_id, *this); + m_overlay.add_stat(*m_cpu_utilization); + m_overlay.add_stat(*m_main_thread_utilization); + + m_history.start(m_audio.input_format(), m_video.current_source() != nullptr); + + m_audio.add_state_listener(m_history); + m_audio.add_stream_listener(m_history); + m_video.add_state_listener(m_history); + m_video.add_frame_listener(m_history); +} + + +void SwitchSystemSession::get(SwitchSystemOption& option){ + m_controller.get(option.m_controller); + m_video.get(option.m_video); + m_audio.get(option.m_audio); + m_overlay.get(option.m_overlay); +} +void SwitchSystemSession::set(const SwitchSystemOption& option){ + m_controller.set(option.m_controller); + m_video.set(option.m_video); + m_audio.set(option.m_audio); + m_overlay.set(option.m_overlay); +} + +void SwitchSystemSession::set_allow_user_commands(std::string disallow_reason){ + m_controller.set_user_input_blocked(std::move(disallow_reason)); +} +void SwitchSystemSession::save_history(const std::string& filename){ + m_history.save(filename); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h index ad9d1ad909..c5dcf4b611 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h @@ -1,102 +1,102 @@ -/* Switch System Session - * - * From: https://github.com/PokemonAutomation/ - * - * This class holds the run-time state of an entire Switch system. - * - * - Serial Port - * - Camera - * - Audio - * - Video Overlay - * - * This class is fully thread-safe. You can call any functions from anywhere at - * anytime. - * - * Warning: Constructing this class requires an "option" parameter. It is not - * safe to modify this "option" parameter during the lifetime of this class. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SwitchSystemSession_H -#define PokemonAutomation_NintendoSwitch_SwitchSystemSession_H - -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/AudioPipeline/AudioSession.h" -#include "CommonFramework/VideoPipeline/VideoSession.h" -#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "Controllers/ControllerSession.h" -#include "Integrations/ProgramTrackerInterfaces.h" -#include "NintendoSwitch_SwitchSystemOption.h" - -namespace PokemonAutomation{ - class CpuUtilizationStat; - class ThreadUtilizationStat; -namespace NintendoSwitch{ - -class SwitchSystemOption; - - - - -class SwitchSystemSession final : public TrackableConsole{ -public: - ~SwitchSystemSession(); - SwitchSystemSession( - SwitchSystemOption& option, - uint64_t program_id, - size_t console_number - ); - -public: - size_t console_number() const{ return m_console_number; } - const ControllerFeatures& required_features() const{ return m_option.m_required_features; } - bool allow_commands_while_running() const{ return m_option.m_allow_commands_while_running; } - - Logger& logger(){ return m_logger; } - virtual VideoFeed& video() override{ return m_video; } - virtual AudioFeed& audio() override{ return m_audio; } - virtual ControllerSession& controller() override{ return m_controller; }; - VideoOverlay& overlay(){ return m_overlay; } - const StreamHistorySession& stream_history() const{ return m_history; } - ConsoleModelCell& console_type(){ return m_option.m_console_type; } - -public: - void get(SwitchSystemOption& option); - void set(const SwitchSystemOption& option); - - ControllerSession& controller_session(){ return m_controller; } - VideoSession& video_session(){ return m_video; } - AudioSession& audio_session(){ return m_audio; } - VideoOverlaySession& overlay_session(){ return m_overlay; } - -public: - void set_allow_user_commands(std::string disallow_reason); - void save_history(const std::string& filename); - -private: - // The console # within a program. - const size_t m_console_number; - - // Globally unique ID. - uint64_t m_console_id = 0; - - TaggedLogger m_logger; - SwitchSystemOption& m_option; - - ControllerSession m_controller; - VideoSession m_video; - AudioSession m_audio; - VideoOverlaySession m_overlay; - - StreamHistorySession m_history; - - std::unique_ptr m_cpu_utilization; - std::unique_ptr m_main_thread_utilization; -}; - - - -} -} -#endif +/* Switch System Session + * + * From: https://github.com/PokemonAutomation/ + * + * This class holds the run-time state of an entire Switch system. + * + * - Serial Port + * - Camera + * - Audio + * - Video Overlay + * + * This class is fully thread-safe. You can call any functions from anywhere at + * anytime. + * + * Warning: Constructing this class requires an "option" parameter. It is not + * safe to modify this "option" parameter during the lifetime of this class. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SwitchSystemSession_H +#define PokemonAutomation_NintendoSwitch_SwitchSystemSession_H + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/AudioPipeline/AudioSession.h" +#include "CommonFramework/VideoPipeline/VideoSession.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "Controllers/ControllerSession.h" +#include "Integrations/ProgramTrackerInterfaces.h" +#include "NintendoSwitch_SwitchSystemOption.h" + +namespace PokemonAutomation{ + class CpuUtilizationStat; + class ThreadUtilizationStat; +namespace NintendoSwitch{ + +class SwitchSystemOption; + + + + +class SwitchSystemSession final : public TrackableConsole{ +public: + ~SwitchSystemSession(); + SwitchSystemSession( + SwitchSystemOption& option, + uint64_t program_id, + size_t console_number + ); + +public: + size_t console_number() const{ return m_console_number; } + const ControllerFeatures& required_features() const{ return m_option.m_required_features; } + bool allow_commands_while_running() const{ return m_option.m_allow_commands_while_running; } + + Logger& logger(){ return m_logger; } + virtual VideoFeed& video() override{ return m_video; } + virtual AudioFeed& audio() override{ return m_audio; } + virtual ControllerSession& controller() override{ return m_controller; }; + VideoOverlay& overlay(){ return m_overlay; } + const StreamHistorySession& stream_history() const{ return m_history; } + ConsoleModelCell& console_type(){ return m_option.m_console_type; } + +public: + void get(SwitchSystemOption& option); + void set(const SwitchSystemOption& option); + + ControllerSession& controller_session(){ return m_controller; } + VideoSession& video_session(){ return m_video; } + AudioSession& audio_session(){ return m_audio; } + VideoOverlaySession& overlay_session(){ return m_overlay; } + +public: + void set_allow_user_commands(std::string disallow_reason); + void save_history(const std::string& filename); + +private: + // The console # within a program. + const size_t m_console_number; + + // Globally unique ID. + uint64_t m_console_id = 0; + + TaggedLogger m_logger; + SwitchSystemOption& m_option; + + ControllerSession m_controller; + VideoSession m_video; + AudioSession m_audio; + VideoOverlaySession m_overlay; + + StreamHistorySession m_history; + + std::unique_ptr m_cpu_utilization; + std::unique_ptr m_main_thread_utilization; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp index 91b1f769bc..fc730dbf2e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.cpp @@ -1,330 +1,330 @@ -/* Command Row - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Recording/StreamHistoryOption.h" -#include "NintendoSwitch_CommandRow.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -CommandRow::~CommandRow(){ - m_controller.remove_listener(*this); - m_session.remove_listener(*this); -} -CommandRow::CommandRow( - QWidget& parent, - ControllerSession& controller, - VideoOverlaySession& session, - ConsoleModelCell& console_type, - bool allow_commands_while_running -) - : QWidget(&parent) - , m_controller(controller) - , m_session(session) - , m_allow_commands_while_running(allow_commands_while_running) - , m_last_known_focus(false) - , m_last_known_state(ProgramState::STOPPED) -{ - QHBoxLayout* command_row = new QHBoxLayout(this); - command_row->setContentsMargins(0, 0, 0, 0); - - command_row->addWidget(new QLabel("Console Type:", this), 2); - command_row->addSpacing(5); - - ConfigWidget* console_type_box = console_type.make_QtWidget(*this); - command_row->addWidget(&console_type_box->widget(), 4); - command_row->addSpacing(5); - - QHBoxLayout* row = new QHBoxLayout(); - command_row->addLayout(row, 12); - - -#if 0 - row->addWidget(new QLabel("Keyboard Input:", this), 2); - row->addSpacing(5); -#endif - - row->addStretch(100); - - m_status = new QLabel(this); -// m_status->setVisible(false); - row->addWidget(m_status); - row->addSpacing(5); - -// row->addWidget(new QLabel("Overlays:", this)); - - m_overlay_boxes = new QCheckBox("Boxes", this); - m_overlay_boxes->setChecked(session.enabled_boxes()); - row->addWidget(m_overlay_boxes); - - m_overlay_text = new QCheckBox("Text", this); - m_overlay_text->setHidden(true); // Nothing uses text overlay yet. - m_overlay_text->setChecked(session.enabled_text()); - row->addWidget(m_overlay_text); - - m_overlay_images = new QCheckBox("Masks", this); - m_overlay_images->setChecked(session.enabled_images()); - row->addWidget(m_overlay_images); - - - m_overlay_log = new QCheckBox("Log", this); - m_overlay_log->setChecked(session.enabled_log()); - row->addWidget(m_overlay_log); - - m_overlay_stats = new QCheckBox("Stats", this); - m_overlay_stats->setChecked(session.enabled_stats()); - row->addWidget(m_overlay_stats); - - row->addSpacing(5); - - m_load_profile_button = new QPushButton("Load Profile", this); - row->addWidget(m_load_profile_button, 2); - - m_save_profile_button = new QPushButton("Save Profile", this); - row->addWidget(m_save_profile_button, 2); - - m_screenshot_button = new QPushButton("Screenshot", this); -// m_screenshot_button->setToolTip("Take a screenshot of the console and save to disk."); - row->addWidget(m_screenshot_button, 2); - - -// m_test_button = new QPushButton("Test Button", this); -// row->addWidget(m_test_button, 3); - - update_ui(); - - connect( - m_overlay_boxes, &QCheckBox::clicked, - this, [this](bool checked){ m_session.set_enabled_boxes(checked); } - ); -#if QT_VERSION < 0x060700 - connect( - m_overlay_text, &QCheckBox::stateChanged, - this, [this](bool checked){ m_session.set_enabled_text(checked); } - ); - connect( - m_overlay_images, &QCheckBox::stateChanged, - this, [this](bool checked){ m_session.set_enabled_images(checked); } - ); - connect( - m_overlay_log, &QCheckBox::stateChanged, - this, [this](bool checked){ m_session.set_enabled_log(checked); } - ); - connect( - m_overlay_stats, &QCheckBox::stateChanged, - this, [this](bool checked){ m_session.set_enabled_stats(checked); } - ); -#else - connect( - m_overlay_text, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState state){ m_session.set_enabled_text(state == Qt::Checked); } - ); - connect( - m_overlay_images, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState state){ m_session.set_enabled_images(state == Qt::Checked); } - ); - connect( - m_overlay_log, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState state){ m_session.set_enabled_log(state == Qt::Checked); } - ); - connect( - m_overlay_stats, &QCheckBox::checkStateChanged, - this, [this](Qt::CheckState state){ m_session.set_enabled_stats(state == Qt::Checked); } - ); -#endif - connect( - m_load_profile_button, &QPushButton::clicked, - this, [this](bool) { emit load_profile(); } - ); - connect( - m_save_profile_button, &QPushButton::clicked, - this, [this](bool) { emit save_profile(); } - ); - connect( - m_screenshot_button, &QPushButton::clicked, - this, [this](bool){ emit screenshot_requested(); } - ); - -#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) - if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ - m_video_button = new QPushButton("Video Capture", this); - command_row->addWidget(m_video_button, 2); - if (GlobalSettings::instance().STREAM_HISTORY->enabled()){ - connect( - m_video_button, &QPushButton::clicked, - this, [this](bool){ emit video_requested(); } - ); - }else{ - m_video_button->setEnabled(false); - m_video_button->setToolTip("Please turn on Stream History to enable video capture."); - } - } -#endif - - m_session.add_listener(*this); - m_controller.add_listener(*this); -} - -void CommandRow::on_key_press(const QKeyEvent& key){ - if (!m_last_known_focus){ - m_controller.logger().log("Keyboard Command Suppressed: Not in focus.", COLOR_RED); - return; - } - AbstractController* controller = m_controller.controller(); - if (controller == nullptr){ - m_controller.logger().log("Keyboard Command Suppressed: Controller is null.", COLOR_RED); - return; - } - if (!m_allow_commands_while_running && m_last_known_state != ProgramState::STOPPED){ - m_controller.logger().log("Keyboard Command Suppressed: Program is running.", COLOR_RED); - return; - } - controller->keyboard_press(key); -} -void CommandRow::on_key_release(const QKeyEvent& key){ - if (!m_last_known_focus){ - return; - } - AbstractController* controller = m_controller.controller(); - if (controller == nullptr){ - return; - } - controller->keyboard_release(key); -} - -void CommandRow::set_focus(bool focused){ - AbstractController* controller = m_controller.controller(); - if (!focused){ - if (controller != nullptr){ - controller->keyboard_release_all(); - } - } - if (m_last_known_focus == focused){ - return; - } - m_last_known_focus = focused; - update_ui(); -} - -void CommandRow::update_ui(){ -// cout << "CommandRow::update_ui(): focus = " << m_last_known_focus << endl; - - bool stopped = m_last_known_state == ProgramState::STOPPED; - m_load_profile_button->setEnabled(stopped); - if (!m_allow_commands_while_running){ -// m_reset_button->setEnabled(stopped); - if (!stopped){ - m_status->setText( - QString::fromStdString( - "Keyboard: " + html_color_text("⬤", COLOR_PURPLE) - ) - ); - return; - } - } - - - if (!m_controller.ready()){ - m_status->setText( - QString::fromStdString( - "Keyboard: " + html_color_text("⬤", COLOR_RED) - ) - ); - return; - } - - std::string error = m_controller.user_input_blocked(); - if (!error.empty()){ - m_status->setText(QString::fromStdString(error)); - return; - } - - if (!m_last_known_focus){ - m_status->setText( - QString::fromStdString( - "Keyboard: " + html_color_text("⬤", COLOR_PURPLE) - ) - ); - return; - } - - m_status->setText( - QString::fromStdString( - "Keyboard: " + html_color_text("⬤", COLOR_DARKGREEN) - ) - ); -} - -void CommandRow::on_state_changed(ProgramState state){ - m_last_known_state = state; - if (m_allow_commands_while_running || state == ProgramState::STOPPED){ - AbstractController* controller = m_controller.controller(); - if (controller != nullptr){ - controller->keyboard_release_all(); - } - } - update_ui(); -} - - -void CommandRow::on_overlay_enabled_boxes(bool enabled){ - QMetaObject::invokeMethod(this, [this, enabled]{ - this->m_overlay_boxes->setChecked(enabled); - }, Qt::QueuedConnection); -} -void CommandRow::on_overlay_enabled_text(bool enabled){ - QMetaObject::invokeMethod(this, [this, enabled]{ - this->m_overlay_text->setChecked(enabled); - }, Qt::QueuedConnection); -} -void CommandRow::on_overlay_enabled_images(bool enabled){ - QMetaObject::invokeMethod(this, [this, enabled]{ - this->m_overlay_images->setChecked(enabled); - }, Qt::QueuedConnection); -} -void CommandRow::on_overlay_enabled_log(bool enabled){ - QMetaObject::invokeMethod(this, [this, enabled]{ - this->m_overlay_log->setChecked(enabled); - }, Qt::QueuedConnection); -} -void CommandRow::on_overlay_enabled_stats(bool enabled){ - QMetaObject::invokeMethod(this, [this, enabled]{ - this->m_overlay_stats->setChecked(enabled); - }, Qt::QueuedConnection); -} -void CommandRow::ready_changed(bool ready){ -// cout << "CommandRow::ready_changed(): " << ready << endl; - QMetaObject::invokeMethod(this, [this]{ - update_ui(); - }, Qt::QueuedConnection); -} - - - - -} -} - - - - - - - - - - - - +/* Command Row + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Recording/StreamHistoryOption.h" +#include "NintendoSwitch_CommandRow.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +CommandRow::~CommandRow(){ + m_controller.remove_listener(*this); + m_session.remove_listener(*this); +} +CommandRow::CommandRow( + QWidget& parent, + ControllerSession& controller, + VideoOverlaySession& session, + ConsoleModelCell& console_type, + bool allow_commands_while_running +) + : QWidget(&parent) + , m_controller(controller) + , m_session(session) + , m_allow_commands_while_running(allow_commands_while_running) + , m_last_known_focus(false) + , m_last_known_state(ProgramState::STOPPED) +{ + QHBoxLayout* command_row = new QHBoxLayout(this); + command_row->setContentsMargins(0, 0, 0, 0); + + command_row->addWidget(new QLabel("Console Type:", this), 2); + command_row->addSpacing(5); + + ConfigWidget* console_type_box = console_type.make_QtWidget(*this); + command_row->addWidget(&console_type_box->widget(), 4); + command_row->addSpacing(5); + + QHBoxLayout* row = new QHBoxLayout(); + command_row->addLayout(row, 12); + + +#if 0 + row->addWidget(new QLabel("Keyboard Input:", this), 2); + row->addSpacing(5); +#endif + + row->addStretch(100); + + m_status = new QLabel(this); +// m_status->setVisible(false); + row->addWidget(m_status); + row->addSpacing(5); + +// row->addWidget(new QLabel("Overlays:", this)); + + m_overlay_boxes = new QCheckBox("Boxes", this); + m_overlay_boxes->setChecked(session.enabled_boxes()); + row->addWidget(m_overlay_boxes); + + m_overlay_text = new QCheckBox("Text", this); + m_overlay_text->setHidden(true); // Nothing uses text overlay yet. + m_overlay_text->setChecked(session.enabled_text()); + row->addWidget(m_overlay_text); + + m_overlay_images = new QCheckBox("Masks", this); + m_overlay_images->setChecked(session.enabled_images()); + row->addWidget(m_overlay_images); + + + m_overlay_log = new QCheckBox("Log", this); + m_overlay_log->setChecked(session.enabled_log()); + row->addWidget(m_overlay_log); + + m_overlay_stats = new QCheckBox("Stats", this); + m_overlay_stats->setChecked(session.enabled_stats()); + row->addWidget(m_overlay_stats); + + row->addSpacing(5); + + m_load_profile_button = new QPushButton("Load Profile", this); + row->addWidget(m_load_profile_button, 2); + + m_save_profile_button = new QPushButton("Save Profile", this); + row->addWidget(m_save_profile_button, 2); + + m_screenshot_button = new QPushButton("Screenshot", this); +// m_screenshot_button->setToolTip("Take a screenshot of the console and save to disk."); + row->addWidget(m_screenshot_button, 2); + + +// m_test_button = new QPushButton("Test Button", this); +// row->addWidget(m_test_button, 3); + + update_ui(); + + connect( + m_overlay_boxes, &QCheckBox::clicked, + this, [this](bool checked){ m_session.set_enabled_boxes(checked); } + ); +#if QT_VERSION < 0x060700 + connect( + m_overlay_text, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_text(checked); } + ); + connect( + m_overlay_images, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_images(checked); } + ); + connect( + m_overlay_log, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_log(checked); } + ); + connect( + m_overlay_stats, &QCheckBox::stateChanged, + this, [this](bool checked){ m_session.set_enabled_stats(checked); } + ); +#else + connect( + m_overlay_text, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_text(state == Qt::Checked); } + ); + connect( + m_overlay_images, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_images(state == Qt::Checked); } + ); + connect( + m_overlay_log, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_log(state == Qt::Checked); } + ); + connect( + m_overlay_stats, &QCheckBox::checkStateChanged, + this, [this](Qt::CheckState state){ m_session.set_enabled_stats(state == Qt::Checked); } + ); +#endif + connect( + m_load_profile_button, &QPushButton::clicked, + this, [this](bool) { emit load_profile(); } + ); + connect( + m_save_profile_button, &QPushButton::clicked, + this, [this](bool) { emit save_profile(); } + ); + connect( + m_screenshot_button, &QPushButton::clicked, + this, [this](bool){ emit screenshot_requested(); } + ); + +#if (QT_VERSION_MAJOR == 6) && (QT_VERSION_MINOR >= 8) + if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ + m_video_button = new QPushButton("Video Capture", this); + command_row->addWidget(m_video_button, 2); + if (GlobalSettings::instance().STREAM_HISTORY->enabled()){ + connect( + m_video_button, &QPushButton::clicked, + this, [this](bool){ emit video_requested(); } + ); + }else{ + m_video_button->setEnabled(false); + m_video_button->setToolTip("Please turn on Stream History to enable video capture."); + } + } +#endif + + m_session.add_listener(*this); + m_controller.add_listener(*this); +} + +void CommandRow::on_key_press(const QKeyEvent& key){ + if (!m_last_known_focus){ + m_controller.logger().log("Keyboard Command Suppressed: Not in focus.", COLOR_RED); + return; + } + AbstractController* controller = m_controller.controller(); + if (controller == nullptr){ + m_controller.logger().log("Keyboard Command Suppressed: Controller is null.", COLOR_RED); + return; + } + if (!m_allow_commands_while_running && m_last_known_state != ProgramState::STOPPED){ + m_controller.logger().log("Keyboard Command Suppressed: Program is running.", COLOR_RED); + return; + } + controller->keyboard_press(key); +} +void CommandRow::on_key_release(const QKeyEvent& key){ + if (!m_last_known_focus){ + return; + } + AbstractController* controller = m_controller.controller(); + if (controller == nullptr){ + return; + } + controller->keyboard_release(key); +} + +void CommandRow::set_focus(bool focused){ + AbstractController* controller = m_controller.controller(); + if (!focused){ + if (controller != nullptr){ + controller->keyboard_release_all(); + } + } + if (m_last_known_focus == focused){ + return; + } + m_last_known_focus = focused; + update_ui(); +} + +void CommandRow::update_ui(){ +// cout << "CommandRow::update_ui(): focus = " << m_last_known_focus << endl; + + bool stopped = m_last_known_state == ProgramState::STOPPED; + m_load_profile_button->setEnabled(stopped); + if (!m_allow_commands_while_running){ +// m_reset_button->setEnabled(stopped); + if (!stopped){ + m_status->setText( + QString::fromStdString( + "Keyboard: " + html_color_text("⬤", COLOR_PURPLE) + ) + ); + return; + } + } + + + if (!m_controller.ready()){ + m_status->setText( + QString::fromStdString( + "Keyboard: " + html_color_text("⬤", COLOR_RED) + ) + ); + return; + } + + std::string error = m_controller.user_input_blocked(); + if (!error.empty()){ + m_status->setText(QString::fromStdString(error)); + return; + } + + if (!m_last_known_focus){ + m_status->setText( + QString::fromStdString( + "Keyboard: " + html_color_text("⬤", COLOR_PURPLE) + ) + ); + return; + } + + m_status->setText( + QString::fromStdString( + "Keyboard: " + html_color_text("⬤", COLOR_DARKGREEN) + ) + ); +} + +void CommandRow::on_state_changed(ProgramState state){ + m_last_known_state = state; + if (m_allow_commands_while_running || state == ProgramState::STOPPED){ + AbstractController* controller = m_controller.controller(); + if (controller != nullptr){ + controller->keyboard_release_all(); + } + } + update_ui(); +} + + +void CommandRow::on_overlay_enabled_boxes(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_boxes->setChecked(enabled); + }, Qt::QueuedConnection); +} +void CommandRow::on_overlay_enabled_text(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_text->setChecked(enabled); + }, Qt::QueuedConnection); +} +void CommandRow::on_overlay_enabled_images(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_images->setChecked(enabled); + }, Qt::QueuedConnection); +} +void CommandRow::on_overlay_enabled_log(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_log->setChecked(enabled); + }, Qt::QueuedConnection); +} +void CommandRow::on_overlay_enabled_stats(bool enabled){ + QMetaObject::invokeMethod(this, [this, enabled]{ + this->m_overlay_stats->setChecked(enabled); + }, Qt::QueuedConnection); +} +void CommandRow::ready_changed(bool ready){ +// cout << "CommandRow::ready_changed(): " << ready << endl; + QMetaObject::invokeMethod(this, [this]{ + update_ui(); + }, Qt::QueuedConnection); +} + + + + +} +} + + + + + + + + + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h index 13fe20145d..ffb583aad7 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_CommandRow.h @@ -1,88 +1,88 @@ -/* Command Row - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_CommandRow_H -#define PokemonAutomation_NintendoSwitch_CommandRow_H - -#include -#include -#include -#include -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" -#include "Controllers/ControllerSession.h" -#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -// UI that shows the checkerboxes to control whether to show video overlay elements. -// e.g. checkerbox to toggle on/off overlay boxes -class CommandRow : - public QWidget, - public VideoOverlaySession::ContentListener, - public ControllerSession::Listener -{ - Q_OBJECT - -public: - ~CommandRow(); - CommandRow( - QWidget& parent, - ControllerSession& controller, - VideoOverlaySession& session, - ConsoleModelCell& console_type, - bool allow_commands_while_running - ); - - void on_key_press(const QKeyEvent& key); - void on_key_release(const QKeyEvent& key); - -signals: - void load_profile(); - void save_profile(); - void screenshot_requested(); - void video_requested(); - -public: - void set_focus(bool focused); - void update_ui(); - void on_state_changed(ProgramState state); - -private: - virtual void on_overlay_enabled_boxes (bool enabled) override; - virtual void on_overlay_enabled_text (bool enabled) override; - virtual void on_overlay_enabled_images (bool enabled) override; - virtual void on_overlay_enabled_log (bool enabled) override; - virtual void on_overlay_enabled_stats (bool enabled) override; - virtual void ready_changed(bool ready) override; - -private: - ControllerSession& m_controller; - VideoOverlaySession& m_session; - bool m_allow_commands_while_running; - QComboBox* m_command_box; - QLabel* m_status; - - QCheckBox* m_overlay_log; - QCheckBox* m_overlay_text; - QCheckBox* m_overlay_images; - QCheckBox* m_overlay_boxes; - QCheckBox* m_overlay_stats; - - QPushButton* m_load_profile_button; - QPushButton* m_save_profile_button; - QPushButton* m_screenshot_button; - QPushButton* m_video_button; - bool m_last_known_focus; - ProgramState m_last_known_state; -}; - - -} -} -#endif +/* Command Row + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_CommandRow_H +#define PokemonAutomation_NintendoSwitch_CommandRow_H + +#include +#include +#include +#include +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlaySession.h" +#include "Controllers/ControllerSession.h" +#include "NintendoSwitch/Options/NintendoSwitch_ModelType.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +// UI that shows the checkerboxes to control whether to show video overlay elements. +// e.g. checkerbox to toggle on/off overlay boxes +class CommandRow : + public QWidget, + public VideoOverlaySession::ContentListener, + public ControllerSession::Listener +{ + Q_OBJECT + +public: + ~CommandRow(); + CommandRow( + QWidget& parent, + ControllerSession& controller, + VideoOverlaySession& session, + ConsoleModelCell& console_type, + bool allow_commands_while_running + ); + + void on_key_press(const QKeyEvent& key); + void on_key_release(const QKeyEvent& key); + +signals: + void load_profile(); + void save_profile(); + void screenshot_requested(); + void video_requested(); + +public: + void set_focus(bool focused); + void update_ui(); + void on_state_changed(ProgramState state); + +private: + virtual void on_overlay_enabled_boxes (bool enabled) override; + virtual void on_overlay_enabled_text (bool enabled) override; + virtual void on_overlay_enabled_images (bool enabled) override; + virtual void on_overlay_enabled_log (bool enabled) override; + virtual void on_overlay_enabled_stats (bool enabled) override; + virtual void ready_changed(bool ready) override; + +private: + ControllerSession& m_controller; + VideoOverlaySession& m_session; + bool m_allow_commands_while_running; + QComboBox* m_command_box; + QLabel* m_status; + + QCheckBox* m_overlay_log; + QCheckBox* m_overlay_text; + QCheckBox* m_overlay_images; + QCheckBox* m_overlay_boxes; + QCheckBox* m_overlay_stats; + + QPushButton* m_load_profile_button; + QPushButton* m_save_profile_button; + QPushButton* m_screenshot_button; + QPushButton* m_video_button; + bool m_last_known_focus; + ProgramState m_last_known_state; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp index 65ccd44767..fdac31e7fa 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.cpp @@ -1,177 +1,177 @@ -/* Multi-Switch Program Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Qt/CollapsibleGroupBox.h" -#include "Common/Qt/Options/ConfigWidget.h" -//#include "Common/Qt/Options/BatchWidget.h" -#include "CommonFramework/Startup/NewVersionCheck.h" -#include "CommonFramework/Panels/PanelTools.h" -#include "CommonFramework/Panels/UI/PanelElements.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h" -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h" -#include "NintendoSwitch_MultiSwitchProgramWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -MultiSwitchProgramWidget2::~MultiSwitchProgramWidget2(){ - auto ScopeCheck = m_sanitizer.check_scope(); - m_session.ProgramSession::remove_listener(*this); - m_session.remove_listener(*this); - delete m_actions_bar; - delete m_stats_bar; - delete m_options; - delete m_system; -} - - -MultiSwitchProgramWidget2::MultiSwitchProgramWidget2( - QWidget& parent, - MultiSwitchProgramOption& option, - PanelHolder& holder -) - : QWidget(&parent) - , m_holder(holder) - , m_session(option) - , m_sanitizer("MultiSwitchProgramWidget2") -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - const MultiSwitchProgramDescriptor& descriptor = option.descriptor(); - - CollapsibleGroupBox* header = make_panel_header( - *this, - descriptor.display_name(), - descriptor.doc_link(), - descriptor.description(), - descriptor.required_features(), - descriptor.faster_if_tick_precise() - ); - layout->addWidget(header); - - - { - QScrollArea* scroll_outer = new QScrollArea(this); - layout->addWidget(scroll_outer); - scroll_outer->setWidgetResizable(true); - - QWidget* scroll_inner = new QWidget(scroll_outer); - scroll_outer->setWidget(scroll_inner); - QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); - scroll_layout->setAlignment(Qt::AlignTop); - - m_system = new MultiSwitchSystemWidget(*this, m_session.system(), m_session.instance_id()); - scroll_layout->addWidget(m_system); - - m_options = option.options().make_QtWidget(*this); - scroll_layout->addWidget(&m_options->widget()); - - scroll_layout->addStretch(1); - } - - m_stats_bar = new StatsBar(*this); - m_stats_bar->set_stats("", m_session.historical_stats()); - layout->addWidget(m_stats_bar); - - m_actions_bar = new RunnablePanelActionBar(*this, m_session.current_state()); - layout->addWidget(m_actions_bar); - - connect( - m_actions_bar, &RunnablePanelActionBar::start_clicked, - this, [&](ProgramState state){ - std::string error; - switch (state){ - case ProgramState::STOPPED: - error = m_session.start_program(); - break; - case ProgramState::RUNNING: - error = m_session.stop_program(); - break; - default:; - } - if (!error.empty()){ - this->error(error); - } - } - ); - connect( - m_actions_bar, &RunnablePanelActionBar::defaults_clicked, - this, [&]{ - std::lock_guard lg(m_session.program_lock()); - option.restore_defaults(); - m_options->update_all(false); - } - ); - - m_session.add_listener(*this); - m_session.ProgramSession::add_listener(*this); -} - - - - -void MultiSwitchProgramWidget2::state_change(ProgramState state){ - auto ScopeCheck = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, state]{ - m_system->update_ui(state); - m_options->option().report_program_state(state != ProgramState::STOPPED); -// cout << "state = " << (state != ProgramState::STOPPED) << endl; -// if (m_option.descriptor().lock_options_while_running()){ -// m_options->widget().setEnabled(state == ProgramState::STOPPED); -// } - m_actions_bar->set_state(state); - if (state == ProgramState::STOPPED){ - m_holder.on_idle(); - check_new_version(); - }else{ - m_holder.on_busy(); - } - }); -} -void MultiSwitchProgramWidget2::stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats){ - auto ScopeCheck = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this, current_stats, historical_stats]{ - m_stats_bar->set_stats( - current_stats == nullptr ? "" : current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN), - historical_stats == nullptr ? "" : historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) - ); - }); -} -void MultiSwitchProgramWidget2::error(const std::string& message){ - auto ScopeCheck = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [message]{ - QMessageBox box; - box.critical(nullptr, "Error", QString::fromStdString(message)); - }); -} - -void MultiSwitchProgramWidget2::redraw_options(){ - auto ScopeCheck = m_sanitizer.check_scope(); - QMetaObject::invokeMethod(this, [this]{ - m_options->update_all(false); - }); -} - - - - - - -} -} +/* Multi-Switch Program Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Qt/CollapsibleGroupBox.h" +#include "Common/Qt/Options/ConfigWidget.h" +//#include "Common/Qt/Options/BatchWidget.h" +#include "CommonFramework/Startup/NewVersionCheck.h" +#include "CommonFramework/Panels/PanelTools.h" +#include "CommonFramework/Panels/UI/PanelElements.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramOption.h" +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h" +#include "NintendoSwitch_MultiSwitchProgramWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +MultiSwitchProgramWidget2::~MultiSwitchProgramWidget2(){ + auto ScopeCheck = m_sanitizer.check_scope(); + m_session.ProgramSession::remove_listener(*this); + m_session.remove_listener(*this); + delete m_actions_bar; + delete m_stats_bar; + delete m_options; + delete m_system; +} + + +MultiSwitchProgramWidget2::MultiSwitchProgramWidget2( + QWidget& parent, + MultiSwitchProgramOption& option, + PanelHolder& holder +) + : QWidget(&parent) + , m_holder(holder) + , m_session(option) + , m_sanitizer("MultiSwitchProgramWidget2") +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + const MultiSwitchProgramDescriptor& descriptor = option.descriptor(); + + CollapsibleGroupBox* header = make_panel_header( + *this, + descriptor.display_name(), + descriptor.doc_link(), + descriptor.description(), + descriptor.required_features(), + descriptor.faster_if_tick_precise() + ); + layout->addWidget(header); + + + { + QScrollArea* scroll_outer = new QScrollArea(this); + layout->addWidget(scroll_outer); + scroll_outer->setWidgetResizable(true); + + QWidget* scroll_inner = new QWidget(scroll_outer); + scroll_outer->setWidget(scroll_inner); + QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); + scroll_layout->setAlignment(Qt::AlignTop); + + m_system = new MultiSwitchSystemWidget(*this, m_session.system(), m_session.instance_id()); + scroll_layout->addWidget(m_system); + + m_options = option.options().make_QtWidget(*this); + scroll_layout->addWidget(&m_options->widget()); + + scroll_layout->addStretch(1); + } + + m_stats_bar = new StatsBar(*this); + m_stats_bar->set_stats("", m_session.historical_stats()); + layout->addWidget(m_stats_bar); + + m_actions_bar = new RunnablePanelActionBar(*this, m_session.current_state()); + layout->addWidget(m_actions_bar); + + connect( + m_actions_bar, &RunnablePanelActionBar::start_clicked, + this, [&](ProgramState state){ + std::string error; + switch (state){ + case ProgramState::STOPPED: + error = m_session.start_program(); + break; + case ProgramState::RUNNING: + error = m_session.stop_program(); + break; + default:; + } + if (!error.empty()){ + this->error(error); + } + } + ); + connect( + m_actions_bar, &RunnablePanelActionBar::defaults_clicked, + this, [&]{ + std::lock_guard lg(m_session.program_lock()); + option.restore_defaults(); + m_options->update_all(false); + } + ); + + m_session.add_listener(*this); + m_session.ProgramSession::add_listener(*this); +} + + + + +void MultiSwitchProgramWidget2::state_change(ProgramState state){ + auto ScopeCheck = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, state]{ + m_system->update_ui(state); + m_options->option().report_program_state(state != ProgramState::STOPPED); +// cout << "state = " << (state != ProgramState::STOPPED) << endl; +// if (m_option.descriptor().lock_options_while_running()){ +// m_options->widget().setEnabled(state == ProgramState::STOPPED); +// } + m_actions_bar->set_state(state); + if (state == ProgramState::STOPPED){ + m_holder.on_idle(); + check_new_version(); + }else{ + m_holder.on_busy(); + } + }); +} +void MultiSwitchProgramWidget2::stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats){ + auto ScopeCheck = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this, current_stats, historical_stats]{ + m_stats_bar->set_stats( + current_stats == nullptr ? "" : current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN), + historical_stats == nullptr ? "" : historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) + ); + }); +} +void MultiSwitchProgramWidget2::error(const std::string& message){ + auto ScopeCheck = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [message]{ + QMessageBox box; + box.critical(nullptr, "Error", QString::fromStdString(message)); + }); +} + +void MultiSwitchProgramWidget2::redraw_options(){ + auto ScopeCheck = m_sanitizer.check_scope(); + QMetaObject::invokeMethod(this, [this]{ + m_options->update_all(false); + }); +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.h b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.h index 65bcad5f77..4c9e0324b9 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchProgramWidget.h @@ -1,66 +1,66 @@ -/* Multi-Switch Program Widget - * - * From: https://github.com/PokemonAutomation/ - * - * This is the Qt Widget implementation of the UI for MultiSwitchProgramSession. - * - * On construction, this class attaches itself to the session it is constructed - * with and automatically detaches on destruction. Therefore, this class must - * not outlive the session it is constructed with. While not useful, it is also - * safe to construct multiple UI classes attached to the same session. - * - * Modifications directly to the session object will automatically update this - * UI class. For example, if you use Discord to change the volume of the - * audio playback, it will move the slider as shown by this UI. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgramWidget_H -#define PokemonAutomation_NintendoSwitch_MultiSwitchProgramWidget_H - -#include "CommonFramework/Panels/UI/PanelElements.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h" -#include "NintendoSwitch_MultiSwitchSystemWidget.h" - -namespace PokemonAutomation{ - struct PanelHolder; -namespace NintendoSwitch{ - - - -class MultiSwitchProgramWidget2 : public QWidget, private ProgramSession::Listener, private MultiSwitchProgramSession::Listener{ -public: - ~MultiSwitchProgramWidget2(); - MultiSwitchProgramWidget2( - QWidget& parent, - MultiSwitchProgramOption& option, - PanelHolder& holder - ); - -private: - virtual void state_change(ProgramState state) override; - virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) override; - virtual void error(const std::string& message) override; - - virtual void redraw_options() override; - -private: - PanelHolder& m_holder; - MultiSwitchProgramSession m_session; - MultiSwitchSystemWidget* m_system; - ConfigWidget* m_options; - StatsBar* m_stats_bar; - RunnablePanelActionBar* m_actions_bar; - - LifetimeSanitizer m_sanitizer; -}; - - - - - - -} -} -#endif +/* Multi-Switch Program Widget + * + * From: https://github.com/PokemonAutomation/ + * + * This is the Qt Widget implementation of the UI for MultiSwitchProgramSession. + * + * On construction, this class attaches itself to the session it is constructed + * with and automatically detaches on destruction. Therefore, this class must + * not outlive the session it is constructed with. While not useful, it is also + * safe to construct multiple UI classes attached to the same session. + * + * Modifications directly to the session object will automatically update this + * UI class. For example, if you use Discord to change the volume of the + * audio playback, it will move the slider as shown by this UI. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgramWidget_H +#define PokemonAutomation_NintendoSwitch_MultiSwitchProgramWidget_H + +#include "CommonFramework/Panels/UI/PanelElements.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchProgramSession.h" +#include "NintendoSwitch_MultiSwitchSystemWidget.h" + +namespace PokemonAutomation{ + struct PanelHolder; +namespace NintendoSwitch{ + + + +class MultiSwitchProgramWidget2 : public QWidget, private ProgramSession::Listener, private MultiSwitchProgramSession::Listener{ +public: + ~MultiSwitchProgramWidget2(); + MultiSwitchProgramWidget2( + QWidget& parent, + MultiSwitchProgramOption& option, + PanelHolder& holder + ); + +private: + virtual void state_change(ProgramState state) override; + virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) override; + virtual void error(const std::string& message) override; + + virtual void redraw_options() override; + +private: + PanelHolder& m_holder; + MultiSwitchProgramSession m_session; + MultiSwitchSystemWidget* m_system; + ConfigWidget* m_options; + StatsBar* m_stats_bar; + RunnablePanelActionBar* m_actions_bar; + + LifetimeSanitizer m_sanitizer; +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.cpp index 2994634091..dcd03c3b1d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.cpp @@ -1,176 +1,176 @@ -/* Multi-Switch System Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "NintendoSwitch_SwitchSystemWidget.h" -#include "NintendoSwitch_MultiSwitchSystemWidget.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -MultiSwitchSystemWidget::~MultiSwitchSystemWidget(){ - { - std::lock_guard lg(m_lock); - for (SwitchSystemWidget* console : m_switches){ - delete console; - } - m_switches.clear(); - delete m_videos; - m_videos = nullptr; - m_shutting_down = true; - } - m_session.remove_listener(*this); -} -MultiSwitchSystemWidget::MultiSwitchSystemWidget( - QWidget& parent, - MultiSwitchSystemSession& session, - uint64_t program_id -) - : QWidget(&parent) - , m_program_id(program_id) - , m_session(session) - , m_videos(nullptr) -{ - QVBoxLayout* vbox = new QVBoxLayout(this); - vbox->setContentsMargins(0, 0, 0, 0); - - QHBoxLayout* row = new QHBoxLayout(); - vbox->addLayout(row, 0); - row->setContentsMargins(0, 0, 0, 0); - row->addStretch(2); - row->addWidget(new QLabel("Switch Count:", this), 0); - m_console_count_box = new NoWheelComboBox(this); - row->addWidget(m_console_count_box, 1); - row->addStretch(2); - - for (size_t c = session.min_switches(); c <= session.max_switches(); c++){ - m_console_count_box->addItem(QString::number(c)); - } - m_console_count_box->setCurrentIndex((int)(m_session.count() - m_session.min_switches())); - - connect( - m_console_count_box, static_cast(&QComboBox::currentIndexChanged), - this, [this](int index){ - if (index < 0 || index > (int)(m_session.max_switches() - m_session.min_switches())){ - return; - } - m_session.set_switch_count(index + m_session.min_switches()); - } - ); - - -#if 0 - // Acquire the lock now and attach listener. This will block the session - // from changing the # of switches while we draw everything. - std::lock_guard lg(m_lock); - m_session.add_listener(*this); - - m_console_count_box->setCurrentIndex((int)(m_session.count() - m_session.min_switches())); - - redraw_videos(m_session.count()); -#endif - m_session.add_listener(*this); -} - -void MultiSwitchSystemWidget::shutdown(){ -// cout << "MultiSwitchSystemWidget::shutdown()" << endl; - std::lock_guard lg(m_lock); - for (SwitchSystemWidget* console : m_switches){ - delete console; - } - m_switches.clear(); - delete m_videos; - m_videos = nullptr; -} -void MultiSwitchSystemWidget::startup(size_t switch_count){ -// cout << "MultiSwitchSystemWidget::startup()" << endl; - std::lock_guard lg(m_lock); - redraw_videos(switch_count); -} - -void MultiSwitchSystemWidget::redraw_videos(size_t count){ -// cout << "MultiSwitchSystemWidget::redraw_videos()" << endl; -// std::lock_guard lg(m_lock); -// if (count == m_switches.size()){ -// return; -// } - if (m_shutting_down){ - return; - } - - int old_index = m_console_count_box->currentIndex(); - int new_index = (int)(m_session.count() - m_session.min_switches()); - if (new_index != old_index){ - m_console_count_box->setCurrentIndex(new_index); - } - - QVBoxLayout* layout = static_cast(this->layout()); - m_switches.clear(); - if (m_videos != nullptr){ - layout->removeWidget(m_videos); - delete m_videos; - m_videos = nullptr; - } - - m_videos = new QWidget(this); - this->layout()->addWidget(m_videos); - QVBoxLayout* vbox = new QVBoxLayout(m_videos); - vbox->setContentsMargins(0, 0, 0, 0); - -// m_option.resize(count); - for (size_t c = 0; c < m_session.count(); c++){ -// const auto& item = m_option.m_switches[c]; -// m_switches.emplace_back(item->make_ui(*this, m_logger, m_program_id)); - m_switches.emplace_back( - new SwitchSystemWidget( - *m_videos, - m_session[c], - m_program_id - ) - ); - } - - QHBoxLayout* vrow0 = new QHBoxLayout(); - vbox->addLayout(vrow0, 1); - vrow0->setContentsMargins(0, 0, 0, 0); - - vrow0->addWidget(m_switches[0], 1); - if (m_switches.size() >= 2){ - vrow0->addWidget(m_switches[1], 1); - } - if (m_switches.size() >= 3){ - QHBoxLayout* vrow1 = new QHBoxLayout(); - vbox->addLayout(vrow1, 1); - vrow1->setContentsMargins(0, 0, 0, 0); - vrow1->addWidget(m_switches[2], 1); - if (m_switches.size() >= MultiSwitchSystemOption::MAX_SWITCHES){ - vrow1->addWidget(m_switches[3], 1); - }else{ - vrow1->addWidget(new QWidget(), 1); - } - } - static_assert(MultiSwitchSystemOption::MAX_SWITCHES <= 4, "Can't display more than 4 Switches."); -} - -void MultiSwitchSystemWidget::update_ui(ProgramState state){ - m_console_count_box->setEnabled(state == ProgramState::STOPPED); - for (const auto& item : m_switches){ - item->update_ui(state); - } -} - - - - -} -} +/* Multi-Switch System Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "NintendoSwitch_SwitchSystemWidget.h" +#include "NintendoSwitch_MultiSwitchSystemWidget.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +MultiSwitchSystemWidget::~MultiSwitchSystemWidget(){ + { + std::lock_guard lg(m_lock); + for (SwitchSystemWidget* console : m_switches){ + delete console; + } + m_switches.clear(); + delete m_videos; + m_videos = nullptr; + m_shutting_down = true; + } + m_session.remove_listener(*this); +} +MultiSwitchSystemWidget::MultiSwitchSystemWidget( + QWidget& parent, + MultiSwitchSystemSession& session, + uint64_t program_id +) + : QWidget(&parent) + , m_program_id(program_id) + , m_session(session) + , m_videos(nullptr) +{ + QVBoxLayout* vbox = new QVBoxLayout(this); + vbox->setContentsMargins(0, 0, 0, 0); + + QHBoxLayout* row = new QHBoxLayout(); + vbox->addLayout(row, 0); + row->setContentsMargins(0, 0, 0, 0); + row->addStretch(2); + row->addWidget(new QLabel("Switch Count:", this), 0); + m_console_count_box = new NoWheelComboBox(this); + row->addWidget(m_console_count_box, 1); + row->addStretch(2); + + for (size_t c = session.min_switches(); c <= session.max_switches(); c++){ + m_console_count_box->addItem(QString::number(c)); + } + m_console_count_box->setCurrentIndex((int)(m_session.count() - m_session.min_switches())); + + connect( + m_console_count_box, static_cast(&QComboBox::currentIndexChanged), + this, [this](int index){ + if (index < 0 || index > (int)(m_session.max_switches() - m_session.min_switches())){ + return; + } + m_session.set_switch_count(index + m_session.min_switches()); + } + ); + + +#if 0 + // Acquire the lock now and attach listener. This will block the session + // from changing the # of switches while we draw everything. + std::lock_guard lg(m_lock); + m_session.add_listener(*this); + + m_console_count_box->setCurrentIndex((int)(m_session.count() - m_session.min_switches())); + + redraw_videos(m_session.count()); +#endif + m_session.add_listener(*this); +} + +void MultiSwitchSystemWidget::shutdown(){ +// cout << "MultiSwitchSystemWidget::shutdown()" << endl; + std::lock_guard lg(m_lock); + for (SwitchSystemWidget* console : m_switches){ + delete console; + } + m_switches.clear(); + delete m_videos; + m_videos = nullptr; +} +void MultiSwitchSystemWidget::startup(size_t switch_count){ +// cout << "MultiSwitchSystemWidget::startup()" << endl; + std::lock_guard lg(m_lock); + redraw_videos(switch_count); +} + +void MultiSwitchSystemWidget::redraw_videos(size_t count){ +// cout << "MultiSwitchSystemWidget::redraw_videos()" << endl; +// std::lock_guard lg(m_lock); +// if (count == m_switches.size()){ +// return; +// } + if (m_shutting_down){ + return; + } + + int old_index = m_console_count_box->currentIndex(); + int new_index = (int)(m_session.count() - m_session.min_switches()); + if (new_index != old_index){ + m_console_count_box->setCurrentIndex(new_index); + } + + QVBoxLayout* layout = static_cast(this->layout()); + m_switches.clear(); + if (m_videos != nullptr){ + layout->removeWidget(m_videos); + delete m_videos; + m_videos = nullptr; + } + + m_videos = new QWidget(this); + this->layout()->addWidget(m_videos); + QVBoxLayout* vbox = new QVBoxLayout(m_videos); + vbox->setContentsMargins(0, 0, 0, 0); + +// m_option.resize(count); + for (size_t c = 0; c < m_session.count(); c++){ +// const auto& item = m_option.m_switches[c]; +// m_switches.emplace_back(item->make_ui(*this, m_logger, m_program_id)); + m_switches.emplace_back( + new SwitchSystemWidget( + *m_videos, + m_session[c], + m_program_id + ) + ); + } + + QHBoxLayout* vrow0 = new QHBoxLayout(); + vbox->addLayout(vrow0, 1); + vrow0->setContentsMargins(0, 0, 0, 0); + + vrow0->addWidget(m_switches[0], 1); + if (m_switches.size() >= 2){ + vrow0->addWidget(m_switches[1], 1); + } + if (m_switches.size() >= 3){ + QHBoxLayout* vrow1 = new QHBoxLayout(); + vbox->addLayout(vrow1, 1); + vrow1->setContentsMargins(0, 0, 0, 0); + vrow1->addWidget(m_switches[2], 1); + if (m_switches.size() >= MultiSwitchSystemOption::MAX_SWITCHES){ + vrow1->addWidget(m_switches[3], 1); + }else{ + vrow1->addWidget(new QWidget(), 1); + } + } + static_assert(MultiSwitchSystemOption::MAX_SWITCHES <= 4, "Can't display more than 4 Switches."); +} + +void MultiSwitchSystemWidget::update_ui(ProgramState state){ + m_console_count_box->setEnabled(state == ProgramState::STOPPED); + for (const auto& item : m_switches){ + item->update_ui(state); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h index 374e157411..abcdafbda6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h @@ -1,72 +1,72 @@ -/* Multi-Switch System Widget - * - * From: https://github.com/PokemonAutomation/ - * - * This is the Qt Widget implementation of the UI for MultiSwitchSystemSession. - * - * On construction, this class attaches itself to the session it is constructed - * with and automatically detaches on destruction. Therefore, this class must - * not outlive the session it is constructed with. While not useful, it is also - * safe to construct multiple UI classes attached to the same session. - * - * Modifications directly to the session object will automatically update this - * UI class. For example, if you use Discord to change the volume of the - * audio playback, it will move the slider as shown by this UI. - * - */ - -#ifndef PokemonAutomationn_NintendoSwitch_SwitchSystem4Widget_H -#define PokemonAutomationn_NintendoSwitch_SwitchSystem4Widget_H - -#include -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h" -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h" - -class QComboBox; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class SwitchSystemWidget; - - -class MultiSwitchSystemWidget final : public QWidget, private MultiSwitchSystemSession::Listener{ - Q_OBJECT - -public: - ~MultiSwitchSystemWidget(); - MultiSwitchSystemWidget( - QWidget& parent, - MultiSwitchSystemSession& session, - uint64_t program_id - ); - - size_t switch_count() const{ return m_switches.size(); } - SwitchSystemWidget& operator[](size_t index){ return *m_switches[index]; } - -public: - void update_ui(ProgramState state); - -private: - virtual void shutdown() override; - virtual void startup(size_t switch_count) override; - - void redraw_videos(size_t count); - -private: - uint64_t m_program_id; - MultiSwitchSystemSession& m_session; - - std::mutex m_lock; - bool m_shutting_down = false; - - QComboBox* m_console_count_box; - std::vector m_switches; - QWidget* m_videos; -// std::map m_active_ports; -}; - - -} -} -#endif +/* Multi-Switch System Widget + * + * From: https://github.com/PokemonAutomation/ + * + * This is the Qt Widget implementation of the UI for MultiSwitchSystemSession. + * + * On construction, this class attaches itself to the session it is constructed + * with and automatically detaches on destruction. Therefore, this class must + * not outlive the session it is constructed with. While not useful, it is also + * safe to construct multiple UI classes attached to the same session. + * + * Modifications directly to the session object will automatically update this + * UI class. For example, if you use Discord to change the volume of the + * audio playback, it will move the slider as shown by this UI. + * + */ + +#ifndef PokemonAutomationn_NintendoSwitch_SwitchSystem4Widget_H +#define PokemonAutomationn_NintendoSwitch_SwitchSystem4Widget_H + +#include +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h" +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h" + +class QComboBox; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class SwitchSystemWidget; + + +class MultiSwitchSystemWidget final : public QWidget, private MultiSwitchSystemSession::Listener{ + Q_OBJECT + +public: + ~MultiSwitchSystemWidget(); + MultiSwitchSystemWidget( + QWidget& parent, + MultiSwitchSystemSession& session, + uint64_t program_id + ); + + size_t switch_count() const{ return m_switches.size(); } + SwitchSystemWidget& operator[](size_t index){ return *m_switches[index]; } + +public: + void update_ui(ProgramState state); + +private: + virtual void shutdown() override; + virtual void startup(size_t switch_count) override; + + void redraw_videos(size_t count); + +private: + uint64_t m_program_id; + MultiSwitchSystemSession& m_session; + + std::mutex m_lock; + bool m_shutting_down = false; + + QComboBox* m_console_count_box; + std::vector m_switches; + QWidget* m_videos; +// std::map m_active_ports; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp index 4cca7d04c2..deaa855442 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.cpp @@ -1,161 +1,161 @@ -/* Single Switch Program Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Qt/CollapsibleGroupBox.h" -#include "Common/Qt/Options/ConfigWidget.h" -#include "CommonFramework/Startup/NewVersionCheck.h" -#include "CommonFramework/Panels/PanelTools.h" -#include "CommonFramework/Panels/UI/PanelElements.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h" -#include "NintendoSwitch_SingleSwitchProgramWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SingleSwitchProgramWidget2::~SingleSwitchProgramWidget2(){ - m_session.remove_listener(*this); - delete m_actions_bar; - delete m_stats_bar; - delete m_options; - delete m_system; -} -SingleSwitchProgramWidget2::SingleSwitchProgramWidget2( - QWidget& parent, - SingleSwitchProgramOption& option, - PanelHolder& holder -) - : QWidget(&parent) - , m_holder(holder) - , m_session(option, 0) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - - const SingleSwitchProgramDescriptor& descriptor = option.descriptor(); - - CollapsibleGroupBox* header = make_panel_header( - *this, - descriptor.display_name(), - descriptor.doc_link(), - descriptor.description(), - descriptor.required_features(), - descriptor.faster_if_tick_precise() - ); - layout->addWidget(header); - - - { - QScrollArea* scroll_outer = new QScrollArea(this); - layout->addWidget(scroll_outer); - scroll_outer->setWidgetResizable(true); - - QWidget* scroll_inner = new QWidget(scroll_outer); - scroll_outer->setWidget(scroll_inner); - QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); - scroll_layout->setAlignment(Qt::AlignTop); - - m_system = new SwitchSystemWidget( - *this, - m_session.system(), - m_session.instance_id() - ); - scroll_layout->addWidget(m_system); - - m_options = option.options().make_QtWidget(*this); - scroll_layout->addWidget(&m_options->widget()); - - scroll_layout->addStretch(1); - } - - m_stats_bar = new StatsBar(*this); - m_stats_bar->set_stats("", m_session.historical_stats()); - layout->addWidget(m_stats_bar); - - m_actions_bar = new RunnablePanelActionBar(*this, m_session.current_state()); - layout->addWidget(m_actions_bar); - - connect( - m_actions_bar, &RunnablePanelActionBar::start_clicked, - this, [&](ProgramState state){ - std::string error; - switch (state){ - case ProgramState::STOPPED: - error = m_session.start_program(); - break; - case ProgramState::RUNNING: - error = m_session.stop_program(); - break; - default:; - } - if (!error.empty()){ - this->error(error); - } - } - ); - connect( - m_actions_bar, &RunnablePanelActionBar::defaults_clicked, - this, [&]{ - std::lock_guard lg(m_session.program_lock()); - option.restore_defaults(); - m_options->update_all(false); - } - ); - - m_session.add_listener(*this); -} - -void SingleSwitchProgramWidget2::state_change(ProgramState state){ - QMetaObject::invokeMethod(this, [this, state]{ - m_system->update_ui(state); - m_options->option().report_program_state(state != ProgramState::STOPPED); -// cout << "state = " << (state != ProgramState::STOPPED) << endl; -// if (m_option.descriptor().lock_options_while_running()){ -// m_options->widget().setEnabled(state == ProgramState::STOPPED); -// } - m_actions_bar->set_state(state); - if (state == ProgramState::STOPPED){ - m_holder.on_idle(); - check_new_version(); - }else{ - m_holder.on_busy(); - } - }); -} -void SingleSwitchProgramWidget2::stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats){ - QMetaObject::invokeMethod(this, [this, current_stats, historical_stats]{ - m_stats_bar->set_stats( - current_stats == nullptr ? "" : current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN), - historical_stats == nullptr ? "" : historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) - ); - }); -} -void SingleSwitchProgramWidget2::error(const std::string& message){ - QMetaObject::invokeMethod(this, [message]{ - QMessageBox box; - box.critical(nullptr, "Error", QString::fromStdString(message)); - }); -} - - - - - - - - -} -} +/* Single Switch Program Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Qt/CollapsibleGroupBox.h" +#include "Common/Qt/Options/ConfigWidget.h" +#include "CommonFramework/Startup/NewVersionCheck.h" +#include "CommonFramework/Panels/PanelTools.h" +#include "CommonFramework/Panels/UI/PanelElements.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramOption.h" +#include "NintendoSwitch_SingleSwitchProgramWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SingleSwitchProgramWidget2::~SingleSwitchProgramWidget2(){ + m_session.remove_listener(*this); + delete m_actions_bar; + delete m_stats_bar; + delete m_options; + delete m_system; +} +SingleSwitchProgramWidget2::SingleSwitchProgramWidget2( + QWidget& parent, + SingleSwitchProgramOption& option, + PanelHolder& holder +) + : QWidget(&parent) + , m_holder(holder) + , m_session(option, 0) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + + const SingleSwitchProgramDescriptor& descriptor = option.descriptor(); + + CollapsibleGroupBox* header = make_panel_header( + *this, + descriptor.display_name(), + descriptor.doc_link(), + descriptor.description(), + descriptor.required_features(), + descriptor.faster_if_tick_precise() + ); + layout->addWidget(header); + + + { + QScrollArea* scroll_outer = new QScrollArea(this); + layout->addWidget(scroll_outer); + scroll_outer->setWidgetResizable(true); + + QWidget* scroll_inner = new QWidget(scroll_outer); + scroll_outer->setWidget(scroll_inner); + QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); + scroll_layout->setAlignment(Qt::AlignTop); + + m_system = new SwitchSystemWidget( + *this, + m_session.system(), + m_session.instance_id() + ); + scroll_layout->addWidget(m_system); + + m_options = option.options().make_QtWidget(*this); + scroll_layout->addWidget(&m_options->widget()); + + scroll_layout->addStretch(1); + } + + m_stats_bar = new StatsBar(*this); + m_stats_bar->set_stats("", m_session.historical_stats()); + layout->addWidget(m_stats_bar); + + m_actions_bar = new RunnablePanelActionBar(*this, m_session.current_state()); + layout->addWidget(m_actions_bar); + + connect( + m_actions_bar, &RunnablePanelActionBar::start_clicked, + this, [&](ProgramState state){ + std::string error; + switch (state){ + case ProgramState::STOPPED: + error = m_session.start_program(); + break; + case ProgramState::RUNNING: + error = m_session.stop_program(); + break; + default:; + } + if (!error.empty()){ + this->error(error); + } + } + ); + connect( + m_actions_bar, &RunnablePanelActionBar::defaults_clicked, + this, [&]{ + std::lock_guard lg(m_session.program_lock()); + option.restore_defaults(); + m_options->update_all(false); + } + ); + + m_session.add_listener(*this); +} + +void SingleSwitchProgramWidget2::state_change(ProgramState state){ + QMetaObject::invokeMethod(this, [this, state]{ + m_system->update_ui(state); + m_options->option().report_program_state(state != ProgramState::STOPPED); +// cout << "state = " << (state != ProgramState::STOPPED) << endl; +// if (m_option.descriptor().lock_options_while_running()){ +// m_options->widget().setEnabled(state == ProgramState::STOPPED); +// } + m_actions_bar->set_state(state); + if (state == ProgramState::STOPPED){ + m_holder.on_idle(); + check_new_version(); + }else{ + m_holder.on_busy(); + } + }); +} +void SingleSwitchProgramWidget2::stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats){ + QMetaObject::invokeMethod(this, [this, current_stats, historical_stats]{ + m_stats_bar->set_stats( + current_stats == nullptr ? "" : current_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN), + historical_stats == nullptr ? "" : historical_stats->to_str(StatsTracker::DISPLAY_ON_SCREEN) + ); + }); +} +void SingleSwitchProgramWidget2::error(const std::string& message){ + QMetaObject::invokeMethod(this, [message]{ + QMessageBox box; + box.critical(nullptr, "Error", QString::fromStdString(message)); + }); +} + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h index e907d76b36..cd0c40073c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SingleSwitchProgramWidget.h @@ -1,63 +1,63 @@ -/* Single Switch Program Widget - * - * From: https://github.com/PokemonAutomation/ - * - * This is the Qt Widget implementation of the UI for SwitchSystemSession. - * - * On construction, this class attaches itself to the session it is constructed - * with and automatically detaches on destruction. Therefore, this class must - * not outlive the session it is constructed with. While not useful, it is also - * safe to construct multiple UI classes attached to the same session. - * - * Modifications directly to the session object will automatically update this - * UI class. For example, if you use Discord to change the volume of the - * audio playback, it will move the slider as shown by this UI. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramWidget_H -#define PokemonAutomation_NintendoSwitch_SingleSwitchProgramWidget_H - -#include "CommonFramework/Panels/UI/PanelElements.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h" -#include "NintendoSwitch_SwitchSystemWidget.h" - -namespace PokemonAutomation{ - struct PanelHolder; -namespace NintendoSwitch{ - - - -class SingleSwitchProgramWidget2 : public QWidget, private ProgramSession::Listener{ -public: - ~SingleSwitchProgramWidget2(); - SingleSwitchProgramWidget2( - QWidget& parent, - SingleSwitchProgramOption& option, - PanelHolder& holder - ); - -private: - virtual void state_change(ProgramState state) override; - virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) override; - virtual void error(const std::string& message) override; - -private: - PanelHolder& m_holder; - SingleSwitchProgramSession m_session; - SwitchSystemWidget* m_system; - ConfigWidget* m_options; - StatsBar* m_stats_bar; - RunnablePanelActionBar* m_actions_bar; -}; - - - - - - - -} -} -#endif +/* Single Switch Program Widget + * + * From: https://github.com/PokemonAutomation/ + * + * This is the Qt Widget implementation of the UI for SwitchSystemSession. + * + * On construction, this class attaches itself to the session it is constructed + * with and automatically detaches on destruction. Therefore, this class must + * not outlive the session it is constructed with. While not useful, it is also + * safe to construct multiple UI classes attached to the same session. + * + * Modifications directly to the session object will automatically update this + * UI class. For example, if you use Discord to change the volume of the + * audio playback, it will move the slider as shown by this UI. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgramWidget_H +#define PokemonAutomation_NintendoSwitch_SingleSwitchProgramWidget_H + +#include "CommonFramework/Panels/UI/PanelElements.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramSession.h" +#include "NintendoSwitch_SwitchSystemWidget.h" + +namespace PokemonAutomation{ + struct PanelHolder; +namespace NintendoSwitch{ + + + +class SingleSwitchProgramWidget2 : public QWidget, private ProgramSession::Listener{ +public: + ~SingleSwitchProgramWidget2(); + SingleSwitchProgramWidget2( + QWidget& parent, + SingleSwitchProgramOption& option, + PanelHolder& holder + ); + +private: + virtual void state_change(ProgramState state) override; + virtual void stats_update(const StatsTracker* current_stats, const StatsTracker* historical_stats) override; + virtual void error(const std::string& message) override; + +private: + PanelHolder& m_holder; + SingleSwitchProgramSession m_session; + SwitchSystemWidget* m_system; + ConfigWidget* m_options; + StatsBar* m_stats_bar; + RunnablePanelActionBar* m_actions_bar; +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp index 17a040e694..37d6012986 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.cpp @@ -1,247 +1,247 @@ -/* Switch System - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Concurrency/FireForgetDispatcher.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/CollapsibleGroupBox.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h" -#include "CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h" -#include "CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h" -#include "CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h" -#include "Controllers/ControllerSelectorWidget.h" -#include "NintendoSwitch_CommandRow.h" -#include "NintendoSwitch_SwitchSystemWidget.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SwitchSystemWidget::~SwitchSystemWidget(){ - // Delete all the UI elements first since they reference the states. - delete m_audio_display; - delete m_audio_widget; - delete m_video_display; - delete m_video_selector; - delete m_controller; -} - -SwitchSystemWidget::SwitchSystemWidget( - QWidget& parent, - SwitchSystemSession& session, - uint64_t program_id -) - : QWidget(&parent) - , m_session(session) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->setAlignment(Qt::AlignTop); - - m_group_box = new CollapsibleGroupBox(*this, "Console " + QString::number(m_session.console_number()) + " Settings"); - layout->addWidget(m_group_box); - - QWidget* widget = new QWidget(m_group_box); - m_group_box->set_widget(widget); - { - m_audio_display = new AudioDisplayWidget(*this, m_session.logger(), m_session.audio_session()); - layout->addWidget(m_audio_display); - - QVBoxLayout* video_holder = new QVBoxLayout(); - layout->addLayout(video_holder); - video_holder->setContentsMargins(0, 0, 0, 0); - - m_video_display = new VideoDisplayWidget( - *this, *video_holder, - m_session.console_number(), - *this, - m_session.video_session(), - m_session.overlay_session() - ); - video_holder->addWidget(m_video_display); - } - { - QVBoxLayout* group_layout = new QVBoxLayout(widget); - group_layout->setAlignment(Qt::AlignTop); - group_layout->setContentsMargins(0, 0, 0, 0); - - m_controller = new ControllerSelectorWidget(*this, m_session.controller_session()); - group_layout->addWidget(m_controller); - - m_video_selector = new VideoSourceSelectorWidget(m_session.logger(), m_session.video_session()); - group_layout->addWidget(m_video_selector); - - m_audio_widget = new AudioSelectorWidget(*widget, m_session.audio_session()); - group_layout->addWidget(m_audio_widget); - -#if 0 - // Experiment with multiple controller layouts. - m_controller = new ControllerSelectorWidget(*this, m_session.controller_session()); - group_layout->addWidget(m_controller); - - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); - group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); -#endif - - m_command = new CommandRow( - *widget, - m_session.controller_session(), - m_session.overlay_session(), - m_session.console_type(), - m_session.allow_commands_while_running() - ); - group_layout->addWidget(m_command); - } - - setFocusPolicy(Qt::StrongFocus); - - -// connect( -// m_serial_widget, &SerialPortWidget::signal_on_ready, -// m_command, [this](bool ready){ -// m_command->update_ui(); -// } -// ); - connect( - m_command, &CommandRow::load_profile, - m_command, [this](){ - std::string path = QFileDialog::getOpenFileName(this, tr("Choose the name of your profile file"), "", tr("JSON files (*.json)")).toStdString(); - if (path.empty()){ - return; - } - - SwitchSystemOption option( - m_session.required_features(), - m_session.allow_commands_while_running() - ); - - // Deserialize into this local option instance. - option.load_json(load_json_file(path)); - - m_session.set(option); - } - ); - connect( - m_command, &CommandRow::save_profile, - m_command, [this](){ - std::string path = QFileDialog::getSaveFileName(this, tr("Choose the name of your profile file"), "", tr("JSON files (*.json)")).toStdString(); - if (path.empty()){ - return; - } - - // Create a copy of option, to be able to serialize it later on - SwitchSystemOption option( - m_session.required_features(), - m_session.allow_commands_while_running() - ); - - m_session.get(option); - - option.to_json().dump(path); - } - ); - connect( - m_command, &CommandRow::screenshot_requested, - m_video_display, [this](){ - global_dispatcher.dispatch([this]{ - VideoSnapshot image = m_session.video_session().snapshot(); - if (!image){ - return; - } - std::string filename = SCREENSHOTS_PATH() + "screenshot-" + now_to_filestring() + ".png"; - m_session.logger().log("Saving screenshot to: " + filename, COLOR_PURPLE); - image->save(filename); - }); - } - ); - connect( - m_command, &CommandRow::video_requested, - m_video_display, [this](){ - global_dispatcher.dispatch([this]{ - std::string filename = SCREENSHOTS_PATH() + "video-" + now_to_filestring() + ".mp4"; - m_session.logger().log("Saving screenshot to: " + filename, COLOR_PURPLE); - m_session.save_history(filename); - }); - } - ); -} - - -void SwitchSystemWidget::update_ui(ProgramState state){ - m_session.controller_session().set_options_locked(state != ProgramState::STOPPED); - if (m_session.allow_commands_while_running()){ - m_session.set_allow_user_commands(""); - }else{ - switch (state){ - case ProgramState::NOT_READY: - m_session.set_allow_user_commands("Program is not ready."); - break; - case ProgramState::STOPPED: - m_session.set_allow_user_commands(""); - break; - case ProgramState::RUNNING: - case ProgramState::STOPPING: - m_session.set_allow_user_commands("Program is running."); - break; - } - } - m_command->on_state_changed(state); -} - -void SwitchSystemWidget::key_press(QKeyEvent* event){ -// cout << "press: " << event->nativeVirtualKey() << endl; - m_command->on_key_press(*event); -} - -void SwitchSystemWidget::key_release(QKeyEvent* event){ -// cout << "release: " << event->nativeVirtualKey() << endl; - m_command->on_key_release(*event); -} - -void SwitchSystemWidget::focus_in(QFocusEvent* event){ - m_command->set_focus(true); -} - -void SwitchSystemWidget::focus_out(QFocusEvent* event){ - m_command->set_focus(false); -} - -void SwitchSystemWidget::keyPressEvent(QKeyEvent* event){ - key_press(event); -} -void SwitchSystemWidget::keyReleaseEvent(QKeyEvent* event){ - key_release(event); -} -void SwitchSystemWidget::focusInEvent(QFocusEvent* event){ -// cout << "focusInEvent" << endl; - focus_in(event); - QWidget::focusInEvent(event); -} -void SwitchSystemWidget::focusOutEvent(QFocusEvent* event){ -// cout << "focusOutEvent" << endl; - focus_out(event); - QWidget::focusOutEvent(event); -} - - - -} -} +/* Switch System + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Concurrency/FireForgetDispatcher.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/CollapsibleGroupBox.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/AudioPipeline/UI/AudioSelectorWidget.h" +#include "CommonFramework/AudioPipeline/UI/AudioDisplayWidget.h" +#include "CommonFramework/VideoPipeline/UI/VideoSourceSelectorWidget.h" +#include "CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h" +#include "Controllers/ControllerSelectorWidget.h" +#include "NintendoSwitch_CommandRow.h" +#include "NintendoSwitch_SwitchSystemWidget.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SwitchSystemWidget::~SwitchSystemWidget(){ + // Delete all the UI elements first since they reference the states. + delete m_audio_display; + delete m_audio_widget; + delete m_video_display; + delete m_video_selector; + delete m_controller; +} + +SwitchSystemWidget::SwitchSystemWidget( + QWidget& parent, + SwitchSystemSession& session, + uint64_t program_id +) + : QWidget(&parent) + , m_session(session) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->setAlignment(Qt::AlignTop); + + m_group_box = new CollapsibleGroupBox(*this, "Console " + QString::number(m_session.console_number()) + " Settings"); + layout->addWidget(m_group_box); + + QWidget* widget = new QWidget(m_group_box); + m_group_box->set_widget(widget); + { + m_audio_display = new AudioDisplayWidget(*this, m_session.logger(), m_session.audio_session()); + layout->addWidget(m_audio_display); + + QVBoxLayout* video_holder = new QVBoxLayout(); + layout->addLayout(video_holder); + video_holder->setContentsMargins(0, 0, 0, 0); + + m_video_display = new VideoDisplayWidget( + *this, *video_holder, + m_session.console_number(), + *this, + m_session.video_session(), + m_session.overlay_session() + ); + video_holder->addWidget(m_video_display); + } + { + QVBoxLayout* group_layout = new QVBoxLayout(widget); + group_layout->setAlignment(Qt::AlignTop); + group_layout->setContentsMargins(0, 0, 0, 0); + + m_controller = new ControllerSelectorWidget(*this, m_session.controller_session()); + group_layout->addWidget(m_controller); + + m_video_selector = new VideoSourceSelectorWidget(m_session.logger(), m_session.video_session()); + group_layout->addWidget(m_video_selector); + + m_audio_widget = new AudioSelectorWidget(*widget, m_session.audio_session()); + group_layout->addWidget(m_audio_widget); + +#if 0 + // Experiment with multiple controller layouts. + m_controller = new ControllerSelectorWidget(*this, m_session.controller_session()); + group_layout->addWidget(m_controller); + + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); + group_layout->addWidget(new ControllerSelectorWidget(*this, m_session.controller_session())); +#endif + + m_command = new CommandRow( + *widget, + m_session.controller_session(), + m_session.overlay_session(), + m_session.console_type(), + m_session.allow_commands_while_running() + ); + group_layout->addWidget(m_command); + } + + setFocusPolicy(Qt::StrongFocus); + + +// connect( +// m_serial_widget, &SerialPortWidget::signal_on_ready, +// m_command, [this](bool ready){ +// m_command->update_ui(); +// } +// ); + connect( + m_command, &CommandRow::load_profile, + m_command, [this](){ + std::string path = QFileDialog::getOpenFileName(this, tr("Choose the name of your profile file"), "", tr("JSON files (*.json)")).toStdString(); + if (path.empty()){ + return; + } + + SwitchSystemOption option( + m_session.required_features(), + m_session.allow_commands_while_running() + ); + + // Deserialize into this local option instance. + option.load_json(load_json_file(path)); + + m_session.set(option); + } + ); + connect( + m_command, &CommandRow::save_profile, + m_command, [this](){ + std::string path = QFileDialog::getSaveFileName(this, tr("Choose the name of your profile file"), "", tr("JSON files (*.json)")).toStdString(); + if (path.empty()){ + return; + } + + // Create a copy of option, to be able to serialize it later on + SwitchSystemOption option( + m_session.required_features(), + m_session.allow_commands_while_running() + ); + + m_session.get(option); + + option.to_json().dump(path); + } + ); + connect( + m_command, &CommandRow::screenshot_requested, + m_video_display, [this](){ + global_dispatcher.dispatch([this]{ + VideoSnapshot image = m_session.video_session().snapshot(); + if (!image){ + return; + } + std::string filename = SCREENSHOTS_PATH() + "screenshot-" + now_to_filestring() + ".png"; + m_session.logger().log("Saving screenshot to: " + filename, COLOR_PURPLE); + image->save(filename); + }); + } + ); + connect( + m_command, &CommandRow::video_requested, + m_video_display, [this](){ + global_dispatcher.dispatch([this]{ + std::string filename = SCREENSHOTS_PATH() + "video-" + now_to_filestring() + ".mp4"; + m_session.logger().log("Saving screenshot to: " + filename, COLOR_PURPLE); + m_session.save_history(filename); + }); + } + ); +} + + +void SwitchSystemWidget::update_ui(ProgramState state){ + m_session.controller_session().set_options_locked(state != ProgramState::STOPPED); + if (m_session.allow_commands_while_running()){ + m_session.set_allow_user_commands(""); + }else{ + switch (state){ + case ProgramState::NOT_READY: + m_session.set_allow_user_commands("Program is not ready."); + break; + case ProgramState::STOPPED: + m_session.set_allow_user_commands(""); + break; + case ProgramState::RUNNING: + case ProgramState::STOPPING: + m_session.set_allow_user_commands("Program is running."); + break; + } + } + m_command->on_state_changed(state); +} + +void SwitchSystemWidget::key_press(QKeyEvent* event){ +// cout << "press: " << event->nativeVirtualKey() << endl; + m_command->on_key_press(*event); +} + +void SwitchSystemWidget::key_release(QKeyEvent* event){ +// cout << "release: " << event->nativeVirtualKey() << endl; + m_command->on_key_release(*event); +} + +void SwitchSystemWidget::focus_in(QFocusEvent* event){ + m_command->set_focus(true); +} + +void SwitchSystemWidget::focus_out(QFocusEvent* event){ + m_command->set_focus(false); +} + +void SwitchSystemWidget::keyPressEvent(QKeyEvent* event){ + key_press(event); +} +void SwitchSystemWidget::keyReleaseEvent(QKeyEvent* event){ + key_release(event); +} +void SwitchSystemWidget::focusInEvent(QFocusEvent* event){ +// cout << "focusInEvent" << endl; + focus_in(event); + QWidget::focusInEvent(event); +} +void SwitchSystemWidget::focusOutEvent(QFocusEvent* event){ +// cout << "focusOutEvent" << endl; + focus_out(event); + QWidget::focusOutEvent(event); +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h index 0216c143c0..e67b55a29e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h @@ -1,96 +1,96 @@ -/* Switch System - * - * From: https://github.com/PokemonAutomation/ - * - * This is the Qt Widget implementation of the UI for SwitchSystemSession. - * - * On construction, this class attaches itself to the session it is constructed - * with and automatically detaches on destruction. Therefore, this class must - * not outlive the session it is constructed with. While not useful, it is also - * safe to construct multiple UI classes attached to the same session. - * - * Modifications directly to the session object will automatically update this - * UI class. For example, if you use Discord to change the volume of the - * audio playback, it will move the slider as shown by this UI. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SwitchSystemWidget_H -#define PokemonAutomation_NintendoSwitch_SwitchSystemWidget_H - -#include -#include "CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" - -namespace PokemonAutomation{ - class CollapsibleGroupBox; - class AudioFeed; - class ControllerSelectorWidget; - class CameraSelectorWidget; - class VideoSourceSelectorWidget; - class VideoDisplayWidget; - class AudioDisplayWidget; - class VideoOverlay; - -namespace NintendoSwitch{ - -class CommandRow; - -// UI widget for controlling and monitoring a Nintendo Switch. -// It includes: -// - A micro-controller selection UI -// - Video source selection UI -// - Audio source selection UI -// - Audio display -// - Video stream display -// It also owns a SwitchSystemSession that manages the life time of the controller, -// audio and video streams that will be exposed to automation programs. -class SwitchSystemWidget final : public QWidget, public CommandReceiver{ -public: - virtual ~SwitchSystemWidget(); - SwitchSystemWidget( - QWidget& parent, - SwitchSystemSession& session, - uint64_t program_id - ); - -public: - void update_ui(ProgramState state); - - // The public versions of the private QWidget key and focus event handling functions. - // They are needed to accept key and focus passed from CommonFramework/VideoPipeline/UI:VideoDisplayWindow. - - virtual void key_press(QKeyEvent* event) override; - virtual void key_release(QKeyEvent* event) override; - - virtual void focus_in(QFocusEvent* event) override; - virtual void focus_out(QFocusEvent* event) override; - -private: - virtual void keyPressEvent(QKeyEvent* event) override; - virtual void keyReleaseEvent(QKeyEvent* event) override; - virtual void focusInEvent(QFocusEvent* event) override; - virtual void focusOutEvent(QFocusEvent* event) override; - -private: - SwitchSystemSession& m_session; - - CollapsibleGroupBox* m_group_box; - - ControllerSelectorWidget* m_controller; - - VideoDisplayWidget* m_video_display; - AudioDisplayWidget* m_audio_display; - - CommandRow* m_command; - - VideoSourceSelectorWidget* m_video_selector; - AudioSelectorWidget* m_audio_widget; -}; - - - - -} -} -#endif +/* Switch System + * + * From: https://github.com/PokemonAutomation/ + * + * This is the Qt Widget implementation of the UI for SwitchSystemSession. + * + * On construction, this class attaches itself to the session it is constructed + * with and automatically detaches on destruction. Therefore, this class must + * not outlive the session it is constructed with. While not useful, it is also + * safe to construct multiple UI classes attached to the same session. + * + * Modifications directly to the session object will automatically update this + * UI class. For example, if you use Discord to change the volume of the + * audio playback, it will move the slider as shown by this UI. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SwitchSystemWidget_H +#define PokemonAutomation_NintendoSwitch_SwitchSystemWidget_H + +#include +#include "CommonFramework/VideoPipeline/UI/VideoDisplayWidget.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" + +namespace PokemonAutomation{ + class CollapsibleGroupBox; + class AudioFeed; + class ControllerSelectorWidget; + class CameraSelectorWidget; + class VideoSourceSelectorWidget; + class VideoDisplayWidget; + class AudioDisplayWidget; + class VideoOverlay; + +namespace NintendoSwitch{ + +class CommandRow; + +// UI widget for controlling and monitoring a Nintendo Switch. +// It includes: +// - A micro-controller selection UI +// - Video source selection UI +// - Audio source selection UI +// - Audio display +// - Video stream display +// It also owns a SwitchSystemSession that manages the life time of the controller, +// audio and video streams that will be exposed to automation programs. +class SwitchSystemWidget final : public QWidget, public CommandReceiver{ +public: + virtual ~SwitchSystemWidget(); + SwitchSystemWidget( + QWidget& parent, + SwitchSystemSession& session, + uint64_t program_id + ); + +public: + void update_ui(ProgramState state); + + // The public versions of the private QWidget key and focus event handling functions. + // They are needed to accept key and focus passed from CommonFramework/VideoPipeline/UI:VideoDisplayWindow. + + virtual void key_press(QKeyEvent* event) override; + virtual void key_release(QKeyEvent* event) override; + + virtual void focus_in(QFocusEvent* event) override; + virtual void focus_out(QFocusEvent* event) override; + +private: + virtual void keyPressEvent(QKeyEvent* event) override; + virtual void keyReleaseEvent(QKeyEvent* event) override; + virtual void focusInEvent(QFocusEvent* event) override; + virtual void focusOutEvent(QFocusEvent* event) override; + +private: + SwitchSystemSession& m_session; + + CollapsibleGroupBox* m_group_box; + + ControllerSelectorWidget* m_controller; + + VideoDisplayWidget* m_video_display; + AudioDisplayWidget* m_audio_display; + + CommandRow* m_command; + + VideoSourceSelectorWidget* m_video_selector; + AudioSelectorWidget* m_audio_widget; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp index 97ee9e2c54..5e5ad212f3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.cpp @@ -1,89 +1,89 @@ -/* Binary Slider Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "NintendoSwitch2_BinarySliderDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -BinarySliderDetector::BinarySliderDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} -void BinarySliderDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -std::vector> BinarySliderDetector::detect(const ImageViewRGB32& image) const{ - using namespace Kernels::Waterfill; - - static ImageMatch::ExactImageMatcher LIGHT_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-Cursor.png"); - static ImageMatch::ExactImageMatcher LIGHT_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-NoCursor.png"); - static ImageMatch::ExactImageMatcher LIGHT_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-Cursor.png"); - static ImageMatch::ExactImageMatcher LIGHT_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-NoCursor.png"); - static ImageMatch::ExactImageMatcher DARK_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-Cursor.png"); - static ImageMatch::ExactImageMatcher DARK_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-NoCursor.png"); - static ImageMatch::ExactImageMatcher DARK_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-Cursor.png"); - static ImageMatch::ExactImageMatcher DARK_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-NoCursor.png"); - - ImageViewRGB32 region = extract_box_reference(image, m_box); - - auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(200); - WaterfillObject object; - - std::vector> ret; - - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 0.9 || aspect_ratio > 1.1){ - continue; - } - ImageViewRGB32 cropped = extract_box_reference(region, object); - - double best_off_rmsd = 9999; - best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_CURSOR.rmsd(cropped)); - best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_NOCURSOR.rmsd(cropped)); - best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_CURSOR.rmsd(cropped)); - best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_NOCURSOR.rmsd(cropped)); - - double best_on_rmsd = 9999; - best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_CURSOR.rmsd(cropped)); - best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_NOCURSOR.rmsd(cropped)); - best_on_rmsd = std::min(best_on_rmsd, DARK_ON_CURSOR.rmsd(cropped)); - best_on_rmsd = std::min(best_on_rmsd, DARK_ON_NOCURSOR.rmsd(cropped)); - -// cout << "best_off_rmsd = " << best_off_rmsd << endl; -// cout << "best_on_rmsd = " << best_on_rmsd << endl; - - bool on = best_on_rmsd < best_off_rmsd; - double best = on ? best_on_rmsd : best_off_rmsd; - - if (best < 60){ - ret.emplace_back(on, object); - } - - } - - return ret; -} - - - -} -} +/* Binary Slider Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "NintendoSwitch2_BinarySliderDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +BinarySliderDetector::BinarySliderDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} +void BinarySliderDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +std::vector> BinarySliderDetector::detect(const ImageViewRGB32& image) const{ + using namespace Kernels::Waterfill; + + static ImageMatch::ExactImageMatcher LIGHT_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-Cursor.png"); + static ImageMatch::ExactImageMatcher LIGHT_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-Off-NoCursor.png"); + static ImageMatch::ExactImageMatcher LIGHT_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-Cursor.png"); + static ImageMatch::ExactImageMatcher LIGHT_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Light-On-NoCursor.png"); + static ImageMatch::ExactImageMatcher DARK_OFF_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-Cursor.png"); + static ImageMatch::ExactImageMatcher DARK_OFF_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-Off-NoCursor.png"); + static ImageMatch::ExactImageMatcher DARK_ON_CURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-Cursor.png"); + static ImageMatch::ExactImageMatcher DARK_ON_NOCURSOR (RESOURCE_PATH() + "NintendoSwitch2/BinarySlider-Dark-On-NoCursor.png"); + + ImageViewRGB32 region = extract_box_reference(image, m_box); + + auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(200); + WaterfillObject object; + + std::vector> ret; + + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 0.9 || aspect_ratio > 1.1){ + continue; + } + ImageViewRGB32 cropped = extract_box_reference(region, object); + + double best_off_rmsd = 9999; + best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_CURSOR.rmsd(cropped)); + best_off_rmsd = std::min(best_off_rmsd, LIGHT_OFF_NOCURSOR.rmsd(cropped)); + best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_CURSOR.rmsd(cropped)); + best_off_rmsd = std::min(best_off_rmsd, DARK_OFF_NOCURSOR.rmsd(cropped)); + + double best_on_rmsd = 9999; + best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_CURSOR.rmsd(cropped)); + best_on_rmsd = std::min(best_on_rmsd, LIGHT_ON_NOCURSOR.rmsd(cropped)); + best_on_rmsd = std::min(best_on_rmsd, DARK_ON_CURSOR.rmsd(cropped)); + best_on_rmsd = std::min(best_on_rmsd, DARK_ON_NOCURSOR.rmsd(cropped)); + +// cout << "best_off_rmsd = " << best_off_rmsd << endl; +// cout << "best_on_rmsd = " << best_on_rmsd << endl; + + bool on = best_on_rmsd < best_off_rmsd; + double best = on ? best_on_rmsd : best_off_rmsd; + + if (best < 60){ + ret.emplace_back(on, object); + } + + } + + return ret; +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h index 0c45c26087..561022ed62 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h @@ -1,37 +1,37 @@ -/* Binary Slider Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H -#define PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class BinarySliderDetector{ -public: - BinarySliderDetector(Color color, const ImageFloatBox& box); - void make_overlays(VideoOverlaySet& items) const; - - std::vector> detect(const ImageViewRGB32& image) const; - -private: - Color m_color; - ImageFloatBox m_box; -}; - - - - -} -} -#endif +/* Binary Slider Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H +#define PokemonAutomation_NintendoSwitch2_BinarySliderDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class BinarySliderDetector{ +public: + BinarySliderDetector(Color color, const ImageFloatBox& box); + void make_overlays(VideoOverlaySet& items) const; + + std::vector> detect(const ImageViewRGB32& image) const; + +private: + Color m_color; + ImageFloatBox m_box; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp index 87a8398d3e..127ff5256e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.cpp @@ -1,90 +1,90 @@ -/* Console Type Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -ConsoleTypeDetector_Home::ConsoleTypeDetector_Home(ConsoleHandle& console, Color color) - : m_console(console) - , m_color(color) - , m_bottom_line(0.10, 0.88, 0.80, 0.03) - , m_last(ConsoleType::Unknown) -{} -void ConsoleTypeDetector_Home::make_overlays(VideoOverlaySet& items) const{ - ConsoleType known_state = m_console.state().console_type(); - if (known_state != ConsoleType::Unknown){ - return; - } - items.add(m_color, m_bottom_line); -} -ConsoleType ConsoleTypeDetector_Home::detect_only(const ImageViewRGB32& screen){ - if (m_console.state().console_type_confirmed()){ - ConsoleType state = m_console.state().console_type(); - m_last = state; - return state; - } - - ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); -// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; - ConsoleType state; - if (stats.stddev.sum() < 10){ - state = ConsoleType::Switch2_Unknown; - }else{ - state = ConsoleType::Switch1; - } - m_last = state; - return state; -} -void ConsoleTypeDetector_Home::commit_to_cache(){ - if (m_last != ConsoleType::Unknown){ - m_console.state().set_console_type(m_console, m_last); - } -} - - - -ConsoleTypeDetector_StartGameUserSelect::ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color) - : m_console(console) - , m_color(color) - , m_bottom_line(0.02, 0.53, 0.96, 0.03) -{} -void ConsoleTypeDetector_StartGameUserSelect::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_line); -} -ConsoleType ConsoleTypeDetector_StartGameUserSelect::detect_only(const ImageViewRGB32& screen){ - if (m_console.state().console_type_confirmed()){ - return m_console.state().console_type(); - } - - ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); -// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; - ConsoleType state; - if (stats.stddev.sum() < 10){ - state = ConsoleType::Switch2_Unknown; - }else{ - state = ConsoleType::Switch1; - } - m_last = state; - return state; -} -void ConsoleTypeDetector_StartGameUserSelect::commit_to_cache(){ - m_console.state().set_console_type(m_console, m_last); -} - - - - -} -} +/* Console Type Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +ConsoleTypeDetector_Home::ConsoleTypeDetector_Home(ConsoleHandle& console, Color color) + : m_console(console) + , m_color(color) + , m_bottom_line(0.10, 0.88, 0.80, 0.03) + , m_last(ConsoleType::Unknown) +{} +void ConsoleTypeDetector_Home::make_overlays(VideoOverlaySet& items) const{ + ConsoleType known_state = m_console.state().console_type(); + if (known_state != ConsoleType::Unknown){ + return; + } + items.add(m_color, m_bottom_line); +} +ConsoleType ConsoleTypeDetector_Home::detect_only(const ImageViewRGB32& screen){ + if (m_console.state().console_type_confirmed()){ + ConsoleType state = m_console.state().console_type(); + m_last = state; + return state; + } + + ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); +// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; + ConsoleType state; + if (stats.stddev.sum() < 10){ + state = ConsoleType::Switch2_Unknown; + }else{ + state = ConsoleType::Switch1; + } + m_last = state; + return state; +} +void ConsoleTypeDetector_Home::commit_to_cache(){ + if (m_last != ConsoleType::Unknown){ + m_console.state().set_console_type(m_console, m_last); + } +} + + + +ConsoleTypeDetector_StartGameUserSelect::ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color) + : m_console(console) + , m_color(color) + , m_bottom_line(0.02, 0.53, 0.96, 0.03) +{} +void ConsoleTypeDetector_StartGameUserSelect::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_line); +} +ConsoleType ConsoleTypeDetector_StartGameUserSelect::detect_only(const ImageViewRGB32& screen){ + if (m_console.state().console_type_confirmed()){ + return m_console.state().console_type(); + } + + ImageStats stats = image_stats(extract_box_reference(screen, m_bottom_line)); +// cout << "ConsoleTypeDetector: " << stats.stddev.sum() << endl; + ConsoleType state; + if (stats.stddev.sum() < 10){ + state = ConsoleType::Switch2_Unknown; + }else{ + state = ConsoleType::Switch1; + } + m_last = state; + return state; +} +void ConsoleTypeDetector_StartGameUserSelect::commit_to_cache(){ + m_console.state().set_console_type(m_console, m_last); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h index 47d34fc5e5..2b9dad8356 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h @@ -1,58 +1,58 @@ -/* Console Type Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H -#define PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class ConsoleTypeDetector_Home{ -public: - ConsoleTypeDetector_Home(ConsoleHandle& console, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - ConsoleType detect_only(const ImageViewRGB32& screen); - void commit_to_cache(); - -private: - ConsoleHandle& m_console; - Color m_color; - ImageFloatBox m_bottom_line; - ConsoleType m_last; -}; - -class ConsoleTypeDetector_StartGameUserSelect{ -public: - ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - ConsoleType detect_only(const ImageViewRGB32& screen); - void commit_to_cache(); - -private: - ConsoleHandle& m_console; - Color m_color; - ImageFloatBox m_bottom_line; - ConsoleType m_last; -}; - - - - - -} -} -#endif +/* Console Type Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H +#define PokemonAutomation_NintendoSwitch_ConsoleTypeDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class ConsoleTypeDetector_Home{ +public: + ConsoleTypeDetector_Home(ConsoleHandle& console, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + ConsoleType detect_only(const ImageViewRGB32& screen); + void commit_to_cache(); + +private: + ConsoleHandle& m_console; + Color m_color; + ImageFloatBox m_bottom_line; + ConsoleType m_last; +}; + +class ConsoleTypeDetector_StartGameUserSelect{ +public: + ConsoleTypeDetector_StartGameUserSelect(ConsoleHandle& console, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + ConsoleType detect_only(const ImageViewRGB32& screen); + void commit_to_cache(); + +private: + ConsoleHandle& m_console; + Color m_color; + ImageFloatBox m_bottom_line; + ConsoleType m_last; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp index d2436234b1..9c14ba016f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.cpp @@ -1,173 +1,173 @@ -/* Date Change Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch_DateChangeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -DateChangeDetector_Switch1::DateChangeDetector_Switch1(Color color) - : m_color(color) - , m_background_top(0.50, 0.02, 0.45, 0.08) - , m_window_top(0.50, 0.36, 0.45, 0.07) - , m_window_text(0.05, 0.36, 0.10, 0.07) - , m_jp_year(0.136, 0.61, 0.11, 0.09) - , m_us_hour(0.473, 0.61, 0.06, 0.09) - , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) -{} -void DateChangeDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_background_top); - items.add(m_color, m_window_top); - items.add(m_color, m_window_text); - items.add(m_color, m_jp_year); - items.add(m_color, m_us_hour); - items.add(m_color, m_jp_month_arrow); -} -bool DateChangeDetector_Switch1::detect(const ImageViewRGB32& screen){ - ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); - if (stats_background_top.stddev.sum() > 10){ -// cout << "asdf" << endl; - return false; - } - ImageStats stats_window_top = image_stats(extract_box_reference(screen, m_window_top)); -// cout << stats_window_top.average << stats_window_top.stddev << endl; - if (stats_window_top.stddev.sum() > 10){ -// cout << "qwer" << endl; - return false; - } - ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); -// cout << stats_window_text.stddev << endl; - if (stats_window_text.stddev.sum() < 100){ -// cout << "zxcv" << endl; - return false; - } -// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; -// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; - if (std::abs(stats_background_top.average.sum() - stats_window_top.average.sum()) < 50){ -// cout << "xcvb" << endl; - return false; - } - -// bool white_theme = stats_window_top.average.sum() > 600; - - ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); - ImageStats year_stats = image_stats(year_box); -// cout << year_stats.average << year_stats.stddev << endl; - - double stddev = year_stats.stddev.sum(); - if (stddev < 80){ -// cout << "sdfg" << endl; - return false; - } - - return true; -} -DateFormat DateChangeDetector_Switch1::detect_date_format(const ImageViewRGB32& screen) const{ - ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); - ImageStats stats_us_hours = image_stats(us_hours); - - if (stats_us_hours.stddev.sum() > 30){ - return DateFormat::US; - } - - ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); - ImageStats stats_arrow = image_stats(jp_arrow); - if (stats_arrow.stddev.sum() > 30){ - return DateFormat::JP; - } - - return DateFormat::EU; -} - - - -DateChangeDetector_Switch2::DateChangeDetector_Switch2(Color color) - : m_color(color) - , m_background_top(0.50, 0.02, 0.45, 0.08) - , m_window_bottom(0.50, 0.80, 0.45, 0.07) - , m_window_text(0.05, 0.02, 0.10, 0.08) - , m_jp_year(0.139, 0.436, 0.088, 0.095) - , m_us_hour(0.473, 0.61, 0.06, 0.09) - , m_jp_month_arrow(0.291705, 0.331675, 0.054986, 0.069652) -{} -void DateChangeDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_background_top); - items.add(m_color, m_window_bottom); - items.add(m_color, m_window_text); - items.add(m_color, m_jp_year); - items.add(m_color, m_us_hour); - items.add(m_color, m_jp_month_arrow); -} -bool DateChangeDetector_Switch2::detect(const ImageViewRGB32& screen){ - ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); - if (stats_background_top.stddev.sum() > 10){ -// cout << "asdf" << endl; - return false; - } - ImageStats stats_window_bottom = image_stats(extract_box_reference(screen, m_window_bottom)); -// cout << stats_window_bottom.average << stats_window_top.stddev << endl; - if (stats_window_bottom.stddev.sum() > 10){ -// cout << "qwer" << endl; - return false; - } - ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); -// cout << stats_window_text.stddev << endl; - if (stats_window_text.stddev.sum() < 100){ -// cout << "zxcv" << endl; - return false; - } -// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; -// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; - - if (euclidean_distance(stats_background_top.average, stats_window_bottom.average) > 10){ -// cout << "xcvb" << endl; - return false; - } - -// bool white_theme = stats_window_top.average.sum() > 600; - - ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); - ImageStats year_stats = image_stats(year_box); -// cout << year_stats.average << year_stats.stddev << endl; - - double stddev = year_stats.stddev.sum(); - if (stddev < 80){ -// cout << "sdfg" << endl; - return false; - } - - return true; -} -DateFormat DateChangeDetector_Switch2::detect_date_format(const ImageViewRGB32& screen) const{ - ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); - ImageStats stats_us_hours = image_stats(us_hours); - - if (stats_us_hours.stddev.sum() > 30){ - return DateFormat::US; - } - - ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); - ImageStats stats_arrow = image_stats(jp_arrow); - if (stats_arrow.stddev.sum() > 30){ - return DateFormat::JP; - } - - return DateFormat::EU; -} - - - - - - - -} -} +/* Date Change Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch_DateChangeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +DateChangeDetector_Switch1::DateChangeDetector_Switch1(Color color) + : m_color(color) + , m_background_top(0.50, 0.02, 0.45, 0.08) + , m_window_top(0.50, 0.36, 0.45, 0.07) + , m_window_text(0.05, 0.36, 0.10, 0.07) + , m_jp_year(0.136, 0.61, 0.11, 0.09) + , m_us_hour(0.473, 0.61, 0.06, 0.09) + , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) +{} +void DateChangeDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_background_top); + items.add(m_color, m_window_top); + items.add(m_color, m_window_text); + items.add(m_color, m_jp_year); + items.add(m_color, m_us_hour); + items.add(m_color, m_jp_month_arrow); +} +bool DateChangeDetector_Switch1::detect(const ImageViewRGB32& screen){ + ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); + if (stats_background_top.stddev.sum() > 10){ +// cout << "asdf" << endl; + return false; + } + ImageStats stats_window_top = image_stats(extract_box_reference(screen, m_window_top)); +// cout << stats_window_top.average << stats_window_top.stddev << endl; + if (stats_window_top.stddev.sum() > 10){ +// cout << "qwer" << endl; + return false; + } + ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); +// cout << stats_window_text.stddev << endl; + if (stats_window_text.stddev.sum() < 100){ +// cout << "zxcv" << endl; + return false; + } +// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; +// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; + if (std::abs(stats_background_top.average.sum() - stats_window_top.average.sum()) < 50){ +// cout << "xcvb" << endl; + return false; + } + +// bool white_theme = stats_window_top.average.sum() > 600; + + ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); + ImageStats year_stats = image_stats(year_box); +// cout << year_stats.average << year_stats.stddev << endl; + + double stddev = year_stats.stddev.sum(); + if (stddev < 80){ +// cout << "sdfg" << endl; + return false; + } + + return true; +} +DateFormat DateChangeDetector_Switch1::detect_date_format(const ImageViewRGB32& screen) const{ + ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); + ImageStats stats_us_hours = image_stats(us_hours); + + if (stats_us_hours.stddev.sum() > 30){ + return DateFormat::US; + } + + ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); + ImageStats stats_arrow = image_stats(jp_arrow); + if (stats_arrow.stddev.sum() > 30){ + return DateFormat::JP; + } + + return DateFormat::EU; +} + + + +DateChangeDetector_Switch2::DateChangeDetector_Switch2(Color color) + : m_color(color) + , m_background_top(0.50, 0.02, 0.45, 0.08) + , m_window_bottom(0.50, 0.80, 0.45, 0.07) + , m_window_text(0.05, 0.02, 0.10, 0.08) + , m_jp_year(0.139, 0.436, 0.088, 0.095) + , m_us_hour(0.473, 0.61, 0.06, 0.09) + , m_jp_month_arrow(0.291705, 0.331675, 0.054986, 0.069652) +{} +void DateChangeDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_background_top); + items.add(m_color, m_window_bottom); + items.add(m_color, m_window_text); + items.add(m_color, m_jp_year); + items.add(m_color, m_us_hour); + items.add(m_color, m_jp_month_arrow); +} +bool DateChangeDetector_Switch2::detect(const ImageViewRGB32& screen){ + ImageStats stats_background_top = image_stats(extract_box_reference(screen, m_background_top)); + if (stats_background_top.stddev.sum() > 10){ +// cout << "asdf" << endl; + return false; + } + ImageStats stats_window_bottom = image_stats(extract_box_reference(screen, m_window_bottom)); +// cout << stats_window_bottom.average << stats_window_top.stddev << endl; + if (stats_window_bottom.stddev.sum() > 10){ +// cout << "qwer" << endl; + return false; + } + ImageStats stats_window_text = image_stats(extract_box_reference(screen, m_window_text)); +// cout << stats_window_text.stddev << endl; + if (stats_window_text.stddev.sum() < 100){ +// cout << "zxcv" << endl; + return false; + } +// cout << "stats_background_top: " << stats_background_top.average.sum() << endl; +// cout << "stats_window_top: " << stats_window_top.average.sum() << endl; + + if (euclidean_distance(stats_background_top.average, stats_window_bottom.average) > 10){ +// cout << "xcvb" << endl; + return false; + } + +// bool white_theme = stats_window_top.average.sum() > 600; + + ImageViewRGB32 year_box = extract_box_reference(screen, m_jp_year); + ImageStats year_stats = image_stats(year_box); +// cout << year_stats.average << year_stats.stddev << endl; + + double stddev = year_stats.stddev.sum(); + if (stddev < 80){ +// cout << "sdfg" << endl; + return false; + } + + return true; +} +DateFormat DateChangeDetector_Switch2::detect_date_format(const ImageViewRGB32& screen) const{ + ImageViewRGB32 us_hours = extract_box_reference(screen, m_us_hour); + ImageStats stats_us_hours = image_stats(us_hours); + + if (stats_us_hours.stddev.sum() > 30){ + return DateFormat::US; + } + + ImageViewRGB32 jp_arrow = extract_box_reference(screen, m_jp_month_arrow); + ImageStats stats_arrow = image_stats(jp_arrow); + if (stats_arrow.stddev.sum() > 30){ + return DateFormat::JP; + } + + return DateFormat::EU; +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h index 4336f25bb6..7515de0658 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h @@ -1,71 +1,71 @@ -/* Date Change Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateChangeDetector_H -#define PokemonAutomation_NintendoSwitch_DateChangeDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -enum class DateFormat{ - US, - EU, - JP, -}; - - - - -class DateChangeDetector : public StaticScreenDetector{ -public: - virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const = 0; -}; -class DateChangeDetector_Switch1 : public DateChangeDetector{ -public: - DateChangeDetector_Switch1(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; - -private: - Color m_color; - ImageFloatBox m_background_top; - ImageFloatBox m_window_top; - ImageFloatBox m_window_text; - ImageFloatBox m_jp_year; - ImageFloatBox m_us_hour; - ImageFloatBox m_jp_month_arrow; -}; -class DateChangeDetector_Switch2 : public DateChangeDetector{ -public: - DateChangeDetector_Switch2(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; - -private: - Color m_color; - ImageFloatBox m_background_top; - ImageFloatBox m_window_bottom; - ImageFloatBox m_window_text; - ImageFloatBox m_jp_year; - ImageFloatBox m_us_hour; - ImageFloatBox m_jp_month_arrow; -}; - - - - -} -} -#endif +/* Date Change Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateChangeDetector_H +#define PokemonAutomation_NintendoSwitch_DateChangeDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +enum class DateFormat{ + US, + EU, + JP, +}; + + + + +class DateChangeDetector : public StaticScreenDetector{ +public: + virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const = 0; +}; +class DateChangeDetector_Switch1 : public DateChangeDetector{ +public: + DateChangeDetector_Switch1(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; + +private: + Color m_color; + ImageFloatBox m_background_top; + ImageFloatBox m_window_top; + ImageFloatBox m_window_text; + ImageFloatBox m_jp_year; + ImageFloatBox m_us_hour; + ImageFloatBox m_jp_month_arrow; +}; +class DateChangeDetector_Switch2 : public DateChangeDetector{ +public: + DateChangeDetector_Switch2(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + virtual DateFormat detect_date_format(const ImageViewRGB32& screen) const override; + +private: + Color m_color; + ImageFloatBox m_background_top; + ImageFloatBox m_window_bottom; + ImageFloatBox m_window_text; + ImageFloatBox m_jp_year; + ImageFloatBox m_us_hour; + ImageFloatBox m_jp_month_arrow; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.cpp index 045477b042..6ddfc2dda7 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.cpp @@ -1,145 +1,145 @@ -/* Detect Home - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_DetectHome.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - - - - - - - - - - - - -CheckOnlineDetector::CheckOnlineDetector(Color color, bool invert) - : m_color(color) - , m_invert(invert) - , m_box_top(0.25, 0.32, 0.50, 0.02) - , m_box_mid(0.25, 0.57, 0.50, 0.02) - , m_top(0.10, 0.15, 0.80, 0.03) - , m_left(0.08, 0.25, 0.10, 0.38) - , m_bottom_solid(0.10, 0.84, 0.80, 0.04) - , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) -{} -void CheckOnlineDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_top); - items.add(m_color, m_box_mid); - items.add(m_color, m_top); - items.add(m_color, m_left); - items.add(m_color, m_bottom_solid); - items.add(m_color, m_bottom_buttons); -} -bool CheckOnlineDetector::detect(const ImageViewRGB32& screen){ - ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); -// cout << stats_box_top.average << stats_box_top.stddev << endl; - bool white; - if (stats_box_top.average.sum() < 300){ - white = false; - }else if (stats_box_top.average.sum() > 500){ - white = true; - }else{ - return m_invert; - } - if (stats_box_top.stddev.sum() > 10){ - return m_invert; - } - -// cout << "white: " << white << endl; - - ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); - if (stats_box_mid.stddev.sum() > 10){ - return m_invert; - } - if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ - return m_invert; - } - - ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); -// cout << stats_left.stddev << endl; - if (stats_left.stddev.sum() < 30){ -// cout << "zxcv" << endl; - return m_invert; - } - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - - ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); -// cout << bottom_solid.average << bottom_solid.stddev << endl; - - if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ -// cout << "qwer" << endl; - return m_invert; - } - - if (white){ - if (!is_grey(stats_top, 100, 300) || !is_grey(bottom_solid, 100, 300)){ -// cout << "asdf" << endl; - return m_invert; - } - }else{ - if (!is_grey(stats_top, 0, 100) || !is_grey(bottom_solid, 0, 100)){ -// cout << "zxcv" << endl; - return m_invert; - } - } - - ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); -// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; - if (stats_bottom_buttons.stddev.sum() < 30){ - return m_invert; - } - - return !m_invert; -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Detect Home + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_DetectHome.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + + + + + + + + + + + + +CheckOnlineDetector::CheckOnlineDetector(Color color, bool invert) + : m_color(color) + , m_invert(invert) + , m_box_top(0.25, 0.32, 0.50, 0.02) + , m_box_mid(0.25, 0.57, 0.50, 0.02) + , m_top(0.10, 0.15, 0.80, 0.03) + , m_left(0.08, 0.25, 0.10, 0.38) + , m_bottom_solid(0.10, 0.84, 0.80, 0.04) + , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) +{} +void CheckOnlineDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_top); + items.add(m_color, m_box_mid); + items.add(m_color, m_top); + items.add(m_color, m_left); + items.add(m_color, m_bottom_solid); + items.add(m_color, m_bottom_buttons); +} +bool CheckOnlineDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); +// cout << stats_box_top.average << stats_box_top.stddev << endl; + bool white; + if (stats_box_top.average.sum() < 300){ + white = false; + }else if (stats_box_top.average.sum() > 500){ + white = true; + }else{ + return m_invert; + } + if (stats_box_top.stddev.sum() > 10){ + return m_invert; + } + +// cout << "white: " << white << endl; + + ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); + if (stats_box_mid.stddev.sum() > 10){ + return m_invert; + } + if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ + return m_invert; + } + + ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); +// cout << stats_left.stddev << endl; + if (stats_left.stddev.sum() < 30){ +// cout << "zxcv" << endl; + return m_invert; + } + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + + ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); +// cout << bottom_solid.average << bottom_solid.stddev << endl; + + if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ +// cout << "qwer" << endl; + return m_invert; + } + + if (white){ + if (!is_grey(stats_top, 100, 300) || !is_grey(bottom_solid, 100, 300)){ +// cout << "asdf" << endl; + return m_invert; + } + }else{ + if (!is_grey(stats_top, 0, 100) || !is_grey(bottom_solid, 0, 100)){ +// cout << "zxcv" << endl; + return m_invert; + } + } + + ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); +// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; + if (stats_bottom_buttons.stddev.sum() < 30){ + return m_invert; + } + + return !m_invert; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.h index 7109ee5693..a7bd4db27f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_DetectHome.h @@ -1,56 +1,56 @@ -/* Detect Home - * - * From: https://github.com/PokemonAutomation/ - * - * - * This file is in the process of being split up and refactored. - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DetectHome_H -#define PokemonAutomation_NintendoSwitch_DetectHome_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - - - - -// Detect the "Checking if the software can be played..." menu. -class CheckOnlineDetector : public StaticScreenDetector{ -public: - CheckOnlineDetector(Color color = COLOR_RED, bool invert = false); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - bool m_invert; - ImageFloatBox m_box_top; - ImageFloatBox m_box_mid; - ImageFloatBox m_top; - ImageFloatBox m_left; - ImageFloatBox m_bottom_solid; - ImageFloatBox m_bottom_buttons; -}; -class CheckOnlineWatcher : public DetectorToFinder{ -public: - CheckOnlineWatcher(Color color = COLOR_RED, bool invert = false) - : DetectorToFinder("CheckOnlineWatcher", std::chrono::milliseconds(250), color, invert) - {} -}; - - -} -} -#endif - +/* Detect Home + * + * From: https://github.com/PokemonAutomation/ + * + * + * This file is in the process of being split up and refactored. + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DetectHome_H +#define PokemonAutomation_NintendoSwitch_DetectHome_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + + + + +// Detect the "Checking if the software can be played..." menu. +class CheckOnlineDetector : public StaticScreenDetector{ +public: + CheckOnlineDetector(Color color = COLOR_RED, bool invert = false); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + bool m_invert; + ImageFloatBox m_box_top; + ImageFloatBox m_box_mid; + ImageFloatBox m_top; + ImageFloatBox m_left; + ImageFloatBox m_bottom_solid; + ImageFloatBox m_bottom_buttons; +}; +class CheckOnlineWatcher : public DetectorToFinder{ +public: + CheckOnlineWatcher(Color color = COLOR_RED, bool invert = false) + : DetectorToFinder("CheckOnlineWatcher", std::chrono::milliseconds(250), color, invert) + {} +}; + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp index f609545d17..e794fdd6cb 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.cpp @@ -1,141 +1,141 @@ -/* Home Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_HomeMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -HomeMenuDetector::HomeMenuDetector(ConsoleHandle& console, Color color) - : m_color(color) - , m_console_type(console, color) - , m_top(0.510223, 0.019835, 0.441450, 0.034711) - , m_bottom_row(0.10, 0.92, 0.10, 0.05) - , m_bottom_icons(0.70, 0.92, 0.28, 0.05) - , m_bottom_left(0.02, 0.70, 0.15, 0.15) - , m_bottom_right(0.83, 0.70, 0.15, 0.15) - , m_user_icons(0.05, 0.05, 0.2, 0.08) - , m_game_slot(0.08, 0.25, 0.10, 0.38) -{} -void HomeMenuDetector::make_overlays(VideoOverlaySet& items) const{ - m_console_type.make_overlays(items); - items.add(m_color, m_top); - items.add(m_color, m_bottom_row); - items.add(m_color, m_bottom_icons); - items.add(m_color, m_bottom_left); - items.add(m_color, m_bottom_right); - items.add(m_color, m_user_icons); - items.add(m_color, m_game_slot); -} - -// -// This miraculously works on both Switch 1 and Switch 2. -// -bool HomeMenuDetector::detect(const ImageViewRGB32& screen){ - if (detect_only(screen)){ - m_console_type.commit_to_cache(); - return true; - }else{ - return false; - } -} -bool HomeMenuDetector::detect_only(const ImageViewRGB32& screen){ - ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); -// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; - bool white; -// cout << "stats_bottom_row.average.sum() = " << stats_bottom_row.average.sum() << endl; - if (stats_bottom_row.average.sum() < 200){ - white = false; - }else if (stats_bottom_row.average.sum() > 500){ - white = true; - }else{ - return false; - } - -// cout << "white: " << white << endl; - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - if (stats_top.stddev.sum() > 20){ - return false; - } - - ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); -// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; - if (stats_bottom_icons.stddev.sum() < 50){ - return false; - } - - ImageStats stats_bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); - ImageStats stats_bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << stats_bottom_left.average << stats_bottom_left.stddev << endl; -// cout << stats_bottom_right.average << stats_bottom_right.stddev << endl; - if (white){ - if (!is_white(stats_bottom_left) || !is_white(stats_bottom_right)){ -// cout << "asdf" << endl; - return false; - } - }else{ - if (!is_grey(stats_bottom_left, 0, 200) || !is_grey(stats_bottom_right, 0, 200)){ -// cout << "qwer" << endl; - return false; - } - } - -// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; - if (euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) > 20){ -// cout << "qwer = " << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; - return false; - } -// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) << endl; - if (euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) > 20){ -// cout << "asdf" << endl; - return false; - } -// cout << euclidean_distance(stats_bottom_left.average, stats_bottom_left.average) << endl; - if (euclidean_distance(stats_bottom_left.average, stats_bottom_right.average) > 20){ -// cout << "zxcv" << endl; - return false; - } -// cout << euclidean_distance(stats_top.average, stats_bottom_left.average) << endl; - if (euclidean_distance(stats_top.average, stats_bottom_left.average) > 20){ -// cout << "xcvb" << endl; - return false; - } - - ImageStats stats_user_icons = image_stats(extract_box_reference(screen, m_user_icons)); -// cout << stats_user_icons.stddev << endl; - if (stats_user_icons.stddev.sum() < 40){ - return false; - } - ImageStats stats_game_slot = image_stats(extract_box_reference(screen, m_game_slot)); -// cout << stats_game_slot.stddev << endl; - if (stats_game_slot.stddev.sum() < 50){ - return false; - } - - // Read the console type only when we have confirmed the home menu. - m_console_type.detect_only(screen); - - return true; -} - - - - - - -} -} +/* Home Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_HomeMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +HomeMenuDetector::HomeMenuDetector(ConsoleHandle& console, Color color) + : m_color(color) + , m_console_type(console, color) + , m_top(0.510223, 0.019835, 0.441450, 0.034711) + , m_bottom_row(0.10, 0.92, 0.10, 0.05) + , m_bottom_icons(0.70, 0.92, 0.28, 0.05) + , m_bottom_left(0.02, 0.70, 0.15, 0.15) + , m_bottom_right(0.83, 0.70, 0.15, 0.15) + , m_user_icons(0.05, 0.05, 0.2, 0.08) + , m_game_slot(0.08, 0.25, 0.10, 0.38) +{} +void HomeMenuDetector::make_overlays(VideoOverlaySet& items) const{ + m_console_type.make_overlays(items); + items.add(m_color, m_top); + items.add(m_color, m_bottom_row); + items.add(m_color, m_bottom_icons); + items.add(m_color, m_bottom_left); + items.add(m_color, m_bottom_right); + items.add(m_color, m_user_icons); + items.add(m_color, m_game_slot); +} + +// +// This miraculously works on both Switch 1 and Switch 2. +// +bool HomeMenuDetector::detect(const ImageViewRGB32& screen){ + if (detect_only(screen)){ + m_console_type.commit_to_cache(); + return true; + }else{ + return false; + } +} +bool HomeMenuDetector::detect_only(const ImageViewRGB32& screen){ + ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); +// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; + bool white; +// cout << "stats_bottom_row.average.sum() = " << stats_bottom_row.average.sum() << endl; + if (stats_bottom_row.average.sum() < 200){ + white = false; + }else if (stats_bottom_row.average.sum() > 500){ + white = true; + }else{ + return false; + } + +// cout << "white: " << white << endl; + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + if (stats_top.stddev.sum() > 20){ + return false; + } + + ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); +// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; + if (stats_bottom_icons.stddev.sum() < 50){ + return false; + } + + ImageStats stats_bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); + ImageStats stats_bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << stats_bottom_left.average << stats_bottom_left.stddev << endl; +// cout << stats_bottom_right.average << stats_bottom_right.stddev << endl; + if (white){ + if (!is_white(stats_bottom_left) || !is_white(stats_bottom_right)){ +// cout << "asdf" << endl; + return false; + } + }else{ + if (!is_grey(stats_bottom_left, 0, 200) || !is_grey(stats_bottom_right, 0, 200)){ +// cout << "qwer" << endl; + return false; + } + } + +// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; + if (euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) > 20){ +// cout << "qwer = " << euclidean_distance(stats_bottom_row.average, stats_bottom_left.average) << endl; + return false; + } +// cout << euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) << endl; + if (euclidean_distance(stats_bottom_row.average, stats_bottom_right.average) > 20){ +// cout << "asdf" << endl; + return false; + } +// cout << euclidean_distance(stats_bottom_left.average, stats_bottom_left.average) << endl; + if (euclidean_distance(stats_bottom_left.average, stats_bottom_right.average) > 20){ +// cout << "zxcv" << endl; + return false; + } +// cout << euclidean_distance(stats_top.average, stats_bottom_left.average) << endl; + if (euclidean_distance(stats_top.average, stats_bottom_left.average) > 20){ +// cout << "xcvb" << endl; + return false; + } + + ImageStats stats_user_icons = image_stats(extract_box_reference(screen, m_user_icons)); +// cout << stats_user_icons.stddev << endl; + if (stats_user_icons.stddev.sum() < 40){ + return false; + } + ImageStats stats_game_slot = image_stats(extract_box_reference(screen, m_game_slot)); +// cout << stats_game_slot.stddev << endl; + if (stats_game_slot.stddev.sum() < 50){ + return false; + } + + // Read the console type only when we have confirmed the home menu. + m_console_type.detect_only(screen); + + return true; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h index ae888f53fb..85285b42b0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h @@ -1,55 +1,55 @@ -/* Home Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_HomeMenuDetector_H -#define PokemonAutomation_NintendoSwitch_HomeMenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class HomeMenuDetector : public StaticScreenDetector{ -public: - HomeMenuDetector(ConsoleHandle& console, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - bool detect_only(const ImageViewRGB32& screen); - -private: - Color m_color; - ConsoleTypeDetector_Home m_console_type; - ImageFloatBox m_top; - ImageFloatBox m_bottom_row; - ImageFloatBox m_bottom_icons; - ImageFloatBox m_bottom_left; - ImageFloatBox m_bottom_right; - ImageFloatBox m_user_icons; - ImageFloatBox m_game_slot; -}; -class HomeMenuWatcher : public DetectorToFinder{ -public: - HomeMenuWatcher( - ConsoleHandle& console, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("HomeMenuWatcher", hold_duration, console) - {} -}; - - - - -} -} -#endif +/* Home Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_HomeMenuDetector_H +#define PokemonAutomation_NintendoSwitch_HomeMenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class HomeMenuDetector : public StaticScreenDetector{ +public: + HomeMenuDetector(ConsoleHandle& console, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + bool detect_only(const ImageViewRGB32& screen); + +private: + Color m_color; + ConsoleTypeDetector_Home m_console_type; + ImageFloatBox m_top; + ImageFloatBox m_bottom_row; + ImageFloatBox m_bottom_icons; + ImageFloatBox m_bottom_left; + ImageFloatBox m_bottom_right; + ImageFloatBox m_user_icons; + ImageFloatBox m_game_slot; +}; +class HomeMenuWatcher : public DetectorToFinder{ +public: + HomeMenuWatcher( + ConsoleHandle& console, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("HomeMenuWatcher", hold_duration, console) + {} +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp index 43c8c15e93..47ed10181c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.cpp @@ -1,79 +1,79 @@ -/* Detect Home - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_SelectedSettingDetector.h" - -// -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -SelectedSettingWatcher::~SelectedSettingWatcher() = default; - -SelectedSettingWatcher::SelectedSettingWatcher( - ImageFloatBox selected_box, - ImageFloatBox not_selected_box1, - ImageFloatBox not_selected_box2 -) - : VisualInferenceCallback("SelectedSettingWatcher") - , m_selected_box(selected_box) - , m_not_selected_box1(not_selected_box1) - , m_not_selected_box2(not_selected_box2) -{} - -void SelectedSettingWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_selected_box); - items.add(COLOR_BLUE, m_not_selected_box1); - items.add(COLOR_BLUE, m_not_selected_box2); -} - -bool is_white_theme(const ImageViewRGB32& screen){ - ImageFloatBox window_top(0.60, 0.02, 0.35, 0.05); - ImageStats stats_window_top = image_stats(extract_box_reference(screen, window_top)); - bool white_theme = stats_window_top.average.sum() > 500; - return white_theme; -} - -bool SelectedSettingWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - - ImageStats stats_unselected_box1 = image_stats(extract_box_reference(screen, m_not_selected_box1)); - double unselected1_average_sum = stats_unselected_box1.average.sum(); -// cout << "unselected_average_sum1: " << std::to_string(unselected1_average_sum) << endl; - - ImageStats stats_unselected_box2 = image_stats(extract_box_reference(screen, m_not_selected_box2)); - double unselected2_average_sum = stats_unselected_box2.average.sum(); -// cout << "unselected_average_sum2: " << std::to_string(unselected2_average_sum) << endl; - - double average_sum_unselected_diff = std::abs(unselected1_average_sum - unselected2_average_sum); - - ImageStats stats_selected_box = image_stats(extract_box_reference(screen, m_selected_box)); - double selected_average_sum = stats_selected_box.average.sum(); -// cout << "selected_average_sum: " << std::to_string(selected_average_sum) << endl; - - bool is_selected = false; - if (is_white_theme(screen)){ // light mode - // unselected should be brighter than selected - is_selected = selected_average_sum < std::min(unselected1_average_sum, unselected2_average_sum) - average_sum_unselected_diff - 20 ; - }else{ // dark mode - // selected should be brighter than unselected - is_selected = selected_average_sum > std::max(unselected1_average_sum, unselected2_average_sum) + average_sum_unselected_diff + 20; - } - - return is_selected; -} - - - - - - -} -} +/* Detect Home + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_SelectedSettingDetector.h" + +// +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +SelectedSettingWatcher::~SelectedSettingWatcher() = default; + +SelectedSettingWatcher::SelectedSettingWatcher( + ImageFloatBox selected_box, + ImageFloatBox not_selected_box1, + ImageFloatBox not_selected_box2 +) + : VisualInferenceCallback("SelectedSettingWatcher") + , m_selected_box(selected_box) + , m_not_selected_box1(not_selected_box1) + , m_not_selected_box2(not_selected_box2) +{} + +void SelectedSettingWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_selected_box); + items.add(COLOR_BLUE, m_not_selected_box1); + items.add(COLOR_BLUE, m_not_selected_box2); +} + +bool is_white_theme(const ImageViewRGB32& screen){ + ImageFloatBox window_top(0.60, 0.02, 0.35, 0.05); + ImageStats stats_window_top = image_stats(extract_box_reference(screen, window_top)); + bool white_theme = stats_window_top.average.sum() > 500; + return white_theme; +} + +bool SelectedSettingWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + + ImageStats stats_unselected_box1 = image_stats(extract_box_reference(screen, m_not_selected_box1)); + double unselected1_average_sum = stats_unselected_box1.average.sum(); +// cout << "unselected_average_sum1: " << std::to_string(unselected1_average_sum) << endl; + + ImageStats stats_unselected_box2 = image_stats(extract_box_reference(screen, m_not_selected_box2)); + double unselected2_average_sum = stats_unselected_box2.average.sum(); +// cout << "unselected_average_sum2: " << std::to_string(unselected2_average_sum) << endl; + + double average_sum_unselected_diff = std::abs(unselected1_average_sum - unselected2_average_sum); + + ImageStats stats_selected_box = image_stats(extract_box_reference(screen, m_selected_box)); + double selected_average_sum = stats_selected_box.average.sum(); +// cout << "selected_average_sum: " << std::to_string(selected_average_sum) << endl; + + bool is_selected = false; + if (is_white_theme(screen)){ // light mode + // unselected should be brighter than selected + is_selected = selected_average_sum < std::min(unselected1_average_sum, unselected2_average_sum) - average_sum_unselected_diff - 20 ; + }else{ // dark mode + // selected should be brighter than unselected + is_selected = selected_average_sum > std::max(unselected1_average_sum, unselected2_average_sum) + average_sum_unselected_diff + 20; + } + + return is_selected; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h index 5d3858ed84..0134638273 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h @@ -1,47 +1,47 @@ -/* Selected Setting Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H -#define PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SelectedSettingWatcher : public VisualInferenceCallback{ -public: - SelectedSettingWatcher( - ImageFloatBox selected_box, - ImageFloatBox not_selected_box1, - ImageFloatBox not_selected_box2 - ); - virtual ~SelectedSettingWatcher(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // return true if the area within the selected_box is highlighted, compared with the area within unselected_box - // This compares the brightness of the selected_box with the unselected_box. - // selected_box: the box where we expect the screen should be highlighted - // not_selected_box 1 and 2: the boxes where we expect the screen should NOT be highlighted. These acts as the control, for comparison. - // the average sum of selected_box should be greater than the absolute difference of average sum between unselected_box 1 and 2. - virtual bool process_frame(const ImageViewRGB32& screen, WallClock timestamp) override; - - -protected: - ImageFloatBox m_selected_box; - ImageFloatBox m_not_selected_box1; - ImageFloatBox m_not_selected_box2; -}; - - -} -} -#endif - +/* Selected Setting Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H +#define PokemonAutomation_NintendoSwitch_SelectedSettingDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SelectedSettingWatcher : public VisualInferenceCallback{ +public: + SelectedSettingWatcher( + ImageFloatBox selected_box, + ImageFloatBox not_selected_box1, + ImageFloatBox not_selected_box2 + ); + virtual ~SelectedSettingWatcher(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // return true if the area within the selected_box is highlighted, compared with the area within unselected_box + // This compares the brightness of the selected_box with the unselected_box. + // selected_box: the box where we expect the screen should be highlighted + // not_selected_box 1 and 2: the boxes where we expect the screen should NOT be highlighted. These acts as the control, for comparison. + // the average sum of selected_box should be greater than the absolute difference of average sum between unselected_box 1 and 2. + virtual bool process_frame(const ImageViewRGB32& screen, WallClock timestamp) override; + + +protected: + ImageFloatBox m_selected_box; + ImageFloatBox m_not_selected_box1; + ImageFloatBox m_not_selected_box2; +}; + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp index 2029cd97ea..9f8a1718d6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.cpp @@ -1,208 +1,208 @@ -/* Start Game User-Select Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_StartGameUserSelectDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -StartGameUserSelectDetector::StartGameUserSelectDetector(ConsoleHandle& console, Color color) - : m_console(console) - , m_type_detector(console, color) - , m_switch1(color) - , m_switch2(color) -{} -void StartGameUserSelectDetector::make_overlays(VideoOverlaySet& items) const{ - m_type_detector.make_overlays(items); - m_switch1.make_overlays(items); - m_switch2.make_overlays(items); -} -bool StartGameUserSelectDetector::detect(const ImageViewRGB32& screen){ - if (detect_only(screen)){ - m_console.state().set_console_type(m_console, m_console_type); - return true; - }else{ - return false; - } -} -bool StartGameUserSelectDetector::detect_only(const ImageViewRGB32& screen){ - ConsoleType type = m_type_detector.detect_only(screen); - m_console_type = type; - - if (type == ConsoleType::Unknown){ - return false; - } - if (is_switch1(type)){ - return m_switch1.detect(screen); - } - if (is_switch2(type)){ - return m_switch2.detect(screen); - } - - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid ConsoleType: " + std::to_string((int)type) - ); -} - - - - - - - - -StartGameUserSelectDetector_Switch1::StartGameUserSelectDetector_Switch1(Color color) - : m_color(color) - , m_bottom_row(0.10, 0.92, 0.10, 0.05) - , m_bottom_icons(0.70, 0.92, 0.28, 0.05) - , m_top_row(0.50, 0.47, 0.45, 0.05) - , m_mid_row(0.10, 0.55, 0.80, 0.02) - , m_user_slot(0.45, 0.55, 0.10, 0.35) -{} -void StartGameUserSelectDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_row); - items.add(m_color, m_bottom_icons); - items.add(m_color, m_top_row); - items.add(m_color, m_mid_row); - items.add(m_color, m_user_slot); -} -bool StartGameUserSelectDetector_Switch1::detect(const ImageViewRGB32& screen){ - ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); -// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; - if (stats_bottom_row.stddev.sum() > 10){ - return false; - } - bool white; - if (is_grey(stats_bottom_row, 50, 300)){ - white = false; - }else if (stats_bottom_row.average.sum() > 500){ - white = true; - }else{ - return false; - } - - ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); -// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; - if (stats_bottom_icons.stddev.sum() < 50){ - return false; - } - - ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); - ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); -// cout << stats_top_row.average << stats_top_row.stddev << endl; - if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ - return false; - } - if (white){ - if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ - return false; - } - }else{ - if (!is_grey(stats_top_row, 50, 300) || !is_grey(stats_mid_row, 50, 300)){ - return false; - } - } - - if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ - return false; - } - - ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); -// cout << stats_user_slot.average << stats_user_slot.stddev << endl; - if (stats_user_slot.stddev.sum() < 50){ - return false; - } - - return true; -} - - -StartGameUserSelectDetector_Switch2::StartGameUserSelectDetector_Switch2(Color color) - : m_color(color) - , m_bottom_row(0.10, 0.92, 0.10, 0.05) - , m_bottom_icons(0.70, 0.92, 0.28, 0.05) - , m_top_row(0.50, 0.45, 0.45, 0.05) - , m_mid_row(0.10, 0.53, 0.80, 0.02) - , m_user_slot(0.45, 0.55, 0.10, 0.30) -{} -void StartGameUserSelectDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_row); - items.add(m_color, m_bottom_icons); - items.add(m_color, m_top_row); - items.add(m_color, m_mid_row); - items.add(m_color, m_user_slot); -} -bool StartGameUserSelectDetector_Switch2::detect(const ImageViewRGB32& screen){ - ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); -// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; - if (stats_bottom_row.stddev.sum() > 10){ - return false; - } - bool white; - if (is_grey(stats_bottom_row, 0, 300)){ - white = false; - }else if (stats_bottom_row.average.sum() > 500){ - white = true; - }else{ - return false; - } - - ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); -// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; - if (stats_bottom_icons.stddev.sum() < 50){ - return false; - } - - ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); - ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); -// cout << stats_top_row.average << stats_top_row.stddev << endl; - if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ - return false; - } - if (white){ - if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ - return false; - } - }else{ - if (!is_grey(stats_top_row, 0, 300) || !is_grey(stats_mid_row, 0, 300)){ - return false; - } - } - - if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ - return false; - } - - ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); -// cout << stats_user_slot.average << stats_user_slot.stddev << endl; - if (stats_user_slot.stddev.sum() < 50){ - return false; - } - - return true; -} - - - - - - - - - -} -} +/* Start Game User-Select Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_StartGameUserSelectDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +StartGameUserSelectDetector::StartGameUserSelectDetector(ConsoleHandle& console, Color color) + : m_console(console) + , m_type_detector(console, color) + , m_switch1(color) + , m_switch2(color) +{} +void StartGameUserSelectDetector::make_overlays(VideoOverlaySet& items) const{ + m_type_detector.make_overlays(items); + m_switch1.make_overlays(items); + m_switch2.make_overlays(items); +} +bool StartGameUserSelectDetector::detect(const ImageViewRGB32& screen){ + if (detect_only(screen)){ + m_console.state().set_console_type(m_console, m_console_type); + return true; + }else{ + return false; + } +} +bool StartGameUserSelectDetector::detect_only(const ImageViewRGB32& screen){ + ConsoleType type = m_type_detector.detect_only(screen); + m_console_type = type; + + if (type == ConsoleType::Unknown){ + return false; + } + if (is_switch1(type)){ + return m_switch1.detect(screen); + } + if (is_switch2(type)){ + return m_switch2.detect(screen); + } + + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid ConsoleType: " + std::to_string((int)type) + ); +} + + + + + + + + +StartGameUserSelectDetector_Switch1::StartGameUserSelectDetector_Switch1(Color color) + : m_color(color) + , m_bottom_row(0.10, 0.92, 0.10, 0.05) + , m_bottom_icons(0.70, 0.92, 0.28, 0.05) + , m_top_row(0.50, 0.47, 0.45, 0.05) + , m_mid_row(0.10, 0.55, 0.80, 0.02) + , m_user_slot(0.45, 0.55, 0.10, 0.35) +{} +void StartGameUserSelectDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_row); + items.add(m_color, m_bottom_icons); + items.add(m_color, m_top_row); + items.add(m_color, m_mid_row); + items.add(m_color, m_user_slot); +} +bool StartGameUserSelectDetector_Switch1::detect(const ImageViewRGB32& screen){ + ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); +// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; + if (stats_bottom_row.stddev.sum() > 10){ + return false; + } + bool white; + if (is_grey(stats_bottom_row, 50, 300)){ + white = false; + }else if (stats_bottom_row.average.sum() > 500){ + white = true; + }else{ + return false; + } + + ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); +// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; + if (stats_bottom_icons.stddev.sum() < 50){ + return false; + } + + ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); + ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); +// cout << stats_top_row.average << stats_top_row.stddev << endl; + if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ + return false; + } + if (white){ + if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ + return false; + } + }else{ + if (!is_grey(stats_top_row, 50, 300) || !is_grey(stats_mid_row, 50, 300)){ + return false; + } + } + + if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ + return false; + } + + ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); +// cout << stats_user_slot.average << stats_user_slot.stddev << endl; + if (stats_user_slot.stddev.sum() < 50){ + return false; + } + + return true; +} + + +StartGameUserSelectDetector_Switch2::StartGameUserSelectDetector_Switch2(Color color) + : m_color(color) + , m_bottom_row(0.10, 0.92, 0.10, 0.05) + , m_bottom_icons(0.70, 0.92, 0.28, 0.05) + , m_top_row(0.50, 0.45, 0.45, 0.05) + , m_mid_row(0.10, 0.53, 0.80, 0.02) + , m_user_slot(0.45, 0.55, 0.10, 0.30) +{} +void StartGameUserSelectDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_row); + items.add(m_color, m_bottom_icons); + items.add(m_color, m_top_row); + items.add(m_color, m_mid_row); + items.add(m_color, m_user_slot); +} +bool StartGameUserSelectDetector_Switch2::detect(const ImageViewRGB32& screen){ + ImageStats stats_bottom_row = image_stats(extract_box_reference(screen, m_bottom_row)); +// cout << stats_bottom_row.average << stats_bottom_row.stddev << endl; + if (stats_bottom_row.stddev.sum() > 10){ + return false; + } + bool white; + if (is_grey(stats_bottom_row, 0, 300)){ + white = false; + }else if (stats_bottom_row.average.sum() > 500){ + white = true; + }else{ + return false; + } + + ImageStats stats_bottom_icons = image_stats(extract_box_reference(screen, m_bottom_icons)); +// cout << stats_bottom_icons.average << stats_bottom_icons.stddev << endl; + if (stats_bottom_icons.stddev.sum() < 50){ + return false; + } + + ImageStats stats_top_row = image_stats(extract_box_reference(screen, m_top_row)); + ImageStats stats_mid_row = image_stats(extract_box_reference(screen, m_mid_row)); +// cout << stats_top_row.average << stats_top_row.stddev << endl; + if (stats_top_row.stddev.sum() > 10 || stats_mid_row.stddev.sum() > 10){ + return false; + } + if (white){ + if (!is_white(stats_top_row) || !is_white(stats_mid_row)){ + return false; + } + }else{ + if (!is_grey(stats_top_row, 0, 300) || !is_grey(stats_mid_row, 0, 300)){ + return false; + } + } + + if (euclidean_distance(stats_bottom_row.average, stats_top_row.average) > 20){ + return false; + } + + ImageStats stats_user_slot = image_stats(extract_box_reference(screen, m_user_slot)); +// cout << stats_user_slot.average << stats_user_slot.stddev << endl; + if (stats_user_slot.stddev.sum() < 50){ + return false; + } + + return true; +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h index 55ee54f62b..8519893cdf 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h @@ -1,87 +1,87 @@ -/* Start Game User-Select Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H -#define PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class StartGameUserSelectDetector_Switch1 : public StaticScreenDetector{ -public: - StartGameUserSelectDetector_Switch1(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom_row; - ImageFloatBox m_bottom_icons; - ImageFloatBox m_top_row; - ImageFloatBox m_mid_row; - ImageFloatBox m_user_slot; -}; -class StartGameUserSelectDetector_Switch2 : public StaticScreenDetector{ -public: - StartGameUserSelectDetector_Switch2(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom_row; - ImageFloatBox m_bottom_icons; - ImageFloatBox m_top_row; - ImageFloatBox m_mid_row; - ImageFloatBox m_user_slot; -}; - - - - - -class StartGameUserSelectDetector : public StaticScreenDetector{ -public: - StartGameUserSelectDetector(ConsoleHandle& console, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - bool detect_only(const ImageViewRGB32& screen); - -private: - ConsoleHandle& m_console; - ConsoleTypeDetector_StartGameUserSelect m_type_detector; - StartGameUserSelectDetector_Switch1 m_switch1; - StartGameUserSelectDetector_Switch2 m_switch2; - - ConsoleType m_console_type; -}; -class StartGameUserSelectWatcher : public DetectorToFinder{ -public: - StartGameUserSelectWatcher(ConsoleHandle& console, Color color = COLOR_RED) - : DetectorToFinder("StartGameUserSelectWatcher", std::chrono::milliseconds(250), console, color) - {} -}; - - - - - - -} -} -#endif +/* Start Game User-Select Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H +#define PokemonAutomation_NintendoSwitch_StartGameUserSelectDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class StartGameUserSelectDetector_Switch1 : public StaticScreenDetector{ +public: + StartGameUserSelectDetector_Switch1(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom_row; + ImageFloatBox m_bottom_icons; + ImageFloatBox m_top_row; + ImageFloatBox m_mid_row; + ImageFloatBox m_user_slot; +}; +class StartGameUserSelectDetector_Switch2 : public StaticScreenDetector{ +public: + StartGameUserSelectDetector_Switch2(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom_row; + ImageFloatBox m_bottom_icons; + ImageFloatBox m_top_row; + ImageFloatBox m_mid_row; + ImageFloatBox m_user_slot; +}; + + + + + +class StartGameUserSelectDetector : public StaticScreenDetector{ +public: + StartGameUserSelectDetector(ConsoleHandle& console, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + bool detect_only(const ImageViewRGB32& screen); + +private: + ConsoleHandle& m_console; + ConsoleTypeDetector_StartGameUserSelect m_type_detector; + StartGameUserSelectDetector_Switch1 m_switch1; + StartGameUserSelectDetector_Switch2 m_switch2; + + ConsoleType m_console_type; +}; +class StartGameUserSelectWatcher : public DetectorToFinder{ +public: + StartGameUserSelectWatcher(ConsoleHandle& console, Color color = COLOR_RED) + : DetectorToFinder("StartGameUserSelectWatcher", std::chrono::milliseconds(250), console, color) + {} +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp index 57ec2119f1..f508ecd1f4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.cpp @@ -1,247 +1,247 @@ -/* Update Popup Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch_UpdatePopupDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -UpdatePopupDetector::UpdatePopupDetector(ConsoleHandle& console, Color color) - : m_type_detector(console, color) - , m_switch1(color) - , m_switch2(color) -{} -void UpdatePopupDetector::make_overlays(VideoOverlaySet& items) const{ - m_type_detector.make_overlays(items); - m_switch1.make_overlays(items); - m_switch2.make_overlays(items); -} -bool UpdatePopupDetector::detect(const ImageViewRGB32& screen){ - if (detect_only(screen)){ - m_type_detector.commit_to_cache(); - return true; - }else{ - return false; - } -} -bool UpdatePopupDetector::detect_only(const ImageViewRGB32& screen){ - ConsoleType type = m_type_detector.detect_only(screen); - - if (type == ConsoleType::Unknown){ - return false; - } - if (is_switch1(type)){ - return m_switch1.detect(screen); - } - if (is_switch2(type)){ - return m_switch2.detect(screen); - } - - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid ConsoleType: " + std::to_string((int)type) - ); -} - - - - - - - - -UpdatePopupDetector_Switch1::UpdatePopupDetector_Switch1(Color color) - : m_color(color) - , m_box_top(0.25, 0.26, 0.50, 0.02) - , m_box_mid(0.25, 0.52, 0.50, 0.02) - , m_top(0.10, 0.15, 0.80, 0.03) - , m_left(0.08, 0.25, 0.10, 0.38) - , m_bottom_solid(0.10, 0.84, 0.80, 0.04) - , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) -{} -void UpdatePopupDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_top); - items.add(m_color, m_box_mid); - items.add(m_color, m_top); - items.add(m_color, m_left); - items.add(m_color, m_bottom_solid); - items.add(m_color, m_bottom_buttons); -} -bool UpdatePopupDetector_Switch1::detect(const ImageViewRGB32& screen){ - ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); -// cout << stats_box_top.average << stats_box_top.stddev << endl; - bool white; - if (stats_box_top.average.sum() < 300){ - white = false; - }else if (stats_box_top.average.sum() > 500){ - white = true; - }else{ - return false; - } - if (stats_box_top.stddev.sum() > 10){ - return false; - } - -// cout << "white: " << white << endl; - - ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); - if (stats_box_mid.stddev.sum() > 10){ - return false; - } - if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ - return false; - } - - ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); -// cout << stats_left.stddev << endl; - if (stats_left.stddev.sum() < 30){ -// cout << "zxcv" << endl; - return false; - } - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - - ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); -// cout << bottom_solid.average << bottom_solid.stddev << endl; - - if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ -// cout << "qwer" << endl; - return false; - } - - if (white){ - if (!is_grey(stats_top, 100, 300) || !is_grey(bottom_solid, 100, 300)){ -// cout << "asdf" << endl; - return false; - } - }else{ - if (!is_grey(stats_top, 0, 100) || !is_grey(bottom_solid, 0, 100)){ -// cout << "zxcv" << endl; - return false; - } - } - - ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); -// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; - if (stats_bottom_buttons.stddev.sum() < 30){ - return false; - } - - return true; -} - - - - -UpdatePopupDetector_Switch2::UpdatePopupDetector_Switch2(Color color) - : m_color(color) - , m_box_top(0.25, 0.31, 0.50, 0.02) -// , m_box_mid(0.25, 0.482, 0.50, 0.02) - , m_top(0.10, 0.17, 0.80, 0.03) - , m_left(0.08, 0.25, 0.10, 0.38) - , m_bottom_solid(0.10, 0.86, 0.80, 0.04) - , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) -{} - -void UpdatePopupDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_top); -// items.add(m_color, m_box_mid); - items.add(m_color, m_top); - items.add(m_color, m_left); - items.add(m_color, m_bottom_solid); - items.add(m_color, m_bottom_buttons); -} -bool UpdatePopupDetector_Switch2::detect(const ImageViewRGB32& screen){ - ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); -// cout << stats_box_top.average << stats_box_top.stddev << endl; - bool white; - if (stats_box_top.average.sum() < 300){ - white = false; - }else if (stats_box_top.average.sum() > 500){ - white = true; - }else{ - return false; - } - if (stats_box_top.stddev.sum() > 10){ - return false; - } - -// cout << "white: " << white << endl; - -#if 0 - ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); - if (stats_box_mid.stddev.sum() > 10){ - return false; - } - if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ - return false; - } -#endif - - ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); -// cout << stats_left.stddev << endl; - if (stats_left.stddev.sum() < 30){ -// cout << "zxcv" << endl; - return false; - } - - ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); -// cout << stats_top.average << stats_top.stddev << endl; - - ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); -// cout << bottom_solid.average << bottom_solid.stddev << endl; - - if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ -// cout << "qwer" << endl; - return false; - } - - do{ - if (white){ - if (is_grey(stats_top, 200, 765) && is_grey(bottom_solid, 200, 765)){ - break; - } - }else{ - if (is_grey(stats_top, 0, 100) && is_grey(bottom_solid, 0, 100)){ - break; - } - if (is_grey(stats_top, 200, 500) && is_grey(bottom_solid, 200, 500)){ - break; - } - } - - return false; - }while (false); - - ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); -// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; - if (stats_bottom_buttons.stddev.sum() < 30){ - return false; - } - - return true; -} - - - - - - - - - -} -} +/* Update Popup Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch_UpdatePopupDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +UpdatePopupDetector::UpdatePopupDetector(ConsoleHandle& console, Color color) + : m_type_detector(console, color) + , m_switch1(color) + , m_switch2(color) +{} +void UpdatePopupDetector::make_overlays(VideoOverlaySet& items) const{ + m_type_detector.make_overlays(items); + m_switch1.make_overlays(items); + m_switch2.make_overlays(items); +} +bool UpdatePopupDetector::detect(const ImageViewRGB32& screen){ + if (detect_only(screen)){ + m_type_detector.commit_to_cache(); + return true; + }else{ + return false; + } +} +bool UpdatePopupDetector::detect_only(const ImageViewRGB32& screen){ + ConsoleType type = m_type_detector.detect_only(screen); + + if (type == ConsoleType::Unknown){ + return false; + } + if (is_switch1(type)){ + return m_switch1.detect(screen); + } + if (is_switch2(type)){ + return m_switch2.detect(screen); + } + + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid ConsoleType: " + std::to_string((int)type) + ); +} + + + + + + + + +UpdatePopupDetector_Switch1::UpdatePopupDetector_Switch1(Color color) + : m_color(color) + , m_box_top(0.25, 0.26, 0.50, 0.02) + , m_box_mid(0.25, 0.52, 0.50, 0.02) + , m_top(0.10, 0.15, 0.80, 0.03) + , m_left(0.08, 0.25, 0.10, 0.38) + , m_bottom_solid(0.10, 0.84, 0.80, 0.04) + , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) +{} +void UpdatePopupDetector_Switch1::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_top); + items.add(m_color, m_box_mid); + items.add(m_color, m_top); + items.add(m_color, m_left); + items.add(m_color, m_bottom_solid); + items.add(m_color, m_bottom_buttons); +} +bool UpdatePopupDetector_Switch1::detect(const ImageViewRGB32& screen){ + ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); +// cout << stats_box_top.average << stats_box_top.stddev << endl; + bool white; + if (stats_box_top.average.sum() < 300){ + white = false; + }else if (stats_box_top.average.sum() > 500){ + white = true; + }else{ + return false; + } + if (stats_box_top.stddev.sum() > 10){ + return false; + } + +// cout << "white: " << white << endl; + + ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); + if (stats_box_mid.stddev.sum() > 10){ + return false; + } + if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ + return false; + } + + ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); +// cout << stats_left.stddev << endl; + if (stats_left.stddev.sum() < 30){ +// cout << "zxcv" << endl; + return false; + } + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + + ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); +// cout << bottom_solid.average << bottom_solid.stddev << endl; + + if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ +// cout << "qwer" << endl; + return false; + } + + if (white){ + if (!is_grey(stats_top, 100, 300) || !is_grey(bottom_solid, 100, 300)){ +// cout << "asdf" << endl; + return false; + } + }else{ + if (!is_grey(stats_top, 0, 100) || !is_grey(bottom_solid, 0, 100)){ +// cout << "zxcv" << endl; + return false; + } + } + + ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); +// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; + if (stats_bottom_buttons.stddev.sum() < 30){ + return false; + } + + return true; +} + + + + +UpdatePopupDetector_Switch2::UpdatePopupDetector_Switch2(Color color) + : m_color(color) + , m_box_top(0.25, 0.31, 0.50, 0.02) +// , m_box_mid(0.25, 0.482, 0.50, 0.02) + , m_top(0.10, 0.17, 0.80, 0.03) + , m_left(0.08, 0.25, 0.10, 0.38) + , m_bottom_solid(0.10, 0.86, 0.80, 0.04) + , m_bottom_buttons(0.70, 0.92, 0.28, 0.05) +{} + +void UpdatePopupDetector_Switch2::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_top); +// items.add(m_color, m_box_mid); + items.add(m_color, m_top); + items.add(m_color, m_left); + items.add(m_color, m_bottom_solid); + items.add(m_color, m_bottom_buttons); +} +bool UpdatePopupDetector_Switch2::detect(const ImageViewRGB32& screen){ + ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); +// cout << stats_box_top.average << stats_box_top.stddev << endl; + bool white; + if (stats_box_top.average.sum() < 300){ + white = false; + }else if (stats_box_top.average.sum() > 500){ + white = true; + }else{ + return false; + } + if (stats_box_top.stddev.sum() > 10){ + return false; + } + +// cout << "white: " << white << endl; + +#if 0 + ImageStats stats_box_mid = image_stats(extract_box_reference(screen, m_box_mid)); + if (stats_box_mid.stddev.sum() > 10){ + return false; + } + if (euclidean_distance(stats_box_top.average, stats_box_mid.average) > 10){ + return false; + } +#endif + + ImageStats stats_left = image_stats(extract_box_reference(screen, m_left)); +// cout << stats_left.stddev << endl; + if (stats_left.stddev.sum() < 30){ +// cout << "zxcv" << endl; + return false; + } + + ImageStats stats_top = image_stats(extract_box_reference(screen, m_top)); +// cout << stats_top.average << stats_top.stddev << endl; + + ImageStats bottom_solid = image_stats(extract_box_reference(screen, m_bottom_solid)); +// cout << bottom_solid.average << bottom_solid.stddev << endl; + + if (euclidean_distance(stats_top.average, bottom_solid.average) > 10){ +// cout << "qwer" << endl; + return false; + } + + do{ + if (white){ + if (is_grey(stats_top, 200, 765) && is_grey(bottom_solid, 200, 765)){ + break; + } + }else{ + if (is_grey(stats_top, 0, 100) && is_grey(bottom_solid, 0, 100)){ + break; + } + if (is_grey(stats_top, 200, 500) && is_grey(bottom_solid, 200, 500)){ + break; + } + } + + return false; + }while (false); + + ImageStats stats_bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); +// cout << stats_bottom_buttons.average << stats_bottom_buttons.stddev << endl; + if (stats_bottom_buttons.stddev.sum() < 30){ + return false; + } + + return true; +} + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h index 420c29a517..ee8a1dfb82 100644 --- a/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h +++ b/SerialPrograms/Source/NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h @@ -1,86 +1,86 @@ -/* Update Popup Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H -#define PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch_ConsoleTypeDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class UpdatePopupDetector_Switch1 : public StaticScreenDetector{ -public: - UpdatePopupDetector_Switch1(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box_top; - ImageFloatBox m_box_mid; - ImageFloatBox m_top; - ImageFloatBox m_left; - ImageFloatBox m_bottom_solid; - ImageFloatBox m_bottom_buttons; -}; -class UpdatePopupDetector_Switch2 : public StaticScreenDetector{ -public: - UpdatePopupDetector_Switch2(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box_top; -// ImageFloatBox m_box_mid; - ImageFloatBox m_top; - ImageFloatBox m_left; - ImageFloatBox m_bottom_solid; - ImageFloatBox m_bottom_buttons; -}; - - - - - -// Detect the Switch system update screen when you are about to enter a game from Switch Home screen -class UpdatePopupDetector : public StaticScreenDetector{ -public: - UpdatePopupDetector(ConsoleHandle& console, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - bool detect_only(const ImageViewRGB32& screen); - -private: - ConsoleTypeDetector_Home m_type_detector; - UpdatePopupDetector_Switch1 m_switch1; - UpdatePopupDetector_Switch2 m_switch2; -}; -class UpdateMenuWatcher : public DetectorToFinder{ -public: - UpdateMenuWatcher(ConsoleHandle& console, Color color = COLOR_RED) - : DetectorToFinder("UpdateMenuWatcher", std::chrono::milliseconds(250), console, color) - {} -}; - - - - - - -} -} -#endif +/* Update Popup Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H +#define PokemonAutomation_NintendoSwitch_UpdatePopupDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch_ConsoleTypeDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class UpdatePopupDetector_Switch1 : public StaticScreenDetector{ +public: + UpdatePopupDetector_Switch1(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box_top; + ImageFloatBox m_box_mid; + ImageFloatBox m_top; + ImageFloatBox m_left; + ImageFloatBox m_bottom_solid; + ImageFloatBox m_bottom_buttons; +}; +class UpdatePopupDetector_Switch2 : public StaticScreenDetector{ +public: + UpdatePopupDetector_Switch2(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box_top; +// ImageFloatBox m_box_mid; + ImageFloatBox m_top; + ImageFloatBox m_left; + ImageFloatBox m_bottom_solid; + ImageFloatBox m_bottom_buttons; +}; + + + + + +// Detect the Switch system update screen when you are about to enter a game from Switch Home screen +class UpdatePopupDetector : public StaticScreenDetector{ +public: + UpdatePopupDetector(ConsoleHandle& console, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + bool detect_only(const ImageViewRGB32& screen); + +private: + ConsoleTypeDetector_Home m_type_detector; + UpdatePopupDetector_Switch1 m_switch1; + UpdatePopupDetector_Switch2 m_switch2; +}; +class UpdateMenuWatcher : public DetectorToFinder{ +public: + UpdateMenuWatcher(ConsoleHandle& console, Color color = COLOR_RED) + : DetectorToFinder("UpdateMenuWatcher", std::chrono::milliseconds(250), console, color) + {} +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp index 5db361a844..40ae43b548 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.cpp @@ -1,50 +1,50 @@ -/* Console Handle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" -#include "CommonTools/InferencePivots/VisualInferencePivot.h" -#include "CommonTools/InferencePivots/AudioInferencePivot.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "NintendoSwitch_ConsoleHandle.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -//ConsoleHandle::ConsoleHandle(ConsoleHandle&& x) = default; -ConsoleHandle::~ConsoleHandle(){ - overlay().remove_stat(*m_thread_utilization); -} - - -ConsoleHandle::ConsoleHandle( - size_t index, - Logger& logger, - AbstractController& controller, - VideoFeed& video, - VideoOverlay& overlay, - AudioFeed& audio, - const StreamHistorySession& history -) - : VideoStream(logger, audio, video, history, overlay) - , m_index(index) - , m_controller(controller) - , m_thread_utilization(new ThreadUtilizationStat(current_thread_handle(), "Program Thread:")) -{ - overlay.add_stat(*m_thread_utilization); -} - - - - - -} -} +/* Console Handle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" +#include "CommonTools/InferencePivots/VisualInferencePivot.h" +#include "CommonTools/InferencePivots/AudioInferencePivot.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "NintendoSwitch_ConsoleHandle.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +//ConsoleHandle::ConsoleHandle(ConsoleHandle&& x) = default; +ConsoleHandle::~ConsoleHandle(){ + overlay().remove_stat(*m_thread_utilization); +} + + +ConsoleHandle::ConsoleHandle( + size_t index, + Logger& logger, + AbstractController& controller, + VideoFeed& video, + VideoOverlay& overlay, + AudioFeed& audio, + const StreamHistorySession& history +) + : VideoStream(logger, audio, video, history, overlay) + , m_index(index) + , m_controller(controller) + , m_thread_utilization(new ThreadUtilizationStat(current_thread_handle(), "Program Thread:")) +{ + overlay.add_stat(*m_thread_utilization); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h index 9ddbeb9bca..2acd30f3cd 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleHandle.h @@ -1,88 +1,88 @@ -/* Console Handle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ConsoleHandle_H -#define PokemonAutomation_NintendoSwitch_ConsoleHandle_H - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch_ConsoleState.h" - -namespace PokemonAutomation{ - class ThreadHandle; - class ThreadUtilizationStat; -namespace NintendoSwitch{ - -class ConsoleHandle : public VideoStream{ -public: - ~ConsoleHandle(); -// ConsoleHandle(ConsoleHandle&& x); -// void operator=(ConsoleHandle&& x) = delete; - ConsoleHandle(const ConsoleHandle& x) = delete; - void operator=(const ConsoleHandle& x) = delete; - - -public: - ConsoleHandle( - size_t index, - Logger& logger, - AbstractController& controller, - VideoFeed& video, - VideoOverlay& overlay, - AudioFeed& audio, - const StreamHistorySession& history - ); - - size_t index() const{ return m_index; } - - template - ControllerType& controller(){ - ControllerType* ret = dynamic_cast(&m_controller); - if (ret){ - return *ret; - } - throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast controller."); - } - - // REMOVE: Temporary for refactor. - ProController& pro_controller(){ - ProController* ret = dynamic_cast(&m_controller); - if (ret){ - return *ret; - } - throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast to ProController."); - } - - - operator Logger&(){ return logger(); } - operator VideoFeed&(){ return video(); } - operator VideoOverlay&(){ return overlay(); } - operator AudioFeed&() { return audio(); } - operator const StreamHistorySession&() const{ return history(); } - - ConsoleState& state(){ return m_console_state; } - operator ConsoleState&(){ return m_console_state; } - - -private: - size_t m_index; - AbstractController& m_controller; - - ConsoleState m_console_state; - - std::unique_ptr m_thread_utilization; -}; - - - - -} -} -#endif - - +/* Console Handle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ConsoleHandle_H +#define PokemonAutomation_NintendoSwitch_ConsoleHandle_H + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch_ConsoleState.h" + +namespace PokemonAutomation{ + class ThreadHandle; + class ThreadUtilizationStat; +namespace NintendoSwitch{ + +class ConsoleHandle : public VideoStream{ +public: + ~ConsoleHandle(); +// ConsoleHandle(ConsoleHandle&& x); +// void operator=(ConsoleHandle&& x) = delete; + ConsoleHandle(const ConsoleHandle& x) = delete; + void operator=(const ConsoleHandle& x) = delete; + + +public: + ConsoleHandle( + size_t index, + Logger& logger, + AbstractController& controller, + VideoFeed& video, + VideoOverlay& overlay, + AudioFeed& audio, + const StreamHistorySession& history + ); + + size_t index() const{ return m_index; } + + template + ControllerType& controller(){ + ControllerType* ret = dynamic_cast(&m_controller); + if (ret){ + return *ret; + } + throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast controller."); + } + + // REMOVE: Temporary for refactor. + ProController& pro_controller(){ + ProController* ret = dynamic_cast(&m_controller); + if (ret){ + return *ret; + } + throw InternalProgramError(&logger(), PA_CURRENT_FUNCTION, "Unable to cast to ProController."); + } + + + operator Logger&(){ return logger(); } + operator VideoFeed&(){ return video(); } + operator VideoOverlay&(){ return overlay(); } + operator AudioFeed&() { return audio(); } + operator const StreamHistorySession&() const{ return history(); } + + ConsoleState& state(){ return m_console_state; } + operator ConsoleState&(){ return m_console_state; } + + +private: + size_t m_index; + AbstractController& m_controller; + + ConsoleState m_console_state; + + std::unique_ptr m_thread_utilization; +}; + + + + +} +} +#endif + + diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp index 13ccc194d4..e9e3859455 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.cpp @@ -1,182 +1,182 @@ -/* Console State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/Pimpl.tpp" -#include "NintendoSwitch_ConsoleState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -const std::string& ConsoleType_strings(ConsoleType type){ - static std::string STRINGS[] = { - "Unknown", - "Switch 1 + OLED", - "Switch 2 (unknown model)", - "Switch 2 (FW19, international)", - "Switch 2 (FW19, Japan-locked)", - "Switch 2 (FW20, international)", - "Switch 2 (FW20, Japan-locked)", - }; - size_t index = (size_t)type; - if (index < sizeof(STRINGS) / sizeof(std::string)){ - return STRINGS[(size_t)type]; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid ConsoleType enum: " + std::to_string(index) - ); -} - -[[noreturn]] void throw_conflict( - Logger& logger, - ConsoleType user_type, - ConsoleType detected_type -){ - throw UserSetupError( - logger, - std::string("Conflicting Console Types:") + - "\n User Selected: " + ConsoleType_strings(user_type) + - "\n Detected Type: " + ConsoleType_strings(detected_type) + - "\n\nIf you think this is a bug, please report it to either our Github or our Discord server!" - ); -} - - - -void check_for_conflict( - Logger& logger, - ConsoleType user_type, - ConsoleType detected_type -){ - if (user_type == detected_type){ - return; - } - if (user_type == ConsoleType::Unknown || detected_type == ConsoleType::Unknown){ - return; - } - - if (is_switch1(user_type) && is_switch1(detected_type)){ - return; - } - - if (is_switch2(user_type) && is_switch2(detected_type)){ - if (user_type == ConsoleType::Switch2_Unknown || detected_type == ConsoleType::Switch2_Unknown){ - return; - } - if (user_type != detected_type){ - throw_conflict(logger, user_type, detected_type); - } - return; - } - - throw_conflict(logger, user_type, detected_type); -} - - - - - - -struct ConsoleState::Data{ - Data() - : m_console_type_confirmed(false) - , m_console_type(ConsoleType::Unknown) - , m_text_size_standard(false) - {} - - std::atomic m_console_type_confirmed; - std::atomic m_console_type; - - std::atomic m_text_size_standard; -}; - - - -ConsoleState::~ConsoleState() = default; -ConsoleState::ConsoleState() - : m_data(CONSTRUCT_TOKEN) -{} - -bool ConsoleState::console_type_confirmed() const{ - return m_data->m_console_type_confirmed.load(std::memory_order_relaxed); -} -ConsoleType ConsoleState::console_type() const{ - return m_data->m_console_type.load(std::memory_order_relaxed); -} -void ConsoleState::set_console_type_user(ConsoleType type){ - m_data->m_console_type_confirmed.store(false, std::memory_order_relaxed); - m_data->m_console_type.store(type, std::memory_order_relaxed); -} -void ConsoleState::set_console_type(Logger& logger, ConsoleType type){ - ConsoleType current = console_type(); - bool confirmed = m_data->m_console_type_confirmed.load(std::memory_order_relaxed); - if (!confirmed){ - check_for_conflict(logger, current, type); - } - - do{ - if (type == ConsoleType::Unknown){ - return; - } - if (current == ConsoleType::Unknown){ - break; - } - - if (type == ConsoleType::Switch2_Unknown){ - return; - } - - }while (false); - - if (!confirmed || current != type){ - logger.log( - std::string("Setting console type to: ") + ConsoleType_strings(type), - COLOR_BLUE - ); - } - - m_data->m_console_type.store(type, std::memory_order_relaxed); - m_data->m_console_type_confirmed.store(true, std::memory_order_relaxed); -} - - - -bool ConsoleState::text_size_ok() const{ - return m_data->m_text_size_standard.load(std::memory_order_relaxed); -} -void ConsoleState::set_text_size_ok(bool ok){ - m_data->m_text_size_standard.store(ok, std::memory_order_relaxed); -} - - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Console State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/Pimpl.tpp" +#include "NintendoSwitch_ConsoleState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +const std::string& ConsoleType_strings(ConsoleType type){ + static std::string STRINGS[] = { + "Unknown", + "Switch 1 + OLED", + "Switch 2 (unknown model)", + "Switch 2 (FW19, international)", + "Switch 2 (FW19, Japan-locked)", + "Switch 2 (FW20, international)", + "Switch 2 (FW20, Japan-locked)", + }; + size_t index = (size_t)type; + if (index < sizeof(STRINGS) / sizeof(std::string)){ + return STRINGS[(size_t)type]; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid ConsoleType enum: " + std::to_string(index) + ); +} + +[[noreturn]] void throw_conflict( + Logger& logger, + ConsoleType user_type, + ConsoleType detected_type +){ + throw UserSetupError( + logger, + std::string("Conflicting Console Types:") + + "\n User Selected: " + ConsoleType_strings(user_type) + + "\n Detected Type: " + ConsoleType_strings(detected_type) + + "\n\nIf you think this is a bug, please report it to either our Github or our Discord server!" + ); +} + + + +void check_for_conflict( + Logger& logger, + ConsoleType user_type, + ConsoleType detected_type +){ + if (user_type == detected_type){ + return; + } + if (user_type == ConsoleType::Unknown || detected_type == ConsoleType::Unknown){ + return; + } + + if (is_switch1(user_type) && is_switch1(detected_type)){ + return; + } + + if (is_switch2(user_type) && is_switch2(detected_type)){ + if (user_type == ConsoleType::Switch2_Unknown || detected_type == ConsoleType::Switch2_Unknown){ + return; + } + if (user_type != detected_type){ + throw_conflict(logger, user_type, detected_type); + } + return; + } + + throw_conflict(logger, user_type, detected_type); +} + + + + + + +struct ConsoleState::Data{ + Data() + : m_console_type_confirmed(false) + , m_console_type(ConsoleType::Unknown) + , m_text_size_standard(false) + {} + + std::atomic m_console_type_confirmed; + std::atomic m_console_type; + + std::atomic m_text_size_standard; +}; + + + +ConsoleState::~ConsoleState() = default; +ConsoleState::ConsoleState() + : m_data(CONSTRUCT_TOKEN) +{} + +bool ConsoleState::console_type_confirmed() const{ + return m_data->m_console_type_confirmed.load(std::memory_order_relaxed); +} +ConsoleType ConsoleState::console_type() const{ + return m_data->m_console_type.load(std::memory_order_relaxed); +} +void ConsoleState::set_console_type_user(ConsoleType type){ + m_data->m_console_type_confirmed.store(false, std::memory_order_relaxed); + m_data->m_console_type.store(type, std::memory_order_relaxed); +} +void ConsoleState::set_console_type(Logger& logger, ConsoleType type){ + ConsoleType current = console_type(); + bool confirmed = m_data->m_console_type_confirmed.load(std::memory_order_relaxed); + if (!confirmed){ + check_for_conflict(logger, current, type); + } + + do{ + if (type == ConsoleType::Unknown){ + return; + } + if (current == ConsoleType::Unknown){ + break; + } + + if (type == ConsoleType::Switch2_Unknown){ + return; + } + + }while (false); + + if (!confirmed || current != type){ + logger.log( + std::string("Setting console type to: ") + ConsoleType_strings(type), + COLOR_BLUE + ); + } + + m_data->m_console_type.store(type, std::memory_order_relaxed); + m_data->m_console_type_confirmed.store(true, std::memory_order_relaxed); +} + + + +bool ConsoleState::text_size_ok() const{ + return m_data->m_text_size_standard.load(std::memory_order_relaxed); +} +void ConsoleState::set_text_size_ok(bool ok){ + m_data->m_text_size_standard.store(ok, std::memory_order_relaxed); +} + + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h index c6f6750906..f1319c4618 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_ConsoleState.h @@ -1,72 +1,72 @@ -/* Console State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ConsoleState_H -#define PokemonAutomation_NintendoSwitch_ConsoleState_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/Pimpl.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -enum class ConsoleType{ - Unknown, - Switch1, - Switch2_Unknown, - Switch2_FW19_International, - Switch2_FW19_JapanLocked, - Switch2_FW20_International, - Switch2_FW20_JapanLocked, -}; -const std::string& ConsoleType_strings(ConsoleType type); - -inline bool is_switch1(ConsoleType type){ - return type == ConsoleType::Switch1; -} -inline bool is_switch2(ConsoleType type){ - return type == ConsoleType::Switch2_Unknown - || type == ConsoleType::Switch2_FW19_International - || type == ConsoleType::Switch2_FW19_JapanLocked - || type == ConsoleType::Switch2_FW20_International - || type == ConsoleType::Switch2_FW20_JapanLocked; -} -void check_for_conflict( - Logger& logger, - ConsoleType user_type, - ConsoleType detected_type -); - - - - -class ConsoleState{ -public: - ~ConsoleState(); - ConsoleState(); - - - bool console_type_confirmed() const; - ConsoleType console_type() const; - void set_console_type_user(ConsoleType type); - void set_console_type(Logger& logger, ConsoleType type); - - bool text_size_ok() const; - void set_text_size_ok(bool ok); - -private: - struct Data; - Pimpl m_data; -}; - - - - -} -} -#endif +/* Console State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ConsoleState_H +#define PokemonAutomation_NintendoSwitch_ConsoleState_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/Pimpl.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +enum class ConsoleType{ + Unknown, + Switch1, + Switch2_Unknown, + Switch2_FW19_International, + Switch2_FW19_JapanLocked, + Switch2_FW20_International, + Switch2_FW20_JapanLocked, +}; +const std::string& ConsoleType_strings(ConsoleType type); + +inline bool is_switch1(ConsoleType type){ + return type == ConsoleType::Switch1; +} +inline bool is_switch2(ConsoleType type){ + return type == ConsoleType::Switch2_Unknown + || type == ConsoleType::Switch2_FW19_International + || type == ConsoleType::Switch2_FW19_JapanLocked + || type == ConsoleType::Switch2_FW20_International + || type == ConsoleType::Switch2_FW20_JapanLocked; +} +void check_for_conflict( + Logger& logger, + ConsoleType user_type, + ConsoleType detected_type +); + + + + +class ConsoleState{ +public: + ~ConsoleState(); + ConsoleState(); + + + bool console_type_confirmed() const; + ConsoleType console_type() const; + void set_console_type_user(ConsoleType type); + void set_console_type(Logger& logger, ConsoleType type); + + bool text_size_ok() const; + void set_text_size_ok(bool ok); + +private: + struct Data; + Pimpl m_data; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp index 7b7715c6e6..14bef83eda 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.cpp @@ -1,224 +1,224 @@ -/* Multi-Switch Program Template - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" -#include "CommonTools/StartupChecks/StartProgramChecks.h" -#include "Controllers/ControllerSession.h" -#include "NintendoSwitch_MultiSwitchProgram.h" -#include "Framework/NintendoSwitch_MultiSwitchProgramOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -MultiSwitchProgramEnvironment::~MultiSwitchProgramEnvironment(){} - -MultiSwitchProgramEnvironment::MultiSwitchProgramEnvironment( - const ProgramInfo& program_info, - CancellableScope& scope, - ProgramSession& session, - StatsTracker* current_stats, - const StatsTracker* historical_stats, - FixedLimitVector p_switches -) - : ProgramEnvironment(program_info, session, current_stats, historical_stats) - , consoles(std::move(p_switches)) -{ - for (ConsoleHandle& console : consoles){ - console.initialize_inference_threads(scope, realtime_inference_dispatcher()); - } -} - -void MultiSwitchProgramEnvironment::run_in_parallel( - CancellableScope& scope, - const std::function& func -){ - run_in_parallel(scope, 0, consoles.size(), func); -} -void MultiSwitchProgramEnvironment::run_in_parallel( - CancellableScope& scope, - const std::function& func -){ - run_in_parallel(scope, 0, consoles.size(), func); -} -void MultiSwitchProgramEnvironment::run_in_parallel( - CancellableScope& scope, size_t s, size_t e, - const std::function& func -){ - realtime_dispatcher().run_in_parallel( - s, e, - [&](size_t index){ - ConsoleHandle& console = consoles[index]; - ThreadUtilizationStat stat(current_thread_handle(), "Program Thread " + std::to_string(index) + ":"); - console.overlay().add_stat(stat); - try{ - func(scope, console); - console.controller().wait_for_all(&scope); - console.overlay().remove_stat(stat); - }catch (...){ - console.overlay().remove_stat(stat); - throw; - } - } - ); -} -void MultiSwitchProgramEnvironment::run_in_parallel( - CancellableScope& scope, size_t s, size_t e, - const std::function& func -){ - realtime_dispatcher().run_in_parallel( - s, e, - [&](size_t index){ - ConsoleHandle& console = consoles[index]; - ThreadUtilizationStat stat(current_thread_handle(), "Program Thread " + std::to_string(index) + ":"); - console.overlay().add_stat(stat); - try{ - ProControllerContext context(scope, consoles[index].pro_controller()); // REMOVE: don't use pro_controller() - func(console, context); - context.wait_for_all_requests(); - console.overlay().remove_stat(stat); - }catch (...){ - console.overlay().remove_stat(stat); - throw; - } - } - ); -} - -void MultiSwitchProgramEnvironment::add_overlay_log_to_all_consoles(const std::string& message, Color color){ - for (auto&console: consoles){ - console.overlay().add_log(message, color); - } -} - -void MultiSwitchProgramEnvironment::clear_all_overlay_logs(){ - for (auto&console: consoles){ - console.overlay().clear_log(); - } -} - - -MultiSwitchProgramDescriptor::MultiSwitchProgramDescriptor( - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - ControllerFeatures required_features, - FasterIfTickPrecise faster_if_tick_precise, - size_t min_switches, - size_t max_switches, - size_t default_switches -) - : ProgramDescriptor( - pick_color(required_features, faster_if_tick_precise), - std::move(identifier), - std::move(category), std::move(display_name), - std::move(doc_link), - std::move(description) - ) - , m_feedback(feedback) - , m_required_features(std::move(required_features)) - , m_faster_if_tick_precise(faster_if_tick_precise) - , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) - , m_min_switches(min_switches) - , m_max_switches(max_switches) - , m_default_switches(default_switches) -{} -std::unique_ptr MultiSwitchProgramDescriptor::make_panel() const{ - return std::unique_ptr(new MultiSwitchProgramOption(*this)); -} - - - - -MultiSwitchProgramInstance::~MultiSwitchProgramInstance() = default; -MultiSwitchProgramInstance::MultiSwitchProgramInstance( - const std::vector& error_notification_tags -) - : m_options(LockMode::UNLOCK_WHILE_RUNNING) - , NOTIFICATION_PROGRAM_FINISH( - "Program Finished", - true, true, - ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_ERROR_RECOVERABLE( - "Program Error (Recoverable)", - true, false, - ImageAttachmentMode::PNG, - error_notification_tags - ) - , NOTIFICATION_ERROR_FATAL( - "Program Error (Fatal)", - true, true, - ImageAttachmentMode::PNG, - error_notification_tags - ) -{} - - -void MultiSwitchProgramInstance::start_program_controller_check( - ControllerSession& session, size_t console_index -){ - if (!session.ready()){ - throw UserSetupError(session.logger(), "Cannot Start: Controller is not ready."); - } -} -void MultiSwitchProgramInstance::start_program_feedback_check( - VideoStream& stream, size_t console_index, - FeedbackType feedback_type -){ - StartProgramChecks::check_feedback(stream, feedback_type); -} -void MultiSwitchProgramInstance::start_program_border_check( - VideoStream& stream, size_t console_index, - FeedbackType feedback_type -){ - switch (feedback_type){ - case FeedbackType::NONE: - case FeedbackType::OPTIONAL_: - return; - case FeedbackType::REQUIRED: - case FeedbackType::VIDEO_AUDIO: - StartProgramChecks::check_border(stream); - } -} - - -void MultiSwitchProgramInstance::add_option(ConfigOption& option, std::string serialization_string){ - m_options.add_option(option, std::move(serialization_string)); -} -void MultiSwitchProgramInstance::from_json(const JsonValue& json){ - m_options.load_json(json); -} -JsonValue MultiSwitchProgramInstance::to_json() const{ - return m_options.to_json(); -} -std::string MultiSwitchProgramInstance::check_validity() const{ - return m_options.check_validity(); -} -void MultiSwitchProgramInstance::restore_defaults(){ - return m_options.restore_defaults(); -} - - - - - - - - - - - - -} -} +/* Multi-Switch Program Template + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/VideoPipeline/Stats/ThreadUtilizationStats.h" +#include "CommonTools/StartupChecks/StartProgramChecks.h" +#include "Controllers/ControllerSession.h" +#include "NintendoSwitch_MultiSwitchProgram.h" +#include "Framework/NintendoSwitch_MultiSwitchProgramOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +MultiSwitchProgramEnvironment::~MultiSwitchProgramEnvironment(){} + +MultiSwitchProgramEnvironment::MultiSwitchProgramEnvironment( + const ProgramInfo& program_info, + CancellableScope& scope, + ProgramSession& session, + StatsTracker* current_stats, + const StatsTracker* historical_stats, + FixedLimitVector p_switches +) + : ProgramEnvironment(program_info, session, current_stats, historical_stats) + , consoles(std::move(p_switches)) +{ + for (ConsoleHandle& console : consoles){ + console.initialize_inference_threads(scope, realtime_inference_dispatcher()); + } +} + +void MultiSwitchProgramEnvironment::run_in_parallel( + CancellableScope& scope, + const std::function& func +){ + run_in_parallel(scope, 0, consoles.size(), func); +} +void MultiSwitchProgramEnvironment::run_in_parallel( + CancellableScope& scope, + const std::function& func +){ + run_in_parallel(scope, 0, consoles.size(), func); +} +void MultiSwitchProgramEnvironment::run_in_parallel( + CancellableScope& scope, size_t s, size_t e, + const std::function& func +){ + realtime_dispatcher().run_in_parallel( + s, e, + [&](size_t index){ + ConsoleHandle& console = consoles[index]; + ThreadUtilizationStat stat(current_thread_handle(), "Program Thread " + std::to_string(index) + ":"); + console.overlay().add_stat(stat); + try{ + func(scope, console); + console.controller().wait_for_all(&scope); + console.overlay().remove_stat(stat); + }catch (...){ + console.overlay().remove_stat(stat); + throw; + } + } + ); +} +void MultiSwitchProgramEnvironment::run_in_parallel( + CancellableScope& scope, size_t s, size_t e, + const std::function& func +){ + realtime_dispatcher().run_in_parallel( + s, e, + [&](size_t index){ + ConsoleHandle& console = consoles[index]; + ThreadUtilizationStat stat(current_thread_handle(), "Program Thread " + std::to_string(index) + ":"); + console.overlay().add_stat(stat); + try{ + ProControllerContext context(scope, consoles[index].pro_controller()); // REMOVE: don't use pro_controller() + func(console, context); + context.wait_for_all_requests(); + console.overlay().remove_stat(stat); + }catch (...){ + console.overlay().remove_stat(stat); + throw; + } + } + ); +} + +void MultiSwitchProgramEnvironment::add_overlay_log_to_all_consoles(const std::string& message, Color color){ + for (auto&console: consoles){ + console.overlay().add_log(message, color); + } +} + +void MultiSwitchProgramEnvironment::clear_all_overlay_logs(){ + for (auto&console: consoles){ + console.overlay().clear_log(); + } +} + + +MultiSwitchProgramDescriptor::MultiSwitchProgramDescriptor( + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + ControllerFeatures required_features, + FasterIfTickPrecise faster_if_tick_precise, + size_t min_switches, + size_t max_switches, + size_t default_switches +) + : ProgramDescriptor( + pick_color(required_features, faster_if_tick_precise), + std::move(identifier), + std::move(category), std::move(display_name), + std::move(doc_link), + std::move(description) + ) + , m_feedback(feedback) + , m_required_features(std::move(required_features)) + , m_faster_if_tick_precise(faster_if_tick_precise) + , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) + , m_min_switches(min_switches) + , m_max_switches(max_switches) + , m_default_switches(default_switches) +{} +std::unique_ptr MultiSwitchProgramDescriptor::make_panel() const{ + return std::unique_ptr(new MultiSwitchProgramOption(*this)); +} + + + + +MultiSwitchProgramInstance::~MultiSwitchProgramInstance() = default; +MultiSwitchProgramInstance::MultiSwitchProgramInstance( + const std::vector& error_notification_tags +) + : m_options(LockMode::UNLOCK_WHILE_RUNNING) + , NOTIFICATION_PROGRAM_FINISH( + "Program Finished", + true, true, + ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_ERROR_RECOVERABLE( + "Program Error (Recoverable)", + true, false, + ImageAttachmentMode::PNG, + error_notification_tags + ) + , NOTIFICATION_ERROR_FATAL( + "Program Error (Fatal)", + true, true, + ImageAttachmentMode::PNG, + error_notification_tags + ) +{} + + +void MultiSwitchProgramInstance::start_program_controller_check( + ControllerSession& session, size_t console_index +){ + if (!session.ready()){ + throw UserSetupError(session.logger(), "Cannot Start: Controller is not ready."); + } +} +void MultiSwitchProgramInstance::start_program_feedback_check( + VideoStream& stream, size_t console_index, + FeedbackType feedback_type +){ + StartProgramChecks::check_feedback(stream, feedback_type); +} +void MultiSwitchProgramInstance::start_program_border_check( + VideoStream& stream, size_t console_index, + FeedbackType feedback_type +){ + switch (feedback_type){ + case FeedbackType::NONE: + case FeedbackType::OPTIONAL_: + return; + case FeedbackType::REQUIRED: + case FeedbackType::VIDEO_AUDIO: + StartProgramChecks::check_border(stream); + } +} + + +void MultiSwitchProgramInstance::add_option(ConfigOption& option, std::string serialization_string){ + m_options.add_option(option, std::move(serialization_string)); +} +void MultiSwitchProgramInstance::from_json(const JsonValue& json){ + m_options.load_json(json); +} +JsonValue MultiSwitchProgramInstance::to_json() const{ + return m_options.to_json(); +} +std::string MultiSwitchProgramInstance::check_validity() const{ + return m_options.check_validity(); +} +void MultiSwitchProgramInstance::restore_defaults(){ + return m_options.restore_defaults(); +} + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h index 0613c06187..f2abaa8c09 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h @@ -1,217 +1,217 @@ -/* Multi-Switch Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgram_H -#define PokemonAutomation_NintendoSwitch_MultiSwitchProgram_H - -#include -//#include "Common/Compiler.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "Common/Cpp/Options/BatchOption.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Panels/ProgramDescriptor.h" -#include "Controllers/ControllerCapability.h" -#include "Controllers/SerialPABotBase/SerialPABotBase.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class ControllerSession; -namespace NintendoSwitch{ - - -class MultiSwitchProgramInstance; - - -class MultiSwitchProgramEnvironment : public ProgramEnvironment{ -public: - ~MultiSwitchProgramEnvironment(); - MultiSwitchProgramEnvironment( - const ProgramInfo& program_info, - CancellableScope& scope, - ProgramSession& session, - StatsTracker* current_stats, - const StatsTracker* historical_stats, - FixedLimitVector p_switches - ); - - FixedLimitVector consoles; - - // Run the specified lambda for all switches in parallel. - void run_in_parallel( - CancellableScope& scope, - const std::function& func - ); - void run_in_parallel( // REMOVE: Temporary for refactor. - CancellableScope& scope, - const std::function& func - ); - - // Run the specified lambda for switch indices [s, e) in parallel. - void run_in_parallel( - CancellableScope& scope, size_t s, size_t e, - const std::function& func - ); - void run_in_parallel( // REMOVE: Temporary for refactor. - CancellableScope& scope, size_t s, size_t e, - const std::function& func - ); - - // add video overlay log on all console video streams - void add_overlay_log_to_all_consoles(const std::string& message, Color color = COLOR_WHITE); - // clear video overlay log on all console video streams - void clear_all_overlay_logs(); -}; - - - -class MultiSwitchProgramDescriptor : public ProgramDescriptor{ -public: - MultiSwitchProgramDescriptor( - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - ControllerFeatures required_features, - FasterIfTickPrecise faster_if_tick_precise, - size_t min_switches, - size_t max_switches, - size_t default_switches - ); - - FeedbackType feedback() const{ return m_feedback; } - const ControllerFeatures& required_features() const{ return m_required_features; } - FasterIfTickPrecise faster_if_tick_precise() const{ return m_faster_if_tick_precise; } - bool allow_commands_while_running() const{ return m_allow_commands_while_running; } - - size_t min_switches() const{ return m_min_switches; } - size_t max_switches() const{ return m_max_switches; } - size_t default_switches() const{ return m_default_switches; } - - virtual std::unique_ptr make_panel() const override; - virtual std::unique_ptr make_instance() const{ return nullptr; } - -private: - const FeedbackType m_feedback; - const ControllerFeatures m_required_features; - const FasterIfTickPrecise m_faster_if_tick_precise; - const bool m_allow_commands_while_running; - - const size_t m_min_switches; - const size_t m_max_switches; - const size_t m_default_switches; -}; - - - - -// -// As of this writing, this class will never be called in a manner where -// thread-safety is of concern with one exception: config options -// -// Here is the curent status: -// -// Called from UI thread: -// - Construction/destruction -// - from/to_json() -// - restore_defaults() -// -// Called from program thread: -// - program() -// -// Called from both UI and program threads: -// - check_validity() -// - All config options. -// -// With the exception of the configs, nothing will be called concurrently from -// different threads. -// -class MultiSwitchProgramInstance{ -public: - virtual ~MultiSwitchProgramInstance(); - MultiSwitchProgramInstance(const MultiSwitchProgramInstance&) = delete; - void operator=(const MultiSwitchProgramInstance&) = delete; - - MultiSwitchProgramInstance( - const std::vector& error_notification_tags = {"Notifs"} - ); - - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) = 0; - - -public: - // Startup Checks: Feel free to override to change behavior. - - virtual void start_program_controller_check( - ControllerSession& session, size_t console_index - ); - virtual void start_program_feedback_check( - VideoStream& stream, size_t console_index, - FeedbackType feedback_type - ); - virtual void start_program_border_check( - VideoStream& stream, size_t console_index, - FeedbackType feedback_type - ); - - -public: - // Settings - - virtual void from_json(const JsonValue& json); - virtual JsonValue to_json() const; - - virtual std::string check_validity() const; - virtual void restore_defaults(); - - // Called when the # of Switches changes. - virtual void update_active_consoles(size_t switch_count){} - - -protected: - friend class MultiSwitchProgramOption; - - BatchOption m_options; - void add_option(ConfigOption& option, std::string serialization_string); - - -public: - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationOption NOTIFICATION_ERROR_RECOVERABLE; - EventNotificationOption NOTIFICATION_ERROR_FATAL; -}; - - - - -template -class MultiSwitchProgramWrapper : public Descriptor{ -public: - virtual std::unique_ptr make_instance() const override{ - return std::unique_ptr(new Instance()); - } -}; - -template -std::unique_ptr make_multi_switch_program(){ - return std::make_unique>(); -} - - - - - - - - - -} -} -#endif - +/* Multi-Switch Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MultiSwitchProgram_H +#define PokemonAutomation_NintendoSwitch_MultiSwitchProgram_H + +#include +//#include "Common/Compiler.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "Common/Cpp/Options/BatchOption.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Panels/ProgramDescriptor.h" +#include "Controllers/ControllerCapability.h" +#include "Controllers/SerialPABotBase/SerialPABotBase.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class ControllerSession; +namespace NintendoSwitch{ + + +class MultiSwitchProgramInstance; + + +class MultiSwitchProgramEnvironment : public ProgramEnvironment{ +public: + ~MultiSwitchProgramEnvironment(); + MultiSwitchProgramEnvironment( + const ProgramInfo& program_info, + CancellableScope& scope, + ProgramSession& session, + StatsTracker* current_stats, + const StatsTracker* historical_stats, + FixedLimitVector p_switches + ); + + FixedLimitVector consoles; + + // Run the specified lambda for all switches in parallel. + void run_in_parallel( + CancellableScope& scope, + const std::function& func + ); + void run_in_parallel( // REMOVE: Temporary for refactor. + CancellableScope& scope, + const std::function& func + ); + + // Run the specified lambda for switch indices [s, e) in parallel. + void run_in_parallel( + CancellableScope& scope, size_t s, size_t e, + const std::function& func + ); + void run_in_parallel( // REMOVE: Temporary for refactor. + CancellableScope& scope, size_t s, size_t e, + const std::function& func + ); + + // add video overlay log on all console video streams + void add_overlay_log_to_all_consoles(const std::string& message, Color color = COLOR_WHITE); + // clear video overlay log on all console video streams + void clear_all_overlay_logs(); +}; + + + +class MultiSwitchProgramDescriptor : public ProgramDescriptor{ +public: + MultiSwitchProgramDescriptor( + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + ControllerFeatures required_features, + FasterIfTickPrecise faster_if_tick_precise, + size_t min_switches, + size_t max_switches, + size_t default_switches + ); + + FeedbackType feedback() const{ return m_feedback; } + const ControllerFeatures& required_features() const{ return m_required_features; } + FasterIfTickPrecise faster_if_tick_precise() const{ return m_faster_if_tick_precise; } + bool allow_commands_while_running() const{ return m_allow_commands_while_running; } + + size_t min_switches() const{ return m_min_switches; } + size_t max_switches() const{ return m_max_switches; } + size_t default_switches() const{ return m_default_switches; } + + virtual std::unique_ptr make_panel() const override; + virtual std::unique_ptr make_instance() const{ return nullptr; } + +private: + const FeedbackType m_feedback; + const ControllerFeatures m_required_features; + const FasterIfTickPrecise m_faster_if_tick_precise; + const bool m_allow_commands_while_running; + + const size_t m_min_switches; + const size_t m_max_switches; + const size_t m_default_switches; +}; + + + + +// +// As of this writing, this class will never be called in a manner where +// thread-safety is of concern with one exception: config options +// +// Here is the curent status: +// +// Called from UI thread: +// - Construction/destruction +// - from/to_json() +// - restore_defaults() +// +// Called from program thread: +// - program() +// +// Called from both UI and program threads: +// - check_validity() +// - All config options. +// +// With the exception of the configs, nothing will be called concurrently from +// different threads. +// +class MultiSwitchProgramInstance{ +public: + virtual ~MultiSwitchProgramInstance(); + MultiSwitchProgramInstance(const MultiSwitchProgramInstance&) = delete; + void operator=(const MultiSwitchProgramInstance&) = delete; + + MultiSwitchProgramInstance( + const std::vector& error_notification_tags = {"Notifs"} + ); + + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) = 0; + + +public: + // Startup Checks: Feel free to override to change behavior. + + virtual void start_program_controller_check( + ControllerSession& session, size_t console_index + ); + virtual void start_program_feedback_check( + VideoStream& stream, size_t console_index, + FeedbackType feedback_type + ); + virtual void start_program_border_check( + VideoStream& stream, size_t console_index, + FeedbackType feedback_type + ); + + +public: + // Settings + + virtual void from_json(const JsonValue& json); + virtual JsonValue to_json() const; + + virtual std::string check_validity() const; + virtual void restore_defaults(); + + // Called when the # of Switches changes. + virtual void update_active_consoles(size_t switch_count){} + + +protected: + friend class MultiSwitchProgramOption; + + BatchOption m_options; + void add_option(ConfigOption& option, std::string serialization_string); + + +public: + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationOption NOTIFICATION_ERROR_RECOVERABLE; + EventNotificationOption NOTIFICATION_ERROR_FATAL; +}; + + + + +template +class MultiSwitchProgramWrapper : public Descriptor{ +public: + virtual std::unique_ptr make_instance() const override{ + return std::unique_ptr(new Instance()); + } +}; + +template +std::unique_ptr make_multi_switch_program(){ + return std::make_unique>(); +} + + + + + + + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.cpp index dba29f1f55..8647406bf5 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.cpp @@ -1,91 +1,91 @@ -/* Nintendo Switch Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NintendoSwitch_Panels.h" - -#include "NintendoSwitch_Settings.h" - -#include "Programs/NintendoSwitch_VirtualConsole.h" -#include "Programs/NintendoSwitch_SwitchViewer.h" - -#include "Programs/NintendoSwitch_TurboA.h" -#include "Programs/NintendoSwitch_TurboButton.h" -#include "Programs/NintendoSwitch_TurboMacro.h" -#include "Programs/NintendoSwitch_PushJoySticks.h" -#include "Programs/NintendoSwitch_PreventSleep.h" -#include "Programs/NintendoSwitch_FriendCodeAdder.h" -#include "Programs/NintendoSwitch_FriendDelete.h" - -#include "DevPrograms/BoxDraw.h" -#include "Programs/NintendoSwitch_SnapshotDumper.h" -#include "Programs/NintendoSwitch_MenuStabilityTester.h" -#include "DevPrograms/TestProgramComputer.h" -#include "DevPrograms/TestProgramSwitch.h" -#include "DevPrograms/JoyconProgram.h" -#include "DevPrograms/TestDudunsparceFormDetector.h" -#include "Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h" -#include "Pokemon/Inference/Pokemon_TrainPokemonOCR.h" - -#ifdef PA_OFFICIAL -#include "../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.h" -#endif - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor("Nintendo Switch") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- Virtual Consoles ----"); - ret.emplace_back(make_panel()); - ret.emplace_back(make_panel()); - - ret.emplace_back("---- Programs ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - -// ret.emplace_back("---- " + STRING_POKEMON + " Home ----"); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_computer_program()); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_computer_program()); - ret.emplace_back(make_computer_program()); - ret.emplace_back(make_single_switch_program()); -#ifdef PA_OFFICIAL - add_panels(ret); -#endif - } - - return ret; -} - - - - - -} -} +/* Nintendo Switch Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NintendoSwitch_Panels.h" + +#include "NintendoSwitch_Settings.h" + +#include "Programs/NintendoSwitch_VirtualConsole.h" +#include "Programs/NintendoSwitch_SwitchViewer.h" + +#include "Programs/NintendoSwitch_TurboA.h" +#include "Programs/NintendoSwitch_TurboButton.h" +#include "Programs/NintendoSwitch_TurboMacro.h" +#include "Programs/NintendoSwitch_PushJoySticks.h" +#include "Programs/NintendoSwitch_PreventSleep.h" +#include "Programs/NintendoSwitch_FriendCodeAdder.h" +#include "Programs/NintendoSwitch_FriendDelete.h" + +#include "DevPrograms/BoxDraw.h" +#include "Programs/NintendoSwitch_SnapshotDumper.h" +#include "Programs/NintendoSwitch_MenuStabilityTester.h" +#include "DevPrograms/TestProgramComputer.h" +#include "DevPrograms/TestProgramSwitch.h" +#include "DevPrograms/JoyconProgram.h" +#include "DevPrograms/TestDudunsparceFormDetector.h" +#include "Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h" +#include "Pokemon/Inference/Pokemon_TrainPokemonOCR.h" + +#ifdef PA_OFFICIAL +#include "../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.h" +#endif + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor("Nintendo Switch") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- Virtual Consoles ----"); + ret.emplace_back(make_panel()); + ret.emplace_back(make_panel()); + + ret.emplace_back("---- Programs ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + +// ret.emplace_back("---- " + STRING_POKEMON + " Home ----"); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_computer_program()); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_computer_program()); + ret.emplace_back(make_computer_program()); + ret.emplace_back(make_single_switch_program()); +#ifdef PA_OFFICIAL + add_panels(ret); +#endif + } + + return ret; +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.h index d88acdd0d1..26a718d130 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Panels.h @@ -1,28 +1,28 @@ -/* Nintendo Switch Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Panels_H -#define PokemonAutomation_NintendoSwitch_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -#endif +/* Nintendo Switch Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Panels_H +#define PokemonAutomation_NintendoSwitch_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp index 85a77c689c..2e6bff240e 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.cpp @@ -1,172 +1,172 @@ -/* Nintendo Switch Settings Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NintendoSwitch_Settings.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - -const Resolution DEFAULT_RESOLUTION(1920, 1080); - - - -TimingOptions::TimingOptions() - : GroupOption( - "Timing Options", - LockMode::UNLOCK_WHILE_RUNNING, - EnableMode::ALWAYS_ENABLED, - true - ) - , WIRED_MICROCONTROLLER( - "Wired Microcontroller Timing Variation:
" - "Assume that wired microcontrollers have a timing variation of no greater than this. " - "This is used to adjust button delays to ensure they go through correctly.", - LockMode::LOCK_WHILE_RUNNING, - 0ms, 200ms, "0 ms" - ) - , WIRELESS_ESP32( - "Wireless ESP32 Timing Variation:
" - "Assume that wireless ESP32 controllers have a timing variation of no greater than this. " - "This is used to adjust button delays to ensure they go through correctly.", - LockMode::LOCK_WHILE_RUNNING, - 0ms, 200ms, "10 ms" - ) - , SYSBOTBASE( - "sys-botbase Timing Variation:
" - "Assume that sys-botbase controllers have a timing variation of no greater than this. " - "This is used to adjust button delays to ensure they go through correctly.", - LockMode::LOCK_WHILE_RUNNING, - 0ms, 200ms, "150 ms" - ) -{ - PA_ADD_OPTION(WIRED_MICROCONTROLLER); - PA_ADD_OPTION(WIRELESS_ESP32); - PA_ADD_OPTION(SYSBOTBASE); -} - - - - - -ConsoleSettings& ConsoleSettings::instance(){ - static ConsoleSettings settings; - return settings; -} -ConsoleSettings::ConsoleSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , TRUST_USER_CONSOLE_SELECTION( - "Trust User Console Selection:
" - "Trust that the user's selection for the console type (Switch 1 vs. Switch 2) is correct.
" - "Do not cross-check it. Do not stop the program if it disagrees with the user selection.
" - "Don't enable this option unless you are encountering issues.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SETTINGS_TO_HOME_DELAY0( - "Settings to Home Delay:
Delay from pressing home anywhere in the settings to return to the home menu.", - LockMode::LOCK_WHILE_RUNNING, - "960 ms" - ) - , START_GAME_REQUIRES_INTERNET( - "Start Game Requires Internet:
" - "Set this to true if starting the game requires checking the internet. " - "Otherwise, programs that require soft-resetting may not work properly.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , START_GAME_INTERNET_CHECK_DELAY0( - "Start Game Internet Check Delay:
" - "If starting the game requires checking the internet, wait this long for it.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , TOLERATE_SYSTEM_UPDATE_MENU_FAST( - "Tolerate System Update Menu (fast):
" - "Some programs can bypass the system update menu at little performance cost. Setting this to true enables this.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , TOLERATE_SYSTEM_UPDATE_MENU_SLOW( - "Tolerate System Update Menu (slow):Some programs can bypass the system update menu, but will take a noticeable performance hit. " - "Setting this to true enables this.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SWITCH1_DIGIT_ENTRY(false) - , SWITCH1_KEYBOARD_ENTRY(false) - , SWITCH2_DIGIT_ENTRY(true) - , SWITCH2_KEYBOARD_ENTRY(true) - , KEYBOARD_SECTION("Keyboard to Controller Mappings:") -{ - PA_ADD_OPTION(CONTROLLER_SETTINGS); - PA_ADD_OPTION(TRUST_USER_CONSOLE_SELECTION); - PA_ADD_OPTION(SETTINGS_TO_HOME_DELAY0); - PA_ADD_OPTION(START_GAME_REQUIRES_INTERNET); - PA_ADD_OPTION(START_GAME_INTERNET_CHECK_DELAY0); - PA_ADD_OPTION(TOLERATE_SYSTEM_UPDATE_MENU_FAST); - PA_ADD_OPTION(TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - PA_ADD_OPTION(TIMING_OPTIONS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SWITCH1_DIGIT_ENTRY); - PA_ADD_OPTION(SWITCH1_KEYBOARD_ENTRY); - PA_ADD_OPTION(SWITCH2_DIGIT_ENTRY); - PA_ADD_OPTION(SWITCH2_KEYBOARD_ENTRY); - } - PA_ADD_STATIC(KEYBOARD_SECTION); - PA_ADD_OPTION(KEYBOARD_MAPPINGS); -} -void ConsoleSettings::load_json(const JsonValue& json){ - if (m_loaded){ - return; - } - m_loaded = true; - BatchOption::load_json(json); -} - - -ConsoleSettings_Descriptor::ConsoleSettings_Descriptor() - : PanelDescriptor( - Color(), - "NintendoSwitch:GlobalSettings", - "Nintendo Switch", "Framework Settings", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/FrameworkSettings.md", - "Switch Framework Settings" - ) -{} - -ConsoleSettingsPanel::ConsoleSettingsPanel(const ConsoleSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(ConsoleSettings::instance()) -{ - PA_ADD_OPTION(settings); - - settings.CONTROLLER_SETTINGS.set_visibility( - settings.CONTROLLER_SETTINGS.current_rows() > 0 - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN - ); -} - - - - -} -} - - - - - - +/* Nintendo Switch Settings Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NintendoSwitch_Settings.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + +const Resolution DEFAULT_RESOLUTION(1920, 1080); + + + +TimingOptions::TimingOptions() + : GroupOption( + "Timing Options", + LockMode::UNLOCK_WHILE_RUNNING, + EnableMode::ALWAYS_ENABLED, + true + ) + , WIRED_MICROCONTROLLER( + "Wired Microcontroller Timing Variation:
" + "Assume that wired microcontrollers have a timing variation of no greater than this. " + "This is used to adjust button delays to ensure they go through correctly.", + LockMode::LOCK_WHILE_RUNNING, + 0ms, 200ms, "0 ms" + ) + , WIRELESS_ESP32( + "Wireless ESP32 Timing Variation:
" + "Assume that wireless ESP32 controllers have a timing variation of no greater than this. " + "This is used to adjust button delays to ensure they go through correctly.", + LockMode::LOCK_WHILE_RUNNING, + 0ms, 200ms, "10 ms" + ) + , SYSBOTBASE( + "sys-botbase Timing Variation:
" + "Assume that sys-botbase controllers have a timing variation of no greater than this. " + "This is used to adjust button delays to ensure they go through correctly.", + LockMode::LOCK_WHILE_RUNNING, + 0ms, 200ms, "150 ms" + ) +{ + PA_ADD_OPTION(WIRED_MICROCONTROLLER); + PA_ADD_OPTION(WIRELESS_ESP32); + PA_ADD_OPTION(SYSBOTBASE); +} + + + + + +ConsoleSettings& ConsoleSettings::instance(){ + static ConsoleSettings settings; + return settings; +} +ConsoleSettings::ConsoleSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , TRUST_USER_CONSOLE_SELECTION( + "Trust User Console Selection:
" + "Trust that the user's selection for the console type (Switch 1 vs. Switch 2) is correct.
" + "Do not cross-check it. Do not stop the program if it disagrees with the user selection.
" + "Don't enable this option unless you are encountering issues.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SETTINGS_TO_HOME_DELAY0( + "Settings to Home Delay:
Delay from pressing home anywhere in the settings to return to the home menu.", + LockMode::LOCK_WHILE_RUNNING, + "960 ms" + ) + , START_GAME_REQUIRES_INTERNET( + "Start Game Requires Internet:
" + "Set this to true if starting the game requires checking the internet. " + "Otherwise, programs that require soft-resetting may not work properly.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , START_GAME_INTERNET_CHECK_DELAY0( + "Start Game Internet Check Delay:
" + "If starting the game requires checking the internet, wait this long for it.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , TOLERATE_SYSTEM_UPDATE_MENU_FAST( + "Tolerate System Update Menu (fast):
" + "Some programs can bypass the system update menu at little performance cost. Setting this to true enables this.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TOLERATE_SYSTEM_UPDATE_MENU_SLOW( + "Tolerate System Update Menu (slow):Some programs can bypass the system update menu, but will take a noticeable performance hit. " + "Setting this to true enables this.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SWITCH1_DIGIT_ENTRY(false) + , SWITCH1_KEYBOARD_ENTRY(false) + , SWITCH2_DIGIT_ENTRY(true) + , SWITCH2_KEYBOARD_ENTRY(true) + , KEYBOARD_SECTION("Keyboard to Controller Mappings:") +{ + PA_ADD_OPTION(CONTROLLER_SETTINGS); + PA_ADD_OPTION(TRUST_USER_CONSOLE_SELECTION); + PA_ADD_OPTION(SETTINGS_TO_HOME_DELAY0); + PA_ADD_OPTION(START_GAME_REQUIRES_INTERNET); + PA_ADD_OPTION(START_GAME_INTERNET_CHECK_DELAY0); + PA_ADD_OPTION(TOLERATE_SYSTEM_UPDATE_MENU_FAST); + PA_ADD_OPTION(TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + PA_ADD_OPTION(TIMING_OPTIONS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SWITCH1_DIGIT_ENTRY); + PA_ADD_OPTION(SWITCH1_KEYBOARD_ENTRY); + PA_ADD_OPTION(SWITCH2_DIGIT_ENTRY); + PA_ADD_OPTION(SWITCH2_KEYBOARD_ENTRY); + } + PA_ADD_STATIC(KEYBOARD_SECTION); + PA_ADD_OPTION(KEYBOARD_MAPPINGS); +} +void ConsoleSettings::load_json(const JsonValue& json){ + if (m_loaded){ + return; + } + m_loaded = true; + BatchOption::load_json(json); +} + + +ConsoleSettings_Descriptor::ConsoleSettings_Descriptor() + : PanelDescriptor( + Color(), + "NintendoSwitch:GlobalSettings", + "Nintendo Switch", "Framework Settings", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/FrameworkSettings.md", + "Switch Framework Settings" + ) +{} + +ConsoleSettingsPanel::ConsoleSettingsPanel(const ConsoleSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(ConsoleSettings::instance()) +{ + PA_ADD_OPTION(settings); + + settings.CONTROLLER_SETTINGS.set_visibility( + settings.CONTROLLER_SETTINGS.current_rows() > 0 + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN + ); +} + + + + +} +} + + + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h index 791d24124e..4d51d70895 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_Settings.h @@ -1,87 +1,87 @@ -/* Nintendo Switch Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_Settings_H -#define PokemonAutomation_NintendoSwitch_Settings_H - -#include "Common/Cpp/ImageResolution.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" -#include "Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "Controllers/NintendoSwitch_ControllerSettings.h" -#include "Controllers/NintendoSwitch_KeyboardMapping.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -extern const Resolution DEFAULT_RESOLUTION; - - -class TimingOptions : public GroupOption{ -public: - TimingOptions(); - -public: - MillisecondsOption WIRED_MICROCONTROLLER; - MillisecondsOption WIRELESS_ESP32; - MillisecondsOption SYSBOTBASE; -}; - - -class ConsoleSettings : public BatchOption{ - ConsoleSettings(); - virtual void load_json(const JsonValue& json) override; -public: - static ConsoleSettings& instance(); - - ControllerSettingsTable CONTROLLER_SETTINGS; - - BooleanCheckBoxOption TRUST_USER_CONSOLE_SELECTION; - MillisecondsOption SETTINGS_TO_HOME_DELAY0; - BooleanCheckBoxOption START_GAME_REQUIRES_INTERNET; - MillisecondsOption START_GAME_INTERNET_CHECK_DELAY0; - BooleanCheckBoxOption TOLERATE_SYSTEM_UPDATE_MENU_FAST; - BooleanCheckBoxOption TOLERATE_SYSTEM_UPDATE_MENU_SLOW; - - TimingOptions TIMING_OPTIONS; - - DigitEntryTimingsOption SWITCH1_DIGIT_ENTRY; - KeyboardEntryTimingsOption SWITCH1_KEYBOARD_ENTRY; - DigitEntryTimingsOption SWITCH2_DIGIT_ENTRY; - KeyboardEntryTimingsOption SWITCH2_KEYBOARD_ENTRY; - - SectionDividerOption KEYBOARD_SECTION; - KeyboardMappingOption KEYBOARD_MAPPINGS; - -private: - bool m_loaded; -}; - - - - - -class ConsoleSettings_Descriptor : public PanelDescriptor{ -public: - ConsoleSettings_Descriptor(); -}; - - -class ConsoleSettingsPanel : public SettingsPanelInstance{ -public: - ConsoleSettingsPanel(const ConsoleSettings_Descriptor& descriptor); -private: - ConsoleSettings& settings; -}; - - - -} -} -#endif +/* Nintendo Switch Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_Settings_H +#define PokemonAutomation_NintendoSwitch_Settings_H + +#include "Common/Cpp/ImageResolution.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" +#include "Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "Controllers/NintendoSwitch_ControllerSettings.h" +#include "Controllers/NintendoSwitch_KeyboardMapping.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +extern const Resolution DEFAULT_RESOLUTION; + + +class TimingOptions : public GroupOption{ +public: + TimingOptions(); + +public: + MillisecondsOption WIRED_MICROCONTROLLER; + MillisecondsOption WIRELESS_ESP32; + MillisecondsOption SYSBOTBASE; +}; + + +class ConsoleSettings : public BatchOption{ + ConsoleSettings(); + virtual void load_json(const JsonValue& json) override; +public: + static ConsoleSettings& instance(); + + ControllerSettingsTable CONTROLLER_SETTINGS; + + BooleanCheckBoxOption TRUST_USER_CONSOLE_SELECTION; + MillisecondsOption SETTINGS_TO_HOME_DELAY0; + BooleanCheckBoxOption START_GAME_REQUIRES_INTERNET; + MillisecondsOption START_GAME_INTERNET_CHECK_DELAY0; + BooleanCheckBoxOption TOLERATE_SYSTEM_UPDATE_MENU_FAST; + BooleanCheckBoxOption TOLERATE_SYSTEM_UPDATE_MENU_SLOW; + + TimingOptions TIMING_OPTIONS; + + DigitEntryTimingsOption SWITCH1_DIGIT_ENTRY; + KeyboardEntryTimingsOption SWITCH1_KEYBOARD_ENTRY; + DigitEntryTimingsOption SWITCH2_DIGIT_ENTRY; + KeyboardEntryTimingsOption SWITCH2_KEYBOARD_ENTRY; + + SectionDividerOption KEYBOARD_SECTION; + KeyboardMappingOption KEYBOARD_MAPPINGS; + +private: + bool m_loaded; +}; + + + + + +class ConsoleSettings_Descriptor : public PanelDescriptor{ +public: + ConsoleSettings_Descriptor(); +}; + + +class ConsoleSettingsPanel : public SettingsPanelInstance{ +public: + ConsoleSettingsPanel(const ConsoleSettings_Descriptor& descriptor); +private: + ConsoleSettings& settings; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp index c66ad0706f..f08273e166 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.cpp @@ -1,138 +1,138 @@ -/* Single Switch Program Template - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -//#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/StartupChecks/StartProgramChecks.h" -#include "Controllers/ControllerSession.h" -#include "NintendoSwitch_SingleSwitchProgram.h" -#include "Framework/NintendoSwitch_SingleSwitchProgramOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -SingleSwitchProgramDescriptor::SingleSwitchProgramDescriptor( - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - ControllerFeatures required_features, - FasterIfTickPrecise faster_if_tick_precise -) - : ProgramDescriptor( - pick_color(required_features, faster_if_tick_precise), - std::move(identifier), - std::move(category), std::move(display_name), - std::move(doc_link), - std::move(description) - ) - , m_feedback(feedback) - , m_required_features(std::move(required_features)) - , m_faster_if_tick_precise(faster_if_tick_precise) - , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) -{} -std::unique_ptr SingleSwitchProgramDescriptor::make_panel() const{ - return std::make_unique(*this); -} - - - -SingleSwitchProgramInstance::~SingleSwitchProgramInstance() = default; -SingleSwitchProgramInstance::SingleSwitchProgramInstance( - const std::vector& error_notification_tags -) - : m_options(LockMode::UNLOCK_WHILE_RUNNING) - , NOTIFICATION_PROGRAM_FINISH( - "Program Finished", - true, true, - ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_ERROR_RECOVERABLE( - "Program Error (Recoverable)", - true, false, - ImageAttachmentMode::PNG, - error_notification_tags - - ) - , NOTIFICATION_ERROR_FATAL( - "Program Error (Fatal)", - true, true, - ImageAttachmentMode::PNG, - error_notification_tags - ) -{} - - -void SingleSwitchProgramInstance::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - ProControllerContext context(scope, env.console.pro_controller()); - program(env, context); -} -void SingleSwitchProgramInstance::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Not implemented."); -} - - -void SingleSwitchProgramInstance::start_program_controller_check( - ControllerSession& session -){ - if (!session.ready()){ - throw UserSetupError(session.logger(), "Cannot Start: Controller is not ready."); - } - - StartProgramChecks::check_controller_features( - session.logger(), - session.controller()->controller_features(), - session.required_features() - ); -} -void SingleSwitchProgramInstance::start_program_feedback_check( - VideoStream& stream, - FeedbackType feedback_type -){ - StartProgramChecks::check_feedback(stream, feedback_type); -} -void SingleSwitchProgramInstance::start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type -){ - switch (feedback_type){ - case FeedbackType::NONE: - case FeedbackType::OPTIONAL_: - return; - case FeedbackType::REQUIRED: - case FeedbackType::VIDEO_AUDIO: - StartProgramChecks::check_border(stream); - } -} - - -void SingleSwitchProgramInstance::add_option(ConfigOption& option, std::string serialization_string){ - m_options.add_option(option, std::move(serialization_string)); -} -void SingleSwitchProgramInstance::from_json(const JsonValue& json){ - m_options.load_json(json); -} -JsonValue SingleSwitchProgramInstance::to_json() const{ - return m_options.to_json(); -} -std::string SingleSwitchProgramInstance::check_validity() const{ - return m_options.check_validity(); -} -void SingleSwitchProgramInstance::restore_defaults(){ - return m_options.restore_defaults(); -} - - - - -} -} +/* Single Switch Program Template + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +//#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/StartupChecks/StartProgramChecks.h" +#include "Controllers/ControllerSession.h" +#include "NintendoSwitch_SingleSwitchProgram.h" +#include "Framework/NintendoSwitch_SingleSwitchProgramOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +SingleSwitchProgramDescriptor::SingleSwitchProgramDescriptor( + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + ControllerFeatures required_features, + FasterIfTickPrecise faster_if_tick_precise +) + : ProgramDescriptor( + pick_color(required_features, faster_if_tick_precise), + std::move(identifier), + std::move(category), std::move(display_name), + std::move(doc_link), + std::move(description) + ) + , m_feedback(feedback) + , m_required_features(std::move(required_features)) + , m_faster_if_tick_precise(faster_if_tick_precise) + , m_allow_commands_while_running(allow_commands_while_running == AllowCommandsWhenRunning::ENABLE_COMMANDS) +{} +std::unique_ptr SingleSwitchProgramDescriptor::make_panel() const{ + return std::make_unique(*this); +} + + + +SingleSwitchProgramInstance::~SingleSwitchProgramInstance() = default; +SingleSwitchProgramInstance::SingleSwitchProgramInstance( + const std::vector& error_notification_tags +) + : m_options(LockMode::UNLOCK_WHILE_RUNNING) + , NOTIFICATION_PROGRAM_FINISH( + "Program Finished", + true, true, + ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_ERROR_RECOVERABLE( + "Program Error (Recoverable)", + true, false, + ImageAttachmentMode::PNG, + error_notification_tags + + ) + , NOTIFICATION_ERROR_FATAL( + "Program Error (Fatal)", + true, true, + ImageAttachmentMode::PNG, + error_notification_tags + ) +{} + + +void SingleSwitchProgramInstance::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + ProControllerContext context(scope, env.console.pro_controller()); + program(env, context); +} +void SingleSwitchProgramInstance::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Not implemented."); +} + + +void SingleSwitchProgramInstance::start_program_controller_check( + ControllerSession& session +){ + if (!session.ready()){ + throw UserSetupError(session.logger(), "Cannot Start: Controller is not ready."); + } + + StartProgramChecks::check_controller_features( + session.logger(), + session.controller()->controller_features(), + session.required_features() + ); +} +void SingleSwitchProgramInstance::start_program_feedback_check( + VideoStream& stream, + FeedbackType feedback_type +){ + StartProgramChecks::check_feedback(stream, feedback_type); +} +void SingleSwitchProgramInstance::start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type +){ + switch (feedback_type){ + case FeedbackType::NONE: + case FeedbackType::OPTIONAL_: + return; + case FeedbackType::REQUIRED: + case FeedbackType::VIDEO_AUDIO: + StartProgramChecks::check_border(stream); + } +} + + +void SingleSwitchProgramInstance::add_option(ConfigOption& option, std::string serialization_string){ + m_options.add_option(option, std::move(serialization_string)); +} +void SingleSwitchProgramInstance::from_json(const JsonValue& json){ + m_options.load_json(json); +} +JsonValue SingleSwitchProgramInstance::to_json() const{ + return m_options.to_json(); +} +std::string SingleSwitchProgramInstance::check_validity() const{ + return m_options.check_validity(); +} +void SingleSwitchProgramInstance::restore_defaults(){ + return m_options.restore_defaults(); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h index 064c85b4ce..ba622fb063 100644 --- a/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h +++ b/SerialPrograms/Source/NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h @@ -1,187 +1,187 @@ -/* Single Switch Program - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgram_H -#define PokemonAutomation_NintendoSwitch_SingleSwitchProgram_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Panels/ProgramDescriptor.h" -#include "Controllers/ControllerCapability.h" -#include "Controllers/SerialPABotBase/SerialPABotBase.h" // REMOVE -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class ControllerSession; -namespace NintendoSwitch{ - - -class SingleSwitchProgramInstance; - - -class SingleSwitchProgramEnvironment : public ProgramEnvironment{ -public: - ConsoleHandle console; - -private: - friend class SingleSwitchProgramSession; - friend class SingleSwitchProgramWidget; - template - SingleSwitchProgramEnvironment( - const ProgramInfo& program_info, - CancellableScope& scope, - ProgramSession& session, - StatsTracker* current_stats, - const StatsTracker* historical_stats, - Args&&... args - ) - : ProgramEnvironment(program_info, session, current_stats, historical_stats) - , console(0, std::forward(args)...) - { - console.initialize_inference_threads(scope, realtime_inference_dispatcher()); - } -}; - - -class SingleSwitchProgramDescriptor : public ProgramDescriptor{ -public: - SingleSwitchProgramDescriptor( - std::string identifier, - std::string category, std::string display_name, - std::string doc_link, - std::string description, - FeedbackType feedback, - AllowCommandsWhenRunning allow_commands_while_running, - ControllerFeatures required_features, - FasterIfTickPrecise faster_if_tick_precise = FasterIfTickPrecise::NOT_FASTER - ); - - FeedbackType feedback() const{ return m_feedback; } - const ControllerFeatures& required_features() const{ return m_required_features; } - FasterIfTickPrecise faster_if_tick_precise() const{ return m_faster_if_tick_precise; } - bool allow_commands_while_running() const{ return m_allow_commands_while_running; } - - virtual std::unique_ptr make_panel() const override; - virtual std::unique_ptr make_instance() const = 0; - -private: - const FeedbackType m_feedback; - const ControllerFeatures m_required_features; - const FasterIfTickPrecise m_faster_if_tick_precise; - const bool m_allow_commands_while_running; -}; - - - - - - -// -// As of this writing, this class will never be called in a manner where -// thread-safety is of concern with one exception: config options -// -// Here is the curent status: -// -// Called from UI thread: -// - Construction/destruction -// - from/to_json() -// - restore_defaults() -// -// Called from program thread: -// - program() -// -// Called from both UI and program threads: -// - check_validity() -// - All config options. -// -// With the exception of the configs, nothing will be called concurrently from -// different threads. -// -class SingleSwitchProgramInstance{ -public: - virtual ~SingleSwitchProgramInstance(); - SingleSwitchProgramInstance(const SingleSwitchProgramInstance&) = delete; - void operator=(const SingleSwitchProgramInstance&) = delete; - - SingleSwitchProgramInstance( - const std::vector& error_notification_tags = {"Notifs"} - ); - - // Child classes should override one of these. - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - -public: - // Startup Checks: Feel free to override to change behavior. - - virtual void start_program_controller_check( - ControllerSession& session - ); - virtual void start_program_feedback_check( - VideoStream& stream, - FeedbackType feedback_type - ); - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ); - - -public: - // Settings - - virtual void from_json(const JsonValue& json); - virtual JsonValue to_json() const; - - virtual std::string check_validity() const; - virtual void restore_defaults(); - - -protected: - friend class SingleSwitchProgramOption; - - BatchOption m_options; - void add_option(ConfigOption& option, std::string serialization_string); - - -public: - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationOption NOTIFICATION_ERROR_RECOVERABLE; - EventNotificationOption NOTIFICATION_ERROR_FATAL; -}; - - - - -template -class SingleSwitchProgramWrapper : public Descriptor{ -public: - virtual std::unique_ptr make_instance() const override{ - return std::make_unique(); - } -}; - -// Create a program PanelDescriptor -template -std::unique_ptr make_single_switch_program(){ - return std::make_unique>(); -} - - - - - - - - -} -} -#endif - +/* Single Switch Program + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SingleSwitchProgram_H +#define PokemonAutomation_NintendoSwitch_SingleSwitchProgram_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Panels/ProgramDescriptor.h" +#include "Controllers/ControllerCapability.h" +#include "Controllers/SerialPABotBase/SerialPABotBase.h" // REMOVE +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class ControllerSession; +namespace NintendoSwitch{ + + +class SingleSwitchProgramInstance; + + +class SingleSwitchProgramEnvironment : public ProgramEnvironment{ +public: + ConsoleHandle console; + +private: + friend class SingleSwitchProgramSession; + friend class SingleSwitchProgramWidget; + template + SingleSwitchProgramEnvironment( + const ProgramInfo& program_info, + CancellableScope& scope, + ProgramSession& session, + StatsTracker* current_stats, + const StatsTracker* historical_stats, + Args&&... args + ) + : ProgramEnvironment(program_info, session, current_stats, historical_stats) + , console(0, std::forward(args)...) + { + console.initialize_inference_threads(scope, realtime_inference_dispatcher()); + } +}; + + +class SingleSwitchProgramDescriptor : public ProgramDescriptor{ +public: + SingleSwitchProgramDescriptor( + std::string identifier, + std::string category, std::string display_name, + std::string doc_link, + std::string description, + FeedbackType feedback, + AllowCommandsWhenRunning allow_commands_while_running, + ControllerFeatures required_features, + FasterIfTickPrecise faster_if_tick_precise = FasterIfTickPrecise::NOT_FASTER + ); + + FeedbackType feedback() const{ return m_feedback; } + const ControllerFeatures& required_features() const{ return m_required_features; } + FasterIfTickPrecise faster_if_tick_precise() const{ return m_faster_if_tick_precise; } + bool allow_commands_while_running() const{ return m_allow_commands_while_running; } + + virtual std::unique_ptr make_panel() const override; + virtual std::unique_ptr make_instance() const = 0; + +private: + const FeedbackType m_feedback; + const ControllerFeatures m_required_features; + const FasterIfTickPrecise m_faster_if_tick_precise; + const bool m_allow_commands_while_running; +}; + + + + + + +// +// As of this writing, this class will never be called in a manner where +// thread-safety is of concern with one exception: config options +// +// Here is the curent status: +// +// Called from UI thread: +// - Construction/destruction +// - from/to_json() +// - restore_defaults() +// +// Called from program thread: +// - program() +// +// Called from both UI and program threads: +// - check_validity() +// - All config options. +// +// With the exception of the configs, nothing will be called concurrently from +// different threads. +// +class SingleSwitchProgramInstance{ +public: + virtual ~SingleSwitchProgramInstance(); + SingleSwitchProgramInstance(const SingleSwitchProgramInstance&) = delete; + void operator=(const SingleSwitchProgramInstance&) = delete; + + SingleSwitchProgramInstance( + const std::vector& error_notification_tags = {"Notifs"} + ); + + // Child classes should override one of these. + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + +public: + // Startup Checks: Feel free to override to change behavior. + + virtual void start_program_controller_check( + ControllerSession& session + ); + virtual void start_program_feedback_check( + VideoStream& stream, + FeedbackType feedback_type + ); + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ); + + +public: + // Settings + + virtual void from_json(const JsonValue& json); + virtual JsonValue to_json() const; + + virtual std::string check_validity() const; + virtual void restore_defaults(); + + +protected: + friend class SingleSwitchProgramOption; + + BatchOption m_options; + void add_option(ConfigOption& option, std::string serialization_string); + + +public: + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationOption NOTIFICATION_ERROR_RECOVERABLE; + EventNotificationOption NOTIFICATION_ERROR_FATAL; +}; + + + + +template +class SingleSwitchProgramWrapper : public Descriptor{ +public: + virtual std::unique_ptr make_instance() const override{ + return std::make_unique(); + } +}; + +// Create a program PanelDescriptor +template +std::unique_ptr make_single_switch_program(){ + return std::make_unique>(); +} + + + + + + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp index 0586f9655d..5839290924 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.cpp @@ -1,139 +1,139 @@ -/* Code Entry Settings Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "NintendoSwitch_CodeEntrySettingsOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -KeyboardLayoutOption::KeyboardLayoutOption() - : EnumDropdownOption( - "Keyboard Layout:", - { - {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, - {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, - }, - LockMode::LOCK_WHILE_RUNNING, - KeyboardLayout::QWERTY - ) -{} -KeyboardLayoutOption::KeyboardLayoutOption(std::string label) - : EnumDropdownOption( - std::move(label), - { - {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, - {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, - }, - LockMode::LOCK_WHILE_RUNNING, - KeyboardLayout::QWERTY - ) -{} - -CodeEntrySkipPlusOption::CodeEntrySkipPlusOption() - : BooleanCheckBoxOption( - "Skip the Plus:
Don't press + to finalize the code. Useful for testing.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -{} - - - - - -DigitEntryTimingsOption::DigitEntryTimingsOption(bool switch2) - : GroupOption( - switch2 - ? "Switch 2 Digit Entry Timings" - : "Switch 1 Digit Entry Timings", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , REORDERING( - "Digit Reordering:
Allow digits to be entered out of order.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , TIME_UNIT( - "Time Unit:
Timesteps should increment in multiples of this unit.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - switch2 - ? "48ms" - : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) - , HOLD( - "Hold:
Duration to hold each button press down.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" - ) - , COOLDOWN( - "Hold:
Do not reuse a button until this long after it is reused.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) -{ - PA_ADD_OPTION(REORDERING); - PA_ADD_OPTION(TIME_UNIT); - PA_ADD_OPTION(HOLD); - PA_ADD_OPTION(COOLDOWN); -} - - - -KeyboardEntryTimingsOption::KeyboardEntryTimingsOption(bool switch2) - : GroupOption( - switch2 - ? "Switch 2 Keyboard Entry Timings" - : "Switch 1 Keyboard Entry Timings", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::ALWAYS_ENABLED, true - ) - , REORDERING( - "Character Reordering:
Allow characters to be entered out of order.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE - ) - , TIME_UNIT( - "Time Unit:
Timesteps should increment in multiples of this unit.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - switch2 - ? "48ms" - : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) - , HOLD( - "Hold:
Duration to hold each button press down.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" - ) - , COOLDOWN( - "Hold:
Do not reuse a button until this long after it is reused.
" - "Controller timing variation will be added to this number.", - LockMode::UNLOCK_WHILE_RUNNING, - PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" - ) -{ - PA_ADD_OPTION(REORDERING); - PA_ADD_OPTION(TIME_UNIT); - PA_ADD_OPTION(HOLD); - PA_ADD_OPTION(COOLDOWN); -} - - - - - - - -} -} +/* Code Entry Settings Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "NintendoSwitch_CodeEntrySettingsOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +KeyboardLayoutOption::KeyboardLayoutOption() + : EnumDropdownOption( + "Keyboard Layout:", + { + {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, + {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, + }, + LockMode::LOCK_WHILE_RUNNING, + KeyboardLayout::QWERTY + ) +{} +KeyboardLayoutOption::KeyboardLayoutOption(std::string label) + : EnumDropdownOption( + std::move(label), + { + {KeyboardLayout::QWERTY, "qwerty", "QWERTY"}, + {KeyboardLayout::AZERTY, "azerty", "AZERTY"}, + }, + LockMode::LOCK_WHILE_RUNNING, + KeyboardLayout::QWERTY + ) +{} + +CodeEntrySkipPlusOption::CodeEntrySkipPlusOption() + : BooleanCheckBoxOption( + "Skip the Plus:
Don't press + to finalize the code. Useful for testing.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +{} + + + + + +DigitEntryTimingsOption::DigitEntryTimingsOption(bool switch2) + : GroupOption( + switch2 + ? "Switch 2 Digit Entry Timings" + : "Switch 1 Digit Entry Timings", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , REORDERING( + "Digit Reordering:
Allow digits to be entered out of order.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , TIME_UNIT( + "Time Unit:
Timesteps should increment in multiples of this unit.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + switch2 + ? "48ms" + : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) + , HOLD( + "Hold:
Duration to hold each button press down.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" + ) + , COOLDOWN( + "Hold:
Do not reuse a button until this long after it is reused.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) +{ + PA_ADD_OPTION(REORDERING); + PA_ADD_OPTION(TIME_UNIT); + PA_ADD_OPTION(HOLD); + PA_ADD_OPTION(COOLDOWN); +} + + + +KeyboardEntryTimingsOption::KeyboardEntryTimingsOption(bool switch2) + : GroupOption( + switch2 + ? "Switch 2 Keyboard Entry Timings" + : "Switch 1 Keyboard Entry Timings", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::ALWAYS_ENABLED, true + ) + , REORDERING( + "Character Reordering:
Allow characters to be entered out of order.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE + ) + , TIME_UNIT( + "Time Unit:
Timesteps should increment in multiples of this unit.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + switch2 + ? "48ms" + : PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) + , HOLD( + "Hold:
Duration to hold each button press down.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "48 ms" : "80ms" + ) + , COOLDOWN( + "Hold:
Do not reuse a button until this long after it is reused.
" + "Controller timing variation will be added to this number.", + LockMode::UNLOCK_WHILE_RUNNING, + PreloadSettings::instance().DEVELOPER_MODE ? "24 ms" : "40ms" + ) +{ + PA_ADD_OPTION(REORDERING); + PA_ADD_OPTION(TIME_UNIT); + PA_ADD_OPTION(HOLD); + PA_ADD_OPTION(COOLDOWN); +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h index baf8b5356f..299091299a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h @@ -1,67 +1,67 @@ -/* Code Entry Settings Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H -#define PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H - -#include "Common/Cpp/Options/GroupOption.h" -//#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -enum class KeyboardLayout{ - QWERTY, - AZERTY -}; -class KeyboardLayoutOption : public EnumDropdownOption{ -public: - KeyboardLayoutOption(); - KeyboardLayoutOption(std::string label); -}; - -class CodeEntrySkipPlusOption : public BooleanCheckBoxOption{ -public: - CodeEntrySkipPlusOption(); -}; - - - - -class DigitEntryTimingsOption : public GroupOption{ -public: - DigitEntryTimingsOption(bool switch2); - -public: - BooleanCheckBoxOption REORDERING; - MillisecondsOption TIME_UNIT; - MillisecondsOption HOLD; - MillisecondsOption COOLDOWN; -}; - -class KeyboardEntryTimingsOption : public GroupOption{ -public: - KeyboardEntryTimingsOption(bool switch2); - -public: - BooleanCheckBoxOption REORDERING; - MillisecondsOption TIME_UNIT; - MillisecondsOption HOLD; - MillisecondsOption COOLDOWN; -}; - - - - - -} -} -#endif +/* Code Entry Settings Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H +#define PokemonAutomation_NintendoSwitch_CodeEntrySettingsOption_H + +#include "Common/Cpp/Options/GroupOption.h" +//#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +enum class KeyboardLayout{ + QWERTY, + AZERTY +}; +class KeyboardLayoutOption : public EnumDropdownOption{ +public: + KeyboardLayoutOption(); + KeyboardLayoutOption(std::string label); +}; + +class CodeEntrySkipPlusOption : public BooleanCheckBoxOption{ +public: + CodeEntrySkipPlusOption(); +}; + + + + +class DigitEntryTimingsOption : public GroupOption{ +public: + DigitEntryTimingsOption(bool switch2); + +public: + BooleanCheckBoxOption REORDERING; + MillisecondsOption TIME_UNIT; + MillisecondsOption HOLD; + MillisecondsOption COOLDOWN; +}; + +class KeyboardEntryTimingsOption : public GroupOption{ +public: + KeyboardEntryTimingsOption(bool switch2); + +public: + BooleanCheckBoxOption REORDERING; + MillisecondsOption TIME_UNIT; + MillisecondsOption HOLD; + MillisecondsOption COOLDOWN; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.cpp b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.cpp index 8dbf829e62..6f62c89d1e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.cpp @@ -1,126 +1,126 @@ -/* Friend Code List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "NintendoSwitch_FriendCodeListOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -FriendCodeListOption::FriendCodeListOption(std::string label, std::vector default_lines) - : m_label(std::move(label)) - , m_default(std::move(default_lines)) - , m_lines(m_default) -{} - -void FriendCodeListOption::load_json(const JsonValue& json){ - const JsonArray* list = json.to_array(); - if (list == nullptr){ - return; - } - std::vector lines; - for (const auto& line : *list){ - const std::string* str = line.to_string(); - if (str == nullptr || str->empty()){ - continue; - } - lines.emplace_back(*str); - } - { - WriteSpinLock lg(m_lock); - m_lines = std::move(lines); - } - report_value_changed(this); -} -JsonValue FriendCodeListOption::to_json() const{ - JsonArray list; - ReadSpinLock lg(m_lock); - for (const std::string& line : m_lines){ - list.push_back(line); - } - return list; -} -void FriendCodeListOption::restore_defaults(){ - { - WriteSpinLock lg(m_lock); - m_lines = m_default; - } - report_value_changed(this); -} - - - -std::string FriendCodeListOption::parse(const std::string& line){ - std::string code; - for (char ch : line){ - if ('0' <= ch && ch <= '9'){ - code.push_back(ch); - } - } - return code; -} -void FriendCodeListOption::set(const std::string& text){ - std::vector lines; - std::string line; - for (char ch : text){ - if (ch == '\n'){ - lines.emplace_back(std::move(line)); - line.clear(); - continue; - } - line += ch; - } - if (line.size() > 0){ - lines.emplace_back(std::move(line)); - } - { - WriteSpinLock lg(m_lock); - m_lines = std::move(lines); - } - report_value_changed(this); -} -std::vector FriendCodeListOption::lines() const{ - ReadSpinLock lg(m_lock); - return m_lines; -} -std::vector FriendCodeListOption::list() const{ - ReadSpinLock lg(m_lock); - std::vector ret; - for (const auto& item : m_lines){ - std::string line = parse(item); - if (line.size() != 12){ - continue; - } - std::string str = "SW"; - for (size_t c = 0; c < 12; c++){ - if (c % 4 == 0){ - str += "-"; - } - str += line[c]; - } - ret.emplace_back(std::move(str)); - } - return ret; -} - - - - - -} -} - - - - - - - - - +/* Friend Code List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "NintendoSwitch_FriendCodeListOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +FriendCodeListOption::FriendCodeListOption(std::string label, std::vector default_lines) + : m_label(std::move(label)) + , m_default(std::move(default_lines)) + , m_lines(m_default) +{} + +void FriendCodeListOption::load_json(const JsonValue& json){ + const JsonArray* list = json.to_array(); + if (list == nullptr){ + return; + } + std::vector lines; + for (const auto& line : *list){ + const std::string* str = line.to_string(); + if (str == nullptr || str->empty()){ + continue; + } + lines.emplace_back(*str); + } + { + WriteSpinLock lg(m_lock); + m_lines = std::move(lines); + } + report_value_changed(this); +} +JsonValue FriendCodeListOption::to_json() const{ + JsonArray list; + ReadSpinLock lg(m_lock); + for (const std::string& line : m_lines){ + list.push_back(line); + } + return list; +} +void FriendCodeListOption::restore_defaults(){ + { + WriteSpinLock lg(m_lock); + m_lines = m_default; + } + report_value_changed(this); +} + + + +std::string FriendCodeListOption::parse(const std::string& line){ + std::string code; + for (char ch : line){ + if ('0' <= ch && ch <= '9'){ + code.push_back(ch); + } + } + return code; +} +void FriendCodeListOption::set(const std::string& text){ + std::vector lines; + std::string line; + for (char ch : text){ + if (ch == '\n'){ + lines.emplace_back(std::move(line)); + line.clear(); + continue; + } + line += ch; + } + if (line.size() > 0){ + lines.emplace_back(std::move(line)); + } + { + WriteSpinLock lg(m_lock); + m_lines = std::move(lines); + } + report_value_changed(this); +} +std::vector FriendCodeListOption::lines() const{ + ReadSpinLock lg(m_lock); + return m_lines; +} +std::vector FriendCodeListOption::list() const{ + ReadSpinLock lg(m_lock); + std::vector ret; + for (const auto& item : m_lines){ + std::string line = parse(item); + if (line.size() != 12){ + continue; + } + std::string str = "SW"; + for (size_t c = 0; c < 12; c++){ + if (c % 4 == 0){ + str += "-"; + } + str += line[c]; + } + ret.emplace_back(std::move(str)); + } + return ret; +} + + + + + +} +} + + + + + + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h index e388cd40a9..332aac1eb3 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h @@ -1,50 +1,50 @@ -/* Friend Code List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_FriendCodeListOption_H -#define PokemonAutomation_NintendoSwitch_FriendCodeListOption_H - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Options/ConfigOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class FriendCodeListOption : public ConfigOption{ -public: - FriendCodeListOption(std::string label, std::vector default_lines); - - static std::string parse(const std::string& line); - - void set(const std::string& text); - std::vector lines() const; - std::vector list() const; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class FriendCodeListWidget; - const std::string m_label; - const std::vector m_default; - - mutable SpinLock m_lock; - std::vector m_lines; -}; - - - - -} -} -#endif - +/* Friend Code List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_FriendCodeListOption_H +#define PokemonAutomation_NintendoSwitch_FriendCodeListOption_H + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Options/ConfigOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class FriendCodeListOption : public ConfigOption{ +public: + FriendCodeListOption(std::string label, std::vector default_lines); + + static std::string parse(const std::string& line); + + void set(const std::string& text); + std::vector lines() const; + std::vector list() const; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class FriendCodeListWidget; + const std::string m_label; + const std::vector m_default; + + mutable SpinLock m_lock; + std::vector m_lines; +}; + + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.cpp b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.cpp index cf615dbe2e..8cfb62e724 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.cpp @@ -1,33 +1,33 @@ -/* Go Home When Done - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -GoHomeWhenDoneOption::GoHomeWhenDoneOption(bool default_value) - : BooleanCheckBoxOption( - "Go Home when Done:
" - "When the program finishes, go to the Switch Home menu to idle. (turn this off for unattended streaming)", - LockMode::UNLOCK_WHILE_RUNNING, - default_value - ) -{} - -void GoHomeWhenDoneOption::run_end_of_program(ProControllerContext& context){ - if (*this){ - pbf_wait(context, 5 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_HOME, 20, 125); - } -} - - - -} -} +/* Go Home When Done + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +GoHomeWhenDoneOption::GoHomeWhenDoneOption(bool default_value) + : BooleanCheckBoxOption( + "Go Home when Done:
" + "When the program finishes, go to the Switch Home menu to idle. (turn this off for unattended streaming)", + LockMode::UNLOCK_WHILE_RUNNING, + default_value + ) +{} + +void GoHomeWhenDoneOption::run_end_of_program(ProControllerContext& context){ + if (*this){ + pbf_wait(context, 5 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_HOME, 20, 125); + } +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h index 574a7d49ca..8593d730db 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h @@ -1,27 +1,27 @@ -/* Go Home When Done - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_GoHomeWhenDone_H -#define PokemonAutomation_NintendoSwitch_GoHomeWhenDone_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class GoHomeWhenDoneOption : public BooleanCheckBoxOption{ -public: - GoHomeWhenDoneOption(bool default_value); - - void run_end_of_program(ProControllerContext& context); -}; - - -} -} -#endif +/* Go Home When Done + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_GoHomeWhenDone_H +#define PokemonAutomation_NintendoSwitch_GoHomeWhenDone_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class GoHomeWhenDoneOption : public BooleanCheckBoxOption{ +public: + GoHomeWhenDoneOption(bool default_value); + + void run_end_of_program(ProControllerContext& context); +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h index 423fddd62e..290cc8bcfe 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_ModelType.h @@ -1,67 +1,67 @@ -/* Model Type - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_ModelType_H -#define PokemonAutomation_NintendoSwitch_ModelType_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -inline const EnumDropdownDatabase& CONSOLE_MODEL_DATABASE(){ - static const EnumDropdownDatabase database{ - {ConsoleType::Unknown, "unknown", "Auto-detect if possible."}, - {ConsoleType::Switch1, "switch1", ConsoleType_strings(ConsoleType::Switch1)}, - {ConsoleType::Switch2_Unknown, "switch2-unknown", ConsoleType_strings(ConsoleType::Switch2_Unknown)}, -// {ConsoleType::Switch2_FW19_International, "switch2-FW19-international", ConsoleType_strings(ConsoleType::Switch2_FW19_International)}, -// {ConsoleType::Switch2_FW19_JapanLocked, "switch2-FW19-japan", ConsoleType_strings(ConsoleType::Switch2_FW19_JapanLocked)}, - {ConsoleType::Switch2_FW20_International, "switch2-FW20-international", ConsoleType_strings(ConsoleType::Switch2_FW20_International)}, - {ConsoleType::Switch2_FW20_JapanLocked, "switch2-FW20-japan", ConsoleType_strings(ConsoleType::Switch2_FW20_JapanLocked)}, - }; - return database; -} - - - -class ConsoleModelCell : public EnumDropdownCell{ -public: - ConsoleModelCell() - : EnumDropdownCell( - CONSOLE_MODEL_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - ConsoleType::Unknown - ) - {} - -private: -}; - - -class ConsoleModelOption : public EnumDropdownOption{ -public: - ConsoleModelOption(std::string label = "Console Type:") - : EnumDropdownOption( - std::move(label), - CONSOLE_MODEL_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - ConsoleType::Unknown - ) - {} - -private: -}; - - - - - - -} -} -#endif +/* Model Type + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_ModelType_H +#define PokemonAutomation_NintendoSwitch_ModelType_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +inline const EnumDropdownDatabase& CONSOLE_MODEL_DATABASE(){ + static const EnumDropdownDatabase database{ + {ConsoleType::Unknown, "unknown", "Auto-detect if possible."}, + {ConsoleType::Switch1, "switch1", ConsoleType_strings(ConsoleType::Switch1)}, + {ConsoleType::Switch2_Unknown, "switch2-unknown", ConsoleType_strings(ConsoleType::Switch2_Unknown)}, +// {ConsoleType::Switch2_FW19_International, "switch2-FW19-international", ConsoleType_strings(ConsoleType::Switch2_FW19_International)}, +// {ConsoleType::Switch2_FW19_JapanLocked, "switch2-FW19-japan", ConsoleType_strings(ConsoleType::Switch2_FW19_JapanLocked)}, + {ConsoleType::Switch2_FW20_International, "switch2-FW20-international", ConsoleType_strings(ConsoleType::Switch2_FW20_International)}, + {ConsoleType::Switch2_FW20_JapanLocked, "switch2-FW20-japan", ConsoleType_strings(ConsoleType::Switch2_FW20_JapanLocked)}, + }; + return database; +} + + + +class ConsoleModelCell : public EnumDropdownCell{ +public: + ConsoleModelCell() + : EnumDropdownCell( + CONSOLE_MODEL_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + ConsoleType::Unknown + ) + {} + +private: +}; + + +class ConsoleModelOption : public EnumDropdownOption{ +public: + ConsoleModelOption(std::string label = "Console Type:") + : EnumDropdownOption( + std::move(label), + CONSOLE_MODEL_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + ConsoleType::Unknown + ) + {} + +private: +}; + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h index c54d94d4a3..064405a453 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h @@ -1,62 +1,62 @@ -/* Start in Grip Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_StartInGripMenu_H -#define PokemonAutomation_NintendoSwitch_StartInGripMenu_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class StartInGripOrGameOption : public IntegerEnumDropdownOption{ -public: - StartInGripOrGameOption(bool grip_menu = false) - : IntegerEnumDropdownOption( - "Start Location:
" - "If set to start in game, you must disconnect all other controllers.", - { - {0, "in-game", "Start in game."}, - {1, "grip-menu", "Start in grip menu."}, - }, - LockMode::LOCK_WHILE_RUNNING, - grip_menu ? 1 : 0 - ) - {} - - bool start_in_grip_menu() const{ - return current_value() != 0; - } - -}; - -class StartInGripOrClosedOption : public IntegerEnumDropdownOption{ -public: - StartInGripOrClosedOption(bool grip_menu = false) - : IntegerEnumDropdownOption( - "Start Location:
" - "If set to start in Switch Home, you must disconnect all other controllers.", - { - {0, "home", "Start in Switch Home with game closed."}, - {1, "grip-menu", "Start in grip menu."}, - }, - LockMode::LOCK_WHILE_RUNNING, - grip_menu ? 1 : 0 - ) - {} - - bool start_in_grip_menu() const{ - return current_value() != 0; - } - -}; - - - -} -} -#endif +/* Start in Grip Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_StartInGripMenu_H +#define PokemonAutomation_NintendoSwitch_StartInGripMenu_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class StartInGripOrGameOption : public IntegerEnumDropdownOption{ +public: + StartInGripOrGameOption(bool grip_menu = false) + : IntegerEnumDropdownOption( + "Start Location:
" + "If set to start in game, you must disconnect all other controllers.", + { + {0, "in-game", "Start in game."}, + {1, "grip-menu", "Start in grip menu."}, + }, + LockMode::LOCK_WHILE_RUNNING, + grip_menu ? 1 : 0 + ) + {} + + bool start_in_grip_menu() const{ + return current_value() != 0; + } + +}; + +class StartInGripOrClosedOption : public IntegerEnumDropdownOption{ +public: + StartInGripOrClosedOption(bool grip_menu = false) + : IntegerEnumDropdownOption( + "Start Location:
" + "If set to start in Switch Home, you must disconnect all other controllers.", + { + {0, "home", "Start in Switch Home with game closed."}, + {1, "grip-menu", "Start in grip menu."}, + }, + LockMode::LOCK_WHILE_RUNNING, + grip_menu ? 1 : 0 + ) + {} + + bool start_in_grip_menu() const{ + return current_value() != 0; + } + +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.cpp b/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.cpp index 8305ec73eb..b6b70a5caa 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.cpp @@ -1,313 +1,313 @@ -/* Turbo Macro Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Cpp/Json/JsonTools.h" -#include "NintendoSwitch/Options/TurboMacroTable.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -using namespace std::chrono_literals; - - - -const EnumDropdownDatabase& TurboMacroAction_Database(){ - static const EnumDropdownDatabase database({ - {TurboMacroAction::NO_ACTION, "no-action", "No Action"}, - {TurboMacroAction::LEFT_JOYSTICK, "left-joystick", "Left Joystick"}, - {TurboMacroAction::RIGHT_JOYSTICK, "right-joystick", "Right Joystick"}, - {TurboMacroAction::LEFT_JOY_CLICK, "left-joy-click", "Press Left Joystick (L3)"}, - {TurboMacroAction::RIGHT_JOY_CLICK, "right-joy-click", "Press Right Joystick (R3)"}, - {TurboMacroAction::B, "button-B", "Press B"}, - {TurboMacroAction::A, "button-A", "Press A"}, - {TurboMacroAction::Y, "button-Y", "Press Y"}, - {TurboMacroAction::X, "button-X", "Press X"}, - {TurboMacroAction::R, "button-R", "Press R"}, - {TurboMacroAction::L, "button-L", "Press L"}, - {TurboMacroAction::ZR, "button-ZR", "Press ZR"}, - {TurboMacroAction::ZL, "button-ZL", "Press ZL"}, - {TurboMacroAction::PLUS, "button-plus", "Press PLUS"}, - {TurboMacroAction::MINUS, "button-minus", "Press MINUS"}, - {TurboMacroAction::DPADLEFT, "dpad-left", "Press DPad Left"}, - {TurboMacroAction::DPADRIGHT, "dpad-right", "Press DPad Right"}, - {TurboMacroAction::DPADUP, "dpad-up", "Press DPad Up"}, - {TurboMacroAction::DPADDOWN, "dpad-down", "Press DPad Down"}, - {TurboMacroAction::WAIT, "wait", "Wait"} - }); - return database; -} - - - - - -TurboMacroCell::~TurboMacroCell(){ - m_action.remove_listener(*this); -} -void TurboMacroCell::operator=(const TurboMacroCell& x){ - x_axis.set(x.x_axis); - y_axis.set(x.y_axis); - button_hold.set(x.button_hold.current_text()); - button_release.set(x.button_release.current_text()); - wait.set(x.wait.current_text()); -} -TurboMacroCell::TurboMacroCell(EnumDropdownCell& action) - : BatchOption(LockMode::LOCK_WHILE_RUNNING, true) - , m_action(action) - , x_axis("X:", LockMode::LOCK_WHILE_RUNNING, 128) - , y_axis("Y:", LockMode::LOCK_WHILE_RUNNING, 128) - , button_hold( - "Hold (ms):", false, - LockMode::LOCK_WHILE_RUNNING, - 0ms, Milliseconds::max(), - "2000 ms" - ) - , button_release( - "Release (ms):", false, - LockMode::LOCK_WHILE_RUNNING, - 0ms, Milliseconds::max(), - "2000 ms" - ) - , wait( - "Wait (ms):", false, - LockMode::LOCK_WHILE_RUNNING, - 0ms, Milliseconds::max(), - "1000 ms" - ) -{ - PA_ADD_OPTION(x_axis); - PA_ADD_OPTION(y_axis); - PA_ADD_OPTION(button_hold); - PA_ADD_OPTION(button_release); - PA_ADD_OPTION(wait); - - TurboMacroCell::on_config_value_changed(this); - action.add_listener(*this); -} -void TurboMacroCell::on_config_value_changed(void* object){ - x_axis.set_visibility(ConfigOptionState::HIDDEN); - y_axis.set_visibility(ConfigOptionState::HIDDEN); - button_hold.set_visibility(ConfigOptionState::HIDDEN); - button_release.set_visibility(ConfigOptionState::HIDDEN); - wait.set_visibility(ConfigOptionState::HIDDEN); - switch (m_action){ - case TurboMacroAction::LEFT_JOYSTICK: - case TurboMacroAction::RIGHT_JOYSTICK: - x_axis.set_visibility(ConfigOptionState::ENABLED); - y_axis.set_visibility(ConfigOptionState::ENABLED); - case TurboMacroAction::LEFT_JOY_CLICK: - case TurboMacroAction::RIGHT_JOY_CLICK: - case TurboMacroAction::B: - case TurboMacroAction::A: - case TurboMacroAction::Y: - case TurboMacroAction::X: - case TurboMacroAction::R: - case TurboMacroAction::L: - case TurboMacroAction::ZR: - case TurboMacroAction::ZL: - case TurboMacroAction::PLUS: - case TurboMacroAction::MINUS: - case TurboMacroAction::DPADLEFT: - case TurboMacroAction::DPADRIGHT: - case TurboMacroAction::DPADUP: - case TurboMacroAction::DPADDOWN: - button_hold.set_visibility(ConfigOptionState::ENABLED); - button_release.set_visibility(ConfigOptionState::ENABLED); - break; - case TurboMacroAction::WAIT: - wait.set_visibility(ConfigOptionState::ENABLED); - break; - default: - break; - } -} - - - - -TurboMacroRow::TurboMacroRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , action(TurboMacroAction_Database(), LockMode::LOCK_WHILE_RUNNING, TurboMacroAction::NO_ACTION) - , parameters(action) -{ - PA_ADD_OPTION(action); - PA_ADD_OPTION(parameters); -} -std::unique_ptr TurboMacroRow::clone() const{ - std::unique_ptr ret(new TurboMacroRow(parent())); - ret->action.set(action); - ret->parameters = parameters; - return ret; -} - -void TurboMacroRow::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - const JsonValue* value = obj->get_value("Action"); - if (value == nullptr){ - return; - } - action.load_json(*value); - - switch (action){ - case TurboMacroAction::LEFT_JOYSTICK: - case TurboMacroAction::RIGHT_JOYSTICK: - value = obj->get_value("MoveDirectionX"); - if (value != nullptr){ - parameters.x_axis.load_json(*value); - } - value = obj->get_value("MoveDirectionY"); - if (value != nullptr){ - parameters.y_axis.load_json(*value); - } - value = obj->get_value("Hold"); - if (value != nullptr && value->is_integer()){ - parameters.button_hold.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("HoldMs"); - if (value != nullptr){ - parameters.button_hold.load_json(*value); - } - value = obj->get_value("Release"); - if (value != nullptr && value->is_integer()){ - parameters.button_release.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("ReleaseMs"); - if (value != nullptr){ - parameters.button_release.load_json(*value); - } - break; - case TurboMacroAction::LEFT_JOY_CLICK: - case TurboMacroAction::RIGHT_JOY_CLICK: - case TurboMacroAction::B: - case TurboMacroAction::A: - case TurboMacroAction::Y: - case TurboMacroAction::X: - case TurboMacroAction::R: - case TurboMacroAction::L: - case TurboMacroAction::ZR: - case TurboMacroAction::ZL: - case TurboMacroAction::PLUS: - case TurboMacroAction::MINUS: - case TurboMacroAction::DPADLEFT: - case TurboMacroAction::DPADRIGHT: - case TurboMacroAction::DPADUP: - case TurboMacroAction::DPADDOWN: - value = obj->get_value("Hold"); - if (value != nullptr && value->is_integer()){ - parameters.button_hold.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("HoldMs"); - if (value != nullptr){ - parameters.button_hold.load_json(*value); - } - value = obj->get_value("Release"); - if (value != nullptr && value->is_integer()){ - parameters.button_release.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("ReleaseMs"); - if (value != nullptr){ - parameters.button_release.load_json(*value); - } - break; - case TurboMacroAction::WAIT: - value = obj->get_value("Wait"); - if (value != nullptr && value->is_integer()){ - parameters.wait.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("WaitMs"); - if (value != nullptr){ - parameters.wait.load_json(*value); - } - break; - default: - break; - } -} -JsonValue TurboMacroRow::to_json() const{ - JsonObject obj; - obj["Action"] = action.to_json(); - switch (action){ - case TurboMacroAction::LEFT_JOY_CLICK: - case TurboMacroAction::RIGHT_JOY_CLICK: - case TurboMacroAction::B: - case TurboMacroAction::A: - case TurboMacroAction::Y: - case TurboMacroAction::X: - case TurboMacroAction::R: - case TurboMacroAction::L: - case TurboMacroAction::ZR: - case TurboMacroAction::ZL: - case TurboMacroAction::PLUS: - case TurboMacroAction::MINUS: - case TurboMacroAction::DPADLEFT: - case TurboMacroAction::DPADRIGHT: - case TurboMacroAction::DPADUP: - case TurboMacroAction::DPADDOWN: - obj["HoldMs"] = parameters.button_hold.to_json(); - obj["ReleaseMs"] = parameters.button_release.to_json(); - break; - case TurboMacroAction::LEFT_JOYSTICK: - case TurboMacroAction::RIGHT_JOYSTICK: - obj["MoveDirectionX"] = parameters.x_axis.to_json(); - obj["MoveDirectionY"] = parameters.y_axis.to_json(); - obj["HoldMs"] = parameters.button_hold.to_json(); - obj["ReleaseMs"] = parameters.button_release.to_json(); - break; - case TurboMacroAction::WAIT: - obj["WaitMs"] = parameters.wait.to_json(); - break; - default: - break; - } - return obj; -} - - -TurboMacroTable::TurboMacroTable() - : EditableTableOption_t( - "Custom Macro Table:
" - "Set a list of button press to create a macro. 125 ticks = 1 second. Joystick direction is specified by (x, y).
" - "x = 0 is left, x = 255 is right. y = 0 is up, y = 255 is down. 128 is neutral for both. Ex. Move joystick fully left would be (0, 128). Move joystick up-right would be (255, 0).", - LockMode::LOCK_WHILE_RUNNING - ) -{} -std::vector TurboMacroTable::make_header() const{ - return std::vector{ - "Action", - "Parameters", - }; -} - - - - - - - - - - -} -} +/* Turbo Macro Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonTools.h" +#include "NintendoSwitch/Options/TurboMacroTable.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +using namespace std::chrono_literals; + + + +const EnumDropdownDatabase& TurboMacroAction_Database(){ + static const EnumDropdownDatabase database({ + {TurboMacroAction::NO_ACTION, "no-action", "No Action"}, + {TurboMacroAction::LEFT_JOYSTICK, "left-joystick", "Left Joystick"}, + {TurboMacroAction::RIGHT_JOYSTICK, "right-joystick", "Right Joystick"}, + {TurboMacroAction::LEFT_JOY_CLICK, "left-joy-click", "Press Left Joystick (L3)"}, + {TurboMacroAction::RIGHT_JOY_CLICK, "right-joy-click", "Press Right Joystick (R3)"}, + {TurboMacroAction::B, "button-B", "Press B"}, + {TurboMacroAction::A, "button-A", "Press A"}, + {TurboMacroAction::Y, "button-Y", "Press Y"}, + {TurboMacroAction::X, "button-X", "Press X"}, + {TurboMacroAction::R, "button-R", "Press R"}, + {TurboMacroAction::L, "button-L", "Press L"}, + {TurboMacroAction::ZR, "button-ZR", "Press ZR"}, + {TurboMacroAction::ZL, "button-ZL", "Press ZL"}, + {TurboMacroAction::PLUS, "button-plus", "Press PLUS"}, + {TurboMacroAction::MINUS, "button-minus", "Press MINUS"}, + {TurboMacroAction::DPADLEFT, "dpad-left", "Press DPad Left"}, + {TurboMacroAction::DPADRIGHT, "dpad-right", "Press DPad Right"}, + {TurboMacroAction::DPADUP, "dpad-up", "Press DPad Up"}, + {TurboMacroAction::DPADDOWN, "dpad-down", "Press DPad Down"}, + {TurboMacroAction::WAIT, "wait", "Wait"} + }); + return database; +} + + + + + +TurboMacroCell::~TurboMacroCell(){ + m_action.remove_listener(*this); +} +void TurboMacroCell::operator=(const TurboMacroCell& x){ + x_axis.set(x.x_axis); + y_axis.set(x.y_axis); + button_hold.set(x.button_hold.current_text()); + button_release.set(x.button_release.current_text()); + wait.set(x.wait.current_text()); +} +TurboMacroCell::TurboMacroCell(EnumDropdownCell& action) + : BatchOption(LockMode::LOCK_WHILE_RUNNING, true) + , m_action(action) + , x_axis("X:", LockMode::LOCK_WHILE_RUNNING, 128) + , y_axis("Y:", LockMode::LOCK_WHILE_RUNNING, 128) + , button_hold( + "Hold (ms):", false, + LockMode::LOCK_WHILE_RUNNING, + 0ms, Milliseconds::max(), + "2000 ms" + ) + , button_release( + "Release (ms):", false, + LockMode::LOCK_WHILE_RUNNING, + 0ms, Milliseconds::max(), + "2000 ms" + ) + , wait( + "Wait (ms):", false, + LockMode::LOCK_WHILE_RUNNING, + 0ms, Milliseconds::max(), + "1000 ms" + ) +{ + PA_ADD_OPTION(x_axis); + PA_ADD_OPTION(y_axis); + PA_ADD_OPTION(button_hold); + PA_ADD_OPTION(button_release); + PA_ADD_OPTION(wait); + + TurboMacroCell::on_config_value_changed(this); + action.add_listener(*this); +} +void TurboMacroCell::on_config_value_changed(void* object){ + x_axis.set_visibility(ConfigOptionState::HIDDEN); + y_axis.set_visibility(ConfigOptionState::HIDDEN); + button_hold.set_visibility(ConfigOptionState::HIDDEN); + button_release.set_visibility(ConfigOptionState::HIDDEN); + wait.set_visibility(ConfigOptionState::HIDDEN); + switch (m_action){ + case TurboMacroAction::LEFT_JOYSTICK: + case TurboMacroAction::RIGHT_JOYSTICK: + x_axis.set_visibility(ConfigOptionState::ENABLED); + y_axis.set_visibility(ConfigOptionState::ENABLED); + case TurboMacroAction::LEFT_JOY_CLICK: + case TurboMacroAction::RIGHT_JOY_CLICK: + case TurboMacroAction::B: + case TurboMacroAction::A: + case TurboMacroAction::Y: + case TurboMacroAction::X: + case TurboMacroAction::R: + case TurboMacroAction::L: + case TurboMacroAction::ZR: + case TurboMacroAction::ZL: + case TurboMacroAction::PLUS: + case TurboMacroAction::MINUS: + case TurboMacroAction::DPADLEFT: + case TurboMacroAction::DPADRIGHT: + case TurboMacroAction::DPADUP: + case TurboMacroAction::DPADDOWN: + button_hold.set_visibility(ConfigOptionState::ENABLED); + button_release.set_visibility(ConfigOptionState::ENABLED); + break; + case TurboMacroAction::WAIT: + wait.set_visibility(ConfigOptionState::ENABLED); + break; + default: + break; + } +} + + + + +TurboMacroRow::TurboMacroRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , action(TurboMacroAction_Database(), LockMode::LOCK_WHILE_RUNNING, TurboMacroAction::NO_ACTION) + , parameters(action) +{ + PA_ADD_OPTION(action); + PA_ADD_OPTION(parameters); +} +std::unique_ptr TurboMacroRow::clone() const{ + std::unique_ptr ret(new TurboMacroRow(parent())); + ret->action.set(action); + ret->parameters = parameters; + return ret; +} + +void TurboMacroRow::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + const JsonValue* value = obj->get_value("Action"); + if (value == nullptr){ + return; + } + action.load_json(*value); + + switch (action){ + case TurboMacroAction::LEFT_JOYSTICK: + case TurboMacroAction::RIGHT_JOYSTICK: + value = obj->get_value("MoveDirectionX"); + if (value != nullptr){ + parameters.x_axis.load_json(*value); + } + value = obj->get_value("MoveDirectionY"); + if (value != nullptr){ + parameters.y_axis.load_json(*value); + } + value = obj->get_value("Hold"); + if (value != nullptr && value->is_integer()){ + parameters.button_hold.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("HoldMs"); + if (value != nullptr){ + parameters.button_hold.load_json(*value); + } + value = obj->get_value("Release"); + if (value != nullptr && value->is_integer()){ + parameters.button_release.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("ReleaseMs"); + if (value != nullptr){ + parameters.button_release.load_json(*value); + } + break; + case TurboMacroAction::LEFT_JOY_CLICK: + case TurboMacroAction::RIGHT_JOY_CLICK: + case TurboMacroAction::B: + case TurboMacroAction::A: + case TurboMacroAction::Y: + case TurboMacroAction::X: + case TurboMacroAction::R: + case TurboMacroAction::L: + case TurboMacroAction::ZR: + case TurboMacroAction::ZL: + case TurboMacroAction::PLUS: + case TurboMacroAction::MINUS: + case TurboMacroAction::DPADLEFT: + case TurboMacroAction::DPADRIGHT: + case TurboMacroAction::DPADUP: + case TurboMacroAction::DPADDOWN: + value = obj->get_value("Hold"); + if (value != nullptr && value->is_integer()){ + parameters.button_hold.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("HoldMs"); + if (value != nullptr){ + parameters.button_hold.load_json(*value); + } + value = obj->get_value("Release"); + if (value != nullptr && value->is_integer()){ + parameters.button_release.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("ReleaseMs"); + if (value != nullptr){ + parameters.button_release.load_json(*value); + } + break; + case TurboMacroAction::WAIT: + value = obj->get_value("Wait"); + if (value != nullptr && value->is_integer()){ + parameters.wait.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("WaitMs"); + if (value != nullptr){ + parameters.wait.load_json(*value); + } + break; + default: + break; + } +} +JsonValue TurboMacroRow::to_json() const{ + JsonObject obj; + obj["Action"] = action.to_json(); + switch (action){ + case TurboMacroAction::LEFT_JOY_CLICK: + case TurboMacroAction::RIGHT_JOY_CLICK: + case TurboMacroAction::B: + case TurboMacroAction::A: + case TurboMacroAction::Y: + case TurboMacroAction::X: + case TurboMacroAction::R: + case TurboMacroAction::L: + case TurboMacroAction::ZR: + case TurboMacroAction::ZL: + case TurboMacroAction::PLUS: + case TurboMacroAction::MINUS: + case TurboMacroAction::DPADLEFT: + case TurboMacroAction::DPADRIGHT: + case TurboMacroAction::DPADUP: + case TurboMacroAction::DPADDOWN: + obj["HoldMs"] = parameters.button_hold.to_json(); + obj["ReleaseMs"] = parameters.button_release.to_json(); + break; + case TurboMacroAction::LEFT_JOYSTICK: + case TurboMacroAction::RIGHT_JOYSTICK: + obj["MoveDirectionX"] = parameters.x_axis.to_json(); + obj["MoveDirectionY"] = parameters.y_axis.to_json(); + obj["HoldMs"] = parameters.button_hold.to_json(); + obj["ReleaseMs"] = parameters.button_release.to_json(); + break; + case TurboMacroAction::WAIT: + obj["WaitMs"] = parameters.wait.to_json(); + break; + default: + break; + } + return obj; +} + + +TurboMacroTable::TurboMacroTable() + : EditableTableOption_t( + "Custom Macro Table:
" + "Set a list of button press to create a macro. 125 ticks = 1 second. Joystick direction is specified by (x, y).
" + "x = 0 is left, x = 255 is right. y = 0 is up, y = 255 is down. 128 is neutral for both. Ex. Move joystick fully left would be (0, 128). Move joystick up-right would be (255, 0).", + LockMode::LOCK_WHILE_RUNNING + ) +{} +std::vector TurboMacroTable::make_header() const{ + return std::vector{ + "Action", + "Parameters", + }; +} + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.h b/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.h index 66026b77a5..836a14d2a8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/TurboMacroTable.h @@ -1,101 +1,101 @@ -/* Turbo Macro Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_TurboMacroTable_H -#define PokemonAutomation_NintendoSwitch_TurboMacroTable_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -enum class TurboMacroAction{ - NO_ACTION, - LEFT_JOYSTICK, - RIGHT_JOYSTICK, - LEFT_JOY_CLICK, - RIGHT_JOY_CLICK, - B, - A, - Y, - X, - R, - L, - ZR, - ZL, - PLUS, - MINUS, - DPADLEFT, - DPADRIGHT, - DPADUP, - DPADDOWN, - WAIT -}; -const EnumDropdownDatabase& TurboMacroAction_Database(); - - -class TurboMacroCell : public BatchOption, private ConfigOption::Listener{ -public: - ~TurboMacroCell(); - void operator=(const TurboMacroCell& x); - TurboMacroCell(EnumDropdownCell& action); - - virtual void on_config_value_changed(void* object) override; - -private: - EnumDropdownCell& m_action; - -public: - SimpleIntegerOption x_axis; - SimpleIntegerOption y_axis; - - MillisecondsOption button_hold; - MillisecondsOption button_release; - MillisecondsOption wait; -// SimpleIntegerOption button_hold_ticks; -// SimpleIntegerOption button_release_ticks; -// SimpleIntegerOption wait_ticks; -}; - - -class TurboMacroRow : public EditableTableRow{ -public: - TurboMacroRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - EnumDropdownCell action; - TurboMacroCell parameters; -}; - - -class TurboMacroTable : public EditableTableOption_t{ -public: - TurboMacroTable(); - virtual std::vector make_header() const override; - - -private: - -}; - - - - - - - -} -} -#endif +/* Turbo Macro Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_TurboMacroTable_H +#define PokemonAutomation_NintendoSwitch_TurboMacroTable_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +enum class TurboMacroAction{ + NO_ACTION, + LEFT_JOYSTICK, + RIGHT_JOYSTICK, + LEFT_JOY_CLICK, + RIGHT_JOY_CLICK, + B, + A, + Y, + X, + R, + L, + ZR, + ZL, + PLUS, + MINUS, + DPADLEFT, + DPADRIGHT, + DPADUP, + DPADDOWN, + WAIT +}; +const EnumDropdownDatabase& TurboMacroAction_Database(); + + +class TurboMacroCell : public BatchOption, private ConfigOption::Listener{ +public: + ~TurboMacroCell(); + void operator=(const TurboMacroCell& x); + TurboMacroCell(EnumDropdownCell& action); + + virtual void on_config_value_changed(void* object) override; + +private: + EnumDropdownCell& m_action; + +public: + SimpleIntegerOption x_axis; + SimpleIntegerOption y_axis; + + MillisecondsOption button_hold; + MillisecondsOption button_release; + MillisecondsOption wait; +// SimpleIntegerOption button_hold_ticks; +// SimpleIntegerOption button_release_ticks; +// SimpleIntegerOption wait_ticks; +}; + + +class TurboMacroRow : public EditableTableRow{ +public: + TurboMacroRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + EnumDropdownCell action; + TurboMacroCell parameters; +}; + + +class TurboMacroTable : public EditableTableOption_t{ +public: + TurboMacroTable(); + virtual std::vector make_header() const override; + + +private: + +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.cpp b/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.cpp index 053f46523c..bf43b9e1c8 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.cpp @@ -1,91 +1,91 @@ -/* Friend Code List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "NintendoSwitch_FriendCodeListWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -ConfigWidget* FriendCodeListOption::make_QtWidget(QWidget& parent){ - return new FriendCodeListWidget(parent, *this); -} - - - -class FriendCodeListWidget::Box : public QTextEdit{ -public: - Box(FriendCodeListWidget& parent) - : QTextEdit(&parent) - , m_parent(parent) - { - this->setAcceptRichText(false); - this->setFocusPolicy(Qt::StrongFocus); - } - - void redraw(){ - std::vector lines = m_parent.m_value.lines(); - this->clear(); - for (const std::string& line : lines){ - if (FriendCodeListOption::parse(line).size() == 12){ - this->append(QString::fromStdString(line)); - }else{ -// this->append("" + line + ""); - } - } - } - - virtual void focusOutEvent(QFocusEvent* event) override{ - QTextEdit::focusOutEvent(event); -// cout << "focusOutEvent()" << endl; - m_parent.m_value.set(this->toPlainText().toStdString()); - redraw(); - } - -private: - FriendCodeListWidget& m_parent; -}; - - - -FriendCodeListWidget::~FriendCodeListWidget(){ - m_value.remove_listener(*this); -} -FriendCodeListWidget::FriendCodeListWidget(QWidget& parent, FriendCodeListOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - QLabel* label = new QLabel(QString::fromStdString(value.m_label), this); - label->setWordWrap(true); - layout->addWidget(label); - m_box = new Box(*this); - layout->addWidget(m_box); - - m_box->redraw(); - - m_value.add_listener(*this); -} - -void FriendCodeListWidget::update_value(){ - m_box->redraw(); -} -void FriendCodeListWidget::on_config_value_changed(void* object){ - QMetaObject::invokeMethod(m_box, [this]{ - update_value(); - }, Qt::QueuedConnection); -} - - - - - -} -} +/* Friend Code List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "NintendoSwitch_FriendCodeListWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +ConfigWidget* FriendCodeListOption::make_QtWidget(QWidget& parent){ + return new FriendCodeListWidget(parent, *this); +} + + + +class FriendCodeListWidget::Box : public QTextEdit{ +public: + Box(FriendCodeListWidget& parent) + : QTextEdit(&parent) + , m_parent(parent) + { + this->setAcceptRichText(false); + this->setFocusPolicy(Qt::StrongFocus); + } + + void redraw(){ + std::vector lines = m_parent.m_value.lines(); + this->clear(); + for (const std::string& line : lines){ + if (FriendCodeListOption::parse(line).size() == 12){ + this->append(QString::fromStdString(line)); + }else{ +// this->append("" + line + ""); + } + } + } + + virtual void focusOutEvent(QFocusEvent* event) override{ + QTextEdit::focusOutEvent(event); +// cout << "focusOutEvent()" << endl; + m_parent.m_value.set(this->toPlainText().toStdString()); + redraw(); + } + +private: + FriendCodeListWidget& m_parent; +}; + + + +FriendCodeListWidget::~FriendCodeListWidget(){ + m_value.remove_listener(*this); +} +FriendCodeListWidget::FriendCodeListWidget(QWidget& parent, FriendCodeListOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + QLabel* label = new QLabel(QString::fromStdString(value.m_label), this); + label->setWordWrap(true); + layout->addWidget(label); + m_box = new Box(*this); + layout->addWidget(m_box); + + m_box->redraw(); + + m_value.add_listener(*this); +} + +void FriendCodeListWidget::update_value(){ + m_box->redraw(); +} +void FriendCodeListWidget::on_config_value_changed(void* object){ + QMetaObject::invokeMethod(m_box, [this]{ + update_value(); + }, Qt::QueuedConnection); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.h b/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.h index c2d269e1ac..592acfb537 100644 --- a/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.h +++ b/SerialPrograms/Source/NintendoSwitch/Options/UI/NintendoSwitch_FriendCodeListWidget.h @@ -1,40 +1,40 @@ -/* Friend Code List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_FriendCodeListWidget_H -#define PokemonAutomation_NintendoSwitch_FriendCodeListWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class FriendCodeListWidget : public QWidget, public ConfigWidget{ -public: - ~FriendCodeListWidget(); - FriendCodeListWidget(QWidget& parent, FriendCodeListOption& value); - - virtual void update_value() override; - virtual void on_config_value_changed(void* object) override; - -private: - class Box; - - FriendCodeListOption& m_value; - Box* m_box; -}; - - - - - -} -} -#endif +/* Friend Code List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_FriendCodeListWidget_H +#define PokemonAutomation_NintendoSwitch_FriendCodeListWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class FriendCodeListWidget : public QWidget, public ConfigWidget{ +public: + ~FriendCodeListWidget(); + FriendCodeListWidget(QWidget& parent, FriendCodeListOption& value); + + virtual void update_value() override; + virtual void on_config_value_changed(void* object) override; + +private: + class Box; + + FriendCodeListOption& m_value; + Box* m_box; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp index 63b982b824..839c8dba37 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.cpp @@ -1,271 +1,271 @@ -/* Date Manip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch_DateManip.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -//using namespace std::chrono_literals; - - - - - - - - -DateReader::DateReader(ConsoleHandle& console) - : m_console(console) - , m_switch1(COLOR_RED) - , m_switch2(COLOR_MAGENTA) - , m_background_top(0.50, 0.02, 0.45, 0.08) - , m_window_top(0.50, 0.36, 0.45, 0.07) - , m_window_text(0.05, 0.36, 0.10, 0.07) - , m_us_hour(0.473, 0.61, 0.06, 0.09) - , m_jp_year(0.136, 0.61, 0.11, 0.09) - , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) - , m_switch1_US(COLOR_YELLOW) - , m_switch1_EU(COLOR_CYAN) - , m_switch1_JP(COLOR_PURPLE) - , m_switch2_US(COLOR_YELLOW) - , m_switch2_EU(COLOR_CYAN) - , m_switch2_JP(COLOR_PURPLE) -{} -void DateReader::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_background_top); - items.add(COLOR_RED, m_window_top); - items.add(COLOR_RED, m_window_text); - items.add(COLOR_RED, m_us_hour); - items.add(COLOR_RED, m_jp_year); - items.add(COLOR_RED, m_jp_month_arrow); - m_switch1_US.make_overlays(items); - m_switch1_EU.make_overlays(items); - m_switch1_JP.make_overlays(items); - m_switch2_US.make_overlays(items); - m_switch2_EU.make_overlays(items); - m_switch2_JP.make_overlays(items); -} -bool DateReader::detect(const ImageViewRGB32& screen){ - ConsoleType type = m_console.state().console_type(); - - if (is_switch1(type)){ - return m_switch1.detect(screen); - } - - if (is_switch2(type)){ - return m_switch2.detect(screen); - } - - throw UserSetupError( - m_console, - "Please select a valid Switch console type." - ); -} - - -std::pair DateReader::read_date(Logger& logger, std::shared_ptr screen){ - if (!detect(*screen)){ - throw_and_log( - logger, ErrorReport::SEND_ERROR_REPORT, - "Not on date change screen.", - nullptr, - std::move(screen) - ); - } - - ConsoleType type = m_console.state().console_type(); - - if (is_switch1(type)){ - switch (m_switch1.detect_date_format(*screen)){ - case DateFormat::US: - return {DateFormat::US, m_switch1_US.read_date(logger, std::move(screen))}; - case DateFormat::EU: - return {DateFormat::EU, m_switch1_EU.read_date(logger, std::move(screen))}; - case DateFormat::JP: - return {DateFormat::JP, m_switch1_JP.read_date(logger, std::move(screen))}; - } - } - - if (is_switch2(type)){ - switch (m_switch2.detect_date_format(*screen)){ - case DateFormat::US: - return {DateFormat::US, m_switch2_US.read_date(logger, std::move(screen))}; - case DateFormat::EU: - return {DateFormat::EU, m_switch2_EU.read_date(logger, std::move(screen))}; - case DateFormat::JP: - return {DateFormat::JP, m_switch2_JP.read_date(logger, std::move(screen))}; - } - } - - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - "Unrecognized Console Type: " + std::to_string((int)type) - ); -} - -void DateReader::set_date( - const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, - const DateTime& date -){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - -#if 0 - { - auto snapshot = console.video().snapshot(); - if (!detect(snapshot)){ - throw_and_log( - console.logger(), ErrorReport::SEND_ERROR_REPORT, - "Expected date change menu.", - &console, - snapshot - ); - } - } -#endif - - auto snapshot = console.video().snapshot(); - - if (!detect(snapshot)){ - throw_and_log( - console, ErrorReport::SEND_ERROR_REPORT, - "Not on date change screen.", - nullptr, - snapshot - ); - } - - ConsoleType type = m_console.state().console_type(); - - if (is_switch1(type)){ - switch (m_switch1.detect_date_format(snapshot)){ - case DateFormat::US: - m_switch1_US.set_date(info, console, context, date); - return; - case DateFormat::EU: - m_switch1_EU.set_date(info, console, context, date); - return; - case DateFormat::JP: - m_switch1_JP.set_date(info, console, context, date); - return; - } - } - - if (is_switch2(type)){ - switch (m_switch2.detect_date_format(snapshot)){ - case DateFormat::US: - m_switch2_US.set_date(info, console, context, date); - return; - case DateFormat::EU: - m_switch2_EU.set_date(info, console, context, date); - return; - case DateFormat::JP: - m_switch2_JP.set_date(info, console, context, date); - return; - } - } - - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - "Unrecognized Console Type: " + std::to_string((int)type) - ); - - -} - -void change_date( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const DateTime& date -){ - Milliseconds timing_variation = context->timing_variation(); - while (true){ - context.wait_for_all_requests(); - - HomeMenuWatcher home(env.console); - DateChangeWatcher date_reader(env.console); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - { - home, - date_reader - } - ); - switch (ret){ - case 0: - home_to_date_time(env.console, context, true); - pbf_press_button(context, BUTTON_A, 80ms + timing_variation, 240ms + timing_variation); - context.wait_for_all_requests(); - continue; - case 1:{ - env.log("Detected date change."); - - // Set the date - VideoOverlaySet overlays(env.console.overlay()); - date_reader.make_overlays(overlays); - date_reader.set_date(env.program_info(), env.console, context, date); - - // Commit the date. - pbf_press_button(context, BUTTON_A, 160ms + timing_variation, 340ms + timing_variation); - - // Re-enter the game. - pbf_press_button(context, BUTTON_HOME, 160ms + timing_variation, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - return; - } - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to set date", - env.console - ); - } - } -} - - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Date Manip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch_DateManip.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +//using namespace std::chrono_literals; + + + + + + + + +DateReader::DateReader(ConsoleHandle& console) + : m_console(console) + , m_switch1(COLOR_RED) + , m_switch2(COLOR_MAGENTA) + , m_background_top(0.50, 0.02, 0.45, 0.08) + , m_window_top(0.50, 0.36, 0.45, 0.07) + , m_window_text(0.05, 0.36, 0.10, 0.07) + , m_us_hour(0.473, 0.61, 0.06, 0.09) + , m_jp_year(0.136, 0.61, 0.11, 0.09) + , m_jp_month_arrow(0.30, 0.50, 0.05, 0.06) + , m_switch1_US(COLOR_YELLOW) + , m_switch1_EU(COLOR_CYAN) + , m_switch1_JP(COLOR_PURPLE) + , m_switch2_US(COLOR_YELLOW) + , m_switch2_EU(COLOR_CYAN) + , m_switch2_JP(COLOR_PURPLE) +{} +void DateReader::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_background_top); + items.add(COLOR_RED, m_window_top); + items.add(COLOR_RED, m_window_text); + items.add(COLOR_RED, m_us_hour); + items.add(COLOR_RED, m_jp_year); + items.add(COLOR_RED, m_jp_month_arrow); + m_switch1_US.make_overlays(items); + m_switch1_EU.make_overlays(items); + m_switch1_JP.make_overlays(items); + m_switch2_US.make_overlays(items); + m_switch2_EU.make_overlays(items); + m_switch2_JP.make_overlays(items); +} +bool DateReader::detect(const ImageViewRGB32& screen){ + ConsoleType type = m_console.state().console_type(); + + if (is_switch1(type)){ + return m_switch1.detect(screen); + } + + if (is_switch2(type)){ + return m_switch2.detect(screen); + } + + throw UserSetupError( + m_console, + "Please select a valid Switch console type." + ); +} + + +std::pair DateReader::read_date(Logger& logger, std::shared_ptr screen){ + if (!detect(*screen)){ + throw_and_log( + logger, ErrorReport::SEND_ERROR_REPORT, + "Not on date change screen.", + nullptr, + std::move(screen) + ); + } + + ConsoleType type = m_console.state().console_type(); + + if (is_switch1(type)){ + switch (m_switch1.detect_date_format(*screen)){ + case DateFormat::US: + return {DateFormat::US, m_switch1_US.read_date(logger, std::move(screen))}; + case DateFormat::EU: + return {DateFormat::EU, m_switch1_EU.read_date(logger, std::move(screen))}; + case DateFormat::JP: + return {DateFormat::JP, m_switch1_JP.read_date(logger, std::move(screen))}; + } + } + + if (is_switch2(type)){ + switch (m_switch2.detect_date_format(*screen)){ + case DateFormat::US: + return {DateFormat::US, m_switch2_US.read_date(logger, std::move(screen))}; + case DateFormat::EU: + return {DateFormat::EU, m_switch2_EU.read_date(logger, std::move(screen))}; + case DateFormat::JP: + return {DateFormat::JP, m_switch2_JP.read_date(logger, std::move(screen))}; + } + } + + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + "Unrecognized Console Type: " + std::to_string((int)type) + ); +} + +void DateReader::set_date( + const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, + const DateTime& date +){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + +#if 0 + { + auto snapshot = console.video().snapshot(); + if (!detect(snapshot)){ + throw_and_log( + console.logger(), ErrorReport::SEND_ERROR_REPORT, + "Expected date change menu.", + &console, + snapshot + ); + } + } +#endif + + auto snapshot = console.video().snapshot(); + + if (!detect(snapshot)){ + throw_and_log( + console, ErrorReport::SEND_ERROR_REPORT, + "Not on date change screen.", + nullptr, + snapshot + ); + } + + ConsoleType type = m_console.state().console_type(); + + if (is_switch1(type)){ + switch (m_switch1.detect_date_format(snapshot)){ + case DateFormat::US: + m_switch1_US.set_date(info, console, context, date); + return; + case DateFormat::EU: + m_switch1_EU.set_date(info, console, context, date); + return; + case DateFormat::JP: + m_switch1_JP.set_date(info, console, context, date); + return; + } + } + + if (is_switch2(type)){ + switch (m_switch2.detect_date_format(snapshot)){ + case DateFormat::US: + m_switch2_US.set_date(info, console, context, date); + return; + case DateFormat::EU: + m_switch2_EU.set_date(info, console, context, date); + return; + case DateFormat::JP: + m_switch2_JP.set_date(info, console, context, date); + return; + } + } + + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + "Unrecognized Console Type: " + std::to_string((int)type) + ); + + +} + +void change_date( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const DateTime& date +){ + Milliseconds timing_variation = context->timing_variation(); + while (true){ + context.wait_for_all_requests(); + + HomeMenuWatcher home(env.console); + DateChangeWatcher date_reader(env.console); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + { + home, + date_reader + } + ); + switch (ret){ + case 0: + home_to_date_time(env.console, context, true); + pbf_press_button(context, BUTTON_A, 80ms + timing_variation, 240ms + timing_variation); + context.wait_for_all_requests(); + continue; + case 1:{ + env.log("Detected date change."); + + // Set the date + VideoOverlaySet overlays(env.console.overlay()); + date_reader.make_overlays(overlays); + date_reader.set_date(env.program_info(), env.console, context, date); + + // Commit the date. + pbf_press_button(context, BUTTON_A, 160ms + timing_variation, 340ms + timing_variation); + + // Re-enter the game. + pbf_press_button(context, BUTTON_HOME, 160ms + timing_variation, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + return; + } + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to set date", + env.console + ); + } + } +} + + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h index e1803c1b5c..5f9b0c5a06 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h @@ -1,85 +1,85 @@ -/* Date Manip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManip_H -#define PokemonAutomation_NintendoSwitch_DateManip_H - -#include "Common/Cpp/DateTime.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class Logger; -namespace NintendoSwitch{ - - - - -class DateReader : public StaticScreenDetector{ -public: - DateReader(ConsoleHandle& console); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Returns true if we are on the date change window. - virtual bool detect(const ImageViewRGB32& screen) override; - - - std::pair read_date(Logger& logger, std::shared_ptr screen); - void set_date( - const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ); - -private: - ConsoleHandle& m_console; - - DateChangeDetector_Switch1 m_switch1; - DateChangeDetector_Switch2 m_switch2; - - ImageFloatBox m_background_top; - ImageFloatBox m_window_top; - ImageFloatBox m_window_text; - - ImageFloatBox m_us_hour; - ImageFloatBox m_jp_year; - ImageFloatBox m_jp_month_arrow; - - DateReader_Switch1_US m_switch1_US; - DateReader_Switch1_EU m_switch1_EU; - DateReader_Switch1_JP m_switch1_JP; - - DateReader_Switch2_US m_switch2_US; - DateReader_Switch2_EU m_switch2_EU; - DateReader_Switch2_JP m_switch2_JP; -}; - -class DateChangeWatcher : public DetectorToFinder{ -public: - DateChangeWatcher(ConsoleHandle& console, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) - : DetectorToFinder("DateChangeWatcher", duration, console) - {} -}; - -// starting from Home screen, change the date to the desired date -// then go back to the home screen -void change_date( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const DateTime& date -); - - - -} -} -#endif +/* Date Manip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManip_H +#define PokemonAutomation_NintendoSwitch_DateManip_H + +#include "Common/Cpp/DateTime.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DateChangeDetector.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class Logger; +namespace NintendoSwitch{ + + + + +class DateReader : public StaticScreenDetector{ +public: + DateReader(ConsoleHandle& console); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Returns true if we are on the date change window. + virtual bool detect(const ImageViewRGB32& screen) override; + + + std::pair read_date(Logger& logger, std::shared_ptr screen); + void set_date( + const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ); + +private: + ConsoleHandle& m_console; + + DateChangeDetector_Switch1 m_switch1; + DateChangeDetector_Switch2 m_switch2; + + ImageFloatBox m_background_top; + ImageFloatBox m_window_top; + ImageFloatBox m_window_text; + + ImageFloatBox m_us_hour; + ImageFloatBox m_jp_year; + ImageFloatBox m_jp_month_arrow; + + DateReader_Switch1_US m_switch1_US; + DateReader_Switch1_EU m_switch1_EU; + DateReader_Switch1_JP m_switch1_JP; + + DateReader_Switch2_US m_switch2_US; + DateReader_Switch2_EU m_switch2_EU; + DateReader_Switch2_JP m_switch2_JP; +}; + +class DateChangeWatcher : public DetectorToFinder{ +public: + DateChangeWatcher(ConsoleHandle& console, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) + : DetectorToFinder("DateChangeWatcher", duration, console) + {} +}; + +// starting from Home screen, change the date to the desired date +// then go back to the home screen +void change_date( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const DateTime& date +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h index 8eeff57fea..36fb99f28a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipBase.h @@ -1,41 +1,41 @@ -/* Date Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManipBase_H -#define PokemonAutomation_NintendoSwitch_DateManipBase_H - -#include -#include "Common/Cpp/DateTime.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class Logger; - class ImageRGB32; - class VideoOverlaySet; - class VideoStream; -namespace NintendoSwitch{ - - -class DateReaderBase{ -public: - virtual void make_overlays(VideoOverlaySet& items) const = 0; - virtual DateTime read_date( - Logger& logger, - std::shared_ptr screen - ) = 0; - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) = 0; -}; - - - - -} -} -#endif +/* Date Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManipBase_H +#define PokemonAutomation_NintendoSwitch_DateManipBase_H + +#include +#include "Common/Cpp/DateTime.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class Logger; + class ImageRGB32; + class VideoOverlaySet; + class VideoStream; +namespace NintendoSwitch{ + + +class DateReaderBase{ +public: + virtual void make_overlays(VideoOverlaySet& items) const = 0; + virtual DateTime read_date( + Logger& logger, + std::shared_ptr screen + ) = 0; + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) = 0; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp index 7f8232ace3..6a21695ea4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.cpp @@ -1,197 +1,197 @@ -/* Date Manipulation Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/ImageFilter.h" -//#include "CommonTools/OCR/OCR_RawOCR.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_DateManipTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace DateReaderTools{ - - - -ImageRGB32 filter_image(const ImageViewRGB32& image){ - double brightness = image_stats(image).average.sum(); - bool white_theme = brightness > 600; - - ImageRGB32 filtered = to_blackwhite_rgb32_range( - image, - white_theme, - 0xff000000, white_theme ? 0xffff7fff : 0xff7f7f7f - ); - return filtered; -} -int read_box( - Logger& logger, - int min, int max, - const ImageViewRGB32& screen, const ImageFloatBox& box -){ - ImageViewRGB32 cropped = extract_box_reference(screen, box); - double brightness = image_stats(cropped).average.sum(); - bool white_theme = brightness > 600; - - int value; - if (white_theme){ - value = OCR::read_number_waterfill( - logger, cropped, - 0xff000000, 0xffff7fff, true - ); - }else{ - value = OCR::read_number_waterfill( - logger, cropped, - 0xff000000, 0xff7f7f7f, false - ); - } - - if (value < min || value > max){ - value = -1; - } - return value; -} - - - -void move_horizontal(ProControllerContext& context, int current, int desired){ - while (current < desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - current++; - } - while (current > desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - current--; - } -} - -void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired){ -// cout << "adjust_no_wrap_Switch1(): " << current << " -> " << desired << endl; - - // Invalid read. Change something and hope the next attempt fixes it. - if (current < 0){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - return; - } - - while (current < desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - current++; - } - while (current > desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - current--; - } -} -void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired){ - - // Invalid read. Change something and hope the next attempt fixes it. - if (current < 0){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - return; - } - - while (current < desired){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - current++; - } - while (current > desired){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - current--; - } -} - -void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired){ - // Invalid read. Change something and hope the next attempt fixes it. - if (current < min || current > max){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - return; - } - - int total = max - min + 1; - int half = total / 2; - - int diff = desired - current; - if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ - while (current != desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - current++; - if (current > max){ - current -= total; - } - } - }else{ - while (current != desired){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - current--; - if (current < min){ - current += total; - } - } - } -} -void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired){ - // Invalid read. Change something and hope the next attempt fixes it. - if (current < min || current > max){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - return; - } - - int total = max - min + 1; - int half = total / 2; - - int diff = desired - current; - if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ - while (current != desired){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); - current++; - if (current > max){ - current -= total; - } - } - }else{ - while (current != desired){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - current--; - if (current < min){ - current += total; - } - } - } -} - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Date Manipulation Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/ImageFilter.h" +//#include "CommonTools/OCR/OCR_RawOCR.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_DateManipTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace DateReaderTools{ + + + +ImageRGB32 filter_image(const ImageViewRGB32& image){ + double brightness = image_stats(image).average.sum(); + bool white_theme = brightness > 600; + + ImageRGB32 filtered = to_blackwhite_rgb32_range( + image, + white_theme, + 0xff000000, white_theme ? 0xffff7fff : 0xff7f7f7f + ); + return filtered; +} +int read_box( + Logger& logger, + int min, int max, + const ImageViewRGB32& screen, const ImageFloatBox& box +){ + ImageViewRGB32 cropped = extract_box_reference(screen, box); + double brightness = image_stats(cropped).average.sum(); + bool white_theme = brightness > 600; + + int value; + if (white_theme){ + value = OCR::read_number_waterfill( + logger, cropped, + 0xff000000, 0xffff7fff, true + ); + }else{ + value = OCR::read_number_waterfill( + logger, cropped, + 0xff000000, 0xff7f7f7f, false + ); + } + + if (value < min || value > max){ + value = -1; + } + return value; +} + + + +void move_horizontal(ProControllerContext& context, int current, int desired){ + while (current < desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + current++; + } + while (current > desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + current--; + } +} + +void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired){ +// cout << "adjust_no_wrap_Switch1(): " << current << " -> " << desired << endl; + + // Invalid read. Change something and hope the next attempt fixes it. + if (current < 0){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + return; + } + + while (current < desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + current++; + } + while (current > desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + current--; + } +} +void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired){ + + // Invalid read. Change something and hope the next attempt fixes it. + if (current < 0){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + return; + } + + while (current < desired){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + current++; + } + while (current > desired){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + current--; + } +} + +void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired){ + // Invalid read. Change something and hope the next attempt fixes it. + if (current < min || current > max){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + return; + } + + int total = max - min + 1; + int half = total / 2; + + int diff = desired - current; + if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ + while (current != desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + current++; + if (current > max){ + current -= total; + } + } + }else{ + while (current != desired){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + current--; + if (current < min){ + current += total; + } + } + } +} +void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired){ + // Invalid read. Change something and hope the next attempt fixes it. + if (current < min || current > max){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + return; + } + + int total = max - min + 1; + int half = total / 2; + + int diff = desired - current; + if ((diff >= 0 && diff <= half) || (diff < 0 && diff < -half)){ + while (current != desired){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 112ms, 48ms, 24ms); + current++; + if (current > max){ + current -= total; + } + } + }else{ + while (current != desired){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + current--; + if (current < min){ + current += total; + } + } + } +} + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h index 48baa578cd..63c72e09f4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManipTools.h @@ -1,39 +1,39 @@ -/* Date Manipulation Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManipTools_H -#define PokemonAutomation_NintendoSwitch_DateManipTools_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "NintendoSwitch_DateManipBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace DateReaderTools{ - - - -ImageRGB32 filter_image(const ImageViewRGB32& image); -int read_box( - Logger& logger, - int min, int max, - const ImageViewRGB32& screen, const ImageFloatBox& box -); - -void move_horizontal(ProControllerContext& context, int current, int desired); - -void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired); -void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired); - -void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired); -void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired); - - - -} -} -} -#endif +/* Date Manipulation Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManipTools_H +#define PokemonAutomation_NintendoSwitch_DateManipTools_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch_DateManipBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace DateReaderTools{ + + + +ImageRGB32 filter_image(const ImageViewRGB32& image); +int read_box( + Logger& logger, + int min, int max, + const ImageViewRGB32& screen, const ImageFloatBox& box +); + +void move_horizontal(ProControllerContext& context, int current, int desired); + +void adjust_no_wrap_Switch1(ProControllerContext& context, int current, int desired); +void adjust_no_wrap_Switch2(ProControllerContext& context, int current, int desired); + +void adjust_wrap_Switch1(ProControllerContext& context, int min, int max, int current, int desired); +void adjust_wrap_Switch2(ProControllerContext& context, int min, int max, int current, int desired); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp index ef5e670db8..4d573e4241 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.cpp @@ -1,197 +1,197 @@ -/* Date Manipulation (24h) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManip_24h.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -DateReader_24h::DateReader_24h(Color color) - : m_color(color) -{} -void DateReader_24h::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_day); - items.add(m_color, m_month); - items.add(m_color, m_year); - items.add(m_color, m_hour); - items.add(m_color, m_minute); -} -DateTime DateReader_24h::read_date(Logger& logger, std::shared_ptr screen){ - logger.log("Attempting to read EU date..."); - - DateTime date; - - date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); - date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); - date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); - date.hour = (int8_t)DateReaderTools::read_box(logger, 0, 23, *screen, m_hour); - date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); - - return date; -} - - - -DateReader_EU::DateReader_EU(Color color) - : DateReader_24h(color) -{} -void DateReader_EU::set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date -){ - stream.log("DateReader_EU::set_date()"); - - int cursor_position = 0; - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - - auto snapshot = stream.video().snapshot(); - DateTime current = read_date(stream.logger(), snapshot); - if (current.year == date.year && - current.month == date.month && - current.day == date.day && - current.hour == date.hour && - current.minute == date.minute - ){ - move_horizontal(context, cursor_position, 5); - return; - } - - move_horizontal(context, cursor_position, 0); - adjust_no_wrap(context, current.day, date.day); - - move_horizontal(context, cursor_position, 1); - adjust_wrap(context, 1, 12, current.month, date.month); - - move_horizontal(context, cursor_position, 2); - adjust_no_wrap(context, current.year, date.year); - - move_horizontal(context, cursor_position, 3); - adjust_wrap(context, 0, 23, current.hour, date.hour); - - move_horizontal(context, cursor_position, 4); - adjust_wrap(context, 0, 59, current.minute, date.minute); - - move_horizontal(context, cursor_position, 5); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set the hour after 10 attempts.", - stream - ); -} - - -DateReader_Switch1_EU::DateReader_Switch1_EU(Color color) - : DateReader_EU(color) -{ - m_day = ImageFloatBox(0.145, 0.61, 0.06, 0.09); - m_month = ImageFloatBox(0.247, 0.61, 0.06, 0.09); - m_year = ImageFloatBox(0.355, 0.61, 0.11, 0.09); - m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); - m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); -} -DateReader_Switch2_EU::DateReader_Switch2_EU(Color color) - : DateReader_EU(color) -{ - m_day = ImageFloatBox(0.139, 0.436, 0.053, 0.095); - m_month = ImageFloatBox(0.246, 0.436, 0.053, 0.095); - m_year = ImageFloatBox(0.355, 0.436, 0.088, 0.095); - m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); - m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); -} - - - -DateReader_JP::DateReader_JP(Color color) - : DateReader_24h(color) -{} -void DateReader_JP::set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date -){ - stream.log("DateReader_JP::set_date()"); - - int cursor_position = 0; - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - - auto snapshot = stream.video().snapshot(); - DateTime current = read_date(stream.logger(), snapshot); - if (current.year == date.year && - current.month == date.month && - current.day == date.day && - current.hour == date.hour && - current.minute == date.minute - ){ - move_horizontal(context, cursor_position, 5); - return; - } - - move_horizontal(context, cursor_position, 0); - adjust_no_wrap(context, current.year, date.year); - - move_horizontal(context, cursor_position, 1); - adjust_wrap(context, 1, 12, current.month, date.month); - - move_horizontal(context, cursor_position, 2); - adjust_no_wrap(context, current.day, date.day); - - move_horizontal(context, cursor_position, 3); - adjust_wrap(context, 0, 23, current.hour, date.hour); - - move_horizontal(context, cursor_position, 4); - adjust_wrap(context, 0, 59, current.minute, date.minute); - - move_horizontal(context, cursor_position, 5); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set the hour after 10 attempts.", - stream - ); -} - - -DateReader_Switch1_JP::DateReader_Switch1_JP(Color color) - : DateReader_JP(color) -{ - m_year = ImageFloatBox(0.136, 0.61, 0.11, 0.09); - m_month = ImageFloatBox(0.295, 0.61, 0.06, 0.09); - m_day = ImageFloatBox(0.395, 0.61, 0.06, 0.09); - m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); - m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); -} -DateReader_Switch2_JP::DateReader_Switch2_JP(Color color) - : DateReader_JP(color) -{ - m_year = ImageFloatBox(0.139, 0.436, 0.088, 0.095); - m_month = ImageFloatBox(0.292, 0.436, 0.053, 0.095); - m_day = ImageFloatBox(0.410, 0.436, 0.053, 0.095); - m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); - m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); -} - - - - - -} -} +/* Date Manipulation (24h) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManip_24h.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +DateReader_24h::DateReader_24h(Color color) + : m_color(color) +{} +void DateReader_24h::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_day); + items.add(m_color, m_month); + items.add(m_color, m_year); + items.add(m_color, m_hour); + items.add(m_color, m_minute); +} +DateTime DateReader_24h::read_date(Logger& logger, std::shared_ptr screen){ + logger.log("Attempting to read EU date..."); + + DateTime date; + + date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); + date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); + date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); + date.hour = (int8_t)DateReaderTools::read_box(logger, 0, 23, *screen, m_hour); + date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); + + return date; +} + + + +DateReader_EU::DateReader_EU(Color color) + : DateReader_24h(color) +{} +void DateReader_EU::set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date +){ + stream.log("DateReader_EU::set_date()"); + + int cursor_position = 0; + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + + auto snapshot = stream.video().snapshot(); + DateTime current = read_date(stream.logger(), snapshot); + if (current.year == date.year && + current.month == date.month && + current.day == date.day && + current.hour == date.hour && + current.minute == date.minute + ){ + move_horizontal(context, cursor_position, 5); + return; + } + + move_horizontal(context, cursor_position, 0); + adjust_no_wrap(context, current.day, date.day); + + move_horizontal(context, cursor_position, 1); + adjust_wrap(context, 1, 12, current.month, date.month); + + move_horizontal(context, cursor_position, 2); + adjust_no_wrap(context, current.year, date.year); + + move_horizontal(context, cursor_position, 3); + adjust_wrap(context, 0, 23, current.hour, date.hour); + + move_horizontal(context, cursor_position, 4); + adjust_wrap(context, 0, 59, current.minute, date.minute); + + move_horizontal(context, cursor_position, 5); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set the hour after 10 attempts.", + stream + ); +} + + +DateReader_Switch1_EU::DateReader_Switch1_EU(Color color) + : DateReader_EU(color) +{ + m_day = ImageFloatBox(0.145, 0.61, 0.06, 0.09); + m_month = ImageFloatBox(0.247, 0.61, 0.06, 0.09); + m_year = ImageFloatBox(0.355, 0.61, 0.11, 0.09); + m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); + m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); +} +DateReader_Switch2_EU::DateReader_Switch2_EU(Color color) + : DateReader_EU(color) +{ + m_day = ImageFloatBox(0.139, 0.436, 0.053, 0.095); + m_month = ImageFloatBox(0.246, 0.436, 0.053, 0.095); + m_year = ImageFloatBox(0.355, 0.436, 0.088, 0.095); + m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); + m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); +} + + + +DateReader_JP::DateReader_JP(Color color) + : DateReader_24h(color) +{} +void DateReader_JP::set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date +){ + stream.log("DateReader_JP::set_date()"); + + int cursor_position = 0; + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + + auto snapshot = stream.video().snapshot(); + DateTime current = read_date(stream.logger(), snapshot); + if (current.year == date.year && + current.month == date.month && + current.day == date.day && + current.hour == date.hour && + current.minute == date.minute + ){ + move_horizontal(context, cursor_position, 5); + return; + } + + move_horizontal(context, cursor_position, 0); + adjust_no_wrap(context, current.year, date.year); + + move_horizontal(context, cursor_position, 1); + adjust_wrap(context, 1, 12, current.month, date.month); + + move_horizontal(context, cursor_position, 2); + adjust_no_wrap(context, current.day, date.day); + + move_horizontal(context, cursor_position, 3); + adjust_wrap(context, 0, 23, current.hour, date.hour); + + move_horizontal(context, cursor_position, 4); + adjust_wrap(context, 0, 59, current.minute, date.minute); + + move_horizontal(context, cursor_position, 5); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set the hour after 10 attempts.", + stream + ); +} + + +DateReader_Switch1_JP::DateReader_Switch1_JP(Color color) + : DateReader_JP(color) +{ + m_year = ImageFloatBox(0.136, 0.61, 0.11, 0.09); + m_month = ImageFloatBox(0.295, 0.61, 0.06, 0.09); + m_day = ImageFloatBox(0.395, 0.61, 0.06, 0.09); + m_hour = ImageFloatBox(0.528, 0.61, 0.06, 0.09); + m_minute = ImageFloatBox(0.629, 0.61, 0.06, 0.09); +} +DateReader_Switch2_JP::DateReader_Switch2_JP(Color color) + : DateReader_JP(color) +{ + m_year = ImageFloatBox(0.139, 0.436, 0.088, 0.095); + m_month = ImageFloatBox(0.292, 0.436, 0.053, 0.095); + m_day = ImageFloatBox(0.410, 0.436, 0.053, 0.095); + m_hour = ImageFloatBox(0.532, 0.436, 0.053, 0.095); + m_minute = ImageFloatBox(0.645, 0.436, 0.053, 0.095); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h index aa8d379fdc..1cd6b815aa 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_24h.h @@ -1,131 +1,131 @@ -/* Date Manipulation (24h) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManip_24h_H -#define PokemonAutomation_NintendoSwitch_DateManip_24h_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManipBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class DateReader_24h : public DateReaderBase{ -public: - DateReader_24h(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual DateTime read_date( - Logger& logger, - std::shared_ptr screen - ) override; - -protected: - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; - - -protected: - Color m_color; - ImageFloatBox m_year; - ImageFloatBox m_month; - ImageFloatBox m_day; - ImageFloatBox m_hour; - ImageFloatBox m_minute; -}; - - - - -class DateReader_EU : public DateReader_24h{ -public: - DateReader_EU(Color color); - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) override; -}; -class DateReader_Switch1_EU : public DateReader_EU{ -public: - DateReader_Switch1_EU(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); - } -}; -class DateReader_Switch2_EU : public DateReader_EU{ -public: - DateReader_Switch2_EU(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); - } -}; - - - - -class DateReader_JP : public DateReader_24h{ -public: - DateReader_JP(Color color); - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) override; -}; -class DateReader_Switch1_JP : public DateReader_JP{ -public: - DateReader_Switch1_JP(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); - } -}; -class DateReader_Switch2_JP : public DateReader_JP{ -public: - DateReader_Switch2_JP(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); - } -}; - - - - - -} -} -#endif +/* Date Manipulation (24h) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManip_24h_H +#define PokemonAutomation_NintendoSwitch_DateManip_24h_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManipBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class DateReader_24h : public DateReaderBase{ +public: + DateReader_24h(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual DateTime read_date( + Logger& logger, + std::shared_ptr screen + ) override; + +protected: + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; + + +protected: + Color m_color; + ImageFloatBox m_year; + ImageFloatBox m_month; + ImageFloatBox m_day; + ImageFloatBox m_hour; + ImageFloatBox m_minute; +}; + + + + +class DateReader_EU : public DateReader_24h{ +public: + DateReader_EU(Color color); + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) override; +}; +class DateReader_Switch1_EU : public DateReader_EU{ +public: + DateReader_Switch1_EU(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); + } +}; +class DateReader_Switch2_EU : public DateReader_EU{ +public: + DateReader_Switch2_EU(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); + } +}; + + + + +class DateReader_JP : public DateReader_24h{ +public: + DateReader_JP(Color color); + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) override; +}; +class DateReader_Switch1_JP : public DateReader_JP{ +public: + DateReader_Switch1_JP(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); + } +}; +class DateReader_Switch2_JP : public DateReader_JP{ +public: + DateReader_Switch2_JP(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); + } +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp index 1a856e47e8..a1e0f3c9f6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.cpp @@ -1,188 +1,188 @@ -/* Date Manipulation (US) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "CommonTools/OCR/OCR_StringNormalization.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManip_US.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -DateReader_US::DateReader_US(Color color) - : m_color(color) -{} -void DateReader_US::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_month); - items.add(m_color, m_day); - items.add(m_color, m_year); - items.add(m_color, m_hour); - items.add(m_color, m_minute); - items.add(m_color, m_ampm); -} -DateTime DateReader_US::read_date(Logger& logger, std::shared_ptr screen){ - logger.log("Attempting to read US date..."); - - DateTime date; - - date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); - date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); - date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); - date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); - - // Hour - { - int hour = DateReaderTools::read_box(logger, 1, 12, *screen, m_hour); - if (hour == 12){ - hour = 0; - } - - ImageRGB32 us_ampm_filtered = DateReaderTools::filter_image( - extract_box_reference(*screen, m_ampm) - ); - - std::string ampm_ocr = OCR::ocr_read(Language::English, us_ampm_filtered); - if (ampm_ocr.back() == '\n'){ - ampm_ocr.pop_back(); - } - std::string ampm = to_utf8(OCR::normalize_utf32(ampm_ocr)); - - auto has_a = ampm.find('a') != std::string::npos; - auto has_p = ampm.find('p') != std::string::npos; - - if (has_a && !has_p){ - // Do nothing. - logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> AM"); - }else if (!has_a && has_p){ - logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> PM"); - hour += 12; - }else{ - logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> ??", COLOR_RED); - hour = -1; - } - - date.hour = (int8_t)hour; - } - - return date; -} -void DateReader_US::set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date -){ - stream.log("DateReader_US::set_date()"); - - int cursor_position = 0; - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(250)); - - auto snapshot = stream.video().snapshot(); - DateTime current = read_date(stream.logger(), snapshot); - if (current.year == date.year && - current.month == date.month && - current.day == date.day && - current.hour == date.hour && - current.minute == date.minute - ){ - move_horizontal(context, cursor_position, 6); - return; - } - - move_horizontal(context, cursor_position, 0); - adjust_wrap(context, 1, 12, current.month, date.month); - - move_horizontal(context, cursor_position, 1); - adjust_no_wrap(context, current.day, date.day); - - move_horizontal(context, cursor_position, 2); - adjust_no_wrap(context, current.year, date.year); - - move_horizontal(context, cursor_position, 3); - { - int8_t c = current.hour; - int8_t t = date.hour; - if (c >= 12) c -= 12; - if (t >= 12) t -= 12; - adjust_wrap(context, 0, 11, c, t); - } - - move_horizontal(context, cursor_position, 4); - adjust_wrap(context, 0, 59, current.minute, date.minute); - - move_horizontal(context, cursor_position, 5); - if ((date.hour < 12) != (current.hour < 12)){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - - move_horizontal(context, cursor_position, 6); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set the hour after 10 attempts.", - stream - ); -} - - - - -DateReader_Switch1_US::DateReader_Switch1_US(Color color) - : DateReader_US(color) -{ - m_month = ImageFloatBox(0.090, 0.61, 0.06, 0.09); - m_day = ImageFloatBox(0.193, 0.61, 0.06, 0.09); - m_year = ImageFloatBox(0.300, 0.61, 0.11, 0.09); - m_hour = ImageFloatBox(0.473, 0.61, 0.06, 0.09); - m_minute = ImageFloatBox(0.574, 0.61, 0.06, 0.09); - m_ampm = ImageFloatBox(0.663, 0.61, 0.07, 0.09); -} -DateReader_Switch2_US::DateReader_Switch2_US(Color color) - : DateReader_US(color) -{ - m_month = ImageFloatBox(0.080, 0.436, 0.053, 0.095); - m_day = ImageFloatBox(0.188, 0.436, 0.053, 0.095); - m_year = ImageFloatBox(0.298, 0.436, 0.088, 0.095); - m_hour = ImageFloatBox(0.463, 0.436, 0.053, 0.095); - m_minute = ImageFloatBox(0.575, 0.436, 0.053, 0.095); - m_ampm = ImageFloatBox(0.671, 0.436, 0.080, 0.095); -} - - - - - - - - - - - - - - - - - - - - - - -} -} +/* Date Manipulation (US) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "CommonTools/OCR/OCR_StringNormalization.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManip_US.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +DateReader_US::DateReader_US(Color color) + : m_color(color) +{} +void DateReader_US::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_month); + items.add(m_color, m_day); + items.add(m_color, m_year); + items.add(m_color, m_hour); + items.add(m_color, m_minute); + items.add(m_color, m_ampm); +} +DateTime DateReader_US::read_date(Logger& logger, std::shared_ptr screen){ + logger.log("Attempting to read US date..."); + + DateTime date; + + date.month = (int8_t)DateReaderTools::read_box(logger, 1, 12, *screen, m_month); + date.day = (int8_t)DateReaderTools::read_box(logger, 1, 31, *screen, m_day); + date.year = (int16_t)DateReaderTools::read_box(logger, 2000, 2060, *screen, m_year); + date.minute = (int8_t)DateReaderTools::read_box(logger, 0, 59, *screen, m_minute); + + // Hour + { + int hour = DateReaderTools::read_box(logger, 1, 12, *screen, m_hour); + if (hour == 12){ + hour = 0; + } + + ImageRGB32 us_ampm_filtered = DateReaderTools::filter_image( + extract_box_reference(*screen, m_ampm) + ); + + std::string ampm_ocr = OCR::ocr_read(Language::English, us_ampm_filtered); + if (ampm_ocr.back() == '\n'){ + ampm_ocr.pop_back(); + } + std::string ampm = to_utf8(OCR::normalize_utf32(ampm_ocr)); + + auto has_a = ampm.find('a') != std::string::npos; + auto has_p = ampm.find('p') != std::string::npos; + + if (has_a && !has_p){ + // Do nothing. + logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> AM"); + }else if (!has_a && has_p){ + logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> PM"); + hour += 12; + }else{ + logger.log("OCR Text: \"" + ampm_ocr + "\" -> \"" + ampm + "\" -> ??", COLOR_RED); + hour = -1; + } + + date.hour = (int8_t)hour; + } + + return date; +} +void DateReader_US::set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date +){ + stream.log("DateReader_US::set_date()"); + + int cursor_position = 0; + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(250)); + + auto snapshot = stream.video().snapshot(); + DateTime current = read_date(stream.logger(), snapshot); + if (current.year == date.year && + current.month == date.month && + current.day == date.day && + current.hour == date.hour && + current.minute == date.minute + ){ + move_horizontal(context, cursor_position, 6); + return; + } + + move_horizontal(context, cursor_position, 0); + adjust_wrap(context, 1, 12, current.month, date.month); + + move_horizontal(context, cursor_position, 1); + adjust_no_wrap(context, current.day, date.day); + + move_horizontal(context, cursor_position, 2); + adjust_no_wrap(context, current.year, date.year); + + move_horizontal(context, cursor_position, 3); + { + int8_t c = current.hour; + int8_t t = date.hour; + if (c >= 12) c -= 12; + if (t >= 12) t -= 12; + adjust_wrap(context, 0, 11, c, t); + } + + move_horizontal(context, cursor_position, 4); + adjust_wrap(context, 0, 59, current.minute, date.minute); + + move_horizontal(context, cursor_position, 5); + if ((date.hour < 12) != (current.hour < 12)){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + + move_horizontal(context, cursor_position, 6); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set the hour after 10 attempts.", + stream + ); +} + + + + +DateReader_Switch1_US::DateReader_Switch1_US(Color color) + : DateReader_US(color) +{ + m_month = ImageFloatBox(0.090, 0.61, 0.06, 0.09); + m_day = ImageFloatBox(0.193, 0.61, 0.06, 0.09); + m_year = ImageFloatBox(0.300, 0.61, 0.11, 0.09); + m_hour = ImageFloatBox(0.473, 0.61, 0.06, 0.09); + m_minute = ImageFloatBox(0.574, 0.61, 0.06, 0.09); + m_ampm = ImageFloatBox(0.663, 0.61, 0.07, 0.09); +} +DateReader_Switch2_US::DateReader_Switch2_US(Color color) + : DateReader_US(color) +{ + m_month = ImageFloatBox(0.080, 0.436, 0.053, 0.095); + m_day = ImageFloatBox(0.188, 0.436, 0.053, 0.095); + m_year = ImageFloatBox(0.298, 0.436, 0.088, 0.095); + m_hour = ImageFloatBox(0.463, 0.436, 0.053, 0.095); + m_minute = ImageFloatBox(0.575, 0.436, 0.053, 0.095); + m_ampm = ImageFloatBox(0.671, 0.436, 0.080, 0.095); +} + + + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h index 8dfec7e86a..51b57cf8af 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip_US.h @@ -1,87 +1,87 @@ -/* Date Manipulation (US) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateManip_US_H -#define PokemonAutomation_NintendoSwitch_DateManip_US_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "NintendoSwitch_DateManipTools.h" -#include "NintendoSwitch_DateManipBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -class DateReader_US : public DateReaderBase{ -public: - DateReader_US(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual DateTime read_date( - Logger& logger, - std::shared_ptr screen - ) override; - virtual void set_date( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const DateTime& date // Seconds is ignored. - ) override; - -protected: - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; - -protected: - Color m_color; - ImageFloatBox m_month; - ImageFloatBox m_day; - ImageFloatBox m_year; - ImageFloatBox m_hour; - ImageFloatBox m_minute; - ImageFloatBox m_ampm; -}; - - - -class DateReader_Switch1_US : public DateReader_US{ -public: - DateReader_Switch1_US(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); - } -}; -class DateReader_Switch2_US : public DateReader_US{ -public: - DateReader_Switch2_US(Color color); - virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ - DateReaderTools::move_horizontal(context, current, desired); - current = desired; - } - virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ - DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); - } - virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ - DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); - } -}; - - - - - - - -} -} -#endif +/* Date Manipulation (US) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateManip_US_H +#define PokemonAutomation_NintendoSwitch_DateManip_US_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "NintendoSwitch_DateManipTools.h" +#include "NintendoSwitch_DateManipBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +class DateReader_US : public DateReaderBase{ +public: + DateReader_US(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual DateTime read_date( + Logger& logger, + std::shared_ptr screen + ) override; + virtual void set_date( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const DateTime& date // Seconds is ignored. + ) override; + +protected: + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const = 0; + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const = 0; + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const = 0; + +protected: + Color m_color; + ImageFloatBox m_month; + ImageFloatBox m_day; + ImageFloatBox m_year; + ImageFloatBox m_hour; + ImageFloatBox m_minute; + ImageFloatBox m_ampm; +}; + + + +class DateReader_Switch1_US : public DateReader_US{ +public: + DateReader_Switch1_US(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch1(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch1(context, min, max, current, desired); + } +}; +class DateReader_Switch2_US : public DateReader_US{ +public: + DateReader_Switch2_US(Color color); + virtual void move_horizontal(ProControllerContext& context, int& current, int desired) const override{ + DateReaderTools::move_horizontal(context, current, desired); + current = desired; + } + virtual void adjust_no_wrap(ProControllerContext& context, int current, int desired) const override{ + DateReaderTools::adjust_no_wrap_Switch2(context, current, desired); + } + virtual void adjust_wrap(ProControllerContext& context, int min, int max, int current, int desired) const override{ + DateReaderTools::adjust_wrap_Switch2(context, min, max, current, desired); + } +}; + + + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp index bfdbb26667..414f62331a 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch1_HomeToDateTime.cpp @@ -1,337 +1,337 @@ -/* Nintendo Switch 2 Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -//#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -//#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -void home_to_date_time_Switch1_wired_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -){ - logger.log("home_to_date_time_Switch1_wired_blind()"); - - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 32ms); - - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 48ms, 24ms); - - // Two A presses in case we drop the 1st one. - ssf_press_button(context, BUTTON_A, 24ms, 40ms, 24ms); - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - - // Just button mash it. lol - { - auto iterations = Milliseconds(1200) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } - - // Scroll left and press A to exit the sleep menu if we happened to - // land there. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 24ms); - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - - { - auto iterations = Milliseconds(312) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); - }while (--iterations); - } - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 80ms, 40ms, 24ms); - ssf_press_dpad(context, DPAD_DOWN, 360ms, 320ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - - if (!to_date_change){ - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 360ms, 48ms, 24ms); - return; - } - - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - { - auto iterations = Milliseconds(250) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } -// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); - - // Left scroll in case we missed and landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); -} -void home_to_date_time_Switch1_wireless_esp32_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -){ - logger.log("home_to_date_time_Switch1_wireless_esp32_blind()"); - - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); - - // Press A multiple times to make sure one goes through. - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - // Just button mash it. lol - { - auto iterations = Milliseconds(1100) / unit + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - }while (--iterations); - } - - // Scroll left and press A to exit the sleep menu if we happened to - // land there. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); - ssf_press_button(context, BUTTON_A, unit, 2*unit, unit); - - { - auto iterations = Milliseconds(312) / unit + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - }while (--iterations); - } - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 400ms, 2*unit, unit); - ssf_press_dpad(context, DPAD_DOWN, 360ms, 304ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - - if (!to_date_change){ - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); - return; - } - - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, unit); - ssf_press_button(context, BUTTON_A, unit); - { - auto iterations = Milliseconds(250) / unit + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - }while (--iterations); - } - - // Left scroll in case we missed landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); - -} -void home_to_date_time_Switch1_sbb_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -){ - logger.log("home_to_date_time_Switch1_sbb_blind()"); - - Milliseconds tv = context->timing_variation(); -// ssf_do_nothing(context, 1500ms); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - - // Down twice in case we drop one. - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); -// ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - - // Press A multiple times to make sure one goes through. - ssf_mash1_button(context, BUTTON_A, 200ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 2500ms, 2500ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT, 500ms, 500ms); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 500ms, tv, tv); - ssf_press_right_joystick(context, 128, 224, 1000ms, 300ms, tv); -// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 250ms, tv); // Scroll down - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - - if (!to_date_change){ - ssf_press_button_ptv(context, BUTTON_A); - return; - } - - ssf_press_button_ptv(context, BUTTON_A, 1000ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); -} - - - - - -void home_to_date_time_Switch1_wired_feedback( - VideoStream& stream, ProControllerContext& context, bool to_date_change -){ - stream.log("home_to_date_time_Switch1_wired_with_feedback()"); - - size_t max_attempts = 5; - for (size_t i = 0; i < max_attempts; i++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 32ms); - - // if (i > 0){ // intentionally create a failure, for testing - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 40ms, 24ms); - // } - - - // ImageFloatBox system_icon(0.685, 0.69, 0.05, 0.03); - // ImageFloatBox other_setting1(0.615, 0.69, 0.05, 0.03); - // ImageFloatBox other_setting2(0.545, 0.69, 0.05, 0.03); - - // Two A presses in case we drop the 1st one. - // the program can self recover even if the second button press is registered. - ssf_press_button(context, BUTTON_A, 24ms, 40ms, 24ms); - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - - // Just button mash it. lol - { - auto iterations = Milliseconds(1200) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } - - context.wait_for_all_requests(); - // Should now be in System Settings, with System highlighted - ImageFloatBox system_setting_box(0.056, 0.74, 0.01, 0.1); - ImageFloatBox other_setting1(0.04, 0.74, 0.01, 0.1); - ImageFloatBox other_setting2(0.02, 0.74, 0.01, 0.1); - SelectedSettingWatcher system_setting_selected(system_setting_box, other_setting1, other_setting2); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - } - }, - {system_setting_selected} - ); - if (ret < 0){ // failed to detect "System" being highlighted. press home and re-try - pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); - continue; - } - - - { - auto iterations = Milliseconds(312) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); - }while (--iterations); - } - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 80ms, 40ms, 24ms); - ssf_press_dpad(context, DPAD_DOWN, 360ms, 320ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - // if (i > 1){ // intentionally create a failure, for testing - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - // } - - // only one ButtonA press since the program can self-recover if the button is dropped. - // furthermore, the program can't self-recover if a second button press is registered. - ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); - - context.wait_for_all_requests(); - context.wait_for(Milliseconds(300)); - // we expect to be within "Date and Time", with "Synchronize Clock via Internet" being highlighted - ImageFloatBox sync_clock_box(0.168, 0.185, 0.01, 0.1); - ImageFloatBox other_setting3(0.1, 0.185, 0.01, 0.1); - ImageFloatBox other_setting4(0.05, 0.185, 0.01, 0.1); - SelectedSettingWatcher sync_clock_selected(sync_clock_box, other_setting3, other_setting4); - ret = wait_until( - stream, context, - Milliseconds(2000), - {sync_clock_selected} - ); - if (ret < 0){ // failed to detect "Synchronize clock" being highlighted. press home and re-try - pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); - continue; - } - - - if (!to_date_change){ - return; - } - - { - auto iterations = Milliseconds(250) / 24ms + 1; - do{ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - }while (--iterations); - } - - // Left scroll in case we missed landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); - - return; - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "home_to_date_time(): Failed to reach Date and Time after several attempts.", - stream - ); - -} - - - -} -} +/* Nintendo Switch 2 Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +//#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +//#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +void home_to_date_time_Switch1_wired_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +){ + logger.log("home_to_date_time_Switch1_wired_blind()"); + + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 32ms); + + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 48ms, 24ms); + + // Two A presses in case we drop the 1st one. + ssf_press_button(context, BUTTON_A, 24ms, 40ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + // Just button mash it. lol + { + auto iterations = Milliseconds(1200) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + { + auto iterations = Milliseconds(312) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); + }while (--iterations); + } + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 80ms, 40ms, 24ms); + ssf_press_dpad(context, DPAD_DOWN, 360ms, 320ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + + if (!to_date_change){ + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 360ms, 48ms, 24ms); + return; + } + + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + { + auto iterations = Milliseconds(250) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } +// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); + + // Left scroll in case we missed and landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); +} +void home_to_date_time_Switch1_wireless_esp32_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +){ + logger.log("home_to_date_time_Switch1_wireless_esp32_blind()"); + + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); + + // Press A multiple times to make sure one goes through. + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + // Just button mash it. lol + { + auto iterations = Milliseconds(1100) / unit + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + }while (--iterations); + } + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); + ssf_press_button(context, BUTTON_A, unit, 2*unit, unit); + + { + auto iterations = Milliseconds(312) / unit + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + }while (--iterations); + } + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 400ms, 2*unit, unit); + ssf_press_dpad(context, DPAD_DOWN, 360ms, 304ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + + if (!to_date_change){ + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); + return; + } + + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_press_button(context, BUTTON_A, unit); + { + auto iterations = Milliseconds(250) / unit + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + }while (--iterations); + } + + // Left scroll in case we missed landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); + +} +void home_to_date_time_Switch1_sbb_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +){ + logger.log("home_to_date_time_Switch1_sbb_blind()"); + + Milliseconds tv = context->timing_variation(); +// ssf_do_nothing(context, 1500ms); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + + // Down twice in case we drop one. + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); +// ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + + // Press A multiple times to make sure one goes through. + ssf_mash1_button(context, BUTTON_A, 200ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 2500ms, 2500ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT, 500ms, 500ms); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 500ms, tv, tv); + ssf_press_right_joystick(context, 128, 224, 1000ms, 300ms, tv); +// ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 250ms, tv); // Scroll down + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + + if (!to_date_change){ + ssf_press_button_ptv(context, BUTTON_A); + return; + } + + ssf_press_button_ptv(context, BUTTON_A, 1000ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); +} + + + + + +void home_to_date_time_Switch1_wired_feedback( + VideoStream& stream, ProControllerContext& context, bool to_date_change +){ + stream.log("home_to_date_time_Switch1_wired_with_feedback()"); + + size_t max_attempts = 5; + for (size_t i = 0; i < max_attempts; i++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 32ms); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 32ms); + + // if (i > 0){ // intentionally create a failure, for testing + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 40ms, 24ms); + // } + + + // ImageFloatBox system_icon(0.685, 0.69, 0.05, 0.03); + // ImageFloatBox other_setting1(0.615, 0.69, 0.05, 0.03); + // ImageFloatBox other_setting2(0.545, 0.69, 0.05, 0.03); + + // Two A presses in case we drop the 1st one. + // the program can self recover even if the second button press is registered. + ssf_press_button(context, BUTTON_A, 24ms, 40ms, 24ms); + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + // Just button mash it. lol + { + auto iterations = Milliseconds(1200) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } + + context.wait_for_all_requests(); + // Should now be in System Settings, with System highlighted + ImageFloatBox system_setting_box(0.056, 0.74, 0.01, 0.1); + ImageFloatBox other_setting1(0.04, 0.74, 0.01, 0.1); + ImageFloatBox other_setting2(0.02, 0.74, 0.01, 0.1); + SelectedSettingWatcher system_setting_selected(system_setting_box, other_setting1, other_setting2); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + } + }, + {system_setting_selected} + ); + if (ret < 0){ // failed to detect "System" being highlighted. press home and re-try + pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); + continue; + } + + + { + auto iterations = Milliseconds(312) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); + }while (--iterations); + } + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 80ms, 40ms, 24ms); + ssf_press_dpad(context, DPAD_DOWN, 360ms, 320ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + // if (i > 1){ // intentionally create a failure, for testing + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + // } + + // only one ButtonA press since the program can self-recover if the button is dropped. + // furthermore, the program can't self-recover if a second button press is registered. + ssf_press_button(context, BUTTON_A, 24ms, 48ms, 24ms); + + context.wait_for_all_requests(); + context.wait_for(Milliseconds(300)); + // we expect to be within "Date and Time", with "Synchronize Clock via Internet" being highlighted + ImageFloatBox sync_clock_box(0.168, 0.185, 0.01, 0.1); + ImageFloatBox other_setting3(0.1, 0.185, 0.01, 0.1); + ImageFloatBox other_setting4(0.05, 0.185, 0.01, 0.1); + SelectedSettingWatcher sync_clock_selected(sync_clock_box, other_setting3, other_setting4); + ret = wait_until( + stream, context, + Milliseconds(2000), + {sync_clock_selected} + ); + if (ret < 0){ // failed to detect "Synchronize clock" being highlighted. press home and re-try + pbf_press_button(context, BUTTON_HOME, 100ms, 2000ms); + continue; + } + + + if (!to_date_change){ + return; + } + + { + auto iterations = Milliseconds(250) / 24ms + 1; + do{ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + }while (--iterations); + } + + // Left scroll in case we missed landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms); + + return; + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "home_to_date_time(): Failed to reach Date and Time after several attempts.", + stream + ); + +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp index 061af8c501..a423a9b8e9 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch2_HomeToDateTime.cpp @@ -1,190 +1,190 @@ -/* Nintendo Switch 2 Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void home_to_settings_Switch2_wired_blind( - ProControllerContext& context -){ - Milliseconds delay = 24ms; - Milliseconds hold = 48ms; - Milliseconds cool = 24ms; - - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - - // Down twice in case we drop one. - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); - - // Two A presses in case we drop the 1st one. - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - - for (size_t c = 0; c < 40; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - } - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 1000ms, cool); - - // Scroll left and press A to exit the sleep menu if we happened to - // land there. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - - for (size_t c = 0; c < 2; c++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); - } -} -void settings_to_date_time_Switch2_wired_blind( - Logger& logger, ProControllerContext& context, - ConsoleType console_type, bool to_date_change -){ - Milliseconds delay = 24ms; - Milliseconds hold = 48ms; - Milliseconds cool = 24ms; - - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 192ms, hold, cool); - - - switch (console_type){ - case ConsoleType::Switch2_FW19_International: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - case ConsoleType::Switch2_FW19_JapanLocked: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - case ConsoleType::Switch2_FW20_International: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - case ConsoleType::Switch2_FW20_JapanLocked: - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); - break; - default: - throw UserSetupError( - logger, - "You need to specify a specific Switch 2 model." - ); - } - - - if (!to_date_change){ - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, 360ms, hold, cool); - return; - } - - // Triple up this A press to make sure it gets through. - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - ssf_press_button(context, BUTTON_A, delay, hold, cool); - - for (size_t c = 0; c < 5; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); - } - - // Left scroll in case we missed and landed in the language change or sleep - // confirmation menus. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); -} -ConsoleType settings_detect_console_type( - ConsoleHandle& console, ProControllerContext& context -){ - ConsoleType console_type = console.state().console_type(); - console.log(std::string("Console Type: ") + ConsoleType_strings(console_type)); - - // We already know for sure the Switch type. - if (console_type != ConsoleType::Switch2_Unknown && - console.state().console_type_confirmed() - ){ - return console_type; - } - - console.log("Console type unknown or not confirmed. Attempting to detect..."); - - VideoOverlaySet overlays(console.overlay()); - BinarySliderDetector detector(COLOR_BLUE, {0.836431, 0.097521, 0.069703, 0.796694}); - detector.make_overlays(overlays); - - ssf_do_nothing(context, 500ms); - for (size_t c = 0; c < 5; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 200ms, 100ms, 100ms); - } - ssf_do_nothing(context, 500ms); - context.wait_for_all_requests(); - - auto snapshot = console.video().snapshot(); - size_t sliders = detector.detect(snapshot).size(); - switch (sliders){ - case 2: - console.state().set_console_type(console, ConsoleType::Switch2_FW20_International); - break; - case 3: - console.state().set_console_type(console, ConsoleType::Switch2_FW20_JapanLocked); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect if this Switch 2 model is international or Japan-locked.", - console, std::move(snapshot) - ); - } - console_type = console.state().console_type(); - console.log(std::string("Detected console type as: ") + ConsoleType_strings(console_type)); - - // Scroll back up. - for (size_t c = 0; c < 6; c++){ - ssf_issue_scroll(context, SSF_SCROLL_UP, 200ms, 100ms, 100ms); - } - ssf_do_nothing(context, 500ms); - - return console_type; -} - -void home_to_date_time_Switch2_wired_blind( - Logger& logger, ProControllerContext& context, - ConsoleType console_type, bool to_date_change -){ - logger.log("home_to_date_time_Switch2_wired_blind()"); - home_to_settings_Switch2_wired_blind(context); - settings_to_date_time_Switch2_wired_blind(logger, context, console_type, to_date_change); -} -void home_to_date_time_Switch2_wired_feedback( - ConsoleHandle& console, ProControllerContext& context, - bool to_date_change -){ - console.log("home_to_date_time_Switch2_wired_feedback()"); - home_to_settings_Switch2_wired_blind(context); - ConsoleType console_type = settings_detect_console_type(console, context); - settings_to_date_time_Switch2_wired_blind(console, context, console_type, to_date_change); -} - - - -} -} +/* Nintendo Switch 2 Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch2_BinarySliderDetector.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void home_to_settings_Switch2_wired_blind( + ProControllerContext& context +){ + Milliseconds delay = 24ms; + Milliseconds hold = 48ms; + Milliseconds cool = 24ms; + + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); + + // Down twice in case we drop one. + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); + + ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); + + // Two A presses in case we drop the 1st one. + ssf_press_button(context, BUTTON_A, delay, hold, cool); + ssf_press_button(context, BUTTON_A, delay, hold, cool); + + for (size_t c = 0; c < 40; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); + } + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 1000ms, 1000ms, cool); + + // Scroll left and press A to exit the sleep menu if we happened to + // land there. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); + ssf_press_button(context, BUTTON_A, delay, hold, cool); + + for (size_t c = 0; c < 2; c++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay, hold, cool); + } +} +void settings_to_date_time_Switch2_wired_blind( + Logger& logger, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +){ + Milliseconds delay = 24ms; + Milliseconds hold = 48ms; + Milliseconds cool = 24ms; + + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 192ms, hold, cool); + + + switch (console_type){ + case ConsoleType::Switch2_FW19_International: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + break; + case ConsoleType::Switch2_FW19_JapanLocked: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + break; + case ConsoleType::Switch2_FW20_International: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + break; + case ConsoleType::Switch2_FW20_JapanLocked: + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 128ms, hold, cool); + break; + default: + throw UserSetupError( + logger, + "You need to specify a specific Switch 2 model." + ); + } + + + if (!to_date_change){ + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, delay, hold, cool); + ssf_press_button(context, BUTTON_A, delay, hold, cool); + ssf_press_button(context, BUTTON_A, 360ms, hold, cool); + return; + } + + // Triple up this A press to make sure it gets through. + ssf_press_button(context, BUTTON_A, delay, hold, cool); + ssf_press_button(context, BUTTON_A, delay, hold, cool); + ssf_press_button(context, BUTTON_A, delay, hold, cool); + + for (size_t c = 0; c < 5; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay, hold, cool); + } + + // Left scroll in case we missed and landed in the language change or sleep + // confirmation menus. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay, hold, cool); +} +ConsoleType settings_detect_console_type( + ConsoleHandle& console, ProControllerContext& context +){ + ConsoleType console_type = console.state().console_type(); + console.log(std::string("Console Type: ") + ConsoleType_strings(console_type)); + + // We already know for sure the Switch type. + if (console_type != ConsoleType::Switch2_Unknown && + console.state().console_type_confirmed() + ){ + return console_type; + } + + console.log("Console type unknown or not confirmed. Attempting to detect..."); + + VideoOverlaySet overlays(console.overlay()); + BinarySliderDetector detector(COLOR_BLUE, {0.836431, 0.097521, 0.069703, 0.796694}); + detector.make_overlays(overlays); + + ssf_do_nothing(context, 500ms); + for (size_t c = 0; c < 5; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 200ms, 100ms, 100ms); + } + ssf_do_nothing(context, 500ms); + context.wait_for_all_requests(); + + auto snapshot = console.video().snapshot(); + size_t sliders = detector.detect(snapshot).size(); + switch (sliders){ + case 2: + console.state().set_console_type(console, ConsoleType::Switch2_FW20_International); + break; + case 3: + console.state().set_console_type(console, ConsoleType::Switch2_FW20_JapanLocked); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect if this Switch 2 model is international or Japan-locked.", + console, std::move(snapshot) + ); + } + console_type = console.state().console_type(); + console.log(std::string("Detected console type as: ") + ConsoleType_strings(console_type)); + + // Scroll back up. + for (size_t c = 0; c < 6; c++){ + ssf_issue_scroll(context, SSF_SCROLL_UP, 200ms, 100ms, 100ms); + } + ssf_do_nothing(context, 500ms); + + return console_type; +} + +void home_to_date_time_Switch2_wired_blind( + Logger& logger, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +){ + logger.log("home_to_date_time_Switch2_wired_blind()"); + home_to_settings_Switch2_wired_blind(context); + settings_to_date_time_Switch2_wired_blind(logger, context, console_type, to_date_change); +} +void home_to_date_time_Switch2_wired_feedback( + ConsoleHandle& console, ProControllerContext& context, + bool to_date_change +){ + console.log("home_to_date_time_Switch2_wired_feedback()"); + home_to_settings_Switch2_wired_blind(context); + ConsoleType console_type = settings_detect_console_type(console, context); + settings_to_date_time_Switch2_wired_blind(console, context, console_type, to_date_change); +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp index 09e08a13f7..84cb770ca4 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.cpp @@ -1,172 +1,172 @@ -/* Nintendo Switch Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -//#include "CommonFramework/Exceptions/OperationFailedException.h" -//#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -//#include "CommonTools/Async/InferenceRoutines.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -//#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -//#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" -#include "NintendoSwitch_HomeToDateTime.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -void home_to_date_time_Switch1_blind(Logger& logger, ProControllerContext& context, bool to_date_change){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - home_to_date_time_Switch1_wired_blind(logger, context, to_date_change); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - home_to_date_time_Switch1_wireless_esp32_blind(logger, context, to_date_change); - return; - default: - // Slow version for tick-imprecise controllers. - home_to_date_time_Switch1_sbb_blind(logger, context, to_date_change); - return; - } -} -bool home_to_date_time_Switch1_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - home_to_date_time_Switch1_wired_feedback(console, context, to_date_change); - return true; - default:; - return false; - } -} - - - - -// Returns true if success. False if not supported. -bool home_to_date_time_with_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ - wait_for_home(console, context); - - ConsoleTypeDetector_Home detector(console); - ConsoleType console_type = detector.detect_only(console.video().snapshot()); - switch (console_type){ - case ConsoleType::Switch1: - return home_to_date_time_Switch1_feedback(console, context, to_date_change); - case ConsoleType::Switch2_Unknown: - case ConsoleType::Switch2_FW19_International: - case ConsoleType::Switch2_FW19_JapanLocked: - case ConsoleType::Switch2_FW20_International: - case ConsoleType::Switch2_FW20_JapanLocked: - home_to_date_time_Switch2_wired_feedback(console, context, to_date_change); - return true; - default:; - } - - return false; -} -void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ - if (console.video().snapshot() && home_to_date_time_with_feedback(console, context, to_date_change)){ - return; - } - - // No feedback available. - - ConsoleType console_type = console.state().console_type(); - - switch (console_type){ - case ConsoleType::Unknown: - throw UserSetupError(console, "Switch type is not specified and feedback is not available."); - case ConsoleType::Switch1: - home_to_date_time_Switch1_blind(console, context, to_date_change); - return; - case ConsoleType::Switch2_Unknown: - case ConsoleType::Switch2_FW19_International: - case ConsoleType::Switch2_FW19_JapanLocked: - case ConsoleType::Switch2_FW20_International: - case ConsoleType::Switch2_FW20_JapanLocked: - home_to_date_time_Switch2_wired_blind(console, context, console_type, to_date_change); - return; - } -} - - - - - - - - - - - - - - - -void home_to_date_time(JoyconContext& context, bool to_date_change){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 100ms + tv; - - //From ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32 - //as Joycon will only have that controller type - - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - - // Down twice in case we drop one. - pbf_move_joystick(context, 128, 255, 2*unit, unit); - pbf_move_joystick(context, 128, 255, 2*unit, unit); - - pbf_move_joystick(context, 0, 128, 2*unit, unit); - - // Press A multiple times to make sure one goes through. - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - // Scroll to System, move right to top option (update) - pbf_move_joystick(context, 128, 255, 2500ms, unit); - pbf_move_joystick(context, 255, 128, 500ms, unit); - - // To date/time - pbf_move_joystick(context, 128, 255, 2*unit, unit); - pbf_move_joystick(context, 128, 255, 2*unit, unit); - context.wait_for_all_requests(); - pbf_move_joystick(context, 128, 255, 525ms, unit); - //pbf_move_joystick(context, 128, 255, 365ms, 305ms); - pbf_move_joystick(context, 128, 255, 2*unit, unit); - //pbf_move_joystick(context, 128, 255, 2*unit, unit); - context.wait_for_all_requests(); - - if (!to_date_change){ - ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); - return; - } - - //ssf_press_button(context, BUTTON_A, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - context.wait_for_all_requests(); - { - auto iterations = Milliseconds(216) / unit + 1; - do{ - pbf_move_joystick(context, 128, 255, 2*unit, unit); - }while (--iterations); - } - pbf_move_joystick(context, 128, 255, 2*unit, 0ms); -} - - - - -} -} +/* Nintendo Switch Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +//#include "CommonFramework/Exceptions/OperationFailedException.h" +//#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +//#include "CommonTools/Async/InferenceRoutines.h" +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch_ConsoleTypeDetector.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +//#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +//#include "NintendoSwitch/Inference/NintendoSwitch_SelectedSettingDetector.h" +#include "NintendoSwitch_HomeToDateTime.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +void home_to_date_time_Switch1_blind(Logger& logger, ProControllerContext& context, bool to_date_change){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: + home_to_date_time_Switch1_wired_blind(logger, context, to_date_change); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: + home_to_date_time_Switch1_wireless_esp32_blind(logger, context, to_date_change); + return; + default: + // Slow version for tick-imprecise controllers. + home_to_date_time_Switch1_sbb_blind(logger, context, to_date_change); + return; + } +} +bool home_to_date_time_Switch1_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: + home_to_date_time_Switch1_wired_feedback(console, context, to_date_change); + return true; + default:; + return false; + } +} + + + + +// Returns true if success. False if not supported. +bool home_to_date_time_with_feedback(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ + wait_for_home(console, context); + + ConsoleTypeDetector_Home detector(console); + ConsoleType console_type = detector.detect_only(console.video().snapshot()); + switch (console_type){ + case ConsoleType::Switch1: + return home_to_date_time_Switch1_feedback(console, context, to_date_change); + case ConsoleType::Switch2_Unknown: + case ConsoleType::Switch2_FW19_International: + case ConsoleType::Switch2_FW19_JapanLocked: + case ConsoleType::Switch2_FW20_International: + case ConsoleType::Switch2_FW20_JapanLocked: + home_to_date_time_Switch2_wired_feedback(console, context, to_date_change); + return true; + default:; + } + + return false; +} +void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change){ + if (console.video().snapshot() && home_to_date_time_with_feedback(console, context, to_date_change)){ + return; + } + + // No feedback available. + + ConsoleType console_type = console.state().console_type(); + + switch (console_type){ + case ConsoleType::Unknown: + throw UserSetupError(console, "Switch type is not specified and feedback is not available."); + case ConsoleType::Switch1: + home_to_date_time_Switch1_blind(console, context, to_date_change); + return; + case ConsoleType::Switch2_Unknown: + case ConsoleType::Switch2_FW19_International: + case ConsoleType::Switch2_FW19_JapanLocked: + case ConsoleType::Switch2_FW20_International: + case ConsoleType::Switch2_FW20_JapanLocked: + home_to_date_time_Switch2_wired_blind(console, context, console_type, to_date_change); + return; + } +} + + + + + + + + + + + + + + + +void home_to_date_time(JoyconContext& context, bool to_date_change){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 100ms + tv; + + //From ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32 + //as Joycon will only have that controller type + + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + + // Down twice in case we drop one. + pbf_move_joystick(context, 128, 255, 2*unit, unit); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + + pbf_move_joystick(context, 0, 128, 2*unit, unit); + + // Press A multiple times to make sure one goes through. + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + // Scroll to System, move right to top option (update) + pbf_move_joystick(context, 128, 255, 2500ms, unit); + pbf_move_joystick(context, 255, 128, 500ms, unit); + + // To date/time + pbf_move_joystick(context, 128, 255, 2*unit, unit); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + context.wait_for_all_requests(); + pbf_move_joystick(context, 128, 255, 525ms, unit); + //pbf_move_joystick(context, 128, 255, 365ms, 305ms); + pbf_move_joystick(context, 128, 255, 2*unit, unit); + //pbf_move_joystick(context, 128, 255, 2*unit, unit); + context.wait_for_all_requests(); + + if (!to_date_change){ + ssf_press_button(context, BUTTON_A, 360ms, 2*unit, unit); + return; + } + + //ssf_press_button(context, BUTTON_A, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + context.wait_for_all_requests(); + { + auto iterations = Milliseconds(216) / unit + 1; + do{ + pbf_move_joystick(context, 128, 255, 2*unit, unit); + }while (--iterations); + } + pbf_move_joystick(context, 128, 255, 2*unit, 0ms); +} + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h index 8d25a9b48a..3919f07882 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h @@ -1,64 +1,64 @@ -/* Nintendo Switch Home To Date-Time - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_HomeToDateTime_H -#define PokemonAutomation_NintendoSwitch_HomeToDateTime_H - -//#include "CommonFramework/ImageTools/ImageBoxes.h" -//#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -//// Navigates from Home screen to the Date and Time screen. Using visual inference. -//void home_to_date_time(VideoStream& stream, ProControllerContext& context, bool to_date_change); - -//// Navigates from Home screen to the Date and Time screen. Done blind, without inference. -//void home_to_date_time(Logger& logger, ProControllerContext& context, bool to_date_change); - - -void home_to_date_time_Switch1_wired_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -); -void home_to_date_time_Switch1_wireless_esp32_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -); -void home_to_date_time_Switch1_sbb_blind( - Logger& logger, ProControllerContext& context, bool to_date_change -); -void home_to_date_time_Switch1_wired_feedback( - VideoStream& stream, ProControllerContext& context, bool to_date_change -); - - - -void home_to_date_time_Switch2_wired_blind( - Logger& logger, ProControllerContext& context, - ConsoleType console_type, bool to_date_change -); -void home_to_date_time_Switch2_wired_feedback( - ConsoleHandle& console, ProControllerContext& context, - bool to_date_change -); - - - -void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change); - - - -//Joycon must not be sideways -void home_to_date_time(JoyconContext& context, bool to_date_change); - - - -} -} -#endif +/* Nintendo Switch Home To Date-Time + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_HomeToDateTime_H +#define PokemonAutomation_NintendoSwitch_HomeToDateTime_H + +//#include "CommonFramework/ImageTools/ImageBoxes.h" +//#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +//// Navigates from Home screen to the Date and Time screen. Using visual inference. +//void home_to_date_time(VideoStream& stream, ProControllerContext& context, bool to_date_change); + +//// Navigates from Home screen to the Date and Time screen. Done blind, without inference. +//void home_to_date_time(Logger& logger, ProControllerContext& context, bool to_date_change); + + +void home_to_date_time_Switch1_wired_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +); +void home_to_date_time_Switch1_wireless_esp32_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +); +void home_to_date_time_Switch1_sbb_blind( + Logger& logger, ProControllerContext& context, bool to_date_change +); +void home_to_date_time_Switch1_wired_feedback( + VideoStream& stream, ProControllerContext& context, bool to_date_change +); + + + +void home_to_date_time_Switch2_wired_blind( + Logger& logger, ProControllerContext& context, + ConsoleType console_type, bool to_date_change +); +void home_to_date_time_Switch2_wired_feedback( + ConsoleHandle& console, ProControllerContext& context, + bool to_date_change +); + + + +void home_to_date_time(ConsoleHandle& console, ProControllerContext& context, bool to_date_change); + + + +//Joycon must not be sideways +void home_to_date_time(JoyconContext& context, bool to_date_change); + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp index f6cdcd2e32..0f1fee0b63 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.cpp @@ -1,133 +1,133 @@ -/* Nintendo Switch Neutral Date Skip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void neutral_date_skip_switch1_wired(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 40ms, 24ms); - ssf_press_button(context, BUTTON_A, 16ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); -// ssf_press_button(context, BUTTON_A, 2); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - for (uint8_t c = 0; c < 6; c++){ - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 24ms, 48ms, 24ms); - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 48ms, 24ms); -} -void neutral_date_skip_switch1_wireless(ProControllerContext& context){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); -// ssf_press_button(context, BUTTON_A, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - for (uint8_t c = 0; c < 6; c++){ - ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); -} -void neutral_date_skip_switch1_sbb(ProControllerContext& context){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - for (uint8_t c = 0; c < 6; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - } - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); -} -void neutral_date_skip_switch2_wired(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); -} - - -void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context){ - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - neutral_date_skip_switch1_wired(context); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - neutral_date_skip_switch1_wireless(context); - return; - case ControllerPerformanceClass::SysbotBase: - neutral_date_skip_switch1_sbb(context); - return; - default: - throw InternalProgramError( - &console.logger(), PA_CURRENT_FUNCTION, - "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) - ); - } - } - - if (is_switch2(type)){ - neutral_date_skip_switch2_wired(context); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - -} -} +/* Nintendo Switch Neutral Date Skip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void neutral_date_skip_switch1_wired(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 40ms, 24ms); + ssf_press_button(context, BUTTON_A, 16ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); +// ssf_press_button(context, BUTTON_A, 2); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < 6; c++){ + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 24ms, 48ms, 24ms); + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 48ms, 24ms); +} +void neutral_date_skip_switch1_wireless(ProControllerContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); +// ssf_press_button(context, BUTTON_A, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < 6; c++){ + ssf_issue_scroll(context, SSF_SCROLL_LEFT, unit); + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); +} +void neutral_date_skip_switch1_sbb(ProControllerContext& context){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < 6; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + } + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); +} +void neutral_date_skip_switch2_wired(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} + + +void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context){ + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: + neutral_date_skip_switch1_wired(context); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: + neutral_date_skip_switch1_wireless(context); + return; + case ControllerPerformanceClass::SysbotBase: + neutral_date_skip_switch1_sbb(context); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + } + + if (is_switch2(type)){ + neutral_date_skip_switch2_wired(context); + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h index 2575f7cbb4..a8f0ba08ae 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h @@ -1,26 +1,26 @@ -/* Nintendo Switch Neutral Date Skip - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_NeutralDateSkip_H -#define PokemonAutomation_NintendoSwitch_NeutralDateSkip_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context); - - - - - -} -} -#endif +/* Nintendo Switch Neutral Date Skip + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_NeutralDateSkip_H +#define PokemonAutomation_NintendoSwitch_NeutralDateSkip_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void neutral_date_skip(ConsoleHandle& console, ProControllerContext& context); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp index 3dfe9ca0dc..30efdc4c43 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.cpp @@ -1,199 +1,199 @@ -/* Nintendo Switch Roll Date Backward N - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_RollDateBackwardN.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void roll_date_backward_N_Switch1_wired(ProControllerContext& context, uint8_t skips, bool fast){ - Milliseconds delay = 24ms; - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); - } -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); -// ssf_press_button(context, BUTTON_A, delay); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); - } -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); - ssf_press_button(context, BUTTON_A, up_delay); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - -#if 0 -// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0); -#else - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay); - ssf_press_button(context, BUTTON_A); -#endif - - ssf_press_button(context, BUTTON_A, 160ms, 80ms); -} -void roll_date_backward_N_Switch1_wireless(ProControllerContext& context, uint8_t skips){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); - - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - } - -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, unit); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - for (uint8_t c = 0; c < skips - 1; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - } -#if 0 - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, unit); -#else - ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); -#endif - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); -} -void roll_date_backward_N_Switch1_sbb(ProControllerContext& context, uint8_t skips){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - if (skips >= 60){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - } - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - - ssf_press_button_ptv(context, BUTTON_A); -// ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - if (skips >= 60){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - } - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); -} -void roll_date_backward_N_Switch2_wired(ProControllerContext& context, uint8_t skips){ - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - if (skips >= 60){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - } - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - if (skips >= 60){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); - }else{ - for (uint8_t c = 0; c < skips; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - } - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); -} -void roll_date_backward_N( - ConsoleHandle& console, ProControllerContext& context, - uint8_t skips, bool fast -){ - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - roll_date_backward_N_Switch1_wired(context, skips, fast); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - roll_date_backward_N_Switch1_wireless(context, skips); - return; - case ControllerPerformanceClass::SysbotBase: - roll_date_backward_N_Switch1_sbb(context, skips); - return; - default: - throw InternalProgramError( - &console.logger(), PA_CURRENT_FUNCTION, - "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) - ); - } - } - - if (is_switch2(type)){ - roll_date_backward_N_Switch2_wired(context, skips); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - - - - - - - - -} -} - - - - - - - - - - +/* Nintendo Switch Roll Date Backward N + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_RollDateBackwardN.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void roll_date_backward_N_Switch1_wired(ProControllerContext& context, uint8_t skips, bool fast){ + Milliseconds delay = 24ms; + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + } +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); +// ssf_press_button(context, BUTTON_A, delay); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + } +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0); + ssf_press_button(context, BUTTON_A, up_delay); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + +#if 0 +// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0); +#else + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_LEFT, delay); + ssf_press_button(context, BUTTON_A); +#endif + + ssf_press_button(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_backward_N_Switch1_wireless(ProControllerContext& context, uint8_t skips){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); + + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + } + +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, unit); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + for (uint8_t c = 0; c < skips - 1; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + } +#if 0 + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, unit); +#else + ssf_issue_scroll(context, SSF_SCROLL_DOWN, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); +#endif + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); +} +void roll_date_backward_N_Switch1_sbb(ProControllerContext& context, uint8_t skips){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + if (skips >= 60){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + } + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + + ssf_press_button_ptv(context, BUTTON_A); +// ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + if (skips >= 60){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 6000ms, 6000ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + } + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_backward_N_Switch2_wired(ProControllerContext& context, uint8_t skips){ + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + if (skips >= 60){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + } + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + if (skips >= 60){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 4160ms, 4160ms, 24ms); + }else{ + for (uint8_t c = 0; c < skips; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + } + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void roll_date_backward_N( + ConsoleHandle& console, ProControllerContext& context, + uint8_t skips, bool fast +){ + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: + roll_date_backward_N_Switch1_wired(context, skips, fast); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: + roll_date_backward_N_Switch1_wireless(context, skips); + return; + case ControllerPerformanceClass::SysbotBase: + roll_date_backward_N_Switch1_sbb(context, skips); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + } + + if (is_switch2(type)){ + roll_date_backward_N_Switch2_wired(context, skips); + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + + + + + + + + +} +} + + + + + + + + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h index bfd6f43d03..00f55057c2 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h @@ -1,29 +1,29 @@ -/* Nintendo Switch Roll Date Backward N - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_RollDateBackwardN_H -#define PokemonAutomation_NintendoSwitch_RollDateBackwardN_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void roll_date_backward_N( - ConsoleHandle& console, ProControllerContext& context, - uint8_t skips, bool fast -); - - - - - -} -} -#endif +/* Nintendo Switch Roll Date Backward N + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_RollDateBackwardN_H +#define PokemonAutomation_NintendoSwitch_RollDateBackwardN_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void roll_date_backward_N( + ConsoleHandle& console, ProControllerContext& context, + uint8_t skips, bool fast +); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp index 6ba18258c6..5b161874bc 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.cpp @@ -1,131 +1,131 @@ -/* Nintendo Switch Roll Date Forward 1 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_RollDateForward1.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void roll_date_forward_1_Switch1_wired(ProControllerContext& context, bool fast){ - Milliseconds delay = 24ms; - - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 2*delay, delay); - ssf_press_button(context, BUTTON_A, delay); -// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_issue_scroll(context, SSF_SCROLL_UP, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_press_button(context, BUTTON_A, 0ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*delay, delay); - ssf_press_button(context, BUTTON_A, 160ms, 80ms); -} -void roll_date_forward_1_Switch1_wireless(ProControllerContext& context){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); - ssf_issue_scroll(context, SSF_SCROLL_UP, unit); - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); - - ssf_press_button(context, BUTTON_A, unit); -// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_UP, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_press_button(context, BUTTON_A, 0ms, 2*unit, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); - ssf_press_button(context, BUTTON_A, 160ms, 3*unit); -} -void roll_date_forward_1_Switch1_sbb(ProControllerContext& context){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); -} -void roll_date_forward_1_Switch2_wired(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); -} -void roll_date_forward_1( - ConsoleHandle& console, ProControllerContext& context, - bool fast -){ - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - switch (context->performance_class()){ - case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: - roll_date_forward_1_Switch1_wired(context, fast); - return; - case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: - roll_date_forward_1_Switch1_wireless(context); - return; - case ControllerPerformanceClass::SysbotBase: - roll_date_forward_1_Switch1_sbb(context); - return; - default: - throw InternalProgramError( - &console.logger(), PA_CURRENT_FUNCTION, - "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) - ); - } - } - - if (is_switch2(type)){ - roll_date_forward_1_Switch2_wired(context); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - - - - - - - -} -} +/* Nintendo Switch Roll Date Forward 1 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_RollDateForward1.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void roll_date_forward_1_Switch1_wired(ProControllerContext& context, bool fast){ + Milliseconds delay = 24ms; + + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 0ms, 2*delay, delay); + ssf_press_button(context, BUTTON_A, delay); +// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_UP, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_press_button(context, BUTTON_A, 0ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, delay); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*delay, delay); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_forward_1_Switch1_wireless(ProControllerContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll(context, SSF_SCROLL_LEFT, 0ms, 2*unit, unit); + + ssf_press_button(context, BUTTON_A, unit); +// ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_UP, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_press_button(context, BUTTON_A, 0ms, 2*unit, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, unit); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 0ms, 2*unit, unit); + ssf_press_button(context, BUTTON_A, 160ms, 3*unit); +} +void roll_date_forward_1_Switch1_sbb(ProControllerContext& context){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); +} +void roll_date_forward_1_Switch2_wired(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); +} +void roll_date_forward_1( + ConsoleHandle& console, ProControllerContext& context, + bool fast +){ + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + switch (context->performance_class()){ + case ControllerPerformanceClass::SerialPABotBase_Wired_125Hz: + roll_date_forward_1_Switch1_wired(context, fast); + return; + case ControllerPerformanceClass::SerialPABotBase_Wireless_ESP32: + roll_date_forward_1_Switch1_wireless(context); + return; + case ControllerPerformanceClass::SysbotBase: + roll_date_forward_1_Switch1_sbb(context); + return; + default: + throw InternalProgramError( + &console.logger(), PA_CURRENT_FUNCTION, + "Unsupported ControllerPerformanceClass: " + std::to_string((int)context->performance_class()) + ); + } + } + + if (is_switch2(type)){ + roll_date_forward_1_Switch2_wired(context); + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h index 7032e08c22..0fefab9761 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h @@ -1,29 +1,29 @@ -/* Nintendo Switch Roll Date Forward 1 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_RollDateForward1_H -#define PokemonAutomation_NintendoSwitch_RollDateForward1_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -void roll_date_forward_1( - ConsoleHandle& console, ProControllerContext& context, - bool fast -); - - - - - -} -} -#endif +/* Nintendo Switch Roll Date Forward 1 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_RollDateForward1_H +#define PokemonAutomation_NintendoSwitch_RollDateForward1_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +void roll_date_forward_1( + ConsoleHandle& console, ProControllerContext& context, + bool fast +); + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp index 9e4fdb4b02..ba5d89c540 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.cpp @@ -1,138 +1,138 @@ -/* Code Entry Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_CodeEntryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - - -void codeboard_populate_delays( - bool switch2, - std::vector& path_with_delays, - const std::vector& path, - const CodeEntryDelays& delays, - bool optimize -){ - // Populate and assign default delays first. - path_with_delays.resize(path.size()); - for (size_t c = 0; c < path_with_delays.size(); c++){ - CodeEntryAction action = path[c]; - Milliseconds delay; - if (action == CodeEntryAction::ENTER_CHAR){ - delay = delays.press_delay; - }else if (action == CodeEntryAction::SCROLL_LEFT){ - delay = delays.scroll_delay; - }else{ - delay = delays.move_delay; - } - - // If we are wrapping and the previous action is a move, then we can't - // overlap. - if (is_wrap(action) && c != 0){ - CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; - if (is_move(previous.action)){ - previous.delay = delays.hold; - } - } - - path_with_delays[c].action = action; - path_with_delays[c].delay = delay; - } - - - // Pad out the stalls. - Milliseconds A_to_A_delay = std::max(delays.press_delay, delays.hold + delays.cool); - Milliseconds last_A_time = -1000ms; - Milliseconds current_time = 0ms; - for (size_t c = 1; c < path_with_delays.size(); c++){ - CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; - CodeEntryActionWithDelay& current = path_with_delays[c]; - - // The Switch doesn't like overlapping the scroll with the A press. - // So we treat the left-scroll like an A press for timing purposes. - - if (current.action == CodeEntryAction::ENTER_CHAR || - (switch2 && current.action == CodeEntryAction::SCROLL_LEFT) - ){ - Milliseconds time_since_last_A = current_time - last_A_time; - if (time_since_last_A < A_to_A_delay){ - Milliseconds stall = A_to_A_delay - time_since_last_A; - previous.delay += stall; - current_time += stall; - } - last_A_time = current_time; - } - - current_time += current.delay; - } - - - // Optimize - - if (!optimize || path_with_delays.empty() || switch2){ - return; - } - - // These only work on the Switch 1. - for (size_t c = 1; c < path_with_delays.size(); c++){ - // Zero the delay for any L press. - CodeEntryActionWithDelay& current = path_with_delays[c]; - if (current.action == CodeEntryAction::SCROLL_LEFT){ - current.delay = 0ms; - continue; - } - - // Zero the delay for any scroll immediately preceding an A press. - CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; - if (current.action == CodeEntryAction::ENTER_CHAR && - previous.action != CodeEntryAction::ENTER_CHAR && - previous.action != CodeEntryAction::SCROLL_LEFT - ){ - previous.delay = 0ms; - } - } -} - - - - -void codeboard_execute_path( - ProControllerContext& context, - const CodeEntryDelays& delays, - const std::vector& path -){ - for (const CodeEntryActionWithDelay& action : path){ - switch (action.action){ - case CodeEntryAction::ENTER_CHAR: - ssf_press_button(context, BUTTON_A, action.delay, delays.hold, delays.cool); - break; - case CodeEntryAction::SCROLL_LEFT: - ssf_press_button(context, BUTTON_L, action.delay, delays.hold, delays.cool); - break; - default: - ssf_issue_scroll( - context, - (DpadPosition)((uint8_t)action.action & 0x7f), - action.delay, delays.hold, delays.cool - ); - break; - } - } -} - - - - - - -} -} -} +/* Code Entry Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_CodeEntryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + + +void codeboard_populate_delays( + bool switch2, + std::vector& path_with_delays, + const std::vector& path, + const CodeEntryDelays& delays, + bool optimize +){ + // Populate and assign default delays first. + path_with_delays.resize(path.size()); + for (size_t c = 0; c < path_with_delays.size(); c++){ + CodeEntryAction action = path[c]; + Milliseconds delay; + if (action == CodeEntryAction::ENTER_CHAR){ + delay = delays.press_delay; + }else if (action == CodeEntryAction::SCROLL_LEFT){ + delay = delays.scroll_delay; + }else{ + delay = delays.move_delay; + } + + // If we are wrapping and the previous action is a move, then we can't + // overlap. + if (is_wrap(action) && c != 0){ + CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; + if (is_move(previous.action)){ + previous.delay = delays.hold; + } + } + + path_with_delays[c].action = action; + path_with_delays[c].delay = delay; + } + + + // Pad out the stalls. + Milliseconds A_to_A_delay = std::max(delays.press_delay, delays.hold + delays.cool); + Milliseconds last_A_time = -1000ms; + Milliseconds current_time = 0ms; + for (size_t c = 1; c < path_with_delays.size(); c++){ + CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; + CodeEntryActionWithDelay& current = path_with_delays[c]; + + // The Switch doesn't like overlapping the scroll with the A press. + // So we treat the left-scroll like an A press for timing purposes. + + if (current.action == CodeEntryAction::ENTER_CHAR || + (switch2 && current.action == CodeEntryAction::SCROLL_LEFT) + ){ + Milliseconds time_since_last_A = current_time - last_A_time; + if (time_since_last_A < A_to_A_delay){ + Milliseconds stall = A_to_A_delay - time_since_last_A; + previous.delay += stall; + current_time += stall; + } + last_A_time = current_time; + } + + current_time += current.delay; + } + + + // Optimize + + if (!optimize || path_with_delays.empty() || switch2){ + return; + } + + // These only work on the Switch 1. + for (size_t c = 1; c < path_with_delays.size(); c++){ + // Zero the delay for any L press. + CodeEntryActionWithDelay& current = path_with_delays[c]; + if (current.action == CodeEntryAction::SCROLL_LEFT){ + current.delay = 0ms; + continue; + } + + // Zero the delay for any scroll immediately preceding an A press. + CodeEntryActionWithDelay& previous = path_with_delays[c - 1]; + if (current.action == CodeEntryAction::ENTER_CHAR && + previous.action != CodeEntryAction::ENTER_CHAR && + previous.action != CodeEntryAction::SCROLL_LEFT + ){ + previous.delay = 0ms; + } + } +} + + + + +void codeboard_execute_path( + ProControllerContext& context, + const CodeEntryDelays& delays, + const std::vector& path +){ + for (const CodeEntryActionWithDelay& action : path){ + switch (action.action){ + case CodeEntryAction::ENTER_CHAR: + ssf_press_button(context, BUTTON_A, action.delay, delays.hold, delays.cool); + break; + case CodeEntryAction::SCROLL_LEFT: + ssf_press_button(context, BUTTON_L, action.delay, delays.hold, delays.cool); + break; + default: + ssf_issue_scroll( + context, + (DpadPosition)((uint8_t)action.action & 0x7f), + action.delay, delays.hold, delays.cool + ); + break; + } + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h index 6478a30976..5e1518276e 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_CodeEntryTools.h @@ -1,134 +1,134 @@ -/* Code Entry Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_CodeEntryTools_H -#define PokemonAutomation_NintendoSwitch_CodeEntryTools_H - -#include -#include -#include "Common/Cpp/Time.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - - -enum class CodeEntryAction : uint8_t{ - ENTER_CHAR = 0xf0, - SCROLL_LEFT = 0xf1, - NORM_MOVE_UP = (uint8_t)DpadPosition::DPAD_UP, - NORM_MOVE_RIGHT = (uint8_t)DpadPosition::DPAD_RIGHT, - NORM_MOVE_DOWN = (uint8_t)DpadPosition::DPAD_DOWN, - NORM_MOVE_LEFT = (uint8_t)DpadPosition::DPAD_LEFT, - WRAP_MOVE_UP = 0x80 | (uint8_t)DpadPosition::DPAD_UP, - WRAP_MOVE_RIGHT = 0x80 | (uint8_t)DpadPosition::DPAD_RIGHT, - WRAP_MOVE_DOWN = 0x80 | (uint8_t)DpadPosition::DPAD_DOWN, - WRAP_MOVE_LEFT = 0x80 | (uint8_t)DpadPosition::DPAD_LEFT, -}; -inline bool is_button_press(CodeEntryAction action){ - switch (action){ - case CodeEntryAction::ENTER_CHAR: - case CodeEntryAction::SCROLL_LEFT: - return true; - default: - return false; - } -} -inline bool is_move(CodeEntryAction action){ - switch (action){ - case CodeEntryAction::NORM_MOVE_UP: - case CodeEntryAction::NORM_MOVE_RIGHT: - case CodeEntryAction::NORM_MOVE_DOWN: - case CodeEntryAction::NORM_MOVE_LEFT: - case CodeEntryAction::WRAP_MOVE_UP: - case CodeEntryAction::WRAP_MOVE_RIGHT: - case CodeEntryAction::WRAP_MOVE_DOWN: - case CodeEntryAction::WRAP_MOVE_LEFT: - return true; - default: - return false; - } -} -inline bool is_wrap(CodeEntryAction action){ - switch (action){ - case CodeEntryAction::WRAP_MOVE_UP: - case CodeEntryAction::WRAP_MOVE_RIGHT: - case CodeEntryAction::WRAP_MOVE_DOWN: - case CodeEntryAction::WRAP_MOVE_LEFT: - return true; - default: - return false; - } -} - - -struct CodeEntryDelays{ - Milliseconds hold; - Milliseconds cool; - Milliseconds press_delay; - Milliseconds move_delay; - Milliseconds scroll_delay; - Milliseconds wrap_delay; -}; - - -struct CodeEntryActionWithDelay{ - CodeEntryAction action; - Milliseconds delay; -}; - - - - -// Given a path, optimize it and fully populate the delays. -void codeboard_populate_delays( - bool switch2, - std::vector& path_with_delays, - const std::vector& path, - const CodeEntryDelays& delays, - bool optimize -); - - - - - -//inline Milliseconds calculate_path_delay(const std::vector& path){ - -//} - - - -// Actually execute a path and enter it into the Switch. -void codeboard_execute_path( - ProControllerContext& context, - const CodeEntryDelays& delays, - const std::vector& path -); - - - - - - - - - - - - - - - - -} -} -} -#endif +/* Code Entry Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_CodeEntryTools_H +#define PokemonAutomation_NintendoSwitch_CodeEntryTools_H + +#include +#include +#include "Common/Cpp/Time.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ControllerState.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + + +enum class CodeEntryAction : uint8_t{ + ENTER_CHAR = 0xf0, + SCROLL_LEFT = 0xf1, + NORM_MOVE_UP = (uint8_t)DpadPosition::DPAD_UP, + NORM_MOVE_RIGHT = (uint8_t)DpadPosition::DPAD_RIGHT, + NORM_MOVE_DOWN = (uint8_t)DpadPosition::DPAD_DOWN, + NORM_MOVE_LEFT = (uint8_t)DpadPosition::DPAD_LEFT, + WRAP_MOVE_UP = 0x80 | (uint8_t)DpadPosition::DPAD_UP, + WRAP_MOVE_RIGHT = 0x80 | (uint8_t)DpadPosition::DPAD_RIGHT, + WRAP_MOVE_DOWN = 0x80 | (uint8_t)DpadPosition::DPAD_DOWN, + WRAP_MOVE_LEFT = 0x80 | (uint8_t)DpadPosition::DPAD_LEFT, +}; +inline bool is_button_press(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::ENTER_CHAR: + case CodeEntryAction::SCROLL_LEFT: + return true; + default: + return false; + } +} +inline bool is_move(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::NORM_MOVE_UP: + case CodeEntryAction::NORM_MOVE_RIGHT: + case CodeEntryAction::NORM_MOVE_DOWN: + case CodeEntryAction::NORM_MOVE_LEFT: + case CodeEntryAction::WRAP_MOVE_UP: + case CodeEntryAction::WRAP_MOVE_RIGHT: + case CodeEntryAction::WRAP_MOVE_DOWN: + case CodeEntryAction::WRAP_MOVE_LEFT: + return true; + default: + return false; + } +} +inline bool is_wrap(CodeEntryAction action){ + switch (action){ + case CodeEntryAction::WRAP_MOVE_UP: + case CodeEntryAction::WRAP_MOVE_RIGHT: + case CodeEntryAction::WRAP_MOVE_DOWN: + case CodeEntryAction::WRAP_MOVE_LEFT: + return true; + default: + return false; + } +} + + +struct CodeEntryDelays{ + Milliseconds hold; + Milliseconds cool; + Milliseconds press_delay; + Milliseconds move_delay; + Milliseconds scroll_delay; + Milliseconds wrap_delay; +}; + + +struct CodeEntryActionWithDelay{ + CodeEntryAction action; + Milliseconds delay; +}; + + + + +// Given a path, optimize it and fully populate the delays. +void codeboard_populate_delays( + bool switch2, + std::vector& path_with_delays, + const std::vector& path, + const CodeEntryDelays& delays, + bool optimize +); + + + + + +//inline Milliseconds calculate_path_delay(const std::vector& path){ + +//} + + + +// Actually execute a path and enter it into the Switch. +void codeboard_execute_path( + ProControllerContext& context, + const CodeEntryDelays& delays, + const std::vector& path +); + + + + + + + + + + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp index ef8bd79a15..c2141b06e0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.cpp @@ -1,369 +1,369 @@ -/* Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch_CodeEntryTools.h" -#include "NintendoSwitch_KeyboardCodeEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - -struct KeyboardEntryPosition{ - uint8_t row; - uint8_t col; -}; - -static const std::map& KEYBOARD_POSITIONS_QWERTY(){ - static const std::map map{ - {'1', {0, 0}}, - {'2', {0, 1}}, - {'3', {0, 2}}, - {'4', {0, 3}}, - {'5', {0, 4}}, - {'6', {0, 5}}, - {'7', {0, 6}}, - {'8', {0, 7}}, - {'9', {0, 8}}, - {'0', {0, 9}}, - - {'Q', {1, 0}}, - {'W', {1, 1}}, - {'E', {1, 2}}, - {'R', {1, 3}}, - {'T', {1, 4}}, - {'Y', {1, 5}}, - {'U', {1, 6}}, - {'P', {1, 9}}, - - {'A', {2, 0}}, - {'S', {2, 1}}, - {'D', {2, 2}}, - {'F', {2, 3}}, - {'G', {2, 4}}, - {'H', {2, 5}}, - {'J', {2, 6}}, - {'K', {2, 7}}, - {'L', {2, 8}}, - - {'X', {3, 1}}, - {'C', {3, 2}}, - {'V', {3, 3}}, - {'B', {3, 4}}, - {'N', {3, 5}}, - {'M', {3, 6}}, - }; - return map; -} -static const std::map& KEYBOARD_POSITIONS_AZERTY(){ - static const std::map map{ - {'1', {0, 0}}, - {'2', {0, 1}}, - {'3', {0, 2}}, - {'4', {0, 3}}, - {'5', {0, 4}}, - {'6', {0, 5}}, - {'7', {0, 6}}, - {'8', {0, 7}}, - {'9', {0, 8}}, - {'0', {0, 9}}, - - {'A', {1, 0}}, - {'E', {1, 2}}, - {'R', {1, 3}}, - {'T', {1, 4}}, - {'Y', {1, 5}}, - {'U', {1, 6}}, - {'P', {1, 9}}, - - {'Q', {2, 0}}, - {'S', {2, 1}}, - {'D', {2, 2}}, - {'F', {2, 3}}, - {'G', {2, 4}}, - {'H', {2, 5}}, - {'J', {2, 6}}, - {'K', {2, 7}}, - {'L', {2, 8}}, - {'M', {2, 9}}, - - {'W', {3, 0}}, - {'X', {3, 1}}, - {'C', {3, 2}}, - {'V', {3, 3}}, - {'B', {3, 4}}, - {'N', {3, 5}}, - }; - return map; -} - - - - - - -// Return the path from "source" to "destination". -std::vector keyboard_get_path( - KeyboardEntryPosition source, - KeyboardEntryPosition destination -){ - std::vector path; - - // Vertical is easy since there's no wrapping and no hazards. - if (source.row < destination.row){ - size_t diff = destination.row - source.row; - for (size_t c = 0; c < diff; c++){ - path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); - } - }else{ - size_t diff = source.row - destination.row; - for (size_t c = 0; c < diff; c++){ - path.emplace_back(CodeEntryAction::NORM_MOVE_UP); - } - } - - // Horizontal is messy because we need extra delay on wrapping. - uint8_t col = source.col; - while (true){ - if (col == destination.col){ - break; - } - - CodeEntryAction action; - if (destination.col > col){ - if (destination.col - col <= 6){ - action = CodeEntryAction::NORM_MOVE_RIGHT; - col++; - }else{ - action = CodeEntryAction::NORM_MOVE_LEFT; - col--; - } - }else{ - if (col - destination.col <= 6){ - action = CodeEntryAction::NORM_MOVE_LEFT; - col--; - }else{ - action = CodeEntryAction::NORM_MOVE_RIGHT; - col++; - } - } - - // Wrap around the sides. - if (col == (uint8_t)-1){ - col = 11; - action = (CodeEntryAction)((uint8_t)action | 0x80); - } - if (col == 12){ - col = 0; - action = (CodeEntryAction)((uint8_t)action | 0x80); - } - - path.emplace_back(action); - } - - path.emplace_back(CodeEntryAction::ENTER_CHAR); - - return path; -} - - -// Get all possible paths from "start" to cover everything [positions, positions + length). -std::vector> keyboard_get_all_paths( - KeyboardEntryPosition start, - const KeyboardEntryPosition* positions, size_t length, - bool reordering -){ - if (length == 1){ - return {keyboard_get_path(start, positions[0])}; - } - - std::vector> paths; - { - KeyboardEntryPosition position = positions[0]; - std::vector current = keyboard_get_path(start, position); - std::vector> subpaths = keyboard_get_all_paths( - position, - positions + 1, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - if (reordering){ - KeyboardEntryPosition position = positions[length - 1]; - std::vector current = keyboard_get_path(start, position); - current.emplace_back(CodeEntryAction::SCROLL_LEFT); - std::vector> subpaths = keyboard_get_all_paths( - position, - positions, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - - return paths; -} - - - - -// Given a set of paths, find the best one and return it with fully populated -// delays. -std::vector keyboard_get_best_path( - bool switch2, - const std::vector>& paths, - const CodeEntryDelays& delays, - bool optimize -){ - std::vector best_path; - Milliseconds best_time = Milliseconds::max(); - for (const std::vector& path : paths){ - std::vector current_path; - codeboard_populate_delays(switch2, current_path, path, delays, optimize); - Milliseconds current_time = 0ms; - for (CodeEntryActionWithDelay& action : current_path){ - current_time += action.delay; - } - if (best_time > current_time){ - best_time = current_time; - best_path = std::move(current_path); - } - } - return best_path; -} - - - - -void keyboard_enter_code( - ConsoleHandle& console, ProControllerContext& context, - KeyboardLayout keyboard_layout, const std::string& code, - bool include_plus -){ - // Calculate the coordinates. - auto get_keyboard_layout = [](KeyboardLayout keyboard_layout){ - switch (keyboard_layout){ - case KeyboardLayout::QWERTY: - return KEYBOARD_POSITIONS_QWERTY(); - case KeyboardLayout::AZERTY: - return KEYBOARD_POSITIONS_AZERTY(); - default: - return KEYBOARD_POSITIONS_QWERTY(); - } - }; - - const std::map& POSITION_MAP = get_keyboard_layout(keyboard_layout); - std::vector positions; - for (char ch : code){ - auto iter = POSITION_MAP.find(ch); - if (iter == POSITION_MAP.end()){ - throw_and_log( - console, ErrorReport::NO_ERROR_REPORT, - "Invalid code character." - ); - } - positions.emplace_back(iter->second); - } - - - ConsoleType console_type = console.state().console_type(); - bool switch2; - if (is_switch1(console_type)){ - switch2 = false; - }else if (is_switch2(console_type)){ - switch2 = true; - }else{ - throw UserSetupError( - console, - "Please select a valid Switch console type." - ); - } - - - // Compute the delays. - - Milliseconds unit; - Milliseconds hold; - Milliseconds cool; - bool reordering; - if (switch2){ - unit = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.REORDERING; - }else{ - unit = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.REORDERING; - } - - Milliseconds tv = context->timing_variation(); - unit += tv; - - CodeEntryDelays delays{ - .hold = hold, - .cool = cool, - .press_delay = unit, - .move_delay = unit, - .scroll_delay = unit, - .wrap_delay = 2*unit, - }; - - // Get all the possible paths. - std::vector> all_paths = keyboard_get_all_paths( - {0, 0}, - positions.data(), positions.size(), - reordering - ); - - // Pick the best path. - std::vector best_path = keyboard_get_best_path( - switch2, - all_paths, - delays, - !switch2 && context->atomic_multibutton() - ); - - codeboard_execute_path(context, delays, best_path); - - if (include_plus){ - ssf_press_button_ptv(context, BUTTON_PLUS); - ssf_press_button_ptv(context, BUTTON_PLUS); - } - - ssf_flush_pipeline(context); -} - - - - - - - - - - - - -} -} -} +/* Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch_CodeEntryTools.h" +#include "NintendoSwitch_KeyboardCodeEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + +struct KeyboardEntryPosition{ + uint8_t row; + uint8_t col; +}; + +static const std::map& KEYBOARD_POSITIONS_QWERTY(){ + static const std::map map{ + {'1', {0, 0}}, + {'2', {0, 1}}, + {'3', {0, 2}}, + {'4', {0, 3}}, + {'5', {0, 4}}, + {'6', {0, 5}}, + {'7', {0, 6}}, + {'8', {0, 7}}, + {'9', {0, 8}}, + {'0', {0, 9}}, + + {'Q', {1, 0}}, + {'W', {1, 1}}, + {'E', {1, 2}}, + {'R', {1, 3}}, + {'T', {1, 4}}, + {'Y', {1, 5}}, + {'U', {1, 6}}, + {'P', {1, 9}}, + + {'A', {2, 0}}, + {'S', {2, 1}}, + {'D', {2, 2}}, + {'F', {2, 3}}, + {'G', {2, 4}}, + {'H', {2, 5}}, + {'J', {2, 6}}, + {'K', {2, 7}}, + {'L', {2, 8}}, + + {'X', {3, 1}}, + {'C', {3, 2}}, + {'V', {3, 3}}, + {'B', {3, 4}}, + {'N', {3, 5}}, + {'M', {3, 6}}, + }; + return map; +} +static const std::map& KEYBOARD_POSITIONS_AZERTY(){ + static const std::map map{ + {'1', {0, 0}}, + {'2', {0, 1}}, + {'3', {0, 2}}, + {'4', {0, 3}}, + {'5', {0, 4}}, + {'6', {0, 5}}, + {'7', {0, 6}}, + {'8', {0, 7}}, + {'9', {0, 8}}, + {'0', {0, 9}}, + + {'A', {1, 0}}, + {'E', {1, 2}}, + {'R', {1, 3}}, + {'T', {1, 4}}, + {'Y', {1, 5}}, + {'U', {1, 6}}, + {'P', {1, 9}}, + + {'Q', {2, 0}}, + {'S', {2, 1}}, + {'D', {2, 2}}, + {'F', {2, 3}}, + {'G', {2, 4}}, + {'H', {2, 5}}, + {'J', {2, 6}}, + {'K', {2, 7}}, + {'L', {2, 8}}, + {'M', {2, 9}}, + + {'W', {3, 0}}, + {'X', {3, 1}}, + {'C', {3, 2}}, + {'V', {3, 3}}, + {'B', {3, 4}}, + {'N', {3, 5}}, + }; + return map; +} + + + + + + +// Return the path from "source" to "destination". +std::vector keyboard_get_path( + KeyboardEntryPosition source, + KeyboardEntryPosition destination +){ + std::vector path; + + // Vertical is easy since there's no wrapping and no hazards. + if (source.row < destination.row){ + size_t diff = destination.row - source.row; + for (size_t c = 0; c < diff; c++){ + path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); + } + }else{ + size_t diff = source.row - destination.row; + for (size_t c = 0; c < diff; c++){ + path.emplace_back(CodeEntryAction::NORM_MOVE_UP); + } + } + + // Horizontal is messy because we need extra delay on wrapping. + uint8_t col = source.col; + while (true){ + if (col == destination.col){ + break; + } + + CodeEntryAction action; + if (destination.col > col){ + if (destination.col - col <= 6){ + action = CodeEntryAction::NORM_MOVE_RIGHT; + col++; + }else{ + action = CodeEntryAction::NORM_MOVE_LEFT; + col--; + } + }else{ + if (col - destination.col <= 6){ + action = CodeEntryAction::NORM_MOVE_LEFT; + col--; + }else{ + action = CodeEntryAction::NORM_MOVE_RIGHT; + col++; + } + } + + // Wrap around the sides. + if (col == (uint8_t)-1){ + col = 11; + action = (CodeEntryAction)((uint8_t)action | 0x80); + } + if (col == 12){ + col = 0; + action = (CodeEntryAction)((uint8_t)action | 0x80); + } + + path.emplace_back(action); + } + + path.emplace_back(CodeEntryAction::ENTER_CHAR); + + return path; +} + + +// Get all possible paths from "start" to cover everything [positions, positions + length). +std::vector> keyboard_get_all_paths( + KeyboardEntryPosition start, + const KeyboardEntryPosition* positions, size_t length, + bool reordering +){ + if (length == 1){ + return {keyboard_get_path(start, positions[0])}; + } + + std::vector> paths; + { + KeyboardEntryPosition position = positions[0]; + std::vector current = keyboard_get_path(start, position); + std::vector> subpaths = keyboard_get_all_paths( + position, + positions + 1, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + if (reordering){ + KeyboardEntryPosition position = positions[length - 1]; + std::vector current = keyboard_get_path(start, position); + current.emplace_back(CodeEntryAction::SCROLL_LEFT); + std::vector> subpaths = keyboard_get_all_paths( + position, + positions, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + + return paths; +} + + + + +// Given a set of paths, find the best one and return it with fully populated +// delays. +std::vector keyboard_get_best_path( + bool switch2, + const std::vector>& paths, + const CodeEntryDelays& delays, + bool optimize +){ + std::vector best_path; + Milliseconds best_time = Milliseconds::max(); + for (const std::vector& path : paths){ + std::vector current_path; + codeboard_populate_delays(switch2, current_path, path, delays, optimize); + Milliseconds current_time = 0ms; + for (CodeEntryActionWithDelay& action : current_path){ + current_time += action.delay; + } + if (best_time > current_time){ + best_time = current_time; + best_path = std::move(current_path); + } + } + return best_path; +} + + + + +void keyboard_enter_code( + ConsoleHandle& console, ProControllerContext& context, + KeyboardLayout keyboard_layout, const std::string& code, + bool include_plus +){ + // Calculate the coordinates. + auto get_keyboard_layout = [](KeyboardLayout keyboard_layout){ + switch (keyboard_layout){ + case KeyboardLayout::QWERTY: + return KEYBOARD_POSITIONS_QWERTY(); + case KeyboardLayout::AZERTY: + return KEYBOARD_POSITIONS_AZERTY(); + default: + return KEYBOARD_POSITIONS_QWERTY(); + } + }; + + const std::map& POSITION_MAP = get_keyboard_layout(keyboard_layout); + std::vector positions; + for (char ch : code){ + auto iter = POSITION_MAP.find(ch); + if (iter == POSITION_MAP.end()){ + throw_and_log( + console, ErrorReport::NO_ERROR_REPORT, + "Invalid code character." + ); + } + positions.emplace_back(iter->second); + } + + + ConsoleType console_type = console.state().console_type(); + bool switch2; + if (is_switch1(console_type)){ + switch2 = false; + }else if (is_switch2(console_type)){ + switch2 = true; + }else{ + throw UserSetupError( + console, + "Please select a valid Switch console type." + ); + } + + + // Compute the delays. + + Milliseconds unit; + Milliseconds hold; + Milliseconds cool; + bool reordering; + if (switch2){ + unit = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH2_KEYBOARD_ENTRY.REORDERING; + }else{ + unit = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH1_KEYBOARD_ENTRY.REORDERING; + } + + Milliseconds tv = context->timing_variation(); + unit += tv; + + CodeEntryDelays delays{ + .hold = hold, + .cool = cool, + .press_delay = unit, + .move_delay = unit, + .scroll_delay = unit, + .wrap_delay = 2*unit, + }; + + // Get all the possible paths. + std::vector> all_paths = keyboard_get_all_paths( + {0, 0}, + positions.data(), positions.size(), + reordering + ); + + // Pick the best path. + std::vector best_path = keyboard_get_best_path( + switch2, + all_paths, + delays, + !switch2 && context->atomic_multibutton() + ); + + codeboard_execute_path(context, delays, best_path); + + if (include_plus){ + ssf_press_button_ptv(context, BUTTON_PLUS); + ssf_press_button_ptv(context, BUTTON_PLUS); + } + + ssf_flush_pipeline(context); +} + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h index f30d61f004..6271a82bfc 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h @@ -1,32 +1,32 @@ -/* Keyboard Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H -#define PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H - -#include -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - -void keyboard_enter_code( - ConsoleHandle& console, ProControllerContext& context, - KeyboardLayout keyboard_layout, const std::string& code, - bool include_plus -); - - - -} -} -} -#endif +/* Keyboard Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H +#define PokemonAutomation_NintendoSwitch_KeyboardCodeEntry_H + +#include +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + +void keyboard_enter_code( + ConsoleHandle& console, ProControllerContext& context, + KeyboardLayout keyboard_layout, const std::string& code, + bool include_plus +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp index 5eb25735cc..2680b7731c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.cpp @@ -1,273 +1,273 @@ -/* Number Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch_CodeEntryTools.h" -#include "NintendoSwitch_NumberCodeEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - -struct NumberEntryPosition{ - uint8_t row; - uint8_t col; -}; - -static const std::map& NUMBER_POSITIONS(){ - static const std::map map{ - {1, {0, 0}}, - {2, {0, 1}}, - {3, {0, 2}}, - {4, {1, 0}}, - {5, {1, 1}}, - {6, {1, 2}}, - {7, {2, 0}}, - {8, {2, 1}}, - {9, {2, 2}}, - {0, {3, 1}}, - - {'1', {0, 0}}, - {'2', {0, 1}}, - {'3', {0, 2}}, - {'4', {1, 0}}, - {'5', {1, 1}}, - {'6', {1, 2}}, - {'7', {2, 0}}, - {'8', {2, 1}}, - {'9', {2, 2}}, - {'0', {3, 1}}, - }; - return map; -} - - - - - -// Return the path from "source" to "destination". -std::vector numberpad_get_path( - NumberEntryPosition source, - NumberEntryPosition destination -){ - std::vector path; - - uint8_t row = source.row; - uint8_t col = source.col; - - // Do vertical first since it may auto-center the horizontal position. - while (row < destination.row){ - path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); - row++; - } - while (row > destination.row){ - path.emplace_back(CodeEntryAction::NORM_MOVE_UP); - row--; - } - - // Moving to the zero automatically changes the column. - if (row == 3){ - col = 1; - } - - while (col < destination.col){ - path.emplace_back(CodeEntryAction::NORM_MOVE_RIGHT); - col++; - } - while (col > destination.col){ - path.emplace_back(CodeEntryAction::NORM_MOVE_LEFT); - col--; - } - - path.emplace_back(CodeEntryAction::ENTER_CHAR); - - return path; -} - - -// Get all possible paths from "start" to cover everything [positions, positions + length). -std::vector> numberpad_get_all_paths( - NumberEntryPosition start, - const NumberEntryPosition* positions, size_t length, - bool reordering -){ - if (length == 1){ - return {numberpad_get_path(start, positions[0])}; - } - - std::vector> paths; - { - NumberEntryPosition position = positions[0]; - std::vector current = numberpad_get_path(start, position); - std::vector> subpaths = numberpad_get_all_paths( - position, - positions + 1, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - if (reordering){ - NumberEntryPosition position = positions[length - 1]; - std::vector current = numberpad_get_path(start, position); - current.emplace_back(CodeEntryAction::SCROLL_LEFT); - std::vector> subpaths = numberpad_get_all_paths( - position, - positions, length - 1, - reordering - ); - for (std::vector& path : subpaths){ - path.insert(path.begin(), current.begin(), current.end()); - paths.emplace_back(std::move(path)); - } - } - - return paths; -} - - - -// Given a set of paths, find the best one and return it with fully populated -// delays. -std::vector numberpad_get_best_path( - bool switch2, - const std::vector>& paths, - const CodeEntryDelays& delays, - bool optimize -){ - std::vector best_path; - Milliseconds best_time = Milliseconds::max(); - for (const std::vector& path : paths){ - std::vector current_path; - codeboard_populate_delays(switch2, current_path, path, delays, optimize); - Milliseconds current_time = 0ms; - for (CodeEntryActionWithDelay& action : current_path){ - current_time += action.delay; - if (action.action == CodeEntryAction::SCROLL_LEFT){ -// action.delay = - } - } - if (best_time > current_time){ - best_time = current_time; - best_path = std::move(current_path); - } - } - return best_path; -} - - - - -void numberpad_enter_code( - ConsoleHandle& console, ProControllerContext& context, - const std::string& code, - bool include_plus -){ - // Calculate the coordinates. - const std::map& POSITION_MAP = NUMBER_POSITIONS(); - std::vector positions; - for (char ch : code){ - auto iter = POSITION_MAP.find(ch); - if (iter == POSITION_MAP.end()){ - throw_and_log( - console, ErrorReport::NO_ERROR_REPORT, - "Invalid code character." - ); - } - positions.emplace_back(iter->second); - } - - - ConsoleType console_type = console.state().console_type(); - bool switch2; - if (is_switch1(console_type)){ - switch2 = false; - }else if (is_switch2(console_type)){ - switch2 = true; - }else{ - throw UserSetupError( - console, - "Please select a valid Switch console type." - ); - } - - - // Fetch the delays. - - Milliseconds unit; - Milliseconds hold; - Milliseconds cool; - bool reordering; - if (switch2){ - unit = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.REORDERING; - }else{ - unit = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.TIME_UNIT; - hold = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.HOLD; - cool = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.COOLDOWN; - reordering = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.REORDERING; - } - - Milliseconds tv = context->timing_variation(); - unit += tv; - - CodeEntryDelays delays{ - .hold = hold, - .cool = cool, - .press_delay = unit, - .move_delay = unit, - .scroll_delay = unit, - .wrap_delay = 2*unit, - }; - - - // Get all the possible paths. - std::vector> all_paths = numberpad_get_all_paths( - {0, 0}, - positions.data(), positions.size(), - reordering - ); - - // Pick the best path. - std::vector best_path = numberpad_get_best_path( - switch2, - all_paths, - delays, - !switch2 && context->atomic_multibutton() - ); - - codeboard_execute_path(context, delays, best_path); - - if (include_plus){ - ssf_press_button_ptv(context, BUTTON_PLUS); - ssf_press_button_ptv(context, BUTTON_PLUS); - } - - ssf_flush_pipeline(context); -} - - - - - - - -} -} -} +/* Number Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch_CodeEntryTools.h" +#include "NintendoSwitch_NumberCodeEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + +struct NumberEntryPosition{ + uint8_t row; + uint8_t col; +}; + +static const std::map& NUMBER_POSITIONS(){ + static const std::map map{ + {1, {0, 0}}, + {2, {0, 1}}, + {3, {0, 2}}, + {4, {1, 0}}, + {5, {1, 1}}, + {6, {1, 2}}, + {7, {2, 0}}, + {8, {2, 1}}, + {9, {2, 2}}, + {0, {3, 1}}, + + {'1', {0, 0}}, + {'2', {0, 1}}, + {'3', {0, 2}}, + {'4', {1, 0}}, + {'5', {1, 1}}, + {'6', {1, 2}}, + {'7', {2, 0}}, + {'8', {2, 1}}, + {'9', {2, 2}}, + {'0', {3, 1}}, + }; + return map; +} + + + + + +// Return the path from "source" to "destination". +std::vector numberpad_get_path( + NumberEntryPosition source, + NumberEntryPosition destination +){ + std::vector path; + + uint8_t row = source.row; + uint8_t col = source.col; + + // Do vertical first since it may auto-center the horizontal position. + while (row < destination.row){ + path.emplace_back(CodeEntryAction::NORM_MOVE_DOWN); + row++; + } + while (row > destination.row){ + path.emplace_back(CodeEntryAction::NORM_MOVE_UP); + row--; + } + + // Moving to the zero automatically changes the column. + if (row == 3){ + col = 1; + } + + while (col < destination.col){ + path.emplace_back(CodeEntryAction::NORM_MOVE_RIGHT); + col++; + } + while (col > destination.col){ + path.emplace_back(CodeEntryAction::NORM_MOVE_LEFT); + col--; + } + + path.emplace_back(CodeEntryAction::ENTER_CHAR); + + return path; +} + + +// Get all possible paths from "start" to cover everything [positions, positions + length). +std::vector> numberpad_get_all_paths( + NumberEntryPosition start, + const NumberEntryPosition* positions, size_t length, + bool reordering +){ + if (length == 1){ + return {numberpad_get_path(start, positions[0])}; + } + + std::vector> paths; + { + NumberEntryPosition position = positions[0]; + std::vector current = numberpad_get_path(start, position); + std::vector> subpaths = numberpad_get_all_paths( + position, + positions + 1, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + if (reordering){ + NumberEntryPosition position = positions[length - 1]; + std::vector current = numberpad_get_path(start, position); + current.emplace_back(CodeEntryAction::SCROLL_LEFT); + std::vector> subpaths = numberpad_get_all_paths( + position, + positions, length - 1, + reordering + ); + for (std::vector& path : subpaths){ + path.insert(path.begin(), current.begin(), current.end()); + paths.emplace_back(std::move(path)); + } + } + + return paths; +} + + + +// Given a set of paths, find the best one and return it with fully populated +// delays. +std::vector numberpad_get_best_path( + bool switch2, + const std::vector>& paths, + const CodeEntryDelays& delays, + bool optimize +){ + std::vector best_path; + Milliseconds best_time = Milliseconds::max(); + for (const std::vector& path : paths){ + std::vector current_path; + codeboard_populate_delays(switch2, current_path, path, delays, optimize); + Milliseconds current_time = 0ms; + for (CodeEntryActionWithDelay& action : current_path){ + current_time += action.delay; + if (action.action == CodeEntryAction::SCROLL_LEFT){ +// action.delay = + } + } + if (best_time > current_time){ + best_time = current_time; + best_path = std::move(current_path); + } + } + return best_path; +} + + + + +void numberpad_enter_code( + ConsoleHandle& console, ProControllerContext& context, + const std::string& code, + bool include_plus +){ + // Calculate the coordinates. + const std::map& POSITION_MAP = NUMBER_POSITIONS(); + std::vector positions; + for (char ch : code){ + auto iter = POSITION_MAP.find(ch); + if (iter == POSITION_MAP.end()){ + throw_and_log( + console, ErrorReport::NO_ERROR_REPORT, + "Invalid code character." + ); + } + positions.emplace_back(iter->second); + } + + + ConsoleType console_type = console.state().console_type(); + bool switch2; + if (is_switch1(console_type)){ + switch2 = false; + }else if (is_switch2(console_type)){ + switch2 = true; + }else{ + throw UserSetupError( + console, + "Please select a valid Switch console type." + ); + } + + + // Fetch the delays. + + Milliseconds unit; + Milliseconds hold; + Milliseconds cool; + bool reordering; + if (switch2){ + unit = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH2_DIGIT_ENTRY.REORDERING; + }else{ + unit = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.TIME_UNIT; + hold = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.HOLD; + cool = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.COOLDOWN; + reordering = ConsoleSettings::instance().SWITCH1_DIGIT_ENTRY.REORDERING; + } + + Milliseconds tv = context->timing_variation(); + unit += tv; + + CodeEntryDelays delays{ + .hold = hold, + .cool = cool, + .press_delay = unit, + .move_delay = unit, + .scroll_delay = unit, + .wrap_delay = 2*unit, + }; + + + // Get all the possible paths. + std::vector> all_paths = numberpad_get_all_paths( + {0, 0}, + positions.data(), positions.size(), + reordering + ); + + // Pick the best path. + std::vector best_path = numberpad_get_best_path( + switch2, + all_paths, + delays, + !switch2 && context->atomic_multibutton() + ); + + codeboard_execute_path(context, delays, best_path); + + if (include_plus){ + ssf_press_button_ptv(context, BUTTON_PLUS); + ssf_press_button_ptv(context, BUTTON_PLUS); + } + + ssf_flush_pipeline(context); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h index 462241a506..78cc1afd77 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h @@ -1,31 +1,31 @@ -/* Number Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_NumberCodeEntry_H -#define PokemonAutomation_NintendoSwitch_NumberCodeEntry_H - -#include -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace FastCodeEntry{ - - - -void numberpad_enter_code( - ConsoleHandle& console, ProControllerContext& context, - const std::string& code, - bool include_plus -); - - - -} -} -} -#endif +/* Number Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_NumberCodeEntry_H +#define PokemonAutomation_NintendoSwitch_NumberCodeEntry_H + +#include +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace FastCodeEntry{ + + + +void numberpad_enter_code( + ConsoleHandle& console, ProControllerContext& context, + const std::string& code, + bool include_plus +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h index dd00acc076..7eb737bb15 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h @@ -1,43 +1,43 @@ -/* Date Skippers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_DateSkippers_H -#define PokemonAutomation_NintendoSwitch_DateSkippers_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "CommonFramework/Tools/VideoStream.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace DateSkippers{ - - -namespace Switch1{ - void init_view(ProControllerContext& context); - void auto_recovery(ProControllerContext& context); - void increment_day_with_feedback(VideoStream& stream, ProControllerContext& context, bool date_us); - void increment_day(ProControllerContext& context, bool date_us); - void rollback_year_full(ProControllerContext& context, bool date_us); - void rollback_year_sync(ProControllerContext& context); - void increment_monthday(ProControllerContext& context); - void increment_daymonth(ProControllerContext& context); - void increment_month(ProControllerContext& context, uint8_t days); - void increment_all(ProControllerContext& context); - void increment_all_rollback(ProControllerContext& context); -} -namespace Switch2{ - void init_view(ProControllerContext& context); - void increment_day_us(ProControllerContext& context); - void increment_day_eu(ProControllerContext& context); - void increment_day_jp(ProControllerContext& context); -} - - - -} -} -} -#endif +/* Date Skippers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_DateSkippers_H +#define PokemonAutomation_NintendoSwitch_DateSkippers_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "CommonFramework/Tools/VideoStream.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace DateSkippers{ + + +namespace Switch1{ + void init_view(ProControllerContext& context); + void auto_recovery(ProControllerContext& context); + void increment_day_with_feedback(VideoStream& stream, ProControllerContext& context, bool date_us); + void increment_day(ProControllerContext& context, bool date_us); + void rollback_year_full(ProControllerContext& context, bool date_us); + void rollback_year_sync(ProControllerContext& context); + void increment_monthday(ProControllerContext& context); + void increment_daymonth(ProControllerContext& context); + void increment_month(ProControllerContext& context, uint8_t days); + void increment_all(ProControllerContext& context); + void increment_all_rollback(ProControllerContext& context); +} +namespace Switch2{ + void init_view(ProControllerContext& context); + void increment_day_us(ProControllerContext& context); + void increment_day_eu(ProControllerContext& context); + void increment_day_jp(ProControllerContext& context); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp index 2b2ecd526f..9f85aca169 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.cpp @@ -1,111 +1,111 @@ -/* Friend Code Adder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch_FriendCodeAdder.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -FriendCodeAdder_Descriptor::FriendCodeAdder_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:FriendCodeAdder", - "Nintendo Switch", "Friend Code Adder", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/FriendCodeAdder.md", - "Add a list of friend codes.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - -FriendCodeAdder::FriendCodeAdder() - : USER_SLOT( - "User Slot:
Send friend requests for this profile.", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 8 - ) - , FRIEND_CODES( - "Friend Codes: One per line only. Invalid characters are ignored.", - { - "SW-1234-5678-9012", - "123456789012", - } - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , OPEN_CODE_PAD_DELAY1( - "Open Code Pad Delay", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , SEARCH_TIME0( - "Search Time:
Wait this long after initiating search.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , TOGGLE_BEST_STATUS_DELAY0( - "Toggle Best Delay:
Time needed to toggle the best friend status.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) -{ - PA_ADD_OPTION(USER_SLOT); - PA_ADD_OPTION(FRIEND_CODES); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(OPEN_CODE_PAD_DELAY1); - PA_ADD_OPTION(SEARCH_TIME0); - PA_ADD_OPTION(TOGGLE_BEST_STATUS_DELAY0); -} - -void FriendCodeAdder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - grip_menu_connect_go_home(context); - - ConsoleType type = env.console.state().console_type(); - uint8_t scroll_down_slots = 0; - if (is_switch1(type)){ - scroll_down_slots = 3; - }else if (is_switch2(type)){ - scroll_down_slots = 1; - }else{ - throw UserSetupError( - env.logger(), - "Please select a valid Switch console type." - ); - } - - bool first = true; - for (const std::string& line : FRIEND_CODES.lines()){ - std::string code = FriendCodeListOption::parse(line); - if (code.size() != 12){ - continue; - } - - PokemonSwSh::home_to_add_friends(context, USER_SLOT - 1, scroll_down_slots, first); - first = false; - - ssf_press_button_ptv(context, BUTTON_A, OPEN_CODE_PAD_DELAY1); - FastCodeEntry::numberpad_enter_code(env.console, context, code, true); - - pbf_wait(context, SEARCH_TIME0); - ssf_press_button(context, BUTTON_A, TOGGLE_BEST_STATUS_DELAY0); - ssf_press_button(context, BUTTON_A, TOGGLE_BEST_STATUS_DELAY0); - pbf_press_button(context, BUTTON_HOME, 80ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - } -} - - - -} -} +/* Friend Code Adder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch_FriendCodeAdder.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +FriendCodeAdder_Descriptor::FriendCodeAdder_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:FriendCodeAdder", + "Nintendo Switch", "Friend Code Adder", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/FriendCodeAdder.md", + "Add a list of friend codes.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + +FriendCodeAdder::FriendCodeAdder() + : USER_SLOT( + "User Slot:
Send friend requests for this profile.", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 8 + ) + , FRIEND_CODES( + "Friend Codes: One per line only. Invalid characters are ignored.", + { + "SW-1234-5678-9012", + "123456789012", + } + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , OPEN_CODE_PAD_DELAY1( + "Open Code Pad Delay", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , SEARCH_TIME0( + "Search Time:
Wait this long after initiating search.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , TOGGLE_BEST_STATUS_DELAY0( + "Toggle Best Delay:
Time needed to toggle the best friend status.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) +{ + PA_ADD_OPTION(USER_SLOT); + PA_ADD_OPTION(FRIEND_CODES); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(OPEN_CODE_PAD_DELAY1); + PA_ADD_OPTION(SEARCH_TIME0); + PA_ADD_OPTION(TOGGLE_BEST_STATUS_DELAY0); +} + +void FriendCodeAdder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + grip_menu_connect_go_home(context); + + ConsoleType type = env.console.state().console_type(); + uint8_t scroll_down_slots = 0; + if (is_switch1(type)){ + scroll_down_slots = 3; + }else if (is_switch2(type)){ + scroll_down_slots = 1; + }else{ + throw UserSetupError( + env.logger(), + "Please select a valid Switch console type." + ); + } + + bool first = true; + for (const std::string& line : FRIEND_CODES.lines()){ + std::string code = FriendCodeListOption::parse(line); + if (code.size() != 12){ + continue; + } + + PokemonSwSh::home_to_add_friends(context, USER_SLOT - 1, scroll_down_slots, first); + first = false; + + ssf_press_button_ptv(context, BUTTON_A, OPEN_CODE_PAD_DELAY1); + FastCodeEntry::numberpad_enter_code(env.console, context, code, true); + + pbf_wait(context, SEARCH_TIME0); + ssf_press_button(context, BUTTON_A, TOGGLE_BEST_STATUS_DELAY0); + ssf_press_button(context, BUTTON_A, TOGGLE_BEST_STATUS_DELAY0); + pbf_press_button(context, BUTTON_HOME, 80ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + } +} + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h index 98684dee56..aef2568716 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendCodeAdder.h @@ -1,45 +1,45 @@ -/* Friend Code Adder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_FriendCodeAdder_H -#define PokemonAutomation_NintendoSwitch_FriendCodeAdder_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class FriendCodeAdder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FriendCodeAdder_Descriptor(); -}; - - -class FriendCodeAdder : public SingleSwitchProgramInstance{ -public: - FriendCodeAdder(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption USER_SLOT; - FriendCodeListOption FRIEND_CODES; - SectionDividerOption m_advanced_options; - MillisecondsOption OPEN_CODE_PAD_DELAY1; - MillisecondsOption SEARCH_TIME0; - MillisecondsOption TOGGLE_BEST_STATUS_DELAY0; -}; - - -} -} -#endif - +/* Friend Code Adder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_FriendCodeAdder_H +#define PokemonAutomation_NintendoSwitch_FriendCodeAdder_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class FriendCodeAdder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FriendCodeAdder_Descriptor(); +}; + + +class FriendCodeAdder : public SingleSwitchProgramInstance{ +public: + FriendCodeAdder(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption USER_SLOT; + FriendCodeListOption FRIEND_CODES; + SectionDividerOption m_advanced_options; + MillisecondsOption OPEN_CODE_PAD_DELAY1; + MillisecondsOption SEARCH_TIME0; + MillisecondsOption TOGGLE_BEST_STATUS_DELAY0; +}; + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp index 6f84b83fe2..681ef5418b 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.cpp @@ -1,86 +1,86 @@ -/* Friend Delete - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch_FriendDelete.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -FriendDelete_Descriptor::FriendDelete_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:FriendDelete", - "Nintendo Switch", "Friend Delete", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/FriendDelete.md", - "Mass delete/block all those unwanted friends.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -FriendDelete::FriendDelete() - : FRIENDS_TO_DELETE( - "Number of Friends to Delete:", - LockMode::LOCK_WHILE_RUNNING, - 3, 0, 300 - ) - , BLOCK_FRIENDS( - "Block Friends:
Block instead of delete!", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , VIEW_FRIEND_DELAY0( - "View Friend Delay:
Delay from opening a friend to when you can press buttons.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , DELETE_FRIEND_DELAY0( - "Delete Friend Delay:
Delay to delete the friend.", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , FINISH_DELETE_DELAY0( - "Finish Delete Delay:
Delay after deleting a friend.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) -{ - PA_ADD_OPTION(FRIENDS_TO_DELETE); - PA_ADD_OPTION(BLOCK_FRIENDS); - PA_ADD_OPTION(VIEW_FRIEND_DELAY0); - PA_ADD_OPTION(DELETE_FRIEND_DELAY0); - PA_ADD_OPTION(FINISH_DELETE_DELAY0); -} -void FriendDelete::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 10, 20); - - for (uint16_t c = 0; c < FRIENDS_TO_DELETE; c++){ - pbf_press_button(context, BUTTON_A, 40ms, VIEW_FRIEND_DELAY0); // View friend - pbf_press_dpad(context, DPAD_DOWN, 10, 20); - pbf_press_button(context, BUTTON_A, 10, 90); // Click on Options - if (BLOCK_FRIENDS){ - pbf_press_dpad(context, DPAD_DOWN, 10, 20); - } - pbf_press_button(context, BUTTON_A, 10, 90); // Click on Remove/Block Friend - if (BLOCK_FRIENDS){ - pbf_press_button(context, BUTTON_A, 80ms, VIEW_FRIEND_DELAY0); // Confirm - } - pbf_press_button(context, BUTTON_A, 80ms, DELETE_FRIEND_DELAY0); // Confirm - pbf_press_button(context, BUTTON_A, 80ms, FINISH_DELETE_DELAY0); // Finish delete friend. - } -} - - - - - - -} -} +/* Friend Delete + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch_FriendDelete.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +FriendDelete_Descriptor::FriendDelete_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:FriendDelete", + "Nintendo Switch", "Friend Delete", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/FriendDelete.md", + "Mass delete/block all those unwanted friends.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +FriendDelete::FriendDelete() + : FRIENDS_TO_DELETE( + "Number of Friends to Delete:", + LockMode::LOCK_WHILE_RUNNING, + 3, 0, 300 + ) + , BLOCK_FRIENDS( + "Block Friends:
Block instead of delete!", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , VIEW_FRIEND_DELAY0( + "View Friend Delay:
Delay from opening a friend to when you can press buttons.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , DELETE_FRIEND_DELAY0( + "Delete Friend Delay:
Delay to delete the friend.", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , FINISH_DELETE_DELAY0( + "Finish Delete Delay:
Delay after deleting a friend.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) +{ + PA_ADD_OPTION(FRIENDS_TO_DELETE); + PA_ADD_OPTION(BLOCK_FRIENDS); + PA_ADD_OPTION(VIEW_FRIEND_DELAY0); + PA_ADD_OPTION(DELETE_FRIEND_DELAY0); + PA_ADD_OPTION(FINISH_DELETE_DELAY0); +} +void FriendDelete::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 10, 20); + + for (uint16_t c = 0; c < FRIENDS_TO_DELETE; c++){ + pbf_press_button(context, BUTTON_A, 40ms, VIEW_FRIEND_DELAY0); // View friend + pbf_press_dpad(context, DPAD_DOWN, 10, 20); + pbf_press_button(context, BUTTON_A, 10, 90); // Click on Options + if (BLOCK_FRIENDS){ + pbf_press_dpad(context, DPAD_DOWN, 10, 20); + } + pbf_press_button(context, BUTTON_A, 10, 90); // Click on Remove/Block Friend + if (BLOCK_FRIENDS){ + pbf_press_button(context, BUTTON_A, 80ms, VIEW_FRIEND_DELAY0); // Confirm + } + pbf_press_button(context, BUTTON_A, 80ms, DELETE_FRIEND_DELAY0); // Confirm + pbf_press_button(context, BUTTON_A, 80ms, FINISH_DELETE_DELAY0); // Finish delete friend. + } +} + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.h index 67082bdf24..2cda3fbcb6 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_FriendDelete.h @@ -1,47 +1,47 @@ -/* Friend Delete - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_FriendDelete_H -#define PokemonAutomation_NintendoSwitch_FriendDelete_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class FriendDelete_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FriendDelete_Descriptor(); -}; - - - -class FriendDelete : public SingleSwitchProgramInstance{ -public: - FriendDelete(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption FRIENDS_TO_DELETE; - BooleanCheckBoxOption BLOCK_FRIENDS; - MillisecondsOption VIEW_FRIEND_DELAY0; - MillisecondsOption DELETE_FRIEND_DELAY0; - MillisecondsOption FINISH_DELETE_DELAY0; -}; - - - - -} -} -#endif - - - +/* Friend Delete + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_FriendDelete_H +#define PokemonAutomation_NintendoSwitch_FriendDelete_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class FriendDelete_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FriendDelete_Descriptor(); +}; + + + +class FriendDelete : public SingleSwitchProgramInstance{ +public: + FriendDelete(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption FRIENDS_TO_DELETE; + BooleanCheckBoxOption BLOCK_FRIENDS; + MillisecondsOption VIEW_FRIEND_DELAY0; + MillisecondsOption DELETE_FRIEND_DELAY0; + MillisecondsOption FINISH_DELETE_DELAY0; +}; + + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp index 6f92e9463b..1541c65b4f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.cpp @@ -1,551 +1,551 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h" -#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" -#include "NintendoSwitch_GameEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - - - -void wait_for_home(ConsoleHandle& console, ProControllerContext& context){ - // Feedback not available. Just assume we're already on Home. - if (!console.video().snapshot()){ - return; - } - - for (size_t attempts = 0;; attempts++){ - HomeMenuWatcher home_menu(console, 100ms); - int ret = wait_until( - console, context, 5000ms, - {home_menu} - ); - if (ret == 0){ - break; - } - if (attempts == 2){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find Switch Home", - console - ); - } - } -} - - - - - - - - - -void resume_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool skip_home_press -){ - if (!skip_home_press){ - pbf_press_button(context, BUTTON_HOME, 10, 10); - } - context.wait_for_all_requests(); - - while (true){ - { - UpdateMenuWatcher update_detector(console); - int ret = wait_until( - console, context, - std::chrono::milliseconds(1000), - { update_detector } - ); - if (ret == 0){ - console.log("Detected update window.", COLOR_RED); - - pbf_press_dpad(context, DPAD_UP, 5, 0); - pbf_press_button(context, BUTTON_A, 10, 500); - context.wait_for_all_requests(); - continue; - } - } - - // In case we failed to enter the game. - HomeMenuWatcher home_detector(console); - if (home_detector.detect(console.video().snapshot())){ - console.log("Failed to re-enter game. Trying again...", COLOR_RED); - pbf_press_button(context, BUTTON_HOME, 10, 10); - continue; - }else{ - break; - } - } -} - - - - - - - - - - - -void move_to_user(ProControllerContext& context, uint8_t user_slot){ - if (user_slot != 0){ - // Move to correct user. - for (uint8_t c = 0; c < 9; c++){ // Extra iteration in case one gets dropped. - ssf_issue_scroll_ptv(context, DPAD_LEFT, 160ms, 160ms); - } - for (uint8_t c = 1; c < user_slot; c++){ - ssf_issue_scroll_ptv(context, DPAD_RIGHT, 160ms, 160ms); - } - } -} - - -void start_game_from_home_with_inference( - ConsoleHandle& console, ProControllerContext& context, - uint8_t game_slot, - uint8_t user_slot, - Milliseconds start_game_wait -){ - context.wait_for_all_requests(); - { - HomeMenuWatcher detector(console); - int ret = run_until( - console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - }, - { detector } - ); - if (ret == 0){ - console.log("Detected Home screen."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "start_game_from_home_with_inference(): Failed to detect Home screen after 10 seconds.", - console - ); - } - context.wait_for(std::chrono::milliseconds(100)); - } - - if (game_slot != 0){ - ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); - for (uint8_t c = 1; c < game_slot; c++){ - ssf_press_dpad_ptv(context, DPAD_RIGHT, 160ms); - } - context.wait_for_all_requests(); - } - - pbf_press_button(context, BUTTON_A, 20, 105); - - while (true){ - HomeMenuWatcher home(console, std::chrono::milliseconds(2000)); - StartGameUserSelectWatcher user_select(console, COLOR_GREEN); - UpdateMenuWatcher update_menu(console, COLOR_PURPLE); - CheckOnlineWatcher check_online(COLOR_CYAN); - BlackScreenWatcher black_screen(COLOR_BLUE, {0.1, 0.15, 0.8, 0.7}); - context.wait_for_all_requests(); - int ret = wait_until( - console, context, - std::chrono::seconds(30), - { - home, - user_select, - update_menu, - check_online, - black_screen, - } - ); - - // Wait for screen to stabilize. - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: - console.log("Detected home screen (again).", COLOR_RED); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case 1: - console.log("Detected user-select screen."); - move_to_user(context, user_slot); - pbf_press_button(context, BUTTON_A, 80ms, start_game_wait); - break; - case 2: - console.log("Detected update menu.", COLOR_RED); - pbf_press_dpad(context, DPAD_UP, 5, 0); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case 3: - console.log("Detected check online.", COLOR_RED); - context.wait_for(std::chrono::seconds(1)); - break; - case 4: - console.log("Detected black screen. Game started..."); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "start_game_from_home_with_inference(): No recognizable state after 30 seconds.", - console - ); - } - } -} - - -void start_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot, - uint8_t user_slot, - Milliseconds start_game_mash -){ - context.wait_for_all_requests(); - if (console.video().snapshot()){ - console.log("start_game_from_home(): Video capture available. Using inference..."); - start_game_from_home_with_inference( - console, context, - game_slot, user_slot, - start_game_mash - ); - return; - }else{ - console.log("start_game_from_home(): Video capture not available.", COLOR_RED); - } - - if (game_slot != 0){ - ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); - for (uint8_t c = 1; c < game_slot; c++){ - ssf_press_dpad_ptv(context, DPAD_RIGHT, 80ms); - } - } - - if (tolerate_update_menu){ - if (ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET){ - throw UserSetupError( - console.logger(), - "Cannot have both \"Tolerate Update Menu\" and \"Start Game Requires Internet\" enabled at the same time without video feedback." - ); - } - - // If the update menu isn't there, these will get swallowed by the opening - // animation for the select user menu. - pbf_press_button(context, BUTTON_A, 10, 175); // Choose game - pbf_press_dpad(context, DPAD_UP, 10, 0); // Skip the update window. - move_to_user(context, user_slot); - } - -// cout << "START_GAME_REQUIRES_INTERNET = " << ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET << endl; - if (!ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET && user_slot == 0){ - // Mash your way into the game. - pbf_mash_button(context, BUTTON_A, start_game_mash); - }else{ - pbf_press_button(context, BUTTON_A, 10, 175); // Enter select user menu. - move_to_user(context, user_slot); - ssf_press_button_ptv(context, BUTTON_A, 160ms); // Enter game - - // Switch to mashing ZL instead of A to get into the game. - // Mash your way into the game. - Milliseconds duration = start_game_mash; - if (ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET){ - // Need to wait a bit longer for the internet check. - duration += ConsoleSettings::instance().START_GAME_INTERNET_CHECK_DELAY0; - } -// pbf_mash_button(context, BUTTON_ZL, duration); - pbf_wait(context, duration); - } - context.wait_for_all_requests(); -} - - - -class GameLoadingDetector : public VisualInferenceCallback{ -public: - GameLoadingDetector(bool invert) - : VisualInferenceCallback("LoadingDetector") - , m_box0(0.2, 0.2, 0.6, 0.1) - , m_box1(0.2, 0.7, 0.6, 0.1) - , m_invert(invert) - {} - - virtual void make_overlays(VideoOverlaySet& items) const override{ - items.add(COLOR_RED, m_box0); - items.add(COLOR_RED, m_box1); - } - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - if (!is_black(extract_box_reference(frame, m_box0))){ - return m_invert; - } - if (!is_black(extract_box_reference(frame, m_box1))){ - return m_invert; - } - return !m_invert; - } - -private: - ImageFloatBox m_box0; - ImageFloatBox m_box1; - bool m_invert; -}; - - -bool openedgame_to_gamemenu( - VideoStream& stream, ProControllerContext& context, - Milliseconds timeout -){ - { - stream.log("Waiting to load game..."); - GameLoadingDetector detector(false); - int ret = wait_until( - stream, context, - timeout, - {{detector}} - ); - if (ret < 0){ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } - } - { - stream.log("Waiting for game menu..."); - GameLoadingDetector detector(true); - int ret = wait_until( - stream, context, - timeout, - {{detector}} - ); - if (ret < 0){ - stream.log("Timed out waiting for game menu.", COLOR_RED); - return false; - } - } - return true; -} - - - - -void resume_game_from_home( - ConsoleHandle& console, JoyconContext& context, - bool skip_home_press -){ - if (!skip_home_press){ - pbf_press_button(context, BUTTON_HOME, 20ms, 10ms); - } - context.wait_for_all_requests(); - - while (true){ - { - UpdateMenuWatcher update_detector(console); - int ret = wait_until( - console, context, - std::chrono::milliseconds(1000), - { update_detector } - ); - if (ret == 0){ - console.log("Detected update window.", COLOR_RED); - - pbf_move_joystick(context, 128, 0, 10ms, 0ms); - pbf_press_button(context, BUTTON_A, 10ms, 500ms); - context.wait_for_all_requests(); - continue; - } - } - - // In case we failed to enter the game. - HomeMenuWatcher home_detector(console); - if (home_detector.detect(console.video().snapshot())){ - console.log("Failed to re-enter game. Trying again...", COLOR_RED); - pbf_press_button(context, BUTTON_HOME, 20ms, 10ms); - continue; - }else{ - break; - } - } -} -void move_to_user(JoyconContext& context, uint8_t user_slot){ - if (user_slot != 0){ - // Move to correct user. - for (uint8_t c = 0; c < 9; c++){ // Extra iteration in case one gets dropped. - pbf_move_joystick(context, 0, 128, 160ms, 160ms); - } - for (uint8_t c = 1; c < user_slot; c++){ - pbf_move_joystick(context, 0, 128, 160ms, 160ms); - } - } -} - -void start_game_from_home_with_inference( - ConsoleHandle& console, JoyconContext& context, - uint8_t game_slot, - uint8_t user_slot, - Milliseconds start_game_wait -){ - context.wait_for_all_requests(); - - if (!(context.controller().controller_type() == ControllerType::NintendoSwitch_RightJoycon)) { - console.log("Right Joycon required!", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "start_game_from_home_with_inference(): Right Joycon required.", - console - ); - } - - { - HomeMenuWatcher detector(console); - int ret = run_until( - console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_B, 10000ms); - }, - { detector } - ); - if (ret == 0){ - console.log("Detected Home screen."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "start_game_from_home_with_inference(): Failed to detect Home screen after 10 seconds.", - console - ); - } - context.wait_for(std::chrono::milliseconds(100)); - } - - if (game_slot != 0){ - ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); - for (uint8_t c = 1; c < game_slot; c++){ - pbf_move_joystick(context, 255, 128, 160ms, 0ms); - } - context.wait_for_all_requests(); - } - - pbf_press_button(context, BUTTON_A, 160ms, 840ms); - - while (true){ - HomeMenuWatcher home(console, std::chrono::milliseconds(2000)); - StartGameUserSelectWatcher user_select(console, COLOR_GREEN); - UpdateMenuWatcher update_menu(console, COLOR_PURPLE); - CheckOnlineWatcher check_online(COLOR_CYAN); - BlackScreenWatcher black_screen(COLOR_BLUE); - context.wait_for_all_requests(); - int ret = wait_until( - console, context, - std::chrono::seconds(30), - { - home, - user_select, - update_menu, - check_online, - black_screen, - } - ); - - // Wait for screen to stabilize. - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: - console.log("Detected home screen (again).", COLOR_RED); - pbf_press_button(context, BUTTON_A, 160ms, 840ms); - break; - case 1: - console.log("Detected user-select screen."); - move_to_user(context, user_slot); - pbf_press_button(context, BUTTON_A, 80ms, start_game_wait); - break; - case 2: - console.log("Detected update menu.", COLOR_RED); - pbf_move_joystick(context, 128, 0, 50ms, 0ms); - pbf_press_button(context, BUTTON_A, 160ms, 840ms); - break; - case 3: - console.log("Detected check online.", COLOR_RED); - context.wait_for(std::chrono::seconds(1)); - break; - case 4: - console.log("Detected black screen. Game started..."); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "start_game_from_home_with_inference(): No recognizable state after 30 seconds.", - console - ); - } - } -} - -bool openedgame_to_gamemenu( - VideoStream& stream, JoyconContext& context, - Milliseconds timeout -){ - { - stream.log("Waiting to load game..."); - GameLoadingDetector detector(false); - int ret = wait_until( - stream, context, - timeout, - {{detector}} - ); - if (ret < 0){ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } - } - { - stream.log("Waiting for game menu..."); - GameLoadingDetector detector(true); - int ret = wait_until( - stream, context, - timeout, - {{detector}} - ); - if (ret < 0){ - stream.log("Timed out waiting for game menu.", COLOR_RED); - return false; - } - } - return true; -} - - - - - - - - -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_StartGameUserSelectDetector.h" +#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" +#include "NintendoSwitch_GameEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + + + +void wait_for_home(ConsoleHandle& console, ProControllerContext& context){ + // Feedback not available. Just assume we're already on Home. + if (!console.video().snapshot()){ + return; + } + + for (size_t attempts = 0;; attempts++){ + HomeMenuWatcher home_menu(console, 100ms); + int ret = wait_until( + console, context, 5000ms, + {home_menu} + ); + if (ret == 0){ + break; + } + if (attempts == 2){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find Switch Home", + console + ); + } + } +} + + + + + + + + + +void resume_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool skip_home_press +){ + if (!skip_home_press){ + pbf_press_button(context, BUTTON_HOME, 10, 10); + } + context.wait_for_all_requests(); + + while (true){ + { + UpdateMenuWatcher update_detector(console); + int ret = wait_until( + console, context, + std::chrono::milliseconds(1000), + { update_detector } + ); + if (ret == 0){ + console.log("Detected update window.", COLOR_RED); + + pbf_press_dpad(context, DPAD_UP, 5, 0); + pbf_press_button(context, BUTTON_A, 10, 500); + context.wait_for_all_requests(); + continue; + } + } + + // In case we failed to enter the game. + HomeMenuWatcher home_detector(console); + if (home_detector.detect(console.video().snapshot())){ + console.log("Failed to re-enter game. Trying again...", COLOR_RED); + pbf_press_button(context, BUTTON_HOME, 10, 10); + continue; + }else{ + break; + } + } +} + + + + + + + + + + + +void move_to_user(ProControllerContext& context, uint8_t user_slot){ + if (user_slot != 0){ + // Move to correct user. + for (uint8_t c = 0; c < 9; c++){ // Extra iteration in case one gets dropped. + ssf_issue_scroll_ptv(context, DPAD_LEFT, 160ms, 160ms); + } + for (uint8_t c = 1; c < user_slot; c++){ + ssf_issue_scroll_ptv(context, DPAD_RIGHT, 160ms, 160ms); + } + } +} + + +void start_game_from_home_with_inference( + ConsoleHandle& console, ProControllerContext& context, + uint8_t game_slot, + uint8_t user_slot, + Milliseconds start_game_wait +){ + context.wait_for_all_requests(); + { + HomeMenuWatcher detector(console); + int ret = run_until( + console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + }, + { detector } + ); + if (ret == 0){ + console.log("Detected Home screen."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "start_game_from_home_with_inference(): Failed to detect Home screen after 10 seconds.", + console + ); + } + context.wait_for(std::chrono::milliseconds(100)); + } + + if (game_slot != 0){ + ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); + for (uint8_t c = 1; c < game_slot; c++){ + ssf_press_dpad_ptv(context, DPAD_RIGHT, 160ms); + } + context.wait_for_all_requests(); + } + + pbf_press_button(context, BUTTON_A, 20, 105); + + while (true){ + HomeMenuWatcher home(console, std::chrono::milliseconds(2000)); + StartGameUserSelectWatcher user_select(console, COLOR_GREEN); + UpdateMenuWatcher update_menu(console, COLOR_PURPLE); + CheckOnlineWatcher check_online(COLOR_CYAN); + BlackScreenWatcher black_screen(COLOR_BLUE, {0.1, 0.15, 0.8, 0.7}); + context.wait_for_all_requests(); + int ret = wait_until( + console, context, + std::chrono::seconds(30), + { + home, + user_select, + update_menu, + check_online, + black_screen, + } + ); + + // Wait for screen to stabilize. + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: + console.log("Detected home screen (again).", COLOR_RED); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case 1: + console.log("Detected user-select screen."); + move_to_user(context, user_slot); + pbf_press_button(context, BUTTON_A, 80ms, start_game_wait); + break; + case 2: + console.log("Detected update menu.", COLOR_RED); + pbf_press_dpad(context, DPAD_UP, 5, 0); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case 3: + console.log("Detected check online.", COLOR_RED); + context.wait_for(std::chrono::seconds(1)); + break; + case 4: + console.log("Detected black screen. Game started..."); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "start_game_from_home_with_inference(): No recognizable state after 30 seconds.", + console + ); + } + } +} + + +void start_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot, + uint8_t user_slot, + Milliseconds start_game_mash +){ + context.wait_for_all_requests(); + if (console.video().snapshot()){ + console.log("start_game_from_home(): Video capture available. Using inference..."); + start_game_from_home_with_inference( + console, context, + game_slot, user_slot, + start_game_mash + ); + return; + }else{ + console.log("start_game_from_home(): Video capture not available.", COLOR_RED); + } + + if (game_slot != 0){ + ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); + for (uint8_t c = 1; c < game_slot; c++){ + ssf_press_dpad_ptv(context, DPAD_RIGHT, 80ms); + } + } + + if (tolerate_update_menu){ + if (ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET){ + throw UserSetupError( + console.logger(), + "Cannot have both \"Tolerate Update Menu\" and \"Start Game Requires Internet\" enabled at the same time without video feedback." + ); + } + + // If the update menu isn't there, these will get swallowed by the opening + // animation for the select user menu. + pbf_press_button(context, BUTTON_A, 10, 175); // Choose game + pbf_press_dpad(context, DPAD_UP, 10, 0); // Skip the update window. + move_to_user(context, user_slot); + } + +// cout << "START_GAME_REQUIRES_INTERNET = " << ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET << endl; + if (!ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET && user_slot == 0){ + // Mash your way into the game. + pbf_mash_button(context, BUTTON_A, start_game_mash); + }else{ + pbf_press_button(context, BUTTON_A, 10, 175); // Enter select user menu. + move_to_user(context, user_slot); + ssf_press_button_ptv(context, BUTTON_A, 160ms); // Enter game + + // Switch to mashing ZL instead of A to get into the game. + // Mash your way into the game. + Milliseconds duration = start_game_mash; + if (ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET){ + // Need to wait a bit longer for the internet check. + duration += ConsoleSettings::instance().START_GAME_INTERNET_CHECK_DELAY0; + } +// pbf_mash_button(context, BUTTON_ZL, duration); + pbf_wait(context, duration); + } + context.wait_for_all_requests(); +} + + + +class GameLoadingDetector : public VisualInferenceCallback{ +public: + GameLoadingDetector(bool invert) + : VisualInferenceCallback("LoadingDetector") + , m_box0(0.2, 0.2, 0.6, 0.1) + , m_box1(0.2, 0.7, 0.6, 0.1) + , m_invert(invert) + {} + + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(COLOR_RED, m_box0); + items.add(COLOR_RED, m_box1); + } + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + if (!is_black(extract_box_reference(frame, m_box0))){ + return m_invert; + } + if (!is_black(extract_box_reference(frame, m_box1))){ + return m_invert; + } + return !m_invert; + } + +private: + ImageFloatBox m_box0; + ImageFloatBox m_box1; + bool m_invert; +}; + + +bool openedgame_to_gamemenu( + VideoStream& stream, ProControllerContext& context, + Milliseconds timeout +){ + { + stream.log("Waiting to load game..."); + GameLoadingDetector detector(false); + int ret = wait_until( + stream, context, + timeout, + {{detector}} + ); + if (ret < 0){ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } + } + { + stream.log("Waiting for game menu..."); + GameLoadingDetector detector(true); + int ret = wait_until( + stream, context, + timeout, + {{detector}} + ); + if (ret < 0){ + stream.log("Timed out waiting for game menu.", COLOR_RED); + return false; + } + } + return true; +} + + + + +void resume_game_from_home( + ConsoleHandle& console, JoyconContext& context, + bool skip_home_press +){ + if (!skip_home_press){ + pbf_press_button(context, BUTTON_HOME, 20ms, 10ms); + } + context.wait_for_all_requests(); + + while (true){ + { + UpdateMenuWatcher update_detector(console); + int ret = wait_until( + console, context, + std::chrono::milliseconds(1000), + { update_detector } + ); + if (ret == 0){ + console.log("Detected update window.", COLOR_RED); + + pbf_move_joystick(context, 128, 0, 10ms, 0ms); + pbf_press_button(context, BUTTON_A, 10ms, 500ms); + context.wait_for_all_requests(); + continue; + } + } + + // In case we failed to enter the game. + HomeMenuWatcher home_detector(console); + if (home_detector.detect(console.video().snapshot())){ + console.log("Failed to re-enter game. Trying again...", COLOR_RED); + pbf_press_button(context, BUTTON_HOME, 20ms, 10ms); + continue; + }else{ + break; + } + } +} +void move_to_user(JoyconContext& context, uint8_t user_slot){ + if (user_slot != 0){ + // Move to correct user. + for (uint8_t c = 0; c < 9; c++){ // Extra iteration in case one gets dropped. + pbf_move_joystick(context, 0, 128, 160ms, 160ms); + } + for (uint8_t c = 1; c < user_slot; c++){ + pbf_move_joystick(context, 0, 128, 160ms, 160ms); + } + } +} + +void start_game_from_home_with_inference( + ConsoleHandle& console, JoyconContext& context, + uint8_t game_slot, + uint8_t user_slot, + Milliseconds start_game_wait +){ + context.wait_for_all_requests(); + + if (!(context.controller().controller_type() == ControllerType::NintendoSwitch_RightJoycon)) { + console.log("Right Joycon required!", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "start_game_from_home_with_inference(): Right Joycon required.", + console + ); + } + + { + HomeMenuWatcher detector(console); + int ret = run_until( + console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_B, 10000ms); + }, + { detector } + ); + if (ret == 0){ + console.log("Detected Home screen."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "start_game_from_home_with_inference(): Failed to detect Home screen after 10 seconds.", + console + ); + } + context.wait_for(std::chrono::milliseconds(100)); + } + + if (game_slot != 0){ + ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); + for (uint8_t c = 1; c < game_slot; c++){ + pbf_move_joystick(context, 255, 128, 160ms, 0ms); + } + context.wait_for_all_requests(); + } + + pbf_press_button(context, BUTTON_A, 160ms, 840ms); + + while (true){ + HomeMenuWatcher home(console, std::chrono::milliseconds(2000)); + StartGameUserSelectWatcher user_select(console, COLOR_GREEN); + UpdateMenuWatcher update_menu(console, COLOR_PURPLE); + CheckOnlineWatcher check_online(COLOR_CYAN); + BlackScreenWatcher black_screen(COLOR_BLUE); + context.wait_for_all_requests(); + int ret = wait_until( + console, context, + std::chrono::seconds(30), + { + home, + user_select, + update_menu, + check_online, + black_screen, + } + ); + + // Wait for screen to stabilize. + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: + console.log("Detected home screen (again).", COLOR_RED); + pbf_press_button(context, BUTTON_A, 160ms, 840ms); + break; + case 1: + console.log("Detected user-select screen."); + move_to_user(context, user_slot); + pbf_press_button(context, BUTTON_A, 80ms, start_game_wait); + break; + case 2: + console.log("Detected update menu.", COLOR_RED); + pbf_move_joystick(context, 128, 0, 50ms, 0ms); + pbf_press_button(context, BUTTON_A, 160ms, 840ms); + break; + case 3: + console.log("Detected check online.", COLOR_RED); + context.wait_for(std::chrono::seconds(1)); + break; + case 4: + console.log("Detected black screen. Game started..."); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "start_game_from_home_with_inference(): No recognizable state after 30 seconds.", + console + ); + } + } +} + +bool openedgame_to_gamemenu( + VideoStream& stream, JoyconContext& context, + Milliseconds timeout +){ + { + stream.log("Waiting to load game..."); + GameLoadingDetector detector(false); + int ret = wait_until( + stream, context, + timeout, + {{detector}} + ); + if (ret < 0){ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } + } + { + stream.log("Waiting for game menu..."); + GameLoadingDetector detector(true); + int ret = wait_until( + stream, context, + timeout, + {{detector}} + ); + if (ret < 0){ + stream.log("Timed out waiting for game menu.", COLOR_RED); + return false; + } + } + return true; +} + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h index be8ad300ea..291db73542 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_GameEntry.h @@ -1,62 +1,62 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_GameEntry_H -#define PokemonAutomation_NintendoSwitch_GameEntry_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void wait_for_home(ConsoleHandle& console, ProControllerContext& context); - - - -void resume_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool skip_home_press = false -); - - -void start_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot, - uint8_t user_slot, - Milliseconds start_game_mash -); - -bool openedgame_to_gamemenu( - VideoStream& stream, ProControllerContext& context, - Milliseconds timeout -); - - -void resume_game_from_home( - ConsoleHandle& console, JoyconContext& context, - bool skip_home_press = false -); -void start_game_from_home_with_inference( - ConsoleHandle& console, JoyconContext& context, - uint8_t game_slot, - uint8_t user_slot, - Milliseconds start_game_mash -); - -bool openedgame_to_gamemenu( - VideoStream& stream, JoyconContext& context, - Milliseconds timeout -); - - -} -} -#endif +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_GameEntry_H +#define PokemonAutomation_NintendoSwitch_GameEntry_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void wait_for_home(ConsoleHandle& console, ProControllerContext& context); + + + +void resume_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool skip_home_press = false +); + + +void start_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot, + uint8_t user_slot, + Milliseconds start_game_mash +); + +bool openedgame_to_gamemenu( + VideoStream& stream, ProControllerContext& context, + Milliseconds timeout +); + + +void resume_game_from_home( + ConsoleHandle& console, JoyconContext& context, + bool skip_home_press = false +); +void start_game_from_home_with_inference( + ConsoleHandle& console, JoyconContext& context, + uint8_t game_slot, + uint8_t user_slot, + Milliseconds start_game_mash +); + +bool openedgame_to_gamemenu( + VideoStream& stream, JoyconContext& context, + Milliseconds timeout +); + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp index d73a88ec24..126b08c5b1 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.cpp @@ -1,177 +1,177 @@ -/* Friend Delete - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_MenuStabilityTester.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -MenuStabilityTester_Descriptor::MenuStabilityTester_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:MenuStabilityTester", - "Nintendo Switch", "Menu Stability Tester", - "", - "Test the speed and stability of various fast menu movements.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -MenuStabilityTester::~MenuStabilityTester(){ - TEST_TYPE.remove_listener(*this); -} -MenuStabilityTester::MenuStabilityTester() - : TEST_TYPE( - std::move("Console Type:"), - { - {TestType::Vertical, "vertical", "Vertical Up-Down"}, - {TestType::Horizontal, "horizontal", "Horizontal Side-to-Side"}, - {TestType::SimultaneousScrollA, "scroll-A", "Simultaneous Scroll + A"}, - }, - LockMode::LOCK_WHILE_RUNNING, - TestType::Vertical - ) - , VERTICAL_RANGE( - "Vertical Scroll Range:", - LockMode::LOCK_WHILE_RUNNING, - 20 - ) - , HORIZONTAL_RANGE( - "Horizontal Scroll Range:", - LockMode::LOCK_WHILE_RUNNING, - 4 - ) - , PAUSE_BEFORE_UTURN( - "Pause Before Turning Around:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , DELAY_TO_NEXT( - "Delay to Next Button:", - LockMode::LOCK_WHILE_RUNNING, - "24 ms" - ) - , HOLD_DURATION( - "Hold Duration:", - LockMode::LOCK_WHILE_RUNNING, - "48 ms" - ) - , COOLDOWN( - "Cooldown:", - LockMode::LOCK_WHILE_RUNNING, - "24 ms" - ) -{ - PA_ADD_OPTION(TEST_TYPE); - - PA_ADD_OPTION(VERTICAL_RANGE); - PA_ADD_OPTION(HORIZONTAL_RANGE); - PA_ADD_OPTION(PAUSE_BEFORE_UTURN); - - PA_ADD_OPTION(DELAY_TO_NEXT); - PA_ADD_OPTION(HOLD_DURATION); - PA_ADD_OPTION(COOLDOWN); - - MenuStabilityTester::on_config_value_changed(this); - - TEST_TYPE.add_listener(*this); -} -void MenuStabilityTester::on_config_value_changed(void* object){ - switch (TEST_TYPE){ - case TestType::Vertical: - VERTICAL_RANGE.set_visibility(ConfigOptionState::ENABLED); - HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); - break; - case TestType::Horizontal: - VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - HORIZONTAL_RANGE.set_visibility(ConfigOptionState::ENABLED); - PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); - break; - case TestType::SimultaneousScrollA: - VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); - PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::HIDDEN); - break; - } -} - - - - -void MenuStabilityTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - switch (TEST_TYPE){ - case TestType::Vertical: - while (true){ - for (size_t c = 0; c < VERTICAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_DOWN, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - for (size_t c = 0; c < VERTICAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - } - break; - - case TestType::Horizontal: - while (true){ - for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_RIGHT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ - ssf_issue_scroll(context, DPAD_LEFT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - } - if (PAUSE_BEFORE_UTURN){ - ssf_do_nothing(context, 1000ms); - } - } - break; - - case TestType::SimultaneousScrollA: - while (true){ - ssf_press_button(context, BUTTON_A, 0ms, HOLD_DURATION, COOLDOWN); - ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); - ssf_do_nothing(context, 1000ms); - } - break; - - } -} - - - - - - - - - - - - - - - - - - - - -} -} +/* Friend Delete + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_MenuStabilityTester.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +MenuStabilityTester_Descriptor::MenuStabilityTester_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:MenuStabilityTester", + "Nintendo Switch", "Menu Stability Tester", + "", + "Test the speed and stability of various fast menu movements.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +MenuStabilityTester::~MenuStabilityTester(){ + TEST_TYPE.remove_listener(*this); +} +MenuStabilityTester::MenuStabilityTester() + : TEST_TYPE( + std::move("Console Type:"), + { + {TestType::Vertical, "vertical", "Vertical Up-Down"}, + {TestType::Horizontal, "horizontal", "Horizontal Side-to-Side"}, + {TestType::SimultaneousScrollA, "scroll-A", "Simultaneous Scroll + A"}, + }, + LockMode::LOCK_WHILE_RUNNING, + TestType::Vertical + ) + , VERTICAL_RANGE( + "Vertical Scroll Range:", + LockMode::LOCK_WHILE_RUNNING, + 20 + ) + , HORIZONTAL_RANGE( + "Horizontal Scroll Range:", + LockMode::LOCK_WHILE_RUNNING, + 4 + ) + , PAUSE_BEFORE_UTURN( + "Pause Before Turning Around:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , DELAY_TO_NEXT( + "Delay to Next Button:", + LockMode::LOCK_WHILE_RUNNING, + "24 ms" + ) + , HOLD_DURATION( + "Hold Duration:", + LockMode::LOCK_WHILE_RUNNING, + "48 ms" + ) + , COOLDOWN( + "Cooldown:", + LockMode::LOCK_WHILE_RUNNING, + "24 ms" + ) +{ + PA_ADD_OPTION(TEST_TYPE); + + PA_ADD_OPTION(VERTICAL_RANGE); + PA_ADD_OPTION(HORIZONTAL_RANGE); + PA_ADD_OPTION(PAUSE_BEFORE_UTURN); + + PA_ADD_OPTION(DELAY_TO_NEXT); + PA_ADD_OPTION(HOLD_DURATION); + PA_ADD_OPTION(COOLDOWN); + + MenuStabilityTester::on_config_value_changed(this); + + TEST_TYPE.add_listener(*this); +} +void MenuStabilityTester::on_config_value_changed(void* object){ + switch (TEST_TYPE){ + case TestType::Vertical: + VERTICAL_RANGE.set_visibility(ConfigOptionState::ENABLED); + HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); + break; + case TestType::Horizontal: + VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + HORIZONTAL_RANGE.set_visibility(ConfigOptionState::ENABLED); + PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::ENABLED); + break; + case TestType::SimultaneousScrollA: + VERTICAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + HORIZONTAL_RANGE.set_visibility(ConfigOptionState::HIDDEN); + PAUSE_BEFORE_UTURN.set_visibility(ConfigOptionState::HIDDEN); + break; + } +} + + + + +void MenuStabilityTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + switch (TEST_TYPE){ + case TestType::Vertical: + while (true){ + for (size_t c = 0; c < VERTICAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_DOWN, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + for (size_t c = 0; c < VERTICAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + } + break; + + case TestType::Horizontal: + while (true){ + for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_RIGHT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + for (size_t c = 0; c < HORIZONTAL_RANGE; c++){ + ssf_issue_scroll(context, DPAD_LEFT, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + } + if (PAUSE_BEFORE_UTURN){ + ssf_do_nothing(context, 1000ms); + } + } + break; + + case TestType::SimultaneousScrollA: + while (true){ + ssf_press_button(context, BUTTON_A, 0ms, HOLD_DURATION, COOLDOWN); + ssf_issue_scroll(context, DPAD_UP, DELAY_TO_NEXT, HOLD_DURATION, COOLDOWN); + ssf_do_nothing(context, 1000ms); + } + break; + + } +} + + + + + + + + + + + + + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h index 32812cba04..29754710ff 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_MenuStabilityTester.h @@ -1,65 +1,65 @@ -/* Menu Stability Tester - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_MenuStabilityTester_H -#define PokemonAutomation_NintendoSwitch_MenuStabilityTester_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - - -class MenuStabilityTester_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MenuStabilityTester_Descriptor(); -}; - - - -class MenuStabilityTester : public SingleSwitchProgramInstance, private ConfigOption::Listener{ -public: - ~MenuStabilityTester(); - MenuStabilityTester(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - virtual void on_config_value_changed(void* object) override; - -private: - enum class TestType{ - Vertical, - Horizontal, - SimultaneousScrollA, - }; - - EnumDropdownOption TEST_TYPE; - SimpleIntegerOption VERTICAL_RANGE; - SimpleIntegerOption HORIZONTAL_RANGE; - BooleanCheckBoxOption PAUSE_BEFORE_UTURN; - - MillisecondsOption DELAY_TO_NEXT; - MillisecondsOption HOLD_DURATION; - MillisecondsOption COOLDOWN; - -}; - - - - -} -} -#endif - - - +/* Menu Stability Tester + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_MenuStabilityTester_H +#define PokemonAutomation_NintendoSwitch_MenuStabilityTester_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + + +class MenuStabilityTester_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MenuStabilityTester_Descriptor(); +}; + + + +class MenuStabilityTester : public SingleSwitchProgramInstance, private ConfigOption::Listener{ +public: + ~MenuStabilityTester(); + MenuStabilityTester(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + enum class TestType{ + Vertical, + Horizontal, + SimultaneousScrollA, + }; + + EnumDropdownOption TEST_TYPE; + SimpleIntegerOption VERTICAL_RANGE; + SimpleIntegerOption HORIZONTAL_RANGE; + BooleanCheckBoxOption PAUSE_BEFORE_UTURN; + + MillisecondsOption DELAY_TO_NEXT; + MillisecondsOption HOLD_DURATION; + MillisecondsOption COOLDOWN; + +}; + + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp index 9cddc3f3ef..21da209a6f 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.cpp @@ -1,39 +1,39 @@ -/* Prevent Sleep - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch_PreventSleep.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -PreventSleep_Descriptor::PreventSleep_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:PreventSleep", - "Nintendo Switch", "Prevent Sleep", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/PreventSleep.md", - "Press B every 15 seconds to keep the Switch from sleeping.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - - -PreventSleep::PreventSleep(){} - -void PreventSleep::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - while (true){ - ssf_press_button(context, BUTTON_B, 15000ms, 80ms); - } -} - - -} -} - +/* Prevent Sleep + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch_PreventSleep.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +PreventSleep_Descriptor::PreventSleep_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:PreventSleep", + "Nintendo Switch", "Prevent Sleep", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/PreventSleep.md", + "Press B every 15 seconds to keep the Switch from sleeping.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + + +PreventSleep::PreventSleep(){} + +void PreventSleep::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + while (true){ + ssf_press_button(context, BUTTON_B, 15000ms, 80ms); + } +} + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.h index 6b7405af10..17148fb27c 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PreventSleep.h @@ -1,38 +1,38 @@ -/* Prevent Sleep - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_PreventSleep_H -#define PokemonAutomation_NintendoSwitch_PreventSleep_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class PreventSleep_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PreventSleep_Descriptor(); -}; - - -class PreventSleep : public SingleSwitchProgramInstance{ -public: - PreventSleep(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -}; - - - -} -} -#endif - - - +/* Prevent Sleep + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_PreventSleep_H +#define PokemonAutomation_NintendoSwitch_PreventSleep_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class PreventSleep_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PreventSleep_Descriptor(); +}; + + +class PreventSleep : public SingleSwitchProgramInstance{ +public: + PreventSleep(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +}; + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.cpp index ffc25044ec..5110a2a45b 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.cpp @@ -1,74 +1,74 @@ -/* Turbo Button - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch_PushJoySticks.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -PushJoySticks_Descriptor::PushJoySticks_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:PushJoySticks", - "Nintendo Switch", "Push Joy Sticks", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/PushJoySticks.md", - "Push Joy Sticks continuously.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - -// x = 0 : left -// x = 128 : neutral -// x = 255 : right -// y = 0 : up -// y = 128 : neutral -// y = 255 : down - -PushJoySticks::PushJoySticks() - : LEFT_X( - "Left Joy Stick X direction:
Range: 0-255. 0: left, 128: neutral, 255: right.", - LockMode::LOCK_WHILE_RUNNING, - 128, 0, 255 - ) - , LEFT_Y( - "Left Joy Stick Y direction:
Range: 0-255. 0: up, 128: neutral, 255: down.", - LockMode::LOCK_WHILE_RUNNING, - 128, 0, 255 - ) - , RIGHT_X( - "Right Joy Stick X direction:
Range: 0-255. 0: left, 128: neutral, 255: right.", - LockMode::LOCK_WHILE_RUNNING, - 128, 0, 255 - ) - , RIGHT_Y( - "Right Joy Stick Y direction:
Range: 0-255. 0: up, 128: neutral, 255: down.", - LockMode::LOCK_WHILE_RUNNING, - 128, 0, 255 - ) -{ - PA_ADD_OPTION(LEFT_X); - PA_ADD_OPTION(LEFT_Y); - PA_ADD_OPTION(RIGHT_X); - PA_ADD_OPTION(RIGHT_Y); -} - -void PushJoySticks::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - while(true){ - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, - LEFT_X, LEFT_Y, RIGHT_X, RIGHT_Y, TICKS_PER_SECOND); - } -} - - - -} -} - +/* Turbo Button + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch_PushJoySticks.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +PushJoySticks_Descriptor::PushJoySticks_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:PushJoySticks", + "Nintendo Switch", "Push Joy Sticks", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/PushJoySticks.md", + "Push Joy Sticks continuously.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + +// x = 0 : left +// x = 128 : neutral +// x = 255 : right +// y = 0 : up +// y = 128 : neutral +// y = 255 : down + +PushJoySticks::PushJoySticks() + : LEFT_X( + "Left Joy Stick X direction:
Range: 0-255. 0: left, 128: neutral, 255: right.", + LockMode::LOCK_WHILE_RUNNING, + 128, 0, 255 + ) + , LEFT_Y( + "Left Joy Stick Y direction:
Range: 0-255. 0: up, 128: neutral, 255: down.", + LockMode::LOCK_WHILE_RUNNING, + 128, 0, 255 + ) + , RIGHT_X( + "Right Joy Stick X direction:
Range: 0-255. 0: left, 128: neutral, 255: right.", + LockMode::LOCK_WHILE_RUNNING, + 128, 0, 255 + ) + , RIGHT_Y( + "Right Joy Stick Y direction:
Range: 0-255. 0: up, 128: neutral, 255: down.", + LockMode::LOCK_WHILE_RUNNING, + 128, 0, 255 + ) +{ + PA_ADD_OPTION(LEFT_X); + PA_ADD_OPTION(LEFT_Y); + PA_ADD_OPTION(RIGHT_X); + PA_ADD_OPTION(RIGHT_Y); +} + +void PushJoySticks::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + while(true){ + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, + LEFT_X, LEFT_Y, RIGHT_X, RIGHT_Y, TICKS_PER_SECOND); + } +} + + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.h index 01f750ca45..63fa708eab 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_PushJoySticks.h @@ -1,41 +1,41 @@ -/* Push Joy Sticks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_PushJoySticks_H -#define PokemonAutomation_NintendoSwitch_PushJoySticks_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class PushJoySticks_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PushJoySticks_Descriptor(); -}; - - -class PushJoySticks : public SingleSwitchProgramInstance{ -public: - PushJoySticks(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption LEFT_X; - SimpleIntegerOption LEFT_Y; - SimpleIntegerOption RIGHT_X; - SimpleIntegerOption RIGHT_Y; -}; - - - -} -} -#endif - +/* Push Joy Sticks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_PushJoySticks_H +#define PokemonAutomation_NintendoSwitch_PushJoySticks_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class PushJoySticks_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PushJoySticks_Descriptor(); +}; + + +class PushJoySticks : public SingleSwitchProgramInstance{ +public: + PushJoySticks(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption LEFT_X; + SimpleIntegerOption LEFT_Y; + SimpleIntegerOption RIGHT_X; + SimpleIntegerOption RIGHT_Y; +}; + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.cpp index a9216cb197..a13ca7e817 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.cpp @@ -1,81 +1,81 @@ -/* Snapshot Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch_SnapshotDumper.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -SnapshotDumper_Descriptor::SnapshotDumper_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:SnapshotDumper", - "Nintendo Switch", "Snapshot Dumper", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/SnapshotDumper.md", - "Periodically take screenshots.", - FeedbackType::NONE, - AllowCommandsWhenRunning::ENABLE_COMMANDS, - {} - ) -{} - - - -SnapshotDumper::SnapshotDumper() - : PERIOD_MILLISECONDS( - "Snapshot Period (milliseconds):
Take screenshot every this many milliseconds.", - LockMode::UNLOCK_WHILE_RUNNING, - 1000 - ) - , FORMAT( - "Image Format:", - { - {Format::PNG, "png", ".png"}, - {Format::JPG, "jpg", ".jpg"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - Format::JPG - ) -{ - PA_ADD_OPTION(PERIOD_MILLISECONDS); - PA_ADD_OPTION(FORMAT); -} - -void SnapshotDumper::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - std::string folder_path = USER_FILE_PATH() + "ScreenshotDumper/"; - QDir().mkpath(folder_path.c_str()); - while (true){ - VideoSnapshot last = env.console.video().snapshot(); - std::string filename = folder_path + now_to_filestring(); - switch (FORMAT){ - case Format::PNG: - filename += ".png"; - break; - case Format::JPG: - filename += ".jpg"; - break; - } - last->save(filename); - context.wait_until(last.timestamp + std::chrono::milliseconds(PERIOD_MILLISECONDS)); - } -} - -void dump_snapshot(VideoStream& stream, std::string folder_name){ - std::string folder_path = USER_FILE_PATH() + folder_name + "/"; - QDir().mkpath(folder_path.c_str()); - VideoSnapshot last = stream.video().snapshot(); - std::string filename = folder_path + now_to_filestring() + ".png"; - last->save(filename); -} - - -} -} - +/* Snapshot Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch_SnapshotDumper.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +SnapshotDumper_Descriptor::SnapshotDumper_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:SnapshotDumper", + "Nintendo Switch", "Snapshot Dumper", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/SnapshotDumper.md", + "Periodically take screenshots.", + FeedbackType::NONE, + AllowCommandsWhenRunning::ENABLE_COMMANDS, + {} + ) +{} + + + +SnapshotDumper::SnapshotDumper() + : PERIOD_MILLISECONDS( + "Snapshot Period (milliseconds):
Take screenshot every this many milliseconds.", + LockMode::UNLOCK_WHILE_RUNNING, + 1000 + ) + , FORMAT( + "Image Format:", + { + {Format::PNG, "png", ".png"}, + {Format::JPG, "jpg", ".jpg"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + Format::JPG + ) +{ + PA_ADD_OPTION(PERIOD_MILLISECONDS); + PA_ADD_OPTION(FORMAT); +} + +void SnapshotDumper::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + std::string folder_path = USER_FILE_PATH() + "ScreenshotDumper/"; + QDir().mkpath(folder_path.c_str()); + while (true){ + VideoSnapshot last = env.console.video().snapshot(); + std::string filename = folder_path + now_to_filestring(); + switch (FORMAT){ + case Format::PNG: + filename += ".png"; + break; + case Format::JPG: + filename += ".jpg"; + break; + } + last->save(filename); + context.wait_until(last.timestamp + std::chrono::milliseconds(PERIOD_MILLISECONDS)); + } +} + +void dump_snapshot(VideoStream& stream, std::string folder_name){ + std::string folder_path = USER_FILE_PATH() + folder_name + "/"; + QDir().mkpath(folder_path.c_str()); + VideoSnapshot last = stream.video().snapshot(); + std::string filename = folder_path + now_to_filestring() + ".png"; + last->save(filename); +} + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.h index d2c4330ce1..14a9547a39 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SnapshotDumper.h @@ -1,48 +1,48 @@ -/* Snapshot Dumper - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SnapshotDumper_H -#define PokemonAutomation_NintendoSwitch_SnapshotDumper_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SnapshotDumper_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SnapshotDumper_Descriptor(); -}; - - -class SnapshotDumper : public SingleSwitchProgramInstance{ -public: - SnapshotDumper(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption PERIOD_MILLISECONDS; - - enum class Format{ - PNG, - JPG, - }; - EnumDropdownOption FORMAT; -}; - -// takes a snapshot of the screen and saves it to the given folder_name -void dump_snapshot(VideoStream& stream, std::string folder_name = "ScreenshotDumper"); - -} -} -#endif - - - +/* Snapshot Dumper + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SnapshotDumper_H +#define PokemonAutomation_NintendoSwitch_SnapshotDumper_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SnapshotDumper_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SnapshotDumper_Descriptor(); +}; + + +class SnapshotDumper : public SingleSwitchProgramInstance{ +public: + SnapshotDumper(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption PERIOD_MILLISECONDS; + + enum class Format{ + PNG, + JPG, + }; + EnumDropdownOption FORMAT; +}; + +// takes a snapshot of the screen and saves it to the given folder_name +void dump_snapshot(VideoStream& stream, std::string folder_name = "ScreenshotDumper"); + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.cpp index aaecf2d0df..4bfa65c0bd 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.cpp @@ -1,98 +1,98 @@ -/* Multi-Video Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/CollapsibleGroupBox.h" -#include "NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h" -#include "NintendoSwitch_SwitchViewer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -SwitchViewer_Descriptor::SwitchViewer_Descriptor() - : PanelDescriptor( - Color(), - "NintendoSwitch:SwitchViewer", - "Nintendo Switch", "Switch Viewer", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/SwitchViewer.md", - "View status information from one or more running programs." - ) -{} - - - -SwitchViewer::SwitchViewer(const SwitchViewer_Descriptor& descriptor) - : PanelInstance(descriptor) - , m_switches( - {}, - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - 1, 4, 1 - ) -{} -void SwitchViewer::from_json(const JsonValue& json){ - m_switches.load_json(json); -} -JsonValue SwitchViewer::to_json() const{ - return m_switches.to_json(); -} -QWidget* SwitchViewer::make_widget(QWidget& parent, PanelHolder& holder){ - return SwitchViewer_Widget::make(parent, *this, holder); -} - - - -SwitchViewer_Widget* SwitchViewer_Widget::make( - QWidget& parent, - SwitchViewer& instance, - PanelHolder& holder -){ - SwitchViewer_Widget* widget = new SwitchViewer_Widget(parent, instance, holder); - widget->construct(); - return widget; -} -SwitchViewer_Widget::~SwitchViewer_Widget(){ - delete m_switches; -} -SwitchViewer_Widget::SwitchViewer_Widget( - QWidget& parent, - SwitchViewer& instance, - PanelHolder& holder -) - : PanelWidget(parent, instance, holder) - , m_session(instance.m_switches, 0) -{} -void SwitchViewer_Widget::construct(){ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(make_header(*this)); - - QScrollArea* scroll_outer = new QScrollArea(this); - layout->addWidget(scroll_outer); - scroll_outer->setWidgetResizable(true); - - QWidget* scroll_inner = new QWidget(scroll_outer); - scroll_outer->setWidget(scroll_inner); - QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); - scroll_layout->setAlignment(Qt::AlignTop); - - m_switches = new MultiSwitchSystemWidget(*this, m_session, 0); - scroll_layout->addWidget(m_switches); - scroll_layout->addStretch(1); -} - - - - - - - - -} -} +/* Multi-Video Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/CollapsibleGroupBox.h" +#include "NintendoSwitch/Framework/UI/NintendoSwitch_MultiSwitchSystemWidget.h" +#include "NintendoSwitch_SwitchViewer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +SwitchViewer_Descriptor::SwitchViewer_Descriptor() + : PanelDescriptor( + Color(), + "NintendoSwitch:SwitchViewer", + "Nintendo Switch", "Switch Viewer", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/SwitchViewer.md", + "View status information from one or more running programs." + ) +{} + + + +SwitchViewer::SwitchViewer(const SwitchViewer_Descriptor& descriptor) + : PanelInstance(descriptor) + , m_switches( + {}, + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + 1, 4, 1 + ) +{} +void SwitchViewer::from_json(const JsonValue& json){ + m_switches.load_json(json); +} +JsonValue SwitchViewer::to_json() const{ + return m_switches.to_json(); +} +QWidget* SwitchViewer::make_widget(QWidget& parent, PanelHolder& holder){ + return SwitchViewer_Widget::make(parent, *this, holder); +} + + + +SwitchViewer_Widget* SwitchViewer_Widget::make( + QWidget& parent, + SwitchViewer& instance, + PanelHolder& holder +){ + SwitchViewer_Widget* widget = new SwitchViewer_Widget(parent, instance, holder); + widget->construct(); + return widget; +} +SwitchViewer_Widget::~SwitchViewer_Widget(){ + delete m_switches; +} +SwitchViewer_Widget::SwitchViewer_Widget( + QWidget& parent, + SwitchViewer& instance, + PanelHolder& holder +) + : PanelWidget(parent, instance, holder) + , m_session(instance.m_switches, 0) +{} +void SwitchViewer_Widget::construct(){ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(make_header(*this)); + + QScrollArea* scroll_outer = new QScrollArea(this); + layout->addWidget(scroll_outer); + scroll_outer->setWidgetResizable(true); + + QWidget* scroll_inner = new QWidget(scroll_outer); + scroll_outer->setWidget(scroll_inner); + QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); + scroll_layout->setAlignment(Qt::AlignTop); + + m_switches = new MultiSwitchSystemWidget(*this, m_session, 0); + scroll_layout->addWidget(m_switches); + scroll_layout->addStretch(1); +} + + + + + + + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.h index 989ce26475..a6299c5e27 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_SwitchViewer.h @@ -1,72 +1,72 @@ -/* Multi-Video Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_SwitchViewer_H -#define PokemonAutomation_NintendoSwitch_SwitchViewer_H - -#include "CommonFramework/Panels/PanelInstance.h" -#include "CommonFramework/Panels/UI/PanelWidget.h" -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h" -#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class SwitchViewer_Descriptor : public PanelDescriptor{ -public: - SwitchViewer_Descriptor(); -}; - - - -class SwitchViewer : public PanelInstance{ -public: - SwitchViewer(const SwitchViewer_Descriptor& descriptor); - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -public: - // Serialization - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -private: - friend class SwitchViewer_Widget; - - MultiSwitchSystemOption m_switches; -}; - - - -class SwitchViewer_Widget : public PanelWidget{ -public: - static SwitchViewer_Widget* make( - QWidget& parent, - SwitchViewer& instance, - PanelHolder& holder - ); - -private: - ~SwitchViewer_Widget(); - SwitchViewer_Widget( - QWidget& parent, - SwitchViewer& instance, - PanelHolder& holder - ); - void construct(); - -private: - MultiSwitchSystemSession m_session; - MultiSwitchSystemWidget* m_switches; -}; - - - - - -} -} -#endif +/* Multi-Video Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_SwitchViewer_H +#define PokemonAutomation_NintendoSwitch_SwitchViewer_H + +#include "CommonFramework/Panels/PanelInstance.h" +#include "CommonFramework/Panels/UI/PanelWidget.h" +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemOption.h" +#include "NintendoSwitch/Framework/NintendoSwitch_MultiSwitchSystemSession.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class SwitchViewer_Descriptor : public PanelDescriptor{ +public: + SwitchViewer_Descriptor(); +}; + + + +class SwitchViewer : public PanelInstance{ +public: + SwitchViewer(const SwitchViewer_Descriptor& descriptor); + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +public: + // Serialization + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +private: + friend class SwitchViewer_Widget; + + MultiSwitchSystemOption m_switches; +}; + + + +class SwitchViewer_Widget : public PanelWidget{ +public: + static SwitchViewer_Widget* make( + QWidget& parent, + SwitchViewer& instance, + PanelHolder& holder + ); + +private: + ~SwitchViewer_Widget(); + SwitchViewer_Widget( + QWidget& parent, + SwitchViewer& instance, + PanelHolder& holder + ); + void construct(); + +private: + MultiSwitchSystemSession m_session; + MultiSwitchSystemWidget* m_switches; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.cpp index 3141738b1a..8d35ee1840 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.cpp @@ -1,50 +1,50 @@ -/* Turbo A - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "NintendoSwitch_TurboA.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -TurboA_Descriptor::TurboA_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:TurboA", - "Nintendo Switch", "Turbo A", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/TurboA.md", - "Endlessly mash A.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - - -TurboA::TurboA(){ - PA_ADD_OPTION(START_LOCATION); -} -void TurboA::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - PokemonSwSh::resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - } - - while (true){ - ssf_mash1_button(context, BUTTON_A, 10000ms); - } -} - - - - -} -} - +/* Turbo A + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "NintendoSwitch_TurboA.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +TurboA_Descriptor::TurboA_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:TurboA", + "Nintendo Switch", "Turbo A", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/TurboA.md", + "Endlessly mash A.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + + +TurboA::TurboA(){ + PA_ADD_OPTION(START_LOCATION); +} +void TurboA::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + PokemonSwSh::resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + } + + while (true){ + ssf_mash1_button(context, BUTTON_A, 10000ms); + } +} + + + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.h index 6a811176d8..de6bc3eb95 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboA.h @@ -1,42 +1,42 @@ -/* Turbo A - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_TurboA_H -#define PokemonAutomation_NintendoSwitch_TurboA_H - -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class TurboA_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TurboA_Descriptor(); -}; - - - -class TurboA : public SingleSwitchProgramInstance{ -public: - TurboA(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; -}; - - - - -} -} -#endif - - - +/* Turbo A + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_TurboA_H +#define PokemonAutomation_NintendoSwitch_TurboA_H + +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class TurboA_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TurboA_Descriptor(); +}; + + + +class TurboA : public SingleSwitchProgramInstance{ +public: + TurboA(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; +}; + + + + +} +} +#endif + + + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.cpp index 74925d77dc..bc81c9cb6b 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.cpp @@ -1,99 +1,99 @@ -/* Turbo Button - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch_TurboButton.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - - -TurboButton_Descriptor::TurboButton_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:TurboButton", - "Nintendo Switch", "Turbo Button", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/TurboButton.md", - "Mash a controller button. (similar to turbo controller)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - - -TurboButton::TurboButton() - : BUTTON( - "Button to Mash:", - { - {BUTTON_Y, "Y", "Y"}, - {BUTTON_B, "B", "B"}, - {BUTTON_A, "A", "A"}, - {BUTTON_X, "X", "X"}, - {BUTTON_L, "L", "L"}, - {BUTTON_R, "R", "R"}, - {BUTTON_ZL, "ZL", "ZL"}, - {BUTTON_ZR, "ZR", "ZR"}, - {BUTTON_MINUS, "MINUS", "Minus (-)"}, - {BUTTON_PLUS, "PLUS", "Plus (+)"}, - {BUTTON_LCLICK, "LCLICK", "L-Click (left joystick click)"}, - {BUTTON_RCLICK, "RCLICK", "R-Click (right joystick click)"}, - {BUTTON_HOME, "HOME", "Home"}, - {BUTTON_CAPTURE, "CAPTURE", "Capture"}, - }, - LockMode::LOCK_WHILE_RUNNING, - BUTTON_A - ) - , PRESS_DURATION0( - "Press Duration:
Hold the button down for this long.", - LockMode::LOCK_WHILE_RUNNING, - "40 ms" - ) - , RELEASE_DURATION0( - "Release Duration:
After releasing the button, wait this long before pressing it again.", - LockMode::LOCK_WHILE_RUNNING, - "24 ms" - ) - , TOTAL_PRESSES( - "Total Presses:
Stop the program after this many presses. If zero, run forever.", - LockMode::LOCK_WHILE_RUNNING, - 0 - ) -{ - PA_ADD_OPTION(BUTTON); - PA_ADD_OPTION(PRESS_DURATION0); - PA_ADD_OPTION(RELEASE_DURATION0); - PA_ADD_OPTION(TOTAL_PRESSES); -} -void TurboButton::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (TOTAL_PRESSES == 0){ - while (true){ - pbf_press_button( - context, - (Button)BUTTON.current_value(), - PRESS_DURATION0, - RELEASE_DURATION0 - ); - } - }else{ - for (uint64_t c = 0; c < TOTAL_PRESSES; c++){ - pbf_press_button( - context, - (Button)BUTTON.current_value(), - PRESS_DURATION0, - RELEASE_DURATION0 - ); - } - } - context.wait_for_all_requests(); -} - - - -} -} - +/* Turbo Button + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch_TurboButton.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + + +TurboButton_Descriptor::TurboButton_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:TurboButton", + "Nintendo Switch", "Turbo Button", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/TurboButton.md", + "Mash a controller button. (similar to turbo controller)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + + +TurboButton::TurboButton() + : BUTTON( + "Button to Mash:", + { + {BUTTON_Y, "Y", "Y"}, + {BUTTON_B, "B", "B"}, + {BUTTON_A, "A", "A"}, + {BUTTON_X, "X", "X"}, + {BUTTON_L, "L", "L"}, + {BUTTON_R, "R", "R"}, + {BUTTON_ZL, "ZL", "ZL"}, + {BUTTON_ZR, "ZR", "ZR"}, + {BUTTON_MINUS, "MINUS", "Minus (-)"}, + {BUTTON_PLUS, "PLUS", "Plus (+)"}, + {BUTTON_LCLICK, "LCLICK", "L-Click (left joystick click)"}, + {BUTTON_RCLICK, "RCLICK", "R-Click (right joystick click)"}, + {BUTTON_HOME, "HOME", "Home"}, + {BUTTON_CAPTURE, "CAPTURE", "Capture"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BUTTON_A + ) + , PRESS_DURATION0( + "Press Duration:
Hold the button down for this long.", + LockMode::LOCK_WHILE_RUNNING, + "40 ms" + ) + , RELEASE_DURATION0( + "Release Duration:
After releasing the button, wait this long before pressing it again.", + LockMode::LOCK_WHILE_RUNNING, + "24 ms" + ) + , TOTAL_PRESSES( + "Total Presses:
Stop the program after this many presses. If zero, run forever.", + LockMode::LOCK_WHILE_RUNNING, + 0 + ) +{ + PA_ADD_OPTION(BUTTON); + PA_ADD_OPTION(PRESS_DURATION0); + PA_ADD_OPTION(RELEASE_DURATION0); + PA_ADD_OPTION(TOTAL_PRESSES); +} +void TurboButton::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (TOTAL_PRESSES == 0){ + while (true){ + pbf_press_button( + context, + (Button)BUTTON.current_value(), + PRESS_DURATION0, + RELEASE_DURATION0 + ); + } + }else{ + for (uint64_t c = 0; c < TOTAL_PRESSES; c++){ + pbf_press_button( + context, + (Button)BUTTON.current_value(), + PRESS_DURATION0, + RELEASE_DURATION0 + ); + } + } + context.wait_for_all_requests(); +} + + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.h index f2faa86813..56594b23c0 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboButton.h @@ -1,43 +1,43 @@ -/* Turbo Button - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_TurboButton_H -#define PokemonAutomation_NintendoSwitch_TurboButton_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class TurboButton_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TurboButton_Descriptor(); -}; - - -class TurboButton : public SingleSwitchProgramInstance{ -public: - TurboButton(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - IntegerEnumDropdownOption BUTTON; - MillisecondsOption PRESS_DURATION0; - MillisecondsOption RELEASE_DURATION0; - SimpleIntegerOption TOTAL_PRESSES; -}; - - - -} -} -#endif - +/* Turbo Button + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_TurboButton_H +#define PokemonAutomation_NintendoSwitch_TurboButton_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class TurboButton_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TurboButton_Descriptor(); +}; + + +class TurboButton : public SingleSwitchProgramInstance{ +public: + TurboButton(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + IntegerEnumDropdownOption BUTTON; + MillisecondsOption PRESS_DURATION0; + MillisecondsOption RELEASE_DURATION0; + SimpleIntegerOption TOTAL_PRESSES; +}; + + + +} +} +#endif + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.cpp index b65a56a053..5d2a8c8689 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.cpp @@ -1,129 +1,129 @@ -/* Turbo Macro - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Options/TurboMacroTable.h" -#include "NintendoSwitch_TurboMacro.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -TurboMacro_Descriptor::TurboMacro_Descriptor() - : SingleSwitchProgramDescriptor( - "NintendoSwitch:TurboMacro", - "Nintendo Switch", "Turbo Macro", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/TurboMacro.md", - "Create macros", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -TurboMacro::TurboMacro() - : LOOP( - "Number of times to loop:", - LockMode::UNLOCK_WHILE_RUNNING, - 100, 0 - ) -{ - PA_ADD_OPTION(LOOP); - PA_ADD_OPTION(MACRO); -} - -void TurboMacro::run_macro(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - std::vector> table = MACRO.copy_snapshot(); - for (const std::unique_ptr& row : table){ - execute_action(env.console, context, *row); - } -} - -void TurboMacro::execute_action( - VideoStream& stream, ProControllerContext& context, - const TurboMacroRow& row -){ - stream.log("Execute action " + row.action.current_display()); - const TurboMacroCell& cell = row.parameters; - switch(row.action){ - case TurboMacroAction::LEFT_JOYSTICK: - pbf_move_left_joystick(context, cell.x_axis, cell.y_axis, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::RIGHT_JOYSTICK: - pbf_move_right_joystick(context, cell.x_axis, cell.y_axis, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::LEFT_JOY_CLICK: - pbf_press_button(context, BUTTON_LCLICK, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::RIGHT_JOY_CLICK: - pbf_press_button(context, BUTTON_RCLICK, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::B: - pbf_press_button(context, BUTTON_B, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::A: - pbf_press_button(context, BUTTON_A, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::Y: - pbf_press_button(context, BUTTON_Y, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::X: - pbf_press_button(context, BUTTON_X, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::R: - pbf_press_button(context, BUTTON_R, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::L: - pbf_press_button(context, BUTTON_L, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::ZR: - pbf_press_button(context, BUTTON_ZR,cell.button_hold, cell.button_release); - break; - case TurboMacroAction::ZL: - pbf_press_button(context, BUTTON_ZL, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::PLUS: - pbf_press_button(context, BUTTON_PLUS, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::MINUS: - pbf_press_button(context, BUTTON_MINUS, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::DPADLEFT: - pbf_press_dpad(context, DPAD_LEFT, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::DPADRIGHT: - pbf_press_dpad(context, DPAD_RIGHT, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::DPADUP: - pbf_press_dpad(context, DPAD_UP, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::DPADDOWN: - pbf_press_dpad(context, DPAD_DOWN, cell.button_hold, cell.button_release); - break; - case TurboMacroAction::WAIT: - pbf_wait(context, cell.wait); - default: - break; - } -} - -void TurboMacro::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - // Connect the controller. - //pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - for (uint32_t c = 0; c < LOOP; c++){ - run_macro(env, context); - } -} - - -} -} +/* Turbo Macro + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Options/TurboMacroTable.h" +#include "NintendoSwitch_TurboMacro.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +TurboMacro_Descriptor::TurboMacro_Descriptor() + : SingleSwitchProgramDescriptor( + "NintendoSwitch:TurboMacro", + "Nintendo Switch", "Turbo Macro", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/TurboMacro.md", + "Create macros", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +TurboMacro::TurboMacro() + : LOOP( + "Number of times to loop:", + LockMode::UNLOCK_WHILE_RUNNING, + 100, 0 + ) +{ + PA_ADD_OPTION(LOOP); + PA_ADD_OPTION(MACRO); +} + +void TurboMacro::run_macro(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + std::vector> table = MACRO.copy_snapshot(); + for (const std::unique_ptr& row : table){ + execute_action(env.console, context, *row); + } +} + +void TurboMacro::execute_action( + VideoStream& stream, ProControllerContext& context, + const TurboMacroRow& row +){ + stream.log("Execute action " + row.action.current_display()); + const TurboMacroCell& cell = row.parameters; + switch(row.action){ + case TurboMacroAction::LEFT_JOYSTICK: + pbf_move_left_joystick(context, cell.x_axis, cell.y_axis, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::RIGHT_JOYSTICK: + pbf_move_right_joystick(context, cell.x_axis, cell.y_axis, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::LEFT_JOY_CLICK: + pbf_press_button(context, BUTTON_LCLICK, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::RIGHT_JOY_CLICK: + pbf_press_button(context, BUTTON_RCLICK, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::B: + pbf_press_button(context, BUTTON_B, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::A: + pbf_press_button(context, BUTTON_A, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::Y: + pbf_press_button(context, BUTTON_Y, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::X: + pbf_press_button(context, BUTTON_X, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::R: + pbf_press_button(context, BUTTON_R, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::L: + pbf_press_button(context, BUTTON_L, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::ZR: + pbf_press_button(context, BUTTON_ZR,cell.button_hold, cell.button_release); + break; + case TurboMacroAction::ZL: + pbf_press_button(context, BUTTON_ZL, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::PLUS: + pbf_press_button(context, BUTTON_PLUS, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::MINUS: + pbf_press_button(context, BUTTON_MINUS, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::DPADLEFT: + pbf_press_dpad(context, DPAD_LEFT, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::DPADRIGHT: + pbf_press_dpad(context, DPAD_RIGHT, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::DPADUP: + pbf_press_dpad(context, DPAD_UP, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::DPADDOWN: + pbf_press_dpad(context, DPAD_DOWN, cell.button_hold, cell.button_release); + break; + case TurboMacroAction::WAIT: + pbf_wait(context, cell.wait); + default: + break; + } +} + +void TurboMacro::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + // Connect the controller. + //pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + for (uint32_t c = 0; c < LOOP; c++){ + run_macro(env, context); + } +} + + +} +} diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.h index 74a086de5b..0851be594d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_TurboMacro.h @@ -1,46 +1,46 @@ -/* Turbo Macro - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_TurboMacro_H -#define PokemonAutomation_NintendoSwitch_TurboMacro_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/Options/TurboMacroTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -class TurboMacro_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TurboMacro_Descriptor(); -}; - - -class TurboMacro : public SingleSwitchProgramInstance{ -public: - TurboMacro(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_macro(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void execute_action( - VideoStream& stream, ProControllerContext& context, - const TurboMacroRow& row - ); - -private: - SimpleIntegerOption LOOP; - TurboMacroTable MACRO; -}; - - - -} -} -#endif // PokemonAutomation_NintendoSwitch_TurboMacro_H +/* Turbo Macro + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_TurboMacro_H +#define PokemonAutomation_NintendoSwitch_TurboMacro_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/Options/TurboMacroTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +class TurboMacro_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TurboMacro_Descriptor(); +}; + + +class TurboMacro : public SingleSwitchProgramInstance{ +public: + TurboMacro(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_macro(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void execute_action( + VideoStream& stream, ProControllerContext& context, + const TurboMacroRow& row + ); + +private: + SimpleIntegerOption LOOP; + TurboMacroTable MACRO; +}; + + + +} +} +#endif // PokemonAutomation_NintendoSwitch_TurboMacro_H diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.cpp b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.cpp index 20f4811fc9..6c659578ff 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.cpp +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.cpp @@ -1,90 +1,90 @@ -/* Virtual Game Console - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Qt/CollapsibleGroupBox.h" -#include "NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h" -#include "NintendoSwitch_VirtualConsole.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -VirtualConsole_Descriptor::VirtualConsole_Descriptor() - : PanelDescriptor( - Color(), - "NintendoSwitch:VirtualConsole", - "Nintendo Switch", "Virtual Console", - "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/VirtualConsole.md", - "Play your Switch from your computer. Device logging is logged to the output window." - ) -{} - - - -VirtualConsole::VirtualConsole(const VirtualConsole_Descriptor& descriptor) - : PanelInstance(descriptor) - , m_switch_control_option({}, false) -{} -void VirtualConsole::from_json(const JsonValue& json){ - m_switch_control_option.load_json(json); -} -JsonValue VirtualConsole::to_json() const{ - return m_switch_control_option.to_json(); -} -QWidget* VirtualConsole::make_widget(QWidget& parent, PanelHolder& holder){ - return VirtualConsole_Widget::make(parent, *this, holder); -} - - - -VirtualConsole_Widget* VirtualConsole_Widget::make( - QWidget& parent, - VirtualConsole& instance, - PanelHolder& holder -){ - VirtualConsole_Widget* widget = new VirtualConsole_Widget(parent, instance, holder); - widget->construct(); - return widget; -} -VirtualConsole_Widget::~VirtualConsole_Widget(){ - delete m_switch_widget; -} -VirtualConsole_Widget::VirtualConsole_Widget( - QWidget& parent, - VirtualConsole& instance, - PanelHolder& holder -) - : PanelWidget(parent, instance, holder) - , m_session(instance.m_switch_control_option, 0, 0) -{} -void VirtualConsole_Widget::construct(){ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(make_header(*this)); - - QScrollArea* scroll_outer = new QScrollArea(this); - layout->addWidget(scroll_outer); - scroll_outer->setWidgetResizable(true); - - QWidget* scroll_inner = new QWidget(scroll_outer); - scroll_outer->setWidget(scroll_inner); - QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); - scroll_layout->setAlignment(Qt::AlignTop); - - m_switch_widget = new SwitchSystemWidget(*this, m_session, 0); - scroll_layout->addWidget(m_switch_widget); -} - - - - - - -} -} - +/* Virtual Game Console + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Qt/CollapsibleGroupBox.h" +#include "NintendoSwitch/Framework/UI/NintendoSwitch_SwitchSystemWidget.h" +#include "NintendoSwitch_VirtualConsole.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +VirtualConsole_Descriptor::VirtualConsole_Descriptor() + : PanelDescriptor( + Color(), + "NintendoSwitch:VirtualConsole", + "Nintendo Switch", "Virtual Console", + "ComputerControl/blob/master/Wiki/Programs/NintendoSwitch/VirtualConsole.md", + "Play your Switch from your computer. Device logging is logged to the output window." + ) +{} + + + +VirtualConsole::VirtualConsole(const VirtualConsole_Descriptor& descriptor) + : PanelInstance(descriptor) + , m_switch_control_option({}, false) +{} +void VirtualConsole::from_json(const JsonValue& json){ + m_switch_control_option.load_json(json); +} +JsonValue VirtualConsole::to_json() const{ + return m_switch_control_option.to_json(); +} +QWidget* VirtualConsole::make_widget(QWidget& parent, PanelHolder& holder){ + return VirtualConsole_Widget::make(parent, *this, holder); +} + + + +VirtualConsole_Widget* VirtualConsole_Widget::make( + QWidget& parent, + VirtualConsole& instance, + PanelHolder& holder +){ + VirtualConsole_Widget* widget = new VirtualConsole_Widget(parent, instance, holder); + widget->construct(); + return widget; +} +VirtualConsole_Widget::~VirtualConsole_Widget(){ + delete m_switch_widget; +} +VirtualConsole_Widget::VirtualConsole_Widget( + QWidget& parent, + VirtualConsole& instance, + PanelHolder& holder +) + : PanelWidget(parent, instance, holder) + , m_session(instance.m_switch_control_option, 0, 0) +{} +void VirtualConsole_Widget::construct(){ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(make_header(*this)); + + QScrollArea* scroll_outer = new QScrollArea(this); + layout->addWidget(scroll_outer); + scroll_outer->setWidgetResizable(true); + + QWidget* scroll_inner = new QWidget(scroll_outer); + scroll_outer->setWidget(scroll_inner); + QVBoxLayout* scroll_layout = new QVBoxLayout(scroll_inner); + scroll_layout->setAlignment(Qt::AlignTop); + + m_switch_widget = new SwitchSystemWidget(*this, m_session, 0); + scroll_layout->addWidget(m_switch_widget); +} + + + + + + +} +} + diff --git a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.h b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.h index 530ff96f68..16f2bd8e5d 100644 --- a/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.h +++ b/SerialPrograms/Source/NintendoSwitch/Programs/NintendoSwitch_VirtualConsole.h @@ -1,84 +1,84 @@ -/* Virtual Game Console - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_NintendoSwitch_VirtualConsole_H -#define PokemonAutomation_NintendoSwitch_VirtualConsole_H - -#include "CommonFramework/Panels/PanelInstance.h" -#include "CommonFramework/Panels/UI/PanelWidget.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h" -#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class SwitchSystemWidget; - - -// Descriptor for the program "Virtual Console". -// It defines basic info such as title name and color of the program on the program list panel. -// It inherits abstract base class PanelDescriptor but is still an abstract class as it does -// not define `make_panel()`, which functionality is simply to instantiate the PanelInstance, the -// program panel. -// Call CommonFramework/Panels/PanelTools.h:make_panel() -// to create a wrapper class that implements `make_panel()` to instantiate the descriptor. -class VirtualConsole_Descriptor : public PanelDescriptor{ -public: - VirtualConsole_Descriptor(); -}; - - -// The program panel of Virtual Console. -// It calls make_widget() to create a VirtualConsole_Widget that holds the UI wideget. -class VirtualConsole : public PanelInstance{ -public: - VirtualConsole(const VirtualConsole_Descriptor& descriptor); - virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; - -public: - // Serialization - virtual void from_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -private: - friend class VirtualConsole_Widget; - // switch control options like what micro-controller - // and what video source to use - SwitchSystemOption m_switch_control_option; -}; - - -// The UI of the prgoram Virtual Console -class VirtualConsole_Widget : public PanelWidget{ -public: - static VirtualConsole_Widget* make( - QWidget& parent, - VirtualConsole& instance, - PanelHolder& holder - ); - -private: - ~VirtualConsole_Widget(); - VirtualConsole_Widget( - QWidget& parent, - VirtualConsole& instance, - PanelHolder& holder - ); - void construct(); - -private: - SwitchSystemSession m_session; - SwitchSystemWidget* m_switch_widget; -}; - - - - - -} -} -#endif - +/* Virtual Game Console + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_NintendoSwitch_VirtualConsole_H +#define PokemonAutomation_NintendoSwitch_VirtualConsole_H + +#include "CommonFramework/Panels/PanelInstance.h" +#include "CommonFramework/Panels/UI/PanelWidget.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemOption.h" +#include "NintendoSwitch/Framework/NintendoSwitch_SwitchSystemSession.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class SwitchSystemWidget; + + +// Descriptor for the program "Virtual Console". +// It defines basic info such as title name and color of the program on the program list panel. +// It inherits abstract base class PanelDescriptor but is still an abstract class as it does +// not define `make_panel()`, which functionality is simply to instantiate the PanelInstance, the +// program panel. +// Call CommonFramework/Panels/PanelTools.h:make_panel() +// to create a wrapper class that implements `make_panel()` to instantiate the descriptor. +class VirtualConsole_Descriptor : public PanelDescriptor{ +public: + VirtualConsole_Descriptor(); +}; + + +// The program panel of Virtual Console. +// It calls make_widget() to create a VirtualConsole_Widget that holds the UI wideget. +class VirtualConsole : public PanelInstance{ +public: + VirtualConsole(const VirtualConsole_Descriptor& descriptor); + virtual QWidget* make_widget(QWidget& parent, PanelHolder& holder) override; + +public: + // Serialization + virtual void from_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +private: + friend class VirtualConsole_Widget; + // switch control options like what micro-controller + // and what video source to use + SwitchSystemOption m_switch_control_option; +}; + + +// The UI of the prgoram Virtual Console +class VirtualConsole_Widget : public PanelWidget{ +public: + static VirtualConsole_Widget* make( + QWidget& parent, + VirtualConsole& instance, + PanelHolder& holder + ); + +private: + ~VirtualConsole_Widget(); + VirtualConsole_Widget( + QWidget& parent, + VirtualConsole& instance, + PanelHolder& holder + ); + void construct(); + +private: + SwitchSystemSession m_session; + SwitchSystemWidget* m_switch_widget; +}; + + + + + +} +} +#endif + diff --git a/SerialPrograms/Source/PanelLists.cpp b/SerialPrograms/Source/PanelLists.cpp index 4300b4d6cb..dbcdd3fb63 100644 --- a/SerialPrograms/Source/PanelLists.cpp +++ b/SerialPrograms/Source/PanelLists.cpp @@ -1,142 +1,142 @@ -/* Left-Side Panel - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonFramework/PersistentSettings.h" -#include "CommonFramework/Windows/DpiScaler.h" -#include "CommonFramework/Panels/UI/PanelListWidget.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "ML/ML_Panels.h" -#include "NintendoSwitch/NintendoSwitch_Panels.h" -#include "PokemonSwSh/PokemonSwSh_Panels.h" -#include "PokemonHome/PokemonHome_Panels.h" -#include "PokemonBDSP/PokemonBDSP_Panels.h" -#include "PokemonLA/PokemonLA_Panels.h" -#include "PokemonLGPE/PokemonLGPE_Panels.h" -#include "PokemonRSE/PokemonRSE_Panels.h" -#include "PokemonSV/PokemonSV_Panels.h" -#include "ZeldaTotK/ZeldaTotK_Panels.h" -#include "PanelLists.h" - -//#include -//using std::cout; -//using std::endl; - - -namespace PokemonAutomation{ - - - -ProgramSelect::ProgramSelect(QWidget& parent, PanelHolder& holder) - : QGroupBox("Program Select", &parent) - , m_holder(holder) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setAlignment(Qt::AlignTop); - m_dropdown = new NoWheelComboBox(this); - layout->addWidget(m_dropdown); - - - - add(std::make_unique()); - add(std::make_unique()); - add(std::make_unique()); - add(std::make_unique()); - add(std::make_unique()); - add(std::make_unique()); - add(std::make_unique()); - if (PreloadSettings::instance().DEVELOPER_MODE){ - add(std::make_unique()); - } - add(std::make_unique()); - if (PreloadSettings::instance().DEVELOPER_MODE){ - add(std::make_unique()); - } - - - // Load the 1st list by default. - m_dropdown->setCurrentIndex(0); - m_active_index = 0; - m_active_list = m_lists[0]->make_QWidget(*this, m_holder); - layout->addWidget(m_active_list); - - connect( - m_dropdown, static_cast(&QComboBox::activated), - this, [this](int index){ - change_list(index); - } - ); -} - -void ProgramSelect::add(std::unique_ptr list){ - int index = m_dropdown->count(); - m_dropdown->addItem(QString::fromStdString(list->name())); - m_lists.emplace_back(std::move(list)); - const PanelListDescriptor& back = *m_lists.back(); - if (!m_tab_map.emplace(back.name(), index).second){ - m_lists.pop_back(); - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Category Name: " + back.name()); - } - if (!back.enabled()){ - auto* model = qobject_cast(m_dropdown->model()); - if (model != nullptr){ - QStandardItem* line_handle = model->item(index); - if (line_handle != nullptr){ - line_handle->setEnabled(false); - } - } - } -} - - - -void ProgramSelect::load_persistent_panel(){ - const std::string* str = PERSISTENT_SETTINGS().panels.get_string("ProgramCategory"); - if (str == nullptr){ - return; - } - auto iter = m_tab_map.find(*str); - if (iter == m_tab_map.end()){ - return; - } - m_dropdown->setCurrentIndex(iter->second); - change_list(iter->second); - str = PERSISTENT_SETTINGS().panels.get_string(PanelListWidget::JSON_PROGRAM_PANEL); - if (str != nullptr){ - m_active_list->set_panel(*str); - } -} - -void ProgramSelect::change_list(int index){ - if (m_active_index == index && m_active_list != nullptr){ - return; - } - m_dropdown->setCurrentIndex(index); - m_active_index = index; - PERSISTENT_SETTINGS().panels["ProgramCategory"] = m_lists[index]->name(); - delete m_active_list; - m_active_list = m_lists[index]->make_QWidget(*this, m_holder); - layout()->addWidget(m_active_list); -} - -QSize ProgramSelect::sizeHint() const{ - QSize size = QGroupBox::sizeHint(); -// cout << size.width() << " x " << size.height() << endl; -// cout << this->size().width() << " x " << this->size().height() << endl; - size.setWidth(scale_dpi_width(size.width() + 10)); - return size; -} - - - - - - - -} +/* Left-Side Panel + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonFramework/PersistentSettings.h" +#include "CommonFramework/Windows/DpiScaler.h" +#include "CommonFramework/Panels/UI/PanelListWidget.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "ML/ML_Panels.h" +#include "NintendoSwitch/NintendoSwitch_Panels.h" +#include "PokemonSwSh/PokemonSwSh_Panels.h" +#include "PokemonHome/PokemonHome_Panels.h" +#include "PokemonBDSP/PokemonBDSP_Panels.h" +#include "PokemonLA/PokemonLA_Panels.h" +#include "PokemonLGPE/PokemonLGPE_Panels.h" +#include "PokemonRSE/PokemonRSE_Panels.h" +#include "PokemonSV/PokemonSV_Panels.h" +#include "ZeldaTotK/ZeldaTotK_Panels.h" +#include "PanelLists.h" + +//#include +//using std::cout; +//using std::endl; + + +namespace PokemonAutomation{ + + + +ProgramSelect::ProgramSelect(QWidget& parent, PanelHolder& holder) + : QGroupBox("Program Select", &parent) + , m_holder(holder) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setAlignment(Qt::AlignTop); + m_dropdown = new NoWheelComboBox(this); + layout->addWidget(m_dropdown); + + + + add(std::make_unique()); + add(std::make_unique()); + add(std::make_unique()); + add(std::make_unique()); + add(std::make_unique()); + add(std::make_unique()); + add(std::make_unique()); + if (PreloadSettings::instance().DEVELOPER_MODE){ + add(std::make_unique()); + } + add(std::make_unique()); + if (PreloadSettings::instance().DEVELOPER_MODE){ + add(std::make_unique()); + } + + + // Load the 1st list by default. + m_dropdown->setCurrentIndex(0); + m_active_index = 0; + m_active_list = m_lists[0]->make_QWidget(*this, m_holder); + layout->addWidget(m_active_list); + + connect( + m_dropdown, static_cast(&QComboBox::activated), + this, [this](int index){ + change_list(index); + } + ); +} + +void ProgramSelect::add(std::unique_ptr list){ + int index = m_dropdown->count(); + m_dropdown->addItem(QString::fromStdString(list->name())); + m_lists.emplace_back(std::move(list)); + const PanelListDescriptor& back = *m_lists.back(); + if (!m_tab_map.emplace(back.name(), index).second){ + m_lists.pop_back(); + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Category Name: " + back.name()); + } + if (!back.enabled()){ + auto* model = qobject_cast(m_dropdown->model()); + if (model != nullptr){ + QStandardItem* line_handle = model->item(index); + if (line_handle != nullptr){ + line_handle->setEnabled(false); + } + } + } +} + + + +void ProgramSelect::load_persistent_panel(){ + const std::string* str = PERSISTENT_SETTINGS().panels.get_string("ProgramCategory"); + if (str == nullptr){ + return; + } + auto iter = m_tab_map.find(*str); + if (iter == m_tab_map.end()){ + return; + } + m_dropdown->setCurrentIndex(iter->second); + change_list(iter->second); + str = PERSISTENT_SETTINGS().panels.get_string(PanelListWidget::JSON_PROGRAM_PANEL); + if (str != nullptr){ + m_active_list->set_panel(*str); + } +} + +void ProgramSelect::change_list(int index){ + if (m_active_index == index && m_active_list != nullptr){ + return; + } + m_dropdown->setCurrentIndex(index); + m_active_index = index; + PERSISTENT_SETTINGS().panels["ProgramCategory"] = m_lists[index]->name(); + delete m_active_list; + m_active_list = m_lists[index]->make_QWidget(*this, m_holder); + layout()->addWidget(m_active_list); +} + +QSize ProgramSelect::sizeHint() const{ + QSize size = QGroupBox::sizeHint(); +// cout << size.width() << " x " << size.height() << endl; +// cout << this->size().width() << " x " << this->size().height() << endl; + size.setWidth(scale_dpi_width(size.width() + 10)); + return size; +} + + + + + + + +} diff --git a/SerialPrograms/Source/PanelLists.h b/SerialPrograms/Source/PanelLists.h index 04c7b31811..888f85375f 100644 --- a/SerialPrograms/Source/PanelLists.h +++ b/SerialPrograms/Source/PanelLists.h @@ -1,51 +1,51 @@ -/* Program Tabs - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ProgramTabs_H -#define PokemonAutomation_ProgramTabs_H - -#include -#include "CommonFramework/Panels/PanelList.h" - -class QComboBox; - -namespace PokemonAutomation{ - - -// The program selection UI on the left side of the program window. -// It has a dropdown menu to select which Switch game's program list to show, and -// a display list window to show the current active game's program list. -// This class owns the a vector of PanelListDescriptor. A PanelListDescriptor is -// like a generator for the programs and their UIs for a game. -class ProgramSelect : public QGroupBox{ -public: - ProgramSelect(QWidget& parent, PanelHolder& holder); - - // Load the panel specified in the persistent setting. - void load_persistent_panel(); - - virtual QSize sizeHint() const override; - -private: - void add(std::unique_ptr list); - void change_list(int index); - -private: - PanelHolder& m_holder; - - std::vector> m_lists; - std::map m_tab_map; - - QComboBox* m_dropdown; - - int m_active_index = -1; - PanelListWidget* m_active_list = nullptr; -}; - - - -} -#endif +/* Program Tabs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ProgramTabs_H +#define PokemonAutomation_ProgramTabs_H + +#include +#include "CommonFramework/Panels/PanelList.h" + +class QComboBox; + +namespace PokemonAutomation{ + + +// The program selection UI on the left side of the program window. +// It has a dropdown menu to select which Switch game's program list to show, and +// a display list window to show the current active game's program list. +// This class owns the a vector of PanelListDescriptor. A PanelListDescriptor is +// like a generator for the programs and their UIs for a game. +class ProgramSelect : public QGroupBox{ +public: + ProgramSelect(QWidget& parent, PanelHolder& holder); + + // Load the panel specified in the persistent setting. + void load_persistent_panel(); + + virtual QSize sizeHint() const override; + +private: + void add(std::unique_ptr list); + void change_list(int index); + +private: + PanelHolder& m_holder; + + std::vector> m_lists; + std::map m_tab_map; + + QComboBox* m_dropdown; + + int m_active_index = -1; + PanelListWidget* m_active_list = nullptr; +}; + + + +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp index d537f6b9ff..c0dc5e1480 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.cpp @@ -1,40 +1,40 @@ -/* Berry Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_Routines.h" -#include "Pokemon_BerryNameReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -BerryNameReader& BerryNameReader::instance(){ - static BerryNameReader reader; - return reader; -} - - -BerryNameReader::BerryNameReader() - : SmallDictionaryMatcher("Pokemon/BerryNameOCR.json") -{} - -OCR::StringMatchResult BerryNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - - -} -} +/* Berry Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_Routines.h" +#include "Pokemon_BerryNameReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +BerryNameReader& BerryNameReader::instance(){ + static BerryNameReader reader; + return reader; +} + + +BerryNameReader::BerryNameReader() + : SmallDictionaryMatcher("Pokemon/BerryNameOCR.json") +{} + +OCR::StringMatchResult BerryNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.h index 70841e193d..cdb19fdf6a 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BerryNameReader.h @@ -1,37 +1,37 @@ -/* Berry Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_BerryNameReader_H -#define PokemonAutomation_Pokemon_BerryNameReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class BerryNameReader : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - BerryNameReader(); - - static BerryNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; -}; - - -} -} -#endif +/* Berry Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_BerryNameReader_H +#define PokemonAutomation_Pokemon_BerryNameReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class BerryNameReader : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + BerryNameReader(); + + static BerryNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.cpp index 9b35ea85bb..ec76fa5b74 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.cpp @@ -1,71 +1,71 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "Pokemon_BoxGenderDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace Pokemon{ - -BoxGenderDetector::BoxGenderDetector(const ImageFloatBox& box, double area_ratio_threshold, Color color) -: m_box(box), m_area_ratio_threshold(area_ratio_threshold), m_color(color) {} - -void BoxGenderDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -StatsHuntGenderFilter BoxGenderDetector::detect(const ImageViewRGB32& screen) const{ - const auto region = extract_box_reference(screen, m_box); - - // Retain only red pixels from region - const bool replace_color_within_range = false; - const ImageRGB32 red_region = filter_rgb32_range( - region, - combine_rgb(150, 0, 0), combine_rgb(255, 100, 100), Color(0), replace_color_within_range - ); - const size_t num_red_pixels = image_stats(red_region).count; - - // Retain only blue pixels from region - const ImageRGB32 blue_region = filter_rgb32_range( - region, - combine_rgb(0, 0, 180), combine_rgb(130, 130, 255), Color(0), replace_color_within_range - ); - const size_t num_blue_pixels = image_stats(blue_region).count; - - const double threshold = region.width() * region.height() * m_area_ratio_threshold; - - if (PreloadSettings::debug().COLOR_CHECK){ - cout << "num_red_pixels: " << num_red_pixels << ", num_blue_pixels: " << num_blue_pixels - << ", region " << region.width() << " x " << region.height() << " threshold " << threshold << endl; - - cout << "Save images to ./red_only.png and ./blue_only.png" << endl; - red_region.save("./red_only.png"); - blue_region.save("./blue_only.png"); - } - - if (num_red_pixels > threshold){ - return Pokemon::StatsHuntGenderFilter::Female; - }else if (num_blue_pixels > threshold){ - return Pokemon::StatsHuntGenderFilter::Male; - } - return Pokemon::StatsHuntGenderFilter::Genderless; -} - -} -} +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "Pokemon_BoxGenderDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace Pokemon{ + +BoxGenderDetector::BoxGenderDetector(const ImageFloatBox& box, double area_ratio_threshold, Color color) +: m_box(box), m_area_ratio_threshold(area_ratio_threshold), m_color(color) {} + +void BoxGenderDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +StatsHuntGenderFilter BoxGenderDetector::detect(const ImageViewRGB32& screen) const{ + const auto region = extract_box_reference(screen, m_box); + + // Retain only red pixels from region + const bool replace_color_within_range = false; + const ImageRGB32 red_region = filter_rgb32_range( + region, + combine_rgb(150, 0, 0), combine_rgb(255, 100, 100), Color(0), replace_color_within_range + ); + const size_t num_red_pixels = image_stats(red_region).count; + + // Retain only blue pixels from region + const ImageRGB32 blue_region = filter_rgb32_range( + region, + combine_rgb(0, 0, 180), combine_rgb(130, 130, 255), Color(0), replace_color_within_range + ); + const size_t num_blue_pixels = image_stats(blue_region).count; + + const double threshold = region.width() * region.height() * m_area_ratio_threshold; + + if (PreloadSettings::debug().COLOR_CHECK){ + cout << "num_red_pixels: " << num_red_pixels << ", num_blue_pixels: " << num_blue_pixels + << ", region " << region.width() << " x " << region.height() << " threshold " << threshold << endl; + + cout << "Save images to ./red_only.png and ./blue_only.png" << endl; + red_region.save("./red_only.png"); + blue_region.save("./blue_only.png"); + } + + if (num_red_pixels > threshold){ + return Pokemon::StatsHuntGenderFilter::Female; + }else if (num_blue_pixels > threshold){ + return Pokemon::StatsHuntGenderFilter::Male; + } + return Pokemon::StatsHuntGenderFilter::Genderless; +} + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.h index 225e795b65..06e16e179c 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_BoxGenderDetector.h @@ -1,44 +1,44 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_BoxGenderDetector_H -#define PokemonAutomation_Pokemon_BoxGenderDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class VideoOverlaySet; - -namespace Pokemon{ - -// Detect gender symbol inside the pokemon storage box -class BoxGenderDetector{ -public: - // box: the area where the gender symbol will appear - // area_ratio_threshold: if the number of red pixel count > box total area * area_ratio_threshold, female symbol is detected - // if the number of blue pixel count > box total area * area_ratio_threshold, male symbol is detected - BoxGenderDetector(const ImageFloatBox& box, double area_ratio_threshold, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - StatsHuntGenderFilter detect(const ImageViewRGB32& screen) const; - -private: - ImageFloatBox m_box; - double m_area_ratio_threshold; - Color m_color; -}; - - - -} -} - -#endif - +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_BoxGenderDetector_H +#define PokemonAutomation_Pokemon_BoxGenderDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class VideoOverlaySet; + +namespace Pokemon{ + +// Detect gender symbol inside the pokemon storage box +class BoxGenderDetector{ +public: + // box: the area where the gender symbol will appear + // area_ratio_threshold: if the number of red pixel count > box total area * area_ratio_threshold, female symbol is detected + // if the number of blue pixel count > box total area * area_ratio_threshold, male symbol is detected + BoxGenderDetector(const ImageFloatBox& box, double area_ratio_threshold, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + StatsHuntGenderFilter detect(const ImageViewRGB32& screen) const; + +private: + ImageFloatBox m_box; + double m_area_ratio_threshold; + Color m_color; +}; + + + +} +} + +#endif + diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.cpp index 2ccee854a1..d9f83ff1ae 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.cpp @@ -1,62 +1,62 @@ -/* IV Checker Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -namespace{ - -std::string iv_checker_value_to_string(IvJudgeValue value){ - const char* names[] = { - "UnableToDetect", - "NoGood", - "Decent", - "PrettyGood", - "VeryGood", - "Fantastic", - "Best", - "HyperTrained", - }; - - return names[int(value)]; -} - -} - -IvJudgeReader::IvJudgeReader(const std::string& json_path) - : SmallDictionaryMatcher(json_path) -{} - -OCR::StringMatchResult IvJudgeReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, - min_text_ratio, max_text_ratio - ); -} - - - -std::string IvJudgeReader::Results::to_string() const{ - return "HP: " + iv_checker_value_to_string(hp) - + ", Att: " + iv_checker_value_to_string(attack) - + ", Def: " + iv_checker_value_to_string(defense) - + ", S.Att: " + iv_checker_value_to_string(spatk) - + ", S.Def: " + iv_checker_value_to_string(spdef) - + ", Spd: " + iv_checker_value_to_string(speed); -} - - -} -} +/* IV Checker Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +std::string iv_checker_value_to_string(IvJudgeValue value){ + const char* names[] = { + "UnableToDetect", + "NoGood", + "Decent", + "PrettyGood", + "VeryGood", + "Fantastic", + "Best", + "HyperTrained", + }; + + return names[int(value)]; +} + +} + +IvJudgeReader::IvJudgeReader(const std::string& json_path) + : SmallDictionaryMatcher(json_path) +{} + +OCR::StringMatchResult IvJudgeReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, + min_text_ratio, max_text_ratio + ); +} + + + +std::string IvJudgeReader::Results::to_string() const{ + return "HP: " + iv_checker_value_to_string(hp) + + ", Att: " + iv_checker_value_to_string(attack) + + ", Def: " + iv_checker_value_to_string(defense) + + ", S.Att: " + iv_checker_value_to_string(spatk) + + ", S.Def: " + iv_checker_value_to_string(spdef) + + ", Spd: " + iv_checker_value_to_string(speed); +} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.h index 9af258ac2c..763ec827a3 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_IvJudgeReader.h @@ -1,51 +1,51 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_IvJudgeReader_H -#define PokemonAutomation_Pokemon_IvJudgeReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "Pokemon/Pokemon_IvJudge.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -class IvJudgeReader : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - struct Results{ - IvJudgeValue hp = IvJudgeValue::UnableToDetect; - IvJudgeValue attack = IvJudgeValue::UnableToDetect; - IvJudgeValue defense = IvJudgeValue::UnableToDetect; - IvJudgeValue spatk = IvJudgeValue::UnableToDetect; - IvJudgeValue spdef = IvJudgeValue::UnableToDetect; - IvJudgeValue speed = IvJudgeValue::UnableToDetect; - - std::string to_string() const; - }; - - IvJudgeReader(const std::string& json_path); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -}; - - - -} -} -#endif +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_IvJudgeReader_H +#define PokemonAutomation_Pokemon_IvJudgeReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "Pokemon/Pokemon_IvJudge.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +class IvJudgeReader : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + struct Results{ + IvJudgeValue hp = IvJudgeValue::UnableToDetect; + IvJudgeValue attack = IvJudgeValue::UnableToDetect; + IvJudgeValue defense = IvJudgeValue::UnableToDetect; + IvJudgeValue spatk = IvJudgeValue::UnableToDetect; + IvJudgeValue spdef = IvJudgeValue::UnableToDetect; + IvJudgeValue speed = IvJudgeValue::UnableToDetect; + + std::string to_string() const; + }; + + IvJudgeReader(const std::string& json_path); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.cpp index f5b1b2b62b..28a969a7a8 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.cpp @@ -1,44 +1,44 @@ -/* Pokemon Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "Pokemon_NameReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const PokemonNameReader& PokemonNameReader::instance(){ - static PokemonNameReader reader; - return reader; -} - - -PokemonNameReader::PokemonNameReader() - : LargeDictionaryMatcher("Pokemon/PokemonNameOCR/PokemonOCR-", nullptr, false) -{} -PokemonNameReader::PokemonNameReader(const std::set& subset) - : LargeDictionaryMatcher("Pokemon/PokemonNameOCR/PokemonOCR-", &subset, false) -{} - -OCR::StringMatchResult PokemonNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio, - double max_log10p -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - max_log10p, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - -} -} - +/* Pokemon Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "Pokemon_NameReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const PokemonNameReader& PokemonNameReader::instance(){ + static PokemonNameReader reader; + return reader; +} + + +PokemonNameReader::PokemonNameReader() + : LargeDictionaryMatcher("Pokemon/PokemonNameOCR/PokemonOCR-", nullptr, false) +{} +PokemonNameReader::PokemonNameReader(const std::set& subset) + : LargeDictionaryMatcher("Pokemon/PokemonNameOCR/PokemonOCR-", &subset, false) +{} + +OCR::StringMatchResult PokemonNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio, + double max_log10p +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + max_log10p, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + +} +} + diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.h index f2226e1064..18904a9ef2 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NameReader.h @@ -1,43 +1,43 @@ -/* Pokemon Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonNameReader_H -#define PokemonAutomation_Pokemon_PokemonNameReader_H - -#include "CommonTools/OCR/OCR_LargeDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class PokemonNameReader : public OCR::LargeDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -private: - PokemonNameReader(); -public: - PokemonNameReader(const std::set& subset); - -public: - static const PokemonNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50, - double max_log10p = MAX_LOG10P - ) const; - -}; - - -} -} -#endif +/* Pokemon Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonNameReader_H +#define PokemonAutomation_Pokemon_PokemonNameReader_H + +#include "CommonTools/OCR/OCR_LargeDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class PokemonNameReader : public OCR::LargeDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +private: + PokemonNameReader(); +public: + PokemonNameReader(const std::set& subset); + +public: + static const PokemonNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50, + double max_log10p = MAX_LOG10P + ) const; + +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.cpp index d34c90b0d3..bd2ca27707 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.cpp @@ -1,75 +1,75 @@ -/* Nature Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_Routines.h" -#include "Pokemon_NatureReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -namespace{ - -std::string nature_checker_value_to_string(NatureCheckerValue value){ - const char* names[] = { - "UnableToDetect", - "Any", - "Adamant", - "Bashful", - "Bold", - "Brave", - "Calm", - "Careful", - "Docile", - "Gentle", - "Hardy", - "Hasty", - "Impish", - "Jolly", - "Lax", - "Lonely", - "Mild", - "Modest", - "Naive", - "Naughty", - "Quiet", - "Quirky", - "Rash", - "Relaxed", - "Sassy", - "Serious", - "Timid", - "Last" - }; - - return names[int(value)]; -} -} - -NatureReader::NatureReader(const std::string& json_path) - : SmallDictionaryMatcher(json_path) -{} - -OCR::StringMatchResult NatureReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, - min_text_ratio, max_text_ratio - ); -} - -std::string NatureReader::Results::to_string() const{ - return "Nature: " + nature_checker_value_to_string(nature); -} - - -} -} +/* Nature Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_Routines.h" +#include "Pokemon_NatureReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +namespace{ + +std::string nature_checker_value_to_string(NatureCheckerValue value){ + const char* names[] = { + "UnableToDetect", + "Any", + "Adamant", + "Bashful", + "Bold", + "Brave", + "Calm", + "Careful", + "Docile", + "Gentle", + "Hardy", + "Hasty", + "Impish", + "Jolly", + "Lax", + "Lonely", + "Mild", + "Modest", + "Naive", + "Naughty", + "Quiet", + "Quirky", + "Rash", + "Relaxed", + "Sassy", + "Serious", + "Timid", + "Last" + }; + + return names[int(value)]; +} +} + +NatureReader::NatureReader(const std::string& json_path) + : SmallDictionaryMatcher(json_path) +{} + +OCR::StringMatchResult NatureReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, + min_text_ratio, max_text_ratio + ); +} + +std::string NatureReader::Results::to_string() const{ + return "Nature: " + nature_checker_value_to_string(nature); +} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.h index 4d5cbd4673..26f4917245 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_NatureReader.h @@ -1,41 +1,41 @@ -/* Nature Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_NatureReader_H -#define PokemonAutomation_Pokemon_NatureReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "Pokemon/Pokemon_NatureChecker.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -class NatureReader : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - struct Results{ - NatureCheckerValue nature = NatureCheckerValue::UnableToDetect; - std::string to_string() const; - }; - - NatureReader(const std::string& json_path); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -}; - -} -} -#endif +/* Nature Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_NatureReader_H +#define PokemonAutomation_Pokemon_NatureReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "Pokemon/Pokemon_NatureChecker.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +class NatureReader : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + struct Results{ + NatureCheckerValue nature = NatureCheckerValue::UnableToDetect; + std::string to_string() const; + }; + + NatureReader(const std::string& json_path); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +}; + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.cpp index 1f5a64b52c..ccfee13ea1 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.cpp @@ -1,40 +1,40 @@ -/* Pokeball Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "Pokemon_PokeballNameReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -PokeballNameReader& PokeballNameReader::instance(){ - static PokeballNameReader reader; - return reader; -} - - -PokeballNameReader::PokeballNameReader() - : SmallDictionaryMatcher("Pokemon/PokeballNameOCR.json") -{} - -OCR::StringMatchResult PokeballNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - - -} -} +/* Pokeball Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "Pokemon_PokeballNameReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +PokeballNameReader& PokeballNameReader::instance(){ + static PokeballNameReader reader; + return reader; +} + + +PokeballNameReader::PokeballNameReader() + : SmallDictionaryMatcher("Pokemon/PokeballNameOCR.json") +{} + +OCR::StringMatchResult PokeballNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.h index 9b9593d99b..0ea47ac4c3 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_PokeballNameReader.h @@ -1,39 +1,39 @@ -/* Pokeball Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokeballNameReader_H -#define PokemonAutomation_Pokemon_PokeballNameReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class PokeballNameReader : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - PokeballNameReader(); - - static PokeballNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -}; - - -} -} -#endif +/* Pokeball Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokeballNameReader_H +#define PokemonAutomation_Pokemon_PokeballNameReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class PokeballNameReader : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + PokeballNameReader(); + + static PokeballNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.cpp index 9d163f59d7..416a0bf4db 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.cpp @@ -1,101 +1,101 @@ -/* Read HP Bar - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "Pokemon_ReadHpBar.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Pokemon{ - - -double read_hp_bar_internal(const ImageViewRGB32& image){ - size_t width = image.width(); - size_t height = image.height(); - size_t area = width * height; - -// static int i = 0; -// image.save("test-" + std::to_string(++i) + ".png"); -// cout << "start: " << i << endl; - - ImageStats stats; - double bar = 0.5; - for (size_t c = 0;; c++){ - stats = image_stats(extract_box_reference(image, ImageFloatBox(0.0, 0.0, bar, 1.0))); - double max_color = 0; - max_color = std::max(max_color, stats.average.r); - max_color = std::max(max_color, stats.average.g); - max_color = std::max(max_color, stats.average.b); -// cout << "max_color: " << max_color << ", stddev: " << stats.stddev.sum() << endl; - if (max_color > 128 && stats.stddev.sum() < 120){ - break; - } - bar *= 0.5; - if (c > 12){ - stats = image_stats(extract_box_reference(image, ImageFloatBox(0.0, 0.0, 1.0, 1.0))); -// cout << stats.average << stats.stddev << endl; -// image.save("test.png"); - return stats.average.sum() < 384 && stats.stddev.sum() < 80 - ? 0.0 - : -1; - } - } -// cout << "end: " << i << endl; - - Color color = stats.average.round(); - int bar_R = color.red(); - int bar_G = color.green(); - int bar_B = color.blue(); - - int bar_area = 0; - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - Color pixel(image.pixel(c, r)); - int R = pixel.red() - bar_R; - int G = pixel.green() - bar_G; - int B = pixel.blue() - bar_B; - if (R*R + G*G + B*B < 100*100){ - bar_area++; - } - } - } - - return std::min((double)bar_area / area, bar * 4); -} -double read_hp_bar(const ImageViewRGB32& image){ - // Try reading just the upper half first. - double hp = read_hp_bar_internal(extract_box_reference(image, ImageFloatBox(0.5, 0.0, 0.5, 1.0))); - if (hp > 0){ - return (1.0 + hp) * 0.5; - } - - // Now try the bottom half. - return read_hp_bar_internal(image); -} - -double read_hp_bar(Logger& logger, const ImageViewRGB32& image){ - double hp = read_hp_bar(image); - -// static int c = 0; -// image.save("test-" + std::to_string(c++) + ".png"); - - if (hp <= 0){ - logger.log("HP Read: ?", COLOR_RED); - }else{ - logger.log("HP Read: " + std::to_string(100 * hp) + "%", COLOR_BLUE); - } - return hp; -} - - - -} -} +/* Read HP Bar + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "Pokemon_ReadHpBar.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Pokemon{ + + +double read_hp_bar_internal(const ImageViewRGB32& image){ + size_t width = image.width(); + size_t height = image.height(); + size_t area = width * height; + +// static int i = 0; +// image.save("test-" + std::to_string(++i) + ".png"); +// cout << "start: " << i << endl; + + ImageStats stats; + double bar = 0.5; + for (size_t c = 0;; c++){ + stats = image_stats(extract_box_reference(image, ImageFloatBox(0.0, 0.0, bar, 1.0))); + double max_color = 0; + max_color = std::max(max_color, stats.average.r); + max_color = std::max(max_color, stats.average.g); + max_color = std::max(max_color, stats.average.b); +// cout << "max_color: " << max_color << ", stddev: " << stats.stddev.sum() << endl; + if (max_color > 128 && stats.stddev.sum() < 120){ + break; + } + bar *= 0.5; + if (c > 12){ + stats = image_stats(extract_box_reference(image, ImageFloatBox(0.0, 0.0, 1.0, 1.0))); +// cout << stats.average << stats.stddev << endl; +// image.save("test.png"); + return stats.average.sum() < 384 && stats.stddev.sum() < 80 + ? 0.0 + : -1; + } + } +// cout << "end: " << i << endl; + + Color color = stats.average.round(); + int bar_R = color.red(); + int bar_G = color.green(); + int bar_B = color.blue(); + + int bar_area = 0; + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + Color pixel(image.pixel(c, r)); + int R = pixel.red() - bar_R; + int G = pixel.green() - bar_G; + int B = pixel.blue() - bar_B; + if (R*R + G*G + B*B < 100*100){ + bar_area++; + } + } + } + + return std::min((double)bar_area / area, bar * 4); +} +double read_hp_bar(const ImageViewRGB32& image){ + // Try reading just the upper half first. + double hp = read_hp_bar_internal(extract_box_reference(image, ImageFloatBox(0.5, 0.0, 0.5, 1.0))); + if (hp > 0){ + return (1.0 + hp) * 0.5; + } + + // Now try the bottom half. + return read_hp_bar_internal(image); +} + +double read_hp_bar(Logger& logger, const ImageViewRGB32& image){ + double hp = read_hp_bar(image); + +// static int c = 0; +// image.save("test-" + std::to_string(c++) + ".png"); + + if (hp <= 0){ + logger.log("HP Read: ?", COLOR_RED); + }else{ + logger.log("HP Read: " + std::to_string(100 * hp) + "%", COLOR_BLUE); + } + return hp; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.h index 70cb9e9dc0..ab861d262d 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_ReadHpBar.h @@ -1,25 +1,25 @@ -/* Read HP Bar - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_ReadHpBar_H -#define PokemonAutomation_Pokemon_ReadHpBar_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ - class Logger; -namespace Pokemon{ - - - -double read_hp_bar(const ImageViewRGB32& image); -double read_hp_bar(Logger& logger, const ImageViewRGB32& image); - - - -} -} -#endif +/* Read HP Bar + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_ReadHpBar_H +#define PokemonAutomation_Pokemon_ReadHpBar_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ + class Logger; +namespace Pokemon{ + + + +double read_hp_bar(const ImageViewRGB32& image); +double read_hp_bar(Logger& logger, const ImageViewRGB32& image); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.cpp index bcc462157c..b82e7e93d3 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.cpp @@ -1,65 +1,65 @@ -/* Train IV Checker OCR Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/OCR/OCR_TrainingTools.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon_IvJudgeReader.h" -#include "Pokemon_TrainIVCheckerOCR.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -TrainIVCheckerOCR_Descriptor::TrainIVCheckerOCR_Descriptor() - : ComputerProgramDescriptor( - "PokemonSwSh:TrainIVCheckerOCR", - STRING_POKEMON, "Train IV Checker OCR", - "", - "Train IV Checker OCR" - ) -{} - - - -TrainIVCheckerOCR::TrainIVCheckerOCR() - : DIRECTORY( - false, - "Training Data Directory: (Relative to \"TrainingData/\")", - LockMode::LOCK_WHILE_RUNNING, - "IVCheckerOCR/", - "IVCheckerOCR/" - ) - , THREADS( - "Worker Threads:", - LockMode::LOCK_WHILE_RUNNING, - std::thread::hardware_concurrency() - ) -{ - PA_ADD_OPTION(DIRECTORY); - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(THREADS); -} - - - -void TrainIVCheckerOCR::program(ProgramEnvironment& env, CancellableScope& scope){ - OCR::TrainingSession session(env.logger(), scope, DIRECTORY); - session.generate_small_dictionary( - "Pokemon/IVCheckerOCR.json", - "IVCheckerOCR.json", - MODE == TrainOCRMode::INCREMENTAL, THREADS, - OCR::BLACK_TEXT_FILTERS(), - IvJudgeReader::MAX_LOG10P, - IvJudgeReader::MAX_LOG10P_SPREAD - ); -} - - - -} -} +/* Train IV Checker OCR Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/OCR/OCR_TrainingTools.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon_IvJudgeReader.h" +#include "Pokemon_TrainIVCheckerOCR.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +TrainIVCheckerOCR_Descriptor::TrainIVCheckerOCR_Descriptor() + : ComputerProgramDescriptor( + "PokemonSwSh:TrainIVCheckerOCR", + STRING_POKEMON, "Train IV Checker OCR", + "", + "Train IV Checker OCR" + ) +{} + + + +TrainIVCheckerOCR::TrainIVCheckerOCR() + : DIRECTORY( + false, + "Training Data Directory: (Relative to \"TrainingData/\")", + LockMode::LOCK_WHILE_RUNNING, + "IVCheckerOCR/", + "IVCheckerOCR/" + ) + , THREADS( + "Worker Threads:", + LockMode::LOCK_WHILE_RUNNING, + std::thread::hardware_concurrency() + ) +{ + PA_ADD_OPTION(DIRECTORY); + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(THREADS); +} + + + +void TrainIVCheckerOCR::program(ProgramEnvironment& env, CancellableScope& scope){ + OCR::TrainingSession session(env.logger(), scope, DIRECTORY); + session.generate_small_dictionary( + "Pokemon/IVCheckerOCR.json", + "IVCheckerOCR.json", + MODE == TrainOCRMode::INCREMENTAL, THREADS, + OCR::BLACK_TEXT_FILTERS(), + IvJudgeReader::MAX_LOG10P, + IvJudgeReader::MAX_LOG10P_SPREAD + ); +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h index dc1dd850a0..66e990ec8a 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainIVCheckerOCR.h @@ -1,43 +1,43 @@ -/* Train IV Checker OCR Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TrainIVCheckerOCR_H -#define PokemonAutomation_PokemonSwSh_TrainIVCheckerOCR_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonTools/Options/TrainOCRModeOption.h" -#include "ComputerPrograms/ComputerProgram.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class TrainIVCheckerOCR_Descriptor : public ComputerProgramDescriptor{ -public: - TrainIVCheckerOCR_Descriptor(); -}; - - - -class TrainIVCheckerOCR : public ComputerProgramInstance{ -public: - TrainIVCheckerOCR(); - - virtual void program(ProgramEnvironment& env, CancellableScope& scope) override; - -private: - StringOption DIRECTORY; - TrainOCRModeOption MODE; - SimpleIntegerOption THREADS; // Can't use "size_t" due to integer type ambiguity. - -}; - - - -} -} -#endif +/* Train IV Checker OCR Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TrainIVCheckerOCR_H +#define PokemonAutomation_PokemonSwSh_TrainIVCheckerOCR_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonTools/Options/TrainOCRModeOption.h" +#include "ComputerPrograms/ComputerProgram.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class TrainIVCheckerOCR_Descriptor : public ComputerProgramDescriptor{ +public: + TrainIVCheckerOCR_Descriptor(); +}; + + + +class TrainIVCheckerOCR : public ComputerProgramInstance{ +public: + TrainIVCheckerOCR(); + + virtual void program(ProgramEnvironment& env, CancellableScope& scope) override; + +private: + StringOption DIRECTORY; + TrainOCRModeOption MODE; + SimpleIntegerOption THREADS; // Can't use "size_t" due to integer type ambiguity. + +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.cpp b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.cpp index 0b6b2f3f83..26deaab669 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.cpp +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.cpp @@ -1,86 +1,86 @@ -/* Train Pokemon Name OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/OCR/OCR_TrainingTools.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" -#include "Pokemon_NameReader.h" -#include "Pokemon_TrainPokemonOCR.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -TrainPokemonOCR_Descriptor::TrainPokemonOCR_Descriptor() - : ComputerProgramDescriptor( - "PokemonSwSh:TrainPokemonNameOCR", - STRING_POKEMON, "Train " + STRING_POKEMON + " Name OCR", - "", - "Train " + STRING_POKEMON + " Name OCR" - ) -{} - - - -TrainPokemonOCR::TrainPokemonOCR() - : DIRECTORY( - false, - "Training Data Directory: (Relative to \"TrainingData/\")", - LockMode::LOCK_WHILE_RUNNING, - "PokemonNameOCR/", - "PokemonNameOCR/" - ) - , THREADS( - "Worker Threads:", - LockMode::LOCK_WHILE_RUNNING, - std::thread::hardware_concurrency() - ) -{ - PA_ADD_OPTION(DIRECTORY); - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(THREADS); -} - - -void TrainPokemonOCR::program(ProgramEnvironment& env, CancellableScope& scope){ - if (MODE == TrainOCRMode::GENERATE_BASELINE){ - for (int c = (int)Language::English; c < (int)Language::EndOfList; c++){ - Language language = (Language)c; - - JsonObject json; - - for (const std::string& slug : NATIONAL_DEX_SLUGS()){ - JsonArray array; - array.push_back(get_pokemon_name(slug).display_name(language)); - json[slug] = std::move(array); - } - - json.dump("PokemonOCR-" + language_data(language).code + ".json"); - } - return; - } - - OCR::TrainingSession session(env.logger(), scope, DIRECTORY); - session.generate_large_dictionary( - "Pokemon/PokemonNameOCR/", - "PokemonOCR-", - MODE == TrainOCRMode::INCREMENTAL, - THREADS, - OCR::BLACK_OR_WHITE_TEXT_FILTERS(), - PokemonNameReader::MAX_LOG10P + 1.0, - PokemonNameReader::MAX_LOG10P_SPREAD - ); -} - - -} -} - +/* Train Pokemon Name OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/OCR/OCR_TrainingTools.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" +#include "Pokemon_NameReader.h" +#include "Pokemon_TrainPokemonOCR.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +TrainPokemonOCR_Descriptor::TrainPokemonOCR_Descriptor() + : ComputerProgramDescriptor( + "PokemonSwSh:TrainPokemonNameOCR", + STRING_POKEMON, "Train " + STRING_POKEMON + " Name OCR", + "", + "Train " + STRING_POKEMON + " Name OCR" + ) +{} + + + +TrainPokemonOCR::TrainPokemonOCR() + : DIRECTORY( + false, + "Training Data Directory: (Relative to \"TrainingData/\")", + LockMode::LOCK_WHILE_RUNNING, + "PokemonNameOCR/", + "PokemonNameOCR/" + ) + , THREADS( + "Worker Threads:", + LockMode::LOCK_WHILE_RUNNING, + std::thread::hardware_concurrency() + ) +{ + PA_ADD_OPTION(DIRECTORY); + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(THREADS); +} + + +void TrainPokemonOCR::program(ProgramEnvironment& env, CancellableScope& scope){ + if (MODE == TrainOCRMode::GENERATE_BASELINE){ + for (int c = (int)Language::English; c < (int)Language::EndOfList; c++){ + Language language = (Language)c; + + JsonObject json; + + for (const std::string& slug : NATIONAL_DEX_SLUGS()){ + JsonArray array; + array.push_back(get_pokemon_name(slug).display_name(language)); + json[slug] = std::move(array); + } + + json.dump("PokemonOCR-" + language_data(language).code + ".json"); + } + return; + } + + OCR::TrainingSession session(env.logger(), scope, DIRECTORY); + session.generate_large_dictionary( + "Pokemon/PokemonNameOCR/", + "PokemonOCR-", + MODE == TrainOCRMode::INCREMENTAL, + THREADS, + OCR::BLACK_OR_WHITE_TEXT_FILTERS(), + PokemonNameReader::MAX_LOG10P + 1.0, + PokemonNameReader::MAX_LOG10P_SPREAD + ); +} + + +} +} + diff --git a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h index 5c6ad2fff0..7ad4b4312a 100644 --- a/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h +++ b/SerialPrograms/Source/Pokemon/Inference/Pokemon_TrainPokemonOCR.h @@ -1,43 +1,43 @@ -/* Train Pokemon Name OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_TrainPokemonOCR_H -#define PokemonAutomation_Pokemon_TrainPokemonOCR_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonTools/Options/TrainOCRModeOption.h" -#include "ComputerPrograms/ComputerProgram.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class TrainPokemonOCR_Descriptor : public ComputerProgramDescriptor{ -public: - TrainPokemonOCR_Descriptor(); -}; - - - -class TrainPokemonOCR : public ComputerProgramInstance{ -public: - TrainPokemonOCR(); - - virtual void program(ProgramEnvironment& env, CancellableScope& scope) override; - -private: - StringOption DIRECTORY; - TrainOCRModeOption MODE; - SimpleIntegerOption THREADS; // Can't use "size_t" due to integer type ambiguity. - -}; - - - -} -} -#endif +/* Train Pokemon Name OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_TrainPokemonOCR_H +#define PokemonAutomation_Pokemon_TrainPokemonOCR_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonTools/Options/TrainOCRModeOption.h" +#include "ComputerPrograms/ComputerProgram.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class TrainPokemonOCR_Descriptor : public ComputerProgramDescriptor{ +public: + TrainPokemonOCR_Descriptor(); +}; + + + +class TrainPokemonOCR : public ComputerProgramInstance{ +public: + TrainPokemonOCR(); + + virtual void program(ProgramEnvironment& env, CancellableScope& scope) override; + +private: + StringOption DIRECTORY; + TrainOCRModeOption MODE; + SimpleIntegerOption THREADS; // Can't use "size_t" due to integer type ambiguity. + +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_EncounterBotOptions.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_EncounterBotOptions.h index bc1a33b824..1a76e34bd9 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_EncounterBotOptions.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_EncounterBotOptions.h @@ -1,34 +1,34 @@ -/* Encounter Mon Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_EncounterBotOptions_H -#define PokemonAutomation_Pokemon_EncounterBotOptions_H - -#include "CommonTools/Options/LanguageOCROption.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class EncounterBotLanguage : public OCR::LanguageOCROption{ -public: - EncounterBotLanguage(bool required = false) - : LanguageOCROption( - "Game Language:
Attempt to read and log the encountered " + STRING_POKEMON + " in this language.
Set to \"None\" to disable this feature.", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - required - ) - {} -}; - - - -} -} -#endif +/* Encounter Mon Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_EncounterBotOptions_H +#define PokemonAutomation_Pokemon_EncounterBotOptions_H + +#include "CommonTools/Options/LanguageOCROption.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class EncounterBotLanguage : public OCR::LanguageOCROption{ +public: + EncounterBotLanguage(bool required = false) + : LanguageOCROption( + "Game Language:
Attempt to read and log the encountered " + STRING_POKEMON + " in this language.
Set to \"None\" to disable this feature.", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + required + ) + {} +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp index ee0bc118bd..f761dbccf3 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.cpp @@ -1,57 +1,57 @@ -/* HomeSprite Selector, UI component to select multiple berries - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonForms.h" -#include "Pokemon/Resources/Pokemon_PokemonHomeSprites.h" -#include "Pokemon_HomeSpriteSelectOption.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -StringSelectDatabase make_all_home_sprites_database(){ - StringSelectDatabase ret; - for(const auto& slug: ALL_POKEMON_FORMS()){ - // for(const auto& p: ALL_POKEMON_HOME_SPRITES().get()){ - const SpriteDatabase::Sprite* sprite = ALL_POKEMON_HOME_SPRITES().get_nothrow(slug); - const PokemonForm* form_ptr = get_pokemon_form(slug); - if (form_ptr == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A form slug is in ALL_POKEMON_FORMS but not available in get_pokemon_form() : " + slug); - } - if (sprite == nullptr){ - // we don't have the sprite. Use a replacement sprite instead: - const auto& no_show_sprite = ALL_POKEMON_HOME_SPRITES().get_throw("floette-eternal-flower"); - ret.add_entry(StringSelectEntry(slug, form_ptr->display_name(), no_show_sprite.icon)); - } else{ - ret.add_entry(StringSelectEntry(slug, form_ptr->display_name(), sprite->icon)); - } - } - - return ret; -} -const StringSelectDatabase& ALL_HOME_SPRITES_SELECT_DATABASE(){ - static StringSelectDatabase database = make_all_home_sprites_database(); - return database; -} - - - - -HomeSpriteSelectCell::HomeSpriteSelectCell( - const std::string& default_slug -) - : StringSelectCell( - ALL_HOME_SPRITES_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - -} -} +/* HomeSprite Selector, UI component to select multiple berries + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonForms.h" +#include "Pokemon/Resources/Pokemon_PokemonHomeSprites.h" +#include "Pokemon_HomeSpriteSelectOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +StringSelectDatabase make_all_home_sprites_database(){ + StringSelectDatabase ret; + for(const auto& slug: ALL_POKEMON_FORMS()){ + // for(const auto& p: ALL_POKEMON_HOME_SPRITES().get()){ + const SpriteDatabase::Sprite* sprite = ALL_POKEMON_HOME_SPRITES().get_nothrow(slug); + const PokemonForm* form_ptr = get_pokemon_form(slug); + if (form_ptr == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "A form slug is in ALL_POKEMON_FORMS but not available in get_pokemon_form() : " + slug); + } + if (sprite == nullptr){ + // we don't have the sprite. Use a replacement sprite instead: + const auto& no_show_sprite = ALL_POKEMON_HOME_SPRITES().get_throw("floette-eternal-flower"); + ret.add_entry(StringSelectEntry(slug, form_ptr->display_name(), no_show_sprite.icon)); + } else{ + ret.add_entry(StringSelectEntry(slug, form_ptr->display_name(), sprite->icon)); + } + } + + return ret; +} +const StringSelectDatabase& ALL_HOME_SPRITES_SELECT_DATABASE(){ + static StringSelectDatabase database = make_all_home_sprites_database(); + return database; +} + + + + +HomeSpriteSelectCell::HomeSpriteSelectCell( + const std::string& default_slug +) + : StringSelectCell( + ALL_HOME_SPRITES_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h index 9b17371974..740324cf81 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_HomeSpriteSelectOption.h @@ -1,29 +1,29 @@ -/* HomeSprite Selector, UI component to select multiple berries - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_HomeSpriteSelectOption_H -#define PokemonAutomation_PokemonBDSP_HomeSpriteSelectOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -// Option to select a pokemon form with a Pokemon Home sprite shown. -// The forms are all the unique forms including shiny and non-shiny. -class HomeSpriteSelectCell : public StringSelectCell{ -public: - HomeSpriteSelectCell(const std::string& default_slug); -}; - - - - -} -} -#endif +/* HomeSprite Selector, UI component to select multiple berries + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_HomeSpriteSelectOption_H +#define PokemonAutomation_PokemonBDSP_HomeSpriteSelectOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +// Option to select a pokemon form with a Pokemon Home sprite shown. +// The forms are all the unique forms including shiny and non-shiny. +class HomeSpriteSelectCell : public StringSelectCell{ +public: + HomeSpriteSelectCell(const std::string& default_slug); +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp index 47aa0294ab..fd418f1de1 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.cpp @@ -1,46 +1,46 @@ -/* IV Judge Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_IvJudge.h" -#include "Pokemon_IvJudgeOption.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - - -IVJudgeFilterCell::IVJudgeFilterCell(IvJudgeFilter default_value) - : EnumDropdownCell( - IvJudgeFilter_Database(), - LockMode::LOCK_WHILE_RUNNING, - default_value - ) -{} - - - - -IVJudgeFilterOption::IVJudgeFilterOption(std::string label, IvJudgeFilter default_value) - : EnumDropdownOption( - std::move(label), - IvJudgeFilter_Database(), - LockMode::LOCK_WHILE_RUNNING, - default_value - ) -{} - -bool IVJudgeFilterOption::matches(std::atomic& errors, IvJudgeValue result) const{ - if (result == IvJudgeValue::UnableToDetect){ - errors++; - } - return IvJudge_filter_match(*this, result); -} - - - -} -} +/* IV Judge Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_IvJudge.h" +#include "Pokemon_IvJudgeOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + + +IVJudgeFilterCell::IVJudgeFilterCell(IvJudgeFilter default_value) + : EnumDropdownCell( + IvJudgeFilter_Database(), + LockMode::LOCK_WHILE_RUNNING, + default_value + ) +{} + + + + +IVJudgeFilterOption::IVJudgeFilterOption(std::string label, IvJudgeFilter default_value) + : EnumDropdownOption( + std::move(label), + IvJudgeFilter_Database(), + LockMode::LOCK_WHILE_RUNNING, + default_value + ) +{} + +bool IVJudgeFilterOption::matches(std::atomic& errors, IvJudgeValue result) const{ + if (result == IvJudgeValue::UnableToDetect){ + errors++; + } + return IvJudge_filter_match(*this, result); +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.h index c4e2d24eaf..2e59fcc61a 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_IvJudgeOption.h @@ -1,38 +1,38 @@ -/* IV Judge Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_IvJudgeOption_H -#define PokemonAutomation_Pokemon_IvJudgeOption_H - -#include -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Pokemon/Pokemon_IvJudge.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - - -class IVJudgeFilterCell : public EnumDropdownCell{ -public: - IVJudgeFilterCell(IvJudgeFilter default_value); -}; - - -class IVJudgeFilterOption : public EnumDropdownOption{ -public: - IVJudgeFilterOption(std::string label, IvJudgeFilter default_value = IvJudgeFilter::Anything); - - bool matches(std::atomic& errors, IvJudgeValue result) const; -}; - - - - -} -} -#endif +/* IV Judge Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_IvJudgeOption_H +#define PokemonAutomation_Pokemon_IvJudgeOption_H + +#include +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Pokemon/Pokemon_IvJudge.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + + +class IVJudgeFilterCell : public EnumDropdownCell{ +public: + IVJudgeFilterCell(IvJudgeFilter default_value); +}; + + +class IVJudgeFilterOption : public EnumDropdownOption{ +public: + IVJudgeFilterOption(std::string label, IvJudgeFilter default_value = IvJudgeFilter::Anything); + + bool matches(std::atomic& errors, IvJudgeValue result) const; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.cpp index ea2ef42a79..0bc79ea30d 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.cpp @@ -1,128 +1,128 @@ -/* Pokemon Name Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "Pokemon_NameSelectOption.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -PokemonNameSelectData::PokemonNameSelectData(const std::vector& slugs){ - for (const std::string& slug : slugs){ - if (slug.size() <= 0){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Expected non-empty string for Pokemon slug."); - } - - using namespace NintendoSwitch::PokemonSwSh; - const PokemonNames& data = get_pokemon_name(slug); - const SpriteDatabase::Sprite* sprite = ALL_POKEMON_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - m_database.add_entry(StringSelectEntry( - slug, data.display_name() - )); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - m_database.add_entry(StringSelectEntry( - slug, data.display_name(), sprite->icon - )); - } - } -} -PokemonNameSelectData::PokemonNameSelectData(const std::string& json_file_slugs){ - std::string path = RESOURCE_PATH() + json_file_slugs; - JsonValue json_slugs = load_json_file(path); - JsonArray& slugs = json_slugs.to_array_throw(path); - - for (auto& item : slugs){ - std::string& slug = item.to_string_throw(path); - - using namespace NintendoSwitch::PokemonSwSh; - const PokemonNames& data = get_pokemon_name(slug); - const SpriteDatabase::Sprite* sprite = ALL_POKEMON_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - m_database.add_entry(StringSelectEntry( - slug, data.display_name() - )); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - m_database.add_entry(StringSelectEntry( - slug, data.display_name(), sprite->icon - )); - } - } -} - - - - - -PokemonNameSelectCell::PokemonNameSelectCell( - const std::vector& slugs, - const std::string& default_slug -) - : PokemonNameSelectData(slugs) - , StringSelectCell( - PokemonNameSelectData::m_database, - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} -PokemonNameSelectCell::PokemonNameSelectCell( - const std::string& json_file_slugs, - const std::string& default_slug -) - : PokemonNameSelectData(json_file_slugs) - , StringSelectCell( - PokemonNameSelectData::m_database, - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - - - -PokemonNameSelectOption::PokemonNameSelectOption( - std::string label, - const std::vector& slugs, - const std::string& default_slug -) - : PokemonNameSelectData(slugs) - , StringSelectOption( - std::move(label), - PokemonNameSelectData::m_database, - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} -PokemonNameSelectOption::PokemonNameSelectOption( - std::string label, - const std::string& json_file_slugs, - const std::string& default_slug -) - : PokemonNameSelectData(json_file_slugs) - , StringSelectOption( - std::move(label), - PokemonNameSelectData::m_database, - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - - - - -} -} +/* Pokemon Name Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "Pokemon_NameSelectOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +PokemonNameSelectData::PokemonNameSelectData(const std::vector& slugs){ + for (const std::string& slug : slugs){ + if (slug.size() <= 0){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Expected non-empty string for Pokemon slug."); + } + + using namespace NintendoSwitch::PokemonSwSh; + const PokemonNames& data = get_pokemon_name(slug); + const SpriteDatabase::Sprite* sprite = ALL_POKEMON_SPRITES().get_nothrow(slug); + if (sprite == nullptr){ + m_database.add_entry(StringSelectEntry( + slug, data.display_name() + )); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + m_database.add_entry(StringSelectEntry( + slug, data.display_name(), sprite->icon + )); + } + } +} +PokemonNameSelectData::PokemonNameSelectData(const std::string& json_file_slugs){ + std::string path = RESOURCE_PATH() + json_file_slugs; + JsonValue json_slugs = load_json_file(path); + JsonArray& slugs = json_slugs.to_array_throw(path); + + for (auto& item : slugs){ + std::string& slug = item.to_string_throw(path); + + using namespace NintendoSwitch::PokemonSwSh; + const PokemonNames& data = get_pokemon_name(slug); + const SpriteDatabase::Sprite* sprite = ALL_POKEMON_SPRITES().get_nothrow(slug); + if (sprite == nullptr){ + m_database.add_entry(StringSelectEntry( + slug, data.display_name() + )); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + m_database.add_entry(StringSelectEntry( + slug, data.display_name(), sprite->icon + )); + } + } +} + + + + + +PokemonNameSelectCell::PokemonNameSelectCell( + const std::vector& slugs, + const std::string& default_slug +) + : PokemonNameSelectData(slugs) + , StringSelectCell( + PokemonNameSelectData::m_database, + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} +PokemonNameSelectCell::PokemonNameSelectCell( + const std::string& json_file_slugs, + const std::string& default_slug +) + : PokemonNameSelectData(json_file_slugs) + , StringSelectCell( + PokemonNameSelectData::m_database, + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + + + +PokemonNameSelectOption::PokemonNameSelectOption( + std::string label, + const std::vector& slugs, + const std::string& default_slug +) + : PokemonNameSelectData(slugs) + , StringSelectOption( + std::move(label), + PokemonNameSelectData::m_database, + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} +PokemonNameSelectOption::PokemonNameSelectOption( + std::string label, + const std::string& json_file_slugs, + const std::string& default_slug +) + : PokemonNameSelectData(json_file_slugs) + , StringSelectOption( + std::move(label), + PokemonNameSelectData::m_database, + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.h index 84d2940f53..bcae45a9d8 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectOption.h @@ -1,53 +1,53 @@ -/* Pokemon Name Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonNameSelect_H -#define PokemonAutomation_Pokemon_PokemonNameSelect_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -struct PokemonNameSelectData{ - PokemonNameSelectData(const std::vector& slugs); - PokemonNameSelectData(const std::string& json_file_slugs); - StringSelectDatabase m_database; -}; - - -class PokemonNameSelectCell : private PokemonNameSelectData, public StringSelectCell{ -public: - PokemonNameSelectCell( - const std::vector& slugs, - const std::string& default_slug = "" - ); - PokemonNameSelectCell( - const std::string& json_file_slugs, - const std::string& default_slug = "" - ); -}; - -class PokemonNameSelectOption : private PokemonNameSelectData, public StringSelectOption{ -public: - PokemonNameSelectOption( - std::string label, - const std::vector& slugs, - const std::string& default_slug = "" - ); - PokemonNameSelectOption( - std::string label, - const std::string& json_file_slugs, - const std::string& default_slug = "" - ); -}; - - - -} -} -#endif +/* Pokemon Name Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonNameSelect_H +#define PokemonAutomation_Pokemon_PokemonNameSelect_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct PokemonNameSelectData{ + PokemonNameSelectData(const std::vector& slugs); + PokemonNameSelectData(const std::string& json_file_slugs); + StringSelectDatabase m_database; +}; + + +class PokemonNameSelectCell : private PokemonNameSelectData, public StringSelectCell{ +public: + PokemonNameSelectCell( + const std::vector& slugs, + const std::string& default_slug = "" + ); + PokemonNameSelectCell( + const std::string& json_file_slugs, + const std::string& default_slug = "" + ); +}; + +class PokemonNameSelectOption : private PokemonNameSelectData, public StringSelectOption{ +public: + PokemonNameSelectOption( + std::string label, + const std::vector& slugs, + const std::string& default_slug = "" + ); + PokemonNameSelectOption( + std::string label, + const std::string& json_file_slugs, + const std::string& default_slug = "" + ); +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.cpp index 28d7c2d80f..d9d5751f37 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.cpp @@ -1,139 +1,139 @@ -/* Pokemon Name Select Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon_NameSelectWidget.h" - -//#include "Common/Cpp/Time.h" -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Pokemon{ - -NameSelectWidget::NameSelectWidget( - QWidget& parent, - const SpriteDatabase& icons, - const std::vector& slugs, - const std::string& current_slug, - const std::map* display_names, - const std::map* display_name_to_slug, - const std::map>* extra_names, - const std::vector* extra_name_list, - const std::map* extra_display_name_to_slug -) - : NoWheelComboBox(&parent) - , m_display_name_to_slug(display_name_to_slug) - , m_extra_display_name_to_slug(extra_display_name_to_slug) -{ - this->setEditable(true); - this->setInsertPolicy(QComboBox::NoInsert); - this->completer()->setCompletionMode(QCompleter::PopupCompletion); - this->completer()->setFilterMode(Qt::MatchContains); - this->setIconSize(QSize(25, 25)); - -// WallClock time0 = current_time(); - - // A more optimized version. - QStringList list; - if (display_names == nullptr){ - for (const std::string& slug : slugs){ - list.append(QString::fromStdString(get_pokemon_name(slug).display_name())); - } - }else{ - for (const std::string& slug : slugs){ - auto it = display_names->find(slug); - if (it == display_names->end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "In display_names slug not found: " + slug); - } - list.append(QString::fromStdString(it->second)); - } - } - if (extra_names && extra_name_list){ - for(const std::string& slug : *extra_name_list){ - const auto it = extra_names->find(slug); - if (it == extra_names->end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Extra slug not found: " + slug); - } - list.append(QString::fromStdString(it->second.first)); - } - } - this->addItems(list); - - // Initialize the widget to at least select sth. - if (slugs.size() > 0){ - this->setCurrentIndex(0); - } - - // Set the widget to select the pokemon `current_slug`. - for (size_t index = 0; index < slugs.size(); index++){ - const std::string& slug = slugs[index]; - - const SpriteDatabase::Sprite* sprite = icons.get_nothrow(slug); - if (sprite == nullptr){ - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - QPixmap pixmap = QPixmap::fromImage(sprite->icon.to_QImage_ref()); - this->setItemIcon((int)index, pixmap); - } - - if (slug == current_slug){ - this->setCurrentIndex((int)index); - } - } - if (extra_names && extra_name_list){ - for (size_t index = 0; index < extra_name_list->size(); index++){ - const std::string& slug = extra_name_list->at(index); - const auto it = extra_names->find(slug); - if (it == extra_names->end()){ - global_logger_tagged().log("Missing sprite for extra slug: " + slug, COLOR_RED); - }else{ - this->setItemIcon((int)(index + slugs.size()), it->second.second); - } - - if (slug == current_slug){ - this->setCurrentIndex((int)(index + slugs.size())); - } - } - } - -// WallClock time3 = current_time(); -// cout << std::chrono::duration_cast(time3 - time0).count() / 1000. << endl; - - update_size_cache(); -} - - - - -std::string NameSelectWidget::slug() const{ - std::string current_text = currentText().toStdString(); - if (m_extra_display_name_to_slug){ - auto it = m_extra_display_name_to_slug->find(current_text); - if (it != m_extra_display_name_to_slug->end()){ - return it->second; - } - } - if (m_display_name_to_slug){ - auto it = m_display_name_to_slug->find(current_text); - if (it != m_display_name_to_slug->end()){ - return it->second; - } - return PokemonNames::NULL_SLUG; - } - return parse_pokemon_name_nothrow(current_text); -} - - - - - -} -} +/* Pokemon Name Select Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon_NameSelectWidget.h" + +//#include "Common/Cpp/Time.h" +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Pokemon{ + +NameSelectWidget::NameSelectWidget( + QWidget& parent, + const SpriteDatabase& icons, + const std::vector& slugs, + const std::string& current_slug, + const std::map* display_names, + const std::map* display_name_to_slug, + const std::map>* extra_names, + const std::vector* extra_name_list, + const std::map* extra_display_name_to_slug +) + : NoWheelComboBox(&parent) + , m_display_name_to_slug(display_name_to_slug) + , m_extra_display_name_to_slug(extra_display_name_to_slug) +{ + this->setEditable(true); + this->setInsertPolicy(QComboBox::NoInsert); + this->completer()->setCompletionMode(QCompleter::PopupCompletion); + this->completer()->setFilterMode(Qt::MatchContains); + this->setIconSize(QSize(25, 25)); + +// WallClock time0 = current_time(); + + // A more optimized version. + QStringList list; + if (display_names == nullptr){ + for (const std::string& slug : slugs){ + list.append(QString::fromStdString(get_pokemon_name(slug).display_name())); + } + }else{ + for (const std::string& slug : slugs){ + auto it = display_names->find(slug); + if (it == display_names->end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "In display_names slug not found: " + slug); + } + list.append(QString::fromStdString(it->second)); + } + } + if (extra_names && extra_name_list){ + for(const std::string& slug : *extra_name_list){ + const auto it = extra_names->find(slug); + if (it == extra_names->end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Extra slug not found: " + slug); + } + list.append(QString::fromStdString(it->second.first)); + } + } + this->addItems(list); + + // Initialize the widget to at least select sth. + if (slugs.size() > 0){ + this->setCurrentIndex(0); + } + + // Set the widget to select the pokemon `current_slug`. + for (size_t index = 0; index < slugs.size(); index++){ + const std::string& slug = slugs[index]; + + const SpriteDatabase::Sprite* sprite = icons.get_nothrow(slug); + if (sprite == nullptr){ + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + QPixmap pixmap = QPixmap::fromImage(sprite->icon.to_QImage_ref()); + this->setItemIcon((int)index, pixmap); + } + + if (slug == current_slug){ + this->setCurrentIndex((int)index); + } + } + if (extra_names && extra_name_list){ + for (size_t index = 0; index < extra_name_list->size(); index++){ + const std::string& slug = extra_name_list->at(index); + const auto it = extra_names->find(slug); + if (it == extra_names->end()){ + global_logger_tagged().log("Missing sprite for extra slug: " + slug, COLOR_RED); + }else{ + this->setItemIcon((int)(index + slugs.size()), it->second.second); + } + + if (slug == current_slug){ + this->setCurrentIndex((int)(index + slugs.size())); + } + } + } + +// WallClock time3 = current_time(); +// cout << std::chrono::duration_cast(time3 - time0).count() / 1000. << endl; + + update_size_cache(); +} + + + + +std::string NameSelectWidget::slug() const{ + std::string current_text = currentText().toStdString(); + if (m_extra_display_name_to_slug){ + auto it = m_extra_display_name_to_slug->find(current_text); + if (it != m_extra_display_name_to_slug->end()){ + return it->second; + } + } + if (m_display_name_to_slug){ + auto it = m_display_name_to_slug->find(current_text); + if (it != m_display_name_to_slug->end()){ + return it->second; + } + return PokemonNames::NULL_SLUG; + } + return parse_pokemon_name_nothrow(current_text); +} + + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.h index ea1fb35b5b..0b666fa7a2 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_NameSelectWidget.h @@ -1,53 +1,53 @@ -/* Pokemon Name Select Widget - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonNameSelectWidget_H -#define PokemonAutomation_Pokemon_PokemonNameSelectWidget_H - -#include "Common/Qt/NoWheelComboBox.h" -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -// A widget to select a pokemon -class NameSelectWidget : public NoWheelComboBox{ -public: - // icons: pokemon slug -> icon. This map can be larger than the list of pokemon displayed on the widget. - // slugs: a list of pokemon slugs to choose from on the widget. - // current_slug: current selected pokemon - // display_names: if not nullptr, the mapping from slug to display name. By default, it uses - // Pokemon/Resources/Pokemon_PokemonNames.h:get_pokemon_name() to get display name. - // display_name_to_slug: if not nullptr, the mapping from display name to slug. By default, it uses - // Pokemon/Resources/Pokemon_PokemonNames.h:parse_pokemon_name_nothrow() to get slug from display name. - // extra_names: in rare cases we may add names that are not pokemon into the widget (like MMOs in LA). - // `extra_names` gives the mapping from the slug of the extra names to their display names and icons. - // extra_name_list: list of extra name slugs to display on the widget, after the pokemon from `slugs`. - // extra_display_name_to_slug: the mapping from the display name of the extra names to their slugs. - NameSelectWidget( - QWidget& parent, - const SpriteDatabase& icons, - const std::vector& slugs, - const std::string& current_slug, - const std::map* display_names = nullptr, - const std::map* display_name_to_slug = nullptr, - const std::map>* extra_names = nullptr, - const std::vector* extra_name_list = nullptr, - const std::map* extra_display_name_to_slug = nullptr - ); - - std::string slug() const; - -private: - const std::map* m_display_name_to_slug = nullptr; - const std::map* m_extra_display_name_to_slug = nullptr; -}; - - - -} -} -#endif +/* Pokemon Name Select Widget + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonNameSelectWidget_H +#define PokemonAutomation_Pokemon_PokemonNameSelectWidget_H + +#include "Common/Qt/NoWheelComboBox.h" +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +// A widget to select a pokemon +class NameSelectWidget : public NoWheelComboBox{ +public: + // icons: pokemon slug -> icon. This map can be larger than the list of pokemon displayed on the widget. + // slugs: a list of pokemon slugs to choose from on the widget. + // current_slug: current selected pokemon + // display_names: if not nullptr, the mapping from slug to display name. By default, it uses + // Pokemon/Resources/Pokemon_PokemonNames.h:get_pokemon_name() to get display name. + // display_name_to_slug: if not nullptr, the mapping from display name to slug. By default, it uses + // Pokemon/Resources/Pokemon_PokemonNames.h:parse_pokemon_name_nothrow() to get slug from display name. + // extra_names: in rare cases we may add names that are not pokemon into the widget (like MMOs in LA). + // `extra_names` gives the mapping from the slug of the extra names to their display names and icons. + // extra_name_list: list of extra name slugs to display on the widget, after the pokemon from `slugs`. + // extra_display_name_to_slug: the mapping from the display name of the extra names to their slugs. + NameSelectWidget( + QWidget& parent, + const SpriteDatabase& icons, + const std::vector& slugs, + const std::string& current_slug, + const std::map* display_names = nullptr, + const std::map* display_name_to_slug = nullptr, + const std::map>* extra_names = nullptr, + const std::vector* extra_name_list = nullptr, + const std::map* extra_display_name_to_slug = nullptr + ); + + std::string slug() const; + +private: + const std::map* m_display_name_to_slug = nullptr; + const std::map* m_extra_display_name_to_slug = nullptr; +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp index 726eadf61c..d40d936386 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.cpp @@ -1,411 +1,411 @@ -/* Egg Hatch Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon_StatsHuntFilter.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace Pokemon{ - -std::string gender_to_string(StatsHuntGenderFilter gender){ - const char * names[] = { - "Any", - "Male", - "Female", - "Genderless", - }; - return names[int(gender)]; -} - - -const EnumDropdownDatabase& StatsHuntAction_Database(){ - static const EnumDropdownDatabase database({ - {StatsHuntAction::StopProgram, "stop", "Stop Program"}, - {StatsHuntAction::Keep, "keep", "Keep"}, -// {EggHatchAction::Release, "release", "Release"}, - }); - return database; -} -const EnumDropdownDatabase& StatsHuntShinyFilter_Database(){ - static const EnumDropdownDatabase database({ - {StatsHuntShinyFilter::Anything, "anything", "Anything"}, - {StatsHuntShinyFilter::NotShiny, "not-shiny", "Not Shiny"}, - {StatsHuntShinyFilter::Shiny, "shiny", "Shiny"}, - }); - return database; -} -const EnumDropdownDatabase& StatsHuntGenderFilter_Database(){ - static const EnumDropdownDatabase database({ - {StatsHuntGenderFilter::Any, "any", "Any"}, - {StatsHuntGenderFilter::Male, "male", "Male"}, - {StatsHuntGenderFilter::Female, "female", "Female"}, -// {EggHatchGenderFilter::Genderless, "genderless", "Genderless"}, - }); - return database; -} - - - - -const char* StatsHuntIvJudgeFilterTable_Label_Eggs = - "Actions Table:
" - "If a hatchling matches one of these filters, the specified action will be performed. " - "Otherwise, it will be released. " - "If multiple entries apply and have conflicting actions, the program will stop.
" - "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above."; - -const char* StatsHuntIvJudgeFilterTable_Label_Regular = - "Stop Conditions:
" - "If the Pok\u00e9mon matches one of these filters, the program will stop.
" - "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above."; - - - - - - -StatsHuntRowMisc::StatsHuntRowMisc(const StatsHuntMiscFeatureFlags& p_feature_flags) - : feature_flags(p_feature_flags) - , action( - StatsHuntAction_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - feature_flags.action - ? StatsHuntAction::Keep - : StatsHuntAction::StopProgram - ) - , shiny(StatsHuntShinyFilter_Database(), LockMode::UNLOCK_WHILE_RUNNING, StatsHuntShinyFilter::Anything) - , gender(StatsHuntGenderFilter_Database(), LockMode::UNLOCK_WHILE_RUNNING, StatsHuntGenderFilter::Any) - , nature(NatureCheckerFilter_Database(), LockMode::UNLOCK_WHILE_RUNNING, NatureCheckerFilter::Any) -{} -void StatsHuntRowMisc::set(const StatsHuntRowMisc& x){ - action.set(x.action); - shiny.set(x.shiny); - gender.set(x.gender); - nature.set(x.nature); -} -bool StatsHuntRowMisc::matches( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature -) const{ - // Check the shiny filter. - switch (this->shiny){ - case StatsHuntShinyFilter::Anything: - break; - case StatsHuntShinyFilter::NotShiny: - if (shiny){ - return false; - } - break; - case StatsHuntShinyFilter::Shiny: - if (!shiny){ - return false; - } - break; - } - - StatsHuntGenderFilter filter_gender = this->gender; - if (filter_gender != gender && filter_gender != StatsHuntGenderFilter::Any){ - return false; - } - - if (!NatureChecker_filter_match(this->nature, nature)){ - return false; - } - - return true; -} - - -StatsHuntIvJudgeFilterRow::StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , misc(static_cast(parent_table).feature_flags) - , iv_hp(IvJudgeFilter::Anything) - , iv_atk(IvJudgeFilter::Anything) - , iv_def(IvJudgeFilter::Anything) - , iv_spatk(IvJudgeFilter::Anything) - , iv_spdef(IvJudgeFilter::Anything) - , iv_speed(IvJudgeFilter::Anything) -{ - if (misc.feature_flags.action) PA_ADD_OPTION(misc.action); - if (misc.feature_flags.shiny) PA_ADD_OPTION(misc.shiny); - if (misc.feature_flags.gender) PA_ADD_OPTION(misc.gender); - if (misc.feature_flags.nature) PA_ADD_OPTION(misc.nature); - PA_ADD_OPTION(iv_hp); - PA_ADD_OPTION(iv_atk); - PA_ADD_OPTION(iv_def); - PA_ADD_OPTION(iv_spatk); - PA_ADD_OPTION(iv_spdef); - PA_ADD_OPTION(iv_speed); -} -StatsHuntIvJudgeFilterRow::StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table, StatsHuntShinyFilter p_shiny) - : StatsHuntIvJudgeFilterRow(parent_table) -{ - misc.shiny.set(p_shiny); -} -std::unique_ptr StatsHuntIvJudgeFilterRow::clone() const{ - std::unique_ptr ret(new StatsHuntIvJudgeFilterRow(parent())); - ret->misc.set(misc); - ret->iv_hp.set(iv_hp); - ret->iv_atk.set(iv_atk); - ret->iv_def.set(iv_def); - ret->iv_spatk.set(iv_spatk); - ret->iv_spdef.set(iv_spdef); - ret->iv_speed.set(iv_speed); - return ret; -} -bool StatsHuntIvJudgeFilterRow::matches( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvJudgeReader::Results& IVs -) const{ - if (!misc.matches(shiny, gender, nature)){ - return false; - } - - // Check all the IV filters. - if (!IvJudge_filter_match(iv_hp, IVs.hp)) return false; - if (!IvJudge_filter_match(iv_atk, IVs.attack)) return false; - if (!IvJudge_filter_match(iv_def, IVs.defense)) return false; - if (!IvJudge_filter_match(iv_spatk, IVs.spatk)) return false; - if (!IvJudge_filter_match(iv_spdef, IVs.spdef)) return false; - if (!IvJudge_filter_match(iv_speed, IVs.speed)) return false; - - return true; -} - -StatsHuntIvJudgeFilterTable::StatsHuntIvJudgeFilterTable( - const std::string& label, - const StatsHuntMiscFeatureFlags& p_feature_flags -) - : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) - , feature_flags(p_feature_flags) -{ - set_default(make_defaults()); - restore_defaults(); -} -std::vector StatsHuntIvJudgeFilterTable::make_header() const{ - std::vector ret; - if (feature_flags.action){ - ret.emplace_back("Action"); - } - if (feature_flags.shiny){ - ret.emplace_back("Shininess"); - } - if (feature_flags.gender){ - ret.emplace_back("Gender"); - } - if (feature_flags.nature){ - ret.emplace_back("Nature"); - } - - ret.emplace_back("HP"); - ret.emplace_back("Attack"); - ret.emplace_back("Defense"); - ret.emplace_back("Sp. Attack"); - ret.emplace_back("Sp. Defense"); - ret.emplace_back("Speed"); - - return ret; -} -std::vector> StatsHuntIvJudgeFilterTable::make_defaults(){ - std::vector> ret; - if (feature_flags.shiny){ - ret.emplace_back(new StatsHuntIvJudgeFilterRow(*this, StatsHuntShinyFilter::Shiny)); - } - return ret; -} -StatsHuntAction StatsHuntIvJudgeFilterTable::get_action( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvJudgeReader::Results& IVs -) const{ - StatsHuntAction action = StatsHuntAction::Discard; - std::vector> list = copy_snapshot(); - for (size_t c = 0; c < list.size(); c++){ - const StatsHuntIvJudgeFilterRow& filter = *list[c]; - - if (!filter.matches(shiny, gender, nature, IVs)){ - continue; - } - - StatsHuntAction filter_action = filter.misc.action; - - // No action matched so far. Take the current action and continue. - if (action == StatsHuntAction::Discard){ - action = filter_action; - continue; - } - - // Conflicting actions. - if (action != filter_action){ - global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); - return StatsHuntAction::StopProgram; - } - } - return action; -} - - - - - -const char* StatsHuntIvRangeFilterTable_Label_Regular = - "Stop Conditions:
" - "If the Pok\u00e9mon matches one of these filters, the program will stop.
" - "Partially overlapping IV ranges will count as a match. So if a filter is for 0-1, but the IV calculation returns a range 1-2, it will count."; - - - -StatsHuntIvRangeFilterRow::StatsHuntIvRangeFilterRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , misc(static_cast(parent_table).feature_flags) - , iv_hp(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) - , iv_atk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) - , iv_def(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) - , iv_spatk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) - , iv_spdef(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) - , iv_speed(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) -{ - if (misc.feature_flags.action) PA_ADD_OPTION(misc.action); - if (misc.feature_flags.shiny) PA_ADD_OPTION(misc.shiny); - if (misc.feature_flags.gender) PA_ADD_OPTION(misc.gender); - if (misc.feature_flags.nature) PA_ADD_OPTION(misc.nature); - PA_ADD_OPTION(iv_hp); - PA_ADD_OPTION(iv_atk); - PA_ADD_OPTION(iv_def); - PA_ADD_OPTION(iv_spatk); - PA_ADD_OPTION(iv_spdef); - PA_ADD_OPTION(iv_speed); -} -std::unique_ptr StatsHuntIvRangeFilterRow::clone() const{ - std::unique_ptr ret(new StatsHuntIvRangeFilterRow(parent())); - ret->misc.set(misc); - ret->iv_hp.set(iv_hp); - ret->iv_atk.set(iv_atk); - ret->iv_def.set(iv_def); - ret->iv_spatk.set(iv_spatk); - ret->iv_spdef.set(iv_spdef); - ret->iv_speed.set(iv_speed); - return ret; -} -bool StatsHuntIvRangeFilterRow::match_iv(const IvRange& desired, const IvRange& actual){ - if (desired.low == 0 && desired.high == 31){ - return true; - } - if (actual.high < desired.low){ - return false; - } - if (desired.high < actual.low){ - return false; - } - return true; -} -bool StatsHuntIvRangeFilterRow::match_iv(const IntegerRangeCell& desired, const IvRange& actual){ - uint8_t lo, hi; - desired.current_values(lo, hi); - return match_iv(IvRange{(int8_t)lo, (int8_t)hi}, actual); -} -bool StatsHuntIvRangeFilterRow::matches( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvRanges& IVs -) const{ - if (!misc.matches(shiny, gender, nature)){ - return false; - } - - if (!match_iv(iv_hp, IVs.hp)) return false; - if (!match_iv(iv_atk, IVs.attack)) return false; - if (!match_iv(iv_def, IVs.defense)) return false; - if (!match_iv(iv_spatk, IVs.spatk)) return false; - if (!match_iv(iv_spdef, IVs.spdef)) return false; - if (!match_iv(iv_speed, IVs.speed)) return false; - - return true; -} - - -StatsHuntIvRangeFilterTable::StatsHuntIvRangeFilterTable( - const std::string& label, - const StatsHuntMiscFeatureFlags& p_feature_flags -) - : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) - , feature_flags(p_feature_flags) -{ -// set_default(make_defaults()); -// restore_defaults(); -} -std::vector StatsHuntIvRangeFilterTable::make_header() const{ - std::vector ret; - if (feature_flags.action){ - ret.emplace_back("Action"); - } - if (feature_flags.shiny){ - ret.emplace_back("Shininess"); - } - if (feature_flags.gender){ - ret.emplace_back("Gender"); - } - if (feature_flags.nature){ - ret.emplace_back("Nature"); - } - - ret.emplace_back("HP"); - ret.emplace_back("Atk"); - ret.emplace_back("Def"); - ret.emplace_back("SpAtk"); - ret.emplace_back("SpDef"); - ret.emplace_back("Spd"); - - return ret; -} -StatsHuntAction StatsHuntIvRangeFilterTable::get_action( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvRanges& IVs -) const{ - StatsHuntAction action = StatsHuntAction::Discard; - std::vector> list = copy_snapshot(); - for (size_t c = 0; c < list.size(); c++){ - const StatsHuntIvRangeFilterRow& filter = *list[c]; - - if (!filter.matches(shiny, gender, nature, IVs)){ - continue; - } - - StatsHuntAction filter_action = filter.misc.action; - - // No action matched so far. Take the current action and continue. - if (action == StatsHuntAction::Discard){ - action = filter_action; - continue; - } - - // Conflicting actions. - if (action != filter_action){ - global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); - return StatsHuntAction::StopProgram; - } - } - return action; -} - - - - - - -} -} +/* Egg Hatch Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon_StatsHuntFilter.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace Pokemon{ + +std::string gender_to_string(StatsHuntGenderFilter gender){ + const char * names[] = { + "Any", + "Male", + "Female", + "Genderless", + }; + return names[int(gender)]; +} + + +const EnumDropdownDatabase& StatsHuntAction_Database(){ + static const EnumDropdownDatabase database({ + {StatsHuntAction::StopProgram, "stop", "Stop Program"}, + {StatsHuntAction::Keep, "keep", "Keep"}, +// {EggHatchAction::Release, "release", "Release"}, + }); + return database; +} +const EnumDropdownDatabase& StatsHuntShinyFilter_Database(){ + static const EnumDropdownDatabase database({ + {StatsHuntShinyFilter::Anything, "anything", "Anything"}, + {StatsHuntShinyFilter::NotShiny, "not-shiny", "Not Shiny"}, + {StatsHuntShinyFilter::Shiny, "shiny", "Shiny"}, + }); + return database; +} +const EnumDropdownDatabase& StatsHuntGenderFilter_Database(){ + static const EnumDropdownDatabase database({ + {StatsHuntGenderFilter::Any, "any", "Any"}, + {StatsHuntGenderFilter::Male, "male", "Male"}, + {StatsHuntGenderFilter::Female, "female", "Female"}, +// {EggHatchGenderFilter::Genderless, "genderless", "Genderless"}, + }); + return database; +} + + + + +const char* StatsHuntIvJudgeFilterTable_Label_Eggs = + "Actions Table:
" + "If a hatchling matches one of these filters, the specified action will be performed. " + "Otherwise, it will be released. " + "If multiple entries apply and have conflicting actions, the program will stop.
" + "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above."; + +const char* StatsHuntIvJudgeFilterTable_Label_Regular = + "Stop Conditions:
" + "If the Pok\u00e9mon matches one of these filters, the program will stop.
" + "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above."; + + + + + + +StatsHuntRowMisc::StatsHuntRowMisc(const StatsHuntMiscFeatureFlags& p_feature_flags) + : feature_flags(p_feature_flags) + , action( + StatsHuntAction_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + feature_flags.action + ? StatsHuntAction::Keep + : StatsHuntAction::StopProgram + ) + , shiny(StatsHuntShinyFilter_Database(), LockMode::UNLOCK_WHILE_RUNNING, StatsHuntShinyFilter::Anything) + , gender(StatsHuntGenderFilter_Database(), LockMode::UNLOCK_WHILE_RUNNING, StatsHuntGenderFilter::Any) + , nature(NatureCheckerFilter_Database(), LockMode::UNLOCK_WHILE_RUNNING, NatureCheckerFilter::Any) +{} +void StatsHuntRowMisc::set(const StatsHuntRowMisc& x){ + action.set(x.action); + shiny.set(x.shiny); + gender.set(x.gender); + nature.set(x.nature); +} +bool StatsHuntRowMisc::matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature +) const{ + // Check the shiny filter. + switch (this->shiny){ + case StatsHuntShinyFilter::Anything: + break; + case StatsHuntShinyFilter::NotShiny: + if (shiny){ + return false; + } + break; + case StatsHuntShinyFilter::Shiny: + if (!shiny){ + return false; + } + break; + } + + StatsHuntGenderFilter filter_gender = this->gender; + if (filter_gender != gender && filter_gender != StatsHuntGenderFilter::Any){ + return false; + } + + if (!NatureChecker_filter_match(this->nature, nature)){ + return false; + } + + return true; +} + + +StatsHuntIvJudgeFilterRow::StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , misc(static_cast(parent_table).feature_flags) + , iv_hp(IvJudgeFilter::Anything) + , iv_atk(IvJudgeFilter::Anything) + , iv_def(IvJudgeFilter::Anything) + , iv_spatk(IvJudgeFilter::Anything) + , iv_spdef(IvJudgeFilter::Anything) + , iv_speed(IvJudgeFilter::Anything) +{ + if (misc.feature_flags.action) PA_ADD_OPTION(misc.action); + if (misc.feature_flags.shiny) PA_ADD_OPTION(misc.shiny); + if (misc.feature_flags.gender) PA_ADD_OPTION(misc.gender); + if (misc.feature_flags.nature) PA_ADD_OPTION(misc.nature); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} +StatsHuntIvJudgeFilterRow::StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table, StatsHuntShinyFilter p_shiny) + : StatsHuntIvJudgeFilterRow(parent_table) +{ + misc.shiny.set(p_shiny); +} +std::unique_ptr StatsHuntIvJudgeFilterRow::clone() const{ + std::unique_ptr ret(new StatsHuntIvJudgeFilterRow(parent())); + ret->misc.set(misc); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} +bool StatsHuntIvJudgeFilterRow::matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvJudgeReader::Results& IVs +) const{ + if (!misc.matches(shiny, gender, nature)){ + return false; + } + + // Check all the IV filters. + if (!IvJudge_filter_match(iv_hp, IVs.hp)) return false; + if (!IvJudge_filter_match(iv_atk, IVs.attack)) return false; + if (!IvJudge_filter_match(iv_def, IVs.defense)) return false; + if (!IvJudge_filter_match(iv_spatk, IVs.spatk)) return false; + if (!IvJudge_filter_match(iv_spdef, IVs.spdef)) return false; + if (!IvJudge_filter_match(iv_speed, IVs.speed)) return false; + + return true; +} + +StatsHuntIvJudgeFilterTable::StatsHuntIvJudgeFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags +) + : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) + , feature_flags(p_feature_flags) +{ + set_default(make_defaults()); + restore_defaults(); +} +std::vector StatsHuntIvJudgeFilterTable::make_header() const{ + std::vector ret; + if (feature_flags.action){ + ret.emplace_back("Action"); + } + if (feature_flags.shiny){ + ret.emplace_back("Shininess"); + } + if (feature_flags.gender){ + ret.emplace_back("Gender"); + } + if (feature_flags.nature){ + ret.emplace_back("Nature"); + } + + ret.emplace_back("HP"); + ret.emplace_back("Attack"); + ret.emplace_back("Defense"); + ret.emplace_back("Sp. Attack"); + ret.emplace_back("Sp. Defense"); + ret.emplace_back("Speed"); + + return ret; +} +std::vector> StatsHuntIvJudgeFilterTable::make_defaults(){ + std::vector> ret; + if (feature_flags.shiny){ + ret.emplace_back(new StatsHuntIvJudgeFilterRow(*this, StatsHuntShinyFilter::Shiny)); + } + return ret; +} +StatsHuntAction StatsHuntIvJudgeFilterTable::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvJudgeReader::Results& IVs +) const{ + StatsHuntAction action = StatsHuntAction::Discard; + std::vector> list = copy_snapshot(); + for (size_t c = 0; c < list.size(); c++){ + const StatsHuntIvJudgeFilterRow& filter = *list[c]; + + if (!filter.matches(shiny, gender, nature, IVs)){ + continue; + } + + StatsHuntAction filter_action = filter.misc.action; + + // No action matched so far. Take the current action and continue. + if (action == StatsHuntAction::Discard){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); + return StatsHuntAction::StopProgram; + } + } + return action; +} + + + + + +const char* StatsHuntIvRangeFilterTable_Label_Regular = + "Stop Conditions:
" + "If the Pok\u00e9mon matches one of these filters, the program will stop.
" + "Partially overlapping IV ranges will count as a match. So if a filter is for 0-1, but the IV calculation returns a range 1-2, it will count."; + + + +StatsHuntIvRangeFilterRow::StatsHuntIvRangeFilterRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , misc(static_cast(parent_table).feature_flags) + , iv_hp(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_atk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_def(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spatk(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_spdef(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) + , iv_speed(LockMode::UNLOCK_WHILE_RUNNING, 0, 31, 0, 0, 0, 31, 31, 31) +{ + if (misc.feature_flags.action) PA_ADD_OPTION(misc.action); + if (misc.feature_flags.shiny) PA_ADD_OPTION(misc.shiny); + if (misc.feature_flags.gender) PA_ADD_OPTION(misc.gender); + if (misc.feature_flags.nature) PA_ADD_OPTION(misc.nature); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} +std::unique_ptr StatsHuntIvRangeFilterRow::clone() const{ + std::unique_ptr ret(new StatsHuntIvRangeFilterRow(parent())); + ret->misc.set(misc); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} +bool StatsHuntIvRangeFilterRow::match_iv(const IvRange& desired, const IvRange& actual){ + if (desired.low == 0 && desired.high == 31){ + return true; + } + if (actual.high < desired.low){ + return false; + } + if (desired.high < actual.low){ + return false; + } + return true; +} +bool StatsHuntIvRangeFilterRow::match_iv(const IntegerRangeCell& desired, const IvRange& actual){ + uint8_t lo, hi; + desired.current_values(lo, hi); + return match_iv(IvRange{(int8_t)lo, (int8_t)hi}, actual); +} +bool StatsHuntIvRangeFilterRow::matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvRanges& IVs +) const{ + if (!misc.matches(shiny, gender, nature)){ + return false; + } + + if (!match_iv(iv_hp, IVs.hp)) return false; + if (!match_iv(iv_atk, IVs.attack)) return false; + if (!match_iv(iv_def, IVs.defense)) return false; + if (!match_iv(iv_spatk, IVs.spatk)) return false; + if (!match_iv(iv_spdef, IVs.spdef)) return false; + if (!match_iv(iv_speed, IVs.speed)) return false; + + return true; +} + + +StatsHuntIvRangeFilterTable::StatsHuntIvRangeFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags +) + : EditableTableOption_t(label, LockMode::UNLOCK_WHILE_RUNNING) + , feature_flags(p_feature_flags) +{ +// set_default(make_defaults()); +// restore_defaults(); +} +std::vector StatsHuntIvRangeFilterTable::make_header() const{ + std::vector ret; + if (feature_flags.action){ + ret.emplace_back("Action"); + } + if (feature_flags.shiny){ + ret.emplace_back("Shininess"); + } + if (feature_flags.gender){ + ret.emplace_back("Gender"); + } + if (feature_flags.nature){ + ret.emplace_back("Nature"); + } + + ret.emplace_back("HP"); + ret.emplace_back("Atk"); + ret.emplace_back("Def"); + ret.emplace_back("SpAtk"); + ret.emplace_back("SpDef"); + ret.emplace_back("Spd"); + + return ret; +} +StatsHuntAction StatsHuntIvRangeFilterTable::get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvRanges& IVs +) const{ + StatsHuntAction action = StatsHuntAction::Discard; + std::vector> list = copy_snapshot(); + for (size_t c = 0; c < list.size(); c++){ + const StatsHuntIvRangeFilterRow& filter = *list[c]; + + if (!filter.matches(shiny, gender, nature, IVs)){ + continue; + } + + StatsHuntAction filter_action = filter.misc.action; + + // No action matched so far. Take the current action and continue. + if (action == StatsHuntAction::Discard){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); + return StatsHuntAction::StopProgram; + } + } + return action; +} + + + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.h index 1f8f755820..dd76759052 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsHuntFilter.h @@ -1,187 +1,187 @@ -/* Stats Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_StatsFilter_H -#define PokemonAutomation_Pokemon_StatsFilter_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/IntegerRangeOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -//#include "Pokemon/Pokemon_IVChecker.h" -#include "Pokemon/Pokemon_NatureChecker.h" -#include "Pokemon/Pokemon_StatsCalculation.h" -#include "Pokemon/Options/Pokemon_IvJudgeOption.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" -#include "Pokemon/Inference/Pokemon_NatureReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -enum class StatsHuntAction{ - StopProgram, - Keep, - Discard, -}; - -enum class StatsHuntShinyFilter{ - Anything, - NotShiny, - Shiny, -}; - -enum class StatsHuntGenderFilter{ - Any, - Male, - Female, - Genderless -}; -std::string gender_to_string(StatsHuntGenderFilter gender); - - - -// Preset labels. -extern const char* StatsHuntIvJudgeFilterTable_Label_Eggs; -extern const char* StatsHuntIvJudgeFilterTable_Label_Regular; - - - - -struct StatsHuntMiscFeatureFlags{ - bool action = false; - bool shiny = false; - bool gender = false; - bool nature = false; -}; -struct StatsHuntRowMisc{ - StatsHuntRowMisc(const StatsHuntMiscFeatureFlags& p_feature_flags); - void set(const StatsHuntRowMisc& x); - - bool matches( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature - ) const; - - const StatsHuntMiscFeatureFlags& feature_flags; - - EnumDropdownCell action; - EnumDropdownCell shiny; - EnumDropdownCell gender; - EnumDropdownCell nature; -}; - - - - -class StatsHuntIvJudgeFilterTable; -class StatsHuntIvJudgeFilterRow : public EditableTableRow{ -public: - StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table); - StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table, StatsHuntShinyFilter p_shiny); - virtual std::unique_ptr clone() const override; - - bool matches( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvJudgeReader::Results& IVs - ) const; - -public: - StatsHuntRowMisc misc; - - IVJudgeFilterCell iv_hp; - IVJudgeFilterCell iv_atk; - IVJudgeFilterCell iv_def; - IVJudgeFilterCell iv_spatk; - IVJudgeFilterCell iv_spdef; - IVJudgeFilterCell iv_speed; -}; -class StatsHuntIvJudgeFilterTable : public EditableTableOption_t{ -public: - StatsHuntIvJudgeFilterTable( - const std::string& label, - const StatsHuntMiscFeatureFlags& p_feature_flags - ); - virtual std::vector make_header() const override; - std::vector> make_defaults(); - - StatsHuntAction get_action( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvJudgeReader::Results& IVs - ) const; - -public: - const StatsHuntMiscFeatureFlags feature_flags; -}; - - - - - - - - -// Preset labels. -extern const char* StatsHuntIvRangeFilterTable_Label_Regular; - - -class StatsHuntIvRangeFilterRow : public EditableTableRow{ -public: - StatsHuntIvRangeFilterRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - - bool matches( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvRanges& IVs - ) const; - -private: - static bool match_iv(const IvRange& desired, const IvRange& actual); - static bool match_iv(const IntegerRangeCell& desired, const IvRange& actual); - -public: - StatsHuntRowMisc misc; - - IntegerRangeCell iv_hp; - IntegerRangeCell iv_atk; - IntegerRangeCell iv_def; - IntegerRangeCell iv_spatk; - IntegerRangeCell iv_spdef; - IntegerRangeCell iv_speed; -}; -class StatsHuntIvRangeFilterTable : public EditableTableOption_t{ -public: - StatsHuntIvRangeFilterTable( - const std::string& label, - const StatsHuntMiscFeatureFlags& p_feature_flags - ); - virtual std::vector make_header() const override; - - StatsHuntAction get_action( - bool shiny, - StatsHuntGenderFilter gender, - NatureCheckerValue nature, - const IvRanges& IVs - ) const; - -public: - const StatsHuntMiscFeatureFlags feature_flags; -}; - - - - - -} -} -#endif +/* Stats Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StatsFilter_H +#define PokemonAutomation_Pokemon_StatsFilter_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/IntegerRangeOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +//#include "Pokemon/Pokemon_IVChecker.h" +#include "Pokemon/Pokemon_NatureChecker.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "Pokemon/Options/Pokemon_IvJudgeOption.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" +#include "Pokemon/Inference/Pokemon_NatureReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class StatsHuntAction{ + StopProgram, + Keep, + Discard, +}; + +enum class StatsHuntShinyFilter{ + Anything, + NotShiny, + Shiny, +}; + +enum class StatsHuntGenderFilter{ + Any, + Male, + Female, + Genderless +}; +std::string gender_to_string(StatsHuntGenderFilter gender); + + + +// Preset labels. +extern const char* StatsHuntIvJudgeFilterTable_Label_Eggs; +extern const char* StatsHuntIvJudgeFilterTable_Label_Regular; + + + + +struct StatsHuntMiscFeatureFlags{ + bool action = false; + bool shiny = false; + bool gender = false; + bool nature = false; +}; +struct StatsHuntRowMisc{ + StatsHuntRowMisc(const StatsHuntMiscFeatureFlags& p_feature_flags); + void set(const StatsHuntRowMisc& x); + + bool matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature + ) const; + + const StatsHuntMiscFeatureFlags& feature_flags; + + EnumDropdownCell action; + EnumDropdownCell shiny; + EnumDropdownCell gender; + EnumDropdownCell nature; +}; + + + + +class StatsHuntIvJudgeFilterTable; +class StatsHuntIvJudgeFilterRow : public EditableTableRow{ +public: + StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table); + StatsHuntIvJudgeFilterRow(EditableTableOption& parent_table, StatsHuntShinyFilter p_shiny); + virtual std::unique_ptr clone() const override; + + bool matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvJudgeReader::Results& IVs + ) const; + +public: + StatsHuntRowMisc misc; + + IVJudgeFilterCell iv_hp; + IVJudgeFilterCell iv_atk; + IVJudgeFilterCell iv_def; + IVJudgeFilterCell iv_spatk; + IVJudgeFilterCell iv_spdef; + IVJudgeFilterCell iv_speed; +}; +class StatsHuntIvJudgeFilterTable : public EditableTableOption_t{ +public: + StatsHuntIvJudgeFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags + ); + virtual std::vector make_header() const override; + std::vector> make_defaults(); + + StatsHuntAction get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvJudgeReader::Results& IVs + ) const; + +public: + const StatsHuntMiscFeatureFlags feature_flags; +}; + + + + + + + + +// Preset labels. +extern const char* StatsHuntIvRangeFilterTable_Label_Regular; + + +class StatsHuntIvRangeFilterRow : public EditableTableRow{ +public: + StatsHuntIvRangeFilterRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + bool matches( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvRanges& IVs + ) const; + +private: + static bool match_iv(const IvRange& desired, const IvRange& actual); + static bool match_iv(const IntegerRangeCell& desired, const IvRange& actual); + +public: + StatsHuntRowMisc misc; + + IntegerRangeCell iv_hp; + IntegerRangeCell iv_atk; + IntegerRangeCell iv_def; + IntegerRangeCell iv_spatk; + IntegerRangeCell iv_spdef; + IntegerRangeCell iv_speed; +}; +class StatsHuntIvRangeFilterTable : public EditableTableOption_t{ +public: + StatsHuntIvRangeFilterTable( + const std::string& label, + const StatsHuntMiscFeatureFlags& p_feature_flags + ); + virtual std::vector make_header() const override; + + StatsHuntAction get_action( + bool shiny, + StatsHuntGenderFilter gender, + NatureCheckerValue nature, + const IvRanges& IVs + ) const; + +public: + const StatsHuntMiscFeatureFlags feature_flags; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).cpp b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).cpp index bd7caefa38..372f613a53 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).cpp +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).cpp @@ -1,107 +1,107 @@ -/* Stats Reset Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "Pokemon_StatsResetFilter.h" -#include "Pokemon_StatsHuntFilter.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -StatsResetFilterRow::StatsResetFilterRow() - : action(StatsHuntAction::StopProgram) - , nature(NatureCheckerFilter_Database(), LockMode::LOCK_WHILE_RUNNING, NatureCheckerFilter::Any) - , iv_hp(IvJudgeFilter::Anything) - , iv_atk(IvJudgeFilter::Anything) - , iv_def(IvJudgeFilter::Anything) - , iv_spatk(IvJudgeFilter::Anything) - , iv_spdef(IvJudgeFilter::Anything) - , iv_speed(IvJudgeFilter::Anything) -{ - PA_ADD_OPTION(nature); - PA_ADD_OPTION(iv_hp); - PA_ADD_OPTION(iv_atk); - PA_ADD_OPTION(iv_def); - PA_ADD_OPTION(iv_spatk); - PA_ADD_OPTION(iv_spdef); - PA_ADD_OPTION(iv_speed); -} - -std::unique_ptr StatsResetFilterRow::clone() const{ - std::unique_ptr ret(new StatsResetFilterRow()); - ret->nature.set(nature); - ret->iv_hp.set(iv_hp); - ret->iv_atk.set(iv_atk); - ret->iv_def.set(iv_def); - ret->iv_spatk.set(iv_spatk); - ret->iv_spdef.set(iv_spdef); - ret->iv_speed.set(iv_speed); - return ret; -} - -StatsResetFilterTable::StatsResetFilterTable() - : EditableTableOption_t( - "Actions Table:
" - "If the caught Pokemon matches one of these filters, the program will stop. " - "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above.", - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} -std::vector StatsResetFilterTable::make_header() const{ - return std::vector{ - "Nature", - "HP", - "Attack", - "Defense", - "Sp. Attack", - "Sp. Defense", - "Speed", - }; -} -std::vector> StatsResetFilterTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(new StatsResetFilterRow()); - return ret; -} - -StatsHuntAction StatsResetFilterTable::get_action(bool shiny, const IvJudgeReader::Results& IVs, NatureReader::Results nature) const{ - StatsHuntAction action = StatsHuntAction::Discard; - std::vector> list = copy_snapshot(); - for (size_t c = 0; c < list.size(); c++){ - const StatsResetFilterRow& filter = *list[c]; - - // Check all the IV filters. - if (!IvJudge_filter_match(filter.iv_hp, IVs.hp)) continue; - if (!IvJudge_filter_match(filter.iv_atk, IVs.attack)) continue; - if (!IvJudge_filter_match(filter.iv_def, IVs.defense)) continue; - if (!IvJudge_filter_match(filter.iv_spatk, IVs.spatk)) continue; - if (!IvJudge_filter_match(filter.iv_spdef, IVs.spdef)) continue; - if (!IvJudge_filter_match(filter.iv_speed, IVs.speed)) continue; - - if (!NatureChecker_filter_match(filter.nature, nature.nature)){ - continue; - } - - StatsHuntAction filter_action = filter.action; - - // No action matched so far. Take the current action and continue. - if (action == StatsHuntAction::Discard){ - action = filter_action; - continue; - } - - // Conflicting actions. - if (action != filter_action){ - global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); - return StatsHuntAction::StopProgram; - } - } - return action; -} - -} -} +/* Stats Reset Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "Pokemon_StatsResetFilter.h" +#include "Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +StatsResetFilterRow::StatsResetFilterRow() + : action(StatsHuntAction::StopProgram) + , nature(NatureCheckerFilter_Database(), LockMode::LOCK_WHILE_RUNNING, NatureCheckerFilter::Any) + , iv_hp(IvJudgeFilter::Anything) + , iv_atk(IvJudgeFilter::Anything) + , iv_def(IvJudgeFilter::Anything) + , iv_spatk(IvJudgeFilter::Anything) + , iv_spdef(IvJudgeFilter::Anything) + , iv_speed(IvJudgeFilter::Anything) +{ + PA_ADD_OPTION(nature); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} + +std::unique_ptr StatsResetFilterRow::clone() const{ + std::unique_ptr ret(new StatsResetFilterRow()); + ret->nature.set(nature); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} + +StatsResetFilterTable::StatsResetFilterTable() + : EditableTableOption_t( + "Actions Table:
" + "If the caught Pokemon matches one of these filters, the program will stop. " + "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above.", + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} +std::vector StatsResetFilterTable::make_header() const{ + return std::vector{ + "Nature", + "HP", + "Attack", + "Defense", + "Sp. Attack", + "Sp. Defense", + "Speed", + }; +} +std::vector> StatsResetFilterTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(new StatsResetFilterRow()); + return ret; +} + +StatsHuntAction StatsResetFilterTable::get_action(bool shiny, const IvJudgeReader::Results& IVs, NatureReader::Results nature) const{ + StatsHuntAction action = StatsHuntAction::Discard; + std::vector> list = copy_snapshot(); + for (size_t c = 0; c < list.size(); c++){ + const StatsResetFilterRow& filter = *list[c]; + + // Check all the IV filters. + if (!IvJudge_filter_match(filter.iv_hp, IVs.hp)) continue; + if (!IvJudge_filter_match(filter.iv_atk, IVs.attack)) continue; + if (!IvJudge_filter_match(filter.iv_def, IVs.defense)) continue; + if (!IvJudge_filter_match(filter.iv_spatk, IVs.spatk)) continue; + if (!IvJudge_filter_match(filter.iv_spdef, IVs.spdef)) continue; + if (!IvJudge_filter_match(filter.iv_speed, IVs.speed)) continue; + + if (!NatureChecker_filter_match(filter.nature, nature.nature)){ + continue; + } + + StatsHuntAction filter_action = filter.action; + + // No action matched so far. Take the current action and continue. + if (action == StatsHuntAction::Discard){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); + return StatsHuntAction::StopProgram; + } + } + return action; +} + +} +} diff --git a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).h b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).h index 6b5e69cf83..8e67452f9a 100644 --- a/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).h +++ b/SerialPrograms/Source/Pokemon/Options/Pokemon_StatsResetFilter (disabled).h @@ -1,48 +1,48 @@ -/* Stats Reset Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_StatsResetFilter_H -#define PokemonAutomation_Pokemon_StatsResetFilter_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -//#include "Pokemon/Pokemon_IvJudge.h" -#include "Pokemon/Options/Pokemon_IvJudgeOption.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" -#include "Pokemon_StatsHuntFilter.h" -#include "Pokemon/Inference/Pokemon_NatureReader.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -class StatsResetFilterRow : public EditableTableRow{ -public: - StatsResetFilterRow(); - virtual std::unique_ptr clone() const override; - -public: - StatsHuntAction action; - EnumDropdownCell nature; - IVJudgeFilterCell iv_hp; - IVJudgeFilterCell iv_atk; - IVJudgeFilterCell iv_def; - IVJudgeFilterCell iv_spatk; - IVJudgeFilterCell iv_spdef; - IVJudgeFilterCell iv_speed; -}; - -class StatsResetFilterTable : public EditableTableOption_t{ -public: - StatsResetFilterTable(); - virtual std::vector make_header() const override; - static std::vector> make_defaults(); - - StatsHuntAction get_action(bool shiny, const IvJudgeReader::Results& IVs, NatureReader::Results nature) const; -}; - -} -} -#endif +/* Stats Reset Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StatsResetFilter_H +#define PokemonAutomation_Pokemon_StatsResetFilter_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +//#include "Pokemon/Pokemon_IvJudge.h" +#include "Pokemon/Options/Pokemon_IvJudgeOption.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" +#include "Pokemon_StatsHuntFilter.h" +#include "Pokemon/Inference/Pokemon_NatureReader.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +class StatsResetFilterRow : public EditableTableRow{ +public: + StatsResetFilterRow(); + virtual std::unique_ptr clone() const override; + +public: + StatsHuntAction action; + EnumDropdownCell nature; + IVJudgeFilterCell iv_hp; + IVJudgeFilterCell iv_atk; + IVJudgeFilterCell iv_def; + IVJudgeFilterCell iv_spatk; + IVJudgeFilterCell iv_spdef; + IVJudgeFilterCell iv_speed; +}; + +class StatsResetFilterTable : public EditableTableOption_t{ +public: + StatsResetFilterTable(); + virtual std::vector make_header() const override; + static std::vector> make_defaults(); + + StatsHuntAction get_action(bool shiny, const IvJudgeReader::Results& IVs, NatureReader::Results nature) const; +}; + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_DataTypes.h b/SerialPrograms/Source/Pokemon/Pokemon_DataTypes.h index adce61ce2f..4719bf5fb6 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_DataTypes.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_DataTypes.h @@ -1,67 +1,67 @@ -/* Pokemon Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_DataTypes_H -#define PokemonAutomation_Pokemon_DataTypes_H - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -enum class ShinyType{ - UNKNOWN, - NOT_SHINY, - MAYBE_SHINY, // Unknown, but likely to be shiny. - UNKNOWN_SHINY, - STAR_SHINY, - SQUARE_SHINY, -}; -inline bool is_likely_shiny(ShinyType type){ - switch (type){ - case ShinyType::UNKNOWN: - case ShinyType::NOT_SHINY: - return false; - case ShinyType::MAYBE_SHINY: - case ShinyType::UNKNOWN_SHINY: - case ShinyType::STAR_SHINY: - case ShinyType::SQUARE_SHINY: - return true; - } - return false; -} -inline bool is_confirmed_shiny(ShinyType type){ - switch (type){ - case ShinyType::UNKNOWN: - case ShinyType::NOT_SHINY: - case ShinyType::MAYBE_SHINY: - return false; - case ShinyType::UNKNOWN_SHINY: - case ShinyType::STAR_SHINY: - case ShinyType::SQUARE_SHINY: - return true; - } - return false; -} - - -struct ShinyDetectionResult{ - ShinyType shiny_type = ShinyType::UNKNOWN; - double alpha = 0; - std::shared_ptr best_screenshot; - - ImageViewRGB32 get_best_screenshot() const{ - return best_screenshot ? (ImageViewRGB32)*best_screenshot : ImageViewRGB32(); - } -}; - - - -} -} -#endif +/* Pokemon Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_DataTypes_H +#define PokemonAutomation_Pokemon_DataTypes_H + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class ShinyType{ + UNKNOWN, + NOT_SHINY, + MAYBE_SHINY, // Unknown, but likely to be shiny. + UNKNOWN_SHINY, + STAR_SHINY, + SQUARE_SHINY, +}; +inline bool is_likely_shiny(ShinyType type){ + switch (type){ + case ShinyType::UNKNOWN: + case ShinyType::NOT_SHINY: + return false; + case ShinyType::MAYBE_SHINY: + case ShinyType::UNKNOWN_SHINY: + case ShinyType::STAR_SHINY: + case ShinyType::SQUARE_SHINY: + return true; + } + return false; +} +inline bool is_confirmed_shiny(ShinyType type){ + switch (type){ + case ShinyType::UNKNOWN: + case ShinyType::NOT_SHINY: + case ShinyType::MAYBE_SHINY: + return false; + case ShinyType::UNKNOWN_SHINY: + case ShinyType::STAR_SHINY: + case ShinyType::SQUARE_SHINY: + return true; + } + return false; +} + + +struct ShinyDetectionResult{ + ShinyType shiny_type = ShinyType::UNKNOWN; + double alpha = 0; + std::shared_ptr best_screenshot; + + ImageViewRGB32 get_best_screenshot() const{ + return best_screenshot ? (ImageViewRGB32)*best_screenshot : ImageViewRGB32(); + } +}; + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.cpp b/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.cpp index e6c63eec8e..95656787f4 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.cpp @@ -1,96 +1,96 @@ -/* Pokemon Encounter Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon_EncounterStats.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -bool operator<(const PokemonEncounterSet& x, const PokemonEncounterSet& y){ - auto iter0 = x.m_set.begin(); - auto iter1 = y.m_set.begin(); - while (true){ - bool end0 = iter0 == x.m_set.end(); - bool end1 = iter1 == y.m_set.end(); - if (end0 && end1){ - return false; - } - if (end0){ - return true; - } - if (end1){ - return false; - } - int cmp = strcmp(iter0->c_str(), iter1->c_str()); - if (cmp < 0){ - return true; - } - if (cmp > 0){ - return false; - } - - ++iter0; - ++iter1; - } -} -std::string PokemonEncounterSet::dump() const{ - if (m_set.empty()){ - return "None - Unable to detect"; - } - if (m_set.size() == 1){ - return get_pokemon_name(*m_set.begin()).display_name(); - } - if (m_set.size() <= 5){ - std::string str = "Ambiguous ("; - bool first = true; - for (const std::string& slug : m_set){ - if (!first){ - str += ", "; - } - first = false; - str += get_pokemon_name(slug).display_name(); - } - str += ")"; - return str; - } - return "Ambiguous (" + std::to_string(m_set.size()) + " candidates)"; -} - - - -void EncounterFrequencies::operator+=(const PokemonEncounterSet& set){ - m_encounter_map[set]++; -} - -std::multimap> -EncounterFrequencies::to_sorted_map() const{ - MapType ret; - for (const auto& item : m_encounter_map){ - ret.emplace(item.second, &item.first); - } - return ret; -} -std::string EncounterFrequencies::dump_sorted_map(const std::string& header) const{ - MapType map = to_sorted_map(); - std::string str = header; - for (const auto& item : map){ - str += tostr_u_commas(item.first); - str += " : "; - str += item.second->dump(); - str += "\n"; - } - return str; -} - - - -} -} - +/* Pokemon Encounter Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon_EncounterStats.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +bool operator<(const PokemonEncounterSet& x, const PokemonEncounterSet& y){ + auto iter0 = x.m_set.begin(); + auto iter1 = y.m_set.begin(); + while (true){ + bool end0 = iter0 == x.m_set.end(); + bool end1 = iter1 == y.m_set.end(); + if (end0 && end1){ + return false; + } + if (end0){ + return true; + } + if (end1){ + return false; + } + int cmp = strcmp(iter0->c_str(), iter1->c_str()); + if (cmp < 0){ + return true; + } + if (cmp > 0){ + return false; + } + + ++iter0; + ++iter1; + } +} +std::string PokemonEncounterSet::dump() const{ + if (m_set.empty()){ + return "None - Unable to detect"; + } + if (m_set.size() == 1){ + return get_pokemon_name(*m_set.begin()).display_name(); + } + if (m_set.size() <= 5){ + std::string str = "Ambiguous ("; + bool first = true; + for (const std::string& slug : m_set){ + if (!first){ + str += ", "; + } + first = false; + str += get_pokemon_name(slug).display_name(); + } + str += ")"; + return str; + } + return "Ambiguous (" + std::to_string(m_set.size()) + " candidates)"; +} + + + +void EncounterFrequencies::operator+=(const PokemonEncounterSet& set){ + m_encounter_map[set]++; +} + +std::multimap> +EncounterFrequencies::to_sorted_map() const{ + MapType ret; + for (const auto& item : m_encounter_map){ + ret.emplace(item.second, &item.first); + } + return ret; +} +std::string EncounterFrequencies::dump_sorted_map(const std::string& header) const{ + MapType map = to_sorted_map(); + std::string str = header; + for (const auto& item : map){ + str += tostr_u_commas(item.first); + str += " : "; + str += item.second->dump(); + str += "\n"; + } + return str; +} + + + +} +} + diff --git a/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.h b/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.h index a91b460cf4..1229253333 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_EncounterStats.h @@ -1,57 +1,57 @@ -/* Pokemon Encounter Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_EncounterStats_H -#define PokemonAutomation_Pokemon_EncounterStats_H - -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class PokemonEncounterSet{ -public: - PokemonEncounterSet() = default; - PokemonEncounterSet(const std::set& set) - : m_set(set) - {} - PokemonEncounterSet(std::set&& set) - : m_set(std::move(set)) - {} - - friend bool operator<(const PokemonEncounterSet& x, const PokemonEncounterSet& y); - - std::string dump() const; - - -private: - std::set m_set; -}; - - -class EncounterFrequencies{ - -public: - void operator+=(const PokemonEncounterSet& set); - - bool empty() const{ return m_encounter_map.empty(); } - std::string dump_sorted_map(const std::string& header) const; - -public: - using MapType = std::multimap>; - MapType to_sorted_map() const; - -private: - std::map m_encounter_map; -}; - - -} -} -#endif +/* Pokemon Encounter Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_EncounterStats_H +#define PokemonAutomation_Pokemon_EncounterStats_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class PokemonEncounterSet{ +public: + PokemonEncounterSet() = default; + PokemonEncounterSet(const std::set& set) + : m_set(set) + {} + PokemonEncounterSet(std::set&& set) + : m_set(std::move(set)) + {} + + friend bool operator<(const PokemonEncounterSet& x, const PokemonEncounterSet& y); + + std::string dump() const; + + +private: + std::set m_set; +}; + + +class EncounterFrequencies{ + +public: + void operator+=(const PokemonEncounterSet& set); + + bool empty() const{ return m_encounter_map.empty(); } + std::string dump_sorted_map(const std::string& header) const; + +public: + using MapType = std::multimap>; + MapType to_sorted_map() const; + +private: + std::map m_encounter_map; +}; + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.cpp b/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.cpp index 95bee7174c..b5d1ec37f0 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.cpp @@ -1,84 +1,84 @@ -/* Pokemon IV Checker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_IvJudge.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -const EnumStringMap& IV_JUDGE_VALUE_STRINGS(){ - static EnumStringMap database{ - {IvJudgeValue::UnableToDetect, "Unable to Detect"}, - {IvJudgeValue::NoGood, "No Good"}, - {IvJudgeValue::Decent, "Decent"}, - {IvJudgeValue::PrettyGood, "Pretty Good"}, - {IvJudgeValue::VeryGood, "Very Good"}, - {IvJudgeValue::Fantastic, "Fantastic"}, - {IvJudgeValue::Best, "Best"}, - {IvJudgeValue::HyperTrained, "Hyper trained!"}, - }; - return database; -} -const EnumDropdownDatabase& IvJudgeValue_Database(){ - static EnumDropdownDatabase database({ - {IvJudgeValue::NoGood, "no-good", "No Good (0)"}, - {IvJudgeValue::Decent, "decent", "Decent (1-15)"}, - {IvJudgeValue::PrettyGood, "pretty-good", "Pretty Good (16-25)"}, - {IvJudgeValue::VeryGood, "very-good", "Very Good (26-29)"}, - {IvJudgeValue::Fantastic, "fantastic", "Fantastic (30)"}, - {IvJudgeValue::Best, "best", "Best (31)"}, - {IvJudgeValue::HyperTrained, "hyper-trained", "Hyper trained!"}, - }); - return database; -} - - - - - - -const EnumDropdownDatabase& IvJudgeFilter_Database(){ - static EnumDropdownDatabase database({ - {IvJudgeFilter::Anything, "anything", "Anything (0-31)"}, - {IvJudgeFilter::NoGood, "no-good", "No Good (0)"}, - {IvJudgeFilter::Decent, "decent", "Decent (1-15)"}, - {IvJudgeFilter::PrettyGood, "pretty-good", "Pretty Good (16-25)"}, - {IvJudgeFilter::VeryGood, "very-good", "Very Good (26-29)"}, - {IvJudgeFilter::Fantastic, "fantastic", "Fantastic (30)"}, - {IvJudgeFilter::Best, "best", "Best (31)"}, - }); - return database; -} - - - -bool IvJudge_filter_match(IvJudgeFilter filter, IvJudgeValue value){ - switch (filter){ - case IvJudgeFilter::Anything: - return true; - case IvJudgeFilter::NoGood: - return value == IvJudgeValue::NoGood; - case IvJudgeFilter::Decent: - return value == IvJudgeValue::Decent; - case IvJudgeFilter::PrettyGood: - return value == IvJudgeValue::PrettyGood; - case IvJudgeFilter::VeryGood: - return value == IvJudgeValue::VeryGood; - case IvJudgeFilter::Fantastic: - return value == IvJudgeValue::Fantastic; - case IvJudgeFilter::Best: - return value == IvJudgeValue::Best; - } - return false; -} - - - - -} -} +/* Pokemon IV Checker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_IvJudge.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +const EnumStringMap& IV_JUDGE_VALUE_STRINGS(){ + static EnumStringMap database{ + {IvJudgeValue::UnableToDetect, "Unable to Detect"}, + {IvJudgeValue::NoGood, "No Good"}, + {IvJudgeValue::Decent, "Decent"}, + {IvJudgeValue::PrettyGood, "Pretty Good"}, + {IvJudgeValue::VeryGood, "Very Good"}, + {IvJudgeValue::Fantastic, "Fantastic"}, + {IvJudgeValue::Best, "Best"}, + {IvJudgeValue::HyperTrained, "Hyper trained!"}, + }; + return database; +} +const EnumDropdownDatabase& IvJudgeValue_Database(){ + static EnumDropdownDatabase database({ + {IvJudgeValue::NoGood, "no-good", "No Good (0)"}, + {IvJudgeValue::Decent, "decent", "Decent (1-15)"}, + {IvJudgeValue::PrettyGood, "pretty-good", "Pretty Good (16-25)"}, + {IvJudgeValue::VeryGood, "very-good", "Very Good (26-29)"}, + {IvJudgeValue::Fantastic, "fantastic", "Fantastic (30)"}, + {IvJudgeValue::Best, "best", "Best (31)"}, + {IvJudgeValue::HyperTrained, "hyper-trained", "Hyper trained!"}, + }); + return database; +} + + + + + + +const EnumDropdownDatabase& IvJudgeFilter_Database(){ + static EnumDropdownDatabase database({ + {IvJudgeFilter::Anything, "anything", "Anything (0-31)"}, + {IvJudgeFilter::NoGood, "no-good", "No Good (0)"}, + {IvJudgeFilter::Decent, "decent", "Decent (1-15)"}, + {IvJudgeFilter::PrettyGood, "pretty-good", "Pretty Good (16-25)"}, + {IvJudgeFilter::VeryGood, "very-good", "Very Good (26-29)"}, + {IvJudgeFilter::Fantastic, "fantastic", "Fantastic (30)"}, + {IvJudgeFilter::Best, "best", "Best (31)"}, + }); + return database; +} + + + +bool IvJudge_filter_match(IvJudgeFilter filter, IvJudgeValue value){ + switch (filter){ + case IvJudgeFilter::Anything: + return true; + case IvJudgeFilter::NoGood: + return value == IvJudgeValue::NoGood; + case IvJudgeFilter::Decent: + return value == IvJudgeValue::Decent; + case IvJudgeFilter::PrettyGood: + return value == IvJudgeValue::PrettyGood; + case IvJudgeFilter::VeryGood: + return value == IvJudgeValue::VeryGood; + case IvJudgeFilter::Fantastic: + return value == IvJudgeValue::Fantastic; + case IvJudgeFilter::Best: + return value == IvJudgeValue::Best; + } + return false; +} + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.h b/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.h index 22e953a9e1..f598b3c3b3 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_IvJudge.h @@ -1,47 +1,47 @@ -/* Pokemon Iv Judge - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_IvJudge_H -#define PokemonAutomation_Pokemon_IvJudge_H - -#include "Common/Cpp/EnumStringMap.h" -#include "Common/Cpp/Options/EnumDropdownDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -enum class IvJudgeValue{ - UnableToDetect, - NoGood, - Decent, - PrettyGood, - VeryGood, - Fantastic, - Best, - HyperTrained, -}; -const EnumStringMap& IV_JUDGE_VALUE_STRINGS(); -const EnumDropdownDatabase& IvJudgeValue_Database(); - - -enum class IvJudgeFilter{ - Anything, - NoGood, - Decent, - PrettyGood, - VeryGood, - Fantastic, - Best, -}; -const EnumDropdownDatabase& IvJudgeFilter_Database(); -bool IvJudge_filter_match(IvJudgeFilter filter, IvJudgeValue value); - - - -} -} -#endif +/* Pokemon Iv Judge + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_IvJudge_H +#define PokemonAutomation_Pokemon_IvJudge_H + +#include "Common/Cpp/EnumStringMap.h" +#include "Common/Cpp/Options/EnumDropdownDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class IvJudgeValue{ + UnableToDetect, + NoGood, + Decent, + PrettyGood, + VeryGood, + Fantastic, + Best, + HyperTrained, +}; +const EnumStringMap& IV_JUDGE_VALUE_STRINGS(); +const EnumDropdownDatabase& IvJudgeValue_Database(); + + +enum class IvJudgeFilter{ + Anything, + NoGood, + Decent, + PrettyGood, + VeryGood, + Fantastic, + Best, +}; +const EnumDropdownDatabase& IvJudgeFilter_Database(); +bool IvJudge_filter_match(IvJudgeFilter filter, IvJudgeValue value); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.cpp b/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.cpp index 7f0bbeb926..49761f1d1d 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.cpp @@ -1,230 +1,230 @@ -/* Pokemon Nature Checker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Pokemon_NatureChecker.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const EnumStringMap& NATURE_CHECKER_VALUE_STRINGS(){ - static EnumStringMap database{ - {NatureCheckerValue::UnableToDetect, "Unable to Detect"}, - {NatureCheckerValue::Neutral, "Neutral"}, - {NatureCheckerValue::Adamant, "Adamant"}, - {NatureCheckerValue::Bashful, "Bashful"}, - {NatureCheckerValue::Bold, "Bold"}, - {NatureCheckerValue::Brave, "Brave"}, - {NatureCheckerValue::Calm, "Calm"}, - {NatureCheckerValue::Careful, "Careful"}, - {NatureCheckerValue::Docile, "Docile"}, - {NatureCheckerValue::Gentle, "Gentle"}, - {NatureCheckerValue::Hardy, "Hardy"}, - {NatureCheckerValue::Hasty, "Hasty"}, - {NatureCheckerValue::Impish, "Impish"}, - {NatureCheckerValue::Jolly, "Jolly"}, - {NatureCheckerValue::Lax, "Lax"}, - {NatureCheckerValue::Lonely, "Lonely"}, - {NatureCheckerValue::Mild, "Mild"}, - {NatureCheckerValue::Modest, "Modest"}, - {NatureCheckerValue::Naive, "Naive"}, - {NatureCheckerValue::Naughty, "Naughty"}, - {NatureCheckerValue::Quiet, "Quiet"}, - {NatureCheckerValue::Quirky, "Quirky"}, - {NatureCheckerValue::Rash, "Rash"}, - {NatureCheckerValue::Relaxed, "Relaxed"}, - {NatureCheckerValue::Sassy, "Sassy"}, - {NatureCheckerValue::Serious, "Serious"}, - {NatureCheckerValue::Timid, "Timid"}, - }; - return database; -} - - -const std::map, NatureCheckerValue>& NatureCheckerValue_HELPHINDER_TO_ENUM(){ - static std::map, NatureCheckerValue> data{ - {{ 0, 2 }, NatureCheckerValue::Adamant}, - {{ -1, -1 }, NatureCheckerValue::Neutral}, //Bashful, Docile, Hardy, Quirky, Serious - {{ 1, 0 }, NatureCheckerValue::Bold}, - {{ 0, 4 }, NatureCheckerValue::Brave}, - {{ 3, 0 }, NatureCheckerValue::Calm}, - {{ 3, 2 }, NatureCheckerValue::Careful}, - {{ 3, 1 }, NatureCheckerValue::Gentle}, - {{ 4, 1 }, NatureCheckerValue::Hasty}, - {{ 1, 2 }, NatureCheckerValue::Impish}, - {{ 4, 2 }, NatureCheckerValue::Jolly}, - {{ 1, 3 }, NatureCheckerValue::Lax}, - {{ 0, 1 }, NatureCheckerValue::Lonely}, - {{ 2, 1 }, NatureCheckerValue::Mild}, - {{ 2, 0 }, NatureCheckerValue::Modest}, - {{ 4, 3 }, NatureCheckerValue::Naive}, - {{ 0, 3 }, NatureCheckerValue::Naughty}, - {{ 2, 4 }, NatureCheckerValue::Quiet}, - {{ 2, 3 }, NatureCheckerValue::Rash}, - {{ 1, 4 }, NatureCheckerValue::Relaxed}, - {{ 3, 4 }, NatureCheckerValue::Sassy}, - {{ 4, 0 }, NatureCheckerValue::Timid}, - }; - return data; -} - - -NatureCheckerValue NatureCheckerValue_helphinder_to_enum(const std::pair& token){ - auto iter = NatureCheckerValue_HELPHINDER_TO_ENUM().find(token); - if (iter == NatureCheckerValue_HELPHINDER_TO_ENUM().end()){ - return NatureCheckerValue::UnableToDetect; - } - return iter->second; -} - - - - - -const EnumDropdownDatabase& NatureCheckerValue_Database(){ - static EnumDropdownDatabase database({ - {NatureCheckerValue::Adamant, "adamant", "Adamant"}, - {NatureCheckerValue::Bashful, "bashful", "Bashful"}, - {NatureCheckerValue::Bold, "bold", "Bold"}, - {NatureCheckerValue::Brave, "brave", "Brave"}, - {NatureCheckerValue::Calm, "calm", "Calm"}, - {NatureCheckerValue::Careful, "careful", "Careful"}, - {NatureCheckerValue::Docile, "docile", "Docile"}, - {NatureCheckerValue::Gentle, "gentle", "Gentle"}, - {NatureCheckerValue::Hardy, "hardy", "Hardy"}, - {NatureCheckerValue::Hasty, "hasty", "Hasty"}, - {NatureCheckerValue::Impish, "impish", "Impish"}, - {NatureCheckerValue::Jolly, "jolly", "Jolly"}, - {NatureCheckerValue::Lax, "lax", "Lax"}, - {NatureCheckerValue::Lonely, "lonely", "Lonely"}, - {NatureCheckerValue::Mild, "mild", "Mild"}, - {NatureCheckerValue::Modest, "modest", "Modest"}, - {NatureCheckerValue::Naive, "naive", "Naive"}, - {NatureCheckerValue::Naughty, "naughty", "Naughty"}, - {NatureCheckerValue::Quiet, "quiet", "Quiet"}, - {NatureCheckerValue::Quirky, "quirky", "Quirky"}, - {NatureCheckerValue::Rash, "rash", "Rash"}, - {NatureCheckerValue::Relaxed, "relaxed", "Relaxed"}, - {NatureCheckerValue::Sassy, "sassy", "Sassy"}, - {NatureCheckerValue::Serious, "serious", "Serious"}, - {NatureCheckerValue::Timid, "timid", "Timid"}, - }); - return database; -} - -const EnumDropdownDatabase& NatureCheckerFilter_Database(){ - static EnumDropdownDatabase database({ - {NatureCheckerFilter::Any, "any", "Any"}, - {NatureCheckerFilter::Adamant, "adamant", "Adamant"}, - {NatureCheckerFilter::Bashful, "bashful", "Bashful"}, - {NatureCheckerFilter::Bold, "bold", "Bold"}, - {NatureCheckerFilter::Brave, "brave", "Brave"}, - {NatureCheckerFilter::Calm, "calm", "Calm"}, - {NatureCheckerFilter::Careful, "careful", "Careful"}, - {NatureCheckerFilter::Docile, "docile", "Docile"}, - {NatureCheckerFilter::Gentle, "gentle", "Gentle"}, - {NatureCheckerFilter::Hardy, "hardy", "Hardy"}, - {NatureCheckerFilter::Hasty, "hasty", "Hasty"}, - {NatureCheckerFilter::Impish, "impish", "Impish"}, - {NatureCheckerFilter::Jolly, "jolly", "Jolly"}, - {NatureCheckerFilter::Lax, "lax", "Lax"}, - {NatureCheckerFilter::Lonely, "lonely", "Lonely"}, - {NatureCheckerFilter::Mild, "mild", "Mild"}, - {NatureCheckerFilter::Modest, "modest", "Modest"}, - {NatureCheckerFilter::Naive, "naive", "Naive"}, - {NatureCheckerFilter::Naughty, "naughty", "Naughty"}, - {NatureCheckerFilter::Quiet, "quiet", "Quiet"}, - {NatureCheckerFilter::Quirky, "quirky", "Quirky"}, - {NatureCheckerFilter::Rash, "rash", "Rash"}, - {NatureCheckerFilter::Relaxed, "relaxed", "Relaxed"}, - {NatureCheckerFilter::Sassy, "sassy", "Sassy"}, - {NatureCheckerFilter::Serious, "serious", "Serious"}, - {NatureCheckerFilter::Timid, "timid", "Timid"}, - }); - return database; -} - - - -bool NatureChecker_filter_match(NatureCheckerFilter filter, NatureCheckerValue value){ - switch (filter){ - case NatureCheckerFilter::Any: - return true; - case NatureCheckerFilter::Adamant: - return value == NatureCheckerValue::Adamant; - case NatureCheckerFilter::Bashful: - if (value == NatureCheckerValue::Neutral){ - return true; - } - return value == NatureCheckerValue::Bashful; - case NatureCheckerFilter::Bold: - return value == NatureCheckerValue::Bold; - case NatureCheckerFilter::Brave: - return value == NatureCheckerValue::Brave; - case NatureCheckerFilter::Calm: - return value == NatureCheckerValue::Calm; - case NatureCheckerFilter::Careful: - return value == NatureCheckerValue::Careful; - case NatureCheckerFilter::Docile: - if (value == NatureCheckerValue::Neutral){ - return true; - } - return value == NatureCheckerValue::Docile; - case NatureCheckerFilter::Gentle: - return value == NatureCheckerValue::Gentle; - case NatureCheckerFilter::Hardy: - if (value == NatureCheckerValue::Neutral){ - return true; - } - return value == NatureCheckerValue::Hardy; - case NatureCheckerFilter::Hasty: - return value == NatureCheckerValue::Hasty; - case NatureCheckerFilter::Impish: - return value == NatureCheckerValue::Impish; - case NatureCheckerFilter::Jolly: - return value == NatureCheckerValue::Jolly; - case NatureCheckerFilter::Lax: - return value == NatureCheckerValue::Lax; - case NatureCheckerFilter::Lonely: - return value == NatureCheckerValue::Lonely; - case NatureCheckerFilter::Mild: - return value == NatureCheckerValue::Mild; - case NatureCheckerFilter::Modest: - return value == NatureCheckerValue::Modest; - case NatureCheckerFilter::Naive: - return value == NatureCheckerValue::Naive; - case NatureCheckerFilter::Naughty: - return value == NatureCheckerValue::Naughty; - case NatureCheckerFilter::Quiet: - return value == NatureCheckerValue::Quiet; - case NatureCheckerFilter::Quirky: - if (value == NatureCheckerValue::Neutral){ - return true; - } - return value == NatureCheckerValue::Quirky; - case NatureCheckerFilter::Rash: - return value == NatureCheckerValue::Rash; - case NatureCheckerFilter::Relaxed: - return value == NatureCheckerValue::Relaxed; - case NatureCheckerFilter::Sassy: - return value == NatureCheckerValue::Sassy; - case NatureCheckerFilter::Serious: - if (value == NatureCheckerValue::Neutral){ - return true; - } - return value == NatureCheckerValue::Serious; - case NatureCheckerFilter::Timid: - return value == NatureCheckerValue::Timid; - } - return false; -} - - - - -} -} +/* Pokemon Nature Checker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_NatureChecker.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const EnumStringMap& NATURE_CHECKER_VALUE_STRINGS(){ + static EnumStringMap database{ + {NatureCheckerValue::UnableToDetect, "Unable to Detect"}, + {NatureCheckerValue::Neutral, "Neutral"}, + {NatureCheckerValue::Adamant, "Adamant"}, + {NatureCheckerValue::Bashful, "Bashful"}, + {NatureCheckerValue::Bold, "Bold"}, + {NatureCheckerValue::Brave, "Brave"}, + {NatureCheckerValue::Calm, "Calm"}, + {NatureCheckerValue::Careful, "Careful"}, + {NatureCheckerValue::Docile, "Docile"}, + {NatureCheckerValue::Gentle, "Gentle"}, + {NatureCheckerValue::Hardy, "Hardy"}, + {NatureCheckerValue::Hasty, "Hasty"}, + {NatureCheckerValue::Impish, "Impish"}, + {NatureCheckerValue::Jolly, "Jolly"}, + {NatureCheckerValue::Lax, "Lax"}, + {NatureCheckerValue::Lonely, "Lonely"}, + {NatureCheckerValue::Mild, "Mild"}, + {NatureCheckerValue::Modest, "Modest"}, + {NatureCheckerValue::Naive, "Naive"}, + {NatureCheckerValue::Naughty, "Naughty"}, + {NatureCheckerValue::Quiet, "Quiet"}, + {NatureCheckerValue::Quirky, "Quirky"}, + {NatureCheckerValue::Rash, "Rash"}, + {NatureCheckerValue::Relaxed, "Relaxed"}, + {NatureCheckerValue::Sassy, "Sassy"}, + {NatureCheckerValue::Serious, "Serious"}, + {NatureCheckerValue::Timid, "Timid"}, + }; + return database; +} + + +const std::map, NatureCheckerValue>& NatureCheckerValue_HELPHINDER_TO_ENUM(){ + static std::map, NatureCheckerValue> data{ + {{ 0, 2 }, NatureCheckerValue::Adamant}, + {{ -1, -1 }, NatureCheckerValue::Neutral}, //Bashful, Docile, Hardy, Quirky, Serious + {{ 1, 0 }, NatureCheckerValue::Bold}, + {{ 0, 4 }, NatureCheckerValue::Brave}, + {{ 3, 0 }, NatureCheckerValue::Calm}, + {{ 3, 2 }, NatureCheckerValue::Careful}, + {{ 3, 1 }, NatureCheckerValue::Gentle}, + {{ 4, 1 }, NatureCheckerValue::Hasty}, + {{ 1, 2 }, NatureCheckerValue::Impish}, + {{ 4, 2 }, NatureCheckerValue::Jolly}, + {{ 1, 3 }, NatureCheckerValue::Lax}, + {{ 0, 1 }, NatureCheckerValue::Lonely}, + {{ 2, 1 }, NatureCheckerValue::Mild}, + {{ 2, 0 }, NatureCheckerValue::Modest}, + {{ 4, 3 }, NatureCheckerValue::Naive}, + {{ 0, 3 }, NatureCheckerValue::Naughty}, + {{ 2, 4 }, NatureCheckerValue::Quiet}, + {{ 2, 3 }, NatureCheckerValue::Rash}, + {{ 1, 4 }, NatureCheckerValue::Relaxed}, + {{ 3, 4 }, NatureCheckerValue::Sassy}, + {{ 4, 0 }, NatureCheckerValue::Timid}, + }; + return data; +} + + +NatureCheckerValue NatureCheckerValue_helphinder_to_enum(const std::pair& token){ + auto iter = NatureCheckerValue_HELPHINDER_TO_ENUM().find(token); + if (iter == NatureCheckerValue_HELPHINDER_TO_ENUM().end()){ + return NatureCheckerValue::UnableToDetect; + } + return iter->second; +} + + + + + +const EnumDropdownDatabase& NatureCheckerValue_Database(){ + static EnumDropdownDatabase database({ + {NatureCheckerValue::Adamant, "adamant", "Adamant"}, + {NatureCheckerValue::Bashful, "bashful", "Bashful"}, + {NatureCheckerValue::Bold, "bold", "Bold"}, + {NatureCheckerValue::Brave, "brave", "Brave"}, + {NatureCheckerValue::Calm, "calm", "Calm"}, + {NatureCheckerValue::Careful, "careful", "Careful"}, + {NatureCheckerValue::Docile, "docile", "Docile"}, + {NatureCheckerValue::Gentle, "gentle", "Gentle"}, + {NatureCheckerValue::Hardy, "hardy", "Hardy"}, + {NatureCheckerValue::Hasty, "hasty", "Hasty"}, + {NatureCheckerValue::Impish, "impish", "Impish"}, + {NatureCheckerValue::Jolly, "jolly", "Jolly"}, + {NatureCheckerValue::Lax, "lax", "Lax"}, + {NatureCheckerValue::Lonely, "lonely", "Lonely"}, + {NatureCheckerValue::Mild, "mild", "Mild"}, + {NatureCheckerValue::Modest, "modest", "Modest"}, + {NatureCheckerValue::Naive, "naive", "Naive"}, + {NatureCheckerValue::Naughty, "naughty", "Naughty"}, + {NatureCheckerValue::Quiet, "quiet", "Quiet"}, + {NatureCheckerValue::Quirky, "quirky", "Quirky"}, + {NatureCheckerValue::Rash, "rash", "Rash"}, + {NatureCheckerValue::Relaxed, "relaxed", "Relaxed"}, + {NatureCheckerValue::Sassy, "sassy", "Sassy"}, + {NatureCheckerValue::Serious, "serious", "Serious"}, + {NatureCheckerValue::Timid, "timid", "Timid"}, + }); + return database; +} + +const EnumDropdownDatabase& NatureCheckerFilter_Database(){ + static EnumDropdownDatabase database({ + {NatureCheckerFilter::Any, "any", "Any"}, + {NatureCheckerFilter::Adamant, "adamant", "Adamant"}, + {NatureCheckerFilter::Bashful, "bashful", "Bashful"}, + {NatureCheckerFilter::Bold, "bold", "Bold"}, + {NatureCheckerFilter::Brave, "brave", "Brave"}, + {NatureCheckerFilter::Calm, "calm", "Calm"}, + {NatureCheckerFilter::Careful, "careful", "Careful"}, + {NatureCheckerFilter::Docile, "docile", "Docile"}, + {NatureCheckerFilter::Gentle, "gentle", "Gentle"}, + {NatureCheckerFilter::Hardy, "hardy", "Hardy"}, + {NatureCheckerFilter::Hasty, "hasty", "Hasty"}, + {NatureCheckerFilter::Impish, "impish", "Impish"}, + {NatureCheckerFilter::Jolly, "jolly", "Jolly"}, + {NatureCheckerFilter::Lax, "lax", "Lax"}, + {NatureCheckerFilter::Lonely, "lonely", "Lonely"}, + {NatureCheckerFilter::Mild, "mild", "Mild"}, + {NatureCheckerFilter::Modest, "modest", "Modest"}, + {NatureCheckerFilter::Naive, "naive", "Naive"}, + {NatureCheckerFilter::Naughty, "naughty", "Naughty"}, + {NatureCheckerFilter::Quiet, "quiet", "Quiet"}, + {NatureCheckerFilter::Quirky, "quirky", "Quirky"}, + {NatureCheckerFilter::Rash, "rash", "Rash"}, + {NatureCheckerFilter::Relaxed, "relaxed", "Relaxed"}, + {NatureCheckerFilter::Sassy, "sassy", "Sassy"}, + {NatureCheckerFilter::Serious, "serious", "Serious"}, + {NatureCheckerFilter::Timid, "timid", "Timid"}, + }); + return database; +} + + + +bool NatureChecker_filter_match(NatureCheckerFilter filter, NatureCheckerValue value){ + switch (filter){ + case NatureCheckerFilter::Any: + return true; + case NatureCheckerFilter::Adamant: + return value == NatureCheckerValue::Adamant; + case NatureCheckerFilter::Bashful: + if (value == NatureCheckerValue::Neutral){ + return true; + } + return value == NatureCheckerValue::Bashful; + case NatureCheckerFilter::Bold: + return value == NatureCheckerValue::Bold; + case NatureCheckerFilter::Brave: + return value == NatureCheckerValue::Brave; + case NatureCheckerFilter::Calm: + return value == NatureCheckerValue::Calm; + case NatureCheckerFilter::Careful: + return value == NatureCheckerValue::Careful; + case NatureCheckerFilter::Docile: + if (value == NatureCheckerValue::Neutral){ + return true; + } + return value == NatureCheckerValue::Docile; + case NatureCheckerFilter::Gentle: + return value == NatureCheckerValue::Gentle; + case NatureCheckerFilter::Hardy: + if (value == NatureCheckerValue::Neutral){ + return true; + } + return value == NatureCheckerValue::Hardy; + case NatureCheckerFilter::Hasty: + return value == NatureCheckerValue::Hasty; + case NatureCheckerFilter::Impish: + return value == NatureCheckerValue::Impish; + case NatureCheckerFilter::Jolly: + return value == NatureCheckerValue::Jolly; + case NatureCheckerFilter::Lax: + return value == NatureCheckerValue::Lax; + case NatureCheckerFilter::Lonely: + return value == NatureCheckerValue::Lonely; + case NatureCheckerFilter::Mild: + return value == NatureCheckerValue::Mild; + case NatureCheckerFilter::Modest: + return value == NatureCheckerValue::Modest; + case NatureCheckerFilter::Naive: + return value == NatureCheckerValue::Naive; + case NatureCheckerFilter::Naughty: + return value == NatureCheckerValue::Naughty; + case NatureCheckerFilter::Quiet: + return value == NatureCheckerValue::Quiet; + case NatureCheckerFilter::Quirky: + if (value == NatureCheckerValue::Neutral){ + return true; + } + return value == NatureCheckerValue::Quirky; + case NatureCheckerFilter::Rash: + return value == NatureCheckerValue::Rash; + case NatureCheckerFilter::Relaxed: + return value == NatureCheckerValue::Relaxed; + case NatureCheckerFilter::Sassy: + return value == NatureCheckerValue::Sassy; + case NatureCheckerFilter::Serious: + if (value == NatureCheckerValue::Neutral){ + return true; + } + return value == NatureCheckerValue::Serious; + case NatureCheckerFilter::Timid: + return value == NatureCheckerValue::Timid; + } + return false; +} + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.h b/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.h index 8c653924a8..f727eae7f6 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_NatureChecker.h @@ -1,99 +1,99 @@ -/* Pokemon Nature Checker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_NatureChecker_H -#define PokemonAutomation_Pokemon_NatureChecker_H - -#include -#include "Common/Cpp/EnumStringMap.h" -#include "Common/Cpp/Options/EnumDropdownDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -enum class NatureCheckerValue{ - UnableToDetect, -// Any, - - Neutral, - - Bashful, - Docile, - Hardy, - Quirky, - Serious, - - Bold, - Modest, - Calm, - Timid, - - Lonely, - Mild, - Gentle, - Hasty, - - Adamant, - Impish, - Careful, - Jolly, - - Naughty, - Lax, - Rash, - Naive, - - Brave, - Relaxed, - Quiet, - Sassy, -}; -const EnumStringMap& NATURE_CHECKER_VALUE_STRINGS(); -const EnumDropdownDatabase& NatureCheckerValue_Database(); -NatureCheckerValue NatureCheckerValue_helphinder_to_enum(const std::pair& token); - - -enum class NatureCheckerFilter{ - Any, - - Bashful, - Docile, - Hardy, - Quirky, - Serious, - - Bold, - Modest, - Calm, - Timid, - - Lonely, - Mild, - Gentle, - Hasty, - - Adamant, - Impish, - Careful, - Jolly, - - Naughty, - Lax, - Rash, - Naive, - - Brave, - Relaxed, - Quiet, - Sassy, -}; - -const EnumDropdownDatabase& NatureCheckerFilter_Database(); -bool NatureChecker_filter_match(NatureCheckerFilter filter, NatureCheckerValue value); - -} -} -#endif +/* Pokemon Nature Checker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_NatureChecker_H +#define PokemonAutomation_Pokemon_NatureChecker_H + +#include +#include "Common/Cpp/EnumStringMap.h" +#include "Common/Cpp/Options/EnumDropdownDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +enum class NatureCheckerValue{ + UnableToDetect, +// Any, + + Neutral, + + Bashful, + Docile, + Hardy, + Quirky, + Serious, + + Bold, + Modest, + Calm, + Timid, + + Lonely, + Mild, + Gentle, + Hasty, + + Adamant, + Impish, + Careful, + Jolly, + + Naughty, + Lax, + Rash, + Naive, + + Brave, + Relaxed, + Quiet, + Sassy, +}; +const EnumStringMap& NATURE_CHECKER_VALUE_STRINGS(); +const EnumDropdownDatabase& NatureCheckerValue_Database(); +NatureCheckerValue NatureCheckerValue_helphinder_to_enum(const std::pair& token); + + +enum class NatureCheckerFilter{ + Any, + + Bashful, + Docile, + Hardy, + Quirky, + Serious, + + Bold, + Modest, + Calm, + Timid, + + Lonely, + Mild, + Gentle, + Hasty, + + Adamant, + Impish, + Careful, + Jolly, + + Naughty, + Lax, + Rash, + Naive, + + Brave, + Relaxed, + Quiet, + Sassy, +}; + +const EnumDropdownDatabase& NatureCheckerFilter_Database(); +bool NatureChecker_filter_match(NatureCheckerFilter filter, NatureCheckerValue value); + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Notification.cpp b/SerialPrograms/Source/Pokemon/Pokemon_Notification.cpp index 31e8c7ccb8..f383c9808e 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Notification.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_Notification.cpp @@ -1,273 +1,273 @@ -/* Shiny Notification - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokeballNames.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon_Notification.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -Color shiny_color(ShinyType shiny_type){ - switch (shiny_type){ - case ShinyType::MAYBE_SHINY: - case ShinyType::UNKNOWN_SHINY: - case ShinyType::STAR_SHINY: - return COLOR_STAR_SHINY; - case ShinyType::SQUARE_SHINY: - return COLOR_SQUARE_SHINY; - default: - return Color(); - } -} -std::string shiny_symbol(ShinyType shiny_type){ - switch (shiny_type){ - case ShinyType::MAYBE_SHINY: - return ":question:"; - case ShinyType::UNKNOWN_SHINY: - case ShinyType::STAR_SHINY: - return "\u2728"; - case ShinyType::SQUARE_SHINY: - return ":purple_square:"; - default: - return ""; - } -} -std::string pokemon_to_string(const EncounterResult& pokemon){ - std::string str; - - std::string symbol = shiny_symbol(pokemon.shininess); - if (!symbol.empty()){ - str += symbol + " "; - } - - if (pokemon.slug_candidates.empty()){ - str = "Unable to detect."; - }else if (pokemon.slug_candidates.size() == 1){ - str += get_pokemon_name(*pokemon.slug_candidates.begin()).display_name(); - }else{ - str += "Ambiguous: "; - bool first1 = true; - for (const std::string& slug : pokemon.slug_candidates){ - if (!first1){ - str += ", "; - } - first1 = false; - str += get_pokemon_name(slug).display_name(); - } - } - return str; -} - - - -void send_encounter_notification( - ProgramEnvironment& env, - EventNotificationOption& settings_nonshiny, - EventNotificationOption& settings_shiny, - bool enable_names, bool shiny_detected, - const std::vector& results, - double alpha, - const ImageViewRGB32& screenshot, - const EncounterFrequencies* frequencies -){ - ShinyType max_shiny_type = ShinyType::UNKNOWN; - size_t shiny_count = 0; - - std::string names; - - bool first = true; - for (const EncounterResult& result : results){ - if (!first){ - names += "\n"; - } - first = false; - names += pokemon_to_string(result); - max_shiny_type = max_shiny_type < result.shininess ? result.shininess : max_shiny_type; - shiny_count += is_confirmed_shiny(result.shininess) ? 1 : 0; - } - if (max_shiny_type == ShinyType::MAYBE_SHINY){ - max_shiny_type = ShinyType::UNKNOWN_SHINY; - } - Color color = shiny_color(max_shiny_type); - bool has_shiny = is_likely_shiny(max_shiny_type) || shiny_detected; - - std::string shinies; - if (results.size() == 1){ - std::string symbol = shiny_symbol(results[0].shininess); - switch (results[0].shininess){ - case ShinyType::UNKNOWN: - shinies = "Unknown"; - break; - case ShinyType::NOT_SHINY: - shinies = "Not Shiny"; - break; - case ShinyType::MAYBE_SHINY: - shinies = "Maybe Shiny"; - break; - case ShinyType::UNKNOWN_SHINY: - shinies = symbol + std::string(" Shiny ") + symbol; - break; - case ShinyType::STAR_SHINY: - shinies = symbol + std::string(" Star Shiny ") + symbol; - break; - case ShinyType::SQUARE_SHINY: - shinies = symbol + std::string(" Square Shiny ") + symbol; - break; - } - }else if (!results.empty()){ - std::string symbol = shiny_symbol(max_shiny_type); - switch (shiny_count){ - case 0: - if (shiny_detected){ - symbol = shiny_symbol(ShinyType::UNKNOWN_SHINY); - shinies = symbol + " Found Shiny! " + symbol + " (Unable to determine which.)"; - }else{ - shinies = "No Shinies"; - } - break; - case 1: - shinies = symbol + " Found Shiny! " + symbol; - break; - default: - shinies += symbol + std::string(" Multiple Shinies! ") + symbol; - break; - } - } - - std::vector> embeds; - if (enable_names && !names.empty()){ - embeds.emplace_back("Species:", std::move(names)); - } - if (!shinies.empty()){ - if (!std::isnan(alpha)){ - shinies += "\n(Detection Alpha = " + tostr_default(alpha) + ")"; - } - embeds.emplace_back("Shininess:", std::move(shinies)); - } - std::string stats_addendum; - if (frequencies && !frequencies->empty()){ - stats_addendum = frequencies->dump_sorted_map(""); - } - - if (has_shiny){ - send_program_notification( - env, settings_shiny, - color, - "Encounter Notification", - embeds, std::move(stats_addendum), - screenshot, true - ); - }else{ - send_program_notification( - env, settings_nonshiny, - color, - "Encounter Notification", - embeds, std::move(stats_addendum), - screenshot, false - ); - } -} - - - -void send_catch_notification( - ProgramEnvironment& env, - EventNotificationOption& settings_catch_success, - EventNotificationOption& settings_catch_failed, - const std::set* pokemon_slugs, - const std::string& ball_slug, int balls_used, - CatchResult result -){ - Color color = result == CatchResult::POKEMON_CAUGHT ? COLOR_GREEN : COLOR_ORANGE; - - std::vector> embeds; - - if (pokemon_slugs){ - std::string str; - if (pokemon_slugs->empty()){ - str = "None - Unable to detect."; - }else if (pokemon_slugs->size() == 1){ - str += get_pokemon_name(*pokemon_slugs->begin()).display_name(); - }else{ - str += "Ambiguous: "; - bool first = true; - for (const std::string& slug : *pokemon_slugs){ - if (!first){ - str += ", "; - } - first = false; - str += get_pokemon_name(slug).display_name(); - } - } - embeds.emplace_back("Species:", std::move(str)); - } - switch (result){ - case CatchResult::POKEMON_CAUGHT: - break; - case CatchResult::POKEMON_FAINTED: - embeds.emplace_back("Fail Reason:", "The " + STRING_POKEMON + " fainted."); - break; - case CatchResult::OWN_FAINTED: - embeds.emplace_back("Fail Reason:", "Your own " + STRING_POKEMON + " fainted."); - break; - case CatchResult::OUT_OF_BALLS: - embeds.emplace_back("Fail Reason:", "Unable to find the desired ball. Did you run out?"); - break; - case CatchResult::BALL_LIMIT_REACHED: - embeds.emplace_back("Fail Reason:", "Ball limit reached."); - break; - case CatchResult::CANNOT_THROW_BALL: - embeds.emplace_back("Fail Reason:", "Unable to throw ball. Is the " + STRING_POKEMON + " semi-invulnerable?"); - break; - case CatchResult::TIMED_OUT: - embeds.emplace_back("Fail Reason:", "Timed out."); - break; - } - { - std::string str; - if (balls_used >= 0){ - str += std::to_string(balls_used); - } - if (!ball_slug.empty()){ - if (!str.empty()){ - str += " x "; - } - str += get_pokeball_name(ball_slug).display_name(); - } - if (!str.empty()){ - embeds.emplace_back("Balls Used:", str); - } - } - - if (result == CatchResult::POKEMON_CAUGHT){ - send_program_notification( - env, settings_catch_success, - color, - STRING_POKEMON + " Caught", - embeds, "" - ); - }else{ - send_program_notification( - env, settings_catch_failed, - color, - "Catch Failed", - embeds, "" - ); - } -} - - - - -} -} +/* Shiny Notification + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokeballNames.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon_Notification.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +Color shiny_color(ShinyType shiny_type){ + switch (shiny_type){ + case ShinyType::MAYBE_SHINY: + case ShinyType::UNKNOWN_SHINY: + case ShinyType::STAR_SHINY: + return COLOR_STAR_SHINY; + case ShinyType::SQUARE_SHINY: + return COLOR_SQUARE_SHINY; + default: + return Color(); + } +} +std::string shiny_symbol(ShinyType shiny_type){ + switch (shiny_type){ + case ShinyType::MAYBE_SHINY: + return ":question:"; + case ShinyType::UNKNOWN_SHINY: + case ShinyType::STAR_SHINY: + return "\u2728"; + case ShinyType::SQUARE_SHINY: + return ":purple_square:"; + default: + return ""; + } +} +std::string pokemon_to_string(const EncounterResult& pokemon){ + std::string str; + + std::string symbol = shiny_symbol(pokemon.shininess); + if (!symbol.empty()){ + str += symbol + " "; + } + + if (pokemon.slug_candidates.empty()){ + str = "Unable to detect."; + }else if (pokemon.slug_candidates.size() == 1){ + str += get_pokemon_name(*pokemon.slug_candidates.begin()).display_name(); + }else{ + str += "Ambiguous: "; + bool first1 = true; + for (const std::string& slug : pokemon.slug_candidates){ + if (!first1){ + str += ", "; + } + first1 = false; + str += get_pokemon_name(slug).display_name(); + } + } + return str; +} + + + +void send_encounter_notification( + ProgramEnvironment& env, + EventNotificationOption& settings_nonshiny, + EventNotificationOption& settings_shiny, + bool enable_names, bool shiny_detected, + const std::vector& results, + double alpha, + const ImageViewRGB32& screenshot, + const EncounterFrequencies* frequencies +){ + ShinyType max_shiny_type = ShinyType::UNKNOWN; + size_t shiny_count = 0; + + std::string names; + + bool first = true; + for (const EncounterResult& result : results){ + if (!first){ + names += "\n"; + } + first = false; + names += pokemon_to_string(result); + max_shiny_type = max_shiny_type < result.shininess ? result.shininess : max_shiny_type; + shiny_count += is_confirmed_shiny(result.shininess) ? 1 : 0; + } + if (max_shiny_type == ShinyType::MAYBE_SHINY){ + max_shiny_type = ShinyType::UNKNOWN_SHINY; + } + Color color = shiny_color(max_shiny_type); + bool has_shiny = is_likely_shiny(max_shiny_type) || shiny_detected; + + std::string shinies; + if (results.size() == 1){ + std::string symbol = shiny_symbol(results[0].shininess); + switch (results[0].shininess){ + case ShinyType::UNKNOWN: + shinies = "Unknown"; + break; + case ShinyType::NOT_SHINY: + shinies = "Not Shiny"; + break; + case ShinyType::MAYBE_SHINY: + shinies = "Maybe Shiny"; + break; + case ShinyType::UNKNOWN_SHINY: + shinies = symbol + std::string(" Shiny ") + symbol; + break; + case ShinyType::STAR_SHINY: + shinies = symbol + std::string(" Star Shiny ") + symbol; + break; + case ShinyType::SQUARE_SHINY: + shinies = symbol + std::string(" Square Shiny ") + symbol; + break; + } + }else if (!results.empty()){ + std::string symbol = shiny_symbol(max_shiny_type); + switch (shiny_count){ + case 0: + if (shiny_detected){ + symbol = shiny_symbol(ShinyType::UNKNOWN_SHINY); + shinies = symbol + " Found Shiny! " + symbol + " (Unable to determine which.)"; + }else{ + shinies = "No Shinies"; + } + break; + case 1: + shinies = symbol + " Found Shiny! " + symbol; + break; + default: + shinies += symbol + std::string(" Multiple Shinies! ") + symbol; + break; + } + } + + std::vector> embeds; + if (enable_names && !names.empty()){ + embeds.emplace_back("Species:", std::move(names)); + } + if (!shinies.empty()){ + if (!std::isnan(alpha)){ + shinies += "\n(Detection Alpha = " + tostr_default(alpha) + ")"; + } + embeds.emplace_back("Shininess:", std::move(shinies)); + } + std::string stats_addendum; + if (frequencies && !frequencies->empty()){ + stats_addendum = frequencies->dump_sorted_map(""); + } + + if (has_shiny){ + send_program_notification( + env, settings_shiny, + color, + "Encounter Notification", + embeds, std::move(stats_addendum), + screenshot, true + ); + }else{ + send_program_notification( + env, settings_nonshiny, + color, + "Encounter Notification", + embeds, std::move(stats_addendum), + screenshot, false + ); + } +} + + + +void send_catch_notification( + ProgramEnvironment& env, + EventNotificationOption& settings_catch_success, + EventNotificationOption& settings_catch_failed, + const std::set* pokemon_slugs, + const std::string& ball_slug, int balls_used, + CatchResult result +){ + Color color = result == CatchResult::POKEMON_CAUGHT ? COLOR_GREEN : COLOR_ORANGE; + + std::vector> embeds; + + if (pokemon_slugs){ + std::string str; + if (pokemon_slugs->empty()){ + str = "None - Unable to detect."; + }else if (pokemon_slugs->size() == 1){ + str += get_pokemon_name(*pokemon_slugs->begin()).display_name(); + }else{ + str += "Ambiguous: "; + bool first = true; + for (const std::string& slug : *pokemon_slugs){ + if (!first){ + str += ", "; + } + first = false; + str += get_pokemon_name(slug).display_name(); + } + } + embeds.emplace_back("Species:", std::move(str)); + } + switch (result){ + case CatchResult::POKEMON_CAUGHT: + break; + case CatchResult::POKEMON_FAINTED: + embeds.emplace_back("Fail Reason:", "The " + STRING_POKEMON + " fainted."); + break; + case CatchResult::OWN_FAINTED: + embeds.emplace_back("Fail Reason:", "Your own " + STRING_POKEMON + " fainted."); + break; + case CatchResult::OUT_OF_BALLS: + embeds.emplace_back("Fail Reason:", "Unable to find the desired ball. Did you run out?"); + break; + case CatchResult::BALL_LIMIT_REACHED: + embeds.emplace_back("Fail Reason:", "Ball limit reached."); + break; + case CatchResult::CANNOT_THROW_BALL: + embeds.emplace_back("Fail Reason:", "Unable to throw ball. Is the " + STRING_POKEMON + " semi-invulnerable?"); + break; + case CatchResult::TIMED_OUT: + embeds.emplace_back("Fail Reason:", "Timed out."); + break; + } + { + std::string str; + if (balls_used >= 0){ + str += std::to_string(balls_used); + } + if (!ball_slug.empty()){ + if (!str.empty()){ + str += " x "; + } + str += get_pokeball_name(ball_slug).display_name(); + } + if (!str.empty()){ + embeds.emplace_back("Balls Used:", str); + } + } + + if (result == CatchResult::POKEMON_CAUGHT){ + send_program_notification( + env, settings_catch_success, + color, + STRING_POKEMON + " Caught", + embeds, "" + ); + }else{ + send_program_notification( + env, settings_catch_failed, + color, + "Catch Failed", + embeds, "" + ); + } +} + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Notification.h b/SerialPrograms/Source/Pokemon/Pokemon_Notification.h index 20ec7383c8..43b23ab256 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Notification.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_Notification.h @@ -1,66 +1,66 @@ -/* Shiny Notification - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_ShinyNotification_H -#define PokemonAutomation_Pokemon_ShinyNotification_H - -#include -#include -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "Pokemon_EncounterStats.h" -#include "Pokemon_DataTypes.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const Color COLOR_STAR_SHINY(0xffff99); -const Color COLOR_SQUARE_SHINY(0xb266ff); - - - -struct EncounterResult{ - std::set slug_candidates; - ShinyType shininess = ShinyType::UNKNOWN; -}; - - -void send_encounter_notification( - ProgramEnvironment& env, - EventNotificationOption& settings_nonshiny, - EventNotificationOption& settings_shiny, - bool enable_names, bool shiny_detected, - const std::vector& results, - double alpha, // Set to std::nan("") to hide the field. - const ImageViewRGB32& screenshot = ImageViewRGB32(), - const EncounterFrequencies* frequencies = nullptr -); - - -enum class CatchResult{ - POKEMON_CAUGHT, - POKEMON_FAINTED, - OWN_FAINTED, - OUT_OF_BALLS, - BALL_LIMIT_REACHED, - CANNOT_THROW_BALL, - TIMED_OUT, -}; -void send_catch_notification( - ProgramEnvironment& env, - EventNotificationOption& settings_catch_success, - EventNotificationOption& settings_catch_failed, - const std::set* pokemon_slugs, - const std::string& ball_slug, int balls_used, - CatchResult result -); - - - -} -} -#endif +/* Shiny Notification + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_ShinyNotification_H +#define PokemonAutomation_Pokemon_ShinyNotification_H + +#include +#include +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "Pokemon_EncounterStats.h" +#include "Pokemon_DataTypes.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const Color COLOR_STAR_SHINY(0xffff99); +const Color COLOR_SQUARE_SHINY(0xb266ff); + + + +struct EncounterResult{ + std::set slug_candidates; + ShinyType shininess = ShinyType::UNKNOWN; +}; + + +void send_encounter_notification( + ProgramEnvironment& env, + EventNotificationOption& settings_nonshiny, + EventNotificationOption& settings_shiny, + bool enable_names, bool shiny_detected, + const std::vector& results, + double alpha, // Set to std::nan("") to hide the field. + const ImageViewRGB32& screenshot = ImageViewRGB32(), + const EncounterFrequencies* frequencies = nullptr +); + + +enum class CatchResult{ + POKEMON_CAUGHT, + POKEMON_FAINTED, + OWN_FAINTED, + OUT_OF_BALLS, + BALL_LIMIT_REACHED, + CANNOT_THROW_BALL, + TIMED_OUT, +}; +void send_catch_notification( + ProgramEnvironment& env, + EventNotificationOption& settings_catch_success, + EventNotificationOption& settings_catch_failed, + const std::set* pokemon_slugs, + const std::string& ball_slug, int balls_used, + CatchResult result +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.cpp b/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.cpp index 4efa1960b7..b662da5d1b 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.cpp @@ -1,47 +1,47 @@ -/* Shiny Sparkle Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon_ShinySparkleSet.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -ShinySparkleTracker::ShinySparkleTracker( - Logger& logger, VideoOverlay& overlay, - ShinySparkleSet& sparkle_set, - const ImageFloatBox& box -) - : VisualInferenceCallback("ShinySparkleTracker") - , m_box(box) - , m_logger(logger) - , m_current_sparkles(sparkle_set) - , m_overlays(overlay) -{} -void ShinySparkleTracker::clear_boxes(){ - m_overlays.clear(); -} -void ShinySparkleTracker::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool ShinySparkleTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ImageViewRGB32 image = extract_box_reference(frame, m_box); - m_current_sparkles.read_from_image(frame.total_pixels(), image); - m_overlays.clear(); - m_current_sparkles.draw_boxes(m_overlays, frame, m_box); - std::string log_str = m_current_sparkles.to_str(); - if (!log_str.empty()){ - m_logger.log(log_str, COLOR_BLUE); - } - return false; -} - - - -} -} +/* Shiny Sparkle Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon_ShinySparkleSet.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +ShinySparkleTracker::ShinySparkleTracker( + Logger& logger, VideoOverlay& overlay, + ShinySparkleSet& sparkle_set, + const ImageFloatBox& box +) + : VisualInferenceCallback("ShinySparkleTracker") + , m_box(box) + , m_logger(logger) + , m_current_sparkles(sparkle_set) + , m_overlays(overlay) +{} +void ShinySparkleTracker::clear_boxes(){ + m_overlays.clear(); +} +void ShinySparkleTracker::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool ShinySparkleTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ImageViewRGB32 image = extract_box_reference(frame, m_box); + m_current_sparkles.read_from_image(frame.total_pixels(), image); + m_overlays.clear(); + m_current_sparkles.draw_boxes(m_overlays, frame, m_box); + std::string log_str = m_current_sparkles.to_str(); + if (!log_str.empty()){ + m_logger.log(log_str, COLOR_BLUE); + } + return false; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.h b/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.h index dc51423a7f..12b54dc1e9 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_ShinySparkleSet.h @@ -1,63 +1,63 @@ -/* Shiny Sparkle Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_ShinySparkleSet_H -#define PokemonAutomation_Pokemon_ShinySparkleSet_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class Logger; -namespace Pokemon{ - - -class ShinySparkleSet{ -public: - virtual ~ShinySparkleSet() = default; - virtual void clear() = 0; - - virtual std::string to_str() const = 0; - - virtual void read_from_image(size_t screen_area, const ImageViewRGB32& image) = 0; - virtual void draw_boxes( - VideoOverlaySet& overlays, - const ImageViewRGB32& frame, - const ImageFloatBox& inference_box - ) const = 0; - -}; - - - -class ShinySparkleTracker : public VisualInferenceCallback{ -public: - ShinySparkleTracker( - Logger& logger, VideoOverlay& overlay, - ShinySparkleSet& sparkle_set, - const ImageFloatBox& box - ); - - void clear_boxes(); - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - using VisualInferenceCallback::process_frame; - -private: - ImageFloatBox m_box; - Logger& m_logger; - ShinySparkleSet& m_current_sparkles; - VideoOverlaySet m_overlays; -}; - - - - - -} -} -#endif +/* Shiny Sparkle Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_ShinySparkleSet_H +#define PokemonAutomation_Pokemon_ShinySparkleSet_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class Logger; +namespace Pokemon{ + + +class ShinySparkleSet{ +public: + virtual ~ShinySparkleSet() = default; + virtual void clear() = 0; + + virtual std::string to_str() const = 0; + + virtual void read_from_image(size_t screen_area, const ImageViewRGB32& image) = 0; + virtual void draw_boxes( + VideoOverlaySet& overlays, + const ImageViewRGB32& frame, + const ImageFloatBox& inference_box + ) const = 0; + +}; + + + +class ShinySparkleTracker : public VisualInferenceCallback{ +public: + ShinySparkleTracker( + Logger& logger, VideoOverlay& overlay, + ShinySparkleSet& sparkle_set, + const ImageFloatBox& box + ); + + void clear_boxes(); + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + using VisualInferenceCallback::process_frame; + +private: + ImageFloatBox m_box; + Logger& m_logger; + ShinySparkleSet& m_current_sparkles; + VideoOverlaySet m_overlays; +}; + + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.cpp b/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.cpp index 140c814cf0..d441bb9de4 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.cpp @@ -1,260 +1,260 @@ -/* Stats Calculation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Pokemon_StatsCalculation.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -#if 0 -NatureAdjustments get_nature_adjustments(NatureCheckerValue nature){ - NatureAdjustments ret; - ret.attack = NatureAdjustment::NEUTRAL; - ret.defense = NatureAdjustment::NEUTRAL; - ret.spatk = NatureAdjustment::NEUTRAL; - ret.spdef = NatureAdjustment::NEUTRAL; - ret.speed = NatureAdjustment::NEUTRAL; - - switch (nature){ - case NatureCheckerValue::UnableToDetect: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot query invalid nature."); - - case NatureCheckerValue::Neutral: - case NatureCheckerValue::Bashful: - case NatureCheckerValue::Docile: - case NatureCheckerValue::Hardy: - case NatureCheckerValue::Quirky: - case NatureCheckerValue::Serious: - return ret; - - case NatureCheckerValue::Bold: - ret.attack = NatureAdjustment::NEGATIVE; - ret.defense = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Modest: - ret.attack = NatureAdjustment::NEGATIVE; - ret.spatk = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Calm: - ret.attack = NatureAdjustment::NEGATIVE; - ret.spdef = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Timid: - ret.attack = NatureAdjustment::NEGATIVE; - ret.speed = NatureAdjustment::POSITIVE; - return ret; - - case NatureCheckerValue::Lonely: - ret.defense = NatureAdjustment::NEGATIVE; - ret.attack = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Mild: - ret.defense = NatureAdjustment::NEGATIVE; - ret.spatk = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Gentle: - ret.defense = NatureAdjustment::NEGATIVE; - ret.spdef = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Hasty: - ret.defense = NatureAdjustment::NEGATIVE; - ret.speed = NatureAdjustment::POSITIVE; - return ret; - - case NatureCheckerValue::Adamant: - ret.spatk = NatureAdjustment::NEGATIVE; - ret.attack = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Impish: - ret.spatk = NatureAdjustment::NEGATIVE; - ret.defense = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Careful: - ret.spatk = NatureAdjustment::NEGATIVE; - ret.spdef = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Jolly: - ret.spatk = NatureAdjustment::NEGATIVE; - ret.speed = NatureAdjustment::POSITIVE; - return ret; - - case NatureCheckerValue::Naughty: - ret.spdef = NatureAdjustment::NEGATIVE; - ret.attack = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Lax: - ret.spdef = NatureAdjustment::NEGATIVE; - ret.defense = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Rash: - ret.spdef = NatureAdjustment::NEGATIVE; - ret.spatk = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Naive: - ret.spdef = NatureAdjustment::NEGATIVE; - ret.speed = NatureAdjustment::POSITIVE; - return ret; - - case NatureCheckerValue::Brave: - ret.speed = NatureAdjustment::NEGATIVE; - ret.attack = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Relaxed: - ret.speed = NatureAdjustment::NEGATIVE; - ret.defense = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Quiet: - ret.speed = NatureAdjustment::NEGATIVE; - ret.spatk = NatureAdjustment::POSITIVE; - return ret; - case NatureCheckerValue::Sassy: - ret.speed = NatureAdjustment::NEGATIVE; - ret.spdef = NatureAdjustment::POSITIVE; - return ret; - - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Nature: " + std::to_string((int)nature)); - } -} -#endif - - -uint16_t calc_stats_hp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev){ - uint16_t stat = (uint16_t)2 * base_stat + iv + ev/4; - stat *= level; - stat /= 100; - stat += level; - stat += 10; - return stat; -} -uint16_t calc_stats_nonhp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev, NatureAdjustment nature){ - uint16_t stat = (uint16_t)2 * base_stat + iv + ev/4; - stat *= level; - stat /= 100; - stat += 5; - switch (nature){ - case NatureAdjustment::NEUTRAL: - break; - case NatureAdjustment::POSITIVE: - stat *= 110; - stat /= 100; - break; - case NatureAdjustment::NEGATIVE: - stat *= 90; - stat /= 100; - break; - } - return stat; -} - - -#if 0 -bool calc_iv_range( - uint8_t& low_iv, uint8_t& high_iv, - bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, - uint16_t stat, NatureAdjustment nature -){ - bool set = false; - for (uint8_t iv = 0; iv < 32; iv++){ - uint16_t current_stat = is_hp - ? calc_stats_hp(base_stat, level, iv, ev) - : calc_stats_nonhp(base_stat, level, iv, ev, nature); - - if (stat != current_stat){ - continue; - } - - if (!set){ - set = true; - low_iv = iv; - high_iv = iv; - continue; - } - - if (low_iv > iv){ - low_iv = iv; - } - if (high_iv < iv){ - high_iv = iv; - } - } - - return set; -} -#endif -IvRange calc_iv_range( - bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, - uint16_t stat, NatureAdjustment nature -){ - IvRange ret; - - bool set = false; - for (uint8_t iv = 0; iv < 32; iv++){ - uint16_t current_stat = is_hp - ? calc_stats_hp(base_stat, level, iv, ev) - : calc_stats_nonhp(base_stat, level, iv, ev, nature); - - if (stat != current_stat){ - continue; - } - - if (!set){ - set = true; - ret.low = iv; - ret.high = iv; - continue; - } - - if ((uint8_t)ret.low > iv){ - ret.low = iv; - } - if ((uint8_t)ret.high < iv){ - ret.high = iv; - } - } - - return ret; -} - - -IvRanges calc_iv_ranges( - const BaseStats& base_stats, uint8_t level, const EVs& evs, - const StatReads& actual_stats, const NatureAdjustments& natures -){ - IvRanges ret; - - if (actual_stats.hp >= 10){ - ret.hp = calc_iv_range(true, base_stats.hp, level, evs.hp, actual_stats.hp, NatureAdjustment::NEUTRAL); - } - if (actual_stats.attack >= 5){ - ret.attack = calc_iv_range(false, base_stats.attack, level, evs.attack, actual_stats.attack, natures.attack); - } - if (actual_stats.defense >= 5){ - ret.defense = calc_iv_range(false, base_stats.defense, level, evs.defense, actual_stats.defense, natures.defense); - } - if (actual_stats.spatk >= 5){ - ret.spatk = calc_iv_range(false, base_stats.spatk, level, evs.spatk, actual_stats.spatk, natures.spatk); - } - if (actual_stats.spdef >= 5){ - ret.spdef = calc_iv_range(false, base_stats.spdef, level, evs.spdef, actual_stats.spdef, natures.spdef); - } - if (actual_stats.speed >= 5){ - ret.speed = calc_iv_range(false, base_stats.speed, level, evs.speed, actual_stats.speed, natures.speed); - } - - return ret; -} - - - - - - - -} -} +/* Stats Calculation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Pokemon_StatsCalculation.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +#if 0 +NatureAdjustments get_nature_adjustments(NatureCheckerValue nature){ + NatureAdjustments ret; + ret.attack = NatureAdjustment::NEUTRAL; + ret.defense = NatureAdjustment::NEUTRAL; + ret.spatk = NatureAdjustment::NEUTRAL; + ret.spdef = NatureAdjustment::NEUTRAL; + ret.speed = NatureAdjustment::NEUTRAL; + + switch (nature){ + case NatureCheckerValue::UnableToDetect: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Cannot query invalid nature."); + + case NatureCheckerValue::Neutral: + case NatureCheckerValue::Bashful: + case NatureCheckerValue::Docile: + case NatureCheckerValue::Hardy: + case NatureCheckerValue::Quirky: + case NatureCheckerValue::Serious: + return ret; + + case NatureCheckerValue::Bold: + ret.attack = NatureAdjustment::NEGATIVE; + ret.defense = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Modest: + ret.attack = NatureAdjustment::NEGATIVE; + ret.spatk = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Calm: + ret.attack = NatureAdjustment::NEGATIVE; + ret.spdef = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Timid: + ret.attack = NatureAdjustment::NEGATIVE; + ret.speed = NatureAdjustment::POSITIVE; + return ret; + + case NatureCheckerValue::Lonely: + ret.defense = NatureAdjustment::NEGATIVE; + ret.attack = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Mild: + ret.defense = NatureAdjustment::NEGATIVE; + ret.spatk = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Gentle: + ret.defense = NatureAdjustment::NEGATIVE; + ret.spdef = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Hasty: + ret.defense = NatureAdjustment::NEGATIVE; + ret.speed = NatureAdjustment::POSITIVE; + return ret; + + case NatureCheckerValue::Adamant: + ret.spatk = NatureAdjustment::NEGATIVE; + ret.attack = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Impish: + ret.spatk = NatureAdjustment::NEGATIVE; + ret.defense = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Careful: + ret.spatk = NatureAdjustment::NEGATIVE; + ret.spdef = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Jolly: + ret.spatk = NatureAdjustment::NEGATIVE; + ret.speed = NatureAdjustment::POSITIVE; + return ret; + + case NatureCheckerValue::Naughty: + ret.spdef = NatureAdjustment::NEGATIVE; + ret.attack = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Lax: + ret.spdef = NatureAdjustment::NEGATIVE; + ret.defense = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Rash: + ret.spdef = NatureAdjustment::NEGATIVE; + ret.spatk = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Naive: + ret.spdef = NatureAdjustment::NEGATIVE; + ret.speed = NatureAdjustment::POSITIVE; + return ret; + + case NatureCheckerValue::Brave: + ret.speed = NatureAdjustment::NEGATIVE; + ret.attack = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Relaxed: + ret.speed = NatureAdjustment::NEGATIVE; + ret.defense = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Quiet: + ret.speed = NatureAdjustment::NEGATIVE; + ret.spatk = NatureAdjustment::POSITIVE; + return ret; + case NatureCheckerValue::Sassy: + ret.speed = NatureAdjustment::NEGATIVE; + ret.spdef = NatureAdjustment::POSITIVE; + return ret; + + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Nature: " + std::to_string((int)nature)); + } +} +#endif + + +uint16_t calc_stats_hp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev){ + uint16_t stat = (uint16_t)2 * base_stat + iv + ev/4; + stat *= level; + stat /= 100; + stat += level; + stat += 10; + return stat; +} +uint16_t calc_stats_nonhp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev, NatureAdjustment nature){ + uint16_t stat = (uint16_t)2 * base_stat + iv + ev/4; + stat *= level; + stat /= 100; + stat += 5; + switch (nature){ + case NatureAdjustment::NEUTRAL: + break; + case NatureAdjustment::POSITIVE: + stat *= 110; + stat /= 100; + break; + case NatureAdjustment::NEGATIVE: + stat *= 90; + stat /= 100; + break; + } + return stat; +} + + +#if 0 +bool calc_iv_range( + uint8_t& low_iv, uint8_t& high_iv, + bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, + uint16_t stat, NatureAdjustment nature +){ + bool set = false; + for (uint8_t iv = 0; iv < 32; iv++){ + uint16_t current_stat = is_hp + ? calc_stats_hp(base_stat, level, iv, ev) + : calc_stats_nonhp(base_stat, level, iv, ev, nature); + + if (stat != current_stat){ + continue; + } + + if (!set){ + set = true; + low_iv = iv; + high_iv = iv; + continue; + } + + if (low_iv > iv){ + low_iv = iv; + } + if (high_iv < iv){ + high_iv = iv; + } + } + + return set; +} +#endif +IvRange calc_iv_range( + bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, + uint16_t stat, NatureAdjustment nature +){ + IvRange ret; + + bool set = false; + for (uint8_t iv = 0; iv < 32; iv++){ + uint16_t current_stat = is_hp + ? calc_stats_hp(base_stat, level, iv, ev) + : calc_stats_nonhp(base_stat, level, iv, ev, nature); + + if (stat != current_stat){ + continue; + } + + if (!set){ + set = true; + ret.low = iv; + ret.high = iv; + continue; + } + + if ((uint8_t)ret.low > iv){ + ret.low = iv; + } + if ((uint8_t)ret.high < iv){ + ret.high = iv; + } + } + + return ret; +} + + +IvRanges calc_iv_ranges( + const BaseStats& base_stats, uint8_t level, const EVs& evs, + const StatReads& actual_stats, const NatureAdjustments& natures +){ + IvRanges ret; + + if (actual_stats.hp >= 10){ + ret.hp = calc_iv_range(true, base_stats.hp, level, evs.hp, actual_stats.hp, NatureAdjustment::NEUTRAL); + } + if (actual_stats.attack >= 5){ + ret.attack = calc_iv_range(false, base_stats.attack, level, evs.attack, actual_stats.attack, natures.attack); + } + if (actual_stats.defense >= 5){ + ret.defense = calc_iv_range(false, base_stats.defense, level, evs.defense, actual_stats.defense, natures.defense); + } + if (actual_stats.spatk >= 5){ + ret.spatk = calc_iv_range(false, base_stats.spatk, level, evs.spatk, actual_stats.spatk, natures.spatk); + } + if (actual_stats.spdef >= 5){ + ret.spdef = calc_iv_range(false, base_stats.spdef, level, evs.spdef, actual_stats.spdef, natures.spdef); + } + if (actual_stats.speed >= 5){ + ret.speed = calc_iv_range(false, base_stats.speed, level, evs.speed, actual_stats.speed, natures.speed); + } + + return ret; +} + + + + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.h b/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.h index 615418f65a..85712e61ad 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_StatsCalculation.h @@ -1,102 +1,102 @@ -/* Stats Calculation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_StatsCalculation_H -#define PokemonAutomation_Pokemon_StatsCalculation_H - -#include -#include "Pokemon_NatureChecker.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -struct BaseStats{ - uint8_t hp; - uint8_t attack; - uint8_t defense; - uint8_t spatk; - uint8_t spdef; - uint8_t speed; -}; -struct EVs{ - uint8_t hp = 0; - uint8_t attack = 0; - uint8_t defense = 0; - uint8_t spatk = 0; - uint8_t spdef = 0; - uint8_t speed = 0; -}; - - -struct StatReads{ - int16_t hp = -1; - int16_t attack = -1; - int16_t defense = -1; - int16_t spatk = -1; - int16_t spdef = -1; - int16_t speed = -1; -}; - -struct IvRange{ - int8_t low = -1; - int8_t high = -1; -}; -struct IvRanges{ - IvRange hp; - IvRange attack; - IvRange defense; - IvRange spatk; - IvRange spdef; - IvRange speed; -}; - - -enum class NatureAdjustment{ - NEUTRAL, - NEGATIVE, - POSITIVE, -}; -struct NatureAdjustments{ - NatureAdjustment attack; - NatureAdjustment defense; - NatureAdjustment spatk; - NatureAdjustment spdef; - NatureAdjustment speed; -}; -//NatureAdjustments get_nature_adjustments(NatureCheckerValue nature); - - - - -uint16_t calc_stats_hp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev); -uint16_t calc_stats_nonhp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev, NatureAdjustment nature); - - -#if 0 -bool calc_iv_range( - uint8_t& low_iv, uint8_t& high_iv, - bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, - uint16_t stat, NatureAdjustment nature -); -#endif -IvRange calc_iv_range( - bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, - uint16_t stat, NatureAdjustment nature -); - - -IvRanges calc_iv_ranges( - const BaseStats& base_stats, uint8_t level, const EVs& evs, - const StatReads& actual_stats, const NatureAdjustments& natures -); - - - -} -} -#endif +/* Stats Calculation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_StatsCalculation_H +#define PokemonAutomation_Pokemon_StatsCalculation_H + +#include +#include "Pokemon_NatureChecker.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +struct BaseStats{ + uint8_t hp; + uint8_t attack; + uint8_t defense; + uint8_t spatk; + uint8_t spdef; + uint8_t speed; +}; +struct EVs{ + uint8_t hp = 0; + uint8_t attack = 0; + uint8_t defense = 0; + uint8_t spatk = 0; + uint8_t spdef = 0; + uint8_t speed = 0; +}; + + +struct StatReads{ + int16_t hp = -1; + int16_t attack = -1; + int16_t defense = -1; + int16_t spatk = -1; + int16_t spdef = -1; + int16_t speed = -1; +}; + +struct IvRange{ + int8_t low = -1; + int8_t high = -1; +}; +struct IvRanges{ + IvRange hp; + IvRange attack; + IvRange defense; + IvRange spatk; + IvRange spdef; + IvRange speed; +}; + + +enum class NatureAdjustment{ + NEUTRAL, + NEGATIVE, + POSITIVE, +}; +struct NatureAdjustments{ + NatureAdjustment attack; + NatureAdjustment defense; + NatureAdjustment spatk; + NatureAdjustment spdef; + NatureAdjustment speed; +}; +//NatureAdjustments get_nature_adjustments(NatureCheckerValue nature); + + + + +uint16_t calc_stats_hp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev); +uint16_t calc_stats_nonhp(uint8_t base_stat, uint8_t level, uint8_t iv, uint8_t ev, NatureAdjustment nature); + + +#if 0 +bool calc_iv_range( + uint8_t& low_iv, uint8_t& high_iv, + bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, + uint16_t stat, NatureAdjustment nature +); +#endif +IvRange calc_iv_range( + bool is_hp, uint8_t base_stat, uint8_t level, uint8_t ev, + uint16_t stat, NatureAdjustment nature +); + + +IvRanges calc_iv_ranges( + const BaseStats& base_stats, uint8_t level, const EVs& evs, + const StatReads& actual_stats, const NatureAdjustments& natures +); + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Strings.cpp b/SerialPrograms/Source/Pokemon/Pokemon_Strings.cpp index 36769a41d2..2c420490fe 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Strings.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_Strings.cpp @@ -1,21 +1,21 @@ -/* Pokemon Strings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_Strings.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const std::string STRING_POKEBALL = "Pok\u00e9ball"; -const std::string STRING_POKEMON = "Pok\u00e9mon"; -const std::string STRING_POKEDEX = "Pok\u00e9dex"; -const std::string STRING_POKEJOB = "Pok\u00e9 Job"; - - - -} -} +/* Pokemon Strings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_Strings.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const std::string STRING_POKEBALL = "Pok\u00e9ball"; +const std::string STRING_POKEMON = "Pok\u00e9mon"; +const std::string STRING_POKEDEX = "Pok\u00e9dex"; +const std::string STRING_POKEJOB = "Pok\u00e9 Job"; + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Strings.h b/SerialPrograms/Source/Pokemon/Pokemon_Strings.h index 0214d551b5..aceecd7a0a 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Strings.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_Strings.h @@ -1,24 +1,24 @@ -/* Pokemon Strings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_Strings_H -#define PokemonAutomation_Pokemon_Strings_H - -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -extern const std::string STRING_POKEBALL; -extern const std::string STRING_POKEMON; -extern const std::string STRING_POKEDEX; -extern const std::string STRING_POKEJOB; - - -} -} -#endif +/* Pokemon Strings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_Strings_H +#define PokemonAutomation_Pokemon_Strings_H + +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +extern const std::string STRING_POKEBALL; +extern const std::string STRING_POKEMON; +extern const std::string STRING_POKEDEX; +extern const std::string STRING_POKEJOB; + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Types.cpp b/SerialPrograms/Source/Pokemon/Pokemon_Types.cpp index 460616a381..5a56be7386 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Types.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_Types.cpp @@ -1,43 +1,43 @@ -/* Pokemon Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_Types.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -const EnumStringMap& POKEMON_TYPE_SLUGS(){ - static EnumStringMap database{ - {PokemonType::NONE, "none"}, - {PokemonType::NORMAL, "normal"}, - {PokemonType::FIRE, "fire"}, - {PokemonType::FIGHTING, "fighting"}, - {PokemonType::WATER, "water"}, - {PokemonType::FLYING, "flying"}, - {PokemonType::GRASS, "grass"}, - {PokemonType::POISON, "poison"}, - {PokemonType::ELECTRIC, "electric"}, - {PokemonType::GROUND, "ground"}, - {PokemonType::PSYCHIC, "psychic"}, - {PokemonType::ROCK, "rock"}, - {PokemonType::ICE, "ice"}, - {PokemonType::BUG, "bug"}, - {PokemonType::DRAGON, "dragon"}, - {PokemonType::GHOST, "ghost"}, - {PokemonType::DARK, "dark"}, - {PokemonType::STEEL, "steel"}, - {PokemonType::FAIRY, "fairy"}, - }; - return database; -} - - - - -} -} +/* Pokemon Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +const EnumStringMap& POKEMON_TYPE_SLUGS(){ + static EnumStringMap database{ + {PokemonType::NONE, "none"}, + {PokemonType::NORMAL, "normal"}, + {PokemonType::FIRE, "fire"}, + {PokemonType::FIGHTING, "fighting"}, + {PokemonType::WATER, "water"}, + {PokemonType::FLYING, "flying"}, + {PokemonType::GRASS, "grass"}, + {PokemonType::POISON, "poison"}, + {PokemonType::ELECTRIC, "electric"}, + {PokemonType::GROUND, "ground"}, + {PokemonType::PSYCHIC, "psychic"}, + {PokemonType::ROCK, "rock"}, + {PokemonType::ICE, "ice"}, + {PokemonType::BUG, "bug"}, + {PokemonType::DRAGON, "dragon"}, + {PokemonType::GHOST, "ghost"}, + {PokemonType::DARK, "dark"}, + {PokemonType::STEEL, "steel"}, + {PokemonType::FAIRY, "fairy"}, + }; + return database; +} + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Types.h b/SerialPrograms/Source/Pokemon/Pokemon_Types.h index b4f01c7eaf..2a46facc3f 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Types.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_Types.h @@ -1,50 +1,50 @@ -/* Pokemon Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_Types_H -#define PokemonAutomation_Pokemon_Types_H - -#include -#include "Common/Cpp/EnumStringMap.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -enum class MoveCategory{ - STATUS, - PHYSICAL, - SPECIAL, - UNKNOWN, -}; - -enum class PokemonType{ - NONE, - NORMAL, - FIRE, - FIGHTING, - WATER, - FLYING, - GRASS, - POISON, - ELECTRIC, - GROUND, - PSYCHIC, - ROCK, - ICE, - BUG, - DRAGON, - GHOST, - DARK, - STEEL, - FAIRY, -}; -const EnumStringMap& POKEMON_TYPE_SLUGS(); - - -} -} -#endif +/* Pokemon Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_Types_H +#define PokemonAutomation_Pokemon_Types_H + +#include +#include "Common/Cpp/EnumStringMap.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +enum class MoveCategory{ + STATUS, + PHYSICAL, + SPECIAL, + UNKNOWN, +}; + +enum class PokemonType{ + NONE, + NORMAL, + FIRE, + FIGHTING, + WATER, + FLYING, + GRASS, + POISON, + ELECTRIC, + GROUND, + PSYCHIC, + ROCK, + ICE, + BUG, + DRAGON, + GHOST, + DARK, + STEEL, + FAIRY, +}; +const EnumStringMap& POKEMON_TYPE_SLUGS(); + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.cpp b/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.cpp index f0cd6c0bcc..dab06d9e47 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.cpp +++ b/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.cpp @@ -1,270 +1,270 @@ -/* Xoroshiro128+ and reverse - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Pokemon_Xoroshiro128Plus.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - -Xoroshiro128PlusState::Xoroshiro128PlusState(uint64_t s0, uint64_t s1) - : s0(s0) - , s1(s1) -{} - - -Xoroshiro128Plus::Xoroshiro128Plus(Xoroshiro128PlusState state) - : state(state) -{} - -Xoroshiro128Plus::Xoroshiro128Plus(uint64_t s0, uint64_t s1) - : state(Xoroshiro128PlusState(s0, s1)) -{} - -uint64_t Xoroshiro128Plus::rotl(const uint64_t x, const int k){ - return (x << k) | (x >> (64 - k)); -} - -uint64_t Xoroshiro128Plus::next(){ - const uint64_t s0 = state.s0; - uint64_t s1 = state.s1; - const uint64_t result = s0 + s1; - - s1 ^= s0; - state.s0 = rotl(s0, 24) ^ s1 ^ (s1 << 16); - state.s1 = rotl(s1, 37); - - return result; -} - -Xoroshiro128PlusState Xoroshiro128Plus::get_state(){ - return state; -} - -uint64_t nextPowerOfTwo(uint64_t number){ - uint64_t x = number; - x--; - x |= x >> 1; - x |= x >> 2; - x |= x >> 4; - x |= x >> 8; - x |= x >> 16; - x |= x >> 32; - x++; - return x; -} - -uint64_t Xoroshiro128Plus::nextInt(uint64_t bound){ - uint64_t power = nextPowerOfTwo(bound); - uint64_t result = next() & (power - 1); - while (result >= bound){ - result = next() & (power - 1); - } - return result; -} - -std::vector Xoroshiro128Plus::generate_last_bit_sequence(size_t max_advances){ - std::vector sequence(max_advances); - Xoroshiro128Plus temp_rng(Xoroshiro128PlusState(state.s0, state.s1)); - - for (size_t i = 0; i < max_advances; i++){ - sequence.at(i) = (temp_rng.next() & 1) == 1; - } - - return sequence; -} - - -std::pair Xoroshiro128Plus::advances_to_state(Xoroshiro128PlusState other_state, uint64_t max_advances) { - Xoroshiro128Plus temp_rng(get_state()); - uint64_t advances = 0; - - while (advances <= max_advances) { - Xoroshiro128PlusState temp_state = temp_rng.get_state(); - if (temp_state.s0 == other_state.s0 && temp_state.s1 == other_state.s1) { - return { true, advances }; - } - temp_rng.next(); - advances++; - } - return { false, advances }; -} - -// The generic solution to the system of equations to calculate the initial state from the last bits of 128 consecutive Xoroshiro128+ results. -uint64_t Xoroshiro128Plus::last_bits_reverse_matrix[128][2] = { - /*s0 bit 0*/ {0b0101001100100001111011111110111001010011111110101011100011001101, 0b0111010111110111000101010100001111101001111001011111001011010111} , - {0b0101010001010011100010011010100000100100111101101001100001100000, 0b1000110000001001010011000111001111111111111101110011110001000000}, - {0b0110010000111101101000100110010000011111010111011011100100011001, 0b0001001011110010110110010101101001011110101110010001100111010111}, - {0b0001010111110001100111010110010001000000110101100100001111000111, 0b0000111010011000110111101101011111110010010111001110110100000001}, - {0b0110101010001010010010010111001010100111110010110001110111010000, 0b1101010010101000010001000101100011010101101000011000010011111110}, - {0b0101111110111111110111101011001011100111110010010100001101010000, 0b1100010100111110001001011000001101010100000101010000110111000000}, - {0b1111100100110000110011011000111100000010110111001110111100110000, 0b1101011010100111000100100000001010000111011001100101001001110100}, - {0b1111001001000110100100100111100110010101101110111010111011110010, 0b1000110011100101011101110110100100100110110000001111011111010101}, - {0b1000101111010110110001111000100011001001011001111111010001011110, 0b1110010101111000110001000000001001111110111100101001111111110101}, - {0b0011011111110111010101001010100101110101110011110001010000000110, 0b1001101100000101011110000110111010000000011110101011001110011000}, - /*s0 bit 10*/{0b1100011000100101110010010000010101011101001101101101010111000011, 0b0010101110110011101000100011110010010010111000110111101010100100}, - {0b0110000010110101110001110000100100111001111001000100101101001101, 0b0010011110100101001001100101011010101111101100100111000011001000}, - {0b1110110100010111101100110100000010110110000011100110001000011110, 0b0111000000001101101000100001011000100010101110011110101011011111}, - {0b1010100011101110101010100100100101001000101000111010101001011100, 0b1001011110110001011101001000101001010001011010000100011101010000}, - {0b0010000111110000101111010001010001101111001100001011010011100001, 0b1010101000101111110011001100110001010110001001011101010111101011}, - {0b0100010001011100011101011101110110101100101110001110111111100000, 0b0111101101010000011111111011110010101101100010010010111010001110}, - {0b0111111111001100001101000111011100110100101010011100001010011010, 0b0110100110110000111011110010100000101101011100010000111111101111}, - {0b0000100111110100110110011101110111111001110101001001010010010111, 0b1110000110010111000010101110100111001010110110011110110111011100}, - {0b1001000011111110010011100000011010010001001011110010101100100010, 0b1011110101011010110010111010111110101110011111011010111111110000}, - {0b0111100010101001011100110101100110111110100111110110110111010011, 0b1110111101010000001110110011000111111100100010111011100001100110}, - /*s0 bit 20*/{0b1110100101000011101010001110100100111110011111001110000110100000, 0b0100100001111100111100101100000110011011010011110001001000110101}, - {0b0011000101010101001110010101110000010011011100101100010100001000, 0b1101010100100011000001110111100010000010100011101101101010100010}, - {0b0100011001010010001110110000011001011110011010111011111110100110, 0b1010100001010100001100101111101100101001010111101111100001111110}, - {0b0101100011010100101011000110000110001011010100100111001011010010, 0b0101101111010000001110101101010001001101101001001010111111000001}, - {0b0010111110010011001001110101001001001011110100101101001010000001, 0b0111100010111111111111100010010101001101010101110110000101101010}, - {0b0001011001011000101011100111011010111011100111000000111010100000, 0b0101011010010110101110001110010001000100000000111001110000000111}, - {0b0000111111111001100000000000111011000010010101001111100111111001, 0b1100111101001010010010100000101100011110011001101101101001010111}, - {0b0011100110110100000010011101100000110000001110000010011001110000, 0b1100010010011001000100100111111100001000000010101010010111110010}, - {0b1010011000110011100101100001110000000111011000110011001011110001, 0b0111000101010101011001100111010101100110110000000100101110010001}, - {0b1000000111000001100010011001010101000010010010001011110101101100, 0b0110000111100001101111001010110000011011111000101000011011011110}, - /*s0 bit 30*/{0b1000010011101001111010100010011101101001011010010010010111110101, 0b0111111100110100111110111110001110100000111001100010000011010011}, - {0b1111011100001000010011011100010000000101011000011001001100100111, 0b1000110100100100010101000000111000101000000101011000010011001000}, - {0b0100000111001101011011110101001011010001110101011001100001011000, 0b1110010100000101011010111100100111001111011011111110111101111010}, - {0b0101000111111010111101001011101000011110011101010000010001100011, 0b0111110110010111100110001000100100011110100011100110000010101100}, - {0b1100000011101010100010000111001001110011011101000111010010001110, 0b0001110001111001001111111010101110101011001101001000100010101111}, - {0b0000100101111111110100100010111110001111000011001010000000000111, 0b0010101110100110110001001111000110010101111010010011010110111110}, - {0b0010001110010011010010110110110110110111101110001001110101010001, 0b1001001100101001101011100101011100010110101110011000000101101101}, - {0b1011011101111100011111010101000111010011001000100111010111010111, 0b0010001101010001100110100001001010111111110011100101110000110000}, - {0b0111101101100000011000110010011011010010011111111110101111011111, 0b1000111000100111100001101000100010100111010100110111011000100000}, - {0b0010101001101100100000010100111101100110000101000111100111110100, 0b1101010110010111110010001011010110100001101010110010111110011100}, - /*s0 bit 40*/{0b0111100001010010101011110110000100100111000111101000001010001101, 0b1110001000110001011011101111111101011101011110010111001110111011}, - {0b1011100000011000010000000110111010000100110111000111000010101000, 0b1001111111000111011010100010011110111101000100000110011110100101}, - {0b0000100010001111110001011110101011111011101011001110100010101110, 0b0011011010000110001111100010001011011010000000011110010011110010}, - {0b0110110011110000010000001010000100110101000111001000010101110101, 0b0111011110100101111011111011010010101001110101000111100111100001}, - {0b0111000110101000111100011110111111110000001100100111100101001111, 0b0001111011110001111101100011110000001010000100111011111011001010}, - {0b1001111100011001000010001100001110010110101100000001100010011001, 0b0010101111000000101001000110001100011010110110000101010110011111}, - {0b1001100111000101100011001111101110110010100110111111111110000110, 0b0000011101001101011110010010010101110110100001001001001000010110}, - {0b1000111010100011101100101101110010110100000110011101101010010001, 0b0010001100010110010100010100010011000001110000110101101010100101}, - {0b0110110001011110000010110101110010111101000110101000110110011000, 0b1000110101110100110100100001000000001110100111011100111100111010}, - {0b0110111010011100111011111011000001011011110110001111111011111011, 0b1111110110011000100001100000110001000000010011000010001010110101}, - /*s0 bit 50*/{0b0100010010110110110111011011110010011111000100111001000000101100, 0b1001011111100111000011000010101110011100111000010111110001010110}, - {0b0100010110011001111011001101111111011001011001111010110111110010, 0b0101010111111000100111011111110101010110100100001011111011101001}, - {0b0111110001100101001000000101001011001001110111111000110101110110, 0b0101110111101000110000100100001011011001000000101100010011011101}, - {0b0010010111110110111001111110010111101110001010001011000110101001, 0b1111011010110111100010111101010101101110101111110011110101010111}, - {0b1011100111000100010001001111000100100001000100011001110100111111, 0b1110101110001011110110011001010010010101000110010001010001001001}, - {0b0010010011001000000011110110010011000111001001100100110100110110, 0b0000100100100111000111101110101100000111011111110010111111010100}, - {0b0101000101000011101011011110101110111010100111100101010101000101, 0b0100101110001011111010011111001010100111000101111111011110000000}, - {0b1110011101110010110010110100001001000111011110100110100101010010, 0b0100000110001111100011100001000011110101101011010100000110011100}, - {0b0111100001110000111100100011100011111001101101110011100111101001, 0b1110111101001000000101101011111000000111011001110111111011101010}, - {0b0100000000010101110011101100101011111011001000011001100100011001, 0b1100010011111111001010001110010111101001101000000101000010001001}, - /*s0 bit 60*/{0b0101101000111000001010101011111010000010011011111001100011011111, 0b1100110010111101001011101100100010001000110000001110011111000110}, - {0b1000111011001110110011100010100110110010101001100111011101101011, 0b0000000010001010101110001011000110101000100111100000010010000100}, - {0b1000110101011110011101010001001010111101101011001000100001001100, 0b1101001001010111001100111110110111100101100000111100001011001101}, - {0b1011000110100011111010110001011111001011010001110101000010000101, 0b1110000000100101110011001011110001111001110010110111111110000011}, - - /*s1 bit 0*/{0b1101111011001010010100100111010111001001000000010111111000010001, 0b1111101110010001100010011011000000100010100111011110011011001111}, - {0b1001101111110011000001000000111010001011101101011011101010011011, 0b1100001011011000000110000100101110110111100001000110110000100100}, - {0b1110010101010001000000000110101110110011001011101111111100101000, 0b1011110111011110000010010100101111101100110100101000001001010011}, - {0b0111000011001010101101011011100001010011001001100010001101100110, 0b1001000100110101011100111101101001110011010001110111111001001011}, - {0b1110010000100100001010111100011101111001111000100000000000010100, 0b0000010101110100011010010000001100100010111000001000010100000001}, - {0b1001100101110010010111001100001111000011000111010100000000010001, 0b1101000100011011101101000110001111011110011011011101011001010111}, - {0b1111011001010100010100100001000000110010101011110100000001000101, 0b0111000011001011000011001001110101011101110110101000001110100110}, - {0b0010110000001001101010111011001010011100110100011010110001010000, 0b1011110001100000000011001101001011111101100011000101010010011011}, - {0b1100110000000010000010010011011111001101011000010110001101000010, 0b0000101101110000010110010010010100011111011100011111111111011111}, - {0b0110101001010100101001110010111101101011101110100110001111000111, 0b0111111101111001101100100010111100101101111101000010010011001110}, - /*s1 bit 10*/{0b0110101000101110100101100010111110011111011011101000011101110100, 0b0011101011011100101111111001011010001100010000101011010100001111}, - {0b0111101111111001001101111001100111110010001101101101000000000100, 0b0001000000000000111000110000000000010001111110101101000011010001}, - {0b0000000101110010010001101110001010110000010001101101011011110110, 0b1100101110010010011101101101000101000000101110010100010110000101}, - {0b1100100011110111111111000110001011111000100111011000111010001011, 0b1001011100000101111100010100011001011011101001011010100100011111}, - {0b1000010011110010011000101100110110101010101011110011101101101000, 0b0001101010110010110100010101000000001001111101000101111101111001}, - {0b1010011001000000111101010000011101111000001000001111110001101011, 0b1110101001110110001111110111101001111110111100110011000101100010}, - {0b0111010000100001000000001010001110100010100011000101000000110001, 0b1000111001010000110110111101010100101110111011011001001111110110}, - {0b1111101000100101001111101101100111111111011100001111010011111100, 0b1011111111010100010000000000110000111001010100101011111110011111}, - {0b1010110001110000111001001101111110011110010101111001001011110110, 0b1111111110000111111000011001001001011100011011010111001011001000}, - {0b1010111011011011110001010000010111010011110011011101000001110001, 0b1001100011101010001101111010001011111101111101011110100001011110}, - /*s1 bit 20*/{0b1111010010011011011110001111100110110100110100110100000001111101, 0b1000001010100001100110111100001101100000000111101001101000100100}, - {0b0101100110000110110111011110000100000110000010101101101010001101, 0b1100001001111000001110001111010110111001000111100000000100001011}, - {0b1011000101000111001010000111100110000110000111110100001010111110, 0b0001101001011111010111101000011000010000101101110010000001000101}, - {0b1000100010110101110010001011100000100011011101011110111010111110, 0b0000101111000001011100100101111101011100110111001110001110101101}, - {0b1110110001100100101111001001000110010100010000111111110101111010, 0b1010101011001100101101100100000010101101100000111011000111000000}, - {0b0000000111111010000000110001111000000001011110111111011100000001, 0b1000001011111111010101100001101110110111001111100011001000110001}, - {0b0000000000001010101100111101010011011101111000111011010100100001, 0b0101011110000101101110010001010011100010100000100010000000000001}, - {0b0001101111011101110010001110001111101000000101000011100010011000, 0b0100101101001000100000001111001101110100011100100000100000110001}, - {0b1001111101001011101010001001100110000011011001011111000011010111, 0b1100101000100111000100010110010001110010011001001000000011001001}, - {0b0000001011010011111101111100101110000101000001010011100101000010, 0b0000100111011100000110010011011110000110010101010001011100001001}, - /*s1 bit 30*/{0b1100101001110110010100011011100000100111111000001100000101000011, 0b0011111101011011010110100001101100000010001101110010011010010100}, - {0b0001110101010110011101101011111101100001101100011000111010101000, 0b1111010000111101111000111010001100001100000000000010001111111111}, - {0b1000110110010001101101110011011010010100010010111011001110100011, 0b0111111111001110100110101101010111110110011100111001011100101111}, - {0b0001111011001001001111110011111001100000111001110101111011101011, 0b0100110011011000001111010011111110110101011110011010001110100100}, - {0b1011110010010100110000000100001011001111001101111011000001100101, 0b0011011010001111010011100110001101010100000110110110011010011101}, - {0b1000111110101001100111010111111000001000000011010010111000111001, 0b1101110000010001001110100100111011000011000001101100000001010100}, - {0b1011101101000111111001110000110000111100111010101110111110000011, 0b1100100011111001100101001000001101011011000111010010111010101100}, - {0b0101100000011100000011011000000101011001010100110001000001001111, 0b0111010101011011100000100100000011011111110000011011111101010111}, - {0b0011011010011001111000010010000110010111101001010011011010010010, 0b0110111101001011100010101010110101111100100100010100000000110010}, - {0b1101100011000001010110001001000011010001011100101101110011110000, 0b0010000010111010000100001001101000100110100000110111111010110101}, - /*s1 bit 40*/{0b1100000000110010101011000101011101100000011111000100100110101110, 0b0000000101101001000010111001100000010101100110111101110010011110}, - {0b0100101000001111000011000110011101010110110111001010101000110010, 0b0011011010111111100000100010110001011101001000010011010100100101}, - {0b1100010000110011101100100110000101110100110100111001001000110110, 0b0111010111001001001110001001100101000100011101100001111111011001}, - {0b0001011111011010011010011010100100101100010010110010010101010111, 0b1100111111000000011010011111101000000111001110010011100000110010}, - {0b1110011110101001011111011101110011010000101010110111010111110111, 0b1110101100000011001011001101111100000101100101001000010010000111}, - {0b0111100100011101010101011011001000011110111100010111001110101000, 0b1000010110111010010101000111101111100100001000011011101001110000}, - {0b1010110011101111110111110110110000000111010001101100111001100101, 0b1011100011110001101000000011001011100000011111101000000001110001}, - {0b0011101110110001101000000010000100010101010111110100001110111011, 0b1001010110111010110100100000010111110110101000110001000000100010}, - {0b1101000110100111110010010111101000101010111100000011111100001010, 0b0010111010110110011111110001101001110111001000011011011101010010}, - {0b1110111000100000100101010010101101101101000010100100111100010000, 0b0011001110010011011000011110111010010001010100011001000001110111}, - /*s1 bit 50*/{0b1010000011001000011110100110011110001101101011001000110111111001, 0b1111011110100111001010000000001011000000011100101011100011011001}, - {0b1000011111100101100001000101001101100010110000011110101011010110, 0b1111001101100011001010011101111100100011001010111000000101010101}, - {0b0010111101000101010110101101000101110101110011111111001101000011, 0b1010100011010011110111011111111111100110011110110101110001101100}, - {0b0001111111100110011001111011010000111111011011101001100110110001, 0b0011000110011111111001100011111111111001110010011111010010101100}, - {0b0100010011010011100000100111011110110000010110000011110111010001, 0b0001111110100011001001010001100011111000111100010101101110000110}, - {0b0111001011110000011111010000101100001000000011011000010001001101, 0b0111011011100100111011100010001000101001010010011001011010110000}, - {0b0000011000101110010011110110100101010011011110001011110101111101, 0b1000011111111110111100100010001111011001111011010000001110101111}, - {0b1001110100111111011101110011111010011101000100111100100101101100, 0b1000000011011111010000111111000101000101101000100000110010001110}, - {0b1101010010110110110001010010001000010100010000111000111000111111, 0b1010010110110110110101100100111010101010101010010110111001101111}, - {0b1001100010110011000000110001110001010110110111111110001011010110, 0b0110001000010010010110110010110010010000101110101101000010101011}, - /*s1 bit 60*/{0b1001111001100111100101110000100011111101001001001011010100010000, 0b0110001010011111010010110110110101010111111011111000011000010000}, - {0b1111100011111100100100000110000101111000100001111000100111010110, 0b0101010111101100111000111001000111111110010111111101110001100100}, - {0b0000110110100110001011010111011111010011111000001010100101011100, 0b1011100011101010010001000110101001001111010111011100101111010101}, - {0b0011000110100011111010110001011111001011010001110101000010000101, 0b1110000000100101110011001011110001111001110010110111111110000011} -}; - - -Xoroshiro128Plus Xoroshiro128Plus::xoroshiro128plus_from_last_bits(std::pair last_bits){ - uint64_t s0 = 0; - uint64_t s1 = 0; - - for (size_t i = 0; i < 64; i++){ - uint64_t first_half = last_bits_reverse_matrix[i][0] & last_bits.first; - uint64_t second_half = last_bits_reverse_matrix[i][1] & last_bits.second; - - uint64_t x = first_half ^ second_half; - x ^= x >> 32; - x ^= x >> 16; - x ^= x >> 8; - x ^= x >> 4; - x ^= x >> 2; - x ^= x >> 1; - x &= 1; - - s0 += x << (63 - i); - } - for (size_t i = 0; i < 64; i++){ - uint64_t first_half = last_bits_reverse_matrix[i + 64][0] & last_bits.first; - uint64_t second_half = last_bits_reverse_matrix[i + 64][1] & last_bits.second; - - uint64_t x = first_half ^ second_half; - x ^= x >> 32; - x ^= x >> 16; - x ^= x >> 8; - x ^= x >> 4; - x ^= x >> 2; - x ^= x >> 1; - x &= 1; - - s1 += x << (63 - i); - } - Xoroshiro128PlusState state(s0, s1); - return Xoroshiro128Plus(state); -} - - -} -} +/* Xoroshiro128+ and reverse + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Pokemon_Xoroshiro128Plus.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + +Xoroshiro128PlusState::Xoroshiro128PlusState(uint64_t s0, uint64_t s1) + : s0(s0) + , s1(s1) +{} + + +Xoroshiro128Plus::Xoroshiro128Plus(Xoroshiro128PlusState state) + : state(state) +{} + +Xoroshiro128Plus::Xoroshiro128Plus(uint64_t s0, uint64_t s1) + : state(Xoroshiro128PlusState(s0, s1)) +{} + +uint64_t Xoroshiro128Plus::rotl(const uint64_t x, const int k){ + return (x << k) | (x >> (64 - k)); +} + +uint64_t Xoroshiro128Plus::next(){ + const uint64_t s0 = state.s0; + uint64_t s1 = state.s1; + const uint64_t result = s0 + s1; + + s1 ^= s0; + state.s0 = rotl(s0, 24) ^ s1 ^ (s1 << 16); + state.s1 = rotl(s1, 37); + + return result; +} + +Xoroshiro128PlusState Xoroshiro128Plus::get_state(){ + return state; +} + +uint64_t nextPowerOfTwo(uint64_t number){ + uint64_t x = number; + x--; + x |= x >> 1; + x |= x >> 2; + x |= x >> 4; + x |= x >> 8; + x |= x >> 16; + x |= x >> 32; + x++; + return x; +} + +uint64_t Xoroshiro128Plus::nextInt(uint64_t bound){ + uint64_t power = nextPowerOfTwo(bound); + uint64_t result = next() & (power - 1); + while (result >= bound){ + result = next() & (power - 1); + } + return result; +} + +std::vector Xoroshiro128Plus::generate_last_bit_sequence(size_t max_advances){ + std::vector sequence(max_advances); + Xoroshiro128Plus temp_rng(Xoroshiro128PlusState(state.s0, state.s1)); + + for (size_t i = 0; i < max_advances; i++){ + sequence.at(i) = (temp_rng.next() & 1) == 1; + } + + return sequence; +} + + +std::pair Xoroshiro128Plus::advances_to_state(Xoroshiro128PlusState other_state, uint64_t max_advances) { + Xoroshiro128Plus temp_rng(get_state()); + uint64_t advances = 0; + + while (advances <= max_advances) { + Xoroshiro128PlusState temp_state = temp_rng.get_state(); + if (temp_state.s0 == other_state.s0 && temp_state.s1 == other_state.s1) { + return { true, advances }; + } + temp_rng.next(); + advances++; + } + return { false, advances }; +} + +// The generic solution to the system of equations to calculate the initial state from the last bits of 128 consecutive Xoroshiro128+ results. +uint64_t Xoroshiro128Plus::last_bits_reverse_matrix[128][2] = { + /*s0 bit 0*/ {0b0101001100100001111011111110111001010011111110101011100011001101, 0b0111010111110111000101010100001111101001111001011111001011010111} , + {0b0101010001010011100010011010100000100100111101101001100001100000, 0b1000110000001001010011000111001111111111111101110011110001000000}, + {0b0110010000111101101000100110010000011111010111011011100100011001, 0b0001001011110010110110010101101001011110101110010001100111010111}, + {0b0001010111110001100111010110010001000000110101100100001111000111, 0b0000111010011000110111101101011111110010010111001110110100000001}, + {0b0110101010001010010010010111001010100111110010110001110111010000, 0b1101010010101000010001000101100011010101101000011000010011111110}, + {0b0101111110111111110111101011001011100111110010010100001101010000, 0b1100010100111110001001011000001101010100000101010000110111000000}, + {0b1111100100110000110011011000111100000010110111001110111100110000, 0b1101011010100111000100100000001010000111011001100101001001110100}, + {0b1111001001000110100100100111100110010101101110111010111011110010, 0b1000110011100101011101110110100100100110110000001111011111010101}, + {0b1000101111010110110001111000100011001001011001111111010001011110, 0b1110010101111000110001000000001001111110111100101001111111110101}, + {0b0011011111110111010101001010100101110101110011110001010000000110, 0b1001101100000101011110000110111010000000011110101011001110011000}, + /*s0 bit 10*/{0b1100011000100101110010010000010101011101001101101101010111000011, 0b0010101110110011101000100011110010010010111000110111101010100100}, + {0b0110000010110101110001110000100100111001111001000100101101001101, 0b0010011110100101001001100101011010101111101100100111000011001000}, + {0b1110110100010111101100110100000010110110000011100110001000011110, 0b0111000000001101101000100001011000100010101110011110101011011111}, + {0b1010100011101110101010100100100101001000101000111010101001011100, 0b1001011110110001011101001000101001010001011010000100011101010000}, + {0b0010000111110000101111010001010001101111001100001011010011100001, 0b1010101000101111110011001100110001010110001001011101010111101011}, + {0b0100010001011100011101011101110110101100101110001110111111100000, 0b0111101101010000011111111011110010101101100010010010111010001110}, + {0b0111111111001100001101000111011100110100101010011100001010011010, 0b0110100110110000111011110010100000101101011100010000111111101111}, + {0b0000100111110100110110011101110111111001110101001001010010010111, 0b1110000110010111000010101110100111001010110110011110110111011100}, + {0b1001000011111110010011100000011010010001001011110010101100100010, 0b1011110101011010110010111010111110101110011111011010111111110000}, + {0b0111100010101001011100110101100110111110100111110110110111010011, 0b1110111101010000001110110011000111111100100010111011100001100110}, + /*s0 bit 20*/{0b1110100101000011101010001110100100111110011111001110000110100000, 0b0100100001111100111100101100000110011011010011110001001000110101}, + {0b0011000101010101001110010101110000010011011100101100010100001000, 0b1101010100100011000001110111100010000010100011101101101010100010}, + {0b0100011001010010001110110000011001011110011010111011111110100110, 0b1010100001010100001100101111101100101001010111101111100001111110}, + {0b0101100011010100101011000110000110001011010100100111001011010010, 0b0101101111010000001110101101010001001101101001001010111111000001}, + {0b0010111110010011001001110101001001001011110100101101001010000001, 0b0111100010111111111111100010010101001101010101110110000101101010}, + {0b0001011001011000101011100111011010111011100111000000111010100000, 0b0101011010010110101110001110010001000100000000111001110000000111}, + {0b0000111111111001100000000000111011000010010101001111100111111001, 0b1100111101001010010010100000101100011110011001101101101001010111}, + {0b0011100110110100000010011101100000110000001110000010011001110000, 0b1100010010011001000100100111111100001000000010101010010111110010}, + {0b1010011000110011100101100001110000000111011000110011001011110001, 0b0111000101010101011001100111010101100110110000000100101110010001}, + {0b1000000111000001100010011001010101000010010010001011110101101100, 0b0110000111100001101111001010110000011011111000101000011011011110}, + /*s0 bit 30*/{0b1000010011101001111010100010011101101001011010010010010111110101, 0b0111111100110100111110111110001110100000111001100010000011010011}, + {0b1111011100001000010011011100010000000101011000011001001100100111, 0b1000110100100100010101000000111000101000000101011000010011001000}, + {0b0100000111001101011011110101001011010001110101011001100001011000, 0b1110010100000101011010111100100111001111011011111110111101111010}, + {0b0101000111111010111101001011101000011110011101010000010001100011, 0b0111110110010111100110001000100100011110100011100110000010101100}, + {0b1100000011101010100010000111001001110011011101000111010010001110, 0b0001110001111001001111111010101110101011001101001000100010101111}, + {0b0000100101111111110100100010111110001111000011001010000000000111, 0b0010101110100110110001001111000110010101111010010011010110111110}, + {0b0010001110010011010010110110110110110111101110001001110101010001, 0b1001001100101001101011100101011100010110101110011000000101101101}, + {0b1011011101111100011111010101000111010011001000100111010111010111, 0b0010001101010001100110100001001010111111110011100101110000110000}, + {0b0111101101100000011000110010011011010010011111111110101111011111, 0b1000111000100111100001101000100010100111010100110111011000100000}, + {0b0010101001101100100000010100111101100110000101000111100111110100, 0b1101010110010111110010001011010110100001101010110010111110011100}, + /*s0 bit 40*/{0b0111100001010010101011110110000100100111000111101000001010001101, 0b1110001000110001011011101111111101011101011110010111001110111011}, + {0b1011100000011000010000000110111010000100110111000111000010101000, 0b1001111111000111011010100010011110111101000100000110011110100101}, + {0b0000100010001111110001011110101011111011101011001110100010101110, 0b0011011010000110001111100010001011011010000000011110010011110010}, + {0b0110110011110000010000001010000100110101000111001000010101110101, 0b0111011110100101111011111011010010101001110101000111100111100001}, + {0b0111000110101000111100011110111111110000001100100111100101001111, 0b0001111011110001111101100011110000001010000100111011111011001010}, + {0b1001111100011001000010001100001110010110101100000001100010011001, 0b0010101111000000101001000110001100011010110110000101010110011111}, + {0b1001100111000101100011001111101110110010100110111111111110000110, 0b0000011101001101011110010010010101110110100001001001001000010110}, + {0b1000111010100011101100101101110010110100000110011101101010010001, 0b0010001100010110010100010100010011000001110000110101101010100101}, + {0b0110110001011110000010110101110010111101000110101000110110011000, 0b1000110101110100110100100001000000001110100111011100111100111010}, + {0b0110111010011100111011111011000001011011110110001111111011111011, 0b1111110110011000100001100000110001000000010011000010001010110101}, + /*s0 bit 50*/{0b0100010010110110110111011011110010011111000100111001000000101100, 0b1001011111100111000011000010101110011100111000010111110001010110}, + {0b0100010110011001111011001101111111011001011001111010110111110010, 0b0101010111111000100111011111110101010110100100001011111011101001}, + {0b0111110001100101001000000101001011001001110111111000110101110110, 0b0101110111101000110000100100001011011001000000101100010011011101}, + {0b0010010111110110111001111110010111101110001010001011000110101001, 0b1111011010110111100010111101010101101110101111110011110101010111}, + {0b1011100111000100010001001111000100100001000100011001110100111111, 0b1110101110001011110110011001010010010101000110010001010001001001}, + {0b0010010011001000000011110110010011000111001001100100110100110110, 0b0000100100100111000111101110101100000111011111110010111111010100}, + {0b0101000101000011101011011110101110111010100111100101010101000101, 0b0100101110001011111010011111001010100111000101111111011110000000}, + {0b1110011101110010110010110100001001000111011110100110100101010010, 0b0100000110001111100011100001000011110101101011010100000110011100}, + {0b0111100001110000111100100011100011111001101101110011100111101001, 0b1110111101001000000101101011111000000111011001110111111011101010}, + {0b0100000000010101110011101100101011111011001000011001100100011001, 0b1100010011111111001010001110010111101001101000000101000010001001}, + /*s0 bit 60*/{0b0101101000111000001010101011111010000010011011111001100011011111, 0b1100110010111101001011101100100010001000110000001110011111000110}, + {0b1000111011001110110011100010100110110010101001100111011101101011, 0b0000000010001010101110001011000110101000100111100000010010000100}, + {0b1000110101011110011101010001001010111101101011001000100001001100, 0b1101001001010111001100111110110111100101100000111100001011001101}, + {0b1011000110100011111010110001011111001011010001110101000010000101, 0b1110000000100101110011001011110001111001110010110111111110000011}, + + /*s1 bit 0*/{0b1101111011001010010100100111010111001001000000010111111000010001, 0b1111101110010001100010011011000000100010100111011110011011001111}, + {0b1001101111110011000001000000111010001011101101011011101010011011, 0b1100001011011000000110000100101110110111100001000110110000100100}, + {0b1110010101010001000000000110101110110011001011101111111100101000, 0b1011110111011110000010010100101111101100110100101000001001010011}, + {0b0111000011001010101101011011100001010011001001100010001101100110, 0b1001000100110101011100111101101001110011010001110111111001001011}, + {0b1110010000100100001010111100011101111001111000100000000000010100, 0b0000010101110100011010010000001100100010111000001000010100000001}, + {0b1001100101110010010111001100001111000011000111010100000000010001, 0b1101000100011011101101000110001111011110011011011101011001010111}, + {0b1111011001010100010100100001000000110010101011110100000001000101, 0b0111000011001011000011001001110101011101110110101000001110100110}, + {0b0010110000001001101010111011001010011100110100011010110001010000, 0b1011110001100000000011001101001011111101100011000101010010011011}, + {0b1100110000000010000010010011011111001101011000010110001101000010, 0b0000101101110000010110010010010100011111011100011111111111011111}, + {0b0110101001010100101001110010111101101011101110100110001111000111, 0b0111111101111001101100100010111100101101111101000010010011001110}, + /*s1 bit 10*/{0b0110101000101110100101100010111110011111011011101000011101110100, 0b0011101011011100101111111001011010001100010000101011010100001111}, + {0b0111101111111001001101111001100111110010001101101101000000000100, 0b0001000000000000111000110000000000010001111110101101000011010001}, + {0b0000000101110010010001101110001010110000010001101101011011110110, 0b1100101110010010011101101101000101000000101110010100010110000101}, + {0b1100100011110111111111000110001011111000100111011000111010001011, 0b1001011100000101111100010100011001011011101001011010100100011111}, + {0b1000010011110010011000101100110110101010101011110011101101101000, 0b0001101010110010110100010101000000001001111101000101111101111001}, + {0b1010011001000000111101010000011101111000001000001111110001101011, 0b1110101001110110001111110111101001111110111100110011000101100010}, + {0b0111010000100001000000001010001110100010100011000101000000110001, 0b1000111001010000110110111101010100101110111011011001001111110110}, + {0b1111101000100101001111101101100111111111011100001111010011111100, 0b1011111111010100010000000000110000111001010100101011111110011111}, + {0b1010110001110000111001001101111110011110010101111001001011110110, 0b1111111110000111111000011001001001011100011011010111001011001000}, + {0b1010111011011011110001010000010111010011110011011101000001110001, 0b1001100011101010001101111010001011111101111101011110100001011110}, + /*s1 bit 20*/{0b1111010010011011011110001111100110110100110100110100000001111101, 0b1000001010100001100110111100001101100000000111101001101000100100}, + {0b0101100110000110110111011110000100000110000010101101101010001101, 0b1100001001111000001110001111010110111001000111100000000100001011}, + {0b1011000101000111001010000111100110000110000111110100001010111110, 0b0001101001011111010111101000011000010000101101110010000001000101}, + {0b1000100010110101110010001011100000100011011101011110111010111110, 0b0000101111000001011100100101111101011100110111001110001110101101}, + {0b1110110001100100101111001001000110010100010000111111110101111010, 0b1010101011001100101101100100000010101101100000111011000111000000}, + {0b0000000111111010000000110001111000000001011110111111011100000001, 0b1000001011111111010101100001101110110111001111100011001000110001}, + {0b0000000000001010101100111101010011011101111000111011010100100001, 0b0101011110000101101110010001010011100010100000100010000000000001}, + {0b0001101111011101110010001110001111101000000101000011100010011000, 0b0100101101001000100000001111001101110100011100100000100000110001}, + {0b1001111101001011101010001001100110000011011001011111000011010111, 0b1100101000100111000100010110010001110010011001001000000011001001}, + {0b0000001011010011111101111100101110000101000001010011100101000010, 0b0000100111011100000110010011011110000110010101010001011100001001}, + /*s1 bit 30*/{0b1100101001110110010100011011100000100111111000001100000101000011, 0b0011111101011011010110100001101100000010001101110010011010010100}, + {0b0001110101010110011101101011111101100001101100011000111010101000, 0b1111010000111101111000111010001100001100000000000010001111111111}, + {0b1000110110010001101101110011011010010100010010111011001110100011, 0b0111111111001110100110101101010111110110011100111001011100101111}, + {0b0001111011001001001111110011111001100000111001110101111011101011, 0b0100110011011000001111010011111110110101011110011010001110100100}, + {0b1011110010010100110000000100001011001111001101111011000001100101, 0b0011011010001111010011100110001101010100000110110110011010011101}, + {0b1000111110101001100111010111111000001000000011010010111000111001, 0b1101110000010001001110100100111011000011000001101100000001010100}, + {0b1011101101000111111001110000110000111100111010101110111110000011, 0b1100100011111001100101001000001101011011000111010010111010101100}, + {0b0101100000011100000011011000000101011001010100110001000001001111, 0b0111010101011011100000100100000011011111110000011011111101010111}, + {0b0011011010011001111000010010000110010111101001010011011010010010, 0b0110111101001011100010101010110101111100100100010100000000110010}, + {0b1101100011000001010110001001000011010001011100101101110011110000, 0b0010000010111010000100001001101000100110100000110111111010110101}, + /*s1 bit 40*/{0b1100000000110010101011000101011101100000011111000100100110101110, 0b0000000101101001000010111001100000010101100110111101110010011110}, + {0b0100101000001111000011000110011101010110110111001010101000110010, 0b0011011010111111100000100010110001011101001000010011010100100101}, + {0b1100010000110011101100100110000101110100110100111001001000110110, 0b0111010111001001001110001001100101000100011101100001111111011001}, + {0b0001011111011010011010011010100100101100010010110010010101010111, 0b1100111111000000011010011111101000000111001110010011100000110010}, + {0b1110011110101001011111011101110011010000101010110111010111110111, 0b1110101100000011001011001101111100000101100101001000010010000111}, + {0b0111100100011101010101011011001000011110111100010111001110101000, 0b1000010110111010010101000111101111100100001000011011101001110000}, + {0b1010110011101111110111110110110000000111010001101100111001100101, 0b1011100011110001101000000011001011100000011111101000000001110001}, + {0b0011101110110001101000000010000100010101010111110100001110111011, 0b1001010110111010110100100000010111110110101000110001000000100010}, + {0b1101000110100111110010010111101000101010111100000011111100001010, 0b0010111010110110011111110001101001110111001000011011011101010010}, + {0b1110111000100000100101010010101101101101000010100100111100010000, 0b0011001110010011011000011110111010010001010100011001000001110111}, + /*s1 bit 50*/{0b1010000011001000011110100110011110001101101011001000110111111001, 0b1111011110100111001010000000001011000000011100101011100011011001}, + {0b1000011111100101100001000101001101100010110000011110101011010110, 0b1111001101100011001010011101111100100011001010111000000101010101}, + {0b0010111101000101010110101101000101110101110011111111001101000011, 0b1010100011010011110111011111111111100110011110110101110001101100}, + {0b0001111111100110011001111011010000111111011011101001100110110001, 0b0011000110011111111001100011111111111001110010011111010010101100}, + {0b0100010011010011100000100111011110110000010110000011110111010001, 0b0001111110100011001001010001100011111000111100010101101110000110}, + {0b0111001011110000011111010000101100001000000011011000010001001101, 0b0111011011100100111011100010001000101001010010011001011010110000}, + {0b0000011000101110010011110110100101010011011110001011110101111101, 0b1000011111111110111100100010001111011001111011010000001110101111}, + {0b1001110100111111011101110011111010011101000100111100100101101100, 0b1000000011011111010000111111000101000101101000100000110010001110}, + {0b1101010010110110110001010010001000010100010000111000111000111111, 0b1010010110110110110101100100111010101010101010010110111001101111}, + {0b1001100010110011000000110001110001010110110111111110001011010110, 0b0110001000010010010110110010110010010000101110101101000010101011}, + /*s1 bit 60*/{0b1001111001100111100101110000100011111101001001001011010100010000, 0b0110001010011111010010110110110101010111111011111000011000010000}, + {0b1111100011111100100100000110000101111000100001111000100111010110, 0b0101010111101100111000111001000111111110010111111101110001100100}, + {0b0000110110100110001011010111011111010011111000001010100101011100, 0b1011100011101010010001000110101001001111010111011100101111010101}, + {0b0011000110100011111010110001011111001011010001110101000010000101, 0b1110000000100101110011001011110001111001110010110111111110000011} +}; + + +Xoroshiro128Plus Xoroshiro128Plus::xoroshiro128plus_from_last_bits(std::pair last_bits){ + uint64_t s0 = 0; + uint64_t s1 = 0; + + for (size_t i = 0; i < 64; i++){ + uint64_t first_half = last_bits_reverse_matrix[i][0] & last_bits.first; + uint64_t second_half = last_bits_reverse_matrix[i][1] & last_bits.second; + + uint64_t x = first_half ^ second_half; + x ^= x >> 32; + x ^= x >> 16; + x ^= x >> 8; + x ^= x >> 4; + x ^= x >> 2; + x ^= x >> 1; + x &= 1; + + s0 += x << (63 - i); + } + for (size_t i = 0; i < 64; i++){ + uint64_t first_half = last_bits_reverse_matrix[i + 64][0] & last_bits.first; + uint64_t second_half = last_bits_reverse_matrix[i + 64][1] & last_bits.second; + + uint64_t x = first_half ^ second_half; + x ^= x >> 32; + x ^= x >> 16; + x ^= x >> 8; + x ^= x >> 4; + x ^= x >> 2; + x ^= x >> 1; + x &= 1; + + s1 += x << (63 - i); + } + Xoroshiro128PlusState state(s0, s1); + return Xoroshiro128Plus(state); +} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.h b/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.h index c7b1116d4d..b9cf12e794 100644 --- a/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.h +++ b/SerialPrograms/Source/Pokemon/Pokemon_Xoroshiro128Plus.h @@ -1,52 +1,52 @@ -/* Xoroshiro128+ and reverse - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Xoroshiro128Plus_H -#define PokemonAutomation_PokemonSwSh_Xoroshiro128Plus_H - -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - -struct Xoroshiro128PlusState{ - Xoroshiro128PlusState(uint64_t s0, uint64_t s1); - uint64_t s0; - uint64_t s1; -}; - -class Xoroshiro128Plus{ -public: - Xoroshiro128PlusState state; - - Xoroshiro128Plus(Xoroshiro128PlusState state); - Xoroshiro128Plus(uint64_t s0, uint64_t s1); - uint64_t next(); - uint64_t nextInt(uint64_t); - Xoroshiro128PlusState get_state(); - std::vector generate_last_bit_sequence(size_t max_advances); - - // Calculates how many advances are required to reach the given state. - // The given state must be reachable within max_advances advances. - // Returns a pair: - // first: true if the state is reachable within max_advances, false otherwise - // second: the number of advances required (if first is true) - std::pair advances_to_state(Xoroshiro128PlusState other_state, uint64_t max_advances = 100000); - - static Xoroshiro128Plus xoroshiro128plus_from_last_bits(std::pair last_bits); - - -private: - static uint64_t last_bits_reverse_matrix[128][2]; - - uint64_t rotl(const uint64_t x, int k); -}; - -} -} -#endif +/* Xoroshiro128+ and reverse + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Xoroshiro128Plus_H +#define PokemonAutomation_PokemonSwSh_Xoroshiro128Plus_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + +struct Xoroshiro128PlusState{ + Xoroshiro128PlusState(uint64_t s0, uint64_t s1); + uint64_t s0; + uint64_t s1; +}; + +class Xoroshiro128Plus{ +public: + Xoroshiro128PlusState state; + + Xoroshiro128Plus(Xoroshiro128PlusState state); + Xoroshiro128Plus(uint64_t s0, uint64_t s1); + uint64_t next(); + uint64_t nextInt(uint64_t); + Xoroshiro128PlusState get_state(); + std::vector generate_last_bit_sequence(size_t max_advances); + + // Calculates how many advances are required to reach the given state. + // The given state must be reachable within max_advances advances. + // Returns a pair: + // first: true if the state is reachable within max_advances, false otherwise + // second: the number of advances required (if first is true) + std::pair advances_to_state(Xoroshiro128PlusState other_state, uint64_t max_advances = 100000); + + static Xoroshiro128Plus xoroshiro128plus_from_last_bits(std::pair last_bits); + + +private: + static uint64_t last_bits_reverse_matrix[128][2]; + + uint64_t rotl(const uint64_t x, int k); +}; + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.cpp index fd4c24155b..e70676690b 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.cpp @@ -1,110 +1,110 @@ -/* Pokemon Pokeball Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon_BerryNames.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -struct BerryNameDatabase{ - BerryNameDatabase(); - - static const BerryNameDatabase& instance(){ - static BerryNameDatabase database; - return database; - } - - static const std::string NULL_SLUG; - std::vector ordered_list; - std::map database; - std::map reverse_lookup; -}; -const std::string BerryNameDatabase::NULL_SLUG; - -// Currently only include berries used in BDSP. -BerryNameDatabase::BerryNameDatabase() -{ - // Load a list of berry slugs in the desired order: - // ["cheri-berry", "chesto-berry", ... ] - std::string path_slugs = RESOURCE_PATH() + "Pokemon/ItemListBerries.json"; - JsonValue json_slugs = load_json_file(path_slugs); - JsonArray& slugs = json_slugs.to_array_throw(path_slugs); - - // Load a map of berry slugs to berry names in all languages, e.g.: - // { - // "cheri-berry": { - // "eng": "Cheri Berry", - // "fra": "Baie Ceriz", - // ... - // }, - // .... - // } - std::string path_disp = RESOURCE_PATH() + "Pokemon/ItemNameDisplay.json"; - JsonValue json_disp = load_json_file(path_disp); - JsonObject& item_disp = json_disp.to_object_throw(path_disp); - - for (auto& item : slugs){ - std::string& slug = item.to_string_throw(path_slugs); - - JsonObject& berry_name_dict = item_disp.get_object_throw(slug, path_disp); - std::string& display_name = berry_name_dict.get_string_throw("eng", path_disp); - - ordered_list.push_back(slug); - database[std::move(slug)].m_display_name = std::move(display_name); - - // std::cout << "Berry: " << slug_str << " -> " << display_name.toStdString() << std::endl; - } - - for (const auto& item : database){ - reverse_lookup[item.second.m_display_name] = item.first; - } -} - -const BerryNames& get_berry_name(const std::string& slug){ - const std::map& database = BerryNameDatabase::instance().database; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Berry slug not found in database: " + slug - ); - } - return iter->second; -} -const std::string& parse_berry_name(const std::string& display_name){ - const std::map& database = BerryNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Berry name not found in database: " + display_name - ); - } - return iter->second; -} -const std::string& parse_berry_name_nothrow(const std::string& display_name){ - const std::map& database = BerryNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - return BerryNameDatabase::NULL_SLUG; - } - return iter->second; -} - - -const std::vector& BERRY_SLUGS(){ - return BerryNameDatabase::instance().ordered_list; -} - - -} -} +/* Pokemon Pokeball Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon_BerryNames.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct BerryNameDatabase{ + BerryNameDatabase(); + + static const BerryNameDatabase& instance(){ + static BerryNameDatabase database; + return database; + } + + static const std::string NULL_SLUG; + std::vector ordered_list; + std::map database; + std::map reverse_lookup; +}; +const std::string BerryNameDatabase::NULL_SLUG; + +// Currently only include berries used in BDSP. +BerryNameDatabase::BerryNameDatabase() +{ + // Load a list of berry slugs in the desired order: + // ["cheri-berry", "chesto-berry", ... ] + std::string path_slugs = RESOURCE_PATH() + "Pokemon/ItemListBerries.json"; + JsonValue json_slugs = load_json_file(path_slugs); + JsonArray& slugs = json_slugs.to_array_throw(path_slugs); + + // Load a map of berry slugs to berry names in all languages, e.g.: + // { + // "cheri-berry": { + // "eng": "Cheri Berry", + // "fra": "Baie Ceriz", + // ... + // }, + // .... + // } + std::string path_disp = RESOURCE_PATH() + "Pokemon/ItemNameDisplay.json"; + JsonValue json_disp = load_json_file(path_disp); + JsonObject& item_disp = json_disp.to_object_throw(path_disp); + + for (auto& item : slugs){ + std::string& slug = item.to_string_throw(path_slugs); + + JsonObject& berry_name_dict = item_disp.get_object_throw(slug, path_disp); + std::string& display_name = berry_name_dict.get_string_throw("eng", path_disp); + + ordered_list.push_back(slug); + database[std::move(slug)].m_display_name = std::move(display_name); + + // std::cout << "Berry: " << slug_str << " -> " << display_name.toStdString() << std::endl; + } + + for (const auto& item : database){ + reverse_lookup[item.second.m_display_name] = item.first; + } +} + +const BerryNames& get_berry_name(const std::string& slug){ + const std::map& database = BerryNameDatabase::instance().database; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Berry slug not found in database: " + slug + ); + } + return iter->second; +} +const std::string& parse_berry_name(const std::string& display_name){ + const std::map& database = BerryNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Berry name not found in database: " + display_name + ); + } + return iter->second; +} +const std::string& parse_berry_name_nothrow(const std::string& display_name){ + const std::map& database = BerryNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + return BerryNameDatabase::NULL_SLUG; + } + return iter->second; +} + + +const std::vector& BERRY_SLUGS(){ + return BerryNameDatabase::instance().ordered_list; +} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.h index f909ed762d..df9351567d 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerryNames.h @@ -1,37 +1,37 @@ -/* Pokemon Berry Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_BerryNames_H -#define PokemonAutomation_Pokemon_BerryNames_H - -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class BerryNames{ -public: - const std::string& display_name() const{ return m_display_name; } - -private: - friend struct BerryNameDatabase; - - std::string m_display_name; -}; - - -const BerryNames& get_berry_name(const std::string& slug); -const std::string& parse_berry_name(const std::string& display_name); -const std::string& parse_berry_name_nothrow(const std::string& display_name); - -const std::vector& BERRY_SLUGS(); - - -} -} -#endif +/* Pokemon Berry Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_BerryNames_H +#define PokemonAutomation_Pokemon_BerryNames_H + +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class BerryNames{ +public: + const std::string& display_name() const{ return m_display_name; } + +private: + friend struct BerryNameDatabase; + + std::string m_display_name; +}; + + +const BerryNames& get_berry_name(const std::string& slug); +const std::string& parse_berry_name(const std::string& display_name); +const std::string& parse_berry_name_nothrow(const std::string& display_name); + +const std::vector& BERRY_SLUGS(); + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.cpp index 2a78cc5fde..6dfd21b49a 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.cpp @@ -1,23 +1,23 @@ -/* Pokemon Berry Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_BerrySprites.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -const SpriteDatabase& ALL_BERRY_SPRITES(){ - static const SpriteDatabase database("Pokemon/BerrySprites.png", "Pokemon/BerrySprites.json"); - return database; -} - - - - -} -} +/* Pokemon Berry Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_BerrySprites.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +const SpriteDatabase& ALL_BERRY_SPRITES(){ + static const SpriteDatabase database("Pokemon/BerrySprites.png", "Pokemon/BerrySprites.json"); + return database; +} + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.h index d900a5ccae..3136de9864 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_BerrySprites.h @@ -1,23 +1,23 @@ -/* Pokemon Berry Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_BerrySprites_H -#define PokemonAutomation_Pokemon_BerrySprites_H - -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const SpriteDatabase& ALL_BERRY_SPRITES(); - - - - -} -} -#endif +/* Pokemon Berry Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_BerrySprites_H +#define PokemonAutomation_Pokemon_BerrySprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const SpriteDatabase& ALL_BERRY_SPRITES(); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.cpp index cd56149e49..68427be04a 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.cpp @@ -1,84 +1,84 @@ -/* Egg Steps - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonTools/Resources/SpriteDatabase.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon_EggSteps.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -EggStepDatabase::EggStepDatabase(const char* resource_path, const SpriteDatabase* sprites){ - std::string path_slugs = RESOURCE_PATH() + resource_path; - JsonValue json_slugs = load_json_file(path_slugs); - JsonObject& slugs = json_slugs.to_object_throw(path_slugs); - - const std::map& SLUGS_TO_NATIONAL_DEX = Pokemon::SLUGS_TO_NATIONAL_DEX(); - - std::map> nat_id_to_steps; - for (const auto& slug : slugs){ - auto iter = SLUGS_TO_NATIONAL_DEX.find(slug.first); - if (iter == SLUGS_TO_NATIONAL_DEX.end()){ - global_logger_tagged().log("Unknown " + Pokemon::STRING_POKEMON + "slug: " + slug.first); - continue; - } - - auto ret = nat_id_to_steps.emplace( - std::piecewise_construct, - std::forward_as_tuple(iter->second), - std::forward_as_tuple(iter->first, (uint16_t)slug.second.to_integer_throw(path_slugs)) - ); - if (!ret.second){ - global_logger_tagged().log("Duplicate " + Pokemon::STRING_POKEMON + " nat-dex ID: " + std::to_string(iter->second)); - } - - m_slug_to_steps[slug.first] = (uint16_t)slug.second.to_integer_throw(path_slugs); - } - - for (const auto& item : nat_id_to_steps){ - const std::string& slug = item.second.first; - std::string display_name = Pokemon::get_pokemon_name(slug).display_name(); - display_name += " (" + tostr_u_commas(item.second.second) + " steps)"; - - const SpriteDatabase::Sprite* sprite = sprites == nullptr - ? nullptr - : sprites->get_nothrow(slug); - - if (sprite == nullptr){ - m_stringselect_database.add_entry(StringSelectEntry(slug, display_name)); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - m_stringselect_database.add_entry(StringSelectEntry(slug, display_name, sprite->icon)); - } - } -} - - -size_t EggStepDatabase::step_count(const std::string& slug) const{ - auto iter = m_slug_to_steps.find(slug); - if (iter == m_slug_to_steps.end()){ - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - std::string("Invalid ") + Pokemon::STRING_POKEMON + " slug: " + slug - ); - } - return iter->second; -} - - - -} -} +/* Egg Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonTools/Resources/SpriteDatabase.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon_EggSteps.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +EggStepDatabase::EggStepDatabase(const char* resource_path, const SpriteDatabase* sprites){ + std::string path_slugs = RESOURCE_PATH() + resource_path; + JsonValue json_slugs = load_json_file(path_slugs); + JsonObject& slugs = json_slugs.to_object_throw(path_slugs); + + const std::map& SLUGS_TO_NATIONAL_DEX = Pokemon::SLUGS_TO_NATIONAL_DEX(); + + std::map> nat_id_to_steps; + for (const auto& slug : slugs){ + auto iter = SLUGS_TO_NATIONAL_DEX.find(slug.first); + if (iter == SLUGS_TO_NATIONAL_DEX.end()){ + global_logger_tagged().log("Unknown " + Pokemon::STRING_POKEMON + "slug: " + slug.first); + continue; + } + + auto ret = nat_id_to_steps.emplace( + std::piecewise_construct, + std::forward_as_tuple(iter->second), + std::forward_as_tuple(iter->first, (uint16_t)slug.second.to_integer_throw(path_slugs)) + ); + if (!ret.second){ + global_logger_tagged().log("Duplicate " + Pokemon::STRING_POKEMON + " nat-dex ID: " + std::to_string(iter->second)); + } + + m_slug_to_steps[slug.first] = (uint16_t)slug.second.to_integer_throw(path_slugs); + } + + for (const auto& item : nat_id_to_steps){ + const std::string& slug = item.second.first; + std::string display_name = Pokemon::get_pokemon_name(slug).display_name(); + display_name += " (" + tostr_u_commas(item.second.second) + " steps)"; + + const SpriteDatabase::Sprite* sprite = sprites == nullptr + ? nullptr + : sprites->get_nothrow(slug); + + if (sprite == nullptr){ + m_stringselect_database.add_entry(StringSelectEntry(slug, display_name)); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + m_stringselect_database.add_entry(StringSelectEntry(slug, display_name, sprite->icon)); + } + } +} + + +size_t EggStepDatabase::step_count(const std::string& slug) const{ + auto iter = m_slug_to_steps.find(slug); + if (iter == m_slug_to_steps.end()){ + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + std::string("Invalid ") + Pokemon::STRING_POKEMON + " slug: " + slug + ); + } + return iter->second; +} + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.h index 59aff44869..997202b05d 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_EggSteps.h @@ -1,39 +1,39 @@ -/* Egg Steps - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_EggSteps_H -#define PokemonAutomation_Pokemon_EggSteps_H - -#include -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ - -class SpriteDatabase; - -namespace Pokemon{ - - -class EggStepDatabase{ -public: - EggStepDatabase(const char* resource_path, const SpriteDatabase* sprites); - - size_t step_count(const std::string& slug) const; - const StringSelectDatabase& database() const{ - return m_stringselect_database; - } - -private: - std::map m_slug_to_steps; - StringSelectDatabase m_stringselect_database; -}; - - - - -} -} -#endif +/* Egg Steps + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_EggSteps_H +#define PokemonAutomation_Pokemon_EggSteps_H + +#include +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ + +class SpriteDatabase; + +namespace Pokemon{ + + +class EggStepDatabase{ +public: + EggStepDatabase(const char* resource_path, const SpriteDatabase* sprites); + + size_t step_count(const std::string& slug) const; + const StringSelectDatabase& database() const{ + return m_stringselect_database; + } + +private: + std::map m_slug_to_steps; + StringSelectDatabase m_stringselect_database; +}; + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp index 8b4b278f9f..eaf5564f25 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.cpp @@ -1,85 +1,85 @@ -/* Pokemon Pokeball Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon_PokeballNames.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -struct PokeballNameDatabase{ - PokeballNameDatabase(); - - static const PokeballNameDatabase& instance(){ - static PokeballNameDatabase database; - return database; - } - - static const std::string NULL_SLUG; - std::vector ordered_list; - std::map database; - std::map reverse_lookup; -}; -const std::string PokeballNameDatabase::NULL_SLUG; - -PokeballNameDatabase::PokeballNameDatabase(){ - std::string path_slugs = RESOURCE_PATH() + "Pokemon/ItemListBalls.json"; - JsonValue json_slugs = load_json_file(path_slugs); - JsonArray& slugs = json_slugs.to_array_throw(path_slugs); - - std::string path_disp = RESOURCE_PATH() + "Pokemon/ItemNameDisplay.json"; - JsonValue json_disp = load_json_file(path_disp); - JsonObject& item_disp = json_disp.to_object_throw(path_disp); - - for (auto& item : slugs){ - std::string& slug = item.to_string_throw(path_slugs); - ordered_list.emplace_back(slug); - - JsonObject& languages = item_disp.get_object_throw(slug, path_disp); - std::string& display_name = languages.get_string_throw("eng", path_disp); - - database[slug].m_display_name = display_name; - reverse_lookup[std::move(display_name)] = std::move(slug); - } -} - -const PokeballNames& get_pokeball_name(const std::string& slug){ - const std::map& database = PokeballNameDatabase::instance().database; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Pokeball slug not found in database: " + slug); - } - return iter->second; -} -const std::string& parse_pokeball_name(const std::string& display_name){ - const std::map& database = PokeballNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Pokeball name not found in database: " + display_name); - } - return iter->second; -} -const std::string& parse_pokeball_name_nothrow(const std::string& display_name){ - const std::map& database = PokeballNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - return PokeballNameDatabase::NULL_SLUG; - } - return iter->second; -} - - -const std::vector& POKEBALL_SLUGS(){ - return PokeballNameDatabase::instance().ordered_list; -} - - -} -} +/* Pokemon Pokeball Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon_PokeballNames.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct PokeballNameDatabase{ + PokeballNameDatabase(); + + static const PokeballNameDatabase& instance(){ + static PokeballNameDatabase database; + return database; + } + + static const std::string NULL_SLUG; + std::vector ordered_list; + std::map database; + std::map reverse_lookup; +}; +const std::string PokeballNameDatabase::NULL_SLUG; + +PokeballNameDatabase::PokeballNameDatabase(){ + std::string path_slugs = RESOURCE_PATH() + "Pokemon/ItemListBalls.json"; + JsonValue json_slugs = load_json_file(path_slugs); + JsonArray& slugs = json_slugs.to_array_throw(path_slugs); + + std::string path_disp = RESOURCE_PATH() + "Pokemon/ItemNameDisplay.json"; + JsonValue json_disp = load_json_file(path_disp); + JsonObject& item_disp = json_disp.to_object_throw(path_disp); + + for (auto& item : slugs){ + std::string& slug = item.to_string_throw(path_slugs); + ordered_list.emplace_back(slug); + + JsonObject& languages = item_disp.get_object_throw(slug, path_disp); + std::string& display_name = languages.get_string_throw("eng", path_disp); + + database[slug].m_display_name = display_name; + reverse_lookup[std::move(display_name)] = std::move(slug); + } +} + +const PokeballNames& get_pokeball_name(const std::string& slug){ + const std::map& database = PokeballNameDatabase::instance().database; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Pokeball slug not found in database: " + slug); + } + return iter->second; +} +const std::string& parse_pokeball_name(const std::string& display_name){ + const std::map& database = PokeballNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Pokeball name not found in database: " + display_name); + } + return iter->second; +} +const std::string& parse_pokeball_name_nothrow(const std::string& display_name){ + const std::map& database = PokeballNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + return PokeballNameDatabase::NULL_SLUG; + } + return iter->second; +} + + +const std::vector& POKEBALL_SLUGS(){ + return PokeballNameDatabase::instance().ordered_list; +} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.h index 1e907feada..5ab1558f9b 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokeballNames.h @@ -1,38 +1,38 @@ -/* Pokemon Pokeball Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokeballNames_H -#define PokemonAutomation_Pokemon_PokeballNames_H - -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class PokeballNames{ -public: - const std::string& display_name() const{ return m_display_name; } - -private: - friend struct PokeballNameDatabase; - - std::string m_display_name; -}; - - -const PokeballNames& get_pokeball_name(const std::string& slug); -const std::string& parse_pokeball_name(const std::string& display_name); -const std::string& parse_pokeball_name_nothrow(const std::string& display_name); - -const std::vector& POKEBALL_SLUGS(); - - -} -} -#endif +/* Pokemon Pokeball Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokeballNames_H +#define PokemonAutomation_Pokemon_PokeballNames_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class PokeballNames{ +public: + const std::string& display_name() const{ return m_display_name; } + +private: + friend struct PokeballNameDatabase; + + std::string m_display_name; +}; + + +const PokeballNames& get_pokeball_name(const std::string& slug); +const std::string& parse_pokeball_name(const std::string& display_name); +const std::string& parse_pokeball_name_nothrow(const std::string& display_name); + +const std::vector& POKEBALL_SLUGS(); + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.cpp index 21522393f3..8e0ed4feff 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.cpp @@ -1,137 +1,137 @@ -/* Pokemon Forms - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/Globals.h" -#include "Pokemon_PokemonNames.h" -#include "Pokemon_PokemonForms.h" -#include "Pokemon_PokemonSlugs.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -struct PokemonFormDatabase{ - PokemonFormDatabase(); - static const PokemonFormDatabase& instance(){ - static PokemonFormDatabase database; - return database; - } - - std::map m_slug_to_form; - std::vector m_slugs; -}; - -bool is_form_shiny(const std::string& form_slug){ - const std::string& suffix = "-shiny"; - if (form_slug.length() < suffix.length()) { - return false; - } - return form_slug.compare(form_slug.length() - suffix.length(), suffix.length(), suffix) == 0; -} - -bool PokemonForm::is_shiny() const { - return is_form_shiny(m_slug); -} - -PokemonFormDatabase::PokemonFormDatabase(){ - // Load form map JSON - const std::string form_display_map_path = RESOURCE_PATH() + "Pokemon/AllFormDisplayMap.json"; - JsonValue json = load_json_file(form_display_map_path); - // a map from form slug to list of tuples, where each tuple contains a form slug and a display name - JsonObject& form_displays = json.to_object_throw(form_display_map_path); - - const std::string no_shiny_pokemon_path = RESOURCE_PATH() + "Pokemon/SpecialPokemonWithNoShinyForm.txt"; - std::ifstream fin(no_shiny_pokemon_path); - if (!fin.is_open()) { - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "canot open resource file: " + no_shiny_pokemon_path); - } - std::string line; - std::set no_shiny_forms; - while (std::getline(fin, line)) { - fin >> std::ws; - no_shiny_forms.emplace(std::move(line)); - } - - for(const auto& species_slug: NATIONAL_DEX_SLUGS()){ - const std::string& species_display_name = get_pokemon_name(species_slug).display_name(); - const JsonArray* form_array = form_displays.get_array(species_slug); - if (form_array == nullptr){ - // there is a single form for this species - m_slug_to_form.emplace(species_slug, PokemonForm(species_slug, species_display_name, species_slug)); - std::string shiny_slug = species_slug + "-shiny"; - m_slug_to_form.emplace(shiny_slug, PokemonForm(shiny_slug, "Shiny " + species_display_name, species_slug)); - m_slugs.push_back(species_slug); - m_slugs.emplace_back(std::move(shiny_slug)); - continue; - } - - bool has_shiny_form = false; - std::vector::const_iterator> forms; - for (const auto& form : *form_array){ - // form is a list of two elements, first the form slug name, second the display name - const JsonArray* form_ptr = form.to_array(); - if (form_ptr == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No [form_slug, display_name] format in form display map: " + species_slug); - } - const JsonArray& form_slug_and_display = *form_ptr; - if (form_slug_and_display.size() != 2){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Wrong [form_slug, display_name] length in form display map: " + species_slug); - } - const std::string& form_slug = form_slug_and_display[0].to_string_throw(); - const std::string& display_name = form_slug_and_display[1].to_string_throw(); - if (form_slug.empty() || display_name.empty()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Empty string in [form_slug, display_name] in form display map: " + species_slug); - } - if (is_form_shiny(form_slug)){ - has_shiny_form = true; - } - const auto it = m_slug_to_form.emplace(form_slug, PokemonForm(form_slug, display_name, species_slug)).first; - m_slugs.push_back(form_slug); - forms.push_back(it); - } - if (!has_shiny_form){ // if no explict shiny form loaded, we build it our own - for (const auto& it: forms){ - const auto& form = it->second; - if (no_shiny_forms.find(form.m_slug) != no_shiny_forms.end()){ - continue; // this form has no shiny - } - std::string shiny_slug = form.m_slug + "-shiny"; - m_slug_to_form.emplace(shiny_slug, PokemonForm( - shiny_slug, "Shiny " + form.m_display_name, form.m_species - )); - m_slugs.emplace_back(std::move(shiny_slug)); - } - } - } - std::cout << "Loaded " << m_slug_to_form.size() << " form slugs" << std::endl; -} - -const PokemonForm* get_pokemon_form(const std::string& slug){ - const auto& slug_to_form = PokemonFormDatabase::instance().m_slug_to_form; - const auto it = slug_to_form.find(slug); - if (it == slug_to_form.end()){ - return nullptr; - } - return &it->second; -} - -const std::vector& ALL_POKEMON_FORMS(){ - return PokemonFormDatabase::instance().m_slugs; -} - - -} +/* Pokemon Forms + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/Globals.h" +#include "Pokemon_PokemonNames.h" +#include "Pokemon_PokemonForms.h" +#include "Pokemon_PokemonSlugs.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +struct PokemonFormDatabase{ + PokemonFormDatabase(); + static const PokemonFormDatabase& instance(){ + static PokemonFormDatabase database; + return database; + } + + std::map m_slug_to_form; + std::vector m_slugs; +}; + +bool is_form_shiny(const std::string& form_slug){ + const std::string& suffix = "-shiny"; + if (form_slug.length() < suffix.length()) { + return false; + } + return form_slug.compare(form_slug.length() - suffix.length(), suffix.length(), suffix) == 0; +} + +bool PokemonForm::is_shiny() const { + return is_form_shiny(m_slug); +} + +PokemonFormDatabase::PokemonFormDatabase(){ + // Load form map JSON + const std::string form_display_map_path = RESOURCE_PATH() + "Pokemon/AllFormDisplayMap.json"; + JsonValue json = load_json_file(form_display_map_path); + // a map from form slug to list of tuples, where each tuple contains a form slug and a display name + JsonObject& form_displays = json.to_object_throw(form_display_map_path); + + const std::string no_shiny_pokemon_path = RESOURCE_PATH() + "Pokemon/SpecialPokemonWithNoShinyForm.txt"; + std::ifstream fin(no_shiny_pokemon_path); + if (!fin.is_open()) { + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "canot open resource file: " + no_shiny_pokemon_path); + } + std::string line; + std::set no_shiny_forms; + while (std::getline(fin, line)) { + fin >> std::ws; + no_shiny_forms.emplace(std::move(line)); + } + + for(const auto& species_slug: NATIONAL_DEX_SLUGS()){ + const std::string& species_display_name = get_pokemon_name(species_slug).display_name(); + const JsonArray* form_array = form_displays.get_array(species_slug); + if (form_array == nullptr){ + // there is a single form for this species + m_slug_to_form.emplace(species_slug, PokemonForm(species_slug, species_display_name, species_slug)); + std::string shiny_slug = species_slug + "-shiny"; + m_slug_to_form.emplace(shiny_slug, PokemonForm(shiny_slug, "Shiny " + species_display_name, species_slug)); + m_slugs.push_back(species_slug); + m_slugs.emplace_back(std::move(shiny_slug)); + continue; + } + + bool has_shiny_form = false; + std::vector::const_iterator> forms; + for (const auto& form : *form_array){ + // form is a list of two elements, first the form slug name, second the display name + const JsonArray* form_ptr = form.to_array(); + if (form_ptr == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No [form_slug, display_name] format in form display map: " + species_slug); + } + const JsonArray& form_slug_and_display = *form_ptr; + if (form_slug_and_display.size() != 2){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Wrong [form_slug, display_name] length in form display map: " + species_slug); + } + const std::string& form_slug = form_slug_and_display[0].to_string_throw(); + const std::string& display_name = form_slug_and_display[1].to_string_throw(); + if (form_slug.empty() || display_name.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Empty string in [form_slug, display_name] in form display map: " + species_slug); + } + if (is_form_shiny(form_slug)){ + has_shiny_form = true; + } + const auto it = m_slug_to_form.emplace(form_slug, PokemonForm(form_slug, display_name, species_slug)).first; + m_slugs.push_back(form_slug); + forms.push_back(it); + } + if (!has_shiny_form){ // if no explict shiny form loaded, we build it our own + for (const auto& it: forms){ + const auto& form = it->second; + if (no_shiny_forms.find(form.m_slug) != no_shiny_forms.end()){ + continue; // this form has no shiny + } + std::string shiny_slug = form.m_slug + "-shiny"; + m_slug_to_form.emplace(shiny_slug, PokemonForm( + shiny_slug, "Shiny " + form.m_display_name, form.m_species + )); + m_slugs.emplace_back(std::move(shiny_slug)); + } + } + } + std::cout << "Loaded " << m_slug_to_form.size() << " form slugs" << std::endl; +} + +const PokemonForm* get_pokemon_form(const std::string& slug){ + const auto& slug_to_form = PokemonFormDatabase::instance().m_slug_to_form; + const auto it = slug_to_form.find(slug); + if (it == slug_to_form.end()){ + return nullptr; + } + return &it->second; +} + +const std::vector& ALL_POKEMON_FORMS(){ + return PokemonFormDatabase::instance().m_slugs; +} + + +} } \ No newline at end of file diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.h index 7a632d95f5..d2b8c62dca 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonForms.h @@ -1,51 +1,51 @@ -/* Pokemon Forms - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonForms_H -#define PokemonAutomation_Pokemon_PokemonForms_H - -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// slug and display names related to a pokemon form -class PokemonForm{ -public: - const std::string& slug() const{ return m_slug; } - const std::string& display_name() const{ return m_display_name; } - bool is_shiny() const; - // slug of the base species - const std::string& species() const { return m_species; } - // const PokemonForm& shiny_form() const; - // const PokemonForm& non_shiny_form() const; - -private: - PokemonForm(std::string slug, std::string display_name, std::string species) - : m_slug(std::move(slug)), m_display_name(std::move(display_name)), m_species(std::move(species)) {} - friend struct PokemonFormDatabase; - - std::string m_slug; - std::string m_display_name; - std::string m_species; -}; - - -// Given a slug, find the form related data -// You can find all form slugs with unique appearance from the map keys of: -// Pokemon_PokemonHomeSprites.h:ALL_POKEMON_HOME_SPRITES().get() -// If no such slug is found, return nullptr -const PokemonForm* get_pokemon_form(const std::string& form_slug); - -// Get a vector of form slugs. Each slug is a form with unique appearance -// that has a unique sprite loaded in Pokemon_PokemonHomeSprites.h:ALL_POKEMON_HOME_SPRITES() -const std::vector& ALL_POKEMON_FORMS(); - -} -} -#endif +/* Pokemon Forms + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonForms_H +#define PokemonAutomation_Pokemon_PokemonForms_H + +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// slug and display names related to a pokemon form +class PokemonForm{ +public: + const std::string& slug() const{ return m_slug; } + const std::string& display_name() const{ return m_display_name; } + bool is_shiny() const; + // slug of the base species + const std::string& species() const { return m_species; } + // const PokemonForm& shiny_form() const; + // const PokemonForm& non_shiny_form() const; + +private: + PokemonForm(std::string slug, std::string display_name, std::string species) + : m_slug(std::move(slug)), m_display_name(std::move(display_name)), m_species(std::move(species)) {} + friend struct PokemonFormDatabase; + + std::string m_slug; + std::string m_display_name; + std::string m_species; +}; + + +// Given a slug, find the form related data +// You can find all form slugs with unique appearance from the map keys of: +// Pokemon_PokemonHomeSprites.h:ALL_POKEMON_HOME_SPRITES().get() +// If no such slug is found, return nullptr +const PokemonForm* get_pokemon_form(const std::string& form_slug); + +// Get a vector of form slugs. Each slug is a form with unique appearance +// that has a unique sprite loaded in Pokemon_PokemonHomeSprites.h:ALL_POKEMON_HOME_SPRITES() +const std::vector& ALL_POKEMON_FORMS(); + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.cpp index d07f7a2b3b..8f60d6b529 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.cpp @@ -1,23 +1,23 @@ -/* Pokemon Home Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon_PokemonHomeSprites.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -const SpriteDatabase& ALL_POKEMON_HOME_SPRITES(){ - static const SpriteDatabase database("Pokemon/AllHomeSprites.png", "Pokemon/AllHomeSprites.json"); - return database; -} - - - - -} -} +/* Pokemon Home Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon_PokemonHomeSprites.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +const SpriteDatabase& ALL_POKEMON_HOME_SPRITES(){ + static const SpriteDatabase database("Pokemon/AllHomeSprites.png", "Pokemon/AllHomeSprites.json"); + return database; +} + + + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.h index 0dcb4871ba..a84702e200 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonHomeSprites.h @@ -1,24 +1,24 @@ -/* Pokemon Home Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonHomeSprites_H -#define PokemonAutomation_Pokemon_PokemonHomeSprites_H - -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -// All pokemon form sprites (including shiny and non-shiny) from Pokemon Home -const SpriteDatabase& ALL_POKEMON_HOME_SPRITES(); - - - - -} -} -#endif +/* Pokemon Home Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonHomeSprites_H +#define PokemonAutomation_Pokemon_PokemonHomeSprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +// All pokemon form sprites (including shiny and non-shiny) from Pokemon Home +const SpriteDatabase& ALL_POKEMON_HOME_SPRITES(); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.cpp index 8b5e29cc5e..b5eb26459f 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.cpp @@ -1,127 +1,127 @@ -/* Pokemon Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon_PokemonNames.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const std::string PokemonNames::NULL_SLUG; - - -struct PokemonNameDatabase{ - PokemonNameDatabase(); - static const PokemonNameDatabase& instance(){ - static PokemonNameDatabase database; - return database; - } - - std::map m_slug_to_data; - std::map m_display_name_to_slug; -}; - - -PokemonNameDatabase::PokemonNameDatabase(){ - std::string path = RESOURCE_PATH() + "Pokemon/PokemonNameDisplay.json"; - JsonValue json = load_json_file(path); - JsonObject& displays = json.to_object_throw(path); - - for (auto& item0 : displays){ - const std::string& slug = item0.first; - - JsonObject& names = item0.second.to_object_throw(path); - PokemonNames data; - for (auto& item1 : names){ - std::string& name = item1.second.to_string_throw(path); - data.m_display_names[language_code_to_enum(item1.first)] = std::move(name); - } - - // Display name for English. - auto iter2 = data.m_display_names.find(Language::English); - if (iter2 == data.m_display_names.end()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Missing English translation: " + slug, - std::move(path) - ); - } - data.m_display_name = iter2->second; - - m_display_name_to_slug.emplace(data.m_display_name, slug); - m_slug_to_data.emplace(slug, std::move(data)); - } -} - - -const std::string& PokemonNames::display_name(Language language) const{ - auto iter = m_display_names.find(language); - if (iter == m_display_names.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No data loaded for this language."); - } - return iter->second; -} - - -const PokemonNames& get_pokemon_name(const std::string& slug){ - const std::map& database = PokemonNameDatabase::instance().m_slug_to_data; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Pokemon slug not found in database: " + slug); - } - return iter->second; -} -const PokemonNames* get_pokemon_name_nothrow(const std::string& slug){ - const std::map& database = PokemonNameDatabase::instance().m_slug_to_data; - auto iter = database.find(slug); - if (iter == database.end()){ - return nullptr; - } - return &iter->second; -} -const std::string& parse_pokemon_name(const std::string& display_name){ - const std::map& database = PokemonNameDatabase::instance().m_display_name_to_slug; - auto iter = database.find(display_name); - if (iter == database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Display name not found in database: " + display_name); - } - return iter->second; -} -const std::string& parse_pokemon_name_nothrow(const std::string& display_name){ - const std::map& database = PokemonNameDatabase::instance().m_display_name_to_slug; - auto iter = database.find(display_name); - if (iter == database.end()){ - return PokemonNames::NULL_SLUG; - } - return iter->second; -} - -std::vector load_pokemon_slug_json_list(const char* json_path){ - std::string path = RESOURCE_PATH() + json_path; - JsonValue json = load_json_file(path); - JsonArray& array = json.to_array_throw(); - - std::vector list; - for (auto& item : array){ - std::string& slug = item.to_string_throw(); - if (slug.empty()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Expected non-empty string for Pokemon slug.", - std::move(path) - ); - } - list.emplace_back(std::move(slug)); - } - return list; -} - -} -} +/* Pokemon Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon_PokemonNames.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const std::string PokemonNames::NULL_SLUG; + + +struct PokemonNameDatabase{ + PokemonNameDatabase(); + static const PokemonNameDatabase& instance(){ + static PokemonNameDatabase database; + return database; + } + + std::map m_slug_to_data; + std::map m_display_name_to_slug; +}; + + +PokemonNameDatabase::PokemonNameDatabase(){ + std::string path = RESOURCE_PATH() + "Pokemon/PokemonNameDisplay.json"; + JsonValue json = load_json_file(path); + JsonObject& displays = json.to_object_throw(path); + + for (auto& item0 : displays){ + const std::string& slug = item0.first; + + JsonObject& names = item0.second.to_object_throw(path); + PokemonNames data; + for (auto& item1 : names){ + std::string& name = item1.second.to_string_throw(path); + data.m_display_names[language_code_to_enum(item1.first)] = std::move(name); + } + + // Display name for English. + auto iter2 = data.m_display_names.find(Language::English); + if (iter2 == data.m_display_names.end()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Missing English translation: " + slug, + std::move(path) + ); + } + data.m_display_name = iter2->second; + + m_display_name_to_slug.emplace(data.m_display_name, slug); + m_slug_to_data.emplace(slug, std::move(data)); + } +} + + +const std::string& PokemonNames::display_name(Language language) const{ + auto iter = m_display_names.find(language); + if (iter == m_display_names.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No data loaded for this language."); + } + return iter->second; +} + + +const PokemonNames& get_pokemon_name(const std::string& slug){ + const std::map& database = PokemonNameDatabase::instance().m_slug_to_data; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Pokemon slug not found in database: " + slug); + } + return iter->second; +} +const PokemonNames* get_pokemon_name_nothrow(const std::string& slug){ + const std::map& database = PokemonNameDatabase::instance().m_slug_to_data; + auto iter = database.find(slug); + if (iter == database.end()){ + return nullptr; + } + return &iter->second; +} +const std::string& parse_pokemon_name(const std::string& display_name){ + const std::map& database = PokemonNameDatabase::instance().m_display_name_to_slug; + auto iter = database.find(display_name); + if (iter == database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Display name not found in database: " + display_name); + } + return iter->second; +} +const std::string& parse_pokemon_name_nothrow(const std::string& display_name){ + const std::map& database = PokemonNameDatabase::instance().m_display_name_to_slug; + auto iter = database.find(display_name); + if (iter == database.end()){ + return PokemonNames::NULL_SLUG; + } + return iter->second; +} + +std::vector load_pokemon_slug_json_list(const char* json_path){ + std::string path = RESOURCE_PATH() + json_path; + JsonValue json = load_json_file(path); + JsonArray& array = json.to_array_throw(); + + std::vector list; + for (auto& item : array){ + std::string& slug = item.to_string_throw(); + if (slug.empty()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Expected non-empty string for Pokemon slug.", + std::move(path) + ); + } + list.emplace_back(std::move(slug)); + } + return list; +} + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.h index 6ca5cd3aa8..a869acbf58 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonNames.h @@ -1,49 +1,49 @@ -/* Pokemon Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonNames_H -#define PokemonAutomation_Pokemon_PokemonNames_H - -#include -#include -#include -#include "CommonFramework/Language.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - -class PokemonNames{ -public: - const std::string& display_name() const{ return m_display_name; } - const std::string& display_name(Language language) const; - -public: - const static std::string NULL_SLUG; -private: - friend struct PokemonNameDatabase; - - std::string m_display_name; - std::map m_display_names; -}; - - -const PokemonNames& get_pokemon_name(const std::string& slug); -const PokemonNames* get_pokemon_name_nothrow(const std::string& slug); -const std::string& parse_pokemon_name(const std::string& display_name); -const std::string& parse_pokemon_name_nothrow(const std::string& display_name); - - - -// Load a list of pokemon name slugs from a json file. -// json_path: the path relative to the resource root, accessed via -// RESOURCE_PATH() declared in CommonFramework/Globals.h. -std::vector load_pokemon_slug_json_list(const char* json_path); - - -} -} -#endif +/* Pokemon Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonNames_H +#define PokemonAutomation_Pokemon_PokemonNames_H + +#include +#include +#include +#include "CommonFramework/Language.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + +class PokemonNames{ +public: + const std::string& display_name() const{ return m_display_name; } + const std::string& display_name(Language language) const; + +public: + const static std::string NULL_SLUG; +private: + friend struct PokemonNameDatabase; + + std::string m_display_name; + std::map m_display_names; +}; + + +const PokemonNames& get_pokemon_name(const std::string& slug); +const PokemonNames* get_pokemon_name_nothrow(const std::string& slug); +const std::string& parse_pokemon_name(const std::string& display_name); +const std::string& parse_pokemon_name_nothrow(const std::string& display_name); + + + +// Load a list of pokemon name slugs from a json file. +// json_path: the path relative to the resource root, accessed via +// RESOURCE_PATH() declared in CommonFramework/Globals.h. +std::vector load_pokemon_slug_json_list(const char* json_path); + + +} +} +#endif diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp index 91691e69df..e9f4e7a64e 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.cpp @@ -1,53 +1,53 @@ -/* Pokemon Pokemon Slugs - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/Globals.h" -#include "Pokemon_PokemonSlugs.h" - -namespace PokemonAutomation{ -namespace Pokemon{ - - - -struct PokemonSlugDatabase{ - std::set all_slugs; - std::vector national_dex; - std::map slugs_to_dex; - - static PokemonSlugDatabase& instance(){ - static PokemonSlugDatabase data; - return data; - } - PokemonSlugDatabase(){ - std::string path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-National.json"; - JsonValue json = load_json_file(path); - JsonArray& slugs = json.to_array_throw(path); - - for (auto& item : slugs){ - std::string& slug = item.to_string_throw(path); - all_slugs.insert(slug); - national_dex.emplace_back(slug); - slugs_to_dex[std::move(slug)] = national_dex.size(); - } - } -}; - - -const std::set& ALL_POKEMON_SLUGS(){ - return PokemonSlugDatabase::instance().all_slugs; -} -const std::vector& NATIONAL_DEX_SLUGS(){ - return PokemonSlugDatabase::instance().national_dex; -} -const std::map& SLUGS_TO_NATIONAL_DEX(){ - return PokemonSlugDatabase::instance().slugs_to_dex; -} - - -} -} +/* Pokemon Pokemon Slugs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/Globals.h" +#include "Pokemon_PokemonSlugs.h" + +namespace PokemonAutomation{ +namespace Pokemon{ + + + +struct PokemonSlugDatabase{ + std::set all_slugs; + std::vector national_dex; + std::map slugs_to_dex; + + static PokemonSlugDatabase& instance(){ + static PokemonSlugDatabase data; + return data; + } + PokemonSlugDatabase(){ + std::string path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-National.json"; + JsonValue json = load_json_file(path); + JsonArray& slugs = json.to_array_throw(path); + + for (auto& item : slugs){ + std::string& slug = item.to_string_throw(path); + all_slugs.insert(slug); + national_dex.emplace_back(slug); + slugs_to_dex[std::move(slug)] = national_dex.size(); + } + } +}; + + +const std::set& ALL_POKEMON_SLUGS(){ + return PokemonSlugDatabase::instance().all_slugs; +} +const std::vector& NATIONAL_DEX_SLUGS(){ + return PokemonSlugDatabase::instance().national_dex; +} +const std::map& SLUGS_TO_NATIONAL_DEX(){ + return PokemonSlugDatabase::instance().slugs_to_dex; +} + + +} +} diff --git a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.h b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.h index 55709ccd0b..2731c78364 100644 --- a/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.h +++ b/SerialPrograms/Source/Pokemon/Resources/Pokemon_PokemonSlugs.h @@ -1,26 +1,26 @@ -/* Pokemon Pokemon Slugs - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_Pokemon_PokemonSlugs_H -#define PokemonAutomation_Pokemon_PokemonSlugs_H - -#include -#include -#include -#include - -namespace PokemonAutomation{ -namespace Pokemon{ - - -const std::set& ALL_POKEMON_SLUGS(); -const std::vector& NATIONAL_DEX_SLUGS(); -const std::map& SLUGS_TO_NATIONAL_DEX(); - - -} -} -#endif +/* Pokemon Pokemon Slugs + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_Pokemon_PokemonSlugs_H +#define PokemonAutomation_Pokemon_PokemonSlugs_H + +#include +#include +#include +#include + +namespace PokemonAutomation{ +namespace Pokemon{ + + +const std::set& ALL_POKEMON_SLUGS(); +const std::vector& NATIONAL_DEX_SLUGS(); +const std::map& SLUGS_TO_NATIONAL_DEX(); + + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp index 3e1229b7e3..a03388b802 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.cpp @@ -1,121 +1,121 @@ -/* In-Battle Ball Inventory Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h" -#include "PokemonBDSP_BattleBallReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -const double BattleBallReader::MAX_ALPHA = 0.40; -const double BattleBallReader::ALPHA_SPREAD = 0.02; - - -const PokeballSpriteMatcher& BALL_SPRITE_MATCHER(){ - static PokeballSpriteMatcher matcher; - return matcher; -} - - - -BattleBallReader::BattleBallReader(VideoStream& stream, Language language) - : m_matcher(BALL_SPRITE_MATCHER()) - , m_name_reader(PokeballNameReader::instance()) - , m_language(language) - , m_stream(stream) - , m_box_sprite(stream.overlay(), {0.617, 0.650, 0.0335, 0.060}) - , m_box_name(stream.overlay(), {0.650, 0.650, 0.22, 0.060}) - , m_box_quantity(stream.overlay(), {0.880, 0.650, 0.070, 0.060}) -{} - - - -std::string BattleBallReader::read_ball(const ImageViewRGB32& screen) const{ - if (!screen){ - return ""; - } - - ImageMatch::ImageMatchResult sprite_result; - { - ImageViewRGB32 image = extract_box_reference(screen, m_box_sprite); - sprite_result = m_matcher.match(image, ALPHA_SPREAD); - sprite_result.log(m_stream.logger(), 0.50); - if (!sprite_result.results.empty() && sprite_result.results.begin()->first > MAX_ALPHA){ - sprite_result.results.clear(); - } - } -// if (sprite_result.results.empty()){ -// dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Sprite", screen); -// } - - OCR::StringMatchResult name_result; - { - ImageViewRGB32 cropped = extract_box_reference(screen, m_box_name); - name_result = m_name_reader.read_substring( - m_stream.logger(), m_language, cropped, - { - {0xff000000, 0xff404040}, - {0xff000000, 0xff808080}, - } - ); - } -// if (name_result.results.size() != 1){ -// dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Name", screen); -// } - - if (sprite_result.results.empty()){ - if (name_result.results.size() == 1){ - return name_result.results.begin()->second.token; - } - dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-FailedSprite-AmbiguousName", screen); - return ""; - } - - if (sprite_result.results.size() == 1){ - return sprite_result.results.begin()->second; - } - - std::set ocr_slugs; - for (const auto& item : name_result.results){ - ocr_slugs.insert(item.second.token); - } - - std::vector overlap; - for (const auto& item : sprite_result.results){ - auto iter = ocr_slugs.find(item.second); - if (iter != ocr_slugs.end()){ - overlap.emplace_back(item.second); - } - } - if (overlap.size() != 1){ - dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-SpriteNameMismatch", screen); - return ""; - } - return overlap[0]; -} - -uint16_t BattleBallReader::read_quantity(const ImageViewRGB32& screen) const{ - ImageRGB32 image = to_blackwhite_rgb32_range( - extract_box_reference(screen, m_box_quantity), - true, - 0xff808080, 0xffffffff - ); - int qty = OCR::read_number(m_stream.logger(), image); - return (uint16_t)std::max(qty, 0); -} - - - -} -} -} +/* In-Battle Ball Inventory Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h" +#include "PokemonBDSP_BattleBallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +const double BattleBallReader::MAX_ALPHA = 0.40; +const double BattleBallReader::ALPHA_SPREAD = 0.02; + + +const PokeballSpriteMatcher& BALL_SPRITE_MATCHER(){ + static PokeballSpriteMatcher matcher; + return matcher; +} + + + +BattleBallReader::BattleBallReader(VideoStream& stream, Language language) + : m_matcher(BALL_SPRITE_MATCHER()) + , m_name_reader(PokeballNameReader::instance()) + , m_language(language) + , m_stream(stream) + , m_box_sprite(stream.overlay(), {0.617, 0.650, 0.0335, 0.060}) + , m_box_name(stream.overlay(), {0.650, 0.650, 0.22, 0.060}) + , m_box_quantity(stream.overlay(), {0.880, 0.650, 0.070, 0.060}) +{} + + + +std::string BattleBallReader::read_ball(const ImageViewRGB32& screen) const{ + if (!screen){ + return ""; + } + + ImageMatch::ImageMatchResult sprite_result; + { + ImageViewRGB32 image = extract_box_reference(screen, m_box_sprite); + sprite_result = m_matcher.match(image, ALPHA_SPREAD); + sprite_result.log(m_stream.logger(), 0.50); + if (!sprite_result.results.empty() && sprite_result.results.begin()->first > MAX_ALPHA){ + sprite_result.results.clear(); + } + } +// if (sprite_result.results.empty()){ +// dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Sprite", screen); +// } + + OCR::StringMatchResult name_result; + { + ImageViewRGB32 cropped = extract_box_reference(screen, m_box_name); + name_result = m_name_reader.read_substring( + m_stream.logger(), m_language, cropped, + { + {0xff000000, 0xff404040}, + {0xff000000, 0xff808080}, + } + ); + } +// if (name_result.results.size() != 1){ +// dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Name", screen); +// } + + if (sprite_result.results.empty()){ + if (name_result.results.size() == 1){ + return name_result.results.begin()->second.token; + } + dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-FailedSprite-AmbiguousName", screen); + return ""; + } + + if (sprite_result.results.size() == 1){ + return sprite_result.results.begin()->second; + } + + std::set ocr_slugs; + for (const auto& item : name_result.results){ + ocr_slugs.insert(item.second.token); + } + + std::vector overlap; + for (const auto& item : sprite_result.results){ + auto iter = ocr_slugs.find(item.second); + if (iter != ocr_slugs.end()){ + overlap.emplace_back(item.second); + } + } + if (overlap.size() != 1){ + dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-SpriteNameMismatch", screen); + return ""; + } + return overlap[0]; +} + +uint16_t BattleBallReader::read_quantity(const ImageViewRGB32& screen) const{ + ImageRGB32 image = to_blackwhite_rgb32_range( + extract_box_reference(screen, m_box_quantity), + true, + 0xff808080, 0xffffffff + ); + int qty = OCR::read_number(m_stream.logger(), image); + return (uint16_t)std::max(qty, 0); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h index 5345242711..ccf78f812a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h @@ -1,49 +1,49 @@ -/* In-Battle Ball Inventory Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BattleBallInventoryReader_H -#define PokemonAutomation_PokemonBDSP_BattleBallInventoryReader_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -using namespace Pokemon; - - -class BattleBallReader{ - static const double MAX_ALPHA; - static const double ALPHA_SPREAD; - -public: - BattleBallReader(VideoStream& stream, Language language); - -public: - std::string read_ball(const ImageViewRGB32& screen) const; - uint16_t read_quantity(const ImageViewRGB32& screen) const; - -private: - const ImageMatch::CroppedImageDictionaryMatcher& m_matcher; - const PokeballNameReader& m_name_reader; - Language m_language; - VideoStream& m_stream; - OverlayBoxScope m_box_sprite; - OverlayBoxScope m_box_name; - OverlayBoxScope m_box_quantity; -}; - - - - -} -} -} -#endif +/* In-Battle Ball Inventory Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BattleBallInventoryReader_H +#define PokemonAutomation_PokemonBDSP_BattleBallInventoryReader_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace Pokemon; + + +class BattleBallReader{ + static const double MAX_ALPHA; + static const double ALPHA_SPREAD; + +public: + BattleBallReader(VideoStream& stream, Language language); + +public: + std::string read_ball(const ImageViewRGB32& screen) const; + uint16_t read_quantity(const ImageViewRGB32& screen) const; + +private: + const ImageMatch::CroppedImageDictionaryMatcher& m_matcher; + const PokeballNameReader& m_name_reader; + Language m_language; + VideoStream& m_stream; + OverlayBoxScope m_box_sprite; + OverlayBoxScope m_box_name; + OverlayBoxScope m_box_quantity; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp index 536df70512..c6f6e64653 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.cpp @@ -1,173 +1,173 @@ -/* Battle Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_BattleMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -BattleMenuDetector::BattleMenuDetector(BattleType battle_type, Color color) - : m_color(color) - , m_battle_type(battle_type) - , m_left0_status (0.140, 0.922, 0.100, 0.010) - , m_left1_status (0.140, 0.910, 0.100, 0.010) - , m_right_status (0.405, 0.925, 0.100, 0.010) -// , m_opponent_left (0.685, 0.065, 0.020, 0.030) -// , m_opponent_right (0.960, 0.065, 0.020, 0.030) - , m_opponent_left (0.708, 0.070, 0.005, 0.028) - , m_opponent_right (0.982, 0.070, 0.005, 0.028) - , m_ball_left (0.890, 0.475, 0.02, 0.03) - , m_ball_right (0.960, 0.475, 0.03, 0.03) - , m_menu_battle (0.817, 0.585 + 0 * 0.1075, 0.150, 0.070) - , m_menu_pokemon (0.817, 0.585 + 1 * 0.1075, 0.150, 0.070) - , m_menu_bag (0.817, 0.585 + 2 * 0.1075, 0.150, 0.070) - , m_menu_run (0.817, 0.585 + 3 * 0.1075, 0.150, 0.070) -{} -void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_left0_status); - items.add(m_color, m_left1_status); - items.add(m_color, m_right_status); - items.add(m_color, m_opponent_left); - items.add(m_color, m_opponent_right); - items.add(m_color, m_ball_left); - items.add(m_color, m_ball_right); - items.add(m_color, m_menu_battle); - items.add(m_color, m_menu_pokemon); - items.add(m_color, m_menu_bag); - items.add(m_color, m_menu_run); -} -bool BattleMenuDetector::is_battle_button(const ImageViewRGB32& screen) const{ - ImageStats stats = image_stats(extract_box_reference(screen, m_menu_battle)); -// cout << stats.average << stats.stddev << endl; - double stddev = stats.stddev.sum(); - if (stddev < 30 || stddev > 150){ - return false; - } - double average = stats.average.sum(); - FloatPixel actual = stats.average / average; - if (euclidean_distance(actual, {0.541961, 0.231317, 0.226722}) > 0.2){ - return false; - } - return true; -} -bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ - { - bool left = is_white(extract_box_reference(screen, m_opponent_left)); - bool right = is_white(extract_box_reference(screen, m_opponent_right)); - if (!left && !right){ -// cout << "opp left or right" << endl; - return false; - } - } - { - bool left0 = is_white(extract_box_reference(screen, m_left0_status)); - bool left1 = is_white(extract_box_reference(screen, m_left1_status)); - bool right = is_white(extract_box_reference(screen, m_right_status)); - if (!left0 && !left1 && !right){ - return false; - } - } - - if (m_battle_type == BattleType::STARTER){ - return is_battle_button(screen); - } - - - if (m_battle_type == BattleType::STANDARD){ - if (!is_white(extract_box_reference(screen, m_ball_left))){ -// cout << "Not white" << endl; - return false; - } - if (!is_white(extract_box_reference(screen, m_ball_right))){ -// cout << "Not white" << endl; - return false; - } - } - - if (!is_battle_button(screen)){ - return false; - } -// cout << "Start Checking Pokemon" << endl; - { - ImageStats stats = image_stats(extract_box_reference(screen, m_menu_pokemon)); -// cout << stats.average << stats.stddev << endl; - double stddev = stats.stddev.sum(); - if (stddev < 30 || stddev > 150){ - return false; - } - double average = stats.average.sum(); - FloatPixel actual = stats.average / average; - if (euclidean_distance(actual, {0.255944, 0.582771, 0.161285}) > 0.2){ - return false; - } - } - // cout << "Start Checking bag" << endl; - { - ImageStats stats = image_stats(extract_box_reference(screen, m_menu_bag)); -// cout << stats.average << stats.stddev << endl; - double stddev = stats.stddev.sum(); - if (stddev < 30 || stddev > 100){ - return false; - } - double average = stats.average.sum(); - FloatPixel actual = stats.average / average; - if (euclidean_distance(actual, {0.485857, 0.414946, 0.099197}) > 0.2){ - return false; - } - } - { - ImageStats stats = image_stats(extract_box_reference(screen, m_menu_run)); -// cout << stats.average << stats.stddev << endl; - double stddev = stats.stddev.sum(); - if (stddev < 30 || stddev > 100){ - return false; - } - double average = stats.average.sum(); - FloatPixel actual = stats.average / average; - if (euclidean_distance(actual, {0.250977, 0.269868, 0.479155}) > 0.2){ - return false; - } - } - - return true; -} - - - - -BattleMenuWatcher::BattleMenuWatcher(BattleType battle_type, Color color) - : BattleMenuDetector(battle_type, color) - , VisualInferenceCallback("BattleMenuWatcher") -{} -void BattleMenuWatcher::make_overlays(VideoOverlaySet& items) const{ - BattleMenuDetector::make_overlays(items); -} -bool BattleMenuWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // Need 5 consecutive successful detections. - if (!detect(frame)){ -// cout << "no detect" << endl; - m_trigger_count = 0; - return false; - } -// cout << "detected" << endl; - m_trigger_count++; - return m_trigger_count >= 5; -} - - - - -} -} -} +/* Battle Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_BattleMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +BattleMenuDetector::BattleMenuDetector(BattleType battle_type, Color color) + : m_color(color) + , m_battle_type(battle_type) + , m_left0_status (0.140, 0.922, 0.100, 0.010) + , m_left1_status (0.140, 0.910, 0.100, 0.010) + , m_right_status (0.405, 0.925, 0.100, 0.010) +// , m_opponent_left (0.685, 0.065, 0.020, 0.030) +// , m_opponent_right (0.960, 0.065, 0.020, 0.030) + , m_opponent_left (0.708, 0.070, 0.005, 0.028) + , m_opponent_right (0.982, 0.070, 0.005, 0.028) + , m_ball_left (0.890, 0.475, 0.02, 0.03) + , m_ball_right (0.960, 0.475, 0.03, 0.03) + , m_menu_battle (0.817, 0.585 + 0 * 0.1075, 0.150, 0.070) + , m_menu_pokemon (0.817, 0.585 + 1 * 0.1075, 0.150, 0.070) + , m_menu_bag (0.817, 0.585 + 2 * 0.1075, 0.150, 0.070) + , m_menu_run (0.817, 0.585 + 3 * 0.1075, 0.150, 0.070) +{} +void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_left0_status); + items.add(m_color, m_left1_status); + items.add(m_color, m_right_status); + items.add(m_color, m_opponent_left); + items.add(m_color, m_opponent_right); + items.add(m_color, m_ball_left); + items.add(m_color, m_ball_right); + items.add(m_color, m_menu_battle); + items.add(m_color, m_menu_pokemon); + items.add(m_color, m_menu_bag); + items.add(m_color, m_menu_run); +} +bool BattleMenuDetector::is_battle_button(const ImageViewRGB32& screen) const{ + ImageStats stats = image_stats(extract_box_reference(screen, m_menu_battle)); +// cout << stats.average << stats.stddev << endl; + double stddev = stats.stddev.sum(); + if (stddev < 30 || stddev > 150){ + return false; + } + double average = stats.average.sum(); + FloatPixel actual = stats.average / average; + if (euclidean_distance(actual, {0.541961, 0.231317, 0.226722}) > 0.2){ + return false; + } + return true; +} +bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ + { + bool left = is_white(extract_box_reference(screen, m_opponent_left)); + bool right = is_white(extract_box_reference(screen, m_opponent_right)); + if (!left && !right){ +// cout << "opp left or right" << endl; + return false; + } + } + { + bool left0 = is_white(extract_box_reference(screen, m_left0_status)); + bool left1 = is_white(extract_box_reference(screen, m_left1_status)); + bool right = is_white(extract_box_reference(screen, m_right_status)); + if (!left0 && !left1 && !right){ + return false; + } + } + + if (m_battle_type == BattleType::STARTER){ + return is_battle_button(screen); + } + + + if (m_battle_type == BattleType::STANDARD){ + if (!is_white(extract_box_reference(screen, m_ball_left))){ +// cout << "Not white" << endl; + return false; + } + if (!is_white(extract_box_reference(screen, m_ball_right))){ +// cout << "Not white" << endl; + return false; + } + } + + if (!is_battle_button(screen)){ + return false; + } +// cout << "Start Checking Pokemon" << endl; + { + ImageStats stats = image_stats(extract_box_reference(screen, m_menu_pokemon)); +// cout << stats.average << stats.stddev << endl; + double stddev = stats.stddev.sum(); + if (stddev < 30 || stddev > 150){ + return false; + } + double average = stats.average.sum(); + FloatPixel actual = stats.average / average; + if (euclidean_distance(actual, {0.255944, 0.582771, 0.161285}) > 0.2){ + return false; + } + } + // cout << "Start Checking bag" << endl; + { + ImageStats stats = image_stats(extract_box_reference(screen, m_menu_bag)); +// cout << stats.average << stats.stddev << endl; + double stddev = stats.stddev.sum(); + if (stddev < 30 || stddev > 100){ + return false; + } + double average = stats.average.sum(); + FloatPixel actual = stats.average / average; + if (euclidean_distance(actual, {0.485857, 0.414946, 0.099197}) > 0.2){ + return false; + } + } + { + ImageStats stats = image_stats(extract_box_reference(screen, m_menu_run)); +// cout << stats.average << stats.stddev << endl; + double stddev = stats.stddev.sum(); + if (stddev < 30 || stddev > 100){ + return false; + } + double average = stats.average.sum(); + FloatPixel actual = stats.average / average; + if (euclidean_distance(actual, {0.250977, 0.269868, 0.479155}) > 0.2){ + return false; + } + } + + return true; +} + + + + +BattleMenuWatcher::BattleMenuWatcher(BattleType battle_type, Color color) + : BattleMenuDetector(battle_type, color) + , VisualInferenceCallback("BattleMenuWatcher") +{} +void BattleMenuWatcher::make_overlays(VideoOverlaySet& items) const{ + BattleMenuDetector::make_overlays(items); +} +bool BattleMenuWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // Need 5 consecutive successful detections. + if (!detect(frame)){ +// cout << "no detect" << endl; + m_trigger_count = 0; + return false; + } +// cout << "detected" << endl; + m_trigger_count++; + return m_trigger_count >= 5; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h index 30a7d2249b..be49b79573 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h @@ -1,73 +1,73 @@ -/* Battle Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BattleMenuDetector_H -#define PokemonAutomation_PokemonBDSP_BattleMenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -enum class BattleType{ - STARTER, - STANDARD, - GREAT_MARSH, - TRAINER, -}; - - -class BattleMenuDetector : public StaticScreenDetector{ -public: - BattleMenuDetector(BattleType battle_type, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - bool is_battle_button(const ImageViewRGB32& screen) const; - -private: - Color m_color; - BattleType m_battle_type; - ImageFloatBox m_left0_status; - ImageFloatBox m_left1_status; - ImageFloatBox m_right_status; - ImageFloatBox m_opponent_left; - ImageFloatBox m_opponent_right; - ImageFloatBox m_ball_left; - ImageFloatBox m_ball_right; - ImageFloatBox m_menu_battle; - ImageFloatBox m_menu_pokemon; - ImageFloatBox m_menu_bag; - ImageFloatBox m_menu_run; -}; - - -class BattleMenuWatcher : public BattleMenuDetector, public VisualInferenceCallback{ -public: - BattleMenuWatcher(BattleType battle_type, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - using VisualInferenceCallback::process_frame; - - -private: - size_t m_trigger_count = 0; -}; - - - -} -} -} -#endif +/* Battle Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BattleMenuDetector_H +#define PokemonAutomation_PokemonBDSP_BattleMenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class BattleType{ + STARTER, + STANDARD, + GREAT_MARSH, + TRAINER, +}; + + +class BattleMenuDetector : public StaticScreenDetector{ +public: + BattleMenuDetector(BattleType battle_type, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + bool is_battle_button(const ImageViewRGB32& screen) const; + +private: + Color m_color; + BattleType m_battle_type; + ImageFloatBox m_left0_status; + ImageFloatBox m_left1_status; + ImageFloatBox m_right_status; + ImageFloatBox m_opponent_left; + ImageFloatBox m_opponent_right; + ImageFloatBox m_ball_left; + ImageFloatBox m_ball_right; + ImageFloatBox m_menu_battle; + ImageFloatBox m_menu_pokemon; + ImageFloatBox m_menu_bag; + ImageFloatBox m_menu_run; +}; + + +class BattleMenuWatcher : public BattleMenuDetector, public VisualInferenceCallback{ +public: + BattleMenuWatcher(BattleType battle_type, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + using VisualInferenceCallback::process_frame; + + +private: + size_t m_trigger_count = 0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.cpp index 9462228ca9..bcdca4e701 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.cpp @@ -1,59 +1,59 @@ -/* End Battle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonBDSP_EndBattleDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -#if 0 -EndBattleWatcher::EndBattleWatcher(const ImageFloatBox& box, Color color) - : VisualInferenceCallback("EndBattleWatcher") - , m_color(color) - , m_box(box) - , m_has_been_black(false) -{} -void EndBattleWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool EndBattleWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return battle_is_over(frame); -} -bool EndBattleWatcher::battle_is_over(const ImageViewRGB32& frame){ - ImageViewRGB32 image = extract_box_reference(frame, m_box); - ImageStats stats = image_stats(image); - if (is_black(stats)){ - m_has_been_black = true; - return false; - } - if (!m_has_been_black){ - return false; - } -// cout << stats.stddev.sum() << endl; - if (stats.stddev.sum() < 20){ - return false; - } - return true; -} -#endif - - - -} -} -} +/* End Battle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonBDSP_EndBattleDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +#if 0 +EndBattleWatcher::EndBattleWatcher(const ImageFloatBox& box, Color color) + : VisualInferenceCallback("EndBattleWatcher") + , m_color(color) + , m_box(box) + , m_has_been_black(false) +{} +void EndBattleWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool EndBattleWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return battle_is_over(frame); +} +bool EndBattleWatcher::battle_is_over(const ImageViewRGB32& frame){ + ImageViewRGB32 image = extract_box_reference(frame, m_box); + ImageStats stats = image_stats(image); + if (is_black(stats)){ + m_has_been_black = true; + return false; + } + if (!m_has_been_black){ + return false; + } +// cout << stats.stddev.sum() << endl; + if (stats.stddev.sum() < 20){ + return false; + } + return true; +} +#endif + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h index 551da4737a..3b48ca5d41 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h @@ -1,59 +1,59 @@ -/* End Battle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EndBattleDetector_H -#define PokemonAutomation_PokemonBDSP_EndBattleDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -#if 0 -class EndBattleWatcher : public VisualInferenceCallback{ -public: - EndBattleWatcher( - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - Color color = COLOR_RED - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool battle_is_over(const ImageViewRGB32& frame); - -private: - Color m_color; - ImageFloatBox m_box; - bool m_has_been_black = false; -}; -#endif - - -class EndBattleWatcher : public BlackScreenOverWatcher{ -public: - EndBattleWatcher( - const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, - Color color = COLOR_RED - ) - : BlackScreenOverWatcher( - color, box, 100, 10, std::chrono::milliseconds(1000) - ) - {} - -}; - - - -} -} -} -#endif +/* End Battle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EndBattleDetector_H +#define PokemonAutomation_PokemonBDSP_EndBattleDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +#if 0 +class EndBattleWatcher : public VisualInferenceCallback{ +public: + EndBattleWatcher( + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + Color color = COLOR_RED + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool battle_is_over(const ImageViewRGB32& frame); + +private: + Color m_color; + ImageFloatBox m_box; + bool m_has_been_black = false; +}; +#endif + + +class EndBattleWatcher : public BlackScreenOverWatcher{ +public: + EndBattleWatcher( + const ImageFloatBox& box = {0.1, 0.1, 0.8, 0.8}, + Color color = COLOR_RED + ) + : BlackScreenOverWatcher( + color, box, 100, 10, std::chrono::milliseconds(1000) + ) + {} + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.cpp index c7656fb2b7..8cc1b67cd6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.cpp @@ -1,80 +1,80 @@ -/* Experience Gain Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_ExperienceGainDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ExperienceGainDetector::~ExperienceGainDetector(){} -ExperienceGainDetector::ExperienceGainDetector(Color color) - : m_color(color) - , m_dialog(color) - , m_middle_column(0.369, 0.01, 0.003, 0.79) - , m_left_column(0.006, 0.01, 0.03, 0.79) - , m_lower_left_region(0.006, 0.8, 0.16, 0.15) -{} - -void ExperienceGainDetector::make_overlays(VideoOverlaySet& items) const{ - m_dialog.make_overlays(items); - items.add(m_color, m_middle_column); - items.add(m_color, m_left_column); - items.add(m_color, m_lower_left_region); -} -bool ExperienceGainDetector::detect(const ImageViewRGB32& screen){ - if (!m_dialog.detect(screen)){ -// cout << "ExperienceGainDetector: No dialogue detected, return" << endl; - return false; - } - - const ImageStats stats0 = image_stats(extract_box_reference(screen, m_middle_column)); -// cout << "ExperienceGainDetector: No m_middle_column detected, " << stats0.average.to_string() << ", " << stats0.stddev.to_string() << endl; - if (!is_solid(stats0, {0.16, 0.42, 0.42}, 0.1, 40)){ - return false; - } - const ImageStats stats1 = image_stats(extract_box_reference(screen, m_left_column)); -// cout << "ExperienceGainDetector: No m_left_column detected, " << stats1.average.to_string() << ", " << stats1.stddev.to_string() << endl; - if (!is_solid(stats1, {0.3, 0.35, 0.35}, 0.1, 40)){ - return false; - } - const ImageStats stats2 = image_stats(extract_box_reference(screen, m_lower_left_region)); -// cout << "ExperienceGainDetector: No m_lower_left_region detected, " << stats2.average.to_string() << ", " << stats2.stddev.to_string() << endl; - if (!is_solid(stats2, {0.3, 0.35, 0.35}, 0.1, 40)){ - return false; - } - -// std::cout << "ExperienceGainDetector: detect!" << std::endl; - return true; -} - - -ExperienceGainWatcher::ExperienceGainWatcher(Color color) - : ExperienceGainDetector(color) - , VisualInferenceCallback("ExperienceGainWatcher") -{} -void ExperienceGainWatcher::make_overlays(VideoOverlaySet& items) const{ - ExperienceGainDetector::make_overlays(items); -} -bool ExperienceGainWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - - - - -} -} -} +/* Experience Gain Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_ExperienceGainDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ExperienceGainDetector::~ExperienceGainDetector(){} +ExperienceGainDetector::ExperienceGainDetector(Color color) + : m_color(color) + , m_dialog(color) + , m_middle_column(0.369, 0.01, 0.003, 0.79) + , m_left_column(0.006, 0.01, 0.03, 0.79) + , m_lower_left_region(0.006, 0.8, 0.16, 0.15) +{} + +void ExperienceGainDetector::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + items.add(m_color, m_middle_column); + items.add(m_color, m_left_column); + items.add(m_color, m_lower_left_region); +} +bool ExperienceGainDetector::detect(const ImageViewRGB32& screen){ + if (!m_dialog.detect(screen)){ +// cout << "ExperienceGainDetector: No dialogue detected, return" << endl; + return false; + } + + const ImageStats stats0 = image_stats(extract_box_reference(screen, m_middle_column)); +// cout << "ExperienceGainDetector: No m_middle_column detected, " << stats0.average.to_string() << ", " << stats0.stddev.to_string() << endl; + if (!is_solid(stats0, {0.16, 0.42, 0.42}, 0.1, 40)){ + return false; + } + const ImageStats stats1 = image_stats(extract_box_reference(screen, m_left_column)); +// cout << "ExperienceGainDetector: No m_left_column detected, " << stats1.average.to_string() << ", " << stats1.stddev.to_string() << endl; + if (!is_solid(stats1, {0.3, 0.35, 0.35}, 0.1, 40)){ + return false; + } + const ImageStats stats2 = image_stats(extract_box_reference(screen, m_lower_left_region)); +// cout << "ExperienceGainDetector: No m_lower_left_region detected, " << stats2.average.to_string() << ", " << stats2.stddev.to_string() << endl; + if (!is_solid(stats2, {0.3, 0.35, 0.35}, 0.1, 40)){ + return false; + } + +// std::cout << "ExperienceGainDetector: detect!" << std::endl; + return true; +} + + +ExperienceGainWatcher::ExperienceGainWatcher(Color color) + : ExperienceGainDetector(color) + , VisualInferenceCallback("ExperienceGainWatcher") +{} +void ExperienceGainWatcher::make_overlays(VideoOverlaySet& items) const{ + ExperienceGainDetector::make_overlays(items); +} +bool ExperienceGainWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h index d30d7ec276..9a71adf39f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h @@ -1,52 +1,52 @@ -/* Battle Won Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BattleWonDetector_H -#define PokemonAutomation_PokemonBDSP_BattleWonDetector_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Detect the screen showing the party pokemon are about to gain experience. -// This is useful to detect whether you have caught or defeated a wild pokemon. -// The experience screen still shows even if all party pokemon are max leveled and have max EVs. -class ExperienceGainDetector : public StaticScreenDetector{ -public: - ~ExperienceGainDetector(); - ExperienceGainDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ShortDialogDetector m_dialog; - ImageFloatBox m_middle_column; - ImageFloatBox m_left_column; - ImageFloatBox m_lower_left_region; -}; - -// Watch for the screen that the party pokemon are about to gain experience. -// The experience screen still shows even if all party pokemon are max leveled and have max EVs. -class ExperienceGainWatcher : public ExperienceGainDetector, public VisualInferenceCallback{ -public: - ExperienceGainWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - // Return true when the screen that the party pokemon are about to gain experience is found. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; -}; - - -} -} -} -#endif +/* Battle Won Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BattleWonDetector_H +#define PokemonAutomation_PokemonBDSP_BattleWonDetector_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Detect the screen showing the party pokemon are about to gain experience. +// This is useful to detect whether you have caught or defeated a wild pokemon. +// The experience screen still shows even if all party pokemon are max leveled and have max EVs. +class ExperienceGainDetector : public StaticScreenDetector{ +public: + ~ExperienceGainDetector(); + ExperienceGainDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ShortDialogDetector m_dialog; + ImageFloatBox m_middle_column; + ImageFloatBox m_left_column; + ImageFloatBox m_lower_left_region; +}; + +// Watch for the screen that the party pokemon are about to gain experience. +// The experience screen still shows even if all party pokemon are max leveled and have max EVs. +class ExperienceGainWatcher : public ExperienceGainDetector, public VisualInferenceCallback{ +public: + ExperienceGainWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + // Return true when the screen that the party pokemon are about to gain experience is found. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.cpp index 834e6c2299..52b09fe625 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.cpp @@ -1,90 +1,90 @@ -/* Start Battle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonBDSP_StartBattleDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - - - -StartBattleDetector::StartBattleDetector(VideoOverlay& overlay) - : VisualInferenceCallback("StartBattleDetector") - , m_screen_box(0.2, 0.2, 0.6, 0.6) -{} -void StartBattleDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_screen_box); - m_dialog.make_overlays(items); -} -bool StartBattleDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -bool StartBattleDetector::detect(const ImageViewRGB32& frame){ -// ImageViewRGB32 image = extract_box_reference(frame, m_screen_box); - -// ImageStats stats = image_stats(image); - -// // Solid screen that's not black. -// if (stats.average.sum() > 50 && stats.stddev.sum() < 10){ -// return true; -// } - - return m_dialog.detect(frame); -} - - -StartBattleMenuOverlapDetector::StartBattleMenuOverlapDetector(VideoOverlay& overlay) - : VisualInferenceCallback("StartBattleMenuOverlapDetector") - , m_left(0.02, 0.2, 0.08, 0.5) - , m_right(0.90, 0.2, 0.08, 0.5) - , m_battle_detected(false) -{} -void StartBattleMenuOverlapDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left); - items.add(COLOR_RED, m_right); -} -bool StartBattleMenuOverlapDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - if (detect(frame)){ - m_battle_detected.store(true, std::memory_order_release); - return true; - } - return false; -} -bool StartBattleMenuOverlapDetector::detect(const ImageViewRGB32& frame){ - ImageViewRGB32 image0 = extract_box_reference(frame, m_left); - ImageStats stats0 = image_stats(image0); - // Solid screen that's not black. - if (stats0.average.sum() < 50 || stats0.stddev.sum() > 10){ - return false; - } - - ImageViewRGB32 image1 = extract_box_reference(frame, m_right); - ImageStats stats1 = image_stats(image1); - // Solid screen that's not black. - if (stats1.average.sum() < 50 && stats1.stddev.sum() > 10){ - return false; - } - - return true; -} - - - - -} -} -} +/* Start Battle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonBDSP_StartBattleDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + + + +StartBattleDetector::StartBattleDetector(VideoOverlay& overlay) + : VisualInferenceCallback("StartBattleDetector") + , m_screen_box(0.2, 0.2, 0.6, 0.6) +{} +void StartBattleDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_screen_box); + m_dialog.make_overlays(items); +} +bool StartBattleDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +bool StartBattleDetector::detect(const ImageViewRGB32& frame){ +// ImageViewRGB32 image = extract_box_reference(frame, m_screen_box); + +// ImageStats stats = image_stats(image); + +// // Solid screen that's not black. +// if (stats.average.sum() > 50 && stats.stddev.sum() < 10){ +// return true; +// } + + return m_dialog.detect(frame); +} + + +StartBattleMenuOverlapDetector::StartBattleMenuOverlapDetector(VideoOverlay& overlay) + : VisualInferenceCallback("StartBattleMenuOverlapDetector") + , m_left(0.02, 0.2, 0.08, 0.5) + , m_right(0.90, 0.2, 0.08, 0.5) + , m_battle_detected(false) +{} +void StartBattleMenuOverlapDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left); + items.add(COLOR_RED, m_right); +} +bool StartBattleMenuOverlapDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (detect(frame)){ + m_battle_detected.store(true, std::memory_order_release); + return true; + } + return false; +} +bool StartBattleMenuOverlapDetector::detect(const ImageViewRGB32& frame){ + ImageViewRGB32 image0 = extract_box_reference(frame, m_left); + ImageStats stats0 = image_stats(image0); + // Solid screen that's not black. + if (stats0.average.sum() < 50 || stats0.stddev.sum() > 10){ + return false; + } + + ImageViewRGB32 image1 = extract_box_reference(frame, m_right); + ImageStats stats1 = image_stats(image1); + // Solid screen that's not black. + if (stats1.average.sum() < 50 && stats1.stddev.sum() > 10){ + return false; + } + + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h index 7e6cd64dcc..bc31465d31 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h @@ -1,62 +1,62 @@ -/* Start Battle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_StartBattleDetector_H -#define PokemonAutomation_PokemonBDSP_StartBattleDetector_H - -#include -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class StartBattleDetector : public VisualInferenceCallback{ -public: - StartBattleDetector(VideoOverlay& overlay); - - bool detect(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - ImageFloatBox m_screen_box; - BattleDialogDetector m_dialog; -}; - - -class StartBattleMenuOverlapDetector : public VisualInferenceCallback{ -public: - StartBattleMenuOverlapDetector(VideoOverlay& overlay); - - bool detected() const{ return m_battle_detected.load(std::memory_order_acquire); } - bool detect(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - ImageFloatBox m_left; - ImageFloatBox m_right; - std::atomic m_battle_detected; -}; - - - - - - - -} -} -} -#endif - +/* Start Battle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StartBattleDetector_H +#define PokemonAutomation_PokemonBDSP_StartBattleDetector_H + +#include +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class StartBattleDetector : public VisualInferenceCallback{ +public: + StartBattleDetector(VideoOverlay& overlay); + + bool detect(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + ImageFloatBox m_screen_box; + BattleDialogDetector m_dialog; +}; + + +class StartBattleMenuOverlapDetector : public VisualInferenceCallback{ +public: + StartBattleMenuOverlapDetector(VideoOverlay& overlay); + + bool detected() const{ return m_battle_detected.load(std::memory_order_acquire); } + bool detect(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + ImageFloatBox m_left; + ImageFloatBox m_right; + std::atomic m_battle_detected; +}; + + + + + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.cpp index b079e86256..e60d1b7d33 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.cpp @@ -1,76 +1,76 @@ -/* Box Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_BoxDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -BoxDetector::BoxDetector(Color color) - : m_color(color) - , m_left(0.265, 0.09, 0.03, 0.04) - , m_right(0.650, 0.09, 0.03, 0.04) - , m_bottom(0.02, 0.97, 0.10, 0.02) - , m_row(0.26, 0.20, 0.40, 0.10) -{} -void BoxDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_left); - items.add(m_color, m_right); - items.add(m_color, m_bottom); - items.add(m_color, m_row); -} -bool BoxDetector::detect(const ImageViewRGB32& screen){ - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << left.average << left.stddev << endl; - if (!is_solid(left, {0.274119, 0.355324, 0.370557})){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// cout << right.average << right.stddev << endl; - if (!is_solid(right, {0.274119, 0.355324, 0.370557})){ - return false; - } - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; - if (!is_solid(bottom, {0.190353, 0.327458, 0.482189})){ - return false; - } - ImageStats row = image_stats(extract_box_reference(screen, m_row)); -// cout << row.average << row.stddev << endl; - if (row.stddev.sum() < 50){ - return false; - } - return true; -} - - - -BoxWatcher::BoxWatcher(Color color) - : BoxDetector(color) - , VisualInferenceCallback("BoxWatcher") -{} -void BoxWatcher::make_overlays(VideoOverlaySet& items) const{ - BoxDetector::make_overlays(items); -} -bool BoxWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - - - - -} -} -} +/* Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_BoxDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +BoxDetector::BoxDetector(Color color) + : m_color(color) + , m_left(0.265, 0.09, 0.03, 0.04) + , m_right(0.650, 0.09, 0.03, 0.04) + , m_bottom(0.02, 0.97, 0.10, 0.02) + , m_row(0.26, 0.20, 0.40, 0.10) +{} +void BoxDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_left); + items.add(m_color, m_right); + items.add(m_color, m_bottom); + items.add(m_color, m_row); +} +bool BoxDetector::detect(const ImageViewRGB32& screen){ + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << left.average << left.stddev << endl; + if (!is_solid(left, {0.274119, 0.355324, 0.370557})){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// cout << right.average << right.stddev << endl; + if (!is_solid(right, {0.274119, 0.355324, 0.370557})){ + return false; + } + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; + if (!is_solid(bottom, {0.190353, 0.327458, 0.482189})){ + return false; + } + ImageStats row = image_stats(extract_box_reference(screen, m_row)); +// cout << row.average << row.stddev << endl; + if (row.stddev.sum() < 50){ + return false; + } + return true; +} + + + +BoxWatcher::BoxWatcher(Color color) + : BoxDetector(color) + , VisualInferenceCallback("BoxWatcher") +{} +void BoxWatcher::make_overlays(VideoOverlaySet& items) const{ + BoxDetector::make_overlays(items); +} +bool BoxWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h index d73713edd5..d254e4c097 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h @@ -1,49 +1,49 @@ -/* Box Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BoxDetector_H -#define PokemonAutomation_PokemonBDSP_BoxDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class BoxDetector : public StaticScreenDetector{ -public: - BoxDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_left; - ImageFloatBox m_right; - ImageFloatBox m_bottom; - ImageFloatBox m_row; -}; - - -class BoxWatcher : public BoxDetector, public VisualInferenceCallback{ -public: - BoxWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - - -} -} -} -#endif +/* Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BoxDetector_H +#define PokemonAutomation_PokemonBDSP_BoxDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class BoxDetector : public StaticScreenDetector{ +public: + BoxDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_left; + ImageFloatBox m_right; + ImageFloatBox m_bottom; + ImageFloatBox m_row; +}; + + +class BoxWatcher : public BoxDetector, public VisualInferenceCallback{ +public: + BoxWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.cpp index 82cfd1563c..4c1c923a20 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.cpp @@ -1,126 +1,126 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonBDSP_BoxGenderDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Kernels; -using namespace Kernels::Waterfill; -using namespace Pokemon; - - - -class GenderIcon : public ImageMatch::SubObjectTemplateMatcher{ -public: - GenderIcon(bool male) - : SubObjectTemplateMatcher( - male - ? "PokemonBDSP/M-Icon.png" - : "PokemonBDSP/F-Icon.png", - 100 - ) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), 0xff7f7f7f, 0xffffffff - ); - std::vector objects = find_objects_inplace(matrix, 20); - if (objects.size() != 1){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find exactly one object in resource.", - m_path - ); - } - set_subobject(objects[0]); - } - - static const GenderIcon& female(){ - static GenderIcon matcher(false); - return matcher; - } - static const GenderIcon& male(){ - static GenderIcon matcher(true); - return matcher; - } -}; - - - - -bool is_male(const ImageViewRGB32& image, const WaterfillObject& object){ - size_t width = object.width(); - size_t height = object.height(); - if (width > 2 * height){ - return false; - } - if (height > 2 * width){ - return false; - } - - ImagePixelBox obj; - return GenderIcon::male().matches(obj, image, object); -} - -bool is_female(const ImageViewRGB32& image, const WaterfillObject& object){ - size_t width = object.width(); - size_t height = object.height(); - if (width > 2 * height){ - return false; - } - if (height > 2 * width){ - return false; - } - - ImagePixelBox obj; - return GenderIcon::female().matches(obj, image, object); -} - - -StatsHuntGenderFilter read_gender_from_box(Logger& logger, VideoOverlay& overlay, const ImageViewRGB32& frame) -{ - OverlayBoxScope gender_box(overlay, {0.733, 0.022, 0.204, 0.049}, COLOR_BLUE); - ImageViewRGB32 name_and_gender = extract_box_reference(frame, gender_box); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(name_and_gender, 0xff7f7f7f, 0xffffffff); - std::vector objects = find_objects_inplace(matrix, 20); - for (WaterfillObject& object : objects){ - if (is_male(name_and_gender, object)){ - logger.log("Detected male symbol.", COLOR_PURPLE); - return StatsHuntGenderFilter::Male; - } - if (is_female(name_and_gender, object)){ - logger.log("Detected female symbol.", COLOR_PURPLE); - return StatsHuntGenderFilter::Female; - } - } - - logger.log("No gender symbol detected.", COLOR_PURPLE); - return StatsHuntGenderFilter::Genderless; -} - - - - -} -} -} +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonBDSP_BoxGenderDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Kernels; +using namespace Kernels::Waterfill; +using namespace Pokemon; + + + +class GenderIcon : public ImageMatch::SubObjectTemplateMatcher{ +public: + GenderIcon(bool male) + : SubObjectTemplateMatcher( + male + ? "PokemonBDSP/M-Icon.png" + : "PokemonBDSP/F-Icon.png", + 100 + ) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), 0xff7f7f7f, 0xffffffff + ); + std::vector objects = find_objects_inplace(matrix, 20); + if (objects.size() != 1){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find exactly one object in resource.", + m_path + ); + } + set_subobject(objects[0]); + } + + static const GenderIcon& female(){ + static GenderIcon matcher(false); + return matcher; + } + static const GenderIcon& male(){ + static GenderIcon matcher(true); + return matcher; + } +}; + + + + +bool is_male(const ImageViewRGB32& image, const WaterfillObject& object){ + size_t width = object.width(); + size_t height = object.height(); + if (width > 2 * height){ + return false; + } + if (height > 2 * width){ + return false; + } + + ImagePixelBox obj; + return GenderIcon::male().matches(obj, image, object); +} + +bool is_female(const ImageViewRGB32& image, const WaterfillObject& object){ + size_t width = object.width(); + size_t height = object.height(); + if (width > 2 * height){ + return false; + } + if (height > 2 * width){ + return false; + } + + ImagePixelBox obj; + return GenderIcon::female().matches(obj, image, object); +} + + +StatsHuntGenderFilter read_gender_from_box(Logger& logger, VideoOverlay& overlay, const ImageViewRGB32& frame) +{ + OverlayBoxScope gender_box(overlay, {0.733, 0.022, 0.204, 0.049}, COLOR_BLUE); + ImageViewRGB32 name_and_gender = extract_box_reference(frame, gender_box); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(name_and_gender, 0xff7f7f7f, 0xffffffff); + std::vector objects = find_objects_inplace(matrix, 20); + for (WaterfillObject& object : objects){ + if (is_male(name_and_gender, object)){ + logger.log("Detected male symbol.", COLOR_PURPLE); + return StatsHuntGenderFilter::Male; + } + if (is_female(name_and_gender, object)){ + logger.log("Detected female symbol.", COLOR_PURPLE); + return StatsHuntGenderFilter::Female; + } + } + + logger.log("No gender symbol detected.", COLOR_PURPLE); + return StatsHuntGenderFilter::Genderless; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h index 720e42fcbf..a881ad0b2b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h @@ -1,31 +1,31 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BoxGenderDetector_H -#define PokemonAutomation_PokemonBDSP_BoxGenderDetector_H - -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" - -namespace PokemonAutomation{ -class Logger; -class VideoOverlay; -class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -Pokemon::StatsHuntGenderFilter read_gender_from_box( - Logger& logger, VideoOverlay& overlay, - const ImageViewRGB32& frame -); - - - - -} -} -} -#endif +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BoxGenderDetector_H +#define PokemonAutomation_PokemonBDSP_BoxGenderDetector_H + +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ +class Logger; +class VideoOverlay; +class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +Pokemon::StatsHuntGenderFilter read_gender_from_box( + Logger& logger, VideoOverlay& overlay, + const ImageViewRGB32& frame +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.cpp index 27c51e82c1..0c209f14ba 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.cpp @@ -1,47 +1,47 @@ -/* Box Nature Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonBDSP_BoxNatureDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -const NatureReader& NATURE_READER(){ - const static Pokemon::NatureReader reader("Pokemon/NatureCheckerOCR.json"); - return reader; -} - -BoxNatureDetector::BoxNatureDetector(VideoOverlay& overlay, Language language) - : m_language(language) - , m_nature(overlay, {0.785, 0.196 + 6 * 0.0529, 0.2, 0.0515}) -{} - -NatureCheckerValue BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ - ImageViewRGB32 image = extract_box_reference(frame, box); - OCR::StringMatchResult result = NATURE_READER().read_substring( - logger, m_language, image, - OCR::BLACK_TEXT_FILTERS() - ); - result.clear_beyond_log10p(NatureReader::MAX_LOG10P); - if (result.results.size() != 1){ - return NatureCheckerValue::UnableToDetect; - } - return NATURE_CHECKER_VALUE_STRINGS().get_enum(result.results.begin()->second.token); -} -NatureReader::Results BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame){ - NatureReader::Results results; - if (m_language != Language::None){ - results.nature = read(logger, frame, m_nature); - } - return results; -} - -} -} -} - +/* Box Nature Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonBDSP_BoxNatureDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +const NatureReader& NATURE_READER(){ + const static Pokemon::NatureReader reader("Pokemon/NatureCheckerOCR.json"); + return reader; +} + +BoxNatureDetector::BoxNatureDetector(VideoOverlay& overlay, Language language) + : m_language(language) + , m_nature(overlay, {0.785, 0.196 + 6 * 0.0529, 0.2, 0.0515}) +{} + +NatureCheckerValue BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ + ImageViewRGB32 image = extract_box_reference(frame, box); + OCR::StringMatchResult result = NATURE_READER().read_substring( + logger, m_language, image, + OCR::BLACK_TEXT_FILTERS() + ); + result.clear_beyond_log10p(NatureReader::MAX_LOG10P); + if (result.results.size() != 1){ + return NatureCheckerValue::UnableToDetect; + } + return NATURE_CHECKER_VALUE_STRINGS().get_enum(result.results.begin()->second.token); +} +NatureReader::Results BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame){ + NatureReader::Results results; + if (m_language != Language::None){ + results.nature = read(logger, frame, m_nature); + } + return results; +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h index f5a2622220..dd7fee0e01 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h @@ -1,39 +1,39 @@ -/* Box Nature Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BoxNatureDetector_H -#define PokemonAutomation_PokemonBDSP_BoxNatureDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_NatureReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -using namespace Pokemon; - -const NatureReader& NATURE_READER(); - -class BoxNatureDetector{ -public: - BoxNatureDetector(VideoOverlay& overlay, Language language); - - NatureReader::Results read(Logger& logger, const ImageViewRGB32& frame); - -private: - NatureCheckerValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); - -private: - Language m_language; - OverlayBoxScope m_nature; -}; - - - -} -} -} -#endif +/* Box Nature Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BoxNatureDetector_H +#define PokemonAutomation_PokemonBDSP_BoxNatureDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_NatureReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace Pokemon; + +const NatureReader& NATURE_READER(); + +class BoxNatureDetector{ +public: + BoxNatureDetector(VideoOverlay& overlay, Language language); + + NatureReader::Results read(Logger& logger, const ImageViewRGB32& frame); + +private: + NatureCheckerValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); + +private: + Language m_language; + OverlayBoxScope m_nature; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.cpp index 1cf3dbde2b..5dbd72d207 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.cpp @@ -1,67 +1,67 @@ -/* Box Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_BoxShinyDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -BoxShinyDetector::BoxShinyDetector(Color color) - : m_color(color) - , m_symbol(0.960, 0.145, 0.030, 0.050) - , m_background(0.960, 0.200, 0.030, 0.400) -{} -void BoxShinyDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_symbol); - items.add(m_color, m_background); -} - -bool BoxShinyDetector::is_panel(const ImageViewRGB32& screen) const{ - ImageStats background = image_stats(extract_box_reference(screen, m_background)); -// cout << background.average << background.stddev << endl; - if (!is_white(background)){ - return false; - } - return true; -} -bool BoxShinyDetector::detect(const ImageViewRGB32& screen){ - if (!is_panel(screen)){ - return false; - } - ImageStats symbol = image_stats(extract_box_reference(screen, m_symbol)); -// extract_box(screen, m_symbol).save("test.png"); -// cout << symbol.average << symbol.stddev << endl; - - double average = symbol.average.sum(); - double stddev = symbol.stddev.sum(); - if (stddev < 50){ -// cout << "bad stddev = " << stddev << endl; - return false; - } - - FloatPixel actual = symbol.average / average; - double distance = euclidean_distance(actual, {0.366743, 0.320479, 0.312778}); -// cout << "distance = " << distance << endl; - return distance <= 0.15; -} - - - - - - -} -} -} +/* Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_BoxShinyDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +BoxShinyDetector::BoxShinyDetector(Color color) + : m_color(color) + , m_symbol(0.960, 0.145, 0.030, 0.050) + , m_background(0.960, 0.200, 0.030, 0.400) +{} +void BoxShinyDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_symbol); + items.add(m_color, m_background); +} + +bool BoxShinyDetector::is_panel(const ImageViewRGB32& screen) const{ + ImageStats background = image_stats(extract_box_reference(screen, m_background)); +// cout << background.average << background.stddev << endl; + if (!is_white(background)){ + return false; + } + return true; +} +bool BoxShinyDetector::detect(const ImageViewRGB32& screen){ + if (!is_panel(screen)){ + return false; + } + ImageStats symbol = image_stats(extract_box_reference(screen, m_symbol)); +// extract_box(screen, m_symbol).save("test.png"); +// cout << symbol.average << symbol.stddev << endl; + + double average = symbol.average.sum(); + double stddev = symbol.stddev.sum(); + if (stddev < 50){ +// cout << "bad stddev = " << stddev << endl; + return false; + } + + FloatPixel actual = symbol.average / average; + double distance = euclidean_distance(actual, {0.366743, 0.320479, 0.312778}); +// cout << "distance = " << distance << endl; + return distance <= 0.15; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h index 58682d3b10..6122318b4e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h @@ -1,40 +1,40 @@ -/* Box Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BoxShinyDetector_H -#define PokemonAutomation_PokemonBDSP_BoxShinyDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class BoxShinyDetector : public StaticScreenDetector{ -public: - BoxShinyDetector(Color color = COLOR_RED); - - bool is_panel(const ImageViewRGB32& screen) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_symbol; - ImageFloatBox m_background; -}; - - - - -} -} -} -#endif +/* Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BoxShinyDetector_H +#define PokemonAutomation_PokemonBDSP_BoxShinyDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class BoxShinyDetector : public StaticScreenDetector{ +public: + BoxShinyDetector(Color color = COLOR_RED); + + bool is_panel(const ImageViewRGB32& screen) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_symbol; + ImageFloatBox m_background; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.cpp index 6d2bb6c9b3..b61d8ced47 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.cpp @@ -1,68 +1,68 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonBDSP_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -IvJudgeReaderScope::IvJudgeReaderScope(VideoOverlay& overlay, Language language) - : m_language(language) - , m_box0(overlay, {0.785, 0.196 + 0 * 0.0529, 0.2, 0.0515}) - , m_box1(overlay, {0.785, 0.196 + 1 * 0.0529, 0.2, 0.0515}) - , m_box2(overlay, {0.785, 0.196 + 2 * 0.0529, 0.2, 0.0515}) - , m_box3(overlay, {0.785, 0.196 + 3 * 0.0529, 0.2, 0.0515}) - , m_box4(overlay, {0.785, 0.196 + 4 * 0.0529, 0.2, 0.0515}) - , m_box5(overlay, {0.785, 0.196 + 5 * 0.0529, 0.2, 0.0515}) -{} - - -IvJudgeValue IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ - ImageViewRGB32 image = extract_box_reference(frame, box); - OCR::StringMatchResult result = PokemonSwSh::IV_READER().read_substring( - logger, m_language, image, - OCR::BLACK_TEXT_FILTERS() - ); - result.clear_beyond_log10p(IvJudgeReader::MAX_LOG10P); - if (result.results.size() != 1){ - return IvJudgeValue::UnableToDetect; - } - return IV_JUDGE_VALUE_STRINGS().get_enum(result.results.begin()->second.token); -} -IvJudgeReader::Results IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame){ - IvJudgeReader::Results results; - if (m_language != Language::None){ - results.hp = read(logger, frame, m_box0); - results.attack = read(logger, frame, m_box1); - results.defense = read(logger, frame, m_box2); - results.spatk = read(logger, frame, m_box3); - results.spdef = read(logger, frame, m_box4); - results.speed = read(logger, frame, m_box5); - } - return results; -} - -std::vector IvJudgeReaderScope::dump_images(const ImageViewRGB32& frame){ - std::vector images; - images.emplace_back(extract_box_reference(frame, m_box0)); - images.emplace_back(extract_box_reference(frame, m_box1)); - images.emplace_back(extract_box_reference(frame, m_box2)); - images.emplace_back(extract_box_reference(frame, m_box3)); - images.emplace_back(extract_box_reference(frame, m_box4)); - images.emplace_back(extract_box_reference(frame, m_box5)); - return images; -} - - - -} -} -} - +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonBDSP_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +IvJudgeReaderScope::IvJudgeReaderScope(VideoOverlay& overlay, Language language) + : m_language(language) + , m_box0(overlay, {0.785, 0.196 + 0 * 0.0529, 0.2, 0.0515}) + , m_box1(overlay, {0.785, 0.196 + 1 * 0.0529, 0.2, 0.0515}) + , m_box2(overlay, {0.785, 0.196 + 2 * 0.0529, 0.2, 0.0515}) + , m_box3(overlay, {0.785, 0.196 + 3 * 0.0529, 0.2, 0.0515}) + , m_box4(overlay, {0.785, 0.196 + 4 * 0.0529, 0.2, 0.0515}) + , m_box5(overlay, {0.785, 0.196 + 5 * 0.0529, 0.2, 0.0515}) +{} + + +IvJudgeValue IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ + ImageViewRGB32 image = extract_box_reference(frame, box); + OCR::StringMatchResult result = PokemonSwSh::IV_READER().read_substring( + logger, m_language, image, + OCR::BLACK_TEXT_FILTERS() + ); + result.clear_beyond_log10p(IvJudgeReader::MAX_LOG10P); + if (result.results.size() != 1){ + return IvJudgeValue::UnableToDetect; + } + return IV_JUDGE_VALUE_STRINGS().get_enum(result.results.begin()->second.token); +} +IvJudgeReader::Results IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame){ + IvJudgeReader::Results results; + if (m_language != Language::None){ + results.hp = read(logger, frame, m_box0); + results.attack = read(logger, frame, m_box1); + results.defense = read(logger, frame, m_box2); + results.spatk = read(logger, frame, m_box3); + results.spdef = read(logger, frame, m_box4); + results.speed = read(logger, frame, m_box5); + } + return results; +} + +std::vector IvJudgeReaderScope::dump_images(const ImageViewRGB32& frame){ + std::vector images; + images.emplace_back(extract_box_reference(frame, m_box0)); + images.emplace_back(extract_box_reference(frame, m_box1)); + images.emplace_back(extract_box_reference(frame, m_box2)); + images.emplace_back(extract_box_reference(frame, m_box3)); + images.emplace_back(extract_box_reference(frame, m_box4)); + images.emplace_back(extract_box_reference(frame, m_box5)); + return images; +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h index cc09ad60d1..dcff132b36 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h @@ -1,45 +1,45 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_IvJudgeReader_H -#define PokemonAutomation_PokemonBDSP_IvJudgeReader_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -using namespace Pokemon; - - -class IvJudgeReaderScope{ -public: - IvJudgeReaderScope(VideoOverlay& overlay, Language language); - - IvJudgeReader::Results read(Logger& logger, const ImageViewRGB32& frame); - - std::vector dump_images(const ImageViewRGB32& frame); - -private: - IvJudgeValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); - -private: - Language m_language; - OverlayBoxScope m_box0; - OverlayBoxScope m_box1; - OverlayBoxScope m_box2; - OverlayBoxScope m_box3; - OverlayBoxScope m_box4; - OverlayBoxScope m_box5; -}; - - - -} -} -} -#endif +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_IvJudgeReader_H +#define PokemonAutomation_PokemonBDSP_IvJudgeReader_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace Pokemon; + + +class IvJudgeReaderScope{ +public: + IvJudgeReaderScope(VideoOverlay& overlay, Language language); + + IvJudgeReader::Results read(Logger& logger, const ImageViewRGB32& frame); + + std::vector dump_images(const ImageViewRGB32& frame); + +private: + IvJudgeValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); + +private: + Language m_language; + OverlayBoxScope m_box0; + OverlayBoxScope m_box1; + OverlayBoxScope m_box2; + OverlayBoxScope m_box3; + OverlayBoxScope m_box4; + OverlayBoxScope m_box5; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp index 3097ab5c85..c39092181f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.cpp @@ -1,139 +1,139 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_DialogDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ShortDialogDetector::ShortDialogDetector(Color color) - : m_color(color) -// , m_bottom(0.50, 0.91, 0.29, 0.05) - , m_left_white(0.21, 0.835, 0.008, 0.12) - , m_left(0.18, 0.835, 0.02, 0.12) - , m_right_white(0.785, 0.835, 0.008, 0.12) - , m_right(0.822, 0.835, 0.02, 0.12) -{} -void ShortDialogDetector::make_overlays(VideoOverlaySet& items) const{ -// items.add(m_color, m_bottom); - items.add(m_color, m_left_white); - items.add(m_color, m_left); - items.add(m_color, m_right_white); - items.add(m_color, m_right); -} -bool ShortDialogDetector::detect(const ImageViewRGB32& screen){ - ImageStats left_white = image_stats(extract_box_reference(screen, m_left_white)); - if (!is_white(left_white)){ - return false; - } - ImageStats right_white = image_stats(extract_box_reference(screen, m_right_white)); - if (!is_white(right_white)){ - return false; - } -// ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// if (!is_white(bottom)){ -// return false; -// } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << left.stddev << endl; - if (left.stddev.sum() < 30){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// cout << right.stddev << endl; - if (right.stddev.sum() < 30){ - return false; - } - return true; -} - - -ShortDialogWatcher::ShortDialogWatcher(Color color) - : ShortDialogDetector(color) - , VisualInferenceCallback("ShortDialogWatcher") -{} -void ShortDialogWatcher::make_overlays(VideoOverlaySet& items) const{ - ShortDialogDetector::make_overlays(items); -} -bool ShortDialogWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ - return detect(frame); -} - - - - -BattleDialogDetector::BattleDialogDetector(Color color) - : m_color(color) - , m_bottom(0.50, 0.91, 0.40, 0.05) - , m_left_white(0.07, 0.835, 0.008, 0.12) - , m_left(0.04, 0.835, 0.02, 0.12) - , m_right(0.965, 0.835, 0.02, 0.12) -{} -void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - items.add(m_color, m_left_white); - items.add(m_color, m_left); - items.add(m_color, m_right); -} -bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ - ImageStats left_white = image_stats(extract_box_reference(screen, m_left_white)); - if (!is_white(left_white)){ - return false; - } - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); - if (!is_white(bottom)){ - return false; - } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << left.stddev << endl; - if (left.stddev.sum() < 50){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// cout << right.stddev << endl; - if (right.stddev.sum() < 50){ - return false; - } - return true; -} - - - - -ShortDialogPromptDetector::ShortDialogPromptDetector( - VideoOverlay& overlay, - const ImageFloatBox& box, - Color color -) - : VisualInferenceCallback("ShortDialogPromptDetector") - , m_dialog(color) - , m_arrow(overlay, box, color) -{} -void ShortDialogPromptDetector::make_overlays(VideoOverlaySet& items) const{ - m_dialog.make_overlays(items); - m_arrow.make_overlays(items); -} -bool ShortDialogPromptDetector::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - return m_dialog.detect(screen) && m_arrow.process_frame(screen, timestamp); -} - - - - - - - -} -} -} +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_DialogDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ShortDialogDetector::ShortDialogDetector(Color color) + : m_color(color) +// , m_bottom(0.50, 0.91, 0.29, 0.05) + , m_left_white(0.21, 0.835, 0.008, 0.12) + , m_left(0.18, 0.835, 0.02, 0.12) + , m_right_white(0.785, 0.835, 0.008, 0.12) + , m_right(0.822, 0.835, 0.02, 0.12) +{} +void ShortDialogDetector::make_overlays(VideoOverlaySet& items) const{ +// items.add(m_color, m_bottom); + items.add(m_color, m_left_white); + items.add(m_color, m_left); + items.add(m_color, m_right_white); + items.add(m_color, m_right); +} +bool ShortDialogDetector::detect(const ImageViewRGB32& screen){ + ImageStats left_white = image_stats(extract_box_reference(screen, m_left_white)); + if (!is_white(left_white)){ + return false; + } + ImageStats right_white = image_stats(extract_box_reference(screen, m_right_white)); + if (!is_white(right_white)){ + return false; + } +// ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// if (!is_white(bottom)){ +// return false; +// } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << left.stddev << endl; + if (left.stddev.sum() < 30){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// cout << right.stddev << endl; + if (right.stddev.sum() < 30){ + return false; + } + return true; +} + + +ShortDialogWatcher::ShortDialogWatcher(Color color) + : ShortDialogDetector(color) + , VisualInferenceCallback("ShortDialogWatcher") +{} +void ShortDialogWatcher::make_overlays(VideoOverlaySet& items) const{ + ShortDialogDetector::make_overlays(items); +} +bool ShortDialogWatcher::process_frame(const ImageViewRGB32& frame, WallClock){ + return detect(frame); +} + + + + +BattleDialogDetector::BattleDialogDetector(Color color) + : m_color(color) + , m_bottom(0.50, 0.91, 0.40, 0.05) + , m_left_white(0.07, 0.835, 0.008, 0.12) + , m_left(0.04, 0.835, 0.02, 0.12) + , m_right(0.965, 0.835, 0.02, 0.12) +{} +void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + items.add(m_color, m_left_white); + items.add(m_color, m_left); + items.add(m_color, m_right); +} +bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ + ImageStats left_white = image_stats(extract_box_reference(screen, m_left_white)); + if (!is_white(left_white)){ + return false; + } + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); + if (!is_white(bottom)){ + return false; + } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << left.stddev << endl; + if (left.stddev.sum() < 50){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// cout << right.stddev << endl; + if (right.stddev.sum() < 50){ + return false; + } + return true; +} + + + + +ShortDialogPromptDetector::ShortDialogPromptDetector( + VideoOverlay& overlay, + const ImageFloatBox& box, + Color color +) + : VisualInferenceCallback("ShortDialogPromptDetector") + , m_dialog(color) + , m_arrow(overlay, box, color) +{} +void ShortDialogPromptDetector::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + m_arrow.make_overlays(items); +} +bool ShortDialogPromptDetector::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + return m_dialog.detect(screen) && m_arrow.process_frame(screen, timestamp); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h index 06d3e29e40..a5e9df0bf6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h @@ -1,86 +1,86 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BattleDialogDetector_H -#define PokemonAutomation_PokemonBDSP_BattleDialogDetector_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonBDSP_SelectionArrow.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Detect short dialog boxes that are used in all kinds of ingame situations where texts are displayed. -// The only place the long dialog boxes appear is during pokemon battles. But after battle, the exp gain -// text is in a short dialog box. -class ShortDialogDetector : public StaticScreenDetector{ -public: - ShortDialogDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; -// ImageFloatBox m_bottom; - ImageFloatBox m_left_white; - ImageFloatBox m_left; - ImageFloatBox m_right_white; - ImageFloatBox m_right; -}; -class ShortDialogWatcher : public ShortDialogDetector, public VisualInferenceCallback{ -public: - ShortDialogWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - - -// Detect the long dialog boxes that only appear during pokemon battles. -// Note after battle, the exp gain text is in a short dialog box. -class BattleDialogDetector : public StaticScreenDetector{ -public: - BattleDialogDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom; - ImageFloatBox m_left_white; - ImageFloatBox m_left; - ImageFloatBox m_right; -}; - - -class ShortDialogPromptDetector : public VisualInferenceCallback{ -public: - ShortDialogPromptDetector( - VideoOverlay& overlay, - const ImageFloatBox& box, - Color color = COLOR_RED - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ShortDialogDetector m_dialog; - SelectionArrowFinder m_arrow; -}; - - - - -} -} -} -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BattleDialogDetector_H +#define PokemonAutomation_PokemonBDSP_BattleDialogDetector_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonBDSP_SelectionArrow.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Detect short dialog boxes that are used in all kinds of ingame situations where texts are displayed. +// The only place the long dialog boxes appear is during pokemon battles. But after battle, the exp gain +// text is in a short dialog box. +class ShortDialogDetector : public StaticScreenDetector{ +public: + ShortDialogDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; +// ImageFloatBox m_bottom; + ImageFloatBox m_left_white; + ImageFloatBox m_left; + ImageFloatBox m_right_white; + ImageFloatBox m_right; +}; +class ShortDialogWatcher : public ShortDialogDetector, public VisualInferenceCallback{ +public: + ShortDialogWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + + +// Detect the long dialog boxes that only appear during pokemon battles. +// Note after battle, the exp gain text is in a short dialog box. +class BattleDialogDetector : public StaticScreenDetector{ +public: + BattleDialogDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom; + ImageFloatBox m_left_white; + ImageFloatBox m_left; + ImageFloatBox m_right; +}; + + +class ShortDialogPromptDetector : public VisualInferenceCallback{ +public: + ShortDialogPromptDetector( + VideoOverlay& overlay, + const ImageFloatBox& box, + Color color = COLOR_RED + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ShortDialogDetector m_dialog; + SelectionArrowFinder m_arrow; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.cpp index 495d2054bb..01cf4c460c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.cpp @@ -1,69 +1,69 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_MapDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -MapDetector::MapDetector(Color color) - : m_color(color) - , m_box0(0.68, 0.08, 0.06, 0.05) - , m_box1(0.02, 0.97, 0.12, 0.02) - , m_box2(0.88, 0.84, 0.10, 0.04) -{} -void MapDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box0); - items.add(m_color, m_box1); - items.add(m_color, m_box2); -} -bool MapDetector::detect(const ImageViewRGB32& screen){ - ImageStats stats0 = image_stats(extract_box_reference(screen, m_box0)); -// cout << "m_box0: " << stats0.average << stats0.stddev << endl; - if (!is_solid(stats0, {0.0668203, 0.4447, 0.488479})){ - return false; - } - ImageStats stats1 = image_stats(extract_box_reference(screen, m_box1)); -// cout << "m_box1: " << stats1.average << stats1.stddev << endl; - if (!is_solid(stats1, {0.190189, 0.32745, 0.482361})){ - return false; - } - ImageStats stats2 = image_stats(extract_box_reference(screen, m_box2)); -// cout << "m_box2: " << stats2.average << stats2.stddev << endl; - if (!is_solid(stats2, {0.0668203, 0.4447, 0.488479})){ - return false; - } - return true; -} - - - - -MapWatcher::MapWatcher(Color color) - : MapDetector(color) - , VisualInferenceCallback("MapWatcher") -{} -void MapWatcher::make_overlays(VideoOverlaySet& items) const{ - MapDetector::make_overlays(items); -} -bool MapWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - - - -} -} -} +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_MapDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +MapDetector::MapDetector(Color color) + : m_color(color) + , m_box0(0.68, 0.08, 0.06, 0.05) + , m_box1(0.02, 0.97, 0.12, 0.02) + , m_box2(0.88, 0.84, 0.10, 0.04) +{} +void MapDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box0); + items.add(m_color, m_box1); + items.add(m_color, m_box2); +} +bool MapDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats0 = image_stats(extract_box_reference(screen, m_box0)); +// cout << "m_box0: " << stats0.average << stats0.stddev << endl; + if (!is_solid(stats0, {0.0668203, 0.4447, 0.488479})){ + return false; + } + ImageStats stats1 = image_stats(extract_box_reference(screen, m_box1)); +// cout << "m_box1: " << stats1.average << stats1.stddev << endl; + if (!is_solid(stats1, {0.190189, 0.32745, 0.482361})){ + return false; + } + ImageStats stats2 = image_stats(extract_box_reference(screen, m_box2)); +// cout << "m_box2: " << stats2.average << stats2.stddev << endl; + if (!is_solid(stats2, {0.0668203, 0.4447, 0.488479})){ + return false; + } + return true; +} + + + + +MapWatcher::MapWatcher(Color color) + : MapDetector(color) + , VisualInferenceCallback("MapWatcher") +{} +void MapWatcher::make_overlays(VideoOverlaySet& items) const{ + MapDetector::make_overlays(items); +} +bool MapWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h index 19d0ae7a14..c65b24fd84 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MapDetector.h @@ -1,49 +1,49 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_MapDetector_H -#define PokemonAutomation_PokemonBDSP_MapDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class MapDetector : public StaticScreenDetector{ -public: - MapDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box0; - ImageFloatBox m_box1; - ImageFloatBox m_box2; -}; - - -class MapWatcher : public MapDetector, public VisualInferenceCallback{ -public: - MapWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - - - -} -} -} -#endif +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_MapDetector_H +#define PokemonAutomation_PokemonBDSP_MapDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class MapDetector : public StaticScreenDetector{ +public: + MapDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box0; + ImageFloatBox m_box1; + ImageFloatBox m_box2; +}; + + +class MapWatcher : public MapDetector, public VisualInferenceCallback{ +public: + MapWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp index 16b6da94ed..2ce50b0d3b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.cpp @@ -1,96 +1,96 @@ -/* Mark Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "PokemonBDSP_MarkFinder.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const ImageMatch::ExactImageMatcher& EXCLAMATION_MARK(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonBDSP/ExclamationMark-WhiteFill.png"); - return matcher; -} - - -bool is_exclamation_mark(const ImageViewRGB32& image, const WaterfillObject& object){ - size_t width = object.width(); - size_t height = object.height(); - if (width > 2 * height){ - return false; - } - if (height > 2 * width){ - return false; - } - - ImageViewRGB32 obj = extract_box_reference(image, object); - double rmsd = EXCLAMATION_MARK().rmsd(obj); -// double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= 80; -} - - -std::vector find_exclamation_marks(const ImageViewRGB32& image){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_min(image, 200, 200, 200); - std::vector objects = find_objects_inplace(matrix, 400); - std::vector ret; - for (const WaterfillObject& object : objects){ - if (is_exclamation_mark(image, object)){ - ret.emplace_back( - ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) - ); - } - } - return ret; -} - - - -MarkTracker::MarkTracker(VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("MarkTracker") - , m_overlay(overlay) - , m_box(box) -{} - -void MarkTracker::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool MarkTracker::process_frame(const ImageViewRGB32& frame, WallClock){ - std::vector exclamation_marks = find_exclamation_marks(extract_box_reference(frame, m_box)); -// cout << exclamation_marks.size() << endl; - - m_marks.clear(); - for (const ImagePixelBox& mark : exclamation_marks){ - m_marks.emplace_back(m_overlay, translate_to_parent(frame, m_box, mark), COLOR_MAGENTA); - } - return false; -} - -bool MarkDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - MarkTracker::process_frame(frame, timestamp); - return !m_marks.empty(); -} - - - - -} -} -} +/* Mark Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "PokemonBDSP_MarkFinder.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const ImageMatch::ExactImageMatcher& EXCLAMATION_MARK(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonBDSP/ExclamationMark-WhiteFill.png"); + return matcher; +} + + +bool is_exclamation_mark(const ImageViewRGB32& image, const WaterfillObject& object){ + size_t width = object.width(); + size_t height = object.height(); + if (width > 2 * height){ + return false; + } + if (height > 2 * width){ + return false; + } + + ImageViewRGB32 obj = extract_box_reference(image, object); + double rmsd = EXCLAMATION_MARK().rmsd(obj); +// double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= 80; +} + + +std::vector find_exclamation_marks(const ImageViewRGB32& image){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_min(image, 200, 200, 200); + std::vector objects = find_objects_inplace(matrix, 400); + std::vector ret; + for (const WaterfillObject& object : objects){ + if (is_exclamation_mark(image, object)){ + ret.emplace_back( + ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) + ); + } + } + return ret; +} + + + +MarkTracker::MarkTracker(VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("MarkTracker") + , m_overlay(overlay) + , m_box(box) +{} + +void MarkTracker::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool MarkTracker::process_frame(const ImageViewRGB32& frame, WallClock){ + std::vector exclamation_marks = find_exclamation_marks(extract_box_reference(frame, m_box)); +// cout << exclamation_marks.size() << endl; + + m_marks.clear(); + for (const ImagePixelBox& mark : exclamation_marks){ + m_marks.emplace_back(m_overlay, translate_to_parent(frame, m_box, mark), COLOR_MAGENTA); + } + return false; +} + +bool MarkDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + MarkTracker::process_frame(frame, timestamp); + return !m_marks.empty(); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h index f40d6dfa4a..5fe58bf2a9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h @@ -1,51 +1,51 @@ -/* Mark Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_MarkFinder_H -#define PokemonAutomation_PokemonBDSP_MarkFinder_H - -#include -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class VideoOverlay; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -std::vector find_exclamation_marks(const ImageViewRGB32& image); - - - -class MarkTracker : public VisualInferenceCallback{ -public: - MarkTracker(VideoOverlay& overlay, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -protected: - VideoOverlay& m_overlay; - ImageFloatBox m_box; - std::deque m_marks; -}; - -class MarkDetector : public MarkTracker{ -public: - using MarkTracker::MarkTracker; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - - -} -} -} -#endif +/* Mark Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_MarkFinder_H +#define PokemonAutomation_PokemonBDSP_MarkFinder_H + +#include +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class VideoOverlay; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +std::vector find_exclamation_marks(const ImageViewRGB32& image); + + + +class MarkTracker : public VisualInferenceCallback{ +public: + MarkTracker(VideoOverlay& overlay, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +protected: + VideoOverlay& m_overlay; + ImageFloatBox m_box; + std::deque m_marks; +}; + +class MarkDetector : public MarkTracker{ +public: + using MarkTracker::MarkTracker; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp index 7133bfc814..ae200be06a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.cpp @@ -1,81 +1,81 @@ -/* Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_MenuDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -MenuDetector::MenuDetector(Color color) - : m_color(color) - , m_line0(0.160 + 0.166 * 0, 0.110, 0.015, 0.488) - , m_line1(0.160 + 0.166 * 1, 0.110, 0.015, 0.488) - , m_line2(0.160 + 0.166 * 2, 0.110, 0.015, 0.488) - , m_line3(0.160 + 0.166 * 3, 0.110, 0.015, 0.488) - , m_line4(0.160 + 0.166 * 4, 0.110, 0.015, 0.488) - , m_cross(0.20, 0.15, 0.60, 0.37) -{} - -void MenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_line0); - items.add(m_color, m_line1); - items.add(m_color, m_line2); - items.add(m_color, m_line3); - items.add(m_color, m_line4); - items.add(m_color, m_cross); -} -bool MenuDetector::detect(const ImageViewRGB32& screen){ - ImageStats stats0 = image_stats(extract_box_reference(screen, m_line0)); - if (!is_white(stats0)){ - return false; - } - ImageStats stats1 = image_stats(extract_box_reference(screen, m_line1)); - if (!is_white(stats1)){ - return false; - } - ImageStats stats2 = image_stats(extract_box_reference(screen, m_line2)); - if (!is_white(stats2)){ - return false; - } - ImageStats stats3 = image_stats(extract_box_reference(screen, m_line3)); - if (!is_white(stats3)){ - return false; - } - ImageStats stats4 = image_stats(extract_box_reference(screen, m_line4)); - if (!is_white(stats4)){ - return false; - } - ImageStats cross = image_stats(extract_box_reference(screen, m_cross)); -// cout << cross.average << cross.stddev << endl; - if (cross.stddev.sum() < 100){ - return false; - } - return true; -} - - -MenuWatcher::MenuWatcher(Color color) - : MenuDetector(color) - , VisualInferenceCallback("MenuWatcher") -{} -void MenuWatcher::make_overlays(VideoOverlaySet& items) const{ - MenuDetector::make_overlays(items); -} -bool MenuWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - - - -} -} -} +/* Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_MenuDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +MenuDetector::MenuDetector(Color color) + : m_color(color) + , m_line0(0.160 + 0.166 * 0, 0.110, 0.015, 0.488) + , m_line1(0.160 + 0.166 * 1, 0.110, 0.015, 0.488) + , m_line2(0.160 + 0.166 * 2, 0.110, 0.015, 0.488) + , m_line3(0.160 + 0.166 * 3, 0.110, 0.015, 0.488) + , m_line4(0.160 + 0.166 * 4, 0.110, 0.015, 0.488) + , m_cross(0.20, 0.15, 0.60, 0.37) +{} + +void MenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_line0); + items.add(m_color, m_line1); + items.add(m_color, m_line2); + items.add(m_color, m_line3); + items.add(m_color, m_line4); + items.add(m_color, m_cross); +} +bool MenuDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats0 = image_stats(extract_box_reference(screen, m_line0)); + if (!is_white(stats0)){ + return false; + } + ImageStats stats1 = image_stats(extract_box_reference(screen, m_line1)); + if (!is_white(stats1)){ + return false; + } + ImageStats stats2 = image_stats(extract_box_reference(screen, m_line2)); + if (!is_white(stats2)){ + return false; + } + ImageStats stats3 = image_stats(extract_box_reference(screen, m_line3)); + if (!is_white(stats3)){ + return false; + } + ImageStats stats4 = image_stats(extract_box_reference(screen, m_line4)); + if (!is_white(stats4)){ + return false; + } + ImageStats cross = image_stats(extract_box_reference(screen, m_cross)); +// cout << cross.average << cross.stddev << endl; + if (cross.stddev.sum() < 100){ + return false; + } + return true; +} + + +MenuWatcher::MenuWatcher(Color color) + : MenuDetector(color) + , VisualInferenceCallback("MenuWatcher") +{} +void MenuWatcher::make_overlays(VideoOverlaySet& items) const{ + MenuDetector::make_overlays(items); +} +bool MenuWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h index ed06ac9b37..6a4c992e57 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h @@ -1,52 +1,52 @@ -/* Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_MenuDetector_H -#define PokemonAutomation_PokemonBDSP_MenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class MenuDetector : public StaticScreenDetector{ -public: - MenuDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_line0; - ImageFloatBox m_line1; - ImageFloatBox m_line2; - ImageFloatBox m_line3; - ImageFloatBox m_line4; - ImageFloatBox m_cross; -}; - - -class MenuWatcher : public MenuDetector, public VisualInferenceCallback{ -public: - MenuWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - - - -} -} -} -#endif +/* Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_MenuDetector_H +#define PokemonAutomation_PokemonBDSP_MenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class MenuDetector : public StaticScreenDetector{ +public: + MenuDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_line0; + ImageFloatBox m_line1; + ImageFloatBox m_line2; + ImageFloatBox m_line3; + ImageFloatBox m_line4; + ImageFloatBox m_cross; +}; + + +class MenuWatcher : public MenuDetector, public VisualInferenceCallback{ +public: + MenuWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp index 3e405bda89..77363d7c84 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.cpp @@ -1,48 +1,48 @@ -/* Pokeball Sprite Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" -#include "PokemonBDSP_PokeballSpriteMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -PokeballSpriteMatcher::PokeballSpriteMatcher(double min_euclidean_distance) - : CroppedImageDictionaryMatcher({1, 128}) - , m_min_euclidean_distance_squared(min_euclidean_distance * min_euclidean_distance) -{ - for (const auto& item : PokemonSwSh::ALL_POKEBALL_SPRITES()){ - add(item.first, item.second.sprite); - } -} - - -auto PokeballSpriteMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ - ImageStats border = image_border_stats(image); - ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( - image, - [&](Color pixel){ - double r = (double)pixel.red() - border.average.r; - double g = (double)pixel.green() - border.average.g; - double b = (double)pixel.blue() - border.average.b; - bool stop = r*r + g*g + b*b >= m_min_euclidean_distance_squared; - return stop; - } - ); - std::vector ret; - ret.emplace_back(extract_box_reference(image, box)); - return ret; -} - - - -} -} -} +/* Pokeball Sprite Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" +#include "PokemonBDSP_PokeballSpriteMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +PokeballSpriteMatcher::PokeballSpriteMatcher(double min_euclidean_distance) + : CroppedImageDictionaryMatcher({1, 128}) + , m_min_euclidean_distance_squared(min_euclidean_distance * min_euclidean_distance) +{ + for (const auto& item : PokemonSwSh::ALL_POKEBALL_SPRITES()){ + add(item.first, item.second.sprite); + } +} + + +auto PokeballSpriteMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ + ImageStats border = image_border_stats(image); + ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + image, + [&](Color pixel){ + double r = (double)pixel.red() - border.average.r; + double g = (double)pixel.green() - border.average.g; + double b = (double)pixel.blue() - border.average.b; + bool stop = r*r + g*g + b*b >= m_min_euclidean_distance_squared; + return stop; + } + ); + std::vector ret; + ret.emplace_back(extract_box_reference(image, box)); + return ret; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h index 0c43852939..6fa357e73c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h @@ -1,33 +1,33 @@ -/* Pokeball Sprite Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_PokeballSpriteReader_H -#define PokemonAutomation_PokemonBDSP_PokeballSpriteReader_H - -#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class PokeballSpriteMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ -public: - PokeballSpriteMatcher(double min_euclidean_distance = 100); - -private: - virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; - -private: - double m_min_euclidean_distance_squared; -}; - - - -} -} -} -#endif +/* Pokeball Sprite Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_PokeballSpriteReader_H +#define PokemonAutomation_PokemonBDSP_PokeballSpriteReader_H + +#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class PokeballSpriteMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ +public: + PokeballSpriteMatcher(double min_euclidean_distance = 100); + +private: + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; + +private: + double m_min_euclidean_distance_squared; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.cpp index 9fe7bf7a0b..114b50bd61 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.cpp @@ -1,48 +1,48 @@ -/* Receive Pokemon (Blue Background) Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonBDSP_ReceivePokemonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -ReceivePokemonDetector::ReceivePokemonDetector(Color color) - : VisualInferenceCallback("ReceivePokemonDetector") - , m_color(color) - , m_box0(0.05, 0.10, 0.10, 0.80) - , m_box1(0.87, 0.10, 0.10, 0.80) -{} - - -void ReceivePokemonDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box0); - items.add(m_color, m_box1); -} - -bool ReceivePokemonDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const ImageStats stats0 = image_stats(extract_box_reference(frame, m_box0)); - if (stats0.average.sum() < 100 || !is_solid(stats0, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ - return m_received; - } - const ImageStats stats1 = image_stats(extract_box_reference(frame, m_box1)); - if (stats1.average.sum() < 100 || !is_solid(stats1, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ - return m_received; - } - m_received = true; -// static int c = 0; -// frame.save("test-" + std::to_string(c++) + ".png"); - return false; -} - - -} -} -} +/* Receive Pokemon (Blue Background) Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonBDSP_ReceivePokemonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +ReceivePokemonDetector::ReceivePokemonDetector(Color color) + : VisualInferenceCallback("ReceivePokemonDetector") + , m_color(color) + , m_box0(0.05, 0.10, 0.10, 0.80) + , m_box1(0.87, 0.10, 0.10, 0.80) +{} + + +void ReceivePokemonDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box0); + items.add(m_color, m_box1); +} + +bool ReceivePokemonDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const ImageStats stats0 = image_stats(extract_box_reference(frame, m_box0)); + if (stats0.average.sum() < 100 || !is_solid(stats0, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ + return m_received; + } + const ImageStats stats1 = image_stats(extract_box_reference(frame, m_box1)); + if (stats1.average.sum() < 100 || !is_solid(stats1, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ + return m_received; + } + m_received = true; +// static int c = 0; +// frame.save("test-" + std::to_string(c++) + ".png"); + return false; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h index f2f69631d4..20e500aa4b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h @@ -1,46 +1,46 @@ -/* Receive Pokemon (Blue Background) Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Returns true after the background of receiving a pokemon - * has been detected and has ended. - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ReceivePokemonDetector_H -#define PokemonAutomation_PokemonBDSP_ReceivePokemonDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Detect the end of receiving a pokemon or an egg. -class ReceivePokemonDetector : public VisualInferenceCallback{ -public: - ReceivePokemonDetector(Color color = COLOR_RED); - - // Whether a receive event happened or is happening. - bool received() const { return m_received; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true only when a receiving event happened and ended. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_received = false; - Color m_color; - ImageFloatBox m_box0; - ImageFloatBox m_box1; -}; - - - -} -} -} -#endif +/* Receive Pokemon (Blue Background) Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Returns true after the background of receiving a pokemon + * has been detected and has ended. + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ReceivePokemonDetector_H +#define PokemonAutomation_PokemonBDSP_ReceivePokemonDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Detect the end of receiving a pokemon or an egg. +class ReceivePokemonDetector : public VisualInferenceCallback{ +public: + ReceivePokemonDetector(Color color = COLOR_RED); + + // Whether a receive event happened or is happening. + bool received() const { return m_received; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true only when a receiving event happened and ended. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_received = false; + Color m_color; + ImageFloatBox m_box0; + ImageFloatBox m_box1; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.cpp index 24b613df7e..f29b4e44d2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.cpp @@ -1,126 +1,126 @@ -/* Selection Arrow - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonBDSP_SelectionArrow.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const ImageMatch::ExactImageMatcher& SELECTION_ARROW(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonBDSP/SelectionArrow.png"); - return matcher; -} - - -bool is_selection_arrow(const ImageViewRGB32& image, const WaterfillObject& object){ - size_t width = object.width(); - size_t height = object.height(); - if (width > height){ - return false; - } - if (height > 3 * width){ - return false; - } - - ImageViewRGB32 cropped = extract_box_reference(image, object); - -// static int c = 0; -// scaled.save("test-" + std::to_string(c++) + ".png"); - - double rmsd = SELECTION_ARROW().rmsd(cropped); - -// scaled = scaled.scaled(exclamation_mark.width(), exclamation_mark.height()); -// double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= 90; -} - - -std::vector find_selection_arrows(const ImageViewRGB32& image){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_max(image, 200, 200, 200); - std::vector objects = find_objects_inplace(matrix, 200); - std::vector ret; - for (const WaterfillObject& object : objects){ - if (is_selection_arrow(image, object)){ - ret.emplace_back( - ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) - ); - } - } - return ret; -} - - - - -SelectionArrowFinder::SelectionArrowFinder( - VideoOverlay& overlay, - const ImageFloatBox& box, - Color color -) - : VisualInferenceCallback("SelectionArrowFinder") - , m_overlay(overlay) - , m_color(color) - , m_box(box) -{} - -bool SelectionArrowFinder::detect(const ImageViewRGB32& screen){ - std::vector arrows = find_selection_arrows(extract_box_reference(screen, m_box)); - - m_arrow_boxes.clear(); - for (const ImagePixelBox& mark : arrows){ - m_arrow_boxes.emplace_back(m_overlay, translate_to_parent(screen, m_box, mark), COLOR_MAGENTA); - } - - return !m_arrow_boxes.empty(); -} -void SelectionArrowFinder::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool SelectionArrowFinder::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - detect(frame); -// cout << m_arrow_boxes.size() << endl; -// if (!m_arrow_boxes.empty()){ -// extract_box(frame, m_arrow_boxes[0]).save("temp.png"); -// frame.save("test.png"); -// } -// return !m_arrow_boxes.empty(); - - // Need 5 consecutive successful detections. - if (m_arrow_boxes.empty()){ - m_trigger_count = 0; - return false; - } - m_trigger_count++; - return m_trigger_count >= 5; -} - - - - - - - - - -} -} -} +/* Selection Arrow + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonBDSP_SelectionArrow.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const ImageMatch::ExactImageMatcher& SELECTION_ARROW(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonBDSP/SelectionArrow.png"); + return matcher; +} + + +bool is_selection_arrow(const ImageViewRGB32& image, const WaterfillObject& object){ + size_t width = object.width(); + size_t height = object.height(); + if (width > height){ + return false; + } + if (height > 3 * width){ + return false; + } + + ImageViewRGB32 cropped = extract_box_reference(image, object); + +// static int c = 0; +// scaled.save("test-" + std::to_string(c++) + ".png"); + + double rmsd = SELECTION_ARROW().rmsd(cropped); + +// scaled = scaled.scaled(exclamation_mark.width(), exclamation_mark.height()); +// double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= 90; +} + + +std::vector find_selection_arrows(const ImageViewRGB32& image){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_max(image, 200, 200, 200); + std::vector objects = find_objects_inplace(matrix, 200); + std::vector ret; + for (const WaterfillObject& object : objects){ + if (is_selection_arrow(image, object)){ + ret.emplace_back( + ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) + ); + } + } + return ret; +} + + + + +SelectionArrowFinder::SelectionArrowFinder( + VideoOverlay& overlay, + const ImageFloatBox& box, + Color color +) + : VisualInferenceCallback("SelectionArrowFinder") + , m_overlay(overlay) + , m_color(color) + , m_box(box) +{} + +bool SelectionArrowFinder::detect(const ImageViewRGB32& screen){ + std::vector arrows = find_selection_arrows(extract_box_reference(screen, m_box)); + + m_arrow_boxes.clear(); + for (const ImagePixelBox& mark : arrows){ + m_arrow_boxes.emplace_back(m_overlay, translate_to_parent(screen, m_box, mark), COLOR_MAGENTA); + } + + return !m_arrow_boxes.empty(); +} +void SelectionArrowFinder::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool SelectionArrowFinder::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + detect(frame); +// cout << m_arrow_boxes.size() << endl; +// if (!m_arrow_boxes.empty()){ +// extract_box(frame, m_arrow_boxes[0]).save("temp.png"); +// frame.save("test.png"); +// } +// return !m_arrow_boxes.empty(); + + // Need 5 consecutive successful detections. + if (m_arrow_boxes.empty()){ + m_trigger_count = 0; + return false; + } + m_trigger_count++; + return m_trigger_count >= 5; +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h index b8d7347339..059a57a51d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h @@ -1,47 +1,47 @@ -/* Selection Arrow - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_SelectionArrow_H -#define PokemonAutomation_PokemonBDSP_SelectionArrow_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class SelectionArrowFinder : public VisualInferenceCallback{ -public: - SelectionArrowFinder( - VideoOverlay& overlay, - const ImageFloatBox& box, - Color color - ); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -protected: - VideoOverlay& m_overlay; - Color m_color; - ImageFloatBox m_box; - std::deque m_arrow_boxes; - -private: - size_t m_trigger_count = 0; -}; - - - -} -} -} -#endif +/* Selection Arrow + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_SelectionArrow_H +#define PokemonAutomation_PokemonBDSP_SelectionArrow_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class SelectionArrowFinder : public VisualInferenceCallback{ +public: + SelectionArrowFinder( + VideoOverlay& overlay, + const ImageFloatBox& box, + Color color + ); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +protected: + VideoOverlay& m_overlay; + Color m_color; + ImageFloatBox m_box; + std::deque m_arrow_boxes; + +private: + size_t m_trigger_count = 0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.cpp index 9308c541c0..9b202e46ba 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.cpp @@ -1,93 +1,93 @@ -/* VS Seeker Reaction Bubble - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonBDSP_VSSeekerReaction.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const ImageViewRGB32& VS_SEEKER_REACTION_BUBBLE(){ - static ImageRGB32 image(RESOURCE_PATH() + "PokemonBDSP/VSSeekerReactBuble-WhiteFill.png"); - return image; -} - -bool is_seeker_bubble(const ImageViewRGB32& image, const WaterfillObject& object){ - size_t width = object.width(); - size_t height = object.height(); - if (width > 2 * height){ - return false; - } - if (height > 2 * width){ - return false; - } - - const ImageViewRGB32& exclamation_mark = VS_SEEKER_REACTION_BUBBLE(); - ImageRGB32 scaled = extract_box_reference(image, object).scale_to(exclamation_mark.width(), exclamation_mark.height()); - double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= 80; -} - -std::vector find_seeker_bubbles(const ImageViewRGB32& image){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_min(image, 200, 200, 200); - std::vector objects = find_objects_inplace(matrix, 400); - std::vector ret; - for (const WaterfillObject& object : objects){ - if (is_seeker_bubble(image, object)){ - ret.emplace_back( - ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) - ); - } - } - return ret; -} - - - -VSSeekerReactionTracker::VSSeekerReactionTracker(VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("VSSeekerReactionTracker") - , m_overlay(overlay) - , m_box(box) -{} -void VSSeekerReactionTracker::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool VSSeekerReactionTracker::process_frame(const ImageViewRGB32& frame, WallClock){ - ImageViewRGB32 cropped = extract_box_reference(frame, m_box); - m_dimensions = QSize((int)cropped.width(), (int)cropped.height()); - m_bubbles = find_seeker_bubbles(cropped); -// cout << exclamation_marks.size() << endl; - - m_boxes.clear(); - for (const ImagePixelBox& mark : m_bubbles){ - m_boxes.emplace_back(m_overlay, translate_to_parent(frame, m_box, mark), COLOR_MAGENTA); - } - return false; -} - - - - - - -} -} -} +/* VS Seeker Reaction Bubble + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonBDSP_VSSeekerReaction.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const ImageViewRGB32& VS_SEEKER_REACTION_BUBBLE(){ + static ImageRGB32 image(RESOURCE_PATH() + "PokemonBDSP/VSSeekerReactBuble-WhiteFill.png"); + return image; +} + +bool is_seeker_bubble(const ImageViewRGB32& image, const WaterfillObject& object){ + size_t width = object.width(); + size_t height = object.height(); + if (width > 2 * height){ + return false; + } + if (height > 2 * width){ + return false; + } + + const ImageViewRGB32& exclamation_mark = VS_SEEKER_REACTION_BUBBLE(); + ImageRGB32 scaled = extract_box_reference(image, object).scale_to(exclamation_mark.width(), exclamation_mark.height()); + double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= 80; +} + +std::vector find_seeker_bubbles(const ImageViewRGB32& image){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_min(image, 200, 200, 200); + std::vector objects = find_objects_inplace(matrix, 400); + std::vector ret; + for (const WaterfillObject& object : objects){ + if (is_seeker_bubble(image, object)){ + ret.emplace_back( + ImagePixelBox(object.min_x, object.min_y, object.max_x, object.max_y) + ); + } + } + return ret; +} + + + +VSSeekerReactionTracker::VSSeekerReactionTracker(VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("VSSeekerReactionTracker") + , m_overlay(overlay) + , m_box(box) +{} +void VSSeekerReactionTracker::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool VSSeekerReactionTracker::process_frame(const ImageViewRGB32& frame, WallClock){ + ImageViewRGB32 cropped = extract_box_reference(frame, m_box); + m_dimensions = QSize((int)cropped.width(), (int)cropped.height()); + m_bubbles = find_seeker_bubbles(cropped); +// cout << exclamation_marks.size() << endl; + + m_boxes.clear(); + for (const ImagePixelBox& mark : m_bubbles){ + m_boxes.emplace_back(m_overlay, translate_to_parent(frame, m_box, mark), COLOR_MAGENTA); + } + return false; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h index 6d9957f031..e034eade93 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h @@ -1,50 +1,50 @@ -/* VS Seeker Reaction Bubble - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BSSeekerReactionBubble_H -#define PokemonAutomation_PokemonBDSP_BSSeekerReactionBubble_H - -#include -#include -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -std::vector find_seeker_bubbles(const ImageViewRGB32& image); - - - -class VSSeekerReactionTracker : public VisualInferenceCallback{ -public: - VSSeekerReactionTracker(VideoOverlay& overlay, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - QSize dimensions() const{ return m_dimensions; } - const std::vector& reactions() const{ return m_bubbles; } - -protected: - VideoOverlay& m_overlay; - ImageFloatBox m_box; - QSize m_dimensions; - std::vector m_bubbles; - std::deque m_boxes; -}; - - - - -} -} -} -#endif +/* VS Seeker Reaction Bubble + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BSSeekerReactionBubble_H +#define PokemonAutomation_PokemonBDSP_BSSeekerReactionBubble_H + +#include +#include +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +std::vector find_seeker_bubbles(const ImageViewRGB32& image); + + + +class VSSeekerReactionTracker : public VisualInferenceCallback{ +public: + VSSeekerReactionTracker(VideoOverlay& overlay, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + QSize dimensions() const{ return m_dimensions; } + const std::vector& reactions() const{ return m_bubbles; } + +protected: + VideoOverlay& m_overlay; + ImageFloatBox m_box; + QSize m_dimensions; + std::vector m_bubbles; + std::deque m_boxes; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.cpp index fd22b3f29e..11c570d3ea 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.cpp @@ -1,331 +1,331 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h" -#include "PokemonBDSP_ShinyEncounterDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -const std::chrono::milliseconds SHINY_ANIMATION_DELAY(3900); - -const DetectionType WILD_POKEMON{ - {0.4, 0.02, 0.60, 0.93}, - PokemonSwSh::EncounterState::WILD_ANIMATION, - std::chrono::milliseconds(3900), - true, -}; -const DetectionType YOUR_POKEMON{ - {0.0, 0.1, 0.8, 0.8}, - PokemonSwSh::EncounterState::YOUR_ANIMATION, - std::chrono::milliseconds(3900), - false, -}; - - - -ShinyEncounterTracker::ShinyEncounterTracker( - Logger& logger, VideoOverlay& overlay, - BattleType battle_type -) - : VisualInferenceCallback("ShinyEncounterTracker") - , m_logger(logger) -// , m_overlay(overlay) - , m_battle_menu(battle_type) - , m_dialog_tracker(logger, m_dialog_detector) - , m_wild_animation_end_timestamp(WallClock::min()) - , m_your_animation_start_timestamp(WallClock::min()) - , m_box_wild_left(0.40, 0.02, 0.20, 0.48) - , m_box_wild_right(0.70, 0.02, 0.20, 0.48) - , m_sparkle_tracker_wild(logger, overlay, m_sparkles_wild, {0.4, 0.02, 0.60, 0.93}) - , m_sparkle_tracker_own(logger, overlay, m_sparkles_own, {0.0, 0.1, 0.8, 0.8}) -{} -void ShinyEncounterTracker::make_overlays(VideoOverlaySet& items) const{ - m_battle_menu.make_overlays(items); - m_dialog_tracker.make_overlays(items); - items.add(COLOR_RED, m_box_wild_left); - items.add(COLOR_RED, m_box_wild_right); - m_sparkle_tracker_wild.make_overlays(items); - m_sparkle_tracker_own.make_overlays(items); -} -bool ShinyEncounterTracker::process_frame(const VideoSnapshot& frame){ - using PokemonSwSh::EncounterState; - - if (!frame){ - return false; - } - - size_t width = frame->width(); - size_t height = frame->height(); - - if (height < 720){ - throw UserSetupError(m_logger, "Video resolution must be at least 720p."); - } - double aspect_ratio = (double)width / height; - if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ - throw UserSetupError(m_logger, "Video aspect ratio must be 16:9."); - } - - // End shiny detection when we reach the battle menu - bool battle_menu = m_battle_menu.process_frame(frame); - if (battle_menu){ - m_dialog_tracker.push_end(frame.timestamp); - return true; - } - - // Use m_dialog_tracker to track dialog timings. Dialogs partitions the opening of a battle into: - // before anything -> wild pokemon animation -> player pokemon animation -> battle menu detected - m_dialog_tracker.process_frame(frame); - - switch (m_dialog_tracker.encounter_state()){ - case EncounterState::BEFORE_ANYTHING: - break; - case EncounterState::WILD_ANIMATION:{ - // Update the timestamp that records the end of wild animation - m_wild_animation_end_timestamp = frame.timestamp; - - m_sparkle_tracker_wild.process_frame(frame); - m_sparkle_tracker_own.clear_boxes(); - m_best_wild_overall.add_frame(frame.frame, m_sparkles_wild); - - ImagePixelBox box_overall = floatbox_to_pixelbox(width, height, {0.4, 0.02, 0.60, 0.93}); - ImagePixelBox box_left = floatbox_to_pixelbox(width, height, m_box_wild_left); - ImagePixelBox box_right = floatbox_to_pixelbox(width, height, m_box_wild_right); - box_left.clip(box_overall); - box_right.clip(box_overall); - box_left.min_x -= box_overall.min_x; - box_left.min_y -= box_overall.min_y; - box_left.max_x -= box_overall.min_x; - box_left.max_y -= box_overall.min_y; - box_right.min_x -= box_overall.min_x; - box_right.min_y -= box_overall.min_y; - box_right.max_x -= box_overall.min_x; - box_right.max_y -= box_overall.min_y; - - m_best_wild_left.add_frame(nullptr, m_sparkles_wild.extract_subbox(box_left)); - m_best_wild_right.add_frame(nullptr, m_sparkles_wild.extract_subbox(box_right)); - break; - } - case EncounterState::YOUR_ANIMATION: - // Update the timestamp that records the start of player pokemon animation - if (m_your_animation_start_timestamp == WallClock::min()){ - m_your_animation_start_timestamp = frame.timestamp; - } - - m_sparkle_tracker_wild.clear_boxes(); - m_sparkle_tracker_own.process_frame(frame); - m_best_own.add_frame(frame.frame, m_sparkles_own); - break; - case EncounterState::POST_ENTRY: - break; - } - - return false; -} - -void determine_shiny_status( - ProgramEnvironment& env, - DoublesShinyDetection& wild_result, - ShinyDetectionResult& your_result, - EventNotificationOption& settings, - BattleType battle_type, - const ShinyEncounterTracker& tracker, - const std::vector& shiny_sound_timestamps -){ - const double OVERALL_THRESHOLD = GameSettings::instance().SHINY_ALPHA_OVERALL_THRESHOLD; - const double DOUBLES_THRESHOLD = GameSettings::instance().SHINY_ALPHA_SIDE_THRESHOLD; - const double DIALOG_ALPHA = GameSettings::instance().SHINY_DIALOG_ALPHA; - const double SOUND_ALPHA = GameSettings::instance().SHINY_SOUND_ALPHA; - - const PokemonSwSh::EncounterDialogTracker& dialog_tracker = tracker.dialog_tracker(); - const ShinySparkleAggregator& sparkles_wild_overall = tracker.sparkles_wild_overall(); - const ShinySparkleAggregator& sparkles_wild_left = tracker.sparkles_wild_left(); - const ShinySparkleAggregator& sparkles_wild_right = tracker.sparkles_wild_right(); - const ShinySparkleAggregator& sparkles_own = tracker.sparkles_own(); - - double alpha_wild_overall = sparkles_wild_overall.best_overall(); - double alpha_wild_left = sparkles_wild_left.best_overall(); - double alpha_wild_right = sparkles_wild_right.best_overall(); - double alpha_own = sparkles_own.best_overall(); - - { - std::chrono::milliseconds dialog_duration = dialog_tracker.wild_animation_duration(); - std::chrono::milliseconds min_delay = SHINY_ANIMATION_DELAY - std::chrono::milliseconds(300); - std::chrono::milliseconds max_delay = SHINY_ANIMATION_DELAY + std::chrono::milliseconds(500); - if (min_delay <= dialog_duration && dialog_duration <= max_delay){ - alpha_wild_overall += DIALOG_ALPHA; - } - } - -#if 0 - cout << "Wild End: " << std::chrono::duration_cast(tracker.wild_animation_end_timestmap() - tracker.m_start_time) << endl; - cout << "Your Start: " << std::chrono::duration_cast(tracker.your_animation_start_timestamp() - tracker.m_start_time) << endl; - for (WallClock time : shiny_sound_timestamps){ - cout << "Shiny Sound: " << std::chrono::duration_cast(time - tracker.m_start_time) << endl; - } -#endif - - bool wild_shiny_sound_detected = false; - bool own_shiny_sound_detected = false; - for (const WallClock& timestamp: shiny_sound_timestamps){ - const WallClock& wild_end = tracker.wild_animation_end_timestmap(); - const WallClock& own_start = tracker.your_animation_start_timestamp(); - - bool wild_shiny = timestamp < wild_end + Milliseconds(500); - bool own_shiny = timestamp >= own_start; - - wild_shiny_sound_detected |= wild_shiny; - own_shiny_sound_detected |= own_shiny; - if (!wild_shiny && !own_shiny){ - throw_and_log( - env.logger(), ErrorReport::SEND_ERROR_REPORT, - "Wrong shiny sound timing found." - ); - } - } - alpha_wild_overall += wild_shiny_sound_detected ? SOUND_ALPHA : 0.0; - alpha_own += own_shiny_sound_detected ? SOUND_ALPHA : 0.0; - - if (battle_type == BattleType::STARTER){ - std::chrono::milliseconds dialog_duration = dialog_tracker.your_animation_duration(); - std::chrono::milliseconds min_delay = SHINY_ANIMATION_DELAY - std::chrono::milliseconds(300); - std::chrono::milliseconds max_delay = SHINY_ANIMATION_DELAY + std::chrono::milliseconds(2000); // Add headroom for happiness. - if (min_delay <= dialog_duration && dialog_duration <= max_delay){ - alpha_own += DIALOG_ALPHA; - } - } - env.log( - "ShinyDetector: Wild Alpha = " + tostr_default(alpha_wild_overall) + - (wild_shiny_sound_detected ? " (shiny sound detected)" : "") + - ", Left Alpha = " + tostr_default(alpha_wild_left) + - ", Right Alpha = " + tostr_default(alpha_wild_right) + - ", Your Alpha = " + tostr_default(alpha_own) + - (own_shiny_sound_detected ? " (shiny sound detected)" : ""), - COLOR_PURPLE - ); - - wild_result.shiny_type = ShinyType::UNKNOWN; - wild_result.alpha = alpha_wild_overall; - wild_result.left_is_shiny = false; - wild_result.right_is_shiny = false; - - if (alpha_wild_overall < OVERALL_THRESHOLD){ - env.log("ShinyDetector: Wild not Shiny.", COLOR_PURPLE); - wild_result.shiny_type = ShinyType::NOT_SHINY; - }else{ - env.log("ShinyDetector: Detected Wild Shiny!", COLOR_BLUE); - wild_result.shiny_type = ShinyType::UNKNOWN_SHINY; - wild_result.left_is_shiny = alpha_wild_left >= DOUBLES_THRESHOLD; - wild_result.right_is_shiny = alpha_wild_right >= DOUBLES_THRESHOLD; - } - - if (DIALOG_ALPHA <= alpha_wild_overall && alpha_wild_overall < DIALOG_ALPHA + 1.5){ - dump_image(env.logger(), env.program_info(), "LowShinyAlpha", wild_result.get_best_screenshot()); - std::string str; - str += "Low alpha shiny (alpha = "; - str += tostr_default(alpha_wild_overall); - str += ").\nPlease report this image to the " + PROGRAM_NAME + " server."; - send_program_recoverable_error_notification( - env, settings, - str, - wild_result.get_best_screenshot() - ); - } - - your_result.alpha = alpha_own; - if (alpha_own < OVERALL_THRESHOLD){ - env.log("ShinyDetector: Lead not Shiny.", COLOR_PURPLE); - your_result.shiny_type = ShinyType::NOT_SHINY; - }else{ - env.log("ShinyDetector: Detected Lead Shiny!", COLOR_BLUE); - your_result.shiny_type = ShinyType::UNKNOWN_SHINY; - } -} - - -void detect_shiny_battle( - ProgramEnvironment& env, - VideoStream& stream, CancellableScope& scope, - DoublesShinyDetection& wild_result, - ShinyDetectionResult& your_result, - EventNotificationOption& settings, - const DetectionType& type, - std::chrono::seconds timeout, - bool use_shiny_sound -){ - BattleType battle_type = type.full_battle_menu ? BattleType::STANDARD : BattleType::STARTER; - ShinyEncounterTracker tracker(stream.logger(), stream.overlay(), battle_type); - - std::unique_ptr shiny_sound_detector; - std::vector shiny_sound_timestamps; // the times where shiny sound is detected - - if (use_shiny_sound){ - shiny_sound_detector = std::make_unique( - stream.logger(), - [&shiny_sound_timestamps](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - // When this lambda function is called, a shiny sound is detected. - // Mark this by `shiny_sound_timestamps`. - shiny_sound_timestamps.emplace_back(current_time()); - // This lambda function always returns false. It tells the shiny sound detector to always return false - // in ShinySoundDetector::process_spectrums() when a shiny sound is found, so that it won't stop - // ShinyEncounterTracker tracker from finish running. - - return false; - } - ); - } - - std::vector callbacks = {{tracker}}; - if (use_shiny_sound){ - callbacks.emplace_back(*shiny_sound_detector); - } - int result = wait_until(stream, scope, timeout, callbacks); - if (result < 0){ - stream.log("ShinyDetector: Battle menu not found after timeout.", COLOR_RED); - return; - } - wild_result.best_screenshot = tracker.sparkles_wild_overall().best_image(); - your_result.best_screenshot = tracker.sparkles_own().best_image(); -// your_result.best_screenshot.save("test.png"); - determine_shiny_status( - env, - wild_result, your_result, - settings, - battle_type, - tracker, - shiny_sound_timestamps - ); -} - - - - - - - - - - -} -} -} +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h" +#include "PokemonBDSP_ShinyEncounterDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +const std::chrono::milliseconds SHINY_ANIMATION_DELAY(3900); + +const DetectionType WILD_POKEMON{ + {0.4, 0.02, 0.60, 0.93}, + PokemonSwSh::EncounterState::WILD_ANIMATION, + std::chrono::milliseconds(3900), + true, +}; +const DetectionType YOUR_POKEMON{ + {0.0, 0.1, 0.8, 0.8}, + PokemonSwSh::EncounterState::YOUR_ANIMATION, + std::chrono::milliseconds(3900), + false, +}; + + + +ShinyEncounterTracker::ShinyEncounterTracker( + Logger& logger, VideoOverlay& overlay, + BattleType battle_type +) + : VisualInferenceCallback("ShinyEncounterTracker") + , m_logger(logger) +// , m_overlay(overlay) + , m_battle_menu(battle_type) + , m_dialog_tracker(logger, m_dialog_detector) + , m_wild_animation_end_timestamp(WallClock::min()) + , m_your_animation_start_timestamp(WallClock::min()) + , m_box_wild_left(0.40, 0.02, 0.20, 0.48) + , m_box_wild_right(0.70, 0.02, 0.20, 0.48) + , m_sparkle_tracker_wild(logger, overlay, m_sparkles_wild, {0.4, 0.02, 0.60, 0.93}) + , m_sparkle_tracker_own(logger, overlay, m_sparkles_own, {0.0, 0.1, 0.8, 0.8}) +{} +void ShinyEncounterTracker::make_overlays(VideoOverlaySet& items) const{ + m_battle_menu.make_overlays(items); + m_dialog_tracker.make_overlays(items); + items.add(COLOR_RED, m_box_wild_left); + items.add(COLOR_RED, m_box_wild_right); + m_sparkle_tracker_wild.make_overlays(items); + m_sparkle_tracker_own.make_overlays(items); +} +bool ShinyEncounterTracker::process_frame(const VideoSnapshot& frame){ + using PokemonSwSh::EncounterState; + + if (!frame){ + return false; + } + + size_t width = frame->width(); + size_t height = frame->height(); + + if (height < 720){ + throw UserSetupError(m_logger, "Video resolution must be at least 720p."); + } + double aspect_ratio = (double)width / height; + if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ + throw UserSetupError(m_logger, "Video aspect ratio must be 16:9."); + } + + // End shiny detection when we reach the battle menu + bool battle_menu = m_battle_menu.process_frame(frame); + if (battle_menu){ + m_dialog_tracker.push_end(frame.timestamp); + return true; + } + + // Use m_dialog_tracker to track dialog timings. Dialogs partitions the opening of a battle into: + // before anything -> wild pokemon animation -> player pokemon animation -> battle menu detected + m_dialog_tracker.process_frame(frame); + + switch (m_dialog_tracker.encounter_state()){ + case EncounterState::BEFORE_ANYTHING: + break; + case EncounterState::WILD_ANIMATION:{ + // Update the timestamp that records the end of wild animation + m_wild_animation_end_timestamp = frame.timestamp; + + m_sparkle_tracker_wild.process_frame(frame); + m_sparkle_tracker_own.clear_boxes(); + m_best_wild_overall.add_frame(frame.frame, m_sparkles_wild); + + ImagePixelBox box_overall = floatbox_to_pixelbox(width, height, {0.4, 0.02, 0.60, 0.93}); + ImagePixelBox box_left = floatbox_to_pixelbox(width, height, m_box_wild_left); + ImagePixelBox box_right = floatbox_to_pixelbox(width, height, m_box_wild_right); + box_left.clip(box_overall); + box_right.clip(box_overall); + box_left.min_x -= box_overall.min_x; + box_left.min_y -= box_overall.min_y; + box_left.max_x -= box_overall.min_x; + box_left.max_y -= box_overall.min_y; + box_right.min_x -= box_overall.min_x; + box_right.min_y -= box_overall.min_y; + box_right.max_x -= box_overall.min_x; + box_right.max_y -= box_overall.min_y; + + m_best_wild_left.add_frame(nullptr, m_sparkles_wild.extract_subbox(box_left)); + m_best_wild_right.add_frame(nullptr, m_sparkles_wild.extract_subbox(box_right)); + break; + } + case EncounterState::YOUR_ANIMATION: + // Update the timestamp that records the start of player pokemon animation + if (m_your_animation_start_timestamp == WallClock::min()){ + m_your_animation_start_timestamp = frame.timestamp; + } + + m_sparkle_tracker_wild.clear_boxes(); + m_sparkle_tracker_own.process_frame(frame); + m_best_own.add_frame(frame.frame, m_sparkles_own); + break; + case EncounterState::POST_ENTRY: + break; + } + + return false; +} + +void determine_shiny_status( + ProgramEnvironment& env, + DoublesShinyDetection& wild_result, + ShinyDetectionResult& your_result, + EventNotificationOption& settings, + BattleType battle_type, + const ShinyEncounterTracker& tracker, + const std::vector& shiny_sound_timestamps +){ + const double OVERALL_THRESHOLD = GameSettings::instance().SHINY_ALPHA_OVERALL_THRESHOLD; + const double DOUBLES_THRESHOLD = GameSettings::instance().SHINY_ALPHA_SIDE_THRESHOLD; + const double DIALOG_ALPHA = GameSettings::instance().SHINY_DIALOG_ALPHA; + const double SOUND_ALPHA = GameSettings::instance().SHINY_SOUND_ALPHA; + + const PokemonSwSh::EncounterDialogTracker& dialog_tracker = tracker.dialog_tracker(); + const ShinySparkleAggregator& sparkles_wild_overall = tracker.sparkles_wild_overall(); + const ShinySparkleAggregator& sparkles_wild_left = tracker.sparkles_wild_left(); + const ShinySparkleAggregator& sparkles_wild_right = tracker.sparkles_wild_right(); + const ShinySparkleAggregator& sparkles_own = tracker.sparkles_own(); + + double alpha_wild_overall = sparkles_wild_overall.best_overall(); + double alpha_wild_left = sparkles_wild_left.best_overall(); + double alpha_wild_right = sparkles_wild_right.best_overall(); + double alpha_own = sparkles_own.best_overall(); + + { + std::chrono::milliseconds dialog_duration = dialog_tracker.wild_animation_duration(); + std::chrono::milliseconds min_delay = SHINY_ANIMATION_DELAY - std::chrono::milliseconds(300); + std::chrono::milliseconds max_delay = SHINY_ANIMATION_DELAY + std::chrono::milliseconds(500); + if (min_delay <= dialog_duration && dialog_duration <= max_delay){ + alpha_wild_overall += DIALOG_ALPHA; + } + } + +#if 0 + cout << "Wild End: " << std::chrono::duration_cast(tracker.wild_animation_end_timestmap() - tracker.m_start_time) << endl; + cout << "Your Start: " << std::chrono::duration_cast(tracker.your_animation_start_timestamp() - tracker.m_start_time) << endl; + for (WallClock time : shiny_sound_timestamps){ + cout << "Shiny Sound: " << std::chrono::duration_cast(time - tracker.m_start_time) << endl; + } +#endif + + bool wild_shiny_sound_detected = false; + bool own_shiny_sound_detected = false; + for (const WallClock& timestamp: shiny_sound_timestamps){ + const WallClock& wild_end = tracker.wild_animation_end_timestmap(); + const WallClock& own_start = tracker.your_animation_start_timestamp(); + + bool wild_shiny = timestamp < wild_end + Milliseconds(500); + bool own_shiny = timestamp >= own_start; + + wild_shiny_sound_detected |= wild_shiny; + own_shiny_sound_detected |= own_shiny; + if (!wild_shiny && !own_shiny){ + throw_and_log( + env.logger(), ErrorReport::SEND_ERROR_REPORT, + "Wrong shiny sound timing found." + ); + } + } + alpha_wild_overall += wild_shiny_sound_detected ? SOUND_ALPHA : 0.0; + alpha_own += own_shiny_sound_detected ? SOUND_ALPHA : 0.0; + + if (battle_type == BattleType::STARTER){ + std::chrono::milliseconds dialog_duration = dialog_tracker.your_animation_duration(); + std::chrono::milliseconds min_delay = SHINY_ANIMATION_DELAY - std::chrono::milliseconds(300); + std::chrono::milliseconds max_delay = SHINY_ANIMATION_DELAY + std::chrono::milliseconds(2000); // Add headroom for happiness. + if (min_delay <= dialog_duration && dialog_duration <= max_delay){ + alpha_own += DIALOG_ALPHA; + } + } + env.log( + "ShinyDetector: Wild Alpha = " + tostr_default(alpha_wild_overall) + + (wild_shiny_sound_detected ? " (shiny sound detected)" : "") + + ", Left Alpha = " + tostr_default(alpha_wild_left) + + ", Right Alpha = " + tostr_default(alpha_wild_right) + + ", Your Alpha = " + tostr_default(alpha_own) + + (own_shiny_sound_detected ? " (shiny sound detected)" : ""), + COLOR_PURPLE + ); + + wild_result.shiny_type = ShinyType::UNKNOWN; + wild_result.alpha = alpha_wild_overall; + wild_result.left_is_shiny = false; + wild_result.right_is_shiny = false; + + if (alpha_wild_overall < OVERALL_THRESHOLD){ + env.log("ShinyDetector: Wild not Shiny.", COLOR_PURPLE); + wild_result.shiny_type = ShinyType::NOT_SHINY; + }else{ + env.log("ShinyDetector: Detected Wild Shiny!", COLOR_BLUE); + wild_result.shiny_type = ShinyType::UNKNOWN_SHINY; + wild_result.left_is_shiny = alpha_wild_left >= DOUBLES_THRESHOLD; + wild_result.right_is_shiny = alpha_wild_right >= DOUBLES_THRESHOLD; + } + + if (DIALOG_ALPHA <= alpha_wild_overall && alpha_wild_overall < DIALOG_ALPHA + 1.5){ + dump_image(env.logger(), env.program_info(), "LowShinyAlpha", wild_result.get_best_screenshot()); + std::string str; + str += "Low alpha shiny (alpha = "; + str += tostr_default(alpha_wild_overall); + str += ").\nPlease report this image to the " + PROGRAM_NAME + " server."; + send_program_recoverable_error_notification( + env, settings, + str, + wild_result.get_best_screenshot() + ); + } + + your_result.alpha = alpha_own; + if (alpha_own < OVERALL_THRESHOLD){ + env.log("ShinyDetector: Lead not Shiny.", COLOR_PURPLE); + your_result.shiny_type = ShinyType::NOT_SHINY; + }else{ + env.log("ShinyDetector: Detected Lead Shiny!", COLOR_BLUE); + your_result.shiny_type = ShinyType::UNKNOWN_SHINY; + } +} + + +void detect_shiny_battle( + ProgramEnvironment& env, + VideoStream& stream, CancellableScope& scope, + DoublesShinyDetection& wild_result, + ShinyDetectionResult& your_result, + EventNotificationOption& settings, + const DetectionType& type, + std::chrono::seconds timeout, + bool use_shiny_sound +){ + BattleType battle_type = type.full_battle_menu ? BattleType::STANDARD : BattleType::STARTER; + ShinyEncounterTracker tracker(stream.logger(), stream.overlay(), battle_type); + + std::unique_ptr shiny_sound_detector; + std::vector shiny_sound_timestamps; // the times where shiny sound is detected + + if (use_shiny_sound){ + shiny_sound_detector = std::make_unique( + stream.logger(), + [&shiny_sound_timestamps](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + // When this lambda function is called, a shiny sound is detected. + // Mark this by `shiny_sound_timestamps`. + shiny_sound_timestamps.emplace_back(current_time()); + // This lambda function always returns false. It tells the shiny sound detector to always return false + // in ShinySoundDetector::process_spectrums() when a shiny sound is found, so that it won't stop + // ShinyEncounterTracker tracker from finish running. + + return false; + } + ); + } + + std::vector callbacks = {{tracker}}; + if (use_shiny_sound){ + callbacks.emplace_back(*shiny_sound_detector); + } + int result = wait_until(stream, scope, timeout, callbacks); + if (result < 0){ + stream.log("ShinyDetector: Battle menu not found after timeout.", COLOR_RED); + return; + } + wild_result.best_screenshot = tracker.sparkles_wild_overall().best_image(); + your_result.best_screenshot = tracker.sparkles_own().best_image(); +// your_result.best_screenshot.save("test.png"); + determine_shiny_status( + env, + wild_result, your_result, + settings, + battle_type, + tracker, + shiny_sound_timestamps + ); +} + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h index 2c6cfe7d7b..e3ac698b64 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h @@ -1,141 +1,141 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ShinyEncounterDetector_H -#define PokemonAutomation_PokemonBDSP_ShinyEncounterDetector_H - -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "Pokemon/Pokemon_DataTypes.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP_ShinySparkleSet.h" - -namespace PokemonAutomation{ - class CancellableScope; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - - -struct DoublesShinyDetection : public ShinyDetectionResult{ - bool left_is_shiny = false; - bool right_is_shiny = false; -}; - - -struct DetectionType{ - ImageFloatBox box; - PokemonSwSh::EncounterState required_state; - std::chrono::milliseconds state_duration; - bool full_battle_menu; -}; -extern const DetectionType WILD_POKEMON; -extern const DetectionType YOUR_POKEMON; - - - -// Used by detect_shiny_battle to detect dialog timing and -// shiny sparkle animation to determine whether there is shiny pokemon -// when battle starts. -// See detect_shiny_battle() for more details. -class ShinyEncounterTracker : public VisualInferenceCallback{ - using EncounterDialogTracker = PokemonSwSh::EncounterDialogTracker; - -public: - ShinyEncounterTracker( - Logger& logger, VideoOverlay& overlay, - BattleType battle_type - ); - - const EncounterDialogTracker& dialog_tracker() const{ return m_dialog_tracker; } - const ShinySparkleAggregator& sparkles_wild_overall() const{ return m_best_wild_overall; } - const ShinySparkleAggregator& sparkles_wild_left() const{ return m_best_wild_left; } - const ShinySparkleAggregator& sparkles_wild_right() const{ return m_best_wild_right; } - const ShinySparkleAggregator& sparkles_own() const{ return m_best_own; } - - const WallClock& wild_animation_end_timestmap() const { return m_wild_animation_end_timestamp; } - const WallClock& your_animation_start_timestamp() const { return m_your_animation_start_timestamp; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - - ShinyType get_results() const; - - -private: - Logger& m_logger; -// VideoOverlay& m_overlay; - - BattleMenuWatcher m_battle_menu; - - BattleDialogDetector m_dialog_detector; - EncounterDialogTracker m_dialog_tracker; - WallClock m_wild_animation_end_timestamp; - WallClock m_your_animation_start_timestamp; - - ImageFloatBox m_box_wild_left; - ImageFloatBox m_box_wild_right; - - ShinySparkleSetBDSP m_sparkles_wild; - ShinySparkleSetBDSP m_sparkles_own; - ShinySparkleTracker m_sparkle_tracker_wild; - ShinySparkleTracker m_sparkle_tracker_own; - - ShinySparkleAggregator m_best_wild_overall; - ShinySparkleAggregator m_best_wild_left; - ShinySparkleAggregator m_best_wild_right; - ShinySparkleAggregator m_best_own; -}; - - -// Called when battle starts to detect whether any pokemon in the battle is shiny. -// Store shiny results in `wild_result` and `your_result`. -// wild_result.shiny_type and your_result.shiny_type can be ShinyType::NOT_SHINY or -// ShinyType::UNKNOWN_SHINY. -// `overall_threshold` is the threshold for determining wild shiny and your shiny. -// If there is wild shiny, `doubles_threshold` is the threshold to determine the shiniess -// of the left and right wild pokemon slot. -// -// Internally, we use the symbol alpha to denote how much shininess detected. -// The higher the alpha, the more likely the pokemon is shiny. -// `overall_threshold` and `doubles_threshold` are thresholds on alpha. -// Each detected shiny animation sparkles counts as 1.0 alpha. -// The function uses `ShinyEncounterTracker` to track the frame with the most detected -// sparkles, aka highest alpha. -// If the dialog timing is implies a shiny animation played, add 3.5 to the highest alpha. -// If the final value reaches `overall_threshold`, it is counted as a shiny detected. -// If the highest alpha detected on the cropped view of the left pokemon slot reaches -// `doubles_threshold`, it is considered a shiny on left. Same to the right slot. -// -// The function also use a shiny sound detector to improve its detection on wild pokemon. -// When a shiny sound is detected, it adds 5.0 to the heighest overall alpha value. -void detect_shiny_battle( - ProgramEnvironment& env, - VideoStream& stream, CancellableScope& scope, - DoublesShinyDetection& wild_result, - ShinyDetectionResult& your_result, - EventNotificationOption& settings, - const DetectionType& type, - std::chrono::seconds timeout, - bool use_shiny_sound = false -); - - - - - - - - -} -} -} -#endif +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ShinyEncounterDetector_H +#define PokemonAutomation_PokemonBDSP_ShinyEncounterDetector_H + +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Pokemon/Pokemon_DataTypes.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP_ShinySparkleSet.h" + +namespace PokemonAutomation{ + class CancellableScope; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + + +struct DoublesShinyDetection : public ShinyDetectionResult{ + bool left_is_shiny = false; + bool right_is_shiny = false; +}; + + +struct DetectionType{ + ImageFloatBox box; + PokemonSwSh::EncounterState required_state; + std::chrono::milliseconds state_duration; + bool full_battle_menu; +}; +extern const DetectionType WILD_POKEMON; +extern const DetectionType YOUR_POKEMON; + + + +// Used by detect_shiny_battle to detect dialog timing and +// shiny sparkle animation to determine whether there is shiny pokemon +// when battle starts. +// See detect_shiny_battle() for more details. +class ShinyEncounterTracker : public VisualInferenceCallback{ + using EncounterDialogTracker = PokemonSwSh::EncounterDialogTracker; + +public: + ShinyEncounterTracker( + Logger& logger, VideoOverlay& overlay, + BattleType battle_type + ); + + const EncounterDialogTracker& dialog_tracker() const{ return m_dialog_tracker; } + const ShinySparkleAggregator& sparkles_wild_overall() const{ return m_best_wild_overall; } + const ShinySparkleAggregator& sparkles_wild_left() const{ return m_best_wild_left; } + const ShinySparkleAggregator& sparkles_wild_right() const{ return m_best_wild_right; } + const ShinySparkleAggregator& sparkles_own() const{ return m_best_own; } + + const WallClock& wild_animation_end_timestmap() const { return m_wild_animation_end_timestamp; } + const WallClock& your_animation_start_timestamp() const { return m_your_animation_start_timestamp; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + + ShinyType get_results() const; + + +private: + Logger& m_logger; +// VideoOverlay& m_overlay; + + BattleMenuWatcher m_battle_menu; + + BattleDialogDetector m_dialog_detector; + EncounterDialogTracker m_dialog_tracker; + WallClock m_wild_animation_end_timestamp; + WallClock m_your_animation_start_timestamp; + + ImageFloatBox m_box_wild_left; + ImageFloatBox m_box_wild_right; + + ShinySparkleSetBDSP m_sparkles_wild; + ShinySparkleSetBDSP m_sparkles_own; + ShinySparkleTracker m_sparkle_tracker_wild; + ShinySparkleTracker m_sparkle_tracker_own; + + ShinySparkleAggregator m_best_wild_overall; + ShinySparkleAggregator m_best_wild_left; + ShinySparkleAggregator m_best_wild_right; + ShinySparkleAggregator m_best_own; +}; + + +// Called when battle starts to detect whether any pokemon in the battle is shiny. +// Store shiny results in `wild_result` and `your_result`. +// wild_result.shiny_type and your_result.shiny_type can be ShinyType::NOT_SHINY or +// ShinyType::UNKNOWN_SHINY. +// `overall_threshold` is the threshold for determining wild shiny and your shiny. +// If there is wild shiny, `doubles_threshold` is the threshold to determine the shiniess +// of the left and right wild pokemon slot. +// +// Internally, we use the symbol alpha to denote how much shininess detected. +// The higher the alpha, the more likely the pokemon is shiny. +// `overall_threshold` and `doubles_threshold` are thresholds on alpha. +// Each detected shiny animation sparkles counts as 1.0 alpha. +// The function uses `ShinyEncounterTracker` to track the frame with the most detected +// sparkles, aka highest alpha. +// If the dialog timing is implies a shiny animation played, add 3.5 to the highest alpha. +// If the final value reaches `overall_threshold`, it is counted as a shiny detected. +// If the highest alpha detected on the cropped view of the left pokemon slot reaches +// `doubles_threshold`, it is considered a shiny on left. Same to the right slot. +// +// The function also use a shiny sound detector to improve its detection on wild pokemon. +// When a shiny sound is detected, it adds 5.0 to the heighest overall alpha value. +void detect_shiny_battle( + ProgramEnvironment& env, + VideoStream& stream, CancellableScope& scope, + DoublesShinyDetection& wild_result, + ShinyDetectionResult& your_result, + EventNotificationOption& settings, + const DetectionType& type, + std::chrono::seconds timeout, + bool use_shiny_sound = false +); + + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp index 7a741b023f..c97395c97c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.cpp @@ -1,151 +1,151 @@ -/* Shiny Sparkle Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h" -#include "PokemonBDSP_ShinySparkleSet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -ShinySparkleSetBDSP::~ShinySparkleSetBDSP(){} -void ShinySparkleSetBDSP::clear(){ - balls.clear(); - stars.clear(); - m_alpha_overall = 0; -} - -ShinySparkleSetBDSP ShinySparkleSetBDSP::extract_subbox(const ImagePixelBox& subbox) const{ - ShinySparkleSetBDSP ret; - for (const ImagePixelBox& box : balls){ - if (subbox.min_x <= box.min_x && - subbox.min_y <= box.min_y && - subbox.max_x >= box.max_x && - subbox.max_y >= box.max_y - ){ - ret.balls.emplace_back(box); - } - } - for (const ImagePixelBox& box : stars){ - if (subbox.min_x <= box.min_x && - subbox.min_y <= box.min_y && - subbox.max_x >= box.max_x && - subbox.max_y >= box.max_y - ){ - ret.stars.emplace_back(box); - } - } - ret.update_alphas(); - return ret; -} -std::string ShinySparkleSetBDSP::to_str() const{ - std::string str; - if (m_alpha_overall < 3.0){ - return str; - } - str += "SparkleDetector"; - if (!balls.empty()){ - str += " - Balls: " + std::to_string(balls.size()); - } - if (!stars.empty()){ - str += " - Stars: " + std::to_string(stars.size()); - } - str += " - (alpha = " + tostr_default(m_alpha_overall) + ")"; - return str; -} -void ShinySparkleSetBDSP::draw_boxes( - VideoOverlaySet& overlays, - const ImageViewRGB32& frame, - const ImageFloatBox& inference_box -) const{ - for (const ImagePixelBox& box : balls){ - overlays.add(COLOR_GREEN, translate_to_parent(frame, inference_box, box)); - } - for (const ImagePixelBox& box : stars){ - overlays.add(COLOR_BLUE, translate_to_parent(frame, inference_box, box)); - } -} -void ShinySparkleSetBDSP::update_alphas(){ - double ball_alpha = 1.0 * balls.size(); - double star_alpha = 1.0 * stars.size(); - m_alpha_overall = ball_alpha + star_alpha; -} - - - - -ShinySparkleSetBDSP find_sparkles(size_t screen_area, WaterfillSession& session){ - ShinySparkleSetBDSP sparkles; - auto finder = session.make_iterator(20); - WaterfillObject object; - while (finder->find_next(object, true)){ - PokemonSwSh::RadialSparkleDetector radial_sparkle(screen_area, object); - if (radial_sparkle.is_ball()){ - sparkles.balls.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); - continue; - } - if (radial_sparkle.is_star()){ - sparkles.stars.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); - continue; - } - } - return sparkles; -} -void ShinySparkleSetBDSP::read_from_image(size_t screen_area, const ImageViewRGB32& image){ - clear(); - if (!image){ - return; - } - - std::vector matrices = compress_rgb32_to_binary_range( - image, - { - {0xff606000, 0xffffffff}, - {0xff707000, 0xffffffff}, - {0xff808000, 0xffffffff}, - {0xff909000, 0xffffffff}, - } - ); - auto session = make_WaterfillSession(); - - double best_alpha = 0; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - ShinySparkleSetBDSP sparkles = find_sparkles(screen_area, *session); - sparkles.update_alphas(); - double alpha = sparkles.alpha_overall(); - if (best_alpha < alpha){ - best_alpha = alpha; - *this = std::move(sparkles); - } - } -} - - - - -void ShinySparkleAggregator::add_frame(const std::shared_ptr& image, const ShinySparkleSetBDSP& sparkles){ - double alpha = sparkles.alpha_overall(); - if (m_best_overall < alpha){ - m_best_overall = alpha; - m_best_image = image; - } -} - - - - - -} -} -} +/* Shiny Sparkle Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h" +#include "PokemonBDSP_ShinySparkleSet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +ShinySparkleSetBDSP::~ShinySparkleSetBDSP(){} +void ShinySparkleSetBDSP::clear(){ + balls.clear(); + stars.clear(); + m_alpha_overall = 0; +} + +ShinySparkleSetBDSP ShinySparkleSetBDSP::extract_subbox(const ImagePixelBox& subbox) const{ + ShinySparkleSetBDSP ret; + for (const ImagePixelBox& box : balls){ + if (subbox.min_x <= box.min_x && + subbox.min_y <= box.min_y && + subbox.max_x >= box.max_x && + subbox.max_y >= box.max_y + ){ + ret.balls.emplace_back(box); + } + } + for (const ImagePixelBox& box : stars){ + if (subbox.min_x <= box.min_x && + subbox.min_y <= box.min_y && + subbox.max_x >= box.max_x && + subbox.max_y >= box.max_y + ){ + ret.stars.emplace_back(box); + } + } + ret.update_alphas(); + return ret; +} +std::string ShinySparkleSetBDSP::to_str() const{ + std::string str; + if (m_alpha_overall < 3.0){ + return str; + } + str += "SparkleDetector"; + if (!balls.empty()){ + str += " - Balls: " + std::to_string(balls.size()); + } + if (!stars.empty()){ + str += " - Stars: " + std::to_string(stars.size()); + } + str += " - (alpha = " + tostr_default(m_alpha_overall) + ")"; + return str; +} +void ShinySparkleSetBDSP::draw_boxes( + VideoOverlaySet& overlays, + const ImageViewRGB32& frame, + const ImageFloatBox& inference_box +) const{ + for (const ImagePixelBox& box : balls){ + overlays.add(COLOR_GREEN, translate_to_parent(frame, inference_box, box)); + } + for (const ImagePixelBox& box : stars){ + overlays.add(COLOR_BLUE, translate_to_parent(frame, inference_box, box)); + } +} +void ShinySparkleSetBDSP::update_alphas(){ + double ball_alpha = 1.0 * balls.size(); + double star_alpha = 1.0 * stars.size(); + m_alpha_overall = ball_alpha + star_alpha; +} + + + + +ShinySparkleSetBDSP find_sparkles(size_t screen_area, WaterfillSession& session){ + ShinySparkleSetBDSP sparkles; + auto finder = session.make_iterator(20); + WaterfillObject object; + while (finder->find_next(object, true)){ + PokemonSwSh::RadialSparkleDetector radial_sparkle(screen_area, object); + if (radial_sparkle.is_ball()){ + sparkles.balls.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); + continue; + } + if (radial_sparkle.is_star()){ + sparkles.stars.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); + continue; + } + } + return sparkles; +} +void ShinySparkleSetBDSP::read_from_image(size_t screen_area, const ImageViewRGB32& image){ + clear(); + if (!image){ + return; + } + + std::vector matrices = compress_rgb32_to_binary_range( + image, + { + {0xff606000, 0xffffffff}, + {0xff707000, 0xffffffff}, + {0xff808000, 0xffffffff}, + {0xff909000, 0xffffffff}, + } + ); + auto session = make_WaterfillSession(); + + double best_alpha = 0; + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + ShinySparkleSetBDSP sparkles = find_sparkles(screen_area, *session); + sparkles.update_alphas(); + double alpha = sparkles.alpha_overall(); + if (best_alpha < alpha){ + best_alpha = alpha; + *this = std::move(sparkles); + } + } +} + + + + +void ShinySparkleAggregator::add_frame(const std::shared_ptr& image, const ShinySparkleSetBDSP& sparkles){ + double alpha = sparkles.alpha_overall(); + if (m_best_overall < alpha){ + m_best_overall = alpha; + m_best_image = image; + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h index 3c880a72ba..882c30395f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinySparkleSet.h @@ -1,66 +1,66 @@ -/* Shiny Sparkle Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ShinySparkleSet_H -#define PokemonAutomation_PokemonBDSP_ShinySparkleSet_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "Pokemon/Pokemon_ShinySparkleSet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class ShinySparkleSetBDSP : public Pokemon::ShinySparkleSet{ -public: - std::vector balls; - std::vector stars; - - virtual ~ShinySparkleSetBDSP(); - virtual void clear() override; - - double alpha_overall() const{ return m_alpha_overall; } - - ShinySparkleSetBDSP extract_subbox(const ImagePixelBox& subbox) const; - - virtual std::string to_str() const override; - virtual void read_from_image(size_t screen_area, const ImageViewRGB32& image) override; - - virtual void draw_boxes( - VideoOverlaySet& overlays, - const ImageViewRGB32& frame, - const ImageFloatBox& inference_box - ) const override; - -private: - void update_alphas(); - - double m_alpha_overall = 0; -}; - - - -class ShinySparkleAggregator{ -public: - double best_overall() const{ return m_best_overall; } - const std::shared_ptr& best_image() const{ return m_best_image; } - - void add_frame(const std::shared_ptr& image, const ShinySparkleSetBDSP& sparkles); - -private: - double m_best_overall = 0; - std::shared_ptr m_best_image; -}; - - - - -} -} -} -#endif +/* Shiny Sparkle Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ShinySparkleSet_H +#define PokemonAutomation_PokemonBDSP_ShinySparkleSet_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "Pokemon/Pokemon_ShinySparkleSet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class ShinySparkleSetBDSP : public Pokemon::ShinySparkleSet{ +public: + std::vector balls; + std::vector stars; + + virtual ~ShinySparkleSetBDSP(); + virtual void clear() override; + + double alpha_overall() const{ return m_alpha_overall; } + + ShinySparkleSetBDSP extract_subbox(const ImagePixelBox& subbox) const; + + virtual std::string to_str() const override; + virtual void read_from_image(size_t screen_area, const ImageViewRGB32& image) override; + + virtual void draw_boxes( + VideoOverlaySet& overlays, + const ImageViewRGB32& frame, + const ImageFloatBox& inference_box + ) const override; + +private: + void update_alphas(); + + double m_alpha_overall = 0; +}; + + + +class ShinySparkleAggregator{ +public: + double best_overall() const{ return m_best_overall; } + const std::shared_ptr& best_image() const{ return m_best_image; } + + void add_frame(const std::shared_ptr& image, const ShinySparkleSetBDSP& sparkles); + +private: + double m_best_overall = 0; + std::shared_ptr m_best_image; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.cpp index b11832b7c8..6720aa08f6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.cpp @@ -1,46 +1,46 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} - - -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; -} - -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonBDSP/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} + + +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; +} + +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonBDSP/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h b/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h index 5c3b19e6f7..728b0aeeb8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h @@ -1,36 +1,36 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ShinySoundDetector_H -#define PokemonAutomation_PokemonBDSP_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ShinySoundDetector_H +#define PokemonAutomation_PokemonBDSP_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.cpp b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.cpp index 284c30f2e5..eadb0502f3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.cpp @@ -1,57 +1,57 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonBDSP_EncounterFilterEnums.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -const EnumDropdownDatabase& ShinyFilter_Database(){ - static const EnumDropdownDatabase database({ - {ShinyFilter::ANYTHING, "anything", "Anything"}, - {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, - {ShinyFilter::SHINY, "shiny", "Shiny"}, - {ShinyFilter::NOTHING, "nothing", "Nothing"}, - }); - return database; -} - - -const std::vector EncounterAction_NAMES{ - "Stop Program", - "Run Away", - "Throw balls.", - "Throw balls. Save if caught.", -}; -const std::map EncounterAction_MAP{ - {EncounterAction_NAMES[0], EncounterAction::StopProgram}, - {EncounterAction_NAMES[1], EncounterAction::RunAway}, - {EncounterAction_NAMES[2], EncounterAction::ThrowBalls}, - {EncounterAction_NAMES[3], EncounterAction::ThrowBallsAndSave}, -}; - - -const std::vector ShinyFilter_NAMES{ - "Anything", - "Not Shiny", - "Shiny", - "Nothing", -}; -const std::map ShinyFilter_MAP{ - {ShinyFilter_NAMES[0], ShinyFilter::ANYTHING}, - {ShinyFilter_NAMES[1], ShinyFilter::NOT_SHINY}, - {ShinyFilter_NAMES[2], ShinyFilter::SHINY}, - {ShinyFilter_NAMES[3], ShinyFilter::NOTHING}, -}; - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonBDSP_EncounterFilterEnums.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +const EnumDropdownDatabase& ShinyFilter_Database(){ + static const EnumDropdownDatabase database({ + {ShinyFilter::ANYTHING, "anything", "Anything"}, + {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, + {ShinyFilter::SHINY, "shiny", "Shiny"}, + {ShinyFilter::NOTHING, "nothing", "Nothing"}, + }); + return database; +} + + +const std::vector EncounterAction_NAMES{ + "Stop Program", + "Run Away", + "Throw balls.", + "Throw balls. Save if caught.", +}; +const std::map EncounterAction_MAP{ + {EncounterAction_NAMES[0], EncounterAction::StopProgram}, + {EncounterAction_NAMES[1], EncounterAction::RunAway}, + {EncounterAction_NAMES[2], EncounterAction::ThrowBalls}, + {EncounterAction_NAMES[3], EncounterAction::ThrowBallsAndSave}, +}; + + +const std::vector ShinyFilter_NAMES{ + "Anything", + "Not Shiny", + "Shiny", + "Nothing", +}; +const std::map ShinyFilter_MAP{ + {ShinyFilter_NAMES[0], ShinyFilter::ANYTHING}, + {ShinyFilter_NAMES[1], ShinyFilter::NOT_SHINY}, + {ShinyFilter_NAMES[2], ShinyFilter::SHINY}, + {ShinyFilter_NAMES[3], ShinyFilter::NOTHING}, +}; + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.h b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.h index fe0f8aab94..62fa71e9c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterEnums.h @@ -1,59 +1,59 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterEnums_H -#define PokemonAutomation_PokemonBDSP_EncounterFilterEnums_H - -#include -#include -#include -#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -using EncounterAction = PokemonSwSh::EncounterAction; -using EncounterActionCell = PokemonSwSh::EncounterActionCell; - -extern const std::vector EncounterAction_NAMES; -extern const std::map EncounterAction_MAP; - - - - - -enum class ShinyFilter{ - ANYTHING, - NOT_SHINY, - SHINY, - NOTHING, -}; -const EnumDropdownDatabase& ShinyFilter_Database(); - -class ShinyFilterCell : public EnumDropdownCell{ -public: - ShinyFilterCell() - : EnumDropdownCell( - ShinyFilter_Database(), - LockMode::LOCK_WHILE_RUNNING, - ShinyFilter::ANYTHING - ) - {} -}; - -extern const std::vector ShinyFilter_NAMES; -extern const std::map ShinyFilter_MAP; - - - - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterEnums_H +#define PokemonAutomation_PokemonBDSP_EncounterFilterEnums_H + +#include +#include +#include +#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +using EncounterAction = PokemonSwSh::EncounterAction; +using EncounterActionCell = PokemonSwSh::EncounterActionCell; + +extern const std::vector EncounterAction_NAMES; +extern const std::map EncounterAction_MAP; + + + + + +enum class ShinyFilter{ + ANYTHING, + NOT_SHINY, + SHINY, + NOTHING, +}; +const EnumDropdownDatabase& ShinyFilter_Database(); + +class ShinyFilterCell : public EnumDropdownCell{ +public: + ShinyFilterCell() + : EnumDropdownCell( + ShinyFilter_Database(), + LockMode::LOCK_WHILE_RUNNING, + ShinyFilter::ANYTHING + ) + {} +}; + +extern const std::vector ShinyFilter_NAMES; +extern const std::map ShinyFilter_MAP; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.cpp b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.cpp index 10571c70fc..45e7a308cd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.cpp @@ -1,92 +1,92 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include "Common/Cpp/Json/JsonValue.h" -//#include "Common/Cpp/Json/JsonObject.h" -//#include "CommonFramework/Globals.h" -//#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP_EncounterFilterEnums.h" -#include "PokemonBDSP_EncounterFilterOption.h" -//#include "PokemonBDSP_EncounterFilterWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -// using namespace Pokemon; - - - -#if 0 -EncounterFilterOption::EncounterFilterOption(bool enable_overrides) - : m_enable_overrides(enable_overrides) - , m_shiny_filter_default(ShinyFilter::SHINY) - , m_shiny_filter_current(m_shiny_filter_default) -{} -void EncounterFilterOption::load_json(const JsonValue& json){ - using namespace Pokemon; - - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - const std::string* str = obj->get_string("ShinyFilter"); - if (str != nullptr){ - auto iter = ShinyFilter_MAP.find(*str); - if (iter != ShinyFilter_MAP.end()){ - m_shiny_filter_current.store(iter->second, std::memory_order_release); - } - } - - if (m_enable_overrides){ - const JsonValue* array = obj->get_value("Overrides"); - if (array != nullptr){ - m_table.load_json(*array); - } - } -} -JsonValue EncounterFilterOption::to_json() const{ - JsonObject obj; - obj["ShinyFilter"] = ShinyFilter_NAMES[(size_t)m_shiny_filter_current.load(std::memory_order_acquire)]; - - if (m_enable_overrides){ - obj["Overrides"] = m_table.to_json(); - } - - return obj; -} -void EncounterFilterOption::restore_defaults(){ - m_shiny_filter_current.store(m_shiny_filter_default, std::memory_order_release); - m_table.restore_defaults(); -} -ConfigWidget* EncounterFilterOption::make_QtWidget(QWidget& parent){ - return new EncounterFilterWidget(parent, *this); -} -#endif - - -EncounterFilterOption2::EncounterFilterOption2(bool enable_overrides) - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , SHINY_FILTER( - "Stop on:", - ShinyFilter_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ShinyFilter::SHINY - ) -{ - PA_ADD_OPTION(SHINY_FILTER); - if (enable_overrides){ - PA_ADD_OPTION(FILTER_TABLE); - } -} - - - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include "Common/Cpp/Json/JsonValue.h" +//#include "Common/Cpp/Json/JsonObject.h" +//#include "CommonFramework/Globals.h" +//#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP_EncounterFilterEnums.h" +#include "PokemonBDSP_EncounterFilterOption.h" +//#include "PokemonBDSP_EncounterFilterWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +// using namespace Pokemon; + + + +#if 0 +EncounterFilterOption::EncounterFilterOption(bool enable_overrides) + : m_enable_overrides(enable_overrides) + , m_shiny_filter_default(ShinyFilter::SHINY) + , m_shiny_filter_current(m_shiny_filter_default) +{} +void EncounterFilterOption::load_json(const JsonValue& json){ + using namespace Pokemon; + + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + const std::string* str = obj->get_string("ShinyFilter"); + if (str != nullptr){ + auto iter = ShinyFilter_MAP.find(*str); + if (iter != ShinyFilter_MAP.end()){ + m_shiny_filter_current.store(iter->second, std::memory_order_release); + } + } + + if (m_enable_overrides){ + const JsonValue* array = obj->get_value("Overrides"); + if (array != nullptr){ + m_table.load_json(*array); + } + } +} +JsonValue EncounterFilterOption::to_json() const{ + JsonObject obj; + obj["ShinyFilter"] = ShinyFilter_NAMES[(size_t)m_shiny_filter_current.load(std::memory_order_acquire)]; + + if (m_enable_overrides){ + obj["Overrides"] = m_table.to_json(); + } + + return obj; +} +void EncounterFilterOption::restore_defaults(){ + m_shiny_filter_current.store(m_shiny_filter_default, std::memory_order_release); + m_table.restore_defaults(); +} +ConfigWidget* EncounterFilterOption::make_QtWidget(QWidget& parent){ + return new EncounterFilterWidget(parent, *this); +} +#endif + + +EncounterFilterOption2::EncounterFilterOption2(bool enable_overrides) + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , SHINY_FILTER( + "Stop on:", + ShinyFilter_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ShinyFilter::SHINY + ) +{ + PA_ADD_OPTION(SHINY_FILTER); + if (enable_overrides){ + PA_ADD_OPTION(FILTER_TABLE); + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h index 6926bbea9b..23fb1d7a11 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h @@ -1,63 +1,63 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterOption_H -#define PokemonAutomation_PokemonBDSP_EncounterFilterOption_H - -//#include -#include "Common/Cpp/Options/BatchOption.h" -#include "PokemonBDSP_EncounterFilterOverride.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -#if 0 -class EncounterFilterOption : public ConfigOption{ -public: - EncounterFilterOption(bool enable_overrides); - - ShinyFilter shiny_filter() const{ return m_shiny_filter_current.load(std::memory_order_acquire); } - std::vector> copy_snapshot() const{ - return m_table.copy_snapshot(); - } - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class EncounterFilterWidget; - - const bool m_enable_overrides; - - const ShinyFilter m_shiny_filter_default; - std::atomic m_shiny_filter_current; - - EncounterFilterTable m_table; -}; -#endif - - - -class EncounterFilterOption2 : public BatchOption{ -public: - EncounterFilterOption2(bool enable_overrides); - -public: - EnumDropdownOption SHINY_FILTER; - EncounterFilterTable FILTER_TABLE; -}; - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterOption_H +#define PokemonAutomation_PokemonBDSP_EncounterFilterOption_H + +//#include +#include "Common/Cpp/Options/BatchOption.h" +#include "PokemonBDSP_EncounterFilterOverride.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +#if 0 +class EncounterFilterOption : public ConfigOption{ +public: + EncounterFilterOption(bool enable_overrides); + + ShinyFilter shiny_filter() const{ return m_shiny_filter_current.load(std::memory_order_acquire); } + std::vector> copy_snapshot() const{ + return m_table.copy_snapshot(); + } + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class EncounterFilterWidget; + + const bool m_enable_overrides; + + const ShinyFilter m_shiny_filter_default; + std::atomic m_shiny_filter_current; + + EncounterFilterTable m_table; +}; +#endif + + + +class EncounterFilterOption2 : public BatchOption{ +public: + EncounterFilterOption2(bool enable_overrides); + +public: + EnumDropdownOption SHINY_FILTER; + EncounterFilterTable FILTER_TABLE; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.cpp b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.cpp index 979ee51102..df4544f819 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.cpp @@ -1,160 +1,160 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokeballNames.h" -#include "PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h" -#include "PokemonBDSP_EncounterFilterEnums.h" -#include "PokemonBDSP_EncounterFilterOverride.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -bool EncounterActionFull::operator==(const EncounterActionFull& x) const{ - switch (action){ - case EncounterAction::StopProgram: - case EncounterAction::RunAway: - return action == x.action; - case EncounterAction::ThrowBalls: - case EncounterAction::ThrowBallsAndSave: - return action == x.action && pokeball_slug == x.pokeball_slug; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "EncounterActionFull: Invalid Enum " + std::to_string((int)action) - ); -} -bool EncounterActionFull::operator!=(const EncounterActionFull& x) const{ - return !(*this == x); -} -std::string EncounterActionFull::to_str() const{ - std::string str; - str += EncounterAction_NAMES[(size_t)action]; - if (action == EncounterAction::ThrowBalls || action == EncounterAction::ThrowBallsAndSave){ - str += " ("; - str += get_pokeball_name(pokeball_slug).display_name(); - str += ")"; - } - return str; -} - - - - - -EncounterFilterOverride::~EncounterFilterOverride(){ - action.remove_listener(*this); -} -EncounterFilterOverride::EncounterFilterOverride(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , pokemon(ALL_POKEMON_NAMES(), LockMode::UNLOCK_WHILE_RUNNING, "starly") - , ball_limit(LockMode::UNLOCK_WHILE_RUNNING, 40, 1, 999) -{ - PA_ADD_OPTION(pokemon); - PA_ADD_OPTION(shininess); - PA_ADD_OPTION(action); - PA_ADD_OPTION(pokeball); - PA_ADD_OPTION(ball_limit); - action.add_listener(*this); -} -void EncounterFilterOverride::load_json(const JsonValue& json){ - EditableTableRow::load_json(json); - - // Parse old format for backwards compatibility. - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - const JsonValue* value; - value = obj->get_value("Action"); - if (value != nullptr){ - action.load_json(*value); - } - value = obj->get_value("Ball"); - if (value != nullptr){ - pokeball.load_json(*value); - } - value = obj->get_value("Species"); - if (value != nullptr){ - pokemon.load_json(*value); - } - value = obj->get_value("ShinyFilter"); - if (value != nullptr){ - shininess.load_json(*value); - } -} -std::unique_ptr EncounterFilterOverride::clone() const{ - std::unique_ptr ret(new EncounterFilterOverride(parent())); - ret->action.set(action); - ret->pokeball.set_by_index(pokeball.index()); - ret->pokemon.set_by_index(pokemon.index()); - ret->shininess.set(shininess); - ret->ball_limit.set(ball_limit); - return ret; -} -void EncounterFilterOverride::on_config_value_changed(void* object){ - switch ((EncounterAction)action){ - case EncounterAction::StopProgram: - case EncounterAction::RunAway: - pokeball.set_visibility(ConfigOptionState::DISABLED); - break; - case EncounterAction::ThrowBalls: - case EncounterAction::ThrowBallsAndSave: - pokeball.set_visibility(ConfigOptionState::ENABLED); - break; - } -} - - - - - -EncounterFilterTable::EncounterFilterTable() - : EditableTableOption_t( - "Overrides:
" - "The game language must be properly set to read " + STRING_POKEMON + " names. " - "If multiple overrides apply and are conflicting, the program will stop." + - "
Auto-catching only applies in single battles. The program will stop if asked to auto-catch in a double-battle.", - LockMode::UNLOCK_WHILE_RUNNING - ) -{} -std::vector EncounterFilterTable::make_header() const{ - return std::vector{ - STRING_POKEMON, - "Shininess", - "Action", - STRING_POKEBALL, - "Ball Limit" - }; -} - - - - - - - - - - - - - - - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokeballNames.h" +#include "PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h" +#include "PokemonBDSP_EncounterFilterEnums.h" +#include "PokemonBDSP_EncounterFilterOverride.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +bool EncounterActionFull::operator==(const EncounterActionFull& x) const{ + switch (action){ + case EncounterAction::StopProgram: + case EncounterAction::RunAway: + return action == x.action; + case EncounterAction::ThrowBalls: + case EncounterAction::ThrowBallsAndSave: + return action == x.action && pokeball_slug == x.pokeball_slug; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "EncounterActionFull: Invalid Enum " + std::to_string((int)action) + ); +} +bool EncounterActionFull::operator!=(const EncounterActionFull& x) const{ + return !(*this == x); +} +std::string EncounterActionFull::to_str() const{ + std::string str; + str += EncounterAction_NAMES[(size_t)action]; + if (action == EncounterAction::ThrowBalls || action == EncounterAction::ThrowBallsAndSave){ + str += " ("; + str += get_pokeball_name(pokeball_slug).display_name(); + str += ")"; + } + return str; +} + + + + + +EncounterFilterOverride::~EncounterFilterOverride(){ + action.remove_listener(*this); +} +EncounterFilterOverride::EncounterFilterOverride(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , pokemon(ALL_POKEMON_NAMES(), LockMode::UNLOCK_WHILE_RUNNING, "starly") + , ball_limit(LockMode::UNLOCK_WHILE_RUNNING, 40, 1, 999) +{ + PA_ADD_OPTION(pokemon); + PA_ADD_OPTION(shininess); + PA_ADD_OPTION(action); + PA_ADD_OPTION(pokeball); + PA_ADD_OPTION(ball_limit); + action.add_listener(*this); +} +void EncounterFilterOverride::load_json(const JsonValue& json){ + EditableTableRow::load_json(json); + + // Parse old format for backwards compatibility. + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + const JsonValue* value; + value = obj->get_value("Action"); + if (value != nullptr){ + action.load_json(*value); + } + value = obj->get_value("Ball"); + if (value != nullptr){ + pokeball.load_json(*value); + } + value = obj->get_value("Species"); + if (value != nullptr){ + pokemon.load_json(*value); + } + value = obj->get_value("ShinyFilter"); + if (value != nullptr){ + shininess.load_json(*value); + } +} +std::unique_ptr EncounterFilterOverride::clone() const{ + std::unique_ptr ret(new EncounterFilterOverride(parent())); + ret->action.set(action); + ret->pokeball.set_by_index(pokeball.index()); + ret->pokemon.set_by_index(pokemon.index()); + ret->shininess.set(shininess); + ret->ball_limit.set(ball_limit); + return ret; +} +void EncounterFilterOverride::on_config_value_changed(void* object){ + switch ((EncounterAction)action){ + case EncounterAction::StopProgram: + case EncounterAction::RunAway: + pokeball.set_visibility(ConfigOptionState::DISABLED); + break; + case EncounterAction::ThrowBalls: + case EncounterAction::ThrowBallsAndSave: + pokeball.set_visibility(ConfigOptionState::ENABLED); + break; + } +} + + + + + +EncounterFilterTable::EncounterFilterTable() + : EditableTableOption_t( + "Overrides:
" + "The game language must be properly set to read " + STRING_POKEMON + " names. " + "If multiple overrides apply and are conflicting, the program will stop." + + "
Auto-catching only applies in single battles. The program will stop if asked to auto-catch in a double-battle.", + LockMode::UNLOCK_WHILE_RUNNING + ) +{} +std::vector EncounterFilterTable::make_header() const{ + return std::vector{ + STRING_POKEMON, + "Shininess", + "Action", + STRING_POKEBALL, + "Ball Limit" + }; +} + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.h b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.h index 4a295cb9e4..0e776df4af 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOverride.h @@ -1,64 +1,64 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterOverride_H -#define PokemonAutomation_PokemonBDSP_EncounterFilterOverride_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonBDSP_EncounterFilterEnums.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -struct EncounterActionFull{ - EncounterAction action; - std::string pokeball_slug; - uint16_t ball_limit = 999; - - bool operator==(const EncounterActionFull& x) const; - bool operator!=(const EncounterActionFull& x) const; - std::string to_str() const; -}; - - - -class EncounterFilterOverride : public EditableTableRow, private ConfigOption::Listener{ -public: - ~EncounterFilterOverride(); - EncounterFilterOverride(EditableTableOption& parent_table); - virtual void load_json(const JsonValue& json) override; - virtual std::unique_ptr clone() const override; - - virtual void on_config_value_changed(void* object) override; - -public: - StringSelectCell pokemon; - ShinyFilterCell shininess; - EncounterActionCell action; - PokemonSwSh::PokemonBallSelectCell pokeball; - SimpleIntegerCell ball_limit; -}; - -class EncounterFilterTable : public EditableTableOption_t{ -public: - EncounterFilterTable(); - virtual std::vector make_header() const override; -}; - - - - - - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterOverride_H +#define PokemonAutomation_PokemonBDSP_EncounterFilterOverride_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonBDSP_EncounterFilterEnums.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct EncounterActionFull{ + EncounterAction action; + std::string pokeball_slug; + uint16_t ball_limit = 999; + + bool operator==(const EncounterActionFull& x) const; + bool operator!=(const EncounterActionFull& x) const; + std::string to_str() const; +}; + + + +class EncounterFilterOverride : public EditableTableRow, private ConfigOption::Listener{ +public: + ~EncounterFilterOverride(); + EncounterFilterOverride(EditableTableOption& parent_table); + virtual void load_json(const JsonValue& json) override; + virtual std::unique_ptr clone() const override; + + virtual void on_config_value_changed(void* object) override; + +public: + StringSelectCell pokemon; + ShinyFilterCell shininess; + EncounterActionCell action; + PokemonSwSh::PokemonBallSelectCell pokeball; + SimpleIntegerCell ball_limit; +}; + +class EncounterFilterTable : public EditableTableOption_t{ +public: + EncounterFilterTable(); + virtual std::vector make_header() const override; +}; + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.cpp b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.cpp index ebcf16b9c2..2f2801f352 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.cpp @@ -1,93 +1,93 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Qt/NoWheelComboBox.h" -#include "PokemonBDSP_EncounterFilterEnums.h" -#include "PokemonBDSP_EncounterFilterWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -#if 0 -EncounterFilterWidget::EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); -// QLabel* text = new QLabel(value.label(), this); -// layout->addWidget(text); - - { -// QWidget* widget = new QWidget(this); - - QHBoxLayout* hbox = new QHBoxLayout(); - layout->addLayout(hbox); - hbox->addWidget(new QLabel("Stop on:")); - - m_shininess = new NoWheelComboBox(this); - hbox->addWidget(m_shininess); - for (const std::string& item : ShinyFilter_NAMES){ - m_shininess->addItem(QString::fromStdString(item)); - } - ShinyFilter current = m_value.m_shiny_filter_current.load(std::memory_order_acquire); - for (int c = 0; c < m_shininess->count(); c++){ - if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ - m_shininess->setCurrentIndex(c); - break; - } - } - connect( - m_shininess, static_cast(&QComboBox::currentIndexChanged), - this, [this](int index){ - if (index < 0){ - return; - } - - std::string text = m_shininess->itemText(index).toStdString(); - auto iter = ShinyFilter_MAP.find(text); - if (iter == ShinyFilter_MAP.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid option: " + text); - } - m_value.m_shiny_filter_current.store(iter->second, std::memory_order_release); - } - ); - } - - if (m_value.m_enable_overrides){ - layout->addSpacing(5); - m_table = value.m_table.make_QtWidget(*this); - layout->addWidget(&m_table->widget()); - } -} -void EncounterFilterWidget::update_value(){ - ShinyFilter current = m_value.m_shiny_filter_current.load(std::memory_order_acquire); - for (int c = 0; c < m_shininess->count(); c++){ - if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ - m_shininess->setCurrentIndex(c); - break; - } - } -} -void EncounterFilterWidget::update_visibility(){ - ConfigWidget::update_visibility(); - if (m_table){ - m_table->update_visibility(); - } -} -#endif - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Qt/NoWheelComboBox.h" +#include "PokemonBDSP_EncounterFilterEnums.h" +#include "PokemonBDSP_EncounterFilterWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +#if 0 +EncounterFilterWidget::EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); +// QLabel* text = new QLabel(value.label(), this); +// layout->addWidget(text); + + { +// QWidget* widget = new QWidget(this); + + QHBoxLayout* hbox = new QHBoxLayout(); + layout->addLayout(hbox); + hbox->addWidget(new QLabel("Stop on:")); + + m_shininess = new NoWheelComboBox(this); + hbox->addWidget(m_shininess); + for (const std::string& item : ShinyFilter_NAMES){ + m_shininess->addItem(QString::fromStdString(item)); + } + ShinyFilter current = m_value.m_shiny_filter_current.load(std::memory_order_acquire); + for (int c = 0; c < m_shininess->count(); c++){ + if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ + m_shininess->setCurrentIndex(c); + break; + } + } + connect( + m_shininess, static_cast(&QComboBox::currentIndexChanged), + this, [this](int index){ + if (index < 0){ + return; + } + + std::string text = m_shininess->itemText(index).toStdString(); + auto iter = ShinyFilter_MAP.find(text); + if (iter == ShinyFilter_MAP.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid option: " + text); + } + m_value.m_shiny_filter_current.store(iter->second, std::memory_order_release); + } + ); + } + + if (m_value.m_enable_overrides){ + layout->addSpacing(5); + m_table = value.m_table.make_QtWidget(*this); + layout->addWidget(&m_table->widget()); + } +} +void EncounterFilterWidget::update_value(){ + ShinyFilter current = m_value.m_shiny_filter_current.load(std::memory_order_acquire); + for (int c = 0; c < m_shininess->count(); c++){ + if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ + m_shininess->setCurrentIndex(c); + break; + } + } +} +void EncounterFilterWidget::update_visibility(){ + ConfigWidget::update_visibility(); + if (m_table){ + m_table->update_visibility(); + } +} +#endif + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.h b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.h index 4c8d996950..f901fd41f4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterWidget.h @@ -1,39 +1,39 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterWidget_H -#define PokemonAutomation_PokemonBDSP_EncounterFilterWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "PokemonBDSP_EncounterFilterOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -#if 0 -class EncounterFilterWidget : public QWidget, public ConfigWidget{ -public: - EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value); - - virtual void update_value() override; - virtual void update_visibility() override; - -private: - EncounterFilterOption& m_value; - - QComboBox* m_shininess = nullptr; - ConfigWidget* m_table = nullptr; -}; -#endif - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterFilterWidget_H +#define PokemonAutomation_PokemonBDSP_EncounterFilterWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "PokemonBDSP_EncounterFilterOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +#if 0 +class EncounterFilterWidget : public QWidget, public ConfigWidget{ +public: + EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value); + + virtual void update_value() override; + virtual void update_visibility() override; + +private: + EncounterFilterOption& m_value; + + QComboBox* m_shininess = nullptr; + ConfigWidget* m_table = nullptr; +}; +#endif + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.cpp index bf5e41572f..53bf09dc4e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.cpp @@ -1,54 +1,54 @@ -/* Berry Selector, UI component to select multiple berries - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_BerryNames.h" -#include "Pokemon/Resources/Pokemon_BerrySprites.h" -#include "PokemonBDSP_BerrySelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -StringSelectDatabase make_all_berries_database(){ - StringSelectDatabase ret; - for (const auto& slug : BERRY_SLUGS()){ - const BerryNames& data = get_berry_name(slug); - const SpriteDatabase::Sprite* sprite = ALL_BERRY_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); - } - } - return ret; -} -const StringSelectDatabase& ALL_BERRYS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_all_berries_database(); - return database; -} - - - - -BerrySelectCell::BerrySelectCell( - const std::string& default_slug -) - : StringSelectCell( - ALL_BERRYS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - -} -} -} +/* Berry Selector, UI component to select multiple berries + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_BerryNames.h" +#include "Pokemon/Resources/Pokemon_BerrySprites.h" +#include "PokemonBDSP_BerrySelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +StringSelectDatabase make_all_berries_database(){ + StringSelectDatabase ret; + for (const auto& slug : BERRY_SLUGS()){ + const BerryNames& data = get_berry_name(slug); + const SpriteDatabase::Sprite* sprite = ALL_BERRY_SPRITES().get_nothrow(slug); + if (sprite == nullptr){ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + } + } + return ret; +} +const StringSelectDatabase& ALL_BERRYS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_all_berries_database(); + return database; +} + + + + +BerrySelectCell::BerrySelectCell( + const std::string& default_slug +) + : StringSelectCell( + ALL_BERRYS_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.h index b863b0ba69..a5ac271ecc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerrySelectOption.h @@ -1,29 +1,29 @@ -/* Berry Selector, UI component to select multiple berries - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BerrySelectOption_H -#define PokemonAutomation_PokemonBDSP_BerrySelectOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class BerrySelectCell : public StringSelectCell{ -public: - BerrySelectCell(const std::string& default_slug); -}; - - - - -} -} -} -#endif +/* Berry Selector, UI component to select multiple berries + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BerrySelectOption_H +#define PokemonAutomation_PokemonBDSP_BerrySelectOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class BerrySelectCell : public StringSelectCell{ +public: + BerrySelectCell(const std::string& default_slug); +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.cpp index 56f75dac88..2b5ce528a6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.cpp @@ -1,96 +1,96 @@ -/* Berry Selector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Resources/Pokemon_BerryNames.h" -#include "PokemonBDSP_BerryTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - - -BerrySelectorRow2::BerrySelectorRow2(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , berry("cheri-berry") -{ - PA_ADD_OPTION(berry); -} -std::unique_ptr BerrySelectorRow2::clone() const{ - std::unique_ptr ret(new BerrySelectorRow2(parent())); - ret->berry.set_by_index(berry.index()); - return ret; -} - - - - - -BerryTable::BerryTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - - - -bool BerryTable::find_berry(const std::string& berry_slug) const{ - std::vector> table = copy_snapshot(); - for (const std::unique_ptr& row : table){ - if (row->berry.slug() == berry_slug){ - return true; - } - } - return false; -} - -std::vector BerryTable::selected_berries() const{ - std::vector> table = copy_snapshot(); - std::vector slugs; - for (const std::unique_ptr& row : table){ - slugs.emplace_back(row->berry.slug()); - } - return slugs; -} - - - - -std::vector BerryTable::make_header() const{ - return std::vector{ - "Berry", - }; -} - -std::vector> BerryTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} - - - - - - - - - - - - - - - - - -} -} -} +/* Berry Selector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Resources/Pokemon_BerryNames.h" +#include "PokemonBDSP_BerryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + + +BerrySelectorRow2::BerrySelectorRow2(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , berry("cheri-berry") +{ + PA_ADD_OPTION(berry); +} +std::unique_ptr BerrySelectorRow2::clone() const{ + std::unique_ptr ret(new BerrySelectorRow2(parent())); + ret->berry.set_by_index(berry.index()); + return ret; +} + + + + + +BerryTable::BerryTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + + + +bool BerryTable::find_berry(const std::string& berry_slug) const{ + std::vector> table = copy_snapshot(); + for (const std::unique_ptr& row : table){ + if (row->berry.slug() == berry_slug){ + return true; + } + } + return false; +} + +std::vector BerryTable::selected_berries() const{ + std::vector> table = copy_snapshot(); + std::vector slugs; + for (const std::unique_ptr& row : table){ + slugs.emplace_back(row->berry.slug()); + } + return slugs; +} + + + + +std::vector BerryTable::make_header() const{ + return std::vector{ + "Berry", + }; +} + +std::vector> BerryTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.h index 33a13aae5b..90bc3f7293 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_BerryTable.h @@ -1,52 +1,52 @@ -/* Berry Selector, UI component to select multiple berries - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BerrySelector_H -#define PokemonAutomation_PokemonBDSP_BerrySelector_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonBDSP_BerrySelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class BerrySelectorRow2 : public EditableTableRow{ -public: - BerrySelectorRow2(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const; - -public: - BerrySelectCell berry; -}; - - - -class BerryTable : public EditableTableOption_t{ -public: - BerryTable(std::string label); - - - // Whether berry_slug is among the selected berries. - bool find_berry(const std::string& berry_slug) const; - // Return the berry slugs that the user has selected via the berry table UI. - std::vector selected_berries() const; - - virtual std::vector make_header() const; - - std::vector> make_defaults(); -}; - - - - - -} -} -} -#endif +/* Berry Selector, UI component to select multiple berries + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BerrySelector_H +#define PokemonAutomation_PokemonBDSP_BerrySelector_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonBDSP_BerrySelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class BerrySelectorRow2 : public EditableTableRow{ +public: + BerrySelectorRow2(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const; + +public: + BerrySelectCell berry; +}; + + + +class BerryTable : public EditableTableOption_t{ +public: + BerryTable(std::string label); + + + // Whether berry_slug is among the selected berries. + bool find_berry(const std::string& berry_slug) const; + // Return the berry slugs that the user has selected via the berry table UI. + std::vector selected_berries() const; + + virtual std::vector make_header() const; + + std::vector> make_defaults(); +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.cpp index 8a08e4df17..00a488bd35 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.cpp @@ -1,183 +1,183 @@ -/* Egg Hatch Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h" -#include "PokemonBDSP_EggHatchFilter.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - - -const EnumDatabase& EggHatchAction_Database(){ - static const EnumDatabase database({ - {EggHatchAction::StopProgram, "stop", "Stop Program"}, - {EggHatchAction::Keep, "keep", "Keep"}, -// {EggHatchAction::Release, "release", "Release"}, - }); - return database; -} -const EnumDatabase& EggHatchShinyFilter_Database(){ - static const EnumDatabase database({ - {EggHatchShinyFilter::Anything, "anything", "Anything"}, - {EggHatchShinyFilter::NotShiny, "not-shiny", "Not Shiny"}, - {EggHatchShinyFilter::Shiny, "shiny", "Shiny"}, - }); - return database; -} -const EnumDatabase& EggHatchGenderFilter_Database(){ - static const EnumDatabase database({ - {EggHatchGenderFilter::Any, "any", "Any"}, - {EggHatchGenderFilter::Male, "male", "Male"}, - {EggHatchGenderFilter::Female, "female", "Female"}, -// {EggHatchGenderFilter::Genderless, "genderless", "Genderless"}, - }); - return database; -} - - - - -EggHatchFilterRow::EggHatchFilterRow() - : action(EggHatchAction_Database(), EggHatchAction::Keep) - , shiny(EggHatchShinyFilter_Database(), EggHatchShinyFilter::Anything) - , gender(EggHatchGenderFilter_Database(), EggHatchGenderFilter::Any) - , iv_hp(IVCheckerFilter::Anything) - , iv_atk(IVCheckerFilter::Anything) - , iv_def(IVCheckerFilter::Anything) - , iv_spatk(IVCheckerFilter::Anything) - , iv_spdef(IVCheckerFilter::Anything) - , iv_speed(IVCheckerFilter::Anything) -{ - PA_ADD_OPTION(action); - PA_ADD_OPTION(shiny); - PA_ADD_OPTION(gender); - PA_ADD_OPTION(iv_hp); - PA_ADD_OPTION(iv_atk); - PA_ADD_OPTION(iv_def); - PA_ADD_OPTION(iv_spatk); - PA_ADD_OPTION(iv_spdef); - PA_ADD_OPTION(iv_speed); -} -EggHatchFilterRow::EggHatchFilterRow(EggHatchShinyFilter p_shiny) - : EggHatchFilterRow() -{ - shiny.set(p_shiny); -} -std::unique_ptr EggHatchFilterRow::clone() const{ - std::unique_ptr ret(new EggHatchFilterRow()); - ret->action.set(action); - ret->shiny.set(shiny); - ret->gender.set(gender); - ret->iv_hp.set(iv_hp); - ret->iv_atk.set(iv_atk); - ret->iv_def.set(iv_def); - ret->iv_spatk.set(iv_spatk); - ret->iv_spdef.set(iv_spdef); - ret->iv_speed.set(iv_speed); - return ret; -} - - - - - -EggHatchFilterTable::EggHatchFilterTable() - : EditableTableOption_t( - "Actions Table:
" - "If a hatchling matches one of these filters, the specified action will be performed. " - "Otherwise, it will be released. " - "If multiple entries apply and have conflicting actions, the program will stop.
" - "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above.", - make_defaults() - ) -{} -std::vector EggHatchFilterTable::make_header() const{ - return std::vector{ - "Action", - "Shininess", - "Gender", - "HP", - "Attack", - "Defense", - "Sp. Attack", - "Sp. Defense", - "Speed", - }; -} -std::vector> EggHatchFilterTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(new EggHatchFilterRow(EggHatchShinyFilter::Shiny)); - return ret; -} - - -EggHatchAction EggHatchFilterTable::get_action(bool shiny, const IVCheckerReader::Results& IVs, EggHatchGenderFilter gender) const{ - EggHatchAction action = EggHatchAction::Release; - std::vector> list = copy_snapshot(); - for (size_t c = 0; c < list.size(); c++){ - const EggHatchFilterRow& filter = *list[c]; - - // Check the shiny filter. - switch (filter.shiny){ - case EggHatchShinyFilter::Anything: - break; - case EggHatchShinyFilter::NotShiny: - if (shiny){ - continue; - } - break; - case EggHatchShinyFilter::Shiny: - if (!shiny){ - continue; - } - break; - } - - // Check all the IV filters. - if (!IVChecker_filter_match(filter.iv_hp, IVs.hp)) continue; - if (!IVChecker_filter_match(filter.iv_atk, IVs.attack)) continue; - if (!IVChecker_filter_match(filter.iv_def, IVs.defense)) continue; - if (!IVChecker_filter_match(filter.iv_spatk, IVs.spatk)) continue; - if (!IVChecker_filter_match(filter.iv_spdef, IVs.spdef)) continue; - if (!IVChecker_filter_match(filter.iv_speed, IVs.speed)) continue; - - EggHatchGenderFilter filter_gender = filter.gender; - if(filter_gender != gender && filter_gender != EggHatchGenderFilter::Any){ - continue; - } - - EggHatchAction filter_action = filter.action; - - // No action matched so far. Take the current action and continue. - if (action == EggHatchAction::Release){ - action = filter_action; - continue; - } - - // Conflicting actions. - if (action != filter_action){ - global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); - return EggHatchAction::StopProgram; - } - } - return action; -} - - - - - -} -} -} +/* Egg Hatch Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h" +#include "PokemonBDSP_EggHatchFilter.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + + +const EnumDatabase& EggHatchAction_Database(){ + static const EnumDatabase database({ + {EggHatchAction::StopProgram, "stop", "Stop Program"}, + {EggHatchAction::Keep, "keep", "Keep"}, +// {EggHatchAction::Release, "release", "Release"}, + }); + return database; +} +const EnumDatabase& EggHatchShinyFilter_Database(){ + static const EnumDatabase database({ + {EggHatchShinyFilter::Anything, "anything", "Anything"}, + {EggHatchShinyFilter::NotShiny, "not-shiny", "Not Shiny"}, + {EggHatchShinyFilter::Shiny, "shiny", "Shiny"}, + }); + return database; +} +const EnumDatabase& EggHatchGenderFilter_Database(){ + static const EnumDatabase database({ + {EggHatchGenderFilter::Any, "any", "Any"}, + {EggHatchGenderFilter::Male, "male", "Male"}, + {EggHatchGenderFilter::Female, "female", "Female"}, +// {EggHatchGenderFilter::Genderless, "genderless", "Genderless"}, + }); + return database; +} + + + + +EggHatchFilterRow::EggHatchFilterRow() + : action(EggHatchAction_Database(), EggHatchAction::Keep) + , shiny(EggHatchShinyFilter_Database(), EggHatchShinyFilter::Anything) + , gender(EggHatchGenderFilter_Database(), EggHatchGenderFilter::Any) + , iv_hp(IVCheckerFilter::Anything) + , iv_atk(IVCheckerFilter::Anything) + , iv_def(IVCheckerFilter::Anything) + , iv_spatk(IVCheckerFilter::Anything) + , iv_spdef(IVCheckerFilter::Anything) + , iv_speed(IVCheckerFilter::Anything) +{ + PA_ADD_OPTION(action); + PA_ADD_OPTION(shiny); + PA_ADD_OPTION(gender); + PA_ADD_OPTION(iv_hp); + PA_ADD_OPTION(iv_atk); + PA_ADD_OPTION(iv_def); + PA_ADD_OPTION(iv_spatk); + PA_ADD_OPTION(iv_spdef); + PA_ADD_OPTION(iv_speed); +} +EggHatchFilterRow::EggHatchFilterRow(EggHatchShinyFilter p_shiny) + : EggHatchFilterRow() +{ + shiny.set(p_shiny); +} +std::unique_ptr EggHatchFilterRow::clone() const{ + std::unique_ptr ret(new EggHatchFilterRow()); + ret->action.set(action); + ret->shiny.set(shiny); + ret->gender.set(gender); + ret->iv_hp.set(iv_hp); + ret->iv_atk.set(iv_atk); + ret->iv_def.set(iv_def); + ret->iv_spatk.set(iv_spatk); + ret->iv_spdef.set(iv_spdef); + ret->iv_speed.set(iv_speed); + return ret; +} + + + + + +EggHatchFilterTable::EggHatchFilterTable() + : EditableTableOption_t( + "Actions Table:
" + "If a hatchling matches one of these filters, the specified action will be performed. " + "Otherwise, it will be released. " + "If multiple entries apply and have conflicting actions, the program will stop.
" + "IV checking requires that your right panel be set to the IV Judge and that you have selected the correct game language above.", + make_defaults() + ) +{} +std::vector EggHatchFilterTable::make_header() const{ + return std::vector{ + "Action", + "Shininess", + "Gender", + "HP", + "Attack", + "Defense", + "Sp. Attack", + "Sp. Defense", + "Speed", + }; +} +std::vector> EggHatchFilterTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(new EggHatchFilterRow(EggHatchShinyFilter::Shiny)); + return ret; +} + + +EggHatchAction EggHatchFilterTable::get_action(bool shiny, const IVCheckerReader::Results& IVs, EggHatchGenderFilter gender) const{ + EggHatchAction action = EggHatchAction::Release; + std::vector> list = copy_snapshot(); + for (size_t c = 0; c < list.size(); c++){ + const EggHatchFilterRow& filter = *list[c]; + + // Check the shiny filter. + switch (filter.shiny){ + case EggHatchShinyFilter::Anything: + break; + case EggHatchShinyFilter::NotShiny: + if (shiny){ + continue; + } + break; + case EggHatchShinyFilter::Shiny: + if (!shiny){ + continue; + } + break; + } + + // Check all the IV filters. + if (!IVChecker_filter_match(filter.iv_hp, IVs.hp)) continue; + if (!IVChecker_filter_match(filter.iv_atk, IVs.attack)) continue; + if (!IVChecker_filter_match(filter.iv_def, IVs.defense)) continue; + if (!IVChecker_filter_match(filter.iv_spatk, IVs.spatk)) continue; + if (!IVChecker_filter_match(filter.iv_spdef, IVs.spdef)) continue; + if (!IVChecker_filter_match(filter.iv_speed, IVs.speed)) continue; + + EggHatchGenderFilter filter_gender = filter.gender; + if(filter_gender != gender && filter_gender != EggHatchGenderFilter::Any){ + continue; + } + + EggHatchAction filter_action = filter.action; + + // No action matched so far. Take the current action and continue. + if (action == EggHatchAction::Release){ + action = filter_action; + continue; + } + + // Conflicting actions. + if (action != filter_action){ + global_logger_tagged().log("Multiple filters matched with conflicting actions. Stopping program...", COLOR_RED); + return EggHatchAction::StopProgram; + } + } + return action; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.h index 27d7d8f8c4..b1e16ba77f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggHatchFilter.h @@ -1,83 +1,83 @@ -/* Egg Hatch Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggHatchFilter_H -#define PokemonAutomation_PokemonBDSP_EggHatchFilter_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Pokemon/Pokemon_IVChecker.h" -#include "Pokemon/Options/Pokemon_IVCheckerOption.h" -#include "Pokemon/Inference/Pokemon_IVCheckerReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ -using namespace Pokemon; - - -enum class EggHatchAction{ - StopProgram, - Keep, - Release, -}; - -enum class EggHatchShinyFilter{ - Anything, - NotShiny, - Shiny, -}; - -enum class EggHatchGenderFilter{ - Any, - Male, - Female, - Genderless -}; - - - - -class EggHatchFilterRow : public EditableTableRow{ -public: - EggHatchFilterRow(); - EggHatchFilterRow(EggHatchShinyFilter p_shiny); - virtual std::unique_ptr clone() const override; - -public: - EnumDropdownCell action; - EnumDropdownCell shiny; - EnumDropdownCell gender; - IVCheckerFilterCell iv_hp; - IVCheckerFilterCell iv_atk; - IVCheckerFilterCell iv_def; - IVCheckerFilterCell iv_spatk; - IVCheckerFilterCell iv_spdef; - IVCheckerFilterCell iv_speed; -}; - -class EggHatchFilterTable : public EditableTableOption_t{ -public: - EggHatchFilterTable(); - virtual std::vector make_header() const override; - static std::vector> make_defaults(); - - EggHatchAction get_action(bool shiny, const IVCheckerReader::Results& IVs, EggHatchGenderFilter gender) const; -}; - - - - - - - - - - -} -} -} -#endif +/* Egg Hatch Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggHatchFilter_H +#define PokemonAutomation_PokemonBDSP_EggHatchFilter_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Pokemon/Pokemon_IVChecker.h" +#include "Pokemon/Options/Pokemon_IVCheckerOption.h" +#include "Pokemon/Inference/Pokemon_IVCheckerReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ +using namespace Pokemon; + + +enum class EggHatchAction{ + StopProgram, + Keep, + Release, +}; + +enum class EggHatchShinyFilter{ + Anything, + NotShiny, + Shiny, +}; + +enum class EggHatchGenderFilter{ + Any, + Male, + Female, + Genderless +}; + + + + +class EggHatchFilterRow : public EditableTableRow{ +public: + EggHatchFilterRow(); + EggHatchFilterRow(EggHatchShinyFilter p_shiny); + virtual std::unique_ptr clone() const override; + +public: + EnumDropdownCell action; + EnumDropdownCell shiny; + EnumDropdownCell gender; + IVCheckerFilterCell iv_hp; + IVCheckerFilterCell iv_atk; + IVCheckerFilterCell iv_def; + IVCheckerFilterCell iv_spatk; + IVCheckerFilterCell iv_spdef; + IVCheckerFilterCell iv_speed; +}; + +class EggHatchFilterTable : public EditableTableOption_t{ +public: + EggHatchFilterTable(); + virtual std::vector make_header() const override; + static std::vector> make_defaults(); + + EggHatchAction get_action(bool shiny, const IVCheckerReader::Results& IVs, EggHatchGenderFilter gender) const; +}; + + + + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.cpp index 58df74813b..3952f60e5d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.cpp @@ -1,43 +1,43 @@ -/* Egg Step Count Dropdown - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Resources/Pokemon_EggSteps.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "PokemonBDSP_EggStepOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - - - -const Pokemon::EggStepDatabase& EGGSTEP_DATABASE(){ - static Pokemon::EggStepDatabase database("PokemonBDSP/EggSteps.json", &PokemonSwSh::ALL_POKEMON_SPRITES()); - return database; -} - - - -EggStepCountOption::EggStepCountOption() - : StringSelectOption( - "Step Count:", - EGGSTEP_DATABASE().database(), - LockMode::LOCK_WHILE_RUNNING, - "turtwig" - ) -{} - -EggStepCountOption::operator uint16_t() const{ - return (uint16_t)EGGSTEP_DATABASE().step_count(this->slug()); -} - - - -} -} -} +/* Egg Step Count Dropdown + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Resources/Pokemon_EggSteps.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "PokemonBDSP_EggStepOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + + + +const Pokemon::EggStepDatabase& EGGSTEP_DATABASE(){ + static Pokemon::EggStepDatabase database("PokemonBDSP/EggSteps.json", &PokemonSwSh::ALL_POKEMON_SPRITES()); + return database; +} + + + +EggStepCountOption::EggStepCountOption() + : StringSelectOption( + "Step Count:", + EGGSTEP_DATABASE().database(), + LockMode::LOCK_WHILE_RUNNING, + "turtwig" + ) +{} + +EggStepCountOption::operator uint16_t() const{ + return (uint16_t)EGGSTEP_DATABASE().step_count(this->slug()); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.h index 652e10a8ea..6a5c7fbff4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EggStepOption.h @@ -1,33 +1,33 @@ -/* Egg Step Count Dropdown - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggStepOption_H -#define PokemonAutomation_PokemonBDSP_EggStepOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - - - -class EggStepCountOption : public StringSelectOption{ -public: - EggStepCountOption(); - - operator uint16_t() const; -}; - - - -} -} -} -#endif - +/* Egg Step Count Dropdown + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggStepOption_H +#define PokemonAutomation_PokemonBDSP_EggStepOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + + + +class EggStepCountOption : public StringSelectOption{ +public: + EggStepCountOption(); + + operator uint16_t() const; +}; + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h index 7fa1418322..aaa5f8858b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h @@ -1,81 +1,81 @@ -/* Encounter Bot Common - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterBotCommon_H -#define PokemonAutomation_PokemonBDSP_EncounterBotCommon_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -//#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "EncounterFilter/PokemonBDSP_EncounterFilterOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class EncounterBotCommonOptions : public BatchOption{ -public: - EncounterBotCommonOptions(bool enable_overrides) - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , USE_SOUND_DETECTION( - "Use Sound Detection:
Use sound to improve shiny detection.
" - "Make sure you have correct audio input set.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , FILTER(enable_overrides) - , VIDEO_ON_SHINY( - "Video Capture:
Take a video of the encounter if it is shiny.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_CATCH_SUCCESS( - "Catch Success", - true, false, - {"Notifs"} - ) - , NOTIFICATION_CATCH_FAILED( - "Catch Failed", - true, true, - {"Notifs"} - ) - { - PA_ADD_OPTION(USE_SOUND_DETECTION); - PA_ADD_OPTION(FILTER); - PA_ADD_OPTION(VIDEO_ON_SHINY); - } - - BooleanCheckBoxOption USE_SOUND_DETECTION; - EncounterFilterOption2 FILTER; - BooleanCheckBoxOption VIDEO_ON_SHINY; - - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; -}; - - - - -} -} -} -#endif +/* Encounter Bot Common + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterBotCommon_H +#define PokemonAutomation_PokemonBDSP_EncounterBotCommon_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +//#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "EncounterFilter/PokemonBDSP_EncounterFilterOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class EncounterBotCommonOptions : public BatchOption{ +public: + EncounterBotCommonOptions(bool enable_overrides) + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , USE_SOUND_DETECTION( + "Use Sound Detection:
Use sound to improve shiny detection.
" + "Make sure you have correct audio input set.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , FILTER(enable_overrides) + , VIDEO_ON_SHINY( + "Video Capture:
Take a video of the encounter if it is shiny.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_CATCH_SUCCESS( + "Catch Success", + true, false, + {"Notifs"} + ) + , NOTIFICATION_CATCH_FAILED( + "Catch Failed", + true, true, + {"Notifs"} + ) + { + PA_ADD_OPTION(USE_SOUND_DETECTION); + PA_ADD_OPTION(FILTER); + PA_ADD_OPTION(VIDEO_ON_SHINY); + } + + BooleanCheckBoxOption USE_SOUND_DETECTION; + EncounterFilterOption2 FILTER; + BooleanCheckBoxOption VIDEO_ON_SHINY; + + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h index 6acadcf67f..9ca33616e5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_LearnMove.h @@ -1,42 +1,42 @@ -/* Learn Move - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_LearnMove_H -#define PokemonAutomation_PokemonBDSP_LearnMove_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -enum class OnLearnMove{ - DONT_LEARN, - STOP_PROGRAM, -}; - -class OnLearnMoveOption : public EnumDropdownOption{ -public: - OnLearnMoveOption() - : EnumDropdownOption( - "On Learn Move:", - { - {OnLearnMove::DONT_LEARN, "skip", "Don't learn moves."}, - {OnLearnMove::STOP_PROGRAM, "stop-program", "Stop Program"}, - }, - LockMode::LOCK_WHILE_RUNNING, - OnLearnMove::DONT_LEARN - ) - {} -}; - - - -} -} -} -#endif +/* Learn Move + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_LearnMove_H +#define PokemonAutomation_PokemonBDSP_LearnMove_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +enum class OnLearnMove{ + DONT_LEARN, + STOP_PROGRAM, +}; + +class OnLearnMoveOption : public EnumDropdownOption{ +public: + OnLearnMoveOption() + : EnumDropdownOption( + "On Learn Move:", + { + {OnLearnMove::DONT_LEARN, "skip", "Don't learn moves."}, + {OnLearnMove::STOP_PROGRAM, "stop-program", "Stop Program"}, + }, + LockMode::LOCK_WHILE_RUNNING, + OnLearnMove::DONT_LEARN + ) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp index 7033e23034..5b1155a0c1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.cpp @@ -1,72 +1,72 @@ -/* Shortcut Direction - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP_ShortcutDirection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -const EnumDropdownDatabase& ShortcutDirection_Nullable(){ - static EnumDropdownDatabase database({ - {ShortcutDirection::NONE, "none", "None"}, - {ShortcutDirection::UP, "up", "Up"}, - {ShortcutDirection::RIGHT, "right", "Right"}, - {ShortcutDirection::DOWN, "down", "Down"}, - {ShortcutDirection::LEFT, "left", "Left"}, - }); - return database; -} -const EnumDropdownDatabase& ShortcutDirection_Required(){ - static EnumDropdownDatabase database({ - {ShortcutDirection::UP, "up", "Up"}, - {ShortcutDirection::RIGHT, "right", "Right"}, - {ShortcutDirection::DOWN, "down", "Down"}, - {ShortcutDirection::LEFT, "left", "Left"}, - }); - return database; -} - - - -ShortcutDirectionOption::ShortcutDirectionOption(std::string label) - : EnumDropdownOption( - std::move(label), - ShortcutDirection_Nullable(), - LockMode::LOCK_WHILE_RUNNING, - ShortcutDirection::NONE - ) -{} - -void ShortcutDirectionOption::run(ProControllerContext& context, uint16_t delay){ - uint8_t shortcut_x = 128; - uint8_t shortcut_y = 128; - switch (this->get()){ - case ShortcutDirection::NONE: - pbf_press_button(context, BUTTON_PLUS, 20, 105); - return; - case ShortcutDirection::UP: shortcut_y = 0; break; - case ShortcutDirection::RIGHT: shortcut_x = 255; break; - case ShortcutDirection::DOWN: shortcut_y = 255; break; - case ShortcutDirection::LEFT: shortcut_x = 0; break; - default: - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Invalid shortcut value: " + std::to_string(current_value()) - ); - } - - pbf_mash_button(context, BUTTON_PLUS, 125); - pbf_move_right_joystick(context, shortcut_x, shortcut_y, 20, delay); -} - - -} -} -} +/* Shortcut Direction + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_ShortcutDirection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +const EnumDropdownDatabase& ShortcutDirection_Nullable(){ + static EnumDropdownDatabase database({ + {ShortcutDirection::NONE, "none", "None"}, + {ShortcutDirection::UP, "up", "Up"}, + {ShortcutDirection::RIGHT, "right", "Right"}, + {ShortcutDirection::DOWN, "down", "Down"}, + {ShortcutDirection::LEFT, "left", "Left"}, + }); + return database; +} +const EnumDropdownDatabase& ShortcutDirection_Required(){ + static EnumDropdownDatabase database({ + {ShortcutDirection::UP, "up", "Up"}, + {ShortcutDirection::RIGHT, "right", "Right"}, + {ShortcutDirection::DOWN, "down", "Down"}, + {ShortcutDirection::LEFT, "left", "Left"}, + }); + return database; +} + + + +ShortcutDirectionOption::ShortcutDirectionOption(std::string label) + : EnumDropdownOption( + std::move(label), + ShortcutDirection_Nullable(), + LockMode::LOCK_WHILE_RUNNING, + ShortcutDirection::NONE + ) +{} + +void ShortcutDirectionOption::run(ProControllerContext& context, uint16_t delay){ + uint8_t shortcut_x = 128; + uint8_t shortcut_y = 128; + switch (this->get()){ + case ShortcutDirection::NONE: + pbf_press_button(context, BUTTON_PLUS, 20, 105); + return; + case ShortcutDirection::UP: shortcut_y = 0; break; + case ShortcutDirection::RIGHT: shortcut_x = 255; break; + case ShortcutDirection::DOWN: shortcut_y = 255; break; + case ShortcutDirection::LEFT: shortcut_x = 0; break; + default: + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Invalid shortcut value: " + std::to_string(current_value()) + ); + } + + pbf_mash_button(context, BUTTON_PLUS, 125); + pbf_move_right_joystick(context, shortcut_x, shortcut_y, 20, delay); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h index 3e018506a0..ae4d4c5d6b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h +++ b/SerialPrograms/Source/PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h @@ -1,44 +1,44 @@ -/* Shortcut Direction - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -#ifndef PokemonAutomation_PokemonBDSP_ShortcutDirection_H -#define PokemonAutomation_PokemonBDSP_ShortcutDirection_H - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -enum class ShortcutDirection{ - NONE, - UP, - RIGHT, - DOWN, - LEFT, -}; -const EnumDropdownDatabase& ShortcutDirection_Nullable(); -const EnumDropdownDatabase& ShortcutDirection_Required(); - - - -class ShortcutDirectionOption : public EnumDropdownOption{ -public: - ShortcutDirectionOption(std::string label); - - void run(ProControllerContext& context, uint16_t delay); - -}; - - - -} -} -} -#endif +/* Shortcut Direction + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +#ifndef PokemonAutomation_PokemonBDSP_ShortcutDirection_H +#define PokemonAutomation_PokemonBDSP_ShortcutDirection_H + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +enum class ShortcutDirection{ + NONE, + UP, + RIGHT, + DOWN, + LEFT, +}; +const EnumDropdownDatabase& ShortcutDirection_Nullable(); +const EnumDropdownDatabase& ShortcutDirection_Required(); + + + +class ShortcutDirectionOption : public EnumDropdownOption{ +public: + ShortcutDirectionOption(std::string label); + + void run(ProControllerContext& context, uint16_t delay); + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp index 4d803febd5..546055a2d7 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.cpp @@ -1,111 +1,111 @@ -/* Pokemon BD/SP Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "PokemonBDSP_Panels.h" - -#include "PokemonBDSP_Settings.h" - -#include "Programs/General/PokemonBDSP_MassRelease.h" -#include "Programs/General/PokemonBDSP_AutonomousBallThrower.h" - -#include "Programs/Trading/PokemonBDSP_SelfBoxTrade.h" -#include "Programs/Trading/PokemonBDSP_SelfTouchTrade.h" - -#include "Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h" -#include "Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h" -#include "Programs/Farming/PokemonBDSP_DoublesLeveling.h" -#include "Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h" -#include "Programs/Farming/PokemonBDSP_PoffinCooker.h" -#include "Programs/Farming/PokemonBDSP_GiftBerryReset.h" - -#include "Programs/ShinyHunting/PokemonBDSP_StarterReset.h" -#include "Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h" -#include "Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h" -#include "Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h" -#include "Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h" - -#include "Programs/Eggs/PokemonBDSP_EggFetcher.h" -#include "Programs/Eggs/PokemonBDSP_EggHatcher.h" -#include "Programs/Eggs/PokemonBDSP_EggAutonomous.h" - -#include "Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h" -#include "Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h" -#include "Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h" -//#include "Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy.h" -//#include "Programs/Glitches/PokemonBDSP_CloneItemsMenuOverlap.h" - -#include "Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h" -#include "Programs/TestPrograms/PokemonBDSP_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Brilliant Diamond and Shining Pearl") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Trading ----"); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - - ret.emplace_back("---- Farming ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Eggs ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Glitches (v1.1.3) ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Glitches (v1.1.2) ----"); - ret.emplace_back(make_single_switch_program()); - - if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Untested/Beta/WIP ----"); - } - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - -} -} -} +/* Pokemon BD/SP Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "PokemonBDSP_Panels.h" + +#include "PokemonBDSP_Settings.h" + +#include "Programs/General/PokemonBDSP_MassRelease.h" +#include "Programs/General/PokemonBDSP_AutonomousBallThrower.h" + +#include "Programs/Trading/PokemonBDSP_SelfBoxTrade.h" +#include "Programs/Trading/PokemonBDSP_SelfTouchTrade.h" + +#include "Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h" +#include "Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h" +#include "Programs/Farming/PokemonBDSP_DoublesLeveling.h" +#include "Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h" +#include "Programs/Farming/PokemonBDSP_PoffinCooker.h" +#include "Programs/Farming/PokemonBDSP_GiftBerryReset.h" + +#include "Programs/ShinyHunting/PokemonBDSP_StarterReset.h" +#include "Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h" +#include "Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h" +#include "Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h" +#include "Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h" + +#include "Programs/Eggs/PokemonBDSP_EggFetcher.h" +#include "Programs/Eggs/PokemonBDSP_EggHatcher.h" +#include "Programs/Eggs/PokemonBDSP_EggAutonomous.h" + +#include "Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h" +#include "Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h" +#include "Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h" +//#include "Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy.h" +//#include "Programs/Glitches/PokemonBDSP_CloneItemsMenuOverlap.h" + +#include "Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h" +#include "Programs/TestPrograms/PokemonBDSP_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Brilliant Diamond and Shining Pearl") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Trading ----"); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + + ret.emplace_back("---- Farming ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Eggs ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Glitches (v1.1.3) ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Glitches (v1.1.2) ----"); + ret.emplace_back(make_single_switch_program()); + + if (IS_BETA_VERSION || PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Untested/Beta/WIP ----"); + } + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.h b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.h index 9c1f6da8e7..9e851a68f9 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.h +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon BD/SP Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_Panels_H -#define PokemonAutomation_PokemonBDSP_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon BD/SP Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_Panels_H +#define PokemonAutomation_PokemonBDSP_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.cpp b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.cpp index 53b7e50d64..9e44700cb7 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.cpp +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.cpp @@ -1,210 +1,210 @@ -/* Pokemon BDSP Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_menu_navigation("Menu Navigation Timings:") - , OVERWORLD_TO_MENU_DELAY0( - "Overworld to Menu Delay:
Delay to bring up the menu when pressing X in the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , MENU_TO_OVERWORLD_DELAY0( - "Menu to Overworld Delay:
Delay to go from menu back to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , GAME_TO_HOME_DELAY0( - "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , m_start_game_timings("Start Game Timings:") - , START_GAME_MASH0( - "1. Start Game Mash:
Mash A for this long to start the game.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , START_GAME_WAIT0( - "2. Start Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "300 s" - ) - , ENTER_GAME_MASH0( - "3. Enter Game Mash:
Mash A for this long to enter the game.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , ENTER_GAME_WAIT0( - "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "300 s" - ) - , m_box_timings("Box Timings: (for egg programs)") - , BOX_SCROLL_DELAY0( - "Box Scroll Delay:
Delay to move the cursor.", - LockMode::LOCK_WHILE_RUNNING, - "240 ms" - ) - , BOX_CHANGE_DELAY0( - "Box Change Delay:
Delay to change boxes.", - LockMode::LOCK_WHILE_RUNNING, - "1600 ms" - ) - , BOX_PICKUP_DROP_DELAY0( - "Box Pickup/Drop Delay:
Delay to pickup/drop " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "400 ms" - ) - , MENU_TO_POKEMON_DELAY0( - "Menu To " + STRING_POKEMON + " Delay:
Delay to enter " + STRING_POKEMON + " menu.", - LockMode::LOCK_WHILE_RUNNING, - "2400 ms" - ) - , POKEMON_TO_BOX_DELAY1( - "" + STRING_POKEMON + " to Box Delay:
Delay to enter box system.", - LockMode::LOCK_WHILE_RUNNING, - "2560 ms" - ) - , BOX_TO_POKEMON_DELAY0( - "Box to " + STRING_POKEMON + " Delay:
Delay to exit box system.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , POKEMON_TO_MENU_DELAY0( - "" + STRING_POKEMON + " to Menu Delay:
Delay to return to menu.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SHINY_ALPHA_OVERALL_THRESHOLD( - "Shiny Threshold (overall):
Threshold to detect a shiny encounter.", - LockMode::LOCK_WHILE_RUNNING, - 4.0, 0 - ) - , SHINY_ALPHA_SIDE_THRESHOLD( - "Shiny Threshold (left/right):
Threshold to detect a left/right shiny.", - LockMode::LOCK_WHILE_RUNNING, - 3.0, 0 - ) - , BALL_SPARKLE_ALPHA( - "Ball Sparkle Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 1.0, 0 - ) - , STAR_SPARKLE_ALPHA( - "Star Sparkle Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 1.0, 0 - ) - , SHINY_DIALOG_ALPHA( - "Shiny Dialog Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 3.5, 0 - ) - , SHINY_SOUND_THRESHOLD( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.87, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 5000, 0, 48000 - ) - , SHINY_SOUND_ALPHA( - "Shiny Sound Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 5.0, 0 - ) -// , m_experimental("Experimental/Beta Features:") -{ - PA_ADD_STATIC(m_menu_navigation); - PA_ADD_OPTION(OVERWORLD_TO_MENU_DELAY0); - PA_ADD_OPTION(MENU_TO_OVERWORLD_DELAY0); - PA_ADD_OPTION(GAME_TO_HOME_DELAY0); - - PA_ADD_STATIC(m_start_game_timings); - PA_ADD_OPTION(START_GAME_MASH0); - PA_ADD_OPTION(START_GAME_WAIT0); - PA_ADD_OPTION(ENTER_GAME_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - - PA_ADD_STATIC(m_box_timings); - PA_ADD_OPTION(BOX_SCROLL_DELAY0); - PA_ADD_OPTION(BOX_CHANGE_DELAY0); - PA_ADD_OPTION(BOX_PICKUP_DROP_DELAY0); - PA_ADD_OPTION(MENU_TO_POKEMON_DELAY0); - PA_ADD_OPTION(POKEMON_TO_BOX_DELAY1); - PA_ADD_OPTION(BOX_TO_POKEMON_DELAY0); - PA_ADD_OPTION(POKEMON_TO_MENU_DELAY0); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SHINY_ALPHA_OVERALL_THRESHOLD); - PA_ADD_OPTION(SHINY_ALPHA_SIDE_THRESHOLD); - PA_ADD_OPTION(BALL_SPARKLE_ALPHA); - PA_ADD_OPTION(STAR_SPARKLE_ALPHA); - PA_ADD_OPTION(SHINY_DIALOG_ALPHA); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); - PA_ADD_OPTION(SHINY_SOUND_ALPHA); - -// PA_ADD_STATIC(m_experimental); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonBDSP:GlobalSettings", - STRING_POKEMON + " BDSP", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/PokemonSettings.md", - "Global " + STRING_POKEMON + " Brilliant Diamond and Shing Pearl Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon BDSP Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_menu_navigation("Menu Navigation Timings:") + , OVERWORLD_TO_MENU_DELAY0( + "Overworld to Menu Delay:
Delay to bring up the menu when pressing X in the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , MENU_TO_OVERWORLD_DELAY0( + "Menu to Overworld Delay:
Delay to go from menu back to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , GAME_TO_HOME_DELAY0( + "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , m_start_game_timings("Start Game Timings:") + , START_GAME_MASH0( + "1. Start Game Mash:
Mash A for this long to start the game.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , START_GAME_WAIT0( + "2. Start Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "300 s" + ) + , ENTER_GAME_MASH0( + "3. Enter Game Mash:
Mash A for this long to enter the game.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , ENTER_GAME_WAIT0( + "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "300 s" + ) + , m_box_timings("Box Timings: (for egg programs)") + , BOX_SCROLL_DELAY0( + "Box Scroll Delay:
Delay to move the cursor.", + LockMode::LOCK_WHILE_RUNNING, + "240 ms" + ) + , BOX_CHANGE_DELAY0( + "Box Change Delay:
Delay to change boxes.", + LockMode::LOCK_WHILE_RUNNING, + "1600 ms" + ) + , BOX_PICKUP_DROP_DELAY0( + "Box Pickup/Drop Delay:
Delay to pickup/drop " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "400 ms" + ) + , MENU_TO_POKEMON_DELAY0( + "Menu To " + STRING_POKEMON + " Delay:
Delay to enter " + STRING_POKEMON + " menu.", + LockMode::LOCK_WHILE_RUNNING, + "2400 ms" + ) + , POKEMON_TO_BOX_DELAY1( + "" + STRING_POKEMON + " to Box Delay:
Delay to enter box system.", + LockMode::LOCK_WHILE_RUNNING, + "2560 ms" + ) + , BOX_TO_POKEMON_DELAY0( + "Box to " + STRING_POKEMON + " Delay:
Delay to exit box system.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , POKEMON_TO_MENU_DELAY0( + "" + STRING_POKEMON + " to Menu Delay:
Delay to return to menu.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SHINY_ALPHA_OVERALL_THRESHOLD( + "Shiny Threshold (overall):
Threshold to detect a shiny encounter.", + LockMode::LOCK_WHILE_RUNNING, + 4.0, 0 + ) + , SHINY_ALPHA_SIDE_THRESHOLD( + "Shiny Threshold (left/right):
Threshold to detect a left/right shiny.", + LockMode::LOCK_WHILE_RUNNING, + 3.0, 0 + ) + , BALL_SPARKLE_ALPHA( + "Ball Sparkle Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 1.0, 0 + ) + , STAR_SPARKLE_ALPHA( + "Star Sparkle Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 1.0, 0 + ) + , SHINY_DIALOG_ALPHA( + "Shiny Dialog Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 3.5, 0 + ) + , SHINY_SOUND_THRESHOLD( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.87, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 5000, 0, 48000 + ) + , SHINY_SOUND_ALPHA( + "Shiny Sound Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 5.0, 0 + ) +// , m_experimental("Experimental/Beta Features:") +{ + PA_ADD_STATIC(m_menu_navigation); + PA_ADD_OPTION(OVERWORLD_TO_MENU_DELAY0); + PA_ADD_OPTION(MENU_TO_OVERWORLD_DELAY0); + PA_ADD_OPTION(GAME_TO_HOME_DELAY0); + + PA_ADD_STATIC(m_start_game_timings); + PA_ADD_OPTION(START_GAME_MASH0); + PA_ADD_OPTION(START_GAME_WAIT0); + PA_ADD_OPTION(ENTER_GAME_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + + PA_ADD_STATIC(m_box_timings); + PA_ADD_OPTION(BOX_SCROLL_DELAY0); + PA_ADD_OPTION(BOX_CHANGE_DELAY0); + PA_ADD_OPTION(BOX_PICKUP_DROP_DELAY0); + PA_ADD_OPTION(MENU_TO_POKEMON_DELAY0); + PA_ADD_OPTION(POKEMON_TO_BOX_DELAY1); + PA_ADD_OPTION(BOX_TO_POKEMON_DELAY0); + PA_ADD_OPTION(POKEMON_TO_MENU_DELAY0); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SHINY_ALPHA_OVERALL_THRESHOLD); + PA_ADD_OPTION(SHINY_ALPHA_SIDE_THRESHOLD); + PA_ADD_OPTION(BALL_SPARKLE_ALPHA); + PA_ADD_OPTION(STAR_SPARKLE_ALPHA); + PA_ADD_OPTION(SHINY_DIALOG_ALPHA); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); + PA_ADD_OPTION(SHINY_SOUND_ALPHA); + +// PA_ADD_STATIC(m_experimental); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonBDSP:GlobalSettings", + STRING_POKEMON + " BDSP", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/PokemonSettings.md", + "Global " + STRING_POKEMON + " Brilliant Diamond and Shing Pearl Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.h b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.h index fc4043aa8f..f9392b23a8 100644 --- a/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.h +++ b/SerialPrograms/Source/PokemonBDSP/PokemonBDSP_Settings.h @@ -1,79 +1,79 @@ -/* Pokemon BDSP Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_Settings_H -#define PokemonAutomation_PokemonBDSP_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_menu_navigation; - MillisecondsOption OVERWORLD_TO_MENU_DELAY0; - MillisecondsOption MENU_TO_OVERWORLD_DELAY0; - MillisecondsOption GAME_TO_HOME_DELAY0; - - SectionDividerOption m_start_game_timings; - MillisecondsOption START_GAME_MASH0; - MillisecondsOption START_GAME_WAIT0; - MillisecondsOption ENTER_GAME_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_box_timings; - MillisecondsOption BOX_SCROLL_DELAY0; - MillisecondsOption BOX_CHANGE_DELAY0; - MillisecondsOption BOX_PICKUP_DROP_DELAY0; - MillisecondsOption MENU_TO_POKEMON_DELAY0; - MillisecondsOption POKEMON_TO_BOX_DELAY1; - MillisecondsOption BOX_TO_POKEMON_DELAY0; - MillisecondsOption POKEMON_TO_MENU_DELAY0; - - SectionDividerOption m_advanced_options; - FloatingPointOption SHINY_ALPHA_OVERALL_THRESHOLD; - FloatingPointOption SHINY_ALPHA_SIDE_THRESHOLD; - - FloatingPointOption BALL_SPARKLE_ALPHA; - FloatingPointOption STAR_SPARKLE_ALPHA; - - FloatingPointOption SHINY_DIALOG_ALPHA; - - FloatingPointOption SHINY_SOUND_THRESHOLD; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; - FloatingPointOption SHINY_SOUND_ALPHA; -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon BDSP Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_Settings_H +#define PokemonAutomation_PokemonBDSP_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_menu_navigation; + MillisecondsOption OVERWORLD_TO_MENU_DELAY0; + MillisecondsOption MENU_TO_OVERWORLD_DELAY0; + MillisecondsOption GAME_TO_HOME_DELAY0; + + SectionDividerOption m_start_game_timings; + MillisecondsOption START_GAME_MASH0; + MillisecondsOption START_GAME_WAIT0; + MillisecondsOption ENTER_GAME_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_box_timings; + MillisecondsOption BOX_SCROLL_DELAY0; + MillisecondsOption BOX_CHANGE_DELAY0; + MillisecondsOption BOX_PICKUP_DROP_DELAY0; + MillisecondsOption MENU_TO_POKEMON_DELAY0; + MillisecondsOption POKEMON_TO_BOX_DELAY1; + MillisecondsOption BOX_TO_POKEMON_DELAY0; + MillisecondsOption POKEMON_TO_MENU_DELAY0; + + SectionDividerOption m_advanced_options; + FloatingPointOption SHINY_ALPHA_OVERALL_THRESHOLD; + FloatingPointOption SHINY_ALPHA_SIDE_THRESHOLD; + + FloatingPointOption BALL_SPARKLE_ALPHA; + FloatingPointOption STAR_SPARKLE_ALPHA; + + FloatingPointOption SHINY_DIALOG_ALPHA; + + FloatingPointOption SHINY_SOUND_THRESHOLD; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; + FloatingPointOption SHINY_SOUND_ALPHA; +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp index a6eb05ba36..228806dcde 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.cpp @@ -1,256 +1,256 @@ -/* Egg Autonomous - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_EggAutonomousState.h" -#include "PokemonBDSP_EggAutonomous.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - - -EggAutonomous_Descriptor::EggAutonomous_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:EggAutonomous", - STRING_POKEMON + " BDSP", "Egg Autonomous", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/EggAutonomous.md", - "Automatically fetch+hatch eggs and keep all shinies.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr EggAutonomous_Descriptor::make_stats() const{ - return std::unique_ptr(new EggAutonomousStats()); -} - - -EggAutonomous::EggAutonomous() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:
Required to read IVs.", - PokemonSwSh::IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SHORTCUT("Bike Shortcut:") - , MAX_KEEPERS( - "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " - "This number plus the number of " + STRING_POKEMON + " in your last box must not exceed 30. " - "Otherwise, the program will break when that box is full.", - LockMode::LOCK_WHILE_RUNNING, - 10, 1, 30 - ) - , TRAVEL_TIME_PER_FETCH0( - "Travel Time per Fetch:
Fetch an egg after traveling for this long.", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) - , NUM_EGGS_IN_COLUMN( - "Num Eggs in Column:
How many eggs already deposited in the first column in Box 1.", - { - {0, "0", "0"}, - {1, "1", "1"}, - {2, "2", "2"}, - {3, "3", "3"}, - {4, "4", "4"}, - {5, "5", "5"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , AUTO_SAVING( - "Auto-Saving:
Automatically save the game to recover from crashes and allow eggs to be unhatched.
" - "(Unhatching eggs can be useful for obtaining breeding parents by rehatching a perfect egg in a game with a different language.)

" - "To collect (unhatched) eggs with the desired stats, set this option to \"Save before every batch\". " - "Then set the Action Table below to \"Stop Program\" on the desired stats. " - "Once the program stops on the baby with the desired stats, you can manually reset the game and it will revert to an egg in your party.", - { - {AutoSave::NoAutoSave, "none", "No auto-saving. (No error/crash recovery.)"}, - {AutoSave::AfterStartAndKeep, "start-and-keep", "Save at beginning and after obtaining each baby that is kept. (Allows for error/crash recovery.)"}, - {AutoSave::EveryBatch, "every-batch", "Save before every batch. (Allows you to unhatch eggs.)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - AutoSave::AfterStartAndKeep - ) - , FILTERS0( - StatsHuntIvJudgeFilterTable_Label_Eggs, - { - .action = true, - .shiny = true, - .gender = true, - .nature = true, - } - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_NONSHINY_KEEP( - "Non-Shiny Keep", - true, true, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_SHINY( - "Shiny Hatch", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_NONSHINY_KEEP, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SCROLL_TO_READ_DELAY0( - "Scroll to Read Delay:
Wait this long after scrolling in the box to read the " + STRING_POKEMON + "'s stats. " - "Increase this if your video has high latency.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(SHORTCUT); - PA_ADD_OPTION(MAX_KEEPERS); - PA_ADD_OPTION(TRAVEL_TIME_PER_FETCH0); - PA_ADD_OPTION(NUM_EGGS_IN_COLUMN); - PA_ADD_OPTION(AUTO_SAVING); - PA_ADD_OPTION(FILTERS0); - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SCROLL_TO_READ_DELAY0); -} - - - - - -bool EggAutonomous::run_batch( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - EggAutonomousState& saved_state, - EggAutonomousState& current_state -){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - bool save = false; - switch (AUTO_SAVING){ - case AutoSave::NoAutoSave: - break; - case AutoSave::AfterStartAndKeep: - save = saved_state.babies_saved() != current_state.babies_saved(); - break; - case AutoSave::EveryBatch: - save = true; - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid saving option."); - } - - if (save){ - save_game(env.console, context); - saved_state.set(current_state); - } - - while (!current_state.overworld_detect_and_run_state()); - return current_state.process_batch(); -} - -void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - EggAutonomousStats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_move_right_joystick(context, 0, 255, 10, 0); - - // Move to corner. - pbf_move_left_joystick(context, 0, 255, 125, 0); - - EggAutonomousState current_state( - env, env.console, context, - stats, - NOTIFICATION_NONSHINY_KEEP, - NOTIFICATION_SHINY, - SCROLL_TO_READ_DELAY0, - LANGUAGE, - SHORTCUT, - TRAVEL_TIME_PER_FETCH0, - FILTERS0, - MAX_KEEPERS, - static_cast(NUM_EGGS_IN_COLUMN.current_value()) - ); - EggAutonomousState saved_state = current_state; - -// overworld_to_box(env, env.console); -// current_state.withdraw_egg_column(); -// box_to_overworld(env, env.console); - - if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ - save_game(env.console, context); - saved_state.set(current_state); - } - - size_t consecutive_failures = 0; - while (current_state.babies_saved() < MAX_KEEPERS){ - try{ - if (run_batch(env, context, saved_state, current_state)){ - break; - } - consecutive_failures = 0; - }catch (OperationFailedException& e){ - // If there is no auto save, then we shouldn't reset to game to lose previous progress. - if (AUTO_SAVING == AutoSave::NoAutoSave){ - throw; - } - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - consecutive_failures++; - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 batches in the row.", - env.console - ); - } - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - current_state.set(saved_state); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - - - -} -} -} +/* Egg Autonomous + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_EggAutonomousState.h" +#include "PokemonBDSP_EggAutonomous.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + + +EggAutonomous_Descriptor::EggAutonomous_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:EggAutonomous", + STRING_POKEMON + " BDSP", "Egg Autonomous", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/EggAutonomous.md", + "Automatically fetch+hatch eggs and keep all shinies.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr EggAutonomous_Descriptor::make_stats() const{ + return std::unique_ptr(new EggAutonomousStats()); +} + + +EggAutonomous::EggAutonomous() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:
Required to read IVs.", + PokemonSwSh::IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SHORTCUT("Bike Shortcut:") + , MAX_KEEPERS( + "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " + "This number plus the number of " + STRING_POKEMON + " in your last box must not exceed 30. " + "Otherwise, the program will break when that box is full.", + LockMode::LOCK_WHILE_RUNNING, + 10, 1, 30 + ) + , TRAVEL_TIME_PER_FETCH0( + "Travel Time per Fetch:
Fetch an egg after traveling for this long.", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) + , NUM_EGGS_IN_COLUMN( + "Num Eggs in Column:
How many eggs already deposited in the first column in Box 1.", + { + {0, "0", "0"}, + {1, "1", "1"}, + {2, "2", "2"}, + {3, "3", "3"}, + {4, "4", "4"}, + {5, "5", "5"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , AUTO_SAVING( + "Auto-Saving:
Automatically save the game to recover from crashes and allow eggs to be unhatched.
" + "(Unhatching eggs can be useful for obtaining breeding parents by rehatching a perfect egg in a game with a different language.)

" + "To collect (unhatched) eggs with the desired stats, set this option to \"Save before every batch\". " + "Then set the Action Table below to \"Stop Program\" on the desired stats. " + "Once the program stops on the baby with the desired stats, you can manually reset the game and it will revert to an egg in your party.", + { + {AutoSave::NoAutoSave, "none", "No auto-saving. (No error/crash recovery.)"}, + {AutoSave::AfterStartAndKeep, "start-and-keep", "Save at beginning and after obtaining each baby that is kept. (Allows for error/crash recovery.)"}, + {AutoSave::EveryBatch, "every-batch", "Save before every batch. (Allows you to unhatch eggs.)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + AutoSave::AfterStartAndKeep + ) + , FILTERS0( + StatsHuntIvJudgeFilterTable_Label_Eggs, + { + .action = true, + .shiny = true, + .gender = true, + .nature = true, + } + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_NONSHINY_KEEP( + "Non-Shiny Keep", + true, true, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_SHINY( + "Shiny Hatch", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_NONSHINY_KEEP, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SCROLL_TO_READ_DELAY0( + "Scroll to Read Delay:
Wait this long after scrolling in the box to read the " + STRING_POKEMON + "'s stats. " + "Increase this if your video has high latency.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(SHORTCUT); + PA_ADD_OPTION(MAX_KEEPERS); + PA_ADD_OPTION(TRAVEL_TIME_PER_FETCH0); + PA_ADD_OPTION(NUM_EGGS_IN_COLUMN); + PA_ADD_OPTION(AUTO_SAVING); + PA_ADD_OPTION(FILTERS0); + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SCROLL_TO_READ_DELAY0); +} + + + + + +bool EggAutonomous::run_batch( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + EggAutonomousState& saved_state, + EggAutonomousState& current_state +){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + bool save = false; + switch (AUTO_SAVING){ + case AutoSave::NoAutoSave: + break; + case AutoSave::AfterStartAndKeep: + save = saved_state.babies_saved() != current_state.babies_saved(); + break; + case AutoSave::EveryBatch: + save = true; + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid saving option."); + } + + if (save){ + save_game(env.console, context); + saved_state.set(current_state); + } + + while (!current_state.overworld_detect_and_run_state()); + return current_state.process_batch(); +} + +void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + EggAutonomousStats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_move_right_joystick(context, 0, 255, 10, 0); + + // Move to corner. + pbf_move_left_joystick(context, 0, 255, 125, 0); + + EggAutonomousState current_state( + env, env.console, context, + stats, + NOTIFICATION_NONSHINY_KEEP, + NOTIFICATION_SHINY, + SCROLL_TO_READ_DELAY0, + LANGUAGE, + SHORTCUT, + TRAVEL_TIME_PER_FETCH0, + FILTERS0, + MAX_KEEPERS, + static_cast(NUM_EGGS_IN_COLUMN.current_value()) + ); + EggAutonomousState saved_state = current_state; + +// overworld_to_box(env, env.console); +// current_state.withdraw_egg_column(); +// box_to_overworld(env, env.console); + + if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ + save_game(env.console, context); + saved_state.set(current_state); + } + + size_t consecutive_failures = 0; + while (current_state.babies_saved() < MAX_KEEPERS){ + try{ + if (run_batch(env, context, saved_state, current_state)){ + break; + } + consecutive_failures = 0; + }catch (OperationFailedException& e){ + // If there is no auto save, then we shouldn't reset to game to lose previous progress. + if (AUTO_SAVING == AutoSave::NoAutoSave){ + throw; + } + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + consecutive_failures++; + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 batches in the row.", + env.console + ); + } + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + current_state.set(saved_state); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h index 24cadd6c08..dc9305bff2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomous.h @@ -1,79 +1,79 @@ -/* Egg Autonomous - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggAutonomous_H -#define PokemonAutomation_PokemonBDSP_EggAutonomous_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonBDSP_EggAutonomousState.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class EggAutonomous_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggAutonomous_Descriptor(); - virtual std::unique_ptr make_stats() const override; -}; - - -class EggAutonomous : public SingleSwitchProgramInstance{ -public: - EggAutonomous(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run_batch( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - EggAutonomousState& saved_state, - EggAutonomousState& current_state - ); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - - ShortcutDirectionOption SHORTCUT; - SimpleIntegerOption MAX_KEEPERS; - MillisecondsOption TRAVEL_TIME_PER_FETCH0; - IntegerEnumDropdownOption NUM_EGGS_IN_COLUMN; - - enum class AutoSave{ - NoAutoSave, - AfterStartAndKeep, - EveryBatch, - }; - EnumDropdownOption AUTO_SAVING; - - Pokemon::StatsHuntIvJudgeFilterTable FILTERS0; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_NONSHINY_KEEP; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption SCROLL_TO_READ_DELAY0; -}; - - - -} -} -} -#endif +/* Egg Autonomous + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggAutonomous_H +#define PokemonAutomation_PokemonBDSP_EggAutonomous_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonBDSP_EggAutonomousState.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class EggAutonomous_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggAutonomous_Descriptor(); + virtual std::unique_ptr make_stats() const override; +}; + + +class EggAutonomous : public SingleSwitchProgramInstance{ +public: + EggAutonomous(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run_batch( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + EggAutonomousState& saved_state, + EggAutonomousState& current_state + ); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + + ShortcutDirectionOption SHORTCUT; + SimpleIntegerOption MAX_KEEPERS; + MillisecondsOption TRAVEL_TIME_PER_FETCH0; + IntegerEnumDropdownOption NUM_EGGS_IN_COLUMN; + + enum class AutoSave{ + NoAutoSave, + AfterStartAndKeep, + EveryBatch, + }; + EnumDropdownOption AUTO_SAVING; + + Pokemon::StatsHuntIvJudgeFilterTable FILTERS0; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_NONSHINY_KEEP; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption SCROLL_TO_READ_DELAY0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp index 4d7e22aed2..e11c7c5ee5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.cpp @@ -1,533 +1,533 @@ -/* Egg Autonomous State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/FrozenImageDetector.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_EggRoutines.h" -#include "PokemonBDSP_EggFeedback.h" -#include "PokemonBDSP_EggAutonomousState.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -EggAutonomousStats::EggAutonomousStats() - : m_hatched(m_stats["Eggs Hatched"]) - , m_errors(m_stats["Errors"]) - , m_fetch_attempts(m_stats["Fetch Attempts"]) - , m_fetch_success(m_stats["Fetch Success"]) - , m_shinies(m_stats["Shinies"]) -{ - m_display_order.emplace_back("Eggs Hatched"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Fetch Attempts"); - m_display_order.emplace_back("Fetch Success"); - m_display_order.emplace_back("Shinies"); -} - - - - -class EggReceivedDetector : public VisualInferenceCallback{ -public: - EggReceivedDetector(Color color = COLOR_RED) - : VisualInferenceCallback("EggReceivedDetector") - , m_fetched(false) - , m_color(color) - , m_box0(0.05, 0.10, 0.10, 0.80) - , m_box1(0.87, 0.10, 0.10, 0.80) - {} - - bool fetched() const{ - return m_fetched; - } - - virtual void make_overlays(VideoOverlaySet& items) const override{ - items.add(m_color, m_box0); - items.add(m_color, m_box1); - } - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - ImageStats stats0 = image_stats(extract_box_reference(frame, m_box0)); - ImageStats stats1 = image_stats(extract_box_reference(frame, m_box1)); - if (!is_solid(stats0, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ - return false; - } - if (!is_solid(stats1, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ - return false; - } - m_fetched = true; - return false; - } - -private: - bool m_fetched; - Color m_color; - ImageFloatBox m_box0; - ImageFloatBox m_box1; -}; - - - -EventNotificationOption EggAutonomousState::m_notification_noop("", false, false); - - -EggAutonomousState::EggAutonomousState( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - EggAutonomousStats& stats, - EventNotificationOption& notification_nonshiny_keep, - EventNotificationOption& notification_shiny, - Milliseconds scroll_to_read_delay, - Language language, - ShortcutDirectionOption& shortcut, - Milliseconds travel_time_per_fetch, - const StatsHuntIvJudgeFilterTable& filters, - uint8_t max_keepers, - uint8_t existing_eggs_in_columns -) - : m_env(env), m_stream(stream), m_context(context) - , m_stats(stats) - , m_notification_nonshiny_keep(notification_nonshiny_keep) - , m_notification_shiny(notification_shiny) - , m_scroll_to_read_delay(scroll_to_read_delay) - , m_language(language) - , m_shortcut(shortcut) - , m_travel_time_per_fetch(travel_time_per_fetch) - , m_filters(filters) - , m_max_keepers(max_keepers) - , m_eggs_in_column(existing_eggs_in_columns) -{} - -void EggAutonomousState::dump() const{ - std::string str = "Current State:\n"; - str += " On Bike: "; - str += (m_on_bike ? "Yes" : "No"); - str += "\n Box Column: " + std::to_string(m_eggs_in_column); - str += "\n Party Eggs: " + std::to_string(m_eggs_in_party); - str += "\n Babies Saved: " + std::to_string(m_babies_saved); - m_stream.log(str); -} -void EggAutonomousState::set(const EggAutonomousState& state){ - m_on_bike = state.m_on_bike; - m_eggs_in_column = state.m_eggs_in_column; - m_eggs_in_party = state.m_eggs_in_party; - m_babies_saved = state.m_babies_saved; -} - -void EggAutonomousState::process_error(const std::string& name, const char* message){ - m_stats.m_errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - message, - m_stream - ); -} - -void EggAutonomousState::process_shiny(const ImageViewRGB32& screen){ -// take_video(m_console); - m_stats.m_shinies++; - m_env.update_stats(); - send_encounter_notification( - m_env, - m_notification_noop, - m_notification_shiny, - false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), - screen - ); -} - - -void EggAutonomousState::withdraw_egg_column(){ - m_stream.log("Withdrawing column from box to your party..."); - - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - - pbf_press_button(m_context, BUTTON_Y, 20, 50); - pbf_press_button(m_context, BUTTON_Y, 20, 50); - pickup_column(m_context); - pbf_move_right_joystick(m_context, 0, 128, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(m_context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_press_button(m_context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - - m_eggs_in_column = 0; - m_eggs_in_party = 5; -} -bool EggAutonomousState::process_party(){ - m_stream.log("Processing party..."); - - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - - pbf_move_right_joystick(m_context, 0, 128, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(m_context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_wait(m_context, m_scroll_to_read_delay); - m_context.wait_for_all_requests(); -// m_env.wait_for(SCROLL_TO_READ_DELAY); - - BoxShinyDetector shiny_reader; - IvJudgeReaderScope iv_reader(m_stream.overlay(), m_language); - BoxNatureDetector nature_detector(m_stream.overlay(), m_language); - - VideoOverlaySet set(m_stream.overlay()); - shiny_reader.make_overlays(set); - - // Make sure the stats menu is up. - VideoSnapshot screen = m_stream.video().snapshot(); - if (!shiny_reader.is_panel(screen)){ - process_error("StatsPanel", "Stats panel not detected."); - } - - // Run through the 5 hatchlings and release all the non-shinies. - for (size_t c = 0; c < 5; c++){ - if (c != 0){ - pbf_move_right_joystick(m_context, 128, 0, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(m_context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_wait(m_context, m_scroll_to_read_delay); - m_context.wait_for_all_requests(); -// m_env.wait_for(SCROLL_TO_READ_DELAY); - - screen = m_stream.video().snapshot(); - if (!shiny_reader.is_panel(screen)){ - process_error("StatsPanel", "Stats panel not detected."); - } - } -// m_context.wait_for_all_requests(); - - bool shiny = shiny_reader.detect(screen); - if (shiny){ - m_stream.log("Pokemon " + std::to_string(c) + " is shiny!", COLOR_BLUE); - process_shiny(screen); - }else{ - m_stream.log("Pokemon " + std::to_string(c) + " is not shiny.", COLOR_PURPLE); - } - IvJudgeReader::Results IVs = iv_reader.read(m_stream.logger(), screen); - StatsHuntGenderFilter gender = read_gender_from_box(m_stream.logger(), m_stream.overlay(), screen); - NatureReader::Results nature = nature_detector.read(m_stream.logger(), screen); - - StatsHuntAction action = m_filters.get_action(shiny, gender, nature.nature, IVs); - - switch (action){ - case StatsHuntAction::StopProgram: - m_stream.log("Program stop requested..."); - if (!shiny){ - send_encounter_notification( - m_env, - m_notification_nonshiny_keep, - m_notification_shiny, - false, false, {}, std::nan(""), - screen - ); - } - return true; - case StatsHuntAction::Keep: - m_stream.log("Moving Pokemon to keep box...", COLOR_BLUE); - if (!shiny){ - send_encounter_notification( - m_env, - m_notification_nonshiny_keep, - m_notification_shiny, - false, false, {}, std::nan(""), - screen - ); - } - pbf_press_button(m_context, BUTTON_ZL, 20, 105); - pbf_press_button(m_context, BUTTON_ZL, 20, 105); - pbf_move_right_joystick(m_context, 128, 0, 20, 105); - pbf_move_right_joystick(m_context, 128, 0, 20, 105); - pbf_move_right_joystick(m_context, 128, 0, 20, 105); - pbf_move_right_joystick(m_context, 255, 128, 20, 105); - pbf_press_button(m_context, BUTTON_ZL, 20, 230); - pbf_move_right_joystick(m_context, 0, 128, 20, 105); - pbf_move_right_joystick(m_context, 128, 0, 20, 105); - pbf_move_right_joystick(m_context, 128, 0, 20, 105); - pbf_press_button(m_context, BUTTON_ZL, 20, 105); - pbf_press_button(m_context, BUTTON_B, 20, 230); - pbf_press_button(m_context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); - pbf_move_right_joystick(m_context, 0, 128, 20, 105); - pbf_move_right_joystick(m_context, 128, 255, 20, 105); - pbf_move_right_joystick(m_context, 128, 255, 20, 105); - pbf_move_right_joystick(m_context, 128, 255, 20, 105); - m_babies_saved++; - if (m_babies_saved >= m_max_keepers){ - m_stream.log("Max keepers reached. Stopping program..."); - return true; - } - break; - case StatsHuntAction::Discard: - m_stream.log("Releasing Pokemon...", COLOR_PURPLE); - release(m_stream, m_context); - } - } - - pbf_move_right_joystick(m_context, 128, 0, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(m_context, 255, 128, 160ms, BOX_SCROLL_DELAY); - return false; -} -bool EggAutonomousState::process_batch(){ - overworld_to_box(m_stream, m_context); - if (process_party()){ - return true; - } - withdraw_egg_column(); - box_to_overworld(m_stream, m_context); - return false; -} - - - - -void EggAutonomousState::fetch_egg(){ - if (m_eggs_in_column >= 5){ - process_error("FetchFullColumn", "Attempted to fetch an egg when column is full."); - } - - // Move to corner. - m_context.wait_for_all_requests(); - m_stream.log("Attempting to fetch an egg."); - { - ShortDialogWatcher dialog; - int ret = run_until( - m_stream, m_context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 255, 125, 0); - }, - {{dialog}} - ); - if (ret >= 0){ - return; - } - } - m_context.wait_for(std::chrono::milliseconds(200)); - - m_stream.log("Getting off bike."); - if (m_on_bike){ - m_shortcut.run(m_context, 100); - m_context.wait_for_all_requests(); - m_on_bike = false; - } - - m_stream.log("Going to daycare man."); - { - ShortDialogWatcher dialog; - int ret = run_until( - m_stream, m_context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 255, 30, 0); - pbf_move_left_joystick(context, 128, 0, 35, 0); - pbf_move_left_joystick(context, 255, 128, 60, 125); - }, - {{dialog}} - ); - if (ret >= 0){ - return; - } - } - - // Talk to daycare man. - { - ShortDialogWatcher dialog; - int ret = run_until( - m_stream, m_context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 20, 230); - }, - {{dialog}} - ); - if (ret < 0){ - process_error("DaycareMan", "Unable to find daycare man."); - } - m_stream.log("Found daycare man!"); - } - - { - EggReceivedDetector received; - run_until( - m_stream, m_context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_ZL, 500); - pbf_mash_button(context, BUTTON_B, 500); - }, - {{received}} - ); - m_stats.m_fetch_attempts++; - if (received.fetched()){ - m_eggs_in_column++; - m_stats.m_fetch_success++; - m_stream.log("Fetched an egg!", COLOR_BLUE); - }else{ - m_stream.log("No egg fetched.", COLOR_ORANGE); - } - m_env.update_stats(); - } - - m_stream.log("Getting back on bike."); - m_shortcut.run(m_context, 100); - m_on_bike = true; - pbf_move_left_joystick(m_context, 0, 255, 125, 0); -} -void EggAutonomousState::hatch_egg(){ - if (m_eggs_in_party == 0){ - process_error("HatchFullParty", "State Inconsistency: An egg started hatching when you have no eggs in your party."); - } - - // Hatch the egg. - VideoSnapshot overworld = m_stream.video().snapshot(); -// overworld.save("test-0.png"); - { - pbf_mash_button(m_context, BUTTON_B, 10 * TICKS_PER_SECOND); - m_context.wait_for_all_requests(); - - ShortDialogWatcher dialog; - int ret = wait_until( - m_stream, m_context, std::chrono::seconds(30), - {{dialog}} - ); - if (ret < 0){ - process_error("NoHatchEnd", "End of hatch not detected after 30 seconds."); -// OperationFailedException::fire(m_console, "End of hatch not detected after 30 seconds."); - } - m_stream.log("Egg finished hatching."); - m_stats.m_hatched++; - m_env.update_stats(); - pbf_mash_button(m_context, BUTTON_B, 1 * TICKS_PER_SECOND); - } - - // Return to overworld. - while (true){ - m_context.wait_for_all_requests(); - - // Wait for steady state and read it again. - m_context.wait_for(std::chrono::milliseconds(200)); - ImageMatchWatcher matcher(overworld.frame, {0.10, 0.10, 0.80, 0.60}, 100); - ShortDialogPromptDetector prompt(m_stream.overlay(), {0.50, 0.60, 0.30, 0.20}, COLOR_GREEN); - int ret = wait_until( - m_stream, m_context, std::chrono::seconds(30), - { - {matcher}, - {prompt}, - } - ); - switch (ret){ - case 0: - m_stream.log("Returned to overworld."); - m_eggs_in_party--; - return; - case 1: - m_stream.log("Detected prompt. Please turn off nicknaming.", COLOR_RED); - m_stats.m_errors++; - throw UserSetupError(m_stream.logger(), "Please turn off nicknaming."); - default: - m_stream.log("Failed to detect overworld after 30 seconds. Did day/night change?", COLOR_RED); -// pbf_mash_button(context, BUTTON_ZL, 30 * TICKS_PER_SECOND); - return; - } - } -} - -void EggAutonomousState::hatch_rest_of_party(){ - m_stream.log("Hatching rest of party without fetching..."); - while (m_eggs_in_party > 0){ - dump(); - ShortDialogWatcher dialog; - FrozenImageDetector frozen(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(60), 20); - int ret = run_until( - m_stream, m_context, - [&](ProControllerContext& context){ - egg_spin(context, 8min); - }, - { - {dialog}, - {frozen}, - } - ); - switch (ret){ - case 0: - m_stream.log("Egg is hatching!"); - m_context.wait_for_all_requests(); - hatch_egg(); - break; - case 1: - process_error("FrozenScreen", "Frozen screen detected. Possible game crash."); - default: - process_error("NoHatch", "No hatch detected after 8 minutes of spinning."); - } - - } -} -void EggAutonomousState::spin_until_fetch_or_hatch(){ - m_context.wait_for_all_requests(); - m_stream.log("Looking for more eggs..."); - ShortDialogWatcher dialog; - int ret = run_until( - m_stream, m_context, - [&](ProControllerContext& context){ - egg_spin(context, m_travel_time_per_fetch); - }, - {{dialog}} - ); - m_context.wait_for(std::chrono::milliseconds(200)); - if (ret < 0){ -// m_stream.log("Attempting to fetch an egg."); - fetch_egg(); - }else{ -// m_stream.log("Egg is hatching!"); -// hatch_egg(); - } -} - -bool EggAutonomousState::overworld_detect_and_run_state(){ - ShortDialogWatcher dialog; - m_context.wait_for_all_requests(); - m_context.wait_for(std::chrono::milliseconds(200)); - dump(); - - // Egg is hatching. Handle that now. - if (dialog.detect(m_stream.video().snapshot())){ - m_stream.log("Egg is hatching!"); - hatch_egg(); - return false; - } - - // Need more eggs. - if (m_eggs_in_column < 5){ - spin_until_fetch_or_hatch(); - return false; - } - - // More eggs to hatch. - if (m_eggs_in_party > 0){ - hatch_rest_of_party(); - return false; - } - - // Done with batch. - return true; -} - - - - -} -} -} +/* Egg Autonomous State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/FrozenImageDetector.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxGenderDetector.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxNatureDetector.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxShinyDetector.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_IvJudgeReader.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_EggRoutines.h" +#include "PokemonBDSP_EggFeedback.h" +#include "PokemonBDSP_EggAutonomousState.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +EggAutonomousStats::EggAutonomousStats() + : m_hatched(m_stats["Eggs Hatched"]) + , m_errors(m_stats["Errors"]) + , m_fetch_attempts(m_stats["Fetch Attempts"]) + , m_fetch_success(m_stats["Fetch Success"]) + , m_shinies(m_stats["Shinies"]) +{ + m_display_order.emplace_back("Eggs Hatched"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Fetch Attempts"); + m_display_order.emplace_back("Fetch Success"); + m_display_order.emplace_back("Shinies"); +} + + + + +class EggReceivedDetector : public VisualInferenceCallback{ +public: + EggReceivedDetector(Color color = COLOR_RED) + : VisualInferenceCallback("EggReceivedDetector") + , m_fetched(false) + , m_color(color) + , m_box0(0.05, 0.10, 0.10, 0.80) + , m_box1(0.87, 0.10, 0.10, 0.80) + {} + + bool fetched() const{ + return m_fetched; + } + + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(m_color, m_box0); + items.add(m_color, m_box1); + } + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + ImageStats stats0 = image_stats(extract_box_reference(frame, m_box0)); + ImageStats stats1 = image_stats(extract_box_reference(frame, m_box1)); + if (!is_solid(stats0, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ + return false; + } + if (!is_solid(stats1, {0.22951, 0.340853, 0.429638}, 0.15, 20)){ + return false; + } + m_fetched = true; + return false; + } + +private: + bool m_fetched; + Color m_color; + ImageFloatBox m_box0; + ImageFloatBox m_box1; +}; + + + +EventNotificationOption EggAutonomousState::m_notification_noop("", false, false); + + +EggAutonomousState::EggAutonomousState( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + EggAutonomousStats& stats, + EventNotificationOption& notification_nonshiny_keep, + EventNotificationOption& notification_shiny, + Milliseconds scroll_to_read_delay, + Language language, + ShortcutDirectionOption& shortcut, + Milliseconds travel_time_per_fetch, + const StatsHuntIvJudgeFilterTable& filters, + uint8_t max_keepers, + uint8_t existing_eggs_in_columns +) + : m_env(env), m_stream(stream), m_context(context) + , m_stats(stats) + , m_notification_nonshiny_keep(notification_nonshiny_keep) + , m_notification_shiny(notification_shiny) + , m_scroll_to_read_delay(scroll_to_read_delay) + , m_language(language) + , m_shortcut(shortcut) + , m_travel_time_per_fetch(travel_time_per_fetch) + , m_filters(filters) + , m_max_keepers(max_keepers) + , m_eggs_in_column(existing_eggs_in_columns) +{} + +void EggAutonomousState::dump() const{ + std::string str = "Current State:\n"; + str += " On Bike: "; + str += (m_on_bike ? "Yes" : "No"); + str += "\n Box Column: " + std::to_string(m_eggs_in_column); + str += "\n Party Eggs: " + std::to_string(m_eggs_in_party); + str += "\n Babies Saved: " + std::to_string(m_babies_saved); + m_stream.log(str); +} +void EggAutonomousState::set(const EggAutonomousState& state){ + m_on_bike = state.m_on_bike; + m_eggs_in_column = state.m_eggs_in_column; + m_eggs_in_party = state.m_eggs_in_party; + m_babies_saved = state.m_babies_saved; +} + +void EggAutonomousState::process_error(const std::string& name, const char* message){ + m_stats.m_errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + message, + m_stream + ); +} + +void EggAutonomousState::process_shiny(const ImageViewRGB32& screen){ +// take_video(m_console); + m_stats.m_shinies++; + m_env.update_stats(); + send_encounter_notification( + m_env, + m_notification_noop, + m_notification_shiny, + false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), + screen + ); +} + + +void EggAutonomousState::withdraw_egg_column(){ + m_stream.log("Withdrawing column from box to your party..."); + + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + + pbf_press_button(m_context, BUTTON_Y, 20, 50); + pbf_press_button(m_context, BUTTON_Y, 20, 50); + pickup_column(m_context); + pbf_move_right_joystick(m_context, 0, 128, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(m_context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_press_button(m_context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + + m_eggs_in_column = 0; + m_eggs_in_party = 5; +} +bool EggAutonomousState::process_party(){ + m_stream.log("Processing party..."); + + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + + pbf_move_right_joystick(m_context, 0, 128, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(m_context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_wait(m_context, m_scroll_to_read_delay); + m_context.wait_for_all_requests(); +// m_env.wait_for(SCROLL_TO_READ_DELAY); + + BoxShinyDetector shiny_reader; + IvJudgeReaderScope iv_reader(m_stream.overlay(), m_language); + BoxNatureDetector nature_detector(m_stream.overlay(), m_language); + + VideoOverlaySet set(m_stream.overlay()); + shiny_reader.make_overlays(set); + + // Make sure the stats menu is up. + VideoSnapshot screen = m_stream.video().snapshot(); + if (!shiny_reader.is_panel(screen)){ + process_error("StatsPanel", "Stats panel not detected."); + } + + // Run through the 5 hatchlings and release all the non-shinies. + for (size_t c = 0; c < 5; c++){ + if (c != 0){ + pbf_move_right_joystick(m_context, 128, 0, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(m_context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_wait(m_context, m_scroll_to_read_delay); + m_context.wait_for_all_requests(); +// m_env.wait_for(SCROLL_TO_READ_DELAY); + + screen = m_stream.video().snapshot(); + if (!shiny_reader.is_panel(screen)){ + process_error("StatsPanel", "Stats panel not detected."); + } + } +// m_context.wait_for_all_requests(); + + bool shiny = shiny_reader.detect(screen); + if (shiny){ + m_stream.log("Pokemon " + std::to_string(c) + " is shiny!", COLOR_BLUE); + process_shiny(screen); + }else{ + m_stream.log("Pokemon " + std::to_string(c) + " is not shiny.", COLOR_PURPLE); + } + IvJudgeReader::Results IVs = iv_reader.read(m_stream.logger(), screen); + StatsHuntGenderFilter gender = read_gender_from_box(m_stream.logger(), m_stream.overlay(), screen); + NatureReader::Results nature = nature_detector.read(m_stream.logger(), screen); + + StatsHuntAction action = m_filters.get_action(shiny, gender, nature.nature, IVs); + + switch (action){ + case StatsHuntAction::StopProgram: + m_stream.log("Program stop requested..."); + if (!shiny){ + send_encounter_notification( + m_env, + m_notification_nonshiny_keep, + m_notification_shiny, + false, false, {}, std::nan(""), + screen + ); + } + return true; + case StatsHuntAction::Keep: + m_stream.log("Moving Pokemon to keep box...", COLOR_BLUE); + if (!shiny){ + send_encounter_notification( + m_env, + m_notification_nonshiny_keep, + m_notification_shiny, + false, false, {}, std::nan(""), + screen + ); + } + pbf_press_button(m_context, BUTTON_ZL, 20, 105); + pbf_press_button(m_context, BUTTON_ZL, 20, 105); + pbf_move_right_joystick(m_context, 128, 0, 20, 105); + pbf_move_right_joystick(m_context, 128, 0, 20, 105); + pbf_move_right_joystick(m_context, 128, 0, 20, 105); + pbf_move_right_joystick(m_context, 255, 128, 20, 105); + pbf_press_button(m_context, BUTTON_ZL, 20, 230); + pbf_move_right_joystick(m_context, 0, 128, 20, 105); + pbf_move_right_joystick(m_context, 128, 0, 20, 105); + pbf_move_right_joystick(m_context, 128, 0, 20, 105); + pbf_press_button(m_context, BUTTON_ZL, 20, 105); + pbf_press_button(m_context, BUTTON_B, 20, 230); + pbf_press_button(m_context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); + pbf_move_right_joystick(m_context, 0, 128, 20, 105); + pbf_move_right_joystick(m_context, 128, 255, 20, 105); + pbf_move_right_joystick(m_context, 128, 255, 20, 105); + pbf_move_right_joystick(m_context, 128, 255, 20, 105); + m_babies_saved++; + if (m_babies_saved >= m_max_keepers){ + m_stream.log("Max keepers reached. Stopping program..."); + return true; + } + break; + case StatsHuntAction::Discard: + m_stream.log("Releasing Pokemon...", COLOR_PURPLE); + release(m_stream, m_context); + } + } + + pbf_move_right_joystick(m_context, 128, 0, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(m_context, 255, 128, 160ms, BOX_SCROLL_DELAY); + return false; +} +bool EggAutonomousState::process_batch(){ + overworld_to_box(m_stream, m_context); + if (process_party()){ + return true; + } + withdraw_egg_column(); + box_to_overworld(m_stream, m_context); + return false; +} + + + + +void EggAutonomousState::fetch_egg(){ + if (m_eggs_in_column >= 5){ + process_error("FetchFullColumn", "Attempted to fetch an egg when column is full."); + } + + // Move to corner. + m_context.wait_for_all_requests(); + m_stream.log("Attempting to fetch an egg."); + { + ShortDialogWatcher dialog; + int ret = run_until( + m_stream, m_context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 255, 125, 0); + }, + {{dialog}} + ); + if (ret >= 0){ + return; + } + } + m_context.wait_for(std::chrono::milliseconds(200)); + + m_stream.log("Getting off bike."); + if (m_on_bike){ + m_shortcut.run(m_context, 100); + m_context.wait_for_all_requests(); + m_on_bike = false; + } + + m_stream.log("Going to daycare man."); + { + ShortDialogWatcher dialog; + int ret = run_until( + m_stream, m_context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 255, 30, 0); + pbf_move_left_joystick(context, 128, 0, 35, 0); + pbf_move_left_joystick(context, 255, 128, 60, 125); + }, + {{dialog}} + ); + if (ret >= 0){ + return; + } + } + + // Talk to daycare man. + { + ShortDialogWatcher dialog; + int ret = run_until( + m_stream, m_context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 20, 230); + }, + {{dialog}} + ); + if (ret < 0){ + process_error("DaycareMan", "Unable to find daycare man."); + } + m_stream.log("Found daycare man!"); + } + + { + EggReceivedDetector received; + run_until( + m_stream, m_context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_ZL, 500); + pbf_mash_button(context, BUTTON_B, 500); + }, + {{received}} + ); + m_stats.m_fetch_attempts++; + if (received.fetched()){ + m_eggs_in_column++; + m_stats.m_fetch_success++; + m_stream.log("Fetched an egg!", COLOR_BLUE); + }else{ + m_stream.log("No egg fetched.", COLOR_ORANGE); + } + m_env.update_stats(); + } + + m_stream.log("Getting back on bike."); + m_shortcut.run(m_context, 100); + m_on_bike = true; + pbf_move_left_joystick(m_context, 0, 255, 125, 0); +} +void EggAutonomousState::hatch_egg(){ + if (m_eggs_in_party == 0){ + process_error("HatchFullParty", "State Inconsistency: An egg started hatching when you have no eggs in your party."); + } + + // Hatch the egg. + VideoSnapshot overworld = m_stream.video().snapshot(); +// overworld.save("test-0.png"); + { + pbf_mash_button(m_context, BUTTON_B, 10 * TICKS_PER_SECOND); + m_context.wait_for_all_requests(); + + ShortDialogWatcher dialog; + int ret = wait_until( + m_stream, m_context, std::chrono::seconds(30), + {{dialog}} + ); + if (ret < 0){ + process_error("NoHatchEnd", "End of hatch not detected after 30 seconds."); +// OperationFailedException::fire(m_console, "End of hatch not detected after 30 seconds."); + } + m_stream.log("Egg finished hatching."); + m_stats.m_hatched++; + m_env.update_stats(); + pbf_mash_button(m_context, BUTTON_B, 1 * TICKS_PER_SECOND); + } + + // Return to overworld. + while (true){ + m_context.wait_for_all_requests(); + + // Wait for steady state and read it again. + m_context.wait_for(std::chrono::milliseconds(200)); + ImageMatchWatcher matcher(overworld.frame, {0.10, 0.10, 0.80, 0.60}, 100); + ShortDialogPromptDetector prompt(m_stream.overlay(), {0.50, 0.60, 0.30, 0.20}, COLOR_GREEN); + int ret = wait_until( + m_stream, m_context, std::chrono::seconds(30), + { + {matcher}, + {prompt}, + } + ); + switch (ret){ + case 0: + m_stream.log("Returned to overworld."); + m_eggs_in_party--; + return; + case 1: + m_stream.log("Detected prompt. Please turn off nicknaming.", COLOR_RED); + m_stats.m_errors++; + throw UserSetupError(m_stream.logger(), "Please turn off nicknaming."); + default: + m_stream.log("Failed to detect overworld after 30 seconds. Did day/night change?", COLOR_RED); +// pbf_mash_button(context, BUTTON_ZL, 30 * TICKS_PER_SECOND); + return; + } + } +} + +void EggAutonomousState::hatch_rest_of_party(){ + m_stream.log("Hatching rest of party without fetching..."); + while (m_eggs_in_party > 0){ + dump(); + ShortDialogWatcher dialog; + FrozenImageDetector frozen(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(60), 20); + int ret = run_until( + m_stream, m_context, + [&](ProControllerContext& context){ + egg_spin(context, 8min); + }, + { + {dialog}, + {frozen}, + } + ); + switch (ret){ + case 0: + m_stream.log("Egg is hatching!"); + m_context.wait_for_all_requests(); + hatch_egg(); + break; + case 1: + process_error("FrozenScreen", "Frozen screen detected. Possible game crash."); + default: + process_error("NoHatch", "No hatch detected after 8 minutes of spinning."); + } + + } +} +void EggAutonomousState::spin_until_fetch_or_hatch(){ + m_context.wait_for_all_requests(); + m_stream.log("Looking for more eggs..."); + ShortDialogWatcher dialog; + int ret = run_until( + m_stream, m_context, + [&](ProControllerContext& context){ + egg_spin(context, m_travel_time_per_fetch); + }, + {{dialog}} + ); + m_context.wait_for(std::chrono::milliseconds(200)); + if (ret < 0){ +// m_stream.log("Attempting to fetch an egg."); + fetch_egg(); + }else{ +// m_stream.log("Egg is hatching!"); +// hatch_egg(); + } +} + +bool EggAutonomousState::overworld_detect_and_run_state(){ + ShortDialogWatcher dialog; + m_context.wait_for_all_requests(); + m_context.wait_for(std::chrono::milliseconds(200)); + dump(); + + // Egg is hatching. Handle that now. + if (dialog.detect(m_stream.video().snapshot())){ + m_stream.log("Egg is hatching!"); + hatch_egg(); + return false; + } + + // Need more eggs. + if (m_eggs_in_column < 5){ + spin_until_fetch_or_hatch(); + return false; + } + + // More eggs to hatch. + if (m_eggs_in_party > 0){ + hatch_rest_of_party(); + return false; + } + + // Done with batch. + return true; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.h b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.h index 10ec3092f9..04b6bf20a7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggAutonomousState.h @@ -1,107 +1,107 @@ -/* Egg Autonomous State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggAutonomousState_H -#define PokemonAutomation_PokemonBDSP_EggAutonomousState_H - -//#include "Common/Compiler.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" - -namespace PokemonAutomation{ - class ImageRGB32; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -struct EggAutonomousStats : public StatsTracker{ - EggAutonomousStats(); - std::atomic& m_hatched; - std::atomic& m_errors; - std::atomic& m_fetch_attempts; - std::atomic& m_fetch_success; - std::atomic& m_shinies; -}; - - - -class EggAutonomousState{ -public: - EggAutonomousState( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - EggAutonomousStats& stats, - EventNotificationOption& notification_nonshiny_keep, - EventNotificationOption& notification_shiny, - Milliseconds scroll_to_read_delay, - Language language, - ShortcutDirectionOption& shortcut, - Milliseconds travel_time_per_fetch, - const Pokemon::StatsHuntIvJudgeFilterTable& filters, - uint8_t max_keepers, - uint8_t existing_eggs_in_columns - ); - - bool column_is_filled() const { return m_eggs_in_column >= 5; } - size_t babies_saved() const{ return m_babies_saved; } - - void dump() const; - - void set(const EggAutonomousState& state); - -public: - bool overworld_detect_and_run_state(); - -public: - // All of these must be run from the overworld with the menu closed. - void fetch_egg(); - void hatch_egg(); - void hatch_rest_of_party(); - void spin_until_fetch_or_hatch(); - - bool process_batch(); // Returns true if program should stop. - -public: - // Run inside the box system. - void withdraw_egg_column(); - bool process_party(); // Returns true if program should stop. - -private: - [[noreturn]] void process_error(const std::string& name, const char* message); - void process_shiny(const ImageViewRGB32& screen); - -private: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ProControllerContext& m_context; - EggAutonomousStats& m_stats; - static EventNotificationOption m_notification_noop; - EventNotificationOption& m_notification_nonshiny_keep; - EventNotificationOption& m_notification_shiny; - Milliseconds m_scroll_to_read_delay; - Language m_language; - ShortcutDirectionOption& m_shortcut; - Milliseconds m_travel_time_per_fetch; - const Pokemon::StatsHuntIvJudgeFilterTable& m_filters; - uint8_t m_max_keepers; - - bool m_on_bike = true; - uint8_t m_eggs_in_column = 0; - uint8_t m_eggs_in_party = 5; - uint8_t m_babies_saved = 0; -}; - - - - -} -} -} -#endif +/* Egg Autonomous State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggAutonomousState_H +#define PokemonAutomation_PokemonBDSP_EggAutonomousState_H + +//#include "Common/Compiler.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" + +namespace PokemonAutomation{ + class ImageRGB32; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct EggAutonomousStats : public StatsTracker{ + EggAutonomousStats(); + std::atomic& m_hatched; + std::atomic& m_errors; + std::atomic& m_fetch_attempts; + std::atomic& m_fetch_success; + std::atomic& m_shinies; +}; + + + +class EggAutonomousState{ +public: + EggAutonomousState( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + EggAutonomousStats& stats, + EventNotificationOption& notification_nonshiny_keep, + EventNotificationOption& notification_shiny, + Milliseconds scroll_to_read_delay, + Language language, + ShortcutDirectionOption& shortcut, + Milliseconds travel_time_per_fetch, + const Pokemon::StatsHuntIvJudgeFilterTable& filters, + uint8_t max_keepers, + uint8_t existing_eggs_in_columns + ); + + bool column_is_filled() const { return m_eggs_in_column >= 5; } + size_t babies_saved() const{ return m_babies_saved; } + + void dump() const; + + void set(const EggAutonomousState& state); + +public: + bool overworld_detect_and_run_state(); + +public: + // All of these must be run from the overworld with the menu closed. + void fetch_egg(); + void hatch_egg(); + void hatch_rest_of_party(); + void spin_until_fetch_or_hatch(); + + bool process_batch(); // Returns true if program should stop. + +public: + // Run inside the box system. + void withdraw_egg_column(); + bool process_party(); // Returns true if program should stop. + +private: + [[noreturn]] void process_error(const std::string& name, const char* message); + void process_shiny(const ImageViewRGB32& screen); + +private: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ProControllerContext& m_context; + EggAutonomousStats& m_stats; + static EventNotificationOption m_notification_noop; + EventNotificationOption& m_notification_nonshiny_keep; + EventNotificationOption& m_notification_shiny; + Milliseconds m_scroll_to_read_delay; + Language m_language; + ShortcutDirectionOption& m_shortcut; + Milliseconds m_travel_time_per_fetch; + const Pokemon::StatsHuntIvJudgeFilterTable& m_filters; + uint8_t m_max_keepers; + + bool m_on_bike = true; + uint8_t m_eggs_in_column = 0; + uint8_t m_eggs_in_party = 5; + uint8_t m_babies_saved = 0; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.cpp index 66e202f4b0..6bab748547 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.cpp @@ -1,165 +1,165 @@ -/* Egg Feedback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/FrozenImageDetector.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_EggRoutines.h" -#include "PokemonBDSP_EggFeedback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -void hatch_egg(VideoStream& stream, ProControllerContext& context){ - // Spin until egg starts hatching. - do{ - ShortDialogWatcher dialog; - FrozenImageDetector frozen(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(10), 20); - if (dialog.detect(stream.video().snapshot())){ - break; - } - - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - egg_spin(context, 8min); - }, - { - {dialog}, - {frozen}, - } - ); - switch (ret){ - case 0: - stream.log("Egg is hatching!"); - break; - case 1: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Frozen screen detected!", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No hatch detected after 8 minutes of spinning.", - stream - ); - } - }while (false); - - - // Hatch the egg. - VideoSnapshot overworld = stream.video().snapshot(); -// overworld.save("test-0.png"); - { - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - ShortDialogWatcher dialog; - int ret = wait_until( - stream, context, std::chrono::seconds(30), - {{dialog}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "End of hatch not detected after 30 seconds.", - stream - ); - } - stream.log("Egg finished hatching."); - pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); - } - - // Return to overworld. - while (true){ - context.wait_for_all_requests(); - - // Wait for steady state and read it again. - context.wait_for(std::chrono::milliseconds(200)); - ImageMatchWatcher matcher(overworld.frame, {0.10, 0.10, 0.80, 0.60}, 100); - SelectionArrowFinder arrow(stream.overlay(), {0.50, 0.60, 0.30, 0.20}, COLOR_GREEN); - int ret = wait_until( - stream, context, std::chrono::seconds(30), - { - {matcher}, - {arrow}, - } - ); - switch (ret){ - case 0: - stream.log("Returned to overworld."); - return; - case 1: - throw UserSetupError(stream.logger(), "Detected prompt. Please turn off nicknaming."); - default: - stream.log("Failed to detect overworld after 30 seconds. Did day/night change?", COLOR_RED); -// pbf_mash_button(context, BUTTON_ZL, 30 * TICKS_PER_SECOND); - return; - } - } -} -void hatch_party(VideoStream& stream, ProControllerContext& context, size_t eggs){ - for (size_t c = 0; c < eggs; c++){ - hatch_egg(stream, context); - } -} - -void withdraw_1st_column_from_overworld(VideoStream& stream, ProControllerContext& context){ - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - overworld_to_box(stream, context); - pbf_press_button(context, BUTTON_Y, 20, 50); - pbf_press_button(context, BUTTON_Y, 20, 50); - pickup_column(context); - pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - box_to_overworld(stream, context); -} - - - -void release(VideoStream& stream, ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 20, 50); - pbf_move_right_joystick(context, 128, 0, 20, 30); - pbf_move_right_joystick(context, 128, 0, 20, 30); - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_move_right_joystick(context, 128, 255, 20, 30); - - ShortDialogDetector detector; - for (size_t c = 0; c < 3; c++){ - context.wait_for_all_requests(); - if (!detector.detect(stream.video().snapshot())){ - return; - } - pbf_press_button(context, BUTTON_ZL, 20, 105); - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unexpected dialogs when releasing.", - stream - ); -} - - - - - -} -} -} +/* Egg Feedback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/FrozenImageDetector.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_EggRoutines.h" +#include "PokemonBDSP_EggFeedback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +void hatch_egg(VideoStream& stream, ProControllerContext& context){ + // Spin until egg starts hatching. + do{ + ShortDialogWatcher dialog; + FrozenImageDetector frozen(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(10), 20); + if (dialog.detect(stream.video().snapshot())){ + break; + } + + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + egg_spin(context, 8min); + }, + { + {dialog}, + {frozen}, + } + ); + switch (ret){ + case 0: + stream.log("Egg is hatching!"); + break; + case 1: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Frozen screen detected!", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No hatch detected after 8 minutes of spinning.", + stream + ); + } + }while (false); + + + // Hatch the egg. + VideoSnapshot overworld = stream.video().snapshot(); +// overworld.save("test-0.png"); + { + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + ShortDialogWatcher dialog; + int ret = wait_until( + stream, context, std::chrono::seconds(30), + {{dialog}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "End of hatch not detected after 30 seconds.", + stream + ); + } + stream.log("Egg finished hatching."); + pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); + } + + // Return to overworld. + while (true){ + context.wait_for_all_requests(); + + // Wait for steady state and read it again. + context.wait_for(std::chrono::milliseconds(200)); + ImageMatchWatcher matcher(overworld.frame, {0.10, 0.10, 0.80, 0.60}, 100); + SelectionArrowFinder arrow(stream.overlay(), {0.50, 0.60, 0.30, 0.20}, COLOR_GREEN); + int ret = wait_until( + stream, context, std::chrono::seconds(30), + { + {matcher}, + {arrow}, + } + ); + switch (ret){ + case 0: + stream.log("Returned to overworld."); + return; + case 1: + throw UserSetupError(stream.logger(), "Detected prompt. Please turn off nicknaming."); + default: + stream.log("Failed to detect overworld after 30 seconds. Did day/night change?", COLOR_RED); +// pbf_mash_button(context, BUTTON_ZL, 30 * TICKS_PER_SECOND); + return; + } + } +} +void hatch_party(VideoStream& stream, ProControllerContext& context, size_t eggs){ + for (size_t c = 0; c < eggs; c++){ + hatch_egg(stream, context); + } +} + +void withdraw_1st_column_from_overworld(VideoStream& stream, ProControllerContext& context){ + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + overworld_to_box(stream, context); + pbf_press_button(context, BUTTON_Y, 20, 50); + pbf_press_button(context, BUTTON_Y, 20, 50); + pickup_column(context); + pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + box_to_overworld(stream, context); +} + + + +void release(VideoStream& stream, ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 20, 50); + pbf_move_right_joystick(context, 128, 0, 20, 30); + pbf_move_right_joystick(context, 128, 0, 20, 30); + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_move_right_joystick(context, 128, 255, 20, 30); + + ShortDialogDetector detector; + for (size_t c = 0; c < 3; c++){ + context.wait_for_all_requests(); + if (!detector.detect(stream.video().snapshot())){ + return; + } + pbf_press_button(context, BUTTON_ZL, 20, 105); + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unexpected dialogs when releasing.", + stream + ); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h index c2fa93edf0..24d048c9a0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFeedback.h @@ -1,31 +1,31 @@ -/* Egg Feedback - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggFeedback_H -#define PokemonAutomation_PokemonBDSP_EggFeedback_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -void hatch_egg(VideoStream& stream, ProControllerContext& context); -void hatch_party(VideoStream& stream, ProControllerContext& context, size_t eggs = 5); - -void withdraw_1st_column_from_overworld(VideoStream& stream, ProControllerContext& context); - - -void release(VideoStream& stream, ProControllerContext& context); - - - -} -} -} -#endif +/* Egg Feedback + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggFeedback_H +#define PokemonAutomation_PokemonBDSP_EggFeedback_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void hatch_egg(VideoStream& stream, ProControllerContext& context); +void hatch_party(VideoStream& stream, ProControllerContext& context, size_t eggs = 5); + +void withdraw_1st_column_from_overworld(VideoStream& stream, ProControllerContext& context); + + +void release(VideoStream& stream, ProControllerContext& context); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.cpp index 44793f864a..b08b3eecce 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.cpp @@ -1,117 +1,117 @@ -/* Egg Fetcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP_EggRoutines.h" -#include "PokemonBDSP_EggFetcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - - -EggFetcher_Descriptor::EggFetcher_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:EggFetcher", - STRING_POKEMON + " BDSP", "Egg Fetcher", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/EggFetcher.md", - "Automatically fetch eggs from the daycare man.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct EggFetcher_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Fetch Attempts"]) - { - m_display_order.emplace_back("Fetch Attempts"); - } - std::atomic& m_attempts; -}; -std::unique_ptr EggFetcher_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -EggFetcher::EggFetcher() - : GO_HOME_WHEN_DONE(false) - , SHORTCUT("Bike Shortcut:") - , MAX_FETCH_ATTEMPTS( - "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", - LockMode::LOCK_WHILE_RUNNING, - 2000 - ) - , TRAVEL_TIME_PER_FETCH0( - "Travel Time per Fetch:
Fetch an egg after traveling for this long.", - LockMode::LOCK_WHILE_RUNNING, - "15 s" - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(SHORTCUT); - PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); - PA_ADD_OPTION(TRAVEL_TIME_PER_FETCH0); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void EggFetcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - EggFetcher_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_move_right_joystick(context, 0, 255, 10, 0); - - // Move to corner. - pbf_move_left_joystick(context, 0, 255, 125, 0); - - for (uint16_t c = 0; c < MAX_FETCH_ATTEMPTS; c++){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - egg_spin_with_A(context, TRAVEL_TIME_PER_FETCH0); - SHORTCUT.run(context, 100); - - // Move to man. - pbf_move_left_joystick(context, 0, 255, 30, 0); - pbf_move_left_joystick(context, 128, 0, 35, 0); - pbf_move_left_joystick(context, 255, 128, 60, 0); - - // Fetch egg. - pbf_mash_button(context, BUTTON_ZL, 600); - pbf_mash_button(context, BUTTON_B, 520); - pbf_move_left_joystick(context, 0, 255, 125, 0); - SHORTCUT.run(context, 100); - - stats.m_attempts++; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Egg Fetcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP_EggRoutines.h" +#include "PokemonBDSP_EggFetcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + + +EggFetcher_Descriptor::EggFetcher_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:EggFetcher", + STRING_POKEMON + " BDSP", "Egg Fetcher", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/EggFetcher.md", + "Automatically fetch eggs from the daycare man.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct EggFetcher_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Fetch Attempts"]) + { + m_display_order.emplace_back("Fetch Attempts"); + } + std::atomic& m_attempts; +}; +std::unique_ptr EggFetcher_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +EggFetcher::EggFetcher() + : GO_HOME_WHEN_DONE(false) + , SHORTCUT("Bike Shortcut:") + , MAX_FETCH_ATTEMPTS( + "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", + LockMode::LOCK_WHILE_RUNNING, + 2000 + ) + , TRAVEL_TIME_PER_FETCH0( + "Travel Time per Fetch:
Fetch an egg after traveling for this long.", + LockMode::LOCK_WHILE_RUNNING, + "15 s" + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(SHORTCUT); + PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); + PA_ADD_OPTION(TRAVEL_TIME_PER_FETCH0); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void EggFetcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + EggFetcher_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_move_right_joystick(context, 0, 255, 10, 0); + + // Move to corner. + pbf_move_left_joystick(context, 0, 255, 125, 0); + + for (uint16_t c = 0; c < MAX_FETCH_ATTEMPTS; c++){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + egg_spin_with_A(context, TRAVEL_TIME_PER_FETCH0); + SHORTCUT.run(context, 100); + + // Move to man. + pbf_move_left_joystick(context, 0, 255, 30, 0); + pbf_move_left_joystick(context, 128, 0, 35, 0); + pbf_move_left_joystick(context, 255, 128, 60, 0); + + // Fetch egg. + pbf_mash_button(context, BUTTON_ZL, 600); + pbf_mash_button(context, BUTTON_B, 520); + pbf_move_left_joystick(context, 0, 255, 125, 0); + SHORTCUT.run(context, 100); + + stats.m_attempts++; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.h b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.h index 22bbd70c24..ec9df5ba44 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggFetcher.h @@ -1,57 +1,57 @@ -/* Egg Fetcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggFetcher_H -#define PokemonAutomation_PokemonBDSP_EggFetcher_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class EggFetcher_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggFetcher_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class EggFetcher : public SingleSwitchProgramInstance{ -public: - EggFetcher(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - ShortcutDirectionOption SHORTCUT; - SimpleIntegerOption MAX_FETCH_ATTEMPTS; - MillisecondsOption TRAVEL_TIME_PER_FETCH0; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Egg Fetcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggFetcher_H +#define PokemonAutomation_PokemonBDSP_EggFetcher_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class EggFetcher_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggFetcher_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class EggFetcher : public SingleSwitchProgramInstance{ +public: + EggFetcher(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + ShortcutDirectionOption SHORTCUT; + SimpleIntegerOption MAX_FETCH_ATTEMPTS; + MillisecondsOption TRAVEL_TIME_PER_FETCH0; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.cpp index fc1260ac32..2870295ef8 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.cpp @@ -1,146 +1,146 @@ -/* Egg Hatcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_EggRoutines.h" -#include "PokemonBDSP_EggHatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - -EggHatcher_Descriptor::EggHatcher_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:EggHatcher", - STRING_POKEMON + " BDSP", "Egg Hatcher", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/EggHatcher.md", - "Hatch eggs from boxes.", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct EggHatcher_Descriptor::Stats : public StatsTracker{ - Stats() - : m_batches(m_stats["Batches"]) - { - m_display_order.emplace_back("Batches"); - } - std::atomic& m_batches; -}; -std::unique_ptr EggHatcher_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -EggHatcher::EggHatcher() - : GO_HOME_WHEN_DONE(false) -// , SHORTCUT("Bike Shortcut:") - , BOXES_TO_HATCH( - "Boxes to Hatch:", - LockMode::LOCK_WHILE_RUNNING, - 3 - ) - , SAVE_AND_RESET( - "Save and Reset:
After hatching a box, save the game and reset. This will recover from game crashes.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SAFETY_TIME1( - "Safety Time:
Additional time added to the spinning.", - LockMode::LOCK_WHILE_RUNNING, - "10000 ms" - ) - , HATCH_DELAY0( - "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", - LockMode::LOCK_WHILE_RUNNING, - "105 s" - ) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); -// PA_ADD_OPTION(SHORTCUT); - PA_ADD_OPTION(BOXES_TO_HATCH); - PA_ADD_OPTION(STEPS_TO_HATCH); - PA_ADD_OPTION(SAVE_AND_RESET); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SAFETY_TIME1); - PA_ADD_OPTION(HATCH_DELAY0); -} - - - - -void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - EggHatcher_Descriptor::Stats& stats = env.current_stats(); - - Milliseconds INCUBATION_TIME = (uint16_t)((1258.5 + 4.05 * STEPS_TO_HATCH) * 1.05) * 8ms; - Milliseconds TOTAL_DELAY = INCUBATION_TIME + SAFETY_TIME1.get() + HATCH_DELAY0.get(); - - // Connect the controller. - pbf_move_right_joystick(context, 0, 255, 10, 0); - - uint8_t batches = BOXES_TO_HATCH * 6; - uint8_t column = 0; - for (uint8_t c = 0; c < batches; c++){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (c == 0){ - withdraw_1st_column_from_overworld(context); - }else if (column < 5 || !SAVE_AND_RESET){ - swap_party(context, column); - column++; - if (column == 6){ - column = 0; - } - }else{ - deposit_party_to_column(context, 5); - pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); - box_to_overworld(context); - save_game(context); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - withdraw_1st_column_from_overworld(context); - column = 0; - } - - pbf_move_left_joystick(context, 0, 255, 125, 0); - egg_spin_with_A(context, TOTAL_DELAY); - - stats.m_batches++; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Egg Hatcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_EggRoutines.h" +#include "PokemonBDSP_EggHatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + +EggHatcher_Descriptor::EggHatcher_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:EggHatcher", + STRING_POKEMON + " BDSP", "Egg Hatcher", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/EggHatcher.md", + "Hatch eggs from boxes.", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct EggHatcher_Descriptor::Stats : public StatsTracker{ + Stats() + : m_batches(m_stats["Batches"]) + { + m_display_order.emplace_back("Batches"); + } + std::atomic& m_batches; +}; +std::unique_ptr EggHatcher_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +EggHatcher::EggHatcher() + : GO_HOME_WHEN_DONE(false) +// , SHORTCUT("Bike Shortcut:") + , BOXES_TO_HATCH( + "Boxes to Hatch:", + LockMode::LOCK_WHILE_RUNNING, + 3 + ) + , SAVE_AND_RESET( + "Save and Reset:
After hatching a box, save the game and reset. This will recover from game crashes.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SAFETY_TIME1( + "Safety Time:
Additional time added to the spinning.", + LockMode::LOCK_WHILE_RUNNING, + "10000 ms" + ) + , HATCH_DELAY0( + "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", + LockMode::LOCK_WHILE_RUNNING, + "105 s" + ) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); +// PA_ADD_OPTION(SHORTCUT); + PA_ADD_OPTION(BOXES_TO_HATCH); + PA_ADD_OPTION(STEPS_TO_HATCH); + PA_ADD_OPTION(SAVE_AND_RESET); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SAFETY_TIME1); + PA_ADD_OPTION(HATCH_DELAY0); +} + + + + +void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + EggHatcher_Descriptor::Stats& stats = env.current_stats(); + + Milliseconds INCUBATION_TIME = (uint16_t)((1258.5 + 4.05 * STEPS_TO_HATCH) * 1.05) * 8ms; + Milliseconds TOTAL_DELAY = INCUBATION_TIME + SAFETY_TIME1.get() + HATCH_DELAY0.get(); + + // Connect the controller. + pbf_move_right_joystick(context, 0, 255, 10, 0); + + uint8_t batches = BOXES_TO_HATCH * 6; + uint8_t column = 0; + for (uint8_t c = 0; c < batches; c++){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (c == 0){ + withdraw_1st_column_from_overworld(context); + }else if (column < 5 || !SAVE_AND_RESET){ + swap_party(context, column); + column++; + if (column == 6){ + column = 0; + } + }else{ + deposit_party_to_column(context, 5); + pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); + box_to_overworld(context); + save_game(context); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + withdraw_1st_column_from_overworld(context); + column = 0; + } + + pbf_move_left_joystick(context, 0, 255, 125, 0); + egg_spin_with_A(context, TOTAL_DELAY); + + stats.m_batches++; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.h b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.h index dd6975d99b..d63b40719c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggHatcher.h @@ -1,64 +1,64 @@ -/* Egg Hatcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggHatcher_H -#define PokemonAutomation_PokemonBDSP_EggHatcher_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Options/PokemonBDSP_EggStepOption.h" -//#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class EggHatcher_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggHatcher_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class EggHatcher : public SingleSwitchProgramInstance{ -public: - EggHatcher(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - -// ShortcutDirection SHORTCUT; - SimpleIntegerOption BOXES_TO_HATCH; - EggStepCountOption STEPS_TO_HATCH; - - BooleanCheckBoxOption SAVE_AND_RESET; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption SAFETY_TIME1; - MillisecondsOption HATCH_DELAY0; -}; - - - - -} -} -} -#endif +/* Egg Hatcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggHatcher_H +#define PokemonAutomation_PokemonBDSP_EggHatcher_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Options/PokemonBDSP_EggStepOption.h" +//#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class EggHatcher_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggHatcher_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class EggHatcher : public SingleSwitchProgramInstance{ +public: + EggHatcher(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + +// ShortcutDirection SHORTCUT; + SimpleIntegerOption BOXES_TO_HATCH; + EggStepCountOption STEPS_TO_HATCH; + + BooleanCheckBoxOption SAVE_AND_RESET; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption SAFETY_TIME1; + MillisecondsOption HATCH_DELAY0; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp index 7b212d5310..08bd412065 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.cpp @@ -1,133 +1,133 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_EggRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -void egg_spin(ProControllerContext& context, Milliseconds duration){ - for (Milliseconds c = 0ms; c < duration; c += 42*8ms){ - pbf_move_left_joystick(context, 0, 0, 5, 0); - pbf_move_left_joystick(context, 128, 0, 5, 0); - pbf_move_left_joystick(context, 255, 0, 5, 0); - pbf_move_left_joystick(context, 255, 128, 5, 0); - pbf_move_left_joystick(context, 255, 255, 5, 0); - pbf_move_left_joystick(context, 128, 255, 5, 0); - pbf_move_left_joystick(context, 0, 255, 6, 0); - pbf_move_left_joystick(context, 0, 128, 6, 0); - } -} -void egg_spin_with_A(ProControllerContext& context, Milliseconds duration){ - for (Milliseconds c = 0ms; c < duration; c += 42*8ms){ - ssf_press_button(context, BUTTON_ZL, 0ms, 80ms); - pbf_move_left_joystick(context, 0, 0, 5, 0); - pbf_move_left_joystick(context, 128, 0, 5, 0); - pbf_move_left_joystick(context, 255, 0, 5, 0); - pbf_move_left_joystick(context, 255, 128, 5, 0); - pbf_move_left_joystick(context, 255, 255, 5, 0); - pbf_move_left_joystick(context, 128, 255, 5, 0); - pbf_move_left_joystick(context, 0, 255, 6, 0); - pbf_move_left_joystick(context, 0, 128, 6, 0); - } -} - -void pickup_column(ProControllerContext& context){ -// const uint16_t BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY_0; - pbf_press_button(context, BUTTON_ZL, 20, 50); - for (size_t c = 0; c < 30; c++){ - ssf_issue_scroll(context, DPAD_DOWN, 24ms); - } - pbf_press_button(context, BUTTON_ZL, 160ms, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); -} -void party_to_column(ProControllerContext& context, uint8_t column){ - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - pbf_move_right_joystick(context, 128, 0, 160ms, BOX_SCROLL_DELAY); - if (column < 3){ - for (uint8_t c = 0; c <= column; c++){ - pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); - } - }else{ - for (uint8_t c = 6; c != column; c--){ - pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); - } - } -} -void column_to_party(ProControllerContext& context, uint8_t column){ - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - if (column < 3){ - for (uint8_t c = 0; c <= column; c++){ - pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); - } - }else{ - for (uint8_t c = 6; c != column; c--){ - pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); - } - } - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); -} - -void withdraw_1st_column_from_overworld(ProControllerContext& context){ - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - overworld_to_box(context); - pbf_press_button(context, BUTTON_Y, 20, 50); - pbf_press_button(context, BUTTON_Y, 20, 50); - pickup_column(context); - pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - box_to_overworld(context); -} -void deposit_party_to_column(ProControllerContext& context, uint8_t column){ - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - overworld_to_box(context); - pbf_press_button(context, BUTTON_Y, 20, 50); - pbf_press_button(context, BUTTON_Y, 20, 50); - pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); - - // Deposit current column. - pickup_column(context); - party_to_column(context, column); - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); -} -void swap_party(ProControllerContext& context, uint8_t current_column){ - deposit_party_to_column(context, current_column); - - const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - - pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); - if (current_column < 5){ - pickup_column(context); - column_to_party(context, current_column + 1); - }else{ - pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); - pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); - pickup_column(context); - column_to_party(context, 0); - } - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - box_to_overworld(context); -} - - - - - - - -} -} -} +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_EggRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void egg_spin(ProControllerContext& context, Milliseconds duration){ + for (Milliseconds c = 0ms; c < duration; c += 42*8ms){ + pbf_move_left_joystick(context, 0, 0, 5, 0); + pbf_move_left_joystick(context, 128, 0, 5, 0); + pbf_move_left_joystick(context, 255, 0, 5, 0); + pbf_move_left_joystick(context, 255, 128, 5, 0); + pbf_move_left_joystick(context, 255, 255, 5, 0); + pbf_move_left_joystick(context, 128, 255, 5, 0); + pbf_move_left_joystick(context, 0, 255, 6, 0); + pbf_move_left_joystick(context, 0, 128, 6, 0); + } +} +void egg_spin_with_A(ProControllerContext& context, Milliseconds duration){ + for (Milliseconds c = 0ms; c < duration; c += 42*8ms){ + ssf_press_button(context, BUTTON_ZL, 0ms, 80ms); + pbf_move_left_joystick(context, 0, 0, 5, 0); + pbf_move_left_joystick(context, 128, 0, 5, 0); + pbf_move_left_joystick(context, 255, 0, 5, 0); + pbf_move_left_joystick(context, 255, 128, 5, 0); + pbf_move_left_joystick(context, 255, 255, 5, 0); + pbf_move_left_joystick(context, 128, 255, 5, 0); + pbf_move_left_joystick(context, 0, 255, 6, 0); + pbf_move_left_joystick(context, 0, 128, 6, 0); + } +} + +void pickup_column(ProControllerContext& context){ +// const uint16_t BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY_0; + pbf_press_button(context, BUTTON_ZL, 20, 50); + for (size_t c = 0; c < 30; c++){ + ssf_issue_scroll(context, DPAD_DOWN, 24ms); + } + pbf_press_button(context, BUTTON_ZL, 160ms, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); +} +void party_to_column(ProControllerContext& context, uint8_t column){ + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + pbf_move_right_joystick(context, 128, 0, 160ms, BOX_SCROLL_DELAY); + if (column < 3){ + for (uint8_t c = 0; c <= column; c++){ + pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); + } + }else{ + for (uint8_t c = 6; c != column; c--){ + pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); + } + } +} +void column_to_party(ProControllerContext& context, uint8_t column){ + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + if (column < 3){ + for (uint8_t c = 0; c <= column; c++){ + pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); + } + }else{ + for (uint8_t c = 6; c != column; c--){ + pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); + } + } + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); +} + +void withdraw_1st_column_from_overworld(ProControllerContext& context){ + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + overworld_to_box(context); + pbf_press_button(context, BUTTON_Y, 20, 50); + pbf_press_button(context, BUTTON_Y, 20, 50); + pickup_column(context); + pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + box_to_overworld(context); +} +void deposit_party_to_column(ProControllerContext& context, uint8_t column){ + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + overworld_to_box(context); + pbf_press_button(context, BUTTON_Y, 20, 50); + pbf_press_button(context, BUTTON_Y, 20, 50); + pbf_move_right_joystick(context, 0, 128, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); + + // Deposit current column. + pickup_column(context); + party_to_column(context, column); + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); +} +void swap_party(ProControllerContext& context, uint8_t current_column){ + deposit_party_to_column(context, current_column); + + const Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + + pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); + if (current_column < 5){ + pickup_column(context); + column_to_party(context, current_column + 1); + }else{ + pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); + pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); + pickup_column(context); + column_to_party(context, 0); + } + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + box_to_overworld(context); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h index 5724bc06d9..afdb858c9c 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Eggs/PokemonBDSP_EggRoutines.h @@ -1,32 +1,32 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EggRoutines_H -#define PokemonAutomation_PokemonBDSP_EggRoutines_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -void egg_spin(ProControllerContext& context, Milliseconds duration); -void egg_spin_with_A(ProControllerContext& context, Milliseconds duration); - -void pickup_column(ProControllerContext& context); -void party_to_column(ProControllerContext& context, uint8_t column); -void column_to_party(ProControllerContext& context, uint8_t column); - -void withdraw_1st_column_from_overworld(ProControllerContext& context); -void deposit_party_to_column(ProControllerContext& context, uint8_t column); -void swap_party(ProControllerContext& context, uint8_t current_column); - - -} -} -} -#endif +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EggRoutines_H +#define PokemonAutomation_PokemonBDSP_EggRoutines_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +void egg_spin(ProControllerContext& context, Milliseconds duration); +void egg_spin_with_A(ProControllerContext& context, Milliseconds duration); + +void pickup_column(ProControllerContext& context); +void party_to_column(ProControllerContext& context, uint8_t column); +void column_to_party(ProControllerContext& context, uint8_t column); + +void withdraw_1st_column_from_overworld(ProControllerContext& context); +void deposit_party_to_column(ProControllerContext& context, uint8_t column); +void swap_party(ProControllerContext& context, uint8_t current_column); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.cpp index 283b3c0140..f20d1d493d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.cpp @@ -1,129 +1,129 @@ -/* Walking Pokemon Berry Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -//#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_AmitySquarePickUpFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - -AmitySquarePickUpFarmer_Descriptor::AmitySquarePickUpFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:AmitySquarePickUpFarmer", - STRING_POKEMON + " BDSP", "Amity Square Pick Up Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/AmitySquarePickUpFarmer.md", - "Automatically fetch berries and stickers from the walking pokemon in Amity Square.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct AmitySquarePickUpFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Fetch Attempts"]) - { - m_display_order.emplace_back("Fetch Attempts"); - } - std::atomic& m_attempts; -}; -std::unique_ptr AmitySquarePickUpFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -AmitySquarePickUpFarmer::AmitySquarePickUpFarmer() - : GO_HOME_WHEN_DONE(false) - , MAX_FETCH_ATTEMPTS( - "Fetch this many times:
This puts a limit on how many items you can get.", - LockMode::LOCK_WHILE_RUNNING, - 100 - ) - , ONE_WAY_MOVING_TIME0( - "One Way walking Time:
Walk this amount of time in one direction before going back to finish one round of walking.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , ROUNDS_PER_FETCH( - "Rounds per fetch:
How many rounds of walking before doing a berry fetch attempt.", - LockMode::LOCK_WHILE_RUNNING, - 3 - ) - , WAIT_TIME_FOR_POKEMON0( - "Wait Time for Pokemon:
Wait this time for pokemon to catch up to you before you ask for a berry.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); - PA_ADD_OPTION(ONE_WAY_MOVING_TIME0); - PA_ADD_OPTION(ROUNDS_PER_FETCH); - PA_ADD_OPTION(WAIT_TIME_FOR_POKEMON0); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void AmitySquarePickUpFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AmitySquarePickUpFarmer_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_move_right_joystick(context, 0, 255, 10, 0); - - for (uint16_t c = 0; c < MAX_FETCH_ATTEMPTS; c++){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - for (uint16_t i = 0; i < ROUNDS_PER_FETCH; i++){ - // Move right - pbf_move_left_joystick(context, 255, 128, ONE_WAY_MOVING_TIME0, 0ms); - // Move left - pbf_move_left_joystick(context, 0, 128, ONE_WAY_MOVING_TIME0, 0ms); - } - - // Wait for your pokemon to catch up to you - pbf_wait(context, WAIT_TIME_FOR_POKEMON0); - - // Face toward your pokemon. - pbf_press_dpad(context, DPAD_RIGHT, 1, 0); - - // Mash button to talk to pokemon - pbf_mash_button(context, BUTTON_ZL, 500); - - // Mash button to end talking to pokemon - pbf_mash_button(context, BUTTON_B, 500); - - stats.m_attempts++; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Walking Pokemon Berry Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +//#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_AmitySquarePickUpFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + +AmitySquarePickUpFarmer_Descriptor::AmitySquarePickUpFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:AmitySquarePickUpFarmer", + STRING_POKEMON + " BDSP", "Amity Square Pick Up Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/AmitySquarePickUpFarmer.md", + "Automatically fetch berries and stickers from the walking pokemon in Amity Square.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct AmitySquarePickUpFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Fetch Attempts"]) + { + m_display_order.emplace_back("Fetch Attempts"); + } + std::atomic& m_attempts; +}; +std::unique_ptr AmitySquarePickUpFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +AmitySquarePickUpFarmer::AmitySquarePickUpFarmer() + : GO_HOME_WHEN_DONE(false) + , MAX_FETCH_ATTEMPTS( + "Fetch this many times:
This puts a limit on how many items you can get.", + LockMode::LOCK_WHILE_RUNNING, + 100 + ) + , ONE_WAY_MOVING_TIME0( + "One Way walking Time:
Walk this amount of time in one direction before going back to finish one round of walking.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , ROUNDS_PER_FETCH( + "Rounds per fetch:
How many rounds of walking before doing a berry fetch attempt.", + LockMode::LOCK_WHILE_RUNNING, + 3 + ) + , WAIT_TIME_FOR_POKEMON0( + "Wait Time for Pokemon:
Wait this time for pokemon to catch up to you before you ask for a berry.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); + PA_ADD_OPTION(ONE_WAY_MOVING_TIME0); + PA_ADD_OPTION(ROUNDS_PER_FETCH); + PA_ADD_OPTION(WAIT_TIME_FOR_POKEMON0); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void AmitySquarePickUpFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AmitySquarePickUpFarmer_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_move_right_joystick(context, 0, 255, 10, 0); + + for (uint16_t c = 0; c < MAX_FETCH_ATTEMPTS; c++){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + for (uint16_t i = 0; i < ROUNDS_PER_FETCH; i++){ + // Move right + pbf_move_left_joystick(context, 255, 128, ONE_WAY_MOVING_TIME0, 0ms); + // Move left + pbf_move_left_joystick(context, 0, 128, ONE_WAY_MOVING_TIME0, 0ms); + } + + // Wait for your pokemon to catch up to you + pbf_wait(context, WAIT_TIME_FOR_POKEMON0); + + // Face toward your pokemon. + pbf_press_dpad(context, DPAD_RIGHT, 1, 0); + + // Mash button to talk to pokemon + pbf_mash_button(context, BUTTON_ZL, 500); + + // Mash button to end talking to pokemon + pbf_mash_button(context, BUTTON_B, 500); + + stats.m_attempts++; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h index eb0707d1c6..3ad6d7e4bf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_AmitySquarePickUpFarmer.h @@ -1,53 +1,53 @@ -/* Walking Pokemon Berry Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AmitySquarePickUpFarmer_H -#define PokemonAutomation_PokemonBDSP_AmitySquarePickUpFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class AmitySquarePickUpFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AmitySquarePickUpFarmer_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class AmitySquarePickUpFarmer : public SingleSwitchProgramInstance{ -public: - AmitySquarePickUpFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - SimpleIntegerOption MAX_FETCH_ATTEMPTS; - MillisecondsOption ONE_WAY_MOVING_TIME0; - SimpleIntegerOption ROUNDS_PER_FETCH; - MillisecondsOption WAIT_TIME_FOR_POKEMON0; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Walking Pokemon Berry Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AmitySquarePickUpFarmer_H +#define PokemonAutomation_PokemonBDSP_AmitySquarePickUpFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class AmitySquarePickUpFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AmitySquarePickUpFarmer_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class AmitySquarePickUpFarmer : public SingleSwitchProgramInstance{ +public: + AmitySquarePickUpFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + SimpleIntegerOption MAX_FETCH_ATTEMPTS; + MillisecondsOption ONE_WAY_MOVING_TIME0; + SimpleIntegerOption ROUNDS_PER_FETCH; + MillisecondsOption WAIT_TIME_FOR_POKEMON0; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.cpp index b5f2a1fa17..f7ee984d1b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.cpp @@ -1,222 +1,222 @@ -/* Double Battle Leveling - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/FrozenImageDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" -#include "PokemonBDSP_DoublesLeveling.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -DoublesLeveling_Descriptor::DoublesLeveling_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:DoublesLeveling", - STRING_POKEMON + " BDSP", "Double Battle Leveling", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/DoublesLeveling.md", - "Level up your party by spamming spread moves in a double battle with a partner that heals you forever.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct DoublesLeveling_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(false) -// , m_resets(m_stats["Resets"]) - { -// m_display_order.insert(m_display_order.begin() + 2, Stat("Resets")); -// m_aliases["Unexpected Battles"] = "Errors"; - } -// std::atomic& m_resets; -}; -std::unique_ptr DoublesLeveling_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -DoublesLeveling::DoublesLeveling() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(TRIGGER_METHOD); - PA_ADD_OPTION(ON_LEARN_MOVE); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); -// PA_ADD_OPTION(WATCHDOG_TIMER0); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -} - - - - - - - -bool DoublesLeveling::battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DoublesLeveling_Descriptor::Stats& stats = env.current_stats(); - - env.log("Starting battle!"); - - // State Machine - for (size_t c = 0; c < 5;){ - context.wait_for_all_requests(); - - BattleMenuWatcher battle_menu(BattleType::STANDARD); - EndBattleWatcher end_battle; - SelectionArrowFinder learn_move(env.console, {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); - FrozenImageDetector overworld(std::chrono::seconds(5), 10); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - { - battle_menu, - end_battle, - learn_move, - overworld, - } - ); - switch (ret){ - case 0: - env.log("Battle menu detected!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_ZL, 5 * TICKS_PER_SECOND); - c++; - break; - case 1: - env.log("Battle finished!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_B, 250); - return false; - case 2: - env.log("Detected move learn!", COLOR_BLUE); - if (ON_LEARN_MOVE == OnLearnMove::DONT_LEARN){ - pbf_move_right_joystick(context, 128, 255, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - } - return true; - case 3: - env.log("Detected possible overworld!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_B, 250); - return false; - default: - env.log("Timed out.", COLOR_RED); - stats.add_error(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out after 2 minutes.", - env.console - ); - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No progress detected after 5 battle menus. Are you out of PP?", - env.console - ); -} - - - -void DoublesLeveling::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DoublesLeveling_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - // Encounter Loop - while (true){ - // Find encounter. - bool battle = TRIGGER_METHOD.find_encounter(env.console, context); - if (!battle){ - // Unexpected battle: detect battle menu but not battle starting animation. - stats.add_error(); - handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); - continue; - } - - // Detect shiny. - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - WILD_POKEMON, - std::chrono::seconds(30), - ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION - ); - - bool stop = handler.handle_standard_encounter(result_wild); - if (stop){ - break; - } - - if (this->battle(env, context)){ - break; - } - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - - - - -} -} -} +/* Double Battle Leveling + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/FrozenImageDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" +#include "PokemonBDSP_DoublesLeveling.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +DoublesLeveling_Descriptor::DoublesLeveling_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:DoublesLeveling", + STRING_POKEMON + " BDSP", "Double Battle Leveling", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/DoublesLeveling.md", + "Level up your party by spamming spread moves in a double battle with a partner that heals you forever.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct DoublesLeveling_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(false) +// , m_resets(m_stats["Resets"]) + { +// m_display_order.insert(m_display_order.begin() + 2, Stat("Resets")); +// m_aliases["Unexpected Battles"] = "Errors"; + } +// std::atomic& m_resets; +}; +std::unique_ptr DoublesLeveling_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +DoublesLeveling::DoublesLeveling() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(TRIGGER_METHOD); + PA_ADD_OPTION(ON_LEARN_MOVE); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); +// PA_ADD_OPTION(WATCHDOG_TIMER0); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +} + + + + + + + +bool DoublesLeveling::battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DoublesLeveling_Descriptor::Stats& stats = env.current_stats(); + + env.log("Starting battle!"); + + // State Machine + for (size_t c = 0; c < 5;){ + context.wait_for_all_requests(); + + BattleMenuWatcher battle_menu(BattleType::STANDARD); + EndBattleWatcher end_battle; + SelectionArrowFinder learn_move(env.console, {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); + FrozenImageDetector overworld(std::chrono::seconds(5), 10); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + { + battle_menu, + end_battle, + learn_move, + overworld, + } + ); + switch (ret){ + case 0: + env.log("Battle menu detected!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_ZL, 5 * TICKS_PER_SECOND); + c++; + break; + case 1: + env.log("Battle finished!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_B, 250); + return false; + case 2: + env.log("Detected move learn!", COLOR_BLUE); + if (ON_LEARN_MOVE == OnLearnMove::DONT_LEARN){ + pbf_move_right_joystick(context, 128, 255, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + } + return true; + case 3: + env.log("Detected possible overworld!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_B, 250); + return false; + default: + env.log("Timed out.", COLOR_RED); + stats.add_error(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out after 2 minutes.", + env.console + ); + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No progress detected after 5 battle menus. Are you out of PP?", + env.console + ); +} + + + +void DoublesLeveling::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DoublesLeveling_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + // Encounter Loop + while (true){ + // Find encounter. + bool battle = TRIGGER_METHOD.find_encounter(env.console, context); + if (!battle){ + // Unexpected battle: detect battle menu but not battle starting animation. + stats.add_error(); + handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); + continue; + } + + // Detect shiny. + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + WILD_POKEMON, + std::chrono::seconds(30), + ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION + ); + + bool stop = handler.handle_standard_encounter(result_wild); + if (stop){ + break; + } + + if (this->battle(env, context)){ + break; + } + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.h b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.h index 7023a3c155..c63019b5d0 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_DoublesLeveling.h @@ -1,66 +1,66 @@ -/* Double Battle Leveling - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_DoublesLeveling_H -#define PokemonAutomation_PokemonBDSP_DoublesLeveling_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonBDSP/Options/PokemonBDSP_LearnMove.h" -#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" -#include "PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class DoublesLeveling_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DoublesLeveling_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class DoublesLeveling : public SingleSwitchProgramInstance{ -public: - DoublesLeveling(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - bool battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - Pokemon::EncounterBotLanguage LANGUAGE; - - OverworldTrigger TRIGGER_METHOD; - OnLearnMoveOption ON_LEARN_MOVE; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; -// MillisecondsOption WATCHDOG_TIMER; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -}; - - - - -} -} -} -#endif +/* Double Battle Leveling + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_DoublesLeveling_H +#define PokemonAutomation_PokemonBDSP_DoublesLeveling_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonBDSP/Options/PokemonBDSP_LearnMove.h" +#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" +#include "PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class DoublesLeveling_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DoublesLeveling_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class DoublesLeveling : public SingleSwitchProgramInstance{ +public: + DoublesLeveling(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + bool battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + Pokemon::EncounterBotLanguage LANGUAGE; + + OverworldTrigger TRIGGER_METHOD; + OnLearnMoveOption ON_LEARN_MOVE; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; +// MillisecondsOption WATCHDOG_TIMER; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.cpp index c53ca7dff5..a0c8ec7423 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.cpp @@ -1,199 +1,199 @@ -/* Gift Berry Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP_GiftBerryReset.h" -#include "Pokemon/Inference/Pokemon_BerryNameReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - -// The list of berries the Pastoria city berry npc offers. -const std::set Pastoria_berry_list = { - "occa-berry", - "passho-berry", - "wacan-berry", - "rindo-berry", - "yache-berry", - "chople-berry", - "kebia-berry", - "shuca-berry", - "coba-berry", - "payapa-berry", - "tanga-berry", - "charti-berry", - "kasib-berry", - "haban-berry", - "colbur-berry", - "babiri-berry", - "chilan-berry", - "jaboca-berry", - "rowap-berry", - "roseli-berry", -}; - - -GiftBerryReset_Descriptor::GiftBerryReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:GiftBerryReset", - STRING_POKEMON + " BDSP", "Gift Berry Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/GiftBerryReset.md", - "Reset the game in front of the NPC that gives rare berries in Pastoria City until a desired berry is received.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct GiftBerryReset_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Fetch Attempts"]) - { - m_display_order.emplace_back("Fetch Attempts"); - } - std::atomic& m_attempts; -}; -std::unique_ptr GiftBerryReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -GiftBerryReset::GiftBerryReset() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:
This is needed to read the berry name.", - Pokemon::BerryNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , TARGET_BERRIES( - "Berries:
Multiple berries can be selected. The program will stop if one of the selected berries is received." - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(TARGET_BERRIES); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void GiftBerryReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - GiftBerryReset_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_move_right_joystick(context, 0, 255, 10, 0); - - const auto selected_berries = TARGET_BERRIES.selected_berries(); - for (const auto& berry_slug: selected_berries){ - env.console.log("Target berry: " + berry_slug); - if (Pastoria_berry_list.find(berry_slug) == Pastoria_berry_list.end()){ - throw UserSetupError(env.console, "The npc does not offer this berry: " + berry_slug); - } - } - - while (true){ - env.console.log("Talking to berry npc."); - // Press ZL three times to advance dialog with npc - for (int i = 0; i < 3; i++){ - pbf_mash_button(context, BUTTON_ZL, 30); - pbf_wait(context, 150); - } - context.wait_for_all_requests(); - - // Read dialog box to check which berry it is - ShortDialogDetector dialog_detector; - // VideoOverlaySet set(env.console); - // dialog_detector.make_overlays(set); - VideoSnapshot screen = env.console.video().snapshot(); - if (!dialog_detector.detect(screen)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No npc dialog box found when reading berry name", - env.console - ); - } - - ImageFloatBox dialog_box(0.218, 0.835, 0.657, 0.12); - ImageViewRGB32 dialog_image = extract_box_reference(screen, dialog_box); - const auto result = Pokemon::BerryNameReader::instance().read_substring( - env.console, LANGUAGE, dialog_image, - OCR::BLACK_TEXT_FILTERS() - ); - if (result.results.empty()){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No berry name found in dialog box", - env.console - ); - } - bool found_berry = false; - for (const auto& r: result.results){ - env.console.log("Found potential berry name: " + r.second.token); - - if (TARGET_BERRIES.find_berry(r.second.token)){ - found_berry = true; - break; - } - } - - stats.m_attempts++; - env.update_stats(); - - if (found_berry){ - env.console.log("Found one target berry. Stop program."); - break; - } - - // Reset game: - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Error resetting game", - env.console - ); - } - } - - env.update_stats(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Match found!", - env.console.video().snapshot() - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Gift Berry Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP_GiftBerryReset.h" +#include "Pokemon/Inference/Pokemon_BerryNameReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + +// The list of berries the Pastoria city berry npc offers. +const std::set Pastoria_berry_list = { + "occa-berry", + "passho-berry", + "wacan-berry", + "rindo-berry", + "yache-berry", + "chople-berry", + "kebia-berry", + "shuca-berry", + "coba-berry", + "payapa-berry", + "tanga-berry", + "charti-berry", + "kasib-berry", + "haban-berry", + "colbur-berry", + "babiri-berry", + "chilan-berry", + "jaboca-berry", + "rowap-berry", + "roseli-berry", +}; + + +GiftBerryReset_Descriptor::GiftBerryReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:GiftBerryReset", + STRING_POKEMON + " BDSP", "Gift Berry Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/GiftBerryReset.md", + "Reset the game in front of the NPC that gives rare berries in Pastoria City until a desired berry is received.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct GiftBerryReset_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Fetch Attempts"]) + { + m_display_order.emplace_back("Fetch Attempts"); + } + std::atomic& m_attempts; +}; +std::unique_ptr GiftBerryReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +GiftBerryReset::GiftBerryReset() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:
This is needed to read the berry name.", + Pokemon::BerryNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TARGET_BERRIES( + "Berries:
Multiple berries can be selected. The program will stop if one of the selected berries is received." + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(TARGET_BERRIES); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void GiftBerryReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + GiftBerryReset_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_move_right_joystick(context, 0, 255, 10, 0); + + const auto selected_berries = TARGET_BERRIES.selected_berries(); + for (const auto& berry_slug: selected_berries){ + env.console.log("Target berry: " + berry_slug); + if (Pastoria_berry_list.find(berry_slug) == Pastoria_berry_list.end()){ + throw UserSetupError(env.console, "The npc does not offer this berry: " + berry_slug); + } + } + + while (true){ + env.console.log("Talking to berry npc."); + // Press ZL three times to advance dialog with npc + for (int i = 0; i < 3; i++){ + pbf_mash_button(context, BUTTON_ZL, 30); + pbf_wait(context, 150); + } + context.wait_for_all_requests(); + + // Read dialog box to check which berry it is + ShortDialogDetector dialog_detector; + // VideoOverlaySet set(env.console); + // dialog_detector.make_overlays(set); + VideoSnapshot screen = env.console.video().snapshot(); + if (!dialog_detector.detect(screen)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No npc dialog box found when reading berry name", + env.console + ); + } + + ImageFloatBox dialog_box(0.218, 0.835, 0.657, 0.12); + ImageViewRGB32 dialog_image = extract_box_reference(screen, dialog_box); + const auto result = Pokemon::BerryNameReader::instance().read_substring( + env.console, LANGUAGE, dialog_image, + OCR::BLACK_TEXT_FILTERS() + ); + if (result.results.empty()){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No berry name found in dialog box", + env.console + ); + } + bool found_berry = false; + for (const auto& r: result.results){ + env.console.log("Found potential berry name: " + r.second.token); + + if (TARGET_BERRIES.find_berry(r.second.token)){ + found_berry = true; + break; + } + } + + stats.m_attempts++; + env.update_stats(); + + if (found_berry){ + env.console.log("Found one target berry. Stop program."); + break; + } + + // Reset game: + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Error resetting game", + env.console + ); + } + } + + env.update_stats(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Match found!", + env.console.video().snapshot() + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.h b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.h index 21304630c7..afbef69387 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_GiftBerryReset.h @@ -1,52 +1,52 @@ -/* Gift Berry Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_GiftBerryReset_H -#define PokemonAutomation_PokemonBDSP_GiftBerryReset_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Options/PokemonBDSP_BerryTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class GiftBerryReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GiftBerryReset_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class GiftBerryReset : public SingleSwitchProgramInstance{ -public: - GiftBerryReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - - BerryTable TARGET_BERRIES; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Gift Berry Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_GiftBerryReset_H +#define PokemonAutomation_PokemonBDSP_GiftBerryReset_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Options/PokemonBDSP_BerryTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class GiftBerryReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GiftBerryReset_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class GiftBerryReset : public SingleSwitchProgramInstance{ +public: + GiftBerryReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + + BerryTable TARGET_BERRIES; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.cpp index 0ad8dccc42..12280f90b1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.cpp @@ -1,443 +1,443 @@ -/* Money Farmer (Route 210) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h" -#include "PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" -#include "PokemonBDSP_MoneyFarmerRoute210.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -MoneyFarmerRoute210_Descriptor::MoneyFarmerRoute210_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:MoneyFarmerRoute210", - STRING_POKEMON + " BDSP", "Money Farmer (Route 210)", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/MoneyFarmerRoute210.md", - "Farm money by using VS Seeker to rebattle the Ace Trainer couple on Route 210.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - } - ) -{} -struct MoneyFarmerRoute210_Descriptor::Stats : public StatsTracker{ - Stats() - : m_searches(m_stats["Searches"]) - , m_errors(m_stats["Errors"]) - , m_noreact(m_stats["No React"]) - , m_react(m_stats["React"]) - { - m_display_order.emplace_back("Searches"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("No React"); - m_display_order.emplace_back("React"); - } - std::atomic& m_searches; - std::atomic& m_errors; - std::atomic& m_noreact; - std::atomic& m_react; -}; -std::unique_ptr MoneyFarmerRoute210_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -MoneyFarmerRoute210::MoneyFarmerRoute210() - : SHORTCUT("VS Seeker Shortcut:") - , START_LOCATION( - "Start Location:", - { - {StartLocation::CelesticTown, "celestic", "In front of the Celestic Town " + STRING_POKEMON + " center."}, - {StartLocation::AceTrainerPair, "trainer-pair", "Lower-most row of the platform the Ace Trainer pair in Route 210 is on."}, - }, - LockMode::LOCK_WHILE_RUNNING, - StartLocation::CelesticTown - ) - , HEALING_METHOD( - " Healing method:", - { - {HealMethod::CelesticTown, "celestic", "Celestic Town " + STRING_POKEMON + " center."}, - {HealMethod::GlobalRoom, "global-room", "Use Global Room. (will force update your game)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - HealMethod::CelesticTown - ) - , MON0_MOVE1_PP("Lead " + STRING_POKEMON + " Move 1 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON0_MOVE2_PP("Lead " + STRING_POKEMON + " Move 2 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON0_MOVE3_PP("Lead " + STRING_POKEMON + " Move 3 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON0_MOVE4_PP("Lead " + STRING_POKEMON + " Move 4 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON1_MOVE1_PP("2nd " + STRING_POKEMON + " Move 1 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON1_MOVE2_PP("2nd " + STRING_POKEMON + " Move 2 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON1_MOVE3_PP("2nd " + STRING_POKEMON + " Move 3 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MON1_MOVE4_PP("2nd " + STRING_POKEMON + " Move 4 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(SHORTCUT); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(HEALING_METHOD); - PA_ADD_OPTION(ON_LEARN_MOVE); - PA_ADD_OPTION(MON0_MOVE1_PP); - PA_ADD_OPTION(MON0_MOVE2_PP); - PA_ADD_OPTION(MON0_MOVE3_PP); - PA_ADD_OPTION(MON0_MOVE4_PP); - PA_ADD_OPTION(MON1_MOVE1_PP); - PA_ADD_OPTION(MON1_MOVE2_PP); - PA_ADD_OPTION(MON1_MOVE3_PP); - PA_ADD_OPTION(MON1_MOVE4_PP); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -bool MoneyFarmerRoute210::battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp0[4], uint8_t pp1[4]){ - MoneyFarmerRoute210_Descriptor::Stats& stats = env.current_stats(); - - env.log("Starting battle!"); - - { - StartBattleDetector detector(env.console); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 10, 10); - for (size_t c = 0; c < 17; c++){ - pbf_press_dpad(context, DPAD_UP, 5, 10); - pbf_press_button(context, BUTTON_ZL, 10, 10); - pbf_press_dpad(context, DPAD_RIGHT, 20, 10); - pbf_press_button(context, BUTTON_ZL, 10, 10); - } - }, - {{detector}} - ); - if (ret < 0){ - stats.m_errors++; - env.log("Failed to detect start of battle after 20 seconds.", COLOR_RED); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - return false; - } - } - pbf_wait(context, 5 * TICKS_PER_SECOND); - - bool battle_menu_seen = false; - - // State Machine - // We need lots of loops in case the party pokemon need to learn lots of moves. - while (true){ - context.wait_for_all_requests(); - - BattleMenuWatcher battle_menu(BattleType::TRAINER); - EndBattleWatcher end_battle; - SelectionArrowFinder learn_move(env.console, {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - { - {battle_menu}, - battle_menu_seen ? PeriodicInferenceCallback{end_battle} : PeriodicInferenceCallback{}, - {learn_move}, - } - ); - switch (ret){ - case 0: - env.log("Battle menu detected!", COLOR_BLUE); - battle_menu_seen = true; - - { - pbf_press_button(context, BUTTON_ZL, 10, 125); - uint8_t slot = 0; - for (; slot < 4; slot++){ - if (pp0[slot] != 0){ - break; - } - } - if (slot == 4){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Ran out of PP in a battle.", - env.console - ); - } - - for (uint8_t move_slot = 0; move_slot < slot; move_slot++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } - pbf_press_button(context, BUTTON_ZL, 10, 125); - pbf_press_button(context, BUTTON_ZL, 10, 375); - pp0[slot]--; - } - - { - pbf_press_button(context, BUTTON_ZL, 10, 125); - uint8_t slot = 0; - for (; slot < 4; slot++){ - if (pp1[slot] != 0){ - break; - } - } - if (slot == 4){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Ran out of PP in a battle.", - env.console - ); - } - - for (uint8_t move_slot = 0; move_slot < slot; move_slot++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } - pbf_press_button(context, BUTTON_ZL, 10, 125); - pbf_press_button(context, BUTTON_ZL, 10, 375); - pp1[slot]--; - } - - break; - case 1: - env.log("Battle finished!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_B, 250); - return false; - case 2: - env.log("Detected move learn!", COLOR_BLUE); - if (ON_LEARN_MOVE == OnLearnMove::DONT_LEARN){ - pbf_move_right_joystick(context, 128, 255, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - } - return true; - default: - stats.m_errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out after 2 minutes.", - env.console - ); - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No progress detected after 5 battle menus. Are you out of PP?", - env.console - ); -} - -void MoneyFarmerRoute210::heal_at_center_and_return( - Logger& logger, ProControllerContext& context, - uint8_t pp0[4], uint8_t pp1[4] -){ - logger.log("Healing " + STRING_POKEMON + " Celestic Town " + STRING_POKEMON + " Center."); - pbf_move_left_joystick(context, 125, 0, 6 * TICKS_PER_SECOND, 0); - pbf_mash_button(context, BUTTON_ZL, 3 * TICKS_PER_SECOND); - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - - logger.log("Returning to trainers..."); - pbf_move_left_joystick(context, 128, 255, 6 * TICKS_PER_SECOND, 0); - pbf_move_left_joystick(context, 255, 128, 60, 0); - pbf_move_left_joystick(context, 128, 0, 200, 0); - pbf_move_left_joystick(context, 255, 128, 750, 0); - - pbf_press_button(context, BUTTON_R, 10, 150); - pbf_mash_button(context, BUTTON_ZL, 6 * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 255, 30, 0); - pbf_move_left_joystick(context, 0, 128, 30, 0); - pbf_move_left_joystick(context, 128, 255, 80, 0); - pbf_move_left_joystick(context, 255, 128, 110, 0); - pbf_move_left_joystick(context, 128, 255, 125, 0); - pbf_move_left_joystick(context, 255, 128, 105, 0); - pbf_move_left_joystick(context, 128, 0, 375, 0); - pbf_move_left_joystick(context, 255, 128, 300, 0); - pbf_move_left_joystick(context, 128, 255, 375, 0); - - pbf_press_dpad(context, DPAD_RIGHT, 375, 0); - pbf_press_dpad(context, DPAD_LEFT, 375, 0); - pbf_press_dpad(context, DPAD_DOWN, 125, 0); - - pp0[0] = MON0_MOVE1_PP; - pp0[1] = MON0_MOVE2_PP; - pp0[2] = MON0_MOVE3_PP; - pp0[3] = MON0_MOVE4_PP; - pp1[0] = MON1_MOVE1_PP; - pp1[1] = MON1_MOVE2_PP; - pp1[2] = MON1_MOVE3_PP; - pp1[3] = MON1_MOVE4_PP; -} -void MoneyFarmerRoute210::fly_to_center_heal_and_return( - Logger& logger, ProControllerContext& context, - uint8_t pp0[4], uint8_t pp1[4] -){ - logger.log("Flying back to Hearthome City to heal."); - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_PLUS, 10, 240); - pbf_press_dpad(context, DPAD_LEFT, 10, 60); - pbf_press_dpad(context, DPAD_LEFT, 10, 60); - pbf_mash_button(context, BUTTON_ZL, 12 * TICKS_PER_SECOND); - heal_at_center_and_return(logger, context, pp0, pp1); -} - -bool MoneyFarmerRoute210::heal_after_battle_and_return( - SingleSwitchProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - uint8_t pp0[4], uint8_t pp1[4]) -{ - if (HEALING_METHOD == HealMethod::CelesticTown){ - // Go to Celestic Town Pokecenter to heal the party. - fly_to_center_heal_and_return(stream.logger(), context, pp0, pp1); - return false; - }else{ - // Use Global Room to heal the party. - heal_by_global_room(stream, context); - - pp0[0] = MON0_MOVE1_PP; - pp0[1] = MON0_MOVE2_PP; - pp0[2] = MON0_MOVE3_PP; - pp0[3] = MON0_MOVE4_PP; - pp1[0] = MON1_MOVE1_PP; - pp1[1] = MON1_MOVE2_PP; - pp1[2] = MON1_MOVE3_PP; - pp1[3] = MON1_MOVE4_PP; - return true; - } -} - - -bool MoneyFarmerRoute210::has_pp(uint8_t pp0[4], uint8_t pp1[4]){ - size_t count0 = 0; - size_t count1 = 0; - for (size_t c = 0; c < 4; c++){ - count0 += pp0[c]; - count1 += pp1[c]; - } - return count0 > 0 && count1 > 0; -} - - - -void MoneyFarmerRoute210::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MoneyFarmerRoute210_Descriptor::Stats& stats = env.current_stats(); - - uint8_t pp0[4] = { - MON0_MOVE1_PP, - MON0_MOVE2_PP, - MON0_MOVE3_PP, - MON0_MOVE4_PP, - }; - uint8_t pp1[4] = { - MON1_MOVE1_PP, - MON1_MOVE2_PP, - MON1_MOVE3_PP, - MON1_MOVE4_PP, - }; - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - bool need_to_charge = true; - if (START_LOCATION == StartLocation::CelesticTown){ - heal_at_center_and_return(env.console, context, pp0, pp1); - need_to_charge = false; - }else{ - if (HEALING_METHOD == HealMethod::GlobalRoom){ - heal_by_global_room(env.console, context); - } - pbf_move_left_joystick(context, 255, 128, 140, 0); - } - - while (true){ - env.update_stats(); - - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (need_to_charge){ - pbf_move_left_joystick(context, 255, 128, 140, 0); - pbf_press_dpad(context, DPAD_UP, 85, 0); - for (size_t c = 0; c < 7; c++){ - pbf_move_left_joystick(context, 0, 128, 140, 0); - pbf_move_left_joystick(context, 255, 128, 140, 0); - } - pbf_press_dpad(context, DPAD_DOWN, 75, 0); - } - pbf_press_dpad(context, DPAD_LEFT, 200, 0); - - context.wait_for_all_requests(); - stats.m_searches++; - - std::vector bubbles; - { - VSSeekerReactionTracker tracker(env.console, {0.20, 0.20, 0.60, 0.60}); - run_until( - env.console, context, - [this](ProControllerContext& context){ - SHORTCUT.run(context, TICKS_PER_SECOND); - }, - {{tracker}} - ); - need_to_charge = true; - pbf_mash_button(context, BUTTON_B, 250); - - bubbles = tracker.reactions(); - if (bubbles.empty()){ - env.log("No reactions.", COLOR_ORANGE); - stats.m_noreact++; - continue; - } - stats.m_react++; - } - for (const ImagePixelBox& box : bubbles){ - env.log("Reaction at: " + std::to_string(box.min_x), COLOR_BLUE); - } - - if (this->battle(env, context, pp0, pp1)){ - return; - } - if (!has_pp(pp0, pp1)){ - need_to_charge = heal_after_battle_and_return(env, env.console, context, pp0, pp1); - continue; - } - } -} - - - - - - -} -} -} - - - - - - - - - - +/* Money Farmer (Route 210) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h" +#include "PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP_MoneyFarmerRoute210.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +MoneyFarmerRoute210_Descriptor::MoneyFarmerRoute210_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:MoneyFarmerRoute210", + STRING_POKEMON + " BDSP", "Money Farmer (Route 210)", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/MoneyFarmerRoute210.md", + "Farm money by using VS Seeker to rebattle the Ace Trainer couple on Route 210.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + } + ) +{} +struct MoneyFarmerRoute210_Descriptor::Stats : public StatsTracker{ + Stats() + : m_searches(m_stats["Searches"]) + , m_errors(m_stats["Errors"]) + , m_noreact(m_stats["No React"]) + , m_react(m_stats["React"]) + { + m_display_order.emplace_back("Searches"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("No React"); + m_display_order.emplace_back("React"); + } + std::atomic& m_searches; + std::atomic& m_errors; + std::atomic& m_noreact; + std::atomic& m_react; +}; +std::unique_ptr MoneyFarmerRoute210_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +MoneyFarmerRoute210::MoneyFarmerRoute210() + : SHORTCUT("VS Seeker Shortcut:") + , START_LOCATION( + "Start Location:", + { + {StartLocation::CelesticTown, "celestic", "In front of the Celestic Town " + STRING_POKEMON + " center."}, + {StartLocation::AceTrainerPair, "trainer-pair", "Lower-most row of the platform the Ace Trainer pair in Route 210 is on."}, + }, + LockMode::LOCK_WHILE_RUNNING, + StartLocation::CelesticTown + ) + , HEALING_METHOD( + " Healing method:", + { + {HealMethod::CelesticTown, "celestic", "Celestic Town " + STRING_POKEMON + " center."}, + {HealMethod::GlobalRoom, "global-room", "Use Global Room. (will force update your game)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + HealMethod::CelesticTown + ) + , MON0_MOVE1_PP("Lead " + STRING_POKEMON + " Move 1 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON0_MOVE2_PP("Lead " + STRING_POKEMON + " Move 2 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON0_MOVE3_PP("Lead " + STRING_POKEMON + " Move 3 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON0_MOVE4_PP("Lead " + STRING_POKEMON + " Move 4 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON1_MOVE1_PP("2nd " + STRING_POKEMON + " Move 1 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON1_MOVE2_PP("2nd " + STRING_POKEMON + " Move 2 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON1_MOVE3_PP("2nd " + STRING_POKEMON + " Move 3 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MON1_MOVE4_PP("2nd " + STRING_POKEMON + " Move 4 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(SHORTCUT); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(HEALING_METHOD); + PA_ADD_OPTION(ON_LEARN_MOVE); + PA_ADD_OPTION(MON0_MOVE1_PP); + PA_ADD_OPTION(MON0_MOVE2_PP); + PA_ADD_OPTION(MON0_MOVE3_PP); + PA_ADD_OPTION(MON0_MOVE4_PP); + PA_ADD_OPTION(MON1_MOVE1_PP); + PA_ADD_OPTION(MON1_MOVE2_PP); + PA_ADD_OPTION(MON1_MOVE3_PP); + PA_ADD_OPTION(MON1_MOVE4_PP); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +bool MoneyFarmerRoute210::battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp0[4], uint8_t pp1[4]){ + MoneyFarmerRoute210_Descriptor::Stats& stats = env.current_stats(); + + env.log("Starting battle!"); + + { + StartBattleDetector detector(env.console); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 10, 10); + for (size_t c = 0; c < 17; c++){ + pbf_press_dpad(context, DPAD_UP, 5, 10); + pbf_press_button(context, BUTTON_ZL, 10, 10); + pbf_press_dpad(context, DPAD_RIGHT, 20, 10); + pbf_press_button(context, BUTTON_ZL, 10, 10); + } + }, + {{detector}} + ); + if (ret < 0){ + stats.m_errors++; + env.log("Failed to detect start of battle after 20 seconds.", COLOR_RED); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + return false; + } + } + pbf_wait(context, 5 * TICKS_PER_SECOND); + + bool battle_menu_seen = false; + + // State Machine + // We need lots of loops in case the party pokemon need to learn lots of moves. + while (true){ + context.wait_for_all_requests(); + + BattleMenuWatcher battle_menu(BattleType::TRAINER); + EndBattleWatcher end_battle; + SelectionArrowFinder learn_move(env.console, {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + { + {battle_menu}, + battle_menu_seen ? PeriodicInferenceCallback{end_battle} : PeriodicInferenceCallback{}, + {learn_move}, + } + ); + switch (ret){ + case 0: + env.log("Battle menu detected!", COLOR_BLUE); + battle_menu_seen = true; + + { + pbf_press_button(context, BUTTON_ZL, 10, 125); + uint8_t slot = 0; + for (; slot < 4; slot++){ + if (pp0[slot] != 0){ + break; + } + } + if (slot == 4){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Ran out of PP in a battle.", + env.console + ); + } + + for (uint8_t move_slot = 0; move_slot < slot; move_slot++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } + pbf_press_button(context, BUTTON_ZL, 10, 125); + pbf_press_button(context, BUTTON_ZL, 10, 375); + pp0[slot]--; + } + + { + pbf_press_button(context, BUTTON_ZL, 10, 125); + uint8_t slot = 0; + for (; slot < 4; slot++){ + if (pp1[slot] != 0){ + break; + } + } + if (slot == 4){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Ran out of PP in a battle.", + env.console + ); + } + + for (uint8_t move_slot = 0; move_slot < slot; move_slot++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } + pbf_press_button(context, BUTTON_ZL, 10, 125); + pbf_press_button(context, BUTTON_ZL, 10, 375); + pp1[slot]--; + } + + break; + case 1: + env.log("Battle finished!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_B, 250); + return false; + case 2: + env.log("Detected move learn!", COLOR_BLUE); + if (ON_LEARN_MOVE == OnLearnMove::DONT_LEARN){ + pbf_move_right_joystick(context, 128, 255, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + } + return true; + default: + stats.m_errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out after 2 minutes.", + env.console + ); + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No progress detected after 5 battle menus. Are you out of PP?", + env.console + ); +} + +void MoneyFarmerRoute210::heal_at_center_and_return( + Logger& logger, ProControllerContext& context, + uint8_t pp0[4], uint8_t pp1[4] +){ + logger.log("Healing " + STRING_POKEMON + " Celestic Town " + STRING_POKEMON + " Center."); + pbf_move_left_joystick(context, 125, 0, 6 * TICKS_PER_SECOND, 0); + pbf_mash_button(context, BUTTON_ZL, 3 * TICKS_PER_SECOND); + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + + logger.log("Returning to trainers..."); + pbf_move_left_joystick(context, 128, 255, 6 * TICKS_PER_SECOND, 0); + pbf_move_left_joystick(context, 255, 128, 60, 0); + pbf_move_left_joystick(context, 128, 0, 200, 0); + pbf_move_left_joystick(context, 255, 128, 750, 0); + + pbf_press_button(context, BUTTON_R, 10, 150); + pbf_mash_button(context, BUTTON_ZL, 6 * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 255, 30, 0); + pbf_move_left_joystick(context, 0, 128, 30, 0); + pbf_move_left_joystick(context, 128, 255, 80, 0); + pbf_move_left_joystick(context, 255, 128, 110, 0); + pbf_move_left_joystick(context, 128, 255, 125, 0); + pbf_move_left_joystick(context, 255, 128, 105, 0); + pbf_move_left_joystick(context, 128, 0, 375, 0); + pbf_move_left_joystick(context, 255, 128, 300, 0); + pbf_move_left_joystick(context, 128, 255, 375, 0); + + pbf_press_dpad(context, DPAD_RIGHT, 375, 0); + pbf_press_dpad(context, DPAD_LEFT, 375, 0); + pbf_press_dpad(context, DPAD_DOWN, 125, 0); + + pp0[0] = MON0_MOVE1_PP; + pp0[1] = MON0_MOVE2_PP; + pp0[2] = MON0_MOVE3_PP; + pp0[3] = MON0_MOVE4_PP; + pp1[0] = MON1_MOVE1_PP; + pp1[1] = MON1_MOVE2_PP; + pp1[2] = MON1_MOVE3_PP; + pp1[3] = MON1_MOVE4_PP; +} +void MoneyFarmerRoute210::fly_to_center_heal_and_return( + Logger& logger, ProControllerContext& context, + uint8_t pp0[4], uint8_t pp1[4] +){ + logger.log("Flying back to Hearthome City to heal."); + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_PLUS, 10, 240); + pbf_press_dpad(context, DPAD_LEFT, 10, 60); + pbf_press_dpad(context, DPAD_LEFT, 10, 60); + pbf_mash_button(context, BUTTON_ZL, 12 * TICKS_PER_SECOND); + heal_at_center_and_return(logger, context, pp0, pp1); +} + +bool MoneyFarmerRoute210::heal_after_battle_and_return( + SingleSwitchProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + uint8_t pp0[4], uint8_t pp1[4]) +{ + if (HEALING_METHOD == HealMethod::CelesticTown){ + // Go to Celestic Town Pokecenter to heal the party. + fly_to_center_heal_and_return(stream.logger(), context, pp0, pp1); + return false; + }else{ + // Use Global Room to heal the party. + heal_by_global_room(stream, context); + + pp0[0] = MON0_MOVE1_PP; + pp0[1] = MON0_MOVE2_PP; + pp0[2] = MON0_MOVE3_PP; + pp0[3] = MON0_MOVE4_PP; + pp1[0] = MON1_MOVE1_PP; + pp1[1] = MON1_MOVE2_PP; + pp1[2] = MON1_MOVE3_PP; + pp1[3] = MON1_MOVE4_PP; + return true; + } +} + + +bool MoneyFarmerRoute210::has_pp(uint8_t pp0[4], uint8_t pp1[4]){ + size_t count0 = 0; + size_t count1 = 0; + for (size_t c = 0; c < 4; c++){ + count0 += pp0[c]; + count1 += pp1[c]; + } + return count0 > 0 && count1 > 0; +} + + + +void MoneyFarmerRoute210::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MoneyFarmerRoute210_Descriptor::Stats& stats = env.current_stats(); + + uint8_t pp0[4] = { + MON0_MOVE1_PP, + MON0_MOVE2_PP, + MON0_MOVE3_PP, + MON0_MOVE4_PP, + }; + uint8_t pp1[4] = { + MON1_MOVE1_PP, + MON1_MOVE2_PP, + MON1_MOVE3_PP, + MON1_MOVE4_PP, + }; + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + bool need_to_charge = true; + if (START_LOCATION == StartLocation::CelesticTown){ + heal_at_center_and_return(env.console, context, pp0, pp1); + need_to_charge = false; + }else{ + if (HEALING_METHOD == HealMethod::GlobalRoom){ + heal_by_global_room(env.console, context); + } + pbf_move_left_joystick(context, 255, 128, 140, 0); + } + + while (true){ + env.update_stats(); + + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (need_to_charge){ + pbf_move_left_joystick(context, 255, 128, 140, 0); + pbf_press_dpad(context, DPAD_UP, 85, 0); + for (size_t c = 0; c < 7; c++){ + pbf_move_left_joystick(context, 0, 128, 140, 0); + pbf_move_left_joystick(context, 255, 128, 140, 0); + } + pbf_press_dpad(context, DPAD_DOWN, 75, 0); + } + pbf_press_dpad(context, DPAD_LEFT, 200, 0); + + context.wait_for_all_requests(); + stats.m_searches++; + + std::vector bubbles; + { + VSSeekerReactionTracker tracker(env.console, {0.20, 0.20, 0.60, 0.60}); + run_until( + env.console, context, + [this](ProControllerContext& context){ + SHORTCUT.run(context, TICKS_PER_SECOND); + }, + {{tracker}} + ); + need_to_charge = true; + pbf_mash_button(context, BUTTON_B, 250); + + bubbles = tracker.reactions(); + if (bubbles.empty()){ + env.log("No reactions.", COLOR_ORANGE); + stats.m_noreact++; + continue; + } + stats.m_react++; + } + for (const ImagePixelBox& box : bubbles){ + env.log("Reaction at: " + std::to_string(box.min_x), COLOR_BLUE); + } + + if (this->battle(env, context, pp0, pp1)){ + return; + } + if (!has_pp(pp0, pp1)){ + need_to_charge = heal_after_battle_and_return(env, env.console, context, pp0, pp1); + continue; + } + } +} + + + + + + +} +} +} + + + + + + + + + + diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h index 9c735d2014..43b892f85e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute210.h @@ -1,94 +1,94 @@ -/* Money Farmer (Route 210) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_MoneyFarmerRoute210_H -#define PokemonAutomation_PokemonBDSP_MoneyFarmerRoute210_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" -#include "PokemonBDSP/Options/PokemonBDSP_LearnMove.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class MoneyFarmerRoute210_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MoneyFarmerRoute210_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class MoneyFarmerRoute210 : public SingleSwitchProgramInstance{ -public: - MoneyFarmerRoute210(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - // Run the battle loop. Return true if the program should stop. - bool battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp0[4], uint8_t pp1[4]); - // From the bottom row of the Ace Trainer pair, heal Pokemon and return. - // Return true if VS Seeker needs charging. - bool heal_after_battle_and_return( - SingleSwitchProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - uint8_t pp0[4], uint8_t pp1[4] - ); - // Starting in front of the Celestic Town Pokecenter, heal and return - // to the Ace Trainer pair. - void heal_at_center_and_return(Logger& logger, ProControllerContext& context, uint8_t pp0[4], uint8_t pp1[4]); - // Fly from the Ace Trainer pair to Hearthome Pokecenter, heal and return. - void fly_to_center_heal_and_return( - Logger& logger, ProControllerContext& context, - uint8_t pp0[4],uint8_t pp1[4] - ); - // Move around to charge VS Seeker. - void charge_vs_seeker(VideoStream& stream); - - static bool has_pp(uint8_t pp0[4], uint8_t pp1[4]); - -private: - enum class StartLocation{ - CelesticTown, - AceTrainerPair, - }; - enum class HealMethod{ - CelesticTown, - GlobalRoom, - }; - - ShortcutDirectionOption SHORTCUT; - - EnumDropdownOption START_LOCATION; - EnumDropdownOption HEALING_METHOD; - OnLearnMoveOption ON_LEARN_MOVE; - - SimpleIntegerOption MON0_MOVE1_PP; - SimpleIntegerOption MON0_MOVE2_PP; - SimpleIntegerOption MON0_MOVE3_PP; - SimpleIntegerOption MON0_MOVE4_PP; - - SimpleIntegerOption MON1_MOVE1_PP; - SimpleIntegerOption MON1_MOVE2_PP; - SimpleIntegerOption MON1_MOVE3_PP; - SimpleIntegerOption MON1_MOVE4_PP; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Money Farmer (Route 210) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_MoneyFarmerRoute210_H +#define PokemonAutomation_PokemonBDSP_MoneyFarmerRoute210_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" +#include "PokemonBDSP/Options/PokemonBDSP_LearnMove.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class MoneyFarmerRoute210_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MoneyFarmerRoute210_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class MoneyFarmerRoute210 : public SingleSwitchProgramInstance{ +public: + MoneyFarmerRoute210(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + // Run the battle loop. Return true if the program should stop. + bool battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp0[4], uint8_t pp1[4]); + // From the bottom row of the Ace Trainer pair, heal Pokemon and return. + // Return true if VS Seeker needs charging. + bool heal_after_battle_and_return( + SingleSwitchProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + uint8_t pp0[4], uint8_t pp1[4] + ); + // Starting in front of the Celestic Town Pokecenter, heal and return + // to the Ace Trainer pair. + void heal_at_center_and_return(Logger& logger, ProControllerContext& context, uint8_t pp0[4], uint8_t pp1[4]); + // Fly from the Ace Trainer pair to Hearthome Pokecenter, heal and return. + void fly_to_center_heal_and_return( + Logger& logger, ProControllerContext& context, + uint8_t pp0[4],uint8_t pp1[4] + ); + // Move around to charge VS Seeker. + void charge_vs_seeker(VideoStream& stream); + + static bool has_pp(uint8_t pp0[4], uint8_t pp1[4]); + +private: + enum class StartLocation{ + CelesticTown, + AceTrainerPair, + }; + enum class HealMethod{ + CelesticTown, + GlobalRoom, + }; + + ShortcutDirectionOption SHORTCUT; + + EnumDropdownOption START_LOCATION; + EnumDropdownOption HEALING_METHOD; + OnLearnMoveOption ON_LEARN_MOVE; + + SimpleIntegerOption MON0_MOVE1_PP; + SimpleIntegerOption MON0_MOVE2_PP; + SimpleIntegerOption MON0_MOVE3_PP; + SimpleIntegerOption MON0_MOVE4_PP; + + SimpleIntegerOption MON1_MOVE1_PP; + SimpleIntegerOption MON1_MOVE2_PP; + SimpleIntegerOption MON1_MOVE3_PP; + SimpleIntegerOption MON1_MOVE4_PP; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.cpp index fdb7e742f3..959bb85608 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.cpp @@ -1,460 +1,460 @@ -/* Money Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h" -#include "PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h" -#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" -#include "PokemonBDSP_MoneyFarmerRoute212.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -MoneyFarmerRoute212_Descriptor::MoneyFarmerRoute212_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:MoneyFarmerRoute212", - STRING_POKEMON + " BDSP", "Money Farmer (Route 212)", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/MoneyFarmerRoute212.md", - "Farm money by using VS Seeker to rebattle the rich couple on Route 212.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - } - ) -{} -struct MoneyFarmerRoute212_Descriptor::Stats : public StatsTracker{ - Stats() - : m_searches(m_stats["Searches"]) - , m_errors(m_stats["Errors"]) - , m_nothing(m_stats["No React"]) - , m_man(m_stats["Man Only"]) - , m_woman(m_stats["Woman Only"]) - , m_both(m_stats["Both"]) - { - m_display_order.emplace_back("Searches"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("No React"); - m_display_order.emplace_back("Man Only"); - m_display_order.emplace_back("Woman Only"); - m_display_order.emplace_back("Both"); - } - std::atomic& m_searches; - std::atomic& m_errors; - std::atomic& m_nothing; - std::atomic& m_man; - std::atomic& m_woman; - std::atomic& m_both; -}; -std::unique_ptr MoneyFarmerRoute212_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -MoneyFarmerRoute212::MoneyFarmerRoute212() - : SHORTCUT("VS Seeker Shortcut:") - , START_LOCATION( - "Start Location:", - { - {StartLocation::Hearthome, "hearthome", "In front of the Hearthome City " + STRING_POKEMON + " center."}, - {StartLocation::OldCouple, "old-couple", "In the row above the rich couple in Route 212."}, - }, - LockMode::LOCK_WHILE_RUNNING, - StartLocation::Hearthome - ) - , HEALING_METHOD( - " Healing method:", - { - {HealMethod::Hearthome, "hearthome", "Hearthome City " + STRING_POKEMON + " center."}, - {HealMethod::GlobalRoom, "global-room", "Use Global Room. (will force update your game)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - HealMethod::Hearthome - ) - , MOVE1_PP("Move 1 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MOVE2_PP("Move 2 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MOVE3_PP("Move 3 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , MOVE4_PP("Move 4 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(SHORTCUT); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(HEALING_METHOD); - PA_ADD_OPTION(ON_LEARN_MOVE); - PA_ADD_OPTION(MOVE1_PP); - PA_ADD_OPTION(MOVE2_PP); - PA_ADD_OPTION(MOVE3_PP); - PA_ADD_OPTION(MOVE4_PP); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -bool MoneyFarmerRoute212::battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp[4], bool man){ - MoneyFarmerRoute212_Descriptor::Stats& stats = env.current_stats(); - context.wait_for_all_requests(); - if (man){ - env.log("Starting battle with man (left)."); - }else{ - env.log("Starting battle with woman (right)."); - } - env.console.overlay().add_log("Starting battle", COLOR_WHITE); - - pbf_mash_button(context, BUTTON_ZL, 5 * TICKS_PER_SECOND); - - bool battle_menu_seen = false; - - // State Machine - // We need lots of loops in case the party pokemon need to learn lots of moves. - while (true){ - context.wait_for_all_requests(); - - BattleMenuWatcher battle_menu(BattleType::TRAINER); - EndBattleWatcher end_battle; - SelectionArrowFinder learn_move(env.console, {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 30 * TICKS_PER_SECOND); - }, - { - {battle_menu}, - battle_menu_seen ? PeriodicInferenceCallback{end_battle} : PeriodicInferenceCallback{}, - {learn_move}, - } - ); - switch (ret){ - case 0:{ - env.log("Battle menu detected!", COLOR_BLUE); - env.console.overlay().add_log("Choose move", COLOR_BLUE); - battle_menu_seen = true; - - pbf_press_button(context, BUTTON_ZL, 10, 125); - - uint8_t slot = 0; - for (; slot < 4; slot++){ - if (pp[slot] != 0){ - break; - } - } - if (slot == 4){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Ran out of PP in a battle.", - env.console - ); - } - - for (uint8_t move_slot = 0; move_slot < slot; move_slot++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } - pbf_mash_button(context, BUTTON_ZL, 250); - pp[slot]--; - env.log("Used move at slot " + std::to_string(slot+1) + ". " + std::to_string(pp[slot]) + " PP left.", COLOR_BLUE); - - break; - } - case 1: - env.log("Battle finished!", COLOR_BLUE); - env.console.overlay().add_log("Battle finished", COLOR_WHITE); - pbf_mash_button(context, BUTTON_B, 250); - return false; -// case 1: -// env.log("Dialog detected! Battle finished?", COLOR_BLUE); -// pbf_mash_button(context, BUTTON_B, 250); -// return; - case 2: - env.log("Detected move to learn!", COLOR_BLUE); - env.console.overlay().add_log("Detected move to learn", COLOR_WHITE); - if (ON_LEARN_MOVE == OnLearnMove::DONT_LEARN){ - pbf_move_right_joystick(context, 128, 255, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - } - return true; - - default: - stats.m_errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out after 30 seconds.", - env.console - ); - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No progress detected after 5 battle menus. Are you out of PP?", - env.console - ); -} - - -void MoneyFarmerRoute212::heal_at_center_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]){ - stream.overlay().add_log("Heal at " + STRING_POKEMON + " Center", COLOR_WHITE); - stream.log("Healing " + STRING_POKEMON + " at Hearthome City " + STRING_POKEMON + " Center."); - pbf_move_left_joystick(context, 125, 0, 6 * TICKS_PER_SECOND, 0); - pbf_mash_button(context, BUTTON_ZL, 3 * TICKS_PER_SECOND); -// ssf_mash_AZs(context, 3 * TICKS_PER_SECOND); - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - stream.overlay().add_log("Heal complete", COLOR_WHITE); - stream.overlay().add_log("To rich couple", COLOR_WHITE); - stream.log("Returning to rich couple location..."); - pbf_move_left_joystick(context, 128, 255, 8 * TICKS_PER_SECOND, 0); - pbf_move_left_joystick(context, 255, 128, 380, 0); - pbf_move_left_joystick(context, 128, 255, 300, 0); - pbf_move_left_joystick(context, 0, 128, 600, 0); - pbf_move_left_joystick(context, 255, 128, 75, 0); - pbf_move_left_joystick(context, 128, 255, 1375, 0); - pbf_move_left_joystick(context, 255, 128, 125, 0); - pbf_move_left_joystick(context, 128, 255, 200, 0); - pbf_move_left_joystick(context, 0, 128, 200, 0); - pbf_move_left_joystick(context, 128, 255, 50, 0); - pbf_move_left_joystick(context, 0, 128, 125, 0); - pbf_move_left_joystick(context, 128, 255, 125, 0); - pbf_move_left_joystick(context, 255, 128, 250, 0); - pbf_move_left_joystick(context, 128, 255, 200, 0); - pbf_move_left_joystick(context, 0, 128, 90, 0); - pbf_move_left_joystick(context, 128, 255, 200, 0); - pbf_move_left_joystick(context, 255, 128, 125, 0); - pbf_move_left_joystick(context, 128, 255, 200, 0); - - pp[0] = MOVE1_PP; - pp[1] = MOVE2_PP; - pp[2] = MOVE3_PP; - pp[3] = MOVE4_PP; - context.wait_for_all_requests(); -} - - -void MoneyFarmerRoute212::fly_to_center_heal_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]){ - stream.log("Flying back to Hearthome City to heal."); - stream.overlay().add_log("Fly to Hearthome City", COLOR_WHITE); - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_PLUS, 10, 240); - pbf_press_dpad(context, DPAD_UP, 10, 60); - pbf_press_dpad(context, DPAD_UP, 10, 60); - pbf_mash_button(context, BUTTON_ZL, 12 * TICKS_PER_SECOND); - heal_at_center_and_return(stream, context, pp); -} - -bool MoneyFarmerRoute212::heal_after_battle_and_return( - VideoStream& stream, ProControllerContext& context, - uint8_t pp[4]) -{ - if (HEALING_METHOD == HealMethod::Hearthome){ - // Go to Hearhome City Pokecenter to heal the party. - fly_to_center_heal_and_return(stream, context, pp); - return false; - }else{ - // Use Global Room to heal the party. - heal_by_global_room(stream, context); - - pp[0] = MOVE1_PP; - pp[1] = MOVE2_PP; - pp[2] = MOVE3_PP; - pp[3] = MOVE4_PP; - return true; - } -} - -void MoneyFarmerRoute212::charge_vs_seeker(ProControllerContext& context){ - for (size_t c = 0; c < 5; c++){ - pbf_move_left_joystick(context, 0, 128, 180, 0); - pbf_move_left_joystick(context, 255, 128, 180, 0); - } -} - - -size_t MoneyFarmerRoute212::total_pp(uint8_t pp[4]){ - size_t ret = 0; - ret += pp[0]; - ret += pp[1]; - ret += pp[2]; - ret += pp[3]; - return ret; -} - - -void MoneyFarmerRoute212::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MoneyFarmerRoute212_Descriptor::Stats& stats = env.current_stats(); - - uint8_t pp[4] = { - MOVE1_PP, - MOVE2_PP, - MOVE3_PP, - MOVE4_PP, - }; - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - bool need_to_charge = true; - if (START_LOCATION == StartLocation::Hearthome){ - heal_at_center_and_return(env.console, context, pp); - need_to_charge = false; - }else{ // start location is the row above the rich couple - if (HEALING_METHOD == HealMethod::GlobalRoom){ - heal_by_global_room(env.console, context); - } - // Reset position to right most on the row above the rich couple - pbf_move_left_joystick(context, 255, 128, 180, 0); - } - - while (true){ - context.wait_for_all_requests(); - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (need_to_charge){ - env.console.overlay().add_log("Charging Vs. Seeker", COLOR_WHITE); - charge_vs_seeker(context); - } - - // Move to woman. - pbf_move_left_joystick(context, 0, 128, 52, 0); - - context.wait_for_all_requests(); - stats.m_searches++; - - QSize dimensions; - std::vector bubbles; - { - env.console.overlay().add_log("Using Vs. Seeker", COLOR_WHITE); - VSSeekerReactionTracker tracker(env.console, {0.23, 0.30, 0.35, 0.30}); - run_until( - env.console, context, - [this](ProControllerContext& context){ - SHORTCUT.run(context, TICKS_PER_SECOND); - - }, - {{tracker}} - ); - need_to_charge = true; - pbf_mash_button(context, BUTTON_B, 250); - - dimensions = tracker.dimensions(); - bubbles = tracker.reactions(); - if (bubbles.empty()){ - env.log("No reactions.", COLOR_ORANGE); - stats.m_nothing++; - continue; - } - } - - bool man = false; - bool woman = false; - for (const ImagePixelBox& box : bubbles){ - double x_coord = (double)box.min_x / dimensions.width(); - env.log("Reaction at: " + std::to_string(x_coord), COLOR_BLUE); - if (x_coord < 0.5){ - man = true; - } - if (x_coord > 0.5){ - woman = true; - } - } - - if (man && woman){ - env.console.overlay().add_log("Found both", COLOR_GREEN); - stats.m_both++; - }else if (man){ - env.console.overlay().add_log("Found Gentleman", COLOR_GREEN); - stats.m_man++; - }else if (woman){ - env.console.overlay().add_log("Found Madame", COLOR_GREEN); - stats.m_woman++; - } - - env.update_stats(); - - if (woman){ -// pbf_move_left_joystick(context, 0, 128, 52, 0); - pbf_move_left_joystick(context, 128, 255, 10, 0); - - // Battle woman. - if(battle(env, context, pp, false)){ - return; - } - - // Check PP. - if (total_pp(pp) == 0){ - need_to_charge = heal_after_battle_and_return(env.console, context, pp); - continue; - } - } - if (man){ -#if 0 - // Make sure we have enough PP. - if (total_pp(pp) < 2){ - need_to_charge = heal_after_battle_and_return(env.console, pp); - continue; - } -#endif - -// if (woman){ - pbf_move_left_joystick(context, 0, 128, 52, 0); - pbf_move_left_joystick(context, 128, 255, 10, 0); -// }else{ -// pbf_move_left_joystick(context, 0, 128, 105, 0); -// pbf_move_left_joystick(context, 128, 255, 10, 0); -// } - - // Battle man. - if (battle(env, context, pp, true)){ - return; - } - - // Check PP. - if (total_pp(pp) == 0){ - need_to_charge = heal_after_battle_and_return(env.console, context, pp); - continue; - } - } - pbf_move_left_joystick(context, 255, 128, 180, 0); - - } -} - - - - - - - -} -} -} - - - - - - - - - - +/* Money Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h" +#include "PokemonBDSP/Inference/PokemonBDSP_VSSeekerReaction.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP_MoneyFarmerRoute212.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +MoneyFarmerRoute212_Descriptor::MoneyFarmerRoute212_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:MoneyFarmerRoute212", + STRING_POKEMON + " BDSP", "Money Farmer (Route 212)", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/MoneyFarmerRoute212.md", + "Farm money by using VS Seeker to rebattle the rich couple on Route 212.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + } + ) +{} +struct MoneyFarmerRoute212_Descriptor::Stats : public StatsTracker{ + Stats() + : m_searches(m_stats["Searches"]) + , m_errors(m_stats["Errors"]) + , m_nothing(m_stats["No React"]) + , m_man(m_stats["Man Only"]) + , m_woman(m_stats["Woman Only"]) + , m_both(m_stats["Both"]) + { + m_display_order.emplace_back("Searches"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("No React"); + m_display_order.emplace_back("Man Only"); + m_display_order.emplace_back("Woman Only"); + m_display_order.emplace_back("Both"); + } + std::atomic& m_searches; + std::atomic& m_errors; + std::atomic& m_nothing; + std::atomic& m_man; + std::atomic& m_woman; + std::atomic& m_both; +}; +std::unique_ptr MoneyFarmerRoute212_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +MoneyFarmerRoute212::MoneyFarmerRoute212() + : SHORTCUT("VS Seeker Shortcut:") + , START_LOCATION( + "Start Location:", + { + {StartLocation::Hearthome, "hearthome", "In front of the Hearthome City " + STRING_POKEMON + " center."}, + {StartLocation::OldCouple, "old-couple", "In the row above the rich couple in Route 212."}, + }, + LockMode::LOCK_WHILE_RUNNING, + StartLocation::Hearthome + ) + , HEALING_METHOD( + " Healing method:", + { + {HealMethod::Hearthome, "hearthome", "Hearthome City " + STRING_POKEMON + " center."}, + {HealMethod::GlobalRoom, "global-room", "Use Global Room. (will force update your game)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + HealMethod::Hearthome + ) + , MOVE1_PP("Move 1 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MOVE2_PP("Move 2 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MOVE3_PP("Move 3 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , MOVE4_PP("Move 4 PP:
Set to zero to not use this move.", LockMode::LOCK_WHILE_RUNNING, 5, 0, 64) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(SHORTCUT); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(HEALING_METHOD); + PA_ADD_OPTION(ON_LEARN_MOVE); + PA_ADD_OPTION(MOVE1_PP); + PA_ADD_OPTION(MOVE2_PP); + PA_ADD_OPTION(MOVE3_PP); + PA_ADD_OPTION(MOVE4_PP); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +bool MoneyFarmerRoute212::battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp[4], bool man){ + MoneyFarmerRoute212_Descriptor::Stats& stats = env.current_stats(); + context.wait_for_all_requests(); + if (man){ + env.log("Starting battle with man (left)."); + }else{ + env.log("Starting battle with woman (right)."); + } + env.console.overlay().add_log("Starting battle", COLOR_WHITE); + + pbf_mash_button(context, BUTTON_ZL, 5 * TICKS_PER_SECOND); + + bool battle_menu_seen = false; + + // State Machine + // We need lots of loops in case the party pokemon need to learn lots of moves. + while (true){ + context.wait_for_all_requests(); + + BattleMenuWatcher battle_menu(BattleType::TRAINER); + EndBattleWatcher end_battle; + SelectionArrowFinder learn_move(env.console, {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 30 * TICKS_PER_SECOND); + }, + { + {battle_menu}, + battle_menu_seen ? PeriodicInferenceCallback{end_battle} : PeriodicInferenceCallback{}, + {learn_move}, + } + ); + switch (ret){ + case 0:{ + env.log("Battle menu detected!", COLOR_BLUE); + env.console.overlay().add_log("Choose move", COLOR_BLUE); + battle_menu_seen = true; + + pbf_press_button(context, BUTTON_ZL, 10, 125); + + uint8_t slot = 0; + for (; slot < 4; slot++){ + if (pp[slot] != 0){ + break; + } + } + if (slot == 4){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Ran out of PP in a battle.", + env.console + ); + } + + for (uint8_t move_slot = 0; move_slot < slot; move_slot++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } + pbf_mash_button(context, BUTTON_ZL, 250); + pp[slot]--; + env.log("Used move at slot " + std::to_string(slot+1) + ". " + std::to_string(pp[slot]) + " PP left.", COLOR_BLUE); + + break; + } + case 1: + env.log("Battle finished!", COLOR_BLUE); + env.console.overlay().add_log("Battle finished", COLOR_WHITE); + pbf_mash_button(context, BUTTON_B, 250); + return false; +// case 1: +// env.log("Dialog detected! Battle finished?", COLOR_BLUE); +// pbf_mash_button(context, BUTTON_B, 250); +// return; + case 2: + env.log("Detected move to learn!", COLOR_BLUE); + env.console.overlay().add_log("Detected move to learn", COLOR_WHITE); + if (ON_LEARN_MOVE == OnLearnMove::DONT_LEARN){ + pbf_move_right_joystick(context, 128, 255, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + } + return true; + + default: + stats.m_errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out after 30 seconds.", + env.console + ); + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No progress detected after 5 battle menus. Are you out of PP?", + env.console + ); +} + + +void MoneyFarmerRoute212::heal_at_center_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]){ + stream.overlay().add_log("Heal at " + STRING_POKEMON + " Center", COLOR_WHITE); + stream.log("Healing " + STRING_POKEMON + " at Hearthome City " + STRING_POKEMON + " Center."); + pbf_move_left_joystick(context, 125, 0, 6 * TICKS_PER_SECOND, 0); + pbf_mash_button(context, BUTTON_ZL, 3 * TICKS_PER_SECOND); +// ssf_mash_AZs(context, 3 * TICKS_PER_SECOND); + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + stream.overlay().add_log("Heal complete", COLOR_WHITE); + stream.overlay().add_log("To rich couple", COLOR_WHITE); + stream.log("Returning to rich couple location..."); + pbf_move_left_joystick(context, 128, 255, 8 * TICKS_PER_SECOND, 0); + pbf_move_left_joystick(context, 255, 128, 380, 0); + pbf_move_left_joystick(context, 128, 255, 300, 0); + pbf_move_left_joystick(context, 0, 128, 600, 0); + pbf_move_left_joystick(context, 255, 128, 75, 0); + pbf_move_left_joystick(context, 128, 255, 1375, 0); + pbf_move_left_joystick(context, 255, 128, 125, 0); + pbf_move_left_joystick(context, 128, 255, 200, 0); + pbf_move_left_joystick(context, 0, 128, 200, 0); + pbf_move_left_joystick(context, 128, 255, 50, 0); + pbf_move_left_joystick(context, 0, 128, 125, 0); + pbf_move_left_joystick(context, 128, 255, 125, 0); + pbf_move_left_joystick(context, 255, 128, 250, 0); + pbf_move_left_joystick(context, 128, 255, 200, 0); + pbf_move_left_joystick(context, 0, 128, 90, 0); + pbf_move_left_joystick(context, 128, 255, 200, 0); + pbf_move_left_joystick(context, 255, 128, 125, 0); + pbf_move_left_joystick(context, 128, 255, 200, 0); + + pp[0] = MOVE1_PP; + pp[1] = MOVE2_PP; + pp[2] = MOVE3_PP; + pp[3] = MOVE4_PP; + context.wait_for_all_requests(); +} + + +void MoneyFarmerRoute212::fly_to_center_heal_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]){ + stream.log("Flying back to Hearthome City to heal."); + stream.overlay().add_log("Fly to Hearthome City", COLOR_WHITE); + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_PLUS, 10, 240); + pbf_press_dpad(context, DPAD_UP, 10, 60); + pbf_press_dpad(context, DPAD_UP, 10, 60); + pbf_mash_button(context, BUTTON_ZL, 12 * TICKS_PER_SECOND); + heal_at_center_and_return(stream, context, pp); +} + +bool MoneyFarmerRoute212::heal_after_battle_and_return( + VideoStream& stream, ProControllerContext& context, + uint8_t pp[4]) +{ + if (HEALING_METHOD == HealMethod::Hearthome){ + // Go to Hearhome City Pokecenter to heal the party. + fly_to_center_heal_and_return(stream, context, pp); + return false; + }else{ + // Use Global Room to heal the party. + heal_by_global_room(stream, context); + + pp[0] = MOVE1_PP; + pp[1] = MOVE2_PP; + pp[2] = MOVE3_PP; + pp[3] = MOVE4_PP; + return true; + } +} + +void MoneyFarmerRoute212::charge_vs_seeker(ProControllerContext& context){ + for (size_t c = 0; c < 5; c++){ + pbf_move_left_joystick(context, 0, 128, 180, 0); + pbf_move_left_joystick(context, 255, 128, 180, 0); + } +} + + +size_t MoneyFarmerRoute212::total_pp(uint8_t pp[4]){ + size_t ret = 0; + ret += pp[0]; + ret += pp[1]; + ret += pp[2]; + ret += pp[3]; + return ret; +} + + +void MoneyFarmerRoute212::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MoneyFarmerRoute212_Descriptor::Stats& stats = env.current_stats(); + + uint8_t pp[4] = { + MOVE1_PP, + MOVE2_PP, + MOVE3_PP, + MOVE4_PP, + }; + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + bool need_to_charge = true; + if (START_LOCATION == StartLocation::Hearthome){ + heal_at_center_and_return(env.console, context, pp); + need_to_charge = false; + }else{ // start location is the row above the rich couple + if (HEALING_METHOD == HealMethod::GlobalRoom){ + heal_by_global_room(env.console, context); + } + // Reset position to right most on the row above the rich couple + pbf_move_left_joystick(context, 255, 128, 180, 0); + } + + while (true){ + context.wait_for_all_requests(); + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (need_to_charge){ + env.console.overlay().add_log("Charging Vs. Seeker", COLOR_WHITE); + charge_vs_seeker(context); + } + + // Move to woman. + pbf_move_left_joystick(context, 0, 128, 52, 0); + + context.wait_for_all_requests(); + stats.m_searches++; + + QSize dimensions; + std::vector bubbles; + { + env.console.overlay().add_log("Using Vs. Seeker", COLOR_WHITE); + VSSeekerReactionTracker tracker(env.console, {0.23, 0.30, 0.35, 0.30}); + run_until( + env.console, context, + [this](ProControllerContext& context){ + SHORTCUT.run(context, TICKS_PER_SECOND); + + }, + {{tracker}} + ); + need_to_charge = true; + pbf_mash_button(context, BUTTON_B, 250); + + dimensions = tracker.dimensions(); + bubbles = tracker.reactions(); + if (bubbles.empty()){ + env.log("No reactions.", COLOR_ORANGE); + stats.m_nothing++; + continue; + } + } + + bool man = false; + bool woman = false; + for (const ImagePixelBox& box : bubbles){ + double x_coord = (double)box.min_x / dimensions.width(); + env.log("Reaction at: " + std::to_string(x_coord), COLOR_BLUE); + if (x_coord < 0.5){ + man = true; + } + if (x_coord > 0.5){ + woman = true; + } + } + + if (man && woman){ + env.console.overlay().add_log("Found both", COLOR_GREEN); + stats.m_both++; + }else if (man){ + env.console.overlay().add_log("Found Gentleman", COLOR_GREEN); + stats.m_man++; + }else if (woman){ + env.console.overlay().add_log("Found Madame", COLOR_GREEN); + stats.m_woman++; + } + + env.update_stats(); + + if (woman){ +// pbf_move_left_joystick(context, 0, 128, 52, 0); + pbf_move_left_joystick(context, 128, 255, 10, 0); + + // Battle woman. + if(battle(env, context, pp, false)){ + return; + } + + // Check PP. + if (total_pp(pp) == 0){ + need_to_charge = heal_after_battle_and_return(env.console, context, pp); + continue; + } + } + if (man){ +#if 0 + // Make sure we have enough PP. + if (total_pp(pp) < 2){ + need_to_charge = heal_after_battle_and_return(env.console, pp); + continue; + } +#endif + +// if (woman){ + pbf_move_left_joystick(context, 0, 128, 52, 0); + pbf_move_left_joystick(context, 128, 255, 10, 0); +// }else{ +// pbf_move_left_joystick(context, 0, 128, 105, 0); +// pbf_move_left_joystick(context, 128, 255, 10, 0); +// } + + // Battle man. + if (battle(env, context, pp, true)){ + return; + } + + // Check PP. + if (total_pp(pp) == 0){ + need_to_charge = heal_after_battle_and_return(env.console, context, pp); + continue; + } + } + pbf_move_left_joystick(context, 255, 128, 180, 0); + + } +} + + + + + + + +} +} +} + + + + + + + + + + diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h index 44e4c18093..c4a5fac86b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_MoneyFarmerRoute212.h @@ -1,82 +1,82 @@ -/* Money Farmer (Route 212) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_MoneyFarmerRoute212_H -#define PokemonAutomation_PokemonBDSP_MoneyFarmerRoute212_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" -#include "PokemonBDSP/Options/PokemonBDSP_LearnMove.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class MoneyFarmerRoute212_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MoneyFarmerRoute212_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class MoneyFarmerRoute212 : public SingleSwitchProgramInstance{ -public: - MoneyFarmerRoute212(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - // Run the battle loop. Return true if the program should stop. - bool battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp[4], bool man); - // From the row above the old couple, heal Pokemon and return. - // Return true if VS Seeker needs charging. - bool heal_after_battle_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]); - // Starting in front of the Hearthome Pokecenter, heal and return - // to the old couple. - void heal_at_center_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]); - // Fly from the old couple to Hearthome Pokecenter, heal and return. - void fly_to_center_heal_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]); - // Move around to charge VS Seeker. - void charge_vs_seeker(ProControllerContext& context); - - static size_t total_pp(uint8_t pp[4]); - -private: - enum class StartLocation{ - Hearthome, - OldCouple, - }; - enum class HealMethod{ - Hearthome, - GlobalRoom, - }; - - ShortcutDirectionOption SHORTCUT; - - EnumDropdownOption START_LOCATION; - EnumDropdownOption HEALING_METHOD; - OnLearnMoveOption ON_LEARN_MOVE; - - SimpleIntegerOption MOVE1_PP; - SimpleIntegerOption MOVE2_PP; - SimpleIntegerOption MOVE3_PP; - SimpleIntegerOption MOVE4_PP; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Money Farmer (Route 212) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_MoneyFarmerRoute212_H +#define PokemonAutomation_PokemonBDSP_MoneyFarmerRoute212_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" +#include "PokemonBDSP/Options/PokemonBDSP_LearnMove.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class MoneyFarmerRoute212_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MoneyFarmerRoute212_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class MoneyFarmerRoute212 : public SingleSwitchProgramInstance{ +public: + MoneyFarmerRoute212(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + // Run the battle loop. Return true if the program should stop. + bool battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pp[4], bool man); + // From the row above the old couple, heal Pokemon and return. + // Return true if VS Seeker needs charging. + bool heal_after_battle_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]); + // Starting in front of the Hearthome Pokecenter, heal and return + // to the old couple. + void heal_at_center_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]); + // Fly from the old couple to Hearthome Pokecenter, heal and return. + void fly_to_center_heal_and_return(VideoStream& stream, ProControllerContext& context, uint8_t pp[4]); + // Move around to charge VS Seeker. + void charge_vs_seeker(ProControllerContext& context); + + static size_t total_pp(uint8_t pp[4]); + +private: + enum class StartLocation{ + Hearthome, + OldCouple, + }; + enum class HealMethod{ + Hearthome, + GlobalRoom, + }; + + ShortcutDirectionOption SHORTCUT; + + EnumDropdownOption START_LOCATION; + EnumDropdownOption HEALING_METHOD; + OnLearnMoveOption ON_LEARN_MOVE; + + SimpleIntegerOption MOVE1_PP; + SimpleIntegerOption MOVE2_PP; + SimpleIntegerOption MOVE3_PP; + SimpleIntegerOption MOVE4_PP; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.cpp index 1a542c053f..f36fdfe98e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.cpp @@ -1,211 +1,211 @@ -/* Poffin Cooker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP_PoffinCooker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - -PoffinCooker_Descriptor::PoffinCooker_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:PoffinCooker", - STRING_POKEMON + " BDSP", "Poffin Cooker", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/PoffinCooker.md", - "Cook Poffins.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -struct PoffinCooker_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Poffins cooked"]) - { - m_display_order.emplace_back("Poffins cooked"); - } - std::atomic& m_attempts; -}; -std::unique_ptr PoffinCooker_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -PoffinCooker::PoffinCooker() - : GO_HOME_WHEN_DONE(false) - , MAX_COOK_ATTEMPTS( - "Cook this many times:
This puts a limit on how many poffins you get. Don't forget that each cooking session gets you 4 poffins, and your bag cannot have more than 100 poffins. Thus you should never input more than 25 here.", - LockMode::LOCK_WHILE_RUNNING, - 1, - 1, - 25 - ) - -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(MAX_COOK_ATTEMPTS); -} - -bool turn = true; // True to turn clockwise, false to turn counter-clockwise - -ImageFloatBox box(0.56, 0.724, 0.012, 0.024); // Create a box that contains both green and blue arrows that need to be detected - -void TurnClockwiseSlow(ProControllerContext& context){ // One turn of stirring poffin at slow speed (clockwise) - pbf_move_right_joystick(context, 128, 255, 5, 0); - pbf_move_right_joystick(context, 53, 231, 5, 0); - pbf_move_right_joystick(context, 6, 167, 5, 0); - pbf_move_right_joystick(context, 6, 88, 5, 0); - pbf_move_right_joystick(context, 53, 24, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_move_right_joystick(context, 202, 24, 5, 0); - pbf_move_right_joystick(context, 249, 88, 5, 0); - pbf_move_right_joystick(context, 249, 167, 5, 0); - pbf_move_right_joystick(context, 202, 231, 5, 0); -} - -void TurnClockwiseFast(ProControllerContext& context){ // Same as above, but faster for the end of the cooking session - pbf_move_right_joystick(context, 128, 255, 5, 0); - pbf_move_right_joystick(context, 38, 218, 5, 0); - pbf_move_right_joystick(context, 0, 128, 5, 0); - pbf_move_right_joystick(context, 38, 38, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_move_right_joystick(context, 218, 38, 5, 0); - pbf_move_right_joystick(context, 255, 128, 5, 0); - pbf_move_right_joystick(context, 218, 218, 5, 0); -} - - -void TurnCounterClockwiseSlow(ProControllerContext& context){ // One turn of stirring poffin (counter-clockwise) - pbf_move_right_joystick(context, 128, 255, 5, 0); - pbf_move_right_joystick(context, 202, 231, 5, 0); - pbf_move_right_joystick(context, 249, 167, 5, 0); - pbf_move_right_joystick(context, 249, 88, 5, 0); - pbf_move_right_joystick(context, 202, 24, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_move_right_joystick(context, 53, 24, 5, 0); - pbf_move_right_joystick(context, 6, 88, 5, 0); - pbf_move_right_joystick(context, 6, 167, 5, 0); - pbf_move_right_joystick(context, 53, 231, 5, 0); -} - -void TurnCounterClockwiseFast(ProControllerContext& context){ // Same as above, but faster for the end of the cooking session - pbf_move_right_joystick(context, 128, 255, 5, 0); - pbf_move_right_joystick(context, 218, 218, 5, 0); - pbf_move_right_joystick(context, 255, 128, 5, 0); - pbf_move_right_joystick(context, 218, 38, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_move_right_joystick(context, 38, 38, 5, 0); - pbf_move_right_joystick(context, 0, 128, 5, 0); - pbf_move_right_joystick(context, 38, 218, 5, 0); -} - - -void PoffinCooker::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PoffinCooker_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_move_right_joystick(context, 0, 255, 10, 0); - - env.log("Select the cooking option"); - // Select the cooking option. - pbf_press_button(context, BUTTON_A, 5, 100); - pbf_press_button(context, BUTTON_A, 5, 175); - pbf_press_button(context, BUTTON_A, 5, 75); - pbf_press_button(context, BUTTON_A, 5, 100); - - - for (uint16_t c = 0; c < MAX_COOK_ATTEMPTS; c++){ - - env.log("Select the 4 berries to use"); - // Select the first four berries to cook and confirm the selection. - pbf_press_button(context, BUTTON_A, 5, 50); - pbf_press_dpad(context, DPAD_DOWN, 5, 50); - pbf_press_button(context, BUTTON_A, 5, 50); - pbf_press_dpad(context, DPAD_DOWN, 5, 50); - pbf_press_button(context, BUTTON_A, 5, 50); - pbf_press_dpad(context, DPAD_DOWN, 5, 50); - pbf_press_button(context, BUTTON_A, 5, 50); - pbf_press_button(context, BUTTON_A, 5, 50); - pbf_mash_button(context, BUTTON_A, 150); // Mash here to make sure the final button press isn't dropped - - // Wait a bit less than 10 seconds for the cinematic to happen then cook. - pbf_wait(context, 1050); - context.wait_for_all_requests(); - - env.log("Stir slowly for the first part"); - for (uint16_t d = 0; d < 79; d++){ - // Capture the image on the screen - VideoSnapshot screen = env.console.video().snapshot(); - - // Get the stats of the screen's image - ImageStats IMGstats = image_stats(extract_box_reference(screen, box)); - if (IMGstats.average.g > 170 && IMGstats.average.r < 125) { // Looking for the green arrow - turn = true; - } - if (IMGstats.average.b > 170 && IMGstats.average.r < 125) { // Looking for the blue arrow - turn = false; - } - if (turn){ - TurnClockwiseSlow(context); - }else{ - TurnCounterClockwiseSlow(context); - } - } - - env.log("Stir at full speed now"); - for (uint16_t d = 0; d < 70; d++){ - // Capture the image on the screen - VideoSnapshot screen = env.console.video().snapshot(); - - // Get the stats of the screen's image - ImageStats IMGstats = image_stats(extract_box_reference(screen, box)); - if (IMGstats.average.g > 170 && IMGstats.average.r < 125) { // Looking for the green arrow - turn = true; - } - if (IMGstats.average.b > 170 && IMGstats.average.r < 125) { // Looking for the blue arrow - turn = false; - } - if (turn){ - TurnClockwiseFast(context); - }else{ - TurnCounterClockwiseFast(context); - } - } - - // Final animation when the cooking session is over - pbf_wait(context, 750); - - if (c < MAX_COOK_ATTEMPTS - 1){ - env.log("Prepare for the next iteration"); - pbf_press_button(context, BUTTON_A, 5, 125); - pbf_press_button(context, BUTTON_A, 5, 125); - pbf_press_button(context, BUTTON_A, 5, 125); - } - stats.m_attempts++; - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Poffin Cooker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP_PoffinCooker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + +PoffinCooker_Descriptor::PoffinCooker_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:PoffinCooker", + STRING_POKEMON + " BDSP", "Poffin Cooker", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/PoffinCooker.md", + "Cook Poffins.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +struct PoffinCooker_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Poffins cooked"]) + { + m_display_order.emplace_back("Poffins cooked"); + } + std::atomic& m_attempts; +}; +std::unique_ptr PoffinCooker_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +PoffinCooker::PoffinCooker() + : GO_HOME_WHEN_DONE(false) + , MAX_COOK_ATTEMPTS( + "Cook this many times:
This puts a limit on how many poffins you get. Don't forget that each cooking session gets you 4 poffins, and your bag cannot have more than 100 poffins. Thus you should never input more than 25 here.", + LockMode::LOCK_WHILE_RUNNING, + 1, + 1, + 25 + ) + +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(MAX_COOK_ATTEMPTS); +} + +bool turn = true; // True to turn clockwise, false to turn counter-clockwise + +ImageFloatBox box(0.56, 0.724, 0.012, 0.024); // Create a box that contains both green and blue arrows that need to be detected + +void TurnClockwiseSlow(ProControllerContext& context){ // One turn of stirring poffin at slow speed (clockwise) + pbf_move_right_joystick(context, 128, 255, 5, 0); + pbf_move_right_joystick(context, 53, 231, 5, 0); + pbf_move_right_joystick(context, 6, 167, 5, 0); + pbf_move_right_joystick(context, 6, 88, 5, 0); + pbf_move_right_joystick(context, 53, 24, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_move_right_joystick(context, 202, 24, 5, 0); + pbf_move_right_joystick(context, 249, 88, 5, 0); + pbf_move_right_joystick(context, 249, 167, 5, 0); + pbf_move_right_joystick(context, 202, 231, 5, 0); +} + +void TurnClockwiseFast(ProControllerContext& context){ // Same as above, but faster for the end of the cooking session + pbf_move_right_joystick(context, 128, 255, 5, 0); + pbf_move_right_joystick(context, 38, 218, 5, 0); + pbf_move_right_joystick(context, 0, 128, 5, 0); + pbf_move_right_joystick(context, 38, 38, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_move_right_joystick(context, 218, 38, 5, 0); + pbf_move_right_joystick(context, 255, 128, 5, 0); + pbf_move_right_joystick(context, 218, 218, 5, 0); +} + + +void TurnCounterClockwiseSlow(ProControllerContext& context){ // One turn of stirring poffin (counter-clockwise) + pbf_move_right_joystick(context, 128, 255, 5, 0); + pbf_move_right_joystick(context, 202, 231, 5, 0); + pbf_move_right_joystick(context, 249, 167, 5, 0); + pbf_move_right_joystick(context, 249, 88, 5, 0); + pbf_move_right_joystick(context, 202, 24, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_move_right_joystick(context, 53, 24, 5, 0); + pbf_move_right_joystick(context, 6, 88, 5, 0); + pbf_move_right_joystick(context, 6, 167, 5, 0); + pbf_move_right_joystick(context, 53, 231, 5, 0); +} + +void TurnCounterClockwiseFast(ProControllerContext& context){ // Same as above, but faster for the end of the cooking session + pbf_move_right_joystick(context, 128, 255, 5, 0); + pbf_move_right_joystick(context, 218, 218, 5, 0); + pbf_move_right_joystick(context, 255, 128, 5, 0); + pbf_move_right_joystick(context, 218, 38, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_move_right_joystick(context, 38, 38, 5, 0); + pbf_move_right_joystick(context, 0, 128, 5, 0); + pbf_move_right_joystick(context, 38, 218, 5, 0); +} + + +void PoffinCooker::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PoffinCooker_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_move_right_joystick(context, 0, 255, 10, 0); + + env.log("Select the cooking option"); + // Select the cooking option. + pbf_press_button(context, BUTTON_A, 5, 100); + pbf_press_button(context, BUTTON_A, 5, 175); + pbf_press_button(context, BUTTON_A, 5, 75); + pbf_press_button(context, BUTTON_A, 5, 100); + + + for (uint16_t c = 0; c < MAX_COOK_ATTEMPTS; c++){ + + env.log("Select the 4 berries to use"); + // Select the first four berries to cook and confirm the selection. + pbf_press_button(context, BUTTON_A, 5, 50); + pbf_press_dpad(context, DPAD_DOWN, 5, 50); + pbf_press_button(context, BUTTON_A, 5, 50); + pbf_press_dpad(context, DPAD_DOWN, 5, 50); + pbf_press_button(context, BUTTON_A, 5, 50); + pbf_press_dpad(context, DPAD_DOWN, 5, 50); + pbf_press_button(context, BUTTON_A, 5, 50); + pbf_press_button(context, BUTTON_A, 5, 50); + pbf_mash_button(context, BUTTON_A, 150); // Mash here to make sure the final button press isn't dropped + + // Wait a bit less than 10 seconds for the cinematic to happen then cook. + pbf_wait(context, 1050); + context.wait_for_all_requests(); + + env.log("Stir slowly for the first part"); + for (uint16_t d = 0; d < 79; d++){ + // Capture the image on the screen + VideoSnapshot screen = env.console.video().snapshot(); + + // Get the stats of the screen's image + ImageStats IMGstats = image_stats(extract_box_reference(screen, box)); + if (IMGstats.average.g > 170 && IMGstats.average.r < 125) { // Looking for the green arrow + turn = true; + } + if (IMGstats.average.b > 170 && IMGstats.average.r < 125) { // Looking for the blue arrow + turn = false; + } + if (turn){ + TurnClockwiseSlow(context); + }else{ + TurnCounterClockwiseSlow(context); + } + } + + env.log("Stir at full speed now"); + for (uint16_t d = 0; d < 70; d++){ + // Capture the image on the screen + VideoSnapshot screen = env.console.video().snapshot(); + + // Get the stats of the screen's image + ImageStats IMGstats = image_stats(extract_box_reference(screen, box)); + if (IMGstats.average.g > 170 && IMGstats.average.r < 125) { // Looking for the green arrow + turn = true; + } + if (IMGstats.average.b > 170 && IMGstats.average.r < 125) { // Looking for the blue arrow + turn = false; + } + if (turn){ + TurnClockwiseFast(context); + }else{ + TurnCounterClockwiseFast(context); + } + } + + // Final animation when the cooking session is over + pbf_wait(context, 750); + + if (c < MAX_COOK_ATTEMPTS - 1){ + env.log("Prepare for the next iteration"); + pbf_press_button(context, BUTTON_A, 5, 125); + pbf_press_button(context, BUTTON_A, 5, 125); + pbf_press_button(context, BUTTON_A, 5, 125); + } + stats.m_attempts++; + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.h b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.h index ee2d4197e7..c94c58de60 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Farming/PokemonBDSP_PoffinCooker.h @@ -1,45 +1,45 @@ -/* Poffin Cooker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_PoffinCooker_H -#define PokemonAutomation_PokemonBDSP_PoffinCooker_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class PoffinCooker_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PoffinCooker_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class PoffinCooker : public SingleSwitchProgramInstance{ -public: - PoffinCooker(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption MAX_COOK_ATTEMPTS; - -}; - - - - -} -} -} -#endif +/* Poffin Cooker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_PoffinCooker_H +#define PokemonAutomation_PokemonBDSP_PoffinCooker_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class PoffinCooker_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PoffinCooker_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class PoffinCooker : public SingleSwitchProgramInstance{ +public: + PoffinCooker(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption MAX_COOK_ATTEMPTS; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.cpp index 7eb814d10b..d7ccf6a4bb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.cpp @@ -1,190 +1,190 @@ -/* Autonomous Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_AutonomousBallThrower.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSPh:AutonomousBallThrower", - STRING_POKEMON + " BDSP", "Autonomous Ball Thrower", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/AutonomousBallThrower.md", - "Repeatedly throw a ball and reset until you catch the pokemon.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ - Stats() - : pokemon_caught(m_stats["Pokemon caught"]) - , pokemon_fainted(m_stats["Pokemon fainted"]) - , own_fainted(m_stats["Own fainted"]) - , out_of_balls(m_stats["Out of balls"]) - , errors(m_stats["Errors"]) - , total_balls_thrown(m_stats["Total balls thrown"]) - { - m_display_order.emplace_back(Stat("Pokemon caught")); - m_display_order.emplace_back(Stat("Pokemon fainted")); - m_display_order.emplace_back(Stat("Own fainted")); - m_display_order.emplace_back(Stat("Out of balls")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Total balls thrown")); - } - - std::atomic& pokemon_caught; - std::atomic& pokemon_fainted; - std::atomic& own_fainted; - std::atomic& out_of_balls; - std::atomic& errors; - std::atomic& total_balls_thrown; -}; -std::unique_ptr AutonomousBallThrower_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -AutonomousBallThrower::AutonomousBallThrower() - : GO_HOME_WHEN_DONE(false) - , BALL_SELECT( - "Ball Select:", - LockMode::LOCK_WHILE_RUNNING, - "master-ball" - ) - , LANGUAGE( - "Game Language:", - { - Language::English, - Language::Japanese, - Language::Spanish, - Language::French, - Language::German, - Language::Italian, - Language::Korean, - Language::ChineseSimplified, - Language::ChineseTraditional, - }, - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_CATCH_SUCCESS, - &NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void AutonomousBallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AutonomousBallThrower_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - bool pokemon_caught = false; - while (!pokemon_caught){ - context.wait_for_all_requests(); - env.log("Wait for a pokemon to attack you.", COLOR_PURPLE); - { - BattleMenuWatcher fight_detector(BattleType::STANDARD); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - //TODO edit here for what to do - //pbf_wait(context, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 5, TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_UP, 5, TICKS_PER_SECOND); - } - }, - {{fight_detector}} - ); - if (ret == 0){ - env.log("New fight detected.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); - } - } - - CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); - switch (result.result){ - case CatchResult::POKEMON_CAUGHT: - pokemon_caught = true; - stats.pokemon_caught++; - break; - case CatchResult::POKEMON_FAINTED: - stats.pokemon_fainted++; - break; - case CatchResult::OWN_FAINTED: - stats.own_fainted++; - break; - case CatchResult::OUT_OF_BALLS: - stats.out_of_balls++; - break; - case CatchResult::BALL_LIMIT_REACHED: - case CatchResult::CANNOT_THROW_BALL: - case CatchResult::TIMED_OUT: - stats.errors++; - break; - } - stats.total_balls_thrown += result.balls_used; - env.update_stats(); - - if (pokemon_caught){ - send_program_status_notification( - env, NOTIFICATION_CATCH_SUCCESS, - "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." - ); - }else{ - send_program_status_notification( - env, NOTIFICATION_CATCH_FAILED, - "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." - ); - } - - if (!pokemon_caught){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, true); - } - } - - env.log("Result Found!", COLOR_BLUE); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Caught the " + STRING_POKEMON - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} +/* Autonomous Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_AutonomousBallThrower.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSPh:AutonomousBallThrower", + STRING_POKEMON + " BDSP", "Autonomous Ball Thrower", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/AutonomousBallThrower.md", + "Repeatedly throw a ball and reset until you catch the pokemon.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ + Stats() + : pokemon_caught(m_stats["Pokemon caught"]) + , pokemon_fainted(m_stats["Pokemon fainted"]) + , own_fainted(m_stats["Own fainted"]) + , out_of_balls(m_stats["Out of balls"]) + , errors(m_stats["Errors"]) + , total_balls_thrown(m_stats["Total balls thrown"]) + { + m_display_order.emplace_back(Stat("Pokemon caught")); + m_display_order.emplace_back(Stat("Pokemon fainted")); + m_display_order.emplace_back(Stat("Own fainted")); + m_display_order.emplace_back(Stat("Out of balls")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Total balls thrown")); + } + + std::atomic& pokemon_caught; + std::atomic& pokemon_fainted; + std::atomic& own_fainted; + std::atomic& out_of_balls; + std::atomic& errors; + std::atomic& total_balls_thrown; +}; +std::unique_ptr AutonomousBallThrower_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +AutonomousBallThrower::AutonomousBallThrower() + : GO_HOME_WHEN_DONE(false) + , BALL_SELECT( + "Ball Select:", + LockMode::LOCK_WHILE_RUNNING, + "master-ball" + ) + , LANGUAGE( + "Game Language:", + { + Language::English, + Language::Japanese, + Language::Spanish, + Language::French, + Language::German, + Language::Italian, + Language::Korean, + Language::ChineseSimplified, + Language::ChineseTraditional, + }, + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_CATCH_SUCCESS, + &NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void AutonomousBallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AutonomousBallThrower_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + bool pokemon_caught = false; + while (!pokemon_caught){ + context.wait_for_all_requests(); + env.log("Wait for a pokemon to attack you.", COLOR_PURPLE); + { + BattleMenuWatcher fight_detector(BattleType::STANDARD); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + //TODO edit here for what to do + //pbf_wait(context, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 5, TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_UP, 5, TICKS_PER_SECOND); + } + }, + {{fight_detector}} + ); + if (ret == 0){ + env.log("New fight detected.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); + } + } + + CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); + switch (result.result){ + case CatchResult::POKEMON_CAUGHT: + pokemon_caught = true; + stats.pokemon_caught++; + break; + case CatchResult::POKEMON_FAINTED: + stats.pokemon_fainted++; + break; + case CatchResult::OWN_FAINTED: + stats.own_fainted++; + break; + case CatchResult::OUT_OF_BALLS: + stats.out_of_balls++; + break; + case CatchResult::BALL_LIMIT_REACHED: + case CatchResult::CANNOT_THROW_BALL: + case CatchResult::TIMED_OUT: + stats.errors++; + break; + } + stats.total_balls_thrown += result.balls_used; + env.update_stats(); + + if (pokemon_caught){ + send_program_status_notification( + env, NOTIFICATION_CATCH_SUCCESS, + "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." + ); + }else{ + send_program_status_notification( + env, NOTIFICATION_CATCH_FAILED, + "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." + ); + } + + if (!pokemon_caught){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, true); + } + } + + env.log("Result Found!", COLOR_BLUE); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Caught the " + STRING_POKEMON + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.h b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.h index c42c2a4f1b..e48854b23a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_AutonomousBallThrower.h @@ -1,51 +1,51 @@ -/* Autonomous Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_AutonomousBallThrower_H -#define PokemonAutomation_PokemonBDSP_AutonomousBallThrower_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class AutonomousBallThrower_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutonomousBallThrower_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class AutonomousBallThrower : public SingleSwitchProgramInstance{ -public: - AutonomousBallThrower(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - OCR::LanguageOCROption LANGUAGE; - - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Autonomous Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_AutonomousBallThrower_H +#define PokemonAutomation_PokemonBDSP_AutonomousBallThrower_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class AutonomousBallThrower_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutonomousBallThrower_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class AutonomousBallThrower : public SingleSwitchProgramInstance{ +public: + AutonomousBallThrower(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + OCR::LanguageOCROption LANGUAGE; + + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.cpp index 3ed28f8a79..c9f2ab0e46 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.cpp @@ -1,109 +1,109 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h" -#include "PokemonBDSP_MassRelease.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - -MassRelease_Descriptor::MassRelease_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:MassRelease", - STRING_POKEMON + " BDSP", "Mass Release", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/MassRelease.md", - "Mass release boxes of " + STRING_POKEMON + ".", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct MassRelease_Descriptor::Stats : public StatsTracker{ - Stats() - : m_boxes_released(m_stats["Boxes Released"]) - { - m_display_order.emplace_back("Boxes Released"); - } - std::atomic& m_boxes_released; -}; -std::unique_ptr MassRelease_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -MassRelease::MassRelease() - : GO_HOME_WHEN_DONE(false) - , BOXES_TO_RELEASE( - "Number of Boxes to Release:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 40 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(BOXES_TO_RELEASE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - - - - -void MassRelease::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MassRelease_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - Milliseconds box_scroll_delay = GameSettings::instance().BOX_SCROLL_DELAY0; - Milliseconds box_change_delay = GameSettings::instance().BOX_CHANGE_DELAY0; - - if (BOXES_TO_RELEASE > 0){ - env.update_stats(); - release_box(context, box_scroll_delay); - stats.m_boxes_released++; - for (uint8_t box = 1; box < BOXES_TO_RELEASE; box++){ - env.update_stats(); - pbf_press_dpad(context, DPAD_DOWN, 160ms, box_scroll_delay); - pbf_press_dpad(context, DPAD_DOWN, 160ms, box_scroll_delay); - pbf_press_dpad(context, DPAD_DOWN, 160ms, box_scroll_delay); - pbf_press_dpad(context, DPAD_RIGHT, 160ms, box_scroll_delay); - pbf_press_dpad(context, DPAD_RIGHT, 160ms, box_scroll_delay); - pbf_wait(context, 50); - pbf_press_button(context, BUTTON_R, 160ms, box_change_delay); - release_box(context, box_scroll_delay); - stats.m_boxes_released++; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h" +#include "PokemonBDSP_MassRelease.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + +MassRelease_Descriptor::MassRelease_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:MassRelease", + STRING_POKEMON + " BDSP", "Mass Release", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/MassRelease.md", + "Mass release boxes of " + STRING_POKEMON + ".", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct MassRelease_Descriptor::Stats : public StatsTracker{ + Stats() + : m_boxes_released(m_stats["Boxes Released"]) + { + m_display_order.emplace_back("Boxes Released"); + } + std::atomic& m_boxes_released; +}; +std::unique_ptr MassRelease_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +MassRelease::MassRelease() + : GO_HOME_WHEN_DONE(false) + , BOXES_TO_RELEASE( + "Number of Boxes to Release:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 40 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(BOXES_TO_RELEASE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + + + + +void MassRelease::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MassRelease_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + Milliseconds box_scroll_delay = GameSettings::instance().BOX_SCROLL_DELAY0; + Milliseconds box_change_delay = GameSettings::instance().BOX_CHANGE_DELAY0; + + if (BOXES_TO_RELEASE > 0){ + env.update_stats(); + release_box(context, box_scroll_delay); + stats.m_boxes_released++; + for (uint8_t box = 1; box < BOXES_TO_RELEASE; box++){ + env.update_stats(); + pbf_press_dpad(context, DPAD_DOWN, 160ms, box_scroll_delay); + pbf_press_dpad(context, DPAD_DOWN, 160ms, box_scroll_delay); + pbf_press_dpad(context, DPAD_DOWN, 160ms, box_scroll_delay); + pbf_press_dpad(context, DPAD_RIGHT, 160ms, box_scroll_delay); + pbf_press_dpad(context, DPAD_RIGHT, 160ms, box_scroll_delay); + pbf_wait(context, 50); + pbf_press_button(context, BUTTON_R, 160ms, box_change_delay); + release_box(context, box_scroll_delay); + stats.m_boxes_released++; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.h b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.h index aaf3369c71..c370c2b505 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/General/PokemonBDSP_MassRelease.h @@ -1,45 +1,45 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_MassRelease_H -#define PokemonAutomation_PokemonBDSP_MassRelease_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class MassRelease_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MassRelease_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class MassRelease : public SingleSwitchProgramInstance{ -public: - MassRelease(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption BOXES_TO_RELEASE; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_MassRelease_H +#define PokemonAutomation_PokemonBDSP_MassRelease_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class MassRelease_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MassRelease_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class MassRelease : public SingleSwitchProgramInstance{ +public: + MassRelease(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption BOXES_TO_RELEASE; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.cpp index 201696a874..fe74d54685 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.cpp @@ -1,186 +1,186 @@ -/* Activate Menu Glitch (1.1.2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_MapDetector.h" -#include "PokemonBDSP_ActivateMenuGlitch-1.1.2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -ActivateMenuGlitch112_Descriptor::ActivateMenuGlitch112_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:ActivateMenuGlitch112", - STRING_POKEMON + " BDSP", "Activate Menu Glitch (1.1.2)", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ActivateMenuGlitch-Poketch.md", - "Activate the menu glitch using the Pok\u00e9tch. " - "(This requires game versions 1.1.0 - 1.1.2. The glitch it relies on was patched in v1.1.3.)", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - }, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -ActivateMenuGlitch112::ActivateMenuGlitch112() - : FLY_A_TO_X_DELAY0( - "Fly Menu A-to-X Delay:
The delay between the A and X presses to overlap the menu with the fly option.
" - "(German players may need to increase this to 90.)", - LockMode::LOCK_WHILE_RUNNING, - 160ms, "400 ms" - ) -{ - PA_ADD_OPTION(FLY_A_TO_X_DELAY0); -} - - - -void trigger_menu(VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - MapWatcher detector; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t i = 0; i < 12; i++){ - for (size_t c = 0; c < 42; c++){ - pbf_controller_state(context, BUTTON_ZL, DPAD_NONE, 128, 128, 128, 128, 1); - pbf_controller_state(context, BUTTON_R | BUTTON_ZL, DPAD_NONE, 128, 128, 128, 128, 5); - pbf_wait(context, 3); - } - pbf_wait(context, 125); - pbf_press_button(context, BUTTON_R, 20, 105); - } - }, - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after 60 seconds.", - stream - ); - } - stream.log("Detected map!", COLOR_BLUE); - - context.wait_for(std::chrono::milliseconds(500)); - ShortDialogDetector dialog; - while (dialog.detect(stream.video().snapshot())){ - stream.log("Overshot mashing. Backing out.", COLOR_ORANGE); - pbf_press_button(context, BUTTON_B, 20, 105); - context.wait_for_all_requests(); - } -} -void trigger_map_overlap(VideoStream& stream, ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - trigger_menu(stream, context); - - pbf_press_dpad(context, DPAD_UP, 50, 0); - context.wait_for_all_requests(); - BlackScreenWatcher detector; - int ret = wait_until( - stream, context, std::chrono::seconds(4), - {{detector}} - ); - if (ret >= 0){ - stream.log("Overlap detected! Entered " + STRING_POKEMON + " center.", COLOR_BLUE); - return; - } - stream.log("Failed to activate map overlap.", COLOR_ORANGE); - pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_R, 20, 230); - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to trigger map overlap after 10 attempts.", - stream - ); -} - - - -void ActivateMenuGlitch112::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - VideoStream& stream = env.console; - - trigger_map_overlap(stream, context); - pbf_wait(context, 3 * TICKS_PER_SECOND); - - // Move to escalator. - pbf_press_dpad(context, DPAD_UP, 20, 125); - pbf_press_dpad(context, DPAD_UP, 20, 125); - pbf_move_left_joystick(context, 255, 128, 250, 5 * TICKS_PER_SECOND); - - // Re-enter escalator. - pbf_press_dpad(context, DPAD_RIGHT, 125, 6 * TICKS_PER_SECOND); - - // Leave Pokemon center. - pbf_press_dpad(context, DPAD_LEFT, 20, 105); - pbf_press_dpad(context, DPAD_LEFT, 20, 105); - pbf_press_dpad(context, DPAD_LEFT, 20, 105); - { - context.wait_for_all_requests(); - BlackScreenWatcher detector; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 5; c++){ - pbf_press_dpad(context, DPAD_LEFT, 20, 105); - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - } - }, - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to leave " + STRING_POKEMON + " center.", - stream - ); - } - stream.log("Leaving " + STRING_POKEMON + " center detected!", COLOR_BLUE); - } - pbf_move_left_joystick(context, 128, 255, 125, 4 * TICKS_PER_SECOND); - - // Center cursor. - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0); - - // Bring up menu - pbf_press_button(context, BUTTON_ZL, 160ms, FLY_A_TO_X_DELAY0.get() - 160ms); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - - // Fly - pbf_press_button(context, BUTTON_ZL, 20, 10 * TICKS_PER_SECOND); - - // Enter Pokemon center. - pbf_press_dpad(context, DPAD_UP, 50, 5 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 255, 128, 125, 0); - pbf_move_left_joystick(context, 128, 255, 125, 125); - - // Move cursor back to default location for "Pokemon". - pbf_move_right_joystick(context, 128, 0, 20, 20); - pbf_move_right_joystick(context, 0, 128, 20, 20); - pbf_move_right_joystick(context, 0, 128, 20, 20); -} - - - -} -} -} +/* Activate Menu Glitch (1.1.2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MapDetector.h" +#include "PokemonBDSP_ActivateMenuGlitch-1.1.2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +ActivateMenuGlitch112_Descriptor::ActivateMenuGlitch112_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:ActivateMenuGlitch112", + STRING_POKEMON + " BDSP", "Activate Menu Glitch (1.1.2)", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ActivateMenuGlitch-Poketch.md", + "Activate the menu glitch using the Pok\u00e9tch. " + "(This requires game versions 1.1.0 - 1.1.2. The glitch it relies on was patched in v1.1.3.)", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + }, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +ActivateMenuGlitch112::ActivateMenuGlitch112() + : FLY_A_TO_X_DELAY0( + "Fly Menu A-to-X Delay:
The delay between the A and X presses to overlap the menu with the fly option.
" + "(German players may need to increase this to 90.)", + LockMode::LOCK_WHILE_RUNNING, + 160ms, "400 ms" + ) +{ + PA_ADD_OPTION(FLY_A_TO_X_DELAY0); +} + + + +void trigger_menu(VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + MapWatcher detector; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t i = 0; i < 12; i++){ + for (size_t c = 0; c < 42; c++){ + pbf_controller_state(context, BUTTON_ZL, DPAD_NONE, 128, 128, 128, 128, 1); + pbf_controller_state(context, BUTTON_R | BUTTON_ZL, DPAD_NONE, 128, 128, 128, 128, 5); + pbf_wait(context, 3); + } + pbf_wait(context, 125); + pbf_press_button(context, BUTTON_R, 20, 105); + } + }, + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after 60 seconds.", + stream + ); + } + stream.log("Detected map!", COLOR_BLUE); + + context.wait_for(std::chrono::milliseconds(500)); + ShortDialogDetector dialog; + while (dialog.detect(stream.video().snapshot())){ + stream.log("Overshot mashing. Backing out.", COLOR_ORANGE); + pbf_press_button(context, BUTTON_B, 20, 105); + context.wait_for_all_requests(); + } +} +void trigger_map_overlap(VideoStream& stream, ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + trigger_menu(stream, context); + + pbf_press_dpad(context, DPAD_UP, 50, 0); + context.wait_for_all_requests(); + BlackScreenWatcher detector; + int ret = wait_until( + stream, context, std::chrono::seconds(4), + {{detector}} + ); + if (ret >= 0){ + stream.log("Overlap detected! Entered " + STRING_POKEMON + " center.", COLOR_BLUE); + return; + } + stream.log("Failed to activate map overlap.", COLOR_ORANGE); + pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_R, 20, 230); + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to trigger map overlap after 10 attempts.", + stream + ); +} + + + +void ActivateMenuGlitch112::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + VideoStream& stream = env.console; + + trigger_map_overlap(stream, context); + pbf_wait(context, 3 * TICKS_PER_SECOND); + + // Move to escalator. + pbf_press_dpad(context, DPAD_UP, 20, 125); + pbf_press_dpad(context, DPAD_UP, 20, 125); + pbf_move_left_joystick(context, 255, 128, 250, 5 * TICKS_PER_SECOND); + + // Re-enter escalator. + pbf_press_dpad(context, DPAD_RIGHT, 125, 6 * TICKS_PER_SECOND); + + // Leave Pokemon center. + pbf_press_dpad(context, DPAD_LEFT, 20, 105); + pbf_press_dpad(context, DPAD_LEFT, 20, 105); + pbf_press_dpad(context, DPAD_LEFT, 20, 105); + { + context.wait_for_all_requests(); + BlackScreenWatcher detector; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 5; c++){ + pbf_press_dpad(context, DPAD_LEFT, 20, 105); + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + } + }, + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to leave " + STRING_POKEMON + " center.", + stream + ); + } + stream.log("Leaving " + STRING_POKEMON + " center detected!", COLOR_BLUE); + } + pbf_move_left_joystick(context, 128, 255, 125, 4 * TICKS_PER_SECOND); + + // Center cursor. + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0); + + // Bring up menu + pbf_press_button(context, BUTTON_ZL, 160ms, FLY_A_TO_X_DELAY0.get() - 160ms); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + + // Fly + pbf_press_button(context, BUTTON_ZL, 20, 10 * TICKS_PER_SECOND); + + // Enter Pokemon center. + pbf_press_dpad(context, DPAD_UP, 50, 5 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 255, 128, 125, 0); + pbf_move_left_joystick(context, 128, 255, 125, 125); + + // Move cursor back to default location for "Pokemon". + pbf_move_right_joystick(context, 128, 0, 20, 20); + pbf_move_right_joystick(context, 0, 128, 20, 20); + pbf_move_right_joystick(context, 0, 128, 20, 20); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h index e0f8662d9b..59fb21f6be 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.2.h @@ -1,40 +1,40 @@ -/* Activate Menu Glitch (Poketch) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ActivateMenuGlitchPoketch_H -#define PokemonAutomation_PokemonBDSP_ActivateMenuGlitchPoketch_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class ActivateMenuGlitch112_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ActivateMenuGlitch112_Descriptor(); -}; - - - -class ActivateMenuGlitch112 : public SingleSwitchProgramInstance{ -public: - ActivateMenuGlitch112(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - MillisecondsOption FLY_A_TO_X_DELAY0; -}; - - - -} -} -} -#endif +/* Activate Menu Glitch (Poketch) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ActivateMenuGlitchPoketch_H +#define PokemonAutomation_PokemonBDSP_ActivateMenuGlitchPoketch_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class ActivateMenuGlitch112_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ActivateMenuGlitch112_Descriptor(); +}; + + + +class ActivateMenuGlitch112 : public SingleSwitchProgramInstance{ +public: + ActivateMenuGlitch112(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + MillisecondsOption FLY_A_TO_X_DELAY0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.cpp index 370b44f42d..cde376c7bb 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.cpp @@ -1,97 +1,97 @@ -/* Activate Menu Glitch (1.1.3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_MapDetector.h" -#include "PokemonBDSP_ActivateMenuGlitch-1.1.3.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - - -ActivateMenuGlitch113_Descriptor::ActivateMenuGlitch113_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:ActivateMenuGlitch113", - STRING_POKEMON + " BDSP", "Activate Menu Glitch (1.1.3)", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ActivateMenuGlitch-113.md", - "Activate the menu glitch using the strength/fly method. " - "(This works on game versions 1.1.1 - 1.1.3. It has been patched out in later versions.)", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - }, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -ActivateMenuGlitch113::ActivateMenuGlitch113() - : FLY_A_TO_X_DELAY0( - "Fly Menu A-to-X Delay:
The delay between the A and X presses to overlap the menu with the fly option.
" - "(German players may need to increase this to 90.)", - LockMode::LOCK_WHILE_RUNNING, - 160ms, "400 ms" - ) -{ - PA_ADD_OPTION(FLY_A_TO_X_DELAY0); -} - - - -void ActivateMenuGlitch113::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - VideoStream& stream = env.console; - - // Enable Strength - pbf_mash_button(context, BUTTON_ZL, 2 * TICKS_PER_SECOND); - pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); - - - pbf_press_button(context, BUTTON_R, 5, 0); - pbf_press_dpad(context, DPAD_RIGHT, 10, 115); - pbf_press_button(context, BUTTON_ZL, 10, 0); - context.wait_for_all_requests(); - MapWatcher detector; - int ret = wait_until( - stream, context, std::chrono::seconds(2), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after 2 seconds.", - stream - ); - }else{ - stream.log("Detected map!", COLOR_BLUE); - } - - context.wait_for(std::chrono::seconds(1)); - - // Move bolder and cursor to Celestial town. - pbf_press_dpad(context, DPAD_RIGHT, 30, 95); - - // Bring up menu - pbf_press_button(context, BUTTON_ZL, 160ms, FLY_A_TO_X_DELAY0.get() - 160ms); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - - // Fly - pbf_press_button(context, BUTTON_ZL, 20, 10 * TICKS_PER_SECOND); -} - - -} -} -} +/* Activate Menu Glitch (1.1.3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MapDetector.h" +#include "PokemonBDSP_ActivateMenuGlitch-1.1.3.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + + +ActivateMenuGlitch113_Descriptor::ActivateMenuGlitch113_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:ActivateMenuGlitch113", + STRING_POKEMON + " BDSP", "Activate Menu Glitch (1.1.3)", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ActivateMenuGlitch-113.md", + "Activate the menu glitch using the strength/fly method. " + "(This works on game versions 1.1.1 - 1.1.3. It has been patched out in later versions.)", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + }, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +ActivateMenuGlitch113::ActivateMenuGlitch113() + : FLY_A_TO_X_DELAY0( + "Fly Menu A-to-X Delay:
The delay between the A and X presses to overlap the menu with the fly option.
" + "(German players may need to increase this to 90.)", + LockMode::LOCK_WHILE_RUNNING, + 160ms, "400 ms" + ) +{ + PA_ADD_OPTION(FLY_A_TO_X_DELAY0); +} + + + +void ActivateMenuGlitch113::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + VideoStream& stream = env.console; + + // Enable Strength + pbf_mash_button(context, BUTTON_ZL, 2 * TICKS_PER_SECOND); + pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); + + + pbf_press_button(context, BUTTON_R, 5, 0); + pbf_press_dpad(context, DPAD_RIGHT, 10, 115); + pbf_press_button(context, BUTTON_ZL, 10, 0); + context.wait_for_all_requests(); + MapWatcher detector; + int ret = wait_until( + stream, context, std::chrono::seconds(2), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after 2 seconds.", + stream + ); + }else{ + stream.log("Detected map!", COLOR_BLUE); + } + + context.wait_for(std::chrono::seconds(1)); + + // Move bolder and cursor to Celestial town. + pbf_press_dpad(context, DPAD_RIGHT, 30, 95); + + // Bring up menu + pbf_press_button(context, BUTTON_ZL, 160ms, FLY_A_TO_X_DELAY0.get() - 160ms); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + + // Fly + pbf_press_button(context, BUTTON_ZL, 20, 10 * TICKS_PER_SECOND); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h index d852cb8d3a..21dd3fa658 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_ActivateMenuGlitch-1.1.3.h @@ -1,40 +1,40 @@ -/* Activate Menu Glitch (1.1.3) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ActivateMenuGlitch113_H -#define PokemonAutomation_PokemonBDSP_ActivateMenuGlitch113_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class ActivateMenuGlitch113_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ActivateMenuGlitch113_Descriptor(); -}; - - - -class ActivateMenuGlitch113 : public SingleSwitchProgramInstance{ -public: - ActivateMenuGlitch113(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - MillisecondsOption FLY_A_TO_X_DELAY0; -}; - - - -} -} -} -#endif +/* Activate Menu Glitch (1.1.3) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ActivateMenuGlitch113_H +#define PokemonAutomation_PokemonBDSP_ActivateMenuGlitch113_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class ActivateMenuGlitch113_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ActivateMenuGlitch113_Descriptor(); +}; + + + +class ActivateMenuGlitch113 : public SingleSwitchProgramInstance{ +public: + ActivateMenuGlitch113(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + MillisecondsOption FLY_A_TO_X_DELAY0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.cpp index 4822b3cf52..6acc275242 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.cpp @@ -1,204 +1,204 @@ -/* Clone Items (Box Swap Method 2) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_CloneItemsBoxCopy2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - -CloneItemsBoxCopy2_Descriptor::CloneItemsBoxCopy2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:CloneItemsBoxCopy2", - STRING_POKEMON + " BDSP", "Clone Items (Box Copy 2)", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/CloneItemsBoxCopy2.md", - "With the menu glitch active, clone entire boxes of items at a time. " - "(The menu glitch can only be activated on version 1.1.0 - 1.1.3.)", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - }, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct CloneItemsBoxCopy2_Descriptor::Stats : public StatsTracker{ - Stats() - : m_boxes(m_stats["Boxes Cloned"]) - , m_errors(m_stats["Errors"]) -// , m_resets(m_stats["Resets"]) - { - m_display_order.emplace_back("Boxes Cloned"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); -// m_display_order.emplace_back("Resets"); - } - std::atomic& m_boxes; - std::atomic& m_errors; -// std::atomic& m_resets; -}; -std::unique_ptr CloneItemsBoxCopy2_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -CloneItemsBoxCopy2::CloneItemsBoxCopy2() - : GO_HOME_WHEN_DONE(false) - , BOXES( - "Boxes to Clone:", - LockMode::LOCK_WHILE_RUNNING, - 999, 0, 999 - ) - , RELEASE( - "Release the pokemon after cloning them:" - "Beware, if set to false, the pokemons will be stored in the subsequent boxes. Make sure you have enough empty boxes.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(BOXES); - PA_ADD_OPTION(RELEASE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void CloneItemsBoxCopy2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - CloneItemsBoxCopy2_Descriptor::Stats& stats = env.current_stats(); - -// uint16_t MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY; -// uint16_t POKEMON_TO_BOX_DELAY = GameSettings::instance().POKEMON_TO_BOX_DELAY0; -// uint16_t OVERWORLD_TO_MENU_DELAY = GameSettings::instance().OVERWORLD_TO_MENU_DELAY; -// uint16_t MENU_TO_OVERWORLD_DELAY = GameSettings::instance().MENU_TO_OVERWORLD_DELAY; - Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; - Milliseconds BOX_CHANGE_DELAY = GameSettings::instance().BOX_CHANGE_DELAY0; -// uint16_t BOX_TO_POKEMON_DELAY = GameSettings::instance().BOX_TO_POKEMON_DELAY; -// uint16_t POKEMON_TO_MENU_DELAY = GameSettings::instance().POKEMON_TO_MENU_DELAY; - - // Connect the controller. - pbf_mash_button(context, BUTTON_RCLICK, 50); - - // Enter box system. - menu_to_box(context); - - context.wait_for_all_requests(); - VideoSnapshot expected = env.console.video().snapshot(); - ImageMatchWatcher matcher(std::move(expected.frame), {0.02, 0.25, 0.96, 0.73}, 20); - - for (uint16_t box = 0; box < BOXES; box++){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // Select 1st mon. - pbf_press_button(context, BUTTON_ZL, 20, 50); - - // Enter box system again. - overworld_to_box(context); - -#if 0 - // Detach all items. - pbf_press_button(context, BUTTON_X, 20, 50); - detach_box(context, BOX_SCROLL_DELAY); - - // Back to previous menu. - box_to_overworld(context); - - // View Summary - pbf_move_right_joystick(context, 128, 255, 20, 10); - pbf_press_button(context, BUTTON_ZL, 20, 250); - - // Back out. - pbf_press_button(context, BUTTON_B, 20, 230); - -#else - // Move entire box to a new box. - pbf_press_button(context, BUTTON_Y, 20, 50); - pbf_press_button(context, BUTTON_Y, 20, 50); - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - for (size_t c = 0; c < 10; c++){ - pbf_move_right_joystick(context, 255, 128, 5, 3); - pbf_move_right_joystick(context, 128, 255, 5, 3); - } - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - int box_offset = RELEASE ? 1 : 1 + box; - for (int i = 0; i < box_offset; ++i){ - pbf_press_button(context, BUTTON_R, 160ms, BOX_CHANGE_DELAY); - } - pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); - - // Back to previous menu. - box_to_overworld(context); - - // View Summary - pbf_move_right_joystick(context, 128, 255, 20, 10); - pbf_press_button(context, BUTTON_ZL, 20, 250); - - // Back out. - pbf_press_button(context, BUTTON_B, 20, 230); - - if (RELEASE){ - // Release the cloned box. - pbf_press_button(context, BUTTON_R, 160ms, BOX_CHANGE_DELAY); - release_box(context, BOX_SCROLL_DELAY); - pbf_press_button(context, BUTTON_L, 160ms, BOX_CHANGE_DELAY); - - // Move cursor back to starting position. - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); - pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); - } -#endif - - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(500)); - if (!matcher.detect(env.console.video().snapshot())){ - stats.m_errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to return to starting position. Something is wrong.", - env.console - ); - } - - stats.m_boxes++; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - - -} -} -} +/* Clone Items (Box Swap Method 2) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_CloneItemsBoxCopy2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + +CloneItemsBoxCopy2_Descriptor::CloneItemsBoxCopy2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:CloneItemsBoxCopy2", + STRING_POKEMON + " BDSP", "Clone Items (Box Copy 2)", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/CloneItemsBoxCopy2.md", + "With the menu glitch active, clone entire boxes of items at a time. " + "(The menu glitch can only be activated on version 1.1.0 - 1.1.3.)", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + }, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct CloneItemsBoxCopy2_Descriptor::Stats : public StatsTracker{ + Stats() + : m_boxes(m_stats["Boxes Cloned"]) + , m_errors(m_stats["Errors"]) +// , m_resets(m_stats["Resets"]) + { + m_display_order.emplace_back("Boxes Cloned"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); +// m_display_order.emplace_back("Resets"); + } + std::atomic& m_boxes; + std::atomic& m_errors; +// std::atomic& m_resets; +}; +std::unique_ptr CloneItemsBoxCopy2_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +CloneItemsBoxCopy2::CloneItemsBoxCopy2() + : GO_HOME_WHEN_DONE(false) + , BOXES( + "Boxes to Clone:", + LockMode::LOCK_WHILE_RUNNING, + 999, 0, 999 + ) + , RELEASE( + "Release the pokemon after cloning them:" + "Beware, if set to false, the pokemons will be stored in the subsequent boxes. Make sure you have enough empty boxes.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(BOXES); + PA_ADD_OPTION(RELEASE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void CloneItemsBoxCopy2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + CloneItemsBoxCopy2_Descriptor::Stats& stats = env.current_stats(); + +// uint16_t MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY; +// uint16_t POKEMON_TO_BOX_DELAY = GameSettings::instance().POKEMON_TO_BOX_DELAY0; +// uint16_t OVERWORLD_TO_MENU_DELAY = GameSettings::instance().OVERWORLD_TO_MENU_DELAY; +// uint16_t MENU_TO_OVERWORLD_DELAY = GameSettings::instance().MENU_TO_OVERWORLD_DELAY; + Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + Milliseconds BOX_SCROLL_DELAY = GameSettings::instance().BOX_SCROLL_DELAY0; + Milliseconds BOX_CHANGE_DELAY = GameSettings::instance().BOX_CHANGE_DELAY0; +// uint16_t BOX_TO_POKEMON_DELAY = GameSettings::instance().BOX_TO_POKEMON_DELAY; +// uint16_t POKEMON_TO_MENU_DELAY = GameSettings::instance().POKEMON_TO_MENU_DELAY; + + // Connect the controller. + pbf_mash_button(context, BUTTON_RCLICK, 50); + + // Enter box system. + menu_to_box(context); + + context.wait_for_all_requests(); + VideoSnapshot expected = env.console.video().snapshot(); + ImageMatchWatcher matcher(std::move(expected.frame), {0.02, 0.25, 0.96, 0.73}, 20); + + for (uint16_t box = 0; box < BOXES; box++){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // Select 1st mon. + pbf_press_button(context, BUTTON_ZL, 20, 50); + + // Enter box system again. + overworld_to_box(context); + +#if 0 + // Detach all items. + pbf_press_button(context, BUTTON_X, 20, 50); + detach_box(context, BOX_SCROLL_DELAY); + + // Back to previous menu. + box_to_overworld(context); + + // View Summary + pbf_move_right_joystick(context, 128, 255, 20, 10); + pbf_press_button(context, BUTTON_ZL, 20, 250); + + // Back out. + pbf_press_button(context, BUTTON_B, 20, 230); + +#else + // Move entire box to a new box. + pbf_press_button(context, BUTTON_Y, 20, 50); + pbf_press_button(context, BUTTON_Y, 20, 50); + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + for (size_t c = 0; c < 10; c++){ + pbf_move_right_joystick(context, 255, 128, 5, 3); + pbf_move_right_joystick(context, 128, 255, 5, 3); + } + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + int box_offset = RELEASE ? 1 : 1 + box; + for (int i = 0; i < box_offset; ++i){ + pbf_press_button(context, BUTTON_R, 160ms, BOX_CHANGE_DELAY); + } + pbf_press_button(context, BUTTON_ZL, 160ms, BOX_PICKUP_DROP_DELAY); + + // Back to previous menu. + box_to_overworld(context); + + // View Summary + pbf_move_right_joystick(context, 128, 255, 20, 10); + pbf_press_button(context, BUTTON_ZL, 20, 250); + + // Back out. + pbf_press_button(context, BUTTON_B, 20, 230); + + if (RELEASE){ + // Release the cloned box. + pbf_press_button(context, BUTTON_R, 160ms, BOX_CHANGE_DELAY); + release_box(context, BOX_SCROLL_DELAY); + pbf_press_button(context, BUTTON_L, 160ms, BOX_CHANGE_DELAY); + + // Move cursor back to starting position. + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 128, 255, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); + pbf_move_right_joystick(context, 255, 128, 160ms, BOX_SCROLL_DELAY); + } +#endif + + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(500)); + if (!matcher.detect(env.console.video().snapshot())){ + stats.m_errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to return to starting position. Something is wrong.", + env.console + ); + } + + stats.m_boxes++; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h index e5a7ca520f..26561531c4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Glitches/PokemonBDSP_CloneItemsBoxCopy2.h @@ -1,50 +1,50 @@ -/* Clone Items (Box Copy Method) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_CloneItemsBoxCopy2_H -#define PokemonAutomation_PokemonBDSP_CloneItemsBoxCopy2_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class CloneItemsBoxCopy2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - CloneItemsBoxCopy2_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class CloneItemsBoxCopy2 : public SingleSwitchProgramInstance{ -public: - CloneItemsBoxCopy2(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption BOXES; - BooleanCheckBoxOption RELEASE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Clone Items (Box Copy Method) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_CloneItemsBoxCopy2_H +#define PokemonAutomation_PokemonBDSP_CloneItemsBoxCopy2_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class CloneItemsBoxCopy2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + CloneItemsBoxCopy2_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class CloneItemsBoxCopy2 : public SingleSwitchProgramInstance{ +public: + CloneItemsBoxCopy2(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption BOXES; + BooleanCheckBoxOption RELEASE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.cpp index b7702b87f7..80be22a21a 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.cpp @@ -1,282 +1,282 @@ -/* Basic Pokemon Catcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h" -#include "PokemonBDSP_BasicCatcher.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Returns the # of slots scrolled. Returns -1 if not found. -int move_to_ball( - const BattleBallReader& reader, - VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug, - bool forward, int attempts, uint16_t delay -){ - std::string first_ball = reader.read_ball(stream.video().snapshot()); - if (first_ball == ball_slug){ - return 0; - } - - size_t repeat_counter = 0; - for (int c = 1; c < attempts; c++){ - pbf_press_dpad(context, forward ? DPAD_RIGHT : DPAD_LEFT, 10, delay); - context.wait_for_all_requests(); - std::string current_ball = reader.read_ball(stream.video().snapshot()); - if (current_ball == ball_slug){ - return c; - } - if (current_ball == first_ball){ - repeat_counter++; - if (repeat_counter == 3){ - return -1; - } - } - } - return -1; -} - - -// Returns the quantity of the ball. -// Returns -1 if unable to read. -int16_t move_to_ball( - const BattleBallReader& reader, - VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug -){ - // Search forward at high speed. - int ret = move_to_ball(reader, stream, context, ball_slug, true, 50, 30); - if (ret < 0){ - return 0; - } - if (ret == 0){ - uint16_t quantity = reader.read_quantity(stream.video().snapshot()); - return quantity == 0 ? -1 : quantity; - } - - // Wait a second to let the video catch up. - pbf_wait(context, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Now try again in reverse at a lower speed in case we overshot. - // This will return immediately if we got it right the first time. - ret = move_to_ball(reader, stream, context, ball_slug, false, 5, TICKS_PER_SECOND); - if (ret < 0){ - return 0; - } - if (ret > 0){ - stream.log("BasicCatcher: Fast ball scrolling overshot by " + - std::to_string(ret) + " slot(s).", COLOR_RED); - } - uint16_t quantity = reader.read_quantity(stream.video().snapshot()); - return quantity == 0 ? -1 : quantity; -} - - -CatchResults throw_balls( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit -){ - uint16_t balls_used = 0; - while (true){ - // Test code for checking catch outcome handling: if the wild pokemon fainted: -// #define TEST_WILD_POKEMON_FAINTED -#ifdef TEST_WILD_POKEMON_FAINTED - pbf_mash_button(context, BUTTON_ZL, TICKS_PER_SECOND); - context.wait_for_all_requests(); - if (0) -#endif - { - BattleBallReader reader(stream, language); - - pbf_press_button(context, BUTTON_X, 20, 105); - context.wait_for_all_requests(); - - const int16_t num_balls = move_to_ball(reader, stream, context, ball_slug); - if (num_balls < 0){ - stream.log("BasicCatcher: Unable to read quantity of ball " + ball_slug + "."); - } - if (num_balls == 0){ - stream.log("BasicCatcher: No ball " + ball_slug + - " found in bag or used them all during catching."); - return {CatchResult::OUT_OF_BALLS, balls_used}; - } - - stream.log( - "BasicCatcher: Found " + ball_slug + " with amount " + - std::to_string(num_balls) - ); - pbf_mash_button(context, BUTTON_ZL, 125); - context.wait_for_all_requests(); - } - balls_used++; - - auto start = current_time(); - - BattleMenuWatcher menu_detector(BattleType::STANDARD); - ExperienceGainWatcher experience_detector; - SelectionArrowFinder own_fainted_detector(stream.overlay(), {0.18, 0.64, 0.46, 0.3}, COLOR_YELLOW); - int result = wait_until( - stream, context, - std::chrono::seconds(60), - { - {menu_detector}, - {experience_detector}, - {own_fainted_detector}, - } - ); - switch (result){ - case 0: - if (current_time() < start + std::chrono::seconds(5)){ - return {CatchResult::CANNOT_THROW_BALL, balls_used}; - } - stream.log("BasicCatcher: Failed to catch.", COLOR_ORANGE); - if (balls_used >= ball_limit){ - stream.log("Reached the limit of " + std::to_string(ball_limit) + " balls.", COLOR_RED); - return {CatchResult::BALL_LIMIT_REACHED, balls_used}; - } - continue; - case 1: - stream.log("BasicCatcher: End of battle detected.", COLOR_PURPLE); - // It's actually fainted or caught. The logic to find out which one - // is in basic_catcher(). - return {CatchResult::POKEMON_FAINTED, balls_used}; - case 2: - return {CatchResult::OWN_FAINTED, balls_used}; - default: - return {CatchResult::TIMED_OUT, balls_used}; - } - } -} - - -CatchResults basic_catcher( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit -){ - context.wait_for_all_requests(); - stream.log("Attempting to catch with: " + ball_slug); - - CatchResults results = throw_balls(stream, context, language, ball_slug, ball_limit); - const std::string s = (results.balls_used <= 1 ? "" : "s"); - const std::string pokeball_str = std::to_string(results.balls_used) + " " + ball_slug + s; - - switch (results.result){ - case CatchResult::OUT_OF_BALLS: - stream.log("BasicCatcher: Out of balls after throwing " + pokeball_str, COLOR_RED); - return results; - case CatchResult::CANNOT_THROW_BALL: - stream.log("BasicCatcher: Unable to throw a ball.", COLOR_RED); - return results; - case CatchResult::BALL_LIMIT_REACHED: - stream.log("BasicCatcher: Ball limit reached.", COLOR_RED); - return results; - case CatchResult::OWN_FAINTED: - stream.log("BasicCatcher: Wwn " + Pokemon::STRING_POKEMON + " fainted after throwing " + pokeball_str, COLOR_RED); - return results; - case CatchResult::TIMED_OUT: - stream.log("BasicCatcher: Timed out.", COLOR_RED); - return results; - default:; - } - - // Need to distinguish between caught or faint. - // Where there is no pokemon evolving, the order of events in BDSP is: - // exp screen -> lvl up and learn new move dialog -> new pokemon received screen if caught - // -> black screen -> return to overworld - // Wthere there is pokemon evolving, the order becomes: - // exp screen -> lvl up and learn new move dialog -> black screen -> pokemon evolving - // -> new pokemon received screen if caught. - // In this basic_catcher() we don't handle pokemon evolving. - - // First, default the result to be fainted. - results.result = CatchResult::POKEMON_FAINTED; - size_t num_learned_moves = 0; - while (true){ - context.wait_for_all_requests(); - // Wait for end of battle. - // BlackScreenOverWatcher black_screen_detector; - EndBattleWatcher end_battle; - // Look for a pokemon learning a new move. - SelectionArrowFinder learn_move(stream.overlay(), {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); - // Look for the pokemon caught screen. - ReceivePokemonDetector caught_detector; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - { - {end_battle}, - {caught_detector}, - {learn_move}, - } - ); - switch (ret){ - case 0: - if (results.result == CatchResult::POKEMON_FAINTED){ - stream.log( - "BasicCatcher: The wild " + STRING_POKEMON + " fainted after " + - pokeball_str, COLOR_RED - ); - } - stream.log("BasicCatcher: Battle finished!", COLOR_BLUE); - pbf_wait(context, TICKS_PER_SECOND); - context.wait_for_all_requests(); - return results; - case 1: - if (results.result == CatchResult::POKEMON_CAUGHT){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "BasicCatcher: Found receive pokemon screen two times.", - stream - ); - } - stream.log("BasicCatcher: The wild " + STRING_POKEMON + " was caught by " + pokeball_str, COLOR_BLUE); - pbf_wait(context, 50); - results.result = CatchResult::POKEMON_CAUGHT; - break; // Continue the loop. - case 2: - stream.log("BasicCatcher: Detected move learn! Don't learn the new move.", COLOR_BLUE); - num_learned_moves++; - if (num_learned_moves == 100){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "BasicCatcher: Learn new move attempts reach 100.", - stream - ); - } - pbf_move_right_joystick(context, 128, 255, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; // Continue the loop. - - default: - stream.log("BasicCatcher: Timed out.", COLOR_RED); - results.result = CatchResult::TIMED_OUT; - return results; - } - } -} - - -} -} -} +/* Basic Pokemon Catcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_ReceivePokemonDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_ExperienceGainDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_EndBattleDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleBallReader.h" +#include "PokemonBDSP_BasicCatcher.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Returns the # of slots scrolled. Returns -1 if not found. +int move_to_ball( + const BattleBallReader& reader, + VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug, + bool forward, int attempts, uint16_t delay +){ + std::string first_ball = reader.read_ball(stream.video().snapshot()); + if (first_ball == ball_slug){ + return 0; + } + + size_t repeat_counter = 0; + for (int c = 1; c < attempts; c++){ + pbf_press_dpad(context, forward ? DPAD_RIGHT : DPAD_LEFT, 10, delay); + context.wait_for_all_requests(); + std::string current_ball = reader.read_ball(stream.video().snapshot()); + if (current_ball == ball_slug){ + return c; + } + if (current_ball == first_ball){ + repeat_counter++; + if (repeat_counter == 3){ + return -1; + } + } + } + return -1; +} + + +// Returns the quantity of the ball. +// Returns -1 if unable to read. +int16_t move_to_ball( + const BattleBallReader& reader, + VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug +){ + // Search forward at high speed. + int ret = move_to_ball(reader, stream, context, ball_slug, true, 50, 30); + if (ret < 0){ + return 0; + } + if (ret == 0){ + uint16_t quantity = reader.read_quantity(stream.video().snapshot()); + return quantity == 0 ? -1 : quantity; + } + + // Wait a second to let the video catch up. + pbf_wait(context, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Now try again in reverse at a lower speed in case we overshot. + // This will return immediately if we got it right the first time. + ret = move_to_ball(reader, stream, context, ball_slug, false, 5, TICKS_PER_SECOND); + if (ret < 0){ + return 0; + } + if (ret > 0){ + stream.log("BasicCatcher: Fast ball scrolling overshot by " + + std::to_string(ret) + " slot(s).", COLOR_RED); + } + uint16_t quantity = reader.read_quantity(stream.video().snapshot()); + return quantity == 0 ? -1 : quantity; +} + + +CatchResults throw_balls( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit +){ + uint16_t balls_used = 0; + while (true){ + // Test code for checking catch outcome handling: if the wild pokemon fainted: +// #define TEST_WILD_POKEMON_FAINTED +#ifdef TEST_WILD_POKEMON_FAINTED + pbf_mash_button(context, BUTTON_ZL, TICKS_PER_SECOND); + context.wait_for_all_requests(); + if (0) +#endif + { + BattleBallReader reader(stream, language); + + pbf_press_button(context, BUTTON_X, 20, 105); + context.wait_for_all_requests(); + + const int16_t num_balls = move_to_ball(reader, stream, context, ball_slug); + if (num_balls < 0){ + stream.log("BasicCatcher: Unable to read quantity of ball " + ball_slug + "."); + } + if (num_balls == 0){ + stream.log("BasicCatcher: No ball " + ball_slug + + " found in bag or used them all during catching."); + return {CatchResult::OUT_OF_BALLS, balls_used}; + } + + stream.log( + "BasicCatcher: Found " + ball_slug + " with amount " + + std::to_string(num_balls) + ); + pbf_mash_button(context, BUTTON_ZL, 125); + context.wait_for_all_requests(); + } + balls_used++; + + auto start = current_time(); + + BattleMenuWatcher menu_detector(BattleType::STANDARD); + ExperienceGainWatcher experience_detector; + SelectionArrowFinder own_fainted_detector(stream.overlay(), {0.18, 0.64, 0.46, 0.3}, COLOR_YELLOW); + int result = wait_until( + stream, context, + std::chrono::seconds(60), + { + {menu_detector}, + {experience_detector}, + {own_fainted_detector}, + } + ); + switch (result){ + case 0: + if (current_time() < start + std::chrono::seconds(5)){ + return {CatchResult::CANNOT_THROW_BALL, balls_used}; + } + stream.log("BasicCatcher: Failed to catch.", COLOR_ORANGE); + if (balls_used >= ball_limit){ + stream.log("Reached the limit of " + std::to_string(ball_limit) + " balls.", COLOR_RED); + return {CatchResult::BALL_LIMIT_REACHED, balls_used}; + } + continue; + case 1: + stream.log("BasicCatcher: End of battle detected.", COLOR_PURPLE); + // It's actually fainted or caught. The logic to find out which one + // is in basic_catcher(). + return {CatchResult::POKEMON_FAINTED, balls_used}; + case 2: + return {CatchResult::OWN_FAINTED, balls_used}; + default: + return {CatchResult::TIMED_OUT, balls_used}; + } + } +} + + +CatchResults basic_catcher( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit +){ + context.wait_for_all_requests(); + stream.log("Attempting to catch with: " + ball_slug); + + CatchResults results = throw_balls(stream, context, language, ball_slug, ball_limit); + const std::string s = (results.balls_used <= 1 ? "" : "s"); + const std::string pokeball_str = std::to_string(results.balls_used) + " " + ball_slug + s; + + switch (results.result){ + case CatchResult::OUT_OF_BALLS: + stream.log("BasicCatcher: Out of balls after throwing " + pokeball_str, COLOR_RED); + return results; + case CatchResult::CANNOT_THROW_BALL: + stream.log("BasicCatcher: Unable to throw a ball.", COLOR_RED); + return results; + case CatchResult::BALL_LIMIT_REACHED: + stream.log("BasicCatcher: Ball limit reached.", COLOR_RED); + return results; + case CatchResult::OWN_FAINTED: + stream.log("BasicCatcher: Wwn " + Pokemon::STRING_POKEMON + " fainted after throwing " + pokeball_str, COLOR_RED); + return results; + case CatchResult::TIMED_OUT: + stream.log("BasicCatcher: Timed out.", COLOR_RED); + return results; + default:; + } + + // Need to distinguish between caught or faint. + // Where there is no pokemon evolving, the order of events in BDSP is: + // exp screen -> lvl up and learn new move dialog -> new pokemon received screen if caught + // -> black screen -> return to overworld + // Wthere there is pokemon evolving, the order becomes: + // exp screen -> lvl up and learn new move dialog -> black screen -> pokemon evolving + // -> new pokemon received screen if caught. + // In this basic_catcher() we don't handle pokemon evolving. + + // First, default the result to be fainted. + results.result = CatchResult::POKEMON_FAINTED; + size_t num_learned_moves = 0; + while (true){ + context.wait_for_all_requests(); + // Wait for end of battle. + // BlackScreenOverWatcher black_screen_detector; + EndBattleWatcher end_battle; + // Look for a pokemon learning a new move. + SelectionArrowFinder learn_move(stream.overlay(), {0.50, 0.62, 0.40, 0.18}, COLOR_YELLOW); + // Look for the pokemon caught screen. + ReceivePokemonDetector caught_detector; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + { + {end_battle}, + {caught_detector}, + {learn_move}, + } + ); + switch (ret){ + case 0: + if (results.result == CatchResult::POKEMON_FAINTED){ + stream.log( + "BasicCatcher: The wild " + STRING_POKEMON + " fainted after " + + pokeball_str, COLOR_RED + ); + } + stream.log("BasicCatcher: Battle finished!", COLOR_BLUE); + pbf_wait(context, TICKS_PER_SECOND); + context.wait_for_all_requests(); + return results; + case 1: + if (results.result == CatchResult::POKEMON_CAUGHT){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "BasicCatcher: Found receive pokemon screen two times.", + stream + ); + } + stream.log("BasicCatcher: The wild " + STRING_POKEMON + " was caught by " + pokeball_str, COLOR_BLUE); + pbf_wait(context, 50); + results.result = CatchResult::POKEMON_CAUGHT; + break; // Continue the loop. + case 2: + stream.log("BasicCatcher: Detected move learn! Don't learn the new move.", COLOR_BLUE); + num_learned_moves++; + if (num_learned_moves == 100){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "BasicCatcher: Learn new move attempts reach 100.", + stream + ); + } + pbf_move_right_joystick(context, 128, 255, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; // Continue the loop. + + default: + stream.log("BasicCatcher: Timed out.", COLOR_RED); + results.result = CatchResult::TIMED_OUT; + return results; + } + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h index c8b9154d0b..8566fe18b6 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BasicCatcher.h @@ -1,47 +1,47 @@ -/* Basic Pokemon Catcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BasicCatcher_H -#define PokemonAutomation_PokemonBDSP_BasicCatcher_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_Notification.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -struct CatchResults{ - CatchResult result = CatchResult::TIMED_OUT; - uint16_t balls_used = 0; -}; - -// Throw balls repeatedly to catch wild pokemon. -// It can detect whether the wild pokemon is caught, the wild pokemon is fainted, -// cannot throw balls, own pokemon fainted, out of balls or timeout. -// If both own and wild pokemon fainted and not blackout, count as wild pokemon fainted. -// If own pokemon level up and want to learn new moves, choose to not learn them. -// If the wild pokemon is caught or fainted, the game returns to the overworld when -// basic_catcher() returns. -// -// Don't handle the case that own pokemon evolving or black out to Pokecenter. -CatchResults basic_catcher( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit -); - - - -} -} -} -#endif +/* Basic Pokemon Catcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BasicCatcher_H +#define PokemonAutomation_PokemonBDSP_BasicCatcher_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_Notification.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +struct CatchResults{ + CatchResult result = CatchResult::TIMED_OUT; + uint16_t balls_used = 0; +}; + +// Throw balls repeatedly to catch wild pokemon. +// It can detect whether the wild pokemon is caught, the wild pokemon is fainted, +// cannot throw balls, own pokemon fainted, out of balls or timeout. +// If both own and wild pokemon fainted and not blackout, count as wild pokemon fainted. +// If own pokemon level up and want to learn new moves, choose to not learn them. +// If the wild pokemon is caught or fainted, the game returns to the overworld when +// basic_catcher() returns. +// +// Don't handle the case that own pokemon evolving or black out to Pokecenter. +CatchResults basic_catcher( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.cpp index 2895247c51..ee85f7b855 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.cpp @@ -1,95 +1,95 @@ -/* Box Release Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP_BoxRelease.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -void detach(ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 20, 50); - pbf_move_right_joystick(context, 128, 255, 20, 10); - pbf_press_button(context, BUTTON_ZL, 20, 85); - pbf_press_button(context, BUTTON_ZL, 20, 85); -// pbf_move_right_joystick(context, 128, 255, 20, 0); - pbf_press_button(context, BUTTON_B, 20, 85); -} -void detach_box(ProControllerContext& context, uint16_t box_scroll_delay){ - for (uint8_t row = 0; row < 5; row++){ - if (row != 0){ - pbf_move_right_joystick(context, 128, 255, 20, box_scroll_delay); - pbf_move_right_joystick(context, 255, 128, 20, box_scroll_delay); - pbf_move_right_joystick(context, 255, 128, 20, box_scroll_delay); - } - for (uint8_t col = 0; col < 6; col++){ -// context->wait_for_all_requests(); - if (col != 0){ - pbf_move_right_joystick(context, 255, 128, 20, box_scroll_delay); - } -// context->wait_for_all_requests(); - detach(context); - } - } -} - - - - - -void release(ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 20, 50); - pbf_move_right_joystick(context, 128, 0, 20, 10); - pbf_move_right_joystick(context, 128, 0, 20, 10); - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_move_right_joystick(context, 128, 255, 20, 10); - pbf_mash_button(context, BUTTON_ZL, 120); - pbf_wait(context, 30); -} -void release_box(ProControllerContext& context, Milliseconds box_scroll_delay){ - for (uint8_t row = 0; row < 5; row++){ - if (row != 0){ - pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); - pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); - pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); - } - for (uint8_t col = 0; col < 6; col++){ -// context->wait_for_all_requests(); - if (col != 0){ - pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); - } -// context->wait_for_all_requests(); - release(context); - } - } -} -void release_boxes( - ProControllerContext& context, - uint8_t boxes, - Milliseconds box_scroll_delay, - Milliseconds box_change_delay -){ - if (boxes == 0){ - return; - } - release_box(context, box_scroll_delay); - for (uint8_t box = 1; box < boxes; box++){ - pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); - pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); - pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); - pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); - pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); - pbf_wait(context, 50); - pbf_press_button(context, BUTTON_R, 160ms, box_change_delay); - release_box(context, box_scroll_delay); - } -} - - -} -} -} +/* Box Release Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_BoxRelease.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +void detach(ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 20, 50); + pbf_move_right_joystick(context, 128, 255, 20, 10); + pbf_press_button(context, BUTTON_ZL, 20, 85); + pbf_press_button(context, BUTTON_ZL, 20, 85); +// pbf_move_right_joystick(context, 128, 255, 20, 0); + pbf_press_button(context, BUTTON_B, 20, 85); +} +void detach_box(ProControllerContext& context, uint16_t box_scroll_delay){ + for (uint8_t row = 0; row < 5; row++){ + if (row != 0){ + pbf_move_right_joystick(context, 128, 255, 20, box_scroll_delay); + pbf_move_right_joystick(context, 255, 128, 20, box_scroll_delay); + pbf_move_right_joystick(context, 255, 128, 20, box_scroll_delay); + } + for (uint8_t col = 0; col < 6; col++){ +// context->wait_for_all_requests(); + if (col != 0){ + pbf_move_right_joystick(context, 255, 128, 20, box_scroll_delay); + } +// context->wait_for_all_requests(); + detach(context); + } + } +} + + + + + +void release(ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 20, 50); + pbf_move_right_joystick(context, 128, 0, 20, 10); + pbf_move_right_joystick(context, 128, 0, 20, 10); + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_move_right_joystick(context, 128, 255, 20, 10); + pbf_mash_button(context, BUTTON_ZL, 120); + pbf_wait(context, 30); +} +void release_box(ProControllerContext& context, Milliseconds box_scroll_delay){ + for (uint8_t row = 0; row < 5; row++){ + if (row != 0){ + pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); + pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); + pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); + } + for (uint8_t col = 0; col < 6; col++){ +// context->wait_for_all_requests(); + if (col != 0){ + pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); + } +// context->wait_for_all_requests(); + release(context); + } + } +} +void release_boxes( + ProControllerContext& context, + uint8_t boxes, + Milliseconds box_scroll_delay, + Milliseconds box_change_delay +){ + if (boxes == 0){ + return; + } + release_box(context, box_scroll_delay); + for (uint8_t box = 1; box < boxes; box++){ + pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); + pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); + pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); + pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); + pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); + pbf_wait(context, 50); + pbf_press_button(context, BUTTON_R, 160ms, box_change_delay); + release_box(context, box_scroll_delay); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h index 83a1870eb5..00ebc7690f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_BoxRelease.h @@ -1,34 +1,34 @@ -/* Box Release Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_BoxReleaseTools_H -#define PokemonAutomation_PokemonBDSP_BoxReleaseTools_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Detach items. -void detach(ProControllerContext& context); -void detach_box(ProControllerContext& context, uint16_t box_scroll_delay); - -// Release Pokemon. -void release(ProControllerContext& context); -void release_box(ProControllerContext& context, Milliseconds box_scroll_delay); -void release_boxes( - ProControllerContext& context, - uint8_t boxes, - Milliseconds box_scroll_delay, - Milliseconds box_change_delay -); - - -} -} -} -#endif +/* Box Release Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_BoxReleaseTools_H +#define PokemonAutomation_PokemonBDSP_BoxReleaseTools_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Detach items. +void detach(ProControllerContext& context); +void detach_box(ProControllerContext& context, uint16_t box_scroll_delay); + +// Release Pokemon. +void release(ProControllerContext& context); +void release_box(ProControllerContext& context, Milliseconds box_scroll_delay); +void release_boxes( + ProControllerContext& context, + uint8_t boxes, + Milliseconds box_scroll_delay, + Milliseconds box_change_delay +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.cpp index 19cfc24ace..aefc488a79 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.cpp @@ -1,294 +1,294 @@ -/* Encounter Detection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonBDSP_EncounterDetection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -StandardEncounterDetection::StandardEncounterDetection( - VideoStream& stream, ProControllerContext& context, - Language language, - const EncounterFilterOption2& filter, - const DoublesShinyDetection& shininess, - std::chrono::milliseconds read_name_delay -) - : m_stream(stream) - , m_language(language) - , m_filter(filter) - , m_shininess(shininess) - , m_double_battle(false) -{ -// InferenceBoxScope left_mon_white(stream, {0.685, 0.065, 0.025, 0.040}); - OverlayBoxScope left_mon_white(stream.overlay(), {0.708, 0.070, 0.005, 0.028}); - OverlayBoxScope left_mon_hp(stream.overlay(), {0.500, 0.120, 0.18, 0.005}); - OverlayBoxScope left_name(stream.overlay(), {0.467, 0.06, 0.16, 0.050}); - OverlayBoxScope right_name(stream.overlay(), {0.740, 0.06, 0.16, 0.050}); - - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(100)); - VideoSnapshot screen = stream.video().snapshot(); - - // Check if it's a double battle. - do{ - if (!is_white(extract_box_reference(screen, left_mon_white))){ - break; - } - ImageStats stats_hp = image_stats(extract_box_reference(screen, left_mon_hp)); -// cout << stats_hp.average << stats_hp.stddev << endl; - if (!is_solid(stats_hp, {0.27731, 0.461346, 0.261344}, 0.1, 50)){ - break; - } - m_double_battle = true; - }while (false); - - m_pokemon_left.exists = m_double_battle; - m_pokemon_right.exists = true; - - // Read the names. - if (m_language != Language::None){ - if (m_double_battle){ - m_pokemon_left.detection_enabled = true; - m_pokemon_left.slugs = read_name(screen, left_name); - } - m_pokemon_right.detection_enabled = true; - m_pokemon_right.slugs = read_name(screen, right_name); - } - - // Not a double battle. Pass overall shiny detection to right side. - if (!m_double_battle){ - m_shininess_left = ShinyType::NOT_SHINY; - m_shininess_right = m_shininess.shiny_type; - return; - } - - // Not shiny. Pass shiny detection to both sides. - bool overall_shiny = is_likely_shiny(m_shininess.shiny_type); - if (!overall_shiny){ - m_shininess_left = m_shininess.shiny_type; - m_shininess_right = m_shininess.shiny_type; - return; - } - - // Shiny. But neither side takes ownership. Mark both as unknown. - if (!m_shininess.left_is_shiny && !m_shininess.right_is_shiny){ - m_shininess_left = ShinyType::MAYBE_SHINY; - m_shininess_right = ShinyType::MAYBE_SHINY; - return; - } - - // Shiny. Someone claims it. - m_shininess_left = m_shininess.left_is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY; - m_shininess_right = m_shininess.right_is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY; -} -const PokemonDetection& StandardEncounterDetection::pokemon_left() const{ - return m_pokemon_left; -} -const PokemonDetection& StandardEncounterDetection::pokemon_right() const{ - return m_pokemon_right; -} -bool StandardEncounterDetection::has_shiny() const{ - switch (m_shininess.shiny_type){ - case ShinyType::UNKNOWN: - case ShinyType::NOT_SHINY: - return false; - case ShinyType::MAYBE_SHINY: - case ShinyType::UNKNOWN_SHINY: - case ShinyType::STAR_SHINY: - case ShinyType::SQUARE_SHINY: - return true; - } - return false; -} - -std::set StandardEncounterDetection::read_name(const ImageViewRGB32& screen, const ImageFloatBox& box){ - ImageViewRGB32 image = extract_box_reference(screen, box); - - std::set ret; - - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - m_stream.logger(), m_language, image, - OCR::BLACK_TEXT_FILTERS() - ); - if (result.results.empty()){ - dump_image( - m_stream.logger(), ProgramInfo(), - "StandardEncounterDetection-NameOCR-" + language_data(m_language).code, - screen, - &m_stream.history() - ); - }else{ - for (const auto& item : result.results){ - ret.insert(item.second.token); - } - } - return ret; -} - - - - -bool filter_match(ShinyType detection, ShinyFilter filter){ - if (detection == ShinyType::UNKNOWN){ - return false; - } - - switch (filter){ - case ShinyFilter::ANYTHING: - return true; - case ShinyFilter::NOT_SHINY: - return detection == ShinyType::NOT_SHINY; - case ShinyFilter::SHINY: - return detection != ShinyType::NOT_SHINY; - case ShinyFilter::NOTHING: - return false; - } - - return false; -} -bool StandardEncounterDetection::run_overrides( - EncounterActionFull& action, - const std::vector>& overrides, - const PokemonDetection& pokemon, ShinyType side_shiny -) const{ - if (!pokemon.exists || !pokemon.detection_enabled){ - return false; - } - bool triggered = false; - for (const std::unique_ptr& override : overrides){ - // Not a token match. - if (pokemon.slugs.find(override->pokemon.slug()) == pokemon.slugs.end()){ - continue; - } - - ShinyType shiny = side_shiny; - if (shiny == ShinyType::MAYBE_SHINY){ -// actions.emplace_back(EncounterAction::StopProgram, ""); - throw_and_log( - m_stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Cannot run encounter actions due to low confidence shiny detection.", - m_stream - ); - } - - // Matched the filter. - if (filter_match(shiny, override->shininess)){ - triggered = true; - action = {override->action, override->pokeball.slug(), override->ball_limit}; - } - } - return triggered; -} - - -EncounterActionFull StandardEncounterDetection::get_action_singles(){ - if (m_shininess_right == ShinyType::UNKNOWN){ - return {EncounterAction::RunAway, "", 999}; - } - - ShinyFilter shiny_filter = m_filter.SHINY_FILTER; - - EncounterActionFull default_action; - default_action.action = filter_match(m_shininess_right, shiny_filter) - ? EncounterAction::StopProgram - : EncounterAction::RunAway; - - const std::vector>& overrides = m_filter.FILTER_TABLE.copy_snapshot(); - if (m_language != Language::None && !overrides.empty()){ - run_overrides(default_action, overrides, m_pokemon_right, m_shininess_right); - } - - m_stream.log("Action: " + default_action.to_str()); - - return default_action; -} -EncounterActionFull StandardEncounterDetection::get_action_doubles(){ - ShinyFilter shiny_filter = m_filter.SHINY_FILTER; - - EncounterActionFull action_left; - action_left.action = filter_match(m_shininess_left, shiny_filter) - ? EncounterAction::StopProgram - : EncounterAction::RunAway; - - EncounterActionFull action_right; - action_right.action = filter_match(m_shininess_right, shiny_filter) - ? EncounterAction::StopProgram - : EncounterAction::RunAway; - - const std::vector>& overrides = m_filter.FILTER_TABLE.copy_snapshot(); - if (m_language != Language::None && !overrides.empty()){ - run_overrides(action_left, overrides, m_pokemon_left, m_shininess_left); - run_overrides(action_right, overrides, m_pokemon_right, m_shininess_right); - } - - std::string str_left = "Left " + STRING_POKEMON + ": " + action_left.to_str(); - std::string str_right = "Right " + STRING_POKEMON + ": " + action_right.to_str(); - m_stream.log(str_left); - m_stream.log(str_right); - - // If either action is stop program, we stop program. - if (action_left.action == EncounterAction::StopProgram){ - return action_left; - } - if (action_right.action == EncounterAction::StopProgram){ - return action_right; - } - - if (action_left != action_right){ - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Conflicting actions requested.\n" + str_left + "\n" + str_right, - m_stream - ); - } - - bool auto_catch = false; - auto_catch |= action_left.action == EncounterAction::ThrowBalls; - auto_catch |= action_left.action == EncounterAction::ThrowBallsAndSave; - auto_catch |= action_right.action == EncounterAction::ThrowBalls; - auto_catch |= action_right.action == EncounterAction::ThrowBallsAndSave; - - // Double battle and someone is set to auto-catch. - if (auto_catch && m_double_battle){ - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Cannot auto-catch in a double battle.", - m_stream - ); - } - - // Otherwise, return the matching action. - return action_right; -} - -EncounterActionFull StandardEncounterDetection::get_action(){ - return m_double_battle ? get_action_doubles() : get_action_singles(); -} - - - - - - - -} -} -} +/* Encounter Detection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonBDSP_EncounterDetection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +StandardEncounterDetection::StandardEncounterDetection( + VideoStream& stream, ProControllerContext& context, + Language language, + const EncounterFilterOption2& filter, + const DoublesShinyDetection& shininess, + std::chrono::milliseconds read_name_delay +) + : m_stream(stream) + , m_language(language) + , m_filter(filter) + , m_shininess(shininess) + , m_double_battle(false) +{ +// InferenceBoxScope left_mon_white(stream, {0.685, 0.065, 0.025, 0.040}); + OverlayBoxScope left_mon_white(stream.overlay(), {0.708, 0.070, 0.005, 0.028}); + OverlayBoxScope left_mon_hp(stream.overlay(), {0.500, 0.120, 0.18, 0.005}); + OverlayBoxScope left_name(stream.overlay(), {0.467, 0.06, 0.16, 0.050}); + OverlayBoxScope right_name(stream.overlay(), {0.740, 0.06, 0.16, 0.050}); + + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(100)); + VideoSnapshot screen = stream.video().snapshot(); + + // Check if it's a double battle. + do{ + if (!is_white(extract_box_reference(screen, left_mon_white))){ + break; + } + ImageStats stats_hp = image_stats(extract_box_reference(screen, left_mon_hp)); +// cout << stats_hp.average << stats_hp.stddev << endl; + if (!is_solid(stats_hp, {0.27731, 0.461346, 0.261344}, 0.1, 50)){ + break; + } + m_double_battle = true; + }while (false); + + m_pokemon_left.exists = m_double_battle; + m_pokemon_right.exists = true; + + // Read the names. + if (m_language != Language::None){ + if (m_double_battle){ + m_pokemon_left.detection_enabled = true; + m_pokemon_left.slugs = read_name(screen, left_name); + } + m_pokemon_right.detection_enabled = true; + m_pokemon_right.slugs = read_name(screen, right_name); + } + + // Not a double battle. Pass overall shiny detection to right side. + if (!m_double_battle){ + m_shininess_left = ShinyType::NOT_SHINY; + m_shininess_right = m_shininess.shiny_type; + return; + } + + // Not shiny. Pass shiny detection to both sides. + bool overall_shiny = is_likely_shiny(m_shininess.shiny_type); + if (!overall_shiny){ + m_shininess_left = m_shininess.shiny_type; + m_shininess_right = m_shininess.shiny_type; + return; + } + + // Shiny. But neither side takes ownership. Mark both as unknown. + if (!m_shininess.left_is_shiny && !m_shininess.right_is_shiny){ + m_shininess_left = ShinyType::MAYBE_SHINY; + m_shininess_right = ShinyType::MAYBE_SHINY; + return; + } + + // Shiny. Someone claims it. + m_shininess_left = m_shininess.left_is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY; + m_shininess_right = m_shininess.right_is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY; +} +const PokemonDetection& StandardEncounterDetection::pokemon_left() const{ + return m_pokemon_left; +} +const PokemonDetection& StandardEncounterDetection::pokemon_right() const{ + return m_pokemon_right; +} +bool StandardEncounterDetection::has_shiny() const{ + switch (m_shininess.shiny_type){ + case ShinyType::UNKNOWN: + case ShinyType::NOT_SHINY: + return false; + case ShinyType::MAYBE_SHINY: + case ShinyType::UNKNOWN_SHINY: + case ShinyType::STAR_SHINY: + case ShinyType::SQUARE_SHINY: + return true; + } + return false; +} + +std::set StandardEncounterDetection::read_name(const ImageViewRGB32& screen, const ImageFloatBox& box){ + ImageViewRGB32 image = extract_box_reference(screen, box); + + std::set ret; + + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + m_stream.logger(), m_language, image, + OCR::BLACK_TEXT_FILTERS() + ); + if (result.results.empty()){ + dump_image( + m_stream.logger(), ProgramInfo(), + "StandardEncounterDetection-NameOCR-" + language_data(m_language).code, + screen, + &m_stream.history() + ); + }else{ + for (const auto& item : result.results){ + ret.insert(item.second.token); + } + } + return ret; +} + + + + +bool filter_match(ShinyType detection, ShinyFilter filter){ + if (detection == ShinyType::UNKNOWN){ + return false; + } + + switch (filter){ + case ShinyFilter::ANYTHING: + return true; + case ShinyFilter::NOT_SHINY: + return detection == ShinyType::NOT_SHINY; + case ShinyFilter::SHINY: + return detection != ShinyType::NOT_SHINY; + case ShinyFilter::NOTHING: + return false; + } + + return false; +} +bool StandardEncounterDetection::run_overrides( + EncounterActionFull& action, + const std::vector>& overrides, + const PokemonDetection& pokemon, ShinyType side_shiny +) const{ + if (!pokemon.exists || !pokemon.detection_enabled){ + return false; + } + bool triggered = false; + for (const std::unique_ptr& override : overrides){ + // Not a token match. + if (pokemon.slugs.find(override->pokemon.slug()) == pokemon.slugs.end()){ + continue; + } + + ShinyType shiny = side_shiny; + if (shiny == ShinyType::MAYBE_SHINY){ +// actions.emplace_back(EncounterAction::StopProgram, ""); + throw_and_log( + m_stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Cannot run encounter actions due to low confidence shiny detection.", + m_stream + ); + } + + // Matched the filter. + if (filter_match(shiny, override->shininess)){ + triggered = true; + action = {override->action, override->pokeball.slug(), override->ball_limit}; + } + } + return triggered; +} + + +EncounterActionFull StandardEncounterDetection::get_action_singles(){ + if (m_shininess_right == ShinyType::UNKNOWN){ + return {EncounterAction::RunAway, "", 999}; + } + + ShinyFilter shiny_filter = m_filter.SHINY_FILTER; + + EncounterActionFull default_action; + default_action.action = filter_match(m_shininess_right, shiny_filter) + ? EncounterAction::StopProgram + : EncounterAction::RunAway; + + const std::vector>& overrides = m_filter.FILTER_TABLE.copy_snapshot(); + if (m_language != Language::None && !overrides.empty()){ + run_overrides(default_action, overrides, m_pokemon_right, m_shininess_right); + } + + m_stream.log("Action: " + default_action.to_str()); + + return default_action; +} +EncounterActionFull StandardEncounterDetection::get_action_doubles(){ + ShinyFilter shiny_filter = m_filter.SHINY_FILTER; + + EncounterActionFull action_left; + action_left.action = filter_match(m_shininess_left, shiny_filter) + ? EncounterAction::StopProgram + : EncounterAction::RunAway; + + EncounterActionFull action_right; + action_right.action = filter_match(m_shininess_right, shiny_filter) + ? EncounterAction::StopProgram + : EncounterAction::RunAway; + + const std::vector>& overrides = m_filter.FILTER_TABLE.copy_snapshot(); + if (m_language != Language::None && !overrides.empty()){ + run_overrides(action_left, overrides, m_pokemon_left, m_shininess_left); + run_overrides(action_right, overrides, m_pokemon_right, m_shininess_right); + } + + std::string str_left = "Left " + STRING_POKEMON + ": " + action_left.to_str(); + std::string str_right = "Right " + STRING_POKEMON + ": " + action_right.to_str(); + m_stream.log(str_left); + m_stream.log(str_right); + + // If either action is stop program, we stop program. + if (action_left.action == EncounterAction::StopProgram){ + return action_left; + } + if (action_right.action == EncounterAction::StopProgram){ + return action_right; + } + + if (action_left != action_right){ + throw_and_log( + m_stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Conflicting actions requested.\n" + str_left + "\n" + str_right, + m_stream + ); + } + + bool auto_catch = false; + auto_catch |= action_left.action == EncounterAction::ThrowBalls; + auto_catch |= action_left.action == EncounterAction::ThrowBallsAndSave; + auto_catch |= action_right.action == EncounterAction::ThrowBalls; + auto_catch |= action_right.action == EncounterAction::ThrowBallsAndSave; + + // Double battle and someone is set to auto-catch. + if (auto_catch && m_double_battle){ + throw_and_log( + m_stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Cannot auto-catch in a double battle.", + m_stream + ); + } + + // Otherwise, return the matching action. + return action_right; +} + +EncounterActionFull StandardEncounterDetection::get_action(){ + return m_double_battle ? get_action_doubles() : get_action_singles(); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h index 00b495c599..5a7c74b924 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h @@ -1,84 +1,84 @@ -/* Encounter Detection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterTracker_H -#define PokemonAutomation_PokemonBDSP_EncounterTracker_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -struct PokemonDetection{ - bool exists = false; - bool detection_enabled = false; - std::set slugs; -}; - - -class StandardEncounterDetection{ -public: - StandardEncounterDetection( - VideoStream& stream, ProControllerContext& context, - Language language, - const EncounterFilterOption2& filter, - const DoublesShinyDetection& shininess, - std::chrono::milliseconds read_name_delay = std::chrono::milliseconds(500) - ); - - bool is_double_battle() const{ return m_double_battle; } - const PokemonDetection& pokemon_left() const; - const PokemonDetection& pokemon_right() const; - - bool has_shiny() const; - ShinyType overall_shininess() const{ return m_shininess.shiny_type; } - ShinyType left_shininess() const{ return m_shininess_left; } - ShinyType right_shininess() const{ return m_shininess_right; } - - EncounterActionFull get_action(); - -private: - std::set read_name(const ImageViewRGB32& screen, const ImageFloatBox& box); - bool run_overrides( - EncounterActionFull& action, - const std::vector>& overrides, - const PokemonDetection& pokemon, ShinyType side_shiny - ) const; - EncounterActionFull get_action_singles(); - EncounterActionFull get_action_doubles(); - -private: - VideoStream& m_stream; - - const Language m_language; - - const EncounterFilterOption2& m_filter; - const DoublesShinyDetection& m_shininess; - - bool m_double_battle = false; - ShinyType m_shininess_left; - ShinyType m_shininess_right; - - PokemonDetection m_pokemon_left; - PokemonDetection m_pokemon_right; -}; - - - - - - - -} -} -} -#endif +/* Encounter Detection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterTracker_H +#define PokemonAutomation_PokemonBDSP_EncounterTracker_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonBDSP/Options/EncounterFilter/PokemonBDSP_EncounterFilterOption.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +struct PokemonDetection{ + bool exists = false; + bool detection_enabled = false; + std::set slugs; +}; + + +class StandardEncounterDetection{ +public: + StandardEncounterDetection( + VideoStream& stream, ProControllerContext& context, + Language language, + const EncounterFilterOption2& filter, + const DoublesShinyDetection& shininess, + std::chrono::milliseconds read_name_delay = std::chrono::milliseconds(500) + ); + + bool is_double_battle() const{ return m_double_battle; } + const PokemonDetection& pokemon_left() const; + const PokemonDetection& pokemon_right() const; + + bool has_shiny() const; + ShinyType overall_shininess() const{ return m_shininess.shiny_type; } + ShinyType left_shininess() const{ return m_shininess_left; } + ShinyType right_shininess() const{ return m_shininess_right; } + + EncounterActionFull get_action(); + +private: + std::set read_name(const ImageViewRGB32& screen, const ImageFloatBox& box); + bool run_overrides( + EncounterActionFull& action, + const std::vector>& overrides, + const PokemonDetection& pokemon, ShinyType side_shiny + ) const; + EncounterActionFull get_action_singles(); + EncounterActionFull get_action_doubles(); + +private: + VideoStream& m_stream; + + const Language m_language; + + const EncounterFilterOption2& m_filter; + const DoublesShinyDetection& m_shininess; + + bool m_double_battle = false; + ShinyType m_shininess_left; + ShinyType m_shininess_right; + + PokemonDetection m_pokemon_left; + PokemonDetection m_pokemon_right; +}; + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.cpp index 224e142519..11561884d7 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.cpp @@ -1,331 +1,331 @@ -/* Encounter Handler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP_BasicCatcher.h" -#include "PokemonBDSP_EncounterHandler.h" -#include "PokemonBDSP_GameNavigation.h" -#include "PokemonBDSP_RunFromBattle.h" - -#include -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -void take_video(ProControllerContext& context){ - pbf_wait(context, 5 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); -// context->wait_for_all_requests(); -} - - -StandardEncounterHandler::StandardEncounterHandler( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - Language language, - EncounterBotCommonOptions& settings, - PokemonSwSh::ShinyHuntTracker& session_stats -) - : m_env(env) - , m_context(context) - , m_stream(stream) - , m_language(language) - , m_settings(settings) - , m_session_stats(session_stats) -{} - - - -std::vector get_mon_list(StandardEncounterDetection& encounter){ - std::vector mon_list; - const PokemonDetection& left = encounter.pokemon_left(); - const PokemonDetection& right = encounter.pokemon_right(); - if (left.exists){ - mon_list.emplace_back(left); - } - if (right.exists){ - mon_list.emplace_back(right); - } - return mon_list; -} - -void StandardEncounterHandler::run_away_due_to_error(Milliseconds exit_battle_time){ - pbf_mash_button(m_context, BUTTON_B, 3000ms); - pbf_press_dpad(m_context, DPAD_DOWN, 3000ms, 0ms); - m_context.wait_for_all_requests(); - - run_from_battle(m_stream, m_context, exit_battle_time); -} - -std::vector StandardEncounterHandler::results(StandardEncounterDetection& encounter){ - std::vector ret; - const PokemonDetection& left = encounter.pokemon_left(); - const PokemonDetection& right = encounter.pokemon_right(); - if (left.exists){ - ret.emplace_back(EncounterResult{left.slugs, encounter.left_shininess()}); - } - if (right.exists){ - ret.emplace_back(EncounterResult{right.slugs, encounter.right_shininess()}); - } - return ret; -} -void StandardEncounterHandler::update_frequencies(StandardEncounterDetection& encounter){ - const PokemonDetection& left = encounter.pokemon_left(); - const PokemonDetection& right = encounter.pokemon_right(); - if (!left.detection_enabled && !right.detection_enabled){ - return; - } - if (left.exists){ - m_frequencies += left.slugs; - } - if (right.exists){ - m_frequencies += right.slugs; - } - if (left.exists || right.exists){ - m_env.log(m_frequencies.dump_sorted_map("Encounter Stats:\n")); - } -} - - -bool StandardEncounterHandler::handle_standard_encounter(const DoublesShinyDetection& result){ - if (result.shiny_type == ShinyType::UNKNOWN){ - m_stream.log("Unable to determine result of battle.", COLOR_RED); - m_session_stats.add_error(); - m_consecutive_failures++; - if (m_consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "3 consecutive failed encounter detections.", - m_stream - ); - } - return false; - } - m_consecutive_failures = 0; - - StandardEncounterDetection encounter( - m_stream, m_context, - m_language, - m_settings.FILTER, - result - ); - - m_session_stats += result.shiny_type; - if (encounter.is_double_battle()){ - bool left = is_confirmed_shiny(encounter.left_shininess()); - bool right = is_confirmed_shiny(encounter.right_shininess()); - if (left && right){ - m_session_stats += ShinyType::UNKNOWN_SHINY; - }else{ - m_session_stats += ShinyType::NOT_SHINY; - } - } - m_env.update_stats(); - - if (result.shiny_type == ShinyType::UNKNOWN){ - pbf_mash_button(m_context, BUTTON_B, TICKS_PER_SECOND); - return false; - } - - bool enable_names = m_language != Language::None; - std::vector encounter_results = results(encounter); - - update_frequencies(encounter); - send_encounter_notification( - m_env, - m_settings.NOTIFICATION_NONSHINY, - m_settings.NOTIFICATION_SHINY, - m_language != Language::None, is_likely_shiny(result.shiny_type), - encounter_results, result.alpha, - result.get_best_screenshot(), - enable_names ? &m_frequencies : nullptr - ); - - if (m_settings.VIDEO_ON_SHINY && encounter.has_shiny()){ - take_video(m_context); - } - - return encounter.get_action().action == EncounterAction::StopProgram; -} -bool StandardEncounterHandler::handle_standard_encounter_end_battle( - const DoublesShinyDetection& result, - Milliseconds exit_battle_time -){ - if (result.shiny_type == ShinyType::UNKNOWN){ - m_stream.log("Unable to determine result of battle.", COLOR_RED); - m_session_stats.add_error(); - m_consecutive_failures++; - if (m_consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "3 consecutive failed encounter detections.", - m_stream - ); - } - return false; - } - m_consecutive_failures = 0; - - StandardEncounterDetection encounter( - m_stream, m_context, - m_language, - m_settings.FILTER, - result - ); - - m_session_stats += result.shiny_type; - if (encounter.is_double_battle()){ - bool left = is_confirmed_shiny(encounter.left_shininess()); - bool right = is_confirmed_shiny(encounter.right_shininess()); - if (left && right){ - m_session_stats += ShinyType::UNKNOWN_SHINY; - }else{ - m_session_stats += ShinyType::NOT_SHINY; - } - } - m_env.update_stats(); - - if (m_settings.VIDEO_ON_SHINY && encounter.has_shiny()){ - take_video(m_context); - } - - bool enable_names = m_language != Language::None; - std::vector encounter_results = results(encounter); - std::ostringstream os; - if (encounter_results.size() > 0){ - os << "Pokemon: ("; - bool first_slug = true; - for(const auto& name: encounter_results[0].slug_candidates){ - if (first_slug == false){ - os << ","; - } - os << name; - first_slug = false; - } - os << ")"; - } - if (encounter_results.size() > 1){ - os << "("; - bool first_slug = true; - for(const auto& name: encounter_results[1].slug_candidates){ - if (first_slug == false){ - os << ","; - } - os << name; - first_slug = false; - } - os << ")"; - } - m_stream.overlay().add_log(os.str(), COLOR_WHITE); - - update_frequencies(encounter); - send_encounter_notification( - m_env, - m_settings.NOTIFICATION_NONSHINY, - m_settings.NOTIFICATION_SHINY, - enable_names, is_likely_shiny(result.shiny_type), - encounter_results, result.alpha, - result.get_best_screenshot(), - enable_names ? &m_frequencies : nullptr - ); - - EncounterActionFull action = encounter.get_action(); - switch (action.action){ - case EncounterAction::StopProgram: - return true; - case EncounterAction::RunAway: - // Fast run-away sequence to save time. - pbf_press_dpad(m_context, DPAD_UP, 20, 0); - m_context.wait_for_all_requests(); - - run_from_battle(m_stream, m_context, exit_battle_time); - return false; - - case EncounterAction::ThrowBalls: - case EncounterAction::ThrowBallsAndSave:{ - CatchResults catch_result = basic_catcher( - m_stream, m_context, - m_language, - action.pokeball_slug, - action.ball_limit - ); - send_catch_notification( - m_env, - m_settings.NOTIFICATION_CATCH_SUCCESS, - m_settings.NOTIFICATION_CATCH_FAILED, - &encounter_results[0].slug_candidates, - action.pokeball_slug, - catch_result.balls_used, - catch_result.result - ); - switch (catch_result.result){ - case CatchResult::POKEMON_CAUGHT: - m_session_stats.add_caught(); - m_env.update_stats(); - if (action.action == EncounterAction::ThrowBallsAndSave){ - // Save the game - save_game(m_stream, m_context); - } - break; - case CatchResult::POKEMON_FAINTED: - pbf_mash_button(m_context, BUTTON_B, 2 * TICKS_PER_SECOND); - break; - default: - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to recover from failed catch.", - m_stream - ); - } - return false; - } - default: - return true; - } - - return false; -} - - - - - -LeadingShinyTracker::LeadingShinyTracker(Logger& logger) - : m_logger(logger) - , m_consecutive_shinies(0) -{} - -void LeadingShinyTracker::report_result(ShinyType type){ - if (is_confirmed_shiny(type)){ - m_consecutive_shinies++; -// cout << "own shiny = " << m_consecutive_shinies << endl; - if (m_consecutive_shinies >= 3){ - throw UserSetupError(m_logger, "Don't use a shiny as your lead. It causes false positive detections."); - } - }else{ - m_consecutive_shinies = 0; - } -} - - - - - - - - -} -} -} +/* Encounter Handler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_BasicCatcher.h" +#include "PokemonBDSP_EncounterHandler.h" +#include "PokemonBDSP_GameNavigation.h" +#include "PokemonBDSP_RunFromBattle.h" + +#include +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +void take_video(ProControllerContext& context){ + pbf_wait(context, 5 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); +// context->wait_for_all_requests(); +} + + +StandardEncounterHandler::StandardEncounterHandler( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + Language language, + EncounterBotCommonOptions& settings, + PokemonSwSh::ShinyHuntTracker& session_stats +) + : m_env(env) + , m_context(context) + , m_stream(stream) + , m_language(language) + , m_settings(settings) + , m_session_stats(session_stats) +{} + + + +std::vector get_mon_list(StandardEncounterDetection& encounter){ + std::vector mon_list; + const PokemonDetection& left = encounter.pokemon_left(); + const PokemonDetection& right = encounter.pokemon_right(); + if (left.exists){ + mon_list.emplace_back(left); + } + if (right.exists){ + mon_list.emplace_back(right); + } + return mon_list; +} + +void StandardEncounterHandler::run_away_due_to_error(Milliseconds exit_battle_time){ + pbf_mash_button(m_context, BUTTON_B, 3000ms); + pbf_press_dpad(m_context, DPAD_DOWN, 3000ms, 0ms); + m_context.wait_for_all_requests(); + + run_from_battle(m_stream, m_context, exit_battle_time); +} + +std::vector StandardEncounterHandler::results(StandardEncounterDetection& encounter){ + std::vector ret; + const PokemonDetection& left = encounter.pokemon_left(); + const PokemonDetection& right = encounter.pokemon_right(); + if (left.exists){ + ret.emplace_back(EncounterResult{left.slugs, encounter.left_shininess()}); + } + if (right.exists){ + ret.emplace_back(EncounterResult{right.slugs, encounter.right_shininess()}); + } + return ret; +} +void StandardEncounterHandler::update_frequencies(StandardEncounterDetection& encounter){ + const PokemonDetection& left = encounter.pokemon_left(); + const PokemonDetection& right = encounter.pokemon_right(); + if (!left.detection_enabled && !right.detection_enabled){ + return; + } + if (left.exists){ + m_frequencies += left.slugs; + } + if (right.exists){ + m_frequencies += right.slugs; + } + if (left.exists || right.exists){ + m_env.log(m_frequencies.dump_sorted_map("Encounter Stats:\n")); + } +} + + +bool StandardEncounterHandler::handle_standard_encounter(const DoublesShinyDetection& result){ + if (result.shiny_type == ShinyType::UNKNOWN){ + m_stream.log("Unable to determine result of battle.", COLOR_RED); + m_session_stats.add_error(); + m_consecutive_failures++; + if (m_consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "3 consecutive failed encounter detections.", + m_stream + ); + } + return false; + } + m_consecutive_failures = 0; + + StandardEncounterDetection encounter( + m_stream, m_context, + m_language, + m_settings.FILTER, + result + ); + + m_session_stats += result.shiny_type; + if (encounter.is_double_battle()){ + bool left = is_confirmed_shiny(encounter.left_shininess()); + bool right = is_confirmed_shiny(encounter.right_shininess()); + if (left && right){ + m_session_stats += ShinyType::UNKNOWN_SHINY; + }else{ + m_session_stats += ShinyType::NOT_SHINY; + } + } + m_env.update_stats(); + + if (result.shiny_type == ShinyType::UNKNOWN){ + pbf_mash_button(m_context, BUTTON_B, TICKS_PER_SECOND); + return false; + } + + bool enable_names = m_language != Language::None; + std::vector encounter_results = results(encounter); + + update_frequencies(encounter); + send_encounter_notification( + m_env, + m_settings.NOTIFICATION_NONSHINY, + m_settings.NOTIFICATION_SHINY, + m_language != Language::None, is_likely_shiny(result.shiny_type), + encounter_results, result.alpha, + result.get_best_screenshot(), + enable_names ? &m_frequencies : nullptr + ); + + if (m_settings.VIDEO_ON_SHINY && encounter.has_shiny()){ + take_video(m_context); + } + + return encounter.get_action().action == EncounterAction::StopProgram; +} +bool StandardEncounterHandler::handle_standard_encounter_end_battle( + const DoublesShinyDetection& result, + Milliseconds exit_battle_time +){ + if (result.shiny_type == ShinyType::UNKNOWN){ + m_stream.log("Unable to determine result of battle.", COLOR_RED); + m_session_stats.add_error(); + m_consecutive_failures++; + if (m_consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "3 consecutive failed encounter detections.", + m_stream + ); + } + return false; + } + m_consecutive_failures = 0; + + StandardEncounterDetection encounter( + m_stream, m_context, + m_language, + m_settings.FILTER, + result + ); + + m_session_stats += result.shiny_type; + if (encounter.is_double_battle()){ + bool left = is_confirmed_shiny(encounter.left_shininess()); + bool right = is_confirmed_shiny(encounter.right_shininess()); + if (left && right){ + m_session_stats += ShinyType::UNKNOWN_SHINY; + }else{ + m_session_stats += ShinyType::NOT_SHINY; + } + } + m_env.update_stats(); + + if (m_settings.VIDEO_ON_SHINY && encounter.has_shiny()){ + take_video(m_context); + } + + bool enable_names = m_language != Language::None; + std::vector encounter_results = results(encounter); + std::ostringstream os; + if (encounter_results.size() > 0){ + os << "Pokemon: ("; + bool first_slug = true; + for(const auto& name: encounter_results[0].slug_candidates){ + if (first_slug == false){ + os << ","; + } + os << name; + first_slug = false; + } + os << ")"; + } + if (encounter_results.size() > 1){ + os << "("; + bool first_slug = true; + for(const auto& name: encounter_results[1].slug_candidates){ + if (first_slug == false){ + os << ","; + } + os << name; + first_slug = false; + } + os << ")"; + } + m_stream.overlay().add_log(os.str(), COLOR_WHITE); + + update_frequencies(encounter); + send_encounter_notification( + m_env, + m_settings.NOTIFICATION_NONSHINY, + m_settings.NOTIFICATION_SHINY, + enable_names, is_likely_shiny(result.shiny_type), + encounter_results, result.alpha, + result.get_best_screenshot(), + enable_names ? &m_frequencies : nullptr + ); + + EncounterActionFull action = encounter.get_action(); + switch (action.action){ + case EncounterAction::StopProgram: + return true; + case EncounterAction::RunAway: + // Fast run-away sequence to save time. + pbf_press_dpad(m_context, DPAD_UP, 20, 0); + m_context.wait_for_all_requests(); + + run_from_battle(m_stream, m_context, exit_battle_time); + return false; + + case EncounterAction::ThrowBalls: + case EncounterAction::ThrowBallsAndSave:{ + CatchResults catch_result = basic_catcher( + m_stream, m_context, + m_language, + action.pokeball_slug, + action.ball_limit + ); + send_catch_notification( + m_env, + m_settings.NOTIFICATION_CATCH_SUCCESS, + m_settings.NOTIFICATION_CATCH_FAILED, + &encounter_results[0].slug_candidates, + action.pokeball_slug, + catch_result.balls_used, + catch_result.result + ); + switch (catch_result.result){ + case CatchResult::POKEMON_CAUGHT: + m_session_stats.add_caught(); + m_env.update_stats(); + if (action.action == EncounterAction::ThrowBallsAndSave){ + // Save the game + save_game(m_stream, m_context); + } + break; + case CatchResult::POKEMON_FAINTED: + pbf_mash_button(m_context, BUTTON_B, 2 * TICKS_PER_SECOND); + break; + default: + throw_and_log( + m_stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to recover from failed catch.", + m_stream + ); + } + return false; + } + default: + return true; + } + + return false; +} + + + + + +LeadingShinyTracker::LeadingShinyTracker(Logger& logger) + : m_logger(logger) + , m_consecutive_shinies(0) +{} + +void LeadingShinyTracker::report_result(ShinyType type){ + if (is_confirmed_shiny(type)){ + m_consecutive_shinies++; +// cout << "own shiny = " << m_consecutive_shinies << endl; + if (m_consecutive_shinies >= 3){ + throw UserSetupError(m_logger, "Don't use a shiny as your lead. It causes false positive detections."); + } + }else{ + m_consecutive_shinies = 0; + } +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h index 1b547479e9..c2a644d262 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h @@ -1,98 +1,98 @@ -/* Encounter Handler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_EncounterHandler_H -#define PokemonAutomation_PokemonBDSP_EncounterHandler_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Handle wild encounters using feedback. -class StandardEncounterHandler{ -public: - StandardEncounterHandler( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - Language language, - EncounterBotCommonOptions& settings, - PokemonSwSh::ShinyHuntTracker& session_stats - ); - - // Run away sequence for unexpected battle. - // Must be called during a battle. Hit "Run" and go through the dialogue until - // end of battle is detected. - // The pokemon must be able to run successfully with no trapping or run away failure. - // - // exit_battle_time: number of ticks to wait for battle ends after pressing "Run" button. - // If end of battle not detected in time, log the error but don't throw exception. - void run_away_due_to_error(Milliseconds exit_battle_time); - - // Use shiny detection result and inference of pokemon species to determine whether - // to stop the program according to the user setting. - // Return true if program should stop. - bool handle_standard_encounter(const DoublesShinyDetection& result); - // Use shiny detection result and inference of pokemon species to determine whether - // to stop the program, run away from battle or catch the pokemon according to the user - // setting. - // Return true if program should stop. - bool handle_standard_encounter_end_battle(const DoublesShinyDetection& result, Milliseconds exit_battle_time); - - -private: - std::vector results(StandardEncounterDetection& encounter); - // Record the types of pokemon encountered into encounter stats. - // The stats are then logged. - void update_frequencies(StandardEncounterDetection& encounter); - -private: - ProgramEnvironment& m_env; - ProControllerContext& m_context; - VideoStream& m_stream; - const Language m_language; - EncounterBotCommonOptions& m_settings; - - EncounterFrequencies m_frequencies; - PokemonSwSh::ShinyHuntTracker& m_session_stats; - size_t m_consecutive_failures = 0; -}; - - -void take_video(ProControllerContext& context); -void run_away( - ProgramEnvironment& env, - VideoStream& stream, - Milliseconds exit_battle_time -); - - - -class LeadingShinyTracker{ -public: - LeadingShinyTracker(Logger& logger); - - void report_result(ShinyType type); - -private: - Logger& m_logger; - size_t m_consecutive_shinies; -}; - - - - -} -} -} -#endif +/* Encounter Handler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_EncounterHandler_H +#define PokemonAutomation_PokemonBDSP_EncounterHandler_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_EncounterDetection.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Handle wild encounters using feedback. +class StandardEncounterHandler{ +public: + StandardEncounterHandler( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + Language language, + EncounterBotCommonOptions& settings, + PokemonSwSh::ShinyHuntTracker& session_stats + ); + + // Run away sequence for unexpected battle. + // Must be called during a battle. Hit "Run" and go through the dialogue until + // end of battle is detected. + // The pokemon must be able to run successfully with no trapping or run away failure. + // + // exit_battle_time: number of ticks to wait for battle ends after pressing "Run" button. + // If end of battle not detected in time, log the error but don't throw exception. + void run_away_due_to_error(Milliseconds exit_battle_time); + + // Use shiny detection result and inference of pokemon species to determine whether + // to stop the program according to the user setting. + // Return true if program should stop. + bool handle_standard_encounter(const DoublesShinyDetection& result); + // Use shiny detection result and inference of pokemon species to determine whether + // to stop the program, run away from battle or catch the pokemon according to the user + // setting. + // Return true if program should stop. + bool handle_standard_encounter_end_battle(const DoublesShinyDetection& result, Milliseconds exit_battle_time); + + +private: + std::vector results(StandardEncounterDetection& encounter); + // Record the types of pokemon encountered into encounter stats. + // The stats are then logged. + void update_frequencies(StandardEncounterDetection& encounter); + +private: + ProgramEnvironment& m_env; + ProControllerContext& m_context; + VideoStream& m_stream; + const Language m_language; + EncounterBotCommonOptions& m_settings; + + EncounterFrequencies m_frequencies; + PokemonSwSh::ShinyHuntTracker& m_session_stats; + size_t m_consecutive_failures = 0; +}; + + +void take_video(ProControllerContext& context); +void run_away( + ProgramEnvironment& env, + VideoStream& stream, + Milliseconds exit_battle_time +); + + + +class LeadingShinyTracker{ +public: + LeadingShinyTracker(Logger& logger); + + void report_result(ShinyType type); + +private: + Logger& m_logger; + size_t m_consecutive_shinies; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.cpp index 29763aa68e..0a8af1daa3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.cpp @@ -1,109 +1,109 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_GameEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -bool gamemenu_to_ingame( - VideoStream& stream, ProControllerContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -){ - stream.log("Mashing A to enter game..."); - BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); - pbf_mash_button(context, BUTTON_ZL, mash_duration); - context.wait_for_all_requests(); - stream.log("Waiting to enter game..."); - int ret = wait_until( - stream, context, - std::chrono::milliseconds(enter_game_timeout * (1000 / TICKS_PER_SECOND)), - {{detector}} - ); - if (ret == 0){ - stream.log("Entered game!"); - return true; - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } -} -bool openedgame_to_ingame( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - Milliseconds load_game_timeout, - Milliseconds mash_duration, Milliseconds enter_game_timeout, - Milliseconds post_wait_time -){ - bool ok = true; - ok &= openedgame_to_gamemenu(stream, context, load_game_timeout); - ok &= gamemenu_to_ingame(stream, context, mash_duration, enter_game_timeout); - if (!ok){ - dump_image(stream.logger(), env.program_info(), stream.video(), "StartGame"); - } - stream.log("Entered game! Waiting out grace period."); - pbf_wait(context, post_wait_time); - context.wait_for_all_requests(); - return ok; -} - - - - -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - Milliseconds post_wait_time -){ - bool video_available = (bool)console.video().snapshot(); - if (video_available || - ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || - tolerate_update_menu - ){ - close_game(console, context); - start_game_from_home( - console, - context, - tolerate_update_menu, - 0, 0, - GameSettings::instance().START_GAME_MASH0 - ); - }else{ - pbf_press_button(context, BUTTON_X, 50, 0); - pbf_mash_button(context, BUTTON_A, GameSettings::instance().START_GAME_MASH0); - } - bool ret = openedgame_to_ingame( - env, console, context, - GameSettings::instance().START_GAME_WAIT0, - GameSettings::instance().ENTER_GAME_MASH0, - GameSettings::instance().ENTER_GAME_WAIT0, - post_wait_time - ); - context.wait_for_all_requests(); - return ret; -} - - - -} -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_GameEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +bool gamemenu_to_ingame( + VideoStream& stream, ProControllerContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +){ + stream.log("Mashing A to enter game..."); + BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); + pbf_mash_button(context, BUTTON_ZL, mash_duration); + context.wait_for_all_requests(); + stream.log("Waiting to enter game..."); + int ret = wait_until( + stream, context, + std::chrono::milliseconds(enter_game_timeout * (1000 / TICKS_PER_SECOND)), + {{detector}} + ); + if (ret == 0){ + stream.log("Entered game!"); + return true; + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } +} +bool openedgame_to_ingame( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + Milliseconds load_game_timeout, + Milliseconds mash_duration, Milliseconds enter_game_timeout, + Milliseconds post_wait_time +){ + bool ok = true; + ok &= openedgame_to_gamemenu(stream, context, load_game_timeout); + ok &= gamemenu_to_ingame(stream, context, mash_duration, enter_game_timeout); + if (!ok){ + dump_image(stream.logger(), env.program_info(), stream.video(), "StartGame"); + } + stream.log("Entered game! Waiting out grace period."); + pbf_wait(context, post_wait_time); + context.wait_for_all_requests(); + return ok; +} + + + + +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + Milliseconds post_wait_time +){ + bool video_available = (bool)console.video().snapshot(); + if (video_available || + ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || + tolerate_update_menu + ){ + close_game(console, context); + start_game_from_home( + console, + context, + tolerate_update_menu, + 0, 0, + GameSettings::instance().START_GAME_MASH0 + ); + }else{ + pbf_press_button(context, BUTTON_X, 50, 0); + pbf_mash_button(context, BUTTON_A, GameSettings::instance().START_GAME_MASH0); + } + bool ret = openedgame_to_ingame( + env, console, context, + GameSettings::instance().START_GAME_WAIT0, + GameSettings::instance().ENTER_GAME_MASH0, + GameSettings::instance().ENTER_GAME_WAIT0, + post_wait_time + ); + context.wait_for_all_requests(); + return ret; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.h index a892c42c4a..a44cdcfc91 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameEntry.h @@ -1,44 +1,44 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_GameEntry_H -#define PokemonAutomation_PokemonBDSP_GameEntry_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace std::chrono_literals; - - -bool gamemenu_to_ingame( - VideoStream& stream, ProControllerContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -); -bool openedgame_to_ingame( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - Milliseconds load_game_timeout, - Milliseconds mash_duration, Milliseconds enter_game_timeout, - Milliseconds post_wait_time = 1000ms -); -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - Milliseconds post_wait_time = 1000ms -); - - - -} -} -} -#endif +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_GameEntry_H +#define PokemonAutomation_PokemonBDSP_GameEntry_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace std::chrono_literals; + + +bool gamemenu_to_ingame( + VideoStream& stream, ProControllerContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +); +bool openedgame_to_ingame( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + Milliseconds load_game_timeout, + Milliseconds mash_duration, Milliseconds enter_game_timeout, + Milliseconds post_wait_time = 1000ms +); +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + Milliseconds post_wait_time = 1000ms +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.cpp index e9ffbd17cb..c319715d24 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.cpp @@ -1,166 +1,166 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" -#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h" -#include "PokemonBDSP_GameNavigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -// Non-Feedback - -void save_game(ProControllerContext& context){ - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 80ms, 2000ms); - pbf_press_button(context, BUTTON_ZL, 80ms, 5000ms); -} -void menu_to_box(ProControllerContext& context){ - Milliseconds MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY0; - pbf_mash_button(context, BUTTON_ZL, 30); - if (MENU_TO_POKEMON_DELAY > 240ms){ - pbf_wait(context, MENU_TO_POKEMON_DELAY - 240ms); - } - - pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().POKEMON_TO_BOX_DELAY1); -} -void overworld_to_box(ProControllerContext& context){ - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); -// pbf_press_button(context, BUTTON_ZL, 160ms, GameSettings::instance().MENU_TO_POKEMON_DELAY); - - menu_to_box(context); -} -void box_to_overworld(ProControllerContext& context){ - // There are two states here which need to be merged: - // 1. The depositing column was empty. The party has been swapped and - // it's sitting in the box with no held pokemon. - // 2. The depositing column was not empty. The party swap failed and - // it's sitting in the box holding on the party pokemon. - // - // Double press B quickly here to back out of the box. - // In state (1): The 1st B will begin back out of the box. The 2nd B will - // be swallowed by the animation. - // In state (2): The 1st B will drop the party pokemon. The 2nd B will - // back out of the box. - - pbf_press_button(context, BUTTON_B, 20, 30); - pbf_press_button(context, BUTTON_B, 160ms, GameSettings::instance().BOX_TO_POKEMON_DELAY0); - - pbf_press_button(context, BUTTON_B, 160ms, GameSettings::instance().POKEMON_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0); -} - - - -// Feedback - -void overworld_to_menu(VideoStream& stream, ProControllerContext& context){ - pbf_press_button(context, BUTTON_X, 20, 105); - context.wait_for_all_requests(); - { - MenuWatcher detector; - int ret = wait_until( - stream, context, std::chrono::seconds(10), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Menu not detected after 10 seconds.", - stream - ); - } - stream.log("Detected menu."); - } - context.wait_for(std::chrono::milliseconds(100)); -} - -void save_game(VideoStream& stream, ProControllerContext& context){ - overworld_to_menu(stream, context); - pbf_press_button(context, BUTTON_R, 10, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_ZL, 10, 5 * TICKS_PER_SECOND); -} - -void overworld_to_box(VideoStream& stream, ProControllerContext& context){ - // Open menu. - overworld_to_menu(stream, context); - - // Enter Pokemon - Milliseconds MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY0; - pbf_press_button(context, BUTTON_ZL, 160ms, MENU_TO_POKEMON_DELAY); - - // Enter box system. - pbf_press_button(context, BUTTON_R, 20, 105); - context.wait_for_all_requests(); - { - BoxWatcher detector; - int ret = wait_until( - stream, context, std::chrono::seconds(10), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Box system not detected after 10 seconds.", - stream - ); - } - stream.log("Detected box system."); - } - context.wait_for(std::chrono::milliseconds(500)); -} -void box_to_overworld(VideoStream& stream, ProControllerContext& context){ - // There are two states here which need to be merged: - // 1. The depositing column was empty. The party has been swapped and - // it's sitting in the box with no held pokemon. - // 2. The depositing column was not empty. The party swap failed and - // it's sitting in the box holding on the party pokemon. - // - // Double press B quickly here to back out of the box. - // In state (1): The 1st B will begin back out of the box. The 2nd B will - // be swallowed by the animation. - // In state (2): The 1st B will drop the party pokemon. The 2nd B will - // back out of the box. - pbf_press_button(context, BUTTON_B, 20, 30); - pbf_press_button(context, BUTTON_B, 160ms, GameSettings::instance().BOX_TO_POKEMON_DELAY0); - - // To menu. - pbf_press_button(context, BUTTON_B, 20, 105); - context.wait_for_all_requests(); - { - MenuWatcher detector; - int ret = wait_until( - stream, context, std::chrono::seconds(10), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Menu not detected after 10 seconds.", - stream - ); - } - stream.log("Detected menu."); - } - - // To overworld. - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0); -} - - - - - -} -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MenuDetector.h" +#include "PokemonBDSP/Inference/BoxSystem/PokemonBDSP_BoxDetector.h" +#include "PokemonBDSP_GameNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +// Non-Feedback + +void save_game(ProControllerContext& context){ + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 80ms, 2000ms); + pbf_press_button(context, BUTTON_ZL, 80ms, 5000ms); +} +void menu_to_box(ProControllerContext& context){ + Milliseconds MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY0; + pbf_mash_button(context, BUTTON_ZL, 30); + if (MENU_TO_POKEMON_DELAY > 240ms){ + pbf_wait(context, MENU_TO_POKEMON_DELAY - 240ms); + } + + pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().POKEMON_TO_BOX_DELAY1); +} +void overworld_to_box(ProControllerContext& context){ + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); +// pbf_press_button(context, BUTTON_ZL, 160ms, GameSettings::instance().MENU_TO_POKEMON_DELAY); + + menu_to_box(context); +} +void box_to_overworld(ProControllerContext& context){ + // There are two states here which need to be merged: + // 1. The depositing column was empty. The party has been swapped and + // it's sitting in the box with no held pokemon. + // 2. The depositing column was not empty. The party swap failed and + // it's sitting in the box holding on the party pokemon. + // + // Double press B quickly here to back out of the box. + // In state (1): The 1st B will begin back out of the box. The 2nd B will + // be swallowed by the animation. + // In state (2): The 1st B will drop the party pokemon. The 2nd B will + // back out of the box. + + pbf_press_button(context, BUTTON_B, 20, 30); + pbf_press_button(context, BUTTON_B, 160ms, GameSettings::instance().BOX_TO_POKEMON_DELAY0); + + pbf_press_button(context, BUTTON_B, 160ms, GameSettings::instance().POKEMON_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0); +} + + + +// Feedback + +void overworld_to_menu(VideoStream& stream, ProControllerContext& context){ + pbf_press_button(context, BUTTON_X, 20, 105); + context.wait_for_all_requests(); + { + MenuWatcher detector; + int ret = wait_until( + stream, context, std::chrono::seconds(10), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Menu not detected after 10 seconds.", + stream + ); + } + stream.log("Detected menu."); + } + context.wait_for(std::chrono::milliseconds(100)); +} + +void save_game(VideoStream& stream, ProControllerContext& context){ + overworld_to_menu(stream, context); + pbf_press_button(context, BUTTON_R, 10, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_ZL, 10, 5 * TICKS_PER_SECOND); +} + +void overworld_to_box(VideoStream& stream, ProControllerContext& context){ + // Open menu. + overworld_to_menu(stream, context); + + // Enter Pokemon + Milliseconds MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY0; + pbf_press_button(context, BUTTON_ZL, 160ms, MENU_TO_POKEMON_DELAY); + + // Enter box system. + pbf_press_button(context, BUTTON_R, 20, 105); + context.wait_for_all_requests(); + { + BoxWatcher detector; + int ret = wait_until( + stream, context, std::chrono::seconds(10), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Box system not detected after 10 seconds.", + stream + ); + } + stream.log("Detected box system."); + } + context.wait_for(std::chrono::milliseconds(500)); +} +void box_to_overworld(VideoStream& stream, ProControllerContext& context){ + // There are two states here which need to be merged: + // 1. The depositing column was empty. The party has been swapped and + // it's sitting in the box with no held pokemon. + // 2. The depositing column was not empty. The party swap failed and + // it's sitting in the box holding on the party pokemon. + // + // Double press B quickly here to back out of the box. + // In state (1): The 1st B will begin back out of the box. The 2nd B will + // be swallowed by the animation. + // In state (2): The 1st B will drop the party pokemon. The 2nd B will + // back out of the box. + pbf_press_button(context, BUTTON_B, 20, 30); + pbf_press_button(context, BUTTON_B, 160ms, GameSettings::instance().BOX_TO_POKEMON_DELAY0); + + // To menu. + pbf_press_button(context, BUTTON_B, 20, 105); + context.wait_for_all_requests(); + { + MenuWatcher detector; + int ret = wait_until( + stream, context, std::chrono::seconds(10), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Menu not detected after 10 seconds.", + stream + ); + } + stream.log("Detected menu."); + } + + // To overworld. + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h index 174622d669..2621be03f1 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GameNavigation.h @@ -1,39 +1,39 @@ -/* Game Navigation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_GameNavigation_H -#define PokemonAutomation_PokemonBDSP_GameNavigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Non-Feedback - -void save_game(ProControllerContext& context); - -void menu_to_box(ProControllerContext& context); -void overworld_to_box(ProControllerContext& context); -void box_to_overworld(ProControllerContext& context); - - -// Feedback - -void overworld_to_menu(VideoStream& stream, ProControllerContext& context); -void save_game(VideoStream& stream, ProControllerContext& context); - -void overworld_to_box(VideoStream& stream, ProControllerContext& context); -void box_to_overworld(VideoStream& stream, ProControllerContext& context); - - -} -} -} -#endif +/* Game Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_GameNavigation_H +#define PokemonAutomation_PokemonBDSP_GameNavigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Non-Feedback + +void save_game(ProControllerContext& context); + +void menu_to_box(ProControllerContext& context); +void overworld_to_box(ProControllerContext& context); +void box_to_overworld(ProControllerContext& context); + + +// Feedback + +void overworld_to_menu(VideoStream& stream, ProControllerContext& context); +void save_game(VideoStream& stream, ProControllerContext& context); + +void overworld_to_box(VideoStream& stream, ProControllerContext& context); +void box_to_overworld(VideoStream& stream, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.cpp index b4a88255b0..c5ba314f9d 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.cpp @@ -1,63 +1,63 @@ -/* Heal the party using Global Room - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" -#include "PokemonBDSP_GlobalRoomHeal.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -bool heal_by_global_room(VideoStream& stream, ProControllerContext& context){ - stream.overlay().add_log("Heal by Global Room", COLOR_WHITE); - // Go to union room menu. - const uint16_t overworld_to_room_delay = 125; - pbf_press_button(context, BUTTON_Y, 10, overworld_to_room_delay); - - // Go to global room. - pbf_press_dpad(context, DPAD_RIGHT, 10, 100); - - // Press ZL until we are at: - // - "Would you like to enter the Global Room?" To select: "Yes" and other options. - SelectionArrowFinder arrow(stream.overlay(), {0.50, 0.45, 0.20, 0.20}, COLOR_GREEN); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (int i = 0; i < 5; i++){ - pbf_press_button(context, BUTTON_ZL, 10, 125); - } - }, - {{arrow}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No selection arrow detected when using Global Room.", - stream - ); - } - - // Select "Yes" - pbf_press_button(context, BUTTON_ZL, 10, 125); - - // Then mash B to leave Union Room - pbf_mash_button(context, BUTTON_B, 400); - - context.wait_for_all_requests(); - stream.overlay().add_log("Heal complete", COLOR_WHITE); - return true; -} - - - -} -} -} +/* Heal the party using Global Room + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP_GlobalRoomHeal.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +bool heal_by_global_room(VideoStream& stream, ProControllerContext& context){ + stream.overlay().add_log("Heal by Global Room", COLOR_WHITE); + // Go to union room menu. + const uint16_t overworld_to_room_delay = 125; + pbf_press_button(context, BUTTON_Y, 10, overworld_to_room_delay); + + // Go to global room. + pbf_press_dpad(context, DPAD_RIGHT, 10, 100); + + // Press ZL until we are at: + // - "Would you like to enter the Global Room?" To select: "Yes" and other options. + SelectionArrowFinder arrow(stream.overlay(), {0.50, 0.45, 0.20, 0.20}, COLOR_GREEN); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (int i = 0; i < 5; i++){ + pbf_press_button(context, BUTTON_ZL, 10, 125); + } + }, + {{arrow}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No selection arrow detected when using Global Room.", + stream + ); + } + + // Select "Yes" + pbf_press_button(context, BUTTON_ZL, 10, 125); + + // Then mash B to leave Union Room + pbf_mash_button(context, BUTTON_B, 400); + + context.wait_for_all_requests(); + stream.overlay().add_log("Heal complete", COLOR_WHITE); + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h index faff482dbe..514d33d65f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_GlobalRoomHeal.h @@ -1,26 +1,26 @@ -/* Heal the party using Global Room - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_GlobalRoomHeal_H -#define PokemonAutomation_PokemonBDSP_GlobalRoomHeal_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -// Use Global Room to heal the party. -// Must start at overworld and have Y-shotcut to Global Room unlocked. -bool heal_by_global_room(VideoStream& stream, ProControllerContext& context); - - -} -} -} -#endif +/* Heal the party using Global Room + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_GlobalRoomHeal_H +#define PokemonAutomation_PokemonBDSP_GlobalRoomHeal_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +// Use Global Room to heal the party. +// Must start at overworld and have Y-shotcut to Global Room unlocked. +bool heal_by_global_room(VideoStream& stream, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.cpp index 4ac9d17fc5..95bd96a0e3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.cpp @@ -1,191 +1,191 @@ -/* Overworld Trigger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" -#include "PokemonBDSP_OverworldTrigger.h" -#include "PokemonBDSP_GameNavigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -OverworldTrigger::OverworldTrigger() - : GroupOption("Trigger Method", LockMode::LOCK_WHILE_RUNNING) - , TRIGGER_METHOD( - "Maneuver:
How to trigger an encounter", - { - {TriggerMethod::HORIZONTAL_NO_BIAS, "horizontal-none", "Move left/right. (no bias)"}, - {TriggerMethod::HORIZONTAL_BIAS_LEFT, "horizontal-left", "Move left/right. (bias left)"}, - {TriggerMethod::HORIZONTAL_BIAS_RIGHT, "horizontal-right", "Move left/right. (bias right)"}, - {TriggerMethod::VERTICAL_NO_BIAS, "vertical-none", "Move up/down. (no bias)"}, - {TriggerMethod::VERTICAL_BIAS_UP, "vertical-up", "Move up/down. (bias up)"}, - {TriggerMethod::VERTICAL_BIAS_DOWN, "vertical-down", "Move up/down. (bias down)"}, - {TriggerMethod::SWEET_SCENT, "sweet-scent", "Sweet scent"}, - }, - LockMode::LOCK_WHILE_RUNNING, - TriggerMethod::HORIZONTAL_NO_BIAS - ) - , MOVE_DURATION0( - "Move Duration:
Move in each direction for this long before turning around.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , SWEET_SCENT_POKEMON_LOCATION( - "Sweet Scent Pokemon Location:
Which Pokemon in the party knows Sweet Scent.", - { - {0, "slot1", "1st"}, - {1, "slot2", "2nd"}, - {2, "slot3", "3rd"}, - {3, "slot4", "4th"}, - {4, "slot5", "2nd last"}, - {5, "slot6", "Last"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) -{ - PA_ADD_OPTION(TRIGGER_METHOD); - PA_ADD_OPTION(MOVE_DURATION0); - PA_ADD_OPTION(SWEET_SCENT_POKEMON_LOCATION); -} - - -void OverworldTrigger::run_trigger(ProControllerContext& context) const{ - Milliseconds normal_duration = MOVE_DURATION0; - Milliseconds biased_duration = MOVE_DURATION0.get() + 200ms; - Milliseconds mash_duration = normal_duration - 64ms; - switch (TRIGGER_METHOD){ - case TriggerMethod::HORIZONTAL_NO_BIAS: - ssf_press_left_joystick(context, 0, 128, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - ssf_press_left_joystick(context, 255, 128, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - break; - case TriggerMethod::HORIZONTAL_BIAS_LEFT: - ssf_press_left_joystick(context, 0, 128, 0ms, biased_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - ssf_press_left_joystick(context, 255, 128, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - break; - case TriggerMethod::HORIZONTAL_BIAS_RIGHT: - ssf_press_left_joystick(context, 255, 128, 0ms, biased_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - ssf_press_left_joystick(context, 0, 128, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - break; - case TriggerMethod::VERTICAL_NO_BIAS: - ssf_press_left_joystick(context, 128, 0, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - ssf_press_left_joystick(context, 128, 255, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - break; - case TriggerMethod::VERTICAL_BIAS_UP: - ssf_press_left_joystick(context, 128, 0, 0ms, biased_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - ssf_press_left_joystick(context, 128, 255, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - break; - case TriggerMethod::VERTICAL_BIAS_DOWN: - ssf_press_left_joystick(context, 128, 255, 0ms, biased_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - ssf_press_left_joystick(context, 128, 0, 0ms, normal_duration); - ssf_mash1_button(context, BUTTON_B, mash_duration); - break; - default:; - } -} - -bool OverworldTrigger::find_encounter(VideoStream& stream, ProControllerContext& context) const{ - BattleMenuWatcher battle_menu_detector(BattleType::STANDARD); - StartBattleDetector start_battle_detector(stream.overlay()); - - int ret = 0; - if (TRIGGER_METHOD != TriggerMethod::SWEET_SCENT){ - // Move character back and forth to trigger encounter. - ret = run_until( - stream, context, - [&](ProControllerContext& context){ - while (true){ - run_trigger(context); - } - }, - { - {battle_menu_detector}, - {start_battle_detector}, - } - ); - }else{ - stream.overlay().add_log("Using Sweet Scent", COLOR_CYAN); - // Use Sweet Scent to trigger encounter. - overworld_to_menu(stream, context); - - // Go to pokemon page - const Milliseconds MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY0; - pbf_press_button(context, BUTTON_ZL, 160ms, MENU_TO_POKEMON_DELAY); - - // Go to the pokemon that knows Sweet Scent - const size_t location = SWEET_SCENT_POKEMON_LOCATION.current_value(); - const uint16_t change_pokemon_delay = 20; - if (location >= 1 && location <= 3){ - const size_t move_down_times = location; - for(size_t i = 0; i < move_down_times; ++i){ - pbf_press_dpad(context, DPAD_DOWN, 20, change_pokemon_delay); - } - }else if (location >= 1){ // for location 4 and 5 - const size_t move_down_times = 6 - location; - for (size_t i = 0; i < move_down_times; ++i){ - pbf_press_dpad(context, DPAD_UP, 20, change_pokemon_delay); - } - } - - // Open the pokemon menu of the selected pokemon - const uint16_t pokemon_to_pokemon_menu_delay = 30; - pbf_press_button(context, BUTTON_ZL, 20, pokemon_to_pokemon_menu_delay); - // Move down one menuitem to select "Sweet Scent" - const uint16_t move_pokemon_menu_item_delay = 30; - pbf_press_dpad(context, DPAD_DOWN, 20, move_pokemon_menu_item_delay); - // Use sweet scent - pbf_mash_button(context, BUTTON_ZL, 30); - - ret = wait_until( - stream, context, std::chrono::seconds(30), - { - {battle_menu_detector}, - {start_battle_detector}, - } - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Battle not detected after Sweet Scent for 30 seconds.", - stream - ); - } - } - - switch (ret){ - case 0: - stream.log("Unexpected Battle.", COLOR_RED); - return false; - case 1: - stream.log("Battle started!"); - return true; - } - return false; -} - - -} -} -} +/* Overworld Trigger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" +#include "PokemonBDSP_OverworldTrigger.h" +#include "PokemonBDSP_GameNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +OverworldTrigger::OverworldTrigger() + : GroupOption("Trigger Method", LockMode::LOCK_WHILE_RUNNING) + , TRIGGER_METHOD( + "Maneuver:
How to trigger an encounter", + { + {TriggerMethod::HORIZONTAL_NO_BIAS, "horizontal-none", "Move left/right. (no bias)"}, + {TriggerMethod::HORIZONTAL_BIAS_LEFT, "horizontal-left", "Move left/right. (bias left)"}, + {TriggerMethod::HORIZONTAL_BIAS_RIGHT, "horizontal-right", "Move left/right. (bias right)"}, + {TriggerMethod::VERTICAL_NO_BIAS, "vertical-none", "Move up/down. (no bias)"}, + {TriggerMethod::VERTICAL_BIAS_UP, "vertical-up", "Move up/down. (bias up)"}, + {TriggerMethod::VERTICAL_BIAS_DOWN, "vertical-down", "Move up/down. (bias down)"}, + {TriggerMethod::SWEET_SCENT, "sweet-scent", "Sweet scent"}, + }, + LockMode::LOCK_WHILE_RUNNING, + TriggerMethod::HORIZONTAL_NO_BIAS + ) + , MOVE_DURATION0( + "Move Duration:
Move in each direction for this long before turning around.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , SWEET_SCENT_POKEMON_LOCATION( + "Sweet Scent Pokemon Location:
Which Pokemon in the party knows Sweet Scent.", + { + {0, "slot1", "1st"}, + {1, "slot2", "2nd"}, + {2, "slot3", "3rd"}, + {3, "slot4", "4th"}, + {4, "slot5", "2nd last"}, + {5, "slot6", "Last"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) +{ + PA_ADD_OPTION(TRIGGER_METHOD); + PA_ADD_OPTION(MOVE_DURATION0); + PA_ADD_OPTION(SWEET_SCENT_POKEMON_LOCATION); +} + + +void OverworldTrigger::run_trigger(ProControllerContext& context) const{ + Milliseconds normal_duration = MOVE_DURATION0; + Milliseconds biased_duration = MOVE_DURATION0.get() + 200ms; + Milliseconds mash_duration = normal_duration - 64ms; + switch (TRIGGER_METHOD){ + case TriggerMethod::HORIZONTAL_NO_BIAS: + ssf_press_left_joystick(context, 0, 128, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + ssf_press_left_joystick(context, 255, 128, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + break; + case TriggerMethod::HORIZONTAL_BIAS_LEFT: + ssf_press_left_joystick(context, 0, 128, 0ms, biased_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + ssf_press_left_joystick(context, 255, 128, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + break; + case TriggerMethod::HORIZONTAL_BIAS_RIGHT: + ssf_press_left_joystick(context, 255, 128, 0ms, biased_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + ssf_press_left_joystick(context, 0, 128, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + break; + case TriggerMethod::VERTICAL_NO_BIAS: + ssf_press_left_joystick(context, 128, 0, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + ssf_press_left_joystick(context, 128, 255, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + break; + case TriggerMethod::VERTICAL_BIAS_UP: + ssf_press_left_joystick(context, 128, 0, 0ms, biased_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + ssf_press_left_joystick(context, 128, 255, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + break; + case TriggerMethod::VERTICAL_BIAS_DOWN: + ssf_press_left_joystick(context, 128, 255, 0ms, biased_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + ssf_press_left_joystick(context, 128, 0, 0ms, normal_duration); + ssf_mash1_button(context, BUTTON_B, mash_duration); + break; + default:; + } +} + +bool OverworldTrigger::find_encounter(VideoStream& stream, ProControllerContext& context) const{ + BattleMenuWatcher battle_menu_detector(BattleType::STANDARD); + StartBattleDetector start_battle_detector(stream.overlay()); + + int ret = 0; + if (TRIGGER_METHOD != TriggerMethod::SWEET_SCENT){ + // Move character back and forth to trigger encounter. + ret = run_until( + stream, context, + [&](ProControllerContext& context){ + while (true){ + run_trigger(context); + } + }, + { + {battle_menu_detector}, + {start_battle_detector}, + } + ); + }else{ + stream.overlay().add_log("Using Sweet Scent", COLOR_CYAN); + // Use Sweet Scent to trigger encounter. + overworld_to_menu(stream, context); + + // Go to pokemon page + const Milliseconds MENU_TO_POKEMON_DELAY = GameSettings::instance().MENU_TO_POKEMON_DELAY0; + pbf_press_button(context, BUTTON_ZL, 160ms, MENU_TO_POKEMON_DELAY); + + // Go to the pokemon that knows Sweet Scent + const size_t location = SWEET_SCENT_POKEMON_LOCATION.current_value(); + const uint16_t change_pokemon_delay = 20; + if (location >= 1 && location <= 3){ + const size_t move_down_times = location; + for(size_t i = 0; i < move_down_times; ++i){ + pbf_press_dpad(context, DPAD_DOWN, 20, change_pokemon_delay); + } + }else if (location >= 1){ // for location 4 and 5 + const size_t move_down_times = 6 - location; + for (size_t i = 0; i < move_down_times; ++i){ + pbf_press_dpad(context, DPAD_UP, 20, change_pokemon_delay); + } + } + + // Open the pokemon menu of the selected pokemon + const uint16_t pokemon_to_pokemon_menu_delay = 30; + pbf_press_button(context, BUTTON_ZL, 20, pokemon_to_pokemon_menu_delay); + // Move down one menuitem to select "Sweet Scent" + const uint16_t move_pokemon_menu_item_delay = 30; + pbf_press_dpad(context, DPAD_DOWN, 20, move_pokemon_menu_item_delay); + // Use sweet scent + pbf_mash_button(context, BUTTON_ZL, 30); + + ret = wait_until( + stream, context, std::chrono::seconds(30), + { + {battle_menu_detector}, + {start_battle_detector}, + } + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Battle not detected after Sweet Scent for 30 seconds.", + stream + ); + } + } + + switch (ret){ + case 0: + stream.log("Unexpected Battle.", COLOR_RED); + return false; + case 1: + stream.log("Battle started!"); + return true; + } + return false; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h index 2b42280956..d375c3665f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h @@ -1,57 +1,57 @@ -/* Overworld Trigger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_OverworldTrigger_H -#define PokemonAutomation_PokemonBDSP_OverworldTrigger_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Program component to trigger an overworld encounter. -class OverworldTrigger : public GroupOption{ -public: - OverworldTrigger(); - - // Move character back and forth or use Sweet Scent to trigger an encounter. - // Return true if the start of a battle is detected. - // Return false if an unexpected battle happens where the battle menu is detected but - // not the starting animation. - // Throw exception if inference times out after Sweet Scent is used. - bool find_encounter(VideoStream& stream, ProControllerContext& context) const; - -private: - // Move character up and down or left and right once. - void run_trigger(ProControllerContext& context) const; - -public: - enum class TriggerMethod{ - HORIZONTAL_NO_BIAS, - HORIZONTAL_BIAS_LEFT, - HORIZONTAL_BIAS_RIGHT, - VERTICAL_NO_BIAS, - VERTICAL_BIAS_UP, - VERTICAL_BIAS_DOWN, - SWEET_SCENT, - }; - - EnumDropdownOption TRIGGER_METHOD; - MillisecondsOption MOVE_DURATION0; - IntegerEnumDropdownOption SWEET_SCENT_POKEMON_LOCATION; -}; - - - -} -} -} -#endif +/* Overworld Trigger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_OverworldTrigger_H +#define PokemonAutomation_PokemonBDSP_OverworldTrigger_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Program component to trigger an overworld encounter. +class OverworldTrigger : public GroupOption{ +public: + OverworldTrigger(); + + // Move character back and forth or use Sweet Scent to trigger an encounter. + // Return true if the start of a battle is detected. + // Return false if an unexpected battle happens where the battle menu is detected but + // not the starting animation. + // Throw exception if inference times out after Sweet Scent is used. + bool find_encounter(VideoStream& stream, ProControllerContext& context) const; + +private: + // Move character up and down or left and right once. + void run_trigger(ProControllerContext& context) const; + +public: + enum class TriggerMethod{ + HORIZONTAL_NO_BIAS, + HORIZONTAL_BIAS_LEFT, + HORIZONTAL_BIAS_RIGHT, + VERTICAL_NO_BIAS, + VERTICAL_BIAS_UP, + VERTICAL_BIAS_DOWN, + SWEET_SCENT, + }; + + EnumDropdownOption TRIGGER_METHOD; + MillisecondsOption MOVE_DURATION0; + IntegerEnumDropdownOption SWEET_SCENT_POKEMON_LOCATION; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.cpp index 9ca6b2a50b..53278680fc 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.cpp @@ -1,46 +1,46 @@ -/* Run from Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP_RunFromBattle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -bool run_from_battle( - VideoStream& stream, ProControllerContext& context, - Milliseconds exit_battle_time -){ - BlackScreenOverWatcher black_screen_detector; - int ret = run_until( - stream, context, - [exit_battle_time](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_ZL, 1000ms); - if (exit_battle_time > 1000ms){ - pbf_mash_button(context, BUTTON_B, exit_battle_time - 1000ms); - } - }, - {{black_screen_detector}} - ); - if (ret < 0){ - stream.log("Timed out waiting for end of battle. Are you stuck in the battle?", COLOR_RED); - return false; - } - pbf_wait(context, TICKS_PER_SECOND); - context.wait_for_all_requests(); - return true; -} - - - -} -} -} +/* Run from Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP_RunFromBattle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +bool run_from_battle( + VideoStream& stream, ProControllerContext& context, + Milliseconds exit_battle_time +){ + BlackScreenOverWatcher black_screen_detector; + int ret = run_until( + stream, context, + [exit_battle_time](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_ZL, 1000ms); + if (exit_battle_time > 1000ms){ + pbf_mash_button(context, BUTTON_B, exit_battle_time - 1000ms); + } + }, + {{black_screen_detector}} + ); + if (ret < 0){ + stream.log("Timed out waiting for end of battle. Are you stuck in the battle?", COLOR_RED); + return false; + } + pbf_wait(context, TICKS_PER_SECOND); + context.wait_for_all_requests(); + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h index 87561b5e4f..f815643e7f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/PokemonBDSP_RunFromBattle.h @@ -1,31 +1,31 @@ -/* Run from Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_RunFromBattle_H -#define PokemonAutomation_PokemonBDSP_RunFromBattle_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -// Run from a wild battle. -// The cursor must be over the "Run" button when starting this function. -// It uses feedback to ensure battle ends by detecting a black screen. -// Return true if a black screen is detected, false if not detected after -// `exit_battle_time` of ticks have passed. -bool run_from_battle( - VideoStream& stream, ProControllerContext& context, - Milliseconds exit_battle_time -); - - -} -} -} -#endif +/* Run from Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_RunFromBattle_H +#define PokemonAutomation_PokemonBDSP_RunFromBattle_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +// Run from a wild battle. +// The cursor must be over the "Run" button when starting this function. +// It uses feedback to ensure battle ends by detecting a black screen. +// Return true if a black screen is detected, false if not detected after +// `exit_battle_time` of ticks have passed. +bool run_from_battle( + VideoStream& stream, ProControllerContext& context, + Milliseconds exit_battle_time +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp index 9dee46388f..bb1a6b548b 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.cpp @@ -1,157 +1,157 @@ -/* Shiny Hunt - Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" -#include "PokemonBDSP_LegendaryReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -LegendaryReset_Descriptor::LegendaryReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:LegendaryReset", - STRING_POKEMON + " BDSP", "Legendary Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/LegendaryReset.md", - "Shiny hunt a standing legendary " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr LegendaryReset_Descriptor::make_stats() const{ - return std::unique_ptr(new PokemonSwSh::ShinyHuntTracker(false)); -} - - -LegendaryReset::LegendaryReset() - : GO_HOME_WHEN_DONE(false) - , WALK_UP( - "Walk Up:
Walk up while mashing A to trigger encounter.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , ENCOUNTER_BOT_OPTIONS(false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(WALK_UP); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void LegendaryReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PokemonSwSh::ShinyHuntTracker& stats = env.current_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - LeadingShinyTracker lead_tracker(env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - bool reset = false; - while (true){ - env.update_stats(); - - if (reset){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ - stats.add_error(); - continue; - } - } - reset = true; - - StartBattleDetector start_battle(env.console); - BattleMenuWatcher battle_menu(BattleType::STANDARD); - - int ret = run_until( - env.console, context, - [this](ProControllerContext& context){ - size_t stop = WALK_UP ? 30 : 60; - for (size_t c = 0; c < stop; c++){ - if (WALK_UP){ - pbf_move_left_joystick(context, 128, 0, 125, 0); - } - pbf_mash_button(context, BUTTON_ZL, 125); - } - }, - { - {start_battle}, - {battle_menu}, - } - ); - switch (ret){ - case 0: - env.log("Battle started!"); - break; - case 1: - env.log("Unexpected battle menu.", COLOR_RED); - continue; - default: - env.log("Timed out.", COLOR_RED); - continue; - } - - // Detect shiny. - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - WILD_POKEMON, - std::chrono::seconds(30), - ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION - ); - - bool stop = handler.handle_standard_encounter(result_wild); - if (stop){ - break; - } - lead_tracker.report_result(result_own.shiny_type); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - -} -} -} +/* Shiny Hunt - Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" +#include "PokemonBDSP_LegendaryReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +LegendaryReset_Descriptor::LegendaryReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:LegendaryReset", + STRING_POKEMON + " BDSP", "Legendary Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/LegendaryReset.md", + "Shiny hunt a standing legendary " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr LegendaryReset_Descriptor::make_stats() const{ + return std::unique_ptr(new PokemonSwSh::ShinyHuntTracker(false)); +} + + +LegendaryReset::LegendaryReset() + : GO_HOME_WHEN_DONE(false) + , WALK_UP( + "Walk Up:
Walk up while mashing A to trigger encounter.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , ENCOUNTER_BOT_OPTIONS(false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(WALK_UP); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void LegendaryReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PokemonSwSh::ShinyHuntTracker& stats = env.current_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + LeadingShinyTracker lead_tracker(env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + bool reset = false; + while (true){ + env.update_stats(); + + if (reset){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ + stats.add_error(); + continue; + } + } + reset = true; + + StartBattleDetector start_battle(env.console); + BattleMenuWatcher battle_menu(BattleType::STANDARD); + + int ret = run_until( + env.console, context, + [this](ProControllerContext& context){ + size_t stop = WALK_UP ? 30 : 60; + for (size_t c = 0; c < stop; c++){ + if (WALK_UP){ + pbf_move_left_joystick(context, 128, 0, 125, 0); + } + pbf_mash_button(context, BUTTON_ZL, 125); + } + }, + { + {start_battle}, + {battle_menu}, + } + ); + switch (ret){ + case 0: + env.log("Battle started!"); + break; + case 1: + env.log("Unexpected battle menu.", COLOR_RED); + continue; + default: + env.log("Timed out.", COLOR_RED); + continue; + } + + // Detect shiny. + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + WILD_POKEMON, + std::chrono::seconds(30), + ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION + ); + + bool stop = handler.handle_standard_encounter(result_wild); + if (stop){ + break; + } + lead_tracker.report_result(result_own.shiny_type); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h index 60255b8142..dda421660e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_LegendaryReset.h @@ -1,56 +1,56 @@ -/* Shiny Hunt - Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_LegendaryReset_H -#define PokemonAutomation_PokemonBDSP_LegendaryReset_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class LegendaryReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LegendaryReset_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class LegendaryReset : public SingleSwitchProgramInstance{ -public: - LegendaryReset(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - Pokemon::EncounterBotLanguage LANGUAGE; - - BooleanCheckBoxOption WALK_UP; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Shiny Hunt - Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_LegendaryReset_H +#define PokemonAutomation_PokemonBDSP_LegendaryReset_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class LegendaryReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LegendaryReset_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class LegendaryReset : public SingleSwitchProgramInstance{ +public: + LegendaryReset(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + Pokemon::EncounterBotLanguage LANGUAGE; + + BooleanCheckBoxOption WALK_UP; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp index 2cebc451d3..0e48bba28f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.cpp @@ -1,229 +1,229 @@ -/* Shiny Hunt - Fishing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" -#include "PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" -#include "PokemonBDSP_ShinyHunt-Fishing.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ShinyHuntFishing_Descriptor::ShinyHuntFishing_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:ShinyHuntFishing", - STRING_POKEMON + " BDSP", "Shiny Hunt - Fishing", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ShinyHunt-Fishing.md", - "Shiny hunt fishing " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntFishing_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(false) - , m_nothing(m_stats["Nothing"]) - , m_misses(m_stats["Misses"]) - { - m_display_order.insert(m_display_order.begin() + 1, Stat("Nothing")); - m_display_order.insert(m_display_order.begin() + 2, Stat("Misses")); - } - std::atomic& m_nothing; - std::atomic& m_misses; -}; -std::unique_ptr ShinyHuntFishing_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -ShinyHuntFishing::ShinyHuntFishing() - : GO_HOME_WHEN_DONE(false) - , SHORTCUT("Fishing Shortcut:") - , ENCOUNTER_BOT_OPTIONS(true) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(SHORTCUT); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -} - - - - - - -void ShinyHuntFishing::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntFishing_Descriptor::Stats& stats = env.current_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - LeadingShinyTracker lead_tracker(env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - // Encounter Loop - while (true){ - env.update_stats(); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - { - ShortDialogWatcher dialog_detector; - MarkDetector mark_detector(env.console, {0.4, 0.2, 0.2, 0.5}); - StartBattleDetector battle(env.console); - BattleMenuWatcher battle_menu(BattleType::STANDARD); - int ret = run_until( - env.console, context, - [this](ProControllerContext& context){ - SHORTCUT.run(context, 30 * TICKS_PER_SECOND); - }, - { - {dialog_detector}, - {mark_detector}, - {battle_menu}, - } - ); - switch (ret){ - case 0: - env.log("Nothing found...", COLOR_ORANGE); - stats.m_nothing++; - continue; - case 1: - env.log("Hooked something!", COLOR_BLUE); - pbf_press_button(context, BUTTON_ZL, 10, TICKS_PER_SECOND); - break; - case 2: - env.log("Unexpected battle menu.", COLOR_RED); - stats.add_error(); - handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); - continue; - default: - env.log("Timed out.", COLOR_RED); - stats.add_error(); - continue; - } - - // Wait for dialog after hooking to appear. - ret = wait_until( - env.console, context, - std::chrono::milliseconds(5000), - { - {dialog_detector}, - {battle_menu}, - } - ); - switch (ret){ - case 0: - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - break; - case 1: - env.log("Unexpected battle menu.", COLOR_RED); - stats.add_error(); - handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); - continue; - default: - env.log("Timed out.", COLOR_RED); - stats.add_error(); - continue; - } - - // Wait for battle to start. - ret = wait_until( - env.console, context, - std::chrono::milliseconds(10000), - { - {battle}, - {battle_menu}, - } - ); - switch (ret){ - case 0: - env.console.log("Battle started!"); - break; - case 1: - env.log("Unexpected battle menu.", COLOR_RED); - stats.add_error(); - handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); - continue; - default: - env.log("Missed the hook.", COLOR_ORANGE); - stats.m_misses++; - continue; - } - } - - // Detect shiny. - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - WILD_POKEMON, - std::chrono::seconds(30), - ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION - ); - - bool stop = handler.handle_standard_encounter_end_battle( - result_wild, EXIT_BATTLE_TIMEOUT0 - ); - if (stop){ - break; - } - lead_tracker.report_result(result_own.shiny_type); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Shiny Hunt - Fishing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/Inference/PokemonBDSP_DialogDetector.h" +#include "PokemonBDSP/Inference/PokemonBDSP_MarkFinder.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" +#include "PokemonBDSP_ShinyHunt-Fishing.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ShinyHuntFishing_Descriptor::ShinyHuntFishing_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:ShinyHuntFishing", + STRING_POKEMON + " BDSP", "Shiny Hunt - Fishing", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ShinyHunt-Fishing.md", + "Shiny hunt fishing " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntFishing_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(false) + , m_nothing(m_stats["Nothing"]) + , m_misses(m_stats["Misses"]) + { + m_display_order.insert(m_display_order.begin() + 1, Stat("Nothing")); + m_display_order.insert(m_display_order.begin() + 2, Stat("Misses")); + } + std::atomic& m_nothing; + std::atomic& m_misses; +}; +std::unique_ptr ShinyHuntFishing_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +ShinyHuntFishing::ShinyHuntFishing() + : GO_HOME_WHEN_DONE(false) + , SHORTCUT("Fishing Shortcut:") + , ENCOUNTER_BOT_OPTIONS(true) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(SHORTCUT); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +} + + + + + + +void ShinyHuntFishing::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntFishing_Descriptor::Stats& stats = env.current_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + LeadingShinyTracker lead_tracker(env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + // Encounter Loop + while (true){ + env.update_stats(); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + { + ShortDialogWatcher dialog_detector; + MarkDetector mark_detector(env.console, {0.4, 0.2, 0.2, 0.5}); + StartBattleDetector battle(env.console); + BattleMenuWatcher battle_menu(BattleType::STANDARD); + int ret = run_until( + env.console, context, + [this](ProControllerContext& context){ + SHORTCUT.run(context, 30 * TICKS_PER_SECOND); + }, + { + {dialog_detector}, + {mark_detector}, + {battle_menu}, + } + ); + switch (ret){ + case 0: + env.log("Nothing found...", COLOR_ORANGE); + stats.m_nothing++; + continue; + case 1: + env.log("Hooked something!", COLOR_BLUE); + pbf_press_button(context, BUTTON_ZL, 10, TICKS_PER_SECOND); + break; + case 2: + env.log("Unexpected battle menu.", COLOR_RED); + stats.add_error(); + handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); + continue; + default: + env.log("Timed out.", COLOR_RED); + stats.add_error(); + continue; + } + + // Wait for dialog after hooking to appear. + ret = wait_until( + env.console, context, + std::chrono::milliseconds(5000), + { + {dialog_detector}, + {battle_menu}, + } + ); + switch (ret){ + case 0: + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + break; + case 1: + env.log("Unexpected battle menu.", COLOR_RED); + stats.add_error(); + handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); + continue; + default: + env.log("Timed out.", COLOR_RED); + stats.add_error(); + continue; + } + + // Wait for battle to start. + ret = wait_until( + env.console, context, + std::chrono::milliseconds(10000), + { + {battle}, + {battle_menu}, + } + ); + switch (ret){ + case 0: + env.console.log("Battle started!"); + break; + case 1: + env.log("Unexpected battle menu.", COLOR_RED); + stats.add_error(); + handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); + continue; + default: + env.log("Missed the hook.", COLOR_ORANGE); + stats.m_misses++; + continue; + } + } + + // Detect shiny. + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + WILD_POKEMON, + std::chrono::seconds(30), + ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION + ); + + bool stop = handler.handle_standard_encounter_end_battle( + result_wild, EXIT_BATTLE_TIMEOUT0 + ); + if (stop){ + break; + } + lead_tracker.report_result(result_own.shiny_type); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h index c6a18760ac..38ded69a43 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Fishing.h @@ -1,63 +1,63 @@ -/* Shiny Hunt - Fishing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ShinyHuntFishing_H -#define PokemonAutomation_PokemonBDSP_ShinyHuntFishing_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" -#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class ShinyHuntFishing_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntFishing_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class ShinyHuntFishing : public SingleSwitchProgramInstance{ -public: - ShinyHuntFishing(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - void run_trigger(ProControllerContext& context) const; - bool find_encounter(SingleSwitchProgramEnvironment& env) const; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - Pokemon::EncounterBotLanguage LANGUAGE; - - ShortcutDirectionOption SHORTCUT; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -}; - - - -} -} -} -#endif +/* Shiny Hunt - Fishing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ShinyHuntFishing_H +#define PokemonAutomation_PokemonBDSP_ShinyHuntFishing_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" +#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class ShinyHuntFishing_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntFishing_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class ShinyHuntFishing : public SingleSwitchProgramInstance{ +public: + ShinyHuntFishing(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + void run_trigger(ProControllerContext& context) const; + bool find_encounter(SingleSwitchProgramEnvironment& env) const; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + Pokemon::EncounterBotLanguage LANGUAGE; + + ShortcutDirectionOption SHORTCUT; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.cpp index ecccd0a351..dfb4af0ae5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.cpp @@ -1,191 +1,191 @@ -/* Shiny Hunt Autonomous - Overworld - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP_ShinyHunt-Overworld.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ShinyHuntOverworld_Descriptor::ShinyHuntOverworld_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:ShinyHuntOverworld", - STRING_POKEMON + " BDSP", "Shiny Hunt - Overworld", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ShinyHunt-Overworld.md", - "Shiny hunt overworld " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntOverworld_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(false) -// , m_resets(m_stats["Resets"]) - { -// m_display_order.insert(m_display_order.begin() + 2, Stat("Resets")); -// m_aliases["Unexpected Battles"] = "Errors"; - } -// std::atomic& m_resets; -}; -std::unique_ptr ShinyHuntOverworld_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ShinyHuntOverworld::ShinyHuntOverworld() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(true) - , RESET_GAME_WHEN_ERROR( - "Reset Game in Case of Error:
" - "When the program encounters an error, whether to reset the game to fix it.
" - "Make sure you have set \"Throw balls. Save if caught.\" in Option Overrides if you don't stop when finding a shiny.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(TRIGGER_METHOD); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(RESET_GAME_WHEN_ERROR); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); -// PA_ADD_OPTION(WATCHDOG_TIMER0); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -} - - - - - - -void ShinyHuntOverworld::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - OverlayLogTextScope overlay_log_text_scope(env.console.overlay()); - ShinyHuntOverworld_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - LeadingShinyTracker lead_tracker(env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - // Encounter Loop - while (true){ - // Find encounter. - try{ - bool battle = TRIGGER_METHOD.find_encounter(env.console, context); - if (!battle){ - stats.add_error(); - handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); - continue; - } - env.console.overlay().add_log("Battle started", COLOR_GREEN); - - // Detect shiny. - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - WILD_POKEMON, - std::chrono::seconds(30), - ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION - ); - - // result_wild.shiny_type = ShinyType::UNKNOWN_SHINY; - // result_wild.left_is_shiny = false; - // result_wild.right_is_shiny = true; - - bool stop = handler.handle_standard_encounter_end_battle( - result_wild, EXIT_BATTLE_TIMEOUT0 - ); - - if (stop){ - break; - } - lead_tracker.report_result(result_own.shiny_type); - - }catch (OperationFailedException& e){ - if (!RESET_GAME_WHEN_ERROR){ - throw; - } - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - stats.add_error(); - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - if (!reset_game_from_home( - env, env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - )){ - stats.add_error(); - continue; - } - } - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - - - - - - - - - - - -} -} -} +/* Shiny Hunt Autonomous - Overworld + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP_ShinyHunt-Overworld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ShinyHuntOverworld_Descriptor::ShinyHuntOverworld_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:ShinyHuntOverworld", + STRING_POKEMON + " BDSP", "Shiny Hunt - Overworld", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ShinyHunt-Overworld.md", + "Shiny hunt overworld " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntOverworld_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(false) +// , m_resets(m_stats["Resets"]) + { +// m_display_order.insert(m_display_order.begin() + 2, Stat("Resets")); +// m_aliases["Unexpected Battles"] = "Errors"; + } +// std::atomic& m_resets; +}; +std::unique_ptr ShinyHuntOverworld_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ShinyHuntOverworld::ShinyHuntOverworld() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(true) + , RESET_GAME_WHEN_ERROR( + "Reset Game in Case of Error:
" + "When the program encounters an error, whether to reset the game to fix it.
" + "Make sure you have set \"Throw balls. Save if caught.\" in Option Overrides if you don't stop when finding a shiny.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(TRIGGER_METHOD); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(RESET_GAME_WHEN_ERROR); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); +// PA_ADD_OPTION(WATCHDOG_TIMER0); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +} + + + + + + +void ShinyHuntOverworld::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + OverlayLogTextScope overlay_log_text_scope(env.console.overlay()); + ShinyHuntOverworld_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + LeadingShinyTracker lead_tracker(env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + // Encounter Loop + while (true){ + // Find encounter. + try{ + bool battle = TRIGGER_METHOD.find_encounter(env.console, context); + if (!battle){ + stats.add_error(); + handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); + continue; + } + env.console.overlay().add_log("Battle started", COLOR_GREEN); + + // Detect shiny. + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + WILD_POKEMON, + std::chrono::seconds(30), + ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION + ); + + // result_wild.shiny_type = ShinyType::UNKNOWN_SHINY; + // result_wild.left_is_shiny = false; + // result_wild.right_is_shiny = true; + + bool stop = handler.handle_standard_encounter_end_battle( + result_wild, EXIT_BATTLE_TIMEOUT0 + ); + + if (stop){ + break; + } + lead_tracker.report_result(result_own.shiny_type); + + }catch (OperationFailedException& e){ + if (!RESET_GAME_WHEN_ERROR){ + throw; + } + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + stats.add_error(); + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + if (!reset_game_from_home( + env, env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + )){ + stats.add_error(); + continue; + } + } + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h index 18d93c1b74..de1db616d5 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Overworld.h @@ -1,62 +1,62 @@ -/* Shiny Hunt - Overworld - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ShinyHuntOverworld_H -#define PokemonAutomation_PokemonBDSP_ShinyHuntOverworld_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" -#include "PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class ShinyHuntOverworld_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntOverworld_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class ShinyHuntOverworld : public SingleSwitchProgramInstance{ -public: - ShinyHuntOverworld(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - Pokemon::EncounterBotLanguage LANGUAGE; - - OverworldTrigger TRIGGER_METHOD; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - BooleanCheckBoxOption RESET_GAME_WHEN_ERROR; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; -// MillisecondsOption WATCHDOG_TIMER0; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -}; - - - -} -} -} -#endif +/* Shiny Hunt - Overworld + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ShinyHuntOverworld_H +#define PokemonAutomation_PokemonBDSP_ShinyHuntOverworld_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" +#include "PokemonBDSP/Programs/PokemonBDSP_OverworldTrigger.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class ShinyHuntOverworld_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntOverworld_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class ShinyHuntOverworld : public SingleSwitchProgramInstance{ +public: + ShinyHuntOverworld(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + Pokemon::EncounterBotLanguage LANGUAGE; + + OverworldTrigger TRIGGER_METHOD; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + BooleanCheckBoxOption RESET_GAME_WHEN_ERROR; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; +// MillisecondsOption WATCHDOG_TIMER0; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.cpp index 23d5cb524b..e730c23de4 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.cpp @@ -1,190 +1,190 @@ -/* Shiny Hunt - Shaymin Runaway - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" -#include "PokemonBDSP_ShinyHunt-Shaymin.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ShinyHuntShaymin_Descriptor::ShinyHuntShaymin_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:ShinyHuntShaymin", - STRING_POKEMON + " BDSP", "Shiny Hunt - Shaymin", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ShinyHunt-Shaymin.md", - "Shiny hunt Shaymin using the runaway method.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr ShinyHuntShaymin_Descriptor::make_stats() const{ - return std::unique_ptr(new PokemonSwSh::ShinyHuntTracker(false)); -} - - -ShinyHuntShaymin::ShinyHuntShaymin() - : GO_HOME_WHEN_DONE(false) -// , SHORTCUT("Bike Shortcut:") - , ENCOUNTER_BOT_OPTIONS(false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, -// &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, -// &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); -// PA_ADD_OPTION(SHORTCUT); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); -// PA_ADD_OPTION(WATCHDOG_TIMER); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -} - - - -bool ShinyHuntShaymin::start_encounter(SingleSwitchProgramEnvironment& env, ProControllerContext& context) const{ - context.wait_for_all_requests(); - { - BattleMenuWatcher battle_menu_detector(BattleType::STANDARD); - ShortDialogWatcher dialog_detector; - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - ssf_press_dpad(context, DPAD_UP, 0ms, 10s, 0ms); - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_ZL, 200ms, 300ms); - pbf_mash_button(context, BUTTON_B, 400ms); - } - }, - { - {battle_menu_detector}, - {dialog_detector}, - } - ); - switch (ret){ - case 0: - env.console.log("Unexpected Battle.", COLOR_RED); - return false; - case 1: - env.console.log("Talked to Shaymin!"); - break; - } - } - { - BattleMenuWatcher battle_menu_detector(BattleType::STANDARD); - StartBattleDetector start_battle_detector(env.console); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - ssf_press_dpad(context, DPAD_UP, 0ms, 10s, 0ms); - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_ZL, 200ms, 400ms); - pbf_mash_button(context, BUTTON_B, 400ms); - } - }, - { - {battle_menu_detector}, - {start_battle_detector}, - } - ); - switch (ret){ - case 0: - env.console.log("Unexpected Battle.", COLOR_RED); - return false; - case 1: - env.console.log("Battle started!"); - break; - } - } - return true; -} - -void ShinyHuntShaymin::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PokemonSwSh::ShinyHuntTracker& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - Language::None, - ENCOUNTER_BOT_OPTIONS, - stats - ); - LeadingShinyTracker lead_tracker(env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - // Encounter Loop - while (true){ - // Find encounter. - bool battle = start_encounter(env, context); - if (!battle){ - stats.add_error(); - handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); - continue; - } - - // Detect shiny. - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - WILD_POKEMON, - std::chrono::seconds(30), - ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION - ); - - bool stop = handler.handle_standard_encounter_end_battle(result_wild, EXIT_BATTLE_TIMEOUT0); - if (stop){ - break; - } - lead_tracker.report_result(result_own.shiny_type); - - // Clear dialogs. - pbf_mash_button(context, BUTTON_B, 75); - - // Hop on bike, ride down to seabreak path -// SHORTCUT.run(env.console, 0); - pbf_move_left_joystick(context, 128, 255, 360, 0); - pbf_move_left_joystick(context, 128, 0, 400, 0); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - -} -} -} +/* Shiny Hunt - Shaymin Runaway + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_StartBattleDetector.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP/Programs/PokemonBDSP_EncounterHandler.h" +#include "PokemonBDSP_ShinyHunt-Shaymin.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ShinyHuntShaymin_Descriptor::ShinyHuntShaymin_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:ShinyHuntShaymin", + STRING_POKEMON + " BDSP", "Shiny Hunt - Shaymin", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/ShinyHunt-Shaymin.md", + "Shiny hunt Shaymin using the runaway method.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr ShinyHuntShaymin_Descriptor::make_stats() const{ + return std::unique_ptr(new PokemonSwSh::ShinyHuntTracker(false)); +} + + +ShinyHuntShaymin::ShinyHuntShaymin() + : GO_HOME_WHEN_DONE(false) +// , SHORTCUT("Bike Shortcut:") + , ENCOUNTER_BOT_OPTIONS(false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, +// &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, +// &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); +// PA_ADD_OPTION(SHORTCUT); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); +// PA_ADD_OPTION(WATCHDOG_TIMER); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +} + + + +bool ShinyHuntShaymin::start_encounter(SingleSwitchProgramEnvironment& env, ProControllerContext& context) const{ + context.wait_for_all_requests(); + { + BattleMenuWatcher battle_menu_detector(BattleType::STANDARD); + ShortDialogWatcher dialog_detector; + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + ssf_press_dpad(context, DPAD_UP, 0ms, 10s, 0ms); + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_ZL, 200ms, 300ms); + pbf_mash_button(context, BUTTON_B, 400ms); + } + }, + { + {battle_menu_detector}, + {dialog_detector}, + } + ); + switch (ret){ + case 0: + env.console.log("Unexpected Battle.", COLOR_RED); + return false; + case 1: + env.console.log("Talked to Shaymin!"); + break; + } + } + { + BattleMenuWatcher battle_menu_detector(BattleType::STANDARD); + StartBattleDetector start_battle_detector(env.console); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + ssf_press_dpad(context, DPAD_UP, 0ms, 10s, 0ms); + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_ZL, 200ms, 400ms); + pbf_mash_button(context, BUTTON_B, 400ms); + } + }, + { + {battle_menu_detector}, + {start_battle_detector}, + } + ); + switch (ret){ + case 0: + env.console.log("Unexpected Battle.", COLOR_RED); + return false; + case 1: + env.console.log("Battle started!"); + break; + } + } + return true; +} + +void ShinyHuntShaymin::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PokemonSwSh::ShinyHuntTracker& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + Language::None, + ENCOUNTER_BOT_OPTIONS, + stats + ); + LeadingShinyTracker lead_tracker(env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + // Encounter Loop + while (true){ + // Find encounter. + bool battle = start_encounter(env, context); + if (!battle){ + stats.add_error(); + handler.run_away_due_to_error(EXIT_BATTLE_TIMEOUT0); + continue; + } + + // Detect shiny. + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + WILD_POKEMON, + std::chrono::seconds(30), + ENCOUNTER_BOT_OPTIONS.USE_SOUND_DETECTION + ); + + bool stop = handler.handle_standard_encounter_end_battle(result_wild, EXIT_BATTLE_TIMEOUT0); + if (stop){ + break; + } + lead_tracker.report_result(result_own.shiny_type); + + // Clear dialogs. + pbf_mash_button(context, BUTTON_B, 75); + + // Hop on bike, ride down to seabreak path +// SHORTCUT.run(env.console, 0); + pbf_move_left_joystick(context, 128, 255, 360, 0); + pbf_move_left_joystick(context, 128, 0, 400, 0); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h index 25aff2ed1a..5394a5a4e9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_ShinyHunt-Shaymin.h @@ -1,60 +1,60 @@ -/* Shiny Hunt - Shaymin Runaway - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_ShinyHuntShaymin_H -#define PokemonAutomation_PokemonBDSP_ShinyHuntShaymin_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" -#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class ShinyHuntShaymin_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntShaymin_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class ShinyHuntShaymin : public SingleSwitchProgramInstance{ -public: - ShinyHuntShaymin(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - bool start_encounter(SingleSwitchProgramEnvironment& env, ProControllerContext& context) const; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - -// ShortcutDirection SHORTCUT; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -}; - - - -} -} -} -#endif +/* Shiny Hunt - Shaymin Runaway + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_ShinyHuntShaymin_H +#define PokemonAutomation_PokemonBDSP_ShinyHuntShaymin_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonBDSP/Options/PokemonBDSP_ShortcutDirection.h" +#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class ShinyHuntShaymin_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntShaymin_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class ShinyHuntShaymin : public SingleSwitchProgramInstance{ +public: + ShinyHuntShaymin(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + bool start_encounter(SingleSwitchProgramEnvironment& env, ProControllerContext& context) const; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + +// ShortcutDirection SHORTCUT; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.cpp index 571354a2c4..42e555ff13 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.cpp @@ -1,270 +1,270 @@ -/* Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h" -#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" -#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP_StarterReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -StarterReset_Descriptor::StarterReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:StarterReset", - STRING_POKEMON + " BDSP", "Starter Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/StarterReset.md", - "Shiny hunt your starter " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StarterReset_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(false) - , m_shiny_starly(m_stats["Shiny Starly"]) - { - m_display_order.emplace_back("Shiny Starly", HIDDEN_IF_ZERO); - } - std::atomic& m_shiny_starly; -}; -std::unique_ptr StarterReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -StarterReset::StarterReset() - : GO_HOME_WHEN_DONE(false) - , STARTER_DATABASE(make_name_database({"turtwig", "chimchar", "piplup"})) - , STARTER( - "Starter:", - STARTER_DATABASE, - LockMode::LOCK_WHILE_RUNNING, - "turtwig" - ) - , USE_SOUND_DETECTION( - "Use Sound Detection:
Use sound to improve shiny detection.
" - "Make sure you have correct audio input set.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , VIDEO_ON_SHINY( - "Video Capture:
Take a video of the encounter if it is shiny.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_NONSHINY( - "Non-Shiny Starter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Starter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_NONSHINY, - &NOTIFICATION_SHINY, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ -// PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(STARTER); - PA_ADD_OPTION(USE_SOUND_DETECTION); - PA_ADD_OPTION(VIDEO_ON_SHINY); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - - -void StarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StarterReset_Descriptor::Stats& stats = env.current_stats(); - - std::shared_ptr briefcase = std::make_shared(RESOURCE_PATH() + "PokemonBDSP/StarterBriefcase.png"); - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - size_t consecutive_failures = 0; - - bool reset = false; - while (true){ - env.update_stats(); - - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 times in the row.", - env.console - ); - } - - if (reset){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ - stats.add_error(); - consecutive_failures++; - continue; - } - } - reset = true; - - // Enter the lake. - pbf_move_left_joystick(context, 128, 0, TICKS_PER_SECOND, 0); - - // Mash B until we see the briefcase. - ImageMatchWatcher detector(briefcase, {0.5, 0.1, 0.5, 0.7}, 100, true); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - {{detector}} - ); - if (ret == 0){ - env.log("Detected briefcase!"); - }else{ - env.log("Timed out waiting for briefcase.", COLOR_RED); - stats.add_error(); - consecutive_failures++; - dump_image(env.console, env.program_info(), env.console, "Briefcase"); - continue; - } - - // Wait for briefcase to fully open. - env.log("Mashing B for briefcase to fully open."); - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - - // Scroll to your starter. - size_t scroll = 0; - const std::string& starter = STARTER.slug(); - env.log("Scrolling to starter... " + starter); - if (starter == "turtwig"){ - scroll = 0; - }else if (starter == "chimchar"){ - scroll = 1; - }else if (starter == "piplup"){ - scroll = 2; - } - for (size_t c = 0; c < scroll; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - } - - // Select starter. - pbf_press_button(context, BUTTON_ZL, 20, 30); - context.wait_for_all_requests(); - - { - SelectionArrowFinder selection_arrow(env.console, {0.50, 0.60, 0.35, 0.20}, COLOR_RED); - ret = wait_until( - env.console, context, std::chrono::seconds(3), - {{selection_arrow}} - ); - if (ret == 0){ - env.log("Detected selection prompt!"); - }else{ - env.log("Timed out waiting for selection prompt.", COLOR_RED); - consecutive_failures++; - } - pbf_wait(context, 50); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_button(context, BUTTON_ZL, 10, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - // Detect shiny. - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - YOUR_POKEMON, - std::chrono::seconds(30), - USE_SOUND_DETECTION - ); - -// if (result_wild.shiny_type == ShinyType::UNKNOWN || result_own.shiny_type == ShinyType::UNKNOWN){ - if (result_own.shiny_type == ShinyType::UNKNOWN){ - stats.add_error(); - consecutive_failures++; - dump_image(env.console, env.program_info(), env.console, "UnknownShinyDetection"); - }else{ - consecutive_failures = 0; - } - - bool wild_shiny = is_likely_shiny(result_wild.shiny_type); - if (wild_shiny){ - stats.m_shiny_starly++; - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - true, true, {{{"starly"}, ShinyType::UNKNOWN_SHINY}}, result_wild.alpha, - result_wild.get_best_screenshot() - ); - pbf_wait(context, 5 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - } - - bool your_shiny = is_likely_shiny(result_own.shiny_type); - if (your_shiny){ - stats.add_unknown_shiny(); - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - true, true, {{{starter}, ShinyType::UNKNOWN_SHINY}}, result_own.alpha, - result_own.get_best_screenshot() - ); - pbf_wait(context, 5 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - break; - }else{ - stats.add_non_shiny(); - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - true, false, {{{starter}, ShinyType::NOT_SHINY}}, result_own.alpha, - result_own.get_best_screenshot() - ); - } - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h" +#include "PokemonBDSP/Programs/PokemonBDSP_GameEntry.h" +#include "PokemonBDSP/Inference/PokemonBDSP_SelectionArrow.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP_StarterReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +StarterReset_Descriptor::StarterReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:StarterReset", + STRING_POKEMON + " BDSP", "Starter Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/StarterReset.md", + "Shiny hunt your starter " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StarterReset_Descriptor::Stats : public PokemonSwSh::ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(false) + , m_shiny_starly(m_stats["Shiny Starly"]) + { + m_display_order.emplace_back("Shiny Starly", HIDDEN_IF_ZERO); + } + std::atomic& m_shiny_starly; +}; +std::unique_ptr StarterReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +StarterReset::StarterReset() + : GO_HOME_WHEN_DONE(false) + , STARTER_DATABASE(make_name_database({"turtwig", "chimchar", "piplup"})) + , STARTER( + "Starter:", + STARTER_DATABASE, + LockMode::LOCK_WHILE_RUNNING, + "turtwig" + ) + , USE_SOUND_DETECTION( + "Use Sound Detection:
Use sound to improve shiny detection.
" + "Make sure you have correct audio input set.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , VIDEO_ON_SHINY( + "Video Capture:
Take a video of the encounter if it is shiny.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_NONSHINY( + "Non-Shiny Starter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_NONSHINY, + &NOTIFICATION_SHINY, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ +// PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(STARTER); + PA_ADD_OPTION(USE_SOUND_DETECTION); + PA_ADD_OPTION(VIDEO_ON_SHINY); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + + +void StarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StarterReset_Descriptor::Stats& stats = env.current_stats(); + + std::shared_ptr briefcase = std::make_shared(RESOURCE_PATH() + "PokemonBDSP/StarterBriefcase.png"); + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + size_t consecutive_failures = 0; + + bool reset = false; + while (true){ + env.update_stats(); + + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 times in the row.", + env.console + ); + } + + if (reset){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ + stats.add_error(); + consecutive_failures++; + continue; + } + } + reset = true; + + // Enter the lake. + pbf_move_left_joystick(context, 128, 0, TICKS_PER_SECOND, 0); + + // Mash B until we see the briefcase. + ImageMatchWatcher detector(briefcase, {0.5, 0.1, 0.5, 0.7}, 100, true); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + {{detector}} + ); + if (ret == 0){ + env.log("Detected briefcase!"); + }else{ + env.log("Timed out waiting for briefcase.", COLOR_RED); + stats.add_error(); + consecutive_failures++; + dump_image(env.console, env.program_info(), env.console, "Briefcase"); + continue; + } + + // Wait for briefcase to fully open. + env.log("Mashing B for briefcase to fully open."); + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + + // Scroll to your starter. + size_t scroll = 0; + const std::string& starter = STARTER.slug(); + env.log("Scrolling to starter... " + starter); + if (starter == "turtwig"){ + scroll = 0; + }else if (starter == "chimchar"){ + scroll = 1; + }else if (starter == "piplup"){ + scroll = 2; + } + for (size_t c = 0; c < scroll; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + } + + // Select starter. + pbf_press_button(context, BUTTON_ZL, 20, 30); + context.wait_for_all_requests(); + + { + SelectionArrowFinder selection_arrow(env.console, {0.50, 0.60, 0.35, 0.20}, COLOR_RED); + ret = wait_until( + env.console, context, std::chrono::seconds(3), + {{selection_arrow}} + ); + if (ret == 0){ + env.log("Detected selection prompt!"); + }else{ + env.log("Timed out waiting for selection prompt.", COLOR_RED); + consecutive_failures++; + } + pbf_wait(context, 50); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_button(context, BUTTON_ZL, 10, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + // Detect shiny. + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + YOUR_POKEMON, + std::chrono::seconds(30), + USE_SOUND_DETECTION + ); + +// if (result_wild.shiny_type == ShinyType::UNKNOWN || result_own.shiny_type == ShinyType::UNKNOWN){ + if (result_own.shiny_type == ShinyType::UNKNOWN){ + stats.add_error(); + consecutive_failures++; + dump_image(env.console, env.program_info(), env.console, "UnknownShinyDetection"); + }else{ + consecutive_failures = 0; + } + + bool wild_shiny = is_likely_shiny(result_wild.shiny_type); + if (wild_shiny){ + stats.m_shiny_starly++; + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + true, true, {{{"starly"}, ShinyType::UNKNOWN_SHINY}}, result_wild.alpha, + result_wild.get_best_screenshot() + ); + pbf_wait(context, 5 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + } + + bool your_shiny = is_likely_shiny(result_own.shiny_type); + if (your_shiny){ + stats.add_unknown_shiny(); + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + true, true, {{{starter}, ShinyType::UNKNOWN_SHINY}}, result_own.alpha, + result_own.get_best_screenshot() + ); + pbf_wait(context, 5 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + break; + }else{ + stats.add_non_shiny(); + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + true, false, {{{starter}, ShinyType::NOT_SHINY}}, result_own.alpha, + result_own.get_best_screenshot() + ); + } + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.h b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.h index 9c876b3005..0132f04767 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/ShinyHunting/PokemonBDSP_StarterReset.h @@ -1,59 +1,59 @@ -/* Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_StarterReset_H -#define PokemonAutomation_PokemonBDSP_StarterReset_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_NameSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class StarterReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StarterReset_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class StarterReset : public SingleSwitchProgramInstance{ -public: - StarterReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - void run_trigger(ProControllerContext& context) const; - bool find_encounter(SingleSwitchProgramEnvironment& env) const; - -private: -// StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - StringSelectDatabase STARTER_DATABASE; - StringSelectOption STARTER; - - BooleanCheckBoxOption USE_SOUND_DETECTION; - BooleanCheckBoxOption VIDEO_ON_SHINY; - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_StarterReset_H +#define PokemonAutomation_PokemonBDSP_StarterReset_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_NameSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class StarterReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StarterReset_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class StarterReset : public SingleSwitchProgramInstance{ +public: + StarterReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + void run_trigger(ProControllerContext& context) const; + bool find_encounter(SingleSwitchProgramEnvironment& env) const; + +private: +// StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + StringSelectDatabase STARTER_DATABASE; + StringSelectOption STARTER; + + BooleanCheckBoxOption USE_SOUND_DETECTION; + BooleanCheckBoxOption VIDEO_ON_SHINY; + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.cpp index 8efd039e35..7229983955 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.cpp @@ -1,81 +1,81 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" -#include "PokemonBDSP_ShinyEncounterTester.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -ShinyEncounterTester_Descriptor::ShinyEncounterTester_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:ShinyEncounterTester", - STRING_POKEMON + " BDSP", "Shiny Encounter Tester", - "", - "Test the shiny encounter detector. Start this program just before an encounter.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -ShinyEncounterTester::ShinyEncounterTester() - : ENCOUNTER_TYPE( - "Encounter Type:", - { - {BattleType::STARTER, "starter", "Starter Battle"}, - {BattleType::STANDARD, "standard", "Wild Encounter"}, - }, - LockMode::LOCK_WHILE_RUNNING, - BattleType::STANDARD - ) - , USE_SOUND_DETECTION( - "Use Sound Detection:
Use sound to improve shiny detection.
" - "Make sure you have correct audio input set.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATIONS({ - &NOTIFICATION_ERROR_RECOVERABLE, - }) -{ - PA_ADD_OPTION(ENCOUNTER_TYPE); - PA_ADD_OPTION(USE_SOUND_DETECTION); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void ShinyEncounterTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DoublesShinyDetection result_wild; - ShinyDetectionResult result_own; - detect_shiny_battle( - env, env.console, context, - result_wild, result_own, - NOTIFICATION_ERROR_RECOVERABLE, - ENCOUNTER_TYPE == BattleType::STARTER ? YOUR_POKEMON : WILD_POKEMON, - std::chrono::seconds(30), - USE_SOUND_DETECTION - ); - if (ENCOUNTER_TYPE == BattleType::STARTER){ - result_own.get_best_screenshot().save(now_to_filestring() + ".png"); - }else{ - result_wild.get_best_screenshot().save(now_to_filestring() + ".png"); - } -} - - - - - -} -} -} +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/ShinyDetection/PokemonBDSP_ShinyEncounterDetector.h" +#include "PokemonBDSP_ShinyEncounterTester.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +ShinyEncounterTester_Descriptor::ShinyEncounterTester_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:ShinyEncounterTester", + STRING_POKEMON + " BDSP", "Shiny Encounter Tester", + "", + "Test the shiny encounter detector. Start this program just before an encounter.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +ShinyEncounterTester::ShinyEncounterTester() + : ENCOUNTER_TYPE( + "Encounter Type:", + { + {BattleType::STARTER, "starter", "Starter Battle"}, + {BattleType::STANDARD, "standard", "Wild Encounter"}, + }, + LockMode::LOCK_WHILE_RUNNING, + BattleType::STANDARD + ) + , USE_SOUND_DETECTION( + "Use Sound Detection:
Use sound to improve shiny detection.
" + "Make sure you have correct audio input set.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATIONS({ + &NOTIFICATION_ERROR_RECOVERABLE, + }) +{ + PA_ADD_OPTION(ENCOUNTER_TYPE); + PA_ADD_OPTION(USE_SOUND_DETECTION); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void ShinyEncounterTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DoublesShinyDetection result_wild; + ShinyDetectionResult result_own; + detect_shiny_battle( + env, env.console, context, + result_wild, result_own, + NOTIFICATION_ERROR_RECOVERABLE, + ENCOUNTER_TYPE == BattleType::STARTER ? YOUR_POKEMON : WILD_POKEMON, + std::chrono::seconds(30), + USE_SOUND_DETECTION + ); + if (ENCOUNTER_TYPE == BattleType::STARTER){ + result_own.get_best_screenshot().save(now_to_filestring() + ".png"); + }else{ + result_wild.get_best_screenshot().save(now_to_filestring() + ".png"); + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h index b3bfdf5a96..27e41b34f3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_ShinyEncounterTester.h @@ -1,44 +1,44 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -class ShinyEncounterTester_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyEncounterTester_Descriptor(); -}; - - - -class ShinyEncounterTester : public SingleSwitchProgramInstance{ -public: - ShinyEncounterTester(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - EnumDropdownOption ENCOUNTER_TYPE; - - BooleanCheckBoxOption USE_SOUND_DETECTION; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonBDSP/Inference/Battles/PokemonBDSP_BattleMenuDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +class ShinyEncounterTester_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyEncounterTester_Descriptor(); +}; + + + +class ShinyEncounterTester : public SingleSwitchProgramInstance{ +public: + ShinyEncounterTester(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + EnumDropdownOption ENCOUNTER_TYPE; + + BooleanCheckBoxOption USE_SOUND_DETECTION; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.cpp index cfc6d10853..2dc9abbb5e 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.cpp @@ -1,197 +1,197 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h" -#include "PokemonBDSP_SoundListener.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - using namespace Pokemon; - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonBDSP:SoundListener", - STRING_POKEMON + " LA", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {} - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::SHINY, "shiny", "Shiny Sound"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::SHINY - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - - -// void search_alpha_roar_from_audio_dump(); - -void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // search_alpha_roar_from_audio_dump(); - // return; - - std::cout << "Running audio test program." << std::endl; - - std::shared_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::SHINY: - detector = std::make_shared(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "Not such sound detector as sound type " + std::to_string((size_t)type) - ); - return; - } - - InferenceSession session( - context, env.console, - {{*detector, std::chrono::milliseconds(20)}} - ); - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - -// A function used to search for the alpha roar on LA audio dump. -// But we didn't find the shound sound :P -void search_alpha_roar_from_audio_dump(){ - - const size_t SAMPLE_RATE = 48000; - - SpectrogramMatcher matcher( - "Alpha Roar", - AudioTemplateCache::instance().get_throw("PokemonBDSP/AlphaRoar", SAMPLE_RATE), - SpectrogramMatcher::Mode::RAW, SAMPLE_RATE, - 100.0 - ); - - // std::string file_listFile = "./scripts/short_audio_files.txt"; - std::string file_listFile = "1.txt"; - // std::string file_listFile = "./scripts/all_audio_files.txt"; - std::ifstream fin(file_listFile.c_str()); - std::vector file_list; - while(!fin.eof()){ - std::string line; - std::getline(fin, line); - file_list.push_back(line); - fin >> std::ws; - } - std::cout << "File num " << file_list.size() << std::endl; - - std::map closest_files; - - std::ofstream fout("file_check_output.txt"); - - for(size_t fileIdx = 0; fileIdx < file_list.size(); fileIdx++){ - matcher.clear(); - - - const auto& path = file_list[fileIdx]; - std::ostringstream os; - os << "File " << fileIdx << "/" << file_list.size() << " " << path << " "; - AudioTemplate audio = loadAudioTemplate(path); - if (audio.numWindows() == 0){ - os << "Fail" << std::endl; - fout << os.str(); - std::cout << os.str() << std::flush; - continue; - } - - // audio.scale(2.0); - - os << "#W " << audio.numWindows() << " "; - - // match! - float minScore = FLT_MAX; - std::vector new_spectrums; - size_t numStreamWindows = std::max(matcher.numMatchedWindows(), audio.numWindows()); - for(size_t audioIdx = 0; audioIdx < numStreamWindows; audioIdx++){ - new_spectrums.clear(); - AlignedVector freqVector(audio.numFrequencies()); - if (audioIdx < audio.numWindows()){ - const float * freq = audio.getWindow(audioIdx); - memcpy(freqVector.data(), freq, sizeof(float) * audio.numFrequencies()); - }else{ - // add zero-freq window - } - new_spectrums.emplace_back( - audioIdx, SAMPLE_RATE, - std::make_unique>(std::move(freqVector)) - ); - float score = matcher.match(new_spectrums); - minScore = std::min(score, minScore); - } // end audio Idx - - os << "dist " << minScore << std::endl; - fout << os.str(); - std::cout << os.str() << std::flush; - - closest_files.emplace(minScore, path); - } - - fout.close(); - - auto it = closest_files.begin(); - std::cout << "--------------" << std::endl; - fout.open("file_check_output_sorted.txt"); - for(int i = 0; it != closest_files.end(); i++, it++){ - if (i < 40) - std::cout << it->first << ", " << it->second << std::endl; - fout << it->first << ", " << it->second << std::endl; - } - fout.close(); - return; -} - - - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/Inference/Sounds/PokemonBDSP_ShinySoundDetector.h" +#include "PokemonBDSP_SoundListener.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + using namespace Pokemon; + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonBDSP:SoundListener", + STRING_POKEMON + " LA", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {} + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::SHINY, "shiny", "Shiny Sound"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::SHINY + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + + +// void search_alpha_roar_from_audio_dump(); + +void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // search_alpha_roar_from_audio_dump(); + // return; + + std::cout << "Running audio test program." << std::endl; + + std::shared_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::SHINY: + detector = std::make_shared(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "Not such sound detector as sound type " + std::to_string((size_t)type) + ); + return; + } + + InferenceSession session( + context, env.console, + {{*detector, std::chrono::milliseconds(20)}} + ); + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + +// A function used to search for the alpha roar on LA audio dump. +// But we didn't find the shound sound :P +void search_alpha_roar_from_audio_dump(){ + + const size_t SAMPLE_RATE = 48000; + + SpectrogramMatcher matcher( + "Alpha Roar", + AudioTemplateCache::instance().get_throw("PokemonBDSP/AlphaRoar", SAMPLE_RATE), + SpectrogramMatcher::Mode::RAW, SAMPLE_RATE, + 100.0 + ); + + // std::string file_listFile = "./scripts/short_audio_files.txt"; + std::string file_listFile = "1.txt"; + // std::string file_listFile = "./scripts/all_audio_files.txt"; + std::ifstream fin(file_listFile.c_str()); + std::vector file_list; + while(!fin.eof()){ + std::string line; + std::getline(fin, line); + file_list.push_back(line); + fin >> std::ws; + } + std::cout << "File num " << file_list.size() << std::endl; + + std::map closest_files; + + std::ofstream fout("file_check_output.txt"); + + for(size_t fileIdx = 0; fileIdx < file_list.size(); fileIdx++){ + matcher.clear(); + + + const auto& path = file_list[fileIdx]; + std::ostringstream os; + os << "File " << fileIdx << "/" << file_list.size() << " " << path << " "; + AudioTemplate audio = loadAudioTemplate(path); + if (audio.numWindows() == 0){ + os << "Fail" << std::endl; + fout << os.str(); + std::cout << os.str() << std::flush; + continue; + } + + // audio.scale(2.0); + + os << "#W " << audio.numWindows() << " "; + + // match! + float minScore = FLT_MAX; + std::vector new_spectrums; + size_t numStreamWindows = std::max(matcher.numMatchedWindows(), audio.numWindows()); + for(size_t audioIdx = 0; audioIdx < numStreamWindows; audioIdx++){ + new_spectrums.clear(); + AlignedVector freqVector(audio.numFrequencies()); + if (audioIdx < audio.numWindows()){ + const float * freq = audio.getWindow(audioIdx); + memcpy(freqVector.data(), freq, sizeof(float) * audio.numFrequencies()); + }else{ + // add zero-freq window + } + new_spectrums.emplace_back( + audioIdx, SAMPLE_RATE, + std::make_unique>(std::move(freqVector)) + ); + float score = matcher.match(new_spectrums); + minScore = std::min(score, minScore); + } // end audio Idx + + os << "dist " << minScore << std::endl; + fout << os.str(); + std::cout << os.str() << std::flush; + + closest_files.emplace(minScore, path); + } + + fout.close(); + + auto it = closest_files.begin(); + std::cout << "--------------" << std::endl; + fout.open("file_check_output_sorted.txt"); + for(int i = 0; it != closest_files.end(); i++, it++){ + if (i < 40) + std::cout << it->first << ", " << it->second << std::endl; + fout << it->first << ", " << it->second << std::endl; + } + fout.close(); + return; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.h b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.h index 585edea8a4..46130f35c3 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/TestPrograms/PokemonBDSP_SoundListener.h @@ -1,48 +1,48 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonBDSP_SoundListener_H -#define PokemonAutomation_PokemonBDSP_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - enum class SoundType{ - SHINY, - }; - - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonBDSP_SoundListener_H +#define PokemonAutomation_PokemonBDSP_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + enum class SoundType{ + SHINY, + }; + + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.cpp index 34bfe06fba..9962a9ae5f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.cpp @@ -1,81 +1,81 @@ -/* Self Box Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_TradeRoutines.h" -#include "PokemonBDSP_SelfBoxTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -SelfBoxTrade_Descriptor::SelfBoxTrade_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonBDSP:SelfBoxTrade", - STRING_POKEMON + " BDSP", "Self Box Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/SelfBoxTrade.md", - "Trade boxes of " + STRING_POKEMON + " between two local Switches.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 2, 2, 2 - ) -{} -std::unique_ptr SelfBoxTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new TradeStats()); -} - - - -SelfBoxTrade::SelfBoxTrade() - : BOXES_TO_TRADE( - "Number of Boxes to Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 40 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void SelfBoxTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - TradeStats& stats = env.current_stats(); - env.update_stats(); - - for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ - if (box != 0){ - env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); - }); - } - trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats); - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Self Box Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_TradeRoutines.h" +#include "PokemonBDSP_SelfBoxTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +SelfBoxTrade_Descriptor::SelfBoxTrade_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonBDSP:SelfBoxTrade", + STRING_POKEMON + " BDSP", "Self Box Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/SelfBoxTrade.md", + "Trade boxes of " + STRING_POKEMON + " between two local Switches.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 2, 2, 2 + ) +{} +std::unique_ptr SelfBoxTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new TradeStats()); +} + + + +SelfBoxTrade::SelfBoxTrade() + : BOXES_TO_TRADE( + "Number of Boxes to Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 40 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void SelfBoxTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + TradeStats& stats = env.current_stats(); + env.update_stats(); + + for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ + if (box != 0){ + env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); + }); + } + trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats); + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.h b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.h index a1d5a23c71..470d953d2f 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfBoxTrade.h @@ -1,44 +1,44 @@ -/* Self Box Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_SelfBoxTrade_H -#define PokemonAutomation_PokemonBDSP_SelfBoxTrade_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class SelfBoxTrade_Descriptor : public MultiSwitchProgramDescriptor{ -public: - SelfBoxTrade_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class SelfBoxTrade : public MultiSwitchProgramInstance{ -public: - SelfBoxTrade(); - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - SimpleIntegerOption BOXES_TO_TRADE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Self Box Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_SelfBoxTrade_H +#define PokemonAutomation_PokemonBDSP_SelfBoxTrade_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class SelfBoxTrade_Descriptor : public MultiSwitchProgramDescriptor{ +public: + SelfBoxTrade_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class SelfBoxTrade : public MultiSwitchProgramInstance{ +public: + SelfBoxTrade(); + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + SimpleIntegerOption BOXES_TO_TRADE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.cpp index 22a99e2841..9625dc05c9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.cpp @@ -1,99 +1,99 @@ -/* Self Touch Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_TradeRoutines.h" -#include "PokemonBDSP_SelfTouchTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - -SelfTouchTrade_Descriptor::SelfTouchTrade_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonBDSP:SelfTouchTrade", - STRING_POKEMON + " BDSP", "Self Touch Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/SelfTouchTrade.md", - "Touch trade boxes of " + STRING_POKEMON + " between two local Switches.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 2, 2, 2 - ) -{} -std::unique_ptr SelfTouchTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new TradeStats()); -} - - -SelfTouchTrade::SelfTouchTrade() - : HOSTING_SWITCH( - "Host Switch:
This is the Switch hosting the " + STRING_POKEMON + " to be touch-traded to the other.", - { - {HostingSwitch::Switch0, "switch0", "Switch 0 (Left)"}, - {HostingSwitch::Switch1, "switch1", "Switch 1 (Right)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - HostingSwitch::Switch0 - ) - , BOXES_TO_TRADE( - "Number of Boxes to Touch-Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 40 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(HOSTING_SWITCH); - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void SelfTouchTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - TradeStats& stats = env.current_stats(); - env.update_stats(); - - size_t host_index = HOSTING_SWITCH == HostingSwitch::Switch0 ? 0 : 1; - ProControllerContext host(scope, env.consoles[host_index].pro_controller()); - - // Swap trade all the boxes. - for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ - if (box != 0){ - pbf_press_button(host, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); - } - trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats); - } - - // Trade back the last box. - for (uint8_t box = 1; box < BOXES_TO_TRADE; box++){ - pbf_press_button(host, BUTTON_L, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); - } - trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats); - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Self Touch Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_TradeRoutines.h" +#include "PokemonBDSP_SelfTouchTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + +SelfTouchTrade_Descriptor::SelfTouchTrade_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonBDSP:SelfTouchTrade", + STRING_POKEMON + " BDSP", "Self Touch Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonBDSP/SelfTouchTrade.md", + "Touch trade boxes of " + STRING_POKEMON + " between two local Switches.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 2, 2, 2 + ) +{} +std::unique_ptr SelfTouchTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new TradeStats()); +} + + +SelfTouchTrade::SelfTouchTrade() + : HOSTING_SWITCH( + "Host Switch:
This is the Switch hosting the " + STRING_POKEMON + " to be touch-traded to the other.", + { + {HostingSwitch::Switch0, "switch0", "Switch 0 (Left)"}, + {HostingSwitch::Switch1, "switch1", "Switch 1 (Right)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + HostingSwitch::Switch0 + ) + , BOXES_TO_TRADE( + "Number of Boxes to Touch-Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 40 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(HOSTING_SWITCH); + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void SelfTouchTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + TradeStats& stats = env.current_stats(); + env.update_stats(); + + size_t host_index = HOSTING_SWITCH == HostingSwitch::Switch0 ? 0 : 1; + ProControllerContext host(scope, env.consoles[host_index].pro_controller()); + + // Swap trade all the boxes. + for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ + if (box != 0){ + pbf_press_button(host, BUTTON_R, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); + } + trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats); + } + + // Trade back the last box. + for (uint8_t box = 1; box < BOXES_TO_TRADE; box++){ + pbf_press_button(host, BUTTON_L, 160ms, GameSettings::instance().BOX_CHANGE_DELAY0); + } + trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats); + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.h b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.h index a25142cd66..505d25bbb9 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_SelfTouchTrade.h @@ -1,50 +1,50 @@ -/* Self Touch Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_SelfTouchTrade_H -#define PokemonAutomation_PokemonBDSP_SelfTouchTrade_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -class SelfTouchTrade_Descriptor : public MultiSwitchProgramDescriptor{ -public: - SelfTouchTrade_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class SelfTouchTrade : public MultiSwitchProgramInstance{ -public: - SelfTouchTrade(); - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - enum class HostingSwitch{ - Switch0, - Switch1 - }; - EnumDropdownOption HOSTING_SWITCH; - SimpleIntegerOption BOXES_TO_TRADE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Self Touch Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_SelfTouchTrade_H +#define PokemonAutomation_PokemonBDSP_SelfTouchTrade_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +class SelfTouchTrade_Descriptor : public MultiSwitchProgramDescriptor{ +public: + SelfTouchTrade_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class SelfTouchTrade : public MultiSwitchProgramInstance{ +public: + SelfTouchTrade(); + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + enum class HostingSwitch{ + Switch0, + Switch1 + }; + EnumDropdownOption HOSTING_SWITCH; + SimpleIntegerOption BOXES_TO_TRADE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.cpp b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.cpp index c08d895c01..a957fe07cd 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.cpp @@ -1,167 +1,167 @@ -/* Trade Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonBDSP/PokemonBDSP_Settings.h" -#include "PokemonBDSP_TradeRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - - -TradeStats::TradeStats() - : m_trades(m_stats["Trades"]) - , m_errors(m_stats["Errors"]) -{ - m_display_order.emplace_back("Trades"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); -} - - -void trade_current_pokemon( - VideoStream& stream, ProControllerContext& context, - MultiConsoleErrorState& tracker, - TradeStats& stats -){ - tracker.check_unrecoverable_error(stream.logger()); - - context.wait_for_all_requests(); - VideoSnapshot box_image = stream.video().snapshot(); - ImageMatchWatcher box_detector(std::move(box_image.frame), {0.02, 0.10, 0.15, 0.80}, 50); - -// pbf_press_button(context, BUTTON_ZL, 20, 0); - -#if 0 - while (true){ - context.wait_for_all_requests(); - SelectionArrowFinder detector0(stream, {0.50, 0.58, 0.40, 0.10}, COLOR_RED); - SelectionArrowFinder detector1(stream, {0.50, 0.52, 0.40, 0.10}, COLOR_RED); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_ZL, 20 * TICKS_PER_SECOND); - }, - {detector0, detector1} - ); - switch (ret){ - case 0: - stream.log("Detected trade prompt."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream); - pbf_press_button(context, BUTTON_ZL, 20, 0); - continue; - case 1: - stream.log("Detected trade confirm prompt."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream); - pbf_press_button(context, BUTTON_ZL, 20, 0); - break; - default: - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect a prompt after 20 seconds."); - } - break; - } -#endif - - // Start trade. -// pbf_press_button(context, BUTTON_ZL, 20, 0); - - // Wait for black screen. - { - BlackScreenOverWatcher black_screen; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_ZL, 120 * TICKS_PER_SECOND); - }, - {{black_screen}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect start of trade after 2 minutes."); - } - stream.log("Detected start of trade."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - - // Mash B until 2nd black screen. - { - BlackScreenWatcher black_screen; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - {{black_screen}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect end of trade after 2 minutes."); - } - stream.log("Detected end of trade."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - - // Wait to return to box. - { - int ret = wait_until( - stream, context, std::chrono::minutes(2), - {{box_detector}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to return to box after 2 minutes after a trade."); - } - stream.log("Detected box. Trade completed."); - tracker.check_unrecoverable_error(stream.logger()); - } -} - - -void trade_current_box( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - EventNotificationOption& notifications, - TradeStats& stats -){ - for (size_t row = 0; row < 5; row++){ - for (size_t col = 0; col < 6; col++){ - env.update_stats(); - send_program_status_notification(env, notifications); - - MultiConsoleErrorState error_state; - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - Milliseconds box_scroll_delay = GameSettings::instance().BOX_SCROLL_DELAY0; - for (size_t r = 0; r < row; r++){ - pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); - } - for (size_t c = 0; c < col; c++){ - pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); - } - trade_current_pokemon(console, context, error_state, stats); - }); - stats.m_trades++; - } - } -} - - - - - -} -} -} +/* Trade Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonBDSP/PokemonBDSP_Settings.h" +#include "PokemonBDSP_TradeRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + + +TradeStats::TradeStats() + : m_trades(m_stats["Trades"]) + , m_errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Trades"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); +} + + +void trade_current_pokemon( + VideoStream& stream, ProControllerContext& context, + MultiConsoleErrorState& tracker, + TradeStats& stats +){ + tracker.check_unrecoverable_error(stream.logger()); + + context.wait_for_all_requests(); + VideoSnapshot box_image = stream.video().snapshot(); + ImageMatchWatcher box_detector(std::move(box_image.frame), {0.02, 0.10, 0.15, 0.80}, 50); + +// pbf_press_button(context, BUTTON_ZL, 20, 0); + +#if 0 + while (true){ + context.wait_for_all_requests(); + SelectionArrowFinder detector0(stream, {0.50, 0.58, 0.40, 0.10}, COLOR_RED); + SelectionArrowFinder detector1(stream, {0.50, 0.52, 0.40, 0.10}, COLOR_RED); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_ZL, 20 * TICKS_PER_SECOND); + }, + {detector0, detector1} + ); + switch (ret){ + case 0: + stream.log("Detected trade prompt."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream); + pbf_press_button(context, BUTTON_ZL, 20, 0); + continue; + case 1: + stream.log("Detected trade confirm prompt."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream); + pbf_press_button(context, BUTTON_ZL, 20, 0); + break; + default: + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect a prompt after 20 seconds."); + } + break; + } +#endif + + // Start trade. +// pbf_press_button(context, BUTTON_ZL, 20, 0); + + // Wait for black screen. + { + BlackScreenOverWatcher black_screen; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_ZL, 120 * TICKS_PER_SECOND); + }, + {{black_screen}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect start of trade after 2 minutes."); + } + stream.log("Detected start of trade."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + + // Mash B until 2nd black screen. + { + BlackScreenWatcher black_screen; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + {{black_screen}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect end of trade after 2 minutes."); + } + stream.log("Detected end of trade."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + + // Wait to return to box. + { + int ret = wait_until( + stream, context, std::chrono::minutes(2), + {{box_detector}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to return to box after 2 minutes after a trade."); + } + stream.log("Detected box. Trade completed."); + tracker.check_unrecoverable_error(stream.logger()); + } +} + + +void trade_current_box( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + EventNotificationOption& notifications, + TradeStats& stats +){ + for (size_t row = 0; row < 5; row++){ + for (size_t col = 0; col < 6; col++){ + env.update_stats(); + send_program_status_notification(env, notifications); + + MultiConsoleErrorState error_state; + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + Milliseconds box_scroll_delay = GameSettings::instance().BOX_SCROLL_DELAY0; + for (size_t r = 0; r < row; r++){ + pbf_move_right_joystick(context, 128, 255, 160ms, box_scroll_delay); + } + for (size_t c = 0; c < col; c++){ + pbf_move_right_joystick(context, 255, 128, 160ms, box_scroll_delay); + } + trade_current_pokemon(console, context, error_state, stats); + }); + stats.m_trades++; + } + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.h b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.h index 29859ef89c..0660410cc2 100644 --- a/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.h +++ b/SerialPrograms/Source/PokemonBDSP/Programs/Trading/PokemonBDSP_TradeRoutines.h @@ -1,48 +1,48 @@ -/* Trade Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_TradeRoutines_H -#define PokemonAutomation_PokemonBDSP_TradeRoutines_H - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/MultiConsoleErrors.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - - -struct TradeStats : public StatsTracker{ - TradeStats(); - std::atomic& m_trades; - std::atomic& m_errors; -}; - - - - -void trade_current_pokemon( - VideoStream& stream, ProControllerContext& context, - MultiConsoleErrorState& tracker, - TradeStats& stats -); -void trade_current_box( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - EventNotificationOption& notifications, - TradeStats& stats -); - - - - -} -} -} -#endif +/* Trade Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_TradeRoutines_H +#define PokemonAutomation_PokemonBDSP_TradeRoutines_H + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/MultiConsoleErrors.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + + +struct TradeStats : public StatsTracker{ + TradeStats(); + std::atomic& m_trades; + std::atomic& m_errors; +}; + + + + +void trade_current_pokemon( + VideoStream& stream, ProControllerContext& context, + MultiConsoleErrorState& tracker, + TradeStats& stats +); +void trade_current_box( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + EventNotificationOption& notifications, + TradeStats& stats +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.cpp b/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.cpp index f64e09c784..85ccedf625 100644 --- a/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.cpp +++ b/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.cpp @@ -1,71 +1,71 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "PokemonBDSP_NameDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - -using namespace Pokemon; - - - -StringSelectDatabase make_name_database(const std::vector& slugs){ - const SpriteDatabase& sprites = PokemonSwSh::ALL_POKEMON_SPRITES(); - - StringSelectDatabase database; - for (const std::string& slug : slugs){ - const PokemonNames& name = get_pokemon_name(slug); - const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); - if (sprite){ - database.add_entry(StringSelectEntry( - slug, - name.display_name(), - sprite->icon - )); - }else{ - global_logger_tagged().log("No sprite for: " + slug); - database.add_entry(StringSelectEntry( - slug, - name.display_name() - )); - } - } - return database; -} -StringSelectDatabase make_name_database(const char* json_file_slugs){ - return make_name_database(load_pokemon_slug_json_list(json_file_slugs)); -} - - - -StringSelectDatabase make_ALL_POKEMON_NAMES(){ - std::vector slugs = load_pokemon_slug_json_list("Pokemon/Pokedex/Pokedex-National.json"); - if (slugs.size() < 493){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Expected national dex to be greater than 493 members.", - "Pokemon/Pokedex/Pokedex-National.json" - ); - } - slugs.resize(493); - return make_name_database(slugs); -} -const StringSelectDatabase& ALL_POKEMON_NAMES(){ - static const StringSelectDatabase database = make_ALL_POKEMON_NAMES(); - return database; -} - - - -} -} -} +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "PokemonBDSP_NameDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + +using namespace Pokemon; + + + +StringSelectDatabase make_name_database(const std::vector& slugs){ + const SpriteDatabase& sprites = PokemonSwSh::ALL_POKEMON_SPRITES(); + + StringSelectDatabase database; + for (const std::string& slug : slugs){ + const PokemonNames& name = get_pokemon_name(slug); + const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); + if (sprite){ + database.add_entry(StringSelectEntry( + slug, + name.display_name(), + sprite->icon + )); + }else{ + global_logger_tagged().log("No sprite for: " + slug); + database.add_entry(StringSelectEntry( + slug, + name.display_name() + )); + } + } + return database; +} +StringSelectDatabase make_name_database(const char* json_file_slugs){ + return make_name_database(load_pokemon_slug_json_list(json_file_slugs)); +} + + + +StringSelectDatabase make_ALL_POKEMON_NAMES(){ + std::vector slugs = load_pokemon_slug_json_list("Pokemon/Pokedex/Pokedex-National.json"); + if (slugs.size() < 493){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Expected national dex to be greater than 493 members.", + "Pokemon/Pokedex/Pokedex-National.json" + ); + } + slugs.resize(493); + return make_name_database(slugs); +} +const StringSelectDatabase& ALL_POKEMON_NAMES(){ + static const StringSelectDatabase database = make_ALL_POKEMON_NAMES(); + return database; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h b/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h index d1746825d3..e58c8dadaf 100644 --- a/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h +++ b/SerialPrograms/Source/PokemonBDSP/Resources/PokemonBDSP_NameDatabase.h @@ -1,28 +1,28 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonBDSP_NameDatabase_H -#define PokemonAutomation_PokemonBDSP_NameDatabase_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonBDSP{ - - -StringSelectDatabase make_name_database(const std::vector& slugs); -StringSelectDatabase make_name_database(const char* json_file_slugs); - -const StringSelectDatabase& ALL_POKEMON_NAMES(); - - - - -} -} -} -#endif +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonBDSP_NameDatabase_H +#define PokemonAutomation_PokemonBDSP_NameDatabase_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonBDSP{ + + +StringSelectDatabase make_name_database(const std::vector& slugs); +StringSelectDatabase make_name_database(const char* json_file_slugs); + +const StringSelectDatabase& ALL_POKEMON_NAMES(); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp index 611eea9c30..914ce7c508 100644 --- a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp +++ b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.cpp @@ -1,67 +1,67 @@ -/* Ball Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" -#include "PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h" -#include "PokemonHome_BallReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - -const double BallReader::MAX_ALPHA = 0.40; -const double BallReader::ALPHA_SPREAD = 0.02; - - -const PokemonBDSP::PokeballSpriteMatcher& BALL_SPRITE_MATCHER(){ - static PokemonBDSP::PokeballSpriteMatcher matcher; - return matcher; -} - - - -BallReader::BallReader(VideoStream& stream) - : m_matcher(BALL_SPRITE_MATCHER()) - , m_stream(stream) - , m_box_sprite(stream.overlay(), {0.228, 0.095, 0.030, 0.049}) -{} - - - -std::string BallReader::read_ball(const ImageViewRGB32& screen) const{ - if (!screen){ - return ""; - } - - ImageMatch::ImageMatchResult sprite_result; - { - ImageViewRGB32 image = extract_box_reference(screen, m_box_sprite); - sprite_result = m_matcher.match(image, ALPHA_SPREAD); - sprite_result.log(m_stream.logger(), 0.50); - if (!sprite_result.results.empty() && sprite_result.results.begin()->first > MAX_ALPHA){ - sprite_result.results.clear(); - } - } - - if (sprite_result.results.size() != 1){ - dump_image(m_stream.logger(), ProgramInfo(), "BallReader", screen); - } - if (sprite_result.results.empty()){ - return ""; - } - - return sprite_result.results.begin()->second; -} - - - -} -} -} +/* Ball Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" +#include "PokemonBDSP/Inference/PokemonBDSP_PokeballSpriteMatcher.h" +#include "PokemonHome_BallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +const double BallReader::MAX_ALPHA = 0.40; +const double BallReader::ALPHA_SPREAD = 0.02; + + +const PokemonBDSP::PokeballSpriteMatcher& BALL_SPRITE_MATCHER(){ + static PokemonBDSP::PokeballSpriteMatcher matcher; + return matcher; +} + + + +BallReader::BallReader(VideoStream& stream) + : m_matcher(BALL_SPRITE_MATCHER()) + , m_stream(stream) + , m_box_sprite(stream.overlay(), {0.228, 0.095, 0.030, 0.049}) +{} + + + +std::string BallReader::read_ball(const ImageViewRGB32& screen) const{ + if (!screen){ + return ""; + } + + ImageMatch::ImageMatchResult sprite_result; + { + ImageViewRGB32 image = extract_box_reference(screen, m_box_sprite); + sprite_result = m_matcher.match(image, ALPHA_SPREAD); + sprite_result.log(m_stream.logger(), 0.50); + if (!sprite_result.results.empty() && sprite_result.results.begin()->first > MAX_ALPHA){ + sprite_result.results.clear(); + } + } + + if (sprite_result.results.size() != 1){ + dump_image(m_stream.logger(), ProgramInfo(), "BallReader", screen); + } + if (sprite_result.results.empty()){ + return ""; + } + + return sprite_result.results.begin()->second; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h index a844692685..9072d7de2f 100644 --- a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h +++ b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BallReader.h @@ -1,42 +1,42 @@ -/* Ball Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_BallReader_H -#define PokemonAutomation_PokemonHome_BallReader_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - -class BallReader{ - static const double MAX_ALPHA; - static const double ALPHA_SPREAD; - -public: - BallReader(VideoStream& stream); - -public: - std::string read_ball(const ImageViewRGB32& screen) const; - -private: - const ImageMatch::CroppedImageDictionaryMatcher& m_matcher; - VideoStream& m_stream; - OverlayBoxScope m_box_sprite; -}; - - - - -} -} -} -#endif +/* Ball Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_BallReader_H +#define PokemonAutomation_PokemonHome_BallReader_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +class BallReader{ + static const double MAX_ALPHA; + static const double ALPHA_SPREAD; + +public: + BallReader(VideoStream& stream); + +public: + std::string read_ball(const ImageViewRGB32& screen) const; + +private: + const ImageMatch::CroppedImageDictionaryMatcher& m_matcher; + VideoStream& m_stream; + OverlayBoxScope m_box_sprite; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp index 9c96beda12..3f99304897 100644 --- a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp +++ b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.cpp @@ -1,72 +1,72 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonHome_BoxGenderDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - -namespace{ - ImageFloatBox GENDER_BOX{0.417, 0.097, 0.031, 0.046}; -} - -void BoxGenderDetector::make_overlays(VideoOverlaySet& items){ - items.add(COLOR_RED, GENDER_BOX); -} - -Pokemon::StatsHuntGenderFilter BoxGenderDetector::detect(const ImageViewRGB32& screen){ - const auto region = extract_box_reference(screen, GENDER_BOX); - - // Retain only red pixels from region - const bool replace_color_within_range = false; - const ImageRGB32 red_region = filter_rgb32_range( - region, - combine_rgb(150, 0, 0), combine_rgb(255, 100, 100), Color(0), replace_color_within_range - ); - const size_t num_red_pixels = image_stats(red_region).count; - - // Retain only blue pixels from region - const ImageRGB32 blue_region = filter_rgb32_range( - region, - combine_rgb(0, 0, 150), combine_rgb(100, 100, 255), Color(0), replace_color_within_range - ); - const size_t num_blue_pixels = image_stats(blue_region).count; - - if (PreloadSettings::debug().COLOR_CHECK){ - cout << "num_red_pixels: " << num_red_pixels << ", num_blue_pixels: " << num_blue_pixels - << ", region " << region.width() << " x " << region.height() << endl; - - cout << "Save images to ./red_only.png and ./blue_only.png" << endl; - red_region.save("./red_only.png"); - blue_region.save("./blue_only.png"); - } - - const size_t threshold = region.width() * region.height() / 100; - - if (num_red_pixels > threshold){ - return Pokemon::StatsHuntGenderFilter::Female; - }else if (num_blue_pixels > threshold){ - return Pokemon::StatsHuntGenderFilter::Male; - } - return Pokemon::StatsHuntGenderFilter::Genderless; -} - -} -} -} +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonHome_BoxGenderDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + +namespace{ + ImageFloatBox GENDER_BOX{0.417, 0.097, 0.031, 0.046}; +} + +void BoxGenderDetector::make_overlays(VideoOverlaySet& items){ + items.add(COLOR_RED, GENDER_BOX); +} + +Pokemon::StatsHuntGenderFilter BoxGenderDetector::detect(const ImageViewRGB32& screen){ + const auto region = extract_box_reference(screen, GENDER_BOX); + + // Retain only red pixels from region + const bool replace_color_within_range = false; + const ImageRGB32 red_region = filter_rgb32_range( + region, + combine_rgb(150, 0, 0), combine_rgb(255, 100, 100), Color(0), replace_color_within_range + ); + const size_t num_red_pixels = image_stats(red_region).count; + + // Retain only blue pixels from region + const ImageRGB32 blue_region = filter_rgb32_range( + region, + combine_rgb(0, 0, 150), combine_rgb(100, 100, 255), Color(0), replace_color_within_range + ); + const size_t num_blue_pixels = image_stats(blue_region).count; + + if (PreloadSettings::debug().COLOR_CHECK){ + cout << "num_red_pixels: " << num_red_pixels << ", num_blue_pixels: " << num_blue_pixels + << ", region " << region.width() << " x " << region.height() << endl; + + cout << "Save images to ./red_only.png and ./blue_only.png" << endl; + red_region.save("./red_only.png"); + blue_region.save("./blue_only.png"); + } + + const size_t threshold = region.width() * region.height() / 100; + + if (num_red_pixels > threshold){ + return Pokemon::StatsHuntGenderFilter::Female; + }else if (num_blue_pixels > threshold){ + return Pokemon::StatsHuntGenderFilter::Male; + } + return Pokemon::StatsHuntGenderFilter::Genderless; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h index 59797d6c18..51c48cf92e 100644 --- a/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h +++ b/SerialPrograms/Source/PokemonHome/Inference/PokemonHome_BoxGenderDetector.h @@ -1,34 +1,34 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_BoxGenderDetector_H -#define PokemonAutomation_PokemonHome_BoxGenderDetector_H - -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class VideoOverlaySet; - -namespace NintendoSwitch{ -namespace PokemonHome{ - -// Detect gender symbol inside the pokemon storage box -class BoxGenderDetector{ -public: - static void make_overlays(VideoOverlaySet& items); - - static Pokemon::StatsHuntGenderFilter detect(const ImageViewRGB32& screen); -}; - - - -} -} -} - -#endif +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_BoxGenderDetector_H +#define PokemonAutomation_PokemonHome_BoxGenderDetector_H + +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class VideoOverlaySet; + +namespace NintendoSwitch{ +namespace PokemonHome{ + +// Detect gender symbol inside the pokemon storage box +class BoxGenderDetector{ +public: + static void make_overlays(VideoOverlaySet& items); + + static Pokemon::StatsHuntGenderFilter detect(const ImageViewRGB32& screen); +}; + + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.cpp b/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.cpp index 56bc05643a..d70bb2d0a6 100644 --- a/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.cpp +++ b/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.cpp @@ -1,98 +1,98 @@ -/* Box Sorter Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonHome_BoxSortingTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - -const EnumDropdownDatabase& BallType_Database(){ - static const EnumDropdownDatabase database({ - {BoxSortingSortType::NationalDexNo, "dex", "National Dex Number"}, - {BoxSortingSortType::Shiny, "shiny", "Shiny"}, - {BoxSortingSortType::Gigantamax, "gigantamax", "Gigantamax"}, - {BoxSortingSortType::Ball_Slug, "ball_slug", "Ball Type"}, - {BoxSortingSortType::Gender, "gender", "Gender (Male, Female, Genderless)"}, - }); - return database; -} - - - -BoxSortingRow::BoxSortingRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , sort_type(BallType_Database(), LockMode::LOCK_WHILE_RUNNING, BoxSortingSortType::NationalDexNo) - , reverse(LockMode::LOCK_WHILE_RUNNING, false) -{ - PA_ADD_OPTION(sort_type); - PA_ADD_OPTION(reverse); -} -std::unique_ptr BoxSortingRow::clone() const{ - std::unique_ptr ret(new BoxSortingRow(parent())); - ret->sort_type.set_value(sort_type.current_value()); - ret->reverse = reverse.current_value(); - return ret; -} - - -BoxSortingTable::BoxSortingTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - - -std::vector BoxSortingTable::preferences() const{ - std::vector> table = copy_snapshot(); - std::vector selections; - for (const std::unique_ptr& row : table){ - BoxSortingSelection selection; - selection.sort_type = BoxSortingSortType(row->sort_type.current_value()); - selection.reverse = row->reverse.current_value(); - - selections.emplace_back(selection); - } - return selections; -} - - - - -std::vector BoxSortingTable::make_header() const{ - return std::vector{ - "Criteria", "Reverse", - }; -} - -std::vector> BoxSortingTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} - - - - - - - - - - - - - - - - - -} -} -} +/* Box Sorter Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonHome_BoxSortingTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +const EnumDropdownDatabase& BallType_Database(){ + static const EnumDropdownDatabase database({ + {BoxSortingSortType::NationalDexNo, "dex", "National Dex Number"}, + {BoxSortingSortType::Shiny, "shiny", "Shiny"}, + {BoxSortingSortType::Gigantamax, "gigantamax", "Gigantamax"}, + {BoxSortingSortType::Ball_Slug, "ball_slug", "Ball Type"}, + {BoxSortingSortType::Gender, "gender", "Gender (Male, Female, Genderless)"}, + }); + return database; +} + + + +BoxSortingRow::BoxSortingRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , sort_type(BallType_Database(), LockMode::LOCK_WHILE_RUNNING, BoxSortingSortType::NationalDexNo) + , reverse(LockMode::LOCK_WHILE_RUNNING, false) +{ + PA_ADD_OPTION(sort_type); + PA_ADD_OPTION(reverse); +} +std::unique_ptr BoxSortingRow::clone() const{ + std::unique_ptr ret(new BoxSortingRow(parent())); + ret->sort_type.set_value(sort_type.current_value()); + ret->reverse = reverse.current_value(); + return ret; +} + + +BoxSortingTable::BoxSortingTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + + +std::vector BoxSortingTable::preferences() const{ + std::vector> table = copy_snapshot(); + std::vector selections; + for (const std::unique_ptr& row : table){ + BoxSortingSelection selection; + selection.sort_type = BoxSortingSortType(row->sort_type.current_value()); + selection.reverse = row->reverse.current_value(); + + selections.emplace_back(selection); + } + return selections; +} + + + + +std::vector BoxSortingTable::make_header() const{ + return std::vector{ + "Criteria", "Reverse", + }; +} + +std::vector> BoxSortingTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.h b/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.h index f2551f9e26..0af785f199 100644 --- a/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.h +++ b/SerialPrograms/Source/PokemonHome/Options/PokemonHome_BoxSortingTable.h @@ -1,64 +1,64 @@ -/* Cram-o-matic Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_BoxSortingTable_H -#define PokemonAutomation_PokemonHome_BoxSortingTable_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - -enum class BoxSortingSortType -{ - NationalDexNo, - Shiny, - Gigantamax, - Ball_Slug, - Gender, -}; - -struct BoxSortingSelection -{ - BoxSortingSortType sort_type; - bool reverse; -}; - -class BoxSortingRow : public EditableTableRow{ -public: - BoxSortingRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const; - -public: - EnumDropdownCell sort_type; - BooleanCheckBoxCell reverse; -}; - - - -class BoxSortingTable : public EditableTableOption_t{ -public: - BoxSortingTable(std::string label); - - std::vector preferences() const; - - virtual std::vector make_header() const; - - std::vector> make_defaults(); -}; - - - - - -} -} -} -#endif +/* Cram-o-matic Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_BoxSortingTable_H +#define PokemonAutomation_PokemonHome_BoxSortingTable_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + +enum class BoxSortingSortType +{ + NationalDexNo, + Shiny, + Gigantamax, + Ball_Slug, + Gender, +}; + +struct BoxSortingSelection +{ + BoxSortingSortType sort_type; + bool reverse; +}; + +class BoxSortingRow : public EditableTableRow{ +public: + BoxSortingRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const; + +public: + EnumDropdownCell sort_type; + BooleanCheckBoxCell reverse; +}; + + + +class BoxSortingTable : public EditableTableOption_t{ +public: + BoxSortingTable(std::string label); + + std::vector preferences() const; + + virtual std::vector make_header() const; + + std::vector> make_defaults(); +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.cpp b/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.cpp index 8421820824..8ca504b8d7 100644 --- a/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.cpp +++ b/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.cpp @@ -1,54 +1,54 @@ -/* Pokemon Home Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonHome_Panels.h" - -#include "Programs/PokemonHome_PageSwap.h" -#include "Programs/PokemonHome_BoxSorting.h" - -#include "Programs/PokemonHome_GenerateNameOCR.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Home") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - -// ret.emplace_back("---- Settings ----"); -// ret.emplace_back(make_settings()); - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - -// ret.emplace_back("---- Trading ----"); - -// ret.emplace_back("---- Farming ----"); - -// ret.emplace_back("---- Shiny Hunting ----"); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} -} +/* Pokemon Home Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonHome_Panels.h" + +#include "Programs/PokemonHome_PageSwap.h" +#include "Programs/PokemonHome_BoxSorting.h" + +#include "Programs/PokemonHome_GenerateNameOCR.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Home") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + +// ret.emplace_back("---- Settings ----"); +// ret.emplace_back(make_settings()); + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + +// ret.emplace_back("---- Trading ----"); + +// ret.emplace_back("---- Farming ----"); + +// ret.emplace_back("---- Shiny Hunting ----"); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.h b/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.h index adc705aad5..2ebfb5bd90 100644 --- a/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.h +++ b/SerialPrograms/Source/PokemonHome/PokemonHome_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon Scarlet/Violet Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_Panels_H -#define PokemonAutomation_PokemonHome_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon Scarlet/Violet Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_Panels_H +#define PokemonAutomation_PokemonHome_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.cpp b/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.cpp index 470c067bb7..d4016f75c3 100644 --- a/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.cpp +++ b/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.cpp @@ -1,62 +1,62 @@ -/* Pokemon SV Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonHome_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) -{ -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonHome:GlobalSettings", - STRING_POKEMON + " Home", STRING_POKEMON + " Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonHome/PokemonSettings.md", - "Global " + STRING_POKEMON + " Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon SV Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonHome_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) +{ +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonHome:GlobalSettings", + STRING_POKEMON + " Home", STRING_POKEMON + " Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonHome/PokemonSettings.md", + "Global " + STRING_POKEMON + " Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.h b/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.h index 094cec1ebb..ca7bf9b3a5 100644 --- a/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.h +++ b/SerialPrograms/Source/PokemonHome/PokemonHome_Settings.h @@ -1,44 +1,44 @@ -/* Pokemon Home Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_Settings_H -#define PokemonAutomation_PokemonHome_Settings_H - -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon Home Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_Settings_H +#define PokemonAutomation_PokemonHome_Settings_H + +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.cpp b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.cpp index f3ea879cb1..53a3aed1d1 100644 --- a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.cpp +++ b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.cpp @@ -1,723 +1,723 @@ -/* Home Box Sorting - * - * From: https://github.com/PokemonAutomation/ - * - */ - -/* TODO ideas -break into smaller functions -read pokemon name and store the slug (easier to detect missread than reading a number) -Optimise the swapping algo -Add enum for ball ? Also, BDSP is reading from swsh data. Worth refactoring ? - -ideas for more checks : -ability -nature -type -original game -OT -moves -stats -level -surname -language -"stamps" -*/ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonHome/Inference/PokemonHome_BoxGenderDetector.h" -#include "PokemonHome/Inference/PokemonHome_BallReader.h" -#include "PokemonHome_BoxSorting.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ -using namespace Pokemon; - - -const size_t MAX_BOXES = 200; -const size_t MAX_COLUMNS = 6; -const size_t MAX_ROWS = 5; - -BoxSorting_Descriptor::BoxSorting_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonHome:BoxSorter", - STRING_POKEMON + " Home", "Box Sorter", - "ComputerControl/blob/master/Wiki/Programs/PokemonHome/BoxSorter.md", - "Order boxes of " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} -struct BoxSorting_Descriptor::Stats : public StatsTracker{ - Stats() - : pkmn(m_stats["Pokemon"]) - , empty(m_stats["Empty Slots"]) - , compare(m_stats["Compares"]) - , swaps(m_stats["Swaps"]) - { - m_display_order.emplace_back(Stat("Pokemon")); - m_display_order.emplace_back(Stat("Empty Slots")); - m_display_order.emplace_back(Stat("Compares")); - m_display_order.emplace_back(Stat("Swaps")); - } - std::atomic& pkmn; - std::atomic& empty; - std::atomic& compare; - std::atomic& swaps; -}; -std::unique_ptr BoxSorting_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -BoxSorting::BoxSorting() - : BOX_NUMBER( - "Number of boxes to order:", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, MAX_BOXES - ) - , VIDEO_DELAY( - "Delay of your capture card:", - LockMode::LOCK_WHILE_RUNNING, - 50 - ) - , GAME_DELAY( - "Delay of your Pokemon Home app:", - LockMode::LOCK_WHILE_RUNNING, - 30 - ) - , SORT_TABLE( - "Sort Order Rules:
Sort order rules will be applied top to bottom." - ) - , OUTPUT_FILE( - false, - "Output File:
JSON file for output of storage boxes.", - LockMode::LOCK_WHILE_RUNNING, - "box_order", - "box_order" - ) - , DRY_RUN( - "Dry Run:
Catalogue and make sort plan without executing. (Will output to OUTPUT_FILE and OUTPUT_FILE.sortplan)", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH - }) -{ - PA_ADD_OPTION(BOX_NUMBER); //number of box to check and sort - PA_ADD_OPTION(VIDEO_DELAY); //delay for every input that need video feedback, user will be able to modify this to enhance capture card delay compatibility - PA_ADD_OPTION(GAME_DELAY); //delay for non video feedback, this way I can go as fast as pokemon home can handle movement when needed - PA_ADD_OPTION(SORT_TABLE); - PA_ADD_OPTION(OUTPUT_FILE); - PA_ADD_OPTION(DRY_RUN); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -struct Cursor{ - size_t box; - size_t row; - size_t column; -}; - -std::ostream& operator<<(std::ostream& os, const Cursor& cursor){ - os << "(" << cursor.box << "/" << cursor.row << "/" << cursor.column << ")"; - return os; -} - -Cursor get_cursor(size_t index){ - Cursor ret; - - ret.column = index % MAX_COLUMNS; - index = index / MAX_COLUMNS; - - ret.row = index % MAX_ROWS; - index = index / MAX_ROWS; - - ret.box = index; - return ret; -} - -size_t get_index(size_t box, size_t row, size_t column){ - return box * MAX_ROWS * MAX_COLUMNS + row * MAX_COLUMNS + column; -} - - - -struct Pokemon{ - const std::vector* preferences; - - // When adding any new member here, do not forget to modify the operators below (ctrl-f "new struct members") - uint16_t national_dex_number = 0; - bool shiny = false; - bool gmax = false; - std::string ball_slug = ""; - StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; - uint32_t ot_id = 0; -}; - -bool operator==(const Pokemon& lhs, const Pokemon& rhs){ - // NOTE edit when adding new struct members - return lhs.national_dex_number == rhs.national_dex_number && - lhs.shiny == rhs.shiny && - lhs.gmax == rhs.gmax && - lhs.ball_slug == rhs.ball_slug && - lhs.gender == rhs.gender && - lhs.ot_id == rhs.ot_id; -} - -bool operator<(const std::optional& lhs, const std::optional& rhs){ - if (!lhs.has_value()){ - return false; - } - if (!rhs.has_value()){ - return true; - } - - for (const BoxSortingSelection preference : *lhs->preferences){ - std::optional ret{}; - switch(preference.sort_type){ - // NOTE edit when adding new struct members - case BoxSortingSortType::NationalDexNo: - if (lhs->national_dex_number != rhs->national_dex_number){ - ret = lhs->national_dex_number < rhs->national_dex_number; - } - break; - case BoxSortingSortType::Shiny: - if (lhs->shiny != rhs->shiny){ - ret = lhs->shiny; - } - break; - case BoxSortingSortType::Gigantamax: - if (lhs->gmax != rhs->gmax){ - ret = lhs->gmax; - } - break; - case BoxSortingSortType::Ball_Slug: - if (lhs->ball_slug < rhs->ball_slug){ - ret = true; - } - if (lhs->ball_slug > rhs->ball_slug){ - ret = false; - } - break; - case BoxSortingSortType::Gender: - if (lhs->gender < rhs->gender){ - ret = true; - } - if (lhs->gender > rhs->gender){ - ret = false; - } - break; - } - if (ret.has_value()){ - bool value = *ret; - if (preference.reverse){ - return !value; - }else{ - return value; - } - } - } - - return lhs->national_dex_number < rhs->national_dex_number; -} - -std::ostream& operator<<(std::ostream& os, const std::optional& pokemon) -{ - if (pokemon.has_value()){ - // NOTE edit when adding new struct members - os << "("; - os << "national_dex_number:" << pokemon->national_dex_number << " "; - os << "shiny:" << (pokemon->shiny ? "true" : "false") << " "; - os << "gmax:" << (pokemon->gmax ? "true" : "false") << " "; - os << "ball_slug:" << pokemon->ball_slug << " "; - os << "gender:" << gender_to_string(pokemon->gender) << " "; - os << "ot_id:" << pokemon->ot_id << " "; - os << ")"; - }else{ - os << "(empty)"; - } - return os; -} - -bool go_to_first_slot(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint16_t VIDEO_DELAY){ - - ImageFloatBox cursor_check(0.07, 0.15, 0.01, 0.01); //cursor position of the first slot of the box - VideoSnapshot screen = env.console.video().snapshot(); - FloatPixel image_value = image_stats(extract_box_reference(screen, cursor_check)).average; - env.console.log("Cursor color detection: " + image_value.to_string()); - VideoOverlaySet BoxRender(env.console); - - BoxRender.add(COLOR_BLUE, cursor_check); - if(image_value.r <= image_value.g + image_value.b){ - - bool cursor_found = false; - - for (uint8_t rows = 0; rows < 7; rows++){ - for (uint8_t column = 0; column < 5; column++){ - pbf_press_dpad(context, DPAD_LEFT, 10, VIDEO_DELAY); - context.wait_for_all_requests(); - screen = env.console.video().snapshot(); - image_value = image_stats(extract_box_reference(screen, cursor_check)).average; - env.console.log("Cursor color detection: " + image_value.to_string()); - - if(image_value.r > image_value.g + image_value.b){ - cursor_found = true; - break; - } - } - if(!cursor_found){ - pbf_press_dpad(context, DPAD_UP, 10, VIDEO_DELAY); - context.wait_for_all_requests(); - screen = env.console.video().snapshot(); - image_value = image_stats(extract_box_reference(screen, cursor_check)).average; - env.console.log("Cursor color detection: " + image_value.to_string()); - - if(image_value.r > image_value.g + image_value.b){ - cursor_found = true; - break; - } - }else{ - break; - } - } - if(!cursor_found){ - return false; - } - } - BoxRender.clear(); - return true; -} - -//Move the cursor to the given coordinates, knowing current pos via the cursor struct -[[nodiscard]] Cursor move_cursor_to(SingleSwitchProgramEnvironment& env, ProControllerContext& context, const Cursor& cur_cursor, const Cursor& dest_cursor, uint16_t GAME_DELAY){ - - std::ostringstream ss; - ss << "Moving cursor from " << cur_cursor << " to " << dest_cursor; - env.console.log(ss.str()); - - // TODO: shortest path movement though pages, boxes - for (size_t i = cur_cursor.box; i < dest_cursor.box; ++i){ - pbf_press_button(context, BUTTON_R, 10, GAME_DELAY+30); - } - for (size_t i = dest_cursor.box; i < cur_cursor.box; ++i){ - pbf_press_button(context, BUTTON_L, 10, GAME_DELAY+30); - } - - - // direct nav up or down through rows - if (!(cur_cursor.row == 0 && dest_cursor.row == 4) && !(dest_cursor.row == 0 && cur_cursor.row == 4)){ - for (size_t i = cur_cursor.row; i < dest_cursor.row; ++i){ - pbf_press_dpad(context, DPAD_DOWN, 10, GAME_DELAY); - } - for (size_t i = dest_cursor.row; i < cur_cursor.row; ++i){ - pbf_press_dpad(context, DPAD_UP, 10, GAME_DELAY); - } - }else{ // wrap around is faster to move between first or last row - if (cur_cursor.row == 0 && dest_cursor.row == 4){ - for (size_t i = 0; i <= 2; ++i){ - pbf_press_dpad(context, DPAD_UP, 10, GAME_DELAY); - } - }else{ - for (size_t i = 0; i <= 2; ++i){ - pbf_press_dpad(context, DPAD_DOWN, 10, GAME_DELAY); - } - } - } - - // direct nav forward or backward through columns - if ((dest_cursor.column > cur_cursor.column && dest_cursor.column - cur_cursor.column <= 3) || (cur_cursor.column > dest_cursor.column && cur_cursor.column - dest_cursor.column <= 3)){ - for (size_t i = cur_cursor.column; i < dest_cursor.column; ++i){ - pbf_press_dpad(context, DPAD_RIGHT, 10, GAME_DELAY); - } - for (size_t i = dest_cursor.column; i < cur_cursor.column; ++i){ - pbf_press_dpad(context, DPAD_LEFT, 10, GAME_DELAY); - } - }else{ // wrap around is faster if direct movement is more than 3 away - if (dest_cursor.column > cur_cursor.column){ - for (size_t i = 0; i < MAX_COLUMNS - (dest_cursor.column - cur_cursor.column); ++i){ - pbf_press_dpad(context, DPAD_LEFT, 10, GAME_DELAY); - } - } - if (cur_cursor.column > dest_cursor.column){ - for (size_t i = 0; i < MAX_COLUMNS - (cur_cursor.column - dest_cursor.column); ++i){ - pbf_press_dpad(context, DPAD_RIGHT, 10, GAME_DELAY); - } - } - } - - context.wait_for_all_requests(); - return dest_cursor; -} - -void print_boxes_data(const std::vector>& boxes_data, SingleSwitchProgramEnvironment& env){ - std::ostringstream ss; - for (const std::optional& pokemon : boxes_data){ - ss << pokemon << "\n"; - } - env.console.log(ss.str()); -} - -void output_boxes_data_json(const std::vector>& boxes_data, const std::string& json_path){ - JsonArray pokemon_data; - for (size_t poke_nb = 0; poke_nb < boxes_data.size(); poke_nb++){ - Cursor cursor = get_cursor(poke_nb); - JsonObject pokemon; - pokemon["index"] = poke_nb; - pokemon["box"] = cursor.box; - pokemon["row"] = cursor.row; - pokemon["column"] = cursor.column; - if (std::optional current_pokemon = boxes_data[poke_nb]; current_pokemon != std::nullopt){ - // NOTE edit when adding new struct members - pokemon["national_dex_number"] = current_pokemon->national_dex_number; - pokemon["shiny"] = current_pokemon->shiny; - pokemon["gmax"] = current_pokemon->gmax; - pokemon["ball_slug"] = current_pokemon->ball_slug; - pokemon["gender"] = gender_to_string(current_pokemon->gender); - pokemon["ot_id"] = current_pokemon->ot_id; - } - pokemon_data.push_back(std::move(pokemon)); - } - pokemon_data.dump(json_path + ".json"); -} - -void do_sort( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - std::vector> boxes_data, - std::vector> boxes_sorted, - BoxSorting_Descriptor::Stats& stats, - Cursor& cur_cursor, - uint16_t GAME_DELAY - ){ - std::ostringstream ss; - // this need to be separated into functions when I will redo the whole thing but I just wanted it to work - - // going thru the sorted list one by one and for each one go through the current pokemon layout to find the closest possible match to fill the slot - for (size_t poke_nb_s = 0; poke_nb_s < boxes_sorted.size(); poke_nb_s++){ - if (boxes_sorted[poke_nb_s] == std::nullopt){ // we've hit the end of the sorted list. - break; - } - for (size_t poke_nb = poke_nb_s; poke_nb < boxes_data.size(); poke_nb++){ - Cursor cursor_s = get_cursor(poke_nb_s); - Cursor cursor = get_cursor(poke_nb); - - // ss << "Comparing " << boxes_data[poke_nb] << " at " << cursor << " to " << boxes_sorted[poke_nb_s] << " at " << cursor_s; - // env.console.log(ss.str()); - // ss.str(""); - - //check for a match and also check if the pokemon is not already in the slot - stats.compare++; - env.update_stats(); - if(boxes_sorted[poke_nb_s] == boxes_data[poke_nb] && poke_nb_s == poke_nb){ // Same spot no need to move. - break; - } - if(boxes_sorted[poke_nb_s] == boxes_data[poke_nb]){ - ss << "Swapping " << boxes_data[poke_nb] << " at " << cursor << " and " << boxes_sorted[poke_nb_s] << " at " << cursor_s; - env.console.log(ss.str()); - ss.str(""); - - //moving cursor to the pokemon to pick it up - cur_cursor = move_cursor_to(env, context, cur_cursor, cursor, GAME_DELAY); - pbf_press_button(context, BUTTON_Y, 10, GAME_DELAY+30); - - //moving to destination to place it or swap it - cur_cursor = move_cursor_to(env, context, cur_cursor, cursor_s, GAME_DELAY); - pbf_press_button(context, BUTTON_Y, 10, GAME_DELAY+30); - - context.wait_for_all_requests(); - - std::swap(boxes_data[poke_nb_s], boxes_data[poke_nb]); - stats.swaps++; - env.update_stats(); - - break; - } - } - } -} - -void BoxSorting::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - std::vector sort_preferences = SORT_TABLE.preferences(); - if (sort_preferences.empty()){ - throw UserSetupError(env.console, "At least one sorting method selection needs to be made!"); - } - - BoxSorting_Descriptor::Stats& stats = env.current_stats< BoxSorting_Descriptor::Stats>(); - - ImageFloatBox select_check(0.495, 0.0045, 0.01, 0.005); // square color to check which mode is active - ImageFloatBox national_dex_number_box(0.448, 0.245, 0.049, 0.04); //pokemon national dex number pos - ImageFloatBox shiny_symbol_box(0.702, 0.09, 0.04, 0.06); // shiny symbol pos - ImageFloatBox gmax_symbol_box(0.463, 0.09, 0.04, 0.06); // gmax symbol pos - ImageFloatBox origin_symbol_box(0.623, 0.095, 0.033, 0.05); // origin symbol pos - ImageFloatBox pokemon_box(0.69, 0.18, 0.28, 0.46); // pokemon render pos - ImageFloatBox level_box(0.546, 0.099, 0.044, 0.041); // Level box - ImageFloatBox ot_id_box(0.782, 0.719, 0.193, 0.046); // OT ID box - ImageFloatBox ot_box(0.492, 0.719, 0.165, 0.049); // OT box - ImageFloatBox nature_box(0.157, 0.783, 0.212, 0.042); // Nature box - ImageFloatBox ability_box(0.158, 0.838, 0.213, 0.042); // Ability box - - - // vector that will store data for each slot - std::vector> boxes_data; - - Cursor cur_cursor{static_cast(BOX_NUMBER-1), 0, 0}; - - VideoSnapshot screen = env.console.video().snapshot(); - - VideoOverlaySet box_render(env.console); - - std::ostringstream ss; - - FloatPixel image_value = image_stats(extract_box_reference(screen, select_check)).average; - - env.console.log("Color detected from the select square: " + image_value.to_string()); - - //if the correct color is not detected, getting out of every possible menu to make sure the program work no matter where you start it in your pokemon home - box_render.add(COLOR_BLUE, select_check); - if(image_value.r <= image_value.g + image_value.b){ - for (int var = 0; var < 5; ++var){ - pbf_press_button(context, BUTTON_B, 10, GAME_DELAY+10); - } - context.wait_for_all_requests(); - context.wait_for(std::chrono::milliseconds(VIDEO_DELAY)); - screen = env.console.video().snapshot(); - image_value = image_stats(extract_box_reference(screen, select_check)).average; - env.console.log("Color detected from the select square: " + image_value.to_string()); - if(image_value.r <= image_value.g + image_value.b){ - for (int i = 0; i < 2; ++i){ - pbf_press_button(context, BUTTON_ZR, 10, VIDEO_DELAY+30); //additional delay because this animation is slower than the rest - context.wait_for_all_requests(); - screen = env.console.video().snapshot(); - image_value = image_stats(extract_box_reference(screen, select_check)).average; - env.console.log("Color detected from the select square: " + image_value.to_string()); - if(image_value.r > image_value.g + image_value.b){ - break; - }else if(i==1){ - dump_image(env.console, ProgramInfo(), "SelectSquare", screen); - env.console.log("ERROR: Could not find correct color mode please check color logs and timings\n", COLOR_RED); - return; - } - } - } - } - - box_render.clear(); - - Cursor dest_cursor; - std::vector first_poke_slot; - Cursor nav_cursor = {0, 0, 0}; - bool find_first_poke; - - //cycle through each box - for (size_t box_nb = 0; box_nb < BOX_NUMBER; box_nb++){ - - if(box_nb != 0){ - pbf_press_button(context, BUTTON_R, 10, VIDEO_DELAY+100); - context.wait_for_all_requests(); - }else{ - // Moving the cursor until it goes to the first slot - if(!go_to_first_slot(env, context, VIDEO_DELAY)){ - env.console.log("ERROR: Could not move cursor to the first slot, please consider adjusting delay\n", COLOR_RED); - return; - } - context.wait_for_all_requests(); - } - - screen = env.console.video().snapshot(); - - // Box grid to find empty slots (red boxes) and fill boxes_data with value to check or not for pokemon dex number - - ss << "\n"; - - first_poke_slot = {0, 0}; - find_first_poke = false; - - for (size_t row = 0; row < MAX_ROWS; row++){ - - for (size_t column = 0; column < MAX_COLUMNS; column++){ - - ImageFloatBox slot_box(0.06 + (0.072 * column), 0.2 + (0.1035 * row), 0.03, 0.057); - int current_box_value = (int)image_stddev(extract_box_reference(screen, slot_box)).sum(); - - ss << current_box_value; - - //checking color to know if a pokemon is on the slot or not - if(current_box_value < 5){ - box_render.add(COLOR_RED, slot_box); - stats.empty++; - env.update_stats(); - boxes_data.push_back(std::nullopt); //empty optional to make sorting easier later - ss << "\u274c " ; // "X" - }else{ - if(find_first_poke == false){ - first_poke_slot = {column, row}; - find_first_poke = true; - } - box_render.add(COLOR_GREEN, slot_box); - stats.pkmn++; - env.update_stats(); - boxes_data.push_back( - Pokemon{ - .preferences = &sort_preferences - } - ); //default initialised pokemon to know there is a pokemon here that needs a value - ss << "\u2705 " ; // checkbox - } - } - ss << "\n"; - } - - env.console.log(ss.str()); - ss.str(""); - - // moving cursor to the first pokemon slot - dest_cursor = {0, first_poke_slot[1], first_poke_slot[0]}; - nav_cursor = move_cursor_to(env, context, nav_cursor, dest_cursor, GAME_DELAY); - - //enter the summary screen - if (find_first_poke == true){ - pbf_press_button(context, BUTTON_A, 10, GAME_DELAY); - context.wait_for_all_requests(); - box_render.clear(); - pbf_press_dpad(context, DPAD_DOWN, 10, GAME_DELAY); - pbf_press_button(context, BUTTON_A, 10, VIDEO_DELAY+150); - context.wait_for_all_requests(); - - box_render.add(COLOR_RED, national_dex_number_box); - box_render.add(COLOR_BLUE, shiny_symbol_box); - box_render.add(COLOR_GREEN, gmax_symbol_box); - box_render.add(COLOR_DARKGREEN, origin_symbol_box); - box_render.add(COLOR_DARK_BLUE, pokemon_box); - box_render.add(COLOR_RED, level_box); - box_render.add(COLOR_RED, ot_id_box); - box_render.add(COLOR_RED, ot_box); - box_render.add(COLOR_RED, nature_box); - box_render.add(COLOR_RED, ability_box); - - //cycle through each summary of the current box and fill pokemon information - for (size_t row = 0; row < MAX_ROWS; row++){ - for (size_t column = 0; column < MAX_COLUMNS; column++){ - - if (boxes_data[get_index(box_nb, row, column)].has_value()){ - screen = env.console.video().snapshot(); - - int national_dex_number = OCR::read_number_waterfill(env.console, extract_box_reference(screen, national_dex_number_box), 0xff808080, 0xffffffff); - if (national_dex_number < 0 || national_dex_number > 1025) { - dump_image(env.console, ProgramInfo(), "ReadSummary_national_dex_number", screen); - } - boxes_data[get_index(box_nb, row, column)]->national_dex_number = (uint16_t)national_dex_number; - - int shiny_stddev_value = (int)image_stddev(extract_box_reference(screen, shiny_symbol_box)).sum(); - bool is_shiny = shiny_stddev_value > 30; - boxes_data[get_index(box_nb, row, column)]->shiny = is_shiny; - env.console.log("Shiny detection stddev:" + std::to_string(shiny_stddev_value) + " is shiny:" + std::to_string(is_shiny)); - - int gmax_stddev_value = (int)image_stddev(extract_box_reference(screen, gmax_symbol_box)).sum(); - bool is_gmax = gmax_stddev_value > 30; - boxes_data[get_index(box_nb, row, column)]->gmax = is_gmax; - env.console.log("Gmax detection stddev:" + std::to_string(gmax_stddev_value) + " is gmax:" + std::to_string(is_gmax)); - - BallReader ball_reader(env.console); - boxes_data[get_index(box_nb, row, column)]->ball_slug = ball_reader.read_ball(screen); - - BoxGenderDetector::make_overlays(box_render); - StatsHuntGenderFilter gender = BoxGenderDetector::detect(screen); - env.console.log("Gender: " + gender_to_string(gender), COLOR_GREEN); - boxes_data[get_index(box_nb, row, column)]->gender = gender; - - int ot_id = OCR::read_number_waterfill(env.console, extract_box_reference(screen, ot_id_box), 0xff808080, 0xffffffff); - if (ot_id < 0 || ot_id > 999'999) { - dump_image(env.console, ProgramInfo(), "ReadSummary_OT", screen); - } - boxes_data[get_index(box_nb, row, column)]->ot_id = ot_id; - - // NOTE edit when adding new struct members (detections go here likely) - - // level_box - // ot_box - // nature_box - // ability_box - - pbf_press_button(context, BUTTON_R, 10, VIDEO_DELAY+15); - context.wait_for_all_requests(); - } - } - } - - box_render.clear(); - - ss << std::endl; - - // print box information - for (size_t row = 0; row < MAX_ROWS; row++){ - for (size_t column = 0; column < MAX_COLUMNS; column++){ - ss << boxes_data[get_index(box_nb, row, column)] << " "; - } - ss << std::endl; - } - - env.console.log(ss.str()); - ss.str(""); - - //get out of summary with a lot of delay because it's slow for some reasons - pbf_press_button(context, BUTTON_B, 10, VIDEO_DELAY+250); - box_render.clear(); - context.wait_for_all_requests(); - } - - box_render.clear(); - - dest_cursor = {0, 0, 0}; - nav_cursor = move_cursor_to(env, context, nav_cursor, dest_cursor, GAME_DELAY); - context.wait_for_all_requests(); - } - - // copy boxes data to sort - std::vector> boxes_sorted = boxes_data; - - // sorting copy of boxes_data - std::sort(boxes_sorted.begin(), boxes_sorted.end()); - - env.console.log("Current boxes data :"); - print_boxes_data(boxes_data, env); - const std::string json_path = OUTPUT_FILE; - output_boxes_data_json(boxes_data, json_path); - - env.console.log("Sorted boxes data :"); - print_boxes_data(boxes_sorted, env); - const std::string sorted_path = json_path + "-sorted"; - output_boxes_data_json(boxes_sorted, sorted_path); - - if (!DRY_RUN){ - do_sort(env, context, boxes_data, boxes_sorted, stats, cur_cursor, GAME_DELAY); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - -} - -} -} -} - +/* Home Box Sorting + * + * From: https://github.com/PokemonAutomation/ + * + */ + +/* TODO ideas +break into smaller functions +read pokemon name and store the slug (easier to detect missread than reading a number) +Optimise the swapping algo +Add enum for ball ? Also, BDSP is reading from swsh data. Worth refactoring ? + +ideas for more checks : +ability +nature +type +original game +OT +moves +stats +level +surname +language +"stamps" +*/ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonHome/Inference/PokemonHome_BoxGenderDetector.h" +#include "PokemonHome/Inference/PokemonHome_BallReader.h" +#include "PokemonHome_BoxSorting.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ +using namespace Pokemon; + + +const size_t MAX_BOXES = 200; +const size_t MAX_COLUMNS = 6; +const size_t MAX_ROWS = 5; + +BoxSorting_Descriptor::BoxSorting_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonHome:BoxSorter", + STRING_POKEMON + " Home", "Box Sorter", + "ComputerControl/blob/master/Wiki/Programs/PokemonHome/BoxSorter.md", + "Order boxes of " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} +struct BoxSorting_Descriptor::Stats : public StatsTracker{ + Stats() + : pkmn(m_stats["Pokemon"]) + , empty(m_stats["Empty Slots"]) + , compare(m_stats["Compares"]) + , swaps(m_stats["Swaps"]) + { + m_display_order.emplace_back(Stat("Pokemon")); + m_display_order.emplace_back(Stat("Empty Slots")); + m_display_order.emplace_back(Stat("Compares")); + m_display_order.emplace_back(Stat("Swaps")); + } + std::atomic& pkmn; + std::atomic& empty; + std::atomic& compare; + std::atomic& swaps; +}; +std::unique_ptr BoxSorting_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +BoxSorting::BoxSorting() + : BOX_NUMBER( + "Number of boxes to order:", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, MAX_BOXES + ) + , VIDEO_DELAY( + "Delay of your capture card:", + LockMode::LOCK_WHILE_RUNNING, + 50 + ) + , GAME_DELAY( + "Delay of your Pokemon Home app:", + LockMode::LOCK_WHILE_RUNNING, + 30 + ) + , SORT_TABLE( + "Sort Order Rules:
Sort order rules will be applied top to bottom." + ) + , OUTPUT_FILE( + false, + "Output File:
JSON file for output of storage boxes.", + LockMode::LOCK_WHILE_RUNNING, + "box_order", + "box_order" + ) + , DRY_RUN( + "Dry Run:
Catalogue and make sort plan without executing. (Will output to OUTPUT_FILE and OUTPUT_FILE.sortplan)", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH + }) +{ + PA_ADD_OPTION(BOX_NUMBER); //number of box to check and sort + PA_ADD_OPTION(VIDEO_DELAY); //delay for every input that need video feedback, user will be able to modify this to enhance capture card delay compatibility + PA_ADD_OPTION(GAME_DELAY); //delay for non video feedback, this way I can go as fast as pokemon home can handle movement when needed + PA_ADD_OPTION(SORT_TABLE); + PA_ADD_OPTION(OUTPUT_FILE); + PA_ADD_OPTION(DRY_RUN); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +struct Cursor{ + size_t box; + size_t row; + size_t column; +}; + +std::ostream& operator<<(std::ostream& os, const Cursor& cursor){ + os << "(" << cursor.box << "/" << cursor.row << "/" << cursor.column << ")"; + return os; +} + +Cursor get_cursor(size_t index){ + Cursor ret; + + ret.column = index % MAX_COLUMNS; + index = index / MAX_COLUMNS; + + ret.row = index % MAX_ROWS; + index = index / MAX_ROWS; + + ret.box = index; + return ret; +} + +size_t get_index(size_t box, size_t row, size_t column){ + return box * MAX_ROWS * MAX_COLUMNS + row * MAX_COLUMNS + column; +} + + + +struct Pokemon{ + const std::vector* preferences; + + // When adding any new member here, do not forget to modify the operators below (ctrl-f "new struct members") + uint16_t national_dex_number = 0; + bool shiny = false; + bool gmax = false; + std::string ball_slug = ""; + StatsHuntGenderFilter gender = StatsHuntGenderFilter::Genderless; + uint32_t ot_id = 0; +}; + +bool operator==(const Pokemon& lhs, const Pokemon& rhs){ + // NOTE edit when adding new struct members + return lhs.national_dex_number == rhs.national_dex_number && + lhs.shiny == rhs.shiny && + lhs.gmax == rhs.gmax && + lhs.ball_slug == rhs.ball_slug && + lhs.gender == rhs.gender && + lhs.ot_id == rhs.ot_id; +} + +bool operator<(const std::optional& lhs, const std::optional& rhs){ + if (!lhs.has_value()){ + return false; + } + if (!rhs.has_value()){ + return true; + } + + for (const BoxSortingSelection preference : *lhs->preferences){ + std::optional ret{}; + switch(preference.sort_type){ + // NOTE edit when adding new struct members + case BoxSortingSortType::NationalDexNo: + if (lhs->national_dex_number != rhs->national_dex_number){ + ret = lhs->national_dex_number < rhs->national_dex_number; + } + break; + case BoxSortingSortType::Shiny: + if (lhs->shiny != rhs->shiny){ + ret = lhs->shiny; + } + break; + case BoxSortingSortType::Gigantamax: + if (lhs->gmax != rhs->gmax){ + ret = lhs->gmax; + } + break; + case BoxSortingSortType::Ball_Slug: + if (lhs->ball_slug < rhs->ball_slug){ + ret = true; + } + if (lhs->ball_slug > rhs->ball_slug){ + ret = false; + } + break; + case BoxSortingSortType::Gender: + if (lhs->gender < rhs->gender){ + ret = true; + } + if (lhs->gender > rhs->gender){ + ret = false; + } + break; + } + if (ret.has_value()){ + bool value = *ret; + if (preference.reverse){ + return !value; + }else{ + return value; + } + } + } + + return lhs->national_dex_number < rhs->national_dex_number; +} + +std::ostream& operator<<(std::ostream& os, const std::optional& pokemon) +{ + if (pokemon.has_value()){ + // NOTE edit when adding new struct members + os << "("; + os << "national_dex_number:" << pokemon->national_dex_number << " "; + os << "shiny:" << (pokemon->shiny ? "true" : "false") << " "; + os << "gmax:" << (pokemon->gmax ? "true" : "false") << " "; + os << "ball_slug:" << pokemon->ball_slug << " "; + os << "gender:" << gender_to_string(pokemon->gender) << " "; + os << "ot_id:" << pokemon->ot_id << " "; + os << ")"; + }else{ + os << "(empty)"; + } + return os; +} + +bool go_to_first_slot(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint16_t VIDEO_DELAY){ + + ImageFloatBox cursor_check(0.07, 0.15, 0.01, 0.01); //cursor position of the first slot of the box + VideoSnapshot screen = env.console.video().snapshot(); + FloatPixel image_value = image_stats(extract_box_reference(screen, cursor_check)).average; + env.console.log("Cursor color detection: " + image_value.to_string()); + VideoOverlaySet BoxRender(env.console); + + BoxRender.add(COLOR_BLUE, cursor_check); + if(image_value.r <= image_value.g + image_value.b){ + + bool cursor_found = false; + + for (uint8_t rows = 0; rows < 7; rows++){ + for (uint8_t column = 0; column < 5; column++){ + pbf_press_dpad(context, DPAD_LEFT, 10, VIDEO_DELAY); + context.wait_for_all_requests(); + screen = env.console.video().snapshot(); + image_value = image_stats(extract_box_reference(screen, cursor_check)).average; + env.console.log("Cursor color detection: " + image_value.to_string()); + + if(image_value.r > image_value.g + image_value.b){ + cursor_found = true; + break; + } + } + if(!cursor_found){ + pbf_press_dpad(context, DPAD_UP, 10, VIDEO_DELAY); + context.wait_for_all_requests(); + screen = env.console.video().snapshot(); + image_value = image_stats(extract_box_reference(screen, cursor_check)).average; + env.console.log("Cursor color detection: " + image_value.to_string()); + + if(image_value.r > image_value.g + image_value.b){ + cursor_found = true; + break; + } + }else{ + break; + } + } + if(!cursor_found){ + return false; + } + } + BoxRender.clear(); + return true; +} + +//Move the cursor to the given coordinates, knowing current pos via the cursor struct +[[nodiscard]] Cursor move_cursor_to(SingleSwitchProgramEnvironment& env, ProControllerContext& context, const Cursor& cur_cursor, const Cursor& dest_cursor, uint16_t GAME_DELAY){ + + std::ostringstream ss; + ss << "Moving cursor from " << cur_cursor << " to " << dest_cursor; + env.console.log(ss.str()); + + // TODO: shortest path movement though pages, boxes + for (size_t i = cur_cursor.box; i < dest_cursor.box; ++i){ + pbf_press_button(context, BUTTON_R, 10, GAME_DELAY+30); + } + for (size_t i = dest_cursor.box; i < cur_cursor.box; ++i){ + pbf_press_button(context, BUTTON_L, 10, GAME_DELAY+30); + } + + + // direct nav up or down through rows + if (!(cur_cursor.row == 0 && dest_cursor.row == 4) && !(dest_cursor.row == 0 && cur_cursor.row == 4)){ + for (size_t i = cur_cursor.row; i < dest_cursor.row; ++i){ + pbf_press_dpad(context, DPAD_DOWN, 10, GAME_DELAY); + } + for (size_t i = dest_cursor.row; i < cur_cursor.row; ++i){ + pbf_press_dpad(context, DPAD_UP, 10, GAME_DELAY); + } + }else{ // wrap around is faster to move between first or last row + if (cur_cursor.row == 0 && dest_cursor.row == 4){ + for (size_t i = 0; i <= 2; ++i){ + pbf_press_dpad(context, DPAD_UP, 10, GAME_DELAY); + } + }else{ + for (size_t i = 0; i <= 2; ++i){ + pbf_press_dpad(context, DPAD_DOWN, 10, GAME_DELAY); + } + } + } + + // direct nav forward or backward through columns + if ((dest_cursor.column > cur_cursor.column && dest_cursor.column - cur_cursor.column <= 3) || (cur_cursor.column > dest_cursor.column && cur_cursor.column - dest_cursor.column <= 3)){ + for (size_t i = cur_cursor.column; i < dest_cursor.column; ++i){ + pbf_press_dpad(context, DPAD_RIGHT, 10, GAME_DELAY); + } + for (size_t i = dest_cursor.column; i < cur_cursor.column; ++i){ + pbf_press_dpad(context, DPAD_LEFT, 10, GAME_DELAY); + } + }else{ // wrap around is faster if direct movement is more than 3 away + if (dest_cursor.column > cur_cursor.column){ + for (size_t i = 0; i < MAX_COLUMNS - (dest_cursor.column - cur_cursor.column); ++i){ + pbf_press_dpad(context, DPAD_LEFT, 10, GAME_DELAY); + } + } + if (cur_cursor.column > dest_cursor.column){ + for (size_t i = 0; i < MAX_COLUMNS - (cur_cursor.column - dest_cursor.column); ++i){ + pbf_press_dpad(context, DPAD_RIGHT, 10, GAME_DELAY); + } + } + } + + context.wait_for_all_requests(); + return dest_cursor; +} + +void print_boxes_data(const std::vector>& boxes_data, SingleSwitchProgramEnvironment& env){ + std::ostringstream ss; + for (const std::optional& pokemon : boxes_data){ + ss << pokemon << "\n"; + } + env.console.log(ss.str()); +} + +void output_boxes_data_json(const std::vector>& boxes_data, const std::string& json_path){ + JsonArray pokemon_data; + for (size_t poke_nb = 0; poke_nb < boxes_data.size(); poke_nb++){ + Cursor cursor = get_cursor(poke_nb); + JsonObject pokemon; + pokemon["index"] = poke_nb; + pokemon["box"] = cursor.box; + pokemon["row"] = cursor.row; + pokemon["column"] = cursor.column; + if (std::optional current_pokemon = boxes_data[poke_nb]; current_pokemon != std::nullopt){ + // NOTE edit when adding new struct members + pokemon["national_dex_number"] = current_pokemon->national_dex_number; + pokemon["shiny"] = current_pokemon->shiny; + pokemon["gmax"] = current_pokemon->gmax; + pokemon["ball_slug"] = current_pokemon->ball_slug; + pokemon["gender"] = gender_to_string(current_pokemon->gender); + pokemon["ot_id"] = current_pokemon->ot_id; + } + pokemon_data.push_back(std::move(pokemon)); + } + pokemon_data.dump(json_path + ".json"); +} + +void do_sort( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + std::vector> boxes_data, + std::vector> boxes_sorted, + BoxSorting_Descriptor::Stats& stats, + Cursor& cur_cursor, + uint16_t GAME_DELAY + ){ + std::ostringstream ss; + // this need to be separated into functions when I will redo the whole thing but I just wanted it to work + + // going thru the sorted list one by one and for each one go through the current pokemon layout to find the closest possible match to fill the slot + for (size_t poke_nb_s = 0; poke_nb_s < boxes_sorted.size(); poke_nb_s++){ + if (boxes_sorted[poke_nb_s] == std::nullopt){ // we've hit the end of the sorted list. + break; + } + for (size_t poke_nb = poke_nb_s; poke_nb < boxes_data.size(); poke_nb++){ + Cursor cursor_s = get_cursor(poke_nb_s); + Cursor cursor = get_cursor(poke_nb); + + // ss << "Comparing " << boxes_data[poke_nb] << " at " << cursor << " to " << boxes_sorted[poke_nb_s] << " at " << cursor_s; + // env.console.log(ss.str()); + // ss.str(""); + + //check for a match and also check if the pokemon is not already in the slot + stats.compare++; + env.update_stats(); + if(boxes_sorted[poke_nb_s] == boxes_data[poke_nb] && poke_nb_s == poke_nb){ // Same spot no need to move. + break; + } + if(boxes_sorted[poke_nb_s] == boxes_data[poke_nb]){ + ss << "Swapping " << boxes_data[poke_nb] << " at " << cursor << " and " << boxes_sorted[poke_nb_s] << " at " << cursor_s; + env.console.log(ss.str()); + ss.str(""); + + //moving cursor to the pokemon to pick it up + cur_cursor = move_cursor_to(env, context, cur_cursor, cursor, GAME_DELAY); + pbf_press_button(context, BUTTON_Y, 10, GAME_DELAY+30); + + //moving to destination to place it or swap it + cur_cursor = move_cursor_to(env, context, cur_cursor, cursor_s, GAME_DELAY); + pbf_press_button(context, BUTTON_Y, 10, GAME_DELAY+30); + + context.wait_for_all_requests(); + + std::swap(boxes_data[poke_nb_s], boxes_data[poke_nb]); + stats.swaps++; + env.update_stats(); + + break; + } + } + } +} + +void BoxSorting::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + std::vector sort_preferences = SORT_TABLE.preferences(); + if (sort_preferences.empty()){ + throw UserSetupError(env.console, "At least one sorting method selection needs to be made!"); + } + + BoxSorting_Descriptor::Stats& stats = env.current_stats< BoxSorting_Descriptor::Stats>(); + + ImageFloatBox select_check(0.495, 0.0045, 0.01, 0.005); // square color to check which mode is active + ImageFloatBox national_dex_number_box(0.448, 0.245, 0.049, 0.04); //pokemon national dex number pos + ImageFloatBox shiny_symbol_box(0.702, 0.09, 0.04, 0.06); // shiny symbol pos + ImageFloatBox gmax_symbol_box(0.463, 0.09, 0.04, 0.06); // gmax symbol pos + ImageFloatBox origin_symbol_box(0.623, 0.095, 0.033, 0.05); // origin symbol pos + ImageFloatBox pokemon_box(0.69, 0.18, 0.28, 0.46); // pokemon render pos + ImageFloatBox level_box(0.546, 0.099, 0.044, 0.041); // Level box + ImageFloatBox ot_id_box(0.782, 0.719, 0.193, 0.046); // OT ID box + ImageFloatBox ot_box(0.492, 0.719, 0.165, 0.049); // OT box + ImageFloatBox nature_box(0.157, 0.783, 0.212, 0.042); // Nature box + ImageFloatBox ability_box(0.158, 0.838, 0.213, 0.042); // Ability box + + + // vector that will store data for each slot + std::vector> boxes_data; + + Cursor cur_cursor{static_cast(BOX_NUMBER-1), 0, 0}; + + VideoSnapshot screen = env.console.video().snapshot(); + + VideoOverlaySet box_render(env.console); + + std::ostringstream ss; + + FloatPixel image_value = image_stats(extract_box_reference(screen, select_check)).average; + + env.console.log("Color detected from the select square: " + image_value.to_string()); + + //if the correct color is not detected, getting out of every possible menu to make sure the program work no matter where you start it in your pokemon home + box_render.add(COLOR_BLUE, select_check); + if(image_value.r <= image_value.g + image_value.b){ + for (int var = 0; var < 5; ++var){ + pbf_press_button(context, BUTTON_B, 10, GAME_DELAY+10); + } + context.wait_for_all_requests(); + context.wait_for(std::chrono::milliseconds(VIDEO_DELAY)); + screen = env.console.video().snapshot(); + image_value = image_stats(extract_box_reference(screen, select_check)).average; + env.console.log("Color detected from the select square: " + image_value.to_string()); + if(image_value.r <= image_value.g + image_value.b){ + for (int i = 0; i < 2; ++i){ + pbf_press_button(context, BUTTON_ZR, 10, VIDEO_DELAY+30); //additional delay because this animation is slower than the rest + context.wait_for_all_requests(); + screen = env.console.video().snapshot(); + image_value = image_stats(extract_box_reference(screen, select_check)).average; + env.console.log("Color detected from the select square: " + image_value.to_string()); + if(image_value.r > image_value.g + image_value.b){ + break; + }else if(i==1){ + dump_image(env.console, ProgramInfo(), "SelectSquare", screen); + env.console.log("ERROR: Could not find correct color mode please check color logs and timings\n", COLOR_RED); + return; + } + } + } + } + + box_render.clear(); + + Cursor dest_cursor; + std::vector first_poke_slot; + Cursor nav_cursor = {0, 0, 0}; + bool find_first_poke; + + //cycle through each box + for (size_t box_nb = 0; box_nb < BOX_NUMBER; box_nb++){ + + if(box_nb != 0){ + pbf_press_button(context, BUTTON_R, 10, VIDEO_DELAY+100); + context.wait_for_all_requests(); + }else{ + // Moving the cursor until it goes to the first slot + if(!go_to_first_slot(env, context, VIDEO_DELAY)){ + env.console.log("ERROR: Could not move cursor to the first slot, please consider adjusting delay\n", COLOR_RED); + return; + } + context.wait_for_all_requests(); + } + + screen = env.console.video().snapshot(); + + // Box grid to find empty slots (red boxes) and fill boxes_data with value to check or not for pokemon dex number + + ss << "\n"; + + first_poke_slot = {0, 0}; + find_first_poke = false; + + for (size_t row = 0; row < MAX_ROWS; row++){ + + for (size_t column = 0; column < MAX_COLUMNS; column++){ + + ImageFloatBox slot_box(0.06 + (0.072 * column), 0.2 + (0.1035 * row), 0.03, 0.057); + int current_box_value = (int)image_stddev(extract_box_reference(screen, slot_box)).sum(); + + ss << current_box_value; + + //checking color to know if a pokemon is on the slot or not + if(current_box_value < 5){ + box_render.add(COLOR_RED, slot_box); + stats.empty++; + env.update_stats(); + boxes_data.push_back(std::nullopt); //empty optional to make sorting easier later + ss << "\u274c " ; // "X" + }else{ + if(find_first_poke == false){ + first_poke_slot = {column, row}; + find_first_poke = true; + } + box_render.add(COLOR_GREEN, slot_box); + stats.pkmn++; + env.update_stats(); + boxes_data.push_back( + Pokemon{ + .preferences = &sort_preferences + } + ); //default initialised pokemon to know there is a pokemon here that needs a value + ss << "\u2705 " ; // checkbox + } + } + ss << "\n"; + } + + env.console.log(ss.str()); + ss.str(""); + + // moving cursor to the first pokemon slot + dest_cursor = {0, first_poke_slot[1], first_poke_slot[0]}; + nav_cursor = move_cursor_to(env, context, nav_cursor, dest_cursor, GAME_DELAY); + + //enter the summary screen + if (find_first_poke == true){ + pbf_press_button(context, BUTTON_A, 10, GAME_DELAY); + context.wait_for_all_requests(); + box_render.clear(); + pbf_press_dpad(context, DPAD_DOWN, 10, GAME_DELAY); + pbf_press_button(context, BUTTON_A, 10, VIDEO_DELAY+150); + context.wait_for_all_requests(); + + box_render.add(COLOR_RED, national_dex_number_box); + box_render.add(COLOR_BLUE, shiny_symbol_box); + box_render.add(COLOR_GREEN, gmax_symbol_box); + box_render.add(COLOR_DARKGREEN, origin_symbol_box); + box_render.add(COLOR_DARK_BLUE, pokemon_box); + box_render.add(COLOR_RED, level_box); + box_render.add(COLOR_RED, ot_id_box); + box_render.add(COLOR_RED, ot_box); + box_render.add(COLOR_RED, nature_box); + box_render.add(COLOR_RED, ability_box); + + //cycle through each summary of the current box and fill pokemon information + for (size_t row = 0; row < MAX_ROWS; row++){ + for (size_t column = 0; column < MAX_COLUMNS; column++){ + + if (boxes_data[get_index(box_nb, row, column)].has_value()){ + screen = env.console.video().snapshot(); + + int national_dex_number = OCR::read_number_waterfill(env.console, extract_box_reference(screen, national_dex_number_box), 0xff808080, 0xffffffff); + if (national_dex_number < 0 || national_dex_number > 1025) { + dump_image(env.console, ProgramInfo(), "ReadSummary_national_dex_number", screen); + } + boxes_data[get_index(box_nb, row, column)]->national_dex_number = (uint16_t)national_dex_number; + + int shiny_stddev_value = (int)image_stddev(extract_box_reference(screen, shiny_symbol_box)).sum(); + bool is_shiny = shiny_stddev_value > 30; + boxes_data[get_index(box_nb, row, column)]->shiny = is_shiny; + env.console.log("Shiny detection stddev:" + std::to_string(shiny_stddev_value) + " is shiny:" + std::to_string(is_shiny)); + + int gmax_stddev_value = (int)image_stddev(extract_box_reference(screen, gmax_symbol_box)).sum(); + bool is_gmax = gmax_stddev_value > 30; + boxes_data[get_index(box_nb, row, column)]->gmax = is_gmax; + env.console.log("Gmax detection stddev:" + std::to_string(gmax_stddev_value) + " is gmax:" + std::to_string(is_gmax)); + + BallReader ball_reader(env.console); + boxes_data[get_index(box_nb, row, column)]->ball_slug = ball_reader.read_ball(screen); + + BoxGenderDetector::make_overlays(box_render); + StatsHuntGenderFilter gender = BoxGenderDetector::detect(screen); + env.console.log("Gender: " + gender_to_string(gender), COLOR_GREEN); + boxes_data[get_index(box_nb, row, column)]->gender = gender; + + int ot_id = OCR::read_number_waterfill(env.console, extract_box_reference(screen, ot_id_box), 0xff808080, 0xffffffff); + if (ot_id < 0 || ot_id > 999'999) { + dump_image(env.console, ProgramInfo(), "ReadSummary_OT", screen); + } + boxes_data[get_index(box_nb, row, column)]->ot_id = ot_id; + + // NOTE edit when adding new struct members (detections go here likely) + + // level_box + // ot_box + // nature_box + // ability_box + + pbf_press_button(context, BUTTON_R, 10, VIDEO_DELAY+15); + context.wait_for_all_requests(); + } + } + } + + box_render.clear(); + + ss << std::endl; + + // print box information + for (size_t row = 0; row < MAX_ROWS; row++){ + for (size_t column = 0; column < MAX_COLUMNS; column++){ + ss << boxes_data[get_index(box_nb, row, column)] << " "; + } + ss << std::endl; + } + + env.console.log(ss.str()); + ss.str(""); + + //get out of summary with a lot of delay because it's slow for some reasons + pbf_press_button(context, BUTTON_B, 10, VIDEO_DELAY+250); + box_render.clear(); + context.wait_for_all_requests(); + } + + box_render.clear(); + + dest_cursor = {0, 0, 0}; + nav_cursor = move_cursor_to(env, context, nav_cursor, dest_cursor, GAME_DELAY); + context.wait_for_all_requests(); + } + + // copy boxes data to sort + std::vector> boxes_sorted = boxes_data; + + // sorting copy of boxes_data + std::sort(boxes_sorted.begin(), boxes_sorted.end()); + + env.console.log("Current boxes data :"); + print_boxes_data(boxes_data, env); + const std::string json_path = OUTPUT_FILE; + output_boxes_data_json(boxes_data, json_path); + + env.console.log("Sorted boxes data :"); + print_boxes_data(boxes_sorted, env); + const std::string sorted_path = json_path + "-sorted"; + output_boxes_data_json(boxes_sorted, sorted_path); + + if (!DRY_RUN){ + do_sort(env, context, boxes_data, boxes_sorted, stats, cur_cursor, GAME_DELAY); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.h b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.h index 13fb48cb42..a3624217dd 100644 --- a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.h +++ b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_BoxSorting.h @@ -1,52 +1,52 @@ -/* Box Reorder National Dex - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef BOXSORTING_H -#define BOXSORTING_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "PokemonHome/Options/PokemonHome_BoxSortingTable.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - -class BoxSorting_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BoxSorting_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class BoxSorting : public SingleSwitchProgramInstance{ -public: - BoxSorting(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption BOX_NUMBER; - SimpleIntegerOption VIDEO_DELAY; - SimpleIntegerOption GAME_DELAY; - BoxSortingTable SORT_TABLE; - StringOption OUTPUT_FILE; - BooleanCheckBoxOption DRY_RUN; - EventNotificationsOption NOTIFICATIONS; - -}; - -} -} -} -#endif // BOXSORTING_H - +/* Box Reorder National Dex + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef BOXSORTING_H +#define BOXSORTING_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "PokemonHome/Options/PokemonHome_BoxSortingTable.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + +class BoxSorting_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BoxSorting_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class BoxSorting : public SingleSwitchProgramInstance{ +public: + BoxSorting(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption BOX_NUMBER; + SimpleIntegerOption VIDEO_DELAY; + SimpleIntegerOption GAME_DELAY; + BoxSortingTable SORT_TABLE; + StringOption OUTPUT_FILE; + BooleanCheckBoxOption DRY_RUN; + EventNotificationsOption NOTIFICATIONS; + +}; + +} +} +} +#endif // BOXSORTING_H + diff --git a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp index 83a520945d..b7142eb7c3 100644 --- a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp +++ b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.cpp @@ -1,110 +1,110 @@ -/* Pokemon Home Generate Name OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonHome_GenerateNameOCR.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ -using namespace Pokemon; - - -GenerateNameOCRData_Descriptor::GenerateNameOCRData_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonHome:GenerateNameOCR", - STRING_POKEMON + " Home", STRING_POKEMON + " Home: Generate Name OCR", - "", - "Generate " + STRING_POKEMON + " Name OCR data by iterating the National " + STRING_POKEDEX + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -GenerateNameOCRData::GenerateNameOCRData() - : LANGUAGE( - "Game Language:", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING - ) - , DELAY0( - "Delay Between Each Iteration:", - LockMode::LOCK_WHILE_RUNNING, - "240 ms" - ) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(DELAY0); - -} - - -void GenerateNameOCRData::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - std::string resource_path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-National.json"; - JsonValue json = load_json_file(resource_path); - JsonArray& array = json.to_array_throw(resource_path); - - std::vector slugs; - for (auto& item : array){ - std::string& slug = item.to_string_throw(resource_path); - slugs.emplace_back(std::move(slug)); - } - - - OverlayBoxScope box(env.console, {0.705, 0.815, 0.219, 0.055}); - std::string language_code = language_data(LANGUAGE).code; - - for (const std::string& slug : slugs){ - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - ImageViewRGB32 image = extract_box_reference(screen, box); - - std::string path = "PokemonNameOCR/"; - path += language_code; - path += "/"; - - QDir dir(QString::fromStdString(path)); - if (!dir.exists()){ - dir.mkpath("."); - } - - path += slug; - path += "-"; - path += now_to_filestring(); - path += ".png"; - image.save(path); - - pbf_press_dpad(context, DPAD_RIGHT, 80ms, DELAY0); - - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - env.console, LANGUAGE, image, - OCR::BLACK_TEXT_FILTERS() - ); - } - - -} - - - - -} -} -} +/* Pokemon Home Generate Name OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonHome_GenerateNameOCR.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ +using namespace Pokemon; + + +GenerateNameOCRData_Descriptor::GenerateNameOCRData_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonHome:GenerateNameOCR", + STRING_POKEMON + " Home", STRING_POKEMON + " Home: Generate Name OCR", + "", + "Generate " + STRING_POKEMON + " Name OCR data by iterating the National " + STRING_POKEDEX + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +GenerateNameOCRData::GenerateNameOCRData() + : LANGUAGE( + "Game Language:", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING + ) + , DELAY0( + "Delay Between Each Iteration:", + LockMode::LOCK_WHILE_RUNNING, + "240 ms" + ) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(DELAY0); + +} + + +void GenerateNameOCRData::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + std::string resource_path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-National.json"; + JsonValue json = load_json_file(resource_path); + JsonArray& array = json.to_array_throw(resource_path); + + std::vector slugs; + for (auto& item : array){ + std::string& slug = item.to_string_throw(resource_path); + slugs.emplace_back(std::move(slug)); + } + + + OverlayBoxScope box(env.console, {0.705, 0.815, 0.219, 0.055}); + std::string language_code = language_data(LANGUAGE).code; + + for (const std::string& slug : slugs){ + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + ImageViewRGB32 image = extract_box_reference(screen, box); + + std::string path = "PokemonNameOCR/"; + path += language_code; + path += "/"; + + QDir dir(QString::fromStdString(path)); + if (!dir.exists()){ + dir.mkpath("."); + } + + path += slug; + path += "-"; + path += now_to_filestring(); + path += ".png"; + image.save(path); + + pbf_press_dpad(context, DPAD_RIGHT, 80ms, DELAY0); + + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + env.console, LANGUAGE, image, + OCR::BLACK_TEXT_FILTERS() + ); + } + + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h index 6d2740772d..f73989a4fa 100644 --- a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h +++ b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_GenerateNameOCR.h @@ -1,43 +1,43 @@ -/* Pokemon Home Generate Name OCR - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_GenerateNameOCR_H -#define PokemonAutomation_PokemonHome_GenerateNameOCR_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - - -class GenerateNameOCRData_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GenerateNameOCRData_Descriptor(); -}; - - - -class GenerateNameOCRData : public SingleSwitchProgramInstance{ - -public: - GenerateNameOCRData(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - OCR::LanguageOCROption LANGUAGE; - MillisecondsOption DELAY0; -}; - - - -} -} -} -#endif +/* Pokemon Home Generate Name OCR + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_GenerateNameOCR_H +#define PokemonAutomation_PokemonHome_GenerateNameOCR_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + + +class GenerateNameOCRData_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GenerateNameOCRData_Descriptor(); +}; + + + +class GenerateNameOCRData : public SingleSwitchProgramInstance{ + +public: + GenerateNameOCRData(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + OCR::LanguageOCROption LANGUAGE; + MillisecondsOption DELAY0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp index 73d2bbd703..41137065d3 100644 --- a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp +++ b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.cpp @@ -1,111 +1,111 @@ -/* Pokemon Home Page Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonHome_PageSwap.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - using namespace Pokemon; - - - -PageSwap_Descriptor::PageSwap_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonHome:PageSwap", - STRING_POKEMON + " Home", STRING_POKEMON + " Home: Page Swap", - "ComputerControl/blob/master/Wiki/Programs/PokemonHome/PageSwap.md", - "Swap 30 boxes (1 page) in " + STRING_POKEMON + " Home.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -PageSwap::PageSwap() - : DODGE_SYSTEM_UPDATE_WINDOW( - "Dodge System Update Window:", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(DODGE_SYSTEM_UPDATE_WINDOW); -} - -void PageSwap::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - PokemonSwSh::resume_game_no_interact(env.console, context, DODGE_SYSTEM_UPDATE_WINDOW); - }else{ - pbf_press_button(context, BUTTON_RCLICK, 5, 5); - } - - const uint16_t PICKUP_DELAY = 250; - const uint16_t SCROLL_DELAY = 20; - - for (uint8_t i = 0; i < 2; i++){ - for (uint8_t j = 0; j < 3; j++){ - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - for (uint8_t c = 0; c < 6; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - } - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - for (uint8_t c = 0; c < 6; c++){ - pbf_press_dpad(context, DPAD_LEFT, 10, SCROLL_DELAY); - } - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - } - pbf_press_dpad(context, DPAD_DOWN, 10, SCROLL_DELAY); - for (uint8_t j = 0; j < 3; j++){ - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - for (uint8_t c = 0; c < 6; c++){ - pbf_press_dpad(context, DPAD_LEFT, 10, SCROLL_DELAY); - } - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - for (uint8_t c = 0; c < 6; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - } - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - } - pbf_press_dpad(context, DPAD_DOWN, 10, SCROLL_DELAY); - } - for (uint8_t j = 0; j < 3; j++){ - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - for (uint8_t c = 0; c < 6; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - } - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - for (uint8_t c = 0; c < 6; c++){ - pbf_press_dpad(context, DPAD_LEFT, 10, SCROLL_DELAY); - } - pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); - pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); - } -} - - - - - - -} -} -} +/* Pokemon Home Page Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonHome_PageSwap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + using namespace Pokemon; + + + +PageSwap_Descriptor::PageSwap_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonHome:PageSwap", + STRING_POKEMON + " Home", STRING_POKEMON + " Home: Page Swap", + "ComputerControl/blob/master/Wiki/Programs/PokemonHome/PageSwap.md", + "Swap 30 boxes (1 page) in " + STRING_POKEMON + " Home.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +PageSwap::PageSwap() + : DODGE_SYSTEM_UPDATE_WINDOW( + "Dodge System Update Window:", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(DODGE_SYSTEM_UPDATE_WINDOW); +} + +void PageSwap::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + PokemonSwSh::resume_game_no_interact(env.console, context, DODGE_SYSTEM_UPDATE_WINDOW); + }else{ + pbf_press_button(context, BUTTON_RCLICK, 5, 5); + } + + const uint16_t PICKUP_DELAY = 250; + const uint16_t SCROLL_DELAY = 20; + + for (uint8_t i = 0; i < 2; i++){ + for (uint8_t j = 0; j < 3; j++){ + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + for (uint8_t c = 0; c < 6; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + } + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + for (uint8_t c = 0; c < 6; c++){ + pbf_press_dpad(context, DPAD_LEFT, 10, SCROLL_DELAY); + } + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + } + pbf_press_dpad(context, DPAD_DOWN, 10, SCROLL_DELAY); + for (uint8_t j = 0; j < 3; j++){ + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + for (uint8_t c = 0; c < 6; c++){ + pbf_press_dpad(context, DPAD_LEFT, 10, SCROLL_DELAY); + } + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + for (uint8_t c = 0; c < 6; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + } + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + } + pbf_press_dpad(context, DPAD_DOWN, 10, SCROLL_DELAY); + } + for (uint8_t j = 0; j < 3; j++){ + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + for (uint8_t c = 0; c < 6; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + } + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + for (uint8_t c = 0; c < 6; c++){ + pbf_press_dpad(context, DPAD_LEFT, 10, SCROLL_DELAY); + } + pbf_press_button(context, BUTTON_Y, 10, PICKUP_DELAY); + pbf_press_dpad(context, DPAD_RIGHT, 10, SCROLL_DELAY); + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.h b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.h index 0fcadbaf61..a070ef792d 100644 --- a/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.h +++ b/SerialPrograms/Source/PokemonHome/Programs/PokemonHome_PageSwap.h @@ -1,39 +1,39 @@ -/* Pokemon Home Page Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonHome_PageSwap_H -#define PokemonAutomation_PokemonHome_PageSwap_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonHome{ - -class PageSwap_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PageSwap_Descriptor(); -}; - - -class PageSwap : public SingleSwitchProgramInstance{ -public: - PageSwap(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - BooleanCheckBoxOption DODGE_SYSTEM_UPDATE_WINDOW; -}; - - -} -} -} -#endif +/* Pokemon Home Page Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonHome_PageSwap_H +#define PokemonAutomation_PokemonHome_PageSwap_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonHome{ + +class PageSwap_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PageSwap_Descriptor(); +}; + + +class PageSwap : public SingleSwitchProgramInstance{ +public: + PageSwap(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + BooleanCheckBoxOption DODGE_SYSTEM_UPDATE_WINDOW; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp index b0806e9965..848fecebf1 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.cpp @@ -1,67 +1,67 @@ -/* Battle Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA_BattleMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -BattleMenuDetector::BattleMenuDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("BattleMenuDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_pokemon_stroke_bg_left (0.056, 0.948, 0.013, 0.020) - , m_pokemon_stroke_bg_right (0.174, 0.948, 0.032, 0.046) - , m_button_A_detector(logger, overlay, ButtonType::ButtonA, ImageFloatBox{0.764, 0.752, 0.034, 0.054}, std::chrono::milliseconds(0), false) - // , m_button_B_detector(logger, overlay, ButtonType::ButtonB, ImageFloatBox{0.720, 0.828, 0.027, 0.048}, std::chrono::milliseconds(0), false) -{} - -void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_pokemon_stroke_bg_left); - items.add(COLOR_RED, m_pokemon_stroke_bg_right); -} - - -bool BattleMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const ImageStats stroke_left = image_stats(extract_box_reference(frame, m_pokemon_stroke_bg_left)); -// cout << stroke_left.average << stroke_left.stddev << endl; - if (is_solid(stroke_left,{0.179,0.386,0.435}, 0.2, 15) == false){ - m_detected.store(false, std::memory_order_release); - return false; - } - - - const ImageStats stroke_right = image_stats(extract_box_reference(frame, m_pokemon_stroke_bg_right)); - if (is_solid(stroke_right, {0.228,0.358,0.414}, 0.2, 15) == false){ - m_detected.store(false, std::memory_order_release); - return false; - } - - m_button_A_detector.process_frame(frame, timestamp); - - // m_button_B_detector.process_frame(frame, timestamp); - // hits += m_button_B_detector.detected(); - - bool detected = m_button_A_detector.detected(); - m_detected.store(detected, std::memory_order_release); - - return detected && m_stop_on_detected; -} - - - -} -} -} +/* Battle Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA_BattleMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +BattleMenuDetector::BattleMenuDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("BattleMenuDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_pokemon_stroke_bg_left (0.056, 0.948, 0.013, 0.020) + , m_pokemon_stroke_bg_right (0.174, 0.948, 0.032, 0.046) + , m_button_A_detector(logger, overlay, ButtonType::ButtonA, ImageFloatBox{0.764, 0.752, 0.034, 0.054}, std::chrono::milliseconds(0), false) + // , m_button_B_detector(logger, overlay, ButtonType::ButtonB, ImageFloatBox{0.720, 0.828, 0.027, 0.048}, std::chrono::milliseconds(0), false) +{} + +void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_pokemon_stroke_bg_left); + items.add(COLOR_RED, m_pokemon_stroke_bg_right); +} + + +bool BattleMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const ImageStats stroke_left = image_stats(extract_box_reference(frame, m_pokemon_stroke_bg_left)); +// cout << stroke_left.average << stroke_left.stddev << endl; + if (is_solid(stroke_left,{0.179,0.386,0.435}, 0.2, 15) == false){ + m_detected.store(false, std::memory_order_release); + return false; + } + + + const ImageStats stroke_right = image_stats(extract_box_reference(frame, m_pokemon_stroke_bg_right)); + if (is_solid(stroke_right, {0.228,0.358,0.414}, 0.2, 15) == false){ + m_detected.store(false, std::memory_order_release); + return false; + } + + m_button_A_detector.process_frame(frame, timestamp); + + // m_button_B_detector.process_frame(frame, timestamp); + // hits += m_button_B_detector.detected(); + + bool detected = m_button_A_detector.detected(); + m_detected.store(detected, std::memory_order_release); + + return detected && m_stop_on_detected; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h index 388f8a62b0..62fcf298aa 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h @@ -1,50 +1,50 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the battle menu, which has the option (A) battle, (B) run, - * DPAD_UP for items and DPAD_DOWN to change pokemon. - */ - -#ifndef PokemonAutomation_PokemonLA_BattleMenuDetector_H -#define PokemonAutomation_PokemonLA_BattleMenuDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" - -namespace PokemonAutomation{ - -class Logger; - -namespace NintendoSwitch{ -namespace PokemonLA{ - -class BattleMenuDetector : public VisualInferenceCallback{ -public: - BattleMenuDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - // m_pokemon_stroke_bg_*: match the deep sky blue background of the player's pokemon stats - // in the lower left part of the screen. - ImageFloatBox m_pokemon_stroke_bg_left; - ImageFloatBox m_pokemon_stroke_bg_right; - - ButtonDetector m_button_A_detector; - // ButtonDetector m_button_B_detector; -}; - - -} -} -} -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the battle menu, which has the option (A) battle, (B) run, + * DPAD_UP for items and DPAD_DOWN to change pokemon. + */ + +#ifndef PokemonAutomation_PokemonLA_BattleMenuDetector_H +#define PokemonAutomation_PokemonLA_BattleMenuDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" + +namespace PokemonAutomation{ + +class Logger; + +namespace NintendoSwitch{ +namespace PokemonLA{ + +class BattleMenuDetector : public VisualInferenceCallback{ +public: + BattleMenuDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + // m_pokemon_stroke_bg_*: match the deep sky blue background of the player's pokemon stats + // in the lower left part of the screen. + ImageFloatBox m_pokemon_stroke_bg_left; + ImageFloatBox m_pokemon_stroke_bg_right; + + ButtonDetector m_button_A_detector; + // ButtonDetector m_button_B_detector; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp index 0b76208999..85891d6499 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.cpp @@ -1,79 +1,79 @@ -/* Battle Move Selection Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA_BattleMoveSelectionDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -BattleMoveSelectionDetector::BattleMoveSelectionDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("BattleMoveSelectionDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_move_1_highlight(0.800, 0.6220, 0.02, 0.032) - , m_move_2_highlight(0.779, 0.6875, 0.02, 0.032) - , m_move_3_highlight(0.758, 0.7530, 0.02, 0.032) - , m_move_4_highlight(0.737, 0.8185, 0.02, 0.032) -{} - -void BattleMoveSelectionDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_BLUE, m_move_1_highlight); - items.add(COLOR_BLUE, m_move_2_highlight); - items.add(COLOR_BLUE, m_move_3_highlight); - items.add(COLOR_BLUE, m_move_4_highlight); -} - - - -bool BattleMoveSelectionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - size_t highlighted = 0; - - const ImageStats move_1 = image_stats(extract_box_reference(frame, m_move_1_highlight)); - highlighted += is_white(move_1); - // std::cout << "highlighted is now " << highlighted << std::endl; - - const ImageStats move_2 = image_stats(extract_box_reference(frame, m_move_2_highlight)); - highlighted += is_white(move_2); - // std::cout << "highlighted is now " << highlighted << std::endl; - if (highlighted > 1){ - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats move_3 = image_stats(extract_box_reference(frame, m_move_3_highlight)); - highlighted += is_white(move_3); - // std::cout << "highlighted is now " << highlighted << std::endl; - if (highlighted > 1){ - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats move_4 = image_stats(extract_box_reference(frame, m_move_4_highlight)); - highlighted += is_white(move_4); - - // std::cout << "move selection highlighted " << highlighted << std::endl; - - bool detected = highlighted == 1; - m_detected.store(detected, std::memory_order_release); - - return detected && m_stop_on_detected; -} - - - -} -} -} +/* Battle Move Selection Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA_BattleMoveSelectionDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +BattleMoveSelectionDetector::BattleMoveSelectionDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("BattleMoveSelectionDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_move_1_highlight(0.800, 0.6220, 0.02, 0.032) + , m_move_2_highlight(0.779, 0.6875, 0.02, 0.032) + , m_move_3_highlight(0.758, 0.7530, 0.02, 0.032) + , m_move_4_highlight(0.737, 0.8185, 0.02, 0.032) +{} + +void BattleMoveSelectionDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_BLUE, m_move_1_highlight); + items.add(COLOR_BLUE, m_move_2_highlight); + items.add(COLOR_BLUE, m_move_3_highlight); + items.add(COLOR_BLUE, m_move_4_highlight); +} + + + +bool BattleMoveSelectionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + size_t highlighted = 0; + + const ImageStats move_1 = image_stats(extract_box_reference(frame, m_move_1_highlight)); + highlighted += is_white(move_1); + // std::cout << "highlighted is now " << highlighted << std::endl; + + const ImageStats move_2 = image_stats(extract_box_reference(frame, m_move_2_highlight)); + highlighted += is_white(move_2); + // std::cout << "highlighted is now " << highlighted << std::endl; + if (highlighted > 1){ + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats move_3 = image_stats(extract_box_reference(frame, m_move_3_highlight)); + highlighted += is_white(move_3); + // std::cout << "highlighted is now " << highlighted << std::endl; + if (highlighted > 1){ + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats move_4 = image_stats(extract_box_reference(frame, m_move_4_highlight)); + highlighted += is_white(move_4); + + // std::cout << "move selection highlighted " << highlighted << std::endl; + + bool detected = highlighted == 1; + m_detected.store(detected, std::memory_order_release); + + return detected && m_stop_on_detected; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.h index 5d4610d692..9d3b852a0e 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleMoveSelectionDetector.h @@ -1,50 +1,50 @@ -/* Battle Move Selection Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the move selection screen. Useful to detect whether a move has no PP so it can - * not be used. - * Note: this detector is very easy to get false positives. Can be deleted if it is not used in future. - */ - -#ifndef PokemonAutomation_PokemonLA_BattleMoveSelectionDetector_H -#define PokemonAutomation_PokemonLA_BattleMoveSelectionDetector_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - -class VideoOverlay; -class Logger; - -namespace NintendoSwitch{ -namespace PokemonLA{ - -class BattleMoveSelectionDetector : public VisualInferenceCallback{ -public: - BattleMoveSelectionDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - - ImageFloatBox m_move_1_highlight; - ImageFloatBox m_move_2_highlight; - ImageFloatBox m_move_3_highlight; - ImageFloatBox m_move_4_highlight; -}; - - -} -} -} -#endif +/* Battle Move Selection Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the move selection screen. Useful to detect whether a move has no PP so it can + * not be used. + * Note: this detector is very easy to get false positives. Can be deleted if it is not used in future. + */ + +#ifndef PokemonAutomation_PokemonLA_BattleMoveSelectionDetector_H +#define PokemonAutomation_PokemonLA_BattleMoveSelectionDetector_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + +class VideoOverlay; +class Logger; + +namespace NintendoSwitch{ +namespace PokemonLA{ + +class BattleMoveSelectionDetector : public VisualInferenceCallback{ +public: + BattleMoveSelectionDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + + ImageFloatBox m_move_1_highlight; + ImageFloatBox m_move_2_highlight; + ImageFloatBox m_move_3_highlight; + ImageFloatBox m_move_4_highlight; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.cpp index fdaae377c7..4fe5646840 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.cpp @@ -1,100 +1,100 @@ -/* Battle Move Selection Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA/Inference/PokemonLA_CommonColorCheck.h" -#include "PokemonLA_BattlePokemonSwitchDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -BattlePokemonSwitchDetector::BattlePokemonSwitchDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("BattlePokemonSwitchDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_white_bg_1(0.641, 0.178, 0.05, 0.023) - , m_white_bg_2(0.641, 0.248, 0.05, 0.023) - , m_white_bg_3(0.517, 0.195, 0.011, 0.061) - , m_white_bg_4(0.924, 0.185, 0.019, 0.076) - , m_ready_to_battle_bg_1(0.538, 0.216, 0.008, 0.018) - , m_ready_to_battle_bg_2(0.686, 0.216, 0.008, 0.018) - , m_button_plus_detector(logger, overlay, ButtonType::ButtonPlus, ImageFloatBox{0.044, 0.091, 0.043, 0.077}, std::chrono::milliseconds(0), false) -{} - -void BattlePokemonSwitchDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_YELLOW, m_white_bg_1); - items.add(COLOR_YELLOW, m_white_bg_2); - items.add(COLOR_YELLOW, m_white_bg_3); - items.add(COLOR_YELLOW, m_white_bg_4); - items.add(COLOR_YELLOW, m_ready_to_battle_bg_1); - items.add(COLOR_YELLOW, m_ready_to_battle_bg_2); -} - - -bool BattlePokemonSwitchDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const ImageStats white_1 = image_stats(extract_box_reference(frame, m_white_bg_1)); - if(is_white(white_1, 500, 10) == false){ - // std::cout << "no white_1" << std::endl; - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats white_2 = image_stats(extract_box_reference(frame, m_white_bg_2)); - if(is_white(white_2, 500, 10) == false){ - // std::cout << "no white_2" << std::endl; - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats white_3 = image_stats(extract_box_reference(frame, m_white_bg_3)); - if(is_white(white_3, 500, 15) == false){ - // std::cout << "no white_3" << std::endl; - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats white_4 = image_stats(extract_box_reference(frame, m_white_bg_4)); - if(is_white(white_4, 500, 10) == false){ - // std::cout << "no white_4" << std::endl; - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats battle_1 = image_stats(extract_box_reference(frame, m_ready_to_battle_bg_1)); - if (!is_LA_dark_blue(battle_1)){ - // std::cout << "battle_1 not enough " << battle_1.average << " " << battle_1.stddev << std::endl; - m_detected.store(false, std::memory_order_release); - return false; - } - - const ImageStats battle_2 = image_stats(extract_box_reference(frame, m_ready_to_battle_bg_2)); - if (!is_LA_dark_blue(battle_2)){ - // std::cout << "battle_2 not enough" << battle_2.average << " " << battle_2.stddev << std::endl; - m_detected.store(false, std::memory_order_release); - return false; - } - - - m_button_plus_detector.process_frame(frame, timestamp); - bool detected = m_button_plus_detector.detected(); - // std::cout << "button plus detected " << detected << std::endl; - m_detected.store(detected, std::memory_order_release); - - return detected && m_stop_on_detected; -} - - - -} -} -} +/* Battle Move Selection Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA/Inference/PokemonLA_CommonColorCheck.h" +#include "PokemonLA_BattlePokemonSwitchDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +BattlePokemonSwitchDetector::BattlePokemonSwitchDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("BattlePokemonSwitchDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_white_bg_1(0.641, 0.178, 0.05, 0.023) + , m_white_bg_2(0.641, 0.248, 0.05, 0.023) + , m_white_bg_3(0.517, 0.195, 0.011, 0.061) + , m_white_bg_4(0.924, 0.185, 0.019, 0.076) + , m_ready_to_battle_bg_1(0.538, 0.216, 0.008, 0.018) + , m_ready_to_battle_bg_2(0.686, 0.216, 0.008, 0.018) + , m_button_plus_detector(logger, overlay, ButtonType::ButtonPlus, ImageFloatBox{0.044, 0.091, 0.043, 0.077}, std::chrono::milliseconds(0), false) +{} + +void BattlePokemonSwitchDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_YELLOW, m_white_bg_1); + items.add(COLOR_YELLOW, m_white_bg_2); + items.add(COLOR_YELLOW, m_white_bg_3); + items.add(COLOR_YELLOW, m_white_bg_4); + items.add(COLOR_YELLOW, m_ready_to_battle_bg_1); + items.add(COLOR_YELLOW, m_ready_to_battle_bg_2); +} + + +bool BattlePokemonSwitchDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const ImageStats white_1 = image_stats(extract_box_reference(frame, m_white_bg_1)); + if(is_white(white_1, 500, 10) == false){ + // std::cout << "no white_1" << std::endl; + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats white_2 = image_stats(extract_box_reference(frame, m_white_bg_2)); + if(is_white(white_2, 500, 10) == false){ + // std::cout << "no white_2" << std::endl; + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats white_3 = image_stats(extract_box_reference(frame, m_white_bg_3)); + if(is_white(white_3, 500, 15) == false){ + // std::cout << "no white_3" << std::endl; + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats white_4 = image_stats(extract_box_reference(frame, m_white_bg_4)); + if(is_white(white_4, 500, 10) == false){ + // std::cout << "no white_4" << std::endl; + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats battle_1 = image_stats(extract_box_reference(frame, m_ready_to_battle_bg_1)); + if (!is_LA_dark_blue(battle_1)){ + // std::cout << "battle_1 not enough " << battle_1.average << " " << battle_1.stddev << std::endl; + m_detected.store(false, std::memory_order_release); + return false; + } + + const ImageStats battle_2 = image_stats(extract_box_reference(frame, m_ready_to_battle_bg_2)); + if (!is_LA_dark_blue(battle_2)){ + // std::cout << "battle_2 not enough" << battle_2.average << " " << battle_2.stddev << std::endl; + m_detected.store(false, std::memory_order_release); + return false; + } + + + m_button_plus_detector.process_frame(frame, timestamp); + bool detected = m_button_plus_detector.detected(); + // std::cout << "button plus detected " << detected << std::endl; + m_detected.store(detected, std::memory_order_release); + + return detected && m_stop_on_detected; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h index 052948491e..04673217a5 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h @@ -1,52 +1,52 @@ -/* Battle Pokemon Switch Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the screen of switching to another pokemon during battle. - */ - -#ifndef PokemonAutomation_PokemonLA_BattlePokemonSwitchDetector_H -#define PokemonAutomation_PokemonLA_BattlePokemonSwitchDetector_H - -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -class BattlePokemonSwitchDetector : public VisualInferenceCallback{ -public: - BattlePokemonSwitchDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - - // The white background of the current selected pokemon's name and types: - ImageFloatBox m_white_bg_1; - ImageFloatBox m_white_bg_2; - ImageFloatBox m_white_bg_3; - ImageFloatBox m_white_bg_4; - - // The dark blue background of "Ready to battle": - ImageFloatBox m_ready_to_battle_bg_1; - ImageFloatBox m_ready_to_battle_bg_2; - - ButtonDetector m_button_plus_detector; -}; - - -} -} -} -#endif +/* Battle Pokemon Switch Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the screen of switching to another pokemon during battle. + */ + +#ifndef PokemonAutomation_PokemonLA_BattlePokemonSwitchDetector_H +#define PokemonAutomation_PokemonLA_BattlePokemonSwitchDetector_H + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +class BattlePokemonSwitchDetector : public VisualInferenceCallback{ +public: + BattlePokemonSwitchDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + + // The white background of the current selected pokemon's name and types: + ImageFloatBox m_white_bg_1; + ImageFloatBox m_white_bg_2; + ImageFloatBox m_white_bg_3; + ImageFloatBox m_white_bg_4; + + // The dark blue background of "Ready to battle": + ImageFloatBox m_ready_to_battle_bg_1; + ImageFloatBox m_ready_to_battle_bg_2; + + ButtonDetector m_button_plus_detector; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.cpp b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.cpp index f63faa638d..07adb42a77 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.cpp @@ -1,85 +1,85 @@ -/* Battle Sprite Watcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonLA_BattleSpriteWatcher.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -const size_t MAX_WILD_POKEMON_IN_MULTI_BATTLE = 8; - - - -BattleSpriteWatcher::BattleSpriteWatcher(Logger& logger, VideoOverlay& overlay) - : VisualInferenceCallback("BattleSpriteWatcher") - , m_logger(logger) - , m_battle_start_detector(logger, overlay) -{ - for(size_t i = 0; i < MAX_WILD_POKEMON_IN_MULTI_BATTLE; i++){ - m_sprite_boxes.emplace_back(0.957 - 0.035*i, 0.044, 0.021, 0.035); - } - m_sprite_appeared.resize(m_sprite_boxes.size(), false); -} - -void BattleSpriteWatcher::make_overlays(VideoOverlaySet& items) const{ - for(const auto& box : m_sprite_boxes){ - items.add(COLOR_RED, box); - } -} - -bool BattleSpriteWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool in_battle = m_battle_start_detector.process_frame(frame, timestamp); - if (in_battle == false){ - return false; - } - - const bool found_new_sprites = set_detected_sprites(frame, m_sprite_appeared); - if (found_new_sprites && PreloadSettings::instance().DEVELOPER_MODE){ - dump_debug_image(m_logger, "PokemonLA/BattleSpriteWatcher", "SpriteDetected", frame); - } - - return false; -} - - -std::vector BattleSpriteWatcher::detect_sprites(const ImageViewRGB32& frame) const{ - std::vector ret(m_sprite_boxes.size(), false); - set_detected_sprites(frame, ret); - return ret; -} - - -bool BattleSpriteWatcher::set_detected_sprites(const ImageViewRGB32& frame, std::vector& sprites) const{ - bool ret = false; - for(size_t i = 0; i < m_sprite_boxes.size(); i++){ - const auto& box = m_sprite_boxes[i]; - const auto stats = image_stats(extract_box_reference(frame, box)); - // cout << stats.average.to_string() << " " << stats.stddev.to_string() << endl; - if (sprites[i] == false && (stats.average.sum() > 150.0 || stats.stddev.sum() > 60.0)){ - ret = true; - sprites[i] = true; - } - } - - return ret; -} - - -} -} -} +/* Battle Sprite Watcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonLA_BattleSpriteWatcher.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +const size_t MAX_WILD_POKEMON_IN_MULTI_BATTLE = 8; + + + +BattleSpriteWatcher::BattleSpriteWatcher(Logger& logger, VideoOverlay& overlay) + : VisualInferenceCallback("BattleSpriteWatcher") + , m_logger(logger) + , m_battle_start_detector(logger, overlay) +{ + for(size_t i = 0; i < MAX_WILD_POKEMON_IN_MULTI_BATTLE; i++){ + m_sprite_boxes.emplace_back(0.957 - 0.035*i, 0.044, 0.021, 0.035); + } + m_sprite_appeared.resize(m_sprite_boxes.size(), false); +} + +void BattleSpriteWatcher::make_overlays(VideoOverlaySet& items) const{ + for(const auto& box : m_sprite_boxes){ + items.add(COLOR_RED, box); + } +} + +bool BattleSpriteWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool in_battle = m_battle_start_detector.process_frame(frame, timestamp); + if (in_battle == false){ + return false; + } + + const bool found_new_sprites = set_detected_sprites(frame, m_sprite_appeared); + if (found_new_sprites && PreloadSettings::instance().DEVELOPER_MODE){ + dump_debug_image(m_logger, "PokemonLA/BattleSpriteWatcher", "SpriteDetected", frame); + } + + return false; +} + + +std::vector BattleSpriteWatcher::detect_sprites(const ImageViewRGB32& frame) const{ + std::vector ret(m_sprite_boxes.size(), false); + set_detected_sprites(frame, ret); + return ret; +} + + +bool BattleSpriteWatcher::set_detected_sprites(const ImageViewRGB32& frame, std::vector& sprites) const{ + bool ret = false; + for(size_t i = 0; i < m_sprite_boxes.size(); i++){ + const auto& box = m_sprite_boxes[i]; + const auto stats = image_stats(extract_box_reference(frame, box)); + // cout << stats.average.to_string() << " " << stats.stddev.to_string() << endl; + if (sprites[i] == false && (stats.average.sum() > 150.0 || stats.stddev.sum() > 60.0)){ + ret = true; + sprites[i] = true; + } + } + + return ret; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h index d3bd481d48..4f174c4983 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h @@ -1,68 +1,68 @@ -/* Battle Sprite Watcher - * - * From: https://github.com/PokemonAutomation/ - * - * Watch the sprites appear on the upper right corner of the screen during a mult-pokemon - * battle. This is useful to detect if any skittish pokemon escape during the starting - * stage of the battle. - */ - -#ifndef PokemonAutomation_PokemonLA_BattleSpriteWatcher_H -#define PokemonAutomation_PokemonLA_BattleSpriteWatcher_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h" - -namespace PokemonAutomation{ - -class Logger; - -namespace NintendoSwitch{ -namespace PokemonLA{ - -// Max number of wild pokemon that can enter a multi battle against player -extern const size_t MAX_WILD_POKEMON_IN_MULTI_BATTLE; - -class BattleSpriteWatcher : public VisualInferenceCallback{ -public: - BattleSpriteWatcher(Logger& logger, VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // As a watcher, this function always returns false. - // If it detects a sprite appears, it sets the corresponding bool in `m_sprite_appeared` to true. - // After inference session ends, call `sprites_appeared() to access it. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - // Read whether a sprite appeared duing an inference session, where BattleSpriteWatcher::process_frame() is called. - // Return a vector of `MAX_WILD_POKEMON_IN_MULTI_BATTLE` bools. - // The sprites are indexed from right to left, with the rightmost sprite with index 0. - const std::vector& sprites_appeared() const { return m_sprite_appeared; } - - // Detect whether a sprite is present on the input frame. - // Does not modify any internal data of `BattleSpriteWatcher`. - // Return a vector of `MAX_WILD_POKEMON_IN_MULTI_BATTLE` bools. - // The sprites are indexed from right to left, with the rightmost sprite with index 0. - std::vector detect_sprites(const ImageViewRGB32& frame) const; - -private: - - // Set the bool value of the detected sprites in `sprites` to true - // Return true if at least one sprite is newly detected - bool set_detected_sprites(const ImageViewRGB32& frame, std::vector& sprites) const; - - Logger& m_logger; - - BattleStartDetector m_battle_start_detector; - std::vector m_sprite_boxes; - std::vector m_sprite_appeared; -}; - - -} -} -} -#endif +/* Battle Sprite Watcher + * + * From: https://github.com/PokemonAutomation/ + * + * Watch the sprites appear on the upper right corner of the screen during a mult-pokemon + * battle. This is useful to detect if any skittish pokemon escape during the starting + * stage of the battle. + */ + +#ifndef PokemonAutomation_PokemonLA_BattleSpriteWatcher_H +#define PokemonAutomation_PokemonLA_BattleSpriteWatcher_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h" + +namespace PokemonAutomation{ + +class Logger; + +namespace NintendoSwitch{ +namespace PokemonLA{ + +// Max number of wild pokemon that can enter a multi battle against player +extern const size_t MAX_WILD_POKEMON_IN_MULTI_BATTLE; + +class BattleSpriteWatcher : public VisualInferenceCallback{ +public: + BattleSpriteWatcher(Logger& logger, VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // As a watcher, this function always returns false. + // If it detects a sprite appears, it sets the corresponding bool in `m_sprite_appeared` to true. + // After inference session ends, call `sprites_appeared() to access it. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + // Read whether a sprite appeared duing an inference session, where BattleSpriteWatcher::process_frame() is called. + // Return a vector of `MAX_WILD_POKEMON_IN_MULTI_BATTLE` bools. + // The sprites are indexed from right to left, with the rightmost sprite with index 0. + const std::vector& sprites_appeared() const { return m_sprite_appeared; } + + // Detect whether a sprite is present on the input frame. + // Does not modify any internal data of `BattleSpriteWatcher`. + // Return a vector of `MAX_WILD_POKEMON_IN_MULTI_BATTLE` bools. + // The sprites are indexed from right to left, with the rightmost sprite with index 0. + std::vector detect_sprites(const ImageViewRGB32& frame) const; + +private: + + // Set the bool value of the detected sprites in `sprites` to true + // Return true if at least one sprite is newly detected + bool set_detected_sprites(const ImageViewRGB32& frame, std::vector& sprites) const; + + Logger& m_logger; + + BattleStartDetector m_battle_start_detector; + std::vector m_sprite_boxes; + std::vector m_sprite_appeared; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.cpp index a645f9f4bc..771af00789 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.cpp @@ -1,67 +1,67 @@ -/* Battle Start Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageGradient.h" -#include "PokemonLA_BattleStartDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -BattleStartDetector::BattleStartDetector(Logger& logger, VideoOverlay& overlay) - : VisualInferenceCallback("BattleStartDetector") - , m_logger(logger) - , m_upper_boundary (0.0, 0.113, 1.0, 0.15) - , m_lower_boundary (0.2, 0.871, 0.63, 0.015) -{} - -void BattleStartDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_BLUE, m_upper_boundary); - items.add(COLOR_BLUE, m_lower_boundary); -} - -bool BattleStartDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - - Color threshold(50, 50, 50); - - const ImageViewRGB32 upper_boundary = extract_box_reference(frame, m_upper_boundary); - - const size_t upper_border_length = count_horizontal_translucent_border_pixels(upper_boundary, threshold, true); - - bool detected = upper_border_length / (float)upper_boundary.width() > 0.9; - - if (detected == false){ - return false; - } - - const ImageViewRGB32 lower_boundary = extract_box_reference(frame, m_lower_boundary); - - const size_t lower_border_length = count_horizontal_translucent_border_pixels(lower_boundary, threshold, false); - - detected = lower_border_length / (float)lower_boundary.width() > 0.9; - - if (detected && m_started == false){ - m_started = true; - m_logger.log("Detected battle start by black borders."); - } - - return detected; -} - - - -} -} -} +/* Battle Start Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageGradient.h" +#include "PokemonLA_BattleStartDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +BattleStartDetector::BattleStartDetector(Logger& logger, VideoOverlay& overlay) + : VisualInferenceCallback("BattleStartDetector") + , m_logger(logger) + , m_upper_boundary (0.0, 0.113, 1.0, 0.15) + , m_lower_boundary (0.2, 0.871, 0.63, 0.015) +{} + +void BattleStartDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_BLUE, m_upper_boundary); + items.add(COLOR_BLUE, m_lower_boundary); +} + +bool BattleStartDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + + Color threshold(50, 50, 50); + + const ImageViewRGB32 upper_boundary = extract_box_reference(frame, m_upper_boundary); + + const size_t upper_border_length = count_horizontal_translucent_border_pixels(upper_boundary, threshold, true); + + bool detected = upper_border_length / (float)upper_boundary.width() > 0.9; + + if (detected == false){ + return false; + } + + const ImageViewRGB32 lower_boundary = extract_box_reference(frame, m_lower_boundary); + + const size_t lower_border_length = count_horizontal_translucent_border_pixels(lower_boundary, threshold, false); + + detected = lower_border_length / (float)lower_boundary.width() > 0.9; + + if (detected && m_started == false){ + m_started = true; + m_logger.log("Detected battle start by black borders."); + } + + return detected; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h index 2c2a2059d1..26474c849e 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h @@ -1,41 +1,41 @@ -/* Battle Start Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the start of a battle when the upper and lower part of the screen - * is covered by black. - */ - -#ifndef PokemonAutomation_PokemonLA_BattleStartDetector_H -#define PokemonAutomation_PokemonLA_BattleStartDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -class BattleStartDetector : public VisualInferenceCallback{ -public: - BattleStartDetector(Logger& logger, VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - // The upper and lower black area boundary - ImageFloatBox m_upper_boundary; - ImageFloatBox m_lower_boundary; - // Record whether a battle start has been detected. This is used for logging. - bool m_started = false; -}; - - -} -} -} -#endif +/* Battle Start Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the start of a battle when the upper and lower part of the screen + * is covered by black. + */ + +#ifndef PokemonAutomation_PokemonLA_BattleStartDetector_H +#define PokemonAutomation_PokemonLA_BattleStartDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +class BattleStartDetector : public VisualInferenceCallback{ +public: + BattleStartDetector(Logger& logger, VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + // The upper and lower black area boundary + ImageFloatBox m_upper_boundary; + ImageFloatBox m_lower_boundary; + // Record whether a battle start has been detected. This is used for logging. + bool m_started = false; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.cpp index dc23f6380f..49ff75660c 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.cpp @@ -1,51 +1,51 @@ -/* Transparent Dialogue Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonLA_TransparentDialogueDetector.h" - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -TransparentDialogueDetector::TransparentDialogueDetector( - Logger& logger, VideoOverlay& overlay, - bool stop_on_detected -) - : VisualInferenceCallback("TransparentDialogueDetector") - , m_arrow_detector(logger, overlay, stop_on_detected) - , m_ellipse_detector(logger, overlay, std::chrono::milliseconds(0), stop_on_detected) -{} - - -void TransparentDialogueDetector::make_overlays(VideoOverlaySet& items) const{ - m_arrow_detector.make_overlays(items); - m_ellipse_detector.make_overlays(items); -} - - -bool TransparentDialogueDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool stop = m_arrow_detector.process_frame(frame, timestamp); - bool detected = m_arrow_detector.detected(); - if (detected){ - stop = stop && m_ellipse_detector.process_frame(frame, timestamp); - detected = m_ellipse_detector.detected(); - } - - m_detected.store(detected, std::memory_order_release); - - return stop; -} - - - - - -} -} -} +/* Transparent Dialogue Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonLA_TransparentDialogueDetector.h" + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +TransparentDialogueDetector::TransparentDialogueDetector( + Logger& logger, VideoOverlay& overlay, + bool stop_on_detected +) + : VisualInferenceCallback("TransparentDialogueDetector") + , m_arrow_detector(logger, overlay, stop_on_detected) + , m_ellipse_detector(logger, overlay, std::chrono::milliseconds(0), stop_on_detected) +{} + + +void TransparentDialogueDetector::make_overlays(VideoOverlaySet& items) const{ + m_arrow_detector.make_overlays(items); + m_ellipse_detector.make_overlays(items); +} + + +bool TransparentDialogueDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool stop = m_arrow_detector.process_frame(frame, timestamp); + bool detected = m_arrow_detector.detected(); + if (detected){ + stop = stop && m_ellipse_detector.process_frame(frame, timestamp); + detected = m_ellipse_detector.detected(); + } + + m_detected.store(detected, std::memory_order_release); + + return stop; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h index c58be09b59..483f31afbc 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h @@ -1,47 +1,47 @@ -/* Transparent Dialogue Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the transparent dialogue box from your opponent shown before and/or after the battle, like - * Ingo's battles or Fortune Sisters'. - */ - -#ifndef PokemonAutomation_PokemonLA_TransparentDialogueDetector_H -#define PokemonAutomation_PokemonLA_TransparentDialogueDetector_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class TransparentDialogueDetector : public VisualInferenceCallback{ -public: - TransparentDialogueDetector( - Logger& logger, VideoOverlay& overlay, - bool stop_on_detected - ); - - bool detected() const{ - return m_detected; - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - DialogueYellowArrowDetector m_arrow_detector; - DialogueEllipseDetector m_ellipse_detector; - std::atomic m_detected; -}; - - - -} -} -} -#endif +/* Transparent Dialogue Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the transparent dialogue box from your opponent shown before and/or after the battle, like + * Ingo's battles or Fortune Sisters'. + */ + +#ifndef PokemonAutomation_PokemonLA_TransparentDialogueDetector_H +#define PokemonAutomation_PokemonLA_TransparentDialogueDetector_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class TransparentDialogueDetector : public VisualInferenceCallback{ +public: + TransparentDialogueDetector( + Logger& logger, VideoOverlay& overlay, + bool stop_on_detected + ); + + bool detected() const{ + return m_detected; + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + DialogueYellowArrowDetector m_arrow_detector; + DialogueEllipseDetector m_ellipse_detector; + std::atomic m_detected; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.cpp index 27a8957548..af54fc3620 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.cpp @@ -1,98 +1,98 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonLA_MMOSpriteStarSymbolDetector.h" - - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -MMOSpriteStarSymbolDetector::MMOSpriteStarSymbolDetector(const ImageViewRGB32& frame, const std::vector& star_boxes) - : VisualInferenceCallback("MMOSpriteStarSymbolDetector") - , m_boxes(star_boxes), m_is_star(star_boxes.size(), false), m_rmsd(star_boxes.size(), 0.0) - , m_symbol_colors(star_boxes.size(), FloatPixel()) - , m_frame_width(frame.width()), m_frame_height(frame.height()) -{ - for(size_t i = 0; i < m_boxes.size(); i++){ - ImageViewRGB32 ref = extract_box_reference(frame, m_boxes[i]); - m_initial_images.push_back(std::move(ref)); - } -} - -void MMOSpriteStarSymbolDetector::make_overlays(VideoOverlaySet& items) const{ - for(const auto& box : m_boxes){ - items.add(COLOR_RED, pixelbox_to_floatbox(m_frame_width, m_frame_height, box)); - } -} - -// Return true if the inference session should stop. -bool MMOSpriteStarSymbolDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // If we already collect enough frames, then we should stop doing detection - if (m_num_frames >= 30){ - return true; - } - - // Collect image color stats: - for(size_t i = 0; i < m_boxes.size(); i++){ - ImageViewRGB32 ref = extract_box_reference(frame, m_boxes[i]); - double rmsd = ImageMatch::pixel_RMSD(m_initial_images[i], ref); - m_rmsd[i] += rmsd; - - m_symbol_colors[i] += frame.pixel(m_boxes[i].center_x(), m_boxes[i].center_y()); - } - - m_num_frames++; - - // We don't have enough frames, continue collection: - if (m_num_frames < 30){ - return false; - } - - // We have enough frames, compute stats to determine whether each sprite has a star symbol. - // Caller of this detector can query `m_is_star` to know the detection result. - // Details of the detection can be queried via `m_rmsd` and `m_symbol_colors` - // - for(size_t i = 0; i < m_boxes.size(); i++){ - // Compute average values: - m_rmsd[i] = m_rmsd[i] / (double)m_num_frames; - m_symbol_colors[i] = m_symbol_colors[i] / (double)m_num_frames; - - if (m_rmsd[i] <= 20){ - continue; - } - - if (m_symbol_colors[i].r <= m_symbol_colors[i].g * 1.2 && m_symbol_colors[i].g > 200 && m_symbol_colors[i].r > 220){ - // It's not very red, so it's not a berry symbol - m_is_star[i] = true; - } - } - - // ImageRGB32 output = frame.copy(); - // for(size_t i = 0; i < m_boxes.size(); i++){ - // draw_box(output, m_boxes[i], combine_rgb(255, 0,0)); - // draw_box(output, ImagePixelBox(m_boxes[i].center_x()-1, m_boxes[i].center_y()-1, m_boxes[i].center_x()+1, m_boxes[i].center_y()+1), - // combine_rgb(0, 255,0)); - // } - // output.save("test_MMO_star.png"); - - return true; -} - - - -} -} -} +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonLA_MMOSpriteStarSymbolDetector.h" + + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +MMOSpriteStarSymbolDetector::MMOSpriteStarSymbolDetector(const ImageViewRGB32& frame, const std::vector& star_boxes) + : VisualInferenceCallback("MMOSpriteStarSymbolDetector") + , m_boxes(star_boxes), m_is_star(star_boxes.size(), false), m_rmsd(star_boxes.size(), 0.0) + , m_symbol_colors(star_boxes.size(), FloatPixel()) + , m_frame_width(frame.width()), m_frame_height(frame.height()) +{ + for(size_t i = 0; i < m_boxes.size(); i++){ + ImageViewRGB32 ref = extract_box_reference(frame, m_boxes[i]); + m_initial_images.push_back(std::move(ref)); + } +} + +void MMOSpriteStarSymbolDetector::make_overlays(VideoOverlaySet& items) const{ + for(const auto& box : m_boxes){ + items.add(COLOR_RED, pixelbox_to_floatbox(m_frame_width, m_frame_height, box)); + } +} + +// Return true if the inference session should stop. +bool MMOSpriteStarSymbolDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // If we already collect enough frames, then we should stop doing detection + if (m_num_frames >= 30){ + return true; + } + + // Collect image color stats: + for(size_t i = 0; i < m_boxes.size(); i++){ + ImageViewRGB32 ref = extract_box_reference(frame, m_boxes[i]); + double rmsd = ImageMatch::pixel_RMSD(m_initial_images[i], ref); + m_rmsd[i] += rmsd; + + m_symbol_colors[i] += frame.pixel(m_boxes[i].center_x(), m_boxes[i].center_y()); + } + + m_num_frames++; + + // We don't have enough frames, continue collection: + if (m_num_frames < 30){ + return false; + } + + // We have enough frames, compute stats to determine whether each sprite has a star symbol. + // Caller of this detector can query `m_is_star` to know the detection result. + // Details of the detection can be queried via `m_rmsd` and `m_symbol_colors` + // + for(size_t i = 0; i < m_boxes.size(); i++){ + // Compute average values: + m_rmsd[i] = m_rmsd[i] / (double)m_num_frames; + m_symbol_colors[i] = m_symbol_colors[i] / (double)m_num_frames; + + if (m_rmsd[i] <= 20){ + continue; + } + + if (m_symbol_colors[i].r <= m_symbol_colors[i].g * 1.2 && m_symbol_colors[i].g > 200 && m_symbol_colors[i].r > 220){ + // It's not very red, so it's not a berry symbol + m_is_star[i] = true; + } + } + + // ImageRGB32 output = frame.copy(); + // for(size_t i = 0; i < m_boxes.size(); i++){ + // draw_box(output, m_boxes[i], combine_rgb(255, 0,0)); + // draw_box(output, ImagePixelBox(m_boxes[i].center_x()-1, m_boxes[i].center_y()-1, m_boxes[i].center_x()+1, m_boxes[i].center_y()+1), + // combine_rgb(0, 255,0)); + // } + // output.save("test_MMO_star.png"); + + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h index 107e712bdd..9a07c1b968 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h @@ -1,60 +1,60 @@ -/* MMO Sprite Star Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the star symbols on MMO sprite on the map - */ - -#ifndef PokemonAutomation_PokemonLA_MMOSpriteStarSymbolDetector_H -#define PokemonAutomation_PokemonLA_MMOSpriteStarSymbolDetector_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/FloatPixel.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -// Detect the star symbols on MMO sprite on the map -class MMOSpriteStarSymbolDetector : public VisualInferenceCallback{ -public: - MMOSpriteStarSymbolDetector(const ImageViewRGB32& frame, const std::vector& star_boxes); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - // Get detection result: whether the `index`-th sprite has a star symbol. - // Not thread safe: must call after inference session ends. - bool is_star(size_t index) const { return m_is_star[index]; } - - // Get the rmsd value used to determine if `index`-th sprite has an animating symbol. - // If the value is larger than a threshold, then it is considered the sprite has an animating symbol. - // This is for debugging purposes. - // Not thread safe: must call after inference session ends. - double animation_value(size_t index) const { return m_rmsd[index]; } - - // Get the color used to determine if `index`-th sprite has a star symbol. - // Not thread safe: must call after inference session ends. - const FloatPixel& symbol_color(size_t index) const { return m_symbol_colors[index]; } - -private: - const std::vector& m_boxes; - std::vector m_is_star; - std::vector m_rmsd; - std::vector m_symbol_colors; - size_t m_num_frames = 0; - size_t m_frame_width = 0; - size_t m_frame_height = 0; - std::vector m_initial_images; - -}; - - -} -} -} -#endif +/* MMO Sprite Star Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the star symbols on MMO sprite on the map + */ + +#ifndef PokemonAutomation_PokemonLA_MMOSpriteStarSymbolDetector_H +#define PokemonAutomation_PokemonLA_MMOSpriteStarSymbolDetector_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/FloatPixel.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +// Detect the star symbols on MMO sprite on the map +class MMOSpriteStarSymbolDetector : public VisualInferenceCallback{ +public: + MMOSpriteStarSymbolDetector(const ImageViewRGB32& frame, const std::vector& star_boxes); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + // Get detection result: whether the `index`-th sprite has a star symbol. + // Not thread safe: must call after inference session ends. + bool is_star(size_t index) const { return m_is_star[index]; } + + // Get the rmsd value used to determine if `index`-th sprite has an animating symbol. + // If the value is larger than a threshold, then it is considered the sprite has an animating symbol. + // This is for debugging purposes. + // Not thread safe: must call after inference session ends. + double animation_value(size_t index) const { return m_rmsd[index]; } + + // Get the color used to determine if `index`-th sprite has a star symbol. + // Not thread safe: must call after inference session ends. + const FloatPixel& symbol_color(size_t index) const { return m_symbol_colors[index]; } + +private: + const std::vector& m_boxes; + std::vector m_is_star; + std::vector m_rmsd; + std::vector m_symbol_colors; + size_t m_num_frames = 0; + size_t m_frame_width = 0; + size_t m_frame_height = 0; + std::vector m_initial_images; + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.cpp index d2a1817670..86bc7545de 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.cpp @@ -1,52 +1,52 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA_MapDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -MapDetector::MapDetector() - : VisualInferenceCallback("MapDetector") - , m_bottom0(0.450, 0.935, 0.500, 0.015) - , m_bottom1(0.450, 0.965, 0.100, 0.020) -{} - -void MapDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_bottom0); - items.add(COLOR_RED, m_bottom1); -} - -// Return true if the inference session should stop. -bool MapDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ImageStats bottom0 = image_stats(extract_box_reference(frame, m_bottom0)); -// cout << bottom0.average << bottom0.stddev << endl; - if (!is_solid(bottom0, {0.330212, 0.334083, 0.335705})){ - return false; - } - ImageStats bottom1 = image_stats(extract_box_reference(frame, m_bottom1)); -// cout << bottom1.average << bottom1.stddev << endl; - if (!is_solid(bottom1, {0.32716, 0.33642, 0.33642})){ - return false; - } - - if (bottom0.average.sum() < bottom1.average.sum()){ - return false; - } - - return true; -} - - - -} -} -} +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA_MapDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +MapDetector::MapDetector() + : VisualInferenceCallback("MapDetector") + , m_bottom0(0.450, 0.935, 0.500, 0.015) + , m_bottom1(0.450, 0.965, 0.100, 0.020) +{} + +void MapDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_bottom0); + items.add(COLOR_RED, m_bottom1); +} + +// Return true if the inference session should stop. +bool MapDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ImageStats bottom0 = image_stats(extract_box_reference(frame, m_bottom0)); +// cout << bottom0.average << bottom0.stddev << endl; + if (!is_solid(bottom0, {0.330212, 0.334083, 0.335705})){ + return false; + } + ImageStats bottom1 = image_stats(extract_box_reference(frame, m_bottom1)); +// cout << bottom1.average << bottom1.stddev << endl; + if (!is_solid(bottom1, {0.32716, 0.33642, 0.33642})){ + return false; + } + + if (bottom0.average.sum() < bottom1.average.sum()){ + return false; + } + + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.h index a9cef6f7a0..a2cefd8dd6 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapDetector.h @@ -1,36 +1,36 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_MapDetector_H -#define PokemonAutomation_PokemonLA_MapDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -// Detect whether the map is opened -class MapDetector : public VisualInferenceCallback{ -public: - MapDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_bottom0; - ImageFloatBox m_bottom1; -}; - - -} -} -} -#endif +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_MapDetector_H +#define PokemonAutomation_PokemonLA_MapDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +// Detect whether the map is opened +class MapDetector : public VisualInferenceCallback{ +public: + MapDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_bottom0; + ImageFloatBox m_bottom1; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.cpp index a1bd46633d..be7fd5777d 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.cpp @@ -1,138 +1,138 @@ -/* Item Compatibility Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "PokemonLA_MapMarkerLocator.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -double get_orientation_on_map(const ImageViewRGB32& screen, bool avoid_lava_area){ - // The map region of the entire screen - const ImageFloatBox box(0.271, 0.059, 0.458, 0.833); - - const ImageViewRGB32 region = extract_box_reference(screen, box); - - // Find the red pixels that form the red arrow - PackedBinaryMatrix matrix = compress_rgb32_to_binary_multirange(region, - { - {combine_rgb(200, 0, 0), combine_rgb(255, 180, 180)}, - {combine_rgb(180, 0, 0), combine_rgb(255, 160, 160)}, - {combine_rgb(160, 0, 0), combine_rgb(255, 140, 140)}, - {combine_rgb(140, 0, 0), combine_rgb(255, 120, 120)}, - {combine_rgb(120, 0, 0), combine_rgb(255, 100, 100)}, - }); - - ImageRGB32 output = region.copy(); - - std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); - session->set_source(matrix); - - const size_t min_area = 100; - auto finder = session->make_iterator(min_area); - Kernels::Waterfill::WaterfillObject red_marker_obj; - bool found_red_marker = false; - // Since the lava area in coastlands is also red, to avoid confusion, we avoid the lava area: - const size_t lava_min_x = (size_t)(screen.width() * 0.636); - const size_t lava_max_x = (size_t)(screen.width() * 0.7 + 0.5); - const size_t lava_min_y = (size_t)(screen.height() * 0.124); - const size_t lava_max_y = (size_t)(screen.height() * 0.243 + 0.5); - while (finder->find_next(red_marker_obj, true)){ - const size_t center_x = (size_t)red_marker_obj.center_of_gravity_x(); - const size_t center_y = (size_t)red_marker_obj.center_of_gravity_y(); - if (center_x >= lava_min_x && center_x <= lava_max_x && center_y >= lava_min_y && center_y <= lava_max_y){ - // Skip lava area - continue; - } - // cout << red_marker_obj.area << endl; - found_red_marker = true; - break; - } - - if (!found_red_marker){ - cout << "Error: cannot find red marker on the map" << endl; - return FLT_MAX; - } - - const size_t stop = (size_t)(0.85 * red_marker_obj.area); - // matrix2 stores pixels that are at the end points of the red marker. - PackedBinaryMatrix matrix2 = remove_center_pixels(red_marker_obj, stop).first; - - draw_matrix_on_image(matrix2, combine_rgb(0, 0, 255), output, red_marker_obj.min_x, red_marker_obj.min_y); - - // Get those end point regions from matrix2 into marker_ends. - // The object in marker_ends are in the local coordinate system of the red marker - const size_t local_marker_center_x = (size_t)red_marker_obj.center_of_gravity_x() - red_marker_obj.min_x; - const size_t local_marker_center_y = (size_t)red_marker_obj.center_of_gravity_y() - red_marker_obj.min_y; - session->set_source(matrix2); - finder = session->make_iterator(1); - std::vector marker_ends; - for (Kernels::Waterfill::WaterfillObject marker_end; finder->find_next(marker_end, false);){ - marker_ends.emplace_back(std::move(marker_end)); - } - - if (marker_ends.size() != 3){ - cout << "Error: detected red marker has wrong shape. Found wrong red area on map?" << endl; - return FLT_MAX; - } - - // The angle of each marker end relative to the marker center - double end_angles[3] = {0.0, 0.0, 0.0}; - for(int i = 0; i < 3; i++){ - ptrdiff_t x = (ptrdiff_t)marker_ends[i].center_of_gravity_x() - (ptrdiff_t)local_marker_center_x; - ptrdiff_t y = (ptrdiff_t)marker_ends[i].center_of_gravity_y() - (ptrdiff_t)local_marker_center_y; - double angle = std::atan2(y, x) * 57.29577951308232; - if (angle < 0){ - angle += 360; - } - end_angles[i] = angle; - } - - // end_angle_distance[i], the angular distance between end_angles[i] and end_angles[(i+1)%3] - double end_angle_distances[3] = {0.0, 0.0, 0.0}; - // Find out which two ends form the smallest angular distance between them - int min_angle_distance_index = 0; - for(int i = 0; i < 3; i++){ - end_angle_distances[i] = std::fabs(end_angles[i] - end_angles[(i+1)%3]); - if (end_angle_distances[i] > 180){ - end_angle_distances[i] = 360 - end_angle_distances[i]; - } - - if (end_angle_distances[i] < end_angle_distances[min_angle_distance_index]){ - min_angle_distance_index = i; - } - } - - // so now the marker end with the index: min_angle_distance_index and (min_angle_distance_index+1)%3 form - // the smallest anglular distance between two ends. The other one, min_angle_distance_index+2)%3 must be - // the end where the red marker points to! - double red_marker_direction = end_angles[(min_angle_distance_index+2)%3]; - cout << "Found red marker direction " << red_marker_direction << endl; - - output.pixel((size_t)red_marker_obj.center_of_gravity_x(), (size_t)red_marker_obj.center_of_gravity_y()) = (uint32_t)Color(255, 0, 0); - output.save("./test_map_location.png"); - - return red_marker_direction; -} - - - -} -} -} +/* Item Compatibility Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "PokemonLA_MapMarkerLocator.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +double get_orientation_on_map(const ImageViewRGB32& screen, bool avoid_lava_area){ + // The map region of the entire screen + const ImageFloatBox box(0.271, 0.059, 0.458, 0.833); + + const ImageViewRGB32 region = extract_box_reference(screen, box); + + // Find the red pixels that form the red arrow + PackedBinaryMatrix matrix = compress_rgb32_to_binary_multirange(region, + { + {combine_rgb(200, 0, 0), combine_rgb(255, 180, 180)}, + {combine_rgb(180, 0, 0), combine_rgb(255, 160, 160)}, + {combine_rgb(160, 0, 0), combine_rgb(255, 140, 140)}, + {combine_rgb(140, 0, 0), combine_rgb(255, 120, 120)}, + {combine_rgb(120, 0, 0), combine_rgb(255, 100, 100)}, + }); + + ImageRGB32 output = region.copy(); + + std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); + session->set_source(matrix); + + const size_t min_area = 100; + auto finder = session->make_iterator(min_area); + Kernels::Waterfill::WaterfillObject red_marker_obj; + bool found_red_marker = false; + // Since the lava area in coastlands is also red, to avoid confusion, we avoid the lava area: + const size_t lava_min_x = (size_t)(screen.width() * 0.636); + const size_t lava_max_x = (size_t)(screen.width() * 0.7 + 0.5); + const size_t lava_min_y = (size_t)(screen.height() * 0.124); + const size_t lava_max_y = (size_t)(screen.height() * 0.243 + 0.5); + while (finder->find_next(red_marker_obj, true)){ + const size_t center_x = (size_t)red_marker_obj.center_of_gravity_x(); + const size_t center_y = (size_t)red_marker_obj.center_of_gravity_y(); + if (center_x >= lava_min_x && center_x <= lava_max_x && center_y >= lava_min_y && center_y <= lava_max_y){ + // Skip lava area + continue; + } + // cout << red_marker_obj.area << endl; + found_red_marker = true; + break; + } + + if (!found_red_marker){ + cout << "Error: cannot find red marker on the map" << endl; + return FLT_MAX; + } + + const size_t stop = (size_t)(0.85 * red_marker_obj.area); + // matrix2 stores pixels that are at the end points of the red marker. + PackedBinaryMatrix matrix2 = remove_center_pixels(red_marker_obj, stop).first; + + draw_matrix_on_image(matrix2, combine_rgb(0, 0, 255), output, red_marker_obj.min_x, red_marker_obj.min_y); + + // Get those end point regions from matrix2 into marker_ends. + // The object in marker_ends are in the local coordinate system of the red marker + const size_t local_marker_center_x = (size_t)red_marker_obj.center_of_gravity_x() - red_marker_obj.min_x; + const size_t local_marker_center_y = (size_t)red_marker_obj.center_of_gravity_y() - red_marker_obj.min_y; + session->set_source(matrix2); + finder = session->make_iterator(1); + std::vector marker_ends; + for (Kernels::Waterfill::WaterfillObject marker_end; finder->find_next(marker_end, false);){ + marker_ends.emplace_back(std::move(marker_end)); + } + + if (marker_ends.size() != 3){ + cout << "Error: detected red marker has wrong shape. Found wrong red area on map?" << endl; + return FLT_MAX; + } + + // The angle of each marker end relative to the marker center + double end_angles[3] = {0.0, 0.0, 0.0}; + for(int i = 0; i < 3; i++){ + ptrdiff_t x = (ptrdiff_t)marker_ends[i].center_of_gravity_x() - (ptrdiff_t)local_marker_center_x; + ptrdiff_t y = (ptrdiff_t)marker_ends[i].center_of_gravity_y() - (ptrdiff_t)local_marker_center_y; + double angle = std::atan2(y, x) * 57.29577951308232; + if (angle < 0){ + angle += 360; + } + end_angles[i] = angle; + } + + // end_angle_distance[i], the angular distance between end_angles[i] and end_angles[(i+1)%3] + double end_angle_distances[3] = {0.0, 0.0, 0.0}; + // Find out which two ends form the smallest angular distance between them + int min_angle_distance_index = 0; + for(int i = 0; i < 3; i++){ + end_angle_distances[i] = std::fabs(end_angles[i] - end_angles[(i+1)%3]); + if (end_angle_distances[i] > 180){ + end_angle_distances[i] = 360 - end_angle_distances[i]; + } + + if (end_angle_distances[i] < end_angle_distances[min_angle_distance_index]){ + min_angle_distance_index = i; + } + } + + // so now the marker end with the index: min_angle_distance_index and (min_angle_distance_index+1)%3 form + // the smallest anglular distance between two ends. The other one, min_angle_distance_index+2)%3 must be + // the end where the red marker points to! + double red_marker_direction = end_angles[(min_angle_distance_index+2)%3]; + cout << "Found red marker direction " << red_marker_direction << endl; + + output.pixel((size_t)red_marker_obj.center_of_gravity_x(), (size_t)red_marker_obj.center_of_gravity_y()) = (uint32_t)Color(255, 0, 0); + output.save("./test_map_location.png"); + + return red_marker_direction; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h index 8de7ef8baa..996149d3d0 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h @@ -1,37 +1,37 @@ -/* Map Location - * - * From: https://github.com/PokemonAutomation/ - * - * Function to detect player character location and orientation on the in-game map. - */ - -#ifndef PokemonAutomation_PokemonLA_MapLocation_H -#define PokemonAutomation_PokemonLA_MapLocation_H - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonLA{ - -enum class MapRegion; - -// Get which direction the player is facing by detecting the direction of the red arrow on the map. -// The orientation is measured by the angle to the positive x-axis direction on the screen image. -// The image x-axis points to the right, and y-axis points downward. -// e.g south-east direction is measured as 45 degree. -// Range of the orientation: [0, 360), or FLT_MAX if sth. wrong happens. -// -// Notes: -// - The red arrow won't be occluded by lables on the map. -// - Due to the lava being red on the map too, this function does not work if the player is inside -// the volcano area in the coastlands when viewing the map in zoom level 1 (whole region view). -// It also does not work if the player is near the volcano area when viewing the map in zoom level -// 2 (local area view). If `avoid_lava_area` is true, skip the red pixels that are in the upper right -// area of the map, which is well the lava area is on the coastlands map at zoom level 1. -double get_orientation_on_map(const ImageViewRGB32& screen, bool avoid_lava_area = false); - - -} -} -} -#endif +/* Map Location + * + * From: https://github.com/PokemonAutomation/ + * + * Function to detect player character location and orientation on the in-game map. + */ + +#ifndef PokemonAutomation_PokemonLA_MapLocation_H +#define PokemonAutomation_PokemonLA_MapLocation_H + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonLA{ + +enum class MapRegion; + +// Get which direction the player is facing by detecting the direction of the red arrow on the map. +// The orientation is measured by the angle to the positive x-axis direction on the screen image. +// The image x-axis points to the right, and y-axis points downward. +// e.g south-east direction is measured as 45 degree. +// Range of the orientation: [0, 360), or FLT_MAX if sth. wrong happens. +// +// Notes: +// - The red arrow won't be occluded by lables on the map. +// - Due to the lava being red on the map too, this function does not work if the player is inside +// the volcano area in the coastlands when viewing the map in zoom level 1 (whole region view). +// It also does not work if the player is near the volcano area when viewing the map in zoom level +// 2 (local area view). If `avoid_lava_area` is true, skip the red pixels that are in the upper right +// area of the map, which is well the lava area is on the coastlands map at zoom level 1. +double get_orientation_on_map(const ImageViewRGB32& screen, bool avoid_lava_area = false); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.cpp index df8fddbdb1..e41288a283 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.cpp @@ -1,27 +1,27 @@ -/* Map Zoom Level Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA_MapMissionTabReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -bool is_map_mission_tab_raised(const ImageViewRGB32& screen){ - // The white area around the "R" button when the tab is raise. - const ImageFloatBox box0{0.9235, 0.617, 0.003, 0.019}; - const ImageFloatBox box1{0.937, 0.62, 0.0035, 0.012}; - - return is_white(image_stats(extract_box_reference(screen, box0))) || - is_white(image_stats(extract_box_reference(screen, box1))); -} - -} -} -} +/* Map Zoom Level Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA_MapMissionTabReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +bool is_map_mission_tab_raised(const ImageViewRGB32& screen){ + // The white area around the "R" button when the tab is raise. + const ImageFloatBox box0{0.9235, 0.617, 0.003, 0.019}; + const ImageFloatBox box1{0.937, 0.62, 0.0035, 0.012}; + + return is_white(image_stats(extract_box_reference(screen, box0))) || + is_white(image_stats(extract_box_reference(screen, box1))); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h index 39ece400d9..e9f69cf6b2 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h @@ -1,26 +1,26 @@ -/* Map Mission Tab Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_PokemonLA_MapMissionTabReader_H -#define PokemonAutomation_PokemonLA_MapMissionTabReader_H - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -// Whether the Missions & Requests tab is raised on map view. -// The detection is most reliable when map is in zoom level 1: the full region map view. -// Suggest using this detection only when zoom level is 1. -bool is_map_mission_tab_raised(const ImageViewRGB32& screen); - - -} -} -} -#endif +/* Map Mission Tab Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_PokemonLA_MapMissionTabReader_H +#define PokemonAutomation_PokemonLA_MapMissionTabReader_H + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +// Whether the Missions & Requests tab is raised on map view. +// The detection is most reliable when map is in zoom level 1: the full region map view. +// Suggest using this detection only when zoom level is 1. +bool is_map_mission_tab_raised(const ImageViewRGB32& screen); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.cpp index 26f42ac807..4c5ce66c5d 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.cpp @@ -1,130 +1,130 @@ -/* Selected Region Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" -#include "PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h" -#include "PokemonLA_MapWeatherAndTimeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -ImageMatch::SilhouetteDictionaryMatcher BUILD_WEATHER_ICON_MATCHER(){ - ImageMatch::SilhouetteDictionaryMatcher matcher; - for (size_t i = 0; i < NUM_WEATHER; i++){ - matcher.add(WEATHER_NAMES[i], ALL_WEATHER_ICONS()[i]); - } - return matcher; -} - -const ImageMatch::SilhouetteDictionaryMatcher& WEATHER_ICON_MATCHER(){ - const static auto matcher = BUILD_WEATHER_ICON_MATCHER(); - return matcher; -} - - -ImageMatch::SilhouetteDictionaryMatcher BUILD_TIME_OF_DAY_ICON_MATCHER(){ - ImageMatch::SilhouetteDictionaryMatcher matcher; - for (size_t i = 0; i < NUM_TIMES_OF_DAY; i++){ - // +1 here to skip the name of TimeOfDay::NONE - matcher.add(TIME_OF_DAY_NAMES[i+1], ALL_TIME_OF_DAY_ICONS()[i]); - } - return matcher; -} - -const ImageMatch::SilhouetteDictionaryMatcher& TIME_OF_DAY_ICON_MATCHER(){ - const static auto matcher = BUILD_TIME_OF_DAY_ICON_MATCHER(); - return matcher; -} - - - - -Weather detect_weather_on_map(Logger& logger, const ImageViewRGB32& screen){ - const ImageFloatBox box{0.0285, 0.069, 0.025, 0.044}; - - // Get a loose crop of the weather icon - ImageViewRGB32 cropped_image = extract_box_reference(screen, box); - - // image.save("./weather_crop.png"); - // Get a tight crop: - const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( - cropped_image, - // The filter is a lambda function that returns true on white weather icon pixels. - [](Color pixel){ - return (uint32_t)pixel.red() + pixel.green() + pixel.blue() > 600; - } - ); - cropped_image = extract_box_reference(cropped_image, tight_box); - - // Replace the background dark pixels (outside the range from 0xffa0a0a0 to 0xffffffff) with - // 0-alpha black pixels. - const bool replace_range = false; - ImageRGB32 icon_image = filter_rgb32_range( - cropped_image, - 0xffa0a0a0, 0xffffffff, Color(0), replace_range - ); - - const auto match_result = WEATHER_ICON_MATCHER().match(icon_image, 100); - std::ostringstream os; - os << "Weather icon match result: "; - for(auto result : match_result.results){ - os << result.second << "(" << result.first << ") "; - } - logger.log(os.str(), COLOR_BLUE); - - return get_weather(match_result.results.begin()->second); -} - - -TimeOfDay detect_time_of_day_on_map(Logger& logger, const ImageViewRGB32& screen){ - const ImageFloatBox box{0.910, 0.070, 0.034, 0.041}; - - // Get a loose crop of the time of day icon - ImageViewRGB32 cropped_image = extract_box_reference(screen, box); - - // Get a tight crop: - const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( - cropped_image, - // The filter is a lambda function that returns true on white time of day icon pixels. - [](Color pixel){ - return (uint32_t)pixel.red() + pixel.green() + pixel.blue() > 600; - } - ); - cropped_image = extract_box_reference(cropped_image, tight_box); - - // Replace the background dark pixels (outside the range from 0xffa0a0a0 to 0xffffffff) with - // 0-alpha black pixels. - const bool replace_range = false; - ImageRGB32 icon_image = filter_rgb32_range( - cropped_image, - 0xffa0a0a0, 0xffffffff, Color(0), replace_range - ); - - const auto match_result = TIME_OF_DAY_ICON_MATCHER().match(icon_image, 100); - - std::ostringstream os; - os << "Time of day icon match result: "; - for(auto result : match_result.results){ - os << result.second << "(" << result.first << ") "; - } - logger.log(os.str(), COLOR_BLUE); - - return get_time_of_day(match_result.results.begin()->second); -} - - -} -} -} +/* Selected Region Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" +#include "PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h" +#include "PokemonLA_MapWeatherAndTimeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +ImageMatch::SilhouetteDictionaryMatcher BUILD_WEATHER_ICON_MATCHER(){ + ImageMatch::SilhouetteDictionaryMatcher matcher; + for (size_t i = 0; i < NUM_WEATHER; i++){ + matcher.add(WEATHER_NAMES[i], ALL_WEATHER_ICONS()[i]); + } + return matcher; +} + +const ImageMatch::SilhouetteDictionaryMatcher& WEATHER_ICON_MATCHER(){ + const static auto matcher = BUILD_WEATHER_ICON_MATCHER(); + return matcher; +} + + +ImageMatch::SilhouetteDictionaryMatcher BUILD_TIME_OF_DAY_ICON_MATCHER(){ + ImageMatch::SilhouetteDictionaryMatcher matcher; + for (size_t i = 0; i < NUM_TIMES_OF_DAY; i++){ + // +1 here to skip the name of TimeOfDay::NONE + matcher.add(TIME_OF_DAY_NAMES[i+1], ALL_TIME_OF_DAY_ICONS()[i]); + } + return matcher; +} + +const ImageMatch::SilhouetteDictionaryMatcher& TIME_OF_DAY_ICON_MATCHER(){ + const static auto matcher = BUILD_TIME_OF_DAY_ICON_MATCHER(); + return matcher; +} + + + + +Weather detect_weather_on_map(Logger& logger, const ImageViewRGB32& screen){ + const ImageFloatBox box{0.0285, 0.069, 0.025, 0.044}; + + // Get a loose crop of the weather icon + ImageViewRGB32 cropped_image = extract_box_reference(screen, box); + + // image.save("./weather_crop.png"); + // Get a tight crop: + const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( + cropped_image, + // The filter is a lambda function that returns true on white weather icon pixels. + [](Color pixel){ + return (uint32_t)pixel.red() + pixel.green() + pixel.blue() > 600; + } + ); + cropped_image = extract_box_reference(cropped_image, tight_box); + + // Replace the background dark pixels (outside the range from 0xffa0a0a0 to 0xffffffff) with + // 0-alpha black pixels. + const bool replace_range = false; + ImageRGB32 icon_image = filter_rgb32_range( + cropped_image, + 0xffa0a0a0, 0xffffffff, Color(0), replace_range + ); + + const auto match_result = WEATHER_ICON_MATCHER().match(icon_image, 100); + std::ostringstream os; + os << "Weather icon match result: "; + for(auto result : match_result.results){ + os << result.second << "(" << result.first << ") "; + } + logger.log(os.str(), COLOR_BLUE); + + return get_weather(match_result.results.begin()->second); +} + + +TimeOfDay detect_time_of_day_on_map(Logger& logger, const ImageViewRGB32& screen){ + const ImageFloatBox box{0.910, 0.070, 0.034, 0.041}; + + // Get a loose crop of the time of day icon + ImageViewRGB32 cropped_image = extract_box_reference(screen, box); + + // Get a tight crop: + const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( + cropped_image, + // The filter is a lambda function that returns true on white time of day icon pixels. + [](Color pixel){ + return (uint32_t)pixel.red() + pixel.green() + pixel.blue() > 600; + } + ); + cropped_image = extract_box_reference(cropped_image, tight_box); + + // Replace the background dark pixels (outside the range from 0xffa0a0a0 to 0xffffffff) with + // 0-alpha black pixels. + const bool replace_range = false; + ImageRGB32 icon_image = filter_rgb32_range( + cropped_image, + 0xffa0a0a0, 0xffffffff, Color(0), replace_range + ); + + const auto match_result = TIME_OF_DAY_ICON_MATCHER().match(icon_image, 100); + + std::ostringstream os; + os << "Time of day icon match result: "; + for(auto result : match_result.results){ + os << result.second << "(" << result.first << ") "; + } + logger.log(os.str(), COLOR_BLUE); + + return get_time_of_day(match_result.results.begin()->second); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h index 39786bff56..11c0eb6565 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h @@ -1,31 +1,31 @@ -/* Map weather & Time Reader - * - * From: https://github.com/PokemonAutomation/ - * - * Read the weather and time symbols on the map. - */ - - -#ifndef PokemonAutomation_PokemonLA_MapWeatherAndTimeReader_H -#define PokemonAutomation_PokemonLA_MapWeatherAndTimeReader_H - -#include "PokemonLA/PokemonLA_WeatherAndTime.h" - -namespace PokemonAutomation{ - class Logger; - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -Weather detect_weather_on_map(Logger& logger, const ImageViewRGB32& screen); - - -TimeOfDay detect_time_of_day_on_map(Logger& logger, const ImageViewRGB32& screen); - - - -} -} -} -#endif +/* Map weather & Time Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Read the weather and time symbols on the map. + */ + + +#ifndef PokemonAutomation_PokemonLA_MapWeatherAndTimeReader_H +#define PokemonAutomation_PokemonLA_MapWeatherAndTimeReader_H + +#include "PokemonLA/PokemonLA_WeatherAndTime.h" + +namespace PokemonAutomation{ + class Logger; + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +Weather detect_weather_on_map(Logger& logger, const ImageViewRGB32& screen); + + +TimeOfDay detect_time_of_day_on_map(Logger& logger, const ImageViewRGB32& screen); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.cpp index 15342427e1..ff50231210 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.cpp @@ -1,71 +1,71 @@ -/* Map Zoom Level Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonLA_MapZoomLevelReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -int read_map_zoom_level(const ImageViewRGB32& screen){ - - // The three locations of the yellow disk on the zoom gauge, from left to right. - // Left most is Hisui map, zoom level 0. Right most is local view, zoom level 2. - const ImageFloatBox boxes[3] = { - {0.780, 0.085, 0.008, 0.014}, - {0.795, 0.082, 0.010, 0.019}, - {0.807, 0.081, 0.014, 0.022}, - }; - - double max_yellow = 0; - int max_yellow_index = -1; - - for (int i = 0; i < 3; i++){ - - // Replacing non-yellow color with zero-alpha color so that they won't be counted in - // the following image_stats() - const bool replace_background = true; - size_t pixels_filtered; - ImageRGB32 region = filter_rgb32_range( - pixels_filtered, - extract_box_reference(screen, boxes[i]), - combine_rgb(0, 0, 0), combine_rgb(200, 200, 255), Color(0), replace_background - ); - if (pixels_filtered == (size_t)region.width() * (size_t)region.height()){ - // All pixels are filtered out, so no yellow color. In this case, this is defenitiely not the location - // of the yellow disk: - // std::cout << "No yellow disk at " << i << std::endl; - continue; - } - - const auto stats = image_stats(region); - - if (std::isnan(stats.average.r) == false && std::isnan(stats.average.g) == false){ - const double yellow = (stats.average.r + stats.average.g) / 2.0; - if (yellow > max_yellow){ - max_yellow_index = i; - max_yellow = yellow; - } - } - // std::cout << "Compatibility color " << stats.average << " " << stats.stddev << std::endl; - } - - return max_yellow_index; -} - - -} -} -} +/* Map Zoom Level Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonLA_MapZoomLevelReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +int read_map_zoom_level(const ImageViewRGB32& screen){ + + // The three locations of the yellow disk on the zoom gauge, from left to right. + // Left most is Hisui map, zoom level 0. Right most is local view, zoom level 2. + const ImageFloatBox boxes[3] = { + {0.780, 0.085, 0.008, 0.014}, + {0.795, 0.082, 0.010, 0.019}, + {0.807, 0.081, 0.014, 0.022}, + }; + + double max_yellow = 0; + int max_yellow_index = -1; + + for (int i = 0; i < 3; i++){ + + // Replacing non-yellow color with zero-alpha color so that they won't be counted in + // the following image_stats() + const bool replace_background = true; + size_t pixels_filtered; + ImageRGB32 region = filter_rgb32_range( + pixels_filtered, + extract_box_reference(screen, boxes[i]), + combine_rgb(0, 0, 0), combine_rgb(200, 200, 255), Color(0), replace_background + ); + if (pixels_filtered == (size_t)region.width() * (size_t)region.height()){ + // All pixels are filtered out, so no yellow color. In this case, this is defenitiely not the location + // of the yellow disk: + // std::cout << "No yellow disk at " << i << std::endl; + continue; + } + + const auto stats = image_stats(region); + + if (std::isnan(stats.average.r) == false && std::isnan(stats.average.g) == false){ + const double yellow = (stats.average.r + stats.average.g) / 2.0; + if (yellow > max_yellow){ + max_yellow_index = i; + max_yellow = yellow; + } + } + // std::cout << "Compatibility color " << stats.average << " " << stats.stddev << std::endl; + } + + return max_yellow_index; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h index 70d029ccf5..c6721fd34d 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h @@ -1,29 +1,29 @@ -/* Map Zoom Level Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_PokemonLA_MapZoomLevelReader_H -#define PokemonAutomation_PokemonLA_MapZoomLevelReader_H - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -// Return the zoom level of the map by checking the location of the yellow disk in -// the zoom gauge. -// zoom level 0: full Hisui map view -// zoom level 1: full region map view -// zoom level 2: local view -// Return -1 if the reading fails. -int read_map_zoom_level(const ImageViewRGB32& screen); - - -} -} -} -#endif +/* Map Zoom Level Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_PokemonLA_MapZoomLevelReader_H +#define PokemonAutomation_PokemonLA_MapZoomLevelReader_H + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +// Return the zoom level of the map by checking the location of the yellow disk in +// the zoom gauge. +// zoom level 0: full Hisui map view +// zoom level 1: full region map view +// zoom level 2: local view +// Return -1 if the reading fails. +int read_map_zoom_level(const ImageViewRGB32& screen); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.cpp index 4e0ebca76f..cec4ec2742 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.cpp @@ -1,57 +1,57 @@ -/* Outbreak Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -//#include "CommonFramework/Tools/ErrorDumper.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA_OutbreakReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -OutbreakReader::OutbreakReader(Logger& logger, Language language, VideoOverlay& overlay) - : m_logger(logger) - , m_language(language) - , m_dialog_box0(overlay, {0.030, 0.177, 0.020, 0.038}) - , m_dialog_box1(overlay, {0.030, 0.225, 0.020, 0.038}) - , m_text_box(overlay, {0.050, 0.177, 0.200, 0.038}) -{} - -void OutbreakReader::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_dialog_box0); - items.add(COLOR_RED, m_dialog_box1); -} -OCR::StringMatchResult OutbreakReader::read(const ImageViewRGB32& screen) const{ - OCR::StringMatchResult result; - ImageStats box0 = image_stats(extract_box_reference(screen, m_dialog_box0)); - ImageStats box1 = image_stats(extract_box_reference(screen, m_dialog_box1)); - double distance = euclidean_distance(box0.average, box1.average); - if (distance < 20){ - m_logger.log("No outbreak found.", COLOR_ORANGE); - return result; - } - - ImageViewRGB32 image = extract_box_reference(screen, m_text_box); - result = Pokemon::PokemonNameReader::instance().read_substring( - m_logger, m_language, image, - OCR::WHITE_TEXT_FILTERS() - ); - result.clear_beyond_log10p(Pokemon::PokemonNameReader::MAX_LOG10P); -// if (result.results.empty()){ -// dump_image(m_logger, ProgramInfo(), "OutbreakReader", screen); -// } - - return result; -} - - -} -} -} +/* Outbreak Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +//#include "CommonFramework/Tools/ErrorDumper.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA_OutbreakReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +OutbreakReader::OutbreakReader(Logger& logger, Language language, VideoOverlay& overlay) + : m_logger(logger) + , m_language(language) + , m_dialog_box0(overlay, {0.030, 0.177, 0.020, 0.038}) + , m_dialog_box1(overlay, {0.030, 0.225, 0.020, 0.038}) + , m_text_box(overlay, {0.050, 0.177, 0.200, 0.038}) +{} + +void OutbreakReader::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_dialog_box0); + items.add(COLOR_RED, m_dialog_box1); +} +OCR::StringMatchResult OutbreakReader::read(const ImageViewRGB32& screen) const{ + OCR::StringMatchResult result; + ImageStats box0 = image_stats(extract_box_reference(screen, m_dialog_box0)); + ImageStats box1 = image_stats(extract_box_reference(screen, m_dialog_box1)); + double distance = euclidean_distance(box0.average, box1.average); + if (distance < 20){ + m_logger.log("No outbreak found.", COLOR_ORANGE); + return result; + } + + ImageViewRGB32 image = extract_box_reference(screen, m_text_box); + result = Pokemon::PokemonNameReader::instance().read_substring( + m_logger, m_language, image, + OCR::WHITE_TEXT_FILTERS() + ); + result.clear_beyond_log10p(Pokemon::PokemonNameReader::MAX_LOG10P); +// if (result.results.empty()){ +// dump_image(m_logger, ProgramInfo(), "OutbreakReader", screen); +// } + + return result; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h index 16d6d671cb..b0b59dab90 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h @@ -1,42 +1,42 @@ -/* Outbreak Reader - * - * From: https://github.com/PokemonAutomation/ - * - * Read Outbreak pokemon text on map when leaving village - */ - -#ifndef PokemonAutomation_PokemonLA_OutbreakReader_H -#define PokemonAutomation_PokemonLA_OutbreakReader_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/OCR/OCR_StringMatchResult.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class OutbreakReader{ -public: - OutbreakReader(Logger& logger, Language language, VideoOverlay& overlay); - - void make_overlays(VideoOverlaySet& items) const; - OCR::StringMatchResult read(const ImageViewRGB32& screen) const; - - -private: - Logger& m_logger; - Language m_language; - OverlayBoxScope m_dialog_box0; - OverlayBoxScope m_dialog_box1; - OverlayBoxScope m_text_box; -}; - - - -} -} -} -#endif +/* Outbreak Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Read Outbreak pokemon text on map when leaving village + */ + +#ifndef PokemonAutomation_PokemonLA_OutbreakReader_H +#define PokemonAutomation_PokemonLA_OutbreakReader_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/OCR/OCR_StringMatchResult.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class OutbreakReader{ +public: + OutbreakReader(Logger& logger, Language language, VideoOverlay& overlay); + + void make_overlays(VideoOverlaySet& items) const; + OCR::StringMatchResult read(const ImageViewRGB32& screen) const; + + +private: + Logger& m_logger; + Language m_language; + OverlayBoxScope m_dialog_box0; + OverlayBoxScope m_dialog_box1; + OverlayBoxScope m_text_box; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.cpp index 4e3845700d..fbacef78f2 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.cpp @@ -1,1004 +1,1004 @@ -/* Selected Region Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageHSV32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Resources/SpriteDatabase.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonLA_PokemonMapSpriteReader.h" -#include "PokemonLA/Resources/PokemonLA_AvailablePokemon.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -namespace{ - -using FeatureType = double; -using FeatureVector = std::vector; - -using ImageMatch::ExactImageDictionaryMatcher; - -// We set each sprite resolution to be 50 x 50 during image matching. -const size_t IMAGE_TEMPLATE_SIZE = 50; -// The amount of pixel offset allowed in color matching -const size_t IMAGE_COLOR_MATCH_EXTRA_SIDE_EXT = 2; - -const size_t EXTENDED_IMAGE_SIZE = IMAGE_TEMPLATE_SIZE + IMAGE_COLOR_MATCH_EXTRA_SIDE_EXT * 2; - -// Defined locally stored data for matching MMO sprites: -// Store data belonging to one sprite -struct PerSpriteMatchingData{ - - FeatureVector feature; - - ImageStats rgb_stats; - - ImageHSV32 hsv_image; - - ImageRGB32 gradient_image; -}; - -using MMOSpriteMatchingMap = std::map; - -inline bool is_transparent(uint32_t g){ - return (g >> 24) < 128; -} - - -FeatureType feature_distance(const FeatureVector& a, const FeatureVector& b){ - if (a.size() != b.size()){ - cout << "Error, feature size mismatch " << a.size() << " " << b.size() << endl; - throw std::runtime_error("feature size mismatch"); - } - FeatureType sum = 0.0f; - for(size_t i = 0; i < a.size(); i++){ - FeatureType d = a[i] - b[i]; - sum += d*d; - } - - return sum; -} - -std::string feature_to_str(const FeatureVector& a){ - std::ostringstream os; - os << "["; - for(size_t i = 0; i < a.size(); i++){ - if (i != 0){ - os << ", "; - } - os << a[i]; - } - os << "]"; - return os.str(); -} - -void run_Sobel_gradient_filter(const ImageViewRGB32& image, std::function process_gradient){ - const size_t width = image.width(); - const size_t height = image.height(); - // Kernel for computing gradient along x axis - const int kx[3][3] = { - {-1, 0, 1}, - {-2, 0, 2}, - {-1, 0, 1}, - }; - // kernel for gradient along y axis - const int ky[3][3] = { - { 1, 2, 1}, - { 0, 0, 0}, - {-1, -2, -1}, - }; - const int ksz = 3; // kernel size - if (width <= ksz || height <= ksz){ - return; - } - const size_t x_end = width - ksz + 1; - const size_t y_end = height - ksz + 1; - - for(size_t y = 0; y < y_end; y++){ - for(size_t x = 0; x < x_end; x++){ - int sum_x[3] = {0, 0, 0}; - int sum_y[3] = {0, 0, 0}; - bool has_alpha_pixel = false; - for(size_t sy = 0; sy < 3; sy++){ - for(size_t sx = 0; sx < 3; sx++){ - uint32_t p = image.pixel(x + sx, y + sy); - int alpha = p >> 24; - if (alpha < 128){ - // We don't compute gradient when there is a pixel in the kernel - // scope that is transparent - has_alpha_pixel = true; - break; - } - for(int ch = 0; ch < 3; ch++){ // rgb channel - int shift = ch * 8; - int c = (uint32_t(0xff) & p >> shift); - - sum_x[ch] += c * kx[sy][sx]; - sum_y[ch] += c * ky[sy][sx]; - } - } - if (has_alpha_pixel){ - break; - } - } // end of kernel operation - if (has_alpha_pixel){ - continue; - } - - process_gradient(x+1, y+1, sum_x, sum_y); - } - } -} - -ImageRGB32 smooth_image(const ImageViewRGB32& image){ - // static int count = 0; - // { - // image.save("./test_smooth_before_" + std::to_string(count) + ".png"); - // } - - ImageRGB32 result(image.width(), image.height()); - result.fill(0); - - const float filter[5] = {0.062f, 0.244f, 0.388f, 0.244f, 0.062f}; - - size_t image_width = image.width(); - size_t image_height = image.height(); - for(size_t y = 0; y < image_height; y++){ - for(size_t x = 0; x < image_width; x++){ - float sum[3] = {0,0,0}; - float weights = 0.0; - for(size_t i = 0; i < 5; i++){ - if (x + i < 2 || x + i >= image_width + 2){ - continue; - } - size_t sx = x + i - 2; - - uint32_t p = image.pixel(sx, y); - if (is_transparent(p)){ - continue; - } - - weights += filter[i]; - - for(int ch = 0; ch < 3; ch++){ - int shift = 16 - ch * 8; - int c = (uint32_t(0xff) & p >> shift); - sum[ch] += filter[i] * c; - } - } - if (weights == 0){ - continue; - } - - char c[3]; - for(int ch = 0; ch < 3; ch++){ - sum[ch] /= weights; - int v = std::min(std::max(int(sum[ch] + 0.5f), 0), 255); - c[ch] = (char)v; - } - result.pixel(x, y) = combine_rgb(c[0], c[1], c[2]); - } - } - - ImageRGB32 result2(image.width(), image.height()); - result2.fill(0); - - for(size_t y = 0; y < image_height; y++){ - for(size_t x = 0; x < image_width; x++){ - float sum[3] = {0,0,0}; - float weights = 0.0; - for(size_t i = 0; i < 5; i++){ - if (y + i < 2 || y + i - 2 >= image_height){ - continue; - } - size_t sy = y + i - 2; - - uint32_t p = result.pixel(x, sy); - if (is_transparent(p)){ - continue; - } - - weights += filter[i]; - - for(int ch = 0; ch < 3; ch++){ - int shift = 16 - ch * 8; - int c = (uint32_t(0xff) & (p >> shift)); - sum[ch] += filter[i] * c; - } - } - if (weights == 0){ - continue; - } - - char c[3]; - for(int ch = 0; ch < 3; ch++){ - sum[ch] /= weights; - int v = std::min(std::max(int(sum[ch] + 0.5f), 0), 255); - c[ch] = (char)v; - } - result2.pixel(x, y) = combine_rgb(c[0], c[1], c[2]); - } - } - - // { - // result_ref.save("./test_smooth_middle_" + std::to_string(count) + ".png"); - // result_ref2.save("./test_smooth_after_" + std::to_string(count) + ".png"); - // count++; - // } - // exit(0); - - return result2; -} - - -ImageRGB32 compute_image_gradient(const ImageViewRGB32& image){ - ImageRGB32 result(image.width(), image.height()); - result.fill(0); - - run_Sobel_gradient_filter(image, [&](size_t x, size_t y, int sum_x[3], int sum_y[3]){ - int gx = (sum_x[0] + sum_x[1] + sum_x[2] + 1) / 3; - int gy = (sum_y[0] + sum_y[1] + sum_y[2] + 1) / 3; - - uint8_t gxc = (uint8_t)std::min(std::abs(gx), 255); - uint8_t gyc = (uint8_t)std::min(std::abs(gy), 255); - - result.pixel(x, y) = combine_rgb(gxc, gyc, 0); - }); - - return result; -} - -FeatureVector compute_gradient_histogram(const ImageViewRGB32& image){ - const int num_angle_divisions = 8; - double division_angle = 2. * M_PI / num_angle_divisions; - double inverse_division_angle = 1.0 / division_angle; - - std::array bin = {0}; - - int num_grad = 0; - - run_Sobel_gradient_filter(image, [&](size_t x, size_t y, int sum_x[3], int sum_y[3]){ - int gx = sum_x[0] + sum_x[1] + sum_x[2]; - int gy = sum_y[0] + sum_y[1] + sum_y[2]; - if (gx*gx + gy*gy <= 2000){ - return; - } - num_grad++; - - // if (count == 0){ - // // cout << "gxy " << sum_x[0] << " " << sum_x[1] << " " << sum_x[2] << ", " << - // // sum_y[0] << " " << sum_y[1] << " " << sum_y[2] << endl; - // int gxc = std::min(std::abs(gx), 255); - // int gyc = std::min(std::abs(gy), 255); - - // output_image->setPixelColor(x, y, QColor(gxc, gyc, 0)); - // } - - double angle = std::atan2(gy, gx); // range in -pi, pi - int bin_idx = int((angle + M_PI) * inverse_division_angle); - // clamp bin to [0, 11] - bin_idx = std::min(std::max(bin_idx, 0), num_angle_divisions-1); - bin[bin_idx]++; - }); - - FeatureVector result(num_angle_divisions); - for(size_t i = 0; i < num_angle_divisions; i++){ - result[i] = bin[i] / (FeatureType)num_grad; - } - - return result; -} - -} // end anonymous namespace - -FeatureVector compute_feature(const ImageViewRGB32& input_image){ - ImageRGB32 image = input_image.copy(); - size_t width = image.width(); - size_t height = image.height(); - - // Set pixel outside the sprite circle to transparent: - double r = (width + height) / 4.0; - double center_x = (width-1) / 2.0f; - double center_y = (height-1) / 2.0f; - double r2 = r * r; - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - if ((x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) >= r2){ - image.pixel(x, y) = 0; - } - } - } - - // Divide the image into 4 areas, compute average color on each. - // Note: we skip the upper right area because that area may overlap with - // the berry or star (bonus wave) symbol. - const int num_divisions = 2; - const double portion = 1.0 / (double)num_divisions; - FeatureVector result; - for(int i = 0; i < num_divisions; i++){ - for(int j = 0; j < num_divisions; j++){ - if (i == 1 && j == 0){ - continue; // skip the berry / bonus wave overlapping area - } - ImageFloatBox box{i*portion, j*portion, portion, portion}; - auto sub_image = extract_box_reference(image, box); - - ImageStats stats = image_stats(sub_image); - - result.push_back(stats.average.r); - result.push_back(stats.average.g); - result.push_back(stats.average.b); - } - } - - return result; -} - -void load_and_visit_MMO_sprite(std::function visit_sprit){ - static const SpriteDatabase database("PokemonLA/MMOSprites.png", "PokemonLA/MMOSprites.json"); - for (const auto& item : database){ - // cout << "sprite " << count << endl; - const std::string& slug = item.first; - const auto& sprite = item.second.sprite; - if (sprite.width() != 128 || sprite.height() != 128){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Wrong size of Loaded MMO Sprite sprite: " + slug); - } - visit_sprit(slug, item.second.sprite.sub_image(12, 12, 104, 104).scale_to(50, 50)); - } -} - -MMOSpriteMatchingMap build_MMO_sprite_matching_data(){ - - MMOSpriteMatchingMap sprite_map; - - load_and_visit_MMO_sprite([&](const std::string& slug, const ImageViewRGB32& sprite){ - - PerSpriteMatchingData per_sprite_data; - - per_sprite_data.rgb_stats = image_stats(sprite); - per_sprite_data.hsv_image = ImageHSV32(sprite); - - ImageRGB32 smoothed_sprite = smooth_image(sprite); - per_sprite_data.gradient_image = compute_image_gradient(smoothed_sprite); - per_sprite_data.feature = compute_feature(smoothed_sprite); - - sprite_map.emplace(slug, std::move(per_sprite_data)); - }); - - return sprite_map; -} - -const MMOSpriteMatchingMap& MMO_SPRITE_MATCHING_DATA(){ - const static auto& sprite_matching_data = build_MMO_sprite_matching_data(); - - return sprite_matching_data; -} - - -std::multimap match_pokemon_map_sprite_feature(const ImageViewRGB32& image, MapRegion region){ - const FeatureVector& image_feature = compute_feature(image); - - const MMOSpriteMatchingMap& sprite_map = MMO_SPRITE_MATCHING_DATA(); - - const std::array, 5>& region_available_sprites = MMO_FIRST_WAVE_REGION_SPRITE_SLUGS(); - int region_index = 0; - switch(region){ - case MapRegion::FIELDLANDS: - region_index = 0; - break; - case MapRegion::MIRELANDS: - region_index = 1; - break; - case MapRegion::COASTLANDS: - region_index = 2; - break; - case MapRegion::HIGHLANDS: - region_index = 3; - break; - case MapRegion::ICELANDS: - region_index = 4; - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid region."); -// return {}; - } - - // cout << "input image feature: " << feature_to_str(image_feature) << endl; - - // FeatureType closest_dist = FLT_MAX; - // std::string closest_slug = ""; - - std::multimap result; - - for(const auto& slug : region_available_sprites[region_index]){ - auto it = sprite_map.find(slug); - if (it == sprite_map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Inconsistent sprite slug definitions in resource: " + slug); - } - - const FeatureVector& feature = it->second.feature; - const FeatureType dist = feature_distance(image_feature, feature); - result.emplace(dist, slug); - } - - // cout << "Closest feature distance " << closest_dist << ", slug " << closest_slug << endl; - // cout << feature_to_str(features.find(closest_slug)->second) << endl; - - return result; -} - - -ImageHSV32 compute_MMO_sprite_color_hsv(const ImageViewRGB32& image_rgb){ - // Convert the image to HSV during ImageHSV32 class construction - ImageHSV32 result = [&](){ - if (image_rgb.width() == EXTENDED_IMAGE_SIZE || image_rgb.height() == EXTENDED_IMAGE_SIZE){ - return ImageHSV32(image_rgb); - } - // First scale the image - return ImageHSV32(image_rgb.scale_to(EXTENDED_IMAGE_SIZE, EXTENDED_IMAGE_SIZE)); - }(); - - const size_t width = result.width(); - const size_t height = result.height(); - - // Set all the pixels outside the sprite area transparent to avoid matching the template to background colors. - double r = (width + height) / 4.0; - double center_x = (width-1) / 2.0f; - double center_y = (height-1) / 2.0f; - // -r/12 to remove some boundary areas - double dist2_th = (r - r/12) * (r - r/12); - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - if ((x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) >= dist2_th){ - // color outside of the sprite circle is set to zero transparency - result.pixel(x, y) = uint32_t(0); - } - // else if (x > center_x && y < center_y){ - // // Upper-right part of the sprite is set to zero transparency to avoid matching the - // // berry or star symbol - // result.pixel(x, y) = uint32_t(0); - // } - } - } - return result; -} - - -// For a sprite on the screenshot, create gradient image of it -ImageRGB32 compute_MMO_sprite_gradient(const ImageViewRGB32& image){ - - ImageRGB32 result = [&](){ - if (image.width() == IMAGE_TEMPLATE_SIZE || image.height() == IMAGE_TEMPLATE_SIZE){ - return smooth_image(image); - } - // First scale the image - return smooth_image(image.scale_to(IMAGE_TEMPLATE_SIZE, IMAGE_TEMPLATE_SIZE)); - }(); - result = compute_image_gradient(result); - - size_t width = image.width(); - size_t height = image.height(); - if (width == 0 || height == 0){ - return result; - } - - // Remove gradients outside of the image area - double r = (width + height) / 4.0; - double center_x = (width-1) / 2.0f; - double center_y = (height-1) / 2.0f; - // -r/8 to remove some boundary areas - double dist2_th = (r - r/8) * (r - r/8); - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - if ((x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) >= dist2_th){ - // gradients outside of the sprite circle is set to zero - result.pixel(x, y) = combine_argb(0,0,0,0); - } - // else if (x > center_x && y < center_y){ - // // Upper-right part of the sprite is set to zero transparency to avoid matching the - // // berry or star symbol - // result.pixel(x, y) = uint32_t(0); - // } - } - } - return result; -} - - - - - - - - - - - -double compute_MMO_sprite_gradient_distance(const ImageViewRGB32& gradient_template, const ImageViewRGB32& gradient){ - int tempt_width = (int)gradient_template.width(); - int tempt_height = (int)gradient_template.height(); - - double score = 0.0f; - int max_offset = 2; - - auto compute_pixel_dist = [](uint32_t t_g, uint32_t g){ - int gx = uint32_t(0xff) & (g >> 16); - int gy = uint32_t(0xff) & (g >> 8); - int t_gx = uint32_t(0xff) & (t_g >> 16); - int t_gy = uint32_t(0xff) & (t_g >> 8); - double pixel_score = std::max(t_gx, gx) * (gx - t_gx) * (gx - t_gx) + std::max(t_gy, gy) * (gy - t_gy) * (gy - t_gy); - pixel_score /= 255; - return pixel_score; - }; - - -// #define USE_IMAGE_LEVEL_TRANSLATION -// #define USE_PIXEL_LEVEL_TRANSLATION -#define USE_BLOCK_LEVEL_TRANSLATION - -#ifdef USE_IMAGE_LEVEL_TRANSLATION - score = FLT_MAX; - for(int oy = -max_offset; oy <= max_offset; oy++){ // offset_y - for(int ox = -max_offset; ox <= max_offset; ox++){ // offset_x - - float match_score = 0.0; - int num_gradients = 0; - for(size_t y = 0; y < gradient.height(); y++){ - for(size_t x = 0; x < gradient.width(); x++){ - uint32_t g = gradient.pixel(x, y); - if (is_transparent(g)){ - continue; - } - int my = (int)(y + oy); // moved y - int mx = (int)(x + ox); // moved x - if (mx < 0 || mx >= tempt_width || my < 0 || my >= tempt_height){ - continue; - } - - uint32_t t_g = gradient_template.pixel(mx, my); - if (is_transparent(t_g)){ - continue; - } - - num_gradients++; - - float pixel_score = compute_pixel_dist(t_g, g); - match_score += pixel_score; - - // output.setPixelColor(x, y, QColor( - // std::min((int)std::sqrt(gx*gx+gy*gy),255), - // std::min((int)std::sqrt(t_gx*t_gx+t_gy*t_gy), 255), - // 0 - // )); - } - } - - match_score = std::sqrt(match_score / num_gradients); - if (match_score < score){ - score = match_score; - } - } - } - score = std::sqrt(score); -#endif - -#ifdef USE_PIXEL_LEVEL_TRANSLATION - score = 0; - int num_gradients = 0; - for(size_t y = 0; y < gradient.height(); y++){ - for(size_t x = 0; x < gradient.width(); x++){ - uint32_t g = gradient.pixel(x, y); - uint32_t gx = uint32_t(0xff) & (g >> 16); - uint32_t gy = uint32_t(0xff) & (g >> 8); - uint32_t alpha = g >> 24; - if (alpha < 128){ - continue; - } - - float min_pixel_score = FLT_MAX; - for(int oy = -max_offset; oy <= max_offset; oy++){ // offset_y - for(int ox = -max_offset; ox <= max_offset; ox++){ // offset_x - int my = (int)(y + oy); // moved y - int mx = (int)(x + ox); // moved x - if (mx < 0 || mx >= tempt_width || my < 0 || my >= tempt_height){ - continue; - } - // int dist_x = std::abs(ox); - // int dist_y = std::abs(oy); - // int dist2 = dist_x * dist_x + dist_y * dist_y; - uint32_t t_g = scaled_template.pixel(mx, my); - uint32_t t_a = t_g >> 24; - if (t_a < 128){ - continue; - } - - uint32_t t_gx = uint32_t(0xff) & (t_g >> 16); - uint32_t t_gy = uint32_t(0xff) & (t_g >> 8); - float pixel_score = std::max(t_gx, gx) * (gx - t_gx) * (gx - t_gx) + std::max(t_gy, gy) * (gy - t_gy) * (gy - t_gy); - pixel_score /= 255; - if (pixel_score < min_pixel_score){ - min_pixel_score = pixel_score; - } - - if (ox == 0 && oy == 0){ - output.setPixelColor(x, y, QColor( - std::min((int)std::sqrt(gx*gx+gy*gy),255), - std::min((int)std::sqrt(t_gx*t_gx+t_gy*t_gy), 255), - 0 - )); - } - } - } // end offset - - if (min_pixel_score < FLT_MAX){ - score += min_pixel_score; - num_gradients++; - } - } - } - score = std::sqrt(score / num_gradients); -#endif - -#ifdef USE_BLOCK_LEVEL_TRANSLATION - int block_radius = 5; - - score = 0; - int num_gradients = 0; - - for(int y = 0; y < (int)gradient.height(); y++){ - for(int x = 0; x < (int)gradient.width(); x++){ - uint32_t g = gradient.pixel(x, y); - if (is_transparent(g)){ - continue; - } - - double min_block_score = FLT_MAX; - for(int oy = -max_offset; oy <= max_offset; oy++){ // offset_y - for(int ox = -max_offset; ox <= max_offset; ox++){ // offset_x - - double block_score = 0.0; - int block_size = 0; - for(int by = y - block_radius; by <= y + block_radius; by++){ - for(int bx = x - block_radius; bx <= x + block_radius; bx++){ - if (bx < 0 || bx >= (int)gradient.width() || by < 0 || by >= (int)gradient.height()){ - continue; - } - - uint32_t bg = gradient.pixel(bx, by); - if (is_transparent(bg)){ - continue; - } - - int ty = by + oy; // template y - int tx = bx + ox; // template x - if (tx < 0 || tx >= tempt_width || ty < 0 || ty >= tempt_height){ - continue; - } - uint32_t t_bg = gradient_template.pixel(tx, ty); - if (is_transparent(t_bg)){ - continue; - } - - block_score += compute_pixel_dist(t_bg, bg); - block_size++; - } - } - block_score = block_score / block_size; - min_block_score = std::min(min_block_score, block_score); - } - } // end offset - - if (min_block_score < FLT_MAX){ - score += min_block_score; - num_gradients++; - } - } - } - score = std::sqrt(score / num_gradients); -#endif - - // output.save("test_distance_alignment_" + QString::number(count) + ".png"); - // count++; - - return score; -} - -double compute_hsv_dist2(uint32_t template_color, uint32_t color){ - int t_h = (uint32_t(0xff) & (template_color >> 16)); - int t_s = (uint32_t(0xff) & (template_color >> 8)); - int t_v = (uint32_t(0xff) & template_color); - - int h = (uint32_t(0xff) & (color >> 16)); - int s = (uint32_t(0xff) & (color >> 8)); - int v = (uint32_t(0xff) & color); - - int h_dif = std::abs(t_h - h); - if (h_dif > 255 - h_dif){ - h_dif = 256 - h_dif; - } - - return h_dif * h_dif + (t_s - s) * (t_s - s) + 0.5 * (t_v - v) * (t_v - v); -} - -double compute_MMO_sprite_hsv_distance(const ImageViewHSV32& image_template, const ImageViewHSV32& query_image){ - size_t tempt_width = image_template.width(); - size_t tempt_height = image_template.height(); - - // cout << tempt_width << " " << tempt_height << " " << query_image.width() << " " << query_image.height() << endl; - double score = 0.0; - int num_pixels = 0; - for (size_t y = 0; y < query_image.height(); y++){ - for (size_t x = 0; x < query_image.width(); x++){ - uint32_t p = query_image.pixel(x, y); - if (is_transparent(p)){ - // cout << "Skip query pixel " << x << " " << y << endl; - continue; - } - if (x >= tempt_width || y >= tempt_height){ - continue; - } - - uint32_t t_p = image_template.pixel(x, y); - if (is_transparent(t_p)){ - // cout << "Skip template pixel " << x << " " << y << endl; - continue; - } - - num_pixels++; - - double pixel_score = compute_hsv_dist2(t_p, p); - score += pixel_score; - } - } - - score = std::sqrt(score / num_pixels); - // cout << "score " << score << " " << num_pixels << endl; - // exit(0); - return score; -} - - -MapSpriteMatchResult match_sprite_on_map(Logger& logger, const ImageViewRGB32& screen, const ImagePixelBox& box, MapRegion region, bool debug_mode){ - const static auto& sprite_map = MMO_SPRITE_MATCHING_DATA(); - - auto save_debug_image_if_required = [&](const MapSpriteMatchResult& result){ - if (debug_mode == false){ - return; - } - const std::string debug_path = std::string("PokemonLA/PokemonMapSpriteReader/") + std::string(WILD_REGION_SHORT_NAMES[(int)region-2]) - + "/" + result.slug; - - dump_debug_image(logger, debug_path, result.slug, extract_box_reference(screen, box.expand_as(5))); - }; - - // configs for the algorithm: - const size_t num_feature_candidates = 10; - const double color_difference_threshold = 10.0; - const double gradient_confidence_threshold = 2.0; - const double color_to_gradient_confidence_scale = 2.0; - - MapSpriteMatchResult result; - logger.log("Start map MMO sprite matching:"); - - // This map has the match score for all sprites. - // This map must be not empty for subsequent computation. - const auto& feature_map = match_pokemon_map_sprite_feature(extract_box_reference(screen, box), region); - - for (const auto& p : feature_map){ - result.candidates.push_back(p.second); - if (result.candidates.size() >= num_feature_candidates){ - break; - } - } - - { - std::ostringstream os; - os << " Candidates: "; - for(size_t i = 0; i < result.candidates.size(); i++){ - if (i > 0){ - os << ", "; - } - os << result.candidates[i]; - } - logger.log(os.str()); - } - - // Should not happen if we correctly loads the sprite data. - if (result.candidates.size() == 0){ - return result; - } - - logger.log("Color matching..."); - { - const ImagePixelBox expanded_box = box.expand_as(2); - const ImageHSV32 sprite_hsv = compute_MMO_sprite_color_hsv(extract_box_reference(screen, expanded_box)); - - for(const auto& slug: result.candidates){ - const ImageHSV32& candidate_template = sprite_map.find(slug)->second.hsv_image; - double score = FLT_MAX; - for(size_t ox = 0; ox <= 4; ox++){ - for(size_t oy = 0; oy <= 4; oy++){ - ImagePixelBox shifted_box(ox, oy, box.width(), box.height()); - double match_score = compute_MMO_sprite_hsv_distance( - candidate_template, - extract_box_reference(sprite_hsv, shifted_box) - ); - score = std::min(match_score, score); - } - } - - result.color_match_results.emplace(score, slug); - } - } - - // Build a map from sprite to their color score and output scores for debugging - std::map color_match_sprite_scores; - int result_count = 0; - for(const auto& p : result.color_match_results){ - const auto& slug = p.second; - color_match_sprite_scores.emplace(slug, p.first); - if (result_count < 5){ - const auto& stats = sprite_map.find(slug)->second.rgb_stats; - std::ostringstream os; - os << p.first << " - " << slug << " " << stats.stddev.sum(); - logger.log(os.str()); - } - if (result_count == 5){ - size_t num_rest_results = result.color_match_results.size() - 5; - std::ostringstream os; - os << "Skip " << num_rest_results << " more result" << (num_rest_results > 1 ? "s" : ""); - logger.log(os.str()); - } - - result_count++; - } - - auto color_top = result.color_match_results.begin(); - const std::string& color_top_slug = color_top->second; - auto color_second = color_top; - color_second++; - - result.slug = color_top_slug; - result.color_score = color_top->first; - - if (color_second == result.color_match_results.end()){ - // we only have one color match result. - result.color_lead = DBL_MAX; - logger.log("Single color match result: " + color_top_slug); - save_debug_image_if_required(result); - return result; - } - - // We have some sprites which have closer scores to the top color match: - // Find the difference between the top and second match score - result.color_lead = color_second->first - result.color_score; - { - std::ostringstream os; - os << "Top color score: " << result.color_score << " diff to second: " << result.color_lead; - logger.log(os.str()); - } - - if (result.color_lead >= color_difference_threshold){ - logger.log("Color difference large enough. Good match: " + result.slug); - result.second_slug = color_second->second; - save_debug_image_if_required(result); - return result; - } - - logger.log("Gradient matching..."); - ImageRGB32 gradient_image = compute_MMO_sprite_gradient(extract_box_reference(screen, box)); - - // std::ostringstream os; - // os << "test_sprite_gradient" << count << "_" << std::setfill('0') << std::setw(2) << i << ".png"; - // std::string sprite_filename = os.str(); - // gradient_image.save(sprite_filename); - - for(const auto& p : result.color_match_results){ - const auto& slug = p.second; - ImageViewRGB32 template_gradient = sprite_map.find(slug)->second.gradient_image; - double score = compute_MMO_sprite_gradient_distance(template_gradient, gradient_image); - result.gradient_match_results.emplace(score, slug); - } - - result_count = 0; - for(const auto& p : result.gradient_match_results){ - if (result_count == 5){ - size_t num_rest_results = result.gradient_match_results.size() - 5; - std::ostringstream os; - os << "Skip " << num_rest_results << " more result" << (num_rest_results > 1 ? "s" : ""); - logger.log(os.str()); - break; - } - std::ostringstream os; - os << p.first << " - " << p.second; - logger.log(os.str()); - result_count++; - } - - // In case the gradient match is not confident, rely again on the color match: - auto gradient_top = result.gradient_match_results.begin(); - const auto& gradient_top_slug = gradient_top->second; - auto gradient_second = gradient_top; - gradient_second++; - const auto& gradient_second_slug = gradient_second->second; - - result.slug = gradient_top_slug; - result.gradient_score = gradient_top->first; - result.gradient_lead = gradient_second->first - gradient_top->first; - result.second_slug = gradient_second_slug; - - { - std::ostringstream os; - os << "Top gradient score: " << result.gradient_score << " diff to second: " << result.gradient_lead; - logger.log(os.str()); - } - - if (result.gradient_lead >= gradient_confidence_threshold){ - logger.log("Gradient difference large enough. Good match: " + result.slug); - save_debug_image_if_required(result); - return result; - } - - // The diff between top and second gradient match is close - // Let's check their color score: - result.graident_top_color_score = color_match_sprite_scores[gradient_top_slug]; - result.gradient_second_color_score = color_match_sprite_scores[gradient_second_slug]; - double color_diff = result.gradient_second_color_score - result.graident_top_color_score; - - { - std::ostringstream os; - os << "Gradient difference not large enough. Check color difference: " << - result.graident_top_color_score << " vs " << result.gradient_second_color_score << ", diff: " << - color_diff; - logger.log(os.str()); - } - - // If color score is more confident in telling those two sprites apart - if (std::fabs(color_diff) > result.gradient_lead * color_to_gradient_confidence_scale){ - if (color_diff < 0){ // second gradient sprite is better in color matching than the first graident sprite: - result.pick_gradient_second = true; - std::swap(result.slug, result.second_slug); - logger.log("Switch to more confident color result: " + result.slug); - } - }else{ - logger.log("Low confidence match: " + result.slug); - } - - save_debug_image_if_required(result); - return result; -} - - - - - -} -} -} +/* Selected Region Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageHSV32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Resources/SpriteDatabase.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonLA_PokemonMapSpriteReader.h" +#include "PokemonLA/Resources/PokemonLA_AvailablePokemon.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +namespace{ + +using FeatureType = double; +using FeatureVector = std::vector; + +using ImageMatch::ExactImageDictionaryMatcher; + +// We set each sprite resolution to be 50 x 50 during image matching. +const size_t IMAGE_TEMPLATE_SIZE = 50; +// The amount of pixel offset allowed in color matching +const size_t IMAGE_COLOR_MATCH_EXTRA_SIDE_EXT = 2; + +const size_t EXTENDED_IMAGE_SIZE = IMAGE_TEMPLATE_SIZE + IMAGE_COLOR_MATCH_EXTRA_SIDE_EXT * 2; + +// Defined locally stored data for matching MMO sprites: +// Store data belonging to one sprite +struct PerSpriteMatchingData{ + + FeatureVector feature; + + ImageStats rgb_stats; + + ImageHSV32 hsv_image; + + ImageRGB32 gradient_image; +}; + +using MMOSpriteMatchingMap = std::map; + +inline bool is_transparent(uint32_t g){ + return (g >> 24) < 128; +} + + +FeatureType feature_distance(const FeatureVector& a, const FeatureVector& b){ + if (a.size() != b.size()){ + cout << "Error, feature size mismatch " << a.size() << " " << b.size() << endl; + throw std::runtime_error("feature size mismatch"); + } + FeatureType sum = 0.0f; + for(size_t i = 0; i < a.size(); i++){ + FeatureType d = a[i] - b[i]; + sum += d*d; + } + + return sum; +} + +std::string feature_to_str(const FeatureVector& a){ + std::ostringstream os; + os << "["; + for(size_t i = 0; i < a.size(); i++){ + if (i != 0){ + os << ", "; + } + os << a[i]; + } + os << "]"; + return os.str(); +} + +void run_Sobel_gradient_filter(const ImageViewRGB32& image, std::function process_gradient){ + const size_t width = image.width(); + const size_t height = image.height(); + // Kernel for computing gradient along x axis + const int kx[3][3] = { + {-1, 0, 1}, + {-2, 0, 2}, + {-1, 0, 1}, + }; + // kernel for gradient along y axis + const int ky[3][3] = { + { 1, 2, 1}, + { 0, 0, 0}, + {-1, -2, -1}, + }; + const int ksz = 3; // kernel size + if (width <= ksz || height <= ksz){ + return; + } + const size_t x_end = width - ksz + 1; + const size_t y_end = height - ksz + 1; + + for(size_t y = 0; y < y_end; y++){ + for(size_t x = 0; x < x_end; x++){ + int sum_x[3] = {0, 0, 0}; + int sum_y[3] = {0, 0, 0}; + bool has_alpha_pixel = false; + for(size_t sy = 0; sy < 3; sy++){ + for(size_t sx = 0; sx < 3; sx++){ + uint32_t p = image.pixel(x + sx, y + sy); + int alpha = p >> 24; + if (alpha < 128){ + // We don't compute gradient when there is a pixel in the kernel + // scope that is transparent + has_alpha_pixel = true; + break; + } + for(int ch = 0; ch < 3; ch++){ // rgb channel + int shift = ch * 8; + int c = (uint32_t(0xff) & p >> shift); + + sum_x[ch] += c * kx[sy][sx]; + sum_y[ch] += c * ky[sy][sx]; + } + } + if (has_alpha_pixel){ + break; + } + } // end of kernel operation + if (has_alpha_pixel){ + continue; + } + + process_gradient(x+1, y+1, sum_x, sum_y); + } + } +} + +ImageRGB32 smooth_image(const ImageViewRGB32& image){ + // static int count = 0; + // { + // image.save("./test_smooth_before_" + std::to_string(count) + ".png"); + // } + + ImageRGB32 result(image.width(), image.height()); + result.fill(0); + + const float filter[5] = {0.062f, 0.244f, 0.388f, 0.244f, 0.062f}; + + size_t image_width = image.width(); + size_t image_height = image.height(); + for(size_t y = 0; y < image_height; y++){ + for(size_t x = 0; x < image_width; x++){ + float sum[3] = {0,0,0}; + float weights = 0.0; + for(size_t i = 0; i < 5; i++){ + if (x + i < 2 || x + i >= image_width + 2){ + continue; + } + size_t sx = x + i - 2; + + uint32_t p = image.pixel(sx, y); + if (is_transparent(p)){ + continue; + } + + weights += filter[i]; + + for(int ch = 0; ch < 3; ch++){ + int shift = 16 - ch * 8; + int c = (uint32_t(0xff) & p >> shift); + sum[ch] += filter[i] * c; + } + } + if (weights == 0){ + continue; + } + + char c[3]; + for(int ch = 0; ch < 3; ch++){ + sum[ch] /= weights; + int v = std::min(std::max(int(sum[ch] + 0.5f), 0), 255); + c[ch] = (char)v; + } + result.pixel(x, y) = combine_rgb(c[0], c[1], c[2]); + } + } + + ImageRGB32 result2(image.width(), image.height()); + result2.fill(0); + + for(size_t y = 0; y < image_height; y++){ + for(size_t x = 0; x < image_width; x++){ + float sum[3] = {0,0,0}; + float weights = 0.0; + for(size_t i = 0; i < 5; i++){ + if (y + i < 2 || y + i - 2 >= image_height){ + continue; + } + size_t sy = y + i - 2; + + uint32_t p = result.pixel(x, sy); + if (is_transparent(p)){ + continue; + } + + weights += filter[i]; + + for(int ch = 0; ch < 3; ch++){ + int shift = 16 - ch * 8; + int c = (uint32_t(0xff) & (p >> shift)); + sum[ch] += filter[i] * c; + } + } + if (weights == 0){ + continue; + } + + char c[3]; + for(int ch = 0; ch < 3; ch++){ + sum[ch] /= weights; + int v = std::min(std::max(int(sum[ch] + 0.5f), 0), 255); + c[ch] = (char)v; + } + result2.pixel(x, y) = combine_rgb(c[0], c[1], c[2]); + } + } + + // { + // result_ref.save("./test_smooth_middle_" + std::to_string(count) + ".png"); + // result_ref2.save("./test_smooth_after_" + std::to_string(count) + ".png"); + // count++; + // } + // exit(0); + + return result2; +} + + +ImageRGB32 compute_image_gradient(const ImageViewRGB32& image){ + ImageRGB32 result(image.width(), image.height()); + result.fill(0); + + run_Sobel_gradient_filter(image, [&](size_t x, size_t y, int sum_x[3], int sum_y[3]){ + int gx = (sum_x[0] + sum_x[1] + sum_x[2] + 1) / 3; + int gy = (sum_y[0] + sum_y[1] + sum_y[2] + 1) / 3; + + uint8_t gxc = (uint8_t)std::min(std::abs(gx), 255); + uint8_t gyc = (uint8_t)std::min(std::abs(gy), 255); + + result.pixel(x, y) = combine_rgb(gxc, gyc, 0); + }); + + return result; +} + +FeatureVector compute_gradient_histogram(const ImageViewRGB32& image){ + const int num_angle_divisions = 8; + double division_angle = 2. * M_PI / num_angle_divisions; + double inverse_division_angle = 1.0 / division_angle; + + std::array bin = {0}; + + int num_grad = 0; + + run_Sobel_gradient_filter(image, [&](size_t x, size_t y, int sum_x[3], int sum_y[3]){ + int gx = sum_x[0] + sum_x[1] + sum_x[2]; + int gy = sum_y[0] + sum_y[1] + sum_y[2]; + if (gx*gx + gy*gy <= 2000){ + return; + } + num_grad++; + + // if (count == 0){ + // // cout << "gxy " << sum_x[0] << " " << sum_x[1] << " " << sum_x[2] << ", " << + // // sum_y[0] << " " << sum_y[1] << " " << sum_y[2] << endl; + // int gxc = std::min(std::abs(gx), 255); + // int gyc = std::min(std::abs(gy), 255); + + // output_image->setPixelColor(x, y, QColor(gxc, gyc, 0)); + // } + + double angle = std::atan2(gy, gx); // range in -pi, pi + int bin_idx = int((angle + M_PI) * inverse_division_angle); + // clamp bin to [0, 11] + bin_idx = std::min(std::max(bin_idx, 0), num_angle_divisions-1); + bin[bin_idx]++; + }); + + FeatureVector result(num_angle_divisions); + for(size_t i = 0; i < num_angle_divisions; i++){ + result[i] = bin[i] / (FeatureType)num_grad; + } + + return result; +} + +} // end anonymous namespace + +FeatureVector compute_feature(const ImageViewRGB32& input_image){ + ImageRGB32 image = input_image.copy(); + size_t width = image.width(); + size_t height = image.height(); + + // Set pixel outside the sprite circle to transparent: + double r = (width + height) / 4.0; + double center_x = (width-1) / 2.0f; + double center_y = (height-1) / 2.0f; + double r2 = r * r; + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + if ((x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) >= r2){ + image.pixel(x, y) = 0; + } + } + } + + // Divide the image into 4 areas, compute average color on each. + // Note: we skip the upper right area because that area may overlap with + // the berry or star (bonus wave) symbol. + const int num_divisions = 2; + const double portion = 1.0 / (double)num_divisions; + FeatureVector result; + for(int i = 0; i < num_divisions; i++){ + for(int j = 0; j < num_divisions; j++){ + if (i == 1 && j == 0){ + continue; // skip the berry / bonus wave overlapping area + } + ImageFloatBox box{i*portion, j*portion, portion, portion}; + auto sub_image = extract_box_reference(image, box); + + ImageStats stats = image_stats(sub_image); + + result.push_back(stats.average.r); + result.push_back(stats.average.g); + result.push_back(stats.average.b); + } + } + + return result; +} + +void load_and_visit_MMO_sprite(std::function visit_sprit){ + static const SpriteDatabase database("PokemonLA/MMOSprites.png", "PokemonLA/MMOSprites.json"); + for (const auto& item : database){ + // cout << "sprite " << count << endl; + const std::string& slug = item.first; + const auto& sprite = item.second.sprite; + if (sprite.width() != 128 || sprite.height() != 128){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Wrong size of Loaded MMO Sprite sprite: " + slug); + } + visit_sprit(slug, item.second.sprite.sub_image(12, 12, 104, 104).scale_to(50, 50)); + } +} + +MMOSpriteMatchingMap build_MMO_sprite_matching_data(){ + + MMOSpriteMatchingMap sprite_map; + + load_and_visit_MMO_sprite([&](const std::string& slug, const ImageViewRGB32& sprite){ + + PerSpriteMatchingData per_sprite_data; + + per_sprite_data.rgb_stats = image_stats(sprite); + per_sprite_data.hsv_image = ImageHSV32(sprite); + + ImageRGB32 smoothed_sprite = smooth_image(sprite); + per_sprite_data.gradient_image = compute_image_gradient(smoothed_sprite); + per_sprite_data.feature = compute_feature(smoothed_sprite); + + sprite_map.emplace(slug, std::move(per_sprite_data)); + }); + + return sprite_map; +} + +const MMOSpriteMatchingMap& MMO_SPRITE_MATCHING_DATA(){ + const static auto& sprite_matching_data = build_MMO_sprite_matching_data(); + + return sprite_matching_data; +} + + +std::multimap match_pokemon_map_sprite_feature(const ImageViewRGB32& image, MapRegion region){ + const FeatureVector& image_feature = compute_feature(image); + + const MMOSpriteMatchingMap& sprite_map = MMO_SPRITE_MATCHING_DATA(); + + const std::array, 5>& region_available_sprites = MMO_FIRST_WAVE_REGION_SPRITE_SLUGS(); + int region_index = 0; + switch(region){ + case MapRegion::FIELDLANDS: + region_index = 0; + break; + case MapRegion::MIRELANDS: + region_index = 1; + break; + case MapRegion::COASTLANDS: + region_index = 2; + break; + case MapRegion::HIGHLANDS: + region_index = 3; + break; + case MapRegion::ICELANDS: + region_index = 4; + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid region."); +// return {}; + } + + // cout << "input image feature: " << feature_to_str(image_feature) << endl; + + // FeatureType closest_dist = FLT_MAX; + // std::string closest_slug = ""; + + std::multimap result; + + for(const auto& slug : region_available_sprites[region_index]){ + auto it = sprite_map.find(slug); + if (it == sprite_map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Inconsistent sprite slug definitions in resource: " + slug); + } + + const FeatureVector& feature = it->second.feature; + const FeatureType dist = feature_distance(image_feature, feature); + result.emplace(dist, slug); + } + + // cout << "Closest feature distance " << closest_dist << ", slug " << closest_slug << endl; + // cout << feature_to_str(features.find(closest_slug)->second) << endl; + + return result; +} + + +ImageHSV32 compute_MMO_sprite_color_hsv(const ImageViewRGB32& image_rgb){ + // Convert the image to HSV during ImageHSV32 class construction + ImageHSV32 result = [&](){ + if (image_rgb.width() == EXTENDED_IMAGE_SIZE || image_rgb.height() == EXTENDED_IMAGE_SIZE){ + return ImageHSV32(image_rgb); + } + // First scale the image + return ImageHSV32(image_rgb.scale_to(EXTENDED_IMAGE_SIZE, EXTENDED_IMAGE_SIZE)); + }(); + + const size_t width = result.width(); + const size_t height = result.height(); + + // Set all the pixels outside the sprite area transparent to avoid matching the template to background colors. + double r = (width + height) / 4.0; + double center_x = (width-1) / 2.0f; + double center_y = (height-1) / 2.0f; + // -r/12 to remove some boundary areas + double dist2_th = (r - r/12) * (r - r/12); + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + if ((x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) >= dist2_th){ + // color outside of the sprite circle is set to zero transparency + result.pixel(x, y) = uint32_t(0); + } + // else if (x > center_x && y < center_y){ + // // Upper-right part of the sprite is set to zero transparency to avoid matching the + // // berry or star symbol + // result.pixel(x, y) = uint32_t(0); + // } + } + } + return result; +} + + +// For a sprite on the screenshot, create gradient image of it +ImageRGB32 compute_MMO_sprite_gradient(const ImageViewRGB32& image){ + + ImageRGB32 result = [&](){ + if (image.width() == IMAGE_TEMPLATE_SIZE || image.height() == IMAGE_TEMPLATE_SIZE){ + return smooth_image(image); + } + // First scale the image + return smooth_image(image.scale_to(IMAGE_TEMPLATE_SIZE, IMAGE_TEMPLATE_SIZE)); + }(); + result = compute_image_gradient(result); + + size_t width = image.width(); + size_t height = image.height(); + if (width == 0 || height == 0){ + return result; + } + + // Remove gradients outside of the image area + double r = (width + height) / 4.0; + double center_x = (width-1) / 2.0f; + double center_y = (height-1) / 2.0f; + // -r/8 to remove some boundary areas + double dist2_th = (r - r/8) * (r - r/8); + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + if ((x-center_x)*(x-center_x) + (y-center_y)*(y-center_y) >= dist2_th){ + // gradients outside of the sprite circle is set to zero + result.pixel(x, y) = combine_argb(0,0,0,0); + } + // else if (x > center_x && y < center_y){ + // // Upper-right part of the sprite is set to zero transparency to avoid matching the + // // berry or star symbol + // result.pixel(x, y) = uint32_t(0); + // } + } + } + return result; +} + + + + + + + + + + + +double compute_MMO_sprite_gradient_distance(const ImageViewRGB32& gradient_template, const ImageViewRGB32& gradient){ + int tempt_width = (int)gradient_template.width(); + int tempt_height = (int)gradient_template.height(); + + double score = 0.0f; + int max_offset = 2; + + auto compute_pixel_dist = [](uint32_t t_g, uint32_t g){ + int gx = uint32_t(0xff) & (g >> 16); + int gy = uint32_t(0xff) & (g >> 8); + int t_gx = uint32_t(0xff) & (t_g >> 16); + int t_gy = uint32_t(0xff) & (t_g >> 8); + double pixel_score = std::max(t_gx, gx) * (gx - t_gx) * (gx - t_gx) + std::max(t_gy, gy) * (gy - t_gy) * (gy - t_gy); + pixel_score /= 255; + return pixel_score; + }; + + +// #define USE_IMAGE_LEVEL_TRANSLATION +// #define USE_PIXEL_LEVEL_TRANSLATION +#define USE_BLOCK_LEVEL_TRANSLATION + +#ifdef USE_IMAGE_LEVEL_TRANSLATION + score = FLT_MAX; + for(int oy = -max_offset; oy <= max_offset; oy++){ // offset_y + for(int ox = -max_offset; ox <= max_offset; ox++){ // offset_x + + float match_score = 0.0; + int num_gradients = 0; + for(size_t y = 0; y < gradient.height(); y++){ + for(size_t x = 0; x < gradient.width(); x++){ + uint32_t g = gradient.pixel(x, y); + if (is_transparent(g)){ + continue; + } + int my = (int)(y + oy); // moved y + int mx = (int)(x + ox); // moved x + if (mx < 0 || mx >= tempt_width || my < 0 || my >= tempt_height){ + continue; + } + + uint32_t t_g = gradient_template.pixel(mx, my); + if (is_transparent(t_g)){ + continue; + } + + num_gradients++; + + float pixel_score = compute_pixel_dist(t_g, g); + match_score += pixel_score; + + // output.setPixelColor(x, y, QColor( + // std::min((int)std::sqrt(gx*gx+gy*gy),255), + // std::min((int)std::sqrt(t_gx*t_gx+t_gy*t_gy), 255), + // 0 + // )); + } + } + + match_score = std::sqrt(match_score / num_gradients); + if (match_score < score){ + score = match_score; + } + } + } + score = std::sqrt(score); +#endif + +#ifdef USE_PIXEL_LEVEL_TRANSLATION + score = 0; + int num_gradients = 0; + for(size_t y = 0; y < gradient.height(); y++){ + for(size_t x = 0; x < gradient.width(); x++){ + uint32_t g = gradient.pixel(x, y); + uint32_t gx = uint32_t(0xff) & (g >> 16); + uint32_t gy = uint32_t(0xff) & (g >> 8); + uint32_t alpha = g >> 24; + if (alpha < 128){ + continue; + } + + float min_pixel_score = FLT_MAX; + for(int oy = -max_offset; oy <= max_offset; oy++){ // offset_y + for(int ox = -max_offset; ox <= max_offset; ox++){ // offset_x + int my = (int)(y + oy); // moved y + int mx = (int)(x + ox); // moved x + if (mx < 0 || mx >= tempt_width || my < 0 || my >= tempt_height){ + continue; + } + // int dist_x = std::abs(ox); + // int dist_y = std::abs(oy); + // int dist2 = dist_x * dist_x + dist_y * dist_y; + uint32_t t_g = scaled_template.pixel(mx, my); + uint32_t t_a = t_g >> 24; + if (t_a < 128){ + continue; + } + + uint32_t t_gx = uint32_t(0xff) & (t_g >> 16); + uint32_t t_gy = uint32_t(0xff) & (t_g >> 8); + float pixel_score = std::max(t_gx, gx) * (gx - t_gx) * (gx - t_gx) + std::max(t_gy, gy) * (gy - t_gy) * (gy - t_gy); + pixel_score /= 255; + if (pixel_score < min_pixel_score){ + min_pixel_score = pixel_score; + } + + if (ox == 0 && oy == 0){ + output.setPixelColor(x, y, QColor( + std::min((int)std::sqrt(gx*gx+gy*gy),255), + std::min((int)std::sqrt(t_gx*t_gx+t_gy*t_gy), 255), + 0 + )); + } + } + } // end offset + + if (min_pixel_score < FLT_MAX){ + score += min_pixel_score; + num_gradients++; + } + } + } + score = std::sqrt(score / num_gradients); +#endif + +#ifdef USE_BLOCK_LEVEL_TRANSLATION + int block_radius = 5; + + score = 0; + int num_gradients = 0; + + for(int y = 0; y < (int)gradient.height(); y++){ + for(int x = 0; x < (int)gradient.width(); x++){ + uint32_t g = gradient.pixel(x, y); + if (is_transparent(g)){ + continue; + } + + double min_block_score = FLT_MAX; + for(int oy = -max_offset; oy <= max_offset; oy++){ // offset_y + for(int ox = -max_offset; ox <= max_offset; ox++){ // offset_x + + double block_score = 0.0; + int block_size = 0; + for(int by = y - block_radius; by <= y + block_radius; by++){ + for(int bx = x - block_radius; bx <= x + block_radius; bx++){ + if (bx < 0 || bx >= (int)gradient.width() || by < 0 || by >= (int)gradient.height()){ + continue; + } + + uint32_t bg = gradient.pixel(bx, by); + if (is_transparent(bg)){ + continue; + } + + int ty = by + oy; // template y + int tx = bx + ox; // template x + if (tx < 0 || tx >= tempt_width || ty < 0 || ty >= tempt_height){ + continue; + } + uint32_t t_bg = gradient_template.pixel(tx, ty); + if (is_transparent(t_bg)){ + continue; + } + + block_score += compute_pixel_dist(t_bg, bg); + block_size++; + } + } + block_score = block_score / block_size; + min_block_score = std::min(min_block_score, block_score); + } + } // end offset + + if (min_block_score < FLT_MAX){ + score += min_block_score; + num_gradients++; + } + } + } + score = std::sqrt(score / num_gradients); +#endif + + // output.save("test_distance_alignment_" + QString::number(count) + ".png"); + // count++; + + return score; +} + +double compute_hsv_dist2(uint32_t template_color, uint32_t color){ + int t_h = (uint32_t(0xff) & (template_color >> 16)); + int t_s = (uint32_t(0xff) & (template_color >> 8)); + int t_v = (uint32_t(0xff) & template_color); + + int h = (uint32_t(0xff) & (color >> 16)); + int s = (uint32_t(0xff) & (color >> 8)); + int v = (uint32_t(0xff) & color); + + int h_dif = std::abs(t_h - h); + if (h_dif > 255 - h_dif){ + h_dif = 256 - h_dif; + } + + return h_dif * h_dif + (t_s - s) * (t_s - s) + 0.5 * (t_v - v) * (t_v - v); +} + +double compute_MMO_sprite_hsv_distance(const ImageViewHSV32& image_template, const ImageViewHSV32& query_image){ + size_t tempt_width = image_template.width(); + size_t tempt_height = image_template.height(); + + // cout << tempt_width << " " << tempt_height << " " << query_image.width() << " " << query_image.height() << endl; + double score = 0.0; + int num_pixels = 0; + for (size_t y = 0; y < query_image.height(); y++){ + for (size_t x = 0; x < query_image.width(); x++){ + uint32_t p = query_image.pixel(x, y); + if (is_transparent(p)){ + // cout << "Skip query pixel " << x << " " << y << endl; + continue; + } + if (x >= tempt_width || y >= tempt_height){ + continue; + } + + uint32_t t_p = image_template.pixel(x, y); + if (is_transparent(t_p)){ + // cout << "Skip template pixel " << x << " " << y << endl; + continue; + } + + num_pixels++; + + double pixel_score = compute_hsv_dist2(t_p, p); + score += pixel_score; + } + } + + score = std::sqrt(score / num_pixels); + // cout << "score " << score << " " << num_pixels << endl; + // exit(0); + return score; +} + + +MapSpriteMatchResult match_sprite_on_map(Logger& logger, const ImageViewRGB32& screen, const ImagePixelBox& box, MapRegion region, bool debug_mode){ + const static auto& sprite_map = MMO_SPRITE_MATCHING_DATA(); + + auto save_debug_image_if_required = [&](const MapSpriteMatchResult& result){ + if (debug_mode == false){ + return; + } + const std::string debug_path = std::string("PokemonLA/PokemonMapSpriteReader/") + std::string(WILD_REGION_SHORT_NAMES[(int)region-2]) + + "/" + result.slug; + + dump_debug_image(logger, debug_path, result.slug, extract_box_reference(screen, box.expand_as(5))); + }; + + // configs for the algorithm: + const size_t num_feature_candidates = 10; + const double color_difference_threshold = 10.0; + const double gradient_confidence_threshold = 2.0; + const double color_to_gradient_confidence_scale = 2.0; + + MapSpriteMatchResult result; + logger.log("Start map MMO sprite matching:"); + + // This map has the match score for all sprites. + // This map must be not empty for subsequent computation. + const auto& feature_map = match_pokemon_map_sprite_feature(extract_box_reference(screen, box), region); + + for (const auto& p : feature_map){ + result.candidates.push_back(p.second); + if (result.candidates.size() >= num_feature_candidates){ + break; + } + } + + { + std::ostringstream os; + os << " Candidates: "; + for(size_t i = 0; i < result.candidates.size(); i++){ + if (i > 0){ + os << ", "; + } + os << result.candidates[i]; + } + logger.log(os.str()); + } + + // Should not happen if we correctly loads the sprite data. + if (result.candidates.size() == 0){ + return result; + } + + logger.log("Color matching..."); + { + const ImagePixelBox expanded_box = box.expand_as(2); + const ImageHSV32 sprite_hsv = compute_MMO_sprite_color_hsv(extract_box_reference(screen, expanded_box)); + + for(const auto& slug: result.candidates){ + const ImageHSV32& candidate_template = sprite_map.find(slug)->second.hsv_image; + double score = FLT_MAX; + for(size_t ox = 0; ox <= 4; ox++){ + for(size_t oy = 0; oy <= 4; oy++){ + ImagePixelBox shifted_box(ox, oy, box.width(), box.height()); + double match_score = compute_MMO_sprite_hsv_distance( + candidate_template, + extract_box_reference(sprite_hsv, shifted_box) + ); + score = std::min(match_score, score); + } + } + + result.color_match_results.emplace(score, slug); + } + } + + // Build a map from sprite to their color score and output scores for debugging + std::map color_match_sprite_scores; + int result_count = 0; + for(const auto& p : result.color_match_results){ + const auto& slug = p.second; + color_match_sprite_scores.emplace(slug, p.first); + if (result_count < 5){ + const auto& stats = sprite_map.find(slug)->second.rgb_stats; + std::ostringstream os; + os << p.first << " - " << slug << " " << stats.stddev.sum(); + logger.log(os.str()); + } + if (result_count == 5){ + size_t num_rest_results = result.color_match_results.size() - 5; + std::ostringstream os; + os << "Skip " << num_rest_results << " more result" << (num_rest_results > 1 ? "s" : ""); + logger.log(os.str()); + } + + result_count++; + } + + auto color_top = result.color_match_results.begin(); + const std::string& color_top_slug = color_top->second; + auto color_second = color_top; + color_second++; + + result.slug = color_top_slug; + result.color_score = color_top->first; + + if (color_second == result.color_match_results.end()){ + // we only have one color match result. + result.color_lead = DBL_MAX; + logger.log("Single color match result: " + color_top_slug); + save_debug_image_if_required(result); + return result; + } + + // We have some sprites which have closer scores to the top color match: + // Find the difference between the top and second match score + result.color_lead = color_second->first - result.color_score; + { + std::ostringstream os; + os << "Top color score: " << result.color_score << " diff to second: " << result.color_lead; + logger.log(os.str()); + } + + if (result.color_lead >= color_difference_threshold){ + logger.log("Color difference large enough. Good match: " + result.slug); + result.second_slug = color_second->second; + save_debug_image_if_required(result); + return result; + } + + logger.log("Gradient matching..."); + ImageRGB32 gradient_image = compute_MMO_sprite_gradient(extract_box_reference(screen, box)); + + // std::ostringstream os; + // os << "test_sprite_gradient" << count << "_" << std::setfill('0') << std::setw(2) << i << ".png"; + // std::string sprite_filename = os.str(); + // gradient_image.save(sprite_filename); + + for(const auto& p : result.color_match_results){ + const auto& slug = p.second; + ImageViewRGB32 template_gradient = sprite_map.find(slug)->second.gradient_image; + double score = compute_MMO_sprite_gradient_distance(template_gradient, gradient_image); + result.gradient_match_results.emplace(score, slug); + } + + result_count = 0; + for(const auto& p : result.gradient_match_results){ + if (result_count == 5){ + size_t num_rest_results = result.gradient_match_results.size() - 5; + std::ostringstream os; + os << "Skip " << num_rest_results << " more result" << (num_rest_results > 1 ? "s" : ""); + logger.log(os.str()); + break; + } + std::ostringstream os; + os << p.first << " - " << p.second; + logger.log(os.str()); + result_count++; + } + + // In case the gradient match is not confident, rely again on the color match: + auto gradient_top = result.gradient_match_results.begin(); + const auto& gradient_top_slug = gradient_top->second; + auto gradient_second = gradient_top; + gradient_second++; + const auto& gradient_second_slug = gradient_second->second; + + result.slug = gradient_top_slug; + result.gradient_score = gradient_top->first; + result.gradient_lead = gradient_second->first - gradient_top->first; + result.second_slug = gradient_second_slug; + + { + std::ostringstream os; + os << "Top gradient score: " << result.gradient_score << " diff to second: " << result.gradient_lead; + logger.log(os.str()); + } + + if (result.gradient_lead >= gradient_confidence_threshold){ + logger.log("Gradient difference large enough. Good match: " + result.slug); + save_debug_image_if_required(result); + return result; + } + + // The diff between top and second gradient match is close + // Let's check their color score: + result.graident_top_color_score = color_match_sprite_scores[gradient_top_slug]; + result.gradient_second_color_score = color_match_sprite_scores[gradient_second_slug]; + double color_diff = result.gradient_second_color_score - result.graident_top_color_score; + + { + std::ostringstream os; + os << "Gradient difference not large enough. Check color difference: " << + result.graident_top_color_score << " vs " << result.gradient_second_color_score << ", diff: " << + color_diff; + logger.log(os.str()); + } + + // If color score is more confident in telling those two sprites apart + if (std::fabs(color_diff) > result.gradient_lead * color_to_gradient_confidence_scale){ + if (color_diff < 0){ // second gradient sprite is better in color matching than the first graident sprite: + result.pick_gradient_second = true; + std::swap(result.slug, result.second_slug); + logger.log("Switch to more confident color result: " + result.slug); + } + }else{ + logger.log("Low confidence match: " + result.slug); + } + + save_debug_image_if_required(result); + return result; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h index bdabf85f01..c131edcdd8 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h @@ -1,62 +1,62 @@ -/* Pokemon Map Sprite Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_PokemonLA_PokemonMapSpriteReader_H -#define PokemonAutomation_PokemonLA_PokemonMapSpriteReader_H - -#include -#include -#include "CommonTools/ImageMatch/ExactImageDictionaryMatcher.h" -#include "PokemonLA/PokemonLA_Locations.h" - -struct ImagePixelBox; - -namespace PokemonAutomation{ - - -namespace NintendoSwitch{ -namespace PokemonLA{ - -struct MapSpriteMatchResult{ - std::string slug; - - std::vector candidates; - - std::multimap color_match_results; - - std::multimap gradient_match_results; - - double color_score = 0.0; - - double color_lead = 0.0; - - double gradient_score = 0.0; - - double gradient_lead = 0.0; - - double graident_top_color_score = 0.0; - - double gradient_second_color_score = 0.0; - - bool pick_gradient_second = false; - - std::string second_slug; -}; - -MapSpriteMatchResult match_sprite_on_map( - Logger& logger, - const ImageViewRGB32& screen, - const ImagePixelBox& box, - MapRegion region, - bool debug_mode = false -); - - -} -} -} -#endif +/* Pokemon Map Sprite Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_PokemonLA_PokemonMapSpriteReader_H +#define PokemonAutomation_PokemonLA_PokemonMapSpriteReader_H + +#include +#include +#include "CommonTools/ImageMatch/ExactImageDictionaryMatcher.h" +#include "PokemonLA/PokemonLA_Locations.h" + +struct ImagePixelBox; + +namespace PokemonAutomation{ + + +namespace NintendoSwitch{ +namespace PokemonLA{ + +struct MapSpriteMatchResult{ + std::string slug; + + std::vector candidates; + + std::multimap color_match_results; + + std::multimap gradient_match_results; + + double color_score = 0.0; + + double color_lead = 0.0; + + double gradient_score = 0.0; + + double gradient_lead = 0.0; + + double graident_top_color_score = 0.0; + + double gradient_second_color_score = 0.0; + + bool pick_gradient_second = false; + + std::string second_slug; +}; + +MapSpriteMatchResult match_sprite_on_map( + Logger& logger, + const ImageViewRGB32& screen, + const ImagePixelBox& box, + MapRegion region, + bool debug_mode = false +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp index bbccc429c4..0d2b4c88ee 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.cpp @@ -1,112 +1,112 @@ -/* Selected Region Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA_SelectedRegionDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class MapLocationDetector : public VisualInferenceCallback{ -public: - MapLocationDetector() - : VisualInferenceCallback("MapLocationDetector") - , m_current_region(MapRegion::NONE) - {} - - MapRegion current_region() const{ - return m_current_region; - } - - virtual void make_overlays(VideoOverlaySet& items) const override{ -// for (const RegionState& region : m_regions){ -// items.add(COLOR_CYAN, region.box); -// } - } - - virtual bool process_frame(const VideoSnapshot& frame) override{ - if (!frame){ - return false; - } - if (m_regions.empty()){ - reload_reference(frame.frame); - } - - for (RegionState& region : m_regions){ - ImageViewRGB32 current = extract_box_reference(frame, region.box); - - if (current.width() != (size_t)region.start.width() || current.height() != (size_t)region.start.height()){ - reload_reference(frame.frame); - return false; - } - - double rmsd = ImageMatch::pixel_RMSD(region.start, current); - if (rmsd > 20){ - m_current_region = region.region; - return true; - } - } - return false; - } - - void reload_reference(std::shared_ptr screen){ - m_screen = std::move(screen); - m_regions.clear(); - m_regions.emplace_back(MapRegion::JUBILIFE, ImageFloatBox(0.252, 0.400, 0.025, 0.150), *m_screen); - m_regions.emplace_back(MapRegion::FIELDLANDS, ImageFloatBox(0.415, 0.550, 0.025, 0.150), *m_screen); - m_regions.emplace_back(MapRegion::MIRELANDS, ImageFloatBox(0.750, 0.570, 0.025, 0.150), *m_screen); - m_regions.emplace_back(MapRegion::COASTLANDS, ImageFloatBox(0.865, 0.240, 0.025, 0.150), *m_screen); - m_regions.emplace_back(MapRegion::HIGHLANDS, ImageFloatBox(0.508, 0.320, 0.025, 0.150), *m_screen); - m_regions.emplace_back(MapRegion::ICELANDS, ImageFloatBox(0.457, 0.060, 0.025, 0.150), *m_screen); - m_regions.emplace_back(MapRegion::RETREAT, ImageFloatBox(0.635, 0.285, 0.025, 0.150), *m_screen); - } - -private: - struct RegionState{ - MapRegion region; - ImageFloatBox box; - ImageViewRGB32 start; - RegionState(MapRegion p_region, const ImageFloatBox& p_box, const ImageViewRGB32& screen) - : region(p_region) - , box(p_box) - , start(extract_box_reference(screen, box)) - {} - }; - - std::shared_ptr m_screen; - std::vector m_regions; - MapRegion m_current_region; -}; - - -MapRegion detect_selected_region(VideoStream& stream, CancellableScope& scope){ - MapLocationDetector detector; - int ret = wait_until( - stream, scope, - std::chrono::seconds(2), - {{detector}} - ); - MapRegion region = detector.current_region(); - if (ret < 0){ - stream.log("Unable to detect active region on map.", COLOR_RED); - }else{ - stream.log(std::string("Current Selection: ") + MAP_REGION_NAMES[(int)region]); - } - return region; -} - - - -} -} -} +/* Selected Region Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA_SelectedRegionDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class MapLocationDetector : public VisualInferenceCallback{ +public: + MapLocationDetector() + : VisualInferenceCallback("MapLocationDetector") + , m_current_region(MapRegion::NONE) + {} + + MapRegion current_region() const{ + return m_current_region; + } + + virtual void make_overlays(VideoOverlaySet& items) const override{ +// for (const RegionState& region : m_regions){ +// items.add(COLOR_CYAN, region.box); +// } + } + + virtual bool process_frame(const VideoSnapshot& frame) override{ + if (!frame){ + return false; + } + if (m_regions.empty()){ + reload_reference(frame.frame); + } + + for (RegionState& region : m_regions){ + ImageViewRGB32 current = extract_box_reference(frame, region.box); + + if (current.width() != (size_t)region.start.width() || current.height() != (size_t)region.start.height()){ + reload_reference(frame.frame); + return false; + } + + double rmsd = ImageMatch::pixel_RMSD(region.start, current); + if (rmsd > 20){ + m_current_region = region.region; + return true; + } + } + return false; + } + + void reload_reference(std::shared_ptr screen){ + m_screen = std::move(screen); + m_regions.clear(); + m_regions.emplace_back(MapRegion::JUBILIFE, ImageFloatBox(0.252, 0.400, 0.025, 0.150), *m_screen); + m_regions.emplace_back(MapRegion::FIELDLANDS, ImageFloatBox(0.415, 0.550, 0.025, 0.150), *m_screen); + m_regions.emplace_back(MapRegion::MIRELANDS, ImageFloatBox(0.750, 0.570, 0.025, 0.150), *m_screen); + m_regions.emplace_back(MapRegion::COASTLANDS, ImageFloatBox(0.865, 0.240, 0.025, 0.150), *m_screen); + m_regions.emplace_back(MapRegion::HIGHLANDS, ImageFloatBox(0.508, 0.320, 0.025, 0.150), *m_screen); + m_regions.emplace_back(MapRegion::ICELANDS, ImageFloatBox(0.457, 0.060, 0.025, 0.150), *m_screen); + m_regions.emplace_back(MapRegion::RETREAT, ImageFloatBox(0.635, 0.285, 0.025, 0.150), *m_screen); + } + +private: + struct RegionState{ + MapRegion region; + ImageFloatBox box; + ImageViewRGB32 start; + RegionState(MapRegion p_region, const ImageFloatBox& p_box, const ImageViewRGB32& screen) + : region(p_region) + , box(p_box) + , start(extract_box_reference(screen, box)) + {} + }; + + std::shared_ptr m_screen; + std::vector m_regions; + MapRegion m_current_region; +}; + + +MapRegion detect_selected_region(VideoStream& stream, CancellableScope& scope){ + MapLocationDetector detector; + int ret = wait_until( + stream, scope, + std::chrono::seconds(2), + {{detector}} + ); + MapRegion region = detector.current_region(); + if (ret < 0){ + stream.log("Unable to detect active region on map.", COLOR_RED); + }else{ + stream.log(std::string("Current Selection: ") + MAP_REGION_NAMES[(int)region]); + } + return region; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h index 11945293e2..fd4f595e83 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h @@ -1,29 +1,29 @@ -/* Selected Region Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#ifndef PokemonAutomation_PokemonLA_SelectedRegionDetector_H -#define PokemonAutomation_PokemonLA_SelectedRegionDetector_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "PokemonLA/PokemonLA_Locations.h" - -namespace PokemonAutomation{ - class CancellableScope; -namespace NintendoSwitch{ -namespace PokemonLA{ - -// On the map that you see when you leave village, detect which region the cursor is currently -// floats on. -// The function detects the region by checking which red region name sign is moving up and down. -MapRegion detect_selected_region(VideoStream& stream, CancellableScope& scope); - - - -} -} -} -#endif +/* Selected Region Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#ifndef PokemonAutomation_PokemonLA_SelectedRegionDetector_H +#define PokemonAutomation_PokemonLA_SelectedRegionDetector_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "PokemonLA/PokemonLA_Locations.h" + +namespace PokemonAutomation{ + class CancellableScope; +namespace NintendoSwitch{ +namespace PokemonLA{ + +// On the map that you see when you leave village, detect which region the cursor is currently +// floats on. +// The function detects the region by checking which red region name sign is moving up and down. +MapRegion detect_selected_region(VideoStream& stream, CancellableScope& scope); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.cpp index 57f32cf7d6..7d2fdcdb39 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.cpp @@ -1,129 +1,129 @@ -/* Arc Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "PokemonLA_ArcDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -class ArcMatcher : public ImageMatch::SubObjectTemplateMatcher{ -public: - ArcMatcher(bool left) - : SubObjectTemplateMatcher( - left - ? "PokemonLA/ArcL-Template0.png" - : "PokemonLA/ArcR-Template0.png", - 80 - ) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), - 128, 255, - 128, 255, - 128, 255 - ); - std::vector objects = find_objects_inplace(matrix, 20); - if (objects.size() != 1){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find exactly one object in resource.", - m_path - ); - } - set_subobject(objects[0]); - } - - static const ArcMatcher& left(){ - static ArcMatcher matcher(true); - return matcher; - } - static const ArcMatcher& right(){ - static ArcMatcher matcher(false); - return matcher; - } -}; - - - - -ArcDetector::ArcDetector() - : WhiteObjectDetector( - COLOR_GREEN, - { - Color(0xff808080), - Color(0xff909090), - Color(0xffa0a0a0), - Color(0xffb0b0b0), - } - ) -{} -void ArcDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ - ImagePixelBox object_box; - if (ArcMatcher::left().matches(object_box, image, object)){ - m_left.emplace_back(object_box); - } - if (ArcMatcher::right().matches(object_box, image, object)){ - m_right.emplace_back(object_box); - } -} -void ArcDetector::finish(const ImageViewRGB32& image){ - // Merge left/right arcs. - for (auto iter0 = m_left.begin(); iter0 != m_left.end();){ - double height = (double)iter0->height(); - bool removed = false; - for (auto iter1 = m_right.begin(); iter1 != m_right.end(); ++iter1){ - double height_ratio = height / iter1->height(); - if (height_ratio < 0.9 || height_ratio > 1.1){ - continue; - } - - double vertical_offset = ((ptrdiff_t)iter0->min_y - (ptrdiff_t)iter1->min_y) / height; - if (std::abs(vertical_offset) > 0.1){ - continue; - } - - double horizontal_offset = ((ptrdiff_t)iter1->min_x - (ptrdiff_t)iter0->min_x) / height - 1.27; - if (horizontal_offset < -0.1 || horizontal_offset > 0.8){ - continue; - } - - m_detections.emplace_back( - iter0->min_x, - std::min(iter0->min_y, iter1->min_y), - iter1->max_x, - std::max(iter0->max_y, iter1->max_y) - ); - iter0 = m_left.erase(iter0); - m_right.erase(iter1); - removed = true; - break; - } - if (!removed){ - ++iter0; - } - } - m_left.clear(); - m_right.clear(); - merge_heavily_overlapping(); -} - - - - - - -} -} -} +/* Arc Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "PokemonLA_ArcDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +class ArcMatcher : public ImageMatch::SubObjectTemplateMatcher{ +public: + ArcMatcher(bool left) + : SubObjectTemplateMatcher( + left + ? "PokemonLA/ArcL-Template0.png" + : "PokemonLA/ArcR-Template0.png", + 80 + ) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), + 128, 255, + 128, 255, + 128, 255 + ); + std::vector objects = find_objects_inplace(matrix, 20); + if (objects.size() != 1){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find exactly one object in resource.", + m_path + ); + } + set_subobject(objects[0]); + } + + static const ArcMatcher& left(){ + static ArcMatcher matcher(true); + return matcher; + } + static const ArcMatcher& right(){ + static ArcMatcher matcher(false); + return matcher; + } +}; + + + + +ArcDetector::ArcDetector() + : WhiteObjectDetector( + COLOR_GREEN, + { + Color(0xff808080), + Color(0xff909090), + Color(0xffa0a0a0), + Color(0xffb0b0b0), + } + ) +{} +void ArcDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ + ImagePixelBox object_box; + if (ArcMatcher::left().matches(object_box, image, object)){ + m_left.emplace_back(object_box); + } + if (ArcMatcher::right().matches(object_box, image, object)){ + m_right.emplace_back(object_box); + } +} +void ArcDetector::finish(const ImageViewRGB32& image){ + // Merge left/right arcs. + for (auto iter0 = m_left.begin(); iter0 != m_left.end();){ + double height = (double)iter0->height(); + bool removed = false; + for (auto iter1 = m_right.begin(); iter1 != m_right.end(); ++iter1){ + double height_ratio = height / iter1->height(); + if (height_ratio < 0.9 || height_ratio > 1.1){ + continue; + } + + double vertical_offset = ((ptrdiff_t)iter0->min_y - (ptrdiff_t)iter1->min_y) / height; + if (std::abs(vertical_offset) > 0.1){ + continue; + } + + double horizontal_offset = ((ptrdiff_t)iter1->min_x - (ptrdiff_t)iter0->min_x) / height - 1.27; + if (horizontal_offset < -0.1 || horizontal_offset > 0.8){ + continue; + } + + m_detections.emplace_back( + iter0->min_x, + std::min(iter0->min_y, iter1->min_y), + iter1->max_x, + std::max(iter0->max_y, iter1->max_y) + ); + iter0 = m_left.erase(iter0); + m_right.erase(iter1); + removed = true; + break; + } + if (!removed){ + ++iter0; + } + } + m_left.clear(); + m_right.clear(); + merge_heavily_overlapping(); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h index b38b66a07b..f6c9e2bbfd 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h @@ -1,34 +1,34 @@ -/* Arc Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ArcDetector_H -#define PokemonAutomation_PokemonLA_ArcDetector_H - -#include -#include "PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ArcDetector : public WhiteObjectDetector{ -public: - ArcDetector(); - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; - -private: - std::list m_left; - std::list m_right; -}; - - - -} -} -} -#endif +/* Arc Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ArcDetector_H +#define PokemonAutomation_PokemonLA_ArcDetector_H + +#include +#include "PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ArcDetector : public WhiteObjectDetector{ +public: + ArcDetector(); + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; + +private: + std::list m_left; + std::list m_right; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.cpp index 963c0c42ae..831c556f61 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.cpp @@ -1,145 +1,145 @@ -/* Arc Phone Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "PokemonLA_ArcPhoneDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -ArcPhoneMatcher::ArcPhoneMatcher() - : WaterfillTemplateMatcher( - "PokemonLA/ArcPhone-Template.png", - Color(0xff808008), Color(0xffffffff), 100 - ) -{} -const ArcPhoneMatcher& ArcPhoneMatcher::instance(){ - static ArcPhoneMatcher matcher; - return matcher; -} - - -ArcPhoneTracker::ArcPhoneTracker() - : WhiteObjectDetector( - COLOR_CYAN, - { - Color(0xff808080), - Color(0xff909090), - Color(0xffa0a0a0), - Color(0xffb0b0b0), - Color(0xffc0c0c0), - Color(0xffd0d0d0), - Color(0xffe0e0e0), - Color(0xfff0f0f0), - } - ) -{} - -void ArcPhoneTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ -// cout << "asdf" << endl; -// static int c = 0; -// cout << "c = " << c << endl; -// extract_box_reference(image, object).save("testA-" + std::to_string(c++) + ".png"); -// image.save("test-" + std::to_string(c++) + "-A.png"); -// extract_box_reference(image, object).save("testB-" + std::to_string(c++) + ".png"); - - double width = (double)object.width() / image.width(); - if (width < 0.40 || width > 0.50){ - return; - } - -// cout << (double)object.width() / image.width() << endl; - - double rmsd = ArcPhoneMatcher::instance().rmsd_original(image, object); -// cout << "rmsd = " << rmsd << endl; - if (rmsd < 80){ -// cout << "rmsd = " << rmsd << endl; -// extract_box(image, object).save("test.png"); - m_detections.emplace_back(object); - } -} -void ArcPhoneTracker::finish(const ImageViewRGB32& image){ -// static int count = 0; -// image.save("test0-" + std::to_string(count++) + ".png"); - merge_heavily_overlapping(); -} - - - -ArcPhoneDetector::ArcPhoneDetector( - Logger& logger, VideoOverlay& overlay, - std::chrono::milliseconds min_streak, - bool stop_on_detected -) - : VisualInferenceCallback("CenterAButtonDetector") - , m_logger(logger) - , m_box(0.010, 0.700, 0.050, 0.100) - , m_stop_on_detected(stop_on_detected) - , m_tracker_button(ButtonType::ButtonMinus) - , m_watcher( - overlay, m_box, { - {m_tracker_phone, false}, - {m_tracker_button, false}, - } - ) - , m_debouncer_phone( - false, min_streak, - [&](bool value){ - if (value){ - m_logger.log("Detected Arc Phone.", COLOR_PURPLE); - }else{ - m_logger.log("Arc Phone has disappeared.", COLOR_PURPLE); - } - } - ) - , m_debouncer_button( - false, min_streak, - [&](bool value){ - if (value){ - m_logger.log("Detected (-) Button.", COLOR_PURPLE); - }else{ - m_logger.log("(-) button has disappeared.", COLOR_PURPLE); - } - } - ) -{} - - -void ArcPhoneDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool ArcPhoneDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_watcher.process_frame(frame, timestamp); -// cout << "White Objects = " << m_tracker_phone.detections().size() << endl; - bool detected0 = m_debouncer_phone.push_value(!m_tracker_phone.detections().empty(), timestamp); - bool detected1 = m_debouncer_button.push_value(!m_tracker_phone.detections().empty(), timestamp); - -// cout << detected0 << ", " << detected1 << endl; - -#if 0 - if (detected){ - static size_t c = 0; - frame.save("ArcPhoneTriggered-" + std::to_string(c++) + ".png"); - } -#endif - - return detected0 && detected1 && m_stop_on_detected; -} - - - - - -} -} -} +/* Arc Phone Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "PokemonLA_ArcPhoneDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +ArcPhoneMatcher::ArcPhoneMatcher() + : WaterfillTemplateMatcher( + "PokemonLA/ArcPhone-Template.png", + Color(0xff808008), Color(0xffffffff), 100 + ) +{} +const ArcPhoneMatcher& ArcPhoneMatcher::instance(){ + static ArcPhoneMatcher matcher; + return matcher; +} + + +ArcPhoneTracker::ArcPhoneTracker() + : WhiteObjectDetector( + COLOR_CYAN, + { + Color(0xff808080), + Color(0xff909090), + Color(0xffa0a0a0), + Color(0xffb0b0b0), + Color(0xffc0c0c0), + Color(0xffd0d0d0), + Color(0xffe0e0e0), + Color(0xfff0f0f0), + } + ) +{} + +void ArcPhoneTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ +// cout << "asdf" << endl; +// static int c = 0; +// cout << "c = " << c << endl; +// extract_box_reference(image, object).save("testA-" + std::to_string(c++) + ".png"); +// image.save("test-" + std::to_string(c++) + "-A.png"); +// extract_box_reference(image, object).save("testB-" + std::to_string(c++) + ".png"); + + double width = (double)object.width() / image.width(); + if (width < 0.40 || width > 0.50){ + return; + } + +// cout << (double)object.width() / image.width() << endl; + + double rmsd = ArcPhoneMatcher::instance().rmsd_original(image, object); +// cout << "rmsd = " << rmsd << endl; + if (rmsd < 80){ +// cout << "rmsd = " << rmsd << endl; +// extract_box(image, object).save("test.png"); + m_detections.emplace_back(object); + } +} +void ArcPhoneTracker::finish(const ImageViewRGB32& image){ +// static int count = 0; +// image.save("test0-" + std::to_string(count++) + ".png"); + merge_heavily_overlapping(); +} + + + +ArcPhoneDetector::ArcPhoneDetector( + Logger& logger, VideoOverlay& overlay, + std::chrono::milliseconds min_streak, + bool stop_on_detected +) + : VisualInferenceCallback("CenterAButtonDetector") + , m_logger(logger) + , m_box(0.010, 0.700, 0.050, 0.100) + , m_stop_on_detected(stop_on_detected) + , m_tracker_button(ButtonType::ButtonMinus) + , m_watcher( + overlay, m_box, { + {m_tracker_phone, false}, + {m_tracker_button, false}, + } + ) + , m_debouncer_phone( + false, min_streak, + [&](bool value){ + if (value){ + m_logger.log("Detected Arc Phone.", COLOR_PURPLE); + }else{ + m_logger.log("Arc Phone has disappeared.", COLOR_PURPLE); + } + } + ) + , m_debouncer_button( + false, min_streak, + [&](bool value){ + if (value){ + m_logger.log("Detected (-) Button.", COLOR_PURPLE); + }else{ + m_logger.log("(-) button has disappeared.", COLOR_PURPLE); + } + } + ) +{} + + +void ArcPhoneDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool ArcPhoneDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_watcher.process_frame(frame, timestamp); +// cout << "White Objects = " << m_tracker_phone.detections().size() << endl; + bool detected0 = m_debouncer_phone.push_value(!m_tracker_phone.detections().empty(), timestamp); + bool detected1 = m_debouncer_button.push_value(!m_tracker_phone.detections().empty(), timestamp); + +// cout << detected0 << ", " << detected1 << endl; + +#if 0 + if (detected){ + static size_t c = 0; + frame.save("ArcPhoneTriggered-" + std::to_string(c++) + ".png"); + } +#endif + + return detected0 && detected1 && m_stop_on_detected; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h index e46c714033..f36feb1520 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h @@ -1,75 +1,75 @@ -/* Arc Phone Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ArcPhoneDetector_H -#define PokemonAutomation_PokemonLA_ArcPhoneDetector_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/DetectionDebouncer.h" -#include "PokemonLA_WhiteObjectDetector.h" -#include "PokemonLA_ButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ArcPhoneMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - ArcPhoneMatcher(); - static const ArcPhoneMatcher& instance(); -}; - - - -class ArcPhoneTracker : public WhiteObjectDetector{ -public: - ArcPhoneTracker(); - - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; -}; - - - -class ArcPhoneDetector : public VisualInferenceCallback{ -public: - ArcPhoneDetector( - Logger& logger, VideoOverlay& overlay, - std::chrono::milliseconds min_streak, - bool stop_on_detected - ); - - bool detected() const{ - return m_debouncer_phone.get() && m_debouncer_button.get(); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - ImageFloatBox m_box; - bool m_stop_on_detected; - - SpinLock m_lock; - ArcPhoneTracker m_tracker_phone; - ButtonTracker m_tracker_button; - WhiteObjectWatcher m_watcher; - - DetectionDebouncer m_debouncer_phone; - DetectionDebouncer m_debouncer_button; -}; - - - -} -} -} -#endif +/* Arc Phone Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ArcPhoneDetector_H +#define PokemonAutomation_PokemonLA_ArcPhoneDetector_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/DetectionDebouncer.h" +#include "PokemonLA_WhiteObjectDetector.h" +#include "PokemonLA_ButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ArcPhoneMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + ArcPhoneMatcher(); + static const ArcPhoneMatcher& instance(); +}; + + + +class ArcPhoneTracker : public WhiteObjectDetector{ +public: + ArcPhoneTracker(); + + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; +}; + + + +class ArcPhoneDetector : public VisualInferenceCallback{ +public: + ArcPhoneDetector( + Logger& logger, VideoOverlay& overlay, + std::chrono::milliseconds min_streak, + bool stop_on_detected + ); + + bool detected() const{ + return m_debouncer_phone.get() && m_debouncer_button.get(); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + ImageFloatBox m_box; + bool m_stop_on_detected; + + SpinLock m_lock; + ArcPhoneTracker m_tracker_phone; + ButtonTracker m_tracker_button; + WhiteObjectWatcher m_watcher; + + DetectionDebouncer m_debouncer_phone; + DetectionDebouncer m_debouncer_button; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.cpp index e779bdf70f..83d413d909 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.cpp @@ -1,97 +1,97 @@ -/* Battle Sprite Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "PokemonLA_BattleSpriteArrowDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -BattleSpriteArrowMatcher::BattleSpriteArrowMatcher() - : WaterfillTemplateMatcher( - "PokemonLA/BattleSpriteArrow-Template.png", - Color(0xff808008), Color(0xffffffff), 100 - ) -{ - m_aspect_ratio_lower = 0.95; - m_aspect_ratio_upper = 1.05; - m_area_ratio_lower = 0.95; - m_area_ratio_upper = 1.05; -} - -const BattleSpriteArrowMatcher& BattleSpriteArrowMatcher::instance(){ - static BattleSpriteArrowMatcher matcher; - return matcher; -} - - -BattleSpriteArrowTracker::BattleSpriteArrowTracker() - : WhiteObjectDetector( - COLOR_CYAN, - { - Color(0xff808080), - Color(0xff909090), - Color(0xffa0a0a0), - Color(0xffb0b0b0), - } - ) -{} - -void BattleSpriteArrowTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ - double rmsd = BattleSpriteArrowMatcher::instance().rmsd_original(image, object); - if (rmsd < 80){ - m_detections.emplace_back(object); - } -} - -void BattleSpriteArrowTracker::finish(const ImageViewRGB32& image){ - merge_heavily_overlapping(); -} - - - -BattleSpriteArrowDetector::BattleSpriteArrowDetector( - Logger& logger, VideoOverlay& overlay, - size_t sprite_index, - std::chrono::milliseconds min_streak, - bool stop_on_detected -) - : VisualInferenceCallback("BattleSpriteArrowButtonDetector") - , m_logger(logger) - , m_box(0.936 - 0.035*sprite_index, 0.018, 0.015, 0.027) - , m_stop_on_detected(stop_on_detected) - , m_watcher(overlay, m_box, { {m_tracker, false} }) - , m_debouncer( - false, min_streak, - [&](bool value){ - if (value){ - m_logger.log("Detected sprite arrow.", COLOR_PURPLE); - }else{ - m_logger.log("Sprite arrow disappeared.", COLOR_PURPLE); - } - } - ) -{} - - -void BattleSpriteArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool BattleSpriteArrowDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_watcher.process_frame(frame, timestamp); - bool detected = m_debouncer.push_value(!m_tracker.detections().empty(), timestamp); - return detected && m_stop_on_detected; -} - - - - - -} -} -} +/* Battle Sprite Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "PokemonLA_BattleSpriteArrowDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +BattleSpriteArrowMatcher::BattleSpriteArrowMatcher() + : WaterfillTemplateMatcher( + "PokemonLA/BattleSpriteArrow-Template.png", + Color(0xff808008), Color(0xffffffff), 100 + ) +{ + m_aspect_ratio_lower = 0.95; + m_aspect_ratio_upper = 1.05; + m_area_ratio_lower = 0.95; + m_area_ratio_upper = 1.05; +} + +const BattleSpriteArrowMatcher& BattleSpriteArrowMatcher::instance(){ + static BattleSpriteArrowMatcher matcher; + return matcher; +} + + +BattleSpriteArrowTracker::BattleSpriteArrowTracker() + : WhiteObjectDetector( + COLOR_CYAN, + { + Color(0xff808080), + Color(0xff909090), + Color(0xffa0a0a0), + Color(0xffb0b0b0), + } + ) +{} + +void BattleSpriteArrowTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ + double rmsd = BattleSpriteArrowMatcher::instance().rmsd_original(image, object); + if (rmsd < 80){ + m_detections.emplace_back(object); + } +} + +void BattleSpriteArrowTracker::finish(const ImageViewRGB32& image){ + merge_heavily_overlapping(); +} + + + +BattleSpriteArrowDetector::BattleSpriteArrowDetector( + Logger& logger, VideoOverlay& overlay, + size_t sprite_index, + std::chrono::milliseconds min_streak, + bool stop_on_detected +) + : VisualInferenceCallback("BattleSpriteArrowButtonDetector") + , m_logger(logger) + , m_box(0.936 - 0.035*sprite_index, 0.018, 0.015, 0.027) + , m_stop_on_detected(stop_on_detected) + , m_watcher(overlay, m_box, { {m_tracker, false} }) + , m_debouncer( + false, min_streak, + [&](bool value){ + if (value){ + m_logger.log("Detected sprite arrow.", COLOR_PURPLE); + }else{ + m_logger.log("Sprite arrow disappeared.", COLOR_PURPLE); + } + } + ) +{} + + +void BattleSpriteArrowDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool BattleSpriteArrowDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_watcher.process_frame(frame, timestamp); + bool detected = m_debouncer.push_value(!m_tracker.detections().empty(), timestamp); + return detected && m_stop_on_detected; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h index 1512bfce42..0f41e3b00a 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h @@ -1,76 +1,76 @@ -/* Battle Sprite Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the white arrow pointing towards left on the selected sprite, in the upper right corner - * of the screen, during a multi-pokemon battle. - */ - -#ifndef PokemonAutomation_PokemonLA_BattleSpriteArrowDetector_H -#define PokemonAutomation_PokemonLA_BattleSpriteArrowDetector_H - -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/DetectionDebouncer.h" -#include "PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class BattleSpriteArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - BattleSpriteArrowMatcher(); - static const BattleSpriteArrowMatcher& instance(); -}; - - - -class BattleSpriteArrowTracker : public WhiteObjectDetector{ -public: - BattleSpriteArrowTracker(); - - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; -}; - - - -class BattleSpriteArrowDetector : public VisualInferenceCallback{ -public: - // Sprite index: the index of the sprite the current selected arrow is on top of. - // The index is ordered from right to left on the screen. - BattleSpriteArrowDetector( - Logger& logger, VideoOverlay& overlay, - size_t sprite_index, - std::chrono::milliseconds min_streak, - bool stop_on_detected - ); - - bool detected() const{ - return m_debouncer.get(); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - ImageFloatBox m_box; - bool m_stop_on_detected; - - BattleSpriteArrowTracker m_tracker; - WhiteObjectWatcher m_watcher; - - DetectionDebouncer m_debouncer; -}; - - - -} -} -} -#endif +/* Battle Sprite Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the white arrow pointing towards left on the selected sprite, in the upper right corner + * of the screen, during a multi-pokemon battle. + */ + +#ifndef PokemonAutomation_PokemonLA_BattleSpriteArrowDetector_H +#define PokemonAutomation_PokemonLA_BattleSpriteArrowDetector_H + +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/DetectionDebouncer.h" +#include "PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class BattleSpriteArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + BattleSpriteArrowMatcher(); + static const BattleSpriteArrowMatcher& instance(); +}; + + + +class BattleSpriteArrowTracker : public WhiteObjectDetector{ +public: + BattleSpriteArrowTracker(); + + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; +}; + + + +class BattleSpriteArrowDetector : public VisualInferenceCallback{ +public: + // Sprite index: the index of the sprite the current selected arrow is on top of. + // The index is ordered from right to left on the screen. + BattleSpriteArrowDetector( + Logger& logger, VideoOverlay& overlay, + size_t sprite_index, + std::chrono::milliseconds min_streak, + bool stop_on_detected + ); + + bool detected() const{ + return m_debouncer.get(); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + ImageFloatBox m_box; + bool m_stop_on_detected; + + BattleSpriteArrowTracker m_tracker; + WhiteObjectWatcher m_watcher; + + DetectionDebouncer m_debouncer; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.cpp index e19c7661b5..50cd2b735e 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.cpp @@ -1,82 +1,82 @@ -/* Bubble Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "PokemonLA_BubbleDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -class BubbleMatcher : public ImageMatch::SubObjectTemplateMatcher{ -public: - BubbleMatcher() - : SubObjectTemplateMatcher("PokemonLA/Bubble-Template0.png", 40) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), - 128, 255, - 128, 255, - 128, 255 - ); - std::vector objects = find_objects_inplace(matrix, 20); - if (objects.size() != 1){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find exactly one object in resource.", - m_path - ); - } - set_subobject(objects[0]); - } - - virtual bool check_image(const ImageViewRGB32& image) const override{ - return image_stddev(image).sum() > 100; - }; - - static const BubbleMatcher& instance(){ - static BubbleMatcher matcher; - return matcher; - } -}; - - - -BubbleDetector::BubbleDetector() - : WhiteObjectDetector(COLOR_GREEN, {Color(0xffb0b0b0)}) -{} -void BubbleDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ - if (object.area < 200){ - return; - } - if (object.width() < 0.03 * image.width()){ - return; - } - if (object.width() > 0.06 * image.width()){ - return; - } - ImagePixelBox object_box; - if (BubbleMatcher::instance().matches(object_box, image, object)){ - m_detections.emplace_back(object_box); - } -} -void BubbleDetector::finish(const ImageViewRGB32& image){ - merge_heavily_overlapping(); -} - - - -} -} -} +/* Bubble Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "PokemonLA_BubbleDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +class BubbleMatcher : public ImageMatch::SubObjectTemplateMatcher{ +public: + BubbleMatcher() + : SubObjectTemplateMatcher("PokemonLA/Bubble-Template0.png", 40) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), + 128, 255, + 128, 255, + 128, 255 + ); + std::vector objects = find_objects_inplace(matrix, 20); + if (objects.size() != 1){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find exactly one object in resource.", + m_path + ); + } + set_subobject(objects[0]); + } + + virtual bool check_image(const ImageViewRGB32& image) const override{ + return image_stddev(image).sum() > 100; + }; + + static const BubbleMatcher& instance(){ + static BubbleMatcher matcher; + return matcher; + } +}; + + + +BubbleDetector::BubbleDetector() + : WhiteObjectDetector(COLOR_GREEN, {Color(0xffb0b0b0)}) +{} +void BubbleDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ + if (object.area < 200){ + return; + } + if (object.width() < 0.03 * image.width()){ + return; + } + if (object.width() > 0.06 * image.width()){ + return; + } + ImagePixelBox object_box; + if (BubbleMatcher::instance().matches(object_box, image, object)){ + m_detections.emplace_back(object_box); + } +} +void BubbleDetector::finish(const ImageViewRGB32& image){ + merge_heavily_overlapping(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h index 6f0d3d41fa..6d63fb1759 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h @@ -1,30 +1,30 @@ -/* Bubble Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_BubbleDetector_H -#define PokemonAutomation_PokemonLA_BubbleDetector_H - -#include -#include "PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class BubbleDetector : public WhiteObjectDetector{ -public: - BubbleDetector(); - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; -}; - - - -} -} -} -#endif +/* Bubble Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_BubbleDetector_H +#define PokemonAutomation_PokemonLA_BubbleDetector_H + +#include +#include "PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class BubbleDetector : public WhiteObjectDetector{ +public: + BubbleDetector(); + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.cpp index 632d2b2bf7..efb24c2125 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.cpp @@ -1,191 +1,191 @@ -/* Button Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "PokemonLA_ButtonDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -namespace{ - -const char* templatePath(ButtonType type){ - switch (type){ - case ButtonType::ButtonA: - return "PokemonLA/Buttons/ButtonA-Template.png"; - case ButtonType::ButtonB: - return "PokemonLA/Buttons/ButtonB-Template.png"; - case ButtonType::ButtonPlus: - return "PokemonLA/Buttons/ButtonPlus-Template.png"; - case ButtonType::ButtonMinus: - return "PokemonLA/Buttons/ButtonMinus-Template.png"; - case ButtonType::ArrowLeft: - return "PokemonLA/Buttons/ArrowLeft-Template.png"; - case ButtonType::ArrowRight: - return "PokemonLA/Buttons/ArrowRight-Template.png"; - default: - return ""; - } -} - -const char* button_name(ButtonType type){ - switch (type){ - case ButtonType::ButtonA: - return "A"; - case ButtonType::ButtonB: - return "B"; - case ButtonType::ButtonPlus: - return "+"; - case ButtonType::ButtonMinus: - return "-"; - case ButtonType::ArrowLeft: - return "<"; - case ButtonType::ArrowRight: - return ">"; - default: - return ""; - } -} - -const ButtonMatcher& getButtonMatcher(ButtonType type){ - switch (type){ - case ButtonType::ButtonA: - return ButtonMatcher::A(); - case ButtonType::ButtonB: - return ButtonMatcher::B(); - case ButtonType::ButtonPlus: - return ButtonMatcher::Plus(); - case ButtonType::ButtonMinus: - return ButtonMatcher::Minus(); - case ButtonType::ArrowLeft: - return ButtonMatcher::ArrowLeft(); - case ButtonType::ArrowRight: - return ButtonMatcher::ArrowRight(); - default: - throw std::runtime_error("No corresponding ButtonMatcher for ButtonType"); - } -} - -} - -ButtonMatcher::ButtonMatcher(ButtonType type, size_t min_width, size_t max_width, double max_rmsd) - : WaterfillTemplateMatcher( - templatePath(type), Color(0xff808008), Color(0xffffffff), 100 - ) - , m_min_width(min_width) - , m_min_height(max_width) - , m_max_rmsd(max_rmsd) -{} -const ButtonMatcher& ButtonMatcher::A(){ - static ButtonMatcher matcher(ButtonType::ButtonA, 15, 15, 90); - return matcher; -} -const ButtonMatcher& ButtonMatcher::B(){ - static ButtonMatcher matcher(ButtonType::ButtonB, 15, 15, 90); - return matcher; -} -const ButtonMatcher& ButtonMatcher::Plus(){ - static ButtonMatcher matcher(ButtonType::ButtonPlus, 15, 15, 120); - return matcher; -} -const ButtonMatcher& ButtonMatcher::Minus(){ - static ButtonMatcher matcher(ButtonType::ButtonMinus, 15, 15, 120); - return matcher; -} -const ButtonMatcher& ButtonMatcher::ArrowLeft(){ - static ButtonMatcher matcher(ButtonType::ArrowLeft, 5, 10, 180); - return matcher; -} -const ButtonMatcher& ButtonMatcher::ArrowRight(){ - static ButtonMatcher matcher(ButtonType::ArrowRight, 5, 10, 180); - return matcher; -} - - - - - -ButtonTracker::ButtonTracker(ButtonType type) - : WhiteObjectDetector( - COLOR_CYAN, - { - Color(0xff808080), - Color(0xff909090), - Color(0xffa0a0a0), - Color(0xffb0b0b0), - Color(0xffc0c0c0), - Color(0xffd0d0d0), - } - ) - , m_matcher(getButtonMatcher(type)) -{} - -void ButtonTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ -// cout << "asdf" << endl; -// static int c = 0; -// extract_box(image, object).save("test-" + std::to_string(c++) + ".png"); -// image.save("test-" + std::to_string(c++) + "-A.png"); -// extract_box(image, object).save("test-" + std::to_string(c++) + "-B.png"); - - double rmsd = m_matcher.rmsd_precropped(extract_box_reference(image, object), object); -// cout << "rmsd = " << rmsd << endl; -// cout << "max = " << m_matcher.m_max_rmsd << endl; - if (rmsd < m_matcher.m_max_rmsd){ -// cout << "matching rmsd = " << rmsd << endl; - m_detections.emplace_back(object); - } -} -void ButtonTracker::finish(const ImageViewRGB32& image){ - merge_heavily_overlapping(); -} - - - -ButtonDetector::ButtonDetector( - Logger& logger, VideoOverlay& overlay, - ButtonType type, - const ImageFloatBox& box, - std::chrono::milliseconds min_streak, - bool stop_on_detected -) - : VisualInferenceCallback("CenterAButtonDetector") - , m_logger(logger) - , m_box(box) - , m_stop_on_detected(stop_on_detected) - , m_tracker(type) - , m_watcher(overlay, m_box, { {m_tracker, false} }) - , m_debouncer( - false, min_streak, - [this, type](bool value){ - if (value){ - m_logger.log(std::string("Detected (") + button_name(type) + ") Button.", COLOR_PURPLE); - }else{ - m_logger.log(std::string("(") + button_name(type) + ") Button has disappeared.", COLOR_PURPLE); - } - } - ) -{} - -void ButtonDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool ButtonDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_watcher.process_frame(frame, timestamp); - bool detected = m_debouncer.push_value(!m_tracker.detections().empty(), timestamp); - return detected && m_stop_on_detected; -} - - - - -} -} -} +/* Button Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "PokemonLA_ButtonDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +namespace{ + +const char* templatePath(ButtonType type){ + switch (type){ + case ButtonType::ButtonA: + return "PokemonLA/Buttons/ButtonA-Template.png"; + case ButtonType::ButtonB: + return "PokemonLA/Buttons/ButtonB-Template.png"; + case ButtonType::ButtonPlus: + return "PokemonLA/Buttons/ButtonPlus-Template.png"; + case ButtonType::ButtonMinus: + return "PokemonLA/Buttons/ButtonMinus-Template.png"; + case ButtonType::ArrowLeft: + return "PokemonLA/Buttons/ArrowLeft-Template.png"; + case ButtonType::ArrowRight: + return "PokemonLA/Buttons/ArrowRight-Template.png"; + default: + return ""; + } +} + +const char* button_name(ButtonType type){ + switch (type){ + case ButtonType::ButtonA: + return "A"; + case ButtonType::ButtonB: + return "B"; + case ButtonType::ButtonPlus: + return "+"; + case ButtonType::ButtonMinus: + return "-"; + case ButtonType::ArrowLeft: + return "<"; + case ButtonType::ArrowRight: + return ">"; + default: + return ""; + } +} + +const ButtonMatcher& getButtonMatcher(ButtonType type){ + switch (type){ + case ButtonType::ButtonA: + return ButtonMatcher::A(); + case ButtonType::ButtonB: + return ButtonMatcher::B(); + case ButtonType::ButtonPlus: + return ButtonMatcher::Plus(); + case ButtonType::ButtonMinus: + return ButtonMatcher::Minus(); + case ButtonType::ArrowLeft: + return ButtonMatcher::ArrowLeft(); + case ButtonType::ArrowRight: + return ButtonMatcher::ArrowRight(); + default: + throw std::runtime_error("No corresponding ButtonMatcher for ButtonType"); + } +} + +} + +ButtonMatcher::ButtonMatcher(ButtonType type, size_t min_width, size_t max_width, double max_rmsd) + : WaterfillTemplateMatcher( + templatePath(type), Color(0xff808008), Color(0xffffffff), 100 + ) + , m_min_width(min_width) + , m_min_height(max_width) + , m_max_rmsd(max_rmsd) +{} +const ButtonMatcher& ButtonMatcher::A(){ + static ButtonMatcher matcher(ButtonType::ButtonA, 15, 15, 90); + return matcher; +} +const ButtonMatcher& ButtonMatcher::B(){ + static ButtonMatcher matcher(ButtonType::ButtonB, 15, 15, 90); + return matcher; +} +const ButtonMatcher& ButtonMatcher::Plus(){ + static ButtonMatcher matcher(ButtonType::ButtonPlus, 15, 15, 120); + return matcher; +} +const ButtonMatcher& ButtonMatcher::Minus(){ + static ButtonMatcher matcher(ButtonType::ButtonMinus, 15, 15, 120); + return matcher; +} +const ButtonMatcher& ButtonMatcher::ArrowLeft(){ + static ButtonMatcher matcher(ButtonType::ArrowLeft, 5, 10, 180); + return matcher; +} +const ButtonMatcher& ButtonMatcher::ArrowRight(){ + static ButtonMatcher matcher(ButtonType::ArrowRight, 5, 10, 180); + return matcher; +} + + + + + +ButtonTracker::ButtonTracker(ButtonType type) + : WhiteObjectDetector( + COLOR_CYAN, + { + Color(0xff808080), + Color(0xff909090), + Color(0xffa0a0a0), + Color(0xffb0b0b0), + Color(0xffc0c0c0), + Color(0xffd0d0d0), + } + ) + , m_matcher(getButtonMatcher(type)) +{} + +void ButtonTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ +// cout << "asdf" << endl; +// static int c = 0; +// extract_box(image, object).save("test-" + std::to_string(c++) + ".png"); +// image.save("test-" + std::to_string(c++) + "-A.png"); +// extract_box(image, object).save("test-" + std::to_string(c++) + "-B.png"); + + double rmsd = m_matcher.rmsd_precropped(extract_box_reference(image, object), object); +// cout << "rmsd = " << rmsd << endl; +// cout << "max = " << m_matcher.m_max_rmsd << endl; + if (rmsd < m_matcher.m_max_rmsd){ +// cout << "matching rmsd = " << rmsd << endl; + m_detections.emplace_back(object); + } +} +void ButtonTracker::finish(const ImageViewRGB32& image){ + merge_heavily_overlapping(); +} + + + +ButtonDetector::ButtonDetector( + Logger& logger, VideoOverlay& overlay, + ButtonType type, + const ImageFloatBox& box, + std::chrono::milliseconds min_streak, + bool stop_on_detected +) + : VisualInferenceCallback("CenterAButtonDetector") + , m_logger(logger) + , m_box(box) + , m_stop_on_detected(stop_on_detected) + , m_tracker(type) + , m_watcher(overlay, m_box, { {m_tracker, false} }) + , m_debouncer( + false, min_streak, + [this, type](bool value){ + if (value){ + m_logger.log(std::string("Detected (") + button_name(type) + ") Button.", COLOR_PURPLE); + }else{ + m_logger.log(std::string("(") + button_name(type) + ") Button has disappeared.", COLOR_PURPLE); + } + } + ) +{} + +void ButtonDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool ButtonDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_watcher.process_frame(frame, timestamp); + bool detected = m_debouncer.push_value(!m_tracker.detections().empty(), timestamp); + return detected && m_stop_on_detected; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h index 024297e215..e29c9252a2 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h @@ -1,101 +1,101 @@ -/* Button Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ButtonDetector_H -#define PokemonAutomation_PokemonLA_ButtonDetector_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/DetectionDebouncer.h" -#include "PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class ButtonType{ - ButtonA, - ButtonB, - ButtonPlus, - ButtonMinus, - ArrowLeft, - ArrowRight, -}; - - -class ButtonMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - ButtonMatcher(ButtonType type, size_t min_width, size_t max_width, double max_rmsd); - static const ButtonMatcher& A(); - static const ButtonMatcher& B(); - static const ButtonMatcher& Plus(); - static const ButtonMatcher& Minus(); - static const ButtonMatcher& ArrowLeft(); - static const ButtonMatcher& ArrowRight(); - - virtual bool check_image(const ImageViewRGB32& image) const override{ - return image.width() >= m_min_width && image.height() >= m_min_height; - }; - - size_t m_min_width; - size_t m_min_height; - double m_max_rmsd; -}; - - - - -class ButtonTracker : public WhiteObjectDetector{ -public: - ButtonTracker(ButtonType type); - - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; - -private: - const ButtonMatcher& m_matcher; -}; - - - -class ButtonDetector : public VisualInferenceCallback{ -public: - ButtonDetector( - Logger& logger, VideoOverlay& overlay, - ButtonType type, - const ImageFloatBox& box, - std::chrono::milliseconds min_streak, - bool stop_on_detected - ); - - bool detected() const{ - return m_debouncer.get(); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - ImageFloatBox m_box; - bool m_stop_on_detected; - - ButtonTracker m_tracker; - WhiteObjectWatcher m_watcher; - - DetectionDebouncer m_debouncer; -}; - - - -} -} -} -#endif +/* Button Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ButtonDetector_H +#define PokemonAutomation_PokemonLA_ButtonDetector_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/DetectionDebouncer.h" +#include "PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class ButtonType{ + ButtonA, + ButtonB, + ButtonPlus, + ButtonMinus, + ArrowLeft, + ArrowRight, +}; + + +class ButtonMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + ButtonMatcher(ButtonType type, size_t min_width, size_t max_width, double max_rmsd); + static const ButtonMatcher& A(); + static const ButtonMatcher& B(); + static const ButtonMatcher& Plus(); + static const ButtonMatcher& Minus(); + static const ButtonMatcher& ArrowLeft(); + static const ButtonMatcher& ArrowRight(); + + virtual bool check_image(const ImageViewRGB32& image) const override{ + return image.width() >= m_min_width && image.height() >= m_min_height; + }; + + size_t m_min_width; + size_t m_min_height; + double m_max_rmsd; +}; + + + + +class ButtonTracker : public WhiteObjectDetector{ +public: + ButtonTracker(ButtonType type); + + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; + +private: + const ButtonMatcher& m_matcher; +}; + + + +class ButtonDetector : public VisualInferenceCallback{ +public: + ButtonDetector( + Logger& logger, VideoOverlay& overlay, + ButtonType type, + const ImageFloatBox& box, + std::chrono::milliseconds min_streak, + bool stop_on_detected + ); + + bool detected() const{ + return m_debouncer.get(); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + ImageFloatBox m_box; + bool m_stop_on_detected; + + ButtonTracker m_tracker; + WhiteObjectWatcher m_watcher; + + DetectionDebouncer m_debouncer; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.cpp index d25f55f81b..5d069d2249 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.cpp @@ -1,102 +1,102 @@ -/* Dialogue Ellipse Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "PokemonLA_DialogueEllipseDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -DialogueEllipseMatcher::DialogueEllipseMatcher() - : WaterfillTemplateMatcher( - "PokemonLA/DialogueEllipse-Template.png", - Color(0xff808008), Color(0xffffffff), 300 - ) -{ - m_aspect_ratio_lower = 0.95; - m_aspect_ratio_upper = 1.05; - m_area_ratio_lower = 0.95; - m_area_ratio_upper = 1.05; -} - -const DialogueEllipseMatcher& DialogueEllipseMatcher::instance(){ - static DialogueEllipseMatcher matcher; - return matcher; -} - - -DialogueEllipseTracker::DialogueEllipseTracker() - : WhiteObjectDetector( - COLOR_CYAN, - { - Color(0xff808080), - Color(0xff909090), - Color(0xffa0a0a0), - Color(0xffb0b0b0), - } - ) -{} - -void DialogueEllipseTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ - double rmsd = DialogueEllipseMatcher::instance().rmsd_original(image, object); - if (rmsd < 80){ - m_detections.emplace_back(object); - } -} - -void DialogueEllipseTracker::finish(const ImageViewRGB32& image){ - merge_heavily_overlapping(); -} - - - -DialogueEllipseDetector::DialogueEllipseDetector( - Logger& logger, VideoOverlay& overlay, - std::chrono::milliseconds min_streak, - bool stop_on_detected -) - : VisualInferenceCallback("DialogueEllipseButtonDetector") - , m_logger(logger) - , m_box(0.741, 0.811, 0.028, 0.023) - , m_stop_on_detected(stop_on_detected) - , m_watcher(overlay, m_box, { {m_tracker, false} }) - , m_debouncer( - false, min_streak, - [&](bool value){ - if (value){ - m_logger.log("Detected transparent dialogue box ellipse button.", COLOR_PURPLE); - }else{ - m_logger.log("Transparent dialogue box ellipse button disappeared.", COLOR_PURPLE); - } - } - ) -{} - - -void DialogueEllipseDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool DialogueEllipseDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_watcher.process_frame(frame, timestamp); - bool detected = m_debouncer.push_value(!m_tracker.detections().empty(), timestamp); - - // static int count = 0; - // if (detected){ - // frame.save("./debug_transparentEllipse" + std::to_string(count) + ".png"); - // count++; - // } - return detected && m_stop_on_detected; -} - - - - - -} -} -} +/* Dialogue Ellipse Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "PokemonLA_DialogueEllipseDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +DialogueEllipseMatcher::DialogueEllipseMatcher() + : WaterfillTemplateMatcher( + "PokemonLA/DialogueEllipse-Template.png", + Color(0xff808008), Color(0xffffffff), 300 + ) +{ + m_aspect_ratio_lower = 0.95; + m_aspect_ratio_upper = 1.05; + m_area_ratio_lower = 0.95; + m_area_ratio_upper = 1.05; +} + +const DialogueEllipseMatcher& DialogueEllipseMatcher::instance(){ + static DialogueEllipseMatcher matcher; + return matcher; +} + + +DialogueEllipseTracker::DialogueEllipseTracker() + : WhiteObjectDetector( + COLOR_CYAN, + { + Color(0xff808080), + Color(0xff909090), + Color(0xffa0a0a0), + Color(0xffb0b0b0), + } + ) +{} + +void DialogueEllipseTracker::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ + double rmsd = DialogueEllipseMatcher::instance().rmsd_original(image, object); + if (rmsd < 80){ + m_detections.emplace_back(object); + } +} + +void DialogueEllipseTracker::finish(const ImageViewRGB32& image){ + merge_heavily_overlapping(); +} + + + +DialogueEllipseDetector::DialogueEllipseDetector( + Logger& logger, VideoOverlay& overlay, + std::chrono::milliseconds min_streak, + bool stop_on_detected +) + : VisualInferenceCallback("DialogueEllipseButtonDetector") + , m_logger(logger) + , m_box(0.741, 0.811, 0.028, 0.023) + , m_stop_on_detected(stop_on_detected) + , m_watcher(overlay, m_box, { {m_tracker, false} }) + , m_debouncer( + false, min_streak, + [&](bool value){ + if (value){ + m_logger.log("Detected transparent dialogue box ellipse button.", COLOR_PURPLE); + }else{ + m_logger.log("Transparent dialogue box ellipse button disappeared.", COLOR_PURPLE); + } + } + ) +{} + + +void DialogueEllipseDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool DialogueEllipseDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_watcher.process_frame(frame, timestamp); + bool detected = m_debouncer.push_value(!m_tracker.detections().empty(), timestamp); + + // static int count = 0; + // if (detected){ + // frame.save("./debug_transparentEllipse" + std::to_string(count) + ".png"); + // count++; + // } + return detected && m_stop_on_detected; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h index 3f72aba30c..fbbae06e4e 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h @@ -1,74 +1,74 @@ -/* Dialogue Ellipse Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the white wide ellipse at the end of the transparent dialogue box. - * The transparent dialogue box comes from your opponent shown before and/or after the battle, like - * Ingo's battles or Fortune Sisters'. - */ - -#ifndef PokemonAutomation_PokemonLA_DialogueEllipseDetector_H -#define PokemonAutomation_PokemonLA_DialogueEllipseDetector_H - -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/DetectionDebouncer.h" -#include "PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class DialogueEllipseMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - DialogueEllipseMatcher(); - static const DialogueEllipseMatcher& instance(); -}; - - - -class DialogueEllipseTracker : public WhiteObjectDetector{ -public: - DialogueEllipseTracker(); - - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; -}; - - - -class DialogueEllipseDetector : public VisualInferenceCallback{ -public: - DialogueEllipseDetector( - Logger& logger, VideoOverlay& overlay, - std::chrono::milliseconds min_streak, - bool stop_on_detected - ); - - bool detected() const{ - return m_debouncer.get(); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - ImageFloatBox m_box; - bool m_stop_on_detected; - - DialogueEllipseTracker m_tracker; - WhiteObjectWatcher m_watcher; - - DetectionDebouncer m_debouncer; -}; - - - -} -} -} -#endif +/* Dialogue Ellipse Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the white wide ellipse at the end of the transparent dialogue box. + * The transparent dialogue box comes from your opponent shown before and/or after the battle, like + * Ingo's battles or Fortune Sisters'. + */ + +#ifndef PokemonAutomation_PokemonLA_DialogueEllipseDetector_H +#define PokemonAutomation_PokemonLA_DialogueEllipseDetector_H + +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/DetectionDebouncer.h" +#include "PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class DialogueEllipseMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + DialogueEllipseMatcher(); + static const DialogueEllipseMatcher& instance(); +}; + + + +class DialogueEllipseTracker : public WhiteObjectDetector{ +public: + DialogueEllipseTracker(); + + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; +}; + + + +class DialogueEllipseDetector : public VisualInferenceCallback{ +public: + DialogueEllipseDetector( + Logger& logger, VideoOverlay& overlay, + std::chrono::milliseconds min_streak, + bool stop_on_detected + ); + + bool detected() const{ + return m_debouncer.get(); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + ImageFloatBox m_box; + bool m_stop_on_detected; + + DialogueEllipseTracker m_tracker; + WhiteObjectWatcher m_watcher; + + DetectionDebouncer m_debouncer; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.cpp index 3a4392508a..5e6e68a843 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.cpp @@ -1,110 +1,110 @@ -/* Dialogue Yellow Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonLA_DialogueYellowArrowDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -namespace{ - // This box covers all possible locations of the yellow arrow - ImageFloatBox YELLOW_ARROW_BOX{0.720, 0.759, 0.049, 0.128}; -} - -class DialogueYellowArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - DialogueYellowArrowMatcher(); - static const DialogueYellowArrowMatcher& instance(); -}; - - -DialogueYellowArrowMatcher::DialogueYellowArrowMatcher() - : WaterfillTemplateMatcher( - "PokemonLA/YellowArrow-Template.png", - Color(0xff808008), Color(0xffffffff), 200 - ) -{ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.1; -} - -const DialogueYellowArrowMatcher& DialogueYellowArrowMatcher::instance(){ - static DialogueYellowArrowMatcher matcher; - return matcher; -} - - - -DialogueYellowArrowDetector::DialogueYellowArrowDetector( - Logger& logger, VideoOverlay& overlay, - bool stop_on_detected -) - : VisualInferenceCallback("DialogueYellowArrowDetector") - , m_logger(logger) - , m_stop_on_detected(stop_on_detected) -{} - - -void DialogueYellowArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, YELLOW_ARROW_BOX); -} -bool DialogueYellowArrowDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const std::vector> filters = { - {combine_rgb(160, 160, 0), combine_rgb(255, 255, 255)}, - {combine_rgb(200, 200, 0), combine_rgb(255, 255, 255)}, - {combine_rgb(200, 200, 0), combine_rgb(255, 255, 180)}, - }; - - // We found 200 to be a good minimal yellow arrow pixel count on a 1920x1080 resolution screenshot. - const double screen_scale = frame.height() / 1080.0; - const size_t min_size = size_t(200 * screen_scale * screen_scale); - - const bool detected = match_template_by_waterfill( - extract_box_reference(frame, YELLOW_ARROW_BOX), - DialogueYellowArrowMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 80, - [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); - - if (detected){ - m_logger.log("Detected yellow arrow in transparent dialogue box.", COLOR_PURPLE); - } - - m_detected.store(detected, std::memory_order_release); - -#if 0 - if (detected){ - static size_t c = 0; - frame.save("YellowArrowTriggered-" + std::to_string(c++) + ".png"); - } -#endif - - return detected && m_stop_on_detected; -} - - - - - -} -} -} +/* Dialogue Yellow Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonLA_DialogueYellowArrowDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +namespace{ + // This box covers all possible locations of the yellow arrow + ImageFloatBox YELLOW_ARROW_BOX{0.720, 0.759, 0.049, 0.128}; +} + +class DialogueYellowArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + DialogueYellowArrowMatcher(); + static const DialogueYellowArrowMatcher& instance(); +}; + + +DialogueYellowArrowMatcher::DialogueYellowArrowMatcher() + : WaterfillTemplateMatcher( + "PokemonLA/YellowArrow-Template.png", + Color(0xff808008), Color(0xffffffff), 200 + ) +{ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.1; +} + +const DialogueYellowArrowMatcher& DialogueYellowArrowMatcher::instance(){ + static DialogueYellowArrowMatcher matcher; + return matcher; +} + + + +DialogueYellowArrowDetector::DialogueYellowArrowDetector( + Logger& logger, VideoOverlay& overlay, + bool stop_on_detected +) + : VisualInferenceCallback("DialogueYellowArrowDetector") + , m_logger(logger) + , m_stop_on_detected(stop_on_detected) +{} + + +void DialogueYellowArrowDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, YELLOW_ARROW_BOX); +} +bool DialogueYellowArrowDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const std::vector> filters = { + {combine_rgb(160, 160, 0), combine_rgb(255, 255, 255)}, + {combine_rgb(200, 200, 0), combine_rgb(255, 255, 255)}, + {combine_rgb(200, 200, 0), combine_rgb(255, 255, 180)}, + }; + + // We found 200 to be a good minimal yellow arrow pixel count on a 1920x1080 resolution screenshot. + const double screen_scale = frame.height() / 1080.0; + const size_t min_size = size_t(200 * screen_scale * screen_scale); + + const bool detected = match_template_by_waterfill( + extract_box_reference(frame, YELLOW_ARROW_BOX), + DialogueYellowArrowMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 80, + [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); + + if (detected){ + m_logger.log("Detected yellow arrow in transparent dialogue box.", COLOR_PURPLE); + } + + m_detected.store(detected, std::memory_order_release); + +#if 0 + if (detected){ + static size_t c = 0; + frame.save("YellowArrowTriggered-" + std::to_string(c++) + ".png"); + } +#endif + + return detected && m_stop_on_detected; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h index bd13b153b4..392fea518d 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h @@ -1,51 +1,51 @@ -/* Dialogue Yellow Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - * The yellow marker pointing to the button to advance dialogue boxes. - * For different types of dialogue boxes, the locations of the yellow arrow is different. - * This detector covers all possible locations of the yellow arrow. - */ - -#ifndef PokemonAutomation_PokemonLA_DialogueYellowArrowDetector_H -#define PokemonAutomation_PokemonLA_DialogueYellowArrowDetector_H - -#include -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class Logger; - class VideoOverlay; -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class DialogueYellowArrowDetector : public VisualInferenceCallback{ -public: - DialogueYellowArrowDetector( - Logger& logger, VideoOverlay& overlay, - bool stop_on_detected - ); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - bool m_stop_on_detected; - - std::atomic m_detected; -}; - - - -} -} -} -#endif +/* Dialogue Yellow Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + * The yellow marker pointing to the button to advance dialogue boxes. + * For different types of dialogue boxes, the locations of the yellow arrow is different. + * This detector covers all possible locations of the yellow arrow. + */ + +#ifndef PokemonAutomation_PokemonLA_DialogueYellowArrowDetector_H +#define PokemonAutomation_PokemonLA_DialogueYellowArrowDetector_H + +#include +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class Logger; + class VideoOverlay; +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class DialogueYellowArrowDetector : public VisualInferenceCallback{ +public: + DialogueYellowArrowDetector( + Logger& logger, VideoOverlay& overlay, + bool stop_on_detected + ); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + bool m_stop_on_detected; + + std::atomic m_detected; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.cpp index ddfefb848c..cef89debee 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.cpp @@ -1,457 +1,457 @@ -/* Flag Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "PokemonLA_FlagDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels::Waterfill; - - -void FlagMatcher_make_template(){ - ImageRGB32 image("Flag-Original.png"); - image = image.scale_to(image.width() / 2, image.height() / 2); - uint32_t* ptr = image.data(); - size_t words = image.bytes_per_row() / sizeof(uint32_t); - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - uint32_t& pixel = ptr[r * words + c]; - Color color(pixel); - uint32_t red = color.red(); - uint32_t green = color.green(); - uint32_t blue = color.blue(); -// if (red < 128 && green < 128 && blue < 128){ -// pixel = 0x00000000; -// } - if (red < 128 || green < 128 || blue < 128){ - pixel = 0x00000000; - } - } - } - image.save("Flag-Template0.png"); -} - - - - -class FlagMatcher : public ImageMatch::SubObjectTemplateMatcher{ -public: - FlagMatcher(bool left) - : SubObjectTemplateMatcher("PokemonLA/Flag-Template.png", 100) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), - 128, 255, - 128, 255, - 128, 255 - ); - std::vector objects = find_objects_inplace(matrix, 20); - if (objects.size() != 2){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find exactly 2 objects in resource.", - m_path - ); - } - - if (left == (objects[0].min_x < objects[1].min_x)){ - set_subobject(objects[0]); - }else{ - set_subobject(objects[1]); - } - } - - static const FlagMatcher& left(){ - static FlagMatcher matcher(true); - return matcher; - } - static const FlagMatcher& right(){ - static FlagMatcher matcher(false); - return matcher; - } -}; - - - - -FlagDetector::FlagDetector() - : WhiteObjectDetector( - COLOR_CYAN, - { - Color(0xff808080), - Color(0xff909090), - Color(0xffa0a0a0), - Color(0xffb0b0b0), - Color(0xffc0c0c0), - Color(0xffd0d0d0), - Color(0xffe0e0e0), - Color(0xfff0f0f0), - } - ) -{} -void FlagDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ -// cout << "FlagDetector::process_object()" << endl; - if (object.area < 50){ - return; - } - if (object.height() > 0.04 * image.height()){ - return; - } - if (object.height() < 0.01 * image.height()){ - return; - } - if (object.width() > 0.03 * image.width()){ - return; - } - ImagePixelBox object_box; - -// static int count = 0; -// extract_box_reference(image, object).save("test-" + std::to_string(count++) + ".png"); - -// cout << "left" << endl; - if (FlagMatcher::left().matches(object_box, image, object)){ -// static int count = 0; -// extract_box_reference(image, object_box).save("test-left-" + std::to_string(count++) + ".png"); - m_left.emplace_back(object_box); - } -// cout << "right" << endl; - if (FlagMatcher::right().matches(object_box, image, object)){ -// static int count = 0; -// extract_box_reference(image, object_box).save("test-right-" + std::to_string(count++) + ".png"); - m_right.emplace_back(object_box); - } - -// cout << "left = " << m_left.size() << endl; -// cout << "right = " << m_right.size() << endl; -} -void FlagDetector::finish(const ImageViewRGB32& image){ -#if 0 - cout << "left = " << m_left.size() << endl; - cout << "right = " << m_right.size() << endl; - - for (const ImagePixelBox& box : m_left){ - static int count = 0; - extract_box_reference(image, box).save("test-left-" + std::to_string(count++) + ".png"); - } - for (const ImagePixelBox& box : m_right){ - static int count = 0; - extract_box_reference(image, box).save("test-right-" + std::to_string(count++) + ".png"); - } -#endif - - // Merge left/right parts. - for (auto iter0 = m_left.begin(); iter0 != m_left.end();){ - double height = (double)iter0->height(); - double width = (double)iter0->width(); - bool removed = false; - for (auto iter1 = m_right.begin(); iter1 != m_right.end(); ++iter1){ - double height_ratio = height / iter1->height(); - if (height_ratio < 0.8 || height_ratio > 1.2){ -// cout << "bad height ratio: " << height_ratio << endl; - continue; - } - double width_ratio = width / iter1->width(); - if (width_ratio < 0.8 || width_ratio > 1.2){ -// cout << "bad width ratio: " << width_ratio << endl; - continue; - } - - double horizontal_offset = ((ptrdiff_t)iter0->min_x - (ptrdiff_t)iter1->min_x) / width; - if (std::abs(horizontal_offset) > 0.1){ -// cout << "bad horizontal offset: " << horizontal_offset << endl; - continue; - } - - double vertical_offset = ((ptrdiff_t)iter0->min_y - (ptrdiff_t)iter1->min_y) / height; - if (std::abs(vertical_offset) > 0.1){ -// cout << "bad vertical offset: " << vertical_offset << endl; - continue; - } - - m_detections.emplace_back( - iter0->min_x, - std::min(iter0->min_y, iter1->min_y), - iter1->max_x, - std::max(iter0->max_y, iter1->max_y) - ); - iter0 = m_left.erase(iter0); - m_right.erase(iter1); - removed = true; - break; - } - if (!removed){ - ++iter0; - } - } - m_left.clear(); - m_right.clear(); -// cout << "m_detections = " << m_detections.size() << endl; - merge_heavily_overlapping(0.3); -} - - - - - - - -class DigitMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - DigitMatcher(const char* path) - : WaterfillTemplateMatcher(path, Color(0xffa0a0a0), Color(0xffffffff), 30) - {} -}; - -std::vector> make_digit_matchers(){ - std::vector> matchers; - matchers.emplace_back(0, "PokemonLA/Digits/Digit-0-Template.png"); - matchers.emplace_back(1, "PokemonLA/Digits/Digit-1-Template.png"); - matchers.emplace_back(2, "PokemonLA/Digits/Digit-2-Template.png"); - matchers.emplace_back(3, "PokemonLA/Digits/Digit-3-Template.png"); - matchers.emplace_back(4, "PokemonLA/Digits/Digit-4-Template.png"); - matchers.emplace_back(5, "PokemonLA/Digits/Digit-5-Template.png"); - matchers.emplace_back(6, "PokemonLA/Digits/Digit-6-Template.png"); - matchers.emplace_back(7, "PokemonLA/Digits/Digit-7-Template.png"); - matchers.emplace_back(8, "PokemonLA/Digits/Digit-8-Template.png"); - matchers.emplace_back(9, "PokemonLA/Digits/Digit-9-Template.png"); - return matchers; -} - - -std::pair read_digit(const ImageViewRGB32& image, const WaterfillObject& object){ - static const std::vector> MATCHERS = make_digit_matchers(); - double best_rmsd = 99999; - int best_digit = -1; - for (const auto& item : MATCHERS){ -// cout << item.first << " : " << << endl; - double rmsd = item.second.rmsd_original(image, object); - if (best_rmsd > rmsd){ - best_rmsd = rmsd; - best_digit = item.first; - } - } -// cout << best_rmsd << endl; - if (best_rmsd > 100){ - best_digit = -1; - } - return {best_rmsd, best_digit}; -} - - - -int read_flag_distance(const ImageViewRGB32& screen, double flag_x, double flag_y){ - ImageFloatBox box(flag_x - 0.025, flag_y - 0.055, 0.045, 0.025); - ImageViewRGB32 image = extract_box_reference(screen, box); -// image.save("test.png"); - - size_t width = image.width(); - size_t height = image.height(); - - // Detect all the digits. - struct Hit{ - size_t min_x; - size_t max_x; - double mid_x; - double rmsd; - int digit; - }; - std::multimap hits; - - { - std::vector matrices = compress_rgb32_to_binary_range( - image, - { - {0xff808080, 0xffffffff}, - {0xff909090, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - {0xffb0b0b0, 0xffffffff}, - {0xffc0c0c0, 0xffffffff}, - {0xffd0d0d0, 0xffffffff}, - {0xffe0e0e0, 0xffffffff}, - {0xfff0f0f0, 0xffffffff}, - } - ); - - double inv_width = 0.5 / width; - - std::unique_ptr session = make_WaterfillSession(); - for (PackedBinaryMatrix& matrix : matrices){ -// cout << (int)filters[c].matrix.type() << endl; - session->set_source(matrix); - auto finder = session->make_iterator(30); - WaterfillObject object; - while (finder->find_next(object, false)){ - // Skip anything that touches the edge. - if (object.min_x == 0 || object.min_y == 0 || - object.max_x + 1 == width || object.max_y + 1 == height - ){ - continue; - } - -// static int c = 0; -// extract_box_reference(image, object).save("image-" + std::to_string(c++) + ".png"); - - std::pair digit = read_digit(image, object); - if (digit.second >= 0){ - hits.emplace( - object.min_x, - Hit{ - object.min_x, - object.max_x, - (object.min_x + object.max_x) * inv_width, - digit.first, - digit.second - } - ); - } - } - } - } - if (hits.empty()){ - return -1; - } - -#if 0 - for (const auto& item : hits){ - cout << item.first << " : " << item.second.min_x << " - " << item.second.max_x << " : " << item.second.digit << endl; - } -#endif - - - // Remove overlapping detections by picking the one with strongest detection on each overlap. - std::vector digits; - auto best = hits.begin(); - auto iter = best; - ++iter; - for (; iter != hits.end(); ++iter){ - // Next digit - if (best->second.max_x < iter->second.min_x){ - digits.emplace_back(best->second); - best = iter; - } - - // Overlapping. Pick better score. - if (best->second.rmsd > iter->second.rmsd){ - best = iter; - } - } - digits.emplace_back(best->second); - - - - // Now we use the position of the digits to correct for errors. - - int even_buckets[4] = {-1, -1, -1, -1}; - int odd_buckets[3] = {-1, -1, -1}; - size_t even_count = 0; - size_t odd_count = 0; - - // Put every digit into one of 7 buckets. - for (const Hit& digit : digits){ -// cout << "[" << digit.mid_x << " : " << digit.digit << "]"; - int bucket = (int)(digit.mid_x * 9.55557 - 1.4); - bucket = std::max(bucket, 0); - bucket = std::min(bucket, 6); - if (bucket % 2){ - odd_buckets[bucket / 2] = digit.digit; - odd_count++; - }else{ - even_buckets[bucket / 2] = digit.digit; - even_count++; - } - } -// cout << endl; - -// cout << "even = " << even_count << endl; -// cout << "odd = " << odd_count << endl; - - - // All the digits must call into either odd or even buckets. - // Anything else is a misread and we must return undetected. - if ((even_count != 0) == (odd_count != 0)){ - return -1; - } - -// cout << odd_buckets[0] << odd_buckets[1] << odd_buckets[2] << endl; - - if (odd_count != 0){ - // 1 digit only. - if (odd_buckets[0] < 0 && odd_buckets[2] < 0){ - // Return unconditionally. If it's one digit, then it matters so don't try to assume anything if it can't be read. - return odd_buckets[1]; - } - - // Now we know it's 3 digits for sure. - - // If we can't read the first 2 digits, we're stuck. - if (odd_buckets[0] < 0 || odd_buckets[1] < 0){ - return -1; - } - - // If we can't read the 3rd digit, then assume it's 5. - if (odd_buckets[2] < 0){ - odd_buckets[2] = 5; - } - - return odd_buckets[0] * 100 + odd_buckets[1] * 10 + odd_buckets[2]; - }else{ - // 2 digits only. - if (even_buckets[0] < 0 && even_buckets[3] < 0){ - // If we can't read the first digit, we're stuck. - if (even_buckets[1] < 0){ - return -1; - } - // If we can't read the 2nd digit, then assume it's 5. - if (even_buckets[2] < 0){ - even_buckets[2] = 5; - } - return even_buckets[1] * 10 + even_buckets[2]; - } - - // Now we know it's 4 digits for sure. - - // If we can't read either of the first 2 digits, assume they are 1. - if (even_buckets[0] < 0){ - even_buckets[0] = 1; - } - if (even_buckets[1] < 0){ - even_buckets[1] = 1; - } - - // If we can't read either of the last digits, assume they are 5. - if (even_buckets[2] < 0){ - even_buckets[2] = 5; - } - if (even_buckets[3] < 0){ - even_buckets[3] = 5; - } - - return even_buckets[0] * 1000 + even_buckets[1] * 100 + even_buckets[2] * 10 + even_buckets[3]; - } - -// return ret; -} - - - - - -} -} -} +/* Flag Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "PokemonLA_FlagDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels::Waterfill; + + +void FlagMatcher_make_template(){ + ImageRGB32 image("Flag-Original.png"); + image = image.scale_to(image.width() / 2, image.height() / 2); + uint32_t* ptr = image.data(); + size_t words = image.bytes_per_row() / sizeof(uint32_t); + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + uint32_t& pixel = ptr[r * words + c]; + Color color(pixel); + uint32_t red = color.red(); + uint32_t green = color.green(); + uint32_t blue = color.blue(); +// if (red < 128 && green < 128 && blue < 128){ +// pixel = 0x00000000; +// } + if (red < 128 || green < 128 || blue < 128){ + pixel = 0x00000000; + } + } + } + image.save("Flag-Template0.png"); +} + + + + +class FlagMatcher : public ImageMatch::SubObjectTemplateMatcher{ +public: + FlagMatcher(bool left) + : SubObjectTemplateMatcher("PokemonLA/Flag-Template.png", 100) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), + 128, 255, + 128, 255, + 128, 255 + ); + std::vector objects = find_objects_inplace(matrix, 20); + if (objects.size() != 2){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find exactly 2 objects in resource.", + m_path + ); + } + + if (left == (objects[0].min_x < objects[1].min_x)){ + set_subobject(objects[0]); + }else{ + set_subobject(objects[1]); + } + } + + static const FlagMatcher& left(){ + static FlagMatcher matcher(true); + return matcher; + } + static const FlagMatcher& right(){ + static FlagMatcher matcher(false); + return matcher; + } +}; + + + + +FlagDetector::FlagDetector() + : WhiteObjectDetector( + COLOR_CYAN, + { + Color(0xff808080), + Color(0xff909090), + Color(0xffa0a0a0), + Color(0xffb0b0b0), + Color(0xffc0c0c0), + Color(0xffd0d0d0), + Color(0xffe0e0e0), + Color(0xfff0f0f0), + } + ) +{} +void FlagDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ +// cout << "FlagDetector::process_object()" << endl; + if (object.area < 50){ + return; + } + if (object.height() > 0.04 * image.height()){ + return; + } + if (object.height() < 0.01 * image.height()){ + return; + } + if (object.width() > 0.03 * image.width()){ + return; + } + ImagePixelBox object_box; + +// static int count = 0; +// extract_box_reference(image, object).save("test-" + std::to_string(count++) + ".png"); + +// cout << "left" << endl; + if (FlagMatcher::left().matches(object_box, image, object)){ +// static int count = 0; +// extract_box_reference(image, object_box).save("test-left-" + std::to_string(count++) + ".png"); + m_left.emplace_back(object_box); + } +// cout << "right" << endl; + if (FlagMatcher::right().matches(object_box, image, object)){ +// static int count = 0; +// extract_box_reference(image, object_box).save("test-right-" + std::to_string(count++) + ".png"); + m_right.emplace_back(object_box); + } + +// cout << "left = " << m_left.size() << endl; +// cout << "right = " << m_right.size() << endl; +} +void FlagDetector::finish(const ImageViewRGB32& image){ +#if 0 + cout << "left = " << m_left.size() << endl; + cout << "right = " << m_right.size() << endl; + + for (const ImagePixelBox& box : m_left){ + static int count = 0; + extract_box_reference(image, box).save("test-left-" + std::to_string(count++) + ".png"); + } + for (const ImagePixelBox& box : m_right){ + static int count = 0; + extract_box_reference(image, box).save("test-right-" + std::to_string(count++) + ".png"); + } +#endif + + // Merge left/right parts. + for (auto iter0 = m_left.begin(); iter0 != m_left.end();){ + double height = (double)iter0->height(); + double width = (double)iter0->width(); + bool removed = false; + for (auto iter1 = m_right.begin(); iter1 != m_right.end(); ++iter1){ + double height_ratio = height / iter1->height(); + if (height_ratio < 0.8 || height_ratio > 1.2){ +// cout << "bad height ratio: " << height_ratio << endl; + continue; + } + double width_ratio = width / iter1->width(); + if (width_ratio < 0.8 || width_ratio > 1.2){ +// cout << "bad width ratio: " << width_ratio << endl; + continue; + } + + double horizontal_offset = ((ptrdiff_t)iter0->min_x - (ptrdiff_t)iter1->min_x) / width; + if (std::abs(horizontal_offset) > 0.1){ +// cout << "bad horizontal offset: " << horizontal_offset << endl; + continue; + } + + double vertical_offset = ((ptrdiff_t)iter0->min_y - (ptrdiff_t)iter1->min_y) / height; + if (std::abs(vertical_offset) > 0.1){ +// cout << "bad vertical offset: " << vertical_offset << endl; + continue; + } + + m_detections.emplace_back( + iter0->min_x, + std::min(iter0->min_y, iter1->min_y), + iter1->max_x, + std::max(iter0->max_y, iter1->max_y) + ); + iter0 = m_left.erase(iter0); + m_right.erase(iter1); + removed = true; + break; + } + if (!removed){ + ++iter0; + } + } + m_left.clear(); + m_right.clear(); +// cout << "m_detections = " << m_detections.size() << endl; + merge_heavily_overlapping(0.3); +} + + + + + + + +class DigitMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + DigitMatcher(const char* path) + : WaterfillTemplateMatcher(path, Color(0xffa0a0a0), Color(0xffffffff), 30) + {} +}; + +std::vector> make_digit_matchers(){ + std::vector> matchers; + matchers.emplace_back(0, "PokemonLA/Digits/Digit-0-Template.png"); + matchers.emplace_back(1, "PokemonLA/Digits/Digit-1-Template.png"); + matchers.emplace_back(2, "PokemonLA/Digits/Digit-2-Template.png"); + matchers.emplace_back(3, "PokemonLA/Digits/Digit-3-Template.png"); + matchers.emplace_back(4, "PokemonLA/Digits/Digit-4-Template.png"); + matchers.emplace_back(5, "PokemonLA/Digits/Digit-5-Template.png"); + matchers.emplace_back(6, "PokemonLA/Digits/Digit-6-Template.png"); + matchers.emplace_back(7, "PokemonLA/Digits/Digit-7-Template.png"); + matchers.emplace_back(8, "PokemonLA/Digits/Digit-8-Template.png"); + matchers.emplace_back(9, "PokemonLA/Digits/Digit-9-Template.png"); + return matchers; +} + + +std::pair read_digit(const ImageViewRGB32& image, const WaterfillObject& object){ + static const std::vector> MATCHERS = make_digit_matchers(); + double best_rmsd = 99999; + int best_digit = -1; + for (const auto& item : MATCHERS){ +// cout << item.first << " : " << << endl; + double rmsd = item.second.rmsd_original(image, object); + if (best_rmsd > rmsd){ + best_rmsd = rmsd; + best_digit = item.first; + } + } +// cout << best_rmsd << endl; + if (best_rmsd > 100){ + best_digit = -1; + } + return {best_rmsd, best_digit}; +} + + + +int read_flag_distance(const ImageViewRGB32& screen, double flag_x, double flag_y){ + ImageFloatBox box(flag_x - 0.025, flag_y - 0.055, 0.045, 0.025); + ImageViewRGB32 image = extract_box_reference(screen, box); +// image.save("test.png"); + + size_t width = image.width(); + size_t height = image.height(); + + // Detect all the digits. + struct Hit{ + size_t min_x; + size_t max_x; + double mid_x; + double rmsd; + int digit; + }; + std::multimap hits; + + { + std::vector matrices = compress_rgb32_to_binary_range( + image, + { + {0xff808080, 0xffffffff}, + {0xff909090, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + {0xffb0b0b0, 0xffffffff}, + {0xffc0c0c0, 0xffffffff}, + {0xffd0d0d0, 0xffffffff}, + {0xffe0e0e0, 0xffffffff}, + {0xfff0f0f0, 0xffffffff}, + } + ); + + double inv_width = 0.5 / width; + + std::unique_ptr session = make_WaterfillSession(); + for (PackedBinaryMatrix& matrix : matrices){ +// cout << (int)filters[c].matrix.type() << endl; + session->set_source(matrix); + auto finder = session->make_iterator(30); + WaterfillObject object; + while (finder->find_next(object, false)){ + // Skip anything that touches the edge. + if (object.min_x == 0 || object.min_y == 0 || + object.max_x + 1 == width || object.max_y + 1 == height + ){ + continue; + } + +// static int c = 0; +// extract_box_reference(image, object).save("image-" + std::to_string(c++) + ".png"); + + std::pair digit = read_digit(image, object); + if (digit.second >= 0){ + hits.emplace( + object.min_x, + Hit{ + object.min_x, + object.max_x, + (object.min_x + object.max_x) * inv_width, + digit.first, + digit.second + } + ); + } + } + } + } + if (hits.empty()){ + return -1; + } + +#if 0 + for (const auto& item : hits){ + cout << item.first << " : " << item.second.min_x << " - " << item.second.max_x << " : " << item.second.digit << endl; + } +#endif + + + // Remove overlapping detections by picking the one with strongest detection on each overlap. + std::vector digits; + auto best = hits.begin(); + auto iter = best; + ++iter; + for (; iter != hits.end(); ++iter){ + // Next digit + if (best->second.max_x < iter->second.min_x){ + digits.emplace_back(best->second); + best = iter; + } + + // Overlapping. Pick better score. + if (best->second.rmsd > iter->second.rmsd){ + best = iter; + } + } + digits.emplace_back(best->second); + + + + // Now we use the position of the digits to correct for errors. + + int even_buckets[4] = {-1, -1, -1, -1}; + int odd_buckets[3] = {-1, -1, -1}; + size_t even_count = 0; + size_t odd_count = 0; + + // Put every digit into one of 7 buckets. + for (const Hit& digit : digits){ +// cout << "[" << digit.mid_x << " : " << digit.digit << "]"; + int bucket = (int)(digit.mid_x * 9.55557 - 1.4); + bucket = std::max(bucket, 0); + bucket = std::min(bucket, 6); + if (bucket % 2){ + odd_buckets[bucket / 2] = digit.digit; + odd_count++; + }else{ + even_buckets[bucket / 2] = digit.digit; + even_count++; + } + } +// cout << endl; + +// cout << "even = " << even_count << endl; +// cout << "odd = " << odd_count << endl; + + + // All the digits must call into either odd or even buckets. + // Anything else is a misread and we must return undetected. + if ((even_count != 0) == (odd_count != 0)){ + return -1; + } + +// cout << odd_buckets[0] << odd_buckets[1] << odd_buckets[2] << endl; + + if (odd_count != 0){ + // 1 digit only. + if (odd_buckets[0] < 0 && odd_buckets[2] < 0){ + // Return unconditionally. If it's one digit, then it matters so don't try to assume anything if it can't be read. + return odd_buckets[1]; + } + + // Now we know it's 3 digits for sure. + + // If we can't read the first 2 digits, we're stuck. + if (odd_buckets[0] < 0 || odd_buckets[1] < 0){ + return -1; + } + + // If we can't read the 3rd digit, then assume it's 5. + if (odd_buckets[2] < 0){ + odd_buckets[2] = 5; + } + + return odd_buckets[0] * 100 + odd_buckets[1] * 10 + odd_buckets[2]; + }else{ + // 2 digits only. + if (even_buckets[0] < 0 && even_buckets[3] < 0){ + // If we can't read the first digit, we're stuck. + if (even_buckets[1] < 0){ + return -1; + } + // If we can't read the 2nd digit, then assume it's 5. + if (even_buckets[2] < 0){ + even_buckets[2] = 5; + } + return even_buckets[1] * 10 + even_buckets[2]; + } + + // Now we know it's 4 digits for sure. + + // If we can't read either of the first 2 digits, assume they are 1. + if (even_buckets[0] < 0){ + even_buckets[0] = 1; + } + if (even_buckets[1] < 0){ + even_buckets[1] = 1; + } + + // If we can't read either of the last digits, assume they are 5. + if (even_buckets[2] < 0){ + even_buckets[2] = 5; + } + if (even_buckets[3] < 0){ + even_buckets[3] = 5; + } + + return even_buckets[0] * 1000 + even_buckets[1] * 100 + even_buckets[2] * 10 + even_buckets[3]; + } + +// return ret; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h index a9c17b2f0b..876c66d8b2 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h @@ -1,39 +1,39 @@ -/* Flag Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_FlagDetector_H -#define PokemonAutomation_PokemonLA_FlagDetector_H - -#include -#include "PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class FlagDetector : public WhiteObjectDetector{ -public: - FlagDetector(); - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; - virtual void finish(const ImageViewRGB32& image) override; - -private: - std::list m_left; - std::list m_right; -}; - - - -int read_flag_distance(const ImageViewRGB32& screen, double flag_x, double flag_y); - - - - -} -} -} -#endif +/* Flag Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_FlagDetector_H +#define PokemonAutomation_PokemonLA_FlagDetector_H + +#include +#include "PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class FlagDetector : public WhiteObjectDetector{ +public: + FlagDetector(); + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; + virtual void finish(const ImageViewRGB32& image) override; + +private: + std::list m_left; + std::list m_right; +}; + + + +int read_flag_distance(const ImageViewRGB32& screen, double flag_x, double flag_y); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.cpp index c8f692d279..ca1c7ef5ae 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.cpp @@ -1,134 +1,134 @@ -/* Flag Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonLA_FlagTracker.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -FlagTracker::FlagTracker(Logger& /*logger*/, VideoOverlay& overlay) - : VisualInferenceCallback("FlagTracker") - // , m_logger(logger) - , m_watcher(overlay, {0, 0, 1, 1}, {{m_flags, false}}) -{} - -void FlagTracker::make_overlays(VideoOverlaySet& items) const{ - m_watcher.make_overlays(items); -} - -bool FlagTracker::get( - double& distance, double& x, double& y, - WallClock timestamp -) const{ - ReadSpinLock lg(m_lock); - - // If history is empty or stale, return no detection. - if (m_history.empty() || m_history.back().timestamp + std::chrono::milliseconds(500) < timestamp){ - return false; - } - - { - const Sample& sample = m_history.back(); - x = sample.x; - y = sample.y; - } - - // Distance reading is unreliable. So look at the last 2 seconds of history to infer it. - std::multimap distances; - for (const Sample& sample : m_history){ - if (0 <= sample.distance && sample.distance <= 999){ - distances.emplace(sample.distance, sample.timestamp); - } - } - - if (distances.size() < 5){ - distance = -1; - return true; - } - - // Find the median. - double median; - { - size_t mid = distances.size() / 2; - auto iter = distances.begin(); - for (size_t c = 0; c < mid; c++){ - ++iter; - } - median = iter->first; - } - -// distance = median; -// cout << distance << endl; - - // Pick the latest value that isn't too far from the median. - for (auto iter = m_history.rbegin(); iter != m_history.rend(); ++iter){ - if (std::abs(iter->distance - median) < 20){ - distance = iter->distance; - return true; - } - } - distance = -1; - return true; -} - -bool FlagTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_watcher.process_frame(frame, timestamp); - - Sample sample; - - const std::vector& flags = m_flags.detections(); - bool ok = flags.size() == 1; - if (ok){ - sample.timestamp = timestamp; - sample.x = (double)(flags[0].min_x + flags[0].max_x) / (frame.width() * 2); - sample.y = (double)(flags[0].min_y + flags[0].max_y) / (frame.height() * 2); - sample.distance = read_flag_distance(frame, sample.x, sample.y); - -#if 0 -// cout << sample.distance << endl; - if (sample.distance > 0 && sample.distance < 10){ - static int c = 0; - frame.save("test-" + std::to_string(c++) + ".png"); - } -#endif - }else{ -// frame.save("test.png"); -// cout << "no flag" << endl; - } - - - WriteSpinLock lg(m_lock); - - // Clear out old history. - WallClock threshold = timestamp - std::chrono::seconds(2); - while (!m_history.empty() && m_history.front().timestamp < threshold){ - m_history.pop_front(); - } - - if (ok){ - m_history.emplace_back(std::move(sample)); - } - - return false; -} - - - - - -} -} -} +/* Flag Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonLA_FlagTracker.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +FlagTracker::FlagTracker(Logger& /*logger*/, VideoOverlay& overlay) + : VisualInferenceCallback("FlagTracker") + // , m_logger(logger) + , m_watcher(overlay, {0, 0, 1, 1}, {{m_flags, false}}) +{} + +void FlagTracker::make_overlays(VideoOverlaySet& items) const{ + m_watcher.make_overlays(items); +} + +bool FlagTracker::get( + double& distance, double& x, double& y, + WallClock timestamp +) const{ + ReadSpinLock lg(m_lock); + + // If history is empty or stale, return no detection. + if (m_history.empty() || m_history.back().timestamp + std::chrono::milliseconds(500) < timestamp){ + return false; + } + + { + const Sample& sample = m_history.back(); + x = sample.x; + y = sample.y; + } + + // Distance reading is unreliable. So look at the last 2 seconds of history to infer it. + std::multimap distances; + for (const Sample& sample : m_history){ + if (0 <= sample.distance && sample.distance <= 999){ + distances.emplace(sample.distance, sample.timestamp); + } + } + + if (distances.size() < 5){ + distance = -1; + return true; + } + + // Find the median. + double median; + { + size_t mid = distances.size() / 2; + auto iter = distances.begin(); + for (size_t c = 0; c < mid; c++){ + ++iter; + } + median = iter->first; + } + +// distance = median; +// cout << distance << endl; + + // Pick the latest value that isn't too far from the median. + for (auto iter = m_history.rbegin(); iter != m_history.rend(); ++iter){ + if (std::abs(iter->distance - median) < 20){ + distance = iter->distance; + return true; + } + } + distance = -1; + return true; +} + +bool FlagTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_watcher.process_frame(frame, timestamp); + + Sample sample; + + const std::vector& flags = m_flags.detections(); + bool ok = flags.size() == 1; + if (ok){ + sample.timestamp = timestamp; + sample.x = (double)(flags[0].min_x + flags[0].max_x) / (frame.width() * 2); + sample.y = (double)(flags[0].min_y + flags[0].max_y) / (frame.height() * 2); + sample.distance = read_flag_distance(frame, sample.x, sample.y); + +#if 0 +// cout << sample.distance << endl; + if (sample.distance > 0 && sample.distance < 10){ + static int c = 0; + frame.save("test-" + std::to_string(c++) + ".png"); + } +#endif + }else{ +// frame.save("test.png"); +// cout << "no flag" << endl; + } + + + WriteSpinLock lg(m_lock); + + // Clear out old history. + WallClock threshold = timestamp - std::chrono::seconds(2); + while (!m_history.empty() && m_history.front().timestamp < threshold){ + m_history.pop_front(); + } + + if (ok){ + m_history.emplace_back(std::move(sample)); + } + + return false; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h index 119418aa29..8b702234af 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h @@ -1,57 +1,57 @@ -/* Flag Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_FlagTracker_H -#define PokemonAutomation_PokemonLA_FlagTracker_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "PokemonLA_WhiteObjectDetector.h" -#include "PokemonLA_FlagDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class FlagTracker : public VisualInferenceCallback{ -public: - FlagTracker(Logger& logger, VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - bool get( - double& distance, double& x, double& y, - WallClock timestamp = current_time() - ) const; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - struct Sample{ - WallClock timestamp; - int distance; - double x; - double y; - }; - -private: - // Logger& m_logger; - - mutable SpinLock m_lock; - FlagDetector m_flags; - WhiteObjectWatcher m_watcher; - - std::deque m_history; -}; - - - -} -} -} -#endif +/* Flag Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_FlagTracker_H +#define PokemonAutomation_PokemonLA_FlagTracker_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "PokemonLA_WhiteObjectDetector.h" +#include "PokemonLA_FlagDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class FlagTracker : public VisualInferenceCallback{ +public: + FlagTracker(Logger& logger, VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + bool get( + double& distance, double& x, double& y, + WallClock timestamp = current_time() + ) const; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + struct Sample{ + WallClock timestamp; + int distance; + double x; + double y; + }; + +private: + // Logger& m_logger; + + mutable SpinLock m_lock; + FlagDetector m_flags; + WhiteObjectWatcher m_watcher; + + std::deque m_history; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.cpp index ac72a3f917..e536f22828 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.cpp @@ -1,215 +1,215 @@ -/* MMO Question Marks Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonLA_MMOQuestionMarkDetector.h" -#include "PokemonLA/PokemonLA_Locations.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels::Waterfill; - -namespace{ - -// Match the dark blue background of the question mark -class MMOQuestionMarkBackgroundMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - MMOQuestionMarkBackgroundMatcher(); - static const MMOQuestionMarkBackgroundMatcher& instance(); -}; - -MMOQuestionMarkBackgroundMatcher::MMOQuestionMarkBackgroundMatcher() - : WaterfillTemplateMatcher( - "PokemonLA/MMOQuestionMark-Template.png", - Color(0, 20, 40), Color(60, 90, 130), 200 - ) -{ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; -} - -const MMOQuestionMarkBackgroundMatcher& MMOQuestionMarkBackgroundMatcher::instance(){ - static MMOQuestionMarkBackgroundMatcher matcher; - return matcher; -} - - -// Match the main curve of the question mark -class MMOQuestionMarkCurveMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - MMOQuestionMarkCurveMatcher(); - static const MMOQuestionMarkCurveMatcher& instance(); -}; - -MMOQuestionMarkCurveMatcher::MMOQuestionMarkCurveMatcher() - : WaterfillTemplateMatcher( - "PokemonLA/MMOQuestionMark-Template.png", - Color(0xff808080), Color(0xffffffff), 200 - ) -{ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; -} - -const MMOQuestionMarkCurveMatcher& MMOQuestionMarkCurveMatcher::instance(){ - static MMOQuestionMarkCurveMatcher matcher; - return matcher; -} - - - -// The boxes that cover the locations on the Hisui map that MMO question marks will appear. -const std::array hisui_map_boxes{{ - {0.362, 0.670, 0.045, 0.075}, - {0.683, 0.555, 0.039, 0.076}, - {0.828, 0.372, 0.042, 0.082}, - {0.485, 0.440, 0.044, 0.080}, - {0.393, 0.144, 0.050, 0.084} -}}; - - -bool detect_MMO_question_mark(const PokemonAutomation::ImageViewRGB32 &frame, const ImageFloatBox& box){ - auto image = extract_box_reference(frame, box); - - const double screen_rel_size = (frame.height() / 1080.0); - const double rel_scale = screen_rel_size * screen_rel_size; - - const size_t min_bg_size = 1300; - const size_t max_bg_size = 1600; - - auto scale = [&](size_t size) -> size_t{ - return size_t(size * rel_scale); - }; - - bool detected = match_template_by_waterfill( - image, - MMOQuestionMarkBackgroundMatcher::instance(), - { - {combine_rgb(0, 0, 0), combine_rgb(127, 127, 127)}, - {combine_rgb(0, 10, 30), combine_rgb(60, 90, 130)}, - }, - {scale(min_bg_size), scale(max_bg_size)}, - 90, - [](WaterfillObject&) { return true; } - ); - -// cout << "detected = " << detected << endl; - - if (detected){ - const size_t min_curve_size = 250; - const size_t max_curve_size = 450; - detected = match_template_by_waterfill( - image, MMOQuestionMarkCurveMatcher::instance(), - {{combine_rgb(180, 180, 180), combine_rgb(255, 255, 255)}}, - {scale(min_curve_size), scale(max_curve_size)}, 100, - [](WaterfillObject&) { return true; } - ); - } - - return detected; -} - -} // anonymous namespace - - -MMOQuestionMarkDetector::MMOQuestionMarkDetector(Logger& logger) - : m_logger(logger) -{} - - -void MMOQuestionMarkDetector::make_overlays(VideoOverlaySet& items) const{ - for(size_t i = 0; i < hisui_map_boxes.size(); i++){ - items.add(COLOR_RED, hisui_map_boxes[i]); - } -} - -std::array MMOQuestionMarkDetector::detect_MMO_on_hisui_map(const ImageViewRGB32& frame){ - std::array detected{false}; - for(size_t i = 0; i < hisui_map_boxes.size(); i++){ - detected[i] = detect_MMO_question_mark(frame, hisui_map_boxes[i]); - } - - if (std::find(detected.begin(), detected.end(), true) != detected.end()){ - std::ostringstream os; - os << "Detected MMO question mark on region "; - for(size_t i = 0; i < detected.size(); i++){ - if (detected[i]){ - os << WILD_REGION_SHORT_NAMES[i] << ", "; - } - } - m_logger.log(os.str(), COLOR_PURPLE); - } - - return detected; -} - -std::vector MMOQuestionMarkDetector::detect_MMOs_on_region_map(const ImageViewRGB32& frame){ - ImageFloatBox map_view{0.261, 0.060, 0.481, 0.842}; - size_t map_min_x = (size_t)(frame.width() * map_view.x + 0.5); - size_t map_min_y = (size_t)(frame.height() * map_view.y + 0.5); - size_t map_width = (size_t)(frame.width() * map_view.width + 0.5); - size_t map_height = (size_t)(frame.height() * map_view.height + 0.5); - ImageViewRGB32 map_image(frame.sub_image(map_min_x, map_min_y, map_width, map_height)); - - std::vector results; - - const double screen_rel_size = (frame.height() / 1080.0); - const double rel_scale = screen_rel_size * screen_rel_size; - - const size_t min_bg_size = 1300; - const size_t max_bg_size = 1800; - - auto scale = [&](size_t size) -> size_t{ - return size_t(size * rel_scale); - }; - - match_template_by_waterfill( - map_image, MMOQuestionMarkBackgroundMatcher::instance(), - {{combine_rgb(0, 5, 30), combine_rgb(100, 130, 130)}}, - {scale(min_bg_size), scale(max_bg_size)}, 110, - [&](WaterfillObject& object){ - size_t min_x = object.min_x + map_min_x; - size_t min_y = object.min_y + map_min_y; - size_t max_x = object.max_x + map_min_x; - size_t max_y = object.max_y + map_min_y; - results.emplace_back(min_x, min_y, max_x, max_y); - return false; - } - ); - - return results; -} - - - - -void add_hisui_MMO_detection_to_overlay(const std::array& detection_result, VideoOverlaySet& items){ - for(size_t i = 0; i < hisui_map_boxes.size(); i++){ - if (detection_result[i]){ - items.add(COLOR_CYAN, hisui_map_boxes[i]); - } - } -} - - - -} -} -} +/* MMO Question Marks Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonLA_MMOQuestionMarkDetector.h" +#include "PokemonLA/PokemonLA_Locations.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels::Waterfill; + +namespace{ + +// Match the dark blue background of the question mark +class MMOQuestionMarkBackgroundMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + MMOQuestionMarkBackgroundMatcher(); + static const MMOQuestionMarkBackgroundMatcher& instance(); +}; + +MMOQuestionMarkBackgroundMatcher::MMOQuestionMarkBackgroundMatcher() + : WaterfillTemplateMatcher( + "PokemonLA/MMOQuestionMark-Template.png", + Color(0, 20, 40), Color(60, 90, 130), 200 + ) +{ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; +} + +const MMOQuestionMarkBackgroundMatcher& MMOQuestionMarkBackgroundMatcher::instance(){ + static MMOQuestionMarkBackgroundMatcher matcher; + return matcher; +} + + +// Match the main curve of the question mark +class MMOQuestionMarkCurveMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + MMOQuestionMarkCurveMatcher(); + static const MMOQuestionMarkCurveMatcher& instance(); +}; + +MMOQuestionMarkCurveMatcher::MMOQuestionMarkCurveMatcher() + : WaterfillTemplateMatcher( + "PokemonLA/MMOQuestionMark-Template.png", + Color(0xff808080), Color(0xffffffff), 200 + ) +{ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; +} + +const MMOQuestionMarkCurveMatcher& MMOQuestionMarkCurveMatcher::instance(){ + static MMOQuestionMarkCurveMatcher matcher; + return matcher; +} + + + +// The boxes that cover the locations on the Hisui map that MMO question marks will appear. +const std::array hisui_map_boxes{{ + {0.362, 0.670, 0.045, 0.075}, + {0.683, 0.555, 0.039, 0.076}, + {0.828, 0.372, 0.042, 0.082}, + {0.485, 0.440, 0.044, 0.080}, + {0.393, 0.144, 0.050, 0.084} +}}; + + +bool detect_MMO_question_mark(const PokemonAutomation::ImageViewRGB32 &frame, const ImageFloatBox& box){ + auto image = extract_box_reference(frame, box); + + const double screen_rel_size = (frame.height() / 1080.0); + const double rel_scale = screen_rel_size * screen_rel_size; + + const size_t min_bg_size = 1300; + const size_t max_bg_size = 1600; + + auto scale = [&](size_t size) -> size_t{ + return size_t(size * rel_scale); + }; + + bool detected = match_template_by_waterfill( + image, + MMOQuestionMarkBackgroundMatcher::instance(), + { + {combine_rgb(0, 0, 0), combine_rgb(127, 127, 127)}, + {combine_rgb(0, 10, 30), combine_rgb(60, 90, 130)}, + }, + {scale(min_bg_size), scale(max_bg_size)}, + 90, + [](WaterfillObject&) { return true; } + ); + +// cout << "detected = " << detected << endl; + + if (detected){ + const size_t min_curve_size = 250; + const size_t max_curve_size = 450; + detected = match_template_by_waterfill( + image, MMOQuestionMarkCurveMatcher::instance(), + {{combine_rgb(180, 180, 180), combine_rgb(255, 255, 255)}}, + {scale(min_curve_size), scale(max_curve_size)}, 100, + [](WaterfillObject&) { return true; } + ); + } + + return detected; +} + +} // anonymous namespace + + +MMOQuestionMarkDetector::MMOQuestionMarkDetector(Logger& logger) + : m_logger(logger) +{} + + +void MMOQuestionMarkDetector::make_overlays(VideoOverlaySet& items) const{ + for(size_t i = 0; i < hisui_map_boxes.size(); i++){ + items.add(COLOR_RED, hisui_map_boxes[i]); + } +} + +std::array MMOQuestionMarkDetector::detect_MMO_on_hisui_map(const ImageViewRGB32& frame){ + std::array detected{false}; + for(size_t i = 0; i < hisui_map_boxes.size(); i++){ + detected[i] = detect_MMO_question_mark(frame, hisui_map_boxes[i]); + } + + if (std::find(detected.begin(), detected.end(), true) != detected.end()){ + std::ostringstream os; + os << "Detected MMO question mark on region "; + for(size_t i = 0; i < detected.size(); i++){ + if (detected[i]){ + os << WILD_REGION_SHORT_NAMES[i] << ", "; + } + } + m_logger.log(os.str(), COLOR_PURPLE); + } + + return detected; +} + +std::vector MMOQuestionMarkDetector::detect_MMOs_on_region_map(const ImageViewRGB32& frame){ + ImageFloatBox map_view{0.261, 0.060, 0.481, 0.842}; + size_t map_min_x = (size_t)(frame.width() * map_view.x + 0.5); + size_t map_min_y = (size_t)(frame.height() * map_view.y + 0.5); + size_t map_width = (size_t)(frame.width() * map_view.width + 0.5); + size_t map_height = (size_t)(frame.height() * map_view.height + 0.5); + ImageViewRGB32 map_image(frame.sub_image(map_min_x, map_min_y, map_width, map_height)); + + std::vector results; + + const double screen_rel_size = (frame.height() / 1080.0); + const double rel_scale = screen_rel_size * screen_rel_size; + + const size_t min_bg_size = 1300; + const size_t max_bg_size = 1800; + + auto scale = [&](size_t size) -> size_t{ + return size_t(size * rel_scale); + }; + + match_template_by_waterfill( + map_image, MMOQuestionMarkBackgroundMatcher::instance(), + {{combine_rgb(0, 5, 30), combine_rgb(100, 130, 130)}}, + {scale(min_bg_size), scale(max_bg_size)}, 110, + [&](WaterfillObject& object){ + size_t min_x = object.min_x + map_min_x; + size_t min_y = object.min_y + map_min_y; + size_t max_x = object.max_x + map_min_x; + size_t max_y = object.max_y + map_min_y; + results.emplace_back(min_x, min_y, max_x, max_y); + return false; + } + ); + + return results; +} + + + + +void add_hisui_MMO_detection_to_overlay(const std::array& detection_result, VideoOverlaySet& items){ + for(size_t i = 0; i < hisui_map_boxes.size(); i++){ + if (detection_result[i]){ + items.add(COLOR_CYAN, hisui_map_boxes[i]); + } + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h index a6315e1122..d5bcf563a6 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h @@ -1,51 +1,51 @@ -/* MMO Question Mark Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect MMO question mark symbol. - */ - -#ifndef PokemonAutomation_PokemonLA_MMOQuestionMarkDetector_H -#define PokemonAutomation_PokemonLA_MMOQuestionMarkDetector_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; - - -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class MMOQuestionMarkDetector{ -public: - MMOQuestionMarkDetector(Logger& logger); - - void make_overlays(VideoOverlaySet& items) const; - - // Detect the MMO question marks on the Hisui map when you leave village. - // Return an array of bool, each bool is whether MMO appears on one of the - // wild region. The order of the bool is the same order as the game progession: - // Fieldlands, Mirelands, Coastlands, Highlands, Icelands. - std::array detect_MMO_on_hisui_map(const ImageViewRGB32& frame); - - std::vector detect_MMOs_on_region_map(const ImageViewRGB32& frame); - -private: - Logger& m_logger; -}; - -// Show output of `MMOQuestionMarkDetector::detect_MMO_on_hisui_map()` to video overlay. -void add_hisui_MMO_detection_to_overlay(const std::array& detection_result, VideoOverlaySet& items); - - -} -} -} -#endif +/* MMO Question Mark Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect MMO question mark symbol. + */ + +#ifndef PokemonAutomation_PokemonLA_MMOQuestionMarkDetector_H +#define PokemonAutomation_PokemonLA_MMOQuestionMarkDetector_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; + + +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class MMOQuestionMarkDetector{ +public: + MMOQuestionMarkDetector(Logger& logger); + + void make_overlays(VideoOverlaySet& items) const; + + // Detect the MMO question marks on the Hisui map when you leave village. + // Return an array of bool, each bool is whether MMO appears on one of the + // wild region. The order of the bool is the same order as the game progession: + // Fieldlands, Mirelands, Coastlands, Highlands, Icelands. + std::array detect_MMO_on_hisui_map(const ImageViewRGB32& frame); + + std::vector detect_MMOs_on_region_map(const ImageViewRGB32& frame); + +private: + Logger& m_logger; +}; + +// Show output of `MMOQuestionMarkDetector::detect_MMO_on_hisui_map()` to video overlay. +void add_hisui_MMO_detection_to_overlay(const std::array& detection_result, VideoOverlaySet& items); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.cpp index ddcfa54a2a..d42f2d22bb 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.cpp @@ -1,80 +1,80 @@ -/* Quest Mark Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "PokemonLA_QuestMarkDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - - -class QuestMarkMatcher : public ImageMatch::SubObjectTemplateMatcher{ -public: - QuestMarkMatcher() - : SubObjectTemplateMatcher("PokemonLA/QuestMark-Template1.png", 100) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), - 128, 255, - 128, 255, - 128, 255 - ); - std::vector objects = find_objects_inplace(matrix, 100); - - // Get largest white object. - size_t area = 0; - size_t index = 0; - for (size_t c = 0; c < objects.size(); c++){ - if (area < objects[c].area){ - area = objects[c].area; - index = c; - } - } - - set_subobject(objects[index]); - } - - static const QuestMarkMatcher& instance(){ - static QuestMarkMatcher matcher; - return matcher; - } -}; - - - -QuestMarkDetector::QuestMarkDetector() - : WhiteObjectDetector( - COLOR_CYAN, - { -// Color(0xff808080), - Color(0xff909090), -// Color(0xffa0a0a0), -// Color(0xffb0b0b0), - } - ) -{} -void QuestMarkDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ - ImagePixelBox object_box; - if (QuestMarkMatcher::instance().matches(object_box, image, object)){ - m_detections.emplace_back(object_box); - } - merge_heavily_overlapping(); -} - - - - - -} -} -} +/* Quest Mark Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "PokemonLA_QuestMarkDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + + +class QuestMarkMatcher : public ImageMatch::SubObjectTemplateMatcher{ +public: + QuestMarkMatcher() + : SubObjectTemplateMatcher("PokemonLA/QuestMark-Template1.png", 100) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), + 128, 255, + 128, 255, + 128, 255 + ); + std::vector objects = find_objects_inplace(matrix, 100); + + // Get largest white object. + size_t area = 0; + size_t index = 0; + for (size_t c = 0; c < objects.size(); c++){ + if (area < objects[c].area){ + area = objects[c].area; + index = c; + } + } + + set_subobject(objects[index]); + } + + static const QuestMarkMatcher& instance(){ + static QuestMarkMatcher matcher; + return matcher; + } +}; + + + +QuestMarkDetector::QuestMarkDetector() + : WhiteObjectDetector( + COLOR_CYAN, + { +// Color(0xff808080), + Color(0xff909090), +// Color(0xffa0a0a0), +// Color(0xffb0b0b0), + } + ) +{} +void QuestMarkDetector::process_object(const ImageViewRGB32& image, const WaterfillObject& object){ + ImagePixelBox object_box; + if (QuestMarkMatcher::instance().matches(object_box, image, object)){ + m_detections.emplace_back(object_box); + } + merge_heavily_overlapping(); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h index 2301f3f6af..e7b0a68e2f 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h @@ -1,29 +1,29 @@ -/* Quest Mark Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_QuestMarkDetector_H -#define PokemonAutomation_PokemonLA_QuestMarkDetector_H - -#include -#include "PokemonLA_WhiteObjectDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class QuestMarkDetector : public WhiteObjectDetector{ -public: - QuestMarkDetector(); - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; -}; - - - -} -} -} -#endif +/* Quest Mark Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_QuestMarkDetector_H +#define PokemonAutomation_PokemonLA_QuestMarkDetector_H + +#include +#include "PokemonLA_WhiteObjectDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class QuestMarkDetector : public WhiteObjectDetector{ +public: + QuestMarkDetector(); + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.cpp index f79a84250c..b4a70623cb 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.cpp @@ -1,128 +1,128 @@ -/* Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "PokemonLA_ShinySymbolDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const ImageFloatBox SHINY_SYMBOL_BOX_BOTTOM(0.32, 0.87, 0.03, 0.04); - - - -class ShinySymbolDetector : public ImageMatch::SubObjectTemplateMatcher{ -public: - ShinySymbolDetector() - : SubObjectTemplateMatcher("PokemonLA/ShinySymbol-Template1.png", COLOR_BLACK, 100) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), - 128, 255, - 128, 255, - 128, 255 - ); - std::vector objects = find_objects_inplace(matrix, 20); - if (objects.size() != 2){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find exactly 2 objects in resource.", - m_path - ); - } - size_t index = 0; - if (objects[0].area < objects[1].area){ - index = 1; - } - set_subobject(objects[index]); -// cout << m_feature_box.x << ", " -// << m_feature_box.y << ", " -// << m_feature_box.width << ", " -// << m_feature_box.height << endl; - } - - static const ShinySymbolDetector& instance(){ - static ShinySymbolDetector matcher; - return matcher; - } -}; - - - -std::vector find_shiny_symbols(const ImageViewRGB32& image){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - image, - 128, 255, - 128, 255, - 128, 255 - ); - std::vector ret; - { - PackedBinaryMatrix copy = matrix.copy(); - auto session = make_WaterfillSession(copy); - auto finder = session->make_iterator(20); - WaterfillObject object; - while (finder->find_next(object, false)){ - ImagePixelBox object_box; - if (ShinySymbolDetector::instance().matches_with_background_replace(object_box, image, matrix, object)){ - ret.emplace_back(object_box); - } - } - } -#if 0 - cout << "objects = " << objects.size() << endl; - static int c = 0; - for (const auto& object : objects){ - image.copy( - object.min_x, object.min_y, object.width(), object.height() - ).save("test-" + std::to_string(c++) + ".png"); - } -#endif - return ret; -} - - - -ShinySymbolWatcher::ShinySymbolWatcher(VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("ShinySymbolWatcher") - , m_box(box) - , m_overlays(overlay) -{} -void ShinySymbolWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool ShinySymbolWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_matches = find_shiny_symbols(extract_box_reference(frame, m_box)); - m_overlays.clear(); - for (const ImagePixelBox& hit : m_matches){ - ImageFloatBox box = translate_to_parent(frame, m_box, hit); - m_overlays.add(COLOR_CYAN, box); - } - return false; -} - - -bool ShinySymbolWaiter::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ShinySymbolWatcher::process_frame(frame, timestamp); - return !matches().empty(); -} - - - - - -} -} -} +/* Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "PokemonLA_ShinySymbolDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const ImageFloatBox SHINY_SYMBOL_BOX_BOTTOM(0.32, 0.87, 0.03, 0.04); + + + +class ShinySymbolDetector : public ImageMatch::SubObjectTemplateMatcher{ +public: + ShinySymbolDetector() + : SubObjectTemplateMatcher("PokemonLA/ShinySymbol-Template1.png", COLOR_BLACK, 100) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), + 128, 255, + 128, 255, + 128, 255 + ); + std::vector objects = find_objects_inplace(matrix, 20); + if (objects.size() != 2){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find exactly 2 objects in resource.", + m_path + ); + } + size_t index = 0; + if (objects[0].area < objects[1].area){ + index = 1; + } + set_subobject(objects[index]); +// cout << m_feature_box.x << ", " +// << m_feature_box.y << ", " +// << m_feature_box.width << ", " +// << m_feature_box.height << endl; + } + + static const ShinySymbolDetector& instance(){ + static ShinySymbolDetector matcher; + return matcher; + } +}; + + + +std::vector find_shiny_symbols(const ImageViewRGB32& image){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + image, + 128, 255, + 128, 255, + 128, 255 + ); + std::vector ret; + { + PackedBinaryMatrix copy = matrix.copy(); + auto session = make_WaterfillSession(copy); + auto finder = session->make_iterator(20); + WaterfillObject object; + while (finder->find_next(object, false)){ + ImagePixelBox object_box; + if (ShinySymbolDetector::instance().matches_with_background_replace(object_box, image, matrix, object)){ + ret.emplace_back(object_box); + } + } + } +#if 0 + cout << "objects = " << objects.size() << endl; + static int c = 0; + for (const auto& object : objects){ + image.copy( + object.min_x, object.min_y, object.width(), object.height() + ).save("test-" + std::to_string(c++) + ".png"); + } +#endif + return ret; +} + + + +ShinySymbolWatcher::ShinySymbolWatcher(VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("ShinySymbolWatcher") + , m_box(box) + , m_overlays(overlay) +{} +void ShinySymbolWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool ShinySymbolWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_matches = find_shiny_symbols(extract_box_reference(frame, m_box)); + m_overlays.clear(); + for (const ImagePixelBox& hit : m_matches){ + ImageFloatBox box = translate_to_parent(frame, m_box, hit); + m_overlays.add(COLOR_CYAN, box); + } + return false; +} + + +bool ShinySymbolWaiter::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ShinySymbolWatcher::process_frame(frame, timestamp); + return !matches().empty(); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h index 537475e644..3d4b606537 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h @@ -1,57 +1,57 @@ -/* Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ShinySymbolDetector_H -#define PokemonAutomation_PokemonLA_ShinySymbolDetector_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -extern const ImageFloatBox SHINY_SYMBOL_BOX_BOTTOM; - - -std::vector find_shiny_symbols(const ImageViewRGB32& image); - - -class ShinySymbolWatcher : public VisualInferenceCallback{ -public: - ShinySymbolWatcher(VideoOverlay& overlay, const ImageFloatBox& box = {0, 0, 1, 1}); - - bool detected() const{ return !m_matches.empty(); } - const std::vector& matches() const{ return m_matches; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_box; - std::vector m_matches; - VideoOverlaySet m_overlays; -}; - -class ShinySymbolWaiter : public ShinySymbolWatcher{ -public: - using ShinySymbolWatcher::ShinySymbolWatcher; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; -}; - - - - -} -} -} -#endif +/* Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ShinySymbolDetector_H +#define PokemonAutomation_PokemonLA_ShinySymbolDetector_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +extern const ImageFloatBox SHINY_SYMBOL_BOX_BOTTOM; + + +std::vector find_shiny_symbols(const ImageViewRGB32& image); + + +class ShinySymbolWatcher : public VisualInferenceCallback{ +public: + ShinySymbolWatcher(VideoOverlay& overlay, const ImageFloatBox& box = {0, 0, 1, 1}); + + bool detected() const{ return !m_matches.empty(); } + const std::vector& matches() const{ return m_matches; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_box; + std::vector m_matches; + VideoOverlaySet m_overlays; +}; + +class ShinySymbolWaiter : public ShinySymbolWatcher{ +public: + using ShinySymbolWatcher::ShinySymbolWatcher; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.cpp index 739cd7def6..c1931d228d 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.cpp @@ -1,158 +1,158 @@ -/* White Object Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonLA_WhiteObjectDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels::Waterfill; - - - -void find_overworld_white_objects( - const std::vector>& detectors, - const ImageViewRGB32& image -){ - std::set threshold_set; - for (const auto& item : detectors){ - const std::set& thresholds = item.first.thresholds(); - threshold_set.insert(thresholds.begin(), thresholds.end()); - } - -// FixedLimitVector filters(threshold_set.size()); -// for (Color filter : threshold_set){ -// filters.emplace_back(image.width(), image.height(), (uint32_t)filter, 0xffffffff); -// } -// compress_rgb32_to_binary_range(image, filters.data(), filters.size()); - -// static int count = 0; - { - std::vector> filters; - for (Color filter : threshold_set){ - filters.emplace_back((uint32_t)filter, 0xffffffff); - } - std::vector matrix = compress_rgb32_to_binary_range(image, filters); - -#if 1 - std::unique_ptr session = make_WaterfillSession(); - for (size_t c = 0; c < filters.size(); c++){ - -// cout << "filter[" << c << "] = " << filters[c].first << endl; -// cout << matrix[c].width() << " x " << matrix[c].height() << endl; -// cout << matrix[c].dump() << endl; - session->set_source(matrix[c]); - auto finder = session->make_iterator(50); - WaterfillObject object; - while (finder->find_next(object, false)){ -// cout << object.area << endl; -// cout << matrix[c].submatrix(object.min_x, object.min_y, object.width(), object.height()).dump() << endl; -// extract_box_reference(image, object).save("test-" + std::to_string(count++) + "-" + std::to_string(c) + ".png"); - for (const auto& detector : detectors){ - const std::set& thresholds = detector.first.thresholds(); - if (thresholds.find((Color)filters[c].first) != thresholds.end()){ - detector.first.process_object(image, object); - } - } - } - } -#endif - } - - for (const auto& detector : detectors){ - detector.first.finish(image); - } -} - - -void WhiteObjectDetector::merge_heavily_overlapping(double tolerance){ - std::multimap boxes; - for (const ImagePixelBox& box : m_detections){ - boxes.emplace(box.area(), box); - } - m_detections.clear(); -// cout << "boxes.size() = " << boxes.size() << endl; - - double ratio = 1.0 + tolerance; - - while (!boxes.empty()){ - auto current = boxes.begin(); - size_t limit = (size_t)(current->first * ratio); - auto candidate = current; - ++candidate; - while (candidate != boxes.end()){ - if (candidate->first > limit){ - ++candidate; - continue; - } - size_t overlap = current->second.overlapping_area(candidate->second); - if ((double)overlap * ratio > current->first){ - current->second.merge_with(candidate->second); - candidate = boxes.erase(candidate); - }else{ - ++candidate; - } - } - m_detections.emplace_back(current->second); - current = boxes.erase(current); - } -// cout << "m_detections.size() = " << m_detections.size() << endl; -} - - - - -WhiteObjectWatcher::WhiteObjectWatcher( - VideoOverlay& overlay, - const ImageFloatBox& box, - std::vector> detectors -) - : VisualInferenceCallback("WhiteObjectWatcher") - , m_box(box) - , m_overlays(overlay) - , m_detectors(detectors) -{} - -void WhiteObjectWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} -bool WhiteObjectWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - for (auto& detector : m_detectors){ - detector.first.clear(); - } - - find_overworld_white_objects(m_detectors, extract_box_reference(frame, m_box)); - m_overlays.clear(); - - for (auto& detector : m_detectors){ - for (const ImagePixelBox& obj : detector.first.detections()){ - ImageFloatBox box = translate_to_parent(frame, m_box, obj); - m_overlays.add(detector.first.color(), box); - } - } - for (auto& detector : m_detectors){ - if (detector.second && !detector.first.detections().empty()){ - return true; - } - } - return false; -} - - - - - -} -} -} +/* White Object Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonLA_WhiteObjectDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels::Waterfill; + + + +void find_overworld_white_objects( + const std::vector>& detectors, + const ImageViewRGB32& image +){ + std::set threshold_set; + for (const auto& item : detectors){ + const std::set& thresholds = item.first.thresholds(); + threshold_set.insert(thresholds.begin(), thresholds.end()); + } + +// FixedLimitVector filters(threshold_set.size()); +// for (Color filter : threshold_set){ +// filters.emplace_back(image.width(), image.height(), (uint32_t)filter, 0xffffffff); +// } +// compress_rgb32_to_binary_range(image, filters.data(), filters.size()); + +// static int count = 0; + { + std::vector> filters; + for (Color filter : threshold_set){ + filters.emplace_back((uint32_t)filter, 0xffffffff); + } + std::vector matrix = compress_rgb32_to_binary_range(image, filters); + +#if 1 + std::unique_ptr session = make_WaterfillSession(); + for (size_t c = 0; c < filters.size(); c++){ + +// cout << "filter[" << c << "] = " << filters[c].first << endl; +// cout << matrix[c].width() << " x " << matrix[c].height() << endl; +// cout << matrix[c].dump() << endl; + session->set_source(matrix[c]); + auto finder = session->make_iterator(50); + WaterfillObject object; + while (finder->find_next(object, false)){ +// cout << object.area << endl; +// cout << matrix[c].submatrix(object.min_x, object.min_y, object.width(), object.height()).dump() << endl; +// extract_box_reference(image, object).save("test-" + std::to_string(count++) + "-" + std::to_string(c) + ".png"); + for (const auto& detector : detectors){ + const std::set& thresholds = detector.first.thresholds(); + if (thresholds.find((Color)filters[c].first) != thresholds.end()){ + detector.first.process_object(image, object); + } + } + } + } +#endif + } + + for (const auto& detector : detectors){ + detector.first.finish(image); + } +} + + +void WhiteObjectDetector::merge_heavily_overlapping(double tolerance){ + std::multimap boxes; + for (const ImagePixelBox& box : m_detections){ + boxes.emplace(box.area(), box); + } + m_detections.clear(); +// cout << "boxes.size() = " << boxes.size() << endl; + + double ratio = 1.0 + tolerance; + + while (!boxes.empty()){ + auto current = boxes.begin(); + size_t limit = (size_t)(current->first * ratio); + auto candidate = current; + ++candidate; + while (candidate != boxes.end()){ + if (candidate->first > limit){ + ++candidate; + continue; + } + size_t overlap = current->second.overlapping_area(candidate->second); + if ((double)overlap * ratio > current->first){ + current->second.merge_with(candidate->second); + candidate = boxes.erase(candidate); + }else{ + ++candidate; + } + } + m_detections.emplace_back(current->second); + current = boxes.erase(current); + } +// cout << "m_detections.size() = " << m_detections.size() << endl; +} + + + + +WhiteObjectWatcher::WhiteObjectWatcher( + VideoOverlay& overlay, + const ImageFloatBox& box, + std::vector> detectors +) + : VisualInferenceCallback("WhiteObjectWatcher") + , m_box(box) + , m_overlays(overlay) + , m_detectors(detectors) +{} + +void WhiteObjectWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} +bool WhiteObjectWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + for (auto& detector : m_detectors){ + detector.first.clear(); + } + + find_overworld_white_objects(m_detectors, extract_box_reference(frame, m_box)); + m_overlays.clear(); + + for (auto& detector : m_detectors){ + for (const ImagePixelBox& obj : detector.first.detections()){ + ImageFloatBox box = translate_to_parent(frame, m_box, obj); + m_overlays.add(detector.first.color(), box); + } + } + for (auto& detector : m_detectors){ + if (detector.second && !detector.first.detections().empty()){ + return true; + } + } + return false; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h index aa19a31a83..a7948bb070 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Objects/PokemonLA_WhiteObjectDetector.h @@ -1,102 +1,102 @@ -/* White Object Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_WhiteObjectDetector_H -#define PokemonAutomation_PokemonLA_WhiteObjectDetector_H - -#include -#include -#include "Common/Compiler.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - class WaterfillObject; -} -} -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class WhiteObjectDetector{ -protected: - using WaterfillObject = Kernels::Waterfill::WaterfillObject; - -public: - virtual ~WhiteObjectDetector() = default; - WhiteObjectDetector(const WhiteObjectDetector&) = delete; - void operator=(const WhiteObjectDetector&) = delete; - - // thresholds: thresholds for various filters. Each filter has a different threshold - // to filter out candidate objects on an image. The thresholds specified here are the - // min color thresholds. The max color thresholds for all filters are always 0xffffffff. - WhiteObjectDetector(Color inference_box_color, std::set thresholds) - : m_box_color(inference_box_color) - , m_thresholds(std::move(thresholds)) - {} - - Color color() const{ return m_box_color; } - const std::set& thresholds() const{ return m_thresholds; } - - const std::vector& detections() const{ return m_detections; } - void clear(){ m_detections.clear(); } - - virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) = 0; - virtual void finish(const ImageViewRGB32& image){} - -protected: - void merge_heavily_overlapping(double tolerance = 0.2); - -protected: - Color m_box_color; - std::set m_thresholds; - std::vector m_detections; -}; - - - - - - -void find_overworld_white_objects( - const std::vector>& detectors, - const ImageViewRGB32& screen -); - -class WhiteObjectWatcher : public VisualInferenceCallback{ -public: - WhiteObjectWatcher( - VideoOverlay& overlay, - const ImageFloatBox& box, - std::vector> detectors - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - -private: - ImageFloatBox m_box; - VideoOverlaySet m_overlays; - - std::vector> m_detectors; -}; - - - - - - -} -} -} -#endif +/* White Object Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_WhiteObjectDetector_H +#define PokemonAutomation_PokemonLA_WhiteObjectDetector_H + +#include +#include +#include "Common/Compiler.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + class WaterfillObject; +} +} +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class WhiteObjectDetector{ +protected: + using WaterfillObject = Kernels::Waterfill::WaterfillObject; + +public: + virtual ~WhiteObjectDetector() = default; + WhiteObjectDetector(const WhiteObjectDetector&) = delete; + void operator=(const WhiteObjectDetector&) = delete; + + // thresholds: thresholds for various filters. Each filter has a different threshold + // to filter out candidate objects on an image. The thresholds specified here are the + // min color thresholds. The max color thresholds for all filters are always 0xffffffff. + WhiteObjectDetector(Color inference_box_color, std::set thresholds) + : m_box_color(inference_box_color) + , m_thresholds(std::move(thresholds)) + {} + + Color color() const{ return m_box_color; } + const std::set& thresholds() const{ return m_thresholds; } + + const std::vector& detections() const{ return m_detections; } + void clear(){ m_detections.clear(); } + + virtual void process_object(const ImageViewRGB32& image, const WaterfillObject& object) = 0; + virtual void finish(const ImageViewRGB32& image){} + +protected: + void merge_heavily_overlapping(double tolerance = 0.2); + +protected: + Color m_box_color; + std::set m_thresholds; + std::vector m_detections; +}; + + + + + + +void find_overworld_white_objects( + const std::vector>& detectors, + const ImageViewRGB32& screen +); + +class WhiteObjectWatcher : public VisualInferenceCallback{ +public: + WhiteObjectWatcher( + VideoOverlay& overlay, + const ImageFloatBox& box, + std::vector> detectors + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + +private: + ImageFloatBox m_box; + VideoOverlaySet m_overlays; + + std::vector> m_detectors; +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.cpp index 0359f016ad..76445a58ba 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.cpp @@ -1,388 +1,388 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Time.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "PokemonLA_BerryTreeDetector.h" -#include "PokemonLA/PokemonLA_Locations.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ - -using Kernels::Waterfill::WaterfillObject; -using Kernels::DisjointSet; - -namespace NintendoSwitch{ -namespace PokemonLA{ - - -// Merge boxes that overlap with each other, meaning ImagePixelBox::overlap_with() return true. -// return a vector of boxes that are merged versions of the input boxes. -// Note this function will order the input vector. -// Note the returned boxes may still overlap with each other. This is because the algorithm -// essentially find the connected components of the input boxes and return the bounding box of each -// connected component. Although any two connected components don't overlap with each other, their -// bounding boxes may still overlap. -std::vector merge_overlapping_boxes(std::vector& boxes){ - // sort boxes according to min_x. If two boxes have same min_x, compare min_y - std::sort(boxes.begin(), boxes.end(), [](const ImagePixelBox& a, const ImagePixelBox& b){ - return a.min_x < b.min_x ? true : (a.min_x == b.min_x ? a.min_y < b.min_y : false); - }); - - DisjointSet disjoint_set(boxes.size()); - - for (size_t i = 0; i < boxes.size(); i++){ - for(size_t j = i + 1; j < boxes.size(); j++){ - // box_j and the ones behind it won't overlap with cur_box. - if (boxes[j].min_x >= boxes[i].max_x){ - // break; - } - - if (boxes[i].overlaps_with(boxes[j])){ - disjoint_set.merge(i, j); - } - } - } - - std::map merged_boxes; - for(size_t i = 0; i < boxes.size(); i++){ - size_t rep_box = disjoint_set.find(i); - auto it = merged_boxes.find(rep_box); - if (it == merged_boxes.end()){ - it = merged_boxes.emplace(rep_box, boxes[rep_box]).first; - } - - if(rep_box != i){ - // merge the child box i with the rep_box - it->second.merge_with(boxes[i]); - } - } - - std::vector output_boxes; - for(const auto& p : merged_boxes){ - output_boxes.push_back(p.second); - } - - return output_boxes; -} - - -bool detect_sphere(const Kernels::Waterfill::WaterfillObject& object, ImageRGB32* image, size_t offset_x, size_t offset_y){ - PackedBinaryMatrix matrix = object.packed_matrix(); - - cout << "Object area in detection sphere: " << object.area << endl; - double threshold = 0.3; - if (object.area >= 900){ - threshold = 0.5; - }else if (object.area >= 100){ - // For area size (assuming square shape) from 10.0 to 30.0, linearly raise - // threshold from 0.3 to 0.5. - threshold = 0.3 + 0.2 * (std::sqrt(object.area) - 10.0) / 20.0; - } - const size_t stop = (size_t)(threshold * object.area); - - PackedBinaryMatrix matrix2 = remove_center_pixels(object, stop).first; - - auto session = Kernels::Waterfill::make_WaterfillSession(matrix2); - auto finder = session->make_iterator(1); - Kernels::Waterfill::WaterfillObject obj; - size_t num_regions = 0; - const bool keep_object = (image != nullptr); - while (finder->find_next(obj, keep_object)){ - num_regions++; - - if (image){ - Color color(0, 0, 255); - if (num_regions == 1){ - color = Color(128, 128, 255); - } - // cout << "cut area " << obj.area << endl; - for (size_t x = 0; x < obj.width(); x++){ - for (size_t y = 0; y < obj.height(); y++){ - if (obj.object->get(obj.min_x + x, obj.min_y + y)){ - image->pixel( - (pxint_t)(object.min_x + offset_x + obj.min_x + x), - (pxint_t)(offset_y + object.min_y + obj.min_y + y) - ) = (uint32_t)color; - // cout << "Set color at " << offset_x + object.min_x + obj.min_x + x << ", " << offset_y + object.min_y + obj.min_y + y << endl; - } - } - } - } - } - - std::cout << "num regions " << num_regions << std::endl; - - return num_regions == 1; -} - -namespace{ - -using ColorPair = std::pair; - -// Color of a tree at a certain time/weather -struct TreeColor{ - ColorPair fruit_core; - - ColorPair fruit_full; - - ColorPair leave; - - TreeColor(ColorPair fruit_core, ColorPair fruit_full, ColorPair leave) : fruit_core(fruit_core), fruit_full(fruit_full), leave(leave) {} -}; - -enum class BerryTreeType{ - APRICON, - ORAN, - LEPPA, // fieldlands: blue-leaf leppa - SITRUS // fieldlands: blue-leaf sitrus -}; - -std::map>> all_tree_colors = { - { - MapRegion::FIELDLANDS, - { - { - BerryTreeType::APRICON, - { - // Nightfall color - TreeColor( - ColorPair(Color(110, 65, 35), Color(160, 110, 65)), - ColorPair(Color(60, 45, 10), Color(210, 160, 130)), - ColorPair(Color(0, 20, 0), Color(60, 85, 40)) - ) - } - } - } - } -}; - - - - -std::string to_str(const ImagePixelBox& box){ - std::ostringstream os; - os << "(" << box.min_x << ", " << box.max_x << ", " << box.min_y << ", " << box.max_y << ")"; - return os.str(); -} - - -} // anonymous namespace - - - -BerryTreeDetector::BerryTreeDetector() - : VisualInferenceCallback("BerryTreeDetector") -{} - -void BerryTreeDetector::make_overlays(VideoOverlaySet& items) const{ -} - -// Return true if the inference session should stop. -bool BerryTreeDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - - // First, use the core-color of the berry to find candidate locations: - - // Run waterfill: - // pixels within the color range are marked as 1 in matrices: - PackedBinaryMatrix matrix = compress_rgb32_to_binary_multirange(frame, { - // light color: - {combine_rgb(110, 60, 25), combine_rgb(190, 130, 105)}, - // dark color - {combine_rgb(90, 40, 10), combine_rgb(130, 60, 50)} - // {combine_rgb(70, 30, 0), combine_rgb(130, 80, 100)} - // {combine_rgb(70, 30, 0), combine_rgb(160, 110, 100)} - }); - - ImageRGB32 debug_image = frame.copy(); - - // Create the session and reuse it for each matrix. - std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); - session->set_source(matrix); - - // Create object iterator for this matrix. - const size_t core_color_min_area = frame.width() / 100; - const size_t core_color_max_area = frame.width() / 2; - auto finder = session->make_iterator(core_color_min_area); - Kernels::Waterfill::WaterfillObject object; - - // item area is the lower left of the screen with the current selected item/pokemon. - // We won't do any berry detection on that area as it's covered with item/pokemon sprites. - const size_t item_area_x = size_t(frame.width() * 0.78); - const size_t item_area_y = size_t(frame.height() * 0.752); - const ImagePixelBox character_area( - (pxint_t)(frame.width() * 0.39), (pxint_t)(frame.height() * 0.77), - (pxint_t)(frame.width() * 0.61), (pxint_t)frame.height() - ); - - std::vector berry_candidate_areas; - // Iterate the objects for this matrix. - while (finder->find_next(object, false)){ - // Do something with candidate. (stored in "object") - if (object.area > core_color_max_area){ - continue; - } - - // Skip the item area (lower left of the screen) - if (object.center_of_gravity_x() >= item_area_x && object.center_of_gravity_y() >= item_area_y){ - continue; - } - // Skip if it overlaps with the main character. - if (character_area.is_inside((size_t)object.center_of_gravity_x(), (size_t)object.center_of_gravity_y())){ - continue; - } - - // The size of the core-color area - size_t size = std::max(object.width(), object.height()); - - // Increase the size to cover the full berry and surrounding area: - pxint_t radius = (pxint_t)size; - - ImagePixelBox box; - box.min_x = (pxint_t)object.center_of_gravity_x() - radius; - box.max_x = (pxint_t)object.center_of_gravity_x() + radius; - box.min_y = (pxint_t)object.center_of_gravity_y() - radius; - box.max_y = (pxint_t)object.center_of_gravity_y() + radius; - box.clip(debug_image.width(), debug_image.height()); - - // std::cout << "core berry color " << to_str(box) << std::endl; - // draw_box(debug_image, box, uint32_t(COLOR_GREEN), 1); - - berry_candidate_areas.push_back(box); - } - - berry_candidate_areas = merge_overlapping_boxes(berry_candidate_areas); - - std::vector berry_boxes; - - for(const auto& candidate_box: berry_candidate_areas){ - std::cout << "candidate box " << to_str(candidate_box) << std::endl; - // std::cout << std::endl; - - draw_box(debug_image, candidate_box, uint32_t(COLOR_RED), 1); - - // Waterfill using the full range of berry color: - auto full_color_matrix = compress_rgb32_to_binary_multirange( - extract_box_reference(frame, candidate_box), { - // light color: - {combine_rgb(140, 100, 30), combine_rgb(255, 200, 180)}, - // bright color - // {combine_rgb(70, 30, 0), combine_rgb(130, 80, 100)} - {combine_rgb(70, 30, 0), combine_rgb(160, 110, 100)} - }); - - // Kernels::Waterfill::draw_matrix_on_image(full_color_matrix, combine_rgb(0, 0, 255), debug_image, candidate_box.min_x, candidate_box.min_y); - - session->set_source(full_color_matrix); - const size_t berry_min_area = core_color_min_area * 3; - finder = session->make_iterator(berry_min_area); - - // Find the object at the center of the berry candidate region - const bool keep_object = true; - if (session->find_object_on_bit(object, keep_object, candidate_box.width()/2, candidate_box.height()/2) == false){ - continue; - } - if (object.area > core_color_max_area){ - continue; - } - if (detect_sphere(object, &debug_image, candidate_box.min_x, candidate_box.min_y) == false){ - continue; - } - - ImagePixelBox box; - box.min_x = candidate_box.min_x + (pxint_t)(object.center_of_gravity_x() - object.width()/2); - box.max_x = candidate_box.min_x + (pxint_t)(object.center_of_gravity_x() + object.width()/2); - box.min_y = candidate_box.min_y + (pxint_t)(object.center_of_gravity_y() - object.height()/2); - box.max_y = candidate_box.min_y + (pxint_t)(object.center_of_gravity_y() + object.height()/2); - - std::cout << "full-color region #pixels: " << object.area << " at " << box.center_x() << " " << box.center_y() << std::endl; - - berry_boxes.push_back(box); - } - - // Check leaf color around berries - for(const auto& berry_box : berry_boxes){ - draw_box(debug_image, berry_box, uint32_t(COLOR_GREEN), 1); - - ImagePixelBox enlarged_box; - size_t enlarged_width = berry_box.width() + berry_box.width() / 2; - size_t enlarged_height = berry_box.height() + berry_box.height() / 2; - size_t enlarged_box_size = enlarged_width * enlarged_height; - enlarged_box.min_x = (pxint_t)berry_box.center_x() - (pxint_t)enlarged_width/2; - enlarged_box.max_x = (pxint_t)berry_box.center_x() + (pxint_t)enlarged_width/2; - enlarged_box.min_y = (pxint_t)berry_box.center_y() - (pxint_t)enlarged_height/2; - enlarged_box.max_y = (pxint_t)berry_box.center_y() + (pxint_t)enlarged_height/2; - - size_t potential_leaf_area = enlarged_box_size - berry_box.width() * berry_box.height(); - - auto leaf_matrix = compress_rgb32_to_binary_multirange( - extract_box_reference(frame, enlarged_box), { - // {combine_rgb(0, 0, 0), combine_rgb(60, 85, 50)}, // old values - {combine_rgb(0, 0, 0), combine_rgb(20, 90, 40)}, - {combine_rgb(0, 50, 0), combine_rgb(20, 90, 60)}, - // avoid dark blue color: 9, 36, 60 and (0, 6, 28) - // {combine_rgb(20, 30, 0), combine_rgb(20, 90, 50)}, - } - ); - - // for(int x = 0; x < enlarged_box.width(); x++){ - // for(int y = 0; y < enlarged_box.height(); y++){ - // if (leaf_matrix.get(x, y)){ - // debug_image.setPixelColor(enlarged_box.min_x + x, enlarged_box.min_y + y, QColor(255, 0, 0)); - // } - // } - // } - - session->set_source(leaf_matrix); - finder = session->make_iterator(0); - - size_t num_leaf_bits = 0; - while (finder->find_next(object, false)){ - num_leaf_bits += object.area; - } - - std::cout << "candidate berry at " << berry_box.center_x() << " " << berry_box.center_y() << ", leaf " << num_leaf_bits << "/" << potential_leaf_area << std::endl; - // draw_box(debug_image, enlarged_box, uint32_t(COLOR_CYAN), 2); - // draw_box(debug_image, berry_box, uint32_t(COLOR_BLUE), 2); - if (num_leaf_bits > potential_leaf_area * 2 / 3){ - std::cout << "berry at " << berry_box.center_x() << " " << berry_box.center_y() << ", leaf " << num_leaf_bits << "/" << potential_leaf_area << std::endl; - draw_box(debug_image, berry_box, uint32_t(COLOR_BLUE), 3); - } - } - - - - // for(int x = 0; x < debug_image.width(); x++){ - // for(int y = 0; y < debug_image.height(); y++){ - // if (matrices[0].get(x, y)){ - // debug_image.setPixelColor(x, y, QColor(255, 0, 0)); - // } - // } - // } - std::cout << "Saving inference debug_image" << std::endl; - debug_image.save("./test_berry_tree_output.png"); - - return true; -} - - - -} -} -} +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Time.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "Kernels/Algorithm/Kernels_Algorithm_DisjointSet.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "PokemonLA_BerryTreeDetector.h" +#include "PokemonLA/PokemonLA_Locations.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ + +using Kernels::Waterfill::WaterfillObject; +using Kernels::DisjointSet; + +namespace NintendoSwitch{ +namespace PokemonLA{ + + +// Merge boxes that overlap with each other, meaning ImagePixelBox::overlap_with() return true. +// return a vector of boxes that are merged versions of the input boxes. +// Note this function will order the input vector. +// Note the returned boxes may still overlap with each other. This is because the algorithm +// essentially find the connected components of the input boxes and return the bounding box of each +// connected component. Although any two connected components don't overlap with each other, their +// bounding boxes may still overlap. +std::vector merge_overlapping_boxes(std::vector& boxes){ + // sort boxes according to min_x. If two boxes have same min_x, compare min_y + std::sort(boxes.begin(), boxes.end(), [](const ImagePixelBox& a, const ImagePixelBox& b){ + return a.min_x < b.min_x ? true : (a.min_x == b.min_x ? a.min_y < b.min_y : false); + }); + + DisjointSet disjoint_set(boxes.size()); + + for (size_t i = 0; i < boxes.size(); i++){ + for(size_t j = i + 1; j < boxes.size(); j++){ + // box_j and the ones behind it won't overlap with cur_box. + if (boxes[j].min_x >= boxes[i].max_x){ + // break; + } + + if (boxes[i].overlaps_with(boxes[j])){ + disjoint_set.merge(i, j); + } + } + } + + std::map merged_boxes; + for(size_t i = 0; i < boxes.size(); i++){ + size_t rep_box = disjoint_set.find(i); + auto it = merged_boxes.find(rep_box); + if (it == merged_boxes.end()){ + it = merged_boxes.emplace(rep_box, boxes[rep_box]).first; + } + + if(rep_box != i){ + // merge the child box i with the rep_box + it->second.merge_with(boxes[i]); + } + } + + std::vector output_boxes; + for(const auto& p : merged_boxes){ + output_boxes.push_back(p.second); + } + + return output_boxes; +} + + +bool detect_sphere(const Kernels::Waterfill::WaterfillObject& object, ImageRGB32* image, size_t offset_x, size_t offset_y){ + PackedBinaryMatrix matrix = object.packed_matrix(); + + cout << "Object area in detection sphere: " << object.area << endl; + double threshold = 0.3; + if (object.area >= 900){ + threshold = 0.5; + }else if (object.area >= 100){ + // For area size (assuming square shape) from 10.0 to 30.0, linearly raise + // threshold from 0.3 to 0.5. + threshold = 0.3 + 0.2 * (std::sqrt(object.area) - 10.0) / 20.0; + } + const size_t stop = (size_t)(threshold * object.area); + + PackedBinaryMatrix matrix2 = remove_center_pixels(object, stop).first; + + auto session = Kernels::Waterfill::make_WaterfillSession(matrix2); + auto finder = session->make_iterator(1); + Kernels::Waterfill::WaterfillObject obj; + size_t num_regions = 0; + const bool keep_object = (image != nullptr); + while (finder->find_next(obj, keep_object)){ + num_regions++; + + if (image){ + Color color(0, 0, 255); + if (num_regions == 1){ + color = Color(128, 128, 255); + } + // cout << "cut area " << obj.area << endl; + for (size_t x = 0; x < obj.width(); x++){ + for (size_t y = 0; y < obj.height(); y++){ + if (obj.object->get(obj.min_x + x, obj.min_y + y)){ + image->pixel( + (pxint_t)(object.min_x + offset_x + obj.min_x + x), + (pxint_t)(offset_y + object.min_y + obj.min_y + y) + ) = (uint32_t)color; + // cout << "Set color at " << offset_x + object.min_x + obj.min_x + x << ", " << offset_y + object.min_y + obj.min_y + y << endl; + } + } + } + } + } + + std::cout << "num regions " << num_regions << std::endl; + + return num_regions == 1; +} + +namespace{ + +using ColorPair = std::pair; + +// Color of a tree at a certain time/weather +struct TreeColor{ + ColorPair fruit_core; + + ColorPair fruit_full; + + ColorPair leave; + + TreeColor(ColorPair fruit_core, ColorPair fruit_full, ColorPair leave) : fruit_core(fruit_core), fruit_full(fruit_full), leave(leave) {} +}; + +enum class BerryTreeType{ + APRICON, + ORAN, + LEPPA, // fieldlands: blue-leaf leppa + SITRUS // fieldlands: blue-leaf sitrus +}; + +std::map>> all_tree_colors = { + { + MapRegion::FIELDLANDS, + { + { + BerryTreeType::APRICON, + { + // Nightfall color + TreeColor( + ColorPair(Color(110, 65, 35), Color(160, 110, 65)), + ColorPair(Color(60, 45, 10), Color(210, 160, 130)), + ColorPair(Color(0, 20, 0), Color(60, 85, 40)) + ) + } + } + } + } +}; + + + + +std::string to_str(const ImagePixelBox& box){ + std::ostringstream os; + os << "(" << box.min_x << ", " << box.max_x << ", " << box.min_y << ", " << box.max_y << ")"; + return os.str(); +} + + +} // anonymous namespace + + + +BerryTreeDetector::BerryTreeDetector() + : VisualInferenceCallback("BerryTreeDetector") +{} + +void BerryTreeDetector::make_overlays(VideoOverlaySet& items) const{ +} + +// Return true if the inference session should stop. +bool BerryTreeDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + + // First, use the core-color of the berry to find candidate locations: + + // Run waterfill: + // pixels within the color range are marked as 1 in matrices: + PackedBinaryMatrix matrix = compress_rgb32_to_binary_multirange(frame, { + // light color: + {combine_rgb(110, 60, 25), combine_rgb(190, 130, 105)}, + // dark color + {combine_rgb(90, 40, 10), combine_rgb(130, 60, 50)} + // {combine_rgb(70, 30, 0), combine_rgb(130, 80, 100)} + // {combine_rgb(70, 30, 0), combine_rgb(160, 110, 100)} + }); + + ImageRGB32 debug_image = frame.copy(); + + // Create the session and reuse it for each matrix. + std::unique_ptr session = Kernels::Waterfill::make_WaterfillSession(); + session->set_source(matrix); + + // Create object iterator for this matrix. + const size_t core_color_min_area = frame.width() / 100; + const size_t core_color_max_area = frame.width() / 2; + auto finder = session->make_iterator(core_color_min_area); + Kernels::Waterfill::WaterfillObject object; + + // item area is the lower left of the screen with the current selected item/pokemon. + // We won't do any berry detection on that area as it's covered with item/pokemon sprites. + const size_t item_area_x = size_t(frame.width() * 0.78); + const size_t item_area_y = size_t(frame.height() * 0.752); + const ImagePixelBox character_area( + (pxint_t)(frame.width() * 0.39), (pxint_t)(frame.height() * 0.77), + (pxint_t)(frame.width() * 0.61), (pxint_t)frame.height() + ); + + std::vector berry_candidate_areas; + // Iterate the objects for this matrix. + while (finder->find_next(object, false)){ + // Do something with candidate. (stored in "object") + if (object.area > core_color_max_area){ + continue; + } + + // Skip the item area (lower left of the screen) + if (object.center_of_gravity_x() >= item_area_x && object.center_of_gravity_y() >= item_area_y){ + continue; + } + // Skip if it overlaps with the main character. + if (character_area.is_inside((size_t)object.center_of_gravity_x(), (size_t)object.center_of_gravity_y())){ + continue; + } + + // The size of the core-color area + size_t size = std::max(object.width(), object.height()); + + // Increase the size to cover the full berry and surrounding area: + pxint_t radius = (pxint_t)size; + + ImagePixelBox box; + box.min_x = (pxint_t)object.center_of_gravity_x() - radius; + box.max_x = (pxint_t)object.center_of_gravity_x() + radius; + box.min_y = (pxint_t)object.center_of_gravity_y() - radius; + box.max_y = (pxint_t)object.center_of_gravity_y() + radius; + box.clip(debug_image.width(), debug_image.height()); + + // std::cout << "core berry color " << to_str(box) << std::endl; + // draw_box(debug_image, box, uint32_t(COLOR_GREEN), 1); + + berry_candidate_areas.push_back(box); + } + + berry_candidate_areas = merge_overlapping_boxes(berry_candidate_areas); + + std::vector berry_boxes; + + for(const auto& candidate_box: berry_candidate_areas){ + std::cout << "candidate box " << to_str(candidate_box) << std::endl; + // std::cout << std::endl; + + draw_box(debug_image, candidate_box, uint32_t(COLOR_RED), 1); + + // Waterfill using the full range of berry color: + auto full_color_matrix = compress_rgb32_to_binary_multirange( + extract_box_reference(frame, candidate_box), { + // light color: + {combine_rgb(140, 100, 30), combine_rgb(255, 200, 180)}, + // bright color + // {combine_rgb(70, 30, 0), combine_rgb(130, 80, 100)} + {combine_rgb(70, 30, 0), combine_rgb(160, 110, 100)} + }); + + // Kernels::Waterfill::draw_matrix_on_image(full_color_matrix, combine_rgb(0, 0, 255), debug_image, candidate_box.min_x, candidate_box.min_y); + + session->set_source(full_color_matrix); + const size_t berry_min_area = core_color_min_area * 3; + finder = session->make_iterator(berry_min_area); + + // Find the object at the center of the berry candidate region + const bool keep_object = true; + if (session->find_object_on_bit(object, keep_object, candidate_box.width()/2, candidate_box.height()/2) == false){ + continue; + } + if (object.area > core_color_max_area){ + continue; + } + if (detect_sphere(object, &debug_image, candidate_box.min_x, candidate_box.min_y) == false){ + continue; + } + + ImagePixelBox box; + box.min_x = candidate_box.min_x + (pxint_t)(object.center_of_gravity_x() - object.width()/2); + box.max_x = candidate_box.min_x + (pxint_t)(object.center_of_gravity_x() + object.width()/2); + box.min_y = candidate_box.min_y + (pxint_t)(object.center_of_gravity_y() - object.height()/2); + box.max_y = candidate_box.min_y + (pxint_t)(object.center_of_gravity_y() + object.height()/2); + + std::cout << "full-color region #pixels: " << object.area << " at " << box.center_x() << " " << box.center_y() << std::endl; + + berry_boxes.push_back(box); + } + + // Check leaf color around berries + for(const auto& berry_box : berry_boxes){ + draw_box(debug_image, berry_box, uint32_t(COLOR_GREEN), 1); + + ImagePixelBox enlarged_box; + size_t enlarged_width = berry_box.width() + berry_box.width() / 2; + size_t enlarged_height = berry_box.height() + berry_box.height() / 2; + size_t enlarged_box_size = enlarged_width * enlarged_height; + enlarged_box.min_x = (pxint_t)berry_box.center_x() - (pxint_t)enlarged_width/2; + enlarged_box.max_x = (pxint_t)berry_box.center_x() + (pxint_t)enlarged_width/2; + enlarged_box.min_y = (pxint_t)berry_box.center_y() - (pxint_t)enlarged_height/2; + enlarged_box.max_y = (pxint_t)berry_box.center_y() + (pxint_t)enlarged_height/2; + + size_t potential_leaf_area = enlarged_box_size - berry_box.width() * berry_box.height(); + + auto leaf_matrix = compress_rgb32_to_binary_multirange( + extract_box_reference(frame, enlarged_box), { + // {combine_rgb(0, 0, 0), combine_rgb(60, 85, 50)}, // old values + {combine_rgb(0, 0, 0), combine_rgb(20, 90, 40)}, + {combine_rgb(0, 50, 0), combine_rgb(20, 90, 60)}, + // avoid dark blue color: 9, 36, 60 and (0, 6, 28) + // {combine_rgb(20, 30, 0), combine_rgb(20, 90, 50)}, + } + ); + + // for(int x = 0; x < enlarged_box.width(); x++){ + // for(int y = 0; y < enlarged_box.height(); y++){ + // if (leaf_matrix.get(x, y)){ + // debug_image.setPixelColor(enlarged_box.min_x + x, enlarged_box.min_y + y, QColor(255, 0, 0)); + // } + // } + // } + + session->set_source(leaf_matrix); + finder = session->make_iterator(0); + + size_t num_leaf_bits = 0; + while (finder->find_next(object, false)){ + num_leaf_bits += object.area; + } + + std::cout << "candidate berry at " << berry_box.center_x() << " " << berry_box.center_y() << ", leaf " << num_leaf_bits << "/" << potential_leaf_area << std::endl; + // draw_box(debug_image, enlarged_box, uint32_t(COLOR_CYAN), 2); + // draw_box(debug_image, berry_box, uint32_t(COLOR_BLUE), 2); + if (num_leaf_bits > potential_leaf_area * 2 / 3){ + std::cout << "berry at " << berry_box.center_x() << " " << berry_box.center_y() << ", leaf " << num_leaf_bits << "/" << potential_leaf_area << std::endl; + draw_box(debug_image, berry_box, uint32_t(COLOR_BLUE), 3); + } + } + + + + // for(int x = 0; x < debug_image.width(); x++){ + // for(int y = 0; y < debug_image.height(); y++){ + // if (matrices[0].get(x, y)){ + // debug_image.setPixelColor(x, y, QColor(255, 0, 0)); + // } + // } + // } + std::cout << "Saving inference debug_image" << std::endl; + debug_image.save("./test_berry_tree_output.png"); + + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.h index d91f0cbc76..84d8fb14b7 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BerryTreeDetector.h @@ -1,34 +1,34 @@ -/* Berry Tree Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_BerryTreeDetector_H -#define PokemonAutomation_PokemonLA_BerryTreeDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class BerryTreeDetector : public VisualInferenceCallback{ -public: - BerryTreeDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: -}; - - -} -} -} -#endif +/* Berry Tree Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_BerryTreeDetector_H +#define PokemonAutomation_PokemonLA_BerryTreeDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class BerryTreeDetector : public VisualInferenceCallback{ +public: + BerryTreeDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.cpp index 8db9bd9140..579be4f0dd 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.cpp @@ -1,93 +1,93 @@ -/* Black Out Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA_BlackOutDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -namespace{ - -// const std::array dropped_item_bg_checks = { -// ImageSolidCheck(0.031, 0.900, 0.024, 0.017, 0.444, 0.440, 0.116, 0.15, 20.0), -// ImageSolidCheck(0.026, 0.743, 0.021, 0.038, 0.407, 0.397, 0.196, 0.15, 50.0), -// ImageSolidCheck(0.022, 0.581, 0.020, 0.018, 0.332, 0.433, 0.234, 0.15, 30.0), -// ImageSolidCheck(0.152, 0.482, 0.017, 0.040, 0.343, 0.451, 0.207, 0.15, 30.0), -// ImageSolidCheck(0.016, 0.218, 0.018, 0.021, 0.341, 0.350, 0.309, 0.15, 20.0), -// ImageSolidCheck(0.169, 0.103, 0.024, 0.036, 0.216, 0.385, 0.399, 0.15, 10.0), -// ImageSolidCheck(0.815, 0.244, 0.026, 0.026, 0.339, 0.350, 0.310, 0.15, 40.0), -// ImageSolidCheck(0.737, 0.126, 0.045, 0.056, 0.227, 0.384, 0.389, 0.15, 30.0), -// ImageSolidCheck(0.806, 0.431, 0.043, 0.026, 0.350, 0.371, 0.278, 0.15, 20.0), -// ImageSolidCheck(0.827, 0.507, 0.023, 0.028, 0.327, 0.386, 0.287, 0.15, 30.0), -// ImageSolidCheck(0.747, 0.603, 0.087, 0.086, 0.402, 0.439, 0.159, 0.15, 20.0), -// ImageSolidCheck(0.885, 0.653, 0.041, 0.093, 0.353, 0.404, 0.242, 0.15, 20.0), -// ImageSolidCheck(0.934, 0.556, 0.039, 0.038, 0.413, 0.446, 0.141, 0.15, 30.0), -// ImageSolidCheck(0.761, 0.913, 0.071, 0.051, 0.373, 0.424, 0.203, 0.15, 30.0), -// ImageSolidCheck(0.865, 0.098, 0.022, 0.030, 0.326, 0.353, 0.321, 0.15, 50.0), -// ImageSolidCheck(0.202, 0.631, 0.057, 0.075, 0.414, 0.468, 0.118, 0.15, 20.0), -// ImageSolidCheck(0.099, 0.265, 0.072, 0.070, 0.288, 0.376, 0.336, 0.15, 20.0), -// ImageSolidCheck(0.908, 0.313, 0.020, 0.017, 0.316, 0.387, 0.297, 0.15, 20.0), -// }; - - -} - - -BlackOutDetector::BlackOutDetector(Logger& logger, VideoOverlay& overlay) - : VisualInferenceCallback("BlackOutDetector") - , m_black_screen(0.068, 0.088, 0.864, 0.581) - , m_yellow_arrow_detector(logger, overlay, true) - // , m_button_Y_detector(logger, overlay, ButtonType::ButtonY, ImageFloatBox{0.439, 0.819, 0.029, 0.059}, std::chrono::milliseconds(0), false) -{} - -void BlackOutDetector::make_overlays(VideoOverlaySet& items) const{ - m_yellow_arrow_detector.make_overlays(items); - items.add(COLOR_BLUE, m_black_screen); -} - -// Return true if the inference session should stop. -bool BlackOutDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - - auto save_image = [&](){ - static int count = 0; - frame.save("BlackOut-" + std::to_string(count) + ".png"); - count++; - }; - - // check whether it is the black out screen - const bool is_screen_black = is_black(extract_box_reference(frame, m_black_screen), 100, 10); - if (is_screen_black && m_yellow_arrow_detector.process_frame(frame, timestamp)){ - // We have both a mostly black screen and a yellow arrow: - save_image(); - return true; - } - - return false; - - - // // Check each patch of background color of the dropped item screen - // for(const auto& check: dropped_item_bg_checks){ - // if (check.check(frame) == false){ - // // cout << "Check failed " << check.debug_string(frame) << endl; - // return false; - // } - // } - // save_image(); - // return true; -} - - - -} -} -} +/* Black Out Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA_BlackOutDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +namespace{ + +// const std::array dropped_item_bg_checks = { +// ImageSolidCheck(0.031, 0.900, 0.024, 0.017, 0.444, 0.440, 0.116, 0.15, 20.0), +// ImageSolidCheck(0.026, 0.743, 0.021, 0.038, 0.407, 0.397, 0.196, 0.15, 50.0), +// ImageSolidCheck(0.022, 0.581, 0.020, 0.018, 0.332, 0.433, 0.234, 0.15, 30.0), +// ImageSolidCheck(0.152, 0.482, 0.017, 0.040, 0.343, 0.451, 0.207, 0.15, 30.0), +// ImageSolidCheck(0.016, 0.218, 0.018, 0.021, 0.341, 0.350, 0.309, 0.15, 20.0), +// ImageSolidCheck(0.169, 0.103, 0.024, 0.036, 0.216, 0.385, 0.399, 0.15, 10.0), +// ImageSolidCheck(0.815, 0.244, 0.026, 0.026, 0.339, 0.350, 0.310, 0.15, 40.0), +// ImageSolidCheck(0.737, 0.126, 0.045, 0.056, 0.227, 0.384, 0.389, 0.15, 30.0), +// ImageSolidCheck(0.806, 0.431, 0.043, 0.026, 0.350, 0.371, 0.278, 0.15, 20.0), +// ImageSolidCheck(0.827, 0.507, 0.023, 0.028, 0.327, 0.386, 0.287, 0.15, 30.0), +// ImageSolidCheck(0.747, 0.603, 0.087, 0.086, 0.402, 0.439, 0.159, 0.15, 20.0), +// ImageSolidCheck(0.885, 0.653, 0.041, 0.093, 0.353, 0.404, 0.242, 0.15, 20.0), +// ImageSolidCheck(0.934, 0.556, 0.039, 0.038, 0.413, 0.446, 0.141, 0.15, 30.0), +// ImageSolidCheck(0.761, 0.913, 0.071, 0.051, 0.373, 0.424, 0.203, 0.15, 30.0), +// ImageSolidCheck(0.865, 0.098, 0.022, 0.030, 0.326, 0.353, 0.321, 0.15, 50.0), +// ImageSolidCheck(0.202, 0.631, 0.057, 0.075, 0.414, 0.468, 0.118, 0.15, 20.0), +// ImageSolidCheck(0.099, 0.265, 0.072, 0.070, 0.288, 0.376, 0.336, 0.15, 20.0), +// ImageSolidCheck(0.908, 0.313, 0.020, 0.017, 0.316, 0.387, 0.297, 0.15, 20.0), +// }; + + +} + + +BlackOutDetector::BlackOutDetector(Logger& logger, VideoOverlay& overlay) + : VisualInferenceCallback("BlackOutDetector") + , m_black_screen(0.068, 0.088, 0.864, 0.581) + , m_yellow_arrow_detector(logger, overlay, true) + // , m_button_Y_detector(logger, overlay, ButtonType::ButtonY, ImageFloatBox{0.439, 0.819, 0.029, 0.059}, std::chrono::milliseconds(0), false) +{} + +void BlackOutDetector::make_overlays(VideoOverlaySet& items) const{ + m_yellow_arrow_detector.make_overlays(items); + items.add(COLOR_BLUE, m_black_screen); +} + +// Return true if the inference session should stop. +bool BlackOutDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + + auto save_image = [&](){ + static int count = 0; + frame.save("BlackOut-" + std::to_string(count) + ".png"); + count++; + }; + + // check whether it is the black out screen + const bool is_screen_black = is_black(extract_box_reference(frame, m_black_screen), 100, 10); + if (is_screen_black && m_yellow_arrow_detector.process_frame(frame, timestamp)){ + // We have both a mostly black screen and a yellow arrow: + save_image(); + return true; + } + + return false; + + + // // Check each patch of background color of the dropped item screen + // for(const auto& check: dropped_item_bg_checks){ + // if (check.check(frame) == false){ + // // cout << "Check failed " << check.debug_string(frame) << endl; + // return false; + // } + // } + // save_image(); + // return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.h index 017a490e08..34746ee97a 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_BlackOutDetector.h @@ -1,44 +1,44 @@ -/* Black Out Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the black out screen when player character blacks out. - */ - -#ifndef PokemonAutomation_PokemonLA_BlackOutDetector_H -#define PokemonAutomation_PokemonLA_BlackOutDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class BlackOutDetector : public VisualInferenceCallback{ -public: - BlackOutDetector(Logger& logger, VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - // The black screen when the dialog of "Everything went black!" appears - ImageFloatBox m_black_screen; - // The yellow arrow pointing to the white button on the "Everything went black!" dialog box. - DialogueYellowArrowDetector m_yellow_arrow_detector; - // The bottom white space of the "Return to Base Camp" button. - // ImageFloatBox m_return_camp_bottom; - - // ButtonDetector m_button_Y_detector; -}; - - -} -} -} -#endif +/* Black Out Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the black out screen when player character blacks out. + */ + +#ifndef PokemonAutomation_PokemonLA_BlackOutDetector_H +#define PokemonAutomation_PokemonLA_BlackOutDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class BlackOutDetector : public VisualInferenceCallback{ +public: + BlackOutDetector(Logger& logger, VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + // The black screen when the dialog of "Everything went black!" appears + ImageFloatBox m_black_screen; + // The yellow arrow pointing to the white button on the "Everything went black!" dialog box. + DialogueYellowArrowDetector m_yellow_arrow_detector; + // The bottom white space of the "Return to Base Camp" button. + // ImageFloatBox m_return_camp_bottom; + + // ButtonDetector m_button_Y_detector; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.cpp index f6b974f9ff..ea93cc9e70 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.cpp @@ -1,24 +1,24 @@ -/* Common Color Check - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "PokemonLA_CommonColorCheck.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -bool is_LA_dark_blue(const ImageStats& stats){ - return (stats.average.sum() <= 300 && stats.stddev.sum() <= 15 && - stats.average.b > stats.average.r && stats.average.b > stats.average.g - ); -} - - -} -} -} +/* Common Color Check + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "PokemonLA_CommonColorCheck.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +bool is_LA_dark_blue(const ImageStats& stats){ + return (stats.average.sum() <= 300 && stats.stddev.sum() <= 15 && + stats.average.b > stats.average.r && stats.average.b > stats.average.g + ); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.h index 880fa0f5d7..5bd88f9a38 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_CommonColorCheck.h @@ -1,28 +1,28 @@ -/* Common Color Check - * - * From: https://github.com/PokemonAutomation/ - * - * Several checks for commonly used color in LA. These checks are used by various inference detector classes. - */ - -#ifndef PokemonAutomation_PokemonLA_MapDetector_H -#define PokemonAutomation_PokemonLA_MapDetector_H - -namespace PokemonAutomation{ - -struct ImageStats; - -namespace NintendoSwitch{ -namespace PokemonLA{ - -// The dark blue used as the background of the title text on normal and surprise diallgue boxes. -// The color is also used as the selected tab on the top of the screen in the main menu space -// (entered by pressing DPAD_UP from overworld). -bool is_LA_dark_blue(const ImageStats& stats); - - - -} -} -} -#endif +/* Common Color Check + * + * From: https://github.com/PokemonAutomation/ + * + * Several checks for commonly used color in LA. These checks are used by various inference detector classes. + */ + +#ifndef PokemonAutomation_PokemonLA_MapDetector_H +#define PokemonAutomation_PokemonLA_MapDetector_H + +namespace PokemonAutomation{ + +struct ImageStats; + +namespace NintendoSwitch{ +namespace PokemonLA{ + +// The dark blue used as the background of the title text on normal and surprise diallgue boxes. +// The color is also used as the selected tab on the top of the screen in the main menu space +// (entered by pressing DPAD_UP from overworld). +bool is_LA_dark_blue(const ImageStats& stats); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.cpp index ec85ff9f85..d5fa318353 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.cpp @@ -1,197 +1,197 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLA_CommonColorCheck.h" -#include "PokemonLA_DialogDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -DialogSurpriseDetector::DialogSurpriseDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("DialogSurpriseDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_title_top (0.295, 0.722, 0.100, 0.005) - , m_title_bottom(0.295, 0.765, 0.100, 0.005) - , m_top_white (0.500, 0.760, 0.200, 0.020) - , m_bottom_white(0.400, 0.900, 0.200, 0.020) - , m_cursor (0.720, 0.855, 0.030, 0.060) - , m_arc_phone(logger, overlay, std::chrono::milliseconds(0), false) -{} -void DialogSurpriseDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_title_top); - items.add(COLOR_RED, m_title_bottom); - items.add(COLOR_RED, m_top_white); - items.add(COLOR_RED, m_bottom_white); - items.add(COLOR_RED, m_cursor); - m_arc_phone.make_overlays(items); -} -bool DialogSurpriseDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - size_t hits = 0; - - ImageStats title_top = image_stats(extract_box_reference(frame, m_title_top)); -// cout << title_top.average << title_top.stddev << endl; -// hits += is_solid(title_top, {0.218332, 0.330301, 0.451367}, 0.2, 15) ? 1 : 0; - if (is_LA_dark_blue(title_top)){ - hits++; - } -// cout << "hits = " << hits << endl; - - ImageStats title_bottom = image_stats(extract_box_reference(frame, m_title_bottom)); -// cout << title_bottom.average << title_bottom.stddev << endl; -// hits += is_solid(title_bottom, {0.226944, 0.323437, 0.449619}, 0.2, 15) ? 1 : 0; - if (is_LA_dark_blue(title_bottom)){ - hits++; - } -// cout << "hits = " << hits << endl; - - ImageStats top_white = image_stats(extract_box_reference(frame, m_top_white)); -// cout << top_white.average << top_white.stddev << endl; - hits += is_white(top_white, 480, 20) ? 1 : 0; -// cout << "hits = " << hits << endl; - - ImageStats bottom_white = image_stats(extract_box_reference(frame, m_bottom_white)); -// cout << bottom_white.average << bottom_white.stddev << endl; - hits += is_white(bottom_white, 480, 20) ? 1 : 0; -// cout << "hits = " << hits << endl; - - ImageStats cursor = image_stats(extract_box_reference(frame, m_cursor)); -// cout << cursor.average << cursor.stddev << endl; - hits += cursor.stddev.sum() > 50 ? 1 : 0; -// cout << "hits = " << hits << endl; - - m_arc_phone.process_frame(frame, timestamp); - bool phone = m_arc_phone.detected(); -// cout << !phone << endl; - hits += !phone; -// cout << "hits = " << hits << endl; - - bool detected = hits >= 5; - m_detected.store(detected, std::memory_order_release); - -#if 0 - if (detected){ - static size_t c = 0; - frame.save("SurpriseDialogueBoxTriggered-" + std::to_string(c++) + ".png"); - } -#endif - - - return detected && m_stop_on_detected; -} - - - - - - -NormalDialogDetector::NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("NormalDialogDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_title_top (0.278, 0.712, 0.100, 0.005) - , m_title_bottom(0.278, 0.755, 0.100, 0.005) - , m_title_left (0.259, 0.715, 0.003, 0.043) - , m_title_right (0.390, 0.715, 0.003, 0.043) - , m_top_white (0.500, 0.750, 0.200, 0.020) - , m_bottom_white(0.400, 0.895, 0.200, 0.020) - , m_left_white (0.230, 0.805, 0.016, 0.057) - , m_right_white (0.755, 0.805, 0.016, 0.057) - // , m_arc_phone(logger, overlay, std::chrono::milliseconds(0), false) -{} -void NormalDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_title_top); - items.add(COLOR_RED, m_title_bottom); - items.add(COLOR_RED, m_top_white); - items.add(COLOR_RED, m_bottom_white); - items.add(COLOR_RED, m_left_white); - items.add(COLOR_RED, m_right_white); - // m_arc_phone.make_overlays(items); -} -bool NormalDialogDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - size_t hits = 0; - - const ImageStats title_top = image_stats(extract_box_reference(frame, m_title_top)); - const ImageStats title_bottom = image_stats(extract_box_reference(frame, m_title_bottom)); - const ImageStats title_left = image_stats(extract_box_reference(frame, m_title_left)); - const ImageStats title_right = image_stats(extract_box_reference(frame, m_title_right)); - // If three of the four passes, then we are good for title check - if (is_LA_dark_blue(title_top) + is_LA_dark_blue(title_bottom) + is_LA_dark_blue(title_left) + is_LA_dark_blue(title_right) >= 3){ - hits++; - } - - ImageStats top_white = image_stats(extract_box_reference(frame, m_top_white)); - hits += is_white(top_white, 480, 30) ? 1 : 0; - - ImageStats bottom_white = image_stats(extract_box_reference(frame, m_bottom_white)); - hits += is_white(bottom_white, 480, 30) ? 1 : 0; - - ImageStats left_white = image_stats(extract_box_reference(frame, m_left_white)); - hits += is_white(left_white, 480, 30) ? 1 : 0; - - ImageStats right_white = image_stats(extract_box_reference(frame, m_right_white)); - hits += is_white(right_white, 480, 30) ? 1 : 0; - - // m_arc_phone.process_frame(frame, timestamp); - // bool phone = m_arc_phone.detected(); - // hits += !phone; - - bool detected = hits == 5; - m_detected.store(detected, std::memory_order_release); - - return detected && m_stop_on_detected; -} - - - - -EventDialogDetector::EventDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("EventDialogDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_left_blue (0.248, 0.768, 0.009, 0.135) - , m_right_blue(0.723, 0.766, 0.029, 0.063) - , m_yellow_arrow_detector(logger, overlay, false) -{} -void EventDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_blue); - items.add(COLOR_RED, m_right_blue); - m_yellow_arrow_detector.make_overlays(items); -} -bool EventDialogDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - size_t hits = 0; - - auto dialog_bg_color_check = [](const ImageStats & stats) -> bool{ - // cout << "stats " << stats.average << " " << stats.stddev << endl; - const auto& avg = stats.average; - return avg.r < 50.0 && avg.g < 70.0 && avg.b < 100.0 && avg.r < avg.b * 1.3 && avg.g < avg.b * 1.3 && stats.stddev.sum() < 20.; - }; - - ImageStats left_blue = image_stats(extract_box_reference(frame, m_left_blue)); - hits += dialog_bg_color_check(left_blue); - - ImageStats right_blue = image_stats(extract_box_reference(frame, m_right_blue)); - hits += dialog_bg_color_check(right_blue); - - m_yellow_arrow_detector.process_frame(frame, timestamp); - hits += m_yellow_arrow_detector.detected(); - - bool detected = hits == 3; - m_detected.store(detected, std::memory_order_release); - - return detected && m_stop_on_detected; -} -} -} -} +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLA_CommonColorCheck.h" +#include "PokemonLA_DialogDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +DialogSurpriseDetector::DialogSurpriseDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("DialogSurpriseDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_title_top (0.295, 0.722, 0.100, 0.005) + , m_title_bottom(0.295, 0.765, 0.100, 0.005) + , m_top_white (0.500, 0.760, 0.200, 0.020) + , m_bottom_white(0.400, 0.900, 0.200, 0.020) + , m_cursor (0.720, 0.855, 0.030, 0.060) + , m_arc_phone(logger, overlay, std::chrono::milliseconds(0), false) +{} +void DialogSurpriseDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_title_top); + items.add(COLOR_RED, m_title_bottom); + items.add(COLOR_RED, m_top_white); + items.add(COLOR_RED, m_bottom_white); + items.add(COLOR_RED, m_cursor); + m_arc_phone.make_overlays(items); +} +bool DialogSurpriseDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + size_t hits = 0; + + ImageStats title_top = image_stats(extract_box_reference(frame, m_title_top)); +// cout << title_top.average << title_top.stddev << endl; +// hits += is_solid(title_top, {0.218332, 0.330301, 0.451367}, 0.2, 15) ? 1 : 0; + if (is_LA_dark_blue(title_top)){ + hits++; + } +// cout << "hits = " << hits << endl; + + ImageStats title_bottom = image_stats(extract_box_reference(frame, m_title_bottom)); +// cout << title_bottom.average << title_bottom.stddev << endl; +// hits += is_solid(title_bottom, {0.226944, 0.323437, 0.449619}, 0.2, 15) ? 1 : 0; + if (is_LA_dark_blue(title_bottom)){ + hits++; + } +// cout << "hits = " << hits << endl; + + ImageStats top_white = image_stats(extract_box_reference(frame, m_top_white)); +// cout << top_white.average << top_white.stddev << endl; + hits += is_white(top_white, 480, 20) ? 1 : 0; +// cout << "hits = " << hits << endl; + + ImageStats bottom_white = image_stats(extract_box_reference(frame, m_bottom_white)); +// cout << bottom_white.average << bottom_white.stddev << endl; + hits += is_white(bottom_white, 480, 20) ? 1 : 0; +// cout << "hits = " << hits << endl; + + ImageStats cursor = image_stats(extract_box_reference(frame, m_cursor)); +// cout << cursor.average << cursor.stddev << endl; + hits += cursor.stddev.sum() > 50 ? 1 : 0; +// cout << "hits = " << hits << endl; + + m_arc_phone.process_frame(frame, timestamp); + bool phone = m_arc_phone.detected(); +// cout << !phone << endl; + hits += !phone; +// cout << "hits = " << hits << endl; + + bool detected = hits >= 5; + m_detected.store(detected, std::memory_order_release); + +#if 0 + if (detected){ + static size_t c = 0; + frame.save("SurpriseDialogueBoxTriggered-" + std::to_string(c++) + ".png"); + } +#endif + + + return detected && m_stop_on_detected; +} + + + + + + +NormalDialogDetector::NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("NormalDialogDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_title_top (0.278, 0.712, 0.100, 0.005) + , m_title_bottom(0.278, 0.755, 0.100, 0.005) + , m_title_left (0.259, 0.715, 0.003, 0.043) + , m_title_right (0.390, 0.715, 0.003, 0.043) + , m_top_white (0.500, 0.750, 0.200, 0.020) + , m_bottom_white(0.400, 0.895, 0.200, 0.020) + , m_left_white (0.230, 0.805, 0.016, 0.057) + , m_right_white (0.755, 0.805, 0.016, 0.057) + // , m_arc_phone(logger, overlay, std::chrono::milliseconds(0), false) +{} +void NormalDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_title_top); + items.add(COLOR_RED, m_title_bottom); + items.add(COLOR_RED, m_top_white); + items.add(COLOR_RED, m_bottom_white); + items.add(COLOR_RED, m_left_white); + items.add(COLOR_RED, m_right_white); + // m_arc_phone.make_overlays(items); +} +bool NormalDialogDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + size_t hits = 0; + + const ImageStats title_top = image_stats(extract_box_reference(frame, m_title_top)); + const ImageStats title_bottom = image_stats(extract_box_reference(frame, m_title_bottom)); + const ImageStats title_left = image_stats(extract_box_reference(frame, m_title_left)); + const ImageStats title_right = image_stats(extract_box_reference(frame, m_title_right)); + // If three of the four passes, then we are good for title check + if (is_LA_dark_blue(title_top) + is_LA_dark_blue(title_bottom) + is_LA_dark_blue(title_left) + is_LA_dark_blue(title_right) >= 3){ + hits++; + } + + ImageStats top_white = image_stats(extract_box_reference(frame, m_top_white)); + hits += is_white(top_white, 480, 30) ? 1 : 0; + + ImageStats bottom_white = image_stats(extract_box_reference(frame, m_bottom_white)); + hits += is_white(bottom_white, 480, 30) ? 1 : 0; + + ImageStats left_white = image_stats(extract_box_reference(frame, m_left_white)); + hits += is_white(left_white, 480, 30) ? 1 : 0; + + ImageStats right_white = image_stats(extract_box_reference(frame, m_right_white)); + hits += is_white(right_white, 480, 30) ? 1 : 0; + + // m_arc_phone.process_frame(frame, timestamp); + // bool phone = m_arc_phone.detected(); + // hits += !phone; + + bool detected = hits == 5; + m_detected.store(detected, std::memory_order_release); + + return detected && m_stop_on_detected; +} + + + + +EventDialogDetector::EventDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("EventDialogDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_left_blue (0.248, 0.768, 0.009, 0.135) + , m_right_blue(0.723, 0.766, 0.029, 0.063) + , m_yellow_arrow_detector(logger, overlay, false) +{} +void EventDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_blue); + items.add(COLOR_RED, m_right_blue); + m_yellow_arrow_detector.make_overlays(items); +} +bool EventDialogDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + size_t hits = 0; + + auto dialog_bg_color_check = [](const ImageStats & stats) -> bool{ + // cout << "stats " << stats.average << " " << stats.stddev << endl; + const auto& avg = stats.average; + return avg.r < 50.0 && avg.g < 70.0 && avg.b < 100.0 && avg.r < avg.b * 1.3 && avg.g < avg.b * 1.3 && stats.stddev.sum() < 20.; + }; + + ImageStats left_blue = image_stats(extract_box_reference(frame, m_left_blue)); + hits += dialog_bg_color_check(left_blue); + + ImageStats right_blue = image_stats(extract_box_reference(frame, m_right_blue)); + hits += dialog_bg_color_check(right_blue); + + m_yellow_arrow_detector.process_frame(frame, timestamp); + hits += m_yellow_arrow_detector.detected(); + + bool detected = hits == 3; + m_detected.store(detected, std::memory_order_release); + + return detected && m_stop_on_detected; +} +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.h index b8158aa8e7..cee535040b 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_DialogDetector.h @@ -1,92 +1,92 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_DialogDetector_H -#define PokemonAutomation_PokemonLA_DialogDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -// Detect surprise dialogue that is used in cases like the bandits stop you. -class DialogSurpriseDetector : public VisualInferenceCallback{ -public: - DialogSurpriseDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - ImageFloatBox m_title_top; - ImageFloatBox m_title_bottom; - ImageFloatBox m_top_white; - ImageFloatBox m_bottom_white; - ImageFloatBox m_cursor; - ArcPhoneDetector m_arc_phone; -}; - -// Detect normal dialogue that is used in cases like when you talk to gate guard Ross when leaving the village. -// Note: it can only detect dialogue boxes with a title. Title appears when you talk to an NPC with known names. -// The Galaxy member at each camp that gives you access to the ranch and shop has no dialogue title. -class NormalDialogDetector : public VisualInferenceCallback{ -public: - NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - ImageFloatBox m_title_top; - ImageFloatBox m_title_bottom; - ImageFloatBox m_title_left; - ImageFloatBox m_title_right; - ImageFloatBox m_top_white; - ImageFloatBox m_bottom_white; - ImageFloatBox m_left_white; - ImageFloatBox m_right_white; -}; - -// Detect event dialogue that is used in cases like when you interact with the tent in a camp. -class EventDialogDetector : public VisualInferenceCallback{ -public: - EventDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - ImageFloatBox m_left_blue; - ImageFloatBox m_right_blue; - DialogueYellowArrowDetector m_yellow_arrow_detector; -}; - -} -} -} -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_DialogDetector_H +#define PokemonAutomation_PokemonLA_DialogDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +// Detect surprise dialogue that is used in cases like the bandits stop you. +class DialogSurpriseDetector : public VisualInferenceCallback{ +public: + DialogSurpriseDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + ImageFloatBox m_title_top; + ImageFloatBox m_title_bottom; + ImageFloatBox m_top_white; + ImageFloatBox m_bottom_white; + ImageFloatBox m_cursor; + ArcPhoneDetector m_arc_phone; +}; + +// Detect normal dialogue that is used in cases like when you talk to gate guard Ross when leaving the village. +// Note: it can only detect dialogue boxes with a title. Title appears when you talk to an NPC with known names. +// The Galaxy member at each camp that gives you access to the ranch and shop has no dialogue title. +class NormalDialogDetector : public VisualInferenceCallback{ +public: + NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + ImageFloatBox m_title_top; + ImageFloatBox m_title_bottom; + ImageFloatBox m_title_left; + ImageFloatBox m_title_right; + ImageFloatBox m_top_white; + ImageFloatBox m_bottom_white; + ImageFloatBox m_left_white; + ImageFloatBox m_right_white; +}; + +// Detect event dialogue that is used in cases like when you interact with the tent in a camp. +class EventDialogDetector : public VisualInferenceCallback{ +public: + EventDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + ImageFloatBox m_left_blue; + ImageFloatBox m_right_blue; + DialogueYellowArrowDetector m_yellow_arrow_detector; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.cpp index de6def9571..1ea63f9f19 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.cpp @@ -1,51 +1,51 @@ -/* Item Compatibility Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonLA_ItemCompatibilityDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -ItemCompatibility detect_item_compatibility(const ImageViewRGB32& screen){ - // The Compatible/Incompatible text region of the lead pokemon on the screen. - const ImageFloatBox box(0.838, 0.1815, 0.090, 0.024); - - // Replacing white background with zero-alpha color so that they won't be counted in - // the following image_stats() - // The white background is defined as the color between 0xffa0a0a0 and 0xffffffff. - const bool replace_color_within_range = true; - ImageRGB32 region = filter_rgb32_range( - extract_box_reference(screen, box), - 0xffa0a0a0, 0xffffffff, Color(0), replace_color_within_range - ); - - ImageStats stats = image_stats(region); - // std::cout << "Compatibility color " << stats.average.r << " " << stats.average.g << " " << stats.average.b << std::endl; - if (stats.average.r > stats.average.b + 50.0){ - return ItemCompatibility::INCOMPATIBLE; - } - if (stats.average.b > stats.average.r + 50.0){ - return ItemCompatibility::COMPATIBLE; - } - - return ItemCompatibility::NONE; -} - - -} -} -} +/* Item Compatibility Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonLA_ItemCompatibilityDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +ItemCompatibility detect_item_compatibility(const ImageViewRGB32& screen){ + // The Compatible/Incompatible text region of the lead pokemon on the screen. + const ImageFloatBox box(0.838, 0.1815, 0.090, 0.024); + + // Replacing white background with zero-alpha color so that they won't be counted in + // the following image_stats() + // The white background is defined as the color between 0xffa0a0a0 and 0xffffffff. + const bool replace_color_within_range = true; + ImageRGB32 region = filter_rgb32_range( + extract_box_reference(screen, box), + 0xffa0a0a0, 0xffffffff, Color(0), replace_color_within_range + ); + + ImageStats stats = image_stats(region); + // std::cout << "Compatibility color " << stats.average.r << " " << stats.average.g << " " << stats.average.b << std::endl; + if (stats.average.r > stats.average.b + 50.0){ + return ItemCompatibility::INCOMPATIBLE; + } + if (stats.average.b > stats.average.r + 50.0){ + return ItemCompatibility::COMPATIBLE; + } + + return ItemCompatibility::NONE; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h index 0a8e823427..497cd78110 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h @@ -1,31 +1,31 @@ -/* Item Compatibility Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ItemCompatibilityDetector_H -#define PokemonAutomation_PokemonLA_ItemCompatibilityDetector_H - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonLA{ - -enum class ItemCompatibility{ - NONE, - COMPATIBLE, - INCOMPATIBLE, -}; - -// Detect whether an item can be used on the lead pokemon. -// The game shows blue "Compatible" if it can be used, red "Incompatible" otherwise. -// This function uses the color of the text to detect which one is shown. -// Return ItemCompatibility::NONE if the detection fails. -ItemCompatibility detect_item_compatibility(const ImageViewRGB32& screen); - - -} -} -} -#endif +/* Item Compatibility Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ItemCompatibilityDetector_H +#define PokemonAutomation_PokemonLA_ItemCompatibilityDetector_H + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonLA{ + +enum class ItemCompatibility{ + NONE, + COMPATIBLE, + INCOMPATIBLE, +}; + +// Detect whether an item can be used on the lead pokemon. +// The game shows blue "Compatible" if it can be used, red "Incompatible" otherwise. +// This function uses the color of the text to detect which one is shown. +// Return ItemCompatibility::NONE if the detection fails. +ItemCompatibility detect_item_compatibility(const ImageViewRGB32& screen); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.cpp index b56ac640d4..1d18cd4eaa 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.cpp @@ -1,680 +1,680 @@ -/* Mount Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA_MountDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - -class MountMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - using WaterfillTemplateMatcher::WaterfillTemplateMatcher; -}; - - -#if 1 - -ImageRGB32 make_MountMatcher2Image(const char* path){ - ImageRGB32 image(RESOURCE_PATH() + path); - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto finder = session->make_iterator(50); - - WaterfillObject plus, arrowL, arrowR; - -// image.save("test.png"); -// static int c = 0; - - - double rmsd_plus = 99999; - double rmsd_arrowL = 99999; - double rmsd_arrowR = 99999; - - - WaterfillObject object; - while (finder->find_next(object, false)){ - ImageViewRGB32 cropped = extract_box_reference(image, object); -// cropped.save("test-" + std::to_string(c++) + ".png"); - - double current_rmsd_plus = ButtonMatcher::Plus().rmsd_precropped(cropped, object); - if (rmsd_plus > current_rmsd_plus){ - rmsd_plus = current_rmsd_plus; - plus = object; - } - double current_rmsd_arrowL = ButtonMatcher::ArrowLeft().rmsd_precropped(cropped, object); - if (rmsd_arrowL > current_rmsd_arrowL){ - rmsd_arrowL = current_rmsd_arrowL; - arrowL = object; - } - double current_rmsd_arrowR = ButtonMatcher::ArrowRight().rmsd_precropped(cropped, object); - if (rmsd_arrowR > current_rmsd_arrowR){ - rmsd_arrowR = current_rmsd_arrowR; - arrowR = object; - continue; - } - } - -// cout << "plus = " << rmsd_plus << ", arrowL = " << rmsd_arrowL << ", arrowR = " << rmsd_arrowR << endl; - - if (rmsd_plus > 80){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to find (+) button in resource. rmsd = " + std::to_string(rmsd_plus), path); - } - if (rmsd_arrowL > 180){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to find (<) button in resource. rmsd = " + std::to_string(rmsd_arrowL), path); - } - if (rmsd_arrowR > 180){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to find (>) button in resource. rmsd = " + std::to_string(rmsd_arrowR), path); - } - - plus.merge_assume_no_overlap(arrowL); - plus.merge_assume_no_overlap(arrowR); - - return extract_box_reference(image, plus).copy(); -} - -class MountMatcherButtons : public ImageMatch::ExactImageMatcher{ -public: - MountMatcherButtons(const char* path) - : ExactImageMatcher(make_MountMatcher2Image(path)) - {} - -}; -#endif - - - - - -class MountWyrdeerMatcher : public MountMatcher{ -public: - MountWyrdeerMatcher(bool on) - : MountMatcher( - on - ? "PokemonLA/Mounts/MountOn-Wyrdeer-Template-1.png" - : "PokemonLA/Mounts/MountOff-Wyrdeer-Template.png", - Color(0xff808000), Color(0xffffffff), 100 - ) - {} - static const MountWyrdeerMatcher& on(){ - static MountWyrdeerMatcher matcher(true); - return matcher; - } - static const MountWyrdeerMatcher& off(){ - static MountWyrdeerMatcher matcher(false); - return matcher; - } -}; -class MountUrsalunaMatcher : public MountMatcher{ -public: - MountUrsalunaMatcher(bool on) - : MountMatcher( - on - ? "PokemonLA/Mounts/MountOn-Ursaluna-Template-1.png" - : "PokemonLA/Mounts/MountOff-Ursaluna-Template.png", - Color(0xff808000), Color(0xffffffff), 100 - ) - {} - static const MountUrsalunaMatcher& on(){ - static MountUrsalunaMatcher matcher(true); - return matcher; - } - static const MountUrsalunaMatcher& off(){ - static MountUrsalunaMatcher matcher(false); - return matcher; - } -}; -class MountBasculegionMatcher : public MountMatcher{ -public: - MountBasculegionMatcher(bool on) - : MountMatcher( - on - ? "PokemonLA/Mounts/MountOn-Basculegion-Template-1.png" - : "PokemonLA/Mounts/MountOff-Basculegion-Template.png", - Color(0xff808000), Color(0xffffffff), 100 - ) - { - m_area_ratio_upper = 1.50; - } - static const MountBasculegionMatcher& on(){ - static MountBasculegionMatcher matcher(true); - return matcher; - } - static const MountBasculegionMatcher& off(){ - static MountBasculegionMatcher matcher(false); - return matcher; - } -}; -class MountSneaslerMatcher : public MountMatcher{ -public: - MountSneaslerMatcher(bool on) - : MountMatcher( - on - ? "PokemonLA/Mounts/MountOn-Sneasler-Template-1.png" - : "PokemonLA/Mounts/MountOff-Sneasler-Template.png", - Color(0xff808000), Color(0xffffffff), 100 - ) - {} - static const MountSneaslerMatcher& on(){ - static MountSneaslerMatcher matcher(true); - return matcher; - } - static const MountSneaslerMatcher& off(){ - static MountSneaslerMatcher matcher(false); - return matcher; - } -}; -class MountBraviaryMatcher : public MountMatcher{ -public: - MountBraviaryMatcher(bool on) - : MountMatcher( - on - ? "PokemonLA/Mounts/MountOn-Braviary-Template-1.png" - : "PokemonLA/Mounts/MountOff-Braviary-Template.png", - Color(0xff808000), Color(0xffffffff), 100 - ) - { - m_area_ratio_upper = 1.65; - } - static const MountBraviaryMatcher& on(){ - static MountBraviaryMatcher matcher(true); - return matcher; - } - static const MountBraviaryMatcher& off(){ - static MountBraviaryMatcher matcher(false); - return matcher; - } -}; - - - - - -class MountWyrdeerMatcherButtons : public MountMatcherButtons{ -public: - MountWyrdeerMatcherButtons(bool on) - : MountMatcherButtons(on - ? "PokemonLA/Mounts/MountOn-Wyrdeer-Template.png" - : "PokemonLA/Mounts/MountOff-Wyrdeer-Template.png" - ) - {} - static const MountWyrdeerMatcherButtons& on(){ - static MountWyrdeerMatcherButtons matcher(true); - return matcher; - } - static const MountWyrdeerMatcherButtons& off(){ - static MountWyrdeerMatcherButtons matcher(false); - return matcher; - } -}; -class MountUrsalunaMatcherButtons : public MountMatcherButtons{ -public: - MountUrsalunaMatcherButtons(bool on) - : MountMatcherButtons(on - ? "PokemonLA/Mounts/MountOn-Ursaluna-Template.png" - : "PokemonLA/Mounts/MountOff-Ursaluna-Template.png" - ) - {} - static const MountUrsalunaMatcherButtons& on(){ - static MountUrsalunaMatcherButtons matcher(true); - return matcher; - } - static const MountUrsalunaMatcherButtons& off(){ - static MountUrsalunaMatcherButtons matcher(false); - return matcher; - } -}; -class MountBasculegionMatcherButtons : public MountMatcherButtons{ -public: - MountBasculegionMatcherButtons(bool on) - : MountMatcherButtons(on - ? "PokemonLA/Mounts/MountOn-Basculegion-Template.png" - : "PokemonLA/Mounts/MountOff-Basculegion-Template.png" - ) - {} - static const MountBasculegionMatcherButtons& on(){ - static MountBasculegionMatcherButtons matcher(true); - return matcher; - } -// static const MountBasculegionMatcherButtons& off(){ -// static MountBasculegionMatcherButtons matcher(false); -// return matcher; -// } -}; -class MountSneaslerMatcherButtons : public MountMatcherButtons{ -public: - MountSneaslerMatcherButtons(bool on) - : MountMatcherButtons(on - ? "PokemonLA/Mounts/MountOn-Sneasler-Template.png" - : "PokemonLA/Mounts/MountOff-Sneasler-Template.png" - ) - {} - static const MountSneaslerMatcherButtons& on(){ - static MountSneaslerMatcherButtons matcher(true); - return matcher; - } - static const MountSneaslerMatcherButtons& off(){ - static MountSneaslerMatcherButtons matcher(false); - return matcher; - } -}; -class MountBraviaryMatcherButtons : public MountMatcherButtons{ -public: - MountBraviaryMatcherButtons(bool on) - : MountMatcherButtons(on - ? "PokemonLA/Mounts/MountOn-Braviary-Template.png" - : "PokemonLA/Mounts/MountOff-Braviary-Template.png" - ) - {} - static const MountBraviaryMatcherButtons& on(){ - static MountBraviaryMatcherButtons matcher(true); - return matcher; - } - static const MountBraviaryMatcherButtons& off(){ - static MountBraviaryMatcherButtons matcher(false); - return matcher; - } -}; - - - - -const char* MOUNT_STATE_STRINGS[] = { - "No Detection", - "Wrydeer Off", - "Wrydeer On", - "Ursaluna Off", - "Ursaluna On", - "Basculegion Off", - "Basculegion On", - "Sneasler Off", - "Sneasler On", - "Braviary Off", - "Braviary On", -}; - - -MountDetector::MountDetector(MountDetectorLogging logging) - : m_box(0.905, 0.65, 0.08, 0.13) - , m_logging(logging) -{} - -struct MountCandiateTracker{ - double m_rmsd = 1000; - MountState m_state = MountState::NOTHING; - - void add_filtered(double rmsd, MountState state){ - if (rmsd > 150 || m_rmsd <= rmsd){ - return; - } - m_rmsd = rmsd; - m_state = state; - } - void add_direct(double rmsd, MountState state){ - if (rmsd > 80 || m_rmsd <= rmsd){ - return; - } - m_rmsd = rmsd; - m_state = state; - } - void add_button_crop(double rmsd, MountState state){ - if (rmsd > 90 || m_rmsd <= rmsd){ - return; - } - m_rmsd = rmsd; - m_state = state; - } -}; - -void MountDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); -} - - -struct MountDetectorFilteredImage{ - ImageRGB32 image; - PackedBinaryMatrix matrix; -}; - -std::vector run_filters(const ImageViewRGB32& image, const std::vector>& range){ - std::vector filters; - for (size_t c = 0; c < range.size(); c++){ - filters.emplace_back( - FilterRgb32Range{ - COLOR_BLACK, false, - range[c].first, range[c].second - } - ); - } - - std::vector matrices = compress_rgb32_to_binary_range(image, range); - std::vector> filtered = filter_rgb32_range(image, filters); - - std::vector ret(range.size()); - for (size_t c = 0; c < range.size(); c++){ - ret[c].image = std::move(filtered[c].first); - ret[c].matrix = std::move(matrices[c]); - } - - return ret; -} - - -MountState MountDetector::detect(const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_box); - - MountCandiateTracker candidates; - WaterfillObject plus, arrowL, arrowR; - - // Run direct-waterfill to detect all the off-mounts. - double rmsd_plus = 99999; - double rmsd_arrowL = 99999; - double rmsd_arrowR = 99999; - auto session = make_WaterfillSession(); - { - std::vector filtered_images = run_filters( - image, - { - {0xff808060, 0xffffffff}, - {0xff909070, 0xffffffff}, - {0xffa0a080, 0xffffffff}, - {0xffb0b090, 0xffffffff}, - {0xffc0c0a0, 0xffffffff}, - {0xffd0d0b0, 0xffffffff}, - {0xffe0e0c0, 0xffffffff}, - {0xfff0f0d0, 0xffffffff}, - } - ); -// static int c = 0; - for (MountDetectorFilteredImage& filtered : filtered_images){ -// cout << filtered.matrix.dump() << endl; - session->set_source(filtered.matrix); - auto finder = session->make_iterator(50); - WaterfillObject object; -// int c = 0; - while (finder->find_next(object, false)){ -// c++; - // Skip anything that touches the borders. - if (object.min_x == 0 || object.min_y == 0 || - object.max_x - 1 == (size_t)image.width() || - object.max_y - 1 == (size_t)image.height() - ){ - continue; - } - - ImageViewRGB32 cropped = extract_box_reference(image, object); - -// cout << "object = " << c << endl; -// cropped.save("object-" + std::to_string(c) + ".png"); - - - // Read the buttons. - double current_rmsd_plus = ButtonMatcher::Plus().rmsd_precropped(cropped, object); - if (rmsd_plus > current_rmsd_plus){ - rmsd_plus = current_rmsd_plus; - plus = object; - } -// cout << "Arrow (left)" << endl; - double current_rmsd_arrowL = ButtonMatcher::ArrowLeft().rmsd_precropped(cropped, object); - if (rmsd_arrowL > current_rmsd_arrowL){ - rmsd_arrowL = current_rmsd_arrowL; - arrowL = object; - } -// cout << "Arrow (right)" << endl; - double current_rmsd_arrowR = ButtonMatcher::ArrowRight().rmsd_precropped(cropped, object); -// cout << "rmsd_arrowR = " << rmsd_arrowR << endl; - if (rmsd_arrowR > current_rmsd_arrowR){ - rmsd_arrowR = current_rmsd_arrowR; - arrowR = object; - } - - // Skip bad geometry. - if (object.width() * 2 < image.width()){ - continue; - } - if (object.height() * 3 < image.height()){ - continue; - } - - ImageViewRGB32 filtered_cropped = extract_box_reference(filtered.image, object); -#if 1 - candidates.add_filtered(MountWyrdeerMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::WYRDEER_OFF); - candidates.add_direct (MountWyrdeerMatcher ::off().rmsd_precropped(cropped , object), MountState::WYRDEER_OFF); - candidates.add_filtered(MountUrsalunaMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::URSALUNA_OFF); - candidates.add_direct (MountUrsalunaMatcher ::off().rmsd_precropped(cropped , object), MountState::URSALUNA_OFF); - candidates.add_filtered(MountBasculegionMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::BASCULEGION_OFF); - candidates.add_direct (MountBasculegionMatcher ::off().rmsd_precropped(cropped , object), MountState::BASCULEGION_OFF); - candidates.add_filtered(MountSneaslerMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::SNEASLER_OFF); - candidates.add_direct (MountSneaslerMatcher ::off().rmsd_precropped(cropped , object), MountState::SNEASLER_OFF); - candidates.add_filtered(MountBraviaryMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::BRAVIARY_OFF); - candidates.add_direct (MountBraviaryMatcher ::off().rmsd_precropped(cropped , object), MountState::BRAVIARY_OFF); -#endif - - } - } - } - -// cout << "plus = " << plus.area << endl; -// cout << "arrowL = " << arrowL.area << endl; -// cout << "arrowR = " << arrowR.area << endl; - - // No buttons detected means mounts aren't available or we're on Basculegion. - bool buttons_detected = rmsd_plus < 120 && rmsd_arrowL < 180 && rmsd_arrowR < 180; - if (!buttons_detected){ -// cout << "plus = " << rmsd_plus << ", arrowL = " << rmsd_arrowL << ", arrowR = " << rmsd_arrowR << endl; - } - - // If we detected buttons, run the detections that align to the buttons. - if (buttons_detected){ - WaterfillObject arrows = std::move(plus); - arrows.merge_assume_no_overlap(arrowL); - arrows.merge_assume_no_overlap(arrowR); - - ImageViewRGB32 cropped = extract_box_reference(image, arrows); - -// cout << "Start mounts" << endl; - -#if 1 - candidates.add_button_crop(MountWyrdeerMatcherButtons ::off().rmsd(cropped), MountState::WYRDEER_OFF); -// candidates.add_button_crop(MountBasculegionMatcherButtons::off().rmsd(cropped), MountState::URSALUNA_OFF); - candidates.add_button_crop(MountUrsalunaMatcherButtons ::off().rmsd(cropped), MountState::BASCULEGION_OFF); - candidates.add_button_crop(MountSneaslerMatcherButtons ::off().rmsd(cropped), MountState::SNEASLER_OFF); - candidates.add_button_crop(MountBraviaryMatcherButtons ::off().rmsd(cropped), MountState::BRAVIARY_OFF); - candidates.add_button_crop(MountWyrdeerMatcherButtons ::on().rmsd(cropped), MountState::WYRDEER_ON); - candidates.add_button_crop(MountBasculegionMatcherButtons::on().rmsd(cropped), MountState::URSALUNA_ON); - candidates.add_button_crop(MountUrsalunaMatcherButtons ::on().rmsd(cropped), MountState::BASCULEGION_ON); - candidates.add_button_crop(MountSneaslerMatcherButtons ::on().rmsd(cropped), MountState::SNEASLER_ON); - candidates.add_button_crop(MountBraviaryMatcherButtons ::on().rmsd(cropped), MountState::BRAVIARY_ON); -#endif - } - -#if 1 - // Now run all the direct-waterfill to detect all the yellow mounts. - { - std::vector filtered_images = run_filters( - image, - { - {0xff606000, 0xffffff7f}, - {0xff808000, 0xffffff6f}, - {0xffa0a000, 0xffffff5f}, - {0xffc0c000, 0xffffff4f}, -// {0xff606000, 0xffffffff}, -// {0xff808000, 0xffffffff}, -// {0xffa0a000, 0xffffffff}, -// {0xffc0c000, 0xffffffff}, - } - ); -// int i = 0; - for (MountDetectorFilteredImage& filtered : filtered_images){ - session->set_source(filtered.matrix); - auto finder = session->make_iterator(50); - WaterfillObject object; - while (finder->find_next(object, false)){ - // Skip anything that touches the borders. - if (object.min_x == 0 || object.min_y == 0 || - object.max_x - 1 == (size_t)image.width() || - object.max_y - 1 == (size_t)image.height() - ){ - continue; - } - if (object.width() * 2 < (size_t)image.width()){ - continue; - } - if (object.height() * 3 < (size_t)image.height()){ - continue; - } - - ImageViewRGB32 cropped = extract_box_reference(image, object); - ImageViewRGB32 filtered_cropped = extract_box_reference(filtered.image, object); -#if 1 - candidates.add_filtered(MountWyrdeerMatcher ::on().rmsd(filtered_cropped), MountState::WYRDEER_ON); - candidates.add_direct (MountWyrdeerMatcher ::on().rmsd(cropped ), MountState::WYRDEER_ON); - candidates.add_filtered(MountUrsalunaMatcher ::on().rmsd(filtered_cropped), MountState::URSALUNA_ON); - candidates.add_direct (MountUrsalunaMatcher ::on().rmsd(cropped ), MountState::URSALUNA_ON); - candidates.add_filtered(MountBasculegionMatcher ::on().rmsd(filtered_cropped), MountState::BASCULEGION_ON); - candidates.add_direct (MountBasculegionMatcher ::on().rmsd(cropped ), MountState::BASCULEGION_ON); - candidates.add_filtered(MountSneaslerMatcher ::on().rmsd(filtered_cropped), MountState::SNEASLER_ON); - candidates.add_direct (MountSneaslerMatcher ::on().rmsd(cropped ), MountState::SNEASLER_ON); - candidates.add_filtered(MountBraviaryMatcher ::on().rmsd(filtered_cropped), MountState::BRAVIARY_ON); - candidates.add_direct (MountBraviaryMatcher ::on().rmsd(cropped ), MountState::BRAVIARY_ON); -#endif -// extract_box(image, object).save("test-" + std::to_string(i) + ".png"); -// i++; - } - } -// cout << "i = " << i << endl; - } -#endif - -// cout << "Button: rmsd = " << candidates.m_rmsd << ", state = " << (int)candidates.m_state << endl; -// if (candidates.m_state == MountState::BASCULEGION_ON){ -// screen.save("basculegion-detection.png"); -// } - if (m_logging != MountDetectorLogging::NONE){ - std::cout << "MountDetector: " << MOUNT_STATE_STRINGS[(size_t)candidates.m_state] - << ", rmsd = " << candidates.m_rmsd << (buttons_detected ? " (button)" : " (no button)") << std::endl; - if (m_logging == MountDetectorLogging::LOG_AND_DUMP_FAILURES && candidates.m_state == MountState::NOTHING){ - dump_image(global_logger_tagged(), ProgramInfo(), "MountDetection", screen); - } - } - return candidates.m_state; -} - - - - - -MountTracker::MountTracker(Logger& logger, MountDetectorLogging logging) - : VisualInferenceCallback("MountTracker") - , m_logger(logger) - , m_state(MountState::NOTHING) - , m_detector(logging) -{} - -void MountTracker::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -MountState MountTracker::state() const{ - return m_state.load(std::memory_order_acquire); -} - -bool MountTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - MountState state = m_detector.detect(frame); -// cout << "state = " << (int)state << endl; - - // Clear out old history. - WallClock threshold = timestamp - std::chrono::seconds(1); - while (!m_history.empty()){ - Sample& sample = m_history.front(); - if (m_history.front().timestamp >= threshold){ - break; - } - m_counts[sample.state]--; - m_history.pop_front(); - } - - size_t& count = m_counts[state]; - m_history.emplace_back(Sample{timestamp, state}); - count++; - - // Return most reported state in the last window. - MountState best_state = MountState::NOTHING; - size_t best_count = 0; - for (const auto& item : m_counts){ - if (best_count < item.second){ - best_count = item.second; - best_state = item.first; - } - } - - MountState last_state = this->state(); - if (last_state != best_state){ - m_logger.log( - std::string("Mount changed from ") + MOUNT_STATE_STRINGS[(int)last_state] + - " to " + MOUNT_STATE_STRINGS[(int)best_state] + ".", - COLOR_PURPLE - ); - } - m_state.store(best_state, std::memory_order_release); - - return false; -} - - - - -void make_mount_template(){ - ImageRGB32 image("MountOn-Braviary-Original.png"); - - size_t width = image.width(); - size_t height = image.height(); - size_t plus_min_x = width < 29 ? 0 : width - 29; - size_t plus_max_x = width < 10 ? 0 : width - 10; - size_t plus_min_y = height < 23 ? 0 : height - 23; - size_t plus_max_y = height < 4 ? 0 : height - 4; - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - if (plus_min_x < c && c < plus_max_x && plus_min_y < r && r < plus_max_y){ - continue; - } - Color pixel(image.pixel(c, r)); - if (pixel.red() < 128 || pixel.green() < 128){ - image.pixel(c, r) = 0; - } - } - } - - image.save("MountOn-Braviary-Template.png"); -} - - - - - - - -} -} -} +/* Mount Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA_MountDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + +class MountMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + using WaterfillTemplateMatcher::WaterfillTemplateMatcher; +}; + + +#if 1 + +ImageRGB32 make_MountMatcher2Image(const char* path){ + ImageRGB32 image(RESOURCE_PATH() + path); + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto finder = session->make_iterator(50); + + WaterfillObject plus, arrowL, arrowR; + +// image.save("test.png"); +// static int c = 0; + + + double rmsd_plus = 99999; + double rmsd_arrowL = 99999; + double rmsd_arrowR = 99999; + + + WaterfillObject object; + while (finder->find_next(object, false)){ + ImageViewRGB32 cropped = extract_box_reference(image, object); +// cropped.save("test-" + std::to_string(c++) + ".png"); + + double current_rmsd_plus = ButtonMatcher::Plus().rmsd_precropped(cropped, object); + if (rmsd_plus > current_rmsd_plus){ + rmsd_plus = current_rmsd_plus; + plus = object; + } + double current_rmsd_arrowL = ButtonMatcher::ArrowLeft().rmsd_precropped(cropped, object); + if (rmsd_arrowL > current_rmsd_arrowL){ + rmsd_arrowL = current_rmsd_arrowL; + arrowL = object; + } + double current_rmsd_arrowR = ButtonMatcher::ArrowRight().rmsd_precropped(cropped, object); + if (rmsd_arrowR > current_rmsd_arrowR){ + rmsd_arrowR = current_rmsd_arrowR; + arrowR = object; + continue; + } + } + +// cout << "plus = " << rmsd_plus << ", arrowL = " << rmsd_arrowL << ", arrowR = " << rmsd_arrowR << endl; + + if (rmsd_plus > 80){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to find (+) button in resource. rmsd = " + std::to_string(rmsd_plus), path); + } + if (rmsd_arrowL > 180){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to find (<) button in resource. rmsd = " + std::to_string(rmsd_arrowL), path); + } + if (rmsd_arrowR > 180){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Unable to find (>) button in resource. rmsd = " + std::to_string(rmsd_arrowR), path); + } + + plus.merge_assume_no_overlap(arrowL); + plus.merge_assume_no_overlap(arrowR); + + return extract_box_reference(image, plus).copy(); +} + +class MountMatcherButtons : public ImageMatch::ExactImageMatcher{ +public: + MountMatcherButtons(const char* path) + : ExactImageMatcher(make_MountMatcher2Image(path)) + {} + +}; +#endif + + + + + +class MountWyrdeerMatcher : public MountMatcher{ +public: + MountWyrdeerMatcher(bool on) + : MountMatcher( + on + ? "PokemonLA/Mounts/MountOn-Wyrdeer-Template-1.png" + : "PokemonLA/Mounts/MountOff-Wyrdeer-Template.png", + Color(0xff808000), Color(0xffffffff), 100 + ) + {} + static const MountWyrdeerMatcher& on(){ + static MountWyrdeerMatcher matcher(true); + return matcher; + } + static const MountWyrdeerMatcher& off(){ + static MountWyrdeerMatcher matcher(false); + return matcher; + } +}; +class MountUrsalunaMatcher : public MountMatcher{ +public: + MountUrsalunaMatcher(bool on) + : MountMatcher( + on + ? "PokemonLA/Mounts/MountOn-Ursaluna-Template-1.png" + : "PokemonLA/Mounts/MountOff-Ursaluna-Template.png", + Color(0xff808000), Color(0xffffffff), 100 + ) + {} + static const MountUrsalunaMatcher& on(){ + static MountUrsalunaMatcher matcher(true); + return matcher; + } + static const MountUrsalunaMatcher& off(){ + static MountUrsalunaMatcher matcher(false); + return matcher; + } +}; +class MountBasculegionMatcher : public MountMatcher{ +public: + MountBasculegionMatcher(bool on) + : MountMatcher( + on + ? "PokemonLA/Mounts/MountOn-Basculegion-Template-1.png" + : "PokemonLA/Mounts/MountOff-Basculegion-Template.png", + Color(0xff808000), Color(0xffffffff), 100 + ) + { + m_area_ratio_upper = 1.50; + } + static const MountBasculegionMatcher& on(){ + static MountBasculegionMatcher matcher(true); + return matcher; + } + static const MountBasculegionMatcher& off(){ + static MountBasculegionMatcher matcher(false); + return matcher; + } +}; +class MountSneaslerMatcher : public MountMatcher{ +public: + MountSneaslerMatcher(bool on) + : MountMatcher( + on + ? "PokemonLA/Mounts/MountOn-Sneasler-Template-1.png" + : "PokemonLA/Mounts/MountOff-Sneasler-Template.png", + Color(0xff808000), Color(0xffffffff), 100 + ) + {} + static const MountSneaslerMatcher& on(){ + static MountSneaslerMatcher matcher(true); + return matcher; + } + static const MountSneaslerMatcher& off(){ + static MountSneaslerMatcher matcher(false); + return matcher; + } +}; +class MountBraviaryMatcher : public MountMatcher{ +public: + MountBraviaryMatcher(bool on) + : MountMatcher( + on + ? "PokemonLA/Mounts/MountOn-Braviary-Template-1.png" + : "PokemonLA/Mounts/MountOff-Braviary-Template.png", + Color(0xff808000), Color(0xffffffff), 100 + ) + { + m_area_ratio_upper = 1.65; + } + static const MountBraviaryMatcher& on(){ + static MountBraviaryMatcher matcher(true); + return matcher; + } + static const MountBraviaryMatcher& off(){ + static MountBraviaryMatcher matcher(false); + return matcher; + } +}; + + + + + +class MountWyrdeerMatcherButtons : public MountMatcherButtons{ +public: + MountWyrdeerMatcherButtons(bool on) + : MountMatcherButtons(on + ? "PokemonLA/Mounts/MountOn-Wyrdeer-Template.png" + : "PokemonLA/Mounts/MountOff-Wyrdeer-Template.png" + ) + {} + static const MountWyrdeerMatcherButtons& on(){ + static MountWyrdeerMatcherButtons matcher(true); + return matcher; + } + static const MountWyrdeerMatcherButtons& off(){ + static MountWyrdeerMatcherButtons matcher(false); + return matcher; + } +}; +class MountUrsalunaMatcherButtons : public MountMatcherButtons{ +public: + MountUrsalunaMatcherButtons(bool on) + : MountMatcherButtons(on + ? "PokemonLA/Mounts/MountOn-Ursaluna-Template.png" + : "PokemonLA/Mounts/MountOff-Ursaluna-Template.png" + ) + {} + static const MountUrsalunaMatcherButtons& on(){ + static MountUrsalunaMatcherButtons matcher(true); + return matcher; + } + static const MountUrsalunaMatcherButtons& off(){ + static MountUrsalunaMatcherButtons matcher(false); + return matcher; + } +}; +class MountBasculegionMatcherButtons : public MountMatcherButtons{ +public: + MountBasculegionMatcherButtons(bool on) + : MountMatcherButtons(on + ? "PokemonLA/Mounts/MountOn-Basculegion-Template.png" + : "PokemonLA/Mounts/MountOff-Basculegion-Template.png" + ) + {} + static const MountBasculegionMatcherButtons& on(){ + static MountBasculegionMatcherButtons matcher(true); + return matcher; + } +// static const MountBasculegionMatcherButtons& off(){ +// static MountBasculegionMatcherButtons matcher(false); +// return matcher; +// } +}; +class MountSneaslerMatcherButtons : public MountMatcherButtons{ +public: + MountSneaslerMatcherButtons(bool on) + : MountMatcherButtons(on + ? "PokemonLA/Mounts/MountOn-Sneasler-Template.png" + : "PokemonLA/Mounts/MountOff-Sneasler-Template.png" + ) + {} + static const MountSneaslerMatcherButtons& on(){ + static MountSneaslerMatcherButtons matcher(true); + return matcher; + } + static const MountSneaslerMatcherButtons& off(){ + static MountSneaslerMatcherButtons matcher(false); + return matcher; + } +}; +class MountBraviaryMatcherButtons : public MountMatcherButtons{ +public: + MountBraviaryMatcherButtons(bool on) + : MountMatcherButtons(on + ? "PokemonLA/Mounts/MountOn-Braviary-Template.png" + : "PokemonLA/Mounts/MountOff-Braviary-Template.png" + ) + {} + static const MountBraviaryMatcherButtons& on(){ + static MountBraviaryMatcherButtons matcher(true); + return matcher; + } + static const MountBraviaryMatcherButtons& off(){ + static MountBraviaryMatcherButtons matcher(false); + return matcher; + } +}; + + + + +const char* MOUNT_STATE_STRINGS[] = { + "No Detection", + "Wrydeer Off", + "Wrydeer On", + "Ursaluna Off", + "Ursaluna On", + "Basculegion Off", + "Basculegion On", + "Sneasler Off", + "Sneasler On", + "Braviary Off", + "Braviary On", +}; + + +MountDetector::MountDetector(MountDetectorLogging logging) + : m_box(0.905, 0.65, 0.08, 0.13) + , m_logging(logging) +{} + +struct MountCandiateTracker{ + double m_rmsd = 1000; + MountState m_state = MountState::NOTHING; + + void add_filtered(double rmsd, MountState state){ + if (rmsd > 150 || m_rmsd <= rmsd){ + return; + } + m_rmsd = rmsd; + m_state = state; + } + void add_direct(double rmsd, MountState state){ + if (rmsd > 80 || m_rmsd <= rmsd){ + return; + } + m_rmsd = rmsd; + m_state = state; + } + void add_button_crop(double rmsd, MountState state){ + if (rmsd > 90 || m_rmsd <= rmsd){ + return; + } + m_rmsd = rmsd; + m_state = state; + } +}; + +void MountDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); +} + + +struct MountDetectorFilteredImage{ + ImageRGB32 image; + PackedBinaryMatrix matrix; +}; + +std::vector run_filters(const ImageViewRGB32& image, const std::vector>& range){ + std::vector filters; + for (size_t c = 0; c < range.size(); c++){ + filters.emplace_back( + FilterRgb32Range{ + COLOR_BLACK, false, + range[c].first, range[c].second + } + ); + } + + std::vector matrices = compress_rgb32_to_binary_range(image, range); + std::vector> filtered = filter_rgb32_range(image, filters); + + std::vector ret(range.size()); + for (size_t c = 0; c < range.size(); c++){ + ret[c].image = std::move(filtered[c].first); + ret[c].matrix = std::move(matrices[c]); + } + + return ret; +} + + +MountState MountDetector::detect(const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_box); + + MountCandiateTracker candidates; + WaterfillObject plus, arrowL, arrowR; + + // Run direct-waterfill to detect all the off-mounts. + double rmsd_plus = 99999; + double rmsd_arrowL = 99999; + double rmsd_arrowR = 99999; + auto session = make_WaterfillSession(); + { + std::vector filtered_images = run_filters( + image, + { + {0xff808060, 0xffffffff}, + {0xff909070, 0xffffffff}, + {0xffa0a080, 0xffffffff}, + {0xffb0b090, 0xffffffff}, + {0xffc0c0a0, 0xffffffff}, + {0xffd0d0b0, 0xffffffff}, + {0xffe0e0c0, 0xffffffff}, + {0xfff0f0d0, 0xffffffff}, + } + ); +// static int c = 0; + for (MountDetectorFilteredImage& filtered : filtered_images){ +// cout << filtered.matrix.dump() << endl; + session->set_source(filtered.matrix); + auto finder = session->make_iterator(50); + WaterfillObject object; +// int c = 0; + while (finder->find_next(object, false)){ +// c++; + // Skip anything that touches the borders. + if (object.min_x == 0 || object.min_y == 0 || + object.max_x - 1 == (size_t)image.width() || + object.max_y - 1 == (size_t)image.height() + ){ + continue; + } + + ImageViewRGB32 cropped = extract_box_reference(image, object); + +// cout << "object = " << c << endl; +// cropped.save("object-" + std::to_string(c) + ".png"); + + + // Read the buttons. + double current_rmsd_plus = ButtonMatcher::Plus().rmsd_precropped(cropped, object); + if (rmsd_plus > current_rmsd_plus){ + rmsd_plus = current_rmsd_plus; + plus = object; + } +// cout << "Arrow (left)" << endl; + double current_rmsd_arrowL = ButtonMatcher::ArrowLeft().rmsd_precropped(cropped, object); + if (rmsd_arrowL > current_rmsd_arrowL){ + rmsd_arrowL = current_rmsd_arrowL; + arrowL = object; + } +// cout << "Arrow (right)" << endl; + double current_rmsd_arrowR = ButtonMatcher::ArrowRight().rmsd_precropped(cropped, object); +// cout << "rmsd_arrowR = " << rmsd_arrowR << endl; + if (rmsd_arrowR > current_rmsd_arrowR){ + rmsd_arrowR = current_rmsd_arrowR; + arrowR = object; + } + + // Skip bad geometry. + if (object.width() * 2 < image.width()){ + continue; + } + if (object.height() * 3 < image.height()){ + continue; + } + + ImageViewRGB32 filtered_cropped = extract_box_reference(filtered.image, object); +#if 1 + candidates.add_filtered(MountWyrdeerMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::WYRDEER_OFF); + candidates.add_direct (MountWyrdeerMatcher ::off().rmsd_precropped(cropped , object), MountState::WYRDEER_OFF); + candidates.add_filtered(MountUrsalunaMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::URSALUNA_OFF); + candidates.add_direct (MountUrsalunaMatcher ::off().rmsd_precropped(cropped , object), MountState::URSALUNA_OFF); + candidates.add_filtered(MountBasculegionMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::BASCULEGION_OFF); + candidates.add_direct (MountBasculegionMatcher ::off().rmsd_precropped(cropped , object), MountState::BASCULEGION_OFF); + candidates.add_filtered(MountSneaslerMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::SNEASLER_OFF); + candidates.add_direct (MountSneaslerMatcher ::off().rmsd_precropped(cropped , object), MountState::SNEASLER_OFF); + candidates.add_filtered(MountBraviaryMatcher ::off().rmsd_precropped(filtered_cropped, object), MountState::BRAVIARY_OFF); + candidates.add_direct (MountBraviaryMatcher ::off().rmsd_precropped(cropped , object), MountState::BRAVIARY_OFF); +#endif + + } + } + } + +// cout << "plus = " << plus.area << endl; +// cout << "arrowL = " << arrowL.area << endl; +// cout << "arrowR = " << arrowR.area << endl; + + // No buttons detected means mounts aren't available or we're on Basculegion. + bool buttons_detected = rmsd_plus < 120 && rmsd_arrowL < 180 && rmsd_arrowR < 180; + if (!buttons_detected){ +// cout << "plus = " << rmsd_plus << ", arrowL = " << rmsd_arrowL << ", arrowR = " << rmsd_arrowR << endl; + } + + // If we detected buttons, run the detections that align to the buttons. + if (buttons_detected){ + WaterfillObject arrows = std::move(plus); + arrows.merge_assume_no_overlap(arrowL); + arrows.merge_assume_no_overlap(arrowR); + + ImageViewRGB32 cropped = extract_box_reference(image, arrows); + +// cout << "Start mounts" << endl; + +#if 1 + candidates.add_button_crop(MountWyrdeerMatcherButtons ::off().rmsd(cropped), MountState::WYRDEER_OFF); +// candidates.add_button_crop(MountBasculegionMatcherButtons::off().rmsd(cropped), MountState::URSALUNA_OFF); + candidates.add_button_crop(MountUrsalunaMatcherButtons ::off().rmsd(cropped), MountState::BASCULEGION_OFF); + candidates.add_button_crop(MountSneaslerMatcherButtons ::off().rmsd(cropped), MountState::SNEASLER_OFF); + candidates.add_button_crop(MountBraviaryMatcherButtons ::off().rmsd(cropped), MountState::BRAVIARY_OFF); + candidates.add_button_crop(MountWyrdeerMatcherButtons ::on().rmsd(cropped), MountState::WYRDEER_ON); + candidates.add_button_crop(MountBasculegionMatcherButtons::on().rmsd(cropped), MountState::URSALUNA_ON); + candidates.add_button_crop(MountUrsalunaMatcherButtons ::on().rmsd(cropped), MountState::BASCULEGION_ON); + candidates.add_button_crop(MountSneaslerMatcherButtons ::on().rmsd(cropped), MountState::SNEASLER_ON); + candidates.add_button_crop(MountBraviaryMatcherButtons ::on().rmsd(cropped), MountState::BRAVIARY_ON); +#endif + } + +#if 1 + // Now run all the direct-waterfill to detect all the yellow mounts. + { + std::vector filtered_images = run_filters( + image, + { + {0xff606000, 0xffffff7f}, + {0xff808000, 0xffffff6f}, + {0xffa0a000, 0xffffff5f}, + {0xffc0c000, 0xffffff4f}, +// {0xff606000, 0xffffffff}, +// {0xff808000, 0xffffffff}, +// {0xffa0a000, 0xffffffff}, +// {0xffc0c000, 0xffffffff}, + } + ); +// int i = 0; + for (MountDetectorFilteredImage& filtered : filtered_images){ + session->set_source(filtered.matrix); + auto finder = session->make_iterator(50); + WaterfillObject object; + while (finder->find_next(object, false)){ + // Skip anything that touches the borders. + if (object.min_x == 0 || object.min_y == 0 || + object.max_x - 1 == (size_t)image.width() || + object.max_y - 1 == (size_t)image.height() + ){ + continue; + } + if (object.width() * 2 < (size_t)image.width()){ + continue; + } + if (object.height() * 3 < (size_t)image.height()){ + continue; + } + + ImageViewRGB32 cropped = extract_box_reference(image, object); + ImageViewRGB32 filtered_cropped = extract_box_reference(filtered.image, object); +#if 1 + candidates.add_filtered(MountWyrdeerMatcher ::on().rmsd(filtered_cropped), MountState::WYRDEER_ON); + candidates.add_direct (MountWyrdeerMatcher ::on().rmsd(cropped ), MountState::WYRDEER_ON); + candidates.add_filtered(MountUrsalunaMatcher ::on().rmsd(filtered_cropped), MountState::URSALUNA_ON); + candidates.add_direct (MountUrsalunaMatcher ::on().rmsd(cropped ), MountState::URSALUNA_ON); + candidates.add_filtered(MountBasculegionMatcher ::on().rmsd(filtered_cropped), MountState::BASCULEGION_ON); + candidates.add_direct (MountBasculegionMatcher ::on().rmsd(cropped ), MountState::BASCULEGION_ON); + candidates.add_filtered(MountSneaslerMatcher ::on().rmsd(filtered_cropped), MountState::SNEASLER_ON); + candidates.add_direct (MountSneaslerMatcher ::on().rmsd(cropped ), MountState::SNEASLER_ON); + candidates.add_filtered(MountBraviaryMatcher ::on().rmsd(filtered_cropped), MountState::BRAVIARY_ON); + candidates.add_direct (MountBraviaryMatcher ::on().rmsd(cropped ), MountState::BRAVIARY_ON); +#endif +// extract_box(image, object).save("test-" + std::to_string(i) + ".png"); +// i++; + } + } +// cout << "i = " << i << endl; + } +#endif + +// cout << "Button: rmsd = " << candidates.m_rmsd << ", state = " << (int)candidates.m_state << endl; +// if (candidates.m_state == MountState::BASCULEGION_ON){ +// screen.save("basculegion-detection.png"); +// } + if (m_logging != MountDetectorLogging::NONE){ + std::cout << "MountDetector: " << MOUNT_STATE_STRINGS[(size_t)candidates.m_state] + << ", rmsd = " << candidates.m_rmsd << (buttons_detected ? " (button)" : " (no button)") << std::endl; + if (m_logging == MountDetectorLogging::LOG_AND_DUMP_FAILURES && candidates.m_state == MountState::NOTHING){ + dump_image(global_logger_tagged(), ProgramInfo(), "MountDetection", screen); + } + } + return candidates.m_state; +} + + + + + +MountTracker::MountTracker(Logger& logger, MountDetectorLogging logging) + : VisualInferenceCallback("MountTracker") + , m_logger(logger) + , m_state(MountState::NOTHING) + , m_detector(logging) +{} + +void MountTracker::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +MountState MountTracker::state() const{ + return m_state.load(std::memory_order_acquire); +} + +bool MountTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + MountState state = m_detector.detect(frame); +// cout << "state = " << (int)state << endl; + + // Clear out old history. + WallClock threshold = timestamp - std::chrono::seconds(1); + while (!m_history.empty()){ + Sample& sample = m_history.front(); + if (m_history.front().timestamp >= threshold){ + break; + } + m_counts[sample.state]--; + m_history.pop_front(); + } + + size_t& count = m_counts[state]; + m_history.emplace_back(Sample{timestamp, state}); + count++; + + // Return most reported state in the last window. + MountState best_state = MountState::NOTHING; + size_t best_count = 0; + for (const auto& item : m_counts){ + if (best_count < item.second){ + best_count = item.second; + best_state = item.first; + } + } + + MountState last_state = this->state(); + if (last_state != best_state){ + m_logger.log( + std::string("Mount changed from ") + MOUNT_STATE_STRINGS[(int)last_state] + + " to " + MOUNT_STATE_STRINGS[(int)best_state] + ".", + COLOR_PURPLE + ); + } + m_state.store(best_state, std::memory_order_release); + + return false; +} + + + + +void make_mount_template(){ + ImageRGB32 image("MountOn-Braviary-Original.png"); + + size_t width = image.width(); + size_t height = image.height(); + size_t plus_min_x = width < 29 ? 0 : width - 29; + size_t plus_max_x = width < 10 ? 0 : width - 10; + size_t plus_min_y = height < 23 ? 0 : height - 23; + size_t plus_max_y = height < 4 ? 0 : height - 4; + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + if (plus_min_x < c && c < plus_max_x && plus_min_y < r && r < plus_max_y){ + continue; + } + Color pixel(image.pixel(c, r)); + if (pixel.red() < 128 || pixel.green() < 128){ + image.pixel(c, r) = 0; + } + } + } + + image.save("MountOn-Braviary-Template.png"); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.h index 4d10391a6d..69afa931f7 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_MountDetector.h @@ -1,113 +1,113 @@ -/* Mount Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_MountDetector_H -#define PokemonAutomation_PokemonLA_MountDetector_H - -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -//#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -//#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class MountState{ - NOTHING, - WYRDEER_OFF, - WYRDEER_ON, - URSALUNA_OFF, - URSALUNA_ON, - BASCULEGION_OFF, - BASCULEGION_ON, - SNEASLER_OFF, - SNEASLER_ON, - BRAVIARY_OFF, - BRAVIARY_ON, -}; -extern const char* MOUNT_STATE_STRINGS[]; - - -enum class MountDetectorLogging{ - NONE, - LOG_ONLY, - LOG_AND_DUMP_FAILURES, -}; - -class MountDetectorLoggingOption : public EnumDropdownOption{ -public: - MountDetectorLoggingOption() - : EnumDropdownOption( - "Detection Failed Action", - { - {MountDetectorLogging::NONE, "none", "Do Nothing"}, - {MountDetectorLogging::LOG_ONLY, "log", "Log to output window."}, - {MountDetectorLogging::LOG_AND_DUMP_FAILURES, "log+dump", "Log to output window and save to file."}, - }, - LockMode::LOCK_WHILE_RUNNING, - MountDetectorLogging::LOG_AND_DUMP_FAILURES - ) - {} -}; - - - - - -class MountDetector{ -public: - MountDetector(MountDetectorLogging logging = MountDetectorLogging::NONE); - - void make_overlays(VideoOverlaySet& items) const; - MountState detect(const ImageViewRGB32& screen) const; - -private: - ImageFloatBox m_box; - MountDetectorLogging m_logging; -}; - - - -class MountTracker : public VisualInferenceCallback{ -public: - MountTracker(Logger& logger, MountDetectorLogging logging = MountDetectorLogging::NONE); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - MountState state() const; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - struct Sample{ - WallClock timestamp; - MountState state; - }; - -private: - Logger& m_logger; - std::atomic m_state; - -// SpinLock m_lock; - MountDetector m_detector; - - std::deque m_history; - std::map m_counts; -}; - - - -} -} -} -#endif +/* Mount Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_MountDetector_H +#define PokemonAutomation_PokemonLA_MountDetector_H + +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +//#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +//#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class MountState{ + NOTHING, + WYRDEER_OFF, + WYRDEER_ON, + URSALUNA_OFF, + URSALUNA_ON, + BASCULEGION_OFF, + BASCULEGION_ON, + SNEASLER_OFF, + SNEASLER_ON, + BRAVIARY_OFF, + BRAVIARY_ON, +}; +extern const char* MOUNT_STATE_STRINGS[]; + + +enum class MountDetectorLogging{ + NONE, + LOG_ONLY, + LOG_AND_DUMP_FAILURES, +}; + +class MountDetectorLoggingOption : public EnumDropdownOption{ +public: + MountDetectorLoggingOption() + : EnumDropdownOption( + "Detection Failed Action", + { + {MountDetectorLogging::NONE, "none", "Do Nothing"}, + {MountDetectorLogging::LOG_ONLY, "log", "Log to output window."}, + {MountDetectorLogging::LOG_AND_DUMP_FAILURES, "log+dump", "Log to output window and save to file."}, + }, + LockMode::LOCK_WHILE_RUNNING, + MountDetectorLogging::LOG_AND_DUMP_FAILURES + ) + {} +}; + + + + + +class MountDetector{ +public: + MountDetector(MountDetectorLogging logging = MountDetectorLogging::NONE); + + void make_overlays(VideoOverlaySet& items) const; + MountState detect(const ImageViewRGB32& screen) const; + +private: + ImageFloatBox m_box; + MountDetectorLogging m_logging; +}; + + + +class MountTracker : public VisualInferenceCallback{ +public: + MountTracker(Logger& logger, MountDetectorLogging logging = MountDetectorLogging::NONE); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + MountState state() const; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + struct Sample{ + WallClock timestamp; + MountState state; + }; + +private: + Logger& m_logger; + std::atomic m_state; + +// SpinLock m_lock; + MountDetector m_detector; + + std::deque m_history; + std::map m_counts; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.cpp index 94867de036..8be839cd3d 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.cpp @@ -1,149 +1,149 @@ -/* Notification Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonLA_NotificationReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const NotificationOCR& NotificationOCR::instance(){ - static NotificationOCR reader; - return reader; -} - -NotificationOCR::NotificationOCR() - : SmallDictionaryMatcher("PokemonLA/NotificationOCR.json") -{} - - -OCR::StringMatchResult NotificationOCR::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, - min_text_ratio, max_text_ratio - ); -} - - - - - - -NotificationReader::NotificationReader(Logger& logger, Language language) - : m_logger(logger) - , m_language(language) - , m_ocr_box(0.30, 0.138, 0.40, 0.036) -{} - -void NotificationReader::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_ocr_box); -} -Notification NotificationReader::detect(const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_ocr_box); - - - // Check if there anything that looks like text. - size_t objects = 0; - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto finder = session->make_iterator(20); - WaterfillObject object; - while (finder->find_next(object, false)){ - objects++; - } - if (objects < 20){ - return Notification::NOTHING; - } - } - - - - m_logger.log("NotificationReader: Possible text found (" + std::to_string(objects) + " objects). Attempting to read it...", COLOR_PURPLE); - - OCR::StringMatchResult results = NotificationOCR::instance().read_substring( - m_logger, m_language, image, - OCR::WHITE_TEXT_FILTERS() - ); - - if (results.results.empty()){ - return Notification::NOTHING; - } - -// cout << results.results.begin()->second.token << endl; - - static std::map MAP{ - {"distortion_forming", Notification::DISTORTION_FORMING}, - {"distortion_appeared", Notification::DISTORTION_APPEARED}, - {"distortion_faded", Notification::DISTORTION_FADED}, - {"cannot_go_farther", Notification::CANNOT_GO_FURTHER}, - }; - auto iter = MAP.find(results.results.begin()->second.token); - if (iter != MAP.end()){ - return iter->second; - } - return Notification::NOTHING; -} - - - - -NotificationDetector::NotificationDetector(Logger& logger, Language language) - : VisualInferenceCallback("NotificationDetector") - , m_reader(logger, language) - , m_last(Notification::NOTHING) - , m_last_check(WallClock::min()) -{} - -void NotificationDetector::make_overlays(VideoOverlaySet& items) const{ - m_reader.make_overlays(items); -} - -bool NotificationDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // Throttle this to 1/sec. - auto now = current_time(); - if (m_last_check + std::chrono::milliseconds(1000) > now){ - return false; - } - m_last_check = now; - - Notification result = m_reader.detect(frame); - m_last.store(result, std::memory_order_release); - return result != Notification::NOTHING; -} - - - - - - - - - - - -} -} -} +/* Notification Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonLA_NotificationReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const NotificationOCR& NotificationOCR::instance(){ + static NotificationOCR reader; + return reader; +} + +NotificationOCR::NotificationOCR() + : SmallDictionaryMatcher("PokemonLA/NotificationOCR.json") +{} + + +OCR::StringMatchResult NotificationOCR::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, + min_text_ratio, max_text_ratio + ); +} + + + + + + +NotificationReader::NotificationReader(Logger& logger, Language language) + : m_logger(logger) + , m_language(language) + , m_ocr_box(0.30, 0.138, 0.40, 0.036) +{} + +void NotificationReader::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_ocr_box); +} +Notification NotificationReader::detect(const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_ocr_box); + + + // Check if there anything that looks like text. + size_t objects = 0; + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff808080, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto finder = session->make_iterator(20); + WaterfillObject object; + while (finder->find_next(object, false)){ + objects++; + } + if (objects < 20){ + return Notification::NOTHING; + } + } + + + + m_logger.log("NotificationReader: Possible text found (" + std::to_string(objects) + " objects). Attempting to read it...", COLOR_PURPLE); + + OCR::StringMatchResult results = NotificationOCR::instance().read_substring( + m_logger, m_language, image, + OCR::WHITE_TEXT_FILTERS() + ); + + if (results.results.empty()){ + return Notification::NOTHING; + } + +// cout << results.results.begin()->second.token << endl; + + static std::map MAP{ + {"distortion_forming", Notification::DISTORTION_FORMING}, + {"distortion_appeared", Notification::DISTORTION_APPEARED}, + {"distortion_faded", Notification::DISTORTION_FADED}, + {"cannot_go_farther", Notification::CANNOT_GO_FURTHER}, + }; + auto iter = MAP.find(results.results.begin()->second.token); + if (iter != MAP.end()){ + return iter->second; + } + return Notification::NOTHING; +} + + + + +NotificationDetector::NotificationDetector(Logger& logger, Language language) + : VisualInferenceCallback("NotificationDetector") + , m_reader(logger, language) + , m_last(Notification::NOTHING) + , m_last_check(WallClock::min()) +{} + +void NotificationDetector::make_overlays(VideoOverlaySet& items) const{ + m_reader.make_overlays(items); +} + +bool NotificationDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // Throttle this to 1/sec. + auto now = current_time(); + if (m_last_check + std::chrono::milliseconds(1000) > now){ + return false; + } + m_last_check = now; + + Notification result = m_reader.detect(frame); + m_last.store(result, std::memory_order_release); + return result != Notification::NOTHING; +} + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.h index 60f1143c3a..44cd758ed1 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_NotificationReader.h @@ -1,93 +1,93 @@ -/* Notification Reader - * - * From: https://github.com/PokemonAutomation/ - * - * Read overworld notification texts like when distortion appears. - */ - -#ifndef PokemonAutomation_PokemonLA_NotificationReader_H -#define PokemonAutomation_PokemonLA_NotificationReader_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class Notification{ - NOTHING, - ERROR, - DISTORTION_FORMING, - DISTORTION_APPEARED, - DISTORTION_FADED, - CANNOT_GO_FURTHER, -}; - - - -class NotificationOCR : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -8.0; - static constexpr double MAX_LOG10P_SPREAD = 4.0; - -public: - static const NotificationOCR& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -private: - NotificationOCR(); -}; - - - -class NotificationReader{ -public: - NotificationReader(Logger& logger, Language language); - - void make_overlays(VideoOverlaySet& items) const; - Notification detect(const ImageViewRGB32& screen) const; - -private: - Logger& m_logger; - Language m_language; - ImageFloatBox m_ocr_box; -}; - - -class NotificationDetector : public VisualInferenceCallback{ -public: - NotificationDetector(Logger& logger, Language language); - - Notification result() const{ - return m_last.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - NotificationReader m_reader; - std::atomic m_last; - WallClock m_last_check; -}; - - - - - -} -} -} -#endif +/* Notification Reader + * + * From: https://github.com/PokemonAutomation/ + * + * Read overworld notification texts like when distortion appears. + */ + +#ifndef PokemonAutomation_PokemonLA_NotificationReader_H +#define PokemonAutomation_PokemonLA_NotificationReader_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class Notification{ + NOTHING, + ERROR, + DISTORTION_FORMING, + DISTORTION_APPEARED, + DISTORTION_FADED, + CANNOT_GO_FURTHER, +}; + + + +class NotificationOCR : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -8.0; + static constexpr double MAX_LOG10P_SPREAD = 4.0; + +public: + static const NotificationOCR& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +private: + NotificationOCR(); +}; + + + +class NotificationReader{ +public: + NotificationReader(Logger& logger, Language language); + + void make_overlays(VideoOverlaySet& items) const; + Notification detect(const ImageViewRGB32& screen) const; + +private: + Logger& m_logger; + Language m_language; + ImageFloatBox m_ocr_box; +}; + + +class NotificationDetector : public VisualInferenceCallback{ +public: + NotificationDetector(Logger& logger, Language language); + + Notification result() const{ + return m_last.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + NotificationReader m_reader; + std::atomic m_last; + WallClock m_last_check; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.cpp index 20699cd9a1..44522da513 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.cpp @@ -1,97 +1,97 @@ -/* Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonLA_OverworldDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -OverworldDetector::OverworldDetector(Logger& logger, VideoOverlay& overlay) - : VisualInferenceCallback("OverworldDetector") - , m_arc_phone(logger, overlay, std::chrono::milliseconds(100), true) -{} - -void OverworldDetector::make_overlays(VideoOverlaySet& items) const{ - m_arc_phone.make_overlays(items); - m_mount.make_overlays(items); -} -bool OverworldDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - m_arc_phone.process_frame(frame, timestamp); - if (!m_arc_phone.detected()){ - return false; - } - return m_mount.detect(frame) != MountState::NOTHING; -} - - - - -bool is_pokemon_selection(VideoOverlay& overlay, const ImageViewRGB32& frame){ -#if 1 - using namespace Kernels::Waterfill; - - OverlayBoxScope box(overlay, {0.83, 0.95, 0.11, 0.027}); - - std::vector matrices = compress_rgb32_to_binary_range( - extract_box_reference(frame, box), - { - {0xff008000, 0xff40ffc0}, - } - ); -// cout << matrices[0].dump() << endl; - - std::unique_ptr session = make_WaterfillSession(); - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - auto iter = session->make_iterator(200); - WaterfillObject object; - while (iter->find_next(object, false)){ - // Skip if it touches the boundary. -// cout << object.min_x << " , " << object.min_y << endl; - if (object.min_x == 0 || object.min_y == 0 || - object.min_x >= matrix.width() - 1 || object.min_y >= matrix.height() - 1 - ){ - continue; - } - - // Too short. -// cout << object.width() << " x " << object.height() << endl; - if (object.width() < object.height() * 10){ - continue; - } - - return true; - } - } - - return false; -#else - InferenceBoxScope box(overlay, 0.843, 0.96, 0.075, 0.005); - ImageStats stats = image_stats(extract_box_reference(frame, box)); - cout << stats.average << stats.stddev << endl; - extract_box_reference(frame, box).save("test.png"); - if (is_solid(stats, {0.0652401, 0.606812, 0.327948}, 0.15, 70)){ - return true; - } - return false; -#endif -} - - - - -} -} -} +/* Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonLA_OverworldDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +OverworldDetector::OverworldDetector(Logger& logger, VideoOverlay& overlay) + : VisualInferenceCallback("OverworldDetector") + , m_arc_phone(logger, overlay, std::chrono::milliseconds(100), true) +{} + +void OverworldDetector::make_overlays(VideoOverlaySet& items) const{ + m_arc_phone.make_overlays(items); + m_mount.make_overlays(items); +} +bool OverworldDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + m_arc_phone.process_frame(frame, timestamp); + if (!m_arc_phone.detected()){ + return false; + } + return m_mount.detect(frame) != MountState::NOTHING; +} + + + + +bool is_pokemon_selection(VideoOverlay& overlay, const ImageViewRGB32& frame){ +#if 1 + using namespace Kernels::Waterfill; + + OverlayBoxScope box(overlay, {0.83, 0.95, 0.11, 0.027}); + + std::vector matrices = compress_rgb32_to_binary_range( + extract_box_reference(frame, box), + { + {0xff008000, 0xff40ffc0}, + } + ); +// cout << matrices[0].dump() << endl; + + std::unique_ptr session = make_WaterfillSession(); + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + auto iter = session->make_iterator(200); + WaterfillObject object; + while (iter->find_next(object, false)){ + // Skip if it touches the boundary. +// cout << object.min_x << " , " << object.min_y << endl; + if (object.min_x == 0 || object.min_y == 0 || + object.min_x >= matrix.width() - 1 || object.min_y >= matrix.height() - 1 + ){ + continue; + } + + // Too short. +// cout << object.width() << " x " << object.height() << endl; + if (object.width() < object.height() * 10){ + continue; + } + + return true; + } + } + + return false; +#else + InferenceBoxScope box(overlay, 0.843, 0.96, 0.075, 0.005); + ImageStats stats = image_stats(extract_box_reference(frame, box)); + cout << stats.average << stats.stddev << endl; + extract_box_reference(frame, box).save("test.png"); + if (is_solid(stats, {0.0652401, 0.606812, 0.327948}, 0.15, 70)){ + return true; + } + return false; +#endif +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.h index bab91f3ca5..b4f03b12b9 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_OverworldDetector.h @@ -1,38 +1,38 @@ -/* Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_OverworldDetector_H -#define PokemonAutomation_PokemonLA_OverworldDetector_H - -#include "PokemonLA_MountDetector.h" -#include "Objects/PokemonLA_ArcPhoneDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class OverworldDetector : public VisualInferenceCallback{ -public: - OverworldDetector(Logger& logger, VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ArcPhoneDetector m_arc_phone; - MountDetector m_mount; -}; - - -// Only works at full health. -bool is_pokemon_selection(VideoOverlay& overlay, const ImageViewRGB32& frame); - - -} -} -} -#endif +/* Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_OverworldDetector_H +#define PokemonAutomation_PokemonLA_OverworldDetector_H + +#include "PokemonLA_MountDetector.h" +#include "Objects/PokemonLA_ArcPhoneDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class OverworldDetector : public VisualInferenceCallback{ +public: + OverworldDetector(Logger& logger, VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ArcPhoneDetector m_arc_phone; + MountDetector m_mount; +}; + + +// Only works at full health. +bool is_pokemon_selection(VideoOverlay& overlay, const ImageViewRGB32& frame); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.cpp index 12d2d022a3..fb74f7e5b6 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.cpp @@ -1,98 +1,98 @@ -/* Status Info Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA_CommonColorCheck.h" -#include "PokemonLA_StatusInfoScreenDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -PokemonDetails read_status_info( - Logger& logger, VideoOverlay& overlay, - const ImageViewRGB32& frame, - Language language -){ - OverlayBoxScope shiny_box(overlay, {0.726, 0.133, 0.015, 0.023}, COLOR_BLUE); - OverlayBoxScope alpha_box(overlay, {0.750, 0.133, 0.015, 0.023}, COLOR_RED); - OverlayBoxScope gender_box(overlay, {0.777, 0.138, 0.001, 0.015}, COLOR_PURPLE); - OverlayBoxScope name_box(overlay, {0.525, 0.130, 0.100, 0.038}, COLOR_BLACK); - - PokemonDetails ret; - - { - const ImageStats shiny_box_stats = image_stats(extract_box_reference(frame, shiny_box)); - // std::cout << "ImageStats " << shiny_box_stats.average << " " << shiny_box_stats.stddev << std::endl; - const auto& stddev = shiny_box_stats.stddev; - const double max_stddev = std::max(std::max(stddev.r, stddev.g), stddev.b); - if(!is_solid(shiny_box_stats, {0.333333, 0.333333, 0.333333}, 0.2, 15) || max_stddev > 8.){ - ret.is_shiny = true; - logger.log("Detected Shiny!", COLOR_BLUE); - } - } - - const ImageStats alpha_stats = image_stats(extract_box_reference(frame, alpha_box)); - if (alpha_stats.stddev.sum() > 80 && - alpha_stats.average.r > alpha_stats.average.g + 30 && - alpha_stats.average.r > alpha_stats.average.b + 30 - ){ - ret.is_alpha = true; - logger.log("Detected Alpha!", COLOR_BLUE); - } - - const ImageStats gender_stats = image_stats(extract_box_reference(frame, gender_box)); -// cout << gender_stats.average << gender_stats.stddev << endl; - if (is_solid(gender_stats, {0.333333, 0.333333, 0.333333}, 0.1, 10)){ - ret.gender = Gender::Genderless; - logger.log("Gender: Genderless"); - }else if (gender_stats.average.b > gender_stats.average.g + 30 && gender_stats.average.b > gender_stats.average.r + 30){ - ret.gender = Gender::Male; - logger.log("Gender: Male"); - }else if (gender_stats.average.r > gender_stats.average.g + 30 && gender_stats.average.r > gender_stats.average.b + 30){ - ret.gender = Gender::Female; - logger.log("Gender: Female"); - }else{ - logger.log("Gender: Unable to detect", COLOR_RED); - } - - if (language == Language::None){ - return ret; - } - - ImageViewRGB32 image = extract_box_reference(frame, name_box); - - OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( - logger, language, image, - OCR::BLACK_TEXT_FILTERS() - ); - - for (auto& item : result.results){ - ret.name_candidates.insert(std::move(item.second.token)); - } - - return ret; -} - - - - - - - -} -} -} +/* Status Info Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA_CommonColorCheck.h" +#include "PokemonLA_StatusInfoScreenDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +PokemonDetails read_status_info( + Logger& logger, VideoOverlay& overlay, + const ImageViewRGB32& frame, + Language language +){ + OverlayBoxScope shiny_box(overlay, {0.726, 0.133, 0.015, 0.023}, COLOR_BLUE); + OverlayBoxScope alpha_box(overlay, {0.750, 0.133, 0.015, 0.023}, COLOR_RED); + OverlayBoxScope gender_box(overlay, {0.777, 0.138, 0.001, 0.015}, COLOR_PURPLE); + OverlayBoxScope name_box(overlay, {0.525, 0.130, 0.100, 0.038}, COLOR_BLACK); + + PokemonDetails ret; + + { + const ImageStats shiny_box_stats = image_stats(extract_box_reference(frame, shiny_box)); + // std::cout << "ImageStats " << shiny_box_stats.average << " " << shiny_box_stats.stddev << std::endl; + const auto& stddev = shiny_box_stats.stddev; + const double max_stddev = std::max(std::max(stddev.r, stddev.g), stddev.b); + if(!is_solid(shiny_box_stats, {0.333333, 0.333333, 0.333333}, 0.2, 15) || max_stddev > 8.){ + ret.is_shiny = true; + logger.log("Detected Shiny!", COLOR_BLUE); + } + } + + const ImageStats alpha_stats = image_stats(extract_box_reference(frame, alpha_box)); + if (alpha_stats.stddev.sum() > 80 && + alpha_stats.average.r > alpha_stats.average.g + 30 && + alpha_stats.average.r > alpha_stats.average.b + 30 + ){ + ret.is_alpha = true; + logger.log("Detected Alpha!", COLOR_BLUE); + } + + const ImageStats gender_stats = image_stats(extract_box_reference(frame, gender_box)); +// cout << gender_stats.average << gender_stats.stddev << endl; + if (is_solid(gender_stats, {0.333333, 0.333333, 0.333333}, 0.1, 10)){ + ret.gender = Gender::Genderless; + logger.log("Gender: Genderless"); + }else if (gender_stats.average.b > gender_stats.average.g + 30 && gender_stats.average.b > gender_stats.average.r + 30){ + ret.gender = Gender::Male; + logger.log("Gender: Male"); + }else if (gender_stats.average.r > gender_stats.average.g + 30 && gender_stats.average.r > gender_stats.average.b + 30){ + ret.gender = Gender::Female; + logger.log("Gender: Female"); + }else{ + logger.log("Gender: Unable to detect", COLOR_RED); + } + + if (language == Language::None){ + return ret; + } + + ImageViewRGB32 image = extract_box_reference(frame, name_box); + + OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( + logger, language, image, + OCR::BLACK_TEXT_FILTERS() + ); + + for (auto& item : result.results){ + ret.name_candidates.insert(std::move(item.second.token)); + } + + return ret; +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h index 6782679424..2223ccd809 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h @@ -1,33 +1,33 @@ -/* Status Info Screen Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect shiny and alpha on the Status Info Screen in a battle. - */ - -#ifndef PokemonAutomation_PokemonLA_StatusInfoScreenDetector_H -#define PokemonAutomation_PokemonLA_StatusInfoScreenDetector_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -PokemonDetails read_status_info( - Logger& logger, VideoOverlay& overlay, - const ImageViewRGB32& frame, - Language language -); - - - - -} -} -} -#endif +/* Status Info Screen Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect shiny and alpha on the Status Info Screen in a battle. + */ + +#ifndef PokemonAutomation_PokemonLA_StatusInfoScreenDetector_H +#define PokemonAutomation_PokemonLA_StatusInfoScreenDetector_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +PokemonDetails read_status_info( + Logger& logger, VideoOverlay& overlay, + const ImageViewRGB32& frame, + Language language +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.cpp index 32d680aa18..be454462c8 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.cpp @@ -1,99 +1,99 @@ -/* Under Attack Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonLA_UnderAttackDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -const char* UNDER_ATTACK_STRINGS[] = { - "Unknown", - "Safe", - "Under Attack", -}; - - -UnderAttackWatcher::UnderAttackWatcher(Logger& logger) - : VisualInferenceCallback("UnderAttackWatcher") - , m_logger(logger) - , m_box(0.49, 0.07, 0.02, 0.03) - , m_state(UnderAttackState::UNKNOWN) -{} - -void UnderAttackWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_CYAN, m_box); -} -bool UnderAttackWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - UnderAttackState state = detect(frame); - - // Clear out old history. - WallClock threshold = timestamp - std::chrono::seconds(1); - while (!m_history.empty()){ - Sample& sample = m_history.front(); - if (m_history.front().timestamp >= threshold){ - break; - } - m_counts[sample.state]--; - m_history.pop_front(); - } - - size_t& count = m_counts[state]; - m_history.emplace_back(Sample{timestamp, state}); - count++; - - // Return most reported state in the last window. - UnderAttackState best_state = UnderAttackState::UNKNOWN; - size_t best_count = 0; - for (const auto& item : m_counts){ - if (best_count < item.second){ - best_count = item.second; - best_state = item.first; - } - } - - UnderAttackState last_state = this->state(); - if (last_state != best_state){ - m_logger.log( - std::string("State changed from ") + UNDER_ATTACK_STRINGS[(int)last_state] + - " to " + UNDER_ATTACK_STRINGS[(int)best_state] + ".", - COLOR_PURPLE - ); - } - m_state.store(best_state, std::memory_order_release); - - return false; -} - - -UnderAttackState UnderAttackWatcher::detect(const ImageViewRGB32& frame){ - ImageStats stats = image_stats(extract_box_reference(frame, m_box)); -// cout << stats.average << stats.stddev << endl; -// if (stats.stddev.sum() > 100){ -// return UnderAttackState::SAFE; -// } - if (stats.average.r < 160 || stats.average.g > 170 || stats.average.b > 130){ - return UnderAttackState::SAFE; - } - if (stats.average.r < stats.average.g * 1.4 || stats.average.r < stats.average.g * 1.8){ - return UnderAttackState::SAFE; - } -// cout << "Under attack!" << endl; - return UnderAttackState::UNDER_ATTACK; -} - - -} -} -} +/* Under Attack Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonLA_UnderAttackDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +const char* UNDER_ATTACK_STRINGS[] = { + "Unknown", + "Safe", + "Under Attack", +}; + + +UnderAttackWatcher::UnderAttackWatcher(Logger& logger) + : VisualInferenceCallback("UnderAttackWatcher") + , m_logger(logger) + , m_box(0.49, 0.07, 0.02, 0.03) + , m_state(UnderAttackState::UNKNOWN) +{} + +void UnderAttackWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_CYAN, m_box); +} +bool UnderAttackWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + UnderAttackState state = detect(frame); + + // Clear out old history. + WallClock threshold = timestamp - std::chrono::seconds(1); + while (!m_history.empty()){ + Sample& sample = m_history.front(); + if (m_history.front().timestamp >= threshold){ + break; + } + m_counts[sample.state]--; + m_history.pop_front(); + } + + size_t& count = m_counts[state]; + m_history.emplace_back(Sample{timestamp, state}); + count++; + + // Return most reported state in the last window. + UnderAttackState best_state = UnderAttackState::UNKNOWN; + size_t best_count = 0; + for (const auto& item : m_counts){ + if (best_count < item.second){ + best_count = item.second; + best_state = item.first; + } + } + + UnderAttackState last_state = this->state(); + if (last_state != best_state){ + m_logger.log( + std::string("State changed from ") + UNDER_ATTACK_STRINGS[(int)last_state] + + " to " + UNDER_ATTACK_STRINGS[(int)best_state] + ".", + COLOR_PURPLE + ); + } + m_state.store(best_state, std::memory_order_release); + + return false; +} + + +UnderAttackState UnderAttackWatcher::detect(const ImageViewRGB32& frame){ + ImageStats stats = image_stats(extract_box_reference(frame, m_box)); +// cout << stats.average << stats.stddev << endl; +// if (stats.stddev.sum() > 100){ +// return UnderAttackState::SAFE; +// } + if (stats.average.r < 160 || stats.average.g > 170 || stats.average.b > 130){ + return UnderAttackState::SAFE; + } + if (stats.average.r < stats.average.g * 1.4 || stats.average.r < stats.average.g * 1.8){ + return UnderAttackState::SAFE; + } +// cout << "Under attack!" << endl; + return UnderAttackState::UNDER_ATTACK; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.h index 45f8488239..0170500640 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_UnderAttackDetector.h @@ -1,67 +1,67 @@ -/* Under Attack Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_UnderAttackDetector_H -#define PokemonAutomation_PokemonLA_UnderAttackDetector_H - -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class UnderAttackState{ - UNKNOWN, - SAFE, - UNDER_ATTACK, -}; -extern const char* UNDER_ATTACK_STRINGS[]; - - -class UnderAttackWatcher : public VisualInferenceCallback{ -public: - -public: - UnderAttackWatcher(Logger& logger); - - UnderAttackState state() const{ - return m_state.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - UnderAttackState detect(const ImageViewRGB32& frame); - -private: - struct Sample{ - WallClock timestamp; - UnderAttackState state; - }; - - Logger& m_logger; - ImageFloatBox m_box; - - std::atomic m_state; - -// SpinLock m_lock; - std::deque m_history; - std::map m_counts; -}; - - - -} -} -} -#endif +/* Under Attack Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_UnderAttackDetector_H +#define PokemonAutomation_PokemonLA_UnderAttackDetector_H + +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class UnderAttackState{ + UNKNOWN, + SAFE, + UNDER_ATTACK, +}; +extern const char* UNDER_ATTACK_STRINGS[]; + + +class UnderAttackWatcher : public VisualInferenceCallback{ +public: + +public: + UnderAttackWatcher(Logger& logger); + + UnderAttackState state() const{ + return m_state.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + UnderAttackState detect(const ImageViewRGB32& frame); + +private: + struct Sample{ + WallClock timestamp; + UnderAttackState state; + }; + + Logger& m_logger; + ImageFloatBox m_box; + + std::atomic m_state; + +// SpinLock m_lock; + std::deque m_history; + std::map m_counts; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.cpp index 3f60e030cd..b801f37c25 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.cpp @@ -1,163 +1,163 @@ -/* Wild Pokemon Focus Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/ImageGradient.h" -#include "CommonTools/OCR/OCR_Routines.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h" -#include "PokemonLA_WildPokemonFocusDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -WildPokemonFocusDetector::WildPokemonFocusDetector(Logger& logger, VideoOverlay& overlay) - : VisualInferenceCallback("WildPokemonFocusDetector") - , m_pokemon_tab_upper_bound(0.109, 0.857, 0.24, 0.012) - , m_pokemon_tab_lower_bound(0.109, 0.949, 0.24, 0.012) - , m_pokemon_tab_left_bound(0.102, 0.875, 0.007, 0.073) - , m_pokemon_tab_right_bound(0.348, 0.873, 0.007, 0.073) -{} - -void WildPokemonFocusDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_BLUE, m_pokemon_tab_upper_bound); - items.add(COLOR_BLUE, m_pokemon_tab_lower_bound); - items.add(COLOR_BLUE, m_pokemon_tab_left_bound); - items.add(COLOR_BLUE, m_pokemon_tab_right_bound); -} - -// Return true if the inference session should stop. -bool WildPokemonFocusDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - - // dump_debug_image(m_logger, "PokemonLA/WildPokemonFocusDetector", "Received", frame); - - // float threshold = 10.0; - const Color threshold(10, 10, 10); - const ImageViewRGB32& upper_border = extract_box_reference(frame, m_pokemon_tab_upper_bound); - - const size_t upper_border_length = count_horizontal_translucent_border_pixels( - upper_border, threshold, false); - - if (upper_border_length / (float)upper_border.width() <= 0.9){ - return false; - } - - const ImageViewRGB32& lower_border = extract_box_reference(frame, m_pokemon_tab_lower_bound); - - const size_t lower_border_length = count_horizontal_translucent_border_pixels( - lower_border, threshold, true); - - if (lower_border_length / (float)lower_border.width() <= 0.9){ - return false; - } - - const ImageViewRGB32& left_border = extract_box_reference(frame, m_pokemon_tab_left_bound); - const size_t left_border_length = count_vertical_translucent_border_pixels( - left_border, threshold, false); - if (left_border_length / (float)left_border.height() <= 0.9){ - return false; - } - - const ImageViewRGB32& right_border = extract_box_reference(frame, m_pokemon_tab_right_bound); - const size_t right_border_length = count_vertical_translucent_border_pixels( - right_border, threshold, true); - if (right_border_length / (float)right_border.height() <= 0.9){ - return false; - } - - // dump_debug_image(m_logger, "PokemonLA/WildPokemonFocusDetector", "Detected", frame); - return true; -} - - -PokemonDetails read_focused_wild_pokemon_info( - Logger& logger, VideoOverlay& overlay, - const ImageViewRGB32& frame, - Language language -){ - PokemonDetails ret; - - const OverlayBoxScope name_box(overlay, {0.108, 0.868, 0.135, 0.037}, COLOR_BLACK); - const OverlayBoxScope gender_box(overlay, {0.307, 0.873, 0.016, 0.030}, COLOR_PURPLE); - const OverlayBoxScope alpha_box(overlay, {0.307, 0.920, 0.016, 0.029}, COLOR_RED); - - const ImageViewRGB32 name_image = extract_box_reference(frame, name_box); - - const OCR::StringMatchResult name_result = Pokemon::PokemonNameReader::instance().read_substring( - logger, language, name_image, - OCR::WHITE_TEXT_FILTERS()); - for (const auto& item : name_result.results){ - ret.name_candidates.insert(std::move(item.second.token)); - } - - // Replacing white color of the gender symbol with zero-alpha color so that they won't be counted in - // the following image_stats(). - // The white color is defined as the color between (160, 160, 160) and (255, 255, 255). - bool replace_color_range = true; - const ImageStats gender_stats = image_stats(filter_rgb32_range( - extract_box_reference(frame, gender_box), - combine_rgb(160, 160, 160), combine_rgb(255, 255, 255), Color(0), replace_color_range - )); - const FloatPixel gender_avg = gender_stats.average; - if (gender_stats.count > 0 && gender_avg.r > gender_avg.b + 50.0 && gender_avg.r > 150.0){ - ret.gender = Gender::Female; - logger.log("Gender Female, color " + gender_avg.to_string()); - }else if (gender_stats.count > 0 && gender_avg.b > gender_avg.r + 50.0 && gender_avg.b > 150.0){ - ret.gender = Gender::Male; - logger.log("Gender Male, color " + gender_avg.to_string()); - }else{ - ret.gender = Gender::Genderless; - logger.log("Gender Genderless, color " + gender_avg.to_string()); - } - - // Replace non-red color with zero-alpha color so that they won't be counted in - // the following image_stats(). - // The red color is defined as ranging from (200, 0, 0) to (255, 100, 100). - replace_color_range = false; - const ImageStats alpha_stats = image_stats(filter_rgb32_range( - extract_box_reference(frame, alpha_box), - combine_rgb(200, 0, 0), combine_rgb(255, 100, 100), Color(0), replace_color_range - )); - const FloatPixel alpha_avg = alpha_stats.average; - logger.log("Alpha color " + alpha_avg.to_string()); - if (alpha_stats.count > 0 && alpha_avg.r > alpha_avg.g + 100.0 && alpha_avg.r > alpha_avg.b + 100.0 && alpha_avg.r > 200.0){ - ret.is_alpha = true; - logger.log("Is alpha, color " + alpha_avg.to_string()); - } - - const std::vector shiny_locations = find_shiny_symbols(frame); - if (shiny_locations.size() > 0){ - ret.is_shiny = true; - logger.log("Found shiny symbol."); - } - - return ret; -} - - -bool detect_change_focus(Logger& logger, VideoOverlay& overlay, const ImageViewRGB32& frame){ - const bool stop_on_detect = true; - ButtonDetector button(logger, overlay, ButtonType::ButtonA, {0.244, 0.815, 0.026, 0.047}, - std::chrono::milliseconds(0), stop_on_detect); - - return button.process_frame(frame, current_time()); -} - - - -} -} -} +/* Wild Pokemon Focus Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/ImageGradient.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h" +#include "PokemonLA_WildPokemonFocusDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +WildPokemonFocusDetector::WildPokemonFocusDetector(Logger& logger, VideoOverlay& overlay) + : VisualInferenceCallback("WildPokemonFocusDetector") + , m_pokemon_tab_upper_bound(0.109, 0.857, 0.24, 0.012) + , m_pokemon_tab_lower_bound(0.109, 0.949, 0.24, 0.012) + , m_pokemon_tab_left_bound(0.102, 0.875, 0.007, 0.073) + , m_pokemon_tab_right_bound(0.348, 0.873, 0.007, 0.073) +{} + +void WildPokemonFocusDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_BLUE, m_pokemon_tab_upper_bound); + items.add(COLOR_BLUE, m_pokemon_tab_lower_bound); + items.add(COLOR_BLUE, m_pokemon_tab_left_bound); + items.add(COLOR_BLUE, m_pokemon_tab_right_bound); +} + +// Return true if the inference session should stop. +bool WildPokemonFocusDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + + // dump_debug_image(m_logger, "PokemonLA/WildPokemonFocusDetector", "Received", frame); + + // float threshold = 10.0; + const Color threshold(10, 10, 10); + const ImageViewRGB32& upper_border = extract_box_reference(frame, m_pokemon_tab_upper_bound); + + const size_t upper_border_length = count_horizontal_translucent_border_pixels( + upper_border, threshold, false); + + if (upper_border_length / (float)upper_border.width() <= 0.9){ + return false; + } + + const ImageViewRGB32& lower_border = extract_box_reference(frame, m_pokemon_tab_lower_bound); + + const size_t lower_border_length = count_horizontal_translucent_border_pixels( + lower_border, threshold, true); + + if (lower_border_length / (float)lower_border.width() <= 0.9){ + return false; + } + + const ImageViewRGB32& left_border = extract_box_reference(frame, m_pokemon_tab_left_bound); + const size_t left_border_length = count_vertical_translucent_border_pixels( + left_border, threshold, false); + if (left_border_length / (float)left_border.height() <= 0.9){ + return false; + } + + const ImageViewRGB32& right_border = extract_box_reference(frame, m_pokemon_tab_right_bound); + const size_t right_border_length = count_vertical_translucent_border_pixels( + right_border, threshold, true); + if (right_border_length / (float)right_border.height() <= 0.9){ + return false; + } + + // dump_debug_image(m_logger, "PokemonLA/WildPokemonFocusDetector", "Detected", frame); + return true; +} + + +PokemonDetails read_focused_wild_pokemon_info( + Logger& logger, VideoOverlay& overlay, + const ImageViewRGB32& frame, + Language language +){ + PokemonDetails ret; + + const OverlayBoxScope name_box(overlay, {0.108, 0.868, 0.135, 0.037}, COLOR_BLACK); + const OverlayBoxScope gender_box(overlay, {0.307, 0.873, 0.016, 0.030}, COLOR_PURPLE); + const OverlayBoxScope alpha_box(overlay, {0.307, 0.920, 0.016, 0.029}, COLOR_RED); + + const ImageViewRGB32 name_image = extract_box_reference(frame, name_box); + + const OCR::StringMatchResult name_result = Pokemon::PokemonNameReader::instance().read_substring( + logger, language, name_image, + OCR::WHITE_TEXT_FILTERS()); + for (const auto& item : name_result.results){ + ret.name_candidates.insert(std::move(item.second.token)); + } + + // Replacing white color of the gender symbol with zero-alpha color so that they won't be counted in + // the following image_stats(). + // The white color is defined as the color between (160, 160, 160) and (255, 255, 255). + bool replace_color_range = true; + const ImageStats gender_stats = image_stats(filter_rgb32_range( + extract_box_reference(frame, gender_box), + combine_rgb(160, 160, 160), combine_rgb(255, 255, 255), Color(0), replace_color_range + )); + const FloatPixel gender_avg = gender_stats.average; + if (gender_stats.count > 0 && gender_avg.r > gender_avg.b + 50.0 && gender_avg.r > 150.0){ + ret.gender = Gender::Female; + logger.log("Gender Female, color " + gender_avg.to_string()); + }else if (gender_stats.count > 0 && gender_avg.b > gender_avg.r + 50.0 && gender_avg.b > 150.0){ + ret.gender = Gender::Male; + logger.log("Gender Male, color " + gender_avg.to_string()); + }else{ + ret.gender = Gender::Genderless; + logger.log("Gender Genderless, color " + gender_avg.to_string()); + } + + // Replace non-red color with zero-alpha color so that they won't be counted in + // the following image_stats(). + // The red color is defined as ranging from (200, 0, 0) to (255, 100, 100). + replace_color_range = false; + const ImageStats alpha_stats = image_stats(filter_rgb32_range( + extract_box_reference(frame, alpha_box), + combine_rgb(200, 0, 0), combine_rgb(255, 100, 100), Color(0), replace_color_range + )); + const FloatPixel alpha_avg = alpha_stats.average; + logger.log("Alpha color " + alpha_avg.to_string()); + if (alpha_stats.count > 0 && alpha_avg.r > alpha_avg.g + 100.0 && alpha_avg.r > alpha_avg.b + 100.0 && alpha_avg.r > 200.0){ + ret.is_alpha = true; + logger.log("Is alpha, color " + alpha_avg.to_string()); + } + + const std::vector shiny_locations = find_shiny_symbols(frame); + if (shiny_locations.size() > 0){ + ret.is_shiny = true; + logger.log("Found shiny symbol."); + } + + return ret; +} + + +bool detect_change_focus(Logger& logger, VideoOverlay& overlay, const ImageViewRGB32& frame){ + const bool stop_on_detect = true; + ButtonDetector button(logger, overlay, ButtonType::ButtonA, {0.244, 0.815, 0.026, 0.047}, + std::chrono::milliseconds(0), stop_on_detect); + + return button.process_frame(frame, current_time()); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h index 73bd72f849..a71b4dba3a 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h @@ -1,60 +1,60 @@ -/* Wild Pokemon Focus Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Detect the lower left dark translucent tab when player focuses on one pokemon - */ - -#ifndef PokemonAutomation_PokemonLA_WildPokemonFocusDetector_H -#define PokemonAutomation_PokemonLA_WildPokemonFocusDetector_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" - -namespace PokemonAutomation{ - -class VideoOverlay; - -namespace NintendoSwitch{ - - -namespace PokemonLA{ - - -class WildPokemonFocusDetector : public VisualInferenceCallback{ -public: - WildPokemonFocusDetector(Logger& logger, VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true if the inference session should stop. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - // The upper bound of the transparent dark pokemon tab shown in lower left of the screen when focusing on - // one pokemon. It should the pokemon name, lv, gender, whether caught before, alpha status and shiny status. - ImageFloatBox m_pokemon_tab_upper_bound; - ImageFloatBox m_pokemon_tab_lower_bound; - ImageFloatBox m_pokemon_tab_left_bound; - ImageFloatBox m_pokemon_tab_right_bound; -}; - -// Read the pokemon details: name, alpha, shiny, gender from the focused tab. -PokemonDetails read_focused_wild_pokemon_info( - Logger& logger, VideoOverlay& overlay, - const ImageViewRGB32& frame, - Language language -); - -// Detect the A button to know whether you can press A to change focus. -bool detect_change_focus(Logger& logger, VideoOverlay& overlay, const ImageViewRGB32& frame); - - -} -} -} -#endif +/* Wild Pokemon Focus Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Detect the lower left dark translucent tab when player focuses on one pokemon + */ + +#ifndef PokemonAutomation_PokemonLA_WildPokemonFocusDetector_H +#define PokemonAutomation_PokemonLA_WildPokemonFocusDetector_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" + +namespace PokemonAutomation{ + +class VideoOverlay; + +namespace NintendoSwitch{ + + +namespace PokemonLA{ + + +class WildPokemonFocusDetector : public VisualInferenceCallback{ +public: + WildPokemonFocusDetector(Logger& logger, VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true if the inference session should stop. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + // The upper bound of the transparent dark pokemon tab shown in lower left of the screen when focusing on + // one pokemon. It should the pokemon name, lv, gender, whether caught before, alpha status and shiny status. + ImageFloatBox m_pokemon_tab_upper_bound; + ImageFloatBox m_pokemon_tab_lower_bound; + ImageFloatBox m_pokemon_tab_left_bound; + ImageFloatBox m_pokemon_tab_right_bound; +}; + +// Read the pokemon details: name, alpha, shiny, gender from the focused tab. +PokemonDetails read_focused_wild_pokemon_info( + Logger& logger, VideoOverlay& overlay, + const ImageViewRGB32& frame, + Language language +); + +// Detect the A button to know whether you can press A to change focus. +bool detect_change_focus(Logger& logger, VideoOverlay& overlay, const ImageViewRGB32& frame); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.cpp index 205179a13e..200c63babd 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.cpp @@ -1,49 +1,49 @@ -/* Alpha Music Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA_AlphaMusicDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -AlphaMusicDetector::AlphaMusicDetector(VideoStream& stream, DetectedCallback detected_callback) - // Use a red as the detection color because the alpha symbol is red. - : AudioPerSpectrumDetectorBase( - stream.logger(), - "AlphaMusicDetector", - "Alpha music", - COLOR_RED, - detected_callback - ) -{} - -float AlphaMusicDetector::get_score_threshold() const{ - return (float)GameSettings::instance().ALPHA_MUSIC_THRESHOLD; -} - -std::unique_ptr AlphaMusicDetector::build_spectrogram_matcher(size_t sample_rate){ - const double low_frequency_filter = 50.0; // we don't match frequencies under 50.0 Hz - const size_t templateSubdivision = 12; - return std::make_unique( - "Alpha Music", - AudioTemplateCache::instance().get_throw("PokemonLA/AlphaMusic", sample_rate), - SpectrogramMatcher::Mode::RAW, sample_rate, - low_frequency_filter, templateSubdivision - ); -} - - - - -} -} -} +/* Alpha Music Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA_AlphaMusicDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +AlphaMusicDetector::AlphaMusicDetector(VideoStream& stream, DetectedCallback detected_callback) + // Use a red as the detection color because the alpha symbol is red. + : AudioPerSpectrumDetectorBase( + stream.logger(), + "AlphaMusicDetector", + "Alpha music", + COLOR_RED, + detected_callback + ) +{} + +float AlphaMusicDetector::get_score_threshold() const{ + return (float)GameSettings::instance().ALPHA_MUSIC_THRESHOLD; +} + +std::unique_ptr AlphaMusicDetector::build_spectrogram_matcher(size_t sample_rate){ + const double low_frequency_filter = 50.0; // we don't match frequencies under 50.0 Hz + const size_t templateSubdivision = 12; + return std::make_unique( + "Alpha Music", + AudioTemplateCache::instance().get_throw("PokemonLA/AlphaMusic", sample_rate), + SpectrogramMatcher::Mode::RAW, sample_rate, + low_frequency_filter, templateSubdivision + ); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h index 0d698abe1e..48940e49bc 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h @@ -1,37 +1,37 @@ -/* Alpha Music Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_AlphaMusicDetector_H -#define PokemonAutomation_PokemonLA_AlphaMusicDetector_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - - -namespace PokemonAutomation{ - class SpectrogramMatcher; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class AlphaMusicDetector : public AudioPerSpectrumDetectorBase{ -public: - AlphaMusicDetector(VideoStream& stream, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - -} -} -} -#endif +/* Alpha Music Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_AlphaMusicDetector_H +#define PokemonAutomation_PokemonLA_AlphaMusicDetector_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + + +namespace PokemonAutomation{ + class SpectrogramMatcher; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class AlphaMusicDetector : public AudioPerSpectrumDetectorBase{ +public: + AlphaMusicDetector(VideoStream& stream, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.cpp index 73423ca158..7b5ec8ef6c 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.cpp @@ -1,49 +1,49 @@ -/* Alpha Roar Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA_AlphaRoarDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -AlphaRoarDetector::AlphaRoarDetector(VideoStream& stream, DetectedCallback detected_callback) - // Use a purple as the detection color because the alpha symbol is red. To differentiate with the - // detection color of alpha music, the roar (which is loud -> heavy -> darker color) uses purple. - : AudioPerSpectrumDetectorBase( - stream.logger(), - "AlphaRoarDetector", - "Alpha roar", - COLOR_PURPLE, - detected_callback - ) -{} - -float AlphaRoarDetector::get_score_threshold() const{ - return (float)GameSettings::instance().ALPHA_ROAR_THRESHOLD; -} - -std::unique_ptr AlphaRoarDetector::build_spectrogram_matcher(size_t sample_rate){ - const double low_frequency_filter = 100.0; // we don't match frequencies under 100.0 Hz - return std::make_unique( - "Alpha Roar", - AudioTemplateCache::instance().get_throw("PokemonLA/AlphaRoar", sample_rate), - SpectrogramMatcher::Mode::RAW, sample_rate, - low_frequency_filter - ); -} - - - - -} -} -} +/* Alpha Roar Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA_AlphaRoarDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +AlphaRoarDetector::AlphaRoarDetector(VideoStream& stream, DetectedCallback detected_callback) + // Use a purple as the detection color because the alpha symbol is red. To differentiate with the + // detection color of alpha music, the roar (which is loud -> heavy -> darker color) uses purple. + : AudioPerSpectrumDetectorBase( + stream.logger(), + "AlphaRoarDetector", + "Alpha roar", + COLOR_PURPLE, + detected_callback + ) +{} + +float AlphaRoarDetector::get_score_threshold() const{ + return (float)GameSettings::instance().ALPHA_ROAR_THRESHOLD; +} + +std::unique_ptr AlphaRoarDetector::build_spectrogram_matcher(size_t sample_rate){ + const double low_frequency_filter = 100.0; // we don't match frequencies under 100.0 Hz + return std::make_unique( + "Alpha Roar", + AudioTemplateCache::instance().get_throw("PokemonLA/AlphaRoar", sample_rate), + SpectrogramMatcher::Mode::RAW, sample_rate, + low_frequency_filter + ); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h index 5ed6835763..1cb053183c 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h @@ -1,35 +1,35 @@ -/* Alpha Roar Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_AlphaRoarDetector_H -#define PokemonAutomation_PokemonLA_AlphaRoarDetector_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class AlphaRoarDetector : public AudioPerSpectrumDetectorBase{ -public: - AlphaRoarDetector(VideoStream& stream, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - -} -} -} -#endif +/* Alpha Roar Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_AlphaRoarDetector_H +#define PokemonAutomation_PokemonLA_AlphaRoarDetector_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class AlphaRoarDetector : public AudioPerSpectrumDetectorBase{ +public: + AlphaRoarDetector(VideoStream& stream, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.cpp index fd05a34bcc..72dd464af7 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.cpp @@ -1,46 +1,46 @@ -/* Item Drop Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA_ItemDropSoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -ItemDropSoundDetector::ItemDropSoundDetector(VideoStream& stream, DetectedCallback detected_callback) - // Use a green as the detection color because the shiny symbol in LA is green. - : AudioPerSpectrumDetectorBase( - stream.logger(), - "ItemDropSoundDetector", - "Item drop sound", - COLOR_DARKGREEN, - detected_callback - ) -{} - - -float ItemDropSoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().ITEM_DROP_SOUND_THRESHOLD; -} - -std::unique_ptr ItemDropSoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Item Drop", - AudioTemplateCache::instance().get_throw("PokemonLA/ItemDropSound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().ITEM_DROP_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Item Drop Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA_ItemDropSoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +ItemDropSoundDetector::ItemDropSoundDetector(VideoStream& stream, DetectedCallback detected_callback) + // Use a green as the detection color because the shiny symbol in LA is green. + : AudioPerSpectrumDetectorBase( + stream.logger(), + "ItemDropSoundDetector", + "Item drop sound", + COLOR_DARKGREEN, + detected_callback + ) +{} + + +float ItemDropSoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().ITEM_DROP_SOUND_THRESHOLD; +} + +std::unique_ptr ItemDropSoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Item Drop", + AudioTemplateCache::instance().get_throw("PokemonLA/ItemDropSound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().ITEM_DROP_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h index 9bba39e928..feef30edb9 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h @@ -1,37 +1,37 @@ -/* Item Drop Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ItemDropSoundDetector_H -#define PokemonAutomation_PokemonLA_ItemDropSoundDetector_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ItemDropSoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ItemDropSoundDetector(VideoStream& stream, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Item Drop Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ItemDropSoundDetector_H +#define PokemonAutomation_PokemonLA_ItemDropSoundDetector_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ItemDropSoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ItemDropSoundDetector(VideoStream& stream, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.cpp index 342729b7aa..5e0b5c60de 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.cpp @@ -1,46 +1,46 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} - - -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; -} - -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonLA/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} + + +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; +} + +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonLA/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h index 49bc4ca45e..46a783621a 100644 --- a/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h @@ -1,36 +1,36 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ShinySoundDetector_H -#define PokemonAutomation_PokemonLA_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ShinySoundDetector_H +#define PokemonAutomation_PokemonLA_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.cpp b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.cpp index e78508b133..7a6d1fb0e2 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.cpp +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.cpp @@ -1,263 +1,263 @@ -/* Battle Pokemon Action Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -//#include "Common/Compiler.h" -//#include "Common/Cpp/Json/JsonValue.h" -//#include "Common/Cpp/Json/JsonObject.h" -//#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_BattlePokemonActionTable.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -const EnumDropdownDatabase& MoveStyle_Database(){ - static const EnumDropdownDatabase database({ - {MoveStyle::NoStyle, "none", "No Style"}, - {MoveStyle::Agile, "agile", "Agile"}, - {MoveStyle::Strong, "strong", "Strong"}, - }); - return database; -} - - - - -BattlePokemonActionRow::BattlePokemonActionRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , switch_pokemon(LockMode::LOCK_WHILE_RUNNING, false) - , num_turns_to_switch(LockMode::LOCK_WHILE_RUNNING, 1) - , stop_after_num_moves(LockMode::LOCK_WHILE_RUNNING, false) - , num_moves_to_stop(LockMode::LOCK_WHILE_RUNNING, 25, 0) -{ - PA_ADD_OPTION(style[0]); - PA_ADD_OPTION(style[1]); - PA_ADD_OPTION(style[2]); - PA_ADD_OPTION(style[3]); - PA_ADD_OPTION(switch_pokemon); - PA_ADD_OPTION(num_turns_to_switch); - PA_ADD_OPTION(stop_after_num_moves); - PA_ADD_OPTION(num_moves_to_stop); -} -std::unique_ptr BattlePokemonActionRow::clone() const{ - std::unique_ptr ret(new BattlePokemonActionRow(parent())); - ret->style[0].set(style[0]); - ret->style[1].set(style[1]); - ret->style[2].set(style[2]); - ret->style[3].set(style[3]); - ret->switch_pokemon = (bool)switch_pokemon; - ret->num_turns_to_switch.set(num_turns_to_switch); - ret->stop_after_num_moves = (bool)stop_after_num_moves; - ret->num_moves_to_stop.set(num_moves_to_stop); - return ret; -} - - -std::vector> BattlePokemonActionTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} -BattlePokemonActionTable::BattlePokemonActionTable() - : EditableTableOption_t( - "" + STRING_POKEMON + " Action Table:
" - "Set what move styles to use and whether to switch the " + STRING_POKEMON + " after some turns.

" - "Each row is the action for one " + STRING_POKEMON + ". " - "The table follows the order that " + STRING_POKEMON + " are sent to battle.
" - "You can also set a target number of move attempts. After it is reached the program will finish the battle and stop.

" - "Note: if your second last " + STRING_POKEMON + " faints, the game will send your last " + STRING_POKEMON + " automatically for you.
" - "The program cannot detect this switch as there is no switch selection screen. " - "Therefore the program will treat it as the same " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} -std::vector BattlePokemonActionTable::make_header() const{ - return std::vector{ - "Move 1 Style", - "Move 2 Style", - "Move 3 Style", - "Move 4 Style", - "Switch " + STRING_POKEMON, - "Num Turns to Switch", - "Limit Move Attempts", - "Max Move Attempts", - }; -} -MoveStyle BattlePokemonActionTable::get_style(size_t pokemon, size_t move) const{ - std::vector> table = copy_snapshot(); - if (pokemon >= table.size()){ - return MoveStyle::NoStyle; - } - - const BattlePokemonActionRow& action = *table[pokemon]; - return action.style[move]; -} -bool BattlePokemonActionTable::switch_pokemon(size_t pokemon, size_t num_turns) const{ - std::vector> table = copy_snapshot(); - if (pokemon >= table.size()){ - return false; - } - - const BattlePokemonActionRow& action = *table[pokemon]; - return action.switch_pokemon && num_turns >= (size_t)action.num_turns_to_switch; -} -bool BattlePokemonActionTable::stop_battle(size_t pokemon, size_t num_move_attempts) const{ - std::vector> table = copy_snapshot(); - if (pokemon >= table.size()){ - return false; - } - - const BattlePokemonActionRow& action = *table[pokemon]; - return action.stop_after_num_moves && num_move_attempts >= (size_t)action.num_moves_to_stop; -} - - - - - - - - - - - -OneMoveBattlePokemonActionRow::OneMoveBattlePokemonActionRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) -{ - PA_ADD_OPTION(style); -} -std::unique_ptr OneMoveBattlePokemonActionRow::clone() const{ - std::unique_ptr ret(new OneMoveBattlePokemonActionRow(parent())); - ret->style.set(style); - return ret; -} - -std::vector> OneMoveBattlePokemonActionTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} -OneMoveBattlePokemonActionTable::OneMoveBattlePokemonActionTable() - : EditableTableOption_t( - "" + STRING_POKEMON + " Action Table:
" - "Set what move style to use for each " + STRING_POKEMON + " to grind against a Magikarp. " - "Each row is the action for one " + STRING_POKEMON + ". " - "The table follows the order that " + STRING_POKEMON + " are sent to battle.", - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} -std::vector OneMoveBattlePokemonActionTable::make_header() const{ - return std::vector{ - "Move Style", - }; -} -MoveStyle OneMoveBattlePokemonActionTable::get_style(size_t pokemon){ - std::vector> table = copy_snapshot(); - if (pokemon >= table.size()){ - return MoveStyle::NoStyle; - } - const OneMoveBattlePokemonActionRow& action = *table[pokemon]; - return action.style; -} - - - - - - - -const IntegerEnumDropdownDatabase& PokemonIndex_Database(){ - static const IntegerEnumDropdownDatabase database({ - {0, "1st", "1st " + STRING_POKEMON}, - {1, "2nd", "2nd " + STRING_POKEMON}, - {2, "3rd", "3rd " + STRING_POKEMON}, - {3, "4th", "4th " + STRING_POKEMON}, - }); - return database; -} -const IntegerEnumDropdownDatabase& MoveIndex_Database(){ - static const IntegerEnumDropdownDatabase database({ - {0, "1st", "1st Move"}, - {1, "2nd", "2nd Move"}, - {2, "3rd", "3rd Move"}, - {3, "4th", "4th Move"}, - }); - return database; -} - - - -MoveGrinderActionRow::MoveGrinderActionRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , pokemon_index(PokemonIndex_Database(), LockMode::LOCK_WHILE_RUNNING, 0) - , move_index(MoveIndex_Database(), LockMode::LOCK_WHILE_RUNNING, 0) - , attempts(LockMode::LOCK_WHILE_RUNNING, 1, 1) -{ - PA_ADD_OPTION(pokemon_index); - PA_ADD_OPTION(move_index); - PA_ADD_OPTION(style); - PA_ADD_OPTION(attempts); -} -std::unique_ptr MoveGrinderActionRow::clone() const{ - std::unique_ptr ret(new MoveGrinderActionRow(parent())); - ret->pokemon_index.set_value(pokemon_index.current_value()); - ret->move_index.set_value(move_index.current_value()); - ret->style.set(style); - ret->attempts.set(attempts); - return ret; -} - -MoveGrinderActionTable::MoveGrinderActionTable() - : EditableTableOption_t( - "For every move you want to perform, input the style and the number of attempts you want to achieve.", - LockMode::LOCK_WHILE_RUNNING - ) -{} -Move MoveGrinderActionTable::get_move(size_t pokemon, size_t move) const{ - // Pokemon index 4 is gonna be Arceus with powerful moves, just use them with normal style and hope you'll win the battle - if (pokemon == 4){ - return {MoveStyle::NoStyle, std::numeric_limits::max()}; - - } - std::vector> table = copy_snapshot(); - for (size_t i = 0; i < table.size(); ++i){ - const MoveGrinderActionRow& action = *table[i]; - if (action.pokemon_index.current_value() != pokemon){ - continue; - } - if (action.move_index.current_value() != move){ - continue; - } - return {action.style , action.attempts}; - } - return {MoveStyle::NoStyle, 0}; -} -std::vector MoveGrinderActionTable::make_header() const{ - return std::vector{ - "Pokemon index", - "Move index", - "Move Style", - "Move Attempts", - }; -} - - - - -} -} -} +/* Battle Pokemon Action Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include "Common/Compiler.h" +//#include "Common/Cpp/Json/JsonValue.h" +//#include "Common/Cpp/Json/JsonObject.h" +//#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_BattlePokemonActionTable.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +const EnumDropdownDatabase& MoveStyle_Database(){ + static const EnumDropdownDatabase database({ + {MoveStyle::NoStyle, "none", "No Style"}, + {MoveStyle::Agile, "agile", "Agile"}, + {MoveStyle::Strong, "strong", "Strong"}, + }); + return database; +} + + + + +BattlePokemonActionRow::BattlePokemonActionRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , switch_pokemon(LockMode::LOCK_WHILE_RUNNING, false) + , num_turns_to_switch(LockMode::LOCK_WHILE_RUNNING, 1) + , stop_after_num_moves(LockMode::LOCK_WHILE_RUNNING, false) + , num_moves_to_stop(LockMode::LOCK_WHILE_RUNNING, 25, 0) +{ + PA_ADD_OPTION(style[0]); + PA_ADD_OPTION(style[1]); + PA_ADD_OPTION(style[2]); + PA_ADD_OPTION(style[3]); + PA_ADD_OPTION(switch_pokemon); + PA_ADD_OPTION(num_turns_to_switch); + PA_ADD_OPTION(stop_after_num_moves); + PA_ADD_OPTION(num_moves_to_stop); +} +std::unique_ptr BattlePokemonActionRow::clone() const{ + std::unique_ptr ret(new BattlePokemonActionRow(parent())); + ret->style[0].set(style[0]); + ret->style[1].set(style[1]); + ret->style[2].set(style[2]); + ret->style[3].set(style[3]); + ret->switch_pokemon = (bool)switch_pokemon; + ret->num_turns_to_switch.set(num_turns_to_switch); + ret->stop_after_num_moves = (bool)stop_after_num_moves; + ret->num_moves_to_stop.set(num_moves_to_stop); + return ret; +} + + +std::vector> BattlePokemonActionTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} +BattlePokemonActionTable::BattlePokemonActionTable() + : EditableTableOption_t( + "" + STRING_POKEMON + " Action Table:
" + "Set what move styles to use and whether to switch the " + STRING_POKEMON + " after some turns.

" + "Each row is the action for one " + STRING_POKEMON + ". " + "The table follows the order that " + STRING_POKEMON + " are sent to battle.
" + "You can also set a target number of move attempts. After it is reached the program will finish the battle and stop.

" + "Note: if your second last " + STRING_POKEMON + " faints, the game will send your last " + STRING_POKEMON + " automatically for you.
" + "The program cannot detect this switch as there is no switch selection screen. " + "Therefore the program will treat it as the same " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} +std::vector BattlePokemonActionTable::make_header() const{ + return std::vector{ + "Move 1 Style", + "Move 2 Style", + "Move 3 Style", + "Move 4 Style", + "Switch " + STRING_POKEMON, + "Num Turns to Switch", + "Limit Move Attempts", + "Max Move Attempts", + }; +} +MoveStyle BattlePokemonActionTable::get_style(size_t pokemon, size_t move) const{ + std::vector> table = copy_snapshot(); + if (pokemon >= table.size()){ + return MoveStyle::NoStyle; + } + + const BattlePokemonActionRow& action = *table[pokemon]; + return action.style[move]; +} +bool BattlePokemonActionTable::switch_pokemon(size_t pokemon, size_t num_turns) const{ + std::vector> table = copy_snapshot(); + if (pokemon >= table.size()){ + return false; + } + + const BattlePokemonActionRow& action = *table[pokemon]; + return action.switch_pokemon && num_turns >= (size_t)action.num_turns_to_switch; +} +bool BattlePokemonActionTable::stop_battle(size_t pokemon, size_t num_move_attempts) const{ + std::vector> table = copy_snapshot(); + if (pokemon >= table.size()){ + return false; + } + + const BattlePokemonActionRow& action = *table[pokemon]; + return action.stop_after_num_moves && num_move_attempts >= (size_t)action.num_moves_to_stop; +} + + + + + + + + + + + +OneMoveBattlePokemonActionRow::OneMoveBattlePokemonActionRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) +{ + PA_ADD_OPTION(style); +} +std::unique_ptr OneMoveBattlePokemonActionRow::clone() const{ + std::unique_ptr ret(new OneMoveBattlePokemonActionRow(parent())); + ret->style.set(style); + return ret; +} + +std::vector> OneMoveBattlePokemonActionTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} +OneMoveBattlePokemonActionTable::OneMoveBattlePokemonActionTable() + : EditableTableOption_t( + "" + STRING_POKEMON + " Action Table:
" + "Set what move style to use for each " + STRING_POKEMON + " to grind against a Magikarp. " + "Each row is the action for one " + STRING_POKEMON + ". " + "The table follows the order that " + STRING_POKEMON + " are sent to battle.", + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} +std::vector OneMoveBattlePokemonActionTable::make_header() const{ + return std::vector{ + "Move Style", + }; +} +MoveStyle OneMoveBattlePokemonActionTable::get_style(size_t pokemon){ + std::vector> table = copy_snapshot(); + if (pokemon >= table.size()){ + return MoveStyle::NoStyle; + } + const OneMoveBattlePokemonActionRow& action = *table[pokemon]; + return action.style; +} + + + + + + + +const IntegerEnumDropdownDatabase& PokemonIndex_Database(){ + static const IntegerEnumDropdownDatabase database({ + {0, "1st", "1st " + STRING_POKEMON}, + {1, "2nd", "2nd " + STRING_POKEMON}, + {2, "3rd", "3rd " + STRING_POKEMON}, + {3, "4th", "4th " + STRING_POKEMON}, + }); + return database; +} +const IntegerEnumDropdownDatabase& MoveIndex_Database(){ + static const IntegerEnumDropdownDatabase database({ + {0, "1st", "1st Move"}, + {1, "2nd", "2nd Move"}, + {2, "3rd", "3rd Move"}, + {3, "4th", "4th Move"}, + }); + return database; +} + + + +MoveGrinderActionRow::MoveGrinderActionRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , pokemon_index(PokemonIndex_Database(), LockMode::LOCK_WHILE_RUNNING, 0) + , move_index(MoveIndex_Database(), LockMode::LOCK_WHILE_RUNNING, 0) + , attempts(LockMode::LOCK_WHILE_RUNNING, 1, 1) +{ + PA_ADD_OPTION(pokemon_index); + PA_ADD_OPTION(move_index); + PA_ADD_OPTION(style); + PA_ADD_OPTION(attempts); +} +std::unique_ptr MoveGrinderActionRow::clone() const{ + std::unique_ptr ret(new MoveGrinderActionRow(parent())); + ret->pokemon_index.set_value(pokemon_index.current_value()); + ret->move_index.set_value(move_index.current_value()); + ret->style.set(style); + ret->attempts.set(attempts); + return ret; +} + +MoveGrinderActionTable::MoveGrinderActionTable() + : EditableTableOption_t( + "For every move you want to perform, input the style and the number of attempts you want to achieve.", + LockMode::LOCK_WHILE_RUNNING + ) +{} +Move MoveGrinderActionTable::get_move(size_t pokemon, size_t move) const{ + // Pokemon index 4 is gonna be Arceus with powerful moves, just use them with normal style and hope you'll win the battle + if (pokemon == 4){ + return {MoveStyle::NoStyle, std::numeric_limits::max()}; + + } + std::vector> table = copy_snapshot(); + for (size_t i = 0; i < table.size(); ++i){ + const MoveGrinderActionRow& action = *table[i]; + if (action.pokemon_index.current_value() != pokemon){ + continue; + } + if (action.move_index.current_value() != move){ + continue; + } + return {action.style , action.attempts}; + } + return {MoveStyle::NoStyle, 0}; +} +std::vector MoveGrinderActionTable::make_header() const{ + return std::vector{ + "Pokemon index", + "Move index", + "Move Style", + "Move Attempts", + }; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h index 1f76a82de1..e71f10381e 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h @@ -1,166 +1,166 @@ -/* Battle Pokemon Action Table - * - * From: https://github.com/PokemonAutomation/ - * - * Tables to set moves and switching during battle. - * - */ - -#ifndef PokemonAutomation_PokemonLA_BattlePokemonActionTable_H -#define PokemonAutomation_PokemonLA_BattlePokemonActionTable_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class MoveStyle{ - NoStyle, - Agile, - Strong, -}; -const EnumDropdownDatabase& MoveStyle_Database(); - - - -class MoveStyleCell : public EnumDropdownCell{ -public: - MoveStyleCell() - : EnumDropdownCell( - MoveStyle_Database(), - LockMode::LOCK_WHILE_RUNNING, - MoveStyle::NoStyle - ) - {} -}; - - - - -// A program option about which pokemon to use which move styles during battle, and whether to switch out -// after some turns. -// This table option is used in IngoBattleGrinder program to set the action of each pokemon sent out to -// battle. -// The pokemon order is defined as the order they are sent onto the battle. - -class BattlePokemonActionRow : public EditableTableRow{ -public: - BattlePokemonActionRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - MoveStyleCell style[4]; - BooleanCheckBoxCell switch_pokemon; - SimpleIntegerCell num_turns_to_switch; - BooleanCheckBoxCell stop_after_num_moves; - SimpleIntegerCell num_moves_to_stop; -}; - -class BattlePokemonActionTable : public EditableTableOption_t{ -public: - BattlePokemonActionTable(); - - // Get which style to use according to the info in the table. - // pokemon: pokemon index, usually at range [0, 5] - // move: move index, range [0, 3] - MoveStyle get_style(size_t pokemon, size_t move) const; - - // Whether to switch the pokemon at current turns. - // pokemon: pokemon index, usually at range [0, 5] - // num_turns: num turns passed so far since the pokemon is sent to the battle. - bool switch_pokemon(size_t pokemon, size_t num_turns) const; - // Whether to stop battling after a certain number of move attempts are made on - // a pokemon. - // pokemon: pokemon index, usually at range [0, 5] - // num_move_attempts: number of move attempts made from this pokemon so far. - bool stop_battle(size_t pokemon, size_t num_move_attempts) const; - -private: - virtual std::vector make_header() const; - std::vector> make_defaults(); -}; - - - - - -// A program option used by MagikarpMoveGrinder. To easily grind pokemon moves against a Magikarp which -// only knows Splash. -// Each row in the table option sets which style the first move of a pokemon to use on the Magikarp. -// Since it's most efficient to grind non-damaging moves on Magikarp, the program is designed to grind -// only non-damaging moves. There are not many pokemon whose pokedex researches require grinding more -// than one non-damaging moves, so the program only grinds one move (the first move) per pokemon. -// The pokemon order is defined as the order they are sent onto the battle. - -// Used by MagikarpMoveGrinder, for each pokemon, set what style the first move to use -class OneMoveBattlePokemonActionRow : public EditableTableRow{ -public: - OneMoveBattlePokemonActionRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - MoveStyleCell style; -}; - -class OneMoveBattlePokemonActionTable : public EditableTableOption_t{ -public: - OneMoveBattlePokemonActionTable(); - - size_t num_pokemon() const{ return current_rows(); } - - // Get which style to use according to the info in the table. - // pokemon: pokemon index, range [0, 5] - MoveStyle get_style(size_t pokemon); - -private: - virtual std::vector make_header() const; - std::vector> make_defaults(); -}; - - - - - - -class MoveGrinderActionRow : public EditableTableRow{ -public: - MoveGrinderActionRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - IntegerEnumDropdownCell pokemon_index; - IntegerEnumDropdownCell move_index; - MoveStyleCell style; - SimpleIntegerCell attempts; -}; - -struct Move{ - MoveStyle style; - uint16_t attempts; -}; - -class MoveGrinderActionTable : public EditableTableOption_t{ -public: - MoveGrinderActionTable(); - - Move get_move(size_t pokemon, size_t move) const; - -private: - virtual std::vector make_header() const; -}; - - - - - - - -} -} -} -#endif +/* Battle Pokemon Action Table + * + * From: https://github.com/PokemonAutomation/ + * + * Tables to set moves and switching during battle. + * + */ + +#ifndef PokemonAutomation_PokemonLA_BattlePokemonActionTable_H +#define PokemonAutomation_PokemonLA_BattlePokemonActionTable_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class MoveStyle{ + NoStyle, + Agile, + Strong, +}; +const EnumDropdownDatabase& MoveStyle_Database(); + + + +class MoveStyleCell : public EnumDropdownCell{ +public: + MoveStyleCell() + : EnumDropdownCell( + MoveStyle_Database(), + LockMode::LOCK_WHILE_RUNNING, + MoveStyle::NoStyle + ) + {} +}; + + + + +// A program option about which pokemon to use which move styles during battle, and whether to switch out +// after some turns. +// This table option is used in IngoBattleGrinder program to set the action of each pokemon sent out to +// battle. +// The pokemon order is defined as the order they are sent onto the battle. + +class BattlePokemonActionRow : public EditableTableRow{ +public: + BattlePokemonActionRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + MoveStyleCell style[4]; + BooleanCheckBoxCell switch_pokemon; + SimpleIntegerCell num_turns_to_switch; + BooleanCheckBoxCell stop_after_num_moves; + SimpleIntegerCell num_moves_to_stop; +}; + +class BattlePokemonActionTable : public EditableTableOption_t{ +public: + BattlePokemonActionTable(); + + // Get which style to use according to the info in the table. + // pokemon: pokemon index, usually at range [0, 5] + // move: move index, range [0, 3] + MoveStyle get_style(size_t pokemon, size_t move) const; + + // Whether to switch the pokemon at current turns. + // pokemon: pokemon index, usually at range [0, 5] + // num_turns: num turns passed so far since the pokemon is sent to the battle. + bool switch_pokemon(size_t pokemon, size_t num_turns) const; + // Whether to stop battling after a certain number of move attempts are made on + // a pokemon. + // pokemon: pokemon index, usually at range [0, 5] + // num_move_attempts: number of move attempts made from this pokemon so far. + bool stop_battle(size_t pokemon, size_t num_move_attempts) const; + +private: + virtual std::vector make_header() const; + std::vector> make_defaults(); +}; + + + + + +// A program option used by MagikarpMoveGrinder. To easily grind pokemon moves against a Magikarp which +// only knows Splash. +// Each row in the table option sets which style the first move of a pokemon to use on the Magikarp. +// Since it's most efficient to grind non-damaging moves on Magikarp, the program is designed to grind +// only non-damaging moves. There are not many pokemon whose pokedex researches require grinding more +// than one non-damaging moves, so the program only grinds one move (the first move) per pokemon. +// The pokemon order is defined as the order they are sent onto the battle. + +// Used by MagikarpMoveGrinder, for each pokemon, set what style the first move to use +class OneMoveBattlePokemonActionRow : public EditableTableRow{ +public: + OneMoveBattlePokemonActionRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + MoveStyleCell style; +}; + +class OneMoveBattlePokemonActionTable : public EditableTableOption_t{ +public: + OneMoveBattlePokemonActionTable(); + + size_t num_pokemon() const{ return current_rows(); } + + // Get which style to use according to the info in the table. + // pokemon: pokemon index, range [0, 5] + MoveStyle get_style(size_t pokemon); + +private: + virtual std::vector make_header() const; + std::vector> make_defaults(); +}; + + + + + + +class MoveGrinderActionRow : public EditableTableRow{ +public: + MoveGrinderActionRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + IntegerEnumDropdownCell pokemon_index; + IntegerEnumDropdownCell move_index; + MoveStyleCell style; + SimpleIntegerCell attempts; +}; + +struct Move{ + MoveStyle style; + uint16_t attempts; +}; + +class MoveGrinderActionTable : public EditableTableOption_t{ +public: + MoveGrinderActionTable(); + + Move get_move(size_t pokemon, size_t move) const; + +private: + virtual std::vector make_header() const; +}; + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.cpp b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.cpp index 866aa41fd8..38cc2757fa 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.cpp +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.cpp @@ -1,445 +1,445 @@ -/* Battle Pokemon Action Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include - -//#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -//#include "Common/Cpp/Json/JsonTools.h" -#include "Common/Qt/Options/ConfigWidget.h" -//#include "CommonFramework/Globals.h" -#include "PokemonLA_CustomPathTable.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace std::chrono_literals; - - - - -const EnumDropdownDatabase& PathAction_Database(){ - static const EnumDropdownDatabase database({ - {PathAction::NO_ACTION, "no-action", "NO Action"}, - {PathAction::CHANGE_MOUNT, "change-mount", "Change Mount"}, - {PathAction::MOVE_FORWARD, "move-forward", "Move Forward"}, - {PathAction::MOVE_IN_DIRECTION, "move-in-direction", "Move in Direction"}, - {PathAction::CENTER_CAMERA, "center-camera", "Center Camera"}, - {PathAction::JUMP, "jump", "Jump"}, - {PathAction::WAIT, "wait", "Wait"}, - {PathAction::START_LISTEN, "start-listen", "Start Listen"}, - {PathAction::END_LISTEN, "end-listen", "End Listen"} - }); - return database; -} -const EnumDropdownDatabase& PathMount_Database(){ - static const EnumDropdownDatabase database({ - {PathMount::NO_MOUNT, "none", "No Mount"}, - {PathMount::WYRDEER, "wrydeer", "Wrydeer"}, - {PathMount::URSALUNA, "ursaluna", "Ursaluna"}, - {PathMount::BASCULEGION, "basculegion", "Basculegion"}, - {PathMount::SNEASLER, "sneasler", "Sneasler"}, - {PathMount::BRAVIARY, "braviary", "Braviary"}, - }); - return database; -} -const EnumDropdownDatabase& PathSpeed_Database(){ - static const EnumDropdownDatabase database({ - {PathSpeed::NORMAL_SPEED, "normal", "Normal Speed"}, - {PathSpeed::SLOW_SPEED, "slow", "Slow Speed"}, - {PathSpeed::RUN, "run", "Run on Foot"}, - {PathSpeed::DASH, "dash", "Dash on Ride"}, - {PathSpeed::DASH_B_SPAM, "mash-b", "Dash on Braviary B Spam"}, - {PathSpeed::DIVE, "dive", "Dive on Braviary"}, - }); - return database; -} - - - - - -CustomPathCell::~CustomPathCell(){ - m_action.remove_listener(*this); -} -void CustomPathCell::operator=(const CustomPathCell& x){ - text.set_text(x.text.text()); - mount.set(x.mount); - move_forward.set(x.move_forward.current_text()); - move_speed.set(x.move_speed); - left_x.set(x.left_x); - left_y.set(x.left_y); - jump_wait.set(x.jump_wait.current_text()); - wait.set(x.wait.current_text()); -} -CustomPathCell::CustomPathCell(EnumDropdownCell& action) - : BatchOption(LockMode::LOCK_WHILE_RUNNING, true) - , m_action(action) - , text("", false) - , mount(PathMount_Database(), LockMode::LOCK_WHILE_RUNNING, PathMount::NO_MOUNT) - , move_forward( - "Duration (ms):", false, - LockMode::LOCK_WHILE_RUNNING, - 0ms, Milliseconds::max(), - "2000 ms" - ) - , move_speed(PathSpeed_Database(), LockMode::LOCK_WHILE_RUNNING,PathSpeed::NORMAL_SPEED) - , left_x("x: [left: -1.0, right: 1.0]", LockMode::LOCK_WHILE_RUNNING, 0, -1.0, 1.0) - , left_y("y: [backward: -1.0, forward: 1.0]", LockMode::LOCK_WHILE_RUNNING, 0, -1.0, 1.0) - , jump_wait( - "Wait after jump (ms):", false, - LockMode::LOCK_WHILE_RUNNING, - 0ms, Milliseconds::max(), - "2000 ms" - ) - , wait( - "Wait Time (ms):", false, - LockMode::LOCK_WHILE_RUNNING, - 0ms, Milliseconds::max(), - "2000 ms" - ) -{ - PA_ADD_STATIC(text); - PA_ADD_OPTION(mount); - PA_ADD_OPTION(move_forward); - PA_ADD_OPTION(move_speed); - PA_ADD_OPTION(left_x); - PA_ADD_OPTION(left_y); - PA_ADD_OPTION(jump_wait); - PA_ADD_OPTION(wait); - - CustomPathCell::on_config_value_changed(this); - action.add_listener(*this); -} -void CustomPathCell::on_config_value_changed(void* object){ - text.set_visibility(ConfigOptionState::HIDDEN); - mount.set_visibility(ConfigOptionState::HIDDEN); - move_forward.set_visibility(ConfigOptionState::HIDDEN); - move_speed.set_visibility(ConfigOptionState::HIDDEN); - left_x.set_visibility(ConfigOptionState::HIDDEN); - left_y.set_visibility(ConfigOptionState::HIDDEN); - jump_wait.set_visibility(ConfigOptionState::HIDDEN); - wait.set_visibility(ConfigOptionState::HIDDEN); - switch (m_action){ - case PathAction::NO_ACTION: - break; - case PathAction::CHANGE_MOUNT: - mount.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::MOVE_FORWARD: - move_forward.set_visibility(ConfigOptionState::ENABLED); - move_speed.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::MOVE_IN_DIRECTION: - move_forward.set_visibility(ConfigOptionState::ENABLED); - left_x.set_visibility(ConfigOptionState::ENABLED); - left_y.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::CENTER_CAMERA: - text.set_text("Center the camera so that you can move straight forward."); - text.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::JUMP: - jump_wait.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::WAIT: - wait.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::START_LISTEN: - text.set_text("If shiny detected, use \"Destination Shiny Action\"."); - text.set_visibility(ConfigOptionState::ENABLED); - break; - case PathAction::END_LISTEN: - text.set_text("If shiny detected, use \"Enroute Shiny Action\"."); - text.set_visibility(ConfigOptionState::ENABLED); - break; - default: - break; - } -} - - - - -CustomPathTableRow2::CustomPathTableRow2(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , action(PathAction_Database(), LockMode::LOCK_WHILE_RUNNING, PathAction::NO_ACTION) - , parameters(action) -{ - PA_ADD_OPTION(action); - PA_ADD_OPTION(parameters); -} -std::unique_ptr CustomPathTableRow2::clone() const{ - std::unique_ptr ret(new CustomPathTableRow2(parent())); - ret->action.set(action); - ret->parameters = parameters; - return ret; -} -void CustomPathTableRow2::load_json(const JsonValue& json){ - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - const JsonValue* value = obj->get_value("Action"); - if (value == nullptr){ - return; - } - action.load_json(*value); - - switch(action){ - case PathAction::CHANGE_MOUNT: - value = obj->get_value("Mount"); - if (value != nullptr){ - parameters.mount.load_json(*value); - } - break; - case PathAction::MOVE_FORWARD: - value = obj->get_value("MoveForwardTicks"); - if (value != nullptr && value->is_integer()){ - parameters.move_forward.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("MoveForwardMs"); - if (value != nullptr){ - parameters.move_forward.load_json(*value); - } - value = obj->get_value("Speed"); - if (value != nullptr){ - parameters.move_speed.load_json(*value); - } - break; - case PathAction::MOVE_IN_DIRECTION: - value = obj->get_value("MoveForwardTicks"); - if (value != nullptr && value->is_integer()){ - parameters.move_forward.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("MoveForwardMs"); - if (value != nullptr){ - parameters.move_forward.load_json(*value); - } -// value = obj->get_value("Speed"); -// if (value != nullptr){ -// parameters.move_speed.load_json(*value); -// } - value = obj->get_value("MoveDirectionX"); - if (value != nullptr){ - parameters.left_x.load_json(*value); - } - value = obj->get_value("MoveDirectionY"); - if (value != nullptr){ - parameters.left_y.load_json(*value); - } - break; - case PathAction::JUMP: - value = obj->get_value("JumpWaitTicks"); - if (value != nullptr && value->is_integer()){ - parameters.jump_wait.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("JumpWaitMs"); - if (value != nullptr){ - parameters.jump_wait.load_json(*value); - } - break; - case PathAction::WAIT: - value = obj->get_value("WaitTicks"); - if (value != nullptr && value->is_integer()){ - parameters.wait.set(std::to_string(value->to_integer_default() * 8)); - } - value = obj->get_value("WaitMs"); - if (value != nullptr){ - parameters.wait.load_json(*value); - } - break; - default: - break; - } -} -JsonValue CustomPathTableRow2::to_json() const{ - JsonObject obj; - obj["Action"] = action.to_json(); - switch (action){ - case PathAction::CHANGE_MOUNT: - obj["Mount"] = parameters.mount.to_json(); - break; - case PathAction::MOVE_FORWARD: - obj["MoveForwardMs"] = parameters.move_forward.to_json(); - obj["Speed"] = parameters.move_speed.to_json(); - break; - case PathAction::MOVE_IN_DIRECTION: - obj["MoveForwardMs"] = parameters.move_forward.to_json(); -// obj["Speed"] = parameters.move_speed.to_json(); - obj["MoveDirectionX"] = parameters.left_x.to_json(); - obj["MoveDirectionY"] = parameters.left_y.to_json(); - break; - case PathAction::JUMP: - obj["JumpWaitMs"] = parameters.jump_wait.to_json(); - break; - case PathAction::WAIT: - obj["WaitMs"] = parameters.wait.to_json(); - break; - default: - break; - } - return obj; -} - -CustomPathTable2::CustomPathTable2() - : EditableTableOption_t( - "Custom Path Table:
" - "Set a sequence of actions to navigate the map. By default, the shiny detected behavior is \"Enroute Shiny Action\".
" - "If you wish to ignore enroute shinies, make sure you set \"Enroute Shiny Action\" to ignore shinies.", - LockMode::LOCK_WHILE_RUNNING, - false, // Disable the save/load buttons since we have our own. - make_defaults() - ) -{} -std::vector CustomPathTable2::make_header() const{ - return std::vector{ - "Action", - "Parameters", - }; -} -std::vector> CustomPathTable2::make_defaults(){ - std::vector> ret; - auto row = std::make_unique(*this); - row->action.set(PathAction::START_LISTEN); - ret.emplace_back(std::move(row)); - - row = std::make_unique(*this); - row->action.set(PathAction::CHANGE_MOUNT); - row->parameters.mount.set(PathMount::WYRDEER); - ret.emplace_back(std::move(row)); - - row = std::make_unique(*this); - row->action.set(PathAction::MOVE_IN_DIRECTION); - row->parameters.move_forward.set("3200 ms"); - row->parameters.left_x.set(-1.0); - row->parameters.left_y.set(1.0); - ret.emplace_back(std::move(row)); - - row = std::make_unique(*this); - row->action.set(PathAction::CENTER_CAMERA); - ret.emplace_back(std::move(row)); - - row = std::make_unique(*this); - row->action.set(PathAction::MOVE_FORWARD); - row->parameters.move_speed.set(PathSpeed::DASH); - row->parameters.move_forward.set("3200 ms"); - ret.emplace_back(std::move(row)); - - return ret; -} - - - - - - - - - -CustomPathTable::CustomPathTable() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) -// : PATH( -// "Custom Path Table:
" -// "Set a sequence of actions to navigate the map. By default, the shiny detected behavior is \"Enroute Shiny Action\".
" -// "If you wish to ignore enroute shinies, make sure you set \"Enroute Shiny Action\" to ignore shinies.", -// m_factory, make_defaults() -// ) -{ - PA_ADD_OPTION(TRAVEL_LOCATION); - PA_ADD_OPTION(PATH); -} - - -class CustomPathTableWidget : public QWidget, public ConfigWidget{ -public: - CustomPathTableWidget(QWidget& parent, CustomPathTable& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - { - // m_table_widget is class EditableTableWidget : public EditableTableBaseWidget, public ConfigWidget - // EditableTableBaseWidget inherits QWidget. - // Since it's a QWidget, we don't need to care about its memory ownership after its parent is set (as `this`). - - m_travel_location = value.TRAVEL_LOCATION.make_QtWidget(*this); - m_table_widget = value.PATH.make_QtWidget(*this); - - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); - layout->addWidget(&m_travel_location->widget()); - layout->addWidget(&m_table_widget->widget()); - - QHBoxLayout* button_layout = new QHBoxLayout(); - button_layout->setContentsMargins(0, 0, 0, 0); - layout->addLayout(button_layout); - auto load_button = new QPushButton("Load Path", this); - button_layout->addWidget(load_button, 1); - auto save_button = new QPushButton("Save Path", this); - button_layout->addWidget(save_button, 1); - button_layout->addStretch(2); - - connect(load_button, &QPushButton::clicked, this, [&value, this](bool){ - std::string path = QFileDialog::getOpenFileName(this, tr("Open option file"), ".", "*.json").toStdString(); - std::cout << "Load CustomPathTable from " << path << std::endl; - if (path.empty()){ - return; - } - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - JsonValue& obj = root.get_value_throw("CUSTOM_PATH_TABLE", path); - value.load_json(obj); - if (m_table_widget == nullptr){ - QMessageBox box; - box.critical(nullptr, "Error", "Internal code error, cannot convert to EditableTableBaseWidget."); - return; - } -// m_travel_location->update(); -// m_table_widget->update(); - }); - - connect(save_button, &QPushButton::clicked, this, [&value, this](bool){ - std::string path = QFileDialog::getSaveFileName(this, tr("Open option file"), ".", "*.json").toStdString(); - std::cout << "Save CustomPathTable from " << path << std::endl; - if (path.size() > 0){ - try{ - JsonObject root; - root["CUSTOM_PATH_TABLE"] = value.to_json(); - root.dump(path); - }catch (FileException&){ - QMessageBox box; - box.critical(nullptr, "Error", QString::fromStdString("Failed to save to file: " + path)); - return; - } - } - }); - } - -private: - ConfigWidget* m_travel_location = nullptr; - ConfigWidget* m_table_widget = nullptr; -}; - -ConfigWidget* CustomPathTable::make_QtWidget(QWidget& parent){ - return new CustomPathTableWidget(parent, *this); -} - - -} -} -} +/* Battle Pokemon Action Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include + +//#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +//#include "Common/Cpp/Json/JsonTools.h" +#include "Common/Qt/Options/ConfigWidget.h" +//#include "CommonFramework/Globals.h" +#include "PokemonLA_CustomPathTable.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace std::chrono_literals; + + + + +const EnumDropdownDatabase& PathAction_Database(){ + static const EnumDropdownDatabase database({ + {PathAction::NO_ACTION, "no-action", "NO Action"}, + {PathAction::CHANGE_MOUNT, "change-mount", "Change Mount"}, + {PathAction::MOVE_FORWARD, "move-forward", "Move Forward"}, + {PathAction::MOVE_IN_DIRECTION, "move-in-direction", "Move in Direction"}, + {PathAction::CENTER_CAMERA, "center-camera", "Center Camera"}, + {PathAction::JUMP, "jump", "Jump"}, + {PathAction::WAIT, "wait", "Wait"}, + {PathAction::START_LISTEN, "start-listen", "Start Listen"}, + {PathAction::END_LISTEN, "end-listen", "End Listen"} + }); + return database; +} +const EnumDropdownDatabase& PathMount_Database(){ + static const EnumDropdownDatabase database({ + {PathMount::NO_MOUNT, "none", "No Mount"}, + {PathMount::WYRDEER, "wrydeer", "Wrydeer"}, + {PathMount::URSALUNA, "ursaluna", "Ursaluna"}, + {PathMount::BASCULEGION, "basculegion", "Basculegion"}, + {PathMount::SNEASLER, "sneasler", "Sneasler"}, + {PathMount::BRAVIARY, "braviary", "Braviary"}, + }); + return database; +} +const EnumDropdownDatabase& PathSpeed_Database(){ + static const EnumDropdownDatabase database({ + {PathSpeed::NORMAL_SPEED, "normal", "Normal Speed"}, + {PathSpeed::SLOW_SPEED, "slow", "Slow Speed"}, + {PathSpeed::RUN, "run", "Run on Foot"}, + {PathSpeed::DASH, "dash", "Dash on Ride"}, + {PathSpeed::DASH_B_SPAM, "mash-b", "Dash on Braviary B Spam"}, + {PathSpeed::DIVE, "dive", "Dive on Braviary"}, + }); + return database; +} + + + + + +CustomPathCell::~CustomPathCell(){ + m_action.remove_listener(*this); +} +void CustomPathCell::operator=(const CustomPathCell& x){ + text.set_text(x.text.text()); + mount.set(x.mount); + move_forward.set(x.move_forward.current_text()); + move_speed.set(x.move_speed); + left_x.set(x.left_x); + left_y.set(x.left_y); + jump_wait.set(x.jump_wait.current_text()); + wait.set(x.wait.current_text()); +} +CustomPathCell::CustomPathCell(EnumDropdownCell& action) + : BatchOption(LockMode::LOCK_WHILE_RUNNING, true) + , m_action(action) + , text("", false) + , mount(PathMount_Database(), LockMode::LOCK_WHILE_RUNNING, PathMount::NO_MOUNT) + , move_forward( + "Duration (ms):", false, + LockMode::LOCK_WHILE_RUNNING, + 0ms, Milliseconds::max(), + "2000 ms" + ) + , move_speed(PathSpeed_Database(), LockMode::LOCK_WHILE_RUNNING,PathSpeed::NORMAL_SPEED) + , left_x("x: [left: -1.0, right: 1.0]", LockMode::LOCK_WHILE_RUNNING, 0, -1.0, 1.0) + , left_y("y: [backward: -1.0, forward: 1.0]", LockMode::LOCK_WHILE_RUNNING, 0, -1.0, 1.0) + , jump_wait( + "Wait after jump (ms):", false, + LockMode::LOCK_WHILE_RUNNING, + 0ms, Milliseconds::max(), + "2000 ms" + ) + , wait( + "Wait Time (ms):", false, + LockMode::LOCK_WHILE_RUNNING, + 0ms, Milliseconds::max(), + "2000 ms" + ) +{ + PA_ADD_STATIC(text); + PA_ADD_OPTION(mount); + PA_ADD_OPTION(move_forward); + PA_ADD_OPTION(move_speed); + PA_ADD_OPTION(left_x); + PA_ADD_OPTION(left_y); + PA_ADD_OPTION(jump_wait); + PA_ADD_OPTION(wait); + + CustomPathCell::on_config_value_changed(this); + action.add_listener(*this); +} +void CustomPathCell::on_config_value_changed(void* object){ + text.set_visibility(ConfigOptionState::HIDDEN); + mount.set_visibility(ConfigOptionState::HIDDEN); + move_forward.set_visibility(ConfigOptionState::HIDDEN); + move_speed.set_visibility(ConfigOptionState::HIDDEN); + left_x.set_visibility(ConfigOptionState::HIDDEN); + left_y.set_visibility(ConfigOptionState::HIDDEN); + jump_wait.set_visibility(ConfigOptionState::HIDDEN); + wait.set_visibility(ConfigOptionState::HIDDEN); + switch (m_action){ + case PathAction::NO_ACTION: + break; + case PathAction::CHANGE_MOUNT: + mount.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::MOVE_FORWARD: + move_forward.set_visibility(ConfigOptionState::ENABLED); + move_speed.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::MOVE_IN_DIRECTION: + move_forward.set_visibility(ConfigOptionState::ENABLED); + left_x.set_visibility(ConfigOptionState::ENABLED); + left_y.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::CENTER_CAMERA: + text.set_text("Center the camera so that you can move straight forward."); + text.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::JUMP: + jump_wait.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::WAIT: + wait.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::START_LISTEN: + text.set_text("If shiny detected, use \"Destination Shiny Action\"."); + text.set_visibility(ConfigOptionState::ENABLED); + break; + case PathAction::END_LISTEN: + text.set_text("If shiny detected, use \"Enroute Shiny Action\"."); + text.set_visibility(ConfigOptionState::ENABLED); + break; + default: + break; + } +} + + + + +CustomPathTableRow2::CustomPathTableRow2(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , action(PathAction_Database(), LockMode::LOCK_WHILE_RUNNING, PathAction::NO_ACTION) + , parameters(action) +{ + PA_ADD_OPTION(action); + PA_ADD_OPTION(parameters); +} +std::unique_ptr CustomPathTableRow2::clone() const{ + std::unique_ptr ret(new CustomPathTableRow2(parent())); + ret->action.set(action); + ret->parameters = parameters; + return ret; +} +void CustomPathTableRow2::load_json(const JsonValue& json){ + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + const JsonValue* value = obj->get_value("Action"); + if (value == nullptr){ + return; + } + action.load_json(*value); + + switch(action){ + case PathAction::CHANGE_MOUNT: + value = obj->get_value("Mount"); + if (value != nullptr){ + parameters.mount.load_json(*value); + } + break; + case PathAction::MOVE_FORWARD: + value = obj->get_value("MoveForwardTicks"); + if (value != nullptr && value->is_integer()){ + parameters.move_forward.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("MoveForwardMs"); + if (value != nullptr){ + parameters.move_forward.load_json(*value); + } + value = obj->get_value("Speed"); + if (value != nullptr){ + parameters.move_speed.load_json(*value); + } + break; + case PathAction::MOVE_IN_DIRECTION: + value = obj->get_value("MoveForwardTicks"); + if (value != nullptr && value->is_integer()){ + parameters.move_forward.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("MoveForwardMs"); + if (value != nullptr){ + parameters.move_forward.load_json(*value); + } +// value = obj->get_value("Speed"); +// if (value != nullptr){ +// parameters.move_speed.load_json(*value); +// } + value = obj->get_value("MoveDirectionX"); + if (value != nullptr){ + parameters.left_x.load_json(*value); + } + value = obj->get_value("MoveDirectionY"); + if (value != nullptr){ + parameters.left_y.load_json(*value); + } + break; + case PathAction::JUMP: + value = obj->get_value("JumpWaitTicks"); + if (value != nullptr && value->is_integer()){ + parameters.jump_wait.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("JumpWaitMs"); + if (value != nullptr){ + parameters.jump_wait.load_json(*value); + } + break; + case PathAction::WAIT: + value = obj->get_value("WaitTicks"); + if (value != nullptr && value->is_integer()){ + parameters.wait.set(std::to_string(value->to_integer_default() * 8)); + } + value = obj->get_value("WaitMs"); + if (value != nullptr){ + parameters.wait.load_json(*value); + } + break; + default: + break; + } +} +JsonValue CustomPathTableRow2::to_json() const{ + JsonObject obj; + obj["Action"] = action.to_json(); + switch (action){ + case PathAction::CHANGE_MOUNT: + obj["Mount"] = parameters.mount.to_json(); + break; + case PathAction::MOVE_FORWARD: + obj["MoveForwardMs"] = parameters.move_forward.to_json(); + obj["Speed"] = parameters.move_speed.to_json(); + break; + case PathAction::MOVE_IN_DIRECTION: + obj["MoveForwardMs"] = parameters.move_forward.to_json(); +// obj["Speed"] = parameters.move_speed.to_json(); + obj["MoveDirectionX"] = parameters.left_x.to_json(); + obj["MoveDirectionY"] = parameters.left_y.to_json(); + break; + case PathAction::JUMP: + obj["JumpWaitMs"] = parameters.jump_wait.to_json(); + break; + case PathAction::WAIT: + obj["WaitMs"] = parameters.wait.to_json(); + break; + default: + break; + } + return obj; +} + +CustomPathTable2::CustomPathTable2() + : EditableTableOption_t( + "Custom Path Table:
" + "Set a sequence of actions to navigate the map. By default, the shiny detected behavior is \"Enroute Shiny Action\".
" + "If you wish to ignore enroute shinies, make sure you set \"Enroute Shiny Action\" to ignore shinies.", + LockMode::LOCK_WHILE_RUNNING, + false, // Disable the save/load buttons since we have our own. + make_defaults() + ) +{} +std::vector CustomPathTable2::make_header() const{ + return std::vector{ + "Action", + "Parameters", + }; +} +std::vector> CustomPathTable2::make_defaults(){ + std::vector> ret; + auto row = std::make_unique(*this); + row->action.set(PathAction::START_LISTEN); + ret.emplace_back(std::move(row)); + + row = std::make_unique(*this); + row->action.set(PathAction::CHANGE_MOUNT); + row->parameters.mount.set(PathMount::WYRDEER); + ret.emplace_back(std::move(row)); + + row = std::make_unique(*this); + row->action.set(PathAction::MOVE_IN_DIRECTION); + row->parameters.move_forward.set("3200 ms"); + row->parameters.left_x.set(-1.0); + row->parameters.left_y.set(1.0); + ret.emplace_back(std::move(row)); + + row = std::make_unique(*this); + row->action.set(PathAction::CENTER_CAMERA); + ret.emplace_back(std::move(row)); + + row = std::make_unique(*this); + row->action.set(PathAction::MOVE_FORWARD); + row->parameters.move_speed.set(PathSpeed::DASH); + row->parameters.move_forward.set("3200 ms"); + ret.emplace_back(std::move(row)); + + return ret; +} + + + + + + + + + +CustomPathTable::CustomPathTable() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) +// : PATH( +// "Custom Path Table:
" +// "Set a sequence of actions to navigate the map. By default, the shiny detected behavior is \"Enroute Shiny Action\".
" +// "If you wish to ignore enroute shinies, make sure you set \"Enroute Shiny Action\" to ignore shinies.", +// m_factory, make_defaults() +// ) +{ + PA_ADD_OPTION(TRAVEL_LOCATION); + PA_ADD_OPTION(PATH); +} + + +class CustomPathTableWidget : public QWidget, public ConfigWidget{ +public: + CustomPathTableWidget(QWidget& parent, CustomPathTable& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + { + // m_table_widget is class EditableTableWidget : public EditableTableBaseWidget, public ConfigWidget + // EditableTableBaseWidget inherits QWidget. + // Since it's a QWidget, we don't need to care about its memory ownership after its parent is set (as `this`). + + m_travel_location = value.TRAVEL_LOCATION.make_QtWidget(*this); + m_table_widget = value.PATH.make_QtWidget(*this); + + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); + layout->addWidget(&m_travel_location->widget()); + layout->addWidget(&m_table_widget->widget()); + + QHBoxLayout* button_layout = new QHBoxLayout(); + button_layout->setContentsMargins(0, 0, 0, 0); + layout->addLayout(button_layout); + auto load_button = new QPushButton("Load Path", this); + button_layout->addWidget(load_button, 1); + auto save_button = new QPushButton("Save Path", this); + button_layout->addWidget(save_button, 1); + button_layout->addStretch(2); + + connect(load_button, &QPushButton::clicked, this, [&value, this](bool){ + std::string path = QFileDialog::getOpenFileName(this, tr("Open option file"), ".", "*.json").toStdString(); + std::cout << "Load CustomPathTable from " << path << std::endl; + if (path.empty()){ + return; + } + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + JsonValue& obj = root.get_value_throw("CUSTOM_PATH_TABLE", path); + value.load_json(obj); + if (m_table_widget == nullptr){ + QMessageBox box; + box.critical(nullptr, "Error", "Internal code error, cannot convert to EditableTableBaseWidget."); + return; + } +// m_travel_location->update(); +// m_table_widget->update(); + }); + + connect(save_button, &QPushButton::clicked, this, [&value, this](bool){ + std::string path = QFileDialog::getSaveFileName(this, tr("Open option file"), ".", "*.json").toStdString(); + std::cout << "Save CustomPathTable from " << path << std::endl; + if (path.size() > 0){ + try{ + JsonObject root; + root["CUSTOM_PATH_TABLE"] = value.to_json(); + root.dump(path); + }catch (FileException&){ + QMessageBox box; + box.critical(nullptr, "Error", QString::fromStdString("Failed to save to file: " + path)); + return; + } + } + }); + } + +private: + ConfigWidget* m_travel_location = nullptr; + ConfigWidget* m_table_widget = nullptr; +}; + +ConfigWidget* CustomPathTable::make_QtWidget(QWidget& parent){ + return new CustomPathTableWidget(parent, *this); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.h index 1ea81999c0..76f1c0049a 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_CustomPathTable.h @@ -1,133 +1,133 @@ -/* Custom Path Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_CustomPathTableTable_H -#define PokemonAutomation_PokemonLA_CustomPathTableTable_H - -#include "Common/Cpp/Options/ConfigOption.h" -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonLA_TravelLocation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -enum class PathAction{ - NO_ACTION, - CHANGE_MOUNT, - MOVE_FORWARD, - MOVE_IN_DIRECTION, - CENTER_CAMERA, - JUMP, - WAIT, - START_LISTEN, - END_LISTEN, -}; -const EnumDropdownDatabase& PathAction_Database(); - -enum class PathMount{ - NO_MOUNT, - WYRDEER, - URSALUNA, - BASCULEGION, - SNEASLER, - BRAVIARY, -}; -const EnumDropdownDatabase& PathMount_Database(); - -enum class PathSpeed{ - NORMAL_SPEED, - SLOW_SPEED, - RUN, - DASH, - DASH_B_SPAM, - DIVE, -}; -const EnumDropdownDatabase& PathSpeed_Database(); - - - - -class CustomPathCell : public BatchOption, private ConfigOption::Listener{ -public: - ~CustomPathCell(); - void operator=(const CustomPathCell& x); - CustomPathCell(EnumDropdownCell& action); - - virtual void on_config_value_changed(void* object) override; - -private: - EnumDropdownCell& m_action; - -public: - StaticTextOption text; - EnumDropdownCell mount; - MillisecondsOption move_forward; - EnumDropdownCell move_speed; - FloatingPointOption left_x; - FloatingPointOption left_y; - MillisecondsOption jump_wait; - MillisecondsOption wait; -}; - -class CustomPathTableRow2 : public EditableTableRow{ -public: - CustomPathTableRow2(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - -public: - EnumDropdownCell action; - CustomPathCell parameters; -}; - -class CustomPathTable2 : public EditableTableOption_t{ -public: - CustomPathTable2(); - virtual std::vector make_header() const override; - -private: - std::vector> make_defaults(); -}; - - - - - -// A program option to build a custom path to navigate the map -class CustomPathTable : public BatchOption{ -public: - CustomPathTable(); - - const TravelLocationOption& travel_location() const{ return TRAVEL_LOCATION; } - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -public: - friend class CustomPathTableWidget; - - TravelLocationOption TRAVEL_LOCATION; - CustomPathTable2 PATH; -}; - - - - - -} -} -} -#endif +/* Custom Path Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_CustomPathTableTable_H +#define PokemonAutomation_PokemonLA_CustomPathTableTable_H + +#include "Common/Cpp/Options/ConfigOption.h" +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonLA_TravelLocation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +enum class PathAction{ + NO_ACTION, + CHANGE_MOUNT, + MOVE_FORWARD, + MOVE_IN_DIRECTION, + CENTER_CAMERA, + JUMP, + WAIT, + START_LISTEN, + END_LISTEN, +}; +const EnumDropdownDatabase& PathAction_Database(); + +enum class PathMount{ + NO_MOUNT, + WYRDEER, + URSALUNA, + BASCULEGION, + SNEASLER, + BRAVIARY, +}; +const EnumDropdownDatabase& PathMount_Database(); + +enum class PathSpeed{ + NORMAL_SPEED, + SLOW_SPEED, + RUN, + DASH, + DASH_B_SPAM, + DIVE, +}; +const EnumDropdownDatabase& PathSpeed_Database(); + + + + +class CustomPathCell : public BatchOption, private ConfigOption::Listener{ +public: + ~CustomPathCell(); + void operator=(const CustomPathCell& x); + CustomPathCell(EnumDropdownCell& action); + + virtual void on_config_value_changed(void* object) override; + +private: + EnumDropdownCell& m_action; + +public: + StaticTextOption text; + EnumDropdownCell mount; + MillisecondsOption move_forward; + EnumDropdownCell move_speed; + FloatingPointOption left_x; + FloatingPointOption left_y; + MillisecondsOption jump_wait; + MillisecondsOption wait; +}; + +class CustomPathTableRow2 : public EditableTableRow{ +public: + CustomPathTableRow2(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + +public: + EnumDropdownCell action; + CustomPathCell parameters; +}; + +class CustomPathTable2 : public EditableTableOption_t{ +public: + CustomPathTable2(); + virtual std::vector make_header() const override; + +private: + std::vector> make_defaults(); +}; + + + + + +// A program option to build a custom path to navigate the map +class CustomPathTable : public BatchOption{ +public: + CustomPathTable(); + + const TravelLocationOption& travel_location() const{ return TRAVEL_LOCATION; } + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +public: + friend class CustomPathTableWidget; + + TravelLocationOption TRAVEL_LOCATION; + CustomPathTable2 PATH; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.cpp b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.cpp index d946fbe618..8aeb11d56d 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.cpp +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.cpp @@ -1,86 +1,86 @@ -/* Ingo Opponent Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonLA_IngoOpponent.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -const char* INGO_OPPONENT_STRINGS[] = { - "Wenton", - "Bren", - "Zisu", - "Akari/Rei", - "Kamado", - "Beni", - "Ingo", - "Ingo - but tougher", - "Mai", - "Sabi", - "Ress", - "Ingo - but using alphas", -}; -const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V10[] = { - {0, 0}, // Wenton - {0, 1}, // Bren - {0, 2}, // Zisu - {0, 3}, // Akari/Rei - {1, 0}, // Kamado - {1, 1}, // Beni - {1, 2}, // Ingo - {-1, -1}, // Ingo - but tougher - {-1, -1}, // Mai - {-1, -1}, // Sabi - {-1, -1}, // Ress - {-1, -1}, // Ingo - but using alphas -}; -const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V12[] = { - {0, 0}, // Wenton - {0, 1}, // Bren - {0, 2}, // Zisu - {0, 3}, // Akari/Rei - {0, 4}, // Kamado - {1, 0}, // Beni - {1, 1}, // Ingo - {1, 2}, // Ingo - but tougher - {1, 3}, // Mai - {1, 4}, // Sabi - {2, 0}, // Ress - {2, 1}, // Ingo - but using alphas -}; - - -IngoOpponentOption::IngoOpponentOption() - : EnumDropdownOption( - "Opponent:", - { - {IngoOpponents::Wenton, "wenton", "Wenton"}, - {IngoOpponents::Bren, "bren", "Bren"}, - {IngoOpponents::Zisu, "zisu", "Zisu"}, - {IngoOpponents::Akari_Rei, "akari-rei", "Akari/Rei"}, - {IngoOpponents::Kamado, "kamado", "Kamado"}, - {IngoOpponents::Beni, "beni", "Beni"}, - {IngoOpponents::Ingo, "ingo", "Ingo"}, - {IngoOpponents::Ingo_Tougher, "ingo-tougher", "Ingo - but tougher"}, - {IngoOpponents::Mai, "mai", "Mai"}, - {IngoOpponents::Sabi, "sabi", "Sabi"}, - {IngoOpponents::Ress, "ress", "Ress"}, - {IngoOpponents::Ingo_Alphas, "ingo-alphas", "Ingo - but using alphas"}, - }, - LockMode::LOCK_WHILE_RUNNING, - IngoOpponents::Wenton - ) -{} - - - - - -} -} -} +/* Ingo Opponent Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonLA_IngoOpponent.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +const char* INGO_OPPONENT_STRINGS[] = { + "Wenton", + "Bren", + "Zisu", + "Akari/Rei", + "Kamado", + "Beni", + "Ingo", + "Ingo - but tougher", + "Mai", + "Sabi", + "Ress", + "Ingo - but using alphas", +}; +const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V10[] = { + {0, 0}, // Wenton + {0, 1}, // Bren + {0, 2}, // Zisu + {0, 3}, // Akari/Rei + {1, 0}, // Kamado + {1, 1}, // Beni + {1, 2}, // Ingo + {-1, -1}, // Ingo - but tougher + {-1, -1}, // Mai + {-1, -1}, // Sabi + {-1, -1}, // Ress + {-1, -1}, // Ingo - but using alphas +}; +const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V12[] = { + {0, 0}, // Wenton + {0, 1}, // Bren + {0, 2}, // Zisu + {0, 3}, // Akari/Rei + {0, 4}, // Kamado + {1, 0}, // Beni + {1, 1}, // Ingo + {1, 2}, // Ingo - but tougher + {1, 3}, // Mai + {1, 4}, // Sabi + {2, 0}, // Ress + {2, 1}, // Ingo - but using alphas +}; + + +IngoOpponentOption::IngoOpponentOption() + : EnumDropdownOption( + "Opponent:", + { + {IngoOpponents::Wenton, "wenton", "Wenton"}, + {IngoOpponents::Bren, "bren", "Bren"}, + {IngoOpponents::Zisu, "zisu", "Zisu"}, + {IngoOpponents::Akari_Rei, "akari-rei", "Akari/Rei"}, + {IngoOpponents::Kamado, "kamado", "Kamado"}, + {IngoOpponents::Beni, "beni", "Beni"}, + {IngoOpponents::Ingo, "ingo", "Ingo"}, + {IngoOpponents::Ingo_Tougher, "ingo-tougher", "Ingo - but tougher"}, + {IngoOpponents::Mai, "mai", "Mai"}, + {IngoOpponents::Sabi, "sabi", "Sabi"}, + {IngoOpponents::Ress, "ress", "Ress"}, + {IngoOpponents::Ingo_Alphas, "ingo-alphas", "Ingo - but using alphas"}, + }, + LockMode::LOCK_WHILE_RUNNING, + IngoOpponents::Wenton + ) +{} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.h index 4af4341e37..6efadf6056 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_IngoOpponent.h @@ -1,52 +1,52 @@ -/* Ingo Opponent Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_IngoOpponent_H -#define PokemonAutomation_PokemonLA_IngoOpponent_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class IngoOpponents{ - Wenton, - Bren, - Zisu, - Akari_Rei, - Kamado, - Beni, - Ingo, - Ingo_Tougher, - Mai, - Sabi, - Ress, - Ingo_Alphas, - END_LIST, -}; -extern const char* INGO_OPPONENT_STRINGS[]; - -struct IngoOpponentMenuLocation{ - int8_t page; - int8_t index; -}; -extern const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V10[]; -extern const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V12[]; - - -class IngoOpponentOption : public EnumDropdownOption{ -public: - IngoOpponentOption(); -}; - - - -} -} -} -#endif +/* Ingo Opponent Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_IngoOpponent_H +#define PokemonAutomation_PokemonLA_IngoOpponent_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class IngoOpponents{ + Wenton, + Bren, + Zisu, + Akari_Rei, + Kamado, + Beni, + Ingo, + Ingo_Tougher, + Mai, + Sabi, + Ress, + Ingo_Alphas, + END_LIST, +}; +extern const char* INGO_OPPONENT_STRINGS[]; + +struct IngoOpponentMenuLocation{ + int8_t page; + int8_t index; +}; +extern const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V10[]; +extern const IngoOpponentMenuLocation INGO_OPPONENT_MENU_LOCATIONS_V12[]; + + +class IngoOpponentOption : public EnumDropdownOption{ +public: + IngoOpponentOption(); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_MiscOptions.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_MiscOptions.h index b9950d84f4..1a023af03a 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_MiscOptions.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_MiscOptions.h @@ -1,112 +1,112 @@ -/* Misc. Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_MiscOptions_H -#define PokemonAutomation_PokemonLA_MiscOptions_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "PokemonLA/PokemonLA_WeatherAndTime.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class ResetMethod{ - SoftReset, - GoBackToVillage, -}; - -class ResetMethodOption : public EnumDropdownOption{ -public: - ResetMethodOption() - : EnumDropdownOption( - "Reset Method:", - { - {ResetMethod::SoftReset, "reset", "Soft Reset"}, - {ResetMethod::GoBackToVillage, "return-to-village", "Go back to village"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - ResetMethod::SoftReset - ) - {} -}; - - - - - -enum class StopOn{ - Shiny, - Alpha, - ShinyOrAlpha, - ShinyAndAlpha, -}; - -class StopOnOption : public EnumDropdownOption{ -public: - StopOnOption() - : EnumDropdownOption( - "Stop On:", - { - {StopOn::Shiny, "shiny", "Shiny"}, - {StopOn::Alpha, "alpha", "Alpha"}, - {StopOn::ShinyOrAlpha, "shiny-or-alpha", "Shiny or Alpha"}, - {StopOn::ShinyAndAlpha, "shiny-and-alpha", "Shiny and Alpha"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - StopOn::ShinyOrAlpha - ) - {} -}; - - - -enum class ExitBattleMethod{ - RunAway, - MashAToKill, -}; - -class ExitBattleMethodOption : public EnumDropdownOption{ -public: - ExitBattleMethodOption() - : EnumDropdownOption( - "Exit Battle Method:", - { - {ExitBattleMethod::RunAway, "run", "Run Away"}, - {ExitBattleMethod::MashAToKill, "mash-a-to-kill", "Mash A to Kill"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - ExitBattleMethod::RunAway - ) - {} -}; - - -class TimeOfDayOption : public EnumDropdownOption{ -public: - TimeOfDayOption(std::string label = "Time of Day:") - : EnumDropdownOption( - label, - { - {TimeOfDay::NONE, TIME_OF_DAY_NAMES[int(TimeOfDay::NONE)], "None"}, - {TimeOfDay::MORNING, TIME_OF_DAY_NAMES[int(TimeOfDay::MORNING)], "Morning"}, - {TimeOfDay::MIDDAY, TIME_OF_DAY_NAMES[int(TimeOfDay::MIDDAY)], "Midday"}, - {TimeOfDay::EVENING, TIME_OF_DAY_NAMES[int(TimeOfDay::EVENING)], "Evening"}, - {TimeOfDay::MIDNIGHT, TIME_OF_DAY_NAMES[int(TimeOfDay::MIDNIGHT)], "Midnight"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - TimeOfDay::NONE - ) - {} -}; - - - -} -} -} -#endif +/* Misc. Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_MiscOptions_H +#define PokemonAutomation_PokemonLA_MiscOptions_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "PokemonLA/PokemonLA_WeatherAndTime.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class ResetMethod{ + SoftReset, + GoBackToVillage, +}; + +class ResetMethodOption : public EnumDropdownOption{ +public: + ResetMethodOption() + : EnumDropdownOption( + "Reset Method:", + { + {ResetMethod::SoftReset, "reset", "Soft Reset"}, + {ResetMethod::GoBackToVillage, "return-to-village", "Go back to village"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + ResetMethod::SoftReset + ) + {} +}; + + + + + +enum class StopOn{ + Shiny, + Alpha, + ShinyOrAlpha, + ShinyAndAlpha, +}; + +class StopOnOption : public EnumDropdownOption{ +public: + StopOnOption() + : EnumDropdownOption( + "Stop On:", + { + {StopOn::Shiny, "shiny", "Shiny"}, + {StopOn::Alpha, "alpha", "Alpha"}, + {StopOn::ShinyOrAlpha, "shiny-or-alpha", "Shiny or Alpha"}, + {StopOn::ShinyAndAlpha, "shiny-and-alpha", "Shiny and Alpha"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + StopOn::ShinyOrAlpha + ) + {} +}; + + + +enum class ExitBattleMethod{ + RunAway, + MashAToKill, +}; + +class ExitBattleMethodOption : public EnumDropdownOption{ +public: + ExitBattleMethodOption() + : EnumDropdownOption( + "Exit Battle Method:", + { + {ExitBattleMethod::RunAway, "run", "Run Away"}, + {ExitBattleMethod::MashAToKill, "mash-a-to-kill", "Mash A to Kill"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + ExitBattleMethod::RunAway + ) + {} +}; + + +class TimeOfDayOption : public EnumDropdownOption{ +public: + TimeOfDayOption(std::string label = "Time of Day:") + : EnumDropdownOption( + label, + { + {TimeOfDay::NONE, TIME_OF_DAY_NAMES[int(TimeOfDay::NONE)], "None"}, + {TimeOfDay::MORNING, TIME_OF_DAY_NAMES[int(TimeOfDay::MORNING)], "Morning"}, + {TimeOfDay::MIDDAY, TIME_OF_DAY_NAMES[int(TimeOfDay::MIDDAY)], "Midday"}, + {TimeOfDay::EVENING, TIME_OF_DAY_NAMES[int(TimeOfDay::EVENING)], "Evening"}, + {TimeOfDay::MIDNIGHT, TIME_OF_DAY_NAMES[int(TimeOfDay::MIDNIGHT)], "Midnight"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + TimeOfDay::NONE + ) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.cpp b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.cpp index 4f591b869c..6239cacee5 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.cpp +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.cpp @@ -1,222 +1,222 @@ -/* Shiny Detected Action - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -ShinyRequiresAudioText::ShinyRequiresAudioText() - : StaticTextOption( - html_color_text( - "Shiny detection uses sound. Make sure you have the correct audio input set.", - COLOR_BLUE - ) - ) -{} - - - - -OverworldShinyDetectedActionOption::OverworldShinyDetectedActionOption( - std::string label, std::string description, - std::string default_delay, - OverworldShinyDetectedAction default_action -) - : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) - , DESCRIPTION(std::move(description)) - , ACTION( - "Shiny Detected Action:", - { - {OverworldShinyDetectedAction::IGNORE, "ignore", "Ignore the shiny. Do not stop the program."}, - {OverworldShinyDetectedAction::STOP_PROGRAM, "stop", "Stop program. Align camera for a screenshot. Then go Home."}, - {OverworldShinyDetectedAction::TAKE_VIDEO_STOP_PROGRAM, "video+stop", "Stop program. Align camera for a screenshot + video. Then go Home."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - default_action - ) -// , STOP_PROGRAM("Stop Program:
Stop program and go Home if it hears a shiny.", true) -// , TAKE_VIDEO("Take Video:
Take a video if a shiny is heard.", true) - , SCREENSHOT_DELAY0( - "Screenshot Delay:
" - "Align the camera, then wait this long before taking a screenshot + video of the shiny.
" - "Set to zero to skip this. Don't set this too large or the shiny may run away!", - LockMode::UNLOCK_WHILE_RUNNING, - std::move(default_delay) - ) - , NOTIFICATIONS( - this->label(), - true, true, - ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) -{ - if (!DESCRIPTION.text().empty()){ - PA_ADD_OPTION(DESCRIPTION); - } - PA_ADD_OPTION(ACTION); -// PA_ADD_OPTION(STOP_PROGRAM); -// PA_ADD_OPTION(TAKE_VIDEO); - PA_ADD_OPTION(SCREENSHOT_DELAY0); -} -bool OverworldShinyDetectedActionOption::stop_on_shiny() const{ - return ACTION != OverworldShinyDetectedAction::IGNORE; -} - - - -BattleMatchActionOption::BattleMatchActionOption( - std::string label, std::string description, - std::string default_delay -) - : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) - , DESCRIPTION(std::move(description)) - , TAKE_VIDEO("Take Video:", LockMode::UNLOCK_WHILE_RUNNING, true) - , NOTIFICATIONS( - this->label(), - true, true, - ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) -{ - if (!DESCRIPTION.text().empty()){ - PA_ADD_OPTION(DESCRIPTION); - } - PA_ADD_OPTION(TAKE_VIDEO); -} - - - - - - -bool on_shiny_callback( - ProgramEnvironment& env, VideoStream& stream, - OverworldShinyDetectedActionOption& options, - float error_coefficient -){ - { - std::ostringstream ss; - ss << "Detected Shiny Sound! (error coefficient = " << error_coefficient << ")"; - stream.log(ss.str(), COLOR_BLUE); - - // If we're not ignoring the shiny, return now. Actions will be deferred - // until after the session ends. - OverworldShinyDetectedAction action = options.ACTION; - if (action != OverworldShinyDetectedAction::IGNORE){ - return true; - } - } - - stream.log("Ignoring shiny per user settings...", COLOR_RED); - - std::vector> embeds; - - std::ostringstream ss; - ss << "Error Coefficient: " << error_coefficient << "\n(Shiny may not be visible on the screen.)"; - embeds.emplace_back("Detection Results:", ss.str()); - - send_program_notification( - env, options.NOTIFICATIONS, - Pokemon::COLOR_STAR_SHINY, - "Detected Shiny Sound", - embeds, "", - stream.video().snapshot(), true - ); - return false; -} -void on_shiny_sound( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - OverworldShinyDetectedActionOption& options, - float error_coefficient -){ - std::vector> embeds; - - std::ostringstream ss; - ss << "Error Coefficient: "; - ss << error_coefficient; - ss << "\n(Shiny may not be visible on the screen.)"; - embeds.emplace_back("Detection Results:", ss.str()); - -// pbf_press_button(context, BUTTON_ZL, 20, options.SCREENSHOT_DELAY); - pbf_mash_button(context, BUTTON_ZL, options.SCREENSHOT_DELAY0); - context.wait_for_all_requests(); - - send_program_notification( - env, options.NOTIFICATIONS, - Pokemon::COLOR_STAR_SHINY, - "Detected Shiny Sound", - embeds, "", - stream.video().snapshot(), true - ); - - switch (options.ACTION){ - case OverworldShinyDetectedAction::IGNORE: - break; - case OverworldShinyDetectedAction::STOP_PROGRAM: - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - context.wait_for_all_requests(); - throw ProgramFinishedException(); - case OverworldShinyDetectedAction::TAKE_VIDEO_STOP_PROGRAM: - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - context.wait_for_all_requests(); - throw ProgramFinishedException(); - } -} - -void on_battle_match_found( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - BattleMatchActionOption& options, - bool allow_notification -){ - context.wait_for_all_requests(); - - if (allow_notification){ - send_program_notification( - env, options.NOTIFICATIONS, - Pokemon::COLOR_STAR_SHINY, - "Match Found", - {}, "", - stream.video().snapshot(), true - ); - } - - if (options.TAKE_VIDEO){ - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); - } - - stream.log("Stopping..."); - context.wait_for_all_requests(); - throw ProgramFinishedException(); -} - - - - - - - - - - - - -} -} -} +/* Shiny Detected Action + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +ShinyRequiresAudioText::ShinyRequiresAudioText() + : StaticTextOption( + html_color_text( + "Shiny detection uses sound. Make sure you have the correct audio input set.", + COLOR_BLUE + ) + ) +{} + + + + +OverworldShinyDetectedActionOption::OverworldShinyDetectedActionOption( + std::string label, std::string description, + std::string default_delay, + OverworldShinyDetectedAction default_action +) + : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) + , DESCRIPTION(std::move(description)) + , ACTION( + "Shiny Detected Action:", + { + {OverworldShinyDetectedAction::IGNORE, "ignore", "Ignore the shiny. Do not stop the program."}, + {OverworldShinyDetectedAction::STOP_PROGRAM, "stop", "Stop program. Align camera for a screenshot. Then go Home."}, + {OverworldShinyDetectedAction::TAKE_VIDEO_STOP_PROGRAM, "video+stop", "Stop program. Align camera for a screenshot + video. Then go Home."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + default_action + ) +// , STOP_PROGRAM("Stop Program:
Stop program and go Home if it hears a shiny.", true) +// , TAKE_VIDEO("Take Video:
Take a video if a shiny is heard.", true) + , SCREENSHOT_DELAY0( + "Screenshot Delay:
" + "Align the camera, then wait this long before taking a screenshot + video of the shiny.
" + "Set to zero to skip this. Don't set this too large or the shiny may run away!", + LockMode::UNLOCK_WHILE_RUNNING, + std::move(default_delay) + ) + , NOTIFICATIONS( + this->label(), + true, true, + ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) +{ + if (!DESCRIPTION.text().empty()){ + PA_ADD_OPTION(DESCRIPTION); + } + PA_ADD_OPTION(ACTION); +// PA_ADD_OPTION(STOP_PROGRAM); +// PA_ADD_OPTION(TAKE_VIDEO); + PA_ADD_OPTION(SCREENSHOT_DELAY0); +} +bool OverworldShinyDetectedActionOption::stop_on_shiny() const{ + return ACTION != OverworldShinyDetectedAction::IGNORE; +} + + + +BattleMatchActionOption::BattleMatchActionOption( + std::string label, std::string description, + std::string default_delay +) + : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) + , DESCRIPTION(std::move(description)) + , TAKE_VIDEO("Take Video:", LockMode::UNLOCK_WHILE_RUNNING, true) + , NOTIFICATIONS( + this->label(), + true, true, + ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) +{ + if (!DESCRIPTION.text().empty()){ + PA_ADD_OPTION(DESCRIPTION); + } + PA_ADD_OPTION(TAKE_VIDEO); +} + + + + + + +bool on_shiny_callback( + ProgramEnvironment& env, VideoStream& stream, + OverworldShinyDetectedActionOption& options, + float error_coefficient +){ + { + std::ostringstream ss; + ss << "Detected Shiny Sound! (error coefficient = " << error_coefficient << ")"; + stream.log(ss.str(), COLOR_BLUE); + + // If we're not ignoring the shiny, return now. Actions will be deferred + // until after the session ends. + OverworldShinyDetectedAction action = options.ACTION; + if (action != OverworldShinyDetectedAction::IGNORE){ + return true; + } + } + + stream.log("Ignoring shiny per user settings...", COLOR_RED); + + std::vector> embeds; + + std::ostringstream ss; + ss << "Error Coefficient: " << error_coefficient << "\n(Shiny may not be visible on the screen.)"; + embeds.emplace_back("Detection Results:", ss.str()); + + send_program_notification( + env, options.NOTIFICATIONS, + Pokemon::COLOR_STAR_SHINY, + "Detected Shiny Sound", + embeds, "", + stream.video().snapshot(), true + ); + return false; +} +void on_shiny_sound( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + OverworldShinyDetectedActionOption& options, + float error_coefficient +){ + std::vector> embeds; + + std::ostringstream ss; + ss << "Error Coefficient: "; + ss << error_coefficient; + ss << "\n(Shiny may not be visible on the screen.)"; + embeds.emplace_back("Detection Results:", ss.str()); + +// pbf_press_button(context, BUTTON_ZL, 20, options.SCREENSHOT_DELAY); + pbf_mash_button(context, BUTTON_ZL, options.SCREENSHOT_DELAY0); + context.wait_for_all_requests(); + + send_program_notification( + env, options.NOTIFICATIONS, + Pokemon::COLOR_STAR_SHINY, + "Detected Shiny Sound", + embeds, "", + stream.video().snapshot(), true + ); + + switch (options.ACTION){ + case OverworldShinyDetectedAction::IGNORE: + break; + case OverworldShinyDetectedAction::STOP_PROGRAM: + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + context.wait_for_all_requests(); + throw ProgramFinishedException(); + case OverworldShinyDetectedAction::TAKE_VIDEO_STOP_PROGRAM: + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + context.wait_for_all_requests(); + throw ProgramFinishedException(); + } +} + +void on_battle_match_found( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + BattleMatchActionOption& options, + bool allow_notification +){ + context.wait_for_all_requests(); + + if (allow_notification){ + send_program_notification( + env, options.NOTIFICATIONS, + Pokemon::COLOR_STAR_SHINY, + "Match Found", + {}, "", + stream.video().snapshot(), true + ); + } + + if (options.TAKE_VIDEO){ + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); + } + + stream.log("Stopping..."); + context.wait_for_all_requests(); + throw ProgramFinishedException(); +} + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.h index 48e72d5e80..b86117b411 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_ShinyDetectedAction.h @@ -1,117 +1,117 @@ -/* Shiny Detected Action - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ShinyDetectedAction_H -#define PokemonAutomation_PokemonLA_ShinyDetectedAction_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class EventNotificationOption; - class StatsTracker; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ShinyRequiresAudioText : public StaticTextOption{ -public: - ShinyRequiresAudioText(); -}; - - - -class ShinySoundDetector; - - -class ShinyStatIncrementer{ -public: - virtual void add_shiny() = 0; -}; - - - - -enum class OverworldShinyDetectedAction{ - IGNORE, - STOP_PROGRAM, - TAKE_VIDEO_STOP_PROGRAM, -}; - - -class OverworldShinyDetectedActionOption : public GroupOption{ -public: - OverworldShinyDetectedActionOption( - std::string label, std::string description, - std::string default_delay, - OverworldShinyDetectedAction default_action = OverworldShinyDetectedAction::TAKE_VIDEO_STOP_PROGRAM - ); - - bool stop_on_shiny() const; - - StaticTextOption DESCRIPTION; - EnumDropdownOption ACTION; -// BooleanCheckBoxOption STOP_PROGRAM; -// BooleanCheckBoxOption TAKE_VIDEO; - MillisecondsOption SCREENSHOT_DELAY0; - EventNotificationOption NOTIFICATIONS; -}; -class BattleMatchActionOption : public GroupOption{ -public: - BattleMatchActionOption( - std::string label, std::string description, - std::string default_delay - ); - - bool stop_on_shiny() const; - - StaticTextOption DESCRIPTION; - BooleanCheckBoxOption TAKE_VIDEO; - EventNotificationOption NOTIFICATIONS; -}; - - - -// Call this inside the ShinySoundDetector callback. -// Returns true if session should stop. -bool on_shiny_callback( - ProgramEnvironment& env, VideoStream& stream, - OverworldShinyDetectedActionOption& options, - float error_coefficient -); - -// Call this after the session ends. Only if the session stopped on the shiny. -void on_shiny_sound( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - OverworldShinyDetectedActionOption& options, - float error_coefficient -); - -// Alternative for matches (shiny/alphas) not found by sound. -void on_battle_match_found( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - BattleMatchActionOption& options, - bool allow_notification -); - - - - - - - - -} -} -} -#endif +/* Shiny Detected Action + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ShinyDetectedAction_H +#define PokemonAutomation_PokemonLA_ShinyDetectedAction_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class EventNotificationOption; + class StatsTracker; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ShinyRequiresAudioText : public StaticTextOption{ +public: + ShinyRequiresAudioText(); +}; + + + +class ShinySoundDetector; + + +class ShinyStatIncrementer{ +public: + virtual void add_shiny() = 0; +}; + + + + +enum class OverworldShinyDetectedAction{ + IGNORE, + STOP_PROGRAM, + TAKE_VIDEO_STOP_PROGRAM, +}; + + +class OverworldShinyDetectedActionOption : public GroupOption{ +public: + OverworldShinyDetectedActionOption( + std::string label, std::string description, + std::string default_delay, + OverworldShinyDetectedAction default_action = OverworldShinyDetectedAction::TAKE_VIDEO_STOP_PROGRAM + ); + + bool stop_on_shiny() const; + + StaticTextOption DESCRIPTION; + EnumDropdownOption ACTION; +// BooleanCheckBoxOption STOP_PROGRAM; +// BooleanCheckBoxOption TAKE_VIDEO; + MillisecondsOption SCREENSHOT_DELAY0; + EventNotificationOption NOTIFICATIONS; +}; +class BattleMatchActionOption : public GroupOption{ +public: + BattleMatchActionOption( + std::string label, std::string description, + std::string default_delay + ); + + bool stop_on_shiny() const; + + StaticTextOption DESCRIPTION; + BooleanCheckBoxOption TAKE_VIDEO; + EventNotificationOption NOTIFICATIONS; +}; + + + +// Call this inside the ShinySoundDetector callback. +// Returns true if session should stop. +bool on_shiny_callback( + ProgramEnvironment& env, VideoStream& stream, + OverworldShinyDetectedActionOption& options, + float error_coefficient +); + +// Call this after the session ends. Only if the session stopped on the shiny. +void on_shiny_sound( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + OverworldShinyDetectedActionOption& options, + float error_coefficient +); + +// Alternative for matches (shiny/alphas) not found by sound. +void on_battle_match_found( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + BattleMatchActionOption& options, + bool allow_notification +); + + + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.cpp b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.cpp index f87e2657e1..99864033cc 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.cpp +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.cpp @@ -1,95 +1,95 @@ -/* Trade Count Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonLA/Resources/PokemonLA_AvailablePokemon.h" -#include "PokemonLA/Resources/PokemonLA_PokemonSprites.h" -#include "PokemonLA_TradeCountTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -std::map make_research_catch_count_map(){ - std::string path = RESOURCE_PATH() + "PokemonLA/ResearchMaxCatches.json"; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - std::map map; - for (auto& item : root){ - map.emplace(item.first, (uint8_t)item.second.to_integer_throw(path)); - } - - return map; -} -uint8_t research_catch_count(const std::string& slug){ - static const std::map database = make_research_catch_count_map(); - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No research count for: " + slug); - } - return iter->second; -} - - - - -TradeCountTableRow::TradeCountTableRow(const std::string& slug, const ImageViewRGB32& icon) - : StaticTableRow(slug) - , default_value(research_catch_count(slug)) - , pokemon(LockMode::LOCK_WHILE_RUNNING, Pokemon::get_pokemon_name(slug).display_name(), icon, 40) - , count(LockMode::LOCK_WHILE_RUNNING, default_value, 0, default_value) - , default_label(LockMode::LOCK_WHILE_RUNNING, std::to_string(default_value), ImageViewRGB32()) -{ - PA_ADD_STATIC(pokemon); - add_option(count, "Count"); - PA_ADD_STATIC(default_label); -} - -TradeCountTable::TradeCountTable() - : StaticTableOption( - "Trade Counts:" - "
Trade each " + STRING_POKEMON + " of this species this many times.
" - "The defaults here are the # of catches needed to max out research. " - "Maxing out catches is sufficient to reach level 10 for everything except Unown, Spritomb, and legendaries. " - "Note that gen1 trade evolutions cannot be touch traded. The program will skip them. This applies to Kadabra, Haunter, Graveler, and Machoke.", - LockMode::LOCK_WHILE_RUNNING - ) -{ - for (const std::string& slug : HISUI_DEX_SLUGS()){ - const SpriteDatabase::Sprite* sprite = ALL_POKEMON_SPRITES().get_nothrow(slug); - ImageViewRGB32 icon; - if (sprite != nullptr){ - icon = sprite->icon; - } - add_row(std::make_unique(slug, icon)); - } - finish_construction(); -} -std::vector TradeCountTable::make_header() const{ - std::vector ret{ - STRING_POKEMON, - "Trades", - "Default" - }; - return ret; -} - - - - - -} -} -} +/* Trade Count Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonLA/Resources/PokemonLA_AvailablePokemon.h" +#include "PokemonLA/Resources/PokemonLA_PokemonSprites.h" +#include "PokemonLA_TradeCountTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +std::map make_research_catch_count_map(){ + std::string path = RESOURCE_PATH() + "PokemonLA/ResearchMaxCatches.json"; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + std::map map; + for (auto& item : root){ + map.emplace(item.first, (uint8_t)item.second.to_integer_throw(path)); + } + + return map; +} +uint8_t research_catch_count(const std::string& slug){ + static const std::map database = make_research_catch_count_map(); + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "No research count for: " + slug); + } + return iter->second; +} + + + + +TradeCountTableRow::TradeCountTableRow(const std::string& slug, const ImageViewRGB32& icon) + : StaticTableRow(slug) + , default_value(research_catch_count(slug)) + , pokemon(LockMode::LOCK_WHILE_RUNNING, Pokemon::get_pokemon_name(slug).display_name(), icon, 40) + , count(LockMode::LOCK_WHILE_RUNNING, default_value, 0, default_value) + , default_label(LockMode::LOCK_WHILE_RUNNING, std::to_string(default_value), ImageViewRGB32()) +{ + PA_ADD_STATIC(pokemon); + add_option(count, "Count"); + PA_ADD_STATIC(default_label); +} + +TradeCountTable::TradeCountTable() + : StaticTableOption( + "Trade Counts:" + "
Trade each " + STRING_POKEMON + " of this species this many times.
" + "The defaults here are the # of catches needed to max out research. " + "Maxing out catches is sufficient to reach level 10 for everything except Unown, Spritomb, and legendaries. " + "Note that gen1 trade evolutions cannot be touch traded. The program will skip them. This applies to Kadabra, Haunter, Graveler, and Machoke.", + LockMode::LOCK_WHILE_RUNNING + ) +{ + for (const std::string& slug : HISUI_DEX_SLUGS()){ + const SpriteDatabase::Sprite* sprite = ALL_POKEMON_SPRITES().get_nothrow(slug); + ImageViewRGB32 icon; + if (sprite != nullptr){ + icon = sprite->icon; + } + add_row(std::make_unique(slug, icon)); + } + finish_construction(); +} +std::vector TradeCountTable::make_header() const{ + std::vector ret{ + STRING_POKEMON, + "Trades", + "Default" + }; + return ret; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.h index c373948549..6c01d410fa 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TradeCountTable.h @@ -1,47 +1,47 @@ -/* Trade Count Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_TradeCountTable_H -#define PokemonAutomation_PokemonLA_TradeCountTable_H - -#include -#include -#include "Common/Cpp/Options/ConfigOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StaticTableOption.h" -#include "CommonFramework/Options/LabelCellOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class TradeCountTableRow : public StaticTableRow{ -public: - TradeCountTableRow(const std::string& slug, const ImageViewRGB32& icon); - - const uint8_t default_value; - - LabelCellOption pokemon; - SimpleIntegerCell count; - LabelCellOption default_label; -}; - - -class TradeCountTable : public StaticTableOption{ -public: - TradeCountTable(); - virtual std::vector make_header() const; -}; - - - - - -} -} -} -#endif +/* Trade Count Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_TradeCountTable_H +#define PokemonAutomation_PokemonLA_TradeCountTable_H + +#include +#include +#include "Common/Cpp/Options/ConfigOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StaticTableOption.h" +#include "CommonFramework/Options/LabelCellOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class TradeCountTableRow : public StaticTableRow{ +public: + TradeCountTableRow(const std::string& slug, const ImageViewRGB32& icon); + + const uint8_t default_value; + + LabelCellOption pokemon; + SimpleIntegerCell count; + LabelCellOption default_label; +}; + + +class TradeCountTable : public StaticTableOption{ +public: + TradeCountTable(); + virtual std::vector make_header() const; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.cpp b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.cpp index 201c2ca0db..3cf0967bd1 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.cpp +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.cpp @@ -1,35 +1,35 @@ -/* Travel Location - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "PokemonLA_TravelLocation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -TravelLocationOption::TravelLocationOption() - : IntegerEnumDropdownOption( - "Start Location:
Travel from this location.", - TravelLocations::instance().database(), - LockMode::LOCK_WHILE_RUNNING, - 0 - ) -{} - -TravelLocationOption::operator TravelLocation() const{ - size_t index = this->current_value(); - return TravelLocations::instance()[index]; -} - - - - - -} -} -} +/* Travel Location + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonLA_TravelLocation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +TravelLocationOption::TravelLocationOption() + : IntegerEnumDropdownOption( + "Start Location:
Travel from this location.", + TravelLocations::instance().database(), + LockMode::LOCK_WHILE_RUNNING, + 0 + ) +{} + +TravelLocationOption::operator TravelLocation() const{ + size_t index = this->current_value(); + return TravelLocations::instance()[index]; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.h b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.h index 0f6b19b0a4..129491b930 100644 --- a/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.h +++ b/SerialPrograms/Source/PokemonLA/Options/PokemonLA_TravelLocation.h @@ -1,31 +1,31 @@ -/* Travel Location - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_TravelLocation_H -#define PokemonAutomation_PokemonLA_TravelLocation_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class TravelLocationOption : public IntegerEnumDropdownOption{ -public: - TravelLocationOption(); - operator TravelLocation() const; -}; - - - - - -} -} -} -#endif +/* Travel Location + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_TravelLocation_H +#define PokemonAutomation_PokemonLA_TravelLocation_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class TravelLocationOption : public IntegerEnumDropdownOption{ +public: + TravelLocationOption(); + operator TravelLocation() const; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.cpp b/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.cpp index d9d8e8ae9a..c97f04decf 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.cpp +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.cpp @@ -1,61 +1,61 @@ -/* Pokemon Legends Arceus Locations - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonLA_Locations.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -const char* MAP_REGION_NAMES[] = { - "None", - "Jubilife Village", - "Obsidian Fieldlands", - "Crimson Mirelands", - "Cobalt Coastlands", - "Coronet Highlands", - "Alabaster Icelands", - "Ancient Retreat", -}; - -const char* WILD_REGION_SHORT_NAMES[] = { - "Fieldlands", - "Mirelands", - "Coastlands", - "Highlands", - "Icelands", -}; - -bool is_wild_land(MapRegion region){ - return region == MapRegion::FIELDLANDS || region == MapRegion::MIRELANDS || region == MapRegion::COASTLANDS - || region == MapRegion::HIGHLANDS || region == MapRegion::ICELANDS; -} - -Camp map_region_default_camp(MapRegion region){ - switch (region){ - case MapRegion::FIELDLANDS: - return Camp::FIELDLANDS_FIELDLANDS; - case MapRegion::MIRELANDS: - return Camp::MIRELANDS_MIRELANDS; - case MapRegion::COASTLANDS: - return Camp::COASTLANDS_BEACHSIDE; - case MapRegion::HIGHLANDS: - return Camp::HIGHLANDS_HIGHLANDS; - case MapRegion::ICELANDS: - return Camp::ICELANDS_SNOWFIELDS; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid region."); - } - -} - -} -} -} +/* Pokemon Legends Arceus Locations + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonLA_Locations.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +const char* MAP_REGION_NAMES[] = { + "None", + "Jubilife Village", + "Obsidian Fieldlands", + "Crimson Mirelands", + "Cobalt Coastlands", + "Coronet Highlands", + "Alabaster Icelands", + "Ancient Retreat", +}; + +const char* WILD_REGION_SHORT_NAMES[] = { + "Fieldlands", + "Mirelands", + "Coastlands", + "Highlands", + "Icelands", +}; + +bool is_wild_land(MapRegion region){ + return region == MapRegion::FIELDLANDS || region == MapRegion::MIRELANDS || region == MapRegion::COASTLANDS + || region == MapRegion::HIGHLANDS || region == MapRegion::ICELANDS; +} + +Camp map_region_default_camp(MapRegion region){ + switch (region){ + case MapRegion::FIELDLANDS: + return Camp::FIELDLANDS_FIELDLANDS; + case MapRegion::MIRELANDS: + return Camp::MIRELANDS_MIRELANDS; + case MapRegion::COASTLANDS: + return Camp::COASTLANDS_BEACHSIDE; + case MapRegion::HIGHLANDS: + return Camp::HIGHLANDS_HIGHLANDS; + case MapRegion::ICELANDS: + return Camp::ICELANDS_SNOWFIELDS; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid region."); + } + +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.h b/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.h index 154b367bc5..b944ac452f 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.h +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_Locations.h @@ -1,60 +1,60 @@ -/* Pokemon Legends Arceus Locations - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_Locations_H -#define PokemonAutomation_PokemonLA_Locations_H - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -enum class MapRegion{ - NONE, - JUBILIFE, - FIELDLANDS, - MIRELANDS, - COASTLANDS, - HIGHLANDS, - ICELANDS, - RETREAT, -}; - -// Map from int(MapRegion) to its region name -extern const char* MAP_REGION_NAMES[]; - -// from int [0, 1, 2, 3, 4] to short names of the five wild regions: -// { "Fieldlands", "Mirelands", ... } -// This is useful for logging purpose. -extern const char* WILD_REGION_SHORT_NAMES[]; - - -enum class Camp{ - FIELDLANDS_FIELDLANDS, - FIELDLANDS_HEIGHTS, - MIRELANDS_MIRELANDS, - MIRELANDS_BOGBOUND, - COASTLANDS_BEACHSIDE, - COASTLANDS_COASTLANDS, - HIGHLANDS_HIGHLANDS, - HIGHLANDS_MOUNTAIN, - HIGHLANDS_SUMMIT, - ICELANDS_SNOWFIELDS, - ICELANDS_ICEPEAK, -}; - -// Return true if the region is fieldlands, mirelands, coastlands, highlands or icelands. -bool is_wild_land(MapRegion region); - -// Get the first camp of the region, which is the default camp when warping on the region map. -Camp map_region_default_camp(MapRegion region); - - - - -} -} -} -#endif +/* Pokemon Legends Arceus Locations + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_Locations_H +#define PokemonAutomation_PokemonLA_Locations_H + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +enum class MapRegion{ + NONE, + JUBILIFE, + FIELDLANDS, + MIRELANDS, + COASTLANDS, + HIGHLANDS, + ICELANDS, + RETREAT, +}; + +// Map from int(MapRegion) to its region name +extern const char* MAP_REGION_NAMES[]; + +// from int [0, 1, 2, 3, 4] to short names of the five wild regions: +// { "Fieldlands", "Mirelands", ... } +// This is useful for logging purpose. +extern const char* WILD_REGION_SHORT_NAMES[]; + + +enum class Camp{ + FIELDLANDS_FIELDLANDS, + FIELDLANDS_HEIGHTS, + MIRELANDS_MIRELANDS, + MIRELANDS_BOGBOUND, + COASTLANDS_BEACHSIDE, + COASTLANDS_COASTLANDS, + HIGHLANDS_HIGHLANDS, + HIGHLANDS_MOUNTAIN, + HIGHLANDS_SUMMIT, + ICELANDS_SNOWFIELDS, + ICELANDS_ICEPEAK, +}; + +// Return true if the region is fieldlands, mirelands, coastlands, highlands or icelands. +bool is_wild_land(MapRegion region); + +// Get the first camp of the region, which is the default camp when warping on the region map. +Camp map_region_default_camp(MapRegion region); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.cpp b/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.cpp index ee3190d61d..4aa0054ece 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.cpp +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.cpp @@ -1,117 +1,117 @@ -/* Pokemon LA Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_Panels.h" - -#include "PokemonLA_Settings.h" - -#include "Programs/General/PokemonLA_BraviaryHeightGlitch.h" -#include "Programs/General/PokemonLA_DistortionWaiter.h" -#include "Programs/General/PokemonLA_OutbreakFinder.h" -#include "Programs/General/PokemonLA_ClothingBuyer.h" -#include "Programs/General/PokemonLA_SkipToFullMoon.h" -#include "Programs/General/PokemonLA_PokedexTasksReader.h" -#include "Programs/General/PokemonLA_RamanasIslandCombee.h" -#include "Programs/General/PokemonLA_ApplyGrits.h" - -#include "Programs/Trading/PokemonLA_SelfBoxTrade.h" -#include "Programs/Trading/PokemonLA_SelfTouchTrade.h" - -#include "Programs/Farming/PokemonLA_IngoBattleGrinder.h" -#include "Programs/Farming/PokemonLA_IngoMoveGrinder.h" -#include "Programs/Farming/PokemonLA_MagikarpMoveGrinder.h" -#include "Programs/Farming/PokemonLA_NuggetFarmerHighlands.h" -#include "Programs/Farming/PokemonLA_TenacityCandyFarmer.h" -#include "Programs/Farming/PokemonLA_LeapGrinder.h" - -//#include "Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h" -#include "Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h" -#include "Programs/ShinyHunting/PokemonLA_GalladeFinder.h" -#include "Programs/ShinyHunting/PokemonLA_CrobatFinder.h" -#include "Programs/ShinyHunting/PokemonLA_FroslassFinder.h" -#include "Programs/ShinyHunting/PokemonLA_BurmyFinder.h" -#include "Programs/ShinyHunting/PokemonLA_UnownFinder.h" -#include "Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h" -#include "Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h" -#include "Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h" - -#include "Programs/TestPrograms/PokemonLA_MountDetectionTest.h" -#include "Programs/TestPrograms/PokemonLA_OverworldWatcher.h" -#include "Programs/TestPrograms/PokemonLA_FlagNavigationTest.h" -#include "Programs/TestPrograms/PokemonLA_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Legends Arceus") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Trading ----"); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - - ret.emplace_back("---- Farming ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting ----"); -// ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Untested/Beta/WIP ----"); - ret.emplace_back(make_single_switch_program()); - } - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} -} +/* Pokemon LA Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_Panels.h" + +#include "PokemonLA_Settings.h" + +#include "Programs/General/PokemonLA_BraviaryHeightGlitch.h" +#include "Programs/General/PokemonLA_DistortionWaiter.h" +#include "Programs/General/PokemonLA_OutbreakFinder.h" +#include "Programs/General/PokemonLA_ClothingBuyer.h" +#include "Programs/General/PokemonLA_SkipToFullMoon.h" +#include "Programs/General/PokemonLA_PokedexTasksReader.h" +#include "Programs/General/PokemonLA_RamanasIslandCombee.h" +#include "Programs/General/PokemonLA_ApplyGrits.h" + +#include "Programs/Trading/PokemonLA_SelfBoxTrade.h" +#include "Programs/Trading/PokemonLA_SelfTouchTrade.h" + +#include "Programs/Farming/PokemonLA_IngoBattleGrinder.h" +#include "Programs/Farming/PokemonLA_IngoMoveGrinder.h" +#include "Programs/Farming/PokemonLA_MagikarpMoveGrinder.h" +#include "Programs/Farming/PokemonLA_NuggetFarmerHighlands.h" +#include "Programs/Farming/PokemonLA_TenacityCandyFarmer.h" +#include "Programs/Farming/PokemonLA_LeapGrinder.h" + +//#include "Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h" +#include "Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h" +#include "Programs/ShinyHunting/PokemonLA_GalladeFinder.h" +#include "Programs/ShinyHunting/PokemonLA_CrobatFinder.h" +#include "Programs/ShinyHunting/PokemonLA_FroslassFinder.h" +#include "Programs/ShinyHunting/PokemonLA_BurmyFinder.h" +#include "Programs/ShinyHunting/PokemonLA_UnownFinder.h" +#include "Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h" +#include "Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h" +#include "Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h" + +#include "Programs/TestPrograms/PokemonLA_MountDetectionTest.h" +#include "Programs/TestPrograms/PokemonLA_OverworldWatcher.h" +#include "Programs/TestPrograms/PokemonLA_FlagNavigationTest.h" +#include "Programs/TestPrograms/PokemonLA_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Legends Arceus") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Trading ----"); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + + ret.emplace_back("---- Farming ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting ----"); +// ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Untested/Beta/WIP ----"); + ret.emplace_back(make_single_switch_program()); + } + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.h b/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.h index 6077b1ccda..df957d8cc6 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.h +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon Legends Arceus Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_Panels_H -#define PokemonAutomation_PokemonLA_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon Legends Arceus Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_Panels_H +#define PokemonAutomation_PokemonLA_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.cpp b/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.cpp index ea5aa76d11..2dff5bedc1 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.cpp +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.cpp @@ -1,152 +1,152 @@ -/* Pokemon Legends Arceus Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_general("General Settings:") - , POST_WARP_DELAY0( - "Post-Warp Delay:
After warping, wait this many seconds before continuing.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , m_menu_navigation("Menu Navigation Timings:") - , GAME_TO_HOME_DELAY0( - "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , LOAD_REGION_TIMEOUT0( - "Load Region Timeout:
Wait at most this long to enter a region before giving up.", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) - , m_start_game_timings("Start Game Timings:") - , START_GAME_MASH0( - "1. Start Game Mash:
Mash A for this long to start the game.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , START_GAME_WAIT1( - "2. Start Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "40 s" - ) - , ENTER_GAME_MASH0( - "3. Enter Game Mash:
Mash A for this long to enter the game.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , ENTER_GAME_WAIT0( - "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "15 s" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SHINY_SOUND_THRESHOLD( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.87, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 5000, 0, 48000 - ) - , ALPHA_ROAR_THRESHOLD( - "Alpha Roar Threshold:
Maximum error coefficient to trigger an alpha roar detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.65, 0, 1.0 - ) - , ALPHA_MUSIC_THRESHOLD( - "Alpha Music Threshold:
Maximum error coefficient to trigger an alpha music detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.81, 0, 1.0 - ) - , ITEM_DROP_SOUND_THRESHOLD( - "Item Drop Sound Threshold:
Maximum error coefficient to trigger an item drop sound detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.9, 0, 1.0 - ) - , ITEM_DROP_SOUND_LOW_FREQUENCY( - "Item Drop Sound Low Frequency (Hz):
High pass filter frequency for item drop sound.", - LockMode::LOCK_WHILE_RUNNING, - 5000, 0, 48000 - ) -{ - PA_ADD_STATIC(m_general); - PA_ADD_OPTION(POST_WARP_DELAY0); - - PA_ADD_STATIC(m_menu_navigation); - PA_ADD_OPTION(GAME_TO_HOME_DELAY0); - PA_ADD_OPTION(LOAD_REGION_TIMEOUT0); - - PA_ADD_STATIC(m_start_game_timings); - PA_ADD_OPTION(START_GAME_MASH0); - PA_ADD_OPTION(START_GAME_WAIT1); - PA_ADD_OPTION(ENTER_GAME_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); - PA_ADD_OPTION(ALPHA_ROAR_THRESHOLD); - PA_ADD_OPTION(ALPHA_MUSIC_THRESHOLD); - PA_ADD_OPTION(ITEM_DROP_SOUND_THRESHOLD); - PA_ADD_OPTION(ITEM_DROP_SOUND_LOW_FREQUENCY); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonLA:GlobalSettings", - STRING_POKEMON + " LA", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/PokemonSettings.md", - "Global " + STRING_POKEMON + " Legends Arceus Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon Legends Arceus Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_general("General Settings:") + , POST_WARP_DELAY0( + "Post-Warp Delay:
After warping, wait this many seconds before continuing.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , m_menu_navigation("Menu Navigation Timings:") + , GAME_TO_HOME_DELAY0( + "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , LOAD_REGION_TIMEOUT0( + "Load Region Timeout:
Wait at most this long to enter a region before giving up.", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) + , m_start_game_timings("Start Game Timings:") + , START_GAME_MASH0( + "1. Start Game Mash:
Mash A for this long to start the game.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , START_GAME_WAIT1( + "2. Start Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "40 s" + ) + , ENTER_GAME_MASH0( + "3. Enter Game Mash:
Mash A for this long to enter the game.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , ENTER_GAME_WAIT0( + "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "15 s" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SHINY_SOUND_THRESHOLD( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.87, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 5000, 0, 48000 + ) + , ALPHA_ROAR_THRESHOLD( + "Alpha Roar Threshold:
Maximum error coefficient to trigger an alpha roar detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.65, 0, 1.0 + ) + , ALPHA_MUSIC_THRESHOLD( + "Alpha Music Threshold:
Maximum error coefficient to trigger an alpha music detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.81, 0, 1.0 + ) + , ITEM_DROP_SOUND_THRESHOLD( + "Item Drop Sound Threshold:
Maximum error coefficient to trigger an item drop sound detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.9, 0, 1.0 + ) + , ITEM_DROP_SOUND_LOW_FREQUENCY( + "Item Drop Sound Low Frequency (Hz):
High pass filter frequency for item drop sound.", + LockMode::LOCK_WHILE_RUNNING, + 5000, 0, 48000 + ) +{ + PA_ADD_STATIC(m_general); + PA_ADD_OPTION(POST_WARP_DELAY0); + + PA_ADD_STATIC(m_menu_navigation); + PA_ADD_OPTION(GAME_TO_HOME_DELAY0); + PA_ADD_OPTION(LOAD_REGION_TIMEOUT0); + + PA_ADD_STATIC(m_start_game_timings); + PA_ADD_OPTION(START_GAME_MASH0); + PA_ADD_OPTION(START_GAME_WAIT1); + PA_ADD_OPTION(ENTER_GAME_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); + PA_ADD_OPTION(ALPHA_ROAR_THRESHOLD); + PA_ADD_OPTION(ALPHA_MUSIC_THRESHOLD); + PA_ADD_OPTION(ITEM_DROP_SOUND_THRESHOLD); + PA_ADD_OPTION(ITEM_DROP_SOUND_LOW_FREQUENCY); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonLA:GlobalSettings", + STRING_POKEMON + " LA", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/PokemonSettings.md", + "Global " + STRING_POKEMON + " Legends Arceus Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.h b/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.h index 8e7a16a896..b9982fd87c 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.h +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_Settings.h @@ -1,67 +1,67 @@ -/* Pokemon Legends Arceus Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_Settings_H -#define PokemonAutomation_PokemonLA_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_general; - MillisecondsOption POST_WARP_DELAY0; - - SectionDividerOption m_menu_navigation; - MillisecondsOption GAME_TO_HOME_DELAY0; - MillisecondsOption LOAD_REGION_TIMEOUT0; - - SectionDividerOption m_start_game_timings; - MillisecondsOption START_GAME_MASH0; - MillisecondsOption START_GAME_WAIT1; - MillisecondsOption ENTER_GAME_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_advanced_options; - FloatingPointOption SHINY_SOUND_THRESHOLD; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; - FloatingPointOption ALPHA_ROAR_THRESHOLD; - FloatingPointOption ALPHA_MUSIC_THRESHOLD; - FloatingPointOption ITEM_DROP_SOUND_THRESHOLD; - FloatingPointOption ITEM_DROP_SOUND_LOW_FREQUENCY; -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon Legends Arceus Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_Settings_H +#define PokemonAutomation_PokemonLA_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_general; + MillisecondsOption POST_WARP_DELAY0; + + SectionDividerOption m_menu_navigation; + MillisecondsOption GAME_TO_HOME_DELAY0; + MillisecondsOption LOAD_REGION_TIMEOUT0; + + SectionDividerOption m_start_game_timings; + MillisecondsOption START_GAME_MASH0; + MillisecondsOption START_GAME_WAIT1; + MillisecondsOption ENTER_GAME_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_advanced_options; + FloatingPointOption SHINY_SOUND_THRESHOLD; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; + FloatingPointOption ALPHA_ROAR_THRESHOLD; + FloatingPointOption ALPHA_MUSIC_THRESHOLD; + FloatingPointOption ITEM_DROP_SOUND_THRESHOLD; + FloatingPointOption ITEM_DROP_SOUND_LOW_FREQUENCY; +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.cpp b/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.cpp index 5d5488ff7e..dbb5d209d1 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.cpp +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.cpp @@ -1,211 +1,211 @@ -/* Travel Locations - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA_TravelLocations.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -TravelLocation::TravelLocation( - const char* p_slug, const char* p_display, - MapRegion p_region, - uint8_t p_warp_slot, uint8_t p_warp_sub_slot, - std::function&& p_post_arrival_maneuver, - bool p_reverse_sub_menu_direction -) - : slug(p_slug) - , display(p_display) - , region(p_region) - , warp_slot(p_warp_slot) - , warp_sub_slot(p_warp_sub_slot) - , reverse_sub_menu_direction(p_reverse_sub_menu_direction) - , post_arrival_maneuver(std::move(p_post_arrival_maneuver)) -{} - - -const TravelLocations& TravelLocations::instance(){ - static const TravelLocations locations; - return locations; -} -const IntegerEnumDropdownDatabase& TravelLocations::database() const{ - return m_database; -} - - -void TravelLocations::add_location(const TravelLocation& location){ - if (!m_map.emplace(location.display, &location).second){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - std::string("Duplicate TravelLocation name: ") + location.display - ); - } - m_list.emplace_back(&location); - m_database.add(m_list.size() - 1, location.slug, location.display, true); -} -TravelLocations::TravelLocations() - : Fieldlands_Fieldlands( - "fieldlands-fieldlands", - "Obsidian Fieldlands - Fieldlands Camp", - MapRegion::FIELDLANDS, 0, 0, nullptr - ) - , Fieldlands_Heights( - "fieldlands-heights", - "Obsidian Fieldlands - Heights Camp", - MapRegion::FIELDLANDS, 1, 0, nullptr - ) - , Fieldlands_Arena( - "fieldlands-arena", - "Obsidian Fieldlands - Grandtree Arena", - MapRegion::FIELDLANDS, 0, 2, nullptr - ) - - , Mirelands_Mirelands( - "mirelands-mirelands", - "Crimson Mirelands - Mirelands Camp", - MapRegion::MIRELANDS, 0, 0, nullptr - ) - , Mirelands_Bogbound( - "mirelands-bogboung", - "Crimson Mirelands - Bogbound Camp", - MapRegion::MIRELANDS, 1, 0, nullptr - ) - , Mirelands_DiamondSettlement( - "mirelands-settlement", - "Crimson Mirelands - Diamond Settlement", - MapRegion::MIRELANDS, 0, 2, nullptr - ) - , Mirelands_Arena( - "mirelands-arena", - "Crimson Mirelands - Brava Arena", - MapRegion::MIRELANDS, 0, 2, nullptr, true - ) - - , Coastlands_Beachside( - "coastlands-beachside", - "Cobalt Coastlands - Beachside Camp", - MapRegion::COASTLANDS, 0, 0, nullptr - ) - , Coastlands_Coastlands( - "coastlands-coastlands", - "Cobalt Coastlands - Coastlands Camp", - MapRegion::COASTLANDS, 1, 0, nullptr - ) - , Coastlands_Arena( - "coastlands-arena", - "Cobalt Coastlands - Molten Arena", - MapRegion::COASTLANDS, 0, 2, nullptr - ) - , Coastlands_Arena_NW( - "coastlands-arena-nw", - "Cobalt Coastlands - Molten Arena (NW of Volcano)", - MapRegion::COASTLANDS, 0, 2, [](VideoStream& stream, ProControllerContext& context){ - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_move_left_joystick(context, 160, 0, 160, 0); - pbf_mash_button(context, BUTTON_B, 4 * TICKS_PER_SECOND); - } - ) - - , Highlands_Highlands( - "highlands-highlands", - "Coronet Highlands - Highlands Camp", - MapRegion::HIGHLANDS, 0, 0, nullptr - ) - , Highlands_Mountain( - "highlands-mountain", - "Coronet Highlands - Mountain Camp", - MapRegion::HIGHLANDS, 1, 0, nullptr - ) - , Highlands_Summit( - "highlands-summit", - "Coronet Highlands - Summit Camp", - MapRegion::HIGHLANDS, 2, 0, nullptr - ) - , Highlands_Arena( - "highlands-arena", - "Coronet Highlands - Moonview Arena", - MapRegion::HIGHLANDS, 0, 2, nullptr, true - ) - - , Icelands_Snowfields( - "icelands-icelands", - "Alabaster Icelands - Snowfields Camp", - MapRegion::ICELANDS, 0, 0, nullptr - ) - , Icelands_Icepeak( - "icelands-icepeak", - "Alabaster Icelands - Icepeak Camp", - MapRegion::ICELANDS, 1, 0, nullptr - ) - , Icelands_PearlSettlement( - "icelands-settlement", - "Alabaster Icelands - Pearl Settlement", - MapRegion::ICELANDS, 0, 2, nullptr - ) - , Icelands_PearlSettlement_SW( - "icelands-settlement-sw", - "Alabaster Icelands - Pearl Settlement (SW of landing spot)", - MapRegion::ICELANDS, 0, 2, [](VideoStream& stream, ProControllerContext& context){ - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_move_left_joystick(context, 192, 255, 160, 0); - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - } - ) - , Icelands_Arena( - "icelands-arena", - "Alabaster Icelands - Icepeak Arena", - MapRegion::ICELANDS, 0, 2, nullptr, true - ) - , Retreat( - "retreat", - "Ancient Retreat", - MapRegion::RETREAT, 0, 0, nullptr, false - ) -{ - add_location(Fieldlands_Fieldlands); - add_location(Fieldlands_Heights); - add_location(Fieldlands_Arena); - - add_location(Mirelands_Mirelands); - add_location(Mirelands_Bogbound); - add_location(Mirelands_DiamondSettlement); - add_location(Mirelands_Arena); - - add_location(Coastlands_Beachside); - add_location(Coastlands_Coastlands); - add_location(Coastlands_Arena); - add_location(Coastlands_Arena_NW); - - add_location(Highlands_Highlands); - add_location(Highlands_Mountain); - add_location(Highlands_Summit); - add_location(Highlands_Arena); - - add_location(Icelands_Snowfields); - add_location(Icelands_Icepeak); - add_location(Icelands_PearlSettlement); - add_location(Icelands_PearlSettlement_SW); - add_location(Icelands_Arena); - add_location(Retreat); -} - - - - - - - - - -} -} -} +/* Travel Locations + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA_TravelLocations.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +TravelLocation::TravelLocation( + const char* p_slug, const char* p_display, + MapRegion p_region, + uint8_t p_warp_slot, uint8_t p_warp_sub_slot, + std::function&& p_post_arrival_maneuver, + bool p_reverse_sub_menu_direction +) + : slug(p_slug) + , display(p_display) + , region(p_region) + , warp_slot(p_warp_slot) + , warp_sub_slot(p_warp_sub_slot) + , reverse_sub_menu_direction(p_reverse_sub_menu_direction) + , post_arrival_maneuver(std::move(p_post_arrival_maneuver)) +{} + + +const TravelLocations& TravelLocations::instance(){ + static const TravelLocations locations; + return locations; +} +const IntegerEnumDropdownDatabase& TravelLocations::database() const{ + return m_database; +} + + +void TravelLocations::add_location(const TravelLocation& location){ + if (!m_map.emplace(location.display, &location).second){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + std::string("Duplicate TravelLocation name: ") + location.display + ); + } + m_list.emplace_back(&location); + m_database.add(m_list.size() - 1, location.slug, location.display, true); +} +TravelLocations::TravelLocations() + : Fieldlands_Fieldlands( + "fieldlands-fieldlands", + "Obsidian Fieldlands - Fieldlands Camp", + MapRegion::FIELDLANDS, 0, 0, nullptr + ) + , Fieldlands_Heights( + "fieldlands-heights", + "Obsidian Fieldlands - Heights Camp", + MapRegion::FIELDLANDS, 1, 0, nullptr + ) + , Fieldlands_Arena( + "fieldlands-arena", + "Obsidian Fieldlands - Grandtree Arena", + MapRegion::FIELDLANDS, 0, 2, nullptr + ) + + , Mirelands_Mirelands( + "mirelands-mirelands", + "Crimson Mirelands - Mirelands Camp", + MapRegion::MIRELANDS, 0, 0, nullptr + ) + , Mirelands_Bogbound( + "mirelands-bogboung", + "Crimson Mirelands - Bogbound Camp", + MapRegion::MIRELANDS, 1, 0, nullptr + ) + , Mirelands_DiamondSettlement( + "mirelands-settlement", + "Crimson Mirelands - Diamond Settlement", + MapRegion::MIRELANDS, 0, 2, nullptr + ) + , Mirelands_Arena( + "mirelands-arena", + "Crimson Mirelands - Brava Arena", + MapRegion::MIRELANDS, 0, 2, nullptr, true + ) + + , Coastlands_Beachside( + "coastlands-beachside", + "Cobalt Coastlands - Beachside Camp", + MapRegion::COASTLANDS, 0, 0, nullptr + ) + , Coastlands_Coastlands( + "coastlands-coastlands", + "Cobalt Coastlands - Coastlands Camp", + MapRegion::COASTLANDS, 1, 0, nullptr + ) + , Coastlands_Arena( + "coastlands-arena", + "Cobalt Coastlands - Molten Arena", + MapRegion::COASTLANDS, 0, 2, nullptr + ) + , Coastlands_Arena_NW( + "coastlands-arena-nw", + "Cobalt Coastlands - Molten Arena (NW of Volcano)", + MapRegion::COASTLANDS, 0, 2, [](VideoStream& stream, ProControllerContext& context){ + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_move_left_joystick(context, 160, 0, 160, 0); + pbf_mash_button(context, BUTTON_B, 4 * TICKS_PER_SECOND); + } + ) + + , Highlands_Highlands( + "highlands-highlands", + "Coronet Highlands - Highlands Camp", + MapRegion::HIGHLANDS, 0, 0, nullptr + ) + , Highlands_Mountain( + "highlands-mountain", + "Coronet Highlands - Mountain Camp", + MapRegion::HIGHLANDS, 1, 0, nullptr + ) + , Highlands_Summit( + "highlands-summit", + "Coronet Highlands - Summit Camp", + MapRegion::HIGHLANDS, 2, 0, nullptr + ) + , Highlands_Arena( + "highlands-arena", + "Coronet Highlands - Moonview Arena", + MapRegion::HIGHLANDS, 0, 2, nullptr, true + ) + + , Icelands_Snowfields( + "icelands-icelands", + "Alabaster Icelands - Snowfields Camp", + MapRegion::ICELANDS, 0, 0, nullptr + ) + , Icelands_Icepeak( + "icelands-icepeak", + "Alabaster Icelands - Icepeak Camp", + MapRegion::ICELANDS, 1, 0, nullptr + ) + , Icelands_PearlSettlement( + "icelands-settlement", + "Alabaster Icelands - Pearl Settlement", + MapRegion::ICELANDS, 0, 2, nullptr + ) + , Icelands_PearlSettlement_SW( + "icelands-settlement-sw", + "Alabaster Icelands - Pearl Settlement (SW of landing spot)", + MapRegion::ICELANDS, 0, 2, [](VideoStream& stream, ProControllerContext& context){ + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_move_left_joystick(context, 192, 255, 160, 0); + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + } + ) + , Icelands_Arena( + "icelands-arena", + "Alabaster Icelands - Icepeak Arena", + MapRegion::ICELANDS, 0, 2, nullptr, true + ) + , Retreat( + "retreat", + "Ancient Retreat", + MapRegion::RETREAT, 0, 0, nullptr, false + ) +{ + add_location(Fieldlands_Fieldlands); + add_location(Fieldlands_Heights); + add_location(Fieldlands_Arena); + + add_location(Mirelands_Mirelands); + add_location(Mirelands_Bogbound); + add_location(Mirelands_DiamondSettlement); + add_location(Mirelands_Arena); + + add_location(Coastlands_Beachside); + add_location(Coastlands_Coastlands); + add_location(Coastlands_Arena); + add_location(Coastlands_Arena_NW); + + add_location(Highlands_Highlands); + add_location(Highlands_Mountain); + add_location(Highlands_Summit); + add_location(Highlands_Arena); + + add_location(Icelands_Snowfields); + add_location(Icelands_Icepeak); + add_location(Icelands_PearlSettlement); + add_location(Icelands_PearlSettlement_SW); + add_location(Icelands_Arena); + add_location(Retreat); +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.h b/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.h index d2e68881ed..03b1bb2b40 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.h +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_TravelLocations.h @@ -1,103 +1,103 @@ -/* Travel Locations - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_TravelLocations_H -#define PokemonAutomation_PokemonLA_TravelLocations_H - -#include -#include -#include -#include -#include "Common/Cpp/Options/EnumDropdownDatabase.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonLA_Locations.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -struct TravelLocation{ - const char* slug; - const char* display; - - MapRegion region; - uint8_t warp_slot; // which menu slot to warp from the full-Hisui map when leaving the village. - uint8_t warp_sub_slot; // which menu slot to warp the region map, if the location is a settlement or arena that requires an in-region warp. - bool reverse_sub_menu_direction; // whether it is faster to go upwards in the in-region warp map to reach the destination slot. - - std::function post_arrival_maneuver; - - TravelLocation( - const char* p_slug, const char* p_display, - MapRegion p_region, - uint8_t p_warp_slot, uint8_t p_warp_sub_slot, - std::function&& p_post_arrival_maneuver, - bool reverse_sub_menu_direction = false - ); -}; - - -class TravelLocations{ -public: - static const TravelLocations& instance(); - - const TravelLocation& operator[](size_t index) const{ - return *m_list[index]; - } - const IntegerEnumDropdownDatabase& database() const; - - -public: - const TravelLocation Fieldlands_Fieldlands; - const TravelLocation Fieldlands_Heights; - const TravelLocation Fieldlands_Arena; - - const TravelLocation Mirelands_Mirelands; - const TravelLocation Mirelands_Bogbound; - const TravelLocation Mirelands_DiamondSettlement; - const TravelLocation Mirelands_Arena; - - const TravelLocation Coastlands_Beachside; - const TravelLocation Coastlands_Coastlands; - const TravelLocation Coastlands_Arena; - const TravelLocation Coastlands_Arena_NW; - - const TravelLocation Highlands_Highlands; - const TravelLocation Highlands_Mountain; - const TravelLocation Highlands_Summit; - const TravelLocation Highlands_Arena; - - const TravelLocation Icelands_Snowfields; - const TravelLocation Icelands_Icepeak; - const TravelLocation Icelands_PearlSettlement; - const TravelLocation Icelands_PearlSettlement_SW; - const TravelLocation Icelands_Arena; - - const TravelLocation Retreat; - - -private: - TravelLocations(); - void add_location(const TravelLocation& location); - - std::vector m_list; - std::map m_map; - - IntegerEnumDropdownDatabase m_database; -}; - - - - - - -} -} -} -#endif +/* Travel Locations + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_TravelLocations_H +#define PokemonAutomation_PokemonLA_TravelLocations_H + +#include +#include +#include +#include +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonLA_Locations.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +struct TravelLocation{ + const char* slug; + const char* display; + + MapRegion region; + uint8_t warp_slot; // which menu slot to warp from the full-Hisui map when leaving the village. + uint8_t warp_sub_slot; // which menu slot to warp the region map, if the location is a settlement or arena that requires an in-region warp. + bool reverse_sub_menu_direction; // whether it is faster to go upwards in the in-region warp map to reach the destination slot. + + std::function post_arrival_maneuver; + + TravelLocation( + const char* p_slug, const char* p_display, + MapRegion p_region, + uint8_t p_warp_slot, uint8_t p_warp_sub_slot, + std::function&& p_post_arrival_maneuver, + bool reverse_sub_menu_direction = false + ); +}; + + +class TravelLocations{ +public: + static const TravelLocations& instance(); + + const TravelLocation& operator[](size_t index) const{ + return *m_list[index]; + } + const IntegerEnumDropdownDatabase& database() const; + + +public: + const TravelLocation Fieldlands_Fieldlands; + const TravelLocation Fieldlands_Heights; + const TravelLocation Fieldlands_Arena; + + const TravelLocation Mirelands_Mirelands; + const TravelLocation Mirelands_Bogbound; + const TravelLocation Mirelands_DiamondSettlement; + const TravelLocation Mirelands_Arena; + + const TravelLocation Coastlands_Beachside; + const TravelLocation Coastlands_Coastlands; + const TravelLocation Coastlands_Arena; + const TravelLocation Coastlands_Arena_NW; + + const TravelLocation Highlands_Highlands; + const TravelLocation Highlands_Mountain; + const TravelLocation Highlands_Summit; + const TravelLocation Highlands_Arena; + + const TravelLocation Icelands_Snowfields; + const TravelLocation Icelands_Icepeak; + const TravelLocation Icelands_PearlSettlement; + const TravelLocation Icelands_PearlSettlement_SW; + const TravelLocation Icelands_Arena; + + const TravelLocation Retreat; + + +private: + TravelLocations(); + void add_location(const TravelLocation& location); + + std::vector m_list; + std::map m_map; + + IntegerEnumDropdownDatabase m_database; +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.cpp b/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.cpp index 7019256141..9498872626 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.cpp +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.cpp @@ -1,76 +1,76 @@ -/* Weather and Time of Day Definitions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonLA_WeatherAndTime.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -const std::array WEATHER_NAMES = { - "Sunny", - "Cloudy", - "Rain", - "Snowy", - "Drought", - "Fog", - "Rainstorm", - "Snowstorm" -}; - -Weather get_weather(const std::string& name){ - const auto it = std::find(WEATHER_NAMES.begin(), WEATHER_NAMES.end(), name); - if (it == WEATHER_NAMES.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown weather name: " + name); - } - - return Weather(std::distance(WEATHER_NAMES.begin(), it)); -} - - - -const std::array TIME_OF_DAY_NAMES = { - "None", - "Morning", - "Midday", - "Evening", - "Midnight" -}; - -char timeOfDayOneLetter(TimeOfDay time){ - switch (time){ - case TimeOfDay::NONE: - return 'S'; // "S"ame time, no change on time of day - case TimeOfDay::MORNING: - return 'M'; - case TimeOfDay::MIDDAY: - return 'D'; - case TimeOfDay::EVENING: - return 'E'; - case TimeOfDay::MIDNIGHT: - return 'N'; - } - return '\0'; -} - -TimeOfDay get_time_of_day(const std::string& name){ - const auto it = std::find(TIME_OF_DAY_NAMES.begin(), TIME_OF_DAY_NAMES.end(), name); - if (it == TIME_OF_DAY_NAMES.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown time of day name: " + name); - } - - return TimeOfDay(std::distance(TIME_OF_DAY_NAMES.begin(), it)); -} - - -} -} -} +/* Weather and Time of Day Definitions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonLA_WeatherAndTime.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +const std::array WEATHER_NAMES = { + "Sunny", + "Cloudy", + "Rain", + "Snowy", + "Drought", + "Fog", + "Rainstorm", + "Snowstorm" +}; + +Weather get_weather(const std::string& name){ + const auto it = std::find(WEATHER_NAMES.begin(), WEATHER_NAMES.end(), name); + if (it == WEATHER_NAMES.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown weather name: " + name); + } + + return Weather(std::distance(WEATHER_NAMES.begin(), it)); +} + + + +const std::array TIME_OF_DAY_NAMES = { + "None", + "Morning", + "Midday", + "Evening", + "Midnight" +}; + +char timeOfDayOneLetter(TimeOfDay time){ + switch (time){ + case TimeOfDay::NONE: + return 'S'; // "S"ame time, no change on time of day + case TimeOfDay::MORNING: + return 'M'; + case TimeOfDay::MIDDAY: + return 'D'; + case TimeOfDay::EVENING: + return 'E'; + case TimeOfDay::MIDNIGHT: + return 'N'; + } + return '\0'; +} + +TimeOfDay get_time_of_day(const std::string& name){ + const auto it = std::find(TIME_OF_DAY_NAMES.begin(), TIME_OF_DAY_NAMES.end(), name); + if (it == TIME_OF_DAY_NAMES.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown time of day name: " + name); + } + + return TimeOfDay(std::distance(TIME_OF_DAY_NAMES.begin(), it)); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.h b/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.h index 67866eaffe..5ca901925c 100644 --- a/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.h +++ b/SerialPrograms/Source/PokemonLA/PokemonLA_WeatherAndTime.h @@ -1,78 +1,78 @@ -/* Weather and Time of Day Definitions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_WeatherAndTime_H -#define PokemonAutomation_PokemonLA_WeatherAndTime_H - -#include -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -enum class Weather{ - SUNNY = 0, - CLOUDY, - RAIN, - SNOW, - DROUGHT, - FOG, - RAINSTORM, - SNOWSTORM, -}; - -constexpr size_t NUM_WEATHER = 8; - -// Map from int(Weather) to their names -// "Sunny", -// "Cloudy", -// "Rain", -// "Snowy", -// "Drought", -// "Fog", -// "Rainstorm", -// "Snowstorm" -extern const std::array WEATHER_NAMES; - -// From weather name (listed in WEATHER_NAMES) to enum -Weather get_weather(const std::string& name); - -// The order of `TimeOfDay` enums corresponds to the order -// of setting the time in the camp, with `NONE` being no -// change of time while using the camp -enum class TimeOfDay{ - NONE = 0, - MORNING, - MIDDAY, - EVENING, - MIDNIGHT -}; - -// Number of time setting options listed in enum TimeOfDay -constexpr size_t NUM_TIME_CHANGE_CHOICES = 5; -// Number of unique times -constexpr size_t NUM_TIMES_OF_DAY = 4; - -// Map from int(TimeOfDay) to their names -// "None", -// "Morning", -// "Midday", -// "Evening", -// "Midnight" -extern const std::array TIME_OF_DAY_NAMES; - -// Use one char to represent a time of day -char timeOfDayOneLetter(TimeOfDay time); - -// From time of day name (listed in TIME_OF_DAY_NAMES) to enum -TimeOfDay get_time_of_day(const std::string& name); - -} -} -} -#endif +/* Weather and Time of Day Definitions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_WeatherAndTime_H +#define PokemonAutomation_PokemonLA_WeatherAndTime_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +enum class Weather{ + SUNNY = 0, + CLOUDY, + RAIN, + SNOW, + DROUGHT, + FOG, + RAINSTORM, + SNOWSTORM, +}; + +constexpr size_t NUM_WEATHER = 8; + +// Map from int(Weather) to their names +// "Sunny", +// "Cloudy", +// "Rain", +// "Snowy", +// "Drought", +// "Fog", +// "Rainstorm", +// "Snowstorm" +extern const std::array WEATHER_NAMES; + +// From weather name (listed in WEATHER_NAMES) to enum +Weather get_weather(const std::string& name); + +// The order of `TimeOfDay` enums corresponds to the order +// of setting the time in the camp, with `NONE` being no +// change of time while using the camp +enum class TimeOfDay{ + NONE = 0, + MORNING, + MIDDAY, + EVENING, + MIDNIGHT +}; + +// Number of time setting options listed in enum TimeOfDay +constexpr size_t NUM_TIME_CHANGE_CHOICES = 5; +// Number of unique times +constexpr size_t NUM_TIMES_OF_DAY = 4; + +// Map from int(TimeOfDay) to their names +// "None", +// "Morning", +// "Midday", +// "Evening", +// "Midnight" +extern const std::array TIME_OF_DAY_NAMES; + +// Use one char to represent a time of day +char timeOfDayOneLetter(TimeOfDay time); + +// From time of day name (listed in TIME_OF_DAY_NAMES) to enum +TimeOfDay get_time_of_day(const std::string& name); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.cpp index 757bc085e8..351bc304c8 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.cpp @@ -1,417 +1,417 @@ -/* Ingo Battle Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" -#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" -#include "PokemonLA_IngoBattleGrinder.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - -// #define DEBUG_INGO_BATTLE - - - -IngoBattleGrinder_Descriptor::IngoBattleGrinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:IngoBattleGrinder", - STRING_POKEMON + " LA", "Ingo Battle Grinder", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/IngoBattleGrinder.md", - "Attend Ingo's battles to grind exp and move related " + STRING_POKEDEX + " research tasks. Less effective than Ingo Move Grinder for " + STRING_POKEDEX + " research tasks but more effective for everything else.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class IngoBattleGrinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : battles(m_stats["Battles"]) - , turns(m_stats["Turns"]) - , lead_move_attempts(m_stats["Lead Move Attempts"]) - , faint_switches(m_stats["Faint Switches"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Battles"); - m_display_order.emplace_back("Turns"); - m_display_order.emplace_back("Lead Move Attempts"); - m_display_order.emplace_back("Faint Switches", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - - std::atomic& battles; - std::atomic& turns; - std::atomic& lead_move_attempts; - std::atomic& faint_switches; - std::atomic& errors; -}; -std::unique_ptr IngoBattleGrinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -IngoBattleGrinder::IngoBattleGrinder() - : NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(OPPONENT); - PA_ADD_OPTION(POKEMON_ACTIONS); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -bool IngoBattleGrinder::start_dialog(VideoStream& stream, ProControllerContext& context){ - // First press A to start talking with Ingo. - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - { - ButtonDetector button0( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.408, 0.40, 0.042}, - std::chrono::milliseconds(100), - true - ); - ButtonDetector button1( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.450, 0.40, 0.042}, - std::chrono::milliseconds(100), - true - ); - ButtonDetector button2( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.492, 0.40, 0.042}, - std::chrono::milliseconds(100), - true - ); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, 150); - } - }, - { - {button0}, - {button1}, - {button2}, - } - ); - switch (ret){ - case 0: - // Version 1.1 without new options unlocked. - return false; - case 1: - // Version 1.0 - return true; - case 2: - // Version 1.1 with new options unlocked. - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect options after 10 A presses.", - stream - ); - } - } - - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - ButtonDetector button2( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.350, 0.40, 0.400}, - std::chrono::milliseconds(100), - true - ); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 5; c++){ - pbf_press_button(context, BUTTON_A, 20, 150); - } - }, - {{button2}} - ); - switch (ret){ - case 0: - return false; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find opponent list options after 5 A presses.", - stream - ); - } -} - - -bool IngoBattleGrinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::map& pokemon_move_attempts){ - IngoBattleGrinder_Descriptor::Stats& stats = env.current_stats(); - - env.console.log("Starting battle..."); - - // Talk to Ingo to start conversation and select regular battles: - // The dialogues are different between version 10 (the vanilla version) and later versions. - bool version_10 = start_dialog(env.console, context); - env.log(std::string("Detected current version: ") + (version_10 ? "1.0" : "1.2")); - - IngoOpponentMenuLocation menu_location = version_10 - ? INGO_OPPONENT_MENU_LOCATIONS_V10[OPPONENT.current_value()] - : INGO_OPPONENT_MENU_LOCATIONS_V12[OPPONENT.current_value()]; - - // Choose which opponent - if (menu_location.page < 0){ - throw UserSetupError(env.console, "Opponent doesn't exist in this version of the game."); - } - - // Move to page. - for (int8_t c = 0; c < menu_location.page; c++){ - pbf_press_dpad(context, DPAD_UP, 10, 60); - pbf_press_dpad(context, DPAD_UP, 10, 60); - pbf_press_button(context, BUTTON_A, 10, 100); - } - - // Move to slot. - for (int8_t c = 0; c < menu_location.index; c++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 60); - } - - // Press the button to select the opponent - pbf_press_button(context, BUTTON_A, 10, 115); - pbf_wait(context, 1 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - env.log("Finish selecting the opponent. Battle should start now."); - - // Which move (0, 1, 2 or 3) to use in next turn. - size_t cur_move = 0; - // The battle-order index of the current pokemon on the battle field. - // This index starts at 0. Whenever a new pokemon is sent to battle, the index adds by 1. - // It is equal to how many pokemon have left the battle. - // Note: battle order is different than party order, which is the order of the pokemon in the party. - // When the player selects a pokemon in the lower right corner of the screen in the overworld using "L" - // and "R" buttons, this pokemon will be sent to the battle first, with battle-order index of 0. But this - // pokemon can be in any place in the party list, therefore can have any party-order index. - size_t cur_pokemon = 0; - // How many turns have passed for the current pokemon in this battle. - // This turn count is reset to zero when a new pokemon is sent to battle. - size_t num_turns = 0; - // Used to skip fainted pokemon in the party when switching a pokemon - // This is the party-order index of the pokemon to switch to. - // The index is the index in the pokemon party list. - size_t next_pokemon_to_switch_to = 0; - - // Whether this is the last battle. After the last battle ends, stops the program. - bool last_battle = false; - - // Switch pokemon and update the battle states: - auto switch_cur_pokemon = [&](){ - cur_move = 0; - num_turns = 0; - next_pokemon_to_switch_to = switch_pokemon(env.console, context, next_pokemon_to_switch_to); - next_pokemon_to_switch_to++; - cur_pokemon++; - }; - - while(true){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); - // dialogue ellipse appears on a semi-transparent dialog box if you win the fight. - DialogueEllipseDetector dialogue_ellipse_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); - // normal dialogue appears if you lose the fight. - NormalDialogDetector normal_dialogue_detector(env.console, env.console, stop_on_detected); - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - int ret = wait_until( - env.console, context, std::chrono::minutes(2), - { - {battle_menu_detector}, - {dialogue_ellipse_detector}, - {normal_dialogue_detector}, - {pokemon_switch_detector}, - {arc_phone_detector}, - } - ); - if (ret < 0){ - env.console.log("Error: Failed to find battle menu after 2 minutes."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find battle menu after 2 minutes.", - env.console - ); - } - - if (ret == 0){ - env.console.log("Our turn!", COLOR_BLUE); - stats.turns++; - - // User may want to switch the pokemon after some turns, to get more exp, or prevent if from - // fainting. - if (POKEMON_ACTIONS.switch_pokemon(cur_pokemon, num_turns)){ - env.console.log("Switch pokemon"); - - // Go to the switching pokemon screen: - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - - switch_cur_pokemon(); - }else{ - // Choose move to use! - if (cur_pokemon == 0){ - // We collect the stat of move attempts of the first pokemon. - stats.lead_move_attempts++; - } - - // Press A to select moves - pbf_press_button(context, BUTTON_A, 10, 125); - context.wait_for_all_requests(); - - // Use move. - // Use while loop to go to next move if the current move has no PP. - // No PP is detected by checking whether the pixels on the selected move menu item is still the same - // after about one second. - // Note: if the pokemon has no PP on any moves and results to Struggle, the fight animation should - // ensure we won't get the same pixels on the area that the move menu item would appear, so we won't - // get stuck in this while loop. - MoveStyle style = POKEMON_ACTIONS.get_style(cur_pokemon, cur_move); - const bool check_move_success = true; - while (use_move(env.console, context, cur_pokemon, cur_move, style, check_move_success) == false){ - // We are still on the move selection screen. No PP. - if (cur_move == 3){ - // Pokemon has zero PP on all moves. This should not happen as it will just use - // Struggle. - env.console.log("No PP on all moves. Abort program.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No PP on all moves.", - env.console - ); - } - - // Go to the next move. - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - // env.console.context().wait_for_all_requests(); - cur_move++; - env.console.log("No PP. Use next move, " + std::to_string(cur_move), COLOR_RED); - - style = POKEMON_ACTIONS.get_style(cur_pokemon, cur_move); - } - - num_turns++; - pokemon_move_attempts[cur_pokemon]++; - // Check whether to stop battle - if (last_battle == false){ - last_battle = POKEMON_ACTIONS.stop_battle(cur_pokemon, pokemon_move_attempts[cur_pokemon]); - if (last_battle){ - env.log("Target move attempts reached: " + std::to_string(pokemon_move_attempts[cur_pokemon]) + - ". Stop program after this battle finishes."); - } - } - } - - env.update_stats(); - }else if (ret == 1){ - env.console.log("Transparent dialogue box."); - - pbf_press_button(context, BUTTON_B, 20, 100); - context.wait_for_all_requests(); - }else if(ret == 2){ - env.console.log("Normal dialogue box."); - - pbf_press_button(context, BUTTON_B, 20, 100); - context.wait_for_all_requests(); - }else if (ret == 3){ - env.console.log("Pokemon fainted.", COLOR_RED); - stats.faint_switches++; - env.update_stats(); - - switch_cur_pokemon(); - }else{ // ret is 4 - env.console.log("Battle finished."); - break; - } - } - - stats.battles++; - env.update_stats(); - - return last_battle; -} - - - -void IngoBattleGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - IngoBattleGrinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - // { - // // ImageRGB32 image("./scripts/LA_switch_pokemon_Kuro.png"); - // ImageRGB32 image("./PLA_test_data/ingoBattle/broken_dialogue_detector.png"); - // const bool stop_on_detected = true; - // NormalDialogDetector detector(env.console, env.console, stop_on_detected); - // bool detected = detector.process_frame(image, current_time()); - // std::cout << "detector " << detected << std::endl; - // return; - // } - - // pokemon index -> number of move attempts made so far - std::map pokemon_move_attempts; - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - if (run_iteration(env, context, pokemon_move_attempts)){ - break; - } - }catch (OperationFailedException&){ - stats.errors++; - throw; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Ingo Battle Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" +#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" +#include "PokemonLA_IngoBattleGrinder.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + +// #define DEBUG_INGO_BATTLE + + + +IngoBattleGrinder_Descriptor::IngoBattleGrinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:IngoBattleGrinder", + STRING_POKEMON + " LA", "Ingo Battle Grinder", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/IngoBattleGrinder.md", + "Attend Ingo's battles to grind exp and move related " + STRING_POKEDEX + " research tasks. Less effective than Ingo Move Grinder for " + STRING_POKEDEX + " research tasks but more effective for everything else.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class IngoBattleGrinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : battles(m_stats["Battles"]) + , turns(m_stats["Turns"]) + , lead_move_attempts(m_stats["Lead Move Attempts"]) + , faint_switches(m_stats["Faint Switches"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Battles"); + m_display_order.emplace_back("Turns"); + m_display_order.emplace_back("Lead Move Attempts"); + m_display_order.emplace_back("Faint Switches", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + + std::atomic& battles; + std::atomic& turns; + std::atomic& lead_move_attempts; + std::atomic& faint_switches; + std::atomic& errors; +}; +std::unique_ptr IngoBattleGrinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +IngoBattleGrinder::IngoBattleGrinder() + : NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(OPPONENT); + PA_ADD_OPTION(POKEMON_ACTIONS); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +bool IngoBattleGrinder::start_dialog(VideoStream& stream, ProControllerContext& context){ + // First press A to start talking with Ingo. + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + { + ButtonDetector button0( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.408, 0.40, 0.042}, + std::chrono::milliseconds(100), + true + ); + ButtonDetector button1( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.450, 0.40, 0.042}, + std::chrono::milliseconds(100), + true + ); + ButtonDetector button2( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.492, 0.40, 0.042}, + std::chrono::milliseconds(100), + true + ); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, 150); + } + }, + { + {button0}, + {button1}, + {button2}, + } + ); + switch (ret){ + case 0: + // Version 1.1 without new options unlocked. + return false; + case 1: + // Version 1.0 + return true; + case 2: + // Version 1.1 with new options unlocked. + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect options after 10 A presses.", + stream + ); + } + } + + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + ButtonDetector button2( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.350, 0.40, 0.400}, + std::chrono::milliseconds(100), + true + ); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 5; c++){ + pbf_press_button(context, BUTTON_A, 20, 150); + } + }, + {{button2}} + ); + switch (ret){ + case 0: + return false; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find opponent list options after 5 A presses.", + stream + ); + } +} + + +bool IngoBattleGrinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::map& pokemon_move_attempts){ + IngoBattleGrinder_Descriptor::Stats& stats = env.current_stats(); + + env.console.log("Starting battle..."); + + // Talk to Ingo to start conversation and select regular battles: + // The dialogues are different between version 10 (the vanilla version) and later versions. + bool version_10 = start_dialog(env.console, context); + env.log(std::string("Detected current version: ") + (version_10 ? "1.0" : "1.2")); + + IngoOpponentMenuLocation menu_location = version_10 + ? INGO_OPPONENT_MENU_LOCATIONS_V10[OPPONENT.current_value()] + : INGO_OPPONENT_MENU_LOCATIONS_V12[OPPONENT.current_value()]; + + // Choose which opponent + if (menu_location.page < 0){ + throw UserSetupError(env.console, "Opponent doesn't exist in this version of the game."); + } + + // Move to page. + for (int8_t c = 0; c < menu_location.page; c++){ + pbf_press_dpad(context, DPAD_UP, 10, 60); + pbf_press_dpad(context, DPAD_UP, 10, 60); + pbf_press_button(context, BUTTON_A, 10, 100); + } + + // Move to slot. + for (int8_t c = 0; c < menu_location.index; c++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 60); + } + + // Press the button to select the opponent + pbf_press_button(context, BUTTON_A, 10, 115); + pbf_wait(context, 1 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + env.log("Finish selecting the opponent. Battle should start now."); + + // Which move (0, 1, 2 or 3) to use in next turn. + size_t cur_move = 0; + // The battle-order index of the current pokemon on the battle field. + // This index starts at 0. Whenever a new pokemon is sent to battle, the index adds by 1. + // It is equal to how many pokemon have left the battle. + // Note: battle order is different than party order, which is the order of the pokemon in the party. + // When the player selects a pokemon in the lower right corner of the screen in the overworld using "L" + // and "R" buttons, this pokemon will be sent to the battle first, with battle-order index of 0. But this + // pokemon can be in any place in the party list, therefore can have any party-order index. + size_t cur_pokemon = 0; + // How many turns have passed for the current pokemon in this battle. + // This turn count is reset to zero when a new pokemon is sent to battle. + size_t num_turns = 0; + // Used to skip fainted pokemon in the party when switching a pokemon + // This is the party-order index of the pokemon to switch to. + // The index is the index in the pokemon party list. + size_t next_pokemon_to_switch_to = 0; + + // Whether this is the last battle. After the last battle ends, stops the program. + bool last_battle = false; + + // Switch pokemon and update the battle states: + auto switch_cur_pokemon = [&](){ + cur_move = 0; + num_turns = 0; + next_pokemon_to_switch_to = switch_pokemon(env.console, context, next_pokemon_to_switch_to); + next_pokemon_to_switch_to++; + cur_pokemon++; + }; + + while(true){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); + // dialogue ellipse appears on a semi-transparent dialog box if you win the fight. + DialogueEllipseDetector dialogue_ellipse_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); + // normal dialogue appears if you lose the fight. + NormalDialogDetector normal_dialogue_detector(env.console, env.console, stop_on_detected); + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + int ret = wait_until( + env.console, context, std::chrono::minutes(2), + { + {battle_menu_detector}, + {dialogue_ellipse_detector}, + {normal_dialogue_detector}, + {pokemon_switch_detector}, + {arc_phone_detector}, + } + ); + if (ret < 0){ + env.console.log("Error: Failed to find battle menu after 2 minutes."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find battle menu after 2 minutes.", + env.console + ); + } + + if (ret == 0){ + env.console.log("Our turn!", COLOR_BLUE); + stats.turns++; + + // User may want to switch the pokemon after some turns, to get more exp, or prevent if from + // fainting. + if (POKEMON_ACTIONS.switch_pokemon(cur_pokemon, num_turns)){ + env.console.log("Switch pokemon"); + + // Go to the switching pokemon screen: + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + + switch_cur_pokemon(); + }else{ + // Choose move to use! + if (cur_pokemon == 0){ + // We collect the stat of move attempts of the first pokemon. + stats.lead_move_attempts++; + } + + // Press A to select moves + pbf_press_button(context, BUTTON_A, 10, 125); + context.wait_for_all_requests(); + + // Use move. + // Use while loop to go to next move if the current move has no PP. + // No PP is detected by checking whether the pixels on the selected move menu item is still the same + // after about one second. + // Note: if the pokemon has no PP on any moves and results to Struggle, the fight animation should + // ensure we won't get the same pixels on the area that the move menu item would appear, so we won't + // get stuck in this while loop. + MoveStyle style = POKEMON_ACTIONS.get_style(cur_pokemon, cur_move); + const bool check_move_success = true; + while (use_move(env.console, context, cur_pokemon, cur_move, style, check_move_success) == false){ + // We are still on the move selection screen. No PP. + if (cur_move == 3){ + // Pokemon has zero PP on all moves. This should not happen as it will just use + // Struggle. + env.console.log("No PP on all moves. Abort program.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No PP on all moves.", + env.console + ); + } + + // Go to the next move. + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + // env.console.context().wait_for_all_requests(); + cur_move++; + env.console.log("No PP. Use next move, " + std::to_string(cur_move), COLOR_RED); + + style = POKEMON_ACTIONS.get_style(cur_pokemon, cur_move); + } + + num_turns++; + pokemon_move_attempts[cur_pokemon]++; + // Check whether to stop battle + if (last_battle == false){ + last_battle = POKEMON_ACTIONS.stop_battle(cur_pokemon, pokemon_move_attempts[cur_pokemon]); + if (last_battle){ + env.log("Target move attempts reached: " + std::to_string(pokemon_move_attempts[cur_pokemon]) + + ". Stop program after this battle finishes."); + } + } + } + + env.update_stats(); + }else if (ret == 1){ + env.console.log("Transparent dialogue box."); + + pbf_press_button(context, BUTTON_B, 20, 100); + context.wait_for_all_requests(); + }else if(ret == 2){ + env.console.log("Normal dialogue box."); + + pbf_press_button(context, BUTTON_B, 20, 100); + context.wait_for_all_requests(); + }else if (ret == 3){ + env.console.log("Pokemon fainted.", COLOR_RED); + stats.faint_switches++; + env.update_stats(); + + switch_cur_pokemon(); + }else{ // ret is 4 + env.console.log("Battle finished."); + break; + } + } + + stats.battles++; + env.update_stats(); + + return last_battle; +} + + + +void IngoBattleGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + IngoBattleGrinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + // { + // // ImageRGB32 image("./scripts/LA_switch_pokemon_Kuro.png"); + // ImageRGB32 image("./PLA_test_data/ingoBattle/broken_dialogue_detector.png"); + // const bool stop_on_detected = true; + // NormalDialogDetector detector(env.console, env.console, stop_on_detected); + // bool detected = detector.process_frame(image, current_time()); + // std::cout << "detector " << detected << std::endl; + // return; + // } + + // pokemon index -> number of move attempts made so far + std::map pokemon_move_attempts; + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + if (run_iteration(env, context, pokemon_move_attempts)){ + break; + } + }catch (OperationFailedException&){ + stats.errors++; + throw; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.h b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.h index e841d94b91..c4c76bd9a6 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoBattleGrinder.h @@ -1,57 +1,57 @@ -/* Ingo Battle Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_IngoBattleGrinder_H -#define PokemonAutomation_PokemonLA_IngoBattleGrinder_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_IngoOpponent.h" -#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - - - -class IngoBattleGrinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - IngoBattleGrinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class IngoBattleGrinder : public SingleSwitchProgramInstance{ -public: - IngoBattleGrinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::map& pokemon_move_attempts); - - // Returns true if version 1.0. - bool start_dialog(VideoStream& stream, ProControllerContext& context); - -private: - IngoOpponentOption OPPONENT; - BattlePokemonActionTable POKEMON_ACTIONS; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Ingo Battle Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_IngoBattleGrinder_H +#define PokemonAutomation_PokemonLA_IngoBattleGrinder_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_IngoOpponent.h" +#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + + + +class IngoBattleGrinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + IngoBattleGrinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class IngoBattleGrinder : public SingleSwitchProgramInstance{ +public: + IngoBattleGrinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::map& pokemon_move_attempts); + + // Returns true if version 1.0. + bool start_dialog(VideoStream& stream, ProControllerContext& context); + +private: + IngoOpponentOption OPPONENT; + BattlePokemonActionTable POKEMON_ACTIONS; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.cpp index 8db8e76117..8047df0245 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.cpp @@ -1,448 +1,448 @@ -/* Ingo Move Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" -#include "PokemonLA_IngoMoveGrinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - - - -IngoMoveGrinder_Descriptor::IngoMoveGrinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:IngoMoveGrinder", - STRING_POKEMON + " LA", "Ingo Move Grinder", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/IngoMoveGrinder.md", - "Attend Ingo's battles to grind move related " + STRING_POKEDEX + " research tasks. More effective than Ingo Battle Grinder for " + STRING_POKEDEX + " research tasks but less effective for everything else.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class IngoMoveGrinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : battles(m_stats["Battles"]) - , turns(m_stats["Turns"]) - , move_attempts(m_stats["Move Attempts"]) - , faint_switches(m_stats["Faint Switches"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Battles"); - m_display_order.emplace_back("Turns"); - m_display_order.emplace_back("Move Attempts"); - m_display_order.emplace_back("Faint Switches", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - - std::atomic& battles; - std::atomic& turns; - std::atomic& move_attempts; - std::atomic& faint_switches; - std::atomic& errors; -}; -std::unique_ptr IngoMoveGrinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -IngoMoveGrinder::IngoMoveGrinder() - : NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(OPPONENT); - PA_ADD_OPTION(POKEMON_ACTIONS); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - -bool IngoMoveGrinder::start_dialog(VideoStream& stream, ProControllerContext& context){ - // First press A to start talking with Ingo. - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - { - ButtonDetector button0( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.408, 0.40, 0.042}, - std::chrono::milliseconds(100), - true - ); - ButtonDetector button1( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.450, 0.40, 0.042}, - std::chrono::milliseconds(100), - true - ); - ButtonDetector button2( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.492, 0.40, 0.042}, - std::chrono::milliseconds(100), - true - ); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, 150); - } - }, - { - {button0}, - {button1}, - {button2}, - } - ); - switch (ret){ - case 0: - // Version 1.1 without new options unlocked. - return false; - case 1: - // Version 1.0 - return true; - case 2: - // Version 1.1 with new options unlocked. - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect options after 10 A presses.", - stream - ); - } - } - - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - ButtonDetector button2( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.50, 0.350, 0.40, 0.400}, - std::chrono::milliseconds(100), - true - ); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 5; c++){ - pbf_press_button(context, BUTTON_A, 20, 150); - } - }, - {{button2}} - ); - switch (ret){ - case 0: - return false; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find opponent list options after 5 A presses.", - stream - ); - } -} - -bool IngoMoveGrinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - IngoMoveGrinder_Descriptor::Stats& stats = env.current_stats(); - - env.console.log("Starting battle..."); - - cur_pokemon = 0; - cur_move = 0; - - // Talk to Ingo to start conversation and select regular battles: - // The dialogues are different between version 10 (the vanilla version) and later versions. - bool version_10 = start_dialog(env.console, context); - env.log(std::string("Detected current version: ") + (version_10 ? "1.0" : "1.2")); - - IngoOpponentMenuLocation menu_location = version_10 - ? INGO_OPPONENT_MENU_LOCATIONS_V10[OPPONENT.current_value()] - : INGO_OPPONENT_MENU_LOCATIONS_V12[OPPONENT.current_value()]; - - // Choose which opponent - if (menu_location.page < 0){ - throw UserSetupError(env.console, "Opponent doesn't exist in this version of the game."); - } - - // Move to page. - for (int8_t c = 0; c < menu_location.page; c++){ - pbf_press_dpad(context, DPAD_UP, 10, 60); - pbf_press_dpad(context, DPAD_UP, 10, 60); - pbf_press_button(context, BUTTON_A, 10, 100); - } - - // Move to slot. - for (int8_t c = 0; c < menu_location.index; c++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 60); - } - - // Press the button to select the opponent - pbf_press_button(context, BUTTON_A, 10, 115); - pbf_wait(context, 1 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - env.log("Finish selecting the opponent. Battle should start now."); - - while(true){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); - // dialogue ellipse appears on a semi-transparent dialog box if you win the fight. - DialogueEllipseDetector dialogue_ellipse_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); - // normal dialogue appears if you lose the fight. - NormalDialogDetector normal_dialogue_detector(env.console, env.console, stop_on_detected); - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - int ret = wait_until( - env.console, context, std::chrono::minutes(2), - { - {battle_menu_detector}, - {dialogue_ellipse_detector}, - {normal_dialogue_detector}, - {pokemon_switch_detector}, - {arc_phone_detector}, - } - ); - if (ret < 0){ - env.console.log("Error: Failed to find battle menu after 2 minutes."); -// auto snapshot = env.console.video().snapshot(); -// dump_image(env.logger(), env.program_info(), "BattleMenuNotFound", snapshot); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find battle menu after 2 minutes.", - env.console - ); - } - - if (ret == 0){ - env.console.log("Our turn!", COLOR_BLUE); - - Move move = POKEMON_ACTIONS.get_move(cur_pokemon, cur_move); - if (move_issued[cur_pokemon][cur_move] < move.attempts){ - // Press A to select moves - pbf_press_button(context, BUTTON_A, 10, 125); - context.wait_for_all_requests(); - const bool check_move_success = true; - if (use_move(env.console, context, cur_pokemon, cur_move, move.style, check_move_success)){ - stats.turns++; - if (cur_pokemon < 4) - { - stats.move_attempts++; - move_issued[cur_pokemon][cur_move]++; - env.console.log("Successfully attempted a new move " + debug_current_info() + debug_move_attempts_info()); - } - context.wait_for_all_requests(); - }else{ - pbf_press_button(context, BUTTON_B, 20, 2 * TICKS_PER_SECOND); - env.console.log("No PP left for pokemon " + std::to_string(cur_pokemon) + " and move " + std::to_string(cur_move)); - if (get_next_move_to_switch_to() == 4){ - // Press down to select pokemons - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - go_to_next_pokemon(env, context); - - }else -{ - go_to_next_move(env, context); - } - } - }else{ - env.console.log("Done grinding for pokemon " + std::to_string(cur_pokemon) + " and move " + std::to_string(cur_move)); - if (get_next_move_to_switch_to() == 4){ - // Press down to select pokemons - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - go_to_next_pokemon(env, context); - - }else{ - go_to_next_move(env, context); - } - } - - env.update_stats(); - }else if (ret == 1){ - env.console.log("Transparent dialogue box."); - - pbf_press_button(context, BUTTON_B, 20, 100); - context.wait_for_all_requests(); - }else if(ret == 2){ - env.console.log("Normal dialogue box."); - - pbf_press_button(context, BUTTON_B, 20, 100); - context.wait_for_all_requests(); - }else if (ret == 3){ - env.console.log("Pokemon fainted.", COLOR_RED); - stats.faint_switches++; - env.update_stats(); - - go_to_next_pokemon(env, context); - }else{ // ret is 4 - env.console.log("Battle finished."); - break; - } - } - - stats.battles++; - env.update_stats(); - for (size_t i = 0; i < 4; ++i) - { - for (size_t j = 0; j < 4; ++j) - { - if (move_issued[i][j] < POKEMON_ACTIONS.get_move(i, j).attempts) - { - env.console.log("Grinding will continue." + debug_move_attempts_info()); - return false; - } - } - } - env.console.log("Grinding will stop." + debug_move_attempts_info()); - return true; -} - - - -void IngoMoveGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - IngoMoveGrinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - for (auto& row : move_issued) - { - for (auto& elem : row) - { - elem = 0; - } - } - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - if (run_iteration(env, context)){ - break; - } - }catch (OperationFailedException&){ - stats.errors++; - throw; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -void IngoMoveGrinder::go_to_next_move(SingleSwitchProgramEnvironment& env, ProControllerContext& context) -{ - env.console.log("Switch to next move " + debug_current_info() + debug_move_attempts_info()); - pbf_press_button(context, BUTTON_A, 10, 125); - size_t next_move = get_next_move_to_switch_to(); - for (size_t i = 0; i < next_move - cur_move; ++i) - { - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - } - pbf_press_button(context, BUTTON_B, 10, 125); - cur_move = next_move; - env.console.log("Switched to next move " + debug_current_info() + debug_move_attempts_info()); - context.wait_for_all_requests(); -} - -void IngoMoveGrinder::go_to_next_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context) -{ - if (cur_pokemon == 4){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Abort program. Your 4 first pokemons are done grinding moves, dead or without PP. " - "Your fifth pokemon (Arceus) died so no other choice than stopping the program.", - env.console - ); - } - env.console.log("Switch to next pokemon " + debug_current_info() + debug_move_attempts_info()); - cur_pokemon = get_next_pokemon_to_switch_to(); - cur_move = 0; - switch_pokemon(env.console, context, cur_pokemon); - env.console.log("Switched to next pokemon " + debug_current_info() + debug_move_attempts_info()); - context.wait_for_all_requests(); -} - -size_t IngoMoveGrinder::get_next_move_to_switch_to() const -{ - for (size_t i = cur_move + 1; i < 4; ++i) - { - if (move_issued[cur_pokemon][i] < POKEMON_ACTIONS.get_move(cur_pokemon, i).attempts) - { - return i; - } - } - // Means switch to next pokemon - return 4; -} - -size_t IngoMoveGrinder::get_next_pokemon_to_switch_to() const -{ - for (size_t i = cur_pokemon + 1; i < 4; ++i) - { - for (size_t j = 0; j < 4; ++j) - { - if (move_issued[i][j] < POKEMON_ACTIONS.get_move(i, j).attempts) - { - return i; - } - } - } - // Means switch to arceus and spam moves to end the battle - return 4; -} - -std::string IngoMoveGrinder::debug_current_info() const -{ - return "(cur_pokemon : " + std::to_string(cur_pokemon) + ", cur_move : " + std::to_string(cur_move) + ")"; -} - -std::string IngoMoveGrinder::debug_move_attempts_info() const -{ - std::string debug = "\n"; - for (size_t i = 0; i < 4; ++i){ - for (size_t j = 0; j < 4; ++j){ - Move move = POKEMON_ACTIONS.get_move(i, j); - if (move.attempts != 0) - { - debug += "(pokemon : " + std::to_string(i) + ", move : " + std::to_string(j) + " did " + std::to_string(move_issued[i][j]) + " out of " + std::to_string(move.attempts) + ")\n"; - } - } - } - return debug; -} - - - - -} -} -} +/* Ingo Move Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueEllipseDetector.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" +#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" +#include "PokemonLA_IngoMoveGrinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + + + +IngoMoveGrinder_Descriptor::IngoMoveGrinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:IngoMoveGrinder", + STRING_POKEMON + " LA", "Ingo Move Grinder", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/IngoMoveGrinder.md", + "Attend Ingo's battles to grind move related " + STRING_POKEDEX + " research tasks. More effective than Ingo Battle Grinder for " + STRING_POKEDEX + " research tasks but less effective for everything else.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class IngoMoveGrinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : battles(m_stats["Battles"]) + , turns(m_stats["Turns"]) + , move_attempts(m_stats["Move Attempts"]) + , faint_switches(m_stats["Faint Switches"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Battles"); + m_display_order.emplace_back("Turns"); + m_display_order.emplace_back("Move Attempts"); + m_display_order.emplace_back("Faint Switches", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + + std::atomic& battles; + std::atomic& turns; + std::atomic& move_attempts; + std::atomic& faint_switches; + std::atomic& errors; +}; +std::unique_ptr IngoMoveGrinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +IngoMoveGrinder::IngoMoveGrinder() + : NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(OPPONENT); + PA_ADD_OPTION(POKEMON_ACTIONS); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + +bool IngoMoveGrinder::start_dialog(VideoStream& stream, ProControllerContext& context){ + // First press A to start talking with Ingo. + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + { + ButtonDetector button0( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.408, 0.40, 0.042}, + std::chrono::milliseconds(100), + true + ); + ButtonDetector button1( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.450, 0.40, 0.042}, + std::chrono::milliseconds(100), + true + ); + ButtonDetector button2( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.492, 0.40, 0.042}, + std::chrono::milliseconds(100), + true + ); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, 150); + } + }, + { + {button0}, + {button1}, + {button2}, + } + ); + switch (ret){ + case 0: + // Version 1.1 without new options unlocked. + return false; + case 1: + // Version 1.0 + return true; + case 2: + // Version 1.1 with new options unlocked. + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect options after 10 A presses.", + stream + ); + } + } + + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + ButtonDetector button2( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.50, 0.350, 0.40, 0.400}, + std::chrono::milliseconds(100), + true + ); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 5; c++){ + pbf_press_button(context, BUTTON_A, 20, 150); + } + }, + {{button2}} + ); + switch (ret){ + case 0: + return false; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find opponent list options after 5 A presses.", + stream + ); + } +} + +bool IngoMoveGrinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + IngoMoveGrinder_Descriptor::Stats& stats = env.current_stats(); + + env.console.log("Starting battle..."); + + cur_pokemon = 0; + cur_move = 0; + + // Talk to Ingo to start conversation and select regular battles: + // The dialogues are different between version 10 (the vanilla version) and later versions. + bool version_10 = start_dialog(env.console, context); + env.log(std::string("Detected current version: ") + (version_10 ? "1.0" : "1.2")); + + IngoOpponentMenuLocation menu_location = version_10 + ? INGO_OPPONENT_MENU_LOCATIONS_V10[OPPONENT.current_value()] + : INGO_OPPONENT_MENU_LOCATIONS_V12[OPPONENT.current_value()]; + + // Choose which opponent + if (menu_location.page < 0){ + throw UserSetupError(env.console, "Opponent doesn't exist in this version of the game."); + } + + // Move to page. + for (int8_t c = 0; c < menu_location.page; c++){ + pbf_press_dpad(context, DPAD_UP, 10, 60); + pbf_press_dpad(context, DPAD_UP, 10, 60); + pbf_press_button(context, BUTTON_A, 10, 100); + } + + // Move to slot. + for (int8_t c = 0; c < menu_location.index; c++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 60); + } + + // Press the button to select the opponent + pbf_press_button(context, BUTTON_A, 10, 115); + pbf_wait(context, 1 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + env.log("Finish selecting the opponent. Battle should start now."); + + while(true){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); + // dialogue ellipse appears on a semi-transparent dialog box if you win the fight. + DialogueEllipseDetector dialogue_ellipse_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); + // normal dialogue appears if you lose the fight. + NormalDialogDetector normal_dialogue_detector(env.console, env.console, stop_on_detected); + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + int ret = wait_until( + env.console, context, std::chrono::minutes(2), + { + {battle_menu_detector}, + {dialogue_ellipse_detector}, + {normal_dialogue_detector}, + {pokemon_switch_detector}, + {arc_phone_detector}, + } + ); + if (ret < 0){ + env.console.log("Error: Failed to find battle menu after 2 minutes."); +// auto snapshot = env.console.video().snapshot(); +// dump_image(env.logger(), env.program_info(), "BattleMenuNotFound", snapshot); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find battle menu after 2 minutes.", + env.console + ); + } + + if (ret == 0){ + env.console.log("Our turn!", COLOR_BLUE); + + Move move = POKEMON_ACTIONS.get_move(cur_pokemon, cur_move); + if (move_issued[cur_pokemon][cur_move] < move.attempts){ + // Press A to select moves + pbf_press_button(context, BUTTON_A, 10, 125); + context.wait_for_all_requests(); + const bool check_move_success = true; + if (use_move(env.console, context, cur_pokemon, cur_move, move.style, check_move_success)){ + stats.turns++; + if (cur_pokemon < 4) + { + stats.move_attempts++; + move_issued[cur_pokemon][cur_move]++; + env.console.log("Successfully attempted a new move " + debug_current_info() + debug_move_attempts_info()); + } + context.wait_for_all_requests(); + }else{ + pbf_press_button(context, BUTTON_B, 20, 2 * TICKS_PER_SECOND); + env.console.log("No PP left for pokemon " + std::to_string(cur_pokemon) + " and move " + std::to_string(cur_move)); + if (get_next_move_to_switch_to() == 4){ + // Press down to select pokemons + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + go_to_next_pokemon(env, context); + + }else +{ + go_to_next_move(env, context); + } + } + }else{ + env.console.log("Done grinding for pokemon " + std::to_string(cur_pokemon) + " and move " + std::to_string(cur_move)); + if (get_next_move_to_switch_to() == 4){ + // Press down to select pokemons + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + go_to_next_pokemon(env, context); + + }else{ + go_to_next_move(env, context); + } + } + + env.update_stats(); + }else if (ret == 1){ + env.console.log("Transparent dialogue box."); + + pbf_press_button(context, BUTTON_B, 20, 100); + context.wait_for_all_requests(); + }else if(ret == 2){ + env.console.log("Normal dialogue box."); + + pbf_press_button(context, BUTTON_B, 20, 100); + context.wait_for_all_requests(); + }else if (ret == 3){ + env.console.log("Pokemon fainted.", COLOR_RED); + stats.faint_switches++; + env.update_stats(); + + go_to_next_pokemon(env, context); + }else{ // ret is 4 + env.console.log("Battle finished."); + break; + } + } + + stats.battles++; + env.update_stats(); + for (size_t i = 0; i < 4; ++i) + { + for (size_t j = 0; j < 4; ++j) + { + if (move_issued[i][j] < POKEMON_ACTIONS.get_move(i, j).attempts) + { + env.console.log("Grinding will continue." + debug_move_attempts_info()); + return false; + } + } + } + env.console.log("Grinding will stop." + debug_move_attempts_info()); + return true; +} + + + +void IngoMoveGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + IngoMoveGrinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + for (auto& row : move_issued) + { + for (auto& elem : row) + { + elem = 0; + } + } + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + if (run_iteration(env, context)){ + break; + } + }catch (OperationFailedException&){ + stats.errors++; + throw; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +void IngoMoveGrinder::go_to_next_move(SingleSwitchProgramEnvironment& env, ProControllerContext& context) +{ + env.console.log("Switch to next move " + debug_current_info() + debug_move_attempts_info()); + pbf_press_button(context, BUTTON_A, 10, 125); + size_t next_move = get_next_move_to_switch_to(); + for (size_t i = 0; i < next_move - cur_move; ++i) + { + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + } + pbf_press_button(context, BUTTON_B, 10, 125); + cur_move = next_move; + env.console.log("Switched to next move " + debug_current_info() + debug_move_attempts_info()); + context.wait_for_all_requests(); +} + +void IngoMoveGrinder::go_to_next_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context) +{ + if (cur_pokemon == 4){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Abort program. Your 4 first pokemons are done grinding moves, dead or without PP. " + "Your fifth pokemon (Arceus) died so no other choice than stopping the program.", + env.console + ); + } + env.console.log("Switch to next pokemon " + debug_current_info() + debug_move_attempts_info()); + cur_pokemon = get_next_pokemon_to_switch_to(); + cur_move = 0; + switch_pokemon(env.console, context, cur_pokemon); + env.console.log("Switched to next pokemon " + debug_current_info() + debug_move_attempts_info()); + context.wait_for_all_requests(); +} + +size_t IngoMoveGrinder::get_next_move_to_switch_to() const +{ + for (size_t i = cur_move + 1; i < 4; ++i) + { + if (move_issued[cur_pokemon][i] < POKEMON_ACTIONS.get_move(cur_pokemon, i).attempts) + { + return i; + } + } + // Means switch to next pokemon + return 4; +} + +size_t IngoMoveGrinder::get_next_pokemon_to_switch_to() const +{ + for (size_t i = cur_pokemon + 1; i < 4; ++i) + { + for (size_t j = 0; j < 4; ++j) + { + if (move_issued[i][j] < POKEMON_ACTIONS.get_move(i, j).attempts) + { + return i; + } + } + } + // Means switch to arceus and spam moves to end the battle + return 4; +} + +std::string IngoMoveGrinder::debug_current_info() const +{ + return "(cur_pokemon : " + std::to_string(cur_pokemon) + ", cur_move : " + std::to_string(cur_move) + ")"; +} + +std::string IngoMoveGrinder::debug_move_attempts_info() const +{ + std::string debug = "\n"; + for (size_t i = 0; i < 4; ++i){ + for (size_t j = 0; j < 4; ++j){ + Move move = POKEMON_ACTIONS.get_move(i, j); + if (move.attempts != 0) + { + debug += "(pokemon : " + std::to_string(i) + ", move : " + std::to_string(j) + " did " + std::to_string(move_issued[i][j]) + " out of " + std::to_string(move.attempts) + ")\n"; + } + } + } + return debug; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.h b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.h index d7daa8aaa7..e6fa35d5c0 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_IngoMoveGrinder.h @@ -1,67 +1,67 @@ -/* Ingo Move Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_IngoMoveGrinder_H -#define PokemonAutomation_PokemonLA_IngoMoveGrinder_H - -#include -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_IngoOpponent.h" -#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class IngoMoveGrinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - IngoMoveGrinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class IngoMoveGrinder : public SingleSwitchProgramInstance{ -public: - IngoMoveGrinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // Returns true if version 1.0. - bool start_dialog(VideoStream& stream, ProControllerContext& context); - -private: - void go_to_next_move(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void go_to_next_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - size_t get_next_move_to_switch_to() const; - size_t get_next_pokemon_to_switch_to() const; - std::string debug_current_info() const; - std::string debug_move_attempts_info() const; - - IngoOpponentOption OPPONENT; - MoveGrinderActionTable POKEMON_ACTIONS; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; - - size_t cur_pokemon = 0; - size_t cur_move = 0; - std::array, 5> move_issued{}; -}; - - - - - -} -} -} -#endif +/* Ingo Move Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_IngoMoveGrinder_H +#define PokemonAutomation_PokemonLA_IngoMoveGrinder_H + +#include +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_IngoOpponent.h" +#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class IngoMoveGrinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + IngoMoveGrinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class IngoMoveGrinder : public SingleSwitchProgramInstance{ +public: + IngoMoveGrinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // Returns true if version 1.0. + bool start_dialog(VideoStream& stream, ProControllerContext& context); + +private: + void go_to_next_move(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void go_to_next_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + size_t get_next_move_to_switch_to() const; + size_t get_next_pokemon_to_switch_to() const; + std::string debug_current_info() const; + std::string debug_move_attempts_info() const; + + IngoOpponentOption OPPONENT; + MoveGrinderActionTable POKEMON_ACTIONS; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; + + size_t cur_pokemon = 0; + size_t cur_move = 0; + std::array, 5> move_issued{}; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.cpp index 3b0978eb01..b1d22a1286 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.cpp @@ -1,331 +1,331 @@ -/* Leap Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Resources/PokemonLA_NameDatabase.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" -#include "PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -LeapGrinder_Descriptor::LeapGrinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:Leap Grinder", - STRING_POKEMON + " LA", "Leap Grinder", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/LeapGrinder.md", - "Shake trees and ores to grind tasks", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class LeapGrinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , leaps(m_stats["Leaps"]) - , found(m_stats["Found"]) - , enroute_shinies(m_stats["Enroute Shinies"]) - , leap_alphas(m_stats["Leap Alphas"]) - , leap_shinies(m_stats["Leap Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Leaps"); - m_display_order.emplace_back("Found"); - m_display_order.emplace_back("Enroute Shinies"); - m_display_order.emplace_back("Leap Alphas"); - m_display_order.emplace_back("Leap Shinies"); - m_aliases["Shinies"] = "Enroute Shinies"; - m_aliases["Alphas"] = "Leap Alphas"; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& leaps; - std::atomic& found; - std::atomic& enroute_shinies; - std::atomic& leap_alphas; - std::atomic& leap_shinies; -}; -std::unique_ptr LeapGrinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -LeapGrinder::LeapGrinder() - : LANGUAGE( - "Game Language", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , POKEMON_DATABASE(make_name_database({ - "aipom", - "burmy", - "cherrim", - "cherubi", - "combee", - "heracross", - "pachirisu", - "vespiquen", - "wormadam", - "geodude", - "graveler", - "bonsly", - "bronzor", - "nosepass", - "bergmite", - })) - , POKEMON( - "Pokemon Species", - POKEMON_DATABASE, - LockMode::UNLOCK_WHILE_RUNNING, - "cherubi" - ) - , LEAPS( - "Leaps
How many leaps before stopping the program
", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 100 - ) - , SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while traveling in the overworld.", - "0 ms" - ) - , FOUND_SHINY_OR_ALPHA( - "Found Shiny or Alpha", - true, true, - ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , MATCH_DETECTED_OPTIONS( - "Match Action", - "What to do when the leaping " + Pokemon::STRING_POKEMON + " matches the \"Stop On\" parameter.", - "Found Shiny or Alpha" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &FOUND_SHINY_OR_ALPHA, - &MATCH_DETECTED_OPTIONS.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(POKEMON); - PA_ADD_OPTION(LEAPS); - PA_ADD_OPTION(STOP_ON); - PA_ADD_OPTION(EXIT_METHOD); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(MATCH_DETECTED_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -bool LeapGrinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - LeapGrinder_Descriptor::Stats& stats = env.current_stats(); - stats.attempts++; - - env.console.log("Starting route and shiny detection..."); - - for (size_t c = 0; true; c++){ - context.wait_for_all_requests(); - if (is_pokemon_selection(env.console, env.console.video().snapshot())){ - break; - } - if (c >= 5){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to switch to Pokemon selection after 5 attempts.", - env.console - ); - } - env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_X, 20, 230); - } - - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.enroute_shinies++; - shiny_coefficient = error_coefficient; - return on_shiny_callback(env, env.console, SHINY_DETECTED_ENROUTE, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - route(env, env.console, context, (LeapPokemon)POKEMON.index()); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, SHINY_DETECTED_ENROUTE, shiny_coefficient); - } - - env.console.log("End of route and shiny detection..."); - - bool battle_found = check_tree_or_ore_for_battle(env.console, context); - - context.wait_for_all_requests(); - - if (battle_found){ - env.console.log("Pokemon leaped!"); - stats.leaps++; - - PokemonDetails pokemon = get_pokemon_details(env.console, context, LANGUAGE); - pbf_press_button(context, BUTTON_B, 20, 225); - context.wait_for_all_requests(); - - env.console.log("Looking for: " + POKEMON.slug()); - env.console.log("Found: " + set_to_str(pokemon.name_candidates)); - env.console.log("Gender: " + std::string(get_gender_str(pokemon.gender))); - env.console.log("Alpha: " + std::string(pokemon.is_alpha ? "Yes" : "No")); - env.console.log("Shiny: " + std::string(pokemon.is_shiny ? "Yes" : "No")); - - if (pokemon.name_candidates.find(POKEMON.slug()) != pokemon.name_candidates.end()){ - env.console.log("Expected Pokemon leaped!"); - stats.found++; - }else{ - env.console.log("Not the expected pokemon."); - } - - // Match validation - - if (pokemon.is_alpha && pokemon.is_shiny){ - env.console.log("Found Shiny Alpha!"); - stats.leap_shinies++; - stats.leap_alphas++; - }else if (pokemon.is_alpha){ - env.console.log("Found Alpha!"); - stats.leap_alphas++; - }else if (pokemon.is_shiny){ - env.console.log("Found Shiny!"); - stats.leap_shinies++; - }else{ - env.console.log("Normie in the tree -_-"); - } - env.update_stats(); - - bool is_match = false; - switch (STOP_ON){ - case StopOn::Shiny: - is_match = pokemon.is_shiny; - break; - case StopOn::Alpha: - is_match = pokemon.is_alpha; - break; - case StopOn::ShinyOrAlpha: - is_match = pokemon.is_alpha || pokemon.is_shiny; - break; - case StopOn::ShinyAndAlpha: - is_match = pokemon.is_alpha && pokemon.is_shiny; - break; - } - - bool notification_sent = false; - do{ - std::string str; - if (pokemon.is_shiny){ - if (pokemon.is_alpha){ - str = "Found Shiny Alpha!"; - }else{ - str = "Found Shiny!"; - } - }else{ - if (pokemon.is_alpha){ - str = "Found Alpha!"; - }else{ - break; - } - } - notification_sent |= send_program_notification( - env, FOUND_SHINY_OR_ALPHA, - Pokemon::COLOR_STAR_SHINY, - std::move(str), - {}, "", - env.console.video().snapshot(), true - ); - }while (false); - - if (is_match){ - on_battle_match_found(env, env.console, context, MATCH_DETECTED_OPTIONS, !notification_sent); - } - - exit_battle(env.console, context, EXIT_METHOD); - } - - env.console.log("Remaining Leaps:" + std::to_string(LEAPS - stats.leaps)); - - return_to_jubilife(env, env.console, context, (LeapPokemon)POKEMON.index()); - - if (stats.leaps == LEAPS){ - return true; - } - - return false; -} - -void LeapGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - LeapGrinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - if(run_iteration(env, context)){ - break; - } - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - // Switch from items to pokemons - pbf_press_button(context, BUTTON_X, 20, 30); - } - } - - env.update_stats(); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Leap Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Resources/PokemonLA_NameDatabase.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" +#include "PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +LeapGrinder_Descriptor::LeapGrinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:Leap Grinder", + STRING_POKEMON + " LA", "Leap Grinder", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/LeapGrinder.md", + "Shake trees and ores to grind tasks", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class LeapGrinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , leaps(m_stats["Leaps"]) + , found(m_stats["Found"]) + , enroute_shinies(m_stats["Enroute Shinies"]) + , leap_alphas(m_stats["Leap Alphas"]) + , leap_shinies(m_stats["Leap Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Leaps"); + m_display_order.emplace_back("Found"); + m_display_order.emplace_back("Enroute Shinies"); + m_display_order.emplace_back("Leap Alphas"); + m_display_order.emplace_back("Leap Shinies"); + m_aliases["Shinies"] = "Enroute Shinies"; + m_aliases["Alphas"] = "Leap Alphas"; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& leaps; + std::atomic& found; + std::atomic& enroute_shinies; + std::atomic& leap_alphas; + std::atomic& leap_shinies; +}; +std::unique_ptr LeapGrinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +LeapGrinder::LeapGrinder() + : LANGUAGE( + "Game Language", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , POKEMON_DATABASE(make_name_database({ + "aipom", + "burmy", + "cherrim", + "cherubi", + "combee", + "heracross", + "pachirisu", + "vespiquen", + "wormadam", + "geodude", + "graveler", + "bonsly", + "bronzor", + "nosepass", + "bergmite", + })) + , POKEMON( + "Pokemon Species", + POKEMON_DATABASE, + LockMode::UNLOCK_WHILE_RUNNING, + "cherubi" + ) + , LEAPS( + "Leaps
How many leaps before stopping the program
", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 100 + ) + , SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while traveling in the overworld.", + "0 ms" + ) + , FOUND_SHINY_OR_ALPHA( + "Found Shiny or Alpha", + true, true, + ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , MATCH_DETECTED_OPTIONS( + "Match Action", + "What to do when the leaping " + Pokemon::STRING_POKEMON + " matches the \"Stop On\" parameter.", + "Found Shiny or Alpha" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &FOUND_SHINY_OR_ALPHA, + &MATCH_DETECTED_OPTIONS.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(POKEMON); + PA_ADD_OPTION(LEAPS); + PA_ADD_OPTION(STOP_ON); + PA_ADD_OPTION(EXIT_METHOD); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(MATCH_DETECTED_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +bool LeapGrinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + LeapGrinder_Descriptor::Stats& stats = env.current_stats(); + stats.attempts++; + + env.console.log("Starting route and shiny detection..."); + + for (size_t c = 0; true; c++){ + context.wait_for_all_requests(); + if (is_pokemon_selection(env.console, env.console.video().snapshot())){ + break; + } + if (c >= 5){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to switch to Pokemon selection after 5 attempts.", + env.console + ); + } + env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_X, 20, 230); + } + + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.enroute_shinies++; + shiny_coefficient = error_coefficient; + return on_shiny_callback(env, env.console, SHINY_DETECTED_ENROUTE, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + route(env, env.console, context, (LeapPokemon)POKEMON.index()); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, SHINY_DETECTED_ENROUTE, shiny_coefficient); + } + + env.console.log("End of route and shiny detection..."); + + bool battle_found = check_tree_or_ore_for_battle(env.console, context); + + context.wait_for_all_requests(); + + if (battle_found){ + env.console.log("Pokemon leaped!"); + stats.leaps++; + + PokemonDetails pokemon = get_pokemon_details(env.console, context, LANGUAGE); + pbf_press_button(context, BUTTON_B, 20, 225); + context.wait_for_all_requests(); + + env.console.log("Looking for: " + POKEMON.slug()); + env.console.log("Found: " + set_to_str(pokemon.name_candidates)); + env.console.log("Gender: " + std::string(get_gender_str(pokemon.gender))); + env.console.log("Alpha: " + std::string(pokemon.is_alpha ? "Yes" : "No")); + env.console.log("Shiny: " + std::string(pokemon.is_shiny ? "Yes" : "No")); + + if (pokemon.name_candidates.find(POKEMON.slug()) != pokemon.name_candidates.end()){ + env.console.log("Expected Pokemon leaped!"); + stats.found++; + }else{ + env.console.log("Not the expected pokemon."); + } + + // Match validation + + if (pokemon.is_alpha && pokemon.is_shiny){ + env.console.log("Found Shiny Alpha!"); + stats.leap_shinies++; + stats.leap_alphas++; + }else if (pokemon.is_alpha){ + env.console.log("Found Alpha!"); + stats.leap_alphas++; + }else if (pokemon.is_shiny){ + env.console.log("Found Shiny!"); + stats.leap_shinies++; + }else{ + env.console.log("Normie in the tree -_-"); + } + env.update_stats(); + + bool is_match = false; + switch (STOP_ON){ + case StopOn::Shiny: + is_match = pokemon.is_shiny; + break; + case StopOn::Alpha: + is_match = pokemon.is_alpha; + break; + case StopOn::ShinyOrAlpha: + is_match = pokemon.is_alpha || pokemon.is_shiny; + break; + case StopOn::ShinyAndAlpha: + is_match = pokemon.is_alpha && pokemon.is_shiny; + break; + } + + bool notification_sent = false; + do{ + std::string str; + if (pokemon.is_shiny){ + if (pokemon.is_alpha){ + str = "Found Shiny Alpha!"; + }else{ + str = "Found Shiny!"; + } + }else{ + if (pokemon.is_alpha){ + str = "Found Alpha!"; + }else{ + break; + } + } + notification_sent |= send_program_notification( + env, FOUND_SHINY_OR_ALPHA, + Pokemon::COLOR_STAR_SHINY, + std::move(str), + {}, "", + env.console.video().snapshot(), true + ); + }while (false); + + if (is_match){ + on_battle_match_found(env, env.console, context, MATCH_DETECTED_OPTIONS, !notification_sent); + } + + exit_battle(env.console, context, EXIT_METHOD); + } + + env.console.log("Remaining Leaps:" + std::to_string(LEAPS - stats.leaps)); + + return_to_jubilife(env, env.console, context, (LeapPokemon)POKEMON.index()); + + if (stats.leaps == LEAPS){ + return true; + } + + return false; +} + +void LeapGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + LeapGrinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + if(run_iteration(env, context)){ + break; + } + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + // Switch from items to pokemons + pbf_press_button(context, BUTTON_X, 20, 30); + } + } + + env.update_stats(); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h index 55d6b56689..dd2a8db70b 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_LeapGrinder.h @@ -1,66 +1,66 @@ -/* Tree Leap Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_LeapGrinder_H -#define PokemonAutomation_PokemonLA_LeapGrinder_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_MiscOptions.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -class LeapGrinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LeapGrinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class LeapGrinder : public SingleSwitchProgramInstance{ -public: - LeapGrinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool quick_check(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - class RunRoute; - - OCR::LanguageOCROption LANGUAGE; - - StringSelectDatabase POKEMON_DATABASE; - StringSelectOption POKEMON; - - SimpleIntegerOption LEAPS; - StopOnOption STOP_ON; - ExitBattleMethodOption EXIT_METHOD; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - EventNotificationOption FOUND_SHINY_OR_ALPHA; - BattleMatchActionOption MATCH_DETECTED_OPTIONS; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Tree Leap Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_LeapGrinder_H +#define PokemonAutomation_PokemonLA_LeapGrinder_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_MiscOptions.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +class LeapGrinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LeapGrinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class LeapGrinder : public SingleSwitchProgramInstance{ +public: + LeapGrinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool quick_check(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + class RunRoute; + + OCR::LanguageOCROption LANGUAGE; + + StringSelectDatabase POKEMON_DATABASE; + StringSelectOption POKEMON; + + SimpleIntegerOption LEAPS; + StopOnOption STOP_ON; + ExitBattleMethodOption EXIT_METHOD; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + EventNotificationOption FOUND_SHINY_OR_ALPHA; + BattleMatchActionOption MATCH_DETECTED_OPTIONS; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.cpp index 4634c832f9..90952dee12 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.cpp @@ -1,273 +1,273 @@ -/* Ingo Battle Grinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" -#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" -#include "PokemonLA_MagikarpMoveGrinder.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -MagikarpMoveGrinder_Descriptor::MagikarpMoveGrinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:MagikarpMoveGrinder", - STRING_POKEMON + " LA", "Magikarp Move Grinder", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/MagikarpMoveGrinder.md", - "grind status moves with any style against a Magikarp to finish " + STRING_POKEDEX + " research tasks.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class MagikarpMoveGrinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : magikarp(m_stats["Magikarp"]) - , move_attempts(m_stats["Move Attempts"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Magikarp"); - m_display_order.emplace_back("Move Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - - std::atomic& magikarp; - std::atomic& move_attempts; - std::atomic& errors; -}; -std::unique_ptr MagikarpMoveGrinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -MagikarpMoveGrinder::MagikarpMoveGrinder() - : SPECIAL_CASE_MIMIC( - "Special Case, Mimic:
Grind Mimic move usages by switching between first two " + STRING_POKEMON + ". Set the first move as Mimic on the first two " + STRING_POKEMON + ".
" - "After switching, the retreated " + STRING_POKEMON + " will forget the move learned by Mimic, allowing efficient Mimic grinding.
" - "Choosing this will ignore the content in " + STRING_POKEMON + " Action Table.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(POKEMON_ACTIONS); - PA_ADD_OPTION(SPECIAL_CASE_MIMIC); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void MagikarpMoveGrinder::grind_mimic(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MagikarpMoveGrinder_Descriptor::Stats& stats = env.current_stats(); - env.log("Special case: grinding Mimic..."); - - // Which pokemon in the party is not fainted - size_t cur_pokemon = 0; - // Whether to switch the pokemon next turn - bool to_switch_pokemon = false; - - while(true){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); - BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - int ret = wait_until( - env.console, context, std::chrono::minutes(2), - { - {battle_menu_detector}, - {pokemon_switch_detector}, - {arc_phone_detector}, - } - ); - if (ret < 0){ - env.console.log("Error: Failed to find battle menu after 2 minutes."); -// auto snapshot = env.console.video().snapshot(); -// dump_image(env.logger(), env.program_info(), "BattleMenuNotFound", snapshot); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find battle menu after 2 minutes.", - env.console - ); - } - - if (ret == 0){ - env.console.log("Our turn!", COLOR_BLUE); - - if (to_switch_pokemon){ - cur_pokemon = (cur_pokemon+1) % 2; - env.console.log("Switch Pokemon after Mimic used.", COLOR_RED);; - - // Go to the switching pokemon screen: - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - - cur_pokemon = switch_pokemon(env.console, context, cur_pokemon); - - to_switch_pokemon = false; - }else{ - // Press A to select moves - pbf_press_button(context, BUTTON_A, 10, 125); - context.wait_for_all_requests(); - - const MoveStyle style = MoveStyle::NoStyle; - const bool check_move_success = true; - if (use_move(env.console, context, cur_pokemon, 0, style, check_move_success) == false){ - // Finish grinding. - env.log("No PP. Finish grinding."); - return; - }else{ - stats.move_attempts++; - env.update_stats(); - - to_switch_pokemon = true; - } - } - }else if (ret == 1){ - env.log("Your pokemon fainted. Can only happen if Magikarp Struggled and defeated your pokemon."); - return; - }else{ // ret is 2 - env.log("Battle finished."); - return; - } - } -} - -void MagikarpMoveGrinder::battle_magikarp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MagikarpMoveGrinder_Descriptor::Stats& stats = env.current_stats(); - - // Which pokemon in the party is not fainted - size_t cur_pokemon = 0; - - while(true){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); - BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - int ret = wait_until( - env.console, context, std::chrono::minutes(2), - { - {battle_menu_detector}, - {pokemon_switch_detector}, - {arc_phone_detector}, - } - ); - if (ret < 0){ - env.console.log("Error: Failed to find battle menu after 2 minutes."); -// auto snapshot = env.console.video().snapshot(); -// dump_image(env.logger(), env.program_info(), "BattleMenuNotFound", snapshot); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find battle menu after 2 minutes.", - env.console - ); - } - - if (ret == 0){ - env.console.log("Our turn!", COLOR_BLUE); - - // Press A to select moves - pbf_press_button(context, BUTTON_A, 10, 125); - context.wait_for_all_requests(); - - const MoveStyle style = POKEMON_ACTIONS.get_style(cur_pokemon); - - const bool check_move_success = true; - if (use_move(env.console, context, cur_pokemon, 0, style, check_move_success) == false){ - // We are still on the move selection screen. No PP. - cur_pokemon++; - if (cur_pokemon >= POKEMON_ACTIONS.num_pokemon()){ - env.console.log("All pokemon grinded. Stop program."); - break; - } - env.console.log("No PP. Switch Pokemon.", COLOR_RED); - - // Press B to leave move selection menu - pbf_press_button(context, BUTTON_B, 10, 125); - - // Go to the switching pokemon screen: - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - - cur_pokemon = switch_pokemon(env.console, context, cur_pokemon, POKEMON_ACTIONS.num_pokemon()); - }else{ - stats.move_attempts++; - env.update_stats(); - } - }else if (ret == 1){ - env.console.log("Pokemon fainted."); - cur_pokemon++; - if (cur_pokemon >= POKEMON_ACTIONS.num_pokemon()){ - env.console.log("All pokemon grinded. Stop program."); - break; - } - cur_pokemon = switch_pokemon(env.console, context, cur_pokemon, POKEMON_ACTIONS.num_pokemon()); - }else{ // ret is 2 - env.console.log("Battle finished."); - break; - } - } -} - - - -void MagikarpMoveGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MagikarpMoveGrinder_Descriptor::Stats& stats = env.current_stats(); - - if (POKEMON_ACTIONS.num_pokemon() == 0){ - throw UserSetupError(env.console, "No Pokemon specified to grind."); - } - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - env.console.log("Grinding on Magikarp..."); - - try{ - if (SPECIAL_CASE_MIMIC){ - grind_mimic(env, context); - }else{ - battle_magikarp(env, context); - } - - stats.magikarp++; - env.update_stats(); - }catch (OperationFailedException&){ - stats.errors++; - throw; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Ingo Battle Grinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" +#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" +#include "PokemonLA_MagikarpMoveGrinder.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +MagikarpMoveGrinder_Descriptor::MagikarpMoveGrinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:MagikarpMoveGrinder", + STRING_POKEMON + " LA", "Magikarp Move Grinder", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/MagikarpMoveGrinder.md", + "grind status moves with any style against a Magikarp to finish " + STRING_POKEDEX + " research tasks.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class MagikarpMoveGrinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : magikarp(m_stats["Magikarp"]) + , move_attempts(m_stats["Move Attempts"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Magikarp"); + m_display_order.emplace_back("Move Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + + std::atomic& magikarp; + std::atomic& move_attempts; + std::atomic& errors; +}; +std::unique_ptr MagikarpMoveGrinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +MagikarpMoveGrinder::MagikarpMoveGrinder() + : SPECIAL_CASE_MIMIC( + "Special Case, Mimic:
Grind Mimic move usages by switching between first two " + STRING_POKEMON + ". Set the first move as Mimic on the first two " + STRING_POKEMON + ".
" + "After switching, the retreated " + STRING_POKEMON + " will forget the move learned by Mimic, allowing efficient Mimic grinding.
" + "Choosing this will ignore the content in " + STRING_POKEMON + " Action Table.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(POKEMON_ACTIONS); + PA_ADD_OPTION(SPECIAL_CASE_MIMIC); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void MagikarpMoveGrinder::grind_mimic(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MagikarpMoveGrinder_Descriptor::Stats& stats = env.current_stats(); + env.log("Special case: grinding Mimic..."); + + // Which pokemon in the party is not fainted + size_t cur_pokemon = 0; + // Whether to switch the pokemon next turn + bool to_switch_pokemon = false; + + while(true){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); + BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + int ret = wait_until( + env.console, context, std::chrono::minutes(2), + { + {battle_menu_detector}, + {pokemon_switch_detector}, + {arc_phone_detector}, + } + ); + if (ret < 0){ + env.console.log("Error: Failed to find battle menu after 2 minutes."); +// auto snapshot = env.console.video().snapshot(); +// dump_image(env.logger(), env.program_info(), "BattleMenuNotFound", snapshot); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find battle menu after 2 minutes.", + env.console + ); + } + + if (ret == 0){ + env.console.log("Our turn!", COLOR_BLUE); + + if (to_switch_pokemon){ + cur_pokemon = (cur_pokemon+1) % 2; + env.console.log("Switch Pokemon after Mimic used.", COLOR_RED);; + + // Go to the switching pokemon screen: + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + + cur_pokemon = switch_pokemon(env.console, context, cur_pokemon); + + to_switch_pokemon = false; + }else{ + // Press A to select moves + pbf_press_button(context, BUTTON_A, 10, 125); + context.wait_for_all_requests(); + + const MoveStyle style = MoveStyle::NoStyle; + const bool check_move_success = true; + if (use_move(env.console, context, cur_pokemon, 0, style, check_move_success) == false){ + // Finish grinding. + env.log("No PP. Finish grinding."); + return; + }else{ + stats.move_attempts++; + env.update_stats(); + + to_switch_pokemon = true; + } + } + }else if (ret == 1){ + env.log("Your pokemon fainted. Can only happen if Magikarp Struggled and defeated your pokemon."); + return; + }else{ // ret is 2 + env.log("Battle finished."); + return; + } + } +} + +void MagikarpMoveGrinder::battle_magikarp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MagikarpMoveGrinder_Descriptor::Stats& stats = env.current_stats(); + + // Which pokemon in the party is not fainted + size_t cur_pokemon = 0; + + while(true){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); + BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + int ret = wait_until( + env.console, context, std::chrono::minutes(2), + { + {battle_menu_detector}, + {pokemon_switch_detector}, + {arc_phone_detector}, + } + ); + if (ret < 0){ + env.console.log("Error: Failed to find battle menu after 2 minutes."); +// auto snapshot = env.console.video().snapshot(); +// dump_image(env.logger(), env.program_info(), "BattleMenuNotFound", snapshot); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find battle menu after 2 minutes.", + env.console + ); + } + + if (ret == 0){ + env.console.log("Our turn!", COLOR_BLUE); + + // Press A to select moves + pbf_press_button(context, BUTTON_A, 10, 125); + context.wait_for_all_requests(); + + const MoveStyle style = POKEMON_ACTIONS.get_style(cur_pokemon); + + const bool check_move_success = true; + if (use_move(env.console, context, cur_pokemon, 0, style, check_move_success) == false){ + // We are still on the move selection screen. No PP. + cur_pokemon++; + if (cur_pokemon >= POKEMON_ACTIONS.num_pokemon()){ + env.console.log("All pokemon grinded. Stop program."); + break; + } + env.console.log("No PP. Switch Pokemon.", COLOR_RED); + + // Press B to leave move selection menu + pbf_press_button(context, BUTTON_B, 10, 125); + + // Go to the switching pokemon screen: + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + + cur_pokemon = switch_pokemon(env.console, context, cur_pokemon, POKEMON_ACTIONS.num_pokemon()); + }else{ + stats.move_attempts++; + env.update_stats(); + } + }else if (ret == 1){ + env.console.log("Pokemon fainted."); + cur_pokemon++; + if (cur_pokemon >= POKEMON_ACTIONS.num_pokemon()){ + env.console.log("All pokemon grinded. Stop program."); + break; + } + cur_pokemon = switch_pokemon(env.console, context, cur_pokemon, POKEMON_ACTIONS.num_pokemon()); + }else{ // ret is 2 + env.console.log("Battle finished."); + break; + } + } +} + + + +void MagikarpMoveGrinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MagikarpMoveGrinder_Descriptor::Stats& stats = env.current_stats(); + + if (POKEMON_ACTIONS.num_pokemon() == 0){ + throw UserSetupError(env.console, "No Pokemon specified to grind."); + } + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + env.console.log("Grinding on Magikarp..."); + + try{ + if (SPECIAL_CASE_MIMIC){ + grind_mimic(env, context); + }else{ + battle_magikarp(env, context); + } + + stats.magikarp++; + env.update_stats(); + }catch (OperationFailedException&){ + stats.errors++; + throw; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.h b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.h index 8d75d9cd21..546da9544a 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_MagikarpMoveGrinder.h @@ -1,55 +1,55 @@ -/* Magikarp Move Grinder - * - * From: https://github.com/PokemonAutomation/ - * - * Battle a magikarp to grind move related research tasks. - */ - -#ifndef PokemonAutomation_PokemonLA_MagikarpMoveGrinder_H -#define PokemonAutomation_PokemonLA_MagikarpMoveGrinder_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class MagikarpMoveGrinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MagikarpMoveGrinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class MagikarpMoveGrinder : public SingleSwitchProgramInstance{ -public: - MagikarpMoveGrinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void battle_magikarp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - void grind_mimic(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - OneMoveBattlePokemonActionTable POKEMON_ACTIONS; - - BooleanCheckBoxOption SPECIAL_CASE_MIMIC; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Magikarp Move Grinder + * + * From: https://github.com/PokemonAutomation/ + * + * Battle a magikarp to grind move related research tasks. + */ + +#ifndef PokemonAutomation_PokemonLA_MagikarpMoveGrinder_H +#define PokemonAutomation_PokemonLA_MagikarpMoveGrinder_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class MagikarpMoveGrinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MagikarpMoveGrinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class MagikarpMoveGrinder : public SingleSwitchProgramInstance{ +public: + MagikarpMoveGrinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void battle_magikarp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + void grind_mimic(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + OneMoveBattlePokemonActionTable POKEMON_ACTIONS; + + BooleanCheckBoxOption SPECIAL_CASE_MIMIC; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.cpp b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.cpp index bcd596706d..dca3a5c8a8 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.cpp @@ -1,249 +1,249 @@ -/* Money Farmer (Highlands) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_GameSave.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA_NuggetFarmerHighlands.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -NuggetFarmerHighlands_Descriptor::NuggetFarmerHighlands_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:NuggetFarmerHighlands", - STRING_POKEMON + " LA", "Nugget Farmer (Highlands)", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/NuggetFarmerHighlands.md", - "Farm nuggets off the Miss Fortune sisters in the Coronet Highlands.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class NuggetFarmerHighlands_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , charm(m_stats["Charm"]) - , coin(m_stats["Coin"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Charm", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Coin", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& charm; - std::atomic& coin; - std::atomic& shinies; -}; -std::unique_ptr NuggetFarmerHighlands_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -NuggetFarmerHighlands::NuggetFarmerHighlands() - : SHINY_DETECTED("Shiny Detected Action", "", "2000 ms") - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(SHINY_DETECTED); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -bool NuggetFarmerHighlands::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - NuggetFarmerHighlands_Descriptor::Stats& stats = env.current_stats(); - - // Go to Coronet Highlands Mountain camp. - goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Highlands_Mountain); - - stats.attempts++; - - change_mount(env.console, context, MountState::WYRDEER_ON); - - - bool success = false; - - - env.console.log("Traveling to Charm's location..."); - { - DialogSurpriseDetector dialog_detector(env.console, env.console, true); - - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - return on_shiny_callback(env, env.console, SHINY_DETECTED, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 212, 50, 0); - pbf_press_button(context, BUTTON_B, 492, 80); - - pbf_move_left_joystick(context, 224, 0, 50, 0); -// pbf_press_button(context, BUTTON_B, 350, 80); - pbf_press_button(context, BUTTON_B, 80, 0); - for (size_t c = 0; c < 7; c++){ - pbf_press_button(context, BUTTON_A | BUTTON_B, 5, 0); - pbf_press_button(context, BUTTON_B, 5, 0); - } - pbf_press_button(context, BUTTON_B, 200, 80); - pbf_wait(context, 80); - - pbf_move_left_joystick(context, 0, 64, 50, 0); - pbf_press_button(context, BUTTON_B, 250, 80); - - pbf_move_left_joystick(context, 0, 48, 50, 0); - pbf_press_button(context, BUTTON_B, 250, 0); - - pbf_move_left_joystick(context, 64, 255, 50, 0); - pbf_press_button(context, BUTTON_B, 150, 250); - -// pbf_move_right_joystick(context, 0, 128, 200, 125); - - }, - { - {dialog_detector}, - {shiny_detector}, - } - ); - switch (ret){ - case 0: - env.console.log("Found Charm!", COLOR_BLUE); - stats.charm++; - mash_A_until_end_of_battle(env.console, context); - env.console.log("Battle succeeded!", COLOR_BLUE); - success = true; - break; - case 1: - on_shiny_sound(env, env.console, context, SHINY_DETECTED, shiny_coefficient); - break; - } - } - - -#if 0 - env.console.log("Traveling to Coin's location..."); - { - - } -#endif - - - env.console.log("Returning to Jubilife..."); - - - { - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - return on_shiny_callback(env, env.console, SHINY_DETECTED, error_coefficient); - }); - - int ret = run_until(env.console, context, - [&env](ProControllerContext& context){ - goto_camp_from_overworld(env, env.console, context); - goto_professor(env.console, context, Camp::HIGHLANDS_HIGHLANDS); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, SHINY_DETECTED, shiny_coefficient); - } - } - - - from_professor_return_to_jubilife(env, env.console, context); - - if (success){ - save_game_from_overworld(env, env.console, context); - } - - return false; -} - - - -void NuggetFarmerHighlands::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - NuggetFarmerHighlands_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - // Put a save here so that when the program reloads from error it won't break. - save_game_from_overworld(env, env.console, context); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - if (run_iteration(env, context)){ - break; - } - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Money Farmer (Highlands) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_GameSave.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA_NuggetFarmerHighlands.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +NuggetFarmerHighlands_Descriptor::NuggetFarmerHighlands_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:NuggetFarmerHighlands", + STRING_POKEMON + " LA", "Nugget Farmer (Highlands)", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/NuggetFarmerHighlands.md", + "Farm nuggets off the Miss Fortune sisters in the Coronet Highlands.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class NuggetFarmerHighlands_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , charm(m_stats["Charm"]) + , coin(m_stats["Coin"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Charm", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Coin", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& charm; + std::atomic& coin; + std::atomic& shinies; +}; +std::unique_ptr NuggetFarmerHighlands_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +NuggetFarmerHighlands::NuggetFarmerHighlands() + : SHINY_DETECTED("Shiny Detected Action", "", "2000 ms") + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(SHINY_DETECTED); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +bool NuggetFarmerHighlands::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + NuggetFarmerHighlands_Descriptor::Stats& stats = env.current_stats(); + + // Go to Coronet Highlands Mountain camp. + goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Highlands_Mountain); + + stats.attempts++; + + change_mount(env.console, context, MountState::WYRDEER_ON); + + + bool success = false; + + + env.console.log("Traveling to Charm's location..."); + { + DialogSurpriseDetector dialog_detector(env.console, env.console, true); + + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + return on_shiny_callback(env, env.console, SHINY_DETECTED, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 212, 50, 0); + pbf_press_button(context, BUTTON_B, 492, 80); + + pbf_move_left_joystick(context, 224, 0, 50, 0); +// pbf_press_button(context, BUTTON_B, 350, 80); + pbf_press_button(context, BUTTON_B, 80, 0); + for (size_t c = 0; c < 7; c++){ + pbf_press_button(context, BUTTON_A | BUTTON_B, 5, 0); + pbf_press_button(context, BUTTON_B, 5, 0); + } + pbf_press_button(context, BUTTON_B, 200, 80); + pbf_wait(context, 80); + + pbf_move_left_joystick(context, 0, 64, 50, 0); + pbf_press_button(context, BUTTON_B, 250, 80); + + pbf_move_left_joystick(context, 0, 48, 50, 0); + pbf_press_button(context, BUTTON_B, 250, 0); + + pbf_move_left_joystick(context, 64, 255, 50, 0); + pbf_press_button(context, BUTTON_B, 150, 250); + +// pbf_move_right_joystick(context, 0, 128, 200, 125); + + }, + { + {dialog_detector}, + {shiny_detector}, + } + ); + switch (ret){ + case 0: + env.console.log("Found Charm!", COLOR_BLUE); + stats.charm++; + mash_A_until_end_of_battle(env.console, context); + env.console.log("Battle succeeded!", COLOR_BLUE); + success = true; + break; + case 1: + on_shiny_sound(env, env.console, context, SHINY_DETECTED, shiny_coefficient); + break; + } + } + + +#if 0 + env.console.log("Traveling to Coin's location..."); + { + + } +#endif + + + env.console.log("Returning to Jubilife..."); + + + { + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + return on_shiny_callback(env, env.console, SHINY_DETECTED, error_coefficient); + }); + + int ret = run_until(env.console, context, + [&env](ProControllerContext& context){ + goto_camp_from_overworld(env, env.console, context); + goto_professor(env.console, context, Camp::HIGHLANDS_HIGHLANDS); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, SHINY_DETECTED, shiny_coefficient); + } + } + + + from_professor_return_to_jubilife(env, env.console, context); + + if (success){ + save_game_from_overworld(env, env.console, context); + } + + return false; +} + + + +void NuggetFarmerHighlands::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + NuggetFarmerHighlands_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + // Put a save here so that when the program reloads from error it won't break. + save_game_from_overworld(env, env.console, context); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + if (run_iteration(env, context)){ + break; + } + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.h b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.h index e9614f2248..3b96622e13 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_NuggetFarmerHighlands.h @@ -1,54 +1,54 @@ -/* Money Farmer (Highlands) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_MoneyFarmerHighlands_H -#define PokemonAutomation_PokemonLA_MoneyFarmerHighlands_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class NuggetFarmerHighlands_Descriptor : public SingleSwitchProgramDescriptor{ -public: - NuggetFarmerHighlands_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class NuggetFarmerHighlands : public SingleSwitchProgramInstance{ -public: - NuggetFarmerHighlands(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - class RunRoute; - - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - OverworldShinyDetectedActionOption SHINY_DETECTED; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Money Farmer (Highlands) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_MoneyFarmerHighlands_H +#define PokemonAutomation_PokemonLA_MoneyFarmerHighlands_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class NuggetFarmerHighlands_Descriptor : public SingleSwitchProgramDescriptor{ +public: + NuggetFarmerHighlands_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class NuggetFarmerHighlands : public SingleSwitchProgramInstance{ +public: + NuggetFarmerHighlands(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + class RunRoute; + + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + OverworldShinyDetectedActionOption SHINY_DETECTED; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.cpp b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.cpp index 6d8a1d1955..1a498b885a 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.cpp @@ -1,390 +1,390 @@ -/* Tenacity Candy Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" -#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" -#include "PokemonLA/Programs/PokemonLA_GameSave.h" -#include "PokemonLA_TenacityCandyFarmer.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - -TenacityCandyFarmer_Descriptor::TenacityCandyFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:TenacityCandyFarmer", - STRING_POKEMON + " LA", "Tenacity Candy Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/TenacityCandyFarmer.md", - "Attend Ingo's Path of Tenacity battles leading with a stats fully upgraded, max level, Modest nature Arceus with Legend Plate applied to grind exp, exp candies XL and evolution items.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class TenacityCandyFarmer_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : battles(m_stats["Battles"]) - , faint_switches(m_stats["Faint Switches"]) - , fourth_moves(m_stats["Fourth Moves"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Battles"); - m_display_order.emplace_back("Faint Switches", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Fourth Moves", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - - std::atomic& battles; - std::atomic& faint_switches; - std::atomic& fourth_moves; - std::atomic& errors; -}; -std::unique_ptr TenacityCandyFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -TenacityCandyFarmer::TenacityCandyFarmer() - : FOURTH_MOVE_ON( - "Fourth Move On:
Use Arceus' fourth move to grind research tasks", - { - {FourthMoveOn::None, "none", "None"}, - {FourthMoveOn::Mamoswine, "mamoswine", "Mamoswine (fourth move needs to be set to Flamethrower)"}, - {FourthMoveOn::Avalugg, "avalugg", "Avalugg (fourth move needs to be set to Rock Smash)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - FourthMoveOn::None - ) - , SAVE_EVERY_FEW_BATTLES( - "Save every few battles:
After every this number of battles, save the game. Enter zero to never save the game.", - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(FOURTH_MOVE_ON); - PA_ADD_OPTION(SAVE_EVERY_FEW_BATTLES); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -bool TenacityCandyFarmer::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - TenacityCandyFarmer_Descriptor::Stats& stats = env.current_stats(); - - env.console.log("Starting battle..."); - - // Talk to Ingo to start conversation and select Path of Tenacity: - // Press A to start talking - pbf_press_button(context, BUTTON_A, 20, 100); - // Press A to show battle type selection menu box - pbf_press_button(context, BUTTON_A, 20, 50); - // Move down the menu box to select Path of Tenacity - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - // Press A to select Path of Tenacity - pbf_press_button(context, BUTTON_A, 20, 200); - - // Press A repeatedly to show the opponenet team selection menu box. - // Note: in different languages, there are different number of dialogue boxes to clear to show the team selection menu. - // So we have to use a ButtonDetector to visually check when the team selection menu appears. - { - context.wait_for_all_requests(); - ButtonDetector button(env.console, env.console, ButtonType::ButtonA, {0.56, 0.46, 0.33, 0.27}, std::chrono::milliseconds(100), true); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, 150); - } - }, - { - {button} - } - ); - if (ret != 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect Tenacity path menu after 10 A presses.", - env.console - ); - } - } - // Move down the menu box to select Pearl Clan - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - // Select Pearl Plan to start Path of Tenacity - pbf_mash_button(context, BUTTON_A, 200); - context.wait_for_all_requests(); - - // First opponent, Lian: - // - Goodra: to be KOed or largely weakened by Judgement - // - Mamoswine: to be KOed by Energy Ball - // - Wiscash: to be KOed by Energy Ball - // Note: Wiscash knows Mud Bomb to decrease accuracy, so the battle may take longer than three turns. - // Second opponent, Gaeric: - // - Glalie: to be KOed by Judgement - // - Avalugg: to be KOed by Flash Cannon - // - Froslass: to be KOed by Flash Cannon - // Note: Froslass knows Thunderbolt to inflict paralysis, so the battle may take longer than three turns. - // Third opponent, Irida: - // - Glaceon: to be KOed by Judgement - // - Espeon: to be KOed by Judgement - // - Flareon: to be KOed by Judgement - - // Assume player's Arceus has move: - // 0: Judgement - // 1: Energy Ball - // 2: Flash Cannon - const size_t target_battle_moves[3][3] = { - {0, 1, 1}, - {0, 2, 2}, - {0, 0, 0}, - }; - - // Which move (0, 1, 2 or 3) the game currently selects - size_t cur_move = 0; - // The battle-order index of the current pokemon on the battle field. - size_t cur_pokemon = 0; - // How many turns have passed for the current pokemon in this battle. - int num_turns = 0; - // Used to skip fainted pokemon in the party when switching a pokemon - // This is the party-order index of the pokemon to switch to. - // The index is the index in the pokemon party list. - size_t next_pokemon_to_switch_to = 0; - - // which battle is currently on (vs Lian, Gaeric or Irida) - size_t cur_battle = 0; - // Whether we are in a state to clear multiple dialogue boxes. - bool clearing_dialogues = true; - - auto clear_dialogue_box = [&](){ - if (clearing_dialogues == false){ - // We just ended one battle: - cur_battle++; - cur_move = 0; - cur_pokemon = 0; - num_turns = 0; - } - clearing_dialogues = true; - pbf_press_button(context, BUTTON_B, 20, 100); - context.wait_for_all_requests(); - - if (cur_battle >= 3){ - env.log("All three battles finished. Mashing B to clear dialogues."); - // All three battles are now finished, wait for ArcPhoneDetector - const bool stop_on_detected = true; - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - int ret = run_until( - env.console, context, [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 20 * TICKS_PER_SECOND); - }, - {{arc_phone_detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find Arc phone after 20 seconds when the last battle ends.", - env.console - ); - } - env.log("Found Arc Phone. End of one path."); - - return true; - } - return false; - }; - - while(true){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); - BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); - // normal dialogue appears if you lose the fight. - NormalDialogDetector normal_dialogue_detector(env.console, env.console, stop_on_detected); - DialogSurpriseDetector surprise_dialogue_detector(env.console, env.console, stop_on_detected); - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); - int ret = wait_until( - env.console, context, std::chrono::minutes(2), - { - {battle_menu_detector}, - {normal_dialogue_detector}, - {surprise_dialogue_detector}, - {pokemon_switch_detector}, - {arc_phone_detector}, - } - ); - if (ret < 0){ - env.console.log("Error: Failed to find battle menu after 2 minutes."); -// return true; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find battle menu after 2 minutes.", - env.console - ); - } - - if (ret == 0){ - env.console.log("Our turn! Battle " + std::to_string(cur_battle) + " turn " + std::to_string(num_turns), COLOR_BLUE); - clearing_dialogues = false; - - if (cur_battle == 1 && num_turns == 1){ - // Change opponent to Froslass as Froslass is fast and Avalugg is slow. - // So better to finish Forslass first so that we may move immediately to finish Avalugg - // without taking damage. - pbf_press_button(context, BUTTON_ZL, 10, 100); - } - - // Press A to select moves - pbf_press_button(context, BUTTON_A, 10, 125); - context.wait_for_all_requests(); - - // Choose move to use! - if (cur_pokemon == 0){ // Arceus is still alive - size_t target_move = target_battle_moves[cur_battle][std::min(num_turns, 2)]; - - if (FOURTH_MOVE_ON == FourthMoveOn::Mamoswine && cur_battle == 0 && num_turns == 1){ - env.console.log("Target fourth move on Mamonswine"); - target_move = 3; - stats.fourth_moves++; - env.update_stats(); - }else if (FOURTH_MOVE_ON == FourthMoveOn::Avalugg && cur_battle == 1 && num_turns >= 1){ - // Use Flash Cannon to finish Froslass first, then use fourth move, Rock Smash to grind Avalugg. - target_move = (num_turns == 1 ? 2 : 3); - if (num_turns == 2){ - env.console.log("Target fourth move on Avalugg"); - stats.fourth_moves++; - env.update_stats(); - } - } - - if (cur_move < target_move){ - // Move move selection down - for(size_t i = 0; i < target_move - cur_move; i++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - } - }else if (cur_move > target_move){ - // Move move selection up - for(size_t i = 0; i < cur_move - target_move; i++){ - pbf_press_dpad(context, DPAD_UP, 20, 100); - } - } - cur_move = target_move; - } - - const MoveStyle no_style = MoveStyle::NoStyle; - const bool check_move_success = true; - while (use_move(env.console, context, cur_pokemon, cur_move, no_style, check_move_success) == false){ - // We are still on the move selection screen. No PP. - // Go to the next move. - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - // env.console.context().wait_for_all_requests(); - cur_move = (cur_move + 1) % 4; - env.console.log("No PP. Use next move, " + std::to_string(cur_move), COLOR_RED); - } - - num_turns++; - }else if(ret == 1){ - env.console.log("Normal dialogue box."); - if (clear_dialogue_box()){ - break; - } - }else if(ret == 2){ - env.console.log("Surprise dialogue box."); - if (clear_dialogue_box()){ - break; - } - }else if (ret == 3){ - env.console.log("Pokemon fainted.", COLOR_RED); - - clearing_dialogues = false; - stats.faint_switches++; - env.update_stats(); - - cur_move = 0; - next_pokemon_to_switch_to++; - next_pokemon_to_switch_to = switch_pokemon(env.console, context, next_pokemon_to_switch_to); - cur_pokemon++; - }else{ // ret is 4 - env.console.log("Battle finished."); - break; - } - } - - stats.battles++; - env.update_stats(); - - return false; -} - - - -void TenacityCandyFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - TenacityCandyFarmer_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - // { - // // ImageRGB32 image("./scripts/LA_switch_pokemon_Kuro.png"); - // ImageRGB32 image("./PLA_test_data/ingoBattle/broken_dialogue_detector.png"); - // const bool stop_on_detected = true; - // NormalDialogDetector detector(env.console, env.console, stop_on_detected); - // bool detected = detector.process_frame(image, current_time()); - // std::cout << "detector " << detected << std::endl; - // return; - // } - - size_t num_battles = 0; - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - if (run_iteration(env, context)){ - break; - } - num_battles++; - if (SAVE_EVERY_FEW_BATTLES > 0 && num_battles % SAVE_EVERY_FEW_BATTLES == 0){ - save_game_from_overworld(env, env.console, context); - } - - }catch (OperationFailedException&){ - stats.errors++; - throw; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Tenacity Candy Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" +#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" +#include "PokemonLA/Programs/PokemonLA_GameSave.h" +#include "PokemonLA_TenacityCandyFarmer.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + +TenacityCandyFarmer_Descriptor::TenacityCandyFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:TenacityCandyFarmer", + STRING_POKEMON + " LA", "Tenacity Candy Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/TenacityCandyFarmer.md", + "Attend Ingo's Path of Tenacity battles leading with a stats fully upgraded, max level, Modest nature Arceus with Legend Plate applied to grind exp, exp candies XL and evolution items.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class TenacityCandyFarmer_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : battles(m_stats["Battles"]) + , faint_switches(m_stats["Faint Switches"]) + , fourth_moves(m_stats["Fourth Moves"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Battles"); + m_display_order.emplace_back("Faint Switches", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Fourth Moves", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + + std::atomic& battles; + std::atomic& faint_switches; + std::atomic& fourth_moves; + std::atomic& errors; +}; +std::unique_ptr TenacityCandyFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +TenacityCandyFarmer::TenacityCandyFarmer() + : FOURTH_MOVE_ON( + "Fourth Move On:
Use Arceus' fourth move to grind research tasks", + { + {FourthMoveOn::None, "none", "None"}, + {FourthMoveOn::Mamoswine, "mamoswine", "Mamoswine (fourth move needs to be set to Flamethrower)"}, + {FourthMoveOn::Avalugg, "avalugg", "Avalugg (fourth move needs to be set to Rock Smash)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + FourthMoveOn::None + ) + , SAVE_EVERY_FEW_BATTLES( + "Save every few battles:
After every this number of battles, save the game. Enter zero to never save the game.", + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(FOURTH_MOVE_ON); + PA_ADD_OPTION(SAVE_EVERY_FEW_BATTLES); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +bool TenacityCandyFarmer::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + TenacityCandyFarmer_Descriptor::Stats& stats = env.current_stats(); + + env.console.log("Starting battle..."); + + // Talk to Ingo to start conversation and select Path of Tenacity: + // Press A to start talking + pbf_press_button(context, BUTTON_A, 20, 100); + // Press A to show battle type selection menu box + pbf_press_button(context, BUTTON_A, 20, 50); + // Move down the menu box to select Path of Tenacity + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + // Press A to select Path of Tenacity + pbf_press_button(context, BUTTON_A, 20, 200); + + // Press A repeatedly to show the opponenet team selection menu box. + // Note: in different languages, there are different number of dialogue boxes to clear to show the team selection menu. + // So we have to use a ButtonDetector to visually check when the team selection menu appears. + { + context.wait_for_all_requests(); + ButtonDetector button(env.console, env.console, ButtonType::ButtonA, {0.56, 0.46, 0.33, 0.27}, std::chrono::milliseconds(100), true); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, 150); + } + }, + { + {button} + } + ); + if (ret != 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect Tenacity path menu after 10 A presses.", + env.console + ); + } + } + // Move down the menu box to select Pearl Clan + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + // Select Pearl Plan to start Path of Tenacity + pbf_mash_button(context, BUTTON_A, 200); + context.wait_for_all_requests(); + + // First opponent, Lian: + // - Goodra: to be KOed or largely weakened by Judgement + // - Mamoswine: to be KOed by Energy Ball + // - Wiscash: to be KOed by Energy Ball + // Note: Wiscash knows Mud Bomb to decrease accuracy, so the battle may take longer than three turns. + // Second opponent, Gaeric: + // - Glalie: to be KOed by Judgement + // - Avalugg: to be KOed by Flash Cannon + // - Froslass: to be KOed by Flash Cannon + // Note: Froslass knows Thunderbolt to inflict paralysis, so the battle may take longer than three turns. + // Third opponent, Irida: + // - Glaceon: to be KOed by Judgement + // - Espeon: to be KOed by Judgement + // - Flareon: to be KOed by Judgement + + // Assume player's Arceus has move: + // 0: Judgement + // 1: Energy Ball + // 2: Flash Cannon + const size_t target_battle_moves[3][3] = { + {0, 1, 1}, + {0, 2, 2}, + {0, 0, 0}, + }; + + // Which move (0, 1, 2 or 3) the game currently selects + size_t cur_move = 0; + // The battle-order index of the current pokemon on the battle field. + size_t cur_pokemon = 0; + // How many turns have passed for the current pokemon in this battle. + int num_turns = 0; + // Used to skip fainted pokemon in the party when switching a pokemon + // This is the party-order index of the pokemon to switch to. + // The index is the index in the pokemon party list. + size_t next_pokemon_to_switch_to = 0; + + // which battle is currently on (vs Lian, Gaeric or Irida) + size_t cur_battle = 0; + // Whether we are in a state to clear multiple dialogue boxes. + bool clearing_dialogues = true; + + auto clear_dialogue_box = [&](){ + if (clearing_dialogues == false){ + // We just ended one battle: + cur_battle++; + cur_move = 0; + cur_pokemon = 0; + num_turns = 0; + } + clearing_dialogues = true; + pbf_press_button(context, BUTTON_B, 20, 100); + context.wait_for_all_requests(); + + if (cur_battle >= 3){ + env.log("All three battles finished. Mashing B to clear dialogues."); + // All three battles are now finished, wait for ArcPhoneDetector + const bool stop_on_detected = true; + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + int ret = run_until( + env.console, context, [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 20 * TICKS_PER_SECOND); + }, + {{arc_phone_detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find Arc phone after 20 seconds when the last battle ends.", + env.console + ); + } + env.log("Found Arc Phone. End of one path."); + + return true; + } + return false; + }; + + while(true){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); + BattlePokemonSwitchDetector pokemon_switch_detector(env.console, env.console, stop_on_detected); + // normal dialogue appears if you lose the fight. + NormalDialogDetector normal_dialogue_detector(env.console, env.console, stop_on_detected); + DialogSurpriseDetector surprise_dialogue_detector(env.console, env.console, stop_on_detected); + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(200), stop_on_detected); + int ret = wait_until( + env.console, context, std::chrono::minutes(2), + { + {battle_menu_detector}, + {normal_dialogue_detector}, + {surprise_dialogue_detector}, + {pokemon_switch_detector}, + {arc_phone_detector}, + } + ); + if (ret < 0){ + env.console.log("Error: Failed to find battle menu after 2 minutes."); +// return true; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find battle menu after 2 minutes.", + env.console + ); + } + + if (ret == 0){ + env.console.log("Our turn! Battle " + std::to_string(cur_battle) + " turn " + std::to_string(num_turns), COLOR_BLUE); + clearing_dialogues = false; + + if (cur_battle == 1 && num_turns == 1){ + // Change opponent to Froslass as Froslass is fast and Avalugg is slow. + // So better to finish Forslass first so that we may move immediately to finish Avalugg + // without taking damage. + pbf_press_button(context, BUTTON_ZL, 10, 100); + } + + // Press A to select moves + pbf_press_button(context, BUTTON_A, 10, 125); + context.wait_for_all_requests(); + + // Choose move to use! + if (cur_pokemon == 0){ // Arceus is still alive + size_t target_move = target_battle_moves[cur_battle][std::min(num_turns, 2)]; + + if (FOURTH_MOVE_ON == FourthMoveOn::Mamoswine && cur_battle == 0 && num_turns == 1){ + env.console.log("Target fourth move on Mamonswine"); + target_move = 3; + stats.fourth_moves++; + env.update_stats(); + }else if (FOURTH_MOVE_ON == FourthMoveOn::Avalugg && cur_battle == 1 && num_turns >= 1){ + // Use Flash Cannon to finish Froslass first, then use fourth move, Rock Smash to grind Avalugg. + target_move = (num_turns == 1 ? 2 : 3); + if (num_turns == 2){ + env.console.log("Target fourth move on Avalugg"); + stats.fourth_moves++; + env.update_stats(); + } + } + + if (cur_move < target_move){ + // Move move selection down + for(size_t i = 0; i < target_move - cur_move; i++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + } + }else if (cur_move > target_move){ + // Move move selection up + for(size_t i = 0; i < cur_move - target_move; i++){ + pbf_press_dpad(context, DPAD_UP, 20, 100); + } + } + cur_move = target_move; + } + + const MoveStyle no_style = MoveStyle::NoStyle; + const bool check_move_success = true; + while (use_move(env.console, context, cur_pokemon, cur_move, no_style, check_move_success) == false){ + // We are still on the move selection screen. No PP. + // Go to the next move. + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + // env.console.context().wait_for_all_requests(); + cur_move = (cur_move + 1) % 4; + env.console.log("No PP. Use next move, " + std::to_string(cur_move), COLOR_RED); + } + + num_turns++; + }else if(ret == 1){ + env.console.log("Normal dialogue box."); + if (clear_dialogue_box()){ + break; + } + }else if(ret == 2){ + env.console.log("Surprise dialogue box."); + if (clear_dialogue_box()){ + break; + } + }else if (ret == 3){ + env.console.log("Pokemon fainted.", COLOR_RED); + + clearing_dialogues = false; + stats.faint_switches++; + env.update_stats(); + + cur_move = 0; + next_pokemon_to_switch_to++; + next_pokemon_to_switch_to = switch_pokemon(env.console, context, next_pokemon_to_switch_to); + cur_pokemon++; + }else{ // ret is 4 + env.console.log("Battle finished."); + break; + } + } + + stats.battles++; + env.update_stats(); + + return false; +} + + + +void TenacityCandyFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + TenacityCandyFarmer_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + // { + // // ImageRGB32 image("./scripts/LA_switch_pokemon_Kuro.png"); + // ImageRGB32 image("./PLA_test_data/ingoBattle/broken_dialogue_detector.png"); + // const bool stop_on_detected = true; + // NormalDialogDetector detector(env.console, env.console, stop_on_detected); + // bool detected = detector.process_frame(image, current_time()); + // std::cout << "detector " << detected << std::endl; + // return; + // } + + size_t num_battles = 0; + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + if (run_iteration(env, context)){ + break; + } + num_battles++; + if (SAVE_EVERY_FEW_BATTLES > 0 && num_battles % SAVE_EVERY_FEW_BATTLES == 0){ + save_game_from_overworld(env, env.console, context); + } + + }catch (OperationFailedException&){ + stats.errors++; + throw; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.h b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.h index 67255c7174..eed5a400c8 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Farming/PokemonLA_TenacityCandyFarmer.h @@ -1,59 +1,59 @@ -/* Tenacity Candy Farmer - * - * From: https://github.com/PokemonAutomation/ - * - * Battle Pearl Clan in Path of Tenacity to farm exp, Exp Candy XL and random evolution items. - */ - -#ifndef PokemonAutomation_PokemonLA_TenacityCandyFarmer_H -#define PokemonAutomation_PokemonLA_TenacityCandyFarmer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class TenacityCandyFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TenacityCandyFarmer_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class TenacityCandyFarmer : public SingleSwitchProgramInstance{ -public: - TenacityCandyFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - enum class FourthMoveOn{ - None, - Mamoswine, - Avalugg, - }; - EnumDropdownOption FOURTH_MOVE_ON; - - SimpleIntegerOption SAVE_EVERY_FEW_BATTLES; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Tenacity Candy Farmer + * + * From: https://github.com/PokemonAutomation/ + * + * Battle Pearl Clan in Path of Tenacity to farm exp, Exp Candy XL and random evolution items. + */ + +#ifndef PokemonAutomation_PokemonLA_TenacityCandyFarmer_H +#define PokemonAutomation_PokemonLA_TenacityCandyFarmer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class TenacityCandyFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TenacityCandyFarmer_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class TenacityCandyFarmer : public SingleSwitchProgramInstance{ +public: + TenacityCandyFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + enum class FourthMoveOn{ + None, + Mamoswine, + Avalugg, + }; + EnumDropdownOption FOURTH_MOVE_ON; + + SimpleIntegerOption SAVE_EVERY_FEW_BATTLES; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.cpp index 2626c3cd96..fe6ea9d48a 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.cpp @@ -1,133 +1,133 @@ -/* Apply Grits - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_ApplyGrits.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - -namespace{ - -// For each grit item, how many levels it can increase: -const size_t grit_level_increase[4] = {3, 3, 3, 1}; - -} - - -ApplyGrits_Descriptor::ApplyGrits_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:ApplyGrits", - STRING_POKEMON + " LA", "Apply Grits", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ApplyGrits.md", - "Use Grits items on " + STRING_POKEMON, - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -ApplyGrits::ApplyGrits() - : NUM_POKEMON( - "Number of " + STRING_POKEMON + " to Apply Grits:", - { - {1, "1", "1"}, - {2, "2", "2"}, - {3, "3", "3"}, - {4, "4", "4"}, - {5, "5", "5"}, - {6, "6", "6"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 1 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(NUM_POKEMON); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void ApplyGrits::ApplyGritsOnOnePokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t pokemon_index){ - // Start the function when the game is in the item menu, with cursor hovering over Grit Dust - // Grit Gravel, Grit Pebble and Grit Rock must be on the right side of Grit Dust, in the correct order. - - for(size_t grit_index = 0; grit_index < 4; grit_index++){ - - if (grit_index > 0){ - // Move to the next Grit item - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - } - - // Press A to open the item menu of Grit Dust - pbf_press_button(context, BUTTON_A, 20, 50); - // Press A again to use the item - pbf_press_button(context, BUTTON_A, 20, 50); - - // Move down the pokemon list - for(size_t i = 0; i < pokemon_index; i++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 80); - } - - // Select the pokemon - pbf_press_button(context, BUTTON_A, 20, 80); - - // For each of the size pokemon attributes: HP, Attack, Defense, Sp. Atk, Sp. Def, Speed - for(size_t attr_index = 0; attr_index < 6; attr_index++){ - if (attr_index > 0){ - // Move to the next attribute - pbf_press_dpad(context, DPAD_DOWN, 20, 50); - } - for(size_t i = 0; i < grit_level_increase[grit_index]; i++){ - // One press to apply the Grit item - pbf_press_button(context, BUTTON_A, 20, 100); - // Second press to clear the message box, whether it is applied successfully or not. - pbf_press_button(context, BUTTON_A, 20, 100); - } - } - - // Press B twice to back to item selection - pbf_press_button(context, BUTTON_B, 20, 50); - pbf_press_button(context, BUTTON_B, 20, 50); - } - - // Move back to hovering over Grit Dust - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - - context.wait_for_all_requests(); -} - -void ApplyGrits::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - size_t num_pokemon = NUM_POKEMON.current_value(); - for(size_t i = 0; i < num_pokemon; i++){ - ApplyGritsOnOnePokemon(env, context, i); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Apply Grits + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_ApplyGrits.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + +namespace{ + +// For each grit item, how many levels it can increase: +const size_t grit_level_increase[4] = {3, 3, 3, 1}; + +} + + +ApplyGrits_Descriptor::ApplyGrits_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:ApplyGrits", + STRING_POKEMON + " LA", "Apply Grits", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ApplyGrits.md", + "Use Grits items on " + STRING_POKEMON, + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +ApplyGrits::ApplyGrits() + : NUM_POKEMON( + "Number of " + STRING_POKEMON + " to Apply Grits:", + { + {1, "1", "1"}, + {2, "2", "2"}, + {3, "3", "3"}, + {4, "4", "4"}, + {5, "5", "5"}, + {6, "6", "6"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 1 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(NUM_POKEMON); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void ApplyGrits::ApplyGritsOnOnePokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t pokemon_index){ + // Start the function when the game is in the item menu, with cursor hovering over Grit Dust + // Grit Gravel, Grit Pebble and Grit Rock must be on the right side of Grit Dust, in the correct order. + + for(size_t grit_index = 0; grit_index < 4; grit_index++){ + + if (grit_index > 0){ + // Move to the next Grit item + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + } + + // Press A to open the item menu of Grit Dust + pbf_press_button(context, BUTTON_A, 20, 50); + // Press A again to use the item + pbf_press_button(context, BUTTON_A, 20, 50); + + // Move down the pokemon list + for(size_t i = 0; i < pokemon_index; i++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 80); + } + + // Select the pokemon + pbf_press_button(context, BUTTON_A, 20, 80); + + // For each of the size pokemon attributes: HP, Attack, Defense, Sp. Atk, Sp. Def, Speed + for(size_t attr_index = 0; attr_index < 6; attr_index++){ + if (attr_index > 0){ + // Move to the next attribute + pbf_press_dpad(context, DPAD_DOWN, 20, 50); + } + for(size_t i = 0; i < grit_level_increase[grit_index]; i++){ + // One press to apply the Grit item + pbf_press_button(context, BUTTON_A, 20, 100); + // Second press to clear the message box, whether it is applied successfully or not. + pbf_press_button(context, BUTTON_A, 20, 100); + } + } + + // Press B twice to back to item selection + pbf_press_button(context, BUTTON_B, 20, 50); + pbf_press_button(context, BUTTON_B, 20, 50); + } + + // Move back to hovering over Grit Dust + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + + context.wait_for_all_requests(); +} + +void ApplyGrits::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + size_t num_pokemon = NUM_POKEMON.current_value(); + for(size_t i = 0; i < num_pokemon; i++){ + ApplyGritsOnOnePokemon(env, context, i); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.h index 08ec716b31..b67d2950c6 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ApplyGrits.h @@ -1,47 +1,47 @@ -/* Apply Grits - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ApplyGrits_H -#define PokemonAutomation_PokemonLA_ApplyGrits_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ApplyGrits_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ApplyGrits_Descriptor(); -}; - - -class ApplyGrits : public SingleSwitchProgramInstance{ -public: - ApplyGrits(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - - void ApplyGritsOnOnePokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t pokemon_index); - - IntegerEnumDropdownOption NUM_POKEMON; - - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Apply Grits + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ApplyGrits_H +#define PokemonAutomation_PokemonLA_ApplyGrits_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ApplyGrits_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ApplyGrits_Descriptor(); +}; + + +class ApplyGrits : public SingleSwitchProgramInstance{ +public: + ApplyGrits(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + + void ApplyGritsOnOnePokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t pokemon_index); + + IntegerEnumDropdownOption NUM_POKEMON; + + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.cpp index 1fb0f40d99..05826262f2 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.cpp @@ -1,47 +1,47 @@ -/* Braviary Height Glitch - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_BraviaryHeightGlitch.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -BraviaryHeightGlitch_Descriptor::BraviaryHeightGlitch_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:BraviaryHeightGlitch", - STRING_POKEMON + " LA", "Braviary Height Glitch", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/BraviaryHeightGlitch.md", - "Increase your height in place using the height glitch.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -BraviaryHeightGlitch::BraviaryHeightGlitch(){} - - -void BraviaryHeightGlitch::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - while (true){ - pbf_press_button(context, BUTTON_Y, 30, 0); - pbf_press_button(context, BUTTON_PLUS, 30, 10); - pbf_press_button(context, BUTTON_PLUS, 30, 30); - } -} - - - - -} -} -} +/* Braviary Height Glitch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_BraviaryHeightGlitch.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +BraviaryHeightGlitch_Descriptor::BraviaryHeightGlitch_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:BraviaryHeightGlitch", + STRING_POKEMON + " LA", "Braviary Height Glitch", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/BraviaryHeightGlitch.md", + "Increase your height in place using the height glitch.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +BraviaryHeightGlitch::BraviaryHeightGlitch(){} + + +void BraviaryHeightGlitch::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + while (true){ + pbf_press_button(context, BUTTON_Y, 30, 0); + pbf_press_button(context, BUTTON_PLUS, 30, 10); + pbf_press_button(context, BUTTON_PLUS, 30, 30); + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.h index dc5b212399..aa8ecd30f0 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_BraviaryHeightGlitch.h @@ -1,37 +1,37 @@ -/* Braviary Height Glitch - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_BraviaryHeightGlitch_H -#define PokemonAutomation_PokemonLA_BraviaryHeightGlitch_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class BraviaryHeightGlitch_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BraviaryHeightGlitch_Descriptor(); -}; - - -class BraviaryHeightGlitch : public SingleSwitchProgramInstance{ -public: - BraviaryHeightGlitch(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; -}; - - - - - -} -} -} -#endif +/* Braviary Height Glitch + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_BraviaryHeightGlitch_H +#define PokemonAutomation_PokemonLA_BraviaryHeightGlitch_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class BraviaryHeightGlitch_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BraviaryHeightGlitch_Descriptor(); +}; + + +class BraviaryHeightGlitch : public SingleSwitchProgramInstance{ +public: + BraviaryHeightGlitch(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.cpp index 24712e143e..fd0cf82976 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.cpp @@ -1,79 +1,79 @@ -/* Clothing Buyer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_ClothingBuyer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -ClothingBuyer_Descriptor::ClothingBuyer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:ClothingBuyer", - STRING_POKEMON + " LA", "Clothing Buyer", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ClothingBuyer.md", - "Buy out all the clothing in the store.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -ClothingBuyer::ClothingBuyer() - : CATEGORY_ROTATION( - "Rotate Categories:
This slows down the program, but ensures it will cover all categories.", - LockMode::LOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_OPTION(CATEGORY_ROTATION); -} - - -void ClothingBuyer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - // If this clothing is not bought: - // Press A to pop purchase dialogue - // Press A to confirm purchase - // Press B to not wear it - // Press B to clear dialogue - - // If this clothing is already bought: - // Press A to do nothing - // Press A to do nothing - // Press B to be asked whether to leave menu - // Press B to not leave - - pbf_press_button(context, BUTTON_A, 10, 120); - pbf_press_button(context, BUTTON_A, 10, 130); - pbf_press_button(context, BUTTON_B, 10, 120); - pbf_press_button(context, BUTTON_B, 10, 60); - - // Move to the next clothing in the same category - pbf_press_dpad(context, DPAD_DOWN, 10, 40); - - // Move to the next category - if (CATEGORY_ROTATION){ - pbf_press_button(context, BUTTON_R, 10, 40); - } - } -} - - - - -} -} -} +/* Clothing Buyer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_ClothingBuyer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +ClothingBuyer_Descriptor::ClothingBuyer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:ClothingBuyer", + STRING_POKEMON + " LA", "Clothing Buyer", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ClothingBuyer.md", + "Buy out all the clothing in the store.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +ClothingBuyer::ClothingBuyer() + : CATEGORY_ROTATION( + "Rotate Categories:
This slows down the program, but ensures it will cover all categories.", + LockMode::LOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_OPTION(CATEGORY_ROTATION); +} + + +void ClothingBuyer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + // If this clothing is not bought: + // Press A to pop purchase dialogue + // Press A to confirm purchase + // Press B to not wear it + // Press B to clear dialogue + + // If this clothing is already bought: + // Press A to do nothing + // Press A to do nothing + // Press B to be asked whether to leave menu + // Press B to not leave + + pbf_press_button(context, BUTTON_A, 10, 120); + pbf_press_button(context, BUTTON_A, 10, 130); + pbf_press_button(context, BUTTON_B, 10, 120); + pbf_press_button(context, BUTTON_B, 10, 60); + + // Move to the next clothing in the same category + pbf_press_dpad(context, DPAD_DOWN, 10, 40); + + // Move to the next category + if (CATEGORY_ROTATION){ + pbf_press_button(context, BUTTON_R, 10, 40); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.h index f544fa98a9..54dc806b6a 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_ClothingBuyer.h @@ -1,43 +1,43 @@ -/* Clothing Buyer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ClothingBuyer_H -#define PokemonAutomation_PokemonLA_ClothingBuyer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ClothingBuyer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ClothingBuyer_Descriptor(); -}; - - -class ClothingBuyer : public SingleSwitchProgramInstance{ -public: - ClothingBuyer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - - BooleanCheckBoxOption CATEGORY_ROTATION; - -}; - - - - - -} -} -} -#endif +/* Clothing Buyer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ClothingBuyer_H +#define PokemonAutomation_PokemonLA_ClothingBuyer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ClothingBuyer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ClothingBuyer_Descriptor(); +}; + + +class ClothingBuyer : public SingleSwitchProgramInstance{ +public: + ClothingBuyer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + + BooleanCheckBoxOption CATEGORY_ROTATION; + +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.cpp index eb717e043e..fd479118c6 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.cpp @@ -1,158 +1,158 @@ -/* Distortion Waiter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/PokemonLA_NotificationReader.h" -#include "PokemonLA_DistortionWaiter.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -DistortionWaiter_Descriptor::DistortionWaiter_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:DistortionWaiter", - STRING_POKEMON + " LA", "Distortion Waiter", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/DistortionWaiter.md", - "Wait for a distortion to appear.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class DistortionWaiter_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : minutes_waited(m_stats["Minutes Waited"]) - , distortions(m_stats["Distortions"]) - , other(m_stats["Other Notifications"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Minutes Waited"); - m_display_order.emplace_back("Distortions"); - m_display_order.emplace_back("Other Notifications", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - - std::atomic& minutes_waited; - std::atomic& distortions; - std::atomic& other; - std::atomic& errors; -}; -std::unique_ptr DistortionWaiter_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -DistortionWaiter::DistortionWaiter() - : LANGUAGE( - "Game Language:", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_DISTORTION( - "Distortion Appeared", - true, true, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_DISTORTION, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void DistortionWaiter::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DistortionWaiter_Descriptor::Stats& stats = env.current_stats(); - - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - - NotificationDetector detector(env.console, LANGUAGE); - - WallClock start = current_time(); - while (true){ - env.update_stats(); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 60; c++){ - pbf_press_button(context, BUTTON_LCLICK, 20, 60 * TICKS_PER_SECOND - 20); - context.wait_for_all_requests(); - auto elapsed = current_time() - start; - uint64_t minutes = std::chrono::duration_cast(elapsed).count(); - if (minutes != stats.minutes_waited.load(std::memory_order_relaxed)){ - stats.minutes_waited.store(minutes, std::memory_order_relaxed); - env.update_stats(); - } - } - }, - {{detector}} - ); - if (ret < 0){ - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No distortion found after one hour.", - env.console - ); - } - - auto elapsed = current_time() - start; - uint64_t minutes = std::chrono::duration_cast(elapsed).count(); - stats.minutes_waited.store(minutes, std::memory_order_relaxed); - - if (detector.result() == Notification::DISTORTION_FORMING){ - stats.distortions++; - break; - } - if (detector.result() == Notification::ERROR){ - stats.errors++; - }else{ - stats.other++; - } - - context.wait_for(std::chrono::seconds(10)); - } - - - env.update_stats(); - - send_program_notification( - env, NOTIFICATION_DISTORTION, - COLOR_GREEN, - "Found Distortion", - {}, "", - env.console.video().snapshot() - ); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); -} - - - -} -} -} +/* Distortion Waiter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/PokemonLA_NotificationReader.h" +#include "PokemonLA_DistortionWaiter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +DistortionWaiter_Descriptor::DistortionWaiter_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:DistortionWaiter", + STRING_POKEMON + " LA", "Distortion Waiter", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/DistortionWaiter.md", + "Wait for a distortion to appear.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class DistortionWaiter_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : minutes_waited(m_stats["Minutes Waited"]) + , distortions(m_stats["Distortions"]) + , other(m_stats["Other Notifications"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Minutes Waited"); + m_display_order.emplace_back("Distortions"); + m_display_order.emplace_back("Other Notifications", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + + std::atomic& minutes_waited; + std::atomic& distortions; + std::atomic& other; + std::atomic& errors; +}; +std::unique_ptr DistortionWaiter_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +DistortionWaiter::DistortionWaiter() + : LANGUAGE( + "Game Language:", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_DISTORTION( + "Distortion Appeared", + true, true, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_DISTORTION, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void DistortionWaiter::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DistortionWaiter_Descriptor::Stats& stats = env.current_stats(); + + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + + NotificationDetector detector(env.console, LANGUAGE); + + WallClock start = current_time(); + while (true){ + env.update_stats(); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 60; c++){ + pbf_press_button(context, BUTTON_LCLICK, 20, 60 * TICKS_PER_SECOND - 20); + context.wait_for_all_requests(); + auto elapsed = current_time() - start; + uint64_t minutes = std::chrono::duration_cast(elapsed).count(); + if (minutes != stats.minutes_waited.load(std::memory_order_relaxed)){ + stats.minutes_waited.store(minutes, std::memory_order_relaxed); + env.update_stats(); + } + } + }, + {{detector}} + ); + if (ret < 0){ + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No distortion found after one hour.", + env.console + ); + } + + auto elapsed = current_time() - start; + uint64_t minutes = std::chrono::duration_cast(elapsed).count(); + stats.minutes_waited.store(minutes, std::memory_order_relaxed); + + if (detector.result() == Notification::DISTORTION_FORMING){ + stats.distortions++; + break; + } + if (detector.result() == Notification::ERROR){ + stats.errors++; + }else{ + stats.other++; + } + + context.wait_for(std::chrono::seconds(10)); + } + + + env.update_stats(); + + send_program_notification( + env, NOTIFICATION_DISTORTION, + COLOR_GREEN, + "Found Distortion", + {}, "", + env.console.video().snapshot() + ); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.h index 54cc81d372..e7c9360bf0 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_DistortionWaiter.h @@ -1,48 +1,48 @@ -/* Distortion Waiter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_DistortionWaiter_H -#define PokemonAutomation_PokemonLA_DistortionWaiter_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class DistortionWaiter_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DistortionWaiter_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class DistortionWaiter : public SingleSwitchProgramInstance{ -public: - DistortionWaiter(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - OCR::LanguageOCROption LANGUAGE; - - EventNotificationOption NOTIFICATION_DISTORTION; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Distortion Waiter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_DistortionWaiter_H +#define PokemonAutomation_PokemonLA_DistortionWaiter_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class DistortionWaiter_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DistortionWaiter_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class DistortionWaiter : public SingleSwitchProgramInstance{ +public: + DistortionWaiter(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + OCR::LanguageOCROption LANGUAGE; + + EventNotificationOption NOTIFICATION_DISTORTION; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp index c4b78f7e6d..dff72c48e5 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.cpp @@ -1,305 +1,305 @@ -/* Pokemon LA MMO Routines - * - * Functions to run MMO related tasks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/PokemonLA_Locations.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -std::vector load_mmo_names(){ - return { - "fieldlands-mmo", - "mirelands-mmo", - "coastlands-mmo", - "highlands-mmo", - "icelands-mmo" - }; -} - -const std::vector& MMO_NAMES(){ - const static std::vector mmo_names = load_mmo_names(); - return mmo_names; -} - - -std::set enter_region_and_read_MMO( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::string& mmo_name, - const std::set& desired_MMOs, - const std::set& desired_star_MMOs, - bool debug_mode, - int& num_mmo_pokemon_found, - int& num_star_mmo_found -){ - MapRegion region = MapRegion::NONE; - TravelLocation location = TravelLocations::instance().Fieldlands_Fieldlands; - Camp camp = Camp::FIELDLANDS_FIELDLANDS; - // When you open the map in a region, the map cursor is initialized at your current location - // on map. But when you land in a region, the initial location is a camp, the map cursor - // will show a text box "xxx Camp - Take a rest or do some crafting". This may occlude some - // MMO question marks. So we have to move the map cursor away after we land in the region. - uint8_t map_cursor_move_x = 0; - uint8_t map_cursor_move_y = 0; - const int map_cursor_move_duration = 50; - - for(size_t i = 0; i < 5; i++){ - if (mmo_name == MMO_NAMES()[i]){ - switch (i){ - case 0: - region = MapRegion::FIELDLANDS; - location = TravelLocations::instance().Fieldlands_Fieldlands; - camp = Camp::FIELDLANDS_FIELDLANDS; - map_cursor_move_x = 128; - map_cursor_move_y = 0; - break; - case 1: - region = MapRegion::MIRELANDS; - location = TravelLocations::instance().Mirelands_Mirelands; - camp = Camp::MIRELANDS_MIRELANDS; - map_cursor_move_x = 0; - map_cursor_move_y = 128; - break; - case 2: - region = MapRegion::COASTLANDS; - location = TravelLocations::instance().Coastlands_Beachside; - camp = Camp::COASTLANDS_BEACHSIDE; - map_cursor_move_x = 0; - map_cursor_move_y = 128; - break; - case 3: - region = MapRegion::HIGHLANDS; - location = TravelLocations::instance().Highlands_Highlands; - camp = Camp::HIGHLANDS_HIGHLANDS; - map_cursor_move_x = 128; - map_cursor_move_y = 255; - break; - case 4: - region = MapRegion::ICELANDS; - location = TravelLocations::instance().Icelands_Snowfields; - camp = Camp::ICELANDS_SNOWFIELDS; - map_cursor_move_x = 128; - map_cursor_move_y = 255; - break; - } - } - } - if (region == MapRegion::NONE){ - throw InternalProgramError(&env.console.logger(), PA_CURRENT_FUNCTION, "No MMO region name found."); - } - - env.log("Go to " + std::string(MAP_REGION_NAMES[int(region)]) + " to check MMO."); - goto_camp_from_jubilife(env, env.console, context, location); - - // Open map - pbf_press_button(context, BUTTON_MINUS, 50, 100); - context.wait_for_all_requests(); - - // Take a photo of the map before - VideoSnapshot question_mark_image = env.console.video().snapshot(); - - // Fix zoom level: - const int zoom_level = read_map_zoom_level(question_mark_image); - if (zoom_level < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Canot read map zoom level.", - env.console - ); - } - if (zoom_level == 0){ - pbf_press_button(context, BUTTON_ZR, 50, 50); - context.wait_for_all_requests(); - question_mark_image = env.console.video().snapshot(); - }else if (zoom_level == 2){ - pbf_press_button(context, BUTTON_ZL, 50, 50); - context.wait_for_all_requests(); - question_mark_image = env.console.video().snapshot(); - } - - // Move cursor away so that it does not show a text box that occludes MMO sprites. - pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); - context.wait_for_all_requests(); - - // Fix Missions & Requests tab: - if (is_map_mission_tab_raised(question_mark_image)){ - pbf_press_button(context, BUTTON_R, 50, 100); - context.wait_for_all_requests(); - question_mark_image = env.console.video().snapshot(); - } - - // Now detect question marks: - MMOQuestionMarkDetector question_mark_detector(env.logger()); - - const auto quest_results = question_mark_detector.detect_MMOs_on_region_map(question_mark_image); - env.log("Detected MMO question marks:"); - for(const auto& box : quest_results){ - std::ostringstream os; - os << "- " << box.center_x() << ", " << box.center_y() << " " << box.width() << " x " << box.height(); - env.log(os.str()); - } - - // Clean the detected boxes, make them square. - std::vector new_boxes; - for (size_t i = 0; i < quest_results.size(); i++){ - const auto& box = quest_results[i]; - - pxint_t radius = (pxint_t)((box.width() + box.height()) / 4 + 0.5); - pxint_t center_x = (pxint_t)box.center_x(); - pxint_t center_y = (pxint_t)box.center_y(); - auto new_box = ImagePixelBox(center_x - radius, center_y - radius, center_x + radius, center_y + radius); - new_boxes.push_back(new_box); - } - - // Leave map view, back to overworld - pbf_press_button(context, BUTTON_B, 20, 50); - - // Now go to Mai to see the reviewed map - goto_Mai_from_camp(env.logger(), context, camp); - - pbf_mash_button(context, BUTTON_A, 350); - context.wait_for_all_requests(); - - // Wait for the last dialog box before the MMO pokemon sprites are revealed. - { - EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); - int ret = wait_until(env.console, context, std::chrono::seconds(10), {{event_dialog_detector}}); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Dialog box not detected when waiting for MMO map.", - env.console - ); - } - } - pbf_press_button(context, BUTTON_B, 50, 50); - - while (true){ - EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); - MapDetector map_detector; - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - {event_dialog_detector, map_detector} - ); - switch (ret){ - case 0: - env.console.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 1: - env.console.log("Found revealed map thanks to Munchlax!"); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after talking to Mai.", - env.console - ); - } - break; - } - -#if 0 - MapDetector map_detector; - ret = wait_until(env.console, context, std::chrono::seconds(5), {{map_detector}}); - if (ret < 0){ - OperationFailedException::fire( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Map not detected after talking to Mai.", - true - ); - } - env.console.log("Found revealed map thanks to Munchlax!"); -#endif - - VideoOverlaySet mmo_sprites_overlay(env.console); - for (size_t i = 0; i < new_boxes.size(); i++){ - mmo_sprites_overlay.add(COLOR_BLUE, pixelbox_to_floatbox(question_mark_image, new_boxes[i])); - } - - // Move cursor away so that it does not show a text box that occludes MMO sprites. - pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); - context.wait_for_all_requests(); - - std::set found; - - // Check MMO results: - std::vector sprites; - VideoSnapshot sprites_screen = env.console.video().snapshot(); - for (size_t i = 0; i < new_boxes.size(); i++){ - auto result = match_sprite_on_map(env.logger(), sprites_screen, new_boxes[i], region, debug_mode); - env.console.log("Found MMO sprite " + result.slug); - num_mmo_pokemon_found++; - - sprites.push_back(result.slug); - if (desired_MMOs.find(result.slug) != desired_MMOs.end()){ - found.insert(result.slug); - } - } - - // Check star MMO results: - std::vector star_boxes; - for (size_t i = 0; i < new_boxes.size(); i++){ - const auto& sprite_box = new_boxes[i]; - pxint_t radius = (pxint_t)sprite_box.width() / 2; - pxint_t center_x = (pxint_t)sprite_box.center_x(); - pxint_t center_y = (pxint_t)sprite_box.center_y(); - ImagePixelBox star_box( - center_x + radius/10, - center_y - radius*16/10, - center_x + radius * 5/4, - center_y - ); - star_boxes.push_back(std::move(star_box)); - } - - MMOSpriteStarSymbolDetector star_detector(sprites_screen, star_boxes); - - env.log("Detect star symbols..."); - wait_until(env.console, context, std::chrono::seconds(5), {{star_detector}}); - for (size_t i = 0; i < new_boxes.size(); i++){ - std::ostringstream os; - os << "- " << sprites[i] << " box [" << star_boxes[i].min_x << ", " << star_boxes[i].min_y - << star_boxes[i].max_x << ", " << star_boxes[i].max_y << "]" - << " motion: " << star_detector.animation_value(i) - << " color: " << star_detector.symbol_color(i); - if (star_detector.is_star(i)){ - num_star_mmo_found++; - os << ", has star"; - if (desired_star_MMOs.find(sprites[i]) != desired_star_MMOs.end()){ - found.insert(sprites[i]); - } - } - env.log(os.str()); - } - return found; -} - - - -} -} -} +/* Pokemon LA MMO Routines + * + * Functions to run MMO related tasks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" +#include "PokemonLA/Inference/Map/PokemonLA_MMOSpriteStarSymbolDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" +#include "PokemonLA/PokemonLA_Locations.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +std::vector load_mmo_names(){ + return { + "fieldlands-mmo", + "mirelands-mmo", + "coastlands-mmo", + "highlands-mmo", + "icelands-mmo" + }; +} + +const std::vector& MMO_NAMES(){ + const static std::vector mmo_names = load_mmo_names(); + return mmo_names; +} + + +std::set enter_region_and_read_MMO( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& mmo_name, + const std::set& desired_MMOs, + const std::set& desired_star_MMOs, + bool debug_mode, + int& num_mmo_pokemon_found, + int& num_star_mmo_found +){ + MapRegion region = MapRegion::NONE; + TravelLocation location = TravelLocations::instance().Fieldlands_Fieldlands; + Camp camp = Camp::FIELDLANDS_FIELDLANDS; + // When you open the map in a region, the map cursor is initialized at your current location + // on map. But when you land in a region, the initial location is a camp, the map cursor + // will show a text box "xxx Camp - Take a rest or do some crafting". This may occlude some + // MMO question marks. So we have to move the map cursor away after we land in the region. + uint8_t map_cursor_move_x = 0; + uint8_t map_cursor_move_y = 0; + const int map_cursor_move_duration = 50; + + for(size_t i = 0; i < 5; i++){ + if (mmo_name == MMO_NAMES()[i]){ + switch (i){ + case 0: + region = MapRegion::FIELDLANDS; + location = TravelLocations::instance().Fieldlands_Fieldlands; + camp = Camp::FIELDLANDS_FIELDLANDS; + map_cursor_move_x = 128; + map_cursor_move_y = 0; + break; + case 1: + region = MapRegion::MIRELANDS; + location = TravelLocations::instance().Mirelands_Mirelands; + camp = Camp::MIRELANDS_MIRELANDS; + map_cursor_move_x = 0; + map_cursor_move_y = 128; + break; + case 2: + region = MapRegion::COASTLANDS; + location = TravelLocations::instance().Coastlands_Beachside; + camp = Camp::COASTLANDS_BEACHSIDE; + map_cursor_move_x = 0; + map_cursor_move_y = 128; + break; + case 3: + region = MapRegion::HIGHLANDS; + location = TravelLocations::instance().Highlands_Highlands; + camp = Camp::HIGHLANDS_HIGHLANDS; + map_cursor_move_x = 128; + map_cursor_move_y = 255; + break; + case 4: + region = MapRegion::ICELANDS; + location = TravelLocations::instance().Icelands_Snowfields; + camp = Camp::ICELANDS_SNOWFIELDS; + map_cursor_move_x = 128; + map_cursor_move_y = 255; + break; + } + } + } + if (region == MapRegion::NONE){ + throw InternalProgramError(&env.console.logger(), PA_CURRENT_FUNCTION, "No MMO region name found."); + } + + env.log("Go to " + std::string(MAP_REGION_NAMES[int(region)]) + " to check MMO."); + goto_camp_from_jubilife(env, env.console, context, location); + + // Open map + pbf_press_button(context, BUTTON_MINUS, 50, 100); + context.wait_for_all_requests(); + + // Take a photo of the map before + VideoSnapshot question_mark_image = env.console.video().snapshot(); + + // Fix zoom level: + const int zoom_level = read_map_zoom_level(question_mark_image); + if (zoom_level < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Canot read map zoom level.", + env.console + ); + } + if (zoom_level == 0){ + pbf_press_button(context, BUTTON_ZR, 50, 50); + context.wait_for_all_requests(); + question_mark_image = env.console.video().snapshot(); + }else if (zoom_level == 2){ + pbf_press_button(context, BUTTON_ZL, 50, 50); + context.wait_for_all_requests(); + question_mark_image = env.console.video().snapshot(); + } + + // Move cursor away so that it does not show a text box that occludes MMO sprites. + pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); + context.wait_for_all_requests(); + + // Fix Missions & Requests tab: + if (is_map_mission_tab_raised(question_mark_image)){ + pbf_press_button(context, BUTTON_R, 50, 100); + context.wait_for_all_requests(); + question_mark_image = env.console.video().snapshot(); + } + + // Now detect question marks: + MMOQuestionMarkDetector question_mark_detector(env.logger()); + + const auto quest_results = question_mark_detector.detect_MMOs_on_region_map(question_mark_image); + env.log("Detected MMO question marks:"); + for(const auto& box : quest_results){ + std::ostringstream os; + os << "- " << box.center_x() << ", " << box.center_y() << " " << box.width() << " x " << box.height(); + env.log(os.str()); + } + + // Clean the detected boxes, make them square. + std::vector new_boxes; + for (size_t i = 0; i < quest_results.size(); i++){ + const auto& box = quest_results[i]; + + pxint_t radius = (pxint_t)((box.width() + box.height()) / 4 + 0.5); + pxint_t center_x = (pxint_t)box.center_x(); + pxint_t center_y = (pxint_t)box.center_y(); + auto new_box = ImagePixelBox(center_x - radius, center_y - radius, center_x + radius, center_y + radius); + new_boxes.push_back(new_box); + } + + // Leave map view, back to overworld + pbf_press_button(context, BUTTON_B, 20, 50); + + // Now go to Mai to see the reviewed map + goto_Mai_from_camp(env.logger(), context, camp); + + pbf_mash_button(context, BUTTON_A, 350); + context.wait_for_all_requests(); + + // Wait for the last dialog box before the MMO pokemon sprites are revealed. + { + EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); + int ret = wait_until(env.console, context, std::chrono::seconds(10), {{event_dialog_detector}}); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Dialog box not detected when waiting for MMO map.", + env.console + ); + } + } + pbf_press_button(context, BUTTON_B, 50, 50); + + while (true){ + EventDialogDetector event_dialog_detector(env.logger(), env.console.overlay(), true); + MapDetector map_detector; + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + {event_dialog_detector, map_detector} + ); + switch (ret){ + case 0: + env.console.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 1: + env.console.log("Found revealed map thanks to Munchlax!"); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after talking to Mai.", + env.console + ); + } + break; + } + +#if 0 + MapDetector map_detector; + ret = wait_until(env.console, context, std::chrono::seconds(5), {{map_detector}}); + if (ret < 0){ + OperationFailedException::fire( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Map not detected after talking to Mai.", + true + ); + } + env.console.log("Found revealed map thanks to Munchlax!"); +#endif + + VideoOverlaySet mmo_sprites_overlay(env.console); + for (size_t i = 0; i < new_boxes.size(); i++){ + mmo_sprites_overlay.add(COLOR_BLUE, pixelbox_to_floatbox(question_mark_image, new_boxes[i])); + } + + // Move cursor away so that it does not show a text box that occludes MMO sprites. + pbf_move_left_joystick(context, map_cursor_move_x, map_cursor_move_y, map_cursor_move_duration, 30); + context.wait_for_all_requests(); + + std::set found; + + // Check MMO results: + std::vector sprites; + VideoSnapshot sprites_screen = env.console.video().snapshot(); + for (size_t i = 0; i < new_boxes.size(); i++){ + auto result = match_sprite_on_map(env.logger(), sprites_screen, new_boxes[i], region, debug_mode); + env.console.log("Found MMO sprite " + result.slug); + num_mmo_pokemon_found++; + + sprites.push_back(result.slug); + if (desired_MMOs.find(result.slug) != desired_MMOs.end()){ + found.insert(result.slug); + } + } + + // Check star MMO results: + std::vector star_boxes; + for (size_t i = 0; i < new_boxes.size(); i++){ + const auto& sprite_box = new_boxes[i]; + pxint_t radius = (pxint_t)sprite_box.width() / 2; + pxint_t center_x = (pxint_t)sprite_box.center_x(); + pxint_t center_y = (pxint_t)sprite_box.center_y(); + ImagePixelBox star_box( + center_x + radius/10, + center_y - radius*16/10, + center_x + radius * 5/4, + center_y + ); + star_boxes.push_back(std::move(star_box)); + } + + MMOSpriteStarSymbolDetector star_detector(sprites_screen, star_boxes); + + env.log("Detect star symbols..."); + wait_until(env.console, context, std::chrono::seconds(5), {{star_detector}}); + for (size_t i = 0; i < new_boxes.size(); i++){ + std::ostringstream os; + os << "- " << sprites[i] << " box [" << star_boxes[i].min_x << ", " << star_boxes[i].min_y + << star_boxes[i].max_x << ", " << star_boxes[i].max_y << "]" + << " motion: " << star_detector.animation_value(i) + << " color: " << star_detector.symbol_color(i); + if (star_detector.is_star(i)){ + num_star_mmo_found++; + os << ", has star"; + if (desired_star_MMOs.find(sprites[i]) != desired_star_MMOs.end()){ + found.insert(sprites[i]); + } + } + env.log(os.str()); + } + return found; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h index f7367d7c17..29f6666a48 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_MMORoutines.h @@ -1,52 +1,52 @@ -/* Pokemon LA MMO Routines - * - * Functions to run MMO related tasks - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - -class SingleSwitchProgramEnvironment; - -namespace PokemonLA{ - -// The name of each MMO event happening at each region. Their slugs are: -// - "fieldlands-mmo" -// - "mirelands-mmo" -// - "coastlands-mmo" -// - "highlands-mmo" -// - "icelands-mmo" -const std::vector& MMO_NAMES(); - - -// After we find an MMO on map specified by `mmo_name`, -// start from Jubilife Village gate, with camera facing towards the village, run towards the gate -// and travel to the region with that MMO. Go to Mai to show all MMO pokemon on map and read their -// sprites and star symbols. -// The function returns when the map opened by Mai is shown with all pokemon revealed. -// Return true if an MMO pokemon matches slugs in `desired_MMOs`, or if an MMO pokemon with a star -// matches slugs in `desired_star_MMOs`. -// - mmo_name: MMO event slug, e.g. "fieldlands-mmo" -// - num_mmo_found: update this value by adding how many MMO pokemon found during this function. -// - num_star_mmo_found: update this value by adding how many MMO pokemon with star symbol found. -std::set enter_region_and_read_MMO( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::string& mmo_name, - const std::set& desired_MMOs, - const std::set& desired_star_MMOs, - bool debug, - int& num_mmo_found, - int& num_star_mmo_found -); - - -} -} +/* Pokemon LA MMO Routines + * + * Functions to run MMO related tasks + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + +class SingleSwitchProgramEnvironment; + +namespace PokemonLA{ + +// The name of each MMO event happening at each region. Their slugs are: +// - "fieldlands-mmo" +// - "mirelands-mmo" +// - "coastlands-mmo" +// - "highlands-mmo" +// - "icelands-mmo" +const std::vector& MMO_NAMES(); + + +// After we find an MMO on map specified by `mmo_name`, +// start from Jubilife Village gate, with camera facing towards the village, run towards the gate +// and travel to the region with that MMO. Go to Mai to show all MMO pokemon on map and read their +// sprites and star symbols. +// The function returns when the map opened by Mai is shown with all pokemon revealed. +// Return true if an MMO pokemon matches slugs in `desired_MMOs`, or if an MMO pokemon with a star +// matches slugs in `desired_star_MMOs`. +// - mmo_name: MMO event slug, e.g. "fieldlands-mmo" +// - num_mmo_found: update this value by adding how many MMO pokemon found during this function. +// - num_star_mmo_found: update this value by adding how many MMO pokemon with star symbol found. +std::set enter_region_and_read_MMO( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::string& mmo_name, + const std::set& desired_MMOs, + const std::set& desired_star_MMOs, + bool debug, + int& num_mmo_found, + int& num_star_mmo_found +); + + +} +} } \ No newline at end of file diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.cpp index 147b373dc2..d68861b635 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.cpp @@ -1,616 +1,616 @@ -/* Outbreak Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_GameSave.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA/Resources/PokemonLA_AvailablePokemon.h" -#include "PokemonLA/Resources/PokemonLA_PokemonSprites.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" -#include "PokemonLA_MMORoutines.h" -#include "PokemonLA_OutbreakFinder.h" - - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -StringSelectDatabase make_mo_database(){ - const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); - const std::vector& slugs = HISUI_OUTBREAK_SLUGS(); - - static const ImageRGB32 mmo_sprite(RESOURCE_PATH() + "PokemonLA/MMOQuestionMark-Template.png"); - - StringSelectDatabase ret; - ret.add_entry(StringSelectEntry("fieldlands-mmo", "Fieldlands MMO", mmo_sprite)); - ret.add_entry(StringSelectEntry("mirelands-mmo", "Mirelands MMO", mmo_sprite)); - ret.add_entry(StringSelectEntry("coastlands-mmo", "Coastlands MMO", mmo_sprite)); - ret.add_entry(StringSelectEntry("highlands-mmo", "Highlands MMO", mmo_sprite)); - ret.add_entry(StringSelectEntry("icelands-mmo", "Icelands MMO", mmo_sprite)); - for (const std::string& slug : slugs){ - const PokemonNames& name = get_pokemon_name(slug); - const SpriteDatabase::Sprite& sprite = sprites.get_throw(slug); - ret.add_entry(StringSelectEntry( - slug, name.display_name(), - sprite.icon - )); - } - return ret; -} -const StringSelectDatabase& MO_DATABASE(){ - static const StringSelectDatabase database = make_mo_database(); - return database; -} - -StringSelectDatabase make_mmo_database(){ - const SpriteDatabase& sprites = ALL_MMO_SPRITES(); - const std::vector& slugs = MMO_FIRST_WAVE_SPRITE_SLUGS(); - std::vector displays = load_pokemon_slug_json_list("PokemonLA/MMOFirstWaveSpriteNameDisplay.json"); - - if (slugs.size() != displays.size()){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Name and slug lists are not the same size.", - "PokemonLA/MMOFirstWaveSpriteNameDisplay.json" - ); - } - - StringSelectDatabase ret; - for (size_t c = 0; c < displays.size(); c++){ - ret.add_entry(StringSelectEntry( - slugs[c], std::move(displays[c]), - sprites.get_throw(slugs[c]).icon - )); - } - return ret; -} -const StringSelectDatabase& MMO_DATABASE(){ - static const StringSelectDatabase database = make_mmo_database(); - return database; -} - - -OutbreakFinder_Descriptor::OutbreakFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:OutbreakFinder", - STRING_POKEMON + " LA", "Outbreak Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/OutbreakFinder.md", - "Search for an outbreak for a specific " + STRING_POKEMON, - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class OutbreakFinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : checks(m_stats["Checks"]) - , errors(m_stats["Errors"]) - , outbreaks(m_stats["Outbreaks"]) - , mmos(m_stats["MMOs"]) - , mmo_pokemon(m_stats["MMO Pokemon"]) - , stars(m_stats["Stars"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back("Checks"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Outbreaks"); - m_display_order.emplace_back("MMOs"); - m_display_order.emplace_back("MMO Pokemon"); - m_display_order.emplace_back("Stars"); - m_display_order.emplace_back("Matches", HIDDEN_IF_ZERO); - } - - std::atomic& checks; - std::atomic& errors; - std::atomic& outbreaks; - std::atomic& mmos; - std::atomic& mmo_pokemon; - std::atomic& stars; // MMO star symbols - std::atomic& matches; -}; -std::unique_ptr OutbreakFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - - -OutbreakFinder::OutbreakFinder() - : GO_HOME_WHEN_DONE(false) - , RESET_GAME_AND_CONTINUE_SEARCHING( - "Reset Game and Skip Outbreak at Start
If the last outbreak found by the program does not yield what you want, check " - "this option to let the program reset the game and skip the ongoing outbreaks at start, before continuing the search.
" - "Note: you must have saved at Jubilife Village front gate beforehand.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , LANGUAGE( - "Game Language:", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , DESIRED_MO_SLUGS( - "Desired Outbreak " + STRING_POKEMON + ":
Stop when anything on this list is found.", - STRING_POKEMON, MO_DATABASE(), "cherubi" - ) - , DESIRED_MMO_SLUGS( - "Desired first MMO wave " + STRING_POKEMON + ":
Stop when anything on this list is found.", - STRING_POKEMON, MMO_DATABASE(), "rowlet" - ) - , DESIRED_STAR_MMO_SLUGS( - "Desired first MMO wave " + STRING_POKEMON + " with shiny symbols:
Stop when anything on this list is found.", - STRING_POKEMON, MMO_DATABASE(), "rowlet" - ) - , DEBUG_MODE( - "Debug Mode:
Save MMO Sprite to debug folder.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_MATCHED( - "Match Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &NOTIFICATION_MATCHED, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(RESET_GAME_AND_CONTINUE_SEARCHING); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(DESIRED_MO_SLUGS); - PA_ADD_OPTION(DESIRED_MMO_SLUGS); - PA_ADD_OPTION(DESIRED_STAR_MMO_SLUGS); - PA_ADD_OPTION(NOTIFICATIONS); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(DEBUG_MODE); - } -} - - -std::set OutbreakFinder::read_travel_map_outbreaks( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::set& desired_events -){ - OutbreakFinder_Descriptor::Stats& stats = env.current_stats(); - - VideoOverlaySet overlays(env.console); - - MapRegion start_region = MapRegion::NONE; - - MapRegion current_region = detect_selected_region(env.console, context); - if (current_region == MapRegion::NONE){ - env.console.log("Unable to detect selected region.", COLOR_RED); - return std::set(); - } - - OutbreakReader reader(env.console, LANGUAGE, env.console); - reader.make_overlays(overlays); - - MMOQuestionMarkDetector question_mark_detector(env.logger()); -// VideoOverlaySet mmo_overlay_set(env.console); - std::array mmo_appears = question_mark_detector.detect_MMO_on_hisui_map(env.console.video().snapshot()); - add_hisui_MMO_detection_to_overlay(mmo_appears, overlays); - - // If the current region is a wild area, the yellow cursor may overlap with the MMO question marker, causing - // wrong detection. So we have to check it's location again by moving the cursor to the next location - if (current_region != MapRegion::JUBILIFE && current_region != MapRegion::RETREAT){ - // MapRegion starts with None and JUBILIFE. Skip those two, so -2. - size_t current_wild_area_index = (int)current_region - 2; - pbf_press_dpad(context, DPAD_RIGHT, 20, 40); - context.wait_for_all_requests(); - auto new_mmo_read = question_mark_detector.detect_MMO_on_hisui_map(env.console.video().snapshot()); - mmo_appears[current_wild_area_index] = new_mmo_read[current_wild_area_index]; - if (new_mmo_read[current_wild_area_index]){ - add_hisui_MMO_detection_to_overlay(mmo_appears, overlays); - } - // now mmo_appears should contain correct detection of MMO question marks. - } - - // reset current_region to start the looping of checking each wild area's outbreak pokemon name: - current_region = MapRegion::NONE; - - std::set found; - - // First, check whether we match MMOs: - const auto& mmo_names = MMO_NAMES(); - for (int i = 0; i < 5; i++){ - if (mmo_appears[i]){ - auto iter = desired_events.find(mmo_names[i]); - if (iter != desired_events.end()){ - env.console.log("Found a match!", COLOR_BLUE); - found.insert(mmo_names[i]); - } - stats.mmos++; - } - } - env.update_stats(); - - // Next, go to each region, read the outbreak names: - while (true){ - current_region = detect_selected_region(env.console, context); - if (current_region == MapRegion::NONE){ - env.console.log("Unable to detect selected region.", COLOR_RED); - return std::set(); - } - if (start_region == MapRegion::NONE){ - start_region = current_region; - }else if (start_region == current_region){ - // We've visited all the regions. Exit the loop. - break; - } - - if (current_region != MapRegion::JUBILIFE && current_region != MapRegion::RETREAT){ - // MapRegion starts with None and JUBILIFE. Skip those two, so -2. - const int wild_region_index = (int)current_region - 2; - if (mmo_appears[wild_region_index]){ - env.log(std::string(MAP_REGION_NAMES[(int)current_region]) + " have MMO.", COLOR_ORANGE); - }else{ - OCR::StringMatchResult result = reader.read(env.console.video().snapshot()); - if (!result.results.empty()){ - stats.outbreaks++; - } - for (const auto& item : result.results){ - auto iter = desired_events.find(item.second.token); - if (iter != desired_events.end()){ - env.console.log("Found a match!", COLOR_BLUE); - found.insert(item.second.token); - } - } - } - } - - pbf_press_dpad(context, DPAD_RIGHT, 20, 40); - context.wait_for_all_requests(); - } - - stats.checks++; - - return found; -} - - -void OutbreakFinder::goto_region_and_return(SingleSwitchProgramEnvironment& env, ProControllerContext& context, - bool inside_travel_map -){ - env.log("Go to a random region and back to refresh outbreaks..."); - env.console.overlay().add_log("Refresh outbreaks"); - OutbreakFinder_Descriptor::Stats& stats = env.current_stats(); - - if (inside_travel_map == false){ - // Move to guard to open map - open_travel_map_from_jubilife(env, env.console, context); - context.wait_for(std::chrono::milliseconds(500)); - } - - MapRegion current_region = MapRegion::NONE; - for (size_t c = 0; c < 10; c++){ - current_region = detect_selected_region(env.console, context); - if (is_wild_land(current_region)){ - break; - } - - if (current_region == MapRegion::JUBILIFE){ - // Move to fieldlands - pbf_press_dpad(context, DPAD_RIGHT, 20, 40); - }else if (current_region == MapRegion::RETREAT){ - // Move to icelands - pbf_press_dpad(context, DPAD_LEFT, 20, 40); - }else{ - // Cannot read current region. Try move to another region - pbf_press_dpad(context, DPAD_RIGHT, 20, 40); - } - context.wait_for_all_requests(); - } - if (is_wild_land(current_region) == false){ - dump_image(env.console.logger(), env.program_info(), "FindRegion", env.console.video().snapshot()); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find a wild land.", - env.console - ); - } - - mash_A_to_change_region(env, env.console, context); - - Camp camp = Camp::FIELDLANDS_FIELDLANDS; - switch (current_region){ - case MapRegion::FIELDLANDS: - camp = Camp::FIELDLANDS_FIELDLANDS; - break; - case MapRegion::MIRELANDS: - camp = Camp::MIRELANDS_MIRELANDS; - break; - case MapRegion::COASTLANDS: - camp = Camp::COASTLANDS_BEACHSIDE; - break; - case MapRegion::HIGHLANDS: - camp = Camp::HIGHLANDS_HIGHLANDS; - break; - case MapRegion::ICELANDS: - camp = Camp::ICELANDS_SNOWFIELDS; - break; - default: - throw InternalProgramError(&env.console.logger(), PA_CURRENT_FUNCTION, "Invalid region."); - } - goto_professor(env.console, context, camp); - - while (true){ - context.wait_for_all_requests(); - ButtonDetector button_detector( - env.console, env.console, - ButtonType::ButtonA, ImageFloatBox(0.50, 0.50, 0.30, 0.30), - std::chrono::milliseconds(200), true - ); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, 125); - } - }, - {{button_detector}} - ); - if (ret >= 0){ - context.wait_for(std::chrono::milliseconds(500)); - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - break; - } - env.console.log("Did not detect option to return to Jubilife.", COLOR_RED); - pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); - stats.errors++; - } - - mash_A_to_change_region(env, env.console, context); -} - - -std::vector OutbreakFinder::run_iteration( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::set& desired_hisui_map_events, - const std::set& desired_outbreaks, - const std::set& desired_MMOs, - const std::set& desired_star_MMOs -){ - OutbreakFinder_Descriptor::Stats& stats = env.current_stats(); - - // Enter map. - try{ - open_travel_map_from_jubilife(env, env.console, context); - }catch (OperationFailedException&){ - stats.errors++; - throw; - } - context.wait_for(std::chrono::milliseconds(500)); - - // found_hisui_map_events: desired pokemon names or MMO names - std::set found_hisui_map_events; - found_hisui_map_events = read_travel_map_outbreaks(env, context, desired_hisui_map_events); - - bool inside_travel_map = true; - if (found_hisui_map_events.size() > 0){ - // Check if we found any Massive Outbreak pokemon (including MMO symbol targets) - { - std::vector desired_outbreaks_found; - for(const auto& found : found_hisui_map_events){ - if (desired_outbreaks.find(found) != desired_outbreaks.end()){ - desired_outbreaks_found.push_back(found); - } - } - if (desired_outbreaks_found.size() > 0){ - stats.matches += desired_outbreaks_found.size(); - std::ostringstream os; - os << "Found following desired outbreak" << (desired_outbreaks_found.size() > 1 ? "s: " : ": "); - for(const auto& outbreak: desired_outbreaks_found){ - os << outbreak << ", "; - env.console.overlay().add_log("Found " + outbreak, COLOR_GREEN); - } - env.log(os.str(), COLOR_GREEN); - - return desired_outbreaks_found; - } - - env.log("No desired outbreak."); - } - - // What we found is MMO symbols for MMO pokemon. - // Go into those regions to check MMO details. - - // Cancel map view - inside_travel_map = false; - pbf_press_button(context, BUTTON_B, 50, 50); - // Leave the guard. - pbf_move_left_joystick(context, 128, 0, 100, 50); - // Checking MMO costs Aguav Berries. - // To not waste them, save here so that we can reset to get berries back. - save_game_from_overworld(env, env.console, context); - - for(const auto& mmo_name: found_hisui_map_events){ - int num_new_mmo_pokemon_found = 0; - int num_new_star_mmo_found = 0; - std::set found_pokemon = enter_region_and_read_MMO( - env, context, mmo_name, desired_MMOs, desired_star_MMOs, DEBUG_MODE, - num_new_mmo_pokemon_found, num_new_star_mmo_found); - stats.mmo_pokemon += num_new_mmo_pokemon_found; - stats.stars += num_new_star_mmo_found; - env.update_stats(); - - if (found_pokemon.size() > 0){ - stats.matches += found_pokemon.size(); - std::ostringstream os; - os << "Found desired MMO pokemon (including desired MMO pokemon with star symbols): "; - for (const auto& pokemon : found_pokemon){ - os << pokemon << ", "; - env.console.overlay().add_log("Found " + pokemon, COLOR_GREEN); - } - env.log(os.str(), COLOR_GREEN); - return std::vector(found_pokemon.begin(), found_pokemon.end()); - } - - env.log("No target MMO sprite found. Reset game..."); - env.console.overlay().add_log("No target MMO"); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - - // Go to an arbitrary region and return to refresh outbreaks. - goto_region_and_return(env, context, inside_travel_map); - - return std::vector(); -} - - -std::set OutbreakFinder::to_set(const StringSelectTableOption& option){ - std::set ret; - for (std::string& slug : option.all_slugs()){ - ret.insert(std::move(slug)); - } - return ret; -} - -void OutbreakFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // press a random button to let Switch register the wired controller - pbf_press_button(context, BUTTON_ZL, 10ms, 30ms); - - if (RESET_GAME_AND_CONTINUE_SEARCHING){ - // the outbreak found by the last program run did not yield what the user wants. - // so we reset the game now and skip the ongoing outbreaks - env.log("Reset game and skip ongoing outbreaks"); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - - // Go to region and return. - bool inside_travel_map = false; - goto_region_and_return(env, context, inside_travel_map); - } - - std::set desired_outbreaks = to_set(DESIRED_MO_SLUGS); - std::set desired_MMO_pokemon = to_set(DESIRED_MMO_SLUGS); - std::set desired_star_MMO_pokemon = to_set(DESIRED_STAR_MMO_SLUGS); - { - std::ostringstream os; - os << "Desired outbreaks: "; - std::copy(desired_outbreaks.begin(), desired_outbreaks.end(), std::ostream_iterator(os, ", ")); - env.log(os.str()); - os = std::ostringstream(); - os << "Desired first-wave MMO pokemon: "; - std::copy(desired_MMO_pokemon.begin(), desired_MMO_pokemon.end(), std::ostream_iterator(os, ", ")); - env.log(os.str()); - os = std::ostringstream(); - os << "Desired MMO pokemon with star: "; - std::copy(desired_star_MMO_pokemon.begin(), desired_star_MMO_pokemon.end(), std::ostream_iterator(os, ", ")); - env.log(os.str()); - } - - // desired_hisui_map_events: the slugs of travel map event. This includes - // - Massive Outbreak pokemon - // - Question mark MMO event at any region - std::set desired_hisui_map_events = desired_outbreaks; - - // If the user sets MMO pokemon, then we should add the MMO map events that may spawn those MMO pokemon to - // `desired_hisui_map_events`. - - // MMO_targets: MMO map event slug (e.g. "fieldlands-mmo") -> how many desired MMO pokemon can spawn on this map - std::map MMO_targets; - // Check if each MMO map event may spawn desired MMO pokemon: - for(size_t i = 0; i < 5; i++){ - for(const std::string& sprite_slug: MMO_FIRST_WAVE_REGION_SPRITE_SLUGS()[i]){ - if (desired_MMO_pokemon.find(sprite_slug) != desired_MMO_pokemon.end() - || desired_star_MMO_pokemon.find(sprite_slug) != desired_star_MMO_pokemon.end() - ){ - MMO_targets[MMO_NAMES()[i]]++; - } - } - } - - std::ostringstream os; - os << "User requires MMO pokemon. Need to visit (\"map MMO name\", \"how many desired MMO pokemon on the map\"): "; - for(const auto& p : MMO_targets){ - os << "(" << p.first << ", " << p.second << ") "; - } - env.log(os.str()); - - // Add MMO map event targets (e.g. "fieldlands-mmo") derived from user selected MMO pokemon to - // `desired_hisui_map_events`. - for(const auto& p : MMO_targets){ - desired_hisui_map_events.insert(p.first); - } - - std::vector found_outbreaks; - while (true){ - found_outbreaks = run_iteration( - env, context, desired_hisui_map_events, desired_outbreaks, desired_MMO_pokemon, - desired_star_MMO_pokemon); - if (found_outbreaks.size() > 0) - { - break; - } - } - - env.update_stats(); - - os.str(""); // clear ostringstream - os << "Found "; - for (size_t i = 0; i < found_outbreaks.size(); i++){ - os << found_outbreaks[i]; - if (i + 1 != found_outbreaks.size()){ - os << ", "; - } - } - send_program_finished_notification( - env, NOTIFICATION_MATCHED, - os.str(), - env.console.video().snapshot() - ); - - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - -} -} -} +/* Outbreak Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_OutbreakReader.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_GameSave.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA/Resources/PokemonLA_AvailablePokemon.h" +#include "PokemonLA/Resources/PokemonLA_PokemonSprites.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" +#include "PokemonLA_MMORoutines.h" +#include "PokemonLA_OutbreakFinder.h" + + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +StringSelectDatabase make_mo_database(){ + const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); + const std::vector& slugs = HISUI_OUTBREAK_SLUGS(); + + static const ImageRGB32 mmo_sprite(RESOURCE_PATH() + "PokemonLA/MMOQuestionMark-Template.png"); + + StringSelectDatabase ret; + ret.add_entry(StringSelectEntry("fieldlands-mmo", "Fieldlands MMO", mmo_sprite)); + ret.add_entry(StringSelectEntry("mirelands-mmo", "Mirelands MMO", mmo_sprite)); + ret.add_entry(StringSelectEntry("coastlands-mmo", "Coastlands MMO", mmo_sprite)); + ret.add_entry(StringSelectEntry("highlands-mmo", "Highlands MMO", mmo_sprite)); + ret.add_entry(StringSelectEntry("icelands-mmo", "Icelands MMO", mmo_sprite)); + for (const std::string& slug : slugs){ + const PokemonNames& name = get_pokemon_name(slug); + const SpriteDatabase::Sprite& sprite = sprites.get_throw(slug); + ret.add_entry(StringSelectEntry( + slug, name.display_name(), + sprite.icon + )); + } + return ret; +} +const StringSelectDatabase& MO_DATABASE(){ + static const StringSelectDatabase database = make_mo_database(); + return database; +} + +StringSelectDatabase make_mmo_database(){ + const SpriteDatabase& sprites = ALL_MMO_SPRITES(); + const std::vector& slugs = MMO_FIRST_WAVE_SPRITE_SLUGS(); + std::vector displays = load_pokemon_slug_json_list("PokemonLA/MMOFirstWaveSpriteNameDisplay.json"); + + if (slugs.size() != displays.size()){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Name and slug lists are not the same size.", + "PokemonLA/MMOFirstWaveSpriteNameDisplay.json" + ); + } + + StringSelectDatabase ret; + for (size_t c = 0; c < displays.size(); c++){ + ret.add_entry(StringSelectEntry( + slugs[c], std::move(displays[c]), + sprites.get_throw(slugs[c]).icon + )); + } + return ret; +} +const StringSelectDatabase& MMO_DATABASE(){ + static const StringSelectDatabase database = make_mmo_database(); + return database; +} + + +OutbreakFinder_Descriptor::OutbreakFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:OutbreakFinder", + STRING_POKEMON + " LA", "Outbreak Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/OutbreakFinder.md", + "Search for an outbreak for a specific " + STRING_POKEMON, + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class OutbreakFinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : checks(m_stats["Checks"]) + , errors(m_stats["Errors"]) + , outbreaks(m_stats["Outbreaks"]) + , mmos(m_stats["MMOs"]) + , mmo_pokemon(m_stats["MMO Pokemon"]) + , stars(m_stats["Stars"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back("Checks"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Outbreaks"); + m_display_order.emplace_back("MMOs"); + m_display_order.emplace_back("MMO Pokemon"); + m_display_order.emplace_back("Stars"); + m_display_order.emplace_back("Matches", HIDDEN_IF_ZERO); + } + + std::atomic& checks; + std::atomic& errors; + std::atomic& outbreaks; + std::atomic& mmos; + std::atomic& mmo_pokemon; + std::atomic& stars; // MMO star symbols + std::atomic& matches; +}; +std::unique_ptr OutbreakFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + + +OutbreakFinder::OutbreakFinder() + : GO_HOME_WHEN_DONE(false) + , RESET_GAME_AND_CONTINUE_SEARCHING( + "Reset Game and Skip Outbreak at Start
If the last outbreak found by the program does not yield what you want, check " + "this option to let the program reset the game and skip the ongoing outbreaks at start, before continuing the search.
" + "Note: you must have saved at Jubilife Village front gate beforehand.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , LANGUAGE( + "Game Language:", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , DESIRED_MO_SLUGS( + "Desired Outbreak " + STRING_POKEMON + ":
Stop when anything on this list is found.", + STRING_POKEMON, MO_DATABASE(), "cherubi" + ) + , DESIRED_MMO_SLUGS( + "Desired first MMO wave " + STRING_POKEMON + ":
Stop when anything on this list is found.", + STRING_POKEMON, MMO_DATABASE(), "rowlet" + ) + , DESIRED_STAR_MMO_SLUGS( + "Desired first MMO wave " + STRING_POKEMON + " with shiny symbols:
Stop when anything on this list is found.", + STRING_POKEMON, MMO_DATABASE(), "rowlet" + ) + , DEBUG_MODE( + "Debug Mode:
Save MMO Sprite to debug folder.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_MATCHED( + "Match Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &NOTIFICATION_MATCHED, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(RESET_GAME_AND_CONTINUE_SEARCHING); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(DESIRED_MO_SLUGS); + PA_ADD_OPTION(DESIRED_MMO_SLUGS); + PA_ADD_OPTION(DESIRED_STAR_MMO_SLUGS); + PA_ADD_OPTION(NOTIFICATIONS); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(DEBUG_MODE); + } +} + + +std::set OutbreakFinder::read_travel_map_outbreaks( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::set& desired_events +){ + OutbreakFinder_Descriptor::Stats& stats = env.current_stats(); + + VideoOverlaySet overlays(env.console); + + MapRegion start_region = MapRegion::NONE; + + MapRegion current_region = detect_selected_region(env.console, context); + if (current_region == MapRegion::NONE){ + env.console.log("Unable to detect selected region.", COLOR_RED); + return std::set(); + } + + OutbreakReader reader(env.console, LANGUAGE, env.console); + reader.make_overlays(overlays); + + MMOQuestionMarkDetector question_mark_detector(env.logger()); +// VideoOverlaySet mmo_overlay_set(env.console); + std::array mmo_appears = question_mark_detector.detect_MMO_on_hisui_map(env.console.video().snapshot()); + add_hisui_MMO_detection_to_overlay(mmo_appears, overlays); + + // If the current region is a wild area, the yellow cursor may overlap with the MMO question marker, causing + // wrong detection. So we have to check it's location again by moving the cursor to the next location + if (current_region != MapRegion::JUBILIFE && current_region != MapRegion::RETREAT){ + // MapRegion starts with None and JUBILIFE. Skip those two, so -2. + size_t current_wild_area_index = (int)current_region - 2; + pbf_press_dpad(context, DPAD_RIGHT, 20, 40); + context.wait_for_all_requests(); + auto new_mmo_read = question_mark_detector.detect_MMO_on_hisui_map(env.console.video().snapshot()); + mmo_appears[current_wild_area_index] = new_mmo_read[current_wild_area_index]; + if (new_mmo_read[current_wild_area_index]){ + add_hisui_MMO_detection_to_overlay(mmo_appears, overlays); + } + // now mmo_appears should contain correct detection of MMO question marks. + } + + // reset current_region to start the looping of checking each wild area's outbreak pokemon name: + current_region = MapRegion::NONE; + + std::set found; + + // First, check whether we match MMOs: + const auto& mmo_names = MMO_NAMES(); + for (int i = 0; i < 5; i++){ + if (mmo_appears[i]){ + auto iter = desired_events.find(mmo_names[i]); + if (iter != desired_events.end()){ + env.console.log("Found a match!", COLOR_BLUE); + found.insert(mmo_names[i]); + } + stats.mmos++; + } + } + env.update_stats(); + + // Next, go to each region, read the outbreak names: + while (true){ + current_region = detect_selected_region(env.console, context); + if (current_region == MapRegion::NONE){ + env.console.log("Unable to detect selected region.", COLOR_RED); + return std::set(); + } + if (start_region == MapRegion::NONE){ + start_region = current_region; + }else if (start_region == current_region){ + // We've visited all the regions. Exit the loop. + break; + } + + if (current_region != MapRegion::JUBILIFE && current_region != MapRegion::RETREAT){ + // MapRegion starts with None and JUBILIFE. Skip those two, so -2. + const int wild_region_index = (int)current_region - 2; + if (mmo_appears[wild_region_index]){ + env.log(std::string(MAP_REGION_NAMES[(int)current_region]) + " have MMO.", COLOR_ORANGE); + }else{ + OCR::StringMatchResult result = reader.read(env.console.video().snapshot()); + if (!result.results.empty()){ + stats.outbreaks++; + } + for (const auto& item : result.results){ + auto iter = desired_events.find(item.second.token); + if (iter != desired_events.end()){ + env.console.log("Found a match!", COLOR_BLUE); + found.insert(item.second.token); + } + } + } + } + + pbf_press_dpad(context, DPAD_RIGHT, 20, 40); + context.wait_for_all_requests(); + } + + stats.checks++; + + return found; +} + + +void OutbreakFinder::goto_region_and_return(SingleSwitchProgramEnvironment& env, ProControllerContext& context, + bool inside_travel_map +){ + env.log("Go to a random region and back to refresh outbreaks..."); + env.console.overlay().add_log("Refresh outbreaks"); + OutbreakFinder_Descriptor::Stats& stats = env.current_stats(); + + if (inside_travel_map == false){ + // Move to guard to open map + open_travel_map_from_jubilife(env, env.console, context); + context.wait_for(std::chrono::milliseconds(500)); + } + + MapRegion current_region = MapRegion::NONE; + for (size_t c = 0; c < 10; c++){ + current_region = detect_selected_region(env.console, context); + if (is_wild_land(current_region)){ + break; + } + + if (current_region == MapRegion::JUBILIFE){ + // Move to fieldlands + pbf_press_dpad(context, DPAD_RIGHT, 20, 40); + }else if (current_region == MapRegion::RETREAT){ + // Move to icelands + pbf_press_dpad(context, DPAD_LEFT, 20, 40); + }else{ + // Cannot read current region. Try move to another region + pbf_press_dpad(context, DPAD_RIGHT, 20, 40); + } + context.wait_for_all_requests(); + } + if (is_wild_land(current_region) == false){ + dump_image(env.console.logger(), env.program_info(), "FindRegion", env.console.video().snapshot()); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find a wild land.", + env.console + ); + } + + mash_A_to_change_region(env, env.console, context); + + Camp camp = Camp::FIELDLANDS_FIELDLANDS; + switch (current_region){ + case MapRegion::FIELDLANDS: + camp = Camp::FIELDLANDS_FIELDLANDS; + break; + case MapRegion::MIRELANDS: + camp = Camp::MIRELANDS_MIRELANDS; + break; + case MapRegion::COASTLANDS: + camp = Camp::COASTLANDS_BEACHSIDE; + break; + case MapRegion::HIGHLANDS: + camp = Camp::HIGHLANDS_HIGHLANDS; + break; + case MapRegion::ICELANDS: + camp = Camp::ICELANDS_SNOWFIELDS; + break; + default: + throw InternalProgramError(&env.console.logger(), PA_CURRENT_FUNCTION, "Invalid region."); + } + goto_professor(env.console, context, camp); + + while (true){ + context.wait_for_all_requests(); + ButtonDetector button_detector( + env.console, env.console, + ButtonType::ButtonA, ImageFloatBox(0.50, 0.50, 0.30, 0.30), + std::chrono::milliseconds(200), true + ); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, 125); + } + }, + {{button_detector}} + ); + if (ret >= 0){ + context.wait_for(std::chrono::milliseconds(500)); + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + break; + } + env.console.log("Did not detect option to return to Jubilife.", COLOR_RED); + pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); + stats.errors++; + } + + mash_A_to_change_region(env, env.console, context); +} + + +std::vector OutbreakFinder::run_iteration( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::set& desired_hisui_map_events, + const std::set& desired_outbreaks, + const std::set& desired_MMOs, + const std::set& desired_star_MMOs +){ + OutbreakFinder_Descriptor::Stats& stats = env.current_stats(); + + // Enter map. + try{ + open_travel_map_from_jubilife(env, env.console, context); + }catch (OperationFailedException&){ + stats.errors++; + throw; + } + context.wait_for(std::chrono::milliseconds(500)); + + // found_hisui_map_events: desired pokemon names or MMO names + std::set found_hisui_map_events; + found_hisui_map_events = read_travel_map_outbreaks(env, context, desired_hisui_map_events); + + bool inside_travel_map = true; + if (found_hisui_map_events.size() > 0){ + // Check if we found any Massive Outbreak pokemon (including MMO symbol targets) + { + std::vector desired_outbreaks_found; + for(const auto& found : found_hisui_map_events){ + if (desired_outbreaks.find(found) != desired_outbreaks.end()){ + desired_outbreaks_found.push_back(found); + } + } + if (desired_outbreaks_found.size() > 0){ + stats.matches += desired_outbreaks_found.size(); + std::ostringstream os; + os << "Found following desired outbreak" << (desired_outbreaks_found.size() > 1 ? "s: " : ": "); + for(const auto& outbreak: desired_outbreaks_found){ + os << outbreak << ", "; + env.console.overlay().add_log("Found " + outbreak, COLOR_GREEN); + } + env.log(os.str(), COLOR_GREEN); + + return desired_outbreaks_found; + } + + env.log("No desired outbreak."); + } + + // What we found is MMO symbols for MMO pokemon. + // Go into those regions to check MMO details. + + // Cancel map view + inside_travel_map = false; + pbf_press_button(context, BUTTON_B, 50, 50); + // Leave the guard. + pbf_move_left_joystick(context, 128, 0, 100, 50); + // Checking MMO costs Aguav Berries. + // To not waste them, save here so that we can reset to get berries back. + save_game_from_overworld(env, env.console, context); + + for(const auto& mmo_name: found_hisui_map_events){ + int num_new_mmo_pokemon_found = 0; + int num_new_star_mmo_found = 0; + std::set found_pokemon = enter_region_and_read_MMO( + env, context, mmo_name, desired_MMOs, desired_star_MMOs, DEBUG_MODE, + num_new_mmo_pokemon_found, num_new_star_mmo_found); + stats.mmo_pokemon += num_new_mmo_pokemon_found; + stats.stars += num_new_star_mmo_found; + env.update_stats(); + + if (found_pokemon.size() > 0){ + stats.matches += found_pokemon.size(); + std::ostringstream os; + os << "Found desired MMO pokemon (including desired MMO pokemon with star symbols): "; + for (const auto& pokemon : found_pokemon){ + os << pokemon << ", "; + env.console.overlay().add_log("Found " + pokemon, COLOR_GREEN); + } + env.log(os.str(), COLOR_GREEN); + return std::vector(found_pokemon.begin(), found_pokemon.end()); + } + + env.log("No target MMO sprite found. Reset game..."); + env.console.overlay().add_log("No target MMO"); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + + // Go to an arbitrary region and return to refresh outbreaks. + goto_region_and_return(env, context, inside_travel_map); + + return std::vector(); +} + + +std::set OutbreakFinder::to_set(const StringSelectTableOption& option){ + std::set ret; + for (std::string& slug : option.all_slugs()){ + ret.insert(std::move(slug)); + } + return ret; +} + +void OutbreakFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // press a random button to let Switch register the wired controller + pbf_press_button(context, BUTTON_ZL, 10ms, 30ms); + + if (RESET_GAME_AND_CONTINUE_SEARCHING){ + // the outbreak found by the last program run did not yield what the user wants. + // so we reset the game now and skip the ongoing outbreaks + env.log("Reset game and skip ongoing outbreaks"); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + + // Go to region and return. + bool inside_travel_map = false; + goto_region_and_return(env, context, inside_travel_map); + } + + std::set desired_outbreaks = to_set(DESIRED_MO_SLUGS); + std::set desired_MMO_pokemon = to_set(DESIRED_MMO_SLUGS); + std::set desired_star_MMO_pokemon = to_set(DESIRED_STAR_MMO_SLUGS); + { + std::ostringstream os; + os << "Desired outbreaks: "; + std::copy(desired_outbreaks.begin(), desired_outbreaks.end(), std::ostream_iterator(os, ", ")); + env.log(os.str()); + os = std::ostringstream(); + os << "Desired first-wave MMO pokemon: "; + std::copy(desired_MMO_pokemon.begin(), desired_MMO_pokemon.end(), std::ostream_iterator(os, ", ")); + env.log(os.str()); + os = std::ostringstream(); + os << "Desired MMO pokemon with star: "; + std::copy(desired_star_MMO_pokemon.begin(), desired_star_MMO_pokemon.end(), std::ostream_iterator(os, ", ")); + env.log(os.str()); + } + + // desired_hisui_map_events: the slugs of travel map event. This includes + // - Massive Outbreak pokemon + // - Question mark MMO event at any region + std::set desired_hisui_map_events = desired_outbreaks; + + // If the user sets MMO pokemon, then we should add the MMO map events that may spawn those MMO pokemon to + // `desired_hisui_map_events`. + + // MMO_targets: MMO map event slug (e.g. "fieldlands-mmo") -> how many desired MMO pokemon can spawn on this map + std::map MMO_targets; + // Check if each MMO map event may spawn desired MMO pokemon: + for(size_t i = 0; i < 5; i++){ + for(const std::string& sprite_slug: MMO_FIRST_WAVE_REGION_SPRITE_SLUGS()[i]){ + if (desired_MMO_pokemon.find(sprite_slug) != desired_MMO_pokemon.end() + || desired_star_MMO_pokemon.find(sprite_slug) != desired_star_MMO_pokemon.end() + ){ + MMO_targets[MMO_NAMES()[i]]++; + } + } + } + + std::ostringstream os; + os << "User requires MMO pokemon. Need to visit (\"map MMO name\", \"how many desired MMO pokemon on the map\"): "; + for(const auto& p : MMO_targets){ + os << "(" << p.first << ", " << p.second << ") "; + } + env.log(os.str()); + + // Add MMO map event targets (e.g. "fieldlands-mmo") derived from user selected MMO pokemon to + // `desired_hisui_map_events`. + for(const auto& p : MMO_targets){ + desired_hisui_map_events.insert(p.first); + } + + std::vector found_outbreaks; + while (true){ + found_outbreaks = run_iteration( + env, context, desired_hisui_map_events, desired_outbreaks, desired_MMO_pokemon, + desired_star_MMO_pokemon); + if (found_outbreaks.size() > 0) + { + break; + } + } + + env.update_stats(); + + os.str(""); // clear ostringstream + os << "Found "; + for (size_t i = 0; i < found_outbreaks.size(); i++){ + os << found_outbreaks[i]; + if (i + 1 != found_outbreaks.size()){ + os << ", "; + } + } + send_program_finished_notification( + env, NOTIFICATION_MATCHED, + os.str(), + env.console.video().snapshot() + ); + + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.h index 702262e812..7460e5193a 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_OutbreakFinder.h @@ -1,106 +1,106 @@ -/* Outbreak Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_OutbreakFinder_H -#define PokemonAutomation_PokemonLA_OutbreakFinder_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/StringSelectTableOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class OutbreakFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - OutbreakFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class OutbreakFinder : public SingleSwitchProgramInstance{ -public: - OutbreakFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - // Run one iteration of the outbreak finder loop and return any found outbreaks. - // The iteration includes: - // 1. Starting at Jubilife Village gate, go to check the map for outbreaks. - // 2. If found desired outbreaks, stop. - // 3. If need to check MMOs, save in front of gate, then go to each region with MMO and talk to Mai to - // reveal MMO pokemon. Reset if no desired MMO to conserve Aguav Berries. - // 4. If found desired MMO pokemon, stop. - // 5. No desired outbreak in this iteration, go to an arbitrary region and return to village to refresh outbreaks. - // - // - desired_hisui_map_events: desired events happening on the travel map of Hisui when leaving Jubilife Village. - // It contains desired pokemon outbreak names and MMO outbreak names (e.g. "fieldlands-mmo"). If there are - // desired MMO pokemon (including those with star symbols), the MMO outbreaks that may spawn them are also - // included in `desired_hisui_map_events`. - // - desired_outbreaks: desired events happening on the travel map of Hisui when leaving Jubilife Village. - // This includes any user selected outbreak pokemon and user explicitly selected MMO events (e.g. "fieldlands-mmo") - // in DESIRED_MO_SLUGS. - // User selected MMO pokemon (including those with star symbols) do not affect `desired_outbreaks`. - // - desired_MMO_pokemon: user desired MMO pokemon selected by `DESIRED_MMO_SLUGS`. - // User selected MMO pokemon with star symbols, `DESIRED_STAR_MMO_SLUGS` do not affect `desired_MMO_pokemon`. - // - desired_star_MMO_pokemon: user desired MMO pokemon with star symbols. - std::vector run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::set& desired_hisui_map_events, - const std::set& desired_outbreaks, - const std::set& desired_MMO_pokemon, - const std::set& desired_star_MMO_pokemon); - - // Read the travel map from Jublilife village to find any desired pokemon or MMO events. - // Return true if program should stop (match found). - // desired_events: the desired set of pokemon slugs and MMO events. - std::set read_travel_map_outbreaks( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const std::set& desired_events - ); - - // Go to a random wild region and return to refresh outbreaks. - // If `inside_map` is true, the function is called when the game is inside the travel map. - // Otherwise, the function is called when the player character is standing at the program start location. - void goto_region_and_return( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - bool inside_map - ); - - static std::set to_set(const StringSelectTableOption& option); - - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - BooleanCheckBoxOption RESET_GAME_AND_CONTINUE_SEARCHING; - - OCR::LanguageOCROption LANGUAGE; - - StringSelectTableOption DESIRED_MO_SLUGS; - StringSelectTableOption DESIRED_MMO_SLUGS; - StringSelectTableOption DESIRED_STAR_MMO_SLUGS; - - BooleanCheckBoxOption DEBUG_MODE; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationOption NOTIFICATION_MATCHED; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Outbreak Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_OutbreakFinder_H +#define PokemonAutomation_PokemonLA_OutbreakFinder_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/StringSelectTableOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class OutbreakFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + OutbreakFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class OutbreakFinder : public SingleSwitchProgramInstance{ +public: + OutbreakFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + // Run one iteration of the outbreak finder loop and return any found outbreaks. + // The iteration includes: + // 1. Starting at Jubilife Village gate, go to check the map for outbreaks. + // 2. If found desired outbreaks, stop. + // 3. If need to check MMOs, save in front of gate, then go to each region with MMO and talk to Mai to + // reveal MMO pokemon. Reset if no desired MMO to conserve Aguav Berries. + // 4. If found desired MMO pokemon, stop. + // 5. No desired outbreak in this iteration, go to an arbitrary region and return to village to refresh outbreaks. + // + // - desired_hisui_map_events: desired events happening on the travel map of Hisui when leaving Jubilife Village. + // It contains desired pokemon outbreak names and MMO outbreak names (e.g. "fieldlands-mmo"). If there are + // desired MMO pokemon (including those with star symbols), the MMO outbreaks that may spawn them are also + // included in `desired_hisui_map_events`. + // - desired_outbreaks: desired events happening on the travel map of Hisui when leaving Jubilife Village. + // This includes any user selected outbreak pokemon and user explicitly selected MMO events (e.g. "fieldlands-mmo") + // in DESIRED_MO_SLUGS. + // User selected MMO pokemon (including those with star symbols) do not affect `desired_outbreaks`. + // - desired_MMO_pokemon: user desired MMO pokemon selected by `DESIRED_MMO_SLUGS`. + // User selected MMO pokemon with star symbols, `DESIRED_STAR_MMO_SLUGS` do not affect `desired_MMO_pokemon`. + // - desired_star_MMO_pokemon: user desired MMO pokemon with star symbols. + std::vector run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::set& desired_hisui_map_events, + const std::set& desired_outbreaks, + const std::set& desired_MMO_pokemon, + const std::set& desired_star_MMO_pokemon); + + // Read the travel map from Jublilife village to find any desired pokemon or MMO events. + // Return true if program should stop (match found). + // desired_events: the desired set of pokemon slugs and MMO events. + std::set read_travel_map_outbreaks( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const std::set& desired_events + ); + + // Go to a random wild region and return to refresh outbreaks. + // If `inside_map` is true, the function is called when the game is inside the travel map. + // Otherwise, the function is called when the player character is standing at the program start location. + void goto_region_and_return( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + bool inside_map + ); + + static std::set to_set(const StringSelectTableOption& option); + + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + BooleanCheckBoxOption RESET_GAME_AND_CONTINUE_SEARCHING; + + OCR::LanguageOCROption LANGUAGE; + + StringSelectTableOption DESIRED_MO_SLUGS; + StringSelectTableOption DESIRED_MMO_SLUGS; + StringSelectTableOption DESIRED_STAR_MMO_SLUGS; + + BooleanCheckBoxOption DEBUG_MODE; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationOption NOTIFICATION_MATCHED; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.cpp index 13dd9199e7..896632fe23 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.cpp @@ -1,106 +1,106 @@ -/* Pokedex Tasks Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA_PokedexTasksReader.h" - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -class PokemonTasksReader{ -public: - PokemonTasksReader(VideoStream& stream) - : m_stream(stream) - , m_tasks_box{ - OverlayBoxScope(stream.overlay(), {0.400, 0.190, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.244, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.298, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.353, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.406, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.460, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.514, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.568, 0.040, 0.045}), - OverlayBoxScope(stream.overlay(), {0.400, 0.622, 0.040, 0.045}) - } - {} - - std::array read_tasks(const ImageViewRGB32& screen) const - { - std::array tasks{}; - for (size_t i = 0; i < m_tasks_box.size(); ++i) - { - ImageRGB32 image = to_blackwhite_rgb32_range( - extract_box_reference(screen, m_tasks_box[i]), - false, - 0xff808080, 0xffffffff - ); - tasks[i] = OCR::read_number(m_stream.logger(), image); - } - return tasks; - } - -private: - VideoStream& m_stream; - std::array m_tasks_box; -}; - -PokedexTasksReader_Descriptor::PokedexTasksReader_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:PokedexTasksReader", - STRING_POKEMON + " LA", STRING_POKEDEX + " Tasks Reader", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/PokedexTasksReader.md", - "Read all the tasks in your " + STRING_POKEDEX + " and output a file with the tasks you did.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -PokedexTasksReader::PokedexTasksReader(){} - - -void PokedexTasksReader::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - std::ofstream output_file("output.txt"); - - for (int i = 0; i < 242; ++i){ - PokemonTasksReader reader(env.console); - std::array tasks = reader.read_tasks(env.console.video().snapshot()); - for (auto task : tasks){ - if (task != -1){ - output_file << task << "\n"; - } - } - pbf_press_dpad(context, DPAD_DOWN, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Pokedex Tasks Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA_PokedexTasksReader.h" + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +class PokemonTasksReader{ +public: + PokemonTasksReader(VideoStream& stream) + : m_stream(stream) + , m_tasks_box{ + OverlayBoxScope(stream.overlay(), {0.400, 0.190, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.244, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.298, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.353, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.406, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.460, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.514, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.568, 0.040, 0.045}), + OverlayBoxScope(stream.overlay(), {0.400, 0.622, 0.040, 0.045}) + } + {} + + std::array read_tasks(const ImageViewRGB32& screen) const + { + std::array tasks{}; + for (size_t i = 0; i < m_tasks_box.size(); ++i) + { + ImageRGB32 image = to_blackwhite_rgb32_range( + extract_box_reference(screen, m_tasks_box[i]), + false, + 0xff808080, 0xffffffff + ); + tasks[i] = OCR::read_number(m_stream.logger(), image); + } + return tasks; + } + +private: + VideoStream& m_stream; + std::array m_tasks_box; +}; + +PokedexTasksReader_Descriptor::PokedexTasksReader_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:PokedexTasksReader", + STRING_POKEMON + " LA", STRING_POKEDEX + " Tasks Reader", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/PokedexTasksReader.md", + "Read all the tasks in your " + STRING_POKEDEX + " and output a file with the tasks you did.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +PokedexTasksReader::PokedexTasksReader(){} + + +void PokedexTasksReader::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + std::ofstream output_file("output.txt"); + + for (int i = 0; i < 242; ++i){ + PokemonTasksReader reader(env.console); + std::array tasks = reader.read_tasks(env.console.video().snapshot()); + for (auto task : tasks){ + if (task != -1){ + output_file << task << "\n"; + } + } + pbf_press_dpad(context, DPAD_DOWN, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.h index f264d37074..e914e9fb8c 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_PokedexTasksReader.h @@ -1,37 +1,37 @@ -/* Pokedex Tasks Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_PokedexTasksReader_H -#define PokemonAutomation_PokemonLA_PokedexTasksReader_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class PokedexTasksReader_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PokedexTasksReader_Descriptor(); -}; - - -class PokedexTasksReader : public SingleSwitchProgramInstance{ -public: - PokedexTasksReader(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; -}; - - - - - -} -} -} -#endif +/* Pokedex Tasks Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_PokedexTasksReader_H +#define PokemonAutomation_PokemonLA_PokedexTasksReader_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class PokedexTasksReader_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PokedexTasksReader_Descriptor(); +}; + + +class PokedexTasksReader : public SingleSwitchProgramInstance{ +public: + PokedexTasksReader(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.cpp index 7f32b2bd2c..ceb9889624 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.cpp @@ -1,347 +1,347 @@ -/* Ramanas Island Combee Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/PokemonLA_BlackOutDetector.h" -#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h" -#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -RamanasCombeeFinder_Descriptor::RamanasCombeeFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:Ramanas Island Combee Finder", - STRING_POKEMON + " LA", "Ramanas Combee Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/RamanasCombeeFinder.md", - "Check Ramanas Island Tree until a Combee is found.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class RamanasCombeeFinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , trees(m_stats["Trees"]) - , errors(m_stats["Errors"]) - , blackouts(m_stats["Blackouts"]) - , found(m_stats["Found"]) - , enroute_shinies(m_stats["Enroute Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Trees"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Blackouts", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Found"); - m_display_order.emplace_back("Enroute Shinies"); - m_aliases["Shinies"] = "Enroute Shinies"; - } - - std::atomic& attempts; - std::atomic& trees; - std::atomic& errors; - std::atomic& blackouts; - std::atomic& found; - std::atomic& enroute_shinies; -}; -std::unique_ptr RamanasCombeeFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -RamanasCombeeFinder:: RamanasCombeeFinder() - : LANGUAGE( - "Game Language", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while traveling in the overworld.", - "0 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(NOTIFICATIONS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - } -} - - -void RamanasCombeeFinder::check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - context.wait_for_all_requests(); - disable_shiny_sound(context); - // Throw pokemon - pbf_press_button(context, BUTTON_ZR, 500ms, 1500ms); - context.wait_for_all_requests(); - env.current_stats().trees++; - env.update_stats(); -} - -bool RamanasCombeeFinder::check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - context.wait_for_all_requests(); - - disable_shiny_sound(context); - bool battle_found = check_tree_or_ore_for_battle(env.console, context); - env.current_stats().trees++; - env.update_stats(); - - context.wait_for_all_requests(); - - bool ret = false; - if (battle_found){ - ret = handle_battle(env, context); - } - - enable_shiny_sound(context); - - return ret; -} - - -void RamanasCombeeFinder::disable_shiny_sound(ProControllerContext& context){ - context.wait_for_all_requests(); - m_enable_shiny_sound.store(false, std::memory_order_release); -} -void RamanasCombeeFinder::enable_shiny_sound(ProControllerContext& context){ - context.wait_for_all_requests(); - m_enable_shiny_sound.store(true, std::memory_order_release); -} - -bool RamanasCombeeFinder::handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - RamanasCombeeFinder_Descriptor::Stats& stats = env.current_stats(); - - PokemonDetails pokemon = get_pokemon_details(env.console, context, LANGUAGE); - - pbf_press_button(context, BUTTON_B, 20, 225); - - context.wait_for_all_requests(); - - if (pokemon.name_candidates.find("combee") == pokemon.name_candidates.end()){ - env.console.log("Not a Combee, leaving battle."); - exit_battle(env.console, context, ExitBattleMethod::RunAway); - return false; - } - - env.console.log("Combee found"); - stats.found++; - - context.wait_for_all_requests(); - throw ProgramFinishedException(); -// on_battle_match_found(env, env.console, context, SHINY_DETECTED_ENROUTE, true); -// return true; -} - -void RamanasCombeeFinder::grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - BattleMenuDetector battle_menu_detector(env.console, env.console, true); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - - env.console.log("Checking Tree 1"); - change_mount(env.console,context,MountState::BRAVIARY_ON); - pbf_move_left_joystick(context, 239, 0, 100, 20); - pbf_press_button(context, BUTTON_B, 2390, 0); - pbf_press_button(context, BUTTON_Y, 380, 0); - pbf_move_right_joystick(context, 127, 255, 90, 20); - check_tree_no_stop(env, context); - - env.console.log("Checking Tree 2"); - pbf_press_button(context, BUTTON_PLUS, 20, 200); - pbf_move_left_joystick(context, 242, 0, 100, 20); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, 420, 0); - pbf_press_button(context, BUTTON_Y, 380, 0); - pbf_move_right_joystick(context, 127, 255, 90, 20); - check_tree_no_stop(env, context); - - env.console.log("Checking Tree 3"); - pbf_press_button(context, BUTTON_PLUS, 20, 200); - pbf_move_left_joystick(context, 0, 60, 100, 20); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, 350, 0); - pbf_press_button(context, BUTTON_Y, 380, 0); - pbf_move_right_joystick(context, 127, 255, 90, 20); - check_tree_no_stop(env, context); - - env.console.log("Checking Tree 4"); - pbf_press_button(context, BUTTON_PLUS, 20, 200); - pbf_move_left_joystick(context, 50, 255, 100, 20); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, 375, 0); - pbf_press_button(context, BUTTON_Y, 380, 0); - pbf_move_right_joystick(context, 127, 255, 90, 20); - check_tree_no_stop(env, context); - - env.console.log("Checking Tree 5"); - pbf_press_button(context, BUTTON_PLUS, 20, 200); - pbf_move_left_joystick(context, 200, 0, 100, 20); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, 85, 0); - pbf_press_button(context, BUTTON_Y, 380, 0); - pbf_move_right_joystick(context, 127, 255, 90, 20); - }, - { - {battle_menu_detector}, - } - ); - - if (ret == 0){ - if (handle_battle(env, context)){ - env.console.log("Battle found before last tree in the path."); - } - - }else{ - check_tree(env, context); - env.console.log("Checked all trees in the path."); - } - -} - -void RamanasCombeeFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - RamanasCombeeFinder_Descriptor::Stats& stats = env.current_stats(); - stats.attempts++; - env.update_stats(); - env.console.log("Starting route and shiny detection..."); - - for (size_t c = 0; true; c++){ - context.wait_for_all_requests(); - if (is_pokemon_selection(env.console, env.console.video().snapshot())){ - break; - } - if (c >= 5){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to switch to Pokemon selection after 5 attempts.", - env.console - ); - } - env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_X, 20, 230); - } - - float shiny_coefficient = 1.0; - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - if (!m_enable_shiny_sound.load()){ - return false; - } - stats.enroute_shinies++; - shiny_coefficient = error_coefficient; - return on_shiny_callback(env, env.console, SHINY_DETECTED_ENROUTE, error_coefficient); - }); - - BlackOutDetector black_out_detector(env.console, env.console); - - goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - grouped_path(env, context); - context.wait_for_all_requests(); - goto_camp_from_overworld(env, env.console, context); - goto_professor(env.console, context, Camp::FIELDLANDS_FIELDLANDS); - }, - {{shiny_detector, black_out_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, SHINY_DETECTED_ENROUTE, shiny_coefficient); - }else if (ret == 1){ - env.log("Character blacks out"); - // black out. - stats.blackouts++; - env.update_stats(); - if (SAVE_DEBUG_VIDEO){ - // Take a video to know why it blacks out - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Black out.", - env.console - ); - } - - from_professor_return_to_jubilife(env, env.console, context); -} - -void RamanasCombeeFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - RamanasCombeeFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* Ramanas Island Combee Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/PokemonLA_BlackOutDetector.h" +#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h" +#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +RamanasCombeeFinder_Descriptor::RamanasCombeeFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:Ramanas Island Combee Finder", + STRING_POKEMON + " LA", "Ramanas Combee Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/RamanasCombeeFinder.md", + "Check Ramanas Island Tree until a Combee is found.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class RamanasCombeeFinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , trees(m_stats["Trees"]) + , errors(m_stats["Errors"]) + , blackouts(m_stats["Blackouts"]) + , found(m_stats["Found"]) + , enroute_shinies(m_stats["Enroute Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Trees"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Blackouts", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Found"); + m_display_order.emplace_back("Enroute Shinies"); + m_aliases["Shinies"] = "Enroute Shinies"; + } + + std::atomic& attempts; + std::atomic& trees; + std::atomic& errors; + std::atomic& blackouts; + std::atomic& found; + std::atomic& enroute_shinies; +}; +std::unique_ptr RamanasCombeeFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +RamanasCombeeFinder:: RamanasCombeeFinder() + : LANGUAGE( + "Game Language", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while traveling in the overworld.", + "0 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(NOTIFICATIONS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + } +} + + +void RamanasCombeeFinder::check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + context.wait_for_all_requests(); + disable_shiny_sound(context); + // Throw pokemon + pbf_press_button(context, BUTTON_ZR, 500ms, 1500ms); + context.wait_for_all_requests(); + env.current_stats().trees++; + env.update_stats(); +} + +bool RamanasCombeeFinder::check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + context.wait_for_all_requests(); + + disable_shiny_sound(context); + bool battle_found = check_tree_or_ore_for_battle(env.console, context); + env.current_stats().trees++; + env.update_stats(); + + context.wait_for_all_requests(); + + bool ret = false; + if (battle_found){ + ret = handle_battle(env, context); + } + + enable_shiny_sound(context); + + return ret; +} + + +void RamanasCombeeFinder::disable_shiny_sound(ProControllerContext& context){ + context.wait_for_all_requests(); + m_enable_shiny_sound.store(false, std::memory_order_release); +} +void RamanasCombeeFinder::enable_shiny_sound(ProControllerContext& context){ + context.wait_for_all_requests(); + m_enable_shiny_sound.store(true, std::memory_order_release); +} + +bool RamanasCombeeFinder::handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + RamanasCombeeFinder_Descriptor::Stats& stats = env.current_stats(); + + PokemonDetails pokemon = get_pokemon_details(env.console, context, LANGUAGE); + + pbf_press_button(context, BUTTON_B, 20, 225); + + context.wait_for_all_requests(); + + if (pokemon.name_candidates.find("combee") == pokemon.name_candidates.end()){ + env.console.log("Not a Combee, leaving battle."); + exit_battle(env.console, context, ExitBattleMethod::RunAway); + return false; + } + + env.console.log("Combee found"); + stats.found++; + + context.wait_for_all_requests(); + throw ProgramFinishedException(); +// on_battle_match_found(env, env.console, context, SHINY_DETECTED_ENROUTE, true); +// return true; +} + +void RamanasCombeeFinder::grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + BattleMenuDetector battle_menu_detector(env.console, env.console, true); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + + env.console.log("Checking Tree 1"); + change_mount(env.console,context,MountState::BRAVIARY_ON); + pbf_move_left_joystick(context, 239, 0, 100, 20); + pbf_press_button(context, BUTTON_B, 2390, 0); + pbf_press_button(context, BUTTON_Y, 380, 0); + pbf_move_right_joystick(context, 127, 255, 90, 20); + check_tree_no_stop(env, context); + + env.console.log("Checking Tree 2"); + pbf_press_button(context, BUTTON_PLUS, 20, 200); + pbf_move_left_joystick(context, 242, 0, 100, 20); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, 420, 0); + pbf_press_button(context, BUTTON_Y, 380, 0); + pbf_move_right_joystick(context, 127, 255, 90, 20); + check_tree_no_stop(env, context); + + env.console.log("Checking Tree 3"); + pbf_press_button(context, BUTTON_PLUS, 20, 200); + pbf_move_left_joystick(context, 0, 60, 100, 20); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, 350, 0); + pbf_press_button(context, BUTTON_Y, 380, 0); + pbf_move_right_joystick(context, 127, 255, 90, 20); + check_tree_no_stop(env, context); + + env.console.log("Checking Tree 4"); + pbf_press_button(context, BUTTON_PLUS, 20, 200); + pbf_move_left_joystick(context, 50, 255, 100, 20); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, 375, 0); + pbf_press_button(context, BUTTON_Y, 380, 0); + pbf_move_right_joystick(context, 127, 255, 90, 20); + check_tree_no_stop(env, context); + + env.console.log("Checking Tree 5"); + pbf_press_button(context, BUTTON_PLUS, 20, 200); + pbf_move_left_joystick(context, 200, 0, 100, 20); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, 85, 0); + pbf_press_button(context, BUTTON_Y, 380, 0); + pbf_move_right_joystick(context, 127, 255, 90, 20); + }, + { + {battle_menu_detector}, + } + ); + + if (ret == 0){ + if (handle_battle(env, context)){ + env.console.log("Battle found before last tree in the path."); + } + + }else{ + check_tree(env, context); + env.console.log("Checked all trees in the path."); + } + +} + +void RamanasCombeeFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + RamanasCombeeFinder_Descriptor::Stats& stats = env.current_stats(); + stats.attempts++; + env.update_stats(); + env.console.log("Starting route and shiny detection..."); + + for (size_t c = 0; true; c++){ + context.wait_for_all_requests(); + if (is_pokemon_selection(env.console, env.console.video().snapshot())){ + break; + } + if (c >= 5){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to switch to Pokemon selection after 5 attempts.", + env.console + ); + } + env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_X, 20, 230); + } + + float shiny_coefficient = 1.0; + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + if (!m_enable_shiny_sound.load()){ + return false; + } + stats.enroute_shinies++; + shiny_coefficient = error_coefficient; + return on_shiny_callback(env, env.console, SHINY_DETECTED_ENROUTE, error_coefficient); + }); + + BlackOutDetector black_out_detector(env.console, env.console); + + goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + grouped_path(env, context); + context.wait_for_all_requests(); + goto_camp_from_overworld(env, env.console, context); + goto_professor(env.console, context, Camp::FIELDLANDS_FIELDLANDS); + }, + {{shiny_detector, black_out_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, SHINY_DETECTED_ENROUTE, shiny_coefficient); + }else if (ret == 1){ + env.log("Character blacks out"); + // black out. + stats.blackouts++; + env.update_stats(); + if (SAVE_DEBUG_VIDEO){ + // Take a video to know why it blacks out + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Black out.", + env.console + ); + } + + from_professor_return_to_jubilife(env, env.console, context); +} + +void RamanasCombeeFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + RamanasCombeeFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h index d9987b76bd..472fa9fd0e 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_RamanasIslandCombee.h @@ -1,61 +1,61 @@ -/* Combee Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_RamanasIslandCombee_H -#define PokemonAutomation_PokemonLA_RamanasIslandCombee_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class RamanasCombeeFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - RamanasCombeeFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class RamanasCombeeFinder: public SingleSwitchProgramInstance{ -public: - RamanasCombeeFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void disable_shiny_sound(ProControllerContext& context); - void enable_shiny_sound(ProControllerContext& context); - -private: - class RunRoute; - - std::atomic m_enable_shiny_sound{true}; - - OCR::LanguageOCROption LANGUAGE; - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; - - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; -}; - -} -} -} -#endif +/* Combee Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_RamanasIslandCombee_H +#define PokemonAutomation_PokemonLA_RamanasIslandCombee_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class RamanasCombeeFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + RamanasCombeeFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class RamanasCombeeFinder: public SingleSwitchProgramInstance{ +public: + RamanasCombeeFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void disable_shiny_sound(ProControllerContext& context); + void enable_shiny_sound(ProControllerContext& context); + +private: + class RunRoute; + + std::atomic m_enable_shiny_sound{true}; + + OCR::LanguageOCROption LANGUAGE; + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; + + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.cpp b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.cpp index bbb2b7d188..4548a92445 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.cpp @@ -1,129 +1,129 @@ -/* Skip to Full Moon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h" -#include "PokemonLA_SkipToFullMoon.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - -SkipToFullMoon_Descriptor::SkipToFullMoon_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:SkipToFullMoon", - STRING_POKEMON + " LA", "Skip to Full Moon", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/SkipToFullMoon.md", - "Skip nights until full moon.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -SkipToFullMoon::SkipToFullMoon() - : NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void SkipToFullMoon::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - // Open menu - pbf_press_dpad(context, DPAD_UP, 20, 120); - context.wait_for_all_requests(); - - const auto compatibility = detect_item_compatibility(env.console.video().snapshot()); - - if (compatibility == ItemCompatibility::NONE){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect item compatibility.", - env.console - ); - } - - if (compatibility == ItemCompatibility::COMPATIBLE){ - // Ursaring can evolve, it's full moon now. - break; - } - - // Do another time skip: - - // Close menu - pbf_press_button(context, BUTTON_B, 20, 100); - // Character turn around to face the tent - pbf_move_left_joystick(context, 128, 0, 20, 100); - // Press A to show the "how long do you rest" dialogue - pbf_press_button(context, BUTTON_A, 10, 100); - // Press A to show the time menu - pbf_press_button(context, BUTTON_A, 10, 30); - // Move the selection to "Until nightfall" - pbf_press_dpad(context, DPAD_UP, 10, 30); - pbf_press_dpad(context, DPAD_UP, 10, 50); - - // Press A to sleep to next night - pbf_press_button(context, BUTTON_A, 20, 50); - // Sleeping - pbf_wait(context, 8 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - const bool stop_on_detected = true; - - // DialogueEllipseDetector dialogue_ellipse_detector(env.console, env.console, std::chrono::milliseconds(200), - // DialogueEllipseDetector::EllipseLocation::TENT, stop_on_detected); - // int ret = wait_until( - // env.console, context, std::chrono::seconds(8), - // {{dialogue_ellipse_detector}} - // ); - // if (ret != 0){ - // std::cout << "ERROR! Cannot detect the dialogue ellipse" << std::endl; - // } - // Press B to clear the "You Pokemon happy and healthy" dialogue. - // pbf_press_button(context, BUTTON_B, 20, 100); - - - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(100), stop_on_detected); - run_until( - env.console, context, - [](ProControllerContext& local_context){ - // pbf_mash_button(local_context, BUTTON_B, 7 * TICKS_PER_SECOND); - for(size_t i = 0; i < 15; i++){ - pbf_press_button(local_context, BUTTON_B, 20, 80); - } - }, - {{arc_phone_detector}} - ); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Skip to Full Moon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/PokemonLA_ItemCompatibilityDetector.h" +#include "PokemonLA_SkipToFullMoon.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + +SkipToFullMoon_Descriptor::SkipToFullMoon_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:SkipToFullMoon", + STRING_POKEMON + " LA", "Skip to Full Moon", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/SkipToFullMoon.md", + "Skip nights until full moon.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +SkipToFullMoon::SkipToFullMoon() + : NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void SkipToFullMoon::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + // Open menu + pbf_press_dpad(context, DPAD_UP, 20, 120); + context.wait_for_all_requests(); + + const auto compatibility = detect_item_compatibility(env.console.video().snapshot()); + + if (compatibility == ItemCompatibility::NONE){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect item compatibility.", + env.console + ); + } + + if (compatibility == ItemCompatibility::COMPATIBLE){ + // Ursaring can evolve, it's full moon now. + break; + } + + // Do another time skip: + + // Close menu + pbf_press_button(context, BUTTON_B, 20, 100); + // Character turn around to face the tent + pbf_move_left_joystick(context, 128, 0, 20, 100); + // Press A to show the "how long do you rest" dialogue + pbf_press_button(context, BUTTON_A, 10, 100); + // Press A to show the time menu + pbf_press_button(context, BUTTON_A, 10, 30); + // Move the selection to "Until nightfall" + pbf_press_dpad(context, DPAD_UP, 10, 30); + pbf_press_dpad(context, DPAD_UP, 10, 50); + + // Press A to sleep to next night + pbf_press_button(context, BUTTON_A, 20, 50); + // Sleeping + pbf_wait(context, 8 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + const bool stop_on_detected = true; + + // DialogueEllipseDetector dialogue_ellipse_detector(env.console, env.console, std::chrono::milliseconds(200), + // DialogueEllipseDetector::EllipseLocation::TENT, stop_on_detected); + // int ret = wait_until( + // env.console, context, std::chrono::seconds(8), + // {{dialogue_ellipse_detector}} + // ); + // if (ret != 0){ + // std::cout << "ERROR! Cannot detect the dialogue ellipse" << std::endl; + // } + // Press B to clear the "You Pokemon happy and healthy" dialogue. + // pbf_press_button(context, BUTTON_B, 20, 100); + + + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(100), stop_on_detected); + run_until( + env.console, context, + [](ProControllerContext& local_context){ + // pbf_mash_button(local_context, BUTTON_B, 7 * TICKS_PER_SECOND); + for(size_t i = 0; i < 15; i++){ + pbf_press_button(local_context, BUTTON_B, 20, 80); + } + }, + {{arc_phone_detector}} + ); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.h b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.h index 54b10949d2..4ea68471a4 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.h +++ b/SerialPrograms/Source/PokemonLA/Programs/General/PokemonLA_SkipToFullMoon.h @@ -1,42 +1,42 @@ -/* Skip to Full Moon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_SkipToFullMoon_H -#define PokemonAutomation_PokemonLA_SkipToFullMoon_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class SkipToFullMoon_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SkipToFullMoon_Descriptor(); -}; - - -class SkipToFullMoon : public SingleSwitchProgramInstance{ -public: - SkipToFullMoon(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Skip to Full Moon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_SkipToFullMoon_H +#define PokemonAutomation_PokemonLA_SkipToFullMoon_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class SkipToFullMoon_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SkipToFullMoon_Descriptor(); +}; + + +class SkipToFullMoon : public SingleSwitchProgramInstance{ +public: + SkipToFullMoon(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.cpp index 4a41d4c70d..33c8de4909 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.cpp @@ -1,201 +1,201 @@ -/* Mount Change - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" -#include "PokemonLA_BattleRoutines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -void mash_A_until_end_of_battle(VideoStream& stream, ProControllerContext& context){ - OverworldDetector detector(stream.logger(), stream.overlay()); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 180 * TICKS_PER_SECOND); - }, - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to return to overworld after 3 minutes.", - stream - ); - } - stream.log("Returned to overworld."); -} - - - -size_t switch_pokemon( - VideoStream& stream, ProControllerContext& context, - size_t pokemon_to_switch_to, - size_t max_num_pokemon -){ - if (pokemon_to_switch_to >= max_num_pokemon){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot send any more Pokemon to battle, max: " + std::to_string(max_num_pokemon), - stream - ); - } - // Move past leading fainted pokemon - for(size_t i = 0; i < pokemon_to_switch_to; i++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 80); - } - - while(true){ - // Choose the next pokemon to battle. - pbf_press_button(context, BUTTON_A, 20, 100); - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - // Check whether we can send this pokemon to battle: - const bool stop_on_detected = true; - BattlePokemonSwitchDetector switch_detector(stream.logger(), stream.overlay(), stop_on_detected); - VideoSnapshot screen = stream.video().snapshot(); - if (switch_detector.process_frame(screen, current_time()) == false){ - // No longer at the switching pokemon screen - break; - } - - // We are still in the switching pokemon screen. So the current selected pokemon is fainted - // and therefore cannot be used. Try the next pokemon: - pokemon_to_switch_to++; - if (pokemon_to_switch_to >= max_num_pokemon){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot send any more Pokemon to battle, max: " + std::to_string(max_num_pokemon), - stream - ); - } - - // Fist hit B to clear the "cannot send pokemon" dialogue - pbf_press_button(context, BUTTON_B, 20, 100); - // Move to the next pokemon - pbf_press_dpad(context, DPAD_DOWN, 20, 80); - } - - return pokemon_to_switch_to; -} - - -void use_move_blindly( - VideoStream& stream, ProControllerContext& context, - MoveStyle style, - size_t cur_pokemon, - size_t cur_move -){ - // Select move styles - if (style == MoveStyle::Agile){ - // Agile style - pbf_press_button(context, BUTTON_L, 10, 125); - }else if (style == MoveStyle::Strong){ - // Strong style - pbf_press_button(context, BUTTON_R, 10, 125); - } - - // Use the move - pbf_press_button(context, BUTTON_A, 10, 125); - - stream.log( - "Using pokemon " + std::to_string(cur_pokemon) + " move " + std::to_string(cur_move) + - " style " + MoveStyle_Database().find(style)->display - ); - - pbf_wait(context, 1 * TICKS_PER_SECOND); - context.wait_for_all_requests(); -} - - -bool use_move( - VideoStream& stream, ProControllerContext& context, - size_t cur_pokemon, - size_t cur_move, - MoveStyle style, - bool check_success -){ - if (check_success == false){ - use_move_blindly(stream, context, style, cur_pokemon, cur_move); - return true; - } - - // The location of the move slots when choosing which move to use during battle. - // These boxes will be used to check whether the content in those boxes are changed or not - // after selecting one move to use. In this way we can detect whether the move is out of PP. - const ImageFloatBox move_slot_boxes[4] = { - {0.6600, 0.6220, 0.2500, 0.0320}, - {0.6395, 0.6875, 0.2500, 0.0320}, - {0.6190, 0.7530, 0.2500, 0.0320}, - {0.5985, 0.8185, 0.2500, 0.0320}, - }; - - VideoSnapshot screen = stream.video().snapshot(); - ImageMatchDetector move_slot_detector(std::move(screen.frame), move_slot_boxes[cur_move], 10.0); - - use_move_blindly(stream, context, style, cur_pokemon, cur_move); - - screen = stream.video().snapshot(); - - const bool still_on_move_screen = move_slot_detector.detect(screen); - -#ifdef DEBUG_NO_PP - if (still_on_move_screen == false){ - static int count = 0; - screen.save("./no_pp." + std::to_string(count++) + ".png"); - } -#endif - - return still_on_move_screen == false; -} - -void use_next_move_with_pp( - VideoStream& stream, ProControllerContext& context, - size_t cur_pokemon, - size_t& cur_move -){ - const bool check_move_success = true; - while (use_move(stream, context, cur_pokemon, cur_move, MoveStyle::NoStyle, check_move_success) == false){ - // We are still on the move selection screen. No PP. - if (cur_move == 3){ - // Pokemon has zero PP on all moves. This should not happen as it will just use - // Struggle. - stream.log("No PP on all moves. Abort program.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No PP on all moves.", - stream - ); - } - - // Go to the next move. - pbf_press_dpad(context, DPAD_DOWN, 20, 100); - // env.console.context().wait_for_all_requests(); - cur_move++; - stream.log("No PP. Use next move, " + std::to_string(cur_move), COLOR_RED); - } -} - - - - -} -} -} +/* Mount Change + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" +#include "PokemonLA_BattleRoutines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +void mash_A_until_end_of_battle(VideoStream& stream, ProControllerContext& context){ + OverworldDetector detector(stream.logger(), stream.overlay()); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 180 * TICKS_PER_SECOND); + }, + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to return to overworld after 3 minutes.", + stream + ); + } + stream.log("Returned to overworld."); +} + + + +size_t switch_pokemon( + VideoStream& stream, ProControllerContext& context, + size_t pokemon_to_switch_to, + size_t max_num_pokemon +){ + if (pokemon_to_switch_to >= max_num_pokemon){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot send any more Pokemon to battle, max: " + std::to_string(max_num_pokemon), + stream + ); + } + // Move past leading fainted pokemon + for(size_t i = 0; i < pokemon_to_switch_to; i++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 80); + } + + while(true){ + // Choose the next pokemon to battle. + pbf_press_button(context, BUTTON_A, 20, 100); + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + // Check whether we can send this pokemon to battle: + const bool stop_on_detected = true; + BattlePokemonSwitchDetector switch_detector(stream.logger(), stream.overlay(), stop_on_detected); + VideoSnapshot screen = stream.video().snapshot(); + if (switch_detector.process_frame(screen, current_time()) == false){ + // No longer at the switching pokemon screen + break; + } + + // We are still in the switching pokemon screen. So the current selected pokemon is fainted + // and therefore cannot be used. Try the next pokemon: + pokemon_to_switch_to++; + if (pokemon_to_switch_to >= max_num_pokemon){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot send any more Pokemon to battle, max: " + std::to_string(max_num_pokemon), + stream + ); + } + + // Fist hit B to clear the "cannot send pokemon" dialogue + pbf_press_button(context, BUTTON_B, 20, 100); + // Move to the next pokemon + pbf_press_dpad(context, DPAD_DOWN, 20, 80); + } + + return pokemon_to_switch_to; +} + + +void use_move_blindly( + VideoStream& stream, ProControllerContext& context, + MoveStyle style, + size_t cur_pokemon, + size_t cur_move +){ + // Select move styles + if (style == MoveStyle::Agile){ + // Agile style + pbf_press_button(context, BUTTON_L, 10, 125); + }else if (style == MoveStyle::Strong){ + // Strong style + pbf_press_button(context, BUTTON_R, 10, 125); + } + + // Use the move + pbf_press_button(context, BUTTON_A, 10, 125); + + stream.log( + "Using pokemon " + std::to_string(cur_pokemon) + " move " + std::to_string(cur_move) + + " style " + MoveStyle_Database().find(style)->display + ); + + pbf_wait(context, 1 * TICKS_PER_SECOND); + context.wait_for_all_requests(); +} + + +bool use_move( + VideoStream& stream, ProControllerContext& context, + size_t cur_pokemon, + size_t cur_move, + MoveStyle style, + bool check_success +){ + if (check_success == false){ + use_move_blindly(stream, context, style, cur_pokemon, cur_move); + return true; + } + + // The location of the move slots when choosing which move to use during battle. + // These boxes will be used to check whether the content in those boxes are changed or not + // after selecting one move to use. In this way we can detect whether the move is out of PP. + const ImageFloatBox move_slot_boxes[4] = { + {0.6600, 0.6220, 0.2500, 0.0320}, + {0.6395, 0.6875, 0.2500, 0.0320}, + {0.6190, 0.7530, 0.2500, 0.0320}, + {0.5985, 0.8185, 0.2500, 0.0320}, + }; + + VideoSnapshot screen = stream.video().snapshot(); + ImageMatchDetector move_slot_detector(std::move(screen.frame), move_slot_boxes[cur_move], 10.0); + + use_move_blindly(stream, context, style, cur_pokemon, cur_move); + + screen = stream.video().snapshot(); + + const bool still_on_move_screen = move_slot_detector.detect(screen); + +#ifdef DEBUG_NO_PP + if (still_on_move_screen == false){ + static int count = 0; + screen.save("./no_pp." + std::to_string(count++) + ".png"); + } +#endif + + return still_on_move_screen == false; +} + +void use_next_move_with_pp( + VideoStream& stream, ProControllerContext& context, + size_t cur_pokemon, + size_t& cur_move +){ + const bool check_move_success = true; + while (use_move(stream, context, cur_pokemon, cur_move, MoveStyle::NoStyle, check_move_success) == false){ + // We are still on the move selection screen. No PP. + if (cur_move == 3){ + // Pokemon has zero PP on all moves. This should not happen as it will just use + // Struggle. + stream.log("No PP on all moves. Abort program.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No PP on all moves.", + stream + ); + } + + // Go to the next move. + pbf_press_dpad(context, DPAD_DOWN, 20, 100); + // env.console.context().wait_for_all_requests(); + cur_move++; + stream.log("No PP. Use next move, " + std::to_string(cur_move), COLOR_RED); + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.h index e89d78cd87..9c507b91f9 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_BattleRoutines.h @@ -1,63 +1,63 @@ -/* Battle Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_BattleRoutines_H -#define PokemonAutomation_PokemonLA_BattleRoutines_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -void mash_A_until_end_of_battle(VideoStream& stream, ProControllerContext& context); - -// Assuming the game is in the switching pokemon screen, select a pokemon to send to battle. -// pokemon_to_switch_to: the index of the pokemon in the party to switch to. -// If the pokemon cannot be sent either due to already on the battlefield or fainted, it will select the next -// pokemon in the party list, until it is successfully sent. -// Return the index of the party that is actually sent to battle. -// max_num_pokemon: if the pokemon index to switch to is >= `max_num_pokemon`, throw an OperationFailedException. -size_t switch_pokemon( - VideoStream& stream, ProControllerContext& context, - size_t pokemon_to_switch_to, - size_t max_num_pokemon = SIZE_MAX -); - -// Assuming the game is at the move selection menu, use the current selected move in desired style in battle. -// `cur_pokemon` does not affect game control. It is passed in only for the logging purpose. -// `cur_move` the index of the move (0, 1, 2 or 3). It is only used when `check_success` is true. -// If `check_success` is true, return whether the move is successfully used, by checking whether the game is still in the move selection -// menu after some ticks (need correct `cur_move` to do this). If `check_success` is false, always return true. -// `wait_for_all_requests()` is called at the end of the function no matter `check_success` is true or false. -bool use_move( - VideoStream& stream, ProControllerContext& context, - size_t cur_pokemon, - size_t cur_move, - MoveStyle style, - bool check_success -); - -// Assuming the game is at the move selection menu, use the current selected move with no style. -// If the move has no PP, move to use the next move. -// `cur_pokemon` does not affect game control. It is passed in only for the logging purpose. -// In order for the move PP detection to be correct, must pass in the correct `cur_move`. -// When the function moves to using the next move, it also updates `cur_move`. -// This function assumes it starts with the move selection menu, so it does not consider the case the pokemon has no PP and has to use Struggle. -void use_next_move_with_pp( - VideoStream& stream, ProControllerContext& context, - size_t cur_pokemon, - size_t& cur_move -); - - -} -} -} -#endif +/* Battle Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_BattleRoutines_H +#define PokemonAutomation_PokemonLA_BattleRoutines_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonLA/Options/PokemonLA_BattlePokemonActionTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +void mash_A_until_end_of_battle(VideoStream& stream, ProControllerContext& context); + +// Assuming the game is in the switching pokemon screen, select a pokemon to send to battle. +// pokemon_to_switch_to: the index of the pokemon in the party to switch to. +// If the pokemon cannot be sent either due to already on the battlefield or fainted, it will select the next +// pokemon in the party list, until it is successfully sent. +// Return the index of the party that is actually sent to battle. +// max_num_pokemon: if the pokemon index to switch to is >= `max_num_pokemon`, throw an OperationFailedException. +size_t switch_pokemon( + VideoStream& stream, ProControllerContext& context, + size_t pokemon_to_switch_to, + size_t max_num_pokemon = SIZE_MAX +); + +// Assuming the game is at the move selection menu, use the current selected move in desired style in battle. +// `cur_pokemon` does not affect game control. It is passed in only for the logging purpose. +// `cur_move` the index of the move (0, 1, 2 or 3). It is only used when `check_success` is true. +// If `check_success` is true, return whether the move is successfully used, by checking whether the game is still in the move selection +// menu after some ticks (need correct `cur_move` to do this). If `check_success` is false, always return true. +// `wait_for_all_requests()` is called at the end of the function no matter `check_success` is true or false. +bool use_move( + VideoStream& stream, ProControllerContext& context, + size_t cur_pokemon, + size_t cur_move, + MoveStyle style, + bool check_success +); + +// Assuming the game is at the move selection menu, use the current selected move with no style. +// If the move has no PP, move to use the next move. +// `cur_pokemon` does not affect game control. It is passed in only for the logging purpose. +// In order for the move PP detection to be correct, must pass in the correct `cur_move`. +// When the function moves to using the next move, it also updates `cur_move`. +// This function assumes it starts with the move selection menu, so it does not consider the case the pokemon has no PP and has to use Struggle. +void use_next_move_with_pp( + VideoStream& stream, ProControllerContext& context, + size_t cur_pokemon, + size_t& cur_move +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.cpp index fdd947f776..e8f21394f2 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.cpp @@ -1,197 +1,197 @@ -/* Escape From Attack - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA_EscapeFromAttack.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -EscapeFromAttack::EscapeFromAttack( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - std::chrono::seconds time_min, - std::chrono::seconds time_limit -) - : SuperControlSession(env, stream, context) - , m_min_stop(current_time() + time_min) - , m_deadline(current_time() + time_limit) - , m_attacked(stream.logger()) - , m_mount(stream.logger()) - , m_centerA( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.40, 0.50, 0.40, 0.50}, - std::chrono::milliseconds(200), - false - ) - , m_leftB( - stream.logger(), stream.overlay(), - ButtonType::ButtonB, - {0.02, 0.40, 0.05, 0.20}, - std::chrono::milliseconds(200), - false - ) - , m_get_on_sneasler_time(WallClock::min()) -{ - *this += m_attacked; - *this += m_mount; - *this += m_centerA; - *this += m_leftB; - - const std::chrono::milliseconds GET_ON_BRAVIARY_TIME_MILLIS(GET_ON_BRAVIARY_TIME * 1000 / TICKS_PER_SECOND); - - register_state_command(State::UNKNOWN, [this](){ - m_stream.log("Unknown state. Moving forward..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 300 * TICKS_PER_SECOND, 0); - }); - return false; - }); - register_state_command(State::WYRDEER_BASCULEGION_OFF, [this](){ - m_stream.log("Switching from Wyrdeer/Basculegion (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::WYRDEER_BASCULEGION_ON, [this](){ - m_stream.log("Switching from Wyrdeer/Basculegion (on) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::URSALUNA_OFF, [this](){ - m_stream.log("Switching from Ursaluna (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::URSALUNA_ON, [this](){ - m_stream.log("Switching from Ursaluna (on) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::SNEASLER_OFF, [this](){ - m_stream.log("Switching from Sneasler (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::SNEASLER_ON, [this](){ - m_stream.log("Switching from Sneasler (on) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 125, 0); - pbf_press_dpad(context, DPAD_LEFT, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::BRAVIARY_OFF, [this](){ - m_stream.log("Switching from Braviary (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::DASH_FORWARD, [this, GET_ON_BRAVIARY_TIME_MILLIS](){ - bool delay_dash = - current_time() < m_get_on_sneasler_time + GET_ON_BRAVIARY_TIME_MILLIS; - if (delay_dash){ - m_stream.log("Dashing forward... (delayed due to being on Sneasler)"); - }else{ - m_stream.log("Dashing forward..."); - } - m_active_command->dispatch([delay_dash](ProControllerContext& context){ - if (delay_dash){ - pbf_move_left_joystick(context, 128, 0, 125, 0); - } - pbf_mash_button(context, BUTTON_B, 300 * TICKS_PER_SECOND); - }); - return false; - }); - register_state_command(State::GET_ON_SNEASLER, [this](){ - m_stream.log("Getting on Sneasler..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 20, 230); - }); - m_get_on_sneasler_time = current_time(); - return false; - }); - register_state_command(State::CLIMBING, [this](){ - m_stream.log("Climbing wall..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 300 * TICKS_PER_SECOND, 0); - }); - return false; - }); -} -bool EscapeFromAttack::run_state(AsyncCommandSession& commands, WallClock timestamp){ - if (timestamp > m_deadline){ - return true; - } - if (m_attacked.state() == UnderAttackState::SAFE && timestamp >= m_min_stop){ - return true; - } - - switch (m_mount.state()){ - case MountState::NOTHING: - return run_state_action(State::UNKNOWN); - case MountState::WYRDEER_OFF: - case MountState::BASCULEGION_OFF: - return run_state_action(State::WYRDEER_BASCULEGION_OFF); - case MountState::WYRDEER_ON: - case MountState::BASCULEGION_ON: - return run_state_action(State::WYRDEER_BASCULEGION_ON); - case MountState::URSALUNA_OFF: - return run_state_action(State::URSALUNA_OFF); - case MountState::URSALUNA_ON: - return run_state_action(State::URSALUNA_ON); - case MountState::SNEASLER_OFF: - return run_state_action(State::SNEASLER_OFF); - case MountState::SNEASLER_ON: - return run_climbing(commands, timestamp); - case MountState::BRAVIARY_OFF: - return run_state_action(State::BRAVIARY_OFF); - case MountState::BRAVIARY_ON: - return run_flying(commands, timestamp); - } - - m_stream.log("No state handler for current state.", COLOR_RED); - return false; -} -bool EscapeFromAttack::run_flying(AsyncCommandSession& commands, WallClock timestamp){ - if (m_centerA.detected() && timestamp - last_state_change() > std::chrono::seconds(3)){ - return run_state_action(State::GET_ON_SNEASLER); - } - return run_state_action(State::DASH_FORWARD); -} -bool EscapeFromAttack::run_climbing(AsyncCommandSession& commands, WallClock timestamp){ - // Can't jump off means you're able to stand. Switch back to Braviary. - if (!m_leftB.detected()){ - return run_state_action(State::SNEASLER_OFF); - } - return run_state_action(State::CLIMBING); -} - - -} -} -} +/* Escape From Attack + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA_EscapeFromAttack.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +EscapeFromAttack::EscapeFromAttack( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + std::chrono::seconds time_min, + std::chrono::seconds time_limit +) + : SuperControlSession(env, stream, context) + , m_min_stop(current_time() + time_min) + , m_deadline(current_time() + time_limit) + , m_attacked(stream.logger()) + , m_mount(stream.logger()) + , m_centerA( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.40, 0.50, 0.40, 0.50}, + std::chrono::milliseconds(200), + false + ) + , m_leftB( + stream.logger(), stream.overlay(), + ButtonType::ButtonB, + {0.02, 0.40, 0.05, 0.20}, + std::chrono::milliseconds(200), + false + ) + , m_get_on_sneasler_time(WallClock::min()) +{ + *this += m_attacked; + *this += m_mount; + *this += m_centerA; + *this += m_leftB; + + const std::chrono::milliseconds GET_ON_BRAVIARY_TIME_MILLIS(GET_ON_BRAVIARY_TIME * 1000 / TICKS_PER_SECOND); + + register_state_command(State::UNKNOWN, [this](){ + m_stream.log("Unknown state. Moving forward..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 300 * TICKS_PER_SECOND, 0); + }); + return false; + }); + register_state_command(State::WYRDEER_BASCULEGION_OFF, [this](){ + m_stream.log("Switching from Wyrdeer/Basculegion (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::WYRDEER_BASCULEGION_ON, [this](){ + m_stream.log("Switching from Wyrdeer/Basculegion (on) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::URSALUNA_OFF, [this](){ + m_stream.log("Switching from Ursaluna (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::URSALUNA_ON, [this](){ + m_stream.log("Switching from Ursaluna (on) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::SNEASLER_OFF, [this](){ + m_stream.log("Switching from Sneasler (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::SNEASLER_ON, [this](){ + m_stream.log("Switching from Sneasler (on) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 125, 0); + pbf_press_dpad(context, DPAD_LEFT, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::BRAVIARY_OFF, [this](){ + m_stream.log("Switching from Braviary (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::DASH_FORWARD, [this, GET_ON_BRAVIARY_TIME_MILLIS](){ + bool delay_dash = + current_time() < m_get_on_sneasler_time + GET_ON_BRAVIARY_TIME_MILLIS; + if (delay_dash){ + m_stream.log("Dashing forward... (delayed due to being on Sneasler)"); + }else{ + m_stream.log("Dashing forward..."); + } + m_active_command->dispatch([delay_dash](ProControllerContext& context){ + if (delay_dash){ + pbf_move_left_joystick(context, 128, 0, 125, 0); + } + pbf_mash_button(context, BUTTON_B, 300 * TICKS_PER_SECOND); + }); + return false; + }); + register_state_command(State::GET_ON_SNEASLER, [this](){ + m_stream.log("Getting on Sneasler..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 20, 230); + }); + m_get_on_sneasler_time = current_time(); + return false; + }); + register_state_command(State::CLIMBING, [this](){ + m_stream.log("Climbing wall..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 300 * TICKS_PER_SECOND, 0); + }); + return false; + }); +} +bool EscapeFromAttack::run_state(AsyncCommandSession& commands, WallClock timestamp){ + if (timestamp > m_deadline){ + return true; + } + if (m_attacked.state() == UnderAttackState::SAFE && timestamp >= m_min_stop){ + return true; + } + + switch (m_mount.state()){ + case MountState::NOTHING: + return run_state_action(State::UNKNOWN); + case MountState::WYRDEER_OFF: + case MountState::BASCULEGION_OFF: + return run_state_action(State::WYRDEER_BASCULEGION_OFF); + case MountState::WYRDEER_ON: + case MountState::BASCULEGION_ON: + return run_state_action(State::WYRDEER_BASCULEGION_ON); + case MountState::URSALUNA_OFF: + return run_state_action(State::URSALUNA_OFF); + case MountState::URSALUNA_ON: + return run_state_action(State::URSALUNA_ON); + case MountState::SNEASLER_OFF: + return run_state_action(State::SNEASLER_OFF); + case MountState::SNEASLER_ON: + return run_climbing(commands, timestamp); + case MountState::BRAVIARY_OFF: + return run_state_action(State::BRAVIARY_OFF); + case MountState::BRAVIARY_ON: + return run_flying(commands, timestamp); + } + + m_stream.log("No state handler for current state.", COLOR_RED); + return false; +} +bool EscapeFromAttack::run_flying(AsyncCommandSession& commands, WallClock timestamp){ + if (m_centerA.detected() && timestamp - last_state_change() > std::chrono::seconds(3)){ + return run_state_action(State::GET_ON_SNEASLER); + } + return run_state_action(State::DASH_FORWARD); +} +bool EscapeFromAttack::run_climbing(AsyncCommandSession& commands, WallClock timestamp){ + // Can't jump off means you're able to stand. Switch back to Braviary. + if (!m_leftB.detected()){ + return run_state_action(State::SNEASLER_OFF); + } + return run_state_action(State::CLIMBING); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.h index 88116ae829..c122efcaf6 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_EscapeFromAttack.h @@ -1,82 +1,82 @@ -/* Escape From Attack - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_EscapeFromAttack_H -#define PokemonAutomation_PokemonLA_EscapeFromAttack_H - -#include "CommonTools/Async/SuperControlSession.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonLA/Inference/PokemonLA_UnderAttackDetector.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class EscapeFromAttack : public SuperControlSession{ -public: - EscapeFromAttack( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - std::chrono::seconds time_min, - std::chrono::seconds time_limit - ); - - UnderAttackState state() const{ - return m_attacked.state(); - } - - -private: - enum class State{ - UNKNOWN, - WYRDEER_BASCULEGION_OFF, - WYRDEER_BASCULEGION_ON, - URSALUNA_OFF, - URSALUNA_ON, - SNEASLER_OFF, - SNEASLER_ON, - BRAVIARY_OFF, - DASH_FORWARD, - GET_ON_SNEASLER, - CLIMBING, - }; - void register_state_command(State state, std::function&& action){ - SuperControlSession::register_state_command((size_t)state, std::move(action)); - } - bool run_state_action(State state){ - return SuperControlSession::run_state_action((size_t)state); - } - - virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) override; - - bool run_flying(AsyncCommandSession& commands, WallClock timestamp); - bool run_climbing(AsyncCommandSession& commands, WallClock timestamp); - -private: - static const uint16_t GET_ON_MOUNT_TIME = 125; - static const uint16_t GET_ON_BRAVIARY_TIME = 280; - - - const WallClock m_min_stop; - const WallClock m_deadline; - - UnderAttackWatcher m_attacked; - MountTracker m_mount; - ButtonDetector m_centerA; - ButtonDetector m_leftB; - - WallClock m_get_on_sneasler_time; -}; - - - -} -} -} -#endif +/* Escape From Attack + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_EscapeFromAttack_H +#define PokemonAutomation_PokemonLA_EscapeFromAttack_H + +#include "CommonTools/Async/SuperControlSession.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonLA/Inference/PokemonLA_UnderAttackDetector.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class EscapeFromAttack : public SuperControlSession{ +public: + EscapeFromAttack( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + std::chrono::seconds time_min, + std::chrono::seconds time_limit + ); + + UnderAttackState state() const{ + return m_attacked.state(); + } + + +private: + enum class State{ + UNKNOWN, + WYRDEER_BASCULEGION_OFF, + WYRDEER_BASCULEGION_ON, + URSALUNA_OFF, + URSALUNA_ON, + SNEASLER_OFF, + SNEASLER_ON, + BRAVIARY_OFF, + DASH_FORWARD, + GET_ON_SNEASLER, + CLIMBING, + }; + void register_state_command(State state, std::function&& action){ + SuperControlSession::register_state_command((size_t)state, std::move(action)); + } + bool run_state_action(State state){ + return SuperControlSession::run_state_action((size_t)state); + } + + virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) override; + + bool run_flying(AsyncCommandSession& commands, WallClock timestamp); + bool run_climbing(AsyncCommandSession& commands, WallClock timestamp); + +private: + static const uint16_t GET_ON_MOUNT_TIME = 125; + static const uint16_t GET_ON_BRAVIARY_TIME = 280; + + + const WallClock m_min_stop; + const WallClock m_deadline; + + UnderAttackWatcher m_attacked; + MountTracker m_mount; + ButtonDetector m_centerA; + ButtonDetector m_leftB; + + WallClock m_get_on_sneasler_time; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.cpp index 1ee3170f76..24dec0ba3f 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.cpp @@ -1,521 +1,521 @@ -/* Flag Navigation (Air) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA_FlagNavigationAir.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -FlagNavigationAir::FlagNavigationAir( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - uint16_t stop_radius, - double flag_reached_delay, - std::chrono::seconds navigate_timeout -) - : SuperControlSession(env, stream, context) - , m_stop_radius(stop_radius) - , m_flag_reached_delay(std::chrono::milliseconds((uint64_t)(flag_reached_delay * 1000))) - , m_navigate_timeout(navigate_timeout) - , m_flag(stream.logger(), stream.overlay()) - , m_mount(stream.logger()) - , m_centerA(stream.logger(), stream.overlay(), ButtonType::ButtonA, {0.40, 0.50, 0.40, 0.50}, std::chrono::milliseconds(200), false) - , m_leftB(stream.logger(), stream.overlay(), ButtonType::ButtonB, {0.02, 0.40, 0.05, 0.20}, std::chrono::milliseconds(200), false) - , m_dialog_detector(stream.logger(), stream.overlay(), false) - , m_looking_straight_ahead(false) - , m_looking_straight_ahead_timestamp(WallClock::min()) -// , m_last_good_state(WallClock::min()) - , m_last_known_mount(MountState::NOTHING) - , m_find_flag_failed(false) - , m_flag_reached_time(WallClock::max()) - , m_last_flag_detection(WallClock::min()) - , m_flag_distance(-1) - , m_flag_x(0.5) - , m_flag_y(0.0) - , m_last_flag_print(WallClock::min()) -{ - *this += m_flag; - *this += m_mount; - *this += m_centerA; - *this += m_leftB; - *this += m_dialog_detector; - - auto find_flag = [this](ProControllerContext& context){ - uint8_t turn = m_flag_x <= 0.5 ? 0 : 255; - for (size_t c = 0; c < 2; c++){ - pbf_mash_button(context, BUTTON_ZL, 2 * TICKS_PER_SECOND); - pbf_move_right_joystick(context, turn, 128, 400, 0); - pbf_move_right_joystick(context, 128, 255, 120, 0); - pbf_move_right_joystick(context, turn, 128, 400, 0); - pbf_move_right_joystick(context, 128, 0, 200, 0); - pbf_move_right_joystick(context, turn, 128, 400, 0); - } - context.wait_for_all_requests(); - m_find_flag_failed.store(true, std::memory_order_release); - }; - - register_state_command(State::UNKNOWN, [this, find_flag](){ - m_stream.log("Unknown state. Moving camera around..."); - m_active_command->dispatch(find_flag); - m_looking_straight_ahead.store(false, std::memory_order_release); - return false; - }); - register_state_command(State::WYRDEER_BASCULEGION_OFF, [this](){ - m_stream.log("Switching from Wyrdeer/Basculegion (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::WYRDEER_BASCULEGION_ON, [this](){ - m_stream.log("Switching from Wyrdeer/Basculegion (on) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::URSALUNA_OFF, [this](){ - m_stream.log("Switching from Ursaluna (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); -// pbf_press_dpad(context, DPAD_RIGHT, 20, 50); -// pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::URSALUNA_ON, [this](){ - m_stream.log("Switching from Ursaluna (on) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); -// pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::SNEASLER_OFF, [this](){ - m_stream.log("Switching from Sneasler (off) to Braviary (on)..."); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::SNEASLER_ON, [this](){ - m_stream.log("Switching from Sneasler (on) to Braviary (on)..."); - m_looking_straight_ahead.store(false, std::memory_order_release); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 125, 0); - pbf_press_dpad(context, DPAD_LEFT, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::BRAVIARY_OFF, [this](){ - m_stream.log("Switching from Braviary (off) to Braviary (on)..."); - m_looking_straight_ahead.store(false, std::memory_order_release); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); - }); - return false; - }); - register_state_command(State::GET_ON_SNEASLER, [this](){ - m_stream.log("Getting on Sneasler..."); - m_looking_straight_ahead.store(false, std::memory_order_release); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 20, 230); - }); - return false; - }); - register_state_command(State::CLIMBING, [this](){ - m_stream.log("Climbing wall..."); - m_looking_straight_ahead.store(false, std::memory_order_release); - m_active_command->dispatch([](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 300 * TICKS_PER_SECOND, 0); - }); - return false; - }); - - register_state_command(State::DASH_FORWARD_MASH_B, [this](){ - m_stream.log("Dashing forward (mash B)..."); - m_active_command->dispatch([this](ProControllerContext& context){ - // Move forward to straighten out direction. - if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ - pbf_move_left_joystick(context, 128, 0, 160, 0); - context.wait_for_all_requests(); - m_looking_straight_ahead_timestamp.store(current_time()); - m_looking_straight_ahead.store(true, std::memory_order_release); -// cout << "State::DASH_FORWARD: m_looking_straight_ahead = true" << endl; - } - pbf_mash_button(context, BUTTON_B, 300 * TICKS_PER_SECOND); - }); - return false; - }); - register_state_command(State::DASH_FORWARD_HOLD_B, [this](){ - m_stream.log("Dashing forward (hold B)..."); - m_active_command->dispatch([this](ProControllerContext& context){ - // Move forward to straighten out direction. - if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ - pbf_move_left_joystick(context, 128, 0, 160, 0); - context.wait_for_all_requests(); - m_looking_straight_ahead_timestamp.store(current_time()); - m_looking_straight_ahead.store(true, std::memory_order_release); -// cout << "State::DASH_FORWARD: m_looking_straight_ahead = true" << endl; - } - pbf_press_button(context, BUTTON_B, 300 * TICKS_PER_SECOND, 0); - }); - return false; - }); - - auto dash_turn = [this](){ - m_stream.log("Dashing Turn..."); - m_active_command->dispatch([this](ProControllerContext& context){ - // Move forward to straighten out direction. -// cout << "Straight ahead = " << m_looking_straight_ahead.load(std::memory_order_acquire) << endl; - if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ -// pbf_wait(context, 1000ms); - pbf_move_left_joystick(context, 128, 0, 160, 0); - context.wait_for_all_requests(); - m_looking_straight_ahead_timestamp.store(current_time()); - m_looking_straight_ahead.store(true, std::memory_order_release); -// cout << "State::DASH_LEFT: m_looking_straight_ahead = true" << endl; - } -// pbf_press_button(context, BUTTON_B, 10, 0); - double shift = 0; - double distance, flag_x, flag_y; - if (m_flag.get(distance, flag_x, flag_y)){ - shift = (flag_x - 0.5) * 320; - shift = std::max(shift, -32.); - shift = std::min(shift, 32.); - } - pbf_controller_state(context, BUTTON_B, DPAD_NONE, (int8_t)(128 + shift), 128, 128, 128, 255); - }); - return false; - }; - register_state_command(State::DASH_LEFT, dash_turn); - register_state_command(State::DASH_RIGHT, dash_turn); - - register_state_command(State::DIVE_STRAIGHT, [this](){ - m_stream.log("Diving Straight..."); - m_active_command->dispatch([this](ProControllerContext& context){ - // Move forward to straighten out direction. - if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ - pbf_move_left_joystick(context, 128, 0, 160, 0); - context.wait_for_all_requests(); - m_looking_straight_ahead_timestamp.store(current_time()); - m_looking_straight_ahead.store(true, std::memory_order_release); -// cout << "State::DASH_FORWARD: m_looking_straight_ahead = true" << endl; - } - pbf_press_button(context, BUTTON_Y, 60 * TICKS_PER_SECOND, 0); - }); - return false; - }); - - auto dive_turn = [this](){ - m_stream.log("Diving Turn..."); - m_active_command->dispatch([this](ProControllerContext& context){ - // Move forward to straighten out direction. - if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ - pbf_move_left_joystick(context, 128, 0, 160, 0); - context.wait_for_all_requests(); - m_looking_straight_ahead_timestamp.store(current_time()); - m_looking_straight_ahead.store(true, std::memory_order_release); -// cout << "State::DASH_LEFT: m_looking_straight_ahead = true" << endl; - } -// pbf_press_button(context, BUTTON_Y, 10, 0); - double shift = 0; - double distance, flag_x, flag_y; - if (m_flag.get(distance, flag_x, flag_y)){ - shift = (flag_x - 0.5) * 640; - shift = std::max(shift, -32.); - shift = std::min(shift, 32.); - } - pbf_controller_state(context, BUTTON_Y, DPAD_NONE, (int8_t)(128 + shift), 128, 128, 128, 125); - }); - return false; - }; - register_state_command(State::DIVE_LEFT, dive_turn); - register_state_command(State::DIVE_RIGHT, dive_turn); - - register_state_command(State::TURN_LEFT, [this](){ - m_stream.log("Turning Left..."); - m_active_command->dispatch([this](ProControllerContext& context){ - pbf_wait(context, 150); - context.wait_for_all_requests(); - double distance, flag_x, flag_y; - if (m_flag.get(distance, flag_x, flag_y)){ - pbf_move_right_joystick(context, 0, 128, (uint16_t)(85 * (0.5 - flag_x)), 0); - } - }); - m_looking_straight_ahead.store(false, std::memory_order_release); - return false; - }); - register_state_command(State::TURN_RIGHT, [this](){ - m_stream.log("Turning Right..."); - m_active_command->dispatch([this](ProControllerContext& context){ - pbf_wait(context, 150); - context.wait_for_all_requests(); - double distance, flag_x, flag_y; - if (m_flag.get(distance, flag_x, flag_y)){ - pbf_move_right_joystick(context, 255, 128, (uint16_t)(85 * (flag_x - 0.5)), 0); - } - }); - m_looking_straight_ahead.store(false, std::memory_order_release); - return false; - }); - - register_state_command(State::FIND_FLAG, [this, find_flag](){ - m_stream.log("Looking for flag..."); - m_active_command->dispatch(find_flag); - m_looking_straight_ahead.store(false, std::memory_order_release); - return false; - }); -} -void FlagNavigationAir::set_distance_callback(std::function flag_callback){ - m_flag_callback = std::move(flag_callback); -} - -bool FlagNavigationAir::run_state(AsyncCommandSession& commands, WallClock timestamp){ - if (last_state_change() + std::chrono::seconds(60) < timestamp){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state change detected after 60 seconds.", - m_stream - ); - } - if (start_time() + m_navigate_timeout < timestamp){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to reach flag after timeout period.", - m_stream - ); - } - if (m_dialog_detector.detected()){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Potential ambush by Miss Fortune sister.", - m_stream - ); - } - if (m_find_flag_failed.load(std::memory_order_acquire)){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to find flag.", - m_stream - ); - } - - // Read flag. - m_flag_detected = m_flag.get(m_flag_distance, m_flag_x, m_flag_y, timestamp); - if (m_flag_detected){ - m_last_flag_detection = timestamp; - if (m_flag_callback){ - m_flag_callback(m_flag_distance); - } - }else{ -// m_console.log("Flag not detected.", COLOR_ORANGE); - } -#if 1 - if (true - && m_flag_detected - && m_flag_distance >= 0 - && m_last_flag_print + std::chrono::seconds(1) <= timestamp - ){ - std::ostringstream ss; - ss << "Flag: Distance = " << (m_flag_distance < 0 ? "?" : std::to_string(m_flag_distance)) - << ", x = " << m_flag_x << ", y = " << m_flag_y << std::endl; - m_stream.log(ss.str(), COLOR_PURPLE); - m_last_flag_print = timestamp; - } -#endif - - - // Check if we've reached the flag. - if (m_flag_distance >= 0){ - if (m_flag_distance > m_stop_radius){ - // If we haven't reached the flag, reset the timer. - m_flag_reached_time = WallClock::max(); - }else if (m_flag_distance <= m_stop_radius && m_flag_reached_time == WallClock::max()){ - // If we've reached the flag, start timer if we haven't already. - m_stream.log("Target reached. Waiting out grace period..."); - m_flag_reached_time = timestamp; - } - } - if (m_flag_reached_time <= timestamp - m_flag_reached_delay){ - m_stream.log("Grace period finished. Stopping flag navigation..."); - return true; - } - - - MountState mount = m_mount.state(); - if (mount != MountState::NOTHING){ - m_last_known_mount = mount; - }else{ - m_stream.log( - std::string("Unable to detect mount. Assuming last known mount: ") + - MOUNT_STATE_STRINGS[(size_t)m_last_known_mount] - ); - mount = m_last_known_mount; - } - if (mount == MountState::NOTHING){ - return run_state_action(State::UNKNOWN); - } -#if 0 - if (mount == MountState::NOTHING){ - if (m_last_good_state + std::chrono::seconds(2) < timestamp){ - return run_state_action(State::UNKNOWN); - } - return false; - }else{ - m_last_good_state = timestamp; - } -#endif - - switch (mount){ - case MountState::NOTHING: - return false; - case MountState::WYRDEER_OFF: - case MountState::BASCULEGION_OFF: - return run_state_action(State::WYRDEER_BASCULEGION_OFF); - case MountState::WYRDEER_ON: - case MountState::BASCULEGION_ON: - return run_state_action(State::WYRDEER_BASCULEGION_ON); - case MountState::URSALUNA_OFF: - return run_state_action(State::URSALUNA_OFF); - case MountState::URSALUNA_ON: - return run_state_action(State::URSALUNA_ON); - case MountState::SNEASLER_OFF: - return run_state_action(State::SNEASLER_OFF); - case MountState::SNEASLER_ON: - return run_climbing(commands, timestamp); - case MountState::BRAVIARY_OFF: - return run_state_action(State::BRAVIARY_OFF); - case MountState::BRAVIARY_ON: - return run_flying(commands, timestamp); - } - - m_stream.log("No state handler for current state.", COLOR_RED); - return false; -} -bool FlagNavigationAir::run_flying(AsyncCommandSession& commands, WallClock timestamp){ - // Need to get on Sneasler. - if (m_centerA.detected() && last_state_change() + std::chrono::seconds(2) < timestamp){ - return run_state_action(State::GET_ON_SNEASLER); - } - -// cout << "m_last_known_flag_y = " << m_last_known_flag_y << endl; - - State state = (State)this->last_state(); -#if 0 - if (m_flag_y > 0.9 && last_state_change() + std::chrono::seconds(2) < timestamp){ -// cout << "state = " << (size_t)state << endl; - switch (state){ - case State::DASH_FORWARD_MASH_B: - case State::DASH_FORWARD_HOLD_B: - case State::DIVE: - m_console.log("Target passed under you. Target reached."); - return true; - default:; - } - } -#endif - -// if (m_last_flag_detection + std::chrono::seconds(20) < timestamp){ -// OperationFailedException::fire(m_console, "Flag not detected after 20 seconds.", true); -// } -// double flag_age = std::chrono::duration_cast(timestamp - m_last_flag_detection).count() / 1000.; -// if (flag_age > 0){ -// m_console.log("Flag Age = " + std::to_string(flag_age)); -// } - - // Flag is stale. - if (m_last_flag_detection + std::chrono::seconds(1) < timestamp){ - return run_state_action(State::FIND_FLAG); - } - - - // Re-center the flag. - if (m_flag_x <= 0.30){ - return run_state_action(State::TURN_LEFT); - } - if (m_flag_x >= 0.70){ - return run_state_action(State::TURN_RIGHT); - } - - // Dive - double dive_threshold = 0.80; - switch (state){ - case State::DIVE_STRAIGHT: - case State::DIVE_LEFT: - case State::DIVE_RIGHT: - dive_threshold = 0.10; - break; - case State::DASH_FORWARD_HOLD_B: - case State::DASH_FORWARD_MASH_B: - case State::DASH_LEFT: - case State::DASH_RIGHT:{ - if (m_looking_straight_ahead.load(std::memory_order_acquire) && - m_looking_straight_ahead_timestamp.load(std::memory_order_acquire) + std::chrono::seconds(1) < timestamp){ - dive_threshold = 0.45; - } - break; - } - default:; - } -// cout << "m_flag_y = " << m_flag_y << endl; - if (m_flag_detected && m_flag_y > dive_threshold){ - if (0.49 <= m_flag_x && m_flag_x <= 0.51){ - return run_state_action(State::DIVE_STRAIGHT); - }else{ - return run_state_action(m_flag_x < 0.5 ? State::DIVE_LEFT : State::DIVE_RIGHT); - } - } - - // Turning Cruise - if (0.48 > m_flag_x || m_flag_x > 0.52){ - return run_state_action(m_flag_x < 0.5 ? State::DASH_LEFT : State::DASH_RIGHT); - } - - // B-mash Cruise - return run_state_action(State::DASH_FORWARD_MASH_B); - -#if 0 - if (m_flag_y <= 0.40){ - // B-mash Cruise - return run_state_action(State::DASH_FORWARD_MASH_B); - }else{ - // Normal Cruise - return run_state_action(State::DASH_FORWARD_HOLD_B); - } - - // No known state left. - return run_state_action(State::DIVE_STRAIGHT); -#endif -} -bool FlagNavigationAir::run_climbing(AsyncCommandSession& commands, WallClock timestamp){ - // Can't jump off means you're able to stand. Switch back to Braviary. - if (!m_leftB.detected()){ - return run_state_action(State::SNEASLER_ON); - } - return run_state_action(State::CLIMBING); -} - - - - - - -} -} -} +/* Flag Navigation (Air) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA_FlagNavigationAir.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +FlagNavigationAir::FlagNavigationAir( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + uint16_t stop_radius, + double flag_reached_delay, + std::chrono::seconds navigate_timeout +) + : SuperControlSession(env, stream, context) + , m_stop_radius(stop_radius) + , m_flag_reached_delay(std::chrono::milliseconds((uint64_t)(flag_reached_delay * 1000))) + , m_navigate_timeout(navigate_timeout) + , m_flag(stream.logger(), stream.overlay()) + , m_mount(stream.logger()) + , m_centerA(stream.logger(), stream.overlay(), ButtonType::ButtonA, {0.40, 0.50, 0.40, 0.50}, std::chrono::milliseconds(200), false) + , m_leftB(stream.logger(), stream.overlay(), ButtonType::ButtonB, {0.02, 0.40, 0.05, 0.20}, std::chrono::milliseconds(200), false) + , m_dialog_detector(stream.logger(), stream.overlay(), false) + , m_looking_straight_ahead(false) + , m_looking_straight_ahead_timestamp(WallClock::min()) +// , m_last_good_state(WallClock::min()) + , m_last_known_mount(MountState::NOTHING) + , m_find_flag_failed(false) + , m_flag_reached_time(WallClock::max()) + , m_last_flag_detection(WallClock::min()) + , m_flag_distance(-1) + , m_flag_x(0.5) + , m_flag_y(0.0) + , m_last_flag_print(WallClock::min()) +{ + *this += m_flag; + *this += m_mount; + *this += m_centerA; + *this += m_leftB; + *this += m_dialog_detector; + + auto find_flag = [this](ProControllerContext& context){ + uint8_t turn = m_flag_x <= 0.5 ? 0 : 255; + for (size_t c = 0; c < 2; c++){ + pbf_mash_button(context, BUTTON_ZL, 2 * TICKS_PER_SECOND); + pbf_move_right_joystick(context, turn, 128, 400, 0); + pbf_move_right_joystick(context, 128, 255, 120, 0); + pbf_move_right_joystick(context, turn, 128, 400, 0); + pbf_move_right_joystick(context, 128, 0, 200, 0); + pbf_move_right_joystick(context, turn, 128, 400, 0); + } + context.wait_for_all_requests(); + m_find_flag_failed.store(true, std::memory_order_release); + }; + + register_state_command(State::UNKNOWN, [this, find_flag](){ + m_stream.log("Unknown state. Moving camera around..."); + m_active_command->dispatch(find_flag); + m_looking_straight_ahead.store(false, std::memory_order_release); + return false; + }); + register_state_command(State::WYRDEER_BASCULEGION_OFF, [this](){ + m_stream.log("Switching from Wyrdeer/Basculegion (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::WYRDEER_BASCULEGION_ON, [this](){ + m_stream.log("Switching from Wyrdeer/Basculegion (on) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::URSALUNA_OFF, [this](){ + m_stream.log("Switching from Ursaluna (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); +// pbf_press_dpad(context, DPAD_RIGHT, 20, 50); +// pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::URSALUNA_ON, [this](){ + m_stream.log("Switching from Ursaluna (on) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); +// pbf_press_dpad(context, DPAD_RIGHT, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::SNEASLER_OFF, [this](){ + m_stream.log("Switching from Sneasler (off) to Braviary (on)..."); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::SNEASLER_ON, [this](){ + m_stream.log("Switching from Sneasler (on) to Braviary (on)..."); + m_looking_straight_ahead.store(false, std::memory_order_release); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 125, 0); + pbf_press_dpad(context, DPAD_LEFT, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::BRAVIARY_OFF, [this](){ + m_stream.log("Switching from Braviary (off) to Braviary (on)..."); + m_looking_straight_ahead.store(false, std::memory_order_release); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_PLUS, 20, GET_ON_BRAVIARY_TIME); + }); + return false; + }); + register_state_command(State::GET_ON_SNEASLER, [this](){ + m_stream.log("Getting on Sneasler..."); + m_looking_straight_ahead.store(false, std::memory_order_release); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 20, 230); + }); + return false; + }); + register_state_command(State::CLIMBING, [this](){ + m_stream.log("Climbing wall..."); + m_looking_straight_ahead.store(false, std::memory_order_release); + m_active_command->dispatch([](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 300 * TICKS_PER_SECOND, 0); + }); + return false; + }); + + register_state_command(State::DASH_FORWARD_MASH_B, [this](){ + m_stream.log("Dashing forward (mash B)..."); + m_active_command->dispatch([this](ProControllerContext& context){ + // Move forward to straighten out direction. + if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ + pbf_move_left_joystick(context, 128, 0, 160, 0); + context.wait_for_all_requests(); + m_looking_straight_ahead_timestamp.store(current_time()); + m_looking_straight_ahead.store(true, std::memory_order_release); +// cout << "State::DASH_FORWARD: m_looking_straight_ahead = true" << endl; + } + pbf_mash_button(context, BUTTON_B, 300 * TICKS_PER_SECOND); + }); + return false; + }); + register_state_command(State::DASH_FORWARD_HOLD_B, [this](){ + m_stream.log("Dashing forward (hold B)..."); + m_active_command->dispatch([this](ProControllerContext& context){ + // Move forward to straighten out direction. + if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ + pbf_move_left_joystick(context, 128, 0, 160, 0); + context.wait_for_all_requests(); + m_looking_straight_ahead_timestamp.store(current_time()); + m_looking_straight_ahead.store(true, std::memory_order_release); +// cout << "State::DASH_FORWARD: m_looking_straight_ahead = true" << endl; + } + pbf_press_button(context, BUTTON_B, 300 * TICKS_PER_SECOND, 0); + }); + return false; + }); + + auto dash_turn = [this](){ + m_stream.log("Dashing Turn..."); + m_active_command->dispatch([this](ProControllerContext& context){ + // Move forward to straighten out direction. +// cout << "Straight ahead = " << m_looking_straight_ahead.load(std::memory_order_acquire) << endl; + if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ +// pbf_wait(context, 1000ms); + pbf_move_left_joystick(context, 128, 0, 160, 0); + context.wait_for_all_requests(); + m_looking_straight_ahead_timestamp.store(current_time()); + m_looking_straight_ahead.store(true, std::memory_order_release); +// cout << "State::DASH_LEFT: m_looking_straight_ahead = true" << endl; + } +// pbf_press_button(context, BUTTON_B, 10, 0); + double shift = 0; + double distance, flag_x, flag_y; + if (m_flag.get(distance, flag_x, flag_y)){ + shift = (flag_x - 0.5) * 320; + shift = std::max(shift, -32.); + shift = std::min(shift, 32.); + } + pbf_controller_state(context, BUTTON_B, DPAD_NONE, (int8_t)(128 + shift), 128, 128, 128, 255); + }); + return false; + }; + register_state_command(State::DASH_LEFT, dash_turn); + register_state_command(State::DASH_RIGHT, dash_turn); + + register_state_command(State::DIVE_STRAIGHT, [this](){ + m_stream.log("Diving Straight..."); + m_active_command->dispatch([this](ProControllerContext& context){ + // Move forward to straighten out direction. + if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ + pbf_move_left_joystick(context, 128, 0, 160, 0); + context.wait_for_all_requests(); + m_looking_straight_ahead_timestamp.store(current_time()); + m_looking_straight_ahead.store(true, std::memory_order_release); +// cout << "State::DASH_FORWARD: m_looking_straight_ahead = true" << endl; + } + pbf_press_button(context, BUTTON_Y, 60 * TICKS_PER_SECOND, 0); + }); + return false; + }); + + auto dive_turn = [this](){ + m_stream.log("Diving Turn..."); + m_active_command->dispatch([this](ProControllerContext& context){ + // Move forward to straighten out direction. + if (!m_looking_straight_ahead.load(std::memory_order_acquire)){ + pbf_move_left_joystick(context, 128, 0, 160, 0); + context.wait_for_all_requests(); + m_looking_straight_ahead_timestamp.store(current_time()); + m_looking_straight_ahead.store(true, std::memory_order_release); +// cout << "State::DASH_LEFT: m_looking_straight_ahead = true" << endl; + } +// pbf_press_button(context, BUTTON_Y, 10, 0); + double shift = 0; + double distance, flag_x, flag_y; + if (m_flag.get(distance, flag_x, flag_y)){ + shift = (flag_x - 0.5) * 640; + shift = std::max(shift, -32.); + shift = std::min(shift, 32.); + } + pbf_controller_state(context, BUTTON_Y, DPAD_NONE, (int8_t)(128 + shift), 128, 128, 128, 125); + }); + return false; + }; + register_state_command(State::DIVE_LEFT, dive_turn); + register_state_command(State::DIVE_RIGHT, dive_turn); + + register_state_command(State::TURN_LEFT, [this](){ + m_stream.log("Turning Left..."); + m_active_command->dispatch([this](ProControllerContext& context){ + pbf_wait(context, 150); + context.wait_for_all_requests(); + double distance, flag_x, flag_y; + if (m_flag.get(distance, flag_x, flag_y)){ + pbf_move_right_joystick(context, 0, 128, (uint16_t)(85 * (0.5 - flag_x)), 0); + } + }); + m_looking_straight_ahead.store(false, std::memory_order_release); + return false; + }); + register_state_command(State::TURN_RIGHT, [this](){ + m_stream.log("Turning Right..."); + m_active_command->dispatch([this](ProControllerContext& context){ + pbf_wait(context, 150); + context.wait_for_all_requests(); + double distance, flag_x, flag_y; + if (m_flag.get(distance, flag_x, flag_y)){ + pbf_move_right_joystick(context, 255, 128, (uint16_t)(85 * (flag_x - 0.5)), 0); + } + }); + m_looking_straight_ahead.store(false, std::memory_order_release); + return false; + }); + + register_state_command(State::FIND_FLAG, [this, find_flag](){ + m_stream.log("Looking for flag..."); + m_active_command->dispatch(find_flag); + m_looking_straight_ahead.store(false, std::memory_order_release); + return false; + }); +} +void FlagNavigationAir::set_distance_callback(std::function flag_callback){ + m_flag_callback = std::move(flag_callback); +} + +bool FlagNavigationAir::run_state(AsyncCommandSession& commands, WallClock timestamp){ + if (last_state_change() + std::chrono::seconds(60) < timestamp){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state change detected after 60 seconds.", + m_stream + ); + } + if (start_time() + m_navigate_timeout < timestamp){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to reach flag after timeout period.", + m_stream + ); + } + if (m_dialog_detector.detected()){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Potential ambush by Miss Fortune sister.", + m_stream + ); + } + if (m_find_flag_failed.load(std::memory_order_acquire)){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to find flag.", + m_stream + ); + } + + // Read flag. + m_flag_detected = m_flag.get(m_flag_distance, m_flag_x, m_flag_y, timestamp); + if (m_flag_detected){ + m_last_flag_detection = timestamp; + if (m_flag_callback){ + m_flag_callback(m_flag_distance); + } + }else{ +// m_console.log("Flag not detected.", COLOR_ORANGE); + } +#if 1 + if (true + && m_flag_detected + && m_flag_distance >= 0 + && m_last_flag_print + std::chrono::seconds(1) <= timestamp + ){ + std::ostringstream ss; + ss << "Flag: Distance = " << (m_flag_distance < 0 ? "?" : std::to_string(m_flag_distance)) + << ", x = " << m_flag_x << ", y = " << m_flag_y << std::endl; + m_stream.log(ss.str(), COLOR_PURPLE); + m_last_flag_print = timestamp; + } +#endif + + + // Check if we've reached the flag. + if (m_flag_distance >= 0){ + if (m_flag_distance > m_stop_radius){ + // If we haven't reached the flag, reset the timer. + m_flag_reached_time = WallClock::max(); + }else if (m_flag_distance <= m_stop_radius && m_flag_reached_time == WallClock::max()){ + // If we've reached the flag, start timer if we haven't already. + m_stream.log("Target reached. Waiting out grace period..."); + m_flag_reached_time = timestamp; + } + } + if (m_flag_reached_time <= timestamp - m_flag_reached_delay){ + m_stream.log("Grace period finished. Stopping flag navigation..."); + return true; + } + + + MountState mount = m_mount.state(); + if (mount != MountState::NOTHING){ + m_last_known_mount = mount; + }else{ + m_stream.log( + std::string("Unable to detect mount. Assuming last known mount: ") + + MOUNT_STATE_STRINGS[(size_t)m_last_known_mount] + ); + mount = m_last_known_mount; + } + if (mount == MountState::NOTHING){ + return run_state_action(State::UNKNOWN); + } +#if 0 + if (mount == MountState::NOTHING){ + if (m_last_good_state + std::chrono::seconds(2) < timestamp){ + return run_state_action(State::UNKNOWN); + } + return false; + }else{ + m_last_good_state = timestamp; + } +#endif + + switch (mount){ + case MountState::NOTHING: + return false; + case MountState::WYRDEER_OFF: + case MountState::BASCULEGION_OFF: + return run_state_action(State::WYRDEER_BASCULEGION_OFF); + case MountState::WYRDEER_ON: + case MountState::BASCULEGION_ON: + return run_state_action(State::WYRDEER_BASCULEGION_ON); + case MountState::URSALUNA_OFF: + return run_state_action(State::URSALUNA_OFF); + case MountState::URSALUNA_ON: + return run_state_action(State::URSALUNA_ON); + case MountState::SNEASLER_OFF: + return run_state_action(State::SNEASLER_OFF); + case MountState::SNEASLER_ON: + return run_climbing(commands, timestamp); + case MountState::BRAVIARY_OFF: + return run_state_action(State::BRAVIARY_OFF); + case MountState::BRAVIARY_ON: + return run_flying(commands, timestamp); + } + + m_stream.log("No state handler for current state.", COLOR_RED); + return false; +} +bool FlagNavigationAir::run_flying(AsyncCommandSession& commands, WallClock timestamp){ + // Need to get on Sneasler. + if (m_centerA.detected() && last_state_change() + std::chrono::seconds(2) < timestamp){ + return run_state_action(State::GET_ON_SNEASLER); + } + +// cout << "m_last_known_flag_y = " << m_last_known_flag_y << endl; + + State state = (State)this->last_state(); +#if 0 + if (m_flag_y > 0.9 && last_state_change() + std::chrono::seconds(2) < timestamp){ +// cout << "state = " << (size_t)state << endl; + switch (state){ + case State::DASH_FORWARD_MASH_B: + case State::DASH_FORWARD_HOLD_B: + case State::DIVE: + m_console.log("Target passed under you. Target reached."); + return true; + default:; + } + } +#endif + +// if (m_last_flag_detection + std::chrono::seconds(20) < timestamp){ +// OperationFailedException::fire(m_console, "Flag not detected after 20 seconds.", true); +// } +// double flag_age = std::chrono::duration_cast(timestamp - m_last_flag_detection).count() / 1000.; +// if (flag_age > 0){ +// m_console.log("Flag Age = " + std::to_string(flag_age)); +// } + + // Flag is stale. + if (m_last_flag_detection + std::chrono::seconds(1) < timestamp){ + return run_state_action(State::FIND_FLAG); + } + + + // Re-center the flag. + if (m_flag_x <= 0.30){ + return run_state_action(State::TURN_LEFT); + } + if (m_flag_x >= 0.70){ + return run_state_action(State::TURN_RIGHT); + } + + // Dive + double dive_threshold = 0.80; + switch (state){ + case State::DIVE_STRAIGHT: + case State::DIVE_LEFT: + case State::DIVE_RIGHT: + dive_threshold = 0.10; + break; + case State::DASH_FORWARD_HOLD_B: + case State::DASH_FORWARD_MASH_B: + case State::DASH_LEFT: + case State::DASH_RIGHT:{ + if (m_looking_straight_ahead.load(std::memory_order_acquire) && + m_looking_straight_ahead_timestamp.load(std::memory_order_acquire) + std::chrono::seconds(1) < timestamp){ + dive_threshold = 0.45; + } + break; + } + default:; + } +// cout << "m_flag_y = " << m_flag_y << endl; + if (m_flag_detected && m_flag_y > dive_threshold){ + if (0.49 <= m_flag_x && m_flag_x <= 0.51){ + return run_state_action(State::DIVE_STRAIGHT); + }else{ + return run_state_action(m_flag_x < 0.5 ? State::DIVE_LEFT : State::DIVE_RIGHT); + } + } + + // Turning Cruise + if (0.48 > m_flag_x || m_flag_x > 0.52){ + return run_state_action(m_flag_x < 0.5 ? State::DASH_LEFT : State::DASH_RIGHT); + } + + // B-mash Cruise + return run_state_action(State::DASH_FORWARD_MASH_B); + +#if 0 + if (m_flag_y <= 0.40){ + // B-mash Cruise + return run_state_action(State::DASH_FORWARD_MASH_B); + }else{ + // Normal Cruise + return run_state_action(State::DASH_FORWARD_HOLD_B); + } + + // No known state left. + return run_state_action(State::DIVE_STRAIGHT); +#endif +} +bool FlagNavigationAir::run_climbing(AsyncCommandSession& commands, WallClock timestamp){ + // Can't jump off means you're able to stand. Switch back to Braviary. + if (!m_leftB.detected()){ + return run_state_action(State::SNEASLER_ON); + } + return run_state_action(State::CLIMBING); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.h index 5287e048b1..7a506f97bd 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_FlagNavigationAir.h @@ -1,111 +1,111 @@ -/* Flag Navigation (Air) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_FlagNavigation_H -#define PokemonAutomation_PokemonLA_FlagNavigation_H - -#include "CommonTools/Async/SuperControlSession.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class FlagNavigationAir : public SuperControlSession{ -public: - FlagNavigationAir( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - uint16_t stop_radius, - double flag_reached_delay, - std::chrono::seconds navigate_timeout - ); - - void set_distance_callback(std::function flag_callback); - - -private: - virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) override; - - bool run_flying(AsyncCommandSession& commands, WallClock timestamp); - bool run_climbing(AsyncCommandSession& commands, WallClock timestamp); - - -private: - static const uint16_t GET_ON_MOUNT_TIME = 125; - static const uint16_t GET_ON_BRAVIARY_TIME = 280; - - enum class State{ - UNKNOWN, - WYRDEER_BASCULEGION_OFF, - WYRDEER_BASCULEGION_ON, - URSALUNA_OFF, - URSALUNA_ON, - SNEASLER_OFF, - SNEASLER_ON, - BRAVIARY_OFF, - GET_ON_SNEASLER, - CLIMBING, - DASH_FORWARD_MASH_B, - DASH_FORWARD_HOLD_B, - DASH_LEFT, - DASH_RIGHT, - DIVE_STRAIGHT, - DIVE_LEFT, - DIVE_RIGHT, - TURN_LEFT, - TURN_RIGHT, - FIND_FLAG, - }; - void register_state_command(State state, std::function&& action){ - SuperControlSession::register_state_command((size_t)state, std::move(action)); - } - bool run_state_action(State state){ - return SuperControlSession::run_state_action((size_t)state); - } - - uint16_t m_stop_radius; - std::chrono::milliseconds m_flag_reached_delay; - std::chrono::seconds m_navigate_timeout; - - std::function m_flag_callback; - - FlagTracker m_flag; - MountTracker m_mount; - ButtonDetector m_centerA; - ButtonDetector m_leftB; - DialogSurpriseDetector m_dialog_detector; - - std::atomic m_looking_straight_ahead; - std::atomic m_looking_straight_ahead_timestamp; -// WallClock m_last_good_state; - MountState m_last_known_mount; - - std::atomic m_find_flag_failed; - WallClock m_flag_reached_time; - - WallClock m_last_flag_detection; - bool m_flag_detected; - - // Last known values. - double m_flag_distance; - double m_flag_x; - double m_flag_y; - - WallClock m_last_flag_print; -}; - - - -} -} -} -#endif +/* Flag Navigation (Air) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_FlagNavigation_H +#define PokemonAutomation_PokemonLA_FlagNavigation_H + +#include "CommonTools/Async/SuperControlSession.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class FlagNavigationAir : public SuperControlSession{ +public: + FlagNavigationAir( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + uint16_t stop_radius, + double flag_reached_delay, + std::chrono::seconds navigate_timeout + ); + + void set_distance_callback(std::function flag_callback); + + +private: + virtual bool run_state(AsyncCommandSession& commands, WallClock timestamp) override; + + bool run_flying(AsyncCommandSession& commands, WallClock timestamp); + bool run_climbing(AsyncCommandSession& commands, WallClock timestamp); + + +private: + static const uint16_t GET_ON_MOUNT_TIME = 125; + static const uint16_t GET_ON_BRAVIARY_TIME = 280; + + enum class State{ + UNKNOWN, + WYRDEER_BASCULEGION_OFF, + WYRDEER_BASCULEGION_ON, + URSALUNA_OFF, + URSALUNA_ON, + SNEASLER_OFF, + SNEASLER_ON, + BRAVIARY_OFF, + GET_ON_SNEASLER, + CLIMBING, + DASH_FORWARD_MASH_B, + DASH_FORWARD_HOLD_B, + DASH_LEFT, + DASH_RIGHT, + DIVE_STRAIGHT, + DIVE_LEFT, + DIVE_RIGHT, + TURN_LEFT, + TURN_RIGHT, + FIND_FLAG, + }; + void register_state_command(State state, std::function&& action){ + SuperControlSession::register_state_command((size_t)state, std::move(action)); + } + bool run_state_action(State state){ + return SuperControlSession::run_state_action((size_t)state); + } + + uint16_t m_stop_radius; + std::chrono::milliseconds m_flag_reached_delay; + std::chrono::seconds m_navigate_timeout; + + std::function m_flag_callback; + + FlagTracker m_flag; + MountTracker m_mount; + ButtonDetector m_centerA; + ButtonDetector m_leftB; + DialogSurpriseDetector m_dialog_detector; + + std::atomic m_looking_straight_ahead; + std::atomic m_looking_straight_ahead_timestamp; +// WallClock m_last_good_state; + MountState m_last_known_mount; + + std::atomic m_find_flag_failed; + WallClock m_flag_reached_time; + + WallClock m_last_flag_detection; + bool m_flag_detected; + + // Last known values. + double m_flag_distance; + double m_flag_x; + double m_flag_y; + + WallClock m_last_flag_print; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.cpp index 303bdd1426..e530b1fb72 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.cpp @@ -1,105 +1,105 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA_GameEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -bool reset_game_to_gamemenu( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu -){ - bool video_available = (bool)console.video().snapshot(); - if (video_available || - ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || - tolerate_update_menu - ){ - close_game(console, context); - start_game_from_home( - console, - context, - tolerate_update_menu, - 0, 0, - GameSettings::instance().START_GAME_MASH0 - ); - }else{ - pbf_press_button(context, BUTTON_X, 50, 0); - pbf_mash_button(context, BUTTON_A, GameSettings::instance().START_GAME_MASH0); - } - - // Now the game has opened: - return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT1); -} - -bool gamemenu_to_ingame( - VideoStream& stream, ProControllerContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -){ - stream.log("Mashing A to enter game..."); - BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); - pbf_mash_button(context, BUTTON_A, mash_duration); - context.wait_for_all_requests(); - stream.log("Waiting to enter game..."); - int ret = wait_until( - stream, context, - std::chrono::milliseconds(enter_game_timeout * (1000 / TICKS_PER_SECOND)), - {{detector}} - ); - if (ret == 0){ - stream.log("Entered game!"); - return true; - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } -} - -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint16_t post_wait_time -){ - bool ok = true; - ok &= reset_game_to_gamemenu(console, context, tolerate_update_menu); - ok &= gamemenu_to_ingame( - console, context, - GameSettings::instance().ENTER_GAME_MASH0, - GameSettings::instance().ENTER_GAME_WAIT0 - ); - if (!ok){ - dump_image(console.logger(), env.program_info(), console.video(), "StartGame"); - } - console.log("Entered game! Waiting out grace period."); - pbf_wait(context, post_wait_time); - context.wait_for_all_requests(); - return ok; -} - - - - - -} -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA_GameEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +bool reset_game_to_gamemenu( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu +){ + bool video_available = (bool)console.video().snapshot(); + if (video_available || + ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || + tolerate_update_menu + ){ + close_game(console, context); + start_game_from_home( + console, + context, + tolerate_update_menu, + 0, 0, + GameSettings::instance().START_GAME_MASH0 + ); + }else{ + pbf_press_button(context, BUTTON_X, 50, 0); + pbf_mash_button(context, BUTTON_A, GameSettings::instance().START_GAME_MASH0); + } + + // Now the game has opened: + return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT1); +} + +bool gamemenu_to_ingame( + VideoStream& stream, ProControllerContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +){ + stream.log("Mashing A to enter game..."); + BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); + pbf_mash_button(context, BUTTON_A, mash_duration); + context.wait_for_all_requests(); + stream.log("Waiting to enter game..."); + int ret = wait_until( + stream, context, + std::chrono::milliseconds(enter_game_timeout * (1000 / TICKS_PER_SECOND)), + {{detector}} + ); + if (ret == 0){ + stream.log("Entered game!"); + return true; + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } +} + +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint16_t post_wait_time +){ + bool ok = true; + ok &= reset_game_to_gamemenu(console, context, tolerate_update_menu); + ok &= gamemenu_to_ingame( + console, context, + GameSettings::instance().ENTER_GAME_MASH0, + GameSettings::instance().ENTER_GAME_WAIT0 + ); + if (!ok){ + dump_image(console.logger(), env.program_info(), console.video(), "StartGame"); + } + console.log("Entered game! Waiting out grace period."); + pbf_wait(context, post_wait_time); + context.wait_for_all_requests(); + return ok; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.h index 4fa91250fa..88a60ce17e 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameEntry.h @@ -1,51 +1,51 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_GameEntry_H -#define PokemonAutomation_PokemonLA_GameEntry_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -// From Switch Home menu, reset game and wait until the game menu screen (where -// "Press A" is displayed to enter the game) is shown. -bool reset_game_to_gamemenu( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu -); - -// From the game menu screen (where "Press A" is displayed to enter the game), -// mash A to enter the game and wait until the black screen is gone. -bool gamemenu_to_ingame( - VideoStream& stream, ProControllerContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -); - -// From Switch Home menu, start game and wait until the player character appears in game. -// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint16_t post_wait_time = 125 -); - - - - -} -} -} -#endif +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_GameEntry_H +#define PokemonAutomation_PokemonLA_GameEntry_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +// From Switch Home menu, reset game and wait until the game menu screen (where +// "Press A" is displayed to enter the game) is shown. +bool reset_game_to_gamemenu( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu +); + +// From the game menu screen (where "Press A" is displayed to enter the game), +// mash A to enter the game and wait until the black screen is gone. +bool gamemenu_to_ingame( + VideoStream& stream, ProControllerContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +); + +// From Switch Home menu, start game and wait until the player character appears in game. +// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint16_t post_wait_time = 125 +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.cpp index ca6fd4a0e3..879d06ec8f 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.cpp @@ -1,128 +1,128 @@ -/* Game Save - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA_GameSave.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -namespace{ - -const ImageFloatBox tab_box{0.450, 0.005, 0.040, 0.010}; -const ImageFloatBox save_icon_box{0.456, 0.015, 0.026, 0.041}; - -} - - -bool save_tab_selected(const ImageViewRGB32 &screen){ - - const ImageStats stats = image_stats(extract_box_reference(screen, tab_box)); - return (stats.stddev.sum() < 15 && - stats.average.b > stats.average.r && stats.average.b > stats.average.g - ); -} - -bool save_tab_disabled(const ImageViewRGB32 &screen){ - - // Replace white background with zero-alpha color so that they won't be counted in - // the following image_stats() - // The white background is defined as the color between 0xffa0a0a0 and 0xffffffff. - const bool replace_background = true; - ImageRGB32 region = filter_rgb32_range( - extract_box_reference(screen, save_icon_box), - 0xffa0a0a0, 0xffffffff, Color(0), replace_background - ); - - ImageStats stats = image_stats(region); - // cout << "color " << stats.count << " " << stats.average.to_string() << endl; - return (stats.average.r > stats.average.b + 50.0); -} - - -bool save_game_from_overworld( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context -){ - OverlayBoxScope tab_box_scope(stream.overlay(), tab_box); - OverlayBoxScope icon_box_scope(stream.overlay(), save_icon_box); - stream.log("Saving game..."); - stream.overlay().add_log("Saving game...", COLOR_WHITE); - - // Press DPAD_UP to open menu - pbf_press_dpad(context, DPAD_UP, 20, 120); - context.wait_for_all_requests(); - auto snapshot = stream.video().snapshot(); - if (save_tab_disabled(snapshot)){ - return false; - } - - bool found = false; - for (size_t c = 0; c < 10; c++){ - if (save_tab_selected(snapshot)){ - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); -// pbf_press_button(context, BUTTON_B, 20, 105); - context.wait_for_all_requests(); - found = true; - break; - } - pbf_press_button(context, BUTTON_ZR, 20, 80); - context.wait_for_all_requests(); - snapshot = stream.video().snapshot(); - } - if (!found){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find save menu.", - stream - ); - } - - ArcPhoneDetector detector(stream.logger(), stream.overlay(), std::chrono::milliseconds(100), true); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_B, 20, 230); - } - }, - {detector} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to return to overworld.", - stream - ); - } - stream.log("Saving game... Done."); - - return true; -} - - - - - -} -} -} +/* Game Save + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA_GameSave.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +namespace{ + +const ImageFloatBox tab_box{0.450, 0.005, 0.040, 0.010}; +const ImageFloatBox save_icon_box{0.456, 0.015, 0.026, 0.041}; + +} + + +bool save_tab_selected(const ImageViewRGB32 &screen){ + + const ImageStats stats = image_stats(extract_box_reference(screen, tab_box)); + return (stats.stddev.sum() < 15 && + stats.average.b > stats.average.r && stats.average.b > stats.average.g + ); +} + +bool save_tab_disabled(const ImageViewRGB32 &screen){ + + // Replace white background with zero-alpha color so that they won't be counted in + // the following image_stats() + // The white background is defined as the color between 0xffa0a0a0 and 0xffffffff. + const bool replace_background = true; + ImageRGB32 region = filter_rgb32_range( + extract_box_reference(screen, save_icon_box), + 0xffa0a0a0, 0xffffffff, Color(0), replace_background + ); + + ImageStats stats = image_stats(region); + // cout << "color " << stats.count << " " << stats.average.to_string() << endl; + return (stats.average.r > stats.average.b + 50.0); +} + + +bool save_game_from_overworld( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context +){ + OverlayBoxScope tab_box_scope(stream.overlay(), tab_box); + OverlayBoxScope icon_box_scope(stream.overlay(), save_icon_box); + stream.log("Saving game..."); + stream.overlay().add_log("Saving game...", COLOR_WHITE); + + // Press DPAD_UP to open menu + pbf_press_dpad(context, DPAD_UP, 20, 120); + context.wait_for_all_requests(); + auto snapshot = stream.video().snapshot(); + if (save_tab_disabled(snapshot)){ + return false; + } + + bool found = false; + for (size_t c = 0; c < 10; c++){ + if (save_tab_selected(snapshot)){ + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); +// pbf_press_button(context, BUTTON_B, 20, 105); + context.wait_for_all_requests(); + found = true; + break; + } + pbf_press_button(context, BUTTON_ZR, 20, 80); + context.wait_for_all_requests(); + snapshot = stream.video().snapshot(); + } + if (!found){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find save menu.", + stream + ); + } + + ArcPhoneDetector detector(stream.logger(), stream.overlay(), std::chrono::milliseconds(100), true); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_B, 20, 230); + } + }, + {detector} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to return to overworld.", + stream + ); + } + stream.log("Saving game... Done."); + + return true; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.h index 150ab22f5e..74cc9b4189 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_GameSave.h @@ -1,39 +1,39 @@ -/* Game Save - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_GameSave_H -#define PokemonAutomation_PokemonLA_GameSave_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonLA{ - -// Whether the current tab is the save game tab -bool save_tab_selected(const ImageViewRGB32 &screen); - -// Whether the save game tab is disabled: a red "forbidden" synbol appears on the location of the save game tab icon. -bool save_tab_disabled(const ImageViewRGB32 &screen); - -// Open menu to save game. Return true if success. -// Return false if in current state the game cannot be saved. This can happen if the player character is in the air -// or is rolling or falling. -bool save_game_from_overworld( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context -); - - - - -} -} -} -#endif +/* Game Save + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_GameSave_H +#define PokemonAutomation_PokemonLA_GameSave_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonLA{ + +// Whether the current tab is the save game tab +bool save_tab_selected(const ImageViewRGB32 &screen); + +// Whether the save game tab is disabled: a red "forbidden" synbol appears on the location of the save game tab icon. +bool save_tab_disabled(const ImageViewRGB32 &screen); + +// Open menu to save game. Return true if success. +// Return false if in current state the game cannot be saved. This can happen if the player character is in the air +// or is rolling or falling. +bool save_game_from_overworld( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.cpp index ac28913405..04e2805df3 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.cpp @@ -1,286 +1,286 @@ -/* Leap Pokemon Actions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" -#include "PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA_MountChange.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA_RegionNavigation.h" -#include "PokemonLA_BattleRoutines.h" -#include "PokemonLA_LeapPokemonActions.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -void route(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon){ - switch (pokemon){ - case LeapPokemon::Aipom: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Coastlands_Beachside); - pbf_move_left_joystick(context, 238, 255, 30, 30); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (20 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, (1 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 160, 30, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 127, 0, (3 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Burmy: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Heights); - pbf_move_left_joystick(context, 170, 255, 30, 30); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(6.35 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(1.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 127, 30, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.10 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Cherrim: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Mountain); - pbf_move_left_joystick(context, 255, 35, 30, 30); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(3.35 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(1.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 0, 127, 20, 20); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.20 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Cherubi: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Arena); - pbf_move_left_joystick(context, 255, 152, 30, 30); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(25.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Combee: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Arena); - pbf_move_left_joystick(context, 57, 255, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(2.75 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Heracross: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Mountain); - pbf_move_left_joystick(context, 0, 220, 30, 30); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 127, 0, (4 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.17 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Pachirisu: - case LeapPokemon::Vespiquen: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Mirelands_Bogbound); - pbf_move_left_joystick(context, 0, 170, 30, 30); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(10.2 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Wormadam: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Fieldlands); - pbf_move_left_joystick(context, 110, 255, 30, 30); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(6.25 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 100, 20, 20); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Geodude: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Heights); - pbf_move_left_joystick(context, 200, 255, 20, 20); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(3.75 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 127, 255, 20, 20); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Graveler: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Highlands); - pbf_move_left_joystick(context, 255, 145, 20, 20); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 127, 0, (5 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Bonsly: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Mirelands_DiamondSettlement); - pbf_move_left_joystick(context, 0, 150, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::BRAVIARY_ON); - pbf_move_left_joystick(context, 127, 0, (10 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Bronzor: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Mountain); - pbf_move_left_joystick(context, 55, 255, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::WYRDEER_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(6.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Nosepass: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Summit); - pbf_move_left_joystick(context, 255, 175, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::WYRDEER_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(2.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - case LeapPokemon::Bergimite: - goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Icelands_Snowfields); - pbf_move_left_joystick(context, 115, 255, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(stream, context, MountState::WYRDEER_ON); - pbf_press_button(context, BUTTON_B, (uint16_t)(3.2 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); - break; - } - context.wait_for_all_requests(); -} - -void return_to_jubilife(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon){ - goto_camp_from_overworld(env, stream, context); - switch (pokemon){ - case LeapPokemon::Aipom: - goto_professor(stream.logger(), context, Camp::COASTLANDS_BEACHSIDE); - break; - case LeapPokemon::Burmy: - case LeapPokemon::Cherubi: - case LeapPokemon::Combee: - case LeapPokemon::Wormadam: - case LeapPokemon::Geodude: - goto_professor(stream.logger(), context, Camp::FIELDLANDS_FIELDLANDS); - break; - case LeapPokemon::Cherrim: - case LeapPokemon::Heracross: - case LeapPokemon::Graveler: - case LeapPokemon::Bronzor: - case LeapPokemon::Nosepass: - goto_professor(stream.logger(), context, Camp::HIGHLANDS_HIGHLANDS); - break; - case LeapPokemon::Pachirisu: - case LeapPokemon::Vespiquen: - case LeapPokemon::Bonsly: - goto_professor(stream.logger(), context, Camp::MIRELANDS_MIRELANDS); - break; - case LeapPokemon::Bergimite: - goto_professor(stream.logger(), context, Camp::ICELANDS_SNOWFIELDS); - break; - } - from_professor_return_to_jubilife(env, stream, context); - context.wait_for_all_requests(); -} - -bool check_tree_or_ore_for_battle(VideoStream& stream, ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZR, (uint16_t)(0.5 * TICKS_PER_SECOND), 20); //throw pokemon - pbf_wait(context, (uint16_t)(4.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - - MountDetector mount_detector; - - VideoSnapshot snapshot = stream.video().snapshot(); - MountState mount = mount_detector.detect(snapshot); - bool found = false; - for (int i = 0; i < 4; i++){ - if (mount == MountState::NOTHING){ - found = true; - break; - }else{ - stream.log("Attempt " + std::to_string(i) + ". Found: " + MOUNT_STATE_STRINGS[(int)mount]); - pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - snapshot = stream.video().snapshot(); - } - mount = mount_detector.detect(snapshot); - } - - if (!found){ - stream.log("Battle not found. Tree or ore might be empty."); - return false; - } - - stream.log("Mount icon seems to be gone, waiting for battle menu..."); - - BattleMenuDetector battle_menu_detector(stream.logger(), stream.overlay(), true); - wait_until( - stream, context, std::chrono::seconds(10), - {{battle_menu_detector}} - ); - - if(battle_menu_detector.detected()){ - stream.log("Battle found!"); - return true; - } - - stream.log("Battle menu not found. Tree or ore might be empty."); - return false; -} - -void exit_battle(VideoStream& stream, ProControllerContext& context, ExitBattleMethod exit_method){ -// pbf_press_button(context, BUTTON_B, 20, 225); - - if (exit_method == ExitBattleMethod::RunAway){ - stream.log("Running from battle..."); - pbf_press_button(context, BUTTON_B, 20, 225); - pbf_press_button(context, BUTTON_A, 20, 100 + (uint16_t)(3.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - return; - } - - context.wait_for_all_requests(); - stream.log("Mashing A to battle!"); - mash_A_until_end_of_battle(stream, context); -} - -PokemonDetails get_pokemon_details(VideoStream& stream, ProControllerContext& context, Language language){ - // Open Info Screen - pbf_wait(context, 1000ms); - pbf_press_button(context, BUTTON_PLUS, 500ms, 1000ms); - pbf_press_button(context, BUTTON_R, 500ms, 1000ms); - - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - - return read_status_info(stream.logger(), stream.overlay(), screen, language); -} - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Leap Pokemon Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" +#include "PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA_MountChange.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA_RegionNavigation.h" +#include "PokemonLA_BattleRoutines.h" +#include "PokemonLA_LeapPokemonActions.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +void route(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon){ + switch (pokemon){ + case LeapPokemon::Aipom: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Coastlands_Beachside); + pbf_move_left_joystick(context, 238, 255, 30, 30); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (20 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, (1 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 160, 30, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 127, 0, (3 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Burmy: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Heights); + pbf_move_left_joystick(context, 170, 255, 30, 30); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(6.35 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(1.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 127, 30, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.10 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Cherrim: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Mountain); + pbf_move_left_joystick(context, 255, 35, 30, 30); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(3.35 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(1.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 0, 127, 20, 20); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.20 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Cherubi: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Arena); + pbf_move_left_joystick(context, 255, 152, 30, 30); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(25.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Combee: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Arena); + pbf_move_left_joystick(context, 57, 255, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(2.75 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Heracross: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Mountain); + pbf_move_left_joystick(context, 0, 220, 30, 30); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 127, 0, (4 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.17 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Pachirisu: + case LeapPokemon::Vespiquen: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Mirelands_Bogbound); + pbf_move_left_joystick(context, 0, 170, 30, 30); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(10.2 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Wormadam: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Fieldlands); + pbf_move_left_joystick(context, 110, 255, 30, 30); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(6.25 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 100, 20, 20); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Geodude: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Fieldlands_Heights); + pbf_move_left_joystick(context, 200, 255, 20, 20); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(3.75 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 127, 255, 20, 20); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Graveler: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Highlands); + pbf_move_left_joystick(context, 255, 145, 20, 20); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 127, 0, (5 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Bonsly: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Mirelands_DiamondSettlement); + pbf_move_left_joystick(context, 0, 150, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::BRAVIARY_ON); + pbf_move_left_joystick(context, 127, 0, (10 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Bronzor: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Mountain); + pbf_move_left_joystick(context, 55, 255, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::WYRDEER_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(6.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Nosepass: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Highlands_Summit); + pbf_move_left_joystick(context, 255, 175, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::WYRDEER_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(2.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + case LeapPokemon::Bergimite: + goto_camp_from_jubilife(env, stream, context, TravelLocations::instance().Icelands_Snowfields); + pbf_move_left_joystick(context, 115, 255, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(stream, context, MountState::WYRDEER_ON); + pbf_press_button(context, BUTTON_B, (uint16_t)(3.2 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (uint16_t)(0.2 * TICKS_PER_SECOND), (uint16_t)(0.5 * TICKS_PER_SECOND)); + break; + } + context.wait_for_all_requests(); +} + +void return_to_jubilife(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon){ + goto_camp_from_overworld(env, stream, context); + switch (pokemon){ + case LeapPokemon::Aipom: + goto_professor(stream.logger(), context, Camp::COASTLANDS_BEACHSIDE); + break; + case LeapPokemon::Burmy: + case LeapPokemon::Cherubi: + case LeapPokemon::Combee: + case LeapPokemon::Wormadam: + case LeapPokemon::Geodude: + goto_professor(stream.logger(), context, Camp::FIELDLANDS_FIELDLANDS); + break; + case LeapPokemon::Cherrim: + case LeapPokemon::Heracross: + case LeapPokemon::Graveler: + case LeapPokemon::Bronzor: + case LeapPokemon::Nosepass: + goto_professor(stream.logger(), context, Camp::HIGHLANDS_HIGHLANDS); + break; + case LeapPokemon::Pachirisu: + case LeapPokemon::Vespiquen: + case LeapPokemon::Bonsly: + goto_professor(stream.logger(), context, Camp::MIRELANDS_MIRELANDS); + break; + case LeapPokemon::Bergimite: + goto_professor(stream.logger(), context, Camp::ICELANDS_SNOWFIELDS); + break; + } + from_professor_return_to_jubilife(env, stream, context); + context.wait_for_all_requests(); +} + +bool check_tree_or_ore_for_battle(VideoStream& stream, ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZR, (uint16_t)(0.5 * TICKS_PER_SECOND), 20); //throw pokemon + pbf_wait(context, (uint16_t)(4.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + + MountDetector mount_detector; + + VideoSnapshot snapshot = stream.video().snapshot(); + MountState mount = mount_detector.detect(snapshot); + bool found = false; + for (int i = 0; i < 4; i++){ + if (mount == MountState::NOTHING){ + found = true; + break; + }else{ + stream.log("Attempt " + std::to_string(i) + ". Found: " + MOUNT_STATE_STRINGS[(int)mount]); + pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + snapshot = stream.video().snapshot(); + } + mount = mount_detector.detect(snapshot); + } + + if (!found){ + stream.log("Battle not found. Tree or ore might be empty."); + return false; + } + + stream.log("Mount icon seems to be gone, waiting for battle menu..."); + + BattleMenuDetector battle_menu_detector(stream.logger(), stream.overlay(), true); + wait_until( + stream, context, std::chrono::seconds(10), + {{battle_menu_detector}} + ); + + if(battle_menu_detector.detected()){ + stream.log("Battle found!"); + return true; + } + + stream.log("Battle menu not found. Tree or ore might be empty."); + return false; +} + +void exit_battle(VideoStream& stream, ProControllerContext& context, ExitBattleMethod exit_method){ +// pbf_press_button(context, BUTTON_B, 20, 225); + + if (exit_method == ExitBattleMethod::RunAway){ + stream.log("Running from battle..."); + pbf_press_button(context, BUTTON_B, 20, 225); + pbf_press_button(context, BUTTON_A, 20, 100 + (uint16_t)(3.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + return; + } + + context.wait_for_all_requests(); + stream.log("Mashing A to battle!"); + mash_A_until_end_of_battle(stream, context); +} + +PokemonDetails get_pokemon_details(VideoStream& stream, ProControllerContext& context, Language language){ + // Open Info Screen + pbf_wait(context, 1000ms); + pbf_press_button(context, BUTTON_PLUS, 500ms, 1000ms); + pbf_press_button(context, BUTTON_R, 500ms, 1000ms); + + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + + return read_status_info(stream.logger(), stream.overlay(), screen, language); +} + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.h index 5f2ed62446..1b23c603bb 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_LeapPokemonActions.h @@ -1,51 +1,51 @@ -/* Leap Pokemon Actions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_LeapPokemonActions_H -#define PokemonAutomation_PokemonLA_LeapPokemonActions_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" -#include "PokemonLA/Options/PokemonLA_MiscOptions.h" -#include "PokemonLA_RegionNavigation.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLA{ - -enum class LeapPokemon -{ - Aipom, - Burmy, - Cherrim, - Cherubi, - Combee, - Heracross, - Pachirisu, - Vespiquen, - Wormadam, - Geodude, - Graveler, - Bonsly, - Bronzor, - Nosepass, - Bergimite -}; - -void setup(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); -void route(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon); -bool check_tree_or_ore_for_battle(VideoStream& stream, ProControllerContext& context); -void exit_battle(VideoStream& stream, ProControllerContext& context, ExitBattleMethod exit_method); -void return_to_jubilife(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon); -PokemonDetails get_pokemon_details(VideoStream& stream, ProControllerContext& context, Language language); - - -} -} -} -#endif +/* Leap Pokemon Actions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_LeapPokemonActions_H +#define PokemonAutomation_PokemonLA_LeapPokemonActions_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" +#include "PokemonLA/Options/PokemonLA_MiscOptions.h" +#include "PokemonLA_RegionNavigation.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLA{ + +enum class LeapPokemon +{ + Aipom, + Burmy, + Cherrim, + Cherubi, + Combee, + Heracross, + Pachirisu, + Vespiquen, + Wormadam, + Geodude, + Graveler, + Bonsly, + Bronzor, + Nosepass, + Bergimite +}; + +void setup(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); +void route(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon); +bool check_tree_or_ore_for_battle(VideoStream& stream, ProControllerContext& context); +void exit_battle(VideoStream& stream, ProControllerContext& context, ExitBattleMethod exit_method); +void return_to_jubilife(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, LeapPokemon pokemon); +PokemonDetails get_pokemon_details(VideoStream& stream, ProControllerContext& context, Language language); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.cpp index 60e284f631..da0fbf8a78 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.cpp @@ -1,147 +1,147 @@ -/* Mount Change - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA_MountChange.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -bool get_mount_coordinates(size_t& index, MountState mount){ - switch (mount){ - case MountState::WYRDEER_OFF: - case MountState::BASCULEGION_OFF: - index = 0; - return false; - case MountState::WYRDEER_ON: - case MountState::BASCULEGION_ON: - index = 0; - return true; - case MountState::URSALUNA_OFF: - index = 1; - return false; - case MountState::URSALUNA_ON: - index = 1; - return true; - case MountState::SNEASLER_OFF: - index = 2; - return false; - case MountState::SNEASLER_ON: - index = 2; - return true; - case MountState::BRAVIARY_OFF: - index = 3; - return false; - case MountState::BRAVIARY_ON: - index = 3; - return true; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid MountState = " + std::to_string((size_t)mount)); - } -} - -void change_mount(VideoStream& stream, ProControllerContext& context, MountState mount){ - size_t desired_index; - bool desired_on = get_mount_coordinates(desired_index, mount); - - MountDetector mount_detector; - for (size_t c = 0; c < 20; c++){ - context.wait_for_all_requests(); - - MountState current = mount_detector.detect(stream.video().snapshot()); - if (mount == current){ - return; - } - if (current == MountState::NOTHING){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - continue; - } - - size_t current_index; - bool current_on = get_mount_coordinates(current_index, current); - - if (!desired_on && current_on){ - pbf_press_button(context, BUTTON_PLUS, 20, 105); - } - - size_t index_diff = (4 + current_index - desired_index) % 4; - switch (index_diff){ - case 0: - break; - case 1: - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - break; - case 2: - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - break; - case 3: - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - break; - } - - if (desired_on && !current_on){ - if (desired_index == 3){ - pbf_press_button(context, BUTTON_PLUS, 20, 230); - }else{ - pbf_press_button(context, BUTTON_PLUS, 20, 105); - } - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - std::string("Unable to find ") + MOUNT_STATE_STRINGS[(size_t)mount] + " after 10 attempts.", - stream - ); -} - -void dismount(VideoStream& stream, ProControllerContext& context){ - MountDetector mount_detector; - for (size_t c = 0; c < 10; c++){ - context.wait_for_all_requests(); - - MountState current = mount_detector.detect(stream.video().snapshot()); - switch (current){ - case MountState::WYRDEER_OFF: - case MountState::URSALUNA_OFF: - case MountState::BASCULEGION_OFF: - case MountState::SNEASLER_OFF: - case MountState::BRAVIARY_OFF: - // Already unmount - return; - default: - break; - } - - if (current == MountState::NOTHING){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - continue; - } - - // We are mounted. Press + to unmount - pbf_press_button(context, BUTTON_PLUS, 20, 105); - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to dismount after 10 attempts.", - stream - ); -} - - -} -} -} +/* Mount Change + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA_MountChange.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +bool get_mount_coordinates(size_t& index, MountState mount){ + switch (mount){ + case MountState::WYRDEER_OFF: + case MountState::BASCULEGION_OFF: + index = 0; + return false; + case MountState::WYRDEER_ON: + case MountState::BASCULEGION_ON: + index = 0; + return true; + case MountState::URSALUNA_OFF: + index = 1; + return false; + case MountState::URSALUNA_ON: + index = 1; + return true; + case MountState::SNEASLER_OFF: + index = 2; + return false; + case MountState::SNEASLER_ON: + index = 2; + return true; + case MountState::BRAVIARY_OFF: + index = 3; + return false; + case MountState::BRAVIARY_ON: + index = 3; + return true; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid MountState = " + std::to_string((size_t)mount)); + } +} + +void change_mount(VideoStream& stream, ProControllerContext& context, MountState mount){ + size_t desired_index; + bool desired_on = get_mount_coordinates(desired_index, mount); + + MountDetector mount_detector; + for (size_t c = 0; c < 20; c++){ + context.wait_for_all_requests(); + + MountState current = mount_detector.detect(stream.video().snapshot()); + if (mount == current){ + return; + } + if (current == MountState::NOTHING){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + continue; + } + + size_t current_index; + bool current_on = get_mount_coordinates(current_index, current); + + if (!desired_on && current_on){ + pbf_press_button(context, BUTTON_PLUS, 20, 105); + } + + size_t index_diff = (4 + current_index - desired_index) % 4; + switch (index_diff){ + case 0: + break; + case 1: + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + break; + case 2: + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + break; + case 3: + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + break; + } + + if (desired_on && !current_on){ + if (desired_index == 3){ + pbf_press_button(context, BUTTON_PLUS, 20, 230); + }else{ + pbf_press_button(context, BUTTON_PLUS, 20, 105); + } + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + std::string("Unable to find ") + MOUNT_STATE_STRINGS[(size_t)mount] + " after 10 attempts.", + stream + ); +} + +void dismount(VideoStream& stream, ProControllerContext& context){ + MountDetector mount_detector; + for (size_t c = 0; c < 10; c++){ + context.wait_for_all_requests(); + + MountState current = mount_detector.detect(stream.video().snapshot()); + switch (current){ + case MountState::WYRDEER_OFF: + case MountState::URSALUNA_OFF: + case MountState::BASCULEGION_OFF: + case MountState::SNEASLER_OFF: + case MountState::BRAVIARY_OFF: + // Already unmount + return; + default: + break; + } + + if (current == MountState::NOTHING){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + continue; + } + + // We are mounted. Press + to unmount + pbf_press_button(context, BUTTON_PLUS, 20, 105); + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to dismount after 10 attempts.", + stream + ); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.h index 4256dd3a8c..5003f08e93 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_MountChange.h @@ -1,29 +1,29 @@ -/* Mount Change - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_MountChange_H -#define PokemonAutomation_PokemonLA_MountChange_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -// Be careful when changing away from Braviary (on) since you will fall down. -void change_mount(VideoStream& stream, ProControllerContext& context, MountState mount); - -// Dismount player character. -// Be careful when changing away from Braviary (on) since you will fall down. -void dismount(VideoStream& stream, ProControllerContext& context); - - -} -} -} -#endif +/* Mount Change + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_MountChange_H +#define PokemonAutomation_PokemonLA_MountChange_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +// Be careful when changing away from Braviary (on) since you will fall down. +void change_mount(VideoStream& stream, ProControllerContext& context, MountState mount); + +// Dismount player character. +// Be careful when changing away from Braviary (on) since you will fall down. +void dismount(VideoStream& stream, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.cpp index bf6045e82d..2c3d33adf8 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.cpp @@ -1,608 +1,608 @@ -/* Region Navigation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Programs/PokemonLA_EscapeFromAttack.h" -#include "PokemonLA_RegionNavigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -void goto_professor(Logger& logger, ProControllerContext& context, Camp camp){ - switch (camp){ - case Camp::FIELDLANDS_FIELDLANDS: - pbf_move_left_joystick(context, 255, 0, 125, 0); - return; - case Camp::FIELDLANDS_HEIGHTS: - pbf_move_left_joystick(context, 240, 0, 200, 0); - return; - case Camp::MIRELANDS_MIRELANDS: - pbf_move_left_joystick(context, 255, 64, 160, 0); - return; - case Camp::MIRELANDS_BOGBOUND: - pbf_move_left_joystick(context, 255, 64, 140, 0); - return; - case Camp::COASTLANDS_BEACHSIDE: - pbf_move_left_joystick(context, 255, 96, 125, 0); - return; - case Camp::COASTLANDS_COASTLANDS: - pbf_move_left_joystick(context, 255, 48, 105, 0); - return; - case Camp::HIGHLANDS_HIGHLANDS: - pbf_move_left_joystick(context, 255, 64, 176, 0); - return; - case Camp::HIGHLANDS_MOUNTAIN: - pbf_move_left_joystick(context, 255, 32, 125, 0); - return; - case Camp::HIGHLANDS_SUMMIT: - pbf_move_left_joystick(context, 255, 0, 125, 0); - return; - case Camp::ICELANDS_SNOWFIELDS: - pbf_move_left_joystick(context, 255, 56, 125, 0); - return; - case Camp::ICELANDS_ICEPEAK: - pbf_move_left_joystick(context, 255, 48, 75, 0); - return; - default: - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Unknown Camp: " + std::to_string((int)camp) - ); - } -} -void from_professor_return_to_jubilife( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -){ - ButtonDetector button_detector0( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, ImageFloatBox(0.500, 0.578, 0.300, 0.043), - std::chrono::milliseconds(200), true - ); - ButtonDetector button_detector1( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, ImageFloatBox(0.500, 0.621, 0.300, 0.043), - std::chrono::milliseconds(200), true - ); - ButtonDetector bottom_B( - stream.logger(), stream.overlay(), - ButtonType::ButtonB, ImageFloatBox(0.900, 0.955, 0.080, 0.045), - std::chrono::milliseconds(100), true - ); - while (true){ - context.wait_for_all_requests(); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 20; c++){ - pbf_press_button(context, BUTTON_A, 20, 125); - } - }, - { - {button_detector0}, - {button_detector1}, - {bottom_B} - } - ); - context.wait_for(std::chrono::milliseconds(500)); - switch (ret){ - case 0: - stream.log("Detected return option..."); - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - mash_A_to_change_region(env, stream, context); - return; - case 1: - stream.log("Detected report research option..."); - pbf_press_button(context, BUTTON_A, 20, 125); - break; - case 2: - stream.log("Backing out of Pokedex..."); - pbf_mash_button(context, BUTTON_B, 20); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Did not detect option to return to Jubilife.", - stream - ); - } - } -} - - -void mash_A_to_enter_sub_area( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -){ - BlackScreenOverWatcher black_screen0(COLOR_RED, {0.2, 0.2, 0.6, 0.6}, 100, 10); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 7 * TICKS_PER_SECOND); - }, - {{black_screen0}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to load into sub area after 7 seconds.", - stream - ); - } - - stream.log("Loaded into sub area..."); - context.wait_for(std::chrono::milliseconds(200)); -} - - -void mash_A_to_change_region( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -){ - context.wait_for_all_requests(); - -#if 0 - stream.log("Waiting for loading screen..."); - BlackScreenOverWatcher black_screen0; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, GameSettings::instance().LOAD_REGION_TIMEOUT); - }, - {{black_screen0}} - ); - if (ret < 0){ - OperationFailedException::fire( - stream, ErrorReport::SEND_ERROR_REPORT, - "Failed to load into region after timeout." - ); - } - context.wait_for(std::chrono::milliseconds(1000)); -#endif - - { - stream.log("Waiting for end of loading screen..."); - BlackScreenOverWatcher black_screen1a(COLOR_RED, {0.20, 0.02, 0.60, 0.05}); - BlackScreenOverWatcher black_screen1b(COLOR_RED, {0.20, 0.93, 0.60, 0.05}); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, GameSettings::instance().LOAD_REGION_TIMEOUT0); - }, - { - {black_screen1a}, - {black_screen1b}, - } - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to load into region after timeout.", - stream - ); - } - } - { - stream.log("Waiting for overworld..."); - ArcPhoneDetector phone(stream.logger(), stream.overlay(), std::chrono::milliseconds(250), true); - int ret = wait_until( - stream, context, - GameSettings::instance().LOAD_REGION_TIMEOUT0, - {phone} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to load into region after timeout.", - stream - ); - } - } - - stream.log("Loaded into map..."); - context.wait_for(GameSettings::instance().POST_WARP_DELAY0); -} - - -void open_travel_map_from_jubilife( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -){ - pbf_move_left_joystick(context, 128, 255, 200, 0); - MapDetector detector; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, 105); - } - }, - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after 10 x A presses.", - stream - ); - } - stream.log("Found map!"); -} - - -void goto_camp_from_jubilife( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - const TravelLocation& location -){ - stream.overlay().add_log("Travel to " + std::string(MAP_REGION_NAMES[int(location.region)])); - // Move backwards and talk to guard to open the map. - context.wait_for_all_requests(); - open_travel_map_from_jubilife(env, stream, context); - context.wait_for(std::chrono::milliseconds(500)); - - DpadPosition direction = location.region < MapRegion::HIGHLANDS ? DPAD_RIGHT : DPAD_LEFT; - - // Move to region. - MapRegion current_region = MapRegion::NONE; - for (size_t c = 0; c < 10; c++){ - current_region = detect_selected_region(stream, context); - if (current_region == location.region){ - break; - } - pbf_press_dpad(context, direction, 20, 40); - context.wait_for_all_requests(); - } - if (current_region != location.region){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - std::string("Unable to find: ") + location.display, - stream - ); - } - - if (location.warp_slot != 0){ - pbf_press_button(context, BUTTON_A, 20, 105); - for (size_t c = 0; c < location.warp_slot; c++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - } - - // Enter the region. - mash_A_to_change_region(env, stream, context); - - if (location.warp_sub_slot == 0){ - // The destination is a camp. - // No need to do a warp in the region. - return; - } - - // The destination is not a camp. - // It's a settlement or arena that requires another warp: - - // Open the map. - pbf_press_button(context, BUTTON_MINUS, 20, 30); - { - MapDetector detector; - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after 5 seconds.", - stream - ); - } - stream.log("Found map!"); - context.wait_for(std::chrono::milliseconds(500)); - } - - // Warp to sub-camp. - pbf_press_button(context, BUTTON_X, 20, 30); - { - ButtonDetector detector( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.55, 0.40, 0.20, 0.40}, - std::chrono::milliseconds(200), true - ); - int ret = wait_until( - stream, context, - std::chrono::seconds(2), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to fly. Are you under attack?", - stream - ); - } - } - pbf_wait(context, 50); - for (size_t c = 0; c < location.warp_sub_slot; c++){ - const DpadPosition dir = (location.reverse_sub_menu_direction ? DPAD_UP : DPAD_DOWN); - pbf_press_dpad(context, dir, 20, 30); - } - pbf_mash_button(context, BUTTON_A, 125); - - BlackScreenOverWatcher black_screen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}); - int ret = wait_until( - stream, context, - std::chrono::seconds(20), - {{black_screen}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to camp after 20 seconds.", - stream - ); - } - stream.log("Arrived at sub-camp..."); - context.wait_for(GameSettings::instance().POST_WARP_DELAY0); - - if (location.post_arrival_maneuver == nullptr){ - return; - } - - location.post_arrival_maneuver(stream, context); - context.wait_for_all_requests(); -} - - - - -void goto_camp_from_overworld( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -){ - auto start = current_time(); - std::chrono::seconds grace_period(0); - while (true){ - { - EscapeFromAttack session( - env, stream, context, - grace_period, std::chrono::seconds(10) - ); - session.run_session(); - } - - if (current_time() - start > std::chrono::seconds(60)){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to escape from being attacked.", - stream - ); - } - - // Open the map. - pbf_press_button(context, BUTTON_MINUS, 20, 30); - { - MapDetector detector; - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - {{detector}} - ); - if (ret < 0){ -// dump_image(stream.logger(), env.program_info(), "MapNotDetected", stream.video().snapshot()); - stream.log("Map not detected after 5 seconds.", COLOR_RED); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - context.wait_for_all_requests(); - continue; - } - stream.log("Found map!"); - context.wait_for(std::chrono::milliseconds(500)); - } - - // Try to fly back to camp. - pbf_press_button(context, BUTTON_X, 20, 30); - - { - ButtonDetector detector( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.55, 0.40, 0.20, 0.40}, - std::chrono::milliseconds(200), true - ); - int ret = wait_until( - stream, context, - std::chrono::seconds(2), - {{detector}} - ); - if (ret >= 0){ - stream.log("Flying back to camp..."); - pbf_mash_button(context, BUTTON_A, 125); - break; - } - stream.log("Unable to fly. Are you under attack?", COLOR_RED); - } - - pbf_mash_button(context, BUTTON_B, 125); - grace_period = std::chrono::seconds(5); - } - - BlackScreenOverWatcher black_screen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}); - int ret = wait_until( - stream, context, - std::chrono::seconds(20), - {{black_screen}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to camp after 20 seconds.", - stream - ); - } - stream.log("Arrived at camp..."); - context.wait_for(GameSettings::instance().POST_WARP_DELAY0); -} - -void goto_any_camp_from_overworld( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - const TravelLocation& location -){ - - auto start = current_time(); - std::chrono::seconds grace_period(0); - while (true){ - { - EscapeFromAttack session( - env, stream, context, - grace_period, std::chrono::seconds(10) - ); - session.run_session(); - } - - if (current_time() - start > std::chrono::seconds(60)){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to escape from being attacked.", - stream - ); - } - - // Open the map. - pbf_press_button(context, BUTTON_MINUS, 20, 30); - { - MapDetector detector; - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - {{detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Map not detected after 5 seconds.", - stream - ); - } - stream.log("Found map!"); - context.wait_for(std::chrono::milliseconds(500)); - } - - // Warp to sub-camp. - pbf_press_button(context, BUTTON_X, 20, 30); - { - ButtonDetector detector( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, - {0.55, 0.40, 0.20, 0.40}, - std::chrono::milliseconds(200), true - ); - int ret = wait_until( - stream, context, - std::chrono::seconds(2), - {{detector}} - ); - if (ret >= 0){ - stream.log("Flying back to camp..."); - pbf_wait(context, 50); - if (location.warp_slot != 0){ - for (size_t c = 0; c < location.warp_slot; c++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - } - for (size_t c = 0; c < location.warp_sub_slot; c++){ - const DpadPosition dir = (location.reverse_sub_menu_direction ? DPAD_UP : DPAD_DOWN); - pbf_press_dpad(context, dir, 20, 30); - } - pbf_mash_button(context, BUTTON_A, 125); - break; - } - } - - pbf_mash_button(context, BUTTON_B, 125); - grace_period = std::chrono::seconds(5); - } - BlackScreenOverWatcher black_screen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}); - int ret = wait_until( - stream, context, - std::chrono::seconds(20), - {{black_screen}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to camp after 20 seconds.", - stream - ); - } - stream.log("Arrived at camp..."); - context.wait_for(GameSettings::instance().POST_WARP_DELAY0); - context.wait_for_all_requests(); -} - - -void goto_Mai_from_camp( - Logger& logger, ProControllerContext& context, Camp camp -){ - switch (camp){ - case Camp::FIELDLANDS_FIELDLANDS: - // 80 - 128, time - 400 - pbf_move_left_joystick(context, 85, 255, 300, 0); - return; - case Camp::MIRELANDS_MIRELANDS: - pbf_move_left_joystick(context, 0, 120, 310, 0); - return; - case Camp::COASTLANDS_BEACHSIDE: - // 255, 150 -170, 600 too long - pbf_move_left_joystick(context, 255, 165, 550, 0); - return; - case Camp::HIGHLANDS_HIGHLANDS: - // 255, 150 - 170 - pbf_move_left_joystick(context, 255, 165, 370, 0); - return; - case Camp::ICELANDS_SNOWFIELDS: - pbf_move_left_joystick(context, 255, 124, 250, 0); - return; - default: - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Unknown Camp when going to Mai: " + std::to_string((int)camp) - ); - } -} - -void goto_professor(Logger& logger, ProControllerContext& context, const TravelLocation& location){ - Camp camp = map_region_default_camp(location.region); - goto_professor(logger, context, camp); -} - - - - - - - - - - - - - - - - - - -} -} -} +/* Region Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_MapDetector.h" +#include "PokemonLA/Inference/Map/PokemonLA_SelectedRegionDetector.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Programs/PokemonLA_EscapeFromAttack.h" +#include "PokemonLA_RegionNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +void goto_professor(Logger& logger, ProControllerContext& context, Camp camp){ + switch (camp){ + case Camp::FIELDLANDS_FIELDLANDS: + pbf_move_left_joystick(context, 255, 0, 125, 0); + return; + case Camp::FIELDLANDS_HEIGHTS: + pbf_move_left_joystick(context, 240, 0, 200, 0); + return; + case Camp::MIRELANDS_MIRELANDS: + pbf_move_left_joystick(context, 255, 64, 160, 0); + return; + case Camp::MIRELANDS_BOGBOUND: + pbf_move_left_joystick(context, 255, 64, 140, 0); + return; + case Camp::COASTLANDS_BEACHSIDE: + pbf_move_left_joystick(context, 255, 96, 125, 0); + return; + case Camp::COASTLANDS_COASTLANDS: + pbf_move_left_joystick(context, 255, 48, 105, 0); + return; + case Camp::HIGHLANDS_HIGHLANDS: + pbf_move_left_joystick(context, 255, 64, 176, 0); + return; + case Camp::HIGHLANDS_MOUNTAIN: + pbf_move_left_joystick(context, 255, 32, 125, 0); + return; + case Camp::HIGHLANDS_SUMMIT: + pbf_move_left_joystick(context, 255, 0, 125, 0); + return; + case Camp::ICELANDS_SNOWFIELDS: + pbf_move_left_joystick(context, 255, 56, 125, 0); + return; + case Camp::ICELANDS_ICEPEAK: + pbf_move_left_joystick(context, 255, 48, 75, 0); + return; + default: + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Unknown Camp: " + std::to_string((int)camp) + ); + } +} +void from_professor_return_to_jubilife( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +){ + ButtonDetector button_detector0( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, ImageFloatBox(0.500, 0.578, 0.300, 0.043), + std::chrono::milliseconds(200), true + ); + ButtonDetector button_detector1( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, ImageFloatBox(0.500, 0.621, 0.300, 0.043), + std::chrono::milliseconds(200), true + ); + ButtonDetector bottom_B( + stream.logger(), stream.overlay(), + ButtonType::ButtonB, ImageFloatBox(0.900, 0.955, 0.080, 0.045), + std::chrono::milliseconds(100), true + ); + while (true){ + context.wait_for_all_requests(); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 20; c++){ + pbf_press_button(context, BUTTON_A, 20, 125); + } + }, + { + {button_detector0}, + {button_detector1}, + {bottom_B} + } + ); + context.wait_for(std::chrono::milliseconds(500)); + switch (ret){ + case 0: + stream.log("Detected return option..."); + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + mash_A_to_change_region(env, stream, context); + return; + case 1: + stream.log("Detected report research option..."); + pbf_press_button(context, BUTTON_A, 20, 125); + break; + case 2: + stream.log("Backing out of Pokedex..."); + pbf_mash_button(context, BUTTON_B, 20); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Did not detect option to return to Jubilife.", + stream + ); + } + } +} + + +void mash_A_to_enter_sub_area( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +){ + BlackScreenOverWatcher black_screen0(COLOR_RED, {0.2, 0.2, 0.6, 0.6}, 100, 10); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 7 * TICKS_PER_SECOND); + }, + {{black_screen0}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to load into sub area after 7 seconds.", + stream + ); + } + + stream.log("Loaded into sub area..."); + context.wait_for(std::chrono::milliseconds(200)); +} + + +void mash_A_to_change_region( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +){ + context.wait_for_all_requests(); + +#if 0 + stream.log("Waiting for loading screen..."); + BlackScreenOverWatcher black_screen0; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, GameSettings::instance().LOAD_REGION_TIMEOUT); + }, + {{black_screen0}} + ); + if (ret < 0){ + OperationFailedException::fire( + stream, ErrorReport::SEND_ERROR_REPORT, + "Failed to load into region after timeout." + ); + } + context.wait_for(std::chrono::milliseconds(1000)); +#endif + + { + stream.log("Waiting for end of loading screen..."); + BlackScreenOverWatcher black_screen1a(COLOR_RED, {0.20, 0.02, 0.60, 0.05}); + BlackScreenOverWatcher black_screen1b(COLOR_RED, {0.20, 0.93, 0.60, 0.05}); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, GameSettings::instance().LOAD_REGION_TIMEOUT0); + }, + { + {black_screen1a}, + {black_screen1b}, + } + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to load into region after timeout.", + stream + ); + } + } + { + stream.log("Waiting for overworld..."); + ArcPhoneDetector phone(stream.logger(), stream.overlay(), std::chrono::milliseconds(250), true); + int ret = wait_until( + stream, context, + GameSettings::instance().LOAD_REGION_TIMEOUT0, + {phone} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to load into region after timeout.", + stream + ); + } + } + + stream.log("Loaded into map..."); + context.wait_for(GameSettings::instance().POST_WARP_DELAY0); +} + + +void open_travel_map_from_jubilife( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +){ + pbf_move_left_joystick(context, 128, 255, 200, 0); + MapDetector detector; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, 105); + } + }, + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after 10 x A presses.", + stream + ); + } + stream.log("Found map!"); +} + + +void goto_camp_from_jubilife( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + const TravelLocation& location +){ + stream.overlay().add_log("Travel to " + std::string(MAP_REGION_NAMES[int(location.region)])); + // Move backwards and talk to guard to open the map. + context.wait_for_all_requests(); + open_travel_map_from_jubilife(env, stream, context); + context.wait_for(std::chrono::milliseconds(500)); + + DpadPosition direction = location.region < MapRegion::HIGHLANDS ? DPAD_RIGHT : DPAD_LEFT; + + // Move to region. + MapRegion current_region = MapRegion::NONE; + for (size_t c = 0; c < 10; c++){ + current_region = detect_selected_region(stream, context); + if (current_region == location.region){ + break; + } + pbf_press_dpad(context, direction, 20, 40); + context.wait_for_all_requests(); + } + if (current_region != location.region){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + std::string("Unable to find: ") + location.display, + stream + ); + } + + if (location.warp_slot != 0){ + pbf_press_button(context, BUTTON_A, 20, 105); + for (size_t c = 0; c < location.warp_slot; c++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + } + + // Enter the region. + mash_A_to_change_region(env, stream, context); + + if (location.warp_sub_slot == 0){ + // The destination is a camp. + // No need to do a warp in the region. + return; + } + + // The destination is not a camp. + // It's a settlement or arena that requires another warp: + + // Open the map. + pbf_press_button(context, BUTTON_MINUS, 20, 30); + { + MapDetector detector; + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after 5 seconds.", + stream + ); + } + stream.log("Found map!"); + context.wait_for(std::chrono::milliseconds(500)); + } + + // Warp to sub-camp. + pbf_press_button(context, BUTTON_X, 20, 30); + { + ButtonDetector detector( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.55, 0.40, 0.20, 0.40}, + std::chrono::milliseconds(200), true + ); + int ret = wait_until( + stream, context, + std::chrono::seconds(2), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to fly. Are you under attack?", + stream + ); + } + } + pbf_wait(context, 50); + for (size_t c = 0; c < location.warp_sub_slot; c++){ + const DpadPosition dir = (location.reverse_sub_menu_direction ? DPAD_UP : DPAD_DOWN); + pbf_press_dpad(context, dir, 20, 30); + } + pbf_mash_button(context, BUTTON_A, 125); + + BlackScreenOverWatcher black_screen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}); + int ret = wait_until( + stream, context, + std::chrono::seconds(20), + {{black_screen}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to camp after 20 seconds.", + stream + ); + } + stream.log("Arrived at sub-camp..."); + context.wait_for(GameSettings::instance().POST_WARP_DELAY0); + + if (location.post_arrival_maneuver == nullptr){ + return; + } + + location.post_arrival_maneuver(stream, context); + context.wait_for_all_requests(); +} + + + + +void goto_camp_from_overworld( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +){ + auto start = current_time(); + std::chrono::seconds grace_period(0); + while (true){ + { + EscapeFromAttack session( + env, stream, context, + grace_period, std::chrono::seconds(10) + ); + session.run_session(); + } + + if (current_time() - start > std::chrono::seconds(60)){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to escape from being attacked.", + stream + ); + } + + // Open the map. + pbf_press_button(context, BUTTON_MINUS, 20, 30); + { + MapDetector detector; + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + {{detector}} + ); + if (ret < 0){ +// dump_image(stream.logger(), env.program_info(), "MapNotDetected", stream.video().snapshot()); + stream.log("Map not detected after 5 seconds.", COLOR_RED); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + context.wait_for_all_requests(); + continue; + } + stream.log("Found map!"); + context.wait_for(std::chrono::milliseconds(500)); + } + + // Try to fly back to camp. + pbf_press_button(context, BUTTON_X, 20, 30); + + { + ButtonDetector detector( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.55, 0.40, 0.20, 0.40}, + std::chrono::milliseconds(200), true + ); + int ret = wait_until( + stream, context, + std::chrono::seconds(2), + {{detector}} + ); + if (ret >= 0){ + stream.log("Flying back to camp..."); + pbf_mash_button(context, BUTTON_A, 125); + break; + } + stream.log("Unable to fly. Are you under attack?", COLOR_RED); + } + + pbf_mash_button(context, BUTTON_B, 125); + grace_period = std::chrono::seconds(5); + } + + BlackScreenOverWatcher black_screen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}); + int ret = wait_until( + stream, context, + std::chrono::seconds(20), + {{black_screen}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to camp after 20 seconds.", + stream + ); + } + stream.log("Arrived at camp..."); + context.wait_for(GameSettings::instance().POST_WARP_DELAY0); +} + +void goto_any_camp_from_overworld( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + const TravelLocation& location +){ + + auto start = current_time(); + std::chrono::seconds grace_period(0); + while (true){ + { + EscapeFromAttack session( + env, stream, context, + grace_period, std::chrono::seconds(10) + ); + session.run_session(); + } + + if (current_time() - start > std::chrono::seconds(60)){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to escape from being attacked.", + stream + ); + } + + // Open the map. + pbf_press_button(context, BUTTON_MINUS, 20, 30); + { + MapDetector detector; + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + {{detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Map not detected after 5 seconds.", + stream + ); + } + stream.log("Found map!"); + context.wait_for(std::chrono::milliseconds(500)); + } + + // Warp to sub-camp. + pbf_press_button(context, BUTTON_X, 20, 30); + { + ButtonDetector detector( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, + {0.55, 0.40, 0.20, 0.40}, + std::chrono::milliseconds(200), true + ); + int ret = wait_until( + stream, context, + std::chrono::seconds(2), + {{detector}} + ); + if (ret >= 0){ + stream.log("Flying back to camp..."); + pbf_wait(context, 50); + if (location.warp_slot != 0){ + for (size_t c = 0; c < location.warp_slot; c++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + } + for (size_t c = 0; c < location.warp_sub_slot; c++){ + const DpadPosition dir = (location.reverse_sub_menu_direction ? DPAD_UP : DPAD_DOWN); + pbf_press_dpad(context, dir, 20, 30); + } + pbf_mash_button(context, BUTTON_A, 125); + break; + } + } + + pbf_mash_button(context, BUTTON_B, 125); + grace_period = std::chrono::seconds(5); + } + BlackScreenOverWatcher black_screen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}); + int ret = wait_until( + stream, context, + std::chrono::seconds(20), + {{black_screen}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to camp after 20 seconds.", + stream + ); + } + stream.log("Arrived at camp..."); + context.wait_for(GameSettings::instance().POST_WARP_DELAY0); + context.wait_for_all_requests(); +} + + +void goto_Mai_from_camp( + Logger& logger, ProControllerContext& context, Camp camp +){ + switch (camp){ + case Camp::FIELDLANDS_FIELDLANDS: + // 80 - 128, time - 400 + pbf_move_left_joystick(context, 85, 255, 300, 0); + return; + case Camp::MIRELANDS_MIRELANDS: + pbf_move_left_joystick(context, 0, 120, 310, 0); + return; + case Camp::COASTLANDS_BEACHSIDE: + // 255, 150 -170, 600 too long + pbf_move_left_joystick(context, 255, 165, 550, 0); + return; + case Camp::HIGHLANDS_HIGHLANDS: + // 255, 150 - 170 + pbf_move_left_joystick(context, 255, 165, 370, 0); + return; + case Camp::ICELANDS_SNOWFIELDS: + pbf_move_left_joystick(context, 255, 124, 250, 0); + return; + default: + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Unknown Camp when going to Mai: " + std::to_string((int)camp) + ); + } +} + +void goto_professor(Logger& logger, ProControllerContext& context, const TravelLocation& location){ + Camp camp = map_region_default_camp(location.region); + goto_professor(logger, context, camp); +} + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.h index d386baaa23..63c650ff91 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_RegionNavigation.h @@ -1,70 +1,70 @@ -/* Region Navigation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_RegionNavigation_H -#define PokemonAutomation_PokemonLA_RegionNavigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "PokemonLA/PokemonLA_Locations.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLA{ - -struct TravelLocation; - -void goto_professor(Logger& logger, ProControllerContext& context, Camp camp); - -void goto_professor(Logger& logger, ProControllerContext& context, const TravelLocation& location); - -void from_professor_return_to_jubilife( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -); - - -void mash_A_to_enter_sub_area( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -); -void mash_A_to_change_region( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -); - -// Start from Jubilife Village gate, with camera facing towards the village, run towards the gate -// and travel to a location. -void goto_camp_from_jubilife( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - const TravelLocation& location -); - - -void goto_camp_from_overworld( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -); - -void goto_any_camp_from_overworld( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - const TravelLocation& location -); - -// From a camp location, run to Mai in that camp. -void goto_Mai_from_camp( - Logger& logger, ProControllerContext& context, Camp camp -); - -// From the program starting position at Jubilife Village, move backwards and talk to guard to open the map. -// Return after the map is detected. -// Throw an error if map is not found. -void open_travel_map_from_jubilife( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -); - - -} -} -} -#endif +/* Region Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_RegionNavigation_H +#define PokemonAutomation_PokemonLA_RegionNavigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "PokemonLA/PokemonLA_Locations.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLA{ + +struct TravelLocation; + +void goto_professor(Logger& logger, ProControllerContext& context, Camp camp); + +void goto_professor(Logger& logger, ProControllerContext& context, const TravelLocation& location); + +void from_professor_return_to_jubilife( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +); + + +void mash_A_to_enter_sub_area( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +); +void mash_A_to_change_region( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +); + +// Start from Jubilife Village gate, with camera facing towards the village, run towards the gate +// and travel to a location. +void goto_camp_from_jubilife( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + const TravelLocation& location +); + + +void goto_camp_from_overworld( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +); + +void goto_any_camp_from_overworld( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + const TravelLocation& location +); + +// From a camp location, run to Mai in that camp. +void goto_Mai_from_camp( + Logger& logger, ProControllerContext& context, Camp camp +); + +// From the program starting position at Jubilife Village, move backwards and talk to guard to open the map. +// Return after the map is detected. +// Throw an error if map is not found. +void open_travel_map_from_jubilife( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.cpp b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.cpp index 52d0b893d6..c572efa926 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.cpp @@ -1,140 +1,140 @@ -/* Time of Day Change - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" -#include "PokemonLA_TimeOfDayChange.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -void change_time_of_day_at_tent( - VideoStream& stream, ProControllerContext& context, - TimeOfDay target_time, - Camp camp -){ - stream.overlay().add_log("Change time to " + std::string(TIME_OF_DAY_NAMES[int(target_time)]), COLOR_WHITE); - // Move to the tent - switch (camp) - { - case Camp::FIELDLANDS_FIELDLANDS: - pbf_move_left_joystick(context, 105, 0, 220, 20); - break; - - case Camp::FIELDLANDS_HEIGHTS: - pbf_move_left_joystick(context, 95, 0, 250, 20); - break; - - case Camp::MIRELANDS_MIRELANDS: - pbf_move_left_joystick(context, 70, 0, 180, 20); - break; - - case Camp::MIRELANDS_BOGBOUND: - pbf_move_left_joystick(context, 70, 0, 170, 20); - break; - - case Camp::COASTLANDS_BEACHSIDE: - pbf_move_left_joystick(context, 100, 0, 130, 20); - break; - - case Camp::COASTLANDS_COASTLANDS: - pbf_move_left_joystick(context, 75, 0, 160, 20); - break; - - case Camp::HIGHLANDS_HIGHLANDS: - pbf_move_left_joystick(context, 95, 0, 190, 20); - break; - - case Camp::HIGHLANDS_MOUNTAIN: - pbf_move_left_joystick(context, 60, 0, 190, 20); - break; - - case Camp::HIGHLANDS_SUMMIT: - pbf_move_left_joystick(context, 100, 0, 220, 20); - break; - - case Camp::ICELANDS_SNOWFIELDS: - pbf_move_left_joystick(context, 80, 0, 150, 20); - break; - - case Camp::ICELANDS_ICEPEAK: - pbf_move_left_joystick(context, 110, 0, 220, 20); - break; - } - - // Press A to interact with tent - pbf_press_button(context, BUTTON_A, 30, 30); - context.wait_for_all_requests(); - - const bool stop_on_detected = true; - DialogueYellowArrowDetector yellow_arrow_detector(stream.logger(), stream.overlay(), stop_on_detected); - - context.wait_for_all_requests(); - // Wait for the dialog box to show up - int ret = wait_until( - stream, context, std::chrono::seconds(5), {{yellow_arrow_detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Did not interact with a tent.", - stream - ); - } - - // Press A to clear the dialog box, and show the time menu - // pbf_wait(context, 40); - pbf_press_button(context, BUTTON_A, 30, 80); - stream.log("Change time of day to " + std::string(TIME_OF_DAY_NAMES[int(target_time)])); - - // Move down the menu to find the target time - - int num_movements = (int)target_time; - DpadPosition dpad_dir = DPAD_DOWN; - if (target_time == TimeOfDay::MIDNIGHT){ - num_movements = 2; - dpad_dir = DPAD_UP; - } - for(int i = 0; i < num_movements; i++){ - pbf_press_dpad(context, dpad_dir, 30, 70); - } - - // Press A to start resting - pbf_press_button(context, BUTTON_A, 30, 100); - context.wait_for_all_requests(); - - // Wait for the dialog box to show up - ret = wait_until( - stream, context, std::chrono::seconds(30), {{yellow_arrow_detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to stand up after resting in a tent.", - stream - ); - } - - // Press A again to clear the dialog box - pbf_press_button(context, BUTTON_A, 30, 100); - - context.wait_for_all_requests(); -} - - - -} -} -} +/* Time of Day Change + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" +#include "PokemonLA_TimeOfDayChange.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +void change_time_of_day_at_tent( + VideoStream& stream, ProControllerContext& context, + TimeOfDay target_time, + Camp camp +){ + stream.overlay().add_log("Change time to " + std::string(TIME_OF_DAY_NAMES[int(target_time)]), COLOR_WHITE); + // Move to the tent + switch (camp) + { + case Camp::FIELDLANDS_FIELDLANDS: + pbf_move_left_joystick(context, 105, 0, 220, 20); + break; + + case Camp::FIELDLANDS_HEIGHTS: + pbf_move_left_joystick(context, 95, 0, 250, 20); + break; + + case Camp::MIRELANDS_MIRELANDS: + pbf_move_left_joystick(context, 70, 0, 180, 20); + break; + + case Camp::MIRELANDS_BOGBOUND: + pbf_move_left_joystick(context, 70, 0, 170, 20); + break; + + case Camp::COASTLANDS_BEACHSIDE: + pbf_move_left_joystick(context, 100, 0, 130, 20); + break; + + case Camp::COASTLANDS_COASTLANDS: + pbf_move_left_joystick(context, 75, 0, 160, 20); + break; + + case Camp::HIGHLANDS_HIGHLANDS: + pbf_move_left_joystick(context, 95, 0, 190, 20); + break; + + case Camp::HIGHLANDS_MOUNTAIN: + pbf_move_left_joystick(context, 60, 0, 190, 20); + break; + + case Camp::HIGHLANDS_SUMMIT: + pbf_move_left_joystick(context, 100, 0, 220, 20); + break; + + case Camp::ICELANDS_SNOWFIELDS: + pbf_move_left_joystick(context, 80, 0, 150, 20); + break; + + case Camp::ICELANDS_ICEPEAK: + pbf_move_left_joystick(context, 110, 0, 220, 20); + break; + } + + // Press A to interact with tent + pbf_press_button(context, BUTTON_A, 30, 30); + context.wait_for_all_requests(); + + const bool stop_on_detected = true; + DialogueYellowArrowDetector yellow_arrow_detector(stream.logger(), stream.overlay(), stop_on_detected); + + context.wait_for_all_requests(); + // Wait for the dialog box to show up + int ret = wait_until( + stream, context, std::chrono::seconds(5), {{yellow_arrow_detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Did not interact with a tent.", + stream + ); + } + + // Press A to clear the dialog box, and show the time menu + // pbf_wait(context, 40); + pbf_press_button(context, BUTTON_A, 30, 80); + stream.log("Change time of day to " + std::string(TIME_OF_DAY_NAMES[int(target_time)])); + + // Move down the menu to find the target time + + int num_movements = (int)target_time; + DpadPosition dpad_dir = DPAD_DOWN; + if (target_time == TimeOfDay::MIDNIGHT){ + num_movements = 2; + dpad_dir = DPAD_UP; + } + for(int i = 0; i < num_movements; i++){ + pbf_press_dpad(context, dpad_dir, 30, 70); + } + + // Press A to start resting + pbf_press_button(context, BUTTON_A, 30, 100); + context.wait_for_all_requests(); + + // Wait for the dialog box to show up + ret = wait_until( + stream, context, std::chrono::seconds(30), {{yellow_arrow_detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to stand up after resting in a tent.", + stream + ); + } + + // Press A again to clear the dialog box + pbf_press_button(context, BUTTON_A, 30, 100); + + context.wait_for_all_requests(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.h b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.h index 896bfafb5c..4b3029a43b 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.h +++ b/SerialPrograms/Source/PokemonLA/Programs/PokemonLA_TimeOfDayChange.h @@ -1,32 +1,32 @@ -/* Time of Day Change - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_TimeOfDayChange_H -#define PokemonAutomation_PokemonLA_TimeOfDayChange_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonLA/PokemonLA_WeatherAndTime.h" -#include "PokemonLA/PokemonLA_Locations.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -// From a camp teleport location, move to the tent and change time of day. -// if `target_time` is TimeOfDay::NONE, it resets for only a while, healing the pokemon but no change of time. -void change_time_of_day_at_tent( - VideoStream& stream, ProControllerContext& context, - TimeOfDay target_time, - Camp camp -); - - - -} -} -} -#endif +/* Time of Day Change + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_TimeOfDayChange_H +#define PokemonAutomation_PokemonLA_TimeOfDayChange_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonLA/PokemonLA_WeatherAndTime.h" +#include "PokemonLA/PokemonLA_Locations.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +// From a camp teleport location, move to the tent and change time of day. +// if `target_time` is TimeOfDay::NONE, it resets for only a while, healing the pokemon but no change of time. +void change_time_of_day_at_tent( + VideoStream& stream, ProControllerContext& context, + TimeOfDay target_time, + Camp camp +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.cpp index e9791cbc21..281ece97f3 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.cpp @@ -1,638 +1,638 @@ -/* Auto Multi-Spawn - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -//#include -#include -//#include -#include -#include -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" -#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" -#include "PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA/Programs/PokemonLA_TimeOfDayChange.h" -#include "PokemonLA/PokemonLA_WeatherAndTime.h" -#include "PokemonLA_AutoMultiSpawn.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - -const int MAX_DESPAWN_COUNT[] = { - 2 // Mirelands - Hippopotas -}; - -// The spawned pokemon we want to remove to advance a path -const std::set TARGET_POKEMON[] = { - {"hippopotas", "hippowdon"} // Mirelands - Hippopotas -}; - -// Possible nearby pokemon that we may focus onto near the spawn point. -const std::set WILD_NEARBY_POKEMON[] = { - {"stunky", "skuntank", "carnivine"} // Mirelands - Hippopotas -}; - -// Focus on a pokemon, change focus if possible until one of the target pokemon is found. -// Then thow the current item/pokemon to start a battle or catch/hit the pokemon. -// -// If a target pokemon is focused, the function returns immediately when the item/pokemon is throw, with -// return value: (true, target pokemon details). -// If it fails to find any pokemon, return (false, empty details). -// If it can focus on one pokemon but cannot find a target pokemon, return (true, empty details). -// -// Currently it hardcoded to do maximum 4 focus change attempts before giving up. -// If it cannot find the target pokemon or OCR pokemon name reading fails, it returns -// an empty PokemonDetails. -// Otherwise, it returns the details of the pokemon thrown at. -std::pair control_focus_to_throw( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const std::set& target_pokemon, - const std::set& nearby_pokemon, - Language language -){ - // A session that creates a new thread to send button commands to controller - AsyncCommandSession session( - context, - env.console.logger(), - env.realtime_dispatcher(), - env.console.pro_controller() - ); - - // First, let controller press ZL non-stop to start focusing on a pokemon - session.dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 10000, 0); - }); - - // We try at most 4 focus change attempts - int max_focus_change_attempt = 4; - for(int focus_index = 0; focus_index <= max_focus_change_attempt; focus_index++){ - WildPokemonFocusDetector focus_detector(env.console.logger(), env.console); - int ret = wait_until( - env.console, context, std::chrono::seconds(3), - {{focus_detector}} - ); - - if (ret < 0){ - env.log("Failed to focus on one pokemon."); - session.stop_session_and_rethrow(); // Stop the commands - return std::make_pair(false, PokemonDetails()); - } - - // We have successfully focused on one pokemon. - // Wait for a while so that the pokemon name is fully rendered, to avoid mis-read pokemon name. - context.wait_for(std::chrono::milliseconds(300)); - // Read its details and detect whether we can change focus. - auto focused_frame = env.console.video().snapshot(); - PokemonDetails details = read_focused_wild_pokemon_info(env.console, env.console, focused_frame, language); - bool can_change_focus = detect_change_focus(env.console, env.console, focused_frame); - - if (details.name_candidates.size() == 0){ - // Somehow the program detects a pokemon focus, but cannot read any names - env.log("Warning: Focus on a pokemon but cannot read pokemon name.", COLOR_RED); - session.stop_session_and_rethrow(); // Stop the commands - return std::make_pair(false, PokemonDetails()); - } - - { // log pokemon name candidates - std::ostringstream os; - std::copy(details.name_candidates.begin(), details.name_candidates.end(), std::ostream_iterator(os, " ")); - env.log("Focused pokemon name candidates " + os.str()); - } - - bool found_nearby_pokemon = false; - { // Filter out names that are not target pokemon - std::set filtered_names; - for(const auto& name : details.name_candidates){ - if (target_pokemon.find(name) != target_pokemon.end()){ - filtered_names.insert(name); - } - if (nearby_pokemon.find(name) != nearby_pokemon.end()){ - found_nearby_pokemon = true; - env.log("Focused on a nearby pokemon " + name); - } - } - details.name_candidates = std::move(filtered_names); - } - - if (details.name_candidates.size() > 0){ - // We are focusing on a target pokemon - // Press ZR to throw sth. - // Dispatch a new series of commands that overwrites the last ones - session.dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL | BUTTON_ZR, 30, 0); - pbf_press_button(context, BUTTON_ZL, 50, 0); - }); - - env.log("Sending command to throw pokemon to start battle"); - session.wait(); - env.log("Waited for the throw pokemon command to finish"); - session.stop_session_and_rethrow(); - context.wait_for_all_requests(); - return std::make_pair(true, details); - } - - // Target pokemon not focused: - - if (can_change_focus == false){ - // We focused onto a pokemon that is not the target pokemon, and there is only one - // pokemon that can be focused on. - if (found_nearby_pokemon){ - // We focused on a nearby pokemon, so the player character's location is most likely correct, - // just we are unlucky that the target pokemon is too far from our current position or the - // player character is facing a wrong direction. - env.log("Only one pokemon can be focused. No target pokemon nearby."); - }else{ - // We focused on an unexpected pokemon. Maybe the trip is wrong. - env.log("Focus on an unexpected pokemon."); - } - - session.stop_session_and_rethrow(); - return std::make_pair(true, PokemonDetails()); - } - - if (focus_index < max_focus_change_attempt){ - // We focused onto a pokemon that is not the target pokemon, but there are other pokemon that can be focused. - // Press A to change focus. - session.dispatch([](ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL | BUTTON_A, 30, 0); - pbf_press_button(context, BUTTON_ZL, 10000, 0); - }); - - // Wait some time to let the button A press executed, the game focused on another pokemon - context.wait_for(std::chrono::milliseconds(600)); - } - } - - session.stop_session_and_rethrow(); - env.log("After four focus change attempts we cannot find a target pokemon"); - return std::make_pair(true, PokemonDetails()); -} - - - - -AutoMultiSpawn_Descriptor::AutoMultiSpawn_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:AutoMultiSpawn", - STRING_POKEMON + " LA", "Auto Multi-Spawn", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AutoMultiSpawn.md", - "Advance a path in MultiSpawn shiny hunting method.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - -AutoMultiSpawn::AutoMultiSpawn() - : LANGUAGE( - "Game Language", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , SPAWN( - "Spawn Point:", - { - {MultiSpawn::MirelandsHippopotas, "mirelands-hippopotas", "Mirelands - Hippopotas"}, - }, - LockMode::LOCK_WHILE_RUNNING, - MultiSpawn::MirelandsHippopotas - ) - , PATH( - false, - "Multi-Spawn Path:
e.g. \"A1|A1|A2|A2|A1|A1|A1|A2\".", - LockMode::LOCK_WHILE_RUNNING, - "", "" - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(SPAWN); - PA_ADD_OPTION(PATH); - PA_ADD_OPTION(NOTIFICATIONS); -} - -std::vector parse_multispawn_path(SingleSwitchProgramEnvironment& env, const std::string& path, int max_num_despawn){ - std::vector path_despawns; - std::string raw_path = path + "|"; - for(size_t pos = 0, next_pos = 0; (next_pos = raw_path.find('|', pos)) != std::string::npos; pos = next_pos + 1){ - if (pos == next_pos){ // In the case it's just one "|" - continue; - } - - if (raw_path[pos] != 'A'){ - throw InternalProgramError( - &env.console.logger(), - PA_CURRENT_FUNCTION, - "Wrong Path string. Should have 'A' at pos " + std::to_string(pos) - ); - } - raw_path[next_pos] = '\0'; - int despawn_count = static_cast(strtol(raw_path.data() + pos+1, nullptr, 10)); - if (despawn_count <= 0 || despawn_count > max_num_despawn){ - throw InternalProgramError( - &env.console.logger(), - PA_CURRENT_FUNCTION, - "Wrong Path string. Invalid number " + std::to_string(despawn_count) + " at pos " + std::to_string(pos+1) - ); - } - path_despawns.push_back(despawn_count); - } - - return path_despawns; -} - - -void AutoMultiSpawn::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - MultiSpawn spawn = SPAWN; - const int max_num_despawn = MAX_DESPAWN_COUNT[(size_t)spawn]; - - // Parse input path string: - std::vector path_despawns = parse_multispawn_path(env, PATH, max_num_despawn); - std::vector path_times; - // We + 1 here because we need one more time change to read the desired target pokemon at the end (usually a shiny alpha) - for(size_t i = 0; i < path_despawns.size() + 1; i++){ - // TODO: if murkrow path is added, need to output 'N' - path_times.push_back(i % 2 == 0 ? TimeOfDay::MORNING : TimeOfDay::MIDDAY); - } - - { - std::ostringstream os; - for(size_t i = 0; i < path_despawns.size(); i++){ - if (i >0){ - os << '|'; - } - os << 'A' << path_despawns[i] << '(' << timeOfDayOneLetter(path_times[i]) << ')'; - } - env.log("The path is: " + os.str()); - } - - goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); - change_time_of_day_at_tent(env.console, context, path_times[0], Camp::MIRELANDS_MIRELANDS); - - for(size_t iStep = 0; iStep < path_despawns.size(); iStep++){ - // - Teleport to a camp - // - From camp, go to the spawn point - // - Battle the pokemon there to remove them - // - Teleport back to camp - // - Got to tent to change time of day - advance_one_path_step(env, context, max_num_despawn, path_despawns[iStep], path_times[iStep], path_times[iStep+1]); - - std::ostringstream os; - for(size_t jStep = 0; jStep < path_despawns.size(); jStep++){ - os << 'A' << path_despawns[jStep] << '(' << timeOfDayOneLetter(path_times[jStep]) << ")|"; - if (iStep == jStep){ - os << '*'; - } - } - env.log("Path Progress: " + os.str(), COLOR_CYAN); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -void AutoMultiSpawn::advance_one_path_step( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - size_t num_spawned_pokemon, - size_t num_to_despawn, - TimeOfDay cur_time, - TimeOfDay next_time -){ - - // Switch to pokemon selection so that we can press X to throw a pokemon out to start a battle - for (size_t c = 0; true; c++){ - context.wait_for_all_requests(); - auto snapshot = env.console.video().snapshot(); - if (is_pokemon_selection(env.console, snapshot)){ - break; - } - if (c >= 5){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to switch to Pokemon selection after 5 attempts.", - env.console, - std::move(snapshot) - ); - } - env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_X, 20, 230); - } - - goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); - - // We try at most three battles to remove pokemon - size_t already_removed_pokemon = 0; - size_t remained_to_remove = num_to_despawn; - size_t pokemon_left = num_spawned_pokemon; - for(int i = 0; i < 3; i++){ - // Go to spawn point to start a battle, remove some pokemon, then return to camp. - size_t num_pokemon_removed = try_one_battle_to_remove_pokemon(env, context, pokemon_left, remained_to_remove); - already_removed_pokemon += num_pokemon_removed; - env.log( - "Removed " + std::to_string(num_pokemon_removed) + " via battle, total " - + std::to_string(already_removed_pokemon) + " pokemon removed, target total pokemon to remove: " + std::to_string(num_to_despawn) - ); - if (already_removed_pokemon > num_to_despawn){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Removed more pokemon than required. Removed " - + std::to_string(already_removed_pokemon) + " while target is " + std::to_string(num_to_despawn), - env.console - ); - } - - remained_to_remove -= num_pokemon_removed; - pokemon_left -= num_pokemon_removed; - - // XXX - // Check weather. If weather does not match the weather at the beginning of the path step, then - // weather change refreshed the spawn. This advance is broken. - - if (remained_to_remove == 0){ - break; - } - } - if (remained_to_remove > 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "After trying to start three battles, cannot remove enough pokemon.", - env.console - ); - } - - // All pokemon removed. Now go to tent to change time of day. - change_time_of_day_at_tent(env.console, context, next_time, Camp::MIRELANDS_MIRELANDS); -} - -// From camp, go to spawn, do one battle to remove pokemon. If no error, return camp -size_t AutoMultiSpawn::try_one_battle_to_remove_pokemon( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - size_t num_left, - size_t num_to_despawn -){ - // Try to go to spawn point and focus on one pokemon - PokemonDetails focused_pokemon; - const size_t num_tries = 5; - for(size_t i = 0; i < num_tries; i++){ - // From camp go to the spawn point, try focusing on one pokemon. - // Return the pokemon details if found the target pokemon. Otherwise if cannot find one, return empty details. - focused_pokemon = go_to_spawn_point_and_try_focusing_pokemon(env, context, num_left); - - if (focused_pokemon.name_candidates.size() > 0){ - // We found one - env.log("Focused on one pokemon and starting battle."); - break; - } - env.log("Cannot focus on any pokemon. Retry."); - // TODO: escape routine may scare wild pokemon. A better way is to reset and load from the backup save? - // or load from a previous save? - goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); - // TODO: May need to reset time of day here - } - - if (focused_pokemon.name_candidates.size() == 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot focus on a pokemon after going to the spawn point " + std::to_string(num_tries) + " times", - env.console - ); - } - - // We have found a target pokemon and initiated a pokemon battle - env.log("Now waiting for pokemon battle to begin..."); - BattleSpriteWatcher battle_sprite_watcher(env.console.logger(), env.console.overlay()); - wait_until( - env.console, context, std::chrono::seconds(3), {{battle_sprite_watcher}} - ); - env.log("Waited for 3 sec. Now start detecting battle menu or battle ends."); - - bool battle_starting = true; - size_t num_initial_sprites = 0; - size_t num_removed_pokemon = 0; - bool battle_menu_detectd = false; - size_t cur_move = 0; - while(true){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console.logger(), env.console, stop_on_detected); - ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(100), stop_on_detected); - - std::vector callbacks = { - {arc_phone_detector}, - {battle_menu_detector} - }; - int seconds_to_wait = 60; - if (battle_starting){ - callbacks.emplace_back(battle_sprite_watcher); - // When battle starts, assume your pokemon is the fastest, your turn should - // arrive very quickly. - seconds_to_wait = 30; - } - - int ret = wait_until( - env.console, context, std::chrono::seconds(seconds_to_wait), callbacks - ); - - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect a battle after 30 seconds.", - env.console - ); - } - - if (battle_starting){ - for(bool appeared: battle_sprite_watcher.sprites_appeared()){ - num_initial_sprites += appeared; - } - - env.log("Battle started, detected battle sprite count: " + std::to_string(num_initial_sprites) + - ", number to despawn: " + std::to_string(num_to_despawn)); - battle_starting = false; - } - - if (ret == 0){ // battle ends - env.log("Battle ends"); - if (num_initial_sprites == 0 || battle_menu_detectd == false){ - // num_initial_sprites == 0: battle ends but no sprite detected. So there is only one pokmeon in the battle and it is removed - // battle_menu_detectd == false: we don't go to battle menu before battle ends. This means there is only skittish pokemon and - // it/they flee. Because skittish pokemon cannot be multi-battled, so there is only one skitish pokemon. - // - // Note we need `battle_menu_detectd == false` condition because if battle ends without entering battle menu, battle sprite - // watcher will have lots of false positives when the upper and lower dark borders gradually fade away. - num_removed_pokemon = 1; - }else{ - // More than one pokemon attended the battle and they all fled. - // We think our pokemon is strong enough to defeat all the wild pokemon in the battle, so it is not possible - // that the battle ends because we lost. - num_removed_pokemon = num_initial_sprites; - } - break; - } - - // now in battle menu - battle_menu_detectd = true; - const auto sprite_detection_frame = env.console.video().snapshot().frame; - const auto sprites_remain = battle_sprite_watcher.detect_sprites(*sprite_detection_frame); - size_t num_sprites_remain = 0; - for(bool remain : sprites_remain){ - num_sprites_remain += remain; - } - num_removed_pokemon = num_initial_sprites - num_sprites_remain; - - if (PreloadSettings::instance().DEVELOPER_MODE){ - dump_debug_image(env.logger(), "PokemonLA/AutoMultiSpawn", "battle_sprite_" + std::to_string(num_sprites_remain), *sprite_detection_frame); - } - env.log("Found battle menu, num sprites removed: " + std::to_string(num_removed_pokemon)); - - if (num_removed_pokemon > num_to_despawn){ - // Oh no, we removed more than needed. - // XXX can try to reset the game to fix this. But for now let user handles this. - env.log("Removed more than needed!"); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Removed more pokemon than needed!", - env.console - ); - }else if (num_removed_pokemon < num_to_despawn){ - - // Press A to select moves - pbf_press_button(context, BUTTON_A, 10, 100); - context.wait_for_all_requests(); - use_next_move_with_pp(env.console, context, 0, cur_move); - continue; - } - - // num_removed_pokemon == num_to_despawn: - // We removed exactly what we need. - // Escape battle - env.log("Running from battle..."); - pbf_press_button(context, BUTTON_B, 20, 225); - pbf_press_button(context, BUTTON_A, 20, 100); - context.wait_for_all_requests(); - ArcPhoneDetector escape_detector(env.console, env.console, std::chrono::milliseconds(100), stop_on_detected); - ret = wait_until( - env.console, context, std::chrono::seconds(30), {{escape_detector}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect end of battle when escaping.", - env.console - ); - } - } - - goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); - return num_removed_pokemon; -} - -PokemonDetails AutoMultiSpawn::go_to_spawn_point_and_try_focusing_pokemon( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - size_t nun_pokemon_left -){ - // From camp fly to the spawn point, focus on a target pokemon and start a battle - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_wait(context, 40); - - // Move to spawn location on Braviary - pbf_move_left_joystick(context, 255, 165, 150, 0); // 170 - pbf_press_button(context, BUTTON_B, 200, 10); - pbf_mash_button(context, BUTTON_B, 1500); // 1450 - - // Descend down from the air: - for(int i = 0; i < 2 ; i++){ - change_mount(env.console, context, MountState::BRAVIARY_OFF); - context.wait_for(std::chrono::milliseconds(300)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - } - - // pbf_press_button(context, BUTTON_PLUS, 20, 150); // jump down from Braviary - // for(int i = 0; i < 2; i++){ - // pbf_press_button(context, BUTTON_PLUS, 20, 50); // Call back Braviary to stop falling - // pbf_press_button(context, BUTTON_PLUS, 20, 150); // fall down again - // } - // In case the character hits a tree and change the Braviary mount state due to the hit, - // use visual feedback to makse sure the character is now dismounted. - change_mount(env.console, context, MountState::BRAVIARY_OFF); - pbf_wait(context, 50); - - // Move forward on foot - pbf_move_left_joystick(context, 128, 0, 160, 0); - - context.wait_for_all_requests(); - - // Try three focus sessions: - const int max_focus_try = 5; - for(int i = 0; i < max_focus_try; i++){ - // ret.first: whether we can focus on some pokemon - // ret.second: the details of the target pokemon being focused, or empty if no target pokemon found. - MultiSpawn spawn = SPAWN; - const auto ret = control_focus_to_throw( - env, context, - TARGET_POKEMON[(size_t)spawn], - WILD_NEARBY_POKEMON[(size_t)spawn], - LANGUAGE - ); - if (ret.first){ - return ret.second; - } - - if (i + 1 < max_focus_try){ - env.log("Try another focus attempt."); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - - if (i == 2 && nun_pokemon_left == 1){ - // If its' only one pokemon to despawn, then we don't need to worry about scare multiple pokemon at once. - // We can move closer. - pbf_move_left_joystick(context, 128, 0, 150, 60); - context.wait_for_all_requests(); - } - } - - return PokemonDetails(); -} - - -} -} -} +/* Auto Multi-Spawn + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include +#include +//#include +#include +#include +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcPhoneDetector.h" +#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" +#include "PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Programs/PokemonLA_BattleRoutines.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA/Programs/PokemonLA_TimeOfDayChange.h" +#include "PokemonLA/PokemonLA_WeatherAndTime.h" +#include "PokemonLA_AutoMultiSpawn.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + +const int MAX_DESPAWN_COUNT[] = { + 2 // Mirelands - Hippopotas +}; + +// The spawned pokemon we want to remove to advance a path +const std::set TARGET_POKEMON[] = { + {"hippopotas", "hippowdon"} // Mirelands - Hippopotas +}; + +// Possible nearby pokemon that we may focus onto near the spawn point. +const std::set WILD_NEARBY_POKEMON[] = { + {"stunky", "skuntank", "carnivine"} // Mirelands - Hippopotas +}; + +// Focus on a pokemon, change focus if possible until one of the target pokemon is found. +// Then thow the current item/pokemon to start a battle or catch/hit the pokemon. +// +// If a target pokemon is focused, the function returns immediately when the item/pokemon is throw, with +// return value: (true, target pokemon details). +// If it fails to find any pokemon, return (false, empty details). +// If it can focus on one pokemon but cannot find a target pokemon, return (true, empty details). +// +// Currently it hardcoded to do maximum 4 focus change attempts before giving up. +// If it cannot find the target pokemon or OCR pokemon name reading fails, it returns +// an empty PokemonDetails. +// Otherwise, it returns the details of the pokemon thrown at. +std::pair control_focus_to_throw( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const std::set& target_pokemon, + const std::set& nearby_pokemon, + Language language +){ + // A session that creates a new thread to send button commands to controller + AsyncCommandSession session( + context, + env.console.logger(), + env.realtime_dispatcher(), + env.console.pro_controller() + ); + + // First, let controller press ZL non-stop to start focusing on a pokemon + session.dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 10000, 0); + }); + + // We try at most 4 focus change attempts + int max_focus_change_attempt = 4; + for(int focus_index = 0; focus_index <= max_focus_change_attempt; focus_index++){ + WildPokemonFocusDetector focus_detector(env.console.logger(), env.console); + int ret = wait_until( + env.console, context, std::chrono::seconds(3), + {{focus_detector}} + ); + + if (ret < 0){ + env.log("Failed to focus on one pokemon."); + session.stop_session_and_rethrow(); // Stop the commands + return std::make_pair(false, PokemonDetails()); + } + + // We have successfully focused on one pokemon. + // Wait for a while so that the pokemon name is fully rendered, to avoid mis-read pokemon name. + context.wait_for(std::chrono::milliseconds(300)); + // Read its details and detect whether we can change focus. + auto focused_frame = env.console.video().snapshot(); + PokemonDetails details = read_focused_wild_pokemon_info(env.console, env.console, focused_frame, language); + bool can_change_focus = detect_change_focus(env.console, env.console, focused_frame); + + if (details.name_candidates.size() == 0){ + // Somehow the program detects a pokemon focus, but cannot read any names + env.log("Warning: Focus on a pokemon but cannot read pokemon name.", COLOR_RED); + session.stop_session_and_rethrow(); // Stop the commands + return std::make_pair(false, PokemonDetails()); + } + + { // log pokemon name candidates + std::ostringstream os; + std::copy(details.name_candidates.begin(), details.name_candidates.end(), std::ostream_iterator(os, " ")); + env.log("Focused pokemon name candidates " + os.str()); + } + + bool found_nearby_pokemon = false; + { // Filter out names that are not target pokemon + std::set filtered_names; + for(const auto& name : details.name_candidates){ + if (target_pokemon.find(name) != target_pokemon.end()){ + filtered_names.insert(name); + } + if (nearby_pokemon.find(name) != nearby_pokemon.end()){ + found_nearby_pokemon = true; + env.log("Focused on a nearby pokemon " + name); + } + } + details.name_candidates = std::move(filtered_names); + } + + if (details.name_candidates.size() > 0){ + // We are focusing on a target pokemon + // Press ZR to throw sth. + // Dispatch a new series of commands that overwrites the last ones + session.dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL | BUTTON_ZR, 30, 0); + pbf_press_button(context, BUTTON_ZL, 50, 0); + }); + + env.log("Sending command to throw pokemon to start battle"); + session.wait(); + env.log("Waited for the throw pokemon command to finish"); + session.stop_session_and_rethrow(); + context.wait_for_all_requests(); + return std::make_pair(true, details); + } + + // Target pokemon not focused: + + if (can_change_focus == false){ + // We focused onto a pokemon that is not the target pokemon, and there is only one + // pokemon that can be focused on. + if (found_nearby_pokemon){ + // We focused on a nearby pokemon, so the player character's location is most likely correct, + // just we are unlucky that the target pokemon is too far from our current position or the + // player character is facing a wrong direction. + env.log("Only one pokemon can be focused. No target pokemon nearby."); + }else{ + // We focused on an unexpected pokemon. Maybe the trip is wrong. + env.log("Focus on an unexpected pokemon."); + } + + session.stop_session_and_rethrow(); + return std::make_pair(true, PokemonDetails()); + } + + if (focus_index < max_focus_change_attempt){ + // We focused onto a pokemon that is not the target pokemon, but there are other pokemon that can be focused. + // Press A to change focus. + session.dispatch([](ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL | BUTTON_A, 30, 0); + pbf_press_button(context, BUTTON_ZL, 10000, 0); + }); + + // Wait some time to let the button A press executed, the game focused on another pokemon + context.wait_for(std::chrono::milliseconds(600)); + } + } + + session.stop_session_and_rethrow(); + env.log("After four focus change attempts we cannot find a target pokemon"); + return std::make_pair(true, PokemonDetails()); +} + + + + +AutoMultiSpawn_Descriptor::AutoMultiSpawn_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:AutoMultiSpawn", + STRING_POKEMON + " LA", "Auto Multi-Spawn", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AutoMultiSpawn.md", + "Advance a path in MultiSpawn shiny hunting method.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + +AutoMultiSpawn::AutoMultiSpawn() + : LANGUAGE( + "Game Language", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , SPAWN( + "Spawn Point:", + { + {MultiSpawn::MirelandsHippopotas, "mirelands-hippopotas", "Mirelands - Hippopotas"}, + }, + LockMode::LOCK_WHILE_RUNNING, + MultiSpawn::MirelandsHippopotas + ) + , PATH( + false, + "Multi-Spawn Path:
e.g. \"A1|A1|A2|A2|A1|A1|A1|A2\".", + LockMode::LOCK_WHILE_RUNNING, + "", "" + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(SPAWN); + PA_ADD_OPTION(PATH); + PA_ADD_OPTION(NOTIFICATIONS); +} + +std::vector parse_multispawn_path(SingleSwitchProgramEnvironment& env, const std::string& path, int max_num_despawn){ + std::vector path_despawns; + std::string raw_path = path + "|"; + for(size_t pos = 0, next_pos = 0; (next_pos = raw_path.find('|', pos)) != std::string::npos; pos = next_pos + 1){ + if (pos == next_pos){ // In the case it's just one "|" + continue; + } + + if (raw_path[pos] != 'A'){ + throw InternalProgramError( + &env.console.logger(), + PA_CURRENT_FUNCTION, + "Wrong Path string. Should have 'A' at pos " + std::to_string(pos) + ); + } + raw_path[next_pos] = '\0'; + int despawn_count = static_cast(strtol(raw_path.data() + pos+1, nullptr, 10)); + if (despawn_count <= 0 || despawn_count > max_num_despawn){ + throw InternalProgramError( + &env.console.logger(), + PA_CURRENT_FUNCTION, + "Wrong Path string. Invalid number " + std::to_string(despawn_count) + " at pos " + std::to_string(pos+1) + ); + } + path_despawns.push_back(despawn_count); + } + + return path_despawns; +} + + +void AutoMultiSpawn::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + MultiSpawn spawn = SPAWN; + const int max_num_despawn = MAX_DESPAWN_COUNT[(size_t)spawn]; + + // Parse input path string: + std::vector path_despawns = parse_multispawn_path(env, PATH, max_num_despawn); + std::vector path_times; + // We + 1 here because we need one more time change to read the desired target pokemon at the end (usually a shiny alpha) + for(size_t i = 0; i < path_despawns.size() + 1; i++){ + // TODO: if murkrow path is added, need to output 'N' + path_times.push_back(i % 2 == 0 ? TimeOfDay::MORNING : TimeOfDay::MIDDAY); + } + + { + std::ostringstream os; + for(size_t i = 0; i < path_despawns.size(); i++){ + if (i >0){ + os << '|'; + } + os << 'A' << path_despawns[i] << '(' << timeOfDayOneLetter(path_times[i]) << ')'; + } + env.log("The path is: " + os.str()); + } + + goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); + change_time_of_day_at_tent(env.console, context, path_times[0], Camp::MIRELANDS_MIRELANDS); + + for(size_t iStep = 0; iStep < path_despawns.size(); iStep++){ + // - Teleport to a camp + // - From camp, go to the spawn point + // - Battle the pokemon there to remove them + // - Teleport back to camp + // - Got to tent to change time of day + advance_one_path_step(env, context, max_num_despawn, path_despawns[iStep], path_times[iStep], path_times[iStep+1]); + + std::ostringstream os; + for(size_t jStep = 0; jStep < path_despawns.size(); jStep++){ + os << 'A' << path_despawns[jStep] << '(' << timeOfDayOneLetter(path_times[jStep]) << ")|"; + if (iStep == jStep){ + os << '*'; + } + } + env.log("Path Progress: " + os.str(), COLOR_CYAN); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +void AutoMultiSpawn::advance_one_path_step( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + size_t num_spawned_pokemon, + size_t num_to_despawn, + TimeOfDay cur_time, + TimeOfDay next_time +){ + + // Switch to pokemon selection so that we can press X to throw a pokemon out to start a battle + for (size_t c = 0; true; c++){ + context.wait_for_all_requests(); + auto snapshot = env.console.video().snapshot(); + if (is_pokemon_selection(env.console, snapshot)){ + break; + } + if (c >= 5){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to switch to Pokemon selection after 5 attempts.", + env.console, + std::move(snapshot) + ); + } + env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_X, 20, 230); + } + + goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); + + // We try at most three battles to remove pokemon + size_t already_removed_pokemon = 0; + size_t remained_to_remove = num_to_despawn; + size_t pokemon_left = num_spawned_pokemon; + for(int i = 0; i < 3; i++){ + // Go to spawn point to start a battle, remove some pokemon, then return to camp. + size_t num_pokemon_removed = try_one_battle_to_remove_pokemon(env, context, pokemon_left, remained_to_remove); + already_removed_pokemon += num_pokemon_removed; + env.log( + "Removed " + std::to_string(num_pokemon_removed) + " via battle, total " + + std::to_string(already_removed_pokemon) + " pokemon removed, target total pokemon to remove: " + std::to_string(num_to_despawn) + ); + if (already_removed_pokemon > num_to_despawn){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Removed more pokemon than required. Removed " + + std::to_string(already_removed_pokemon) + " while target is " + std::to_string(num_to_despawn), + env.console + ); + } + + remained_to_remove -= num_pokemon_removed; + pokemon_left -= num_pokemon_removed; + + // XXX + // Check weather. If weather does not match the weather at the beginning of the path step, then + // weather change refreshed the spawn. This advance is broken. + + if (remained_to_remove == 0){ + break; + } + } + if (remained_to_remove > 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "After trying to start three battles, cannot remove enough pokemon.", + env.console + ); + } + + // All pokemon removed. Now go to tent to change time of day. + change_time_of_day_at_tent(env.console, context, next_time, Camp::MIRELANDS_MIRELANDS); +} + +// From camp, go to spawn, do one battle to remove pokemon. If no error, return camp +size_t AutoMultiSpawn::try_one_battle_to_remove_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + size_t num_left, + size_t num_to_despawn +){ + // Try to go to spawn point and focus on one pokemon + PokemonDetails focused_pokemon; + const size_t num_tries = 5; + for(size_t i = 0; i < num_tries; i++){ + // From camp go to the spawn point, try focusing on one pokemon. + // Return the pokemon details if found the target pokemon. Otherwise if cannot find one, return empty details. + focused_pokemon = go_to_spawn_point_and_try_focusing_pokemon(env, context, num_left); + + if (focused_pokemon.name_candidates.size() > 0){ + // We found one + env.log("Focused on one pokemon and starting battle."); + break; + } + env.log("Cannot focus on any pokemon. Retry."); + // TODO: escape routine may scare wild pokemon. A better way is to reset and load from the backup save? + // or load from a previous save? + goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); + // TODO: May need to reset time of day here + } + + if (focused_pokemon.name_candidates.size() == 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot focus on a pokemon after going to the spawn point " + std::to_string(num_tries) + " times", + env.console + ); + } + + // We have found a target pokemon and initiated a pokemon battle + env.log("Now waiting for pokemon battle to begin..."); + BattleSpriteWatcher battle_sprite_watcher(env.console.logger(), env.console.overlay()); + wait_until( + env.console, context, std::chrono::seconds(3), {{battle_sprite_watcher}} + ); + env.log("Waited for 3 sec. Now start detecting battle menu or battle ends."); + + bool battle_starting = true; + size_t num_initial_sprites = 0; + size_t num_removed_pokemon = 0; + bool battle_menu_detectd = false; + size_t cur_move = 0; + while(true){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console.logger(), env.console, stop_on_detected); + ArcPhoneDetector arc_phone_detector(env.console, env.console, std::chrono::milliseconds(100), stop_on_detected); + + std::vector callbacks = { + {arc_phone_detector}, + {battle_menu_detector} + }; + int seconds_to_wait = 60; + if (battle_starting){ + callbacks.emplace_back(battle_sprite_watcher); + // When battle starts, assume your pokemon is the fastest, your turn should + // arrive very quickly. + seconds_to_wait = 30; + } + + int ret = wait_until( + env.console, context, std::chrono::seconds(seconds_to_wait), callbacks + ); + + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect a battle after 30 seconds.", + env.console + ); + } + + if (battle_starting){ + for(bool appeared: battle_sprite_watcher.sprites_appeared()){ + num_initial_sprites += appeared; + } + + env.log("Battle started, detected battle sprite count: " + std::to_string(num_initial_sprites) + + ", number to despawn: " + std::to_string(num_to_despawn)); + battle_starting = false; + } + + if (ret == 0){ // battle ends + env.log("Battle ends"); + if (num_initial_sprites == 0 || battle_menu_detectd == false){ + // num_initial_sprites == 0: battle ends but no sprite detected. So there is only one pokmeon in the battle and it is removed + // battle_menu_detectd == false: we don't go to battle menu before battle ends. This means there is only skittish pokemon and + // it/they flee. Because skittish pokemon cannot be multi-battled, so there is only one skitish pokemon. + // + // Note we need `battle_menu_detectd == false` condition because if battle ends without entering battle menu, battle sprite + // watcher will have lots of false positives when the upper and lower dark borders gradually fade away. + num_removed_pokemon = 1; + }else{ + // More than one pokemon attended the battle and they all fled. + // We think our pokemon is strong enough to defeat all the wild pokemon in the battle, so it is not possible + // that the battle ends because we lost. + num_removed_pokemon = num_initial_sprites; + } + break; + } + + // now in battle menu + battle_menu_detectd = true; + const auto sprite_detection_frame = env.console.video().snapshot().frame; + const auto sprites_remain = battle_sprite_watcher.detect_sprites(*sprite_detection_frame); + size_t num_sprites_remain = 0; + for(bool remain : sprites_remain){ + num_sprites_remain += remain; + } + num_removed_pokemon = num_initial_sprites - num_sprites_remain; + + if (PreloadSettings::instance().DEVELOPER_MODE){ + dump_debug_image(env.logger(), "PokemonLA/AutoMultiSpawn", "battle_sprite_" + std::to_string(num_sprites_remain), *sprite_detection_frame); + } + env.log("Found battle menu, num sprites removed: " + std::to_string(num_removed_pokemon)); + + if (num_removed_pokemon > num_to_despawn){ + // Oh no, we removed more than needed. + // XXX can try to reset the game to fix this. But for now let user handles this. + env.log("Removed more than needed!"); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Removed more pokemon than needed!", + env.console + ); + }else if (num_removed_pokemon < num_to_despawn){ + + // Press A to select moves + pbf_press_button(context, BUTTON_A, 10, 100); + context.wait_for_all_requests(); + use_next_move_with_pp(env.console, context, 0, cur_move); + continue; + } + + // num_removed_pokemon == num_to_despawn: + // We removed exactly what we need. + // Escape battle + env.log("Running from battle..."); + pbf_press_button(context, BUTTON_B, 20, 225); + pbf_press_button(context, BUTTON_A, 20, 100); + context.wait_for_all_requests(); + ArcPhoneDetector escape_detector(env.console, env.console, std::chrono::milliseconds(100), stop_on_detected); + ret = wait_until( + env.console, context, std::chrono::seconds(30), {{escape_detector}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect end of battle when escaping.", + env.console + ); + } + } + + goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); + return num_removed_pokemon; +} + +PokemonDetails AutoMultiSpawn::go_to_spawn_point_and_try_focusing_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + size_t nun_pokemon_left +){ + // From camp fly to the spawn point, focus on a target pokemon and start a battle + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_wait(context, 40); + + // Move to spawn location on Braviary + pbf_move_left_joystick(context, 255, 165, 150, 0); // 170 + pbf_press_button(context, BUTTON_B, 200, 10); + pbf_mash_button(context, BUTTON_B, 1500); // 1450 + + // Descend down from the air: + for(int i = 0; i < 2 ; i++){ + change_mount(env.console, context, MountState::BRAVIARY_OFF); + context.wait_for(std::chrono::milliseconds(300)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + } + + // pbf_press_button(context, BUTTON_PLUS, 20, 150); // jump down from Braviary + // for(int i = 0; i < 2; i++){ + // pbf_press_button(context, BUTTON_PLUS, 20, 50); // Call back Braviary to stop falling + // pbf_press_button(context, BUTTON_PLUS, 20, 150); // fall down again + // } + // In case the character hits a tree and change the Braviary mount state due to the hit, + // use visual feedback to makse sure the character is now dismounted. + change_mount(env.console, context, MountState::BRAVIARY_OFF); + pbf_wait(context, 50); + + // Move forward on foot + pbf_move_left_joystick(context, 128, 0, 160, 0); + + context.wait_for_all_requests(); + + // Try three focus sessions: + const int max_focus_try = 5; + for(int i = 0; i < max_focus_try; i++){ + // ret.first: whether we can focus on some pokemon + // ret.second: the details of the target pokemon being focused, or empty if no target pokemon found. + MultiSpawn spawn = SPAWN; + const auto ret = control_focus_to_throw( + env, context, + TARGET_POKEMON[(size_t)spawn], + WILD_NEARBY_POKEMON[(size_t)spawn], + LANGUAGE + ); + if (ret.first){ + return ret.second; + } + + if (i + 1 < max_focus_try){ + env.log("Try another focus attempt."); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + + if (i == 2 && nun_pokemon_left == 1){ + // If its' only one pokemon to despawn, then we don't need to worry about scare multiple pokemon at once. + // We can move closer. + pbf_move_left_joystick(context, 128, 0, 150, 60); + context.wait_for_all_requests(); + } + } + + return PokemonDetails(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h index 84dcf6d31c..4b95b6d9b2 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_AutoMultiSpawn.h @@ -1,78 +1,78 @@ -/* Auto Multi-Spawn - * - * From: https://github.com/PokemonAutomation/ - * - * Advance a path in Multi-Spawn shiny hunting method - */ - -#ifndef PokemonAutomation_PokemonLA_AutoMultiSpawn_H -#define PokemonAutomation_PokemonLA_AutoMultiSpawn_H - -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/PokemonLA_WeatherAndTime.h" -#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class AutoMultiSpawn_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoMultiSpawn_Descriptor(); -}; - - -enum class MultiSpawn{ - MirelandsHippopotas, -}; - - -class AutoMultiSpawn : public SingleSwitchProgramInstance{ -public: - AutoMultiSpawn(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - // Advance one step (e.g. A1 or A2) in the multi-spawn path - void advance_one_path_step( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - size_t num_spawned_pokemon, - size_t num_to_despawn, - TimeOfDay cur_time, - TimeOfDay next_time - ); - - // From camp, go to the spawn point, start one battle to remove some pokemon - // Return how many pokemon removed in the battle. - // The function will use a loop to do multiple trips to the spawn point if it cannot find a target pokemon after a trip. - size_t try_one_battle_to_remove_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t num_pokemon_left, size_t num_to_despawn); - - // From camp go to the spawn point, try focusing on one pokemon - // Return the pokemon details if found the target pokemon. Otherwise if cannot find one, return empty details - // The function will use a loop to do multiple focusing to try to get a target pokemon focused - PokemonDetails go_to_spawn_point_and_try_focusing_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t nun_pokemon_left); - - OCR::LanguageOCROption LANGUAGE; - - EnumDropdownOption SPAWN; - - StringOption PATH; - - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Auto Multi-Spawn + * + * From: https://github.com/PokemonAutomation/ + * + * Advance a path in Multi-Spawn shiny hunting method + */ + +#ifndef PokemonAutomation_PokemonLA_AutoMultiSpawn_H +#define PokemonAutomation_PokemonLA_AutoMultiSpawn_H + +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/PokemonLA_WeatherAndTime.h" +#include "PokemonLA/Resources/PokemonLA_PokemonInfo.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class AutoMultiSpawn_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoMultiSpawn_Descriptor(); +}; + + +enum class MultiSpawn{ + MirelandsHippopotas, +}; + + +class AutoMultiSpawn : public SingleSwitchProgramInstance{ +public: + AutoMultiSpawn(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + // Advance one step (e.g. A1 or A2) in the multi-spawn path + void advance_one_path_step( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + size_t num_spawned_pokemon, + size_t num_to_despawn, + TimeOfDay cur_time, + TimeOfDay next_time + ); + + // From camp, go to the spawn point, start one battle to remove some pokemon + // Return how many pokemon removed in the battle. + // The function will use a loop to do multiple trips to the spawn point if it cannot find a target pokemon after a trip. + size_t try_one_battle_to_remove_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t num_pokemon_left, size_t num_to_despawn); + + // From camp go to the spawn point, try focusing on one pokemon + // Return the pokemon details if found the target pokemon. Otherwise if cannot find one, return empty details + // The function will use a loop to do multiple focusing to try to get a target pokemon focused + PokemonDetails go_to_spawn_point_and_try_focusing_pokemon(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t nun_pokemon_left); + + OCR::LanguageOCROption LANGUAGE; + + EnumDropdownOption SPAWN; + + StringOption PATH; + + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.cpp index 622cc86846..f433a7b7ea 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.cpp @@ -1,850 +1,850 @@ -/* Burmy Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/PokemonLA_BlackOutDetector.h" -#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h" -#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" -#include "CommonFramework/GlobalSettingsPanel.h" - -#ifdef _MSC_VER -#pragma warning(disable:4244) // double -> int precision loss -#endif - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -BurmyFinder_Descriptor::BurmyFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:Burmy Hunter", - STRING_POKEMON + " LA", "Burmy Hunter", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/BurmyHunter.md", - "Check nearby trees for a possible Shiny, Alpha or Alpha Shiny Burmy", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} -class BurmyFinder_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , trees(m_stats["Trees"]) - , errors(m_stats["Errors"]) - , blackouts(m_stats["Blackouts"]) - , found(m_stats["Found"]) - , enroute_shinies(m_stats["Enroute Shinies"]) - , tree_alphas(m_stats["Tree Alphas"]) - , tree_shinies(m_stats["Tree Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Trees"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Blackouts", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Found"); - m_display_order.emplace_back("Enroute Shinies"); - m_display_order.emplace_back("Tree Alphas"); - m_display_order.emplace_back("Tree Shinies"); - m_aliases["Shinies"] = "Enroute Shinies"; - m_aliases["Alphas"] = "Tree Alphas"; - } - - std::atomic& attempts; - std::atomic& trees; - std::atomic& errors; - std::atomic& blackouts; - std::atomic& found; - std::atomic& enroute_shinies; - std::atomic& tree_alphas; - std::atomic& tree_shinies; - -}; -std::unique_ptr BurmyFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -BurmyFinder::BurmyFinder() - : LANGUAGE( - "Game Language", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while traveling in the overworld.", - "0 ms" - ) - , FOUND_SHINY_OR_ALPHA( - "Found Shiny or Alpha", - true, true, - ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , MATCH_DETECTED_OPTIONS( - "Match Action", - "What to do when a Burmy is found that matches the \"Stop On\" parameter.", - "Found Shiny or Alpha" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &FOUND_SHINY_OR_ALPHA, - &MATCH_DETECTED_OPTIONS.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(STOP_ON); - PA_ADD_OPTION(EXIT_METHOD); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(MATCH_DETECTED_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - } -} - - - -struct BurmyFinder::TreeCounter{ - std::array tree = {}; - - void log(Logger& logger) const{ - std::ostringstream oss; - for(size_t i = 0; i < size(tree); i++){ - if (i != 0){ - oss << " - "; - } - oss << "Tree " << i << ": " << tostr_u_commas(tree[i]); - } - logger.log(oss.str()); - } -}; - -bool BurmyFinder::handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - BurmyFinder_Descriptor::Stats& stats = env.current_stats(); - - PokemonDetails pokemon = get_pokemon_details(env.console, context, LANGUAGE); - pbf_press_button(context, BUTTON_B, 20, 225); - context.wait_for_all_requests(); - - if (pokemon.name_candidates.find("burmy") == pokemon.name_candidates.end()){ - env.console.log("Not a burmy. Leaving battle."); - exit_battle(env.console, context, EXIT_METHOD); - return false; - } - - stats.found++; - // Match validation - - if (pokemon.is_alpha && pokemon.is_shiny){ - env.console.log("Found Shiny Alpha!"); - stats.tree_shinies++; - stats.tree_alphas++; - }else if (pokemon.is_alpha){ - env.console.log("Found Alpha!"); - stats.tree_alphas++; - }else if (pokemon.is_shiny){ - env.console.log("Found Shiny!"); - stats.tree_shinies++; - }else{ - env.console.log("Normie in the tree -_-"); - } - env.update_stats(); - - bool is_match = false; - switch (STOP_ON){ - case StopOn::Shiny: - is_match = pokemon.is_shiny; - break; - case StopOn::Alpha: - is_match = pokemon.is_alpha; - break; - case StopOn::ShinyOrAlpha: - is_match = pokemon.is_alpha || pokemon.is_shiny; - break; - case StopOn::ShinyAndAlpha: - is_match = pokemon.is_alpha && pokemon.is_shiny; - break; - } - - bool notification_sent = false; - do{ - std::string str; - if (pokemon.is_shiny){ - if (pokemon.is_alpha){ - str = "Found Shiny Alpha!"; - }else{ - str = "Found Shiny!"; - } - }else{ - if (pokemon.is_alpha){ - str = "Found Alpha!"; - }else{ - break; - } - } - notification_sent |= send_program_notification( - env, FOUND_SHINY_OR_ALPHA, - Pokemon::COLOR_STAR_SHINY, - std::move(str), - {}, "", - env.console.video().snapshot(), true - ); - }while (false); - - if (is_match){ - on_battle_match_found(env, env.console, context, MATCH_DETECTED_OPTIONS, !notification_sent); - } - - exit_battle(env.console, context, EXIT_METHOD); - - return true; -} - - -bool BurmyFinder::check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - context.wait_for_all_requests(); - - disable_shiny_sound(context); - bool battle_found = check_tree_or_ore_for_battle(env.console, context); - env.current_stats().trees++; - env.update_stats(); - - context.wait_for_all_requests(); - - bool ret = false; - if (battle_found){ - ret = handle_battle(env, context); - } - - enable_shiny_sound(context); - - return ret; -} - -void BurmyFinder::check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - context.wait_for_all_requests(); - disable_shiny_sound(context); - // Throw pokemon - pbf_press_button(context, BUTTON_ZR, (0.5 * TICKS_PER_SECOND), 1.5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - env.current_stats().trees++; - env.update_stats(); -// enable_shiny_sound(context); -} - -void BurmyFinder::disable_shiny_sound(ProControllerContext& context){ - context.wait_for_all_requests(); - m_enable_shiny_sound.store(false, std::memory_order_release); -} -void BurmyFinder::enable_shiny_sound(ProControllerContext& context){ - context.wait_for_all_requests(); - m_enable_shiny_sound.store(true, std::memory_order_release); -} - -void BurmyFinder::go_to_height_camp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - const bool stop_on_detected = true; - BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); - }, - { - {battle_menu_detector}, - } - ); - if (ret == 0){ - env.log("Warning: found inside a battle when trying to return to camp."); - // Unexpected battle during movement to camp - if (SAVE_DEBUG_VIDEO){ - // Take a video to know why it enters battle during return trip - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - // Finish battle - handle_battle(env, context); - // Go back to camp - goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); - } -} - -size_t BurmyFinder::grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, TreeCounter& tree_counter){ - - size_t last_checked_tree = 0; - - if (path != 0){ - go_to_height_camp(env, context); - } - - env.console.log("Currently Checking Path:" + std::to_string(path)); - - BattleMenuDetector battle_menu_detector(env.console, env.console, true); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - switch (path){ - case 0: - //============ Tree 0=============// - env.console.log("Checking tree: 0"); - pbf_move_left_joystick(context, 255, 85, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.6 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_wait(context, 0.7 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_B, (5.1 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4.2 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 128, 255, (0.3 * TICKS_PER_SECOND), (0.2 * TICKS_PER_SECOND)); - last_checked_tree = 0; - check_tree_no_stop(env, context); - - //============ Tree 1=============// - env.console.log("Checking tree: 1"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 10, 1 * TICKS_PER_SECOND, 0); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (0.6 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (2.7 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 128, 255, (0.1 * TICKS_PER_SECOND), (0.3 * TICKS_PER_SECOND)); - last_checked_tree = 1; - check_tree_no_stop(env, context); - - //============ Tree 2=============// - env.console.log("Checking tree: 2"); - pbf_press_button(context, BUTTON_PLUS, 20, 100); - pbf_move_left_joystick(context, 255, 130, 1 * TICKS_PER_SECOND, 0); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (0.6 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (2.4 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 128, 255, (0.1 * TICKS_PER_SECOND), (0.3 * TICKS_PER_SECOND)); - last_checked_tree = 2; - check_tree_no_stop(env, context); - - //============ Tree 3=============// - env.console.log("Checking tree: 3"); - pbf_press_button(context, BUTTON_PLUS, 20, 100); - pbf_move_left_joystick(context, 0, 95, 1 * TICKS_PER_SECOND, 0); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, 110, 0); - pbf_press_button(context, BUTTON_Y, (2.3 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 128, 255, (0.1 * TICKS_PER_SECOND), (0.3 * TICKS_PER_SECOND)); - last_checked_tree = 3; - break; - case 1: - //============ Tree 4=============// - env.console.log("Checking tree: 4"); - pbf_move_left_joystick(context, 255, 165, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_wait(context, 0.6 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_B, (4.8 * TICKS_PER_SECOND), (0.6 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_Y, (1.7 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 4; - check_tree_no_stop(env, context); - - //============ Tree 5=============// - env.console.log("Checking tree: 5"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 190, 1 * TICKS_PER_SECOND, 0); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (0.5 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (2.6 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.15 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 5; - check_tree_no_stop(env, context); - - //============ Tree 6=============// - env.console.log("Checking tree: 6"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 0, 130, 1 * TICKS_PER_SECOND, 0); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (1.3 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (3.2 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.15 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 6; - break; - case 2: - //============ Tree 7=============// - env.console.log("Checking tree: 7"); - pbf_move_left_joystick(context, 180, 255, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (7.2 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4.2 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 0, 127, (1.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, 20); - pbf_move_right_joystick(context, 127, 255, (0.5 * TICKS_PER_SECOND), 20); - last_checked_tree = 7; - check_tree_no_stop(env, context); - - //============ Tree 8=============// - env.console.log("Checking tree: 8"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 230, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_Y, (1.7 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 8; - check_tree_no_stop(env, context); - - //============ Tree 9=============// - env.console.log("Checking tree: 8"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 90, 0, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (0.6 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 9; - check_tree_no_stop(env, context); - - //============ Tree 10=============// - env.console.log("Checking tree: 10"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 0, 235, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (2.5 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (2.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 10; - check_tree_no_stop(env, context); - - //============ Tree 11=============// - env.console.log("Checking tree: 11"); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 145, 0, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (1.8 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (1.8 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.3 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 11; - break; - case 3: - //============ Tree 12=============// - env.console.log("Checking tree: 12"); - pbf_move_left_joystick(context, 148, 255, 20, 20); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (9.7 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_Y, (2.2 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 127, 30, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 12; - check_tree_no_stop(env, context); - - //============ Tree 13=============// - env.console.log("Checking tree: 13"); - pbf_move_left_joystick(context, 148, 0, 20, 20); - change_mount(env.console, context, MountState::BRAVIARY_ON); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_B, (2 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (3 * TICKS_PER_SECOND), 0); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 13; - check_tree_no_stop(env, context); - - //============ Tree 14=============// - env.console.log("Checking tree: 14"); - pbf_move_left_joystick(context, 255, 155, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_move_left_joystick(context, 127, 0, (6.6 * TICKS_PER_SECOND), 20); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 14; - check_tree_no_stop(env, context); - - //============ Tree 15=============// - env.console.log("Checking tree: 15"); - pbf_move_left_joystick(context, 200, 0, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - context.wait_for_all_requests(); - enable_shiny_sound(context); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_B, (1.7 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (3 * TICKS_PER_SECOND), 0); - pbf_move_right_joystick(context, 127, 255, (0.1 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - last_checked_tree = 15; - break; - } - }, - { - {battle_menu_detector}, - } - ); - - if (ret == 0){ - if (handle_battle(env, context)){ - env.console.log("Battle found before last tree in the path."); - tree_counter.tree[last_checked_tree]++; - } - }else{ - // Check last tree - if (check_tree(env, context)){ - tree_counter.tree[last_checked_tree]++; - } - env.console.log("Checked all trees in the path."); - } - - return last_checked_tree; -} - -void BurmyFinder::single_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, size_t last_tree, TreeCounter& tree_counter){ - env.console.log("Last tree was: " + std::to_string(last_tree)); - - switch (path){ - case 0: - if (last_tree < 1){ - env.console.log("Heading to tree 1"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 255, 110, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (7.2 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4.5 * TICKS_PER_SECOND), 0); - pbf_move_left_joystick(context, 180, 0, 20, (0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[1]++; - } - } - - if (last_tree < 2){ - env.console.log("Heading to tree 2"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 255, 147, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (6.6 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4.4 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[2]++; - } - } - - if (last_tree < 3){ - env.console.log("Heading to tree 3"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 255, 158, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (9.5 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[3]++; - } - } - break; - case 1: - if (last_tree < 5){ - env.console.log("Heading to Tree 5"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 240, 240, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (5.95 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1.2 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 0, 0, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[5]++; - } - } - - if (last_tree < 6){ - env.console.log("Heading to Tree 6"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 255, 235, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (8 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4 * TICKS_PER_SECOND), 0); - if (check_tree(env, context)){ - tree_counter.tree[6]++; - } - } - break; - - case 2: - if (last_tree < 8){ - env.console.log("Heading to Tree 8"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 173, 255, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (8.8 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (4 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, 20); - if (check_tree(env, context)){ - tree_counter.tree[8]++; - } - } - - if (last_tree < 9){ - env.console.log("Heading to Tree 9"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 163, 255, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (11.7 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (3.8 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, 20); - if (check_tree(env, context)){ - tree_counter.tree[8]++; - } - } - - if (last_tree < 10){ - env.console.log("Heading to Tree 10"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 218, 255, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (10.4 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (3.8 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, 20); - if (check_tree(env, context)){ - tree_counter.tree[8]++; - } - } - - if (last_tree < 11){ - env.console.log("Heading to Tree 11"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 255, 230, 20, (0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (11.4 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_Y, (3.8 * TICKS_PER_SECOND), 0); - pbf_press_button(context, BUTTON_PLUS, 20, 20); - if (check_tree(env, context)){ - tree_counter.tree[11]++; - } - } - break; - case 3: - if (last_tree < 13){ - env.console.log("Heading to Tree 13"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 104, 255, 30, 30); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (11 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1.3 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[13]++; - } - } - - if (last_tree < 14){ - env.console.log("Heading to Tree 14"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 108, 255, 20, 20); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (8.7 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 140, 255, 20, 20); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 140, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[14]++; - } - } - if (last_tree < 15){ - env.console.log("Heading to Tree 15"); - go_to_height_camp(env, context); - pbf_move_left_joystick(context, 160, 255, 30, 30); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_press_button(context, BUTTON_B, (6.35 * TICKS_PER_SECOND), 20); - pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_PLUS, 20, (1.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 255, 135, 30, (0.5 * TICKS_PER_SECOND)); - pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); - pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); - if (check_tree(env, context)){ - tree_counter.tree[15]++; - } - } - - break; - - } - -} - -void BurmyFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, TreeCounter& tree_counter){ - BurmyFinder_Descriptor::Stats& stats = env.current_stats(); - stats.attempts++; - env.update_stats(); - env.console.log("Starting route and shiny detection..."); - - for (size_t c = 0; true; c++){ - context.wait_for_all_requests(); - auto snapshot = env.console.video().snapshot(); - if (is_pokemon_selection(env.console, snapshot)){ - break; - } - if (c >= 5){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to switch to Pokemon selection after 5 attempts.", - env.console, - std::move(snapshot) - ); - } - env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_X, 20, 230); - } - - float shiny_coefficient = 1.0; - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - if (!m_enable_shiny_sound.load()){ - return false; - } - stats.enroute_shinies++; - shiny_coefficient = error_coefficient; - return on_shiny_callback(env, env.console, SHINY_DETECTED_ENROUTE, error_coefficient); - }); - - BlackOutDetector black_out_detector(env.console, env.console); - - goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - - for (int path = 0; path < 4; path++){ - size_t last_tree = grouped_path(env, context, path, tree_counter); - context.wait_for_all_requests(); - single_path(env, context, path, last_tree, tree_counter); - context.wait_for_all_requests(); - } - // End - goto_camp_from_overworld(env, env.console, context); - goto_professor(env.console, context, Camp::FIELDLANDS_FIELDLANDS); - }, - {{shiny_detector, black_out_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, SHINY_DETECTED_ENROUTE, shiny_coefficient); - }else if (ret == 1){ - env.log("Character blacks out"); - // black out. - stats.blackouts++; - env.update_stats(); - if (SAVE_DEBUG_VIDEO){ - // Take a video to know why it blacks out - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Black out.", - env.console - ); - } - - from_professor_return_to_jubilife(env, env.console, context); -} - -void BurmyFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - BurmyFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - TreeCounter counters; - - while (true){ - env.update_stats(); - counters.log(env.logger()); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context, counters); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Burmy Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" +#include "PokemonLA/Inference/PokemonLA_BlackOutDetector.h" +#include "PokemonLA/Inference/PokemonLA_OverworldDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h" +#include "PokemonLA/Programs/PokemonLA_LeapPokemonActions.h" +#include "CommonFramework/GlobalSettingsPanel.h" + +#ifdef _MSC_VER +#pragma warning(disable:4244) // double -> int precision loss +#endif + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +BurmyFinder_Descriptor::BurmyFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:Burmy Hunter", + STRING_POKEMON + " LA", "Burmy Hunter", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/BurmyHunter.md", + "Check nearby trees for a possible Shiny, Alpha or Alpha Shiny Burmy", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} +class BurmyFinder_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , trees(m_stats["Trees"]) + , errors(m_stats["Errors"]) + , blackouts(m_stats["Blackouts"]) + , found(m_stats["Found"]) + , enroute_shinies(m_stats["Enroute Shinies"]) + , tree_alphas(m_stats["Tree Alphas"]) + , tree_shinies(m_stats["Tree Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Trees"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Blackouts", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Found"); + m_display_order.emplace_back("Enroute Shinies"); + m_display_order.emplace_back("Tree Alphas"); + m_display_order.emplace_back("Tree Shinies"); + m_aliases["Shinies"] = "Enroute Shinies"; + m_aliases["Alphas"] = "Tree Alphas"; + } + + std::atomic& attempts; + std::atomic& trees; + std::atomic& errors; + std::atomic& blackouts; + std::atomic& found; + std::atomic& enroute_shinies; + std::atomic& tree_alphas; + std::atomic& tree_shinies; + +}; +std::unique_ptr BurmyFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +BurmyFinder::BurmyFinder() + : LANGUAGE( + "Game Language", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while traveling in the overworld.", + "0 ms" + ) + , FOUND_SHINY_OR_ALPHA( + "Found Shiny or Alpha", + true, true, + ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , MATCH_DETECTED_OPTIONS( + "Match Action", + "What to do when a Burmy is found that matches the \"Stop On\" parameter.", + "Found Shiny or Alpha" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &FOUND_SHINY_OR_ALPHA, + &MATCH_DETECTED_OPTIONS.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(STOP_ON); + PA_ADD_OPTION(EXIT_METHOD); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(MATCH_DETECTED_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + } +} + + + +struct BurmyFinder::TreeCounter{ + std::array tree = {}; + + void log(Logger& logger) const{ + std::ostringstream oss; + for(size_t i = 0; i < size(tree); i++){ + if (i != 0){ + oss << " - "; + } + oss << "Tree " << i << ": " << tostr_u_commas(tree[i]); + } + logger.log(oss.str()); + } +}; + +bool BurmyFinder::handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BurmyFinder_Descriptor::Stats& stats = env.current_stats(); + + PokemonDetails pokemon = get_pokemon_details(env.console, context, LANGUAGE); + pbf_press_button(context, BUTTON_B, 20, 225); + context.wait_for_all_requests(); + + if (pokemon.name_candidates.find("burmy") == pokemon.name_candidates.end()){ + env.console.log("Not a burmy. Leaving battle."); + exit_battle(env.console, context, EXIT_METHOD); + return false; + } + + stats.found++; + // Match validation + + if (pokemon.is_alpha && pokemon.is_shiny){ + env.console.log("Found Shiny Alpha!"); + stats.tree_shinies++; + stats.tree_alphas++; + }else if (pokemon.is_alpha){ + env.console.log("Found Alpha!"); + stats.tree_alphas++; + }else if (pokemon.is_shiny){ + env.console.log("Found Shiny!"); + stats.tree_shinies++; + }else{ + env.console.log("Normie in the tree -_-"); + } + env.update_stats(); + + bool is_match = false; + switch (STOP_ON){ + case StopOn::Shiny: + is_match = pokemon.is_shiny; + break; + case StopOn::Alpha: + is_match = pokemon.is_alpha; + break; + case StopOn::ShinyOrAlpha: + is_match = pokemon.is_alpha || pokemon.is_shiny; + break; + case StopOn::ShinyAndAlpha: + is_match = pokemon.is_alpha && pokemon.is_shiny; + break; + } + + bool notification_sent = false; + do{ + std::string str; + if (pokemon.is_shiny){ + if (pokemon.is_alpha){ + str = "Found Shiny Alpha!"; + }else{ + str = "Found Shiny!"; + } + }else{ + if (pokemon.is_alpha){ + str = "Found Alpha!"; + }else{ + break; + } + } + notification_sent |= send_program_notification( + env, FOUND_SHINY_OR_ALPHA, + Pokemon::COLOR_STAR_SHINY, + std::move(str), + {}, "", + env.console.video().snapshot(), true + ); + }while (false); + + if (is_match){ + on_battle_match_found(env, env.console, context, MATCH_DETECTED_OPTIONS, !notification_sent); + } + + exit_battle(env.console, context, EXIT_METHOD); + + return true; +} + + +bool BurmyFinder::check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + context.wait_for_all_requests(); + + disable_shiny_sound(context); + bool battle_found = check_tree_or_ore_for_battle(env.console, context); + env.current_stats().trees++; + env.update_stats(); + + context.wait_for_all_requests(); + + bool ret = false; + if (battle_found){ + ret = handle_battle(env, context); + } + + enable_shiny_sound(context); + + return ret; +} + +void BurmyFinder::check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + context.wait_for_all_requests(); + disable_shiny_sound(context); + // Throw pokemon + pbf_press_button(context, BUTTON_ZR, (0.5 * TICKS_PER_SECOND), 1.5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + env.current_stats().trees++; + env.update_stats(); +// enable_shiny_sound(context); +} + +void BurmyFinder::disable_shiny_sound(ProControllerContext& context){ + context.wait_for_all_requests(); + m_enable_shiny_sound.store(false, std::memory_order_release); +} +void BurmyFinder::enable_shiny_sound(ProControllerContext& context){ + context.wait_for_all_requests(); + m_enable_shiny_sound.store(true, std::memory_order_release); +} + +void BurmyFinder::go_to_height_camp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + const bool stop_on_detected = true; + BattleMenuDetector battle_menu_detector(env.console, env.console, stop_on_detected); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); + }, + { + {battle_menu_detector}, + } + ); + if (ret == 0){ + env.log("Warning: found inside a battle when trying to return to camp."); + // Unexpected battle during movement to camp + if (SAVE_DEBUG_VIDEO){ + // Take a video to know why it enters battle during return trip + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + // Finish battle + handle_battle(env, context); + // Go back to camp + goto_any_camp_from_overworld(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); + } +} + +size_t BurmyFinder::grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, TreeCounter& tree_counter){ + + size_t last_checked_tree = 0; + + if (path != 0){ + go_to_height_camp(env, context); + } + + env.console.log("Currently Checking Path:" + std::to_string(path)); + + BattleMenuDetector battle_menu_detector(env.console, env.console, true); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + switch (path){ + case 0: + //============ Tree 0=============// + env.console.log("Checking tree: 0"); + pbf_move_left_joystick(context, 255, 85, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.6 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_wait(context, 0.7 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_B, (5.1 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4.2 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 128, 255, (0.3 * TICKS_PER_SECOND), (0.2 * TICKS_PER_SECOND)); + last_checked_tree = 0; + check_tree_no_stop(env, context); + + //============ Tree 1=============// + env.console.log("Checking tree: 1"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 10, 1 * TICKS_PER_SECOND, 0); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (0.6 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (2.7 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 128, 255, (0.1 * TICKS_PER_SECOND), (0.3 * TICKS_PER_SECOND)); + last_checked_tree = 1; + check_tree_no_stop(env, context); + + //============ Tree 2=============// + env.console.log("Checking tree: 2"); + pbf_press_button(context, BUTTON_PLUS, 20, 100); + pbf_move_left_joystick(context, 255, 130, 1 * TICKS_PER_SECOND, 0); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (0.6 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (2.4 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 128, 255, (0.1 * TICKS_PER_SECOND), (0.3 * TICKS_PER_SECOND)); + last_checked_tree = 2; + check_tree_no_stop(env, context); + + //============ Tree 3=============// + env.console.log("Checking tree: 3"); + pbf_press_button(context, BUTTON_PLUS, 20, 100); + pbf_move_left_joystick(context, 0, 95, 1 * TICKS_PER_SECOND, 0); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, 110, 0); + pbf_press_button(context, BUTTON_Y, (2.3 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 128, 255, (0.1 * TICKS_PER_SECOND), (0.3 * TICKS_PER_SECOND)); + last_checked_tree = 3; + break; + case 1: + //============ Tree 4=============// + env.console.log("Checking tree: 4"); + pbf_move_left_joystick(context, 255, 165, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_wait(context, 0.6 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_B, (4.8 * TICKS_PER_SECOND), (0.6 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_Y, (1.7 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 4; + check_tree_no_stop(env, context); + + //============ Tree 5=============// + env.console.log("Checking tree: 5"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 190, 1 * TICKS_PER_SECOND, 0); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (0.5 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (2.6 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.15 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 5; + check_tree_no_stop(env, context); + + //============ Tree 6=============// + env.console.log("Checking tree: 6"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 0, 130, 1 * TICKS_PER_SECOND, 0); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (1.3 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (3.2 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.15 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 6; + break; + case 2: + //============ Tree 7=============// + env.console.log("Checking tree: 7"); + pbf_move_left_joystick(context, 180, 255, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (7.2 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4.2 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 0, 127, (1.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, 20); + pbf_move_right_joystick(context, 127, 255, (0.5 * TICKS_PER_SECOND), 20); + last_checked_tree = 7; + check_tree_no_stop(env, context); + + //============ Tree 8=============// + env.console.log("Checking tree: 8"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 230, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_Y, (1.7 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 8; + check_tree_no_stop(env, context); + + //============ Tree 9=============// + env.console.log("Checking tree: 8"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 90, 0, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (0.6 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 9; + check_tree_no_stop(env, context); + + //============ Tree 10=============// + env.console.log("Checking tree: 10"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 0, 235, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (2.5 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (2.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 10; + check_tree_no_stop(env, context); + + //============ Tree 11=============// + env.console.log("Checking tree: 11"); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 145, 0, (0.5 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (1.8 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (1.8 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.3 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 11; + break; + case 3: + //============ Tree 12=============// + env.console.log("Checking tree: 12"); + pbf_move_left_joystick(context, 148, 255, 20, 20); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (9.7 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_Y, (2.2 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 127, 30, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 12; + check_tree_no_stop(env, context); + + //============ Tree 13=============// + env.console.log("Checking tree: 13"); + pbf_move_left_joystick(context, 148, 0, 20, 20); + change_mount(env.console, context, MountState::BRAVIARY_ON); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_B, (2 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (3 * TICKS_PER_SECOND), 0); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 13; + check_tree_no_stop(env, context); + + //============ Tree 14=============// + env.console.log("Checking tree: 14"); + pbf_move_left_joystick(context, 255, 155, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_move_left_joystick(context, 127, 0, (6.6 * TICKS_PER_SECOND), 20); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 14; + check_tree_no_stop(env, context); + + //============ Tree 15=============// + env.console.log("Checking tree: 15"); + pbf_move_left_joystick(context, 200, 0, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + context.wait_for_all_requests(); + enable_shiny_sound(context); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_B, (1.7 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (3 * TICKS_PER_SECOND), 0); + pbf_move_right_joystick(context, 127, 255, (0.1 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + last_checked_tree = 15; + break; + } + }, + { + {battle_menu_detector}, + } + ); + + if (ret == 0){ + if (handle_battle(env, context)){ + env.console.log("Battle found before last tree in the path."); + tree_counter.tree[last_checked_tree]++; + } + }else{ + // Check last tree + if (check_tree(env, context)){ + tree_counter.tree[last_checked_tree]++; + } + env.console.log("Checked all trees in the path."); + } + + return last_checked_tree; +} + +void BurmyFinder::single_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, size_t last_tree, TreeCounter& tree_counter){ + env.console.log("Last tree was: " + std::to_string(last_tree)); + + switch (path){ + case 0: + if (last_tree < 1){ + env.console.log("Heading to tree 1"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 255, 110, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (7.2 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4.5 * TICKS_PER_SECOND), 0); + pbf_move_left_joystick(context, 180, 0, 20, (0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[1]++; + } + } + + if (last_tree < 2){ + env.console.log("Heading to tree 2"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 255, 147, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (6.6 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4.4 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[2]++; + } + } + + if (last_tree < 3){ + env.console.log("Heading to tree 3"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 255, 158, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (9.5 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4.5 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[3]++; + } + } + break; + case 1: + if (last_tree < 5){ + env.console.log("Heading to Tree 5"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 240, 240, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (5.95 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1.2 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 0, 0, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[5]++; + } + } + + if (last_tree < 6){ + env.console.log("Heading to Tree 6"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 255, 235, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (8 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4 * TICKS_PER_SECOND), 0); + if (check_tree(env, context)){ + tree_counter.tree[6]++; + } + } + break; + + case 2: + if (last_tree < 8){ + env.console.log("Heading to Tree 8"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 173, 255, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (8.8 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (4 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, 20); + if (check_tree(env, context)){ + tree_counter.tree[8]++; + } + } + + if (last_tree < 9){ + env.console.log("Heading to Tree 9"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 163, 255, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (11.7 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (3.8 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, 20); + if (check_tree(env, context)){ + tree_counter.tree[8]++; + } + } + + if (last_tree < 10){ + env.console.log("Heading to Tree 10"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 218, 255, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (10.4 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (3.8 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, 20); + if (check_tree(env, context)){ + tree_counter.tree[8]++; + } + } + + if (last_tree < 11){ + env.console.log("Heading to Tree 11"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 255, 230, 20, (0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (11.4 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_Y, (3.8 * TICKS_PER_SECOND), 0); + pbf_press_button(context, BUTTON_PLUS, 20, 20); + if (check_tree(env, context)){ + tree_counter.tree[11]++; + } + } + break; + case 3: + if (last_tree < 13){ + env.console.log("Heading to Tree 13"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 104, 255, 30, 30); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (11 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1.3 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[13]++; + } + } + + if (last_tree < 14){ + env.console.log("Heading to Tree 14"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 108, 255, 20, 20); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (8.7 * TICKS_PER_SECOND), (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 140, 255, 20, 20); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 140, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[14]++; + } + } + if (last_tree < 15){ + env.console.log("Heading to Tree 15"); + go_to_height_camp(env, context); + pbf_move_left_joystick(context, 160, 255, 30, 30); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_press_button(context, BUTTON_B, (6.35 * TICKS_PER_SECOND), 20); + pbf_press_button(context, BUTTON_PLUS, 20, (1 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_PLUS, 20, (1.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 255, 135, 30, (0.5 * TICKS_PER_SECOND)); + pbf_press_button(context, BUTTON_ZL, 20, (0.5 * TICKS_PER_SECOND)); + pbf_move_right_joystick(context, 127, 255, (0.2 * TICKS_PER_SECOND), (0.5 * TICKS_PER_SECOND)); + if (check_tree(env, context)){ + tree_counter.tree[15]++; + } + } + + break; + + } + +} + +void BurmyFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, TreeCounter& tree_counter){ + BurmyFinder_Descriptor::Stats& stats = env.current_stats(); + stats.attempts++; + env.update_stats(); + env.console.log("Starting route and shiny detection..."); + + for (size_t c = 0; true; c++){ + context.wait_for_all_requests(); + auto snapshot = env.console.video().snapshot(); + if (is_pokemon_selection(env.console, snapshot)){ + break; + } + if (c >= 5){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to switch to Pokemon selection after 5 attempts.", + env.console, + std::move(snapshot) + ); + } + env.console.log("Not on Pokemon selection. Attempting to switch to it...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_X, 20, 230); + } + + float shiny_coefficient = 1.0; + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + if (!m_enable_shiny_sound.load()){ + return false; + } + stats.enroute_shinies++; + shiny_coefficient = error_coefficient; + return on_shiny_callback(env, env.console, SHINY_DETECTED_ENROUTE, error_coefficient); + }); + + BlackOutDetector black_out_detector(env.console, env.console); + + goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Fieldlands_Heights); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + + for (int path = 0; path < 4; path++){ + size_t last_tree = grouped_path(env, context, path, tree_counter); + context.wait_for_all_requests(); + single_path(env, context, path, last_tree, tree_counter); + context.wait_for_all_requests(); + } + // End + goto_camp_from_overworld(env, env.console, context); + goto_professor(env.console, context, Camp::FIELDLANDS_FIELDLANDS); + }, + {{shiny_detector, black_out_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, SHINY_DETECTED_ENROUTE, shiny_coefficient); + }else if (ret == 1){ + env.log("Character blacks out"); + // black out. + stats.blackouts++; + env.update_stats(); + if (SAVE_DEBUG_VIDEO){ + // Take a video to know why it blacks out + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Black out.", + env.console + ); + } + + from_professor_return_to_jubilife(env, env.console, context); +} + +void BurmyFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BurmyFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + TreeCounter counters; + + while (true){ + env.update_stats(); + counters.log(env.logger()); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context, counters); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h index 055e207a10..2f97382beb 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_BurmyFinder.h @@ -1,113 +1,113 @@ -/* Burmy Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_BurmyFinder_H -#define PokemonAutomation_PokemonLA_BurmyFinder_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_MiscOptions.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class BurmyFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BurmyFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class BurmyFinder : public SingleSwitchProgramInstance{ -public: - BurmyFinder(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - struct TreeCounter; - - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, TreeCounter& tree_counter); - // Press X to throw pokemon, check whether there is pokemon in the tree. Wait for potential battle - // after pokemon is thrown. - // Return true if encountering a burmy in the tree. False otherwise. - // Also during pokemon throwing and battle, disable shiny sound detection. This is because a shiny burmy - // will play the shiny sound when it jumps out of the tree. To avoid this shiny sound be categorized as - // enroute shiny, we disable the sound detection when a burmy may jump out. - bool check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - // Throw pokemon to check a tree. - // Does not wait for potential battle to start. - // Unlike `check_tree()`, shiny sound detection is not disabled. - void check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // While during battle, press + button to check pokemon details. - // May throw ProgramFinishedException if a Burmy match is found. - // Finish battle by mashing A or escape. - // Return true if a burmy is in the battle. False otherwise. - bool handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // Set `m_enable_shiny_sound` to false to disable sound detection. - // Also call `context.wait_for_all_requests()` to make sure controller commands are all executed. - // See `m_enable_shiny_sound` for more context. - void disable_shiny_sound(ProControllerContext& context); - // Re-enable shiny sound detection. - // Also call `context.wait_for_all_requests()` to make sure controller commands are all executed. - // See `m_enable_shiny_sound` for more context. - void enable_shiny_sound(ProControllerContext& context); - - // From any place on the fieldlands, return to Height Camp. - // It will try to ride on Braviary to escape from attacking pokemon if it can not transport via map. - // For robustness, the function will detect pokemon battles if for some reason the player character - // is entering a pokemon battle when this function is called. - // In the case of an active battle, it calls `handle_battle()` to check potential Burmy and then finish - // battle. After that, try to go back to Height Camp again. - void go_to_height_camp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // From camp it will go to trees in sequence instead of heading to camp. - // It returns the last tree checked so the remain can be checked on single_path - size_t grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, TreeCounter& tree_counter); - - // Check trees individually going from camp based on the last tree checked for each path - void single_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, size_t last_tree, TreeCounter& tree_counter); - - -private: - class RunRoute; - - // Atomic bool to control whether to skip shiny sound for shiny sound detector. - // Shiny pokemon will play the shiny sound when it jumps out of a tree. To prevent this shiny sound from being - // treated as enroute shiny (shiny tree pokemon should be regarded as tree shiny), we disable shiny sound - // detection when throwing pokemon to shake a tree. - std::atomic m_enable_shiny_sound{true}; - - OCR::LanguageOCROption LANGUAGE; - StopOnOption STOP_ON; - ExitBattleMethodOption EXIT_METHOD; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - EventNotificationOption FOUND_SHINY_OR_ALPHA; - BattleMatchActionOption MATCH_DETECTED_OPTIONS; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; - - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; -}; - - - - - -} -} -} -#endif +/* Burmy Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_BurmyFinder_H +#define PokemonAutomation_PokemonLA_BurmyFinder_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_MiscOptions.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class BurmyFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BurmyFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class BurmyFinder : public SingleSwitchProgramInstance{ +public: + BurmyFinder(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + struct TreeCounter; + + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, TreeCounter& tree_counter); + // Press X to throw pokemon, check whether there is pokemon in the tree. Wait for potential battle + // after pokemon is thrown. + // Return true if encountering a burmy in the tree. False otherwise. + // Also during pokemon throwing and battle, disable shiny sound detection. This is because a shiny burmy + // will play the shiny sound when it jumps out of the tree. To avoid this shiny sound be categorized as + // enroute shiny, we disable the sound detection when a burmy may jump out. + bool check_tree(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + // Throw pokemon to check a tree. + // Does not wait for potential battle to start. + // Unlike `check_tree()`, shiny sound detection is not disabled. + void check_tree_no_stop(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // While during battle, press + button to check pokemon details. + // May throw ProgramFinishedException if a Burmy match is found. + // Finish battle by mashing A or escape. + // Return true if a burmy is in the battle. False otherwise. + bool handle_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // Set `m_enable_shiny_sound` to false to disable sound detection. + // Also call `context.wait_for_all_requests()` to make sure controller commands are all executed. + // See `m_enable_shiny_sound` for more context. + void disable_shiny_sound(ProControllerContext& context); + // Re-enable shiny sound detection. + // Also call `context.wait_for_all_requests()` to make sure controller commands are all executed. + // See `m_enable_shiny_sound` for more context. + void enable_shiny_sound(ProControllerContext& context); + + // From any place on the fieldlands, return to Height Camp. + // It will try to ride on Braviary to escape from attacking pokemon if it can not transport via map. + // For robustness, the function will detect pokemon battles if for some reason the player character + // is entering a pokemon battle when this function is called. + // In the case of an active battle, it calls `handle_battle()` to check potential Burmy and then finish + // battle. After that, try to go back to Height Camp again. + void go_to_height_camp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // From camp it will go to trees in sequence instead of heading to camp. + // It returns the last tree checked so the remain can be checked on single_path + size_t grouped_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, TreeCounter& tree_counter); + + // Check trees individually going from camp based on the last tree checked for each path + void single_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path, size_t last_tree, TreeCounter& tree_counter); + + +private: + class RunRoute; + + // Atomic bool to control whether to skip shiny sound for shiny sound detector. + // Shiny pokemon will play the shiny sound when it jumps out of a tree. To prevent this shiny sound from being + // treated as enroute shiny (shiny tree pokemon should be regarded as tree shiny), we disable shiny sound + // detection when throwing pokemon to shake a tree. + std::atomic m_enable_shiny_sound{true}; + + OCR::LanguageOCROption LANGUAGE; + StopOnOption STOP_ON; + ExitBattleMethodOption EXIT_METHOD; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + EventNotificationOption FOUND_SHINY_OR_ALPHA; + BattleMatchActionOption MATCH_DETECTED_OPTIONS; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; + + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.cpp index 0236f78956..c9475959ab 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.cpp @@ -1,218 +1,218 @@ -/* Alpha Crobat Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA_CrobatFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - -CrobatFinder_Descriptor::CrobatFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:CrobatFinder", - STRING_POKEMON + " LA", "Alpha Crobat Hunter", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AlphaCrobatHunter.md", - "Constantly reset the cave to find Shiny Alpha Crobat.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class CrobatFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr CrobatFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -CrobatFinder::CrobatFinder() - : SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if you are still traveling to the Crobat.", - "2000 ms" - ) - , SHINY_DETECTED_DESTINATION( - "Destination Shiny Action", - "This applies if you are near the Crobat.", - "2000 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void CrobatFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // NOTE: there's no "stunned by alpha" detection in case any of the close ones are alphas! - CrobatFinder_Descriptor::Stats& stats = env.current_stats(); - - stats.attempts++; - - // program should be started right in front of the entrance - // so enter the sub region - env.console.log("Entering Wayward Cave..."); - mash_A_to_enter_sub_area(env, env.console, context); - - env.console.log("Beginning navigation to the Alpha Crobat..."); - // Switch to Wrydeer. - bool error = true; - MountDetector mount_detector; - for (size_t c = 0; c < 10; c++){ - MountState mount = mount_detector.detect(env.console.video().snapshot()); - if (mount == MountState::WYRDEER_OFF){ - pbf_press_button(context, BUTTON_PLUS, 20, 105); - error = false; - break; - } - if (mount == MountState::WYRDEER_ON){ - pbf_wait(context, 5 * TICKS_PER_SECOND); - error = false; - break; - } - pbf_press_dpad(context, DPAD_LEFT, 20, 50); - context.wait_for_all_requests(); - } - if (error){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find Wyrdeer after 10 attempts.", - env.console - ); - } - - env.console.log("Beginning Shiny Detection..."); - // start the shiny detection, there's nothing initially - { - float shiny_coefficient = 1.0; - std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); - WallClock destination_time = WallClock::max(); - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - return on_shiny_callback(env, env.console, *action, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - - // FORWARD PORTION OF CAVE UNTIL LEDGE - pbf_press_button(context, BUTTON_B, 2200ms, 640ms); // wyrdeer sprint - pbf_move_left_joystick(context, 0, 128, 10, 20); // turn left - pbf_press_button(context, BUTTON_ZL, 20, 50); // align camera - - // ASCEND THE LEDGE WITH BRAVIARY - pbf_press_dpad(context, DPAD_RIGHT, 20, 50); // swap to braviary - pbf_wait(context, 600ms); // wait for the ascent - pbf_press_button(context, BUTTON_Y, 2400ms, 160ms); // descend to swap to Wyrdeer automatically - - // TO CROBAT PORTION - pbf_press_button(context, BUTTON_B, 1050ms, 640ms); // sprint forward for a split second - pbf_move_left_joystick(context, 255, 150, 10, 20); // rotate slightly right - pbf_press_button(context, BUTTON_ZL, 20, 70); // align camera - - context.wait_for_all_requests(); - destination_time = current_time(); - shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); - - pbf_move_left_joystick(context, 128, 0, (uint16_t)(3.8 * TICKS_PER_SECOND), 0); // forward to crobat check - - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0 || shiny_detector.last_detection() > destination_time){ - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - on_shiny_sound(env, env.console, context, *action, shiny_coefficient); - } - }; - - // then reset since no shiny was found - env.console.log("No shiny detected, restarting the game!"); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); -} - - -void CrobatFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - CrobatFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Alpha Crobat Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA_CrobatFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + +CrobatFinder_Descriptor::CrobatFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:CrobatFinder", + STRING_POKEMON + " LA", "Alpha Crobat Hunter", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AlphaCrobatHunter.md", + "Constantly reset the cave to find Shiny Alpha Crobat.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class CrobatFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr CrobatFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +CrobatFinder::CrobatFinder() + : SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if you are still traveling to the Crobat.", + "2000 ms" + ) + , SHINY_DETECTED_DESTINATION( + "Destination Shiny Action", + "This applies if you are near the Crobat.", + "2000 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void CrobatFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // NOTE: there's no "stunned by alpha" detection in case any of the close ones are alphas! + CrobatFinder_Descriptor::Stats& stats = env.current_stats(); + + stats.attempts++; + + // program should be started right in front of the entrance + // so enter the sub region + env.console.log("Entering Wayward Cave..."); + mash_A_to_enter_sub_area(env, env.console, context); + + env.console.log("Beginning navigation to the Alpha Crobat..."); + // Switch to Wrydeer. + bool error = true; + MountDetector mount_detector; + for (size_t c = 0; c < 10; c++){ + MountState mount = mount_detector.detect(env.console.video().snapshot()); + if (mount == MountState::WYRDEER_OFF){ + pbf_press_button(context, BUTTON_PLUS, 20, 105); + error = false; + break; + } + if (mount == MountState::WYRDEER_ON){ + pbf_wait(context, 5 * TICKS_PER_SECOND); + error = false; + break; + } + pbf_press_dpad(context, DPAD_LEFT, 20, 50); + context.wait_for_all_requests(); + } + if (error){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find Wyrdeer after 10 attempts.", + env.console + ); + } + + env.console.log("Beginning Shiny Detection..."); + // start the shiny detection, there's nothing initially + { + float shiny_coefficient = 1.0; + std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); + WallClock destination_time = WallClock::max(); + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + return on_shiny_callback(env, env.console, *action, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + + // FORWARD PORTION OF CAVE UNTIL LEDGE + pbf_press_button(context, BUTTON_B, 2200ms, 640ms); // wyrdeer sprint + pbf_move_left_joystick(context, 0, 128, 10, 20); // turn left + pbf_press_button(context, BUTTON_ZL, 20, 50); // align camera + + // ASCEND THE LEDGE WITH BRAVIARY + pbf_press_dpad(context, DPAD_RIGHT, 20, 50); // swap to braviary + pbf_wait(context, 600ms); // wait for the ascent + pbf_press_button(context, BUTTON_Y, 2400ms, 160ms); // descend to swap to Wyrdeer automatically + + // TO CROBAT PORTION + pbf_press_button(context, BUTTON_B, 1050ms, 640ms); // sprint forward for a split second + pbf_move_left_joystick(context, 255, 150, 10, 20); // rotate slightly right + pbf_press_button(context, BUTTON_ZL, 20, 70); // align camera + + context.wait_for_all_requests(); + destination_time = current_time(); + shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); + + pbf_move_left_joystick(context, 128, 0, (uint16_t)(3.8 * TICKS_PER_SECOND), 0); // forward to crobat check + + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0 || shiny_detector.last_detection() > destination_time){ + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + on_shiny_sound(env, env.console, context, *action, shiny_coefficient); + } + }; + + // then reset since no shiny was found + env.console.log("No shiny detected, restarting the game!"); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); +} + + +void CrobatFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + CrobatFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.h index bbeb50902f..0b7c6e00b9 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_CrobatFinder.h @@ -1,53 +1,53 @@ -/* Alpha Crobat Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_CrobatFinder_H -#define PokemonAutomation_PokemonLA_CrobatFinder_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class CrobatFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - CrobatFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class CrobatFinder : public SingleSwitchProgramInstance{ -public: - CrobatFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Alpha Crobat Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_CrobatFinder_H +#define PokemonAutomation_PokemonLA_CrobatFinder_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class CrobatFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + CrobatFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class CrobatFinder : public SingleSwitchProgramInstance{ +public: + CrobatFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.cpp index 0577229dfb..5d058db093 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.cpp @@ -1,198 +1,198 @@ -/* Alpha Froslass Finder -* -* From: https://github.com/PokemonAutomation/ -* -*/ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -FroslassFinder_Descriptor::FroslassFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:AlphaFroslassFinder", - STRING_POKEMON + " LA", "Alpha Froslass Hunter", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AlphaFroslassHunter.md", - "Constantly reset to find a Alpha Froslass or any Shiny in the path.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class FroslassFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr FroslassFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -FroslassFinder::FroslassFinder() - : DASH_DURATION0( - "Braviary dash duration:
" - "How many ticks for Braviary to dash to reach the hole.", - LockMode::LOCK_WHILE_RUNNING, - "7888" - ) - , SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while enroute to the cave. (Does not ignore Misdreavus and Glalie)", - "0 ms" - ) - , SHINY_DETECTED_DESTINATION( - "Destination Shiny Action", - "This applies if a shiny is detected at or near Froslass.", - "0 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(DASH_DURATION0); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void FroslassFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - FroslassFinder_Descriptor::Stats& stats = env.current_stats(); - - stats.attempts++; - - goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Icelands_Arena); - - //Start path - env.console.log("Beginning Shiny Detection..."); - - //Setup - pbf_move_left_joystick(context, 108, 255, 20, 20); - pbf_press_button(context, BUTTON_ZL, 10,10); - pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); - change_mount(env.console, context, MountState::BRAVIARY_ON); - pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); - - { - float shiny_coefficient = 1.0; - std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); - WallClock destination_time = WallClock::max(); - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - return on_shiny_callback(env, env.console, *action, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - // Route to cave entrance - pbf_press_button(context, BUTTON_B, 2000ms, 80ms); //Get some distance from the moutain - pbf_press_button(context, BUTTON_Y, 4000ms, 80ms); //Descend - pbf_press_button(context, BUTTON_B, DASH_DURATION0, 80ms); //Reach to the cave entrance - pbf_wait(context, 500ms); - pbf_press_button(context, BUTTON_PLUS, 80ms, 80ms); - pbf_wait(context, 1100ms); - pbf_press_button(context, BUTTON_PLUS, 80ms, 80ms); - pbf_press_button(context, BUTTON_B, 2800ms, 80ms); // Braviary Second Push - - context.wait_for_all_requests(); - destination_time = current_time(); - shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); - - // Move to Froslass - pbf_press_dpad(context, DPAD_LEFT, 160ms, 160ms); - pbf_press_button(context, BUTTON_B, 5000ms, 2000ms); - context.wait_for_all_requests(); - - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0 || shiny_detector.last_detection() > destination_time){ - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - on_shiny_sound(env, env.console, context, *action, shiny_coefficient); - } - } - - env.console.log("No shiny detected, Reset game!"); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); -} - - -void FroslassFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - FroslassFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Alpha Froslass Finder +* +* From: https://github.com/PokemonAutomation/ +* +*/ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +FroslassFinder_Descriptor::FroslassFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:AlphaFroslassFinder", + STRING_POKEMON + " LA", "Alpha Froslass Hunter", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AlphaFroslassHunter.md", + "Constantly reset to find a Alpha Froslass or any Shiny in the path.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class FroslassFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr FroslassFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +FroslassFinder::FroslassFinder() + : DASH_DURATION0( + "Braviary dash duration:
" + "How many ticks for Braviary to dash to reach the hole.", + LockMode::LOCK_WHILE_RUNNING, + "7888" + ) + , SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while enroute to the cave. (Does not ignore Misdreavus and Glalie)", + "0 ms" + ) + , SHINY_DETECTED_DESTINATION( + "Destination Shiny Action", + "This applies if a shiny is detected at or near Froslass.", + "0 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(DASH_DURATION0); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void FroslassFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + FroslassFinder_Descriptor::Stats& stats = env.current_stats(); + + stats.attempts++; + + goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Icelands_Arena); + + //Start path + env.console.log("Beginning Shiny Detection..."); + + //Setup + pbf_move_left_joystick(context, 108, 255, 20, 20); + pbf_press_button(context, BUTTON_ZL, 10,10); + pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); + change_mount(env.console, context, MountState::BRAVIARY_ON); + pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); + + { + float shiny_coefficient = 1.0; + std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); + WallClock destination_time = WallClock::max(); + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + return on_shiny_callback(env, env.console, *action, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + // Route to cave entrance + pbf_press_button(context, BUTTON_B, 2000ms, 80ms); //Get some distance from the moutain + pbf_press_button(context, BUTTON_Y, 4000ms, 80ms); //Descend + pbf_press_button(context, BUTTON_B, DASH_DURATION0, 80ms); //Reach to the cave entrance + pbf_wait(context, 500ms); + pbf_press_button(context, BUTTON_PLUS, 80ms, 80ms); + pbf_wait(context, 1100ms); + pbf_press_button(context, BUTTON_PLUS, 80ms, 80ms); + pbf_press_button(context, BUTTON_B, 2800ms, 80ms); // Braviary Second Push + + context.wait_for_all_requests(); + destination_time = current_time(); + shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); + + // Move to Froslass + pbf_press_dpad(context, DPAD_LEFT, 160ms, 160ms); + pbf_press_button(context, BUTTON_B, 5000ms, 2000ms); + context.wait_for_all_requests(); + + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0 || shiny_detector.last_detection() > destination_time){ + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + on_shiny_sound(env, env.console, context, *action, shiny_coefficient); + } + } + + env.console.log("No shiny detected, Reset game!"); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); +} + + +void FroslassFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + FroslassFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h index efc88a24a9..048b229895 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_FroslassFinder.h @@ -1,53 +1,53 @@ -/* Alpha Froslass Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_FroslassFinder_H -#define PokemonAutomation_PokemonLA_FroslassFinder_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -class FroslassFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FroslassFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class FroslassFinder : public SingleSwitchProgramInstance{ -public: - FroslassFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - class RunRoute; - - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - MillisecondsOption DASH_DURATION0; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - +/* Alpha Froslass Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_FroslassFinder_H +#define PokemonAutomation_PokemonLA_FroslassFinder_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +class FroslassFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FroslassFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class FroslassFinder : public SingleSwitchProgramInstance{ +public: + FroslassFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + class RunRoute; + + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + MillisecondsOption DASH_DURATION0; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.cpp index ef26419c14..6383902e2d 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.cpp @@ -1,202 +1,202 @@ -/* Alpha Gallade Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA_GalladeFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -GalladeFinder_Descriptor::GalladeFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:GalladeFinder", - STRING_POKEMON + " LA", "Alpha Gallade Hunter", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AlphaGalladeHunter.md", - "Constantly reset the Snowpoint Temple to find Shiny Alpha Gallade.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class GalladeFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr GalladeFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -GalladeFinder::GalladeFinder() - : SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if you are still traveling to the Gallade.", - "0 ms" - ) - , SHINY_DETECTED_DESTINATION( - "Destination Shiny Action", - "This applies if you are near the Gallade.", - "0 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void GalladeFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // NOTE: there's no "stunned by alpha" detection in case the first spawn is an alpha! - // NOTE: there is also no mitigation for if you get attacked by a Kirlia if it hates you - GalladeFinder_Descriptor::Stats& stats = env.current_stats(); - - stats.attempts++; - - // program should be started right in front of the entrance - // so enter the sub region - env.console.log("Entering Snowpoint Temple..."); - mash_A_to_enter_sub_area(env, env.console, context); - - env.console.log("Beginning navigation to the Alpha Gallade..."); - // start the shiny detection, there's nothing initially - env.console.log("Enabling Shiny Detection..."); - { - float shiny_coefficient = 1.0; - std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); - WallClock destination_time = WallClock::max(); - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - return on_shiny_callback(env, env.console, *action, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - // forward portion - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 6800ms); // forward while running until stairs, mash y a few times down the stairs - pbf_mash_button(context, BUTTON_Y, 2800ms); // roll down the stairs, recover stamina - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 4000ms); // forward while sprinting again - pbf_mash_button(context, BUTTON_Y, 2000ms); // two mashes and then one y - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 3800ms); // forward while sprinting again - // basic map layout is walk forward for a while, move right, run back, then align camera, then walk left then forward to Gallade - - // right portion - pbf_move_left_joystick(context, 255, 128, 500ms, 0ms); // right alone - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 255, 128, 128, 128, 2400ms); // forward while running until stairs - pbf_mash_button(context, BUTTON_Y, 1800ms); // roll down the stairs, recover stamina - pbf_move_left_joystick(context, 255, 128, 1800ms, 160ms); // right alone - - // down portion - // pbf_move_left_joystick(context, 128, 255, (uint16_t)(1.9 * TICKS_PER_SECOND), 20); // OLD down - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 255, 128, 128, 1800ms); - - // camera align - pbf_press_button(context, BUTTON_ZL, 20, 0); // camera align - pbf_wait(context, 70); - - context.wait_for_all_requests(); - destination_time = current_time(); - shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); - - pbf_move_left_joystick(context, 0, 128, 2000ms, 0ms); // left - - // then forward left - pbf_move_left_joystick(context, 0, 0, 1100ms, 0ms); - - //pbf_move_left_joystick(context, 128, 0, 3.9 * TICKS_PER_SECOND, 0); // OLD forward - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 3500ms); // forward while sprinting until stairs, mash y a few times down the stairs - // we should easily be in range of gallade at this point, so if there's no shiny we're done - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0 || shiny_detector.last_detection() > destination_time){ - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - on_shiny_sound(env, env.console, context, *action, shiny_coefficient); - } - }; - - // then reset - env.console.log("No shiny detected, restarting the game!"); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); -} - - -void GalladeFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - GalladeFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Alpha Gallade Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA_GalladeFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +GalladeFinder_Descriptor::GalladeFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:GalladeFinder", + STRING_POKEMON + " LA", "Alpha Gallade Hunter", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/AlphaGalladeHunter.md", + "Constantly reset the Snowpoint Temple to find Shiny Alpha Gallade.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class GalladeFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr GalladeFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +GalladeFinder::GalladeFinder() + : SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if you are still traveling to the Gallade.", + "0 ms" + ) + , SHINY_DETECTED_DESTINATION( + "Destination Shiny Action", + "This applies if you are near the Gallade.", + "0 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void GalladeFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // NOTE: there's no "stunned by alpha" detection in case the first spawn is an alpha! + // NOTE: there is also no mitigation for if you get attacked by a Kirlia if it hates you + GalladeFinder_Descriptor::Stats& stats = env.current_stats(); + + stats.attempts++; + + // program should be started right in front of the entrance + // so enter the sub region + env.console.log("Entering Snowpoint Temple..."); + mash_A_to_enter_sub_area(env, env.console, context); + + env.console.log("Beginning navigation to the Alpha Gallade..."); + // start the shiny detection, there's nothing initially + env.console.log("Enabling Shiny Detection..."); + { + float shiny_coefficient = 1.0; + std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); + WallClock destination_time = WallClock::max(); + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + return on_shiny_callback(env, env.console, *action, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + // forward portion + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 6800ms); // forward while running until stairs, mash y a few times down the stairs + pbf_mash_button(context, BUTTON_Y, 2800ms); // roll down the stairs, recover stamina + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 4000ms); // forward while sprinting again + pbf_mash_button(context, BUTTON_Y, 2000ms); // two mashes and then one y + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 3800ms); // forward while sprinting again + // basic map layout is walk forward for a while, move right, run back, then align camera, then walk left then forward to Gallade + + // right portion + pbf_move_left_joystick(context, 255, 128, 500ms, 0ms); // right alone + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 255, 128, 128, 128, 2400ms); // forward while running until stairs + pbf_mash_button(context, BUTTON_Y, 1800ms); // roll down the stairs, recover stamina + pbf_move_left_joystick(context, 255, 128, 1800ms, 160ms); // right alone + + // down portion + // pbf_move_left_joystick(context, 128, 255, (uint16_t)(1.9 * TICKS_PER_SECOND), 20); // OLD down + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 255, 128, 128, 1800ms); + + // camera align + pbf_press_button(context, BUTTON_ZL, 20, 0); // camera align + pbf_wait(context, 70); + + context.wait_for_all_requests(); + destination_time = current_time(); + shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); + + pbf_move_left_joystick(context, 0, 128, 2000ms, 0ms); // left + + // then forward left + pbf_move_left_joystick(context, 0, 0, 1100ms, 0ms); + + //pbf_move_left_joystick(context, 128, 0, 3.9 * TICKS_PER_SECOND, 0); // OLD forward + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, 3500ms); // forward while sprinting until stairs, mash y a few times down the stairs + // we should easily be in range of gallade at this point, so if there's no shiny we're done + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0 || shiny_detector.last_detection() > destination_time){ + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + on_shiny_sound(env, env.console, context, *action, shiny_coefficient); + } + }; + + // then reset + env.console.log("No shiny detected, restarting the game!"); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); +} + + +void GalladeFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + GalladeFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.h index 7b51e78739..d828168c86 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_GalladeFinder.h @@ -1,53 +1,53 @@ -/* Alpha Gallade Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_GalladeFinder_H -#define PokemonAutomation_PokemonLA_GalladeFinder_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class GalladeFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GalladeFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class GalladeFinder : public SingleSwitchProgramInstance{ -public: - GalladeFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Alpha Gallade Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_GalladeFinder_H +#define PokemonAutomation_PokemonLA_GalladeFinder_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class GalladeFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GalladeFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class GalladeFinder : public SingleSwitchProgramInstance{ +public: + GalladeFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.cpp index cf65aaae15..e86ba9f76d 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.cpp @@ -1,174 +1,174 @@ -/* Post MMO Spawn Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA_PostMMOSpawnReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -PostMMOSpawnReset_Descriptor::PostMMOSpawnReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:PostMMOSpawnReset", - STRING_POKEMON + " LA", "Post-MMO Spawn Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/PostMMOSpawnReset.md", - "Constantly reset the spawn after MMO finishes.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class PostMMOSpawnReset_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr PostMMOSpawnReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -PostMMOSpawnReset::PostMMOSpawnReset() - : TURN_DURATION0( - "Camera Turn:
How many ticks to turn the camera.
Positive values for right turns. Negative values for left turns.", - LockMode::LOCK_WHILE_RUNNING, - "0 ms" - ) - , FORWARD_DURATION0( - "Move Forward:
After turning the camera, how many ticks to move forward.", - LockMode::LOCK_WHILE_RUNNING, - "0 ms" - ) - , WAIT_DURATION0( - "Wait Time:
Wait time after movement.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , SHINY_DETECTED("Shiny Detected Action", "", "0 ms") - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(TURN_DURATION0); - PA_ADD_OPTION(FORWARD_DURATION0); - PA_ADD_OPTION(WAIT_DURATION0); - PA_ADD_OPTION(SHINY_DETECTED); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void PostMMOSpawnReset::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PostMMOSpawnReset_Descriptor::Stats& stats = env.current_stats(); - - // From game to Switch Home - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - { - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - return on_shiny_callback(env, env.console, SHINY_DETECTED, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [this, &env](ProControllerContext& context){ - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - env.console.log("Entered game! Checking shiny sound..."); - - // forward portion - if (TURN_DURATION0.get() > 0ms){ - pbf_move_right_joystick(context, 255, 128, TURN_DURATION0, 0ms); - }else if (TURN_DURATION0.get() < 0ms){ - pbf_move_right_joystick(context, 0, 128, -TURN_DURATION0.get(), 0ms); - } - - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, FORWARD_DURATION0); - - pbf_wait(context, WAIT_DURATION0); - - context.wait_for_all_requests(); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, SHINY_DETECTED, shiny_coefficient); - } - } - - stats.attempts++; - env.console.log("No shiny detected, restarting the game!"); -} - - -void PostMMOSpawnReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PostMMOSpawnReset_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - // run_iteration() restarts the game first then listens to shiny sound. - // If there is any error generated when the game is running and is caught here, - // we just do nothing to handle the error as in the next iteration of run_iteration() - // the game will be immediately restarted. - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Post MMO Spawn Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA_PostMMOSpawnReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +PostMMOSpawnReset_Descriptor::PostMMOSpawnReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:PostMMOSpawnReset", + STRING_POKEMON + " LA", "Post-MMO Spawn Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/PostMMOSpawnReset.md", + "Constantly reset the spawn after MMO finishes.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class PostMMOSpawnReset_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr PostMMOSpawnReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +PostMMOSpawnReset::PostMMOSpawnReset() + : TURN_DURATION0( + "Camera Turn:
How many ticks to turn the camera.
Positive values for right turns. Negative values for left turns.", + LockMode::LOCK_WHILE_RUNNING, + "0 ms" + ) + , FORWARD_DURATION0( + "Move Forward:
After turning the camera, how many ticks to move forward.", + LockMode::LOCK_WHILE_RUNNING, + "0 ms" + ) + , WAIT_DURATION0( + "Wait Time:
Wait time after movement.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , SHINY_DETECTED("Shiny Detected Action", "", "0 ms") + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(TURN_DURATION0); + PA_ADD_OPTION(FORWARD_DURATION0); + PA_ADD_OPTION(WAIT_DURATION0); + PA_ADD_OPTION(SHINY_DETECTED); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void PostMMOSpawnReset::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PostMMOSpawnReset_Descriptor::Stats& stats = env.current_stats(); + + // From game to Switch Home + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + { + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + return on_shiny_callback(env, env.console, SHINY_DETECTED, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [this, &env](ProControllerContext& context){ + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + env.console.log("Entered game! Checking shiny sound..."); + + // forward portion + if (TURN_DURATION0.get() > 0ms){ + pbf_move_right_joystick(context, 255, 128, TURN_DURATION0, 0ms); + }else if (TURN_DURATION0.get() < 0ms){ + pbf_move_right_joystick(context, 0, 128, -TURN_DURATION0.get(), 0ms); + } + + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, FORWARD_DURATION0); + + pbf_wait(context, WAIT_DURATION0); + + context.wait_for_all_requests(); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, SHINY_DETECTED, shiny_coefficient); + } + } + + stats.attempts++; + env.console.log("No shiny detected, restarting the game!"); +} + + +void PostMMOSpawnReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PostMMOSpawnReset_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + // run_iteration() restarts the game first then listens to shiny sound. + // If there is any error generated when the game is running and is caught here, + // we just do nothing to handle the error as in the next iteration of run_iteration() + // the game will be immediately restarted. + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h index af5e06d714..0e2c570419 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_PostMMOSpawnReset.h @@ -1,57 +1,57 @@ -/* Post MMO Spawn Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_PostMMOSpawnReset_H -#define PokemonAutomation_PokemonLA_PostMMOSpawnReset_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class PostMMOSpawnReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PostMMOSpawnReset_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class PostMMOSpawnReset : public SingleSwitchProgramInstance{ -public: - PostMMOSpawnReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - MillisecondsOption TURN_DURATION0; - MillisecondsOption FORWARD_DURATION0; - MillisecondsOption WAIT_DURATION0; - - OverworldShinyDetectedActionOption SHINY_DETECTED; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Post MMO Spawn Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_PostMMOSpawnReset_H +#define PokemonAutomation_PokemonLA_PostMMOSpawnReset_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class PostMMOSpawnReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PostMMOSpawnReset_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class PostMMOSpawnReset : public SingleSwitchProgramInstance{ +public: + PostMMOSpawnReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + MillisecondsOption TURN_DURATION0; + MillisecondsOption FORWARD_DURATION0; + MillisecondsOption WAIT_DURATION0; + + OverworldShinyDetectedActionOption SHINY_DETECTED; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.cpp index 8e8418ac49..86882ecf29 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.cpp @@ -1,346 +1,346 @@ -/* Shiny Hunt - Custom Path - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_TimeOfDayChange.h" -#include "PokemonLA_ShinyHunt-CustomPath.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -ShinyHuntCustomPath_Descriptor::ShinyHuntCustomPath_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:ShinyHunt-CustomPath", - STRING_POKEMON + " LA", "Shiny Hunt - Custom Path", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ShinyHunt-CustomPath.md", - "Repeatedly travel on a custom path to shiny hunt " + STRING_POKEMON + " around it.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController,}, - FasterIfTickPrecise::FASTER - ) -{} -class ShinyHuntCustomPath_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr ShinyHuntCustomPath_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -ShinyHuntCustomPath::ShinyHuntCustomPath() - : TIME_OF_DAY( - "Time of Day:
Reset time of day if Reset Method is Soft Reset. Use this to only hunt " + STRING_POKEMON - + " at day or night, or to avoid visual inference errors on white snow at daytime." - ) - , RUNS_PER_TIME_RESET( - "How Many Runs Before Resetting Time of Day:
To avoid too much time spent on resetting time of day, reset only every several runs.", - LockMode::LOCK_WHILE_RUNNING, - 5, 1 - ) - , TEST_PATH( - "Test Path:
Run the path immediately on the map to test it.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while you are ignoring shinies.", - "0 ms" - ) - , SHINY_DETECTED_DESTINATION( - "Destination Shiny Action", - "This applies if a shiny is detected while you are listening for shinies.", - "0 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); -// PA_ADD_OPTION(TRAVEL_LOCATION); - PA_ADD_OPTION(PATH); - PA_ADD_OPTION(RESET_METHOD); - PA_ADD_OPTION(TIME_OF_DAY); - PA_ADD_OPTION(RUNS_PER_TIME_RESET); - PA_ADD_OPTION(TEST_PATH); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void ShinyHuntCustomPath::do_non_listen_action( - VideoStream& stream, ProControllerContext& context, - const CustomPathTableRow2& row -){ - stream.log("Execute action " + row.action.current_display()); - switch(row.action){ - case PathAction::CHANGE_MOUNT: - { - MountState mountState = MountState::NOTHING; - switch(row.parameters.mount){ - case PathMount::WYRDEER: - mountState = MountState::WYRDEER_ON; - break; - case PathMount::URSALUNA: - mountState = MountState::URSALUNA_ON; - break; - case PathMount::BASCULEGION: - mountState = MountState::BASCULEGION_ON; - break; - case PathMount::SNEASLER: - mountState = MountState::SNEASLER_ON; - break; - case PathMount::BRAVIARY: - mountState = MountState::BRAVIARY_ON; - break; - default: - break; - } - - if (mountState == MountState::NOTHING){ - dismount(stream, context); - }else{ - change_mount(stream, context, mountState); - } - break; - } -#if 0 - case PathAction::ROTATE_CAMERA: - { - if (row.camera_turn_ticks > 0){ - pbf_move_right_joystick(context, 255, 128, uint16_t(row.camera_turn_ticks), 0); - }else if (row.camera_turn_ticks < 0){ - pbf_move_right_joystick(context, 0, 128, uint16_t(-row.camera_turn_ticks), 0); - } - break; - } -#endif - case PathAction::MOVE_FORWARD: - { - switch(row.parameters.move_speed){ - case PathSpeed::NORMAL_SPEED: - pbf_move_left_joystick(context, 128, 0, row.parameters.move_forward, 0ms); - break; - case PathSpeed::SLOW_SPEED: - pbf_move_left_joystick(context, 128, 64, row.parameters.move_forward, 0ms); - break; - case PathSpeed::RUN: - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, row.parameters.move_forward); - break; - case PathSpeed::DASH: - pbf_press_button(context, BUTTON_B, row.parameters.move_forward, 0ms); - break; - case PathSpeed::DASH_B_SPAM: - pbf_mash_button(context, BUTTON_B, row.parameters.move_forward); - break; - case PathSpeed::DIVE: - pbf_press_button(context, BUTTON_Y, row.parameters.move_forward, 0ms); - break; - } - break; - } - case PathAction::MOVE_IN_DIRECTION: - { - uint8_t x = (uint8_t)((row.parameters.left_x + 1.0) * 127.5 + 0.5); - uint8_t y = (uint8_t)((-row.parameters.left_y + 1.0) * 127.5 + 0.5); - pbf_move_left_joystick(context, x, y, row.parameters.move_forward, 0ms); - break; - } - case PathAction::CENTER_CAMERA: - { - pbf_mash_button(context, BUTTON_ZL, 200); - break; - } - case PathAction::JUMP: - { - pbf_press_button(context, BUTTON_Y, 80ms, row.parameters.jump_wait); - break; - } - case PathAction::WAIT: - { - pbf_wait(context, row.parameters.wait); - break; - } - default: - break; - } // end switch action - context.wait_for_all_requests(); -} - - -void ShinyHuntCustomPath::run_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - std::vector> table = PATH.PATH.copy_snapshot(); - - // Check whether the user has set shiny sound listen action: - { - bool has_listen_action = false; - for (const std::unique_ptr& row : table){ - if (row->action == PathAction::START_LISTEN){ - has_listen_action = true; - break; - } - } - if (has_listen_action == false){ - throw UserSetupError(env.console, "No START LISTEN action specified."); - } - } - - ShinyHuntCustomPath_Descriptor::Stats& stats = env.current_stats(); - - std::atomic listen_for_shiny(false); - float shiny_coefficient = 1.0; - OverworldShinyDetectedActionOption* shiny_action = nullptr; - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - if (listen_for_shiny.load(std::memory_order_acquire)){ - shiny_action = &SHINY_DETECTED_DESTINATION; - }else{ - shiny_action = &SHINY_DETECTED_ENROUTE; - } - return on_shiny_callback(env, env.console, *shiny_action, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - for (const std::unique_ptr& row : table){ - if (row->action == PathAction::START_LISTEN){ - listen_for_shiny.store(true, std::memory_order_release); - continue; - }else if (row->action == PathAction::END_LISTEN){ - listen_for_shiny.store(false, std::memory_order_release); - continue; - } - - do_non_listen_action(env.console, context, *row); - context.wait_for_all_requests(); - } - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, *shiny_action, shiny_coefficient); - } -} - - -void ShinyHuntCustomPath::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntCustomPath_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - if (TEST_PATH){ - // Run the test path immediately - env.log("Testing path..."); - run_path(env, context); - return; - } - - // How many runs so far after last time reset - uint32_t time_reset_run_count = 0; - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - stats.attempts++; - - const TravelLocation location = PATH.travel_location(); - goto_camp_from_jubilife(env, env.console, context, location); - run_path(env, context); - ++time_reset_run_count; - - if(RESET_METHOD == ResetMethod::SoftReset){ - env.console.log("Resetting by closing the game."); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - env.console.log("Resetting by going to village."); - goto_camp_from_overworld(env, env.console, context); - - // Now we are at this camp - const Camp camp = map_region_default_camp(location.region); - TimeOfDay target_time = TIME_OF_DAY; - if (target_time != TimeOfDay::NONE && time_reset_run_count >= RUNS_PER_TIME_RESET){ - env.log("Reset time to " + TIME_OF_DAY_NAMES[int(target_time)]); - time_reset_run_count = 0; - change_time_of_day_at_tent(env.console, context, target_time, camp); - // Reset location again since we now are at the tent, not the camp warp spot - goto_camp_from_overworld(env, env.console, context); - } - goto_professor(env.console.logger(), context, camp); - from_professor_return_to_jubilife(env, env.console, context); - } - - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - time_reset_run_count = 0; - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Shiny Hunt - Custom Path + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_TimeOfDayChange.h" +#include "PokemonLA_ShinyHunt-CustomPath.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +ShinyHuntCustomPath_Descriptor::ShinyHuntCustomPath_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:ShinyHunt-CustomPath", + STRING_POKEMON + " LA", "Shiny Hunt - Custom Path", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ShinyHunt-CustomPath.md", + "Repeatedly travel on a custom path to shiny hunt " + STRING_POKEMON + " around it.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController,}, + FasterIfTickPrecise::FASTER + ) +{} +class ShinyHuntCustomPath_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr ShinyHuntCustomPath_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +ShinyHuntCustomPath::ShinyHuntCustomPath() + : TIME_OF_DAY( + "Time of Day:
Reset time of day if Reset Method is Soft Reset. Use this to only hunt " + STRING_POKEMON + + " at day or night, or to avoid visual inference errors on white snow at daytime." + ) + , RUNS_PER_TIME_RESET( + "How Many Runs Before Resetting Time of Day:
To avoid too much time spent on resetting time of day, reset only every several runs.", + LockMode::LOCK_WHILE_RUNNING, + 5, 1 + ) + , TEST_PATH( + "Test Path:
Run the path immediately on the map to test it.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while you are ignoring shinies.", + "0 ms" + ) + , SHINY_DETECTED_DESTINATION( + "Destination Shiny Action", + "This applies if a shiny is detected while you are listening for shinies.", + "0 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); +// PA_ADD_OPTION(TRAVEL_LOCATION); + PA_ADD_OPTION(PATH); + PA_ADD_OPTION(RESET_METHOD); + PA_ADD_OPTION(TIME_OF_DAY); + PA_ADD_OPTION(RUNS_PER_TIME_RESET); + PA_ADD_OPTION(TEST_PATH); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void ShinyHuntCustomPath::do_non_listen_action( + VideoStream& stream, ProControllerContext& context, + const CustomPathTableRow2& row +){ + stream.log("Execute action " + row.action.current_display()); + switch(row.action){ + case PathAction::CHANGE_MOUNT: + { + MountState mountState = MountState::NOTHING; + switch(row.parameters.mount){ + case PathMount::WYRDEER: + mountState = MountState::WYRDEER_ON; + break; + case PathMount::URSALUNA: + mountState = MountState::URSALUNA_ON; + break; + case PathMount::BASCULEGION: + mountState = MountState::BASCULEGION_ON; + break; + case PathMount::SNEASLER: + mountState = MountState::SNEASLER_ON; + break; + case PathMount::BRAVIARY: + mountState = MountState::BRAVIARY_ON; + break; + default: + break; + } + + if (mountState == MountState::NOTHING){ + dismount(stream, context); + }else{ + change_mount(stream, context, mountState); + } + break; + } +#if 0 + case PathAction::ROTATE_CAMERA: + { + if (row.camera_turn_ticks > 0){ + pbf_move_right_joystick(context, 255, 128, uint16_t(row.camera_turn_ticks), 0); + }else if (row.camera_turn_ticks < 0){ + pbf_move_right_joystick(context, 0, 128, uint16_t(-row.camera_turn_ticks), 0); + } + break; + } +#endif + case PathAction::MOVE_FORWARD: + { + switch(row.parameters.move_speed){ + case PathSpeed::NORMAL_SPEED: + pbf_move_left_joystick(context, 128, 0, row.parameters.move_forward, 0ms); + break; + case PathSpeed::SLOW_SPEED: + pbf_move_left_joystick(context, 128, 64, row.parameters.move_forward, 0ms); + break; + case PathSpeed::RUN: + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, 128, 0, 128, 128, row.parameters.move_forward); + break; + case PathSpeed::DASH: + pbf_press_button(context, BUTTON_B, row.parameters.move_forward, 0ms); + break; + case PathSpeed::DASH_B_SPAM: + pbf_mash_button(context, BUTTON_B, row.parameters.move_forward); + break; + case PathSpeed::DIVE: + pbf_press_button(context, BUTTON_Y, row.parameters.move_forward, 0ms); + break; + } + break; + } + case PathAction::MOVE_IN_DIRECTION: + { + uint8_t x = (uint8_t)((row.parameters.left_x + 1.0) * 127.5 + 0.5); + uint8_t y = (uint8_t)((-row.parameters.left_y + 1.0) * 127.5 + 0.5); + pbf_move_left_joystick(context, x, y, row.parameters.move_forward, 0ms); + break; + } + case PathAction::CENTER_CAMERA: + { + pbf_mash_button(context, BUTTON_ZL, 200); + break; + } + case PathAction::JUMP: + { + pbf_press_button(context, BUTTON_Y, 80ms, row.parameters.jump_wait); + break; + } + case PathAction::WAIT: + { + pbf_wait(context, row.parameters.wait); + break; + } + default: + break; + } // end switch action + context.wait_for_all_requests(); +} + + +void ShinyHuntCustomPath::run_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + std::vector> table = PATH.PATH.copy_snapshot(); + + // Check whether the user has set shiny sound listen action: + { + bool has_listen_action = false; + for (const std::unique_ptr& row : table){ + if (row->action == PathAction::START_LISTEN){ + has_listen_action = true; + break; + } + } + if (has_listen_action == false){ + throw UserSetupError(env.console, "No START LISTEN action specified."); + } + } + + ShinyHuntCustomPath_Descriptor::Stats& stats = env.current_stats(); + + std::atomic listen_for_shiny(false); + float shiny_coefficient = 1.0; + OverworldShinyDetectedActionOption* shiny_action = nullptr; + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + if (listen_for_shiny.load(std::memory_order_acquire)){ + shiny_action = &SHINY_DETECTED_DESTINATION; + }else{ + shiny_action = &SHINY_DETECTED_ENROUTE; + } + return on_shiny_callback(env, env.console, *shiny_action, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + for (const std::unique_ptr& row : table){ + if (row->action == PathAction::START_LISTEN){ + listen_for_shiny.store(true, std::memory_order_release); + continue; + }else if (row->action == PathAction::END_LISTEN){ + listen_for_shiny.store(false, std::memory_order_release); + continue; + } + + do_non_listen_action(env.console, context, *row); + context.wait_for_all_requests(); + } + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, *shiny_action, shiny_coefficient); + } +} + + +void ShinyHuntCustomPath::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntCustomPath_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + if (TEST_PATH){ + // Run the test path immediately + env.log("Testing path..."); + run_path(env, context); + return; + } + + // How many runs so far after last time reset + uint32_t time_reset_run_count = 0; + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + stats.attempts++; + + const TravelLocation location = PATH.travel_location(); + goto_camp_from_jubilife(env, env.console, context, location); + run_path(env, context); + ++time_reset_run_count; + + if(RESET_METHOD == ResetMethod::SoftReset){ + env.console.log("Resetting by closing the game."); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + env.console.log("Resetting by going to village."); + goto_camp_from_overworld(env, env.console, context); + + // Now we are at this camp + const Camp camp = map_region_default_camp(location.region); + TimeOfDay target_time = TIME_OF_DAY; + if (target_time != TimeOfDay::NONE && time_reset_run_count >= RUNS_PER_TIME_RESET){ + env.log("Reset time to " + TIME_OF_DAY_NAMES[int(target_time)]); + time_reset_run_count = 0; + change_time_of_day_at_tent(env.console, context, target_time, camp); + // Reset location again since we now are at the tent, not the camp warp spot + goto_camp_from_overworld(env, env.console, context); + } + goto_professor(env.console.logger(), context, camp); + from_professor_return_to_jubilife(env, env.console, context); + } + + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + time_reset_run_count = 0; + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h index e85d8de0e7..9375df7c47 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-CustomPath.h @@ -1,76 +1,76 @@ -/* Shiny Hunt - Custom Path - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ShinyHuntCustomPath_H -#define PokemonAutomation_PokemonLA_ShinyHuntCustomPath_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_MiscOptions.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" -#include "PokemonLA/Options/PokemonLA_CustomPathTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class ShinyHuntCustomPath_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntCustomPath_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class ShinyHuntCustomPath : public SingleSwitchProgramInstance{ -public: - ShinyHuntCustomPath(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - // Run the custom path on overworld. - void run_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // Do one action (while ignoring listen-related actions) - void do_non_listen_action( - VideoStream& stream, ProControllerContext& context, - const CustomPathTableRow2& row - ); - -private: - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - -// TravelLocationOption TRAVEL_LOCATION; - - CustomPathTable PATH; - - ResetMethodOption RESET_METHOD; - - TimeOfDayOption TIME_OF_DAY; - SimpleIntegerOption RUNS_PER_TIME_RESET; - - BooleanCheckBoxOption TEST_PATH; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Shiny Hunt - Custom Path + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ShinyHuntCustomPath_H +#define PokemonAutomation_PokemonLA_ShinyHuntCustomPath_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_MiscOptions.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" +#include "PokemonLA/Options/PokemonLA_CustomPathTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class ShinyHuntCustomPath_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntCustomPath_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class ShinyHuntCustomPath : public SingleSwitchProgramInstance{ +public: + ShinyHuntCustomPath(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + // Run the custom path on overworld. + void run_path(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // Do one action (while ignoring listen-related actions) + void do_non_listen_action( + VideoStream& stream, ProControllerContext& context, + const CustomPathTableRow2& row + ); + +private: + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + +// TravelLocationOption TRAVEL_LOCATION; + + CustomPathTable PATH; + + ResetMethodOption RESET_METHOD; + + TimeOfDayOption TIME_OF_DAY; + SimpleIntegerOption RUNS_PER_TIME_RESET; + + BooleanCheckBoxOption TEST_PATH; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.cpp index 918d043063..ef2dc020b5 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.cpp @@ -1,218 +1,218 @@ -/* Shiny Hunt - Fixed Point - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA/Programs/PokemonLA_FlagNavigationAir.h" -#include "PokemonLA_ShinyHunt-FlagPin.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -ShinyHuntFlagPin_Descriptor::ShinyHuntFlagPin_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:ShinyHunt-FlagPin", - STRING_POKEMON + " LA", "Shiny Hunt - Flag Pin", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ShinyHunt-FlagPin.md", - "Repeatedly travel to a flag pin to shiny hunt " + STRING_POKEMON + " around it.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class ShinyHuntFlagPin_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr ShinyHuntFlagPin_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -ShinyHuntFlagPin::ShinyHuntFlagPin() - : ENROUTE_DISTANCE( - "Enroute Distance:
" - "You are considered \"enroute\" if you are further than this distance from the flag.

" - "If you wish to ignore enroute shinies, scroll down to " - "\"Enroute Shiny Action\" and set it to ignore shinies. " - "Keep in mind that the shiny sound radius is 30 and you will need some headroom.", - LockMode::LOCK_WHILE_RUNNING, - 60 - ) - , SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while enroute to the flag. (defined as being more than the \"Enroute Distance\" specified above)", - "0 ms" - ) - , SHINY_DETECTED_DESTINATION( - "Destination Shiny Action", - "This applies if a shiny is detected at or near the flag. (defined as being less than the \"Enroute Distance\" specified above)", - "0 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , STOP_DISTANCE( - "Stop Distance:
" - "Reset the game when you come within this distance of the flag. " - "Don't set this too small. The navigation is not precise enough to land directly on the flag.", - LockMode::LOCK_WHILE_RUNNING, - 20 - ) - , FLAG_REACHED_DELAY( - "Target Reached Delay:
" - "Once you have reached the flag, wait this many seconds to ensure everything loads and that any shinies are heard before resetting.", - LockMode::LOCK_WHILE_RUNNING, - 1.0, 0, 60 - ) - , NAVIGATION_TIMEOUT( - "Navigation Timeout:
Give up and reset if flag is not reached after this many seconds.", - LockMode::LOCK_WHILE_RUNNING, - 180, 0 - ) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(TRAVEL_LOCATION); - PA_ADD_OPTION(ENROUTE_DISTANCE); - PA_ADD_OPTION(RESET_METHOD); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(STOP_DISTANCE); - PA_ADD_OPTION(FLAG_REACHED_DELAY); - PA_ADD_OPTION(NAVIGATION_TIMEOUT); -} - - - -void ShinyHuntFlagPin::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntFlagPin_Descriptor::Stats& stats = env.current_stats(); - stats.attempts++; - - { - std::atomic flag_distance(10000); - - float shiny_coefficient = 1.0; - OverworldShinyDetectedActionOption* shiny_action = nullptr; - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - if (flag_distance.load(std::memory_order_acquire) <= ENROUTE_DISTANCE){ - shiny_action = &SHINY_DETECTED_DESTINATION; - }else{ - shiny_action = &SHINY_DETECTED_ENROUTE; - } - return on_shiny_callback(env, env.console, *shiny_action, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - goto_camp_from_jubilife(env, env.console, context, TRAVEL_LOCATION); - FlagNavigationAir session( - env, env.console, context, - STOP_DISTANCE, - FLAG_REACHED_DELAY, - std::chrono::seconds(NAVIGATION_TIMEOUT) - ); - session.set_distance_callback([&](double distance){ - flag_distance.store(distance, std::memory_order_release); - }); - session.run_session(); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0){ - on_shiny_sound(env, env.console, context, *shiny_action, shiny_coefficient); - } - - if(RESET_METHOD == ResetMethod::SoftReset){ - env.console.log("Resetting by closing the game."); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - env.console.log("Resetting by going to village."); - goto_camp_from_overworld(env, env.console, context); - goto_professor(env.console.logger(), context, TRAVEL_LOCATION); - from_professor_return_to_jubilife(env, env.console, context); - } - } -} - - -void ShinyHuntFlagPin::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntFlagPin_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Shiny Hunt - Fixed Point + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA/Programs/PokemonLA_FlagNavigationAir.h" +#include "PokemonLA_ShinyHunt-FlagPin.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +ShinyHuntFlagPin_Descriptor::ShinyHuntFlagPin_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:ShinyHunt-FlagPin", + STRING_POKEMON + " LA", "Shiny Hunt - Flag Pin", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ShinyHunt-FlagPin.md", + "Repeatedly travel to a flag pin to shiny hunt " + STRING_POKEMON + " around it.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class ShinyHuntFlagPin_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr ShinyHuntFlagPin_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +ShinyHuntFlagPin::ShinyHuntFlagPin() + : ENROUTE_DISTANCE( + "Enroute Distance:
" + "You are considered \"enroute\" if you are further than this distance from the flag.

" + "If you wish to ignore enroute shinies, scroll down to " + "\"Enroute Shiny Action\" and set it to ignore shinies. " + "Keep in mind that the shiny sound radius is 30 and you will need some headroom.", + LockMode::LOCK_WHILE_RUNNING, + 60 + ) + , SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while enroute to the flag. (defined as being more than the \"Enroute Distance\" specified above)", + "0 ms" + ) + , SHINY_DETECTED_DESTINATION( + "Destination Shiny Action", + "This applies if a shiny is detected at or near the flag. (defined as being less than the \"Enroute Distance\" specified above)", + "0 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , STOP_DISTANCE( + "Stop Distance:
" + "Reset the game when you come within this distance of the flag. " + "Don't set this too small. The navigation is not precise enough to land directly on the flag.", + LockMode::LOCK_WHILE_RUNNING, + 20 + ) + , FLAG_REACHED_DELAY( + "Target Reached Delay:
" + "Once you have reached the flag, wait this many seconds to ensure everything loads and that any shinies are heard before resetting.", + LockMode::LOCK_WHILE_RUNNING, + 1.0, 0, 60 + ) + , NAVIGATION_TIMEOUT( + "Navigation Timeout:
Give up and reset if flag is not reached after this many seconds.", + LockMode::LOCK_WHILE_RUNNING, + 180, 0 + ) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(TRAVEL_LOCATION); + PA_ADD_OPTION(ENROUTE_DISTANCE); + PA_ADD_OPTION(RESET_METHOD); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(STOP_DISTANCE); + PA_ADD_OPTION(FLAG_REACHED_DELAY); + PA_ADD_OPTION(NAVIGATION_TIMEOUT); +} + + + +void ShinyHuntFlagPin::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntFlagPin_Descriptor::Stats& stats = env.current_stats(); + stats.attempts++; + + { + std::atomic flag_distance(10000); + + float shiny_coefficient = 1.0; + OverworldShinyDetectedActionOption* shiny_action = nullptr; + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + if (flag_distance.load(std::memory_order_acquire) <= ENROUTE_DISTANCE){ + shiny_action = &SHINY_DETECTED_DESTINATION; + }else{ + shiny_action = &SHINY_DETECTED_ENROUTE; + } + return on_shiny_callback(env, env.console, *shiny_action, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + goto_camp_from_jubilife(env, env.console, context, TRAVEL_LOCATION); + FlagNavigationAir session( + env, env.console, context, + STOP_DISTANCE, + FLAG_REACHED_DELAY, + std::chrono::seconds(NAVIGATION_TIMEOUT) + ); + session.set_distance_callback([&](double distance){ + flag_distance.store(distance, std::memory_order_release); + }); + session.run_session(); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0){ + on_shiny_sound(env, env.console, context, *shiny_action, shiny_coefficient); + } + + if(RESET_METHOD == ResetMethod::SoftReset){ + env.console.log("Resetting by closing the game."); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + env.console.log("Resetting by going to village."); + goto_camp_from_overworld(env, env.console, context); + goto_professor(env.console.logger(), context, TRAVEL_LOCATION); + from_professor_return_to_jubilife(env, env.console, context); + } + } +} + + +void ShinyHuntFlagPin::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntFlagPin_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h index 5b437ec4d5..29de36f755 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-FlagPin.h @@ -1,70 +1,70 @@ -/* Shiny Hunt - Fixed Point - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ShinyHuntFlagPin_H -#define PokemonAutomation_PokemonLA_ShinyHuntFlagPin_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/PokemonLA_Locations.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Options/PokemonLA_MiscOptions.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" -#include "PokemonLA/Options/PokemonLA_TravelLocation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ShinyHuntFlagPin_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntFlagPin_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class ShinyHuntFlagPin : public SingleSwitchProgramInstance{ -public: - ShinyHuntFlagPin(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - TravelLocationOption TRAVEL_LOCATION; - - SimpleIntegerOption ENROUTE_DISTANCE; - - ResetMethodOption RESET_METHOD; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption STOP_DISTANCE; - FloatingPointOption FLAG_REACHED_DELAY; - SimpleIntegerOption NAVIGATION_TIMEOUT; -}; - - - - - -} -} -} -#endif +/* Shiny Hunt - Fixed Point + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ShinyHuntFlagPin_H +#define PokemonAutomation_PokemonLA_ShinyHuntFlagPin_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/PokemonLA_Locations.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Options/PokemonLA_MiscOptions.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" +#include "PokemonLA/Options/PokemonLA_TravelLocation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ShinyHuntFlagPin_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntFlagPin_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class ShinyHuntFlagPin : public SingleSwitchProgramInstance{ +public: + ShinyHuntFlagPin(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + TravelLocationOption TRAVEL_LOCATION; + + SimpleIntegerOption ENROUTE_DISTANCE; + + ResetMethodOption RESET_METHOD; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption STOP_DISTANCE; + FloatingPointOption FLAG_REACHED_DELAY; + SimpleIntegerOption NAVIGATION_TIMEOUT; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.cpp index 9517460021..2dda13aac8 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.cpp @@ -1,249 +1,249 @@ -/* Shiny Hunt - Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Notification.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA_ShinyHunt-LakeTrio.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -ShinyHuntLakeTrio_Descriptor::ShinyHuntLakeTrio_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:ShinyHunt-LakeTrio", - STRING_POKEMON + " LA", "Shiny Hunt - Lake Trio", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ShinyHunt-LakeTrio.md", - "Shiny hunt the lake trio legendaries.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} -std::unique_ptr ShinyHuntLakeTrio_Descriptor::make_stats() const{ - return std::unique_ptr(new PokemonSwSh::ShinyHuntTracker(false)); -} - - -ShinyHuntLakeTrio::ShinyHuntLakeTrio() - : VIDEO_ON_SHINY( - "Video Capture:
Take a video of the encounter if it is shiny.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_NONSHINY, - &NOTIFICATION_SHINY, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ -// PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - -// PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -std::set read_name( - Logger& logger, - Language language, - const ImageViewRGB32& screen, const ImageFloatBox& box -){ - if (language == Language::None){ - return {}; - } - - - ImageViewRGB32 image = extract_box_reference(screen, box); - OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( - logger, language, image, - OCR::WHITE_TEXT_FILTERS() - ); - result.clear_beyond_log10p(Pokemon::PokemonNameReader::MAX_LOG10P); - - std::set ret; - if (result.results.empty()){ - dump_image( - logger, ProgramInfo(), - "NameOCR-" + language_data(language).code, - screen - ); - }else{ - for (const auto& item : result.results){ - ret.insert(item.second.token); - } - } - return ret; -} - - - -void ShinyHuntLakeTrio::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PokemonSwSh::ShinyHuntTracker& stats = env.current_stats(); - - - // Connect the controller. - pbf_press_button(context, BUTTON_B, 5, 5); - - size_t consecutive_errors = 0; - - bool reset = false; - while (true){ - env.update_stats(); - - if (reset){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ - stats.add_error(); - continue; - } - } - reset = true; - - env.console.log("Entering cave..."); - pbf_move_left_joystick(context, 160, 0, 50, 0); - pbf_move_left_joystick(context, 96, 0, 50, 0); - pbf_move_left_joystick(context, 160, 0, 50, 0); - pbf_move_left_joystick(context, 96, 0, 50, 0); - pbf_mash_button(context, BUTTON_A, 125); - context.wait_for_all_requests(); - - - env.console.log("Waiting for a target to appear..."); - { - ArcDetector arcs; - WhiteObjectWatcher watcher( - env.console, - {0, 0, 1, 1}, - {{arcs, true}} - ); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 60 * TICKS_PER_SECOND); - }, - {{watcher}} - ); - if (ret < 0){ - VideoSnapshot screen = env.console.video().snapshot(); - env.log("No encounter detected after 60 seconds.", COLOR_RED); - stats.add_error(); - dump_image( - env.logger(), ProgramInfo(), - "NoEncounter", - screen - ); - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - "No encounter detected after 60 seconds." - ); - consecutive_errors++; - if (consecutive_errors >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect an encounter 3 times in the row.", - env.console - ); - } - continue; - } - } - - env.console.log("Locking on and searching for shiny symbol..."); - { - ArcDetector arcs; - WhiteObjectWatcher watcher( - env.console, - {0, 0, 1, 1}, - {{arcs, false}} - ); - ShinySymbolWaiter shiny_symbol(env.console, SHINY_SYMBOL_BOX_BOTTOM); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_ZL, 3 * TICKS_PER_SECOND, 0); - }, - { - {watcher}, - {shiny_symbol}, - } - ); - VideoSnapshot screen = env.console.video().snapshot(); - std::set slugs = read_name(env.logger(), LANGUAGE, screen, {0.11, 0.868, 0.135, 0.043}); - - if (ret < 0){ - stats.add_non_shiny(); - env.log("Not shiny.", COLOR_PURPLE); - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - true, false, {{std::move(slugs), ShinyType::NOT_SHINY}}, std::nan(""), - screen - ); - }else{ - stats.add_unknown_shiny(); - env.log("Detected Shiny!", COLOR_BLUE); - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - true, true, {{std::move(slugs), ShinyType::UNKNOWN_SHINY}}, std::nan(""), - screen - ); - if (VIDEO_ON_SHINY){ -// pbf_wait(context, 5 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); - } - break; - } - } - - } - - env.update_stats(); - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - -// GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - -} -} -} +/* Shiny Hunt - Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ShinySymbolDetector.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA_ShinyHunt-LakeTrio.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +ShinyHuntLakeTrio_Descriptor::ShinyHuntLakeTrio_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:ShinyHunt-LakeTrio", + STRING_POKEMON + " LA", "Shiny Hunt - Lake Trio", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/ShinyHunt-LakeTrio.md", + "Shiny hunt the lake trio legendaries.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} +std::unique_ptr ShinyHuntLakeTrio_Descriptor::make_stats() const{ + return std::unique_ptr(new PokemonSwSh::ShinyHuntTracker(false)); +} + + +ShinyHuntLakeTrio::ShinyHuntLakeTrio() + : VIDEO_ON_SHINY( + "Video Capture:
Take a video of the encounter if it is shiny.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_NONSHINY, + &NOTIFICATION_SHINY, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ +// PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + +// PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +std::set read_name( + Logger& logger, + Language language, + const ImageViewRGB32& screen, const ImageFloatBox& box +){ + if (language == Language::None){ + return {}; + } + + + ImageViewRGB32 image = extract_box_reference(screen, box); + OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( + logger, language, image, + OCR::WHITE_TEXT_FILTERS() + ); + result.clear_beyond_log10p(Pokemon::PokemonNameReader::MAX_LOG10P); + + std::set ret; + if (result.results.empty()){ + dump_image( + logger, ProgramInfo(), + "NameOCR-" + language_data(language).code, + screen + ); + }else{ + for (const auto& item : result.results){ + ret.insert(item.second.token); + } + } + return ret; +} + + + +void ShinyHuntLakeTrio::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PokemonSwSh::ShinyHuntTracker& stats = env.current_stats(); + + + // Connect the controller. + pbf_press_button(context, BUTTON_B, 5, 5); + + size_t consecutive_errors = 0; + + bool reset = false; + while (true){ + env.update_stats(); + + if (reset){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + if (!reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST)){ + stats.add_error(); + continue; + } + } + reset = true; + + env.console.log("Entering cave..."); + pbf_move_left_joystick(context, 160, 0, 50, 0); + pbf_move_left_joystick(context, 96, 0, 50, 0); + pbf_move_left_joystick(context, 160, 0, 50, 0); + pbf_move_left_joystick(context, 96, 0, 50, 0); + pbf_mash_button(context, BUTTON_A, 125); + context.wait_for_all_requests(); + + + env.console.log("Waiting for a target to appear..."); + { + ArcDetector arcs; + WhiteObjectWatcher watcher( + env.console, + {0, 0, 1, 1}, + {{arcs, true}} + ); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 60 * TICKS_PER_SECOND); + }, + {{watcher}} + ); + if (ret < 0){ + VideoSnapshot screen = env.console.video().snapshot(); + env.log("No encounter detected after 60 seconds.", COLOR_RED); + stats.add_error(); + dump_image( + env.logger(), ProgramInfo(), + "NoEncounter", + screen + ); + send_program_recoverable_error_notification( + env, NOTIFICATION_ERROR_RECOVERABLE, + "No encounter detected after 60 seconds." + ); + consecutive_errors++; + if (consecutive_errors >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect an encounter 3 times in the row.", + env.console + ); + } + continue; + } + } + + env.console.log("Locking on and searching for shiny symbol..."); + { + ArcDetector arcs; + WhiteObjectWatcher watcher( + env.console, + {0, 0, 1, 1}, + {{arcs, false}} + ); + ShinySymbolWaiter shiny_symbol(env.console, SHINY_SYMBOL_BOX_BOTTOM); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_ZL, 3 * TICKS_PER_SECOND, 0); + }, + { + {watcher}, + {shiny_symbol}, + } + ); + VideoSnapshot screen = env.console.video().snapshot(); + std::set slugs = read_name(env.logger(), LANGUAGE, screen, {0.11, 0.868, 0.135, 0.043}); + + if (ret < 0){ + stats.add_non_shiny(); + env.log("Not shiny.", COLOR_PURPLE); + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + true, false, {{std::move(slugs), ShinyType::NOT_SHINY}}, std::nan(""), + screen + ); + }else{ + stats.add_unknown_shiny(); + env.log("Detected Shiny!", COLOR_BLUE); + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + true, true, {{std::move(slugs), ShinyType::UNKNOWN_SHINY}}, std::nan(""), + screen + ); + if (VIDEO_ON_SHINY){ +// pbf_wait(context, 5 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); + } + break; + } + } + + } + + env.update_stats(); + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + +// GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h index 5341873494..3e3b856ded 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_ShinyHunt-LakeTrio.h @@ -1,57 +1,57 @@ -/* Shiny Hunt - Lake Trio - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_ShinyHuntLakeTrio_H -#define PokemonAutomation_PokemonLA_ShinyHuntLakeTrio_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -//#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class ShinyHuntLakeTrio_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntLakeTrio_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class ShinyHuntLakeTrio : public SingleSwitchProgramInstance{ -public: - ShinyHuntLakeTrio(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: -// GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - Pokemon::EncounterBotLanguage LANGUAGE; - - BooleanCheckBoxOption VIDEO_ON_SHINY; - -// EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Shiny Hunt - Lake Trio + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_ShinyHuntLakeTrio_H +#define PokemonAutomation_PokemonLA_ShinyHuntLakeTrio_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +//#include "PokemonBDSP/Options/PokemonBDSP_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class ShinyHuntLakeTrio_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntLakeTrio_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class ShinyHuntLakeTrio : public SingleSwitchProgramInstance{ +public: + ShinyHuntLakeTrio(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: +// GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + Pokemon::EncounterBotLanguage LANGUAGE; + + BooleanCheckBoxOption VIDEO_ON_SHINY; + +// EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.cpp b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.cpp index 294c20206a..a67f210c9e 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.cpp @@ -1,197 +1,197 @@ -/* Unown Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/PokemonLA_Settings.h" -#include "PokemonLA/PokemonLA_TravelLocations.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_MountChange.h" -#include "PokemonLA/Programs/PokemonLA_GameEntry.h" -#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" -#include "PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -UnownFinder_Descriptor::UnownFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:UnownFinder", - STRING_POKEMON + " LA", "Unown Hunter", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/UnownHunter.md", - "Constantly reset to find a Shiny Unown or any Shiny in the path.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -class UnownFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ -public: - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - virtual void add_shiny() override{ - shinies++; - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& shinies; -}; -std::unique_ptr UnownFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -UnownFinder::UnownFinder() - : SHINY_DETECTED_ENROUTE( - "Enroute Shiny Action", - "This applies if a shiny is detected while enroute to the ruins.", - "0 ms" - ) - , SHINY_DETECTED_DESTINATION( - "Destination Shiny Action", - "This applies if a shiny is detected inside the ruins.", - "0 ms" - ) - , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS, - &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, - &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); - PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); - PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void ruins_entrance_route(ProControllerContext& context){ - pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 139, 120, 10, 10); - pbf_wait(context, (uint16_t)(1.3 * TICKS_PER_SECOND)); - - pbf_press_button(context, BUTTON_B, (uint16_t)(9.5 * TICKS_PER_SECOND), 10); - pbf_wait(context, (uint16_t)(0.8 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 110, 90, 20, 10); - - pbf_press_dpad(context, DPAD_LEFT, 10, 10); - pbf_press_button(context, BUTTON_PLUS, 10, 10); -} - -void enter_ruins(ProControllerContext& context){ - pbf_press_button(context, BUTTON_B, (uint16_t)(4 * TICKS_PER_SECOND), 10); - pbf_wait(context, (uint16_t)(1.5 * TICKS_PER_SECOND)); - pbf_move_left_joystick(context, 128, 255, 10, 0); - pbf_press_button(context, BUTTON_B, (uint16_t)(2 * TICKS_PER_SECOND), 10); -} - - -void UnownFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - UnownFinder_Descriptor::Stats& stats = env.current_stats(); - - stats.attempts++; - - goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); - - change_mount(env.console, context, MountState::BRAVIARY_ON); - - // Start path - env.console.log("Beginning Shiny Detection..."); - { - float shiny_coefficient = 1.0; - std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); - WallClock destination_time = WallClock::max(); - - ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ - // Warning: This callback will be run from a different thread than this function. - stats.shinies++; - shiny_coefficient = error_coefficient; - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - return on_shiny_callback(env, env.console, *action, error_coefficient); - }); - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - ruins_entrance_route(context); - - context.wait_for_all_requests(); - destination_time = current_time(); - shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); - - enter_ruins(context); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (ret == 0 || shiny_detector.last_detection() > destination_time){ - OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); - on_shiny_sound(env, env.console, context, *action, shiny_coefficient); - } - }; - - env.console.log("No shiny detected, returning to Jubilife!"); - goto_camp_from_overworld(env, env.console, context); - pbf_press_dpad(context, DPAD_RIGHT, 10, 10); - goto_professor(env.console, context, Camp::MIRELANDS_MIRELANDS); - from_professor_return_to_jubilife(env, env.console, context); -} - - -void UnownFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - UnownFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS); - try{ - run_iteration(env, context); - }catch (OperationFailedException& e){ - stats.errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); - reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Unown Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/PokemonLA_Settings.h" +#include "PokemonLA/PokemonLA_TravelLocations.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA/Programs/PokemonLA_MountChange.h" +#include "PokemonLA/Programs/PokemonLA_GameEntry.h" +#include "PokemonLA/Programs/PokemonLA_RegionNavigation.h" +#include "PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +UnownFinder_Descriptor::UnownFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:UnownFinder", + STRING_POKEMON + " LA", "Unown Hunter", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/UnownHunter.md", + "Constantly reset to find a Shiny Unown or any Shiny in the path.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +class UnownFinder_Descriptor::Stats : public StatsTracker, public ShinyStatIncrementer{ +public: + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + virtual void add_shiny() override{ + shinies++; + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& shinies; +}; +std::unique_ptr UnownFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +UnownFinder::UnownFinder() + : SHINY_DETECTED_ENROUTE( + "Enroute Shiny Action", + "This applies if a shiny is detected while enroute to the ruins.", + "0 ms" + ) + , SHINY_DETECTED_DESTINATION( + "Destination Shiny Action", + "This applies if a shiny is detected inside the ruins.", + "0 ms" + ) + , NOTIFICATION_STATUS("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS, + &SHINY_DETECTED_ENROUTE.NOTIFICATIONS, + &SHINY_DETECTED_DESTINATION.NOTIFICATIONS, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_STATIC(SHINY_REQUIRES_AUDIO); + PA_ADD_OPTION(SHINY_DETECTED_ENROUTE); + PA_ADD_OPTION(SHINY_DETECTED_DESTINATION); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void ruins_entrance_route(ProControllerContext& context){ + pbf_wait(context, (uint16_t)(0.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 139, 120, 10, 10); + pbf_wait(context, (uint16_t)(1.3 * TICKS_PER_SECOND)); + + pbf_press_button(context, BUTTON_B, (uint16_t)(9.5 * TICKS_PER_SECOND), 10); + pbf_wait(context, (uint16_t)(0.8 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 110, 90, 20, 10); + + pbf_press_dpad(context, DPAD_LEFT, 10, 10); + pbf_press_button(context, BUTTON_PLUS, 10, 10); +} + +void enter_ruins(ProControllerContext& context){ + pbf_press_button(context, BUTTON_B, (uint16_t)(4 * TICKS_PER_SECOND), 10); + pbf_wait(context, (uint16_t)(1.5 * TICKS_PER_SECOND)); + pbf_move_left_joystick(context, 128, 255, 10, 0); + pbf_press_button(context, BUTTON_B, (uint16_t)(2 * TICKS_PER_SECOND), 10); +} + + +void UnownFinder::run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + UnownFinder_Descriptor::Stats& stats = env.current_stats(); + + stats.attempts++; + + goto_camp_from_jubilife(env, env.console, context, TravelLocations::instance().Mirelands_Mirelands); + + change_mount(env.console, context, MountState::BRAVIARY_ON); + + // Start path + env.console.log("Beginning Shiny Detection..."); + { + float shiny_coefficient = 1.0; + std::atomic shiny_action(&SHINY_DETECTED_ENROUTE); + WallClock destination_time = WallClock::max(); + + ShinySoundDetector shiny_detector(env.console, [&](float error_coefficient) -> bool{ + // Warning: This callback will be run from a different thread than this function. + stats.shinies++; + shiny_coefficient = error_coefficient; + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + return on_shiny_callback(env, env.console, *action, error_coefficient); + }); + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + ruins_entrance_route(context); + + context.wait_for_all_requests(); + destination_time = current_time(); + shiny_action.store(&SHINY_DETECTED_DESTINATION, std::memory_order_release); + + enter_ruins(context); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (ret == 0 || shiny_detector.last_detection() > destination_time){ + OverworldShinyDetectedActionOption* action = shiny_action.load(std::memory_order_acquire); + on_shiny_sound(env, env.console, context, *action, shiny_coefficient); + } + }; + + env.console.log("No shiny detected, returning to Jubilife!"); + goto_camp_from_overworld(env, env.console, context); + pbf_press_dpad(context, DPAD_RIGHT, 10, 10); + goto_professor(env.console, context, Camp::MIRELANDS_MIRELANDS); + from_professor_return_to_jubilife(env, env.console, context); +} + + +void UnownFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + UnownFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS); + try{ + run_iteration(env, context); + }catch (OperationFailedException& e){ + stats.errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY0); + reset_game_from_home(env, env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h index f1866cce32..e4a707d361 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h +++ b/SerialPrograms/Source/PokemonLA/Programs/ShinyHunting/PokemonLA_UnownFinder.h @@ -1,54 +1,54 @@ -/* Unown Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_UnownFinder_H -#define PokemonAutomation_PokemonLA_UnownFinder_H -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "PokemonLA/Inference/PokemonLA_UnderAttackDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -class UnownFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - UnownFinder_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class UnownFinder : public SingleSwitchProgramInstance{ -public: - UnownFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - class RunRoute; - - ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; - - OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; - OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Unown Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_UnownFinder_H +#define PokemonAutomation_PokemonLA_UnownFinder_H +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "PokemonLA/Inference/PokemonLA_UnderAttackDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +class UnownFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + UnownFinder_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class UnownFinder : public SingleSwitchProgramInstance{ +public: + UnownFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + class RunRoute; + + ShinyRequiresAudioText SHINY_REQUIRES_AUDIO; + + OverworldShinyDetectedActionOption SHINY_DETECTED_ENROUTE; + OverworldShinyDetectedActionOption SHINY_DETECTED_DESTINATION; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.cpp b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.cpp index 8404b3291a..ccdafba709 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.cpp @@ -1,76 +1,76 @@ -/* Flag Navigation Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Programs/PokemonLA_FlagNavigationAir.h" -#include "PokemonLA_FlagNavigationTest.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -FlagNavigationTest_Descriptor::FlagNavigationTest_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:FlagNavigationTest", - STRING_POKEMON + " LA", "Flag Navigation Test", - "", - "Navigate to the flag pin.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -FlagNavigationTest::FlagNavigationTest() - : STOP_DISTANCE( - "Stop Distance:
" - "You have reached the flag when you come within this distance of it. " - "Don't set this too small. The navigation is not precise enough to land directly on the flag.", - LockMode::LOCK_WHILE_RUNNING, - 20 - ) - , FLAG_REACHED_DELAY( - "Target Reached Delay:
" - "Once you have reached the flag, wait this many seconds to ensure everything loads and that any shinies are heard before resetting.", - LockMode::LOCK_WHILE_RUNNING, - 1.0, 0, 60 - ) - , NAVIGATION_TIMEOUT( - "Navigation Timeout:
Give up if flag is not reached after this many seconds.", - LockMode::LOCK_WHILE_RUNNING, - 180, 0 - ) -{ - PA_ADD_OPTION(STOP_DISTANCE); - PA_ADD_OPTION(FLAG_REACHED_DELAY); - PA_ADD_OPTION(NAVIGATION_TIMEOUT); -// PA_ADD_OPTION(SHINY_DETECTED); -} - - -void FlagNavigationTest::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - FlagNavigationAir session( - env, env.console, context, -// SHINY_DETECTED.stop_on_shiny(), - STOP_DISTANCE, - FLAG_REACHED_DELAY, - std::chrono::seconds(NAVIGATION_TIMEOUT) - ); - session.run_session(); - -} - - - -} -} -} +/* Flag Navigation Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Programs/PokemonLA_FlagNavigationAir.h" +#include "PokemonLA_FlagNavigationTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +FlagNavigationTest_Descriptor::FlagNavigationTest_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:FlagNavigationTest", + STRING_POKEMON + " LA", "Flag Navigation Test", + "", + "Navigate to the flag pin.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +FlagNavigationTest::FlagNavigationTest() + : STOP_DISTANCE( + "Stop Distance:
" + "You have reached the flag when you come within this distance of it. " + "Don't set this too small. The navigation is not precise enough to land directly on the flag.", + LockMode::LOCK_WHILE_RUNNING, + 20 + ) + , FLAG_REACHED_DELAY( + "Target Reached Delay:
" + "Once you have reached the flag, wait this many seconds to ensure everything loads and that any shinies are heard before resetting.", + LockMode::LOCK_WHILE_RUNNING, + 1.0, 0, 60 + ) + , NAVIGATION_TIMEOUT( + "Navigation Timeout:
Give up if flag is not reached after this many seconds.", + LockMode::LOCK_WHILE_RUNNING, + 180, 0 + ) +{ + PA_ADD_OPTION(STOP_DISTANCE); + PA_ADD_OPTION(FLAG_REACHED_DELAY); + PA_ADD_OPTION(NAVIGATION_TIMEOUT); +// PA_ADD_OPTION(SHINY_DETECTED); +} + + +void FlagNavigationTest::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + FlagNavigationAir session( + env, env.console, context, +// SHINY_DETECTED.stop_on_shiny(), + STOP_DISTANCE, + FLAG_REACHED_DELAY, + std::chrono::seconds(NAVIGATION_TIMEOUT) + ); + session.run_session(); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.h b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.h index 167d0ad09c..ef0fa906d9 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.h +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_FlagNavigationTest.h @@ -1,46 +1,46 @@ -/* Flag Navigation Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_FlagNavigationTest_H -#define PokemonAutomation_PokemonLA_FlagNavigationTest_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class FlagNavigationTest_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FlagNavigationTest_Descriptor(); -}; - - -class FlagNavigationTest : public SingleSwitchProgramInstance{ -public: - FlagNavigationTest(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption STOP_DISTANCE; - FloatingPointOption FLAG_REACHED_DELAY; - - SimpleIntegerOption NAVIGATION_TIMEOUT; -// ShinyDetectedActionOption SHINY_DETECTED; -}; - - - -} -} -} -#endif +/* Flag Navigation Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_FlagNavigationTest_H +#define PokemonAutomation_PokemonLA_FlagNavigationTest_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "PokemonLA/Options/PokemonLA_ShinyDetectedAction.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class FlagNavigationTest_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FlagNavigationTest_Descriptor(); +}; + + +class FlagNavigationTest : public SingleSwitchProgramInstance{ +public: + FlagNavigationTest(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption STOP_DISTANCE; + FloatingPointOption FLAG_REACHED_DELAY; + + SimpleIntegerOption NAVIGATION_TIMEOUT; +// ShinyDetectedActionOption SHINY_DETECTED; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.cpp b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.cpp index 468d3a6e75..ae12f6d4a3 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.cpp @@ -1,50 +1,50 @@ -/* Mount Detection Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "PokemonLA_MountDetectionTest.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -MountDetectionTest_Descriptor::MountDetectionTest_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:MountDetectionTest", - STRING_POKEMON + " LA", "Mount Detection Test", - "", - "Test the mount detection in the bottom right corner.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -MountDetectionTest::MountDetectionTest(){ - PA_ADD_OPTION(FAILED_ACTION); -} - - -void MountDetectionTest::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MountTracker tracker(env.console, FAILED_ACTION); - InferenceSession session( - context, env.console, - {{tracker, std::chrono::seconds(1)}} - ); - context.wait_until_cancel(); -} - - - - -} -} -} +/* Mount Detection Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "PokemonLA_MountDetectionTest.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +MountDetectionTest_Descriptor::MountDetectionTest_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:MountDetectionTest", + STRING_POKEMON + " LA", "Mount Detection Test", + "", + "Test the mount detection in the bottom right corner.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +MountDetectionTest::MountDetectionTest(){ + PA_ADD_OPTION(FAILED_ACTION); +} + + +void MountDetectionTest::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MountTracker tracker(env.console, FAILED_ACTION); + InferenceSession session( + context, env.console, + {{tracker, std::chrono::seconds(1)}} + ); + context.wait_until_cancel(); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.h b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.h index 42b91859c3..7a70568dfe 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.h +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_MountDetectionTest.h @@ -1,40 +1,40 @@ -/* Mount Detection Test - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_MountDetectionTest_H -#define PokemonAutomation_PokemonLA_MountDetectionTest_H - -#include "PokemonLA/Inference/PokemonLA_MountDetector.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class MountDetectionTest_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MountDetectionTest_Descriptor(); -}; - - -class MountDetectionTest : public SingleSwitchProgramInstance{ -public: - MountDetectionTest(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - MountDetectorLoggingOption FAILED_ACTION; -}; - - - -} -} -} -#endif +/* Mount Detection Test + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_MountDetectionTest_H +#define PokemonAutomation_PokemonLA_MountDetectionTest_H + +#include "PokemonLA/Inference/PokemonLA_MountDetector.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class MountDetectionTest_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MountDetectionTest_Descriptor(); +}; + + +class MountDetectionTest : public SingleSwitchProgramInstance{ +public: + MountDetectionTest(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + MountDetectorLoggingOption FAILED_ACTION; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.cpp b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.cpp index 1b62fbf806..df1b73d20a 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.cpp @@ -1,67 +1,67 @@ -/* Shiny Hunt - Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h" -#include "PokemonLA_OverworldWatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - -OverworldWatcher_Descriptor::OverworldWatcher_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:OverworldWatcher", - STRING_POKEMON + " LA", "Overworld Watcher", - "", - "This is a test program that simply observes the game and labels things of interest. " - "This program doesn't really do anything.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -OverworldWatcher::OverworldWatcher(){} - - -void OverworldWatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - BubbleDetector bubbles; - ArcDetector arcs; - QuestMarkDetector quest_marks; - FlagDetector flags; - - WhiteObjectWatcher watcher( - env.console, - {0, 0, 1, 1}, - { - {bubbles, false}, - {arcs, false}, - {quest_marks, false}, - {flags, false}, - } - ); - - InferenceSession session( - context, env.console, - {{watcher}} - ); - context.wait_until_cancel(); -} - - - - -} -} -} +/* Shiny Hunt - Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Objects/PokemonLA_BubbleDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ArcDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_QuestMarkDetector.h" +#include "PokemonLA/Inference/Objects/PokemonLA_FlagDetector.h" +#include "PokemonLA_OverworldWatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + +OverworldWatcher_Descriptor::OverworldWatcher_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:OverworldWatcher", + STRING_POKEMON + " LA", "Overworld Watcher", + "", + "This is a test program that simply observes the game and labels things of interest. " + "This program doesn't really do anything.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +OverworldWatcher::OverworldWatcher(){} + + +void OverworldWatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BubbleDetector bubbles; + ArcDetector arcs; + QuestMarkDetector quest_marks; + FlagDetector flags; + + WhiteObjectWatcher watcher( + env.console, + {0, 0, 1, 1}, + { + {bubbles, false}, + {arcs, false}, + {quest_marks, false}, + {flags, false}, + } + ); + + InferenceSession session( + context, env.console, + {{watcher}} + ); + context.wait_until_cancel(); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.h b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.h index ea48e69718..4c359e1396 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.h +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_OverworldWatcher.h @@ -1,40 +1,40 @@ -/* Overworld Watcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_OverworldWatcher_H -#define PokemonAutomation_PokemonLA_OverworldWatcher_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class OverworldWatcher_Descriptor : public SingleSwitchProgramDescriptor{ -public: - OverworldWatcher_Descriptor(); -}; - - -class OverworldWatcher : public SingleSwitchProgramInstance{ -public: - OverworldWatcher(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -}; - - - - - -} -} -} -#endif +/* Overworld Watcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_OverworldWatcher_H +#define PokemonAutomation_PokemonLA_OverworldWatcher_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class OverworldWatcher_Descriptor : public SingleSwitchProgramDescriptor{ +public: + OverworldWatcher_Descriptor(); +}; + + +class OverworldWatcher : public SingleSwitchProgramInstance{ +public: + OverworldWatcher(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.cpp b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.cpp index d58ce5f51a..29bacb8da4 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.cpp @@ -1,217 +1,217 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:SoundListener", - STRING_POKEMON + " LA", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {} - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::Shiny, "shiny", "Shiny Sound"}, - {SoundType::AlphaRoar, "alpha-roar", "Alpha Roar"}, - {SoundType::AlphaMusic, "alpha-music", "Alpha Music"}, - {SoundType::ItemDrop, "item-drop", "Item Drop Sound"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::Shiny - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - - -// void search_alpha_roar_from_audio_dump(); - -void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - // pbf_move_right_joystick(context, 0, 255, 10, 0); - - // search_alpha_roar_from_audio_dump(); - // return; - - std::cout << "Running audio test program." << std::endl; - - std::unique_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::Shiny: - detector = std::make_unique(env.console, action); - break; - case SoundType::AlphaRoar: - detector = std::make_unique(env.console, action); - break; - case SoundType::AlphaMusic: - detector = std::make_unique(env.console, action); - break; - case SoundType::ItemDrop: - detector = std::make_unique(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "Not such sound detector as sound type " + std::to_string((size_t)type) - ); - } - - InferenceSession session( - context, env.console, - {{*detector, std::chrono::milliseconds(20)}} - ); - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - -// A function used to search for the alpha roar on LA audio dump. -// But we didn't find the shound sound :P -void search_alpha_roar_from_audio_dump(){ - - const size_t SAMPLE_RATE = 48000; - - SpectrogramMatcher matcher( - "Alpha Roar", - AudioTemplateCache::instance().get_throw("PokemonLA/AlphaRoar", SAMPLE_RATE), - SpectrogramMatcher::Mode::RAW, SAMPLE_RATE, - 100.0 - ); - - // std::string file_listFile = "./scripts/short_audio_files.txt"; - std::string file_listFile = "1.txt"; - // std::string file_listFile = "./scripts/all_audio_files.txt"; - std::ifstream fin(file_listFile.c_str()); - std::vector file_list; - while(!fin.eof()){ - std::string line; - std::getline(fin, line); - file_list.push_back(line); - fin >> std::ws; - } - std::cout << "File num " << file_list.size() << std::endl; - - std::map closest_files; - - std::ofstream fout("file_check_output.txt"); - - for(size_t fileIdx = 0; fileIdx < file_list.size(); fileIdx++){ - matcher.clear(); - - - const auto& path = file_list[fileIdx]; - std::ostringstream os; - os << "File " << fileIdx << "/" << file_list.size() << " " << path << " "; - AudioTemplate audio = loadAudioTemplate(path); - if (audio.numWindows() == 0){ - os << "Fail" << std::endl; - fout << os.str(); - std::cout << os.str() << std::flush; - continue; - } - - // audio.scale(2.0); - - os << "#W " << audio.numWindows() << " "; - - // match! - float minScore = FLT_MAX; - std::vector new_spectrums; - size_t numStreamWindows = std::max(matcher.numMatchedWindows(), audio.numWindows()); - for(size_t audioIdx = 0; audioIdx < numStreamWindows; audioIdx++){ - new_spectrums.clear(); - AlignedVector freqVector(audio.numFrequencies()); - if (audioIdx < audio.numWindows()){ - const float * freq = audio.getWindow(audioIdx); - memcpy(freqVector.data(), freq, sizeof(float) * audio.numFrequencies()); - }else{ - // add zero-freq window - } - new_spectrums.emplace_back( - audioIdx, SAMPLE_RATE, - std::make_unique>(std::move(freqVector)) - ); - float score = matcher.match(new_spectrums); - minScore = std::min(score, minScore); - } // end audio Idx - - os << "dist " << minScore << std::endl; - fout << os.str(); - std::cout << os.str() << std::flush; - - closest_files.emplace(minScore, path); - } - - fout.close(); - - auto it = closest_files.begin(); - std::cout << "--------------" << std::endl; - fout.open("file_check_output_sorted.txt"); - for(int i = 0; it != closest_files.end(); i++, it++){ - if (i < 40) - std::cout << it->first << ", " << it->second << std::endl; - fout << it->first << ", " << it->second << std::endl; - } - fout.close(); - return; -} - - - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_AlphaMusicDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_AlphaRoarDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ItemDropSoundDetector.h" +#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" +#include "PokemonLA_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:SoundListener", + STRING_POKEMON + " LA", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {} + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::Shiny, "shiny", "Shiny Sound"}, + {SoundType::AlphaRoar, "alpha-roar", "Alpha Roar"}, + {SoundType::AlphaMusic, "alpha-music", "Alpha Music"}, + {SoundType::ItemDrop, "item-drop", "Item Drop Sound"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::Shiny + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + + +// void search_alpha_roar_from_audio_dump(); + +void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + // pbf_move_right_joystick(context, 0, 255, 10, 0); + + // search_alpha_roar_from_audio_dump(); + // return; + + std::cout << "Running audio test program." << std::endl; + + std::unique_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::Shiny: + detector = std::make_unique(env.console, action); + break; + case SoundType::AlphaRoar: + detector = std::make_unique(env.console, action); + break; + case SoundType::AlphaMusic: + detector = std::make_unique(env.console, action); + break; + case SoundType::ItemDrop: + detector = std::make_unique(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "Not such sound detector as sound type " + std::to_string((size_t)type) + ); + } + + InferenceSession session( + context, env.console, + {{*detector, std::chrono::milliseconds(20)}} + ); + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + +// A function used to search for the alpha roar on LA audio dump. +// But we didn't find the shound sound :P +void search_alpha_roar_from_audio_dump(){ + + const size_t SAMPLE_RATE = 48000; + + SpectrogramMatcher matcher( + "Alpha Roar", + AudioTemplateCache::instance().get_throw("PokemonLA/AlphaRoar", SAMPLE_RATE), + SpectrogramMatcher::Mode::RAW, SAMPLE_RATE, + 100.0 + ); + + // std::string file_listFile = "./scripts/short_audio_files.txt"; + std::string file_listFile = "1.txt"; + // std::string file_listFile = "./scripts/all_audio_files.txt"; + std::ifstream fin(file_listFile.c_str()); + std::vector file_list; + while(!fin.eof()){ + std::string line; + std::getline(fin, line); + file_list.push_back(line); + fin >> std::ws; + } + std::cout << "File num " << file_list.size() << std::endl; + + std::map closest_files; + + std::ofstream fout("file_check_output.txt"); + + for(size_t fileIdx = 0; fileIdx < file_list.size(); fileIdx++){ + matcher.clear(); + + + const auto& path = file_list[fileIdx]; + std::ostringstream os; + os << "File " << fileIdx << "/" << file_list.size() << " " << path << " "; + AudioTemplate audio = loadAudioTemplate(path); + if (audio.numWindows() == 0){ + os << "Fail" << std::endl; + fout << os.str(); + std::cout << os.str() << std::flush; + continue; + } + + // audio.scale(2.0); + + os << "#W " << audio.numWindows() << " "; + + // match! + float minScore = FLT_MAX; + std::vector new_spectrums; + size_t numStreamWindows = std::max(matcher.numMatchedWindows(), audio.numWindows()); + for(size_t audioIdx = 0; audioIdx < numStreamWindows; audioIdx++){ + new_spectrums.clear(); + AlignedVector freqVector(audio.numFrequencies()); + if (audioIdx < audio.numWindows()){ + const float * freq = audio.getWindow(audioIdx); + memcpy(freqVector.data(), freq, sizeof(float) * audio.numFrequencies()); + }else{ + // add zero-freq window + } + new_spectrums.emplace_back( + audioIdx, SAMPLE_RATE, + std::make_unique>(std::move(freqVector)) + ); + float score = matcher.match(new_spectrums); + minScore = std::min(score, minScore); + } // end audio Idx + + os << "dist " << minScore << std::endl; + fout << os.str(); + std::cout << os.str() << std::flush; + + closest_files.emplace(minScore, path); + } + + fout.close(); + + auto it = closest_files.begin(); + std::cout << "--------------" << std::endl; + fout.open("file_check_output_sorted.txt"); + for(int i = 0; it != closest_files.end(); i++, it++){ + if (i < 40) + std::cout << it->first << ", " << it->second << std::endl; + fout << it->first << ", " << it->second << std::endl; + } + fout.close(); + return; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.h b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.h index 41e3032240..5c0005730d 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.h +++ b/SerialPrograms/Source/PokemonLA/Programs/TestPrograms/PokemonLA_SoundListener.h @@ -1,49 +1,49 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonLA_SoundListener_H -#define PokemonAutomation_PokemonLA_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - enum class SoundType{ - Shiny, - AlphaRoar, - AlphaMusic, - ItemDrop, - }; - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonLA_SoundListener_H +#define PokemonAutomation_PokemonLA_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + enum class SoundType{ + Shiny, + AlphaRoar, + AlphaMusic, + ItemDrop, + }; + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.cpp b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.cpp index 5cd3b13309..da8b2703f4 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.cpp @@ -1,183 +1,183 @@ -/* Self Box Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA_TradeRoutines.h" -#include "PokemonLA_SelfBoxTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - - -SelfBoxTrade_Descriptor::SelfBoxTrade_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonLA:SelfBoxTrade", - STRING_POKEMON + " LA", "Self Box Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/SelfBoxTrade.md", - "Trade boxes across two Switches.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 2, 2, 2 - ) -{} -std::unique_ptr SelfBoxTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new TradeStats()); -} - - - -SelfBoxTrade::SelfBoxTrade() - : LANGUAGE_LEFT( - "Game Language of Left Switch:", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , LANGUAGE_RIGHT( - "Game Language of Right Switch:", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , BOXES_TO_TRADE( - "Number of Boxes to Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 32 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE_LEFT); - PA_ADD_OPTION(LANGUAGE_RIGHT); - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - - -bool SelfBoxTrade::move_to_next( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - uint8_t& row, uint8_t& col -){ - // Returns true if moved to next box. - - env.log("Moving to next slot."); - if (col < 5){ - env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 140); - }); - col++; - return false; - } - if (row < 4){ - env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - pbf_press_dpad(context, DPAD_DOWN, 20, 140); - }); - col = 0; - row++; - return false; - } - env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_R, 20, 230); - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - pbf_press_dpad(context, DPAD_DOWN, 20, 140); - }); - col = 0; - row = 0; - return true; -} - - -void SelfBoxTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - TradeStats& stats = env.current_stats(); - - - // Connect both controllers. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_LCLICK, 10, 0); - }); - - uint8_t row = 0; - uint8_t col = 0; - for (uint8_t boxes = 0; boxes < BOXES_TO_TRADE;){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // Make sure both consoles have selected something. - std::atomic ok(true); - OverlayBoxScope box0(env.consoles[0], {0.925, 0.100, 0.014, 0.030}); - OverlayBoxScope box1(env.consoles[1], {0.925, 0.100, 0.014, 0.030}); - TradeNameReader name_reader0(env.consoles[0], env.consoles[0], LANGUAGE_LEFT); - TradeNameReader name_reader1(env.consoles[1], env.consoles[1], LANGUAGE_RIGHT); - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - auto snapshot = console.video().snapshot(); - ImageStats stats = image_stats(extract_box_reference(snapshot, box0)); - bool is_ok = is_white(stats); - if (!is_ok){ - console.log("Skipping empty slot.", COLOR_ORANGE); - ok.store(false, std::memory_order_release); - return; - } - - std::string slug = (console.index() == 0 ? name_reader0 : name_reader1).read(snapshot); - if (slug == "machoke" || slug == "haunter" || slug == "graveler" || slug == "kadabra"){ - console.log("Skipping trade evolution: " + slug, COLOR_RED); - ok.store(false, std::memory_order_release); - return; - } - }); - - if (ok.load(std::memory_order_acquire)){ - // Perform trade. - MultiConsoleErrorState error_state; - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - trade_current_pokemon(console, context, error_state, stats); - }); - stats.m_trades++; - }else{ - stats.m_errors++; - } - - // Move to next slot. - if (move_to_next(env, scope, row, col)){ - boxes++; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - - -} -} -} +/* Self Box Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA_TradeRoutines.h" +#include "PokemonLA_SelfBoxTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + + +SelfBoxTrade_Descriptor::SelfBoxTrade_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonLA:SelfBoxTrade", + STRING_POKEMON + " LA", "Self Box Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/SelfBoxTrade.md", + "Trade boxes across two Switches.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 2, 2, 2 + ) +{} +std::unique_ptr SelfBoxTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new TradeStats()); +} + + + +SelfBoxTrade::SelfBoxTrade() + : LANGUAGE_LEFT( + "Game Language of Left Switch:", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , LANGUAGE_RIGHT( + "Game Language of Right Switch:", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , BOXES_TO_TRADE( + "Number of Boxes to Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 32 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE_LEFT); + PA_ADD_OPTION(LANGUAGE_RIGHT); + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + + +bool SelfBoxTrade::move_to_next( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + uint8_t& row, uint8_t& col +){ + // Returns true if moved to next box. + + env.log("Moving to next slot."); + if (col < 5){ + env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 140); + }); + col++; + return false; + } + if (row < 4){ + env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + pbf_press_dpad(context, DPAD_DOWN, 20, 140); + }); + col = 0; + row++; + return false; + } + env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_R, 20, 230); + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + pbf_press_dpad(context, DPAD_DOWN, 20, 140); + }); + col = 0; + row = 0; + return true; +} + + +void SelfBoxTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + TradeStats& stats = env.current_stats(); + + + // Connect both controllers. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_LCLICK, 10, 0); + }); + + uint8_t row = 0; + uint8_t col = 0; + for (uint8_t boxes = 0; boxes < BOXES_TO_TRADE;){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // Make sure both consoles have selected something. + std::atomic ok(true); + OverlayBoxScope box0(env.consoles[0], {0.925, 0.100, 0.014, 0.030}); + OverlayBoxScope box1(env.consoles[1], {0.925, 0.100, 0.014, 0.030}); + TradeNameReader name_reader0(env.consoles[0], env.consoles[0], LANGUAGE_LEFT); + TradeNameReader name_reader1(env.consoles[1], env.consoles[1], LANGUAGE_RIGHT); + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + auto snapshot = console.video().snapshot(); + ImageStats stats = image_stats(extract_box_reference(snapshot, box0)); + bool is_ok = is_white(stats); + if (!is_ok){ + console.log("Skipping empty slot.", COLOR_ORANGE); + ok.store(false, std::memory_order_release); + return; + } + + std::string slug = (console.index() == 0 ? name_reader0 : name_reader1).read(snapshot); + if (slug == "machoke" || slug == "haunter" || slug == "graveler" || slug == "kadabra"){ + console.log("Skipping trade evolution: " + slug, COLOR_RED); + ok.store(false, std::memory_order_release); + return; + } + }); + + if (ok.load(std::memory_order_acquire)){ + // Perform trade. + MultiConsoleErrorState error_state; + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + trade_current_pokemon(console, context, error_state, stats); + }); + stats.m_trades++; + }else{ + stats.m_errors++; + } + + // Move to next slot. + if (move_to_next(env, scope, row, col)){ + boxes++; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.h b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.h index a3428e373f..7651b8a67e 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfBoxTrade.h @@ -1,55 +1,55 @@ -/* Self Box Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_SelfBoxTrade_H -#define PokemonAutomation_PokemonLA_SelfBoxTrade_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -class SelfBoxTrade_Descriptor : public MultiSwitchProgramDescriptor{ -public: - SelfBoxTrade_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class SelfBoxTrade : public MultiSwitchProgramInstance{ -public: - SelfBoxTrade(); - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - bool move_to_next( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - uint8_t& row, uint8_t& col - ); - -private: - OCR::LanguageOCROption LANGUAGE_LEFT; - OCR::LanguageOCROption LANGUAGE_RIGHT; - - SimpleIntegerOption BOXES_TO_TRADE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Self Box Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_SelfBoxTrade_H +#define PokemonAutomation_PokemonLA_SelfBoxTrade_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +class SelfBoxTrade_Descriptor : public MultiSwitchProgramDescriptor{ +public: + SelfBoxTrade_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class SelfBoxTrade : public MultiSwitchProgramInstance{ +public: + SelfBoxTrade(); + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + bool move_to_next( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + uint8_t& row, uint8_t& col + ); + +private: + OCR::LanguageOCROption LANGUAGE_LEFT; + OCR::LanguageOCROption LANGUAGE_RIGHT; + + SimpleIntegerOption BOXES_TO_TRADE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.cpp b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.cpp index 14f69b199f..e12163c9b0 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.cpp @@ -1,223 +1,223 @@ -/* Self Touch Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA_TradeRoutines.h" -#include "PokemonLA_SelfTouchTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - using namespace Pokemon; - - - -SelfTouchTrade_Descriptor::SelfTouchTrade_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonLA:SelfTouchTrade", - STRING_POKEMON + " LA", "Self Touch Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonLA/SelfTouchTrade.md", - "Repeatedly trade " + STRING_POKEMON + " between two local Switches to fill up research.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 2, 2, 2 - ) -{} -std::unique_ptr SelfTouchTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new TradeStats()); -} - - - -SelfTouchTrade::SelfTouchTrade() - : LANGUAGE( - "Game Language of the Hosting Switch:", - Pokemon::PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , HOSTING_SWITCH( - "Host Switch:
This is the Switch hosting the " + STRING_POKEMON + " to be touch-traded to the other.", - { - {HostingSwitch::Switch0, "switch0", "Switch 0 (Left)"}, - {HostingSwitch::Switch1, "switch1", "Switch 1 (Right)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - HostingSwitch::Switch0 - ) - , BOXES_TO_TRADE( - "Number of Boxes to Touch-Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 32 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(HOSTING_SWITCH); - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(TRADE_COUNTS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -bool SelfTouchTrade::trade_one( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - std::map*>& trades_left -){ - TradeStats& stats = env.current_stats(); - - ConsoleHandle& host = HOSTING_SWITCH == HostingSwitch::Switch0 ? env.consoles[0] : env.consoles[1]; - - // Read the name and see if the receiver still needs it. - TradeNameReader name_reader(host, host, LANGUAGE); - VideoSnapshot snapshot = host.video().snapshot(); - std::string slug = name_reader.read(snapshot); - auto iter = trades_left.find(slug); - if (iter == trades_left.end()){ - host.log("Unable to read name. Moving on...", COLOR_RED); - stats.m_errors++; - dump_image(host, env.program_info(), "ReadName", snapshot); - return false; - } - uint8_t current_trades_left = iter->second->current_value(); - if (current_trades_left <= 0){ - host.log(STRING_POKEMON + " not needed anymore. Moving on..."); - return false; - } - if (slug == "machoke" || slug == "haunter" || slug == "graveler" || slug == "kadabra"){ - host.log("Skipping trade evolution: " + slug, COLOR_RED); - return false; - } - - // Perform trade. - host.log("\"" + slug + "\" - Trades Remaining: " + std::to_string(current_trades_left)); -#if 1 - MultiConsoleErrorState error_state; - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - trade_current_pokemon(console, context, error_state, stats); - }); - stats.m_trades++; - iter->second->set(current_trades_left - 1); -#else - env.wait_for(std::chrono::milliseconds(5000)); - return false; -#endif - scope.wait_for(std::chrono::milliseconds(500)); - - return true; -} -bool SelfTouchTrade::move_to_next(Logger& logger, ProControllerContext& host, uint8_t& row, uint8_t& col){ - // Returns true if moved to next box. - - logger.log("Moving to next slot."); - if (col < 5){ - pbf_press_dpad(host, DPAD_RIGHT, 20, 140); - col++; - return false; - } - if (row < 4){ - pbf_press_dpad(host, DPAD_RIGHT, 20, 105); - pbf_press_dpad(host, DPAD_RIGHT, 20, 105); - pbf_press_dpad(host, DPAD_DOWN, 20, 140); - col = 0; - row++; - return false; - } - pbf_press_button(host, BUTTON_R, 20, 230); - pbf_press_dpad(host, DPAD_RIGHT, 20, 105); - pbf_press_dpad(host, DPAD_RIGHT, 20, 105); - pbf_press_dpad(host, DPAD_DOWN, 20, 140); - col = 0; - row = 0; - return true; -} - - -void SelfTouchTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - // Build list of what's needed. - std::map*> trades_left; - for (StaticTableRow* item : TRADE_COUNTS.table()){ - trades_left[item->slug()] = &static_cast(*item).count; - } - - // Connect both controllers. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_LCLICK, 10, 0); - }); - - uint8_t row = 0; - uint8_t col = 0; - - bool host0 = HOSTING_SWITCH == HostingSwitch::Switch0; - ProControllerContext host_context(scope, (host0 ? env.consoles[0] : env.consoles[1]).pro_controller()); - ConsoleHandle& host = host0 ? env.consoles[0] : env.consoles[1]; - ConsoleHandle& recv = host0 ? env.consoles[1] : env.consoles[0]; - - for (uint8_t boxes = 0; boxes < BOXES_TO_TRADE;){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // Make sure both consoles have selected something. - bool host_ok, recv_ok; - OverlayBoxScope box0(host, {0.925, 0.100, 0.014, 0.030}); - OverlayBoxScope box1(recv, {0.925, 0.100, 0.014, 0.030}); - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - ImageStats stats = image_stats(extract_box_reference(console.video().snapshot(), box0)); - bool ok = is_white(stats); - if (host.index() == console.index()){ - host_ok = ok; - }else{ - recv_ok = ok; - } - }); - - if (!recv_ok){ - throw UserSetupError(recv, "Receiving Switch has not selected a " + STRING_POKEMON + "."); - } - - // Perform trade. - bool traded = false; - if (host_ok){ - traded = trade_one(env, scope, trades_left); - }else{ - recv.log("Skipping empty slot on host...", COLOR_PURPLE); - } - - // Move to next slot. - if (!traded){ - if (move_to_next(host, host_context, row, col)){ - boxes++; - } - host_context.wait_for_all_requests(); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Self Touch Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA_TradeRoutines.h" +#include "PokemonLA_SelfTouchTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + using namespace Pokemon; + + + +SelfTouchTrade_Descriptor::SelfTouchTrade_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonLA:SelfTouchTrade", + STRING_POKEMON + " LA", "Self Touch Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonLA/SelfTouchTrade.md", + "Repeatedly trade " + STRING_POKEMON + " between two local Switches to fill up research.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 2, 2, 2 + ) +{} +std::unique_ptr SelfTouchTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new TradeStats()); +} + + + +SelfTouchTrade::SelfTouchTrade() + : LANGUAGE( + "Game Language of the Hosting Switch:", + Pokemon::PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , HOSTING_SWITCH( + "Host Switch:
This is the Switch hosting the " + STRING_POKEMON + " to be touch-traded to the other.", + { + {HostingSwitch::Switch0, "switch0", "Switch 0 (Left)"}, + {HostingSwitch::Switch1, "switch1", "Switch 1 (Right)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + HostingSwitch::Switch0 + ) + , BOXES_TO_TRADE( + "Number of Boxes to Touch-Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 32 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(HOSTING_SWITCH); + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(TRADE_COUNTS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +bool SelfTouchTrade::trade_one( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + std::map*>& trades_left +){ + TradeStats& stats = env.current_stats(); + + ConsoleHandle& host = HOSTING_SWITCH == HostingSwitch::Switch0 ? env.consoles[0] : env.consoles[1]; + + // Read the name and see if the receiver still needs it. + TradeNameReader name_reader(host, host, LANGUAGE); + VideoSnapshot snapshot = host.video().snapshot(); + std::string slug = name_reader.read(snapshot); + auto iter = trades_left.find(slug); + if (iter == trades_left.end()){ + host.log("Unable to read name. Moving on...", COLOR_RED); + stats.m_errors++; + dump_image(host, env.program_info(), "ReadName", snapshot); + return false; + } + uint8_t current_trades_left = iter->second->current_value(); + if (current_trades_left <= 0){ + host.log(STRING_POKEMON + " not needed anymore. Moving on..."); + return false; + } + if (slug == "machoke" || slug == "haunter" || slug == "graveler" || slug == "kadabra"){ + host.log("Skipping trade evolution: " + slug, COLOR_RED); + return false; + } + + // Perform trade. + host.log("\"" + slug + "\" - Trades Remaining: " + std::to_string(current_trades_left)); +#if 1 + MultiConsoleErrorState error_state; + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + trade_current_pokemon(console, context, error_state, stats); + }); + stats.m_trades++; + iter->second->set(current_trades_left - 1); +#else + env.wait_for(std::chrono::milliseconds(5000)); + return false; +#endif + scope.wait_for(std::chrono::milliseconds(500)); + + return true; +} +bool SelfTouchTrade::move_to_next(Logger& logger, ProControllerContext& host, uint8_t& row, uint8_t& col){ + // Returns true if moved to next box. + + logger.log("Moving to next slot."); + if (col < 5){ + pbf_press_dpad(host, DPAD_RIGHT, 20, 140); + col++; + return false; + } + if (row < 4){ + pbf_press_dpad(host, DPAD_RIGHT, 20, 105); + pbf_press_dpad(host, DPAD_RIGHT, 20, 105); + pbf_press_dpad(host, DPAD_DOWN, 20, 140); + col = 0; + row++; + return false; + } + pbf_press_button(host, BUTTON_R, 20, 230); + pbf_press_dpad(host, DPAD_RIGHT, 20, 105); + pbf_press_dpad(host, DPAD_RIGHT, 20, 105); + pbf_press_dpad(host, DPAD_DOWN, 20, 140); + col = 0; + row = 0; + return true; +} + + +void SelfTouchTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + // Build list of what's needed. + std::map*> trades_left; + for (StaticTableRow* item : TRADE_COUNTS.table()){ + trades_left[item->slug()] = &static_cast(*item).count; + } + + // Connect both controllers. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_LCLICK, 10, 0); + }); + + uint8_t row = 0; + uint8_t col = 0; + + bool host0 = HOSTING_SWITCH == HostingSwitch::Switch0; + ProControllerContext host_context(scope, (host0 ? env.consoles[0] : env.consoles[1]).pro_controller()); + ConsoleHandle& host = host0 ? env.consoles[0] : env.consoles[1]; + ConsoleHandle& recv = host0 ? env.consoles[1] : env.consoles[0]; + + for (uint8_t boxes = 0; boxes < BOXES_TO_TRADE;){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // Make sure both consoles have selected something. + bool host_ok, recv_ok; + OverlayBoxScope box0(host, {0.925, 0.100, 0.014, 0.030}); + OverlayBoxScope box1(recv, {0.925, 0.100, 0.014, 0.030}); + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + ImageStats stats = image_stats(extract_box_reference(console.video().snapshot(), box0)); + bool ok = is_white(stats); + if (host.index() == console.index()){ + host_ok = ok; + }else{ + recv_ok = ok; + } + }); + + if (!recv_ok){ + throw UserSetupError(recv, "Receiving Switch has not selected a " + STRING_POKEMON + "."); + } + + // Perform trade. + bool traded = false; + if (host_ok){ + traded = trade_one(env, scope, trades_left); + }else{ + recv.log("Skipping empty slot on host...", COLOR_PURPLE); + } + + // Move to next slot. + if (!traded){ + if (move_to_next(host, host_context, row, col)){ + boxes++; + } + host_context.wait_for_all_requests(); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.h b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.h index ebcac3d61d..2272ba4665 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_SelfTouchTrade.h @@ -1,65 +1,65 @@ -/* Self Touch Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_SelfTouchTrade_H -#define PokemonAutomation_PokemonLA_SelfTouchTrade_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "PokemonLA/Options/PokemonLA_TradeCountTable.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -class SelfTouchTrade_Descriptor : public MultiSwitchProgramDescriptor{ -public: - SelfTouchTrade_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class SelfTouchTrade : public MultiSwitchProgramInstance{ -public: - SelfTouchTrade(); - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - bool trade_one( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - std::map*>& trades_left - ); - bool move_to_next(Logger& logger, ProControllerContext& host, uint8_t& row, uint8_t& col); - -private: - OCR::LanguageOCROption LANGUAGE; - - enum class HostingSwitch{ - Switch0, - Switch1 - }; - EnumDropdownOption HOSTING_SWITCH; - - SimpleIntegerOption BOXES_TO_TRADE; - TradeCountTable TRADE_COUNTS; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Self Touch Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_SelfTouchTrade_H +#define PokemonAutomation_PokemonLA_SelfTouchTrade_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "PokemonLA/Options/PokemonLA_TradeCountTable.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +class SelfTouchTrade_Descriptor : public MultiSwitchProgramDescriptor{ +public: + SelfTouchTrade_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class SelfTouchTrade : public MultiSwitchProgramInstance{ +public: + SelfTouchTrade(); + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + bool trade_one( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + std::map*>& trades_left + ); + bool move_to_next(Logger& logger, ProControllerContext& host, uint8_t& row, uint8_t& col); + +private: + OCR::LanguageOCROption LANGUAGE; + + enum class HostingSwitch{ + Switch0, + Switch1 + }; + EnumDropdownOption HOSTING_SWITCH; + + SimpleIntegerOption BOXES_TO_TRADE; + TradeCountTable TRADE_COUNTS; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.cpp b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.cpp index 2b06609cc2..62eeaf0635 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.cpp +++ b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.cpp @@ -1,215 +1,215 @@ -/* Trade Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/VisualDetectors/ImageMatchDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" -#include "PokemonLA_TradeRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -TradeStats::TradeStats() - : m_trades(m_stats["Trades"]) - , m_errors(m_stats["Errors"]) -{ - m_display_order.emplace_back("Trades"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); -} - - - -void trade_current_pokemon( - VideoStream& stream, ProControllerContext& context, - MultiConsoleErrorState& tracker, - TradeStats& stats -){ - tracker.check_unrecoverable_error(stream.logger()); - - context.wait_for_all_requests(); - VideoSnapshot box_image = stream.video().snapshot(); - ImageMatchWatcher box_detector(std::move(box_image.frame), {0.02, 0.15, 0.15, 0.80}, 50); - - { - pbf_press_button(context, BUTTON_A, 20, 0); - context.wait_for_all_requests(); - ButtonDetector detector( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, ImageFloatBox(0.25, 0.15, 0.50, 0.75), - std::chrono::milliseconds(0), true - ); - int ret = wait_until( - stream, context, std::chrono::seconds(120), - {{detector}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect trade select prompt after 2 minutes."); - } - stream.log("Detected trade prompt."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - { - pbf_press_button(context, BUTTON_A, 20, 105); - context.wait_for_all_requests(); - ButtonDetector detector( - stream.logger(), stream.overlay(), - ButtonType::ButtonA, ImageFloatBox(0.50, 0.52, 0.40, 0.10), - std::chrono::milliseconds(0), true - ); - int ret = wait_until( - stream, context, std::chrono::seconds(10), - {{detector}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect trade confirm prompt after 10 seconds."); - } - stream.log("Detected trade confirm prompt."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - - // Start trade. - pbf_press_button(context, BUTTON_A, 20, 0); - - // Wait for black screen. - { - BlackScreenOverWatcher black_screen; - int ret = wait_until( - stream, context, std::chrono::minutes(2), - {{black_screen}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect start of trade after 2 minutes."); - } - stream.log("Detected start of trade."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - - // Mash B until 2nd black screen. - { - BlackScreenWatcher black_screen; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - {{black_screen}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect end of trade after 2 minutes."); - } - stream.log("Detected end of trade."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - - // Wait to return to box. - { - int ret = wait_until( - stream, context, std::chrono::minutes(2), - {{box_detector}} - ); - if (ret < 0){ - stats.m_errors++; -// box_image->save("ExpectedBox.png"); - tracker.report_unrecoverable_error(stream, "Failed to return to box after 2 minutes after a trade."); - } - stream.log("Detected box. Trade completed."); - tracker.check_unrecoverable_error(stream.logger()); - } -} - - - - - -TradeNameReader::TradeNameReader(Logger& logger, VideoOverlay& overlay, Language language) - : m_logger(logger) - , m_language(language) - , m_box(overlay, {0.80, 0.155, 0.18, 0.05}) -{ - std::string path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-Hisui.json"; - JsonValue json = load_json_file(path); - JsonArray& array = json.to_array_throw(path); - for (auto& item : array){ - m_slugs.insert(std::move(item.to_string_throw(path))); - } -} - -std::string TradeNameReader::read(const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_box); - OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( - m_logger, m_language, image, - OCR::WHITE_TEXT_FILTERS() - ); - result.clear_beyond_log10p(Pokemon::PokemonNameReader::MAX_LOG10P); - - for (auto iter = result.results.begin(); iter != result.results.end();){ - // Remove from candidates if it's not in PLA. - if (m_slugs.find(iter->second.token) == m_slugs.end()){ - iter = result.results.erase(iter); - }else{ - ++iter; - } - } - - if (result.results.size() != 1){ - dump_image(m_logger, ProgramInfo(), "TradeNameReader", screen); - return ""; - } - - return std::move(result.results.begin()->second.token); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Trade Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/VisualDetectors/ImageMatchDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonLA/Inference/Objects/PokemonLA_ButtonDetector.h" +#include "PokemonLA_TradeRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +TradeStats::TradeStats() + : m_trades(m_stats["Trades"]) + , m_errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Trades"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); +} + + + +void trade_current_pokemon( + VideoStream& stream, ProControllerContext& context, + MultiConsoleErrorState& tracker, + TradeStats& stats +){ + tracker.check_unrecoverable_error(stream.logger()); + + context.wait_for_all_requests(); + VideoSnapshot box_image = stream.video().snapshot(); + ImageMatchWatcher box_detector(std::move(box_image.frame), {0.02, 0.15, 0.15, 0.80}, 50); + + { + pbf_press_button(context, BUTTON_A, 20, 0); + context.wait_for_all_requests(); + ButtonDetector detector( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, ImageFloatBox(0.25, 0.15, 0.50, 0.75), + std::chrono::milliseconds(0), true + ); + int ret = wait_until( + stream, context, std::chrono::seconds(120), + {{detector}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect trade select prompt after 2 minutes."); + } + stream.log("Detected trade prompt."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + { + pbf_press_button(context, BUTTON_A, 20, 105); + context.wait_for_all_requests(); + ButtonDetector detector( + stream.logger(), stream.overlay(), + ButtonType::ButtonA, ImageFloatBox(0.50, 0.52, 0.40, 0.10), + std::chrono::milliseconds(0), true + ); + int ret = wait_until( + stream, context, std::chrono::seconds(10), + {{detector}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect trade confirm prompt after 10 seconds."); + } + stream.log("Detected trade confirm prompt."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + + // Start trade. + pbf_press_button(context, BUTTON_A, 20, 0); + + // Wait for black screen. + { + BlackScreenOverWatcher black_screen; + int ret = wait_until( + stream, context, std::chrono::minutes(2), + {{black_screen}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect start of trade after 2 minutes."); + } + stream.log("Detected start of trade."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + + // Mash B until 2nd black screen. + { + BlackScreenWatcher black_screen; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + {{black_screen}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect end of trade after 2 minutes."); + } + stream.log("Detected end of trade."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + + // Wait to return to box. + { + int ret = wait_until( + stream, context, std::chrono::minutes(2), + {{box_detector}} + ); + if (ret < 0){ + stats.m_errors++; +// box_image->save("ExpectedBox.png"); + tracker.report_unrecoverable_error(stream, "Failed to return to box after 2 minutes after a trade."); + } + stream.log("Detected box. Trade completed."); + tracker.check_unrecoverable_error(stream.logger()); + } +} + + + + + +TradeNameReader::TradeNameReader(Logger& logger, VideoOverlay& overlay, Language language) + : m_logger(logger) + , m_language(language) + , m_box(overlay, {0.80, 0.155, 0.18, 0.05}) +{ + std::string path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-Hisui.json"; + JsonValue json = load_json_file(path); + JsonArray& array = json.to_array_throw(path); + for (auto& item : array){ + m_slugs.insert(std::move(item.to_string_throw(path))); + } +} + +std::string TradeNameReader::read(const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_box); + OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( + m_logger, m_language, image, + OCR::WHITE_TEXT_FILTERS() + ); + result.clear_beyond_log10p(Pokemon::PokemonNameReader::MAX_LOG10P); + + for (auto iter = result.results.begin(); iter != result.results.end();){ + // Remove from candidates if it's not in PLA. + if (m_slugs.find(iter->second.token) == m_slugs.end()){ + iter = result.results.erase(iter); + }else{ + ++iter; + } + } + + if (result.results.size() != 1){ + dump_image(m_logger, ProgramInfo(), "TradeNameReader", screen); + return ""; + } + + return std::move(result.results.begin()->second.token); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.h b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.h index dfc0c879bb..04942cc9c1 100644 --- a/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.h +++ b/SerialPrograms/Source/PokemonLA/Programs/Trading/PokemonLA_TradeRoutines.h @@ -1,57 +1,57 @@ -/* Trade Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_TradeRoutines_H -#define PokemonAutomation_PokemonLA_TradeRoutines_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/MultiConsoleErrors.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLA{ - - -struct TradeStats : public StatsTracker{ - TradeStats(); - std::atomic& m_trades; - std::atomic& m_errors; -}; - - -void trade_current_pokemon( - VideoStream& stream, ProControllerContext& context, - MultiConsoleErrorState& tracker, - TradeStats& stats -); - - - -class TradeNameReader{ -public: - TradeNameReader(Logger& logger, VideoOverlay& overlay, Language language); - - std::string read(const ImageViewRGB32& screen) const; - -private: - Logger& m_logger; - Language m_language; - OverlayBoxScope m_box; - std::set m_slugs; -}; - - - - -} -} -} -#endif +/* Trade Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_TradeRoutines_H +#define PokemonAutomation_PokemonLA_TradeRoutines_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/MultiConsoleErrors.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLA{ + + +struct TradeStats : public StatsTracker{ + TradeStats(); + std::atomic& m_trades; + std::atomic& m_errors; +}; + + +void trade_current_pokemon( + VideoStream& stream, ProControllerContext& context, + MultiConsoleErrorState& tracker, + TradeStats& stats +); + + + +class TradeNameReader{ +public: + TradeNameReader(Logger& logger, VideoOverlay& overlay, Language language); + + std::string read(const ImageViewRGB32& screen) const; + +private: + Logger& m_logger; + Language m_language; + OverlayBoxScope m_box; + std::set m_slugs; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp index 9fe2c6fa4b..64ee840f99 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp @@ -1,54 +1,54 @@ -/* Available Pokemon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonLA_AvailablePokemon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - -const std::vector& HISUI_DEX_SLUGS(){ - static const std::vector database = Pokemon::load_pokemon_slug_json_list("Pokemon/Pokedex/Pokedex-Hisui.json"); - return database; -} - -const std::vector& HISUI_OUTBREAK_SLUGS(){ - static const std::vector database = Pokemon::load_pokemon_slug_json_list("PokemonLA/OutbreakList.json"); - return database; -} - -const std::vector& MMO_FIRST_WAVE_SPRITE_SLUGS(){ - static const std::vector database = Pokemon::load_pokemon_slug_json_list("PokemonLA/MMOFirstWaveSpriteList.json"); - return database; -} - -std::array, 5> load_MMO_first_wave_region_sprite_slugs(){ - std::array, 5> slugs; - for(int i = 0; i < 5; i++){ - std::string filename = "PokemonLA/MMOFirstWaveSpriteList-" + std::to_string(i) + ".json"; - slugs[i] = Pokemon::load_pokemon_slug_json_list(filename.c_str()); - } - return slugs; -} - -const std::array, 5>& MMO_FIRST_WAVE_REGION_SPRITE_SLUGS(){ - static const std::array, 5> database = load_MMO_first_wave_region_sprite_slugs(); - return database; -} - - - - - - -} -} -} +/* Available Pokemon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonLA_AvailablePokemon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + +const std::vector& HISUI_DEX_SLUGS(){ + static const std::vector database = Pokemon::load_pokemon_slug_json_list("Pokemon/Pokedex/Pokedex-Hisui.json"); + return database; +} + +const std::vector& HISUI_OUTBREAK_SLUGS(){ + static const std::vector database = Pokemon::load_pokemon_slug_json_list("PokemonLA/OutbreakList.json"); + return database; +} + +const std::vector& MMO_FIRST_WAVE_SPRITE_SLUGS(){ + static const std::vector database = Pokemon::load_pokemon_slug_json_list("PokemonLA/MMOFirstWaveSpriteList.json"); + return database; +} + +std::array, 5> load_MMO_first_wave_region_sprite_slugs(){ + std::array, 5> slugs; + for(int i = 0; i < 5; i++){ + std::string filename = "PokemonLA/MMOFirstWaveSpriteList-" + std::to_string(i) + ".json"; + slugs[i] = Pokemon::load_pokemon_slug_json_list(filename.c_str()); + } + return slugs; +} + +const std::array, 5>& MMO_FIRST_WAVE_REGION_SPRITE_SLUGS(){ + static const std::array, 5> database = load_MMO_first_wave_region_sprite_slugs(); + return database; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.h b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.h index a8e31c7b8c..a112cfdd3d 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.h +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.h @@ -1,33 +1,33 @@ -/* Available Pokemon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_AvailablePokemon_H -#define PokemonAutomation_PokemonLA_AvailablePokemon_H - -#include -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -const std::vector& HISUI_DEX_SLUGS(); - -// List of pokemon in Hisui dex order that appear in Massive Outbreak. -const std::vector& HISUI_OUTBREAK_SLUGS(); - -// List of pokemon sprite slugs in Hisui dex order that appear in first MMO waves. -const std::vector& MMO_FIRST_WAVE_SPRITE_SLUGS(); - -// List of pokemon sprite slugs in Hisui dex order that appear in first MMO waves of each of the five regions. -const std::array, 5>& MMO_FIRST_WAVE_REGION_SPRITE_SLUGS(); - -} -} -} -#endif +/* Available Pokemon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_AvailablePokemon_H +#define PokemonAutomation_PokemonLA_AvailablePokemon_H + +#include +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +const std::vector& HISUI_DEX_SLUGS(); + +// List of pokemon in Hisui dex order that appear in Massive Outbreak. +const std::vector& HISUI_OUTBREAK_SLUGS(); + +// List of pokemon sprite slugs in Hisui dex order that appear in first MMO waves. +const std::vector& MMO_FIRST_WAVE_SPRITE_SLUGS(); + +// List of pokemon sprite slugs in Hisui dex order that appear in first MMO waves of each of the five regions. +const std::array, 5>& MMO_FIRST_WAVE_REGION_SPRITE_SLUGS(); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.cpp b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.cpp index 383c2fd922..bfba9ca450 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.cpp +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.cpp @@ -1,58 +1,58 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonLA_PokemonSprites.h" -#include "PokemonLA_NameDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -using namespace Pokemon; - - - -StringSelectDatabase make_name_database(const std::vector& slugs){ - const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); - - StringSelectDatabase database; - for (const std::string& slug : slugs){ - const PokemonNames& name = get_pokemon_name(slug); - const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); - if (sprite){ - database.add_entry(StringSelectEntry( - slug, - name.display_name(), - sprite->icon - )); - }else{ - global_logger_tagged().log("No sprite for: " + slug); - database.add_entry(StringSelectEntry( - slug, - name.display_name() - )); - } - } - return database; -} -StringSelectDatabase make_name_database(const char* json_file_slugs){ - return make_name_database(load_pokemon_slug_json_list(json_file_slugs)); -} - - - -const StringSelectDatabase& ALL_POKEMON_NAMES(){ - static const StringSelectDatabase database = make_name_database("Pokemon/Pokedex/Pokedex-Hisui.json"); - return database; -} - - - -} -} -} +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonLA_PokemonSprites.h" +#include "PokemonLA_NameDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +using namespace Pokemon; + + + +StringSelectDatabase make_name_database(const std::vector& slugs){ + const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); + + StringSelectDatabase database; + for (const std::string& slug : slugs){ + const PokemonNames& name = get_pokemon_name(slug); + const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); + if (sprite){ + database.add_entry(StringSelectEntry( + slug, + name.display_name(), + sprite->icon + )); + }else{ + global_logger_tagged().log("No sprite for: " + slug); + database.add_entry(StringSelectEntry( + slug, + name.display_name() + )); + } + } + return database; +} +StringSelectDatabase make_name_database(const char* json_file_slugs){ + return make_name_database(load_pokemon_slug_json_list(json_file_slugs)); +} + + + +const StringSelectDatabase& ALL_POKEMON_NAMES(){ + static const StringSelectDatabase database = make_name_database("Pokemon/Pokedex/Pokedex-Hisui.json"); + return database; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.h b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.h index eceff03b00..f0e76a5fb3 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.h +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_NameDatabase.h @@ -1,28 +1,28 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_NameDatabase_H -#define PokemonAutomation_PokemonLA_NameDatabase_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -StringSelectDatabase make_name_database(const std::vector& slugs); -StringSelectDatabase make_name_database(const char* json_file_slugs); - -const StringSelectDatabase& ALL_POKEMON_NAMES(); - - - - -} -} -} -#endif +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_NameDatabase_H +#define PokemonAutomation_PokemonLA_NameDatabase_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +StringSelectDatabase make_name_database(const std::vector& slugs); +StringSelectDatabase make_name_database(const char* json_file_slugs); + +const StringSelectDatabase& ALL_POKEMON_NAMES(); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.cpp b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.cpp index 67c70f1327..8195fa2033 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.cpp +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.cpp @@ -1,23 +1,23 @@ -/* Pokemon LA Info - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Globals.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonLA_PokemonInfo.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - - - - - -} -} -} +/* Pokemon LA Info + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Globals.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonLA_PokemonInfo.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.h b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.h index 446a00bc53..febab928c0 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.h +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonInfo.h @@ -1,48 +1,48 @@ -/* Pokemon LA Info - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_PokemonInfo_H -#define PokemonAutomation_PokemonLA_PokemonInfo_H - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -enum class Gender{ - Unknown, - Genderless, - Male, - Female, -}; -inline const char* get_gender_str(Gender gender){ - switch (gender){ - case Gender::Unknown: return "Unknown"; - case Gender::Genderless: return "Genderless"; - case Gender::Male: return "Male"; - case Gender::Female: return "Female"; - } - return nullptr; -} - - -struct PokemonDetails{ - std::set name_candidates; - Gender gender = Gender::Unknown; - bool is_shiny = false; - bool is_alpha = false; -}; - - - - -} -} -} -#endif +/* Pokemon LA Info + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_PokemonInfo_H +#define PokemonAutomation_PokemonLA_PokemonInfo_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +enum class Gender{ + Unknown, + Genderless, + Male, + Female, +}; +inline const char* get_gender_str(Gender gender){ + switch (gender){ + case Gender::Unknown: return "Unknown"; + case Gender::Genderless: return "Genderless"; + case Gender::Male: return "Male"; + case Gender::Female: return "Female"; + } + return nullptr; +} + + +struct PokemonDetails{ + std::set name_candidates; + Gender gender = Gender::Unknown; + bool is_shiny = false; + bool is_alpha = false; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.cpp b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.cpp index b061c547e3..45912768b1 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.cpp +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.cpp @@ -1,28 +1,28 @@ -/* Pokemon LA Icons - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonLA_PokemonSprites.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - - -const SpriteDatabase& ALL_POKEMON_SPRITES(){ - static const SpriteDatabase database("PokemonLA/PokemonSprites.png", "PokemonLA/PokemonSprites.json"); - return database; -} - - -const SpriteDatabase& ALL_MMO_SPRITES(){ - static const SpriteDatabase database("PokemonLA/MMOSprites.png", "PokemonLA/MMOSprites.json"); - return database; -} - - -} -} -} +/* Pokemon LA Icons + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonLA_PokemonSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + + +const SpriteDatabase& ALL_POKEMON_SPRITES(){ + static const SpriteDatabase database("PokemonLA/PokemonSprites.png", "PokemonLA/PokemonSprites.json"); + return database; +} + + +const SpriteDatabase& ALL_MMO_SPRITES(){ + static const SpriteDatabase database("PokemonLA/MMOSprites.png", "PokemonLA/MMOSprites.json"); + return database; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.h b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.h index 870550fb70..8210636eeb 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.h +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_PokemonSprites.h @@ -1,25 +1,25 @@ -/* Pokemon LA Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_PokemonSprites_H -#define PokemonAutomation_PokemonLA_PokemonSprites_H - -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -// All pokemon sprites in LA -const SpriteDatabase& ALL_POKEMON_SPRITES(); - -// All icons of pokemon sprites in MMO -const SpriteDatabase& ALL_MMO_SPRITES(); - -} -} -} -#endif +/* Pokemon LA Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_PokemonSprites_H +#define PokemonAutomation_PokemonLA_PokemonSprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +// All pokemon sprites in LA +const SpriteDatabase& ALL_POKEMON_SPRITES(); + +// All icons of pokemon sprites in MMO +const SpriteDatabase& ALL_MMO_SPRITES(); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.cpp b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.cpp index 09222366a3..5d8457d0f3 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.cpp +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.cpp @@ -1,66 +1,66 @@ -/* Pokemon LA Weather And Time Icons - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Globals.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonLA_WeatherAndTimeIcons.h" - -// #include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLA{ - -std::array BUILD_WEATHER_ICONS(){ - const std::string image_folder_path = RESOURCE_PATH() + "PokemonLA/Weather/"; - - std::array ret; - for(size_t i = 0; i < NUM_WEATHER; i++){ - const auto& weather_name = WEATHER_NAMES[i]; - const std::string image_path = image_folder_path + weather_name + ".png"; - // std::cout << image_path << std::endl; - // Trim the image to remove 0-alpha boundaries. - ImageRGB32 image(ImageMatch::trim_image_alpha(ImageRGB32(image_path)).copy()); - ret[i] = std::move(image); - } - - return ret; -} - -const std::array& ALL_WEATHER_ICONS(){ - const static auto icons = BUILD_WEATHER_ICONS(); - return icons; -} - - -std::array BUILD_TIME_OF_DAY_ICONS(){ - const std::string image_folder_path = RESOURCE_PATH() + "PokemonLA/Time/"; - - std::array ret; - for(size_t i = 0; i < NUM_TIMES_OF_DAY; i++){ - // +1 here to skip TimeOfDay::NONE - const auto& time_name = TIME_OF_DAY_NAMES[i+1]; - const std::string image_path = image_folder_path + time_name + ".png"; - // std::cout << image_path << std::endl; - // Trim the image to remove 0-alpha boundaries. - ImageRGB32 image(ImageMatch::trim_image_alpha(ImageRGB32(image_path)).copy()); - ret[i] = std::move(image); - } - - return ret; -} - - -const std::array& ALL_TIME_OF_DAY_ICONS(){ - const static auto icons = BUILD_TIME_OF_DAY_ICONS(); - return icons; -} - - -} -} -} +/* Pokemon LA Weather And Time Icons + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Globals.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonLA_WeatherAndTimeIcons.h" + +// #include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLA{ + +std::array BUILD_WEATHER_ICONS(){ + const std::string image_folder_path = RESOURCE_PATH() + "PokemonLA/Weather/"; + + std::array ret; + for(size_t i = 0; i < NUM_WEATHER; i++){ + const auto& weather_name = WEATHER_NAMES[i]; + const std::string image_path = image_folder_path + weather_name + ".png"; + // std::cout << image_path << std::endl; + // Trim the image to remove 0-alpha boundaries. + ImageRGB32 image(ImageMatch::trim_image_alpha(ImageRGB32(image_path)).copy()); + ret[i] = std::move(image); + } + + return ret; +} + +const std::array& ALL_WEATHER_ICONS(){ + const static auto icons = BUILD_WEATHER_ICONS(); + return icons; +} + + +std::array BUILD_TIME_OF_DAY_ICONS(){ + const std::string image_folder_path = RESOURCE_PATH() + "PokemonLA/Time/"; + + std::array ret; + for(size_t i = 0; i < NUM_TIMES_OF_DAY; i++){ + // +1 here to skip TimeOfDay::NONE + const auto& time_name = TIME_OF_DAY_NAMES[i+1]; + const std::string image_path = image_folder_path + time_name + ".png"; + // std::cout << image_path << std::endl; + // Trim the image to remove 0-alpha boundaries. + ImageRGB32 image(ImageMatch::trim_image_alpha(ImageRGB32(image_path)).copy()); + ret[i] = std::move(image); + } + + return ret; +} + + +const std::array& ALL_TIME_OF_DAY_ICONS(){ + const static auto icons = BUILD_TIME_OF_DAY_ICONS(); + return icons; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h index 7ef27876bb..d23aacbc03 100644 --- a/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h +++ b/SerialPrograms/Source/PokemonLA/Resources/PokemonLA_WeatherAndTimeIcons.h @@ -1,32 +1,32 @@ -/* Pokemon LA Weather And Time Icons - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLA_WeatherAndTimeIcons_H -#define PokemonAutomation_PokemonLA_WeatherAndTimeIcons_H - -#include -#include -#include "PokemonLA/PokemonLA_WeatherAndTime.h" - - -namespace PokemonAutomation{ - -class ImageRGB32; - -namespace NintendoSwitch{ -namespace PokemonLA{ - -// weather icon images, in the order listed in PokemonLA_WeatherAndTime.h:Weather -const std::array& ALL_WEATHER_ICONS(); - -// time of day icon images, in the order listed in PokemonLA_WeatherAndTime.h:TimeOfDay -// Note: TimeOfDay::None is not in the array. -const std::array& ALL_TIME_OF_DAY_ICONS(); - -} -} -} -#endif +/* Pokemon LA Weather And Time Icons + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLA_WeatherAndTimeIcons_H +#define PokemonAutomation_PokemonLA_WeatherAndTimeIcons_H + +#include +#include +#include "PokemonLA/PokemonLA_WeatherAndTime.h" + + +namespace PokemonAutomation{ + +class ImageRGB32; + +namespace NintendoSwitch{ +namespace PokemonLA{ + +// weather icon images, in the order listed in PokemonLA_WeatherAndTime.h:Weather +const std::array& ALL_WEATHER_ICONS(); + +// time of day icon images, in the order listed in PokemonLA_WeatherAndTime.h:TimeOfDay +// Note: TimeOfDay::None is not in the array. +const std::array& ALL_TIME_OF_DAY_ICONS(); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp index 559db5f332..d42da73c9f 100644 --- a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.cpp @@ -1,71 +1,71 @@ -/* Auto Host Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "PokemonLGPE_DateSpam.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -void roll_date_forward_1(JoyconContext& context){ - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 128, 0, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 128, 0, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); -} - -void roll_date_backward_N(JoyconContext& context, uint8_t skips){ - if (skips == 0){ - return; - } - - Milliseconds tv = context->timing_variation(); - Milliseconds unit = 24ms + tv; - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - - for (uint8_t c = 0; c < skips - 1; c++){ - pbf_move_joystick(context, 128, 255, 2*unit, unit); - } - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - - for (uint8_t c = 0; c < skips - 1; c++){ - pbf_move_joystick(context, 128, 255, 2*unit, unit); - } - - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_move_joystick(context, 255, 128, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); - pbf_press_button(context, BUTTON_A, 2*unit, unit); -} - - - - - -} - -} -} - +/* Auto Host Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "PokemonLGPE_DateSpam.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +void roll_date_forward_1(JoyconContext& context){ + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 128, 0, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 128, 0, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); +} + +void roll_date_backward_N(JoyconContext& context, uint8_t skips){ + if (skips == 0){ + return; + } + + Milliseconds tv = context->timing_variation(); + Milliseconds unit = 24ms + tv; + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + + for (uint8_t c = 0; c < skips - 1; c++){ + pbf_move_joystick(context, 128, 255, 2*unit, unit); + } + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + + for (uint8_t c = 0; c < skips - 1; c++){ + pbf_move_joystick(context, 128, 255, 2*unit, unit); + } + + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_move_joystick(context, 255, 128, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); + pbf_press_button(context, BUTTON_A, 2*unit, unit); +} + + + + + +} + +} +} + diff --git a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h index d9534ef6bc..f692cdf07f 100644 --- a/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h +++ b/SerialPrograms/Source/PokemonLGPE/Commands/PokemonLGPE_DateSpam.h @@ -1,24 +1,24 @@ -/* Date Spamming Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_Commands_DateSpam_H -#define PokemonAutomation_PokemonLGPE_Commands_DateSpam_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -void roll_date_forward_1 (JoyconContext& context); -void roll_date_backward_N (JoyconContext& context, uint8_t skips); - -} - -} -} -#endif +/* Date Spamming Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_Commands_DateSpam_H +#define PokemonAutomation_PokemonLGPE_Commands_DateSpam_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +void roll_date_forward_1 (JoyconContext& context); +void roll_date_backward_N (JoyconContext& context, uint8_t skips); + +} + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp index d890c4ac94..62beae17e4 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.cpp @@ -1,69 +1,69 @@ -/* Battle Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "PokemonLGPE_BattleArrowDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -const ImageMatch::ExactImageMatcher& BATTLE_ARROW(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonLGPE/BattleArrow.png"); - return matcher; -} - -BattleArrowDetector::BattleArrowDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} -void BattleArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool BattleArrowDetector::detect(const ImageViewRGB32& screen){ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, m_box); - - const ImageMatch::ExactImageMatcher& matcher = BATTLE_ARROW(); - - auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - - //static int c = 0; - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 1.0 || aspect_ratio > 1.3){ - continue; - } - ImageViewRGB32 cropped = extract_box_reference(region, object); - //cropped.save("test-object-" + std::to_string(c++) + ".png"); - double rmsd = matcher.rmsd(cropped); - //cout << rmsd << endl; - if (rmsd < 116){ - return true; - } - } - - return false; -} - - - -} -} -} +/* Battle Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "PokemonLGPE_BattleArrowDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +const ImageMatch::ExactImageMatcher& BATTLE_ARROW(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonLGPE/BattleArrow.png"); + return matcher; +} + +BattleArrowDetector::BattleArrowDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} +void BattleArrowDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool BattleArrowDetector::detect(const ImageViewRGB32& screen){ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, m_box); + + const ImageMatch::ExactImageMatcher& matcher = BATTLE_ARROW(); + + auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + + //static int c = 0; + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 1.0 || aspect_ratio > 1.3){ + continue; + } + ImageViewRGB32 cropped = extract_box_reference(region, object); + //cropped.save("test-object-" + std::to_string(c++) + ".png"); + double rmsd = matcher.rmsd(cropped); + //cout << rmsd << endl; + if (rmsd < 116){ + return true; + } + } + + return false; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h index c4debd4002..f977aff304 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h @@ -1,53 +1,53 @@ -/* Battle Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_BattleArrowDetector_H -#define PokemonAutomation_PokemonLGPE_BattleArrowDetector_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class BattleArrowDetector : public StaticScreenDetector{ -public: - /* - |Fight|Pokemon|Bag|Run| for wild battle - |---|Fight|Pokemon|Bag| for trainer battle - (align right) - Don't know what changes for a double battle. - */ - //Arrow bounces back and forth. - BattleArrowDetector(Color color, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -protected: - Color m_color; - ImageFloatBox m_box; -}; -class BattleArrowWatcher : public DetectorToFinder{ -public: - BattleArrowWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.546, 0.863, 0.045, 0.068}) - : DetectorToFinder("BattleArrowWatcher", std::chrono::milliseconds(100), color, box) - {} -}; - - - -} -} -} - -#endif +/* Battle Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_BattleArrowDetector_H +#define PokemonAutomation_PokemonLGPE_BattleArrowDetector_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class BattleArrowDetector : public StaticScreenDetector{ +public: + /* + |Fight|Pokemon|Bag|Run| for wild battle + |---|Fight|Pokemon|Bag| for trainer battle + (align right) + Don't know what changes for a double battle. + */ + //Arrow bounces back and forth. + BattleArrowDetector(Color color, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +protected: + Color m_color; + ImageFloatBox m_box; +}; +class BattleArrowWatcher : public DetectorToFinder{ +public: + BattleArrowWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.546, 0.863, 0.045, 0.068}) + : DetectorToFinder("BattleArrowWatcher", std::chrono::milliseconds(100), color, box) + {} +}; + + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp index 92704d1e67..374a6c2bb4 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.cpp @@ -1,49 +1,49 @@ -/* Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonLGPE_ShinySymbolDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -ShinySymbolDetector::ShinySymbolDetector(Color color) - : m_box_star(0.666, 0.779, 0.028, 0.044) -{} -void ShinySymbolDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box_star); -} -bool ShinySymbolDetector::read(Logger& logger, const ImageViewRGB32& frame){ - /* - Shiny (charizard): - Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [159, 123, 125] avg sum 408 ratio [0.391, 0.301, 0.308] stddev [74.898, 54.696, 53.354] sum 182.948 crop size (54, 48) - - Not shiny (chansey): - Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [82, 113, 100] avg sum 295 ratio [0.276, 0.384, 0.340] stddev [15.477, 2.178, 2.648] sum 20.303 crop size (54, 48) - - Only had the two to test with for now. - */ - - const auto stats = image_stats(extract_box_reference(frame, m_box_star)); - return stats.stddev.sum() > 100; -} - - -} -} -} - +/* Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonLGPE_ShinySymbolDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +ShinySymbolDetector::ShinySymbolDetector(Color color) + : m_box_star(0.666, 0.779, 0.028, 0.044) +{} +void ShinySymbolDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box_star); +} +bool ShinySymbolDetector::read(Logger& logger, const ImageViewRGB32& frame){ + /* + Shiny (charizard): + Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [159, 123, 125] avg sum 408 ratio [0.391, 0.301, 0.308] stddev [74.898, 54.696, 53.354] sum 182.948 crop size (54, 48) + + Not shiny (chansey): + Add infer box: (0.6660, 0.7790, 0.0280, 0.0440), RGB avg [82, 113, 100] avg sum 295 ratio [0.276, 0.384, 0.340] stddev [15.477, 2.178, 2.648] sum 20.303 crop size (54, 48) + + Only had the two to test with for now. + */ + + const auto stats = image_stats(extract_box_reference(frame, m_box_star)); + return stats.stddev.sum() > 100; +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h index 2fa78427b3..73b565b7d6 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h +++ b/SerialPrograms/Source/PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h @@ -1,35 +1,35 @@ -/* Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H -#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -//Check for the red shiny star on a Pokemon's summary from the Party/Box menu. -//This does not work for the summary that appears after a catch. -class ShinySymbolDetector{ -public: - ShinySymbolDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const; - bool read(Logger& logger, const ImageViewRGB32& frame); - -private: - ImageFloatBox m_box_star; -}; - - - -} -} -} -#endif +/* Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H +#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +//Check for the red shiny star on a Pokemon's summary from the Party/Box menu. +//This does not work for the summary that appears after a catch. +class ShinySymbolDetector{ +public: + ShinySymbolDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const; + bool read(Logger& logger, const ImageViewRGB32& frame); + +private: + ImageFloatBox m_box_star; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp index 4b24aef49d..f1d9cdb9c7 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.cpp @@ -1,47 +1,47 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonLGPE/PokemonLGPE_Settings.h" -#include "PokemonLGPE_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} - - -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; -} - -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonLGPE/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonLGPE/PokemonLGPE_Settings.h" +#include "PokemonLGPE_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} + + +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; +} + +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonLGPE/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h index 46b3ef0d93..cd76bcd059 100644 --- a/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h @@ -1,36 +1,36 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_ShinySoundDetector_H -#define PokemonAutomation_PokemonLGPE_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_ShinySoundDetector_H +#define PokemonAutomation_PokemonLGPE_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp index e51bbcf0d7..e0d229ac79 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.cpp @@ -1,56 +1,56 @@ -/* Pokemon LGPE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLGPE_Panels.h" -#include "PokemonLGPE_Settings.h" - -#include "Programs/Farming/PokemonLGPE_DailyItemFarmer.h" -#include "Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h" -#include "Programs/ShinyHunting/PokemonLGPE_FossilRevival.h" -#include "Programs/ShinyHunting/PokemonLGPE_GiftReset.h" -#include "Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h" - -#include "Programs/TestPrograms/PokemonLGPE_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Let's Go Pikachu and Eevee") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} -} +/* Pokemon LGPE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLGPE_Panels.h" +#include "PokemonLGPE_Settings.h" + +#include "Programs/Farming/PokemonLGPE_DailyItemFarmer.h" +#include "Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h" +#include "Programs/ShinyHunting/PokemonLGPE_FossilRevival.h" +#include "Programs/ShinyHunting/PokemonLGPE_GiftReset.h" +#include "Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h" + +#include "Programs/TestPrograms/PokemonLGPE_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Let's Go Pikachu and Eevee") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h index 4c5d0b925e..8d2eb1108f 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Panels.h @@ -1,28 +1,28 @@ -/* Pokemon LGPE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_Panels_H -#define PokemonAutomation_PokemonLGPE_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon LGPE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_Panels_H +#define PokemonAutomation_PokemonLGPE_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp index a977100c30..db04e2536b 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.cpp @@ -1,114 +1,114 @@ -/* Pokemon Let's Go Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonLGPE_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_general("General Settings:") - , m_menu_navigation("Menu Navigation Timings:") - , GAME_TO_HOME_DELAY0( - "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , m_start_game_timings("Start Game Timings:") - , START_GAME_MASH0( - "1. Start Game Mash:
Mash A for this long to start the game.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , START_GAME_WAIT1( - "2. Start Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) - , ENTER_GAME_MASH0( - "3. Enter Game Mash:
Mash A for this long to enter the game.", - LockMode::LOCK_WHILE_RUNNING, - "5 s" - ) - , ENTER_GAME_WAIT0( - "4. Enter Game Wait:
Wait this long for the opening animations to finish.", - LockMode::LOCK_WHILE_RUNNING, - "15 s" - ) - , m_shiny_audio_settings("Shiny Audio Settings:") - , SHINY_SOUND_THRESHOLD( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.95, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 1000, 0, 48000 - ) -{ - PA_ADD_STATIC(m_general); - - PA_ADD_STATIC(m_menu_navigation); - PA_ADD_OPTION(GAME_TO_HOME_DELAY0); - - PA_ADD_STATIC(m_start_game_timings); - PA_ADD_OPTION(START_GAME_MASH0); - PA_ADD_OPTION(START_GAME_WAIT1); - PA_ADD_OPTION(ENTER_GAME_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - - PA_ADD_STATIC(m_shiny_audio_settings); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonLGPE:GlobalSettings", - STRING_POKEMON + " LGPE", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/PokemonSettings.md", - "Global " + STRING_POKEMON + " Let's Go Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon Let's Go Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonLGPE_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_general("General Settings:") + , m_menu_navigation("Menu Navigation Timings:") + , GAME_TO_HOME_DELAY0( + "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , m_start_game_timings("Start Game Timings:") + , START_GAME_MASH0( + "1. Start Game Mash:
Mash A for this long to start the game.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , START_GAME_WAIT1( + "2. Start Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) + , ENTER_GAME_MASH0( + "3. Enter Game Mash:
Mash A for this long to enter the game.", + LockMode::LOCK_WHILE_RUNNING, + "5 s" + ) + , ENTER_GAME_WAIT0( + "4. Enter Game Wait:
Wait this long for the opening animations to finish.", + LockMode::LOCK_WHILE_RUNNING, + "15 s" + ) + , m_shiny_audio_settings("Shiny Audio Settings:") + , SHINY_SOUND_THRESHOLD( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.95, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 1000, 0, 48000 + ) +{ + PA_ADD_STATIC(m_general); + + PA_ADD_STATIC(m_menu_navigation); + PA_ADD_OPTION(GAME_TO_HOME_DELAY0); + + PA_ADD_STATIC(m_start_game_timings); + PA_ADD_OPTION(START_GAME_MASH0); + PA_ADD_OPTION(START_GAME_WAIT1); + PA_ADD_OPTION(ENTER_GAME_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + + PA_ADD_STATIC(m_shiny_audio_settings); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonLGPE:GlobalSettings", + STRING_POKEMON + " LGPE", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/PokemonSettings.md", + "Global " + STRING_POKEMON + " Let's Go Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h index 4380f298d6..cbaa1135e6 100644 --- a/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h +++ b/SerialPrograms/Source/PokemonLGPE/PokemonLGPE_Settings.h @@ -1,61 +1,61 @@ -/* Pokemon Let's Go Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_Settings_H -#define PokemonAutomation_PokemonLGPE_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_general; - - SectionDividerOption m_menu_navigation; - MillisecondsOption GAME_TO_HOME_DELAY0; - - SectionDividerOption m_start_game_timings; - MillisecondsOption START_GAME_MASH0; - MillisecondsOption START_GAME_WAIT1; - MillisecondsOption ENTER_GAME_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_shiny_audio_settings; - FloatingPointOption SHINY_SOUND_THRESHOLD; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon Let's Go Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_Settings_H +#define PokemonAutomation_PokemonLGPE_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_general; + + SectionDividerOption m_menu_navigation; + MillisecondsOption GAME_TO_HOME_DELAY0; + + SectionDividerOption m_start_game_timings; + MillisecondsOption START_GAME_MASH0; + MillisecondsOption START_GAME_WAIT1; + MillisecondsOption ENTER_GAME_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_shiny_audio_settings; + FloatingPointOption SHINY_SOUND_THRESHOLD; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp index 560f74789f..409a990fdc 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.cpp @@ -1,237 +1,237 @@ -/* LGPE Daily Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Commands/PokemonLGPE_DateSpam.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonLGPE_DailyItemFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -DailyItemFarmer_Descriptor::DailyItemFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:DailyItemFarmer", - Pokemon::STRING_POKEMON + " LGPE", "Daily Item Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/DailyItemFarmer.md", - "Farm daily item respawns (ex. fossils) by date-skipping.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct DailyItemFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : skips(m_stats["Skips"]) - { - m_display_order.emplace_back("Skips"); - } - std::atomic& skips; -}; -std::unique_ptr DailyItemFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -DailyItemFarmer::DailyItemFarmer() - : ATTEMPTS( - "Number of attempts:", - LockMode::LOCK_WHILE_RUNNING, - 30, 1 - ) - , LINK_CODE( - "Link Code:
The link code used when matching for a trade/battle. This only needs to be changed when running multiple LGPE date-skip programs at the same time.", - { //Combinations of 3 different symbols is possible but 10 choices seems like enough. - {LinkCode::Pikachu, "pikachu", "Pikachu"}, - {LinkCode::Eevee, "eevee", "Eevee"}, - {LinkCode::Bulbasaur, "bulbasaur", "Bulbasaur"}, - {LinkCode::Charmander, "charmander", "Charmander"}, - {LinkCode::Squirtle, "squirtle", "Squirtle"}, - {LinkCode::Pidgey, "pidgey", "Pidgey"}, - {LinkCode::Caterpie, "caterpie", "Caterpie"}, - {LinkCode::Rattata, "rattata", "Rattata"}, - {LinkCode::Jigglypuff, "jigglypuff", "Jigglypuff"}, - {LinkCode::Diglett, "diglett", "Diglett"}, - }, - LockMode::LOCK_WHILE_RUNNING, - LinkCode::Pikachu - ) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(ATTEMPTS); - PA_ADD_OPTION(LINK_CODE); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void DailyItemFarmer::start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - env.log("Starting local trade."); - //Open Menu -> Communication -> Nearby player -> Local Trade - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_wait(context, 1000ms); //Black screen - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - - //Enter link code - switch(LINK_CODE) { - case LinkCode::Pikachu: - break; - case LinkCode::Eevee: - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - break; - case LinkCode::Bulbasaur: - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - break; - case LinkCode::Charmander: - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Squirtle: - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Pidgey: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - break; - case LinkCode::Caterpie: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 255, 128, 100ms, 100ms); - break; - case LinkCode::Rattata: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Jigglypuff: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - case LinkCode::Diglett: - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - break; - default: - env.log("Invalid link code selection. Defaulting to Pikachu."); - break; - } - //Select symbol three times, then enter link search - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - pbf_wait(context, 1000ms); //let search start - context.wait_for_all_requests(); -} - -void DailyItemFarmer::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - DailyItemFarmer_Descriptor::Stats& stats = env.current_stats(); - - /* Stand in front of the fossil spawn near Mewtwo. - * Use a repel to keep wild encounters away. - * Start program in-game. - * 100% daily spawn. Only works near Mewtwo. - * Other cave item spawns are tied to steps taken. - * Should work for other hidden daily items, game corner, mt moon moonstones, etc. - */ - - uint8_t year = MAX_YEAR; - - //Roll the date back before doing anything else. - start_local_trade(env, context); - pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); - home_to_date_time(context, true); - env.log("Rolling date back."); - roll_date_backward_N(context, MAX_YEAR); - year = 0; - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - pbf_mash_button(context, BUTTON_B, 5000ms); - context.wait_for_all_requests(); - - env.log("Starting pickup loop."); - for (uint32_t count = 0; count < ATTEMPTS; count++) { - env.log("Pick up item."); - pbf_mash_button(context, BUTTON_A, 4000ms); - context.wait_for_all_requests(); - - start_local_trade(env, context); - - //Dateskip - pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); - home_to_date_time(context, true); - if (year >= MAX_YEAR){ - env.log("Rolling date back."); - roll_date_backward_N(context, MAX_YEAR); - year = 0; - }else{ - env.log("Rolling date forward."); - roll_date_forward_1(context); - year++; - } - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - //Re-enter game and close out link menu - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - pbf_mash_button(context, BUTTON_B, 5000ms); - context.wait_for_all_requests(); - - stats.skips++; - env.update_stats(); - } - - if (FIX_TIME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, 1000ms); - home_to_date_time(context, false); - pbf_press_button(context, BUTTON_A, 50ms, 500ms); - pbf_press_button(context, BUTTON_A, 50ms, 500ms); - pbf_wait(context, 100ms); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Daily Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Commands/PokemonLGPE_DateSpam.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonLGPE_DailyItemFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +DailyItemFarmer_Descriptor::DailyItemFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:DailyItemFarmer", + Pokemon::STRING_POKEMON + " LGPE", "Daily Item Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/DailyItemFarmer.md", + "Farm daily item respawns (ex. fossils) by date-skipping.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct DailyItemFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : skips(m_stats["Skips"]) + { + m_display_order.emplace_back("Skips"); + } + std::atomic& skips; +}; +std::unique_ptr DailyItemFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +DailyItemFarmer::DailyItemFarmer() + : ATTEMPTS( + "Number of attempts:", + LockMode::LOCK_WHILE_RUNNING, + 30, 1 + ) + , LINK_CODE( + "Link Code:
The link code used when matching for a trade/battle. This only needs to be changed when running multiple LGPE date-skip programs at the same time.", + { //Combinations of 3 different symbols is possible but 10 choices seems like enough. + {LinkCode::Pikachu, "pikachu", "Pikachu"}, + {LinkCode::Eevee, "eevee", "Eevee"}, + {LinkCode::Bulbasaur, "bulbasaur", "Bulbasaur"}, + {LinkCode::Charmander, "charmander", "Charmander"}, + {LinkCode::Squirtle, "squirtle", "Squirtle"}, + {LinkCode::Pidgey, "pidgey", "Pidgey"}, + {LinkCode::Caterpie, "caterpie", "Caterpie"}, + {LinkCode::Rattata, "rattata", "Rattata"}, + {LinkCode::Jigglypuff, "jigglypuff", "Jigglypuff"}, + {LinkCode::Diglett, "diglett", "Diglett"}, + }, + LockMode::LOCK_WHILE_RUNNING, + LinkCode::Pikachu + ) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(ATTEMPTS); + PA_ADD_OPTION(LINK_CODE); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void DailyItemFarmer::start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + env.log("Starting local trade."); + //Open Menu -> Communication -> Nearby player -> Local Trade + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_wait(context, 1000ms); //Black screen + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + + //Enter link code + switch(LINK_CODE) { + case LinkCode::Pikachu: + break; + case LinkCode::Eevee: + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + break; + case LinkCode::Bulbasaur: + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + break; + case LinkCode::Charmander: + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Squirtle: + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Pidgey: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + break; + case LinkCode::Caterpie: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 255, 128, 100ms, 100ms); + break; + case LinkCode::Rattata: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Jigglypuff: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + case LinkCode::Diglett: + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + break; + default: + env.log("Invalid link code selection. Defaulting to Pikachu."); + break; + } + //Select symbol three times, then enter link search + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + pbf_wait(context, 1000ms); //let search start + context.wait_for_all_requests(); +} + +void DailyItemFarmer::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + DailyItemFarmer_Descriptor::Stats& stats = env.current_stats(); + + /* Stand in front of the fossil spawn near Mewtwo. + * Use a repel to keep wild encounters away. + * Start program in-game. + * 100% daily spawn. Only works near Mewtwo. + * Other cave item spawns are tied to steps taken. + * Should work for other hidden daily items, game corner, mt moon moonstones, etc. + */ + + uint8_t year = MAX_YEAR; + + //Roll the date back before doing anything else. + start_local_trade(env, context); + pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); + home_to_date_time(context, true); + env.log("Rolling date back."); + roll_date_backward_N(context, MAX_YEAR); + year = 0; + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + + env.log("Starting pickup loop."); + for (uint32_t count = 0; count < ATTEMPTS; count++) { + env.log("Pick up item."); + pbf_mash_button(context, BUTTON_A, 4000ms); + context.wait_for_all_requests(); + + start_local_trade(env, context); + + //Dateskip + pbf_press_button(context, BUTTON_HOME, 160ms, 1000ms); + home_to_date_time(context, true); + if (year >= MAX_YEAR){ + env.log("Rolling date back."); + roll_date_backward_N(context, MAX_YEAR); + year = 0; + }else{ + env.log("Rolling date forward."); + roll_date_forward_1(context); + year++; + } + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + //Re-enter game and close out link menu + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + pbf_mash_button(context, BUTTON_B, 5000ms); + context.wait_for_all_requests(); + + stats.skips++; + env.update_stats(); + } + + if (FIX_TIME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, 1000ms); + home_to_date_time(context, false); + pbf_press_button(context, BUTTON_A, 50ms, 500ms); + pbf_press_button(context, BUTTON_A, 50ms, 500ms); + pbf_wait(context, 100ms); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h index e03be6751d..c16c64db1c 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/Farming/PokemonLGPE_DailyItemFarmer.h @@ -1,67 +1,67 @@ -/* LGPE Daily Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_DailyItemFarmer_H -#define PokemonAutomation_PokemonLGPE_DailyItemFarmer_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class DailyItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DailyItemFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class DailyItemFarmer : public SingleSwitchProgramInstance{ -public: - DailyItemFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - void start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - SimpleIntegerOption ATTEMPTS; - - enum class LinkCode{ - Pikachu, - Eevee, - Bulbasaur, - Charmander, - Squirtle, - Pidgey, - Caterpie, - Rattata, - Jigglypuff, - Diglett, - }; - EnumDropdownOption LINK_CODE; - - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Daily Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_DailyItemFarmer_H +#define PokemonAutomation_PokemonLGPE_DailyItemFarmer_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class DailyItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DailyItemFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class DailyItemFarmer : public SingleSwitchProgramInstance{ +public: + DailyItemFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + void start_local_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + SimpleIntegerOption ATTEMPTS; + + enum class LinkCode{ + Pikachu, + Eevee, + Bulbasaur, + Charmander, + Squirtle, + Pidgey, + Caterpie, + Rattata, + Jigglypuff, + Diglett, + }; + EnumDropdownOption LINK_CODE; + + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp index dadf6f694b..29d1631af7 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.cpp @@ -1,134 +1,134 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" -#include "PokemonLGPE/PokemonLGPE_Settings.h" -#include "PokemonLGPE_GameEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -bool reset_game_to_gamemenu( - ConsoleHandle& console, JoyconContext& context -){ - close_game(console, context); - start_game_from_home_with_inference( - console, - context, - 0, 0, - GameSettings::instance().START_GAME_MASH0 - ); - - // Now the game has opened: - return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT1); -} - -bool gamemenu_to_ingame( - VideoStream& stream, JoyconContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -){ - //Includes choosing the controller. - //Controllers are disconnected? on selection screen so make sure to mash. - stream.log("Mashing A to enter game and select controller..."); - pbf_mash_button(context, BUTTON_A, mash_duration); - context.wait_for_all_requests(); - - //White screen, Pikachu/Eevee running across the screen. Mash will not speed it up. - //Mash A at then end to enter continue screen - BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); - stream.log("Waiting to enter game..."); - int ret = run_until( - stream, context, - [&enter_game_timeout](JoyconContext& context){ - pbf_wait(context, enter_game_timeout); - pbf_press_button(context, BUTTON_A, 400ms, 10ms); - pbf_wait(context, 5000ms); - }, - {detector} - ); - context.wait_for_all_requests(); - if (ret == 0){ - stream.log("At continue screen."); - }else{ - stream.log("Timed out waiting to enter game and select continue.", COLOR_RED); - return false; - } - pbf_wait(context, 1000ms); - context.wait_for_all_requests(); - - //Continue your adventure. - BlackScreenOverWatcher detector2(COLOR_YELLOW, {0.2, 0.2, 0.6, 0.6}); - int ret2 = run_until( - stream, context, - [](JoyconContext& context){ - pbf_press_button(context, BUTTON_A, 400ms, 10ms); - pbf_wait(context, 5000ms); - }, - {detector2} - ); - context.wait_for_all_requests(); - if (ret2 == 0){ - stream.log("Entered game!"); - return true; - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } -} - -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, JoyconContext& context, - Milliseconds post_wait_time -){ - if (!(context.controller().controller_type() == ControllerType::NintendoSwitch_RightJoycon)) { - console.log("Right Joycon required!", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "reset_game_from_home(): Right Joycon required.", - console - ); - } - bool ok = true; - ok &= reset_game_to_gamemenu(console, context); - ok &= gamemenu_to_ingame( - console, context, - GameSettings::instance().ENTER_GAME_MASH0, - GameSettings::instance().ENTER_GAME_WAIT0 - ); - if (!ok){ - dump_image(console.logger(), env.program_info(), console.video(), "StartGame"); - } - console.log("Entered game! Waiting out grace period."); - pbf_wait(context, post_wait_time); - context.wait_for_all_requests(); - return ok; -} - - - - - -} -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "Controllers/ControllerCapability.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Inference/NintendoSwitch_DetectHome.h" +#include "PokemonLGPE/PokemonLGPE_Settings.h" +#include "PokemonLGPE_GameEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +bool reset_game_to_gamemenu( + ConsoleHandle& console, JoyconContext& context +){ + close_game(console, context); + start_game_from_home_with_inference( + console, + context, + 0, 0, + GameSettings::instance().START_GAME_MASH0 + ); + + // Now the game has opened: + return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT1); +} + +bool gamemenu_to_ingame( + VideoStream& stream, JoyconContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +){ + //Includes choosing the controller. + //Controllers are disconnected? on selection screen so make sure to mash. + stream.log("Mashing A to enter game and select controller..."); + pbf_mash_button(context, BUTTON_A, mash_duration); + context.wait_for_all_requests(); + + //White screen, Pikachu/Eevee running across the screen. Mash will not speed it up. + //Mash A at then end to enter continue screen + BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); + stream.log("Waiting to enter game..."); + int ret = run_until( + stream, context, + [&enter_game_timeout](JoyconContext& context){ + pbf_wait(context, enter_game_timeout); + pbf_press_button(context, BUTTON_A, 400ms, 10ms); + pbf_wait(context, 5000ms); + }, + {detector} + ); + context.wait_for_all_requests(); + if (ret == 0){ + stream.log("At continue screen."); + }else{ + stream.log("Timed out waiting to enter game and select continue.", COLOR_RED); + return false; + } + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + + //Continue your adventure. + BlackScreenOverWatcher detector2(COLOR_YELLOW, {0.2, 0.2, 0.6, 0.6}); + int ret2 = run_until( + stream, context, + [](JoyconContext& context){ + pbf_press_button(context, BUTTON_A, 400ms, 10ms); + pbf_wait(context, 5000ms); + }, + {detector2} + ); + context.wait_for_all_requests(); + if (ret2 == 0){ + stream.log("Entered game!"); + return true; + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } +} + +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, JoyconContext& context, + Milliseconds post_wait_time +){ + if (!(context.controller().controller_type() == ControllerType::NintendoSwitch_RightJoycon)) { + console.log("Right Joycon required!", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "reset_game_from_home(): Right Joycon required.", + console + ); + } + bool ok = true; + ok &= reset_game_to_gamemenu(console, context); + ok &= gamemenu_to_ingame( + console, context, + GameSettings::instance().ENTER_GAME_MASH0, + GameSettings::instance().ENTER_GAME_WAIT0 + ); + if (!ok){ + dump_image(console.logger(), env.program_info(), console.video(), "StartGame"); + } + console.log("Entered game! Waiting out grace period."); + pbf_wait(context, post_wait_time); + context.wait_for_all_requests(); + return ok; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h index d2114a8b51..d139cb2965 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/PokemonLGPE_GameEntry.h @@ -1,49 +1,49 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_GameEntry_H -#define PokemonAutomation_PokemonLGPE_GameEntry_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - - -// From Switch Home menu, reset game and wait until the game menu screen (where -// "Press A" is displayed to enter the game) is shown. -bool reset_game_to_gamemenu( - ConsoleHandle& console, JoyconContext& context -); - -// From the game menu screen (where "Press A" is displayed to enter the game), -// mash A to enter the game and wait until the black screen is gone. -bool gamemenu_to_ingame( - VideoStream& stream, JoyconContext& context, - Milliseconds mash_duration, Milliseconds enter_game_timeout -); - -// From Switch Home menu, start game and wait until the player character appears in game. -// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. -bool reset_game_from_home( - ProgramEnvironment& env, - ConsoleHandle& console, JoyconContext& context, - Milliseconds post_wait_time = std::chrono::milliseconds(125) -); - - - - -} -} -} -#endif +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_GameEntry_H +#define PokemonAutomation_PokemonLGPE_GameEntry_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + + +// From Switch Home menu, reset game and wait until the game menu screen (where +// "Press A" is displayed to enter the game) is shown. +bool reset_game_to_gamemenu( + ConsoleHandle& console, JoyconContext& context +); + +// From the game menu screen (where "Press A" is displayed to enter the game), +// mash A to enter the game and wait until the black screen is gone. +bool gamemenu_to_ingame( + VideoStream& stream, JoyconContext& context, + Milliseconds mash_duration, Milliseconds enter_game_timeout +); + +// From Switch Home menu, start game and wait until the player character appears in game. +// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. +bool reset_game_from_home( + ProgramEnvironment& env, + ConsoleHandle& console, JoyconContext& context, + Milliseconds post_wait_time = std::chrono::milliseconds(125) +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp index e7cdb9d606..7b7456f0bb 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.cpp @@ -1,303 +1,303 @@ -/* LGPE Alolan Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_AlolanTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -AlolanTrade_Descriptor::AlolanTrade_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:AlolanTrade", - Pokemon::STRING_POKEMON + " LGPE", "Alolan Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/AlolanTrade.md", - "Shiny hunt Alolan forms by trading in-game.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct AlolanTrade_Descriptor::Stats : public StatsTracker{ - Stats() - : trades(m_stats["Trades"]) - , resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Trades"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& trades; - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr AlolanTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -AlolanTrade::AlolanTrade() - : NUM_TRADES( - "Number of Pokemon to trade:", - LockMode::LOCK_WHILE_RUNNING, - 30, 1 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(NUM_TRADES); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void AlolanTrade::run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - AlolanTrade_Descriptor::Stats& stats = env.current_stats(); - //Talk to NPC, say Yes, select Pokemon from box. - BlackScreenOverWatcher trade_started(COLOR_RED); - int ret = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_A, 15000ms); - }, - {trade_started} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to start trade.", COLOR_RED); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to start trade.", - env.console - ); - } - else { - env.log("Trade started."); - } - - //Wait for trade to complete. - BlackScreenOverWatcher trade_completed(COLOR_YELLOW); - int ret2 = wait_until( - env.console, context, - std::chrono::seconds(120), - {trade_completed} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - stats.errors++; - env.update_stats(); - env.log("Did not detect end of trade.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Did not detect end of trade.", - env.console - ); - } - else { - env.log("Trade completed."); - } - - //Summary will appear the first time you trade in a session(?) - //Sometimes it appears anyway, don't know what determines it - //Exit menu and dialog. - pbf_mash_button(context, BUTTON_B, 3000ms); - context.wait_for_all_requests(); -} - -void AlolanTrade::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - AlolanTrade_Descriptor::Stats& stats = env.current_stats(); - - /* - WARNING: JOYCON TEST PROGRAM. Not well tested. Bare minimum in general. - - Right joycon required for home button (this means no on-switch screenshots). - Also don't remap any of the buttons in the switch button mapping settings. - - Preconditions: - DO NOT have any Pokemon you want to keep in your boxes. Move them out to Home first. - Favoriting a Pokemon does not prevent it from being traded. - ?This must not be your first time doing the trade? (I've done all the trades, so I can't check first time trade behavior.) - - Setup: - Catch the Kanto variant of the target. Put this number in NUM_TRADES. - Stand in front of trade NPC. - Save the game. - Start the program in-game. - - Future additions?: - skip favorited pokemon - they have a symbol to indicate fav status (imo still risky to do, just move them out) - detect when all pokemon traded - trading screen will open but text will appear in the center - "you don't have any pokemon your trading partner wants" - detect dialog box, detect yes/no confirm box - actual enter game and start screen detectors - menu detectors, etc. - get rid of all this blindly mashing A in general...so need everything really. - */ - - bool shiny_found = false; - while (!shiny_found) { - //Run trades - for (uint16_t i = 0; i < NUM_TRADES; i++) { - env.log("Running trade."); - run_trade(env, context); - - stats.trades++; - env.update_stats(); - } - - env.log("Done trading. Checking boxes."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Done trading. Checking boxes." - ); - - //To check pokemon in menu boxes - //Open menu - always defaults to center (Party) - //Menu: - // --Play with Partner--(centered) - //Pokedex - Bag - Party - Communicate - Save (these all have a colored line under when selected + an arrow to indicate) - //(Press Y for options) - - //Make sure any extra dialog is closed - pbf_mash_button(context, BUTTON_B, 3000ms); - context.wait_for_all_requests(); - - //Wait a bit. - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - - //Open menu, open party, open boxes - env.log("Opening boxes."); - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_press_button(context, BUTTON_A, 200ms, 1500ms); - pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); - context.wait_for_all_requests(); - - //Sort by order caught - env.log("Sorting by order caught."); - pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - context.wait_for_all_requests(); - - //Press left to go to last (most recent) Pokemon - env.log("Opening summary of most recent Pokemon."); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - context.wait_for_all_requests(); - - //View summary - it takes a moment to load - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - - //Now check for shinies. Check everything that was traded. - env.log("Checking received Pokemon."); - for (uint16_t i = 0; i < NUM_TRADES; i++) { - VideoSnapshot screen = env.console.video().snapshot(); - ShinySymbolDetector shiny_checker(COLOR_YELLOW); - bool check = shiny_checker.read(env.console.logger(), screen); - - if (check) { - env.log("Shiny detected!"); - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); - shiny_found = true; - - //Back out to menu and favorite the shiny. - env.log("Favoriting shiny."); - pbf_press_button(context, BUTTON_B, 200ms, 5000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 200ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_B, 200ms, 800ms); - - //Go into summary again - env.log("Navigating back into summary."); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - } - else { - env.log("Not shiny."); - } - - //Move left, check next. - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_press_button(context, BUTTON_X, 0ms, 1000ms); - context.wait_for_all_requests(); - } - - if (!shiny_found) { - env.log("Out of Pokemon to trade and no shiny found. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Out of Pokemon to trade and no shiny found. Resetting game." - ); - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - env.update_stats(); - } - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Alolan Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_AlolanTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +AlolanTrade_Descriptor::AlolanTrade_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:AlolanTrade", + Pokemon::STRING_POKEMON + " LGPE", "Alolan Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/AlolanTrade.md", + "Shiny hunt Alolan forms by trading in-game.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct AlolanTrade_Descriptor::Stats : public StatsTracker{ + Stats() + : trades(m_stats["Trades"]) + , resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Trades"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& trades; + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr AlolanTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +AlolanTrade::AlolanTrade() + : NUM_TRADES( + "Number of Pokemon to trade:", + LockMode::LOCK_WHILE_RUNNING, + 30, 1 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(NUM_TRADES); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void AlolanTrade::run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + AlolanTrade_Descriptor::Stats& stats = env.current_stats(); + //Talk to NPC, say Yes, select Pokemon from box. + BlackScreenOverWatcher trade_started(COLOR_RED); + int ret = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_A, 15000ms); + }, + {trade_started} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to start trade.", COLOR_RED); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to start trade.", + env.console + ); + } + else { + env.log("Trade started."); + } + + //Wait for trade to complete. + BlackScreenOverWatcher trade_completed(COLOR_YELLOW); + int ret2 = wait_until( + env.console, context, + std::chrono::seconds(120), + {trade_completed} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + stats.errors++; + env.update_stats(); + env.log("Did not detect end of trade.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Did not detect end of trade.", + env.console + ); + } + else { + env.log("Trade completed."); + } + + //Summary will appear the first time you trade in a session(?) + //Sometimes it appears anyway, don't know what determines it + //Exit menu and dialog. + pbf_mash_button(context, BUTTON_B, 3000ms); + context.wait_for_all_requests(); +} + +void AlolanTrade::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + AlolanTrade_Descriptor::Stats& stats = env.current_stats(); + + /* + WARNING: JOYCON TEST PROGRAM. Not well tested. Bare minimum in general. + + Right joycon required for home button (this means no on-switch screenshots). + Also don't remap any of the buttons in the switch button mapping settings. + + Preconditions: + DO NOT have any Pokemon you want to keep in your boxes. Move them out to Home first. + Favoriting a Pokemon does not prevent it from being traded. + ?This must not be your first time doing the trade? (I've done all the trades, so I can't check first time trade behavior.) + + Setup: + Catch the Kanto variant of the target. Put this number in NUM_TRADES. + Stand in front of trade NPC. + Save the game. + Start the program in-game. + + Future additions?: + skip favorited pokemon - they have a symbol to indicate fav status (imo still risky to do, just move them out) + detect when all pokemon traded - trading screen will open but text will appear in the center + "you don't have any pokemon your trading partner wants" + detect dialog box, detect yes/no confirm box + actual enter game and start screen detectors + menu detectors, etc. + get rid of all this blindly mashing A in general...so need everything really. + */ + + bool shiny_found = false; + while (!shiny_found) { + //Run trades + for (uint16_t i = 0; i < NUM_TRADES; i++) { + env.log("Running trade."); + run_trade(env, context); + + stats.trades++; + env.update_stats(); + } + + env.log("Done trading. Checking boxes."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Done trading. Checking boxes." + ); + + //To check pokemon in menu boxes + //Open menu - always defaults to center (Party) + //Menu: + // --Play with Partner--(centered) + //Pokedex - Bag - Party - Communicate - Save (these all have a colored line under when selected + an arrow to indicate) + //(Press Y for options) + + //Make sure any extra dialog is closed + pbf_mash_button(context, BUTTON_B, 3000ms); + context.wait_for_all_requests(); + + //Wait a bit. + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + + //Open menu, open party, open boxes + env.log("Opening boxes."); + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_press_button(context, BUTTON_A, 200ms, 1500ms); + pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); + context.wait_for_all_requests(); + + //Sort by order caught + env.log("Sorting by order caught."); + pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + context.wait_for_all_requests(); + + //Press left to go to last (most recent) Pokemon + env.log("Opening summary of most recent Pokemon."); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + context.wait_for_all_requests(); + + //View summary - it takes a moment to load + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + + //Now check for shinies. Check everything that was traded. + env.log("Checking received Pokemon."); + for (uint16_t i = 0; i < NUM_TRADES; i++) { + VideoSnapshot screen = env.console.video().snapshot(); + ShinySymbolDetector shiny_checker(COLOR_YELLOW); + bool check = shiny_checker.read(env.console.logger(), screen); + + if (check) { + env.log("Shiny detected!"); + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); + shiny_found = true; + + //Back out to menu and favorite the shiny. + env.log("Favoriting shiny."); + pbf_press_button(context, BUTTON_B, 200ms, 5000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 200ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_B, 200ms, 800ms); + + //Go into summary again + env.log("Navigating back into summary."); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + } + else { + env.log("Not shiny."); + } + + //Move left, check next. + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_press_button(context, BUTTON_X, 0ms, 1000ms); + context.wait_for_all_requests(); + } + + if (!shiny_found) { + env.log("Out of Pokemon to trade and no shiny found. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Out of Pokemon to trade and no shiny found. Resetting game." + ); + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + env.update_stats(); + } + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h index 9b24061d3e..acebc8c3f4 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_AlolanTrade.h @@ -1,53 +1,53 @@ -/* LGPE Alolan Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_AlolanTrade_H -#define PokemonAutomation_PokemonLGPE_AlolanTrade_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class AlolanTrade_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AlolanTrade_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class AlolanTrade : public SingleSwitchProgramInstance{ -public: - AlolanTrade(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - void run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - SimpleIntegerOption NUM_TRADES; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Alolan Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_AlolanTrade_H +#define PokemonAutomation_PokemonLGPE_AlolanTrade_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class AlolanTrade_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AlolanTrade_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class AlolanTrade : public SingleSwitchProgramInstance{ +public: + AlolanTrade(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + void run_trade(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + SimpleIntegerOption NUM_TRADES; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp index 0251229dc2..6769d4daa2 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.cpp @@ -1,310 +1,310 @@ -/* LGPE Fossil Revival - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_FossilRevival.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -FossilRevival_Descriptor::FossilRevival_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:FossilRevival", - Pokemon::STRING_POKEMON + " LGPE", "Fossil Revival", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/FossilRevival.md", - "Shiny hunt fossil Pokemon by reviving and resetting.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct FossilRevival_Descriptor::Stats : public StatsTracker{ - Stats() - : revives(m_stats["Revives"]) - , resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Revives"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& revives; - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr FossilRevival_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -FossilRevival::FossilRevival() - : SLOT( - "Fossil slot:
Position of the fossil in the selection dialog.", - { - {0, "slot0", "Slot 1"}, - {1, "slot1", "Slot 2"}, - {2, "slot2", "Slot 3"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - ,NUM_REVIVALS( - "Number of fossils to revive:", - LockMode::LOCK_WHILE_RUNNING, - 30, 1 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(SLOT); - PA_ADD_OPTION(NUM_REVIVALS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void FossilRevival::run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - FossilRevival_Descriptor::Stats& stats = env.current_stats(); - //Press A to get to selection - env.log("Starting dialog."); - pbf_press_button(context, BUTTON_A, 100ms, 800ms); - pbf_wait(context, 1000ms); //Wait for scientist to turn and face player - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - pbf_press_button(context, BUTTON_A, 100ms, 500ms); - context.wait_for_all_requests(); - - pbf_wait(context, 500ms); - context.wait_for_all_requests(); - - //Select fossil slot - env.log("Selecting fossil."); - for (uint16_t c = 0; c < (uint16_t)SLOT.current_value(); c++){ - pbf_move_joystick(context, 128, 255, 100ms, 200ms); - } - context.wait_for_all_requests(); - - //Mash A until revival over - BlackScreenOverWatcher revival_over(COLOR_RED); - int ret = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_A, 15000ms); - }, - {revival_over} - ); - context.wait_for_all_requests(); - if (ret != 0){ - stats.errors++; - env.update_stats(); - env.log("Failed to revive fossil.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to revive fossil.", - env.console - ); - } - else { - env.log("Fossil revived."); - } - - //Now mash B until next black screen (end of summary/tucked pokemon away) - BlackScreenOverWatcher summary_over(COLOR_YELLOW); - int ret2 = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_B, 15000ms); - }, - {summary_over} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - stats.errors++; - env.update_stats(); - env.log("Did not detect summary over.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Did not detect summary over.", - env.console - ); - } - else { - env.log("Summary closed/Pokemon tucked away in box/team."); - } - - //Close out come back soon text. - pbf_mash_button(context, BUTTON_B, 1000ms); - context.wait_for_all_requests(); -} - -void FossilRevival::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - FossilRevival_Descriptor::Stats& stats = env.current_stats(); - - /* - Settings: - Text speed fast - - is first time dialog different? clear it out first. - selection dialog still appears if only one fossil type - - Setup: - Stand in front of the scientist in cinnebar. - Save the game. - Start the program in-game. - */ - - bool shiny_found = false; - while (!shiny_found) { - //Run revives - for (uint16_t i = 0; i < NUM_REVIVALS; i++) { - env.log("Running trade."); - run_revives(env, context); - - stats.revives++; - env.update_stats(); - } - - env.log("Done reviving. Checking boxes."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Done reviving. Checking boxes." - ); - - //Wait a bit. - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - - //Open menu, open party, open boxes - env.log("Opening boxes."); - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_press_button(context, BUTTON_A, 200ms, 1500ms); - pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); - context.wait_for_all_requests(); - - //Sort by order caught - env.log("Sorting by order caught."); - pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - context.wait_for_all_requests(); - - //Press left to go to last (most recent) Pokemon - env.log("Opening summary of most recent Pokemon."); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - context.wait_for_all_requests(); - - //View summary - it takes a moment to load - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - - //Now check for shinies. Check everything that was traded. - env.log("Checking received Pokemon."); - for (uint16_t i = 0; i < NUM_REVIVALS; i++) { - VideoSnapshot screen = env.console.video().snapshot(); - ShinySymbolDetector shiny_checker(COLOR_YELLOW); - bool check = shiny_checker.read(env.console.logger(), screen); - - if (check) { - env.log("Shiny detected!"); - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); - shiny_found = true; - - //Back out to menu and favorite the shiny. - env.log("Favoriting shiny."); - pbf_press_button(context, BUTTON_B, 200ms, 5000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 100ms); - pbf_move_joystick(context, 128, 0, 100ms, 200ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_B, 200ms, 800ms); - - //Go into summary again - env.log("Navigating back into summary."); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - } - else { - env.log("Not shiny."); - } - - //Move left, check next. - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - pbf_press_button(context, BUTTON_X, 0ms, 1000ms); - context.wait_for_all_requests(); - } - - if (!shiny_found) { - env.log("Out of Pokemon to check and no shiny found. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Out of Pokemon to check and no shiny found. Resetting game." - ); - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - env.update_stats(); - } - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Fossil Revival + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_FossilRevival.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +FossilRevival_Descriptor::FossilRevival_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:FossilRevival", + Pokemon::STRING_POKEMON + " LGPE", "Fossil Revival", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/FossilRevival.md", + "Shiny hunt fossil Pokemon by reviving and resetting.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct FossilRevival_Descriptor::Stats : public StatsTracker{ + Stats() + : revives(m_stats["Revives"]) + , resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Revives"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& revives; + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr FossilRevival_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +FossilRevival::FossilRevival() + : SLOT( + "Fossil slot:
Position of the fossil in the selection dialog.", + { + {0, "slot0", "Slot 1"}, + {1, "slot1", "Slot 2"}, + {2, "slot2", "Slot 3"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + ,NUM_REVIVALS( + "Number of fossils to revive:", + LockMode::LOCK_WHILE_RUNNING, + 30, 1 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(SLOT); + PA_ADD_OPTION(NUM_REVIVALS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void FossilRevival::run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + FossilRevival_Descriptor::Stats& stats = env.current_stats(); + //Press A to get to selection + env.log("Starting dialog."); + pbf_press_button(context, BUTTON_A, 100ms, 800ms); + pbf_wait(context, 1000ms); //Wait for scientist to turn and face player + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + pbf_press_button(context, BUTTON_A, 100ms, 500ms); + context.wait_for_all_requests(); + + pbf_wait(context, 500ms); + context.wait_for_all_requests(); + + //Select fossil slot + env.log("Selecting fossil."); + for (uint16_t c = 0; c < (uint16_t)SLOT.current_value(); c++){ + pbf_move_joystick(context, 128, 255, 100ms, 200ms); + } + context.wait_for_all_requests(); + + //Mash A until revival over + BlackScreenOverWatcher revival_over(COLOR_RED); + int ret = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_A, 15000ms); + }, + {revival_over} + ); + context.wait_for_all_requests(); + if (ret != 0){ + stats.errors++; + env.update_stats(); + env.log("Failed to revive fossil.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to revive fossil.", + env.console + ); + } + else { + env.log("Fossil revived."); + } + + //Now mash B until next black screen (end of summary/tucked pokemon away) + BlackScreenOverWatcher summary_over(COLOR_YELLOW); + int ret2 = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_B, 15000ms); + }, + {summary_over} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + stats.errors++; + env.update_stats(); + env.log("Did not detect summary over.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Did not detect summary over.", + env.console + ); + } + else { + env.log("Summary closed/Pokemon tucked away in box/team."); + } + + //Close out come back soon text. + pbf_mash_button(context, BUTTON_B, 1000ms); + context.wait_for_all_requests(); +} + +void FossilRevival::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + FossilRevival_Descriptor::Stats& stats = env.current_stats(); + + /* + Settings: + Text speed fast + + is first time dialog different? clear it out first. + selection dialog still appears if only one fossil type + + Setup: + Stand in front of the scientist in cinnebar. + Save the game. + Start the program in-game. + */ + + bool shiny_found = false; + while (!shiny_found) { + //Run revives + for (uint16_t i = 0; i < NUM_REVIVALS; i++) { + env.log("Running trade."); + run_revives(env, context); + + stats.revives++; + env.update_stats(); + } + + env.log("Done reviving. Checking boxes."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Done reviving. Checking boxes." + ); + + //Wait a bit. + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + + //Open menu, open party, open boxes + env.log("Opening boxes."); + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_press_button(context, BUTTON_A, 200ms, 1500ms); + pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); + context.wait_for_all_requests(); + + //Sort by order caught + env.log("Sorting by order caught."); + pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + context.wait_for_all_requests(); + + //Press left to go to last (most recent) Pokemon + env.log("Opening summary of most recent Pokemon."); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + context.wait_for_all_requests(); + + //View summary - it takes a moment to load + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + + //Now check for shinies. Check everything that was traded. + env.log("Checking received Pokemon."); + for (uint16_t i = 0; i < NUM_REVIVALS; i++) { + VideoSnapshot screen = env.console.video().snapshot(); + ShinySymbolDetector shiny_checker(COLOR_YELLOW); + bool check = shiny_checker.read(env.console.logger(), screen); + + if (check) { + env.log("Shiny detected!"); + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); + shiny_found = true; + + //Back out to menu and favorite the shiny. + env.log("Favoriting shiny."); + pbf_press_button(context, BUTTON_B, 200ms, 5000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 100ms); + pbf_move_joystick(context, 128, 0, 100ms, 200ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_B, 200ms, 800ms); + + //Go into summary again + env.log("Navigating back into summary."); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + } + else { + env.log("Not shiny."); + } + + //Move left, check next. + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + pbf_press_button(context, BUTTON_X, 0ms, 1000ms); + context.wait_for_all_requests(); + } + + if (!shiny_found) { + env.log("Out of Pokemon to check and no shiny found. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Out of Pokemon to check and no shiny found. Resetting game." + ); + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + env.update_stats(); + } + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h index 8e9d6570cd..101ce30935 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_FossilRevival.h @@ -1,55 +1,55 @@ -/* LGPE Fossil Revival - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_FossilRevival_H -#define PokemonAutomation_PokemonLGPE_FossilRevival_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class FossilRevival_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FossilRevival_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class FossilRevival : public SingleSwitchProgramInstance{ -public: - FossilRevival(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - void run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - IntegerEnumDropdownOption SLOT; - SimpleIntegerOption NUM_REVIVALS; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Fossil Revival + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_FossilRevival_H +#define PokemonAutomation_PokemonLGPE_FossilRevival_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class FossilRevival_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FossilRevival_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class FossilRevival : public SingleSwitchProgramInstance{ +public: + FossilRevival(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + void run_revives(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + IntegerEnumDropdownOption SLOT; + SimpleIntegerOption NUM_REVIVALS; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp index 581754e8a9..8f91fe1a26 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.cpp @@ -1,205 +1,205 @@ -/* LGPE Gift Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_GiftReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -GiftReset_Descriptor::GiftReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:GiftReset", - Pokemon::STRING_POKEMON + " LGPE", "Gift Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/GiftReset.md", - "Shiny hunt gift Pokemon by resetting the game.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct GiftReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr GiftReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -GiftReset::GiftReset() - : EXTRA_DIALOG( - "Persian/Arcanine:
Check this if the gift Pokemon is Persian or Arcanine.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(EXTRA_DIALOG); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void GiftReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - GiftReset_Descriptor::Stats& stats = env.current_stats(); - - /* - Setup: - Stand in front of trade NPC. - Start the program in-game. - - Must have 500yen for magikarp. - Gift Pokemon: https://www.serebii.net/letsgopikachueevee/gift.shtml - Tested with Magikarp on a new save. Should work with most of the others. - Can always add a dropdown with target if it doesn't. - Fossils will be handled in a different program. - */ - - bool shiny_found = false; - while (!shiny_found) { - //Purchase Magikarp - BlackScreenOverWatcher gift_obtained(COLOR_RED); - int ret = run_until( - env.console, context, - [](JoyconContext& context){ - pbf_mash_button(context, BUTTON_A, 20000ms); - }, - {gift_obtained} - ); - context.wait_for_all_requests(); - if (ret != 0){ - stats.errors++; - env.update_stats(); - env.log("Failed to receive gift Pokemon.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to receive gift Pokemon.", - env.console - ); - } - else { - env.log("Received gift Pokemon."); - } - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Received gift Pokemon." - ); - - if (EXTRA_DIALOG){ - env.log("Persian/Arcanine selected. Mashing B to exit dialog."); - pbf_mash_button(context, BUTTON_B, 4100ms); - context.wait_for_all_requests(); - } - - //Wait a bit. - pbf_wait(context, 2500ms); - context.wait_for_all_requests(); - - //Open menu, open party, open boxes - env.log("Opening boxes."); - pbf_press_button(context, BUTTON_X, 200ms, 500ms); - pbf_press_button(context, BUTTON_A, 200ms, 1500ms); - pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); - context.wait_for_all_requests(); - - //Sort by order caught - env.log("Sorting by order caught."); - pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - context.wait_for_all_requests(); - - //Press left to go to last (most recent) Pokemon - env.log("Opening summary of most recent Pokemon."); - pbf_move_joystick(context, 0, 128, 100ms, 100ms); - context.wait_for_all_requests(); - - //View summary - it takes a moment to load - env.log("Viewing summary."); - pbf_press_button(context, BUTTON_A, 200ms, 1000ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_move_joystick(context, 128, 255, 100ms, 100ms); - pbf_press_button(context, BUTTON_A, 200ms, 100ms); - context.wait_for_all_requests(); - - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); - - //Now check for shinies. Check everything that was traded. - VideoSnapshot screen = env.console.video().snapshot(); - ShinySymbolDetector shiny_checker(COLOR_YELLOW); - bool check = shiny_checker.read(env.console.logger(), screen); - - if (check) { - env.log("Shiny detected!"); - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); - shiny_found = true; - } - else { - env.log("Not shiny. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Not shiny. Resetting game." - ); - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - env.update_stats(); - } - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Gift Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/PokemonLGPE_ShinySymbolDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_GiftReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +GiftReset_Descriptor::GiftReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:GiftReset", + Pokemon::STRING_POKEMON + " LGPE", "Gift Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/GiftReset.md", + "Shiny hunt gift Pokemon by resetting the game.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct GiftReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr GiftReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +GiftReset::GiftReset() + : EXTRA_DIALOG( + "Persian/Arcanine:
Check this if the gift Pokemon is Persian or Arcanine.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(EXTRA_DIALOG); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void GiftReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + GiftReset_Descriptor::Stats& stats = env.current_stats(); + + /* + Setup: + Stand in front of trade NPC. + Start the program in-game. + + Must have 500yen for magikarp. + Gift Pokemon: https://www.serebii.net/letsgopikachueevee/gift.shtml + Tested with Magikarp on a new save. Should work with most of the others. + Can always add a dropdown with target if it doesn't. + Fossils will be handled in a different program. + */ + + bool shiny_found = false; + while (!shiny_found) { + //Purchase Magikarp + BlackScreenOverWatcher gift_obtained(COLOR_RED); + int ret = run_until( + env.console, context, + [](JoyconContext& context){ + pbf_mash_button(context, BUTTON_A, 20000ms); + }, + {gift_obtained} + ); + context.wait_for_all_requests(); + if (ret != 0){ + stats.errors++; + env.update_stats(); + env.log("Failed to receive gift Pokemon.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to receive gift Pokemon.", + env.console + ); + } + else { + env.log("Received gift Pokemon."); + } + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Received gift Pokemon." + ); + + if (EXTRA_DIALOG){ + env.log("Persian/Arcanine selected. Mashing B to exit dialog."); + pbf_mash_button(context, BUTTON_B, 4100ms); + context.wait_for_all_requests(); + } + + //Wait a bit. + pbf_wait(context, 2500ms); + context.wait_for_all_requests(); + + //Open menu, open party, open boxes + env.log("Opening boxes."); + pbf_press_button(context, BUTTON_X, 200ms, 500ms); + pbf_press_button(context, BUTTON_A, 200ms, 1500ms); + pbf_press_button(context, BUTTON_Y, 200ms, 2000ms); + context.wait_for_all_requests(); + + //Sort by order caught + env.log("Sorting by order caught."); + pbf_press_button(context, BUTTON_Y, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + context.wait_for_all_requests(); + + //Press left to go to last (most recent) Pokemon + env.log("Opening summary of most recent Pokemon."); + pbf_move_joystick(context, 0, 128, 100ms, 100ms); + context.wait_for_all_requests(); + + //View summary - it takes a moment to load + env.log("Viewing summary."); + pbf_press_button(context, BUTTON_A, 200ms, 1000ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_move_joystick(context, 128, 255, 100ms, 100ms); + pbf_press_button(context, BUTTON_A, 200ms, 100ms); + context.wait_for_all_requests(); + + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); + + //Now check for shinies. Check everything that was traded. + VideoSnapshot screen = env.console.video().snapshot(); + ShinySymbolDetector shiny_checker(COLOR_YELLOW); + bool check = shiny_checker.read(env.console.logger(), screen); + + if (check) { + env.log("Shiny detected!"); + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", screen, true); + shiny_found = true; + } + else { + env.log("Not shiny. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Not shiny. Resetting game." + ); + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + env.update_stats(); + } + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h index fa86dae3a9..c78b69b2f7 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_GiftReset.h @@ -1,50 +1,50 @@ -/* LGPE Gift Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_GiftReset_H -#define PokemonAutomation_PokemonLGPE_GiftReset_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class GiftReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GiftReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class GiftReset : public SingleSwitchProgramInstance{ -public: - GiftReset(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - BooleanCheckBoxOption EXTRA_DIALOG; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Gift Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_GiftReset_H +#define PokemonAutomation_PokemonLGPE_GiftReset_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class GiftReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GiftReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class GiftReset : public SingleSwitchProgramInstance{ +public: + GiftReset(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + BooleanCheckBoxOption EXTRA_DIALOG; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp index 9bb6624721..8e95208d84 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.cpp @@ -1,285 +1,285 @@ -/* LGPE Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h" -#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" -#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" -#include "PokemonLGPE_LegendaryReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -LegendaryReset_Descriptor::LegendaryReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:LegendaryReset", - Pokemon::STRING_POKEMON + " LGPE", "Legendary Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/LegendaryReset.md", - "Shiny hunt Legendary Pokemon by resetting the game.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct LegendaryReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& shinies; - std::atomic& errors; -}; -std::unique_ptr LegendaryReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -LegendaryReset::LegendaryReset() - : TARGET( - "Target:
", - { - {Target::mewtwo, "mewtwo", "Mewtwo, Articuno, Zapdos, Moltres"}, - {Target::snorlax, "snorlax", "Snorlax"}, - {Target::electrode, "electrode", "Electrode"}, - //{Target::snorlax2, "snorlax2", "Snorlax (w/Fuji)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::mewtwo - ) - , GO_HOME_WHEN_DONE(true) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -bool LegendaryReset::run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context){ - LegendaryReset_Descriptor::Stats& stats = env.current_stats(); - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(env.logger(), [&](float error_coefficient) -> bool{ - shiny_coefficient = error_coefficient; - return true; - }); - BattleArrowWatcher battle_started(COLOR_RED, {0.546, 0.863, 0.045, 0.068}); - - env.log("Starting battle."); - switch (TARGET) { - case Target::mewtwo: - pbf_mash_button(context, BUTTON_A, 3000ms); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_PLUS, 500ms, 100ms); - break; - case Target::snorlax: - pbf_mash_button(context, BUTTON_A, 5000ms); - context.wait_for_all_requests(); - pbf_mash_button(context, BUTTON_B, 10000ms); - break; - case Target::electrode: - pbf_press_button(context, BUTTON_A, 200ms, 200ms); - pbf_mash_button(context, BUTTON_B, 5000ms); - break; - } - context.wait_for_all_requests(); - - int res = run_until( - env.console, context, - [&](JoyconContext& context) { - int ret = wait_until( - env.console, context, - std::chrono::seconds(90), - {{battle_started}} - ); - if (ret == 0) { - env.log("HP boxes detected."); - } else { - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle(): Did not detect battle start.", - env.console - ); - } - context.wait_for_all_requests(); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (res == 0){ - env.log("Shiny detected!"); - return true; - } - env.log("Shiny not found."); - - return false; -} - -void LegendaryReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - assert_16_9_720p_min(env.logger(), env.console); - LegendaryReset_Descriptor::Stats& stats = env.current_stats(); - - /* - Setup: - Stand in front of encounter. (And save) - Start the program in game. - Your lead must not be shiny. - - Settings: - Text Speed fast - Skip cutscene On - Skip move animation On - - Mewtwo, Articuno, Zapdos, Moltres, Snorlax, Electrode(?) - Don't do it on the first Snorlax, otherwise have to sit through fuji tutorial - */ - - size_t consecutive_failures = 0; - - while (true) { - env.update_stats(); - - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 times in the row.", - env.console - ); - } - - try{ - bool encounter_battle = run_encounter(env, context); - if (encounter_battle) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - - env.log("No shiny found. Resetting game."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "No shiny found. Resetting game." - ); - context.wait_for_all_requests(); - consecutive_failures = 0; - }catch (OperationFailedException& e){ - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - consecutive_failures++; - } - - //Reset game - pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); - reset_game_from_home(env, env.console, context, 3000ms); - context.wait_for_all_requests(); - - stats.resets++; - } - //Shiny found, complete the battle - WallClock start = current_time(); - BattleArrowWatcher catching_started(COLOR_RED, {0.005, 0.662, 0.049, 0.069}); - int res = run_until( - env.console, context, - [&](JoyconContext& context) { - while(true){ - if (current_time() - start > std::chrono::minutes(5)){ - stats.errors++; - env.update_stats(); - env.log("Timed out during battle after 5 minutes.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle after 5 minutes.", - env.console - ); - } - BattleArrowWatcher battle_menu(COLOR_YELLOW, {0.546, 0.863, 0.045, 0.068}); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(30), - { battle_menu } - ); - switch (ret){ - case 0: - env.log("Detected battle menu. Mashing A to attack."); - pbf_mash_button(context, BUTTON_A, 3000ms); - context.wait_for_all_requests(); - break; - default: - stats.errors++; - env.update_stats(); - env.log("Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", - env.console - ); - } - } - }, - {{catching_started}} - ); - switch (res){ - case 0: - env.log("Catching menu detected."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Catching menu detected." - ); - break; - default: - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect catching menu.", - env.console - ); - break; - } - - if (GO_HOME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* LGPE Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "PokemonLGPE/Inference/Battles/PokemonLGPE_BattleArrowDetector.h" +#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" +#include "PokemonLGPE/Programs/PokemonLGPE_GameEntry.h" +#include "PokemonLGPE_LegendaryReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +LegendaryReset_Descriptor::LegendaryReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:LegendaryReset", + Pokemon::STRING_POKEMON + " LGPE", "Legendary Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonLGPE/LegendaryReset.md", + "Shiny hunt Legendary Pokemon by resetting the game.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct LegendaryReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& resets; + std::atomic& shinies; + std::atomic& errors; +}; +std::unique_ptr LegendaryReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +LegendaryReset::LegendaryReset() + : TARGET( + "Target:
", + { + {Target::mewtwo, "mewtwo", "Mewtwo, Articuno, Zapdos, Moltres"}, + {Target::snorlax, "snorlax", "Snorlax"}, + {Target::electrode, "electrode", "Electrode"}, + //{Target::snorlax2, "snorlax2", "Snorlax (w/Fuji)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::mewtwo + ) + , GO_HOME_WHEN_DONE(true) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +bool LegendaryReset::run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context){ + LegendaryReset_Descriptor::Stats& stats = env.current_stats(); + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(env.logger(), [&](float error_coefficient) -> bool{ + shiny_coefficient = error_coefficient; + return true; + }); + BattleArrowWatcher battle_started(COLOR_RED, {0.546, 0.863, 0.045, 0.068}); + + env.log("Starting battle."); + switch (TARGET) { + case Target::mewtwo: + pbf_mash_button(context, BUTTON_A, 3000ms); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_PLUS, 500ms, 100ms); + break; + case Target::snorlax: + pbf_mash_button(context, BUTTON_A, 5000ms); + context.wait_for_all_requests(); + pbf_mash_button(context, BUTTON_B, 10000ms); + break; + case Target::electrode: + pbf_press_button(context, BUTTON_A, 200ms, 200ms); + pbf_mash_button(context, BUTTON_B, 5000ms); + break; + } + context.wait_for_all_requests(); + + int res = run_until( + env.console, context, + [&](JoyconContext& context) { + int ret = wait_until( + env.console, context, + std::chrono::seconds(90), + {{battle_started}} + ); + if (ret == 0) { + env.log("HP boxes detected."); + } else { + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle(): Did not detect battle start.", + env.console + ); + } + context.wait_for_all_requests(); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (res == 0){ + env.log("Shiny detected!"); + return true; + } + env.log("Shiny not found."); + + return false; +} + +void LegendaryReset::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + assert_16_9_720p_min(env.logger(), env.console); + LegendaryReset_Descriptor::Stats& stats = env.current_stats(); + + /* + Setup: + Stand in front of encounter. (And save) + Start the program in game. + Your lead must not be shiny. + + Settings: + Text Speed fast + Skip cutscene On + Skip move animation On + + Mewtwo, Articuno, Zapdos, Moltres, Snorlax, Electrode(?) + Don't do it on the first Snorlax, otherwise have to sit through fuji tutorial + */ + + size_t consecutive_failures = 0; + + while (true) { + env.update_stats(); + + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 times in the row.", + env.console + ); + } + + try{ + bool encounter_battle = run_encounter(env, context); + if (encounter_battle) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + + env.log("No shiny found. Resetting game."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "No shiny found. Resetting game." + ); + context.wait_for_all_requests(); + consecutive_failures = 0; + }catch (OperationFailedException& e){ + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + consecutive_failures++; + } + + //Reset game + pbf_press_button(context, BUTTON_HOME, 200ms, 2000ms); + reset_game_from_home(env, env.console, context, 3000ms); + context.wait_for_all_requests(); + + stats.resets++; + } + //Shiny found, complete the battle + WallClock start = current_time(); + BattleArrowWatcher catching_started(COLOR_RED, {0.005, 0.662, 0.049, 0.069}); + int res = run_until( + env.console, context, + [&](JoyconContext& context) { + while(true){ + if (current_time() - start > std::chrono::minutes(5)){ + stats.errors++; + env.update_stats(); + env.log("Timed out during battle after 5 minutes.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle after 5 minutes.", + env.console + ); + } + BattleArrowWatcher battle_menu(COLOR_YELLOW, {0.546, 0.863, 0.045, 0.068}); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(30), + { battle_menu } + ); + switch (ret){ + case 0: + env.log("Detected battle menu. Mashing A to attack."); + pbf_mash_button(context, BUTTON_A, 3000ms); + context.wait_for_all_requests(); + break; + default: + stats.errors++; + env.update_stats(); + env.log("Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle. Stuck, crashed, or took more than 30 seconds for a turn.", + env.console + ); + } + } + }, + {{catching_started}} + ); + switch (res){ + case 0: + env.log("Catching menu detected."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Catching menu detected." + ); + break; + default: + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect catching menu.", + env.console + ); + break; + } + + if (GO_HOME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 200ms, 1000ms); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h index 511a2dca9c..69c0250b78 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/ShinyHunting/PokemonLGPE_LegendaryReset.h @@ -1,59 +1,59 @@ -/* LGPE Legendary Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLGPE_LegendaryReset_H -#define PokemonAutomation_PokemonLGPE_LegendaryReset_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - -class LegendaryReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LegendaryReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class LegendaryReset : public SingleSwitchProgramInstance{ -public: - LegendaryReset(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - bool run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context); - - enum class Target{ - mewtwo, - snorlax, - electrode, - //snorlax2, - }; - EnumDropdownOption TARGET; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif - - - +/* LGPE Legendary Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLGPE_LegendaryReset_H +#define PokemonAutomation_PokemonLGPE_LegendaryReset_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + +class LegendaryReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LegendaryReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class LegendaryReset : public SingleSwitchProgramInstance{ +public: + LegendaryReset(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + bool run_encounter(SingleSwitchProgramEnvironment& env, JoyconContext& context); + + enum class Target{ + mewtwo, + snorlax, + electrode, + //snorlax2, + }; + EnumDropdownOption TARGET; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp index d2c4e31e2c..f47c2e6c48 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.cpp @@ -1,100 +1,100 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" -#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" -#include "PokemonLGPE_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - using namespace Pokemon; - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLGPE:SoundListener", - STRING_POKEMON + " LGPE", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_RightJoycon}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::SHINY, "shiny", "Shiny Sound"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::SHINY - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - -void SoundListener::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ - JoyconContext context(scope, env.console.controller()); - - std::cout << "Running audio test program." << std::endl; - - std::shared_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::SHINY: - detector = std::make_shared(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "No such sound detector as sound type " + std::to_string((size_t)type) - ); - return; - } - - InferenceSession session( - context, env.console, - {{*detector, std::chrono::milliseconds(20)}} - ); - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_Joycon.h" +#include "PokemonLGPE/Inference/Sounds/PokemonLGPE_ShinySoundDetector.h" +#include "PokemonLGPE_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + using namespace Pokemon; + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLGPE:SoundListener", + STRING_POKEMON + " LGPE", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_RightJoycon}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::SHINY, "shiny", "Shiny Sound"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::SHINY + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + +void SoundListener::program(SingleSwitchProgramEnvironment& env, CancellableScope& scope){ + JoyconContext context(scope, env.console.controller()); + + std::cout << "Running audio test program." << std::endl; + + std::shared_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::SHINY: + detector = std::make_shared(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "No such sound detector as sound type " + std::to_string((size_t)type) + ); + return; + } + + InferenceSession session( + context, env.console, + {{*detector, std::chrono::milliseconds(20)}} + ); + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h index ac3c233ba6..109c342f3b 100644 --- a/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h +++ b/SerialPrograms/Source/PokemonLGPE/Programs/TestPrograms/PokemonLGPE_SoundListener.h @@ -1,52 +1,52 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonLGPE_SoundListener_H -#define PokemonAutomation_PokemonLGPE_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLGPE{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class SoundType{ - SHINY, - }; - - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonLGPE_SoundListener_H +#define PokemonAutomation_PokemonLGPE_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLGPE{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + virtual void program(SingleSwitchProgramEnvironment& env, CancellableScope& scope) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class SoundType{ + SHINY, + }; + + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.cpp b/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.cpp index b0cd445b5a..891adf89ae 100644 --- a/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.cpp @@ -1,168 +1,168 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonLZA_DialogDetector.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonLZA{ - - -class DialogTitleGreenLineMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - // The white background for the template file is of color range [r=240, g=255, b=230] to [255, 255, 255] - // the green line is of color range [r=180,g=200,b=75] to [190, 214, 110] - DialogTitleGreenLineMatcher() : WaterfillTemplateMatcher( - "PokemonLZA/DialogBox/DialogBoxTitleGreenLine-Template.png", Color(180,200,70), Color(200, 220, 115), 50 - ) { - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.1; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance() { - static DialogTitleGreenLineMatcher matcher; - return matcher; - } -}; - -class DialogBlackArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - // The white background for the template file is of color range [r=240, g=255, b=230] to [255, 255, 255] - // the black arrow color is about [r=36,g=38,b=51] - DialogBlackArrowMatcher() : WaterfillTemplateMatcher( - "PokemonLZA/DialogBox/DialogBoxBlackArrow-Template.png", Color(0,0,0), Color(90, 90, 90), 50 - ) { - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.85; - m_area_ratio_upper = 1.1; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance() { - static DialogBlackArrowMatcher matcher; - return matcher; - } -}; - - - -NormalDialogDetector::NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) - : VisualInferenceCallback("NormalDialogDetector") - , m_stop_on_detected(stop_on_detected) - , m_detected(false) - , m_title_green_line_box(0.224, 0.727, 0.016, 0.056) - , m_black_arrow_box (0.727, 0.868, 0.037, 0.086) -{} -void NormalDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_title_green_line_box); - items.add(COLOR_RED, m_black_arrow_box); -} -bool NormalDialogDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const double screen_rel_size = (frame.height() / 1080.0); - const double screen_rel_size_2 = screen_rel_size * screen_rel_size; - - bool found_green_title_line = false; - bool found_black_arrow = false; - - // Example green pixels from screenshots: - // 194,230,70 - // 212,235,127 - // 176,212,62 - const std::vector> green_line_filters = { - {combine_rgb(160,200,55), combine_rgb(220, 240, 130)} - }; - - const double min_green_line_size_1080P = 100.0; - const double green_line_rmsd_threshold = 50.0; - const size_t min_green_line_size = size_t(screen_rel_size_2 * min_green_line_size_1080P); - match_template_by_waterfill( - extract_box_reference(frame, m_title_green_line_box), - DialogTitleGreenLineMatcher::instance(), - green_line_filters, - {min_green_line_size, SIZE_MAX}, - green_line_rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - found_green_title_line = true; - return true; - } - ); - - // Example green pixels from screenshots: - // [37,34,6] [20,15,55] - // [39,42,58] [60,56,74] [50,49,63] - const std::vector> black_arrow_filters = { - {combine_rgb(0,0,0), combine_rgb(100, 100, 100)} - }; - - const double min_black_arrow_size_1080P = 150.0; - const double black_arrow_rmsd_threshold = 120.0; - const size_t min_black_arrow_size = size_t(screen_rel_size_2 * min_black_arrow_size_1080P); - match_template_by_waterfill( - extract_box_reference(frame, m_black_arrow_box), - DialogBlackArrowMatcher::instance(), - black_arrow_filters, - {min_black_arrow_size, SIZE_MAX}, - black_arrow_rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - found_black_arrow = true; - return true; - } - ); - - bool is_dialog_box = found_green_title_line & found_black_arrow; - - if (is_dialog_box){ - m_detected.store(is_dialog_box); - } - - return is_dialog_box & m_stop_on_detected; - - - // size_t hits = 0; - - // const ImageStats title_top = image_stats(extract_box_reference(frame, m_title_top)); - // const ImageStats title_bottom = image_stats(extract_box_reference(frame, m_title_bottom)); - // const ImageStats title_left = image_stats(extract_box_reference(frame, m_title_left)); - // const ImageStats title_right = image_stats(extract_box_reference(frame, m_title_right)); - - // ImageStats top_white = image_stats(extract_box_reference(frame, m_top_white)); - // hits += is_white(top_white, 480, 30) ? 1 : 0; - - // ImageStats bottom_white = image_stats(extract_box_reference(frame, m_bottom_white)); - // hits += is_white(bottom_white, 480, 30) ? 1 : 0; - - // ImageStats left_white = image_stats(extract_box_reference(frame, m_left_white)); - // hits += is_white(left_white, 480, 30) ? 1 : 0; - - // ImageStats right_white = image_stats(extract_box_reference(frame, m_right_white)); - // hits += is_white(right_white, 480, 30) ? 1 : 0; - - // bool detected = hits == 5; - // m_detected.store(detected, std::memory_order_release); - - // return detected && m_stop_on_detected; -} - - - - -} -} -} +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonLZA_DialogDetector.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonLZA{ + + +class DialogTitleGreenLineMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + // The white background for the template file is of color range [r=240, g=255, b=230] to [255, 255, 255] + // the green line is of color range [r=180,g=200,b=75] to [190, 214, 110] + DialogTitleGreenLineMatcher() : WaterfillTemplateMatcher( + "PokemonLZA/DialogBox/DialogBoxTitleGreenLine-Template.png", Color(180,200,70), Color(200, 220, 115), 50 + ) { + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.1; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance() { + static DialogTitleGreenLineMatcher matcher; + return matcher; + } +}; + +class DialogBlackArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + // The white background for the template file is of color range [r=240, g=255, b=230] to [255, 255, 255] + // the black arrow color is about [r=36,g=38,b=51] + DialogBlackArrowMatcher() : WaterfillTemplateMatcher( + "PokemonLZA/DialogBox/DialogBoxBlackArrow-Template.png", Color(0,0,0), Color(90, 90, 90), 50 + ) { + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.85; + m_area_ratio_upper = 1.1; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance() { + static DialogBlackArrowMatcher matcher; + return matcher; + } +}; + + + +NormalDialogDetector::NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected) + : VisualInferenceCallback("NormalDialogDetector") + , m_stop_on_detected(stop_on_detected) + , m_detected(false) + , m_title_green_line_box(0.224, 0.727, 0.016, 0.056) + , m_black_arrow_box (0.727, 0.868, 0.037, 0.086) +{} +void NormalDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_title_green_line_box); + items.add(COLOR_RED, m_black_arrow_box); +} +bool NormalDialogDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const double screen_rel_size = (frame.height() / 1080.0); + const double screen_rel_size_2 = screen_rel_size * screen_rel_size; + + bool found_green_title_line = false; + bool found_black_arrow = false; + + // Example green pixels from screenshots: + // 194,230,70 + // 212,235,127 + // 176,212,62 + const std::vector> green_line_filters = { + {combine_rgb(160,200,55), combine_rgb(220, 240, 130)} + }; + + const double min_green_line_size_1080P = 100.0; + const double green_line_rmsd_threshold = 50.0; + const size_t min_green_line_size = size_t(screen_rel_size_2 * min_green_line_size_1080P); + match_template_by_waterfill( + extract_box_reference(frame, m_title_green_line_box), + DialogTitleGreenLineMatcher::instance(), + green_line_filters, + {min_green_line_size, SIZE_MAX}, + green_line_rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + found_green_title_line = true; + return true; + } + ); + + // Example green pixels from screenshots: + // [37,34,6] [20,15,55] + // [39,42,58] [60,56,74] [50,49,63] + const std::vector> black_arrow_filters = { + {combine_rgb(0,0,0), combine_rgb(100, 100, 100)} + }; + + const double min_black_arrow_size_1080P = 150.0; + const double black_arrow_rmsd_threshold = 120.0; + const size_t min_black_arrow_size = size_t(screen_rel_size_2 * min_black_arrow_size_1080P); + match_template_by_waterfill( + extract_box_reference(frame, m_black_arrow_box), + DialogBlackArrowMatcher::instance(), + black_arrow_filters, + {min_black_arrow_size, SIZE_MAX}, + black_arrow_rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + found_black_arrow = true; + return true; + } + ); + + bool is_dialog_box = found_green_title_line & found_black_arrow; + + if (is_dialog_box){ + m_detected.store(is_dialog_box); + } + + return is_dialog_box & m_stop_on_detected; + + + // size_t hits = 0; + + // const ImageStats title_top = image_stats(extract_box_reference(frame, m_title_top)); + // const ImageStats title_bottom = image_stats(extract_box_reference(frame, m_title_bottom)); + // const ImageStats title_left = image_stats(extract_box_reference(frame, m_title_left)); + // const ImageStats title_right = image_stats(extract_box_reference(frame, m_title_right)); + + // ImageStats top_white = image_stats(extract_box_reference(frame, m_top_white)); + // hits += is_white(top_white, 480, 30) ? 1 : 0; + + // ImageStats bottom_white = image_stats(extract_box_reference(frame, m_bottom_white)); + // hits += is_white(bottom_white, 480, 30) ? 1 : 0; + + // ImageStats left_white = image_stats(extract_box_reference(frame, m_left_white)); + // hits += is_white(left_white, 480, 30) ? 1 : 0; + + // ImageStats right_white = image_stats(extract_box_reference(frame, m_right_white)); + // hits += is_white(right_white, 480, 30) ? 1 : 0; + + // bool detected = hits == 5; + // m_detected.store(detected, std::memory_order_release); + + // return detected && m_stop_on_detected; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.h b/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.h index 1683ba3a6b..f25d812707 100644 --- a/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.h +++ b/SerialPrograms/Source/PokemonLZA/Inference/PokemonLZA_DialogDetector.h @@ -1,44 +1,44 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonLZA_DialogDetector_H -#define PokemonAutomation_PokemonLZA_DialogDetector_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -class Logger; -class VideoOverlay; - -namespace NintendoSwitch{ -namespace PokemonLZA{ - -// Detect normal dialogue that is used in cases like when you talk to npcs in most situations. -class NormalDialogDetector : public VisualInferenceCallback{ -public: - NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - std::atomic m_detected; - ImageFloatBox m_title_green_line_box; - ImageFloatBox m_black_arrow_box; -}; - - -} -} -} -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonLZA_DialogDetector_H +#define PokemonAutomation_PokemonLZA_DialogDetector_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +class Logger; +class VideoOverlay; + +namespace NintendoSwitch{ +namespace PokemonLZA{ + +// Detect normal dialogue that is used in cases like when you talk to npcs in most situations. +class NormalDialogDetector : public VisualInferenceCallback{ +public: + NormalDialogDetector(Logger& logger, VideoOverlay& overlay, bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + std::atomic m_detected; + ImageFloatBox m_title_green_line_box; + ImageFloatBox m_black_arrow_box; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp index fe4113ecc7..ee21536ccd 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.cpp @@ -1,124 +1,124 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonRSE_DialogDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -/* -DialogDetector::DialogDetector(Color color) - : m_left_box(0.155, 0.727, 0.015, 0.168) - , m_right_box(0.837, 0.729, 0.008, 0.161) -{} -void DialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool DialogDetector::detect(const ImageViewRGB32& screen) const{ - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ - return true; - } - return false; -} -*/ - -BattleDialogDetector::BattleDialogDetector(Color color) - : m_left_box(0.158, 0.725, 0.011, 0.176) - , m_right_box(0.827, 0.722, 0.013, 0.178) -{} -void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ - return true; - } - return false; -} - - -BattleMenuDetector::BattleMenuDetector(Color color) - : m_left_box(0.439, 0.717, 0.021, 0.192) - , m_right_box(0.821, 0.725, 0.030, 0.181) -{} -void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.25, 0.38, 0.369 })){ - return true; - } - return false; -} - - -AdvanceBattleDialogDetector::AdvanceBattleDialogDetector(Color color) - : m_dialog_box(0.156, 0.715, 0.686, 0.193) - , m_left_box(0.156, 0.724, 0.010, 0.176) - , m_right_box(0.836, 0.717, 0.008, 0.189) -{} -void AdvanceBattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_dialog_box); - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool AdvanceBattleDialogDetector::detect(const ImageViewRGB32& screen){ - const bool replace_color_within_range = false; - - //Filter out background - ImageRGB32 filtered_region = filter_rgb32_range( - extract_box_reference(screen, m_dialog_box), - combine_rgb(185, 0, 1), combine_rgb(255, 32, 33), Color(0), replace_color_within_range - ); - ImageStats stats = image_stats(filtered_region); - - /* - filtered_region.save("./filtered_only.png"); - cout << stats.average.r << endl; - cout << stats.average.g << endl; - cout << stats.average.b << endl; - */ - - ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); - - if (is_solid(left_image, { 0.335, 0.331, 0.332 }) - && is_solid(right_image, { 0.335, 0.331, 0.332 }) - && (stats.average.r > stats.average.b + 200) - && (stats.average.r > stats.average.g + 200) - ) - { - return true; - } - return false; -} - - - -} -} -} +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonRSE_DialogDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +/* +DialogDetector::DialogDetector(Color color) + : m_left_box(0.155, 0.727, 0.015, 0.168) + , m_right_box(0.837, 0.729, 0.008, 0.161) +{} +void DialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool DialogDetector::detect(const ImageViewRGB32& screen) const{ + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ + return true; + } + return false; +} +*/ + +BattleDialogDetector::BattleDialogDetector(Color color) + : m_left_box(0.158, 0.725, 0.011, 0.176) + , m_right_box(0.827, 0.722, 0.013, 0.178) +{} +void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.335, 0.331, 0.332 })){ + return true; + } + return false; +} + + +BattleMenuDetector::BattleMenuDetector(Color color) + : m_left_box(0.439, 0.717, 0.021, 0.192) + , m_right_box(0.821, 0.725, 0.030, 0.181) +{} +void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) && is_solid(right_image, { 0.25, 0.38, 0.369 })){ + return true; + } + return false; +} + + +AdvanceBattleDialogDetector::AdvanceBattleDialogDetector(Color color) + : m_dialog_box(0.156, 0.715, 0.686, 0.193) + , m_left_box(0.156, 0.724, 0.010, 0.176) + , m_right_box(0.836, 0.717, 0.008, 0.189) +{} +void AdvanceBattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_dialog_box); + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool AdvanceBattleDialogDetector::detect(const ImageViewRGB32& screen){ + const bool replace_color_within_range = false; + + //Filter out background + ImageRGB32 filtered_region = filter_rgb32_range( + extract_box_reference(screen, m_dialog_box), + combine_rgb(185, 0, 1), combine_rgb(255, 32, 33), Color(0), replace_color_within_range + ); + ImageStats stats = image_stats(filtered_region); + + /* + filtered_region.save("./filtered_only.png"); + cout << stats.average.r << endl; + cout << stats.average.g << endl; + cout << stats.average.b << endl; + */ + + ImageViewRGB32 left_image = extract_box_reference(screen, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(screen, m_right_box); + + if (is_solid(left_image, { 0.335, 0.331, 0.332 }) + && is_solid(right_image, { 0.335, 0.331, 0.332 }) + && (stats.average.r > stats.average.b + 200) + && (stats.average.r > stats.average.g + 200) + ) + { + return true; + } + return false; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h index c059e368b8..8651e9c01d 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h +++ b/SerialPrograms/Source/PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h @@ -1,117 +1,117 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_DialogDetector_H -#define PokemonAutomation_PokemonRSE_DialogDetector_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class CancellableScope; - class VideoFeed; -namespace NintendoSwitch{ -namespace PokemonRSE{ - -/* -// TODO: Detect that a dialog box is on screen by looking for the white of the box -class DialogDetector : public StaticScreenDetector{ -public: - DialogDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) const override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class DialogWatcher : public DetectorToFinder{ -public: - DialogWatcher(Color color) - : DetectorToFinder("DialogWatcher", std::chrono::milliseconds(250), color) - {} -}; -*/ - -// Battle dialog boxes are teal -class BattleDialogDetector : public StaticScreenDetector{ -public: - BattleDialogDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class BattleDialogWatcher : public DetectorToFinder{ -public: - BattleDialogWatcher(Color color) - : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) - {} -}; - - -// Battle menu is up when it is white on the right and teal on the left -// For emerald the text is more flush to the left, so we target the right of the battle menu box -class BattleMenuDetector : public StaticScreenDetector{ -public: - BattleMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class BattleMenuWatcher : public DetectorToFinder{ -public: - BattleMenuWatcher(Color color) - : DetectorToFinder("BattleMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -// Detect the red advancement arrow by filtering for red. -// This works for now, I don't think there's colored text? -// TODO: Change this to detect that the dialog arrow is in the dialog box by filtering for the red arrow -class AdvanceBattleDialogDetector : public StaticScreenDetector{ -public: - AdvanceBattleDialogDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - ImageFloatBox m_dialog_box; - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; -class AdvanceBattleDialogWatcher : public DetectorToFinder{ -public: - AdvanceBattleDialogWatcher(Color color) - : DetectorToFinder("AdvanceBattleDialogWatcher", std::chrono::milliseconds(250), color) - {} -}; - -// Future note: when given a choice popup, there is no advance arrow. -// FRLG doesn't have an advance arrow, that's a future issue. - - -} -} -} - -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_DialogDetector_H +#define PokemonAutomation_PokemonRSE_DialogDetector_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class CancellableScope; + class VideoFeed; +namespace NintendoSwitch{ +namespace PokemonRSE{ + +/* +// TODO: Detect that a dialog box is on screen by looking for the white of the box +class DialogDetector : public StaticScreenDetector{ +public: + DialogDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) const override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class DialogWatcher : public DetectorToFinder{ +public: + DialogWatcher(Color color) + : DetectorToFinder("DialogWatcher", std::chrono::milliseconds(250), color) + {} +}; +*/ + +// Battle dialog boxes are teal +class BattleDialogDetector : public StaticScreenDetector{ +public: + BattleDialogDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class BattleDialogWatcher : public DetectorToFinder{ +public: + BattleDialogWatcher(Color color) + : DetectorToFinder("BattleDialogWatcher", std::chrono::milliseconds(250), color) + {} +}; + + +// Battle menu is up when it is white on the right and teal on the left +// For emerald the text is more flush to the left, so we target the right of the battle menu box +class BattleMenuDetector : public StaticScreenDetector{ +public: + BattleMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class BattleMenuWatcher : public DetectorToFinder{ +public: + BattleMenuWatcher(Color color) + : DetectorToFinder("BattleMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +// Detect the red advancement arrow by filtering for red. +// This works for now, I don't think there's colored text? +// TODO: Change this to detect that the dialog arrow is in the dialog box by filtering for the red arrow +class AdvanceBattleDialogDetector : public StaticScreenDetector{ +public: + AdvanceBattleDialogDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + ImageFloatBox m_dialog_box; + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; +class AdvanceBattleDialogWatcher : public DetectorToFinder{ +public: + AdvanceBattleDialogWatcher(Color color) + : DetectorToFinder("AdvanceBattleDialogWatcher", std::chrono::milliseconds(250), color) + {} +}; + +// Future note: when given a choice popup, there is no advance arrow. +// FRLG doesn't have an advance arrow, that's a future issue. + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp index 46d394d68b..bc4bd0be1a 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp +++ b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.cpp @@ -1,64 +1,64 @@ -/* Shiny Number Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonRSE_ShinyNumberDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -ShinyNumberDetector::ShinyNumberDetector(Color color) - : m_box_number(0.136, 0.156, 0.123, 0.072) -{} -void ShinyNumberDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box_number); -} -bool ShinyNumberDetector::read(Logger& logger, const ImageViewRGB32& frame){ - const bool replace_color_within_range = true; - - //Filter out background - ImageRGB32 filtered_region = filter_rgb32_range( - extract_box_reference(frame, m_box_number), - combine_rgb(138, 97, 221), combine_rgb(200, 181, 239), Color(0), replace_color_within_range - ); - ImageStats stats = image_stats(filtered_region); - - /* - filtered_region.save("./filtered_only.png"); - cout << stats.average.r << endl; - cout << stats.average.g << endl; - cout << stats.average.b << endl; - */ - - /* - Shiny: - R: 196.632, G: 196.771, B: 145.863 - Not shiny: - R: 181.862, G: 180.686, B: 193.999 - */ - - if (stats.average.b + 20 < stats.average.r){ - return true; - } - return false; -} - - -} -} -} - +/* Shiny Number Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonRSE_ShinyNumberDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +ShinyNumberDetector::ShinyNumberDetector(Color color) + : m_box_number(0.136, 0.156, 0.123, 0.072) +{} +void ShinyNumberDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box_number); +} +bool ShinyNumberDetector::read(Logger& logger, const ImageViewRGB32& frame){ + const bool replace_color_within_range = true; + + //Filter out background + ImageRGB32 filtered_region = filter_rgb32_range( + extract_box_reference(frame, m_box_number), + combine_rgb(138, 97, 221), combine_rgb(200, 181, 239), Color(0), replace_color_within_range + ); + ImageStats stats = image_stats(filtered_region); + + /* + filtered_region.save("./filtered_only.png"); + cout << stats.average.r << endl; + cout << stats.average.g << endl; + cout << stats.average.b << endl; + */ + + /* + Shiny: + R: 196.632, G: 196.771, B: 145.863 + Not shiny: + R: 181.862, G: 180.686, B: 193.999 + */ + + if (stats.average.b + 20 < stats.average.r){ + return true; + } + return false; +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h index 0328f0cf3b..52a1f6ce9c 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h +++ b/SerialPrograms/Source/PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h @@ -1,36 +1,36 @@ -/* Shiny Number Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H -#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -// In the summary screen, the dex number will be yellow if a shiny, white if not. -// Additionally, the background behind the sprite will be white if shiny, grey if not. -// Number is easier to check as the background is scan lines. -class ShinyNumberDetector{ -public: - ShinyNumberDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const; - bool read(Logger& logger, const ImageViewRGB32& frame); - -private: - ImageFloatBox m_box_number; -}; - - - -} -} -} -#endif +/* Shiny Number Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyNumberDetector_H +#define PokemonAutomation_PokemonRSE_ShinyNumberDetector_H + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +// In the summary screen, the dex number will be yellow if a shiny, white if not. +// Additionally, the background behind the sprite will be white if shiny, grey if not. +// Number is easier to check as the background is scan lines. +class ShinyNumberDetector{ +public: + ShinyNumberDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const; + bool read(Logger& logger, const ImageViewRGB32& frame); + +private: + ImageFloatBox m_box_number; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp index 6c504843a0..a0d184f89c 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.cpp @@ -1,47 +1,47 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonRSE/PokemonRSE_Settings.h" -#include "PokemonRSE_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} - - -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; -} - -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonRSE/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonRSE/PokemonRSE_Settings.h" +#include "PokemonRSE_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} + + +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD; +} + +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonRSE/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h index 662612cd58..eebdae6944 100644 --- a/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h @@ -1,36 +1,36 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinySoundDetector_H -#define PokemonAutomation_PokemonRSE_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinySoundDetector_H +#define PokemonAutomation_PokemonRSE_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp index 78ff8f6a60..3c3dd355fb 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.cpp @@ -1,165 +1,165 @@ -/* Pokemon RSE Navigation - * - * From: https://github.com/PokemonAutomation/ - * - * Soft reset, menus, etc. - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" -#include "PokemonRSE/PokemonRSE_Settings.h" -#include "PokemonRSE_Navigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - // A + B + Select + Start - pbf_press_button(context, BUTTON_B | BUTTON_Y | BUTTON_MINUS | BUTTON_PLUS, 10, 180); - - pbf_mash_button(context, BUTTON_PLUS, GameSettings::instance().START_BUTTON_MASH0); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_A, 20, 40); - - //Wait for game to load in - BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = wait_until( - stream, context, - GameSettings::instance().ENTER_GAME_WAIT0, - {detector} - ); - if (ret == 0){ - stream.log("Entered game!"); - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "soft_reset(): Timed out waiting to enter game.", - stream - ); - } - context.wait_for_all_requests(); -} - -void flee_battle(VideoStream& stream, ProControllerContext& context) { - stream.log("Navigate to Run."); - pbf_press_dpad(context, DPAD_RIGHT, 20, 20); - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - pbf_press_button(context, BUTTON_A, 20, 40); - - AdvanceBattleDialogWatcher ran_away(COLOR_YELLOW); - int ret2 = wait_until( - stream, context, - std::chrono::seconds(5), - {{ran_away}} - ); - if (ret2 == 0) { - stream.log("Running away..."); - } else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Unable to navigate to flee button.", - stream - ); - } - - pbf_press_button(context, BUTTON_A, 40, 40); - BlackScreenOverWatcher battle_over(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret3 = wait_until( - stream, context, - std::chrono::seconds(5), - {{battle_over}} - ); - if (ret3 == 0) { - stream.log("Ran from battle."); - } else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Unable to flee from battle.", - stream - ); - } -} - -bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead) { - float shiny_coefficient = 1.0; - ShinySoundDetector shiny_detector(stream.logger(), [&](float error_coefficient) -> bool{ - shiny_coefficient = error_coefficient; - return true; - }); - AdvanceBattleDialogWatcher legendary_appeared(COLOR_YELLOW); - - stream.log("Starting battle."); - pbf_mash_button(context, BUTTON_A, 540); - context.wait_for_all_requests(); - - int res = run_until( - stream, context, - [&](ProControllerContext& context) { - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {{legendary_appeared}} - ); - if (ret == 0) { - stream.log("Advance arrow detected."); - } else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Did not detect battle start.", - stream - ); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - }, - {{shiny_detector}} - ); - shiny_detector.throw_if_no_sound(); - if (res == 0){ - stream.log("Shiny detected!"); - return true; - } - stream.log("Shiny not found."); - - if (send_out_lead) { - //Send out lead, no shiny detection needed. - BattleMenuWatcher battle_menu(COLOR_RED); - stream.log("Sending out lead Pokemon."); - pbf_press_button(context, BUTTON_A, 40, 40); - - int ret = wait_until( - stream, context, - std::chrono::seconds(15), - { {battle_menu} } - ); - if (ret == 0) { - stream.log("Battle menu detecteed!"); - } - else { - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_encounter(): Did not detect battle menu.", - stream - ); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - } - - return false; -} - - -} -} -} +/* Pokemon RSE Navigation + * + * From: https://github.com/PokemonAutomation/ + * + * Soft reset, menus, etc. + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" +#include "PokemonRSE/PokemonRSE_Settings.h" +#include "PokemonRSE_Navigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + // A + B + Select + Start + pbf_press_button(context, BUTTON_B | BUTTON_Y | BUTTON_MINUS | BUTTON_PLUS, 10, 180); + + pbf_mash_button(context, BUTTON_PLUS, GameSettings::instance().START_BUTTON_MASH0); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_A, 20, 40); + + //Wait for game to load in + BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = wait_until( + stream, context, + GameSettings::instance().ENTER_GAME_WAIT0, + {detector} + ); + if (ret == 0){ + stream.log("Entered game!"); + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "soft_reset(): Timed out waiting to enter game.", + stream + ); + } + context.wait_for_all_requests(); +} + +void flee_battle(VideoStream& stream, ProControllerContext& context) { + stream.log("Navigate to Run."); + pbf_press_dpad(context, DPAD_RIGHT, 20, 20); + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + pbf_press_button(context, BUTTON_A, 20, 40); + + AdvanceBattleDialogWatcher ran_away(COLOR_YELLOW); + int ret2 = wait_until( + stream, context, + std::chrono::seconds(5), + {{ran_away}} + ); + if (ret2 == 0) { + stream.log("Running away..."); + } else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Unable to navigate to flee button.", + stream + ); + } + + pbf_press_button(context, BUTTON_A, 40, 40); + BlackScreenOverWatcher battle_over(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret3 = wait_until( + stream, context, + std::chrono::seconds(5), + {{battle_over}} + ); + if (ret3 == 0) { + stream.log("Ran from battle."); + } else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Unable to flee from battle.", + stream + ); + } +} + +bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead) { + float shiny_coefficient = 1.0; + ShinySoundDetector shiny_detector(stream.logger(), [&](float error_coefficient) -> bool{ + shiny_coefficient = error_coefficient; + return true; + }); + AdvanceBattleDialogWatcher legendary_appeared(COLOR_YELLOW); + + stream.log("Starting battle."); + pbf_mash_button(context, BUTTON_A, 540); + context.wait_for_all_requests(); + + int res = run_until( + stream, context, + [&](ProControllerContext& context) { + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {{legendary_appeared}} + ); + if (ret == 0) { + stream.log("Advance arrow detected."); + } else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Did not detect battle start.", + stream + ); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + }, + {{shiny_detector}} + ); + shiny_detector.throw_if_no_sound(); + if (res == 0){ + stream.log("Shiny detected!"); + return true; + } + stream.log("Shiny not found."); + + if (send_out_lead) { + //Send out lead, no shiny detection needed. + BattleMenuWatcher battle_menu(COLOR_RED); + stream.log("Sending out lead Pokemon."); + pbf_press_button(context, BUTTON_A, 40, 40); + + int ret = wait_until( + stream, context, + std::chrono::seconds(15), + { {battle_menu} } + ); + if (ret == 0) { + stream.log("Battle menu detecteed!"); + } + else { + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_encounter(): Did not detect battle menu.", + stream + ); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + } + + return false; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h index fd3b6d9cb4..17cc31500f 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Navigation.h @@ -1,36 +1,36 @@ -/* Pokemon RSE Navigation - * - * From: https://github.com/PokemonAutomation/ - * - * Soft reset, menus, etc. - * - */ - -#ifndef PokemonAutomation_PokemonRSE_Navigation_H -#define PokemonAutomation_PokemonRSE_Navigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonRSE{ - -// Press A+B+Select+Start at the same time to soft reset, then re-enters the game. -// For now this assumes no dry battery. -void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext &context); - -// Run from battle. Cursor must start on the FIGHT button. Assumes fleeing will always work. (Smoke Ball) -void flee_battle(VideoStream& stream, ProControllerContext& context); - -// After press A/walking up to enter a battle, run this handle the battle start and to check if opponent is shiny. -// Set send_out_lead to true and then use flee_battle() after if game is Emerald. -// For R/S, send_out_lead as false and then soft_reset() to save time. -bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead); - - -} -} -} -#endif +/* Pokemon RSE Navigation + * + * From: https://github.com/PokemonAutomation/ + * + * Soft reset, menus, etc. + * + */ + +#ifndef PokemonAutomation_PokemonRSE_Navigation_H +#define PokemonAutomation_PokemonRSE_Navigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonRSE{ + +// Press A+B+Select+Start at the same time to soft reset, then re-enters the game. +// For now this assumes no dry battery. +void soft_reset(const ProgramInfo& info, VideoStream& stream, ProControllerContext &context); + +// Run from battle. Cursor must start on the FIGHT button. Assumes fleeing will always work. (Smoke Ball) +void flee_battle(VideoStream& stream, ProControllerContext& context); + +// After press A/walking up to enter a battle, run this handle the battle start and to check if opponent is shiny. +// Set send_out_lead to true and then use flee_battle() after if game is Emerald. +// For R/S, send_out_lead as false and then soft_reset() to save time. +bool handle_encounter(VideoStream& stream, ProControllerContext& context, bool send_out_lead); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp index 8e34831079..b94624a7ac 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.cpp @@ -1,64 +1,64 @@ -/* Pokemon RSE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonRSE_Panels.h" - -#include "PokemonRSE_Settings.h" - -#include "Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h" -#include "Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h" -#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h" -#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h" - -#include "Programs/ShinyHunting/PokemonRSE_StarterReset.h" -#include "Programs/TestPrograms/PokemonRSE_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Ruby, Sapphire, and Emerald") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - //ret.emplace_back("---- General ----"); - - ret.emplace_back("---- Shiny Hunting (Ruby/Sapphire) ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting (Emerald) ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Test ----"); - ret.emplace_back(make_single_switch_program()); //outdated early test program - - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - -} -} -} +/* Pokemon RSE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonRSE_Panels.h" + +#include "PokemonRSE_Settings.h" + +#include "Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h" +#include "Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h" +#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h" +#include "Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h" + +#include "Programs/ShinyHunting/PokemonRSE_StarterReset.h" +#include "Programs/TestPrograms/PokemonRSE_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Ruby, Sapphire, and Emerald") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + //ret.emplace_back("---- General ----"); + + ret.emplace_back("---- Shiny Hunting (Ruby/Sapphire) ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting (Emerald) ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Test ----"); + ret.emplace_back(make_single_switch_program()); //outdated early test program + + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h index 6d28f52e32..f40d7774aa 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon RSE Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_Panels_H -#define PokemonAutomation_PokemonRSE_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon RSE Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_Panels_H +#define PokemonAutomation_PokemonRSE_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp index 865fb83f6e..a6a4af9370 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.cpp @@ -1,91 +1,91 @@ -/* Pokemon RSE Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" - -#include "PokemonRSE_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_soft_reset_timings("Soft Reset Timings:") - , START_BUTTON_MASH0( - "Start Button Mash:
Mash Start for this long after a soft reset to get to the main menu.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , ENTER_GAME_WAIT0( - "Enter Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , m_shiny_audio_settings("Shiny Audio Settings:") - , SHINY_SOUND_THRESHOLD( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.97, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 5000, 0, 48000 - ) -{ - PA_ADD_STATIC(m_soft_reset_timings); - PA_ADD_OPTION(START_BUTTON_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - PA_ADD_STATIC(m_shiny_audio_settings); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonRSE:GlobalSettings", - STRING_POKEMON + " RSE", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/RSESettings.md", - "Global " + STRING_POKEMON + " Ruby, Sapphire, and Emerald Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon RSE Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" + +#include "PokemonRSE_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_soft_reset_timings("Soft Reset Timings:") + , START_BUTTON_MASH0( + "Start Button Mash:
Mash Start for this long after a soft reset to get to the main menu.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , ENTER_GAME_WAIT0( + "Enter Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , m_shiny_audio_settings("Shiny Audio Settings:") + , SHINY_SOUND_THRESHOLD( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.97, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 5000, 0, 48000 + ) +{ + PA_ADD_STATIC(m_soft_reset_timings); + PA_ADD_OPTION(START_BUTTON_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + PA_ADD_STATIC(m_shiny_audio_settings); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonRSE:GlobalSettings", + STRING_POKEMON + " RSE", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/RSESettings.md", + "Global " + STRING_POKEMON + " Ruby, Sapphire, and Emerald Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h index 74d1a114f8..35d73b3422 100644 --- a/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h +++ b/SerialPrograms/Source/PokemonRSE/PokemonRSE_Settings.h @@ -1,55 +1,55 @@ -/* Pokemon RSE Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_Settings_H -#define PokemonAutomation_PokemonRSE_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_soft_reset_timings; - MillisecondsOption START_BUTTON_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_shiny_audio_settings; - FloatingPointOption SHINY_SOUND_THRESHOLD; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; - -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon RSE Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_Settings_H +#define PokemonAutomation_PokemonRSE_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_soft_reset_timings; + MillisecondsOption START_BUTTON_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_shiny_audio_settings; + FloatingPointOption SHINY_SOUND_THRESHOLD; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; + +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp index a7dfeef161..78457e2aef 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.cpp @@ -1,221 +1,221 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_AudioStarterReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -AudioStarterReset_Descriptor::AudioStarterReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:AudioStarterReset", - Pokemon::STRING_POKEMON + " RSE", "Starter Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/AudioStarterReset.md", - "Soft reset for a shiny starter. Ruby and Sapphire only.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct AudioStarterReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , poochyena(m_stats["Shiny Poochyena"]) - , shinystarter(m_stats["Shiny Starter"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shiny Poochyena"); - m_display_order.emplace_back("Shiny Starter"); - } - std::atomic& resets; - std::atomic& poochyena; - std::atomic& shinystarter; -}; -std::unique_ptr AudioStarterReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -AudioStarterReset::AudioStarterReset() - : TARGET( - "Starter:
", - { - {Target::treecko, "treecko", "Treecko"}, - {Target::torchic, "torchic", "Torchic"}, - {Target::mudkip, "mudkip", "Mudkip"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::treecko - ) - , NOTIFICATION_SHINY_POOCH( - "Shiny Poochyena", - false, false, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_SHINY_STARTER( - "Shiny Starter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY_POOCH, - &NOTIFICATION_SHINY_STARTER, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void AudioStarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AudioStarterReset_Descriptor::Stats& stats = env.current_stats(); - - /* - * Settings: Text Speed fast. - * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. - * If on a retro handheld, make sure the screen matches that of NSO+. - * - * Setup: Stand in front of the Professor's bag and save the game. - * - * Required to fight, so have to do the SR method instead of run away - * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. - * - * This also assumes no dry battery. - */ - - bool shiny_starter = false; - while (!shiny_starter) { - float shiny_coefficient = 1.0; - ShinySoundDetector pooch_detector(env.console, [&](float error_coefficient) -> bool{ - shiny_coefficient = error_coefficient; - return true; - }); - - env.log("Opening bag and selecting starter."); - pbf_press_button(context, BUTTON_A, 40, 180); - - switch (TARGET) { - case Target::treecko: - pbf_press_dpad(context, DPAD_LEFT, 40, 100); - break; - case Target::torchic: - //Default cursor position, do nothing. - break; - case Target::mudkip: - pbf_press_dpad(context, DPAD_RIGHT, 40, 100); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "AudioStarterReset: Invalid target.", - env.console - ); - break; - } - pbf_mash_button(context, BUTTON_A, 540); - context.wait_for_all_requests(); - - env.log("Starter selected. Checking for shiny Poochyena."); - AdvanceBattleDialogWatcher pooch_appeared(COLOR_YELLOW); - - int res = run_until( - env.console, context, - [&](ProControllerContext& context) { - int ret = wait_until( - env.console, context, - std::chrono::seconds(20), - {{pooch_appeared}} - ); - if (ret == 0) { - env.log("Advance arrow detected."); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - }, - {{pooch_detector}} - ); - pooch_detector.throw_if_no_sound(); - if (res == 0){ - env.log("Shiny Poochyena detected!"); - stats.poochyena++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY_POOCH, COLOR_YELLOW, "Shiny Poochyena found", {}, "", env.console.video().snapshot(), true); - } - else { - env.log("Poochyena is not shiny."); - } - context.wait_for_all_requests(); - - float shiny_coefficient2 = 1.0; - ShinySoundDetector starter_detector(env.console, [&](float error_coefficient) -> bool{ - shiny_coefficient2 = error_coefficient; - return true; - }); - - BattleMenuWatcher battle_menu(COLOR_RED); - int res2 = run_until( - env.console, context, - [&](ProControllerContext& context) { - env.log("Sending out selected starter."); - pbf_press_button(context, BUTTON_A, 40, 40); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(20), - {{battle_menu}} - ); - if (ret == 0) { - env.log("Battle menu detecteed!"); - } - pbf_wait(context, 125); - context.wait_for_all_requests(); - }, - {{starter_detector}} - ); - starter_detector.throw_if_no_sound(); - context.wait_for_all_requests(); - if (res2 == 0){ - env.log("Shiny starter detected!"); - stats.shinystarter++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY_STARTER, COLOR_YELLOW, "Shiny starter found!", {}, "", env.console.video().snapshot(), true); - shiny_starter = true; - } - else { - env.log("Starter is not shiny."); - env.log("Soft resetting."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Soft resetting." - ); - stats.resets++; - env.update_stats(); - soft_reset(env.program_info(), env.console, context); - } - } - - //if system set to nintendo switch, have go home when done option? - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_AudioStarterReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +AudioStarterReset_Descriptor::AudioStarterReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:AudioStarterReset", + Pokemon::STRING_POKEMON + " RSE", "Starter Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/AudioStarterReset.md", + "Soft reset for a shiny starter. Ruby and Sapphire only.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct AudioStarterReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , poochyena(m_stats["Shiny Poochyena"]) + , shinystarter(m_stats["Shiny Starter"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shiny Poochyena"); + m_display_order.emplace_back("Shiny Starter"); + } + std::atomic& resets; + std::atomic& poochyena; + std::atomic& shinystarter; +}; +std::unique_ptr AudioStarterReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +AudioStarterReset::AudioStarterReset() + : TARGET( + "Starter:
", + { + {Target::treecko, "treecko", "Treecko"}, + {Target::torchic, "torchic", "Torchic"}, + {Target::mudkip, "mudkip", "Mudkip"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::treecko + ) + , NOTIFICATION_SHINY_POOCH( + "Shiny Poochyena", + false, false, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_SHINY_STARTER( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY_POOCH, + &NOTIFICATION_SHINY_STARTER, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void AudioStarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AudioStarterReset_Descriptor::Stats& stats = env.current_stats(); + + /* + * Settings: Text Speed fast. + * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. + * If on a retro handheld, make sure the screen matches that of NSO+. + * + * Setup: Stand in front of the Professor's bag and save the game. + * + * Required to fight, so have to do the SR method instead of run away + * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. + * + * This also assumes no dry battery. + */ + + bool shiny_starter = false; + while (!shiny_starter) { + float shiny_coefficient = 1.0; + ShinySoundDetector pooch_detector(env.console, [&](float error_coefficient) -> bool{ + shiny_coefficient = error_coefficient; + return true; + }); + + env.log("Opening bag and selecting starter."); + pbf_press_button(context, BUTTON_A, 40, 180); + + switch (TARGET) { + case Target::treecko: + pbf_press_dpad(context, DPAD_LEFT, 40, 100); + break; + case Target::torchic: + //Default cursor position, do nothing. + break; + case Target::mudkip: + pbf_press_dpad(context, DPAD_RIGHT, 40, 100); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "AudioStarterReset: Invalid target.", + env.console + ); + break; + } + pbf_mash_button(context, BUTTON_A, 540); + context.wait_for_all_requests(); + + env.log("Starter selected. Checking for shiny Poochyena."); + AdvanceBattleDialogWatcher pooch_appeared(COLOR_YELLOW); + + int res = run_until( + env.console, context, + [&](ProControllerContext& context) { + int ret = wait_until( + env.console, context, + std::chrono::seconds(20), + {{pooch_appeared}} + ); + if (ret == 0) { + env.log("Advance arrow detected."); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + }, + {{pooch_detector}} + ); + pooch_detector.throw_if_no_sound(); + if (res == 0){ + env.log("Shiny Poochyena detected!"); + stats.poochyena++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY_POOCH, COLOR_YELLOW, "Shiny Poochyena found", {}, "", env.console.video().snapshot(), true); + } + else { + env.log("Poochyena is not shiny."); + } + context.wait_for_all_requests(); + + float shiny_coefficient2 = 1.0; + ShinySoundDetector starter_detector(env.console, [&](float error_coefficient) -> bool{ + shiny_coefficient2 = error_coefficient; + return true; + }); + + BattleMenuWatcher battle_menu(COLOR_RED); + int res2 = run_until( + env.console, context, + [&](ProControllerContext& context) { + env.log("Sending out selected starter."); + pbf_press_button(context, BUTTON_A, 40, 40); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(20), + {{battle_menu}} + ); + if (ret == 0) { + env.log("Battle menu detecteed!"); + } + pbf_wait(context, 125); + context.wait_for_all_requests(); + }, + {{starter_detector}} + ); + starter_detector.throw_if_no_sound(); + context.wait_for_all_requests(); + if (res2 == 0){ + env.log("Shiny starter detected!"); + stats.shinystarter++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY_STARTER, COLOR_YELLOW, "Shiny starter found!", {}, "", env.console.video().snapshot(), true); + shiny_starter = true; + } + else { + env.log("Starter is not shiny."); + env.log("Soft resetting."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Soft resetting." + ); + stats.resets++; + env.update_stats(); + soft_reset(env.program_info(), env.console, context); + } + } + + //if system set to nintendo switch, have go home when done option? + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h index 9e890300dd..992180cb86 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_AudioStarterReset.h @@ -1,54 +1,54 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_AudioStarterReset_H -#define PokemonAutomation_PokemonRSE_AudioStarterReset_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class AudioStarterReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AudioStarterReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class AudioStarterReset : public SingleSwitchProgramInstance{ -public: - AudioStarterReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class Target{ - treecko, - torchic, - mudkip, - }; - EnumDropdownOption TARGET; - - EventNotificationOption NOTIFICATION_SHINY_POOCH; - EventNotificationOption NOTIFICATION_SHINY_STARTER; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - - - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_AudioStarterReset_H +#define PokemonAutomation_PokemonRSE_AudioStarterReset_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class AudioStarterReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AudioStarterReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class AudioStarterReset : public SingleSwitchProgramInstance{ +public: + AudioStarterReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class Target{ + treecko, + torchic, + mudkip, + }; + EnumDropdownOption TARGET; + + EventNotificationOption NOTIFICATION_SHINY_POOCH; + EventNotificationOption NOTIFICATION_SHINY_STARTER; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp index ea6a6b31cc..a1fd9d816e 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.cpp @@ -1,530 +1,530 @@ -/* Legendary Hunt - Emerald - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_LegendaryHunt-Emerald.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -LegendaryHuntEmerald_Descriptor::LegendaryHuntEmerald_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:LegendaryHuntEmerald", - Pokemon::STRING_POKEMON + " RSE", "Legendary Hunt (Emerald)", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/LegendaryHuntEmerald.md", - "Use the Run Away method to shiny hunt legendaries in Emerald.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct LegendaryHuntEmerald_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - } - std::atomic& resets; - std::atomic& shinies; -}; -std::unique_ptr LegendaryHuntEmerald_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -LegendaryHuntEmerald::LegendaryHuntEmerald() - : TARGET( - "Target:
", - { - {Target::regis, "regis", "Regirock/Regice/Registeel"}, - {Target::groudon, "groudon", "Groudon"}, - {Target::kyogre, "kyogre", "Kyogre"}, - {Target::hooh, "hooh", "Ho-Oh"}, - {Target::lugia, "lugia", "Lugia"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::regis - ) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void LegendaryHuntEmerald::reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //turn around, walk down 4/until black screen over - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 960ms); - pbf_press_dpad(context, DPAD_DOWN, 120, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - pbf_wait(context, 50); - context.wait_for_all_requests(); - - //turn around, up one/black screen over - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_UP, 120, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //walk back up to the regi - ssf_press_button(context, BUTTON_B, 0ms, 480ms); - pbf_press_dpad(context, DPAD_UP, 60, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //Turn left. Take 10 steps. - ssf_press_button(context, BUTTON_B, 0ms, 1440ms); - pbf_press_dpad(context, DPAD_LEFT, 180, 20); - - //Turn up. Take 14 steps. (Bump into wall.) - ssf_press_button(context, BUTTON_B, 0ms, 1920ms); - pbf_press_dpad(context, DPAD_UP, 240, 20); - - //Turn right. Take 2 steps. - ssf_press_button(context, BUTTON_B, 0ms, 320ms); - pbf_press_dpad(context, DPAD_RIGHT, 40, 20); - - //Turn up. Take 8 steps (Bump into wall.) - ssf_press_button(context, BUTTON_B, 0ms, 1120ms); - pbf_press_dpad(context, DPAD_UP, 140, 20); - - //Turn left. Take 4 steps. - ssf_press_button(context, BUTTON_B, 0ms, 640ms); - pbf_press_dpad(context, DPAD_LEFT, 80, 20); - context.wait_for_all_requests(); - - //Turn down. Exit. Black screen over. - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_DOWN, 90, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - //Reverse above steps. - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_UP, 90, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - ssf_press_button(context, BUTTON_B, 0ms, 640ms); - pbf_press_dpad(context, DPAD_RIGHT, 80, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1120ms); - pbf_press_dpad(context, DPAD_DOWN, 140, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 320ms); - pbf_press_dpad(context, DPAD_LEFT, 40, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1920ms); - pbf_press_dpad(context, DPAD_DOWN, 240, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1440ms); - pbf_press_dpad(context, DPAD_RIGHT, 180, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //Turn down. Take 1 step. - ssf_press_button(context, BUTTON_B, 0ms, 160ms); - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - - //Turn right. Take 9 steps. - ssf_press_button(context, BUTTON_B, 0ms, 1280ms); - pbf_press_dpad(context, DPAD_RIGHT, 160, 20); - - //Turn up. 13 steps. Wall. - ssf_press_button(context, BUTTON_B, 0ms, 1760ms); - pbf_press_dpad(context, DPAD_UP, 220, 20); - - //Turn left. 4 steps. Wall. - ssf_press_button(context, BUTTON_B, 0ms, 640ms); - pbf_press_dpad(context, DPAD_LEFT, 80, 20); - - //Turn up. 10 steps. - ssf_press_button(context, BUTTON_B, 0ms, 1440ms); - pbf_press_dpad(context, DPAD_UP, 180, 20); - - //Turn right. 6 steps. - ssf_press_button(context, BUTTON_B, 0ms, 880ms); - pbf_press_dpad(context, DPAD_RIGHT, 110, 20); - - //Turn down. Exit. Black screen over. - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_DOWN, 90, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_UP, 90, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - ssf_press_button(context, BUTTON_B, 0ms, 880ms); - pbf_press_dpad(context, DPAD_LEFT, 110, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1440ms); - pbf_press_dpad(context, DPAD_DOWN, 180, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 640ms); - pbf_press_dpad(context, DPAD_RIGHT, 80, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1760ms); - pbf_press_dpad(context, DPAD_DOWN, 220, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1280ms); - pbf_press_dpad(context, DPAD_LEFT, 160, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 160ms); - pbf_press_dpad(context, DPAD_UP, 20, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //Turn around, 10 steps down - ssf_press_button(context, BUTTON_B, 0ms, 1440ms); - pbf_press_dpad(context, DPAD_DOWN, 180, 20); - - //Turn right, take 1 step. Wait for black screen over. - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 240ms); - pbf_press_dpad(context, DPAD_RIGHT, 30, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //turn left, take one step. now turn back right and take a step. wait for black screen over. - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 320ms); - pbf_press_dpad(context, DPAD_LEFT, 40, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 320ms); - pbf_press_dpad(context, DPAD_RIGHT, 40, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //reverse above steps, but only take 9 steps up - //doesn't really matter since we want to trigger the encounter anyway - ssf_press_button(context, BUTTON_B, 0ms, 240ms); - pbf_press_dpad(context, DPAD_LEFT, 30, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 1360ms); - pbf_press_dpad(context, DPAD_UP, 170, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //Turn around, 5 steps down - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_DOWN, 90, 20); - - //Turn right, 3 steps right. Wait for black screen over. - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_RIGHT, 90, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Left area."); - } - - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - //turn up, take one step. then turn back down and take a step. wait for black screen over. - int ret2 = run_until( - env.console, context, - [](ProControllerContext& context){ - ssf_press_button(context, BUTTON_B, 0ms, 320ms); - pbf_press_dpad(context, DPAD_UP, 40, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 320ms); - pbf_press_dpad(context, DPAD_DOWN, 40, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret2 != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //reverse above steps - ssf_press_button(context, BUTTON_B, 0ms, 560ms); - pbf_press_dpad(context, DPAD_LEFT, 70, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_UP, 90, 20); - - context.wait_for_all_requests(); -} - -void LegendaryHuntEmerald::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - LegendaryHuntEmerald_Descriptor::Stats& stats = env.current_stats(); - - /* - * Text speed fast, battle animations off - * smoke ball or fast pokemon req. no entry effects. - * - * Don't need to worry about PokeNav or random encounters for any of these targets. - * - * Stand in front of Regis/Ho-Oh/Lugia. Save the game. - */ - - while (true) { - switch (TARGET) { - case Target::hooh: - case Target::kyogre: - case Target::groudon: - //Step forward to start the encounter. - pbf_press_dpad(context, DPAD_UP, 20, 50); - break; - //case Target::groudon: //Step up is easier. - // pbf_press_dpad(context, DPAD_RIGHT, 20, 50); - // break; - //case Target::kyogre: - // pbf_press_dpad(context, DPAD_LEFT, 20, 50); - // break; - default:; - } - //handle_encounter presses A already for everything else - - bool legendary_shiny = handle_encounter(env.console, context, true); - if (legendary_shiny) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - env.log("No shiny found."); - flee_battle(env.console, context); - - //Close out dialog box - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - - //Exit and re-enter the room - switch (TARGET) { - case Target::regis: - reset_regi(env, context); - break; - case Target::groudon: - reset_groudon(env, context); - break; - case Target::kyogre: - reset_kyogre(env, context); - break; - case Target::hooh: - reset_hooh(env, context); - break; - case Target::lugia: - reset_lugia(env, context); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid target!", - env.console - ); - break; - } - - stats.resets++; - env.update_stats(); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* Legendary Hunt - Emerald + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_LegendaryHunt-Emerald.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +LegendaryHuntEmerald_Descriptor::LegendaryHuntEmerald_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:LegendaryHuntEmerald", + Pokemon::STRING_POKEMON + " RSE", "Legendary Hunt (Emerald)", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/LegendaryHuntEmerald.md", + "Use the Run Away method to shiny hunt legendaries in Emerald.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct LegendaryHuntEmerald_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + } + std::atomic& resets; + std::atomic& shinies; +}; +std::unique_ptr LegendaryHuntEmerald_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +LegendaryHuntEmerald::LegendaryHuntEmerald() + : TARGET( + "Target:
", + { + {Target::regis, "regis", "Regirock/Regice/Registeel"}, + {Target::groudon, "groudon", "Groudon"}, + {Target::kyogre, "kyogre", "Kyogre"}, + {Target::hooh, "hooh", "Ho-Oh"}, + {Target::lugia, "lugia", "Lugia"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::regis + ) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void LegendaryHuntEmerald::reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //turn around, walk down 4/until black screen over + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 960ms); + pbf_press_dpad(context, DPAD_DOWN, 120, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + pbf_wait(context, 50); + context.wait_for_all_requests(); + + //turn around, up one/black screen over + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_UP, 120, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //walk back up to the regi + ssf_press_button(context, BUTTON_B, 0ms, 480ms); + pbf_press_dpad(context, DPAD_UP, 60, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //Turn left. Take 10 steps. + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_LEFT, 180, 20); + + //Turn up. Take 14 steps. (Bump into wall.) + ssf_press_button(context, BUTTON_B, 0ms, 1920ms); + pbf_press_dpad(context, DPAD_UP, 240, 20); + + //Turn right. Take 2 steps. + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_RIGHT, 40, 20); + + //Turn up. Take 8 steps (Bump into wall.) + ssf_press_button(context, BUTTON_B, 0ms, 1120ms); + pbf_press_dpad(context, DPAD_UP, 140, 20); + + //Turn left. Take 4 steps. + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_LEFT, 80, 20); + context.wait_for_all_requests(); + + //Turn down. Exit. Black screen over. + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + //Reverse above steps. + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_RIGHT, 80, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1120ms); + pbf_press_dpad(context, DPAD_DOWN, 140, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_LEFT, 40, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1920ms); + pbf_press_dpad(context, DPAD_DOWN, 240, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_RIGHT, 180, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //Turn down. Take 1 step. + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + + //Turn right. Take 9 steps. + ssf_press_button(context, BUTTON_B, 0ms, 1280ms); + pbf_press_dpad(context, DPAD_RIGHT, 160, 20); + + //Turn up. 13 steps. Wall. + ssf_press_button(context, BUTTON_B, 0ms, 1760ms); + pbf_press_dpad(context, DPAD_UP, 220, 20); + + //Turn left. 4 steps. Wall. + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_LEFT, 80, 20); + + //Turn up. 10 steps. + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_UP, 180, 20); + + //Turn right. 6 steps. + ssf_press_button(context, BUTTON_B, 0ms, 880ms); + pbf_press_dpad(context, DPAD_RIGHT, 110, 20); + + //Turn down. Exit. Black screen over. + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + ssf_press_button(context, BUTTON_B, 0ms, 880ms); + pbf_press_dpad(context, DPAD_LEFT, 110, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_DOWN, 180, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_RIGHT, 80, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1760ms); + pbf_press_dpad(context, DPAD_DOWN, 220, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1280ms); + pbf_press_dpad(context, DPAD_LEFT, 160, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + pbf_press_dpad(context, DPAD_UP, 20, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //Turn around, 10 steps down + ssf_press_button(context, BUTTON_B, 0ms, 1440ms); + pbf_press_dpad(context, DPAD_DOWN, 180, 20); + + //Turn right, take 1 step. Wait for black screen over. + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 240ms); + pbf_press_dpad(context, DPAD_RIGHT, 30, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //turn left, take one step. now turn back right and take a step. wait for black screen over. + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_LEFT, 40, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_RIGHT, 40, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //reverse above steps, but only take 9 steps up + //doesn't really matter since we want to trigger the encounter anyway + ssf_press_button(context, BUTTON_B, 0ms, 240ms); + pbf_press_dpad(context, DPAD_LEFT, 30, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 1360ms); + pbf_press_dpad(context, DPAD_UP, 170, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //Turn around, 5 steps down + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 20); + + //Turn right, 3 steps right. Wait for black screen over. + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_RIGHT, 90, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Left area."); + } + + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + //turn up, take one step. then turn back down and take a step. wait for black screen over. + int ret2 = run_until( + env.console, context, + [](ProControllerContext& context){ + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_UP, 40, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 320ms); + pbf_press_dpad(context, DPAD_DOWN, 40, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret2 != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //reverse above steps + ssf_press_button(context, BUTTON_B, 0ms, 560ms); + pbf_press_dpad(context, DPAD_LEFT, 70, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 20); + + context.wait_for_all_requests(); +} + +void LegendaryHuntEmerald::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + LegendaryHuntEmerald_Descriptor::Stats& stats = env.current_stats(); + + /* + * Text speed fast, battle animations off + * smoke ball or fast pokemon req. no entry effects. + * + * Don't need to worry about PokeNav or random encounters for any of these targets. + * + * Stand in front of Regis/Ho-Oh/Lugia. Save the game. + */ + + while (true) { + switch (TARGET) { + case Target::hooh: + case Target::kyogre: + case Target::groudon: + //Step forward to start the encounter. + pbf_press_dpad(context, DPAD_UP, 20, 50); + break; + //case Target::groudon: //Step up is easier. + // pbf_press_dpad(context, DPAD_RIGHT, 20, 50); + // break; + //case Target::kyogre: + // pbf_press_dpad(context, DPAD_LEFT, 20, 50); + // break; + default:; + } + //handle_encounter presses A already for everything else + + bool legendary_shiny = handle_encounter(env.console, context, true); + if (legendary_shiny) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + env.log("No shiny found."); + flee_battle(env.console, context); + + //Close out dialog box + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + + //Exit and re-enter the room + switch (TARGET) { + case Target::regis: + reset_regi(env, context); + break; + case Target::groudon: + reset_groudon(env, context); + break; + case Target::kyogre: + reset_kyogre(env, context); + break; + case Target::hooh: + reset_hooh(env, context); + break; + case Target::lugia: + reset_lugia(env, context); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid target!", + env.console + ); + break; + } + + stats.resets++; + env.update_stats(); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h index 1409ef1d5e..6642058a6f 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_LegendaryHunt-Emerald.h @@ -1,61 +1,61 @@ -/* Legendary Hunt - Emerald - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H -#define PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeExpressionOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class LegendaryHuntEmerald_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LegendaryHuntEmerald_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class LegendaryHuntEmerald : public SingleSwitchProgramInstance{ -public: - LegendaryHuntEmerald(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class Target{ - regis, - groudon, - kyogre, - hooh, - lugia, - }; - EnumDropdownOption TARGET; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif - +/* Legendary Hunt - Emerald + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H +#define PokemonAutomation_PokemonRSE_LegendaryHuntEmerald_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeExpressionOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class LegendaryHuntEmerald_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LegendaryHuntEmerald_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class LegendaryHuntEmerald : public SingleSwitchProgramInstance{ +public: + LegendaryHuntEmerald(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class Target{ + regis, + groudon, + kyogre, + hooh, + lugia, + }; + EnumDropdownOption TARGET; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void reset_regi(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_groudon(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_kyogre(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_hooh(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void reset_lugia(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp index e2c81d35a0..59da23a2cb 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.cpp @@ -1,279 +1,279 @@ -/* E Shiny Deoxys - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_ShinyHunt-Deoxys.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -ShinyHuntDeoxys_Descriptor::ShinyHuntDeoxys_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:ShinyHuntDeoxys", - Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Deoxys", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntDeoxys.md", - "Use the Run Away method to shiny hunt Deoxys in Emerald.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct ShinyHuntDeoxys_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - } - std::atomic& resets; - std::atomic& shinies; -}; -std::unique_ptr ShinyHuntDeoxys_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -ShinyHuntDeoxys::ShinyHuntDeoxys() - : STARTPOS( - "Starting Position:
", - { - {StartPos::boat, "boat", "Boat/Walk up"}, - {StartPos::rock_unsolved, "rock_unsolved", "Triangle rock, puzzle is unsolved"}, - {StartPos::rock_solved, "rock_solved", "Triangle rock, puzzle is already solved"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StartPos::rock_unsolved - ) - , WALK_UP_DOWN_TIME0( - "Walk up/down time
Spend this long to run up to the triangle rock.", - LockMode::LOCK_WHILE_RUNNING, - "3520 ms" - ) - , NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(STARTPOS); - PA_ADD_OPTION(WALK_UP_DOWN_TIME0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void ShinyHuntDeoxys::solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - env.log("Step 1: Press A from below."); - pbf_press_button(context, BUTTON_A, 20, 40); - - env.log("Step 2: 5 Left, 1 Down."); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - - pbf_press_dpad(context, DPAD_DOWN, 10, 80); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 3: 5 Right, 5 Up."); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_UP, 90, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 4: 5 Right, 5 Down"); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_DOWN, 90, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 5: 3 Up, 7 Left"); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_dpad(context, DPAD_UP, 10, 50); - - ssf_press_button(context, BUTTON_B, 0ms, 920ms); - pbf_press_dpad(context, DPAD_LEFT, 115, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 6: 5 Right."); - ssf_press_button(context, BUTTON_B, 0ms, 800ms); - pbf_press_dpad(context, DPAD_RIGHT, 100, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 7: 3 Left, 2 Down."); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - - ssf_press_button(context, BUTTON_B, 0ms, 480ms); - pbf_press_dpad(context, DPAD_DOWN, 60, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 8: 1 Down, 4 Left."); - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - - ssf_press_button(context, BUTTON_B, 0ms, 640ms); - pbf_press_dpad(context, DPAD_LEFT, 80, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 8: 7 Right."); - ssf_press_button(context, BUTTON_B, 0ms, 920ms); - pbf_press_dpad(context, DPAD_RIGHT, 115, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 9: 4 Left, Down 1."); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - - env.log("Step 10: 4 Up."); - ssf_press_button(context, BUTTON_B, 0ms, 640ms); - pbf_press_dpad(context, DPAD_UP, 80, 80); - context.wait_for_all_requests(); -} - -void ShinyHuntDeoxys::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntDeoxys_Descriptor::Stats& stats = env.current_stats(); - - /* - * Settings: Text Speed fast. Turn off animations. - * Full screen, no filter. - * If on a retro handheld, make sure the screen matches that of NSO+. - * - * Setup: Lead is faster or has a Smoke Ball. - * No abilities or items that activate on entry. - * Lead cannot be shiny. - * Stand enter Birth Island and stay at the door. Save the game. - * - * Emerald only. This uses the Run Away method due to the game's RNG issues. - * If powering off your game/resetting, try to start with different timing to avoid repeated frames. - * - * Do not have to handle random PokeNav calls for deoxys/mew. - * Would have to handle both PokeNav and random encounters for ray/others? Why is PokeNav a thing??? - */ - - bool first_run = true; - - while (true) { - if (first_run) { - switch (STARTPOS) { - case StartPos::rock_solved: - env.log("StartPos: Already in position."); - break; - case StartPos::boat: - env.log("StartPos: Walking up to Deoxys."); - //Walk up to the triangle rock from the ship. No bike allowed. - ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); - pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); - context.wait_for_all_requests(); - case StartPos::rock_unsolved: - env.log("StartPos: Solving puzzle."); - solve_puzzle(env, context); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid starting position selected.", - env.console - ); - break; - } - first_run = false; - } - - //Start battle - bool legendary_shiny = handle_encounter(env.console, context, true); - if (legendary_shiny) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - env.log("No shiny found."); - flee_battle(env.console, context); - - //After pressing the flee button, additional dialog box pops up for Deoxys - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - - //Walk down from the triangle rock to the ship. - env.log("Walking down to ship."); - ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); - pbf_press_dpad(context, DPAD_DOWN, WALK_UP_DOWN_TIME0, 160ms); - context.wait_for_all_requests(); - - env.log("Walking up to Deoxys rock."); - //Walk up to the triangle rock from the ship. Bike is not allowed on Birth Island. - ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); - pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); - context.wait_for_all_requests(); - - env.log("Solving puzzle."); - solve_puzzle(env, context); - - stats.resets++; - env.update_stats(); - } - - //switch - go home when done - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* E Shiny Deoxys + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_ShinyHunt-Deoxys.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +ShinyHuntDeoxys_Descriptor::ShinyHuntDeoxys_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:ShinyHuntDeoxys", + Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Deoxys", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntDeoxys.md", + "Use the Run Away method to shiny hunt Deoxys in Emerald.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct ShinyHuntDeoxys_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + } + std::atomic& resets; + std::atomic& shinies; +}; +std::unique_ptr ShinyHuntDeoxys_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +ShinyHuntDeoxys::ShinyHuntDeoxys() + : STARTPOS( + "Starting Position:
", + { + {StartPos::boat, "boat", "Boat/Walk up"}, + {StartPos::rock_unsolved, "rock_unsolved", "Triangle rock, puzzle is unsolved"}, + {StartPos::rock_solved, "rock_solved", "Triangle rock, puzzle is already solved"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StartPos::rock_unsolved + ) + , WALK_UP_DOWN_TIME0( + "Walk up/down time
Spend this long to run up to the triangle rock.", + LockMode::LOCK_WHILE_RUNNING, + "3520 ms" + ) + , NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(STARTPOS); + PA_ADD_OPTION(WALK_UP_DOWN_TIME0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void ShinyHuntDeoxys::solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + env.log("Step 1: Press A from below."); + pbf_press_button(context, BUTTON_A, 20, 40); + + env.log("Step 2: 5 Left, 1 Down."); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + + pbf_press_dpad(context, DPAD_DOWN, 10, 80); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 3: 5 Right, 5 Up."); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_UP, 90, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 4: 5 Right, 5 Down"); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_DOWN, 90, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 5: 3 Up, 7 Left"); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_dpad(context, DPAD_UP, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 920ms); + pbf_press_dpad(context, DPAD_LEFT, 115, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 6: 5 Right."); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + pbf_press_dpad(context, DPAD_RIGHT, 100, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 7: 3 Left, 2 Down."); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 480ms); + pbf_press_dpad(context, DPAD_DOWN, 60, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 8: 1 Down, 4 Left."); + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_LEFT, 80, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 8: 7 Right."); + ssf_press_button(context, BUTTON_B, 0ms, 920ms); + pbf_press_dpad(context, DPAD_RIGHT, 115, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 9: 4 Left, Down 1."); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + + env.log("Step 10: 4 Up."); + ssf_press_button(context, BUTTON_B, 0ms, 640ms); + pbf_press_dpad(context, DPAD_UP, 80, 80); + context.wait_for_all_requests(); +} + +void ShinyHuntDeoxys::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntDeoxys_Descriptor::Stats& stats = env.current_stats(); + + /* + * Settings: Text Speed fast. Turn off animations. + * Full screen, no filter. + * If on a retro handheld, make sure the screen matches that of NSO+. + * + * Setup: Lead is faster or has a Smoke Ball. + * No abilities or items that activate on entry. + * Lead cannot be shiny. + * Stand enter Birth Island and stay at the door. Save the game. + * + * Emerald only. This uses the Run Away method due to the game's RNG issues. + * If powering off your game/resetting, try to start with different timing to avoid repeated frames. + * + * Do not have to handle random PokeNav calls for deoxys/mew. + * Would have to handle both PokeNav and random encounters for ray/others? Why is PokeNav a thing??? + */ + + bool first_run = true; + + while (true) { + if (first_run) { + switch (STARTPOS) { + case StartPos::rock_solved: + env.log("StartPos: Already in position."); + break; + case StartPos::boat: + env.log("StartPos: Walking up to Deoxys."); + //Walk up to the triangle rock from the ship. No bike allowed. + ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); + pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); + context.wait_for_all_requests(); + case StartPos::rock_unsolved: + env.log("StartPos: Solving puzzle."); + solve_puzzle(env, context); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid starting position selected.", + env.console + ); + break; + } + first_run = false; + } + + //Start battle + bool legendary_shiny = handle_encounter(env.console, context, true); + if (legendary_shiny) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + env.log("No shiny found."); + flee_battle(env.console, context); + + //After pressing the flee button, additional dialog box pops up for Deoxys + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + + //Walk down from the triangle rock to the ship. + env.log("Walking down to ship."); + ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); + pbf_press_dpad(context, DPAD_DOWN, WALK_UP_DOWN_TIME0, 160ms); + context.wait_for_all_requests(); + + env.log("Walking up to Deoxys rock."); + //Walk up to the triangle rock from the ship. Bike is not allowed on Birth Island. + ssf_press_button(context, BUTTON_B, 0ms, WALK_UP_DOWN_TIME0); + pbf_press_dpad(context, DPAD_UP, WALK_UP_DOWN_TIME0, 160ms); + context.wait_for_all_requests(); + + env.log("Solving puzzle."); + solve_puzzle(env, context); + + stats.resets++; + env.update_stats(); + } + + //switch - go home when done + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h index 62b7454d0a..b87e6ccc8a 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Deoxys.h @@ -1,56 +1,56 @@ -/* E Shiny Deoxys - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H -#define PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class ShinyHuntDeoxys_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntDeoxys_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class ShinyHuntDeoxys : public SingleSwitchProgramInstance{ -public: - ShinyHuntDeoxys(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class StartPos{ - boat, - rock_unsolved, - rock_solved, - }; - EnumDropdownOption STARTPOS; - - MillisecondsOption WALK_UP_DOWN_TIME0; - - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif - +/* E Shiny Deoxys + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H +#define PokemonAutomation_PokemonRSE_ShinyHuntDeoxys_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class ShinyHuntDeoxys_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntDeoxys_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class ShinyHuntDeoxys : public SingleSwitchProgramInstance{ +public: + ShinyHuntDeoxys(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class StartPos{ + boat, + rock_unsolved, + rock_solved, + }; + EnumDropdownOption STARTPOS; + + MillisecondsOption WALK_UP_DOWN_TIME0; + + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void solve_puzzle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp index 11ac24e9ae..b45e59e24b 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.cpp @@ -1,230 +1,230 @@ -/* E Shiny Mew - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_ShinyHunt-Mew.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -ShinyHuntMew_Descriptor::ShinyHuntMew_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:ShinyHuntMew", - Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Mew", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntMew.md", - "Use the Run Away method to shiny hunt Mew in Emerald.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct ShinyHuntMew_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shinies"); - } - std::atomic& resets; - std::atomic& shinies; -}; -std::unique_ptr ShinyHuntMew_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -ShinyHuntMew::ShinyHuntMew() - : NOTIFICATION_SHINY( - "Shiny Found", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MEW_WAIT_TIME( - "Mew wait time:
Wait this long after entering for Mew to hide in the grass.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , DOOR_TO_GRASS_TIME( - "Door to grass time:
Time it takes to run from the door to the edge of the tall grass. Three steps up.", - LockMode::LOCK_WHILE_RUNNING, - "400 ms" - ) - , RIGHT_GRASS_1_TIME( - "First Right time:
Time it takes to turn right and take three steps. This follows the edge of the grass.", - LockMode::LOCK_WHILE_RUNNING, - "450 ms" - ) - , UP_GRASS_1_TIME( - "Move Up time::
Time it takes turn up and take one step.", - LockMode::LOCK_WHILE_RUNNING, - "200 ms" - ) - , RIGHT_GRASS_2_TIME( - "Second Right time:
Time it takes to turn right and take two steps.", - LockMode::LOCK_WHILE_RUNNING, - "260 ms" - ) - , FACE_UP_TIME( - "Face Up time:
Time it takes to tap the up button and face up, without taking a step.", - LockMode::LOCK_WHILE_RUNNING, - "150 ms" - ) -{ - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(MEW_WAIT_TIME); - PA_ADD_OPTION(DOOR_TO_GRASS_TIME); - PA_ADD_OPTION(RIGHT_GRASS_1_TIME); - PA_ADD_OPTION(UP_GRASS_1_TIME); - PA_ADD_OPTION(RIGHT_GRASS_2_TIME); - PA_ADD_OPTION(FACE_UP_TIME); -} - -void ShinyHuntMew::enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_UP, 250, 20); - pbf_wait(context, 300); - }, - {enter_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to enter area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter area.", - env.console - ); - } - else { - env.log("Entered area."); - } - - //Wait for Mew ! animation to finish - pbf_wait(context, MEW_WAIT_TIME); - context.wait_for_all_requests(); - - //DO NOT pause while running! - //Run up toward the extra tall grass - 3 steps - ssf_press_button(context, BUTTON_B, 0ms, DOOR_TO_GRASS_TIME); - pbf_press_dpad(context, DPAD_UP, DOOR_TO_GRASS_TIME, 0ms); - - //Turn right, take 3 steps - ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_1_TIME); - pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_1_TIME, 0ms); - - //Turn up, take 1 step - ssf_press_button(context, BUTTON_B, 0ms, UP_GRASS_1_TIME); - pbf_press_dpad(context, DPAD_UP, UP_GRASS_1_TIME, 0ms); - - //Turn right, take 2 steps - ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_2_TIME); - pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_2_TIME, 0ms); - - //Turn up. Start battle. - pbf_press_dpad(context, DPAD_UP, FACE_UP_TIME, 0ms); - - context.wait_for_all_requests(); -} - -void ShinyHuntMew::exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - ssf_press_button(context, BUTTON_B, 0ms, 400ms); - pbf_press_dpad(context, DPAD_DOWN, 50, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 720ms); - pbf_press_dpad(context, DPAD_LEFT, 90, 20); - - ssf_press_button(context, BUTTON_B, 0ms, 800ms); - pbf_press_dpad(context, DPAD_DOWN, 100, 20); - - BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_dpad(context, DPAD_DOWN, 250, 20); - pbf_wait(context, 300); - }, - {exit_area} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.log("Failed to exit area.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to exit area.", - env.console - ); - } - else { - env.log("Exited area."); - } -} - -void ShinyHuntMew::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntMew_Descriptor::Stats& stats = env.current_stats(); - - /* - * Requires more precision to ensure a Mew encounter every time. - * Movement is very configurable due to this. - * Enter on the left side, run up and hug the grass to the edge just after the flower on the right - * This but without the bike: - * https://old.reddit.com/r/ShinyPokemon/comments/1c773oi/gen3_discuss_is_this_the_fastest_way_to_encounter/ - */ - - while (true) { - enter_mew(env, context); - - bool legendary_shiny = handle_encounter(env.console, context, true); - if (legendary_shiny) { - stats.shinies++; - env.update_stats(); - send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); - break; - } - env.log("No shiny found."); - flee_battle(env.console, context); - - //Close dialog - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - - exit_mew(env, context); - - stats.resets++; - env.update_stats(); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* E Shiny Mew + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_ShinyHunt-Mew.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +ShinyHuntMew_Descriptor::ShinyHuntMew_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:ShinyHuntMew", + Pokemon::STRING_POKEMON + " RSE", "Shiny Hunt - Mew", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/ShinyHuntMew.md", + "Use the Run Away method to shiny hunt Mew in Emerald.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct ShinyHuntMew_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shinies"); + } + std::atomic& resets; + std::atomic& shinies; +}; +std::unique_ptr ShinyHuntMew_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +ShinyHuntMew::ShinyHuntMew() + : NOTIFICATION_SHINY( + "Shiny Found", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MEW_WAIT_TIME( + "Mew wait time:
Wait this long after entering for Mew to hide in the grass.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , DOOR_TO_GRASS_TIME( + "Door to grass time:
Time it takes to run from the door to the edge of the tall grass. Three steps up.", + LockMode::LOCK_WHILE_RUNNING, + "400 ms" + ) + , RIGHT_GRASS_1_TIME( + "First Right time:
Time it takes to turn right and take three steps. This follows the edge of the grass.", + LockMode::LOCK_WHILE_RUNNING, + "450 ms" + ) + , UP_GRASS_1_TIME( + "Move Up time::
Time it takes turn up and take one step.", + LockMode::LOCK_WHILE_RUNNING, + "200 ms" + ) + , RIGHT_GRASS_2_TIME( + "Second Right time:
Time it takes to turn right and take two steps.", + LockMode::LOCK_WHILE_RUNNING, + "260 ms" + ) + , FACE_UP_TIME( + "Face Up time:
Time it takes to tap the up button and face up, without taking a step.", + LockMode::LOCK_WHILE_RUNNING, + "150 ms" + ) +{ + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(MEW_WAIT_TIME); + PA_ADD_OPTION(DOOR_TO_GRASS_TIME); + PA_ADD_OPTION(RIGHT_GRASS_1_TIME); + PA_ADD_OPTION(UP_GRASS_1_TIME); + PA_ADD_OPTION(RIGHT_GRASS_2_TIME); + PA_ADD_OPTION(FACE_UP_TIME); +} + +void ShinyHuntMew::enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + BlackScreenOverWatcher enter_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_UP, 250, 20); + pbf_wait(context, 300); + }, + {enter_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to enter area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter area.", + env.console + ); + } + else { + env.log("Entered area."); + } + + //Wait for Mew ! animation to finish + pbf_wait(context, MEW_WAIT_TIME); + context.wait_for_all_requests(); + + //DO NOT pause while running! + //Run up toward the extra tall grass - 3 steps + ssf_press_button(context, BUTTON_B, 0ms, DOOR_TO_GRASS_TIME); + pbf_press_dpad(context, DPAD_UP, DOOR_TO_GRASS_TIME, 0ms); + + //Turn right, take 3 steps + ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_1_TIME); + pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_1_TIME, 0ms); + + //Turn up, take 1 step + ssf_press_button(context, BUTTON_B, 0ms, UP_GRASS_1_TIME); + pbf_press_dpad(context, DPAD_UP, UP_GRASS_1_TIME, 0ms); + + //Turn right, take 2 steps + ssf_press_button(context, BUTTON_B, 0ms, RIGHT_GRASS_2_TIME); + pbf_press_dpad(context, DPAD_RIGHT, RIGHT_GRASS_2_TIME, 0ms); + + //Turn up. Start battle. + pbf_press_dpad(context, DPAD_UP, FACE_UP_TIME, 0ms); + + context.wait_for_all_requests(); +} + +void ShinyHuntMew::exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + ssf_press_button(context, BUTTON_B, 0ms, 400ms); + pbf_press_dpad(context, DPAD_DOWN, 50, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 720ms); + pbf_press_dpad(context, DPAD_LEFT, 90, 20); + + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + pbf_press_dpad(context, DPAD_DOWN, 100, 20); + + BlackScreenOverWatcher exit_area(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_dpad(context, DPAD_DOWN, 250, 20); + pbf_wait(context, 300); + }, + {exit_area} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.log("Failed to exit area.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to exit area.", + env.console + ); + } + else { + env.log("Exited area."); + } +} + +void ShinyHuntMew::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntMew_Descriptor::Stats& stats = env.current_stats(); + + /* + * Requires more precision to ensure a Mew encounter every time. + * Movement is very configurable due to this. + * Enter on the left side, run up and hug the grass to the edge just after the flower on the right + * This but without the bike: + * https://old.reddit.com/r/ShinyPokemon/comments/1c773oi/gen3_discuss_is_this_the_fastest_way_to_encounter/ + */ + + while (true) { + enter_mew(env, context); + + bool legendary_shiny = handle_encounter(env.console, context, true); + if (legendary_shiny) { + stats.shinies++; + env.update_stats(); + send_program_notification(env, NOTIFICATION_SHINY, COLOR_YELLOW, "Shiny found!", {}, "", env.console.video().snapshot(), true); + break; + } + env.log("No shiny found."); + flee_battle(env.console, context); + + //Close dialog + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + + exit_mew(env, context); + + stats.resets++; + env.update_stats(); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h index 6d8f81e086..9d438bdb1e 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_ShinyHunt-Mew.h @@ -1,59 +1,59 @@ -/* E Shiny Mew - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_ShinyHuntMew_H -#define PokemonAutomation_PokemonRSE_ShinyHuntMew_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class ShinyHuntMew_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntMew_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class ShinyHuntMew : public SingleSwitchProgramInstance{ -public: - ShinyHuntMew(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - - MillisecondsOption MEW_WAIT_TIME; - MillisecondsOption DOOR_TO_GRASS_TIME; - MillisecondsOption RIGHT_GRASS_1_TIME; - MillisecondsOption UP_GRASS_1_TIME; - MillisecondsOption RIGHT_GRASS_2_TIME; - MillisecondsOption FACE_UP_TIME; - - void enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -}; - -} -} -} -#endif - +/* E Shiny Mew + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_ShinyHuntMew_H +#define PokemonAutomation_PokemonRSE_ShinyHuntMew_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class ShinyHuntMew_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntMew_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class ShinyHuntMew : public SingleSwitchProgramInstance{ +public: + ShinyHuntMew(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + + MillisecondsOption MEW_WAIT_TIME; + MillisecondsOption DOOR_TO_GRASS_TIME; + MillisecondsOption RIGHT_GRASS_1_TIME; + MillisecondsOption UP_GRASS_1_TIME; + MillisecondsOption RIGHT_GRASS_2_TIME; + MillisecondsOption FACE_UP_TIME; + + void enter_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void exit_mew(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +}; + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp index 37539aa6ed..5d73850c5e 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.cpp @@ -1,207 +1,207 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" -#include "PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h" -#include "PokemonRSE/PokemonRSE_Navigation.h" -#include "PokemonRSE_StarterReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -StarterReset_Descriptor::StarterReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:StarterReset", - Pokemon::STRING_POKEMON + " RSE", "[RS]Starter Reset - Video", - "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/StarterReset.md", - "Soft reset for a shiny starter. Ruby and Sapphire only.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -struct StarterReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , shinystarter(m_stats["Shiny Starter"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Shiny Starter"); - } - std::atomic& resets; - std::atomic& shinystarter; -}; -std::unique_ptr StarterReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -StarterReset::StarterReset() - : TARGET( - "Starter:
", - { - {Target::treecko, "treecko", "Treecko"}, - {Target::torchic, "torchic", "Torchic"}, - {Target::mudkip, "mudkip", "Mudkip"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::treecko - ) -// , STARTER_WAIT0( -// "Send out starter wait:
After pressing A to send out your selected starter, wait this long for the animation. Make sure to add extra time in case it is shiny.", -// LockMode::LOCK_WHILE_RUNNING, -// "6000 ms" -// ) - , NOTIFICATION_SHINY_STARTER( - "Shiny Starter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_SHINY_STARTER, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void StarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StarterReset_Descriptor::Stats& stats = env.current_stats(); - - /* - * Settings: Text Speed fast. - * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. - * If on a retro handheld, make sure the screen matches that of NSO+. - * - * Setup: Stand in front of the Professor's bag and save the game. - * - * Required to fight, so have to do the SR method instead of run away - * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. - * - * This also assumes no dry battery. - * - * WARNING: Timings in Emerald for the battle menu are slightly different. This won't work with Emerald at all. - */ - - bool shiny_starter = false; - while (!shiny_starter) { - env.log("Opening bag and selecting starter."); - pbf_press_button(context, BUTTON_A, 40, 180); - - switch (TARGET) { - case Target::treecko: - pbf_press_dpad(context, DPAD_LEFT, 40, 100); - break; - case Target::torchic: - //Default cursor position, do nothing. - break; - case Target::mudkip: - pbf_press_dpad(context, DPAD_RIGHT, 40, 100); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "StarterReset: Invalid target.", - env.console - ); - break; - } - pbf_mash_button(context, BUTTON_A, 540); - context.wait_for_all_requests(); - - env.log("Starting battle."); - - //Now mash B until the battle menu appears - BattleMenuWatcher battle_menu(COLOR_RED); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 1000); - }, - {battle_menu} - ); - context.wait_for_all_requests(); - if (ret != 0){ - env.console.log("Failed to detect battle menu.", COLOR_RED); - } - else { - env.log("Battle menu detected."); - } - - //Open the summary and check the color of the number - pbf_press_dpad(context, DPAD_DOWN, 40, 80); - pbf_press_button(context, BUTTON_A, 40, 80); - - BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); - int ret2 = wait_until( - env.console, context, - std::chrono::milliseconds(3000), - {{detector}} - ); - if (ret2 == 0){ - env.log("Entered party menu."); - }else{ - env.log("Timed out waiting to enter party menu.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "StarterReset: Timed out waiting to enter party menu.", - env.console - ); - } - - pbf_press_button(context, BUTTON_A, 20, 180); - pbf_press_dpad(context, DPAD_DOWN, 40, 80); - pbf_press_button(context, BUTTON_A, 40, 80); - - //Check second party member - used for testing with hacked in shiny starter - //pbf_press_dpad(context, DPAD_DOWN, 40, 80); - - pbf_wait(context, 125); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - ShinyNumberDetector shiny_checker(COLOR_YELLOW); - shiny_starter = shiny_checker.read(env.console.logger(), screen); - - if (shiny_starter) { - env.log("Shiny starter detected!"); - stats.shinystarter++; - send_program_status_notification(env, NOTIFICATION_SHINY_STARTER, "Shiny starter found!", screen, true); - } - else { - env.log("Starter is not shiny."); - env.log("Soft resetting."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Soft resetting." - ); - soft_reset(env.program_info(), env.console, context); - stats.resets++; - } - } - - //if system set to nintendo switch, have go home when done option? - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonRSE/Inference/Dialogs/PokemonRSE_DialogDetector.h" +#include "PokemonRSE/Inference/PokemonRSE_ShinyNumberDetector.h" +#include "PokemonRSE/PokemonRSE_Navigation.h" +#include "PokemonRSE_StarterReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +StarterReset_Descriptor::StarterReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:StarterReset", + Pokemon::STRING_POKEMON + " RSE", "[RS]Starter Reset - Video", + "ComputerControl/blob/master/Wiki/Programs/PokemonRSE/StarterReset.md", + "Soft reset for a shiny starter. Ruby and Sapphire only.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +struct StarterReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , shinystarter(m_stats["Shiny Starter"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Shiny Starter"); + } + std::atomic& resets; + std::atomic& shinystarter; +}; +std::unique_ptr StarterReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +StarterReset::StarterReset() + : TARGET( + "Starter:
", + { + {Target::treecko, "treecko", "Treecko"}, + {Target::torchic, "torchic", "Torchic"}, + {Target::mudkip, "mudkip", "Mudkip"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::treecko + ) +// , STARTER_WAIT0( +// "Send out starter wait:
After pressing A to send out your selected starter, wait this long for the animation. Make sure to add extra time in case it is shiny.", +// LockMode::LOCK_WHILE_RUNNING, +// "6000 ms" +// ) + , NOTIFICATION_SHINY_STARTER( + "Shiny Starter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_SHINY_STARTER, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void StarterReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StarterReset_Descriptor::Stats& stats = env.current_stats(); + + /* + * Settings: Text Speed fast. + * Full screen, no filter? The device I'm using to test has similar looking output, but I don't have switch online+. + * If on a retro handheld, make sure the screen matches that of NSO+. + * + * Setup: Stand in front of the Professor's bag and save the game. + * + * Required to fight, so have to do the SR method instead of run away + * Soft reset programs are only for Ruby/Sapphire, as Emerald has the 0 seed issue. + * + * This also assumes no dry battery. + * + * WARNING: Timings in Emerald for the battle menu are slightly different. This won't work with Emerald at all. + */ + + bool shiny_starter = false; + while (!shiny_starter) { + env.log("Opening bag and selecting starter."); + pbf_press_button(context, BUTTON_A, 40, 180); + + switch (TARGET) { + case Target::treecko: + pbf_press_dpad(context, DPAD_LEFT, 40, 100); + break; + case Target::torchic: + //Default cursor position, do nothing. + break; + case Target::mudkip: + pbf_press_dpad(context, DPAD_RIGHT, 40, 100); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "StarterReset: Invalid target.", + env.console + ); + break; + } + pbf_mash_button(context, BUTTON_A, 540); + context.wait_for_all_requests(); + + env.log("Starting battle."); + + //Now mash B until the battle menu appears + BattleMenuWatcher battle_menu(COLOR_RED); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 1000); + }, + {battle_menu} + ); + context.wait_for_all_requests(); + if (ret != 0){ + env.console.log("Failed to detect battle menu.", COLOR_RED); + } + else { + env.log("Battle menu detected."); + } + + //Open the summary and check the color of the number + pbf_press_dpad(context, DPAD_DOWN, 40, 80); + pbf_press_button(context, BUTTON_A, 40, 80); + + BlackScreenOverWatcher detector(COLOR_RED, {0.282, 0.064, 0.448, 0.871}); + int ret2 = wait_until( + env.console, context, + std::chrono::milliseconds(3000), + {{detector}} + ); + if (ret2 == 0){ + env.log("Entered party menu."); + }else{ + env.log("Timed out waiting to enter party menu.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "StarterReset: Timed out waiting to enter party menu.", + env.console + ); + } + + pbf_press_button(context, BUTTON_A, 20, 180); + pbf_press_dpad(context, DPAD_DOWN, 40, 80); + pbf_press_button(context, BUTTON_A, 40, 80); + + //Check second party member - used for testing with hacked in shiny starter + //pbf_press_dpad(context, DPAD_DOWN, 40, 80); + + pbf_wait(context, 125); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + ShinyNumberDetector shiny_checker(COLOR_YELLOW); + shiny_starter = shiny_checker.read(env.console.logger(), screen); + + if (shiny_starter) { + env.log("Shiny starter detected!"); + stats.shinystarter++; + send_program_status_notification(env, NOTIFICATION_SHINY_STARTER, "Shiny starter found!", screen, true); + } + else { + env.log("Starter is not shiny."); + env.log("Soft resetting."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Soft resetting." + ); + soft_reset(env.program_info(), env.console, context); + stats.resets++; + } + } + + //if system set to nintendo switch, have go home when done option? + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h index 12644eaf8f..866d3035df 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/ShinyHunting/PokemonRSE_StarterReset.h @@ -1,56 +1,56 @@ -/* RS Starter Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonRSE_StarterReset_H -#define PokemonAutomation_PokemonRSE_StarterReset_H - -//#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - -class StarterReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StarterReset_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class StarterReset : public SingleSwitchProgramInstance{ -public: - StarterReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class Target{ - treecko, - torchic, - mudkip, - }; - EnumDropdownOption TARGET; - -// MillisecondsOption STARTER_WAIT0; - - EventNotificationOption NOTIFICATION_SHINY_STARTER; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - - - +/* RS Starter Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonRSE_StarterReset_H +#define PokemonAutomation_PokemonRSE_StarterReset_H + +//#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + +class StarterReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StarterReset_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class StarterReset : public SingleSwitchProgramInstance{ +public: + StarterReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext &context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class Target{ + treecko, + torchic, + mudkip, + }; + EnumDropdownOption TARGET; + +// MillisecondsOption STARTER_WAIT0; + + EventNotificationOption NOTIFICATION_SHINY_STARTER; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp index d2fc7e1e84..63e2d4cac3 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.cpp @@ -1,100 +1,100 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Containers/AlignedVector.tpp" -#include "CommonFramework/AudioPipeline/AudioFeed.h" -#include "CommonFramework/AudioPipeline/AudioTemplate.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" -#include "PokemonRSE_SoundListener.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - using namespace Pokemon; - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonRSE:SoundListener", - STRING_POKEMON + " RSE", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::SHINY, "shiny", "Shiny Sound"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::SHINY - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - -void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // search_alpha_roar_from_audio_dump(); - // return; - - std::cout << "Running audio test program." << std::endl; - - std::shared_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::SHINY: - detector = std::make_shared(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "Not such sound detector as sound type " + std::to_string((size_t)type) - ); - return; - } - - InferenceSession session( - context, env.console, - {{*detector, std::chrono::milliseconds(20)}} - ); - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Containers/AlignedVector.tpp" +#include "CommonFramework/AudioPipeline/AudioFeed.h" +#include "CommonFramework/AudioPipeline/AudioTemplate.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonRSE/Inference/Sounds/PokemonRSE_ShinySoundDetector.h" +#include "PokemonRSE_SoundListener.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + using namespace Pokemon; + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonRSE:SoundListener", + STRING_POKEMON + " RSE", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::SHINY, "shiny", "Shiny Sound"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::SHINY + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + +void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // search_alpha_roar_from_audio_dump(); + // return; + + std::cout << "Running audio test program." << std::endl; + + std::shared_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::SHINY: + detector = std::make_shared(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "Not such sound detector as sound type " + std::to_string((size_t)type) + ); + return; + } + + InferenceSession session( + context, env.console, + {{*detector, std::chrono::milliseconds(20)}} + ); + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h index 4264629acf..107bf308b2 100644 --- a/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h +++ b/SerialPrograms/Source/PokemonRSE/Programs/TestPrograms/PokemonRSE_SoundListener.h @@ -1,53 +1,53 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonRSE_SoundListener_H -#define PokemonAutomation_PokemonRSE_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonRSE{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - virtual void start_program_border_check( - VideoStream& stream, - FeedbackType feedback_type - ) override{} - -private: - enum class SoundType{ - SHINY, - }; - - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonRSE_SoundListener_H +#define PokemonAutomation_PokemonRSE_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonRSE{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + virtual void start_program_border_check( + VideoStream& stream, + FeedbackType feedback_type + ) override{} + +private: + enum class SoundType{ + SHINY, + }; + + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.cpp index 63c1162cbb..4a66a80424 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.cpp @@ -1,76 +1,76 @@ -/* Battle Ball Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV_BattleBallReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -BattleBallReader::BattleBallReader(VideoStream& stream, Language language, Color color) - : m_name_reader(PokeballNameReader::instance()) - , m_language(language) - , m_logger(stream.logger()) - , m_name(stream.overlay(), {0.380, 0.687, 0.240, 0.050}, color) - , m_sprite(stream.overlay(), {0.480, 0.764, 0.040, 0.060}, color) - , m_quantity(stream.overlay(), {0.480, 0.830, 0.040, 0.035}, color) -{} - - -std::string BattleBallReader::read_ball(const ImageViewRGB32& screen) const{ - if (!screen){ - return ""; - } - - // TODO: Use the sprite as well. - - OCR::StringMatchResult name_result; - { - ImageViewRGB32 cropped = extract_box_reference(screen, m_name); - name_result = m_name_reader.read_substring( - m_logger, m_language, cropped, - { - {0xffe0e0e0, 0xffffffff}, - {0xffc0c0c0, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - {0xff808080, 0xffffffff}, - } - ); - } - if (name_result.results.size() != 1){ -// dump_image(m_console, ProgramInfo(), "BattleBallReader-Name", screen); - return ""; - } - - return name_result.results.begin()->second.token; -} - -uint16_t BattleBallReader::read_quantity(const ImageViewRGB32& screen) const{ -#if 0 - ImageRGB32 image = to_blackwhite_rgb32_range( - extract_box_reference(screen, m_quantity), - 0xff000000, 0xff7f7f7f, true - ); - int qty = OCR::read_number(m_logger, image); -#else - int qty = OCR::read_number_waterfill( - m_logger, - extract_box_reference(screen, m_quantity), - 0xff000000, 0xff7f7f7f - ); - #endif - return (uint16_t)std::max(qty, 0); -} - - - -} -} -} +/* Battle Ball Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV_BattleBallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +BattleBallReader::BattleBallReader(VideoStream& stream, Language language, Color color) + : m_name_reader(PokeballNameReader::instance()) + , m_language(language) + , m_logger(stream.logger()) + , m_name(stream.overlay(), {0.380, 0.687, 0.240, 0.050}, color) + , m_sprite(stream.overlay(), {0.480, 0.764, 0.040, 0.060}, color) + , m_quantity(stream.overlay(), {0.480, 0.830, 0.040, 0.035}, color) +{} + + +std::string BattleBallReader::read_ball(const ImageViewRGB32& screen) const{ + if (!screen){ + return ""; + } + + // TODO: Use the sprite as well. + + OCR::StringMatchResult name_result; + { + ImageViewRGB32 cropped = extract_box_reference(screen, m_name); + name_result = m_name_reader.read_substring( + m_logger, m_language, cropped, + { + {0xffe0e0e0, 0xffffffff}, + {0xffc0c0c0, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + {0xff808080, 0xffffffff}, + } + ); + } + if (name_result.results.size() != 1){ +// dump_image(m_console, ProgramInfo(), "BattleBallReader-Name", screen); + return ""; + } + + return name_result.results.begin()->second.token; +} + +uint16_t BattleBallReader::read_quantity(const ImageViewRGB32& screen) const{ +#if 0 + ImageRGB32 image = to_blackwhite_rgb32_range( + extract_box_reference(screen, m_quantity), + 0xff000000, 0xff7f7f7f, true + ); + int qty = OCR::read_number(m_logger, image); +#else + int qty = OCR::read_number_waterfill( + m_logger, + extract_box_reference(screen, m_quantity), + 0xff000000, 0xff7f7f7f + ); + #endif + return (uint16_t)std::max(qty, 0); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h index 91e5be2a04..d9fd622028 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h @@ -1,47 +1,47 @@ -/* Battle Ball Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BattleBallReader_H -#define PokemonAutomation_PokemonSV_BattleBallReader_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetector.h" -#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -// Detect dialog that has the small arrow at bottom to show the next dialog. -class BattleBallReader{ -public: - BattleBallReader(VideoStream& stream, Language language, Color color = COLOR_RED); - - std::string read_ball(const ImageViewRGB32& screen) const; - uint16_t read_quantity(const ImageViewRGB32& screen) const; - -protected: - const PokeballNameReader& m_name_reader; - Language m_language; - Logger& m_logger; - OverlayBoxScope m_name; - OverlayBoxScope m_sprite; - OverlayBoxScope m_quantity; -}; - - - -} -} -} -#endif +/* Battle Ball Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BattleBallReader_H +#define PokemonAutomation_PokemonSV_BattleBallReader_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetector.h" +#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +// Detect dialog that has the small arrow at bottom to show the next dialog. +class BattleBallReader{ +public: + BattleBallReader(VideoStream& stream, Language language, Color color = COLOR_RED); + + std::string read_ball(const ImageViewRGB32& screen) const; + uint16_t read_quantity(const ImageViewRGB32& screen) const; + +protected: + const PokeballNameReader& m_name_reader; + Language m_language; + Logger& m_logger; + OverlayBoxScope m_name; + OverlayBoxScope m_sprite; + OverlayBoxScope m_quantity; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.cpp index 9419230a6e..ad3130fd6c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.cpp @@ -1,81 +1,81 @@ -/* Encounter Watcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonSV_EncounterWatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -EncounterWatcher::EncounterWatcher(VideoStream& stream, Color color) - : VisualInferenceCallback("EncounterWatcher (video)") - , AudioInferenceCallback("EncounterWatcher (audio)") - , m_battle_menu(color) - , m_shiny_sound(stream.logger(), [](float){ return true; }) -{} -void EncounterWatcher::make_overlays(VideoOverlaySet& items) const{ - m_battle_menu.make_overlays(items); -} -bool EncounterWatcher::process_frame(const VideoSnapshot& frame){ - if (!frame){ - return false; - } - - { - std::lock_guard lg(m_lock); - // Clear old history. - while (!m_history.empty() && m_history.front().timestamp + std::chrono::milliseconds(2000) < frame.timestamp){ - m_history.pop_front(); - } - - // Add current frame if it has been long enough since the previous. - if (m_history.empty() || m_history.back().timestamp + std::chrono::milliseconds(250) < frame.timestamp){ - m_history.push_back(frame); - } - } - - return m_battle_menu.process_frame(frame, frame.timestamp); -} -bool EncounterWatcher::process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audio_feed -){ - bool detected = m_shiny_sound.process_spectrums(new_spectrums, audio_feed); - if (!detected){ - return false; - } -// cout << "detected" << endl; - - WallClock threshold = current_time() - std::chrono::seconds(1); - - // Find the brightest frame. - std::lock_guard lg(m_lock); - - double best_bright_portion = 0; - for (const VideoSnapshot& frame : m_history){ - if (frame.timestamp >= threshold){ - break; - } - size_t bright_pixels; - filter_rgb32_range(bright_pixels, frame, 0xffe0e000, 0xffffffff, Color(0xff000000), false); - double bright_portion = bright_pixels / (double)(frame->width() * frame->height()); - if (best_bright_portion < bright_portion){ - best_bright_portion = bright_portion; - m_best_snapshot = frame; - } - } - - return false; -} - - - - -} -} -} +/* Encounter Watcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonSV_EncounterWatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +EncounterWatcher::EncounterWatcher(VideoStream& stream, Color color) + : VisualInferenceCallback("EncounterWatcher (video)") + , AudioInferenceCallback("EncounterWatcher (audio)") + , m_battle_menu(color) + , m_shiny_sound(stream.logger(), [](float){ return true; }) +{} +void EncounterWatcher::make_overlays(VideoOverlaySet& items) const{ + m_battle_menu.make_overlays(items); +} +bool EncounterWatcher::process_frame(const VideoSnapshot& frame){ + if (!frame){ + return false; + } + + { + std::lock_guard lg(m_lock); + // Clear old history. + while (!m_history.empty() && m_history.front().timestamp + std::chrono::milliseconds(2000) < frame.timestamp){ + m_history.pop_front(); + } + + // Add current frame if it has been long enough since the previous. + if (m_history.empty() || m_history.back().timestamp + std::chrono::milliseconds(250) < frame.timestamp){ + m_history.push_back(frame); + } + } + + return m_battle_menu.process_frame(frame, frame.timestamp); +} +bool EncounterWatcher::process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audio_feed +){ + bool detected = m_shiny_sound.process_spectrums(new_spectrums, audio_feed); + if (!detected){ + return false; + } +// cout << "detected" << endl; + + WallClock threshold = current_time() - std::chrono::seconds(1); + + // Find the brightest frame. + std::lock_guard lg(m_lock); + + double best_bright_portion = 0; + for (const VideoSnapshot& frame : m_history){ + if (frame.timestamp >= threshold){ + break; + } + size_t bright_pixels; + filter_rgb32_range(bright_pixels, frame, 0xffe0e000, 0xffffffff, Color(0xff000000), false); + double bright_portion = bright_pixels / (double)(frame->width() * frame->height()); + if (best_bright_portion < bright_portion){ + best_bright_portion = bright_portion; + m_best_snapshot = frame; + } + } + + return false; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h index 024e4676a4..e49ecbd510 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h @@ -1,60 +1,60 @@ -/* Encounter Watcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EncounterWatcher_H -#define PokemonAutomation_PokemonSV_EncounterWatcher_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "PokemonSV_NormalBattleMenus.h" -#include "PokemonSV_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class EncounterWatcher : public VisualInferenceCallback, public AudioInferenceCallback{ -public: - EncounterWatcher(VideoStream& stream, Color color = COLOR_RED); - - const NormalBattleMenuDetector& battle_menu_detector() const{ return m_battle_menu; } - - const VideoSnapshot& shiny_screenshot() const{ - return m_best_snapshot; - } - float lowest_error_coefficient() const{ - return m_shiny_sound.lowest_error(); - } - void throw_if_no_sound() const{ - m_shiny_sound.throw_if_no_sound(); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - virtual bool process_spectrums( - const std::vector& new_spectrums, - AudioFeed& audioFeed - ) override; - -private: - NormalBattleMenuWatcher m_battle_menu; - ShinySoundDetector m_shiny_sound; - - std::mutex m_lock; - std::deque m_history; - VideoSnapshot m_best_snapshot; -}; - - - - -} -} -} -#endif +/* Encounter Watcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EncounterWatcher_H +#define PokemonAutomation_PokemonSV_EncounterWatcher_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "PokemonSV_NormalBattleMenus.h" +#include "PokemonSV_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class EncounterWatcher : public VisualInferenceCallback, public AudioInferenceCallback{ +public: + EncounterWatcher(VideoStream& stream, Color color = COLOR_RED); + + const NormalBattleMenuDetector& battle_menu_detector() const{ return m_battle_menu; } + + const VideoSnapshot& shiny_screenshot() const{ + return m_best_snapshot; + } + float lowest_error_coefficient() const{ + return m_shiny_sound.lowest_error(); + } + void throw_if_no_sound() const{ + m_shiny_sound.throw_if_no_sound(); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + virtual bool process_spectrums( + const std::vector& new_spectrums, + AudioFeed& audioFeed + ) override; + +private: + NormalBattleMenuWatcher m_battle_menu; + ShinySoundDetector m_shiny_sound; + + std::mutex m_lock; + std::deque m_history; + VideoSnapshot m_best_snapshot; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.cpp index b918aedf34..93bb29fa9c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.cpp @@ -1,372 +1,372 @@ -/* Normal Battle Menus - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSV_NormalBattleMenus.h" - - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -NormalBattleMenuDetector::NormalBattleMenuDetector(Color color) - : m_status_button(color, WhiteButton::ButtonY, {0.35, 0.90, 0.30, 0.08}) - , m_arrow(color, GradientArrowType::RIGHT, {0.75, 0.62, 0.05, 0.35}) -{} -void NormalBattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - m_status_button.make_overlays(items); - m_arrow.make_overlays(items); -} -bool NormalBattleMenuDetector::detect(const ImageViewRGB32& screen){ - if (!m_status_button.detect(screen)){ -// cout << "status button" << endl; - return false; - } - if (!m_arrow.detect(screen)){ - return false; - } - return true; -} -int8_t NormalBattleMenuDetector::detect_slot(const ImageViewRGB32& screen){ - if (!m_status_button.detect(screen)){ -// cout << "status button" << endl; - return -1; - } - - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ - return -1; - } - - double y = box.y + box.height * 0.5; - double slot = (y - 0.67963) / 0.0814815; -// cout << "slot = " << slot << endl; - return (int8_t)(slot + 0.5); -} -bool NormalBattleMenuDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ - if (slot > 3){ - return false; - } - for (size_t attempts = 0;; attempts++){ - if (attempts > 10){ - stream.log("NormalBattleMenuDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); - return false; - } - - context.wait_for_all_requests(); - - VideoSnapshot screen = stream.video().snapshot(); - int8_t current_slot = detect_slot(screen); - if (current_slot < 0 || current_slot > 3){ - stream.log("NormalBattleMenuDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); - context.wait_for(std::chrono::milliseconds(500)); - continue; -// static int c = 0; -// screen->save("bad-" + std::to_string(c++) + ".png"); -// return false; - } - - uint8_t diff = (4 + slot - (uint8_t)current_slot) % 4; - switch (diff){ - case 0:{ -// static int c = 0; -// screen->save("good-" + std::to_string(c++) + ".png"); - return true; - } - case 1: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 2: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 3: - pbf_press_dpad(context, DPAD_UP, 20, 30); - continue; - } - } -} - - - -std::set read_singles_opponent( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - Language language -){ - VideoOverlaySet overlay = stream.overlay(); - - ImageFloatBox name(0.422, 0.131, 0.120, 0.050); - overlay.add(COLOR_RED, name); - - std::set slugs; - - bool status_opened = false; - bool battle_menu_seen = false; - for (size_t c = 0; c < 10; c++){ - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - GradientArrowWatcher arrow(COLOR_BLUE, GradientArrowType::DOWN, {0.4, 0.1, 0.2, 0.5}); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(5), - {battle_menu, arrow} - ); - context.wait_for(std::chrono::milliseconds(500)); - - switch (ret){ - case 0: - if (status_opened){ - stream.log("Detected battle menu..."); - return slugs; - } - stream.log("Detected battle menu. Opening status..."); - battle_menu_seen = true; - pbf_press_button(context, BUTTON_Y, 20, 105); - continue; - - case 1: - if (!battle_menu_seen){ - stream.log("Detected status menu before pressing Y...", COLOR_RED); -// dump_image(stream, info, "BattleMenuNotSeen", arrow.last_detected()); - continue; - } - if (status_opened){ - stream.log("Detected status menu (again)...", COLOR_RED); - }else{ - stream.log("Detected status menu. Reading name..."); - status_opened = true; - VideoSnapshot screen = stream.video().snapshot(); - OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( - stream.logger(), language, - extract_box_reference(screen, name), - OCR::WHITE_TEXT_FILTERS() - ); - for (auto& item : result.results){ - slugs.insert(std::move(item.second.token)); - } - if (slugs.empty()){ - dump_image(stream.logger(), info, "UnableToReadName", screen); - } - } - - pbf_mash_button(context, BUTTON_B, 125); - continue; - - default: - stream.log("No recognized state. Mashing B...", COLOR_RED); - pbf_mash_button(context, BUTTON_B, 250); - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to open status menu to read opponent name.", - stream - ); -} - - - - - -MoveSelectDetector::MoveSelectDetector(Color color) - : m_info_button(color, WhiteButton::ButtonY, {0.35, 0.90, 0.30, 0.08}) - , m_arrow(color, GradientArrowType::RIGHT, {0.705, 0.550, 0.050, 0.410}) -{} -void MoveSelectDetector::make_overlays(VideoOverlaySet& items) const{ - m_info_button.make_overlays(items); - m_arrow.make_overlays(items); -} -bool MoveSelectDetector::detect(const ImageViewRGB32& screen){ - if (!m_info_button.detect(screen)){ -// cout << "status" << endl; - return false; - } - if (!m_arrow.detect(screen)){ -// cout << "arrow" << endl; - return false; - } - return true; -} -int8_t MoveSelectDetector::detect_slot(const ImageViewRGB32& screen){ - if (!m_info_button.detect(screen)){ -// cout << "status" << endl; - return false; - } - - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ -// cout << "arrow" << endl; - return false; - } - - double y = box.y + box.height * 0.5; - y = (y - 0.602778) / 0.103549; -// cout << "y = " << y << endl; - - return (int8_t)(y + 0.5); -} -bool MoveSelectDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ - if (slot > 3){ - return false; - } - for (size_t attempts = 0;; attempts++){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int8_t current_slot = detect_slot(screen); - if (current_slot < 0 || current_slot > 3){ - stream.log("MoveSelectDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); - return false; - } - if (attempts > 10){ - stream.log("MoveSelectDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); - return false; - } - - uint8_t diff = (4 + slot - (uint8_t)current_slot) % 4; - switch (diff){ - case 0: - return true; - case 1: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 2: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 3: - pbf_press_dpad(context, DPAD_UP, 20, 30); - continue; - } - } -} - - - - -TerastallizingDetector::TerastallizingDetector(Color color) - : m_color(color) - , m_box(0.62, 0.75, 0.03, 0.06) -{} -void TerastallizingDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool TerastallizingDetector::detect(const ImageViewRGB32& screen){ - ImageStats box = image_stats(extract_box_reference(screen, m_box)); - // dump_debug_image( - // global_logger_command_line(), - // "Test/TeraDetector", - // "box", - // extract_box_reference(screen, m_box)); - // cout << box.average.sum() << endl; - - return box.average.sum() > 600; -} - - - - -SwapMenuDetector::SwapMenuDetector(Color color) - : m_arrow(color, GradientArrowType::RIGHT, { 0.02, 0.10, 0.05, 0.90 }) -{} -void SwapMenuDetector::make_overlays(VideoOverlaySet& items) const{ - m_arrow.make_overlays(items); -} -bool SwapMenuDetector::detect(const ImageViewRGB32& screen){ - if (!m_arrow.detect(screen)){ - return false; - } - return true; -} -int8_t SwapMenuDetector::detect_slot(const ImageViewRGB32& screen) const{ - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ - return -1; - } - - int slot = (int)((box.y - 0.172222) / 0.116482 + 0.5); - if (slot < 0){ - slot = 0; - } - //cout << "slot = " << slot << endl; - return (int8_t)slot; -} -bool SwapMenuDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot) const{ - if (slot > 5){ - return false; - } - for (size_t attempts = 0;; attempts++){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int8_t current_slot = detect_slot(screen); - if (current_slot < 0 || current_slot > 5){ - stream.log("SwapMenuDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); - return false; - } - if (attempts > 20){ - stream.log("SwapMenuDetector::move_to_slot(): Failed to move slot after 20 attempts.", COLOR_RED); - return false; - } - - uint8_t diff = (6 + slot - (uint8_t)current_slot) % 6; - switch (diff){ - case 0: - return true; - case 1: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 2: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 3: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 4: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 5: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - } - } -} - -WipeoutDetector::WipeoutDetector(Color color) - : m_blackscreen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}) - , m_dialog(color, true, DialogType::DIALOG_WHITE) - , m_arrow_detector(COLOR_BLUE, {0.710, 0.850, 0.030, 0.042}) -{} -void WipeoutDetector::make_overlays(VideoOverlaySet& items) const{ - m_blackscreen.make_overlays(items); - m_dialog.make_overlays(items); - m_arrow_detector.make_overlays(items); -} -bool WipeoutDetector::detect(const ImageViewRGB32& screen){ - if (!m_blackscreen.detect(screen)){ - return false; - } - - if(!m_dialog.detect(screen)){ - return false; - } - - return m_arrow_detector.detect(screen); -} - - -} -} -} +/* Normal Battle Menus + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSV_NormalBattleMenus.h" + + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +NormalBattleMenuDetector::NormalBattleMenuDetector(Color color) + : m_status_button(color, WhiteButton::ButtonY, {0.35, 0.90, 0.30, 0.08}) + , m_arrow(color, GradientArrowType::RIGHT, {0.75, 0.62, 0.05, 0.35}) +{} +void NormalBattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + m_status_button.make_overlays(items); + m_arrow.make_overlays(items); +} +bool NormalBattleMenuDetector::detect(const ImageViewRGB32& screen){ + if (!m_status_button.detect(screen)){ +// cout << "status button" << endl; + return false; + } + if (!m_arrow.detect(screen)){ + return false; + } + return true; +} +int8_t NormalBattleMenuDetector::detect_slot(const ImageViewRGB32& screen){ + if (!m_status_button.detect(screen)){ +// cout << "status button" << endl; + return -1; + } + + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ + return -1; + } + + double y = box.y + box.height * 0.5; + double slot = (y - 0.67963) / 0.0814815; +// cout << "slot = " << slot << endl; + return (int8_t)(slot + 0.5); +} +bool NormalBattleMenuDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ + if (slot > 3){ + return false; + } + for (size_t attempts = 0;; attempts++){ + if (attempts > 10){ + stream.log("NormalBattleMenuDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); + return false; + } + + context.wait_for_all_requests(); + + VideoSnapshot screen = stream.video().snapshot(); + int8_t current_slot = detect_slot(screen); + if (current_slot < 0 || current_slot > 3){ + stream.log("NormalBattleMenuDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); + context.wait_for(std::chrono::milliseconds(500)); + continue; +// static int c = 0; +// screen->save("bad-" + std::to_string(c++) + ".png"); +// return false; + } + + uint8_t diff = (4 + slot - (uint8_t)current_slot) % 4; + switch (diff){ + case 0:{ +// static int c = 0; +// screen->save("good-" + std::to_string(c++) + ".png"); + return true; + } + case 1: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 2: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 3: + pbf_press_dpad(context, DPAD_UP, 20, 30); + continue; + } + } +} + + + +std::set read_singles_opponent( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + Language language +){ + VideoOverlaySet overlay = stream.overlay(); + + ImageFloatBox name(0.422, 0.131, 0.120, 0.050); + overlay.add(COLOR_RED, name); + + std::set slugs; + + bool status_opened = false; + bool battle_menu_seen = false; + for (size_t c = 0; c < 10; c++){ + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + GradientArrowWatcher arrow(COLOR_BLUE, GradientArrowType::DOWN, {0.4, 0.1, 0.2, 0.5}); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(5), + {battle_menu, arrow} + ); + context.wait_for(std::chrono::milliseconds(500)); + + switch (ret){ + case 0: + if (status_opened){ + stream.log("Detected battle menu..."); + return slugs; + } + stream.log("Detected battle menu. Opening status..."); + battle_menu_seen = true; + pbf_press_button(context, BUTTON_Y, 20, 105); + continue; + + case 1: + if (!battle_menu_seen){ + stream.log("Detected status menu before pressing Y...", COLOR_RED); +// dump_image(stream, info, "BattleMenuNotSeen", arrow.last_detected()); + continue; + } + if (status_opened){ + stream.log("Detected status menu (again)...", COLOR_RED); + }else{ + stream.log("Detected status menu. Reading name..."); + status_opened = true; + VideoSnapshot screen = stream.video().snapshot(); + OCR::StringMatchResult result = Pokemon::PokemonNameReader::instance().read_substring( + stream.logger(), language, + extract_box_reference(screen, name), + OCR::WHITE_TEXT_FILTERS() + ); + for (auto& item : result.results){ + slugs.insert(std::move(item.second.token)); + } + if (slugs.empty()){ + dump_image(stream.logger(), info, "UnableToReadName", screen); + } + } + + pbf_mash_button(context, BUTTON_B, 125); + continue; + + default: + stream.log("No recognized state. Mashing B...", COLOR_RED); + pbf_mash_button(context, BUTTON_B, 250); + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to open status menu to read opponent name.", + stream + ); +} + + + + + +MoveSelectDetector::MoveSelectDetector(Color color) + : m_info_button(color, WhiteButton::ButtonY, {0.35, 0.90, 0.30, 0.08}) + , m_arrow(color, GradientArrowType::RIGHT, {0.705, 0.550, 0.050, 0.410}) +{} +void MoveSelectDetector::make_overlays(VideoOverlaySet& items) const{ + m_info_button.make_overlays(items); + m_arrow.make_overlays(items); +} +bool MoveSelectDetector::detect(const ImageViewRGB32& screen){ + if (!m_info_button.detect(screen)){ +// cout << "status" << endl; + return false; + } + if (!m_arrow.detect(screen)){ +// cout << "arrow" << endl; + return false; + } + return true; +} +int8_t MoveSelectDetector::detect_slot(const ImageViewRGB32& screen){ + if (!m_info_button.detect(screen)){ +// cout << "status" << endl; + return false; + } + + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ +// cout << "arrow" << endl; + return false; + } + + double y = box.y + box.height * 0.5; + y = (y - 0.602778) / 0.103549; +// cout << "y = " << y << endl; + + return (int8_t)(y + 0.5); +} +bool MoveSelectDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ + if (slot > 3){ + return false; + } + for (size_t attempts = 0;; attempts++){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int8_t current_slot = detect_slot(screen); + if (current_slot < 0 || current_slot > 3){ + stream.log("MoveSelectDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); + return false; + } + if (attempts > 10){ + stream.log("MoveSelectDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); + return false; + } + + uint8_t diff = (4 + slot - (uint8_t)current_slot) % 4; + switch (diff){ + case 0: + return true; + case 1: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 2: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 3: + pbf_press_dpad(context, DPAD_UP, 20, 30); + continue; + } + } +} + + + + +TerastallizingDetector::TerastallizingDetector(Color color) + : m_color(color) + , m_box(0.62, 0.75, 0.03, 0.06) +{} +void TerastallizingDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool TerastallizingDetector::detect(const ImageViewRGB32& screen){ + ImageStats box = image_stats(extract_box_reference(screen, m_box)); + // dump_debug_image( + // global_logger_command_line(), + // "Test/TeraDetector", + // "box", + // extract_box_reference(screen, m_box)); + // cout << box.average.sum() << endl; + + return box.average.sum() > 600; +} + + + + +SwapMenuDetector::SwapMenuDetector(Color color) + : m_arrow(color, GradientArrowType::RIGHT, { 0.02, 0.10, 0.05, 0.90 }) +{} +void SwapMenuDetector::make_overlays(VideoOverlaySet& items) const{ + m_arrow.make_overlays(items); +} +bool SwapMenuDetector::detect(const ImageViewRGB32& screen){ + if (!m_arrow.detect(screen)){ + return false; + } + return true; +} +int8_t SwapMenuDetector::detect_slot(const ImageViewRGB32& screen) const{ + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ + return -1; + } + + int slot = (int)((box.y - 0.172222) / 0.116482 + 0.5); + if (slot < 0){ + slot = 0; + } + //cout << "slot = " << slot << endl; + return (int8_t)slot; +} +bool SwapMenuDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot) const{ + if (slot > 5){ + return false; + } + for (size_t attempts = 0;; attempts++){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int8_t current_slot = detect_slot(screen); + if (current_slot < 0 || current_slot > 5){ + stream.log("SwapMenuDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); + return false; + } + if (attempts > 20){ + stream.log("SwapMenuDetector::move_to_slot(): Failed to move slot after 20 attempts.", COLOR_RED); + return false; + } + + uint8_t diff = (6 + slot - (uint8_t)current_slot) % 6; + switch (diff){ + case 0: + return true; + case 1: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 2: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 3: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 4: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 5: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + } + } +} + +WipeoutDetector::WipeoutDetector(Color color) + : m_blackscreen(COLOR_RED, {0.1, 0.1, 0.8, 0.6}) + , m_dialog(color, true, DialogType::DIALOG_WHITE) + , m_arrow_detector(COLOR_BLUE, {0.710, 0.850, 0.030, 0.042}) +{} +void WipeoutDetector::make_overlays(VideoOverlaySet& items) const{ + m_blackscreen.make_overlays(items); + m_dialog.make_overlays(items); + m_arrow_detector.make_overlays(items); +} +bool WipeoutDetector::detect(const ImageViewRGB32& screen){ + if (!m_blackscreen.detect(screen)){ + return false; + } + + if(!m_dialog.detect(screen)){ + return false; + } + + return m_arrow_detector.detect(screen); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h index 42cc593499..b4ca10181f 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h @@ -1,144 +1,144 @@ -/* Normal Battle Menus - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_NormalBattleMenus_H -#define PokemonAutomation_PokemonSV_NormalBattleMenus_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetector.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h" - - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class NormalBattleMenuDetector : public StaticScreenDetector{ -public: - NormalBattleMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Returns -1 if not found. - int8_t detect_slot(const ImageViewRGB32& screen); - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); - -private: - WhiteButtonDetector m_status_button; - GradientArrowDetector m_arrow; -}; -class NormalBattleMenuWatcher : public DetectorToFinder{ -public: - NormalBattleMenuWatcher(Color color) - : DetectorToFinder("NormalBattleMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - -std::set read_singles_opponent( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - Language language -); - - - -class MoveSelectDetector : public StaticScreenDetector{ -public: - MoveSelectDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Returns -1 if not found. - int8_t detect_slot(const ImageViewRGB32& screen); - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); - -private: - WhiteButtonDetector m_info_button; - GradientArrowDetector m_arrow; -}; -class MoveSelectWatcher : public DetectorToFinder{ -public: - MoveSelectWatcher(Color color) - : DetectorToFinder("MoveSelectWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -class TerastallizingDetector : public StaticScreenDetector{ -public: - TerastallizingDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; - - - -class SwapMenuDetector : public StaticScreenDetector{ -public: - SwapMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Returns -1 if not found. - int8_t detect_slot(const ImageViewRGB32& screen) const; - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot) const; - -private: - GradientArrowDetector m_arrow; -}; -class SwapMenuWatcher : public DetectorToFinder{ -public: - SwapMenuWatcher(Color color) - : DetectorToFinder("SwapMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - -class WipeoutDetector : public StaticScreenDetector{ -public: - WipeoutDetector(Color color = COLOR_CYAN); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // return true if detects a black screen, black dialog box, and dialog arrow. - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - BlackScreenDetector m_blackscreen; - DialogBoxDetector m_dialog; - DialogArrowDetector m_arrow_detector; -}; -class WipeoutWatcher : public DetectorToFinder{ -public: - WipeoutWatcher(Color color = COLOR_CYAN) - : DetectorToFinder("WipeoutWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - - -} -} -} -#endif +/* Normal Battle Menus + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_NormalBattleMenus_H +#define PokemonAutomation_PokemonSV_NormalBattleMenus_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetector.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h" + + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class NormalBattleMenuDetector : public StaticScreenDetector{ +public: + NormalBattleMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Returns -1 if not found. + int8_t detect_slot(const ImageViewRGB32& screen); + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); + +private: + WhiteButtonDetector m_status_button; + GradientArrowDetector m_arrow; +}; +class NormalBattleMenuWatcher : public DetectorToFinder{ +public: + NormalBattleMenuWatcher(Color color) + : DetectorToFinder("NormalBattleMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + +std::set read_singles_opponent( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + Language language +); + + + +class MoveSelectDetector : public StaticScreenDetector{ +public: + MoveSelectDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Returns -1 if not found. + int8_t detect_slot(const ImageViewRGB32& screen); + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); + +private: + WhiteButtonDetector m_info_button; + GradientArrowDetector m_arrow; +}; +class MoveSelectWatcher : public DetectorToFinder{ +public: + MoveSelectWatcher(Color color) + : DetectorToFinder("MoveSelectWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +class TerastallizingDetector : public StaticScreenDetector{ +public: + TerastallizingDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; + + + +class SwapMenuDetector : public StaticScreenDetector{ +public: + SwapMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Returns -1 if not found. + int8_t detect_slot(const ImageViewRGB32& screen) const; + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot) const; + +private: + GradientArrowDetector m_arrow; +}; +class SwapMenuWatcher : public DetectorToFinder{ +public: + SwapMenuWatcher(Color color) + : DetectorToFinder("SwapMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + +class WipeoutDetector : public StaticScreenDetector{ +public: + WipeoutDetector(Color color = COLOR_CYAN); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // return true if detects a black screen, black dialog box, and dialog arrow. + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + BlackScreenDetector m_blackscreen; + DialogBoxDetector m_dialog; + DialogArrowDetector m_arrow_detector; +}; +class WipeoutWatcher : public DetectorToFinder{ +public: + WipeoutWatcher(Color color = COLOR_CYAN) + : DetectorToFinder("WipeoutWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.cpp index 5c4d6d89f6..ac012ede93 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.cpp @@ -1,68 +1,68 @@ -/* Post-Catch Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_PostCatchDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -AddToPartyDetector::AddToPartyDetector(Color color) - : m_color(color) - , m_top_left(0.35, 0.12, 0.10, 0.05) - , m_top_right(0.55, 0.12, 0.10, 0.05) - , m_bottom_left(0.15, 0.83, 0.08, 0.05) - , m_bottom_right(0.77, 0.83, 0.08, 0.05) - , m_dialog(color) -{} -void AddToPartyDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_top_left); - items.add(m_color, m_top_right); - items.add(m_color, m_bottom_left); - items.add(m_color, m_bottom_right); - m_dialog.make_overlays(items); -} -bool AddToPartyDetector::detect(const ImageViewRGB32& screen){ - ImageStats top_left = image_stats(extract_box_reference(screen, m_top_left)); -// cout << top_left.average << top_left.stddev << endl; - if (!is_white(top_left)){ - return false; - } - - ImageStats top_right = image_stats(extract_box_reference(screen, m_top_right)); -// cout << top_right.average << top_right.stddev << endl; - if (!is_white(top_right)){ - return false; - } - - ImageStats bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); -// cout << top_left.average << top_left.stddev << endl; - if (!is_white(bottom_left)){ - return false; - } - - ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << top_right.average << top_right.stddev << endl; - if (!is_white(bottom_right)){ - return false; - } - - return m_dialog.detect(screen); -} - - - - - - - -} -} -} +/* Post-Catch Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_PostCatchDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +AddToPartyDetector::AddToPartyDetector(Color color) + : m_color(color) + , m_top_left(0.35, 0.12, 0.10, 0.05) + , m_top_right(0.55, 0.12, 0.10, 0.05) + , m_bottom_left(0.15, 0.83, 0.08, 0.05) + , m_bottom_right(0.77, 0.83, 0.08, 0.05) + , m_dialog(color) +{} +void AddToPartyDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_top_left); + items.add(m_color, m_top_right); + items.add(m_color, m_bottom_left); + items.add(m_color, m_bottom_right); + m_dialog.make_overlays(items); +} +bool AddToPartyDetector::detect(const ImageViewRGB32& screen){ + ImageStats top_left = image_stats(extract_box_reference(screen, m_top_left)); +// cout << top_left.average << top_left.stddev << endl; + if (!is_white(top_left)){ + return false; + } + + ImageStats top_right = image_stats(extract_box_reference(screen, m_top_right)); +// cout << top_right.average << top_right.stddev << endl; + if (!is_white(top_right)){ + return false; + } + + ImageStats bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); +// cout << top_left.average << top_left.stddev << endl; + if (!is_white(bottom_left)){ + return false; + } + + ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << top_right.average << top_right.stddev << endl; + if (!is_white(bottom_right)){ + return false; + } + + return m_dialog.detect(screen); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h index fe75758e45..431d5a0a79 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_PostCatchDetector.h @@ -1,51 +1,51 @@ -/* Post-Catch Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PostCatchDetector_H -#define PokemonAutomation_PokemonSV_PostCatchDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AddToPartyDetector : public StaticScreenDetector{ -public: - AddToPartyDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -protected: - Color m_color; - ImageFloatBox m_top_left; - ImageFloatBox m_top_right; - ImageFloatBox m_bottom_left; - ImageFloatBox m_bottom_right; - PromptDialogDetector m_dialog; -}; -class AddToPartyWatcher : public DetectorToFinder{ -public: - AddToPartyWatcher(Color color = COLOR_RED) - : DetectorToFinder("AddToPartyFinder", std::chrono::milliseconds(250), color) - {} -}; - - - - - - -} -} -} -#endif +/* Post-Catch Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PostCatchDetector_H +#define PokemonAutomation_PokemonSV_PostCatchDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AddToPartyDetector : public StaticScreenDetector{ +public: + AddToPartyDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +protected: + Color m_color; + ImageFloatBox m_top_left; + ImageFloatBox m_top_right; + ImageFloatBox m_bottom_left; + ImageFloatBox m_bottom_right; + PromptDialogDetector m_dialog; +}; +class AddToPartyWatcher : public DetectorToFinder{ +public: + AddToPartyWatcher(Color color = COLOR_RED) + : DetectorToFinder("AddToPartyFinder", std::chrono::milliseconds(250), color) + {} +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp index 42715958b4..dd0762c28a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.cpp @@ -1,43 +1,43 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV_ShinySoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) - // Use a yellow as the detection color because the shiny animation is yellow. - : AudioPerSpectrumDetectorBase( - logger, - "ShinySoundDetector", - "Shiny sound", - COLOR_YELLOW, - detected_callback - ) -{} -float ShinySoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD2; -} -std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Shiny Sound", - AudioTemplateCache::instance().get_throw("PokemonSV/ShinySound", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY - ); -} - - - -} -} -} +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV_ShinySoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +ShinySoundDetector::ShinySoundDetector(Logger& logger, DetectedCallback detected_callback) + // Use a yellow as the detection color because the shiny animation is yellow. + : AudioPerSpectrumDetectorBase( + logger, + "ShinySoundDetector", + "Shiny sound", + COLOR_YELLOW, + detected_callback + ) +{} +float ShinySoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().SHINY_SOUND_THRESHOLD2; +} +std::unique_ptr ShinySoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Shiny Sound", + AudioTemplateCache::instance().get_throw("PokemonSV/ShinySound", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().SHINY_SOUND_LOW_FREQUENCY + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h index 8edbf1a9e0..0744cb4a2c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h @@ -1,33 +1,33 @@ -/* Shiny Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ShinySoundDetector_H -#define PokemonAutomation_PokemonSV_ShinySoundDetector_H - -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ -public: - ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); - - virtual float get_score_threshold() const override; - -protected: - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; -}; - - - - -} -} -} -#endif +/* Shiny Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ShinySoundDetector_H +#define PokemonAutomation_PokemonSV_ShinySoundDetector_H + +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class ShinySoundDetector : public AudioPerSpectrumDetectorBase{ +public: + ShinySoundDetector(Logger& logger, DetectedCallback detected_callback); + + virtual float get_score_threshold() const override; + +protected: + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp index db83fe997f..60bbebcbee 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.cpp @@ -1,354 +1,354 @@ -/* Tera Battle Menus - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_TeraBattleMenus.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -TeraBattleMenuDetector::TeraBattleMenuDetector(Color color) - : m_callouts_button(color, WhiteButton::ButtonMinus, {0.35, 0.87, 0.30, 0.05}) - , m_arrow(color, GradientArrowType::RIGHT, {0.75, 0.62, 0.05, 0.35}) -{} -void TeraBattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - m_callouts_button.make_overlays(items); - m_arrow.make_overlays(items); -} -bool TeraBattleMenuDetector::detect(const ImageViewRGB32& screen){ - if (!m_callouts_button.detect(screen)){ -// cout << "status button" << endl; - return false; - } - if (!m_arrow.detect(screen)){ -// cout << "arrow" << endl; - return false; - } - return true; -} -int8_t TeraBattleMenuDetector::detect_slot(const ImageViewRGB32& screen){ - if (!m_callouts_button.detect(screen)){ -// cout << "status button" << endl; - return -1; - } - - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ -// cout << "arrow" << endl; -// screen.save("test.png"); - return -1; - } - - double y = box.y + box.height * 0.5; - double slot = (y - 0.761111) / 0.0814815; -// cout << "slot = " << slot << endl; - return (int8_t)(slot + 0.5); -} -bool TeraBattleMenuDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ - if (slot > 2){ - return false; - } - for (size_t attempts = 0;; attempts++){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int8_t current_slot = detect_slot(screen); - if (current_slot < 0 || current_slot > 2){ - stream.log("TeraBattleMenuDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); - return false; - } - if (attempts > 10){ - stream.log("TeraBattleMenuDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); - return false; - } - - uint8_t diff = (3 + slot - (uint8_t)current_slot) % 3; - switch (diff){ - case 0: - return true; - case 1: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 2: - pbf_press_dpad(context, DPAD_UP, 20, 30); - continue; - } - } -} - - - - - -CheerSelectDetector::CheerSelectDetector(Color color) - : m_info_button(color, WhiteButton::ButtonY, {0.35, 0.90, 0.30, 0.08}) - , m_arrow(color, GradientArrowType::RIGHT, {0.705, 0.710, 0.050, 0.260}) -{} -void CheerSelectDetector::make_overlays(VideoOverlaySet& items) const{ - m_info_button.make_overlays(items); - m_arrow.make_overlays(items); -} -bool CheerSelectDetector::detect(const ImageViewRGB32& screen){ - if (m_info_button.detect(screen)){ -// cout << "status" << endl; - return false; - } - if (!m_arrow.detect(screen)){ -// cout << "arrow" << endl; - return false; - } - return true; -} -int8_t CheerSelectDetector::detect_slot(const ImageViewRGB32& screen){ - if (m_info_button.detect(screen)){ -// cout << "status" << endl; - return false; - } - - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ -// cout << "arrow" << endl; - return false; - } - - double y = box.y + box.height * 0.5; - y = (y - 0.758333) / 0.082639; -// cout << "y = " << y << endl; - - return (int8_t)(y + 0.5); -} -bool CheerSelectDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ - if (slot > 2){ - return false; - } - for (size_t attempts = 0;; attempts++){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int8_t current_slot = detect_slot(screen); - if (current_slot < 0 || current_slot > 2){ - stream.log("CheerSelectDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); - return false; - } - if (attempts > 10){ - stream.log("CheerSelectDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); - return false; - } - - uint8_t diff = (3 + slot - (uint8_t)current_slot) % 3; - switch (diff){ - case 0: - return true; - case 1: - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - case 2: - pbf_press_dpad(context, DPAD_UP, 20, 30); - continue; - } - } -} - - - - - -TeraTargetSelectDetector::TeraTargetSelectDetector(Color color) - : m_opponent(color, GradientArrowType::DOWN, {0.45, 0.07, 0.10, 0.10}) - , m_player0(color, GradientArrowType::DOWN, {0.20, 0.46, 0.10, 0.10}) - , m_player1(color, GradientArrowType::DOWN, {0.37, 0.46, 0.10, 0.10}) - , m_player2(color, GradientArrowType::DOWN, {0.53, 0.46, 0.10, 0.10}) - , m_player3(color, GradientArrowType::DOWN, {0.70, 0.46, 0.10, 0.10}) -{} -void TeraTargetSelectDetector::make_overlays(VideoOverlaySet& items) const{ - m_opponent.make_overlays(items); - m_player0.make_overlays(items); - m_player1.make_overlays(items); - m_player2.make_overlays(items); - m_player3.make_overlays(items); -} -bool TeraTargetSelectDetector::detect(const ImageViewRGB32& screen){ - if (m_opponent.detect(screen)){ - return true; - } - if (m_player0.detect(screen)){ - return true; - } - if (m_player1.detect(screen)){ - return true; - } - if (m_player2.detect(screen)){ - return true; - } - if (m_player3.detect(screen)){ - return true; - } - return false; -} -int8_t TeraTargetSelectDetector::detect_slot(const ImageViewRGB32& screen){ - if (m_opponent.detect(screen)){ - return 0; - } - if (m_player0.detect(screen)){ - return 1; - } - if (m_player1.detect(screen)){ - return 2; - } - if (m_player2.detect(screen)){ - return 3; - } - if (m_player3.detect(screen)){ - return 4; - } - return -1; -} -bool TeraTargetSelectDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ - if (slot > 4){ - return false; - } - for (size_t attempts = 0;; attempts++){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int8_t current_slot = detect_slot(screen); - if (current_slot < 0 || current_slot > 4){ - stream.log("TargetSelectDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); - return false; - } - if (attempts > 10){ - stream.log("TargetSelectDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); - return false; - } - - if (current_slot == 0 && slot != 0){ - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - continue; - } - if (current_slot != 0 && slot == 0){ - pbf_press_dpad(context, DPAD_UP, 20, 30); - continue; - } - - uint8_t diff = (4 + slot - (uint8_t)current_slot) % 4; - switch (diff){ - case 0: - return true; - case 1: - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - continue; - case 2: - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - continue; - case 3: - pbf_press_dpad(context, DPAD_LEFT, 20, 30); - continue; - } - } -} - - - - - -TeraCatchDetector::TeraCatchDetector(Color color) - : m_color(color) - , m_callouts_button(color, WhiteButton::ButtonMinus, {0.35, 0.87, 0.30, 0.05}) -{ - m_button[0] = {0.801, 0.818, 0.005, 0.047}; - m_button[1] = {0.801, 0.900, 0.005, 0.047}; - m_box_right[0] = {0.95, 0.810, 0.02, 0.06}; - m_box_right[1] = {0.95, 0.892, 0.02, 0.06}; - m_arrow.emplace_back(color, GradientArrowType::RIGHT, ImageFloatBox(0.75, 0.800, 0.08, 0.09)); - m_arrow.emplace_back(color, GradientArrowType::RIGHT, ImageFloatBox(0.75, 0.878, 0.08, 0.09)); -} -void TeraCatchDetector::make_overlays(VideoOverlaySet& items) const{ - for (int c = 0; c < 2; c++){ - items.add(m_color, m_button[c]); - items.add(m_color, m_box_right[c]); - m_arrow[c].make_overlays(items); - } -} - -bool TeraCatchDetector::detect_slot(const ImageViewRGB32& screen, size_t index){ - ImageStats button = image_stats(extract_box_reference(screen, m_button[index])); -// cout << button.average << button.stddev << endl; -// extract_box_reference(screen, m_button).save("button.png"); - - ImageStats yellow = image_stats(extract_box_reference(screen, m_box_right[index])); -// cout << yellow.average << yellow.stddev << endl; -// extract_box_reference(screen, m_slot0_box_right).save("yellow.png"); - - bool button_ok = is_solid(button, {0.117281, 0.311767, 0.570951}, 0.20, 20) || is_black(button, 100, 20); - bool yellow_ok = is_solid(yellow, {0.554348, 0.445652, 0.}, 0.15, 20); - if (!button_ok && !yellow_ok){ -// cout << "button and yellow bad" << endl; - return false; - } - - if (!m_arrow[index].detect(screen)){ -// cout << "arrow bad" << endl; - return false; - } - - return true; -} -bool TeraCatchDetector::detect(const ImageViewRGB32& screen){ - if (m_callouts_button.detect(screen)){ - return false; - } - - return detect_slot(screen, 0) || detect_slot(screen, 1); -} - -bool TeraCatchDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ - if (slot > 1){ - return false; - } - - for (size_t attempts = 0; attempts < 10; attempts++){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - - if (m_callouts_button.detect(screen)){ - stream.log("TeraCatchDetector::move_to_slot(): Unable to detect catch buttons.", COLOR_RED); - return false; - } - - bool slot0 = detect_slot(screen, 0); - bool slot1 = detect_slot(screen, 1); - if (slot0 == slot1){ - stream.log("TeraCatchDetector::move_to_slot(): Unable to detect catch buttons.", COLOR_RED); - return false; - } - - uint8_t current_slot = slot1 ? 1 : 0; - - if (current_slot == slot){ - return true; - } - - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - - stream.log("TeraCatchDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); - return false; -} - - - - - - -} -} -} +/* Tera Battle Menus + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_TeraBattleMenus.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +TeraBattleMenuDetector::TeraBattleMenuDetector(Color color) + : m_callouts_button(color, WhiteButton::ButtonMinus, {0.35, 0.87, 0.30, 0.05}) + , m_arrow(color, GradientArrowType::RIGHT, {0.75, 0.62, 0.05, 0.35}) +{} +void TeraBattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + m_callouts_button.make_overlays(items); + m_arrow.make_overlays(items); +} +bool TeraBattleMenuDetector::detect(const ImageViewRGB32& screen){ + if (!m_callouts_button.detect(screen)){ +// cout << "status button" << endl; + return false; + } + if (!m_arrow.detect(screen)){ +// cout << "arrow" << endl; + return false; + } + return true; +} +int8_t TeraBattleMenuDetector::detect_slot(const ImageViewRGB32& screen){ + if (!m_callouts_button.detect(screen)){ +// cout << "status button" << endl; + return -1; + } + + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ +// cout << "arrow" << endl; +// screen.save("test.png"); + return -1; + } + + double y = box.y + box.height * 0.5; + double slot = (y - 0.761111) / 0.0814815; +// cout << "slot = " << slot << endl; + return (int8_t)(slot + 0.5); +} +bool TeraBattleMenuDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ + if (slot > 2){ + return false; + } + for (size_t attempts = 0;; attempts++){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int8_t current_slot = detect_slot(screen); + if (current_slot < 0 || current_slot > 2){ + stream.log("TeraBattleMenuDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); + return false; + } + if (attempts > 10){ + stream.log("TeraBattleMenuDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); + return false; + } + + uint8_t diff = (3 + slot - (uint8_t)current_slot) % 3; + switch (diff){ + case 0: + return true; + case 1: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 2: + pbf_press_dpad(context, DPAD_UP, 20, 30); + continue; + } + } +} + + + + + +CheerSelectDetector::CheerSelectDetector(Color color) + : m_info_button(color, WhiteButton::ButtonY, {0.35, 0.90, 0.30, 0.08}) + , m_arrow(color, GradientArrowType::RIGHT, {0.705, 0.710, 0.050, 0.260}) +{} +void CheerSelectDetector::make_overlays(VideoOverlaySet& items) const{ + m_info_button.make_overlays(items); + m_arrow.make_overlays(items); +} +bool CheerSelectDetector::detect(const ImageViewRGB32& screen){ + if (m_info_button.detect(screen)){ +// cout << "status" << endl; + return false; + } + if (!m_arrow.detect(screen)){ +// cout << "arrow" << endl; + return false; + } + return true; +} +int8_t CheerSelectDetector::detect_slot(const ImageViewRGB32& screen){ + if (m_info_button.detect(screen)){ +// cout << "status" << endl; + return false; + } + + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ +// cout << "arrow" << endl; + return false; + } + + double y = box.y + box.height * 0.5; + y = (y - 0.758333) / 0.082639; +// cout << "y = " << y << endl; + + return (int8_t)(y + 0.5); +} +bool CheerSelectDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ + if (slot > 2){ + return false; + } + for (size_t attempts = 0;; attempts++){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int8_t current_slot = detect_slot(screen); + if (current_slot < 0 || current_slot > 2){ + stream.log("CheerSelectDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); + return false; + } + if (attempts > 10){ + stream.log("CheerSelectDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); + return false; + } + + uint8_t diff = (3 + slot - (uint8_t)current_slot) % 3; + switch (diff){ + case 0: + return true; + case 1: + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + case 2: + pbf_press_dpad(context, DPAD_UP, 20, 30); + continue; + } + } +} + + + + + +TeraTargetSelectDetector::TeraTargetSelectDetector(Color color) + : m_opponent(color, GradientArrowType::DOWN, {0.45, 0.07, 0.10, 0.10}) + , m_player0(color, GradientArrowType::DOWN, {0.20, 0.46, 0.10, 0.10}) + , m_player1(color, GradientArrowType::DOWN, {0.37, 0.46, 0.10, 0.10}) + , m_player2(color, GradientArrowType::DOWN, {0.53, 0.46, 0.10, 0.10}) + , m_player3(color, GradientArrowType::DOWN, {0.70, 0.46, 0.10, 0.10}) +{} +void TeraTargetSelectDetector::make_overlays(VideoOverlaySet& items) const{ + m_opponent.make_overlays(items); + m_player0.make_overlays(items); + m_player1.make_overlays(items); + m_player2.make_overlays(items); + m_player3.make_overlays(items); +} +bool TeraTargetSelectDetector::detect(const ImageViewRGB32& screen){ + if (m_opponent.detect(screen)){ + return true; + } + if (m_player0.detect(screen)){ + return true; + } + if (m_player1.detect(screen)){ + return true; + } + if (m_player2.detect(screen)){ + return true; + } + if (m_player3.detect(screen)){ + return true; + } + return false; +} +int8_t TeraTargetSelectDetector::detect_slot(const ImageViewRGB32& screen){ + if (m_opponent.detect(screen)){ + return 0; + } + if (m_player0.detect(screen)){ + return 1; + } + if (m_player1.detect(screen)){ + return 2; + } + if (m_player2.detect(screen)){ + return 3; + } + if (m_player3.detect(screen)){ + return 4; + } + return -1; +} +bool TeraTargetSelectDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ + if (slot > 4){ + return false; + } + for (size_t attempts = 0;; attempts++){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int8_t current_slot = detect_slot(screen); + if (current_slot < 0 || current_slot > 4){ + stream.log("TargetSelectDetector::move_to_slot(): Unable to detect slot.", COLOR_RED); + return false; + } + if (attempts > 10){ + stream.log("TargetSelectDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); + return false; + } + + if (current_slot == 0 && slot != 0){ + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + continue; + } + if (current_slot != 0 && slot == 0){ + pbf_press_dpad(context, DPAD_UP, 20, 30); + continue; + } + + uint8_t diff = (4 + slot - (uint8_t)current_slot) % 4; + switch (diff){ + case 0: + return true; + case 1: + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + continue; + case 2: + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + continue; + case 3: + pbf_press_dpad(context, DPAD_LEFT, 20, 30); + continue; + } + } +} + + + + + +TeraCatchDetector::TeraCatchDetector(Color color) + : m_color(color) + , m_callouts_button(color, WhiteButton::ButtonMinus, {0.35, 0.87, 0.30, 0.05}) +{ + m_button[0] = {0.801, 0.818, 0.005, 0.047}; + m_button[1] = {0.801, 0.900, 0.005, 0.047}; + m_box_right[0] = {0.95, 0.810, 0.02, 0.06}; + m_box_right[1] = {0.95, 0.892, 0.02, 0.06}; + m_arrow.emplace_back(color, GradientArrowType::RIGHT, ImageFloatBox(0.75, 0.800, 0.08, 0.09)); + m_arrow.emplace_back(color, GradientArrowType::RIGHT, ImageFloatBox(0.75, 0.878, 0.08, 0.09)); +} +void TeraCatchDetector::make_overlays(VideoOverlaySet& items) const{ + for (int c = 0; c < 2; c++){ + items.add(m_color, m_button[c]); + items.add(m_color, m_box_right[c]); + m_arrow[c].make_overlays(items); + } +} + +bool TeraCatchDetector::detect_slot(const ImageViewRGB32& screen, size_t index){ + ImageStats button = image_stats(extract_box_reference(screen, m_button[index])); +// cout << button.average << button.stddev << endl; +// extract_box_reference(screen, m_button).save("button.png"); + + ImageStats yellow = image_stats(extract_box_reference(screen, m_box_right[index])); +// cout << yellow.average << yellow.stddev << endl; +// extract_box_reference(screen, m_slot0_box_right).save("yellow.png"); + + bool button_ok = is_solid(button, {0.117281, 0.311767, 0.570951}, 0.20, 20) || is_black(button, 100, 20); + bool yellow_ok = is_solid(yellow, {0.554348, 0.445652, 0.}, 0.15, 20); + if (!button_ok && !yellow_ok){ +// cout << "button and yellow bad" << endl; + return false; + } + + if (!m_arrow[index].detect(screen)){ +// cout << "arrow bad" << endl; + return false; + } + + return true; +} +bool TeraCatchDetector::detect(const ImageViewRGB32& screen){ + if (m_callouts_button.detect(screen)){ + return false; + } + + return detect_slot(screen, 0) || detect_slot(screen, 1); +} + +bool TeraCatchDetector::move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot){ + if (slot > 1){ + return false; + } + + for (size_t attempts = 0; attempts < 10; attempts++){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + + if (m_callouts_button.detect(screen)){ + stream.log("TeraCatchDetector::move_to_slot(): Unable to detect catch buttons.", COLOR_RED); + return false; + } + + bool slot0 = detect_slot(screen, 0); + bool slot1 = detect_slot(screen, 1); + if (slot0 == slot1){ + stream.log("TeraCatchDetector::move_to_slot(): Unable to detect catch buttons.", COLOR_RED); + return false; + } + + uint8_t current_slot = slot1 ? 1 : 0; + + if (current_slot == slot){ + return true; + } + + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + + stream.log("TeraCatchDetector::move_to_slot(): Failed to move slot after 10 attempts.", COLOR_RED); + return false; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h index b14f6f38cb..029ddb7189 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h @@ -1,136 +1,136 @@ -/* Tera Battle Menus - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraBattleMenus_H -#define PokemonAutomation_PokemonSV_TeraBattleMenus_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraBattleMenuDetector : public StaticScreenDetector{ -public: - TeraBattleMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Returns -1 if not found. - int8_t detect_slot(const ImageViewRGB32& screen); - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); - -private: - WhiteButtonDetector m_callouts_button; - GradientArrowDetector m_arrow; -}; -class TeraBattleMenuWatcher : public DetectorToFinder{ -public: - TeraBattleMenuWatcher(Color color) - : DetectorToFinder("TeraBattleMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - -class CheerSelectDetector : public StaticScreenDetector{ -public: - CheerSelectDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Returns -1 if not found. - int8_t detect_slot(const ImageViewRGB32& screen); - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); - -private: - WhiteButtonDetector m_info_button; - GradientArrowDetector m_arrow; -}; -class CheerSelectWatcher : public DetectorToFinder{ -public: - CheerSelectWatcher(Color color) - : DetectorToFinder("CheerSelectWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -class TeraTargetSelectDetector : public StaticScreenDetector{ -public: - TeraTargetSelectDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Returns -1 if not found. - // Returns 0 if opponent. - // Returns 1 if left-most player. - // Returns 4 if right-most player. - int8_t detect_slot(const ImageViewRGB32& screen); - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); - -private: - GradientArrowDetector m_opponent; - GradientArrowDetector m_player0; - GradientArrowDetector m_player1; - GradientArrowDetector m_player2; - GradientArrowDetector m_player3; -}; -class TargetSelectWatcher : public DetectorToFinder{ -public: - TargetSelectWatcher(Color color) - : DetectorToFinder("TargetSelectWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -class TeraCatchDetector : public StaticScreenDetector{ -public: - TeraCatchDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); - -private: - bool detect_slot(const ImageViewRGB32& screen, size_t index); - -private: - Color m_color; - WhiteButtonDetector m_callouts_button; - - ImageFloatBox m_button[2]; - ImageFloatBox m_box_right[2]; - std::vector m_arrow; -}; -class TeraCatchWatcher : public DetectorToFinder{ -public: - TeraCatchWatcher(Color color) - : DetectorToFinder("TeraCatchWatcher", std::chrono::milliseconds(1000), color) - {} -}; - - - - - -} -} -} -#endif +/* Tera Battle Menus + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraBattleMenus_H +#define PokemonAutomation_PokemonSV_TeraBattleMenus_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraBattleMenuDetector : public StaticScreenDetector{ +public: + TeraBattleMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Returns -1 if not found. + int8_t detect_slot(const ImageViewRGB32& screen); + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); + +private: + WhiteButtonDetector m_callouts_button; + GradientArrowDetector m_arrow; +}; +class TeraBattleMenuWatcher : public DetectorToFinder{ +public: + TeraBattleMenuWatcher(Color color) + : DetectorToFinder("TeraBattleMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + +class CheerSelectDetector : public StaticScreenDetector{ +public: + CheerSelectDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Returns -1 if not found. + int8_t detect_slot(const ImageViewRGB32& screen); + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); + +private: + WhiteButtonDetector m_info_button; + GradientArrowDetector m_arrow; +}; +class CheerSelectWatcher : public DetectorToFinder{ +public: + CheerSelectWatcher(Color color) + : DetectorToFinder("CheerSelectWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +class TeraTargetSelectDetector : public StaticScreenDetector{ +public: + TeraTargetSelectDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Returns -1 if not found. + // Returns 0 if opponent. + // Returns 1 if left-most player. + // Returns 4 if right-most player. + int8_t detect_slot(const ImageViewRGB32& screen); + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); + +private: + GradientArrowDetector m_opponent; + GradientArrowDetector m_player0; + GradientArrowDetector m_player1; + GradientArrowDetector m_player2; + GradientArrowDetector m_player3; +}; +class TargetSelectWatcher : public DetectorToFinder{ +public: + TargetSelectWatcher(Color color) + : DetectorToFinder("TargetSelectWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +class TeraCatchDetector : public StaticScreenDetector{ +public: + TeraCatchDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + bool move_to_slot(VideoStream& stream, ProControllerContext& context, uint8_t slot); + +private: + bool detect_slot(const ImageViewRGB32& screen, size_t index); + +private: + Color m_color; + WhiteButtonDetector m_callouts_button; + + ImageFloatBox m_button[2]; + ImageFloatBox m_box_right[2]; + std::vector m_arrow; +}; +class TeraCatchWatcher : public DetectorToFinder{ +public: + TeraCatchWatcher(Color color) + : DetectorToFinder("TeraCatchWatcher", std::chrono::milliseconds(1000), color) + {} +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp index 6e28995fa7..9d55f1e96d 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.cpp @@ -1,436 +1,436 @@ -/* Box Detection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_BoxDetection.h" - -#include -using std::cout; -using std::endl;; - -namespace PokemonAutomation{ - -template class FixedLimitVector; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -std::string BOX_CURSOR_LOCATION_NAMES(BoxCursorLocation location){ - switch(location){ - case BoxCursorLocation::NONE: - return "NONE"; - case BoxCursorLocation::PARTY: - return "PARTY"; - case BoxCursorLocation::BOX_CHANGE: - return "BOX_CHANGE"; - case BoxCursorLocation::ALL_BOXES: - return "ALL_BOXES"; - case BoxCursorLocation::SEARCH: - return "SEARCH"; - case BoxCursorLocation::SLOTS: - return "SLOTS"; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown BoxCursorLocation"); - } -} - -std::string BOX_LOCATION_STRING(BoxCursorLocation location, uint8_t row, uint8_t col){ - return "(" + BOX_CURSOR_LOCATION_NAMES(location) + " row " + std::to_string(row) + " col " + std::to_string(col) + ")"; -} - - -SomethingInBoxSlotDetector::SomethingInBoxSlotDetector(Color color, bool true_if_exists) - : m_true_if_exists(true_if_exists) - , m_color(color) - , m_right(0.985, 0.010, 0.010, 0.050) - , m_top(0.660, 0.005, 0.330, 0.006) - , m_bottom(0.660, 0.064, 0.330, 0.005) - , m_body(0.670, 0.010, 0.060, 0.050) -{} -void SomethingInBoxSlotDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_right); - items.add(m_color, m_top); - items.add(m_color, m_bottom); - items.add(m_color, m_body); -} -bool SomethingInBoxSlotDetector::detect(const ImageViewRGB32& screen){ - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// extract_box_reference(screen, m_right).save("test.png"); -// cout << right.average << right.stddev << endl; - if (!is_solid(right, {0.533473, 0.466527, 0.0}, 0.15, 20)){ -// cout << "asdf" << endl; - return !m_true_if_exists; - } - ImageStats top = image_stats(extract_box_reference(screen, m_top)); -// cout << top.average << top.stddev << endl; - if (!is_solid(top, {0.533473, 0.466527, 0.0})){ -// cout << "qwer" << endl; - return !m_true_if_exists; - } - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; -// extract_box_reference(screen, m_bottom).save("./tmp_bottom.png"); - if (!is_solid(bottom, {0.533473, 0.466527, 0.0}, 0.15, 15.0)){ -// cout << "zxcv" << endl; - return !m_true_if_exists; - } - ImageStats body = image_stats(extract_box_reference(screen, m_body)); -// cout << body.average << body.stddev << endl; - if (body.stddev.sum() < 100){ - return !m_true_if_exists; - } - - return m_true_if_exists; -} - - - - -BoxSelectDetector::BoxSelectDetector(Color color) - : m_color(color) - , m_exists(color, true) - , m_dialog(color) - , m_gradient(color, GradientArrowType::RIGHT, {0.20, 0.17, 0.50, 0.10}) -{} -void BoxSelectDetector::make_overlays(VideoOverlaySet& items) const{ - m_exists.make_overlays(items); - m_dialog.make_overlays(items); - m_gradient.make_overlays(items); -} -bool BoxSelectDetector::exists(const ImageViewRGB32& screen){ - return m_exists.detect(screen); -} -bool BoxSelectDetector::detect(const ImageViewRGB32& screen){ - if (!exists(screen)){ - return false; - } - if (!m_dialog.detect(screen)){ - return false; - } - if (!m_gradient.detect(screen)){ - return false; - } - return true; -} - - -BoxDetector::BoxDetector(Color color) - : m_color(color) - , m_party(color, GradientArrowType::DOWN, {0.140, 0.150, 0.050, 0.700}) - , m_box_change(color, GradientArrowType::DOWN, {0.405, 0.070, 0.050, 0.090}) - , m_all_boxes(color, GradientArrowType::DOWN, {0.295, 0.780, 0.050, 0.090}) - , m_search(color, GradientArrowType::DOWN, {0.510, 0.780, 0.050, 0.090}) - , m_slots(color, GradientArrowType::DOWN, {0.240, 0.160, 0.380, 0.550}) -{} -void BoxDetector::make_overlays(VideoOverlaySet& items) const{ - m_party.make_overlays(items); - m_box_change.make_overlays(items); - m_all_boxes.make_overlays(items); - m_search.make_overlays(items); - m_slots.make_overlays(items); -} -bool BoxDetector::detect(const ImageViewRGB32& screen){ - if (m_party.detect(screen)){ - return true; - } - if (m_box_change.detect(screen)){ - return true; - } - if (m_all_boxes.detect(screen)){ - return true; - } - if (m_search.detect(screen)){ - return true; - } - if (m_slots.detect(screen)){ - return true; - } - return false; -} -std::pair BoxDetector::detect_location(const ImageViewRGB32& screen){ - if (m_box_change.detect(screen)){ - return {BoxCursorLocation::BOX_CHANGE, {0, 0}}; - } - if (m_all_boxes.detect(screen)){ - return {BoxCursorLocation::ALL_BOXES, {0, 0}}; - } - if (m_search.detect(screen)){ - return {BoxCursorLocation::SEARCH, {0, 0}}; - } - - ImageFloatBox box; - if (m_party.detect(box, screen)){ -// cout << box.y << endl; - int slot = (int)((box.y - 0.175926) / 0.116296 + 0.5); - if (slot < 0){ - return {BoxCursorLocation::NONE, {0, 0}}; - } - return {BoxCursorLocation::PARTY, {(uint8_t)slot, 0}}; - } - if (m_slots.detect(box, screen)){ -// cout << box.x << " " << box.y << endl; - int x = (int)((box.x - 0.247917) / 0.065625 + 0.5); - if (x < 0){ - return {BoxCursorLocation::NONE, {0, 0}}; - } - int y = (int)((box.y - 0.175926) / 0.11713 + 0.5); - if (x < 0){ - return {BoxCursorLocation::NONE, {0, 0}}; - } - return {BoxCursorLocation::SLOTS, {(uint8_t)y, (uint8_t)x}}; - } - - return {BoxCursorLocation::NONE, {0, 0}}; -} - - -bool BoxDetector::to_coordinates(int& x, int& y, BoxCursorLocation side, uint8_t row, uint8_t col) const{ - switch (side){ - case BoxCursorLocation::NONE: - return false; - case BoxCursorLocation::PARTY: - x = -1; - y = row; - break; - case BoxCursorLocation::BOX_CHANGE: - x = 2; - y = -1; - break; - case BoxCursorLocation::ALL_BOXES: - x = 1; - y = 5; - break; - case BoxCursorLocation::SEARCH: - x = 4; - y = 5; - break; - case BoxCursorLocation::SLOTS: - x = col; - y = row; - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown BoxCursorLocation"); - } - return true; -} -void BoxDetector::move_vertical(ProControllerContext& context, int current, int desired) const{ - int diff = (current - desired + 7) % 7; -// cout << "diff = " << diff << endl; - if (diff <= 3){ - for (int c = 0; c < diff; c++){ - pbf_press_dpad(context, DPAD_UP, 20, 30); - } - }else{ - for (int c = diff; c < 7; c++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - } -} -void BoxDetector::move_horizontal(ProControllerContext& context, int current, int desired) const{ - int diff = (current - desired + 7) % 7; - if (diff <= 3){ - for (int c = 0; c < diff; c++){ - pbf_press_dpad(context, DPAD_LEFT, 20, 30); - } - }else{ - for (int c = diff; c < 7; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - } - } -} - - -void BoxDetector::move_cursor( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - BoxCursorLocation side, uint8_t row, uint8_t col -){ - int desired_x = 0, desired_y = 0; - if (!to_coordinates(desired_x, desired_y, side, row, col)){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "BoxDetector::move_cursor() called with BoxCursorLocation::NONE." - ); - } -// cout << "desired_x = " << desired_x << ", desired_y = " << desired_y << endl; - - size_t consecutive_fails = 0; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(60)){ - dump_image_and_throw_recoverable_exception( - info, stream, "BoxMoveCursor", - "Failed to move cursor to desired location after 1 minute." - ); - } - - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - std::pair current = this->detect_location(screen); - - int current_x = 0, current_y = 0; - if (!to_coordinates(current_x, current_y, current.first, current.second.row, current.second.col)){ - consecutive_fails++; - if (consecutive_fails > 100){ - dump_image_and_throw_recoverable_exception(info, stream, "BoxSystemNotDetected", "move_cursor(): Unable to detect box system."); - } - context.wait_for(std::chrono::milliseconds(100)); - continue; - } -// cout << "current_x = " << current_x << ", current_y = " << current_y << endl; - - if (current_x == desired_x && current_y == desired_y){ -// cout << "done!" << endl; - return; - } - - // If we're on the party, always move horizontally first. - if (current_x == -1){ - if (desired_x == -1){ - if (row < current.second.row){ - for (uint8_t r = row; r < current.second.row; r++){ - pbf_press_dpad(context, DPAD_UP, 20, 30); - } - }else{ // row >= current.second.row - for (uint8_t r = current.second.row; r < row; r++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - } - continue; - }else if (desired_x < 3){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - }else{ - pbf_press_dpad(context, DPAD_LEFT, 20, 30); - } - continue; - } - - // Otherwise, always move vertically first. - if (current_y != desired_y){ - move_vertical(context, current_y, desired_y); - continue; - } - - // Special case for bottom row. - if (current_y == 5){ - int diff = (current_x - desired_x + 7) % 7; - if (diff <= 3){ - pbf_press_dpad(context, DPAD_LEFT, 20, 30); - }else{ - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - } - continue; - } - - // Now handle horizontals. - move_horizontal(context, current_x, desired_x); - } -} - -BoxEmptySlotDetector::BoxEmptySlotDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color) - : m_color(color) -{ - if (side == BoxCursorLocation::PARTY){ - m_box = ImageFloatBox(0.142, 0.1165 * row + 0.201, 0.048, 0.082); - }else if (side == BoxCursorLocation::SLOTS){ - m_box = ImageFloatBox(0.0656 * col + 0.242, 0.1165 * row + 0.201, 0.048, 0.082); - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "INVALID BoxCursorLocation for BoxEmptySlotDetector"); - } -} - -void BoxEmptySlotDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool BoxEmptySlotDetector::detect(const ImageViewRGB32& frame){ - const auto stats = image_stats(extract_box_reference(frame, m_box)); - return stats.stddev.sum() < 20.0; -} - - - -BoxEmptyPartyWatcher::BoxEmptyPartyWatcher(Color color) : VisualInferenceCallback("BoxEmptyPartyWatcher"), m_empty_watchers(5){ - for(uint8_t i = 0; i < 5; i++){ - m_empty_watchers.emplace_back( - BoxCursorLocation::PARTY, - (uint8_t)(i + 1), (uint8_t)0, - BoxEmptySlotWatcher::FinderType::CONSISTENT, - color - ); - } -} - -void BoxEmptyPartyWatcher::make_overlays(VideoOverlaySet& items) const{ - for(int i = 0; i < 5; i++){ - m_empty_watchers[i].make_overlays(items); - } -} - -bool BoxEmptyPartyWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool all_certain = true; - for(int i = 0; i < 5; i++){ - // Return true if it is sure that the slot is empty or not - const bool empty_certain = m_empty_watchers[i].process_frame(frame, timestamp); - - if (!empty_certain){ - all_certain = false; - } - } - return all_certain; -} - -uint8_t BoxEmptyPartyWatcher::num_empty_slots_found() const{ - uint8_t num_empty = 0; - for(int i = 0; i < 5; i++){ - if (m_empty_watchers[i].consistent_result()){ - num_empty++; - } - } - return num_empty; -} - -namespace{ - ImageFloatBox BOTTOM_BUTTON_Y_BOX{0.391, 0.939, 0.400, 0.047}; -} // anonymous namespace - -BoxBottomButtonYDetector::BoxBottomButtonYDetector(Color color) - : WhiteButtonDetector(color, WhiteButton::ButtonY, BOTTOM_BUTTON_Y_BOX) -{} -BoxBottomButtonBDetector::BoxBottomButtonBDetector(Color color) - : WhiteButtonDetector(color, WhiteButton::ButtonB, {0.842, 0.939, 0.139, 0.047}) -{} - - -BoxSelectionBoxModeWatcher::BoxSelectionBoxModeWatcher(Color color) - : VisualInferenceCallback("BoxSelectionBoxModeWatcher") - , button_y_watcher(color, WhiteButton::ButtonY, BOTTOM_BUTTON_Y_BOX, WhiteButtonWatcher::FinderType::CONSISTENT) -{} - -void BoxSelectionBoxModeWatcher::make_overlays(VideoOverlaySet& items) const{ - button_y_watcher.make_overlays(items); -} - -bool BoxSelectionBoxModeWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return button_y_watcher.process_frame(frame, timestamp); -} - -bool BoxSelectionBoxModeWatcher::in_box_selection_mode() const{ - // If we have button Y detected, then we are NOT in box selection mode - return !button_y_watcher.consistent_result(); -} - - - - - -} -} -} +/* Box Detection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_BoxDetection.h" + +#include +using std::cout; +using std::endl;; + +namespace PokemonAutomation{ + +template class FixedLimitVector; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +std::string BOX_CURSOR_LOCATION_NAMES(BoxCursorLocation location){ + switch(location){ + case BoxCursorLocation::NONE: + return "NONE"; + case BoxCursorLocation::PARTY: + return "PARTY"; + case BoxCursorLocation::BOX_CHANGE: + return "BOX_CHANGE"; + case BoxCursorLocation::ALL_BOXES: + return "ALL_BOXES"; + case BoxCursorLocation::SEARCH: + return "SEARCH"; + case BoxCursorLocation::SLOTS: + return "SLOTS"; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown BoxCursorLocation"); + } +} + +std::string BOX_LOCATION_STRING(BoxCursorLocation location, uint8_t row, uint8_t col){ + return "(" + BOX_CURSOR_LOCATION_NAMES(location) + " row " + std::to_string(row) + " col " + std::to_string(col) + ")"; +} + + +SomethingInBoxSlotDetector::SomethingInBoxSlotDetector(Color color, bool true_if_exists) + : m_true_if_exists(true_if_exists) + , m_color(color) + , m_right(0.985, 0.010, 0.010, 0.050) + , m_top(0.660, 0.005, 0.330, 0.006) + , m_bottom(0.660, 0.064, 0.330, 0.005) + , m_body(0.670, 0.010, 0.060, 0.050) +{} +void SomethingInBoxSlotDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_right); + items.add(m_color, m_top); + items.add(m_color, m_bottom); + items.add(m_color, m_body); +} +bool SomethingInBoxSlotDetector::detect(const ImageViewRGB32& screen){ + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// extract_box_reference(screen, m_right).save("test.png"); +// cout << right.average << right.stddev << endl; + if (!is_solid(right, {0.533473, 0.466527, 0.0}, 0.15, 20)){ +// cout << "asdf" << endl; + return !m_true_if_exists; + } + ImageStats top = image_stats(extract_box_reference(screen, m_top)); +// cout << top.average << top.stddev << endl; + if (!is_solid(top, {0.533473, 0.466527, 0.0})){ +// cout << "qwer" << endl; + return !m_true_if_exists; + } + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; +// extract_box_reference(screen, m_bottom).save("./tmp_bottom.png"); + if (!is_solid(bottom, {0.533473, 0.466527, 0.0}, 0.15, 15.0)){ +// cout << "zxcv" << endl; + return !m_true_if_exists; + } + ImageStats body = image_stats(extract_box_reference(screen, m_body)); +// cout << body.average << body.stddev << endl; + if (body.stddev.sum() < 100){ + return !m_true_if_exists; + } + + return m_true_if_exists; +} + + + + +BoxSelectDetector::BoxSelectDetector(Color color) + : m_color(color) + , m_exists(color, true) + , m_dialog(color) + , m_gradient(color, GradientArrowType::RIGHT, {0.20, 0.17, 0.50, 0.10}) +{} +void BoxSelectDetector::make_overlays(VideoOverlaySet& items) const{ + m_exists.make_overlays(items); + m_dialog.make_overlays(items); + m_gradient.make_overlays(items); +} +bool BoxSelectDetector::exists(const ImageViewRGB32& screen){ + return m_exists.detect(screen); +} +bool BoxSelectDetector::detect(const ImageViewRGB32& screen){ + if (!exists(screen)){ + return false; + } + if (!m_dialog.detect(screen)){ + return false; + } + if (!m_gradient.detect(screen)){ + return false; + } + return true; +} + + +BoxDetector::BoxDetector(Color color) + : m_color(color) + , m_party(color, GradientArrowType::DOWN, {0.140, 0.150, 0.050, 0.700}) + , m_box_change(color, GradientArrowType::DOWN, {0.405, 0.070, 0.050, 0.090}) + , m_all_boxes(color, GradientArrowType::DOWN, {0.295, 0.780, 0.050, 0.090}) + , m_search(color, GradientArrowType::DOWN, {0.510, 0.780, 0.050, 0.090}) + , m_slots(color, GradientArrowType::DOWN, {0.240, 0.160, 0.380, 0.550}) +{} +void BoxDetector::make_overlays(VideoOverlaySet& items) const{ + m_party.make_overlays(items); + m_box_change.make_overlays(items); + m_all_boxes.make_overlays(items); + m_search.make_overlays(items); + m_slots.make_overlays(items); +} +bool BoxDetector::detect(const ImageViewRGB32& screen){ + if (m_party.detect(screen)){ + return true; + } + if (m_box_change.detect(screen)){ + return true; + } + if (m_all_boxes.detect(screen)){ + return true; + } + if (m_search.detect(screen)){ + return true; + } + if (m_slots.detect(screen)){ + return true; + } + return false; +} +std::pair BoxDetector::detect_location(const ImageViewRGB32& screen){ + if (m_box_change.detect(screen)){ + return {BoxCursorLocation::BOX_CHANGE, {0, 0}}; + } + if (m_all_boxes.detect(screen)){ + return {BoxCursorLocation::ALL_BOXES, {0, 0}}; + } + if (m_search.detect(screen)){ + return {BoxCursorLocation::SEARCH, {0, 0}}; + } + + ImageFloatBox box; + if (m_party.detect(box, screen)){ +// cout << box.y << endl; + int slot = (int)((box.y - 0.175926) / 0.116296 + 0.5); + if (slot < 0){ + return {BoxCursorLocation::NONE, {0, 0}}; + } + return {BoxCursorLocation::PARTY, {(uint8_t)slot, 0}}; + } + if (m_slots.detect(box, screen)){ +// cout << box.x << " " << box.y << endl; + int x = (int)((box.x - 0.247917) / 0.065625 + 0.5); + if (x < 0){ + return {BoxCursorLocation::NONE, {0, 0}}; + } + int y = (int)((box.y - 0.175926) / 0.11713 + 0.5); + if (x < 0){ + return {BoxCursorLocation::NONE, {0, 0}}; + } + return {BoxCursorLocation::SLOTS, {(uint8_t)y, (uint8_t)x}}; + } + + return {BoxCursorLocation::NONE, {0, 0}}; +} + + +bool BoxDetector::to_coordinates(int& x, int& y, BoxCursorLocation side, uint8_t row, uint8_t col) const{ + switch (side){ + case BoxCursorLocation::NONE: + return false; + case BoxCursorLocation::PARTY: + x = -1; + y = row; + break; + case BoxCursorLocation::BOX_CHANGE: + x = 2; + y = -1; + break; + case BoxCursorLocation::ALL_BOXES: + x = 1; + y = 5; + break; + case BoxCursorLocation::SEARCH: + x = 4; + y = 5; + break; + case BoxCursorLocation::SLOTS: + x = col; + y = row; + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown BoxCursorLocation"); + } + return true; +} +void BoxDetector::move_vertical(ProControllerContext& context, int current, int desired) const{ + int diff = (current - desired + 7) % 7; +// cout << "diff = " << diff << endl; + if (diff <= 3){ + for (int c = 0; c < diff; c++){ + pbf_press_dpad(context, DPAD_UP, 20, 30); + } + }else{ + for (int c = diff; c < 7; c++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + } +} +void BoxDetector::move_horizontal(ProControllerContext& context, int current, int desired) const{ + int diff = (current - desired + 7) % 7; + if (diff <= 3){ + for (int c = 0; c < diff; c++){ + pbf_press_dpad(context, DPAD_LEFT, 20, 30); + } + }else{ + for (int c = diff; c < 7; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + } + } +} + + +void BoxDetector::move_cursor( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + BoxCursorLocation side, uint8_t row, uint8_t col +){ + int desired_x = 0, desired_y = 0; + if (!to_coordinates(desired_x, desired_y, side, row, col)){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "BoxDetector::move_cursor() called with BoxCursorLocation::NONE." + ); + } +// cout << "desired_x = " << desired_x << ", desired_y = " << desired_y << endl; + + size_t consecutive_fails = 0; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(60)){ + dump_image_and_throw_recoverable_exception( + info, stream, "BoxMoveCursor", + "Failed to move cursor to desired location after 1 minute." + ); + } + + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + std::pair current = this->detect_location(screen); + + int current_x = 0, current_y = 0; + if (!to_coordinates(current_x, current_y, current.first, current.second.row, current.second.col)){ + consecutive_fails++; + if (consecutive_fails > 100){ + dump_image_and_throw_recoverable_exception(info, stream, "BoxSystemNotDetected", "move_cursor(): Unable to detect box system."); + } + context.wait_for(std::chrono::milliseconds(100)); + continue; + } +// cout << "current_x = " << current_x << ", current_y = " << current_y << endl; + + if (current_x == desired_x && current_y == desired_y){ +// cout << "done!" << endl; + return; + } + + // If we're on the party, always move horizontally first. + if (current_x == -1){ + if (desired_x == -1){ + if (row < current.second.row){ + for (uint8_t r = row; r < current.second.row; r++){ + pbf_press_dpad(context, DPAD_UP, 20, 30); + } + }else{ // row >= current.second.row + for (uint8_t r = current.second.row; r < row; r++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + } + continue; + }else if (desired_x < 3){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + }else{ + pbf_press_dpad(context, DPAD_LEFT, 20, 30); + } + continue; + } + + // Otherwise, always move vertically first. + if (current_y != desired_y){ + move_vertical(context, current_y, desired_y); + continue; + } + + // Special case for bottom row. + if (current_y == 5){ + int diff = (current_x - desired_x + 7) % 7; + if (diff <= 3){ + pbf_press_dpad(context, DPAD_LEFT, 20, 30); + }else{ + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + } + continue; + } + + // Now handle horizontals. + move_horizontal(context, current_x, desired_x); + } +} + +BoxEmptySlotDetector::BoxEmptySlotDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color) + : m_color(color) +{ + if (side == BoxCursorLocation::PARTY){ + m_box = ImageFloatBox(0.142, 0.1165 * row + 0.201, 0.048, 0.082); + }else if (side == BoxCursorLocation::SLOTS){ + m_box = ImageFloatBox(0.0656 * col + 0.242, 0.1165 * row + 0.201, 0.048, 0.082); + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "INVALID BoxCursorLocation for BoxEmptySlotDetector"); + } +} + +void BoxEmptySlotDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool BoxEmptySlotDetector::detect(const ImageViewRGB32& frame){ + const auto stats = image_stats(extract_box_reference(frame, m_box)); + return stats.stddev.sum() < 20.0; +} + + + +BoxEmptyPartyWatcher::BoxEmptyPartyWatcher(Color color) : VisualInferenceCallback("BoxEmptyPartyWatcher"), m_empty_watchers(5){ + for(uint8_t i = 0; i < 5; i++){ + m_empty_watchers.emplace_back( + BoxCursorLocation::PARTY, + (uint8_t)(i + 1), (uint8_t)0, + BoxEmptySlotWatcher::FinderType::CONSISTENT, + color + ); + } +} + +void BoxEmptyPartyWatcher::make_overlays(VideoOverlaySet& items) const{ + for(int i = 0; i < 5; i++){ + m_empty_watchers[i].make_overlays(items); + } +} + +bool BoxEmptyPartyWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool all_certain = true; + for(int i = 0; i < 5; i++){ + // Return true if it is sure that the slot is empty or not + const bool empty_certain = m_empty_watchers[i].process_frame(frame, timestamp); + + if (!empty_certain){ + all_certain = false; + } + } + return all_certain; +} + +uint8_t BoxEmptyPartyWatcher::num_empty_slots_found() const{ + uint8_t num_empty = 0; + for(int i = 0; i < 5; i++){ + if (m_empty_watchers[i].consistent_result()){ + num_empty++; + } + } + return num_empty; +} + +namespace{ + ImageFloatBox BOTTOM_BUTTON_Y_BOX{0.391, 0.939, 0.400, 0.047}; +} // anonymous namespace + +BoxBottomButtonYDetector::BoxBottomButtonYDetector(Color color) + : WhiteButtonDetector(color, WhiteButton::ButtonY, BOTTOM_BUTTON_Y_BOX) +{} +BoxBottomButtonBDetector::BoxBottomButtonBDetector(Color color) + : WhiteButtonDetector(color, WhiteButton::ButtonB, {0.842, 0.939, 0.139, 0.047}) +{} + + +BoxSelectionBoxModeWatcher::BoxSelectionBoxModeWatcher(Color color) + : VisualInferenceCallback("BoxSelectionBoxModeWatcher") + , button_y_watcher(color, WhiteButton::ButtonY, BOTTOM_BUTTON_Y_BOX, WhiteButtonWatcher::FinderType::CONSISTENT) +{} + +void BoxSelectionBoxModeWatcher::make_overlays(VideoOverlaySet& items) const{ + button_y_watcher.make_overlays(items); +} + +bool BoxSelectionBoxModeWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return button_y_watcher.process_frame(frame, timestamp); +} + +bool BoxSelectionBoxModeWatcher::in_box_selection_mode() const{ + // If we have button Y detected, then we are NOT in box selection mode + return !button_y_watcher.consistent_result(); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h index aabbc398b0..4137a90c38 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h @@ -1,204 +1,204 @@ -/* Box Detection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BoxDetection_H -#define PokemonAutomation_PokemonSV_BoxDetection_H - -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Detect whether the cursor is over a Pokemon or egg in the box. -// It detects the yellow title bar on top-right corner of the screen when the cursor is on a pokemon or egg -class SomethingInBoxSlotDetector : public StaticScreenDetector{ -public: - SomethingInBoxSlotDetector(Color color, bool true_if_exists = true); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - bool m_true_if_exists; - Color m_color; - ImageFloatBox m_right; - ImageFloatBox m_top; - ImageFloatBox m_bottom; - ImageFloatBox m_body; -}; -class SomethingInBoxSlotWatcher : public DetectorToFinder{ -public: - SomethingInBoxSlotWatcher(Color color, bool stop_on_exists) - : DetectorToFinder("SomethingInBoxSlot", std::chrono::milliseconds(250), color, stop_on_exists) - {} -}; - - - -// Detect whether you have a Pokemon with its menu open in the box system. -class BoxSelectDetector : public StaticScreenDetector{ -public: - BoxSelectDetector(Color color); - - // If there is a pokemon/egg in the current slot in box or party, while in box system view - bool exists(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - SomethingInBoxSlotDetector m_exists; - AdvanceDialogDetector m_dialog; - GradientArrowDetector m_gradient; -}; -class BoxSelectWatcher : public DetectorToFinder{ -public: - BoxSelectWatcher( - Color color, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("BoxSelectFinder", duration, color) - {} -}; - - - - -enum class BoxCursorLocation{ - NONE, - PARTY, // player's party - BOX_CHANGE, // on the box title bar - ALL_BOXES, // bottom-middle "All Boxes" button - SEARCH, // bottom-right "Search" button - SLOTS, // one of the 5 x 6 slots in the box -}; -std::string BOX_CURSOR_LOCATION_NAMES(BoxCursorLocation location); - -std::string BOX_LOCATION_STRING(BoxCursorLocation location, uint8_t row, uint8_t col); - -struct BoxCursorCoordinates{ - uint8_t row; - uint8_t col; -}; - -// Detect if the game is in box system view -class BoxDetector : public StaticScreenDetector{ -public: - BoxDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - std::pair detect_location(const ImageViewRGB32& screen); - - // While in the box system view, move the cursor to the desired slot. - void move_cursor( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - BoxCursorLocation side, uint8_t row, uint8_t col - ); - -private: - bool to_coordinates(int& x, int& y, BoxCursorLocation side, uint8_t row, uint8_t col) const; - void move_vertical(ProControllerContext& context, int current, int desired) const; - void move_horizontal(ProControllerContext& context, int current, int desired) const; - -private: - Color m_color; - GradientArrowDetector m_party; - GradientArrowDetector m_box_change; - GradientArrowDetector m_all_boxes; - GradientArrowDetector m_search; - GradientArrowDetector m_slots; -}; -class BoxWatcher : public DetectorToFinder{ -public: - BoxWatcher(Color color) - : DetectorToFinder("BoxFinder", std::chrono::milliseconds(250), color) - {} -}; - -// Detect whether a box slot is empty by checking color stddev on that slot -// Note: due to the very slow loading of sprites in Pokemon SV box system, you need to make sure the sprites -// are fully loaded before calling this detector. -class BoxEmptySlotDetector : public StaticScreenDetector{ -public: - BoxEmptySlotDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; -private: - Color m_color; - ImageFloatBox m_box; -}; -class BoxEmptySlotWatcher : public DetectorToFinder{ -public: - BoxEmptySlotWatcher(BoxCursorLocation side, uint8_t row, uint8_t col, FinderType finder_type = FinderType::PRESENT, Color color = COLOR_RED) - : DetectorToFinder("BoxEmptySlotWatcher", finder_type, std::chrono::milliseconds(100), side, row, col, color) - {} -}; - - -// Detect party empty slots (the five slots after the party lead). Useful for egg hatching. -class BoxEmptyPartyWatcher : public VisualInferenceCallback{ -public: - BoxEmptyPartyWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true when the watcher is sure that each of the five slots is either egg, non-egg pokemon or empty. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - uint8_t num_empty_slots_found() const; - -private: - FixedLimitVector m_empty_watchers; -}; - - -// Detect whether there is a button Y in the bottom row of the box system view -class BoxBottomButtonYDetector : public WhiteButtonDetector{ -public: - BoxBottomButtonYDetector(Color color = COLOR_RED); -}; - -// Detect whether there is a button B in the bottom row of the box system view -class BoxBottomButtonBDetector : public WhiteButtonDetector{ -public: - BoxBottomButtonBDetector(Color color = COLOR_RED); -}; - -// Detect whether we are in box selection mode or not -class BoxSelectionBoxModeWatcher : public VisualInferenceCallback{ -public: - BoxSelectionBoxModeWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true when the watcher is sure that we are either in box selection mode or not - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - // Return whether in box selection mode - bool in_box_selection_mode() const; - -private: - WhiteButtonWatcher button_y_watcher; -}; - - - - -} -} -} -#endif +/* Box Detection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BoxDetection_H +#define PokemonAutomation_PokemonSV_BoxDetection_H + +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Detect whether the cursor is over a Pokemon or egg in the box. +// It detects the yellow title bar on top-right corner of the screen when the cursor is on a pokemon or egg +class SomethingInBoxSlotDetector : public StaticScreenDetector{ +public: + SomethingInBoxSlotDetector(Color color, bool true_if_exists = true); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + bool m_true_if_exists; + Color m_color; + ImageFloatBox m_right; + ImageFloatBox m_top; + ImageFloatBox m_bottom; + ImageFloatBox m_body; +}; +class SomethingInBoxSlotWatcher : public DetectorToFinder{ +public: + SomethingInBoxSlotWatcher(Color color, bool stop_on_exists) + : DetectorToFinder("SomethingInBoxSlot", std::chrono::milliseconds(250), color, stop_on_exists) + {} +}; + + + +// Detect whether you have a Pokemon with its menu open in the box system. +class BoxSelectDetector : public StaticScreenDetector{ +public: + BoxSelectDetector(Color color); + + // If there is a pokemon/egg in the current slot in box or party, while in box system view + bool exists(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + SomethingInBoxSlotDetector m_exists; + AdvanceDialogDetector m_dialog; + GradientArrowDetector m_gradient; +}; +class BoxSelectWatcher : public DetectorToFinder{ +public: + BoxSelectWatcher( + Color color, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("BoxSelectFinder", duration, color) + {} +}; + + + + +enum class BoxCursorLocation{ + NONE, + PARTY, // player's party + BOX_CHANGE, // on the box title bar + ALL_BOXES, // bottom-middle "All Boxes" button + SEARCH, // bottom-right "Search" button + SLOTS, // one of the 5 x 6 slots in the box +}; +std::string BOX_CURSOR_LOCATION_NAMES(BoxCursorLocation location); + +std::string BOX_LOCATION_STRING(BoxCursorLocation location, uint8_t row, uint8_t col); + +struct BoxCursorCoordinates{ + uint8_t row; + uint8_t col; +}; + +// Detect if the game is in box system view +class BoxDetector : public StaticScreenDetector{ +public: + BoxDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + std::pair detect_location(const ImageViewRGB32& screen); + + // While in the box system view, move the cursor to the desired slot. + void move_cursor( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + BoxCursorLocation side, uint8_t row, uint8_t col + ); + +private: + bool to_coordinates(int& x, int& y, BoxCursorLocation side, uint8_t row, uint8_t col) const; + void move_vertical(ProControllerContext& context, int current, int desired) const; + void move_horizontal(ProControllerContext& context, int current, int desired) const; + +private: + Color m_color; + GradientArrowDetector m_party; + GradientArrowDetector m_box_change; + GradientArrowDetector m_all_boxes; + GradientArrowDetector m_search; + GradientArrowDetector m_slots; +}; +class BoxWatcher : public DetectorToFinder{ +public: + BoxWatcher(Color color) + : DetectorToFinder("BoxFinder", std::chrono::milliseconds(250), color) + {} +}; + +// Detect whether a box slot is empty by checking color stddev on that slot +// Note: due to the very slow loading of sprites in Pokemon SV box system, you need to make sure the sprites +// are fully loaded before calling this detector. +class BoxEmptySlotDetector : public StaticScreenDetector{ +public: + BoxEmptySlotDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; +private: + Color m_color; + ImageFloatBox m_box; +}; +class BoxEmptySlotWatcher : public DetectorToFinder{ +public: + BoxEmptySlotWatcher(BoxCursorLocation side, uint8_t row, uint8_t col, FinderType finder_type = FinderType::PRESENT, Color color = COLOR_RED) + : DetectorToFinder("BoxEmptySlotWatcher", finder_type, std::chrono::milliseconds(100), side, row, col, color) + {} +}; + + +// Detect party empty slots (the five slots after the party lead). Useful for egg hatching. +class BoxEmptyPartyWatcher : public VisualInferenceCallback{ +public: + BoxEmptyPartyWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true when the watcher is sure that each of the five slots is either egg, non-egg pokemon or empty. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + uint8_t num_empty_slots_found() const; + +private: + FixedLimitVector m_empty_watchers; +}; + + +// Detect whether there is a button Y in the bottom row of the box system view +class BoxBottomButtonYDetector : public WhiteButtonDetector{ +public: + BoxBottomButtonYDetector(Color color = COLOR_RED); +}; + +// Detect whether there is a button B in the bottom row of the box system view +class BoxBottomButtonBDetector : public WhiteButtonDetector{ +public: + BoxBottomButtonBDetector(Color color = COLOR_RED); +}; + +// Detect whether we are in box selection mode or not +class BoxSelectionBoxModeWatcher : public VisualInferenceCallback{ +public: + BoxSelectionBoxModeWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true when the watcher is sure that we are either in box selection mode or not + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + // Return whether in box selection mode + bool in_box_selection_mode() const; + +private: + WhiteButtonWatcher button_y_watcher; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.cpp index d54d3d4a0a..b514be3102 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.cpp @@ -1,163 +1,163 @@ -/* Box Eggs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV_BoxEggDetector.h" - -namespace PokemonAutomation{ - -template class FixedLimitVector; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -namespace{ - -class EggMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - EggMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Egg-Template.png", Color(100,100,100), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.2; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static EggMatcher matcher; - return matcher; - } -}; - -} // end anonymous namespace - - - - -BoxCurrentEggDetector::BoxCurrentEggDetector(Color color) -: m_color(color), m_box{0.659, 0.082, 0.329, 0.043} {} - -void BoxCurrentEggDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool BoxCurrentEggDetector::detect(const ImageViewRGB32& frame){ - const auto stats = image_stats(extract_box_reference(frame, m_box)); - return stats.stddev.sum() < 20; -} - - -BoxEggDetector::BoxEggDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color) -: m_color(color){ - if (side == BoxCursorLocation::PARTY){ - m_box = ImageFloatBox(0.149, 0.1165 * row + 0.235, 0.033, 0.066); - }else if (side == BoxCursorLocation::SLOTS){ - m_box = ImageFloatBox(0.0656 * col + 0.249, 0.1165 * row + 0.235, 0.033, 0.066); - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "INVALID BoxCursorLocation for BoxEggDetector"); - } -} - -void BoxEggDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool BoxEggDetector::detect(const ImageViewRGB32& frame){ - const std::vector> filters = { - {combine_rgb(200, 200, 200), combine_rgb(255, 255, 255)}, - {combine_rgb(180, 180, 180), combine_rgb(255, 255, 255)} // for darker capture cards - - }; - - const double screen_rel_size = (frame.height() / 1080.0); - - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 700); - - return match_template_by_waterfill( - extract_box_reference(frame, m_box), - EggMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 75, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); -} - -BoxEggPartyColumnWatcher::BoxEggPartyColumnWatcher(Color color) - : VisualInferenceCallback("BoxEggPartyColumnWatcher"), - m_egg_watchers(5), m_empty_watchers(5) -{ - for(uint8_t i = 0; i < 5; i++){ - m_egg_watchers.emplace_back( - BoxCursorLocation::PARTY, - (uint8_t)(i + 1), (uint8_t)0, - BoxEggWatcher::FinderType::CONSISTENT, - color - ); - m_empty_watchers.emplace_back( - BoxCursorLocation::PARTY, - (uint8_t)(i + 1), (uint8_t)0, - BoxEmptySlotWatcher::FinderType::CONSISTENT, - color - ); - } -} - -void BoxEggPartyColumnWatcher::make_overlays(VideoOverlaySet& items) const{ - for(int i = 0; i < 5; i++){ - m_egg_watchers[i].make_overlays(items); - m_empty_watchers[i].make_overlays(items); - } -} - -bool BoxEggPartyColumnWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool all_certain = true; - for(int i = 0; i < 5; i++){ - // Return true if an egg is detected - const bool egg_certain = m_egg_watchers[i].process_frame(frame, timestamp); - // Return true if it is sure that the slot is empty or not - const bool empty_certain = m_empty_watchers[i].process_frame(frame, timestamp); - - if (!egg_certain || !empty_certain){ - all_certain = false; - } - } - return all_certain; -} - -uint8_t BoxEggPartyColumnWatcher::num_eggs_found() const{ - uint8_t num_eggs = 0; - for(int i = 0; i < 5; i++){ - if (m_egg_watchers[i].consistent_result()){ - num_eggs++; - } - } - return num_eggs; -} - -uint8_t BoxEggPartyColumnWatcher::num_non_egg_pokemon_found() const{ - uint8_t num_pokemon = 0; - for(int i = 0; i < 5; i++){ - if (m_empty_watchers[i].consistent_result() == false && m_egg_watchers[i].consistent_result() == false){ - num_pokemon++; - } - } - return num_pokemon; -} - - -} -} -} +/* Box Eggs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV_BoxEggDetector.h" + +namespace PokemonAutomation{ + +template class FixedLimitVector; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +namespace{ + +class EggMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + EggMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Egg-Template.png", Color(100,100,100), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.2; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static EggMatcher matcher; + return matcher; + } +}; + +} // end anonymous namespace + + + + +BoxCurrentEggDetector::BoxCurrentEggDetector(Color color) +: m_color(color), m_box{0.659, 0.082, 0.329, 0.043} {} + +void BoxCurrentEggDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool BoxCurrentEggDetector::detect(const ImageViewRGB32& frame){ + const auto stats = image_stats(extract_box_reference(frame, m_box)); + return stats.stddev.sum() < 20; +} + + +BoxEggDetector::BoxEggDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color) +: m_color(color){ + if (side == BoxCursorLocation::PARTY){ + m_box = ImageFloatBox(0.149, 0.1165 * row + 0.235, 0.033, 0.066); + }else if (side == BoxCursorLocation::SLOTS){ + m_box = ImageFloatBox(0.0656 * col + 0.249, 0.1165 * row + 0.235, 0.033, 0.066); + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "INVALID BoxCursorLocation for BoxEggDetector"); + } +} + +void BoxEggDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool BoxEggDetector::detect(const ImageViewRGB32& frame){ + const std::vector> filters = { + {combine_rgb(200, 200, 200), combine_rgb(255, 255, 255)}, + {combine_rgb(180, 180, 180), combine_rgb(255, 255, 255)} // for darker capture cards + + }; + + const double screen_rel_size = (frame.height() / 1080.0); + + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 700); + + return match_template_by_waterfill( + extract_box_reference(frame, m_box), + EggMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 75, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); +} + +BoxEggPartyColumnWatcher::BoxEggPartyColumnWatcher(Color color) + : VisualInferenceCallback("BoxEggPartyColumnWatcher"), + m_egg_watchers(5), m_empty_watchers(5) +{ + for(uint8_t i = 0; i < 5; i++){ + m_egg_watchers.emplace_back( + BoxCursorLocation::PARTY, + (uint8_t)(i + 1), (uint8_t)0, + BoxEggWatcher::FinderType::CONSISTENT, + color + ); + m_empty_watchers.emplace_back( + BoxCursorLocation::PARTY, + (uint8_t)(i + 1), (uint8_t)0, + BoxEmptySlotWatcher::FinderType::CONSISTENT, + color + ); + } +} + +void BoxEggPartyColumnWatcher::make_overlays(VideoOverlaySet& items) const{ + for(int i = 0; i < 5; i++){ + m_egg_watchers[i].make_overlays(items); + m_empty_watchers[i].make_overlays(items); + } +} + +bool BoxEggPartyColumnWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool all_certain = true; + for(int i = 0; i < 5; i++){ + // Return true if an egg is detected + const bool egg_certain = m_egg_watchers[i].process_frame(frame, timestamp); + // Return true if it is sure that the slot is empty or not + const bool empty_certain = m_empty_watchers[i].process_frame(frame, timestamp); + + if (!egg_certain || !empty_certain){ + all_certain = false; + } + } + return all_certain; +} + +uint8_t BoxEggPartyColumnWatcher::num_eggs_found() const{ + uint8_t num_eggs = 0; + for(int i = 0; i < 5; i++){ + if (m_egg_watchers[i].consistent_result()){ + num_eggs++; + } + } + return num_eggs; +} + +uint8_t BoxEggPartyColumnWatcher::num_non_egg_pokemon_found() const{ + uint8_t num_pokemon = 0; + for(int i = 0; i < 5; i++){ + if (m_empty_watchers[i].consistent_result() == false && m_egg_watchers[i].consistent_result() == false){ + num_pokemon++; + } + } + return num_pokemon; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h index e050554a64..7abff77f09 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h @@ -1,81 +1,81 @@ -/* Box Egg Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BoxEggDetector_H -#define PokemonAutomation_PokemonSV_BoxEggDetector_H - -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect if the currently selected pokemon is an egg or not, assuming the current -// selected slot is not empty and the box view is stats or judege mode. -class BoxCurrentEggDetector : public StaticScreenDetector{ -public: - BoxCurrentEggDetector(Color color = COLOR_BLUE); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; - - -// Detect if a slot in the box system is an egg. -class BoxEggDetector : public StaticScreenDetector{ -public: - BoxEggDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color = COLOR_YELLOW); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; - -class BoxEggWatcher : public DetectorToFinder{ -public: - BoxEggWatcher(BoxCursorLocation side, uint8_t row, uint8_t col, FinderType finder_type = FinderType::PRESENT, Color color = COLOR_YELLOW) - : DetectorToFinder("BoxEggWatcher", finder_type, std::chrono::milliseconds(100), side, row, col, color) - {} -}; - -// Detect eggs in a party column (five slots after the party lead). Used for egg hatching. -// It also detects empty spaces and non-empty spaces, so that we know whether we have non-egg pokemon in the party. -class BoxEggPartyColumnWatcher : public VisualInferenceCallback{ -public: - BoxEggPartyColumnWatcher(Color color = COLOR_YELLOW); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Return true when the watcher is sure that each of the five slots is either egg, non-egg pokemon or empty. - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - uint8_t num_eggs_found() const; - - uint8_t num_non_egg_pokemon_found() const; - -private: - FixedLimitVector m_egg_watchers; - FixedLimitVector m_empty_watchers; -}; - - - -} -} -} -#endif +/* Box Egg Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BoxEggDetector_H +#define PokemonAutomation_PokemonSV_BoxEggDetector_H + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect if the currently selected pokemon is an egg or not, assuming the current +// selected slot is not empty and the box view is stats or judege mode. +class BoxCurrentEggDetector : public StaticScreenDetector{ +public: + BoxCurrentEggDetector(Color color = COLOR_BLUE); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; + + +// Detect if a slot in the box system is an egg. +class BoxEggDetector : public StaticScreenDetector{ +public: + BoxEggDetector(BoxCursorLocation side, uint8_t row, uint8_t col, Color color = COLOR_YELLOW); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; + +class BoxEggWatcher : public DetectorToFinder{ +public: + BoxEggWatcher(BoxCursorLocation side, uint8_t row, uint8_t col, FinderType finder_type = FinderType::PRESENT, Color color = COLOR_YELLOW) + : DetectorToFinder("BoxEggWatcher", finder_type, std::chrono::milliseconds(100), side, row, col, color) + {} +}; + +// Detect eggs in a party column (five slots after the party lead). Used for egg hatching. +// It also detects empty spaces and non-empty spaces, so that we know whether we have non-egg pokemon in the party. +class BoxEggPartyColumnWatcher : public VisualInferenceCallback{ +public: + BoxEggPartyColumnWatcher(Color color = COLOR_YELLOW); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Return true when the watcher is sure that each of the five slots is either egg, non-egg pokemon or empty. + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + uint8_t num_eggs_found() const; + + uint8_t num_non_egg_pokemon_found() const; + +private: + FixedLimitVector m_egg_watchers; + FixedLimitVector m_empty_watchers; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.cpp index 1e4559e350..1ed9f56782 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.cpp @@ -1,19 +1,19 @@ -/* IV Checker Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_BoxGenderDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -BoxGenderDetector::BoxGenderDetector(Color color) : Pokemon::BoxGenderDetector({0.965, 0.019, 0.019, 0.034}, 0.2, color) {} - - -} -} -} - +/* IV Checker Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_BoxGenderDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +BoxGenderDetector::BoxGenderDetector(Color color) : Pokemon::BoxGenderDetector({0.965, 0.019, 0.019, 0.034}, 0.2, color) {} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h index 3ebbbb06c9..e98b01eec6 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h @@ -1,29 +1,29 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BoxGenderDetector_H -#define PokemonAutomation_PokemonSwSh_BoxGenderDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_BoxGenderDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class BoxGenderDetector : public Pokemon::BoxGenderDetector{ - -public: - BoxGenderDetector(Color color = COLOR_RED); - -}; - - -} -} -} -#endif +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BoxGenderDetector_H +#define PokemonAutomation_PokemonSwSh_BoxGenderDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_BoxGenderDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class BoxGenderDetector : public Pokemon::BoxGenderDetector{ + +public: + BoxGenderDetector(Color color = COLOR_RED); + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.cpp index ffb871dc23..5a2caa4190 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.cpp @@ -1,48 +1,48 @@ -/* Box Nature Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonSV_BoxNatureDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -const NatureReader& NATURE_READER(){ - const static Pokemon::NatureReader reader("Pokemon/NatureCheckerOCR.json"); - return reader; -} - -BoxNatureDetector::BoxNatureDetector(VideoOverlay& overlay, Language language) - : m_language(language) - , m_box_nature(overlay, {0.757, 0.529, 0.141, 0.050}) -{} - -NatureCheckerValue BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ - ImageViewRGB32 image = extract_box_reference(frame, box); - OCR::StringMatchResult result = NATURE_READER().read_substring( - logger, m_language, image, - OCR::WHITE_TEXT_FILTERS() - ); - result.clear_beyond_log10p(NatureReader::MAX_LOG10P); - if (result.results.size() != 1){ - return NatureCheckerValue::UnableToDetect; - } - return NATURE_CHECKER_VALUE_STRINGS().get_enum(result.results.begin()->second.token); -} -NatureReader::Results BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame){ - NatureReader::Results results; - if (m_language != Language::None){ - results.nature = read(logger, frame, m_box_nature); - } - return results; -} - - - -} -} -} +/* Box Nature Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonSV_BoxNatureDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +const NatureReader& NATURE_READER(){ + const static Pokemon::NatureReader reader("Pokemon/NatureCheckerOCR.json"); + return reader; +} + +BoxNatureDetector::BoxNatureDetector(VideoOverlay& overlay, Language language) + : m_language(language) + , m_box_nature(overlay, {0.757, 0.529, 0.141, 0.050}) +{} + +NatureCheckerValue BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ + ImageViewRGB32 image = extract_box_reference(frame, box); + OCR::StringMatchResult result = NATURE_READER().read_substring( + logger, m_language, image, + OCR::WHITE_TEXT_FILTERS() + ); + result.clear_beyond_log10p(NatureReader::MAX_LOG10P); + if (result.results.size() != 1){ + return NatureCheckerValue::UnableToDetect; + } + return NATURE_CHECKER_VALUE_STRINGS().get_enum(result.results.begin()->second.token); +} +NatureReader::Results BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame){ + NatureReader::Results results; + if (m_language != Language::None){ + results.nature = read(logger, frame, m_box_nature); + } + return results; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h index 7cea85de2b..a56f638c53 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h @@ -1,39 +1,39 @@ -/* Box Nature Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BoxNatureDetector_H -#define PokemonAutomation_PokemonSV_BoxNatureDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_NatureReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ -using namespace Pokemon; - -const NatureReader& NATURE_READER(); - -class BoxNatureDetector{ -public: - BoxNatureDetector(VideoOverlay& overlay, Language language); - - NatureReader::Results read(Logger& logger, const ImageViewRGB32& frame); - -private: - NatureCheckerValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); - -private: - Language m_language; - OverlayBoxScope m_box_nature; -}; - - - -} -} -} -#endif +/* Box Nature Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BoxNatureDetector_H +#define PokemonAutomation_PokemonSV_BoxNatureDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_NatureReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +using namespace Pokemon; + +const NatureReader& NATURE_READER(); + +class BoxNatureDetector{ +public: + BoxNatureDetector(VideoOverlay& overlay, Language language); + + NatureReader::Results read(Logger& logger, const ImageViewRGB32& frame); + +private: + NatureCheckerValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); + +private: + Language m_language; + OverlayBoxScope m_box_nature; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.cpp index fec36ae85a..7ffbaeb59a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.cpp @@ -1,39 +1,39 @@ -/* Box Shiny Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonSV_BoxShinyDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -BoxShinyDetector::BoxShinyDetector(Color color, const ImageFloatBox& box) -: m_color(color), m_box(box) {} - -void BoxShinyDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool BoxShinyDetector::detect(const ImageViewRGB32& frame){ - const auto stats = image_stats(extract_box_reference(frame, m_box)); - // cout << "stats.stddev.sum() " << stats.stddev.sum() << endl; - // On screenshots collected from macOS-Mirabox, non-shiny has stddev of at most 3.0, while - // shiny has stdddev of 160. - return stats.stddev.sum() > 100; -} - - -} -} -} +/* Box Shiny Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonSV_BoxShinyDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +BoxShinyDetector::BoxShinyDetector(Color color, const ImageFloatBox& box) +: m_color(color), m_box(box) {} + +void BoxShinyDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool BoxShinyDetector::detect(const ImageViewRGB32& frame){ + const auto stats = image_stats(extract_box_reference(frame, m_box)); + // cout << "stats.stddev.sum() " << stats.stddev.sum() << endl; + // On screenshots collected from macOS-Mirabox, non-shiny has stddev of at most 3.0, while + // shiny has stdddev of 160. + return stats.stddev.sum() > 100; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h index 91520f1b1c..6e6738e8c3 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h @@ -1,48 +1,48 @@ -/* Box Shiny Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BoxShinyDetector_H -#define PokemonAutomation_PokemonSV_BoxShinyDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect the shiny symbol on a pokemon in box system -class BoxShinyDetector : public StaticScreenDetector{ -public: - BoxShinyDetector(Color color = COLOR_YELLOW, const ImageFloatBox& box = {0.878, 0.081, 0.028, 0.046}); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; - -class BoxShinyWatcher : public DetectorToFinder{ -public: - BoxShinyWatcher( - Color color = COLOR_YELLOW, - const ImageFloatBox& box = {0.878, 0.081, 0.028, 0.046}, - FinderType finder_type = FinderType::PRESENT - ) - : DetectorToFinder("BoxShinyWatcher", finder_type, std::chrono::milliseconds(100), color, box) - {} -}; - - -} -} -} -#endif +/* Box Shiny Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BoxShinyDetector_H +#define PokemonAutomation_PokemonSV_BoxShinyDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect the shiny symbol on a pokemon in box system +class BoxShinyDetector : public StaticScreenDetector{ +public: + BoxShinyDetector(Color color = COLOR_YELLOW, const ImageFloatBox& box = {0.878, 0.081, 0.028, 0.046}); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; + +class BoxShinyWatcher : public DetectorToFinder{ +public: + BoxShinyWatcher( + Color color = COLOR_YELLOW, + const ImageFloatBox& box = {0.878, 0.081, 0.028, 0.046}, + FinderType finder_type = FinderType::PRESENT + ) + : DetectorToFinder("BoxShinyWatcher", finder_type, std::chrono::milliseconds(100), color, box) + {} +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.cpp index 1d500bfeef..1cfe57e6b4 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.cpp @@ -1,74 +1,74 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonSV_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const IvJudgeReader& IV_READER(){ - const static Pokemon::IvJudgeReader reader("PokemonSV/IVCheckerOCR.json"); - return reader; -} - - - -IvJudgeReaderScope::IvJudgeReaderScope(VideoOverlay& overlay, Language language) - : m_language(language) - , m_box_hp (overlay, {0.825, 0.192, 0.110, 0.052}) - , m_box_attack (overlay, {0.886, 0.302, 0.110, 0.052}) - , m_box_defense (overlay, {0.886, 0.406, 0.110, 0.052}) - , m_box_spatk (overlay, {0.660, 0.302, 0.110, 0.052}) - , m_box_spdef (overlay, {0.660, 0.406, 0.110, 0.052}) - , m_box_speed (overlay, {0.825, 0.470, 0.110, 0.052}) -{} - - -IvJudgeValue IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ - ImageViewRGB32 image = extract_box_reference(frame, box); - OCR::StringMatchResult result = IV_READER().read_substring( - logger, m_language, image, - OCR::WHITE_TEXT_FILTERS() - ); - result.clear_beyond_log10p(IvJudgeReader::MAX_LOG10P); - if (result.results.size() != 1){ - return IvJudgeValue::UnableToDetect; - } - return IV_JUDGE_VALUE_STRINGS().get_enum(result.results.begin()->second.token); -} -IvJudgeReader::Results IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame){ - IvJudgeReader::Results results; - if (m_language != Language::None){ - results.hp = read(logger, frame, m_box_hp); - results.attack = read(logger, frame, m_box_attack); - results.defense = read(logger, frame, m_box_defense); - results.spatk = read(logger, frame, m_box_spatk); - results.spdef = read(logger, frame, m_box_spdef); - results.speed = read(logger, frame, m_box_speed); - } - return results; -} - -std::vector IvJudgeReaderScope::dump_images(const ImageViewRGB32& frame){ - std::vector images; - images.emplace_back(extract_box_reference(frame, m_box_hp)); - images.emplace_back(extract_box_reference(frame, m_box_attack)); - images.emplace_back(extract_box_reference(frame, m_box_defense)); - images.emplace_back(extract_box_reference(frame, m_box_spatk)); - images.emplace_back(extract_box_reference(frame, m_box_spdef)); - images.emplace_back(extract_box_reference(frame, m_box_speed)); - return images; -} - - - -} -} -} - +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonSV_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const IvJudgeReader& IV_READER(){ + const static Pokemon::IvJudgeReader reader("PokemonSV/IVCheckerOCR.json"); + return reader; +} + + + +IvJudgeReaderScope::IvJudgeReaderScope(VideoOverlay& overlay, Language language) + : m_language(language) + , m_box_hp (overlay, {0.825, 0.192, 0.110, 0.052}) + , m_box_attack (overlay, {0.886, 0.302, 0.110, 0.052}) + , m_box_defense (overlay, {0.886, 0.406, 0.110, 0.052}) + , m_box_spatk (overlay, {0.660, 0.302, 0.110, 0.052}) + , m_box_spdef (overlay, {0.660, 0.406, 0.110, 0.052}) + , m_box_speed (overlay, {0.825, 0.470, 0.110, 0.052}) +{} + + +IvJudgeValue IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ + ImageViewRGB32 image = extract_box_reference(frame, box); + OCR::StringMatchResult result = IV_READER().read_substring( + logger, m_language, image, + OCR::WHITE_TEXT_FILTERS() + ); + result.clear_beyond_log10p(IvJudgeReader::MAX_LOG10P); + if (result.results.size() != 1){ + return IvJudgeValue::UnableToDetect; + } + return IV_JUDGE_VALUE_STRINGS().get_enum(result.results.begin()->second.token); +} +IvJudgeReader::Results IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame){ + IvJudgeReader::Results results; + if (m_language != Language::None){ + results.hp = read(logger, frame, m_box_hp); + results.attack = read(logger, frame, m_box_attack); + results.defense = read(logger, frame, m_box_defense); + results.spatk = read(logger, frame, m_box_spatk); + results.spdef = read(logger, frame, m_box_spdef); + results.speed = read(logger, frame, m_box_speed); + } + return results; +} + +std::vector IvJudgeReaderScope::dump_images(const ImageViewRGB32& frame){ + std::vector images; + images.emplace_back(extract_box_reference(frame, m_box_hp)); + images.emplace_back(extract_box_reference(frame, m_box_attack)); + images.emplace_back(extract_box_reference(frame, m_box_defense)); + images.emplace_back(extract_box_reference(frame, m_box_spatk)); + images.emplace_back(extract_box_reference(frame, m_box_spdef)); + images.emplace_back(extract_box_reference(frame, m_box_speed)); + return images; +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h index 17728b323f..ab08863da3 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h @@ -1,48 +1,48 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_IvJudgeReader_H -#define PokemonAutomation_PokemonSV_IvJudgeReader_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ -using namespace Pokemon; - - -const IvJudgeReader& IV_READER(); - - -class IvJudgeReaderScope{ -public: - IvJudgeReaderScope(VideoOverlay& overlay, Language language); - - IvJudgeReader::Results read(Logger& logger, const ImageViewRGB32& frame); - - std::vector dump_images(const ImageViewRGB32& frame); - -private: - IvJudgeValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); - -private: - Language m_language; - OverlayBoxScope m_box_hp; - OverlayBoxScope m_box_attack; - OverlayBoxScope m_box_defense; - OverlayBoxScope m_box_spatk; - OverlayBoxScope m_box_spdef; - OverlayBoxScope m_box_speed; -}; - - - -} -} -} -#endif +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_IvJudgeReader_H +#define PokemonAutomation_PokemonSV_IvJudgeReader_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +using namespace Pokemon; + + +const IvJudgeReader& IV_READER(); + + +class IvJudgeReaderScope{ +public: + IvJudgeReaderScope(VideoOverlay& overlay, Language language); + + IvJudgeReader::Results read(Logger& logger, const ImageViewRGB32& frame); + + std::vector dump_images(const ImageViewRGB32& frame); + +private: + IvJudgeValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); + +private: + Language m_language; + OverlayBoxScope m_box_hp; + OverlayBoxScope m_box_attack; + OverlayBoxScope m_box_defense; + OverlayBoxScope m_box_spatk; + OverlayBoxScope m_box_spdef; + OverlayBoxScope m_box_speed; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.cpp b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.cpp index 6e2fb2fb0f..1eb6dbb91d 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.cpp @@ -1,49 +1,49 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV_StatsResetChecker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -bool check_stats_reset_info( - VideoStream& stream, ProControllerContext& context, - OCR::LanguageOCROption& LANGUAGE, Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, - Pokemon::StatsHuntAction& action -){ - context.wait_for_all_requests(); - - Language language = LANGUAGE; - - change_view_to_judge(stream, context, language); - - VideoOverlaySet overlay_set(stream.overlay()); - IvJudgeReaderScope iv_reader_scope(stream.overlay(), language); - VideoSnapshot screen = stream.video().snapshot(); - IvJudgeReader::Results IVs = iv_reader_scope.read(stream.logger(), screen); - BoxNatureDetector nature_detector(stream.overlay(), LANGUAGE); - NatureReader::Results nature = nature_detector.read(stream.logger(), screen); - bool shiny = false; - - stream.log(IVs.to_string(), COLOR_GREEN); - action = FILTERS.get_action(shiny, StatsHuntGenderFilter::Any, nature.nature, IVs); - - return shiny; -} - - - -} -} -} +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV_StatsResetChecker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +bool check_stats_reset_info( + VideoStream& stream, ProControllerContext& context, + OCR::LanguageOCROption& LANGUAGE, Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, + Pokemon::StatsHuntAction& action +){ + context.wait_for_all_requests(); + + Language language = LANGUAGE; + + change_view_to_judge(stream, context, language); + + VideoOverlaySet overlay_set(stream.overlay()); + IvJudgeReaderScope iv_reader_scope(stream.overlay(), language); + VideoSnapshot screen = stream.video().snapshot(); + IvJudgeReader::Results IVs = iv_reader_scope.read(stream.logger(), screen); + BoxNatureDetector nature_detector(stream.overlay(), LANGUAGE); + NatureReader::Results nature = nature_detector.read(stream.logger(), screen); + bool shiny = false; + + stream.log(IVs.to_string(), COLOR_GREEN); + action = FILTERS.get_action(shiny, StatsHuntGenderFilter::Any, nature.nature, IVs); + + return shiny; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h index c8abe14440..bb920f01e8 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h @@ -1,43 +1,43 @@ -/* Stats Reset Checker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_StatsResetChecker_H -#define PokemonAutomation_PokemonSV_StatsResetChecker_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class ImageViewRGB32; - -namespace OCR{ - class LanguageOCROption; -} -namespace Pokemon{ - enum class StatsHuntAction; -class StatsHuntIvJudgeFilterTable; -} - -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -//This is a similar to check_baby_info, except for Stats Reset -bool check_stats_reset_info( - VideoStream& stream, ProControllerContext& context, - OCR::LanguageOCROption& LANGUAGE, Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, - Pokemon::StatsHuntAction& action -); - - - - -} -} -} -#endif +/* Stats Reset Checker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StatsResetChecker_H +#define PokemonAutomation_PokemonSV_StatsResetChecker_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class ImageViewRGB32; + +namespace OCR{ + class LanguageOCROption; +} +namespace Pokemon{ + enum class StatsHuntAction; +class StatsHuntIvJudgeFilterTable; +} + +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +//This is a similar to check_baby_info, except for Stats Reset +bool check_stats_reset_info( + VideoStream& stream, ProControllerContext& context, + OCR::LanguageOCROption& LANGUAGE, Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, + Pokemon::StatsHuntAction& action +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp index 1583a01703..8699707ec5 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.cpp @@ -1,239 +1,239 @@ -/* Dialog Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_DialogArrowDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - -class DialogArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DialogArrowMatcher() : WaterfillTemplateMatcher( - // "PokemonSV/DialogArrow-White-BlackBackground.png", Color(140, 140, 140), Color(255, 255, 255), 50 - "PokemonSV/DialogArrow-White-NoBackground.png", Color(140, 140, 140), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.3; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DialogArrowMatcher matcher; - return matcher; - } -}; - -const ImageMatch::ExactImageMatcher& DIALOG_ARROW_BLACK(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/DialogArrow-Black.png"); - return matcher; -} -const ImageMatch::ExactImageMatcher& DIALOG_ARROW_WHITE(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/DialogArrow-White.png"); - return matcher; -} - -bool is_dialog_arrow(const ImageViewRGB32& image, const WaterfillObject& object, bool black_arrow){ - double aspect_ratio = object.aspect_ratio(); -// cout << "aspect_ratio = " << aspect_ratio << endl; - if (aspect_ratio < 1.1 || aspect_ratio > 1.4){ - return false; - } -// double area = (double)object.area_ratio(); -// if (area < 0.4 || area > 0.5){ -// return false; -// } - - ImageViewRGB32 cropped = extract_box_reference(image, object); -// cropped.save("test.png"); - - double rmsd = black_arrow - ? DIALOG_ARROW_BLACK().rmsd(cropped) - : DIALOG_ARROW_WHITE().rmsd(cropped); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= 120; -} - - - -DialogArrowDetector::DialogArrowDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} -void DialogArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool DialogArrowDetector::detect(const ImageViewRGB32& screen){ - std::vector hits = detect_all(screen); - return !hits.empty(); -} - -std::vector DialogArrowDetector::detect_all(const ImageViewRGB32& screen) const{ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, m_box); - - std::vector hits; - - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff000000, 0xff7f7fbf); - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (iter->find_next(object, false)){ - if (is_dialog_arrow(region, object, true)){ - hits.emplace_back(translate_to_parent(screen, m_box, object)); - } - } - } - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff808080, 0xffffffff); - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (iter->find_next(object, false)){ - if (is_dialog_arrow(region, object, false)){ - hits.emplace_back(translate_to_parent(screen, m_box, object)); - } - } - } - - return hits; -} - - -std::pair DialogArrowDetector::locate_dialog_arrow(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(200, 200, 200), combine_rgb(255, 255, 255)}, - - }; - - ImageViewRGB32 cropped = extract_box_reference(screen, m_box); - // ImageRGB32 binaryImage = cropped.copy(); - // PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(cropped, 0xffC8C8C8, 0xffffffff); - // filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); - - const double min_object_size = 50.0; - const double rmsd_threshold = 80.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::pair arrow_location(-1.0, -1.0); - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - cropped, - DialogArrowMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - - arrow_location = std::make_pair( - (object.center_of_gravity_x() + pixel_search_area.min_x) / (double)screen.width(), - (object.center_of_gravity_y() + pixel_search_area.min_y) / (double)screen.height() - ); - - return true; - } - ); - - // std::cout << "north location: " << std::to_string(north_location.first) << ", " << std::to_string(north_location.second) << std::endl; - - return arrow_location; -} - - - -DialogArrowWatcher::~DialogArrowWatcher() = default; -DialogArrowWatcher::DialogArrowWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box, const double top_line, const double bottom_line) - : VisualInferenceCallback("GradientArrowFinder") - , m_overlay(overlay) - , m_detector(color, box) - , m_top_line(top_line) - , m_bottom_line(bottom_line) - , m_num_oscillation_above_top_line(0) - , m_num_oscillation_below_bottom_line(0) -{} - -void DialogArrowWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -// - return true if detects the arrow for 5 up and down oscillations -// - every time the arrow is above top_line, increment m_num_oscillation_above_top_line. -// - likewise for m_num_oscillation_below_bottom_line -// - we alternate between looking for the arrow being above top_line vs below bottom_line -// - reset counts whenever the dialog arrow has not been detected for 10 frames consecutively -bool DialogArrowWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - std::pair arrow_location = m_detector.locate_dialog_arrow(frame); - double y_location = arrow_location.second; - // cout << std::to_string(y_location) << endl; - - if (y_location < 0){ // dialog arrow not detected - m_num_no_detection++; - if (m_num_no_detection > 10){ - // reset oscillation counts - m_num_oscillation_above_top_line = 0; - m_num_oscillation_below_bottom_line = 0; - } - return false; - }else{ - m_num_no_detection = 0; - } - - if (m_num_oscillation_above_top_line >= 5 && m_num_oscillation_below_bottom_line >= 5){ - // we have had 5 oscillations above and below the top and bottom line respectively - return true; - } - - if (m_num_oscillation_above_top_line < m_num_oscillation_below_bottom_line){ - // watch for the arrow above the top_line - if (y_location < m_top_line){ // remember that 0,0 is the top left corner. so being above a line, means less-than - // cout << "above top line." << endl; - m_num_oscillation_above_top_line++; - } - }else{ - // watch for the arrow below the bottom_line - if (y_location > m_bottom_line){ - // cout << "below bottom line." << endl; - m_num_oscillation_below_bottom_line++; - } - } - - return false; -} - - - - - - - - -} -} -} +/* Dialog Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_DialogArrowDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + +class DialogArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DialogArrowMatcher() : WaterfillTemplateMatcher( + // "PokemonSV/DialogArrow-White-BlackBackground.png", Color(140, 140, 140), Color(255, 255, 255), 50 + "PokemonSV/DialogArrow-White-NoBackground.png", Color(140, 140, 140), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.3; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DialogArrowMatcher matcher; + return matcher; + } +}; + +const ImageMatch::ExactImageMatcher& DIALOG_ARROW_BLACK(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/DialogArrow-Black.png"); + return matcher; +} +const ImageMatch::ExactImageMatcher& DIALOG_ARROW_WHITE(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/DialogArrow-White.png"); + return matcher; +} + +bool is_dialog_arrow(const ImageViewRGB32& image, const WaterfillObject& object, bool black_arrow){ + double aspect_ratio = object.aspect_ratio(); +// cout << "aspect_ratio = " << aspect_ratio << endl; + if (aspect_ratio < 1.1 || aspect_ratio > 1.4){ + return false; + } +// double area = (double)object.area_ratio(); +// if (area < 0.4 || area > 0.5){ +// return false; +// } + + ImageViewRGB32 cropped = extract_box_reference(image, object); +// cropped.save("test.png"); + + double rmsd = black_arrow + ? DIALOG_ARROW_BLACK().rmsd(cropped) + : DIALOG_ARROW_WHITE().rmsd(cropped); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= 120; +} + + + +DialogArrowDetector::DialogArrowDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} +void DialogArrowDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool DialogArrowDetector::detect(const ImageViewRGB32& screen){ + std::vector hits = detect_all(screen); + return !hits.empty(); +} + +std::vector DialogArrowDetector::detect_all(const ImageViewRGB32& screen) const{ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, m_box); + + std::vector hits; + + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff000000, 0xff7f7fbf); + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (iter->find_next(object, false)){ + if (is_dialog_arrow(region, object, true)){ + hits.emplace_back(translate_to_parent(screen, m_box, object)); + } + } + } + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff808080, 0xffffffff); + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (iter->find_next(object, false)){ + if (is_dialog_arrow(region, object, false)){ + hits.emplace_back(translate_to_parent(screen, m_box, object)); + } + } + } + + return hits; +} + + +std::pair DialogArrowDetector::locate_dialog_arrow(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(200, 200, 200), combine_rgb(255, 255, 255)}, + + }; + + ImageViewRGB32 cropped = extract_box_reference(screen, m_box); + // ImageRGB32 binaryImage = cropped.copy(); + // PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(cropped, 0xffC8C8C8, 0xffffffff); + // filter_by_mask(matrix, binaryImage, Color(COLOR_BLACK), true); + + const double min_object_size = 50.0; + const double rmsd_threshold = 80.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::pair arrow_location(-1.0, -1.0); + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + cropped, + DialogArrowMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + + arrow_location = std::make_pair( + (object.center_of_gravity_x() + pixel_search_area.min_x) / (double)screen.width(), + (object.center_of_gravity_y() + pixel_search_area.min_y) / (double)screen.height() + ); + + return true; + } + ); + + // std::cout << "north location: " << std::to_string(north_location.first) << ", " << std::to_string(north_location.second) << std::endl; + + return arrow_location; +} + + + +DialogArrowWatcher::~DialogArrowWatcher() = default; +DialogArrowWatcher::DialogArrowWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box, const double top_line, const double bottom_line) + : VisualInferenceCallback("GradientArrowFinder") + , m_overlay(overlay) + , m_detector(color, box) + , m_top_line(top_line) + , m_bottom_line(bottom_line) + , m_num_oscillation_above_top_line(0) + , m_num_oscillation_below_bottom_line(0) +{} + +void DialogArrowWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +// - return true if detects the arrow for 5 up and down oscillations +// - every time the arrow is above top_line, increment m_num_oscillation_above_top_line. +// - likewise for m_num_oscillation_below_bottom_line +// - we alternate between looking for the arrow being above top_line vs below bottom_line +// - reset counts whenever the dialog arrow has not been detected for 10 frames consecutively +bool DialogArrowWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + std::pair arrow_location = m_detector.locate_dialog_arrow(frame); + double y_location = arrow_location.second; + // cout << std::to_string(y_location) << endl; + + if (y_location < 0){ // dialog arrow not detected + m_num_no_detection++; + if (m_num_no_detection > 10){ + // reset oscillation counts + m_num_oscillation_above_top_line = 0; + m_num_oscillation_below_bottom_line = 0; + } + return false; + }else{ + m_num_no_detection = 0; + } + + if (m_num_oscillation_above_top_line >= 5 && m_num_oscillation_below_bottom_line >= 5){ + // we have had 5 oscillations above and below the top and bottom line respectively + return true; + } + + if (m_num_oscillation_above_top_line < m_num_oscillation_below_bottom_line){ + // watch for the arrow above the top_line + if (y_location < m_top_line){ // remember that 0,0 is the top left corner. so being above a line, means less-than + // cout << "above top line." << endl; + m_num_oscillation_above_top_line++; + } + }else{ + // watch for the arrow below the bottom_line + if (y_location > m_bottom_line){ + // cout << "below bottom line." << endl; + m_num_oscillation_below_bottom_line++; + } + } + + return false; +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h index 4205290976..d6aa6c338d 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogArrowDetector.h @@ -1,67 +1,67 @@ -/* Dialog Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_DialogArrowDetector_H -#define PokemonAutomation_PokemonSV_DialogArrowDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class DialogArrowDetector : public StaticScreenDetector{ -public: - DialogArrowDetector(Color color, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - - std::pair locate_dialog_arrow(const ImageViewRGB32& screen) const; - -protected: - Color m_color; - ImageFloatBox m_box; -}; - - - -class DialogArrowWatcher : public VisualInferenceCallback{ -public: - ~DialogArrowWatcher(); - DialogArrowWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box, const double top_line, const double bottom_line); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - -protected: - VideoOverlay& m_overlay; - DialogArrowDetector m_detector; - double m_top_line; - double m_bottom_line; - uint16_t m_num_oscillation_above_top_line; - uint16_t m_num_oscillation_below_bottom_line; - uint16_t m_num_no_detection; - // FixedLimitVector m_arrows; - -}; - - - - -} -} -} -#endif +/* Dialog Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_DialogArrowDetector_H +#define PokemonAutomation_PokemonSV_DialogArrowDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class DialogArrowDetector : public StaticScreenDetector{ +public: + DialogArrowDetector(Color color, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + + std::pair locate_dialog_arrow(const ImageViewRGB32& screen) const; + +protected: + Color m_color; + ImageFloatBox m_box; +}; + + + +class DialogArrowWatcher : public VisualInferenceCallback{ +public: + ~DialogArrowWatcher(); + DialogArrowWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box, const double top_line, const double bottom_line); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + +protected: + VideoOverlay& m_overlay; + DialogArrowDetector m_detector; + double m_top_line; + double m_bottom_line; + uint16_t m_num_oscillation_above_top_line; + uint16_t m_num_oscillation_below_bottom_line; + uint16_t m_num_no_detection; + // FixedLimitVector m_arrows; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp index bdf267e2b9..25fcf82a03 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.cpp @@ -1,136 +1,136 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_DialogArrowDetector.h" -#include "PokemonSV_GradientArrowDetector.h" -#include "PokemonSV_DialogDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -DialogBoxDetector::DialogBoxDetector(Color color, bool true_if_detected, DialogType type) - : m_color(color) - , m_true_if_detected(true_if_detected) - , m_box_top(0.50, 0.74, 0.20, 0.01) - , m_box_bot(0.30, 0.88, 0.40, 0.01) - , m_border_top(0.24, 0.71, 0.52, 0.04) - , m_border_bot(0.24, 0.88, 0.52, 0.04) - , m_dialog_type(type) -{} -void DialogBoxDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_top); - items.add(m_color, m_box_bot); - items.add(m_color, m_border_top); - items.add(m_color, m_border_bot); -} -bool DialogBoxDetector::detect(const ImageViewRGB32& screen){ - ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); -// cout << stats_box_top.average << stats_box_top.stddev << endl; - bool white; - if (is_white(stats_box_top)){ - white = true; - if (m_dialog_type == DialogType::DIALOG_BLACK){ - return !m_true_if_detected; - } - }else if (is_black(stats_box_top, 150)){ - white = false; - if (m_dialog_type == DialogType::DIALOG_WHITE){ - return !m_true_if_detected; - } - }else{ - return !m_true_if_detected; - } - -// cout << "white = " << white << endl; - - ImageStats stats_box_bot = image_stats(extract_box_reference(screen, m_box_bot)); -// cout << stats_box_bot.average << stats_box_bot.stddev << endl; - if (white){ - if (!is_white(stats_box_bot)){ - return !m_true_if_detected; - } - }else{ - if (!is_black(stats_box_bot, 150)){ - return !m_true_if_detected; - } - } - - ImageStats stats_border_top = image_stats(extract_box_reference(screen, m_border_top)); -// cout << stats_border_top.average << stats_border_top.stddev << endl; - if (stats_border_top.stddev.sum() < 50){ - return !m_true_if_detected; - } - - ImageStats stats_border_bot = image_stats(extract_box_reference(screen, m_border_bot)); -// cout << stats_border_bot.average << stats_border_bot.stddev << endl; - if (stats_border_bot.stddev.sum() < 20){ - return !m_true_if_detected; - } - - return m_true_if_detected; -} - - - - -AdvanceDialogDetector::AdvanceDialogDetector(Color color, DialogType type) - : m_box(color, true, type) - , m_arrow(0.710, 0.850, 0.030, 0.042) -{} -void AdvanceDialogDetector::make_overlays(VideoOverlaySet& items) const{ - m_box.make_overlays(items); - items.add(m_box.color(), m_arrow); -} -bool AdvanceDialogDetector::detect(const ImageViewRGB32& screen){ - if (!m_box.detect(screen)){ - return false; - } - - DialogArrowDetector arrow_detector(COLOR_RED, m_arrow); - return arrow_detector.detect(screen); -} - - - - -PromptDialogDetector::PromptDialogDetector(Color color) - : PromptDialogDetector(color, {0.50, 0.40, 0.40, 0.50}) -{} -PromptDialogDetector::PromptDialogDetector(Color color, const ImageFloatBox& arrow_box) - : m_box(color) - , m_gradient(arrow_box) -{} -void PromptDialogDetector::make_overlays(VideoOverlaySet& items) const{ - m_box.make_overlays(items); - items.add(m_box.color(), m_gradient); -} -bool PromptDialogDetector::detect(const ImageViewRGB32& screen){ - if (!m_box.detect(screen)){ - return false; - } - - GradientArrowDetector gradiant_detector(COLOR_RED, GradientArrowType::RIGHT, m_gradient); - return gradiant_detector.detect(screen); -} - - - - - - - - - -} -} -} +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_DialogArrowDetector.h" +#include "PokemonSV_GradientArrowDetector.h" +#include "PokemonSV_DialogDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +DialogBoxDetector::DialogBoxDetector(Color color, bool true_if_detected, DialogType type) + : m_color(color) + , m_true_if_detected(true_if_detected) + , m_box_top(0.50, 0.74, 0.20, 0.01) + , m_box_bot(0.30, 0.88, 0.40, 0.01) + , m_border_top(0.24, 0.71, 0.52, 0.04) + , m_border_bot(0.24, 0.88, 0.52, 0.04) + , m_dialog_type(type) +{} +void DialogBoxDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_top); + items.add(m_color, m_box_bot); + items.add(m_color, m_border_top); + items.add(m_color, m_border_bot); +} +bool DialogBoxDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats_box_top = image_stats(extract_box_reference(screen, m_box_top)); +// cout << stats_box_top.average << stats_box_top.stddev << endl; + bool white; + if (is_white(stats_box_top)){ + white = true; + if (m_dialog_type == DialogType::DIALOG_BLACK){ + return !m_true_if_detected; + } + }else if (is_black(stats_box_top, 150)){ + white = false; + if (m_dialog_type == DialogType::DIALOG_WHITE){ + return !m_true_if_detected; + } + }else{ + return !m_true_if_detected; + } + +// cout << "white = " << white << endl; + + ImageStats stats_box_bot = image_stats(extract_box_reference(screen, m_box_bot)); +// cout << stats_box_bot.average << stats_box_bot.stddev << endl; + if (white){ + if (!is_white(stats_box_bot)){ + return !m_true_if_detected; + } + }else{ + if (!is_black(stats_box_bot, 150)){ + return !m_true_if_detected; + } + } + + ImageStats stats_border_top = image_stats(extract_box_reference(screen, m_border_top)); +// cout << stats_border_top.average << stats_border_top.stddev << endl; + if (stats_border_top.stddev.sum() < 50){ + return !m_true_if_detected; + } + + ImageStats stats_border_bot = image_stats(extract_box_reference(screen, m_border_bot)); +// cout << stats_border_bot.average << stats_border_bot.stddev << endl; + if (stats_border_bot.stddev.sum() < 20){ + return !m_true_if_detected; + } + + return m_true_if_detected; +} + + + + +AdvanceDialogDetector::AdvanceDialogDetector(Color color, DialogType type) + : m_box(color, true, type) + , m_arrow(0.710, 0.850, 0.030, 0.042) +{} +void AdvanceDialogDetector::make_overlays(VideoOverlaySet& items) const{ + m_box.make_overlays(items); + items.add(m_box.color(), m_arrow); +} +bool AdvanceDialogDetector::detect(const ImageViewRGB32& screen){ + if (!m_box.detect(screen)){ + return false; + } + + DialogArrowDetector arrow_detector(COLOR_RED, m_arrow); + return arrow_detector.detect(screen); +} + + + + +PromptDialogDetector::PromptDialogDetector(Color color) + : PromptDialogDetector(color, {0.50, 0.40, 0.40, 0.50}) +{} +PromptDialogDetector::PromptDialogDetector(Color color, const ImageFloatBox& arrow_box) + : m_box(color) + , m_gradient(arrow_box) +{} +void PromptDialogDetector::make_overlays(VideoOverlaySet& items) const{ + m_box.make_overlays(items); + items.add(m_box.color(), m_gradient); +} +bool PromptDialogDetector::detect(const ImageViewRGB32& screen){ + if (!m_box.detect(screen)){ + return false; + } + + GradientArrowDetector gradiant_detector(COLOR_RED, GradientArrowType::RIGHT, m_gradient); + return gradiant_detector.detect(screen); +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h index 3a53794a9b..ca4ec0898e 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h @@ -1,123 +1,123 @@ -/* Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_DialogDetector_H -#define PokemonAutomation_PokemonSV_DialogDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class DialogType{ - DIALOG_WHITE, - DIALOG_BLACK, - DIALOG_ALL -}; - -// Detect any dialog box. -class DialogBoxDetector : public StaticScreenDetector{ -public: - DialogBoxDetector(Color color = COLOR_RED, bool true_if_detected = true, DialogType type = DialogType::DIALOG_ALL); - - Color color() const{ return m_color; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - bool m_true_if_detected; - ImageFloatBox m_box_top; - ImageFloatBox m_box_bot; - ImageFloatBox m_border_top; - ImageFloatBox m_border_bot; - DialogType m_dialog_type; -}; -class DialogBoxWatcher : public DetectorToFinder{ -public: - DialogBoxWatcher( - Color color, - bool trigger_if_detected, - std::chrono::milliseconds duration = std::chrono::milliseconds(250), - DialogType type = DialogType::DIALOG_ALL - ) - : DetectorToFinder("DialogBoxWatcher", duration, color, trigger_if_detected, type) - {} -}; - - - - -// Detect dialog that has the small arrow at bottom to show the next dialog. -// It should be able to detect both the white background dialog and black background dialog. -class AdvanceDialogDetector : public StaticScreenDetector{ -public: - AdvanceDialogDetector(Color color = COLOR_RED, DialogType type = DialogType::DIALOG_ALL); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - DialogBoxDetector m_box; - ImageFloatBox m_arrow; -}; -class AdvanceDialogWatcher : public DetectorToFinder{ -public: - AdvanceDialogWatcher(Color color, DialogType type = DialogType::DIALOG_ALL, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) - : DetectorToFinder("AdvanceDialogWatcher", duration, color, type) - {} -}; - - - -// Detect dialog that prompts the player to make a choice. -// i.e. detects that Dialog box and Gradient arrow are present -class PromptDialogDetector : public StaticScreenDetector{ -public: - // Will catch any prompt. - PromptDialogDetector(Color color); - - // Will only look for prompts with the cursor in this box. - PromptDialogDetector(Color color, const ImageFloatBox& arrow_box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - DialogBoxDetector m_box; - ImageFloatBox m_gradient; -}; -class PromptDialogWatcher : public DetectorToFinder{ -public: - PromptDialogWatcher( - Color color, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("PromptDialogWatcher", duration, color) - {} - PromptDialogWatcher( - Color color, - const ImageFloatBox& arrow_box, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("PromptDialogWatcher", duration, color, arrow_box) - {} -}; - - - - - -} -} -} -#endif +/* Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_DialogDetector_H +#define PokemonAutomation_PokemonSV_DialogDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class DialogType{ + DIALOG_WHITE, + DIALOG_BLACK, + DIALOG_ALL +}; + +// Detect any dialog box. +class DialogBoxDetector : public StaticScreenDetector{ +public: + DialogBoxDetector(Color color = COLOR_RED, bool true_if_detected = true, DialogType type = DialogType::DIALOG_ALL); + + Color color() const{ return m_color; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + bool m_true_if_detected; + ImageFloatBox m_box_top; + ImageFloatBox m_box_bot; + ImageFloatBox m_border_top; + ImageFloatBox m_border_bot; + DialogType m_dialog_type; +}; +class DialogBoxWatcher : public DetectorToFinder{ +public: + DialogBoxWatcher( + Color color, + bool trigger_if_detected, + std::chrono::milliseconds duration = std::chrono::milliseconds(250), + DialogType type = DialogType::DIALOG_ALL + ) + : DetectorToFinder("DialogBoxWatcher", duration, color, trigger_if_detected, type) + {} +}; + + + + +// Detect dialog that has the small arrow at bottom to show the next dialog. +// It should be able to detect both the white background dialog and black background dialog. +class AdvanceDialogDetector : public StaticScreenDetector{ +public: + AdvanceDialogDetector(Color color = COLOR_RED, DialogType type = DialogType::DIALOG_ALL); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + DialogBoxDetector m_box; + ImageFloatBox m_arrow; +}; +class AdvanceDialogWatcher : public DetectorToFinder{ +public: + AdvanceDialogWatcher(Color color, DialogType type = DialogType::DIALOG_ALL, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) + : DetectorToFinder("AdvanceDialogWatcher", duration, color, type) + {} +}; + + + +// Detect dialog that prompts the player to make a choice. +// i.e. detects that Dialog box and Gradient arrow are present +class PromptDialogDetector : public StaticScreenDetector{ +public: + // Will catch any prompt. + PromptDialogDetector(Color color); + + // Will only look for prompts with the cursor in this box. + PromptDialogDetector(Color color, const ImageFloatBox& arrow_box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + DialogBoxDetector m_box; + ImageFloatBox m_gradient; +}; +class PromptDialogWatcher : public DetectorToFinder{ +public: + PromptDialogWatcher( + Color color, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("PromptDialogWatcher", duration, color) + {} + PromptDialogWatcher( + Color color, + const ImageFloatBox& arrow_box, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("PromptDialogWatcher", duration, color, arrow_box) + {} +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.cpp index ecf0155abe..0dd8f404dc 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.cpp @@ -1,275 +1,275 @@ -/* Gradient Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "PokemonSV_GradientArrowDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - - -const ImageMatch::ExactImageMatcher& GRADIENT_ARROW_HORIZONTAL(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/GradientArrowHorizontal-Template.png"); - return matcher; -} -const ImageMatch::ExactImageMatcher& GRADIENT_ARROW_VERTICAL(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/GradientArrowVertical-Template.png"); - return matcher; -} - -bool is_gradient_arrow( - GradientArrowType type, - const ImageViewRGB32& image, - WaterfillObject& object, - const WaterfillObject& yellow, const WaterfillObject& blue -){ - object = yellow; - object.merge_assume_no_overlap(blue); - - if (object.width() < 20){ - return false; - } - - ImageViewRGB32 cropped = extract_box_reference(image, object); -// cropped.save("test.png"); - - const double THRESHOLD = 80; - - double aspect_ratio = object.aspect_ratio(); - switch (type){ - case GradientArrowType::RIGHT:{ - if (!(yellow.min_y < blue.min_y && blue.max_y < yellow.max_y)){ -// cout << "bad position" << endl; - return false; - } - if (!(0.7 < aspect_ratio && aspect_ratio < 1.0)){ -// cout << "bad aspect ratio" << endl; - return false; - } - double rmsd = GRADIENT_ARROW_HORIZONTAL().rmsd(cropped); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= THRESHOLD; - } - case GradientArrowType::DOWN:{ - if (!(yellow.min_x < blue.min_x && blue.max_x < yellow.max_x)){ -// cout << "bad position" << endl; - return false; - } - if (!(1.0 < aspect_ratio && aspect_ratio < 1.43)){ -// cout << "bad aspect ratio" << endl; - return false; - } - double rmsd = GRADIENT_ARROW_VERTICAL().rmsd(cropped); -// cout << "rmsd = " << rmsd << endl; - return rmsd <= THRESHOLD; - } - } - - return false; -} - - - -GradientArrowDetector::GradientArrowDetector( - Color color, - GradientArrowType type, - const ImageFloatBox& box -) - : m_color(color) - , m_type(type) - , m_box(box) -{} -void GradientArrowDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool GradientArrowDetector::detect(const ImageViewRGB32& screen){ - ImageFloatBox box; - return detect(box, screen); -} - -bool GradientArrowDetector::detect(ImageFloatBox& box, const ImageViewRGB32& screen) const{ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, m_box); -// region.save("test.png"); - - std::vector yellows; - std::vector blues; - std::unique_ptr session = make_WaterfillSession(); - { - std::vector matrices = compress_rgb32_to_binary_range( - region, - { - {0xff808000, 0xffffff7f}, - {0xff808000, 0xffffff3f}, - - {0xffa0a000, 0xffffff7f}, - {0xffa0a000, 0xffffff3f}, - - {0xffc0c000, 0xffffff7f}, - {0xffc0c000, 0xffffff3f}, - - {0xffe0e000, 0xffffff7f}, - {0xffe0e000, 0xffffff3f}, - - {0xfff0f000, 0xffffff7f}, - {0xfff0f000, 0xffffff3f}, - - {0xfff8f800, 0xffffff7f}, - {0xfff8f800, 0xffffff3f}, - } - ); - -// size_t c = 0; -// PackedBinaryMatrix yellow_matrix = compress_rgb32_to_binary_range(region, 0xffc0c000, 0xffffff7f); - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - while (iter->find_next(object, false)){ -// cout << "yellow = " << object.area << endl; -// extract_box_reference(region, object).save("yellow-" + std::to_string(c++) + ".png"); - yellows.emplace_back(std::move(object)); - } - } - } - { - std::vector> filters; - const std::array LG{0x40, 0x80, 0xc0}; - const std::array LB{0x80, 0xc0, 0xe0}; - const std::array HR{0x0f, 0x3f, 0x5f, 0x7f}; - const std::array HG{0xdf, 0xff}; - for (uint32_t lg : LG){ - for (uint32_t lb : LB){ - for (uint32_t hr : HR){ - for (uint32_t hg : HG){ - filters.emplace_back( - 0xff000000 | (lg << 8) | (lb << 0), - 0xff0000ff | (hr << 16) | (hg << 8) - ); - } - } - } - } - std::vector matrices = compress_rgb32_to_binary_range( - region, -#if 1 - filters -#else - { - {0xff004080, 0xff7fffff}, - {0xff004080, 0xff5fffff}, - {0xff004080, 0xff3fffff}, - {0xff004080, 0xff0fffff}, - - {0xff008080, 0xff7fffff}, - {0xff008080, 0xff5fffff}, - {0xff008080, 0xff3fffff}, - {0xff008080, 0xff0fffff}, - - {0xff0080c0, 0xff7fffff}, - {0xff0080c0, 0xff5fffff}, - {0xff0080c0, 0xff3fffff}, - {0xff0080c0, 0xff0fffff}, - - {0xff00c0c0, 0xff7fffff}, - {0xff00c0c0, 0xff5fffff}, - {0xff00c0c0, 0xff3fffff}, - {0xff00c0c0, 0xff0fffff}, - - {0xff00c0e0, 0xff7fffff}, - {0xff00c0e0, 0xff5fffff}, - {0xff00c0e0, 0xff3fffff}, - {0xff00c0e0, 0xff0fffff}, - } -#endif - ); -// PackedBinaryMatrix blue_matrix = compress_rgb32_to_binary_range(region, 0xff00c0c0, 0xff3fdfff); -// cout << blue_matrix.dump() << endl; -// size_t c = 0; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - while (iter->find_next(object, false)){ -// cout << "blue = " << object.area << endl; -// extract_box_reference(region, object).save("blue-" + std::to_string(c++) + ".png"); - blues.emplace_back(std::move(object)); - } - } - } - -// std::vector hits; - -// size_t c = 0; - for (WaterfillObject& yellow : yellows){ - for (WaterfillObject& blue : blues){ - WaterfillObject object; - if (is_gradient_arrow(m_type, region, object, yellow, blue)){ -// hits.emplace_back(translate_to_parent(screen, m_box, object)); -// extract_box_reference(region, object).save("object.png"); - box = translate_to_parent(screen, m_box, object); - return true; - } -// double aspect_ratio = object.aspect_ratio(); -// cout << "aspect_ratio = " << aspect_ratio << endl; -// extract_box_reference(region, object).save("object-" + std::to_string(c++) + ".png"); - - } - } - - return false; -} - - - -#if 0 -GradientArrowWatcher::~GradientArrowWatcher() = default; -GradientArrowWatcher::GradientArrowWatcher( - Color color, - GradientArrowType type, - const ImageFloatBox& box -) - : VisualInferenceCallback("GradientArrowWatcher") - , m_detector(color, type, box) -{} - -void GradientArrowWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} -bool GradientArrowWatcher::process_frame(const VideoSnapshot& frame){ - bool detected = m_detector.detect(frame); - if (detected){ -// m_last_detected = frame; - } - return detected; -} -//bool GradientArrowWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ -// return m_detector.detect(frame); -//} -#endif - - - - -} -} -} +/* Gradient Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "PokemonSV_GradientArrowDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + + +const ImageMatch::ExactImageMatcher& GRADIENT_ARROW_HORIZONTAL(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/GradientArrowHorizontal-Template.png"); + return matcher; +} +const ImageMatch::ExactImageMatcher& GRADIENT_ARROW_VERTICAL(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/GradientArrowVertical-Template.png"); + return matcher; +} + +bool is_gradient_arrow( + GradientArrowType type, + const ImageViewRGB32& image, + WaterfillObject& object, + const WaterfillObject& yellow, const WaterfillObject& blue +){ + object = yellow; + object.merge_assume_no_overlap(blue); + + if (object.width() < 20){ + return false; + } + + ImageViewRGB32 cropped = extract_box_reference(image, object); +// cropped.save("test.png"); + + const double THRESHOLD = 80; + + double aspect_ratio = object.aspect_ratio(); + switch (type){ + case GradientArrowType::RIGHT:{ + if (!(yellow.min_y < blue.min_y && blue.max_y < yellow.max_y)){ +// cout << "bad position" << endl; + return false; + } + if (!(0.7 < aspect_ratio && aspect_ratio < 1.0)){ +// cout << "bad aspect ratio" << endl; + return false; + } + double rmsd = GRADIENT_ARROW_HORIZONTAL().rmsd(cropped); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= THRESHOLD; + } + case GradientArrowType::DOWN:{ + if (!(yellow.min_x < blue.min_x && blue.max_x < yellow.max_x)){ +// cout << "bad position" << endl; + return false; + } + if (!(1.0 < aspect_ratio && aspect_ratio < 1.43)){ +// cout << "bad aspect ratio" << endl; + return false; + } + double rmsd = GRADIENT_ARROW_VERTICAL().rmsd(cropped); +// cout << "rmsd = " << rmsd << endl; + return rmsd <= THRESHOLD; + } + } + + return false; +} + + + +GradientArrowDetector::GradientArrowDetector( + Color color, + GradientArrowType type, + const ImageFloatBox& box +) + : m_color(color) + , m_type(type) + , m_box(box) +{} +void GradientArrowDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool GradientArrowDetector::detect(const ImageViewRGB32& screen){ + ImageFloatBox box; + return detect(box, screen); +} + +bool GradientArrowDetector::detect(ImageFloatBox& box, const ImageViewRGB32& screen) const{ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, m_box); +// region.save("test.png"); + + std::vector yellows; + std::vector blues; + std::unique_ptr session = make_WaterfillSession(); + { + std::vector matrices = compress_rgb32_to_binary_range( + region, + { + {0xff808000, 0xffffff7f}, + {0xff808000, 0xffffff3f}, + + {0xffa0a000, 0xffffff7f}, + {0xffa0a000, 0xffffff3f}, + + {0xffc0c000, 0xffffff7f}, + {0xffc0c000, 0xffffff3f}, + + {0xffe0e000, 0xffffff7f}, + {0xffe0e000, 0xffffff3f}, + + {0xfff0f000, 0xffffff7f}, + {0xfff0f000, 0xffffff3f}, + + {0xfff8f800, 0xffffff7f}, + {0xfff8f800, 0xffffff3f}, + } + ); + +// size_t c = 0; +// PackedBinaryMatrix yellow_matrix = compress_rgb32_to_binary_range(region, 0xffc0c000, 0xffffff7f); + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + while (iter->find_next(object, false)){ +// cout << "yellow = " << object.area << endl; +// extract_box_reference(region, object).save("yellow-" + std::to_string(c++) + ".png"); + yellows.emplace_back(std::move(object)); + } + } + } + { + std::vector> filters; + const std::array LG{0x40, 0x80, 0xc0}; + const std::array LB{0x80, 0xc0, 0xe0}; + const std::array HR{0x0f, 0x3f, 0x5f, 0x7f}; + const std::array HG{0xdf, 0xff}; + for (uint32_t lg : LG){ + for (uint32_t lb : LB){ + for (uint32_t hr : HR){ + for (uint32_t hg : HG){ + filters.emplace_back( + 0xff000000 | (lg << 8) | (lb << 0), + 0xff0000ff | (hr << 16) | (hg << 8) + ); + } + } + } + } + std::vector matrices = compress_rgb32_to_binary_range( + region, +#if 1 + filters +#else + { + {0xff004080, 0xff7fffff}, + {0xff004080, 0xff5fffff}, + {0xff004080, 0xff3fffff}, + {0xff004080, 0xff0fffff}, + + {0xff008080, 0xff7fffff}, + {0xff008080, 0xff5fffff}, + {0xff008080, 0xff3fffff}, + {0xff008080, 0xff0fffff}, + + {0xff0080c0, 0xff7fffff}, + {0xff0080c0, 0xff5fffff}, + {0xff0080c0, 0xff3fffff}, + {0xff0080c0, 0xff0fffff}, + + {0xff00c0c0, 0xff7fffff}, + {0xff00c0c0, 0xff5fffff}, + {0xff00c0c0, 0xff3fffff}, + {0xff00c0c0, 0xff0fffff}, + + {0xff00c0e0, 0xff7fffff}, + {0xff00c0e0, 0xff5fffff}, + {0xff00c0e0, 0xff3fffff}, + {0xff00c0e0, 0xff0fffff}, + } +#endif + ); +// PackedBinaryMatrix blue_matrix = compress_rgb32_to_binary_range(region, 0xff00c0c0, 0xff3fdfff); +// cout << blue_matrix.dump() << endl; +// size_t c = 0; + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + while (iter->find_next(object, false)){ +// cout << "blue = " << object.area << endl; +// extract_box_reference(region, object).save("blue-" + std::to_string(c++) + ".png"); + blues.emplace_back(std::move(object)); + } + } + } + +// std::vector hits; + +// size_t c = 0; + for (WaterfillObject& yellow : yellows){ + for (WaterfillObject& blue : blues){ + WaterfillObject object; + if (is_gradient_arrow(m_type, region, object, yellow, blue)){ +// hits.emplace_back(translate_to_parent(screen, m_box, object)); +// extract_box_reference(region, object).save("object.png"); + box = translate_to_parent(screen, m_box, object); + return true; + } +// double aspect_ratio = object.aspect_ratio(); +// cout << "aspect_ratio = " << aspect_ratio << endl; +// extract_box_reference(region, object).save("object-" + std::to_string(c++) + ".png"); + + } + } + + return false; +} + + + +#if 0 +GradientArrowWatcher::~GradientArrowWatcher() = default; +GradientArrowWatcher::GradientArrowWatcher( + Color color, + GradientArrowType type, + const ImageFloatBox& box +) + : VisualInferenceCallback("GradientArrowWatcher") + , m_detector(color, type, box) +{} + +void GradientArrowWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} +bool GradientArrowWatcher::process_frame(const VideoSnapshot& frame){ + bool detected = m_detector.detect(frame); + if (detected){ +// m_last_detected = frame; + } + return detected; +} +//bool GradientArrowWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ +// return m_detector.detect(frame); +//} +#endif + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h index 6076094496..fc2bc05a81 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h @@ -1,87 +1,87 @@ -/* Gradient Arrow Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_GradientArrowDetector_H -#define PokemonAutomation_PokemonSV_GradientArrowDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -enum class GradientArrowType{ - RIGHT, - DOWN, -}; - - -class GradientArrowDetector : public StaticScreenDetector{ -public: - GradientArrowDetector( - Color color, - GradientArrowType type, - const ImageFloatBox& box - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // If arrow is found, returns true and "box" contains the box for the arrow. - // Otherwise, returns false and "box" is undefined. - bool detect(ImageFloatBox& box, const ImageViewRGB32& screen) const; - -protected: - Color m_color; - GradientArrowType m_type; - ImageFloatBox m_box; -}; - - -class GradientArrowWatcher : public DetectorToFinder{ -public: - GradientArrowWatcher( - Color color, - GradientArrowType type, - const ImageFloatBox& box, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("GradientArrowWatcher", hold_duration, color, type, box) - {} -}; - - -#if 0 -class GradientArrowWatcher : public VisualInferenceCallback{ -public: - ~GradientArrowWatcher(); - GradientArrowWatcher( - Color color, - GradientArrowType type, - const ImageFloatBox& box - ); - -// VideoSnapshot last_detected() const{ return m_last_detected; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; -// virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -protected: - GradientArrowDetector m_detector; - -// VideoSnapshot m_last_detected; -}; -#endif - - -} -} -} -#endif +/* Gradient Arrow Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_GradientArrowDetector_H +#define PokemonAutomation_PokemonSV_GradientArrowDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class GradientArrowType{ + RIGHT, + DOWN, +}; + + +class GradientArrowDetector : public StaticScreenDetector{ +public: + GradientArrowDetector( + Color color, + GradientArrowType type, + const ImageFloatBox& box + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // If arrow is found, returns true and "box" contains the box for the arrow. + // Otherwise, returns false and "box" is undefined. + bool detect(ImageFloatBox& box, const ImageViewRGB32& screen) const; + +protected: + Color m_color; + GradientArrowType m_type; + ImageFloatBox m_box; +}; + + +class GradientArrowWatcher : public DetectorToFinder{ +public: + GradientArrowWatcher( + Color color, + GradientArrowType type, + const ImageFloatBox& box, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("GradientArrowWatcher", hold_duration, color, type, box) + {} +}; + + +#if 0 +class GradientArrowWatcher : public VisualInferenceCallback{ +public: + ~GradientArrowWatcher(); + GradientArrowWatcher( + Color color, + GradientArrowType type, + const ImageFloatBox& box + ); + +// VideoSnapshot last_detected() const{ return m_last_detected; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; +// virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +protected: + GradientArrowDetector m_detector; + +// VideoSnapshot m_last_detected; +}; +#endif + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp index 4b850eb572..a8cb2da708 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.cpp @@ -1,160 +1,160 @@ -/* Tournament Prize Jobs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_ItemPrinterJobsDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -ItemPrinterJobsDetector::ItemPrinterJobsDetector(Color color) - : m_color(color) - , m_box_normal(0.86, 0.34, 0.045, 0.050) - , m_box_bonus(0.86, 0.423, 0.045, 0.050) -{} - -void ItemPrinterJobsDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box_normal); - items.add(m_color, m_box_bonus); -} -std::pair ItemPrinterJobsDetector::read_box( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen, const ImageFloatBox& box -) const{ - ImageViewRGB32 cropped = extract_box_reference(screen, box); - - std::vector> filtered = to_blackwhite_rgb32_range( - cropped, - { - {true, 0xff808080, 0xffffffff}, - {true, 0xff909090, 0xffffffff}, - {true, 0xffa0a0a0, 0xffffffff}, - {true, 0xffb0b0b0, 0xffffffff}, - {true, 0xffc0c0c0, 0xffffffff}, - {true, 0xffd0d0d0, 0xffffffff}, - {true, 0xffe0e0e0, 0xffffffff}, - {true, 0xfff0f0f0, 0xffffffff}, - } - ); - - SpinLock lock; - std::map candidates; - std::vector> tasks(filtered.size()); - for (size_t c = 0; c < filtered.size(); c++){ - tasks[c] = dispatcher.dispatch([&, c]{ - int num = OCR::read_number(logger, filtered[c].first); - std::string str = std::to_string(num); - WriteSpinLock lg(lock); - if (str == "1"){ - candidates[1]++; - }else if (str == "5"){ - candidates[5]++; - }else if (str == "10"){ - candidates[10]++; - }else if (str[0] == '5'){ - candidates[5]++; - }else if (str[0] == '1' && str[1] == '0'){ - candidates[10]++; - }else if (str[0] == '1' && str[1] == '5'){ - }else if (str[0] == '1'){ - candidates[1]++; - } - }); - } - - // Wait for everything. - for (auto& task : tasks){ - task->wait_and_rethrow_exceptions(); - } - - std::pair best; - for (const auto& item : candidates){ - if (item.second > best.second){ - best = item; - } - } - - return best; - - -#if 0 - ImageRGB32 filtered = to_blackwhite_rgb32_range(cropped, 0xffc0c0c0, 0xffffffff, true); - - static int c = 0; - filtered.save("test-" + std::to_string(c++) + ".png"); - - int num = OCR::read_number(logger, filtered, m_language); - std::string str = std::to_string(num); - if (str[0] == '5'){ - return 5; - } - if (str[0] == '1' && str[1] == '0'){ - return 10; - } - if (str[0] == '1'){ - return 1; - } - return 0; -#endif -} -uint8_t ItemPrinterJobsDetector::detect_jobs(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ - std::pair normal = read_box(logger, dispatcher, screen, m_box_normal); - if (normal.second > 6){ - return normal.first; - } - std::pair bonus = read_box(logger, dispatcher, screen, m_box_bonus); - if (normal.second + 2 > bonus.second){ - return normal.first; - }else{ - return bonus.first; - } -} - - -void ItemPrinterJobsDetector::set_print_jobs( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, uint8_t jobs -) const{ - VideoSnapshot snapshot; - for (size_t c = 0; c < 10; c++){ - context.wait_for_all_requests(); - snapshot = stream.video().snapshot(); - uint8_t current_jobs = detect_jobs(stream.logger(), dispatcher, snapshot); - if (current_jobs == jobs){ - return; - } - pbf_press_button(context, BUTTON_R, 20, 30); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to set jobs after 10 tries.", - &stream, - std::move(snapshot.frame) - ); -} - - - - - - - -} -} -} +/* Tournament Prize Jobs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_ItemPrinterJobsDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +ItemPrinterJobsDetector::ItemPrinterJobsDetector(Color color) + : m_color(color) + , m_box_normal(0.86, 0.34, 0.045, 0.050) + , m_box_bonus(0.86, 0.423, 0.045, 0.050) +{} + +void ItemPrinterJobsDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box_normal); + items.add(m_color, m_box_bonus); +} +std::pair ItemPrinterJobsDetector::read_box( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen, const ImageFloatBox& box +) const{ + ImageViewRGB32 cropped = extract_box_reference(screen, box); + + std::vector> filtered = to_blackwhite_rgb32_range( + cropped, + { + {true, 0xff808080, 0xffffffff}, + {true, 0xff909090, 0xffffffff}, + {true, 0xffa0a0a0, 0xffffffff}, + {true, 0xffb0b0b0, 0xffffffff}, + {true, 0xffc0c0c0, 0xffffffff}, + {true, 0xffd0d0d0, 0xffffffff}, + {true, 0xffe0e0e0, 0xffffffff}, + {true, 0xfff0f0f0, 0xffffffff}, + } + ); + + SpinLock lock; + std::map candidates; + std::vector> tasks(filtered.size()); + for (size_t c = 0; c < filtered.size(); c++){ + tasks[c] = dispatcher.dispatch([&, c]{ + int num = OCR::read_number(logger, filtered[c].first); + std::string str = std::to_string(num); + WriteSpinLock lg(lock); + if (str == "1"){ + candidates[1]++; + }else if (str == "5"){ + candidates[5]++; + }else if (str == "10"){ + candidates[10]++; + }else if (str[0] == '5'){ + candidates[5]++; + }else if (str[0] == '1' && str[1] == '0'){ + candidates[10]++; + }else if (str[0] == '1' && str[1] == '5'){ + }else if (str[0] == '1'){ + candidates[1]++; + } + }); + } + + // Wait for everything. + for (auto& task : tasks){ + task->wait_and_rethrow_exceptions(); + } + + std::pair best; + for (const auto& item : candidates){ + if (item.second > best.second){ + best = item; + } + } + + return best; + + +#if 0 + ImageRGB32 filtered = to_blackwhite_rgb32_range(cropped, 0xffc0c0c0, 0xffffffff, true); + + static int c = 0; + filtered.save("test-" + std::to_string(c++) + ".png"); + + int num = OCR::read_number(logger, filtered, m_language); + std::string str = std::to_string(num); + if (str[0] == '5'){ + return 5; + } + if (str[0] == '1' && str[1] == '0'){ + return 10; + } + if (str[0] == '1'){ + return 1; + } + return 0; +#endif +} +uint8_t ItemPrinterJobsDetector::detect_jobs(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ + std::pair normal = read_box(logger, dispatcher, screen, m_box_normal); + if (normal.second > 6){ + return normal.first; + } + std::pair bonus = read_box(logger, dispatcher, screen, m_box_bonus); + if (normal.second + 2 > bonus.second){ + return normal.first; + }else{ + return bonus.first; + } +} + + +void ItemPrinterJobsDetector::set_print_jobs( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, uint8_t jobs +) const{ + VideoSnapshot snapshot; + for (size_t c = 0; c < 10; c++){ + context.wait_for_all_requests(); + snapshot = stream.video().snapshot(); + uint8_t current_jobs = detect_jobs(stream.logger(), dispatcher, snapshot); + if (current_jobs == jobs){ + return; + } + pbf_press_button(context, BUTTON_R, 20, 30); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to set jobs after 10 tries.", + &stream, + std::move(snapshot.frame) + ); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h index 1361104938..f3ce22f985 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h @@ -1,54 +1,54 @@ -/* Item Printer Jobs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterJobsDetector_H -#define PokemonAutomation_PokemonSV_ItemPrinterJobsDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class Logger; - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class ItemPrinterJobsDetector{ -public: - ItemPrinterJobsDetector(Color color); - - void make_overlays(VideoOverlaySet& items) const; - uint8_t detect_jobs(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; - - // "jobs" jobs must be 1, 5, or 10. - void set_print_jobs( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, uint8_t jobs - ) const; - - -private: - std::pair read_box( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen, const ImageFloatBox& box - ) const; - -private: - Color m_color; - ImageFloatBox m_box_normal; - ImageFloatBox m_box_bonus; - -}; - - - -} -} -} -#endif +/* Item Printer Jobs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterJobsDetector_H +#define PokemonAutomation_PokemonSV_ItemPrinterJobsDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class Logger; + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class ItemPrinterJobsDetector{ +public: + ItemPrinterJobsDetector(Color color); + + void make_overlays(VideoOverlaySet& items) const; + uint8_t detect_jobs(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; + + // "jobs" jobs must be 1, 5, or 10. + void set_print_jobs( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, uint8_t jobs + ) const; + + +private: + std::pair read_box( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen, const ImageFloatBox& box + ) const; + +private: + Color m_color; + ImageFloatBox m_box_normal; + ImageFloatBox m_box_bonus; + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp index d4b0da6005..af21270cad 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.cpp @@ -1,261 +1,261 @@ -/* Tournament Prize Jobs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_ItemPrinterMaterialDetector.h" - -// #include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -MaterialNameReader& MaterialNameReader::instance(){ - static MaterialNameReader reader; - return reader; -} - -// MaterialNameReader has a very limited dictionary, -// so it can only reliably read the material names with 68% value -// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) -MaterialNameReader::MaterialNameReader() - : SmallDictionaryMatcher("PokemonSV/ItemPrinterMaterialOCR.json") -{} - -OCR::StringMatchResult MaterialNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - -ItemPrinterMaterialDetector::ItemPrinterMaterialDetector(Color color, Language language) - : m_color(color) - , m_language(language) - , m_box_mat_value(Material_Boxes(ImageFloatBox(0.39, 0.176758, 0.025, 0.050))) - , m_box_mat_quantity(Material_Boxes(ImageFloatBox(0.485, 0.176758, 0.037, 0.050))) - , m_box_mat_name(Material_Boxes(ImageFloatBox(0.090, 0.176758, 0.275, 0.050))) -{} - -std::array ItemPrinterMaterialDetector::Material_Boxes(ImageFloatBox initial_box){ - std::array material_boxes; - double x = initial_box.x; - double width = initial_box.width; - double height = initial_box.height; - double initial_y = initial_box.y; - double y_spacing = 0.074219; - for (size_t i = 0; i < 10; i++){ - double y = initial_y + i*y_spacing; - material_boxes[i] = ImageFloatBox(x, y, width, height); - // std::cout << "{" << x << "," << y << "," << width << "," << height << "}, "; - } - // std::cout << std::endl; - return material_boxes; -} - -void ItemPrinterMaterialDetector::make_overlays(VideoOverlaySet& items) const{ - for (size_t i = 0; i < 10; i++){ - items.add(m_color, m_box_mat_value[i]); - items.add(m_color, m_box_mat_quantity[i]); - items.add(m_color, m_box_mat_name[i]); - } -} - -int16_t ItemPrinterMaterialDetector::read_number( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen, const ImageFloatBox& box, - int8_t row_index -) const{ - - ImageViewRGB32 cropped = extract_box_reference(screen, box); - ImageRGB32 filtered = to_blackwhite_rgb32_range( - cropped, - true, - 0xff000000, 0xff808080 - ); - // filtered.save("DebugDumps/test-one-filter-1.png"); - bool is_dark_text_light_background = image_stats(filtered).average.sum() > 400; - // std::cout << "Average sum of filtered: "<< std::to_string(image_stats(filtered).average.sum()) << std::endl; - - const std::vector> filters = - [&](){ - if (is_dark_text_light_background){ - return std::vector>{ - // {0xff000000, 0xffb0b0b0}, - {0xff000000, 0xffa0a0a0}, - {0xff000000, 0xff959595}, - {0xff000000, 0xff909090}, - {0xff000000, 0xff858585}, - {0xff000000, 0xff808080}, - // {0xff000000, 0xff707070}, - // {0xff000000, 0xff606060}, - // {0xff000000, 0xff505050}, - // {0xff000000, 0xff404040}, - // {0xff000000, 0xff303030}, - // {0xff000000, 0xff202020}, - // {0xff000000, 0xff101010}, - }; - }else{ - return std::vector>{ - {0xff808080, 0xffffffff}, - {0xff858585, 0xffffffff}, - {0xff909090, 0xffffffff}, - {0xff959595, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - // {0xffb0b0b0, 0xffffffff}, - // {0xffc0c0c0, 0xffffffff}, - // {0xffd0d0d0, 0xffffffff}, - // {0xffe0e0e0, 0xffffffff}, - // {0xfff0f0f0, 0xffffffff}, - }; - } - }(); - - int16_t number = (int16_t)OCR::read_number_waterfill_multifilter(logger, cropped, filters, 24, true, true, row_index); - - if (number < 1 || number > 999){ - number = -1; - } - return (int16_t)number; -} - - -// return row number where Happiny dust is located on screen -// keep pressing DPAD_RIGHT until Happiny dust is on screen -// check each row on the screen for Happiny Dust -int8_t ItemPrinterMaterialDetector::find_happiny_dust_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context -) const{ - int8_t value_68_row_index; - for (size_t c = 0; c < 30; c++){ - context.wait_for_all_requests(); - std::vector value_68_row_index_list = find_material_value_row_index(dispatcher, stream, context, 68); - for (size_t i = 0; i < value_68_row_index_list.size(); i++){ - value_68_row_index = value_68_row_index_list[i]; - if (detect_material_name(stream, context, value_68_row_index) == "happiny-dust"){ - // found screen and row number with Happiny dust. - // std::cout << "Happiny dust found. Row number: " << std::to_string(value_68_row_index) << std::endl; - return value_68_row_index; - } - } - - // keep searching for Happiny dust - pbf_press_dpad(context, DPAD_RIGHT, 20, 30); - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find Happiny dust after 10 tries.", - stream - ); - -} - -// detects the material name at the given row_index -// MaterialNameReader has a very limited dictionary, -// so it can only reliably read the material names with 68% value -// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) -std::string ItemPrinterMaterialDetector::detect_material_name( - VideoStream& stream, - ProControllerContext& context, - int8_t row_index -) const{ - VideoSnapshot snapshot = stream.video().snapshot(); - ImageFloatBox material_name_box = m_box_mat_name[row_index]; - ImageViewRGB32 material_name_image = extract_box_reference(snapshot, material_name_box); - const auto ocr_result = MaterialNameReader::instance().read_substring( - stream.logger(), m_language, - material_name_image, OCR::BLACK_OR_WHITE_TEXT_FILTERS() - ); - - std::multimap results; - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - } - - if (results.empty()){ - return ""; - } - - if (results.size() > 1){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "ItemPrinterMaterialDetector::detect_material_name(): Unable to read selected item. Ambiguous or multiple results.", - stream - ); - } - - return results.begin()->second.token; -} - -// return vector of row index(es) that matches given material_value. -std::vector ItemPrinterMaterialDetector::find_material_value_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int16_t material_value -) const{ - context.wait_for_all_requests(); - VideoSnapshot snapshot = stream.video().snapshot(); - int8_t total_rows = 10; - std::vector row_indexes; - SpinLock lock; - std::vector> tasks(total_rows); - for (int8_t row_index = 0; row_index < total_rows; row_index++){ - tasks[row_index] = dispatcher.dispatch([&, row_index]{ - int16_t value = read_number(stream.logger(), dispatcher, snapshot, m_box_mat_value[row_index], row_index); - if (value == material_value){ - WriteSpinLock lg(lock); - row_indexes.push_back(row_index); - } - }); - } - - return row_indexes; - -} - -// detect the quantity of material at the given row number -int16_t ItemPrinterMaterialDetector::detect_material_quantity( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int8_t row_index -) const{ - context.wait_for_all_requests(); - VideoSnapshot snapshot = stream.video().snapshot(); - int16_t value = read_number(stream.logger(), dispatcher, snapshot, m_box_mat_quantity[row_index], row_index); - return value; -} - - - - -} -} -} +/* Tournament Prize Jobs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_ItemPrinterMaterialDetector.h" + +// #include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +MaterialNameReader& MaterialNameReader::instance(){ + static MaterialNameReader reader; + return reader; +} + +// MaterialNameReader has a very limited dictionary, +// so it can only reliably read the material names with 68% value +// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) +MaterialNameReader::MaterialNameReader() + : SmallDictionaryMatcher("PokemonSV/ItemPrinterMaterialOCR.json") +{} + +OCR::StringMatchResult MaterialNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + +ItemPrinterMaterialDetector::ItemPrinterMaterialDetector(Color color, Language language) + : m_color(color) + , m_language(language) + , m_box_mat_value(Material_Boxes(ImageFloatBox(0.39, 0.176758, 0.025, 0.050))) + , m_box_mat_quantity(Material_Boxes(ImageFloatBox(0.485, 0.176758, 0.037, 0.050))) + , m_box_mat_name(Material_Boxes(ImageFloatBox(0.090, 0.176758, 0.275, 0.050))) +{} + +std::array ItemPrinterMaterialDetector::Material_Boxes(ImageFloatBox initial_box){ + std::array material_boxes; + double x = initial_box.x; + double width = initial_box.width; + double height = initial_box.height; + double initial_y = initial_box.y; + double y_spacing = 0.074219; + for (size_t i = 0; i < 10; i++){ + double y = initial_y + i*y_spacing; + material_boxes[i] = ImageFloatBox(x, y, width, height); + // std::cout << "{" << x << "," << y << "," << width << "," << height << "}, "; + } + // std::cout << std::endl; + return material_boxes; +} + +void ItemPrinterMaterialDetector::make_overlays(VideoOverlaySet& items) const{ + for (size_t i = 0; i < 10; i++){ + items.add(m_color, m_box_mat_value[i]); + items.add(m_color, m_box_mat_quantity[i]); + items.add(m_color, m_box_mat_name[i]); + } +} + +int16_t ItemPrinterMaterialDetector::read_number( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen, const ImageFloatBox& box, + int8_t row_index +) const{ + + ImageViewRGB32 cropped = extract_box_reference(screen, box); + ImageRGB32 filtered = to_blackwhite_rgb32_range( + cropped, + true, + 0xff000000, 0xff808080 + ); + // filtered.save("DebugDumps/test-one-filter-1.png"); + bool is_dark_text_light_background = image_stats(filtered).average.sum() > 400; + // std::cout << "Average sum of filtered: "<< std::to_string(image_stats(filtered).average.sum()) << std::endl; + + const std::vector> filters = + [&](){ + if (is_dark_text_light_background){ + return std::vector>{ + // {0xff000000, 0xffb0b0b0}, + {0xff000000, 0xffa0a0a0}, + {0xff000000, 0xff959595}, + {0xff000000, 0xff909090}, + {0xff000000, 0xff858585}, + {0xff000000, 0xff808080}, + // {0xff000000, 0xff707070}, + // {0xff000000, 0xff606060}, + // {0xff000000, 0xff505050}, + // {0xff000000, 0xff404040}, + // {0xff000000, 0xff303030}, + // {0xff000000, 0xff202020}, + // {0xff000000, 0xff101010}, + }; + }else{ + return std::vector>{ + {0xff808080, 0xffffffff}, + {0xff858585, 0xffffffff}, + {0xff909090, 0xffffffff}, + {0xff959595, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + // {0xffb0b0b0, 0xffffffff}, + // {0xffc0c0c0, 0xffffffff}, + // {0xffd0d0d0, 0xffffffff}, + // {0xffe0e0e0, 0xffffffff}, + // {0xfff0f0f0, 0xffffffff}, + }; + } + }(); + + int16_t number = (int16_t)OCR::read_number_waterfill_multifilter(logger, cropped, filters, 24, true, true, row_index); + + if (number < 1 || number > 999){ + number = -1; + } + return (int16_t)number; +} + + +// return row number where Happiny dust is located on screen +// keep pressing DPAD_RIGHT until Happiny dust is on screen +// check each row on the screen for Happiny Dust +int8_t ItemPrinterMaterialDetector::find_happiny_dust_row_index( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context +) const{ + int8_t value_68_row_index; + for (size_t c = 0; c < 30; c++){ + context.wait_for_all_requests(); + std::vector value_68_row_index_list = find_material_value_row_index(dispatcher, stream, context, 68); + for (size_t i = 0; i < value_68_row_index_list.size(); i++){ + value_68_row_index = value_68_row_index_list[i]; + if (detect_material_name(stream, context, value_68_row_index) == "happiny-dust"){ + // found screen and row number with Happiny dust. + // std::cout << "Happiny dust found. Row number: " << std::to_string(value_68_row_index) << std::endl; + return value_68_row_index; + } + } + + // keep searching for Happiny dust + pbf_press_dpad(context, DPAD_RIGHT, 20, 30); + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find Happiny dust after 10 tries.", + stream + ); + +} + +// detects the material name at the given row_index +// MaterialNameReader has a very limited dictionary, +// so it can only reliably read the material names with 68% value +// (i.e. Ditto Goo, Happiny Dust, Magby Hair, Beldum Claw) +std::string ItemPrinterMaterialDetector::detect_material_name( + VideoStream& stream, + ProControllerContext& context, + int8_t row_index +) const{ + VideoSnapshot snapshot = stream.video().snapshot(); + ImageFloatBox material_name_box = m_box_mat_name[row_index]; + ImageViewRGB32 material_name_image = extract_box_reference(snapshot, material_name_box); + const auto ocr_result = MaterialNameReader::instance().read_substring( + stream.logger(), m_language, + material_name_image, OCR::BLACK_OR_WHITE_TEXT_FILTERS() + ); + + std::multimap results; + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + } + + if (results.empty()){ + return ""; + } + + if (results.size() > 1){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "ItemPrinterMaterialDetector::detect_material_name(): Unable to read selected item. Ambiguous or multiple results.", + stream + ); + } + + return results.begin()->second.token; +} + +// return vector of row index(es) that matches given material_value. +std::vector ItemPrinterMaterialDetector::find_material_value_row_index( + AsyncDispatcher& dispatcher, + VideoStream& stream, + ProControllerContext& context, + int16_t material_value +) const{ + context.wait_for_all_requests(); + VideoSnapshot snapshot = stream.video().snapshot(); + int8_t total_rows = 10; + std::vector row_indexes; + SpinLock lock; + std::vector> tasks(total_rows); + for (int8_t row_index = 0; row_index < total_rows; row_index++){ + tasks[row_index] = dispatcher.dispatch([&, row_index]{ + int16_t value = read_number(stream.logger(), dispatcher, snapshot, m_box_mat_value[row_index], row_index); + if (value == material_value){ + WriteSpinLock lg(lock); + row_indexes.push_back(row_index); + } + }); + } + + return row_indexes; + +} + +// detect the quantity of material at the given row number +int16_t ItemPrinterMaterialDetector::detect_material_quantity( + AsyncDispatcher& dispatcher, + VideoStream& stream, + ProControllerContext& context, + int8_t row_index +) const{ + context.wait_for_all_requests(); + VideoSnapshot snapshot = stream.video().snapshot(); + int16_t value = read_number(stream.logger(), dispatcher, snapshot, m_box_mat_quantity[row_index], row_index); + return value; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h index 7cf94c7d30..b41f8b5217 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h @@ -1,99 +1,99 @@ -/* Item Printer Jobs Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H -#define PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class Logger; - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class MaterialNameReader : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - MaterialNameReader(); - - static MaterialNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; -}; - -class ItemPrinterMaterialDetector{ -public: - ItemPrinterMaterialDetector(Color color, Language language); - - void make_overlays(VideoOverlaySet& items) const; - - std::array Material_Boxes(ImageFloatBox initial_box); - - int8_t find_happiny_dust_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context - ) const; - - std::vector find_material_value_row_index( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int16_t material_value - ) const; - - int16_t detect_material_quantity( - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - int8_t row_index - ) const; - - std::string detect_material_name( - VideoStream& stream, - ProControllerContext& context, - int8_t row_index - ) const; - - int16_t read_number( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen, const ImageFloatBox& box, - int8_t row_index - ) const; - - -private: - Color m_color; - Language m_language; - std::array m_box_mat_value; // {0.39,0.176758,0.025,0.05}, {0.39,0.250977,0.025,0.05}, {0.39,0.325196,0.025,0.05}, {0.39,0.399415,0.025,0.05}, {0.39,0.473634,0.025,0.05}, {0.39,0.547853,0.025,0.05}, {0.39,0.622072,0.025,0.05}, {0.39,0.696291,0.025,0.05}, {0.39,0.77051,0.025,0.05}, {0.39,0.844729,0.025,0.05}, - std::array m_box_mat_quantity; // {0.485,0.176758,0.037,0.05}, {0.485,0.250977,0.037,0.05}, {0.485,0.325196,0.037,0.05}, {0.485,0.399415,0.037,0.05}, {0.485,0.473634,0.037,0.05}, {0.485,0.547853,0.037,0.05}, {0.485,0.622072,0.037,0.05}, {0.485,0.696291,0.037,0.05}, {0.485,0.77051,0.037,0.05}, {0.485,0.844729,0.037,0.05}, - std::array m_box_mat_name; // {0.09,0.176758,0.275,0.05}, {0.09,0.250977,0.275,0.05}, {0.09,0.325196,0.275,0.05}, {0.09,0.399415,0.275,0.05}, {0.09,0.473634,0.275,0.05}, {0.09,0.547853,0.275,0.05}, {0.09,0.622072,0.275,0.05}, {0.09,0.696291,0.275,0.05}, {0.09,0.77051,0.275,0.05}, {0.09,0.844729,0.275,0.05}, - - -}; - - - -} -} -} -#endif +/* Item Printer Jobs Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H +#define PokemonAutomation_PokemonSV_ItemPrinterMaterialDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class Logger; + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class MaterialNameReader : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + MaterialNameReader(); + + static MaterialNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; +}; + +class ItemPrinterMaterialDetector{ +public: + ItemPrinterMaterialDetector(Color color, Language language); + + void make_overlays(VideoOverlaySet& items) const; + + std::array Material_Boxes(ImageFloatBox initial_box); + + int8_t find_happiny_dust_row_index( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context + ) const; + + std::vector find_material_value_row_index( + AsyncDispatcher& dispatcher, + VideoStream& stream, + ProControllerContext& context, + int16_t material_value + ) const; + + int16_t detect_material_quantity( + AsyncDispatcher& dispatcher, + VideoStream& stream, + ProControllerContext& context, + int8_t row_index + ) const; + + std::string detect_material_name( + VideoStream& stream, + ProControllerContext& context, + int8_t row_index + ) const; + + int16_t read_number( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen, const ImageFloatBox& box, + int8_t row_index + ) const; + + +private: + Color m_color; + Language m_language; + std::array m_box_mat_value; // {0.39,0.176758,0.025,0.05}, {0.39,0.250977,0.025,0.05}, {0.39,0.325196,0.025,0.05}, {0.39,0.399415,0.025,0.05}, {0.39,0.473634,0.025,0.05}, {0.39,0.547853,0.025,0.05}, {0.39,0.622072,0.025,0.05}, {0.39,0.696291,0.025,0.05}, {0.39,0.77051,0.025,0.05}, {0.39,0.844729,0.025,0.05}, + std::array m_box_mat_quantity; // {0.485,0.176758,0.037,0.05}, {0.485,0.250977,0.037,0.05}, {0.485,0.325196,0.037,0.05}, {0.485,0.399415,0.037,0.05}, {0.485,0.473634,0.037,0.05}, {0.485,0.547853,0.037,0.05}, {0.485,0.622072,0.037,0.05}, {0.485,0.696291,0.037,0.05}, {0.485,0.77051,0.037,0.05}, {0.485,0.844729,0.037,0.05}, + std::array m_box_mat_name; // {0.09,0.176758,0.275,0.05}, {0.09,0.250977,0.275,0.05}, {0.09,0.325196,0.275,0.05}, {0.09,0.399415,0.275,0.05}, {0.09,0.473634,0.275,0.05}, {0.09,0.547853,0.275,0.05}, {0.09,0.622072,0.275,0.05}, {0.09,0.696291,0.275,0.05}, {0.09,0.77051,0.275,0.05}, {0.09,0.844729,0.275,0.05}, + + +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp index 1621083f88..7c30af4b16 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.cpp @@ -1,40 +1,40 @@ -/* Main Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_ItemPrinterMenuDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -ItemPrinterMenuDetector::ItemPrinterMenuDetector(Color color) - : m_color(color) - , m_bottom(0.05, 0.945, 0.50, 0.04) - , m_buttons(color, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}) -{} - -void ItemPrinterMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - m_buttons.make_overlays(items); -} -bool ItemPrinterMenuDetector::detect(const ImageViewRGB32& screen){ - ImageViewRGB32 bottom = extract_box_reference(screen, m_bottom); - ImageStats bottom_stats = image_stats(bottom); - if (!is_solid(bottom_stats, {0, 0.318898, 0.681102})){ - return false; - } - if (!m_buttons.detect(screen)){ - return false; - } - return true; -} - - -} -} -} +/* Main Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_ItemPrinterMenuDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +ItemPrinterMenuDetector::ItemPrinterMenuDetector(Color color) + : m_color(color) + , m_bottom(0.05, 0.945, 0.50, 0.04) + , m_buttons(color, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}) +{} + +void ItemPrinterMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + m_buttons.make_overlays(items); +} +bool ItemPrinterMenuDetector::detect(const ImageViewRGB32& screen){ + ImageViewRGB32 bottom = extract_box_reference(screen, m_bottom); + ImageStats bottom_stats = image_stats(bottom); + if (!is_solid(bottom_stats, {0, 0.318898, 0.681102})){ + return false; + } + if (!m_buttons.detect(screen)){ + return false; + } + return true; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h index 9ef1f47f12..31067a9882 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h @@ -1,45 +1,45 @@ -/* Main Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H -#define PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H - -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class ItemPrinterMenuDetector : public StaticScreenDetector{ -public: - ItemPrinterMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - -private: - Color m_color; - ImageFloatBox m_bottom; - WhiteButtonWatcher m_buttons; -}; -class ItemPrinterMenuWatcher : public DetectorToFinder{ -public: - ItemPrinterMenuWatcher(Color color) - : DetectorToFinder("ItemPrinterMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - -} -} -} -#endif +/* Main Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H +#define PokemonAutomation_PokemonSV_ItemPrinterMenuDetector_H + +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class ItemPrinterMenuDetector : public StaticScreenDetector{ +public: + ItemPrinterMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + +private: + Color m_color; + ImageFloatBox m_bottom; + WhiteButtonWatcher m_buttons; +}; +class ItemPrinterMenuWatcher : public DetectorToFinder{ +public: + ItemPrinterMenuWatcher(Color color) + : DetectorToFinder("ItemPrinterMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp index e71e0bbad6..8006a990c7 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.cpp @@ -1,209 +1,209 @@ -/* Item Printer - Prize Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV_ItemPrinterPrizeReader.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -class ItemPrinterPrizeOCR : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - ItemPrinterPrizeOCR() - : SmallDictionaryMatcher("PokemonSV/ItemPrinterPrizeOCR.json") - {} - - static ItemPrinterPrizeOCR& instance(){ - static ItemPrinterPrizeOCR reader; - return reader; - } - - OCR::StringMatchResult read_substring( - Logger* logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const{ - return match_substring_from_image_multifiltered( - logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); - } - -}; - - - - -ItemPrinterPrizeReader::ItemPrinterPrizeReader(Language language) - : m_language(language) -{ - for (size_t c = 0; c < 10; c++){ - m_boxes_normal[c] = ImageFloatBox(0.361, 0.175 + c * 0.0764444, 0.240, 0.060); - m_boxes_bonus[c] = ImageFloatBox(0.361, 0.204 + c * 0.0764444, 0.240, 0.060); - m_boxes_normal_quantity[c] = ImageFloatBox(0.649, 0.175 + c * 0.0764444, 0.034000, 0.060); - m_boxes_bonus_quantity[c] = ImageFloatBox(0.649, 0.204 + c * 0.0764444, 0.034000, 0.060); - } -} - -void ItemPrinterPrizeReader::make_overlays(VideoOverlaySet& items) const{ - for (size_t c = 0; c < 10; c++){ - items.add(COLOR_GREEN, m_boxes_normal[c]); - items.add(COLOR_BLUE, m_boxes_bonus[c]); - items.add(COLOR_GREEN, m_boxes_normal_quantity[c]); - items.add(COLOR_BLUE, m_boxes_bonus_quantity[c]); - } -} -std::array ItemPrinterPrizeReader::read_prizes( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen -) const{ - // OCR 20 things in parallel. - OCR::StringMatchResult results[20]; - std::unique_ptr tasks[20]; - for (size_t c = 0; c < 10; c++){ - tasks[c] = dispatcher.dispatch([=, this, &results]{ - results[c] = ItemPrinterPrizeOCR::instance().read_substring( - nullptr, m_language, - extract_box_reference(screen, m_boxes_normal[c]), - OCR::WHITE_TEXT_FILTERS() - ); - }); - } - for (size_t c = 0; c < 10; c++){ - tasks[10 + c] = dispatcher.dispatch([=, this, &results]{ - results[10 + c] = ItemPrinterPrizeOCR::instance().read_substring( - nullptr, m_language, - extract_box_reference(screen, m_boxes_bonus[c]), - OCR::WHITE_TEXT_FILTERS() - ); - }); - } - - // Wait for everything. - for (size_t c = 0; c < 20; c++){ - tasks[c]->wait_and_rethrow_exceptions(); - } - - std::array ret; - for (size_t c = 0; c < 10; c++){ - OCR::StringMatchResult& result = results[c]; - result.clear_beyond_log10p(MAX_LOG10P); - result.clear_beyond_spread(MAX_LOG10P_SPREAD); - result += results[10 + c]; - result.clear_beyond_log10p(MAX_LOG10P); - result.clear_beyond_spread(MAX_LOG10P_SPREAD); - result.log(logger, MAX_LOG10P); - if (result.results.size() != 1){ - continue; - } - ret[c] = std::move(result.results.begin()->second.token); - } - return ret; -} - - -std::array ItemPrinterPrizeReader::read_quantity( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen -) const{ - size_t total_rows = 10; - - // determine whether to use normal or bonus boxes for OCR - double total_average_sum_normal = 0; - double total_average_sum_bonus = 0; - for (size_t i = 0; i < total_rows; i++){ - total_average_sum_normal += average_sum_filtered(screen, m_boxes_normal[i]); - total_average_sum_bonus += average_sum_filtered(screen, m_boxes_bonus[i]); - } - - logger.log("total_average_sum_normal: " + std::to_string(total_average_sum_normal)); - logger.log("total_average_sum_bonus: " + std::to_string(total_average_sum_bonus)); - - if (total_average_sum_bonus > total_average_sum_normal){ - logger.log("Read quantity with bonus mode."); - }else{ - logger.log("Read quantity with normal mode."); - } - - const std::array& boxes = (total_average_sum_bonus > total_average_sum_normal) - ? m_boxes_bonus_quantity - : m_boxes_normal_quantity; - - std::array results; - std::vector> tasks(total_rows); - for (size_t i = 0; i < total_rows; i++){ - // ImageRGB32 filtered = to_blackwhite_rgb32_range( - // extract_box_reference(screen, m_boxes_bonus_quantity[i]), - // 0xff808000, 0xffffffff, - // true - // ); - // filtered.save("DebugDumps/test"+ std::to_string(i) +".png"); - - tasks[i] = dispatcher.dispatch([&, i]{ - results[i] = read_number(logger, screen, boxes[i], (int8_t)i); - }); - } - - for (size_t c = 0; c < total_rows; c++){ - tasks[c]->wait_and_rethrow_exceptions(); - } - - return results; -} - - -int16_t ItemPrinterPrizeReader::read_number( - Logger& logger, - const ImageViewRGB32& screen, - const ImageFloatBox& box, - int8_t line_index -) const{ - - ImageViewRGB32 cropped = extract_box_reference(screen, box); - int16_t number = (int16_t)OCR::read_number_waterfill(logger, cropped, 0xff808000, 0xffffffff, true, line_index); - - if (number < 1 || number > 40){ - number = 1; // default to 1 if we can't read the prize quantity - } - return (int16_t)number; -} - -double ItemPrinterPrizeReader::average_sum_filtered(const ImageViewRGB32& screen, const ImageFloatBox& box) const{ - ImageViewRGB32 cropped = extract_box_reference(screen, box); - ImageRGB32 filtered = to_blackwhite_rgb32_range( - cropped, - false, - 0xff808000, 0xffffffff - ); - - return image_stats(filtered).average.sum(); -} - - -} -} -} +/* Item Printer - Prize Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV_ItemPrinterPrizeReader.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +class ItemPrinterPrizeOCR : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + ItemPrinterPrizeOCR() + : SmallDictionaryMatcher("PokemonSV/ItemPrinterPrizeOCR.json") + {} + + static ItemPrinterPrizeOCR& instance(){ + static ItemPrinterPrizeOCR reader; + return reader; + } + + OCR::StringMatchResult read_substring( + Logger* logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const{ + return match_substring_from_image_multifiltered( + logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); + } + +}; + + + + +ItemPrinterPrizeReader::ItemPrinterPrizeReader(Language language) + : m_language(language) +{ + for (size_t c = 0; c < 10; c++){ + m_boxes_normal[c] = ImageFloatBox(0.361, 0.175 + c * 0.0764444, 0.240, 0.060); + m_boxes_bonus[c] = ImageFloatBox(0.361, 0.204 + c * 0.0764444, 0.240, 0.060); + m_boxes_normal_quantity[c] = ImageFloatBox(0.649, 0.175 + c * 0.0764444, 0.034000, 0.060); + m_boxes_bonus_quantity[c] = ImageFloatBox(0.649, 0.204 + c * 0.0764444, 0.034000, 0.060); + } +} + +void ItemPrinterPrizeReader::make_overlays(VideoOverlaySet& items) const{ + for (size_t c = 0; c < 10; c++){ + items.add(COLOR_GREEN, m_boxes_normal[c]); + items.add(COLOR_BLUE, m_boxes_bonus[c]); + items.add(COLOR_GREEN, m_boxes_normal_quantity[c]); + items.add(COLOR_BLUE, m_boxes_bonus_quantity[c]); + } +} +std::array ItemPrinterPrizeReader::read_prizes( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen +) const{ + // OCR 20 things in parallel. + OCR::StringMatchResult results[20]; + std::unique_ptr tasks[20]; + for (size_t c = 0; c < 10; c++){ + tasks[c] = dispatcher.dispatch([=, this, &results]{ + results[c] = ItemPrinterPrizeOCR::instance().read_substring( + nullptr, m_language, + extract_box_reference(screen, m_boxes_normal[c]), + OCR::WHITE_TEXT_FILTERS() + ); + }); + } + for (size_t c = 0; c < 10; c++){ + tasks[10 + c] = dispatcher.dispatch([=, this, &results]{ + results[10 + c] = ItemPrinterPrizeOCR::instance().read_substring( + nullptr, m_language, + extract_box_reference(screen, m_boxes_bonus[c]), + OCR::WHITE_TEXT_FILTERS() + ); + }); + } + + // Wait for everything. + for (size_t c = 0; c < 20; c++){ + tasks[c]->wait_and_rethrow_exceptions(); + } + + std::array ret; + for (size_t c = 0; c < 10; c++){ + OCR::StringMatchResult& result = results[c]; + result.clear_beyond_log10p(MAX_LOG10P); + result.clear_beyond_spread(MAX_LOG10P_SPREAD); + result += results[10 + c]; + result.clear_beyond_log10p(MAX_LOG10P); + result.clear_beyond_spread(MAX_LOG10P_SPREAD); + result.log(logger, MAX_LOG10P); + if (result.results.size() != 1){ + continue; + } + ret[c] = std::move(result.results.begin()->second.token); + } + return ret; +} + + +std::array ItemPrinterPrizeReader::read_quantity( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen +) const{ + size_t total_rows = 10; + + // determine whether to use normal or bonus boxes for OCR + double total_average_sum_normal = 0; + double total_average_sum_bonus = 0; + for (size_t i = 0; i < total_rows; i++){ + total_average_sum_normal += average_sum_filtered(screen, m_boxes_normal[i]); + total_average_sum_bonus += average_sum_filtered(screen, m_boxes_bonus[i]); + } + + logger.log("total_average_sum_normal: " + std::to_string(total_average_sum_normal)); + logger.log("total_average_sum_bonus: " + std::to_string(total_average_sum_bonus)); + + if (total_average_sum_bonus > total_average_sum_normal){ + logger.log("Read quantity with bonus mode."); + }else{ + logger.log("Read quantity with normal mode."); + } + + const std::array& boxes = (total_average_sum_bonus > total_average_sum_normal) + ? m_boxes_bonus_quantity + : m_boxes_normal_quantity; + + std::array results; + std::vector> tasks(total_rows); + for (size_t i = 0; i < total_rows; i++){ + // ImageRGB32 filtered = to_blackwhite_rgb32_range( + // extract_box_reference(screen, m_boxes_bonus_quantity[i]), + // 0xff808000, 0xffffffff, + // true + // ); + // filtered.save("DebugDumps/test"+ std::to_string(i) +".png"); + + tasks[i] = dispatcher.dispatch([&, i]{ + results[i] = read_number(logger, screen, boxes[i], (int8_t)i); + }); + } + + for (size_t c = 0; c < total_rows; c++){ + tasks[c]->wait_and_rethrow_exceptions(); + } + + return results; +} + + +int16_t ItemPrinterPrizeReader::read_number( + Logger& logger, + const ImageViewRGB32& screen, + const ImageFloatBox& box, + int8_t line_index +) const{ + + ImageViewRGB32 cropped = extract_box_reference(screen, box); + int16_t number = (int16_t)OCR::read_number_waterfill(logger, cropped, 0xff808000, 0xffffffff, true, line_index); + + if (number < 1 || number > 40){ + number = 1; // default to 1 if we can't read the prize quantity + } + return (int16_t)number; +} + +double ItemPrinterPrizeReader::average_sum_filtered(const ImageViewRGB32& screen, const ImageFloatBox& box) const{ + ImageViewRGB32 cropped = extract_box_reference(screen, box); + ImageRGB32 filtered = to_blackwhite_rgb32_range( + cropped, + false, + 0xff808000, 0xffffffff + ); + + return image_stats(filtered).average.sum(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h index 86508a6cf6..e063f499b8 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h @@ -1,66 +1,66 @@ -/* Item Printer - Prize Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterPrizeReader_H -#define PokemonAutomation_PokemonSV_ItemPrinterPrizeReader_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - class Logger; - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -class ItemPrinterPrizeReader{ - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - ItemPrinterPrizeReader(Language language); - - void make_overlays(VideoOverlaySet& items) const; - - std::array read_prizes( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen - ) const; - - std::array read_quantity( - Logger& logger, AsyncDispatcher& dispatcher, - const ImageViewRGB32& screen - ) const; - - int16_t read_number( - Logger& logger, - const ImageViewRGB32& screen, - const ImageFloatBox& box, - int8_t line_index = -1 - ) const; - - double average_sum_filtered(const ImageViewRGB32& screen, const ImageFloatBox& box) const; - -private: - Language m_language; - std::array m_boxes_normal; - std::array m_boxes_bonus; - std::array m_boxes_normal_quantity; - std::array m_boxes_bonus_quantity; -}; - - - - -} -} -} -#endif +/* Item Printer - Prize Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterPrizeReader_H +#define PokemonAutomation_PokemonSV_ItemPrinterPrizeReader_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + class Logger; + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +class ItemPrinterPrizeReader{ + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + ItemPrinterPrizeReader(Language language); + + void make_overlays(VideoOverlaySet& items) const; + + std::array read_prizes( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen + ) const; + + std::array read_quantity( + Logger& logger, AsyncDispatcher& dispatcher, + const ImageViewRGB32& screen + ) const; + + int16_t read_number( + Logger& logger, + const ImageViewRGB32& screen, + const ImageFloatBox& box, + int8_t line_index = -1 + ) const; + + double average_sum_filtered(const ImageViewRGB32& screen, const ImageFloatBox& box) const; + +private: + Language m_language; + std::array m_boxes_normal; + std::array m_boxes_bonus; + std::array m_boxes_normal_quantity; + std::array m_boxes_bonus_quantity; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp index 3db683ede7..1c70f6ee22 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.cpp @@ -1,163 +1,163 @@ -/* Destination Marker Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_DestinationMarkerDetector.h" - -// #include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class DestinationMarkerMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DestinationMarkerMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/DestinationMarkerIcon-Template.png", Color(180,80,0), Color(255, 130, 50), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DestinationMarkerMatcher matcher; - return matcher; - } -}; - -class DestinationMarkerYellowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DestinationMarkerYellowMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/DestinationMarkerIcon-Yellow.png", Color(180,80,0), Color(255, 200, 50), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DestinationMarkerYellowMatcher matcher; - return matcher; - } -}; - - -DestinationMarkerDetector::~DestinationMarkerDetector() = default; - -DestinationMarkerDetector::DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow) - : m_color(color) - , m_box(box) - , m_check_yellow(check_yellow) -{} - -void DestinationMarkerDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool DestinationMarkerDetector::detect(const ImageViewRGB32& screen){ - std::vector hits = detect_all(screen); - if (!m_check_yellow){ - return !hits.empty(); - }else{ - std::vector hits_yellow = detect_all_yellow(screen); - return !hits.empty() || !hits_yellow.empty(); - } -} - -std::vector DestinationMarkerDetector::detect_all(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(180, 80, 0), combine_rgb(255, 130, 50)}, - - }; - - - const double rmsd_threshold = 65.0; // from my testing: RMSD is 15 at 1080p, 60 at 720p - const double min_object_size = 150.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - DestinationMarkerMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return true; - } - ); - - return found_locations; -} - - - -std::vector DestinationMarkerDetector::detect_all_yellow(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(180, 100, 0), combine_rgb(255, 190, 50)}, // to detect the marker within the minimap, when the radar beam is covering the marker - }; - - - const double rmsd_threshold = 60.0; // from my testing, RMSD ranges from 15-50, even at 720p - /* - - min object size restrictions also helps to filter out false positives - at pokemon centers - */ - const double min_object_size = 150.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - DestinationMarkerYellowMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return true; - } - ); - - return found_locations; -} - - - - - - -} -} -} +/* Destination Marker Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_DestinationMarkerDetector.h" + +// #include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class DestinationMarkerMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DestinationMarkerMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/DestinationMarkerIcon-Template.png", Color(180,80,0), Color(255, 130, 50), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DestinationMarkerMatcher matcher; + return matcher; + } +}; + +class DestinationMarkerYellowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DestinationMarkerYellowMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/DestinationMarkerIcon-Yellow.png", Color(180,80,0), Color(255, 200, 50), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DestinationMarkerYellowMatcher matcher; + return matcher; + } +}; + + +DestinationMarkerDetector::~DestinationMarkerDetector() = default; + +DestinationMarkerDetector::DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow) + : m_color(color) + , m_box(box) + , m_check_yellow(check_yellow) +{} + +void DestinationMarkerDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool DestinationMarkerDetector::detect(const ImageViewRGB32& screen){ + std::vector hits = detect_all(screen); + if (!m_check_yellow){ + return !hits.empty(); + }else{ + std::vector hits_yellow = detect_all_yellow(screen); + return !hits.empty() || !hits_yellow.empty(); + } +} + +std::vector DestinationMarkerDetector::detect_all(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(180, 80, 0), combine_rgb(255, 130, 50)}, + + }; + + + const double rmsd_threshold = 65.0; // from my testing: RMSD is 15 at 1080p, 60 at 720p + const double min_object_size = 150.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + DestinationMarkerMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return true; + } + ); + + return found_locations; +} + + + +std::vector DestinationMarkerDetector::detect_all_yellow(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(180, 100, 0), combine_rgb(255, 190, 50)}, // to detect the marker within the minimap, when the radar beam is covering the marker + }; + + + const double rmsd_threshold = 60.0; // from my testing, RMSD ranges from 15-50, even at 720p + /* + - min object size restrictions also helps to filter out false positives + at pokemon centers + */ + const double min_object_size = 150.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + DestinationMarkerYellowMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return true; + } + ); + + return found_locations; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h index 107cf3bc61..23c72f2ea0 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h @@ -1,65 +1,65 @@ -/* Destination Marker Detector - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_DestinationMarkerDetector_H -#define PokemonAutomation_PokemonSV_DestinationMarkerDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -class DestinationMarkerDetector : public StaticScreenDetector{ -public: - DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow); - virtual ~DestinationMarkerDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - - // for detecting the marker within the minimap - // ImageFloatBox for detecting within the minimap {0.815, 0.645, 0.180, 0.320}. needs to be slightly higher up than the minimap since the marker will stick up past the minimap - std::vector detect_all_yellow(const ImageViewRGB32& screen) const; - -protected: - Color m_color; - ImageFloatBox m_box; - bool m_check_yellow; -}; - - - -class DestinationMarkerWatcher : public DetectorToFinder{ - public: - DestinationMarkerWatcher( - Color color, - const ImageFloatBox& box, - bool check_yellow = false, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("DestinationMarkerWatcher", std::chrono::milliseconds(250), color, box, check_yellow) - {} -}; - - - - -} -} -} -#endif +/* Destination Marker Detector + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_DestinationMarkerDetector_H +#define PokemonAutomation_PokemonSV_DestinationMarkerDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +class DestinationMarkerDetector : public StaticScreenDetector{ +public: + DestinationMarkerDetector(Color color, const ImageFloatBox& box, bool check_yellow); + virtual ~DestinationMarkerDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + + // for detecting the marker within the minimap + // ImageFloatBox for detecting within the minimap {0.815, 0.645, 0.180, 0.320}. needs to be slightly higher up than the minimap since the marker will stick up past the minimap + std::vector detect_all_yellow(const ImageViewRGB32& screen) const; + +protected: + Color m_color; + ImageFloatBox m_box; + bool m_check_yellow; +}; + + + +class DestinationMarkerWatcher : public DetectorToFinder{ + public: + DestinationMarkerWatcher( + Color color, + const ImageFloatBox& box, + bool check_yellow = false, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("DestinationMarkerWatcher", std::chrono::milliseconds(250), color, box, check_yellow) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.cpp index e54dcbc86f..5d3e39d178 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.cpp @@ -1,144 +1,144 @@ -/* Fast Travel Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "PokemonSV_FastTravelDetector.h" - -// #include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -ImageFloatBox MINIMAP_AREA(0.815, 0.680, 0.180, 0.310); - - -class FastTravelMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - /* - - selects for the white, wing-shaped component of the fast travel icon - - Use Waterfilltemplate matcher to get your template so you get the correct area ratio - along with the blue background. You need the blue backgroun so you don't false positive - against the fly icon in Pokemon centers. - - */ - FastTravelMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/FastTravelIcon-Template.png", Color(200,200,200), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.4; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static FastTravelMatcher matcher; - return matcher; - } -}; - - -FastTravelDetector::~FastTravelDetector() = default; - -FastTravelDetector::FastTravelDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} - -void FastTravelDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool FastTravelDetector::detect(const ImageViewRGB32& screen){ - std::vector hits = detect_all(screen); - return !hits.empty(); -} - -std::vector FastTravelDetector::detect_all(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - {combine_rgb(180, 180, 180), combine_rgb(255, 255, 255)}, - - }; - - /* - - need to keep RMSD threshold below 100, - else will false positive the fly icon at pokemon centers - */ - const double rmsd_threshold = 80.0; - /* - - min object size restrictions also helps to filter out false positives - at pokemon centers - */ - const double min_object_size = 150.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - FastTravelMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return false; - } - ); - - return found_locations; -} - - - -FastTravelWatcher::~FastTravelWatcher() = default; - -FastTravelWatcher::FastTravelWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("FastTravelWatcher") - , m_overlay(overlay) - , m_detector(color, box) -{} - -void FastTravelWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool FastTravelWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - std::vector hits = m_detector.detect_all(screen); - - m_hits.reset(hits.size()); - for (const ImageFloatBox& hit : hits){ - m_hits.emplace_back(m_overlay, hit, COLOR_MAGENTA); - } - - return !hits.empty(); -} - - - - - - - - -} -} -} +/* Fast Travel Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "PokemonSV_FastTravelDetector.h" + +// #include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +ImageFloatBox MINIMAP_AREA(0.815, 0.680, 0.180, 0.310); + + +class FastTravelMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + /* + - selects for the white, wing-shaped component of the fast travel icon + - Use Waterfilltemplate matcher to get your template so you get the correct area ratio + along with the blue background. You need the blue backgroun so you don't false positive + against the fly icon in Pokemon centers. + + */ + FastTravelMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/FastTravelIcon-Template.png", Color(200,200,200), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.4; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static FastTravelMatcher matcher; + return matcher; + } +}; + + +FastTravelDetector::~FastTravelDetector() = default; + +FastTravelDetector::FastTravelDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} + +void FastTravelDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool FastTravelDetector::detect(const ImageViewRGB32& screen){ + std::vector hits = detect_all(screen); + return !hits.empty(); +} + +std::vector FastTravelDetector::detect_all(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + {combine_rgb(180, 180, 180), combine_rgb(255, 255, 255)}, + + }; + + /* + - need to keep RMSD threshold below 100, + else will false positive the fly icon at pokemon centers + */ + const double rmsd_threshold = 80.0; + /* + - min object size restrictions also helps to filter out false positives + at pokemon centers + */ + const double min_object_size = 150.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + FastTravelMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return false; + } + ); + + return found_locations; +} + + + +FastTravelWatcher::~FastTravelWatcher() = default; + +FastTravelWatcher::FastTravelWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("FastTravelWatcher") + , m_overlay(overlay) + , m_detector(color, box) +{} + +void FastTravelWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool FastTravelWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + std::vector hits = m_detector.detect_all(screen); + + m_hits.reset(hits.size()); + for (const ImageFloatBox& hit : hits){ + m_hits.emplace_back(m_overlay, hit, COLOR_MAGENTA); + } + + return !hits.empty(); +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h index 14a13d7edf..94c2936e77 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h @@ -1,74 +1,74 @@ -/* Fast Travel Detector - - Detects the Fast Travel symbol on the screen. - - Limitations: - - Does not work if obstructed by the radar beam (while outdoors), - or if obstructed by the radar dot - - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_FastTravelDetector_H -#define PokemonAutomation_PokemonSV_FastTravelDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -// The area on the screen with the minimap -extern ImageFloatBox MINIMAP_AREA; - -class FastTravelDetector : public StaticScreenDetector{ -public: - FastTravelDetector(Color color, const ImageFloatBox& box); - virtual ~FastTravelDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - -protected: - Color m_color; - ImageFloatBox m_box; -}; - - - -class FastTravelWatcher : public VisualInferenceCallback{ -public: - FastTravelWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box); - virtual ~FastTravelWatcher(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - -protected: - VideoOverlay& m_overlay; - FastTravelDetector m_detector; - FixedLimitVector m_hits; -}; - - - - -} -} -} -#endif +/* Fast Travel Detector + + Detects the Fast Travel symbol on the screen. + + Limitations: + - Does not work if obstructed by the radar beam (while outdoors), + or if obstructed by the radar dot + + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_FastTravelDetector_H +#define PokemonAutomation_PokemonSV_FastTravelDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +// The area on the screen with the minimap +extern ImageFloatBox MINIMAP_AREA; + +class FastTravelDetector : public StaticScreenDetector{ +public: + FastTravelDetector(Color color, const ImageFloatBox& box); + virtual ~FastTravelDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + +protected: + Color m_color; + ImageFloatBox m_box; +}; + + + +class FastTravelWatcher : public VisualInferenceCallback{ +public: + FastTravelWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box); + virtual ~FastTravelWatcher(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + +protected: + VideoOverlay& m_overlay; + FastTravelDetector m_detector; + FixedLimitVector m_hits; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.cpp index 423f4faafd..697bd38396 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.cpp @@ -1,154 +1,154 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_MapDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -namespace{ - -class MapOrangleFixedViewArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - MapOrangleFixedViewArrowMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/OrangleFixedView-Template.png", Color(50,50,0), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - } - - static const MapOrangleFixedViewArrowMatcher& instance(){ - static MapOrangleFixedViewArrowMatcher matcher; - return matcher; - } -}; - - -class MapOrangleRotatedViewArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - MapOrangleRotatedViewArrowMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/OrangleRotatedView-Template.png", Color(50,50,0), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - } - - static const MapOrangleRotatedViewArrowMatcher& instance(){ - static MapOrangleRotatedViewArrowMatcher matcher; - return matcher; - } -}; - - -} // end anonymous namespace - - -ImageFloatBox MAP_READABLE_AREA{0.197, 0.182, 0.678, 0.632}; - -MapFixedViewDetector::MapFixedViewDetector(Color color) - : m_color(color) - , m_arrow_box(0.165, 0.712, 0.014, 0.040) -{} -void MapFixedViewDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_arrow_box); -} -bool MapFixedViewDetector::detect(const ImageViewRGB32& frame){ - const std::vector> filters = { - {combine_rgb(100, 100, 0), combine_rgb(255, 255, 200)} - }; - - const double screen_rel_size = (frame.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 150.0); - - const bool detected = match_template_by_waterfill( - extract_box_reference(frame, m_arrow_box), - MapOrangleFixedViewArrowMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 120, - [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); - - return detected; -} - - -MapRotatedViewDetector::MapRotatedViewDetector(Color color) - : m_color(color) - , m_arrow_box(0.157, 0.720, 0.029, 0.039) -{} -void MapRotatedViewDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_arrow_box); -} -bool MapRotatedViewDetector::detect(const ImageViewRGB32& frame){ - const std::vector> filters = { - {combine_rgb(100, 100, 0), combine_rgb(255, 255, 200)} - }; - - const double screen_rel_size = (frame.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 450.0); - - const bool detected = match_template_by_waterfill( - extract_box_reference(frame, m_arrow_box), - MapOrangleRotatedViewArrowMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 120, - [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); - - return detected; -} - - -MapWatcher::MapWatcher(Color color) -: VisualInferenceCallback("MapWatcher") -, m_exit_watcher(COLOR_RED, WhiteButton::ButtonY, {0.800, 0.118, 0.030, 0.060}), m_fixed_view_watcher(color), m_rotated_view_watcher(color){} - -void MapWatcher::make_overlays(VideoOverlaySet& items) const{ - m_exit_watcher.make_overlays(items); - m_fixed_view_watcher.make_overlays(items); - m_rotated_view_watcher.make_overlays(items); -} - -bool MapWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const bool exit_found = m_exit_watcher.process_frame(frame, timestamp); - if (!exit_found){ - return false; - } - - const bool fixed_found = m_fixed_view_watcher.process_frame(frame, timestamp); - const bool rotated_found = m_rotated_view_watcher.process_frame(frame, timestamp); - - if (fixed_found && !rotated_found){ - m_in_fixed_view = true; - return true; - }else if (!fixed_found && rotated_found){ - m_in_fixed_view = false; - return true; - } - - return false; -} - - -} -} -} +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_MapDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +namespace{ + +class MapOrangleFixedViewArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + MapOrangleFixedViewArrowMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/OrangleFixedView-Template.png", Color(50,50,0), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + } + + static const MapOrangleFixedViewArrowMatcher& instance(){ + static MapOrangleFixedViewArrowMatcher matcher; + return matcher; + } +}; + + +class MapOrangleRotatedViewArrowMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + MapOrangleRotatedViewArrowMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/OrangleRotatedView-Template.png", Color(50,50,0), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + } + + static const MapOrangleRotatedViewArrowMatcher& instance(){ + static MapOrangleRotatedViewArrowMatcher matcher; + return matcher; + } +}; + + +} // end anonymous namespace + + +ImageFloatBox MAP_READABLE_AREA{0.197, 0.182, 0.678, 0.632}; + +MapFixedViewDetector::MapFixedViewDetector(Color color) + : m_color(color) + , m_arrow_box(0.165, 0.712, 0.014, 0.040) +{} +void MapFixedViewDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_arrow_box); +} +bool MapFixedViewDetector::detect(const ImageViewRGB32& frame){ + const std::vector> filters = { + {combine_rgb(100, 100, 0), combine_rgb(255, 255, 200)} + }; + + const double screen_rel_size = (frame.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 150.0); + + const bool detected = match_template_by_waterfill( + extract_box_reference(frame, m_arrow_box), + MapOrangleFixedViewArrowMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 120, + [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); + + return detected; +} + + +MapRotatedViewDetector::MapRotatedViewDetector(Color color) + : m_color(color) + , m_arrow_box(0.157, 0.720, 0.029, 0.039) +{} +void MapRotatedViewDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_arrow_box); +} +bool MapRotatedViewDetector::detect(const ImageViewRGB32& frame){ + const std::vector> filters = { + {combine_rgb(100, 100, 0), combine_rgb(255, 255, 200)} + }; + + const double screen_rel_size = (frame.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 450.0); + + const bool detected = match_template_by_waterfill( + extract_box_reference(frame, m_arrow_box), + MapOrangleRotatedViewArrowMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 120, + [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); + + return detected; +} + + +MapWatcher::MapWatcher(Color color) +: VisualInferenceCallback("MapWatcher") +, m_exit_watcher(COLOR_RED, WhiteButton::ButtonY, {0.800, 0.118, 0.030, 0.060}), m_fixed_view_watcher(color), m_rotated_view_watcher(color){} + +void MapWatcher::make_overlays(VideoOverlaySet& items) const{ + m_exit_watcher.make_overlays(items); + m_fixed_view_watcher.make_overlays(items); + m_rotated_view_watcher.make_overlays(items); +} + +bool MapWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const bool exit_found = m_exit_watcher.process_frame(frame, timestamp); + if (!exit_found){ + return false; + } + + const bool fixed_found = m_fixed_view_watcher.process_frame(frame, timestamp); + const bool rotated_found = m_rotated_view_watcher.process_frame(frame, timestamp); + + if (fixed_found && !rotated_found){ + m_in_fixed_view = true; + return true; + }else if (!fixed_found && rotated_found){ + m_in_fixed_view = false; + return true; + } + + return false; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.h index 20f60dc7d0..0b81b684ff 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapDetector.h @@ -1,90 +1,90 @@ -/* Map Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MapDetector_H -#define PokemonAutomation_PokemonSV_MapDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// The area on the screen that the program can clearly read map info, when the map is opened. -extern ImageFloatBox MAP_READABLE_AREA; - -// Detect the orange arrow pointing up on the lower left corner of the map, when the map is in the fixed view mode. -// This arrow is used to differentate the rotation view mode. -class MapFixedViewDetector : public StaticScreenDetector{ -public: - MapFixedViewDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_arrow_box; -}; -class MapFixedViewWatcher : public DetectorToFinder{ -public: - MapFixedViewWatcher(Color color = COLOR_RED) - : DetectorToFinder("MapFixedViewWatcher", std::chrono::milliseconds(1000), color) - {} -}; - - -// Detect the orange double-direction arrows pointing sideways on the lower left corner of the map, when the map is -// in the rotated view mode. -// This arrow is used to differentate the fixed view mode. -class MapRotatedViewDetector : public StaticScreenDetector{ -public: - MapRotatedViewDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_arrow_box; -}; -class MapRotatedViewWatcher : public DetectorToFinder{ -public: - MapRotatedViewWatcher(Color color = COLOR_RED) - : DetectorToFinder("MapRotatedViewWatcher", std::chrono::milliseconds(1000), color) - {} -}; - -// Detect whether map is opened and ready to be closed. -// Can also detect whether the map is in the fixed view or rotated view mode. -class MapWatcher : public VisualInferenceCallback{ -public: - MapWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - // Whether the map is in the fixed view instead of rotated view. - bool map_in_fixed_view() const { return m_in_fixed_view; } - -private: - WhiteButtonWatcher m_exit_watcher; - MapFixedViewWatcher m_fixed_view_watcher; - MapRotatedViewWatcher m_rotated_view_watcher; - - bool m_in_fixed_view = false; -}; - - -} -} -} -#endif +/* Map Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MapDetector_H +#define PokemonAutomation_PokemonSV_MapDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// The area on the screen that the program can clearly read map info, when the map is opened. +extern ImageFloatBox MAP_READABLE_AREA; + +// Detect the orange arrow pointing up on the lower left corner of the map, when the map is in the fixed view mode. +// This arrow is used to differentate the rotation view mode. +class MapFixedViewDetector : public StaticScreenDetector{ +public: + MapFixedViewDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_arrow_box; +}; +class MapFixedViewWatcher : public DetectorToFinder{ +public: + MapFixedViewWatcher(Color color = COLOR_RED) + : DetectorToFinder("MapFixedViewWatcher", std::chrono::milliseconds(1000), color) + {} +}; + + +// Detect the orange double-direction arrows pointing sideways on the lower left corner of the map, when the map is +// in the rotated view mode. +// This arrow is used to differentate the fixed view mode. +class MapRotatedViewDetector : public StaticScreenDetector{ +public: + MapRotatedViewDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_arrow_box; +}; +class MapRotatedViewWatcher : public DetectorToFinder{ +public: + MapRotatedViewWatcher(Color color = COLOR_RED) + : DetectorToFinder("MapRotatedViewWatcher", std::chrono::milliseconds(1000), color) + {} +}; + +// Detect whether map is opened and ready to be closed. +// Can also detect whether the map is in the fixed view or rotated view mode. +class MapWatcher : public VisualInferenceCallback{ +public: + MapWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + // Whether the map is in the fixed view instead of rotated view. + bool map_in_fixed_view() const { return m_in_fixed_view; } + +private: + WhiteButtonWatcher m_exit_watcher; + MapFixedViewWatcher m_fixed_view_watcher; + MapRotatedViewWatcher m_rotated_view_watcher; + + bool m_in_fixed_view = false; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.cpp index 69bce41d22..17ba8b3ae7 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.cpp @@ -1,109 +1,109 @@ -/* Map Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_MapMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -MapFlyMenuDetector::~MapFlyMenuDetector() = default; - -MapFlyMenuDetector::MapFlyMenuDetector(Color color) - : m_color(color) - , m_middle_box(0.523, 0.680, 0.080, 0.010) - , m_bottom_box(0.523, 0.744, 0.080, 0.020) -{} - -void MapFlyMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_middle_box); - items.add(m_color, m_bottom_box); -} - -bool MapFlyMenuDetector::detect(const ImageViewRGB32& screen){ - const ImageStats stats0 = image_stats(extract_box_reference(screen, m_middle_box)); - // The white menu background is actually a bit translucent. So we have to relax the `is_white()` condition. - const double min_rgb_sum = 500.0; - const double min_stddev_sum = 25.0; - if (!is_white(stats0, min_rgb_sum, min_stddev_sum)){ - return false; - } - const ImageStats stats1 = image_stats(extract_box_reference(screen, m_bottom_box)); - return is_white(stats1, min_rgb_sum, min_stddev_sum); -} - - -MapFlyMenuWatcher::~MapFlyMenuWatcher() = default; - -MapFlyMenuWatcher::MapFlyMenuWatcher(Color color) - : VisualInferenceCallback("MapFlyMenuWatcher") - , m_detector(color) -{} - -void MapFlyMenuWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool MapFlyMenuWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - return m_detector.detect(screen); -} - - -MapDestinationMenuDetector::MapDestinationMenuDetector(Color color) - : m_color(color) - , m_bottom_box(0.523, 0.670, 0.080, 0.020) - , m_fly_menu_box(0.523, 0.744, 0.080, 0.020) -{} - -void MapDestinationMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_box); - items.add(m_color, m_fly_menu_box); -} - -bool MapDestinationMenuDetector::detect(const ImageViewRGB32& screen){ - const ImageStats stats0 = image_stats(extract_box_reference(screen, m_bottom_box)); - // The white menu background is actually a bit translucent. So we have to relax the `is_white()` condition. - const double min_rgb_sum = 500.0; - const double min_stddev_sum = 25.0; - if (!is_white(stats0, min_rgb_sum, min_stddev_sum)){ - return false; - } - const ImageStats stats1 = image_stats(extract_box_reference(screen, m_fly_menu_box)); - return !is_white(stats1, min_rgb_sum, min_stddev_sum); -} - - -MapDestinationMenuWatcher::~MapDestinationMenuWatcher() = default; - -MapDestinationMenuWatcher::MapDestinationMenuWatcher(Color color) - : VisualInferenceCallback("MapDestinationMenuWatcher") - , m_detector(color) -{} - -void MapDestinationMenuWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool MapDestinationMenuWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - return m_detector.detect(screen); -} - - - - - - -} -} -} +/* Map Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_MapMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +MapFlyMenuDetector::~MapFlyMenuDetector() = default; + +MapFlyMenuDetector::MapFlyMenuDetector(Color color) + : m_color(color) + , m_middle_box(0.523, 0.680, 0.080, 0.010) + , m_bottom_box(0.523, 0.744, 0.080, 0.020) +{} + +void MapFlyMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_middle_box); + items.add(m_color, m_bottom_box); +} + +bool MapFlyMenuDetector::detect(const ImageViewRGB32& screen){ + const ImageStats stats0 = image_stats(extract_box_reference(screen, m_middle_box)); + // The white menu background is actually a bit translucent. So we have to relax the `is_white()` condition. + const double min_rgb_sum = 500.0; + const double min_stddev_sum = 25.0; + if (!is_white(stats0, min_rgb_sum, min_stddev_sum)){ + return false; + } + const ImageStats stats1 = image_stats(extract_box_reference(screen, m_bottom_box)); + return is_white(stats1, min_rgb_sum, min_stddev_sum); +} + + +MapFlyMenuWatcher::~MapFlyMenuWatcher() = default; + +MapFlyMenuWatcher::MapFlyMenuWatcher(Color color) + : VisualInferenceCallback("MapFlyMenuWatcher") + , m_detector(color) +{} + +void MapFlyMenuWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool MapFlyMenuWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + return m_detector.detect(screen); +} + + +MapDestinationMenuDetector::MapDestinationMenuDetector(Color color) + : m_color(color) + , m_bottom_box(0.523, 0.670, 0.080, 0.020) + , m_fly_menu_box(0.523, 0.744, 0.080, 0.020) +{} + +void MapDestinationMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_box); + items.add(m_color, m_fly_menu_box); +} + +bool MapDestinationMenuDetector::detect(const ImageViewRGB32& screen){ + const ImageStats stats0 = image_stats(extract_box_reference(screen, m_bottom_box)); + // The white menu background is actually a bit translucent. So we have to relax the `is_white()` condition. + const double min_rgb_sum = 500.0; + const double min_stddev_sum = 25.0; + if (!is_white(stats0, min_rgb_sum, min_stddev_sum)){ + return false; + } + const ImageStats stats1 = image_stats(extract_box_reference(screen, m_fly_menu_box)); + return !is_white(stats1, min_rgb_sum, min_stddev_sum); +} + + +MapDestinationMenuWatcher::~MapDestinationMenuWatcher() = default; + +MapDestinationMenuWatcher::MapDestinationMenuWatcher(Color color) + : VisualInferenceCallback("MapDestinationMenuWatcher") + , m_detector(color) +{} + +void MapDestinationMenuWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool MapDestinationMenuWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + return m_detector.detect(screen); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h index 8afc04462a..54407aa759 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h @@ -1,91 +1,91 @@ -/* Map Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MapMenuDetector_H -#define PokemonAutomation_PokemonSV_MapMenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Detect whether the "Fly here" menu is opened on map -// Note: it detects the white background of the menu. So if the underlying map is pure white, it will have false positives. -class MapFlyMenuDetector : public StaticScreenDetector{ -public: - MapFlyMenuDetector(Color color); - virtual ~MapFlyMenuDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -protected: - Color m_color; - ImageFloatBox m_middle_box, m_bottom_box; -}; - - -// Watch for the "Fly here" menu to open on map -class MapFlyMenuWatcher : public VisualInferenceCallback{ -public: - MapFlyMenuWatcher(Color color); - virtual ~MapFlyMenuWatcher(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -protected: - MapFlyMenuDetector m_detector; -}; - - -// Detect whether the "Set as destination" menu is opened on map. -// This menu has no "Fly here" menuitem. -// Note: it detects the white background of the menu. So if the underlying map is pure white, it will have false positives. -class MapDestinationMenuDetector : public StaticScreenDetector{ -public: - MapDestinationMenuDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -protected: - Color m_color; - ImageFloatBox m_bottom_box; - ImageFloatBox m_fly_menu_box; -}; - - -// Watch for the "Set as destination" menu to open on map. -// This menu has no "Fly here" menuitem. -class MapDestinationMenuWatcher : public VisualInferenceCallback{ -public: - ~MapDestinationMenuWatcher(); - MapDestinationMenuWatcher(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -protected: - MapDestinationMenuDetector m_detector; -}; - - -} -} -} -#endif +/* Map Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MapMenuDetector_H +#define PokemonAutomation_PokemonSV_MapMenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Detect whether the "Fly here" menu is opened on map +// Note: it detects the white background of the menu. So if the underlying map is pure white, it will have false positives. +class MapFlyMenuDetector : public StaticScreenDetector{ +public: + MapFlyMenuDetector(Color color); + virtual ~MapFlyMenuDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +protected: + Color m_color; + ImageFloatBox m_middle_box, m_bottom_box; +}; + + +// Watch for the "Fly here" menu to open on map +class MapFlyMenuWatcher : public VisualInferenceCallback{ +public: + MapFlyMenuWatcher(Color color); + virtual ~MapFlyMenuWatcher(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +protected: + MapFlyMenuDetector m_detector; +}; + + +// Detect whether the "Set as destination" menu is opened on map. +// This menu has no "Fly here" menuitem. +// Note: it detects the white background of the menu. So if the underlying map is pure white, it will have false positives. +class MapDestinationMenuDetector : public StaticScreenDetector{ +public: + MapDestinationMenuDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +protected: + Color m_color; + ImageFloatBox m_bottom_box; + ImageFloatBox m_fly_menu_box; +}; + + +// Watch for the "Set as destination" menu to open on map. +// This menu has no "Fly here" menuitem. +class MapDestinationMenuWatcher : public VisualInferenceCallback{ +public: + ~MapDestinationMenuWatcher(); + MapDestinationMenuWatcher(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +protected: + MapDestinationMenuDetector m_detector; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.cpp index b83300695c..f0f0ebc8f1 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.cpp @@ -1,120 +1,120 @@ -/* Map PokeCenter Icon Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_MapPokeCenterIconDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class MapPokeCenterIconMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - MapPokeCenterIconMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/PokeCenterIcon-Template.png", Color(150,0,0), Color(255, 100, 100), 50 - ){ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.6; - m_area_ratio_upper = 1.2; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static MapPokeCenterIconMatcher matcher; - return matcher; - } -}; - - - -MapPokeCenterIconDetector::MapPokeCenterIconDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} - -void MapPokeCenterIconDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool MapPokeCenterIconDetector::detect(const ImageViewRGB32& screen){ - std::vector hits = detect_all(screen); - return !hits.empty(); -} - -std::vector MapPokeCenterIconDetector::detect_all(const ImageViewRGB32& screen) const{ - const std::vector> filters = { - // {combine_rgb(150, 0, 0), combine_rgb(255, 120, 120)}, - {combine_rgb(100, 0, 0), combine_rgb(255, 100, 100)} - }; - - const double min_object_size = 350.0; - const double rmsd_threshold = 100.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::vector found_locations; - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); - match_template_by_waterfill( - extract_box_reference(screen, m_box), - MapPokeCenterIconMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); - return false; - } - ); - - return found_locations; -} - - - -MapPokeCenterIconWatcher::~MapPokeCenterIconWatcher() = default; - -MapPokeCenterIconWatcher::MapPokeCenterIconWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("MapPokeCenterIconWatcher") - , m_overlay(overlay) - , m_detector(color, box) -{} - -void MapPokeCenterIconWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool MapPokeCenterIconWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - m_hits = m_detector.detect_all(screen); - - m_hit_boxes.reset(m_hits.size()); - for (const ImageFloatBox& hit : m_hits){ - m_hit_boxes.emplace_back(m_overlay, hit, COLOR_MAGENTA); - } - return !m_hits.empty(); -} - - - - - -} -} -} +/* Map PokeCenter Icon Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_MapPokeCenterIconDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class MapPokeCenterIconMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + MapPokeCenterIconMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/PokeCenterIcon-Template.png", Color(150,0,0), Color(255, 100, 100), 50 + ){ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.6; + m_area_ratio_upper = 1.2; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static MapPokeCenterIconMatcher matcher; + return matcher; + } +}; + + + +MapPokeCenterIconDetector::MapPokeCenterIconDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} + +void MapPokeCenterIconDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool MapPokeCenterIconDetector::detect(const ImageViewRGB32& screen){ + std::vector hits = detect_all(screen); + return !hits.empty(); +} + +std::vector MapPokeCenterIconDetector::detect_all(const ImageViewRGB32& screen) const{ + const std::vector> filters = { + // {combine_rgb(150, 0, 0), combine_rgb(255, 120, 120)}, + {combine_rgb(100, 0, 0), combine_rgb(255, 100, 100)} + }; + + const double min_object_size = 350.0; + const double rmsd_threshold = 100.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::vector found_locations; + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_box); + match_template_by_waterfill( + extract_box_reference(screen, m_box), + MapPokeCenterIconMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + found_locations.emplace_back(pixelbox_to_floatbox(screen.width(), screen.height(), found_box)); + return false; + } + ); + + return found_locations; +} + + + +MapPokeCenterIconWatcher::~MapPokeCenterIconWatcher() = default; + +MapPokeCenterIconWatcher::MapPokeCenterIconWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("MapPokeCenterIconWatcher") + , m_overlay(overlay) + , m_detector(color, box) +{} + +void MapPokeCenterIconWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool MapPokeCenterIconWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + m_hits = m_detector.detect_all(screen); + + m_hit_boxes.reset(m_hits.size()); + for (const ImageFloatBox& hit : m_hits){ + m_hit_boxes.emplace_back(m_overlay, hit, COLOR_MAGENTA); + } + return !m_hits.empty(); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h index 3cf0a17f90..6ce0693139 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h @@ -1,68 +1,68 @@ -/* Map PokeCenter Icon Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MapPokeCenterIconDetector_H -#define PokemonAutomation_PokemonSV_MapPokeCenterIconDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect one or more pokecenter icons on map -class MapPokeCenterIconDetector : public StaticScreenDetector{ -public: - MapPokeCenterIconDetector(Color color, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - -protected: - Color m_color; - ImageFloatBox m_box; -}; - - -// Watch for at least one pokecenter icon appearing on map -class MapPokeCenterIconWatcher : public VisualInferenceCallback{ -public: - ~MapPokeCenterIconWatcher(); - MapPokeCenterIconWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - const std::vector& found_locations() const { return m_hits; } - - -protected: - VideoOverlay& m_overlay; - MapPokeCenterIconDetector m_detector; - std::vector m_hits; - FixedLimitVector m_hit_boxes; - -}; - - - - -} -} -} -#endif +/* Map PokeCenter Icon Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MapPokeCenterIconDetector_H +#define PokemonAutomation_PokemonSV_MapPokeCenterIconDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect one or more pokecenter icons on map +class MapPokeCenterIconDetector : public StaticScreenDetector{ +public: + MapPokeCenterIconDetector(Color color, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + +protected: + Color m_color; + ImageFloatBox m_box; +}; + + +// Watch for at least one pokecenter icon appearing on map +class MapPokeCenterIconWatcher : public VisualInferenceCallback{ +public: + ~MapPokeCenterIconWatcher(); + MapPokeCenterIconWatcher(Color color, VideoOverlay& overlay, const ImageFloatBox& box); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + const std::vector& found_locations() const { return m_hits; } + + +protected: + VideoOverlay& m_overlay; + MapPokeCenterIconDetector m_detector; + std::vector m_hits; + FixedLimitVector m_hit_boxes; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.cpp index 36630adc50..5de76eea7e 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.cpp @@ -1,198 +1,198 @@ -/* Area Zero Sky Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "CommonTools/Async/InferenceSession.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_AreaZeroSkyDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -bool AreaZeroSkyDetector::detect(Kernels::Waterfill::WaterfillObject& object, const ImageViewRGB32& screen) const{ - using namespace Kernels::Waterfill; - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(screen, 0xffc0c0c0, 0xffffffff); - - size_t min_width = screen.width() / 4; - size_t min_height = screen.height() / 4; - - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(10000); - while (iter->find_next(object, false)){ -// if (object.min_y != 0){ -// continue; -// } - if (object.width() < min_width || object.height() < min_height){ - continue; - } - return true; - } - return false; -} -bool AreaZeroSkyDetector::detect(const ImageViewRGB32& screen){ - using namespace Kernels::Waterfill; - - WaterfillObject object; - return detect(object, screen); -} - - - - -AreaZeroSkyTracker::AreaZeroSkyTracker(VideoOverlay& overlay) - : VisualInferenceCallback("AreaZeroSkyTracker") - , m_overlay(overlay) -{} - -bool AreaZeroSkyTracker::sky_location(double& x, double& y) const{ - ReadSpinLock lg(m_lock); - if (!m_box){ - return false; - } - x = m_center_x; - y = m_center_y; - return true; -} - -void AreaZeroSkyTracker::make_overlays(VideoOverlaySet& items) const{} -bool AreaZeroSkyTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - using namespace Kernels::Waterfill; - - WaterfillObject object; - bool detected = this->detect(object, frame); - WriteSpinLock lg(m_lock); - if (detected){ - m_box.reset(new OverlayBoxScope( - m_overlay, - COLOR_GREEN, - translate_to_parent(frame, {0, 0, 1, 1}, object), - "Area Zero Sky" - )); - m_center_x = object.center_of_gravity_x() / frame.width(); - m_center_y = object.center_of_gravity_y() / frame.height(); - }else{ - m_box.reset(); - } - return false; -} - - - - - -enum class OverworldState{ - None, - FindingSky, - TurningLeft, - TurningRight, -}; -void find_and_center_on_sky( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -){ - context.wait_for_all_requests(); - stream.log("Looking for the sky..."); - - AreaZeroSkyTracker sky_tracker(stream.overlay()); - InferenceSession inference_session( - context, stream, - {sky_tracker} - ); - - AsyncCommandSession session( - context, stream.logger(), - env.realtime_dispatcher(), - context.controller() - ); - OverworldState state = OverworldState::None; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(1)){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Failed to find the sky after 1 minute. (state = " + std::to_string((int)state) + ")", - stream - ); - } - - context.wait_for(std::chrono::milliseconds(200)); - - if (!session.command_is_running()){ - state = OverworldState::None; - } - - double sky_x, sky_y; - bool sky = sky_tracker.sky_location(sky_x, sky_y); - - if (!sky){ - if (state != OverworldState::FindingSky){ - stream.log("Sky not detected. Attempting to find the sky...", COLOR_ORANGE); - session.dispatch([](ProControllerContext& context){ - pbf_move_right_joystick(context, 128, 0, 250, 0); - pbf_move_right_joystick(context, 0, 0, 10 * TICKS_PER_SECOND, 0); - }); - state = OverworldState::FindingSky; - } - continue; - } - -// cout << sky_x << " - " << sky_y << endl; - - if (sky_x < 0.45){ - if (state != OverworldState::TurningLeft){ - stream.log("Centering the sky... Moving left."); - uint8_t magnitude = (uint8_t)((0.5 - sky_x) * 96 + 31); - uint16_t duration = (uint16_t)((0.5 - sky_x) * 125 + 20); - session.dispatch([=](ProControllerContext& context){ - pbf_move_right_joystick(context, 128 - magnitude, 128, duration, 0); - }); - state = OverworldState::TurningLeft; - } - continue; - } - if (sky_x > 0.55){ - if (state != OverworldState::TurningRight){ - stream.log("Centering the sky... Moving Right."); - uint8_t magnitude = (uint8_t)((sky_x - 0.5) * 96 + 31); - uint16_t duration = (uint16_t)((sky_x - 0.5) * 125 + 20); - session.dispatch([=](ProControllerContext& context){ - pbf_move_right_joystick(context, 128 + magnitude, 128, duration, 0); - }); - state = OverworldState::TurningRight; - } - continue; - } - - stream.log("Found the sky!", COLOR_ORANGE); - break; - } - - session.stop_session_and_rethrow(); -} - - - - - - - - - - - - - -} -} -} +/* Area Zero Sky Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "CommonTools/Async/InferenceSession.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_AreaZeroSkyDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +bool AreaZeroSkyDetector::detect(Kernels::Waterfill::WaterfillObject& object, const ImageViewRGB32& screen) const{ + using namespace Kernels::Waterfill; + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(screen, 0xffc0c0c0, 0xffffffff); + + size_t min_width = screen.width() / 4; + size_t min_height = screen.height() / 4; + + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(10000); + while (iter->find_next(object, false)){ +// if (object.min_y != 0){ +// continue; +// } + if (object.width() < min_width || object.height() < min_height){ + continue; + } + return true; + } + return false; +} +bool AreaZeroSkyDetector::detect(const ImageViewRGB32& screen){ + using namespace Kernels::Waterfill; + + WaterfillObject object; + return detect(object, screen); +} + + + + +AreaZeroSkyTracker::AreaZeroSkyTracker(VideoOverlay& overlay) + : VisualInferenceCallback("AreaZeroSkyTracker") + , m_overlay(overlay) +{} + +bool AreaZeroSkyTracker::sky_location(double& x, double& y) const{ + ReadSpinLock lg(m_lock); + if (!m_box){ + return false; + } + x = m_center_x; + y = m_center_y; + return true; +} + +void AreaZeroSkyTracker::make_overlays(VideoOverlaySet& items) const{} +bool AreaZeroSkyTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + using namespace Kernels::Waterfill; + + WaterfillObject object; + bool detected = this->detect(object, frame); + WriteSpinLock lg(m_lock); + if (detected){ + m_box.reset(new OverlayBoxScope( + m_overlay, + COLOR_GREEN, + translate_to_parent(frame, {0, 0, 1, 1}, object), + "Area Zero Sky" + )); + m_center_x = object.center_of_gravity_x() / frame.width(); + m_center_y = object.center_of_gravity_y() / frame.height(); + }else{ + m_box.reset(); + } + return false; +} + + + + + +enum class OverworldState{ + None, + FindingSky, + TurningLeft, + TurningRight, +}; +void find_and_center_on_sky( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +){ + context.wait_for_all_requests(); + stream.log("Looking for the sky..."); + + AreaZeroSkyTracker sky_tracker(stream.overlay()); + InferenceSession inference_session( + context, stream, + {sky_tracker} + ); + + AsyncCommandSession session( + context, stream.logger(), + env.realtime_dispatcher(), + context.controller() + ); + OverworldState state = OverworldState::None; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(1)){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Failed to find the sky after 1 minute. (state = " + std::to_string((int)state) + ")", + stream + ); + } + + context.wait_for(std::chrono::milliseconds(200)); + + if (!session.command_is_running()){ + state = OverworldState::None; + } + + double sky_x, sky_y; + bool sky = sky_tracker.sky_location(sky_x, sky_y); + + if (!sky){ + if (state != OverworldState::FindingSky){ + stream.log("Sky not detected. Attempting to find the sky...", COLOR_ORANGE); + session.dispatch([](ProControllerContext& context){ + pbf_move_right_joystick(context, 128, 0, 250, 0); + pbf_move_right_joystick(context, 0, 0, 10 * TICKS_PER_SECOND, 0); + }); + state = OverworldState::FindingSky; + } + continue; + } + +// cout << sky_x << " - " << sky_y << endl; + + if (sky_x < 0.45){ + if (state != OverworldState::TurningLeft){ + stream.log("Centering the sky... Moving left."); + uint8_t magnitude = (uint8_t)((0.5 - sky_x) * 96 + 31); + uint16_t duration = (uint16_t)((0.5 - sky_x) * 125 + 20); + session.dispatch([=](ProControllerContext& context){ + pbf_move_right_joystick(context, 128 - magnitude, 128, duration, 0); + }); + state = OverworldState::TurningLeft; + } + continue; + } + if (sky_x > 0.55){ + if (state != OverworldState::TurningRight){ + stream.log("Centering the sky... Moving Right."); + uint8_t magnitude = (uint8_t)((sky_x - 0.5) * 96 + 31); + uint16_t duration = (uint16_t)((sky_x - 0.5) * 125 + 20); + session.dispatch([=](ProControllerContext& context){ + pbf_move_right_joystick(context, 128 + magnitude, 128, duration, 0); + }); + state = OverworldState::TurningRight; + } + continue; + } + + stream.log("Found the sky!", COLOR_ORANGE); + break; + } + + session.stop_session_and_rethrow(); +} + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h index edb7c0f5c9..2648003818 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h @@ -1,65 +1,65 @@ -/* Area Zero Sky Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AreaZeroSkyDetector_H -#define PokemonAutomation_PokemonSV_AreaZeroSkyDetector_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - class WaterfillObject; -} -} -class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AreaZeroSkyDetector : public StaticScreenDetector{ -public: - virtual void make_overlays(VideoOverlaySet& items) const override{} - virtual bool detect(const ImageViewRGB32& screen) override; - - bool detect(Kernels::Waterfill::WaterfillObject& object, const ImageViewRGB32& screen) const; -}; - - -class AreaZeroSkyTracker : public AreaZeroSkyDetector, public VisualInferenceCallback{ -public: - AreaZeroSkyTracker(VideoOverlay& overlay); - - bool sky_location(double& x, double& y) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - VideoOverlay& m_overlay; - mutable SpinLock m_lock; - double m_center_x; - double m_center_y; - std::unique_ptr m_box; -}; - - -void find_and_center_on_sky( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context -); - - - -} -} -} -#endif +/* Area Zero Sky Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AreaZeroSkyDetector_H +#define PokemonAutomation_PokemonSV_AreaZeroSkyDetector_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + class WaterfillObject; +} +} +class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AreaZeroSkyDetector : public StaticScreenDetector{ +public: + virtual void make_overlays(VideoOverlaySet& items) const override{} + virtual bool detect(const ImageViewRGB32& screen) override; + + bool detect(Kernels::Waterfill::WaterfillObject& object, const ImageViewRGB32& screen) const; +}; + + +class AreaZeroSkyTracker : public AreaZeroSkyDetector, public VisualInferenceCallback{ +public: + AreaZeroSkyTracker(VideoOverlay& overlay); + + bool sky_location(double& x, double& y) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + VideoOverlay& m_overlay; + mutable SpinLock m_lock; + double m_center_x; + double m_center_y; + std::unique_ptr m_box; +}; + + +void find_and_center_on_sky( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp index d2f56f3dec..4d2afcf0b9 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.cpp @@ -1,242 +1,242 @@ -/* Direction Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class DirectionMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - - DirectionMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Map/DirectionIcon-Template.png", Color(0, 100, 30), Color(50, 230, 85), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static DirectionMatcher matcher; - return matcher; - } -}; - - -DirectionDetector::~DirectionDetector() = default; - -DirectionDetector::DirectionDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_minimap_box(box) -{} - - -bool DirectionDetector::detect_north(Logger& logger, const ImageViewRGB32& screen) const{ - std::pair north_location = locate_north(logger, screen); - - return !(north_location.first == 0 && north_location.second == 0); -} - - -std::pair DirectionDetector::locate_north(Logger& logger, const ImageViewRGB32& screen) const{ - assert_16_9_720p_min(logger, screen); - - const std::vector> filters = { - {combine_rgb(0, 100, 0), combine_rgb(50, 230, 80)}, - - }; - - const double min_object_size = 50.0; - const double rmsd_threshold = 60.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::pair north_location(0, 0); - OverworldDetector detector; - std::pair zero_coord = detector.locate_ball(screen, true); // 0.9061, 0.8328 - if (zero_coord.first > 0.91 || zero_coord.first < 0.90 || - zero_coord.second > 0.84 || zero_coord.second < 0.82) - { - logger.log("Unable to locate the overworld radar ball, falling back on hard coded location.", COLOR_ORANGE); - zero_coord.first = 0.9061; - zero_coord.second = 0.8328; - // throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unable to locate the overworld radar ball."); - } - - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_minimap_box); - match_template_by_waterfill( - extract_box_reference(screen, m_minimap_box), - DirectionMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - - // relative coord wrt upper left corner - double x1 = (object.center_of_gravity_x() + pixel_search_area.min_x) / (double)screen.width(); - double y1 = (object.center_of_gravity_y() + pixel_search_area.min_y) / (double)screen.height(); - // relative coord wrt minimap radar - double x2 = x1 - zero_coord.first; - double y2 = zero_coord.second - y1; // subtract y from zero_coord since I want north to be positive - // absolute coord wrt minimap radar, scaled to screen size - double x3 = x2 * (double)screen.width() / screen_rel_size; - double y3 = y2 * (double)screen.height() / screen_rel_size; - - double hypotenuse = std::hypot(x3, y3); - // std::cout << "hypotenuse: " << std::to_string(hypotenuse) << std::endl; - if (hypotenuse < 135 || hypotenuse > 155){ - return false; - } - north_location = std::make_pair(x3, y3); - return true; - } - ); - - // std::cout << "north location: " << std::to_string(north_location.first) << ", " << std::to_string(north_location.second) << std::endl; - - return north_location; -} - - -double DirectionDetector::get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const{ - std::pair north_location = locate_north(stream.logger(), screen); - if (north_location.first == 0 && north_location.second == 0){ // unable to locate north - return -1; - } - double direction = std::atan2(north_location.first, north_location.second); // swap x and y to use north-clockwise convention - // std::cout << std::to_string(direction) << std::endl; - direction = (direction < 0) ? (direction + 2 * PI) : direction; // change (-pi, pi] to [0, 2pi) - // std::cout << "current_direction: " << std::to_string(direction) << std::endl; - return direction; -} - -// return true if the given direction is pointing north -bool is_pointing_north(double direction){ - return (direction < 0.1 && direction >= 0.0) || (direction <= 2 * PI && direction > 2 * PI - 0.1); -} - -// return true if current_direction is pointing north -// if the above applies, the minimap might be locked. but we will need is_minimap_definitely_locked() to confirm. -bool DirectionDetector::is_minimap_possibly_locked(double current_direction) const{ - return is_pointing_north(current_direction); -} - -// - push the joystick to change its position. if still pointing North, then we know it's locked. -bool DirectionDetector::is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const { - bool pointing_north = is_pointing_north(current_direction); - if (!pointing_north){ - return false; - } - pbf_move_right_joystick(context, 0, 128, 100, 20); - context.wait_for_all_requests(); - double new_direction = get_current_direction(stream, stream.video().snapshot()); - - return is_pointing_north(new_direction); -} - -void DirectionDetector::change_direction( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction -) const{ - size_t i = 0; - size_t MAX_ATTEMPTS = 20; - bool is_minimap_definitely_unlocked = false; - uint8_t scale_factor = 80; - double push_magnitude_scale_factor = 1; - while (i < MAX_ATTEMPTS){ // 10 attempts to move the direction to the target - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - double current = get_current_direction(stream, screen); - if (current < 0){ - stream.log("Unable to detect current direction."); - return; - } - double target = std::fmod(direction, (2 * PI)); - - // try to find the shortest path around the circle - double diff = target - current; - if(diff > PI) { - diff -= (2 * PI); - } - if(diff <= -PI) { - diff += (2 * PI); - } - double abs_diff = std::abs(diff); - stream.log("current direction: " + std::to_string(current)); - stream.log("target: " + std::to_string(target) + ", diff: " + std::to_string(diff)); - - if (!is_minimap_definitely_unlocked && is_minimap_possibly_locked(current)){ - stream.log("Minimap may be locked. Check if definitely locked."); - if (is_minimap_definitely_locked(stream, context, current)){ - stream.log("Minimap locked. Try to unlock the minimap. Then try again."); - open_map_from_overworld(info, stream, context); - pbf_press_button(context, BUTTON_RCLICK, 20, 20); - pbf_press_button(context, BUTTON_RCLICK, 20, 20); - pbf_press_button(context, BUTTON_B, 20, 100); - press_Bs_to_back_to_overworld(info, stream, context, 7); - }else{ - stream.log("Minimap not locked. Try again"); - } - - is_minimap_definitely_unlocked = true; - i = 0; // even if not locked, we reset the attempt counter since the first attempt is most impactful in terms of cursor movement - continue; - } - is_minimap_definitely_unlocked = true; - - if (abs_diff < 0.0105){ - // return when we're close enough to the target - return; - } - - - if (scale_factor > 40 && abs_diff < 0.05){ - scale_factor = 40; - } - - if (abs_diff < 0.05){ - push_magnitude_scale_factor = 0.5; - } - - uint16_t push_duration = std::max(uint16_t(std::abs(diff * scale_factor)), uint16_t(8)); - int16_t push_direction = (diff > 0) ? -1 : 1; - double push_magnitude = std::max(double((128 * push_magnitude_scale_factor) / (i + 1)), double(15)); // push less with each iteration/attempt - uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); - stream.log("push magnitude: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); - pbf_move_right_joystick(context, push_x, 128, push_duration, 100); - i++; - } - -} - - - - -} -} -} +/* Direction Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class DirectionMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + + DirectionMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Map/DirectionIcon-Template.png", Color(0, 100, 30), Color(50, 230, 85), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static DirectionMatcher matcher; + return matcher; + } +}; + + +DirectionDetector::~DirectionDetector() = default; + +DirectionDetector::DirectionDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_minimap_box(box) +{} + + +bool DirectionDetector::detect_north(Logger& logger, const ImageViewRGB32& screen) const{ + std::pair north_location = locate_north(logger, screen); + + return !(north_location.first == 0 && north_location.second == 0); +} + + +std::pair DirectionDetector::locate_north(Logger& logger, const ImageViewRGB32& screen) const{ + assert_16_9_720p_min(logger, screen); + + const std::vector> filters = { + {combine_rgb(0, 100, 0), combine_rgb(50, 230, 80)}, + + }; + + const double min_object_size = 50.0; + const double rmsd_threshold = 60.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::pair north_location(0, 0); + OverworldDetector detector; + std::pair zero_coord = detector.locate_ball(screen, true); // 0.9061, 0.8328 + if (zero_coord.first > 0.91 || zero_coord.first < 0.90 || + zero_coord.second > 0.84 || zero_coord.second < 0.82) + { + logger.log("Unable to locate the overworld radar ball, falling back on hard coded location.", COLOR_ORANGE); + zero_coord.first = 0.9061; + zero_coord.second = 0.8328; + // throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unable to locate the overworld radar ball."); + } + + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), m_minimap_box); + match_template_by_waterfill( + extract_box_reference(screen, m_minimap_box), + DirectionMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + + // relative coord wrt upper left corner + double x1 = (object.center_of_gravity_x() + pixel_search_area.min_x) / (double)screen.width(); + double y1 = (object.center_of_gravity_y() + pixel_search_area.min_y) / (double)screen.height(); + // relative coord wrt minimap radar + double x2 = x1 - zero_coord.first; + double y2 = zero_coord.second - y1; // subtract y from zero_coord since I want north to be positive + // absolute coord wrt minimap radar, scaled to screen size + double x3 = x2 * (double)screen.width() / screen_rel_size; + double y3 = y2 * (double)screen.height() / screen_rel_size; + + double hypotenuse = std::hypot(x3, y3); + // std::cout << "hypotenuse: " << std::to_string(hypotenuse) << std::endl; + if (hypotenuse < 135 || hypotenuse > 155){ + return false; + } + north_location = std::make_pair(x3, y3); + return true; + } + ); + + // std::cout << "north location: " << std::to_string(north_location.first) << ", " << std::to_string(north_location.second) << std::endl; + + return north_location; +} + + +double DirectionDetector::get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const{ + std::pair north_location = locate_north(stream.logger(), screen); + if (north_location.first == 0 && north_location.second == 0){ // unable to locate north + return -1; + } + double direction = std::atan2(north_location.first, north_location.second); // swap x and y to use north-clockwise convention + // std::cout << std::to_string(direction) << std::endl; + direction = (direction < 0) ? (direction + 2 * PI) : direction; // change (-pi, pi] to [0, 2pi) + // std::cout << "current_direction: " << std::to_string(direction) << std::endl; + return direction; +} + +// return true if the given direction is pointing north +bool is_pointing_north(double direction){ + return (direction < 0.1 && direction >= 0.0) || (direction <= 2 * PI && direction > 2 * PI - 0.1); +} + +// return true if current_direction is pointing north +// if the above applies, the minimap might be locked. but we will need is_minimap_definitely_locked() to confirm. +bool DirectionDetector::is_minimap_possibly_locked(double current_direction) const{ + return is_pointing_north(current_direction); +} + +// - push the joystick to change its position. if still pointing North, then we know it's locked. +bool DirectionDetector::is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const { + bool pointing_north = is_pointing_north(current_direction); + if (!pointing_north){ + return false; + } + pbf_move_right_joystick(context, 0, 128, 100, 20); + context.wait_for_all_requests(); + double new_direction = get_current_direction(stream, stream.video().snapshot()); + + return is_pointing_north(new_direction); +} + +void DirectionDetector::change_direction( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction +) const{ + size_t i = 0; + size_t MAX_ATTEMPTS = 20; + bool is_minimap_definitely_unlocked = false; + uint8_t scale_factor = 80; + double push_magnitude_scale_factor = 1; + while (i < MAX_ATTEMPTS){ // 10 attempts to move the direction to the target + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + double current = get_current_direction(stream, screen); + if (current < 0){ + stream.log("Unable to detect current direction."); + return; + } + double target = std::fmod(direction, (2 * PI)); + + // try to find the shortest path around the circle + double diff = target - current; + if(diff > PI) { + diff -= (2 * PI); + } + if(diff <= -PI) { + diff += (2 * PI); + } + double abs_diff = std::abs(diff); + stream.log("current direction: " + std::to_string(current)); + stream.log("target: " + std::to_string(target) + ", diff: " + std::to_string(diff)); + + if (!is_minimap_definitely_unlocked && is_minimap_possibly_locked(current)){ + stream.log("Minimap may be locked. Check if definitely locked."); + if (is_minimap_definitely_locked(stream, context, current)){ + stream.log("Minimap locked. Try to unlock the minimap. Then try again."); + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_RCLICK, 20, 20); + pbf_press_button(context, BUTTON_RCLICK, 20, 20); + pbf_press_button(context, BUTTON_B, 20, 100); + press_Bs_to_back_to_overworld(info, stream, context, 7); + }else{ + stream.log("Minimap not locked. Try again"); + } + + is_minimap_definitely_unlocked = true; + i = 0; // even if not locked, we reset the attempt counter since the first attempt is most impactful in terms of cursor movement + continue; + } + is_minimap_definitely_unlocked = true; + + if (abs_diff < 0.0105){ + // return when we're close enough to the target + return; + } + + + if (scale_factor > 40 && abs_diff < 0.05){ + scale_factor = 40; + } + + if (abs_diff < 0.05){ + push_magnitude_scale_factor = 0.5; + } + + uint16_t push_duration = std::max(uint16_t(std::abs(diff * scale_factor)), uint16_t(8)); + int16_t push_direction = (diff > 0) ? -1 : 1; + double push_magnitude = std::max(double((128 * push_magnitude_scale_factor) / (i + 1)), double(15)); // push less with each iteration/attempt + uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); + stream.log("push magnitude: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); + pbf_move_right_joystick(context, push_x, 128, push_duration, 100); + i++; + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h index fbfe505e27..8c459de238 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h @@ -1,68 +1,68 @@ -/* Direction Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_DirectionDetector_H -#define PokemonAutomation_PokemonSV_DirectionDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -static constexpr double PI = 3.14159265358979323846; - -class DirectionDetector { -public: - DirectionDetector(Color color = COLOR_RED, const ImageFloatBox& box = ImageFloatBox(0.815, 0.680, 0.180, 0.310)); - virtual ~DirectionDetector(); - - bool detect_north(Logger& logger, const ImageViewRGB32& screen) const; - - // return the coordinates of the N symbol, where the coordinates are measured in absolute pixels (scaled to 1080/height) - // with respect to the radar ball - // return 0,0 if unable to locate the N symbol - std::pair locate_north(Logger& logger, const ImageViewRGB32& screen) const; - - // return the direction of the N symbol, in radians, using North-clockwise convention. [0, 2pi) - // return -1 if unable to locate the N symbol - double get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const; - - bool is_minimap_possibly_locked(double current_direction) const; - - bool is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const; - - // given direction in radians (North-clockwise), rotate the camera so N is pointing in the desired direction. - // mini-map must be unlocked. - void change_direction( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction - ) const; - -protected: - Color m_color; - ImageFloatBox m_minimap_box; -}; - - - -} -} -} -#endif +/* Direction Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_DirectionDetector_H +#define PokemonAutomation_PokemonSV_DirectionDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +static constexpr double PI = 3.14159265358979323846; + +class DirectionDetector { +public: + DirectionDetector(Color color = COLOR_RED, const ImageFloatBox& box = ImageFloatBox(0.815, 0.680, 0.180, 0.310)); + virtual ~DirectionDetector(); + + bool detect_north(Logger& logger, const ImageViewRGB32& screen) const; + + // return the coordinates of the N symbol, where the coordinates are measured in absolute pixels (scaled to 1080/height) + // with respect to the radar ball + // return 0,0 if unable to locate the N symbol + std::pair locate_north(Logger& logger, const ImageViewRGB32& screen) const; + + // return the direction of the N symbol, in radians, using North-clockwise convention. [0, 2pi) + // return -1 if unable to locate the N symbol + double get_current_direction(VideoStream& stream, const ImageViewRGB32& screen) const; + + bool is_minimap_possibly_locked(double current_direction) const; + + bool is_minimap_definitely_locked(VideoStream& stream, ProControllerContext& context, double current_direction) const; + + // given direction in radians (North-clockwise), rotate the camera so N is pointing in the desired direction. + // mini-map must be unlocked. + void change_direction( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction + ) const; + +protected: + Color m_color; + ImageFloatBox m_minimap_box; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp index 30a07bd1c3..97331a1007 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.cpp @@ -1,111 +1,111 @@ -/* Let's Go HP Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_ReadHpBar.h" -#include "PokemonSV_LetsGoHpReader.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -LetsGoHpWatcher::LetsGoHpWatcher(Color color) - : VisualInferenceCallback("LetsGoHpWatcher") - , m_color(color) - , m_box(0.055, 0.928, 0.067, 0.012) -// , m_last_known_value(-1) -{} - -void LetsGoHpWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - - -void LetsGoHpWatcher::clear(){ -// m_last_known_value.store(-1, std::memory_order_relaxed); - WriteSpinLock lg(m_lock); - m_history.clear(); -} -double LetsGoHpWatcher::last_known_value() const{ - std::vector sorted; - { - ReadSpinLock lg(m_lock); - - // No history. - if (m_history.empty()){ - return -1; - } - - // Insufficient history. - if (m_history.size() < 10){ - return -1; - } - - // Make local copy. - for (auto& item : m_history){ - sorted.emplace_back(item.second); - } - } - - // Sort and return median. - std::sort(sorted.begin(), sorted.end()); - - return sorted[sorted.size() / 2]; - -// return m_last_known_value.load(std::memory_order_relaxed); -} - - -bool LetsGoHpWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - double hp = read_hp_bar( - extract_box_reference(frame, ImageFloatBox(0.055, 0.928, 0.067, 0.012)) - ); - if (hp <= 0){ - return false; - } -// m_last_known_value.store(hp, std::memory_order_relaxed); - - WriteSpinLock lg(m_lock); - if (m_history.empty()){ - m_history.emplace_back(timestamp, hp); - return false; - } - if (timestamp < m_history.back().first){ - global_logger_tagged().log("LetsGoHpWatcher(): Detected that time has traveled backwards. Clearing history.", COLOR_RED); - m_history.clear(); - m_history.emplace_back(timestamp, hp); - return false; - } - - // Don't let spam skew the results. - if (timestamp < m_history.back().first + std::chrono::milliseconds(40)){ - return false; - } - - while (m_history.size() > 20){ - m_history.pop_front(); - } - m_history.emplace_back(timestamp, hp); - - return false; -} - - - - - - -} -} -} +/* Let's Go HP Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_ReadHpBar.h" +#include "PokemonSV_LetsGoHpReader.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +LetsGoHpWatcher::LetsGoHpWatcher(Color color) + : VisualInferenceCallback("LetsGoHpWatcher") + , m_color(color) + , m_box(0.055, 0.928, 0.067, 0.012) +// , m_last_known_value(-1) +{} + +void LetsGoHpWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + + +void LetsGoHpWatcher::clear(){ +// m_last_known_value.store(-1, std::memory_order_relaxed); + WriteSpinLock lg(m_lock); + m_history.clear(); +} +double LetsGoHpWatcher::last_known_value() const{ + std::vector sorted; + { + ReadSpinLock lg(m_lock); + + // No history. + if (m_history.empty()){ + return -1; + } + + // Insufficient history. + if (m_history.size() < 10){ + return -1; + } + + // Make local copy. + for (auto& item : m_history){ + sorted.emplace_back(item.second); + } + } + + // Sort and return median. + std::sort(sorted.begin(), sorted.end()); + + return sorted[sorted.size() / 2]; + +// return m_last_known_value.load(std::memory_order_relaxed); +} + + +bool LetsGoHpWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + double hp = read_hp_bar( + extract_box_reference(frame, ImageFloatBox(0.055, 0.928, 0.067, 0.012)) + ); + if (hp <= 0){ + return false; + } +// m_last_known_value.store(hp, std::memory_order_relaxed); + + WriteSpinLock lg(m_lock); + if (m_history.empty()){ + m_history.emplace_back(timestamp, hp); + return false; + } + if (timestamp < m_history.back().first){ + global_logger_tagged().log("LetsGoHpWatcher(): Detected that time has traveled backwards. Clearing history.", COLOR_RED); + m_history.clear(); + m_history.emplace_back(timestamp, hp); + return false; + } + + // Don't let spam skew the results. + if (timestamp < m_history.back().first + std::chrono::milliseconds(40)){ + return false; + } + + while (m_history.size() > 20){ + m_history.pop_front(); + } + m_history.emplace_back(timestamp, hp); + + return false; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h index 63d97cff12..f154f5d3d0 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h @@ -1,47 +1,47 @@ -/* Let's Go HP Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_LetsGoHpReader_H -#define PokemonAutomation_PokemonSV_LetsGoHpReader_H - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class LetsGoHpWatcher : public VisualInferenceCallback{ -public: - LetsGoHpWatcher(Color color); - - void clear(); - double last_known_value() const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Color m_color; - ImageFloatBox m_box; -// std::atomic m_last_known_value; - - mutable SpinLock m_lock; - std::deque> m_history; -}; - - - - -} -} -} -#endif +/* Let's Go HP Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_LetsGoHpReader_H +#define PokemonAutomation_PokemonSV_LetsGoHpReader_H + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class LetsGoHpWatcher : public VisualInferenceCallback{ +public: + LetsGoHpWatcher(Color color); + + void clear(); + double last_known_value() const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Color m_color; + ImageFloatBox m_box; +// std::atomic m_last_known_value; + + mutable SpinLock m_lock; + std::deque> m_history; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.cpp index 489e0d7244..e2664c3336 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.cpp @@ -1,229 +1,229 @@ -/* Let's Go Kill Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/AbstractLogger.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV_LetsGoKillDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Kernels::Waterfill; - - -const ImageMatch::ExactImageMatcher& LETS_GO_KILL_CROPPED(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/LetsGoKill-Cropped.png"); - return matcher; -} - - -bool is_kill_icon( - const ImageViewRGB32& image, - WaterfillObject& object, - const WaterfillObject& red, const WaterfillObject& white -){ -// cout << red.min_x << "-" << red.max_x << ", " << white.min_y << "-" << white.max_y << endl; - -// cout << "is_kill_icon" << endl; - if (red.max_y >= white.min_y){ -// cout << "bad y" << endl; - return false; - } - if (red.min_x < white.min_x){ -// cout << "bad min_x" << endl; - return false; - } - if (red.max_x < white.max_x){ -// cout << "bad max_x" << endl; - return false; - } - - object = red; - object.merge_assume_no_overlap(white); - -// extract_box_reference(image, object).save("test.png"); - - if (object.width() < 18 || object.height() < 18){ -// cout << "too small: " << object.width() << endl; - return false; - } - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 0.8 || aspect_ratio > 1.2){ -// cout << aspect_ratio << endl; - return false; - } - - ImageViewRGB32 cropped = extract_box_reference(image, object); -// cropped.save("test.png"); - double rmsd = LETS_GO_KILL_CROPPED().rmsd(cropped); -// cout << rmsd << endl; - return rmsd < 120; -} - - - - -LetsGoKillDetector::LetsGoKillDetector( - Color color, - const ImageFloatBox& box -) - : m_color(color) - , m_box(box) -{} -void LetsGoKillDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool LetsGoKillDetector::detect(const ImageViewRGB32& screen){ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, m_box); - std::vector reds; - std::vector whites; - std::unique_ptr session = make_WaterfillSession(); - { - std::vector matrices = compress_rgb32_to_binary_range( - region, - { - {0xff801e1e, 0xffff7f7f}, - {0xffb31e1e, 0xffff7f7f}, - } - ); -// size_t c = 0; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - auto iter = session->make_iterator(10); - WaterfillObject object; - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 1.5 || aspect_ratio > 2.5){ - continue; - } -// cout << object.area << endl; -// extract_box_reference(region, object).save("red-" + std::to_string(c++) + ".png"); - reds.emplace_back(std::move(object)); - } - } - } - { - std::vector matrices = compress_rgb32_to_binary_range( - region, - { - {0xffc0c0c0, 0xffffffff}, - } - ); -// size_t c = 0; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - auto iter = session->make_iterator(10); - WaterfillObject object; - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 1.5 || aspect_ratio > 2.7){ - continue; - } -// cout << object.area << endl; -// extract_box_reference(region, object).save("white-" + std::to_string(c++) + ".png"); - whites.emplace_back(std::move(object)); - } - } - } - for (WaterfillObject& red : reds){ - for (WaterfillObject& white : whites){ - WaterfillObject object; - if (is_kill_icon(region, object, red, white)){ - return true; - } - } - } - - return false; -} - - - -LetsGoKillWatcher::LetsGoKillWatcher( - Logger& logger, - Color color, bool trigger_if_detected, - const ImageFloatBox& box, - std::function on_kill_callback, - std::chrono::milliseconds duration -) - : DetectorToFinder("LetsGoKillWatcher", duration, color, box) - , m_logger(logger) - , m_trigger_if_detected(trigger_if_detected) - , m_on_kill_callback(on_kill_callback) - , m_last_detection(false) - , m_last_detected(WallClock::min()) -{} -bool LetsGoKillWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool result = DetectorToFinder::process_frame(frame, timestamp); - if (!result){ - m_last_detection = false; - return false; - } - - if (m_last_detected.load(std::memory_order_relaxed) == WallClock::min()){ - m_logger.log("Detected Let's Go kill icon."); - } - m_last_detected.store(timestamp, std::memory_order_release); - - if (!m_last_detection && m_on_kill_callback){ - m_on_kill_callback(); - } - m_last_detection = true; - return m_trigger_if_detected; -} - - - - -LetsGoKillSoundDetector::LetsGoKillSoundDetector(Logger& logger, DetectedCallback detected_callback) - : AudioPerSpectrumDetectorBase( - logger, - "LetsGoKillSoundDetector", - "Let's Go Kill Sound", - COLOR_RED, - [this, callback = std::move(detected_callback)](float error_coefficient){ - m_last_detected = current_time(); - return callback != nullptr ? callback(error_coefficient) : false; - } - ) - , m_last_detected(WallClock::min()) -{} -float LetsGoKillSoundDetector::get_score_threshold() const{ - return (float)GameSettings::instance().LETS_GO_KILL_SOUND_THRESHOLD; -} -std::unique_ptr LetsGoKillSoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Let's Go Kill", - AudioTemplateCache::instance().get_throw("PokemonSV/LetsGoKill", sample_rate), - SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, - GameSettings::instance().LETS_GO_KILL_SOUND_LOW_FREQUENCY - ); -} - - - - - - - - -} -} -} +/* Let's Go Kill Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/AbstractLogger.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV_LetsGoKillDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Kernels::Waterfill; + + +const ImageMatch::ExactImageMatcher& LETS_GO_KILL_CROPPED(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/LetsGoKill-Cropped.png"); + return matcher; +} + + +bool is_kill_icon( + const ImageViewRGB32& image, + WaterfillObject& object, + const WaterfillObject& red, const WaterfillObject& white +){ +// cout << red.min_x << "-" << red.max_x << ", " << white.min_y << "-" << white.max_y << endl; + +// cout << "is_kill_icon" << endl; + if (red.max_y >= white.min_y){ +// cout << "bad y" << endl; + return false; + } + if (red.min_x < white.min_x){ +// cout << "bad min_x" << endl; + return false; + } + if (red.max_x < white.max_x){ +// cout << "bad max_x" << endl; + return false; + } + + object = red; + object.merge_assume_no_overlap(white); + +// extract_box_reference(image, object).save("test.png"); + + if (object.width() < 18 || object.height() < 18){ +// cout << "too small: " << object.width() << endl; + return false; + } + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 0.8 || aspect_ratio > 1.2){ +// cout << aspect_ratio << endl; + return false; + } + + ImageViewRGB32 cropped = extract_box_reference(image, object); +// cropped.save("test.png"); + double rmsd = LETS_GO_KILL_CROPPED().rmsd(cropped); +// cout << rmsd << endl; + return rmsd < 120; +} + + + + +LetsGoKillDetector::LetsGoKillDetector( + Color color, + const ImageFloatBox& box +) + : m_color(color) + , m_box(box) +{} +void LetsGoKillDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool LetsGoKillDetector::detect(const ImageViewRGB32& screen){ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, m_box); + std::vector reds; + std::vector whites; + std::unique_ptr session = make_WaterfillSession(); + { + std::vector matrices = compress_rgb32_to_binary_range( + region, + { + {0xff801e1e, 0xffff7f7f}, + {0xffb31e1e, 0xffff7f7f}, + } + ); +// size_t c = 0; + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + auto iter = session->make_iterator(10); + WaterfillObject object; + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 1.5 || aspect_ratio > 2.5){ + continue; + } +// cout << object.area << endl; +// extract_box_reference(region, object).save("red-" + std::to_string(c++) + ".png"); + reds.emplace_back(std::move(object)); + } + } + } + { + std::vector matrices = compress_rgb32_to_binary_range( + region, + { + {0xffc0c0c0, 0xffffffff}, + } + ); +// size_t c = 0; + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + auto iter = session->make_iterator(10); + WaterfillObject object; + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 1.5 || aspect_ratio > 2.7){ + continue; + } +// cout << object.area << endl; +// extract_box_reference(region, object).save("white-" + std::to_string(c++) + ".png"); + whites.emplace_back(std::move(object)); + } + } + } + for (WaterfillObject& red : reds){ + for (WaterfillObject& white : whites){ + WaterfillObject object; + if (is_kill_icon(region, object, red, white)){ + return true; + } + } + } + + return false; +} + + + +LetsGoKillWatcher::LetsGoKillWatcher( + Logger& logger, + Color color, bool trigger_if_detected, + const ImageFloatBox& box, + std::function on_kill_callback, + std::chrono::milliseconds duration +) + : DetectorToFinder("LetsGoKillWatcher", duration, color, box) + , m_logger(logger) + , m_trigger_if_detected(trigger_if_detected) + , m_on_kill_callback(on_kill_callback) + , m_last_detection(false) + , m_last_detected(WallClock::min()) +{} +bool LetsGoKillWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool result = DetectorToFinder::process_frame(frame, timestamp); + if (!result){ + m_last_detection = false; + return false; + } + + if (m_last_detected.load(std::memory_order_relaxed) == WallClock::min()){ + m_logger.log("Detected Let's Go kill icon."); + } + m_last_detected.store(timestamp, std::memory_order_release); + + if (!m_last_detection && m_on_kill_callback){ + m_on_kill_callback(); + } + m_last_detection = true; + return m_trigger_if_detected; +} + + + + +LetsGoKillSoundDetector::LetsGoKillSoundDetector(Logger& logger, DetectedCallback detected_callback) + : AudioPerSpectrumDetectorBase( + logger, + "LetsGoKillSoundDetector", + "Let's Go Kill Sound", + COLOR_RED, + [this, callback = std::move(detected_callback)](float error_coefficient){ + m_last_detected = current_time(); + return callback != nullptr ? callback(error_coefficient) : false; + } + ) + , m_last_detected(WallClock::min()) +{} +float LetsGoKillSoundDetector::get_score_threshold() const{ + return (float)GameSettings::instance().LETS_GO_KILL_SOUND_THRESHOLD; +} +std::unique_ptr LetsGoKillSoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Let's Go Kill", + AudioTemplateCache::instance().get_throw("PokemonSV/LetsGoKill", sample_rate), + SpectrogramMatcher::Mode::SPIKE_CONV, sample_rate, + GameSettings::instance().LETS_GO_KILL_SOUND_LOW_FREQUENCY + ); +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h index 4dbf24909b..56fc3a7476 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h @@ -1,85 +1,85 @@ -/* Let's Go Kill Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_LetsGoKillDetector_H -#define PokemonAutomation_PokemonSV_LetsGoKillDetector_H - -#include -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class LetsGoKillDetector : public StaticScreenDetector{ -public: - LetsGoKillDetector(Color color, const ImageFloatBox& box = {0.71, 0.15, 0.04, 0.08}); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; -class LetsGoKillWatcher : public DetectorToFinder{ -public: - LetsGoKillWatcher( - Logger& logger, - Color color, bool trigger_if_detected = true, - const ImageFloatBox& box = {0.71, 0.15, 0.04, 0.08}, - std::function on_kill_callback = nullptr, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ); - - WallClock last_kill() const{ - return m_last_detected.load(std::memory_order_relaxed); - } - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - bool m_trigger_if_detected; - std::function m_on_kill_callback; - - bool m_last_detection; - std::atomic m_last_detected; -}; - - - - -class LetsGoKillSoundDetector : public AudioPerSpectrumDetectorBase{ -public: - LetsGoKillSoundDetector(Logger& logger, DetectedCallback detected_callback); - - virtual float get_score_threshold() const override; - - WallClock last_kill() const{ - return m_last_detected.load(std::memory_order_relaxed); - } - -private: - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; - -private: - std::atomic m_last_detected; -}; - - - -} -} -} -#endif +/* Let's Go Kill Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_LetsGoKillDetector_H +#define PokemonAutomation_PokemonSV_LetsGoKillDetector_H + +#include +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class LetsGoKillDetector : public StaticScreenDetector{ +public: + LetsGoKillDetector(Color color, const ImageFloatBox& box = {0.71, 0.15, 0.04, 0.08}); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; +class LetsGoKillWatcher : public DetectorToFinder{ +public: + LetsGoKillWatcher( + Logger& logger, + Color color, bool trigger_if_detected = true, + const ImageFloatBox& box = {0.71, 0.15, 0.04, 0.08}, + std::function on_kill_callback = nullptr, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ); + + WallClock last_kill() const{ + return m_last_detected.load(std::memory_order_relaxed); + } + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + bool m_trigger_if_detected; + std::function m_on_kill_callback; + + bool m_last_detection; + std::atomic m_last_detected; +}; + + + + +class LetsGoKillSoundDetector : public AudioPerSpectrumDetectorBase{ +public: + LetsGoKillSoundDetector(Logger& logger, DetectedCallback detected_callback); + + virtual float get_score_threshold() const override; + + WallClock last_kill() const{ + return m_last_detected.load(std::memory_order_relaxed); + } + +private: + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; + +private: + std::atomic m_last_detected; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp index 3a581ce7b3..73493c8be7 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.cpp @@ -1,37 +1,37 @@ -/* No Minimap Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSV_NoMinimapDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -NoMinimapDetector::NoMinimapDetector(Logger& logger, Color color) - : m_color(color) - , m_ball(0.890, 0.800, 0.030, 0.060) - , m_overworld(color) -{} -void NoMinimapDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_ball); -} -bool NoMinimapDetector::detect(const ImageViewRGB32& screen){ - return !m_overworld.detect(screen); -} - - - - -} -} -} +/* No Minimap Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSV_NoMinimapDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +NoMinimapDetector::NoMinimapDetector(Logger& logger, Color color) + : m_color(color) + , m_ball(0.890, 0.800, 0.030, 0.060) + , m_overworld(color) +{} +void NoMinimapDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_ball); +} +bool NoMinimapDetector::detect(const ImageViewRGB32& screen){ + return !m_overworld.detect(screen); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h index ba0c88a055..d57e99c7c2 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h @@ -1,52 +1,52 @@ -/* No Minimap Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_NoMinimapDetector_H -#define PokemonAutomation_PokemonSV_NoMinimapDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV_OverworldDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect that the minimap is not visible -class NoMinimapDetector : public StaticScreenDetector{ -public: - NoMinimapDetector(Logger& logger, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - -protected: - const Color m_color; - const ImageFloatBox m_ball; - OverworldDetector m_overworld; -}; - -class NoMinimapWatcher : public DetectorToFinder{ -public: - NoMinimapWatcher( - Logger& logger, - Color color = COLOR_RED, - std::chrono::milliseconds hold_duration = std::chrono::milliseconds(5000) - ) - : DetectorToFinder("GradientArrowWatcher", hold_duration, logger, color) - {} - -}; - - -} -} -} -#endif +/* No Minimap Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_NoMinimapDetector_H +#define PokemonAutomation_PokemonSV_NoMinimapDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV_OverworldDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect that the minimap is not visible +class NoMinimapDetector : public StaticScreenDetector{ +public: + NoMinimapDetector(Logger& logger, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + +protected: + const Color m_color; + const ImageFloatBox m_ball; + OverworldDetector m_overworld; +}; + +class NoMinimapWatcher : public DetectorToFinder{ +public: + NoMinimapWatcher( + Logger& logger, + Color color = COLOR_RED, + std::chrono::milliseconds hold_duration = std::chrono::milliseconds(5000) + ) + : DetectorToFinder("GradientArrowWatcher", hold_duration, logger, color) + {} + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp index 196ab42bf1..0bf2a387eb 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.cpp @@ -1,382 +1,382 @@ -/* Olive Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h" -#include "PokemonSV_OliveDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class OliveMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - OliveMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Olive.png", Color(0,0,0), Color(255, 255, 255), 5 - ){ - m_aspect_ratio_lower = 0.35; - m_aspect_ratio_upper = 3; - m_area_ratio_lower = 0.5; - m_area_ratio_upper = 1.5; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static OliveMatcher matcher; - return matcher; - } -}; - - -OliveDetector::OliveDetector(VideoStream& stream, Color color) - : m_overlays(stream.overlay()) - , m_color(color) -{} -void OliveDetector::make_overlays(VideoOverlaySet& items) const{ -} - - -std::pair OliveDetector::olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box){ - context.wait_for_all_requests(); - ImageFloatBox location = get_olive_floatbox(stream, context, 30, box); - double x = location.x + (location.width / 2); - double y = location.y + (location.height / 2); - - return std::make_pair(x, y); -} - -std::pair box_center(ImageFloatBox& box){ - double x = box.x + (box.width / 2); - double y = box.y + (box.height / 2); - - return std::make_pair(x, y); -} - -ImageFloatBox OliveDetector::get_olive_floatbox(const ImageViewRGB32& screen, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ - const std::vector> filters = { - {combine_rgb(0, 10, 0), combine_rgb(255, 255, 255)}, - }; - - ImageRGB32 green_only = filter_green(screen, Color(0xff000000), rgb_gap); - - const double min_object_size = 1000; - const double rmsd_threshold = 100; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - size_t largest_size = 0; - ImageFloatBox largest_green(0, 0, 0, 0); - ImageViewRGB32 cropped = extract_box_reference(green_only, box); - ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), box); - match_template_by_waterfill( - cropped, - OliveMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - size_t object_area = object.area; - if (object_area > largest_size){ - largest_size = object_area; - // cout << largest_size << endl; - ImagePixelBox found_box( - object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, - object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); - largest_green = pixelbox_to_floatbox(screen.width(), screen.height(), found_box); - } - - return false; - } - ); - - m_overlays.clear(); - m_overlays.add(m_color, largest_green); - - return largest_green; -} - -ImageFloatBox OliveDetector::get_olive_floatbox(VideoStream& stream, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ - size_t MAX_ATTEMPTS = 2; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - context.wait_for_all_requests(); - auto snapshot = stream.video().snapshot(); - const ImageViewRGB32& screen = snapshot; - ImageFloatBox olive_box = get_olive_floatbox(screen, context, rgb_gap, box); - if (olive_box.x == 0 && olive_box.y == 0){ - // Olive not detected. try again. may have been obscured by the player's head/hat - context.wait_for(Milliseconds(2000)); - continue; - } - return olive_box; - } - - // dump_snapshot(stream); - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "get_olive_floatbox(): Olive not detected.", - stream, - OliveFail::NO_OLIVE_DETECTED - ); -} - -ImageFloatBox OliveDetector::align_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap, - ImageFloatBox area_to_check -){ - size_t MAX_ATTEMPTS = 10; - // size_t olive_unchanged_count = 0; - ImageFloatBox olive_box; - DirectionDetector direction; - uint16_t scale_factor = 130; - int16_t prev_push_direction = 0; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - direction.change_direction(info, stream, context, direction_facing); - pbf_move_left_joystick(context, 128, 0, 5, 20); - - olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - - std::pair olive = box_center(olive_box); - double olive_x = olive.first; - double olive_y = olive.second; - double olive_area = olive_box.width * olive_box.height; - - double diff_from_center = olive_x - 0.5; - stream.log("olive_x: " + std::to_string(olive_x) + ", olive_y: " + std::to_string(olive_y) + ", olive_area: " + std::to_string(olive_area)); - if (std::abs(diff_from_center) < 0.01){ - return olive_box; - } - - - int16_t push_direction = (diff_from_center > 0) ? 1 : -1; - if (olive_y > 0.50 && scale_factor > 100){ - scale_factor = 100; - } - if (olive_box.height > 0.35 && scale_factor > 50){ - scale_factor = 50; - } - if (push_direction * -1 == prev_push_direction){ - // if you overshot the olive, and are now pushing in the opposite direction - // then reduce the push_duration. - scale_factor = int16_t(scale_factor * 0.5); - } - - // cout << "olive_height" << olive_box.height << endl; - // if (olive_box.height > 0.4){ - // scale_factor = 50; - // } - - - uint16_t push_duration = std::max(uint16_t((std::abs(diff_from_center) + 0.02) * scale_factor / (olive_y)), uint16_t(15)); - double push_magnitude = 128; // std::max(double(128 / (i + 1)), double(20)); // push less with each iteration/attempt - uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); - stream.log("scale_factor: " + std::to_string(scale_factor)); - stream.log("push x: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); - // pbf_wait(context, 100); - uint16_t wait_ticks = 50; - if (std::abs(diff_from_center) < 0.05){ - wait_ticks = 100; - } - pbf_move_left_joystick(context, push_x, 128, push_duration, wait_ticks); - prev_push_direction = push_direction; - - - // // check if we're making progress towards centering on the olive. - // ImageFloatBox olive_box_2 = get_olive_floatbox(console, context, rgb_gap, area_to_check); - // double box_1_area = olive_box.width * olive_box.height; - // double box_2_area = olive_box_2.width * olive_box_2.height; - // double area_diff = std::abs(box_1_area - box_2_area); - // double x_diff = std::abs(olive_box.x - olive_box_2.x); - // double y_diff = std::abs(olive_box.y - olive_box_2.y); - - // if (area_diff < 0.02 && x_diff < 0.01 && y_diff < 0.01){ - // olive_unchanged_count++; - // // not moving closer to the olive. either wall/fence is in the way, or we are right next the olive. - // console.log("Can't align to Olive. Try moving backwards and try again."); - // pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards - // if (olive_unchanged_count == 2){ - // throw OliveActionFailedException( - // console, ErrorReport::SEND_ERROR_REPORT, - // "align_to_olive(): Failed to align to olive.", - // true, - // OliveFail::FAILED_ALIGN_TO_OLIVE - // ); - // } - // }else{ - // olive_unchanged_count = 0; - // } - } - return olive_box; - - // don't throw an exception, since sometimes the program has trouble detecting the olive's exact location with the white logo on the olive. - // so we rely on maxing out the attempts to move on. - // throw OliveActionFailedException( - // console, ErrorReport::SEND_ERROR_REPORT, - // "align_to_olive(): Failed to align to olive.", - // true, - // OliveFail::FAILED_ALIGN_TO_OLIVE - // ); -} - - -// todo: detect and handle case where olive is stuck. -// todo: detect and handle case where olive is slightly to the left, and so we need to move on to the next phase -uint16_t OliveDetector::push_olive_forward( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint16_t total_forward_distance, - uint16_t push_olive, - uint8_t rgb_gap, - ImageFloatBox area_to_check -){ - stream.log("push_olive_forward(): Total distance: " + std::to_string(total_forward_distance)); - // uint16_t initial_push_olive = push_olive; - uint16_t ticks_walked = 0; - size_t MAX_ATTEMPTS = 10; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); - ticks_walked += walk_up_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); - - - if (ticks_walked >= total_forward_distance){ - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - return ticks_walked; - } - - align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); - // check location of olive before and after push - // if olive is approximately in the same location, then the olive is stuck. try moving backward and running forward again. - ImageFloatBox olive_box_1 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - for (size_t j = 0; j < 3; j++){ - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - stream.log("Push the olive."); - pbf_move_left_joystick(context, 128, 0, push_olive, 7 * TICKS_PER_SECOND); - - ticks_walked += push_olive; - ImageFloatBox olive_box_2 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - double box_1_area = olive_box_1.width * olive_box_1.height; - double box_2_area = olive_box_2.width * olive_box_2.height; - double area_diff = std::abs(box_1_area - box_2_area); - double x_diff = std::abs(olive_box_1.x - olive_box_2.x); - double y_diff = std::abs(olive_box_1.y - olive_box_2.y); - - if (area_diff < 0.02 && x_diff < 0.05 && y_diff < 0.05){ - stream.log("Olive is stuck? Move backwards and try pushing again."); - stream.log("Olive 1: area: " + std::to_string(box_1_area) + ", x: " + std::to_string(olive_box_1.x) + ", y: " + std::to_string(olive_box_1.y)); - stream.log("Olive 2: area: " + std::to_string(box_2_area) + ", x: " + std::to_string(olive_box_2.x) + ", y: " + std::to_string(olive_box_2.y)); - pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards - ticks_walked -= push_olive; - push_olive = 200; // run forward more on the next push - - if (j == 2){ - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "push_olive_forward(): Olive stuck.", - stream, - OliveFail::OLIVE_STUCK - ); - } - }else{ - break; - } - } - - if (ticks_walked > total_forward_distance){ - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - return ticks_walked; - } - - stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); - - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "push_olive_forward(): Something went wrong. Failed to walk the Olive forward as expected.", - stream, - OliveFail::FAILED_PUSH_OLIVE_TOTAL_DISTANCE - ); - -} - -uint16_t OliveDetector::walk_up_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap, - ImageFloatBox area_to_check -){ - uint16_t ticks_walked = 0; - size_t MAX_ATTEMPTS = 20; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - ImageFloatBox olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); - std::pair olive = box_center(olive_box); - // double olive_x = olive.first; - double olive_y = olive.second; - - uint16_t scale_factor = 2000; - uint16_t push_duration = std::max(uint16_t((0.57 - olive_y)*(0.57 - olive_y) * scale_factor), uint16_t(20)); - stream.log("walk_up_to_olive(): olive_y: " + std::to_string(olive_y)); - if (olive_y > 0.515){ - return ticks_walked; - } - stream.log("push duration: " + std::to_string(push_duration)); - // when push durations are low, the player moves less than expected - // once above 45, you walk about as much as expected - double walking_factor = 1; - if (push_duration <= 20){ - walking_factor = 0.40; - }else if (push_duration <= 25){ - walking_factor = 0.53; - }else if (push_duration <= 30){ - walking_factor = 0.69; - }else if (push_duration <= 35){ - walking_factor = 0.83; - }else if (push_duration <= 40){ - walking_factor = 0.91; - } - ticks_walked += uint16_t(push_duration * walking_factor); - - uint16_t wait_ticks = 50; - if (olive_y > 0.4){ - wait_ticks = 100; - } - pbf_move_left_joystick(context, 128, 0, push_duration, wait_ticks); - } - - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "walk_up_to_olive(): Something went wrong. Failed to walk up to the Olive", - stream, - OliveFail::FAILED_WALK_TO_OLIVE - ); - -} - - - -} -} -} +/* Olive Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h" +#include "PokemonSV_OliveDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class OliveMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + OliveMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Olive.png", Color(0,0,0), Color(255, 255, 255), 5 + ){ + m_aspect_ratio_lower = 0.35; + m_aspect_ratio_upper = 3; + m_area_ratio_lower = 0.5; + m_area_ratio_upper = 1.5; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static OliveMatcher matcher; + return matcher; + } +}; + + +OliveDetector::OliveDetector(VideoStream& stream, Color color) + : m_overlays(stream.overlay()) + , m_color(color) +{} +void OliveDetector::make_overlays(VideoOverlaySet& items) const{ +} + + +std::pair OliveDetector::olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box){ + context.wait_for_all_requests(); + ImageFloatBox location = get_olive_floatbox(stream, context, 30, box); + double x = location.x + (location.width / 2); + double y = location.y + (location.height / 2); + + return std::make_pair(x, y); +} + +std::pair box_center(ImageFloatBox& box){ + double x = box.x + (box.width / 2); + double y = box.y + (box.height / 2); + + return std::make_pair(x, y); +} + +ImageFloatBox OliveDetector::get_olive_floatbox(const ImageViewRGB32& screen, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ + const std::vector> filters = { + {combine_rgb(0, 10, 0), combine_rgb(255, 255, 255)}, + }; + + ImageRGB32 green_only = filter_green(screen, Color(0xff000000), rgb_gap); + + const double min_object_size = 1000; + const double rmsd_threshold = 100; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + size_t largest_size = 0; + ImageFloatBox largest_green(0, 0, 0, 0); + ImageViewRGB32 cropped = extract_box_reference(green_only, box); + ImagePixelBox pixel_search_area = floatbox_to_pixelbox(screen.width(), screen.height(), box); + match_template_by_waterfill( + cropped, + OliveMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + size_t object_area = object.area; + if (object_area > largest_size){ + largest_size = object_area; + // cout << largest_size << endl; + ImagePixelBox found_box( + object.min_x + pixel_search_area.min_x, object.min_y + pixel_search_area.min_y, + object.max_x + pixel_search_area.min_x, object.max_y + pixel_search_area.min_y); + largest_green = pixelbox_to_floatbox(screen.width(), screen.height(), found_box); + } + + return false; + } + ); + + m_overlays.clear(); + m_overlays.add(m_color, largest_green); + + return largest_green; +} + +ImageFloatBox OliveDetector::get_olive_floatbox(VideoStream& stream, ProControllerContext& context, uint8_t rgb_gap, ImageFloatBox box){ + size_t MAX_ATTEMPTS = 2; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + context.wait_for_all_requests(); + auto snapshot = stream.video().snapshot(); + const ImageViewRGB32& screen = snapshot; + ImageFloatBox olive_box = get_olive_floatbox(screen, context, rgb_gap, box); + if (olive_box.x == 0 && olive_box.y == 0){ + // Olive not detected. try again. may have been obscured by the player's head/hat + context.wait_for(Milliseconds(2000)); + continue; + } + return olive_box; + } + + // dump_snapshot(stream); + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "get_olive_floatbox(): Olive not detected.", + stream, + OliveFail::NO_OLIVE_DETECTED + ); +} + +ImageFloatBox OliveDetector::align_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap, + ImageFloatBox area_to_check +){ + size_t MAX_ATTEMPTS = 10; + // size_t olive_unchanged_count = 0; + ImageFloatBox olive_box; + DirectionDetector direction; + uint16_t scale_factor = 130; + int16_t prev_push_direction = 0; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + direction.change_direction(info, stream, context, direction_facing); + pbf_move_left_joystick(context, 128, 0, 5, 20); + + olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + + std::pair olive = box_center(olive_box); + double olive_x = olive.first; + double olive_y = olive.second; + double olive_area = olive_box.width * olive_box.height; + + double diff_from_center = olive_x - 0.5; + stream.log("olive_x: " + std::to_string(olive_x) + ", olive_y: " + std::to_string(olive_y) + ", olive_area: " + std::to_string(olive_area)); + if (std::abs(diff_from_center) < 0.01){ + return olive_box; + } + + + int16_t push_direction = (diff_from_center > 0) ? 1 : -1; + if (olive_y > 0.50 && scale_factor > 100){ + scale_factor = 100; + } + if (olive_box.height > 0.35 && scale_factor > 50){ + scale_factor = 50; + } + if (push_direction * -1 == prev_push_direction){ + // if you overshot the olive, and are now pushing in the opposite direction + // then reduce the push_duration. + scale_factor = int16_t(scale_factor * 0.5); + } + + // cout << "olive_height" << olive_box.height << endl; + // if (olive_box.height > 0.4){ + // scale_factor = 50; + // } + + + uint16_t push_duration = std::max(uint16_t((std::abs(diff_from_center) + 0.02) * scale_factor / (olive_y)), uint16_t(15)); + double push_magnitude = 128; // std::max(double(128 / (i + 1)), double(20)); // push less with each iteration/attempt + uint8_t push_x = uint8_t(std::max(std::min(int(128 + (push_direction * push_magnitude)), 255), 0)); + stream.log("scale_factor: " + std::to_string(scale_factor)); + stream.log("push x: " + std::to_string(push_x) + ", push duration: " + std::to_string(push_duration)); + // pbf_wait(context, 100); + uint16_t wait_ticks = 50; + if (std::abs(diff_from_center) < 0.05){ + wait_ticks = 100; + } + pbf_move_left_joystick(context, push_x, 128, push_duration, wait_ticks); + prev_push_direction = push_direction; + + + // // check if we're making progress towards centering on the olive. + // ImageFloatBox olive_box_2 = get_olive_floatbox(console, context, rgb_gap, area_to_check); + // double box_1_area = olive_box.width * olive_box.height; + // double box_2_area = olive_box_2.width * olive_box_2.height; + // double area_diff = std::abs(box_1_area - box_2_area); + // double x_diff = std::abs(olive_box.x - olive_box_2.x); + // double y_diff = std::abs(olive_box.y - olive_box_2.y); + + // if (area_diff < 0.02 && x_diff < 0.01 && y_diff < 0.01){ + // olive_unchanged_count++; + // // not moving closer to the olive. either wall/fence is in the way, or we are right next the olive. + // console.log("Can't align to Olive. Try moving backwards and try again."); + // pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards + // if (olive_unchanged_count == 2){ + // throw OliveActionFailedException( + // console, ErrorReport::SEND_ERROR_REPORT, + // "align_to_olive(): Failed to align to olive.", + // true, + // OliveFail::FAILED_ALIGN_TO_OLIVE + // ); + // } + // }else{ + // olive_unchanged_count = 0; + // } + } + return olive_box; + + // don't throw an exception, since sometimes the program has trouble detecting the olive's exact location with the white logo on the olive. + // so we rely on maxing out the attempts to move on. + // throw OliveActionFailedException( + // console, ErrorReport::SEND_ERROR_REPORT, + // "align_to_olive(): Failed to align to olive.", + // true, + // OliveFail::FAILED_ALIGN_TO_OLIVE + // ); +} + + +// todo: detect and handle case where olive is stuck. +// todo: detect and handle case where olive is slightly to the left, and so we need to move on to the next phase +uint16_t OliveDetector::push_olive_forward( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint16_t total_forward_distance, + uint16_t push_olive, + uint8_t rgb_gap, + ImageFloatBox area_to_check +){ + stream.log("push_olive_forward(): Total distance: " + std::to_string(total_forward_distance)); + // uint16_t initial_push_olive = push_olive; + uint16_t ticks_walked = 0; + size_t MAX_ATTEMPTS = 10; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); + ticks_walked += walk_up_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); + + + if (ticks_walked >= total_forward_distance){ + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + return ticks_walked; + } + + align_to_olive(info, stream, context, direction_facing, rgb_gap, area_to_check); + // check location of olive before and after push + // if olive is approximately in the same location, then the olive is stuck. try moving backward and running forward again. + ImageFloatBox olive_box_1 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + for (size_t j = 0; j < 3; j++){ + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + stream.log("Push the olive."); + pbf_move_left_joystick(context, 128, 0, push_olive, 7 * TICKS_PER_SECOND); + + ticks_walked += push_olive; + ImageFloatBox olive_box_2 = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + double box_1_area = olive_box_1.width * olive_box_1.height; + double box_2_area = olive_box_2.width * olive_box_2.height; + double area_diff = std::abs(box_1_area - box_2_area); + double x_diff = std::abs(olive_box_1.x - olive_box_2.x); + double y_diff = std::abs(olive_box_1.y - olive_box_2.y); + + if (area_diff < 0.02 && x_diff < 0.05 && y_diff < 0.05){ + stream.log("Olive is stuck? Move backwards and try pushing again."); + stream.log("Olive 1: area: " + std::to_string(box_1_area) + ", x: " + std::to_string(olive_box_1.x) + ", y: " + std::to_string(olive_box_1.y)); + stream.log("Olive 2: area: " + std::to_string(box_2_area) + ", x: " + std::to_string(olive_box_2.x) + ", y: " + std::to_string(olive_box_2.y)); + pbf_move_left_joystick(context, 128, 255, 75, 100); // walk backwards + ticks_walked -= push_olive; + push_olive = 200; // run forward more on the next push + + if (j == 2){ + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "push_olive_forward(): Olive stuck.", + stream, + OliveFail::OLIVE_STUCK + ); + } + }else{ + break; + } + } + + if (ticks_walked > total_forward_distance){ + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + return ticks_walked; + } + + stream.log("Distance walked: " + std::to_string(ticks_walked) + "/" + std::to_string(total_forward_distance)); + + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "push_olive_forward(): Something went wrong. Failed to walk the Olive forward as expected.", + stream, + OliveFail::FAILED_PUSH_OLIVE_TOTAL_DISTANCE + ); + +} + +uint16_t OliveDetector::walk_up_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap, + ImageFloatBox area_to_check +){ + uint16_t ticks_walked = 0; + size_t MAX_ATTEMPTS = 20; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + ImageFloatBox olive_box = get_olive_floatbox(stream, context, rgb_gap, area_to_check); + std::pair olive = box_center(olive_box); + // double olive_x = olive.first; + double olive_y = olive.second; + + uint16_t scale_factor = 2000; + uint16_t push_duration = std::max(uint16_t((0.57 - olive_y)*(0.57 - olive_y) * scale_factor), uint16_t(20)); + stream.log("walk_up_to_olive(): olive_y: " + std::to_string(olive_y)); + if (olive_y > 0.515){ + return ticks_walked; + } + stream.log("push duration: " + std::to_string(push_duration)); + // when push durations are low, the player moves less than expected + // once above 45, you walk about as much as expected + double walking_factor = 1; + if (push_duration <= 20){ + walking_factor = 0.40; + }else if (push_duration <= 25){ + walking_factor = 0.53; + }else if (push_duration <= 30){ + walking_factor = 0.69; + }else if (push_duration <= 35){ + walking_factor = 0.83; + }else if (push_duration <= 40){ + walking_factor = 0.91; + } + ticks_walked += uint16_t(push_duration * walking_factor); + + uint16_t wait_ticks = 50; + if (olive_y > 0.4){ + wait_ticks = 100; + } + pbf_move_left_joystick(context, 128, 0, push_duration, wait_ticks); + } + + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "walk_up_to_olive(): Something went wrong. Failed to walk up to the Olive", + stream, + OliveFail::FAILED_WALK_TO_OLIVE + ); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h index 48f9aa06e6..c78a2afc26 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h @@ -1,88 +1,88 @@ -/* Olive Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_OliveDetector_H -#define PokemonAutomation_PokemonSV_OliveDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class OliveDetector { -public: - OliveDetector(VideoStream& stream, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - - std::pair olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box = {0, 0.15, 1, 0.7}); - - ImageFloatBox get_olive_floatbox( - const ImageViewRGB32& screen, - ProControllerContext& context, - uint8_t rgb_gap, - ImageFloatBox box - ); - - // return ImageFloatBox of the of the Olive, based on the largest blob of green - ImageFloatBox get_olive_floatbox( - VideoStream& stream, - ProControllerContext& context, - uint8_t rgb_gap, - ImageFloatBox box - ); - - ImageFloatBox align_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap = 20, - ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} - ); - - // push the olive forward. - // move forward a certain number of ticks, as per total_forward_distance - // always face a certain direction, as per direction_facing - // return number of ticks walked - uint16_t push_olive_forward( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint16_t total_forward_distance, - uint16_t push_olive = 75, - uint8_t rgb_gap = 20, - ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} // {0, 0.15, 1, 0.7} - ); - - uint16_t walk_up_to_olive( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double direction_facing, - uint8_t rgb_gap = 20, - ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} - ); - - -protected: - VideoOverlaySet m_overlays; - const Color m_color; -}; - - - -} -} -} -#endif +/* Olive Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_OliveDetector_H +#define PokemonAutomation_PokemonSV_OliveDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class OliveDetector { +public: + OliveDetector(VideoStream& stream, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + + std::pair olive_location(VideoStream& stream, ProControllerContext& context, ImageFloatBox box = {0, 0.15, 1, 0.7}); + + ImageFloatBox get_olive_floatbox( + const ImageViewRGB32& screen, + ProControllerContext& context, + uint8_t rgb_gap, + ImageFloatBox box + ); + + // return ImageFloatBox of the of the Olive, based on the largest blob of green + ImageFloatBox get_olive_floatbox( + VideoStream& stream, + ProControllerContext& context, + uint8_t rgb_gap, + ImageFloatBox box + ); + + ImageFloatBox align_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap = 20, + ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} + ); + + // push the olive forward. + // move forward a certain number of ticks, as per total_forward_distance + // always face a certain direction, as per direction_facing + // return number of ticks walked + uint16_t push_olive_forward( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint16_t total_forward_distance, + uint16_t push_olive = 75, + uint8_t rgb_gap = 20, + ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} // {0, 0.15, 1, 0.7} + ); + + uint16_t walk_up_to_olive( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double direction_facing, + uint8_t rgb_gap = 20, + ImageFloatBox area_to_check = {0, 0.3, 1.0, 0.40} + ); + + +protected: + VideoOverlaySet m_overlays; + const Color m_color; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp index 56c04af2d5..f1edc3e199 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.cpp @@ -1,223 +1,223 @@ -/* Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_OverworldDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -const ImageMatch::ExactImageMatcher& RADAR_BALL(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/RadarBall.png"); - return matcher; -} - -class RadarBallMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - RadarBallMatcher() : WaterfillTemplateMatcher( - "PokemonSV/RadarBall.png", Color(192,192,0), Color(255, 255, 127), 5 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.01; - m_area_ratio_upper = 1.2; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static RadarBallMatcher matcher; - return matcher; - } -}; - - - -OverworldDetector::OverworldDetector(Color color) - : m_color(color) - , m_ball(0.890, 0.800, 0.030, 0.060) - , m_radar(0.815, 0.680, 0.180, 0.310) - , m_radar_inside(0.865, 0.750, 0.080, 0.170) -{} -void OverworldDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_ball); - items.add(m_color, m_radar); - items.add(m_color, m_radar_inside); -} -bool OverworldDetector::detect(const ImageViewRGB32& screen){ - return locate_ball(screen, false).first > 0; -} - -std::pair OverworldDetector::locate_ball(const ImageViewRGB32& screen, bool strict_requirements) const{ - const std::vector> filters = { - {0xffc0a000, 0xffffff1f}, - {0xffc0b000, 0xffffff1f}, - {0xffc0c000, 0xffffff1f}, - {0xffd0d000, 0xffffff1f}, - {0xffe0e000, 0xffffff1f}, - {0xfff0f000, 0xffffff1f}, - {0xfff8f800, 0xffffff1f}, - - {0xffc0c000, 0xffffff3f}, - {0xffd0d000, 0xffffff3f}, - {0xffe0e000, 0xffffff3f}, - {0xfff0f000, 0xffffff3f}, - {0xfff8f800, 0xffffff3f}, - - {0xffc0c000, 0xffffff5f}, - {0xffd0d000, 0xffffff5f}, - {0xffe0e000, 0xffffff5f}, - {0xfff0f000, 0xffffff5f}, - {0xfff8f800, 0xffffff5f}, - - {0xffc0c000, 0xffffff7f}, - {0xffd0d000, 0xffffff7f}, - {0xffe0e000, 0xffffff7f}, - {0xfff0f000, 0xffffff7f}, - {0xfff8f800, 0xffffff7f}, - }; - - // yellow arrow has area of 70-80. the yellow ball, when only partially filled (i.e. only the outer ring is waterfilled), has an area of 200. - // when the ball is fully filled in, it has an area of 550 - const double min_object_size = strict_requirements ? 150.0 : 50; - const double rmsd_threshold = strict_requirements ? 35.0 : 50.0; - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); - - std::pair ball_location(-1.0, -1.0); - ImageViewRGB32 cropped = extract_box_reference(screen, m_ball); - ImagePixelBox pixel_box = floatbox_to_pixelbox(screen.width(), screen.height(), m_ball); - match_template_by_waterfill( - cropped, - RadarBallMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - rmsd_threshold, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - // Exclude if it touches the borders of the box - if (object.min_x == 0 || object.min_y == 0 || - object.max_x == cropped.width() || object.max_y == cropped.height() - ){ - return false; - } - - ball_location = std::make_pair( - (object.center_of_gravity_x() + pixel_box.min_x) / (double)screen.width(), - (object.center_of_gravity_y() + pixel_box.min_y) / (double)screen.height() - ); - return true; - } - ); - - return ball_location; -} - - - -OverworldWatcher::OverworldWatcher(Logger& logger, Color color) - : OverworldDetector(color) - , VisualInferenceCallback("OverworldWatcher") - , m_logger(logger) - , m_ball_hold_duration(std::chrono::milliseconds(5000)) - , m_map_hold_duration(std::chrono::milliseconds(1000)) - , m_north_hold_duration(std::chrono::milliseconds(1000)) - , m_last_ball(WallClock::min()) - , m_last_north(WallClock::min()) -{ - m_direction_detector = DirectionDetector(COLOR_RED); -} - -void OverworldWatcher::make_overlays(VideoOverlaySet& items) const{ - OverworldDetector::make_overlays(items); -} -bool OverworldWatcher::process_frame(const VideoSnapshot& frame){ - // Return true if either of the following is true: - // - Ball is held and radar map stays still for 1 second. - // - Ball is held for 1 second and N symbol is held for 1 second - // - Ball is held for 5 seconds. - - // The map is not static when there is an event raid in it as it will - // sparkle. So instead, we revert to the ball being held for 5 seconds. - - // Using Ball detection alone can false positive on the slow moving lights after a tera raid. - // To reduce false positives, we also require: either the map staying still for 1 second, or detecting the N symbol. - - // No detection. - if (!detect(frame)){ - m_last_ball = WallClock::min(); - m_start_of_detection.clear(); - return false; - } - - // First detection of ball - if (m_last_ball == WallClock::min()){ - m_last_ball = frame.timestamp; - } - if (!m_start_of_detection){ - m_start_of_detection = frame; - return false; - } - - // Ball held for long enough. (5 seconds) - if (frame.timestamp - m_last_ball >= m_ball_hold_duration){ - return true; - } - - - // check for North symbol - if (!m_direction_detector.detect_north(m_logger, frame)){ - m_last_north = WallClock::min(); // not detecting north - }else{ - if (m_last_north == WallClock::min()){ // first detection of north - m_last_north = frame.timestamp; - } - if (frame.timestamp - m_last_north >= m_north_hold_duration){ - return true; - } - } - - - // Check if radar map stays still for 1 second. - - // Mismatching image sizes. - ImageViewRGB32 start = extract_box_reference(m_start_of_detection, m_radar_inside); - ImageViewRGB32 current = extract_box_reference(frame, m_radar_inside); - if (start.width() != current.width() || start.height() != current.height()){ - m_start_of_detection = frame; - return false; - } - - - double rmsd = ImageMatch::pixel_RMSD(start, current); -// cout << "rmsd = " << rmsd << endl; - if (rmsd > 2.0){ // Image of radar map has changed too much. - m_start_of_detection = frame; - return false; - } - - // Make sure radar map held for long enough. - return frame.timestamp - m_start_of_detection.timestamp >= m_map_hold_duration; -} - - - - - -} -} -} +/* Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_OverworldDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +const ImageMatch::ExactImageMatcher& RADAR_BALL(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/RadarBall.png"); + return matcher; +} + +class RadarBallMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + RadarBallMatcher() : WaterfillTemplateMatcher( + "PokemonSV/RadarBall.png", Color(192,192,0), Color(255, 255, 127), 5 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.01; + m_area_ratio_upper = 1.2; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static RadarBallMatcher matcher; + return matcher; + } +}; + + + +OverworldDetector::OverworldDetector(Color color) + : m_color(color) + , m_ball(0.890, 0.800, 0.030, 0.060) + , m_radar(0.815, 0.680, 0.180, 0.310) + , m_radar_inside(0.865, 0.750, 0.080, 0.170) +{} +void OverworldDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_ball); + items.add(m_color, m_radar); + items.add(m_color, m_radar_inside); +} +bool OverworldDetector::detect(const ImageViewRGB32& screen){ + return locate_ball(screen, false).first > 0; +} + +std::pair OverworldDetector::locate_ball(const ImageViewRGB32& screen, bool strict_requirements) const{ + const std::vector> filters = { + {0xffc0a000, 0xffffff1f}, + {0xffc0b000, 0xffffff1f}, + {0xffc0c000, 0xffffff1f}, + {0xffd0d000, 0xffffff1f}, + {0xffe0e000, 0xffffff1f}, + {0xfff0f000, 0xffffff1f}, + {0xfff8f800, 0xffffff1f}, + + {0xffc0c000, 0xffffff3f}, + {0xffd0d000, 0xffffff3f}, + {0xffe0e000, 0xffffff3f}, + {0xfff0f000, 0xffffff3f}, + {0xfff8f800, 0xffffff3f}, + + {0xffc0c000, 0xffffff5f}, + {0xffd0d000, 0xffffff5f}, + {0xffe0e000, 0xffffff5f}, + {0xfff0f000, 0xffffff5f}, + {0xfff8f800, 0xffffff5f}, + + {0xffc0c000, 0xffffff7f}, + {0xffd0d000, 0xffffff7f}, + {0xffe0e000, 0xffffff7f}, + {0xfff0f000, 0xffffff7f}, + {0xfff8f800, 0xffffff7f}, + }; + + // yellow arrow has area of 70-80. the yellow ball, when only partially filled (i.e. only the outer ring is waterfilled), has an area of 200. + // when the ball is fully filled in, it has an area of 550 + const double min_object_size = strict_requirements ? 150.0 : 50; + const double rmsd_threshold = strict_requirements ? 35.0 : 50.0; + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_object_size); + + std::pair ball_location(-1.0, -1.0); + ImageViewRGB32 cropped = extract_box_reference(screen, m_ball); + ImagePixelBox pixel_box = floatbox_to_pixelbox(screen.width(), screen.height(), m_ball); + match_template_by_waterfill( + cropped, + RadarBallMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + rmsd_threshold, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + // Exclude if it touches the borders of the box + if (object.min_x == 0 || object.min_y == 0 || + object.max_x == cropped.width() || object.max_y == cropped.height() + ){ + return false; + } + + ball_location = std::make_pair( + (object.center_of_gravity_x() + pixel_box.min_x) / (double)screen.width(), + (object.center_of_gravity_y() + pixel_box.min_y) / (double)screen.height() + ); + return true; + } + ); + + return ball_location; +} + + + +OverworldWatcher::OverworldWatcher(Logger& logger, Color color) + : OverworldDetector(color) + , VisualInferenceCallback("OverworldWatcher") + , m_logger(logger) + , m_ball_hold_duration(std::chrono::milliseconds(5000)) + , m_map_hold_duration(std::chrono::milliseconds(1000)) + , m_north_hold_duration(std::chrono::milliseconds(1000)) + , m_last_ball(WallClock::min()) + , m_last_north(WallClock::min()) +{ + m_direction_detector = DirectionDetector(COLOR_RED); +} + +void OverworldWatcher::make_overlays(VideoOverlaySet& items) const{ + OverworldDetector::make_overlays(items); +} +bool OverworldWatcher::process_frame(const VideoSnapshot& frame){ + // Return true if either of the following is true: + // - Ball is held and radar map stays still for 1 second. + // - Ball is held for 1 second and N symbol is held for 1 second + // - Ball is held for 5 seconds. + + // The map is not static when there is an event raid in it as it will + // sparkle. So instead, we revert to the ball being held for 5 seconds. + + // Using Ball detection alone can false positive on the slow moving lights after a tera raid. + // To reduce false positives, we also require: either the map staying still for 1 second, or detecting the N symbol. + + // No detection. + if (!detect(frame)){ + m_last_ball = WallClock::min(); + m_start_of_detection.clear(); + return false; + } + + // First detection of ball + if (m_last_ball == WallClock::min()){ + m_last_ball = frame.timestamp; + } + if (!m_start_of_detection){ + m_start_of_detection = frame; + return false; + } + + // Ball held for long enough. (5 seconds) + if (frame.timestamp - m_last_ball >= m_ball_hold_duration){ + return true; + } + + + // check for North symbol + if (!m_direction_detector.detect_north(m_logger, frame)){ + m_last_north = WallClock::min(); // not detecting north + }else{ + if (m_last_north == WallClock::min()){ // first detection of north + m_last_north = frame.timestamp; + } + if (frame.timestamp - m_last_north >= m_north_hold_duration){ + return true; + } + } + + + // Check if radar map stays still for 1 second. + + // Mismatching image sizes. + ImageViewRGB32 start = extract_box_reference(m_start_of_detection, m_radar_inside); + ImageViewRGB32 current = extract_box_reference(frame, m_radar_inside); + if (start.width() != current.width() || start.height() != current.height()){ + m_start_of_detection = frame; + return false; + } + + + double rmsd = ImageMatch::pixel_RMSD(start, current); +// cout << "rmsd = " << rmsd << endl; + if (rmsd > 2.0){ // Image of radar map has changed too much. + m_start_of_detection = frame; + return false; + } + + // Make sure radar map held for long enough. + return frame.timestamp - m_start_of_detection.timestamp >= m_map_hold_duration; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h index 39058946b2..c84f578637 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h @@ -1,64 +1,64 @@ -/* Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_OverworldDetector_H -#define PokemonAutomation_PokemonSV_OverworldDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect the player character is on overworld. -// It detects the center circle of the minimap. -class OverworldDetector : public StaticScreenDetector{ -public: - OverworldDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // return coordinates of the radar ball. return -1, -1 if unable to find the radar ball. - // set strict_requirements to true for more accurate detection of radar ball, - std::pair locate_ball(const ImageViewRGB32& screen, bool strict_requirements) const; - -protected: - const Color m_color; - const ImageFloatBox m_ball; - const ImageFloatBox m_radar; - const ImageFloatBox m_radar_inside; -}; - -class OverworldWatcher : public OverworldDetector, public VisualInferenceCallback{ -public: - OverworldWatcher(Logger& logger, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - - -private: - Logger& m_logger; - std::chrono::milliseconds m_ball_hold_duration; - std::chrono::milliseconds m_map_hold_duration; - std::chrono::milliseconds m_north_hold_duration; - WallClock m_last_ball; - WallClock m_last_north; - VideoSnapshot m_start_of_detection; - DirectionDetector m_direction_detector; -}; - - -} -} -} -#endif +/* Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_OverworldDetector_H +#define PokemonAutomation_PokemonSV_OverworldDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect the player character is on overworld. +// It detects the center circle of the minimap. +class OverworldDetector : public StaticScreenDetector{ +public: + OverworldDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // return coordinates of the radar ball. return -1, -1 if unable to find the radar ball. + // set strict_requirements to true for more accurate detection of radar ball, + std::pair locate_ball(const ImageViewRGB32& screen, bool strict_requirements) const; + +protected: + const Color m_color; + const ImageFloatBox m_ball; + const ImageFloatBox m_radar; + const ImageFloatBox m_radar_inside; +}; + +class OverworldWatcher : public OverworldDetector, public VisualInferenceCallback{ +public: + OverworldWatcher(Logger& logger, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + + +private: + Logger& m_logger; + std::chrono::milliseconds m_ball_hold_duration; + std::chrono::milliseconds m_map_hold_duration; + std::chrono::milliseconds m_north_hold_duration; + WallClock m_last_ball; + WallClock m_last_north; + VideoSnapshot m_start_of_detection; + DirectionDetector m_direction_detector; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp index c5344bef91..4105e8cd8a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.cpp @@ -1,72 +1,72 @@ -/* Stationary Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "PokemonSV_StationaryOverworldWatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -StationaryOverworldWatcher::StationaryOverworldWatcher(Color color, ImageFloatBox box, size_t seconds_stationary) - : VisualInferenceCallback("StationaryOverworldWatcher") - , m_color(color) - , m_box(box) - , m_overworld_detector(color) - , m_map_hold_duration(std::chrono::milliseconds(seconds_stationary * 1000)) -{} - -void StationaryOverworldWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool StationaryOverworldWatcher::process_frame(const VideoSnapshot& frame){ - if (!m_overworld_detector.detect(frame)){ - m_snapshot_start.clear(); - return false; - } - - if (!m_snapshot_start){ - m_snapshot_start = frame; - return false; - } - - // Check if radar map stays still for `m_map_hold_duration` - - // Mismatching image sizes. - ImageViewRGB32 start = extract_box_reference(m_snapshot_start, m_box); - ImageViewRGB32 current = extract_box_reference(frame, m_box); - if (start.width() != current.width() || start.height() != current.height()){ - m_snapshot_start = frame; - return false; - } - - double rmsd = ImageMatch::pixel_RMSD(start, current); -// cout << "rmsd = " << rmsd << endl; - if (rmsd > 2.0){ // Image of radar map has changed too much. - m_snapshot_start = frame; - return false; - } - - // Make sure radar map held for long enough. - return frame.timestamp - m_snapshot_start.timestamp >= m_map_hold_duration; -} - - - -} -} -} +/* Stationary Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "PokemonSV_StationaryOverworldWatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +StationaryOverworldWatcher::StationaryOverworldWatcher(Color color, ImageFloatBox box, size_t seconds_stationary) + : VisualInferenceCallback("StationaryOverworldWatcher") + , m_color(color) + , m_box(box) + , m_overworld_detector(color) + , m_map_hold_duration(std::chrono::milliseconds(seconds_stationary * 1000)) +{} + +void StationaryOverworldWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool StationaryOverworldWatcher::process_frame(const VideoSnapshot& frame){ + if (!m_overworld_detector.detect(frame)){ + m_snapshot_start.clear(); + return false; + } + + if (!m_snapshot_start){ + m_snapshot_start = frame; + return false; + } + + // Check if radar map stays still for `m_map_hold_duration` + + // Mismatching image sizes. + ImageViewRGB32 start = extract_box_reference(m_snapshot_start, m_box); + ImageViewRGB32 current = extract_box_reference(frame, m_box); + if (start.width() != current.width() || start.height() != current.height()){ + m_snapshot_start = frame; + return false; + } + + double rmsd = ImageMatch::pixel_RMSD(start, current); +// cout << "rmsd = " << rmsd << endl; + if (rmsd > 2.0){ // Image of radar map has changed too much. + m_snapshot_start = frame; + return false; + } + + // Make sure radar map held for long enough. + return frame.timestamp - m_snapshot_start.timestamp >= m_map_hold_duration; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h index 78654f1253..c6d8a98571 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h @@ -1,45 +1,45 @@ -/* Stationary Overworld Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H -#define PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class StationaryOverworldWatcher : public VisualInferenceCallback{ -public: - StationaryOverworldWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.865, 0.82, 0.08, 0.1}, size_t seconds_stationary = 5); - - virtual void make_overlays(VideoOverlaySet& items) const override; - // return true if the screen within `m_box` doesn't change for am amount of time as per `seconds_stationary` - // the overworld must be detected throughout this. - virtual bool process_frame(const VideoSnapshot& frame) override; - - -private: - const Color m_color; - const ImageFloatBox m_box; - OverworldDetector m_overworld_detector; - const std::chrono::milliseconds m_map_hold_duration; - VideoSnapshot m_snapshot_start; -}; - - -} -} -} -#endif +/* Stationary Overworld Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H +#define PokemonAutomation_PokemonSV_StationaryOverworldWatcher_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class StationaryOverworldWatcher : public VisualInferenceCallback{ +public: + StationaryOverworldWatcher(Color color = COLOR_RED, ImageFloatBox box = {0.865, 0.82, 0.08, 0.1}, size_t seconds_stationary = 5); + + virtual void make_overlays(VideoOverlaySet& items) const override; + // return true if the screen within `m_box` doesn't change for am amount of time as per `seconds_stationary` + // the overworld must be detected throughout this. + virtual bool process_frame(const VideoSnapshot& frame) override; + + +private: + const Color m_color; + const ImageFloatBox m_box; + OverworldDetector m_overworld_detector; + const std::chrono::milliseconds m_map_hold_duration; + VideoSnapshot m_snapshot_start; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp index f0bd60a484..91a0107ce1 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.cpp @@ -1,41 +1,41 @@ -/* Picnic Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSV_PicnicDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -PicnicDetector::PicnicDetector(Color color) -: m_color(color) -, m_button_b(color, WhiteButton::ButtonB, {0.024, 0.702, 0.024, 0.045}) -, m_button_minus(color, WhiteButton::ButtonMinus, {0.024, 0.866, 0.024, 0.045}) -, m_button_y(color, WhiteButton::ButtonY, {0.024, 0.917, 0.024, 0.045}) {} - -void PicnicDetector::make_overlays(VideoOverlaySet& items) const{ - m_button_b.make_overlays(items); - m_button_minus.make_overlays(items); - m_button_y.make_overlays(items); -} - -bool PicnicDetector::detect(const ImageViewRGB32& frame){ - return m_button_b.detect(frame) - && m_button_minus.detect(frame) - && m_button_y.detect(frame); -} - - -} -} -} +/* Picnic Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSV_PicnicDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +PicnicDetector::PicnicDetector(Color color) +: m_color(color) +, m_button_b(color, WhiteButton::ButtonB, {0.024, 0.702, 0.024, 0.045}) +, m_button_minus(color, WhiteButton::ButtonMinus, {0.024, 0.866, 0.024, 0.045}) +, m_button_y(color, WhiteButton::ButtonY, {0.024, 0.917, 0.024, 0.045}) {} + +void PicnicDetector::make_overlays(VideoOverlaySet& items) const{ + m_button_b.make_overlays(items); + m_button_minus.make_overlays(items); + m_button_y.make_overlays(items); +} + +bool PicnicDetector::detect(const ImageViewRGB32& frame){ + return m_button_b.detect(frame) + && m_button_minus.detect(frame) + && m_button_y.detect(frame); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h index debffcd41f..23617be23e 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h @@ -1,47 +1,47 @@ -/* Picnic Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PicnicDetector_H -#define PokemonAutomation_PokemonSV_PicnicDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect the player character is in a picnic -class PicnicDetector : public StaticScreenDetector{ -public: - PicnicDetector(Color color = COLOR_YELLOW); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - WhiteButtonDetector m_button_b; - WhiteButtonDetector m_button_minus; - WhiteButtonDetector m_button_y; -}; - -class PicnicWatcher : public DetectorToFinder{ -public: - PicnicWatcher(Color color = COLOR_YELLOW) - : DetectorToFinder("PicnicWatcher", std::chrono::milliseconds(1000), color) - {} -}; - - - -} -} -} -#endif +/* Picnic Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PicnicDetector_H +#define PokemonAutomation_PokemonSV_PicnicDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect the player character is in a picnic +class PicnicDetector : public StaticScreenDetector{ +public: + PicnicDetector(Color color = COLOR_YELLOW); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + WhiteButtonDetector m_button_b; + WhiteButtonDetector m_button_minus; + WhiteButtonDetector m_button_y; +}; + +class PicnicWatcher : public DetectorToFinder{ +public: + PicnicWatcher(Color color = COLOR_YELLOW) + : DetectorToFinder("PicnicWatcher", std::chrono::milliseconds(1000), color) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.cpp index c888e21d0d..3074e77991 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.cpp @@ -1,150 +1,150 @@ -/* Sandwich Hand Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSV_SandwichHandDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -namespace{ - -class SandwichFreeHandMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - SandwichFreeHandMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Picnic/SandwichHand-Template.png", Color(100,100,100), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.1; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static SandwichFreeHandMatcher matcher; - return matcher; - } -}; - - -class SandwichGrabbingHandMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - SandwichGrabbingHandMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Picnic/SandwichGrab-Template.png", Color(100,100,100), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.1; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static SandwichGrabbingHandMatcher matcher; - return matcher; - } -}; - -} // anonymous namespace - -std::string SANDWICH_HAND_TYPE_NAMES(SandwichHandType type){ - switch (type) - { - case SandwichHandType::FREE: - return "FREE"; - case SandwichHandType::GRABBING: - return "GRABBING"; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown SandwichHandType"); - } -} - -SandwichHandLocator::SandwichHandLocator(HandType hand_type, const ImageFloatBox& box, Color color) -: m_type(hand_type), m_box(box), m_color(color) {} - -void SandwichHandLocator::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -std::pair SandwichHandLocator::detect(const ImageViewRGB32& frame) const{ - ImageFloatBox entire_screen(0.0, 0.0, 1.0, 1.0); - std::pair location = locate_sandwich_hand(frame, m_box); - if (location.first >= 0.0){ - return location; - }else{ - return locate_sandwich_hand(frame, entire_screen); - } - -} - - -std::pair SandwichHandLocator::locate_sandwich_hand(const ImageViewRGB32& frame, ImageFloatBox area_to_search) const{ - const std::vector> filters = { - {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} - }; - - const double screen_rel_size = (frame.height() / 1080.0); - - double min_hand_size = ((m_type == HandType::FREE) ? 5000.0 : 4500.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_hand_size); - - std::pair hand_location(-1.0, -1.0); - - ImagePixelBox pixel_box = floatbox_to_pixelbox(frame.width(), frame.height(), area_to_search); - match_template_by_waterfill( - extract_box_reference(frame, area_to_search), - ((m_type == HandType::FREE) ? SandwichFreeHandMatcher::instance() : SandwichGrabbingHandMatcher::instance()), - filters, - {min_size, SIZE_MAX}, - 80, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { - hand_location = std::make_pair( - (object.center_of_gravity_x() + pixel_box.min_x) / (double)frame.width(), - (object.center_of_gravity_y() + pixel_box.min_y) / (double)frame.height() - ); - return true; - } - ); - - return hand_location; -} - - -SandwichHandWatcher::SandwichHandWatcher( - HandType hand_type, - const ImageFloatBox& box, - Color color -): VisualInferenceCallback("SandwichHandWatcher"), m_locator(hand_type, box, color), m_location(-1.0, -1.0) {} - -void SandwichHandWatcher::make_overlays(VideoOverlaySet& items) const{ - m_locator.make_overlays(items); -} - -bool SandwichHandWatcher::process_frame(const VideoSnapshot& frame){ - m_last_snapshot = frame; - m_location = m_locator.detect(frame); - return m_location.first >= 0.0; -} - -bool SandwichHandWatcher::recover_sandwich_hand_position(const ImageViewRGB32& frame){ - ImageFloatBox entire_screen(0.0, 0.0, 1.0, 1.0); - m_location = m_locator.locate_sandwich_hand(frame, entire_screen); - return m_location.first >= 0.0; -} - - -} -} -} +/* Sandwich Hand Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSV_SandwichHandDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +namespace{ + +class SandwichFreeHandMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + SandwichFreeHandMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Picnic/SandwichHand-Template.png", Color(100,100,100), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.1; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static SandwichFreeHandMatcher matcher; + return matcher; + } +}; + + +class SandwichGrabbingHandMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + SandwichGrabbingHandMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Picnic/SandwichGrab-Template.png", Color(100,100,100), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.1; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static SandwichGrabbingHandMatcher matcher; + return matcher; + } +}; + +} // anonymous namespace + +std::string SANDWICH_HAND_TYPE_NAMES(SandwichHandType type){ + switch (type) + { + case SandwichHandType::FREE: + return "FREE"; + case SandwichHandType::GRABBING: + return "GRABBING"; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown SandwichHandType"); + } +} + +SandwichHandLocator::SandwichHandLocator(HandType hand_type, const ImageFloatBox& box, Color color) +: m_type(hand_type), m_box(box), m_color(color) {} + +void SandwichHandLocator::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +std::pair SandwichHandLocator::detect(const ImageViewRGB32& frame) const{ + ImageFloatBox entire_screen(0.0, 0.0, 1.0, 1.0); + std::pair location = locate_sandwich_hand(frame, m_box); + if (location.first >= 0.0){ + return location; + }else{ + return locate_sandwich_hand(frame, entire_screen); + } + +} + + +std::pair SandwichHandLocator::locate_sandwich_hand(const ImageViewRGB32& frame, ImageFloatBox area_to_search) const{ + const std::vector> filters = { + {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} + }; + + const double screen_rel_size = (frame.height() / 1080.0); + + double min_hand_size = ((m_type == HandType::FREE) ? 5000.0 : 4500.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * min_hand_size); + + std::pair hand_location(-1.0, -1.0); + + ImagePixelBox pixel_box = floatbox_to_pixelbox(frame.width(), frame.height(), area_to_search); + match_template_by_waterfill( + extract_box_reference(frame, area_to_search), + ((m_type == HandType::FREE) ? SandwichFreeHandMatcher::instance() : SandwichGrabbingHandMatcher::instance()), + filters, + {min_size, SIZE_MAX}, + 80, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { + hand_location = std::make_pair( + (object.center_of_gravity_x() + pixel_box.min_x) / (double)frame.width(), + (object.center_of_gravity_y() + pixel_box.min_y) / (double)frame.height() + ); + return true; + } + ); + + return hand_location; +} + + +SandwichHandWatcher::SandwichHandWatcher( + HandType hand_type, + const ImageFloatBox& box, + Color color +): VisualInferenceCallback("SandwichHandWatcher"), m_locator(hand_type, box, color), m_location(-1.0, -1.0) {} + +void SandwichHandWatcher::make_overlays(VideoOverlaySet& items) const{ + m_locator.make_overlays(items); +} + +bool SandwichHandWatcher::process_frame(const VideoSnapshot& frame){ + m_last_snapshot = frame; + m_location = m_locator.detect(frame); + return m_location.first >= 0.0; +} + +bool SandwichHandWatcher::recover_sandwich_hand_position(const ImageViewRGB32& frame){ + ImageFloatBox entire_screen(0.0, 0.0, 1.0, 1.0); + m_location = m_locator.locate_sandwich_hand(frame, entire_screen); + return m_location.first >= 0.0; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h index 8f6201b3b6..ee5a662577 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h @@ -1,87 +1,87 @@ -/* Sandwich Hand Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichHandLocator_H -#define PokemonAutomation_PokemonSV_SandwichHandLocator_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -enum class SandwichHandType{ - FREE, - GRABBING, -}; - -// Type enum to string -std::string SANDWICH_HAND_TYPE_NAMES(SandwichHandType type); - -// Detect the hand used to make sandwich in the sandwich minigame. -class SandwichHandLocator{ -public: - using HandType = SandwichHandType; - - SandwichHandLocator(HandType hand_type, const ImageFloatBox& box, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - - // - return detected hand cetner location on screen, (x, y) where - // x: [0, 1), 0 left-most, 1 right-most, y: [0, 1), 0 top-most 1 bottom-most - // - first search m_box, then search the entire screen - // - If hand not detected, return (-1, -1). - std::pair detect(const ImageViewRGB32& screen) const; - - void change_box(const ImageFloatBox& new_box) { m_box = new_box; } - - // return the coordinates of the sandwich hand. - // search within the confines of the box area_to_search. - std::pair locate_sandwich_hand(const ImageViewRGB32& frame, ImageFloatBox area_to_search) const; - -private: - HandType m_type; - ImageFloatBox m_box; - Color m_color; -}; - -class SandwichHandWatcher : public VisualInferenceCallback{ -public: - using HandType = SandwichHandType; - - SandwichHandWatcher(HandType hand_type, const ImageFloatBox& box, Color color = COLOR_RED); - - const VideoSnapshot& last_snapshot() const{ return m_last_snapshot; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - - const std::pair& location() const { return m_location; } - - void change_box(const ImageFloatBox& new_box) { m_locator.change_box(new_box); } - - // - searches the whole screen for the sandwich hand, - // - then updates its location - // - return true if hand successfully found - bool recover_sandwich_hand_position(const ImageViewRGB32& frame); - - -private: - SandwichHandLocator m_locator; - std::pair m_location; - VideoSnapshot m_last_snapshot; -}; - - - -} -} -} -#endif +/* Sandwich Hand Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichHandLocator_H +#define PokemonAutomation_PokemonSV_SandwichHandLocator_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class SandwichHandType{ + FREE, + GRABBING, +}; + +// Type enum to string +std::string SANDWICH_HAND_TYPE_NAMES(SandwichHandType type); + +// Detect the hand used to make sandwich in the sandwich minigame. +class SandwichHandLocator{ +public: + using HandType = SandwichHandType; + + SandwichHandLocator(HandType hand_type, const ImageFloatBox& box, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + + // - return detected hand cetner location on screen, (x, y) where + // x: [0, 1), 0 left-most, 1 right-most, y: [0, 1), 0 top-most 1 bottom-most + // - first search m_box, then search the entire screen + // - If hand not detected, return (-1, -1). + std::pair detect(const ImageViewRGB32& screen) const; + + void change_box(const ImageFloatBox& new_box) { m_box = new_box; } + + // return the coordinates of the sandwich hand. + // search within the confines of the box area_to_search. + std::pair locate_sandwich_hand(const ImageViewRGB32& frame, ImageFloatBox area_to_search) const; + +private: + HandType m_type; + ImageFloatBox m_box; + Color m_color; +}; + +class SandwichHandWatcher : public VisualInferenceCallback{ +public: + using HandType = SandwichHandType; + + SandwichHandWatcher(HandType hand_type, const ImageFloatBox& box, Color color = COLOR_RED); + + const VideoSnapshot& last_snapshot() const{ return m_last_snapshot; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + + const std::pair& location() const { return m_location; } + + void change_box(const ImageFloatBox& new_box) { m_locator.change_box(new_box); } + + // - searches the whole screen for the sandwich hand, + // - then updates its location + // - return true if hand successfully found + bool recover_sandwich_hand_position(const ImageViewRGB32& frame); + + +private: + SandwichHandLocator m_locator; + std::pair m_location; + VideoSnapshot m_last_snapshot; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.cpp index ba3eafd039..0ccce251a5 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.cpp @@ -1,403 +1,403 @@ -/* Sandwich Ingredient Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/OCR/OCR_Routines.h" -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSV_SandwichIngredientDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -namespace{ - -class SandwichCondimentsPageMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - SandwichCondimentsPageMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Picnic/Condiments-Template.png", Color(100,100,100), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.1; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static SandwichCondimentsPageMatcher matcher; - return matcher; - } -}; - -class SandwichPicksPageMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - SandwichPicksPageMatcher() : WaterfillTemplateMatcher( - "PokemonSV/Picnic/Picks-Template.png", Color(100,100,100), Color(255, 255, 255), 50 - ){ - m_aspect_ratio_lower = 0.8; - m_aspect_ratio_upper = 1.2; - m_area_ratio_lower = 0.8; - m_area_ratio_upper = 1.2; - } - - static const ImageMatch::WaterfillTemplateMatcher& instance(){ - static SandwichPicksPageMatcher matcher; - return matcher; - } -}; - - -} // anonymous namespace - - -SandwichIngredientArrowDetector::SandwichIngredientArrowDetector(size_t menu_index, Color color) - : m_arrow(color, GradientArrowType::RIGHT, {0.013, menu_index*0.074 + 0.167, 0.056, 0.084}) {} - -void SandwichIngredientArrowDetector::make_overlays(VideoOverlaySet& items) const{ - m_arrow.make_overlays(items); -} - -bool SandwichIngredientArrowDetector::detect(const ImageViewRGB32& screen){ - return m_arrow.detect(screen); -} - - -DeterminedSandwichIngredientDetector::DeterminedSandwichIngredientDetector( - SandwichIngredientType ingredient_type, size_t index, Color color -) : m_color(color){ - float offset = (ingredient_type == SandwichIngredientType::FILLING ? 0.0f : 0.2885f) + index * 0.047f; - m_edges[0] = ImageFloatBox(offset + 0.509, 0.807, 0.033, 0.012); - m_edges[1] = ImageFloatBox(offset + 0.501, 0.821, 0.008, 0.057); - m_edges[2] = ImageFloatBox(offset + 0.509, 0.879, 0.033, 0.012); - m_edges[3] = ImageFloatBox(offset + 0.541, 0.821, 0.008, 0.057); -} - -void DeterminedSandwichIngredientDetector::make_overlays(VideoOverlaySet& items) const{ - for(int i = 0; i < 4; i++){ - items.add(m_color, m_edges[i]); - } -} - -bool DeterminedSandwichIngredientDetector::detect(const ImageViewRGB32& screen){ - int yellow_count = 0; - for(int i = 0; i < 4; i++){ - FloatPixel avg = image_stats(extract_box_reference(screen, m_edges[i])).average; - if (avg.r > avg.b * 1.25 && avg.g > avg.b * 1.15){ - yellow_count++; - } - } - return yellow_count >= 3; -} - - -SandwichCondimentsPageDetector::SandwichCondimentsPageDetector(Color color) - : m_color(color), m_box(0.046, 0.100, 0.021, 0.052) {} - -void SandwichCondimentsPageDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool SandwichCondimentsPageDetector::detect(const ImageViewRGB32& screen){ - const std::vector> filters = { - {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} - }; - - const double screen_rel_size = (screen.height() / 1080.0); - - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 700); - return match_template_by_waterfill( - extract_box_reference(screen, m_box), - SandwichCondimentsPageMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 70, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); -} - - - -SandwichPicksPageDetector::SandwichPicksPageDetector(Color color) - : m_color(color), m_box(0.046, 0.100, 0.021, 0.052) {} - -void SandwichPicksPageDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool SandwichPicksPageDetector::detect(const ImageViewRGB32& screen){ - const std::vector> filters = { - {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} - }; - - const double screen_rel_size = (screen.height() / 1080.0); - - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 300); - return match_template_by_waterfill( - extract_box_reference(screen, m_box), - SandwichPicksPageMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 70, - [&](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); -} - - - - -const SandwichFillingMatcher& SANDWICH_FILLING_MATCHER(){ - static SandwichFillingMatcher matcher; - return matcher; -} -SandwichFillingMatcher::SandwichFillingMatcher(const std::vector& min_euclidean_distance) - : CroppedImageDictionaryMatcher({0, 1}) -{ - for (double x : min_euclidean_distance){ - m_min_euclidean_distance_squared.emplace_back(x * x); - } - for (const auto& item : SANDWICH_FILLINGS_DATABASE()){ - add(item.first, item.second.sprite); - } -} -auto SandwichFillingMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ - ImageStats border = image_border_stats(image); -// cout << "border = " << border.average << endl; -// image.save("image.png"); - std::vector ret; - for (double min_euclidean_distance_squared : m_min_euclidean_distance_squared){ - ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( - image, - [&](Color pixel){ - double r = (double)pixel.red() - border.average.r; - double g = (double)pixel.green() - border.average.g; - double b = (double)pixel.blue() - border.average.b; - bool stop = r * r + g * g + b * b >= min_euclidean_distance_squared; - return stop; - } - ); - ret.emplace_back(extract_box_reference(image, box)); - } - return ret; -} - - -const SandwichCondimentMatcher& SANDWICH_CONDIMENT_MATCHER(){ - static SandwichCondimentMatcher matcher; - return matcher; -} -SandwichCondimentMatcher::SandwichCondimentMatcher(const std::vector& min_euclidean_distance) - : CroppedImageDictionaryMatcher({0, 1}) -{ - for (double x : min_euclidean_distance){ - m_min_euclidean_distance_squared.emplace_back(x * x); - } - for (const auto& item : SANDWICH_CONDIMENTS_DATABASE()){ - add(item.first, item.second.sprite); - } -} -auto SandwichCondimentMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ - ImageStats border = image_border_stats(image); - std::vector ret; - for (double min_euclidean_distance_squared : m_min_euclidean_distance_squared){ - ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( - image, - [&](Color pixel){ - double r = (double)pixel.red() - border.average.r; - double g = (double)pixel.green() - border.average.g; - double b = (double)pixel.blue() - border.average.b; - bool stop = r * r + g * g + b * b >= min_euclidean_distance_squared; - return stop; - } - ); - ret.emplace_back(extract_box_reference(image, box)); - } - return ret; -} - -const SandwichFillingOCR& SandwichFillingOCR::instance(){ - static SandwichFillingOCR reader; - return reader; -} -SandwichFillingOCR::SandwichFillingOCR() - : SmallDictionaryMatcher("PokemonSV/Picnic/SandwichFillingOCR.json") -{} -OCR::StringMatchResult SandwichFillingOCR::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, - min_text_ratio, max_text_ratio - ); -} - -const SandwichCondimentOCR& SandwichCondimentOCR::instance(){ - static SandwichCondimentOCR reader; - return reader; -} -SandwichCondimentOCR::SandwichCondimentOCR() - : SmallDictionaryMatcher("PokemonSV/Picnic/SandwichCondimentOCR.json") -{} -OCR::StringMatchResult SandwichCondimentOCR::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, - min_text_ratio, max_text_ratio - ); -} - -SandwichIngredientReader::SandwichIngredientReader(SandwichIngredientType ingredient_type, Color color) - : m_color(color) - , m_ingredient_type(ingredient_type) - , m_box_ingred_text(ingredient_list_boxes(ImageFloatBox(0.100, 0.179, 0.273, 0.057))) - , m_box_ingred_icon(ingredient_list_boxes(ImageFloatBox(0.064, 0.179, 0.032, 0.057))) - , m_box_confirmed(confirmed_ingredient_boxes(ingredient_type)) -{} - -void SandwichIngredientReader::make_overlays(VideoOverlaySet& items) const{ - for (size_t c = 0; c < INGREDIENT_PAGE_LINES; c++){ - items.add(m_color, m_box_ingred_text[c]); - items.add(m_color, m_box_ingred_icon[c]); - } - - for (size_t i = 0; i < m_box_confirmed.size(); i++){ - items.add(m_color, m_box_confirmed[i]); - } -} - - -std::array SandwichIngredientReader::confirmed_ingredient_boxes(SandwichIngredientType type){ - std::array boxes; - ImageFloatBox initial_box; - size_t total_count = 0; - switch (type){ - case SandwichIngredientType::FILLING: - initial_box = ImageFloatBox(0.508781, 0.820, 0.032, 0.057); - total_count = 6; - break; - case SandwichIngredientType::CONDIMENT: - initial_box = ImageFloatBox(0.797474, 0.820, 0.032, 0.057); - total_count = 4; - break; - } - - double initial_x = initial_box.x; - double width = initial_box.width; - double height = initial_box.height; - double y = initial_box.y; - double x_spacing = 0.0468; - for (size_t i = 0; i < total_count; i++){ - double x = initial_x + i*x_spacing; - boxes[i] = ImageFloatBox(x, y, width, height); - } - return boxes; -} - - -std::array SandwichIngredientReader::ingredient_list_boxes(ImageFloatBox initial_box){ - std::array material_boxes; - double x = initial_box.x; - double width = initial_box.width; - double height = initial_box.height; - double initial_y = initial_box.y; - double y_spacing = 0.074; - for (size_t i = 0; i < 10; i++){ - double y = initial_y + i*y_spacing; - material_boxes[i] = ImageFloatBox(x, y, width, height); - } - return material_boxes; -} - - -ImageMatch::ImageMatchResult SandwichIngredientReader::read_ingredient_page_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const{ - return read_with_icon_matcher(screen, m_box_ingred_icon[index]); -} - -ImageMatch::ImageMatchResult SandwichIngredientReader::read_confirmed_list_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const{ - return read_with_icon_matcher(screen, m_box_confirmed[index]); -} - -ImageMatch::ImageMatchResult SandwichIngredientReader::read_with_icon_matcher(const ImageViewRGB32& screen, const ImageFloatBox icon_box) const{ - // Get a crop of the sandwich ingredient icon - ImageViewRGB32 image = extract_box_reference(screen, icon_box); -// image.save("image" + std::to_string(icon_box.x) + ".png"); - -// // Remove the orange / yellow background when the ingredient is selected -// ImageRGB32 filtered_image = filter_rgb32_range(image, 0xffdfaf00, 0xffffef20, Color(0x00000000), true); -// filtered_image.save("filtered_image.png"); - - ImageMatch::ImageMatchResult results; - switch (m_ingredient_type){ - case SandwichIngredientType::FILLING: -// cout << "Filling" << endl; - results = SANDWICH_FILLING_MATCHER().match(image, ALPHA_SPREAD); - break; - case SandwichIngredientType::CONDIMENT: -// cout << "Condiment" << endl; - results = SANDWICH_CONDIMENT_MATCHER().match(image, ALPHA_SPREAD); - break; - } -// results.clear_beyond_alpha(MAX_ALPHA); - - return results; -} - -OCR::StringMatchResult SandwichIngredientReader::read_ingredient_page_with_ocr( - const ImageViewRGB32& screen, - Logger& logger, - Language language, - size_t index -) const{ - return read_with_ocr(screen, logger, language, m_box_ingred_text[index]); -} - -OCR::StringMatchResult SandwichIngredientReader::read_with_ocr( - const ImageViewRGB32& screen, - Logger& logger, - Language language, - const ImageFloatBox icon_box -) const{ - - // Get a crop of the sandwich ingredient text - ImageViewRGB32 image = extract_box_reference(screen, icon_box); - //image.save("image.png"); - - OCR::StringMatchResult results; - switch (m_ingredient_type){ - case SandwichIngredientType::FILLING: - results = SandwichFillingOCR::instance().read_substring(logger, language, image, OCR::BLACK_OR_WHITE_TEXT_FILTERS()); - break; - case SandwichIngredientType::CONDIMENT: - results = SandwichCondimentOCR::instance().read_substring(logger, language, image, OCR::BLACK_OR_WHITE_TEXT_FILTERS()); - break; - } - - return results; -} - -} -} -} +/* Sandwich Ingredient Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/OCR/OCR_Routines.h" +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSV_SandwichIngredientDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +namespace{ + +class SandwichCondimentsPageMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + SandwichCondimentsPageMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Picnic/Condiments-Template.png", Color(100,100,100), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.1; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static SandwichCondimentsPageMatcher matcher; + return matcher; + } +}; + +class SandwichPicksPageMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + SandwichPicksPageMatcher() : WaterfillTemplateMatcher( + "PokemonSV/Picnic/Picks-Template.png", Color(100,100,100), Color(255, 255, 255), 50 + ){ + m_aspect_ratio_lower = 0.8; + m_aspect_ratio_upper = 1.2; + m_area_ratio_lower = 0.8; + m_area_ratio_upper = 1.2; + } + + static const ImageMatch::WaterfillTemplateMatcher& instance(){ + static SandwichPicksPageMatcher matcher; + return matcher; + } +}; + + +} // anonymous namespace + + +SandwichIngredientArrowDetector::SandwichIngredientArrowDetector(size_t menu_index, Color color) + : m_arrow(color, GradientArrowType::RIGHT, {0.013, menu_index*0.074 + 0.167, 0.056, 0.084}) {} + +void SandwichIngredientArrowDetector::make_overlays(VideoOverlaySet& items) const{ + m_arrow.make_overlays(items); +} + +bool SandwichIngredientArrowDetector::detect(const ImageViewRGB32& screen){ + return m_arrow.detect(screen); +} + + +DeterminedSandwichIngredientDetector::DeterminedSandwichIngredientDetector( + SandwichIngredientType ingredient_type, size_t index, Color color +) : m_color(color){ + float offset = (ingredient_type == SandwichIngredientType::FILLING ? 0.0f : 0.2885f) + index * 0.047f; + m_edges[0] = ImageFloatBox(offset + 0.509, 0.807, 0.033, 0.012); + m_edges[1] = ImageFloatBox(offset + 0.501, 0.821, 0.008, 0.057); + m_edges[2] = ImageFloatBox(offset + 0.509, 0.879, 0.033, 0.012); + m_edges[3] = ImageFloatBox(offset + 0.541, 0.821, 0.008, 0.057); +} + +void DeterminedSandwichIngredientDetector::make_overlays(VideoOverlaySet& items) const{ + for(int i = 0; i < 4; i++){ + items.add(m_color, m_edges[i]); + } +} + +bool DeterminedSandwichIngredientDetector::detect(const ImageViewRGB32& screen){ + int yellow_count = 0; + for(int i = 0; i < 4; i++){ + FloatPixel avg = image_stats(extract_box_reference(screen, m_edges[i])).average; + if (avg.r > avg.b * 1.25 && avg.g > avg.b * 1.15){ + yellow_count++; + } + } + return yellow_count >= 3; +} + + +SandwichCondimentsPageDetector::SandwichCondimentsPageDetector(Color color) + : m_color(color), m_box(0.046, 0.100, 0.021, 0.052) {} + +void SandwichCondimentsPageDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool SandwichCondimentsPageDetector::detect(const ImageViewRGB32& screen){ + const std::vector> filters = { + {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} + }; + + const double screen_rel_size = (screen.height() / 1080.0); + + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 700); + return match_template_by_waterfill( + extract_box_reference(screen, m_box), + SandwichCondimentsPageMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 70, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); +} + + + +SandwichPicksPageDetector::SandwichPicksPageDetector(Color color) + : m_color(color), m_box(0.046, 0.100, 0.021, 0.052) {} + +void SandwichPicksPageDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool SandwichPicksPageDetector::detect(const ImageViewRGB32& screen){ + const std::vector> filters = { + {combine_rgb(150, 150, 150), combine_rgb(255, 255, 255)} + }; + + const double screen_rel_size = (screen.height() / 1080.0); + + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 300); + return match_template_by_waterfill( + extract_box_reference(screen, m_box), + SandwichPicksPageMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 70, + [&](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); +} + + + + +const SandwichFillingMatcher& SANDWICH_FILLING_MATCHER(){ + static SandwichFillingMatcher matcher; + return matcher; +} +SandwichFillingMatcher::SandwichFillingMatcher(const std::vector& min_euclidean_distance) + : CroppedImageDictionaryMatcher({0, 1}) +{ + for (double x : min_euclidean_distance){ + m_min_euclidean_distance_squared.emplace_back(x * x); + } + for (const auto& item : SANDWICH_FILLINGS_DATABASE()){ + add(item.first, item.second.sprite); + } +} +auto SandwichFillingMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ + ImageStats border = image_border_stats(image); +// cout << "border = " << border.average << endl; +// image.save("image.png"); + std::vector ret; + for (double min_euclidean_distance_squared : m_min_euclidean_distance_squared){ + ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + image, + [&](Color pixel){ + double r = (double)pixel.red() - border.average.r; + double g = (double)pixel.green() - border.average.g; + double b = (double)pixel.blue() - border.average.b; + bool stop = r * r + g * g + b * b >= min_euclidean_distance_squared; + return stop; + } + ); + ret.emplace_back(extract_box_reference(image, box)); + } + return ret; +} + + +const SandwichCondimentMatcher& SANDWICH_CONDIMENT_MATCHER(){ + static SandwichCondimentMatcher matcher; + return matcher; +} +SandwichCondimentMatcher::SandwichCondimentMatcher(const std::vector& min_euclidean_distance) + : CroppedImageDictionaryMatcher({0, 1}) +{ + for (double x : min_euclidean_distance){ + m_min_euclidean_distance_squared.emplace_back(x * x); + } + for (const auto& item : SANDWICH_CONDIMENTS_DATABASE()){ + add(item.first, item.second.sprite); + } +} +auto SandwichCondimentMatcher::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ + ImageStats border = image_border_stats(image); + std::vector ret; + for (double min_euclidean_distance_squared : m_min_euclidean_distance_squared){ + ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + image, + [&](Color pixel){ + double r = (double)pixel.red() - border.average.r; + double g = (double)pixel.green() - border.average.g; + double b = (double)pixel.blue() - border.average.b; + bool stop = r * r + g * g + b * b >= min_euclidean_distance_squared; + return stop; + } + ); + ret.emplace_back(extract_box_reference(image, box)); + } + return ret; +} + +const SandwichFillingOCR& SandwichFillingOCR::instance(){ + static SandwichFillingOCR reader; + return reader; +} +SandwichFillingOCR::SandwichFillingOCR() + : SmallDictionaryMatcher("PokemonSV/Picnic/SandwichFillingOCR.json") +{} +OCR::StringMatchResult SandwichFillingOCR::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, + min_text_ratio, max_text_ratio + ); +} + +const SandwichCondimentOCR& SandwichCondimentOCR::instance(){ + static SandwichCondimentOCR reader; + return reader; +} +SandwichCondimentOCR::SandwichCondimentOCR() + : SmallDictionaryMatcher("PokemonSV/Picnic/SandwichCondimentOCR.json") +{} +OCR::StringMatchResult SandwichCondimentOCR::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, + min_text_ratio, max_text_ratio + ); +} + +SandwichIngredientReader::SandwichIngredientReader(SandwichIngredientType ingredient_type, Color color) + : m_color(color) + , m_ingredient_type(ingredient_type) + , m_box_ingred_text(ingredient_list_boxes(ImageFloatBox(0.100, 0.179, 0.273, 0.057))) + , m_box_ingred_icon(ingredient_list_boxes(ImageFloatBox(0.064, 0.179, 0.032, 0.057))) + , m_box_confirmed(confirmed_ingredient_boxes(ingredient_type)) +{} + +void SandwichIngredientReader::make_overlays(VideoOverlaySet& items) const{ + for (size_t c = 0; c < INGREDIENT_PAGE_LINES; c++){ + items.add(m_color, m_box_ingred_text[c]); + items.add(m_color, m_box_ingred_icon[c]); + } + + for (size_t i = 0; i < m_box_confirmed.size(); i++){ + items.add(m_color, m_box_confirmed[i]); + } +} + + +std::array SandwichIngredientReader::confirmed_ingredient_boxes(SandwichIngredientType type){ + std::array boxes; + ImageFloatBox initial_box; + size_t total_count = 0; + switch (type){ + case SandwichIngredientType::FILLING: + initial_box = ImageFloatBox(0.508781, 0.820, 0.032, 0.057); + total_count = 6; + break; + case SandwichIngredientType::CONDIMENT: + initial_box = ImageFloatBox(0.797474, 0.820, 0.032, 0.057); + total_count = 4; + break; + } + + double initial_x = initial_box.x; + double width = initial_box.width; + double height = initial_box.height; + double y = initial_box.y; + double x_spacing = 0.0468; + for (size_t i = 0; i < total_count; i++){ + double x = initial_x + i*x_spacing; + boxes[i] = ImageFloatBox(x, y, width, height); + } + return boxes; +} + + +std::array SandwichIngredientReader::ingredient_list_boxes(ImageFloatBox initial_box){ + std::array material_boxes; + double x = initial_box.x; + double width = initial_box.width; + double height = initial_box.height; + double initial_y = initial_box.y; + double y_spacing = 0.074; + for (size_t i = 0; i < 10; i++){ + double y = initial_y + i*y_spacing; + material_boxes[i] = ImageFloatBox(x, y, width, height); + } + return material_boxes; +} + + +ImageMatch::ImageMatchResult SandwichIngredientReader::read_ingredient_page_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const{ + return read_with_icon_matcher(screen, m_box_ingred_icon[index]); +} + +ImageMatch::ImageMatchResult SandwichIngredientReader::read_confirmed_list_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const{ + return read_with_icon_matcher(screen, m_box_confirmed[index]); +} + +ImageMatch::ImageMatchResult SandwichIngredientReader::read_with_icon_matcher(const ImageViewRGB32& screen, const ImageFloatBox icon_box) const{ + // Get a crop of the sandwich ingredient icon + ImageViewRGB32 image = extract_box_reference(screen, icon_box); +// image.save("image" + std::to_string(icon_box.x) + ".png"); + +// // Remove the orange / yellow background when the ingredient is selected +// ImageRGB32 filtered_image = filter_rgb32_range(image, 0xffdfaf00, 0xffffef20, Color(0x00000000), true); +// filtered_image.save("filtered_image.png"); + + ImageMatch::ImageMatchResult results; + switch (m_ingredient_type){ + case SandwichIngredientType::FILLING: +// cout << "Filling" << endl; + results = SANDWICH_FILLING_MATCHER().match(image, ALPHA_SPREAD); + break; + case SandwichIngredientType::CONDIMENT: +// cout << "Condiment" << endl; + results = SANDWICH_CONDIMENT_MATCHER().match(image, ALPHA_SPREAD); + break; + } +// results.clear_beyond_alpha(MAX_ALPHA); + + return results; +} + +OCR::StringMatchResult SandwichIngredientReader::read_ingredient_page_with_ocr( + const ImageViewRGB32& screen, + Logger& logger, + Language language, + size_t index +) const{ + return read_with_ocr(screen, logger, language, m_box_ingred_text[index]); +} + +OCR::StringMatchResult SandwichIngredientReader::read_with_ocr( + const ImageViewRGB32& screen, + Logger& logger, + Language language, + const ImageFloatBox icon_box +) const{ + + // Get a crop of the sandwich ingredient text + ImageViewRGB32 image = extract_box_reference(screen, icon_box); + //image.save("image.png"); + + OCR::StringMatchResult results; + switch (m_ingredient_type){ + case SandwichIngredientType::FILLING: + results = SandwichFillingOCR::instance().read_substring(logger, language, image, OCR::BLACK_OR_WHITE_TEXT_FILTERS()); + break; + case SandwichIngredientType::CONDIMENT: + results = SandwichCondimentOCR::instance().read_substring(logger, language, image, OCR::BLACK_OR_WHITE_TEXT_FILTERS()); + break; + } + + return results; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h index 1060f206bf..afbaf1887f 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h @@ -1,221 +1,221 @@ -/* Sandwich Ingredient Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichIngredientDetector_H -#define PokemonAutomation_PokemonSV_SandwichIngredientDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/ImageMatch/ImageMatchResult.h" -#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect the selection arrow in the sandwich ingredient list (the list of fillings, condiments and picks). -class SandwichIngredientArrowDetector : public StaticScreenDetector{ -public: - // menu_index: which row of the selection arrow should be on. Range: [0, 9]: - // there are at most 10 rows on screen. - SandwichIngredientArrowDetector(size_t menu_index, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - GradientArrowDetector m_arrow; -}; - -class SandwichIngredientArrowWatcher : public DetectorToFinder{ -public: - SandwichIngredientArrowWatcher(size_t menu_index, Color color = COLOR_RED) - : DetectorToFinder("SandwichIngredientArrowWatcher", std::chrono::milliseconds(250), menu_index, color) - {} -}; - - - -enum class SandwichIngredientType{ - FILLING, - CONDIMENT, -}; - -// Detect one determined sandwich ingredient, displayed in the lower right corner, inside a highlighted yellow box -// The detector detects this yellow box. -class DeterminedSandwichIngredientDetector : public StaticScreenDetector{ -public: - // index: the `index`-th ingredient to detect. - // For single player, there are at most 6 fillings, so if `ingredient_type` == FILLING, `index` range is [0, 5]. - // For single player, there are at most 4 condiments, so if `ingredient_type` == CONDIMENT, `index` range is [0, 3]. - DeterminedSandwichIngredientDetector(SandwichIngredientType ingredient_type, size_t index, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - std::array m_edges; -}; - -class DeterminedSandwichIngredientWatcher : public DetectorToFinder{ -public: - DeterminedSandwichIngredientWatcher(SandwichIngredientType ingredient_type, size_t index, Color color = COLOR_RED) - : DetectorToFinder("DeterminedSandwichIngredientWatcher", std::chrono::milliseconds(100), ingredient_type, index, color) - {} -}; - -// Detect the white condiments page at upper left corner of the screen, during custom sandwich mode. -class SandwichCondimentsPageDetector : public StaticScreenDetector{ -public: - SandwichCondimentsPageDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; -class SandwichCondimentsPageWatcher : public DetectorToFinder{ -public: - SandwichCondimentsPageWatcher(Color color = COLOR_RED) - : DetectorToFinder("SandwichCondimentsPageWatcher", std::chrono::milliseconds(250), color) - {} -}; - -// Detect the white picks page at upper left corner of the screen, during custom sandwich mode. -class SandwichPicksPageDetector : public StaticScreenDetector{ -public: - SandwichPicksPageDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_box; -}; -class SandwichPicksPageWatcher : public DetectorToFinder{ -public: - SandwichPicksPageWatcher(Color color = COLOR_RED) - : DetectorToFinder("SandwichPicksPageWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -class SandwichFillingMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ -public: - SandwichFillingMatcher(const std::vector& min_euclidean_distance = {100, 150, 200}); - -private: - virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; - std::vector m_min_euclidean_distance_squared; -}; - -class SandwichCondimentMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ -public: - SandwichCondimentMatcher(const std::vector& min_euclidean_distance = {100, 150, 200}); - -private: - virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; - std::vector m_min_euclidean_distance_squared; -}; - -class SandwichFillingOCR : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -2.0; - static constexpr double MAX_LOG10P_SPREAD = 0.5; - -public: - static const SandwichFillingOCR& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -private: - SandwichFillingOCR(); -}; -class SandwichCondimentOCR : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -2.0; - static constexpr double MAX_LOG10P_SPREAD = 0.5; - -public: - static const SandwichCondimentOCR& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -private: - SandwichCondimentOCR(); -}; - -class SandwichIngredientReader{ -public: - static constexpr double MAX_ALPHA = 180; - static constexpr double ALPHA_SPREAD = 10; - static constexpr size_t INGREDIENT_PAGE_LINES = 10; - -public: - SandwichIngredientReader(SandwichIngredientType ingredient_type, Color color = COLOR_RED); - - void make_overlays(VideoOverlaySet& items) const; - - std::array confirmed_ingredient_boxes(SandwichIngredientType type); - - std::array ingredient_list_boxes(ImageFloatBox initial_box); - - ImageMatch::ImageMatchResult read_ingredient_page_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const; - - ImageMatch::ImageMatchResult read_confirmed_list_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const; - - // The icon matcher only works on the selected item, because we want to remove the yellow / orange background - ImageMatch::ImageMatchResult read_with_icon_matcher(const ImageViewRGB32& screen, const ImageFloatBox icon_box) const; - - OCR::StringMatchResult read_ingredient_page_with_ocr( - const ImageViewRGB32& screen, - Logger& logger, - Language language, - size_t index - ) const; - - // The OCR works on any ingredient, selected or not - OCR::StringMatchResult read_with_ocr( - const ImageViewRGB32& screen, - Logger& logger, - Language language, - const ImageFloatBox icon_box - ) const; - -// private: - Color m_color; - SandwichIngredientType m_ingredient_type; - std::array m_box_ingred_text; - std::array m_box_ingred_icon; - std::array m_box_confirmed; -}; - -} -} -} -#endif +/* Sandwich Ingredient Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichIngredientDetector_H +#define PokemonAutomation_PokemonSV_SandwichIngredientDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/ImageMatch/ImageMatchResult.h" +#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect the selection arrow in the sandwich ingredient list (the list of fillings, condiments and picks). +class SandwichIngredientArrowDetector : public StaticScreenDetector{ +public: + // menu_index: which row of the selection arrow should be on. Range: [0, 9]: + // there are at most 10 rows on screen. + SandwichIngredientArrowDetector(size_t menu_index, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + GradientArrowDetector m_arrow; +}; + +class SandwichIngredientArrowWatcher : public DetectorToFinder{ +public: + SandwichIngredientArrowWatcher(size_t menu_index, Color color = COLOR_RED) + : DetectorToFinder("SandwichIngredientArrowWatcher", std::chrono::milliseconds(250), menu_index, color) + {} +}; + + + +enum class SandwichIngredientType{ + FILLING, + CONDIMENT, +}; + +// Detect one determined sandwich ingredient, displayed in the lower right corner, inside a highlighted yellow box +// The detector detects this yellow box. +class DeterminedSandwichIngredientDetector : public StaticScreenDetector{ +public: + // index: the `index`-th ingredient to detect. + // For single player, there are at most 6 fillings, so if `ingredient_type` == FILLING, `index` range is [0, 5]. + // For single player, there are at most 4 condiments, so if `ingredient_type` == CONDIMENT, `index` range is [0, 3]. + DeterminedSandwichIngredientDetector(SandwichIngredientType ingredient_type, size_t index, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + std::array m_edges; +}; + +class DeterminedSandwichIngredientWatcher : public DetectorToFinder{ +public: + DeterminedSandwichIngredientWatcher(SandwichIngredientType ingredient_type, size_t index, Color color = COLOR_RED) + : DetectorToFinder("DeterminedSandwichIngredientWatcher", std::chrono::milliseconds(100), ingredient_type, index, color) + {} +}; + +// Detect the white condiments page at upper left corner of the screen, during custom sandwich mode. +class SandwichCondimentsPageDetector : public StaticScreenDetector{ +public: + SandwichCondimentsPageDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; +class SandwichCondimentsPageWatcher : public DetectorToFinder{ +public: + SandwichCondimentsPageWatcher(Color color = COLOR_RED) + : DetectorToFinder("SandwichCondimentsPageWatcher", std::chrono::milliseconds(250), color) + {} +}; + +// Detect the white picks page at upper left corner of the screen, during custom sandwich mode. +class SandwichPicksPageDetector : public StaticScreenDetector{ +public: + SandwichPicksPageDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_box; +}; +class SandwichPicksPageWatcher : public DetectorToFinder{ +public: + SandwichPicksPageWatcher(Color color = COLOR_RED) + : DetectorToFinder("SandwichPicksPageWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +class SandwichFillingMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ +public: + SandwichFillingMatcher(const std::vector& min_euclidean_distance = {100, 150, 200}); + +private: + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; + std::vector m_min_euclidean_distance_squared; +}; + +class SandwichCondimentMatcher : public ImageMatch::CroppedImageDictionaryMatcher{ +public: + SandwichCondimentMatcher(const std::vector& min_euclidean_distance = {100, 150, 200}); + +private: + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; + std::vector m_min_euclidean_distance_squared; +}; + +class SandwichFillingOCR : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -2.0; + static constexpr double MAX_LOG10P_SPREAD = 0.5; + +public: + static const SandwichFillingOCR& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +private: + SandwichFillingOCR(); +}; +class SandwichCondimentOCR : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -2.0; + static constexpr double MAX_LOG10P_SPREAD = 0.5; + +public: + static const SandwichCondimentOCR& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +private: + SandwichCondimentOCR(); +}; + +class SandwichIngredientReader{ +public: + static constexpr double MAX_ALPHA = 180; + static constexpr double ALPHA_SPREAD = 10; + static constexpr size_t INGREDIENT_PAGE_LINES = 10; + +public: + SandwichIngredientReader(SandwichIngredientType ingredient_type, Color color = COLOR_RED); + + void make_overlays(VideoOverlaySet& items) const; + + std::array confirmed_ingredient_boxes(SandwichIngredientType type); + + std::array ingredient_list_boxes(ImageFloatBox initial_box); + + ImageMatch::ImageMatchResult read_ingredient_page_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const; + + ImageMatch::ImageMatchResult read_confirmed_list_with_icon_matcher(const ImageViewRGB32& screen, size_t index) const; + + // The icon matcher only works on the selected item, because we want to remove the yellow / orange background + ImageMatch::ImageMatchResult read_with_icon_matcher(const ImageViewRGB32& screen, const ImageFloatBox icon_box) const; + + OCR::StringMatchResult read_ingredient_page_with_ocr( + const ImageViewRGB32& screen, + Logger& logger, + Language language, + size_t index + ) const; + + // The OCR works on any ingredient, selected or not + OCR::StringMatchResult read_with_ocr( + const ImageViewRGB32& screen, + Logger& logger, + Language language, + const ImageFloatBox icon_box + ) const; + +// private: + Color m_color; + SandwichIngredientType m_ingredient_type; + std::array m_box_ingred_text; + std::array m_box_ingred_icon; + std::array m_box_confirmed; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.cpp index 219e91346a..da4f228d7b 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.cpp @@ -1,138 +1,138 @@ -/* Sandwich Plate Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonSV_SandwichPlateDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -SandwichPlateDetector::~SandwichPlateDetector() = default; - -SandwichPlateDetector::SandwichPlateDetector(Logger& logger, Color color, Language language, Side side) - : m_logger(logger), m_color(color), m_language(language), m_side(side) -{ - switch(side){ - case Side::LEFT: - m_box = ImageFloatBox(0.099, 0.270, 0.205, 0.041); - break; - case Side::MIDDLE: - m_box = ImageFloatBox(0.397, 0.268, 0.203, 0.044); - break; - case Side::RIGHT: - m_box = ImageFloatBox(0.699, 0.269, 0.201, 0.044); - break; - default: - throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, - "Invalid Side for SandwichPlateDetector()"); - } -} - -void SandwichPlateDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool SandwichPlateDetector::detect(const ImageViewRGB32& screen){ - return !detect_filling_name(screen).empty(); -} - -std::string SandwichPlateDetector::detect_filling_name(const ImageViewRGB32& screen) const{ - std::multimap results; - - const uint32_t image_filter_low_bounds[2] = { - combine_rgb(215, 215, 215), - combine_rgb(200, 200, 200) - }; - const uint32_t image_filter_high_bound = combine_rgb(255, 255, 255); - - for (uint32_t image_filter_low_bound : image_filter_low_bounds){ - ImageRGB32 plate_label = to_blackwhite_rgb32_range( - extract_box_reference(screen, m_box), - true, - image_filter_low_bound, image_filter_high_bound - ); - - // dump_debug_image(m_logger, "PokemonSV/SandwichPlateDetector", "blackwhite_input", plate_label); - - OCR::StringMatchResult ocr_result = PokemonSV::SandwichFillingOCR::instance().read_substring( - m_logger, m_language, plate_label, - OCR::BLACK_TEXT_FILTERS() - ); - ocr_result.clear_beyond_log10p(SandwichFillingOCR::MAX_LOG10P); - ocr_result.clear_beyond_spread(SandwichFillingOCR::MAX_LOG10P_SPREAD); - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - - } - } - - if (results.empty()){ - return ""; - } - - return results.begin()->second.token; -} - - -bool SandwichPlateDetector::is_label_yellow(const ImageViewRGB32& screen) const{ - ImageRGB32 yellow_region = filter_rgb32_range( - extract_box_reference(screen, m_box), - combine_rgb(180, 161, 0), combine_rgb(255, 255, 100), Color(0), false - ); - ImageStats stats = image_stats(yellow_region); - - const double screen_rel_size = (screen.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 200); - - return stats.count >= min_size; -} - - - -SandwichPlateWatcher::~SandwichPlateWatcher() = default; - -SandwichPlateWatcher::SandwichPlateWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, Side side) - : VisualInferenceCallback("SandwichPlateWatcher") - , m_overlay(overlay) - , m_detector(logger, color, language, side) -{} - -void SandwichPlateWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool SandwichPlateWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - m_filling_name = m_detector.detect_filling_name(screen); - if (m_filling_name.empty()){ - return false; - } - - return true; -} - - - - - - - - -} -} -} +/* Sandwich Plate Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonSV_SandwichPlateDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +SandwichPlateDetector::~SandwichPlateDetector() = default; + +SandwichPlateDetector::SandwichPlateDetector(Logger& logger, Color color, Language language, Side side) + : m_logger(logger), m_color(color), m_language(language), m_side(side) +{ + switch(side){ + case Side::LEFT: + m_box = ImageFloatBox(0.099, 0.270, 0.205, 0.041); + break; + case Side::MIDDLE: + m_box = ImageFloatBox(0.397, 0.268, 0.203, 0.044); + break; + case Side::RIGHT: + m_box = ImageFloatBox(0.699, 0.269, 0.201, 0.044); + break; + default: + throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, + "Invalid Side for SandwichPlateDetector()"); + } +} + +void SandwichPlateDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool SandwichPlateDetector::detect(const ImageViewRGB32& screen){ + return !detect_filling_name(screen).empty(); +} + +std::string SandwichPlateDetector::detect_filling_name(const ImageViewRGB32& screen) const{ + std::multimap results; + + const uint32_t image_filter_low_bounds[2] = { + combine_rgb(215, 215, 215), + combine_rgb(200, 200, 200) + }; + const uint32_t image_filter_high_bound = combine_rgb(255, 255, 255); + + for (uint32_t image_filter_low_bound : image_filter_low_bounds){ + ImageRGB32 plate_label = to_blackwhite_rgb32_range( + extract_box_reference(screen, m_box), + true, + image_filter_low_bound, image_filter_high_bound + ); + + // dump_debug_image(m_logger, "PokemonSV/SandwichPlateDetector", "blackwhite_input", plate_label); + + OCR::StringMatchResult ocr_result = PokemonSV::SandwichFillingOCR::instance().read_substring( + m_logger, m_language, plate_label, + OCR::BLACK_TEXT_FILTERS() + ); + ocr_result.clear_beyond_log10p(SandwichFillingOCR::MAX_LOG10P); + ocr_result.clear_beyond_spread(SandwichFillingOCR::MAX_LOG10P_SPREAD); + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + + } + } + + if (results.empty()){ + return ""; + } + + return results.begin()->second.token; +} + + +bool SandwichPlateDetector::is_label_yellow(const ImageViewRGB32& screen) const{ + ImageRGB32 yellow_region = filter_rgb32_range( + extract_box_reference(screen, m_box), + combine_rgb(180, 161, 0), combine_rgb(255, 255, 100), Color(0), false + ); + ImageStats stats = image_stats(yellow_region); + + const double screen_rel_size = (screen.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 200); + + return stats.count >= min_size; +} + + + +SandwichPlateWatcher::~SandwichPlateWatcher() = default; + +SandwichPlateWatcher::SandwichPlateWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, Side side) + : VisualInferenceCallback("SandwichPlateWatcher") + , m_overlay(overlay) + , m_detector(logger, color, language, side) +{} + +void SandwichPlateWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool SandwichPlateWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + m_filling_name = m_detector.detect_filling_name(screen); + if (m_filling_name.empty()){ + return false; + } + + return true; +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h index 993871de9e..88841045f3 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h @@ -1,86 +1,86 @@ -/* Sandwich Plate Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichPlateDetector_H -#define PokemonAutomation_PokemonSV_SandwichPlateDetector_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonFramework/Language.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Detect the left, middle or right plate that hold sandwich fillings during the making sandwich minigame, -// using OCR to find the filling name tag under the plate. -class SandwichPlateDetector : public StaticScreenDetector{ -public: - enum class Side{ - LEFT, - MIDDLE, - RIGHT, - NOT_APPLICABLE, - }; - SandwichPlateDetector(Logger& logger, Color color, Language language, Side side); - virtual ~SandwichPlateDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Return detected sandwich filling name slug. Return empty string if not detected - std::string detect_filling_name(const ImageViewRGB32& screen) const; - - // check if the filling name label is yellow. - // It is yellow when a filling is grabbed by the sandwich hand in the minigame. - bool is_label_yellow(const ImageViewRGB32& screen) const; - -protected: - Logger& m_logger; - Color m_color; - Language m_language; - Side m_side; - ImageFloatBox m_box; -}; - - -// Detect the left, middle or right plate that hold sandwich fillings during the making sandwich minigame, -// using OCR to find the filling name tag under the plate. -class SandwichPlateWatcher : public VisualInferenceCallback{ -public: - using Side = SandwichPlateDetector::Side; - ~SandwichPlateWatcher(); - SandwichPlateWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, Side side); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - const std::string& filling_name() const { return m_filling_name; } - - -protected: - VideoOverlay& m_overlay; - SandwichPlateDetector m_detector; - std::string m_filling_name; -}; - - - - -} -} -} -#endif +/* Sandwich Plate Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichPlateDetector_H +#define PokemonAutomation_PokemonSV_SandwichPlateDetector_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonFramework/Language.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Detect the left, middle or right plate that hold sandwich fillings during the making sandwich minigame, +// using OCR to find the filling name tag under the plate. +class SandwichPlateDetector : public StaticScreenDetector{ +public: + enum class Side{ + LEFT, + MIDDLE, + RIGHT, + NOT_APPLICABLE, + }; + SandwichPlateDetector(Logger& logger, Color color, Language language, Side side); + virtual ~SandwichPlateDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Return detected sandwich filling name slug. Return empty string if not detected + std::string detect_filling_name(const ImageViewRGB32& screen) const; + + // check if the filling name label is yellow. + // It is yellow when a filling is grabbed by the sandwich hand in the minigame. + bool is_label_yellow(const ImageViewRGB32& screen) const; + +protected: + Logger& m_logger; + Color m_color; + Language m_language; + Side m_side; + ImageFloatBox m_box; +}; + + +// Detect the left, middle or right plate that hold sandwich fillings during the making sandwich minigame, +// using OCR to find the filling name tag under the plate. +class SandwichPlateWatcher : public VisualInferenceCallback{ +public: + using Side = SandwichPlateDetector::Side; + ~SandwichPlateWatcher(); + SandwichPlateWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, Side side); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + const std::string& filling_name() const { return m_filling_name; } + + +protected: + VideoOverlay& m_overlay; + SandwichPlateDetector m_detector; + std::string m_filling_name; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.cpp index 078637bf5d..4c2f2b6a65 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.cpp @@ -1,147 +1,147 @@ -/* Sandwich Recipe Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV_SandwichRecipeDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ - -template class FixedLimitVector; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -SandwichRecipeNumberDetector::SandwichRecipeNumberDetector(Logger& logger, Color color): m_logger(logger), m_color(color){ - for(int y = 0; y < 3; y++){ - for(int x = 0; x < 2; x++){ - // m_arrow_boxes[y*2+x] = ImageFloatBox(x * 0.26 + 0.103, y * 0.275 + 0.074, 0.068, 0.085); - m_id_boxes[y*2+x] = ImageFloatBox(x * 0.26 + 0.015, y * 0.277 + 0.240, 0.042, 0.048); - } - } -} - -void SandwichRecipeNumberDetector::make_overlays(VideoOverlaySet& items) const{ - for(int i = 0; i < 6; i++){ - // items.add(m_color, m_arrow_boxes[i]); - items.add(m_color, m_id_boxes[i]); - } -} - -void SandwichRecipeNumberDetector::detect_recipes(const ImageViewRGB32& screen, size_t recipe_IDs[6]) const{ - for(int i = 0; i < 6; i++){ - auto cropped_image = extract_box_reference(screen, m_id_boxes[i]); - - const bool invert_blackwhite = true; - ImageRGB32 filterd_image = to_blackwhite_rgb32_range( - cropped_image, - invert_blackwhite, - combine_rgb(180, 180, 180), combine_rgb(255, 255, 255) - ); - - // filterd_image.save("./tmp_fil_" + std::to_string(i) + ".png"); - - ImageRGB32 dilated_image(filterd_image.width(), filterd_image.height()); - - if (screen.width() >= 1280){ - const int dilation_type = cv::MORPH_ELLIPSE; - const int dilation_size = 1; - - cv::Mat element = cv::getStructuringElement(dilation_type, - cv::Size(2*dilation_size + 1, 2*dilation_size+1), - cv::Point(dilation_size, dilation_size)); - - // filterd_image.save("./tmp_" + std::to_string(i) + ".png"); - - cv::Mat filtered_image_mat(static_cast(filterd_image.height()), static_cast(filterd_image.width()), CV_8UC4, (void*)filterd_image.data(), filterd_image.bytes_per_row()); - - cv::Mat dilated_image_mat(static_cast(dilated_image.height()), static_cast(dilated_image.width()), CV_8UC4, (void*)dilated_image.data(), dilated_image.bytes_per_row()); - cv::dilate(filtered_image_mat, dilated_image_mat, element); - }else{ - dilated_image = filterd_image.copy(); - } - - // dilated_image.save("./tmp_dil_" + std::to_string(i) + ".png"); - - const int number = OCR::read_number(m_logger, dilated_image); - if (number <= 0 || number > 151){ - recipe_IDs[i] = 0; - }else{ - recipe_IDs[i] = number; - } - } - - // Fix any broken OCR reads: - for (int i = 1; i < 5; i++){ - if (recipe_IDs[i+1] > 0 && recipe_IDs[i-1] > 0 && recipe_IDs[i-1] + 2 == recipe_IDs[i+1]){ - if (recipe_IDs[i] != recipe_IDs[i-1] + 1){ - recipe_IDs[i] = recipe_IDs[i-1] + 1; - m_logger.log("Fix recipe number at cell " + std::to_string(i) + " to be " + std::to_string(recipe_IDs[i])); - } - } - } - if (recipe_IDs[1] == 2 && recipe_IDs[2] == 3){ - if (recipe_IDs[0] != 1){ - recipe_IDs[0] = 1; - m_logger.log("Fix recipe number at cell 0 to be 1"); - } - } -} - - -SandwichRecipeSelectionWatcher::SandwichRecipeSelectionWatcher(Color color) -: VisualInferenceCallback("SandwichRecipeSelectionWatcher"), m_arrow_watchers(6){ - for(int y = 0; y < 3; y++){ - for(int x = 0; x < 2; x++){ - ImageFloatBox box(x * 0.26 + 0.103, y * 0.275 + 0.074, 0.068, 0.085); - m_arrow_watchers.emplace_back(color, GradientArrowType::DOWN, box); - } - } -} - -void SandwichRecipeSelectionWatcher::make_overlays(VideoOverlaySet& items) const{ - for(int i = 0; i < 6; i++){ - m_arrow_watchers[i].make_overlays(items); - } -} - -bool SandwichRecipeSelectionWatcher::process_frame(const VideoSnapshot& frame){ - int num_arrows_found = 0; - for(int i = 0; i < 6; i++){ - const bool found_arrow = m_arrow_watchers[i].process_frame(frame); - if (found_arrow){ - m_selected_recipe = i; - num_arrows_found++; - } - } - return num_arrows_found == 1; -} - -bool SandwichRecipeSelectionWatcher::detect(const ImageViewRGB32& frame){ - int num_arrows_found = 0; - for(int i = 0; i < 6; i++){ - const bool found_arrow = m_arrow_watchers[i].detect(frame); - if (found_arrow){ - m_selected_recipe = i; - num_arrows_found++; - } - } - return num_arrows_found == 1; -} - -} -} -} +/* Sandwich Recipe Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV_SandwichRecipeDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ + +template class FixedLimitVector; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +SandwichRecipeNumberDetector::SandwichRecipeNumberDetector(Logger& logger, Color color): m_logger(logger), m_color(color){ + for(int y = 0; y < 3; y++){ + for(int x = 0; x < 2; x++){ + // m_arrow_boxes[y*2+x] = ImageFloatBox(x * 0.26 + 0.103, y * 0.275 + 0.074, 0.068, 0.085); + m_id_boxes[y*2+x] = ImageFloatBox(x * 0.26 + 0.015, y * 0.277 + 0.240, 0.042, 0.048); + } + } +} + +void SandwichRecipeNumberDetector::make_overlays(VideoOverlaySet& items) const{ + for(int i = 0; i < 6; i++){ + // items.add(m_color, m_arrow_boxes[i]); + items.add(m_color, m_id_boxes[i]); + } +} + +void SandwichRecipeNumberDetector::detect_recipes(const ImageViewRGB32& screen, size_t recipe_IDs[6]) const{ + for(int i = 0; i < 6; i++){ + auto cropped_image = extract_box_reference(screen, m_id_boxes[i]); + + const bool invert_blackwhite = true; + ImageRGB32 filterd_image = to_blackwhite_rgb32_range( + cropped_image, + invert_blackwhite, + combine_rgb(180, 180, 180), combine_rgb(255, 255, 255) + ); + + // filterd_image.save("./tmp_fil_" + std::to_string(i) + ".png"); + + ImageRGB32 dilated_image(filterd_image.width(), filterd_image.height()); + + if (screen.width() >= 1280){ + const int dilation_type = cv::MORPH_ELLIPSE; + const int dilation_size = 1; + + cv::Mat element = cv::getStructuringElement(dilation_type, + cv::Size(2*dilation_size + 1, 2*dilation_size+1), + cv::Point(dilation_size, dilation_size)); + + // filterd_image.save("./tmp_" + std::to_string(i) + ".png"); + + cv::Mat filtered_image_mat(static_cast(filterd_image.height()), static_cast(filterd_image.width()), CV_8UC4, (void*)filterd_image.data(), filterd_image.bytes_per_row()); + + cv::Mat dilated_image_mat(static_cast(dilated_image.height()), static_cast(dilated_image.width()), CV_8UC4, (void*)dilated_image.data(), dilated_image.bytes_per_row()); + cv::dilate(filtered_image_mat, dilated_image_mat, element); + }else{ + dilated_image = filterd_image.copy(); + } + + // dilated_image.save("./tmp_dil_" + std::to_string(i) + ".png"); + + const int number = OCR::read_number(m_logger, dilated_image); + if (number <= 0 || number > 151){ + recipe_IDs[i] = 0; + }else{ + recipe_IDs[i] = number; + } + } + + // Fix any broken OCR reads: + for (int i = 1; i < 5; i++){ + if (recipe_IDs[i+1] > 0 && recipe_IDs[i-1] > 0 && recipe_IDs[i-1] + 2 == recipe_IDs[i+1]){ + if (recipe_IDs[i] != recipe_IDs[i-1] + 1){ + recipe_IDs[i] = recipe_IDs[i-1] + 1; + m_logger.log("Fix recipe number at cell " + std::to_string(i) + " to be " + std::to_string(recipe_IDs[i])); + } + } + } + if (recipe_IDs[1] == 2 && recipe_IDs[2] == 3){ + if (recipe_IDs[0] != 1){ + recipe_IDs[0] = 1; + m_logger.log("Fix recipe number at cell 0 to be 1"); + } + } +} + + +SandwichRecipeSelectionWatcher::SandwichRecipeSelectionWatcher(Color color) +: VisualInferenceCallback("SandwichRecipeSelectionWatcher"), m_arrow_watchers(6){ + for(int y = 0; y < 3; y++){ + for(int x = 0; x < 2; x++){ + ImageFloatBox box(x * 0.26 + 0.103, y * 0.275 + 0.074, 0.068, 0.085); + m_arrow_watchers.emplace_back(color, GradientArrowType::DOWN, box); + } + } +} + +void SandwichRecipeSelectionWatcher::make_overlays(VideoOverlaySet& items) const{ + for(int i = 0; i < 6; i++){ + m_arrow_watchers[i].make_overlays(items); + } +} + +bool SandwichRecipeSelectionWatcher::process_frame(const VideoSnapshot& frame){ + int num_arrows_found = 0; + for(int i = 0; i < 6; i++){ + const bool found_arrow = m_arrow_watchers[i].process_frame(frame); + if (found_arrow){ + m_selected_recipe = i; + num_arrows_found++; + } + } + return num_arrows_found == 1; +} + +bool SandwichRecipeSelectionWatcher::detect(const ImageViewRGB32& frame){ + int num_arrows_found = 0; + for(int i = 0; i < 6; i++){ + const bool found_arrow = m_arrow_watchers[i].detect(frame); + if (found_arrow){ + m_selected_recipe = i; + num_arrows_found++; + } + } + return num_arrows_found == 1; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h index 759f4a692d..b960810291 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h @@ -1,78 +1,78 @@ -/* Sandwich Recipe Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichRecipeNumberDetector_H -#define PokemonAutomation_PokemonSV_SandwichRecipeNumberDetector_H - -#include "Common/Cpp/Color.h" -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Detect the sandwich recipe IDs -class SandwichRecipeNumberDetector{ -public: - SandwichRecipeNumberDetector(Logger& logger, Color color = COLOR_YELLOW); - - void make_overlays(VideoOverlaySet& items) const; - - // Detect the IDs of the displayed sandwich recipes. - // The order is from top to bottom, left to right: - // -------------------------------------- - // recipe_IDs[0] | recipe_IDs[1] - // recipe_IDs[2] | recipe_IDs[3] - // recipe_IDs[4] | recipe_IDs[5] - // -------------------------------------- - // recipe ID range: [1, 151] - // If there is no recipe at one cell, its value is 0. - // If a recipe has not enough ingredient to make (displayed as semi-transparent), it value is 0. - void detect_recipes(const ImageViewRGB32& screen, size_t recipe_IDs[6]) const; - -private: - Logger& m_logger; - Color m_color; - ImageFloatBox m_id_boxes[6]; -}; - -// Find which recipe cell is selected by the gradient arrow when choosing a sandwich recipe. -// Run `process_frame()` until it returns true, meaning arrow detected, then call `selected_recipe_cell()` -// to get the detected cell. -class SandwichRecipeSelectionWatcher : public VisualInferenceCallback{ -public: - SandwichRecipeSelectionWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - - // Whether it can detect the recipe selection on this frame. - // Unlike `process_frame()` which relies on consecutive frames to give robust result, - // this function uses only one frame. - bool detect(const ImageViewRGB32& frame); - - // Return which recipe cell is currented selected. - // For cell order, see `SandwichRecipeNumberDetector`. - // If no cell selection detected, return -1. - int selected_recipe_cell() const { return m_selected_recipe; } - -private: - FixedLimitVector m_arrow_watchers; - int m_selected_recipe = -1; -}; - - - - -} -} -} -#endif +/* Sandwich Recipe Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichRecipeNumberDetector_H +#define PokemonAutomation_PokemonSV_SandwichRecipeNumberDetector_H + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Detect the sandwich recipe IDs +class SandwichRecipeNumberDetector{ +public: + SandwichRecipeNumberDetector(Logger& logger, Color color = COLOR_YELLOW); + + void make_overlays(VideoOverlaySet& items) const; + + // Detect the IDs of the displayed sandwich recipes. + // The order is from top to bottom, left to right: + // -------------------------------------- + // recipe_IDs[0] | recipe_IDs[1] + // recipe_IDs[2] | recipe_IDs[3] + // recipe_IDs[4] | recipe_IDs[5] + // -------------------------------------- + // recipe ID range: [1, 151] + // If there is no recipe at one cell, its value is 0. + // If a recipe has not enough ingredient to make (displayed as semi-transparent), it value is 0. + void detect_recipes(const ImageViewRGB32& screen, size_t recipe_IDs[6]) const; + +private: + Logger& m_logger; + Color m_color; + ImageFloatBox m_id_boxes[6]; +}; + +// Find which recipe cell is selected by the gradient arrow when choosing a sandwich recipe. +// Run `process_frame()` until it returns true, meaning arrow detected, then call `selected_recipe_cell()` +// to get the detected cell. +class SandwichRecipeSelectionWatcher : public VisualInferenceCallback{ +public: + SandwichRecipeSelectionWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + + // Whether it can detect the recipe selection on this frame. + // Unlike `process_frame()` which relies on consecutive frames to give robust result, + // this function uses only one frame. + bool detect(const ImageViewRGB32& frame); + + // Return which recipe cell is currented selected. + // For cell order, see `SandwichRecipeNumberDetector`. + // If no cell selection detected, return -1. + int selected_recipe_cell() const { return m_selected_recipe; } + +private: + FixedLimitVector m_arrow_watchers; + int m_selected_recipe = -1; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.cpp index 55df95b4e0..5d84b40dd8 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.cpp @@ -1,42 +1,42 @@ -/* Auction Item Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "PokemonSV_AuctionItemNameReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -AuctionItemNameReader& AuctionItemNameReader::instance(){ - static AuctionItemNameReader reader; - return reader; -} - - -AuctionItemNameReader::AuctionItemNameReader() - : SmallDictionaryMatcher("PokemonSV/Auction/AuctionItemNameOCR.json") -{} - -OCR::StringMatchResult AuctionItemNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - - -} -} -} +/* Auction Item Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "PokemonSV_AuctionItemNameReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +AuctionItemNameReader& AuctionItemNameReader::instance(){ + static AuctionItemNameReader reader; + return reader; +} + + +AuctionItemNameReader::AuctionItemNameReader() + : SmallDictionaryMatcher("PokemonSV/Auction/AuctionItemNameOCR.json") +{} + +OCR::StringMatchResult AuctionItemNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h index 19db747d36..357556d914 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h @@ -1,41 +1,41 @@ -/* Auction Item Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AuctionItemNameReader_H -#define PokemonAutomation_PokemonSV_AuctionItemNameReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class AuctionItemNameReader : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - AuctionItemNameReader(); - - static AuctionItemNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -}; - - -} -} -} -#endif +/* Auction Item Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AuctionItemNameReader_H +#define PokemonAutomation_PokemonSV_AuctionItemNameReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class AuctionItemNameReader : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + AuctionItemNameReader(); + + static AuctionItemNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.cpp index 47c1a8e0aa..a2831f1966 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.cpp @@ -1,70 +1,70 @@ -/* Bag Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV_BagDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -BagDetector::BagDetector(Color color) - : m_color(color) - , m_top_blue_left(0.24, 0.09, 0.05, 0.05) - , m_top_blue_right(0.71, 0.09, 0.05, 0.05) - , m_bottom(0.03, 0.94, 0.40, 0.04) -{} -void BagDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_top_blue_left); - items.add(m_color, m_top_blue_right); - items.add(m_color, m_bottom); -} -bool BagDetector::detect(const ImageViewRGB32& screen){ - ImageStats top_blue_left = image_stats(extract_box_reference(screen, m_top_blue_left)); -// cout << top_blue_left.average << top_blue_left.stddev << endl; - if (!is_solid(top_blue_left, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ - return false; - } - - ImageStats top_blue_right = image_stats(extract_box_reference(screen, m_top_blue_right)); -// cout << top_blue_right.average << top_blue_right.stddev << endl; - if (!is_solid(top_blue_right, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ - return false; - } - - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; -#if 0 - if (bottom.stddev.sum() > 20){ - return false; - } -#else - if (!is_summary_color(bottom)){ - return false; - } -#endif - -// ImageStats shiny_symbol = image_stats(extract_box_reference(screen, m_shiny_symbol)); -// cout << shiny_symbol.average << shiny_symbol.stddev << endl; - - return true; -} - - - - - -} -} -} +/* Bag Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV_BagDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +BagDetector::BagDetector(Color color) + : m_color(color) + , m_top_blue_left(0.24, 0.09, 0.05, 0.05) + , m_top_blue_right(0.71, 0.09, 0.05, 0.05) + , m_bottom(0.03, 0.94, 0.40, 0.04) +{} +void BagDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_top_blue_left); + items.add(m_color, m_top_blue_right); + items.add(m_color, m_bottom); +} +bool BagDetector::detect(const ImageViewRGB32& screen){ + ImageStats top_blue_left = image_stats(extract_box_reference(screen, m_top_blue_left)); +// cout << top_blue_left.average << top_blue_left.stddev << endl; + if (!is_solid(top_blue_left, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ + return false; + } + + ImageStats top_blue_right = image_stats(extract_box_reference(screen, m_top_blue_right)); +// cout << top_blue_right.average << top_blue_right.stddev << endl; + if (!is_solid(top_blue_right, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ + return false; + } + + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; +#if 0 + if (bottom.stddev.sum() > 20){ + return false; + } +#else + if (!is_summary_color(bottom)){ + return false; + } +#endif + +// ImageStats shiny_symbol = image_stats(extract_box_reference(screen, m_shiny_symbol)); +// cout << shiny_symbol.average << shiny_symbol.stddev << endl; + + return true; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.h index 3b6085d4bf..22ad017a4a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BagDetector.h @@ -1,48 +1,48 @@ -/* Bag Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BagDetector_H -#define PokemonAutomation_PokemonSV_BagDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class BagDetector : public StaticScreenDetector{ -public: - BagDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - bool is_shiny(const ImageViewRGB32& screen) const; - - -protected: - Color m_color; - ImageFloatBox m_top_blue_left; - ImageFloatBox m_top_blue_right; - ImageFloatBox m_bottom; -}; -class BagWatcher : public DetectorToFinder{ -public: - BagWatcher(FinderType type, Color color = COLOR_RED) - : DetectorToFinder("PokemonSummaryWatcher", type, std::chrono::milliseconds(250), color) - {} -}; - - - -} -} -} -#endif +/* Bag Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BagDetector_H +#define PokemonAutomation_PokemonSV_BagDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class BagDetector : public StaticScreenDetector{ +public: + BagDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + bool is_shiny(const ImageViewRGB32& screen) const; + + +protected: + Color m_color; + ImageFloatBox m_top_blue_left; + ImageFloatBox m_top_blue_right; + ImageFloatBox m_bottom; +}; +class BagWatcher : public DetectorToFinder{ +public: + BagWatcher(FinderType type, Color color = COLOR_RED) + : DetectorToFinder("PokemonSummaryWatcher", type, std::chrono::milliseconds(250), color) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.cpp index 603c60bbe0..eb824e6ae5 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.cpp @@ -1,119 +1,119 @@ -/* Blueberry Quest Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h" -#include "PokemonSV_BlueberryQuestDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -//BlueberryQuestDetector::~BlueberryQuestDetector() = default; - -BlueberryQuestDetector::BlueberryQuestDetector(Logger& logger, Color color, Language language, QuestPosition position) - : m_logger(logger), m_color(color), m_language(language), m_position(position) -{ - switch(position){ - case QuestPosition::FIRST: - m_box = ImageFloatBox(0.604, 0.218, 0.282, 0.095); - break; - case QuestPosition::SECOND: - m_box = ImageFloatBox(0.604, 0.395, 0.282, 0.095); - break; - case QuestPosition::THIRD: - m_box = ImageFloatBox(0.604, 0.572, 0.282, 0.095); - break; - case QuestPosition::FOURTH: - m_box = ImageFloatBox(0.604, 0.749, 0.282, 0.095); - break; - } -} - -void BlueberryQuestDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -bool BlueberryQuestDetector::detect(const ImageViewRGB32& screen){ - return !detect_quest(screen).empty(); -} - -std::string BlueberryQuestDetector::detect_quest(const ImageViewRGB32& screen) const{ - std::multimap results; - - ImageRGB32 quest_label = to_blackwhite_rgb32_range( - extract_box_reference(screen, m_box), - true, - combine_rgb(198, 198, 198), combine_rgb(255, 255, 255) - ); - - //quest_label.save("quest_label.png"); - - OCR::StringMatchResult ocr_result = PokemonSV::BlueberryQuestReader::instance().read_substring( - m_logger, m_language, quest_label, - OCR::BLACK_TEXT_FILTERS() - ); - ocr_result.clear_beyond_log10p(BlueberryQuestReader::MAX_LOG10P); - ocr_result.clear_beyond_spread(BlueberryQuestReader::MAX_LOG10P_SPREAD); - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - - } - - if (results.empty()){ - return ""; - } - - if (results.size() > 1){ - throw_and_log( - m_logger, ErrorReport::SEND_ERROR_REPORT, - "BlueberryQuestDetector::detect_quest(): Unable to read selected item. Ambiguous or multiple results." - ); - } - - return results.begin()->second.token; -} - - - -BlueberryQuestWatcher::~BlueberryQuestWatcher() = default; - -BlueberryQuestWatcher::BlueberryQuestWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, BlueberryQuestDetector::QuestPosition position) - : VisualInferenceCallback("BlueberryQuestWatcher") - , m_overlay(overlay) - , m_detector(logger, color, language, position) -{} - -void BlueberryQuestWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} - -bool BlueberryQuestWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - m_quest_name = m_detector.detect_quest(screen); - if (m_quest_name.empty()){ - return false; - } - - return true; -} - - - - - - - - -} -} -} +/* Blueberry Quest Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h" +#include "PokemonSV_BlueberryQuestDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +//BlueberryQuestDetector::~BlueberryQuestDetector() = default; + +BlueberryQuestDetector::BlueberryQuestDetector(Logger& logger, Color color, Language language, QuestPosition position) + : m_logger(logger), m_color(color), m_language(language), m_position(position) +{ + switch(position){ + case QuestPosition::FIRST: + m_box = ImageFloatBox(0.604, 0.218, 0.282, 0.095); + break; + case QuestPosition::SECOND: + m_box = ImageFloatBox(0.604, 0.395, 0.282, 0.095); + break; + case QuestPosition::THIRD: + m_box = ImageFloatBox(0.604, 0.572, 0.282, 0.095); + break; + case QuestPosition::FOURTH: + m_box = ImageFloatBox(0.604, 0.749, 0.282, 0.095); + break; + } +} + +void BlueberryQuestDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +bool BlueberryQuestDetector::detect(const ImageViewRGB32& screen){ + return !detect_quest(screen).empty(); +} + +std::string BlueberryQuestDetector::detect_quest(const ImageViewRGB32& screen) const{ + std::multimap results; + + ImageRGB32 quest_label = to_blackwhite_rgb32_range( + extract_box_reference(screen, m_box), + true, + combine_rgb(198, 198, 198), combine_rgb(255, 255, 255) + ); + + //quest_label.save("quest_label.png"); + + OCR::StringMatchResult ocr_result = PokemonSV::BlueberryQuestReader::instance().read_substring( + m_logger, m_language, quest_label, + OCR::BLACK_TEXT_FILTERS() + ); + ocr_result.clear_beyond_log10p(BlueberryQuestReader::MAX_LOG10P); + ocr_result.clear_beyond_spread(BlueberryQuestReader::MAX_LOG10P_SPREAD); + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + + } + + if (results.empty()){ + return ""; + } + + if (results.size() > 1){ + throw_and_log( + m_logger, ErrorReport::SEND_ERROR_REPORT, + "BlueberryQuestDetector::detect_quest(): Unable to read selected item. Ambiguous or multiple results." + ); + } + + return results.begin()->second.token; +} + + + +BlueberryQuestWatcher::~BlueberryQuestWatcher() = default; + +BlueberryQuestWatcher::BlueberryQuestWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, BlueberryQuestDetector::QuestPosition position) + : VisualInferenceCallback("BlueberryQuestWatcher") + , m_overlay(overlay) + , m_detector(logger, color, language, position) +{} + +void BlueberryQuestWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} + +bool BlueberryQuestWatcher::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + m_quest_name = m_detector.detect_quest(screen); + if (m_quest_name.empty()){ + return false; + } + + return true; +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h index 35d7022872..d0ac979af9 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h @@ -1,83 +1,83 @@ -/* Blueberry Quest Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BlueberryQuestDetector_H -#define PokemonAutomation_PokemonSV_BlueberryQuestDetector_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Language.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - -class VideoOverlaySet; -class VideoOverlay; -class OverlayBoxScope; - -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Detect the quest in a given position (four positions before having to scroll) -class BlueberryQuestDetector : public StaticScreenDetector{ -public: - //Max quests: 4 in singleplayer (1 red, 3 blue). 17 in multiplayer (with 4 players: 1 gold, 4 red, 12 blue). - //For multiplayer, never read other player's quests. So 1 gold, 4 red, 3 blue. - //Only 4 quests are visible at a time. Need to scroll down. - enum class QuestPosition{ - FIRST, - SECOND, - THIRD, - FOURTH - }; - BlueberryQuestDetector(Logger& logger, Color color, Language language, QuestPosition position); -// virtual ~BlueberryQuestDetector(); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Return detected quest slug. Return empty string if not detected - std::string detect_quest(const ImageViewRGB32& screen) const; - -protected: - Logger& m_logger; - Color m_color; - Language m_language; - QuestPosition m_position; - ImageFloatBox m_box; -}; - - -// Detect the quest in a given position (four positions before having to scroll) -class BlueberryQuestWatcher : public VisualInferenceCallback{ -public: - using Side = BlueberryQuestDetector::QuestPosition; - ~BlueberryQuestWatcher(); - BlueberryQuestWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, BlueberryQuestDetector::QuestPosition position); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - const std::string& quest_name() const { return m_quest_name; } - - -protected: - VideoOverlay& m_overlay; - BlueberryQuestDetector m_detector; - std::string m_quest_name; -}; - - - - -} -} -} -#endif +/* Blueberry Quest Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BlueberryQuestDetector_H +#define PokemonAutomation_PokemonSV_BlueberryQuestDetector_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Language.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + +class VideoOverlaySet; +class VideoOverlay; +class OverlayBoxScope; + +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Detect the quest in a given position (four positions before having to scroll) +class BlueberryQuestDetector : public StaticScreenDetector{ +public: + //Max quests: 4 in singleplayer (1 red, 3 blue). 17 in multiplayer (with 4 players: 1 gold, 4 red, 12 blue). + //For multiplayer, never read other player's quests. So 1 gold, 4 red, 3 blue. + //Only 4 quests are visible at a time. Need to scroll down. + enum class QuestPosition{ + FIRST, + SECOND, + THIRD, + FOURTH + }; + BlueberryQuestDetector(Logger& logger, Color color, Language language, QuestPosition position); +// virtual ~BlueberryQuestDetector(); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Return detected quest slug. Return empty string if not detected + std::string detect_quest(const ImageViewRGB32& screen) const; + +protected: + Logger& m_logger; + Color m_color; + Language m_language; + QuestPosition m_position; + ImageFloatBox m_box; +}; + + +// Detect the quest in a given position (four positions before having to scroll) +class BlueberryQuestWatcher : public VisualInferenceCallback{ +public: + using Side = BlueberryQuestDetector::QuestPosition; + ~BlueberryQuestWatcher(); + BlueberryQuestWatcher(Logger& logger, Color color, VideoOverlay& overlay, Language language, BlueberryQuestDetector::QuestPosition position); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + const std::string& quest_name() const { return m_quest_name; } + + +protected: + VideoOverlay& m_overlay; + BlueberryQuestDetector m_detector; + std::string m_quest_name; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.cpp index aa6b0dacc2..1c04daf200 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.cpp @@ -1,40 +1,40 @@ -/* Blueberry Quest Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_BlueberryQuestReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -BlueberryQuestReader& BlueberryQuestReader::instance(){ - static BlueberryQuestReader reader; - return reader; -} - -BlueberryQuestReader::BlueberryQuestReader() - : SmallDictionaryMatcher("PokemonSV/BlueberryQuestsOCR.json") -{} - -OCR::StringMatchResult BlueberryQuestReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - - -} -} -} +/* Blueberry Quest Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_BlueberryQuestReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +BlueberryQuestReader& BlueberryQuestReader::instance(){ + static BlueberryQuestReader reader; + return reader; +} + +BlueberryQuestReader::BlueberryQuestReader() + : SmallDictionaryMatcher("PokemonSV/BlueberryQuestsOCR.json") +{} + +OCR::StringMatchResult BlueberryQuestReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h index 2b86718345..78ab016fdc 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_BlueberryQuestReader.h @@ -1,41 +1,41 @@ -/* Blueberry Quest Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BlueberryQuestReader_H -#define PokemonAutomation_PokemonSV_BlueberryQuestReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class BlueberryQuestReader : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - BlueberryQuestReader(); - - static BlueberryQuestReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -}; - - -} -} -} -#endif +/* Blueberry Quest Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BlueberryQuestReader_H +#define PokemonAutomation_PokemonSV_BlueberryQuestReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class BlueberryQuestReader : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + BlueberryQuestReader(); + + static BlueberryQuestReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.cpp index 1be66a13be..97d3e1e6e4 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.cpp @@ -1,35 +1,35 @@ -/* Clothing Top Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Tools/ErrorDumper.h" -#include "PokemonSV_ClothingTopDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -//This detects that the gradient arrow is in the top slot of a clothing store menu -ClothingTopDetector::ClothingTopDetector(Color color) - : m_arrow(color, GradientArrowType::RIGHT, { 0.009, 0.158, 0.061, 0.153 }) -{} -void ClothingTopDetector::make_overlays(VideoOverlaySet& items) const{ - m_arrow.make_overlays(items); -} -bool ClothingTopDetector::detect(const ImageViewRGB32& screen){ - if (!m_arrow.detect(screen)){ - return false; - } - return true; -} - - -} -} -} +/* Clothing Top Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Tools/ErrorDumper.h" +#include "PokemonSV_ClothingTopDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +//This detects that the gradient arrow is in the top slot of a clothing store menu +ClothingTopDetector::ClothingTopDetector(Color color) + : m_arrow(color, GradientArrowType::RIGHT, { 0.009, 0.158, 0.061, 0.153 }) +{} +void ClothingTopDetector::make_overlays(VideoOverlaySet& items) const{ + m_arrow.make_overlays(items); +} +bool ClothingTopDetector::detect(const ImageViewRGB32& screen){ + if (!m_arrow.detect(screen)){ + return false; + } + return true; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.h index dea81ed804..4f3ea0f9ee 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ClothingTopDetector.h @@ -1,42 +1,42 @@ -/* Clothing Top Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ClothingTop_H -#define PokemonAutomation_PokemonSV_ClothingTop_H - -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class ClothingTopDetector : public StaticScreenDetector{ -public: - ClothingTopDetector(Color color); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - GradientArrowDetector m_arrow; -}; -class ClothingTopWatcher : public DetectorToFinder{ -public: - ClothingTopWatcher(Color color) - : DetectorToFinder("ClothingTopWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - - -} -} -} -#endif +/* Clothing Top Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ClothingTop_H +#define PokemonAutomation_PokemonSV_ClothingTop_H + +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class ClothingTopDetector : public StaticScreenDetector{ +public: + ClothingTopDetector(Color color); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + GradientArrowDetector m_arrow; +}; +class ClothingTopWatcher : public DetectorToFinder{ +public: + ClothingTopWatcher(Color color) + : DetectorToFinder("ClothingTopWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.cpp index 32422d08a1..0139bcd60f 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.cpp @@ -1,130 +1,130 @@ -/* ESP Emotion Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_ESPEmotionDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -ESPEmotionReader::ESPEmotionReader() - : m_symbol_box(0.297, 0.137, 0.010, 0.016) -{} - -void ESPEmotionReader::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_symbol_box); -} -Detection ESPEmotionReader::detect(const ImageViewRGB32& screen) const{ - ImageViewRGB32 symbol = extract_box_reference(screen, m_symbol_box); - - //Color ratio: R/(R+G+B), G/(R+G+B), B/(R+G+B) - if (is_solid(symbol, { 0.567, 0.2, 0.232 }, 0.2, 40)){ - return Detection::RED; - } - if (is_solid(symbol, { 0.529, 0.447, 0.0258 }, 0.2, 40)){ - return Detection::YELLOW; - } - if (is_solid(symbol, { 0.132, 0.332, 0.536 }, 0.2, 40)){ - return Detection::BLUE; //Sometimes picks up the grey as well but that works - } - if (is_solid(symbol, { 0.323, 0.491, 0.184 }, 0.2, 40)){ - return Detection::GREEN; - } - if (is_solid(symbol, { 0.219, 0.355, 0.426 }, 0.2, 40)){ - return Detection::GREY; - } - return Detection::NO_DETECTION; -} - -ESPEmotionDetector::ESPEmotionDetector() - : VisualInferenceCallback("ESPEmotionDetector") - , m_last(Detection::NO_DETECTION) -{} - -void ESPEmotionDetector::make_overlays(VideoOverlaySet& items) const{ - m_reader.make_overlays(items); -} -bool ESPEmotionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - Detection result = m_reader.detect(frame); - m_last.store(result, std::memory_order_release); - return result != Detection::NO_DETECTION; -} - -ESPStartDetector::ESPStartDetector() - : VisualInferenceCallback("ESPStartDetector") - , m_left_box(0.337, 0.144, 0.007, 0.064) - , m_right_box(0.716, 0.140, 0.008, 0.069) -{} -void ESPStartDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool ESPStartDetector::detect(const ImageViewRGB32& frame){ - ImageViewRGB32 left_image = extract_box_reference(frame, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(frame, m_right_box); - if (is_solid(left_image, { 0.332, 0.335, 0.332 }) && is_solid(right_image, { 0.332, 0.335, 0.332 })){ - return true; - } - return false; -} -bool ESPStartDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -ESPShowNewEmotionDetector::ESPShowNewEmotionDetector() - : VisualInferenceCallback("ESPShowNewEmotionDetector") - , m_left_box(0.337, 0.144, 0.007, 0.064) - , m_right_box(0.716, 0.140, 0.008, 0.069) -{} -void ESPShowNewEmotionDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); -} -bool ESPShowNewEmotionDetector::detect(const ImageViewRGB32& frame){ - ImageViewRGB32 left_image = extract_box_reference(frame, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(frame, m_right_box); - if (is_solid(left_image, { 0.332, 0.335, 0.332 }) && is_solid(right_image, { 0.332, 0.335, 0.332 })){ - return false; - } - return true; -} -bool ESPShowNewEmotionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -ESPPressedEmotionDetector::ESPPressedEmotionDetector() - : VisualInferenceCallback("ESPPressedEmotionDetector") - , m_left_box(0.851, 0.753, 0.015, 0.026) - , m_right_box(0.943, 0.850, 0.021, 0.022) - , m_top_box(0.874, 0.712, 0.014, 0.035) - , m_bottom_box(0.924, 0.884, 0.016, 0.027) -{} -void ESPPressedEmotionDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left_box); - items.add(COLOR_RED, m_right_box); - items.add(COLOR_RED, m_top_box); - items.add(COLOR_RED, m_bottom_box); -} -bool ESPPressedEmotionDetector::detect(const ImageViewRGB32& frame){ - ImageViewRGB32 left_image = extract_box_reference(frame, m_left_box); - ImageViewRGB32 right_image = extract_box_reference(frame, m_right_box); - ImageViewRGB32 top_image = extract_box_reference(frame, m_top_box); - ImageViewRGB32 bottom_image = extract_box_reference(frame, m_bottom_box); - if (is_solid(left_image, { 0.506, 0.439, 0.054 }, 0.2, 15) || is_solid(right_image, { 0.506, 0.439, 0.054 }, 0.2, 15) - || is_solid(top_image, { 0.506, 0.439, 0.054 }, 0.2, 15) || is_solid(bottom_image, { 0.506, 0.439, 0.054 }, 0.2, 15)){ - return true; - } - return false; -} -bool ESPPressedEmotionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -} -} -} +/* ESP Emotion Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_ESPEmotionDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +ESPEmotionReader::ESPEmotionReader() + : m_symbol_box(0.297, 0.137, 0.010, 0.016) +{} + +void ESPEmotionReader::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_symbol_box); +} +Detection ESPEmotionReader::detect(const ImageViewRGB32& screen) const{ + ImageViewRGB32 symbol = extract_box_reference(screen, m_symbol_box); + + //Color ratio: R/(R+G+B), G/(R+G+B), B/(R+G+B) + if (is_solid(symbol, { 0.567, 0.2, 0.232 }, 0.2, 40)){ + return Detection::RED; + } + if (is_solid(symbol, { 0.529, 0.447, 0.0258 }, 0.2, 40)){ + return Detection::YELLOW; + } + if (is_solid(symbol, { 0.132, 0.332, 0.536 }, 0.2, 40)){ + return Detection::BLUE; //Sometimes picks up the grey as well but that works + } + if (is_solid(symbol, { 0.323, 0.491, 0.184 }, 0.2, 40)){ + return Detection::GREEN; + } + if (is_solid(symbol, { 0.219, 0.355, 0.426 }, 0.2, 40)){ + return Detection::GREY; + } + return Detection::NO_DETECTION; +} + +ESPEmotionDetector::ESPEmotionDetector() + : VisualInferenceCallback("ESPEmotionDetector") + , m_last(Detection::NO_DETECTION) +{} + +void ESPEmotionDetector::make_overlays(VideoOverlaySet& items) const{ + m_reader.make_overlays(items); +} +bool ESPEmotionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + Detection result = m_reader.detect(frame); + m_last.store(result, std::memory_order_release); + return result != Detection::NO_DETECTION; +} + +ESPStartDetector::ESPStartDetector() + : VisualInferenceCallback("ESPStartDetector") + , m_left_box(0.337, 0.144, 0.007, 0.064) + , m_right_box(0.716, 0.140, 0.008, 0.069) +{} +void ESPStartDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool ESPStartDetector::detect(const ImageViewRGB32& frame){ + ImageViewRGB32 left_image = extract_box_reference(frame, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(frame, m_right_box); + if (is_solid(left_image, { 0.332, 0.335, 0.332 }) && is_solid(right_image, { 0.332, 0.335, 0.332 })){ + return true; + } + return false; +} +bool ESPStartDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +ESPShowNewEmotionDetector::ESPShowNewEmotionDetector() + : VisualInferenceCallback("ESPShowNewEmotionDetector") + , m_left_box(0.337, 0.144, 0.007, 0.064) + , m_right_box(0.716, 0.140, 0.008, 0.069) +{} +void ESPShowNewEmotionDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); +} +bool ESPShowNewEmotionDetector::detect(const ImageViewRGB32& frame){ + ImageViewRGB32 left_image = extract_box_reference(frame, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(frame, m_right_box); + if (is_solid(left_image, { 0.332, 0.335, 0.332 }) && is_solid(right_image, { 0.332, 0.335, 0.332 })){ + return false; + } + return true; +} +bool ESPShowNewEmotionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +ESPPressedEmotionDetector::ESPPressedEmotionDetector() + : VisualInferenceCallback("ESPPressedEmotionDetector") + , m_left_box(0.851, 0.753, 0.015, 0.026) + , m_right_box(0.943, 0.850, 0.021, 0.022) + , m_top_box(0.874, 0.712, 0.014, 0.035) + , m_bottom_box(0.924, 0.884, 0.016, 0.027) +{} +void ESPPressedEmotionDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left_box); + items.add(COLOR_RED, m_right_box); + items.add(COLOR_RED, m_top_box); + items.add(COLOR_RED, m_bottom_box); +} +bool ESPPressedEmotionDetector::detect(const ImageViewRGB32& frame){ + ImageViewRGB32 left_image = extract_box_reference(frame, m_left_box); + ImageViewRGB32 right_image = extract_box_reference(frame, m_right_box); + ImageViewRGB32 top_image = extract_box_reference(frame, m_top_box); + ImageViewRGB32 bottom_image = extract_box_reference(frame, m_bottom_box); + if (is_solid(left_image, { 0.506, 0.439, 0.054 }, 0.2, 15) || is_solid(right_image, { 0.506, 0.439, 0.054 }, 0.2, 15) + || is_solid(top_image, { 0.506, 0.439, 0.054 }, 0.2, 15) || is_solid(bottom_image, { 0.506, 0.439, 0.054 }, 0.2, 15)){ + return true; + } + return false; +} +bool ESPPressedEmotionDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h index 6493b94bfb..7f15f7c62c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h @@ -1,109 +1,109 @@ -/* ESP Emotion Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ESPEmotionDetector_H -#define PokemonAutomation_PokemonSV_ESPEmotionDetector_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - class CancellableScope; - class VideoFeed; -namespace NintendoSwitch{ -namespace PokemonSV{ - -enum class Detection{ - NO_DETECTION, - RED, - YELLOW, - BLUE, - GREEN, - GREY, -}; -class ESPEmotionReader{ -public: - ESPEmotionReader(); - - void make_overlays(VideoOverlaySet& items) const; - Detection detect(const ImageViewRGB32& screen) const; - -private: - ImageFloatBox m_symbol_box; -}; - -class ESPEmotionDetector : public VisualInferenceCallback{ -public: - ESPEmotionDetector(); - - Detection result() const{ - return m_last.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ESPEmotionReader m_reader; - std::atomic m_last; -}; - -//This checks for the Dendra's dialog box -class ESPStartDetector : public VisualInferenceCallback{ -public: - ESPStartDetector(); - - bool detect(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; - -// This checks that Dendra's box vanished to shout the next emotion -class ESPShowNewEmotionDetector : public VisualInferenceCallback{ -public: - ESPShowNewEmotionDetector(); - - bool detect(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; -}; - -// Check that an emotion is pressed by looking for yellow in the lower right interface -class ESPPressedEmotionDetector : public VisualInferenceCallback{ -public: - ESPPressedEmotionDetector(); - - bool detect(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_left_box; - ImageFloatBox m_right_box; - ImageFloatBox m_top_box; - ImageFloatBox m_bottom_box; -}; - - -} -} -} - -#endif +/* ESP Emotion Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ESPEmotionDetector_H +#define PokemonAutomation_PokemonSV_ESPEmotionDetector_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + class CancellableScope; + class VideoFeed; +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class Detection{ + NO_DETECTION, + RED, + YELLOW, + BLUE, + GREEN, + GREY, +}; +class ESPEmotionReader{ +public: + ESPEmotionReader(); + + void make_overlays(VideoOverlaySet& items) const; + Detection detect(const ImageViewRGB32& screen) const; + +private: + ImageFloatBox m_symbol_box; +}; + +class ESPEmotionDetector : public VisualInferenceCallback{ +public: + ESPEmotionDetector(); + + Detection result() const{ + return m_last.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ESPEmotionReader m_reader; + std::atomic m_last; +}; + +//This checks for the Dendra's dialog box +class ESPStartDetector : public VisualInferenceCallback{ +public: + ESPStartDetector(); + + bool detect(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; + +// This checks that Dendra's box vanished to shout the next emotion +class ESPShowNewEmotionDetector : public VisualInferenceCallback{ +public: + ESPShowNewEmotionDetector(); + + bool detect(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; +}; + +// Check that an emotion is pressed by looking for yellow in the lower right interface +class ESPPressedEmotionDetector : public VisualInferenceCallback{ +public: + ESPPressedEmotionDetector(); + + bool detect(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_left_box; + ImageFloatBox m_right_box; + ImageFloatBox m_top_box; + ImageFloatBox m_bottom_box; +}; + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.cpp index 760dd4eed0..db9e278109 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.cpp @@ -1,211 +1,211 @@ -/* Main Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_MainMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -MainMenuDetector::MainMenuDetector(Color color) - : m_color(color) - , m_bottom(0.10, 0.94, 0.40, 0.05) - , m_arrow_left(color, GradientArrowType::RIGHT, {0.02, 0.10, 0.05, 0.90}) - , m_arrow_right(color, GradientArrowType::RIGHT, {0.67, 0.20, 0.05, 0.50}) - , m_dlc_icon(color, GradientArrowType::RIGHT, {0.67, 0.76, 0.05, 0.10}) -{} -void MainMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - m_arrow_left.make_overlays(items); - m_arrow_right.make_overlays(items); - m_dlc_icon.make_overlays(items); -} -bool MainMenuDetector::detect(const ImageViewRGB32& screen){ - // Disambiguate against the Poke Portal. - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; - if (is_solid(bottom, {0.582218, 0.417782, 0.})){ - return false; - } - - // Check the arrows. - if (m_arrow_left.detect(screen)){ - return true; - } - if (m_arrow_right.detect(screen)){ - return true; - } - if (m_dlc_icon.detect(screen)){ - return true; - } - - return false; -} - -std::pair MainMenuDetector::detect_location(const ImageViewRGB32& screen){ - // Disambiguate against the Poke Portal. - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); - if (is_solid(bottom, {0.582218, 0.417782, 0.})){ - return {MenuSide::NONE, 0}; - } - - // Check the arrows. - ImageFloatBox box; - if (m_arrow_left.detect(box, screen)){ - if (box.y > 0.85){ - return {MenuSide::LEFT, 6}; - } - int slot = (int)((box.y - 0.172222) / 0.116482 + 0.5); - if (slot < 0){ - return {MenuSide::NONE, 0}; - } - return {MenuSide::LEFT, slot}; - } - if (m_arrow_right.detect(box, screen)){ -// cout << box.y << endl; - int slot = (int)((box.y - 0.227778) / 0.074074 + 0.5); - if (slot < 0){ - return {MenuSide::NONE, 0}; - } - return {MenuSide::RIGHT, slot}; - } - if (m_dlc_icon.detect(screen)){ - return {MenuSide::RIGHT, 6}; - } - - return {MenuSide::NONE, 0}; -} - - -bool MainMenuDetector::move_cursor( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - MenuSide side, int row, bool fast -){ - if (side == MenuSide::NONE){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "MainMenuDetector::move_cursor() called with MenuSide::NONE." - ); - } - - size_t consecutive_detection_fails = 0; - size_t moves = 0; - bool target_reached = false; - while (true){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - std::pair current = this->detect_location(screen); - - { - std::string text = "Current Location: "; - switch (current.first){ - case MenuSide::NONE: - text += "?"; - break; - case MenuSide::LEFT: - text += "Left"; - break; - case MenuSide::RIGHT: - text += "Right"; - break; - } - text += " " + std::to_string(current.second); - stream.log(text); - } - - // Failed to detect menu. - if (current.first == MenuSide::NONE){ - consecutive_detection_fails++; - if (consecutive_detection_fails > 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MainMenuDetector::move_cursor(): Unable to detect menu.", - stream, - screen - ); - } - context.wait_for(std::chrono::milliseconds(50)); - continue; - } - consecutive_detection_fails = 0; - - if (moves >= 20){ - stream.log("Unable to move to target after 20 moves.", COLOR_RED); - return false; - } - - // We're done! - if (current.first == side && current.second == row){ - if (target_reached || fast){ - return true; - }else{ - // Don't return yet. Wait a second to make sure the video is - // in steady state before we return. - target_reached = true; - context.wait_for(std::chrono::seconds(1)); - continue; - } - } - target_reached = false; - - moves++; - - // Wrong side. - if (current.first != side){ - if (current.first == MenuSide::LEFT){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 10); - }else{ - pbf_press_dpad(context, DPAD_LEFT, 20, 10); - } - continue; - } - - int rows = side == MenuSide::LEFT ? 7 : 6; - -// cout << "current = " << current.second << endl; -// cout << "target = " << row << endl; - - int diff = (rows + current.second - row) % rows; -// cout << "diff = " << diff << endl; - if (diff < 4){ - if (fast){ - for (int c = 0; c < diff - 1; c++){ - pbf_press_dpad(context, DPAD_UP, 10, 10); - } - } - pbf_press_dpad(context, DPAD_UP, 20, 10); - }else{ - if (fast){ - diff = rows - diff; - for (int c = 0; c < diff - 1; c++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - } - } - pbf_press_dpad(context, DPAD_DOWN, 20, 10); - } - } -} - - - - - - - -} -} -} +/* Main Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_MainMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +MainMenuDetector::MainMenuDetector(Color color) + : m_color(color) + , m_bottom(0.10, 0.94, 0.40, 0.05) + , m_arrow_left(color, GradientArrowType::RIGHT, {0.02, 0.10, 0.05, 0.90}) + , m_arrow_right(color, GradientArrowType::RIGHT, {0.67, 0.20, 0.05, 0.50}) + , m_dlc_icon(color, GradientArrowType::RIGHT, {0.67, 0.76, 0.05, 0.10}) +{} +void MainMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + m_arrow_left.make_overlays(items); + m_arrow_right.make_overlays(items); + m_dlc_icon.make_overlays(items); +} +bool MainMenuDetector::detect(const ImageViewRGB32& screen){ + // Disambiguate against the Poke Portal. + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; + if (is_solid(bottom, {0.582218, 0.417782, 0.})){ + return false; + } + + // Check the arrows. + if (m_arrow_left.detect(screen)){ + return true; + } + if (m_arrow_right.detect(screen)){ + return true; + } + if (m_dlc_icon.detect(screen)){ + return true; + } + + return false; +} + +std::pair MainMenuDetector::detect_location(const ImageViewRGB32& screen){ + // Disambiguate against the Poke Portal. + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); + if (is_solid(bottom, {0.582218, 0.417782, 0.})){ + return {MenuSide::NONE, 0}; + } + + // Check the arrows. + ImageFloatBox box; + if (m_arrow_left.detect(box, screen)){ + if (box.y > 0.85){ + return {MenuSide::LEFT, 6}; + } + int slot = (int)((box.y - 0.172222) / 0.116482 + 0.5); + if (slot < 0){ + return {MenuSide::NONE, 0}; + } + return {MenuSide::LEFT, slot}; + } + if (m_arrow_right.detect(box, screen)){ +// cout << box.y << endl; + int slot = (int)((box.y - 0.227778) / 0.074074 + 0.5); + if (slot < 0){ + return {MenuSide::NONE, 0}; + } + return {MenuSide::RIGHT, slot}; + } + if (m_dlc_icon.detect(screen)){ + return {MenuSide::RIGHT, 6}; + } + + return {MenuSide::NONE, 0}; +} + + +bool MainMenuDetector::move_cursor( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + MenuSide side, int row, bool fast +){ + if (side == MenuSide::NONE){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "MainMenuDetector::move_cursor() called with MenuSide::NONE." + ); + } + + size_t consecutive_detection_fails = 0; + size_t moves = 0; + bool target_reached = false; + while (true){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + std::pair current = this->detect_location(screen); + + { + std::string text = "Current Location: "; + switch (current.first){ + case MenuSide::NONE: + text += "?"; + break; + case MenuSide::LEFT: + text += "Left"; + break; + case MenuSide::RIGHT: + text += "Right"; + break; + } + text += " " + std::to_string(current.second); + stream.log(text); + } + + // Failed to detect menu. + if (current.first == MenuSide::NONE){ + consecutive_detection_fails++; + if (consecutive_detection_fails > 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MainMenuDetector::move_cursor(): Unable to detect menu.", + stream, + screen + ); + } + context.wait_for(std::chrono::milliseconds(50)); + continue; + } + consecutive_detection_fails = 0; + + if (moves >= 20){ + stream.log("Unable to move to target after 20 moves.", COLOR_RED); + return false; + } + + // We're done! + if (current.first == side && current.second == row){ + if (target_reached || fast){ + return true; + }else{ + // Don't return yet. Wait a second to make sure the video is + // in steady state before we return. + target_reached = true; + context.wait_for(std::chrono::seconds(1)); + continue; + } + } + target_reached = false; + + moves++; + + // Wrong side. + if (current.first != side){ + if (current.first == MenuSide::LEFT){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 10); + }else{ + pbf_press_dpad(context, DPAD_LEFT, 20, 10); + } + continue; + } + + int rows = side == MenuSide::LEFT ? 7 : 6; + +// cout << "current = " << current.second << endl; +// cout << "target = " << row << endl; + + int diff = (rows + current.second - row) % rows; +// cout << "diff = " << diff << endl; + if (diff < 4){ + if (fast){ + for (int c = 0; c < diff - 1; c++){ + pbf_press_dpad(context, DPAD_UP, 10, 10); + } + } + pbf_press_dpad(context, DPAD_UP, 20, 10); + }else{ + if (fast){ + diff = rows - diff; + for (int c = 0; c < diff - 1; c++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + } + } + pbf_press_dpad(context, DPAD_DOWN, 20, 10); + } + } +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.h index 8eb5bcdfb1..c2db3253fe 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MainMenuDetector.h @@ -1,78 +1,78 @@ -/* Main Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MainMenuDetector_H -#define PokemonAutomation_PokemonSV_MainMenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class MenuSide{ - NONE, - LEFT, - RIGHT, -}; - - -// Detect the menu where your party is on the right while your main menu is on -// the right. -class MainMenuDetector : public StaticScreenDetector{ -public: - MainMenuDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Read where the cursor is. - // The 2nd return value is the index. 0 is the top row. 6 is only valid on - // the left side and is Koraidon/Miraidon. - std::pair detect_location(const ImageViewRGB32& screen); - - // While sitting on the menu, move the cursor to the desired slot. - // Returns true if success. - // If (fast = true) it will be faster, but may be unreliable. It may not - // actually land on the desired slot if the capture card is slow. - bool move_cursor( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - MenuSide side, int row, bool fast = false - ); - - -protected: - Color m_color; - ImageFloatBox m_bottom; - GradientArrowDetector m_arrow_left; - GradientArrowDetector m_arrow_right; - GradientArrowDetector m_dlc_icon; -}; -class MainMenuWatcher : public DetectorToFinder{ -public: - MainMenuWatcher(Color color = COLOR_RED) - : DetectorToFinder("MainMenuWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - - - -} -} -} -#endif +/* Main Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MainMenuDetector_H +#define PokemonAutomation_PokemonSV_MainMenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class MenuSide{ + NONE, + LEFT, + RIGHT, +}; + + +// Detect the menu where your party is on the right while your main menu is on +// the right. +class MainMenuDetector : public StaticScreenDetector{ +public: + MainMenuDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Read where the cursor is. + // The 2nd return value is the index. 0 is the top row. 6 is only valid on + // the left side and is Koraidon/Miraidon. + std::pair detect_location(const ImageViewRGB32& screen); + + // While sitting on the menu, move the cursor to the desired slot. + // Returns true if success. + // If (fast = true) it will be faster, but may be unreliable. It may not + // actually land on the desired slot if the capture card is slow. + bool move_cursor( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + MenuSide side, int row, bool fast = false + ); + + +protected: + Color m_color; + ImageFloatBox m_bottom; + GradientArrowDetector m_arrow_left; + GradientArrowDetector m_arrow_right; + GradientArrowDetector m_dlc_icon; +}; +class MainMenuWatcher : public DetectorToFinder{ +public: + MainMenuWatcher(Color color = COLOR_RED) + : DetectorToFinder("MainMenuWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp index 1ff5983ee9..e33fcf1f71 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.cpp @@ -1,45 +1,45 @@ -/* Menu Option Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_MenuOptionReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -MenuOptionReader& MenuOptionReader::instance(){ - static MenuOptionReader reader; - return reader; -} - -MenuOptionReader::MenuOptionReader() - : SmallDictionaryMatcher("PokemonSV/MenuOptionsOCR.json") -{} - -OCR::StringMatchResult MenuOptionReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - - - -} -} -} +/* Menu Option Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_MenuOptionReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +MenuOptionReader& MenuOptionReader::instance(){ + static MenuOptionReader reader; + return reader; +} + +MenuOptionReader::MenuOptionReader() + : SmallDictionaryMatcher("PokemonSV/MenuOptionsOCR.json") +{} + +OCR::StringMatchResult MenuOptionReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h index a273d4056a..c51a1e07cb 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MenuOptionReader.h @@ -1,41 +1,41 @@ -/* Menu Option Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MenuOptionReader_H -#define PokemonAutomation_PokemonSV_MenuOptionReader_H - -#include "CommonFramework/Language.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class MenuOptionReader : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.30; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - MenuOptionReader(); - - static MenuOptionReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; -}; - - - -} -} -} -#endif +/* Menu Option Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MenuOptionReader_H +#define PokemonAutomation_PokemonSV_MenuOptionReader_H + +#include "CommonFramework/Language.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class MenuOptionReader : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.30; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + MenuOptionReader(); + + static MenuOptionReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.cpp index c0b1767702..a24e2a7d30 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.cpp @@ -1,75 +1,75 @@ -/* Money Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/Language.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "PokemonSV_MoneyReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace OCR{ - - - -int read_money(Logger& logger, const ImageViewRGB32& image){ - std::string ocr_text = OCR::ocr_read(Language::English, image); - std::string normalized; - - //logger.log("OCR Text: " + ocr_text); - - //Clean up the string because regex search does not like accented characters - std::regex regg("[^a-zA-Z0-9\xA3, .#]+"); - ocr_text = std::regex_replace(ocr_text, regg, ""); - - //Find pound sign and amount, we want to prevent cases like the following: - //OCR Text: "Al IRt 1N} . !You got 27,200 in prize money!" -> "4127200" -> 4127200 - //OCR Text: "You got 26,400 in prize money!AR -" -> "264004" -> 264004 - //OCR Text: "v N r 1 .You got 26,400 in prize money!" -> "126400" -> 126400 - std::regex reg{ "\xA3[a-zA-Z0-9,.]+| [0-9,. ]+(\xA3|#)" }; - std::smatch match; - std::regex_search(ocr_text, match, reg); - std::ssub_match sub_match = match[0]; - - bool has_digit = false; - for (char ch : sub_match.str()){ - // 4 is commonly misread as A. - if (ch == 'a' || ch == 'A'){ - normalized += '4'; - has_digit = true; - } - if ('0' <= ch && ch <= '9'){ - normalized += ch; - has_digit = true; - } - } - - if (!has_digit){ - return -1; - } - - int number = std::atoi(normalized.c_str()); - - std::string str; - for (char ch : ocr_text){ - if (ch != '\r' && ch != '\n'){ - str += ch; - } - } - - logger.log("OCR Text: \"" + str + "\" -> \"" + sub_match.str() + "\" -> " + normalized + "\" -> " + std::to_string(number)); - - return number; -} - - - -} -} +/* Money Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/Language.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "PokemonSV_MoneyReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace OCR{ + + + +int read_money(Logger& logger, const ImageViewRGB32& image){ + std::string ocr_text = OCR::ocr_read(Language::English, image); + std::string normalized; + + //logger.log("OCR Text: " + ocr_text); + + //Clean up the string because regex search does not like accented characters + std::regex regg("[^a-zA-Z0-9\xA3, .#]+"); + ocr_text = std::regex_replace(ocr_text, regg, ""); + + //Find pound sign and amount, we want to prevent cases like the following: + //OCR Text: "Al IRt 1N} . !You got 27,200 in prize money!" -> "4127200" -> 4127200 + //OCR Text: "You got 26,400 in prize money!AR -" -> "264004" -> 264004 + //OCR Text: "v N r 1 .You got 26,400 in prize money!" -> "126400" -> 126400 + std::regex reg{ "\xA3[a-zA-Z0-9,.]+| [0-9,. ]+(\xA3|#)" }; + std::smatch match; + std::regex_search(ocr_text, match, reg); + std::ssub_match sub_match = match[0]; + + bool has_digit = false; + for (char ch : sub_match.str()){ + // 4 is commonly misread as A. + if (ch == 'a' || ch == 'A'){ + normalized += '4'; + has_digit = true; + } + if ('0' <= ch && ch <= '9'){ + normalized += ch; + has_digit = true; + } + } + + if (!has_digit){ + return -1; + } + + int number = std::atoi(normalized.c_str()); + + std::string str; + for (char ch : ocr_text){ + if (ch != '\r' && ch != '\n'){ + str += ch; + } + } + + logger.log("OCR Text: \"" + str + "\" -> \"" + sub_match.str() + "\" -> " + normalized + "\" -> " + std::to_string(number)); + + return number; +} + + + +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.h index d7989b8f71..b8988d7b5c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_MoneyReader.h @@ -1,22 +1,22 @@ -/* Money Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MoneyReader_H -#define PokemonAutomation_PokemonSV_MoneyReader_H - -namespace PokemonAutomation{ - class Logger; - class ImageViewRGB32; -namespace OCR{ - - -// Returns -1 if no number is found. -int read_money(Logger& logger, const ImageViewRGB32& image); - - -} -} -#endif +/* Money Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MoneyReader_H +#define PokemonAutomation_PokemonSV_MoneyReader_H + +namespace PokemonAutomation{ + class Logger; + class ImageViewRGB32; +namespace OCR{ + + +// Returns -1 if no number is found. +int read_money(Logger& logger, const ImageViewRGB32& image); + + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.cpp index d7335a4536..5da689ec1c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.cpp @@ -1,150 +1,150 @@ -/* Poke Portal Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_PokePortalDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -PokePortalDetector::PokePortalDetector(Color color) - : m_color(color) - , m_bottom(0.10, 0.94, 0.40, 0.05) - , m_arrow_union(color, GradientArrowType::RIGHT, {0.025, 0.180, 0.050, 0.080}) - , m_arrow_tera(color, GradientArrowType::RIGHT, {0.025, 0.350, 0.050, 0.080}) - , m_arrow_bottom(color, GradientArrowType::RIGHT, {0.025, 0.460, 0.050, 0.350}) -{} -void PokePortalDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - m_arrow_union.make_overlays(items); - m_arrow_tera.make_overlays(items); - m_arrow_bottom.make_overlays(items); -} -bool PokePortalDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); - if (!is_solid(bottom, {0.582218, 0.417782, 0.})){ - return false; - } - - if (m_arrow_union.detect(screen)){ - return true; - } - if (m_arrow_tera.detect(screen)){ - return true; - } - if (m_arrow_bottom.detect(screen)){ - return true; - } - - return false; -} -int PokePortalDetector::detect_location(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); - if (!is_solid(bottom, {0.582218, 0.417782, 0.})){ - return -1; - } - - if (m_arrow_union.detect(screen)){ - return 0; - } - if (m_arrow_tera.detect(screen)){ - return 1; - } - - ImageFloatBox box; - if (m_arrow_bottom.detect(box, screen)){ -// cout << box.y << endl; - int slot = (int)((box.y - 0.474074) / 0.0645833 + 0.5); - if (slot < 0){ - return -1; - } - return slot + 2; - } - - return false; -} - - - -bool PokePortalDetector::move_cursor( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int row -){ - if (row < 0 || row >= 7){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "PokePortalDetector::move_cursor() called with invalid row." - ); - } - - size_t consecutive_detection_fails = 0; - size_t moves = 0; - bool target_reached = false; - while (true){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int current = this->detect_location(screen); - - // Failed to detect menu. - if (current < 0){ - consecutive_detection_fails++; - if (consecutive_detection_fails > 10){ - dump_image_and_throw_recoverable_exception( - info, stream, "UnableToDetectPokePortal", - "Unable to detect Poke Portal." - ); - } - context.wait_for(std::chrono::milliseconds(50)); - continue; - } - consecutive_detection_fails = 0; - - if (moves >= 10){ - stream.log("Unable to move to target after 10 moves.", COLOR_RED); - return false; - } - - // We're done! - if (current == row){ - if (target_reached){ - return true; - }else{ - // Don't return yet. Wait a second to make sure the video is - // in steady state before we return. - target_reached = true; - context.wait_for(std::chrono::seconds(1)); - continue; - } - } - target_reached = false; - - moves++; - - int diff = (7 + current - row) % 7; - if (diff < 4){ - pbf_press_dpad(context, DPAD_UP, 20, 10); - }else{ - pbf_press_dpad(context, DPAD_DOWN, 20, 10); - } - } -} - - - - - - - - -} -} -} +/* Poke Portal Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_PokePortalDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +PokePortalDetector::PokePortalDetector(Color color) + : m_color(color) + , m_bottom(0.10, 0.94, 0.40, 0.05) + , m_arrow_union(color, GradientArrowType::RIGHT, {0.025, 0.180, 0.050, 0.080}) + , m_arrow_tera(color, GradientArrowType::RIGHT, {0.025, 0.350, 0.050, 0.080}) + , m_arrow_bottom(color, GradientArrowType::RIGHT, {0.025, 0.460, 0.050, 0.350}) +{} +void PokePortalDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + m_arrow_union.make_overlays(items); + m_arrow_tera.make_overlays(items); + m_arrow_bottom.make_overlays(items); +} +bool PokePortalDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); + if (!is_solid(bottom, {0.582218, 0.417782, 0.})){ + return false; + } + + if (m_arrow_union.detect(screen)){ + return true; + } + if (m_arrow_tera.detect(screen)){ + return true; + } + if (m_arrow_bottom.detect(screen)){ + return true; + } + + return false; +} +int PokePortalDetector::detect_location(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); + if (!is_solid(bottom, {0.582218, 0.417782, 0.})){ + return -1; + } + + if (m_arrow_union.detect(screen)){ + return 0; + } + if (m_arrow_tera.detect(screen)){ + return 1; + } + + ImageFloatBox box; + if (m_arrow_bottom.detect(box, screen)){ +// cout << box.y << endl; + int slot = (int)((box.y - 0.474074) / 0.0645833 + 0.5); + if (slot < 0){ + return -1; + } + return slot + 2; + } + + return false; +} + + + +bool PokePortalDetector::move_cursor( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int row +){ + if (row < 0 || row >= 7){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "PokePortalDetector::move_cursor() called with invalid row." + ); + } + + size_t consecutive_detection_fails = 0; + size_t moves = 0; + bool target_reached = false; + while (true){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int current = this->detect_location(screen); + + // Failed to detect menu. + if (current < 0){ + consecutive_detection_fails++; + if (consecutive_detection_fails > 10){ + dump_image_and_throw_recoverable_exception( + info, stream, "UnableToDetectPokePortal", + "Unable to detect Poke Portal." + ); + } + context.wait_for(std::chrono::milliseconds(50)); + continue; + } + consecutive_detection_fails = 0; + + if (moves >= 10){ + stream.log("Unable to move to target after 10 moves.", COLOR_RED); + return false; + } + + // We're done! + if (current == row){ + if (target_reached){ + return true; + }else{ + // Don't return yet. Wait a second to make sure the video is + // in steady state before we return. + target_reached = true; + context.wait_for(std::chrono::seconds(1)); + continue; + } + } + target_reached = false; + + moves++; + + int diff = (7 + current - row) % 7; + if (diff < 4){ + pbf_press_dpad(context, DPAD_UP, 20, 10); + }else{ + pbf_press_dpad(context, DPAD_DOWN, 20, 10); + } + } +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.h index fba73ed30f..55d17f967a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokePortalDetector.h @@ -1,61 +1,61 @@ -/* Poke Portal Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PokePortalDetector_H -#define PokemonAutomation_PokemonSV_PokePortalDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class PokePortalDetector : public StaticScreenDetector{ -public: - PokePortalDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - // Read where the cursor is. Returns -1 on failure. - int detect_location(const ImageViewRGB32& screen); - - // While sitting on the menu, move the cursor to the desired slot. - // Returns true if success. - bool move_cursor( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int row - ); - - -private: - Color m_color; - ImageFloatBox m_bottom; - GradientArrowDetector m_arrow_union; - GradientArrowDetector m_arrow_tera; - GradientArrowDetector m_arrow_bottom; -}; -class PokePortalWatcher : public DetectorToFinder{ -public: - PokePortalWatcher(Color color = COLOR_RED) - : DetectorToFinder("PokePortalWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -} -} -} -#endif +/* Poke Portal Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PokePortalDetector_H +#define PokemonAutomation_PokemonSV_PokePortalDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class PokePortalDetector : public StaticScreenDetector{ +public: + PokePortalDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + // Read where the cursor is. Returns -1 on failure. + int detect_location(const ImageViewRGB32& screen); + + // While sitting on the menu, move the cursor to the desired slot. + // Returns true if success. + bool move_cursor( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int row + ); + + +private: + Color m_color; + ImageFloatBox m_bottom; + GradientArrowDetector m_arrow_union; + GradientArrowDetector m_arrow_tera; + GradientArrowDetector m_arrow_bottom; +}; +class PokePortalWatcher : public DetectorToFinder{ +public: + PokePortalWatcher(Color color = COLOR_RED) + : DetectorToFinder("PokePortalWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp index 971c0b4e2b..c75ddac894 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.cpp @@ -1,90 +1,90 @@ -/* Pokemon Moves Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "PokemonSV_PokemonMovesReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -PokemonMovesOCR& PokemonMovesOCR::instance(){ - static PokemonMovesOCR reader; - return reader; -} - -PokemonMovesOCR::PokemonMovesOCR() - : SmallDictionaryMatcher("PokemonSV/PokemonMovesOCR.json") -{} - -OCR::StringMatchResult PokemonMovesOCR::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - -PokemonMovesReader::PokemonMovesReader(Language language) - : m_language(language) -{ - for (size_t c = 0; c < 4; c++){ - m_boxes_rearrange[c] = ImageFloatBox(0.345, 0.245 + c * 0.074, 0.250, 0.065); - } -} - -void PokemonMovesReader::make_overlays(VideoOverlaySet& items) const{ - for (size_t c = 0; c < 4; c++){ - items.add(COLOR_GREEN, m_boxes_rearrange[c]); - } -} - -std::string PokemonMovesReader::read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const{ - ImageViewRGB32 cropped = extract_box_reference(screen, m_boxes_rearrange[index]); - const auto ocr_result = PokemonMovesOCR::instance().read_substring( - logger, m_language, - cropped, OCR::BLACK_OR_WHITE_TEXT_FILTERS() - ); - - std::multimap results; - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - } - - if (results.empty()){ - return ""; - } - - if (results.size() > 1){ - throw_and_log( - logger, ErrorReport::SEND_ERROR_REPORT, - "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results." - ); - } - - return results.begin()->second.token; -} - - - -} -} -} +/* Pokemon Moves Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "PokemonSV_PokemonMovesReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +PokemonMovesOCR& PokemonMovesOCR::instance(){ + static PokemonMovesOCR reader; + return reader; +} + +PokemonMovesOCR::PokemonMovesOCR() + : SmallDictionaryMatcher("PokemonSV/PokemonMovesOCR.json") +{} + +OCR::StringMatchResult PokemonMovesOCR::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + +PokemonMovesReader::PokemonMovesReader(Language language) + : m_language(language) +{ + for (size_t c = 0; c < 4; c++){ + m_boxes_rearrange[c] = ImageFloatBox(0.345, 0.245 + c * 0.074, 0.250, 0.065); + } +} + +void PokemonMovesReader::make_overlays(VideoOverlaySet& items) const{ + for (size_t c = 0; c < 4; c++){ + items.add(COLOR_GREEN, m_boxes_rearrange[c]); + } +} + +std::string PokemonMovesReader::read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const{ + ImageViewRGB32 cropped = extract_box_reference(screen, m_boxes_rearrange[index]); + const auto ocr_result = PokemonMovesOCR::instance().read_substring( + logger, m_language, + cropped, OCR::BLACK_OR_WHITE_TEXT_FILTERS() + ); + + std::multimap results; + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + } + + if (results.empty()){ + return ""; + } + + if (results.size() > 1){ + throw_and_log( + logger, ErrorReport::SEND_ERROR_REPORT, + "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results." + ); + } + + return results.begin()->second.token; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h index cdac5efc36..35b89dece5 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonMovesReader.h @@ -1,59 +1,59 @@ -/* Pokemon Moves Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PokemonMovesReader_H -#define PokemonAutomation_PokemonSV_PokemonMovesReader_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class PokemonMovesOCR : public OCR::SmallDictionaryMatcher{ - static constexpr double MAX_LOG10P = -1.30; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - PokemonMovesOCR(); - - static PokemonMovesOCR& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - - -}; - -class PokemonMovesReader{ - -public: - PokemonMovesReader(Language language); - - void make_overlays(VideoOverlaySet& items) const; - - std::string read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const; - -private: - Language m_language; - std::array m_boxes_rearrange; -}; - - - -} -} -} -#endif +/* Pokemon Moves Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PokemonMovesReader_H +#define PokemonAutomation_PokemonSV_PokemonMovesReader_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class PokemonMovesOCR : public OCR::SmallDictionaryMatcher{ + static constexpr double MAX_LOG10P = -1.30; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + PokemonMovesOCR(); + + static PokemonMovesOCR& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + + +}; + +class PokemonMovesReader{ + +public: + PokemonMovesReader(Language language); + + void make_overlays(VideoOverlaySet& items) const; + + std::string read_move(Logger& logger, const ImageViewRGB32& screen, int8_t index) const; + +private: + Language m_language; + std::array m_boxes_rearrange; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.cpp index 7f7f791082..11ced7dba4 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.cpp @@ -1,102 +1,102 @@ -/* Pokemon Summary Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_PokemonSummaryReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -bool is_summary_color(const ImageStats& stats){ - return is_solid(stats, {0.648549, 0.2861580, 0.0652928}, 0.15, 25) // Scarlet - || is_solid(stats, {0.367816, 0.0746615, 0.5575230}, 0.15, 25) // Violet - || is_solid(stats, {0.196536, 0.5933000, 0.2101630}, 0.18, 25) // DLC1 Green - || is_solid(stats, {0.169492, 0.330508 , 0.5 }, 0.18, 25) // DLC2 Dark Blue - || (stats.average.g / stats.average.sum()) > 0.5; -} - - - -PokemonSummaryDetector::PokemonSummaryDetector(Color color) - : m_color(color) - , m_top_blue_left(0.30, 0.09, 0.10, 0.05) - , m_top_blue_right(0.60, 0.09, 0.35, 0.05) - , m_bottom(0.03, 0.94, 0.40, 0.04) - , m_arrow_left(color, WhiteButton::ButtonLeft, {0.415, 0.085, 0.035, 0.057}) - , m_arrow_right(color, WhiteButton::ButtonRight, {0.553, 0.085, 0.035, 0.057}) - , m_shiny_symbol(0.575, 0.865, 0.017, 0.030) -{} -void PokemonSummaryDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_top_blue_left); - items.add(m_color, m_top_blue_right); - items.add(m_color, m_bottom); - m_arrow_left.make_overlays(items); - m_arrow_right.make_overlays(items); - items.add(m_color, m_shiny_symbol); -} -bool PokemonSummaryDetector::detect(const ImageViewRGB32& screen){ - ImageStats top_blue_left = image_stats(extract_box_reference(screen, m_top_blue_left)); -// cout << top_blue_left.average << top_blue_left.stddev << endl; - if (!is_solid(top_blue_left, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ -// cout << "bad: blue left" << endl; - return false; - } - - ImageStats top_blue_right = image_stats(extract_box_reference(screen, m_top_blue_right)); -// cout << top_blue_right.average << top_blue_right.stddev << endl; - if (!is_solid(top_blue_right, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ -// cout << "bad: blue right" << endl; - return false; - } - - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; -#if 0 - if (bottom.stddev.sum() > 20){ - return false; - } -#else - if (!is_summary_color(bottom)){ -// cout << "bad summary color" << endl; - return false; - } -#endif - - if (!m_arrow_left.detect(screen)){ -// cout << "bad arrow left" << endl; - return false; - } - if (!m_arrow_right.detect(screen)){ -// cout << "bad arrow right" << endl; - return false; - } - -// ImageStats shiny_symbol = image_stats(extract_box_reference(screen, m_shiny_symbol)); -// cout << shiny_symbol.average << shiny_symbol.stddev << endl; - - return true; -} -bool PokemonSummaryDetector::is_shiny(const ImageViewRGB32& screen) const{ - ImageStats shiny = image_stats(extract_box_reference(screen, m_shiny_symbol)); - return shiny.stddev.sum() > 100; -} - - - - - - -} -} -} +/* Pokemon Summary Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_PokemonSummaryReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +bool is_summary_color(const ImageStats& stats){ + return is_solid(stats, {0.648549, 0.2861580, 0.0652928}, 0.15, 25) // Scarlet + || is_solid(stats, {0.367816, 0.0746615, 0.5575230}, 0.15, 25) // Violet + || is_solid(stats, {0.196536, 0.5933000, 0.2101630}, 0.18, 25) // DLC1 Green + || is_solid(stats, {0.169492, 0.330508 , 0.5 }, 0.18, 25) // DLC2 Dark Blue + || (stats.average.g / stats.average.sum()) > 0.5; +} + + + +PokemonSummaryDetector::PokemonSummaryDetector(Color color) + : m_color(color) + , m_top_blue_left(0.30, 0.09, 0.10, 0.05) + , m_top_blue_right(0.60, 0.09, 0.35, 0.05) + , m_bottom(0.03, 0.94, 0.40, 0.04) + , m_arrow_left(color, WhiteButton::ButtonLeft, {0.415, 0.085, 0.035, 0.057}) + , m_arrow_right(color, WhiteButton::ButtonRight, {0.553, 0.085, 0.035, 0.057}) + , m_shiny_symbol(0.575, 0.865, 0.017, 0.030) +{} +void PokemonSummaryDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_top_blue_left); + items.add(m_color, m_top_blue_right); + items.add(m_color, m_bottom); + m_arrow_left.make_overlays(items); + m_arrow_right.make_overlays(items); + items.add(m_color, m_shiny_symbol); +} +bool PokemonSummaryDetector::detect(const ImageViewRGB32& screen){ + ImageStats top_blue_left = image_stats(extract_box_reference(screen, m_top_blue_left)); +// cout << top_blue_left.average << top_blue_left.stddev << endl; + if (!is_solid(top_blue_left, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ +// cout << "bad: blue left" << endl; + return false; + } + + ImageStats top_blue_right = image_stats(extract_box_reference(screen, m_top_blue_right)); +// cout << top_blue_right.average << top_blue_right.stddev << endl; + if (!is_solid(top_blue_right, {0.0745162, 0.311321, 0.614163}, 0.30, 10)){ +// cout << "bad: blue right" << endl; + return false; + } + + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; +#if 0 + if (bottom.stddev.sum() > 20){ + return false; + } +#else + if (!is_summary_color(bottom)){ +// cout << "bad summary color" << endl; + return false; + } +#endif + + if (!m_arrow_left.detect(screen)){ +// cout << "bad arrow left" << endl; + return false; + } + if (!m_arrow_right.detect(screen)){ +// cout << "bad arrow right" << endl; + return false; + } + +// ImageStats shiny_symbol = image_stats(extract_box_reference(screen, m_shiny_symbol)); +// cout << shiny_symbol.average << shiny_symbol.stddev << endl; + + return true; +} +bool PokemonSummaryDetector::is_shiny(const ImageViewRGB32& screen) const{ + ImageStats shiny = image_stats(extract_box_reference(screen, m_shiny_symbol)); + return shiny.stddev.sum() > 100; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h index 880941ace6..3cba5f3dc7 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h @@ -1,58 +1,58 @@ -/* Pokemon Summary Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PokemonSummaryReader_H -#define PokemonAutomation_PokemonSV_PokemonSummaryReader_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV_WhiteButtonDetector.h" - -namespace PokemonAutomation{ - struct ImageStats; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -bool is_summary_color(const ImageStats& stats); - - -// Detect pokemon status summary page -class PokemonSummaryDetector : public StaticScreenDetector{ -public: - PokemonSummaryDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - bool is_shiny(const ImageViewRGB32& screen) const; - - -protected: - Color m_color; - ImageFloatBox m_top_blue_left; - ImageFloatBox m_top_blue_right; - ImageFloatBox m_bottom; - - WhiteButtonDetector m_arrow_left; - WhiteButtonDetector m_arrow_right; - - ImageFloatBox m_shiny_symbol; -}; -class PokemonSummaryWatcher : public DetectorToFinder{ -public: - PokemonSummaryWatcher(Color color = COLOR_RED) - : DetectorToFinder("PokemonSummaryWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -} -} -} -#endif +/* Pokemon Summary Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PokemonSummaryReader_H +#define PokemonAutomation_PokemonSV_PokemonSummaryReader_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV_WhiteButtonDetector.h" + +namespace PokemonAutomation{ + struct ImageStats; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +bool is_summary_color(const ImageStats& stats); + + +// Detect pokemon status summary page +class PokemonSummaryDetector : public StaticScreenDetector{ +public: + PokemonSummaryDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + bool is_shiny(const ImageViewRGB32& screen) const; + + +protected: + Color m_color; + ImageFloatBox m_top_blue_left; + ImageFloatBox m_top_blue_right; + ImageFloatBox m_bottom; + + WhiteButtonDetector m_arrow_left; + WhiteButtonDetector m_arrow_right; + + ImageFloatBox m_shiny_symbol; +}; +class PokemonSummaryWatcher : public DetectorToFinder{ +public: + PokemonSummaryWatcher(Color color = COLOR_RED) + : DetectorToFinder("PokemonSummaryWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.cpp index 88dd52a974..0b4cb20622 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.cpp @@ -1,278 +1,278 @@ -/* Stat Hexagon Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV_StatHexagonReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -StatHexagonReader::StatHexagonReader( - Color color, - const ImageFloatBox& level, - const ImageFloatBox& ball_attack, - const ImageFloatBox& ball_defense, - const ImageFloatBox& ball_spatk, - const ImageFloatBox& ball_spdef, - const ImageFloatBox& ball_speed, - const ImageFloatBox& stat_hp, - const ImageFloatBox& stat_attack, - const ImageFloatBox& stat_defense, - const ImageFloatBox& stat_spatk, - const ImageFloatBox& stat_spdef, - const ImageFloatBox& stat_speed -) - : m_color(color) - , m_level(level) - , m_ball_attack(ball_attack) - , m_ball_defense(ball_defense) - , m_ball_spatk(ball_spatk) - , m_ball_spdef(ball_spdef) - , m_ball_speed(ball_speed) - , m_stat_hp(stat_hp) - , m_stat_attack(stat_attack) - , m_stat_defense(stat_defense) - , m_stat_spatk(stat_spatk) - , m_stat_spdef(stat_spdef) - , m_stat_speed(stat_speed) -{} -void StatHexagonReader::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_level); - items.add(m_color, m_ball_attack); - items.add(m_color, m_ball_defense); - items.add(m_color, m_ball_spatk); - items.add(m_color, m_ball_spdef); - items.add(m_color, m_ball_speed); - items.add(m_color, m_stat_hp); - items.add(m_color, m_stat_attack); - items.add(m_color, m_stat_defense); - items.add(m_color, m_stat_spatk); - items.add(m_color, m_stat_spdef); - items.add(m_color, m_stat_speed); -} -NatureAdjustment StatHexagonReader::read_stat_adjustment(ImageStats& stats, const ImageFloatBox& box, const ImageViewRGB32& screen) const{ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, box); - -// cout << "--------------" << endl; - { - auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - - WaterfillObject object; - while (iter->find_next(object, false)){ -// cout << object.area << " : " << object.width() << " x " << object.height() -// << ", aspect = " << object.aspect_ratio() << ", area ratio = " << object.area_ratio() << endl; - - double aspect_ratio = object.aspect_ratio(); - if (!(0.8 < aspect_ratio && aspect_ratio < 1.2)){ - continue; - } - if (object.area_ratio() < 0.65){ - continue; - } - - return NatureAdjustment::NEUTRAL; - } - } - - stats = image_stats(region); -// cout << stats.average << "," << stats.stddev << endl; - - return stats.average.r > stats.average.b - ? NatureAdjustment::POSITIVE - : NatureAdjustment::NEGATIVE; -} -NatureAdjustments StatHexagonReader::read_nature(Logger& logger, const ImageViewRGB32& screen) const{ - NatureAdjustments ret; - - std::vector> non_neutral; - - ImageStats stats; - - ret.attack = read_stat_adjustment(stats, m_ball_attack, screen); - if (ret.attack != NatureAdjustment::NEUTRAL){ - non_neutral.emplace_back(&ret.attack, stats); - } - - ret.defense = read_stat_adjustment(stats, m_ball_defense, screen); - if (ret.defense != NatureAdjustment::NEUTRAL){ - non_neutral.emplace_back(&ret.defense, stats); - } - - ret.spatk = read_stat_adjustment(stats, m_ball_spatk, screen); - if (ret.spatk != NatureAdjustment::NEUTRAL){ - non_neutral.emplace_back(&ret.spatk, stats); - } - - ret.spdef = read_stat_adjustment(stats, m_ball_spdef, screen); - if (ret.spdef != NatureAdjustment::NEUTRAL){ - non_neutral.emplace_back(&ret.spdef, stats); - } - - ret.speed = read_stat_adjustment(stats, m_ball_speed, screen); - if (ret.speed != NatureAdjustment::NEUTRAL){ - non_neutral.emplace_back(&ret.speed, stats); - } - - if (non_neutral.size() == 0){ - return ret; - } - if (non_neutral.size() != 2){ - throw_and_log( - logger, ErrorReport::SEND_ERROR_REPORT, - "Unable to read nature." - ); - } - - if (*non_neutral[0].first != *non_neutral[1].first){ - return ret; - } - -// cout << non_neutral[0].second.average << non_neutral[1].second.average << endl; - - if (non_neutral[0].second.average.r > non_neutral[1].second.average.r && - non_neutral[0].second.average.b < non_neutral[1].second.average.b - ){ - *non_neutral[0].first = NatureAdjustment::POSITIVE; - *non_neutral[1].first = NatureAdjustment::NEGATIVE; - return ret; - } - if (non_neutral[0].second.average.r < non_neutral[1].second.average.r && - non_neutral[0].second.average.b > non_neutral[1].second.average.b - ){ - *non_neutral[0].first = NatureAdjustment::NEGATIVE; - *non_neutral[1].first = NatureAdjustment::POSITIVE; - return ret; - } - - throw_and_log( - logger, ErrorReport::SEND_ERROR_REPORT, - "Unable to read nature." - ); -} - - -int8_t StatHexagonReader::read_level(Logger& logger, const ImageViewRGB32& screen) const{ - ImageViewRGB32 region = extract_box_reference(screen, m_level); -#if 0 - ImageRGB32 filtered = to_blackwhite_rgb32_range(region, 0xff808080, 0xffffffff, true); - filtered = pad_image(filtered, filtered.height() / 2, 0xffffffff); - - int number = OCR::read_number(logger, filtered); -#else - int number = OCR::read_number_waterfill(logger, region, 0xff808080, 0xffffffff); -#endif - if (number < 0 || number > 100){ - number = -1; - } - return (int8_t)number; -} -int16_t StatHexagonReader::read_stat(Logger& logger, const ImageFloatBox& box, const ImageViewRGB32& screen) const{ - ImageViewRGB32 region = extract_box_reference(screen, box); -#if 0 - ImageRGB32 filtered = to_blackwhite_rgb32_range(region, 0xff808080, 0xffffffff, true); - filtered = pad_image(filtered, filtered.height() / 2, 0xffffffff); - -// static int c = 0; -// filtered.save("test-" + std::to_string(c++) + ".png"); - - int number = OCR::read_number_waterfill(logger, filtered); -#else - int number = OCR::read_number_waterfill(logger, region, 0xff808080, 0xffffffff); -#endif - if (number < 5 || number > 999){ - number = -1; - } - return (int16_t)number; -} -StatReads StatHexagonReader::read_stats(Logger& logger, const ImageViewRGB32& screen) const{ - StatReads ret; - - // TODO: Handle the slash. (99 / 100) - ret.hp = read_stat(logger, m_stat_hp, screen); - - ret.attack = read_stat(logger, m_stat_attack, screen); - ret.defense = read_stat(logger, m_stat_defense, screen); - ret.spatk = read_stat(logger, m_stat_spatk, screen); - ret.spdef = read_stat(logger, m_stat_spdef, screen); - ret.speed = read_stat(logger, m_stat_speed, screen); - return ret; -} -IvRanges StatHexagonReader::calc_ivs( - Logger& logger, const ImageViewRGB32& screen, - const BaseStats& base_stats, const EVs& evs -) const{ - int16_t level = read_level(logger, screen); - NatureAdjustments nature = read_nature(logger, screen); - StatReads stats = read_stats(logger, screen); - return calc_iv_ranges(base_stats, (uint8_t)level, evs, stats, nature); -} - - - -#if 0 -BoxStatsReader::BoxStatsReader(Color color) - : StatHexagonReader( - color, -// {0.823, 0.244, 0.012, 0.022}, - {0.875, 0.294, 0.012, 0.022}, - {0.875, 0.402, 0.012, 0.022}, - {0.771, 0.294, 0.012, 0.022}, - {0.771, 0.402, 0.012, 0.022}, - {0.823, 0.453, 0.012, 0.022}, - {0.828, 0.198, 0.080, 0.045}, - {0.890, 0.408, 0.050, 0.045}, - {0.890, 0.198, 0.050, 0.045}, - {0.720, 0.408, 0.050, 0.045}, - {0.720, 0.198, 0.050, 0.045}, - {0.828, 0.475, 0.050, 0.045} - ) -{} -#endif - -SummaryStatsReader::SummaryStatsReader(Color color) - : StatHexagonReader( - color, - {0.125, 0.860, 0.050, 0.044}, -// {0.755, 0.253, 0.012, 0.022}, - {0.834, 0.335, 0.012, 0.022}, - {0.834, 0.483, 0.012, 0.022}, - {0.677, 0.335, 0.012, 0.022}, - {0.677, 0.483, 0.012, 0.022}, - {0.755, 0.565, 0.012, 0.022}, - {0.767, 0.205, 0.040, 0.050}, - {0.848, 0.340, 0.040, 0.050}, - {0.848, 0.520, 0.040, 0.050}, - {0.637, 0.340, 0.040, 0.050}, - {0.637, 0.520, 0.040, 0.050}, - {0.742, 0.620, 0.040, 0.050} - ) -{} - - - - - - -} -} -} +/* Stat Hexagon Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV_StatHexagonReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +StatHexagonReader::StatHexagonReader( + Color color, + const ImageFloatBox& level, + const ImageFloatBox& ball_attack, + const ImageFloatBox& ball_defense, + const ImageFloatBox& ball_spatk, + const ImageFloatBox& ball_spdef, + const ImageFloatBox& ball_speed, + const ImageFloatBox& stat_hp, + const ImageFloatBox& stat_attack, + const ImageFloatBox& stat_defense, + const ImageFloatBox& stat_spatk, + const ImageFloatBox& stat_spdef, + const ImageFloatBox& stat_speed +) + : m_color(color) + , m_level(level) + , m_ball_attack(ball_attack) + , m_ball_defense(ball_defense) + , m_ball_spatk(ball_spatk) + , m_ball_spdef(ball_spdef) + , m_ball_speed(ball_speed) + , m_stat_hp(stat_hp) + , m_stat_attack(stat_attack) + , m_stat_defense(stat_defense) + , m_stat_spatk(stat_spatk) + , m_stat_spdef(stat_spdef) + , m_stat_speed(stat_speed) +{} +void StatHexagonReader::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_level); + items.add(m_color, m_ball_attack); + items.add(m_color, m_ball_defense); + items.add(m_color, m_ball_spatk); + items.add(m_color, m_ball_spdef); + items.add(m_color, m_ball_speed); + items.add(m_color, m_stat_hp); + items.add(m_color, m_stat_attack); + items.add(m_color, m_stat_defense); + items.add(m_color, m_stat_spatk); + items.add(m_color, m_stat_spdef); + items.add(m_color, m_stat_speed); +} +NatureAdjustment StatHexagonReader::read_stat_adjustment(ImageStats& stats, const ImageFloatBox& box, const ImageViewRGB32& screen) const{ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, box); + +// cout << "--------------" << endl; + { + auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + + WaterfillObject object; + while (iter->find_next(object, false)){ +// cout << object.area << " : " << object.width() << " x " << object.height() +// << ", aspect = " << object.aspect_ratio() << ", area ratio = " << object.area_ratio() << endl; + + double aspect_ratio = object.aspect_ratio(); + if (!(0.8 < aspect_ratio && aspect_ratio < 1.2)){ + continue; + } + if (object.area_ratio() < 0.65){ + continue; + } + + return NatureAdjustment::NEUTRAL; + } + } + + stats = image_stats(region); +// cout << stats.average << "," << stats.stddev << endl; + + return stats.average.r > stats.average.b + ? NatureAdjustment::POSITIVE + : NatureAdjustment::NEGATIVE; +} +NatureAdjustments StatHexagonReader::read_nature(Logger& logger, const ImageViewRGB32& screen) const{ + NatureAdjustments ret; + + std::vector> non_neutral; + + ImageStats stats; + + ret.attack = read_stat_adjustment(stats, m_ball_attack, screen); + if (ret.attack != NatureAdjustment::NEUTRAL){ + non_neutral.emplace_back(&ret.attack, stats); + } + + ret.defense = read_stat_adjustment(stats, m_ball_defense, screen); + if (ret.defense != NatureAdjustment::NEUTRAL){ + non_neutral.emplace_back(&ret.defense, stats); + } + + ret.spatk = read_stat_adjustment(stats, m_ball_spatk, screen); + if (ret.spatk != NatureAdjustment::NEUTRAL){ + non_neutral.emplace_back(&ret.spatk, stats); + } + + ret.spdef = read_stat_adjustment(stats, m_ball_spdef, screen); + if (ret.spdef != NatureAdjustment::NEUTRAL){ + non_neutral.emplace_back(&ret.spdef, stats); + } + + ret.speed = read_stat_adjustment(stats, m_ball_speed, screen); + if (ret.speed != NatureAdjustment::NEUTRAL){ + non_neutral.emplace_back(&ret.speed, stats); + } + + if (non_neutral.size() == 0){ + return ret; + } + if (non_neutral.size() != 2){ + throw_and_log( + logger, ErrorReport::SEND_ERROR_REPORT, + "Unable to read nature." + ); + } + + if (*non_neutral[0].first != *non_neutral[1].first){ + return ret; + } + +// cout << non_neutral[0].second.average << non_neutral[1].second.average << endl; + + if (non_neutral[0].second.average.r > non_neutral[1].second.average.r && + non_neutral[0].second.average.b < non_neutral[1].second.average.b + ){ + *non_neutral[0].first = NatureAdjustment::POSITIVE; + *non_neutral[1].first = NatureAdjustment::NEGATIVE; + return ret; + } + if (non_neutral[0].second.average.r < non_neutral[1].second.average.r && + non_neutral[0].second.average.b > non_neutral[1].second.average.b + ){ + *non_neutral[0].first = NatureAdjustment::NEGATIVE; + *non_neutral[1].first = NatureAdjustment::POSITIVE; + return ret; + } + + throw_and_log( + logger, ErrorReport::SEND_ERROR_REPORT, + "Unable to read nature." + ); +} + + +int8_t StatHexagonReader::read_level(Logger& logger, const ImageViewRGB32& screen) const{ + ImageViewRGB32 region = extract_box_reference(screen, m_level); +#if 0 + ImageRGB32 filtered = to_blackwhite_rgb32_range(region, 0xff808080, 0xffffffff, true); + filtered = pad_image(filtered, filtered.height() / 2, 0xffffffff); + + int number = OCR::read_number(logger, filtered); +#else + int number = OCR::read_number_waterfill(logger, region, 0xff808080, 0xffffffff); +#endif + if (number < 0 || number > 100){ + number = -1; + } + return (int8_t)number; +} +int16_t StatHexagonReader::read_stat(Logger& logger, const ImageFloatBox& box, const ImageViewRGB32& screen) const{ + ImageViewRGB32 region = extract_box_reference(screen, box); +#if 0 + ImageRGB32 filtered = to_blackwhite_rgb32_range(region, 0xff808080, 0xffffffff, true); + filtered = pad_image(filtered, filtered.height() / 2, 0xffffffff); + +// static int c = 0; +// filtered.save("test-" + std::to_string(c++) + ".png"); + + int number = OCR::read_number_waterfill(logger, filtered); +#else + int number = OCR::read_number_waterfill(logger, region, 0xff808080, 0xffffffff); +#endif + if (number < 5 || number > 999){ + number = -1; + } + return (int16_t)number; +} +StatReads StatHexagonReader::read_stats(Logger& logger, const ImageViewRGB32& screen) const{ + StatReads ret; + + // TODO: Handle the slash. (99 / 100) + ret.hp = read_stat(logger, m_stat_hp, screen); + + ret.attack = read_stat(logger, m_stat_attack, screen); + ret.defense = read_stat(logger, m_stat_defense, screen); + ret.spatk = read_stat(logger, m_stat_spatk, screen); + ret.spdef = read_stat(logger, m_stat_spdef, screen); + ret.speed = read_stat(logger, m_stat_speed, screen); + return ret; +} +IvRanges StatHexagonReader::calc_ivs( + Logger& logger, const ImageViewRGB32& screen, + const BaseStats& base_stats, const EVs& evs +) const{ + int16_t level = read_level(logger, screen); + NatureAdjustments nature = read_nature(logger, screen); + StatReads stats = read_stats(logger, screen); + return calc_iv_ranges(base_stats, (uint8_t)level, evs, stats, nature); +} + + + +#if 0 +BoxStatsReader::BoxStatsReader(Color color) + : StatHexagonReader( + color, +// {0.823, 0.244, 0.012, 0.022}, + {0.875, 0.294, 0.012, 0.022}, + {0.875, 0.402, 0.012, 0.022}, + {0.771, 0.294, 0.012, 0.022}, + {0.771, 0.402, 0.012, 0.022}, + {0.823, 0.453, 0.012, 0.022}, + {0.828, 0.198, 0.080, 0.045}, + {0.890, 0.408, 0.050, 0.045}, + {0.890, 0.198, 0.050, 0.045}, + {0.720, 0.408, 0.050, 0.045}, + {0.720, 0.198, 0.050, 0.045}, + {0.828, 0.475, 0.050, 0.045} + ) +{} +#endif + +SummaryStatsReader::SummaryStatsReader(Color color) + : StatHexagonReader( + color, + {0.125, 0.860, 0.050, 0.044}, +// {0.755, 0.253, 0.012, 0.022}, + {0.834, 0.335, 0.012, 0.022}, + {0.834, 0.483, 0.012, 0.022}, + {0.677, 0.335, 0.012, 0.022}, + {0.677, 0.483, 0.012, 0.022}, + {0.755, 0.565, 0.012, 0.022}, + {0.767, 0.205, 0.040, 0.050}, + {0.848, 0.340, 0.040, 0.050}, + {0.848, 0.520, 0.040, 0.050}, + {0.637, 0.340, 0.040, 0.050}, + {0.637, 0.520, 0.040, 0.050}, + {0.742, 0.620, 0.040, 0.050} + ) +{} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.h index d37a27a252..8707779616 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_StatHexagonReader.h @@ -1,98 +1,98 @@ -/* Stat Hexagon Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_StatHexagonReader_H -#define PokemonAutomation_PokemonSV_StatHexagonReader_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Pokemon_StatsCalculation.h" -#include "Pokemon/Pokemon_NatureChecker.h" - -namespace PokemonAutomation{ - -class Logger; -struct ImageStats; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -class StatHexagonReader{ -public: - StatHexagonReader( - Color color, - const ImageFloatBox& level, - const ImageFloatBox& ball_attack, - const ImageFloatBox& ball_defense, - const ImageFloatBox& ball_spatk, - const ImageFloatBox& ball_spdef, - const ImageFloatBox& ball_speed, - const ImageFloatBox& stat_hp, - const ImageFloatBox& stat_attack, - const ImageFloatBox& stat_defense, - const ImageFloatBox& stat_spatk, - const ImageFloatBox& stat_spdef, - const ImageFloatBox& stat_speed - ); - - void make_overlays(VideoOverlaySet& items) const; - - NatureAdjustments read_nature(Logger& logger, const ImageViewRGB32& screen) const; - int8_t read_level(Logger& logger, const ImageViewRGB32& screen) const; - StatReads read_stats(Logger& logger, const ImageViewRGB32& screen) const; - IvRanges calc_ivs( - Logger& logger, const ImageViewRGB32& screen, - const BaseStats& base_stats, const EVs& evs = EVs() - ) const; - - -private: - NatureAdjustment read_stat_adjustment(ImageStats& stats, const ImageFloatBox& box, const ImageViewRGB32& screen) const; - int16_t read_stat(Logger& logger, const ImageFloatBox& box, const ImageViewRGB32& screen) const; - - -private: - Color m_color; - - ImageFloatBox m_level; - -// ImageFloatBox m_ball_hp; - ImageFloatBox m_ball_attack; - ImageFloatBox m_ball_defense; - ImageFloatBox m_ball_spatk; - ImageFloatBox m_ball_spdef; - ImageFloatBox m_ball_speed; - - ImageFloatBox m_stat_hp; - ImageFloatBox m_stat_attack; - ImageFloatBox m_stat_defense; - ImageFloatBox m_stat_spatk; - ImageFloatBox m_stat_spdef; - ImageFloatBox m_stat_speed; -}; - - -#if 0 // This doesn't work due to HP and level reads being variable position. -class BoxStatsReader : public StatHexagonReader{ -public: - BoxStatsReader(Color color = COLOR_RED); -}; -#endif - -class SummaryStatsReader : public StatHexagonReader{ -public: - SummaryStatsReader(Color color = COLOR_RED); -}; - - - -} -} -} -#endif +/* Stat Hexagon Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StatHexagonReader_H +#define PokemonAutomation_PokemonSV_StatHexagonReader_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Pokemon_StatsCalculation.h" +#include "Pokemon/Pokemon_NatureChecker.h" + +namespace PokemonAutomation{ + +class Logger; +struct ImageStats; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +class StatHexagonReader{ +public: + StatHexagonReader( + Color color, + const ImageFloatBox& level, + const ImageFloatBox& ball_attack, + const ImageFloatBox& ball_defense, + const ImageFloatBox& ball_spatk, + const ImageFloatBox& ball_spdef, + const ImageFloatBox& ball_speed, + const ImageFloatBox& stat_hp, + const ImageFloatBox& stat_attack, + const ImageFloatBox& stat_defense, + const ImageFloatBox& stat_spatk, + const ImageFloatBox& stat_spdef, + const ImageFloatBox& stat_speed + ); + + void make_overlays(VideoOverlaySet& items) const; + + NatureAdjustments read_nature(Logger& logger, const ImageViewRGB32& screen) const; + int8_t read_level(Logger& logger, const ImageViewRGB32& screen) const; + StatReads read_stats(Logger& logger, const ImageViewRGB32& screen) const; + IvRanges calc_ivs( + Logger& logger, const ImageViewRGB32& screen, + const BaseStats& base_stats, const EVs& evs = EVs() + ) const; + + +private: + NatureAdjustment read_stat_adjustment(ImageStats& stats, const ImageFloatBox& box, const ImageViewRGB32& screen) const; + int16_t read_stat(Logger& logger, const ImageFloatBox& box, const ImageViewRGB32& screen) const; + + +private: + Color m_color; + + ImageFloatBox m_level; + +// ImageFloatBox m_ball_hp; + ImageFloatBox m_ball_attack; + ImageFloatBox m_ball_defense; + ImageFloatBox m_ball_spatk; + ImageFloatBox m_ball_spdef; + ImageFloatBox m_ball_speed; + + ImageFloatBox m_stat_hp; + ImageFloatBox m_stat_attack; + ImageFloatBox m_stat_defense; + ImageFloatBox m_stat_spatk; + ImageFloatBox m_stat_spdef; + ImageFloatBox m_stat_speed; +}; + + +#if 0 // This doesn't work due to HP and level reads being variable position. +class BoxStatsReader : public StatHexagonReader{ +public: + BoxStatsReader(Color color = COLOR_RED); +}; +#endif + +class SummaryStatsReader : public StatHexagonReader{ +public: + SummaryStatsReader(Color color = COLOR_RED); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.cpp index 62d4a8aaa3..a722e42bb0 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.cpp @@ -1,73 +1,73 @@ -/* Sweat Bubble Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "PokemonSV_SweatBubbleDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const ImageMatch::ExactImageMatcher& SWEAT_BUBBLE(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/SweatBubble.png"); - return matcher; -} - - - -SweatBubbleDetector::SweatBubbleDetector(Color color, const ImageFloatBox& box) - : m_color(color) - , m_box(box) -{} -void SweatBubbleDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool SweatBubbleDetector::detect(const ImageViewRGB32& screen){ - using namespace Kernels::Waterfill; - - ImageViewRGB32 region = extract_box_reference(screen, m_box); - - const ImageMatch::ExactImageMatcher& matcher = SWEAT_BUBBLE(); - - auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); - auto session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - -// static int c = 0; - while (iter->find_next(object, false)){ - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 1.0 || aspect_ratio > 1.3){ - continue; - } - ImageViewRGB32 cropped = extract_box_reference(region, object); -// cropped.save("test-object-" + std::to_string(c++) + ".png"); - double rmsd = matcher.rmsd(cropped); -// cout << rmsd << endl; - if (rmsd < 80){ - return true; - } - } - - return false; -} - - - - -} -} -} +/* Sweat Bubble Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "PokemonSV_SweatBubbleDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const ImageMatch::ExactImageMatcher& SWEAT_BUBBLE(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSV/SweatBubble.png"); + return matcher; +} + + + +SweatBubbleDetector::SweatBubbleDetector(Color color, const ImageFloatBox& box) + : m_color(color) + , m_box(box) +{} +void SweatBubbleDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool SweatBubbleDetector::detect(const ImageViewRGB32& screen){ + using namespace Kernels::Waterfill; + + ImageViewRGB32 region = extract_box_reference(screen, m_box); + + const ImageMatch::ExactImageMatcher& matcher = SWEAT_BUBBLE(); + + auto matrix = compress_rgb32_to_binary_range(region, 0xffc0c0c0, 0xffffffff); + auto session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + +// static int c = 0; + while (iter->find_next(object, false)){ + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 1.0 || aspect_ratio > 1.3){ + continue; + } + ImageViewRGB32 cropped = extract_box_reference(region, object); +// cropped.save("test-object-" + std::to_string(c++) + ".png"); + double rmsd = matcher.rmsd(cropped); +// cout << rmsd << endl; + if (rmsd < 80){ + return true; + } + } + + return false; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h index 6a2e1a40a5..5d700ac77b 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h @@ -1,45 +1,45 @@ -/* Sweat Bubble Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SweatBubbleDetector_H -#define PokemonAutomation_PokemonSV_SweatBubbleDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class SweatBubbleDetector : public StaticScreenDetector{ -public: - SweatBubbleDetector(Color color, const ImageFloatBox& box = {0.11, 0.81, 0.06, 0.10}); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -protected: - Color m_color; - ImageFloatBox m_box; -}; -class SweatBubbleWatcher : public DetectorToFinder{ -public: - SweatBubbleWatcher(Color color = COLOR_RED) - : DetectorToFinder("SweatBubbleWatcher", std::chrono::milliseconds(100), color) - {} -}; - - - - -} -} -} -#endif +/* Sweat Bubble Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SweatBubbleDetector_H +#define PokemonAutomation_PokemonSV_SweatBubbleDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class SweatBubbleDetector : public StaticScreenDetector{ +public: + SweatBubbleDetector(Color color, const ImageFloatBox& box = {0.11, 0.81, 0.06, 0.10}); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +protected: + Color m_color; + ImageFloatBox m_box; +}; +class SweatBubbleWatcher : public DetectorToFinder{ +public: + SweatBubbleWatcher(Color color = COLOR_RED) + : DetectorToFinder("SweatBubbleWatcher", std::chrono::milliseconds(100), color) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.cpp index 3fbab4bbf9..bf9901d0cd 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.cpp @@ -1,39 +1,39 @@ -/* Tournament Prize Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "PokemonSV_TournamentPrizeNameReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -TournamentPrizeNameReader& TournamentPrizeNameReader::instance(){ - static TournamentPrizeNameReader reader; - return reader; -} - - -TournamentPrizeNameReader::TournamentPrizeNameReader() - : SmallDictionaryMatcher("PokemonSV/AAT/TournamentPrizeNameOCR.json") -{} - -OCR::StringMatchResult TournamentPrizeNameReader::read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio, double max_text_ratio -) const{ - return match_substring_from_image_multifiltered( - &logger, language, image, text_color_ranges, - MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio - ); -} - -} -} -} +/* Tournament Prize Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "PokemonSV_TournamentPrizeNameReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +TournamentPrizeNameReader& TournamentPrizeNameReader::instance(){ + static TournamentPrizeNameReader reader; + return reader; +} + + +TournamentPrizeNameReader::TournamentPrizeNameReader() + : SmallDictionaryMatcher("PokemonSV/AAT/TournamentPrizeNameOCR.json") +{} + +OCR::StringMatchResult TournamentPrizeNameReader::read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio, double max_text_ratio +) const{ + return match_substring_from_image_multifiltered( + &logger, language, image, text_color_ranges, + MAX_LOG10P, MAX_LOG10P_SPREAD, min_text_ratio, max_text_ratio + ); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h index eeb6557694..2ce6fe0ebd 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h @@ -1,38 +1,38 @@ -/* Tournament Prize Name Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TournamentPrizeNameReader_H -#define PokemonAutomation_PokemonSV_TournamentPrizeNameReader_H - -#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class TournamentPrizeNameReader : public OCR::SmallDictionaryMatcher{ -public: - static constexpr double MAX_LOG10P = -1.40; - static constexpr double MAX_LOG10P_SPREAD = 0.50; - -public: - TournamentPrizeNameReader(); - - static TournamentPrizeNameReader& instance(); - - OCR::StringMatchResult read_substring( - Logger& logger, - Language language, - const ImageViewRGB32& image, - const std::vector& text_color_ranges, - double min_text_ratio = 0.01, double max_text_ratio = 0.50 - ) const; - -}; -} -} -} -#endif +/* Tournament Prize Name Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TournamentPrizeNameReader_H +#define PokemonAutomation_PokemonSV_TournamentPrizeNameReader_H + +#include "CommonTools/OCR/OCR_SmallDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class TournamentPrizeNameReader : public OCR::SmallDictionaryMatcher{ +public: + static constexpr double MAX_LOG10P = -1.40; + static constexpr double MAX_LOG10P_SPREAD = 0.50; + +public: + TournamentPrizeNameReader(); + + static TournamentPrizeNameReader& instance(); + + OCR::StringMatchResult read_substring( + Logger& logger, + Language language, + const ImageViewRGB32& image, + const std::vector& text_color_ranges, + double min_text_ratio = 0.01, double max_text_ratio = 0.50 + ) const; + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp index dd56a61922..8143c9f844 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.cpp @@ -1,48 +1,48 @@ -/* Tutorial Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSV_TutorialDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -TutorialDetector::TutorialDetector(Color color) - : m_color(color) - , m_bottom(0.235, 0.87, 0.10, 0.035) - , m_left(0.230, 0.18, 0.02, 0.72) -{} -void TutorialDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - items.add(m_color, m_left); -} - -// detect solid beige color along the side and bottom of the tutorial -bool TutorialDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); - ImageStats left = image_stats(extract_box_reference(screen, m_left)); - // cout << "bottom.average.sum(): " << bottom.average.sum() << endl; - // cout << "left.average.sum(): " << left.average.sum() << endl; - - // expected color is {255, 255, 235} - return is_solid(bottom, {0.342282, 0.342282, 0.315436}) - && bottom.average.sum() > 500 - && is_solid(left, {0.342282, 0.342282, 0.315436}) - && left.average.sum() > 500; -} - - - -} -} -} +/* Tutorial Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSV_TutorialDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +TutorialDetector::TutorialDetector(Color color) + : m_color(color) + , m_bottom(0.235, 0.87, 0.10, 0.035) + , m_left(0.230, 0.18, 0.02, 0.72) +{} +void TutorialDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + items.add(m_color, m_left); +} + +// detect solid beige color along the side and bottom of the tutorial +bool TutorialDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); + ImageStats left = image_stats(extract_box_reference(screen, m_left)); + // cout << "bottom.average.sum(): " << bottom.average.sum() << endl; + // cout << "left.average.sum(): " << left.average.sum() << endl; + + // expected color is {255, 255, 235} + return is_solid(bottom, {0.342282, 0.342282, 0.315436}) + && bottom.average.sum() > 500 + && is_solid(left, {0.342282, 0.342282, 0.315436}) + && left.average.sum() > 500; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h index 3f36b37feb..d350173e58 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_TutorialDetector.h @@ -1,49 +1,49 @@ -/* Tutorial Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TutorialDetector_H -#define PokemonAutomation_PokemonSV_TutorialDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class TutorialDetector : public StaticScreenDetector{ -public: - TutorialDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - -protected: - Color m_color; - ImageFloatBox m_bottom; - ImageFloatBox m_left; -}; -class TutorialWatcher : public DetectorToFinder{ -public: - TutorialWatcher(Color color = COLOR_RED) - : DetectorToFinder("TutorialWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - - - -} -} -} -#endif +/* Tutorial Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TutorialDetector_H +#define PokemonAutomation_PokemonSV_TutorialDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class TutorialDetector : public StaticScreenDetector{ +public: + TutorialDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + +protected: + Color m_color; + ImageFloatBox m_bottom; + ImageFloatBox m_left; +}; +class TutorialWatcher : public DetectorToFinder{ +public: + TutorialWatcher(Color color = COLOR_RED) + : DetectorToFinder("TutorialWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.cpp index 024fc02ffd..fe1533ed99 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.cpp @@ -1,220 +1,220 @@ -/* White Button Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -//#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonSV_WhiteButtonDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - - - -const char* white_button_template_path(WhiteButton type){ - switch (type){ - case WhiteButton::ButtonA: - return "PokemonSV/Buttons/WhiteButtonA.png"; - case WhiteButton::ButtonA_DarkBackground: - return "PokemonSV/Buttons/WhiteButtonA-dark.png"; - case WhiteButton::ButtonB: - return "PokemonSV/Buttons/WhiteButtonB.png"; - case WhiteButton::ButtonX: - return "PokemonSV/Buttons/WhiteButtonX.png"; - case WhiteButton::ButtonY: - return "PokemonSV/Buttons/WhiteButtonY.png"; - case WhiteButton::ButtonMinus: - return "PokemonSV/Buttons/WhiteButtonMinus.png"; - case WhiteButton::ButtonLeft: - return "PokemonSV/Buttons/ArrowLeft.png"; - case WhiteButton::ButtonRight: - return "PokemonSV/Buttons/ArrowRight.png"; - case WhiteButton::ButtonLStick: - return "PokemonSV/Buttons/LStick.png"; - default: - return ""; - } -} - -const WhiteButtonMatcher& get_button_matcher(WhiteButton type){ - switch (type){ - case WhiteButton::ButtonA: - return WhiteButtonMatcher::A(); - case WhiteButton::ButtonA_DarkBackground: - return WhiteButtonMatcher::A_DarkBackground(); - case WhiteButton::ButtonB: - return WhiteButtonMatcher::B(); - case WhiteButton::ButtonX: - return WhiteButtonMatcher::X(); - case WhiteButton::ButtonY: - return WhiteButtonMatcher::Y(); - case WhiteButton::ButtonMinus: - return WhiteButtonMatcher::Minus(); - case WhiteButton::ButtonLeft: - return WhiteButtonMatcher::ArrowLeft(); - case WhiteButton::ButtonRight: - return WhiteButtonMatcher::ArrowRight(); - case WhiteButton::ButtonLStick: - return WhiteButtonMatcher::LStick(); - default: - throw std::runtime_error("No corresponding ButtonMatcher for WhiteButton"); - } -} - - - - -WhiteButtonMatcher::WhiteButtonMatcher(WhiteButton type, size_t min_width, size_t max_width, double max_rmsd) - : WaterfillTemplateMatcher( - white_button_template_path(type), Color(0xff808008), Color(0xffffffff), 100 - ) - , m_min_width(min_width) - , m_min_height(max_width) - , m_max_rmsd(max_rmsd) -{} -const WhiteButtonMatcher& WhiteButtonMatcher::A(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonA, 15, 15, 100); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::A_DarkBackground(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonA_DarkBackground, 15, 15, 100); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::B(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonB, 15, 15, 90); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::X(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonX, 15, 15, 90); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::Y(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonY, 15, 15, 90); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::Minus(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonMinus, 15, 15, 90); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::ArrowLeft(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonLeft, 15, 15, 90); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::ArrowRight(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonRight, 15, 15, 90); - return matcher; -} -const WhiteButtonMatcher& WhiteButtonMatcher::LStick(){ - static WhiteButtonMatcher matcher(WhiteButton::ButtonLStick, 15, 15, 90); - return matcher; -} - - - - - - - -WhiteButtonDetector::WhiteButtonDetector( - Color color, - WhiteButton button, - const ImageFloatBox& box -) - : m_matcher(get_button_matcher(button)) - , m_color(color) - , m_box(box) -{} -void WhiteButtonDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} -bool WhiteButtonDetector::detect(const ImageViewRGB32& screen){ - std::vector hits = detect_all(screen); - return !hits.empty(); -} - -std::vector WhiteButtonDetector::detect_all(const ImageViewRGB32& screen) const{ - ImageViewRGB32 region = extract_box_reference(screen, m_box); - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff808080, 0xffffffff); - - std::vector hits; - - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(50); - WaterfillObject object; - while (iter->find_next(object, false)){ - if (object.min_x == 0 || object.min_y == 0 || - object.max_x == region.width() || object.max_y == region.height() - ){ - continue; - } - double rmsd = m_matcher.rmsd_original(region, object); -// cout << "rmsd = " << rmsd << endl; - if (rmsd < m_matcher.m_max_rmsd){ - hits.emplace_back(translate_to_parent(screen, m_box, object)); - } - } - return hits; -} - - - -#if 0 -WhiteButtonWatcher::~WhiteButtonWatcher() = default; -WhiteButtonWatcher::WhiteButtonWatcher( - Color color, - WhiteButton button, size_t consecutive_detections, - VideoOverlay& overlay, - const ImageFloatBox& box -) - : VisualInferenceCallback("GradientArrowFinder") - , m_overlay(overlay) - , m_detector(color, button, box) - , m_consecutive_detections(consecutive_detections) -{} - -void WhiteButtonWatcher::make_overlays(VideoOverlaySet& items) const{ - m_detector.make_overlays(items); -} -bool WhiteButtonWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - std::vector hits = m_detector.detect_all(frame); -// cout << "arrows = " << arrows.size() << endl; - m_arrows.reset(hits.size()); - for (const ImageFloatBox& hit : hits){ - m_arrows.emplace_back(m_overlay, hit, COLOR_MAGENTA); - } -// if (!hits.empty()){ -// frame.save("test.png"); -// } - - if (hits.empty()){ - m_trigger_count = 0; - return false; - } - - m_trigger_count++; - return m_trigger_count >= m_consecutive_detections; -} -#endif - - - - - -} -} -} +/* White Button Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +//#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonSV_WhiteButtonDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + + + +const char* white_button_template_path(WhiteButton type){ + switch (type){ + case WhiteButton::ButtonA: + return "PokemonSV/Buttons/WhiteButtonA.png"; + case WhiteButton::ButtonA_DarkBackground: + return "PokemonSV/Buttons/WhiteButtonA-dark.png"; + case WhiteButton::ButtonB: + return "PokemonSV/Buttons/WhiteButtonB.png"; + case WhiteButton::ButtonX: + return "PokemonSV/Buttons/WhiteButtonX.png"; + case WhiteButton::ButtonY: + return "PokemonSV/Buttons/WhiteButtonY.png"; + case WhiteButton::ButtonMinus: + return "PokemonSV/Buttons/WhiteButtonMinus.png"; + case WhiteButton::ButtonLeft: + return "PokemonSV/Buttons/ArrowLeft.png"; + case WhiteButton::ButtonRight: + return "PokemonSV/Buttons/ArrowRight.png"; + case WhiteButton::ButtonLStick: + return "PokemonSV/Buttons/LStick.png"; + default: + return ""; + } +} + +const WhiteButtonMatcher& get_button_matcher(WhiteButton type){ + switch (type){ + case WhiteButton::ButtonA: + return WhiteButtonMatcher::A(); + case WhiteButton::ButtonA_DarkBackground: + return WhiteButtonMatcher::A_DarkBackground(); + case WhiteButton::ButtonB: + return WhiteButtonMatcher::B(); + case WhiteButton::ButtonX: + return WhiteButtonMatcher::X(); + case WhiteButton::ButtonY: + return WhiteButtonMatcher::Y(); + case WhiteButton::ButtonMinus: + return WhiteButtonMatcher::Minus(); + case WhiteButton::ButtonLeft: + return WhiteButtonMatcher::ArrowLeft(); + case WhiteButton::ButtonRight: + return WhiteButtonMatcher::ArrowRight(); + case WhiteButton::ButtonLStick: + return WhiteButtonMatcher::LStick(); + default: + throw std::runtime_error("No corresponding ButtonMatcher for WhiteButton"); + } +} + + + + +WhiteButtonMatcher::WhiteButtonMatcher(WhiteButton type, size_t min_width, size_t max_width, double max_rmsd) + : WaterfillTemplateMatcher( + white_button_template_path(type), Color(0xff808008), Color(0xffffffff), 100 + ) + , m_min_width(min_width) + , m_min_height(max_width) + , m_max_rmsd(max_rmsd) +{} +const WhiteButtonMatcher& WhiteButtonMatcher::A(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonA, 15, 15, 100); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::A_DarkBackground(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonA_DarkBackground, 15, 15, 100); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::B(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonB, 15, 15, 90); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::X(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonX, 15, 15, 90); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::Y(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonY, 15, 15, 90); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::Minus(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonMinus, 15, 15, 90); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::ArrowLeft(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonLeft, 15, 15, 90); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::ArrowRight(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonRight, 15, 15, 90); + return matcher; +} +const WhiteButtonMatcher& WhiteButtonMatcher::LStick(){ + static WhiteButtonMatcher matcher(WhiteButton::ButtonLStick, 15, 15, 90); + return matcher; +} + + + + + + + +WhiteButtonDetector::WhiteButtonDetector( + Color color, + WhiteButton button, + const ImageFloatBox& box +) + : m_matcher(get_button_matcher(button)) + , m_color(color) + , m_box(box) +{} +void WhiteButtonDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} +bool WhiteButtonDetector::detect(const ImageViewRGB32& screen){ + std::vector hits = detect_all(screen); + return !hits.empty(); +} + +std::vector WhiteButtonDetector::detect_all(const ImageViewRGB32& screen) const{ + ImageViewRGB32 region = extract_box_reference(screen, m_box); + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(region, 0xff808080, 0xffffffff); + + std::vector hits; + + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(50); + WaterfillObject object; + while (iter->find_next(object, false)){ + if (object.min_x == 0 || object.min_y == 0 || + object.max_x == region.width() || object.max_y == region.height() + ){ + continue; + } + double rmsd = m_matcher.rmsd_original(region, object); +// cout << "rmsd = " << rmsd << endl; + if (rmsd < m_matcher.m_max_rmsd){ + hits.emplace_back(translate_to_parent(screen, m_box, object)); + } + } + return hits; +} + + + +#if 0 +WhiteButtonWatcher::~WhiteButtonWatcher() = default; +WhiteButtonWatcher::WhiteButtonWatcher( + Color color, + WhiteButton button, size_t consecutive_detections, + VideoOverlay& overlay, + const ImageFloatBox& box +) + : VisualInferenceCallback("GradientArrowFinder") + , m_overlay(overlay) + , m_detector(color, button, box) + , m_consecutive_detections(consecutive_detections) +{} + +void WhiteButtonWatcher::make_overlays(VideoOverlaySet& items) const{ + m_detector.make_overlays(items); +} +bool WhiteButtonWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + std::vector hits = m_detector.detect_all(frame); +// cout << "arrows = " << arrows.size() << endl; + m_arrows.reset(hits.size()); + for (const ImageFloatBox& hit : hits){ + m_arrows.emplace_back(m_overlay, hit, COLOR_MAGENTA); + } +// if (!hits.empty()){ +// frame.save("test.png"); +// } + + if (hits.empty()){ + m_trigger_count = 0; + return false; + } + + m_trigger_count++; + return m_trigger_count >= m_consecutive_detections; +} +#endif + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h index 95b62650b8..4709f1ab47 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h @@ -1,124 +1,124 @@ -/* White Button Detector - * - * From: https://github.com/PokemonAutomation/ - * - * Warning: This detector is currently very prone to false positives. - * It is much worse than the PLA buttons because these one have transparent - * text which must be stored as zero alpha. - * - */ - -#ifndef PokemonAutomation_PokemonSV_WhiteButtonDetector_H -#define PokemonAutomation_PokemonSV_WhiteButtonDetector_H - -#include -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class WhiteButton{ - ButtonA, - ButtonA_DarkBackground, - ButtonB, - ButtonX, - ButtonY, - ButtonMinus, - ButtonLeft, - ButtonRight, - ButtonLStick, -}; - - -class WhiteButtonMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - WhiteButtonMatcher(WhiteButton type, size_t min_width, size_t max_width, double max_rmsd); - static const WhiteButtonMatcher& A(); - static const WhiteButtonMatcher& A_DarkBackground(); - static const WhiteButtonMatcher& B(); - static const WhiteButtonMatcher& X(); - static const WhiteButtonMatcher& Y(); - static const WhiteButtonMatcher& Minus(); - static const WhiteButtonMatcher& ArrowLeft(); - static const WhiteButtonMatcher& ArrowRight(); - static const WhiteButtonMatcher& LStick(); - - virtual bool check_image(const ImageViewRGB32& image) const override{ - return image.width() >= m_min_width && image.height() >= m_min_height; - }; - - size_t m_min_width; - size_t m_min_height; - double m_max_rmsd; -}; - - -class WhiteButtonDetector : public StaticScreenDetector{ -public: - WhiteButtonDetector( - Color color, - WhiteButton button, - const ImageFloatBox& box - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - std::vector detect_all(const ImageViewRGB32& screen) const; - -protected: - const WhiteButtonMatcher& m_matcher; - Color m_color; - ImageFloatBox m_box; -}; -class WhiteButtonWatcher : public DetectorToFinder{ -public: - WhiteButtonWatcher( - Color color, - WhiteButton button, - const ImageFloatBox& box, - FinderType finder_type = FinderType::PRESENT, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("WhiteButtonWatcher", finder_type, duration, color, button, box) - {} -}; - - -#if 0 -class WhiteButtonWatcher : public VisualInferenceCallback{ -public: - ~WhiteButtonWatcher(); - WhiteButtonWatcher( - Color color, - WhiteButton button, size_t consecutive_detections, - VideoOverlay& overlay, - const ImageFloatBox& box - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - -protected: - VideoOverlay& m_overlay; - WhiteButtonDetector m_detector; - FixedLimitVector m_arrows; - size_t m_consecutive_detections; - size_t m_trigger_count = 0; -}; -#endif - - - -} -} -} -#endif +/* White Button Detector + * + * From: https://github.com/PokemonAutomation/ + * + * Warning: This detector is currently very prone to false positives. + * It is much worse than the PLA buttons because these one have transparent + * text which must be stored as zero alpha. + * + */ + +#ifndef PokemonAutomation_PokemonSV_WhiteButtonDetector_H +#define PokemonAutomation_PokemonSV_WhiteButtonDetector_H + +#include +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class WhiteButton{ + ButtonA, + ButtonA_DarkBackground, + ButtonB, + ButtonX, + ButtonY, + ButtonMinus, + ButtonLeft, + ButtonRight, + ButtonLStick, +}; + + +class WhiteButtonMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + WhiteButtonMatcher(WhiteButton type, size_t min_width, size_t max_width, double max_rmsd); + static const WhiteButtonMatcher& A(); + static const WhiteButtonMatcher& A_DarkBackground(); + static const WhiteButtonMatcher& B(); + static const WhiteButtonMatcher& X(); + static const WhiteButtonMatcher& Y(); + static const WhiteButtonMatcher& Minus(); + static const WhiteButtonMatcher& ArrowLeft(); + static const WhiteButtonMatcher& ArrowRight(); + static const WhiteButtonMatcher& LStick(); + + virtual bool check_image(const ImageViewRGB32& image) const override{ + return image.width() >= m_min_width && image.height() >= m_min_height; + }; + + size_t m_min_width; + size_t m_min_height; + double m_max_rmsd; +}; + + +class WhiteButtonDetector : public StaticScreenDetector{ +public: + WhiteButtonDetector( + Color color, + WhiteButton button, + const ImageFloatBox& box + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + std::vector detect_all(const ImageViewRGB32& screen) const; + +protected: + const WhiteButtonMatcher& m_matcher; + Color m_color; + ImageFloatBox m_box; +}; +class WhiteButtonWatcher : public DetectorToFinder{ +public: + WhiteButtonWatcher( + Color color, + WhiteButton button, + const ImageFloatBox& box, + FinderType finder_type = FinderType::PRESENT, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("WhiteButtonWatcher", finder_type, duration, color, button, box) + {} +}; + + +#if 0 +class WhiteButtonWatcher : public VisualInferenceCallback{ +public: + ~WhiteButtonWatcher(); + WhiteButtonWatcher( + Color color, + WhiteButton button, size_t consecutive_detections, + VideoOverlay& overlay, + const ImageFloatBox& box + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + +protected: + VideoOverlay& m_overlay; + WhiteButtonDetector m_detector; + FixedLimitVector m_arrows; + size_t m_consecutive_detections; + size_t m_trigger_count = 0; +}; +#endif + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.cpp index f8593bb1d1..8dbdab0e30 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.cpp @@ -1,123 +1,123 @@ -/* Zero Gate Warp Prompt Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_ZeroGateWarpPromptDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -ZeroGateWarpPromptDetector::ZeroGateWarpPromptDetector(Color color) - : m_arrow(color, GradientArrowType::RIGHT, {0.5, 0.32, 0.40, 0.39}) -{} - -void ZeroGateWarpPromptDetector::make_overlays(VideoOverlaySet& items) const{ - m_arrow.make_overlays(items); -} -bool ZeroGateWarpPromptDetector::detect(const ImageViewRGB32& screen){ - return detect_location(screen) >= 0; -} -int ZeroGateWarpPromptDetector::detect_location(const ImageViewRGB32& screen) const{ - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ - return -1; - } - - int index = (int)((box.y - 0.337037) / 0.074074 + 0.5); - -// cout << index << endl; - - return index; -} -bool ZeroGateWarpPromptDetector::move_cursor( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int row -) const{ - VideoOverlaySet overlays(stream.overlay()); - make_overlays(overlays); - - size_t consecutive_detection_fails = 0; - size_t moves = 0; - bool target_reached = false; - while (true){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - int current = this->detect_location(screen); - - stream.log("Current Location: " + std::to_string(current)); - - if (current < 0){ - consecutive_detection_fails++; - if (consecutive_detection_fails > 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "ZeroGateWarpPromptDetector::move_cursor(): Unable to detect cursor.", - stream, - screen - ); - } - context.wait_for(std::chrono::milliseconds(50)); - continue; - } - consecutive_detection_fails = 0; - - if (moves >= 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to move to target after 10 moves.", - stream, - screen - ); - } - - // We're done! - if (current == row){ - if (target_reached){ - return true; - }else{ - // Don't return yet. Wait a second to make sure the video is - // in steady state before we return. - target_reached = true; - context.wait_for(std::chrono::seconds(1)); - continue; - } - } - target_reached = false; - - moves++; - - const int rows = 5; - int diff = (rows + current - row) % rows; - if (diff < 3){ - for (int c = 0; c < diff - 1; c++){ - pbf_press_dpad(context, DPAD_UP, 10, 10); - } - pbf_press_dpad(context, DPAD_UP, 20, 30); - }else{ - diff = rows - diff; - for (int c = 0; c < diff - 1; c++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - } - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - } -} - - - - -} -} -} +/* Zero Gate Warp Prompt Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_ZeroGateWarpPromptDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +ZeroGateWarpPromptDetector::ZeroGateWarpPromptDetector(Color color) + : m_arrow(color, GradientArrowType::RIGHT, {0.5, 0.32, 0.40, 0.39}) +{} + +void ZeroGateWarpPromptDetector::make_overlays(VideoOverlaySet& items) const{ + m_arrow.make_overlays(items); +} +bool ZeroGateWarpPromptDetector::detect(const ImageViewRGB32& screen){ + return detect_location(screen) >= 0; +} +int ZeroGateWarpPromptDetector::detect_location(const ImageViewRGB32& screen) const{ + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ + return -1; + } + + int index = (int)((box.y - 0.337037) / 0.074074 + 0.5); + +// cout << index << endl; + + return index; +} +bool ZeroGateWarpPromptDetector::move_cursor( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int row +) const{ + VideoOverlaySet overlays(stream.overlay()); + make_overlays(overlays); + + size_t consecutive_detection_fails = 0; + size_t moves = 0; + bool target_reached = false; + while (true){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + int current = this->detect_location(screen); + + stream.log("Current Location: " + std::to_string(current)); + + if (current < 0){ + consecutive_detection_fails++; + if (consecutive_detection_fails > 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "ZeroGateWarpPromptDetector::move_cursor(): Unable to detect cursor.", + stream, + screen + ); + } + context.wait_for(std::chrono::milliseconds(50)); + continue; + } + consecutive_detection_fails = 0; + + if (moves >= 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to move to target after 10 moves.", + stream, + screen + ); + } + + // We're done! + if (current == row){ + if (target_reached){ + return true; + }else{ + // Don't return yet. Wait a second to make sure the video is + // in steady state before we return. + target_reached = true; + context.wait_for(std::chrono::seconds(1)); + continue; + } + } + target_reached = false; + + moves++; + + const int rows = 5; + int diff = (rows + current - row) % rows; + if (diff < 3){ + for (int c = 0; c < diff - 1; c++){ + pbf_press_dpad(context, DPAD_UP, 10, 10); + } + pbf_press_dpad(context, DPAD_UP, 20, 30); + }else{ + diff = rows - diff; + for (int c = 0; c < diff - 1; c++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + } + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h index 9b6075eea7..38a49f7c37 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h @@ -1,51 +1,51 @@ -/* Zero Gate Warp Prompt Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ZeroGateWarpPromptDetector_H -#define PokemonAutomation_PokemonSV_ZeroGateWarpPromptDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class ZeroGateWarpPromptDetector : public StaticScreenDetector{ -public: - ZeroGateWarpPromptDetector(Color color = COLOR_RED); - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - int detect_location(const ImageViewRGB32& screen) const; - - bool move_cursor( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int row - ) const; - -private: - GradientArrowDetector m_arrow; -}; -class ZeroGateWarpPromptWatcher : public DetectorToFinder{ -public: - ZeroGateWarpPromptWatcher(Color color = COLOR_RED) - : DetectorToFinder("ZeroGateWarpPromptWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - - -} -} -} -#endif +/* Zero Gate Warp Prompt Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ZeroGateWarpPromptDetector_H +#define PokemonAutomation_PokemonSV_ZeroGateWarpPromptDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class ZeroGateWarpPromptDetector : public StaticScreenDetector{ +public: + ZeroGateWarpPromptDetector(Color color = COLOR_RED); + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + int detect_location(const ImageViewRGB32& screen) const; + + bool move_cursor( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int row + ) const; + +private: + GradientArrowDetector m_arrow; +}; +class ZeroGateWarpPromptWatcher : public DetectorToFinder{ +public: + ZeroGateWarpPromptWatcher(Color color = COLOR_RED) + : DetectorToFinder("ZeroGateWarpPromptWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp index 1e5b50844a..730e1b2c7c 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.cpp @@ -1,498 +1,498 @@ -/* Tera Card Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV_TeraCodeReader.h" -#include "PokemonSV_TeraCardDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - - -TeraCardReader::TeraCardReader(Color color) - : m_color(color) - , m_top(0.15, 0.13, 0.40, 0.03) - , m_bottom_left(0.15, 0.80, 0.10, 0.06) - , m_bottom_right(0.73, 0.85, 0.12, 0.02) - , m_label(CARD_LABEL_BOX()) - , m_cursor(0.135, 0.25, 0.05, 0.25) - , m_stars(0.500, 0.555, 0.310, 0.070) - , m_tera_type(color) - , m_silhouette(color) -{} -void TeraCardReader::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_top); - items.add(m_color, m_bottom_left); - items.add(m_color, m_bottom_right); - items.add(m_color, m_label); - items.add(m_color, m_cursor); - items.add(m_color, m_stars); - m_tera_type.make_overlays(items); - m_silhouette.make_overlays(items); -} - -const ImageFloatBox& TeraCardReader::CARD_LABEL_BOX(){ - static ImageFloatBox box(0.75, 0.67, 0.10, 0.05); - return box; -} -bool TeraCardReader::is_card_label(const ImageViewRGB32& screen){ - ImageStats label = image_stats(extract_box_reference(screen, CARD_LABEL_BOX())); - return is_solid(label, {0.370075, 0.369063, 0.260862}) // Paldea Card - || is_solid(label, {0.258888, 0.369491, 0.371621}, 0.15, 15); // Kitakami Card -} - -bool TeraCardReader::detect(const ImageViewRGB32& screen){ - ImageStats top = image_stats(extract_box_reference(screen, m_top)); -// cout << top.average << top.stddev << endl; - if (!is_solid(top, {0.354167, 0.345833, 0.3})){ -// cout << "bad 1" << endl; - return false; - } - - ImageStats bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); -// cout << bottom_left.average << bottom_left.stddev << endl; - if (!is_solid(bottom_left, {0.354167, 0.345833, 0.3})){ -// cout << "bad 2" << endl; - return false; - } - ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << bottom_right.average << bottom_right.stddev << endl; - if (!is_solid(bottom_right, {0.354167, 0.345833, 0.3})){ -// cout << "bad 3" << endl; - return false; - } - - if (euclidean_distance(top.average, bottom_left.average) > 20){ -// cout << "euclidean_distance 0" << endl; - return false; - } - if (euclidean_distance(top.average, bottom_right.average) > 20){ -// cout << "euclidean_distance 1" << endl; - return false; - } - if (euclidean_distance(bottom_left.average, bottom_right.average) > 20){ -// cout << "euclidean_distance 2" << endl; - return false; - } - -// ImageStats label = image_stats(extract_box_reference(screen, m_label)); -// extract_box_reference(screen, m_label).save("test.png"); -// cout << label.average << label.stddev << endl; - if (!is_card_label(screen)){ - return false; - } - - GradientArrowDetector arrow_detector(COLOR_RED, GradientArrowType::RIGHT, m_cursor); - if (!arrow_detector.detect(screen)){ - return false; - } - - return true; -} -uint8_t TeraCardReader::stars( - Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen -) const{ - using namespace Kernels::Waterfill; - - ImageViewRGB32 cropped = extract_box_reference(screen, m_stars); - - ImageViewRGB32 background = extract_box_reference(screen, ImageFloatBox{0.55, 0.62, 0.20, 0.03}); -// background.save("background.png"); - ImageStats background_stats = image_stats(background); - Color background_average = background_stats.average.round(); - - // Iterate through multiple distance filters and find how many - // possible stars are in each one. Then do a majority vote. - const std::vector DISTANCES{70, 80, 90, 100, 110, 120, 130}; - - std::map count_map; - - for (double distance : DISTANCES){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_euclidean(cropped, (uint32_t)background_average, distance); - - matrix.invert(); -// cout << matrix.dump() << endl; - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - - std::list objects; - while (iter->find_next(object, false)){ - // Attempt to merge with existing objects. - ImagePixelBox current(object); - bool changed; - do{ - changed = false; - for (auto iter1 = objects.begin(); iter1 != objects.end();){ - if (current.overlaps_with(*iter1)){ - changed = true; - current.merge_with(*iter1); - objects.erase(iter1); - break; - }else{ - ++iter1; - } - } - }while (changed); - objects.emplace_back(std::move(current)); - } - -#if 0 - static size_t count = 0; - for (const ImagePixelBox& obj : objects){ - extract_box_reference(cropped, obj).save("test-" + std::to_string(count++) + ".png"); - } - cout << "objects.size() = " << objects.size() << endl; -#endif - - - count_map[objects.size()]++; - } - - count_map.erase(0); - - if (count_map.empty()){ - dump_image(logger, info, "ReadStarsFailed", screen); - return 0; - } - - auto best = count_map.begin(); - for (auto iter = count_map.begin(); iter != count_map.end(); ++iter){ - if (iter->first == 0){ - continue; - } - if (iter->second > best->second){ - best = iter; - } - } - - size_t stars = best->first; - - if (1 <= stars && stars <= 7){ - return (uint8_t)stars; - } - - dump_image(logger, info, "ReadStarsFailed", screen); - return 0; -} -std::string TeraCardReader::tera_type( - Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen -) const{ - ImageMatch::ImageMatchResult type = m_tera_type.read(screen); - type.log(logger, 100); - std::string best_type; - if (!type.results.empty()){ - best_type = type.results.begin()->second; - } - if (best_type.empty()){ - dump_image(logger, info, "ReadTypeFailed", screen); - }else if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - dump_debug_image(logger, "PokemonSV/TeraRoller/" + best_type, "", screen); - } - - return best_type; -} -std::set TeraCardReader::pokemon_slug( - Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen -) const{ - ImageMatch::ImageMatchResult silhouette = m_silhouette.read(screen); - silhouette.log(logger, 110); -// std::string best_silhouette; -// if (!silhouette.results.empty()){ -// best_silhouette = silhouette.results.begin()->second; -// } - if (silhouette.results.empty()){ - dump_image(logger, info, "ReadSilhouetteFailed", screen); - } -// else if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ -// dump_debug_image(logger, "PokemonSV/TeraRoller/" + best_silhouette, "", screen); -// } - - std::set results; - for (const auto& item : silhouette.results){ - results.insert(std::move(item.second)); - } - - return results; -} - - - - - - -std::string TeraLobbyNameMatchResult::to_str() const{ - std::string ret; - ret += "\"" + raw_ocr; - if (ret.back() == '\n'){ - ret.pop_back(); - } -// ret += "\" -> \"" + normalized_ocr + "\" == \""; - ret += "\" -> \""; - ret += entry.name; - ret += "\" ("; - if (exact_match){ - ret += "exact match, "; - }else{ - ret += "partial match, "; - } - ret += "log10p = " + tostr_default(log10p) + ")"; - return ret; -} - - - -TeraLobbyReader::TeraLobbyReader(Logger& logger, AsyncDispatcher& dispatcher, Color color) - : m_logger(logger) - , m_dispatcher(dispatcher) - , m_color(color) - , m_bottom_right(0.73, 0.85, 0.12, 0.02) - , m_label(TeraCardReader::CARD_LABEL_BOX()) - , m_cursor(0.135, 0.25, 0.05, 0.25) -// , m_stars(0.500, 0.555, 0.310, 0.070) - , m_timer(0.175, 0.180, 0.100, 0.080) - , m_code(0.310, 0.180, 0.200, 0.080) -{ - for (size_t c = 0; c < 4; c++){ - m_player_spinner[c] = ImageFloatBox{0.157, 0.575 + 0.070*c, 0.037, 0.060}; - m_player_name[c] = ImageFloatBox{0.200, 0.575 + 0.070*c, 0.095, 0.060}; - m_player_mon[c] = ImageFloatBox{0.425, 0.575 + 0.070*c, 0.037, 0.060}; - m_player_ready[c] = ImageFloatBox{0.465, 0.575 + 0.070*c, 0.037, 0.060}; - } -} -void TeraLobbyReader::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_right); - items.add(m_color, m_label); - items.add(m_color, m_cursor); - items.add(m_color, m_timer); - items.add(m_color, m_code); - for (size_t c = 0; c < 4; c++){ - items.add(m_color, m_player_spinner[c]); - items.add(m_color, m_player_name[c]); - items.add(m_color, m_player_mon[c]); - items.add(m_color, m_player_ready[c]); - } -} -bool TeraLobbyReader::detect(const ImageViewRGB32& screen){ - ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << bottom_right.average << bottom_right.stddev << endl; - if (!is_solid(bottom_right, {0.354167, 0.345833, 0.3})){ - return false; - } - -// ImageStats label = image_stats(extract_box_reference(screen, m_label)); -// cout << label.average << label.stddev << endl; - if (!TeraCardReader::is_card_label(screen)){ - return false; - } - - GradientArrowDetector arrow_detector(COLOR_RED, GradientArrowType::RIGHT, m_cursor); - if (!arrow_detector.detect(screen)){ - return false; - } - - if (seconds_left(m_logger, m_dispatcher, screen) < 0){ - return false; - } - - return true; -} - -uint8_t TeraLobbyReader::total_players(const ImageViewRGB32& screen) const{ - uint8_t total = 0; - for (size_t c = 0; c < 4; c++){ - ImageStats player = image_stats(extract_box_reference(screen, m_player_mon[c])); - if (player.stddev.sum() > 80){ - total++; - } - } - return std::max(total, (uint8_t)1); -} -#if 0 -uint8_t TeraLobbyReader::ready_players(const ImageViewRGB32& screen) const{ - uint8_t total = 0; - for (size_t c = 0; c < 4; c++){ - ImageStats player = image_stats(extract_box_reference(screen, m_player_ready[c])); -// cout << "Player " << c << ": " << player.average << player.stddev << endl; - if (player.stddev.sum() > 80){ - total++; - } - } - return total; -} -#endif -uint8_t TeraLobbyReader::ready_joiners(const ImageViewRGB32& screen, uint8_t host_players){ - uint8_t total = 0; - for (size_t c = host_players; c < 4; c++){ - ImageStats player = image_stats(extract_box_reference(screen, m_player_ready[c])); -// cout << "Player " << c << ": " << player.average << player.stddev << endl; - if (player.stddev.sum() > 80){ - total++; - } - } - return total; -} - -int16_t TeraLobbyReader::seconds_left(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_timer); - return read_raid_timer(logger, dispatcher, image); -} -std::string TeraLobbyReader::raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_code); - return read_raid_code(logger, dispatcher, image); -} - -ImageRGB32 filter_name_image(const ImageViewRGB32& image){ - using namespace Kernels::Waterfill; - - const uint32_t COLOR_THRESHOLD = 0xff8f8f8f; - - // Waterfill the image and throw out everything that touches the border. - - ImageRGB32 filtered(image.width(), image.height()); - filtered.fill(0xffffffff); -// cout << image.width() << " x " << image.height() << endl; - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000000, COLOR_THRESHOLD); - { - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(4); - WaterfillObject object; - while (iter->find_next(object, true)){ - auto packed = object.packed_matrix(); -// cout << packed->width() << " x " << packed->height() << " : " << object.min_x << " x " << object.min_y << endl; - - // Touches border. - if (object.min_x == 0 || - object.min_y == 0 || - object.max_x == filtered.width() || - object.max_y == filtered.height() - ){ - continue; - } - filter_by_mask( - std::move(packed), - filtered, object.min_x, object.min_y, - Color(0xff000000), - false - ); - } - } - -// static int c = 0; -// filtered.save("filtered" + std::to_string(c++) + ".png"); - - return filtered; - -// size_t pixels; -// return to_blackwhite_rgb32_range(pixels, image, 0xff000000, COLOR_THRESHOLD, true); -} - - -std::array, 4> TeraLobbyReader::read_names( - Logger& logger, - const std::set& languages, - const ImageViewRGB32& screen -) const{ - std::array, 4> ret; - for (size_t c = 0; c < 4; c++){ - ImageStats sprite = image_stats(extract_box_reference(screen, m_player_mon[c])); - if (sprite.stddev.sum() <= 80){ - continue; - } -// logger.log("Reading player " + std::to_string(c) + "'s name..."); - std::string str = "Player " + std::to_string(c) + ": "; - bool first = true; - for (Language language : languages){ - ImageViewRGB32 box = extract_box_reference(screen, m_player_name[c]); - ImageRGB32 filtered = filter_name_image(box); -// filtered.save("name" + std::to_string(c) + ".png"); - - std::string raw; - for (char ch : OCR::ocr_read(language, filtered)){ - if ((unsigned)ch < 32){ - continue; - } - raw += ch; - } - if (!first){ - str += ", "; - } - first = false; - str += language_data(language).code + "=\"" + raw + "\""; - ret[c][language] = std::move(raw); - } - logger.log(str); - } - return ret; -} - - - - - -#if 0 -TeraLobbyReadyWaiter::TeraLobbyReadyWaiter( - Logger& logger, AsyncDispatcher& dispatcher, - Color color, uint8_t desired_players -) - : TeraLobbyReader(logger, dispatcher, color) - , VisualInferenceCallback("TeraLobbyReadyWaiter") - , m_desired_players(desired_players) - , m_last_known_total_players(-1) -{} - -void TeraLobbyReadyWaiter::make_overlays(VideoOverlaySet& items) const{ - TeraLobbyReader::make_overlays(items); -} -bool TeraLobbyReadyWaiter::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - if (!detect(frame)){ - return false; - } - uint8_t total_players = this->total_players(frame); - uint8_t ready_players = this->ready_players(frame); - m_last_known_total_players.store(total_players); - return ready_players + 1 >= m_desired_players; -} -#endif - - - - - - - - - - - - -} -} -} +/* Tera Card Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV_TeraCodeReader.h" +#include "PokemonSV_TeraCardDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + + +TeraCardReader::TeraCardReader(Color color) + : m_color(color) + , m_top(0.15, 0.13, 0.40, 0.03) + , m_bottom_left(0.15, 0.80, 0.10, 0.06) + , m_bottom_right(0.73, 0.85, 0.12, 0.02) + , m_label(CARD_LABEL_BOX()) + , m_cursor(0.135, 0.25, 0.05, 0.25) + , m_stars(0.500, 0.555, 0.310, 0.070) + , m_tera_type(color) + , m_silhouette(color) +{} +void TeraCardReader::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_top); + items.add(m_color, m_bottom_left); + items.add(m_color, m_bottom_right); + items.add(m_color, m_label); + items.add(m_color, m_cursor); + items.add(m_color, m_stars); + m_tera_type.make_overlays(items); + m_silhouette.make_overlays(items); +} + +const ImageFloatBox& TeraCardReader::CARD_LABEL_BOX(){ + static ImageFloatBox box(0.75, 0.67, 0.10, 0.05); + return box; +} +bool TeraCardReader::is_card_label(const ImageViewRGB32& screen){ + ImageStats label = image_stats(extract_box_reference(screen, CARD_LABEL_BOX())); + return is_solid(label, {0.370075, 0.369063, 0.260862}) // Paldea Card + || is_solid(label, {0.258888, 0.369491, 0.371621}, 0.15, 15); // Kitakami Card +} + +bool TeraCardReader::detect(const ImageViewRGB32& screen){ + ImageStats top = image_stats(extract_box_reference(screen, m_top)); +// cout << top.average << top.stddev << endl; + if (!is_solid(top, {0.354167, 0.345833, 0.3})){ +// cout << "bad 1" << endl; + return false; + } + + ImageStats bottom_left = image_stats(extract_box_reference(screen, m_bottom_left)); +// cout << bottom_left.average << bottom_left.stddev << endl; + if (!is_solid(bottom_left, {0.354167, 0.345833, 0.3})){ +// cout << "bad 2" << endl; + return false; + } + ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << bottom_right.average << bottom_right.stddev << endl; + if (!is_solid(bottom_right, {0.354167, 0.345833, 0.3})){ +// cout << "bad 3" << endl; + return false; + } + + if (euclidean_distance(top.average, bottom_left.average) > 20){ +// cout << "euclidean_distance 0" << endl; + return false; + } + if (euclidean_distance(top.average, bottom_right.average) > 20){ +// cout << "euclidean_distance 1" << endl; + return false; + } + if (euclidean_distance(bottom_left.average, bottom_right.average) > 20){ +// cout << "euclidean_distance 2" << endl; + return false; + } + +// ImageStats label = image_stats(extract_box_reference(screen, m_label)); +// extract_box_reference(screen, m_label).save("test.png"); +// cout << label.average << label.stddev << endl; + if (!is_card_label(screen)){ + return false; + } + + GradientArrowDetector arrow_detector(COLOR_RED, GradientArrowType::RIGHT, m_cursor); + if (!arrow_detector.detect(screen)){ + return false; + } + + return true; +} +uint8_t TeraCardReader::stars( + Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen +) const{ + using namespace Kernels::Waterfill; + + ImageViewRGB32 cropped = extract_box_reference(screen, m_stars); + + ImageViewRGB32 background = extract_box_reference(screen, ImageFloatBox{0.55, 0.62, 0.20, 0.03}); +// background.save("background.png"); + ImageStats background_stats = image_stats(background); + Color background_average = background_stats.average.round(); + + // Iterate through multiple distance filters and find how many + // possible stars are in each one. Then do a majority vote. + const std::vector DISTANCES{70, 80, 90, 100, 110, 120, 130}; + + std::map count_map; + + for (double distance : DISTANCES){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_euclidean(cropped, (uint32_t)background_average, distance); + + matrix.invert(); +// cout << matrix.dump() << endl; + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + + std::list objects; + while (iter->find_next(object, false)){ + // Attempt to merge with existing objects. + ImagePixelBox current(object); + bool changed; + do{ + changed = false; + for (auto iter1 = objects.begin(); iter1 != objects.end();){ + if (current.overlaps_with(*iter1)){ + changed = true; + current.merge_with(*iter1); + objects.erase(iter1); + break; + }else{ + ++iter1; + } + } + }while (changed); + objects.emplace_back(std::move(current)); + } + +#if 0 + static size_t count = 0; + for (const ImagePixelBox& obj : objects){ + extract_box_reference(cropped, obj).save("test-" + std::to_string(count++) + ".png"); + } + cout << "objects.size() = " << objects.size() << endl; +#endif + + + count_map[objects.size()]++; + } + + count_map.erase(0); + + if (count_map.empty()){ + dump_image(logger, info, "ReadStarsFailed", screen); + return 0; + } + + auto best = count_map.begin(); + for (auto iter = count_map.begin(); iter != count_map.end(); ++iter){ + if (iter->first == 0){ + continue; + } + if (iter->second > best->second){ + best = iter; + } + } + + size_t stars = best->first; + + if (1 <= stars && stars <= 7){ + return (uint8_t)stars; + } + + dump_image(logger, info, "ReadStarsFailed", screen); + return 0; +} +std::string TeraCardReader::tera_type( + Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen +) const{ + ImageMatch::ImageMatchResult type = m_tera_type.read(screen); + type.log(logger, 100); + std::string best_type; + if (!type.results.empty()){ + best_type = type.results.begin()->second; + } + if (best_type.empty()){ + dump_image(logger, info, "ReadTypeFailed", screen); + }else if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + dump_debug_image(logger, "PokemonSV/TeraRoller/" + best_type, "", screen); + } + + return best_type; +} +std::set TeraCardReader::pokemon_slug( + Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen +) const{ + ImageMatch::ImageMatchResult silhouette = m_silhouette.read(screen); + silhouette.log(logger, 110); +// std::string best_silhouette; +// if (!silhouette.results.empty()){ +// best_silhouette = silhouette.results.begin()->second; +// } + if (silhouette.results.empty()){ + dump_image(logger, info, "ReadSilhouetteFailed", screen); + } +// else if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ +// dump_debug_image(logger, "PokemonSV/TeraRoller/" + best_silhouette, "", screen); +// } + + std::set results; + for (const auto& item : silhouette.results){ + results.insert(std::move(item.second)); + } + + return results; +} + + + + + + +std::string TeraLobbyNameMatchResult::to_str() const{ + std::string ret; + ret += "\"" + raw_ocr; + if (ret.back() == '\n'){ + ret.pop_back(); + } +// ret += "\" -> \"" + normalized_ocr + "\" == \""; + ret += "\" -> \""; + ret += entry.name; + ret += "\" ("; + if (exact_match){ + ret += "exact match, "; + }else{ + ret += "partial match, "; + } + ret += "log10p = " + tostr_default(log10p) + ")"; + return ret; +} + + + +TeraLobbyReader::TeraLobbyReader(Logger& logger, AsyncDispatcher& dispatcher, Color color) + : m_logger(logger) + , m_dispatcher(dispatcher) + , m_color(color) + , m_bottom_right(0.73, 0.85, 0.12, 0.02) + , m_label(TeraCardReader::CARD_LABEL_BOX()) + , m_cursor(0.135, 0.25, 0.05, 0.25) +// , m_stars(0.500, 0.555, 0.310, 0.070) + , m_timer(0.175, 0.180, 0.100, 0.080) + , m_code(0.310, 0.180, 0.200, 0.080) +{ + for (size_t c = 0; c < 4; c++){ + m_player_spinner[c] = ImageFloatBox{0.157, 0.575 + 0.070*c, 0.037, 0.060}; + m_player_name[c] = ImageFloatBox{0.200, 0.575 + 0.070*c, 0.095, 0.060}; + m_player_mon[c] = ImageFloatBox{0.425, 0.575 + 0.070*c, 0.037, 0.060}; + m_player_ready[c] = ImageFloatBox{0.465, 0.575 + 0.070*c, 0.037, 0.060}; + } +} +void TeraLobbyReader::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_right); + items.add(m_color, m_label); + items.add(m_color, m_cursor); + items.add(m_color, m_timer); + items.add(m_color, m_code); + for (size_t c = 0; c < 4; c++){ + items.add(m_color, m_player_spinner[c]); + items.add(m_color, m_player_name[c]); + items.add(m_color, m_player_mon[c]); + items.add(m_color, m_player_ready[c]); + } +} +bool TeraLobbyReader::detect(const ImageViewRGB32& screen){ + ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << bottom_right.average << bottom_right.stddev << endl; + if (!is_solid(bottom_right, {0.354167, 0.345833, 0.3})){ + return false; + } + +// ImageStats label = image_stats(extract_box_reference(screen, m_label)); +// cout << label.average << label.stddev << endl; + if (!TeraCardReader::is_card_label(screen)){ + return false; + } + + GradientArrowDetector arrow_detector(COLOR_RED, GradientArrowType::RIGHT, m_cursor); + if (!arrow_detector.detect(screen)){ + return false; + } + + if (seconds_left(m_logger, m_dispatcher, screen) < 0){ + return false; + } + + return true; +} + +uint8_t TeraLobbyReader::total_players(const ImageViewRGB32& screen) const{ + uint8_t total = 0; + for (size_t c = 0; c < 4; c++){ + ImageStats player = image_stats(extract_box_reference(screen, m_player_mon[c])); + if (player.stddev.sum() > 80){ + total++; + } + } + return std::max(total, (uint8_t)1); +} +#if 0 +uint8_t TeraLobbyReader::ready_players(const ImageViewRGB32& screen) const{ + uint8_t total = 0; + for (size_t c = 0; c < 4; c++){ + ImageStats player = image_stats(extract_box_reference(screen, m_player_ready[c])); +// cout << "Player " << c << ": " << player.average << player.stddev << endl; + if (player.stddev.sum() > 80){ + total++; + } + } + return total; +} +#endif +uint8_t TeraLobbyReader::ready_joiners(const ImageViewRGB32& screen, uint8_t host_players){ + uint8_t total = 0; + for (size_t c = host_players; c < 4; c++){ + ImageStats player = image_stats(extract_box_reference(screen, m_player_ready[c])); +// cout << "Player " << c << ": " << player.average << player.stddev << endl; + if (player.stddev.sum() > 80){ + total++; + } + } + return total; +} + +int16_t TeraLobbyReader::seconds_left(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_timer); + return read_raid_timer(logger, dispatcher, image); +} +std::string TeraLobbyReader::raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_code); + return read_raid_code(logger, dispatcher, image); +} + +ImageRGB32 filter_name_image(const ImageViewRGB32& image){ + using namespace Kernels::Waterfill; + + const uint32_t COLOR_THRESHOLD = 0xff8f8f8f; + + // Waterfill the image and throw out everything that touches the border. + + ImageRGB32 filtered(image.width(), image.height()); + filtered.fill(0xffffffff); +// cout << image.width() << " x " << image.height() << endl; + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000000, COLOR_THRESHOLD); + { + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(4); + WaterfillObject object; + while (iter->find_next(object, true)){ + auto packed = object.packed_matrix(); +// cout << packed->width() << " x " << packed->height() << " : " << object.min_x << " x " << object.min_y << endl; + + // Touches border. + if (object.min_x == 0 || + object.min_y == 0 || + object.max_x == filtered.width() || + object.max_y == filtered.height() + ){ + continue; + } + filter_by_mask( + std::move(packed), + filtered, object.min_x, object.min_y, + Color(0xff000000), + false + ); + } + } + +// static int c = 0; +// filtered.save("filtered" + std::to_string(c++) + ".png"); + + return filtered; + +// size_t pixels; +// return to_blackwhite_rgb32_range(pixels, image, 0xff000000, COLOR_THRESHOLD, true); +} + + +std::array, 4> TeraLobbyReader::read_names( + Logger& logger, + const std::set& languages, + const ImageViewRGB32& screen +) const{ + std::array, 4> ret; + for (size_t c = 0; c < 4; c++){ + ImageStats sprite = image_stats(extract_box_reference(screen, m_player_mon[c])); + if (sprite.stddev.sum() <= 80){ + continue; + } +// logger.log("Reading player " + std::to_string(c) + "'s name..."); + std::string str = "Player " + std::to_string(c) + ": "; + bool first = true; + for (Language language : languages){ + ImageViewRGB32 box = extract_box_reference(screen, m_player_name[c]); + ImageRGB32 filtered = filter_name_image(box); +// filtered.save("name" + std::to_string(c) + ".png"); + + std::string raw; + for (char ch : OCR::ocr_read(language, filtered)){ + if ((unsigned)ch < 32){ + continue; + } + raw += ch; + } + if (!first){ + str += ", "; + } + first = false; + str += language_data(language).code + "=\"" + raw + "\""; + ret[c][language] = std::move(raw); + } + logger.log(str); + } + return ret; +} + + + + + +#if 0 +TeraLobbyReadyWaiter::TeraLobbyReadyWaiter( + Logger& logger, AsyncDispatcher& dispatcher, + Color color, uint8_t desired_players +) + : TeraLobbyReader(logger, dispatcher, color) + , VisualInferenceCallback("TeraLobbyReadyWaiter") + , m_desired_players(desired_players) + , m_last_known_total_players(-1) +{} + +void TeraLobbyReadyWaiter::make_overlays(VideoOverlaySet& items) const{ + TeraLobbyReader::make_overlays(items); +} +bool TeraLobbyReadyWaiter::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (!detect(frame)){ + return false; + } + uint8_t total_players = this->total_players(frame); + uint8_t ready_players = this->ready_players(frame); + m_last_known_total_players.store(total_players); + return ready_players + 1 >= m_desired_players; +} +#endif + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h index 9a142d4374..0fbdf91bad 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h @@ -1,169 +1,169 @@ -/* Tera Card Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraCardDetector_H -#define PokemonAutomation_PokemonSV_TeraCardDetector_H - -#include "Common/Cpp/Color.h" -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -//#include "CommonFramework/InferenceInfra/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSV/Options/PokemonSV_PlayerList.h" -#include "PokemonSV_TeraTypeReader.h" -#include "PokemonSV_TeraSilhouetteReader.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -ImageRGB32 filter_name_image(const ImageViewRGB32& image); - - - -class TeraCardReader : public StaticScreenDetector{ -public: - TeraCardReader(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - uint8_t stars( - Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen - ) const; - std::string tera_type( - Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen - ) const; - std::set pokemon_slug( - Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen - ) const; - - static const ImageFloatBox& CARD_LABEL_BOX(); - static bool is_card_label(const ImageViewRGB32& screen); - -private: - Color m_color; - ImageFloatBox m_top; - ImageFloatBox m_bottom_left; - ImageFloatBox m_bottom_right; - ImageFloatBox m_label; - ImageFloatBox m_cursor; - - ImageFloatBox m_stars; - TeraTypeReader m_tera_type; - TeraSilhouetteReader m_silhouette; -}; -class TeraCardWatcher : public DetectorToFinder{ -public: - TeraCardWatcher(Color color = COLOR_RED, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) - : DetectorToFinder("TeraCardFinder", duration, color) - {} -}; - - - - -struct TeraLobbyNameMatchResult{ - PlayerListRowSnapshot entry; - std::string banlist_source; - - std::string raw_ocr; - std::string normalized_ocr; - double log10p; - bool exact_match; - std::string notes; - - std::string to_str() const; -}; - - - -class TeraLobbyReader : public StaticScreenDetector{ -public: - TeraLobbyReader(Logger& logger, AsyncDispatcher& dispatcher, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - // Returns true if we are on an active lobby. - virtual bool detect(const ImageViewRGB32& screen) override; - - uint8_t total_players(const ImageViewRGB32& screen) const; -// uint8_t ready_players(const ImageViewRGB32& screen) const; - uint8_t ready_joiners(const ImageViewRGB32& screen, uint8_t host_players); - - int16_t seconds_left(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; - std::string raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; - - // OCR the player names in all the specified languages. - // The returned strings are raw OCR output and are unprocessed. - std::array, 4> read_names( - Logger& logger, - const std::set& languages, - const ImageViewRGB32& screen - ) const; - - -private: - Logger& m_logger; - AsyncDispatcher& m_dispatcher; - Color m_color; - ImageFloatBox m_bottom_right; - ImageFloatBox m_label; - ImageFloatBox m_cursor; -// ImageFloatBox m_stars; - - ImageFloatBox m_timer; - ImageFloatBox m_code; - - ImageFloatBox m_player_spinner[4]; - ImageFloatBox m_player_name[4]; - ImageFloatBox m_player_mon[4]; - ImageFloatBox m_player_ready[4]; -}; -class TeraLobbyWatcher : public DetectorToFinder{ -public: - TeraLobbyWatcher( - Logger& logger, AsyncDispatcher& dispatcher, - Color color = COLOR_RED, std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("TeraLobbyFinder", duration, logger, dispatcher, color) - {} -}; - -#if 0 -class TeraLobbyReadyWaiter : public TeraLobbyReader, public VisualInferenceCallback{ -public: - TeraLobbyReadyWaiter( - Logger& logger, AsyncDispatcher& dispatcher, - Color color, uint8_t desired_players - ); - - int8_t last_known_total_players() const{ - return m_last_known_total_players.load(std::memory_order_relaxed); - } - int8_t last_known_ready_players() const{ - return m_last_known_ready_players.load(std::memory_order_relaxed); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - uint8_t m_desired_players; - std::atomic m_last_known_total_players; - std::atomic m_last_known_ready_players; -}; -#endif - - - -} -} -} -#endif +/* Tera Card Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraCardDetector_H +#define PokemonAutomation_PokemonSV_TeraCardDetector_H + +#include "Common/Cpp/Color.h" +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +//#include "CommonFramework/InferenceInfra/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSV/Options/PokemonSV_PlayerList.h" +#include "PokemonSV_TeraTypeReader.h" +#include "PokemonSV_TeraSilhouetteReader.h" + +namespace PokemonAutomation{ + class AsyncDispatcher; + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +ImageRGB32 filter_name_image(const ImageViewRGB32& image); + + + +class TeraCardReader : public StaticScreenDetector{ +public: + TeraCardReader(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + uint8_t stars( + Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen + ) const; + std::string tera_type( + Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen + ) const; + std::set pokemon_slug( + Logger& logger, const ProgramInfo& info, const ImageViewRGB32& screen + ) const; + + static const ImageFloatBox& CARD_LABEL_BOX(); + static bool is_card_label(const ImageViewRGB32& screen); + +private: + Color m_color; + ImageFloatBox m_top; + ImageFloatBox m_bottom_left; + ImageFloatBox m_bottom_right; + ImageFloatBox m_label; + ImageFloatBox m_cursor; + + ImageFloatBox m_stars; + TeraTypeReader m_tera_type; + TeraSilhouetteReader m_silhouette; +}; +class TeraCardWatcher : public DetectorToFinder{ +public: + TeraCardWatcher(Color color = COLOR_RED, std::chrono::milliseconds duration = std::chrono::milliseconds(250)) + : DetectorToFinder("TeraCardFinder", duration, color) + {} +}; + + + + +struct TeraLobbyNameMatchResult{ + PlayerListRowSnapshot entry; + std::string banlist_source; + + std::string raw_ocr; + std::string normalized_ocr; + double log10p; + bool exact_match; + std::string notes; + + std::string to_str() const; +}; + + + +class TeraLobbyReader : public StaticScreenDetector{ +public: + TeraLobbyReader(Logger& logger, AsyncDispatcher& dispatcher, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + // Returns true if we are on an active lobby. + virtual bool detect(const ImageViewRGB32& screen) override; + + uint8_t total_players(const ImageViewRGB32& screen) const; +// uint8_t ready_players(const ImageViewRGB32& screen) const; + uint8_t ready_joiners(const ImageViewRGB32& screen, uint8_t host_players); + + int16_t seconds_left(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; + std::string raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& screen) const; + + // OCR the player names in all the specified languages. + // The returned strings are raw OCR output and are unprocessed. + std::array, 4> read_names( + Logger& logger, + const std::set& languages, + const ImageViewRGB32& screen + ) const; + + +private: + Logger& m_logger; + AsyncDispatcher& m_dispatcher; + Color m_color; + ImageFloatBox m_bottom_right; + ImageFloatBox m_label; + ImageFloatBox m_cursor; +// ImageFloatBox m_stars; + + ImageFloatBox m_timer; + ImageFloatBox m_code; + + ImageFloatBox m_player_spinner[4]; + ImageFloatBox m_player_name[4]; + ImageFloatBox m_player_mon[4]; + ImageFloatBox m_player_ready[4]; +}; +class TeraLobbyWatcher : public DetectorToFinder{ +public: + TeraLobbyWatcher( + Logger& logger, AsyncDispatcher& dispatcher, + Color color = COLOR_RED, std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("TeraLobbyFinder", duration, logger, dispatcher, color) + {} +}; + +#if 0 +class TeraLobbyReadyWaiter : public TeraLobbyReader, public VisualInferenceCallback{ +public: + TeraLobbyReadyWaiter( + Logger& logger, AsyncDispatcher& dispatcher, + Color color, uint8_t desired_players + ); + + int8_t last_known_total_players() const{ + return m_last_known_total_players.load(std::memory_order_relaxed); + } + int8_t last_known_ready_players() const{ + return m_last_known_ready_players.load(std::memory_order_relaxed); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + uint8_t m_desired_players; + std::atomic m_last_known_total_players; + std::atomic m_last_known_ready_players; +}; +#endif + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp index 55e9d7e483..a13dec3449 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.cpp @@ -1,346 +1,346 @@ -/* Tera Code Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/ImageManip.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "PokemonSV_TeraCodeReader.h" - -//#define PA_ENABLE_CODE_DEBUG - -#ifdef PA_ENABLE_CODE_DEBUG -#include -using std::cout; -using std::endl; -#endif - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class CharacterTemplates{ - CharacterTemplates() - : ENG_5(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-5-eng.png") - , ENG_S(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-S-eng.png") - , CHI_5(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-5-chi.png") - , CHI_S(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-S-chi.png") - {} - -public: - static const CharacterTemplates& instance(){ - static CharacterTemplates templates; - return templates; - } - - ImageMatch::ExactImageMatcher ENG_5; - ImageMatch::ExactImageMatcher ENG_S; - ImageMatch::ExactImageMatcher CHI_5; - ImageMatch::ExactImageMatcher CHI_S; -}; - -void preload_code_templates(){ - CharacterTemplates::instance(); -} - - - - - -char read_5S( - const ImageViewRGB32& image, - const Kernels::Waterfill::WaterfillObject& object, char OCR_result -){ - // 5 and S are commonly misread as each other. Here we try an extra step to - // distinguish them. - -// cout << matrix.dump() << endl; - -// cout << (object.center_of_gravity_x() - object.min_x) / object.width() << ", " << (object.center_of_gravity_y() - object.min_y) / object.height() << endl; - - const CharacterTemplates& templates = CharacterTemplates::instance(); - - ImageViewRGB32 cropped = extract_box_reference(image, object); -// static int count = 0; -// cropped.save("testC-" + std::to_string(count++) + ".png"); - - double best_rmsd = 1000; - char best_result = OCR_result; - - double rmsd; - - rmsd = templates.ENG_5.rmsd(cropped); -// cout << "eng-5 = " << rmsd << endl; - if (best_rmsd > rmsd){ - best_rmsd = rmsd; - best_result = '5'; - } - - rmsd = templates.ENG_S.rmsd(cropped); -// cout << "eng-S = " << rmsd << endl; - if (best_rmsd > rmsd){ - best_rmsd = rmsd; - best_result = 'S'; - } - - rmsd = templates.CHI_5.rmsd(cropped); -// cout << "chi-5 = " << rmsd << endl; - if (best_rmsd > rmsd){ - best_rmsd = rmsd; - best_result = '5'; - } - - rmsd = templates.CHI_S.rmsd(cropped); -// cout << "chi-S = " << rmsd << endl; - if (best_rmsd > rmsd){ -// best_rmsd = rmsd; - best_result = 'S'; - } - - return best_result; - -#if 0 - PackedBinaryMatrix matrix = object.packed_matrix(); - - size_t width = matrix.width(); - size_t height = matrix.height(); - - for (size_t row = 0; row < height; row++){ - size_t top_black_pixels = 0; - for (size_t c = 0; c < width; c++){ - if (matrix.get(c, 0)){ - top_black_pixels++; - } - } - double ratio = (double)top_black_pixels / width; - cout << "top_black_pixels = " << top_black_pixels << ", " << ratio << endl; - if (ratio > 0.70){ - return '5'; - } - if (ratio > 0.10){ - return 'S'; - } - } - - return OCR_result; -#endif -} - - -struct WaterfillOCRResult{ - Kernels::Waterfill::WaterfillObject object; - std::string ocr; -}; - - -std::vector waterfill_OCR( - AsyncDispatcher& dispatcher, - const ImageViewRGB32& image, - uint32_t threshold -){ - using namespace Kernels::Waterfill; - - // Direct OCR is unreliable. Instead, we will waterfill each character - // to isolate them, then OCR them individually. - - ImageRGB32 filtered = to_blackwhite_rgb32_range(image, true, 0xff000000, threshold); - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000000, threshold); - - std::map map; - { - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(20); - WaterfillObject object; - while (map.size() < 16 && iter->find_next(object, true)){ - map.emplace(object.min_x, std::move(object)); - } - } - - std::vector ret; - for (auto& item : map){ - ret.emplace_back(WaterfillOCRResult{std::move(item.second), ""}); - } - - dispatcher.run_in_parallel( - 0, ret.size(), - [&](size_t index){ - WaterfillObject& object = ret[index].object; - ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); - PackedBinaryMatrix tmp(object.packed_matrix()); - filter_by_mask(tmp, cropped, Color(0xffffffff), true); - ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); - ret[index].ocr = OCR::ocr_read(Language::English, padded); - } - ); - -#ifdef PA_ENABLE_CODE_DEBUG - static size_t count = 0; - for (size_t c = 0; c < ret.size(); c++){ - cout << ret[c].ocr << endl; - ImageRGB32 cropped = extract_box_reference(filtered, ret[c].object).copy(); - filter_by_mask(ret[c].object.packed_matrix(), cropped, Color(0xffffffff), true); - ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); - padded.save("letter-" + std::to_string(count) + ".png"); - count++; - } -#endif - - return ret; -} - - -int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image){ - std::vector characters = waterfill_OCR(dispatcher, image, 0xff7f7f7f); - -// cout << "map.size() = " << map.size() << endl; -// for (auto& item : map){ -// cout << item.second << endl; -// } - - static const std::map SUBSTITUTIONS{ - {'I', '1'}, - {'i', '1'}, - {'l', '1'}, - {'O', '0'}, - {'S', '5'}, - {'s', '5'}, - {'/', '7'}, - {']', '1'}, - }; - - std::string raw; - std::string normalized; - for (const auto& item : characters){ - const std::string& ocr = item.ocr; - if (ocr.empty()){ - continue; - } - if ((uint8_t)ocr.back() < (uint8_t)32){ - raw += ocr.substr(0, ocr.size() - 1); - }else{ - raw += ocr; - } - - char ch = ocr[0]; - - // Character substitution. - auto iter = SUBSTITUTIONS.find(ch); - if (iter != SUBSTITUTIONS.end()){ - ch = iter->second; - } - - if ('0' <= ch && ch <= '9'){ - normalized += ch; - } - } - - std::string log = "Timer OCR: \"" + raw + "\" -> \"" + normalized + "\""; - if (normalized.size() != 3){ - logger.log(log, COLOR_RED); - return -1; - } - - logger.log(log, COLOR_BLUE); - - int16_t ret = 60 * (normalized[0] - '0'); - ret += 10 * (normalized[1] - '0'); - ret += normalized[2] - '0'; - - return ret; -} - - -std::string read_raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image){ - std::vector filters{ - 0xff5f5f5f, - 0xff7f7f7f, - }; - - for (uint32_t filter : filters){ - std::vector characters = waterfill_OCR(dispatcher, image, filter); - - static const std::map SUBSTITUTIONS{ - {'I', '1'}, - {'i', '1'}, - {'l', '1'}, - {'O', '0'}, - {'Z', 'S'}, - {'\\', 'V'}, - {'/', '7'}, - {']', '1'}, - {')', 'J'}, - {'(', 'K'}, - {'[', 'C'}, - }; - - bool contains_letters = false; - - std::string raw; - std::string normalized; - for (const auto& item : characters){ - const std::string& ocr = item.ocr; - if (ocr.empty()){ - continue; - } - if ((uint8_t)ocr.back() < (uint8_t)32){ - raw += ocr.substr(0, ocr.size() - 1); - }else{ - raw += ocr; - } - - char ch = ocr[0]; - - // Upper case. - if ('a' <= ch && ch <= 'z'){ - ch -= 'a' - 'A'; - } - - // Character substitution. - auto iter = SUBSTITUTIONS.find(ch); - if (iter != SUBSTITUTIONS.end()){ - ch = iter->second; - } - - // Distinguish 5 and S. - switch (ch){ - case '5': - case 'S': - ch = read_5S(image, item.object, ch); - } - - contains_letters |= 'A' <= ch && ch <= 'Z'; - - normalized += ch; - } - - std::string log = "Code OCR: \"" + raw + "\" -> \"" + normalized + "\""; - size_t length = normalized.size(); - if ((contains_letters && length == 6) || - (!contains_letters && (length == 4 || length == 6 || length == 8)) - ){ - logger.log(log, COLOR_BLUE); - return normalized; - } - logger.log(log, COLOR_RED); - } - - return ""; -} - - - -} -} -} +/* Tera Code Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/ImageManip.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "PokemonSV_TeraCodeReader.h" + +//#define PA_ENABLE_CODE_DEBUG + +#ifdef PA_ENABLE_CODE_DEBUG +#include +using std::cout; +using std::endl; +#endif + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class CharacterTemplates{ + CharacterTemplates() + : ENG_5(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-5-eng.png") + , ENG_S(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-S-eng.png") + , CHI_5(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-5-chi.png") + , CHI_S(RESOURCE_PATH() + "PokemonSV/TeraCode/TeraCode-S-chi.png") + {} + +public: + static const CharacterTemplates& instance(){ + static CharacterTemplates templates; + return templates; + } + + ImageMatch::ExactImageMatcher ENG_5; + ImageMatch::ExactImageMatcher ENG_S; + ImageMatch::ExactImageMatcher CHI_5; + ImageMatch::ExactImageMatcher CHI_S; +}; + +void preload_code_templates(){ + CharacterTemplates::instance(); +} + + + + + +char read_5S( + const ImageViewRGB32& image, + const Kernels::Waterfill::WaterfillObject& object, char OCR_result +){ + // 5 and S are commonly misread as each other. Here we try an extra step to + // distinguish them. + +// cout << matrix.dump() << endl; + +// cout << (object.center_of_gravity_x() - object.min_x) / object.width() << ", " << (object.center_of_gravity_y() - object.min_y) / object.height() << endl; + + const CharacterTemplates& templates = CharacterTemplates::instance(); + + ImageViewRGB32 cropped = extract_box_reference(image, object); +// static int count = 0; +// cropped.save("testC-" + std::to_string(count++) + ".png"); + + double best_rmsd = 1000; + char best_result = OCR_result; + + double rmsd; + + rmsd = templates.ENG_5.rmsd(cropped); +// cout << "eng-5 = " << rmsd << endl; + if (best_rmsd > rmsd){ + best_rmsd = rmsd; + best_result = '5'; + } + + rmsd = templates.ENG_S.rmsd(cropped); +// cout << "eng-S = " << rmsd << endl; + if (best_rmsd > rmsd){ + best_rmsd = rmsd; + best_result = 'S'; + } + + rmsd = templates.CHI_5.rmsd(cropped); +// cout << "chi-5 = " << rmsd << endl; + if (best_rmsd > rmsd){ + best_rmsd = rmsd; + best_result = '5'; + } + + rmsd = templates.CHI_S.rmsd(cropped); +// cout << "chi-S = " << rmsd << endl; + if (best_rmsd > rmsd){ +// best_rmsd = rmsd; + best_result = 'S'; + } + + return best_result; + +#if 0 + PackedBinaryMatrix matrix = object.packed_matrix(); + + size_t width = matrix.width(); + size_t height = matrix.height(); + + for (size_t row = 0; row < height; row++){ + size_t top_black_pixels = 0; + for (size_t c = 0; c < width; c++){ + if (matrix.get(c, 0)){ + top_black_pixels++; + } + } + double ratio = (double)top_black_pixels / width; + cout << "top_black_pixels = " << top_black_pixels << ", " << ratio << endl; + if (ratio > 0.70){ + return '5'; + } + if (ratio > 0.10){ + return 'S'; + } + } + + return OCR_result; +#endif +} + + +struct WaterfillOCRResult{ + Kernels::Waterfill::WaterfillObject object; + std::string ocr; +}; + + +std::vector waterfill_OCR( + AsyncDispatcher& dispatcher, + const ImageViewRGB32& image, + uint32_t threshold +){ + using namespace Kernels::Waterfill; + + // Direct OCR is unreliable. Instead, we will waterfill each character + // to isolate them, then OCR them individually. + + ImageRGB32 filtered = to_blackwhite_rgb32_range(image, true, 0xff000000, threshold); + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(image, 0xff000000, threshold); + + std::map map; + { + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(20); + WaterfillObject object; + while (map.size() < 16 && iter->find_next(object, true)){ + map.emplace(object.min_x, std::move(object)); + } + } + + std::vector ret; + for (auto& item : map){ + ret.emplace_back(WaterfillOCRResult{std::move(item.second), ""}); + } + + dispatcher.run_in_parallel( + 0, ret.size(), + [&](size_t index){ + WaterfillObject& object = ret[index].object; + ImageRGB32 cropped = extract_box_reference(filtered, object).copy(); + PackedBinaryMatrix tmp(object.packed_matrix()); + filter_by_mask(tmp, cropped, Color(0xffffffff), true); + ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); + ret[index].ocr = OCR::ocr_read(Language::English, padded); + } + ); + +#ifdef PA_ENABLE_CODE_DEBUG + static size_t count = 0; + for (size_t c = 0; c < ret.size(); c++){ + cout << ret[c].ocr << endl; + ImageRGB32 cropped = extract_box_reference(filtered, ret[c].object).copy(); + filter_by_mask(ret[c].object.packed_matrix(), cropped, Color(0xffffffff), true); + ImageRGB32 padded = pad_image(cropped, cropped.width(), 0xffffffff); + padded.save("letter-" + std::to_string(count) + ".png"); + count++; + } +#endif + + return ret; +} + + +int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image){ + std::vector characters = waterfill_OCR(dispatcher, image, 0xff7f7f7f); + +// cout << "map.size() = " << map.size() << endl; +// for (auto& item : map){ +// cout << item.second << endl; +// } + + static const std::map SUBSTITUTIONS{ + {'I', '1'}, + {'i', '1'}, + {'l', '1'}, + {'O', '0'}, + {'S', '5'}, + {'s', '5'}, + {'/', '7'}, + {']', '1'}, + }; + + std::string raw; + std::string normalized; + for (const auto& item : characters){ + const std::string& ocr = item.ocr; + if (ocr.empty()){ + continue; + } + if ((uint8_t)ocr.back() < (uint8_t)32){ + raw += ocr.substr(0, ocr.size() - 1); + }else{ + raw += ocr; + } + + char ch = ocr[0]; + + // Character substitution. + auto iter = SUBSTITUTIONS.find(ch); + if (iter != SUBSTITUTIONS.end()){ + ch = iter->second; + } + + if ('0' <= ch && ch <= '9'){ + normalized += ch; + } + } + + std::string log = "Timer OCR: \"" + raw + "\" -> \"" + normalized + "\""; + if (normalized.size() != 3){ + logger.log(log, COLOR_RED); + return -1; + } + + logger.log(log, COLOR_BLUE); + + int16_t ret = 60 * (normalized[0] - '0'); + ret += 10 * (normalized[1] - '0'); + ret += normalized[2] - '0'; + + return ret; +} + + +std::string read_raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image){ + std::vector filters{ + 0xff5f5f5f, + 0xff7f7f7f, + }; + + for (uint32_t filter : filters){ + std::vector characters = waterfill_OCR(dispatcher, image, filter); + + static const std::map SUBSTITUTIONS{ + {'I', '1'}, + {'i', '1'}, + {'l', '1'}, + {'O', '0'}, + {'Z', 'S'}, + {'\\', 'V'}, + {'/', '7'}, + {']', '1'}, + {')', 'J'}, + {'(', 'K'}, + {'[', 'C'}, + }; + + bool contains_letters = false; + + std::string raw; + std::string normalized; + for (const auto& item : characters){ + const std::string& ocr = item.ocr; + if (ocr.empty()){ + continue; + } + if ((uint8_t)ocr.back() < (uint8_t)32){ + raw += ocr.substr(0, ocr.size() - 1); + }else{ + raw += ocr; + } + + char ch = ocr[0]; + + // Upper case. + if ('a' <= ch && ch <= 'z'){ + ch -= 'a' - 'A'; + } + + // Character substitution. + auto iter = SUBSTITUTIONS.find(ch); + if (iter != SUBSTITUTIONS.end()){ + ch = iter->second; + } + + // Distinguish 5 and S. + switch (ch){ + case '5': + case 'S': + ch = read_5S(image, item.object, ch); + } + + contains_letters |= 'A' <= ch && ch <= 'Z'; + + normalized += ch; + } + + std::string log = "Code OCR: \"" + raw + "\" -> \"" + normalized + "\""; + size_t length = normalized.size(); + if ((contains_letters && length == 6) || + (!contains_letters && (length == 4 || length == 6 || length == 8)) + ){ + logger.log(log, COLOR_BLUE); + return normalized; + } + logger.log(log, COLOR_RED); + } + + return ""; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h index d5bc03ad7b..ebe8b44ec2 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h @@ -1,33 +1,33 @@ -/* Tera Code Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraCodeReader_H -#define PokemonAutomation_PokemonSV_TeraCodeReader_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ - class Logger; - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -void preload_code_templates(); - - -// Returns # of seconds left. Returns -1 if unable to read. -int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image); - -// Returns empty string if unable to read. -std::string read_raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image); - - - -} -} -} -#endif +/* Tera Code Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraCodeReader_H +#define PokemonAutomation_PokemonSV_TeraCodeReader_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ + class Logger; + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +void preload_code_templates(); + + +// Returns # of seconds left. Returns -1 if unable to read. +int16_t read_raid_timer(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image); + +// Returns empty string if unable to read. +std::string read_raid_code(Logger& logger, AsyncDispatcher& dispatcher, const ImageViewRGB32& image); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.cpp index 1c26a6a06d..a0a9453b71 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.cpp @@ -1,218 +1,218 @@ -/* Tera Raid Search Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV_TeraRaidSearchDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraSearchGlassMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - TeraSearchGlassMatcher() - : WaterfillTemplateMatcher("PokemonSV/TeraSearchGlass.png", Color(0xff000000), Color(0xff808080), 100) - {} - - static const TeraSearchGlassMatcher& instance(){ - static TeraSearchGlassMatcher self; - return self; - } -}; - - - -TeraRaidSearchDetector::TeraRaidSearchDetector(Color color) - : m_color(color) -// , m_arrow_offline(color, GradientArrowType::DOWN, {0.475, 0.277, 0.050, 0.080}) -{} -void TeraRaidSearchDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, {0, 0, 1, 1}); -// m_arrow_offline.make_overlays(items); -} -bool TeraRaidSearchDetector::detect(const ImageViewRGB32& screen){ - ImageFloatBox box; - return detect_search_location(box, screen); -} -bool TeraRaidSearchDetector::detect_search_location(ImageFloatBox& box, const ImageViewRGB32& screen) const{ - using namespace Kernels::Waterfill; - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(screen, 0xff000000, 0xff808080); - std::unique_ptr session = make_WaterfillSession(matrix); - auto iter = session->make_iterator(100); - WaterfillObject object; - -// size_t c = 0; - const TeraSearchGlassMatcher& MATCHER = TeraSearchGlassMatcher::instance(); - while (iter->find_next(object, false)){ -// cout << "yellow = " << object.area << endl; -// extract_box_reference(screen, object).save("object-" + std::to_string(c++) + ".png"); -// yellows.emplace_back(std::move(object)); - double rmsd = MATCHER.rmsd(extract_box_reference(screen, object)); -// cout << "rmsd = " << rmsd << endl; - if (rmsd < 100){ - box = translate_to_parent(screen, {0, 0, 1, 1}, object); - return true; - } - } - - return false; -} -bool TeraRaidSearchDetector::move_cursor_to_search( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -) const{ - GradientArrowDetector arrow(m_color, GradientArrowType::DOWN, {0, 0, 1, 1}); - - size_t consecutive_detection_fails = 0; - size_t moves = 0; - bool target_reached = false; - while (true){ - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - - ImageFloatBox search_location; - ImageFloatBox arrow_location; - -// cout << "asdf" << endl; - - bool ok = true; - ok &= detect_search_location(search_location, screen); - ok &= arrow.detect(arrow_location, screen); - if (!ok){ - consecutive_detection_fails++; - if (consecutive_detection_fails > 10){ - dump_image_and_throw_recoverable_exception(info, stream, "UnableToDetectTeraSearch", "Unable to detect Tera Raid Search menu."); - } - context.wait_for(std::chrono::milliseconds(1000)); - continue; - } - - - if (moves >= 10){ - stream.log("Unable to move to target after 10 moves.", COLOR_RED); - return false; - } - moves++; - - double target_x = search_location.x + search_location.width * 0.5; - double target_y = search_location.y - search_location.height * 0.5; - double arrow_x = arrow_location.x + arrow_location.width * 0.5; - double arrow_y = arrow_location.y + arrow_location.height * 0.5; - - double diff_x = target_x - arrow_x; -// cout << "diff_x = " << diff_x << endl; - if (diff_x < -0.1 || diff_x > 0.5){ - target_reached = false; - pbf_press_dpad(context, DPAD_LEFT, 20, 10); - continue; - } - if (diff_x > 0.1 || diff_x < -0.5){ - target_reached = false; - pbf_press_dpad(context, DPAD_RIGHT, 20, 10); - continue; - } - - double diff_y = target_y - arrow_y; -// cout << "diff_y = " << diff_y << endl; - if (std::abs(diff_y) > 0.3){ - target_reached = false; - pbf_press_dpad(context, DPAD_DOWN, 20, 10); - continue; - } - - // Don't return yet. Wait a second to make sure the video is - // in steady state before we return. - if (target_reached){ - return true; - } - target_reached = true; - context.wait_for(std::chrono::seconds(1)); - } -} - - - -CodeEntryDetector::CodeEntryDetector(Color color) - : m_color(color) - , m_bottom(0.15, 0.92, 0.30, 0.07) - , m_left(0.01, 0.55, 0.02, 0.30) - , m_right(0.97, 0.55, 0.02, 0.30) - , m_center(0.20, 0.47, 0.60, 0.50) -{} - -void CodeEntryDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - items.add(m_color, m_left); - items.add(m_color, m_right); - items.add(m_color, m_center); -} -bool CodeEntryDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; - - bool light_theme = bottom.average.sum() > 500; - - if (light_theme){ - if (!is_white(bottom)){ -// cout << "bottom" << endl; - return false; - } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << left.average << left.stddev << endl; - if (!is_white(left)){ -// cout << "left" << endl; - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); - if (!is_white(right)){ -// cout << "right" << endl; - return false; - } - }else{ - if (!is_grey(bottom, 50, 300)){ - return false; - } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); - if (!is_grey(left, 50, 300)){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); - if (!is_grey(right, 50, 300)){ - return false; - } - } - - ImageStats center = image_stats(extract_box_reference(screen, m_center)); -// cout << center.average << center.stddev << endl; - if (center.stddev.sum() < 50){ - return false; - } - - return true; -} - - - - - - -} -} -} +/* Tera Raid Search Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV_TeraRaidSearchDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraSearchGlassMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + TeraSearchGlassMatcher() + : WaterfillTemplateMatcher("PokemonSV/TeraSearchGlass.png", Color(0xff000000), Color(0xff808080), 100) + {} + + static const TeraSearchGlassMatcher& instance(){ + static TeraSearchGlassMatcher self; + return self; + } +}; + + + +TeraRaidSearchDetector::TeraRaidSearchDetector(Color color) + : m_color(color) +// , m_arrow_offline(color, GradientArrowType::DOWN, {0.475, 0.277, 0.050, 0.080}) +{} +void TeraRaidSearchDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, {0, 0, 1, 1}); +// m_arrow_offline.make_overlays(items); +} +bool TeraRaidSearchDetector::detect(const ImageViewRGB32& screen){ + ImageFloatBox box; + return detect_search_location(box, screen); +} +bool TeraRaidSearchDetector::detect_search_location(ImageFloatBox& box, const ImageViewRGB32& screen) const{ + using namespace Kernels::Waterfill; + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(screen, 0xff000000, 0xff808080); + std::unique_ptr session = make_WaterfillSession(matrix); + auto iter = session->make_iterator(100); + WaterfillObject object; + +// size_t c = 0; + const TeraSearchGlassMatcher& MATCHER = TeraSearchGlassMatcher::instance(); + while (iter->find_next(object, false)){ +// cout << "yellow = " << object.area << endl; +// extract_box_reference(screen, object).save("object-" + std::to_string(c++) + ".png"); +// yellows.emplace_back(std::move(object)); + double rmsd = MATCHER.rmsd(extract_box_reference(screen, object)); +// cout << "rmsd = " << rmsd << endl; + if (rmsd < 100){ + box = translate_to_parent(screen, {0, 0, 1, 1}, object); + return true; + } + } + + return false; +} +bool TeraRaidSearchDetector::move_cursor_to_search( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +) const{ + GradientArrowDetector arrow(m_color, GradientArrowType::DOWN, {0, 0, 1, 1}); + + size_t consecutive_detection_fails = 0; + size_t moves = 0; + bool target_reached = false; + while (true){ + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + + ImageFloatBox search_location; + ImageFloatBox arrow_location; + +// cout << "asdf" << endl; + + bool ok = true; + ok &= detect_search_location(search_location, screen); + ok &= arrow.detect(arrow_location, screen); + if (!ok){ + consecutive_detection_fails++; + if (consecutive_detection_fails > 10){ + dump_image_and_throw_recoverable_exception(info, stream, "UnableToDetectTeraSearch", "Unable to detect Tera Raid Search menu."); + } + context.wait_for(std::chrono::milliseconds(1000)); + continue; + } + + + if (moves >= 10){ + stream.log("Unable to move to target after 10 moves.", COLOR_RED); + return false; + } + moves++; + + double target_x = search_location.x + search_location.width * 0.5; + double target_y = search_location.y - search_location.height * 0.5; + double arrow_x = arrow_location.x + arrow_location.width * 0.5; + double arrow_y = arrow_location.y + arrow_location.height * 0.5; + + double diff_x = target_x - arrow_x; +// cout << "diff_x = " << diff_x << endl; + if (diff_x < -0.1 || diff_x > 0.5){ + target_reached = false; + pbf_press_dpad(context, DPAD_LEFT, 20, 10); + continue; + } + if (diff_x > 0.1 || diff_x < -0.5){ + target_reached = false; + pbf_press_dpad(context, DPAD_RIGHT, 20, 10); + continue; + } + + double diff_y = target_y - arrow_y; +// cout << "diff_y = " << diff_y << endl; + if (std::abs(diff_y) > 0.3){ + target_reached = false; + pbf_press_dpad(context, DPAD_DOWN, 20, 10); + continue; + } + + // Don't return yet. Wait a second to make sure the video is + // in steady state before we return. + if (target_reached){ + return true; + } + target_reached = true; + context.wait_for(std::chrono::seconds(1)); + } +} + + + +CodeEntryDetector::CodeEntryDetector(Color color) + : m_color(color) + , m_bottom(0.15, 0.92, 0.30, 0.07) + , m_left(0.01, 0.55, 0.02, 0.30) + , m_right(0.97, 0.55, 0.02, 0.30) + , m_center(0.20, 0.47, 0.60, 0.50) +{} + +void CodeEntryDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + items.add(m_color, m_left); + items.add(m_color, m_right); + items.add(m_color, m_center); +} +bool CodeEntryDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; + + bool light_theme = bottom.average.sum() > 500; + + if (light_theme){ + if (!is_white(bottom)){ +// cout << "bottom" << endl; + return false; + } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << left.average << left.stddev << endl; + if (!is_white(left)){ +// cout << "left" << endl; + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); + if (!is_white(right)){ +// cout << "right" << endl; + return false; + } + }else{ + if (!is_grey(bottom, 50, 300)){ + return false; + } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); + if (!is_grey(left, 50, 300)){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); + if (!is_grey(right, 50, 300)){ + return false; + } + } + + ImageStats center = image_stats(extract_box_reference(screen, m_center)); +// cout << center.average << center.stddev << endl; + if (center.stddev.sum() < 50){ + return false; + } + + return true; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h index 2f7af6c29c..f6b6ae62ef 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h @@ -1,79 +1,79 @@ -/* Tera Raid Search Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraRaidSearchDetector_H -#define PokemonAutomation_PokemonSV_TeraRaidSearchDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraRaidSearchDetector : public StaticScreenDetector{ -public: - TeraRaidSearchDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - - bool detect_search_location(ImageFloatBox& box, const ImageViewRGB32& screen) const; - bool move_cursor_to_search( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context - ) const; - -private: - Color m_color; -}; -class TeraRaidSearchWatcher : public DetectorToFinder{ -public: - TeraRaidSearchWatcher( - Color color = COLOR_RED, - std::chrono::milliseconds duration = std::chrono::milliseconds(250) - ) - : DetectorToFinder("TeraRaidSearchWatcher", duration, color) - {} -}; - - - -class CodeEntryDetector : public StaticScreenDetector{ -public: - CodeEntryDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom; - ImageFloatBox m_left; - ImageFloatBox m_right; - ImageFloatBox m_center; -}; -class CodeEntryWatcher : public DetectorToFinder{ -public: - CodeEntryWatcher(Color color = COLOR_RED) - : DetectorToFinder("CodeEntryWatcher", std::chrono::milliseconds(250), color) - {} -}; - - - -} -} -} -#endif +/* Tera Raid Search Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraRaidSearchDetector_H +#define PokemonAutomation_PokemonSV_TeraRaidSearchDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraRaidSearchDetector : public StaticScreenDetector{ +public: + TeraRaidSearchDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + + bool detect_search_location(ImageFloatBox& box, const ImageViewRGB32& screen) const; + bool move_cursor_to_search( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context + ) const; + +private: + Color m_color; +}; +class TeraRaidSearchWatcher : public DetectorToFinder{ +public: + TeraRaidSearchWatcher( + Color color = COLOR_RED, + std::chrono::milliseconds duration = std::chrono::milliseconds(250) + ) + : DetectorToFinder("TeraRaidSearchWatcher", duration, color) + {} +}; + + + +class CodeEntryDetector : public StaticScreenDetector{ +public: + CodeEntryDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom; + ImageFloatBox m_left; + ImageFloatBox m_right; + ImageFloatBox m_center; +}; +class CodeEntryWatcher : public DetectorToFinder{ +public: + CodeEntryWatcher(Color color = COLOR_RED) + : DetectorToFinder("CodeEntryWatcher", std::chrono::milliseconds(250), color) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.cpp index ce7672c302..a91d31d118 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.cpp @@ -1,96 +1,96 @@ -/* Tera Rewards Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "PokemonSV_TeraRewardsReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -SparklyItemDetector::SparklyItemDetector(Color color) - : VisualInferenceCallback("SparklyItemDetector") - , m_color(color) - , m_start_time(WallClock::min()) -{ - for (size_t c = 0; c < ITEMS; c++){ - m_boxes[c] = ImageFloatBox{0.070, 0.262 + c*0.0804286, 0.045, 0.080}; - m_sparkly[c] = false; - } -} -size_t SparklyItemDetector::sparkly_items() const{ - size_t ret = 0; - for (size_t c = 0; c < ITEMS; c++){ - if (m_sparkly[c]){ - ret++; - } - } - return ret; -} -void SparklyItemDetector::make_overlays(VideoOverlaySet& items) const{ - for (size_t c = 0; c < ITEMS; c++){ - items.add(m_color, m_boxes[c]); - } -} -bool SparklyItemDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ImageRGB32 current[ITEMS]; - for (size_t c = 0; c < ITEMS; c++){ - current[c] = filter_rgb32_range( - extract_box_reference(frame, m_boxes[c]), - 0xff808000, 0xffffffff, - Color(0xff000000), false - ); - } - - // First frame. Save it. - if (m_start_time == WallClock::min()){ - for (size_t c = 0; c < ITEMS; c++){ - m_last[c] = std::move(current[c]); - } - m_start_time = timestamp; - return false; - } - - for (size_t c = 0; c < ITEMS; c++){ - if (m_last[c].width() != current[c].width()){ - continue; - } - if (m_last[c].height() != current[c].height()){ - continue; - } - double rmsd = ImageMatch::pixel_RMSD(m_last[c], current[c]); -// cout << rmsd << endl; - m_sparkly[c] |= rmsd > 25; - } - - return timestamp - m_start_time > std::chrono::seconds(2); -} - - -size_t SparklyItemDetector::count_sparkly_items(VideoStream& stream, CancellableScope& scope){ - SparklyItemDetector detector; - wait_until( - stream, scope, std::chrono::seconds(2), - {detector} - ); -// cout << detector.sparkly_items() << endl; - return detector.sparkly_items(); -} - - - - - - - -} -} -} +/* Tera Rewards Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "PokemonSV_TeraRewardsReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +SparklyItemDetector::SparklyItemDetector(Color color) + : VisualInferenceCallback("SparklyItemDetector") + , m_color(color) + , m_start_time(WallClock::min()) +{ + for (size_t c = 0; c < ITEMS; c++){ + m_boxes[c] = ImageFloatBox{0.070, 0.262 + c*0.0804286, 0.045, 0.080}; + m_sparkly[c] = false; + } +} +size_t SparklyItemDetector::sparkly_items() const{ + size_t ret = 0; + for (size_t c = 0; c < ITEMS; c++){ + if (m_sparkly[c]){ + ret++; + } + } + return ret; +} +void SparklyItemDetector::make_overlays(VideoOverlaySet& items) const{ + for (size_t c = 0; c < ITEMS; c++){ + items.add(m_color, m_boxes[c]); + } +} +bool SparklyItemDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ImageRGB32 current[ITEMS]; + for (size_t c = 0; c < ITEMS; c++){ + current[c] = filter_rgb32_range( + extract_box_reference(frame, m_boxes[c]), + 0xff808000, 0xffffffff, + Color(0xff000000), false + ); + } + + // First frame. Save it. + if (m_start_time == WallClock::min()){ + for (size_t c = 0; c < ITEMS; c++){ + m_last[c] = std::move(current[c]); + } + m_start_time = timestamp; + return false; + } + + for (size_t c = 0; c < ITEMS; c++){ + if (m_last[c].width() != current[c].width()){ + continue; + } + if (m_last[c].height() != current[c].height()){ + continue; + } + double rmsd = ImageMatch::pixel_RMSD(m_last[c], current[c]); +// cout << rmsd << endl; + m_sparkly[c] |= rmsd > 25; + } + + return timestamp - m_start_time > std::chrono::seconds(2); +} + + +size_t SparklyItemDetector::count_sparkly_items(VideoStream& stream, CancellableScope& scope){ + SparklyItemDetector detector; + wait_until( + stream, scope, std::chrono::seconds(2), + {detector} + ); +// cout << detector.sparkly_items() << endl; + return detector.sparkly_items(); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h index 28a6722a23..ba2e0add5f 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h @@ -1,50 +1,50 @@ -/* Tera Rewards Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraRewardsDetector_H -#define PokemonAutomation_PokemonSV_TeraRewardsDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class CancellableScope; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class SparklyItemDetector : public VisualInferenceCallback{ - static const size_t ITEMS = 8; - -public: - SparklyItemDetector(Color color = COLOR_RED); - - static size_t count_sparkly_items(VideoStream& stream, CancellableScope& scope); - - size_t sparkly_items() const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Color m_color; - ImageFloatBox m_boxes[ITEMS]; - ImageRGB32 m_last[ITEMS]; - bool m_sparkly[ITEMS]; - WallClock m_start_time; -}; - - - - - -} -} -} -#endif +/* Tera Rewards Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraRewardsDetector_H +#define PokemonAutomation_PokemonSV_TeraRewardsDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class CancellableScope; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class SparklyItemDetector : public VisualInferenceCallback{ + static const size_t ITEMS = 8; + +public: + SparklyItemDetector(Color color = COLOR_RED); + + static size_t count_sparkly_items(VideoStream& stream, CancellableScope& scope); + + size_t sparkly_items() const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Color m_color; + ImageFloatBox m_boxes[ITEMS]; + ImageRGB32 m_last[ITEMS]; + bool m_sparkly[ITEMS]; + WallClock m_start_time; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.cpp index f8cffb14bd..45f20ea79e 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.cpp @@ -1,127 +1,127 @@ -/* Tera Silhouette Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Logging/Logger.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonSV/Resources/PokemonSV_PokemonSprites.h" -#include "PokemonSV_TeraSilhouetteReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -ImageMatch::SilhouetteDictionaryMatcher make_TERA_RAID_SILHOUETTE_MATCHER(){ - ImageMatch::SilhouetteDictionaryMatcher matcher; - for (const auto& item : ALL_POKEMON_SILHOUETTES()){ - if (item.first == "pm1084_00_00_00_big" || - item.first == "pm1091_00_00_00_big" || - item.first == "error"){ - continue; - } - ImageRGB32 filtered_image = to_blackwhite_rgb32_range( - item.second.icon, - true, - 0xff000000, 0xff5f5f5f - ); - matcher.add(item.first, filtered_image); - } - return matcher; -} -const ImageMatch::SilhouetteDictionaryMatcher& TERA_RAID_SILHOUETTE_MATCHER(){ - static ImageMatch::SilhouetteDictionaryMatcher matcher = make_TERA_RAID_SILHOUETTE_MATCHER(); - return matcher; -} - -TeraSilhouetteReader::TeraSilhouetteReader(Color color) - : m_color(color) - , m_box(0.536, 0.122, 0.252, 0.430) -{} - -void TeraSilhouetteReader::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -ImageMatch::ImageMatchResult TeraSilhouetteReader::read(const ImageViewRGB32& screen) const{ - static constexpr double MAX_ALPHA = 120; - static constexpr double ALPHA_SPREAD = 20; - - const std::vector BRIGHTNESS_THRESHOLDS{ - 200, - 150, - 100, - 125, - 175, - 225, - }; - -// static int c = 0; - - ImageMatch::ImageMatchResult slugs; - for (uint32_t threshold : BRIGHTNESS_THRESHOLDS){ -// cout << "check0" << endl; - // Get a loose crop of the silhouette icon - ImageViewRGB32 cropped_image = extract_box_reference(screen, m_box); -// cropped_image.save("tera_cropped_image-" + std::to_string(c++) + ".png"); - -// cout << "check1" << endl; - ImageRGB32 preprocessed_image(cropped_image.width(), cropped_image.height()); - cv::medianBlur(cropped_image.to_opencv_Mat(), preprocessed_image.to_opencv_Mat(), 5); -// preprocessed_image.save("tera_blurred_image.png"); - - // Get a tight crop -// cout << "check2" << endl; - const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( - preprocessed_image, - // The filter is a lambda function that returns true on black silhouette pixels. - [=](Color pixel){ - return (uint32_t)pixel.red() + pixel.green() + pixel.blue() <= threshold; - } - ); - - if (tight_box.area() == 0){ -// global_logger_tagged().log("TeraSilhouetteReader::read(): Cropped image is empty.", COLOR_RED); - continue; - } - -// cout << "check3" << endl; - ImageRGB32 processed_image = extract_box_reference(preprocessed_image, tight_box).copy(); -// processed_image.save("tera_processed_image-" + std::to_string(c++) + ".png"); - -// cout << "check4" << endl; -// ImageRGB32 filtered_image = to_blackwhite_rgb32_range(processed_image, true, 0xff000000, 0xff5f5f5f); - ImageRGB32 filtered_image = to_blackwhite_rgb32_brightness( - processed_image, true, - 0x00010101, 0, threshold - ); -// filtered_image.save("tera_filtered_image-" + std::to_string(c++) + ".png"); - -// cout << "check5" << endl; - slugs = TERA_RAID_SILHOUETTE_MATCHER().match(filtered_image, ALPHA_SPREAD); - - slugs.clear_beyond_alpha(MAX_ALPHA); - -// slugs.log(global_logger_tagged(), MAX_ALPHA); - - if (slugs.results.size() == 1){ - return slugs; - } - } - - return slugs; -} - - - -} -} -} +/* Tera Silhouette Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Logging/Logger.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonSV/Resources/PokemonSV_PokemonSprites.h" +#include "PokemonSV_TeraSilhouetteReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +ImageMatch::SilhouetteDictionaryMatcher make_TERA_RAID_SILHOUETTE_MATCHER(){ + ImageMatch::SilhouetteDictionaryMatcher matcher; + for (const auto& item : ALL_POKEMON_SILHOUETTES()){ + if (item.first == "pm1084_00_00_00_big" || + item.first == "pm1091_00_00_00_big" || + item.first == "error"){ + continue; + } + ImageRGB32 filtered_image = to_blackwhite_rgb32_range( + item.second.icon, + true, + 0xff000000, 0xff5f5f5f + ); + matcher.add(item.first, filtered_image); + } + return matcher; +} +const ImageMatch::SilhouetteDictionaryMatcher& TERA_RAID_SILHOUETTE_MATCHER(){ + static ImageMatch::SilhouetteDictionaryMatcher matcher = make_TERA_RAID_SILHOUETTE_MATCHER(); + return matcher; +} + +TeraSilhouetteReader::TeraSilhouetteReader(Color color) + : m_color(color) + , m_box(0.536, 0.122, 0.252, 0.430) +{} + +void TeraSilhouetteReader::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +ImageMatch::ImageMatchResult TeraSilhouetteReader::read(const ImageViewRGB32& screen) const{ + static constexpr double MAX_ALPHA = 120; + static constexpr double ALPHA_SPREAD = 20; + + const std::vector BRIGHTNESS_THRESHOLDS{ + 200, + 150, + 100, + 125, + 175, + 225, + }; + +// static int c = 0; + + ImageMatch::ImageMatchResult slugs; + for (uint32_t threshold : BRIGHTNESS_THRESHOLDS){ +// cout << "check0" << endl; + // Get a loose crop of the silhouette icon + ImageViewRGB32 cropped_image = extract_box_reference(screen, m_box); +// cropped_image.save("tera_cropped_image-" + std::to_string(c++) + ".png"); + +// cout << "check1" << endl; + ImageRGB32 preprocessed_image(cropped_image.width(), cropped_image.height()); + cv::medianBlur(cropped_image.to_opencv_Mat(), preprocessed_image.to_opencv_Mat(), 5); +// preprocessed_image.save("tera_blurred_image.png"); + + // Get a tight crop +// cout << "check2" << endl; + const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( + preprocessed_image, + // The filter is a lambda function that returns true on black silhouette pixels. + [=](Color pixel){ + return (uint32_t)pixel.red() + pixel.green() + pixel.blue() <= threshold; + } + ); + + if (tight_box.area() == 0){ +// global_logger_tagged().log("TeraSilhouetteReader::read(): Cropped image is empty.", COLOR_RED); + continue; + } + +// cout << "check3" << endl; + ImageRGB32 processed_image = extract_box_reference(preprocessed_image, tight_box).copy(); +// processed_image.save("tera_processed_image-" + std::to_string(c++) + ".png"); + +// cout << "check4" << endl; +// ImageRGB32 filtered_image = to_blackwhite_rgb32_range(processed_image, true, 0xff000000, 0xff5f5f5f); + ImageRGB32 filtered_image = to_blackwhite_rgb32_brightness( + processed_image, true, + 0x00010101, 0, threshold + ); +// filtered_image.save("tera_filtered_image-" + std::to_string(c++) + ".png"); + +// cout << "check5" << endl; + slugs = TERA_RAID_SILHOUETTE_MATCHER().match(filtered_image, ALPHA_SPREAD); + + slugs.clear_beyond_alpha(MAX_ALPHA); + +// slugs.log(global_logger_tagged(), MAX_ALPHA); + + if (slugs.results.size() == 1){ + return slugs; + } + } + + return slugs; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.h index fc32d31e36..4fb775fcbe 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraSilhouetteReader.h @@ -1,40 +1,40 @@ -/* Tera Silhouette Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraSilhouetteReader_H -#define PokemonAutomation_PokemonSV_TeraSilhouetteReader_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/ImageMatch/ImageMatchResult.h" -#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraSilhouetteReader{ -public: - TeraSilhouetteReader(Color color = COLOR_GREEN); - - void make_overlays(VideoOverlaySet& items) const; - ImageMatch::ImageMatchResult read(const ImageViewRGB32& screen) const; - -private: - Color m_color; - ImageFloatBox m_box; -}; - - - -} -} -} -#endif +/* Tera Silhouette Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraSilhouetteReader_H +#define PokemonAutomation_PokemonSV_TeraSilhouetteReader_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/ImageMatch/ImageMatchResult.h" +#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraSilhouetteReader{ +public: + TeraSilhouetteReader(Color color = COLOR_GREEN); + + void make_overlays(VideoOverlaySet& items) const; + ImageMatch::ImageMatchResult read(const ImageViewRGB32& screen) const; + +private: + Color m_color; + ImageFloatBox m_box; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.cpp b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.cpp index 768384098b..d6f8bb098a 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.cpp +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.cpp @@ -1,102 +1,102 @@ -/* Tera Type Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonSV/Resources/PokemonSV_PokemonSprites.h" -#include "PokemonSV_TeraTypeReader.h" - -#include "CommonFramework/Logging/Logger.h" -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -ImageMatch::SilhouetteDictionaryMatcher make_TERA_RAID_TYPE_MATCHER(){ - ImageMatch::SilhouetteDictionaryMatcher matcher; - for (size_t i = 0; i < NUM_TERA_TYPE; i++){ - matcher.add(TERA_TYPE_NAMES[i], ALL_TERA_TYPE_ICONS()[i]); - } - return matcher; -} -const ImageMatch::SilhouetteDictionaryMatcher& TERA_RAID_TYPE_MATCHER(){ - static ImageMatch::SilhouetteDictionaryMatcher matcher = make_TERA_RAID_TYPE_MATCHER(); - return matcher; -} - -TeraTypeReader::TeraTypeReader(Color color) - : m_matcher(TERA_RAID_TYPE_MATCHER()) - , m_color(color) - , m_box(0.787, 0.139, 0.073, 0.136) -{} -void TeraTypeReader::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_box); -} - -ImageMatch::ImageMatchResult TeraTypeReader::read(const ImageViewRGB32& screen) const{ - static constexpr double MAX_ALPHA = 100; - static constexpr double ALPHA_SPREAD = 20; - - const std::vector BRIGHTNESS_THRESHOLDS{ - 200, - 150, - 100, - 125, - 175, - 225, - }; - -// static int c = 0; - for (uint32_t threshold : BRIGHTNESS_THRESHOLDS){ - - // Get a loose crop of the tera type icon - ImageViewRGB32 cropped_image = extract_box_reference(screen, m_box); - //cropped_image.save("cropped_image.png"); - - // Get a tight crop - const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( - cropped_image, - // The filter is a lambda function that returns true on black tera type pixels. - [=](Color pixel){ - return (uint32_t)pixel.red() + pixel.green() + pixel.blue() <= threshold; - } - ); - - if (tight_box.area() == 0){ - continue; - } - - ImageRGB32 processed_image = extract_box_reference(cropped_image, tight_box).copy(); - processed_image.save("processed_image-" + std::to_string(threshold) + ".png"); - - ImageRGB32 filtered_image = to_blackwhite_rgb32_brightness( - processed_image, true, - 0x00010101, 0, threshold - ); - filtered_image.save("filtered_image-" + std::to_string(threshold) + ".png"); - - ImageMatch::ImageMatchResult types = m_matcher.match(filtered_image, ALPHA_SPREAD); -// types.log(global_logger_tagged(), MAX_ALPHA); - types.clear_beyond_alpha(MAX_ALPHA); - - if (types.results.size() == 1){ - return types; - } - } - - return ImageMatch::ImageMatchResult(); -} - - - -} -} -} +/* Tera Type Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonSV/Resources/PokemonSV_PokemonSprites.h" +#include "PokemonSV_TeraTypeReader.h" + +#include "CommonFramework/Logging/Logger.h" +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +ImageMatch::SilhouetteDictionaryMatcher make_TERA_RAID_TYPE_MATCHER(){ + ImageMatch::SilhouetteDictionaryMatcher matcher; + for (size_t i = 0; i < NUM_TERA_TYPE; i++){ + matcher.add(TERA_TYPE_NAMES[i], ALL_TERA_TYPE_ICONS()[i]); + } + return matcher; +} +const ImageMatch::SilhouetteDictionaryMatcher& TERA_RAID_TYPE_MATCHER(){ + static ImageMatch::SilhouetteDictionaryMatcher matcher = make_TERA_RAID_TYPE_MATCHER(); + return matcher; +} + +TeraTypeReader::TeraTypeReader(Color color) + : m_matcher(TERA_RAID_TYPE_MATCHER()) + , m_color(color) + , m_box(0.787, 0.139, 0.073, 0.136) +{} +void TeraTypeReader::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_box); +} + +ImageMatch::ImageMatchResult TeraTypeReader::read(const ImageViewRGB32& screen) const{ + static constexpr double MAX_ALPHA = 100; + static constexpr double ALPHA_SPREAD = 20; + + const std::vector BRIGHTNESS_THRESHOLDS{ + 200, + 150, + 100, + 125, + 175, + 225, + }; + +// static int c = 0; + for (uint32_t threshold : BRIGHTNESS_THRESHOLDS){ + + // Get a loose crop of the tera type icon + ImageViewRGB32 cropped_image = extract_box_reference(screen, m_box); + //cropped_image.save("cropped_image.png"); + + // Get a tight crop + const ImagePixelBox tight_box = ImageMatch::enclosing_rectangle_with_pixel_filter( + cropped_image, + // The filter is a lambda function that returns true on black tera type pixels. + [=](Color pixel){ + return (uint32_t)pixel.red() + pixel.green() + pixel.blue() <= threshold; + } + ); + + if (tight_box.area() == 0){ + continue; + } + + ImageRGB32 processed_image = extract_box_reference(cropped_image, tight_box).copy(); + processed_image.save("processed_image-" + std::to_string(threshold) + ".png"); + + ImageRGB32 filtered_image = to_blackwhite_rgb32_brightness( + processed_image, true, + 0x00010101, 0, threshold + ); + filtered_image.save("filtered_image-" + std::to_string(threshold) + ".png"); + + ImageMatch::ImageMatchResult types = m_matcher.match(filtered_image, ALPHA_SPREAD); +// types.log(global_logger_tagged(), MAX_ALPHA); + types.clear_beyond_alpha(MAX_ALPHA); + + if (types.results.size() == 1){ + return types; + } + } + + return ImageMatch::ImageMatchResult(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.h b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.h index 07d53a52f8..95162439de 100644 --- a/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.h +++ b/SerialPrograms/Source/PokemonSV/Inference/Tera/PokemonSV_TeraTypeReader.h @@ -1,41 +1,41 @@ -/* Tera Type Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraTypeReader_H -#define PokemonAutomation_PokemonSV_TeraTypeReader_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/ImageMatch/ImageMatchResult.h" -#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraTypeReader{ -public: - TeraTypeReader(Color color = COLOR_BLUE); - - void make_overlays(VideoOverlaySet& items) const; - ImageMatch::ImageMatchResult read(const ImageViewRGB32& screen) const; - -private: - const ImageMatch::SilhouetteDictionaryMatcher& m_matcher; - Color m_color; - ImageFloatBox m_box; -}; - - - -} -} -} -#endif +/* Tera Type Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraTypeReader_H +#define PokemonAutomation_PokemonSV_TeraTypeReader_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/ImageMatch/ImageMatchResult.h" +#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraTypeReader{ +public: + TeraTypeReader(Color color = COLOR_BLUE); + + void make_overlays(VideoOverlaySet& items) const; + ImageMatch::ImageMatchResult read(const ImageViewRGB32& screen) const; + +private: + const ImageMatch::SilhouetteDictionaryMatcher& m_matcher; + Color m_color; + ImageFloatBox m_box; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.cpp index a56bc0bdf8..16d8c020c8 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.cpp @@ -1,52 +1,52 @@ -/* Auction Item Selector, UI component to select multiple items from auctions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "PokemonSV/Resources/PokemonSV_AuctionItemNames.h" -#include "PokemonSV/Resources/PokemonSV_ItemSprites.h" -#include "PokemonSV_AuctionItemSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -StringSelectDatabase make_auction_item_database(){ - StringSelectDatabase ret; - for (const auto& slug : AUCTION_ITEM_SLUGS()){ - const AuctionItemNames& data = get_auction_item_name(slug); - const SpriteDatabase::Sprite* sprite = AUCTION_ITEM_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); - } - } - return ret; -} -const StringSelectDatabase& AUCTION_ITEM_SELECT_DATABASE(){ - static StringSelectDatabase database = make_auction_item_database(); - return database; -} - - - - -AuctionItemSelectCell::AuctionItemSelectCell( - const std::string& default_slug -) - : StringSelectCell( - AUCTION_ITEM_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - -} -} -} +/* Auction Item Selector, UI component to select multiple items from auctions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "PokemonSV/Resources/PokemonSV_AuctionItemNames.h" +#include "PokemonSV/Resources/PokemonSV_ItemSprites.h" +#include "PokemonSV_AuctionItemSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +StringSelectDatabase make_auction_item_database(){ + StringSelectDatabase ret; + for (const auto& slug : AUCTION_ITEM_SLUGS()){ + const AuctionItemNames& data = get_auction_item_name(slug); + const SpriteDatabase::Sprite* sprite = AUCTION_ITEM_SPRITES().get_nothrow(slug); + if (sprite == nullptr){ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + } + } + return ret; +} +const StringSelectDatabase& AUCTION_ITEM_SELECT_DATABASE(){ + static StringSelectDatabase database = make_auction_item_database(); + return database; +} + + + + +AuctionItemSelectCell::AuctionItemSelectCell( + const std::string& default_slug +) + : StringSelectCell( + AUCTION_ITEM_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.h index d488ad413b..c903903336 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemSelectOption.h @@ -1,29 +1,29 @@ -/* Auction Item Selector, UI component to select multiple items from auctions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AuctionItemSelectOption_H -#define PokemonAutomation_PokemonSV_AuctionItemSelectOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AuctionItemSelectCell : public StringSelectCell{ -public: - AuctionItemSelectCell(const std::string& default_slug); -}; - - - - -} -} -} -#endif +/* Auction Item Selector, UI component to select multiple items from auctions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AuctionItemSelectOption_H +#define PokemonAutomation_PokemonSV_AuctionItemSelectOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AuctionItemSelectCell : public StringSelectCell{ +public: + AuctionItemSelectCell(const std::string& default_slug); +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.cpp index 5b17f2078f..2832bf944e 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.cpp @@ -1,81 +1,81 @@ -/* Auction item selector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV/Resources/PokemonSV_AuctionItemNames.h" -#include "PokemonSV_AuctionItemTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -AuctionItemSelectorRow::AuctionItemSelectorRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , item("level-ball") -{ - PA_ADD_OPTION(item); -} -std::unique_ptr AuctionItemSelectorRow::clone() const{ - std::unique_ptr ret(new AuctionItemSelectorRow(parent())); - ret->item.set_by_index(item.index()); - return ret; -} - - - -AuctionItemTable::AuctionItemTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - - - -bool AuctionItemTable::find_item(const std::string& item_slug) const{ - std::vector> table = copy_snapshot(); - for (const std::unique_ptr& row : table){ - if (row->item.slug() == item_slug){ - return true; - } - } - return false; -} - -std::vector AuctionItemTable::selected_items() const{ - std::vector> table = copy_snapshot(); - std::vector slugs; - for (const std::unique_ptr& row : table){ - slugs.emplace_back(row->item.slug()); - } - return slugs; -} - - - - -std::vector AuctionItemTable::make_header() const{ - return std::vector{ - "Item", - }; -} - -std::vector> AuctionItemTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} - - - - - - -} -} -} +/* Auction item selector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV/Resources/PokemonSV_AuctionItemNames.h" +#include "PokemonSV_AuctionItemTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +AuctionItemSelectorRow::AuctionItemSelectorRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , item("level-ball") +{ + PA_ADD_OPTION(item); +} +std::unique_ptr AuctionItemSelectorRow::clone() const{ + std::unique_ptr ret(new AuctionItemSelectorRow(parent())); + ret->item.set_by_index(item.index()); + return ret; +} + + + +AuctionItemTable::AuctionItemTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + + + +bool AuctionItemTable::find_item(const std::string& item_slug) const{ + std::vector> table = copy_snapshot(); + for (const std::unique_ptr& row : table){ + if (row->item.slug() == item_slug){ + return true; + } + } + return false; +} + +std::vector AuctionItemTable::selected_items() const{ + std::vector> table = copy_snapshot(); + std::vector slugs; + for (const std::unique_ptr& row : table){ + slugs.emplace_back(row->item.slug()); + } + return slugs; +} + + + + +std::vector AuctionItemTable::make_header() const{ + return std::vector{ + "Item", + }; +} + +std::vector> AuctionItemTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.h index 1c951b5522..d9ebad9f34 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AuctionItemTable.h @@ -1,52 +1,52 @@ -/* Auction item selector, UI component to select multiple items from auctions - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AuctionItemSelector_H -#define PokemonAutomation_PokemonSV_AuctionItemSelector_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonSV_AuctionItemSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AuctionItemSelectorRow : public EditableTableRow{ -public: - AuctionItemSelectorRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - AuctionItemSelectCell item; -}; - - - -class AuctionItemTable : public EditableTableOption_t{ -public: - AuctionItemTable(std::string label); - - - // Whether item_slug is among the selected items. - bool find_item(const std::string& item_slug) const; - // Return the auction item slugs that the user has selected via the auction item table UI. - std::vector selected_items() const; - - virtual std::vector make_header() const override; - - std::vector> make_defaults(); -}; - - - - - -} -} -} -#endif +/* Auction item selector, UI component to select multiple items from auctions + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AuctionItemSelector_H +#define PokemonAutomation_PokemonSV_AuctionItemSelector_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonSV_AuctionItemSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AuctionItemSelectorRow : public EditableTableRow{ +public: + AuctionItemSelectorRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + AuctionItemSelectCell item; +}; + + + +class AuctionItemTable : public EditableTableOption_t{ +public: + AuctionItemTable(std::string label); + + + // Whether item_slug is among the selected items. + bool find_item(const std::string& item_slug) const; + // Return the auction item slugs that the user has selected via the auction item table UI. + std::vector selected_items() const; + + virtual std::vector make_header() const override; + + std::vector> make_defaults(); +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AutoHostOptions.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AutoHostOptions.h index 2d9a0d2be2..5b1ed7789a 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AutoHostOptions.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_AutoHostOptions.h @@ -1,151 +1,151 @@ -/* Auto Host Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoHostOptions_H -#define PokemonAutomation_PokemonSV_AutoHostOptions_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/TextEditOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class LobbyWaitDelay : public SimpleIntegerOption{ -public: - LobbyWaitDelay() - : SimpleIntegerOption( - "Lobby Wait Delay (in seconds):
Wait this long before starting raid. Start time is 3 minutes minus this number.", - LockMode::UNLOCK_WHILE_RUNNING, - 60, 15, 180 - ) - {} -}; - -class StartRaidPlayers : public IntegerEnumDropdownOption{ -public: - StartRaidPlayers() - : IntegerEnumDropdownOption( - "Start Players:
Start the raid when there are this many players in the lobby.", - { - {2, "2", "2 players including the host(s)"}, - {3, "3", "3 players including the host(s)"}, - {4, "4", "4 players including the host(s)"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - 4 - ) - {} -}; - -class ShowRaidCode : public BooleanCheckBoxOption{ -public: - ShowRaidCode() - : BooleanCheckBoxOption( - "Show Raid Code:
Include the raid code in the post notifications. This allows FCE users to copy-paste the code.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - {} - -}; - -class AutoHostDescription : public TextEditOption{ -public: - AutoHostDescription() - : TextEditOption( - "Description:", - LockMode::UNLOCK_WHILE_RUNNING, - "", - "Auto-Hosting Shiny Eevee" - ) - {} -}; - -class RemoteKillSwitch : public StringOption{ -public: - RemoteKillSwitch() - : StringOption( - false, - "Remote Kill Switch:
Stop the auto-host if the session crosses the date/time specified in this URL. " - "The default URL is maintained by the PA/SHA staff which updates this with the event change dates.", - LockMode::UNLOCK_WHILE_RUNNING, - "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-KillSwitch.json", - "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-KillSwitch.json" - ) - {} -}; - -class ConsecutiveFailurePause : public SimpleIntegerOption{ -public: - ConsecutiveFailurePause() - : SimpleIntegerOption( - "Consecutive Failure Stop/Pause:
Pause or stop the program if this many consecutive raids fail.
" - "It is not recommended to set this higher than 3 since soft bans start after 3 disconnects.", - LockMode::UNLOCK_WHILE_RUNNING, - 3, 1 - ) - {} -}; - -class FailurePauseMinutes : public SimpleIntegerOption{ -public: - FailurePauseMinutes() - : SimpleIntegerOption( - "Failure Pause Time (in minutes):
If you trigger the above by failing too many times, " - "pause for this many minutes before resuming the program. (Zero stops the program.)", - LockMode::UNLOCK_WHILE_RUNNING, - 0, 0 - ) - {} -}; - -class RolloverPrevention : public BooleanCheckBoxOption{ -public: - RolloverPrevention() - : BooleanCheckBoxOption( - "Rollover Prevention:
Periodically set the time back to 12AM to prevent the date from rolling over and losing the raid.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - {} -}; - -class RaidPostNotification : public EventNotificationOption{ -public: - RaidPostNotification() - : EventNotificationOption("Hosting Announcements", true, false, ImageAttachmentMode::JPG, {"LiveHost"}) - {} -}; - -class RaidStartNotification : public EventNotificationOption{ -public: - RaidStartNotification() - : EventNotificationOption("Raid Start Announcements", true, false, ImageAttachmentMode::JPG, {"LiveHost"}) - {} -}; - -class JoinReportNotification : public EventNotificationOption{ -public: - JoinReportNotification() - : EventNotificationOption("Player Join Reports", true, false, {"Telemetry"}) - {} -}; - - - - - - -} -} -} -#endif +/* Auto Host Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoHostOptions_H +#define PokemonAutomation_PokemonSV_AutoHostOptions_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/TextEditOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class LobbyWaitDelay : public SimpleIntegerOption{ +public: + LobbyWaitDelay() + : SimpleIntegerOption( + "Lobby Wait Delay (in seconds):
Wait this long before starting raid. Start time is 3 minutes minus this number.", + LockMode::UNLOCK_WHILE_RUNNING, + 60, 15, 180 + ) + {} +}; + +class StartRaidPlayers : public IntegerEnumDropdownOption{ +public: + StartRaidPlayers() + : IntegerEnumDropdownOption( + "Start Players:
Start the raid when there are this many players in the lobby.", + { + {2, "2", "2 players including the host(s)"}, + {3, "3", "3 players including the host(s)"}, + {4, "4", "4 players including the host(s)"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + 4 + ) + {} +}; + +class ShowRaidCode : public BooleanCheckBoxOption{ +public: + ShowRaidCode() + : BooleanCheckBoxOption( + "Show Raid Code:
Include the raid code in the post notifications. This allows FCE users to copy-paste the code.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + {} + +}; + +class AutoHostDescription : public TextEditOption{ +public: + AutoHostDescription() + : TextEditOption( + "Description:", + LockMode::UNLOCK_WHILE_RUNNING, + "", + "Auto-Hosting Shiny Eevee" + ) + {} +}; + +class RemoteKillSwitch : public StringOption{ +public: + RemoteKillSwitch() + : StringOption( + false, + "Remote Kill Switch:
Stop the auto-host if the session crosses the date/time specified in this URL. " + "The default URL is maintained by the PA/SHA staff which updates this with the event change dates.", + LockMode::UNLOCK_WHILE_RUNNING, + "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-KillSwitch.json", + "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-KillSwitch.json" + ) + {} +}; + +class ConsecutiveFailurePause : public SimpleIntegerOption{ +public: + ConsecutiveFailurePause() + : SimpleIntegerOption( + "Consecutive Failure Stop/Pause:
Pause or stop the program if this many consecutive raids fail.
" + "It is not recommended to set this higher than 3 since soft bans start after 3 disconnects.", + LockMode::UNLOCK_WHILE_RUNNING, + 3, 1 + ) + {} +}; + +class FailurePauseMinutes : public SimpleIntegerOption{ +public: + FailurePauseMinutes() + : SimpleIntegerOption( + "Failure Pause Time (in minutes):
If you trigger the above by failing too many times, " + "pause for this many minutes before resuming the program. (Zero stops the program.)", + LockMode::UNLOCK_WHILE_RUNNING, + 0, 0 + ) + {} +}; + +class RolloverPrevention : public BooleanCheckBoxOption{ +public: + RolloverPrevention() + : BooleanCheckBoxOption( + "Rollover Prevention:
Periodically set the time back to 12AM to prevent the date from rolling over and losing the raid.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + {} +}; + +class RaidPostNotification : public EventNotificationOption{ +public: + RaidPostNotification() + : EventNotificationOption("Hosting Announcements", true, false, ImageAttachmentMode::JPG, {"LiveHost"}) + {} +}; + +class RaidStartNotification : public EventNotificationOption{ +public: + RaidStartNotification() + : EventNotificationOption("Raid Start Announcements", true, false, ImageAttachmentMode::JPG, {"LiveHost"}) + {} +}; + +class JoinReportNotification : public EventNotificationOption{ +public: + JoinReportNotification() + : EventNotificationOption("Player Join Reports", true, false, {"Telemetry"}) + {} +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.cpp index ec4e72739b..7bb493789e 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.cpp @@ -1,221 +1,221 @@ -/* BBQ Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSV_BBQOption.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -//Does not include multiplayer quests -const EnumDropdownDatabase& BBQuests_database(){ - static EnumDropdownDatabase database{ - {BBQuests::auto_10, "auto-10", "Defeat 10 wild Pokemon using Auto Battle!"}, - {BBQuests::make_tm, "make-tm", "Make yourself a TM!"}, - //{BBQuests::pickup_10, "pickup-10", "Pick up items on the ground 10 times!"}, - {BBQuests::sneak_up, "sneak-up", "Successfully sneak up on 1 Pokemon and surprise them with a battle!"}, - {BBQuests::photo_fly, "photo-fly", "Take a photo of a wild Pokemon in flight!"}, - {BBQuests::photo_swim, "photo-swim", "Take a photo of a wild Pokemon that is swimming!"}, - {BBQuests::photo_canyon, "photo-canyon", "Take a photo of a wild Pokemon in the Canyon Biome!"}, - {BBQuests::photo_coastal, "photo-coastal", "Take a photo of a wild Pokemon in the Coastal Biome!"}, - {BBQuests::photo_polar, "photo-polar", "Take a photo of a wild Pokemon in the Polar Biome!"}, - {BBQuests::photo_savanna, "photo-savanna", "Take a photo of a wild Pokemon in the Savanna Biome!"}, - {BBQuests::tera_self_defeat,"tera-self-defeat", "Terastallize your Pokemon to defeat a wild Pokemon!"}, - {BBQuests::travel_500, "travel-500", "Travel over 500 yards!"}, - {BBQuests::catch_any, "catch-any", "Catch 1 Pokemon!"}, - {BBQuests::catch_normal, "catch-normal", "Catch 1 Normal-type Pokemon!"}, - {BBQuests::catch_fighting, "catch-fighting", "Catch 1 Fighting-type Pokemon!"}, - {BBQuests::catch_flying, "catch-flying", "Catch 1 Flying-type Pokemon!"}, - {BBQuests::catch_poison, "catch-poison", "Catch 1 Poison-type Pokemon!"}, - {BBQuests::catch_ground, "catch-ground", "Catch 1 Ground-type Pokemon!"}, - {BBQuests::catch_rock, "catch-rock", "Catch 1 Rock-type Pokemon!"}, - {BBQuests::catch_bug, "catch-bug", "Catch 1 Bug-type Pokemon!"}, - {BBQuests::catch_ghost, "catch-ghost", "Catch 1 Ghost-type Pokemon!"}, - {BBQuests::catch_steel, "catch-steel", "Catch 1 Steel-type Pokemon!"}, - {BBQuests::catch_fire, "catch-fire", "Catch 1 Fire-type Pokemon!"}, - {BBQuests::catch_water, "catch-water", "Catch 1 Water-type Pokemon!"}, - {BBQuests::catch_grass, "catch-grass", "Catch 1 Grass-type Pokemon!"}, - {BBQuests::catch_electric, "catch-electric", "Catch 1 Electric-type Pokemon!"}, - {BBQuests::catch_psychic, "catch-psychic", "Catch 1 Psychic-type Pokemon!"}, - {BBQuests::catch_ice, "catch-ice", "Catch 1 Ice-type Pokemon!"}, - {BBQuests::catch_dragon, "catch-dragon", "Catch 1 Dragon-type Pokemon!"}, - {BBQuests::catch_dark, "catch-dark", "Catch 1 Dark-type Pokemon!"}, - {BBQuests::catch_fairy, "catch-fairy", "Catch 1 Fairy-type Pokemon!"}, - {BBQuests::wash_pokemon, "wash-pokemon", "Give your Pokemon a nice washing!"}, - {BBQuests::wild_tera, "wild-tera", "Battle a wild Tera Pokemon!"}, - {BBQuests::auto_30, "auto-30", "Defeat 30 wild Pokemon using Auto Battle!"}, - {BBQuests::tera_raid, "tera-raid", "Claim victory in a Tera Raid Battle!"}, - {BBQuests::sandwich_three, "sandwich-three", "Make a sandwich that uses at least 3 ingredients!"}, - {BBQuests::bitter_sandwich, "bitter-sandwich", "Make a bitter sandwich!"}, - {BBQuests::sweet_sandwich, "sweet-sandwich", "Make a sweet sandwich!"}, - {BBQuests::salty_sandwich, "salty-sandwich", "Make a salty sandwich!"}, - {BBQuests::sour_sandwich, "sour-sandwich", "Make a sour sandwich!"}, - {BBQuests::spicy_sandwich, "spicy-sandwich", "Make a spicy sandwich!"}, - //{BBQuests::hatch_egg, "hatch-egg", "Hatch a Pokemon Egg!"}, - {BBQuests::photo_normal, "photo-normal", "Take a photo of a wild Normal-type Pokemon!"}, - {BBQuests::photo_fighting, "photo-fighting", "Take a photo of a wild Fighting-type Pokemon!"}, - {BBQuests::photo_flying, "photo-flying", "Take a photo of a wild Flying-type Pokemon!"}, - {BBQuests::photo_poison, "photo-poison", "Take a photo of a wild Poison-type Pokemon!"}, - {BBQuests::photo_ground, "photo-ground", "Take a photo of a wild Ground-type Pokemon!"}, - {BBQuests::photo_rock, "photo-rock", "Take a photo of a wild Rock-type Pokemon!"}, - {BBQuests::photo_bug, "photo-bug", "Take a photo of a wild Bug-type Pokemon!"}, - {BBQuests::photo_ghost, "photo-ghost", "Take a photo of a wild Ghost-type Pokemon!"}, - {BBQuests::photo_steel, "photo-steel", "Take a photo of a wild Steel-type Pokemon!"}, - {BBQuests::photo_fire, "photo-fire", "Take a photo of a wild Fire-type Pokemon!"}, - {BBQuests::photo_water, "photo-water", "Take a photo of a wild Water-type Pokemon!"}, - {BBQuests::photo_grass, "photo-grass", "Take a photo of a wild Grass-type Pokemon!"}, - {BBQuests::photo_electric, "photo-electric", "Take a photo of a wild Electric-type Pokemon!"}, - {BBQuests::photo_psychic, "photo-psychic", "Take a photo of a wild Psychic-type Pokemon!"}, - {BBQuests::photo_ice, "photo-ice", "Take a photo of a wild Ice-type Pokemon!"}, - {BBQuests::photo_dragon, "photo-dragon", "Take a photo of a wild Dragon-type Pokemon!"}, - {BBQuests::photo_dark, "photo-dark", "Take a photo of a wild Dark-type Pokemon!"}, - {BBQuests::photo_fairy, "photo-fairy", "Take a photo of a wild Fairy-type Pokemon!"}, - }; - return database; -} - -const EnumDropdownDatabase& BBQAction_database(){ - static EnumDropdownDatabase database{ - {BBQAction::run, "run", "Run Quest"}, - {BBQAction::skip, "skip", "Skip"}, - {BBQAction::reroll, "reroll", "Reroll"}, - }; - return database; -} - -BBQuestTableRow::BBQuestTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , quest(BBQuests_database(), LockMode::UNLOCK_WHILE_RUNNING, BBQuests::auto_10) - , action(BBQAction_database(), LockMode::UNLOCK_WHILE_RUNNING, BBQAction::skip) -{ - PA_ADD_OPTION(quest); - PA_ADD_OPTION(action); -} -std::unique_ptr BBQuestTableRow::clone() const{ - std::unique_ptr ret(new BBQuestTableRow(parent())); - ret->quest.set(quest); - ret->action.set(action); - return ret; -} - -BBQuestTable::BBQuestTable() - : EditableTableOption_t( - "Quest Exclusions:
" - "Warning: Skipping Bonus quests will block the bonus slot.
" - "Exclude the quests in the table. If you want to skip a quest, select it below. " - "(Quests can be explicitly included, but this is not necessary.) " - "Do not exclude too many quests, as rerolling costs BP. " - "The program will automatically reroll all quests if none are possible, but will not handle being out of BP. " - "Does not include egg hatching or pickup quests, as eggs are handled in other options and pickup is not possible. ", - //"Duplicates of the same quest", - //duplicates will work in table order. might lead to weird behavior like rerolling and then marking a quest as complete. - //won't break the program though. - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - -std::vector BBQuestTable::make_header() const{ - return { - "Quest", - "Action", - }; -} -std::vector> BBQuestTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(new BBQuestTableRow(*this)); - return ret; -} - - -BBQOption::BBQOption(OCR::LanguageOCROption* language_option) - : GroupOption("Blueberry Quests", LockMode::UNLOCK_WHILE_RUNNING) - , m_language_owner(language_option == nullptr - ? new OCR::LanguageOCROption( - "Game Language:
This is required to read quests.", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - : nullptr - ) - , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) - , NUM_QUESTS( - "Number of Quests to run:", - LockMode::UNLOCK_WHILE_RUNNING, - 1000 - ) - , SAVE_NUM_QUESTS( - "Save and reset the game after attempting this many quests:
This preserves progress and prevents potential game lags from long runs.
0 disables this option.", - LockMode::UNLOCK_WHILE_RUNNING, 50 - ) - , INVERTED_FLIGHT( - "Inverted Flight:
Check this box if inverted flight controls are set.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , QUICKBALL( - "Catch Quest - Throw Quick Ball:
When attempting to catch a non-tera Pokemon, use a Quick Ball on the first turn.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , BALL_SELECT( - "Catch Quest - Ball Select:
What ball to use when performing a catch quest.", - LockMode::UNLOCK_WHILE_RUNNING, - "ultra-ball" - ) - , NUM_EGGS( - "Hatch Quest - Number of Eggs:
Amount of eggs located in your current box.", - LockMode::UNLOCK_WHILE_RUNNING, 30, 0, 30 - ) - , OUT_OF_EGGS( - "Hatch Quest - Zero Eggs:
When out of eggs to hatch, do the selected option.", - { - {OOEggs::Stop, "stop", "Stop Program"}, - {OOEggs::Reroll, "reroll", "Reroll Quest - Costs 50BP"}, - {OOEggs::KeepGoing, "keep-going", "Keep Going - Warning: Bonus(Red) quests will be blocked!"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - OOEggs::Stop - ) - , FIX_TIME_FOR_HATCH( - "Hatch Quest - Fix time for eggs:
Fix the time before doing a hatch egg quest.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , CATCH_ON_WIN(true) - , NUM_RETRIES( - "Number of Retries:
Reattempt a quest this many times if it fails.", - LockMode::UNLOCK_WHILE_RUNNING, 1, 0, 5 - ) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) -{ - if (m_language_owner){ - PA_ADD_OPTION(LANGUAGE); - } - PA_ADD_OPTION(NUM_QUESTS); - PA_ADD_OPTION(SAVE_NUM_QUESTS); - PA_ADD_OPTION(QUEST_EXCLUSIONS); - PA_ADD_OPTION(INVERTED_FLIGHT); - PA_ADD_OPTION(QUICKBALL); - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(NUM_EGGS); - PA_ADD_OPTION(OUT_OF_EGGS); - PA_ADD_OPTION(FIX_TIME_FOR_HATCH); - PA_ADD_OPTION(BATTLE_AI); - PA_ADD_OPTION(CATCH_ON_WIN); - PA_ADD_OPTION(NUM_RETRIES); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); -} - - -} -} -} +/* BBQ Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSV_BBQOption.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +//Does not include multiplayer quests +const EnumDropdownDatabase& BBQuests_database(){ + static EnumDropdownDatabase database{ + {BBQuests::auto_10, "auto-10", "Defeat 10 wild Pokemon using Auto Battle!"}, + {BBQuests::make_tm, "make-tm", "Make yourself a TM!"}, + //{BBQuests::pickup_10, "pickup-10", "Pick up items on the ground 10 times!"}, + {BBQuests::sneak_up, "sneak-up", "Successfully sneak up on 1 Pokemon and surprise them with a battle!"}, + {BBQuests::photo_fly, "photo-fly", "Take a photo of a wild Pokemon in flight!"}, + {BBQuests::photo_swim, "photo-swim", "Take a photo of a wild Pokemon that is swimming!"}, + {BBQuests::photo_canyon, "photo-canyon", "Take a photo of a wild Pokemon in the Canyon Biome!"}, + {BBQuests::photo_coastal, "photo-coastal", "Take a photo of a wild Pokemon in the Coastal Biome!"}, + {BBQuests::photo_polar, "photo-polar", "Take a photo of a wild Pokemon in the Polar Biome!"}, + {BBQuests::photo_savanna, "photo-savanna", "Take a photo of a wild Pokemon in the Savanna Biome!"}, + {BBQuests::tera_self_defeat,"tera-self-defeat", "Terastallize your Pokemon to defeat a wild Pokemon!"}, + {BBQuests::travel_500, "travel-500", "Travel over 500 yards!"}, + {BBQuests::catch_any, "catch-any", "Catch 1 Pokemon!"}, + {BBQuests::catch_normal, "catch-normal", "Catch 1 Normal-type Pokemon!"}, + {BBQuests::catch_fighting, "catch-fighting", "Catch 1 Fighting-type Pokemon!"}, + {BBQuests::catch_flying, "catch-flying", "Catch 1 Flying-type Pokemon!"}, + {BBQuests::catch_poison, "catch-poison", "Catch 1 Poison-type Pokemon!"}, + {BBQuests::catch_ground, "catch-ground", "Catch 1 Ground-type Pokemon!"}, + {BBQuests::catch_rock, "catch-rock", "Catch 1 Rock-type Pokemon!"}, + {BBQuests::catch_bug, "catch-bug", "Catch 1 Bug-type Pokemon!"}, + {BBQuests::catch_ghost, "catch-ghost", "Catch 1 Ghost-type Pokemon!"}, + {BBQuests::catch_steel, "catch-steel", "Catch 1 Steel-type Pokemon!"}, + {BBQuests::catch_fire, "catch-fire", "Catch 1 Fire-type Pokemon!"}, + {BBQuests::catch_water, "catch-water", "Catch 1 Water-type Pokemon!"}, + {BBQuests::catch_grass, "catch-grass", "Catch 1 Grass-type Pokemon!"}, + {BBQuests::catch_electric, "catch-electric", "Catch 1 Electric-type Pokemon!"}, + {BBQuests::catch_psychic, "catch-psychic", "Catch 1 Psychic-type Pokemon!"}, + {BBQuests::catch_ice, "catch-ice", "Catch 1 Ice-type Pokemon!"}, + {BBQuests::catch_dragon, "catch-dragon", "Catch 1 Dragon-type Pokemon!"}, + {BBQuests::catch_dark, "catch-dark", "Catch 1 Dark-type Pokemon!"}, + {BBQuests::catch_fairy, "catch-fairy", "Catch 1 Fairy-type Pokemon!"}, + {BBQuests::wash_pokemon, "wash-pokemon", "Give your Pokemon a nice washing!"}, + {BBQuests::wild_tera, "wild-tera", "Battle a wild Tera Pokemon!"}, + {BBQuests::auto_30, "auto-30", "Defeat 30 wild Pokemon using Auto Battle!"}, + {BBQuests::tera_raid, "tera-raid", "Claim victory in a Tera Raid Battle!"}, + {BBQuests::sandwich_three, "sandwich-three", "Make a sandwich that uses at least 3 ingredients!"}, + {BBQuests::bitter_sandwich, "bitter-sandwich", "Make a bitter sandwich!"}, + {BBQuests::sweet_sandwich, "sweet-sandwich", "Make a sweet sandwich!"}, + {BBQuests::salty_sandwich, "salty-sandwich", "Make a salty sandwich!"}, + {BBQuests::sour_sandwich, "sour-sandwich", "Make a sour sandwich!"}, + {BBQuests::spicy_sandwich, "spicy-sandwich", "Make a spicy sandwich!"}, + //{BBQuests::hatch_egg, "hatch-egg", "Hatch a Pokemon Egg!"}, + {BBQuests::photo_normal, "photo-normal", "Take a photo of a wild Normal-type Pokemon!"}, + {BBQuests::photo_fighting, "photo-fighting", "Take a photo of a wild Fighting-type Pokemon!"}, + {BBQuests::photo_flying, "photo-flying", "Take a photo of a wild Flying-type Pokemon!"}, + {BBQuests::photo_poison, "photo-poison", "Take a photo of a wild Poison-type Pokemon!"}, + {BBQuests::photo_ground, "photo-ground", "Take a photo of a wild Ground-type Pokemon!"}, + {BBQuests::photo_rock, "photo-rock", "Take a photo of a wild Rock-type Pokemon!"}, + {BBQuests::photo_bug, "photo-bug", "Take a photo of a wild Bug-type Pokemon!"}, + {BBQuests::photo_ghost, "photo-ghost", "Take a photo of a wild Ghost-type Pokemon!"}, + {BBQuests::photo_steel, "photo-steel", "Take a photo of a wild Steel-type Pokemon!"}, + {BBQuests::photo_fire, "photo-fire", "Take a photo of a wild Fire-type Pokemon!"}, + {BBQuests::photo_water, "photo-water", "Take a photo of a wild Water-type Pokemon!"}, + {BBQuests::photo_grass, "photo-grass", "Take a photo of a wild Grass-type Pokemon!"}, + {BBQuests::photo_electric, "photo-electric", "Take a photo of a wild Electric-type Pokemon!"}, + {BBQuests::photo_psychic, "photo-psychic", "Take a photo of a wild Psychic-type Pokemon!"}, + {BBQuests::photo_ice, "photo-ice", "Take a photo of a wild Ice-type Pokemon!"}, + {BBQuests::photo_dragon, "photo-dragon", "Take a photo of a wild Dragon-type Pokemon!"}, + {BBQuests::photo_dark, "photo-dark", "Take a photo of a wild Dark-type Pokemon!"}, + {BBQuests::photo_fairy, "photo-fairy", "Take a photo of a wild Fairy-type Pokemon!"}, + }; + return database; +} + +const EnumDropdownDatabase& BBQAction_database(){ + static EnumDropdownDatabase database{ + {BBQAction::run, "run", "Run Quest"}, + {BBQAction::skip, "skip", "Skip"}, + {BBQAction::reroll, "reroll", "Reroll"}, + }; + return database; +} + +BBQuestTableRow::BBQuestTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , quest(BBQuests_database(), LockMode::UNLOCK_WHILE_RUNNING, BBQuests::auto_10) + , action(BBQAction_database(), LockMode::UNLOCK_WHILE_RUNNING, BBQAction::skip) +{ + PA_ADD_OPTION(quest); + PA_ADD_OPTION(action); +} +std::unique_ptr BBQuestTableRow::clone() const{ + std::unique_ptr ret(new BBQuestTableRow(parent())); + ret->quest.set(quest); + ret->action.set(action); + return ret; +} + +BBQuestTable::BBQuestTable() + : EditableTableOption_t( + "Quest Exclusions:
" + "Warning: Skipping Bonus quests will block the bonus slot.
" + "Exclude the quests in the table. If you want to skip a quest, select it below. " + "(Quests can be explicitly included, but this is not necessary.) " + "Do not exclude too many quests, as rerolling costs BP. " + "The program will automatically reroll all quests if none are possible, but will not handle being out of BP. " + "Does not include egg hatching or pickup quests, as eggs are handled in other options and pickup is not possible. ", + //"Duplicates of the same quest", + //duplicates will work in table order. might lead to weird behavior like rerolling and then marking a quest as complete. + //won't break the program though. + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + +std::vector BBQuestTable::make_header() const{ + return { + "Quest", + "Action", + }; +} +std::vector> BBQuestTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(new BBQuestTableRow(*this)); + return ret; +} + + +BBQOption::BBQOption(OCR::LanguageOCROption* language_option) + : GroupOption("Blueberry Quests", LockMode::UNLOCK_WHILE_RUNNING) + , m_language_owner(language_option == nullptr + ? new OCR::LanguageOCROption( + "Game Language:
This is required to read quests.", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + : nullptr + ) + , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) + , NUM_QUESTS( + "Number of Quests to run:", + LockMode::UNLOCK_WHILE_RUNNING, + 1000 + ) + , SAVE_NUM_QUESTS( + "Save and reset the game after attempting this many quests:
This preserves progress and prevents potential game lags from long runs.
0 disables this option.", + LockMode::UNLOCK_WHILE_RUNNING, 50 + ) + , INVERTED_FLIGHT( + "Inverted Flight:
Check this box if inverted flight controls are set.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , QUICKBALL( + "Catch Quest - Throw Quick Ball:
When attempting to catch a non-tera Pokemon, use a Quick Ball on the first turn.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , BALL_SELECT( + "Catch Quest - Ball Select:
What ball to use when performing a catch quest.", + LockMode::UNLOCK_WHILE_RUNNING, + "ultra-ball" + ) + , NUM_EGGS( + "Hatch Quest - Number of Eggs:
Amount of eggs located in your current box.", + LockMode::UNLOCK_WHILE_RUNNING, 30, 0, 30 + ) + , OUT_OF_EGGS( + "Hatch Quest - Zero Eggs:
When out of eggs to hatch, do the selected option.", + { + {OOEggs::Stop, "stop", "Stop Program"}, + {OOEggs::Reroll, "reroll", "Reroll Quest - Costs 50BP"}, + {OOEggs::KeepGoing, "keep-going", "Keep Going - Warning: Bonus(Red) quests will be blocked!"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + OOEggs::Stop + ) + , FIX_TIME_FOR_HATCH( + "Hatch Quest - Fix time for eggs:
Fix the time before doing a hatch egg quest.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , CATCH_ON_WIN(true) + , NUM_RETRIES( + "Number of Retries:
Reattempt a quest this many times if it fails.", + LockMode::UNLOCK_WHILE_RUNNING, 1, 0, 5 + ) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) +{ + if (m_language_owner){ + PA_ADD_OPTION(LANGUAGE); + } + PA_ADD_OPTION(NUM_QUESTS); + PA_ADD_OPTION(SAVE_NUM_QUESTS); + PA_ADD_OPTION(QUEST_EXCLUSIONS); + PA_ADD_OPTION(INVERTED_FLIGHT); + PA_ADD_OPTION(QUICKBALL); + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(NUM_EGGS); + PA_ADD_OPTION(OUT_OF_EGGS); + PA_ADD_OPTION(FIX_TIME_FOR_HATCH); + PA_ADD_OPTION(BATTLE_AI); + PA_ADD_OPTION(CATCH_ON_WIN); + PA_ADD_OPTION(NUM_RETRIES); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.h index a4034f10c3..71d463b65c 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BBQOption.h @@ -1,122 +1,122 @@ -/* BBQ Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BBQOption_H -#define PokemonAutomation_PokemonSV_BBQOption_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" -#include "PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -enum class BBQuests{ - auto_10, make_tm, pickup_10, sneak_up, photo_fly, photo_swim, photo_canyon, photo_coastal, photo_polar, photo_savanna, tera_self_defeat, - travel_500, catch_any, catch_normal, catch_fighting, catch_flying, catch_poison, catch_ground, catch_rock, catch_bug, catch_ghost, catch_steel, - catch_fire, catch_water, catch_grass, catch_electric, catch_psychic, catch_ice, catch_dragon, catch_dark, catch_fairy, - wash_pokemon, wild_tera, auto_30, tera_raid, sandwich_three, bitter_sandwich, sweet_sandwich, salty_sandwich, sour_sandwich, spicy_sandwich, hatch_egg, - photo_normal, photo_fighting, photo_flying, photo_poison, photo_ground, photo_rock, photo_bug, photo_ghost, photo_steel, photo_fire, photo_water, - photo_grass, photo_electric, photo_psychic, photo_ice, photo_dragon, photo_dark, photo_fairy, - ditto_central, ditto_canyon, ditto_coastal, ditto_polar, ditto_savanna, group_canyon, group_coastal, group_polar, group_savanna, group_eyewear, group_nonuniform, - group_masks, sandwich_four, catch_hint, catch_hint2, - UnableToDetect -}; - -enum class BBQAction{ - run, - skip, - reroll -}; - -//Quest exclusion table -const EnumDropdownDatabase& BBQuests_database(); - -class BBQuestTableRow : public EditableTableRow{ -public: - BBQuestTableRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - EnumDropdownCell quest; - EnumDropdownCell action; -}; - -class BBQuestTable : public EditableTableOption_t{ -public: - BBQuestTable(); - - virtual std::vector make_header() const; - std::vector> make_defaults(); -}; - - -//BBQ Options -class BBQOption : public GroupOption{ - -public: - // Include the language option in the box. - BBQOption() - : BBQOption(nullptr) - {} - - // Don't include language option. Give it one instead. - BBQOption(OCR::LanguageOCROption& language_option) - : BBQOption(&language_option) - {} - -private: - std::unique_ptr m_language_owner; - -public: - enum class OOEggs { - Stop, - Reroll, - KeepGoing, - }; - - OCR::LanguageOCROption& LANGUAGE; - - SimpleIntegerOption NUM_QUESTS; - SimpleIntegerOption SAVE_NUM_QUESTS; - - BBQuestTable QUEST_EXCLUSIONS; - - BooleanCheckBoxOption INVERTED_FLIGHT; - - //For catching pokemon quests - BooleanCheckBoxOption QUICKBALL; - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - //BattleMoveTable BATTLE_MOVES; No need, not catching legendaries. - - //For egg hatching quest - SimpleIntegerOption NUM_EGGS; - EnumDropdownOption OUT_OF_EGGS; - BooleanCheckBoxOption FIX_TIME_FOR_HATCH; - - //Tera raid - TeraAIOption BATTLE_AI; - TeraFarmerCatchOnWin CATCH_ON_WIN; - - SimpleIntegerOption NUM_RETRIES; - - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - -private: - BBQOption(OCR::LanguageOCROption* language_option); -}; - -} -} -} -#endif +/* BBQ Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQOption_H +#define PokemonAutomation_PokemonSV_BBQOption_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" +#include "PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class BBQuests{ + auto_10, make_tm, pickup_10, sneak_up, photo_fly, photo_swim, photo_canyon, photo_coastal, photo_polar, photo_savanna, tera_self_defeat, + travel_500, catch_any, catch_normal, catch_fighting, catch_flying, catch_poison, catch_ground, catch_rock, catch_bug, catch_ghost, catch_steel, + catch_fire, catch_water, catch_grass, catch_electric, catch_psychic, catch_ice, catch_dragon, catch_dark, catch_fairy, + wash_pokemon, wild_tera, auto_30, tera_raid, sandwich_three, bitter_sandwich, sweet_sandwich, salty_sandwich, sour_sandwich, spicy_sandwich, hatch_egg, + photo_normal, photo_fighting, photo_flying, photo_poison, photo_ground, photo_rock, photo_bug, photo_ghost, photo_steel, photo_fire, photo_water, + photo_grass, photo_electric, photo_psychic, photo_ice, photo_dragon, photo_dark, photo_fairy, + ditto_central, ditto_canyon, ditto_coastal, ditto_polar, ditto_savanna, group_canyon, group_coastal, group_polar, group_savanna, group_eyewear, group_nonuniform, + group_masks, sandwich_four, catch_hint, catch_hint2, + UnableToDetect +}; + +enum class BBQAction{ + run, + skip, + reroll +}; + +//Quest exclusion table +const EnumDropdownDatabase& BBQuests_database(); + +class BBQuestTableRow : public EditableTableRow{ +public: + BBQuestTableRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + EnumDropdownCell quest; + EnumDropdownCell action; +}; + +class BBQuestTable : public EditableTableOption_t{ +public: + BBQuestTable(); + + virtual std::vector make_header() const; + std::vector> make_defaults(); +}; + + +//BBQ Options +class BBQOption : public GroupOption{ + +public: + // Include the language option in the box. + BBQOption() + : BBQOption(nullptr) + {} + + // Don't include language option. Give it one instead. + BBQOption(OCR::LanguageOCROption& language_option) + : BBQOption(&language_option) + {} + +private: + std::unique_ptr m_language_owner; + +public: + enum class OOEggs { + Stop, + Reroll, + KeepGoing, + }; + + OCR::LanguageOCROption& LANGUAGE; + + SimpleIntegerOption NUM_QUESTS; + SimpleIntegerOption SAVE_NUM_QUESTS; + + BBQuestTable QUEST_EXCLUSIONS; + + BooleanCheckBoxOption INVERTED_FLIGHT; + + //For catching pokemon quests + BooleanCheckBoxOption QUICKBALL; + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + //BattleMoveTable BATTLE_MOVES; No need, not catching legendaries. + + //For egg hatching quest + SimpleIntegerOption NUM_EGGS; + EnumDropdownOption OUT_OF_EGGS; + BooleanCheckBoxOption FIX_TIME_FOR_HATCH; + + //Tera raid + TeraAIOption BATTLE_AI; + TeraFarmerCatchOnWin CATCH_ON_WIN; + + SimpleIntegerOption NUM_RETRIES; + + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + +private: + BBQOption(OCR::LanguageOCROption* language_option); +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.cpp index f7535ad7e6..f132ce0114 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.cpp @@ -1,64 +1,64 @@ -/* Battle Move Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_BattleMoveTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -const EnumDropdownDatabase& Battle_move_enum_database(){ - static EnumDropdownDatabase database{ - {BattleMoveType::Move1, "move1", "Move 1"}, - {BattleMoveType::Move2, "move2", "Move 2"}, - {BattleMoveType::Move3, "move3", "Move 3"}, - {BattleMoveType::Move4, "move4", "Move 4"}, - //{BattleMoveType::tera, "tera", "Tera"}, - }; - return database; -} - -BattleMoveTableRow::BattleMoveTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , type(Battle_move_enum_database(), LockMode::UNLOCK_WHILE_RUNNING, BattleMoveType::Move1) - , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "(e.g. False Swipe, Thunder Wave)") -{ - PA_ADD_OPTION(type); - PA_ADD_OPTION(notes); -} -std::unique_ptr BattleMoveTableRow::clone() const{ - std::unique_ptr ret(new BattleMoveTableRow(parent())); - ret->type.set(type); - ret->notes.set(notes); - return ret; -} - -BattleMoveTable::BattleMoveTable() - : EditableTableOption_t( - "Move Table:
" - "Run this sequence of moves for your lead Pokemon only. " - "If your lead faints or the end of the table is reached, the program will switch to throwing the selected ball. ", - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - -std::vector BattleMoveTable::make_header() const{ - return { - "Move", - "Notes", - }; -} -std::vector> BattleMoveTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(new BattleMoveTableRow(*this)); - return ret; -} - - -} -} -} +/* Battle Move Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_BattleMoveTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +const EnumDropdownDatabase& Battle_move_enum_database(){ + static EnumDropdownDatabase database{ + {BattleMoveType::Move1, "move1", "Move 1"}, + {BattleMoveType::Move2, "move2", "Move 2"}, + {BattleMoveType::Move3, "move3", "Move 3"}, + {BattleMoveType::Move4, "move4", "Move 4"}, + //{BattleMoveType::tera, "tera", "Tera"}, + }; + return database; +} + +BattleMoveTableRow::BattleMoveTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , type(Battle_move_enum_database(), LockMode::UNLOCK_WHILE_RUNNING, BattleMoveType::Move1) + , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "(e.g. False Swipe, Thunder Wave)") +{ + PA_ADD_OPTION(type); + PA_ADD_OPTION(notes); +} +std::unique_ptr BattleMoveTableRow::clone() const{ + std::unique_ptr ret(new BattleMoveTableRow(parent())); + ret->type.set(type); + ret->notes.set(notes); + return ret; +} + +BattleMoveTable::BattleMoveTable() + : EditableTableOption_t( + "Move Table:
" + "Run this sequence of moves for your lead Pokemon only. " + "If your lead faints or the end of the table is reached, the program will switch to throwing the selected ball. ", + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + +std::vector BattleMoveTable::make_header() const{ + return { + "Move", + "Notes", + }; +} +std::vector> BattleMoveTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(new BattleMoveTableRow(*this)); + return ret; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.h index 76e8358bef..d54b477d47 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_BattleMoveTable.h @@ -1,50 +1,50 @@ -/* Battle Move Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BattleMoveTable_H -#define PokemonAutomation_PokemonSV_BattleMoveTable_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class BattleMoveType{ - Move1, - Move2, - Move3, - Move4, -}; -const EnumDropdownDatabase& Battle_move_enum_database(); - -class BattleMoveTableRow : public EditableTableRow{ -public: - BattleMoveTableRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - EnumDropdownCell type; - StringCell notes; -}; - -class BattleMoveTable : public EditableTableOption_t{ -public: - BattleMoveTable(); - - virtual std::vector make_header() const; - std::vector> make_defaults(); -}; - - -} -} -} -#endif +/* Battle Move Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BattleMoveTable_H +#define PokemonAutomation_PokemonSV_BattleMoveTable_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class BattleMoveType{ + Move1, + Move2, + Move3, + Move4, +}; +const EnumDropdownDatabase& Battle_move_enum_database(); + +class BattleMoveTableRow : public EditableTableRow{ +public: + BattleMoveTableRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + EnumDropdownCell type; + StringCell notes; +}; + +class BattleMoveTable : public EditableTableOption_t{ +public: + BattleMoveTable(); + + virtual std::vector make_header() const; + std::vector> make_defaults(); +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.cpp index 70886ca553..bb337978d6 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.cpp @@ -1,46 +1,46 @@ -/* Egg Power Sandwich Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_EggPowerSandwichOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -EggPowerSandwichOption::EggPowerSandwichOption() - : GroupOption("Egg Power Sandwich", LockMode::UNLOCK_WHILE_RUNNING) - , MAX_NUM_SANDWICHES( - "Max Sandwiches:
How many sandwiches you can make before running out of ingredients.", - LockMode::UNLOCK_WHILE_RUNNING, - 100, 0, 999 - ) - , EGG_SANDWICH_TYPE( - "Sandwich Recipe:
Which sandwich to get egg power.
" - "Great Peanut Butter Sandwich: Use recipe No. 17. Must have enough ingredients to make it and ALL the other unlocked sandwich recipes for reliable recipe detection.
" - "Two Sweet/Sweet and Salty/Sweet and Bitter Herbs and Lettuce: use the Lettuce and two Herbs. Must provide Game Language option to read ingredient lists.", - { - {EggSandwichType::GREAT_PEANUT_BUTTER, "great-peanut-butter", "Great Peanut Butter Sandwich"}, - {EggSandwichType::TWO_SWEET_HERBS, "two-sweet-herbs", "Two Sweet Herbs and Lettuce"}, - {EggSandwichType::SALTY_SWEET_HERBS, "salty-sweet-herbs", "Sweet and Salty Herbs and Lettuce"}, - {EggSandwichType::BITTER_SWEET_HERBS, "bitter-sweet-herbs", "Sweet and Bitter Herbs and Lettuce"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - EggSandwichType::GREAT_PEANUT_BUTTER - ) -{ - PA_ADD_OPTION(MAX_NUM_SANDWICHES); - PA_ADD_OPTION(EGG_SANDWICH_TYPE); -} - - - - - -} -} -} +/* Egg Power Sandwich Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_EggPowerSandwichOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +EggPowerSandwichOption::EggPowerSandwichOption() + : GroupOption("Egg Power Sandwich", LockMode::UNLOCK_WHILE_RUNNING) + , MAX_NUM_SANDWICHES( + "Max Sandwiches:
How many sandwiches you can make before running out of ingredients.", + LockMode::UNLOCK_WHILE_RUNNING, + 100, 0, 999 + ) + , EGG_SANDWICH_TYPE( + "Sandwich Recipe:
Which sandwich to get egg power.
" + "Great Peanut Butter Sandwich: Use recipe No. 17. Must have enough ingredients to make it and ALL the other unlocked sandwich recipes for reliable recipe detection.
" + "Two Sweet/Sweet and Salty/Sweet and Bitter Herbs and Lettuce: use the Lettuce and two Herbs. Must provide Game Language option to read ingredient lists.", + { + {EggSandwichType::GREAT_PEANUT_BUTTER, "great-peanut-butter", "Great Peanut Butter Sandwich"}, + {EggSandwichType::TWO_SWEET_HERBS, "two-sweet-herbs", "Two Sweet Herbs and Lettuce"}, + {EggSandwichType::SALTY_SWEET_HERBS, "salty-sweet-herbs", "Sweet and Salty Herbs and Lettuce"}, + {EggSandwichType::BITTER_SWEET_HERBS, "bitter-sweet-herbs", "Sweet and Bitter Herbs and Lettuce"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + EggSandwichType::GREAT_PEANUT_BUTTER + ) +{ + PA_ADD_OPTION(MAX_NUM_SANDWICHES); + PA_ADD_OPTION(EGG_SANDWICH_TYPE); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h index 8eac0942da..daa4de9631 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h @@ -1,39 +1,39 @@ -/* Egg Power Sandwich Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EggPowerSandwichOption_H -#define PokemonAutomation_PokemonSV_EggPowerSandwichOption_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class EggPowerSandwichOption : public GroupOption{ -public: - EggPowerSandwichOption(); - - // Make sure herb indices are correct. If they are wrong, throw UserSetUpError. - // void make_egg_sandwich() - -public: - SimpleIntegerOption MAX_NUM_SANDWICHES; - EnumDropdownOption EGG_SANDWICH_TYPE; -}; - - - - -} -} -} -#endif +/* Egg Power Sandwich Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EggPowerSandwichOption_H +#define PokemonAutomation_PokemonSV_EggPowerSandwichOption_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class EggPowerSandwichOption : public GroupOption{ +public: + EggPowerSandwichOption(); + + // Make sure herb indices are correct. If they are wrong, throw UserSetUpError. + // void make_egg_sandwich() + +public: + SimpleIntegerOption MAX_NUM_SANDWICHES; + EnumDropdownOption EGG_SANDWICH_TYPE; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.cpp index 4327c6de51..53eb347582 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.cpp @@ -1,146 +1,146 @@ -/* Encounter Filter Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Resources/PokemonSV_NameDatabase.h" -#include "PokemonSV_EncounterActionsTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - - -const EnumDropdownDatabase& EncounterFilterAction_database(){ - static EnumDropdownDatabase database{ - {EncounterActionsAction::RUN_AWAY, "run-away", "Run Away"}, - {EncounterActionsAction::STOP_PROGRAM, "stop-program", "Stop Program"}, - {EncounterActionsAction::THROW_BALLS, "throw-balls", "Throw Balls"}, - {EncounterActionsAction::THROW_BALLS_AND_SAVE, "throw-balls-and-save", "Throw Balls. Save if caught."}, - }; - return database; -} -const EnumDropdownDatabase& EncounterFilterShininess_database(){ - static EnumDropdownDatabase database{ - {EncounterActionsShininess::ANYTHING, "anything", "Anything"}, - {EncounterActionsShininess::NOT_SHINY, "not-shiny", "Not Shiny"}, - {EncounterActionsShininess::SHINY, "shiny", "Shiny"}, - }; - return database; -} - - - - -EncounterActionsRow::~EncounterActionsRow(){ - action.remove_listener(*this); -} -EncounterActionsRow::EncounterActionsRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , pokemon( - ALL_POKEMON_NAMES(), - LockMode::UNLOCK_WHILE_RUNNING, - "glimmora" - ) - , shininess( - EncounterFilterShininess_database(), - LockMode::UNLOCK_WHILE_RUNNING, - EncounterActionsShininess::SHINY - ) - , action( - EncounterFilterAction_database(), - LockMode::UNLOCK_WHILE_RUNNING, - EncounterActionsAction::STOP_PROGRAM - ) - , pokeball("poke-ball") - , ball_limit(LockMode::UNLOCK_WHILE_RUNNING, 40, 1, 999) -{ - PA_ADD_OPTION(pokemon); - PA_ADD_OPTION(shininess); - PA_ADD_OPTION(action); - PA_ADD_OPTION(pokeball); - PA_ADD_OPTION(ball_limit); - - EncounterActionsRow::on_config_value_changed(this); - - action.add_listener(*this); -} -std::unique_ptr EncounterActionsRow::clone() const{ - std::unique_ptr ret(new EncounterActionsRow(parent())); - ret->action.set(action); - ret->pokeball.set_by_index(pokeball.index()); - ret->pokemon.set_by_index(pokemon.index()); - ret->shininess.set(shininess); - ret->ball_limit.set(ball_limit); - return ret; -} -EncounterActionsEntry EncounterActionsRow::snapshot() const{ - return { - pokemon.slug(), - shininess, - action, - pokeball.slug(), - ball_limit, - }; -} -void EncounterActionsRow::on_config_value_changed(void* object){ - switch (action){ - case EncounterActionsAction::STOP_PROGRAM: - case EncounterActionsAction::RUN_AWAY: - pokeball.set_visibility(ConfigOptionState::HIDDEN); - ball_limit.set_visibility(ConfigOptionState::HIDDEN); - break; - case EncounterActionsAction::THROW_BALLS: - case EncounterActionsAction::THROW_BALLS_AND_SAVE: - pokeball.set_visibility(ConfigOptionState::ENABLED); - ball_limit.set_visibility(ConfigOptionState::ENABLED); - break; - } -} - - - -EncounterActionsTable::EncounterActionsTable() - : EditableTableOption_t( - "Actions Table:
" - "By default, the program will run from non-shinies and stop on shinies. " - "This table lets you override this default behavior for specific " + - STRING_POKEMON + " and their shininess. " - "If multiple entries match, the last one will be chosen. Note that running from " - "shinies will not despawn them since they cannot be killed via Let's Go.", - LockMode::UNLOCK_WHILE_RUNNING, - make_defaults() - ) -{} - -std::vector EncounterActionsTable::snapshot(){ - return EditableTableOption_t::snapshot(); -} -std::vector EncounterActionsTable::make_header() const{ - return { - "Species", - "Shininess", - "Action", - Pokemon::STRING_POKEBALL, - "Ball Limit" - }; -} -std::vector> EncounterActionsTable::make_defaults(){ - std::vector> ret; - return ret; -} - - - - - - -} -} -} +/* Encounter Filter Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Resources/PokemonSV_NameDatabase.h" +#include "PokemonSV_EncounterActionsTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + + +const EnumDropdownDatabase& EncounterFilterAction_database(){ + static EnumDropdownDatabase database{ + {EncounterActionsAction::RUN_AWAY, "run-away", "Run Away"}, + {EncounterActionsAction::STOP_PROGRAM, "stop-program", "Stop Program"}, + {EncounterActionsAction::THROW_BALLS, "throw-balls", "Throw Balls"}, + {EncounterActionsAction::THROW_BALLS_AND_SAVE, "throw-balls-and-save", "Throw Balls. Save if caught."}, + }; + return database; +} +const EnumDropdownDatabase& EncounterFilterShininess_database(){ + static EnumDropdownDatabase database{ + {EncounterActionsShininess::ANYTHING, "anything", "Anything"}, + {EncounterActionsShininess::NOT_SHINY, "not-shiny", "Not Shiny"}, + {EncounterActionsShininess::SHINY, "shiny", "Shiny"}, + }; + return database; +} + + + + +EncounterActionsRow::~EncounterActionsRow(){ + action.remove_listener(*this); +} +EncounterActionsRow::EncounterActionsRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , pokemon( + ALL_POKEMON_NAMES(), + LockMode::UNLOCK_WHILE_RUNNING, + "glimmora" + ) + , shininess( + EncounterFilterShininess_database(), + LockMode::UNLOCK_WHILE_RUNNING, + EncounterActionsShininess::SHINY + ) + , action( + EncounterFilterAction_database(), + LockMode::UNLOCK_WHILE_RUNNING, + EncounterActionsAction::STOP_PROGRAM + ) + , pokeball("poke-ball") + , ball_limit(LockMode::UNLOCK_WHILE_RUNNING, 40, 1, 999) +{ + PA_ADD_OPTION(pokemon); + PA_ADD_OPTION(shininess); + PA_ADD_OPTION(action); + PA_ADD_OPTION(pokeball); + PA_ADD_OPTION(ball_limit); + + EncounterActionsRow::on_config_value_changed(this); + + action.add_listener(*this); +} +std::unique_ptr EncounterActionsRow::clone() const{ + std::unique_ptr ret(new EncounterActionsRow(parent())); + ret->action.set(action); + ret->pokeball.set_by_index(pokeball.index()); + ret->pokemon.set_by_index(pokemon.index()); + ret->shininess.set(shininess); + ret->ball_limit.set(ball_limit); + return ret; +} +EncounterActionsEntry EncounterActionsRow::snapshot() const{ + return { + pokemon.slug(), + shininess, + action, + pokeball.slug(), + ball_limit, + }; +} +void EncounterActionsRow::on_config_value_changed(void* object){ + switch (action){ + case EncounterActionsAction::STOP_PROGRAM: + case EncounterActionsAction::RUN_AWAY: + pokeball.set_visibility(ConfigOptionState::HIDDEN); + ball_limit.set_visibility(ConfigOptionState::HIDDEN); + break; + case EncounterActionsAction::THROW_BALLS: + case EncounterActionsAction::THROW_BALLS_AND_SAVE: + pokeball.set_visibility(ConfigOptionState::ENABLED); + ball_limit.set_visibility(ConfigOptionState::ENABLED); + break; + } +} + + + +EncounterActionsTable::EncounterActionsTable() + : EditableTableOption_t( + "Actions Table:
" + "By default, the program will run from non-shinies and stop on shinies. " + "This table lets you override this default behavior for specific " + + STRING_POKEMON + " and their shininess. " + "If multiple entries match, the last one will be chosen. Note that running from " + "shinies will not despawn them since they cannot be killed via Let's Go.", + LockMode::UNLOCK_WHILE_RUNNING, + make_defaults() + ) +{} + +std::vector EncounterActionsTable::snapshot(){ + return EditableTableOption_t::snapshot(); +} +std::vector EncounterActionsTable::make_header() const{ + return { + "Species", + "Shininess", + "Action", + Pokemon::STRING_POKEBALL, + "Ball Limit" + }; +} +std::vector> EncounterActionsTable::make_defaults(){ + std::vector> ret; + return ret; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.h index 401508c08d..f874040fba 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterActionsTable.h @@ -1,86 +1,86 @@ -/* Encounter Filter Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EncounterFilterTable_H -#define PokemonAutomation_PokemonSV_EncounterFilterTable_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class EncounterActionsAction{ - STOP_PROGRAM, - RUN_AWAY, - THROW_BALLS, - THROW_BALLS_AND_SAVE, -}; - -enum class EncounterActionsShininess{ - ANYTHING, - NOT_SHINY, - SHINY, -}; - - - -struct EncounterActionsEntry{ - std::string pokemon; - EncounterActionsShininess shininess; - EncounterActionsAction action; - std::string ball; - uint16_t ball_limit; -}; - - -class EncounterActionsRow : public EditableTableRow, private ConfigOption::Listener{ -public: - ~EncounterActionsRow(); - EncounterActionsRow(EditableTableOption& parent_table); - - virtual std::unique_ptr clone() const override; - - EncounterActionsEntry snapshot() const; - -private: - virtual void on_config_value_changed(void* object) override; - -private: - StringSelectCell pokemon; - EnumDropdownCell shininess; - EnumDropdownCell action; - PokemonSwSh::PokemonBallSelectCell pokeball; - SimpleIntegerCell ball_limit; -}; - - -class EncounterActionsTable : public EditableTableOption_t{ -public: - EncounterActionsTable(); - - std::vector snapshot(); - - virtual std::vector make_header() const; - - std::vector> make_defaults(); - -}; - - - - - - -} -} -} -#endif +/* Encounter Filter Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EncounterFilterTable_H +#define PokemonAutomation_PokemonSV_EncounterFilterTable_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class EncounterActionsAction{ + STOP_PROGRAM, + RUN_AWAY, + THROW_BALLS, + THROW_BALLS_AND_SAVE, +}; + +enum class EncounterActionsShininess{ + ANYTHING, + NOT_SHINY, + SHINY, +}; + + + +struct EncounterActionsEntry{ + std::string pokemon; + EncounterActionsShininess shininess; + EncounterActionsAction action; + std::string ball; + uint16_t ball_limit; +}; + + +class EncounterActionsRow : public EditableTableRow, private ConfigOption::Listener{ +public: + ~EncounterActionsRow(); + EncounterActionsRow(EditableTableOption& parent_table); + + virtual std::unique_ptr clone() const override; + + EncounterActionsEntry snapshot() const; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + StringSelectCell pokemon; + EnumDropdownCell shininess; + EnumDropdownCell action; + PokemonSwSh::PokemonBallSelectCell pokeball; + SimpleIntegerCell ball_limit; +}; + + +class EncounterActionsTable : public EditableTableOption_t{ +public: + EncounterActionsTable(); + + std::vector snapshot(); + + virtual std::vector make_header() const; + + std::vector> make_defaults(); + +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterBotCommon.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterBotCommon.h index 2bd93d9f15..870a362f8c 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterBotCommon.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_EncounterBotCommon.h @@ -1,82 +1,82 @@ -/* Encounter Bot Common - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EncounterBotCommon_H -#define PokemonAutomation_PokemonSV_EncounterBotCommon_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_EncounterActionsTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -class EncounterBotCommonOptions : public BatchOption{ -public: - EncounterBotCommonOptions() - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , USE_FIRST_MOVE_IF_CANNOT_THROW_BALL( - "Use 1st Move if Cannot Throw Ball:
" - "If you can't throw a ball because the opponent is semi-invulnerable, use the 1st move instead. " - "Therefore, your first move should be non-damaging to avoid killing the wild " + STRING_POKEMON + ".", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , VIDEO_ON_SHINY( - "Video Capture:
Take a video of the encounter if it is shiny.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_CATCH_SUCCESS( - "Catch Success", - true, false, - {"Notifs"} - ) - , NOTIFICATION_CATCH_FAILED( - "Catch Failed", - true, true, - {"Notifs"} - ) - { - PA_ADD_OPTION(ACTIONS_TABLE); - PA_ADD_OPTION(USE_FIRST_MOVE_IF_CANNOT_THROW_BALL); - PA_ADD_OPTION(VIDEO_ON_SHINY); - } - - EncounterActionsTable ACTIONS_TABLE; - BooleanCheckBoxOption USE_FIRST_MOVE_IF_CANNOT_THROW_BALL; - BooleanCheckBoxOption VIDEO_ON_SHINY; - - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; -}; - - - - -} -} -} -#endif +/* Encounter Bot Common + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EncounterBotCommon_H +#define PokemonAutomation_PokemonSV_EncounterBotCommon_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_EncounterActionsTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +class EncounterBotCommonOptions : public BatchOption{ +public: + EncounterBotCommonOptions() + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , USE_FIRST_MOVE_IF_CANNOT_THROW_BALL( + "Use 1st Move if Cannot Throw Ball:
" + "If you can't throw a ball because the opponent is semi-invulnerable, use the 1st move instead. " + "Therefore, your first move should be non-damaging to avoid killing the wild " + STRING_POKEMON + ".", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , VIDEO_ON_SHINY( + "Video Capture:
Take a video of the encounter if it is shiny.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_CATCH_SUCCESS( + "Catch Success", + true, false, + {"Notifs"} + ) + , NOTIFICATION_CATCH_FAILED( + "Catch Failed", + true, true, + {"Notifs"} + ) + { + PA_ADD_OPTION(ACTIONS_TABLE); + PA_ADD_OPTION(USE_FIRST_MOVE_IF_CANNOT_THROW_BALL); + PA_ADD_OPTION(VIDEO_ON_SHINY); + } + + EncounterActionsTable ACTIONS_TABLE; + BooleanCheckBoxOption USE_FIRST_MOVE_IF_CANNOT_THROW_BALL; + BooleanCheckBoxOption VIDEO_ON_SHINY; + + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.cpp index b365b032b4..5e18367b9c 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.cpp @@ -1,181 +1,181 @@ -/* Player List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/FileDownloader.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSV_PlayerList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -PlayerListRow::PlayerListRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , enabled(LockMode::UNLOCK_WHILE_RUNNING, true) - , language( - Pokemon::PokemonNameReader::instance().languages(), - LockMode::UNLOCK_WHILE_RUNNING - ) - , name(false, LockMode::UNLOCK_WHILE_RUNNING, "", "Ash") - , log10p(LockMode::UNLOCK_WHILE_RUNNING, -2.5, -10, 0) - , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") -{ - PA_ADD_OPTION(enabled); - PA_ADD_OPTION(language); - PA_ADD_OPTION(name); - PA_ADD_OPTION(log10p); - PA_ADD_OPTION(notes); -} -std::unique_ptr PlayerListRow::clone() const{ - std::unique_ptr ret(new PlayerListRow(parent())); - ret->enabled = enabled.current_value(); - ret->language.set(language); - ret->name.set(name); - ret->log10p.set(log10p); - ret->notes.set(notes); - return ret; -} -PlayerListRowSnapshot PlayerListRow::snapshot() const{ - PlayerListRowSnapshot entry; - entry.enabled = enabled; - entry.language = language; - entry.name = name; - entry.log10p = log10p; - entry.notes = notes; - return entry; -} - - - - -PlayerListTable::PlayerListTable( - std::string label, - LockMode lock_while_running, - std::string notes_label -) - : EditableTableOption_t( - std::move(label), - lock_while_running, - make_defaults() - ) - , m_notes_label(std::move(notes_label)) -{} - - -std::vector PlayerListTable::make_header() const{ - return std::vector{ - "Enabled", "Language", "Player Name", "Match Threshold (log10p)", m_notes_label - }; -} - -std::vector> PlayerListTable::make_defaults(){ - std::vector> ret; -// ret.emplace_back(std::make_unique()); - return ret; -} -std::vector PlayerListTable::snapshot() const{ - return EditableTableOption_t::snapshot(); -} - - - - - -RaidPlayerBanList::RaidPlayerBanList() - : GroupOption( - "Bans:", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_ENABLED - ) - , text("Ban users from this raid. If a banned person tries to join, the raid will be reset.") - , local_table( - "Ban Table:
A table of users to ban by IGN. " - "The last column is a tuning parameter that specifies how well the name needs to match. " - "Text recognition is imperfect. So exact matches are rare and unreliable. " - "The value is the estimated log10 probability of matching by chance against random characters. " - "It is always negative. Lower value means the match needs to be more perfect to be a match.

" - "If you are getting false positive hits, decrease this value. (make it more negative)
" - "If it is failing to match, increase this value. (make it less negative)", - LockMode::UNLOCK_WHILE_RUNNING, - "Ban Reason (shown publicly)" - ) - , online_table_url( - false, - "Online Ban Table:
In addition to the above table, download a ban list from this URL.
" - "Thus the list of banned players is the combination of both your local table above and the downloaded one.
" - "This online ban list is automatically refreshed every raid - thus allowing the maintainer of the online list to manage bans for you.", - LockMode::UNLOCK_WHILE_RUNNING, - "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json", - "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json" - ) - , ignore_whitelist( - "Ignore Whitelist:
Ignore the developer whitelist.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , online_table("", LockMode::UNLOCK_WHILE_RUNNING, "") -{ - PA_ADD_OPTION(text); - PA_ADD_OPTION(local_table); - PA_ADD_OPTION(online_table_url); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(ignore_whitelist); - } -} - -#if 0 -std::vector RaidPlayerBanList::banlist_combined() const{ - std::vector table0 = local_table.snapshot(); - std::vector table1 = online_table.snapshot(); - for (PlayerListRowSnapshot& entry : table1){ - table0.emplace_back(std::move(entry)); - } - return table0; -} -#endif -std::vector RaidPlayerBanList::banlist_local() const{ - return local_table.snapshot(); -} -std::vector RaidPlayerBanList::banlist_global() const{ - return online_table.snapshot(); -} - -void RaidPlayerBanList::refresh_online_table(Logger& logger){ - std::string url = online_table_url; - if (url.empty()){ - online_table.clear(); - return; - } - logger.log("Refreshing online ban list..."); - try{ - JsonValue json = FileDownloader::download_json_file(logger, url); - if (json.is_null() || !json.is_array()){ - logger.log("Downloaded ban table is empty or invalid.", COLOR_RED); - return; - } - size_t items = json.to_array()->size(); - logger.log("Downloaded table has " + std::to_string(items) + " row(s)."); - online_table.load_json(json); - }catch (OperationFailedException&){} -} - - - - - - - - - - -} -} -} +/* Player List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/FileDownloader.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSV_PlayerList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +PlayerListRow::PlayerListRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , enabled(LockMode::UNLOCK_WHILE_RUNNING, true) + , language( + Pokemon::PokemonNameReader::instance().languages(), + LockMode::UNLOCK_WHILE_RUNNING + ) + , name(false, LockMode::UNLOCK_WHILE_RUNNING, "", "Ash") + , log10p(LockMode::UNLOCK_WHILE_RUNNING, -2.5, -10, 0) + , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "") +{ + PA_ADD_OPTION(enabled); + PA_ADD_OPTION(language); + PA_ADD_OPTION(name); + PA_ADD_OPTION(log10p); + PA_ADD_OPTION(notes); +} +std::unique_ptr PlayerListRow::clone() const{ + std::unique_ptr ret(new PlayerListRow(parent())); + ret->enabled = enabled.current_value(); + ret->language.set(language); + ret->name.set(name); + ret->log10p.set(log10p); + ret->notes.set(notes); + return ret; +} +PlayerListRowSnapshot PlayerListRow::snapshot() const{ + PlayerListRowSnapshot entry; + entry.enabled = enabled; + entry.language = language; + entry.name = name; + entry.log10p = log10p; + entry.notes = notes; + return entry; +} + + + + +PlayerListTable::PlayerListTable( + std::string label, + LockMode lock_while_running, + std::string notes_label +) + : EditableTableOption_t( + std::move(label), + lock_while_running, + make_defaults() + ) + , m_notes_label(std::move(notes_label)) +{} + + +std::vector PlayerListTable::make_header() const{ + return std::vector{ + "Enabled", "Language", "Player Name", "Match Threshold (log10p)", m_notes_label + }; +} + +std::vector> PlayerListTable::make_defaults(){ + std::vector> ret; +// ret.emplace_back(std::make_unique()); + return ret; +} +std::vector PlayerListTable::snapshot() const{ + return EditableTableOption_t::snapshot(); +} + + + + + +RaidPlayerBanList::RaidPlayerBanList() + : GroupOption( + "Bans:", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_ENABLED + ) + , text("Ban users from this raid. If a banned person tries to join, the raid will be reset.") + , local_table( + "Ban Table:
A table of users to ban by IGN. " + "The last column is a tuning parameter that specifies how well the name needs to match. " + "Text recognition is imperfect. So exact matches are rare and unreliable. " + "The value is the estimated log10 probability of matching by chance against random characters. " + "It is always negative. Lower value means the match needs to be more perfect to be a match.

" + "If you are getting false positive hits, decrease this value. (make it more negative)
" + "If it is failing to match, increase this value. (make it less negative)", + LockMode::UNLOCK_WHILE_RUNNING, + "Ban Reason (shown publicly)" + ) + , online_table_url( + false, + "Online Ban Table:
In addition to the above table, download a ban list from this URL.
" + "Thus the list of banned players is the combination of both your local table above and the downloaded one.
" + "This online ban list is automatically refreshed every raid - thus allowing the maintainer of the online list to manage bans for you.", + LockMode::UNLOCK_WHILE_RUNNING, + "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json", + "https://raw.githubusercontent.com/PokemonAutomation/ServerConfigs-PA-SHA/main/PokemonScarletViolet/TeraAutoHost-BanList.json" + ) + , ignore_whitelist( + "Ignore Whitelist:
Ignore the developer whitelist.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , online_table("", LockMode::UNLOCK_WHILE_RUNNING, "") +{ + PA_ADD_OPTION(text); + PA_ADD_OPTION(local_table); + PA_ADD_OPTION(online_table_url); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(ignore_whitelist); + } +} + +#if 0 +std::vector RaidPlayerBanList::banlist_combined() const{ + std::vector table0 = local_table.snapshot(); + std::vector table1 = online_table.snapshot(); + for (PlayerListRowSnapshot& entry : table1){ + table0.emplace_back(std::move(entry)); + } + return table0; +} +#endif +std::vector RaidPlayerBanList::banlist_local() const{ + return local_table.snapshot(); +} +std::vector RaidPlayerBanList::banlist_global() const{ + return online_table.snapshot(); +} + +void RaidPlayerBanList::refresh_online_table(Logger& logger){ + std::string url = online_table_url; + if (url.empty()){ + online_table.clear(); + return; + } + logger.log("Refreshing online ban list..."); + try{ + JsonValue json = FileDownloader::download_json_file(logger, url); + if (json.is_null() || !json.is_array()){ + logger.log("Downloaded ban table is empty or invalid.", COLOR_RED); + return; + } + size_t items = json.to_array()->size(); + logger.log("Downloaded table has " + std::to_string(items) + " row(s)."); + online_table.load_json(json); + }catch (OperationFailedException&){} +} + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.h index cdce1a5bb5..ebd64c48d8 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_PlayerList.h @@ -1,97 +1,97 @@ -/* Player List - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PlayerList_H -#define PokemonAutomation_PokemonSV_PlayerList_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "CommonTools/Options/LanguageOCROption.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -struct PlayerListRowSnapshot{ - bool enabled; - Language language; - std::string name; - double log10p; - std::string notes; -}; - - -class PlayerListRow : public EditableTableRow{ -public: - PlayerListRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const; - - PlayerListRowSnapshot snapshot() const; - -public: - BooleanCheckBoxCell enabled; - OCR::LanguageOCRCell language; - StringCell name; - FloatingPointCell log10p; - StringCell notes; -}; -class PlayerListTable : public EditableTableOption_t{ -public: - PlayerListTable( - std::string label, - LockMode lock_while_running, - std::string notes_label - ); - - virtual std::vector make_header() const; - std::vector> make_defaults(); - - std::vector snapshot() const; - -private: - std::string m_notes_label; -}; - - - - -class RaidPlayerBanList : public GroupOption{ -public: - RaidPlayerBanList(); - - void refresh_online_table(Logger& logger); - -// std::vector banlist_combined() const; - std::vector banlist_local() const; - std::vector banlist_global() const; - -public: - StaticTextOption text; - PlayerListTable local_table; - StringOption online_table_url; - BooleanCheckBoxOption ignore_whitelist; - -private: - PlayerListTable online_table; -}; - - - - - - -} -} -} -#endif +/* Player List + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PlayerList_H +#define PokemonAutomation_PokemonSV_PlayerList_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "CommonTools/Options/LanguageOCROption.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +struct PlayerListRowSnapshot{ + bool enabled; + Language language; + std::string name; + double log10p; + std::string notes; +}; + + +class PlayerListRow : public EditableTableRow{ +public: + PlayerListRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const; + + PlayerListRowSnapshot snapshot() const; + +public: + BooleanCheckBoxCell enabled; + OCR::LanguageOCRCell language; + StringCell name; + FloatingPointCell log10p; + StringCell notes; +}; +class PlayerListTable : public EditableTableOption_t{ +public: + PlayerListTable( + std::string label, + LockMode lock_while_running, + std::string notes_label + ); + + virtual std::vector make_header() const; + std::vector> make_defaults(); + + std::vector snapshot() const; + +private: + std::string m_notes_label; +}; + + + + +class RaidPlayerBanList : public GroupOption{ +public: + RaidPlayerBanList(); + + void refresh_online_table(Logger& logger); + +// std::vector banlist_combined() const; + std::vector banlist_local() const; + std::vector banlist_global() const; + +public: + StaticTextOption text; + PlayerListTable local_table; + StringOption online_table_url; + BooleanCheckBoxOption ignore_whitelist; + +private: + PlayerListTable online_table; +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.cpp index f7f1d0f5b2..1c9c29de70 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.cpp @@ -1,60 +1,60 @@ -/* Sandwich Ingredients Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSV_SandwichIngredientsOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -StringSelectDatabase make_sandwich_ingredient_database(){ - StringSelectDatabase ret; - for (const auto& slug : ALL_SANDWICH_FILLINGS_SLUGS()){ - const SandwichIngredientNames& data = get_ingredient_name(slug); - const SpriteDatabase::Sprite* sprite = SANDWICH_FILLINGS_DATABASE().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); - } - } - for (const auto& slug : ALL_SANDWICH_CONDIMENTS_SLUGS()){ - const SandwichIngredientNames& data = get_ingredient_name(slug); - const SpriteDatabase::Sprite* sprite = SANDWICH_CONDIMENTS_DATABASE().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); - } - } - - return ret; -} -const StringSelectDatabase& SANDWICH_INGREDIENT_DATABASE(){ - static StringSelectDatabase database = make_sandwich_ingredient_database(); - return database; -} - - -SandwichIngredientsTableCell::SandwichIngredientsTableCell( - const std::string& default_slug -) - : StringSelectCell( - SANDWICH_INGREDIENT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - - -} -} -} +/* Sandwich Ingredients Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSV_SandwichIngredientsOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +StringSelectDatabase make_sandwich_ingredient_database(){ + StringSelectDatabase ret; + for (const auto& slug : ALL_SANDWICH_FILLINGS_SLUGS()){ + const SandwichIngredientNames& data = get_ingredient_name(slug); + const SpriteDatabase::Sprite* sprite = SANDWICH_FILLINGS_DATABASE().get_nothrow(slug); + if (sprite == nullptr){ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + } + } + for (const auto& slug : ALL_SANDWICH_CONDIMENTS_SLUGS()){ + const SandwichIngredientNames& data = get_ingredient_name(slug); + const SpriteDatabase::Sprite* sprite = SANDWICH_CONDIMENTS_DATABASE().get_nothrow(slug); + if (sprite == nullptr){ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + } + } + + return ret; +} +const StringSelectDatabase& SANDWICH_INGREDIENT_DATABASE(){ + static StringSelectDatabase database = make_sandwich_ingredient_database(); + return database; +} + + +SandwichIngredientsTableCell::SandwichIngredientsTableCell( + const std::string& default_slug +) + : StringSelectCell( + SANDWICH_INGREDIENT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.h index a80f97e066..f3fdfa3089 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsOption.h @@ -1,27 +1,27 @@ -/* Sandwich Ingredients Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichIngredientsOption_H -#define PokemonAutomation_PokemonSV_SandwichIngredientsOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class SandwichIngredientsTableCell : public StringSelectCell{ -public: - SandwichIngredientsTableCell(const std::string& default_slug); -}; - - - -} -} -} -#endif +/* Sandwich Ingredients Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichIngredientsOption_H +#define PokemonAutomation_PokemonSV_SandwichIngredientsOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class SandwichIngredientsTableCell : public StringSelectCell{ +public: + SandwichIngredientsTableCell(const std::string& default_slug); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.cpp index 0481c164dd..ec4d9fde75 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.cpp @@ -1,53 +1,53 @@ -/* Sandwich Ingredients Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSV_SandwichIngredientsTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -SandwichIngredientsTableRow::SandwichIngredientsTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , item("lettuce") -{ - PA_ADD_OPTION(item); -} -std::unique_ptr SandwichIngredientsTableRow::clone() const{ - std::unique_ptr ret(new SandwichIngredientsTableRow(parent())); - ret->item.set_by_index(item.index()); - return ret; -} - -SandwichIngredientsTable::SandwichIngredientsTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - - -std::vector SandwichIngredientsTable::make_header() const{ - return std::vector{ - "Ingredient/Condiment", - }; -} - -std::vector> SandwichIngredientsTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} - - - -} -} -} +/* Sandwich Ingredients Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSV_SandwichIngredientsTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +SandwichIngredientsTableRow::SandwichIngredientsTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , item("lettuce") +{ + PA_ADD_OPTION(item); +} +std::unique_ptr SandwichIngredientsTableRow::clone() const{ + std::unique_ptr ret(new SandwichIngredientsTableRow(parent())); + ret->item.set_by_index(item.index()); + return ret; +} + +SandwichIngredientsTable::SandwichIngredientsTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + + +std::vector SandwichIngredientsTable::make_header() const{ + return std::vector{ + "Ingredient/Condiment", + }; +} + +std::vector> SandwichIngredientsTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.h index 076e46bfd2..dd80f0c708 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichIngredientsTable.h @@ -1,41 +1,41 @@ -/* Sandwich Ingredients Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichIngredientsTable_H -#define PokemonAutomation_PokemonSV_SandwichIngredientsTable_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonSV_SandwichIngredientsOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class SandwichIngredientsTableRow : public EditableTableRow{ -public: - SandwichIngredientsTableRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - SandwichIngredientsTableCell item; -}; - - -class SandwichIngredientsTable : public EditableTableOption_t{ -public: - SandwichIngredientsTable(std::string label); - - virtual std::vector make_header() const override; - - std::vector> make_defaults(); -}; - - - -} -} -} -#endif +/* Sandwich Ingredients Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichIngredientsTable_H +#define PokemonAutomation_PokemonSV_SandwichIngredientsTable_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonSV_SandwichIngredientsOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class SandwichIngredientsTableRow : public EditableTableRow{ +public: + SandwichIngredientsTableRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + SandwichIngredientsTableCell item; +}; + + +class SandwichIngredientsTable : public EditableTableOption_t{ +public: + SandwichIngredientsTable(std::string label); + + virtual std::vector make_header() const override; + + std::vector> make_defaults(); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.cpp index 3587b810b6..7a68d0edd4 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.cpp @@ -1,567 +1,567 @@ -/* Sandwich Maker Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -//#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV_SandwichMakerOption.h" -//#include "PokemonSV_SandwichIngredientsOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Map for standard+type recipes taking Base + Type to find SandwichRecipe -const std::map, SandwichRecipe>& PREMADE_SANDWICH_TYPE(){ - static const std::map, SandwichRecipe> map{ - {{BaseRecipe::non_shiny, PokemonType::normal}, SandwichRecipe::non_shiny_normal}, - {{BaseRecipe::shiny, PokemonType::normal}, SandwichRecipe::shiny_normal}, - {{BaseRecipe::shiny, PokemonType::fire}, SandwichRecipe::shiny_fire}, - {{BaseRecipe::shiny, PokemonType::water}, SandwichRecipe::shiny_water}, - {{BaseRecipe::shiny, PokemonType::electric},SandwichRecipe::shiny_electric}, - {{BaseRecipe::shiny, PokemonType::grass}, SandwichRecipe::shiny_grass}, - {{BaseRecipe::shiny, PokemonType::ice}, SandwichRecipe::shiny_ice}, - {{BaseRecipe::shiny, PokemonType::fighting},SandwichRecipe::shiny_fighting}, - {{BaseRecipe::shiny, PokemonType::poison}, SandwichRecipe::shiny_poison}, - {{BaseRecipe::shiny, PokemonType::ground}, SandwichRecipe::shiny_ground}, - {{BaseRecipe::shiny, PokemonType::flying}, SandwichRecipe::shiny_flying}, - {{BaseRecipe::shiny, PokemonType::psychic}, SandwichRecipe::shiny_psychic}, - {{BaseRecipe::shiny, PokemonType::bug}, SandwichRecipe::shiny_bug}, - {{BaseRecipe::shiny, PokemonType::rock}, SandwichRecipe::shiny_rock}, - {{BaseRecipe::shiny, PokemonType::ghost}, SandwichRecipe::shiny_ghost}, - {{BaseRecipe::shiny, PokemonType::dragon}, SandwichRecipe::shiny_dragon}, - {{BaseRecipe::shiny, PokemonType::dark}, SandwichRecipe::shiny_dark}, - {{BaseRecipe::shiny, PokemonType::steel}, SandwichRecipe::shiny_steel}, - {{BaseRecipe::shiny, PokemonType::fairy}, SandwichRecipe::shiny_fairy}, - {{BaseRecipe::huge, PokemonType::normal}, SandwichRecipe::huge_normal}, - {{BaseRecipe::huge, PokemonType::fire}, SandwichRecipe::huge_fire}, - {{BaseRecipe::huge, PokemonType::water}, SandwichRecipe::huge_water}, - {{BaseRecipe::huge, PokemonType::electric},SandwichRecipe::huge_electric}, - {{BaseRecipe::huge, PokemonType::grass}, SandwichRecipe::huge_grass}, - {{BaseRecipe::huge, PokemonType::ice}, SandwichRecipe::huge_ice}, - {{BaseRecipe::huge, PokemonType::fighting},SandwichRecipe::huge_fighting}, - {{BaseRecipe::huge, PokemonType::poison}, SandwichRecipe::huge_poison}, - {{BaseRecipe::huge, PokemonType::ground}, SandwichRecipe::huge_ground}, - {{BaseRecipe::huge, PokemonType::flying}, SandwichRecipe::huge_flying}, - {{BaseRecipe::huge, PokemonType::psychic}, SandwichRecipe::huge_psychic}, - {{BaseRecipe::huge, PokemonType::bug}, SandwichRecipe::huge_bug}, - {{BaseRecipe::huge, PokemonType::rock}, SandwichRecipe::huge_rock}, - {{BaseRecipe::huge, PokemonType::ghost}, SandwichRecipe::huge_ghost}, - {{BaseRecipe::huge, PokemonType::dragon}, SandwichRecipe::huge_dragon}, - {{BaseRecipe::huge, PokemonType::dark}, SandwichRecipe::huge_dark}, - {{BaseRecipe::huge, PokemonType::steel}, SandwichRecipe::huge_steel}, - {{BaseRecipe::huge, PokemonType::fairy}, SandwichRecipe::huge_fairy}, - {{BaseRecipe::tiny, PokemonType::normal}, SandwichRecipe::tiny_normal}, - {{BaseRecipe::tiny, PokemonType::fire}, SandwichRecipe::tiny_fire}, - {{BaseRecipe::tiny, PokemonType::water}, SandwichRecipe::tiny_water}, - {{BaseRecipe::tiny, PokemonType::electric},SandwichRecipe::tiny_electric}, - {{BaseRecipe::tiny, PokemonType::grass}, SandwichRecipe::tiny_grass}, - {{BaseRecipe::tiny, PokemonType::ice}, SandwichRecipe::tiny_ice}, - {{BaseRecipe::tiny, PokemonType::fighting},SandwichRecipe::tiny_fighting}, - {{BaseRecipe::tiny, PokemonType::poison}, SandwichRecipe::tiny_poison}, - {{BaseRecipe::tiny, PokemonType::ground}, SandwichRecipe::tiny_ground}, - {{BaseRecipe::tiny, PokemonType::flying}, SandwichRecipe::tiny_flying}, - {{BaseRecipe::tiny, PokemonType::psychic}, SandwichRecipe::tiny_psychic}, - {{BaseRecipe::tiny, PokemonType::bug}, SandwichRecipe::tiny_bug}, - {{BaseRecipe::tiny, PokemonType::rock}, SandwichRecipe::tiny_rock}, - {{BaseRecipe::tiny, PokemonType::ghost}, SandwichRecipe::tiny_ghost}, - {{BaseRecipe::tiny, PokemonType::dragon}, SandwichRecipe::tiny_dragon}, - {{BaseRecipe::tiny, PokemonType::dark}, SandwichRecipe::tiny_dark}, - {{BaseRecipe::tiny, PokemonType::steel}, SandwichRecipe::tiny_steel}, - {{BaseRecipe::tiny, PokemonType::fairy}, SandwichRecipe::tiny_fairy}, - }; - return map; -} - -// Map for Other recipes -const std::map& PREMADE_SANDWICH_OTHER(){ - static const std::map map{ - {ParadoxRecipe::humungo3_greattusk_1, SandwichRecipe::humungo3_greattusk_1}, - {ParadoxRecipe::humungo2_screamtail_1, SandwichRecipe::humungo2_screamtail_1}, - {ParadoxRecipe::humungo2_screamtail_2, SandwichRecipe::humungo2_screamtail_2}, - {ParadoxRecipe::humungo2_brutebonnet_1, SandwichRecipe::humungo2_brutebonnet_1}, - {ParadoxRecipe::humungo2_brutebonnet_2, SandwichRecipe::humungo2_brutebonnet_2}, - {ParadoxRecipe::humungo3_fluttermane_1, SandwichRecipe::humungo3_fluttermane_1}, - {ParadoxRecipe::humungo3_fluttermane_2, SandwichRecipe::humungo3_fluttermane_2}, - {ParadoxRecipe::humungo2_slitherwing_1, SandwichRecipe::humungo2_slitherwing_1}, - {ParadoxRecipe::humungo2_slitherwing_2, SandwichRecipe::humungo2_slitherwing_2}, - {ParadoxRecipe::humungo3_sandyshocks_1, SandwichRecipe::humungo3_sandyshocks_1}, - {ParadoxRecipe::humungo3_sandyshocks_2, SandwichRecipe::humungo3_sandyshocks_2}, - {ParadoxRecipe::humungo3_roaringmoon_1, SandwichRecipe::humungo3_roaringmoon_1}, - {ParadoxRecipe::humungo3_roaringmoon_2, SandwichRecipe::humungo3_roaringmoon_2}, - {ParadoxRecipe::humungo2_irontreads_1, SandwichRecipe::humungo2_irontreads_1}, - {ParadoxRecipe::humungo2_irontreads_2, SandwichRecipe::humungo2_irontreads_2}, - {ParadoxRecipe::humungo2_ironbundle_1, SandwichRecipe::humungo2_ironbundle_1}, - {ParadoxRecipe::humungo2_ironbundle_2, SandwichRecipe::humungo2_ironbundle_2}, - {ParadoxRecipe::humungo2_ironhands_1, SandwichRecipe::humungo2_ironhands_1}, - {ParadoxRecipe::humungo2_ironhands_2, SandwichRecipe::humungo2_ironhands_2}, - {ParadoxRecipe::humungo2_ironjugulis_1, SandwichRecipe::humungo2_ironjugulis_1}, - {ParadoxRecipe::humungo2_ironjugulis_2, SandwichRecipe::humungo2_ironjugulis_2}, - {ParadoxRecipe::humungo3_ironmoth_1, SandwichRecipe::humungo3_ironmoth_1}, - {ParadoxRecipe::humungo3_ironmoth_2, SandwichRecipe::humungo3_ironmoth_2}, - {ParadoxRecipe::humungo3_ironthorns_1, SandwichRecipe::humungo3_ironthorns_1}, - {ParadoxRecipe::humungo3_ironthorns_2, SandwichRecipe::humungo3_ironthorns_2}, - {ParadoxRecipe::humungo2_ironvaliant_1, SandwichRecipe::humungo2_ironvaliant_1}, - {ParadoxRecipe::humungo2_ironvaliant_2, SandwichRecipe::humungo2_ironvaliant_2}, - {ParadoxRecipe::teensy3_greattusk_1, SandwichRecipe::teensy3_greattusk_1}, - {ParadoxRecipe::teensy2_screamtail_1, SandwichRecipe::teensy2_screamtail_1}, - {ParadoxRecipe::teensy2_screamtail_2, SandwichRecipe::teensy2_screamtail_2}, - {ParadoxRecipe::teensy2_brutebonnet_1, SandwichRecipe::teensy2_brutebonnet_1}, - {ParadoxRecipe::teensy3_fluttermane_1, SandwichRecipe::teensy3_fluttermane_1}, - {ParadoxRecipe::teensy2_sliterwing_1, SandwichRecipe::teensy2_sliterwing_1}, - {ParadoxRecipe::teensy2_sliterwing_2, SandwichRecipe::teensy2_sliterwing_2}, - {ParadoxRecipe::teensy3_sandyshocks_1, SandwichRecipe::teensy3_sandyshocks_1}, - {ParadoxRecipe::teensy3_sandyshocks_2, SandwichRecipe::teensy3_sandyshocks_2}, - {ParadoxRecipe::teensy3_roaringmoon_1, SandwichRecipe::teensy3_roaringmoon_1}, - {ParadoxRecipe::teensy2_irontreads_1, SandwichRecipe::teensy2_irontreads_1}, - {ParadoxRecipe::teensy2_irontreads_2, SandwichRecipe::teensy2_irontreads_2}, - {ParadoxRecipe::teensy2_ironbundle_1, SandwichRecipe::teensy2_ironbundle_1}, - {ParadoxRecipe::teensy2_ironbundle_2, SandwichRecipe::teensy2_ironbundle_2}, - {ParadoxRecipe::teensy2_ironhands_1, SandwichRecipe::teensy2_ironhands_1}, - {ParadoxRecipe::teensy2_ironjugulis_1, SandwichRecipe::teensy2_ironjugulis_1}, - {ParadoxRecipe::teensy3_ironmoth_1, SandwichRecipe::teensy3_ironmoth_1}, - {ParadoxRecipe::teensy3_ironthorns_1, SandwichRecipe::teensy3_ironthorns_1}, - {ParadoxRecipe::teensy2_ironvaliant_1, SandwichRecipe::teensy2_ironvaliant_1}, - {ParadoxRecipe::teensy2_ironvaliant_2, SandwichRecipe::teensy2_ironvaliant_2}, - }; - return map; -} - -// Leave the herba out, the user selects them as HERBA_ONE and HERBA_TWO. -// Remember the ingredient limits: Six fillings, four condiments. Two condiment slots will be taken by the Herba. -const std::map>& PREMADE_SANDWICH_INGREDIENTS(){ - static const std::map> map{ - {SandwichRecipe::non_shiny_normal, {"chorizo", "chorizo", "chorizo", "chorizo", "banana", "banana", "mayonnaise", "mayonnaise", "mayonnaise", "whipped-cream"}}, - {SandwichRecipe::shiny_normal, {"cucumber", "pickle", "tofu", "tofu", "tofu", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_fire, {"cucumber", "pickle", "red-bell-pepper", "red-bell-pepper","curry-powder","curry-powder", "red-bell-pepper"}}, - {SandwichRecipe::shiny_water, {"cucumber", "pickle", "cucumber", "cucumber", "cucumber","curry-powder","curry-powder"}}, - {SandwichRecipe::shiny_electric, {"cucumber", "pickle", "yellow-bell-pepper", "yellow-bell-pepper", "yellow-bell-pepper", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_grass, {"cucumber", "pickle", "lettuce", "lettuce", "lettuce", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_ice, {"cucumber", "pickle", "klawf-stick", "klawf-stick", "klawf-stick", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_fighting, {"cucumber", "pickle", "pickle", "pickle", "pickle", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_poison, {"cucumber", "pickle", "green-bell-pepper", "green-bell-pepper", "green-bell-pepper", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_ground, {"cucumber", "pickle", "ham", "ham", "ham", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_flying, {"cucumber", "pickle", "prosciutto", "prosciutto", "prosciutto", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_psychic, {"cucumber", "pickle", "onion", "onion", "onion", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_bug, {"cucumber", "pickle", "cherry-tomatoes", "cherry-tomatoes", "cherry-tomatoes", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_rock, {"cucumber", "pickle", "bacon", "bacon", "bacon", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_ghost, {"cucumber", "pickle", "red-onion", "red-onion", "red-onion", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_dragon, {"cucumber", "pickle", "avocado", "avocado", "avocado", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_dark, {"cucumber", "pickle", "smoked-fillet", "smoked-fillet", "smoked-fillet", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_steel, {"cucumber", "pickle", "hamburger", "hamburger", "hamburger", "curry-powder", "curry-powder"}}, - {SandwichRecipe::shiny_fairy, {"cucumber", "pickle", "tomato", "tomato", "tomato", "curry-powder", "curry-powder"}}, - {SandwichRecipe::huge_normal, {"tofu", "mustard", "mustard"}}, - {SandwichRecipe::huge_fire, {"red-bell-pepper", "mustard", "mustard"}}, - {SandwichRecipe::huge_water, {"cucumber", "mustard", "mustard"}}, - {SandwichRecipe::huge_electric, {"yellow-bell-pepper", "mustard", "mustard"}}, - {SandwichRecipe::huge_grass, {"lettuce", "mustard", "mustard"}}, - {SandwichRecipe::huge_ice, {"klawf-stick", "mustard", "mustard"}}, - {SandwichRecipe::huge_fighting, {"pickle", "mustard", "mustard"}}, - {SandwichRecipe::huge_poison, {"green-bell-pepper", "mustard", "mustard"}}, - {SandwichRecipe::huge_ground, {"ham", "mustard", "mustard"}}, - {SandwichRecipe::huge_flying, {"prosciutto", "mustard", "mustard"}}, - {SandwichRecipe::huge_psychic, {"onion", "mustard", "mustard"}}, - {SandwichRecipe::huge_bug, {"cherry-tomatoes", "mustard", "mustard"}}, - {SandwichRecipe::huge_rock, {"bacon", "mustard", "mustard"}}, - {SandwichRecipe::huge_ghost, {"red-onion", "mustard", "mustard"}}, - {SandwichRecipe::huge_dragon, {"avocado", "mustard", "mustard"}}, - {SandwichRecipe::huge_dark, {"smoked-fillet", "mustard", "mustard"}}, - {SandwichRecipe::huge_steel, {"hamburger", "mustard", "mustard"}}, - {SandwichRecipe::huge_fairy, {"tomato", "mustard", "mustard"}}, - {SandwichRecipe::tiny_normal, {"tofu", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_fire, {"red-bell-pepper", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_water, {"cucumber", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_electric, {"yellow-bell-pepper", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_grass, {"lettuce", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_ice, {"klawf-stick", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_fighting, {"pickle", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_poison, {"green-bell-pepper", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_ground, {"ham", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_flying, {"prosciutto", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_psychic, {"onion", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_bug, {"cherry-tomatoes", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_rock, {"bacon", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_ghost, {"red-onion", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_dragon, {"avocado", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_dark, {"smoked-fillet", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_steel, {"hamburger", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::tiny_fairy, {"tomato", "mayonnaise", "mayonnaise"}}, - {SandwichRecipe::humungo3_greattusk_1, {"herbed-sausage", "herbed-sausage", "herbed-sausage", "herbed-sausage", "ham", "horseradish", "jam", "wasabi", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_screamtail_1, {"noodles", "tomato", "tomato", "wasabi", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_screamtail_2, {"noodles", "potato-salad", "vinegar", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_brutebonnet_1, {"potato-salad", "lettuce", "lettuce", "wasabi", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_brutebonnet_2, {"potato-salad", "rice", "jam", "chili-sauce", "salty-herba-mystica"}}, - {SandwichRecipe::humungo3_fluttermane_1, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "tomato", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo3_fluttermane_2, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "olive-oil", "yogurt", "yogurt", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_slitherwing_1, {"cherry-tomatoes", "cherry-tomatoes", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_slitherwing_2, {"pickle", "potato-salad", "rice", "chili-sauce", "cream-cheese", "salty-herba-mystica"}}, - {SandwichRecipe::humungo3_sandyshocks_1, {"noodles", "noodles", "noodles", "noodles", "noodles", "mustard", "wasabi", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo3_sandyshocks_2, {"noodles", "noodles", "noodles", "noodles", "noodles", "mustard", "jam", "salty-herba-mystica"}}, - {SandwichRecipe::humungo3_roaringmoon_1, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "wasabi", "yogurt", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo3_roaringmoon_2, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "wasabi", "vinegar", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_irontreads_1, {"ham", "ham", "egg", "mustard", "curry-powder", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_irontreads_2, {"noodles", "potato-salad", "peanut-butter", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_ironbundle_1, {"cucumber", "cucumber", "noodles", "jam", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_ironbundle_2, {"noodles", "rice", "wasabi", "curry-powder", "pepper", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_ironhands_1, {"yellow-bell-pepper", "yellow-bell-pepper", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_ironhands_2, {"noodles", "pickle", "rice", "jam", "pepper", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_ironjugulis_1, {"egg", "smoked-fillet", "smoked-fillet", "yogurt", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_ironjugulis_2, {"potato-salad", "rice", "ketchup", "wasabi", "salty-herba-mystica"}}, - {SandwichRecipe::humungo3_ironmoth_1, {"chorizo", "chorizo", "chorizo", "noodles", "red-bell-pepper", "olive-oil", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo3_ironmoth_2, {"chorizo", "chorizo", "noodles", "noodles", "rice", "rice", "curry-powder", "salty-herba-mystica"}}, - {SandwichRecipe::humungo3_ironthorns_1, {"noodles", "noodles", "noodles", "noodles", "noodles", "marmalade", "mustard", "jam", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo3_ironthorns_2, {"noodles", "noodles", "noodles", "noodles", "noodles", "yellow-bell-pepper", "mustard", "mustard", "salty-herba-mystica"}}, - {SandwichRecipe::humungo2_ironvaliant_1, {"herbed-sausage", "tomato", "tomato", "marmalade", "wasabi", "yogurt", "spicy-herba-mystica"}}, - {SandwichRecipe::humungo2_ironvaliant_2, {"potato-salad", "rice", "tomato", "salty-herba-mystica"}}, - {SandwichRecipe::teensy3_greattusk_1, {"herbed-sausage", "herbed-sausage", "herbed-sausage", "noodles", "pickle", "horseradish", "horseradish", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_screamtail_1, {"egg", "onion", "onion", "chili-sauce", "wasabi", "yogurt", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_screamtail_2, {"herbed-sausage", "tomato", "tomato", "wasabi", "wasabi", "salty-herba-mystica"}}, - {SandwichRecipe::teensy2_brutebonnet_1, {"egg", "smoked-fillet", "smoked-fillet", "chili-sauce", "curry-powder", "jam", "sour-herba-mystica"}}, - {SandwichRecipe::teensy3_fluttermane_1, {"cheese", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "tomato", "curry-powder", "curry-powder", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_sliterwing_1, {"chorizo", "pickle", "pickle", "butter", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_sliterwing_2, {"chorizo", "pickle", "pickle", "curry-powder", "marmalade", "wasabi", "salty-herba-mystica"}}, - {SandwichRecipe::teensy3_sandyshocks_1, {"noodles", "noodles", "noodles", "noodles", "yellow-bell-pepper", "herbed-sausage", "horseradish", "sour-herba-mystica"}}, - {SandwichRecipe::teensy3_sandyshocks_2, {"fried-fillet", "fried-fillet", "noodles", "noodles", "noodles", "banana", "wasabi", "wasabi", "wasabi", "salty-herba-mystica"}}, - {SandwichRecipe::teensy3_roaringmoon_1, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "herbed-sausage", "wasabi", "wasabi", "wasabi", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_irontreads_1, {"hamburger", "hamburger", "herbed-sausage", "curry-powder", "whipped-cream", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_irontreads_2, {"hamburger", "hamburger", "herbed-sausage", "curry-powder", "horseradish", "peanut-butter", "salty-herba-mystica"}}, - {SandwichRecipe::teensy2_ironbundle_1, {"herbed-sausage", "klawf-stick", "klawf-stick", "cream-cheese", "wasabi", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_ironbundle_2, {"herbed-sausage", "klawf-stick", "klawf-stick", "curry-powder", "pepper", "wasabi", "salty-herba-mystica"}}, - {SandwichRecipe::teensy2_ironhands_1, {"yellow-bell-pepper", "yellow-bell-pepper", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_ironjugulis_1, {"egg", "smoked-fillet", "smoked-fillet", "yogurt", "salt", "sour-herba-mystica"}}, - {SandwichRecipe::teensy3_ironmoth_1, {"chorizo", "chorizo", "chorizo", "noodles", "red-bell-pepper", "olive-oil", "sour-herba-mystica"}}, - {SandwichRecipe::teensy3_ironthorns_1, {"noodles", "noodles", "noodles", "noodles", "egg", "yellow-bell-pepper", "horseradish", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_ironvaliant_1, {"pickle", "pickle", "egg", "salt", "yogurt", "marmalade", "sour-herba-mystica"}}, - {SandwichRecipe::teensy2_ironvaliant_2, {"pickle", "pickle", "egg", "wasabi", "wasabi", "yogurt", "salty-herba-mystica"}}, - }; - return map; -} - - - - - -std::string SandwichMakerOption::herba_to_string(HerbaSelection value){ - switch (value){ - case HerbaSelection::bitter_herba_mystica: - return "bitter-herba-mystica"; - case HerbaSelection::salty_herba_mystica: - return "salty-herba-mystica"; - case HerbaSelection::sour_herba_mystica: - return "sour-herba-mystica"; - case HerbaSelection::spicy_herba_mystica: - return "spicy-herba-mystica"; - case HerbaSelection::sweet_herba_mystica: - return "sweet-herba-mystica"; - } - return "ERROR"; -} - -std::vector SandwichMakerOption::get_premade_ingredients(SandwichRecipe value){ - auto iter = PREMADE_SANDWICH_INGREDIENTS().find(value); - return iter->second; -} - -bool SandwichMakerOption::two_herba_required(BaseRecipe value){ - if (value == BaseRecipe::shiny || value == BaseRecipe::huge || value == BaseRecipe::tiny){ - return true; - } - return false; -} - -SandwichRecipe SandwichMakerOption::get_premade_sandwich_recipe(BaseRecipe base, PokemonType type, ParadoxRecipe paradox){ - if (base == BaseRecipe::paradox) - { - auto iter = PREMADE_SANDWICH_OTHER().find(paradox); - return iter->second; - }else{ - auto iter = PREMADE_SANDWICH_TYPE().find(std::make_pair(base, type)); - return iter->second; - } -} - -SandwichMakerOption::~SandwichMakerOption(){ - HERBA_TWO.remove_listener(*this); - HERBA_ONE.remove_listener(*this); - TYPE.remove_listener(*this); - BASE_RECIPE.remove_listener(*this); -} - -SandwichMakerOption::SandwichMakerOption( - std::string label, - OCR::LanguageOCROption* language_option, - BaseRecipe base_recipe, - bool show_save_option, - GroupOption::EnableMode enable_mode -) - : GroupOption( - std::move(label), - LockMode::UNLOCK_WHILE_RUNNING, - enable_mode - ) - , m_language_owner(language_option == nullptr - ? new OCR::LanguageOCROption( - "Game Language:
Required to read ingredients.", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - : nullptr - ) - , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) - , SAVE_GAME_BEFORE_SANDWICH( - "Save game before making sandwich:
Sandwich making can be unreliable. " - "Save the game before each sandwich to prevent loss of progress.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , BASE_RECIPE( - "Sandwich Recipe:
Select a recipe to make a sandwich with preset ingredients, or select Custom Sandwich to make a sandwich using the table below. " - "Refer to the documentation for recipe ingredients and valid Herba Mystica combinations.", - { - {BaseRecipe::non_shiny, "non-shiny", "Normal Encounter (non-shiny)"}, - {BaseRecipe::shiny, "shiny", "Sparkling + Title + Encounter"}, - {BaseRecipe::huge, "huge", "Sparkling + Title + Humungo"}, - {BaseRecipe::tiny, "tiny", "Sparkling + Title + Teensy"}, - {BaseRecipe::paradox, "paradox", "Title + Encounter + Humungo/Teensy: Paradox-specific"}, - {BaseRecipe::custom, "custom", "Custom Sandwich"}, - }, - LockMode::LOCK_WHILE_RUNNING, - base_recipe - ) - , TYPE( - "", - { - {PokemonType::normal, "normal", "Normal"}, - {PokemonType::fire, "fire", "Fire"}, - {PokemonType::water, "water", "Water"}, - {PokemonType::electric, "electric", "Electric"}, - {PokemonType::grass, "grass", "Grass"}, - {PokemonType::ice, "ice", "Ice"}, - {PokemonType::fighting, "fighting", "Fighting"}, - {PokemonType::poison, "poison", "Poison"}, - {PokemonType::ground, "ground", "Ground"}, - {PokemonType::flying, "flying", "Flying"}, - {PokemonType::psychic, "psychic", "Psychic"}, - {PokemonType::bug, "bug", "Bug"}, - {PokemonType::rock, "rock", "Rock"}, - {PokemonType::ghost, "ghost", "Ghost"}, - {PokemonType::dragon, "dragon", "Dragon"}, - {PokemonType::dark, "dark", "Dark"}, - {PokemonType::steel, "steel", "Steel"}, - {PokemonType::fairy, "fairy", "Fairy"}, - }, - LockMode::LOCK_WHILE_RUNNING, - PokemonType::normal - ) - , PARADOX( - "", - { - {ParadoxRecipe::humungo3_greattusk_1, "humungo3_greattusk_1", "Great Tusk - Humungo #1"}, - {ParadoxRecipe::humungo2_screamtail_1, "humungo2_screamtail_1", "Scream Tail - Humungo #1"}, - {ParadoxRecipe::humungo2_screamtail_2, "humungo2_screamtail_2", "Scream Tail - Humungo #2"}, - {ParadoxRecipe::humungo2_brutebonnet_1, "humungo2_brutebonnet_1", "Brute Bonnet - Humungo #1"}, - {ParadoxRecipe::humungo2_brutebonnet_2, "humungo2_brutebonnet_2", "Brute Bonnet - Humungo #2"}, - {ParadoxRecipe::humungo3_fluttermane_1, "humungo3_fluttermane_1", "Flutter Mane - Humungo #1"}, - {ParadoxRecipe::humungo3_fluttermane_2, "humungo3_fluttermane_2", "Flutter Mane - Humungo #2"}, - {ParadoxRecipe::humungo2_slitherwing_1, "humungo2_slitherwing_1", "Slither Wing - Humungo #1"}, - {ParadoxRecipe::humungo2_slitherwing_2, "humungo2_slitherwing_2", "Slither Wing - Humungo #2"}, - {ParadoxRecipe::humungo3_sandyshocks_1, "humungo3_sandyshocks_1", "Sandy Shocks - Humungo #1"}, - {ParadoxRecipe::humungo3_sandyshocks_2, "humungo3_sandyshocks_2", "Sandy Shocks - Humungo #2"}, - {ParadoxRecipe::humungo3_roaringmoon_1, "humungo3_roaringmoon_1", "Roaring Moon - Humungo #1"}, - {ParadoxRecipe::humungo3_roaringmoon_2, "humungo3_roaringmoon_2", "Roaring Moon - Humungo #2"}, - {ParadoxRecipe::humungo2_irontreads_1, "humungo2_irontreads_1", "Iron Treads - Humungo #1"}, - {ParadoxRecipe::humungo2_irontreads_2, "humungo2_irontreads_2", "Iron Treads - Humungo #2"}, - {ParadoxRecipe::humungo2_ironbundle_1, "humungo2_ironbundle_1", "Iron Bundle - Humungo #1"}, - {ParadoxRecipe::humungo2_ironbundle_2, "humungo2_ironbundle_2", "Iron Bundle - Humungo #2"}, - {ParadoxRecipe::humungo2_ironhands_1, "humungo2_ironhands_1", "Iron Hands - Humungo #1"}, - {ParadoxRecipe::humungo2_ironhands_2, "humungo2_ironhands_2", "Iron Hands - Humungo #2"}, - {ParadoxRecipe::humungo2_ironjugulis_1, "humungo2_ironjugulis_1", "Iron Jugulis - Humungo #1"}, - {ParadoxRecipe::humungo2_ironjugulis_2, "humungo2_ironjugulis_2", "Iron Jugulis - Humungo #2"}, - {ParadoxRecipe::humungo3_ironmoth_1, "humungo3_ironmoth_1", "Iron Moth - Humungo #1"}, - {ParadoxRecipe::humungo3_ironmoth_2, "humungo3_ironmoth_2", "Iron Moth - Humungo #2"}, - {ParadoxRecipe::humungo3_ironthorns_1, "humungo3_ironthorns_1", "Iron Thorns - Humungo #1"}, - {ParadoxRecipe::humungo3_ironthorns_2, "humungo3_ironthorns_2", "Iron Thorns - Humungo #2"}, - {ParadoxRecipe::humungo2_ironvaliant_1, "humungo2_ironvaliant_1", "Iron Valiant - Humungo #1"}, - {ParadoxRecipe::humungo2_ironvaliant_2, "humungo2_ironvaliant_2", "Iron Valiant - Humungo #2"}, - {ParadoxRecipe::teensy3_greattusk_1, "teensy3_greattusk_1", "Great Tusk - Teensy #1"}, - {ParadoxRecipe::teensy2_screamtail_1, "teensy2_screamtail_1", "Scream Tail - Teensy #1"}, - {ParadoxRecipe::teensy2_screamtail_2, "teensy2_screamtail_2", "Scream Tail - Teensy #2"}, - {ParadoxRecipe::teensy2_brutebonnet_1, "teensy2_brutebonnet_1", "Brute Bonnet - Teensy #1"}, - {ParadoxRecipe::teensy3_fluttermane_1, "teensy3_fluttermane_1", "Flutter Mane - Teensy #1"}, - {ParadoxRecipe::teensy2_sliterwing_1, "teensy2_sliterwing_1", "Slither Wing - Teensy #1"}, - {ParadoxRecipe::teensy2_sliterwing_2, "teensy2_sliterwing_2", "Slither Wing - Teensy #2"}, - {ParadoxRecipe::teensy3_sandyshocks_1, "teensy3_sandyshocks_1", "Sandy Shocks - Teensy #1"}, - {ParadoxRecipe::teensy3_sandyshocks_2, "teensy3_sandyshocks_2", "Sandy Shocks - Teensy #2"}, - {ParadoxRecipe::teensy3_roaringmoon_1, "teensy3_roaringmoon_1", "Roaring Moon - Teensy #1"}, - {ParadoxRecipe::teensy2_irontreads_1, "teensy2_irontreads_1", "Iron Treads - Teensy #1"}, - {ParadoxRecipe::teensy2_irontreads_2, "teensy2_irontreads_2", "Iron Treads - Teensy #2"}, - {ParadoxRecipe::teensy2_ironbundle_1, "teensy2_ironbundle_1", "Iron Bundle - Teensy #1"}, - {ParadoxRecipe::teensy2_ironbundle_2, "teensy2_ironbundle_2", "Iron Bundle - Teensy #2"}, - {ParadoxRecipe::teensy2_ironhands_1, "teensy2_ironhands_1", "Iron Hands - Teensy #1"}, - {ParadoxRecipe::teensy2_ironjugulis_1, "teensy2_ironjugulis_1", "Iron Jugulis - Teensy #1"}, - {ParadoxRecipe::teensy3_ironmoth_1, "teensy3_ironmoth_1", "Iron Moth - Teensy #1"}, - {ParadoxRecipe::teensy3_ironthorns_1, "teensy3_ironthorns_1", "Iron Thorns - Teensy #1"}, - {ParadoxRecipe::teensy2_ironvaliant_1, "teensy2_ironvaliant_1", "Iron Valiant - Teensy #1"}, - {ParadoxRecipe::teensy2_ironvaliant_2, "teensy2_ironvaliant_2", "Iron Vailant - Teensy #2"}, - }, - LockMode::LOCK_WHILE_RUNNING, - ParadoxRecipe::humungo3_greattusk_1 - ) - , HERBA_ONE( - "Herba Mystica:
Select the Herba Mystica to use in the preset recipe. Keep in mind which herb combinations are valid for the selected recipe.", - { - {HerbaSelection::sweet_herba_mystica, "sweet-herba-mystica", "Sweet Herba Mystica"}, - {HerbaSelection::salty_herba_mystica, "salty-herba-mystica", "Salty Herba Mystica"}, - {HerbaSelection::sour_herba_mystica, "sour-herba-mystica", "Sour Herba Mystica"}, - {HerbaSelection::bitter_herba_mystica, "bitter-herba-mystica", "Bitter Herba Mystica"}, - {HerbaSelection::spicy_herba_mystica, "spicy-herba-mystica", "Spicy Herba Mystica"}, - }, - LockMode::LOCK_WHILE_RUNNING, - HerbaSelection::salty_herba_mystica - ) - , HERBA_TWO( - "", - { - {HerbaSelection::sweet_herba_mystica, "sweet-herba-mystica", "Sweet Herba Mystica"}, - {HerbaSelection::salty_herba_mystica, "salty-herba-mystica", "Salty Herba Mystica"}, - {HerbaSelection::sour_herba_mystica, "sour-herba-mystica", "Sour Herba Mystica"}, - {HerbaSelection::bitter_herba_mystica, "bitter-herba-mystica", "Bitter Herba Mystica"}, - {HerbaSelection::spicy_herba_mystica, "spicy-herba-mystica", "Spicy Herba Mystica"}, - }, - LockMode::LOCK_WHILE_RUNNING, - HerbaSelection::salty_herba_mystica - ) - , HERB_INCOMPATIBILITY_WARNING("") - , SANDWICH_INGREDIENTS("Custom Sandwich:
Make a sandwich from the selected ingredients.
You must have at least one ingredient and one condiment, and no more than six ingredients and four condiments.") -{ - if (m_language_owner){ - PA_ADD_OPTION(LANGUAGE); - } - if (show_save_option){ - PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH); - } - PA_ADD_OPTION(BASE_RECIPE); - PA_ADD_OPTION(TYPE); - PA_ADD_OPTION(PARADOX); - PA_ADD_OPTION(HERBA_ONE); - PA_ADD_OPTION(HERBA_TWO); - PA_ADD_OPTION(HERB_INCOMPATIBILITY_WARNING); - PA_ADD_OPTION(SANDWICH_INGREDIENTS); - - HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); - - SandwichMakerOption::on_config_value_changed(this); - BASE_RECIPE.add_listener(*this); - TYPE.add_listener(*this); - HERBA_ONE.add_listener(*this); - HERBA_TWO.add_listener(*this); -} - -void SandwichMakerOption::on_config_value_changed(void* object){ - if (BASE_RECIPE == BaseRecipe::custom){ - HERBA_ONE.set_visibility(ConfigOptionState::HIDDEN); - HERBA_TWO.set_visibility(ConfigOptionState::HIDDEN); - HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); - TYPE.set_visibility(ConfigOptionState::HIDDEN); //to prevent the options moving around - PARADOX.set_visibility(ConfigOptionState::HIDDEN); - SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::ENABLED); - }else if (BASE_RECIPE == BaseRecipe::non_shiny){ - HERBA_ONE.set_visibility(ConfigOptionState::HIDDEN); - HERBA_TWO.set_visibility(ConfigOptionState::HIDDEN); - HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); - TYPE.set_visibility(ConfigOptionState::HIDDEN); //to prevent the options moving around - PARADOX.set_visibility(ConfigOptionState::HIDDEN); - SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); - }else if (two_herba_required(BASE_RECIPE)){ //shiny, huge, tiny - HERBA_ONE.set_visibility(ConfigOptionState::ENABLED); - HERBA_TWO.set_visibility(ConfigOptionState::ENABLED); - SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); - - std::string herb_error; - do{ - if (BASE_RECIPE != BaseRecipe::shiny){ - break; - } - herb_error = check_herb_compatibility(HERBA_ONE, HERBA_TWO, TYPE); - }while (false); - - if (herb_error.empty()){ - HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); - }else{ - HERB_INCOMPATIBILITY_WARNING.set_text("" + herb_error + ""); - HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::ENABLED); - } - TYPE.set_visibility(ConfigOptionState::ENABLED); - PARADOX.set_visibility(ConfigOptionState::HIDDEN); - }else{ //other - HERBA_ONE.set_visibility(ConfigOptionState::HIDDEN); - HERBA_TWO.set_visibility(ConfigOptionState::HIDDEN); - TYPE.set_visibility(ConfigOptionState::HIDDEN); - HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); - PARADOX.set_visibility(ConfigOptionState::ENABLED); - SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); - } -} -std::string SandwichMakerOption::check_validity() const{ - if (!two_herba_required(BASE_RECIPE)){ - return ""; - } - if (BASE_RECIPE != BaseRecipe::shiny){ - return ""; - } - return check_herb_compatibility(HERBA_ONE, HERBA_TWO, TYPE); -} - -std::string SandwichMakerOption::check_herb_compatibility(HerbaSelection herb1, HerbaSelection herb2, PokemonType type) const{ - if ((herb1 == HerbaSelection::sweet_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica) || - (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::sweet_herba_mystica) - ){ - return "1x Sweet and 1x Sour herb are incompatible for all types."; - } - if (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica){ - return "2x Sour herbs are incompatible for all types."; - } - if (herb1 == HerbaSelection::sweet_herba_mystica && herb2 == HerbaSelection::sweet_herba_mystica && - type == PokemonType::bug - ){ - return "2x Sweet herbs are incompatible with bug type."; - } - if ((herb1 == HerbaSelection::salty_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica) || - (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::salty_herba_mystica) - ){ - static const std::set TYPES{ - PokemonType::flying, - PokemonType::ground, - PokemonType::rock, - PokemonType::ice, - }; - if (!TYPES.contains(type)){ - return "1x Salty and 1x Sour herb are only compatible with flying, ground, rock, and ice."; - } - } - if ((herb1 == HerbaSelection::bitter_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica) || - (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::bitter_herba_mystica) - ){ - static const std::set TYPES{ - PokemonType::fighting, - PokemonType::bug, - PokemonType::fairy, - }; - if (TYPES.contains(type)){ - return "1x Sour and 1x Bitter herb are incompatible with fighting, bug, and fairy."; - } - } - - return ""; -} - - - -} -} -} +/* Sandwich Maker Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +//#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV_SandwichMakerOption.h" +//#include "PokemonSV_SandwichIngredientsOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Map for standard+type recipes taking Base + Type to find SandwichRecipe +const std::map, SandwichRecipe>& PREMADE_SANDWICH_TYPE(){ + static const std::map, SandwichRecipe> map{ + {{BaseRecipe::non_shiny, PokemonType::normal}, SandwichRecipe::non_shiny_normal}, + {{BaseRecipe::shiny, PokemonType::normal}, SandwichRecipe::shiny_normal}, + {{BaseRecipe::shiny, PokemonType::fire}, SandwichRecipe::shiny_fire}, + {{BaseRecipe::shiny, PokemonType::water}, SandwichRecipe::shiny_water}, + {{BaseRecipe::shiny, PokemonType::electric},SandwichRecipe::shiny_electric}, + {{BaseRecipe::shiny, PokemonType::grass}, SandwichRecipe::shiny_grass}, + {{BaseRecipe::shiny, PokemonType::ice}, SandwichRecipe::shiny_ice}, + {{BaseRecipe::shiny, PokemonType::fighting},SandwichRecipe::shiny_fighting}, + {{BaseRecipe::shiny, PokemonType::poison}, SandwichRecipe::shiny_poison}, + {{BaseRecipe::shiny, PokemonType::ground}, SandwichRecipe::shiny_ground}, + {{BaseRecipe::shiny, PokemonType::flying}, SandwichRecipe::shiny_flying}, + {{BaseRecipe::shiny, PokemonType::psychic}, SandwichRecipe::shiny_psychic}, + {{BaseRecipe::shiny, PokemonType::bug}, SandwichRecipe::shiny_bug}, + {{BaseRecipe::shiny, PokemonType::rock}, SandwichRecipe::shiny_rock}, + {{BaseRecipe::shiny, PokemonType::ghost}, SandwichRecipe::shiny_ghost}, + {{BaseRecipe::shiny, PokemonType::dragon}, SandwichRecipe::shiny_dragon}, + {{BaseRecipe::shiny, PokemonType::dark}, SandwichRecipe::shiny_dark}, + {{BaseRecipe::shiny, PokemonType::steel}, SandwichRecipe::shiny_steel}, + {{BaseRecipe::shiny, PokemonType::fairy}, SandwichRecipe::shiny_fairy}, + {{BaseRecipe::huge, PokemonType::normal}, SandwichRecipe::huge_normal}, + {{BaseRecipe::huge, PokemonType::fire}, SandwichRecipe::huge_fire}, + {{BaseRecipe::huge, PokemonType::water}, SandwichRecipe::huge_water}, + {{BaseRecipe::huge, PokemonType::electric},SandwichRecipe::huge_electric}, + {{BaseRecipe::huge, PokemonType::grass}, SandwichRecipe::huge_grass}, + {{BaseRecipe::huge, PokemonType::ice}, SandwichRecipe::huge_ice}, + {{BaseRecipe::huge, PokemonType::fighting},SandwichRecipe::huge_fighting}, + {{BaseRecipe::huge, PokemonType::poison}, SandwichRecipe::huge_poison}, + {{BaseRecipe::huge, PokemonType::ground}, SandwichRecipe::huge_ground}, + {{BaseRecipe::huge, PokemonType::flying}, SandwichRecipe::huge_flying}, + {{BaseRecipe::huge, PokemonType::psychic}, SandwichRecipe::huge_psychic}, + {{BaseRecipe::huge, PokemonType::bug}, SandwichRecipe::huge_bug}, + {{BaseRecipe::huge, PokemonType::rock}, SandwichRecipe::huge_rock}, + {{BaseRecipe::huge, PokemonType::ghost}, SandwichRecipe::huge_ghost}, + {{BaseRecipe::huge, PokemonType::dragon}, SandwichRecipe::huge_dragon}, + {{BaseRecipe::huge, PokemonType::dark}, SandwichRecipe::huge_dark}, + {{BaseRecipe::huge, PokemonType::steel}, SandwichRecipe::huge_steel}, + {{BaseRecipe::huge, PokemonType::fairy}, SandwichRecipe::huge_fairy}, + {{BaseRecipe::tiny, PokemonType::normal}, SandwichRecipe::tiny_normal}, + {{BaseRecipe::tiny, PokemonType::fire}, SandwichRecipe::tiny_fire}, + {{BaseRecipe::tiny, PokemonType::water}, SandwichRecipe::tiny_water}, + {{BaseRecipe::tiny, PokemonType::electric},SandwichRecipe::tiny_electric}, + {{BaseRecipe::tiny, PokemonType::grass}, SandwichRecipe::tiny_grass}, + {{BaseRecipe::tiny, PokemonType::ice}, SandwichRecipe::tiny_ice}, + {{BaseRecipe::tiny, PokemonType::fighting},SandwichRecipe::tiny_fighting}, + {{BaseRecipe::tiny, PokemonType::poison}, SandwichRecipe::tiny_poison}, + {{BaseRecipe::tiny, PokemonType::ground}, SandwichRecipe::tiny_ground}, + {{BaseRecipe::tiny, PokemonType::flying}, SandwichRecipe::tiny_flying}, + {{BaseRecipe::tiny, PokemonType::psychic}, SandwichRecipe::tiny_psychic}, + {{BaseRecipe::tiny, PokemonType::bug}, SandwichRecipe::tiny_bug}, + {{BaseRecipe::tiny, PokemonType::rock}, SandwichRecipe::tiny_rock}, + {{BaseRecipe::tiny, PokemonType::ghost}, SandwichRecipe::tiny_ghost}, + {{BaseRecipe::tiny, PokemonType::dragon}, SandwichRecipe::tiny_dragon}, + {{BaseRecipe::tiny, PokemonType::dark}, SandwichRecipe::tiny_dark}, + {{BaseRecipe::tiny, PokemonType::steel}, SandwichRecipe::tiny_steel}, + {{BaseRecipe::tiny, PokemonType::fairy}, SandwichRecipe::tiny_fairy}, + }; + return map; +} + +// Map for Other recipes +const std::map& PREMADE_SANDWICH_OTHER(){ + static const std::map map{ + {ParadoxRecipe::humungo3_greattusk_1, SandwichRecipe::humungo3_greattusk_1}, + {ParadoxRecipe::humungo2_screamtail_1, SandwichRecipe::humungo2_screamtail_1}, + {ParadoxRecipe::humungo2_screamtail_2, SandwichRecipe::humungo2_screamtail_2}, + {ParadoxRecipe::humungo2_brutebonnet_1, SandwichRecipe::humungo2_brutebonnet_1}, + {ParadoxRecipe::humungo2_brutebonnet_2, SandwichRecipe::humungo2_brutebonnet_2}, + {ParadoxRecipe::humungo3_fluttermane_1, SandwichRecipe::humungo3_fluttermane_1}, + {ParadoxRecipe::humungo3_fluttermane_2, SandwichRecipe::humungo3_fluttermane_2}, + {ParadoxRecipe::humungo2_slitherwing_1, SandwichRecipe::humungo2_slitherwing_1}, + {ParadoxRecipe::humungo2_slitherwing_2, SandwichRecipe::humungo2_slitherwing_2}, + {ParadoxRecipe::humungo3_sandyshocks_1, SandwichRecipe::humungo3_sandyshocks_1}, + {ParadoxRecipe::humungo3_sandyshocks_2, SandwichRecipe::humungo3_sandyshocks_2}, + {ParadoxRecipe::humungo3_roaringmoon_1, SandwichRecipe::humungo3_roaringmoon_1}, + {ParadoxRecipe::humungo3_roaringmoon_2, SandwichRecipe::humungo3_roaringmoon_2}, + {ParadoxRecipe::humungo2_irontreads_1, SandwichRecipe::humungo2_irontreads_1}, + {ParadoxRecipe::humungo2_irontreads_2, SandwichRecipe::humungo2_irontreads_2}, + {ParadoxRecipe::humungo2_ironbundle_1, SandwichRecipe::humungo2_ironbundle_1}, + {ParadoxRecipe::humungo2_ironbundle_2, SandwichRecipe::humungo2_ironbundle_2}, + {ParadoxRecipe::humungo2_ironhands_1, SandwichRecipe::humungo2_ironhands_1}, + {ParadoxRecipe::humungo2_ironhands_2, SandwichRecipe::humungo2_ironhands_2}, + {ParadoxRecipe::humungo2_ironjugulis_1, SandwichRecipe::humungo2_ironjugulis_1}, + {ParadoxRecipe::humungo2_ironjugulis_2, SandwichRecipe::humungo2_ironjugulis_2}, + {ParadoxRecipe::humungo3_ironmoth_1, SandwichRecipe::humungo3_ironmoth_1}, + {ParadoxRecipe::humungo3_ironmoth_2, SandwichRecipe::humungo3_ironmoth_2}, + {ParadoxRecipe::humungo3_ironthorns_1, SandwichRecipe::humungo3_ironthorns_1}, + {ParadoxRecipe::humungo3_ironthorns_2, SandwichRecipe::humungo3_ironthorns_2}, + {ParadoxRecipe::humungo2_ironvaliant_1, SandwichRecipe::humungo2_ironvaliant_1}, + {ParadoxRecipe::humungo2_ironvaliant_2, SandwichRecipe::humungo2_ironvaliant_2}, + {ParadoxRecipe::teensy3_greattusk_1, SandwichRecipe::teensy3_greattusk_1}, + {ParadoxRecipe::teensy2_screamtail_1, SandwichRecipe::teensy2_screamtail_1}, + {ParadoxRecipe::teensy2_screamtail_2, SandwichRecipe::teensy2_screamtail_2}, + {ParadoxRecipe::teensy2_brutebonnet_1, SandwichRecipe::teensy2_brutebonnet_1}, + {ParadoxRecipe::teensy3_fluttermane_1, SandwichRecipe::teensy3_fluttermane_1}, + {ParadoxRecipe::teensy2_sliterwing_1, SandwichRecipe::teensy2_sliterwing_1}, + {ParadoxRecipe::teensy2_sliterwing_2, SandwichRecipe::teensy2_sliterwing_2}, + {ParadoxRecipe::teensy3_sandyshocks_1, SandwichRecipe::teensy3_sandyshocks_1}, + {ParadoxRecipe::teensy3_sandyshocks_2, SandwichRecipe::teensy3_sandyshocks_2}, + {ParadoxRecipe::teensy3_roaringmoon_1, SandwichRecipe::teensy3_roaringmoon_1}, + {ParadoxRecipe::teensy2_irontreads_1, SandwichRecipe::teensy2_irontreads_1}, + {ParadoxRecipe::teensy2_irontreads_2, SandwichRecipe::teensy2_irontreads_2}, + {ParadoxRecipe::teensy2_ironbundle_1, SandwichRecipe::teensy2_ironbundle_1}, + {ParadoxRecipe::teensy2_ironbundle_2, SandwichRecipe::teensy2_ironbundle_2}, + {ParadoxRecipe::teensy2_ironhands_1, SandwichRecipe::teensy2_ironhands_1}, + {ParadoxRecipe::teensy2_ironjugulis_1, SandwichRecipe::teensy2_ironjugulis_1}, + {ParadoxRecipe::teensy3_ironmoth_1, SandwichRecipe::teensy3_ironmoth_1}, + {ParadoxRecipe::teensy3_ironthorns_1, SandwichRecipe::teensy3_ironthorns_1}, + {ParadoxRecipe::teensy2_ironvaliant_1, SandwichRecipe::teensy2_ironvaliant_1}, + {ParadoxRecipe::teensy2_ironvaliant_2, SandwichRecipe::teensy2_ironvaliant_2}, + }; + return map; +} + +// Leave the herba out, the user selects them as HERBA_ONE and HERBA_TWO. +// Remember the ingredient limits: Six fillings, four condiments. Two condiment slots will be taken by the Herba. +const std::map>& PREMADE_SANDWICH_INGREDIENTS(){ + static const std::map> map{ + {SandwichRecipe::non_shiny_normal, {"chorizo", "chorizo", "chorizo", "chorizo", "banana", "banana", "mayonnaise", "mayonnaise", "mayonnaise", "whipped-cream"}}, + {SandwichRecipe::shiny_normal, {"cucumber", "pickle", "tofu", "tofu", "tofu", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_fire, {"cucumber", "pickle", "red-bell-pepper", "red-bell-pepper","curry-powder","curry-powder", "red-bell-pepper"}}, + {SandwichRecipe::shiny_water, {"cucumber", "pickle", "cucumber", "cucumber", "cucumber","curry-powder","curry-powder"}}, + {SandwichRecipe::shiny_electric, {"cucumber", "pickle", "yellow-bell-pepper", "yellow-bell-pepper", "yellow-bell-pepper", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_grass, {"cucumber", "pickle", "lettuce", "lettuce", "lettuce", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_ice, {"cucumber", "pickle", "klawf-stick", "klawf-stick", "klawf-stick", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_fighting, {"cucumber", "pickle", "pickle", "pickle", "pickle", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_poison, {"cucumber", "pickle", "green-bell-pepper", "green-bell-pepper", "green-bell-pepper", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_ground, {"cucumber", "pickle", "ham", "ham", "ham", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_flying, {"cucumber", "pickle", "prosciutto", "prosciutto", "prosciutto", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_psychic, {"cucumber", "pickle", "onion", "onion", "onion", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_bug, {"cucumber", "pickle", "cherry-tomatoes", "cherry-tomatoes", "cherry-tomatoes", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_rock, {"cucumber", "pickle", "bacon", "bacon", "bacon", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_ghost, {"cucumber", "pickle", "red-onion", "red-onion", "red-onion", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_dragon, {"cucumber", "pickle", "avocado", "avocado", "avocado", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_dark, {"cucumber", "pickle", "smoked-fillet", "smoked-fillet", "smoked-fillet", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_steel, {"cucumber", "pickle", "hamburger", "hamburger", "hamburger", "curry-powder", "curry-powder"}}, + {SandwichRecipe::shiny_fairy, {"cucumber", "pickle", "tomato", "tomato", "tomato", "curry-powder", "curry-powder"}}, + {SandwichRecipe::huge_normal, {"tofu", "mustard", "mustard"}}, + {SandwichRecipe::huge_fire, {"red-bell-pepper", "mustard", "mustard"}}, + {SandwichRecipe::huge_water, {"cucumber", "mustard", "mustard"}}, + {SandwichRecipe::huge_electric, {"yellow-bell-pepper", "mustard", "mustard"}}, + {SandwichRecipe::huge_grass, {"lettuce", "mustard", "mustard"}}, + {SandwichRecipe::huge_ice, {"klawf-stick", "mustard", "mustard"}}, + {SandwichRecipe::huge_fighting, {"pickle", "mustard", "mustard"}}, + {SandwichRecipe::huge_poison, {"green-bell-pepper", "mustard", "mustard"}}, + {SandwichRecipe::huge_ground, {"ham", "mustard", "mustard"}}, + {SandwichRecipe::huge_flying, {"prosciutto", "mustard", "mustard"}}, + {SandwichRecipe::huge_psychic, {"onion", "mustard", "mustard"}}, + {SandwichRecipe::huge_bug, {"cherry-tomatoes", "mustard", "mustard"}}, + {SandwichRecipe::huge_rock, {"bacon", "mustard", "mustard"}}, + {SandwichRecipe::huge_ghost, {"red-onion", "mustard", "mustard"}}, + {SandwichRecipe::huge_dragon, {"avocado", "mustard", "mustard"}}, + {SandwichRecipe::huge_dark, {"smoked-fillet", "mustard", "mustard"}}, + {SandwichRecipe::huge_steel, {"hamburger", "mustard", "mustard"}}, + {SandwichRecipe::huge_fairy, {"tomato", "mustard", "mustard"}}, + {SandwichRecipe::tiny_normal, {"tofu", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_fire, {"red-bell-pepper", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_water, {"cucumber", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_electric, {"yellow-bell-pepper", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_grass, {"lettuce", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_ice, {"klawf-stick", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_fighting, {"pickle", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_poison, {"green-bell-pepper", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_ground, {"ham", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_flying, {"prosciutto", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_psychic, {"onion", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_bug, {"cherry-tomatoes", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_rock, {"bacon", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_ghost, {"red-onion", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_dragon, {"avocado", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_dark, {"smoked-fillet", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_steel, {"hamburger", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::tiny_fairy, {"tomato", "mayonnaise", "mayonnaise"}}, + {SandwichRecipe::humungo3_greattusk_1, {"herbed-sausage", "herbed-sausage", "herbed-sausage", "herbed-sausage", "ham", "horseradish", "jam", "wasabi", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_screamtail_1, {"noodles", "tomato", "tomato", "wasabi", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_screamtail_2, {"noodles", "potato-salad", "vinegar", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_brutebonnet_1, {"potato-salad", "lettuce", "lettuce", "wasabi", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_brutebonnet_2, {"potato-salad", "rice", "jam", "chili-sauce", "salty-herba-mystica"}}, + {SandwichRecipe::humungo3_fluttermane_1, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "tomato", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo3_fluttermane_2, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "olive-oil", "yogurt", "yogurt", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_slitherwing_1, {"cherry-tomatoes", "cherry-tomatoes", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_slitherwing_2, {"pickle", "potato-salad", "rice", "chili-sauce", "cream-cheese", "salty-herba-mystica"}}, + {SandwichRecipe::humungo3_sandyshocks_1, {"noodles", "noodles", "noodles", "noodles", "noodles", "mustard", "wasabi", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo3_sandyshocks_2, {"noodles", "noodles", "noodles", "noodles", "noodles", "mustard", "jam", "salty-herba-mystica"}}, + {SandwichRecipe::humungo3_roaringmoon_1, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "wasabi", "yogurt", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo3_roaringmoon_2, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "wasabi", "vinegar", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_irontreads_1, {"ham", "ham", "egg", "mustard", "curry-powder", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_irontreads_2, {"noodles", "potato-salad", "peanut-butter", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_ironbundle_1, {"cucumber", "cucumber", "noodles", "jam", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_ironbundle_2, {"noodles", "rice", "wasabi", "curry-powder", "pepper", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_ironhands_1, {"yellow-bell-pepper", "yellow-bell-pepper", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_ironhands_2, {"noodles", "pickle", "rice", "jam", "pepper", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_ironjugulis_1, {"egg", "smoked-fillet", "smoked-fillet", "yogurt", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_ironjugulis_2, {"potato-salad", "rice", "ketchup", "wasabi", "salty-herba-mystica"}}, + {SandwichRecipe::humungo3_ironmoth_1, {"chorizo", "chorizo", "chorizo", "noodles", "red-bell-pepper", "olive-oil", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo3_ironmoth_2, {"chorizo", "chorizo", "noodles", "noodles", "rice", "rice", "curry-powder", "salty-herba-mystica"}}, + {SandwichRecipe::humungo3_ironthorns_1, {"noodles", "noodles", "noodles", "noodles", "noodles", "marmalade", "mustard", "jam", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo3_ironthorns_2, {"noodles", "noodles", "noodles", "noodles", "noodles", "yellow-bell-pepper", "mustard", "mustard", "salty-herba-mystica"}}, + {SandwichRecipe::humungo2_ironvaliant_1, {"herbed-sausage", "tomato", "tomato", "marmalade", "wasabi", "yogurt", "spicy-herba-mystica"}}, + {SandwichRecipe::humungo2_ironvaliant_2, {"potato-salad", "rice", "tomato", "salty-herba-mystica"}}, + {SandwichRecipe::teensy3_greattusk_1, {"herbed-sausage", "herbed-sausage", "herbed-sausage", "noodles", "pickle", "horseradish", "horseradish", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_screamtail_1, {"egg", "onion", "onion", "chili-sauce", "wasabi", "yogurt", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_screamtail_2, {"herbed-sausage", "tomato", "tomato", "wasabi", "wasabi", "salty-herba-mystica"}}, + {SandwichRecipe::teensy2_brutebonnet_1, {"egg", "smoked-fillet", "smoked-fillet", "chili-sauce", "curry-powder", "jam", "sour-herba-mystica"}}, + {SandwichRecipe::teensy3_fluttermane_1, {"cheese", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "tomato", "curry-powder", "curry-powder", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_sliterwing_1, {"chorizo", "pickle", "pickle", "butter", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_sliterwing_2, {"chorizo", "pickle", "pickle", "curry-powder", "marmalade", "wasabi", "salty-herba-mystica"}}, + {SandwichRecipe::teensy3_sandyshocks_1, {"noodles", "noodles", "noodles", "noodles", "yellow-bell-pepper", "herbed-sausage", "horseradish", "sour-herba-mystica"}}, + {SandwichRecipe::teensy3_sandyshocks_2, {"fried-fillet", "fried-fillet", "noodles", "noodles", "noodles", "banana", "wasabi", "wasabi", "wasabi", "salty-herba-mystica"}}, + {SandwichRecipe::teensy3_roaringmoon_1, {"potato-salad", "potato-salad", "potato-salad", "potato-salad", "potato-salad", "herbed-sausage", "wasabi", "wasabi", "wasabi", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_irontreads_1, {"hamburger", "hamburger", "herbed-sausage", "curry-powder", "whipped-cream", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_irontreads_2, {"hamburger", "hamburger", "herbed-sausage", "curry-powder", "horseradish", "peanut-butter", "salty-herba-mystica"}}, + {SandwichRecipe::teensy2_ironbundle_1, {"herbed-sausage", "klawf-stick", "klawf-stick", "cream-cheese", "wasabi", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_ironbundle_2, {"herbed-sausage", "klawf-stick", "klawf-stick", "curry-powder", "pepper", "wasabi", "salty-herba-mystica"}}, + {SandwichRecipe::teensy2_ironhands_1, {"yellow-bell-pepper", "yellow-bell-pepper", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_ironjugulis_1, {"egg", "smoked-fillet", "smoked-fillet", "yogurt", "salt", "sour-herba-mystica"}}, + {SandwichRecipe::teensy3_ironmoth_1, {"chorizo", "chorizo", "chorizo", "noodles", "red-bell-pepper", "olive-oil", "sour-herba-mystica"}}, + {SandwichRecipe::teensy3_ironthorns_1, {"noodles", "noodles", "noodles", "noodles", "egg", "yellow-bell-pepper", "horseradish", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_ironvaliant_1, {"pickle", "pickle", "egg", "salt", "yogurt", "marmalade", "sour-herba-mystica"}}, + {SandwichRecipe::teensy2_ironvaliant_2, {"pickle", "pickle", "egg", "wasabi", "wasabi", "yogurt", "salty-herba-mystica"}}, + }; + return map; +} + + + + + +std::string SandwichMakerOption::herba_to_string(HerbaSelection value){ + switch (value){ + case HerbaSelection::bitter_herba_mystica: + return "bitter-herba-mystica"; + case HerbaSelection::salty_herba_mystica: + return "salty-herba-mystica"; + case HerbaSelection::sour_herba_mystica: + return "sour-herba-mystica"; + case HerbaSelection::spicy_herba_mystica: + return "spicy-herba-mystica"; + case HerbaSelection::sweet_herba_mystica: + return "sweet-herba-mystica"; + } + return "ERROR"; +} + +std::vector SandwichMakerOption::get_premade_ingredients(SandwichRecipe value){ + auto iter = PREMADE_SANDWICH_INGREDIENTS().find(value); + return iter->second; +} + +bool SandwichMakerOption::two_herba_required(BaseRecipe value){ + if (value == BaseRecipe::shiny || value == BaseRecipe::huge || value == BaseRecipe::tiny){ + return true; + } + return false; +} + +SandwichRecipe SandwichMakerOption::get_premade_sandwich_recipe(BaseRecipe base, PokemonType type, ParadoxRecipe paradox){ + if (base == BaseRecipe::paradox) + { + auto iter = PREMADE_SANDWICH_OTHER().find(paradox); + return iter->second; + }else{ + auto iter = PREMADE_SANDWICH_TYPE().find(std::make_pair(base, type)); + return iter->second; + } +} + +SandwichMakerOption::~SandwichMakerOption(){ + HERBA_TWO.remove_listener(*this); + HERBA_ONE.remove_listener(*this); + TYPE.remove_listener(*this); + BASE_RECIPE.remove_listener(*this); +} + +SandwichMakerOption::SandwichMakerOption( + std::string label, + OCR::LanguageOCROption* language_option, + BaseRecipe base_recipe, + bool show_save_option, + GroupOption::EnableMode enable_mode +) + : GroupOption( + std::move(label), + LockMode::UNLOCK_WHILE_RUNNING, + enable_mode + ) + , m_language_owner(language_option == nullptr + ? new OCR::LanguageOCROption( + "Game Language:
Required to read ingredients.", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + : nullptr + ) + , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) + , SAVE_GAME_BEFORE_SANDWICH( + "Save game before making sandwich:
Sandwich making can be unreliable. " + "Save the game before each sandwich to prevent loss of progress.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , BASE_RECIPE( + "Sandwich Recipe:
Select a recipe to make a sandwich with preset ingredients, or select Custom Sandwich to make a sandwich using the table below. " + "Refer to the documentation for recipe ingredients and valid Herba Mystica combinations.", + { + {BaseRecipe::non_shiny, "non-shiny", "Normal Encounter (non-shiny)"}, + {BaseRecipe::shiny, "shiny", "Sparkling + Title + Encounter"}, + {BaseRecipe::huge, "huge", "Sparkling + Title + Humungo"}, + {BaseRecipe::tiny, "tiny", "Sparkling + Title + Teensy"}, + {BaseRecipe::paradox, "paradox", "Title + Encounter + Humungo/Teensy: Paradox-specific"}, + {BaseRecipe::custom, "custom", "Custom Sandwich"}, + }, + LockMode::LOCK_WHILE_RUNNING, + base_recipe + ) + , TYPE( + "", + { + {PokemonType::normal, "normal", "Normal"}, + {PokemonType::fire, "fire", "Fire"}, + {PokemonType::water, "water", "Water"}, + {PokemonType::electric, "electric", "Electric"}, + {PokemonType::grass, "grass", "Grass"}, + {PokemonType::ice, "ice", "Ice"}, + {PokemonType::fighting, "fighting", "Fighting"}, + {PokemonType::poison, "poison", "Poison"}, + {PokemonType::ground, "ground", "Ground"}, + {PokemonType::flying, "flying", "Flying"}, + {PokemonType::psychic, "psychic", "Psychic"}, + {PokemonType::bug, "bug", "Bug"}, + {PokemonType::rock, "rock", "Rock"}, + {PokemonType::ghost, "ghost", "Ghost"}, + {PokemonType::dragon, "dragon", "Dragon"}, + {PokemonType::dark, "dark", "Dark"}, + {PokemonType::steel, "steel", "Steel"}, + {PokemonType::fairy, "fairy", "Fairy"}, + }, + LockMode::LOCK_WHILE_RUNNING, + PokemonType::normal + ) + , PARADOX( + "", + { + {ParadoxRecipe::humungo3_greattusk_1, "humungo3_greattusk_1", "Great Tusk - Humungo #1"}, + {ParadoxRecipe::humungo2_screamtail_1, "humungo2_screamtail_1", "Scream Tail - Humungo #1"}, + {ParadoxRecipe::humungo2_screamtail_2, "humungo2_screamtail_2", "Scream Tail - Humungo #2"}, + {ParadoxRecipe::humungo2_brutebonnet_1, "humungo2_brutebonnet_1", "Brute Bonnet - Humungo #1"}, + {ParadoxRecipe::humungo2_brutebonnet_2, "humungo2_brutebonnet_2", "Brute Bonnet - Humungo #2"}, + {ParadoxRecipe::humungo3_fluttermane_1, "humungo3_fluttermane_1", "Flutter Mane - Humungo #1"}, + {ParadoxRecipe::humungo3_fluttermane_2, "humungo3_fluttermane_2", "Flutter Mane - Humungo #2"}, + {ParadoxRecipe::humungo2_slitherwing_1, "humungo2_slitherwing_1", "Slither Wing - Humungo #1"}, + {ParadoxRecipe::humungo2_slitherwing_2, "humungo2_slitherwing_2", "Slither Wing - Humungo #2"}, + {ParadoxRecipe::humungo3_sandyshocks_1, "humungo3_sandyshocks_1", "Sandy Shocks - Humungo #1"}, + {ParadoxRecipe::humungo3_sandyshocks_2, "humungo3_sandyshocks_2", "Sandy Shocks - Humungo #2"}, + {ParadoxRecipe::humungo3_roaringmoon_1, "humungo3_roaringmoon_1", "Roaring Moon - Humungo #1"}, + {ParadoxRecipe::humungo3_roaringmoon_2, "humungo3_roaringmoon_2", "Roaring Moon - Humungo #2"}, + {ParadoxRecipe::humungo2_irontreads_1, "humungo2_irontreads_1", "Iron Treads - Humungo #1"}, + {ParadoxRecipe::humungo2_irontreads_2, "humungo2_irontreads_2", "Iron Treads - Humungo #2"}, + {ParadoxRecipe::humungo2_ironbundle_1, "humungo2_ironbundle_1", "Iron Bundle - Humungo #1"}, + {ParadoxRecipe::humungo2_ironbundle_2, "humungo2_ironbundle_2", "Iron Bundle - Humungo #2"}, + {ParadoxRecipe::humungo2_ironhands_1, "humungo2_ironhands_1", "Iron Hands - Humungo #1"}, + {ParadoxRecipe::humungo2_ironhands_2, "humungo2_ironhands_2", "Iron Hands - Humungo #2"}, + {ParadoxRecipe::humungo2_ironjugulis_1, "humungo2_ironjugulis_1", "Iron Jugulis - Humungo #1"}, + {ParadoxRecipe::humungo2_ironjugulis_2, "humungo2_ironjugulis_2", "Iron Jugulis - Humungo #2"}, + {ParadoxRecipe::humungo3_ironmoth_1, "humungo3_ironmoth_1", "Iron Moth - Humungo #1"}, + {ParadoxRecipe::humungo3_ironmoth_2, "humungo3_ironmoth_2", "Iron Moth - Humungo #2"}, + {ParadoxRecipe::humungo3_ironthorns_1, "humungo3_ironthorns_1", "Iron Thorns - Humungo #1"}, + {ParadoxRecipe::humungo3_ironthorns_2, "humungo3_ironthorns_2", "Iron Thorns - Humungo #2"}, + {ParadoxRecipe::humungo2_ironvaliant_1, "humungo2_ironvaliant_1", "Iron Valiant - Humungo #1"}, + {ParadoxRecipe::humungo2_ironvaliant_2, "humungo2_ironvaliant_2", "Iron Valiant - Humungo #2"}, + {ParadoxRecipe::teensy3_greattusk_1, "teensy3_greattusk_1", "Great Tusk - Teensy #1"}, + {ParadoxRecipe::teensy2_screamtail_1, "teensy2_screamtail_1", "Scream Tail - Teensy #1"}, + {ParadoxRecipe::teensy2_screamtail_2, "teensy2_screamtail_2", "Scream Tail - Teensy #2"}, + {ParadoxRecipe::teensy2_brutebonnet_1, "teensy2_brutebonnet_1", "Brute Bonnet - Teensy #1"}, + {ParadoxRecipe::teensy3_fluttermane_1, "teensy3_fluttermane_1", "Flutter Mane - Teensy #1"}, + {ParadoxRecipe::teensy2_sliterwing_1, "teensy2_sliterwing_1", "Slither Wing - Teensy #1"}, + {ParadoxRecipe::teensy2_sliterwing_2, "teensy2_sliterwing_2", "Slither Wing - Teensy #2"}, + {ParadoxRecipe::teensy3_sandyshocks_1, "teensy3_sandyshocks_1", "Sandy Shocks - Teensy #1"}, + {ParadoxRecipe::teensy3_sandyshocks_2, "teensy3_sandyshocks_2", "Sandy Shocks - Teensy #2"}, + {ParadoxRecipe::teensy3_roaringmoon_1, "teensy3_roaringmoon_1", "Roaring Moon - Teensy #1"}, + {ParadoxRecipe::teensy2_irontreads_1, "teensy2_irontreads_1", "Iron Treads - Teensy #1"}, + {ParadoxRecipe::teensy2_irontreads_2, "teensy2_irontreads_2", "Iron Treads - Teensy #2"}, + {ParadoxRecipe::teensy2_ironbundle_1, "teensy2_ironbundle_1", "Iron Bundle - Teensy #1"}, + {ParadoxRecipe::teensy2_ironbundle_2, "teensy2_ironbundle_2", "Iron Bundle - Teensy #2"}, + {ParadoxRecipe::teensy2_ironhands_1, "teensy2_ironhands_1", "Iron Hands - Teensy #1"}, + {ParadoxRecipe::teensy2_ironjugulis_1, "teensy2_ironjugulis_1", "Iron Jugulis - Teensy #1"}, + {ParadoxRecipe::teensy3_ironmoth_1, "teensy3_ironmoth_1", "Iron Moth - Teensy #1"}, + {ParadoxRecipe::teensy3_ironthorns_1, "teensy3_ironthorns_1", "Iron Thorns - Teensy #1"}, + {ParadoxRecipe::teensy2_ironvaliant_1, "teensy2_ironvaliant_1", "Iron Valiant - Teensy #1"}, + {ParadoxRecipe::teensy2_ironvaliant_2, "teensy2_ironvaliant_2", "Iron Vailant - Teensy #2"}, + }, + LockMode::LOCK_WHILE_RUNNING, + ParadoxRecipe::humungo3_greattusk_1 + ) + , HERBA_ONE( + "Herba Mystica:
Select the Herba Mystica to use in the preset recipe. Keep in mind which herb combinations are valid for the selected recipe.", + { + {HerbaSelection::sweet_herba_mystica, "sweet-herba-mystica", "Sweet Herba Mystica"}, + {HerbaSelection::salty_herba_mystica, "salty-herba-mystica", "Salty Herba Mystica"}, + {HerbaSelection::sour_herba_mystica, "sour-herba-mystica", "Sour Herba Mystica"}, + {HerbaSelection::bitter_herba_mystica, "bitter-herba-mystica", "Bitter Herba Mystica"}, + {HerbaSelection::spicy_herba_mystica, "spicy-herba-mystica", "Spicy Herba Mystica"}, + }, + LockMode::LOCK_WHILE_RUNNING, + HerbaSelection::salty_herba_mystica + ) + , HERBA_TWO( + "", + { + {HerbaSelection::sweet_herba_mystica, "sweet-herba-mystica", "Sweet Herba Mystica"}, + {HerbaSelection::salty_herba_mystica, "salty-herba-mystica", "Salty Herba Mystica"}, + {HerbaSelection::sour_herba_mystica, "sour-herba-mystica", "Sour Herba Mystica"}, + {HerbaSelection::bitter_herba_mystica, "bitter-herba-mystica", "Bitter Herba Mystica"}, + {HerbaSelection::spicy_herba_mystica, "spicy-herba-mystica", "Spicy Herba Mystica"}, + }, + LockMode::LOCK_WHILE_RUNNING, + HerbaSelection::salty_herba_mystica + ) + , HERB_INCOMPATIBILITY_WARNING("") + , SANDWICH_INGREDIENTS("Custom Sandwich:
Make a sandwich from the selected ingredients.
You must have at least one ingredient and one condiment, and no more than six ingredients and four condiments.") +{ + if (m_language_owner){ + PA_ADD_OPTION(LANGUAGE); + } + if (show_save_option){ + PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH); + } + PA_ADD_OPTION(BASE_RECIPE); + PA_ADD_OPTION(TYPE); + PA_ADD_OPTION(PARADOX); + PA_ADD_OPTION(HERBA_ONE); + PA_ADD_OPTION(HERBA_TWO); + PA_ADD_OPTION(HERB_INCOMPATIBILITY_WARNING); + PA_ADD_OPTION(SANDWICH_INGREDIENTS); + + HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); + + SandwichMakerOption::on_config_value_changed(this); + BASE_RECIPE.add_listener(*this); + TYPE.add_listener(*this); + HERBA_ONE.add_listener(*this); + HERBA_TWO.add_listener(*this); +} + +void SandwichMakerOption::on_config_value_changed(void* object){ + if (BASE_RECIPE == BaseRecipe::custom){ + HERBA_ONE.set_visibility(ConfigOptionState::HIDDEN); + HERBA_TWO.set_visibility(ConfigOptionState::HIDDEN); + HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); + TYPE.set_visibility(ConfigOptionState::HIDDEN); //to prevent the options moving around + PARADOX.set_visibility(ConfigOptionState::HIDDEN); + SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::ENABLED); + }else if (BASE_RECIPE == BaseRecipe::non_shiny){ + HERBA_ONE.set_visibility(ConfigOptionState::HIDDEN); + HERBA_TWO.set_visibility(ConfigOptionState::HIDDEN); + HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); + TYPE.set_visibility(ConfigOptionState::HIDDEN); //to prevent the options moving around + PARADOX.set_visibility(ConfigOptionState::HIDDEN); + SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); + }else if (two_herba_required(BASE_RECIPE)){ //shiny, huge, tiny + HERBA_ONE.set_visibility(ConfigOptionState::ENABLED); + HERBA_TWO.set_visibility(ConfigOptionState::ENABLED); + SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); + + std::string herb_error; + do{ + if (BASE_RECIPE != BaseRecipe::shiny){ + break; + } + herb_error = check_herb_compatibility(HERBA_ONE, HERBA_TWO, TYPE); + }while (false); + + if (herb_error.empty()){ + HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); + }else{ + HERB_INCOMPATIBILITY_WARNING.set_text("" + herb_error + ""); + HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::ENABLED); + } + TYPE.set_visibility(ConfigOptionState::ENABLED); + PARADOX.set_visibility(ConfigOptionState::HIDDEN); + }else{ //other + HERBA_ONE.set_visibility(ConfigOptionState::HIDDEN); + HERBA_TWO.set_visibility(ConfigOptionState::HIDDEN); + TYPE.set_visibility(ConfigOptionState::HIDDEN); + HERB_INCOMPATIBILITY_WARNING.set_visibility(ConfigOptionState::HIDDEN); + PARADOX.set_visibility(ConfigOptionState::ENABLED); + SANDWICH_INGREDIENTS.set_visibility(ConfigOptionState::HIDDEN); + } +} +std::string SandwichMakerOption::check_validity() const{ + if (!two_herba_required(BASE_RECIPE)){ + return ""; + } + if (BASE_RECIPE != BaseRecipe::shiny){ + return ""; + } + return check_herb_compatibility(HERBA_ONE, HERBA_TWO, TYPE); +} + +std::string SandwichMakerOption::check_herb_compatibility(HerbaSelection herb1, HerbaSelection herb2, PokemonType type) const{ + if ((herb1 == HerbaSelection::sweet_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica) || + (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::sweet_herba_mystica) + ){ + return "1x Sweet and 1x Sour herb are incompatible for all types."; + } + if (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica){ + return "2x Sour herbs are incompatible for all types."; + } + if (herb1 == HerbaSelection::sweet_herba_mystica && herb2 == HerbaSelection::sweet_herba_mystica && + type == PokemonType::bug + ){ + return "2x Sweet herbs are incompatible with bug type."; + } + if ((herb1 == HerbaSelection::salty_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica) || + (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::salty_herba_mystica) + ){ + static const std::set TYPES{ + PokemonType::flying, + PokemonType::ground, + PokemonType::rock, + PokemonType::ice, + }; + if (!TYPES.contains(type)){ + return "1x Salty and 1x Sour herb are only compatible with flying, ground, rock, and ice."; + } + } + if ((herb1 == HerbaSelection::bitter_herba_mystica && herb2 == HerbaSelection::sour_herba_mystica) || + (herb1 == HerbaSelection::sour_herba_mystica && herb2 == HerbaSelection::bitter_herba_mystica) + ){ + static const std::set TYPES{ + PokemonType::fighting, + PokemonType::bug, + PokemonType::fairy, + }; + if (TYPES.contains(type)){ + return "1x Sour and 1x Bitter herb are incompatible with fighting, bug, and fairy."; + } + } + + return ""; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.h index d05e84548a..216a155e9b 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SandwichMakerOption.h @@ -1,263 +1,263 @@ -/* Sandwich Makter Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichMakerOption_H -#define PokemonAutomation_PokemonSV_SandwichMakerOption_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "PokemonSV_SandwichIngredientsTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -enum class HerbaSelection{ - sweet_herba_mystica, - salty_herba_mystica, - sour_herba_mystica, - bitter_herba_mystica, - spicy_herba_mystica, -}; - -enum class BaseRecipe{ - non_shiny, - shiny, - huge, - tiny, - paradox, - custom, -}; - -enum class PokemonType{ - normal, - fire, - water, - electric, - grass, - ice, - fighting, - poison, - ground, - flying, - psychic, - bug, - rock, - ghost, - dragon, - dark, - steel, - fairy, -}; - -enum class ParadoxRecipe{ - humungo3_greattusk_1, - humungo2_screamtail_1, - humungo2_screamtail_2, - humungo2_brutebonnet_1, - humungo2_brutebonnet_2, - humungo3_fluttermane_1, - humungo3_fluttermane_2, - humungo2_slitherwing_1, - humungo2_slitherwing_2, - humungo3_sandyshocks_1, - humungo3_sandyshocks_2, - humungo3_roaringmoon_1, - humungo3_roaringmoon_2, - humungo2_irontreads_1, - humungo2_irontreads_2, - humungo2_ironbundle_1, - humungo2_ironbundle_2, - humungo2_ironhands_1, - humungo2_ironhands_2, - humungo2_ironjugulis_1, - humungo2_ironjugulis_2, - humungo3_ironmoth_1, - humungo3_ironmoth_2, - humungo3_ironthorns_1, - humungo3_ironthorns_2, - humungo2_ironvaliant_1, - humungo2_ironvaliant_2, - teensy3_greattusk_1, - teensy2_screamtail_1, - teensy2_screamtail_2, - teensy2_brutebonnet_1, - teensy3_fluttermane_1, - teensy2_sliterwing_1, - teensy2_sliterwing_2, - teensy3_sandyshocks_1, - teensy3_sandyshocks_2, - teensy3_roaringmoon_1, - teensy2_irontreads_1, - teensy2_irontreads_2, - teensy2_ironbundle_1, - teensy2_ironbundle_2, - teensy2_ironhands_1, - teensy2_ironjugulis_1, - teensy3_ironmoth_1, - teensy3_ironthorns_1, - teensy2_ironvaliant_1, - teensy2_ironvaliant_2, -}; - -enum class SandwichRecipe{ - non_shiny_normal, - shiny_normal, - shiny_fire, - shiny_water, - shiny_electric, - shiny_grass, - shiny_ice, - shiny_fighting, - shiny_poison, - shiny_ground, - shiny_flying, - shiny_psychic, - shiny_bug, - shiny_rock, - shiny_ghost, - shiny_dragon, - shiny_dark, - shiny_steel, - shiny_fairy, - huge_normal, - huge_fire, - huge_water, - huge_electric, - huge_grass, - huge_ice, - huge_fighting, - huge_poison, - huge_ground, - huge_flying, - huge_psychic, - huge_bug, - huge_rock, - huge_ghost, - huge_dragon, - huge_dark, - huge_steel, - huge_fairy, - tiny_normal, - tiny_fire, - tiny_water, - tiny_electric, - tiny_grass, - tiny_ice, - tiny_fighting, - tiny_poison, - tiny_ground, - tiny_flying, - tiny_psychic, - tiny_bug, - tiny_rock, - tiny_ghost, - tiny_dragon, - tiny_dark, - tiny_steel, - tiny_fairy, - humungo3_greattusk_1, - humungo2_screamtail_1, - humungo2_screamtail_2, - humungo2_brutebonnet_1, - humungo2_brutebonnet_2, - humungo3_fluttermane_1, - humungo3_fluttermane_2, - humungo2_slitherwing_1, - humungo2_slitherwing_2, - humungo3_sandyshocks_1, - humungo3_sandyshocks_2, - humungo3_roaringmoon_1, - humungo3_roaringmoon_2, - humungo2_irontreads_1, - humungo2_irontreads_2, - humungo2_ironbundle_1, - humungo2_ironbundle_2, - humungo2_ironhands_1, - humungo2_ironhands_2, - humungo2_ironjugulis_1, - humungo2_ironjugulis_2, - humungo3_ironmoth_1, - humungo3_ironmoth_2, - humungo3_ironthorns_1, - humungo3_ironthorns_2, - humungo2_ironvaliant_1, - humungo2_ironvaliant_2, - teensy3_greattusk_1, - teensy2_screamtail_1, - teensy2_screamtail_2, - teensy2_brutebonnet_1, - teensy3_fluttermane_1, - teensy2_sliterwing_1, - teensy2_sliterwing_2, - teensy3_sandyshocks_1, - teensy3_sandyshocks_2, - teensy3_roaringmoon_1, - teensy2_irontreads_1, - teensy2_irontreads_2, - teensy2_ironbundle_1, - teensy2_ironbundle_2, - teensy2_ironhands_1, - teensy2_ironjugulis_1, - teensy3_ironmoth_1, - teensy3_ironthorns_1, - teensy2_ironvaliant_1, - teensy2_ironvaliant_2, -}; - - - - -class SandwichMakerOption : public GroupOption, private ConfigOption::Listener{ - -public: - ~SandwichMakerOption(); - - SandwichMakerOption( - std::string label, - OCR::LanguageOCROption* language_option, - BaseRecipe base_recipe, - bool show_save_option, - GroupOption::EnableMode enable_mode - ); - -public: - std::string herba_to_string(HerbaSelection value); - std::vector get_premade_ingredients(SandwichRecipe value); - static bool two_herba_required(BaseRecipe value); - SandwichRecipe get_premade_sandwich_recipe(BaseRecipe base, PokemonType type, ParadoxRecipe other); - -private: - std::unique_ptr m_language_owner; -public: - OCR::LanguageOCROption& LANGUAGE; - - BooleanCheckBoxOption SAVE_GAME_BEFORE_SANDWICH; - - EnumDropdownOption BASE_RECIPE; - EnumDropdownOption TYPE; - EnumDropdownOption PARADOX; - EnumDropdownOption HERBA_ONE; - EnumDropdownOption HERBA_TWO; - StaticTextOption HERB_INCOMPATIBILITY_WARNING; - SandwichIngredientsTable SANDWICH_INGREDIENTS; - -private: - virtual void on_config_value_changed(void* object) override; - virtual std::string check_validity() const override; - - std::string check_herb_compatibility(HerbaSelection herb1, HerbaSelection herb2, PokemonType type) const; -}; - -} -} -} -#endif +/* Sandwich Makter Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichMakerOption_H +#define PokemonAutomation_PokemonSV_SandwichMakerOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "PokemonSV_SandwichIngredientsTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +enum class HerbaSelection{ + sweet_herba_mystica, + salty_herba_mystica, + sour_herba_mystica, + bitter_herba_mystica, + spicy_herba_mystica, +}; + +enum class BaseRecipe{ + non_shiny, + shiny, + huge, + tiny, + paradox, + custom, +}; + +enum class PokemonType{ + normal, + fire, + water, + electric, + grass, + ice, + fighting, + poison, + ground, + flying, + psychic, + bug, + rock, + ghost, + dragon, + dark, + steel, + fairy, +}; + +enum class ParadoxRecipe{ + humungo3_greattusk_1, + humungo2_screamtail_1, + humungo2_screamtail_2, + humungo2_brutebonnet_1, + humungo2_brutebonnet_2, + humungo3_fluttermane_1, + humungo3_fluttermane_2, + humungo2_slitherwing_1, + humungo2_slitherwing_2, + humungo3_sandyshocks_1, + humungo3_sandyshocks_2, + humungo3_roaringmoon_1, + humungo3_roaringmoon_2, + humungo2_irontreads_1, + humungo2_irontreads_2, + humungo2_ironbundle_1, + humungo2_ironbundle_2, + humungo2_ironhands_1, + humungo2_ironhands_2, + humungo2_ironjugulis_1, + humungo2_ironjugulis_2, + humungo3_ironmoth_1, + humungo3_ironmoth_2, + humungo3_ironthorns_1, + humungo3_ironthorns_2, + humungo2_ironvaliant_1, + humungo2_ironvaliant_2, + teensy3_greattusk_1, + teensy2_screamtail_1, + teensy2_screamtail_2, + teensy2_brutebonnet_1, + teensy3_fluttermane_1, + teensy2_sliterwing_1, + teensy2_sliterwing_2, + teensy3_sandyshocks_1, + teensy3_sandyshocks_2, + teensy3_roaringmoon_1, + teensy2_irontreads_1, + teensy2_irontreads_2, + teensy2_ironbundle_1, + teensy2_ironbundle_2, + teensy2_ironhands_1, + teensy2_ironjugulis_1, + teensy3_ironmoth_1, + teensy3_ironthorns_1, + teensy2_ironvaliant_1, + teensy2_ironvaliant_2, +}; + +enum class SandwichRecipe{ + non_shiny_normal, + shiny_normal, + shiny_fire, + shiny_water, + shiny_electric, + shiny_grass, + shiny_ice, + shiny_fighting, + shiny_poison, + shiny_ground, + shiny_flying, + shiny_psychic, + shiny_bug, + shiny_rock, + shiny_ghost, + shiny_dragon, + shiny_dark, + shiny_steel, + shiny_fairy, + huge_normal, + huge_fire, + huge_water, + huge_electric, + huge_grass, + huge_ice, + huge_fighting, + huge_poison, + huge_ground, + huge_flying, + huge_psychic, + huge_bug, + huge_rock, + huge_ghost, + huge_dragon, + huge_dark, + huge_steel, + huge_fairy, + tiny_normal, + tiny_fire, + tiny_water, + tiny_electric, + tiny_grass, + tiny_ice, + tiny_fighting, + tiny_poison, + tiny_ground, + tiny_flying, + tiny_psychic, + tiny_bug, + tiny_rock, + tiny_ghost, + tiny_dragon, + tiny_dark, + tiny_steel, + tiny_fairy, + humungo3_greattusk_1, + humungo2_screamtail_1, + humungo2_screamtail_2, + humungo2_brutebonnet_1, + humungo2_brutebonnet_2, + humungo3_fluttermane_1, + humungo3_fluttermane_2, + humungo2_slitherwing_1, + humungo2_slitherwing_2, + humungo3_sandyshocks_1, + humungo3_sandyshocks_2, + humungo3_roaringmoon_1, + humungo3_roaringmoon_2, + humungo2_irontreads_1, + humungo2_irontreads_2, + humungo2_ironbundle_1, + humungo2_ironbundle_2, + humungo2_ironhands_1, + humungo2_ironhands_2, + humungo2_ironjugulis_1, + humungo2_ironjugulis_2, + humungo3_ironmoth_1, + humungo3_ironmoth_2, + humungo3_ironthorns_1, + humungo3_ironthorns_2, + humungo2_ironvaliant_1, + humungo2_ironvaliant_2, + teensy3_greattusk_1, + teensy2_screamtail_1, + teensy2_screamtail_2, + teensy2_brutebonnet_1, + teensy3_fluttermane_1, + teensy2_sliterwing_1, + teensy2_sliterwing_2, + teensy3_sandyshocks_1, + teensy3_sandyshocks_2, + teensy3_roaringmoon_1, + teensy2_irontreads_1, + teensy2_irontreads_2, + teensy2_ironbundle_1, + teensy2_ironbundle_2, + teensy2_ironhands_1, + teensy2_ironjugulis_1, + teensy3_ironmoth_1, + teensy3_ironthorns_1, + teensy2_ironvaliant_1, + teensy2_ironvaliant_2, +}; + + + + +class SandwichMakerOption : public GroupOption, private ConfigOption::Listener{ + +public: + ~SandwichMakerOption(); + + SandwichMakerOption( + std::string label, + OCR::LanguageOCROption* language_option, + BaseRecipe base_recipe, + bool show_save_option, + GroupOption::EnableMode enable_mode + ); + +public: + std::string herba_to_string(HerbaSelection value); + std::vector get_premade_ingredients(SandwichRecipe value); + static bool two_herba_required(BaseRecipe value); + SandwichRecipe get_premade_sandwich_recipe(BaseRecipe base, PokemonType type, ParadoxRecipe other); + +private: + std::unique_ptr m_language_owner; +public: + OCR::LanguageOCROption& LANGUAGE; + + BooleanCheckBoxOption SAVE_GAME_BEFORE_SANDWICH; + + EnumDropdownOption BASE_RECIPE; + EnumDropdownOption TYPE; + EnumDropdownOption PARADOX; + EnumDropdownOption HERBA_ONE; + EnumDropdownOption HERBA_TWO; + StaticTextOption HERB_INCOMPATIBILITY_WARNING; + SandwichIngredientsTable SANDWICH_INGREDIENTS; + +private: + virtual void on_config_value_changed(void* object) override; + virtual std::string check_validity() const override; + + std::string check_herb_compatibility(HerbaSelection herb1, HerbaSelection herb2, PokemonType type) const; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.cpp index 4b78f3f750..cf4fb0d676 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.cpp @@ -1,52 +1,52 @@ -/* Singles AI Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_SinglesAIOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -SinglesAIOption::~SinglesAIOption() = default; -SinglesAIOption::SinglesAIOption(bool trainer_battle) - : GroupOption("Battle AI", LockMode::UNLOCK_WHILE_RUNNING) - , description( - "Move Tables: Run these sequence of moves for the corresponding " + STRING_POKEMON + " in your party. " - "When the end of the table is reached, the last entry will be repeated " - "until the battle is won or the " + STRING_POKEMON +" faints. " - "If your " + STRING_POKEMON + " faints, the program will switch to the " - "next available " + STRING_POKEMON + " and run its table. " - "Changes to these tables take effect the next the " + STRING_POKEMON + " is sent out." - ) - , MOVE_TABLES(6) -{ - MOVE_TABLES.emplace_back("1st " + STRING_POKEMON + " Move Table:", trainer_battle); - MOVE_TABLES.emplace_back("2nd " + STRING_POKEMON + " Move Table:", trainer_battle); - MOVE_TABLES.emplace_back("3rd " + STRING_POKEMON + " Move Table:", trainer_battle); - MOVE_TABLES.emplace_back("4th " + STRING_POKEMON + " Move Table:", trainer_battle); - MOVE_TABLES.emplace_back("5th " + STRING_POKEMON + " Move Table:", trainer_battle); - MOVE_TABLES.emplace_back("6th " + STRING_POKEMON + " Move Table:", trainer_battle); - - PA_ADD_STATIC(description); - size_t c = 0; - for (SinglesMoveTable& table : MOVE_TABLES){ - add_option(table, "MOVE_TABLE" + std::to_string(++c)); - } -} - - - - - -} -} -} +/* Singles AI Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_SinglesAIOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +SinglesAIOption::~SinglesAIOption() = default; +SinglesAIOption::SinglesAIOption(bool trainer_battle) + : GroupOption("Battle AI", LockMode::UNLOCK_WHILE_RUNNING) + , description( + "Move Tables: Run these sequence of moves for the corresponding " + STRING_POKEMON + " in your party. " + "When the end of the table is reached, the last entry will be repeated " + "until the battle is won or the " + STRING_POKEMON +" faints. " + "If your " + STRING_POKEMON + " faints, the program will switch to the " + "next available " + STRING_POKEMON + " and run its table. " + "Changes to these tables take effect the next the " + STRING_POKEMON + " is sent out." + ) + , MOVE_TABLES(6) +{ + MOVE_TABLES.emplace_back("1st " + STRING_POKEMON + " Move Table:", trainer_battle); + MOVE_TABLES.emplace_back("2nd " + STRING_POKEMON + " Move Table:", trainer_battle); + MOVE_TABLES.emplace_back("3rd " + STRING_POKEMON + " Move Table:", trainer_battle); + MOVE_TABLES.emplace_back("4th " + STRING_POKEMON + " Move Table:", trainer_battle); + MOVE_TABLES.emplace_back("5th " + STRING_POKEMON + " Move Table:", trainer_battle); + MOVE_TABLES.emplace_back("6th " + STRING_POKEMON + " Move Table:", trainer_battle); + + PA_ADD_STATIC(description); + size_t c = 0; + for (SinglesMoveTable& table : MOVE_TABLES){ + add_option(table, "MOVE_TABLE" + std::to_string(++c)); + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.h index 235fcbe664..6c171904fa 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesAIOption.h @@ -1,39 +1,39 @@ -/* Singles AI Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SinglesAIOption_H -#define PokemonAutomation_PokemonSV_SinglesAIOption_H - -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "Common/Cpp/Options/StaticTextOption.h" -//#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "PokemonSV_SinglesMoveTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class SinglesAIOption : public GroupOption{ -public: - ~SinglesAIOption(); - SinglesAIOption(bool trainer_battle); - -public: - StaticTextOption description; - FixedLimitVector MOVE_TABLES; - -}; - - - - -} -} -} -#endif +/* Singles AI Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SinglesAIOption_H +#define PokemonAutomation_PokemonSV_SinglesAIOption_H + +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "Common/Cpp/Options/StaticTextOption.h" +//#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "PokemonSV_SinglesMoveTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class SinglesAIOption : public GroupOption{ +public: + ~SinglesAIOption(); + SinglesAIOption(bool trainer_battle); + +public: + StaticTextOption description; + FixedLimitVector MOVE_TABLES; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.cpp index 32c19553f7..5db1362a22 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.cpp @@ -1,135 +1,135 @@ -/* Single Battle Move Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_SinglesMoveTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const EnumDropdownDatabase& singles_move_enum_database_wild(){ - static EnumDropdownDatabase database{ - {SinglesMoveType::Move1, "move1", "Move 1"}, - {SinglesMoveType::Move2, "move2", "Move 2"}, - {SinglesMoveType::Move3, "move3", "Move 3"}, - {SinglesMoveType::Move4, "move4", "Move 4"}, - {SinglesMoveType::Run, "run", "Run"}, - }; - return database; -} -const EnumDropdownDatabase& singles_move_enum_database_trainer(){ - static EnumDropdownDatabase database{ - {SinglesMoveType::Move1, "move1", "Move 1"}, - {SinglesMoveType::Move2, "move2", "Move 2"}, - {SinglesMoveType::Move3, "move3", "Move 3"}, - {SinglesMoveType::Move4, "move4", "Move 4"}, - }; - return database; -} - -std::string SinglesMoveEntry::to_str() const{ - switch (type){ - case SinglesMoveType::Move1: - case SinglesMoveType::Move2: - case SinglesMoveType::Move3: - case SinglesMoveType::Move4:{ - int slot = (int)type - (int)SinglesMoveType::Move1; - std::string str = "Move " + std::to_string(slot + 1); - if (terastallize){ - str += " (terastallize)"; - } - str += "."; - return str; - } - case SinglesMoveType::Run: - return "Run Away"; - } - return "(Invalid Move)"; -} - - - -SinglesMoveTableRow::~SinglesMoveTableRow(){ - type.remove_listener(*this); -} -SinglesMoveTableRow::SinglesMoveTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , type( - static_cast(parent_table).m_trainer_battle - ? singles_move_enum_database_trainer() - : singles_move_enum_database_wild(), - LockMode::UNLOCK_WHILE_RUNNING, - SinglesMoveType::Move1 - ) - , terastallize(LockMode::UNLOCK_WHILE_RUNNING, false) - , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "(e.g. Screech, Belly Drum)") -{ - PA_ADD_OPTION(type); - PA_ADD_OPTION(terastallize); - PA_ADD_OPTION(notes); - - SinglesMoveTableRow::on_config_value_changed(this); - type.add_listener(*this); -} -std::unique_ptr SinglesMoveTableRow::clone() const{ - std::unique_ptr ret(new SinglesMoveTableRow(parent())); - ret->type.set(type); - ret->terastallize = (bool)terastallize; - ret->notes.set(notes); - return ret; -} -SinglesMoveEntry SinglesMoveTableRow::snapshot() const{ - return SinglesMoveEntry{type, terastallize}; -} -void SinglesMoveTableRow::on_config_value_changed(void* object){ - -} - - - - - -SinglesMoveTable::SinglesMoveTable(std::string label, bool trainer_battle) - : EditableTableOption_t( - std::move(label), -#if 0 - "Move Table:
" - "Run this sequence of moves. When the end of the table is reached, " - "the last entry will be repeated until the battle is won or your " + Pokemon::STRING_POKEMON +" faints." - "Changes to this table take effect on the next battle.", -#endif - LockMode::UNLOCK_WHILE_RUNNING, - make_defaults() - ) -{} - -std::vector SinglesMoveTable::snapshot(){ - return EditableTableOption_t::snapshot(); -} -std::vector SinglesMoveTable::make_header() const{ - return { - "Move", - "Terastallize", - "Notes", - }; -} -std::vector> SinglesMoveTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(new SinglesMoveTableRow(*this)); - return ret; -} - - - - - - - - -} -} -} +/* Single Battle Move Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_SinglesMoveTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const EnumDropdownDatabase& singles_move_enum_database_wild(){ + static EnumDropdownDatabase database{ + {SinglesMoveType::Move1, "move1", "Move 1"}, + {SinglesMoveType::Move2, "move2", "Move 2"}, + {SinglesMoveType::Move3, "move3", "Move 3"}, + {SinglesMoveType::Move4, "move4", "Move 4"}, + {SinglesMoveType::Run, "run", "Run"}, + }; + return database; +} +const EnumDropdownDatabase& singles_move_enum_database_trainer(){ + static EnumDropdownDatabase database{ + {SinglesMoveType::Move1, "move1", "Move 1"}, + {SinglesMoveType::Move2, "move2", "Move 2"}, + {SinglesMoveType::Move3, "move3", "Move 3"}, + {SinglesMoveType::Move4, "move4", "Move 4"}, + }; + return database; +} + +std::string SinglesMoveEntry::to_str() const{ + switch (type){ + case SinglesMoveType::Move1: + case SinglesMoveType::Move2: + case SinglesMoveType::Move3: + case SinglesMoveType::Move4:{ + int slot = (int)type - (int)SinglesMoveType::Move1; + std::string str = "Move " + std::to_string(slot + 1); + if (terastallize){ + str += " (terastallize)"; + } + str += "."; + return str; + } + case SinglesMoveType::Run: + return "Run Away"; + } + return "(Invalid Move)"; +} + + + +SinglesMoveTableRow::~SinglesMoveTableRow(){ + type.remove_listener(*this); +} +SinglesMoveTableRow::SinglesMoveTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , type( + static_cast(parent_table).m_trainer_battle + ? singles_move_enum_database_trainer() + : singles_move_enum_database_wild(), + LockMode::UNLOCK_WHILE_RUNNING, + SinglesMoveType::Move1 + ) + , terastallize(LockMode::UNLOCK_WHILE_RUNNING, false) + , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "(e.g. Screech, Belly Drum)") +{ + PA_ADD_OPTION(type); + PA_ADD_OPTION(terastallize); + PA_ADD_OPTION(notes); + + SinglesMoveTableRow::on_config_value_changed(this); + type.add_listener(*this); +} +std::unique_ptr SinglesMoveTableRow::clone() const{ + std::unique_ptr ret(new SinglesMoveTableRow(parent())); + ret->type.set(type); + ret->terastallize = (bool)terastallize; + ret->notes.set(notes); + return ret; +} +SinglesMoveEntry SinglesMoveTableRow::snapshot() const{ + return SinglesMoveEntry{type, terastallize}; +} +void SinglesMoveTableRow::on_config_value_changed(void* object){ + +} + + + + + +SinglesMoveTable::SinglesMoveTable(std::string label, bool trainer_battle) + : EditableTableOption_t( + std::move(label), +#if 0 + "Move Table:
" + "Run this sequence of moves. When the end of the table is reached, " + "the last entry will be repeated until the battle is won or your " + Pokemon::STRING_POKEMON +" faints." + "Changes to this table take effect on the next battle.", +#endif + LockMode::UNLOCK_WHILE_RUNNING, + make_defaults() + ) +{} + +std::vector SinglesMoveTable::snapshot(){ + return EditableTableOption_t::snapshot(); +} +std::vector SinglesMoveTable::make_header() const{ + return { + "Move", + "Terastallize", + "Notes", + }; +} +std::vector> SinglesMoveTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(new SinglesMoveTableRow(*this)); + return ret; +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.h index fcab8b94f5..74a9a15685 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_SinglesMoveTable.h @@ -1,79 +1,79 @@ -/* Singles Move Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SinglesMoveTable_H -#define PokemonAutomation_PokemonSV_SinglesMoveTable_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class SinglesMoveType{ - Move1, - Move2, - Move3, - Move4, - Run, -}; -const EnumDropdownDatabase& singles_move_enum_database_wild(); -const EnumDropdownDatabase& singles_move_enum_database_trainer(); - - -struct SinglesMoveEntry{ - SinglesMoveType type; - bool terastallize; - - std::string to_str() const; -}; - - - -class SinglesMoveTableRow : public EditableTableRow, public ConfigOption::Listener{ -public: - ~SinglesMoveTableRow(); - SinglesMoveTableRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - - SinglesMoveEntry snapshot() const; - -private: - virtual void on_config_value_changed(void* object) override; - -private: - EnumDropdownCell type; - BooleanCheckBoxCell terastallize; - StringCell notes; -}; - - -class SinglesMoveTable : public EditableTableOption_t{ -public: - SinglesMoveTable(std::string label, bool trainer_battle); - - std::vector snapshot(); - - virtual std::vector make_header() const; - - std::vector> make_defaults(); - -private: - friend class SinglesMoveTableRow; - - bool m_trainer_battle; -}; - - - -} -} -} -#endif +/* Singles Move Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SinglesMoveTable_H +#define PokemonAutomation_PokemonSV_SinglesMoveTable_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class SinglesMoveType{ + Move1, + Move2, + Move3, + Move4, + Run, +}; +const EnumDropdownDatabase& singles_move_enum_database_wild(); +const EnumDropdownDatabase& singles_move_enum_database_trainer(); + + +struct SinglesMoveEntry{ + SinglesMoveType type; + bool terastallize; + + std::string to_str() const; +}; + + + +class SinglesMoveTableRow : public EditableTableRow, public ConfigOption::Listener{ +public: + ~SinglesMoveTableRow(); + SinglesMoveTableRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + SinglesMoveEntry snapshot() const; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + EnumDropdownCell type; + BooleanCheckBoxCell terastallize; + StringCell notes; +}; + + +class SinglesMoveTable : public EditableTableOption_t{ +public: + SinglesMoveTable(std::string label, bool trainer_battle); + + std::vector snapshot(); + + virtual std::vector make_header() const; + + std::vector> make_defaults(); + +private: + friend class SinglesMoveTableRow; + + bool m_trainer_battle; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.cpp index cd2ca34cea..0968f49608 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.cpp @@ -1,36 +1,36 @@ -/* Tera AI Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_TeraAIOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -TeraAIOption::TeraAIOption() - : GroupOption("Battle AI", LockMode::UNLOCK_WHILE_RUNNING) - , description( - "There is no battle AI yet. It will always select the 1st move unless it is blocked by taunt, disable, torment, etc..." - ) - , TRY_TO_TERASTILLIZE( - "Try to Terastillize:
Try to terastillize if available. Add 4s per try but greatly increase win rate.", - LockMode::UNLOCK_WHILE_RUNNING, true - ) -{ -// PA_ADD_STATIC(description); - PA_ADD_OPTION(TRY_TO_TERASTILLIZE); - PA_ADD_OPTION(MOVE_TABLE); -} - - - - - -} -} -} +/* Tera AI Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_TeraAIOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +TeraAIOption::TeraAIOption() + : GroupOption("Battle AI", LockMode::UNLOCK_WHILE_RUNNING) + , description( + "There is no battle AI yet. It will always select the 1st move unless it is blocked by taunt, disable, torment, etc..." + ) + , TRY_TO_TERASTILLIZE( + "Try to Terastillize:
Try to terastillize if available. Add 4s per try but greatly increase win rate.", + LockMode::UNLOCK_WHILE_RUNNING, true + ) +{ +// PA_ADD_STATIC(description); + PA_ADD_OPTION(TRY_TO_TERASTILLIZE); + PA_ADD_OPTION(MOVE_TABLE); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.h index 95d08003d8..931e30949a 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraAIOption.h @@ -1,38 +1,38 @@ -/* Tera AI Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraAIOption_H -#define PokemonAutomation_PokemonSV_TeraAIOption_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "PokemonSV_TeraMoveTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraAIOption : public GroupOption{ -public: - TeraAIOption(); - -public: - StaticTextOption description; - BooleanCheckBoxOption TRY_TO_TERASTILLIZE; - TeraMoveTable MOVE_TABLE; - -}; - - - - -} -} -} -#endif +/* Tera AI Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraAIOption_H +#define PokemonAutomation_PokemonSV_TeraAIOption_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "PokemonSV_TeraMoveTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraAIOption : public GroupOption{ +public: + TeraAIOption(); + +public: + StaticTextOption description; + BooleanCheckBoxOption TRY_TO_TERASTILLIZE; + TeraMoveTable MOVE_TABLE; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.cpp index 03534f3217..f794a89eab 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.cpp @@ -1,42 +1,42 @@ -/* Tera Catch On Win Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_TeraCatchOnWinOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -TeraFarmerCatchOnWin::TeraFarmerCatchOnWin(bool enabled) - : GroupOption( - "Catch on Win", - LockMode::UNLOCK_WHILE_RUNNING, - enabled - ? GroupOption::EnableMode::DEFAULT_ENABLED - : GroupOption::EnableMode::DEFAULT_DISABLED - ) - , BALL_SELECT( - "Ball Select:", - LockMode::UNLOCK_WHILE_RUNNING, - "poke-ball" - ) - , FIX_TIME_ON_CATCH( - "Fix Clock:
Fix the time when catching so the caught date will be correct.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) -{ - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(FIX_TIME_ON_CATCH); -} - - - - -} -} -} +/* Tera Catch On Win Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_TeraCatchOnWinOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +TeraFarmerCatchOnWin::TeraFarmerCatchOnWin(bool enabled) + : GroupOption( + "Catch on Win", + LockMode::UNLOCK_WHILE_RUNNING, + enabled + ? GroupOption::EnableMode::DEFAULT_ENABLED + : GroupOption::EnableMode::DEFAULT_DISABLED + ) + , BALL_SELECT( + "Ball Select:", + LockMode::UNLOCK_WHILE_RUNNING, + "poke-ball" + ) + , FIX_TIME_ON_CATCH( + "Fix Clock:
Fix the time when catching so the caught date will be correct.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) +{ + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(FIX_TIME_ON_CATCH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h index 854bcb2a8d..b7e8ccb8d5 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h @@ -1,35 +1,35 @@ -/* Tera Catch On Win Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraCatchOnWinOption_H -#define PokemonAutomation_PokemonSV_TeraCatchOnWinOption_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraFarmerCatchOnWin : public GroupOption{ -public: - TeraFarmerCatchOnWin(bool enabled); - -public: - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - BooleanCheckBoxOption FIX_TIME_ON_CATCH; -}; - - - - -} -} -} -#endif +/* Tera Catch On Win Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraCatchOnWinOption_H +#define PokemonAutomation_PokemonSV_TeraCatchOnWinOption_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraFarmerCatchOnWin : public GroupOption{ +public: + TeraFarmerCatchOnWin(bool enabled); + +public: + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + BooleanCheckBoxOption FIX_TIME_ON_CATCH; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.cpp index 1d9d6ca3d0..4da86f258e 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.cpp @@ -1,169 +1,169 @@ -/* Tera Move Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_TeraMoveTable.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const EnumDropdownDatabase& tera_move_enum_database(){ - static EnumDropdownDatabase database{ - {TeraMoveType::Wait, "wait", "Wait for X seconds."}, - {TeraMoveType::Move1, "move1", "Move 1"}, - {TeraMoveType::Move2, "move2", "Move 2"}, - {TeraMoveType::Move3, "move3", "Move 3"}, - {TeraMoveType::Move4, "move4", "Move 4"}, - {TeraMoveType::Cheer_AllOut, "cheer-allout", "Cheer - All Out"}, - {TeraMoveType::Cheer_HangTough, "cheer-hangtough", "Cheer - Hang Tough"}, - {TeraMoveType::Cheer_HealUp, "cheer-healup", "Cheer - Heal Up"}, - }; - return database; -} -const EnumDropdownDatabase& tera_target_enum_database(){ - static EnumDropdownDatabase database{ - {TeraTarget::Opponent, "opponent", "Opponent"}, - {TeraTarget::Player0, "player0", "Player 0 (yourself)"}, - {TeraTarget::Player1, "player1", "Player 1 (right of yourself)"}, - {TeraTarget::Player2, "player2", "Player 2 (2nd from the right)"}, - {TeraTarget::Player3, "player3", "Player 3 (rightmost player)"}, - }; - return database; -} - - -std::string TeraMoveEntry::to_str() const{ - switch (type){ - case TeraMoveType::Wait: - return "Wait for " + std::to_string(seconds) + " second(s)."; - case TeraMoveType::Move1: - case TeraMoveType::Move2: - case TeraMoveType::Move3: - case TeraMoveType::Move4:{ - int slot = (int)type - (int)TeraMoveType::Move1; - std::string str = "Move " + std::to_string(slot + 1) + " on "; - if (target == TeraTarget::Opponent){ - return str + "opponent."; - }else{ - slot = (int)target - (int)TeraTarget::Player0; - return "player " + std::to_string(slot) + "."; - } - } - case TeraMoveType::Cheer_AllOut: - return "Cheer - All Out"; - case TeraMoveType::Cheer_HangTough: - return "Cheer - Hang Tough"; - case TeraMoveType::Cheer_HealUp: - return "Cheer - Heal Up"; - } - return "(Invalid Move)"; -} - - - - -TeraMoveTableRow::~TeraMoveTableRow(){ - type.remove_listener(*this); -} -TeraMoveTableRow::TeraMoveTableRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , type(tera_move_enum_database(), LockMode::UNLOCK_WHILE_RUNNING, TeraMoveType::Move1) - , seconds(LockMode::UNLOCK_WHILE_RUNNING, 5) - , target(tera_target_enum_database(), LockMode::UNLOCK_WHILE_RUNNING, TeraTarget::Opponent) - , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "(e.g. Screech, Belly Drum)") -{ - PA_ADD_OPTION(type); - PA_ADD_OPTION(seconds); - PA_ADD_OPTION(target); - PA_ADD_OPTION(notes); - - TeraMoveTableRow::on_config_value_changed(this); - type.add_listener(*this); -} -std::unique_ptr TeraMoveTableRow::clone() const{ - std::unique_ptr ret(new TeraMoveTableRow(parent())); - ret->type.set(type); - ret->seconds.set(seconds); - ret->target.set(target); - ret->notes.set(notes); - return ret; -} -TeraMoveEntry TeraMoveTableRow::snapshot() const{ - return TeraMoveEntry{type, seconds, target}; -} -void TeraMoveTableRow::on_config_value_changed(void* object){ - TeraMoveType type = this->type; -// cout << "Enter: type = " << (int)type << endl; - - seconds.set_visibility( - type == TeraMoveType::Wait - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN - ); - - bool is_move = - type == TeraMoveType::Move1 || - type == TeraMoveType::Move2 || - type == TeraMoveType::Move3 || - type == TeraMoveType::Move4; - - target.set_visibility( - is_move - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN - ); - -// cout << "Exit: type = " << (int)type << endl; - -} - - - - - -TeraMoveTable::TeraMoveTable() - : EditableTableOption_t( - "Move Table:
" - "Run this sequence of moves. When the end of the table is reached, " - "the last entry will be repeated until the battle is won or lost. " - "Changes to this table take effect on the next battle.", - LockMode::UNLOCK_WHILE_RUNNING, - make_defaults() - ) -{} - -std::vector TeraMoveTable::snapshot(){ - return EditableTableOption_t::snapshot(); -} -std::vector TeraMoveTable::make_header() const{ - return { - "Move", - "Wait (seconds)", - "Target", - "Notes", - }; -} -std::vector> TeraMoveTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(new TeraMoveTableRow(*this)); - return ret; -} - - - - - - - - -} -} -} +/* Tera Move Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_TeraMoveTable.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const EnumDropdownDatabase& tera_move_enum_database(){ + static EnumDropdownDatabase database{ + {TeraMoveType::Wait, "wait", "Wait for X seconds."}, + {TeraMoveType::Move1, "move1", "Move 1"}, + {TeraMoveType::Move2, "move2", "Move 2"}, + {TeraMoveType::Move3, "move3", "Move 3"}, + {TeraMoveType::Move4, "move4", "Move 4"}, + {TeraMoveType::Cheer_AllOut, "cheer-allout", "Cheer - All Out"}, + {TeraMoveType::Cheer_HangTough, "cheer-hangtough", "Cheer - Hang Tough"}, + {TeraMoveType::Cheer_HealUp, "cheer-healup", "Cheer - Heal Up"}, + }; + return database; +} +const EnumDropdownDatabase& tera_target_enum_database(){ + static EnumDropdownDatabase database{ + {TeraTarget::Opponent, "opponent", "Opponent"}, + {TeraTarget::Player0, "player0", "Player 0 (yourself)"}, + {TeraTarget::Player1, "player1", "Player 1 (right of yourself)"}, + {TeraTarget::Player2, "player2", "Player 2 (2nd from the right)"}, + {TeraTarget::Player3, "player3", "Player 3 (rightmost player)"}, + }; + return database; +} + + +std::string TeraMoveEntry::to_str() const{ + switch (type){ + case TeraMoveType::Wait: + return "Wait for " + std::to_string(seconds) + " second(s)."; + case TeraMoveType::Move1: + case TeraMoveType::Move2: + case TeraMoveType::Move3: + case TeraMoveType::Move4:{ + int slot = (int)type - (int)TeraMoveType::Move1; + std::string str = "Move " + std::to_string(slot + 1) + " on "; + if (target == TeraTarget::Opponent){ + return str + "opponent."; + }else{ + slot = (int)target - (int)TeraTarget::Player0; + return "player " + std::to_string(slot) + "."; + } + } + case TeraMoveType::Cheer_AllOut: + return "Cheer - All Out"; + case TeraMoveType::Cheer_HangTough: + return "Cheer - Hang Tough"; + case TeraMoveType::Cheer_HealUp: + return "Cheer - Heal Up"; + } + return "(Invalid Move)"; +} + + + + +TeraMoveTableRow::~TeraMoveTableRow(){ + type.remove_listener(*this); +} +TeraMoveTableRow::TeraMoveTableRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , type(tera_move_enum_database(), LockMode::UNLOCK_WHILE_RUNNING, TeraMoveType::Move1) + , seconds(LockMode::UNLOCK_WHILE_RUNNING, 5) + , target(tera_target_enum_database(), LockMode::UNLOCK_WHILE_RUNNING, TeraTarget::Opponent) + , notes(false, LockMode::UNLOCK_WHILE_RUNNING, "", "(e.g. Screech, Belly Drum)") +{ + PA_ADD_OPTION(type); + PA_ADD_OPTION(seconds); + PA_ADD_OPTION(target); + PA_ADD_OPTION(notes); + + TeraMoveTableRow::on_config_value_changed(this); + type.add_listener(*this); +} +std::unique_ptr TeraMoveTableRow::clone() const{ + std::unique_ptr ret(new TeraMoveTableRow(parent())); + ret->type.set(type); + ret->seconds.set(seconds); + ret->target.set(target); + ret->notes.set(notes); + return ret; +} +TeraMoveEntry TeraMoveTableRow::snapshot() const{ + return TeraMoveEntry{type, seconds, target}; +} +void TeraMoveTableRow::on_config_value_changed(void* object){ + TeraMoveType type = this->type; +// cout << "Enter: type = " << (int)type << endl; + + seconds.set_visibility( + type == TeraMoveType::Wait + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN + ); + + bool is_move = + type == TeraMoveType::Move1 || + type == TeraMoveType::Move2 || + type == TeraMoveType::Move3 || + type == TeraMoveType::Move4; + + target.set_visibility( + is_move + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN + ); + +// cout << "Exit: type = " << (int)type << endl; + +} + + + + + +TeraMoveTable::TeraMoveTable() + : EditableTableOption_t( + "Move Table:
" + "Run this sequence of moves. When the end of the table is reached, " + "the last entry will be repeated until the battle is won or lost. " + "Changes to this table take effect on the next battle.", + LockMode::UNLOCK_WHILE_RUNNING, + make_defaults() + ) +{} + +std::vector TeraMoveTable::snapshot(){ + return EditableTableOption_t::snapshot(); +} +std::vector TeraMoveTable::make_header() const{ + return { + "Move", + "Wait (seconds)", + "Target", + "Notes", + }; +} +std::vector> TeraMoveTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(new TeraMoveTableRow(*this)); + return ret; +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.h index e1e58e4203..25275c8276 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraMoveTable.h @@ -1,91 +1,91 @@ -/* Tera Move Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraMoveTable_H -#define PokemonAutomation_PokemonSV_TeraMoveTable_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -enum class TeraMoveType{ - Wait, - Move1, - Move2, - Move3, - Move4, - Cheer_AllOut, - Cheer_HangTough, - Cheer_HealUp, -}; -const EnumDropdownDatabase& tera_move_enum_database(); - -enum class TeraTarget{ - Opponent, - Player0, // Yourself - Player1, - Player2, - Player3, -}; -const EnumDropdownDatabase& tera_target_enum_database(); - - - - -struct TeraMoveEntry{ - TeraMoveType type; - uint8_t seconds; - TeraTarget target; - - std::string to_str() const; -}; - - -class TeraMoveTableRow : public EditableTableRow, public ConfigOption::Listener{ -public: - ~TeraMoveTableRow(); - TeraMoveTableRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - - TeraMoveEntry snapshot() const; - -private: - virtual void on_config_value_changed(void* object) override; - -private: - EnumDropdownCell type; - SimpleIntegerCell seconds; - EnumDropdownCell target; - StringCell notes; -}; - - -class TeraMoveTable : public EditableTableOption_t{ -public: - TeraMoveTable(); - - std::vector snapshot(); - - virtual std::vector make_header() const; - - std::vector> make_defaults(); - -}; - - - - -} -} -} -#endif +/* Tera Move Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraMoveTable_H +#define PokemonAutomation_PokemonSV_TeraMoveTable_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +enum class TeraMoveType{ + Wait, + Move1, + Move2, + Move3, + Move4, + Cheer_AllOut, + Cheer_HangTough, + Cheer_HealUp, +}; +const EnumDropdownDatabase& tera_move_enum_database(); + +enum class TeraTarget{ + Opponent, + Player0, // Yourself + Player1, + Player2, + Player3, +}; +const EnumDropdownDatabase& tera_target_enum_database(); + + + + +struct TeraMoveEntry{ + TeraMoveType type; + uint8_t seconds; + TeraTarget target; + + std::string to_str() const; +}; + + +class TeraMoveTableRow : public EditableTableRow, public ConfigOption::Listener{ +public: + ~TeraMoveTableRow(); + TeraMoveTableRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + + TeraMoveEntry snapshot() const; + +private: + virtual void on_config_value_changed(void* object) override; + +private: + EnumDropdownCell type; + SimpleIntegerCell seconds; + EnumDropdownCell target; + StringCell notes; +}; + + +class TeraMoveTable : public EditableTableOption_t{ +public: + TeraMoveTable(); + + std::vector snapshot(); + + virtual std::vector make_header() const; + + std::vector> make_defaults(); + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.cpp index 59ed4c6498..bb505dd6f6 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.cpp @@ -1,234 +1,234 @@ -/* Tera Roll Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV_TeraRollFilter.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -TeraRollFilter::TeraRollFilter(uint8_t default_max_stars, bool enable_herb_filter) - : GroupOption("Opponent Filter", LockMode::UNLOCK_WHILE_RUNNING) - , EVENT_CHECK_MODE( - "Event Tera Raid Action:
Choose how the program interacts with event/non-event raids." - "
Check only non-event can be further sped up if you exclude 6 star from your filters.", - { - {EventCheckMode::CHECK_ALL, "check_all", "Check everything. Don't filter by event."}, - {EventCheckMode::CHECK_ONLY_EVENT, "check_event", "Check only event raids."}, - {EventCheckMode::CHECK_ONLY_NONEVENT, "check_nonevent", "Check only non-event raids."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - EventCheckMode::CHECK_ALL - ) - , MIN_STARS( - "Min Stars:
Skip raids with less than this many stars.", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 1, 7 - ) - , MAX_STARS( - "Max Stars:
Skip raids with more than this many stars.", - LockMode::UNLOCK_WHILE_RUNNING, - default_max_stars, 1, 7 - ) - , SKIP_NON_HERBA( - "Skip Non-Herba Raids:
" - "Skip raids that don't have the possibility to reward all types of Herba Mystica. Enable this if you are searching for an herba raid.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(EVENT_CHECK_MODE); - PA_ADD_OPTION(MIN_STARS); - PA_ADD_OPTION(MAX_STARS); - if (enable_herb_filter){ - PA_ADD_OPTION(SKIP_NON_HERBA); - } -} - -std::string TeraRollFilter::check_validity() const{ - if (MIN_STARS > MAX_STARS){ - return "\"Min Stars\" is bigger than \"Max Stars\"."; - } - if (SKIP_NON_HERBA && MAX_STARS < 5){ - return - "Setting \"Max Stars\" below 5 and \"Skip Herba\" to " - "true will never yield results because all herb raids are 5-star or higher."; - } - if (SKIP_NON_HERBA && EVENT_CHECK_MODE == EventCheckMode::CHECK_ONLY_EVENT){ - return "\"Check only event raids\" and \"Skip Non-Herba Raids\" is incompatible because only non-event raids can have all herbs."; - } - return ""; -} - -TeraRollFilter::FilterResult TeraRollFilter::run_filter( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - TeraRaidData& data -) const{ - uint8_t min_stars = MIN_STARS; - uint8_t max_stars = MAX_STARS; - EventCheckMode event_check_mode = EVENT_CHECK_MODE; - - bool sparkling_raid = false; - - switch (event_check_mode){ - case EventCheckMode::CHECK_ALL: - break; - case EventCheckMode::CHECK_ONLY_EVENT: - // this makes sure that we only check sparkling raids - // and that includes event & 6 star raids - // a later star check will be performed to exclude 6 star raids - if (!is_sparkling_raid(stream, context)){ - stream.log("No sparkling raid detected, skipping...", COLOR_ORANGE); -// data.event_type = TeraRaidData::EventType::NORMAL; - return FilterResult::NO_RAID; - } - break; - case EventCheckMode::CHECK_ONLY_NONEVENT: - if (is_sparkling_raid(stream, context)){ - // if the user excluded 6 star raids, skip sparkling raids - if (min_stars > 6 || max_stars < 6){ - stream.log("Sparkling raid detected, skipping...", COLOR_ORANGE); - return FilterResult::FAILED; - } - // if the user included 6 star raids, defer skip decision - sparkling_raid = true; - } - break; - } - - if (!open_raid(stream, context)){ - return FilterResult::NO_RAID; - } - context.wait_for(std::chrono::milliseconds(500)); - - VideoSnapshot screen = stream.video().snapshot(); - TeraCardReader reader(COLOR_RED); - - read_card(info, stream, screen, reader, data); - - switch (event_check_mode){ - case EventCheckMode::CHECK_ALL: - break; - case EventCheckMode::CHECK_ONLY_EVENT: - // only sparkling raids at this point - // skip 6 star raids - if (data.stars == 6){ - stream.log("Detected non-event 6 star raid, skipping...", COLOR_ORANGE); - close_raid(info, stream, context); - return FilterResult::NO_RAID; - } - break; - case EventCheckMode::CHECK_ONLY_NONEVENT: - // skip sparkling raids unless 6 stars - if (sparkling_raid && data.stars != 6){ - stream.log("Detected event raid, skipping...", COLOR_ORANGE); - close_raid(info, stream, context); - return FilterResult::NO_RAID; - } - break; - } - - if (data.stars < min_stars || data.stars > max_stars){ - stream.log("Raid stars is out of range. Skipping..."); - close_raid(info, stream, context); - return FilterResult::FAILED; - } - - // TODO: Add species filter - - if (!check_herba(data.species)){ - stream.log("Raid cannot have all herbas. Skipping..."); - close_raid(info, stream, context); - return FilterResult::FAILED; - } - - return FilterResult::PASSED; -} - - -void TeraRollFilter::read_card( - const ProgramInfo& info, VideoStream& stream, const ImageViewRGB32& screen, - TeraCardReader& reader, TeraRaidData& data -) const{ - data.stars = reader.stars(stream.logger(), info, screen); - data.tera_type = reader.tera_type(stream.logger(), info, screen); - data.species = reader.pokemon_slug(stream.logger(), info, screen); - - std::string stars = data.stars == 0 - ? "?" - : std::to_string(data.stars); - std::string tera_type = data.tera_type.empty() - ? "? tera" - : data.tera_type; - - std::string pokemon; - if (data.species.empty()){ - pokemon = "unknown " + Pokemon::STRING_POKEMON; - }else if (data.species.size() == 1){ - pokemon = *data.species.begin(); - }else{ - pokemon = set_to_str(data.species); - } - - stream.overlay().add_log( - stars + "* " + tera_type + " " + pokemon, - COLOR_GREEN - ); - std::string log = "Detected a " + stars + "* " + tera_type + " " + pokemon; - stream.log(log); -} -bool TeraRollFilter::check_herba(const std::set& pokemon_slugs) const{ - if (!SKIP_NON_HERBA){ - return true; - } - - static const std::set fivestar{ - "gengar", "glalie", "amoonguss", "dondozo", "palafin-zero", "finizen", "blissey", "eelektross", "drifblim", "cetitan", - "snorlax", "dusknoir", "mandibuzz", "basculegion" - }; - static const std::set sixstar{ - "blissey", "vaporeon", "amoonguss", "farigiraf", "cetitan", "dondozo", - "poliwrath", "snorlax", "basculegion" - }; - - std::set fivestar_compatible; - std::set_intersection( - fivestar_compatible.begin(), fivestar_compatible.end(), - pokemon_slugs.begin(), pokemon_slugs.end(), - std::inserter(fivestar_compatible, fivestar_compatible.begin()) - ); - if (!fivestar_compatible.empty()){ - return true; - } - - std::set sixstar_compatible; - std::set_intersection( - sixstar_compatible.begin(), sixstar_compatible.end(), - pokemon_slugs.begin(), pokemon_slugs.end(), - std::inserter(sixstar_compatible, sixstar_compatible.begin()) - ); - if (!sixstar_compatible.empty()){ - return true; - } - - return false; -} - - - - -} -} -} +/* Tera Roll Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV_TeraRollFilter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +TeraRollFilter::TeraRollFilter(uint8_t default_max_stars, bool enable_herb_filter) + : GroupOption("Opponent Filter", LockMode::UNLOCK_WHILE_RUNNING) + , EVENT_CHECK_MODE( + "Event Tera Raid Action:
Choose how the program interacts with event/non-event raids." + "
Check only non-event can be further sped up if you exclude 6 star from your filters.", + { + {EventCheckMode::CHECK_ALL, "check_all", "Check everything. Don't filter by event."}, + {EventCheckMode::CHECK_ONLY_EVENT, "check_event", "Check only event raids."}, + {EventCheckMode::CHECK_ONLY_NONEVENT, "check_nonevent", "Check only non-event raids."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + EventCheckMode::CHECK_ALL + ) + , MIN_STARS( + "Min Stars:
Skip raids with less than this many stars.", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 1, 7 + ) + , MAX_STARS( + "Max Stars:
Skip raids with more than this many stars.", + LockMode::UNLOCK_WHILE_RUNNING, + default_max_stars, 1, 7 + ) + , SKIP_NON_HERBA( + "Skip Non-Herba Raids:
" + "Skip raids that don't have the possibility to reward all types of Herba Mystica. Enable this if you are searching for an herba raid.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(EVENT_CHECK_MODE); + PA_ADD_OPTION(MIN_STARS); + PA_ADD_OPTION(MAX_STARS); + if (enable_herb_filter){ + PA_ADD_OPTION(SKIP_NON_HERBA); + } +} + +std::string TeraRollFilter::check_validity() const{ + if (MIN_STARS > MAX_STARS){ + return "\"Min Stars\" is bigger than \"Max Stars\"."; + } + if (SKIP_NON_HERBA && MAX_STARS < 5){ + return + "Setting \"Max Stars\" below 5 and \"Skip Herba\" to " + "true will never yield results because all herb raids are 5-star or higher."; + } + if (SKIP_NON_HERBA && EVENT_CHECK_MODE == EventCheckMode::CHECK_ONLY_EVENT){ + return "\"Check only event raids\" and \"Skip Non-Herba Raids\" is incompatible because only non-event raids can have all herbs."; + } + return ""; +} + +TeraRollFilter::FilterResult TeraRollFilter::run_filter( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + TeraRaidData& data +) const{ + uint8_t min_stars = MIN_STARS; + uint8_t max_stars = MAX_STARS; + EventCheckMode event_check_mode = EVENT_CHECK_MODE; + + bool sparkling_raid = false; + + switch (event_check_mode){ + case EventCheckMode::CHECK_ALL: + break; + case EventCheckMode::CHECK_ONLY_EVENT: + // this makes sure that we only check sparkling raids + // and that includes event & 6 star raids + // a later star check will be performed to exclude 6 star raids + if (!is_sparkling_raid(stream, context)){ + stream.log("No sparkling raid detected, skipping...", COLOR_ORANGE); +// data.event_type = TeraRaidData::EventType::NORMAL; + return FilterResult::NO_RAID; + } + break; + case EventCheckMode::CHECK_ONLY_NONEVENT: + if (is_sparkling_raid(stream, context)){ + // if the user excluded 6 star raids, skip sparkling raids + if (min_stars > 6 || max_stars < 6){ + stream.log("Sparkling raid detected, skipping...", COLOR_ORANGE); + return FilterResult::FAILED; + } + // if the user included 6 star raids, defer skip decision + sparkling_raid = true; + } + break; + } + + if (!open_raid(stream, context)){ + return FilterResult::NO_RAID; + } + context.wait_for(std::chrono::milliseconds(500)); + + VideoSnapshot screen = stream.video().snapshot(); + TeraCardReader reader(COLOR_RED); + + read_card(info, stream, screen, reader, data); + + switch (event_check_mode){ + case EventCheckMode::CHECK_ALL: + break; + case EventCheckMode::CHECK_ONLY_EVENT: + // only sparkling raids at this point + // skip 6 star raids + if (data.stars == 6){ + stream.log("Detected non-event 6 star raid, skipping...", COLOR_ORANGE); + close_raid(info, stream, context); + return FilterResult::NO_RAID; + } + break; + case EventCheckMode::CHECK_ONLY_NONEVENT: + // skip sparkling raids unless 6 stars + if (sparkling_raid && data.stars != 6){ + stream.log("Detected event raid, skipping...", COLOR_ORANGE); + close_raid(info, stream, context); + return FilterResult::NO_RAID; + } + break; + } + + if (data.stars < min_stars || data.stars > max_stars){ + stream.log("Raid stars is out of range. Skipping..."); + close_raid(info, stream, context); + return FilterResult::FAILED; + } + + // TODO: Add species filter + + if (!check_herba(data.species)){ + stream.log("Raid cannot have all herbas. Skipping..."); + close_raid(info, stream, context); + return FilterResult::FAILED; + } + + return FilterResult::PASSED; +} + + +void TeraRollFilter::read_card( + const ProgramInfo& info, VideoStream& stream, const ImageViewRGB32& screen, + TeraCardReader& reader, TeraRaidData& data +) const{ + data.stars = reader.stars(stream.logger(), info, screen); + data.tera_type = reader.tera_type(stream.logger(), info, screen); + data.species = reader.pokemon_slug(stream.logger(), info, screen); + + std::string stars = data.stars == 0 + ? "?" + : std::to_string(data.stars); + std::string tera_type = data.tera_type.empty() + ? "? tera" + : data.tera_type; + + std::string pokemon; + if (data.species.empty()){ + pokemon = "unknown " + Pokemon::STRING_POKEMON; + }else if (data.species.size() == 1){ + pokemon = *data.species.begin(); + }else{ + pokemon = set_to_str(data.species); + } + + stream.overlay().add_log( + stars + "* " + tera_type + " " + pokemon, + COLOR_GREEN + ); + std::string log = "Detected a " + stars + "* " + tera_type + " " + pokemon; + stream.log(log); +} +bool TeraRollFilter::check_herba(const std::set& pokemon_slugs) const{ + if (!SKIP_NON_HERBA){ + return true; + } + + static const std::set fivestar{ + "gengar", "glalie", "amoonguss", "dondozo", "palafin-zero", "finizen", "blissey", "eelektross", "drifblim", "cetitan", + "snorlax", "dusknoir", "mandibuzz", "basculegion" + }; + static const std::set sixstar{ + "blissey", "vaporeon", "amoonguss", "farigiraf", "cetitan", "dondozo", + "poliwrath", "snorlax", "basculegion" + }; + + std::set fivestar_compatible; + std::set_intersection( + fivestar_compatible.begin(), fivestar_compatible.end(), + pokemon_slugs.begin(), pokemon_slugs.end(), + std::inserter(fivestar_compatible, fivestar_compatible.begin()) + ); + if (!fivestar_compatible.empty()){ + return true; + } + + std::set sixstar_compatible; + std::set_intersection( + sixstar_compatible.begin(), sixstar_compatible.end(), + pokemon_slugs.begin(), pokemon_slugs.end(), + std::inserter(sixstar_compatible, sixstar_compatible.begin()) + ); + if (!sixstar_compatible.empty()){ + return true; + } + + return false; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.h index 50875de6fe..e0e3210344 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TeraRollFilter.h @@ -1,90 +1,90 @@ -/* Tera Roll Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraRollFilter_H -#define PokemonAutomation_PokemonSV_TeraRollFilter_H - -#include -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class Logger; - class ImageViewRGB32; - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class TeraCardReader; - - -struct TeraRaidData{ - -#if 0 - enum class EventType{ - UNKNOWN, - NORMAL, - EVENT, - }; - EventType event_type = EventType::UNKNOWN; -#endif - - uint8_t stars = 0; - std::string tera_type; - std::set species; -}; - - - -class TeraRollFilter : public GroupOption{ -public: - TeraRollFilter(uint8_t default_max_stars, bool enable_herb_filter); - - virtual std::string check_validity() const override; - - enum class FilterResult{ - NO_RAID, - FAILED, - PASSED, - }; - - FilterResult run_filter( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - TeraRaidData& data - ) const; - - -private: - void read_card( - const ProgramInfo& info, VideoStream& stream, const ImageViewRGB32& screen, - TeraCardReader& reader, TeraRaidData& data - ) const; - bool check_herba(const std::set& pokemon_slugs) const; - -public: - enum class EventCheckMode{ - CHECK_ALL, - CHECK_ONLY_EVENT, - CHECK_ONLY_NONEVENT, - }; - EnumDropdownOption EVENT_CHECK_MODE; - - SimpleIntegerOption MIN_STARS; - SimpleIntegerOption MAX_STARS; - - BooleanCheckBoxOption SKIP_NON_HERBA; -}; - - - -} -} -} -#endif +/* Tera Roll Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraRollFilter_H +#define PokemonAutomation_PokemonSV_TeraRollFilter_H + +#include +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class Logger; + class ImageViewRGB32; + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class TeraCardReader; + + +struct TeraRaidData{ + +#if 0 + enum class EventType{ + UNKNOWN, + NORMAL, + EVENT, + }; + EventType event_type = EventType::UNKNOWN; +#endif + + uint8_t stars = 0; + std::string tera_type; + std::set species; +}; + + + +class TeraRollFilter : public GroupOption{ +public: + TeraRollFilter(uint8_t default_max_stars, bool enable_herb_filter); + + virtual std::string check_validity() const override; + + enum class FilterResult{ + NO_RAID, + FAILED, + PASSED, + }; + + FilterResult run_filter( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + TeraRaidData& data + ) const; + + +private: + void read_card( + const ProgramInfo& info, VideoStream& stream, const ImageViewRGB32& screen, + TeraCardReader& reader, TeraRaidData& data + ) const; + bool check_herba(const std::set& pokemon_slugs) const; + +public: + enum class EventCheckMode{ + CHECK_ALL, + CHECK_ONLY_EVENT, + CHECK_ONLY_NONEVENT, + }; + EnumDropdownOption EVENT_CHECK_MODE; + + SimpleIntegerOption MIN_STARS; + SimpleIntegerOption MAX_STARS; + + BooleanCheckBoxOption SKIP_NON_HERBA; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.cpp index e4f0dbf5c0..18529f37b1 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.cpp @@ -1,52 +1,52 @@ -/* Tournament Prize Select Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h" -#include "PokemonSV/Resources/PokemonSV_ItemSprites.h" -#include "PokemonSV_TournamentPrizeSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -StringSelectDatabase make_tournament_prize_database(){ - StringSelectDatabase ret; - for (const auto& slug : TOURNAMENT_PRIZE_SLUGS()){ - const TournamentPrizeNames& data = get_tournament_prize_name(slug); - /* - const SpriteDatabase::Sprite* sprite = TOURNAMENT_PRIZE_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); - } - */ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - } - return ret; -} -const StringSelectDatabase& TOURNAMENT_PRIZE_SELECT_DATABASE(){ - static StringSelectDatabase database = make_tournament_prize_database(); - return database; -} - - -TournamentPrizeSelectCell::TournamentPrizeSelectCell( - const std::string& default_slug -) - : StringSelectCell( - TOURNAMENT_PRIZE_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - -} -} -} +/* Tournament Prize Select Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h" +#include "PokemonSV/Resources/PokemonSV_ItemSprites.h" +#include "PokemonSV_TournamentPrizeSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +StringSelectDatabase make_tournament_prize_database(){ + StringSelectDatabase ret; + for (const auto& slug : TOURNAMENT_PRIZE_SLUGS()){ + const TournamentPrizeNames& data = get_tournament_prize_name(slug); + /* + const SpriteDatabase::Sprite* sprite = TOURNAMENT_PRIZE_SPRITES().get_nothrow(slug); + if (sprite == nullptr){ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + } + */ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + } + return ret; +} +const StringSelectDatabase& TOURNAMENT_PRIZE_SELECT_DATABASE(){ + static StringSelectDatabase database = make_tournament_prize_database(); + return database; +} + + +TournamentPrizeSelectCell::TournamentPrizeSelectCell( + const std::string& default_slug +) + : StringSelectCell( + TOURNAMENT_PRIZE_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.h index ed106496cd..6ff6d1f7b9 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeSelectOption.h @@ -1,24 +1,24 @@ -/* Tournament Prize Select Option - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TournamentPrizeSelectOption_H -#define PokemonAutomation_PokemonSV_TournamentPrizeSelectOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class TournamentPrizeSelectCell : public StringSelectCell{ -public: - TournamentPrizeSelectCell(const std::string& default_slug); -}; - -} -} -} -#endif +/* Tournament Prize Select Option + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TournamentPrizeSelectOption_H +#define PokemonAutomation_PokemonSV_TournamentPrizeSelectOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class TournamentPrizeSelectCell : public StringSelectCell{ +public: + TournamentPrizeSelectCell(const std::string& default_slug); +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.cpp b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.cpp index ca5f4decb4..cd92cd202c 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.cpp @@ -1,73 +1,73 @@ -/* Tournament Prize Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h" -#include "PokemonSV_TournamentPrizeTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -TournamentPrizeSelectorRow::TournamentPrizeSelectorRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , item("beast-ball") -{ - PA_ADD_OPTION(item); -} -std::unique_ptr TournamentPrizeSelectorRow::clone() const{ - std::unique_ptr ret(new TournamentPrizeSelectorRow(parent())); - ret->item.set_by_index(item.index()); - return ret; -} - -TournamentPrizeTable::TournamentPrizeTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - -bool TournamentPrizeTable::find_item(const std::string& item_slug) const{ - std::vector> table = copy_snapshot(); - for (const std::unique_ptr& row : table){ - if (row->item.slug() == item_slug){ - return true; - } - } - return false; -} - -std::vector TournamentPrizeTable::selected_items() const{ - std::vector> table = copy_snapshot(); - std::vector slugs; - for (const std::unique_ptr& row : table){ - slugs.emplace_back(row->item.slug()); - } - return slugs; -} - - -std::vector TournamentPrizeTable::make_header() const{ - return std::vector{ - "Item", - }; -} - -std::vector> TournamentPrizeTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this)); - return ret; -} - - - - - - -} -} -} +/* Tournament Prize Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h" +#include "PokemonSV_TournamentPrizeTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +TournamentPrizeSelectorRow::TournamentPrizeSelectorRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , item("beast-ball") +{ + PA_ADD_OPTION(item); +} +std::unique_ptr TournamentPrizeSelectorRow::clone() const{ + std::unique_ptr ret(new TournamentPrizeSelectorRow(parent())); + ret->item.set_by_index(item.index()); + return ret; +} + +TournamentPrizeTable::TournamentPrizeTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + +bool TournamentPrizeTable::find_item(const std::string& item_slug) const{ + std::vector> table = copy_snapshot(); + for (const std::unique_ptr& row : table){ + if (row->item.slug() == item_slug){ + return true; + } + } + return false; +} + +std::vector TournamentPrizeTable::selected_items() const{ + std::vector> table = copy_snapshot(); + std::vector slugs; + for (const std::unique_ptr& row : table){ + slugs.emplace_back(row->item.slug()); + } + return slugs; +} + + +std::vector TournamentPrizeTable::make_header() const{ + return std::vector{ + "Item", + }; +} + +std::vector> TournamentPrizeTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this)); + return ret; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.h b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.h index 5afd11a651..4aa32aa11e 100644 --- a/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.h +++ b/SerialPrograms/Source/PokemonSV/Options/PokemonSV_TournamentPrizeTable.h @@ -1,51 +1,51 @@ -/* Tournament Prize Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TournamentPrizeTable_H -#define PokemonAutomation_PokemonSV_TournamentPrizeTable_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonSV_TournamentPrizeSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TournamentPrizeSelectorRow : public EditableTableRow{ -public: - TournamentPrizeSelectorRow(EditableTableOption& parent_table); - virtual std::unique_ptr clone() const override; - -public: - TournamentPrizeSelectCell item; -}; - - - -class TournamentPrizeTable : public EditableTableOption_t{ -public: - TournamentPrizeTable(std::string label); - - - // Whether item_slug is among the selected items. - bool find_item(const std::string& item_slug) const; - std::vector selected_items() const; - - virtual std::vector make_header() const override; - - std::vector> make_defaults(); -}; - - - - - -} -} -} -#endif +/* Tournament Prize Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TournamentPrizeTable_H +#define PokemonAutomation_PokemonSV_TournamentPrizeTable_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonSV_TournamentPrizeSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TournamentPrizeSelectorRow : public EditableTableRow{ +public: + TournamentPrizeSelectorRow(EditableTableOption& parent_table); + virtual std::unique_ptr clone() const override; + +public: + TournamentPrizeSelectCell item; +}; + + + +class TournamentPrizeTable : public EditableTableOption_t{ +public: + TournamentPrizeTable(std::string label); + + + // Whether item_slug is among the selected items. + bool find_item(const std::string& item_slug) const; + std::vector selected_items() const; + + virtual std::vector make_header() const override; + + std::vector> make_defaults(); +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp b/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp index 799eab550d..642cb0045f 100644 --- a/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp +++ b/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.cpp @@ -1,180 +1,180 @@ -/* Pokemon SV Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_Panels.h" - -#include "PokemonSV_Settings.h" - -#include "Programs/General/PokemonSV_MassPurchase.h" -#include "Programs/General/PokemonSV_ClothingBuyer.h" -#include "Programs/General/PokemonSV_AutonomousBallThrower.h" -#include "Programs/General/PokemonSV_SizeChecker.h" - -#include "Programs/Boxes/PokemonSV_MassRelease.h" -#include "Programs/Boxes/PokemonSV_MassAttachItems.h" - -#include "Programs/Trading/PokemonSV_SelfBoxTrade.h" -#include "Programs/Sandwiches/PokemonSV_SandwichMaker.h" - -#include "Programs/Farming/PokemonSV_LPFarmer.h" -#include "Programs/Farming/PokemonSV_GimmighoulChestFarmer.h" -#include "Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h" -#include "Programs/Farming/PokemonSV_AuctionFarmer.h" -#include "Programs/Farming/PokemonSV_ESPTraining.h" -#include "Programs/Farming/PokemonSV_TournamentFarmer.h" -#include "Programs/Farming/PokemonSV_TournamentFarmer2.h" -#include "Programs/Farming/PokemonSV_FlyingTrialFarmer.h" -#include "Programs/Farming/PokemonSV_BBQSoloFarmer.h" -#include "Programs/Farming/PokemonSV_MaterialFarmer.h" -#include "Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h" - -#include "Programs/Eggs/PokemonSV_EggFetcher.h" -#include "Programs/Eggs/PokemonSV_EggHatcher.h" -#include "Programs/Eggs/PokemonSV_EggAutonomous.h" - -#include "Programs/TeraRaids/PokemonSV_AutoHost.h" -#include "Programs/TeraRaids/PokemonSV_TeraRoller.h" -#include "Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h" -#include "Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h" - -#include "Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h" -#include "Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h" -#include "Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h" - -#include "Programs/General/PokemonSV_StatsReset.h" -#include "Programs/General/PokemonSV_StatsResetEventBattle.h" - -#include "Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h" -#include "Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h" - -#include "Programs/AutoStory/PokemonSV_AutoStory.h" - -#include "Programs/Glitches/PokemonSV_WildItemFarmer.h" -#include "Programs/Glitches/PokemonSV_RideCloner-1.0.1.h" -#include "Programs/Glitches/PokemonSV_CloneItems-1.0.1.h" - -// Deprecated -#include "Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h" - -#include "Programs/TestPrograms/PokemonSV_SoundListener.h" -#include "Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h" - -#ifdef PA_OFFICIAL -#include "../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.h" -#endif - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Scarlet and Violet") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - -// ret.emplace_back("---- Trading ----"); - ret.emplace_back(make_multi_switch_program()); - -// ret.emplace_back("---- Sandwiches ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Boxes ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Farming ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Eggs ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Tera Raids ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_multi_switch_program()); - - ret.emplace_back("---- Fast Code Entry ----"); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - - ret.emplace_back("---- Stats Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Glitches (v3.0.0) ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Glitches (v1.0.1) ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Public Betas ----"); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Deprecated Programs ----"); - ret.emplace_back(make_single_switch_program()); - - if (PreloadSettings::instance().DEVELOPER_MODE || IS_BETA_VERSION){ - ret.emplace_back("---- Untested/Beta/WIP ----"); - } - if (IS_BETA_VERSION){ -// ret.emplace_back("---- Story Automation ----"); - } - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - } - -#ifdef PA_OFFICIAL - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Research ----"); - add_panels(ret); - } -#endif - - return ret; -} - - - - -} -} -} +/* Pokemon SV Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_Panels.h" + +#include "PokemonSV_Settings.h" + +#include "Programs/General/PokemonSV_MassPurchase.h" +#include "Programs/General/PokemonSV_ClothingBuyer.h" +#include "Programs/General/PokemonSV_AutonomousBallThrower.h" +#include "Programs/General/PokemonSV_SizeChecker.h" + +#include "Programs/Boxes/PokemonSV_MassRelease.h" +#include "Programs/Boxes/PokemonSV_MassAttachItems.h" + +#include "Programs/Trading/PokemonSV_SelfBoxTrade.h" +#include "Programs/Sandwiches/PokemonSV_SandwichMaker.h" + +#include "Programs/Farming/PokemonSV_LPFarmer.h" +#include "Programs/Farming/PokemonSV_GimmighoulChestFarmer.h" +#include "Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h" +#include "Programs/Farming/PokemonSV_AuctionFarmer.h" +#include "Programs/Farming/PokemonSV_ESPTraining.h" +#include "Programs/Farming/PokemonSV_TournamentFarmer.h" +#include "Programs/Farming/PokemonSV_TournamentFarmer2.h" +#include "Programs/Farming/PokemonSV_FlyingTrialFarmer.h" +#include "Programs/Farming/PokemonSV_BBQSoloFarmer.h" +#include "Programs/Farming/PokemonSV_MaterialFarmer.h" +#include "Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h" + +#include "Programs/Eggs/PokemonSV_EggFetcher.h" +#include "Programs/Eggs/PokemonSV_EggHatcher.h" +#include "Programs/Eggs/PokemonSV_EggAutonomous.h" + +#include "Programs/TeraRaids/PokemonSV_AutoHost.h" +#include "Programs/TeraRaids/PokemonSV_TeraRoller.h" +#include "Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h" +#include "Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h" + +#include "Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h" +#include "Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h" +#include "Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h" + +#include "Programs/General/PokemonSV_StatsReset.h" +#include "Programs/General/PokemonSV_StatsResetEventBattle.h" + +#include "Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h" +#include "Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h" + +#include "Programs/AutoStory/PokemonSV_AutoStory.h" + +#include "Programs/Glitches/PokemonSV_WildItemFarmer.h" +#include "Programs/Glitches/PokemonSV_RideCloner-1.0.1.h" +#include "Programs/Glitches/PokemonSV_CloneItems-1.0.1.h" + +// Deprecated +#include "Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h" + +#include "Programs/TestPrograms/PokemonSV_SoundListener.h" +#include "Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h" + +#ifdef PA_OFFICIAL +#include "../../Internal/SerialPrograms/NintendoSwitch_TestPrograms.h" +#endif + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Scarlet and Violet") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + +// ret.emplace_back("---- Trading ----"); + ret.emplace_back(make_multi_switch_program()); + +// ret.emplace_back("---- Sandwiches ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Boxes ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Farming ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Eggs ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Tera Raids ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_multi_switch_program()); + + ret.emplace_back("---- Fast Code Entry ----"); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + + ret.emplace_back("---- Stats Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Glitches (v3.0.0) ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Glitches (v1.0.1) ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Public Betas ----"); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Deprecated Programs ----"); + ret.emplace_back(make_single_switch_program()); + + if (PreloadSettings::instance().DEVELOPER_MODE || IS_BETA_VERSION){ + ret.emplace_back("---- Untested/Beta/WIP ----"); + } + if (IS_BETA_VERSION){ +// ret.emplace_back("---- Story Automation ----"); + } + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + } + +#ifdef PA_OFFICIAL + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Research ----"); + add_panels(ret); + } +#endif + + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.h b/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.h index b8f0c660fe..1acab9f107 100644 --- a/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.h +++ b/SerialPrograms/Source/PokemonSV/PokemonSV_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon Scarlet/Violet Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_Panels_H -#define PokemonAutomation_PokemonSV_Panels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon Scarlet/Violet Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_Panels_H +#define PokemonAutomation_PokemonSV_Panels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.cpp b/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.cpp index 893a8717e7..2f274943f2 100644 --- a/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.cpp +++ b/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.cpp @@ -1,130 +1,130 @@ -/* Pokemon SV Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_menu_navigation("Menu Navigation Timings:") - , GAME_TO_HOME_DELAY1( - "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , m_start_game_timings("Start Game Timings:") - , START_GAME_MASH0( - "1. Start Game Mash:
Mash A for this long to start the game.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , START_GAME_WAIT0( - "2. Start Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "60 s" - ) - , ENTER_GAME_MASH0( - "3. Enter Game Mash:
Mash A for this long to enter the game.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , ENTER_GAME_WAIT0( - "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "60 s" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , RAID_SPAWN_DELAY0( - "Raid Spawn Delay", - LockMode::UNLOCK_WHILE_RUNNING, - "3000 ms" - ) - , SHINY_SOUND_THRESHOLD2( - "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.96, 0, 1.0 - ) - , SHINY_SOUND_LOW_FREQUENCY( - "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", - LockMode::LOCK_WHILE_RUNNING, - 1000, 0, 48000 - ) - , LETS_GO_KILL_SOUND_THRESHOLD( - "Let's Go Kill Sound Threshold:
Maximum error coefficient to trigger a Let's Go Kill detection.", - LockMode::LOCK_WHILE_RUNNING, - 0.93, 0, 1.0 - ) - , LETS_GO_KILL_SOUND_LOW_FREQUENCY( - "Let's Go Kill Sound Low Frequency (Hz):
High pass filter frequency for Let's Go Kill sound.", - LockMode::LOCK_WHILE_RUNNING, - 1000, 0, 48000 - ) -{ - PA_ADD_OPTION(GAME_TO_HOME_DELAY1); - PA_ADD_STATIC(m_start_game_timings); - PA_ADD_OPTION(START_GAME_MASH0); - PA_ADD_OPTION(START_GAME_WAIT0); - PA_ADD_OPTION(ENTER_GAME_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - PA_ADD_OPTION(m_advanced_options); - PA_ADD_OPTION(RAID_SPAWN_DELAY0); - PA_ADD_OPTION(SHINY_SOUND_THRESHOLD2); - PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); - PA_ADD_OPTION(LETS_GO_KILL_SOUND_THRESHOLD); - PA_ADD_OPTION(LETS_GO_KILL_SOUND_LOW_FREQUENCY); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonSV:GlobalSettings", - STRING_POKEMON + " SV", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/PokemonSettings.md", - "Global " + STRING_POKEMON + " Scarlet and Violet Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon SV Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_menu_navigation("Menu Navigation Timings:") + , GAME_TO_HOME_DELAY1( + "Game to Home Delay:
Delay from pressing home to entering the the Switch home menu.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , m_start_game_timings("Start Game Timings:") + , START_GAME_MASH0( + "1. Start Game Mash:
Mash A for this long to start the game.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , START_GAME_WAIT0( + "2. Start Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "60 s" + ) + , ENTER_GAME_MASH0( + "3. Enter Game Mash:
Mash A for this long to enter the game.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , ENTER_GAME_WAIT0( + "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "60 s" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , RAID_SPAWN_DELAY0( + "Raid Spawn Delay", + LockMode::UNLOCK_WHILE_RUNNING, + "3000 ms" + ) + , SHINY_SOUND_THRESHOLD2( + "Shiny Sound Threshold:
Maximum error coefficient to trigger a shiny detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.96, 0, 1.0 + ) + , SHINY_SOUND_LOW_FREQUENCY( + "Shiny Sound Low Frequency (Hz):
High pass filter frequency for shiny sound.", + LockMode::LOCK_WHILE_RUNNING, + 1000, 0, 48000 + ) + , LETS_GO_KILL_SOUND_THRESHOLD( + "Let's Go Kill Sound Threshold:
Maximum error coefficient to trigger a Let's Go Kill detection.", + LockMode::LOCK_WHILE_RUNNING, + 0.93, 0, 1.0 + ) + , LETS_GO_KILL_SOUND_LOW_FREQUENCY( + "Let's Go Kill Sound Low Frequency (Hz):
High pass filter frequency for Let's Go Kill sound.", + LockMode::LOCK_WHILE_RUNNING, + 1000, 0, 48000 + ) +{ + PA_ADD_OPTION(GAME_TO_HOME_DELAY1); + PA_ADD_STATIC(m_start_game_timings); + PA_ADD_OPTION(START_GAME_MASH0); + PA_ADD_OPTION(START_GAME_WAIT0); + PA_ADD_OPTION(ENTER_GAME_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + PA_ADD_OPTION(m_advanced_options); + PA_ADD_OPTION(RAID_SPAWN_DELAY0); + PA_ADD_OPTION(SHINY_SOUND_THRESHOLD2); + PA_ADD_OPTION(SHINY_SOUND_LOW_FREQUENCY); + PA_ADD_OPTION(LETS_GO_KILL_SOUND_THRESHOLD); + PA_ADD_OPTION(LETS_GO_KILL_SOUND_LOW_FREQUENCY); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonSV:GlobalSettings", + STRING_POKEMON + " SV", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/PokemonSettings.md", + "Global " + STRING_POKEMON + " Scarlet and Violet Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.h b/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.h index 5c071e8577..0242238ea2 100644 --- a/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.h +++ b/SerialPrograms/Source/PokemonSV/PokemonSV_Settings.h @@ -1,62 +1,62 @@ -/* Pokemon SV Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_Settings_H -#define PokemonAutomation_PokemonSV_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_menu_navigation; - MillisecondsOption GAME_TO_HOME_DELAY1; - - SectionDividerOption m_start_game_timings; - MillisecondsOption START_GAME_MASH0; - MillisecondsOption START_GAME_WAIT0; - MillisecondsOption ENTER_GAME_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_advanced_options; - MillisecondsOption RAID_SPAWN_DELAY0; - FloatingPointOption SHINY_SOUND_THRESHOLD2; - FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; - FloatingPointOption LETS_GO_KILL_SOUND_THRESHOLD; - FloatingPointOption LETS_GO_KILL_SOUND_LOW_FREQUENCY; -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon SV Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_Settings_H +#define PokemonAutomation_PokemonSV_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_menu_navigation; + MillisecondsOption GAME_TO_HOME_DELAY1; + + SectionDividerOption m_start_game_timings; + MillisecondsOption START_GAME_MASH0; + MillisecondsOption START_GAME_WAIT0; + MillisecondsOption ENTER_GAME_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_advanced_options; + MillisecondsOption RAID_SPAWN_DELAY0; + FloatingPointOption SHINY_SOUND_THRESHOLD2; + FloatingPointOption SHINY_SOUND_LOW_FREQUENCY; + FloatingPointOption LETS_GO_KILL_SOUND_THRESHOLD; + FloatingPointOption LETS_GO_KILL_SOUND_LOW_FREQUENCY; +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp index 1cddcfabb2..780f2f345d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.cpp @@ -1,809 +1,809 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStory_Segment_00.h" -#include "PokemonSV_AutoStory_Segment_01.h" -#include "PokemonSV_AutoStory_Segment_02.h" -#include "PokemonSV_AutoStory_Segment_03.h" -#include "PokemonSV_AutoStory_Segment_04.h" -#include "PokemonSV_AutoStory_Segment_05.h" -#include "PokemonSV_AutoStory_Segment_06.h" -#include "PokemonSV_AutoStory_Segment_07.h" -#include "PokemonSV_AutoStory_Segment_08.h" -#include "PokemonSV_AutoStory_Segment_09.h" -#include "PokemonSV_AutoStory_Segment_10.h" -#include "PokemonSV_AutoStory_Segment_11.h" -#include "PokemonSV_AutoStory_Segment_12.h" -#include "PokemonSV_AutoStory_Segment_13.h" -#include "PokemonSV_AutoStory_Segment_14.h" -#include "PokemonSV_AutoStory_Segment_15.h" -#include "PokemonSV_AutoStory_Segment_16.h" -#include "PokemonSV_AutoStory_Segment_17.h" -#include "PokemonSV_AutoStory_Segment_18.h" -#include "PokemonSV_AutoStory_Segment_19.h" -#include "PokemonSV_AutoStory_Segment_20.h" -#include "PokemonSV_AutoStory_Segment_21.h" -#include "PokemonSV_AutoStory_Segment_22.h" -#include "PokemonSV_AutoStory_Segment_23.h" -#include "PokemonSV_AutoStory_Segment_24.h" -#include "PokemonSV_AutoStory.h" - -#include -using std::cout; -using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -static constexpr size_t INDEX_OF_LAST_TUTORIAL_SEGMENT = 9; - - -std::vector> make_autoStory_segment_list(){ - std::vector> segment_list; - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - segment_list.emplace_back(std::make_unique()); - // segment_list.emplace_back(std::make_unique()); - // segment_list.emplace_back(std::make_unique()); - // segment_list.emplace_back(std::make_unique()); - - return segment_list; -}; - -const std::vector>& ALL_AUTO_STORY_SEGMENT_LIST(){ - static std::vector> segment_list = make_autoStory_segment_list(); - return segment_list; -} - - -StringSelectDatabase make_all_segments_database(){ - StringSelectDatabase ret; - int index_num = 0; - for (const auto& segment : ALL_AUTO_STORY_SEGMENT_LIST()){ - ret.add_entry(StringSelectEntry(std::to_string(index_num), segment->name())); - index_num++; - } - return ret; -} -const StringSelectDatabase& ALL_SEGMENTS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_all_segments_database(); - return database; -} - -StringSelectDatabase make_tutorial_segments_database(){ - StringSelectDatabase ret; - const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); - size_t start = 0; - size_t end = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; - for (size_t i = start; i < end; i++){ - const auto& segment = all_segments[i]; - ret.add_entry(segment); - } - return ret; -} - -const StringSelectDatabase& TUTORIAL_SEGMENTS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_tutorial_segments_database(); - return database; -} - -StringSelectDatabase make_mainstory_segments_database(){ - StringSelectDatabase ret; - const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); - size_t start = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; - size_t end = all_segments.case_list().size(); - for (size_t i = start; i < end; i++){ - const auto& segment = all_segments[i]; - ret.add_entry(segment); - } - return ret; -} - -const StringSelectDatabase& MAINSTORY_SEGMENTS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_mainstory_segments_database(); - return database; -} - - -AutoStory_Descriptor::AutoStory_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:AutoStory", - STRING_POKEMON + " SV", "Auto Story", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoStory.md", - "Progress through the mainstory of SV.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - -std::unique_ptr AutoStory_Descriptor::make_stats() const{ - return std::unique_ptr(new AutoStoryStats()); -} - - - -AutoStory::~AutoStory(){ - STARTPOINT_TUTORIAL.remove_listener(*this); - ENDPOINT_TUTORIAL.remove_listener(*this); -} - -AutoStory::AutoStory() - : LANGUAGE( - "Game Language:", - PokemonSwSh::IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , STORY_SECTION( - "Story Section:", - { - {StorySection::TUTORIAL, "tutorial", "Tutorial"}, - {StorySection::MAIN_STORY, "main-story", "Main Story"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StorySection::TUTORIAL - ) - , STARTPOINT_TUTORIAL( - "Start Point:
Program will start with this segment.", - TUTORIAL_SEGMENTS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - "0" - ) - , ENDPOINT_TUTORIAL( - "End Point:
Program will stop after completing this segment.", - TUTORIAL_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "9" - ) - , STARTPOINT_MAINSTORY( - "Start Point:
Program will start with this segment.", - MAINSTORY_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "10" - ) - , ENDPOINT_MAINSTORY( - "End Point:
Program will stop after completing this segment.", - MAINSTORY_SEGMENTS_SELECT_DATABASE(), - LockMode::UNLOCK_WHILE_RUNNING, - "10" - ) - , MAINSTORY_NOTE{ - "Ensure you have a level 100 Gardevoir with the moves in the following order: Moonblast, Dazzling Gleam, Psychic, Mystical Fire.
" - "Also, make sure you have two other strong pokemon (e.g. level 100 Talonflames)
" - "Refer to the documentation on github for more details." - } - , START_DESCRIPTION( - "" - ) - , END_DESCRIPTION( - "" - ) - , STARTERCHOICE( - "Starter " + STRING_POKEMON + ":", - { - {StarterChoice::SPRIGATITO, "sprigatito", "Sprigatito (Grass)"}, - {StarterChoice::FUECOCO, "fuecoco", "Fuecoco (Fire)"}, - {StarterChoice::QUAXLY, "quaxly", "Quaxly (Water)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StarterChoice::FUECOCO - ) - , GO_HOME_WHEN_DONE(true) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(30)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: (developer only)" - ) - , m_advanced_options_end( - "" - ) - , CHANGE_SETTINGS( - "Change settings at Program Start:
" - "This is to ensure the program has the correct settings, particularly with Autosave turned off.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , ENABLE_TEST_CHECKPOINTS( - "TEST: test_checkpoints():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , START_CHECKPOINT( - "--Start checkpoint:
Start testing with this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , END_CHECKPOINT( - "--End checkpoint:
Stop testing when done this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 11 - ) - , LOOP_CHECKPOINT( - "--Loop checkpoints:
Loop the checkpoints from \"Start loop\" to \"End loop\", inclusive. Loop these checkpoints this number of times.", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 1 - ) - , START_LOOP( - "--Start loop:
Start looping with this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , END_LOOP( - "--End loop:
Stop looping when done this checkpoint number.", - LockMode::UNLOCK_WHILE_RUNNING, - 11 - ) - , ENABLE_TEST_REALIGN( - "TEST: realign_player():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , REALIGN_MODE( - "--REALIGN_MODE:", - { - {PlayerRealignMode::REALIGN_NEW_MARKER, "realign_new", "Realign New Marker"}, - {PlayerRealignMode::REALIGN_NO_MARKER, "realign_no", "Realign No Marker"}, - {PlayerRealignMode::REALIGN_OLD_MARKER, "realign_old", "Realign Old Marker"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - PlayerRealignMode::REALIGN_NEW_MARKER - ) - , X_REALIGN( - "--X_REALIGN:
x = 0 : left, x = 128 : neutral, x = 255 : right.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , Y_REALIGN( - "--Y_REALIGN:
y = 0 : up, y = 128 : neutral, y = 255 : down.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , REALIGN_DURATION( - "--REALIGN_DURATION", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , ENABLE_MISC_TEST( - "TEST: Miscellaneous test code:", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , FORWARD_TICKS( - "--FORWARD_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , TEST_PBF_LEFT_JOYSTICK( - "TEST: pbf_move_left_joystick():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , X_MOVE( - "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , Y_MOVE( - "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , HOLD_TICKS( - "--HOLD_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , RELEASE_TICKS( - "--RELEASE_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , TEST_PBF_LEFT_JOYSTICK2( - "TEST2: pbf_move_left_joystick():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , X_MOVE2( - "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , Y_MOVE2( - "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", - LockMode::UNLOCK_WHILE_RUNNING, - 128 - ) - , HOLD_TICKS2( - "--HOLD_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , RELEASE_TICKS2( - "--RELEASE_TICKS:", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) - , TEST_CURRENT_DIRECTION( - "TEST: get_current_direction():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , TEST_CHANGE_DIRECTION( - "TEST: change_direction():", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , DIR_RADIANS( - "direction in radians", - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) -{ - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(m_advanced_options); - PA_ADD_OPTION(CHANGE_SETTINGS); - - PA_ADD_OPTION(TEST_CURRENT_DIRECTION); - PA_ADD_OPTION(TEST_CHANGE_DIRECTION); - PA_ADD_OPTION(DIR_RADIANS); - - PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK); - PA_ADD_OPTION(X_MOVE); - PA_ADD_OPTION(Y_MOVE); - PA_ADD_OPTION(HOLD_TICKS); - PA_ADD_OPTION(RELEASE_TICKS); - - PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK2); - PA_ADD_OPTION(X_MOVE2); - PA_ADD_OPTION(Y_MOVE2); - PA_ADD_OPTION(HOLD_TICKS2); - PA_ADD_OPTION(RELEASE_TICKS2); - - PA_ADD_OPTION(ENABLE_TEST_CHECKPOINTS); - PA_ADD_OPTION(START_CHECKPOINT); - PA_ADD_OPTION(END_CHECKPOINT); - PA_ADD_OPTION(LOOP_CHECKPOINT); - PA_ADD_OPTION(START_LOOP); - PA_ADD_OPTION(END_LOOP); - - // PA_ADD_OPTION(ENABLE_TEST_REALIGN); - // PA_ADD_OPTION(REALIGN_MODE); - // PA_ADD_OPTION(X_REALIGN); - // PA_ADD_OPTION(Y_REALIGN); - // PA_ADD_OPTION(REALIGN_DURATION); - - PA_ADD_OPTION(ENABLE_MISC_TEST); - // PA_ADD_OPTION(FORWARD_TICKS); - PA_ADD_OPTION(m_advanced_options_end); - } - - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(STORY_SECTION); - PA_ADD_OPTION(STARTPOINT_TUTORIAL); - PA_ADD_OPTION(MAINSTORY_NOTE); - PA_ADD_OPTION(STARTPOINT_MAINSTORY); - PA_ADD_OPTION(START_DESCRIPTION); - PA_ADD_OPTION(ENDPOINT_TUTORIAL); - PA_ADD_OPTION(ENDPOINT_MAINSTORY); - PA_ADD_OPTION(END_DESCRIPTION); - PA_ADD_OPTION(STARTERCHOICE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); - - - AutoStory::on_config_value_changed(this); - - STORY_SECTION.add_listener(*this); - STARTPOINT_TUTORIAL.add_listener(*this); - ENDPOINT_TUTORIAL.add_listener(*this); - STARTPOINT_MAINSTORY.add_listener(*this); - ENDPOINT_MAINSTORY.add_listener(*this); - ENABLE_TEST_CHECKPOINTS.add_listener(*this); - ENABLE_TEST_REALIGN.add_listener(*this); - ENABLE_MISC_TEST.add_listener(*this); - TEST_PBF_LEFT_JOYSTICK.add_listener(*this); - TEST_PBF_LEFT_JOYSTICK2.add_listener(*this); - TEST_CURRENT_DIRECTION.add_listener(*this); - TEST_CHANGE_DIRECTION.add_listener(*this); -} - -void AutoStory::on_config_value_changed(void* object){ - ConfigOptionState state = (STARTPOINT_TUTORIAL.index() <= 1) - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN; - STARTERCHOICE.set_visibility(state); - - if (STORY_SECTION == StorySection::TUTORIAL){ - STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); - ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); - - STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); - ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); - ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); - - STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); - ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); - } - - MAINSTORY_NOTE.set_visibility(STORY_SECTION == StorySection::TUTORIAL ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); - START_DESCRIPTION.set_text(start_segment_description()); - END_DESCRIPTION.set_text(end_segment_description()); - - if (ENABLE_TEST_CHECKPOINTS){ - START_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); - END_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); - LOOP_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); - START_LOOP.set_visibility(ConfigOptionState::ENABLED); - END_LOOP.set_visibility(ConfigOptionState::ENABLED); - }else{ - START_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); - END_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); - LOOP_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); - START_LOOP.set_visibility(ConfigOptionState::DISABLED); - END_LOOP.set_visibility(ConfigOptionState::DISABLED); - } - - if (ENABLE_TEST_REALIGN){ - REALIGN_MODE.set_visibility(ConfigOptionState::ENABLED); - X_REALIGN.set_visibility(ConfigOptionState::ENABLED); - Y_REALIGN.set_visibility(ConfigOptionState::ENABLED); - REALIGN_DURATION.set_visibility(ConfigOptionState::ENABLED); - }else{ - REALIGN_MODE.set_visibility(ConfigOptionState::DISABLED); - X_REALIGN.set_visibility(ConfigOptionState::DISABLED); - Y_REALIGN.set_visibility(ConfigOptionState::DISABLED); - REALIGN_DURATION.set_visibility(ConfigOptionState::DISABLED); - } - - if (ENABLE_MISC_TEST){ - FORWARD_TICKS.set_visibility(ConfigOptionState::ENABLED); - }else{ - FORWARD_TICKS.set_visibility(ConfigOptionState::DISABLED); - } - - if (TEST_PBF_LEFT_JOYSTICK){ - X_MOVE.set_visibility(ConfigOptionState::ENABLED); - Y_MOVE.set_visibility(ConfigOptionState::ENABLED); - HOLD_TICKS.set_visibility(ConfigOptionState::ENABLED); - RELEASE_TICKS.set_visibility(ConfigOptionState::ENABLED); - }else{ - X_MOVE.set_visibility(ConfigOptionState::DISABLED); - Y_MOVE.set_visibility(ConfigOptionState::DISABLED); - HOLD_TICKS.set_visibility(ConfigOptionState::DISABLED); - RELEASE_TICKS.set_visibility(ConfigOptionState::DISABLED); - } - - if (TEST_PBF_LEFT_JOYSTICK2){ - X_MOVE2.set_visibility(ConfigOptionState::ENABLED); - Y_MOVE2.set_visibility(ConfigOptionState::ENABLED); - HOLD_TICKS2.set_visibility(ConfigOptionState::ENABLED); - RELEASE_TICKS2.set_visibility(ConfigOptionState::ENABLED); - }else{ - X_MOVE2.set_visibility(ConfigOptionState::DISABLED); - Y_MOVE2.set_visibility(ConfigOptionState::DISABLED); - HOLD_TICKS2.set_visibility(ConfigOptionState::DISABLED); - RELEASE_TICKS2.set_visibility(ConfigOptionState::DISABLED); - } - - - if (TEST_CHANGE_DIRECTION){ - DIR_RADIANS.set_visibility(ConfigOptionState::ENABLED); - }else{ - DIR_RADIANS.set_visibility(ConfigOptionState::DISABLED); - } - - -} - - - - - - -void AutoStory::test_checkpoints( - SingleSwitchProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - int start, int end, - int loop, int start_loop, int end_loop -){ - EventNotificationOption& notif_status_update = NOTIFICATION_STATUS_UPDATE; - Language language = LANGUAGE; - StarterChoice starter_choice = STARTERCHOICE; - std::vector> checkpoint_list; - checkpoint_list.push_back([&](){checkpoint_00(env, context);}); - checkpoint_list.push_back([&](){checkpoint_01(env, context, notif_status_update, language);}); - checkpoint_list.push_back([&](){checkpoint_02(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_03(env, context, notif_status_update, language, starter_choice);}); - checkpoint_list.push_back([&](){checkpoint_04(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_05(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_06(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_07(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_08(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_09(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_10(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_11(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_12(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_13(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_14(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_15(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_16(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_17(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_18(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_19(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_20(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_21(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_22(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_23(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_24(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_25(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_26(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_27(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_28(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_29(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_30(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_31(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_32(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_33(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_34(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_35(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_36(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_37(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_38(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_39(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_40(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_41(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_42(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_43(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_44(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_45(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_46(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_47(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_48(env, context, notif_status_update);}); - checkpoint_list.push_back([&](){checkpoint_49(env, context, notif_status_update);}); - - for (int checkpoint = start; checkpoint <= end; checkpoint++){ - if (checkpoint == 0){ - stream.log("checkpoint_0"); - checkpoint_list[checkpoint](); - continue; - } - bool has_minimap = true; - if (checkpoint < 3){ - has_minimap = false; - } - - const size_t DIGITS = 3; - std::string number = std::to_string(checkpoint); - if (number.size() < DIGITS){ - number = std::string(DIGITS - number.size(), '0') + number; - } - if (checkpoint >= start_loop && checkpoint <= end_loop){ - for (int i = 0; i < loop; i++){ - if (i > 0){ - try { - reset_game(env.program_info(), env.console, context); - enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); - // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 5 seconds."); - context.wait_for(Milliseconds(5 * 1000)); - }catch(...){ - // try one more time - reset_game(env.program_info(), env.console, context); - enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); - // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 5 seconds."); - context.wait_for(Milliseconds(5 * 1000)); - - } - } - stream.log("checkpoint_" + number + ": loop " + std::to_string(i)); - checkpoint_list[checkpoint](); - } - }else{ - stream.log("checkpoint_" + number + "."); - checkpoint_list[checkpoint](); - } - - } - -} - -std::string AutoStory::start_segment_description(){ - size_t segment_index = 0; - if (STORY_SECTION == StorySection::TUTORIAL){ - segment_index = STARTPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - segment_index = STARTPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); - } - return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->start_text(); -} - -std::string AutoStory::end_segment_description(){ - size_t segment_index = 0; - if (STORY_SECTION == StorySection::TUTORIAL){ - segment_index = ENDPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - segment_index = ENDPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); - } - return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->end_text(); -} - -size_t AutoStory::get_start_segment_index(){ - size_t start = 0; - - if (STORY_SECTION == StorySection::TUTORIAL){ - start = STARTPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - start = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + STARTPOINT_MAINSTORY.index(); - } - - return start; -} - -size_t AutoStory::get_end_segment_index(){ - size_t end = 0; - - if (STORY_SECTION == StorySection::TUTORIAL){ - end = ENDPOINT_TUTORIAL.index(); - }else if (STORY_SECTION == StorySection::MAIN_STORY){ - end = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + ENDPOINT_MAINSTORY.index(); - } - - return end; -} - - -void AutoStory::run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AutoStoryOptions options{ - LANGUAGE, - STARTERCHOICE, - NOTIFICATION_STATUS_UPDATE - }; - - for (size_t segment_index = get_start_segment_index(); segment_index <= get_end_segment_index(); segment_index++){ - ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->run_segment(env, context, options); - } -} - -void AutoStory::test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (TEST_CURRENT_DIRECTION){ - DirectionDetector direction; - // direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); - VideoSnapshot snapshot = env.console.video().snapshot(); - env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); - return; - } - - if (TEST_CHANGE_DIRECTION){ - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); - // VideoSnapshot snapshot = env.console.video().snapshot(); - // env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); - return; - } - - if (TEST_PBF_LEFT_JOYSTICK){ - pbf_move_left_joystick(context, X_MOVE, Y_MOVE, HOLD_TICKS, RELEASE_TICKS); - return; - } - - if (TEST_PBF_LEFT_JOYSTICK2){ - pbf_move_left_joystick(context, X_MOVE2, Y_MOVE2, HOLD_TICKS2, RELEASE_TICKS2); - return; - } - - if (ENABLE_TEST_CHECKPOINTS){ - // test individual checkpoints - test_checkpoints(env, env.console, context, START_CHECKPOINT, END_CHECKPOINT, LOOP_CHECKPOINT, START_LOOP, END_LOOP); - return; - } - - - if (ENABLE_TEST_REALIGN){ - // clear realign marker - // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 128, 0); - realign_player(env.program_info(), env.console, context, REALIGN_MODE, X_REALIGN, Y_REALIGN, REALIGN_DURATION); - return; - } - - if (ENABLE_MISC_TEST){ - // walk_forward_while_clear_front_path(env.program_info(), env.console, context, FORWARD_TICKS); - - // overworld_navigation(env.program_info(), env.console, context, - // NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, - // 128, 0, 60, 10, false); - - DirectionDetector direction; - - return; - } - - // context.wait_for(Milliseconds(1000000)); - - -} - -void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - // AutoStoryStats& stats = env.current_stats(); - - - // test code - if (ENABLE_TEST_CHECKPOINTS || ENABLE_TEST_REALIGN || ENABLE_MISC_TEST || TEST_PBF_LEFT_JOYSTICK || TEST_PBF_LEFT_JOYSTICK2 || TEST_CHANGE_DIRECTION || TEST_CURRENT_DIRECTION){ - test_code(env, context); - return; - } - - // Connect controller - pbf_press_button(context, BUTTON_L, 20, 20); - - // Set settings. to ensure autosave is off. - if (CHANGE_SETTINGS){ - change_settings_prior_to_autostory(env, context, get_start_segment_index(), LANGUAGE); - } - - run_autostory(env, context); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStory_Segment_00.h" +#include "PokemonSV_AutoStory_Segment_01.h" +#include "PokemonSV_AutoStory_Segment_02.h" +#include "PokemonSV_AutoStory_Segment_03.h" +#include "PokemonSV_AutoStory_Segment_04.h" +#include "PokemonSV_AutoStory_Segment_05.h" +#include "PokemonSV_AutoStory_Segment_06.h" +#include "PokemonSV_AutoStory_Segment_07.h" +#include "PokemonSV_AutoStory_Segment_08.h" +#include "PokemonSV_AutoStory_Segment_09.h" +#include "PokemonSV_AutoStory_Segment_10.h" +#include "PokemonSV_AutoStory_Segment_11.h" +#include "PokemonSV_AutoStory_Segment_12.h" +#include "PokemonSV_AutoStory_Segment_13.h" +#include "PokemonSV_AutoStory_Segment_14.h" +#include "PokemonSV_AutoStory_Segment_15.h" +#include "PokemonSV_AutoStory_Segment_16.h" +#include "PokemonSV_AutoStory_Segment_17.h" +#include "PokemonSV_AutoStory_Segment_18.h" +#include "PokemonSV_AutoStory_Segment_19.h" +#include "PokemonSV_AutoStory_Segment_20.h" +#include "PokemonSV_AutoStory_Segment_21.h" +#include "PokemonSV_AutoStory_Segment_22.h" +#include "PokemonSV_AutoStory_Segment_23.h" +#include "PokemonSV_AutoStory_Segment_24.h" +#include "PokemonSV_AutoStory.h" + +#include +using std::cout; +using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +static constexpr size_t INDEX_OF_LAST_TUTORIAL_SEGMENT = 9; + + +std::vector> make_autoStory_segment_list(){ + std::vector> segment_list; + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + segment_list.emplace_back(std::make_unique()); + // segment_list.emplace_back(std::make_unique()); + // segment_list.emplace_back(std::make_unique()); + // segment_list.emplace_back(std::make_unique()); + + return segment_list; +}; + +const std::vector>& ALL_AUTO_STORY_SEGMENT_LIST(){ + static std::vector> segment_list = make_autoStory_segment_list(); + return segment_list; +} + + +StringSelectDatabase make_all_segments_database(){ + StringSelectDatabase ret; + int index_num = 0; + for (const auto& segment : ALL_AUTO_STORY_SEGMENT_LIST()){ + ret.add_entry(StringSelectEntry(std::to_string(index_num), segment->name())); + index_num++; + } + return ret; +} +const StringSelectDatabase& ALL_SEGMENTS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_all_segments_database(); + return database; +} + +StringSelectDatabase make_tutorial_segments_database(){ + StringSelectDatabase ret; + const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); + size_t start = 0; + size_t end = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; + for (size_t i = start; i < end; i++){ + const auto& segment = all_segments[i]; + ret.add_entry(segment); + } + return ret; +} + +const StringSelectDatabase& TUTORIAL_SEGMENTS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_tutorial_segments_database(); + return database; +} + +StringSelectDatabase make_mainstory_segments_database(){ + StringSelectDatabase ret; + const StringSelectDatabase& all_segments = ALL_SEGMENTS_SELECT_DATABASE(); + size_t start = INDEX_OF_LAST_TUTORIAL_SEGMENT + 1; + size_t end = all_segments.case_list().size(); + for (size_t i = start; i < end; i++){ + const auto& segment = all_segments[i]; + ret.add_entry(segment); + } + return ret; +} + +const StringSelectDatabase& MAINSTORY_SEGMENTS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_mainstory_segments_database(); + return database; +} + + +AutoStory_Descriptor::AutoStory_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:AutoStory", + STRING_POKEMON + " SV", "Auto Story", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoStory.md", + "Progress through the mainstory of SV.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + +std::unique_ptr AutoStory_Descriptor::make_stats() const{ + return std::unique_ptr(new AutoStoryStats()); +} + + + +AutoStory::~AutoStory(){ + STARTPOINT_TUTORIAL.remove_listener(*this); + ENDPOINT_TUTORIAL.remove_listener(*this); +} + +AutoStory::AutoStory() + : LANGUAGE( + "Game Language:", + PokemonSwSh::IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , STORY_SECTION( + "Story Section:", + { + {StorySection::TUTORIAL, "tutorial", "Tutorial"}, + {StorySection::MAIN_STORY, "main-story", "Main Story"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StorySection::TUTORIAL + ) + , STARTPOINT_TUTORIAL( + "Start Point:
Program will start with this segment.", + TUTORIAL_SEGMENTS_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + "0" + ) + , ENDPOINT_TUTORIAL( + "End Point:
Program will stop after completing this segment.", + TUTORIAL_SEGMENTS_SELECT_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + "9" + ) + , STARTPOINT_MAINSTORY( + "Start Point:
Program will start with this segment.", + MAINSTORY_SEGMENTS_SELECT_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + "10" + ) + , ENDPOINT_MAINSTORY( + "End Point:
Program will stop after completing this segment.", + MAINSTORY_SEGMENTS_SELECT_DATABASE(), + LockMode::UNLOCK_WHILE_RUNNING, + "10" + ) + , MAINSTORY_NOTE{ + "Ensure you have a level 100 Gardevoir with the moves in the following order: Moonblast, Dazzling Gleam, Psychic, Mystical Fire.
" + "Also, make sure you have two other strong pokemon (e.g. level 100 Talonflames)
" + "Refer to the documentation on github for more details." + } + , START_DESCRIPTION( + "" + ) + , END_DESCRIPTION( + "" + ) + , STARTERCHOICE( + "Starter " + STRING_POKEMON + ":", + { + {StarterChoice::SPRIGATITO, "sprigatito", "Sprigatito (Grass)"}, + {StarterChoice::FUECOCO, "fuecoco", "Fuecoco (Fire)"}, + {StarterChoice::QUAXLY, "quaxly", "Quaxly (Water)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StarterChoice::FUECOCO + ) + , GO_HOME_WHEN_DONE(true) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(30)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: (developer only)" + ) + , m_advanced_options_end( + "" + ) + , CHANGE_SETTINGS( + "Change settings at Program Start:
" + "This is to ensure the program has the correct settings, particularly with Autosave turned off.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , ENABLE_TEST_CHECKPOINTS( + "TEST: test_checkpoints():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , START_CHECKPOINT( + "--Start checkpoint:
Start testing with this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , END_CHECKPOINT( + "--End checkpoint:
Stop testing when done this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 11 + ) + , LOOP_CHECKPOINT( + "--Loop checkpoints:
Loop the checkpoints from \"Start loop\" to \"End loop\", inclusive. Loop these checkpoints this number of times.", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 1 + ) + , START_LOOP( + "--Start loop:
Start looping with this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , END_LOOP( + "--End loop:
Stop looping when done this checkpoint number.", + LockMode::UNLOCK_WHILE_RUNNING, + 11 + ) + , ENABLE_TEST_REALIGN( + "TEST: realign_player():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , REALIGN_MODE( + "--REALIGN_MODE:", + { + {PlayerRealignMode::REALIGN_NEW_MARKER, "realign_new", "Realign New Marker"}, + {PlayerRealignMode::REALIGN_NO_MARKER, "realign_no", "Realign No Marker"}, + {PlayerRealignMode::REALIGN_OLD_MARKER, "realign_old", "Realign Old Marker"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + PlayerRealignMode::REALIGN_NEW_MARKER + ) + , X_REALIGN( + "--X_REALIGN:
x = 0 : left, x = 128 : neutral, x = 255 : right.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , Y_REALIGN( + "--Y_REALIGN:
y = 0 : up, y = 128 : neutral, y = 255 : down.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , REALIGN_DURATION( + "--REALIGN_DURATION", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , ENABLE_MISC_TEST( + "TEST: Miscellaneous test code:", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , FORWARD_TICKS( + "--FORWARD_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , TEST_PBF_LEFT_JOYSTICK( + "TEST: pbf_move_left_joystick():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , X_MOVE( + "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , Y_MOVE( + "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , HOLD_TICKS( + "--HOLD_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , RELEASE_TICKS( + "--RELEASE_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , TEST_PBF_LEFT_JOYSTICK2( + "TEST2: pbf_move_left_joystick():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , X_MOVE2( + "--X_MOVE:
x = 0 : left, x = 128 : neutral, x = 255 : right.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , Y_MOVE2( + "--Y_MOVE:
y = 0 : up, y = 128 : neutral, y = 255 : down.", + LockMode::UNLOCK_WHILE_RUNNING, + 128 + ) + , HOLD_TICKS2( + "--HOLD_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , RELEASE_TICKS2( + "--RELEASE_TICKS:", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) + , TEST_CURRENT_DIRECTION( + "TEST: get_current_direction():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , TEST_CHANGE_DIRECTION( + "TEST: change_direction():", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , DIR_RADIANS( + "direction in radians", + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) +{ + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(m_advanced_options); + PA_ADD_OPTION(CHANGE_SETTINGS); + + PA_ADD_OPTION(TEST_CURRENT_DIRECTION); + PA_ADD_OPTION(TEST_CHANGE_DIRECTION); + PA_ADD_OPTION(DIR_RADIANS); + + PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK); + PA_ADD_OPTION(X_MOVE); + PA_ADD_OPTION(Y_MOVE); + PA_ADD_OPTION(HOLD_TICKS); + PA_ADD_OPTION(RELEASE_TICKS); + + PA_ADD_OPTION(TEST_PBF_LEFT_JOYSTICK2); + PA_ADD_OPTION(X_MOVE2); + PA_ADD_OPTION(Y_MOVE2); + PA_ADD_OPTION(HOLD_TICKS2); + PA_ADD_OPTION(RELEASE_TICKS2); + + PA_ADD_OPTION(ENABLE_TEST_CHECKPOINTS); + PA_ADD_OPTION(START_CHECKPOINT); + PA_ADD_OPTION(END_CHECKPOINT); + PA_ADD_OPTION(LOOP_CHECKPOINT); + PA_ADD_OPTION(START_LOOP); + PA_ADD_OPTION(END_LOOP); + + // PA_ADD_OPTION(ENABLE_TEST_REALIGN); + // PA_ADD_OPTION(REALIGN_MODE); + // PA_ADD_OPTION(X_REALIGN); + // PA_ADD_OPTION(Y_REALIGN); + // PA_ADD_OPTION(REALIGN_DURATION); + + PA_ADD_OPTION(ENABLE_MISC_TEST); + // PA_ADD_OPTION(FORWARD_TICKS); + PA_ADD_OPTION(m_advanced_options_end); + } + + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(STORY_SECTION); + PA_ADD_OPTION(STARTPOINT_TUTORIAL); + PA_ADD_OPTION(MAINSTORY_NOTE); + PA_ADD_OPTION(STARTPOINT_MAINSTORY); + PA_ADD_OPTION(START_DESCRIPTION); + PA_ADD_OPTION(ENDPOINT_TUTORIAL); + PA_ADD_OPTION(ENDPOINT_MAINSTORY); + PA_ADD_OPTION(END_DESCRIPTION); + PA_ADD_OPTION(STARTERCHOICE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); + + + AutoStory::on_config_value_changed(this); + + STORY_SECTION.add_listener(*this); + STARTPOINT_TUTORIAL.add_listener(*this); + ENDPOINT_TUTORIAL.add_listener(*this); + STARTPOINT_MAINSTORY.add_listener(*this); + ENDPOINT_MAINSTORY.add_listener(*this); + ENABLE_TEST_CHECKPOINTS.add_listener(*this); + ENABLE_TEST_REALIGN.add_listener(*this); + ENABLE_MISC_TEST.add_listener(*this); + TEST_PBF_LEFT_JOYSTICK.add_listener(*this); + TEST_PBF_LEFT_JOYSTICK2.add_listener(*this); + TEST_CURRENT_DIRECTION.add_listener(*this); + TEST_CHANGE_DIRECTION.add_listener(*this); +} + +void AutoStory::on_config_value_changed(void* object){ + ConfigOptionState state = (STARTPOINT_TUTORIAL.index() <= 1) + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN; + STARTERCHOICE.set_visibility(state); + + if (STORY_SECTION == StorySection::TUTORIAL){ + STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); + ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::ENABLED); + + STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); + ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::HIDDEN); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + STARTPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); + ENDPOINT_TUTORIAL.set_visibility(ConfigOptionState::HIDDEN); + + STARTPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); + ENDPOINT_MAINSTORY.set_visibility(ConfigOptionState::ENABLED); + } + + MAINSTORY_NOTE.set_visibility(STORY_SECTION == StorySection::TUTORIAL ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); + START_DESCRIPTION.set_text(start_segment_description()); + END_DESCRIPTION.set_text(end_segment_description()); + + if (ENABLE_TEST_CHECKPOINTS){ + START_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); + END_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); + LOOP_CHECKPOINT.set_visibility(ConfigOptionState::ENABLED); + START_LOOP.set_visibility(ConfigOptionState::ENABLED); + END_LOOP.set_visibility(ConfigOptionState::ENABLED); + }else{ + START_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); + END_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); + LOOP_CHECKPOINT.set_visibility(ConfigOptionState::DISABLED); + START_LOOP.set_visibility(ConfigOptionState::DISABLED); + END_LOOP.set_visibility(ConfigOptionState::DISABLED); + } + + if (ENABLE_TEST_REALIGN){ + REALIGN_MODE.set_visibility(ConfigOptionState::ENABLED); + X_REALIGN.set_visibility(ConfigOptionState::ENABLED); + Y_REALIGN.set_visibility(ConfigOptionState::ENABLED); + REALIGN_DURATION.set_visibility(ConfigOptionState::ENABLED); + }else{ + REALIGN_MODE.set_visibility(ConfigOptionState::DISABLED); + X_REALIGN.set_visibility(ConfigOptionState::DISABLED); + Y_REALIGN.set_visibility(ConfigOptionState::DISABLED); + REALIGN_DURATION.set_visibility(ConfigOptionState::DISABLED); + } + + if (ENABLE_MISC_TEST){ + FORWARD_TICKS.set_visibility(ConfigOptionState::ENABLED); + }else{ + FORWARD_TICKS.set_visibility(ConfigOptionState::DISABLED); + } + + if (TEST_PBF_LEFT_JOYSTICK){ + X_MOVE.set_visibility(ConfigOptionState::ENABLED); + Y_MOVE.set_visibility(ConfigOptionState::ENABLED); + HOLD_TICKS.set_visibility(ConfigOptionState::ENABLED); + RELEASE_TICKS.set_visibility(ConfigOptionState::ENABLED); + }else{ + X_MOVE.set_visibility(ConfigOptionState::DISABLED); + Y_MOVE.set_visibility(ConfigOptionState::DISABLED); + HOLD_TICKS.set_visibility(ConfigOptionState::DISABLED); + RELEASE_TICKS.set_visibility(ConfigOptionState::DISABLED); + } + + if (TEST_PBF_LEFT_JOYSTICK2){ + X_MOVE2.set_visibility(ConfigOptionState::ENABLED); + Y_MOVE2.set_visibility(ConfigOptionState::ENABLED); + HOLD_TICKS2.set_visibility(ConfigOptionState::ENABLED); + RELEASE_TICKS2.set_visibility(ConfigOptionState::ENABLED); + }else{ + X_MOVE2.set_visibility(ConfigOptionState::DISABLED); + Y_MOVE2.set_visibility(ConfigOptionState::DISABLED); + HOLD_TICKS2.set_visibility(ConfigOptionState::DISABLED); + RELEASE_TICKS2.set_visibility(ConfigOptionState::DISABLED); + } + + + if (TEST_CHANGE_DIRECTION){ + DIR_RADIANS.set_visibility(ConfigOptionState::ENABLED); + }else{ + DIR_RADIANS.set_visibility(ConfigOptionState::DISABLED); + } + + +} + + + + + + +void AutoStory::test_checkpoints( + SingleSwitchProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + int start, int end, + int loop, int start_loop, int end_loop +){ + EventNotificationOption& notif_status_update = NOTIFICATION_STATUS_UPDATE; + Language language = LANGUAGE; + StarterChoice starter_choice = STARTERCHOICE; + std::vector> checkpoint_list; + checkpoint_list.push_back([&](){checkpoint_00(env, context);}); + checkpoint_list.push_back([&](){checkpoint_01(env, context, notif_status_update, language);}); + checkpoint_list.push_back([&](){checkpoint_02(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_03(env, context, notif_status_update, language, starter_choice);}); + checkpoint_list.push_back([&](){checkpoint_04(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_05(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_06(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_07(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_08(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_09(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_10(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_11(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_12(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_13(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_14(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_15(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_16(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_17(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_18(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_19(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_20(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_21(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_22(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_23(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_24(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_25(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_26(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_27(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_28(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_29(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_30(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_31(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_32(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_33(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_34(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_35(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_36(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_37(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_38(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_39(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_40(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_41(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_42(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_43(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_44(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_45(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_46(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_47(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_48(env, context, notif_status_update);}); + checkpoint_list.push_back([&](){checkpoint_49(env, context, notif_status_update);}); + + for (int checkpoint = start; checkpoint <= end; checkpoint++){ + if (checkpoint == 0){ + stream.log("checkpoint_0"); + checkpoint_list[checkpoint](); + continue; + } + bool has_minimap = true; + if (checkpoint < 3){ + has_minimap = false; + } + + const size_t DIGITS = 3; + std::string number = std::to_string(checkpoint); + if (number.size() < DIGITS){ + number = std::string(DIGITS - number.size(), '0') + number; + } + if (checkpoint >= start_loop && checkpoint <= end_loop){ + for (int i = 0; i < loop; i++){ + if (i > 0){ + try { + reset_game(env.program_info(), env.console, context); + enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); + // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 5 seconds."); + context.wait_for(Milliseconds(5 * 1000)); + }catch(...){ + // try one more time + reset_game(env.program_info(), env.console, context); + enter_menu_from_overworld(env.program_info(), env.console, context, -1, MenuSide::NONE, has_minimap); + // we wait 5 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 5 seconds."); + context.wait_for(Milliseconds(5 * 1000)); + + } + } + stream.log("checkpoint_" + number + ": loop " + std::to_string(i)); + checkpoint_list[checkpoint](); + } + }else{ + stream.log("checkpoint_" + number + "."); + checkpoint_list[checkpoint](); + } + + } + +} + +std::string AutoStory::start_segment_description(){ + size_t segment_index = 0; + if (STORY_SECTION == StorySection::TUTORIAL){ + segment_index = STARTPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + segment_index = STARTPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); + } + return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->start_text(); +} + +std::string AutoStory::end_segment_description(){ + size_t segment_index = 0; + if (STORY_SECTION == StorySection::TUTORIAL){ + segment_index = ENDPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + segment_index = ENDPOINT_MAINSTORY.index() + (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1); + } + return ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->end_text(); +} + +size_t AutoStory::get_start_segment_index(){ + size_t start = 0; + + if (STORY_SECTION == StorySection::TUTORIAL){ + start = STARTPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + start = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + STARTPOINT_MAINSTORY.index(); + } + + return start; +} + +size_t AutoStory::get_end_segment_index(){ + size_t end = 0; + + if (STORY_SECTION == StorySection::TUTORIAL){ + end = ENDPOINT_TUTORIAL.index(); + }else if (STORY_SECTION == StorySection::MAIN_STORY){ + end = (INDEX_OF_LAST_TUTORIAL_SEGMENT + 1) + ENDPOINT_MAINSTORY.index(); + } + + return end; +} + + +void AutoStory::run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AutoStoryOptions options{ + LANGUAGE, + STARTERCHOICE, + NOTIFICATION_STATUS_UPDATE + }; + + for (size_t segment_index = get_start_segment_index(); segment_index <= get_end_segment_index(); segment_index++){ + ALL_AUTO_STORY_SEGMENT_LIST()[segment_index]->run_segment(env, context, options); + } +} + +void AutoStory::test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (TEST_CURRENT_DIRECTION){ + DirectionDetector direction; + // direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); + VideoSnapshot snapshot = env.console.video().snapshot(); + env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); + return; + } + + if (TEST_CHANGE_DIRECTION){ + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, DIR_RADIANS); + // VideoSnapshot snapshot = env.console.video().snapshot(); + // env.console.log("current direction: " + std::to_string(direction.get_current_direction(env.console, snapshot))); + return; + } + + if (TEST_PBF_LEFT_JOYSTICK){ + pbf_move_left_joystick(context, X_MOVE, Y_MOVE, HOLD_TICKS, RELEASE_TICKS); + return; + } + + if (TEST_PBF_LEFT_JOYSTICK2){ + pbf_move_left_joystick(context, X_MOVE2, Y_MOVE2, HOLD_TICKS2, RELEASE_TICKS2); + return; + } + + if (ENABLE_TEST_CHECKPOINTS){ + // test individual checkpoints + test_checkpoints(env, env.console, context, START_CHECKPOINT, END_CHECKPOINT, LOOP_CHECKPOINT, START_LOOP, END_LOOP); + return; + } + + + if (ENABLE_TEST_REALIGN){ + // clear realign marker + // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 128, 0); + realign_player(env.program_info(), env.console, context, REALIGN_MODE, X_REALIGN, Y_REALIGN, REALIGN_DURATION); + return; + } + + if (ENABLE_MISC_TEST){ + // walk_forward_while_clear_front_path(env.program_info(), env.console, context, FORWARD_TICKS); + + // overworld_navigation(env.program_info(), env.console, context, + // NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, + // 128, 0, 60, 10, false); + + DirectionDetector direction; + + return; + } + + // context.wait_for(Milliseconds(1000000)); + + +} + +void AutoStory::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + // AutoStoryStats& stats = env.current_stats(); + + + // test code + if (ENABLE_TEST_CHECKPOINTS || ENABLE_TEST_REALIGN || ENABLE_MISC_TEST || TEST_PBF_LEFT_JOYSTICK || TEST_PBF_LEFT_JOYSTICK2 || TEST_CHANGE_DIRECTION || TEST_CURRENT_DIRECTION){ + test_code(env, context); + return; + } + + // Connect controller + pbf_press_button(context, BUTTON_L, 20, 20); + + // Set settings. to ensure autosave is off. + if (CHANGE_SETTINGS){ + change_settings_prior_to_autostory(env, context, get_start_segment_index(), LANGUAGE); + } + + run_autostory(env, context); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h index 1d3be15268..16964791c4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory.h @@ -1,137 +1,137 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_H -#define PokemonAutomation_PokemonSV_AutoStory_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AutoStory_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoStory_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ -public: - ~AutoStory(); - AutoStory(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - void test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // test the checkpoints from start to end, inclusive - // test each checkpoints "loop" number of times - void test_checkpoints( - SingleSwitchProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - int start, int end, - int loop, int start_loop, int end_loop - ); - - size_t get_start_segment_index(); - size_t get_end_segment_index(); - - void run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - virtual void on_config_value_changed(void* object) override; - - std::string start_segment_description(); - std::string end_segment_description(); - -private: - OCR::LanguageOCROption LANGUAGE; - - enum class StorySection{ - TUTORIAL, - MAIN_STORY, - }; - - EnumDropdownOption STORY_SECTION; - - StringSelectOption STARTPOINT_TUTORIAL; - StringSelectOption ENDPOINT_TUTORIAL; - - StringSelectOption STARTPOINT_MAINSTORY; - StringSelectOption ENDPOINT_MAINSTORY; - - StaticTextOption MAINSTORY_NOTE; - - StaticTextOption START_DESCRIPTION; - StaticTextOption END_DESCRIPTION; - - - EnumDropdownOption STARTERCHOICE; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SectionDividerOption m_advanced_options_end; - BooleanCheckBoxOption CHANGE_SETTINGS; - - BooleanCheckBoxOption ENABLE_TEST_CHECKPOINTS; - SimpleIntegerOption START_CHECKPOINT; - SimpleIntegerOption END_CHECKPOINT; - SimpleIntegerOption LOOP_CHECKPOINT; - SimpleIntegerOption START_LOOP; - SimpleIntegerOption END_LOOP; - - BooleanCheckBoxOption ENABLE_TEST_REALIGN; - EnumDropdownOption REALIGN_MODE; - SimpleIntegerOption X_REALIGN; - SimpleIntegerOption Y_REALIGN; - SimpleIntegerOption REALIGN_DURATION; - - BooleanCheckBoxOption ENABLE_MISC_TEST; - SimpleIntegerOption FORWARD_TICKS; - - BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK; - SimpleIntegerOption X_MOVE; - SimpleIntegerOption Y_MOVE; - SimpleIntegerOption HOLD_TICKS; - SimpleIntegerOption RELEASE_TICKS; - - BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK2; - SimpleIntegerOption X_MOVE2; - SimpleIntegerOption Y_MOVE2; - SimpleIntegerOption HOLD_TICKS2; - SimpleIntegerOption RELEASE_TICKS2; - - BooleanCheckBoxOption TEST_CURRENT_DIRECTION; - BooleanCheckBoxOption TEST_CHANGE_DIRECTION; - FloatingPointOption DIR_RADIANS; -}; - - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_H +#define PokemonAutomation_PokemonSV_AutoStory_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AutoStory_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoStory_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class AutoStory : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + ~AutoStory(); + AutoStory(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + void test_code(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // test the checkpoints from start to end, inclusive + // test each checkpoints "loop" number of times + void test_checkpoints( + SingleSwitchProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + int start, int end, + int loop, int start_loop, int end_loop + ); + + size_t get_start_segment_index(); + size_t get_end_segment_index(); + + void run_autostory(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + virtual void on_config_value_changed(void* object) override; + + std::string start_segment_description(); + std::string end_segment_description(); + +private: + OCR::LanguageOCROption LANGUAGE; + + enum class StorySection{ + TUTORIAL, + MAIN_STORY, + }; + + EnumDropdownOption STORY_SECTION; + + StringSelectOption STARTPOINT_TUTORIAL; + StringSelectOption ENDPOINT_TUTORIAL; + + StringSelectOption STARTPOINT_MAINSTORY; + StringSelectOption ENDPOINT_MAINSTORY; + + StaticTextOption MAINSTORY_NOTE; + + StaticTextOption START_DESCRIPTION; + StaticTextOption END_DESCRIPTION; + + + EnumDropdownOption STARTERCHOICE; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SectionDividerOption m_advanced_options_end; + BooleanCheckBoxOption CHANGE_SETTINGS; + + BooleanCheckBoxOption ENABLE_TEST_CHECKPOINTS; + SimpleIntegerOption START_CHECKPOINT; + SimpleIntegerOption END_CHECKPOINT; + SimpleIntegerOption LOOP_CHECKPOINT; + SimpleIntegerOption START_LOOP; + SimpleIntegerOption END_LOOP; + + BooleanCheckBoxOption ENABLE_TEST_REALIGN; + EnumDropdownOption REALIGN_MODE; + SimpleIntegerOption X_REALIGN; + SimpleIntegerOption Y_REALIGN; + SimpleIntegerOption REALIGN_DURATION; + + BooleanCheckBoxOption ENABLE_MISC_TEST; + SimpleIntegerOption FORWARD_TICKS; + + BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK; + SimpleIntegerOption X_MOVE; + SimpleIntegerOption Y_MOVE; + SimpleIntegerOption HOLD_TICKS; + SimpleIntegerOption RELEASE_TICKS; + + BooleanCheckBoxOption TEST_PBF_LEFT_JOYSTICK2; + SimpleIntegerOption X_MOVE2; + SimpleIntegerOption Y_MOVE2; + SimpleIntegerOption HOLD_TICKS2; + SimpleIntegerOption RELEASE_TICKS2; + + BooleanCheckBoxOption TEST_CURRENT_DIRECTION; + BooleanCheckBoxOption TEST_CHANGE_DIRECTION; + FloatingPointOption DIR_RADIANS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp index 1b74969e3d..7176181b9e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.cpp @@ -1,1192 +1,1192 @@ -/* AutoStoryTools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/UnexpectedBattleException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonMovesReader.h" -#include "PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" -#include "PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" -#include "PokemonSV_AutoStoryTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -void run_battle_press_A( - VideoStream& stream, - ProControllerContext& context, - BattleStopCondition stop_condition, - std::vector enum_optional_callbacks, - bool detect_wipeout -){ - int16_t num_times_seen_overworld = 0; - size_t consecutive_move_select = 0; - while (true){ - NormalBattleMenuWatcher battle(COLOR_BLUE); - SwapMenuWatcher fainted(COLOR_PURPLE); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - AdvanceDialogWatcher dialog(COLOR_RED); - DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); - GradientArrowWatcher next_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); - MoveSelectWatcher move_select_menu(COLOR_YELLOW); - - std::vector callbacks; - // mandatory callbacks: Battle, Overworld, Advance Dialog, Swap menu, Move select - std::vector enum_all_callbacks{CallbackEnum::BATTLE, CallbackEnum::OVERWORLD, CallbackEnum::ADVANCE_DIALOG, CallbackEnum::SWAP_MENU, CallbackEnum::MOVE_SELECT}; // mandatory callbacks - enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together - for (const CallbackEnum& enum_callback : enum_all_callbacks){ - switch(enum_callback){ - case CallbackEnum::ADVANCE_DIALOG: - callbacks.emplace_back(dialog); - break; - case CallbackEnum::OVERWORLD: - callbacks.emplace_back(overworld); - break; - case CallbackEnum::DIALOG_ARROW: - callbacks.emplace_back(dialog_arrow); - break; - case CallbackEnum::BATTLE: - callbacks.emplace_back(battle); - break; - case CallbackEnum::GRADIENT_ARROW: - callbacks.emplace_back(next_pokemon); - break; - case CallbackEnum::SWAP_MENU: - callbacks.emplace_back(fainted); - break; - case CallbackEnum::MOVE_SELECT: - callbacks.emplace_back(move_select_menu); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback requested."); - } - } - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(90), - callbacks - ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Timed out. Did not detect expected stop condition.", - stream - ); - } - - CallbackEnum enum_callback = enum_all_callbacks[ret]; - switch (enum_callback){ - case CallbackEnum::BATTLE: // battle - stream.log("Detected battle menu."); - consecutive_move_select = 0; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::MOVE_SELECT: - stream.log("Detected move select. Spam first move"); - consecutive_move_select++; - select_top_move(stream, context, consecutive_move_select); - break; - case CallbackEnum::OVERWORLD: // overworld - stream.log("Detected overworld, battle over."); - num_times_seen_overworld++; - if (stop_condition == BattleStopCondition::STOP_OVERWORLD){ - return; - } - if(num_times_seen_overworld > 30){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Stuck in overworld. Did not detect expected stop condition.", - stream - ); - } - break; - case CallbackEnum::ADVANCE_DIALOG: // advance dialog - stream.log("Detected dialog."); - - if (detect_wipeout){ - context.wait_for_all_requests(); - WipeoutDetector wipeout; - VideoSnapshot screen = stream.video().snapshot(); - // dump_snapshot(console); - if (wipeout.detect(screen)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Detected wipeout. All pokemon fainted.", - stream - ); - } - } - - if (stop_condition == BattleStopCondition::STOP_DIALOG){ - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::DIALOG_ARROW: // dialog arrow - stream.log("run_battle_press_A: Detected dialog arrow."); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::GRADIENT_ARROW: - stream.log("run_battle_press_A: Detected prompt for bringing in next pokemon. Keep current pokemon."); - pbf_mash_button(context, BUTTON_B, 100); - break; - case CallbackEnum::SWAP_MENU: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_battle_press_A(): Lead pokemon fainted.", - stream - ); - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback triggered."); - - } - } -} - -void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select){ - if (consecutive_move_select > 3){ - // to handle case where move is disabled/out of PP/taunted - stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); - pbf_press_dpad(context, DPAD_DOWN, 20, 40); - } - pbf_mash_button(context, BUTTON_A, 100); - -} - -void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout){ - bool seen_tutorial = false; - while (true){ - TutorialWatcher tutorial; - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(seconds_timeout), - {tutorial} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: - stream.log("clear_tutorial: Detected tutorial screen."); - seen_tutorial = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - default: - stream.log("clear_tutorial: Timed out."); - if(!seen_tutorial){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "clear_tutorial(): Tutorial screen never detected.", - stream - ); - } - return; - } - } -} - -void clear_dialog(VideoStream& stream, ProControllerContext& context, - ClearDialogMode mode, uint16_t seconds_timeout, - std::vector enum_optional_callbacks -){ - bool seen_dialog = false; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "clear_dialog(): Failed to clear dialog after 3 minutes.", - stream - ); - } - - AdvanceDialogWatcher advance_dialog(COLOR_RED); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - PromptDialogWatcher prompt(COLOR_YELLOW); - WhiteButtonWatcher whitebutton(COLOR_GREEN, WhiteButton::ButtonA_DarkBackground, {0.725, 0.833, 0.024, 0.045}); // {0.650, 0.650, 0.140, 0.240} - DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); - NormalBattleMenuWatcher battle(COLOR_ORANGE); - TutorialWatcher tutorial(COLOR_BLUE); - DialogBoxWatcher black_dialog_box(COLOR_BLACK, true, std::chrono::milliseconds(250), DialogType::DIALOG_BLACK); - context.wait_for_all_requests(); - - std::vector callbacks; - std::vector enum_all_callbacks{CallbackEnum::ADVANCE_DIALOG}; // mandatory callbacks - enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together - for (const CallbackEnum& enum_callback : enum_all_callbacks){ - switch(enum_callback){ - case CallbackEnum::ADVANCE_DIALOG: - callbacks.emplace_back(advance_dialog); - break; - case CallbackEnum::OVERWORLD: - callbacks.emplace_back(overworld); - break; - case CallbackEnum::PROMPT_DIALOG: - callbacks.emplace_back(prompt); - break; - case CallbackEnum::WHITE_A_BUTTON: - callbacks.emplace_back(whitebutton); - break; - case CallbackEnum::DIALOG_ARROW: - callbacks.emplace_back(dialog_arrow); - break; - case CallbackEnum::BATTLE: - callbacks.emplace_back(battle); - break; - case CallbackEnum::TUTORIAL: - callbacks.emplace_back(tutorial); - break; - case CallbackEnum::BLACK_DIALOG_BOX: - callbacks.emplace_back(black_dialog_box); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback requested."); - } - } - - - int ret = wait_until( - stream, context, - std::chrono::seconds(seconds_timeout), - callbacks - ); - // int ret = run_until( - // console, context, - // [&](ProControllerContext& context){ - // for (size_t j = 0; j < seconds_timeout/3; j++){ - // pbf_press_button(context, BUTTON_A, 20, 3*TICKS_PER_SECOND-20); - // } - // }, - // {overworld, prompt, whitebutton, advance_dialog, battle} - // ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret < 0){ - stream.log("clear_dialog(): Timed out."); - if (seen_dialog && mode == ClearDialogMode::STOP_TIMEOUT){ - return; - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "clear_dialog(): Timed out. Did not detect dialog or did not detect the expected stop condition.", - stream - ); - } - - CallbackEnum enum_callback = enum_all_callbacks[ret]; - switch(enum_callback){ - case CallbackEnum::ADVANCE_DIALOG: - stream.log("clear_dialog: Detected advance dialog."); - seen_dialog = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::OVERWORLD: - stream.log("clear_dialog: Detected overworld."); - if (seen_dialog && mode == ClearDialogMode::STOP_OVERWORLD){ - return; - } - break; - case CallbackEnum::PROMPT_DIALOG: - stream.log("clear_dialog: Detected prompt."); - seen_dialog = true; - if (mode == ClearDialogMode::STOP_PROMPT){ - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::WHITE_A_BUTTON: - stream.log("clear_dialog: Detected white A button."); - seen_dialog = true; - if (mode == ClearDialogMode::STOP_WHITEBUTTON){ - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::DIALOG_ARROW: - stream.log("clear_dialog: Detected dialog arrow."); - seen_dialog = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::BATTLE: - stream.log("clear_dialog: Detected battle."); - if (mode == ClearDialogMode::STOP_BATTLE){ - return; - } - break; - case CallbackEnum::TUTORIAL: - stream.log("clear_dialog: Detected tutorial."); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case CallbackEnum::BLACK_DIALOG_BOX: - stream.log("clear_dialog: Detected black dialog box."); - seen_dialog = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback triggered."); - - } - - } -} - -bool confirm_marker_present( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -){ - while (true){ - DestinationMarkerWatcher marker(COLOR_RED, {0.815, 0.645, 0.180, 0.320}, true); - NormalBattleMenuWatcher battle(COLOR_BLUE); - - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - {marker, battle} - ); - switch (ret){ - case 0: // marker - stream.log("Confirmed that marker is still present."); - return true; - case 1: // battle - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "confirm_marker_present(): Unexpectedly detected battle.", - stream - ); - default: - stream.log("Destination marker not detected."); - return false; - } - } - -} - -void overworld_navigation( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - NavigationStopCondition stop_condition, - NavigationMovementMode movement_mode, - uint8_t x, uint8_t y, - uint16_t seconds_timeout, uint16_t seconds_realign, - bool auto_heal, - bool detect_wipeout -){ - bool should_realign = true; - if (seconds_timeout <= seconds_realign){ - seconds_realign = seconds_timeout; - should_realign = false; - } - uint16_t forward_ticks = seconds_realign * TICKS_PER_SECOND; - // WallClock start = current_time(); - - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - context.wait_for(Milliseconds(2000)); // the "Destination arrived" notification can sometimes reappear if you opened the map too quickly after you reached the previous marker. - } - - - while (true){ - NormalBattleMenuWatcher battle(COLOR_BLUE); - DialogBoxWatcher dialog(COLOR_RED, true); - DestinationMarkerWatcher marker(COLOR_CYAN, {0.717, 0.165, 0.03, 0.061}); - context.wait_for_all_requests(); - std::vector callbacks = {battle, dialog}; - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - callbacks.emplace_back(marker); - } - // uint16_t ticks_passed = std::chrono::duration_cast(current_time() - start).count() * TICKS_PER_SECOND / 1000; - // forward_ticks = seconds_realign * TICKS_PER_SECOND - ticks_passed; - - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - - for (int i = 0; i < seconds_timeout / seconds_realign; i++){ - if (movement_mode == NavigationMovementMode::CLEAR_WITH_LETS_GO){ - walk_forward_while_clear_front_path(info, stream, context, forward_ticks, y); - }else{ - ssf_press_left_joystick(context, x, y, 0, seconds_realign * TICKS_PER_SECOND); - if (movement_mode == NavigationMovementMode::DIRECTIONAL_ONLY){ - pbf_wait(context, seconds_realign * TICKS_PER_SECOND); - } else if (movement_mode == NavigationMovementMode::DIRECTIONAL_SPAM_A){ - for (size_t j = 0; j < seconds_realign; j++){ - pbf_press_button(context, BUTTON_A, 20, 105); - } - } - } - context.wait_for_all_requests(); - if (should_realign){ - try { - realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); - - }catch (UnexpectedBattleException&){ - pbf_wait(context, 30 * TICKS_PER_SECOND); // catch exception to allow the battle callback to take over. - } - - } - } - }, - callbacks - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: // battle - stream.log("overworld_navigation: Detected start of battle."); - if (stop_condition == NavigationStopCondition::STOP_BATTLE){ - return; - } - - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD, {}, detect_wipeout); - if (auto_heal){ - auto_heal_from_menu_or_overworld(info, stream, context, 0, true); - } - context.wait_for_all_requests(); - try { - realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); - if (stop_condition == NavigationStopCondition::STOP_MARKER && !confirm_marker_present(info, stream, context)){ - // if marker not present when using marker based navigation, don't keep walking forward. - return; - } - - break; - }catch (UnexpectedBattleException&){ - break; - } - case 1: // dialog - stream.log("overworld_navigation: Detected dialog."); - if (stop_condition == NavigationStopCondition::STOP_DIALOG){ - return; - } - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "overworld_navigation(): Unexpectedly detected dialog.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 20); - break; - case 2: // marker - stream.log("overworld_navigation: Detected marker."); - if (stop_condition == NavigationStopCondition::STOP_MARKER){ - return; - } - break; - default: - stream.log("overworld_navigation(): Timed out."); - if (stop_condition == NavigationStopCondition::STOP_TIME){ - return; - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "overworld_navigation(): Timed out. Did not detect expected stop condition.", - stream - ); - } - } -} - -void config_option(ProControllerContext& context, int change_option_value){ - for (int i = 0; i < change_option_value; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 15, 20); - } - pbf_press_dpad(context, DPAD_DOWN, 15, 20); -} - -void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language){ - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "swap_starter_moves(): Failed to swap the starter moves after 3 minutes.", - stream - ); - } - // start in the overworld - press_Bs_to_back_to_overworld(info, stream, context); - - // open menu, select your starter - enter_menu_from_overworld(info, stream, context, 0, MenuSide::LEFT); - - // enter Pokemon summary screen - pbf_press_button(context, BUTTON_A, 20, 5 * TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_RIGHT, 15, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_Y, 20, 40); - - // select move 1 - pbf_press_button(context, BUTTON_A, 20, 40); - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - // extra button presses to avoid drops - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - pbf_press_dpad(context, DPAD_DOWN, 15, 40); - - // select move 3. swap move 1 and move 3. - pbf_press_button(context, BUTTON_A, 20, 40); - - // confirm that Ember/Leafage/Water Gun is in slot 1 - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - PokemonMovesReader reader(language); - std::string top_move = reader.read_move(stream.logger(), screen, 0); - stream.log("Current top move: " + top_move); - if (top_move != "ember" && top_move != "leafage" && top_move != "water-gun"){ - stream.log("Failed to swap moves. Re-try."); - continue; - } - - - break; - } - -} - - -void change_settings_prior_to_autostory( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - size_t current_segment_num, - Language language -){ - - // get index of `Options` in the Main Menu, which depends on where you are in Autostory - int8_t options_index; - switch(current_segment_num){ - case 0: - return; // can't change settings in the intro cutscene - case 1: - // after Intro cutscene done, in room - // Menu - // - Options - // - Save - options_index = 0; - break; - case 2: - // Menu - // - Bag --> unlocked after picked up bag/hat in room. Segment 01, checkpoint 02 - // - Options - // - Save - options_index = 1; - break; - case 3: - case 4: - case 5: - case 6: - // Menu - // - Bag - // - Boxes --> unlocked after battling Nemona and receiving Pokedex app. Segment 02, checkpoint 04 - // - Options - // - Save - options_index = 2; - break; - case 7: - case 8: - case 9: - // Menu - // - Bag - // - Boxes - // - Poke Portal --> unlocked after arriving at Los Platos and talking to Nemona. Segment 06, checkpoint 11 - // - Options - // - Save - options_index = 3; - break; - default: - // Menu - // - Bag - // - Boxes - // - Picnic --> unlocked after finishing tutorial. Segment 09, checkpoint 20 - // - Poke Portal - // - Options - // - Save - options_index = 4; - break; - } - - bool has_minimap = current_segment_num >= 2; // the minimap only shows up in segment 2 and beyond - - enter_menu_from_overworld(env.program_info(), env.console, context, options_index, MenuSide::RIGHT, has_minimap); - change_settings(env, context, language); - if(!has_minimap){ - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - }else{ - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - } -} - - -void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference){ - env.console.log("Update settings."); - if (use_inference){ - MenuOption session(env.console, context, language); - - std::vector>> options = { - {MenuOptionItemEnum::TEXT_SPEED, {MenuOptionToggleEnum::FAST}}, - {MenuOptionItemEnum::SKIP_MOVE_LEARNING, {MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::SEND_TO_BOXES, {MenuOptionToggleEnum::AUTOMATIC, MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::GIVE_NICKNAMES, {MenuOptionToggleEnum::OFF}}, - {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, - {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, - {MenuOptionItemEnum::CAMERA_SUPPORT, {MenuOptionToggleEnum::OFF}}, - {MenuOptionItemEnum::CAMERA_INTERPOLATION, {MenuOptionToggleEnum::NORMAL, MenuOptionToggleEnum::AVERAGE}}, - {MenuOptionItemEnum::CAMERA_DISTANCE, {MenuOptionToggleEnum::CLOSE}}, - {MenuOptionItemEnum::AUTOSAVE, {MenuOptionToggleEnum::OFF}}, - {MenuOptionItemEnum::SHOW_NICKNAMES, {MenuOptionToggleEnum::OFF, MenuOptionToggleEnum::DONT_SHOW}}, - {MenuOptionItemEnum::SKIP_CUTSCENES, {MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::CONTROLLER_RUMBLE, {MenuOptionToggleEnum::ON}}, - {MenuOptionItemEnum::HELPING_FUNCTIONS, {MenuOptionToggleEnum::OFF}}, - - }; - session.set_options(options); - }else{ - config_option(context, 1); // Text Speed: Fast - config_option(context, 1); // Skip Move Learning: On - config_option(context, 1); // Send to Boxes: Automatic - config_option(context, 1); // Give Nicknames: Off - config_option(context, 0); // Vertical Camera Controls: Regular - config_option(context, 0); // Horiztontal Camera Controls: Regular - config_option(context, 1); // Camera Support: Off - config_option(context, 0); // Camera Interpolation: Normal - config_option(context, 0); // Camera Distance: Close - config_option(context, 1); // Autosave: Off - config_option(context, 1); // Show Nicknames: Don't show - config_option(context, 1); // Skip Cutscenes: On - config_option(context, 0); // Background Music: 10 - config_option(context, 0); // Sound Effects: 10 - config_option(context, 0); // Pokemon Cries: 10 - config_option(context, 0); // Controller Rumble: On - config_option(context, 1); // Helping Functions: Off - } - - pbf_mash_button(context, BUTTON_A, 1 * TICKS_PER_SECOND); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {CallbackEnum::PROMPT_DIALOG}); - -} - -void do_action_and_monitor_for_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -){ - NormalBattleMenuWatcher battle_menu(COLOR_RED); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - context.wait_for_all_requests(); - action(info, stream, context); - }, - {battle_menu} - ); - if (ret == 0){ // battle detected - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "do_action_and_monitor_for_battles(): Detected battle. Failed to complete action.", - stream - ); - - } -} - - -void handle_unexpected_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -){ - while (true){ - try { - context.wait_for_all_requests(); - action(info, stream, context); - return; - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } -} - -void handle_when_stationary_in_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t seconds_stationary, - uint16_t minutes_timeout, - size_t max_failures -){ - - WallClock start = current_time(); - size_t num_failures = 0; - while (true){ - if (current_time() - start > std::chrono::minutes(minutes_timeout)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_when_stationary_in_overworld(): Failed to complete action after " + std::to_string(minutes_timeout) + " minutes.", - stream - ); - } - StationaryOverworldWatcher stationary_overworld(COLOR_RED, {0.865, 0.825, 0.08, 0.1}, seconds_stationary); - - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - context.wait_for_all_requests(); - action(info, stream, context); - }, - {stationary_overworld} - ); - if (ret < 0){ - // successfully completed action without being stuck in a position where the overworld is stationary. - return; - }else if (ret == 0){ - // if stationary in overworld, run recovery action then try action again - stream.log("Detected stationary overworld."); - num_failures++; - if (num_failures > max_failures){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "handle_when_stationary_in_overworld(): Failed to complete action within " + std::to_string(max_failures) + " attempts.", - stream - ); - } - context.wait_for_all_requests(); - recovery_action(info, stream, context); - } - } -} - - -void handle_failed_action( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t max_failures -){ - size_t num_failures = 0; - while (true){ - try { - context.wait_for_all_requests(); - action(info, stream, context); - return; - }catch (OperationFailedException& e){ - num_failures++; - if (num_failures > max_failures){ - throw e; - } - recovery_action(info, stream, context); - } - } -} - - -void wait_for_gradient_arrow( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox box_area_to_check, - uint16_t seconds_timeout -){ - context.wait_for_all_requests(); - GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, box_area_to_check); - int ret = wait_until( - stream, context, - Milliseconds(seconds_timeout * 1000), - { arrow } - ); - if (ret == 0){ - stream.log("Gradient arrow detected."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect gradient arrow.", - stream - ); - } -} - -void wait_for_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - uint16_t seconds_timeout -){ - context.wait_for_all_requests(); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret = wait_until( - stream, context, - Milliseconds(seconds_timeout * 1000), - { overworld } - ); - if (ret == 0){ - stream.log("Overworld detected."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect overworld.", - stream - ); - } - -} - -void press_A_until_dialog( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint16_t seconds_between_button_presses -){ - context.wait_for_all_requests(); - AdvanceDialogWatcher advance_dialog(COLOR_RED); - int ret = run_until( - stream, context, - [seconds_between_button_presses](ProControllerContext& context){ - pbf_wait(context, seconds_between_button_presses * TICKS_PER_SECOND); // avoiding pressing A if dialog already present - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, seconds_between_button_presses * TICKS_PER_SECOND); - } - }, - {advance_dialog} - ); - if (ret == 0){ - stream.log("press_A_until_dialog: Detected dialog."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "press_A_until_dialog(): Unable to detect dialog after 10 button presses.", - stream - ); - } -} - -bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - while (true){ - try { - // open main menu - enter_menu_from_overworld(info, stream, context, -1, MenuSide::NONE, true); - context.wait_for_all_requests(); - ImageStats ride_indicator = image_stats( - extract_box_reference( - stream.video().snapshot(), - ImageFloatBox(0.05, 0.995, 0.25, 0.003) - ) - ); - - bool is_ride_active = !is_black(ride_indicator); // ride is active if the ride indicator isn't black. - pbf_press_button(context, BUTTON_B, 30, 100); - press_Bs_to_back_to_overworld(info, stream, context, 7); - if (is_ride_active){ - stream.log("Ride is active."); - }else{ - stream.log("Ride is not active."); - } - return is_ride_active; - - }catch(UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - -} - -void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - get_on_or_off_ride(info, stream, context, true); -} - -void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - get_on_or_off_ride(info, stream, context, false); -} - -void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on){ - pbf_press_button(context, BUTTON_PLUS, 20, 20); - - WallClock start = current_time(); - while (get_on != is_ride_active(info, stream, context)){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "get_on_or_off_ride(): Failed to get on/off ride after 3 minutes.", - stream - ); - } - pbf_press_button(context, BUTTON_PLUS, 30, 100); - } -} - -void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update){ - AutoStoryStats& stats = env.current_stats(); - save_game_from_overworld(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); -} - - -void realign_player_from_landmark( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_landmark, - MoveCursor move_cursor_to_target -){ - - stream.log("Realigning player direction, using a landmark..."); - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "realign_player_from_landmark(): Failed to realign player after 5 minutes.", - stream - ); - } - - try { - open_map_from_overworld(info, stream, context, false); - - // move cursor near landmark (pokecenter) - switch(move_cursor_near_landmark.zoom_change){ - case ZoomChange::ZOOM_IN: - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_IN_TWICE: - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_OUT: - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::ZOOM_OUT_TWICE: - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::KEEP_ZOOM: - break; - } - uint8_t move_x1 = move_cursor_near_landmark.move_x; - uint8_t move_y1 = move_cursor_near_landmark.move_y; - uint16_t move_duration1 = move_cursor_near_landmark.move_duration; - pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); - - // move cursor to pokecenter - if (!detect_closest_pokecenter_and_move_map_cursor_there(info, stream, context, 0.29)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "realign_player_from_landmark(): No visible pokecenter found on map.", - stream - ); - } - - confirm_cursor_centered_on_pokecenter(info, stream, context); // throws exception if fails - - // move cursor from landmark to target - switch(move_cursor_to_target.zoom_change){ - case ZoomChange::ZOOM_IN: - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_IN_TWICE: - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_OUT: - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::ZOOM_OUT_TWICE: - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::KEEP_ZOOM: - break; - } - uint8_t move_x2 = move_cursor_to_target.move_x; - uint8_t move_y2 = move_cursor_to_target.move_y; - uint16_t move_duration2 = move_cursor_to_target.move_duration; - pbf_move_left_joystick(context, move_x2, move_y2, move_duration2, 1 * TICKS_PER_SECOND); - - // place down marker - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - leave_phone_to_overworld(info, stream, context); - - return; - - }catch (OperationFailedException&){ - // reset to overworld if failed to center on the pokecenter, and re-try - leave_phone_to_overworld(info, stream, context); - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - - -} - - -void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - context.wait_for(Milliseconds(500)); - ImageFloatBox center_cursor{0.484, 0.472, 0.030, 0.053}; - MapPokeCenterIconDetector pokecenter(COLOR_RED, center_cursor); - if (!pokecenter.detect(stream.video().snapshot())){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "confirm_cursor_centered_on_pokecenter(): Cursor is not centered on a pokecenter.", - stream - ); - } - - stream.log("Confirmed that the cursor is centered on a pokecenter."); -} - -void move_cursor_towards_flypoint_and_go_there( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_flypoint -){ - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "move_cursor_towards_flypoint_and_go_there(): Failed to fly after 5 minutes.", - stream - ); - } - - try { - open_map_from_overworld(info, stream, context, false); - - // move cursor near landmark (pokecenter) - switch(move_cursor_near_flypoint.zoom_change){ - case ZoomChange::ZOOM_IN: - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_IN_TWICE: - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_press_button(context, BUTTON_ZR, 20, 105); - break; - case ZoomChange::ZOOM_OUT: - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::ZOOM_OUT_TWICE: - pbf_press_button(context, BUTTON_ZL, 20, 105); - pbf_press_button(context, BUTTON_ZL, 20, 105); - break; - case ZoomChange::KEEP_ZOOM: - break; - } - uint8_t move_x1 = move_cursor_near_flypoint.move_x; - uint8_t move_y1 = move_cursor_near_flypoint.move_y; - uint16_t move_duration1 = move_cursor_near_flypoint.move_duration; - pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); - - if (!fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "move_cursor_towards_flypoint_and_go_there(): No visible pokecenter found on map.", - stream - ); - } - - return; - - }catch (OperationFailedException&){ - // reset to overworld if failed to center on the pokecenter, and re-try - leave_phone_to_overworld(info, stream, context); - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - - -} - - - -void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number){ - context.wait_for_all_requests(); - VideoSnapshot screen = env.console.video().snapshot(); - ImageFloatBox num_sunflora_box = {0.27, 0.02, 0.04, 0.055}; - int number = OCR::read_number_waterfill(env.console, extract_box_reference(screen, num_sunflora_box), 0xff000000, 0xff808080); - - if (number != expected_number){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "The number of sunflora found is different than expected.", - env.console - ); - }else{ - env.console.log("Number of sunflora found: " + std::to_string(number)); - } - - -} - - - -} -} -} +/* AutoStoryTools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/UnexpectedBattleException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_StationaryOverworldWatcher.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonMovesReader.h" +#include "PokemonSV/Inference/Map/PokemonSV_DestinationMarkerDetector.h" +#include "PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" +#include "PokemonSV_AutoStoryTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +void run_battle_press_A( + VideoStream& stream, + ProControllerContext& context, + BattleStopCondition stop_condition, + std::vector enum_optional_callbacks, + bool detect_wipeout +){ + int16_t num_times_seen_overworld = 0; + size_t consecutive_move_select = 0; + while (true){ + NormalBattleMenuWatcher battle(COLOR_BLUE); + SwapMenuWatcher fainted(COLOR_PURPLE); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + AdvanceDialogWatcher dialog(COLOR_RED); + DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); + GradientArrowWatcher next_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); + MoveSelectWatcher move_select_menu(COLOR_YELLOW); + + std::vector callbacks; + // mandatory callbacks: Battle, Overworld, Advance Dialog, Swap menu, Move select + std::vector enum_all_callbacks{CallbackEnum::BATTLE, CallbackEnum::OVERWORLD, CallbackEnum::ADVANCE_DIALOG, CallbackEnum::SWAP_MENU, CallbackEnum::MOVE_SELECT}; // mandatory callbacks + enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together + for (const CallbackEnum& enum_callback : enum_all_callbacks){ + switch(enum_callback){ + case CallbackEnum::ADVANCE_DIALOG: + callbacks.emplace_back(dialog); + break; + case CallbackEnum::OVERWORLD: + callbacks.emplace_back(overworld); + break; + case CallbackEnum::DIALOG_ARROW: + callbacks.emplace_back(dialog_arrow); + break; + case CallbackEnum::BATTLE: + callbacks.emplace_back(battle); + break; + case CallbackEnum::GRADIENT_ARROW: + callbacks.emplace_back(next_pokemon); + break; + case CallbackEnum::SWAP_MENU: + callbacks.emplace_back(fainted); + break; + case CallbackEnum::MOVE_SELECT: + callbacks.emplace_back(move_select_menu); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback requested."); + } + } + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(90), + callbacks + ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Timed out. Did not detect expected stop condition.", + stream + ); + } + + CallbackEnum enum_callback = enum_all_callbacks[ret]; + switch (enum_callback){ + case CallbackEnum::BATTLE: // battle + stream.log("Detected battle menu."); + consecutive_move_select = 0; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::MOVE_SELECT: + stream.log("Detected move select. Spam first move"); + consecutive_move_select++; + select_top_move(stream, context, consecutive_move_select); + break; + case CallbackEnum::OVERWORLD: // overworld + stream.log("Detected overworld, battle over."); + num_times_seen_overworld++; + if (stop_condition == BattleStopCondition::STOP_OVERWORLD){ + return; + } + if(num_times_seen_overworld > 30){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Stuck in overworld. Did not detect expected stop condition.", + stream + ); + } + break; + case CallbackEnum::ADVANCE_DIALOG: // advance dialog + stream.log("Detected dialog."); + + if (detect_wipeout){ + context.wait_for_all_requests(); + WipeoutDetector wipeout; + VideoSnapshot screen = stream.video().snapshot(); + // dump_snapshot(console); + if (wipeout.detect(screen)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Detected wipeout. All pokemon fainted.", + stream + ); + } + } + + if (stop_condition == BattleStopCondition::STOP_DIALOG){ + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::DIALOG_ARROW: // dialog arrow + stream.log("run_battle_press_A: Detected dialog arrow."); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::GRADIENT_ARROW: + stream.log("run_battle_press_A: Detected prompt for bringing in next pokemon. Keep current pokemon."); + pbf_mash_button(context, BUTTON_B, 100); + break; + case CallbackEnum::SWAP_MENU: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_battle_press_A(): Lead pokemon fainted.", + stream + ); + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "run_battle_press_A: Unknown callback triggered."); + + } + } +} + +void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select){ + if (consecutive_move_select > 3){ + // to handle case where move is disabled/out of PP/taunted + stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); + pbf_press_dpad(context, DPAD_DOWN, 20, 40); + } + pbf_mash_button(context, BUTTON_A, 100); + +} + +void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout){ + bool seen_tutorial = false; + while (true){ + TutorialWatcher tutorial; + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(seconds_timeout), + {tutorial} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: + stream.log("clear_tutorial: Detected tutorial screen."); + seen_tutorial = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + default: + stream.log("clear_tutorial: Timed out."); + if(!seen_tutorial){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "clear_tutorial(): Tutorial screen never detected.", + stream + ); + } + return; + } + } +} + +void clear_dialog(VideoStream& stream, ProControllerContext& context, + ClearDialogMode mode, uint16_t seconds_timeout, + std::vector enum_optional_callbacks +){ + bool seen_dialog = false; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "clear_dialog(): Failed to clear dialog after 3 minutes.", + stream + ); + } + + AdvanceDialogWatcher advance_dialog(COLOR_RED); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + PromptDialogWatcher prompt(COLOR_YELLOW); + WhiteButtonWatcher whitebutton(COLOR_GREEN, WhiteButton::ButtonA_DarkBackground, {0.725, 0.833, 0.024, 0.045}); // {0.650, 0.650, 0.140, 0.240} + DialogArrowWatcher dialog_arrow(COLOR_RED, stream.overlay(), {0.850, 0.820, 0.020, 0.050}, 0.8365, 0.846); + NormalBattleMenuWatcher battle(COLOR_ORANGE); + TutorialWatcher tutorial(COLOR_BLUE); + DialogBoxWatcher black_dialog_box(COLOR_BLACK, true, std::chrono::milliseconds(250), DialogType::DIALOG_BLACK); + context.wait_for_all_requests(); + + std::vector callbacks; + std::vector enum_all_callbacks{CallbackEnum::ADVANCE_DIALOG}; // mandatory callbacks + enum_all_callbacks.insert(enum_all_callbacks.end(), enum_optional_callbacks.begin(), enum_optional_callbacks.end()); // append the mandatory and optional callback vectors together + for (const CallbackEnum& enum_callback : enum_all_callbacks){ + switch(enum_callback){ + case CallbackEnum::ADVANCE_DIALOG: + callbacks.emplace_back(advance_dialog); + break; + case CallbackEnum::OVERWORLD: + callbacks.emplace_back(overworld); + break; + case CallbackEnum::PROMPT_DIALOG: + callbacks.emplace_back(prompt); + break; + case CallbackEnum::WHITE_A_BUTTON: + callbacks.emplace_back(whitebutton); + break; + case CallbackEnum::DIALOG_ARROW: + callbacks.emplace_back(dialog_arrow); + break; + case CallbackEnum::BATTLE: + callbacks.emplace_back(battle); + break; + case CallbackEnum::TUTORIAL: + callbacks.emplace_back(tutorial); + break; + case CallbackEnum::BLACK_DIALOG_BOX: + callbacks.emplace_back(black_dialog_box); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback requested."); + } + } + + + int ret = wait_until( + stream, context, + std::chrono::seconds(seconds_timeout), + callbacks + ); + // int ret = run_until( + // console, context, + // [&](ProControllerContext& context){ + // for (size_t j = 0; j < seconds_timeout/3; j++){ + // pbf_press_button(context, BUTTON_A, 20, 3*TICKS_PER_SECOND-20); + // } + // }, + // {overworld, prompt, whitebutton, advance_dialog, battle} + // ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret < 0){ + stream.log("clear_dialog(): Timed out."); + if (seen_dialog && mode == ClearDialogMode::STOP_TIMEOUT){ + return; + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "clear_dialog(): Timed out. Did not detect dialog or did not detect the expected stop condition.", + stream + ); + } + + CallbackEnum enum_callback = enum_all_callbacks[ret]; + switch(enum_callback){ + case CallbackEnum::ADVANCE_DIALOG: + stream.log("clear_dialog: Detected advance dialog."); + seen_dialog = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::OVERWORLD: + stream.log("clear_dialog: Detected overworld."); + if (seen_dialog && mode == ClearDialogMode::STOP_OVERWORLD){ + return; + } + break; + case CallbackEnum::PROMPT_DIALOG: + stream.log("clear_dialog: Detected prompt."); + seen_dialog = true; + if (mode == ClearDialogMode::STOP_PROMPT){ + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::WHITE_A_BUTTON: + stream.log("clear_dialog: Detected white A button."); + seen_dialog = true; + if (mode == ClearDialogMode::STOP_WHITEBUTTON){ + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::DIALOG_ARROW: + stream.log("clear_dialog: Detected dialog arrow."); + seen_dialog = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::BATTLE: + stream.log("clear_dialog: Detected battle."); + if (mode == ClearDialogMode::STOP_BATTLE){ + return; + } + break; + case CallbackEnum::TUTORIAL: + stream.log("clear_dialog: Detected tutorial."); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case CallbackEnum::BLACK_DIALOG_BOX: + stream.log("clear_dialog: Detected black dialog box."); + seen_dialog = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "clear_dialog: Unknown callback triggered."); + + } + + } +} + +bool confirm_marker_present( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +){ + while (true){ + DestinationMarkerWatcher marker(COLOR_RED, {0.815, 0.645, 0.180, 0.320}, true); + NormalBattleMenuWatcher battle(COLOR_BLUE); + + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + {marker, battle} + ); + switch (ret){ + case 0: // marker + stream.log("Confirmed that marker is still present."); + return true; + case 1: // battle + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "confirm_marker_present(): Unexpectedly detected battle.", + stream + ); + default: + stream.log("Destination marker not detected."); + return false; + } + } + +} + +void overworld_navigation( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + NavigationStopCondition stop_condition, + NavigationMovementMode movement_mode, + uint8_t x, uint8_t y, + uint16_t seconds_timeout, uint16_t seconds_realign, + bool auto_heal, + bool detect_wipeout +){ + bool should_realign = true; + if (seconds_timeout <= seconds_realign){ + seconds_realign = seconds_timeout; + should_realign = false; + } + uint16_t forward_ticks = seconds_realign * TICKS_PER_SECOND; + // WallClock start = current_time(); + + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + context.wait_for(Milliseconds(2000)); // the "Destination arrived" notification can sometimes reappear if you opened the map too quickly after you reached the previous marker. + } + + + while (true){ + NormalBattleMenuWatcher battle(COLOR_BLUE); + DialogBoxWatcher dialog(COLOR_RED, true); + DestinationMarkerWatcher marker(COLOR_CYAN, {0.717, 0.165, 0.03, 0.061}); + context.wait_for_all_requests(); + std::vector callbacks = {battle, dialog}; + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + callbacks.emplace_back(marker); + } + // uint16_t ticks_passed = std::chrono::duration_cast(current_time() - start).count() * TICKS_PER_SECOND / 1000; + // forward_ticks = seconds_realign * TICKS_PER_SECOND - ticks_passed; + + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + + for (int i = 0; i < seconds_timeout / seconds_realign; i++){ + if (movement_mode == NavigationMovementMode::CLEAR_WITH_LETS_GO){ + walk_forward_while_clear_front_path(info, stream, context, forward_ticks, y); + }else{ + ssf_press_left_joystick(context, x, y, 0, seconds_realign * TICKS_PER_SECOND); + if (movement_mode == NavigationMovementMode::DIRECTIONAL_ONLY){ + pbf_wait(context, seconds_realign * TICKS_PER_SECOND); + } else if (movement_mode == NavigationMovementMode::DIRECTIONAL_SPAM_A){ + for (size_t j = 0; j < seconds_realign; j++){ + pbf_press_button(context, BUTTON_A, 20, 105); + } + } + } + context.wait_for_all_requests(); + if (should_realign){ + try { + realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); + + }catch (UnexpectedBattleException&){ + pbf_wait(context, 30 * TICKS_PER_SECOND); // catch exception to allow the battle callback to take over. + } + + } + } + }, + callbacks + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: // battle + stream.log("overworld_navigation: Detected start of battle."); + if (stop_condition == NavigationStopCondition::STOP_BATTLE){ + return; + } + + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD, {}, detect_wipeout); + if (auto_heal){ + auto_heal_from_menu_or_overworld(info, stream, context, 0, true); + } + context.wait_for_all_requests(); + try { + realign_player(info, stream, context, PlayerRealignMode::REALIGN_OLD_MARKER); + if (stop_condition == NavigationStopCondition::STOP_MARKER && !confirm_marker_present(info, stream, context)){ + // if marker not present when using marker based navigation, don't keep walking forward. + return; + } + + break; + }catch (UnexpectedBattleException&){ + break; + } + case 1: // dialog + stream.log("overworld_navigation: Detected dialog."); + if (stop_condition == NavigationStopCondition::STOP_DIALOG){ + return; + } + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "overworld_navigation(): Unexpectedly detected dialog.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 20); + break; + case 2: // marker + stream.log("overworld_navigation: Detected marker."); + if (stop_condition == NavigationStopCondition::STOP_MARKER){ + return; + } + break; + default: + stream.log("overworld_navigation(): Timed out."); + if (stop_condition == NavigationStopCondition::STOP_TIME){ + return; + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "overworld_navigation(): Timed out. Did not detect expected stop condition.", + stream + ); + } + } +} + +void config_option(ProControllerContext& context, int change_option_value){ + for (int i = 0; i < change_option_value; i++){ + pbf_press_dpad(context, DPAD_RIGHT, 15, 20); + } + pbf_press_dpad(context, DPAD_DOWN, 15, 20); +} + +void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language){ + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "swap_starter_moves(): Failed to swap the starter moves after 3 minutes.", + stream + ); + } + // start in the overworld + press_Bs_to_back_to_overworld(info, stream, context); + + // open menu, select your starter + enter_menu_from_overworld(info, stream, context, 0, MenuSide::LEFT); + + // enter Pokemon summary screen + pbf_press_button(context, BUTTON_A, 20, 5 * TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_RIGHT, 15, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_Y, 20, 40); + + // select move 1 + pbf_press_button(context, BUTTON_A, 20, 40); + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + // extra button presses to avoid drops + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + pbf_press_dpad(context, DPAD_DOWN, 15, 40); + + // select move 3. swap move 1 and move 3. + pbf_press_button(context, BUTTON_A, 20, 40); + + // confirm that Ember/Leafage/Water Gun is in slot 1 + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + PokemonMovesReader reader(language); + std::string top_move = reader.read_move(stream.logger(), screen, 0); + stream.log("Current top move: " + top_move); + if (top_move != "ember" && top_move != "leafage" && top_move != "water-gun"){ + stream.log("Failed to swap moves. Re-try."); + continue; + } + + + break; + } + +} + + +void change_settings_prior_to_autostory( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + size_t current_segment_num, + Language language +){ + + // get index of `Options` in the Main Menu, which depends on where you are in Autostory + int8_t options_index; + switch(current_segment_num){ + case 0: + return; // can't change settings in the intro cutscene + case 1: + // after Intro cutscene done, in room + // Menu + // - Options + // - Save + options_index = 0; + break; + case 2: + // Menu + // - Bag --> unlocked after picked up bag/hat in room. Segment 01, checkpoint 02 + // - Options + // - Save + options_index = 1; + break; + case 3: + case 4: + case 5: + case 6: + // Menu + // - Bag + // - Boxes --> unlocked after battling Nemona and receiving Pokedex app. Segment 02, checkpoint 04 + // - Options + // - Save + options_index = 2; + break; + case 7: + case 8: + case 9: + // Menu + // - Bag + // - Boxes + // - Poke Portal --> unlocked after arriving at Los Platos and talking to Nemona. Segment 06, checkpoint 11 + // - Options + // - Save + options_index = 3; + break; + default: + // Menu + // - Bag + // - Boxes + // - Picnic --> unlocked after finishing tutorial. Segment 09, checkpoint 20 + // - Poke Portal + // - Options + // - Save + options_index = 4; + break; + } + + bool has_minimap = current_segment_num >= 2; // the minimap only shows up in segment 2 and beyond + + enter_menu_from_overworld(env.program_info(), env.console, context, options_index, MenuSide::RIGHT, has_minimap); + change_settings(env, context, language); + if(!has_minimap){ + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + }else{ + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + } +} + + +void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference){ + env.console.log("Update settings."); + if (use_inference){ + MenuOption session(env.console, context, language); + + std::vector>> options = { + {MenuOptionItemEnum::TEXT_SPEED, {MenuOptionToggleEnum::FAST}}, + {MenuOptionItemEnum::SKIP_MOVE_LEARNING, {MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::SEND_TO_BOXES, {MenuOptionToggleEnum::AUTOMATIC, MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::GIVE_NICKNAMES, {MenuOptionToggleEnum::OFF}}, + {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, + {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, {MenuOptionToggleEnum::REGULAR, MenuOptionToggleEnum::NORMAL}}, + {MenuOptionItemEnum::CAMERA_SUPPORT, {MenuOptionToggleEnum::OFF}}, + {MenuOptionItemEnum::CAMERA_INTERPOLATION, {MenuOptionToggleEnum::NORMAL, MenuOptionToggleEnum::AVERAGE}}, + {MenuOptionItemEnum::CAMERA_DISTANCE, {MenuOptionToggleEnum::CLOSE}}, + {MenuOptionItemEnum::AUTOSAVE, {MenuOptionToggleEnum::OFF}}, + {MenuOptionItemEnum::SHOW_NICKNAMES, {MenuOptionToggleEnum::OFF, MenuOptionToggleEnum::DONT_SHOW}}, + {MenuOptionItemEnum::SKIP_CUTSCENES, {MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::CONTROLLER_RUMBLE, {MenuOptionToggleEnum::ON}}, + {MenuOptionItemEnum::HELPING_FUNCTIONS, {MenuOptionToggleEnum::OFF}}, + + }; + session.set_options(options); + }else{ + config_option(context, 1); // Text Speed: Fast + config_option(context, 1); // Skip Move Learning: On + config_option(context, 1); // Send to Boxes: Automatic + config_option(context, 1); // Give Nicknames: Off + config_option(context, 0); // Vertical Camera Controls: Regular + config_option(context, 0); // Horiztontal Camera Controls: Regular + config_option(context, 1); // Camera Support: Off + config_option(context, 0); // Camera Interpolation: Normal + config_option(context, 0); // Camera Distance: Close + config_option(context, 1); // Autosave: Off + config_option(context, 1); // Show Nicknames: Don't show + config_option(context, 1); // Skip Cutscenes: On + config_option(context, 0); // Background Music: 10 + config_option(context, 0); // Sound Effects: 10 + config_option(context, 0); // Pokemon Cries: 10 + config_option(context, 0); // Controller Rumble: On + config_option(context, 1); // Helping Functions: Off + } + + pbf_mash_button(context, BUTTON_A, 1 * TICKS_PER_SECOND); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {CallbackEnum::PROMPT_DIALOG}); + +} + +void do_action_and_monitor_for_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +){ + NormalBattleMenuWatcher battle_menu(COLOR_RED); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + context.wait_for_all_requests(); + action(info, stream, context); + }, + {battle_menu} + ); + if (ret == 0){ // battle detected + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "do_action_and_monitor_for_battles(): Detected battle. Failed to complete action.", + stream + ); + + } +} + + +void handle_unexpected_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +){ + while (true){ + try { + context.wait_for_all_requests(); + action(info, stream, context); + return; + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } +} + +void handle_when_stationary_in_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t seconds_stationary, + uint16_t minutes_timeout, + size_t max_failures +){ + + WallClock start = current_time(); + size_t num_failures = 0; + while (true){ + if (current_time() - start > std::chrono::minutes(minutes_timeout)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_when_stationary_in_overworld(): Failed to complete action after " + std::to_string(minutes_timeout) + " minutes.", + stream + ); + } + StationaryOverworldWatcher stationary_overworld(COLOR_RED, {0.865, 0.825, 0.08, 0.1}, seconds_stationary); + + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + context.wait_for_all_requests(); + action(info, stream, context); + }, + {stationary_overworld} + ); + if (ret < 0){ + // successfully completed action without being stuck in a position where the overworld is stationary. + return; + }else if (ret == 0){ + // if stationary in overworld, run recovery action then try action again + stream.log("Detected stationary overworld."); + num_failures++; + if (num_failures > max_failures){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "handle_when_stationary_in_overworld(): Failed to complete action within " + std::to_string(max_failures) + " attempts.", + stream + ); + } + context.wait_for_all_requests(); + recovery_action(info, stream, context); + } + } +} + + +void handle_failed_action( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t max_failures +){ + size_t num_failures = 0; + while (true){ + try { + context.wait_for_all_requests(); + action(info, stream, context); + return; + }catch (OperationFailedException& e){ + num_failures++; + if (num_failures > max_failures){ + throw e; + } + recovery_action(info, stream, context); + } + } +} + + +void wait_for_gradient_arrow( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox box_area_to_check, + uint16_t seconds_timeout +){ + context.wait_for_all_requests(); + GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, box_area_to_check); + int ret = wait_until( + stream, context, + Milliseconds(seconds_timeout * 1000), + { arrow } + ); + if (ret == 0){ + stream.log("Gradient arrow detected."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect gradient arrow.", + stream + ); + } +} + +void wait_for_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + uint16_t seconds_timeout +){ + context.wait_for_all_requests(); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret = wait_until( + stream, context, + Milliseconds(seconds_timeout * 1000), + { overworld } + ); + if (ret == 0){ + stream.log("Overworld detected."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect overworld.", + stream + ); + } + +} + +void press_A_until_dialog( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint16_t seconds_between_button_presses +){ + context.wait_for_all_requests(); + AdvanceDialogWatcher advance_dialog(COLOR_RED); + int ret = run_until( + stream, context, + [seconds_between_button_presses](ProControllerContext& context){ + pbf_wait(context, seconds_between_button_presses * TICKS_PER_SECOND); // avoiding pressing A if dialog already present + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, seconds_between_button_presses * TICKS_PER_SECOND); + } + }, + {advance_dialog} + ); + if (ret == 0){ + stream.log("press_A_until_dialog: Detected dialog."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "press_A_until_dialog(): Unable to detect dialog after 10 button presses.", + stream + ); + } +} + +bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + while (true){ + try { + // open main menu + enter_menu_from_overworld(info, stream, context, -1, MenuSide::NONE, true); + context.wait_for_all_requests(); + ImageStats ride_indicator = image_stats( + extract_box_reference( + stream.video().snapshot(), + ImageFloatBox(0.05, 0.995, 0.25, 0.003) + ) + ); + + bool is_ride_active = !is_black(ride_indicator); // ride is active if the ride indicator isn't black. + pbf_press_button(context, BUTTON_B, 30, 100); + press_Bs_to_back_to_overworld(info, stream, context, 7); + if (is_ride_active){ + stream.log("Ride is active."); + }else{ + stream.log("Ride is not active."); + } + return is_ride_active; + + }catch(UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + +} + +void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + get_on_or_off_ride(info, stream, context, true); +} + +void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + get_on_or_off_ride(info, stream, context, false); +} + +void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on){ + pbf_press_button(context, BUTTON_PLUS, 20, 20); + + WallClock start = current_time(); + while (get_on != is_ride_active(info, stream, context)){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "get_on_or_off_ride(): Failed to get on/off ride after 3 minutes.", + stream + ); + } + pbf_press_button(context, BUTTON_PLUS, 30, 100); + } +} + +void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update){ + AutoStoryStats& stats = env.current_stats(); + save_game_from_overworld(env.program_info(), env.console, context); + stats.m_checkpoint++; + env.update_stats(); + send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); +} + + +void realign_player_from_landmark( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_landmark, + MoveCursor move_cursor_to_target +){ + + stream.log("Realigning player direction, using a landmark..."); + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "realign_player_from_landmark(): Failed to realign player after 5 minutes.", + stream + ); + } + + try { + open_map_from_overworld(info, stream, context, false); + + // move cursor near landmark (pokecenter) + switch(move_cursor_near_landmark.zoom_change){ + case ZoomChange::ZOOM_IN: + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_IN_TWICE: + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_OUT: + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::ZOOM_OUT_TWICE: + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::KEEP_ZOOM: + break; + } + uint8_t move_x1 = move_cursor_near_landmark.move_x; + uint8_t move_y1 = move_cursor_near_landmark.move_y; + uint16_t move_duration1 = move_cursor_near_landmark.move_duration; + pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); + + // move cursor to pokecenter + if (!detect_closest_pokecenter_and_move_map_cursor_there(info, stream, context, 0.29)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "realign_player_from_landmark(): No visible pokecenter found on map.", + stream + ); + } + + confirm_cursor_centered_on_pokecenter(info, stream, context); // throws exception if fails + + // move cursor from landmark to target + switch(move_cursor_to_target.zoom_change){ + case ZoomChange::ZOOM_IN: + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_IN_TWICE: + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_OUT: + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::ZOOM_OUT_TWICE: + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::KEEP_ZOOM: + break; + } + uint8_t move_x2 = move_cursor_to_target.move_x; + uint8_t move_y2 = move_cursor_to_target.move_y; + uint16_t move_duration2 = move_cursor_to_target.move_duration; + pbf_move_left_joystick(context, move_x2, move_y2, move_duration2, 1 * TICKS_PER_SECOND); + + // place down marker + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + leave_phone_to_overworld(info, stream, context); + + return; + + }catch (OperationFailedException&){ + // reset to overworld if failed to center on the pokecenter, and re-try + leave_phone_to_overworld(info, stream, context); + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + + +} + + +void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + context.wait_for(Milliseconds(500)); + ImageFloatBox center_cursor{0.484, 0.472, 0.030, 0.053}; + MapPokeCenterIconDetector pokecenter(COLOR_RED, center_cursor); + if (!pokecenter.detect(stream.video().snapshot())){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "confirm_cursor_centered_on_pokecenter(): Cursor is not centered on a pokecenter.", + stream + ); + } + + stream.log("Confirmed that the cursor is centered on a pokecenter."); +} + +void move_cursor_towards_flypoint_and_go_there( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_flypoint +){ + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "move_cursor_towards_flypoint_and_go_there(): Failed to fly after 5 minutes.", + stream + ); + } + + try { + open_map_from_overworld(info, stream, context, false); + + // move cursor near landmark (pokecenter) + switch(move_cursor_near_flypoint.zoom_change){ + case ZoomChange::ZOOM_IN: + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_IN_TWICE: + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_press_button(context, BUTTON_ZR, 20, 105); + break; + case ZoomChange::ZOOM_OUT: + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::ZOOM_OUT_TWICE: + pbf_press_button(context, BUTTON_ZL, 20, 105); + pbf_press_button(context, BUTTON_ZL, 20, 105); + break; + case ZoomChange::KEEP_ZOOM: + break; + } + uint8_t move_x1 = move_cursor_near_flypoint.move_x; + uint8_t move_y1 = move_cursor_near_flypoint.move_y; + uint16_t move_duration1 = move_cursor_near_flypoint.move_duration; + pbf_move_left_joystick(context, move_x1, move_y1, move_duration1, 1 * TICKS_PER_SECOND); + + if (!fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "move_cursor_towards_flypoint_and_go_there(): No visible pokecenter found on map.", + stream + ); + } + + return; + + }catch (OperationFailedException&){ + // reset to overworld if failed to center on the pokecenter, and re-try + leave_phone_to_overworld(info, stream, context); + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + + +} + + + +void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number){ + context.wait_for_all_requests(); + VideoSnapshot screen = env.console.video().snapshot(); + ImageFloatBox num_sunflora_box = {0.27, 0.02, 0.04, 0.055}; + int number = OCR::read_number_waterfill(env.console, extract_box_reference(screen, num_sunflora_box), 0xff000000, 0xff808080); + + if (number != expected_number){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "The number of sunflora found is different than expected.", + env.console + ); + }else{ + env.console.log("Number of sunflora found: " + std::to_string(number)); + } + + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h index 6bdb72dfc3..644c10d2b0 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h @@ -1,329 +1,329 @@ -/* AutostoryTools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H -#define PokemonAutomation_PokemonSV_AutoStoryTools_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -// #include "PokemonSV/Programs/PokemonSV_Navigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct AutoStoryStats : public StatsTracker{ - AutoStoryStats() - : m_checkpoint(m_stats["Checkpoint"]) - , m_segment(m_stats["Segment"]) - , m_reset(m_stats["Reset"]) - { - m_display_order.emplace_back("Checkpoint"); - m_display_order.emplace_back("Segment"); - m_display_order.emplace_back("Reset"); - } - std::atomic& m_checkpoint; - std::atomic& m_segment; - std::atomic& m_reset; -}; - - -enum class BattleStopCondition{ - STOP_OVERWORLD, - STOP_DIALOG, -}; - -enum class ClearDialogMode{ - STOP_OVERWORLD, - STOP_PROMPT, - STOP_WHITEBUTTON, - STOP_TIMEOUT, - STOP_BATTLE, -}; - - -enum class CallbackEnum{ - ADVANCE_DIALOG, - OVERWORLD, - PROMPT_DIALOG, - WHITE_A_BUTTON, - DIALOG_ARROW, - BATTLE, - TUTORIAL, - BLACK_DIALOG_BOX, - GRADIENT_ARROW, - SWAP_MENU, - MOVE_SELECT, -}; - -enum class StartPoint{ - INTRO_CUTSCENE, - PICK_STARTER, - NEMONA_FIRST_BATTLE, - CATCH_TUTORIAL, - LEGENDARY_RESCUE, - ARVEN_FIRST_BATTLE, - LOS_PLATOS, - MESAGOZA_SOUTH, -}; - -enum class StarterChoice{ - SPRIGATITO, - FUECOCO, - QUAXLY, -}; - -enum class PlayerRealignMode{ - REALIGN_NEW_MARKER, - REALIGN_OLD_MARKER, - REALIGN_NO_MARKER, -}; - -enum class NavigationStopCondition{ - STOP_DIALOG, - STOP_MARKER, - STOP_TIME, - STOP_BATTLE, -}; - -enum class NavigationMovementMode{ - DIRECTIONAL_ONLY, - DIRECTIONAL_SPAM_A, - CLEAR_WITH_LETS_GO, -}; - -struct AutoStoryOptions{ - Language language; - StarterChoice starter_choice; - EventNotificationOption& notif_status_update; -}; - -class AutoStory_Segment { -public: - virtual ~AutoStory_Segment() = default; - virtual std::string name() const = 0; - virtual std::string start_text() const = 0; - virtual std::string end_text() const = 0; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options) const = 0; -}; - -// spam A button to choose the first move -// throw exception if wipeout. -void run_battle_press_A( - VideoStream& stream, - ProControllerContext& context, - BattleStopCondition stop_condition, - std::vector optional_callbacks = {}, - bool detect_wipeout = false -); - -void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select); - -// press A to clear tutorial screens -// throw exception if tutorial screen never detected -void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout = 5); - -// spam the A button to clear dialog. -// stop depending on ClearDialogMode: stop when detect overworld, or dialog prompt, or A button prompt. Or if times out -// throw exception if times out, unless this is the intended stop condition. -// also throw exception if dialog is never detected. -void clear_dialog(VideoStream& stream, ProControllerContext& context, - ClearDialogMode mode, uint16_t seconds_timeout = 60, - std::vector optional_callbacks = {} -); - - -// return true if the destination marker is present within the minimap area -bool confirm_marker_present( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -); - -// move character with ssf left joystick, as per given x, y, until -// stop_condition is met (e.g. Dialog detected). -// throw exception if reaches timeout before detecting stop condition -void overworld_navigation(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - NavigationStopCondition stop_condition, - NavigationMovementMode movement_mode, - uint8_t x, uint8_t y, - uint16_t seconds_timeout = 60, uint16_t seconds_realign = 60, - bool auto_heal = false, - bool detect_wipeout = false -); - -void config_option(ProControllerContext& context, int change_option_value); - -// enter menu and swap the first and third moves for your starter -void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language); - -// run the given `action`. if detect a battle, stop the action, and throw exception -void do_action_and_monitor_for_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -); - -// catch any UnexpectedBattle exceptions from `action`. then use run_battle_press_A until overworld, and re-try the `action`. -void handle_unexpected_battles( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action -); - -// if stationary in overworld for an amount of time (seconds_stationary), run `recovery_action` then try `action` again -// return once successfully completed `action` -// throw exception if fails to complete `action` within a certain amount of time (minutes_timeout). -// NOTE: if using this function to wrap overworld_navigation(), keep in mind that -// confirm_marker_present() will keep the player still for 5 seconds before moving. Therefore, seconds_stationary should be greater than 5 seconds in this case. -void handle_when_stationary_in_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t seconds_stationary = 6, - uint16_t minutes_timeout = 5, - size_t max_attempts = 2 -); - -// do action. if error is thrown, catch the error and try the recovery action -void handle_failed_action( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& action, - std::function< - void(const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context) - >&& recovery_action, - size_t max_failures -); - -void wait_for_gradient_arrow( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox box_area_to_check, - uint16_t seconds_timeout -); - -void wait_for_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - uint16_t seconds_timeout = 30 -); - -void press_A_until_dialog( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint16_t seconds_between_button_presses -); - -// return true if ride is active. i.e. if you are on your ride -bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on); - - -// change the settings prior to Autostory -// Assumes that `current_segment` represents where we currently are in the story. -void change_settings_prior_to_autostory( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - size_t current_segment_num, - Language language -); - -// from within the Settings/Options menu, change the settings -void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference = true); - - -void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update); - -enum class ZoomChange{ - ZOOM_IN, - ZOOM_IN_TWICE, - ZOOM_OUT, - ZOOM_OUT_TWICE, - KEEP_ZOOM, -}; - -struct MoveCursor{ - ZoomChange zoom_change; - uint8_t move_x; - uint8_t move_y; - uint16_t move_duration; -}; - -// place a marker on the map, not relative to the current player position, but based on a fixed landmark, such as a pokecenter -// How this works: -// - cursor is moved to a point near the landmark, as per `move_cursor_near_landmark` -// - move the cursor onto the landmark using `detect_closest_pokecenter_and_move_map_cursor_there`. -// - confirm that the pokecenter is centered within cursor. If not, close map app, and re-try. -// - cursor is moved to target location, as per `move_cursor_to_target`. A marker is placed down here. -void realign_player_from_landmark( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_landmark, - MoveCursor move_cursor_to_target -); - -// confirm that the cursor is centered on the pokecenter, within the map app -// else throw exception -void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// open map, then move cursor to a point near a flypoint as per `move_cursor_near_flypoint` -// then fly to the closest pokecenter near the cursor -void move_cursor_towards_flypoint_and_go_there( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - MoveCursor move_cursor_near_flypoint -); - - -void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number); - -} -} -} -#endif +/* AutostoryTools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStoryTools_H +#define PokemonAutomation_PokemonSV_AutoStoryTools_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +// #include "PokemonSV/Programs/PokemonSV_Navigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct AutoStoryStats : public StatsTracker{ + AutoStoryStats() + : m_checkpoint(m_stats["Checkpoint"]) + , m_segment(m_stats["Segment"]) + , m_reset(m_stats["Reset"]) + { + m_display_order.emplace_back("Checkpoint"); + m_display_order.emplace_back("Segment"); + m_display_order.emplace_back("Reset"); + } + std::atomic& m_checkpoint; + std::atomic& m_segment; + std::atomic& m_reset; +}; + + +enum class BattleStopCondition{ + STOP_OVERWORLD, + STOP_DIALOG, +}; + +enum class ClearDialogMode{ + STOP_OVERWORLD, + STOP_PROMPT, + STOP_WHITEBUTTON, + STOP_TIMEOUT, + STOP_BATTLE, +}; + + +enum class CallbackEnum{ + ADVANCE_DIALOG, + OVERWORLD, + PROMPT_DIALOG, + WHITE_A_BUTTON, + DIALOG_ARROW, + BATTLE, + TUTORIAL, + BLACK_DIALOG_BOX, + GRADIENT_ARROW, + SWAP_MENU, + MOVE_SELECT, +}; + +enum class StartPoint{ + INTRO_CUTSCENE, + PICK_STARTER, + NEMONA_FIRST_BATTLE, + CATCH_TUTORIAL, + LEGENDARY_RESCUE, + ARVEN_FIRST_BATTLE, + LOS_PLATOS, + MESAGOZA_SOUTH, +}; + +enum class StarterChoice{ + SPRIGATITO, + FUECOCO, + QUAXLY, +}; + +enum class PlayerRealignMode{ + REALIGN_NEW_MARKER, + REALIGN_OLD_MARKER, + REALIGN_NO_MARKER, +}; + +enum class NavigationStopCondition{ + STOP_DIALOG, + STOP_MARKER, + STOP_TIME, + STOP_BATTLE, +}; + +enum class NavigationMovementMode{ + DIRECTIONAL_ONLY, + DIRECTIONAL_SPAM_A, + CLEAR_WITH_LETS_GO, +}; + +struct AutoStoryOptions{ + Language language; + StarterChoice starter_choice; + EventNotificationOption& notif_status_update; +}; + +class AutoStory_Segment { +public: + virtual ~AutoStory_Segment() = default; + virtual std::string name() const = 0; + virtual std::string start_text() const = 0; + virtual std::string end_text() const = 0; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options) const = 0; +}; + +// spam A button to choose the first move +// throw exception if wipeout. +void run_battle_press_A( + VideoStream& stream, + ProControllerContext& context, + BattleStopCondition stop_condition, + std::vector optional_callbacks = {}, + bool detect_wipeout = false +); + +void select_top_move(VideoStream& stream, ProControllerContext& context, size_t consecutive_move_select); + +// press A to clear tutorial screens +// throw exception if tutorial screen never detected +void clear_tutorial(VideoStream& stream, ProControllerContext& context, uint16_t seconds_timeout = 5); + +// spam the A button to clear dialog. +// stop depending on ClearDialogMode: stop when detect overworld, or dialog prompt, or A button prompt. Or if times out +// throw exception if times out, unless this is the intended stop condition. +// also throw exception if dialog is never detected. +void clear_dialog(VideoStream& stream, ProControllerContext& context, + ClearDialogMode mode, uint16_t seconds_timeout = 60, + std::vector optional_callbacks = {} +); + + +// return true if the destination marker is present within the minimap area +bool confirm_marker_present( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +); + +// move character with ssf left joystick, as per given x, y, until +// stop_condition is met (e.g. Dialog detected). +// throw exception if reaches timeout before detecting stop condition +void overworld_navigation(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + NavigationStopCondition stop_condition, + NavigationMovementMode movement_mode, + uint8_t x, uint8_t y, + uint16_t seconds_timeout = 60, uint16_t seconds_realign = 60, + bool auto_heal = false, + bool detect_wipeout = false +); + +void config_option(ProControllerContext& context, int change_option_value); + +// enter menu and swap the first and third moves for your starter +void swap_starter_moves(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, Language language); + +// run the given `action`. if detect a battle, stop the action, and throw exception +void do_action_and_monitor_for_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +); + +// catch any UnexpectedBattle exceptions from `action`. then use run_battle_press_A until overworld, and re-try the `action`. +void handle_unexpected_battles( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action +); + +// if stationary in overworld for an amount of time (seconds_stationary), run `recovery_action` then try `action` again +// return once successfully completed `action` +// throw exception if fails to complete `action` within a certain amount of time (minutes_timeout). +// NOTE: if using this function to wrap overworld_navigation(), keep in mind that +// confirm_marker_present() will keep the player still for 5 seconds before moving. Therefore, seconds_stationary should be greater than 5 seconds in this case. +void handle_when_stationary_in_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t seconds_stationary = 6, + uint16_t minutes_timeout = 5, + size_t max_attempts = 2 +); + +// do action. if error is thrown, catch the error and try the recovery action +void handle_failed_action( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& action, + std::function< + void(const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context) + >&& recovery_action, + size_t max_failures +); + +void wait_for_gradient_arrow( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox box_area_to_check, + uint16_t seconds_timeout +); + +void wait_for_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + uint16_t seconds_timeout = 30 +); + +void press_A_until_dialog( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint16_t seconds_between_button_presses +); + +// return true if ride is active. i.e. if you are on your ride +bool is_ride_active(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void get_on_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void get_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void get_on_or_off_ride(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool get_on); + + +// change the settings prior to Autostory +// Assumes that `current_segment` represents where we currently are in the story. +void change_settings_prior_to_autostory( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + size_t current_segment_num, + Language language +); + +// from within the Settings/Options menu, change the settings +void change_settings(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Language language, bool use_inference = true); + + +void checkpoint_save(SingleSwitchProgramEnvironment& env, ProControllerContext& context, EventNotificationOption& notif_status_update); + +enum class ZoomChange{ + ZOOM_IN, + ZOOM_IN_TWICE, + ZOOM_OUT, + ZOOM_OUT_TWICE, + KEEP_ZOOM, +}; + +struct MoveCursor{ + ZoomChange zoom_change; + uint8_t move_x; + uint8_t move_y; + uint16_t move_duration; +}; + +// place a marker on the map, not relative to the current player position, but based on a fixed landmark, such as a pokecenter +// How this works: +// - cursor is moved to a point near the landmark, as per `move_cursor_near_landmark` +// - move the cursor onto the landmark using `detect_closest_pokecenter_and_move_map_cursor_there`. +// - confirm that the pokecenter is centered within cursor. If not, close map app, and re-try. +// - cursor is moved to target location, as per `move_cursor_to_target`. A marker is placed down here. +void realign_player_from_landmark( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_landmark, + MoveCursor move_cursor_to_target +); + +// confirm that the cursor is centered on the pokecenter, within the map app +// else throw exception +void confirm_cursor_centered_on_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// open map, then move cursor to a point near a flypoint as per `move_cursor_near_flypoint` +// then fly to the closest pokecenter near the cursor +void move_cursor_towards_flypoint_and_go_there( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + MoveCursor move_cursor_near_flypoint +); + + +void check_num_sunflora_found(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int expected_number); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp index 3ffaf6e96d..3c2319d1b9 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.cpp @@ -1,81 +1,81 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_00.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -std::string AutoStory_Segment_00::name() const{ - return "00: Intro Cutscene"; -} - - -std::string AutoStory_Segment_00::start_text() const{ - return "Start: Intro cutscene."; -} - -std::string AutoStory_Segment_00::end_text() const{ - return "End: Finished cutscene."; -} - -void AutoStory_Segment_00::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 00: Intro Cutscene", COLOR_ORANGE); - - checkpoint_00(env, context); - - context.wait_for_all_requests(); - env.console.log("End Segment 00: Intro Cutscene", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); -} - - -void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - - // Mash A through intro cutscene, until the L stick button is detected - WhiteButtonWatcher leftstick(COLOR_GREEN, WhiteButton::ButtonLStick, {0.435, 0.912, 0.046, 0.047}); - context.wait_for_all_requests(); - run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 240 * TICKS_PER_SECOND); - }, - {leftstick} - ); - - // Stand up from chair and walk to left side of room - pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 0, 128, 6 * TICKS_PER_SECOND, 1 * TICKS_PER_SECOND); - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_00.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +std::string AutoStory_Segment_00::name() const{ + return "00: Intro Cutscene"; +} + + +std::string AutoStory_Segment_00::start_text() const{ + return "Start: Intro cutscene."; +} + +std::string AutoStory_Segment_00::end_text() const{ + return "End: Finished cutscene."; +} + +void AutoStory_Segment_00::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 00: Intro Cutscene", COLOR_ORANGE); + + checkpoint_00(env, context); + + context.wait_for_all_requests(); + env.console.log("End Segment 00: Intro Cutscene", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); +} + + +void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + + // Mash A through intro cutscene, until the L stick button is detected + WhiteButtonWatcher leftstick(COLOR_GREEN, WhiteButton::ButtonLStick, {0.435, 0.912, 0.046, 0.047}); + context.wait_for_all_requests(); + run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 240 * TICKS_PER_SECOND); + }, + {leftstick} + ); + + // Stand up from chair and walk to left side of room + pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 0, 128, 6 * TICKS_PER_SECOND, 1 * TICKS_PER_SECOND); + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h index e9abe3156c..f39edbf6a4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_00.h @@ -1,36 +1,36 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_00_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_00_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_00 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: after selecting character name, style and the cutscene has started -// end: stood up from chair. Walked to left side of room. -void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_00_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_00_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_00 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: after selecting character name, style and the cutscene has started +// end: stood up from chair. Walked to left side of room. +void checkpoint_00(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp index aa8cf395ae..600d19a99a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.cpp @@ -1,297 +1,297 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_01.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_01::name() const{ - return "01: Pick Starter"; -} - - -std::string AutoStory_Segment_01::start_text() const{ - return "Start: Finished cutscene."; -} - -std::string AutoStory_Segment_01::end_text() const{ - return "End: Picked the starter."; -} - -void AutoStory_Segment_01::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 01: Pick Starter", COLOR_ORANGE); - - checkpoint_01(env, context, options.notif_status_update, options.language); - checkpoint_02(env, context, options.notif_status_update); - checkpoint_03(env, context, options.notif_status_update, options.language, options.starter_choice); - - context.wait_for_all_requests(); - env.console.log("End Segment 01: Pick Starter", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_01( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language -){ -AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if(first_attempt){ - save_game_tutorial(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); - } - - context.wait_for_all_requests(); - // set settings - enter_menu_from_overworld(env.program_info(), env.console, context, 0, MenuSide::RIGHT, false); - change_settings(env, context, language, first_attempt); - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - break; - }catch(...){ - // (void)e; - first_attempt = false; - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_02( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if(first_attempt){ - save_game_tutorial(env.program_info(), env.console, context); - stats.m_checkpoint++; - env.update_stats(); - send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); - first_attempt = false; - } - - context.wait_for_all_requests(); - env.console.log("Go downstairs, get stopped by Skwovet"); - env.console.overlay().add_log("Go downstairs, get stopped by Skwovet", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 0, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 20); - pbf_wait(context, 5 * TICKS_PER_SECOND); - // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - - context.wait_for_all_requests(); - env.console.log("Go to the kitchen, talk with mom"); - env.console.overlay().add_log("Go to the kitchen, talk with mom", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 255, 2 * TICKS_PER_SECOND, 20); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); - - env.console.log("clear_dialog: Talk with Mom."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - - context.wait_for_all_requests(); - env.console.log("Go to the front door, talk with Clavell"); - env.console.overlay().add_log("Go to the front door, talk with Clavell", COLOR_WHITE); - pbf_move_left_joystick(context, 230, 200, 2 * TICKS_PER_SECOND, 20); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 255, 128); - - env.console.log("clear_dialog: Talk with Clavell at front door."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - - context.wait_for_all_requests(); - env.console.log("Go upstairs, dress up"); - env.console.overlay().add_log("Go upstairs, dress up", COLOR_WHITE); - pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 185, 10, 1 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 255, 128, 4 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 110, 200, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); - pbf_mash_button(context, BUTTON_A, 20 * TICKS_PER_SECOND); - - context.wait_for_all_requests(); - env.console.log("Go to the living room, talk with Clavell"); - env.console.overlay().add_log("Go to the living room, talk with Clavell", COLOR_WHITE); - pbf_move_left_joystick(context, 0, 0, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); - pbf_move_left_joystick(context, 128, 255, 4 * TICKS_PER_SECOND, 20); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); - - env.console.log("clear_dialog: Talk with Clavell at living room."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - - context.wait_for_all_requests(); - env.console.log("Go outside, receive Rotom Phone"); - env.console.overlay().add_log("Go outside, receive Rotom Phone", COLOR_WHITE); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 245, 230); - - env.console.log("clear_dialog: Talk with Clavell outside. Receive Rotom phone. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::WHITE_A_BUTTON}); - - context.wait_for_all_requests(); - env.console.log("Clear map tutorial"); - open_map_from_overworld(env.program_info(), env.console, context, true); - leave_phone_to_overworld(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_03( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language, - StarterChoice starter_choice -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 4.62); - pbf_move_left_joystick(context, 128, 0, 3600, 50); - pbf_move_left_joystick(context, 0, 128, 30, 50); - - direction.change_direction(env.program_info(), env.console, context, 4.62); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - - context.wait_for_all_requests(); - env.console.log("Entered Nemona's house"); - mash_button_till_overworld(env.console, context); - context.wait_for_all_requests(); - env.console.log("Picking a starter..."); - switch(starter_choice){ - case StarterChoice::SPRIGATITO: - env.console.log("Picking Sprigatito..."); - pbf_move_left_joystick(context, 75, 0, 80, 20); - break; - case StarterChoice::FUECOCO: - env.console.log("Picking Fuecoco..."); - pbf_move_left_joystick(context, 180, 0, 80, 20); - break; - case StarterChoice::QUAXLY: - env.console.log("Picking Quaxly..."); - pbf_move_left_joystick(context, 128, 0, 80, 20); - break; - } - pbf_press_button(context, BUTTON_A, 20, 105); // choose the starter - env.console.log("clear_dialog: Choose starter. Stop when detect prompt to receive starter."); - clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); - - pbf_press_button(context, BUTTON_A, 20, 105); // accept the pokemon - env.console.log("clear_dialog: Stop when detect prompt to give nickname to starter."); - clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); - - pbf_mash_button(context, BUTTON_B, 100); // Don't give a nickname - env.console.log("clear_dialog: Talk to Nemona and Clavell. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 20, {CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - env.console.log("Clear auto heal tutorial."); - // Press X until Auto heal tutorial shows up - TutorialWatcher tutorial; - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_X, 20, 250); - } - }, - {tutorial} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Stuck trying to clear auto heal tutorial.", - env.console - ); - } - clear_tutorial(env.console, context); - - env.console.log("Change move order."); - swap_starter_moves(env.program_info(), env.console, context, language); - leave_box_system_to_overworld(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_01.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_01::name() const{ + return "01: Pick Starter"; +} + + +std::string AutoStory_Segment_01::start_text() const{ + return "Start: Finished cutscene."; +} + +std::string AutoStory_Segment_01::end_text() const{ + return "End: Picked the starter."; +} + +void AutoStory_Segment_01::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 01: Pick Starter", COLOR_ORANGE); + + checkpoint_01(env, context, options.notif_status_update, options.language); + checkpoint_02(env, context, options.notif_status_update); + checkpoint_03(env, context, options.notif_status_update, options.language, options.starter_choice); + + context.wait_for_all_requests(); + env.console.log("End Segment 01: Pick Starter", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_01( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language +){ +AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if(first_attempt){ + save_game_tutorial(env.program_info(), env.console, context); + stats.m_checkpoint++; + env.update_stats(); + send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); + } + + context.wait_for_all_requests(); + // set settings + enter_menu_from_overworld(env.program_info(), env.console, context, 0, MenuSide::RIGHT, false); + change_settings(env, context, language, first_attempt); + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + break; + }catch(...){ + // (void)e; + first_attempt = false; + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_02( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if(first_attempt){ + save_game_tutorial(env.program_info(), env.console, context); + stats.m_checkpoint++; + env.update_stats(); + send_program_status_notification(env, notif_status_update, "Saved at checkpoint."); + first_attempt = false; + } + + context.wait_for_all_requests(); + env.console.log("Go downstairs, get stopped by Skwovet"); + env.console.overlay().add_log("Go downstairs, get stopped by Skwovet", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 0, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 128, 255, 3 * TICKS_PER_SECOND, 20); + pbf_wait(context, 5 * TICKS_PER_SECOND); + // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + + context.wait_for_all_requests(); + env.console.log("Go to the kitchen, talk with mom"); + env.console.overlay().add_log("Go to the kitchen, talk with mom", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 255, 2 * TICKS_PER_SECOND, 20); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); + + env.console.log("clear_dialog: Talk with Mom."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + + context.wait_for_all_requests(); + env.console.log("Go to the front door, talk with Clavell"); + env.console.overlay().add_log("Go to the front door, talk with Clavell", COLOR_WHITE); + pbf_move_left_joystick(context, 230, 200, 2 * TICKS_PER_SECOND, 20); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 255, 128); + + env.console.log("clear_dialog: Talk with Clavell at front door."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + + context.wait_for_all_requests(); + env.console.log("Go upstairs, dress up"); + env.console.overlay().add_log("Go upstairs, dress up", COLOR_WHITE); + pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 185, 10, 1 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 255, 128, 4 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 110, 200, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 255, 128, 2 * TICKS_PER_SECOND, 20); + pbf_mash_button(context, BUTTON_A, 20 * TICKS_PER_SECOND); + + context.wait_for_all_requests(); + env.console.log("Go to the living room, talk with Clavell"); + env.console.overlay().add_log("Go to the living room, talk with Clavell", COLOR_WHITE); + pbf_move_left_joystick(context, 0, 0, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 0, 128, 3 * TICKS_PER_SECOND, 20); + pbf_move_left_joystick(context, 128, 255, 4 * TICKS_PER_SECOND, 20); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 0, 128); + + env.console.log("clear_dialog: Talk with Clavell at living room."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + + context.wait_for_all_requests(); + env.console.log("Go outside, receive Rotom Phone"); + env.console.overlay().add_log("Go outside, receive Rotom Phone", COLOR_WHITE); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 245, 230); + + env.console.log("clear_dialog: Talk with Clavell outside. Receive Rotom phone. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::WHITE_A_BUTTON}); + + context.wait_for_all_requests(); + env.console.log("Clear map tutorial"); + open_map_from_overworld(env.program_info(), env.console, context, true); + leave_phone_to_overworld(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_03( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language, + StarterChoice starter_choice +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 4.62); + pbf_move_left_joystick(context, 128, 0, 3600, 50); + pbf_move_left_joystick(context, 0, 128, 30, 50); + + direction.change_direction(env.program_info(), env.console, context, 4.62); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + + context.wait_for_all_requests(); + env.console.log("Entered Nemona's house"); + mash_button_till_overworld(env.console, context); + context.wait_for_all_requests(); + env.console.log("Picking a starter..."); + switch(starter_choice){ + case StarterChoice::SPRIGATITO: + env.console.log("Picking Sprigatito..."); + pbf_move_left_joystick(context, 75, 0, 80, 20); + break; + case StarterChoice::FUECOCO: + env.console.log("Picking Fuecoco..."); + pbf_move_left_joystick(context, 180, 0, 80, 20); + break; + case StarterChoice::QUAXLY: + env.console.log("Picking Quaxly..."); + pbf_move_left_joystick(context, 128, 0, 80, 20); + break; + } + pbf_press_button(context, BUTTON_A, 20, 105); // choose the starter + env.console.log("clear_dialog: Choose starter. Stop when detect prompt to receive starter."); + clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); + + pbf_press_button(context, BUTTON_A, 20, 105); // accept the pokemon + env.console.log("clear_dialog: Stop when detect prompt to give nickname to starter."); + clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 20, {CallbackEnum::PROMPT_DIALOG}); + + pbf_mash_button(context, BUTTON_B, 100); // Don't give a nickname + env.console.log("clear_dialog: Talk to Nemona and Clavell. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 20, {CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + env.console.log("Clear auto heal tutorial."); + // Press X until Auto heal tutorial shows up + TutorialWatcher tutorial; + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_X, 20, 250); + } + }, + {tutorial} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Stuck trying to clear auto heal tutorial.", + env.console + ); + } + clear_tutorial(env.console, context); + + env.console.log("Change move order."); + swap_starter_moves(env.program_info(), env.console, context, language); + leave_box_system_to_overworld(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h index 0a58727f29..024cabf697 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_01.h @@ -1,59 +1,59 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_01_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_01_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_01 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: stood up from chair. Walked to left side of room. -// end: standing in room. updated settings -void checkpoint_01( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language -); - -// start: standing in room. updated settings -// end: standing in front of power of science NPC. Cleared map tutorial. -void checkpoint_02( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: standing in front of power of science NPC. Cleared map tutorial. -// end: received starter, changed move order -void checkpoint_03( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update, - Language language, - StarterChoice starter_choice -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_01_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_01_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_01 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: stood up from chair. Walked to left side of room. +// end: standing in room. updated settings +void checkpoint_01( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language +); + +// start: standing in room. updated settings +// end: standing in front of power of science NPC. Cleared map tutorial. +void checkpoint_02( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: standing in front of power of science NPC. Cleared map tutorial. +// end: received starter, changed move order +void checkpoint_03( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update, + Language language, + StarterChoice starter_choice +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp index 1c2b515b1a..e28de2efcb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.cpp @@ -1,112 +1,112 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_02.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_02::name() const{ - return "02: First Nemona Battle"; -} - -std::string AutoStory_Segment_02::start_text() const{ - return "Start: Picked the starter."; -} - -std::string AutoStory_Segment_02::end_text() const{ - return "End: Battled Nemona on the beach."; -} - -void AutoStory_Segment_02::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 02: First Nemona Battle", COLOR_ORANGE); - - checkpoint_04(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 02: First Nemona Battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_04( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 3.72); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 4.55); - pbf_move_left_joystick(context, 128, 0, 600, 50); - direction.change_direction(env.program_info(), env.console, context, 5.27); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); - - context.wait_for_all_requests(); - env.console.log("Starting battle..."); - // TODO: Battle start prompt detection - // can lose this battle, and story will continue - mash_button_till_overworld(env.console, context); - context.wait_for_all_requests(); - env.console.log("Finished battle."); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_02.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_02::name() const{ + return "02: First Nemona Battle"; +} + +std::string AutoStory_Segment_02::start_text() const{ + return "Start: Picked the starter."; +} + +std::string AutoStory_Segment_02::end_text() const{ + return "End: Battled Nemona on the beach."; +} + +void AutoStory_Segment_02::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 02: First Nemona Battle", COLOR_ORANGE); + + checkpoint_04(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 02: First Nemona Battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_04( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 3.72); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 4.55); + pbf_move_left_joystick(context, 128, 0, 600, 50); + direction.change_direction(env.program_info(), env.console, context, 5.27); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); + + context.wait_for_all_requests(); + env.console.log("Starting battle..."); + // TODO: Battle start prompt detection + // can lose this battle, and story will continue + mash_button_till_overworld(env.console, context); + context.wait_for_all_requests(); + env.console.log("Finished battle."); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h index 0409ae8ca8..c440327663 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_02.h @@ -1,41 +1,41 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_02_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_02_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_02 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Received starter pokemon and changed move order. Cleared autoheal tutorial. -// end: Battled Nemona on the beach. -void checkpoint_04( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_02_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_02_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_02 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Received starter pokemon and changed move order. Cleared autoheal tutorial. +// end: Battled Nemona on the beach. +void checkpoint_04( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp index 73becf4f43..7e3de20acb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.cpp @@ -1,206 +1,206 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_03.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_03::name() const{ - return "03: Catch Tutorial"; -} - -std::string AutoStory_Segment_03::start_text() const{ - return "Start: Battled Nemona on the beach."; -} - -std::string AutoStory_Segment_03::end_text() const{ - return "End: Finished catch tutorial. Walked to the cliff and heard mystery cry."; -} - -void AutoStory_Segment_03::run_segment(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AutoStoryOptions options) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 03: Catch Tutorial", COLOR_ORANGE); - - checkpoint_05(env, context, options.notif_status_update); - checkpoint_06(env, context, options.notif_status_update); - checkpoint_07(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 03: Catch Tutorial", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_05( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 1.92); - pbf_move_left_joystick(context, 128, 0, 7 * TICKS_PER_SECOND, 50); - direction.change_direction(env.program_info(), env.console, context, 1.13); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - - context.wait_for_all_requests(); - env.console.log("Get mom's sandwich"); - env.console.overlay().add_log("Get mom's sandwich", COLOR_WHITE); - mash_button_till_overworld(env.console, context); - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_06( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 40, 82, 60); - pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 10, 60); - env.console.log("overworld_navigation: Go to Nemona."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); - - context.wait_for_all_requests(); - env.console.log("clear_dialog: Talk with Nemona to start catch tutorial. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, - {CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE}); - - // can die in catch tutorial, and the story will continue - env.console.log("run_battle_press_A: Battle Lechonk in catch tutorial. Stop when detect dialog."); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - - env.console.log("clear_dialog: Talk with Nemona to finish catch tutorial. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - env.console.log("Finished catch tutorial"); - env.console.overlay().add_log("Finished catch tutorial", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_07( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - env.console.log("Move to cliff"); - env.console.overlay().add_log("Move to cliff", COLOR_WHITE); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 70, 100); - env.console.log("overworld_navigation: Go to cliff."); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 135, 0, 24, 12, true, true); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 80); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 12, true, true); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - env.console.log("Mystery cry"); - env.console.overlay().add_log("Mystery cry", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_03.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_03::name() const{ + return "03: Catch Tutorial"; +} + +std::string AutoStory_Segment_03::start_text() const{ + return "Start: Battled Nemona on the beach."; +} + +std::string AutoStory_Segment_03::end_text() const{ + return "End: Finished catch tutorial. Walked to the cliff and heard mystery cry."; +} + +void AutoStory_Segment_03::run_segment(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AutoStoryOptions options) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 03: Catch Tutorial", COLOR_ORANGE); + + checkpoint_05(env, context, options.notif_status_update); + checkpoint_06(env, context, options.notif_status_update); + checkpoint_07(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 03: Catch Tutorial", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_05( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 1.92); + pbf_move_left_joystick(context, 128, 0, 7 * TICKS_PER_SECOND, 50); + direction.change_direction(env.program_info(), env.console, context, 1.13); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + + context.wait_for_all_requests(); + env.console.log("Get mom's sandwich"); + env.console.overlay().add_log("Get mom's sandwich", COLOR_WHITE); + mash_button_till_overworld(env.console, context); + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_06( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 40, 82, 60); + pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 10, 60); + env.console.log("overworld_navigation: Go to Nemona."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); + + context.wait_for_all_requests(); + env.console.log("clear_dialog: Talk with Nemona to start catch tutorial. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, + {CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE}); + + // can die in catch tutorial, and the story will continue + env.console.log("run_battle_press_A: Battle Lechonk in catch tutorial. Stop when detect dialog."); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + + env.console.log("clear_dialog: Talk with Nemona to finish catch tutorial. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + env.console.log("Finished catch tutorial"); + env.console.overlay().add_log("Finished catch tutorial", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_07( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + env.console.log("Move to cliff"); + env.console.overlay().add_log("Move to cliff", COLOR_WHITE); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 70, 100); + env.console.log("overworld_navigation: Go to cliff."); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 135, 0, 24, 12, true, true); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 80); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 12, true, true); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + env.console.log("Mystery cry"); + env.console.overlay().add_log("Mystery cry", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h index 949f113349..3fdca90f92 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_03.h @@ -1,56 +1,56 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_03_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_03_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_03 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options) const override; -}; - - -// start: Battled Nemona on the beach. -// end: Met mom at gate. Received mom's sandwich. -void checkpoint_05( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Met mom at gate. Received mom's sandwich. -// end: Cleared catch tutorial. -void checkpoint_06( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Cleared catch tutorial. -// end: Moved to cliff. Heard mystery cry. -void checkpoint_07( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_03_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_03_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_03 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options) const override; +}; + + +// start: Battled Nemona on the beach. +// end: Met mom at gate. Received mom's sandwich. +void checkpoint_05( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Met mom at gate. Received mom's sandwich. +// end: Cleared catch tutorial. +void checkpoint_06( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Cleared catch tutorial. +// end: Moved to cliff. Heard mystery cry. +void checkpoint_07( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp index a1d9345c37..51a58384a0 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.cpp @@ -1,211 +1,211 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_04.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_04::name() const{ - return "04: Rescue Legendary"; -} - -std::string AutoStory_Segment_04::start_text() const{ - return "Start: Finished catch tutorial. Walked to the cliff and heard mystery cry."; -} - -std::string AutoStory_Segment_04::end_text() const{ - return "End: Saved the Legendary. Escaped from the Houndoom cave."; -} - -void AutoStory_Segment_04::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 04: Rescue Legendary", COLOR_ORANGE); - - checkpoint_08(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 04: Rescue Legendary", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_08( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 70, 100); - env.console.log("overworld_navigation: Go to cliff."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 30, 30, true, true); - - env.console.log("Look over the injured Miraidon/Koraidon on the beach."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); - env.console.log("Fall down the cliff."); - pbf_wait(context, 20 * TICKS_PER_SECOND); // long animation - context.wait_for_all_requests(); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - env.console.log("Go to Legendary pokemon laying on the beach."); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 30); - - env.console.log("clear_dialog: Offer Miraidon/Koraidon a sandwich."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - - // TODO: Bag menu navigation - context.wait_for_all_requests(); - env.console.log("Feed mom's sandwich"); - env.console.overlay().add_log("Feed mom's sandwich", COLOR_WHITE); - - GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, {0.104, 0.312, 0.043, 0.08}); - context.wait_for_all_requests(); - - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - pbf_press_dpad(context, DPAD_UP, 20, 250); - } - }, - {arrow} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to feed mom's sandwich.", - env.console - ); - } - - // only press A when the sandwich is selected - pbf_mash_button(context, BUTTON_A, 100); - - env.console.log("Miraidon/Koraidon eats the sandwich."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, {}); - env.console.log("Miraidon/Koraidon gets up and walks to cave entrance."); // long animation - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); - - // First Nemona cave conversation - context.wait_for_all_requests(); - env.console.log("Enter cave"); - env.console.overlay().add_log("Enter cave", COLOR_WHITE); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 600, 50); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 20, 20); - pbf_move_left_joystick(context, 128, 0, 1000, 50); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 160, 20, 20); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 20, true, true); - } - ); - - env.console.log("clear_dialog: Talk to Nemona yelling down, while you're down in the cave."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {CallbackEnum::PROMPT_DIALOG}); - - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - // Legendary rock break - context.wait_for_all_requests(); - stream.log("Rock break"); - stream.overlay().add_log("Rock break", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 230, 25, 30); - pbf_move_left_joystick(context, 128, 0, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - - // Houndour wave - context.wait_for_all_requests(); - stream.log("Houndour wave"); - stream.overlay().add_log("Houndour wave", COLOR_WHITE); - // walk to room entrance - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 15, 30); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 15, 30); - pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 200, 25, 20); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 25, 25); - pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 20 * TICKS_PER_SECOND); - - // Houndoom encounter - context.wait_for_all_requests(); - stream.log("Houndoom encounter"); - stream.overlay().add_log("Houndoom encounter", COLOR_WHITE); - pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 245, 20, 20); - pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 20); - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 255, 90, 20); - pbf_move_left_joystick(context, 128, 20, 8 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_L, 20, 20); - } - ); - - env.console.log("overworld_navigation: Go to Houndoom."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); - - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_04.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_04::name() const{ + return "04: Rescue Legendary"; +} + +std::string AutoStory_Segment_04::start_text() const{ + return "Start: Finished catch tutorial. Walked to the cliff and heard mystery cry."; +} + +std::string AutoStory_Segment_04::end_text() const{ + return "End: Saved the Legendary. Escaped from the Houndoom cave."; +} + +void AutoStory_Segment_04::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 04: Rescue Legendary", COLOR_ORANGE); + + checkpoint_08(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 04: Rescue Legendary", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_08( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 70, 100); + env.console.log("overworld_navigation: Go to cliff."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 30, 30, true, true); + + env.console.log("Look over the injured Miraidon/Koraidon on the beach."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5, {}); + env.console.log("Fall down the cliff."); + pbf_wait(context, 20 * TICKS_PER_SECOND); // long animation + context.wait_for_all_requests(); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + env.console.log("Go to Legendary pokemon laying on the beach."); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 30); + + env.console.log("clear_dialog: Offer Miraidon/Koraidon a sandwich."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + + // TODO: Bag menu navigation + context.wait_for_all_requests(); + env.console.log("Feed mom's sandwich"); + env.console.overlay().add_log("Feed mom's sandwich", COLOR_WHITE); + + GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::RIGHT, {0.104, 0.312, 0.043, 0.08}); + context.wait_for_all_requests(); + + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + pbf_press_dpad(context, DPAD_UP, 20, 250); + } + }, + {arrow} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to feed mom's sandwich.", + env.console + ); + } + + // only press A when the sandwich is selected + pbf_mash_button(context, BUTTON_A, 100); + + env.console.log("Miraidon/Koraidon eats the sandwich."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, {}); + env.console.log("Miraidon/Koraidon gets up and walks to cave entrance."); // long animation + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {}); + + // First Nemona cave conversation + context.wait_for_all_requests(); + env.console.log("Enter cave"); + env.console.overlay().add_log("Enter cave", COLOR_WHITE); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 600, 50); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 20, 20); + pbf_move_left_joystick(context, 128, 0, 1000, 50); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 160, 20, 20); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 20, true, true); + } + ); + + env.console.log("clear_dialog: Talk to Nemona yelling down, while you're down in the cave."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, {CallbackEnum::PROMPT_DIALOG}); + + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + // Legendary rock break + context.wait_for_all_requests(); + stream.log("Rock break"); + stream.overlay().add_log("Rock break", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 230, 25, 30); + pbf_move_left_joystick(context, 128, 0, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + + // Houndour wave + context.wait_for_all_requests(); + stream.log("Houndour wave"); + stream.overlay().add_log("Houndour wave", COLOR_WHITE); + // walk to room entrance + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 150, 15, 30); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 15, 30); + pbf_move_left_joystick(context, 128, 20, 3 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 200, 25, 20); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 210, 25, 25); + pbf_move_left_joystick(context, 128, 20, 6 * TICKS_PER_SECOND, 20 * TICKS_PER_SECOND); + + // Houndoom encounter + context.wait_for_all_requests(); + stream.log("Houndoom encounter"); + stream.overlay().add_log("Houndoom encounter", COLOR_WHITE); + pbf_move_left_joystick(context, 128, 20, 4 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 245, 20, 20); + pbf_move_left_joystick(context, 128, 20, 2 * TICKS_PER_SECOND, 20); + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NO_MARKER, 255, 90, 20); + pbf_move_left_joystick(context, 128, 20, 8 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_L, 20, 20); + } + ); + + env.console.log("overworld_navigation: Go to Houndoom."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, 128, 0, 20, 20, true, true); + + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h index 1879b5cf2b..e4219391a8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_04.h @@ -1,41 +1,41 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_04_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_04_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_04 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Moved to cliff. Heard mystery cry. -// end: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. -void checkpoint_08( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_04_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_04_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_04 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Moved to cliff. Heard mystery cry. +// end: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. +void checkpoint_08( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp index 575bdd013f..dcc80e782c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.cpp @@ -1,161 +1,161 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_05.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_05::name() const{ - return "05: First Arven Battle"; -} - -std::string AutoStory_Segment_05::start_text() const{ - return "Start: Saved the Legendary. Escaped from the Houndoom cave."; -} - -std::string AutoStory_Segment_05::end_text() const{ - return "End: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; -} - -void AutoStory_Segment_05::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 05: First Arven Battle", COLOR_ORANGE); - - checkpoint_09(env, context, options.notif_status_update); - checkpoint_10(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 05: First Arven Battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_09( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 110, 50); - env.console.log("overworld_navigation: Go to Arven at the tower."); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 30, true, true); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - context.wait_for_all_requests(); - env.console.log("Found Arven"); - env.console.overlay().add_log("Found Arven", COLOR_WHITE); - // can lose battle, and story will still continue - mash_button_till_overworld(env.console, context, BUTTON_A); - context.wait_for_all_requests(); - env.console.log("Receive legendary ball"); - env.console.overlay().add_log("Receive legendary ball", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - -void checkpoint_10( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - env.console.log("Lighthouse view"); - env.console.overlay().add_log("Lighthouse view", COLOR_WHITE); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 110, 100); - pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); - } - ); - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 5.41); - - env.console.log("overworld_navigation: Go to Nemona on the lighthouse."); - overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, 128, 0, 20, 20, true, true); - - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_05.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_05::name() const{ + return "05: First Arven Battle"; +} + +std::string AutoStory_Segment_05::start_text() const{ + return "Start: Saved the Legendary. Escaped from the Houndoom cave."; +} + +std::string AutoStory_Segment_05::end_text() const{ + return "End: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; +} + +void AutoStory_Segment_05::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 05: First Arven Battle", COLOR_ORANGE); + + checkpoint_09(env, context, options.notif_status_update); + checkpoint_10(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 05: First Arven Battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_09( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 110, 50); + env.console.log("overworld_navigation: Go to Arven at the tower."); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 30, true, true); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + context.wait_for_all_requests(); + env.console.log("Found Arven"); + env.console.overlay().add_log("Found Arven", COLOR_WHITE); + // can lose battle, and story will still continue + mash_button_till_overworld(env.console, context, BUTTON_A); + context.wait_for_all_requests(); + env.console.log("Receive legendary ball"); + env.console.overlay().add_log("Receive legendary ball", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + +void checkpoint_10( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + env.console.log("Lighthouse view"); + env.console.overlay().add_log("Lighthouse view", COLOR_WHITE); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 230, 110, 100); + pbf_move_left_joystick(context, 128, 0, 6 * TICKS_PER_SECOND, 8 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 20); + } + ); + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 5.41); + + env.console.log("overworld_navigation: Go to Nemona on the lighthouse."); + overworld_navigation(env.program_info(), env.console, context, NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, 128, 0, 20, 20, true, true); + + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h index 4e3e6103cf..9f07103b7c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_05.h @@ -1,48 +1,48 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_05_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_05_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_05 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. -// end: Battled Arven and received Legendary's Pokeball. -void checkpoint_09( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Battled Arven and received Legendary's Pokeball. -// end: Talked to Nemona at the Lighthouse. -void checkpoint_10( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_05_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_05_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_05 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Rescued Koraidon/Miraidon and escaped from the Houndoom Cave. +// end: Battled Arven and received Legendary's Pokeball. +void checkpoint_09( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Battled Arven and received Legendary's Pokeball. +// end: Talked to Nemona at the Lighthouse. +void checkpoint_10( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp index 0500b7a65e..4678865172 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.cpp @@ -1,128 +1,128 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_06.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_06::name() const{ - return "06: Go to Los Platos"; -} - -std::string AutoStory_Segment_06::start_text() const{ - return "Start: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; -} - -std::string AutoStory_Segment_06::end_text() const{ - return "End: At Los Platos Pokecenter."; -} - -void AutoStory_Segment_06::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 06: Go to Los Platos", COLOR_ORANGE); - - checkpoint_11(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 06: Go to Los Platos", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_11( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - context.wait_for_all_requests(); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 210, 100); - pbf_move_left_joystick(context, 128, 0, 187, 20); - pbf_move_left_joystick(context, 0, 128, 30, 8 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, 0, 1 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - - realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 60, 200); - } - ); - - env.console.log("overworld_navigation: Go to Los Platos."); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 75, 75, true, true); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - - env.console.log("clear_dialog: Talk with Nemona at Los Platos. Clear Let's go tutorial. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); - - context.wait_for_all_requests(); - - env.console.log("Reached Los Platos"); - env.console.overlay().add_log("Reached Los Platos", COLOR_WHITE); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_06.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_06::name() const{ + return "06: Go to Los Platos"; +} + +std::string AutoStory_Segment_06::start_text() const{ + return "Start: Battled Arven, received Legendary's Pokeball. Talked to Nemona at Lighthouse."; +} + +std::string AutoStory_Segment_06::end_text() const{ + return "End: At Los Platos Pokecenter."; +} + +void AutoStory_Segment_06::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 06: Go to Los Platos", COLOR_ORANGE); + + checkpoint_11(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 06: Go to Los Platos", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_11( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + context.wait_for_all_requests(); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 210, 100); + pbf_move_left_joystick(context, 128, 0, 187, 20); + pbf_move_left_joystick(context, 0, 128, 30, 8 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, 0, 1 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + + realign_player(info, stream, context, PlayerRealignMode::REALIGN_NEW_MARKER, 100, 60, 200); + } + ); + + env.console.log("overworld_navigation: Go to Los Platos."); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 75, 75, true, true); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + + env.console.log("clear_dialog: Talk with Nemona at Los Platos. Clear Let's go tutorial. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::TUTORIAL, CallbackEnum::OVERWORLD}); + + context.wait_for_all_requests(); + + env.console.log("Reached Los Platos"); + env.console.overlay().add_log("Reached Los Platos", COLOR_WHITE); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h index a608b5f770..9d424ea682 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_06.h @@ -1,40 +1,40 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_06_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_06_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_06 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Talked to Nemona at the Lighthouse. -// end: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. -void checkpoint_11( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_06_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_06_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_06 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Talked to Nemona at the Lighthouse. +// end: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. +void checkpoint_11( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp index 74ff02c30f..5a393fa35d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.cpp @@ -1,138 +1,138 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_07.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_07::name() const{ - return "07: Go to Mesagoza South"; -} - -std::string AutoStory_Segment_07::start_text() const{ - return "Start: At Los Platos Pokecenter."; -} - -std::string AutoStory_Segment_07::end_text() const{ - return "End: At Mesagoza South Pokecenter."; -} - -void AutoStory_Segment_07::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 07: Go to Mesagoza South", COLOR_ORANGE); - - checkpoint_12(env, context, options.notif_status_update); - - // // Mystery Gift, delete later - // enter_menu_from_overworld(env.program_info(), env.console, context, 2); - // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); - // pbf_press_dpad(context, DPAD_UP, 20, 105); - // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); - // pbf_press_dpad(context, DPAD_DOWN, 20, 105); - // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); - // pbf_press_button(context, BUTTON_A, 20, 10 * TICKS_PER_SECOND); - // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10); - - context.wait_for_all_requests(); - env.console.log("End Segment 07: Go to Mesagoza South", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_12( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - // reset rate: ~25%. 12 resets out of 52. - // resets due to: getting attacked by wild pokemon, either from behind, - // or when lead pokemon not strong enough to clear them with Let's go - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - context.wait_for_all_requests(); - - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 20); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_while_clear_front_path(env.program_info(), env.console, context, 35); - - // place the marker elsewhere - realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 50); - - DirectionDetector direction; - direction.change_direction(info, env.console, context, 0); - walk_forward_while_clear_front_path(info, env.console, context, 3300, 0, 125, 125); - - // check we're not still at the Los Platos Pokecenter. - confirm_no_overlapping_flypoint(info, env.console, context); - // not stuck at Los Platos Pokecenter - pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); - press_Bs_to_back_to_overworld(info, env.console, context, 7); - - direction.change_direction(info, env.console, context, 0.29); - walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); - direction.change_direction(info, env.console, context, 0.61); - walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); - - fly_to_overlapping_flypoint(info, env.console, context); - } - ); - - env.console.log("Reached Mesagoza (South) Pokecenter."); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_07.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_07::name() const{ + return "07: Go to Mesagoza South"; +} + +std::string AutoStory_Segment_07::start_text() const{ + return "Start: At Los Platos Pokecenter."; +} + +std::string AutoStory_Segment_07::end_text() const{ + return "End: At Mesagoza South Pokecenter."; +} + +void AutoStory_Segment_07::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 07: Go to Mesagoza South", COLOR_ORANGE); + + checkpoint_12(env, context, options.notif_status_update); + + // // Mystery Gift, delete later + // enter_menu_from_overworld(env.program_info(), env.console, context, 2); + // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); + // pbf_press_dpad(context, DPAD_UP, 20, 105); + // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); + // pbf_press_dpad(context, DPAD_DOWN, 20, 105); + // pbf_press_button(context, BUTTON_A, 20, 4 * TICKS_PER_SECOND); + // pbf_press_button(context, BUTTON_A, 20, 10 * TICKS_PER_SECOND); + // clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10); + + context.wait_for_all_requests(); + env.console.log("End Segment 07: Go to Mesagoza South", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_12( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + // reset rate: ~25%. 12 resets out of 52. + // resets due to: getting attacked by wild pokemon, either from behind, + // or when lead pokemon not strong enough to clear them with Let's go + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + context.wait_for_all_requests(); + + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 20); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_while_clear_front_path(env.program_info(), env.console, context, 35); + + // place the marker elsewhere + realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 50); + + DirectionDetector direction; + direction.change_direction(info, env.console, context, 0); + walk_forward_while_clear_front_path(info, env.console, context, 3300, 0, 125, 125); + + // check we're not still at the Los Platos Pokecenter. + confirm_no_overlapping_flypoint(info, env.console, context); + // not stuck at Los Platos Pokecenter + pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); + press_Bs_to_back_to_overworld(info, env.console, context, 7); + + direction.change_direction(info, env.console, context, 0.29); + walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); + direction.change_direction(info, env.console, context, 0.61); + walk_forward_while_clear_front_path(info, env.console, context, 1200, 0, 125, 125); + + fly_to_overlapping_flypoint(info, env.console, context); + } + ); + + env.console.log("Reached Mesagoza (South) Pokecenter."); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h index a059221d8b..b944d79f95 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_07.h @@ -1,40 +1,40 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_07_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_07_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_07 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. -// end: Arrived at Mesagoza (South) Pokecenter -void checkpoint_12( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_07_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_07_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_07 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Arrived at Los Platos pokecenter. Cleared Let's go tutorial. +// end: Arrived at Mesagoza (South) Pokecenter +void checkpoint_12( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp index 44e2a39401..d6b1911299 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.cpp @@ -1,219 +1,219 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_08.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_08::name() const{ - return "08: Beat Team Star and arrive at School"; -} - -std::string AutoStory_Segment_08::start_text() const{ - return "Start: At Mesagoza South Pokecenter."; -} - -std::string AutoStory_Segment_08::end_text() const{ - return "End: Battled Team Star, talked to Jacq, standing in classroom."; -} - -void AutoStory_Segment_08::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 08: Beat Team Star and arrive at School", COLOR_ORANGE); - - checkpoint_13(env, context, options.notif_status_update); - checkpoint_14(env, context, options.notif_status_update); - checkpoint_15(env, context, options.notif_status_update); - - - context.wait_for_all_requests(); - env.console.log("End Segment 08: Beat Team Star and arrive at School", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_13( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - // reset rate: 0%. 0 resets out of 70. - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - - fly_to_overlapping_flypoint(info, env.console, context); - - context.wait_for_all_requests(); - realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 80, 50); - walk_forward_while_clear_front_path(info, env.console, context, 500); - walk_forward_until_dialog(info, env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 30); - }); - - env.console.log("clear_dialog: Talk with Nemona at Mesagoza gate. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); - - env.console.log("run_battle_press_A: Battle with Nemona at Mesagoza gate. Stop when detect dialog."); - // story continues even if you lose - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - - env.console.log("clear_dialog: Talk with Nemona within Mesagoza. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON}); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_14( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // realign diagonally to the left - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 0, 100); - // walk forward so you're off center - pbf_move_left_joystick(context, 128, 0, 100, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); - // walk forward, while still off center - pbf_move_left_joystick(context, 128, 0, 2000, 100); - // realign diagonally to the right - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); - // walk forward so you're closer to the center - pbf_move_left_joystick(context, 128, 0, 150, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); - // walk forward until hit dialog at top of stairs - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); - // clear dialog until battle. with prompt, battle - env.console.log("clear_dialog: Talk with Team Star at the top of the stairs. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - // run battle until dialog - env.console.log("run_battle_press_A: Battle with Team Star grunt 1. Stop when detect dialog."); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); - // clear dialog until battle, with prompt, white button, tutorial, battle - env.console.log("clear_dialog: Talk with Team Star and Nemona. Receive Tera orb. Stop when detect battle."); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - // run battle until dialog - env.console.log("run_battle_press_A: Battle with Team Star grunt 2. Stop when detect dialog."); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); - // clear dialog until overworld - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_15( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // realign diagonally to the right - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); - // walk forward so you're closer to the center - pbf_move_left_joystick(context, 128, 0, 100, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); - // walk forward up stairs - pbf_move_left_joystick(context, 128, 0, 1000, 100); - // realign going straight - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - // walk forward until hit dialog inside the school - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); - - env.console.log("clear_dialog: Talk with Nemona, Clavell, and Jacq inside the school. Stop when detect overworld."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::OVERWORLD}); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_08.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_08::name() const{ + return "08: Beat Team Star and arrive at School"; +} + +std::string AutoStory_Segment_08::start_text() const{ + return "Start: At Mesagoza South Pokecenter."; +} + +std::string AutoStory_Segment_08::end_text() const{ + return "End: Battled Team Star, talked to Jacq, standing in classroom."; +} + +void AutoStory_Segment_08::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 08: Beat Team Star and arrive at School", COLOR_ORANGE); + + checkpoint_13(env, context, options.notif_status_update); + checkpoint_14(env, context, options.notif_status_update); + checkpoint_15(env, context, options.notif_status_update); + + + context.wait_for_all_requests(); + env.console.log("End Segment 08: Beat Team Star and arrive at School", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_13( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + // reset rate: 0%. 0 resets out of 70. + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + + fly_to_overlapping_flypoint(info, env.console, context); + + context.wait_for_all_requests(); + realign_player(info, env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 80, 50); + walk_forward_while_clear_front_path(info, env.console, context, 500); + walk_forward_until_dialog(info, env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 30); + }); + + env.console.log("clear_dialog: Talk with Nemona at Mesagoza gate. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); + + env.console.log("run_battle_press_A: Battle with Nemona at Mesagoza gate. Stop when detect dialog."); + // story continues even if you lose + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + + env.console.log("clear_dialog: Talk with Nemona within Mesagoza. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON}); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_14( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // realign diagonally to the left + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 0, 100); + // walk forward so you're off center + pbf_move_left_joystick(context, 128, 0, 100, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); + // walk forward, while still off center + pbf_move_left_joystick(context, 128, 0, 2000, 100); + // realign diagonally to the right + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); + // walk forward so you're closer to the center + pbf_move_left_joystick(context, 128, 0, 150, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); + // walk forward until hit dialog at top of stairs + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); + // clear dialog until battle. with prompt, battle + env.console.log("clear_dialog: Talk with Team Star at the top of the stairs. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + // run battle until dialog + env.console.log("run_battle_press_A: Battle with Team Star grunt 1. Stop when detect dialog."); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); + // clear dialog until battle, with prompt, white button, tutorial, battle + env.console.log("clear_dialog: Talk with Team Star and Nemona. Receive Tera orb. Stop when detect battle."); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::WHITE_A_BUTTON, CallbackEnum::TUTORIAL, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + // run battle until dialog + env.console.log("run_battle_press_A: Battle with Team Star grunt 2. Stop when detect dialog."); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); + // clear dialog until overworld + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_15( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // realign diagonally to the right + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 178, 0, 100); + // walk forward so you're closer to the center + pbf_move_left_joystick(context, 128, 0, 100, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 100); + // walk forward up stairs + pbf_move_left_joystick(context, 128, 0, 1000, 100); + // realign going straight + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + // walk forward until hit dialog inside the school + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60); + + env.console.log("clear_dialog: Talk with Nemona, Clavell, and Jacq inside the school. Stop when detect overworld."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::OVERWORLD}); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h index 7f9dbffae7..5ce89fc278 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_08.h @@ -1,57 +1,57 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_08_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_08_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_08 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: Arrived at Mesagoza (South) Pokecenter -// end: Battled Nemona at Mesagoza gate. Entered Mesagoza. -void checkpoint_13( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Battled Nemona at Mesagoza gate. Entered Mesagoza. -// end: Battled Team Star at school entrance. -void checkpoint_14( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Battled Team Star at school entrance. -// end: Talked to Jacq in classroom. Standing in classroom. -void checkpoint_15( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_08_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_08_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_08 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: Arrived at Mesagoza (South) Pokecenter +// end: Battled Nemona at Mesagoza gate. Entered Mesagoza. +void checkpoint_13( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Battled Nemona at Mesagoza gate. Entered Mesagoza. +// end: Battled Team Star at school entrance. +void checkpoint_14( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Battled Team Star at school entrance. +// end: Talked to Jacq in classroom. Standing in classroom. +void checkpoint_15( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp index 5ea17d0e09..749ba36182 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.cpp @@ -1,323 +1,323 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_09.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_09::name() const{ - return "09: Complete tutorial"; -} - -std::string AutoStory_Segment_09::start_text() const{ - return "Start: Battled Team Star, talked to Jacq, standing in classroom."; -} - -std::string AutoStory_Segment_09::end_text() const{ - return "End: Finished tutorial. Acquired all 3 questlines. Got on ride for first time."; -} - -void AutoStory_Segment_09::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 09: Complete tutorial", COLOR_ORANGE); - - checkpoint_16(env, context, options.notif_status_update); - checkpoint_17(env, context, options.notif_status_update); - checkpoint_18(env, context, options.notif_status_update); - checkpoint_19(env, context, options.notif_status_update); - checkpoint_20(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 09: Complete tutorial", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - - -void checkpoint_16( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk left - pbf_move_left_joystick(context, 0, 128, 400, 100); - // walk down to classroom exit. - pbf_move_left_joystick(context, 128, 255, 300, 100); - env.console.log("clear_dialog: Leave classroom."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5); - - // Wait for detection of school navigation menu - wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 5); - - // enter Cafeteria - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - pbf_wait(context, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // walk forward - pbf_move_left_joystick(context, 128, 0, 600, 100); - // turn left - pbf_move_left_joystick(context, 0, 128, 20, 100); - - // talk to Arven. stop at overworld. need prompt, overworld, white button A. and book? - env.console.log("Talk with Arven. Receive Titan questline (Path of Legends)."); - press_A_until_dialog(env.program_info(), env.console, context, 1); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_17( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk backwards until dialog - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20, 128, 255); - env.console.log("Talk with Cassiopeia."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 100); - // move backwards towards front desk - pbf_move_left_joystick(context, 128, 255, 200, 100); - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 100); - // move right towards navigation kiosk - pbf_move_left_joystick(context, 255, 128, 100, 100); - // open school navigation screen - press_button_until_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}); - // go to staff room - navigate_school_layout_menu(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, - {0.031, 0.193 + 0.074219, 0.047, 0.078}, DPAD_DOWN, 1); - // enter staff room - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - pbf_wait(context, 3 * TICKS_PER_SECOND); - - env.console.log("clear_dialog: See Geeta. Talk to Nemona. Receive Gym/Elite Four questline (Victory Road)."); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); - - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_18( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk down - pbf_move_left_joystick(context, 128, 255, 200, 100); - // walk left towards door - pbf_move_left_joystick(context, 0, 128, 100, 100); - - // wait for school navigation menu - context.wait_for_all_requests(); - wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); - // enter Directors office - pbf_mash_button(context, BUTTON_A, 6 * TICKS_PER_SECOND); - - env.console.log("Talk to Clavell in his office, and the professor."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, - {CallbackEnum::PROMPT_DIALOG}); // max time between dialog: 17s. set timeout to 25 seconds for buffer. - // mash A to get through the Random A press that you need. when the professor shows you area zero. - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, - {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_19( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // walk right - pbf_move_left_joystick(context, 255, 128, 50, 100); - // walk down towards door - pbf_move_left_joystick(context, 128, 255, 200, 100); - - env.console.log("Talk to Nemona and go to dorm."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // walk forward - pbf_move_left_joystick(context, 128, 0, 100, 100); - // walk left towards bed - pbf_move_left_joystick(context, 0, 128, 100, 100); - - env.console.log("Go to bed. Time passes until treasure hunt."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -void checkpoint_20( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - //walk right towards door - pbf_move_left_joystick(context, 255, 128, 200, 100); - - wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); - - env.console.log("Leave dorm for schoolyard."); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60, 128, 0); - - env.console.log("Talk to Nemona, Arven, Cassiopeia."); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 16, - {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BLACK_DIALOG_BOX}); // max time between dialog: 11 - - // mash A to get through the Random A press that you need. when the Nemona shows you a Poke Gym. - pbf_mash_button(context, BUTTON_A, 250); - - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, - {CallbackEnum::TUTORIAL}); // max time between dialog: 3 - - env.console.log("Get on ride."); - pbf_mash_button(context, BUTTON_PLUS, 1 * TICKS_PER_SECOND); - - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_09.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_09::name() const{ + return "09: Complete tutorial"; +} + +std::string AutoStory_Segment_09::start_text() const{ + return "Start: Battled Team Star, talked to Jacq, standing in classroom."; +} + +std::string AutoStory_Segment_09::end_text() const{ + return "End: Finished tutorial. Acquired all 3 questlines. Got on ride for first time."; +} + +void AutoStory_Segment_09::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 09: Complete tutorial", COLOR_ORANGE); + + checkpoint_16(env, context, options.notif_status_update); + checkpoint_17(env, context, options.notif_status_update); + checkpoint_18(env, context, options.notif_status_update); + checkpoint_19(env, context, options.notif_status_update); + checkpoint_20(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 09: Complete tutorial", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + + +void checkpoint_16( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk left + pbf_move_left_joystick(context, 0, 128, 400, 100); + // walk down to classroom exit. + pbf_move_left_joystick(context, 128, 255, 300, 100); + env.console.log("clear_dialog: Leave classroom."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 5); + + // Wait for detection of school navigation menu + wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 5); + + // enter Cafeteria + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + pbf_wait(context, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // walk forward + pbf_move_left_joystick(context, 128, 0, 600, 100); + // turn left + pbf_move_left_joystick(context, 0, 128, 20, 100); + + // talk to Arven. stop at overworld. need prompt, overworld, white button A. and book? + env.console.log("Talk with Arven. Receive Titan questline (Path of Legends)."); + press_A_until_dialog(env.program_info(), env.console, context, 1); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_17( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk backwards until dialog + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20, 128, 255); + env.console.log("Talk with Cassiopeia."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 100); + // move backwards towards front desk + pbf_move_left_joystick(context, 128, 255, 200, 100); + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 100); + // move right towards navigation kiosk + pbf_move_left_joystick(context, 255, 128, 100, 100); + // open school navigation screen + press_button_until_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}); + // go to staff room + navigate_school_layout_menu(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, + {0.031, 0.193 + 0.074219, 0.047, 0.078}, DPAD_DOWN, 1); + // enter staff room + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + pbf_wait(context, 3 * TICKS_PER_SECOND); + + env.console.log("clear_dialog: See Geeta. Talk to Nemona. Receive Gym/Elite Four questline (Victory Road)."); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); + + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_18( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk down + pbf_move_left_joystick(context, 128, 255, 200, 100); + // walk left towards door + pbf_move_left_joystick(context, 0, 128, 100, 100); + + // wait for school navigation menu + context.wait_for_all_requests(); + wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); + // enter Directors office + pbf_mash_button(context, BUTTON_A, 6 * TICKS_PER_SECOND); + + env.console.log("Talk to Clavell in his office, and the professor."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 25, + {CallbackEnum::PROMPT_DIALOG}); // max time between dialog: 17s. set timeout to 25 seconds for buffer. + // mash A to get through the Random A press that you need. when the professor shows you area zero. + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, + {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_19( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // walk right + pbf_move_left_joystick(context, 255, 128, 50, 100); + // walk down towards door + pbf_move_left_joystick(context, 128, 255, 200, 100); + + env.console.log("Talk to Nemona and go to dorm."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // walk forward + pbf_move_left_joystick(context, 128, 0, 100, 100); + // walk left towards bed + pbf_move_left_joystick(context, 0, 128, 100, 100); + + env.console.log("Go to bed. Time passes until treasure hunt."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +void checkpoint_20( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + //walk right towards door + pbf_move_left_joystick(context, 255, 128, 200, 100); + + wait_for_gradient_arrow(env.program_info(), env.console, context, {0.031, 0.193, 0.047, 0.078}, 10); + + env.console.log("Leave dorm for schoolyard."); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 60, 128, 0); + + env.console.log("Talk to Nemona, Arven, Cassiopeia."); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 16, + {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BLACK_DIALOG_BOX}); // max time between dialog: 11 + + // mash A to get through the Random A press that you need. when the Nemona shows you a Poke Gym. + pbf_mash_button(context, BUTTON_A, 250); + + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 10, + {CallbackEnum::TUTORIAL}); // max time between dialog: 3 + + env.console.log("Get on ride."); + pbf_mash_button(context, BUTTON_PLUS, 1 * TICKS_PER_SECOND); + + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h index f2f97eadac..f4719142f8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_09.h @@ -1,73 +1,73 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_09_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_09_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_09 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Talked to Jacq in classroom. Standing in classroom. -// end: Talked to Arven. Received Titan questline (Path of Legends). Talked to Cassiopeia. Standing in main hall. -void checkpoint_16( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Arven. Received Titan questline (Path of Legends). -// end: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. -void checkpoint_17( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. -// end: Talked to Clavell and the professor. -void checkpoint_18( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Clavell and the professor. -// end: Talked to Nemona, visited dorm, time passed. -void checkpoint_19( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Talked to Nemona, visited dorm, time passed. -// end: Get on ride for first time. -void checkpoint_20( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_09_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_09_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_09 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Talked to Jacq in classroom. Standing in classroom. +// end: Talked to Arven. Received Titan questline (Path of Legends). Talked to Cassiopeia. Standing in main hall. +void checkpoint_16( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Arven. Received Titan questline (Path of Legends). +// end: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. +void checkpoint_17( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Cassiopeia. Saw Geeta. Talked to Nemona. Received Gym/Elite Four questline (Victory Road). Standing in staff room. +// end: Talked to Clavell and the professor. +void checkpoint_18( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Clavell and the professor. +// end: Talked to Nemona, visited dorm, time passed. +void checkpoint_19( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Talked to Nemona, visited dorm, time passed. +// end: Get on ride for first time. +void checkpoint_20( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp index ef5d26d23b..3b96db8e13 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.cpp @@ -1,321 +1,321 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_10.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_10::name() const{ - return "10.1: Cortondo Gym - Go to Cortondo city"; -} - -std::string AutoStory_Segment_10::start_text() const{ - return "Start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter."; -} - -std::string AutoStory_Segment_10::end_text() const{ - return "End: At Cortondo East Pokecenter."; -} - -void AutoStory_Segment_10::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_ORANGE); - - checkpoint_21(env, context, options.notif_status_update); - checkpoint_22(env, context, options.notif_status_update); - checkpoint_23(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_21( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_L, 20, 20); - // move forward - pbf_move_left_joystick(context, 128, 0, 30, 100); - // get on ride - get_on_ride(env.program_info(), env.console, context); - // turn left - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NO_MARKER, 0, 128, 50); - // move forward - pbf_move_left_joystick(context, 128, 0, 100, 100); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 70); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 70); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // turn towards wall - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 50); - pbf_move_left_joystick(context, 128, 0, 200, 100); - // run and jump over wall - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 100); - - BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); - int ret = wait_until( - env.console, context, - std::chrono::seconds(30), - { black_screen } - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_21(): Failed to jump the East Mesagoza wall.", - env.console - ); - } - context.wait_for_all_requests(); - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_22( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 80}, - {ZoomChange::KEEP_ZOOM, 255, 80, 37} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 20); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 40}, - {ZoomChange::KEEP_ZOOM, 255, 255, 27} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 15); - - // section 3. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 128, 0}, - {ZoomChange::KEEP_ZOOM, 128, 128, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 15); - - // section 3. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 70, 30); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 20, 12, 12); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -void checkpoint_23( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 0, 30); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 80}, - {ZoomChange::KEEP_ZOOM, 255, 95, 100} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 80}, - {ZoomChange::KEEP_ZOOM, 255, 75, 65} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 255, 180, 17} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 128, 0}, - {ZoomChange::KEEP_ZOOM, 128, 128, 0} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 6. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 110, 50); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_10.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_10::name() const{ + return "10.1: Cortondo Gym - Go to Cortondo city"; +} + +std::string AutoStory_Segment_10::start_text() const{ + return "Start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter."; +} + +std::string AutoStory_Segment_10::end_text() const{ + return "End: At Cortondo East Pokecenter."; +} + +void AutoStory_Segment_10::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_ORANGE); + + checkpoint_21(env, context, options.notif_status_update); + checkpoint_22(env, context, options.notif_status_update); + checkpoint_23(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 10.1: Cortondo Gym - Go to Cortondo city", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_21( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_L, 20, 20); + // move forward + pbf_move_left_joystick(context, 128, 0, 30, 100); + // get on ride + get_on_ride(env.program_info(), env.console, context); + // turn left + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NO_MARKER, 0, 128, 50); + // move forward + pbf_move_left_joystick(context, 128, 0, 100, 100); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 70); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 70); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // turn towards wall + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 128, 0, 50); + pbf_move_left_joystick(context, 128, 0, 200, 100); + // run and jump over wall + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 100); + + BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); + int ret = wait_until( + env.console, context, + std::chrono::seconds(30), + { black_screen } + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_21(): Failed to jump the East Mesagoza wall.", + env.console + ); + } + context.wait_for_all_requests(); + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_22( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 80}, + {ZoomChange::KEEP_ZOOM, 255, 80, 37} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 20); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 40}, + {ZoomChange::KEEP_ZOOM, 255, 255, 27} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 15); + + // section 3. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 128, 0}, + {ZoomChange::KEEP_ZOOM, 128, 128, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 15); + + // section 3. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 70, 30); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 20, 12, 12); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +void checkpoint_23( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 110, 0, 30); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 80}, + {ZoomChange::KEEP_ZOOM, 255, 95, 100} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 80}, + {ZoomChange::KEEP_ZOOM, 255, 75, 65} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 255, 180, 17} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 128, 0}, + {ZoomChange::KEEP_ZOOM, 128, 128, 0} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 6. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 110, 50); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h index e7026478e7..a007e24fe3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_10.h @@ -1,57 +1,57 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_10_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_10_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_10 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter. -// end: At Mesagoza West gate flypoint -void checkpoint_21( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At Mesagoza West gate flypoint -// end: At South Province Area Two Pokecenter. -void checkpoint_22( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At South Province Area Two Pokecenter. -// end: At Cortondo East Pokecenter -void checkpoint_23( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_10_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_10_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_10 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: After the break, with level 100 Gardevoir. At Mesagoza West pokecenter. +// end: At Mesagoza West gate flypoint +void checkpoint_21( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At Mesagoza West gate flypoint +// end: At South Province Area Two Pokecenter. +void checkpoint_22( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At South Province Area Two Pokecenter. +// end: At Cortondo East Pokecenter +void checkpoint_23( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp index aadc8cd65d..f6e2135261 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.cpp @@ -1,625 +1,625 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_OliveActionFailedException.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_11.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -std::string AutoStory_Segment_11::name() const{ - return "10.2: Cortondo Gym - Gym challenge"; -} - -std::string AutoStory_Segment_11::start_text() const{ - return "Start: At Cortondo East Pokecenter."; -} - -std::string AutoStory_Segment_11::end_text() const{ - return "End: Beat Cortondo Gym challenge. At Cortondo West Pokecenter."; -} - -void AutoStory_Segment_11::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 10.2: Cortondo Gym - Gym challenge", COLOR_ORANGE); - - checkpoint_24(env, context, options.notif_status_update); - checkpoint_25(env, context, options.notif_status_update); - checkpoint_26(env, context, options.notif_status_update); - checkpoint_27(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 10.2: Cortondo Gym - Gym challenge", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_24( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 2.71); - pbf_move_left_joystick(context, 128, 0, 375, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1750, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 2.73); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 20); - }, - 5, 5 - ); - // enter gym building. talk go Nemona - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - // talk to receptionist - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 450, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -void checkpoint_25( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1. align to Olive roll NPC - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 157, 0, 40); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10); - - // section 1.1. keep walking forward and talk to Olive roll NPC - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - } - ); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 2 - pbf_move_left_joystick(context, 128, 0, 1300, 100); - - // section 3 - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 6.0); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // section 4. align to corner - direction.change_direction(env.program_info(), env.console, context, 4.69); - pbf_move_left_joystick(context, 128, 0, 150, 100); - - // section 5. battle first NPC - direction.change_direction(env.program_info(), env.console, context, 1.485); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 6 - direction.change_direction(env.program_info(), env.console, context, 5.95); - pbf_move_left_joystick(context, 128, 0, 1000, 100); - - // section 7 - direction.change_direction(env.program_info(), env.console, context, 1.327); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // section 8 - direction.change_direction(env.program_info(), env.console, context, 6.106); - pbf_move_left_joystick(context, 128, 0, 200, 100); - - // section 9. battle second NPC - direction.change_direction(env.program_info(), env.console, context, 4.275); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 10. leave Olive roll - pbf_mash_button(context, BUTTON_Y, 100); - clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 60, {CallbackEnum::PROMPT_DIALOG}); - clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 15, {CallbackEnum::PROMPT_DIALOG}); - wait_for_overworld(env.program_info(), env.console, context); - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - - break; - }catch(...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_26( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // change the time of day: close game, change time to 5:45 am. - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - change_date(env, context, {2025, 1, 1, 5, 45, 0}); - reset_game_from_home(env.program_info(), env.console, context); - - // talk to Olive roll NPC - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); - mash_button_till_overworld(env.console, context, BUTTON_A); - - // section 1 - pbf_move_left_joystick(context, 128, 0, 400, 50); - OliveDetector green(env.console); - size_t MAX_ATTEMPTS_SECTION_1 = 2; - uint16_t ticks_to_walk_for_section1 = 650; - uint16_t push_strength_section_1 = 75; - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_1; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 4.38, ticks_to_walk_for_section1, push_strength_section_1); - // green.align_to_olive(env.program_info(), env.console, context, 4.38); - green.walk_up_to_olive(env.program_info(), env.console, context, 4.38); - break; - }catch (OliveActionFailedException& e){ - if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. - break; - } - - if (i >= MAX_ATTEMPTS_SECTION_1-1){ - throw e; - } - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ - // may have walked past olive - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section1 = 100; - push_strength_section_1 = 50; - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE - throw e; - } - - } - } - - - // section 1b. realign using fence corner - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 2.74); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 4.328); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 1.22); - pbf_move_left_joystick(context, 128, 0, 75, 50); - - // section 2.1 nudge olive straight - size_t MAX_ATTEMPTS_SECTION_2_1 = 2; - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_1; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 5.95, 50, 50); - break; - }catch (OliveActionFailedException& e){ - if (i >= MAX_ATTEMPTS_SECTION_2_1-1){ - throw e; - } - - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 250, 50); - pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - break; // then move on to next section - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - - } - } - - pbf_move_left_joystick(context, 128, 255, 100, 50); - green.align_to_olive(env.program_info(), env.console, context, 5.95); - pbf_move_left_joystick(context, 128, 255, 500, 50); - - // section 2.2 push at angle towards outer fence - size_t MAX_ATTEMPTS_SECTION_2_2 = 2; - // uint16_t ticks_walked_section2_2 = 0; - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_2; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 5.8, 250, 50); - break; - }catch (OliveActionFailedException& e){ - if (i >= MAX_ATTEMPTS_SECTION_2_2-1){ - throw e; - } - - if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ // olive possibly stuck on fence - pbf_move_left_joystick(context, 128, 255, 20, 50); - pbf_move_left_joystick(context, 0, 128, 100, 50); - pbf_move_left_joystick(context, 128, 0, 200, 50); - // push olive parallel to fence - green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); - green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); - green.push_olive_forward(env.program_info(), env.console, context, 4.28, 100); - green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); - green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); - // back off - pbf_move_left_joystick(context, 128, 255, 50, 50); - // realign using fence corner - direction.change_direction(env.program_info(), env.console, context, 2.74); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 4.328); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 1.22); - pbf_move_left_joystick(context, 128, 0, 100, 50); - }else if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - // continue trying to push the olive. at a different angle - break; - } - } - } - - pbf_move_left_joystick(context, 128, 255, 100, 50); - green.align_to_olive(env.program_info(), env.console, context, 5.95); - pbf_move_left_joystick(context, 128, 255, 500, 50); - - // section 2.3 push olive past first NPC - uint16_t ticks_to_walk_for_section2_3 = 950; - size_t MAX_ATTEMPTS = 2; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 5.95, ticks_to_walk_for_section2_3, 75, 10); - // green.align_to_olive(env.program_info(), env.console, context, 5.95, 10); - green.walk_up_to_olive(env.program_info(), env.console, context, 5.95, 10); - break; - }catch (OliveActionFailedException& e){ - if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. - break; - } - - if (i >= MAX_ATTEMPTS-1){ - throw e; - } - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ - // may have walked past olive - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - // ticks_to_walk_for_section2_3 = 500; - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE - throw e; - } - - } - } - - // section 2b. realign using fence corner - direction.change_direction(env.program_info(), env.console, context, 4.5); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 5.86); - pbf_move_left_joystick(context, 128, 0, 300, 50); - direction.change_direction(env.program_info(), env.console, context, 2.76); - pbf_move_left_joystick(context, 128, 0, 50, 50); - - // section 3.1 push olive across the hump - uint16_t ticks_to_walk_for_section3_1 = 350; - uint16_t ticks_walked_section3_1 = 0; - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - ticks_walked_section3_1 = green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_1, 125); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive past the hump. and walked past it - if (i >= MAX_ATTEMPTS-1){ - throw e; - } - - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 250, 50); - pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character - pbf_wait(context, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section3_1 = 200; - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section3_1 = 200; - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - - } - } - - - // section 3.2 push olive across the hump and into fence - uint16_t total_ticks_to_walk_for_section3 = 550; - uint16_t ticks_to_walk_for_section3_2 = 0; - if (ticks_walked_section3_1 < total_ticks_to_walk_for_section3){ - ticks_to_walk_for_section3_2 = (total_ticks_to_walk_for_section3 - ticks_walked_section3_1); - } - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_2, 125); - pbf_move_left_joystick(context, 128, 255, 100, 50); - green.align_to_olive(env.program_info(), env.console, context, 1.27); - green.walk_up_to_olive(env.program_info(), env.console, context, 1.27); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive past the hump. and walked past it - if (i >= MAX_ATTEMPTS-1){ - throw e; - } - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - ticks_to_walk_for_section3_2 += 200; - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - - } - } - - - // section 3b. realign using fence. - direction.change_direction(env.program_info(), env.console, context, 3.0); - pbf_move_left_joystick(context, 128, 0, 75, 50); - direction.change_direction(env.program_info(), env.console, context, 1.17); - pbf_move_left_joystick(context, 128, 0, 100, 50); - - // section 4.1 last stretch. nudge the olive - for (size_t i = 0; i < MAX_ATTEMPTS; i++){ - try{ - green.align_to_olive(env.program_info(), env.console, context, 6.0); - green.walk_up_to_olive(env.program_info(), env.console, context, 6.0); - green.push_olive_forward(env.program_info(), env.console, context, 6.0, 50, 50); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive. and walked past it - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 100, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - } - } - - // section 4.2 past second NPC and into the finish line - NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); - size_t MAX_ATTEMPTS_SECTION_4 = 3; - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_4; i++){ - try{ - green.push_olive_forward(env.program_info(), env.console, context, 6.0, 250); - green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); - green.push_olive_forward(env.program_info(), env.console, context, 6.0, 200); - green.push_olive_forward(env.program_info(), env.console, context, 6.1, 200); - break; - }catch (OliveActionFailedException& e){ - // may have failed to push the olive. and walked past it - if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ - pbf_move_left_joystick(context, 128, 255, 200, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ - // try moving back and then ramming forward - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - // then push angled towards the right - green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); - }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - throw e; - } - } - } - }, - {no_minimap} - ); - if (ret < 0){ - throw_and_log( - env.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to finish Olive roll in the last stretch.", - env.console - ); - } - env.log("No minimap seen. Likely finished the Olive roll."); - - // section 8. finish olive roll - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // fix the time - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - // reset_game(env.program_info(), env.console, context); // the checkpoint itself already resets the game, so need to reset twice - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_27( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 128, 40}); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OliveDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_OliveActionFailedException.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_11.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +std::string AutoStory_Segment_11::name() const{ + return "10.2: Cortondo Gym - Gym challenge"; +} + +std::string AutoStory_Segment_11::start_text() const{ + return "Start: At Cortondo East Pokecenter."; +} + +std::string AutoStory_Segment_11::end_text() const{ + return "End: Beat Cortondo Gym challenge. At Cortondo West Pokecenter."; +} + +void AutoStory_Segment_11::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 10.2: Cortondo Gym - Gym challenge", COLOR_ORANGE); + + checkpoint_24(env, context, options.notif_status_update); + checkpoint_25(env, context, options.notif_status_update); + checkpoint_26(env, context, options.notif_status_update); + checkpoint_27(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 10.2: Cortondo Gym - Gym challenge", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_24( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 2.71); + pbf_move_left_joystick(context, 128, 0, 375, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1750, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 2.73); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 20); + }, + 5, 5 + ); + // enter gym building. talk go Nemona + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + // talk to receptionist + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 450, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +void checkpoint_25( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1. align to Olive roll NPC + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 157, 0, 40); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10); + + // section 1.1. keep walking forward and talk to Olive roll NPC + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + } + ); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 2 + pbf_move_left_joystick(context, 128, 0, 1300, 100); + + // section 3 + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 6.0); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // section 4. align to corner + direction.change_direction(env.program_info(), env.console, context, 4.69); + pbf_move_left_joystick(context, 128, 0, 150, 100); + + // section 5. battle first NPC + direction.change_direction(env.program_info(), env.console, context, 1.485); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 6 + direction.change_direction(env.program_info(), env.console, context, 5.95); + pbf_move_left_joystick(context, 128, 0, 1000, 100); + + // section 7 + direction.change_direction(env.program_info(), env.console, context, 1.327); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // section 8 + direction.change_direction(env.program_info(), env.console, context, 6.106); + pbf_move_left_joystick(context, 128, 0, 200, 100); + + // section 9. battle second NPC + direction.change_direction(env.program_info(), env.console, context, 4.275); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 10. leave Olive roll + pbf_mash_button(context, BUTTON_Y, 100); + clear_dialog(env.console, context, ClearDialogMode::STOP_PROMPT, 60, {CallbackEnum::PROMPT_DIALOG}); + clear_dialog(env.console, context, ClearDialogMode::STOP_TIMEOUT, 15, {CallbackEnum::PROMPT_DIALOG}); + wait_for_overworld(env.program_info(), env.console, context); + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + + break; + }catch(...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_26( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // change the time of day: close game, change time to 5:45 am. + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + change_date(env, context, {2025, 1, 1, 5, 45, 0}); + reset_game_from_home(env.program_info(), env.console, context); + + // talk to Olive roll NPC + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10, 128, 20); + mash_button_till_overworld(env.console, context, BUTTON_A); + + // section 1 + pbf_move_left_joystick(context, 128, 0, 400, 50); + OliveDetector green(env.console); + size_t MAX_ATTEMPTS_SECTION_1 = 2; + uint16_t ticks_to_walk_for_section1 = 650; + uint16_t push_strength_section_1 = 75; + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_1; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 4.38, ticks_to_walk_for_section1, push_strength_section_1); + // green.align_to_olive(env.program_info(), env.console, context, 4.38); + green.walk_up_to_olive(env.program_info(), env.console, context, 4.38); + break; + }catch (OliveActionFailedException& e){ + if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. + break; + } + + if (i >= MAX_ATTEMPTS_SECTION_1-1){ + throw e; + } + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ + // may have walked past olive + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section1 = 100; + push_strength_section_1 = 50; + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE + throw e; + } + + } + } + + + // section 1b. realign using fence corner + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 2.74); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 4.328); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 1.22); + pbf_move_left_joystick(context, 128, 0, 75, 50); + + // section 2.1 nudge olive straight + size_t MAX_ATTEMPTS_SECTION_2_1 = 2; + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_1; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 5.95, 50, 50); + break; + }catch (OliveActionFailedException& e){ + if (i >= MAX_ATTEMPTS_SECTION_2_1-1){ + throw e; + } + + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 250, 50); + pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + break; // then move on to next section + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + + } + } + + pbf_move_left_joystick(context, 128, 255, 100, 50); + green.align_to_olive(env.program_info(), env.console, context, 5.95); + pbf_move_left_joystick(context, 128, 255, 500, 50); + + // section 2.2 push at angle towards outer fence + size_t MAX_ATTEMPTS_SECTION_2_2 = 2; + // uint16_t ticks_walked_section2_2 = 0; + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_2_2; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 5.8, 250, 50); + break; + }catch (OliveActionFailedException& e){ + if (i >= MAX_ATTEMPTS_SECTION_2_2-1){ + throw e; + } + + if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ // olive possibly stuck on fence + pbf_move_left_joystick(context, 128, 255, 20, 50); + pbf_move_left_joystick(context, 0, 128, 100, 50); + pbf_move_left_joystick(context, 128, 0, 200, 50); + // push olive parallel to fence + green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); + green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); + green.push_olive_forward(env.program_info(), env.console, context, 4.28, 100); + green.align_to_olive(env.program_info(), env.console, context, 4.28, 20); + green.walk_up_to_olive(env.program_info(), env.console, context, 4.28); + // back off + pbf_move_left_joystick(context, 128, 255, 50, 50); + // realign using fence corner + direction.change_direction(env.program_info(), env.console, context, 2.74); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 4.328); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 1.22); + pbf_move_left_joystick(context, 128, 0, 100, 50); + }else if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + // continue trying to push the olive. at a different angle + break; + } + } + } + + pbf_move_left_joystick(context, 128, 255, 100, 50); + green.align_to_olive(env.program_info(), env.console, context, 5.95); + pbf_move_left_joystick(context, 128, 255, 500, 50); + + // section 2.3 push olive past first NPC + uint16_t ticks_to_walk_for_section2_3 = 950; + size_t MAX_ATTEMPTS = 2; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 5.95, ticks_to_walk_for_section2_3, 75, 10); + // green.align_to_olive(env.program_info(), env.console, context, 5.95, 10); + green.walk_up_to_olive(env.program_info(), env.console, context, 5.95, 10); + break; + }catch (OliveActionFailedException& e){ + if (e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // if olive is stuck, we might have pushed the olive all the way to the end. so we can try moving on. + break; + } + + if (i >= MAX_ATTEMPTS-1){ + throw e; + } + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED || e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE){ + // may have walked past olive + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + // ticks_to_walk_for_section2_3 = 500; + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE + throw e; + } + + } + } + + // section 2b. realign using fence corner + direction.change_direction(env.program_info(), env.console, context, 4.5); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 5.86); + pbf_move_left_joystick(context, 128, 0, 300, 50); + direction.change_direction(env.program_info(), env.console, context, 2.76); + pbf_move_left_joystick(context, 128, 0, 50, 50); + + // section 3.1 push olive across the hump + uint16_t ticks_to_walk_for_section3_1 = 350; + uint16_t ticks_walked_section3_1 = 0; + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + ticks_walked_section3_1 = green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_1, 125); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive past the hump. and walked past it + if (i >= MAX_ATTEMPTS-1){ + throw e; + } + + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 250, 50); + pbf_move_left_joystick(context, 128, 0, 50, 50); // move forward slight in case the olive is undetectable since it's right in front of the character + pbf_wait(context, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section3_1 = 200; + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section3_1 = 200; + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + + } + } + + + // section 3.2 push olive across the hump and into fence + uint16_t total_ticks_to_walk_for_section3 = 550; + uint16_t ticks_to_walk_for_section3_2 = 0; + if (ticks_walked_section3_1 < total_ticks_to_walk_for_section3){ + ticks_to_walk_for_section3_2 = (total_ticks_to_walk_for_section3 - ticks_walked_section3_1); + } + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 1.27, ticks_to_walk_for_section3_2, 125); + pbf_move_left_joystick(context, 128, 255, 100, 50); + green.align_to_olive(env.program_info(), env.console, context, 1.27); + green.walk_up_to_olive(env.program_info(), env.console, context, 1.27); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive past the hump. and walked past it + if (i >= MAX_ATTEMPTS-1){ + throw e; + } + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + ticks_to_walk_for_section3_2 += 200; + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + + } + } + + + // section 3b. realign using fence. + direction.change_direction(env.program_info(), env.console, context, 3.0); + pbf_move_left_joystick(context, 128, 0, 75, 50); + direction.change_direction(env.program_info(), env.console, context, 1.17); + pbf_move_left_joystick(context, 128, 0, 100, 50); + + // section 4.1 last stretch. nudge the olive + for (size_t i = 0; i < MAX_ATTEMPTS; i++){ + try{ + green.align_to_olive(env.program_info(), env.console, context, 6.0); + green.walk_up_to_olive(env.program_info(), env.console, context, 6.0); + green.push_olive_forward(env.program_info(), env.console, context, 6.0, 50, 50); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive. and walked past it + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 100, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + } + } + + // section 4.2 past second NPC and into the finish line + NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); + size_t MAX_ATTEMPTS_SECTION_4 = 3; + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + for (size_t i = 0; i < MAX_ATTEMPTS_SECTION_4; i++){ + try{ + green.push_olive_forward(env.program_info(), env.console, context, 6.0, 250); + green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); + green.push_olive_forward(env.program_info(), env.console, context, 6.0, 200); + green.push_olive_forward(env.program_info(), env.console, context, 6.1, 200); + break; + }catch (OliveActionFailedException& e){ + // may have failed to push the olive. and walked past it + if (e.m_fail_reason == OliveFail::NO_OLIVE_DETECTED){ + pbf_move_left_joystick(context, 128, 255, 200, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else if (e.m_fail_reason == OliveFail::FAILED_WALK_TO_OLIVE || e.m_fail_reason == OliveFail::OLIVE_STUCK){ + // try moving back and then ramming forward + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + // then push angled towards the right + green.push_olive_forward(env.program_info(), env.console, context, 5.8, 100); + }else{ // FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + throw e; + } + } + } + }, + {no_minimap} + ); + if (ret < 0){ + throw_and_log( + env.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to finish Olive roll in the last stretch.", + env.console + ); + } + env.log("No minimap seen. Likely finished the Olive roll."); + + // section 8. finish olive roll + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // fix the time + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + // reset_game(env.program_info(), env.console, context); // the checkpoint itself already resets the game, so need to reset twice + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_27( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 128, 40}); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h index 5b17aaf4f9..4a5eb11259 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_11.h @@ -1,66 +1,66 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_11_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_11_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_11 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Cortondo East Pokecenter -// end: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. -void checkpoint_24( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. -// end: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. -void checkpoint_25( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. -// end: Completed Olive roll gym challenge. -void checkpoint_26( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Completed Olive roll gym challenge. -// end: At Cortondo East Pokecenter. -void checkpoint_27( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_11_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_11_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_11 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Cortondo East Pokecenter +// end: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. +void checkpoint_24( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Spoke to Cortondo Gym reception. At Cortondo West Pokecenter. +// end: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. +void checkpoint_25( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated the trainers at Olive Roll, but left Olive unmoved. Then backed out, standing in front of the Olive Roll NPC. +// end: Completed Olive roll gym challenge. +void checkpoint_26( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Completed Olive roll gym challenge. +// end: At Cortondo East Pokecenter. +void checkpoint_27( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp index 94cda1507c..7c85312967 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.cpp @@ -1,154 +1,154 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_12.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_12::name() const{ - return "10.3: Cortondo Gym - Gym battle"; -} - -std::string AutoStory_Segment_12::start_text() const{ - return "Start: Beat Cortondo Gym challenge."; -} - -std::string AutoStory_Segment_12::end_text() const{ - return "End: Beat Cortondo Gym battle. At Cortondo West Pokecenter."; -} - - -void AutoStory_Segment_12::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 10.3: Cortondo Gym - Gym battle", COLOR_ORANGE); - - checkpoint_28(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 10.3: Cortondo Gym - Gym battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_28( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 2.71); - pbf_move_left_joystick(context, 128, 0, 375, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1750, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 2.73); - - NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(2000)); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 100); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 20); - }, - 5, 3 - ); - }, - {no_minimap} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter Cortondo Gym.", - env.console - ); - } - - wait_for_overworld(env.program_info(), env.console, context); - - // talk to receptionist - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - - // battle Katy - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // leave gym building - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 450, 100); - direction.change_direction(env.program_info(), env.console, context, 1.26); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_12.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_12::name() const{ + return "10.3: Cortondo Gym - Gym battle"; +} + +std::string AutoStory_Segment_12::start_text() const{ + return "Start: Beat Cortondo Gym challenge."; +} + +std::string AutoStory_Segment_12::end_text() const{ + return "End: Beat Cortondo Gym battle. At Cortondo West Pokecenter."; +} + + +void AutoStory_Segment_12::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 10.3: Cortondo Gym - Gym battle", COLOR_ORANGE); + + checkpoint_28(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 10.3: Cortondo Gym - Gym battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_28( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 2.71); + pbf_move_left_joystick(context, 128, 0, 375, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1750, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 2.73); + + NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(2000)); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 100); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 20); + }, + 5, 3 + ); + }, + {no_minimap} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter Cortondo Gym.", + env.console + ); + } + + wait_for_overworld(env.program_info(), env.console, context); + + // talk to receptionist + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + + // battle Katy + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // leave gym building + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 450, 100); + direction.change_direction(env.program_info(), env.console, context, 1.26); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h index 0e7d277412..e61480d5fa 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_12.h @@ -1,39 +1,39 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_12_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_12_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_12 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: At Cortondo East Pokecenter. -// end: Beat Cortondo Gym. At Cortondo West Pokecenter. -void checkpoint_28( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_12_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_12_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_12 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: At Cortondo East Pokecenter. +// end: Beat Cortondo Gym. At Cortondo West Pokecenter. +void checkpoint_28( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp index 0d76a94460..9b6a3e9655 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.cpp @@ -1,331 +1,331 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_13.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_13::name() const{ - return "11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter"; -} - -std::string AutoStory_Segment_13::start_text() const{ - return "Start: At Cortondo West Pokecenter"; -} - -std::string AutoStory_Segment_13::end_text() const{ - return "End: At West Province Area One Central Pokecenter"; -} - -void AutoStory_Segment_13::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_ORANGE); - - checkpoint_29(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -// todo: shift all checkpoint numbers to make space for the Cortondo checkpoints -void checkpoint_29( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - // align for long stretch 1, part 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 70, 0, 60); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 15, false); - - // align for long stretch 1, part 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 40}, - {ZoomChange::KEEP_ZOOM, 80, 0, 75} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 12, 12, false); - - // align for long stretch 1, part 3 - - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 60}, - {ZoomChange::KEEP_ZOOM, 95, 0, 115} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - - // align for long stretch 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 100}, - {ZoomChange::KEEP_ZOOM, 0, 105, 65} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 45, 15, false); - - // align for long stretch 3, part 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 128, 65}, - {ZoomChange::KEEP_ZOOM, 0, 50, 87} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for long stretch 3, part 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 160, 65}, - {ZoomChange::KEEP_ZOOM, 20, 0, 110} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // align for long stretch 3, part 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 60, 110}, - {ZoomChange::KEEP_ZOOM, 255, 128, 115} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // align for long stretch 3, part 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 100}, - {ZoomChange::KEEP_ZOOM, 255, 67, 90} //{ZoomChange::KEEP_ZOOM, 255, 70, 90} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - - // align to cross bridge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 90}, - {ZoomChange::KEEP_ZOOM, 255, 35, 67} - ); - - - // attempt to cross bridge. If fall into water, go back to start position (just before bridge) and try again - WallClock start_to_cross_bridge = current_time(); - while (true){ - if (current_time() - start_to_cross_bridge > std::chrono::minutes(6)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_26(): Failed to cross bridge after 6 minutes.", - env.console - ); - } - - try { - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, - 128, 0, 20, 20, false); - - break; - - }catch (...){ // try again if fall into water - pbf_mash_button(context, BUTTON_A, 250); - - // walk back to start position before bridge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 180}, - {ZoomChange::KEEP_ZOOM, 33, 0, 180} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, - 128, 0, 20, 20, false); - - - // align to cross bridge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 90}, - {ZoomChange::KEEP_ZOOM, 255, 35, 67} - ); - - - } - } - - confirm_no_overlapping_flypoint(env.program_info(), env.console, context); - pbf_press_button(context, BUTTON_B, 20, 100); - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - }); - - env.console.log("Successfully crossed the bridge."); - - // align for post-bridge section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 150, 60}, - {ZoomChange::KEEP_ZOOM, 255, 60, 50} // {ZoomChange::KEEP_ZOOM, 255, 60, 50} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for post-bridge section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 150, 60}, - {ZoomChange::KEEP_ZOOM, 255, 105, 50} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for post-bridge section 3. move up towards tree - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 255, 90, 35} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // align for post-bridge section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 255, 55, 25} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - - - // align for post-bridge section 5. set marker to pokecenter. - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 128, 50}, - {ZoomChange::KEEP_ZOOM, 128, 128, 0} - ); - - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - - // align for post-bridge section 6. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 30); - }); - // realign_player_from_landmark( - // env.program_info(), env.console, context, - // {ZoomChange::ZOOM_IN, 128, 128, 0}, - // {ZoomChange::KEEP_ZOOM, 0, 180, 20} - // ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_13.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_13::name() const{ + return "11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter"; +} + +std::string AutoStory_Segment_13::start_text() const{ + return "Start: At Cortondo West Pokecenter"; +} + +std::string AutoStory_Segment_13::end_text() const{ + return "End: At West Province Area One Central Pokecenter"; +} + +void AutoStory_Segment_13::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_ORANGE); + + checkpoint_29(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 11.1: Bombirdier Titan: Go to West Province Area One Central Pokecenter", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +// todo: shift all checkpoint numbers to make space for the Cortondo checkpoints +void checkpoint_29( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + // align for long stretch 1, part 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 70, 0, 60); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 15, false); + + // align for long stretch 1, part 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 40}, + {ZoomChange::KEEP_ZOOM, 80, 0, 75} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 12, 12, false); + + // align for long stretch 1, part 3 + + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 60}, + {ZoomChange::KEEP_ZOOM, 95, 0, 115} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + + // align for long stretch 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 100}, + {ZoomChange::KEEP_ZOOM, 0, 105, 65} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 45, 15, false); + + // align for long stretch 3, part 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 128, 65}, + {ZoomChange::KEEP_ZOOM, 0, 50, 87} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for long stretch 3, part 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 160, 65}, + {ZoomChange::KEEP_ZOOM, 20, 0, 110} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // align for long stretch 3, part 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 60, 110}, + {ZoomChange::KEEP_ZOOM, 255, 128, 115} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // align for long stretch 3, part 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 100}, + {ZoomChange::KEEP_ZOOM, 255, 67, 90} //{ZoomChange::KEEP_ZOOM, 255, 70, 90} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + + // align to cross bridge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 90}, + {ZoomChange::KEEP_ZOOM, 255, 35, 67} + ); + + + // attempt to cross bridge. If fall into water, go back to start position (just before bridge) and try again + WallClock start_to_cross_bridge = current_time(); + while (true){ + if (current_time() - start_to_cross_bridge > std::chrono::minutes(6)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_26(): Failed to cross bridge after 6 minutes.", + env.console + ); + } + + try { + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, + 128, 0, 20, 20, false); + + break; + + }catch (...){ // try again if fall into water + pbf_mash_button(context, BUTTON_A, 250); + + // walk back to start position before bridge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 180}, + {ZoomChange::KEEP_ZOOM, 33, 0, 180} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::CLEAR_WITH_LETS_GO, + 128, 0, 20, 20, false); + + + // align to cross bridge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 90}, + {ZoomChange::KEEP_ZOOM, 255, 35, 67} + ); + + + } + } + + confirm_no_overlapping_flypoint(env.program_info(), env.console, context); + pbf_press_button(context, BUTTON_B, 20, 100); + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + }); + + env.console.log("Successfully crossed the bridge."); + + // align for post-bridge section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 150, 60}, + {ZoomChange::KEEP_ZOOM, 255, 60, 50} // {ZoomChange::KEEP_ZOOM, 255, 60, 50} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for post-bridge section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 150, 60}, + {ZoomChange::KEEP_ZOOM, 255, 105, 50} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for post-bridge section 3. move up towards tree + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 255, 90, 35} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // align for post-bridge section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 255, 55, 25} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + + + // align for post-bridge section 5. set marker to pokecenter. + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 128, 50}, + {ZoomChange::KEEP_ZOOM, 128, 128, 0} + ); + + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + + // align for post-bridge section 6. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 200, 30); + }); + // realign_player_from_landmark( + // env.program_info(), env.console, context, + // {ZoomChange::ZOOM_IN, 128, 128, 0}, + // {ZoomChange::KEEP_ZOOM, 0, 180, 20} + // ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h index ce4330a4b6..31252d4a2d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_13.h @@ -1,43 +1,43 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_13_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_13_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_13 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Cortondo West Pokecenter. -// end: At West Province Area One Central Pokecenter -void checkpoint_29( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_13_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_13_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_13 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Cortondo West Pokecenter. +// end: At West Province Area One Central Pokecenter +void checkpoint_29( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp index 756a8fa92c..8714ad2c98 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.cpp @@ -1,319 +1,319 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_14.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_14::name() const{ - return "11.2: Bombirdier Titan: Battle Bombirdier"; -} - -std::string AutoStory_Segment_14::start_text() const{ - return "Start: At West Province Area One Central Pokecenter"; -} - -std::string AutoStory_Segment_14::end_text() const{ - return "End: Defeated Bombirder. At West Province Area One North Pokecenter"; -} - -void AutoStory_Segment_14::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_ORANGE); - - checkpoint_30(env, context, options.notif_status_update); - checkpoint_31(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_30( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 17); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 200, 200}, - {ZoomChange::KEEP_ZOOM, 0, 65, 220} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 200, 200}, - {ZoomChange::KEEP_ZOOM, 0, 80, 235} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 4. walk until Arven dialog - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 200, 200}, - {ZoomChange::KEEP_ZOOM, 0, 60, 280} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 30, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); - - // after Arven dialog. section 5 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 18, 6, false); - - // section 6 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 0, 0}, - {ZoomChange::KEEP_ZOOM, 0, 20, 65} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - get_on_ride(env.program_info(), env.console, context); - - // section 7 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 0, 0, 0}, - {ZoomChange::KEEP_ZOOM, 0, 30, 80} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 8. enter left side of boulder field - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 50}, - {ZoomChange::KEEP_ZOOM, 0, 40, 95} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 18, 6, false); - - // section 8.1. move up - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 0, 50); - pbf_move_left_joystick(context, 128, 0, 100, 100); - - // section 9. go to middle-right of boulder field - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 50}, - {ZoomChange::KEEP_ZOOM, 0, 15, 110} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - - // // section 9.1. go to right edge of boulder field - // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 140, 0, 50); - // pbf_move_left_joystick(context, 128, 0, 200, 100); - - // section 10. walk up right edge - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 80}, - {ZoomChange::KEEP_ZOOM, 0, 12, 130} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - - // section 10.1 walk up right edge. until hit rock - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 15, 50); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 140, 0, 10, 5, false); - - // section 10.2. move away from rock. - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 255, 50); - pbf_move_left_joystick(context, 128, 0, 200, 100); - - // section 11 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 100}, - {ZoomChange::KEEP_ZOOM, 0, 5, 150} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - - // section 12. reach the top. battle Bombirdier - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 255, 100}, - {ZoomChange::KEEP_ZOOM, 50, 0, 170} - ); - try{ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 5, false); - }catch (OperationFailedException& e){ - (void) e; - // likely attempted to open/close phone to realign, but failed - // likely already reached cutscene to battle Bombirdeier. - - // keep waiting until battle detected. - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 128, 30, 30, false); - - } - - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); - // round 2 of battle - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); - // get ride upgrade - mash_button_till_overworld(env.console, context, BUTTON_A); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -void checkpoint_31( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1. fall down the mountain - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 80, 180}, - {ZoomChange::KEEP_ZOOM, 0, 170, 120} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 50, 10, false); - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 80, 100}, - {ZoomChange::KEEP_ZOOM, 0, 255, 55} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10, false); - // section 3. align to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 0, 40}, - {ZoomChange::KEEP_ZOOM, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10, false); - - // section 4. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 60, 40); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_14.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_14::name() const{ + return "11.2: Bombirdier Titan: Battle Bombirdier"; +} + +std::string AutoStory_Segment_14::start_text() const{ + return "Start: At West Province Area One Central Pokecenter"; +} + +std::string AutoStory_Segment_14::end_text() const{ + return "End: Defeated Bombirder. At West Province Area One North Pokecenter"; +} + +void AutoStory_Segment_14::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_ORANGE); + + checkpoint_30(env, context, options.notif_status_update); + checkpoint_31(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 11.2: Bombirdier Titan: Battle Bombirdier", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_30( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 128, 17); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 200, 200}, + {ZoomChange::KEEP_ZOOM, 0, 65, 220} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 200, 200}, + {ZoomChange::KEEP_ZOOM, 0, 80, 235} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 4. walk until Arven dialog + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 200, 200}, + {ZoomChange::KEEP_ZOOM, 0, 60, 280} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 30, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); + + // after Arven dialog. section 5 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 18, 6, false); + + // section 6 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 0, 0}, + {ZoomChange::KEEP_ZOOM, 0, 20, 65} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + get_on_ride(env.program_info(), env.console, context); + + // section 7 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 0, 0, 0}, + {ZoomChange::KEEP_ZOOM, 0, 30, 80} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 8. enter left side of boulder field + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 50}, + {ZoomChange::KEEP_ZOOM, 0, 40, 95} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 18, 6, false); + + // section 8.1. move up + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 0, 50); + pbf_move_left_joystick(context, 128, 0, 100, 100); + + // section 9. go to middle-right of boulder field + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 50}, + {ZoomChange::KEEP_ZOOM, 0, 15, 110} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + + // // section 9.1. go to right edge of boulder field + // realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 140, 0, 50); + // pbf_move_left_joystick(context, 128, 0, 200, 100); + + // section 10. walk up right edge + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 80}, + {ZoomChange::KEEP_ZOOM, 0, 12, 130} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + + // section 10.1 walk up right edge. until hit rock + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 15, 50); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 140, 0, 10, 5, false); + + // section 10.2. move away from rock. + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 80, 255, 50); + pbf_move_left_joystick(context, 128, 0, 200, 100); + + // section 11 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 100}, + {ZoomChange::KEEP_ZOOM, 0, 5, 150} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + + // section 12. reach the top. battle Bombirdier + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 255, 100}, + {ZoomChange::KEEP_ZOOM, 50, 0, 170} + ); + try{ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 5, false); + }catch (OperationFailedException& e){ + (void) e; + // likely attempted to open/close phone to realign, but failed + // likely already reached cutscene to battle Bombirdeier. + + // keep waiting until battle detected. + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 128, 30, 30, false); + + } + + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); + // round 2 of battle + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); + // get ride upgrade + mash_button_till_overworld(env.console, context, BUTTON_A); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +void checkpoint_31( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1. fall down the mountain + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 80, 180}, + {ZoomChange::KEEP_ZOOM, 0, 170, 120} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 50, 10, false); + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 80, 100}, + {ZoomChange::KEEP_ZOOM, 0, 255, 55} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10, false); + // section 3. align to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 0, 40}, + {ZoomChange::KEEP_ZOOM, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10, false); + + // section 4. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 60, 40); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h index d4c5128c8a..96fba8e84b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_14.h @@ -1,51 +1,51 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_14_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_14_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_14 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At West Province Area One Central Pokecenter -// end: Defeated Bombirdier -void checkpoint_30( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Bombirdier -// end: At West Province Area One North Pokecenter -void checkpoint_31( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_14_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_14_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_14 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At West Province Area One Central Pokecenter +// end: Defeated Bombirdier +void checkpoint_30( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Bombirdier +// end: At West Province Area One North Pokecenter +void checkpoint_31( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp index f7fb3e8fbb..46b8bb7165 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.cpp @@ -1,344 +1,344 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_15.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_15::name() const{ - return "12: Team Star (Dark)"; -} - -std::string AutoStory_Segment_15::start_text() const{ - return "Start: Defeated Bombirder. At West Province Area One North Pokecenter."; -} - -std::string AutoStory_Segment_15::end_text() const{ - return "End: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; -} - -void AutoStory_Segment_15::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 12: Team Star (Dark)", COLOR_ORANGE); - - checkpoint_32(env, context, options.notif_status_update); - checkpoint_33(env, context, options.notif_status_update); - checkpoint_34(env, context, options.notif_status_update); - - - context.wait_for_all_requests(); - env.console.log("End Segment 12: Team Star (Dark)", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_32( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 50, 0, 25); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 0, 80}, - {ZoomChange::ZOOM_IN, 5, 230, 145} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 0, 60}, - {ZoomChange::ZOOM_IN, 5, 205, 100} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 128, 255, 40}, - {ZoomChange::KEEP_ZOOM, 255, 0, 110} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // section 5 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 30, false); - - // battle team star grunts - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_33( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // enter the base - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, - 128, 0, 20, 20, false); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::TUTORIAL}); - AdvanceDialogWatcher dialog(COLOR_RED); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - - DirectionDetector direction; - uint16_t seconds_wait = 6; - - pbf_move_left_joystick(context, 128, 0, 250, 100); - direction.change_direction(env.program_info(), env.console, context, 3); - pbf_move_left_joystick(context, 128, 0, 10, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 4.1); - pbf_move_left_joystick(context, 128, 0, 750, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 5.04); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 0, 500, 100); - direction.change_direction(env.program_info(), env.console, context, 5.39); - pbf_move_left_joystick(context, 128, 0, 10, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 5.076); - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 0, 250, 100); - direction.change_direction(env.program_info(), env.console, context, 4.800); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 5.32); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 6.16); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - - direction.change_direction(env.program_info(), env.console, context, 0.541); - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 1.41); - pbf_move_left_joystick(context, 128, 0, 350, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 2.34); - pbf_move_left_joystick(context, 128, 0, 250, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - direction.change_direction(env.program_info(), env.console, context, 1.556); - pbf_move_left_joystick(context, 128, 0, 500, 100); - pbf_press_button(context, BUTTON_R, 20, 20); - pbf_wait(context, seconds_wait * TICKS_PER_SECOND); - - }, - {dialog} - ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_33(): Failed to kill 30 pokemon with Let's go.", - env.console - ); - } - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_34( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 128, 40}, - {ZoomChange::ZOOM_IN, 230, 0, 100} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 10, false); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 100, 30}, - {ZoomChange::ZOOM_IN, 0, 240, 40} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 3. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 4. set marker past pokecenter - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 40, 100); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_15.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_15::name() const{ + return "12: Team Star (Dark)"; +} + +std::string AutoStory_Segment_15::start_text() const{ + return "Start: Defeated Bombirder. At West Province Area One North Pokecenter."; +} + +std::string AutoStory_Segment_15::end_text() const{ + return "End: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; +} + +void AutoStory_Segment_15::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 12: Team Star (Dark)", COLOR_ORANGE); + + checkpoint_32(env, context, options.notif_status_update); + checkpoint_33(env, context, options.notif_status_update); + checkpoint_34(env, context, options.notif_status_update); + + + context.wait_for_all_requests(); + env.console.log("End Segment 12: Team Star (Dark)", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_32( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 50, 0, 25); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 0, 80}, + {ZoomChange::ZOOM_IN, 5, 230, 145} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 0, 60}, + {ZoomChange::ZOOM_IN, 5, 205, 100} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 128, 255, 40}, + {ZoomChange::KEEP_ZOOM, 255, 0, 110} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // section 5 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 30, false); + + // battle team star grunts + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::BLACK_DIALOG_BOX}); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_33( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // enter the base + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 50); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_SPAM_A, + 128, 0, 20, 20, false); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG, CallbackEnum::TUTORIAL}); + AdvanceDialogWatcher dialog(COLOR_RED); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + + DirectionDetector direction; + uint16_t seconds_wait = 6; + + pbf_move_left_joystick(context, 128, 0, 250, 100); + direction.change_direction(env.program_info(), env.console, context, 3); + pbf_move_left_joystick(context, 128, 0, 10, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 4.1); + pbf_move_left_joystick(context, 128, 0, 750, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 5.04); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 0, 500, 100); + direction.change_direction(env.program_info(), env.console, context, 5.39); + pbf_move_left_joystick(context, 128, 0, 10, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 5.076); + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 0, 250, 100); + direction.change_direction(env.program_info(), env.console, context, 4.800); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 5.32); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 6.16); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + + direction.change_direction(env.program_info(), env.console, context, 0.541); + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 1.41); + pbf_move_left_joystick(context, 128, 0, 350, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 2.34); + pbf_move_left_joystick(context, 128, 0, 250, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + direction.change_direction(env.program_info(), env.console, context, 1.556); + pbf_move_left_joystick(context, 128, 0, 500, 100); + pbf_press_button(context, BUTTON_R, 20, 20); + pbf_wait(context, seconds_wait * TICKS_PER_SECOND); + + }, + {dialog} + ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_33(): Failed to kill 30 pokemon with Let's go.", + env.console + ); + } + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {}, true); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_34( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 128, 40}, + {ZoomChange::ZOOM_IN, 230, 0, 100} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 10, false); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 100, 30}, + {ZoomChange::ZOOM_IN, 0, 240, 40} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 3. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 4. set marker past pokecenter + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 40, 100); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h index ae8b01571a..455d92b7d2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_15.h @@ -1,59 +1,59 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_15_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_15_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_15 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - - -// start: At West Province Area One North Pokecenter -// end: Defeated Team Star (Dark) grunts at base entrance -void checkpoint_32( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Team star dark grunts at base entrance -// end: Defeated Team Star (Dark) boss -void checkpoint_33( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Team Star (Dark) boss -// end: At Cascarrafa (West) Pokecenter. -void checkpoint_34( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_15_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_15_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_15 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + + +// start: At West Province Area One North Pokecenter +// end: Defeated Team Star (Dark) grunts at base entrance +void checkpoint_32( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Team star dark grunts at base entrance +// end: Defeated Team Star (Dark) boss +void checkpoint_33( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Team Star (Dark) boss +// end: At Cascarrafa (West) Pokecenter. +void checkpoint_34( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp index c38e5a7806..551ef00bf0 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.cpp @@ -1,197 +1,197 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_16.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_16::name() const{ - return "13.1: Cascarrafa Gym (Water): Get Kofu's wallet"; -} - -std::string AutoStory_Segment_16::start_text() const{ - return "Start: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; -} - -std::string AutoStory_Segment_16::end_text() const{ - return "End: Received Kofu's wallet. At Porto Marinada Pokecenter."; -} - -void AutoStory_Segment_16::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_ORANGE); - - checkpoint_35(env, context, options.notif_status_update); - checkpoint_36(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_35( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 0.3491); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 5.075911); - pbf_move_left_joystick(context, 128, 0, 525, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 3.771252); - get_on_ride(env.program_info(), env.console, context); - // walk towards elevator - pbf_move_left_joystick(context, 128, 0, 700, 100); - // jump to ensure you get on elevator - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld to reappear after stepping off elevator - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 120, 100); - direction.change_direction(env.program_info(), env.console, context, 5.11); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_36( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 100, 0, 80}); - - // section 1 - // warning: can't reliably set the marker when in Cascarrafa, possibly due to too many NPCs. worse when sandstorm is up. - // what happens is that the program doesn't reliably push the cursor as much as it should - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 135, 410); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 20, false); - // talk to Arven over phone - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 80}, - {ZoomChange::ZOOM_IN, 255, 255, 110} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 20, false); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 40}, - {ZoomChange::ZOOM_IN, 255, 128, 45} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // cutscene with Kofu looking at flowers - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // section 4. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 5. set marker past pokecenter - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 100, 30); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_16.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_16::name() const{ + return "13.1: Cascarrafa Gym (Water): Get Kofu's wallet"; +} + +std::string AutoStory_Segment_16::start_text() const{ + return "Start: Defeated Team Star (Dark). At Cascarrafa (West) Pokecenter."; +} + +std::string AutoStory_Segment_16::end_text() const{ + return "End: Received Kofu's wallet. At Porto Marinada Pokecenter."; +} + +void AutoStory_Segment_16::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_ORANGE); + + checkpoint_35(env, context, options.notif_status_update); + checkpoint_36(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 13.1: Cascarrafa Gym (Water): Get Kofu's wallet", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_35( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 0.3491); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 5.075911); + pbf_move_left_joystick(context, 128, 0, 525, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 3.771252); + get_on_ride(env.program_info(), env.console, context); + // walk towards elevator + pbf_move_left_joystick(context, 128, 0, 700, 100); + // jump to ensure you get on elevator + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld to reappear after stepping off elevator + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 120, 100); + direction.change_direction(env.program_info(), env.console, context, 5.11); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_36( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 100, 0, 80}); + + // section 1 + // warning: can't reliably set the marker when in Cascarrafa, possibly due to too many NPCs. worse when sandstorm is up. + // what happens is that the program doesn't reliably push the cursor as much as it should + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 135, 410); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 20, false); + // talk to Arven over phone + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 80}, + {ZoomChange::ZOOM_IN, 255, 255, 110} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 20, false); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 40}, + {ZoomChange::ZOOM_IN, 255, 128, 45} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // cutscene with Kofu looking at flowers + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // section 4. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 5. set marker past pokecenter + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 100, 30); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h index a6d5ddcb8c..74ba92f801 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_16.h @@ -1,52 +1,52 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_16_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_16_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_16 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Cascarrafa (West) Pokecenter. -// end: At Cascarrafa Gym. Received Kofu's wallet. -void checkpoint_35( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At Cascarrafa Gym. Received Kofu's wallet. -// end: At Porto Marinada Pokecenter. -void checkpoint_36( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_16_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_16_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_16 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Cascarrafa (West) Pokecenter. +// end: At Cascarrafa Gym. Received Kofu's wallet. +void checkpoint_35( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At Cascarrafa Gym. Received Kofu's wallet. +// end: At Porto Marinada Pokecenter. +void checkpoint_36( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp index 1d4574d920..ccf19c9fe3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.cpp @@ -1,190 +1,190 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_17.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_17::name() const{ - return "13.2: Cascarrafa Gym (Water): Gym challenge and Gym battle"; -} - -std::string AutoStory_Segment_17::start_text() const{ - return "Start: Received Kofu's wallet. At Porto Marinada Pokecenter."; -} - -std::string AutoStory_Segment_17::end_text() const{ - return "End: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; -} - -void AutoStory_Segment_17::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_ORANGE); - - checkpoint_37(env, context, options.notif_status_update); - checkpoint_38(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_37( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 255, 50); - - // section 1 - direction.change_direction(env.program_info(), env.console, context, 1.606); - pbf_move_left_joystick(context, 128, 0, 200, 100); - - get_on_ride(env.program_info(), env.console, context); - - // section 2 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - }); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - // section 3. set marker to shop/Kofu - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 140, 27); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_38( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 180, 170}); - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 0.3491); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 5.075911); - pbf_move_left_joystick(context, 128, 0, 525, 100); - }); - - direction.change_direction(env.program_info(), env.console, context, 3.771252); - get_on_ride(env.program_info(), env.console, context); - // walk towards elevator - pbf_move_left_joystick(context, 128, 0, 700, 100); - // jump to ensure you get on elevator - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld to reappear after stepping off elevator - wait_for_overworld(env.program_info(), env.console, context, 30); - - pbf_move_left_joystick(context, 128, 0, 120, 100); - - direction.change_direction(env.program_info(), env.console, context, 5.11); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - direction.change_direction(env.program_info(), env.console, context, 3.2245); - - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 18); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 0, 100, 50); - pbf_move_left_joystick(context, 0, 0, 100, 50); - } - ); - // talk to Nemona - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - // talk to reception. Battle Kofu - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_17.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_17::name() const{ + return "13.2: Cascarrafa Gym (Water): Gym challenge and Gym battle"; +} + +std::string AutoStory_Segment_17::start_text() const{ + return "Start: Received Kofu's wallet. At Porto Marinada Pokecenter."; +} + +std::string AutoStory_Segment_17::end_text() const{ + return "End: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; +} + +void AutoStory_Segment_17::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_ORANGE); + + checkpoint_37(env, context, options.notif_status_update); + checkpoint_38(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 13.2: Cascarrafa Gym (Water): Gym battle", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_37( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 255, 50); + + // section 1 + direction.change_direction(env.program_info(), env.console, context, 1.606); + pbf_move_left_joystick(context, 128, 0, 200, 100); + + get_on_ride(env.program_info(), env.console, context); + + // section 2 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + }); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + // section 3. set marker to shop/Kofu + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 140, 27); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_38( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 180, 170}); + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 0.3491); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 5.075911); + pbf_move_left_joystick(context, 128, 0, 525, 100); + }); + + direction.change_direction(env.program_info(), env.console, context, 3.771252); + get_on_ride(env.program_info(), env.console, context); + // walk towards elevator + pbf_move_left_joystick(context, 128, 0, 700, 100); + // jump to ensure you get on elevator + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld to reappear after stepping off elevator + wait_for_overworld(env.program_info(), env.console, context, 30); + + pbf_move_left_joystick(context, 128, 0, 120, 100); + + direction.change_direction(env.program_info(), env.console, context, 5.11); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + direction.change_direction(env.program_info(), env.console, context, 3.2245); + + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 18); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 0, 100, 50); + pbf_move_left_joystick(context, 0, 0, 100, 50); + } + ); + // talk to Nemona + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + // talk to reception. Battle Kofu + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}, true); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h index 95db8b3f35..0153ed5bb6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_17.h @@ -1,50 +1,50 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_17_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_17_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_17 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At Porto Marinada Pokecenter. -// end: Won auction at Porto Marinada, passed Gym challenge. -void checkpoint_37( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Won auction at Porto Marinada, passed Gym challenge. -// end: Defeat Cascarrafa Gym -void checkpoint_38( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_17_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_17_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_17 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At Porto Marinada Pokecenter. +// end: Won auction at Porto Marinada, passed Gym challenge. +void checkpoint_37( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Won auction at Porto Marinada, passed Gym challenge. +// end: Defeat Cascarrafa Gym +void checkpoint_38( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp index d406383e8e..78c42ff55e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.cpp @@ -1,373 +1,373 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_18.h" - -// #include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_18::name() const{ - return "14: Great Tusk/Iron Treads titan"; -} - -std::string AutoStory_Segment_18::start_text() const{ - return "Start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; -} - -std::string AutoStory_Segment_18::end_text() const{ - return "End: Defeated Great Tusk/Iron Treads. At South Province (Area Three) Pokecenter."; -} - -void AutoStory_Segment_18::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 14: Great Tusk/Iron Treads titan", COLOR_ORANGE); - - checkpoint_39(env, context, options.notif_status_update); - checkpoint_40(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 14: Great Tusk/Iron Treads titan", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_39( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving Gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - // fly to Porto Marinada pokecenter - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 0, 80, 150}); - - DirectionDetector direction; - - // section 1 - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 4.677921); - pbf_move_left_joystick(context, 128, 0, 150, 100); - }); - - // section 2 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 230, 120); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 10, false); - - // section 3. enter circle - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 50}, - {ZoomChange::ZOOM_IN, 175, 255, 120} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 60, 10, false); - - DialogBoxWatcher dialog(COLOR_RED, true); - - // section 4 - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - // run around in circles until you run into the titan - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(30)){ - break; - } - // std::cout << "1:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 160, 255, 90} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - - - // std::cout << "11:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 135, 255, 90} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - - // std::cout << "10:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 120, 255, 105} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // std::cout << "7:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 115, 255, 127} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 48, 12, false); - - // std::cout << "6:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 135, 255, 137} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - - // std::cout << "2:00" << std::endl; - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 200, 255, 120} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 50, 10, false); - } - - }, - {dialog} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "checkpoint_39(): Failed to run into Great Tusk/Iron Treads.", - env.console - ); - } - - // battle the titan phase 1 - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::BLACK_DIALOG_BOX}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); - - // section 5 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 40}, - {ZoomChange::ZOOM_IN, 122, 255, 130} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - - // section 6 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 128, 0, 50}, - {ZoomChange::ZOOM_IN, 90, 255, 170} - ); - - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 40, 40, false); - - // battle the titan phase 2 - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A, 360); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_40( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - // fly to Mesagoza East - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 185, 440}); - - // place down marker, for section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 180, 90); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 5.60); - - get_on_ride(env.program_info(), env.console, context); - - // jump over the fence to exit Mesagoza - pbf_move_left_joystick(context, 128, 0, 200, 50); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); - - wait_for_overworld(env.program_info(), env.console, context); - - // section 1 - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 128, 40}, - {ZoomChange::ZOOM_IN, 255, 140, 100} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 150, 50}, - {ZoomChange::ZOOM_IN, 255, 90, 120} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::ZOOM_IN, 255, 50, 30}, - {ZoomChange::KEEP_ZOOM, 0, 0, 0} - ); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 0, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 160, 40); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter - - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_18.h" + +// #include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_18::name() const{ + return "14: Great Tusk/Iron Treads titan"; +} + +std::string AutoStory_Segment_18::start_text() const{ + return "Start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym."; +} + +std::string AutoStory_Segment_18::end_text() const{ + return "End: Defeated Great Tusk/Iron Treads. At South Province (Area Three) Pokecenter."; +} + +void AutoStory_Segment_18::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 14: Great Tusk/Iron Treads titan", COLOR_ORANGE); + + checkpoint_39(env, context, options.notif_status_update); + checkpoint_40(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 14: Great Tusk/Iron Treads titan", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_39( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving Gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + // fly to Porto Marinada pokecenter + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 0, 80, 150}); + + DirectionDetector direction; + + // section 1 + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 4.677921); + pbf_move_left_joystick(context, 128, 0, 150, 100); + }); + + // section 2 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 230, 120); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 10, false); + + // section 3. enter circle + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 50}, + {ZoomChange::ZOOM_IN, 175, 255, 120} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 60, 10, false); + + DialogBoxWatcher dialog(COLOR_RED, true); + + // section 4 + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + // run around in circles until you run into the titan + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(30)){ + break; + } + // std::cout << "1:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 160, 255, 90} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + + + // std::cout << "11:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 135, 255, 90} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + + // std::cout << "10:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 120, 255, 105} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // std::cout << "7:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 115, 255, 127} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 48, 12, false); + + // std::cout << "6:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 135, 255, 137} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + + // std::cout << "2:00" << std::endl; + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 200, 255, 120} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 50, 10, false); + } + + }, + {dialog} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "checkpoint_39(): Failed to run into Great Tusk/Iron Treads.", + env.console + ); + } + + // battle the titan phase 1 + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE, CallbackEnum::BLACK_DIALOG_BOX}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); + + // section 5 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 40}, + {ZoomChange::ZOOM_IN, 122, 255, 130} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + + // section 6 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 128, 0, 50}, + {ZoomChange::ZOOM_IN, 90, 255, 170} + ); + + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 40, 40, false); + + // battle the titan phase 2 + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BATTLE}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A, 360); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_40( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + // fly to Mesagoza East + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::KEEP_ZOOM, 255, 185, 440}); + + // place down marker, for section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 180, 90); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 5.60); + + get_on_ride(env.program_info(), env.console, context); + + // jump over the fence to exit Mesagoza + pbf_move_left_joystick(context, 128, 0, 200, 50); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 200); + + wait_for_overworld(env.program_info(), env.console, context); + + // section 1 + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 128, 40}, + {ZoomChange::ZOOM_IN, 255, 140, 100} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 150, 50}, + {ZoomChange::ZOOM_IN, 255, 90, 120} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::ZOOM_IN, 255, 50, 30}, + {ZoomChange::KEEP_ZOOM, 0, 0, 0} + ); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 0, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 160, 40); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter + + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h index e2660a7e4a..f0181b8edb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_18.h @@ -1,51 +1,51 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_18_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_18_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_18 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym. -// end: Defeated Great Tusk/Iron Treads. -void checkpoint_39( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Great Tusk/Iron Treads. -// end: At South Province (Area Three) Pokecenter. -void checkpoint_40( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_18_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_18_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_18 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: Defeated Cascarrafa Gym (Water). At Cascarrafa Gym. +// end: Defeated Great Tusk/Iron Treads. +void checkpoint_39( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Great Tusk/Iron Treads. +// end: At South Province (Area Three) Pokecenter. +void checkpoint_40( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp index 3b1cf9f720..1a182a079d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.cpp @@ -1,376 +1,376 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_19.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_19::name() const{ - return "15.1: Klawf Titan: Battle Klawf"; -} - -std::string AutoStory_Segment_19::start_text() const{ - return "Start: At South Province (Area Three) Pokecenter."; -} - -std::string AutoStory_Segment_19::end_text() const{ - return "End: Defeated Klawf. At Artazon (West) Pokecenter."; -} - -void AutoStory_Segment_19::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment 15.2: Klawf Titan: Battle Klawf", COLOR_ORANGE); - - checkpoint_41(env, context, options.notif_status_update); - checkpoint_42(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment 15.2: Klawf Titan: Battle Klawf", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -void checkpoint_41( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 0.14); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 200, 100); - }); - - // section 2. walk until hit dialog - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 128, 70}, - {ZoomChange::ZOOM_IN, 255, 93, 170} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 20, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - // clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::BLACK_DIALOG_BOX}); - mash_button_till_overworld(env.console, context, BUTTON_A); - - - // section 3. - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 128, 100}, - {ZoomChange::ZOOM_IN, 0, 90, 157} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 255, 128, 50, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 70}, - {ZoomChange::ZOOM_IN, 0, 95, 112} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 6 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 128, 60}, - {ZoomChange::ZOOM_IN, 0, 50, 105} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 8, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 50, 50); - pbf_move_left_joystick(context, 255, 128, 50, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 7. walk up to Klawf on the lower wall, so it moves to the high ground - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 50}, - {ZoomChange::ZOOM_IN, 0, 40, 110} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 8. walk up to Klawf on lower wall - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 50}, - {ZoomChange::ZOOM_IN, 30, 30, 135} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 10, 10, false); - - // section 9 - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_right_joystick(context, 255, 128, 100, 50); - direction.change_direction(env.program_info(), env.console, context, 4.467); - pbf_move_left_joystick(context, 128, 0, 700, 50); - pbf_move_left_joystick(context, 0, 128, 100, 50); - pbf_move_left_joystick(context, 0, 0, 500, 50); - direction.change_direction(env.program_info(), env.console, context, 2.795); - pbf_move_left_joystick(context, 128, 0, 200, 50); - direction.change_direction(env.program_info(), env.console, context, 4.747); - pbf_move_left_joystick(context, 128, 0, 600, 50); - direction.change_direction(env.program_info(), env.console, context, 5.479); - pbf_move_left_joystick(context, 128, 0, 400, 50); - direction.change_direction(env.program_info(), env.console, context, 0.33); - pbf_move_left_joystick(context, 128, 0, 900, 50); - direction.change_direction(env.program_info(), env.console, context, 2.325); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 25, 25, false); - - - // battle Klawf phase 1 - run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 2.83); - // pbf_move_left_joystick(context, 128, 0, 800, 50); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 35, 35, false); - - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); - // Klawf battle phase 2 - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); - // get ride upgrade - mash_button_till_overworld(env.console, context, BUTTON_A); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_42( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - } - context.wait_for_all_requests(); - - // section 1 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 180, 50}, - {ZoomChange::ZOOM_IN, 0, 80, 110} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 12, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 2 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 150, 50}, - {ZoomChange::ZOOM_IN, 0, 80, 38} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 36, 12, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 3 - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 65, 0, 45} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 24, 12, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 4. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 0, 0, 0}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 30, 10, false); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 128, 40, 50); - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); - } - ); - - // section 5. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 30); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter - - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_19.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_19::name() const{ + return "15.1: Klawf Titan: Battle Klawf"; +} + +std::string AutoStory_Segment_19::start_text() const{ + return "Start: At South Province (Area Three) Pokecenter."; +} + +std::string AutoStory_Segment_19::end_text() const{ + return "End: Defeated Klawf. At Artazon (West) Pokecenter."; +} + +void AutoStory_Segment_19::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment 15.2: Klawf Titan: Battle Klawf", COLOR_ORANGE); + + checkpoint_41(env, context, options.notif_status_update); + checkpoint_42(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment 15.2: Klawf Titan: Battle Klawf", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +void checkpoint_41( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 0.14); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 200, 100); + }); + + // section 2. walk until hit dialog + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 128, 70}, + {ZoomChange::ZOOM_IN, 255, 93, 170} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 20, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + // clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::BLACK_DIALOG_BOX}); + mash_button_till_overworld(env.console, context, BUTTON_A); + + + // section 3. + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 128, 100}, + {ZoomChange::ZOOM_IN, 0, 90, 157} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 255, 128, 50, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 70}, + {ZoomChange::ZOOM_IN, 0, 95, 112} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 6 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 128, 60}, + {ZoomChange::ZOOM_IN, 0, 50, 105} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 8, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 50, 50); + pbf_move_left_joystick(context, 255, 128, 50, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 7. walk up to Klawf on the lower wall, so it moves to the high ground + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 50}, + {ZoomChange::ZOOM_IN, 0, 40, 110} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 8. walk up to Klawf on lower wall + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 50}, + {ZoomChange::ZOOM_IN, 30, 30, 135} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 10, 10, false); + + // section 9 + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_right_joystick(context, 255, 128, 100, 50); + direction.change_direction(env.program_info(), env.console, context, 4.467); + pbf_move_left_joystick(context, 128, 0, 700, 50); + pbf_move_left_joystick(context, 0, 128, 100, 50); + pbf_move_left_joystick(context, 0, 0, 500, 50); + direction.change_direction(env.program_info(), env.console, context, 2.795); + pbf_move_left_joystick(context, 128, 0, 200, 50); + direction.change_direction(env.program_info(), env.console, context, 4.747); + pbf_move_left_joystick(context, 128, 0, 600, 50); + direction.change_direction(env.program_info(), env.console, context, 5.479); + pbf_move_left_joystick(context, 128, 0, 400, 50); + direction.change_direction(env.program_info(), env.console, context, 0.33); + pbf_move_left_joystick(context, 128, 0, 900, 50); + direction.change_direction(env.program_info(), env.console, context, 2.325); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_BATTLE, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 25, 25, false); + + + // battle Klawf phase 1 + run_battle_press_A(env.console, context, BattleStopCondition::STOP_OVERWORLD); + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 2.83); + // pbf_move_left_joystick(context, 128, 0, 800, 50); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_DIALOG, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 35, 35, false); + + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 30, {CallbackEnum::BATTLE}); + // Klawf battle phase 2 + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::DIALOG_ARROW}); + // get ride upgrade + mash_button_till_overworld(env.console, context, BUTTON_A); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_42( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + } + context.wait_for_all_requests(); + + // section 1 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 180, 50}, + {ZoomChange::ZOOM_IN, 0, 80, 110} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 12, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 2 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 150, 50}, + {ZoomChange::ZOOM_IN, 0, 80, 38} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 36, 12, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 3 + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 65, 0, 45} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 24, 12, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 4. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 0, 0, 0}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 30, 10, false); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 128, 40, 50); + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_OLD_MARKER); + } + ); + + // section 5. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 255, 255, 30); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); // can't wrap in handle_when_stationary_in_overworld(), since we expect to be stationary when walking into the pokecenter + + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h index 49aa9afc03..e7b35e2f58 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_19.h @@ -1,50 +1,50 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_19_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_19_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_19 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At South Province (Area Three) Pokecenter. -// end: Defeated Klawf. -void checkpoint_41( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Defeated Klawf. -// end: Defeated Klawf. At Artazon (West) Pokecenter. -void checkpoint_42( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_19_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_19_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_19 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At South Province (Area Three) Pokecenter. +// end: Defeated Klawf. +void checkpoint_41( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Defeated Klawf. +// end: Defeated Klawf. At Artazon (West) Pokecenter. +void checkpoint_42( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp index 8dd367fd2d..d2dfd9aae4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.cpp @@ -1,559 +1,559 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_20.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_20::name() const{ - return "16: Artazon Gym (Grass)"; -} - -std::string AutoStory_Segment_20::start_text() const{ - return "Start: Defeated Klawf. At Artazon (West) Pokecenter."; -} - -std::string AutoStory_Segment_20::end_text() const{ - return "End: Defeated Artazon Gym (Grass). Inside gym building."; -} - -void AutoStory_Segment_20::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment ", COLOR_ORANGE); - - checkpoint_43(env, context, options.notif_status_update); - checkpoint_44(env, context, options.notif_status_update); - checkpoint_45(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -void checkpoint_43( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - context.wait_for_all_requests(); - - // place the marker somewhere else. the current location disrupts the Stationary detector - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 50); - - DirectionDetector direction; - do_action_and_monitor_for_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - direction.change_direction(env.program_info(), env.console, context, 6.198); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 4.693); - pbf_move_left_joystick(context, 128, 0, 1000, 100); - }); - // walk up right set of stairs - direction.change_direction(env.program_info(), env.console, context, 4.276); - pbf_move_left_joystick(context, 128, 0, 700, 100); - - // realign using lamp-post - direction.change_direction(env.program_info(), env.console, context, 2.34); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 1.81); - pbf_move_left_joystick(context, 255, 0, 600, 100); - - // move toward gym building - direction.change_direction(env.program_info(), env.console, context, 4.26); - pbf_move_left_joystick(context, 128, 0, 900, 100); - direction.change_direction(env.program_info(), env.console, context, 3.05); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_wait(context, 7 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 50); - }, - 5, 5 - ); - - // enter gym building. talk go Nemona and battle her. - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BLACK_DIALOG_BOX, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_44( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - // talk to receptionist - env.console.log("Talk to Artazon gym receptionist."); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - // talk to Sunflora NPC - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 4.91); - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); - - // realign to wall - direction.change_direction(env.program_info(), env.console, context, 1.477); - pbf_move_left_joystick(context, 128, 0, 500, 100); - direction.change_direction(env.program_info(), env.console, context, 2.166); - pbf_move_left_joystick(context, 0, 0, 300, 100); - - // get sunflora 1 - direction.change_direction(env.program_info(), env.console, context, 4.85); - pbf_move_left_joystick(context, 128, 0, 300, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 1); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // get sunflora 2 - direction.change_direction(env.program_info(), env.console, context, 0.384); - pbf_move_left_joystick(context, 128, 0, 120, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 2); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // get sunflora 3 - direction.change_direction(env.program_info(), env.console, context, 5.377); - pbf_move_left_joystick(context, 128, 0, 120, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 3); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - get_on_ride(env.program_info(), env.console, context); - - // get sunflora 4 - // align to corner 4.1 - direction.change_direction(env.program_info(), env.console, context, 1.90); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 2.166); - pbf_move_left_joystick(context, 0, 0, 300, 100); - - // align to corner 4.2 - direction.change_direction(env.program_info(), env.console, context, 6.056); - pbf_move_left_joystick(context, 128, 0, 670, 100); - direction.change_direction(env.program_info(), env.console, context, 1.22); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 1.69); - pbf_move_left_joystick(context, 0, 0, 500, 100); - - direction.change_direction(env.program_info(), env.console, context, 5.85); - pbf_move_left_joystick(context, 128, 0, 60, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 4); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // get sunflora 5 - // align to corner 5.1 - direction.change_direction(env.program_info(), env.console, context, 1.59); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 1.79); - pbf_move_left_joystick(context, 0, 0, 500, 100); - direction.change_direction(env.program_info(), env.console, context, 6.055); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 5.06); - pbf_move_left_joystick(context, 128, 0, 600, 100); - direction.change_direction(env.program_info(), env.console, context, 4.38); - pbf_move_left_joystick(context, 0, 0, 700, 100); - - direction.change_direction(env.program_info(), env.console, context, 2.53); - pbf_move_left_joystick(context, 128, 0, 160, 100); - direction.change_direction(env.program_info(), env.console, context, 0.78); - pbf_move_left_joystick(context, 128, 0, 90, 100); // todo: adjust this. 80 -> 90? - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 5); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 6 - // align to corner 6.1 - direction.change_direction(env.program_info(), env.console, context, 4.2); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 4.38); - pbf_move_left_joystick(context, 0, 0, 700, 100); - - direction.change_direction(env.program_info(), env.console, context, 0.96); - pbf_move_left_joystick(context, 128, 0, 300, 100); - direction.change_direction(env.program_info(), env.console, context, 5.17); - pbf_move_left_joystick(context, 128, 0, 100, 100); - direction.change_direction(env.program_info(), env.console, context, 3.86); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 6); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 7 - // align to corner 7.1 - direction.change_direction(env.program_info(), env.console, context, 2.06); - pbf_move_left_joystick(context, 128, 0, 80, 100); - direction.change_direction(env.program_info(), env.console, context, 4.7); - pbf_move_left_joystick(context, 128, 0, 100, 100); - direction.change_direction(env.program_info(), env.console, context, 5.01); - pbf_move_left_joystick(context, 128, 0, 1600, 100); - - // align to corner 7.2. bush - direction.change_direction(env.program_info(), env.console, context, 2.34); - pbf_move_left_joystick(context, 128, 0, 700, 100); - direction.change_direction(env.program_info(), env.console, context, 3.42); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - // align to corner 7.3. lamp-post - // todo: adjust routine to get to lampost. go behind the sculpture and goat? - direction.change_direction(env.program_info(), env.console, context, 0); - pbf_move_left_joystick(context, 128, 0, 120, 100); - direction.change_direction(env.program_info(), env.console, context, 1.75); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 2.95); - pbf_move_left_joystick(context, 128, 0, 300, 100); - direction.change_direction(env.program_info(), env.console, context, 2.22); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 1.01); - pbf_move_left_joystick(context, 128, 0, 300, 100); - - // align to corner 7.4. wall corner - direction.change_direction(env.program_info(), env.console, context, 3.70); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 4.28); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 3.54); - pbf_move_left_joystick(context, 128, 0, 600, 100); - - // align to corner 7.5. bush - direction.change_direction(env.program_info(), env.console, context, 3.11); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 60, 100); - direction.change_direction(env.program_info(), env.console, context, 4.28); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 3.60); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - direction.change_direction(env.program_info(), env.console, context, 1.17); - pbf_move_left_joystick(context, 128, 0, 130, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 7); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 8 - // align to corner 8.1. bush - direction.change_direction(env.program_info(), env.console, context, 4.54); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 3.60); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - direction.change_direction(env.program_info(), env.console, context, 1.64); - pbf_move_left_joystick(context, 128, 0, 350, 100); - direction.change_direction(env.program_info(), env.console, context, 4.36); - pbf_move_left_joystick(context, 128, 0, 100, 100); - - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 50, 50); - pbf_press_button(context, BUTTON_A, 50, 50); // extra press in case one is dropped - pbf_press_button(context, BUTTON_A, 50, 50); - pbf_wait(context, 250); - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - check_num_sunflora_found(env, context, 8); - pbf_wait(context, 3 * TICKS_PER_SECOND); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // // sunflora 9 - // // align to corner 9.1. bush - pbf_move_left_joystick(context, 128, 255, 200, 100); - direction.change_direction(env.program_info(), env.console, context, 4.89); - pbf_move_left_joystick(context, 128, 0, 350, 100); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 180); - get_off_ride(env.program_info(), env.console, context); - direction.change_direction(env.program_info(), env.console, context, 3.60); - pbf_move_left_joystick(context, 128, 0, 600, 100); - - - direction.change_direction(env.program_info(), env.console, context, 1.48); - pbf_move_left_joystick(context, 128, 0, 50, 100); - direction.change_direction(env.program_info(), env.console, context, 3.11); - pbf_move_left_joystick(context, 128, 0, 180, 100); - direction.change_direction(env.program_info(), env.console, context, 4.75); - pbf_move_left_joystick(context, 128, 0, 100, 100); - get_on_ride(env.program_info(), env.console, context); - direction.change_direction(env.program_info(), env.console, context, 5.53); - pbf_move_left_joystick(context, 128, 0, 600, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 9); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // sunflora 10 - // align to corner 10.1. bush - pbf_move_left_joystick(context, 0, 128, 200, 100); - - direction.change_direction(env.program_info(), env.console, context, 4.02); - pbf_move_left_joystick(context, 128, 0, 250, 100); - handle_failed_action(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 500); - check_num_sunflora_found(env, context, 10); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30, 100); - }, - 3 - ); - - // go back to Sunflora NPC - // align to corner 11.1. bush - direction.change_direction(env.program_info(), env.console, context, 0.65); - pbf_move_left_joystick(context, 128, 0, 200, 100); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 800, 100); - - direction.change_direction(env.program_info(), env.console, context, 4.49); - pbf_move_left_joystick(context, 128, 0, 100, 100); - direction.change_direction(env.program_info(), env.console, context, 5.53); - - NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 30 * TICKS_PER_SECOND, 100); - }, - {no_minimap} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to finish reach the Sunflora NPC.", - env.console - ); - } - env.log("No minimap seen. Likely finished the Artazon gym challenge."); - - clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - -void checkpoint_45( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - get_on_ride(env.program_info(), env.console, context); - - DirectionDetector direction; - direction.change_direction(env.program_info(), env.console, context, 1.52); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 2.62); - pbf_move_left_joystick(context, 128, 0, 400, 100); - - direction.change_direction(env.program_info(), env.console, context, 2.18); - pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); - pbf_move_left_joystick(context, 128, 0, 400, 100); - direction.change_direction(env.program_info(), env.console, context, 3.16); - pbf_move_left_joystick(context, 0, 0, 100, 50); - - handle_when_stationary_in_overworld(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); - }, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 0, 100, 50); - pbf_move_left_joystick(context, 255, 0, 100, 50); - }, - 5, 2, 2 - ); - - clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); - run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); - mash_button_till_overworld(env.console, context, BUTTON_A); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_NoMinimapDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_20.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_20::name() const{ + return "16: Artazon Gym (Grass)"; +} + +std::string AutoStory_Segment_20::start_text() const{ + return "Start: Defeated Klawf. At Artazon (West) Pokecenter."; +} + +std::string AutoStory_Segment_20::end_text() const{ + return "End: Defeated Artazon Gym (Grass). Inside gym building."; +} + +void AutoStory_Segment_20::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + checkpoint_43(env, context, options.notif_status_update); + checkpoint_44(env, context, options.notif_status_update); + checkpoint_45(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +void checkpoint_43( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + context.wait_for_all_requests(); + + // place the marker somewhere else. the current location disrupts the Stationary detector + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 0, 128, 50); + + DirectionDetector direction; + do_action_and_monitor_for_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + direction.change_direction(env.program_info(), env.console, context, 6.198); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 4.693); + pbf_move_left_joystick(context, 128, 0, 1000, 100); + }); + // walk up right set of stairs + direction.change_direction(env.program_info(), env.console, context, 4.276); + pbf_move_left_joystick(context, 128, 0, 700, 100); + + // realign using lamp-post + direction.change_direction(env.program_info(), env.console, context, 2.34); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 1.81); + pbf_move_left_joystick(context, 255, 0, 600, 100); + + // move toward gym building + direction.change_direction(env.program_info(), env.console, context, 4.26); + pbf_move_left_joystick(context, 128, 0, 900, 100); + direction.change_direction(env.program_info(), env.console, context, 3.05); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_wait(context, 7 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_ONLY, 20); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 50); + }, + 5, 5 + ); + + // enter gym building. talk go Nemona and battle her. + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::BLACK_DIALOG_BOX, CallbackEnum::PROMPT_DIALOG, CallbackEnum::DIALOG_ARROW, CallbackEnum::BATTLE}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_44( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + // talk to receptionist + env.console.log("Talk to Artazon gym receptionist."); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + // talk to Sunflora NPC + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 4.91); + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 10); + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD, CallbackEnum::PROMPT_DIALOG}); + + // realign to wall + direction.change_direction(env.program_info(), env.console, context, 1.477); + pbf_move_left_joystick(context, 128, 0, 500, 100); + direction.change_direction(env.program_info(), env.console, context, 2.166); + pbf_move_left_joystick(context, 0, 0, 300, 100); + + // get sunflora 1 + direction.change_direction(env.program_info(), env.console, context, 4.85); + pbf_move_left_joystick(context, 128, 0, 300, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 1); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // get sunflora 2 + direction.change_direction(env.program_info(), env.console, context, 0.384); + pbf_move_left_joystick(context, 128, 0, 120, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 2); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // get sunflora 3 + direction.change_direction(env.program_info(), env.console, context, 5.377); + pbf_move_left_joystick(context, 128, 0, 120, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 3); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + get_on_ride(env.program_info(), env.console, context); + + // get sunflora 4 + // align to corner 4.1 + direction.change_direction(env.program_info(), env.console, context, 1.90); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 2.166); + pbf_move_left_joystick(context, 0, 0, 300, 100); + + // align to corner 4.2 + direction.change_direction(env.program_info(), env.console, context, 6.056); + pbf_move_left_joystick(context, 128, 0, 670, 100); + direction.change_direction(env.program_info(), env.console, context, 1.22); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 1.69); + pbf_move_left_joystick(context, 0, 0, 500, 100); + + direction.change_direction(env.program_info(), env.console, context, 5.85); + pbf_move_left_joystick(context, 128, 0, 60, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 4); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // get sunflora 5 + // align to corner 5.1 + direction.change_direction(env.program_info(), env.console, context, 1.59); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 1.79); + pbf_move_left_joystick(context, 0, 0, 500, 100); + direction.change_direction(env.program_info(), env.console, context, 6.055); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 5.06); + pbf_move_left_joystick(context, 128, 0, 600, 100); + direction.change_direction(env.program_info(), env.console, context, 4.38); + pbf_move_left_joystick(context, 0, 0, 700, 100); + + direction.change_direction(env.program_info(), env.console, context, 2.53); + pbf_move_left_joystick(context, 128, 0, 160, 100); + direction.change_direction(env.program_info(), env.console, context, 0.78); + pbf_move_left_joystick(context, 128, 0, 90, 100); // todo: adjust this. 80 -> 90? + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 5); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 6 + // align to corner 6.1 + direction.change_direction(env.program_info(), env.console, context, 4.2); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 4.38); + pbf_move_left_joystick(context, 0, 0, 700, 100); + + direction.change_direction(env.program_info(), env.console, context, 0.96); + pbf_move_left_joystick(context, 128, 0, 300, 100); + direction.change_direction(env.program_info(), env.console, context, 5.17); + pbf_move_left_joystick(context, 128, 0, 100, 100); + direction.change_direction(env.program_info(), env.console, context, 3.86); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 6); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 7 + // align to corner 7.1 + direction.change_direction(env.program_info(), env.console, context, 2.06); + pbf_move_left_joystick(context, 128, 0, 80, 100); + direction.change_direction(env.program_info(), env.console, context, 4.7); + pbf_move_left_joystick(context, 128, 0, 100, 100); + direction.change_direction(env.program_info(), env.console, context, 5.01); + pbf_move_left_joystick(context, 128, 0, 1600, 100); + + // align to corner 7.2. bush + direction.change_direction(env.program_info(), env.console, context, 2.34); + pbf_move_left_joystick(context, 128, 0, 700, 100); + direction.change_direction(env.program_info(), env.console, context, 3.42); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + // align to corner 7.3. lamp-post + // todo: adjust routine to get to lampost. go behind the sculpture and goat? + direction.change_direction(env.program_info(), env.console, context, 0); + pbf_move_left_joystick(context, 128, 0, 120, 100); + direction.change_direction(env.program_info(), env.console, context, 1.75); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 2.95); + pbf_move_left_joystick(context, 128, 0, 300, 100); + direction.change_direction(env.program_info(), env.console, context, 2.22); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 1.01); + pbf_move_left_joystick(context, 128, 0, 300, 100); + + // align to corner 7.4. wall corner + direction.change_direction(env.program_info(), env.console, context, 3.70); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 4.28); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 3.54); + pbf_move_left_joystick(context, 128, 0, 600, 100); + + // align to corner 7.5. bush + direction.change_direction(env.program_info(), env.console, context, 3.11); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 60, 100); + direction.change_direction(env.program_info(), env.console, context, 4.28); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 3.60); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + direction.change_direction(env.program_info(), env.console, context, 1.17); + pbf_move_left_joystick(context, 128, 0, 130, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 7); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 8 + // align to corner 8.1. bush + direction.change_direction(env.program_info(), env.console, context, 4.54); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 3.60); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + direction.change_direction(env.program_info(), env.console, context, 1.64); + pbf_move_left_joystick(context, 128, 0, 350, 100); + direction.change_direction(env.program_info(), env.console, context, 4.36); + pbf_move_left_joystick(context, 128, 0, 100, 100); + + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 50, 50); + pbf_press_button(context, BUTTON_A, 50, 50); // extra press in case one is dropped + pbf_press_button(context, BUTTON_A, 50, 50); + pbf_wait(context, 250); + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + check_num_sunflora_found(env, context, 8); + pbf_wait(context, 3 * TICKS_PER_SECOND); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // // sunflora 9 + // // align to corner 9.1. bush + pbf_move_left_joystick(context, 128, 255, 200, 100); + direction.change_direction(env.program_info(), env.console, context, 4.89); + pbf_move_left_joystick(context, 128, 0, 350, 100); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 180); + get_off_ride(env.program_info(), env.console, context); + direction.change_direction(env.program_info(), env.console, context, 3.60); + pbf_move_left_joystick(context, 128, 0, 600, 100); + + + direction.change_direction(env.program_info(), env.console, context, 1.48); + pbf_move_left_joystick(context, 128, 0, 50, 100); + direction.change_direction(env.program_info(), env.console, context, 3.11); + pbf_move_left_joystick(context, 128, 0, 180, 100); + direction.change_direction(env.program_info(), env.console, context, 4.75); + pbf_move_left_joystick(context, 128, 0, 100, 100); + get_on_ride(env.program_info(), env.console, context); + direction.change_direction(env.program_info(), env.console, context, 5.53); + pbf_move_left_joystick(context, 128, 0, 600, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 9); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // sunflora 10 + // align to corner 10.1. bush + pbf_move_left_joystick(context, 0, 128, 200, 100); + + direction.change_direction(env.program_info(), env.console, context, 4.02); + pbf_move_left_joystick(context, 128, 0, 250, 100); + handle_failed_action(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 500); + check_num_sunflora_found(env, context, 10); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30, 100); + }, + 3 + ); + + // go back to Sunflora NPC + // align to corner 11.1. bush + direction.change_direction(env.program_info(), env.console, context, 0.65); + pbf_move_left_joystick(context, 128, 0, 200, 100); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 800, 100); + + direction.change_direction(env.program_info(), env.console, context, 4.49); + pbf_move_left_joystick(context, 128, 0, 100, 100); + direction.change_direction(env.program_info(), env.console, context, 5.53); + + NoMinimapWatcher no_minimap(env.console, COLOR_RED, Milliseconds(5000)); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 30 * TICKS_PER_SECOND, 100); + }, + {no_minimap} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to finish reach the Sunflora NPC.", + env.console + ); + } + env.log("No minimap seen. Likely finished the Artazon gym challenge."); + + clear_dialog(env.console, context, ClearDialogMode::STOP_OVERWORLD, 60, {CallbackEnum::OVERWORLD}); + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + +void checkpoint_45( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + get_on_ride(env.program_info(), env.console, context); + + DirectionDetector direction; + direction.change_direction(env.program_info(), env.console, context, 1.52); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 2.62); + pbf_move_left_joystick(context, 128, 0, 400, 100); + + direction.change_direction(env.program_info(), env.console, context, 2.18); + pbf_controller_state(context, BUTTON_B, DPAD_NONE, 128, 0, 128, 128, 150); + pbf_move_left_joystick(context, 128, 0, 400, 100); + direction.change_direction(env.program_info(), env.console, context, 3.16); + pbf_move_left_joystick(context, 0, 0, 100, 50); + + handle_when_stationary_in_overworld(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + walk_forward_until_dialog(env.program_info(), env.console, context, NavigationMovementMode::DIRECTIONAL_SPAM_A, 20); + }, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 0, 100, 50); + pbf_move_left_joystick(context, 255, 0, 100, 50); + }, + 5, 2, 2 + ); + + clear_dialog(env.console, context, ClearDialogMode::STOP_BATTLE, 60, {CallbackEnum::PROMPT_DIALOG, CallbackEnum::BATTLE, CallbackEnum::DIALOG_ARROW}); + run_battle_press_A(env.console, context, BattleStopCondition::STOP_DIALOG, {CallbackEnum::GRADIENT_ARROW}); + mash_button_till_overworld(env.console, context, BUTTON_A); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h index 9c43729401..a344db5dc6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_20.h @@ -1,57 +1,57 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_20_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_20_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_20 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options) const override; -}; - - -// start: Defeated Klawf. At Artazon (West) Pokecenter. -// end: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. -void checkpoint_43( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. -// end: Finished Sunflora gym challenge. -void checkpoint_44( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: Finished Sunflora gym challenge. -// end: Defeated Artazon Gym (Grass). Inside gym building. -void checkpoint_45( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_20_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_20_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_20 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options) const override; +}; + + +// start: Defeated Klawf. At Artazon (West) Pokecenter. +// end: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. +void checkpoint_43( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: At Artazon Gym building. Battled Nemona. Received Sunflora gym challenge. +// end: Finished Sunflora gym challenge. +void checkpoint_44( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: Finished Sunflora gym challenge. +// end: Defeated Artazon Gym (Grass). Inside gym building. +void checkpoint_45( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp index daa7d080bc..e9558918e5 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.cpp @@ -1,128 +1,128 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_21.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_21::name() const{ - return "17.1: Team Star (Fire): Go to East Province (Area One) Pokecenter"; -} - -std::string AutoStory_Segment_21::start_text() const{ - return "Start: Defeated Artazon Gym (Grass). Inside gym building."; -} - -std::string AutoStory_Segment_21::end_text() const{ - return "End: At East Province (Area One) Pokecenter."; -} - -void AutoStory_Segment_21::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment ", COLOR_ORANGE); - - checkpoint_46(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - -void checkpoint_46( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 255, 500, 100); - pbf_wait(context, 3 * TICKS_PER_SECOND); - // wait for overworld after leaving Gym - wait_for_overworld(env.program_info(), env.console, context, 30); - - // fly to Porto Marinada pokecenter - move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 255, 128, 50}); - - // section 1. set marker to pokecenter - realign_player_from_landmark( - env.program_info(), env.console, context, - {ZoomChange::KEEP_ZOOM, 255, 0, 50}, - {ZoomChange::ZOOM_IN, 0, 0, 0} - ); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 0, 80, 20, false); - - // section 2. set marker past pokecenter - handle_unexpected_battles(env.program_info(), env.console, context, - [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 180, 0, 30); - }); - overworld_navigation(env.program_info(), env.console, context, - NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, - 128, 15, 12, 12, false); - - fly_to_overlapping_flypoint(env.program_info(), env.console, context); - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_DirectionDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_21.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_21::name() const{ + return "17.1: Team Star (Fire): Go to East Province (Area One) Pokecenter"; +} + +std::string AutoStory_Segment_21::start_text() const{ + return "Start: Defeated Artazon Gym (Grass). Inside gym building."; +} + +std::string AutoStory_Segment_21::end_text() const{ + return "End: At East Province (Area One) Pokecenter."; +} + +void AutoStory_Segment_21::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + checkpoint_46(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + +void checkpoint_46( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 255, 500, 100); + pbf_wait(context, 3 * TICKS_PER_SECOND); + // wait for overworld after leaving Gym + wait_for_overworld(env.program_info(), env.console, context, 30); + + // fly to Porto Marinada pokecenter + move_cursor_towards_flypoint_and_go_there(env.program_info(), env.console, context, {ZoomChange::ZOOM_IN, 255, 128, 50}); + + // section 1. set marker to pokecenter + realign_player_from_landmark( + env.program_info(), env.console, context, + {ZoomChange::KEEP_ZOOM, 255, 0, 50}, + {ZoomChange::ZOOM_IN, 0, 0, 0} + ); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_MARKER, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 0, 80, 20, false); + + // section 2. set marker past pokecenter + handle_unexpected_battles(env.program_info(), env.console, context, + [&](const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + realign_player(env.program_info(), env.console, context, PlayerRealignMode::REALIGN_NEW_MARKER, 180, 0, 30); + }); + overworld_navigation(env.program_info(), env.console, context, + NavigationStopCondition::STOP_TIME, NavigationMovementMode::DIRECTIONAL_ONLY, + 128, 15, 12, 12, false); + + fly_to_overlapping_flypoint(env.program_info(), env.console, context); + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h index 43ad7672a4..131dde5af8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_21.h @@ -1,40 +1,40 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_21_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_21_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_21 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - -// start: Defeated Artazon Gym (Grass). Inside gym building. -// end: At East Province (Area One) Pokecenter. -void checkpoint_46( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_21_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_21_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_21 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + +// start: Defeated Artazon Gym (Grass). Inside gym building. +// end: At East Province (Area One) Pokecenter. +void checkpoint_46( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp index 693f1eb20e..a64fc2e327 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.cpp @@ -1,177 +1,177 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_22.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_22::name() const{ - return "17.1: Team Star (Fire): Beat Team Star"; -} - -std::string AutoStory_Segment_22::start_text() const{ - return "Start: At East Province (Area One) Pokecenter."; -} - -std::string AutoStory_Segment_22::end_text() const{ - return "End: "; -} - -void AutoStory_Segment_22::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment ", COLOR_ORANGE); - - // checkpoint_(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - -// todo: uncomment checkpoint_save -void checkpoint_47( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - // checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -// todo: uncomment checkpoint_save -void checkpoint_48( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - // checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - -// todo: uncomment checkpoint_save -void checkpoint_49( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -){ - AutoStoryStats& stats = env.current_stats(); - bool first_attempt = true; - while (true){ - try{ - if (first_attempt){ - // checkpoint_save(env, context, notif_status_update); - first_attempt = false; - }else{ - enter_menu_from_overworld(env.program_info(), env.console, context, -1); - // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. - env.log("Wait 10 seconds."); - context.wait_for(Milliseconds(10 * 1000)); - save_game_from_overworld(env.program_info(), env.console, context); - } - - context.wait_for_all_requests(); - - - - break; - }catch (...){ - context.wait_for_all_requests(); - env.console.log("Resetting from checkpoint."); - reset_game(env.program_info(), env.console, context); - stats.m_reset++; - env.update_stats(); - } - } - -} - - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_22.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_22::name() const{ + return "17.1: Team Star (Fire): Beat Team Star"; +} + +std::string AutoStory_Segment_22::start_text() const{ + return "Start: At East Province (Area One) Pokecenter."; +} + +std::string AutoStory_Segment_22::end_text() const{ + return "End: "; +} + +void AutoStory_Segment_22::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + // checkpoint_(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + +// todo: uncomment checkpoint_save +void checkpoint_47( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + // checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +// todo: uncomment checkpoint_save +void checkpoint_48( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + // checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + +// todo: uncomment checkpoint_save +void checkpoint_49( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +){ + AutoStoryStats& stats = env.current_stats(); + bool first_attempt = true; + while (true){ + try{ + if (first_attempt){ + // checkpoint_save(env, context, notif_status_update); + first_attempt = false; + }else{ + enter_menu_from_overworld(env.program_info(), env.console, context, -1); + // we wait 10 seconds then save, so that the initial conditions are slightly different on each reset. + env.log("Wait 10 seconds."); + context.wait_for(Milliseconds(10 * 1000)); + save_game_from_overworld(env.program_info(), env.console, context); + } + + context.wait_for_all_requests(); + + + + break; + }catch (...){ + context.wait_for_all_requests(); + env.console.log("Resetting from checkpoint."); + reset_game(env.program_info(), env.console, context); + stats.m_reset++; + env.update_stats(); + } + } + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h index fe55075349..3fe4b57e06 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_22.h @@ -1,59 +1,59 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_22_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_22_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_22 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - -// start: At East Province (Area One) Pokecenter. -// end: -void checkpoint_47( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: -// end: -void checkpoint_48( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - -// start: -// end: -void checkpoint_49( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EventNotificationOption& notif_status_update -); - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_22_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_22_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_22 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + +// start: At East Province (Area One) Pokecenter. +// end: +void checkpoint_47( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: +// end: +void checkpoint_48( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + +// start: +// end: +void checkpoint_49( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EventNotificationOption& notif_status_update +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp index 0850353eab..c82e13940f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.cpp @@ -1,61 +1,61 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_23.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_23::name() const{ - return ""; -} - -std::string AutoStory_Segment_23::start_text() const{ - return "Start: "; -} - -std::string AutoStory_Segment_23::end_text() const{ - return "End: "; -} - -void AutoStory_Segment_23::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment ", COLOR_ORANGE); - - // checkpoint_(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_23.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_23::name() const{ + return ""; +} + +std::string AutoStory_Segment_23::start_text() const{ + return "Start: "; +} + +std::string AutoStory_Segment_23::end_text() const{ + return "End: "; +} + +void AutoStory_Segment_23::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + // checkpoint_(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h index 4855f0afb3..b6226218c7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_23.h @@ -1,34 +1,34 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_23_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_23_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_23 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_23_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_23_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_23 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp index 93f7a96131..d121f367d1 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.cpp @@ -1,61 +1,61 @@ -/* AutoStory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV_AutoStoryTools.h" -#include "PokemonSV_AutoStory_Segment_24.h" - -//#include -//using std::cout; -//using std::endl; -//#include -//#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -std::string AutoStory_Segment_24::name() const{ - return ""; -} - -std::string AutoStory_Segment_24::start_text() const{ - return "Start: "; -} - -std::string AutoStory_Segment_24::end_text() const{ - return "End: "; -} - -void AutoStory_Segment_24::run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options -) const{ - AutoStoryStats& stats = env.current_stats(); - - context.wait_for_all_requests(); - env.console.log("Start Segment ", COLOR_ORANGE); - - // checkpoint_(env, context, options.notif_status_update); - - context.wait_for_all_requests(); - env.console.log("End Segment ", COLOR_GREEN); - stats.m_segment++; - env.update_stats(); - -} - - - -} -} -} +/* AutoStory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_AutoStoryTools.h" +#include "PokemonSV_AutoStory_Segment_24.h" + +//#include +//using std::cout; +//using std::endl; +//#include +//#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +std::string AutoStory_Segment_24::name() const{ + return ""; +} + +std::string AutoStory_Segment_24::start_text() const{ + return "Start: "; +} + +std::string AutoStory_Segment_24::end_text() const{ + return "End: "; +} + +void AutoStory_Segment_24::run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options +) const{ + AutoStoryStats& stats = env.current_stats(); + + context.wait_for_all_requests(); + env.console.log("Start Segment ", COLOR_ORANGE); + + // checkpoint_(env, context, options.notif_status_update); + + context.wait_for_all_requests(); + env.console.log("End Segment ", COLOR_GREEN); + stats.m_segment++; + env.update_stats(); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h index d3bca07ba5..e0c4305f92 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_AutoStory_Segment_24.h @@ -1,34 +1,34 @@ -/* Autostory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_24_H -#define PokemonAutomation_PokemonSV_AutoStory_Segment_24_H - -#include "PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class AutoStory_Segment_24 : public AutoStory_Segment{ -public: - virtual std::string name() const override; - virtual std::string start_text() const override; - virtual std::string end_text() const override; - virtual void run_segment( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - AutoStoryOptions options - ) const override; -}; - - - - -} -} -} -#endif +/* Autostory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoStory_Segment_24_H +#define PokemonAutomation_PokemonSV_AutoStory_Segment_24_H + +#include "PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class AutoStory_Segment_24 : public AutoStory_Segment{ +public: + virtual std::string name() const override; + virtual std::string start_text() const override; + virtual std::string end_text() const override; + virtual void run_segment( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + AutoStoryOptions options + ) const override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp index 10acb64e80..066e0a6bf5 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.cpp @@ -1,214 +1,214 @@ -/* Menu Option Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSV_MenuOption.h" -#include "PokemonSV/Inference/PokemonSV_MenuOptionReader.h" - -//#include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -MenuOption::~MenuOption() = default; - -MenuOption::MenuOption( - VideoStream& stream, - ProControllerContext& context, - Language language -) - : m_stream(stream) - , m_context(context) - , m_language(language) - , m_overlays(stream.overlay()) - , m_arrow(COLOR_CYAN, GradientArrowType::RIGHT, {0.02, 0.10, 0.05, 0.80}) -{ - // reader.make_overlays(m_overlays); - for (size_t c = 0; c < 10; c++){ - m_boxes_item[c] = ImageFloatBox(0.055, 0.135 + c * 0.0739, 0.260, 0.060); - m_boxes_toggle[c] = ImageFloatBox(0.345, 0.135 + c * 0.0739, 0.175, 0.060); - m_overlays.add(COLOR_BLUE, m_boxes_item[c]); - m_overlays.add(COLOR_BLUE, m_boxes_toggle[c]); - } -} - -void MenuOption::set_options( - const std::vector>>& options -) const{ - for (std::pair> option : options){ - move_to_option(option.first); - set_target_option(option.second); - } -} - -void MenuOption::set_target_option(const std::vector& target_option_toggle_list) const{ - - for (size_t attempt = 0; attempt < 10; attempt++){ - std::string current_option_slug = read_option_toggle(); - MenuOptionToggleEnum current_option_toggle_enum = menu_option_toggle_lookup_by_slug(current_option_slug).enum_value; - - if (std::find(target_option_toggle_list.begin(), target_option_toggle_list.end(), current_option_toggle_enum) != target_option_toggle_list.end()){ - return; - } - - pbf_press_dpad(m_context, DPAD_RIGHT, 10, 50); - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::set_target_option(): Unable to set option to the correct toggle.", - m_stream - ); - -} - -int8_t MenuOption::get_selected_index(const ImageViewRGB32& screen) const { - m_context.wait_for_all_requests(); - ImageFloatBox box; - if (!m_arrow.detect(box, screen)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::get_selected_index(): Unable to find cursor.", - m_stream - ); - } - -// cout << box.y << endl; - double slot = (box.y - 0.135185) / 0.0739; - int8_t selected_index = (int8_t)(slot + 0.5); - - if (selected_index < 0 || selected_index >= 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::get_selected_index(): Invalid cursor slot.", - m_stream - ); - } - // cout << "selected index:" + std::to_string(selected_index) << endl; - - return selected_index; -} - -std::string MenuOption::read_option(const ImageViewRGB32& cropped) const{ - // cropped.save("test.png"); - const auto ocr_result = MenuOptionReader::instance().read_substring( - m_stream.logger(), - m_language, - cropped, OCR::BLACK_TEXT_FILTERS() - ); - - std::multimap results; - if (!ocr_result.results.empty()){ - for (const auto& result : ocr_result.results){ - results.emplace(result.first, result.second); - } - } - - if (results.empty()){ - if (m_language == Language::German){ - // German Menu Option uses numbers for text speed settings, which string OCR has trouble with detecting. - int16_t number = read_number(m_stream.logger(), cropped); - switch (number){ - case 1: - return "slow"; - case 2: - return "normal"; - case 3: - return "fast"; - } - } - return ""; - } - - if (results.size() > 1){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results.", - m_stream - ); - } - - return results.begin()->second.token; -} - -int16_t MenuOption::read_number( - Logger& logger, - const ImageViewRGB32& cropped -) const{ - - int16_t number = (int16_t)OCR::read_number_waterfill(logger, cropped, 0xff000000, 0xff808080); - - if (number < 1 || number > 3){ - number = -1; - } - return (int16_t)number; -} - -std::string MenuOption::read_option_item() const{ - m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - - ImageFloatBox selected_box = m_boxes_item[get_selected_index(screen)]; - ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); - return read_option(cropped); - -} - -std::string MenuOption::read_option_toggle() const{ - m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - - ImageFloatBox selected_box = m_boxes_toggle[get_selected_index(screen)]; - ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); - - return read_option(cropped); -} - - -void MenuOption::move_to_option(const MenuOptionItemEnum target_option_enum) const{ - std::string current_option_slug = read_option_item(); - MenuOptionItem current_option = menu_option_item_lookup_by_slug(current_option_slug); - - const MenuOptionItem& target_option = menu_option_item_lookup_by_enum(target_option_enum); - std::string target_option_slug = target_option.slug; - int diff = target_option.index - current_option.index; - // cout << "target_option diff: " << std::to_string(target_option.index) << endl; - // cout << "current_option diff: " << std::to_string(current_option.index) << endl; - // cout << "diff: " << std::to_string(diff) << endl; - while (diff != 0){ - // move cursor in direction of target_option - if (diff > 0){ - for (size_t i = 0; i < (size_t)diff; i++){ - pbf_press_dpad(m_context, DPAD_DOWN, 10, 50); - } - } - if (diff < 0){ - for (size_t i = 0; i < (size_t)-diff; i++){ - pbf_press_dpad(m_context, DPAD_UP, 10, 50); - } - } - current_option_slug = read_option_item(); - current_option = menu_option_item_lookup_by_slug(current_option_slug); - diff = target_option.index - current_option.index; - // cout << "diff: " << std::to_string(diff) << endl; - } -} - - - - - - -} -} -} +/* Menu Option Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSV_MenuOption.h" +#include "PokemonSV/Inference/PokemonSV_MenuOptionReader.h" + +//#include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +MenuOption::~MenuOption() = default; + +MenuOption::MenuOption( + VideoStream& stream, + ProControllerContext& context, + Language language +) + : m_stream(stream) + , m_context(context) + , m_language(language) + , m_overlays(stream.overlay()) + , m_arrow(COLOR_CYAN, GradientArrowType::RIGHT, {0.02, 0.10, 0.05, 0.80}) +{ + // reader.make_overlays(m_overlays); + for (size_t c = 0; c < 10; c++){ + m_boxes_item[c] = ImageFloatBox(0.055, 0.135 + c * 0.0739, 0.260, 0.060); + m_boxes_toggle[c] = ImageFloatBox(0.345, 0.135 + c * 0.0739, 0.175, 0.060); + m_overlays.add(COLOR_BLUE, m_boxes_item[c]); + m_overlays.add(COLOR_BLUE, m_boxes_toggle[c]); + } +} + +void MenuOption::set_options( + const std::vector>>& options +) const{ + for (std::pair> option : options){ + move_to_option(option.first); + set_target_option(option.second); + } +} + +void MenuOption::set_target_option(const std::vector& target_option_toggle_list) const{ + + for (size_t attempt = 0; attempt < 10; attempt++){ + std::string current_option_slug = read_option_toggle(); + MenuOptionToggleEnum current_option_toggle_enum = menu_option_toggle_lookup_by_slug(current_option_slug).enum_value; + + if (std::find(target_option_toggle_list.begin(), target_option_toggle_list.end(), current_option_toggle_enum) != target_option_toggle_list.end()){ + return; + } + + pbf_press_dpad(m_context, DPAD_RIGHT, 10, 50); + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::set_target_option(): Unable to set option to the correct toggle.", + m_stream + ); + +} + +int8_t MenuOption::get_selected_index(const ImageViewRGB32& screen) const { + m_context.wait_for_all_requests(); + ImageFloatBox box; + if (!m_arrow.detect(box, screen)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::get_selected_index(): Unable to find cursor.", + m_stream + ); + } + +// cout << box.y << endl; + double slot = (box.y - 0.135185) / 0.0739; + int8_t selected_index = (int8_t)(slot + 0.5); + + if (selected_index < 0 || selected_index >= 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::get_selected_index(): Invalid cursor slot.", + m_stream + ); + } + // cout << "selected index:" + std::to_string(selected_index) << endl; + + return selected_index; +} + +std::string MenuOption::read_option(const ImageViewRGB32& cropped) const{ + // cropped.save("test.png"); + const auto ocr_result = MenuOptionReader::instance().read_substring( + m_stream.logger(), + m_language, + cropped, OCR::BLACK_TEXT_FILTERS() + ); + + std::multimap results; + if (!ocr_result.results.empty()){ + for (const auto& result : ocr_result.results){ + results.emplace(result.first, result.second); + } + } + + if (results.empty()){ + if (m_language == Language::German){ + // German Menu Option uses numbers for text speed settings, which string OCR has trouble with detecting. + int16_t number = read_number(m_stream.logger(), cropped); + switch (number){ + case 1: + return "slow"; + case 2: + return "normal"; + case 3: + return "fast"; + } + } + return ""; + } + + if (results.size() > 1){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "MenuOption::read_option(): Unable to read item. Ambiguous or multiple results.", + m_stream + ); + } + + return results.begin()->second.token; +} + +int16_t MenuOption::read_number( + Logger& logger, + const ImageViewRGB32& cropped +) const{ + + int16_t number = (int16_t)OCR::read_number_waterfill(logger, cropped, 0xff000000, 0xff808080); + + if (number < 1 || number > 3){ + number = -1; + } + return (int16_t)number; +} + +std::string MenuOption::read_option_item() const{ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + + ImageFloatBox selected_box = m_boxes_item[get_selected_index(screen)]; + ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); + return read_option(cropped); + +} + +std::string MenuOption::read_option_toggle() const{ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + + ImageFloatBox selected_box = m_boxes_toggle[get_selected_index(screen)]; + ImageViewRGB32 cropped = extract_box_reference(screen, selected_box); + + return read_option(cropped); +} + + +void MenuOption::move_to_option(const MenuOptionItemEnum target_option_enum) const{ + std::string current_option_slug = read_option_item(); + MenuOptionItem current_option = menu_option_item_lookup_by_slug(current_option_slug); + + const MenuOptionItem& target_option = menu_option_item_lookup_by_enum(target_option_enum); + std::string target_option_slug = target_option.slug; + int diff = target_option.index - current_option.index; + // cout << "target_option diff: " << std::to_string(target_option.index) << endl; + // cout << "current_option diff: " << std::to_string(current_option.index) << endl; + // cout << "diff: " << std::to_string(diff) << endl; + while (diff != 0){ + // move cursor in direction of target_option + if (diff > 0){ + for (size_t i = 0; i < (size_t)diff; i++){ + pbf_press_dpad(m_context, DPAD_DOWN, 10, 50); + } + } + if (diff < 0){ + for (size_t i = 0; i < (size_t)-diff; i++){ + pbf_press_dpad(m_context, DPAD_UP, 10, 50); + } + } + current_option_slug = read_option_item(); + current_option = menu_option_item_lookup_by_slug(current_option_slug); + diff = target_option.index - current_option.index; + // cout << "diff: " << std::to_string(diff) << endl; + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h index fd53066cd1..3919bc71c3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOption.h @@ -1,82 +1,82 @@ -/* Menu Option Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MenuOption_H -#define PokemonAutomation_PokemonSV_MenuOption_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV_MenuOptionDatabase.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class MenuOption{ -public: - ~MenuOption(); - MenuOption( - VideoStream& stream, ProControllerContext& context, - Language language - ); - - // change all settings as per options - void set_options( - const std::vector>>& options) const; - -private: - - // set the current selected option, to one of the option_toggle in the given list. - // We need a list of option_toggle since the mapping for the options in each language is slightly different. - // - e.g. For "Send to Boxes", the options may be Manual/Automatic in English, but may be On/Off in other languages. - // the program keeps cycling the options, until it matches one of the option_toggles in the list. - void set_target_option( - const std::vector& target_option_toggle_list - ) const; - - // Move to the target_option. - // Returns empty string if not found. - void move_to_option(const MenuOptionItemEnum target_option) const; - - std::string read_option(const ImageViewRGB32& cropped) const; - - int16_t read_number(Logger& logger, const ImageViewRGB32& cropped) const; - - // return the slug for the selected menu option item - std::string read_option_item() const; - - // return the slug for the selected menu option toggle - std::string read_option_toggle() const; - - // return the index row of the currently selected item. - // this detects the gradient arrow. - int8_t get_selected_index(const ImageViewRGB32& screen) const; - - -private: - VideoStream& m_stream; - ProControllerContext& m_context; - Language m_language; - VideoOverlaySet m_overlays; - GradientArrowDetector m_arrow; - std::array m_boxes_item; - std::array m_boxes_toggle; -}; - - - - -} -} -} -#endif +/* Menu Option Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MenuOption_H +#define PokemonAutomation_PokemonSV_MenuOption_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV_MenuOptionDatabase.h" + +namespace PokemonAutomation{ + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class MenuOption{ +public: + ~MenuOption(); + MenuOption( + VideoStream& stream, ProControllerContext& context, + Language language + ); + + // change all settings as per options + void set_options( + const std::vector>>& options) const; + +private: + + // set the current selected option, to one of the option_toggle in the given list. + // We need a list of option_toggle since the mapping for the options in each language is slightly different. + // - e.g. For "Send to Boxes", the options may be Manual/Automatic in English, but may be On/Off in other languages. + // the program keeps cycling the options, until it matches one of the option_toggles in the list. + void set_target_option( + const std::vector& target_option_toggle_list + ) const; + + // Move to the target_option. + // Returns empty string if not found. + void move_to_option(const MenuOptionItemEnum target_option) const; + + std::string read_option(const ImageViewRGB32& cropped) const; + + int16_t read_number(Logger& logger, const ImageViewRGB32& cropped) const; + + // return the slug for the selected menu option item + std::string read_option_item() const; + + // return the slug for the selected menu option toggle + std::string read_option_toggle() const; + + // return the index row of the currently selected item. + // this detects the gradient arrow. + int8_t get_selected_index(const ImageViewRGB32& screen) const; + + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + Language m_language; + VideoOverlaySet m_overlays; + GradientArrowDetector m_arrow; + std::array m_boxes_item; + std::array m_boxes_toggle; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp index 5a9d31f8e6..3ad10e57a2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.cpp @@ -1,148 +1,148 @@ -/* Menu Option Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonSV_MenuOptionDatabase.h" -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -static const std::vector& MenuOption_AllItems(){ - static const std::vector database{ - {MenuOptionItemEnum::TEXT_SPEED, "text-speed", 0}, - {MenuOptionItemEnum::SKIP_MOVE_LEARNING, "skip-move-learning", 1}, - {MenuOptionItemEnum::SEND_TO_BOXES, "send-to-boxes", 2}, - {MenuOptionItemEnum::GIVE_NICKNAMES, "give-nicknames", 3}, - {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, "vertical-camera-controls", 4}, - {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, "horizontal-camera-controls", 5}, - {MenuOptionItemEnum::CAMERA_SUPPORT, "camera-support", 6}, - {MenuOptionItemEnum::CAMERA_INTERPOLATION, "camera-interpolation", 7}, - {MenuOptionItemEnum::CAMERA_DISTANCE, "camera-distance", 8}, - {MenuOptionItemEnum::AUTOSAVE, "autosave", 9}, - {MenuOptionItemEnum::SHOW_NICKNAMES, "show-nicknames", 10}, - {MenuOptionItemEnum::SKIP_CUTSCENES, "skip-cutscenes", 11}, - {MenuOptionItemEnum::BACKGROUN_MUSIC, "background-music", 12}, - {MenuOptionItemEnum::SOUND_EFFECTS, "sound-effects", 13}, - {MenuOptionItemEnum::POKEMON_CRIES, "pokemon-cries", 14}, - {MenuOptionItemEnum::CONTROLLER_RUMBLE, "controller-rumble", 15}, - {MenuOptionItemEnum::HELPING_FUNCTIONS, "helping-functions", 16}, - {MenuOptionItemEnum::CONTROLS_WHILE_FLYING, "controls-while-flying", 17}, - }; - - return database; - -} - -static const std::vector& MenuOption_AllToggles(){ - static const std::vector database{ - {MenuOptionToggleEnum::SLOW, "slow"}, - {MenuOptionToggleEnum::AVERAGE, "average"}, - {MenuOptionToggleEnum::NORMAL, "normal"}, - {MenuOptionToggleEnum::FAST, "fast"}, - {MenuOptionToggleEnum::ON, "on"}, - {MenuOptionToggleEnum::OFF, "off"}, - {MenuOptionToggleEnum::MANUAL, "manual"}, - {MenuOptionToggleEnum::AUTOMATIC, "automatic"}, - {MenuOptionToggleEnum::REGULAR, "regular"}, - {MenuOptionToggleEnum::INVERTED, "inverted"}, - {MenuOptionToggleEnum::CLOSE, "close"}, - {MenuOptionToggleEnum::FAR, "far"}, - {MenuOptionToggleEnum::DONT_SHOW, "dont-show"}, - {MenuOptionToggleEnum::SHOW, "show"}, - }; - - return database; - -} - -static std::map make_MenuOptionItem_lookup_by_enum(){ - std::map ret; - for (const MenuOptionItem& item : MenuOption_AllItems()){ - if (!ret.emplace(item.enum_value, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); - } - } - return ret; -} -const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value){ - static const std::map database = make_MenuOptionItem_lookup_by_enum(); - auto iter = database.find(enum_value); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); - } -} -static std::map make_MenuOptionItem_lookup_by_slug(){ - std::map ret; - for (const MenuOptionItem& item : MenuOption_AllItems()){ - if (!ret.emplace(item.slug, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); - } - } - return ret; -} -const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug){ - static const std::map database = make_MenuOptionItem_lookup_by_slug(); - auto iter = database.find(slug); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); - } -} - -static std::map make_MenuOptionToggle_lookup_by_enum(){ - std::map ret; - for (const MenuOptionToggle& item : MenuOption_AllToggles()){ - if (!ret.emplace(item.enum_value, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); - } - } - return ret; -} -const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value){ - static const std::map database = make_MenuOptionToggle_lookup_by_enum(); - auto iter = database.find(enum_value); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); - } -} - -static std::map make_MenuOptionToggle_lookup_by_slug(){ - std::map ret; - for (const MenuOptionToggle& item : MenuOption_AllToggles()){ - if (!ret.emplace(item.slug, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); - } - } - return ret; -} -const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug){ - static const std::map database = make_MenuOptionToggle_lookup_by_slug(); - auto iter = database.find(slug); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); - } -} - - - - -} -} -} +/* Menu Option Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonSV_MenuOptionDatabase.h" +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +static const std::vector& MenuOption_AllItems(){ + static const std::vector database{ + {MenuOptionItemEnum::TEXT_SPEED, "text-speed", 0}, + {MenuOptionItemEnum::SKIP_MOVE_LEARNING, "skip-move-learning", 1}, + {MenuOptionItemEnum::SEND_TO_BOXES, "send-to-boxes", 2}, + {MenuOptionItemEnum::GIVE_NICKNAMES, "give-nicknames", 3}, + {MenuOptionItemEnum::VERTICAL_CAMERA_CONTROLS, "vertical-camera-controls", 4}, + {MenuOptionItemEnum::HORIZONTAL_CAMERA_CONTROLS, "horizontal-camera-controls", 5}, + {MenuOptionItemEnum::CAMERA_SUPPORT, "camera-support", 6}, + {MenuOptionItemEnum::CAMERA_INTERPOLATION, "camera-interpolation", 7}, + {MenuOptionItemEnum::CAMERA_DISTANCE, "camera-distance", 8}, + {MenuOptionItemEnum::AUTOSAVE, "autosave", 9}, + {MenuOptionItemEnum::SHOW_NICKNAMES, "show-nicknames", 10}, + {MenuOptionItemEnum::SKIP_CUTSCENES, "skip-cutscenes", 11}, + {MenuOptionItemEnum::BACKGROUN_MUSIC, "background-music", 12}, + {MenuOptionItemEnum::SOUND_EFFECTS, "sound-effects", 13}, + {MenuOptionItemEnum::POKEMON_CRIES, "pokemon-cries", 14}, + {MenuOptionItemEnum::CONTROLLER_RUMBLE, "controller-rumble", 15}, + {MenuOptionItemEnum::HELPING_FUNCTIONS, "helping-functions", 16}, + {MenuOptionItemEnum::CONTROLS_WHILE_FLYING, "controls-while-flying", 17}, + }; + + return database; + +} + +static const std::vector& MenuOption_AllToggles(){ + static const std::vector database{ + {MenuOptionToggleEnum::SLOW, "slow"}, + {MenuOptionToggleEnum::AVERAGE, "average"}, + {MenuOptionToggleEnum::NORMAL, "normal"}, + {MenuOptionToggleEnum::FAST, "fast"}, + {MenuOptionToggleEnum::ON, "on"}, + {MenuOptionToggleEnum::OFF, "off"}, + {MenuOptionToggleEnum::MANUAL, "manual"}, + {MenuOptionToggleEnum::AUTOMATIC, "automatic"}, + {MenuOptionToggleEnum::REGULAR, "regular"}, + {MenuOptionToggleEnum::INVERTED, "inverted"}, + {MenuOptionToggleEnum::CLOSE, "close"}, + {MenuOptionToggleEnum::FAR, "far"}, + {MenuOptionToggleEnum::DONT_SHOW, "dont-show"}, + {MenuOptionToggleEnum::SHOW, "show"}, + }; + + return database; + +} + +static std::map make_MenuOptionItem_lookup_by_enum(){ + std::map ret; + for (const MenuOptionItem& item : MenuOption_AllItems()){ + if (!ret.emplace(item.enum_value, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); + } + } + return ret; +} +const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value){ + static const std::map database = make_MenuOptionItem_lookup_by_enum(); + auto iter = database.find(enum_value); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); + } +} +static std::map make_MenuOptionItem_lookup_by_slug(){ + std::map ret; + for (const MenuOptionItem& item : MenuOption_AllItems()){ + if (!ret.emplace(item.slug, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); + } + } + return ret; +} +const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug){ + static const std::map database = make_MenuOptionItem_lookup_by_slug(); + auto iter = database.find(slug); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); + } +} + +static std::map make_MenuOptionToggle_lookup_by_enum(){ + std::map ret; + for (const MenuOptionToggle& item : MenuOption_AllToggles()){ + if (!ret.emplace(item.enum_value, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); + } + } + return ret; +} +const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value){ + static const std::map database = make_MenuOptionToggle_lookup_by_enum(); + auto iter = database.find(enum_value); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); + } +} + +static std::map make_MenuOptionToggle_lookup_by_slug(){ + std::map ret; + for (const MenuOptionToggle& item : MenuOption_AllToggles()){ + if (!ret.emplace(item.slug, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + item.slug); + } + } + return ret; +} +const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug){ + static const std::map database = make_MenuOptionToggle_lookup_by_slug(); + auto iter = database.find(slug); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + slug); + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h index cded770045..860fa89c56 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_MenuOptionDatabase.h @@ -1,80 +1,80 @@ -/* Menu Option Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MenuOptionDatabase_H -#define PokemonAutomation_PokemonSV_MenuOptionDatabase_H - -#include - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class MenuOptionItemEnum{ - TEXT_SPEED, - SKIP_MOVE_LEARNING, - SEND_TO_BOXES, - GIVE_NICKNAMES, - VERTICAL_CAMERA_CONTROLS, - HORIZONTAL_CAMERA_CONTROLS, - CAMERA_SUPPORT, - CAMERA_INTERPOLATION, - CAMERA_DISTANCE, - AUTOSAVE, - SHOW_NICKNAMES, - SKIP_CUTSCENES, - BACKGROUN_MUSIC, - SOUND_EFFECTS, - POKEMON_CRIES, - CONTROLLER_RUMBLE, - HELPING_FUNCTIONS, - CONTROLS_WHILE_FLYING, -}; - -enum class MenuOptionToggleEnum{ - SLOW, - AVERAGE, - NORMAL, - FAST, - ON, - OFF, - MANUAL, - AUTOMATIC, - REGULAR, - INVERTED, - CLOSE, - FAR, - DONT_SHOW, - SHOW, - -}; - -struct MenuOptionItem{ - MenuOptionItemEnum enum_value; - std::string slug; - int8_t index; -}; - -struct MenuOptionToggle{ - MenuOptionToggleEnum enum_value; - std::string slug; - -}; - -const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value); - -const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug); - -const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value); - -const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug); - -} -} -} -#endif +/* Menu Option Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MenuOptionDatabase_H +#define PokemonAutomation_PokemonSV_MenuOptionDatabase_H + +#include + +namespace PokemonAutomation{ + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class MenuOptionItemEnum{ + TEXT_SPEED, + SKIP_MOVE_LEARNING, + SEND_TO_BOXES, + GIVE_NICKNAMES, + VERTICAL_CAMERA_CONTROLS, + HORIZONTAL_CAMERA_CONTROLS, + CAMERA_SUPPORT, + CAMERA_INTERPOLATION, + CAMERA_DISTANCE, + AUTOSAVE, + SHOW_NICKNAMES, + SKIP_CUTSCENES, + BACKGROUN_MUSIC, + SOUND_EFFECTS, + POKEMON_CRIES, + CONTROLLER_RUMBLE, + HELPING_FUNCTIONS, + CONTROLS_WHILE_FLYING, +}; + +enum class MenuOptionToggleEnum{ + SLOW, + AVERAGE, + NORMAL, + FAST, + ON, + OFF, + MANUAL, + AUTOMATIC, + REGULAR, + INVERTED, + CLOSE, + FAR, + DONT_SHOW, + SHOW, + +}; + +struct MenuOptionItem{ + MenuOptionItemEnum enum_value; + std::string slug; + int8_t index; +}; + +struct MenuOptionToggle{ + MenuOptionToggleEnum enum_value; + std::string slug; + +}; + +const MenuOptionItem& menu_option_item_lookup_by_enum(MenuOptionItemEnum enum_value); + +const MenuOptionItem& menu_option_item_lookup_by_slug(std::string& slug); + +const MenuOptionToggle& menu_option_toggle_lookup_by_enum(MenuOptionToggleEnum enum_value); + +const MenuOptionToggle& menu_option_toggle_lookup_by_slug(std::string& slug); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h index 5ab0d6f4ce..5eddccb907 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h +++ b/SerialPrograms/Source/PokemonSV/Programs/AutoStory/PokemonSV_OliveActionFailedException.h @@ -1,53 +1,53 @@ -/* Operation Failed Exception - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_OliveActionFailedException_H -#define PokemonAutomation_OliveActionFailedException_H - -#include "CommonFramework/Exceptions/OperationFailedException.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class FatalProgramException; - -enum class OliveFail{ - NONE, - FAILED_ALIGN_TO_OLIVE, - FAILED_PUSH_OLIVE_TOTAL_DISTANCE, - NO_OLIVE_DETECTED, - FAILED_WALK_TO_OLIVE, - OLIVE_STUCK, -}; - -// Thrown by subroutines if they fail for an in-game reason. -// These include recoverable errors which can be consumed by the program. -class OliveActionFailedException : public OperationFailedException{ -public: - OliveActionFailedException( - ErrorReport error_report, - std::string message, - VideoStream& stream, - OliveFail fail_reason = OliveFail::NONE - ) - : OperationFailedException(error_report, std::move(message), stream) - , m_fail_reason(fail_reason) - {} - virtual const char* name() const override{ return "OliveActionFailedException"; } - -public: - OliveFail m_fail_reason; - -}; - - - - -} -} -} -#endif +/* Operation Failed Exception + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_OliveActionFailedException_H +#define PokemonAutomation_OliveActionFailedException_H + +#include "CommonFramework/Exceptions/OperationFailedException.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class FatalProgramException; + +enum class OliveFail{ + NONE, + FAILED_ALIGN_TO_OLIVE, + FAILED_PUSH_OLIVE_TOTAL_DISTANCE, + NO_OLIVE_DETECTED, + FAILED_WALK_TO_OLIVE, + OLIVE_STUCK, +}; + +// Thrown by subroutines if they fail for an in-game reason. +// These include recoverable errors which can be consumed by the program. +class OliveActionFailedException : public OperationFailedException{ +public: + OliveActionFailedException( + ErrorReport error_report, + std::string message, + VideoStream& stream, + OliveFail fail_reason = OliveFail::NONE + ) + : OperationFailedException(error_report, std::move(message), stream) + , m_fail_reason(fail_reason) + {} + virtual const char* name() const override{ return "OliveActionFailedException"; } + +public: + OliveFail m_fail_reason; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.cpp b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.cpp index 58cfd38a07..61b9a9d60d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.cpp @@ -1,323 +1,323 @@ -/* Basic Catcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV_BasicCatcher.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Most of this is copy-pasted from Sword/Shield. - - -// Returns the # of slots scrolled. Returns -1 if not found. -int move_to_ball( - const BattleBallReader& reader, - VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug, - bool forward, int attempts, uint16_t delay -){ - VideoSnapshot frame = stream.video().snapshot(); - std::string first_ball = reader.read_ball(frame); - if (first_ball == ball_slug){ - return 0; - } - - size_t repeat_counter = 0; - for (int c = 1; c < attempts; c++){ - pbf_press_dpad(context, forward ? DPAD_RIGHT : DPAD_LEFT, 10, delay); - context.wait_for_all_requests(); - frame = stream.video().snapshot(); - std::string current_ball = reader.read_ball(frame); - if (current_ball == ball_slug){ - return c; - } - if (current_ball == first_ball){ - repeat_counter++; - if (repeat_counter == 10){ - return -1; - } - } - } - return -1; -} - -// Returns the quantity of the ball. -// Returns -1 if unable to read. -int16_t move_to_ball( - const BattleBallReader& reader, VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug -){ - // Search forward at high speed. - int ret = move_to_ball(reader, stream, context, ball_slug, true, 100, 40); - if (ret < 0){ - return 0; - } - if (ret == 0){ - uint16_t quantity = reader.read_quantity(stream.video().snapshot()); - return quantity == 0 ? -1 : quantity; - } - - // Wait a second to let the video catch up. - pbf_wait(context, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Now try again in reverse at a lower speed in case we overshot. - // This will return immediately if we got it right the first time. - ret = move_to_ball(reader, stream, context, ball_slug, false, 5, TICKS_PER_SECOND); - if (ret < 0){ - return 0; - } - if (ret > 0){ - stream.log("Fast ball scrolling overshot by " + std::to_string(ret) + " slot(s).", COLOR_RED); - } - uint16_t quantity = reader.read_quantity(stream.video().snapshot()); - return quantity == 0 ? -1 : quantity; -} - - -// Throw a ball. If error or not found, throw an exception. -// Returns the quantity prior to throwing the ball. -int16_t throw_ball( - VideoStream& stream, ProControllerContext& context, - Language language, const std::string& ball_slug -){ - BattleBallReader reader(stream, language, COLOR_RED); - size_t attempts = 0; - while (true){ - context.wait_for_all_requests(); - - NormalBattleMenuWatcher normal_battle_menu(COLOR_GREEN); - MoveSelectWatcher move_select_menu(COLOR_BLUE); - TeraCatchWatcher tera_catch_detector(COLOR_GREEN); - int16_t quantity = 0; - int ret = run_until( - stream, context, [&](ProControllerContext& context){ - quantity = move_to_ball(reader, stream, context, ball_slug); - }, - {normal_battle_menu, move_select_menu, tera_catch_detector} - ); - switch (ret){ - case 0: - stream.log("Detected battle menu. Opening up ball selection..."); - pbf_press_button(context, BUTTON_X, 20, 30); - break; - case 1: - stream.log("Detected move select. Backing out..."); - pbf_mash_button(context, BUTTON_B, 125); - break; - case 2: - stream.log("Tera catch menu. Opening up ball selection..."); - tera_catch_detector.move_to_slot(stream, context, 0); - pbf_press_button(context, BUTTON_A, 20, 30); - break; - default: - if (quantity > 0){ - stream.log("Throwing ball...", COLOR_BLUE); - pbf_mash_button(context, BUTTON_A, 30); - return quantity; - } - if (quantity == 0){ - stream.log("Ball not found...", COLOR_RED); - // This is dead code for now. - return 0; - } - if (attempts >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find desired ball after multiple attempts. Did you run out?", - stream - ); - } - attempts++; - pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); - } - } -} - - - - - - - - - - -CatchResults basic_catcher( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit, - bool use_first_move_if_cant_throw, - std::function on_throw_lambda -){ - uint16_t balls_used = 0; - - bool caught = false; - bool overworld_seen = false; - bool last_move_attack = false; - int last_state = -1; - WallClock last_battle_menu = WallClock::min(); - while (true){ - NormalBattleMenuWatcher battle_menu(COLOR_RED); - OverworldWatcher overworld(stream.logger(), COLOR_YELLOW); - GradientArrowWatcher next_pokemon(COLOR_GREEN, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); - GradientArrowWatcher add_to_party(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.39, 0.30, 0.10}); - AdvanceDialogWatcher dialog(COLOR_PURPLE); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(120), - { - battle_menu, - overworld, - next_pokemon, - add_to_party, - dialog, - } - ); - switch (ret){ - case 0:{ - stream.log("Detected Battle Menu..."); - if (caught){ - stream.log("Detected battle menu after catch. Did you get chain attacked?", COLOR_RED); - return CatchResults{CatchResult::POKEMON_CAUGHT, balls_used}; - } - if (overworld_seen){ - stream.log("Detected battle after overworld. Did you get chain attacked?", COLOR_RED); - return CatchResults{CatchResult::POKEMON_FAINTED, balls_used}; - } - if (balls_used >= ball_limit){ - stream.log("Reached the limit of " + std::to_string(ball_limit) + " balls.", COLOR_RED); - return CatchResults{CatchResult::BALL_LIMIT_REACHED, balls_used}; - } - - WallClock now = current_time(); - WallClock previous = last_battle_menu; - last_battle_menu = now; -// cout << "last_state = " << last_state << endl; -// cout << "last_move_attack = " << last_move_attack << endl; -// cout << "last_move_attack = " << std::chrono::duration_cast(now - previous).count() << endl; - if (last_state == 0 && !last_move_attack && now < previous + std::chrono::seconds(8)){ - if (!use_first_move_if_cant_throw){ - stream.log("BasicCatcher: Unable to throw ball.", COLOR_RED); - return {CatchResult::CANNOT_THROW_BALL, balls_used}; - } - - stream.log("BasicCatcher: Unable to throw ball. Attempting to use first move instead...", COLOR_RED); - battle_menu.move_to_slot(stream, context, 0); - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); - last_move_attack = true; - break; - } - - last_move_attack = false; - pbf_press_button(context, BUTTON_X, 20, 105); -#if 0 - context.wait_for_all_requests(); - BattleBallReader reader(stream, language, COLOR_RED); - int16_t qty = move_to_ball(reader, stream, context, ball_slug); - if (qty <= 0){ - return CatchResults{CatchResult::OUT_OF_BALLS, balls_used}; - } - pbf_mash_button(context, BUTTON_A, 30); -#else - int16_t qty = throw_ball(stream, context, language, ball_slug); - if (qty <= 0){ - return CatchResults{CatchResult::OUT_OF_BALLS, balls_used}; - } -#endif - pbf_mash_button(context, BUTTON_B, 500); - balls_used++; - if (on_throw_lambda){ - on_throw_lambda(); - } - break; - } - case 1: - if (!overworld_seen && !caught){ - stream.log("Detected Overworld... Waiting 5 seconds to confirm."); - context.wait_for(std::chrono::seconds(5)); - overworld_seen = true; - break; - } - stream.log("Detected Overworld..."); - if (caught){ - return CatchResults{CatchResult::POKEMON_CAUGHT, balls_used}; - }else{ - return CatchResults{CatchResult::POKEMON_FAINTED, balls_used}; - } - case 2: - stream.log("Detected own " + STRING_POKEMON + " fainted..."); - return CatchResults{CatchResult::OWN_FAINTED, balls_used}; - case 3: - stream.log("Detected add to party..."); - caught = true; - pbf_press_button(context, BUTTON_B, 20, 230); - break; - case 4: - stream.log("Detected dialog..."); - caught = true; - pbf_press_button(context, BUTTON_B, 20, 230); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "basic_catcher(): No state detected after 2 minutes.", - stream - ); - } - - last_state = ret; - } - - - -} - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Basic Catcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV_BasicCatcher.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Most of this is copy-pasted from Sword/Shield. + + +// Returns the # of slots scrolled. Returns -1 if not found. +int move_to_ball( + const BattleBallReader& reader, + VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug, + bool forward, int attempts, uint16_t delay +){ + VideoSnapshot frame = stream.video().snapshot(); + std::string first_ball = reader.read_ball(frame); + if (first_ball == ball_slug){ + return 0; + } + + size_t repeat_counter = 0; + for (int c = 1; c < attempts; c++){ + pbf_press_dpad(context, forward ? DPAD_RIGHT : DPAD_LEFT, 10, delay); + context.wait_for_all_requests(); + frame = stream.video().snapshot(); + std::string current_ball = reader.read_ball(frame); + if (current_ball == ball_slug){ + return c; + } + if (current_ball == first_ball){ + repeat_counter++; + if (repeat_counter == 10){ + return -1; + } + } + } + return -1; +} + +// Returns the quantity of the ball. +// Returns -1 if unable to read. +int16_t move_to_ball( + const BattleBallReader& reader, VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug +){ + // Search forward at high speed. + int ret = move_to_ball(reader, stream, context, ball_slug, true, 100, 40); + if (ret < 0){ + return 0; + } + if (ret == 0){ + uint16_t quantity = reader.read_quantity(stream.video().snapshot()); + return quantity == 0 ? -1 : quantity; + } + + // Wait a second to let the video catch up. + pbf_wait(context, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Now try again in reverse at a lower speed in case we overshot. + // This will return immediately if we got it right the first time. + ret = move_to_ball(reader, stream, context, ball_slug, false, 5, TICKS_PER_SECOND); + if (ret < 0){ + return 0; + } + if (ret > 0){ + stream.log("Fast ball scrolling overshot by " + std::to_string(ret) + " slot(s).", COLOR_RED); + } + uint16_t quantity = reader.read_quantity(stream.video().snapshot()); + return quantity == 0 ? -1 : quantity; +} + + +// Throw a ball. If error or not found, throw an exception. +// Returns the quantity prior to throwing the ball. +int16_t throw_ball( + VideoStream& stream, ProControllerContext& context, + Language language, const std::string& ball_slug +){ + BattleBallReader reader(stream, language, COLOR_RED); + size_t attempts = 0; + while (true){ + context.wait_for_all_requests(); + + NormalBattleMenuWatcher normal_battle_menu(COLOR_GREEN); + MoveSelectWatcher move_select_menu(COLOR_BLUE); + TeraCatchWatcher tera_catch_detector(COLOR_GREEN); + int16_t quantity = 0; + int ret = run_until( + stream, context, [&](ProControllerContext& context){ + quantity = move_to_ball(reader, stream, context, ball_slug); + }, + {normal_battle_menu, move_select_menu, tera_catch_detector} + ); + switch (ret){ + case 0: + stream.log("Detected battle menu. Opening up ball selection..."); + pbf_press_button(context, BUTTON_X, 20, 30); + break; + case 1: + stream.log("Detected move select. Backing out..."); + pbf_mash_button(context, BUTTON_B, 125); + break; + case 2: + stream.log("Tera catch menu. Opening up ball selection..."); + tera_catch_detector.move_to_slot(stream, context, 0); + pbf_press_button(context, BUTTON_A, 20, 30); + break; + default: + if (quantity > 0){ + stream.log("Throwing ball...", COLOR_BLUE); + pbf_mash_button(context, BUTTON_A, 30); + return quantity; + } + if (quantity == 0){ + stream.log("Ball not found...", COLOR_RED); + // This is dead code for now. + return 0; + } + if (attempts >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find desired ball after multiple attempts. Did you run out?", + stream + ); + } + attempts++; + pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); + } + } +} + + + + + + + + + + +CatchResults basic_catcher( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit, + bool use_first_move_if_cant_throw, + std::function on_throw_lambda +){ + uint16_t balls_used = 0; + + bool caught = false; + bool overworld_seen = false; + bool last_move_attack = false; + int last_state = -1; + WallClock last_battle_menu = WallClock::min(); + while (true){ + NormalBattleMenuWatcher battle_menu(COLOR_RED); + OverworldWatcher overworld(stream.logger(), COLOR_YELLOW); + GradientArrowWatcher next_pokemon(COLOR_GREEN, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); + GradientArrowWatcher add_to_party(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.39, 0.30, 0.10}); + AdvanceDialogWatcher dialog(COLOR_PURPLE); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(120), + { + battle_menu, + overworld, + next_pokemon, + add_to_party, + dialog, + } + ); + switch (ret){ + case 0:{ + stream.log("Detected Battle Menu..."); + if (caught){ + stream.log("Detected battle menu after catch. Did you get chain attacked?", COLOR_RED); + return CatchResults{CatchResult::POKEMON_CAUGHT, balls_used}; + } + if (overworld_seen){ + stream.log("Detected battle after overworld. Did you get chain attacked?", COLOR_RED); + return CatchResults{CatchResult::POKEMON_FAINTED, balls_used}; + } + if (balls_used >= ball_limit){ + stream.log("Reached the limit of " + std::to_string(ball_limit) + " balls.", COLOR_RED); + return CatchResults{CatchResult::BALL_LIMIT_REACHED, balls_used}; + } + + WallClock now = current_time(); + WallClock previous = last_battle_menu; + last_battle_menu = now; +// cout << "last_state = " << last_state << endl; +// cout << "last_move_attack = " << last_move_attack << endl; +// cout << "last_move_attack = " << std::chrono::duration_cast(now - previous).count() << endl; + if (last_state == 0 && !last_move_attack && now < previous + std::chrono::seconds(8)){ + if (!use_first_move_if_cant_throw){ + stream.log("BasicCatcher: Unable to throw ball.", COLOR_RED); + return {CatchResult::CANNOT_THROW_BALL, balls_used}; + } + + stream.log("BasicCatcher: Unable to throw ball. Attempting to use first move instead...", COLOR_RED); + battle_menu.move_to_slot(stream, context, 0); + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); + last_move_attack = true; + break; + } + + last_move_attack = false; + pbf_press_button(context, BUTTON_X, 20, 105); +#if 0 + context.wait_for_all_requests(); + BattleBallReader reader(stream, language, COLOR_RED); + int16_t qty = move_to_ball(reader, stream, context, ball_slug); + if (qty <= 0){ + return CatchResults{CatchResult::OUT_OF_BALLS, balls_used}; + } + pbf_mash_button(context, BUTTON_A, 30); +#else + int16_t qty = throw_ball(stream, context, language, ball_slug); + if (qty <= 0){ + return CatchResults{CatchResult::OUT_OF_BALLS, balls_used}; + } +#endif + pbf_mash_button(context, BUTTON_B, 500); + balls_used++; + if (on_throw_lambda){ + on_throw_lambda(); + } + break; + } + case 1: + if (!overworld_seen && !caught){ + stream.log("Detected Overworld... Waiting 5 seconds to confirm."); + context.wait_for(std::chrono::seconds(5)); + overworld_seen = true; + break; + } + stream.log("Detected Overworld..."); + if (caught){ + return CatchResults{CatchResult::POKEMON_CAUGHT, balls_used}; + }else{ + return CatchResults{CatchResult::POKEMON_FAINTED, balls_used}; + } + case 2: + stream.log("Detected own " + STRING_POKEMON + " fainted..."); + return CatchResults{CatchResult::OWN_FAINTED, balls_used}; + case 3: + stream.log("Detected add to party..."); + caught = true; + pbf_press_button(context, BUTTON_B, 20, 230); + break; + case 4: + stream.log("Detected dialog..."); + caught = true; + pbf_press_button(context, BUTTON_B, 20, 230); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "basic_catcher(): No state detected after 2 minutes.", + stream + ); + } + + last_state = ret; + } + + + +} + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h index d778f8bee7..d18514fa79 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h @@ -1,59 +1,59 @@ -/* Basic Catcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BasicCatcher_H -#define PokemonAutomation_PokemonSV_BasicCatcher_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -// Returns the quantity of the ball. -// Returns -1 if unable to read. -int16_t move_to_ball( - const BattleBallReader& reader, - VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug -); - -// Throw a ball. If error, throw an exception. -// Returns the quantity prior to throwing the ball. -// If ball is not found, returns zero. -int16_t throw_ball( - VideoStream& stream, ProControllerContext& context, - Language language, const std::string& ball_slug -); - - - -struct CatchResults{ - CatchResult result; - uint16_t balls_used; -}; -CatchResults basic_catcher( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit, - bool use_first_move_if_cant_throw, - std::function on_throw_lambda = nullptr -); - - - - -} -} -} -#endif +/* Basic Catcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BasicCatcher_H +#define PokemonAutomation_PokemonSV_BasicCatcher_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +// Returns the quantity of the ball. +// Returns -1 if unable to read. +int16_t move_to_ball( + const BattleBallReader& reader, + VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug +); + +// Throw a ball. If error, throw an exception. +// Returns the quantity prior to throwing the ball. +// If ball is not found, returns zero. +int16_t throw_ball( + VideoStream& stream, ProControllerContext& context, + Language language, const std::string& ball_slug +); + + + +struct CatchResults{ + CatchResult result; + uint16_t balls_used; +}; +CatchResults basic_catcher( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit, + bool use_first_move_if_cant_throw, + std::function on_throw_lambda = nullptr +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp index e03e8b4584..1fe95ee07e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.cpp @@ -1,144 +1,144 @@ -/* Battles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV_Battles.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -void auto_heal_from_menu_or_overworld( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - uint8_t party_slot, - bool return_to_overworld -){ - stream.log("Auto-healing..."); - WallClock start = current_time(); - bool healed = false; - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "auto_heal_from_menu(): Failed auto-heal after 5 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - MainMenuWatcher main_menu(COLOR_CYAN); - AdvanceDialogWatcher dialog(COLOR_YELLOW); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(60), - {overworld, main_menu, dialog} - ); - switch (ret){ - case 0: - stream.log("Detected overworld."); - if (healed && return_to_overworld){ - return; - } - pbf_press_button(context, BUTTON_X, 20, 230); - continue; - case 1: - stream.log("Detected main menu."); - if (!healed){ - main_menu.move_cursor(info, stream, context, MenuSide::LEFT, party_slot, false); - pbf_press_button(context, BUTTON_MINUS, 20, 230); - healed = true; - continue; - } - if (!return_to_overworld){ - return; - } - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 2: - stream.log("Detected dialog."); - healed = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "auto_heal_from_menu(): No state detected after 60 seconds.", - stream - ); - } - } -} - - - - -int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Attempting to run away..."); - - int attempts = 0; - for (size_t c = 0; c < 10; c++){ - OverworldWatcher overworld(stream.logger(), COLOR_RED); - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - GradientArrowWatcher next_pokemon(COLOR_GREEN, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(60), - { - overworld, - battle_menu, - next_pokemon, - } - ); - - switch (ret){ - case 0: - stream.log("Detected overworld..."); - return attempts; - case 1: - stream.log("Detected battle menu..."); - battle_menu.move_to_slot(stream, context, 3); -// pbf_press_dpad(context, DPAD_DOWN, 250, 0); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); - attempts++; - continue; - case 2: - stream.log("Detected own " + STRING_POKEMON + " fainted..."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Your " + STRING_POKEMON + " fainted while attempting to run away.", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_from_battle(): No state detected after 60 seconds.", - stream - ); - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to run away after 10 attempts.", - stream - ); -} - - -} -} -} +/* Battles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV_Battles.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +void auto_heal_from_menu_or_overworld( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + uint8_t party_slot, + bool return_to_overworld +){ + stream.log("Auto-healing..."); + WallClock start = current_time(); + bool healed = false; + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "auto_heal_from_menu(): Failed auto-heal after 5 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + MainMenuWatcher main_menu(COLOR_CYAN); + AdvanceDialogWatcher dialog(COLOR_YELLOW); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(60), + {overworld, main_menu, dialog} + ); + switch (ret){ + case 0: + stream.log("Detected overworld."); + if (healed && return_to_overworld){ + return; + } + pbf_press_button(context, BUTTON_X, 20, 230); + continue; + case 1: + stream.log("Detected main menu."); + if (!healed){ + main_menu.move_cursor(info, stream, context, MenuSide::LEFT, party_slot, false); + pbf_press_button(context, BUTTON_MINUS, 20, 230); + healed = true; + continue; + } + if (!return_to_overworld){ + return; + } + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 2: + stream.log("Detected dialog."); + healed = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "auto_heal_from_menu(): No state detected after 60 seconds.", + stream + ); + } + } +} + + + + +int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Attempting to run away..."); + + int attempts = 0; + for (size_t c = 0; c < 10; c++){ + OverworldWatcher overworld(stream.logger(), COLOR_RED); + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + GradientArrowWatcher next_pokemon(COLOR_GREEN, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(60), + { + overworld, + battle_menu, + next_pokemon, + } + ); + + switch (ret){ + case 0: + stream.log("Detected overworld..."); + return attempts; + case 1: + stream.log("Detected battle menu..."); + battle_menu.move_to_slot(stream, context, 3); +// pbf_press_dpad(context, DPAD_DOWN, 250, 0); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 1 * TICKS_PER_SECOND); + attempts++; + continue; + case 2: + stream.log("Detected own " + STRING_POKEMON + " fainted..."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Your " + STRING_POKEMON + " fainted while attempting to run away.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_from_battle(): No state detected after 60 seconds.", + stream + ); + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to run away after 10 attempts.", + stream + ); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h index ea76487c43..59d99238e3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_Battles.h @@ -1,38 +1,38 @@ -/* Battles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_Battles_H -#define PokemonAutomation_PokemonSV_Battles_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -void auto_heal_from_menu_or_overworld( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - uint8_t party_slot, // 0 - 5 - bool return_to_overworld -); - - - -// Returns the # of attempts it took to run. -int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - - -} -} -} -#endif +/* Battles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_Battles_H +#define PokemonAutomation_PokemonSV_Battles_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +void auto_heal_from_menu_or_overworld( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + uint8_t party_slot, // 0 - 5 + bool return_to_overworld +); + + + +// Returns the # of attempts it took to run. +int run_from_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.cpp b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.cpp index 936a6a9c56..5e1e2d4ade 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.cpp @@ -1,330 +1,330 @@ -/* Singles Battler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV_SinglesBattler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -// Run a single move for a single turn. -// Returns true if move is successfully selected. -bool run_move_select( - VideoStream& stream, ProControllerContext& context, - MoveSelectWatcher& move_select_menu, - SinglesMoveEntry& move, size_t consecutive_move_select -){ - uint8_t index = 0; - switch (move.type){ - case SinglesMoveType::Move1: - index = 0; - break; - case SinglesMoveType::Move2: - index = 1; - break; - case SinglesMoveType::Move3: - index = 2; - break; - case SinglesMoveType::Move4: - index = 3; - break; - default: - pbf_press_button(context, BUTTON_B, 20, 10); - return false; - } - - // If we end up here consecutively too many times, the move is - // probably disabled. Select a different move. - if (consecutive_move_select > 3){ - stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); -// pbf_press_dpad(context, DPAD_DOWN, 20, 40); - index++; - if (index >= 4){ - index = 0; - } - move.type = (SinglesMoveType)((uint8_t)SinglesMoveType::Move1 + index); - } - - do{ - if (!move.terastallize){ - stream.log("Skipping Terastallization. Reason: Not requested."); - break; - } - if (consecutive_move_select > 1){ - stream.log("Skipping Terastallization. Reason: Previously failed move select."); - break; - } - - stream.log("Attempting to Terastallize..."); - pbf_press_button(context, BUTTON_R, 20, 1 * TICKS_PER_SECOND); - }while (false); - - context.wait_for_all_requests(); - - if (move_select_menu.move_to_slot(stream, context, index)){ - pbf_press_button(context, BUTTON_A, 20, 10); - } - return true; -} - - -bool run_battle_menu( - VideoStream& stream, ProControllerContext& context, - NormalBattleMenuWatcher& battle_menu, - const SinglesMoveEntry& move -){ - stream.log("Current Move Selection: " + move.to_str()); - switch (move.type){ - case SinglesMoveType::Move1: - case SinglesMoveType::Move2: - case SinglesMoveType::Move3: - case SinglesMoveType::Move4: - if (battle_menu.move_to_slot(stream, context, 0)){ - pbf_press_button(context, BUTTON_A, 20, 10); - return true; - }else{ - stream.log("Unable to move to battle slot.", COLOR_RED); - pbf_mash_button(context, BUTTON_B, 125); - return false; - } - case SinglesMoveType::Run: - if (battle_menu.move_to_slot(stream, context, 3)){ - pbf_press_button(context, BUTTON_A, 20, 10); - return true; - }else{ - stream.log("Unable to move to run option.", COLOR_RED); - pbf_mash_button(context, BUTTON_B, 125); - return false; - } - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid SinglesMoveType: " + std::to_string((int)move.type), - stream - ); -} - - -// Run a battle using the current Pokemon. Returns false if it fainted. -bool run_pokemon( - VideoStream& stream, ProControllerContext& context, - const std::vector& move_table, - bool trainer_battle, bool& terastallized -){ - stream.log("Starting singles battle routine for one " + STRING_POKEMON + "..."); - - size_t turn = 0; - SinglesMoveEntry current_move{SinglesMoveType::Move1, false}; - if (!move_table.empty()){ - current_move = move_table[0]; - } - - size_t consecutive_timeouts = 0; - size_t consecutive_move_select = 0; -// bool battle_menu_seen = false; - bool next_turn_on_battle_menu = false; - while (true){ - - NormalBattleMenuWatcher battle_menu(COLOR_RED); - MoveSelectWatcher move_select_menu(COLOR_YELLOW); - GradientArrowWatcher next_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); - SwapMenuWatcher swap_menu(COLOR_BLUE); - AdvanceDialogWatcher dialog(COLOR_CYAN); - OverworldWatcher overworld(stream.logger(), COLOR_GREEN); - context.wait_for_all_requests(); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 4; c++){ - pbf_wait(context, 30 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_B, 20, 0); - } - }, - { - battle_menu, - move_select_menu, - next_pokemon, - swap_menu, - dialog, - overworld, - } - ); - if (ret >= 0){ - consecutive_timeouts = 0; - } - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0:{ - stream.log("Detected battle menu."); - consecutive_move_select = 0; -// battle_menu_seen = true; - - // If we enter here, we advance to the next turn. - if (next_turn_on_battle_menu){ - stream.log("Detected battle menu. Turn: " + std::to_string(turn)); - turn++; - // Reset the move to the table entry in case we were forced to - // change moves due to move being unselectable. - if (move_table.empty()){ - current_move = SinglesMoveEntry{SinglesMoveType::Move1, false}; - }else if (turn < move_table.size()){ - current_move = move_table[turn]; - }else{ - current_move = move_table.back(); - } -// next_turn_on_battle_menu = false; - } - - if (terastallized){ - stream.log("Already used terastallization. Cannot use again.", COLOR_ORANGE); - current_move.terastallize = false; - } - next_turn_on_battle_menu = run_battle_menu(stream, context, battle_menu, current_move); - if (current_move.terastallize){ - terastallized = true; - } - continue; - } - case 1:{ - stream.log("Detected move select. Turn: " + std::to_string(turn)); - consecutive_move_select++; - run_move_select( - stream, context, - move_select_menu, - current_move, - consecutive_move_select - ); - continue; - } - case 2: - if (trainer_battle){ - stream.log("Detected switch prompt...", COLOR_BLUE); - pbf_press_button(context, BUTTON_B, 20, 10); - }else{ - stream.log("Detected own " + STRING_POKEMON + " fainted...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_A, 20, 10); - } - continue; - case 3: - stream.log("Detected switch " + STRING_POKEMON + " menu...", COLOR_ORANGE); - return false; - case 4: - stream.log("Detected advance dialog!", COLOR_ORANGE); - return true; - case 5: - stream.log("Detected overworld!", COLOR_ORANGE); - return true; - default: - consecutive_timeouts++; - if (consecutive_timeouts == 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 6 minutes.", - stream - ); - } - stream.log("Unable to detect any state for 2 minutes. Mashing B...", COLOR_RED); - pbf_mash_button(context, BUTTON_B, 250); - } - - - } - - - -} - - - - - - - -bool run_singles_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - SinglesAIOption& battle_AI, - bool trainer_battle -){ - stream.log("Starting singles battle routine..."); - - bool terastallized = false; - size_t faint_counter = 0; - while (true){ - bool win = run_pokemon( - stream, context, - battle_AI.MOVE_TABLES[std::min(faint_counter, 5)].snapshot(), - trainer_battle, terastallized - ); - - if (win){ - return true; - } - - // Find something to send out. - faint_counter++; - - NormalBattleMenuWatcher battle_menu(COLOR_RED); - AdvanceDialogWatcher dialog(COLOR_CYAN); - SwapMenuWatcher swap_menu(COLOR_BLUE); - while (true){ - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(120), - {battle_menu, dialog, swap_menu} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected battle menu. Calling battle routine..."); - break; - case 1: - stream.log("Detected advance dialog. Battle has been expectedly won already.", COLOR_RED); - return true; - case 2: - stream.log("Attempting to send in next " + STRING_POKEMON + "..."); - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_mash_button(context, BUTTON_B, 250); - pbf_wait(context, 50); - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to send in a " + STRING_POKEMON + ".", - stream - ); - } - break; - } - } -} - - - - - - - -} -} -} +/* Singles Battler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV_SinglesBattler.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +// Run a single move for a single turn. +// Returns true if move is successfully selected. +bool run_move_select( + VideoStream& stream, ProControllerContext& context, + MoveSelectWatcher& move_select_menu, + SinglesMoveEntry& move, size_t consecutive_move_select +){ + uint8_t index = 0; + switch (move.type){ + case SinglesMoveType::Move1: + index = 0; + break; + case SinglesMoveType::Move2: + index = 1; + break; + case SinglesMoveType::Move3: + index = 2; + break; + case SinglesMoveType::Move4: + index = 3; + break; + default: + pbf_press_button(context, BUTTON_B, 20, 10); + return false; + } + + // If we end up here consecutively too many times, the move is + // probably disabled. Select a different move. + if (consecutive_move_select > 3){ + stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); +// pbf_press_dpad(context, DPAD_DOWN, 20, 40); + index++; + if (index >= 4){ + index = 0; + } + move.type = (SinglesMoveType)((uint8_t)SinglesMoveType::Move1 + index); + } + + do{ + if (!move.terastallize){ + stream.log("Skipping Terastallization. Reason: Not requested."); + break; + } + if (consecutive_move_select > 1){ + stream.log("Skipping Terastallization. Reason: Previously failed move select."); + break; + } + + stream.log("Attempting to Terastallize..."); + pbf_press_button(context, BUTTON_R, 20, 1 * TICKS_PER_SECOND); + }while (false); + + context.wait_for_all_requests(); + + if (move_select_menu.move_to_slot(stream, context, index)){ + pbf_press_button(context, BUTTON_A, 20, 10); + } + return true; +} + + +bool run_battle_menu( + VideoStream& stream, ProControllerContext& context, + NormalBattleMenuWatcher& battle_menu, + const SinglesMoveEntry& move +){ + stream.log("Current Move Selection: " + move.to_str()); + switch (move.type){ + case SinglesMoveType::Move1: + case SinglesMoveType::Move2: + case SinglesMoveType::Move3: + case SinglesMoveType::Move4: + if (battle_menu.move_to_slot(stream, context, 0)){ + pbf_press_button(context, BUTTON_A, 20, 10); + return true; + }else{ + stream.log("Unable to move to battle slot.", COLOR_RED); + pbf_mash_button(context, BUTTON_B, 125); + return false; + } + case SinglesMoveType::Run: + if (battle_menu.move_to_slot(stream, context, 3)){ + pbf_press_button(context, BUTTON_A, 20, 10); + return true; + }else{ + stream.log("Unable to move to run option.", COLOR_RED); + pbf_mash_button(context, BUTTON_B, 125); + return false; + } + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid SinglesMoveType: " + std::to_string((int)move.type), + stream + ); +} + + +// Run a battle using the current Pokemon. Returns false if it fainted. +bool run_pokemon( + VideoStream& stream, ProControllerContext& context, + const std::vector& move_table, + bool trainer_battle, bool& terastallized +){ + stream.log("Starting singles battle routine for one " + STRING_POKEMON + "..."); + + size_t turn = 0; + SinglesMoveEntry current_move{SinglesMoveType::Move1, false}; + if (!move_table.empty()){ + current_move = move_table[0]; + } + + size_t consecutive_timeouts = 0; + size_t consecutive_move_select = 0; +// bool battle_menu_seen = false; + bool next_turn_on_battle_menu = false; + while (true){ + + NormalBattleMenuWatcher battle_menu(COLOR_RED); + MoveSelectWatcher move_select_menu(COLOR_YELLOW); + GradientArrowWatcher next_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.51, 0.30, 0.10}); + SwapMenuWatcher swap_menu(COLOR_BLUE); + AdvanceDialogWatcher dialog(COLOR_CYAN); + OverworldWatcher overworld(stream.logger(), COLOR_GREEN); + context.wait_for_all_requests(); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 4; c++){ + pbf_wait(context, 30 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_B, 20, 0); + } + }, + { + battle_menu, + move_select_menu, + next_pokemon, + swap_menu, + dialog, + overworld, + } + ); + if (ret >= 0){ + consecutive_timeouts = 0; + } + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0:{ + stream.log("Detected battle menu."); + consecutive_move_select = 0; +// battle_menu_seen = true; + + // If we enter here, we advance to the next turn. + if (next_turn_on_battle_menu){ + stream.log("Detected battle menu. Turn: " + std::to_string(turn)); + turn++; + // Reset the move to the table entry in case we were forced to + // change moves due to move being unselectable. + if (move_table.empty()){ + current_move = SinglesMoveEntry{SinglesMoveType::Move1, false}; + }else if (turn < move_table.size()){ + current_move = move_table[turn]; + }else{ + current_move = move_table.back(); + } +// next_turn_on_battle_menu = false; + } + + if (terastallized){ + stream.log("Already used terastallization. Cannot use again.", COLOR_ORANGE); + current_move.terastallize = false; + } + next_turn_on_battle_menu = run_battle_menu(stream, context, battle_menu, current_move); + if (current_move.terastallize){ + terastallized = true; + } + continue; + } + case 1:{ + stream.log("Detected move select. Turn: " + std::to_string(turn)); + consecutive_move_select++; + run_move_select( + stream, context, + move_select_menu, + current_move, + consecutive_move_select + ); + continue; + } + case 2: + if (trainer_battle){ + stream.log("Detected switch prompt...", COLOR_BLUE); + pbf_press_button(context, BUTTON_B, 20, 10); + }else{ + stream.log("Detected own " + STRING_POKEMON + " fainted...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_A, 20, 10); + } + continue; + case 3: + stream.log("Detected switch " + STRING_POKEMON + " menu...", COLOR_ORANGE); + return false; + case 4: + stream.log("Detected advance dialog!", COLOR_ORANGE); + return true; + case 5: + stream.log("Detected overworld!", COLOR_ORANGE); + return true; + default: + consecutive_timeouts++; + if (consecutive_timeouts == 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 6 minutes.", + stream + ); + } + stream.log("Unable to detect any state for 2 minutes. Mashing B...", COLOR_RED); + pbf_mash_button(context, BUTTON_B, 250); + } + + + } + + + +} + + + + + + + +bool run_singles_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + SinglesAIOption& battle_AI, + bool trainer_battle +){ + stream.log("Starting singles battle routine..."); + + bool terastallized = false; + size_t faint_counter = 0; + while (true){ + bool win = run_pokemon( + stream, context, + battle_AI.MOVE_TABLES[std::min(faint_counter, 5)].snapshot(), + trainer_battle, terastallized + ); + + if (win){ + return true; + } + + // Find something to send out. + faint_counter++; + + NormalBattleMenuWatcher battle_menu(COLOR_RED); + AdvanceDialogWatcher dialog(COLOR_CYAN); + SwapMenuWatcher swap_menu(COLOR_BLUE); + while (true){ + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(120), + {battle_menu, dialog, swap_menu} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected battle menu. Calling battle routine..."); + break; + case 1: + stream.log("Detected advance dialog. Battle has been expectedly won already.", COLOR_RED); + return true; + case 2: + stream.log("Attempting to send in next " + STRING_POKEMON + "..."); + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_mash_button(context, BUTTON_B, 250); + pbf_wait(context, 50); + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to send in a " + STRING_POKEMON + ".", + stream + ); + } + break; + } + } +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h index 96f68fa9db..b9b789ca9e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h @@ -1,46 +1,46 @@ -/* Singles Battler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SinglesBattler_H -#define PokemonAutomation_PokemonSV_SinglesBattler_H - -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Options/PokemonSV_SinglesMoveTable.h" -#include "PokemonSV/Options/PokemonSV_SinglesAIOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -//enum RunPokemonResult{ -// OWN_FAINTED, -// OVERWORLD, -//}; - -bool run_pokemon( - VideoStream& stream, ProControllerContext& context, - const std::vector& move_table, - bool trainer_battle, bool& terastallized -); - - -// Run a singles battle until it is over (for whatever reason). -bool run_singles_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - SinglesAIOption& battle_AI, - bool trainer_battle -); - - - -} -} -} -#endif +/* Singles Battler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SinglesBattler_H +#define PokemonAutomation_PokemonSV_SinglesBattler_H + +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Options/PokemonSV_SinglesMoveTable.h" +#include "PokemonSV/Options/PokemonSV_SinglesAIOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +//enum RunPokemonResult{ +// OWN_FAINTED, +// OVERWORLD, +//}; + +bool run_pokemon( + VideoStream& stream, ProControllerContext& context, + const std::vector& move_table, + bool trainer_battle, bool& terastallized +); + + +// Run a singles battle until it is over (for whatever reason). +bool run_singles_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + SinglesAIOption& battle_AI, + bool trainer_battle +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.cpp index 7efddeb99a..10919d83ad 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.cpp @@ -1,243 +1,243 @@ -/* Box Attach - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -//#include "Pokemon/Pokemon_Strings.h" -//#include "PokemonSV_BoxRoutines.h" -#include "PokemonSV/Inference/PokemonSV_BagDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV_BoxAttach.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -// With the cursor over the item you want to attach, attach to the current -// Pokemon, replacing if necessary. -void attach_item_from_bag( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t& errors -){ -// bool attach_attempted = false; - bool attach_completed = false; - - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(60)){ - dump_image_and_throw_recoverable_exception( - info, stream, "AttachFailed", - "Failed to attach item after 1 minute." - ); - } - - BagWatcher bag_detector(BagWatcher::FinderType::GONE, COLOR_GREEN); - GradientArrowWatcher bag_neutral(COLOR_RED, GradientArrowType::RIGHT, {0.10, 0.15, 0.05, 0.77}, std::chrono::milliseconds(1000)); - GradientArrowWatcher selected(COLOR_RED, GradientArrowType::RIGHT, {0.20, 0.20, 0.30, 0.60}); - PromptDialogWatcher prompt(COLOR_CYAN, std::chrono::milliseconds(100)); - AdvanceDialogWatcher advance_dialog(COLOR_YELLOW, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - { - bag_detector, - bag_neutral, - selected, - prompt, - advance_dialog, - } - ); - context.wait_for(std::chrono::milliseconds(50)); - if (ret == 4){ - // Make sure we're not mistakening this for the other dialogs. - auto screenshot = stream.video().snapshot(); - if (prompt.detect(screenshot)){ - ret = 3; - } - } - - - switch (ret){ - case 0: - stream.log("No longer in bag..."); - if (!attach_completed){ - errors++; - } - return; - case 1: - stream.log("Detected bag neutral..."); - if (attach_completed){ - pbf_press_button(context, BUTTON_B, 20, 30); - }else{ - pbf_press_button(context, BUTTON_A, 20, 30); - } - break; - case 2: - stream.log("Detected selection..."); - pbf_press_button(context, BUTTON_A, 20, 30); -// attach_completed = true; - break; - case 3: - stream.log("Detected prompt..."); - pbf_press_button(context, BUTTON_A, 20, 30); - break; - case 4: - stream.log("Detected dialog..."); - pbf_press_button(context, BUTTON_B, 20, 30); - attach_completed = true; - break; - } - } -} - - - -void attach_item_from_box( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t category_index, - size_t& errors -){ - bool attach_attempted = false; -// bool attach_completed = false; - int expected = 0; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(60)){ - dump_image_and_throw_recoverable_exception( - info, stream, "AttachFailed", - "Failed to attach item after 1 minute." - ); - } - - SomethingInBoxSlotDetector exists(COLOR_BLUE); - BoxWatcher box_detector(COLOR_RED); - PromptDialogWatcher selected_empty(COLOR_CYAN, {0.60, 0.57, 0.30, 0.09}, std::chrono::milliseconds(100)); - PromptDialogWatcher selected_held(COLOR_CYAN, {0.60, 0.46, 0.30, 0.09}, std::chrono::milliseconds(100)); - BagWatcher bag_detector(BagWatcher::FinderType::PRESENT, COLOR_GREEN); -// AdvanceDialogWatcher advance_dialog(COLOR_YELLOW, std::chrono::milliseconds(250)); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - { - box_detector, - selected_empty, - selected_held, - bag_detector, -// advance_dialog, - } - ); - context.wait_for(std::chrono::milliseconds(50)); -#if 0 - if (ret == 4){ - // Make sure we're not mistakening this for the other dialogs. - auto screenshot = stream.video().snapshot(); - if (selected_empty.detect(screenshot)){ - ret = 1; - }else if (selected_held.detect(screenshot)){ - ret = 2; - } - } -#endif - - switch (ret){ - case 0:{ - if (ret == expected){ - stream.log("Detected box neutral."); - }else{ - stream.log("Detected box neutral. (unexpected)", COLOR_RED); - errors++; - } - - auto screenshot = stream.video().snapshot(); - if (exists.detect(screenshot)){ - if (attach_attempted){ - return; - } - attach_attempted = false; - pbf_press_button(context, BUTTON_A, 20, 20); - expected = 1; - continue; - }else{ - stream.log("Slot is empty."); - return; - } - } - case 1: - if (ret == expected){ - stream.log("Detected empty selection. Attaching..."); - }else{ - stream.log("Detected empty selection. Attaching... (unexpected)", COLOR_RED); - errors++; - } - - pbf_press_button(context, BUTTON_A, 20, 30); - - expected = 3; - continue; - - case 2: - if (1 == expected){ - stream.log("Detected held selection. Replacing..."); - }else{ - stream.log("Detected held selection. Replacing... (unexpected)", COLOR_RED); - errors++; - } - - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - pbf_press_button(context, BUTTON_A, 20, 30); - - expected = 3; - continue; - - case 3: - if (ret == expected){ - stream.log("Detected bag."); - }else{ - stream.log("Detected bag.(unexpected)", COLOR_RED); - errors++; - } - - context.wait_for(std::chrono::milliseconds(200)); - if (attach_attempted){ - pbf_press_button(context, BUTTON_B, 20, 30); - expected = 0; - continue; - } - - for (size_t c = 0; c < category_index; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - } - - attach_item_from_bag(info, stream, context, errors); - attach_attempted = true; - - expected = 0; - continue; - - default: - dump_image_and_throw_recoverable_exception( - info, stream, "NoStateAttachingItem", "No recognized state while attaching item after 10 seconds." - ); - } - } -} - - - - -} -} -} +/* Box Attach + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +//#include "Pokemon/Pokemon_Strings.h" +//#include "PokemonSV_BoxRoutines.h" +#include "PokemonSV/Inference/PokemonSV_BagDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV_BoxAttach.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +// With the cursor over the item you want to attach, attach to the current +// Pokemon, replacing if necessary. +void attach_item_from_bag( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t& errors +){ +// bool attach_attempted = false; + bool attach_completed = false; + + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(60)){ + dump_image_and_throw_recoverable_exception( + info, stream, "AttachFailed", + "Failed to attach item after 1 minute." + ); + } + + BagWatcher bag_detector(BagWatcher::FinderType::GONE, COLOR_GREEN); + GradientArrowWatcher bag_neutral(COLOR_RED, GradientArrowType::RIGHT, {0.10, 0.15, 0.05, 0.77}, std::chrono::milliseconds(1000)); + GradientArrowWatcher selected(COLOR_RED, GradientArrowType::RIGHT, {0.20, 0.20, 0.30, 0.60}); + PromptDialogWatcher prompt(COLOR_CYAN, std::chrono::milliseconds(100)); + AdvanceDialogWatcher advance_dialog(COLOR_YELLOW, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + { + bag_detector, + bag_neutral, + selected, + prompt, + advance_dialog, + } + ); + context.wait_for(std::chrono::milliseconds(50)); + if (ret == 4){ + // Make sure we're not mistakening this for the other dialogs. + auto screenshot = stream.video().snapshot(); + if (prompt.detect(screenshot)){ + ret = 3; + } + } + + + switch (ret){ + case 0: + stream.log("No longer in bag..."); + if (!attach_completed){ + errors++; + } + return; + case 1: + stream.log("Detected bag neutral..."); + if (attach_completed){ + pbf_press_button(context, BUTTON_B, 20, 30); + }else{ + pbf_press_button(context, BUTTON_A, 20, 30); + } + break; + case 2: + stream.log("Detected selection..."); + pbf_press_button(context, BUTTON_A, 20, 30); +// attach_completed = true; + break; + case 3: + stream.log("Detected prompt..."); + pbf_press_button(context, BUTTON_A, 20, 30); + break; + case 4: + stream.log("Detected dialog..."); + pbf_press_button(context, BUTTON_B, 20, 30); + attach_completed = true; + break; + } + } +} + + + +void attach_item_from_box( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t category_index, + size_t& errors +){ + bool attach_attempted = false; +// bool attach_completed = false; + int expected = 0; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(60)){ + dump_image_and_throw_recoverable_exception( + info, stream, "AttachFailed", + "Failed to attach item after 1 minute." + ); + } + + SomethingInBoxSlotDetector exists(COLOR_BLUE); + BoxWatcher box_detector(COLOR_RED); + PromptDialogWatcher selected_empty(COLOR_CYAN, {0.60, 0.57, 0.30, 0.09}, std::chrono::milliseconds(100)); + PromptDialogWatcher selected_held(COLOR_CYAN, {0.60, 0.46, 0.30, 0.09}, std::chrono::milliseconds(100)); + BagWatcher bag_detector(BagWatcher::FinderType::PRESENT, COLOR_GREEN); +// AdvanceDialogWatcher advance_dialog(COLOR_YELLOW, std::chrono::milliseconds(250)); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + { + box_detector, + selected_empty, + selected_held, + bag_detector, +// advance_dialog, + } + ); + context.wait_for(std::chrono::milliseconds(50)); +#if 0 + if (ret == 4){ + // Make sure we're not mistakening this for the other dialogs. + auto screenshot = stream.video().snapshot(); + if (selected_empty.detect(screenshot)){ + ret = 1; + }else if (selected_held.detect(screenshot)){ + ret = 2; + } + } +#endif + + switch (ret){ + case 0:{ + if (ret == expected){ + stream.log("Detected box neutral."); + }else{ + stream.log("Detected box neutral. (unexpected)", COLOR_RED); + errors++; + } + + auto screenshot = stream.video().snapshot(); + if (exists.detect(screenshot)){ + if (attach_attempted){ + return; + } + attach_attempted = false; + pbf_press_button(context, BUTTON_A, 20, 20); + expected = 1; + continue; + }else{ + stream.log("Slot is empty."); + return; + } + } + case 1: + if (ret == expected){ + stream.log("Detected empty selection. Attaching..."); + }else{ + stream.log("Detected empty selection. Attaching... (unexpected)", COLOR_RED); + errors++; + } + + pbf_press_button(context, BUTTON_A, 20, 30); + + expected = 3; + continue; + + case 2: + if (1 == expected){ + stream.log("Detected held selection. Replacing..."); + }else{ + stream.log("Detected held selection. Replacing... (unexpected)", COLOR_RED); + errors++; + } + + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + pbf_press_button(context, BUTTON_A, 20, 30); + + expected = 3; + continue; + + case 3: + if (ret == expected){ + stream.log("Detected bag."); + }else{ + stream.log("Detected bag.(unexpected)", COLOR_RED); + errors++; + } + + context.wait_for(std::chrono::milliseconds(200)); + if (attach_attempted){ + pbf_press_button(context, BUTTON_B, 20, 30); + expected = 0; + continue; + } + + for (size_t c = 0; c < category_index; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + } + + attach_item_from_bag(info, stream, context, errors); + attach_attempted = true; + + expected = 0; + continue; + + default: + dump_image_and_throw_recoverable_exception( + info, stream, "NoStateAttachingItem", "No recognized state while attaching item after 10 seconds." + ); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h index 23b08e19e4..f9a67f9dc3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h @@ -1,41 +1,41 @@ -/* Box Attach - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BoxAttach_H -#define PokemonAutomation_PokemonSV_BoxAttach_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// With the cursor over the item you want to attach, attach to the current -// Pokemon, replacing if neccessary. -void attach_item_from_bag( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t& errors -); - -// With the cursor over the pokemon you want to attach the item to. -// Make sure you are in the item view. -void attach_item_from_box( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t category_index, - size_t& errors -); - - - -} -} -} -#endif +/* Box Attach + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BoxAttach_H +#define PokemonAutomation_PokemonSV_BoxAttach_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// With the cursor over the item you want to attach, attach to the current +// Pokemon, replacing if neccessary. +void attach_item_from_bag( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t& errors +); + +// With the cursor over the pokemon you want to attach the item to. +// Make sure you are in the item view. +void attach_item_from_box( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t category_index, + size_t& errors +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp index 374118cf91..f1f80f1b42 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.cpp @@ -1,188 +1,188 @@ -/* Box Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_BoxRoutines.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV_BoxRelease.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -void release_one_pokemon( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t& errors -){ - bool release_attempted = false; - bool release_completed = false; - int expected = 0; - int consecutive_box_neutrals = 0; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(60)){ - dump_image_and_throw_recoverable_exception( - info, stream, "ReleaseFailed", - "Failed to release " + Pokemon::STRING_POKEMON + " after 1 minute." - ); - } - - SomethingInBoxSlotDetector exists(COLOR_BLUE); -// GradientArrowDetector change_marks(COLOR_MAGENTA, GradientArrowType::DOWN, {0.28, 0.38, 0.30, 0.10}); - BoxWatcher box_detector(COLOR_RED); - BoxSelectWatcher selected(COLOR_YELLOW, std::chrono::milliseconds(100)); - PromptDialogWatcher confirm(COLOR_CYAN, std::chrono::milliseconds(100)); - AdvanceDialogWatcher advance_dialog(COLOR_GREEN, DialogType::DIALOG_ALL, std::chrono::milliseconds(250)); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - { - box_detector, - selected, - confirm, - advance_dialog - } - ); - context.wait_for(std::chrono::milliseconds(50)); - if (ret == 3){ - // Make sure we're not mistakening this for the other dialogs. - auto screenshot = stream.video().snapshot(); - if (selected.detect(screenshot)){ - ret = 1; - }else if (confirm.detect(screenshot)){ - ret = 2; - } - } -// cout << "consecutive_box_neutrals = " << consecutive_box_neutrals << endl; - - switch (ret){ - case 0:{ - auto screenshot = stream.video().snapshot(); -#if 0 - // Disambiguate with mark change. - if (change_marks.detect(screenshot)){ - stream.log("Detected mark change.", COLOR_RED); - pbf_press_button(context, BUTTON_B, 20, 20); - expected = 0; - continue; - } -#endif - - if (ret == expected){ - stream.log("Detected box neutral."); - consecutive_box_neutrals = 0; - }else{ - // Disambiguate with mark change. - stream.log("Detected box neutral. (unexpected)", COLOR_RED); - errors++; - consecutive_box_neutrals++; -// cout << "consecutive_box_neutrals = " << consecutive_box_neutrals << endl; - if (consecutive_box_neutrals >= 5){ - pbf_press_button(context, BUTTON_B, 20, 20); - expected = 0; - continue; - } - } - - if (exists.detect(screenshot)){ - if (release_attempted && release_completed){ - return; - } - release_attempted = false; - release_completed = false; - pbf_press_button(context, BUTTON_A, 20, 20); - expected = 1; - continue; - }else{ - stream.log("Slot is empty."); - return; - } - } - case 1: - if (ret == expected){ - stream.log("Detected selection. Releasing..."); - }else{ - stream.log("Detected selection. Releasing... (unexpected)", COLOR_RED); - errors++; - } - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_dpad(context, DPAD_UP, 10, 10); - - // Double up this A press since dropping it currently isn't recoverable. - pbf_press_button(context, BUTTON_A, 5, 3); - pbf_press_button(context, BUTTON_A, 5, 27); - - expected = 2; - continue; - case 2: - if (ret == expected){ - stream.log("Detected release confirmation."); - }else{ - stream.log("Detected release confirmation. (unexpected)", COLOR_RED); - errors++; - } - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_button(context, BUTTON_A, 20, 20); - release_attempted = true; - expected = 3; - continue; - case 3: - if (ret == expected){ - stream.log("Detected advance dialog."); - }else{ - stream.log("Detected advance dialog. (unexpected)", COLOR_RED); - errors++; - } - pbf_press_button(context, BUTTON_A, 20, 20); - release_completed = true; - expected = 0; - continue; - default: - dump_image_and_throw_recoverable_exception( - info, stream, - "NoStateReleasingPokemon", - "No recognized state while releasing a pokemon after 10 seconds." - ); - } - } -} - -void release_box( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t& errors, uint8_t start_row -){ - context.wait_for_all_requests(); - stream.log("Release one box."); - stream.overlay().add_log("Release box", COLOR_WHITE); - for (uint8_t row = start_row; row < 5; row++){ - for (uint8_t j_col = 0; j_col < 6; j_col++){ - // Go through slots in a Z-shape pattern - uint8_t col = (row % 2 == 0 ? j_col : 5 - j_col); - move_box_cursor(info, stream, context, BoxCursorLocation::SLOTS, row, col); - release_one_pokemon(info, stream, context, errors); - } - } -} - - - - -} -} -} +/* Box Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_BoxRoutines.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV_BoxRelease.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +void release_one_pokemon( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t& errors +){ + bool release_attempted = false; + bool release_completed = false; + int expected = 0; + int consecutive_box_neutrals = 0; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(60)){ + dump_image_and_throw_recoverable_exception( + info, stream, "ReleaseFailed", + "Failed to release " + Pokemon::STRING_POKEMON + " after 1 minute." + ); + } + + SomethingInBoxSlotDetector exists(COLOR_BLUE); +// GradientArrowDetector change_marks(COLOR_MAGENTA, GradientArrowType::DOWN, {0.28, 0.38, 0.30, 0.10}); + BoxWatcher box_detector(COLOR_RED); + BoxSelectWatcher selected(COLOR_YELLOW, std::chrono::milliseconds(100)); + PromptDialogWatcher confirm(COLOR_CYAN, std::chrono::milliseconds(100)); + AdvanceDialogWatcher advance_dialog(COLOR_GREEN, DialogType::DIALOG_ALL, std::chrono::milliseconds(250)); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + { + box_detector, + selected, + confirm, + advance_dialog + } + ); + context.wait_for(std::chrono::milliseconds(50)); + if (ret == 3){ + // Make sure we're not mistakening this for the other dialogs. + auto screenshot = stream.video().snapshot(); + if (selected.detect(screenshot)){ + ret = 1; + }else if (confirm.detect(screenshot)){ + ret = 2; + } + } +// cout << "consecutive_box_neutrals = " << consecutive_box_neutrals << endl; + + switch (ret){ + case 0:{ + auto screenshot = stream.video().snapshot(); +#if 0 + // Disambiguate with mark change. + if (change_marks.detect(screenshot)){ + stream.log("Detected mark change.", COLOR_RED); + pbf_press_button(context, BUTTON_B, 20, 20); + expected = 0; + continue; + } +#endif + + if (ret == expected){ + stream.log("Detected box neutral."); + consecutive_box_neutrals = 0; + }else{ + // Disambiguate with mark change. + stream.log("Detected box neutral. (unexpected)", COLOR_RED); + errors++; + consecutive_box_neutrals++; +// cout << "consecutive_box_neutrals = " << consecutive_box_neutrals << endl; + if (consecutive_box_neutrals >= 5){ + pbf_press_button(context, BUTTON_B, 20, 20); + expected = 0; + continue; + } + } + + if (exists.detect(screenshot)){ + if (release_attempted && release_completed){ + return; + } + release_attempted = false; + release_completed = false; + pbf_press_button(context, BUTTON_A, 20, 20); + expected = 1; + continue; + }else{ + stream.log("Slot is empty."); + return; + } + } + case 1: + if (ret == expected){ + stream.log("Detected selection. Releasing..."); + }else{ + stream.log("Detected selection. Releasing... (unexpected)", COLOR_RED); + errors++; + } + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_dpad(context, DPAD_UP, 10, 10); + + // Double up this A press since dropping it currently isn't recoverable. + pbf_press_button(context, BUTTON_A, 5, 3); + pbf_press_button(context, BUTTON_A, 5, 27); + + expected = 2; + continue; + case 2: + if (ret == expected){ + stream.log("Detected release confirmation."); + }else{ + stream.log("Detected release confirmation. (unexpected)", COLOR_RED); + errors++; + } + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_button(context, BUTTON_A, 20, 20); + release_attempted = true; + expected = 3; + continue; + case 3: + if (ret == expected){ + stream.log("Detected advance dialog."); + }else{ + stream.log("Detected advance dialog. (unexpected)", COLOR_RED); + errors++; + } + pbf_press_button(context, BUTTON_A, 20, 20); + release_completed = true; + expected = 0; + continue; + default: + dump_image_and_throw_recoverable_exception( + info, stream, + "NoStateReleasingPokemon", + "No recognized state while releasing a pokemon after 10 seconds." + ); + } + } +} + +void release_box( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t& errors, uint8_t start_row +){ + context.wait_for_all_requests(); + stream.log("Release one box."); + stream.overlay().add_log("Release box", COLOR_WHITE); + for (uint8_t row = start_row; row < 5; row++){ + for (uint8_t j_col = 0; j_col < 6; j_col++){ + // Go through slots in a Z-shape pattern + uint8_t col = (row % 2 == 0 ? j_col : 5 - j_col); + move_box_cursor(info, stream, context, BoxCursorLocation::SLOTS, row, col); + release_one_pokemon(info, stream, context, errors); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h index 68c34487da..2cefae9704 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h @@ -1,46 +1,46 @@ -/* Box Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BoxRelease_H -#define PokemonAutomation_PokemonSV_BoxRelease_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Assuming the current slot in box system is not an egg -// release current selected pokemon in the box system. -// It will do nothing if the current slot is empty. -// Throws OperationFailedException, if it got stuck or timed out. -// The # of errors are stored into "errors". These are usually dropped button -// presses that the function recovered from. -void release_one_pokemon( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t& errors -); - -// Release a box of pokemon. Can have empty spots or eggs. Eggs are not released. -// Throws OperationFailedException, if it got stuck or timed out. -// The # of errors are stored into "errors". These are usually dropped button -// presses that the function recovered from. -void release_box( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t& errors, - uint8_t start_row = 0 // Start from this row. (skip te first "start_row" rows) -); - - -} -} -} -#endif +/* Box Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BoxRelease_H +#define PokemonAutomation_PokemonSV_BoxRelease_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Assuming the current slot in box system is not an egg +// release current selected pokemon in the box system. +// It will do nothing if the current slot is empty. +// Throws OperationFailedException, if it got stuck or timed out. +// The # of errors are stored into "errors". These are usually dropped button +// presses that the function recovered from. +void release_one_pokemon( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t& errors +); + +// Release a box of pokemon. Can have empty spots or eggs. Eggs are not released. +// Throws OperationFailedException, if it got stuck or timed out. +// The # of errors are stored into "errors". These are usually dropped button +// presses that the function recovered from. +void release_box( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t& errors, + uint8_t start_row = 0 // Start from this row. (skip te first "start_row" rows) +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp index dbd283796f..3bc4522fee 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.cpp @@ -1,407 +1,407 @@ -/* Sandwich Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include -//#include -//#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -//#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV_BoxRoutines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -bool change_view_to_stats_or_judge( - VideoStream& stream, ProControllerContext& context, - bool throw_exception -){ - ImageFloatBox name_bar(0.66, 0.08, 0.52, 0.04); - OverlayBoxScope name_bar_overlay(stream.overlay(), name_bar); - for (size_t attempts = 0;; attempts++){ - if (throw_exception){ - if (attempts == 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to change Pokemon view after 10 tries.", - stream - ); - } - }else{ - if (attempts == 3){ - return false; - } - } - - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - ImageStats stats = image_stats(extract_box_reference(screen, name_bar)); -// cout << stats.stddev << endl; - if (stats.stddev.sum() > 50){ - break; - } - - stream.log("Unable to detect stats menu. Attempting to correct.", COLOR_RED); - -// // Alternate one and two + presses. If IV checker is enabled, we should -// // land on the IV checker. Otherwise, it will land us back to nothing. -// // Then the next press will be a single which will put us on the stats -// // with no IV checker. - pbf_press_button(context, BUTTON_PLUS, 20, 105); -// if (attempts % 2 == 0){ -// pbf_press_button(context, BUTTON_PLUS, 20, 230); -// } - } - return true; -} - - -void change_view_to_judge( - VideoStream& stream, ProControllerContext& context, - Language language -){ - if (language == Language::None){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "change_view_to_judge() called with no language." - ); - } - - ImageFloatBox name_bar(0.66, 0.08, 0.52, 0.04); - IvJudgeReaderScope iv_checker(stream.overlay(), language); - OverlayBoxScope name_bar_overlay(stream.overlay(), name_bar); - for (size_t attempts = 0;; attempts++){ - if (attempts == 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to change Pokemon view to judge after 10 tries. Have you unlocked it?", - stream - ); - } - - context.wait_for_all_requests(); - VideoSnapshot screen = stream.video().snapshot(); - ImageStats stats = image_stats(extract_box_reference(screen, name_bar)); -// cout << stats.stddev << endl; - - // Check if we're even on a stats screen. - if (stats.stddev.sum() < 50){ - stream.log("Unable to detect stats menu. Attempting to correct.", COLOR_RED); - pbf_press_button(context, BUTTON_PLUS, 20, 105); - continue; - } - - // See if we're on the judge screen. - IvJudgeReader::Results ivs = iv_checker.read(stream.logger(), screen); - - size_t detected = 0; - if (ivs.hp != IvJudgeValue::UnableToDetect) detected++; - if (ivs.attack != IvJudgeValue::UnableToDetect) detected++; - if (ivs.defense != IvJudgeValue::UnableToDetect) detected++; - if (ivs.spatk != IvJudgeValue::UnableToDetect) detected++; - if (ivs.spdef != IvJudgeValue::UnableToDetect) detected++; - if (ivs.speed != IvJudgeValue::UnableToDetect) detected++; - - // If less than 4 of the IVs are read, assume we're not on the judge screen. - if (detected < 4){ - pbf_press_button(context, BUTTON_PLUS, 20, 230); - }else{ - break; - } - } -} - - - -// Moving to left/right box is blind sequence. To prevent game dropping button inputs, -// press the button longer. -void move_to_left_box(ProControllerContext& context){ - pbf_press_button(context, BUTTON_L, 60, 100); -} -void move_to_right_box(ProControllerContext& context){ - pbf_press_button(context, BUTTON_R, 60, 100); -} - -namespace{ - -// In box system, when using button Minus or button Y, it will enter a mode for box selection and holding pokemon. -// The function detects the existence of button symbol in the bottom row of the screen to make -// sure the mode is entered or left. -// If `enter_mode` is true, the program will assume it is not in the mode, and enter the mode by calling -// `button_operation()` repeatedly until the mode is observed. -// If `enter_mode` is false, the program will assume it is in the mode, and leave the mode by calling -// `button_operation()` repeatedly until it confirms to have left the mode. -void change_held_mode(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - std::function button_operation, bool enter_mode, - const char* time_out_error_name, const char* time_out_error_message) -{ - // First attempt to change mode - button_operation(); - - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(60)){ - dump_image_and_throw_recoverable_exception( - info, stream, time_out_error_name, time_out_error_message - ); - } - BoxSelectionBoxModeWatcher watcher; - context.wait_for_all_requests(); - if (wait_until(stream, context, std::chrono::seconds(10), {watcher}) == 0){ - if (watcher.in_box_selection_mode() == enter_mode){ - break; - } - // else: not in the desired mode - button_operation(); - continue; - } - // Cannot detect box selection mode after 10 secs - dump_image_and_throw_recoverable_exception( - info, stream, "NoStateBoxSelectionMode", "Cannot determine box selection mode for 10 seconds." - ); - } -} - -} // anonymous namespace - -// Use box selection mode to hold one column of pokemon. -// Use visual feedback to ensure button Minus is pressed to turn on box selection mode/ -// But no feedback on the button A press to make sure the selection is complete. -void hold_one_column(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Holding one column."); - // Press Minus to draw selection box - const bool to_enter_selection = true; - change_held_mode( - info, stream, context, - [&context](){ pbf_press_button(context, BUTTON_MINUS, 50, 40); }, - to_enter_selection, - "TimeoutHoldingColumn", "Failed to enter box selection mode after 1 minute of Button Minus pressing." - ); - - // Select rest of the pary - // Press down multiple times to make sure we select full party in case the game drops some presses - for(int i = 0; i < 15; i++){ - ssf_press_dpad(context, DPAD_DOWN, 32ms); - ssf_press_left_joystick(context, 128, 255, 4, 5, 3); - } - // Hold rest of the party - pbf_wait(context, 60); - // We cannot detect whether this Button A will be dropped or not. - // So we have to go blind here. - pbf_press_button(context, BUTTON_A, 50, 40); - context.wait_for_all_requests(); -} - -// Assuming already holding one or more pokemon, press A to drop them. -void drop_held_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Drop held pokemon."); - const bool to_enter_selection = false; - change_held_mode( - info, stream, context, - [&context](){ pbf_press_button(context, BUTTON_A, 60, 60); }, - to_enter_selection, - "TimeoutDroppingPokemon", "Failed to drop pokemon after 1 minute of Button A pressing." - ); -} - -// Assuming already holding one or more pokemon, press B to cancel the holding. -void cancel_held_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Cancel pokemon holding."); - const bool to_enter_selection = false; - change_held_mode( - info, stream, context, - [&context](){ pbf_press_button(context, BUTTON_B, 60, 60); }, - to_enter_selection, - "TimeoutCancellingHolding", "Failed to cancel holding pokemon after 1 minute of Button B pressing." - ); -} - -// Assuming the current slot is not empy, press button Y to hold the current pokemon -void press_y_to_hold_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Press button Y to hold pokemon for swapping."); - const bool to_enter_selection = true; - change_held_mode( - info, stream, context, - [&context](){ pbf_press_button(context, BUTTON_Y, 60, 60); }, - to_enter_selection, - "TimeoutHoldingPokemonByButtonY", "Failed to hold a pokemon by button Y after 1 minute of trying." - ); -} - - - -uint8_t check_empty_slots_in_party(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - BoxEmptyPartyWatcher watcher; - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - {watcher} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "ReadSlotEmptinessFailed", "check_empty_slots_in_party(): Cannot read party emptiness in box system." - ); - } - - return watcher.num_empty_slots_found(); -} - -void load_one_column_to_party( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - EventNotificationOption& notification, - uint8_t column_index, bool has_clone_ride_pokemon -){ - context.wait_for_all_requests(); - stream.log("Load column " + std::to_string(column_index) + " to party."); - stream.overlay().add_log("Load column " + std::to_string(column_index+1), COLOR_WHITE); - - size_t fail_count = 0; - while (true){ - // Move cursor to the target column - move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::SLOTS, has_clone_ride_pokemon ? 1 : 0, column_index); - hold_one_column(env.program_info(), stream, context); - try{ - // Move the held column to party - move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::PARTY, has_clone_ride_pokemon ? 2 : 1, 0); - }catch (OperationFailedException& e){ - e.send_notification(env, notification); - - if (++fail_count == 10){ - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "ConsecutiveColumnMoveFailure", - "load_one_column_to_party(): consecutive failure of moving column around." - ); - } - stream.log("Failed to move column around. Cancelling box selection and try again."); - // Cannot move column to party. It could be that the game dropped the button A press that is expected to finish - // the column selection. - // We can press B to back out and try again. - cancel_held_pokemon(env.program_info(), stream, context); - continue; - } - break; - } - - // Drop the column to party - drop_held_pokemon(env.program_info(), stream, context); - - context.wait_for_all_requests(); - stream.log("Loaded column " + std::to_string(column_index) + " to party."); -} - -void unload_one_column_from_party( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - EventNotificationOption& notification, - uint8_t column_index, bool has_clone_ride_pokemon -){ - context.wait_for_all_requests(); - stream.log("Unload party to column " + std::to_string(column_index) + "."); - stream.overlay().add_log("Unload to column " + std::to_string(column_index+1), COLOR_WHITE); - - size_t fail_count = 0; - while (true){ - // Move cursor to party column - move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::PARTY, has_clone_ride_pokemon ? 2 : 1, 0); - hold_one_column(env.program_info(), stream, context); - - try{ - // Move the held column to target - move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::SLOTS, has_clone_ride_pokemon ? 1 : 0, column_index); - }catch (OperationFailedException& e){ - e.send_notification(env, notification); - - if (++fail_count == 10){ - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "ConsecutiveColumnMoveFailure", - "unload_one_column_from_party(): consecutive failure of moving column around." - ); - } - stream.log("Failed to move column around. Cancelling box selection and try again."); - // Cannot move column to party. It could be that the game dropped the button A press that is expected to finish - // the column selection. - // We can press B to back out and try again. - cancel_held_pokemon(env.program_info(), stream, context); - continue; - } - break; - } - // Drop the column - drop_held_pokemon(env.program_info(), stream, context); - - context.wait_for_all_requests(); - stream.log("Unloaded party to column " + std::to_string(column_index) + "."); -} - -void move_box_cursor(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const BoxCursorLocation& side, uint8_t row, uint8_t col) -{ - context.wait_for_all_requests(); - stream.log("Move cursor to " + BOX_LOCATION_STRING(side, row, col) + "."); - BoxDetector detector; - VideoOverlaySet overlay_set(stream.overlay()); - detector.make_overlays(overlay_set); - detector.move_cursor(info, stream, context, side, row, col); - stream.log("Cursor moved."); -} - -void swap_two_box_slots( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const BoxCursorLocation& source_side, uint8_t source_row, uint8_t source_col, - const BoxCursorLocation& target_side, uint8_t target_row, uint8_t target_col -) -{ - context.wait_for_all_requests(); - stream.log("Swap two slots " + BOX_LOCATION_STRING(source_side, source_row, source_col) - + " and " + BOX_LOCATION_STRING(target_side, target_row, target_col) + "."); - stream.overlay().add_log("Swap slots", COLOR_WHITE); - - BoxDetector detector; - VideoOverlaySet overlay_set(stream.overlay()); - detector.make_overlays(overlay_set); - - detector.move_cursor(info, stream, context, source_side, source_row, source_col); - - { - const bool stop_on_exists = true; - SomethingInBoxSlotWatcher exists(COLOR_BLUE, stop_on_exists); - if (wait_until(stream, context, std::chrono::seconds(3), {exists}) < 0){ - dump_image_and_throw_recoverable_exception(info, stream, "EmptySourceSwap", "Swapping an empty slot."); - } - } - - press_y_to_hold_pokemon(info, stream, context); - - detector.move_cursor(info, stream, context, target_side, target_row, target_col); - - drop_held_pokemon(info, stream, context); - - stream.log("Swapped slots."); -} - -} -} -} +/* Sandwich Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include +//#include +//#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +//#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV_BoxRoutines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +bool change_view_to_stats_or_judge( + VideoStream& stream, ProControllerContext& context, + bool throw_exception +){ + ImageFloatBox name_bar(0.66, 0.08, 0.52, 0.04); + OverlayBoxScope name_bar_overlay(stream.overlay(), name_bar); + for (size_t attempts = 0;; attempts++){ + if (throw_exception){ + if (attempts == 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to change Pokemon view after 10 tries.", + stream + ); + } + }else{ + if (attempts == 3){ + return false; + } + } + + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + ImageStats stats = image_stats(extract_box_reference(screen, name_bar)); +// cout << stats.stddev << endl; + if (stats.stddev.sum() > 50){ + break; + } + + stream.log("Unable to detect stats menu. Attempting to correct.", COLOR_RED); + +// // Alternate one and two + presses. If IV checker is enabled, we should +// // land on the IV checker. Otherwise, it will land us back to nothing. +// // Then the next press will be a single which will put us on the stats +// // with no IV checker. + pbf_press_button(context, BUTTON_PLUS, 20, 105); +// if (attempts % 2 == 0){ +// pbf_press_button(context, BUTTON_PLUS, 20, 230); +// } + } + return true; +} + + +void change_view_to_judge( + VideoStream& stream, ProControllerContext& context, + Language language +){ + if (language == Language::None){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "change_view_to_judge() called with no language." + ); + } + + ImageFloatBox name_bar(0.66, 0.08, 0.52, 0.04); + IvJudgeReaderScope iv_checker(stream.overlay(), language); + OverlayBoxScope name_bar_overlay(stream.overlay(), name_bar); + for (size_t attempts = 0;; attempts++){ + if (attempts == 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to change Pokemon view to judge after 10 tries. Have you unlocked it?", + stream + ); + } + + context.wait_for_all_requests(); + VideoSnapshot screen = stream.video().snapshot(); + ImageStats stats = image_stats(extract_box_reference(screen, name_bar)); +// cout << stats.stddev << endl; + + // Check if we're even on a stats screen. + if (stats.stddev.sum() < 50){ + stream.log("Unable to detect stats menu. Attempting to correct.", COLOR_RED); + pbf_press_button(context, BUTTON_PLUS, 20, 105); + continue; + } + + // See if we're on the judge screen. + IvJudgeReader::Results ivs = iv_checker.read(stream.logger(), screen); + + size_t detected = 0; + if (ivs.hp != IvJudgeValue::UnableToDetect) detected++; + if (ivs.attack != IvJudgeValue::UnableToDetect) detected++; + if (ivs.defense != IvJudgeValue::UnableToDetect) detected++; + if (ivs.spatk != IvJudgeValue::UnableToDetect) detected++; + if (ivs.spdef != IvJudgeValue::UnableToDetect) detected++; + if (ivs.speed != IvJudgeValue::UnableToDetect) detected++; + + // If less than 4 of the IVs are read, assume we're not on the judge screen. + if (detected < 4){ + pbf_press_button(context, BUTTON_PLUS, 20, 230); + }else{ + break; + } + } +} + + + +// Moving to left/right box is blind sequence. To prevent game dropping button inputs, +// press the button longer. +void move_to_left_box(ProControllerContext& context){ + pbf_press_button(context, BUTTON_L, 60, 100); +} +void move_to_right_box(ProControllerContext& context){ + pbf_press_button(context, BUTTON_R, 60, 100); +} + +namespace{ + +// In box system, when using button Minus or button Y, it will enter a mode for box selection and holding pokemon. +// The function detects the existence of button symbol in the bottom row of the screen to make +// sure the mode is entered or left. +// If `enter_mode` is true, the program will assume it is not in the mode, and enter the mode by calling +// `button_operation()` repeatedly until the mode is observed. +// If `enter_mode` is false, the program will assume it is in the mode, and leave the mode by calling +// `button_operation()` repeatedly until it confirms to have left the mode. +void change_held_mode(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + std::function button_operation, bool enter_mode, + const char* time_out_error_name, const char* time_out_error_message) +{ + // First attempt to change mode + button_operation(); + + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(60)){ + dump_image_and_throw_recoverable_exception( + info, stream, time_out_error_name, time_out_error_message + ); + } + BoxSelectionBoxModeWatcher watcher; + context.wait_for_all_requests(); + if (wait_until(stream, context, std::chrono::seconds(10), {watcher}) == 0){ + if (watcher.in_box_selection_mode() == enter_mode){ + break; + } + // else: not in the desired mode + button_operation(); + continue; + } + // Cannot detect box selection mode after 10 secs + dump_image_and_throw_recoverable_exception( + info, stream, "NoStateBoxSelectionMode", "Cannot determine box selection mode for 10 seconds." + ); + } +} + +} // anonymous namespace + +// Use box selection mode to hold one column of pokemon. +// Use visual feedback to ensure button Minus is pressed to turn on box selection mode/ +// But no feedback on the button A press to make sure the selection is complete. +void hold_one_column(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Holding one column."); + // Press Minus to draw selection box + const bool to_enter_selection = true; + change_held_mode( + info, stream, context, + [&context](){ pbf_press_button(context, BUTTON_MINUS, 50, 40); }, + to_enter_selection, + "TimeoutHoldingColumn", "Failed to enter box selection mode after 1 minute of Button Minus pressing." + ); + + // Select rest of the pary + // Press down multiple times to make sure we select full party in case the game drops some presses + for(int i = 0; i < 15; i++){ + ssf_press_dpad(context, DPAD_DOWN, 32ms); + ssf_press_left_joystick(context, 128, 255, 4, 5, 3); + } + // Hold rest of the party + pbf_wait(context, 60); + // We cannot detect whether this Button A will be dropped or not. + // So we have to go blind here. + pbf_press_button(context, BUTTON_A, 50, 40); + context.wait_for_all_requests(); +} + +// Assuming already holding one or more pokemon, press A to drop them. +void drop_held_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Drop held pokemon."); + const bool to_enter_selection = false; + change_held_mode( + info, stream, context, + [&context](){ pbf_press_button(context, BUTTON_A, 60, 60); }, + to_enter_selection, + "TimeoutDroppingPokemon", "Failed to drop pokemon after 1 minute of Button A pressing." + ); +} + +// Assuming already holding one or more pokemon, press B to cancel the holding. +void cancel_held_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Cancel pokemon holding."); + const bool to_enter_selection = false; + change_held_mode( + info, stream, context, + [&context](){ pbf_press_button(context, BUTTON_B, 60, 60); }, + to_enter_selection, + "TimeoutCancellingHolding", "Failed to cancel holding pokemon after 1 minute of Button B pressing." + ); +} + +// Assuming the current slot is not empy, press button Y to hold the current pokemon +void press_y_to_hold_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Press button Y to hold pokemon for swapping."); + const bool to_enter_selection = true; + change_held_mode( + info, stream, context, + [&context](){ pbf_press_button(context, BUTTON_Y, 60, 60); }, + to_enter_selection, + "TimeoutHoldingPokemonByButtonY", "Failed to hold a pokemon by button Y after 1 minute of trying." + ); +} + + + +uint8_t check_empty_slots_in_party(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + BoxEmptyPartyWatcher watcher; + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + {watcher} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "ReadSlotEmptinessFailed", "check_empty_slots_in_party(): Cannot read party emptiness in box system." + ); + } + + return watcher.num_empty_slots_found(); +} + +void load_one_column_to_party( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + EventNotificationOption& notification, + uint8_t column_index, bool has_clone_ride_pokemon +){ + context.wait_for_all_requests(); + stream.log("Load column " + std::to_string(column_index) + " to party."); + stream.overlay().add_log("Load column " + std::to_string(column_index+1), COLOR_WHITE); + + size_t fail_count = 0; + while (true){ + // Move cursor to the target column + move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::SLOTS, has_clone_ride_pokemon ? 1 : 0, column_index); + hold_one_column(env.program_info(), stream, context); + try{ + // Move the held column to party + move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::PARTY, has_clone_ride_pokemon ? 2 : 1, 0); + }catch (OperationFailedException& e){ + e.send_notification(env, notification); + + if (++fail_count == 10){ + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "ConsecutiveColumnMoveFailure", + "load_one_column_to_party(): consecutive failure of moving column around." + ); + } + stream.log("Failed to move column around. Cancelling box selection and try again."); + // Cannot move column to party. It could be that the game dropped the button A press that is expected to finish + // the column selection. + // We can press B to back out and try again. + cancel_held_pokemon(env.program_info(), stream, context); + continue; + } + break; + } + + // Drop the column to party + drop_held_pokemon(env.program_info(), stream, context); + + context.wait_for_all_requests(); + stream.log("Loaded column " + std::to_string(column_index) + " to party."); +} + +void unload_one_column_from_party( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + EventNotificationOption& notification, + uint8_t column_index, bool has_clone_ride_pokemon +){ + context.wait_for_all_requests(); + stream.log("Unload party to column " + std::to_string(column_index) + "."); + stream.overlay().add_log("Unload to column " + std::to_string(column_index+1), COLOR_WHITE); + + size_t fail_count = 0; + while (true){ + // Move cursor to party column + move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::PARTY, has_clone_ride_pokemon ? 2 : 1, 0); + hold_one_column(env.program_info(), stream, context); + + try{ + // Move the held column to target + move_box_cursor(env.program_info(), stream, context, BoxCursorLocation::SLOTS, has_clone_ride_pokemon ? 1 : 0, column_index); + }catch (OperationFailedException& e){ + e.send_notification(env, notification); + + if (++fail_count == 10){ + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "ConsecutiveColumnMoveFailure", + "unload_one_column_from_party(): consecutive failure of moving column around." + ); + } + stream.log("Failed to move column around. Cancelling box selection and try again."); + // Cannot move column to party. It could be that the game dropped the button A press that is expected to finish + // the column selection. + // We can press B to back out and try again. + cancel_held_pokemon(env.program_info(), stream, context); + continue; + } + break; + } + // Drop the column + drop_held_pokemon(env.program_info(), stream, context); + + context.wait_for_all_requests(); + stream.log("Unloaded party to column " + std::to_string(column_index) + "."); +} + +void move_box_cursor(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const BoxCursorLocation& side, uint8_t row, uint8_t col) +{ + context.wait_for_all_requests(); + stream.log("Move cursor to " + BOX_LOCATION_STRING(side, row, col) + "."); + BoxDetector detector; + VideoOverlaySet overlay_set(stream.overlay()); + detector.make_overlays(overlay_set); + detector.move_cursor(info, stream, context, side, row, col); + stream.log("Cursor moved."); +} + +void swap_two_box_slots( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const BoxCursorLocation& source_side, uint8_t source_row, uint8_t source_col, + const BoxCursorLocation& target_side, uint8_t target_row, uint8_t target_col +) +{ + context.wait_for_all_requests(); + stream.log("Swap two slots " + BOX_LOCATION_STRING(source_side, source_row, source_col) + + " and " + BOX_LOCATION_STRING(target_side, target_row, target_col) + "."); + stream.overlay().add_log("Swap slots", COLOR_WHITE); + + BoxDetector detector; + VideoOverlaySet overlay_set(stream.overlay()); + detector.make_overlays(overlay_set); + + detector.move_cursor(info, stream, context, source_side, source_row, source_col); + + { + const bool stop_on_exists = true; + SomethingInBoxSlotWatcher exists(COLOR_BLUE, stop_on_exists); + if (wait_until(stream, context, std::chrono::seconds(3), {exists}) < 0){ + dump_image_and_throw_recoverable_exception(info, stream, "EmptySourceSwap", "Swapping an empty slot."); + } + } + + press_y_to_hold_pokemon(info, stream, context); + + detector.move_cursor(info, stream, context, target_side, target_row, target_col); + + drop_held_pokemon(info, stream, context); + + stream.log("Swapped slots."); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h index d16d60f9ea..19ac4b52cc 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h @@ -1,87 +1,87 @@ -/* Box Routines - * - * From: https://github.com/PokemonAutomation/ - * - * Various functions to operate in box system. - */ - -#ifndef PokemonAutomation_PokemonSV_BoxRoutines_H -#define PokemonAutomation_PokemonSV_BoxRoutines_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - - struct ProgramInfo; - class ProgramEnvironment; - class EventNotificationOption; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -enum class BoxCursorLocation; - -// Assuming the current slot in box system is a pokemon, not egg or empty space, -// try to change the view to the judge. However, it may land on the stats instead. -// If it can't land on either stats or judge and `throw_exception` is true, it will throw an exception. -// Return true if it successfully changed view to judge (or stats if judege is not found) -bool change_view_to_stats_or_judge( - VideoStream& stream, ProControllerContext& context, - bool throw_exception = true -); - - -// Assuming the current slot in box system is a pokemon, not egg or empty space, -// change the view to the judge. If it fails, it will OperationFailedException::fire. -void change_view_to_judge( - VideoStream& stream, ProControllerContext& context, - Language language -); - - -// Press button L to move to the box on the left -void move_to_left_box(ProControllerContext& context); - -// Press button R to move to the box on the right -void move_to_right_box(ProControllerContext& context); - - - -// In box system, check how many slots in the party are empty -uint8_t check_empty_slots_in_party(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// In box system, assuming the party is empty, load one column in the current box onto party. -// if has_clone_ride_pokemon is true, skip loading the first row of the box. -void load_one_column_to_party( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - EventNotificationOption& notification, - uint8_t column_index, bool has_clone_ride_pokemon -); - -// In box system, assuming the target column is empty, unload party (after the lead) to the target column. -// if has_clone_ride_pokemon is true, skip unloading the second row of the party. -void unload_one_column_from_party( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - EventNotificationOption& notification, - uint8_t column_index, bool has_clone_ride_pokemon -); - -// In box system, move the cursor to the desired slot. -void move_box_cursor(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const BoxCursorLocation& side, uint8_t row, uint8_t col); - -// In box system, use button Y to swap two slots. -// The source slot must not be empty, while the target slot can be empty. -void swap_two_box_slots( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - const BoxCursorLocation& source_side, uint8_t source_row, uint8_t source_col, - const BoxCursorLocation& target_side, uint8_t target_row, uint8_t target_col -); - -} -} -} -#endif +/* Box Routines + * + * From: https://github.com/PokemonAutomation/ + * + * Various functions to operate in box system. + */ + +#ifndef PokemonAutomation_PokemonSV_BoxRoutines_H +#define PokemonAutomation_PokemonSV_BoxRoutines_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + + struct ProgramInfo; + class ProgramEnvironment; + class EventNotificationOption; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +enum class BoxCursorLocation; + +// Assuming the current slot in box system is a pokemon, not egg or empty space, +// try to change the view to the judge. However, it may land on the stats instead. +// If it can't land on either stats or judge and `throw_exception` is true, it will throw an exception. +// Return true if it successfully changed view to judge (or stats if judege is not found) +bool change_view_to_stats_or_judge( + VideoStream& stream, ProControllerContext& context, + bool throw_exception = true +); + + +// Assuming the current slot in box system is a pokemon, not egg or empty space, +// change the view to the judge. If it fails, it will OperationFailedException::fire. +void change_view_to_judge( + VideoStream& stream, ProControllerContext& context, + Language language +); + + +// Press button L to move to the box on the left +void move_to_left_box(ProControllerContext& context); + +// Press button R to move to the box on the right +void move_to_right_box(ProControllerContext& context); + + + +// In box system, check how many slots in the party are empty +uint8_t check_empty_slots_in_party(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// In box system, assuming the party is empty, load one column in the current box onto party. +// if has_clone_ride_pokemon is true, skip loading the first row of the box. +void load_one_column_to_party( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + EventNotificationOption& notification, + uint8_t column_index, bool has_clone_ride_pokemon +); + +// In box system, assuming the target column is empty, unload party (after the lead) to the target column. +// if has_clone_ride_pokemon is true, skip unloading the second row of the party. +void unload_one_column_from_party( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + EventNotificationOption& notification, + uint8_t column_index, bool has_clone_ride_pokemon +); + +// In box system, move the cursor to the desired slot. +void move_box_cursor(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const BoxCursorLocation& side, uint8_t row, uint8_t col); + +// In box system, use button Y to swap two slots. +// The source slot must not be empty, while the target slot can be empty. +void swap_two_box_slots( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + const BoxCursorLocation& source_side, uint8_t source_row, uint8_t source_col, + const BoxCursorLocation& target_side, uint8_t target_row, uint8_t target_col +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.cpp index 4e70791edf..1130651485 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.cpp @@ -1,185 +1,185 @@ -/* Mass Attach Items - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV_MassAttachItems.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -MassAttachItems_Descriptor::MassAttachItems_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:MassAttachItems", - STRING_POKEMON + " SV", "Mass Attach Items", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MassAttachItems.md", - "Mass attach items to " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct MassAttachItems_Descriptor::Stats : public StatsTracker{ - Stats() - : m_boxes(m_stats["Boxes"]) - , m_attached(m_stats["Attached"]) -// , m_replaced(m_stats["Replaced"]) - , m_empty(m_stats["Empty Slots"]) - , m_eggs(m_stats["Eggs"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Boxes"); - m_display_order.emplace_back("Attached"); -// m_display_order.emplace_back("Replaced"); - m_display_order.emplace_back("Empty Slots"); - m_display_order.emplace_back("Eggs"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_boxes; - std::atomic& m_attached; -// std::atomic& m_replaced; - std::atomic& m_empty; - std::atomic& m_eggs; - std::atomic& m_errors; -}; -std::unique_ptr MassAttachItems_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -MassAttachItems::MassAttachItems() - : GO_HOME_WHEN_DONE(false) - , ITEM_CATEGORY( - "Item Category:", - { - {ItemCategory::Medicines, "medicine", "Medicines"}, - {ItemCategory::PokeBalls, "balls", "Pok\u00e9 Balls"}, - {ItemCategory::BattleItems, "battle", "Battle Items"}, - {ItemCategory::Berries, "berries", "Berries"}, - {ItemCategory::OtherItems, "other", "Other Items"}, - {ItemCategory::TMs, "tms", "TMs"}, - {ItemCategory::Treasures, "treasures", "Treasures"}, - }, - LockMode::LOCK_WHILE_RUNNING, - ItemCategory::PokeBalls - ) - , BOXES( - "Number of Boxes to Attach:", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 0, 32 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(ITEM_CATEGORY); - PA_ADD_OPTION(BOXES); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void MassAttachItems::attach_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MassAttachItems_Descriptor::Stats& stats = env.current_stats(); - - env.log("Selecting " + STRING_POKEMON + "..."); - - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - BoxCurrentEggDetector egg_detector; - VideoOverlaySet overlays(env.console.overlay()); - sth_in_box_detector.make_overlays(overlays); - egg_detector.make_overlays(overlays); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - - if (!sth_in_box_detector.detect(screen)){ - stats.m_empty++; - return; - } - - if (egg_detector.detect(screen)){ - stats.m_eggs++; - return; - } - - try{ - size_t errors = 0; - attach_item_from_box(env.program_info(), env.console, context, (size_t)ITEM_CATEGORY.get(), errors); - stats.m_attached++; - stats.m_errors += errors; - }catch (OperationFailedException&){ - stats.m_errors++; - throw; - } -} -void MassAttachItems::attach_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - for (uint8_t row = 0; row < 5; row++){ - for (uint8_t j_col = 0; j_col < 6; j_col++){ - // Go through slots in a Z-shape pattern - uint8_t col = (row % 2 == 0 ? j_col : 5 - j_col); - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); - attach_one(box_detector, env, context); - env.update_stats(); - } - } -} - - - -void MassAttachItems::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - MassAttachItems_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 10, 0); - - BoxDetector box_detector; - VideoOverlaySet overlays(env.console.overlay()); - box_detector.make_overlays(overlays); - - for (uint8_t box = 0; box < BOXES; box++){ - if (box > 0){ - move_to_right_box(context); - } - context.wait_for_all_requests(); - - env.update_stats(); - - attach_box(box_detector, env, context); - - stats.m_boxes++; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} +/* Mass Attach Items + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxAttach.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV_MassAttachItems.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +MassAttachItems_Descriptor::MassAttachItems_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:MassAttachItems", + STRING_POKEMON + " SV", "Mass Attach Items", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MassAttachItems.md", + "Mass attach items to " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct MassAttachItems_Descriptor::Stats : public StatsTracker{ + Stats() + : m_boxes(m_stats["Boxes"]) + , m_attached(m_stats["Attached"]) +// , m_replaced(m_stats["Replaced"]) + , m_empty(m_stats["Empty Slots"]) + , m_eggs(m_stats["Eggs"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Boxes"); + m_display_order.emplace_back("Attached"); +// m_display_order.emplace_back("Replaced"); + m_display_order.emplace_back("Empty Slots"); + m_display_order.emplace_back("Eggs"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_boxes; + std::atomic& m_attached; +// std::atomic& m_replaced; + std::atomic& m_empty; + std::atomic& m_eggs; + std::atomic& m_errors; +}; +std::unique_ptr MassAttachItems_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +MassAttachItems::MassAttachItems() + : GO_HOME_WHEN_DONE(false) + , ITEM_CATEGORY( + "Item Category:", + { + {ItemCategory::Medicines, "medicine", "Medicines"}, + {ItemCategory::PokeBalls, "balls", "Pok\u00e9 Balls"}, + {ItemCategory::BattleItems, "battle", "Battle Items"}, + {ItemCategory::Berries, "berries", "Berries"}, + {ItemCategory::OtherItems, "other", "Other Items"}, + {ItemCategory::TMs, "tms", "TMs"}, + {ItemCategory::Treasures, "treasures", "Treasures"}, + }, + LockMode::LOCK_WHILE_RUNNING, + ItemCategory::PokeBalls + ) + , BOXES( + "Number of Boxes to Attach:", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 0, 32 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(ITEM_CATEGORY); + PA_ADD_OPTION(BOXES); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void MassAttachItems::attach_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MassAttachItems_Descriptor::Stats& stats = env.current_stats(); + + env.log("Selecting " + STRING_POKEMON + "..."); + + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + BoxCurrentEggDetector egg_detector; + VideoOverlaySet overlays(env.console.overlay()); + sth_in_box_detector.make_overlays(overlays); + egg_detector.make_overlays(overlays); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + + if (!sth_in_box_detector.detect(screen)){ + stats.m_empty++; + return; + } + + if (egg_detector.detect(screen)){ + stats.m_eggs++; + return; + } + + try{ + size_t errors = 0; + attach_item_from_box(env.program_info(), env.console, context, (size_t)ITEM_CATEGORY.get(), errors); + stats.m_attached++; + stats.m_errors += errors; + }catch (OperationFailedException&){ + stats.m_errors++; + throw; + } +} +void MassAttachItems::attach_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + for (uint8_t row = 0; row < 5; row++){ + for (uint8_t j_col = 0; j_col < 6; j_col++){ + // Go through slots in a Z-shape pattern + uint8_t col = (row % 2 == 0 ? j_col : 5 - j_col); + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); + attach_one(box_detector, env, context); + env.update_stats(); + } + } +} + + + +void MassAttachItems::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + MassAttachItems_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 10, 0); + + BoxDetector box_detector; + VideoOverlaySet overlays(env.console.overlay()); + box_detector.make_overlays(overlays); + + for (uint8_t box = 0; box < BOXES; box++){ + if (box > 0){ + move_to_right_box(context); + } + context.wait_for_all_requests(); + + env.update_stats(); + + attach_box(box_detector, env, context); + + stats.m_boxes++; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.h b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.h index 3e478e4901..9098ffe66d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassAttachItems.h @@ -1,66 +1,66 @@ -/* Mass Attach Items - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MassAttachItems_H -#define PokemonAutomation_PokemonSV_MassAttachItems_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class BoxDetector; - - -class MassAttachItems_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MassAttachItems_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class MassAttachItems : public SingleSwitchProgramInstance{ -public: - MassAttachItems(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void attach_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void attach_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - enum class ItemCategory{ - Medicines, - PokeBalls, - BattleItems, - Berries, - OtherItems, - TMs, - Treasures, - }; - EnumDropdownOption ITEM_CATEGORY; - - SimpleIntegerOption BOXES; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Mass Attach Items + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MassAttachItems_H +#define PokemonAutomation_PokemonSV_MassAttachItems_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class BoxDetector; + + +class MassAttachItems_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MassAttachItems_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class MassAttachItems : public SingleSwitchProgramInstance{ +public: + MassAttachItems(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void attach_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void attach_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + enum class ItemCategory{ + Medicines, + PokeBalls, + BattleItems, + Berries, + OtherItems, + TMs, + Treasures, + }; + EnumDropdownOption ITEM_CATEGORY; + + SimpleIntegerOption BOXES; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.cpp b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.cpp index d823480c6a..22ed44374c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.cpp @@ -1,206 +1,206 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h" -#include "PokemonSV_MassRelease.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -MassRelease_Descriptor::MassRelease_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:MassRelease", - STRING_POKEMON + " SV", "Mass Release", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MassRelease.md", - "Mass release boxes of " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct MassRelease_Descriptor::Stats : public StatsTracker{ - Stats() - : m_boxes(m_stats["Boxes Cleared"]) - , m_released(m_stats["Released"]) - , m_empty(m_stats["Empty Slots"]) - , m_shinies(m_stats["Shinies"]) - , m_eggs(m_stats["Eggs"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Boxes Cleared"); - m_display_order.emplace_back("Released"); - m_display_order.emplace_back("Empty Slots"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Eggs"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_boxes; - std::atomic& m_released; - std::atomic& m_empty; - std::atomic& m_shinies; - std::atomic& m_eggs; - std::atomic& m_errors; -}; -std::unique_ptr MassRelease_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -MassRelease::MassRelease() - : GO_HOME_WHEN_DONE(false) - , BOXES_TO_RELEASE( - "Number of Boxes to Release:", - LockMode::UNLOCK_WHILE_RUNNING, - 2, 0, 32 - ) - , SKIP_SHINIES( - "Skip Shinies:
Do not release shiny " + STRING_POKEMON + ".", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, -// &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(BOXES_TO_RELEASE); - PA_ADD_OPTION(SKIP_SHINIES); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - - - - -void MassRelease::release_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - MassRelease_Descriptor::Stats& stats = env.current_stats(); - - env.log("Selecting " + STRING_POKEMON + "..."); - - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - BoxCurrentEggDetector egg_detector; - BoxShinyDetector shiny_detector; - VideoOverlaySet overlays(env.console.overlay()); - sth_in_box_detector.make_overlays(overlays); - egg_detector.make_overlays(overlays); - shiny_detector.make_overlays(overlays); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - - if (!sth_in_box_detector.detect(screen)){ - stats.m_empty++; - return; - } - - // Try to change to stats or judge view - if (m_in_judge_view == false){ - const bool throw_exception = false; - if (change_view_to_stats_or_judge(env.console, context, throw_exception)){ - m_in_judge_view = true; - }else{ - // it is an egg - stats.m_eggs++; - return; - } - screen = env.console.video().snapshot(); - } - - if (egg_detector.detect(screen)){ - stats.m_eggs++; - return; - } - - if (shiny_detector.detect(screen)){ - stats.m_shinies++; - if (SKIP_SHINIES){ - return; - } - } - - try{ - size_t errors = 0; - release_one_pokemon(env.program_info(), env.console, context, errors); - stats.m_released++; - stats.m_errors += errors; - }catch (OperationFailedException&){ - stats.m_errors++; - throw; - } -} -void MassRelease::release_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - for (uint8_t row = 0; row < 5; row++){ - for (uint8_t j_col = 0; j_col < 6; j_col++){ - // Go through slots in a Z-shape pattern - uint8_t col = (row % 2 == 0 ? j_col : 5 - j_col); - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); - release_one(box_detector, env, context); - env.update_stats(); - } - } -} - - - -void MassRelease::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - MassRelease_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 10, 0); - - m_in_judge_view = false; - - BoxDetector box_detector; - VideoOverlaySet overlays(env.console.overlay()); - box_detector.make_overlays(overlays); - - for (uint8_t box = 0; box < BOXES_TO_RELEASE; box++){ - if (box > 0){ - move_to_right_box(context); - } - context.wait_for_all_requests(); - - env.update_stats(); - - release_box(box_detector, env, context); - - stats.m_boxes++; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - -} -} -} +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h" +#include "PokemonSV_MassRelease.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +MassRelease_Descriptor::MassRelease_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:MassRelease", + STRING_POKEMON + " SV", "Mass Release", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MassRelease.md", + "Mass release boxes of " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct MassRelease_Descriptor::Stats : public StatsTracker{ + Stats() + : m_boxes(m_stats["Boxes Cleared"]) + , m_released(m_stats["Released"]) + , m_empty(m_stats["Empty Slots"]) + , m_shinies(m_stats["Shinies"]) + , m_eggs(m_stats["Eggs"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Boxes Cleared"); + m_display_order.emplace_back("Released"); + m_display_order.emplace_back("Empty Slots"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Eggs"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_boxes; + std::atomic& m_released; + std::atomic& m_empty; + std::atomic& m_shinies; + std::atomic& m_eggs; + std::atomic& m_errors; +}; +std::unique_ptr MassRelease_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +MassRelease::MassRelease() + : GO_HOME_WHEN_DONE(false) + , BOXES_TO_RELEASE( + "Number of Boxes to Release:", + LockMode::UNLOCK_WHILE_RUNNING, + 2, 0, 32 + ) + , SKIP_SHINIES( + "Skip Shinies:
Do not release shiny " + STRING_POKEMON + ".", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, +// &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(BOXES_TO_RELEASE); + PA_ADD_OPTION(SKIP_SHINIES); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + + + + +void MassRelease::release_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + MassRelease_Descriptor::Stats& stats = env.current_stats(); + + env.log("Selecting " + STRING_POKEMON + "..."); + + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + BoxCurrentEggDetector egg_detector; + BoxShinyDetector shiny_detector; + VideoOverlaySet overlays(env.console.overlay()); + sth_in_box_detector.make_overlays(overlays); + egg_detector.make_overlays(overlays); + shiny_detector.make_overlays(overlays); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + + if (!sth_in_box_detector.detect(screen)){ + stats.m_empty++; + return; + } + + // Try to change to stats or judge view + if (m_in_judge_view == false){ + const bool throw_exception = false; + if (change_view_to_stats_or_judge(env.console, context, throw_exception)){ + m_in_judge_view = true; + }else{ + // it is an egg + stats.m_eggs++; + return; + } + screen = env.console.video().snapshot(); + } + + if (egg_detector.detect(screen)){ + stats.m_eggs++; + return; + } + + if (shiny_detector.detect(screen)){ + stats.m_shinies++; + if (SKIP_SHINIES){ + return; + } + } + + try{ + size_t errors = 0; + release_one_pokemon(env.program_info(), env.console, context, errors); + stats.m_released++; + stats.m_errors += errors; + }catch (OperationFailedException&){ + stats.m_errors++; + throw; + } +} +void MassRelease::release_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + for (uint8_t row = 0; row < 5; row++){ + for (uint8_t j_col = 0; j_col < 6; j_col++){ + // Go through slots in a Z-shape pattern + uint8_t col = (row % 2 == 0 ? j_col : 5 - j_col); + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); + release_one(box_detector, env, context); + env.update_stats(); + } + } +} + + + +void MassRelease::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + MassRelease_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 10, 0); + + m_in_judge_view = false; + + BoxDetector box_detector; + VideoOverlaySet overlays(env.console.overlay()); + box_detector.make_overlays(overlays); + + for (uint8_t box = 0; box < BOXES_TO_RELEASE; box++){ + if (box > 0){ + move_to_right_box(context); + } + context.wait_for_all_requests(); + + env.update_stats(); + + release_box(box_detector, env, context); + + stats.m_boxes++; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.h b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.h index 181a9b5831..07a42361a7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Boxes/PokemonSV_MassRelease.h @@ -1,58 +1,58 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MassRelease_H -#define PokemonAutomation_PokemonSV_MassRelease_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class BoxDetector; - - -class MassRelease_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MassRelease_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class MassRelease : public SingleSwitchProgramInstance{ -public: - MassRelease(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void release_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void release_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption BOXES_TO_RELEASE; - BooleanCheckBoxOption SKIP_SHINIES; - EventNotificationsOption NOTIFICATIONS; - - // Whether the box system view is judege or stats. - bool m_in_judge_view = false; -}; - - - -} -} -} -#endif +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MassRelease_H +#define PokemonAutomation_PokemonSV_MassRelease_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class BoxDetector; + + +class MassRelease_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MassRelease_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class MassRelease : public SingleSwitchProgramInstance{ +public: + MassRelease(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void release_one(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void release_box(BoxDetector& box_detector, SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption BOXES_TO_RELEASE; + BooleanCheckBoxOption SKIP_SHINIES; + EventNotificationsOption NOTIFICATIONS; + + // Whether the box system view is judege or stats. + bool m_in_judge_view = false; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp index b071f455d2..7a75fad2e2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.cpp @@ -1,739 +1,739 @@ -/* Egg Autonomous - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -//#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV_EggAutonomous.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -EggAutonomous_Descriptor::EggAutonomous_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:EggAutonomous", - STRING_POKEMON + " SV", "Egg Autonomous", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggAutonomous.md", - "Automatically get meal power, fetch eggs from a picnic and hatch them.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct EggAutonomous_Descriptor::Stats : public StatsTracker{ - Stats() - : m_sandwiches(m_stats["Sandwiches"]) - , m_fetch_attempts(m_stats["Fetch Attempts"]) - , m_eggs(m_stats["Eggs"]) - , m_hatched(m_stats["Hatched"]) - , m_shinies(m_stats["Shinies"]) - , m_kept(m_stats["Kept"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Sandwiches"); - m_display_order.emplace_back("Fetch Attempts"); - m_display_order.emplace_back("Eggs"); - m_display_order.emplace_back("Hatched"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Kept"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - - m_aliases.emplace(STRING_POKEMON + " Kept", "Kept"); - } - - std::atomic& m_sandwiches; - std::atomic& m_fetch_attempts; - std::atomic& m_eggs; - std::atomic& m_hatched; - std::atomic& m_shinies; - std::atomic& m_kept; - std::atomic& m_errors; -}; -std::unique_ptr EggAutonomous_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -EggAutonomous::EggAutonomous() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , MAX_KEEPERS( - "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " - "The program will put them into a box neighboring the current box.", - LockMode::UNLOCK_WHILE_RUNNING, - 10, 1, 30 - ) - , AUTO_SAVING( - "Auto-Saving:
Automatically save the game to recover from crashes and allow eggs to be unhatched.
" + - make_text_url( - ONLINE_DOC_URL_BASE + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggAutonomous.md#auto-saving-mode", - "See the wiki for the full explanations of each mode." - ), - { - {AutoSave::NoAutoSave, "none", "No auto-saving."}, - {AutoSave::AfterStartAndKeep, "start-and-keep", "Save at beginning and after keeping a baby."}, - {AutoSave::EveryBatch, "every-batch", "Save before every batch of 4 or 5 eggs."}, - {AutoSave::AfterFetchComplete, "after-fetch", "Save after all eggs have been fetched from picnic."} - }, - LockMode::LOCK_WHILE_RUNNING, - AutoSave::AfterStartAndKeep - ) - , HAS_CLONE_RIDE_POKEMON( - "Cloned Ride Legendary 2nd in Party:
" - "Ride legendary cannot be cloned after patch 1.0.1. To preserve the existing clone while hatching eggs, " - "place it as second in party before starting the program.
" - "The program will skip the first row of the current box when storing and hatching eggs, so you will need " - "to fill the first row with " + STRING_POKEMON + " before running this program.", - LockMode::LOCK_WHILE_RUNNING, - false) - , KEEP_BOX_LOCATION( - "Location of the Keep Box:
Which box to keep the shiny " + STRING_POKEMON + " and others that match the filters.", - { - {0, "left", "Left Box"}, - {1, "right", "Right Box"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - 1 - ) - , FILTERS0( - StatsHuntIvJudgeFilterTable_Label_Eggs, - { - .action = true, - .shiny = true, - .gender = true, - .nature = true, - } - ) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:
" - "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_NONSHINY_KEEP( - "Non-Shiny Keep", - true, true, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_SHINY( - "Shiny Hatch", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , m_notification_noop("", false, false) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_NONSHINY_KEEP, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - } - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(EGG_SANDWICH); - PA_ADD_OPTION(MAX_KEEPERS); - PA_ADD_OPTION(AUTO_SAVING); - PA_ADD_OPTION(KEEP_BOX_LOCATION); - PA_ADD_OPTION(FILTERS0); - PA_ADD_OPTION(HAS_CLONE_RIDE_POKEMON); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 100); - - { - // reset_position_to_flying_spot(env, context); - // picnic_party_to_hatch_party(env, context); - // hatch_eggs_full_routine(env, context, -1); - - // enter_box_system_from_overworld(env.program_info(), env.console, context); - // for(int i = 0; i < 5; i++){ - // process_one_baby(env, context, i, 5); - // } - - // eat_egg_sandwich_at_picnic(env.program_info(), env.normal_inference_dispatcher(), env.console, context, - // EGG_SANDWICH_TYPE, SWEET_HERB_INDEX_BACKWARDS.current_value()); - // return; - } - - if (AUTO_SAVING != AutoSave::NoAutoSave){ - save_game(env, context, true); - } - - const size_t max_num_sandwiches = EGG_SANDWICH.MAX_NUM_SANDWICHES; - m_num_sandwich_spent = 0; - m_num_kept = 0; - size_t consecutive_failures = 0; - while(true){ - m_saved_after_fetched_eggs = false; - m_in_critical_to_save_stage = false; - - // Do one iteration of the outmost loop of egg auto: - // - Start at Aera Zero flying spot - // - Go to front area of the observation station to start picnic - // - Make sandwich to gain egg power - // - Go to picnic basket to fetch eggs - // - Go on ride to hatch eggs - - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // Recoverable loop to fetch eggs: - int num_party_eggs = -1; - while(true){ - try{ - num_party_eggs = fetch_eggs_full_routine(env, context); - break; - }catch (OperationFailedException& e){ - handle_recoverable_error(env, context, NOTIFICATION_ERROR_RECOVERABLE, e, consecutive_failures); - } // end try catch - } // end recoverable loop to fetch eggs: - - // Recoverable loop to hatch eggs - bool game_already_resetted = false; - while(true){ - try{ - hatch_eggs_full_routine(env, context, num_party_eggs); - consecutive_failures = 0; - break; - }catch (OperationFailedException& e){ - handle_recoverable_error(env, context, NOTIFICATION_ERROR_RECOVERABLE, e, consecutive_failures); - // After resetting the game, we don't know how many eggs in party - num_party_eggs = -1; - - // If there is no save during egg hatching, then the game is reset to before fetching eggs - // So we need to break out of the recoverable hatch egg routine loop - if (m_saved_after_fetched_eggs == false){ - env.log("No save during egg hatching routine. After this reset, we should start the egg fetching routine now."); - game_already_resetted = true; - break; - } - }catch (ProgramFinishedException&){ - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - return; - } // end try catch - } // end recoverable loop to hatch eggs - - // If the program can't save-reload, then we cannot reload spent sandwich ingredients - if (AUTO_SAVING == AutoSave::NoAutoSave){ - m_num_sandwich_spent++; - }else if (m_saved_after_fetched_eggs){ - env.log("Game already saved during egg hatching routine, so we cannot reset game to reset sandwich."); - // If we save after fetching eggs, then the save solidifies spent sandwich ingredients. - m_num_sandwich_spent++; - - env.log("Saving game here so that we can reset sandwich later"); - save_game(env, context, true); - }else if (game_already_resetted == false){ - // Nothing found in this iteration - env.log("Resetting game since nothing found, saving sandwich ingredients."); - reset_game(env.program_info(), env.console, context); - }else{ // game_already_resetted == true - env.log("Game reset back to egg fetching routine."); - } - - if (m_num_sandwich_spent >= max_num_sandwiches){ - env.console.overlay().add_log("Max sandwich count: " + std::to_string(max_num_sandwiches), COLOR_PURPLE); - env.log("Max num sandwiches reached: " + std::to_string(max_num_sandwiches), COLOR_PURPLE); - break; - } - // end of one full picnic->hatch iteration - } // end the full egg autonomous loop - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -// start at Area Zero flying spot, start picnic, make sandwich, then fetch eggs at basket. -int EggAutonomous::fetch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - auto& stats = env.current_stats(); - - picnic_at_zero_gate(env.program_info(), env.console, context); - // Now we are at picnic. We are at one end of picnic table while the egg basket is at the other end - bool can_make_sandwich = eat_egg_sandwich_at_picnic(env, env.console, context, - EGG_SANDWICH.EGG_SANDWICH_TYPE, LANGUAGE); - if (can_make_sandwich == false){ - throw UserSetupError(env.console, "No sandwich recipe or ingredients. Cannot open and select the sandwich recipe."); - } - env.current_stats().m_sandwiches++; - env.update_stats(); - - // move past the table and collect eggs - auto basket_check_callback = [&](size_t new_eggs){ - stats.m_fetch_attempts++; - stats.m_eggs += new_eggs; - env.update_stats(); - }; - - const size_t max_eggs = HAS_CLONE_RIDE_POKEMON ? 24 : 30; - size_t num_eggs_collected = 0; - const size_t basket_wait_seconds = (EGG_SANDWICH.EGG_SANDWICH_TYPE == EggSandwichType::GREAT_PEANUT_BUTTER ? 180 : 120); - collect_eggs_after_sandwich(env.program_info(), env.console, context, basket_wait_seconds, max_eggs, - num_eggs_collected, basket_check_callback); - - leave_picnic(env.program_info(), env.console, context); - - // Reset position to flying spot: - reset_position_to_flying_spot(env, context); - - return picnic_party_to_hatch_party(env, context); -} - -// The routine to hatch a box of eggs after fetching. -// When there is an error during hatching, it will throw an OperationFailedException. -// The outmost program loop should catch this exception and recall this function to achieve error recovery, if needed. -// When immediately called after fetching routine finishes, assumes the party is already loaded with the first column of -// eggs and the number of eggs is provided by `num_eggs_in_party`. -// When called after an error recovery, assumes the party is loaded with some unknown number of eggs, and `num_eggs_in_party` is -1. -void EggAutonomous::hatch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int num_eggs_in_party){ - auto& stats = env.current_stats(); - - // index of the egg column in box to be loaded next, 0-indexed - // starting at 1 because when hatch_eggs_full_routine() is called, the first column is already loaded to the party - uint8_t next_egg_column = 1; - - // Find the next egg column in the current box. - // Note: the box columns can be: - // - empty. This is due to the column loaded to party, or released in the case of AutoSaving != AfterStartAndKeep. - // - egg column. - // - hatched pokemon. This only happens in the case of AutoSaving == AfterStartAndKeep. - // To handle all AutoSaving cases, we cannot only use `SomethingInBoxSlotDetector` to find the column, but also need - // `BoxCurrentEggDetector`. - // This function is called in two cases: - // 1. When we recover from error and don't know which column is the next egg column. - // In this case, `change_stats_view_to_judge()` is called as part of the error recovery code before this function, - // so that `BoxCurrentEggDetector` in this function can function correctly to find that the egg column. - // 2. When we finish processing one hatched party and want to load the next egg column. - // In this case, `next_egg_column` already point to the next possible column, that cannot be hatched pokemon. - // So we don't need to call egg detector and don't need to worry about setting box views. - auto go_to_next_egg_column = [&](bool check_eggs = false){ - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - BoxCurrentEggDetector egg_detector; - for (; next_egg_column < 6; next_egg_column++){ - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, HAS_CLONE_RIDE_POKEMON ? 1 : 0, next_egg_column); - context.wait_for_all_requests(); - auto snapshot = env.console.video().snapshot(); - // If there is an egg in slot row 0 (or 1 if using clone ride pokemon), col `col`, - if (sth_in_box_detector.detect(snapshot) && (!check_eggs || egg_detector.detect(snapshot))){ - env.log("Found next column of eggs at col " + std::to_string(next_egg_column) + "."); - break; - } - } - }; - - if (num_eggs_in_party < 0){ - // detect how many eggs in party - enter_box_system_from_overworld(env.program_info(), env.console, context); - - context.wait_for(std::chrono::milliseconds(400)); // wait until box UI is loaded - - // Move box cursor to party lead - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); - - // Change box view to judge or stats - Language language = LANGUAGE; - if (language == Language::None){ - change_view_to_stats_or_judge(env.console, context); - }else{ - change_view_to_judge(env.console, context, language); - } - - const uint8_t expected_non_eggs_count_in_party = HAS_CLONE_RIDE_POKEMON ? 1 : 0; - num_eggs_in_party = check_non_eggs_count_in_party(env.program_info(), env.console, context, expected_non_eggs_count_in_party); - env.log("Read " + std::to_string(num_eggs_in_party) + " eggs."); - env.console.overlay().add_log("Party eggs: " + std::to_string(num_eggs_in_party), COLOR_WHITE); - - // Also detect what's the next egg column - context.wait_for(std::chrono::seconds(2)); // wait until box UI is definitely loaded - env.log("Checking next egg column."); - go_to_next_egg_column(true); - - leave_box_system_to_overworld(env.program_info(), env.console, context); - } - - auto save_game_if_needed = [&](){ - if (AUTO_SAVING == AutoSave::EveryBatch || - (AUTO_SAVING == AutoSave::AfterFetchComplete && m_saved_after_fetched_eggs == false) || - (AUTO_SAVING == AutoSave::AfterStartAndKeep && m_in_critical_to_save_stage)){ - env.log("Saving game during egg hatching routine."); - save_game(env, context, true); - m_saved_after_fetched_eggs = true; - m_in_critical_to_save_stage = false; - } - }; - - // The loop to hatch batches of eggs. - // Each batch consists of at most five eggs. - // There are at most six batches of eggs in a box. - while(true){ - save_game_if_needed(); - - auto hatched_callback = [&](uint8_t){ - stats.m_hatched++; - env.update_stats(); - }; - hatch_eggs_at_zero_gate(env.program_info(), env.console, context, (uint8_t)num_eggs_in_party, hatched_callback); - reset_position_to_flying_spot(env, context); - - enter_box_system_from_overworld(env.program_info(), env.console, context); - - // Check each hatched baby whether they will be kept. - // If yes, move them to the keep box. - // Otherwise, release them or move them into box in case we will reset game later. - for(uint8_t i = 0; i < num_eggs_in_party; i++){ - process_one_baby(env, context, i, (uint8_t)num_eggs_in_party); - } - - // If the auto save mode is AfterStartAndKeep, which allows resetting the game in case no eggs in the box are kept, - // then we can save the time of releasing hatched pokemon in case we will reset the game later. - // So here we place the hatched pokemon back to the box - if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ - // move party back into the box - env.log("Unload party in case we will reset game later to save releasing time."); - unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, next_egg_column-1, HAS_CLONE_RIDE_POKEMON); - } - - // Get the next egg column - go_to_next_egg_column(); - - if (next_egg_column < 6){ - load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, next_egg_column, HAS_CLONE_RIDE_POKEMON); - // Move cursor to party lead so that we can examine rest of party to detect eggs. - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); - - uint8_t expected_non_eggs_count_in_party = HAS_CLONE_RIDE_POKEMON ? 1 : 0; - num_eggs_in_party = check_non_eggs_count_in_party(env.program_info(), env.console, context, expected_non_eggs_count_in_party); - }else{ - // no more eggs to hatch in box - - if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ - // Check if we will reset game: - // We reset game if the auto save mode is AfterStartAndKeep and we have no pokemon kept during hatching this box - // m_in_critical_to_save_stage: whether we need to save the game for the current batch of eggs - // m_saved_after_fetched_eggs: whether we have saved the game already for a past batch of eggs in this box - if (m_in_critical_to_save_stage == false && m_saved_after_fetched_eggs == false){ - // Yes, we will reset game - // So exit this loop early here - env.log("Early exit of egg hatching routine to reset game."); - return; - } - - // release the hatched pokemon in box - size_t local_errors = 0; - release_box( - env.program_info(), env.console, context, local_errors, - HAS_CLONE_RIDE_POKEMON ? 1 : 0 - ); - } - - // change to fetching mode: - env.log("Replace party with picnic team"); - env.console.overlay().add_log("Change to picnic pokemon", COLOR_WHITE); - - // Move to left box - move_to_left_box(context); - - // Swap the party lead, the flame body pokemon with the stored first fetching pokemon - swap_two_box_slots(env.program_info(), env.console, context, - BoxCursorLocation::PARTY, 0, 0, - BoxCursorLocation::SLOTS, 0, 0); - - // Load rest of the fetching pokemon to party - load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, 1, HAS_CLONE_RIDE_POKEMON); - - // Move back to middle box - move_to_right_box(context); - } - - leave_box_system_to_overworld(env.program_info(), env.console, context); - - if (next_egg_column == 6){ // no more eggs to hatch - break; // break egg batch loop. This is the only place to break out of the loop - } - next_egg_column++; - } // end egg batch loop - - save_game_if_needed(); -} - -// While in box system and the current box is egg box, process one baby pokemon in party -// Return true if the program finds a pokemon to keep -void EggAutonomous::process_one_baby(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t egg_index, uint8_t num_eggs_in_party){ - auto& stats = env.current_stats(); - - // Check each pokemon from bottom to top. In this way we can reliably detect end of releasing the pokemon. - uint8_t party_row = num_eggs_in_party - egg_index + (HAS_CLONE_RIDE_POKEMON ? 1 : 0); - context.wait_for_all_requests(); - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, party_row, 0); - - env.log("Check hatched pokemon at party slot " + std::to_string(party_row)); - - bool found_shiny = false; - StatsHuntAction action = StatsHuntAction::Discard; - if (check_baby_info(env.program_info(), env.console, context, LANGUAGE, FILTERS0, action)){ - found_shiny = true; - env.console.log("Shiny found!"); - env.console.overlay().add_log("Shiny " + std::to_string(egg_index+1) + "/" + std::to_string(num_eggs_in_party), COLOR_GREEN); - stats.m_shinies++; - env.update_stats(); - send_encounter_notification( - env, - m_notification_noop, - NOTIFICATION_SHINY, - false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), - env.console.video().snapshot() - ); - }else{ - env.console.overlay().add_log("Not shiny " + std::to_string(egg_index+1) + "/" + std::to_string(num_eggs_in_party), COLOR_WHITE); - } - - auto send_keep_notification = [&](){ - if (!found_shiny){ - send_encounter_notification( - env, - NOTIFICATION_NONSHINY_KEEP, - NOTIFICATION_SHINY, - false, false, {}, std::nan(""), - env.console.video().snapshot() - ); - } - }; - - switch (action){ - case StatsHuntAction::StopProgram: - env.log("Program stop requested..."); - env.console.overlay().add_log("Request program stop", COLOR_WHITE); - send_keep_notification(); - throw ProgramFinishedException(); - case StatsHuntAction::Keep: - m_in_critical_to_save_stage = true; - env.log("Moving Pokemon to keep box...", COLOR_BLUE); - stats.m_kept++; - env.update_stats(); - m_num_kept++; - env.console.overlay().add_log("Keep pokemon " + std::to_string(m_num_kept) + "/" + std::to_string(MAX_KEEPERS), COLOR_YELLOW); - send_keep_notification(); - - if (move_pokemon_to_keep(env, context, party_row) == false){ - env.log("No empty slot available to place new pokemon."); - env.console.overlay().add_log("No box space", COLOR_RED); - throw ProgramFinishedException(); - } - - if (m_num_kept >= MAX_KEEPERS){ - env.log("Max keepers reached. Stopping program..."); - env.console.overlay().add_log("Max Keepers reached", COLOR_WHITE); - throw ProgramFinishedException(); - } - break; - - case StatsHuntAction::Discard: - default: - // If the auto save mode is AfterStartAndKeep, which allows resetting the game in case no eggs in the box are kept, - // then we can save the time of releasing hatched pokemon in case we will reset the game later. - // Otherwise, release the pokemon now. - if (AUTO_SAVING != AutoSave::AfterStartAndKeep){ - size_t local_errors = 0; - release_one_pokemon(env.program_info(), env.console, context, local_errors); - } - break; - } // end switch EggHatchAction -} - -// From the egg box, move to the kept box, drop the pokemon to an empty spot in the box, move back to the egg box. -// Return false if it does not find an empty spot. -bool EggAutonomous::move_pokemon_to_keep(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pokemon_row_in_party){ - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - const size_t keep_box_location = KEEP_BOX_LOCATION.current_value(); - if (keep_box_location == 0){ - move_to_left_box(context); - }else{ - move_to_right_box(context); - } - - context.wait_for_all_requests(); - - const uint8_t col_start = (keep_box_location == 0 ? 2 : 0); - for (uint8_t row = 0; row < 5; row++){ - for (uint8_t col = col_start; col < 6; col++){ - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); - context.wait_for_all_requests(); - // If no pokemon in the slot: - if (!sth_in_box_detector.detect(env.console.video().snapshot())){ - - // Move the to-keep pokemon in party to the empty slot. - swap_two_box_slots(env.program_info(), env.console, context, - BoxCursorLocation::PARTY, pokemon_row_in_party, 0, - BoxCursorLocation::SLOTS, row, col); - - // Move back to middle box - if (keep_box_location == 0){ - move_to_right_box(context); - }else{ - move_to_left_box(context); - } - context.wait_for_all_requests(); - return true; - } - } - } - return false; -} - -void EggAutonomous::reset_position_to_flying_spot(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Use map to fly back to the flying spot - open_map_from_overworld(env.program_info(), env.console, context); - pbf_move_left_joystick(context, 128, 160, 20, 50); - fly_to_overworld_from_map(env.program_info(), env.console, context); -} - -// From overworld, change pokemon party from the one used for getting eggs, to the one used for hatching -// The new party will be one flame body pokemon as lead, and some eggs. -// Function returns how many eggs are in the party -int EggAutonomous::picnic_party_to_hatch_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - env.console.overlay().add_log("Change to hatching", COLOR_WHITE); - // change pokemon party from used for fetching eggs in picnic, to hatching on your ride. - - enter_box_system_from_overworld(env.program_info(), env.console, context); - - // Move to left box - move_to_left_box(context); - - // Swap the stored the flame body pokemon with the stored first fetching pokemon - swap_two_box_slots(env.program_info(), env.console, context, - BoxCursorLocation::SLOTS, 0, 0, - BoxCursorLocation::PARTY, 0, 0); - - // Unload rest of party to the 2nd column (col 1) in box - unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, 1, HAS_CLONE_RIDE_POKEMON); - - // Move to middle box - move_to_right_box(context); - - // Load first egg column to party - load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, 0, HAS_CLONE_RIDE_POKEMON); - // Move cursor to party lead so that we can examine rest of party to detect eggs. - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); - - uint8_t expected_non_eggs_count_in_party = HAS_CLONE_RIDE_POKEMON ? 1 : 0; - const uint8_t num_eggs_in_party = check_non_eggs_count_in_party(env.program_info(), env.console, context, expected_non_eggs_count_in_party); - - leave_box_system_to_overworld(env.program_info(), env.console, context); - - return num_eggs_in_party; -} - - -void EggAutonomous::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool from_overworld){ - try{ - if (from_overworld){ - save_game_from_overworld(env.program_info(), env.console, context); - }else{ - save_game_from_menu(env.program_info(), env.console, context); - } - }catch (OperationFailedException& e){ - // To be safe: avoid interrupting or corrupting game saving, - // make game saving non error recoverable - throw FatalProgramException(std::move(e)); - } -} - - -void EggAutonomous::handle_recoverable_error( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - EventNotificationOption& notification, - OperationFailedException& e, - size_t& consecutive_failures -){ - auto& stats = env.current_stats(); - stats.m_errors++; - env.update_stats(); - e.send_notification(env, notification); - - if (SAVE_DEBUG_VIDEO){ - // Take a video to give more context for debugging - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - // if there is no auto save, then we shouldn't reset game to lose previous progress. - if (AUTO_SAVING == AutoSave::NoAutoSave){ - throw std::move(e); - } - - if (AUTO_SAVING == AutoSave::AfterStartAndKeep && m_in_critical_to_save_stage){ - // We have found a pokemon to keep, but before we can save the game to protect the pokemon, an error occurred. - // To not lose the pokemon, don't reset. - // Note: if AUTO_SAVING == AutoSave::EveryBatch, then we don't need to care about this critical stage, because - // in this auto saving mode, every batch of eggs have been saved beforehand. - env.log("Found an error before we can save the game to protect the newly kept pokemon.", COLOR_RED); - env.log("Don't reset game to protect it.", COLOR_RED); - throw std::move(e); - } - - consecutive_failures++; - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 times in the row.", - env.console - ); - } - - env.log("Reset game to handle recoverable error"); - reset_game(env.program_info(), env.console, context); -} - - -} -} -} +/* Egg Autonomous + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +//#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV_EggAutonomous.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +EggAutonomous_Descriptor::EggAutonomous_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:EggAutonomous", + STRING_POKEMON + " SV", "Egg Autonomous", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggAutonomous.md", + "Automatically get meal power, fetch eggs from a picnic and hatch them.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct EggAutonomous_Descriptor::Stats : public StatsTracker{ + Stats() + : m_sandwiches(m_stats["Sandwiches"]) + , m_fetch_attempts(m_stats["Fetch Attempts"]) + , m_eggs(m_stats["Eggs"]) + , m_hatched(m_stats["Hatched"]) + , m_shinies(m_stats["Shinies"]) + , m_kept(m_stats["Kept"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Sandwiches"); + m_display_order.emplace_back("Fetch Attempts"); + m_display_order.emplace_back("Eggs"); + m_display_order.emplace_back("Hatched"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Kept"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + + m_aliases.emplace(STRING_POKEMON + " Kept", "Kept"); + } + + std::atomic& m_sandwiches; + std::atomic& m_fetch_attempts; + std::atomic& m_eggs; + std::atomic& m_hatched; + std::atomic& m_shinies; + std::atomic& m_kept; + std::atomic& m_errors; +}; +std::unique_ptr EggAutonomous_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +EggAutonomous::EggAutonomous() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , MAX_KEEPERS( + "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " + "The program will put them into a box neighboring the current box.", + LockMode::UNLOCK_WHILE_RUNNING, + 10, 1, 30 + ) + , AUTO_SAVING( + "Auto-Saving:
Automatically save the game to recover from crashes and allow eggs to be unhatched.
" + + make_text_url( + ONLINE_DOC_URL_BASE + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggAutonomous.md#auto-saving-mode", + "See the wiki for the full explanations of each mode." + ), + { + {AutoSave::NoAutoSave, "none", "No auto-saving."}, + {AutoSave::AfterStartAndKeep, "start-and-keep", "Save at beginning and after keeping a baby."}, + {AutoSave::EveryBatch, "every-batch", "Save before every batch of 4 or 5 eggs."}, + {AutoSave::AfterFetchComplete, "after-fetch", "Save after all eggs have been fetched from picnic."} + }, + LockMode::LOCK_WHILE_RUNNING, + AutoSave::AfterStartAndKeep + ) + , HAS_CLONE_RIDE_POKEMON( + "Cloned Ride Legendary 2nd in Party:
" + "Ride legendary cannot be cloned after patch 1.0.1. To preserve the existing clone while hatching eggs, " + "place it as second in party before starting the program.
" + "The program will skip the first row of the current box when storing and hatching eggs, so you will need " + "to fill the first row with " + STRING_POKEMON + " before running this program.", + LockMode::LOCK_WHILE_RUNNING, + false) + , KEEP_BOX_LOCATION( + "Location of the Keep Box:
Which box to keep the shiny " + STRING_POKEMON + " and others that match the filters.", + { + {0, "left", "Left Box"}, + {1, "right", "Right Box"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + 1 + ) + , FILTERS0( + StatsHuntIvJudgeFilterTable_Label_Eggs, + { + .action = true, + .shiny = true, + .gender = true, + .nature = true, + } + ) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:
" + "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_NONSHINY_KEEP( + "Non-Shiny Keep", + true, true, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_SHINY( + "Shiny Hatch", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , m_notification_noop("", false, false) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_NONSHINY_KEEP, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + } + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(EGG_SANDWICH); + PA_ADD_OPTION(MAX_KEEPERS); + PA_ADD_OPTION(AUTO_SAVING); + PA_ADD_OPTION(KEEP_BOX_LOCATION); + PA_ADD_OPTION(FILTERS0); + PA_ADD_OPTION(HAS_CLONE_RIDE_POKEMON); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 100); + + { + // reset_position_to_flying_spot(env, context); + // picnic_party_to_hatch_party(env, context); + // hatch_eggs_full_routine(env, context, -1); + + // enter_box_system_from_overworld(env.program_info(), env.console, context); + // for(int i = 0; i < 5; i++){ + // process_one_baby(env, context, i, 5); + // } + + // eat_egg_sandwich_at_picnic(env.program_info(), env.normal_inference_dispatcher(), env.console, context, + // EGG_SANDWICH_TYPE, SWEET_HERB_INDEX_BACKWARDS.current_value()); + // return; + } + + if (AUTO_SAVING != AutoSave::NoAutoSave){ + save_game(env, context, true); + } + + const size_t max_num_sandwiches = EGG_SANDWICH.MAX_NUM_SANDWICHES; + m_num_sandwich_spent = 0; + m_num_kept = 0; + size_t consecutive_failures = 0; + while(true){ + m_saved_after_fetched_eggs = false; + m_in_critical_to_save_stage = false; + + // Do one iteration of the outmost loop of egg auto: + // - Start at Aera Zero flying spot + // - Go to front area of the observation station to start picnic + // - Make sandwich to gain egg power + // - Go to picnic basket to fetch eggs + // - Go on ride to hatch eggs + + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // Recoverable loop to fetch eggs: + int num_party_eggs = -1; + while(true){ + try{ + num_party_eggs = fetch_eggs_full_routine(env, context); + break; + }catch (OperationFailedException& e){ + handle_recoverable_error(env, context, NOTIFICATION_ERROR_RECOVERABLE, e, consecutive_failures); + } // end try catch + } // end recoverable loop to fetch eggs: + + // Recoverable loop to hatch eggs + bool game_already_resetted = false; + while(true){ + try{ + hatch_eggs_full_routine(env, context, num_party_eggs); + consecutive_failures = 0; + break; + }catch (OperationFailedException& e){ + handle_recoverable_error(env, context, NOTIFICATION_ERROR_RECOVERABLE, e, consecutive_failures); + // After resetting the game, we don't know how many eggs in party + num_party_eggs = -1; + + // If there is no save during egg hatching, then the game is reset to before fetching eggs + // So we need to break out of the recoverable hatch egg routine loop + if (m_saved_after_fetched_eggs == false){ + env.log("No save during egg hatching routine. After this reset, we should start the egg fetching routine now."); + game_already_resetted = true; + break; + } + }catch (ProgramFinishedException&){ + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + return; + } // end try catch + } // end recoverable loop to hatch eggs + + // If the program can't save-reload, then we cannot reload spent sandwich ingredients + if (AUTO_SAVING == AutoSave::NoAutoSave){ + m_num_sandwich_spent++; + }else if (m_saved_after_fetched_eggs){ + env.log("Game already saved during egg hatching routine, so we cannot reset game to reset sandwich."); + // If we save after fetching eggs, then the save solidifies spent sandwich ingredients. + m_num_sandwich_spent++; + + env.log("Saving game here so that we can reset sandwich later"); + save_game(env, context, true); + }else if (game_already_resetted == false){ + // Nothing found in this iteration + env.log("Resetting game since nothing found, saving sandwich ingredients."); + reset_game(env.program_info(), env.console, context); + }else{ // game_already_resetted == true + env.log("Game reset back to egg fetching routine."); + } + + if (m_num_sandwich_spent >= max_num_sandwiches){ + env.console.overlay().add_log("Max sandwich count: " + std::to_string(max_num_sandwiches), COLOR_PURPLE); + env.log("Max num sandwiches reached: " + std::to_string(max_num_sandwiches), COLOR_PURPLE); + break; + } + // end of one full picnic->hatch iteration + } // end the full egg autonomous loop + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +// start at Area Zero flying spot, start picnic, make sandwich, then fetch eggs at basket. +int EggAutonomous::fetch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + auto& stats = env.current_stats(); + + picnic_at_zero_gate(env.program_info(), env.console, context); + // Now we are at picnic. We are at one end of picnic table while the egg basket is at the other end + bool can_make_sandwich = eat_egg_sandwich_at_picnic(env, env.console, context, + EGG_SANDWICH.EGG_SANDWICH_TYPE, LANGUAGE); + if (can_make_sandwich == false){ + throw UserSetupError(env.console, "No sandwich recipe or ingredients. Cannot open and select the sandwich recipe."); + } + env.current_stats().m_sandwiches++; + env.update_stats(); + + // move past the table and collect eggs + auto basket_check_callback = [&](size_t new_eggs){ + stats.m_fetch_attempts++; + stats.m_eggs += new_eggs; + env.update_stats(); + }; + + const size_t max_eggs = HAS_CLONE_RIDE_POKEMON ? 24 : 30; + size_t num_eggs_collected = 0; + const size_t basket_wait_seconds = (EGG_SANDWICH.EGG_SANDWICH_TYPE == EggSandwichType::GREAT_PEANUT_BUTTER ? 180 : 120); + collect_eggs_after_sandwich(env.program_info(), env.console, context, basket_wait_seconds, max_eggs, + num_eggs_collected, basket_check_callback); + + leave_picnic(env.program_info(), env.console, context); + + // Reset position to flying spot: + reset_position_to_flying_spot(env, context); + + return picnic_party_to_hatch_party(env, context); +} + +// The routine to hatch a box of eggs after fetching. +// When there is an error during hatching, it will throw an OperationFailedException. +// The outmost program loop should catch this exception and recall this function to achieve error recovery, if needed. +// When immediately called after fetching routine finishes, assumes the party is already loaded with the first column of +// eggs and the number of eggs is provided by `num_eggs_in_party`. +// When called after an error recovery, assumes the party is loaded with some unknown number of eggs, and `num_eggs_in_party` is -1. +void EggAutonomous::hatch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int num_eggs_in_party){ + auto& stats = env.current_stats(); + + // index of the egg column in box to be loaded next, 0-indexed + // starting at 1 because when hatch_eggs_full_routine() is called, the first column is already loaded to the party + uint8_t next_egg_column = 1; + + // Find the next egg column in the current box. + // Note: the box columns can be: + // - empty. This is due to the column loaded to party, or released in the case of AutoSaving != AfterStartAndKeep. + // - egg column. + // - hatched pokemon. This only happens in the case of AutoSaving == AfterStartAndKeep. + // To handle all AutoSaving cases, we cannot only use `SomethingInBoxSlotDetector` to find the column, but also need + // `BoxCurrentEggDetector`. + // This function is called in two cases: + // 1. When we recover from error and don't know which column is the next egg column. + // In this case, `change_stats_view_to_judge()` is called as part of the error recovery code before this function, + // so that `BoxCurrentEggDetector` in this function can function correctly to find that the egg column. + // 2. When we finish processing one hatched party and want to load the next egg column. + // In this case, `next_egg_column` already point to the next possible column, that cannot be hatched pokemon. + // So we don't need to call egg detector and don't need to worry about setting box views. + auto go_to_next_egg_column = [&](bool check_eggs = false){ + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + BoxCurrentEggDetector egg_detector; + for (; next_egg_column < 6; next_egg_column++){ + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, HAS_CLONE_RIDE_POKEMON ? 1 : 0, next_egg_column); + context.wait_for_all_requests(); + auto snapshot = env.console.video().snapshot(); + // If there is an egg in slot row 0 (or 1 if using clone ride pokemon), col `col`, + if (sth_in_box_detector.detect(snapshot) && (!check_eggs || egg_detector.detect(snapshot))){ + env.log("Found next column of eggs at col " + std::to_string(next_egg_column) + "."); + break; + } + } + }; + + if (num_eggs_in_party < 0){ + // detect how many eggs in party + enter_box_system_from_overworld(env.program_info(), env.console, context); + + context.wait_for(std::chrono::milliseconds(400)); // wait until box UI is loaded + + // Move box cursor to party lead + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); + + // Change box view to judge or stats + Language language = LANGUAGE; + if (language == Language::None){ + change_view_to_stats_or_judge(env.console, context); + }else{ + change_view_to_judge(env.console, context, language); + } + + const uint8_t expected_non_eggs_count_in_party = HAS_CLONE_RIDE_POKEMON ? 1 : 0; + num_eggs_in_party = check_non_eggs_count_in_party(env.program_info(), env.console, context, expected_non_eggs_count_in_party); + env.log("Read " + std::to_string(num_eggs_in_party) + " eggs."); + env.console.overlay().add_log("Party eggs: " + std::to_string(num_eggs_in_party), COLOR_WHITE); + + // Also detect what's the next egg column + context.wait_for(std::chrono::seconds(2)); // wait until box UI is definitely loaded + env.log("Checking next egg column."); + go_to_next_egg_column(true); + + leave_box_system_to_overworld(env.program_info(), env.console, context); + } + + auto save_game_if_needed = [&](){ + if (AUTO_SAVING == AutoSave::EveryBatch || + (AUTO_SAVING == AutoSave::AfterFetchComplete && m_saved_after_fetched_eggs == false) || + (AUTO_SAVING == AutoSave::AfterStartAndKeep && m_in_critical_to_save_stage)){ + env.log("Saving game during egg hatching routine."); + save_game(env, context, true); + m_saved_after_fetched_eggs = true; + m_in_critical_to_save_stage = false; + } + }; + + // The loop to hatch batches of eggs. + // Each batch consists of at most five eggs. + // There are at most six batches of eggs in a box. + while(true){ + save_game_if_needed(); + + auto hatched_callback = [&](uint8_t){ + stats.m_hatched++; + env.update_stats(); + }; + hatch_eggs_at_zero_gate(env.program_info(), env.console, context, (uint8_t)num_eggs_in_party, hatched_callback); + reset_position_to_flying_spot(env, context); + + enter_box_system_from_overworld(env.program_info(), env.console, context); + + // Check each hatched baby whether they will be kept. + // If yes, move them to the keep box. + // Otherwise, release them or move them into box in case we will reset game later. + for(uint8_t i = 0; i < num_eggs_in_party; i++){ + process_one_baby(env, context, i, (uint8_t)num_eggs_in_party); + } + + // If the auto save mode is AfterStartAndKeep, which allows resetting the game in case no eggs in the box are kept, + // then we can save the time of releasing hatched pokemon in case we will reset the game later. + // So here we place the hatched pokemon back to the box + if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ + // move party back into the box + env.log("Unload party in case we will reset game later to save releasing time."); + unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, next_egg_column-1, HAS_CLONE_RIDE_POKEMON); + } + + // Get the next egg column + go_to_next_egg_column(); + + if (next_egg_column < 6){ + load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, next_egg_column, HAS_CLONE_RIDE_POKEMON); + // Move cursor to party lead so that we can examine rest of party to detect eggs. + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); + + uint8_t expected_non_eggs_count_in_party = HAS_CLONE_RIDE_POKEMON ? 1 : 0; + num_eggs_in_party = check_non_eggs_count_in_party(env.program_info(), env.console, context, expected_non_eggs_count_in_party); + }else{ + // no more eggs to hatch in box + + if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ + // Check if we will reset game: + // We reset game if the auto save mode is AfterStartAndKeep and we have no pokemon kept during hatching this box + // m_in_critical_to_save_stage: whether we need to save the game for the current batch of eggs + // m_saved_after_fetched_eggs: whether we have saved the game already for a past batch of eggs in this box + if (m_in_critical_to_save_stage == false && m_saved_after_fetched_eggs == false){ + // Yes, we will reset game + // So exit this loop early here + env.log("Early exit of egg hatching routine to reset game."); + return; + } + + // release the hatched pokemon in box + size_t local_errors = 0; + release_box( + env.program_info(), env.console, context, local_errors, + HAS_CLONE_RIDE_POKEMON ? 1 : 0 + ); + } + + // change to fetching mode: + env.log("Replace party with picnic team"); + env.console.overlay().add_log("Change to picnic pokemon", COLOR_WHITE); + + // Move to left box + move_to_left_box(context); + + // Swap the party lead, the flame body pokemon with the stored first fetching pokemon + swap_two_box_slots(env.program_info(), env.console, context, + BoxCursorLocation::PARTY, 0, 0, + BoxCursorLocation::SLOTS, 0, 0); + + // Load rest of the fetching pokemon to party + load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, 1, HAS_CLONE_RIDE_POKEMON); + + // Move back to middle box + move_to_right_box(context); + } + + leave_box_system_to_overworld(env.program_info(), env.console, context); + + if (next_egg_column == 6){ // no more eggs to hatch + break; // break egg batch loop. This is the only place to break out of the loop + } + next_egg_column++; + } // end egg batch loop + + save_game_if_needed(); +} + +// While in box system and the current box is egg box, process one baby pokemon in party +// Return true if the program finds a pokemon to keep +void EggAutonomous::process_one_baby(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t egg_index, uint8_t num_eggs_in_party){ + auto& stats = env.current_stats(); + + // Check each pokemon from bottom to top. In this way we can reliably detect end of releasing the pokemon. + uint8_t party_row = num_eggs_in_party - egg_index + (HAS_CLONE_RIDE_POKEMON ? 1 : 0); + context.wait_for_all_requests(); + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, party_row, 0); + + env.log("Check hatched pokemon at party slot " + std::to_string(party_row)); + + bool found_shiny = false; + StatsHuntAction action = StatsHuntAction::Discard; + if (check_baby_info(env.program_info(), env.console, context, LANGUAGE, FILTERS0, action)){ + found_shiny = true; + env.console.log("Shiny found!"); + env.console.overlay().add_log("Shiny " + std::to_string(egg_index+1) + "/" + std::to_string(num_eggs_in_party), COLOR_GREEN); + stats.m_shinies++; + env.update_stats(); + send_encounter_notification( + env, + m_notification_noop, + NOTIFICATION_SHINY, + false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), + env.console.video().snapshot() + ); + }else{ + env.console.overlay().add_log("Not shiny " + std::to_string(egg_index+1) + "/" + std::to_string(num_eggs_in_party), COLOR_WHITE); + } + + auto send_keep_notification = [&](){ + if (!found_shiny){ + send_encounter_notification( + env, + NOTIFICATION_NONSHINY_KEEP, + NOTIFICATION_SHINY, + false, false, {}, std::nan(""), + env.console.video().snapshot() + ); + } + }; + + switch (action){ + case StatsHuntAction::StopProgram: + env.log("Program stop requested..."); + env.console.overlay().add_log("Request program stop", COLOR_WHITE); + send_keep_notification(); + throw ProgramFinishedException(); + case StatsHuntAction::Keep: + m_in_critical_to_save_stage = true; + env.log("Moving Pokemon to keep box...", COLOR_BLUE); + stats.m_kept++; + env.update_stats(); + m_num_kept++; + env.console.overlay().add_log("Keep pokemon " + std::to_string(m_num_kept) + "/" + std::to_string(MAX_KEEPERS), COLOR_YELLOW); + send_keep_notification(); + + if (move_pokemon_to_keep(env, context, party_row) == false){ + env.log("No empty slot available to place new pokemon."); + env.console.overlay().add_log("No box space", COLOR_RED); + throw ProgramFinishedException(); + } + + if (m_num_kept >= MAX_KEEPERS){ + env.log("Max keepers reached. Stopping program..."); + env.console.overlay().add_log("Max Keepers reached", COLOR_WHITE); + throw ProgramFinishedException(); + } + break; + + case StatsHuntAction::Discard: + default: + // If the auto save mode is AfterStartAndKeep, which allows resetting the game in case no eggs in the box are kept, + // then we can save the time of releasing hatched pokemon in case we will reset the game later. + // Otherwise, release the pokemon now. + if (AUTO_SAVING != AutoSave::AfterStartAndKeep){ + size_t local_errors = 0; + release_one_pokemon(env.program_info(), env.console, context, local_errors); + } + break; + } // end switch EggHatchAction +} + +// From the egg box, move to the kept box, drop the pokemon to an empty spot in the box, move back to the egg box. +// Return false if it does not find an empty spot. +bool EggAutonomous::move_pokemon_to_keep(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pokemon_row_in_party){ + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + const size_t keep_box_location = KEEP_BOX_LOCATION.current_value(); + if (keep_box_location == 0){ + move_to_left_box(context); + }else{ + move_to_right_box(context); + } + + context.wait_for_all_requests(); + + const uint8_t col_start = (keep_box_location == 0 ? 2 : 0); + for (uint8_t row = 0; row < 5; row++){ + for (uint8_t col = col_start; col < 6; col++){ + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); + context.wait_for_all_requests(); + // If no pokemon in the slot: + if (!sth_in_box_detector.detect(env.console.video().snapshot())){ + + // Move the to-keep pokemon in party to the empty slot. + swap_two_box_slots(env.program_info(), env.console, context, + BoxCursorLocation::PARTY, pokemon_row_in_party, 0, + BoxCursorLocation::SLOTS, row, col); + + // Move back to middle box + if (keep_box_location == 0){ + move_to_right_box(context); + }else{ + move_to_left_box(context); + } + context.wait_for_all_requests(); + return true; + } + } + } + return false; +} + +void EggAutonomous::reset_position_to_flying_spot(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Use map to fly back to the flying spot + open_map_from_overworld(env.program_info(), env.console, context); + pbf_move_left_joystick(context, 128, 160, 20, 50); + fly_to_overworld_from_map(env.program_info(), env.console, context); +} + +// From overworld, change pokemon party from the one used for getting eggs, to the one used for hatching +// The new party will be one flame body pokemon as lead, and some eggs. +// Function returns how many eggs are in the party +int EggAutonomous::picnic_party_to_hatch_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.console.overlay().add_log("Change to hatching", COLOR_WHITE); + // change pokemon party from used for fetching eggs in picnic, to hatching on your ride. + + enter_box_system_from_overworld(env.program_info(), env.console, context); + + // Move to left box + move_to_left_box(context); + + // Swap the stored the flame body pokemon with the stored first fetching pokemon + swap_two_box_slots(env.program_info(), env.console, context, + BoxCursorLocation::SLOTS, 0, 0, + BoxCursorLocation::PARTY, 0, 0); + + // Unload rest of party to the 2nd column (col 1) in box + unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, 1, HAS_CLONE_RIDE_POKEMON); + + // Move to middle box + move_to_right_box(context); + + // Load first egg column to party + load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, 0, HAS_CLONE_RIDE_POKEMON); + // Move cursor to party lead so that we can examine rest of party to detect eggs. + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); + + uint8_t expected_non_eggs_count_in_party = HAS_CLONE_RIDE_POKEMON ? 1 : 0; + const uint8_t num_eggs_in_party = check_non_eggs_count_in_party(env.program_info(), env.console, context, expected_non_eggs_count_in_party); + + leave_box_system_to_overworld(env.program_info(), env.console, context); + + return num_eggs_in_party; +} + + +void EggAutonomous::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool from_overworld){ + try{ + if (from_overworld){ + save_game_from_overworld(env.program_info(), env.console, context); + }else{ + save_game_from_menu(env.program_info(), env.console, context); + } + }catch (OperationFailedException& e){ + // To be safe: avoid interrupting or corrupting game saving, + // make game saving non error recoverable + throw FatalProgramException(std::move(e)); + } +} + + +void EggAutonomous::handle_recoverable_error( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + EventNotificationOption& notification, + OperationFailedException& e, + size_t& consecutive_failures +){ + auto& stats = env.current_stats(); + stats.m_errors++; + env.update_stats(); + e.send_notification(env, notification); + + if (SAVE_DEBUG_VIDEO){ + // Take a video to give more context for debugging + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + // if there is no auto save, then we shouldn't reset game to lose previous progress. + if (AUTO_SAVING == AutoSave::NoAutoSave){ + throw std::move(e); + } + + if (AUTO_SAVING == AutoSave::AfterStartAndKeep && m_in_critical_to_save_stage){ + // We have found a pokemon to keep, but before we can save the game to protect the pokemon, an error occurred. + // To not lose the pokemon, don't reset. + // Note: if AUTO_SAVING == AutoSave::EveryBatch, then we don't need to care about this critical stage, because + // in this auto saving mode, every batch of eggs have been saved beforehand. + env.log("Found an error before we can save the game to protect the newly kept pokemon.", COLOR_RED); + env.log("Don't reset game to protect it.", COLOR_RED); + throw std::move(e); + } + + consecutive_failures++; + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 times in the row.", + env.console + ); + } + + env.log("Reset game to handle recoverable error"); + reset_game(env.program_info(), env.console, context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h index 2e533563ab..a07d04fbd2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggAutonomous.h @@ -1,126 +1,126 @@ -/* Egg Autonomous - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EggAutonomous_H -#define PokemonAutomation_PokemonSV_EggAutonomous_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h" - -// #include - -namespace PokemonAutomation{ - -class OperationFailedException; - -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class EggAutonomous_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggAutonomous_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - -// Automatically hatch eggs to farm shiny -class EggAutonomous : public SingleSwitchProgramInstance{ -public: - EggAutonomous(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - int fetch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - void hatch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int num_eggs_in_party); - - void reset_position_to_flying_spot(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - int picnic_party_to_hatch_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - void process_one_baby(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t egg_index, uint8_t num_eggs_in_party); - - bool move_pokemon_to_keep(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pokemon_row_in_party); - - void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool from_overworld); - - void handle_recoverable_error( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - EventNotificationOption& notification, - OperationFailedException& e, - size_t& consecutive_failures - ); - - // void call_with_debug_dump(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::function MAX_KEEPERS; - - enum class AutoSave{ - NoAutoSave, - AfterStartAndKeep, - EveryBatch, - AfterFetchComplete, - }; - EnumDropdownOption AUTO_SAVING; - - EggPowerSandwichOption EGG_SANDWICH; - - BooleanCheckBoxOption HAS_CLONE_RIDE_POKEMON; - - IntegerEnumDropdownOption KEEP_BOX_LOCATION; - - Pokemon::StatsHuntIvJudgeFilterTable FILTERS0; - - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_NONSHINY_KEEP; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption m_notification_noop; - EventNotificationsOption NOTIFICATIONS; - - // How many pokemon have been kept so far - uint8_t m_num_kept = 0; - // How many sandwich spent so far - size_t m_num_sandwich_spent = 0; - // The program first fetchs some eggs, then hatches them. - // If user selects AUTO_SAVING to be on, then during hatching, when a recoverable error happens, we reset game. - // If we have saved the game after fetching phase, then when reloading the game, we may still have eggs in boxes - // that need hatching. - // If we haven't saved after fetching, then when reloading the game, there is no eggs in boxes. We can directly - // go to the next egg fetching phase. - // To tell apart the two cases, we need this bool var: - bool m_saved_after_fetched_eggs = false; - // When we find a pokemon to keep, we don't want the game to be reset if we haven't placed a save to protect the - // kept the pokemon. This flag is used to signal when we are in this "don't reset" stage. - bool m_in_critical_to_save_stage = false; -}; - - - - -} -} -} -#endif +/* Egg Autonomous + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EggAutonomous_H +#define PokemonAutomation_PokemonSV_EggAutonomous_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h" + +// #include + +namespace PokemonAutomation{ + +class OperationFailedException; + +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class EggAutonomous_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggAutonomous_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + +// Automatically hatch eggs to farm shiny +class EggAutonomous : public SingleSwitchProgramInstance{ +public: + EggAutonomous(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + int fetch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + void hatch_eggs_full_routine(SingleSwitchProgramEnvironment& env, ProControllerContext& context, int num_eggs_in_party); + + void reset_position_to_flying_spot(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + int picnic_party_to_hatch_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + void process_one_baby(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t egg_index, uint8_t num_eggs_in_party); + + bool move_pokemon_to_keep(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t pokemon_row_in_party); + + void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool from_overworld); + + void handle_recoverable_error( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + EventNotificationOption& notification, + OperationFailedException& e, + size_t& consecutive_failures + ); + + // void call_with_debug_dump(SingleSwitchProgramEnvironment& env, ProControllerContext& context, std::function MAX_KEEPERS; + + enum class AutoSave{ + NoAutoSave, + AfterStartAndKeep, + EveryBatch, + AfterFetchComplete, + }; + EnumDropdownOption AUTO_SAVING; + + EggPowerSandwichOption EGG_SANDWICH; + + BooleanCheckBoxOption HAS_CLONE_RIDE_POKEMON; + + IntegerEnumDropdownOption KEEP_BOX_LOCATION; + + Pokemon::StatsHuntIvJudgeFilterTable FILTERS0; + + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_NONSHINY_KEEP; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption m_notification_noop; + EventNotificationsOption NOTIFICATIONS; + + // How many pokemon have been kept so far + uint8_t m_num_kept = 0; + // How many sandwich spent so far + size_t m_num_sandwich_spent = 0; + // The program first fetchs some eggs, then hatches them. + // If user selects AUTO_SAVING to be on, then during hatching, when a recoverable error happens, we reset game. + // If we have saved the game after fetching phase, then when reloading the game, we may still have eggs in boxes + // that need hatching. + // If we haven't saved after fetching, then when reloading the game, there is no eggs in boxes. We can directly + // go to the next egg fetching phase. + // To tell apart the two cases, we need this bool var: + bool m_saved_after_fetched_eggs = false; + // When we find a pokemon to keep, we don't want the game to be reset if we haven't placed a save to protect the + // kept the pokemon. This flag is used to signal when we are in this "don't reset" stage. + bool m_in_critical_to_save_stage = false; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.cpp index b4ba31c051..dc1006df56 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.cpp @@ -1,152 +1,152 @@ -/* Egg Fetcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_EggFetcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -EggFetcher_Descriptor::EggFetcher_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:EggFetcher", - STRING_POKEMON + " SV", "Egg Fetcher", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggFetcher.md", - "Automatically fetch eggs from a picnic.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct EggFetcher_Descriptor::Stats : public StatsTracker{ - Stats() - : m_sandwiches(m_stats["Sandwiches"]) - , m_attempts(m_stats["Fetch Attempts"]) - , m_eggs(m_stats["Eggs"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Sandwiches"); - m_display_order.emplace_back("Fetch Attempts"); - m_display_order.emplace_back("Eggs"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_sandwiches; - std::atomic& m_attempts; - std::atomic& m_eggs; - std::atomic& m_errors; -}; -std::unique_ptr EggFetcher_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -EggFetcher::EggFetcher() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , EGGS_TO_FETCH( - "Fetch this many eggs:", - LockMode::LOCK_WHILE_RUNNING, - 900 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(EGGS_TO_FETCH); - PA_ADD_OPTION(EGG_SANDWICH); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void EggFetcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - EggFetcher_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 100); - - size_t num_eggs_collected = 0; - - try{ - for(uint16_t i = 0; i < EGG_SANDWICH.MAX_NUM_SANDWICHES; i++){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - picnic_at_zero_gate(env.program_info(), env.console, context); - // Now we are at picnic. We are at one end of picnic table while the egg basket is at the other end - - bool can_make_sandwich = eat_egg_sandwich_at_picnic(env, env.console, context, - EGG_SANDWICH.EGG_SANDWICH_TYPE, LANGUAGE); - if (can_make_sandwich == false){ - throw UserSetupError(env.console, "No sandwich recipe or ingredients. Cannot open and select the sandwich recipe."); - } - - stats.m_sandwiches++; - env.update_stats(); - - // move past the table and collect eggs - auto basket_check_callback = [&](size_t new_eggs){ - stats.m_attempts++; - stats.m_eggs += new_eggs; - env.update_stats(); - }; - - const size_t basket_wait_seconds = (EGG_SANDWICH.EGG_SANDWICH_TYPE == EggSandwichType::GREAT_PEANUT_BUTTER ? 180 : 120); - collect_eggs_after_sandwich(env.program_info(), env.console, context, basket_wait_seconds, - EGGS_TO_FETCH, num_eggs_collected, basket_check_callback); - - leave_picnic(env.program_info(), env.console, context); - - // Reset position to flying spot: - reset_position_at_zero_gate(env.program_info(), env.console, context); - - if (num_eggs_collected >= EGGS_TO_FETCH){ - break; - } - } - } catch(OperationFailedException&){ - stats.m_errors++; - env.update_stats(); - throw; - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Egg Fetcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_EggFetcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +EggFetcher_Descriptor::EggFetcher_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:EggFetcher", + STRING_POKEMON + " SV", "Egg Fetcher", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggFetcher.md", + "Automatically fetch eggs from a picnic.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct EggFetcher_Descriptor::Stats : public StatsTracker{ + Stats() + : m_sandwiches(m_stats["Sandwiches"]) + , m_attempts(m_stats["Fetch Attempts"]) + , m_eggs(m_stats["Eggs"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Sandwiches"); + m_display_order.emplace_back("Fetch Attempts"); + m_display_order.emplace_back("Eggs"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_sandwiches; + std::atomic& m_attempts; + std::atomic& m_eggs; + std::atomic& m_errors; +}; +std::unique_ptr EggFetcher_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +EggFetcher::EggFetcher() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , EGGS_TO_FETCH( + "Fetch this many eggs:", + LockMode::LOCK_WHILE_RUNNING, + 900 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(EGGS_TO_FETCH); + PA_ADD_OPTION(EGG_SANDWICH); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void EggFetcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + EggFetcher_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 100); + + size_t num_eggs_collected = 0; + + try{ + for(uint16_t i = 0; i < EGG_SANDWICH.MAX_NUM_SANDWICHES; i++){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + picnic_at_zero_gate(env.program_info(), env.console, context); + // Now we are at picnic. We are at one end of picnic table while the egg basket is at the other end + + bool can_make_sandwich = eat_egg_sandwich_at_picnic(env, env.console, context, + EGG_SANDWICH.EGG_SANDWICH_TYPE, LANGUAGE); + if (can_make_sandwich == false){ + throw UserSetupError(env.console, "No sandwich recipe or ingredients. Cannot open and select the sandwich recipe."); + } + + stats.m_sandwiches++; + env.update_stats(); + + // move past the table and collect eggs + auto basket_check_callback = [&](size_t new_eggs){ + stats.m_attempts++; + stats.m_eggs += new_eggs; + env.update_stats(); + }; + + const size_t basket_wait_seconds = (EGG_SANDWICH.EGG_SANDWICH_TYPE == EggSandwichType::GREAT_PEANUT_BUTTER ? 180 : 120); + collect_eggs_after_sandwich(env.program_info(), env.console, context, basket_wait_seconds, + EGGS_TO_FETCH, num_eggs_collected, basket_check_callback); + + leave_picnic(env.program_info(), env.console, context); + + // Reset position to flying spot: + reset_position_at_zero_gate(env.program_info(), env.console, context); + + if (num_eggs_collected >= EGGS_TO_FETCH){ + break; + } + } + } catch(OperationFailedException&){ + stats.m_errors++; + env.update_stats(); + throw; + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.h b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.h index b506be6b26..daeadd7fa4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggFetcher.h @@ -1,58 +1,58 @@ -/* Egg Fetcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EggFetcher_H -#define PokemonAutomation_PokemonSV_EggFetcher_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class EggFetcher_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggFetcher_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class EggFetcher : public SingleSwitchProgramInstance{ -public: - EggFetcher(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - - SimpleIntegerOption EGGS_TO_FETCH; - EggPowerSandwichOption EGG_SANDWICH; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Egg Fetcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EggFetcher_H +#define PokemonAutomation_PokemonSV_EggFetcher_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSV/Options/PokemonSV_EggPowerSandwichOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class EggFetcher_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggFetcher_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class EggFetcher : public SingleSwitchProgramInstance{ +public: + EggFetcher(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + + SimpleIntegerOption EGGS_TO_FETCH; + EggPowerSandwichOption EGG_SANDWICH; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp index 3ccc1b7981..ef3fd1a1d2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.cpp @@ -1,225 +1,225 @@ -/* Egg Hatcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV_EggHatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -EggHatcher_Descriptor::EggHatcher_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:EggHatcher", - STRING_POKEMON + " SV", "Egg Hatcher", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggHatcher.md", - "Automatically hatch eggs from boxes.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct EggHatcher_Descriptor::Stats : public StatsTracker{ - Stats() - : m_hatched(m_stats["Hatched"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Hatched"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_hatched; - std::atomic& m_errors; -}; -std::unique_ptr EggHatcher_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -EggHatcher::EggHatcher() - : GO_HOME_WHEN_DONE(false) - , START_LOCATION( - "Start location:
Where to start the hatcher program.
" - "Zero Gate Flying Spot: Stand at Zero Gate flying spot. The flying spot is already unlocked.
" - "Anywhere safe, on ride: You are in a safe location with no wild encounters or NPCs. You are on your ride lengendary.
" - "Anywhere safe, on foot: You are in a safe location with no wild encounters or NPCs. You stand on foot.
", - { - {StartLocation::ZeroGateFlyingSpot, "zero-gate", "Zero Gate Flying Spot"}, - {StartLocation::AnywhereOnRide, "anywhere-on-ride", "Anywhere safe, on ride."}, - {StartLocation::AnywhereOffRide, "anywhere-off-ride", "Anywhere safe, on foot."}, - }, - LockMode::LOCK_WHILE_RUNNING, - StartLocation::ZeroGateFlyingSpot - ) - , BOXES( - "How many boxes of eggs to hatch:", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 1, 32 - ) - , HAS_CLONE_RIDE_POKEMON( - "Cloned Ride Legendary 2nd in Party:
" - "Ride legendary cannot be cloned after patch 1.0.1. To preserve the existing clone while hatching eggs, " - "place it as second in party before starting the program." - "The program will skip the first row of eggs in the box as a result.", - LockMode::LOCK_WHILE_RUNNING, - false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(BOXES); - PA_ADD_OPTION(HAS_CLONE_RIDE_POKEMON); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void EggHatcher::hatch_one_box(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - EggHatcher_Descriptor::Stats& stats = env.current_stats(); - - for(uint8_t column_index = 0; column_index < 6; column_index++){ - uint8_t num_eggs = 0, num_non_egg_pokemon = 0; - { - const uint8_t expected_empty_slots_in_party = HAS_CLONE_RIDE_POKEMON ? 4 : 5; - if (check_empty_slots_in_party(env.program_info(), env.console, context) != expected_empty_slots_in_party){ - throw_and_log( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Your party should have " + std::to_string(expected_empty_slots_in_party) + " " + STRING_POKEMON + ".", - env.console - ); - } - } - - load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, column_index, HAS_CLONE_RIDE_POKEMON); - // Move cursor to party lead so that we can examine rest of party to detect eggs. - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); - - std::tie(num_eggs, num_non_egg_pokemon) = check_egg_party_column(env.program_info(), env.console, context); - if (num_eggs == 0){ - if (num_non_egg_pokemon == 0){ - // nothing in this column - env.log("Nothing in column " + std::to_string(column_index+1) + "."); - env.console.overlay().add_log("Empty column"); - continue; - } - - // we have only non-egg pokemon in the column - // Move them back - env.log("Only non-egg pokemon in column, move them back."); - env.console.overlay().add_log("No egg in column"); - unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, column_index, HAS_CLONE_RIDE_POKEMON); - continue; - } - - env.log("Loaded " + std::to_string(num_eggs) + " eggs to party."); - env.console.overlay().add_log("Load " + std::to_string(num_eggs) + " eggs"); - leave_box_system_to_overworld(env.program_info(), env.console, context); - - auto hatched_callback = [&](uint8_t){ - stats.m_hatched++; - env.update_stats(); - }; - - switch (START_LOCATION){ - case StartLocation::ZeroGateFlyingSpot: - hatch_eggs_at_zero_gate(env.program_info(), env.console, context, num_eggs, hatched_callback); - reset_position_at_zero_gate(env.program_info(), env.console, context); - break; - case StartLocation::AnywhereOnRide: - case StartLocation::AnywhereOffRide: // the program already pressed + to get on ride at start - { - const bool on_ride = true; - hatch_eggs_anywhere(env.program_info(), env.console, context, on_ride, num_eggs, hatched_callback); - break; - } - default: - throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Unknown StartLocation"); - } - - enter_box_system_from_overworld(env.program_info(), env.console, context); - - num_eggs = check_egg_party_column(env.program_info(), env.console, context).first; - if (num_eggs > 0){ - throw_and_log( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Detected egg in party after hatching.", - env.console - ); - } - - unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, column_index, HAS_CLONE_RIDE_POKEMON); - } - - context.wait_for_all_requests(); -} - -void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - EggHatcher_Descriptor::Stats& stats = env.current_stats(); - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 0); - - if (START_LOCATION == StartLocation::AnywhereOffRide){ - // Get on ride: - pbf_press_button(context, BUTTON_PLUS, 50, 100); - context.wait_for_all_requests(); - } - - try{ - enter_box_system_from_overworld(env.program_info(), env.console, context); - // // Wait one second to let game load box UI - // context.wait_for(std::chrono::seconds(1)); - - for (uint8_t i = 0; i < BOXES; i++){ - if (i > 0){ - env.log("Go to next box."); - env.console.overlay().add_log("Next box", COLOR_WHITE); - move_to_right_box(context); - } - context.wait_for_all_requests(); - - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - hatch_one_box(env, context); - } - } catch(OperationFailedException&){ - stats.m_errors++; - env.update_stats(); - throw; - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Egg Hatcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV_EggHatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +EggHatcher_Descriptor::EggHatcher_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:EggHatcher", + STRING_POKEMON + " SV", "Egg Hatcher", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/EggHatcher.md", + "Automatically hatch eggs from boxes.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct EggHatcher_Descriptor::Stats : public StatsTracker{ + Stats() + : m_hatched(m_stats["Hatched"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Hatched"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_hatched; + std::atomic& m_errors; +}; +std::unique_ptr EggHatcher_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +EggHatcher::EggHatcher() + : GO_HOME_WHEN_DONE(false) + , START_LOCATION( + "Start location:
Where to start the hatcher program.
" + "Zero Gate Flying Spot: Stand at Zero Gate flying spot. The flying spot is already unlocked.
" + "Anywhere safe, on ride: You are in a safe location with no wild encounters or NPCs. You are on your ride lengendary.
" + "Anywhere safe, on foot: You are in a safe location with no wild encounters or NPCs. You stand on foot.
", + { + {StartLocation::ZeroGateFlyingSpot, "zero-gate", "Zero Gate Flying Spot"}, + {StartLocation::AnywhereOnRide, "anywhere-on-ride", "Anywhere safe, on ride."}, + {StartLocation::AnywhereOffRide, "anywhere-off-ride", "Anywhere safe, on foot."}, + }, + LockMode::LOCK_WHILE_RUNNING, + StartLocation::ZeroGateFlyingSpot + ) + , BOXES( + "How many boxes of eggs to hatch:", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 1, 32 + ) + , HAS_CLONE_RIDE_POKEMON( + "Cloned Ride Legendary 2nd in Party:
" + "Ride legendary cannot be cloned after patch 1.0.1. To preserve the existing clone while hatching eggs, " + "place it as second in party before starting the program." + "The program will skip the first row of eggs in the box as a result.", + LockMode::LOCK_WHILE_RUNNING, + false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(BOXES); + PA_ADD_OPTION(HAS_CLONE_RIDE_POKEMON); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void EggHatcher::hatch_one_box(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + EggHatcher_Descriptor::Stats& stats = env.current_stats(); + + for(uint8_t column_index = 0; column_index < 6; column_index++){ + uint8_t num_eggs = 0, num_non_egg_pokemon = 0; + { + const uint8_t expected_empty_slots_in_party = HAS_CLONE_RIDE_POKEMON ? 4 : 5; + if (check_empty_slots_in_party(env.program_info(), env.console, context) != expected_empty_slots_in_party){ + throw_and_log( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Your party should have " + std::to_string(expected_empty_slots_in_party) + " " + STRING_POKEMON + ".", + env.console + ); + } + } + + load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, column_index, HAS_CLONE_RIDE_POKEMON); + // Move cursor to party lead so that we can examine rest of party to detect eggs. + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 0, 0); + + std::tie(num_eggs, num_non_egg_pokemon) = check_egg_party_column(env.program_info(), env.console, context); + if (num_eggs == 0){ + if (num_non_egg_pokemon == 0){ + // nothing in this column + env.log("Nothing in column " + std::to_string(column_index+1) + "."); + env.console.overlay().add_log("Empty column"); + continue; + } + + // we have only non-egg pokemon in the column + // Move them back + env.log("Only non-egg pokemon in column, move them back."); + env.console.overlay().add_log("No egg in column"); + unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, column_index, HAS_CLONE_RIDE_POKEMON); + continue; + } + + env.log("Loaded " + std::to_string(num_eggs) + " eggs to party."); + env.console.overlay().add_log("Load " + std::to_string(num_eggs) + " eggs"); + leave_box_system_to_overworld(env.program_info(), env.console, context); + + auto hatched_callback = [&](uint8_t){ + stats.m_hatched++; + env.update_stats(); + }; + + switch (START_LOCATION){ + case StartLocation::ZeroGateFlyingSpot: + hatch_eggs_at_zero_gate(env.program_info(), env.console, context, num_eggs, hatched_callback); + reset_position_at_zero_gate(env.program_info(), env.console, context); + break; + case StartLocation::AnywhereOnRide: + case StartLocation::AnywhereOffRide: // the program already pressed + to get on ride at start + { + const bool on_ride = true; + hatch_eggs_anywhere(env.program_info(), env.console, context, on_ride, num_eggs, hatched_callback); + break; + } + default: + throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Unknown StartLocation"); + } + + enter_box_system_from_overworld(env.program_info(), env.console, context); + + num_eggs = check_egg_party_column(env.program_info(), env.console, context).first; + if (num_eggs > 0){ + throw_and_log( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Detected egg in party after hatching.", + env.console + ); + } + + unload_one_column_from_party(env, env.console, context, NOTIFICATION_ERROR_RECOVERABLE, column_index, HAS_CLONE_RIDE_POKEMON); + } + + context.wait_for_all_requests(); +} + +void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + EggHatcher_Descriptor::Stats& stats = env.current_stats(); + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 0); + + if (START_LOCATION == StartLocation::AnywhereOffRide){ + // Get on ride: + pbf_press_button(context, BUTTON_PLUS, 50, 100); + context.wait_for_all_requests(); + } + + try{ + enter_box_system_from_overworld(env.program_info(), env.console, context); + // // Wait one second to let game load box UI + // context.wait_for(std::chrono::seconds(1)); + + for (uint8_t i = 0; i < BOXES; i++){ + if (i > 0){ + env.log("Go to next box."); + env.console.overlay().add_log("Next box", COLOR_WHITE); + move_to_right_box(context); + } + context.wait_for_all_requests(); + + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + hatch_one_box(env, context); + } + } catch(OperationFailedException&){ + stats.m_errors++; + env.update_stats(); + throw; + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.h b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.h index 10fa59ae5e..190b9a320f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggHatcher.h @@ -1,69 +1,69 @@ -/* Egg Hatcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_EggHatcher_H -#define PokemonAutomation_PokemonSV_EggHatcher_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class EggHatcher_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggHatcher_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class EggHatcher : public SingleSwitchProgramInstance{ -public: - EggHatcher(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - // Start at box system, where party is empty, the program will: - // - load one column to party - // - hatch - // - return to box system and offline paty - // Repeat for all six columns of a box - void hatch_one_box(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - enum class StartLocation{ - ZeroGateFlyingSpot, - AnywhereOnRide, - AnywhereOffRide, - }; - EnumDropdownOption START_LOCATION; - - SimpleIntegerOption BOXES; - BooleanCheckBoxOption HAS_CLONE_RIDE_POKEMON; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Egg Hatcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_EggHatcher_H +#define PokemonAutomation_PokemonSV_EggHatcher_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class EggHatcher_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggHatcher_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class EggHatcher : public SingleSwitchProgramInstance{ +public: + EggHatcher(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + // Start at box system, where party is empty, the program will: + // - load one column to party + // - hatch + // - return to box system and offline paty + // Repeat for all six columns of a box + void hatch_one_box(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + enum class StartLocation{ + ZeroGateFlyingSpot, + AnywhereOnRide, + AnywhereOffRide, + }; + EnumDropdownOption START_LOCATION; + + SimpleIntegerOption BOXES; + BooleanCheckBoxOption HAS_CLONE_RIDE_POKEMON; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp index bfaa6a14fd..57eeaac46c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.cpp @@ -1,698 +1,698 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV_EggRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -namespace{ - - -void clear_mons_in_front( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - stream.log("Waiting for all " + STRING_POKEMON + " in front of you to get out of the way..."); - WhiteButtonWatcher button( - COLOR_YELLOW, WhiteButton::ButtonA, - {0.020, 0.590, 0.035, 0.060}, - WhiteButtonWatcher::FinderType::GONE - ); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 40; c++){ - context.wait_for_all_requests(); - context.wait_for(std::chrono::seconds(30)); - stream.log("A " + Pokemon::STRING_POKEMON + " is standing in the way. Whistling and waiting 30 seconds...", COLOR_RED); - pbf_press_button(context, BUTTON_R, 20, 0); - } - }, - {button} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "UnableToClearObstacle", - "Unable to clear " + STRING_POKEMON + " in front of you after 20 min." - ); - } -#if 0 - WhiteButtonDetector detector(COLOR_RED, WhiteButton::ButtonA, {0.020, 0.590, 0.035, 0.060}); - while (detector.detect(console.video().snapshot())){ - pbf_press_button(context, BUTTON_R, 20, 30 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } -#endif -} - - - - -// Call this function when an egg hatching dialog is detected. -// This function presses A to finish the egg hatching dialogs and updates logs and calls callback functions. -// egg_idx: currently which egg in the party is hatching. 0-indexed. -void handle_egg_hatching( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t num_eggs_in_party, - uint8_t egg_idx, - std::function egg_hatched_callback -){ - stream.log("Detect hatching dialog: " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party)); - stream.overlay().add_log("Hatched " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_GREEN); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - ssf_press_right_joystick(context, 0, 128, 0, 95); - for(int i = 0; i < 60; i++){ - pbf_mash_button(context, BUTTON_A, 125); - } - }, - {overworld} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "NoHatchingEnd", - "hatch_eggs_at_zero_gate(): No end of egg hatching detected after one minute." - ); - } - stream.log("Finished hatching animation and dialog."); - - if (egg_hatched_callback){ - egg_hatched_callback(egg_idx); - } -} - -// Assuming on your legendary ride and camera facing the same direction as the player character, -// Turning right to do circullar motion to hatch eggs. -// Function returns when a dialog is detected, meaning an egg is hatching. -// Throw exception when no egg hatching detected after 10 minutes. -void do_egg_cycle_motion( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - AdvanceDialogWatcher dialog(COLOR_RED); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - // hatch circle: - // Left joystick forward, right joystick right - // click left joystick - ssf_press_left_joystick(context, 128, 0, 0ms, std::chrono::minutes(10)); - ssf_press_right_joystick(context, 255, 128, 0ms, std::chrono::minutes(10)); - pbf_press_button(context, BUTTON_LCLICK, std::chrono::minutes(10), 0ms); - }, - {dialog} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "NoEggToHatch", - "hatch_eggs_at_zero_gate(): No more egg hatch after 10 minutes." - ); - } -} - -} // anonymous namespace - -void order_compote_du_fils( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - // We start this function when we enter the restaurant without pressing any button. - - // Se we first press A to clear a dialog: - pbf_press_button(context, BUTTON_A, 30, 100); - - bool paid = false; - bool eating = false; - while(eating == false){ - context.wait_for_all_requests(); - - AdvanceDialogWatcher dialog_watcher(COLOR_RED, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); - GradientArrowWatcher menu_item_0_watcher(COLOR_BLUE, GradientArrowType::RIGHT, {0.037, 0.224, 0.074, 0.104}); - GradientArrowWatcher menu_item_1_watcher(COLOR_BLUE, GradientArrowType::RIGHT, {0.037, 0.339, 0.074, 0.104}); - PromptDialogWatcher prompt_watcher(COLOR_RED, {0.535, 0.450, 0.367, 0.124}); - - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {dialog_watcher, menu_item_0_watcher, menu_item_1_watcher, prompt_watcher} - ); - - switch (ret){ - case 0: - stream.log("Detected dialog advance."); - if (paid){ - // This is a dialog box after we have paid the food. - // Mash A to clear any remaining dialog before a very long eating animation. - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - eating = true; - }else{ - pbf_press_button(context, BUTTON_A, 30, 100); - } - break; - case 1: - stream.log("Detected restaurant menu."); - stream.overlay().add_log("Restaurant menu", COLOR_WHITE); - pbf_press_dpad(context, DPAD_DOWN, 30, 60); - break; - case 2: - stream.log("Detected the dish we want."); - pbf_press_button(context, BUTTON_A, 30, 100); - break; - case 3: - stream.log("Detected the payment prompt."); - stream.overlay().add_log("Pay dish", COLOR_WHITE); - pbf_press_button(context, BUTTON_A, 30, 100); - paid = true; - break; - default: - dump_image_and_throw_recoverable_exception( - info, stream, "ErrorOrderFood", - "order_compote_du_fils(): No recognized state in restaurant menu after 60 seconds." - ); - } - } // end state machine for restaurant menu - - { // Now wait for eating animation to finish. - AdvanceDialogWatcher dialog_watcher(COLOR_RED, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for(int i = 0; i < 60; i++){ - pbf_press_button(context, BUTTON_A, 25, 100); - } - }, - {{dialog_watcher}} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "EndDiningNotDetected", - "order_compote_du_fils(): No end of eating after 60 seconds." - ); - } - } - - // Now leaving the restaurant - pbf_mash_button(context, BUTTON_B, 90); - pbf_wait(context, 100); - while(true){ - context.wait_for_all_requests(); - - AdvanceDialogWatcher dialog_watcher(COLOR_RED, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {dialog_watcher, overworld} - ); - if (ret == 0){ - pbf_press_button(context, BUTTON_A, 30, 100); - continue; - }else if (ret == 1){ - return; // outside restaurant - }else{ - dump_image_and_throw_recoverable_exception( - info, stream, "EndLeavingRestaurantNotDetected", - "order_compote_du_fils(): No end of leaving restaurant after 60 seconds." - ); - } - } -} - -void picnic_at_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - // Orient camera to look at same direction as player character - // This is needed because when save-load the game, the camera is reset - // to this location. - pbf_press_button(context, BUTTON_L, 50, 40); - - // Move right to make player character facing away from Aera Zero observation station - pbf_move_left_joystick(context, 255, 32, 50, 50); - // Press L to move camera to face the same direction as the player character - pbf_press_button(context, BUTTON_L, 50, 40); - // Move forward - pbf_move_left_joystick(context, 128, 0, 125, 0); - - picnic_from_overworld(info, stream, context); -} - -bool eat_egg_sandwich_at_picnic( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - EggSandwichType sandwich_type, - Language language -){ - // Move forward to table to make sandwich - pbf_move_left_joystick(context, 128, 0, 30, 40); - context.wait_for_all_requests(); - - clear_mons_in_front(env.program_info(), stream, context); - if (enter_sandwich_recipe_list(env.program_info(), stream, context) == false){ - return false; - } - switch (sandwich_type){ - case EggSandwichType::GREAT_PEANUT_BUTTER: - { - if (select_sandwich_recipe(env.program_info(), stream, context, 17) == false){ - // cannot find the sandwich recipe, either user has not unlocked it or does not have enough ingredients: - return false; - } - std::map fillings = { {"banana", (uint8_t)1} }; - std::vector fillings_sorted; - fillings_sorted.push_back("banana"); - int plates = 1; - run_sandwich_maker(env, stream, context, language, fillings, fillings_sorted, plates); - break; - } - case EggSandwichType::TWO_SWEET_HERBS: - case EggSandwichType::SALTY_SWEET_HERBS: - case EggSandwichType::BITTER_SWEET_HERBS: - enter_custom_sandwich_mode(env.program_info(), stream, context); - if (language == Language::None){ - throw UserSetupError(stream.logger(), "Must set game language option to read ingredient lists to make herb sandwich."); - } - make_two_herbs_sandwich( - env.program_info(), env.realtime_inference_dispatcher(), - stream, context, - sandwich_type, - language - ); - finish_sandwich_eating(env.program_info(), stream, context); - break; - default: - throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Unknown EggSandwichType"); - } - - return true; -} - -void collect_eggs_after_sandwich( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t basket_wait_seconds, - size_t max_eggs, - size_t& num_eggs_collected, - std::function basket_check_callback -){ - context.wait_for_all_requests(); - stream.log("Move past picnic table"); - stream.overlay().add_log("Move past picnic table", COLOR_WHITE); - - // Recall your ride to reduce obstacles. - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - // Move left - pbf_move_left_joystick(context, 0, 128, 40, 40); - // Move forward to pass table - pbf_move_left_joystick(context, 128, 0, 80, 40); // old value: 80 - // Move right - pbf_move_left_joystick(context, 255, 128, 50, 40); - // Move back to face basket - pbf_move_left_joystick(context, 128, 255, 10, 40); - - // Move closer to the basket. - pbf_press_button(context, BUTTON_L, 20, 105); - pbf_move_left_joystick(context, 128, 0, 10, 40); - - - context.wait_for_all_requests(); - - const size_t default_collection_interval_seconds = basket_wait_seconds; - const auto max_egg_wait_time = std::chrono::minutes(30); - - size_t num_checks = 0; - size_t eggs_collected_cur_session = 0; - - WallClock start = current_time(); - while(true){ - const size_t last_num_eggs_collected = num_eggs_collected; - - clear_mons_in_front(info, stream, context); - check_basket_to_collect_eggs(info, stream, context, max_eggs, num_eggs_collected); - - const size_t new_eggs_added = num_eggs_collected - last_num_eggs_collected; - basket_check_callback(new_eggs_added); - eggs_collected_cur_session += new_eggs_added; - num_checks++; - - if (num_eggs_collected == max_eggs){ - stream.log("Collected enough eggs: " + std::to_string(max_eggs)); - break; - } - - if (current_time() - start > max_egg_wait_time){ - stream.log("Picnic time up."); - stream.overlay().add_log("Picnic time up", COLOR_YELLOW); - break; - } - context.wait_for_all_requests(); - - const size_t remaining_eggs = max_eggs - num_eggs_collected; - const float average_eggs_per_check = eggs_collected_cur_session / (float)num_checks; - - size_t wait_seconds = basket_wait_seconds; - if (remaining_eggs < average_eggs_per_check){ - // If we have few remaining eggs to hatch, adjust wait time accordingly. - wait_seconds = size_t(remaining_eggs * default_collection_interval_seconds / average_eggs_per_check); - stream.log("Last remaining eggs: " + std::to_string(remaining_eggs) + ", avg eggs per check: " + - std::to_string(average_eggs_per_check) + ", wait secs: " + std::to_string(wait_seconds) + "."); - if (wait_seconds < 30){ - // Minimum wait period is 30 sec. - stream.log("Clamp wait time to 30 secs."); - wait_seconds = 30; - } - } - - stream.log("Collected " + std::to_string(num_eggs_collected) + " eggs, avg eggs per check: " + std::to_string(average_eggs_per_check) - + ", wait " + std::to_string(wait_seconds) + " seconds."); - stream.overlay().add_log("Wait " + std::to_string(wait_seconds) + " secs", COLOR_WHITE); - - context.wait_for(std::chrono::seconds(wait_seconds)); - } -} - -void check_basket_to_collect_eggs( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t max_eggs, size_t& num_eggs_collected -){ - bool checked = false; - size_t consecutive_nothing = 0; - Button last_prompt = BUTTON_NONE; - bool pending_refuse = false; - - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - info, stream, "CheckEggsTimedOut", - "check_basket_to_collect_eggs(): Still picking up eggs after 5 minutes." - ); - } - - DialogBoxWatcher picnic(COLOR_RED, false, std::chrono::milliseconds(500)); - AdvanceDialogWatcher advance(COLOR_RED); - PromptDialogWatcher prompt(COLOR_RED, {0.623, 0.530, 0.243, 0.119}); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - { - picnic, - advance, - prompt, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - - if (ret != 0){ - consecutive_nothing = 0; - } - - switch (ret){ - case 0: - stream.log("Detected no dialog."); - consecutive_nothing++; - last_prompt = BUTTON_NONE; - if (consecutive_nothing >= 10){ - dump_image_and_throw_recoverable_exception( - info, stream, "BasketNotFound", - "collect_eggs_from_basket(): Basket not found after 10 attempts." - ); - } - if (checked){ - stream.log("Done talking to basket."); - return; - } - stream.log("Attempting to talk to basket..."); - pbf_press_button(context, BUTTON_A, 20, 30); - continue; - - case 1: - stream.log("Detected advanced dialog."); - last_prompt = BUTTON_NONE; - pbf_press_button(context, BUTTON_B, 20, 30); - checked = true; - continue; - - case 2: - if (last_prompt != 0){ - stream.log("Detected 2nd consecutive prompt. (unexpected)", COLOR_RED); - // Repeat the previous button press. - pbf_press_button(context, last_prompt, 20, 80); - continue; - } - - if (pending_refuse){ - stream.log("Confirming refused egg..."); - pbf_press_button(context, BUTTON_A, 20, 80); - pending_refuse = false; - continue; - } - - if (num_eggs_collected < max_eggs){ - num_eggs_collected++; - - std::string msg = std::to_string(num_eggs_collected) + "/" + std::to_string(max_eggs); - stream.log("Found an egg " + msg + ". Keeping..."); - stream.overlay().add_log("Egg " + msg, COLOR_GREEN); - pbf_press_button(context, BUTTON_A, 20, 80); - - last_prompt = BUTTON_A; - }else{ - stream.log("Found an egg! But we already have enough..."); - stream.overlay().add_log("Full. Skip egg.", COLOR_WHITE); - pbf_press_button(context, BUTTON_B, 20, 80); - last_prompt = BUTTON_B; - pending_refuse = true; - } - continue; - - default: -// dump_image_and_throw_recoverable_exception( -// info, console, "CheckEggsNoState", -// "check_basket_to_collect_eggs(): No state detected after 5 seconds." -// ); - stream.log("Rotating view and trying again...", COLOR_RED); - pbf_move_right_joystick(context, 0, 128, 30, 0); - } - - } -} - - -std::pair check_egg_party_column(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - BoxEggPartyColumnWatcher egg_column_watcher; - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - {egg_column_watcher} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "CannotReadPartyEggs", - "check_egg_party_column(): Cannot read party eggs in box system." - ); - } - return {egg_column_watcher.num_eggs_found(), egg_column_watcher.num_non_egg_pokemon_found()}; -} - -uint8_t check_non_eggs_count_in_party( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t expected_non_eggs_count_in_party -){ - auto counts = check_egg_party_column(info, stream, context); - if (counts.second != expected_non_eggs_count_in_party){ - dump_image_and_throw_recoverable_exception( - info, stream, "NonEggPokemonInParty", - "check_non_eggs_count_in_party: Found non-egg pokemon in party" - ); - } - return counts.first; -} - -void hatch_eggs_at_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t num_eggs_in_party, - std::function egg_hatched_callback) -{ - bool got_off_ramp = false; - for(uint8_t egg_idx = 0; egg_idx < num_eggs_in_party; egg_idx++){ - stream.log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party) + "."); - stream.overlay().add_log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_BLUE); - - // Orient camera to look at same direction as player character - // This is needed because when save-load the game, the camera is reset - // to this location. - pbf_press_button(context, BUTTON_L, 50, 40); - - context.wait_for_all_requests(); - - if (got_off_ramp == false){ - AdvanceDialogWatcher dialog(COLOR_RED); - // first, get off ramp to the empty field for circling motions - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - if (egg_idx == 0){ - // At beginning, ride on Koraidon/Miradon and go off ramp: - pbf_press_button(context, BUTTON_PLUS, 50, 100); - // Move right to make player character facing away from Aera Zero observation station - pbf_move_left_joystick(context, 255, 0, 50, 50); - // Press L to move camera to face the same direction as the player character - pbf_press_button(context, BUTTON_L, 50, 40); - // Move forward - pbf_move_left_joystick(context, 128, 0, 200, 0); - } - }, - {dialog} - ); - if (ret == 0){ - // egg hatching when going off ramp: - handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); - reset_position_at_zero_gate(info, stream, context); - continue; - } - - got_off_ramp = true; - stream.log("Got off ramp"); - } - - // Circular motions: - do_egg_cycle_motion(info, stream, context); - - handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); - } // end hatching each egg -} - -void hatch_eggs_anywhere( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool already_on_ride, - uint8_t num_eggs_in_party, - std::function egg_hatched_callback -){ - if (!already_on_ride){ - // At beginning, ride on Koraidon/Miradon and go off ramp: - pbf_press_button(context, BUTTON_PLUS, 50, 100); - context.wait_for_all_requests(); - } - - for(uint8_t egg_idx = 0; egg_idx < num_eggs_in_party; egg_idx++){ - stream.log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party) + "."); - stream.overlay().add_log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_BLUE); - - // Orient camera to look at same direction as player character - // This is needed because when save-load the game, the camera is reset - // to this location. - pbf_press_button(context, BUTTON_L, 50, 40); - - context.wait_for_all_requests(); - - // Circular motions: - do_egg_cycle_motion(info, stream, context); - - handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); - } // end hatching each egg -} - - -void reset_position_at_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - stream.log("Open map and reset location to Zero Gate."); - // Use map to fly back to the flying spot - open_map_from_overworld(info, stream, context); - - pbf_move_left_joystick(context, 128, 160, 20, 50); - - fly_to_overworld_from_map(info, stream, context); -} - - -bool check_baby_info( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - OCR::LanguageOCROption& LANGUAGE, - Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, - Pokemon::StatsHuntAction& action -){ - context.wait_for_all_requests(); - - Language language = LANGUAGE; - if (language == Language::None){ - change_view_to_stats_or_judge(stream, context); - }else{ - change_view_to_judge(stream, context, language); - } - - VideoOverlaySet overlay_set(stream.overlay()); - - BoxShinyWatcher shiny_detector; - // BoxShinyDetector shiny_detector; - shiny_detector.make_overlays(overlay_set); - - IvJudgeReaderScope iv_reader_scope(stream.overlay(), LANGUAGE); - BoxGenderDetector gender_detector; - gender_detector.make_overlays(overlay_set); - BoxNatureDetector nature_detector(stream.overlay(), LANGUAGE); - - const int shiny_ret = wait_until(stream, context, std::chrono::milliseconds(200), {shiny_detector}); - const bool shiny = (shiny_ret == 0); - VideoSnapshot screen = stream.video().snapshot(); - - IvJudgeReader::Results IVs = iv_reader_scope.read(stream.logger(), screen); - StatsHuntGenderFilter gender = gender_detector.detect(screen); - NatureReader::Results nature = nature_detector.read(stream.logger(), screen); - - stream.log(IVs.to_string(), COLOR_GREEN); - stream.log("Gender: " + gender_to_string(gender), COLOR_GREEN); - stream.log("Nature: " + nature.to_string(), COLOR_GREEN); - - action = FILTERS.get_action(shiny, gender, nature.nature, IVs); - - return shiny; -} - -} -} -} +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxGenderDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxNatureDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV_EggRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +namespace{ + + +void clear_mons_in_front( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + stream.log("Waiting for all " + STRING_POKEMON + " in front of you to get out of the way..."); + WhiteButtonWatcher button( + COLOR_YELLOW, WhiteButton::ButtonA, + {0.020, 0.590, 0.035, 0.060}, + WhiteButtonWatcher::FinderType::GONE + ); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 40; c++){ + context.wait_for_all_requests(); + context.wait_for(std::chrono::seconds(30)); + stream.log("A " + Pokemon::STRING_POKEMON + " is standing in the way. Whistling and waiting 30 seconds...", COLOR_RED); + pbf_press_button(context, BUTTON_R, 20, 0); + } + }, + {button} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "UnableToClearObstacle", + "Unable to clear " + STRING_POKEMON + " in front of you after 20 min." + ); + } +#if 0 + WhiteButtonDetector detector(COLOR_RED, WhiteButton::ButtonA, {0.020, 0.590, 0.035, 0.060}); + while (detector.detect(console.video().snapshot())){ + pbf_press_button(context, BUTTON_R, 20, 30 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } +#endif +} + + + + +// Call this function when an egg hatching dialog is detected. +// This function presses A to finish the egg hatching dialogs and updates logs and calls callback functions. +// egg_idx: currently which egg in the party is hatching. 0-indexed. +void handle_egg_hatching( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t num_eggs_in_party, + uint8_t egg_idx, + std::function egg_hatched_callback +){ + stream.log("Detect hatching dialog: " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party)); + stream.overlay().add_log("Hatched " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_GREEN); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + ssf_press_right_joystick(context, 0, 128, 0, 95); + for(int i = 0; i < 60; i++){ + pbf_mash_button(context, BUTTON_A, 125); + } + }, + {overworld} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "NoHatchingEnd", + "hatch_eggs_at_zero_gate(): No end of egg hatching detected after one minute." + ); + } + stream.log("Finished hatching animation and dialog."); + + if (egg_hatched_callback){ + egg_hatched_callback(egg_idx); + } +} + +// Assuming on your legendary ride and camera facing the same direction as the player character, +// Turning right to do circullar motion to hatch eggs. +// Function returns when a dialog is detected, meaning an egg is hatching. +// Throw exception when no egg hatching detected after 10 minutes. +void do_egg_cycle_motion( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + AdvanceDialogWatcher dialog(COLOR_RED); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + // hatch circle: + // Left joystick forward, right joystick right + // click left joystick + ssf_press_left_joystick(context, 128, 0, 0ms, std::chrono::minutes(10)); + ssf_press_right_joystick(context, 255, 128, 0ms, std::chrono::minutes(10)); + pbf_press_button(context, BUTTON_LCLICK, std::chrono::minutes(10), 0ms); + }, + {dialog} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "NoEggToHatch", + "hatch_eggs_at_zero_gate(): No more egg hatch after 10 minutes." + ); + } +} + +} // anonymous namespace + +void order_compote_du_fils( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + // We start this function when we enter the restaurant without pressing any button. + + // Se we first press A to clear a dialog: + pbf_press_button(context, BUTTON_A, 30, 100); + + bool paid = false; + bool eating = false; + while(eating == false){ + context.wait_for_all_requests(); + + AdvanceDialogWatcher dialog_watcher(COLOR_RED, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); + GradientArrowWatcher menu_item_0_watcher(COLOR_BLUE, GradientArrowType::RIGHT, {0.037, 0.224, 0.074, 0.104}); + GradientArrowWatcher menu_item_1_watcher(COLOR_BLUE, GradientArrowType::RIGHT, {0.037, 0.339, 0.074, 0.104}); + PromptDialogWatcher prompt_watcher(COLOR_RED, {0.535, 0.450, 0.367, 0.124}); + + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {dialog_watcher, menu_item_0_watcher, menu_item_1_watcher, prompt_watcher} + ); + + switch (ret){ + case 0: + stream.log("Detected dialog advance."); + if (paid){ + // This is a dialog box after we have paid the food. + // Mash A to clear any remaining dialog before a very long eating animation. + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + eating = true; + }else{ + pbf_press_button(context, BUTTON_A, 30, 100); + } + break; + case 1: + stream.log("Detected restaurant menu."); + stream.overlay().add_log("Restaurant menu", COLOR_WHITE); + pbf_press_dpad(context, DPAD_DOWN, 30, 60); + break; + case 2: + stream.log("Detected the dish we want."); + pbf_press_button(context, BUTTON_A, 30, 100); + break; + case 3: + stream.log("Detected the payment prompt."); + stream.overlay().add_log("Pay dish", COLOR_WHITE); + pbf_press_button(context, BUTTON_A, 30, 100); + paid = true; + break; + default: + dump_image_and_throw_recoverable_exception( + info, stream, "ErrorOrderFood", + "order_compote_du_fils(): No recognized state in restaurant menu after 60 seconds." + ); + } + } // end state machine for restaurant menu + + { // Now wait for eating animation to finish. + AdvanceDialogWatcher dialog_watcher(COLOR_RED, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for(int i = 0; i < 60; i++){ + pbf_press_button(context, BUTTON_A, 25, 100); + } + }, + {{dialog_watcher}} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "EndDiningNotDetected", + "order_compote_du_fils(): No end of eating after 60 seconds." + ); + } + } + + // Now leaving the restaurant + pbf_mash_button(context, BUTTON_B, 90); + pbf_wait(context, 100); + while(true){ + context.wait_for_all_requests(); + + AdvanceDialogWatcher dialog_watcher(COLOR_RED, DialogType::DIALOG_ALL, std::chrono::milliseconds(100)); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {dialog_watcher, overworld} + ); + if (ret == 0){ + pbf_press_button(context, BUTTON_A, 30, 100); + continue; + }else if (ret == 1){ + return; // outside restaurant + }else{ + dump_image_and_throw_recoverable_exception( + info, stream, "EndLeavingRestaurantNotDetected", + "order_compote_du_fils(): No end of leaving restaurant after 60 seconds." + ); + } + } +} + +void picnic_at_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + // Orient camera to look at same direction as player character + // This is needed because when save-load the game, the camera is reset + // to this location. + pbf_press_button(context, BUTTON_L, 50, 40); + + // Move right to make player character facing away from Aera Zero observation station + pbf_move_left_joystick(context, 255, 32, 50, 50); + // Press L to move camera to face the same direction as the player character + pbf_press_button(context, BUTTON_L, 50, 40); + // Move forward + pbf_move_left_joystick(context, 128, 0, 125, 0); + + picnic_from_overworld(info, stream, context); +} + +bool eat_egg_sandwich_at_picnic( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + EggSandwichType sandwich_type, + Language language +){ + // Move forward to table to make sandwich + pbf_move_left_joystick(context, 128, 0, 30, 40); + context.wait_for_all_requests(); + + clear_mons_in_front(env.program_info(), stream, context); + if (enter_sandwich_recipe_list(env.program_info(), stream, context) == false){ + return false; + } + switch (sandwich_type){ + case EggSandwichType::GREAT_PEANUT_BUTTER: + { + if (select_sandwich_recipe(env.program_info(), stream, context, 17) == false){ + // cannot find the sandwich recipe, either user has not unlocked it or does not have enough ingredients: + return false; + } + std::map fillings = { {"banana", (uint8_t)1} }; + std::vector fillings_sorted; + fillings_sorted.push_back("banana"); + int plates = 1; + run_sandwich_maker(env, stream, context, language, fillings, fillings_sorted, plates); + break; + } + case EggSandwichType::TWO_SWEET_HERBS: + case EggSandwichType::SALTY_SWEET_HERBS: + case EggSandwichType::BITTER_SWEET_HERBS: + enter_custom_sandwich_mode(env.program_info(), stream, context); + if (language == Language::None){ + throw UserSetupError(stream.logger(), "Must set game language option to read ingredient lists to make herb sandwich."); + } + make_two_herbs_sandwich( + env.program_info(), env.realtime_inference_dispatcher(), + stream, context, + sandwich_type, + language + ); + finish_sandwich_eating(env.program_info(), stream, context); + break; + default: + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, "Unknown EggSandwichType"); + } + + return true; +} + +void collect_eggs_after_sandwich( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t basket_wait_seconds, + size_t max_eggs, + size_t& num_eggs_collected, + std::function basket_check_callback +){ + context.wait_for_all_requests(); + stream.log("Move past picnic table"); + stream.overlay().add_log("Move past picnic table", COLOR_WHITE); + + // Recall your ride to reduce obstacles. + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + // Move left + pbf_move_left_joystick(context, 0, 128, 40, 40); + // Move forward to pass table + pbf_move_left_joystick(context, 128, 0, 80, 40); // old value: 80 + // Move right + pbf_move_left_joystick(context, 255, 128, 50, 40); + // Move back to face basket + pbf_move_left_joystick(context, 128, 255, 10, 40); + + // Move closer to the basket. + pbf_press_button(context, BUTTON_L, 20, 105); + pbf_move_left_joystick(context, 128, 0, 10, 40); + + + context.wait_for_all_requests(); + + const size_t default_collection_interval_seconds = basket_wait_seconds; + const auto max_egg_wait_time = std::chrono::minutes(30); + + size_t num_checks = 0; + size_t eggs_collected_cur_session = 0; + + WallClock start = current_time(); + while(true){ + const size_t last_num_eggs_collected = num_eggs_collected; + + clear_mons_in_front(info, stream, context); + check_basket_to_collect_eggs(info, stream, context, max_eggs, num_eggs_collected); + + const size_t new_eggs_added = num_eggs_collected - last_num_eggs_collected; + basket_check_callback(new_eggs_added); + eggs_collected_cur_session += new_eggs_added; + num_checks++; + + if (num_eggs_collected == max_eggs){ + stream.log("Collected enough eggs: " + std::to_string(max_eggs)); + break; + } + + if (current_time() - start > max_egg_wait_time){ + stream.log("Picnic time up."); + stream.overlay().add_log("Picnic time up", COLOR_YELLOW); + break; + } + context.wait_for_all_requests(); + + const size_t remaining_eggs = max_eggs - num_eggs_collected; + const float average_eggs_per_check = eggs_collected_cur_session / (float)num_checks; + + size_t wait_seconds = basket_wait_seconds; + if (remaining_eggs < average_eggs_per_check){ + // If we have few remaining eggs to hatch, adjust wait time accordingly. + wait_seconds = size_t(remaining_eggs * default_collection_interval_seconds / average_eggs_per_check); + stream.log("Last remaining eggs: " + std::to_string(remaining_eggs) + ", avg eggs per check: " + + std::to_string(average_eggs_per_check) + ", wait secs: " + std::to_string(wait_seconds) + "."); + if (wait_seconds < 30){ + // Minimum wait period is 30 sec. + stream.log("Clamp wait time to 30 secs."); + wait_seconds = 30; + } + } + + stream.log("Collected " + std::to_string(num_eggs_collected) + " eggs, avg eggs per check: " + std::to_string(average_eggs_per_check) + + ", wait " + std::to_string(wait_seconds) + " seconds."); + stream.overlay().add_log("Wait " + std::to_string(wait_seconds) + " secs", COLOR_WHITE); + + context.wait_for(std::chrono::seconds(wait_seconds)); + } +} + +void check_basket_to_collect_eggs( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t max_eggs, size_t& num_eggs_collected +){ + bool checked = false; + size_t consecutive_nothing = 0; + Button last_prompt = BUTTON_NONE; + bool pending_refuse = false; + + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + info, stream, "CheckEggsTimedOut", + "check_basket_to_collect_eggs(): Still picking up eggs after 5 minutes." + ); + } + + DialogBoxWatcher picnic(COLOR_RED, false, std::chrono::milliseconds(500)); + AdvanceDialogWatcher advance(COLOR_RED); + PromptDialogWatcher prompt(COLOR_RED, {0.623, 0.530, 0.243, 0.119}); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + { + picnic, + advance, + prompt, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + + if (ret != 0){ + consecutive_nothing = 0; + } + + switch (ret){ + case 0: + stream.log("Detected no dialog."); + consecutive_nothing++; + last_prompt = BUTTON_NONE; + if (consecutive_nothing >= 10){ + dump_image_and_throw_recoverable_exception( + info, stream, "BasketNotFound", + "collect_eggs_from_basket(): Basket not found after 10 attempts." + ); + } + if (checked){ + stream.log("Done talking to basket."); + return; + } + stream.log("Attempting to talk to basket..."); + pbf_press_button(context, BUTTON_A, 20, 30); + continue; + + case 1: + stream.log("Detected advanced dialog."); + last_prompt = BUTTON_NONE; + pbf_press_button(context, BUTTON_B, 20, 30); + checked = true; + continue; + + case 2: + if (last_prompt != 0){ + stream.log("Detected 2nd consecutive prompt. (unexpected)", COLOR_RED); + // Repeat the previous button press. + pbf_press_button(context, last_prompt, 20, 80); + continue; + } + + if (pending_refuse){ + stream.log("Confirming refused egg..."); + pbf_press_button(context, BUTTON_A, 20, 80); + pending_refuse = false; + continue; + } + + if (num_eggs_collected < max_eggs){ + num_eggs_collected++; + + std::string msg = std::to_string(num_eggs_collected) + "/" + std::to_string(max_eggs); + stream.log("Found an egg " + msg + ". Keeping..."); + stream.overlay().add_log("Egg " + msg, COLOR_GREEN); + pbf_press_button(context, BUTTON_A, 20, 80); + + last_prompt = BUTTON_A; + }else{ + stream.log("Found an egg! But we already have enough..."); + stream.overlay().add_log("Full. Skip egg.", COLOR_WHITE); + pbf_press_button(context, BUTTON_B, 20, 80); + last_prompt = BUTTON_B; + pending_refuse = true; + } + continue; + + default: +// dump_image_and_throw_recoverable_exception( +// info, console, "CheckEggsNoState", +// "check_basket_to_collect_eggs(): No state detected after 5 seconds." +// ); + stream.log("Rotating view and trying again...", COLOR_RED); + pbf_move_right_joystick(context, 0, 128, 30, 0); + } + + } +} + + +std::pair check_egg_party_column(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + BoxEggPartyColumnWatcher egg_column_watcher; + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + {egg_column_watcher} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "CannotReadPartyEggs", + "check_egg_party_column(): Cannot read party eggs in box system." + ); + } + return {egg_column_watcher.num_eggs_found(), egg_column_watcher.num_non_egg_pokemon_found()}; +} + +uint8_t check_non_eggs_count_in_party( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t expected_non_eggs_count_in_party +){ + auto counts = check_egg_party_column(info, stream, context); + if (counts.second != expected_non_eggs_count_in_party){ + dump_image_and_throw_recoverable_exception( + info, stream, "NonEggPokemonInParty", + "check_non_eggs_count_in_party: Found non-egg pokemon in party" + ); + } + return counts.first; +} + +void hatch_eggs_at_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t num_eggs_in_party, + std::function egg_hatched_callback) +{ + bool got_off_ramp = false; + for(uint8_t egg_idx = 0; egg_idx < num_eggs_in_party; egg_idx++){ + stream.log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party) + "."); + stream.overlay().add_log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_BLUE); + + // Orient camera to look at same direction as player character + // This is needed because when save-load the game, the camera is reset + // to this location. + pbf_press_button(context, BUTTON_L, 50, 40); + + context.wait_for_all_requests(); + + if (got_off_ramp == false){ + AdvanceDialogWatcher dialog(COLOR_RED); + // first, get off ramp to the empty field for circling motions + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + if (egg_idx == 0){ + // At beginning, ride on Koraidon/Miradon and go off ramp: + pbf_press_button(context, BUTTON_PLUS, 50, 100); + // Move right to make player character facing away from Aera Zero observation station + pbf_move_left_joystick(context, 255, 0, 50, 50); + // Press L to move camera to face the same direction as the player character + pbf_press_button(context, BUTTON_L, 50, 40); + // Move forward + pbf_move_left_joystick(context, 128, 0, 200, 0); + } + }, + {dialog} + ); + if (ret == 0){ + // egg hatching when going off ramp: + handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); + reset_position_at_zero_gate(info, stream, context); + continue; + } + + got_off_ramp = true; + stream.log("Got off ramp"); + } + + // Circular motions: + do_egg_cycle_motion(info, stream, context); + + handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); + } // end hatching each egg +} + +void hatch_eggs_anywhere( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool already_on_ride, + uint8_t num_eggs_in_party, + std::function egg_hatched_callback +){ + if (!already_on_ride){ + // At beginning, ride on Koraidon/Miradon and go off ramp: + pbf_press_button(context, BUTTON_PLUS, 50, 100); + context.wait_for_all_requests(); + } + + for(uint8_t egg_idx = 0; egg_idx < num_eggs_in_party; egg_idx++){ + stream.log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party) + "."); + stream.overlay().add_log("Hatching egg " + std::to_string(egg_idx+1) + "/" + std::to_string(num_eggs_in_party), COLOR_BLUE); + + // Orient camera to look at same direction as player character + // This is needed because when save-load the game, the camera is reset + // to this location. + pbf_press_button(context, BUTTON_L, 50, 40); + + context.wait_for_all_requests(); + + // Circular motions: + do_egg_cycle_motion(info, stream, context); + + handle_egg_hatching(info, stream, context, num_eggs_in_party, egg_idx, egg_hatched_callback); + } // end hatching each egg +} + + +void reset_position_at_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + stream.log("Open map and reset location to Zero Gate."); + // Use map to fly back to the flying spot + open_map_from_overworld(info, stream, context); + + pbf_move_left_joystick(context, 128, 160, 20, 50); + + fly_to_overworld_from_map(info, stream, context); +} + + +bool check_baby_info( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + OCR::LanguageOCROption& LANGUAGE, + Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, + Pokemon::StatsHuntAction& action +){ + context.wait_for_all_requests(); + + Language language = LANGUAGE; + if (language == Language::None){ + change_view_to_stats_or_judge(stream, context); + }else{ + change_view_to_judge(stream, context, language); + } + + VideoOverlaySet overlay_set(stream.overlay()); + + BoxShinyWatcher shiny_detector; + // BoxShinyDetector shiny_detector; + shiny_detector.make_overlays(overlay_set); + + IvJudgeReaderScope iv_reader_scope(stream.overlay(), LANGUAGE); + BoxGenderDetector gender_detector; + gender_detector.make_overlays(overlay_set); + BoxNatureDetector nature_detector(stream.overlay(), LANGUAGE); + + const int shiny_ret = wait_until(stream, context, std::chrono::milliseconds(200), {shiny_detector}); + const bool shiny = (shiny_ret == 0); + VideoSnapshot screen = stream.video().snapshot(); + + IvJudgeReader::Results IVs = iv_reader_scope.read(stream.logger(), screen); + StatsHuntGenderFilter gender = gender_detector.detect(screen); + NatureReader::Results nature = nature_detector.read(stream.logger(), screen); + + stream.log(IVs.to_string(), COLOR_GREEN); + stream.log("Gender: " + gender_to_string(gender), COLOR_GREEN); + stream.log("Nature: " + nature.to_string(), COLOR_GREEN); + + action = FILTERS.get_action(shiny, gender, nature.nature, IVs); + + return shiny; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h index b4d6b74f26..380840f526 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h @@ -1,137 +1,137 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - * Various functions to do egg related automation. - * This file is used to prevent main function like EggAutonomous from becoming too long. - */ - -#ifndef PokemonAutomation_PokemonSV_EggRoutines_H -#define PokemonAutomation_PokemonSV_EggRoutines_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" - -namespace PokemonAutomation{ - - struct ProgramInfo; - class AsyncDispatcher; - class ImageViewRGB32; - - namespace OCR{ - class LanguageOCROption; - } - namespace Pokemon{ - enum class StatsHuntAction; - class StatsHuntIvJudgeFilterTable; - } - -namespace NintendoSwitch{ -namespace PokemonSV{ - -// While entering Gastronome En Famille, order the dish Compote du Fils. -// This gives Egg Power Lv. 2 at price of 2800. -void order_compote_du_fils( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// Start at Zero Gate flying spot, go off ramp to start a picnic. -void picnic_at_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// Starting at the initial position of a picnic, go to picnic table to make a sandwich that gives egg power. -// Can choose: -// - Great Peanut Butter Sandwich to gain egg power Lv 2, must have unlocked its recipe and have enough ingredients to make all -// the sandwiches for all the unlocked recipes. -// - Two-sweet-herbs, bitter-sweet-herbs or salty-sweet-herbs custom sandwich to gain egg power Lv 3, must have enough ingredinets and -// provide game language for OCR ingredient lists. -// Return false if no needed sandwich ingredients or recipe. -bool eat_egg_sandwich_at_picnic( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - EggSandwichType sandwich_type, - Language language -); - -// After eating a sandwich, go around picnic table to wait at basket and collect eggs. -// `num_eggs_collected` will be updated to add newly collected eggs. -void collect_eggs_after_sandwich( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t basket_wait_seconds, - size_t max_eggs, - size_t& num_eggs_collected, - std::function basket_check_callback); - -// Start at Zero Gate flying spot, go in circles in front of the lab to hatch eggs. -// `egg_hatched_callback` will be called after each egg hatched, with egg index (0-indexed) -void hatch_eggs_at_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t num_eggs_in_party, - std::function egg_hatched_callback = nullptr -); - -// From overworld, go in circles to hatch eggs. -// `egg_hatched_callback` will be called after each egg hatched, with egg index (0-indexed) -// `already_on_ride`: whether the player character is on ride when starting the function. -void hatch_eggs_anywhere( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool already_on_ride, - uint8_t num_eggs_in_party, - std::function egg_hatched_callback = nullptr -); - - -// Standing in front of basket during picnic, check basket and update egg count. -void check_basket_to_collect_eggs( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t max_eggs, size_t& num_eggs_collected -); - -// In box view, check the five slots in the party column, after party lead. -// return how many eggs in the five slots, and how many non-egg pokemon in the five slots. -// Note: make sure the current cursor does not float above the five slots, otherwise it may affect detection. -std::pair check_egg_party_column( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// In box view, check whether there is the right amount of non-egg pokemon in the five slots in the party column, after party lead. -// return how many eggs in the five slots. -// Throw OperationFailedException if found unxepcted non-egg pokemon count in the slots. -// Note: make sure the current cursor does not float above the five slots, otherwise it may affect detection. -uint8_t check_non_eggs_count_in_party( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t expected_non_eggs_count_in_party -); - - -// When hatching at Zero Gate, use this function to reset player character position back to Zero Gate flying spot -void reset_position_at_zero_gate(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// Assuming the current selected slot in box system is a hatched pokemon, not empty space or egg, -// check the hatched pokemon's info to determine what to do with it. -// Return if the pokemon is shiny. The action to handle the pokemon is returned in `action`. -// The function will try to switch to judge view if possible so that it can read IVs. -// If judge view is not unlocked, it will settle onto stats view, and the pokemon's IVs will be regarded as unknown. -bool check_baby_info( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - OCR::LanguageOCROption& LANGUAGE, - Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, - Pokemon::StatsHuntAction& action -); - -} -} -} -#endif +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + * Various functions to do egg related automation. + * This file is used to prevent main function like EggAutonomous from becoming too long. + */ + +#ifndef PokemonAutomation_PokemonSV_EggRoutines_H +#define PokemonAutomation_PokemonSV_EggRoutines_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" + +namespace PokemonAutomation{ + + struct ProgramInfo; + class AsyncDispatcher; + class ImageViewRGB32; + + namespace OCR{ + class LanguageOCROption; + } + namespace Pokemon{ + enum class StatsHuntAction; + class StatsHuntIvJudgeFilterTable; + } + +namespace NintendoSwitch{ +namespace PokemonSV{ + +// While entering Gastronome En Famille, order the dish Compote du Fils. +// This gives Egg Power Lv. 2 at price of 2800. +void order_compote_du_fils( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// Start at Zero Gate flying spot, go off ramp to start a picnic. +void picnic_at_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// Starting at the initial position of a picnic, go to picnic table to make a sandwich that gives egg power. +// Can choose: +// - Great Peanut Butter Sandwich to gain egg power Lv 2, must have unlocked its recipe and have enough ingredients to make all +// the sandwiches for all the unlocked recipes. +// - Two-sweet-herbs, bitter-sweet-herbs or salty-sweet-herbs custom sandwich to gain egg power Lv 3, must have enough ingredinets and +// provide game language for OCR ingredient lists. +// Return false if no needed sandwich ingredients or recipe. +bool eat_egg_sandwich_at_picnic( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + EggSandwichType sandwich_type, + Language language +); + +// After eating a sandwich, go around picnic table to wait at basket and collect eggs. +// `num_eggs_collected` will be updated to add newly collected eggs. +void collect_eggs_after_sandwich( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t basket_wait_seconds, + size_t max_eggs, + size_t& num_eggs_collected, + std::function basket_check_callback); + +// Start at Zero Gate flying spot, go in circles in front of the lab to hatch eggs. +// `egg_hatched_callback` will be called after each egg hatched, with egg index (0-indexed) +void hatch_eggs_at_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t num_eggs_in_party, + std::function egg_hatched_callback = nullptr +); + +// From overworld, go in circles to hatch eggs. +// `egg_hatched_callback` will be called after each egg hatched, with egg index (0-indexed) +// `already_on_ride`: whether the player character is on ride when starting the function. +void hatch_eggs_anywhere( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool already_on_ride, + uint8_t num_eggs_in_party, + std::function egg_hatched_callback = nullptr +); + + +// Standing in front of basket during picnic, check basket and update egg count. +void check_basket_to_collect_eggs( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t max_eggs, size_t& num_eggs_collected +); + +// In box view, check the five slots in the party column, after party lead. +// return how many eggs in the five slots, and how many non-egg pokemon in the five slots. +// Note: make sure the current cursor does not float above the five slots, otherwise it may affect detection. +std::pair check_egg_party_column( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// In box view, check whether there is the right amount of non-egg pokemon in the five slots in the party column, after party lead. +// return how many eggs in the five slots. +// Throw OperationFailedException if found unxepcted non-egg pokemon count in the slots. +// Note: make sure the current cursor does not float above the five slots, otherwise it may affect detection. +uint8_t check_non_eggs_count_in_party( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t expected_non_eggs_count_in_party +); + + +// When hatching at Zero Gate, use this function to reset player character position back to Zero Gate flying spot +void reset_position_at_zero_gate(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// Assuming the current selected slot in box system is a hatched pokemon, not empty space or egg, +// check the hatched pokemon's info to determine what to do with it. +// Return if the pokemon is shiny. The action to handle the pokemon is returned in `action`. +// The function will try to switch to judge view if possible so that it can read IVs. +// If judge view is not unlocked, it will settle onto stats view, and the pokemon's IVs will be regarded as unknown. +bool check_baby_info( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + OCR::LanguageOCROption& LANGUAGE, + Pokemon::StatsHuntIvJudgeFilterTable& FILTERS, + Pokemon::StatsHuntAction& action +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp index ab49f77ca4..8af388d55c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.cpp @@ -1,616 +1,616 @@ -/* Auction Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include -#include -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "Pokemon/Pokemon_Strings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Resources/PokemonSV_AuctionItemNames.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSV_AuctionFarmer.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -AuctionFarmer_Descriptor::AuctionFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:AuctionFarmer", - STRING_POKEMON + " SV", "Auction Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AuctionFarmer.md", - "Check auctions and bid on items.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -struct AuctionFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : m_resets(m_stats["Resets"]) - , m_auctions(m_stats["Auctions"]) - , m_money(m_stats["Spent Money"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Auctions"); - m_display_order.emplace_back("Spent Money"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_resets; - std::atomic& m_auctions; - std::atomic& m_money; - std::atomic& m_errors; -}; -std::unique_ptr AuctionFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -AuctionFarmer::AuctionFarmer() - : LANGUAGE( - "Game Language:
The language is needed to read which items are offered.", - AuctionItemNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , TARGET_ITEMS("Items:
Multiple Items can be selected. The program will bid on any selected item which is offered.") - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_AUCTION_WIN("Auction Win", true, false, ImageAttachmentMode::JPG, {"Notifs"}) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_AUCTION_WIN, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options("Advanced Options: (developer only)") - , ONE_NPC("One NPC:
Check only the NPC you're standing in front of. (Multiple NPCs in development)", LockMode::LOCK_WHILE_RUNNING, true) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(TARGET_ITEMS); - PA_ADD_OPTION(NOTIFICATIONS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(ONE_NPC); - } -} - - -std::vector AuctionFarmer::detect_dialog_boxes(const ImageViewRGB32& screen){ - using namespace Kernels::Waterfill; - - uint32_t MIN_BORDER_THRESHOLD = 0xffc07000; - uint32_t MAX_BORDER_THRESHOLD = 0xffffc550; - - uint32_t MIN_YELLOW_THRESHOLD = 0xffd0b000; - uint32_t MAX_YELLOW_THRESHOLD = 0xffffff30; - - size_t width = screen.width(); - size_t height = screen.height(); - - - std::vector dialog_boxes; - { - PackedBinaryMatrix border_matrix = compress_rgb32_to_binary_range(screen, MIN_BORDER_THRESHOLD, MAX_BORDER_THRESHOLD); - - std::unique_ptr session = make_WaterfillSession(border_matrix); - auto iter = session->make_iterator(50); - WaterfillObject object; - while (iter->find_next(object, true)){ - // Discard objects touching the edge of the screen or bottom right corner where the map is located or if the object is too small - if (object.min_x == 0 || object.min_y == 0 // touching left or top edge - || object.max_x + 1 >= width || object.max_y + 1 >= height // touching right or bottom edge - || (object.max_x > width * 0.82 && object.max_y > height * 0.68) // touches mini map area - || object.width() < width * 0.0926 || object.height() < height * 0.0926 // object is too small - ){ - continue; - } - dialog_boxes.emplace_back(object); - -// static int c = 0; -// extract_box_reference(screen, object).save("image-" + std::to_string(c++) + ".png"); - -#if 1 - // check for yellow inside the orange border - ImagePixelBox border_pixel_box(object); -// ImageFloatBox border_float_box = pixelbox_to_floatbox(screen, border_pixel_box); - ImageViewRGB32 dialog = extract_box_reference(screen, border_pixel_box); - PackedBinaryMatrix yellow_matrix = compress_rgb32_to_binary_range(dialog, MIN_YELLOW_THRESHOLD, MAX_YELLOW_THRESHOLD); - - std::unique_ptr yellow_session = make_WaterfillSession(yellow_matrix); - auto yellow_iter = yellow_session->make_iterator(300); - WaterfillObject yellow_object; - while (yellow_iter->find_next(yellow_object, true)){ - // Discard small objects - if (object.width() < width * 0.0925 || object.height() < height * 0.0925){ - continue; - } - -// extract_box_reference(dialog, yellow_object).save("yellow-" + std::to_string(c++) + ".png"); - -// ImagePixelBox dialog_pixel_box(yellow_object); - ImagePixelBox dialog_pixel_box; - dialog_pixel_box.min_x = border_pixel_box.min_x + yellow_object.min_x; - dialog_pixel_box.min_y = border_pixel_box.min_y + yellow_object.min_y; - dialog_pixel_box.max_x = dialog_pixel_box.min_x + yellow_object.width(); - dialog_pixel_box.max_y = dialog_pixel_box.min_y + yellow_object.height(); - -// ImageFloatBox translated_dialog_box = translate_to_parent(screen, border_float_box, dialog_pixel_box); -// dialog_boxes.emplace_back(translated_dialog_box); - dialog_boxes.emplace_back(dialog_pixel_box); - } -#endif - } - } - return dialog_boxes; -} - - -void AuctionFarmer::reset_auctions(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool do_full_reset, uint8_t& year){ - try{ - if (do_full_reset){ - if (year == MAX_YEAR){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - PokemonSwSh::home_roll_date_enter_game_autorollback(env.console, context, year); - } - save_game_from_overworld(env.program_info(), env.console, context); - - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - PokemonSwSh::home_roll_date_enter_game_autorollback(env.console, context, year); - } - pbf_wait(context, 1 * TICKS_PER_SECOND); - - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - context.wait_for_all_requests(); - reset_game_from_home(env.program_info(), env.console, context, TICKS_PER_SECOND); - }catch (OperationFailedException& e){ - AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); - stats.m_errors++; - env.update_stats(); - throw FatalProgramException(std::move(e)); - } -} - -std::vector> AuctionFarmer::check_offers(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); - - pbf_wait(context, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - std::vector dialog_boxes = detect_dialog_boxes(screen); - std::deque bubbles_boxes; - std::deque offer_overlay_boxes; - std::vector> offers; - - if (dialog_boxes.empty()){ - stats.m_errors++; - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Could not detect any offer dialogs.", screen); - } - - // read dialog bubble - ImageFloatBox top_offer_box(0.05, 0.02, 0.90, 0.49); - ImageFloatBox bottom_offer_box(0.05, 0.49, 0.90, 0.49); - std::vector offer_boxes = {top_offer_box}; - if (LANGUAGE == Language::Spanish || LANGUAGE == Language::ChineseTraditional) { - offer_boxes.emplace_back(bottom_offer_box); - } - - for (ImagePixelBox dialog_box : dialog_boxes){ - for (ImageFloatBox offer_box : offer_boxes) { - // std::cout << "dialog_box: [" - // << dialog_box.min_x << "," << dialog_box.min_y << "] - [" - // << dialog_box.max_x << "," << dialog_box.max_y << "]" << std::endl; - - ImageFloatBox dialog_float_box = pixelbox_to_floatbox(screen, dialog_box); - bubbles_boxes.emplace_back(env.console, dialog_float_box, COLOR_GREEN); - - - // OverlayBoxScope dialog_overlay(env.console, dialog_box, COLOR_DARK_BLUE); - ImageFloatBox translated_offer_box = translate_to_parent( - screen, - dialog_float_box, - floatbox_to_pixelbox(dialog_box.width(), dialog_box.height(), offer_box) - ); - // std::cout << "translated_offer_box: [" - // << translated_offer_box.x << "," << translated_offer_box.y << "] - [" - // << translated_offer_box.width << "," << translated_offer_box.height << "]" << std::endl; - - offer_overlay_boxes.emplace_back(env.console, translated_offer_box, COLOR_BLUE); - - // OverlayBoxScope offer_overlay(env.console, translated_offer_box, COLOR_BLUE); - - ImageViewRGB32 dialog = extract_box_reference(screen, dialog_box); - ImageViewRGB32 offer_image = extract_box_reference(dialog, offer_box); - - // std::cout << offer_image.width() << " x " << offer_image.height() << std::endl; - - - const double LOG10P_THRESHOLD = -1.5; - std::string best_item; - OCR::StringMatchResult result = AuctionItemNameReader::instance().read_substring( - env.console, LANGUAGE, - offer_image, - OCR::BLACK_TEXT_FILTERS() - ); - - result.clear_beyond_log10p(LOG10P_THRESHOLD); - if (best_item.empty() && !result.results.empty()) { - auto iter = result.results.begin(); - if (iter->first < LOG10P_THRESHOLD) { - best_item = iter->second.token; - - AuctionOffer offer{ best_item }; - std::pair pair(offer, dialog_float_box); - offers.emplace_back(pair); - } - } - } - } -// context.wait_for(std::chrono::seconds(100)); - return offers; -} - -bool AuctionFarmer::is_good_offer(AuctionOffer offer){ - // Special handling for Japanese bottle cap items - bool any_bottle_cap = false; - if (LANGUAGE == Language::Japanese){ - any_bottle_cap = (offer.item == "bottle-cap" || offer.item == "gold-bottle-cap") - && (TARGET_ITEMS.find_item("bottle-cap") || TARGET_ITEMS.find_item("gold-bottle-cap")); - } - - return TARGET_ITEMS.find_item(offer.item) || any_bottle_cap ; -} - -// Move to auctioneer and interact -void AuctionFarmer::move_to_auctioneer(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer){ - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - - size_t tries = 0; - while (tries < 10){ - if (!ONE_NPC){ - move_dialog_to_center(env, context, offer); - pbf_move_left_joystick(context, 128, 0, 60, 10); - } - - pbf_press_button(context, BUTTON_A, 20, 100); - int ret = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); - - if (ret == 0){ - return; - } - tries++; - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Too many attempts to talk to the NPC.", - env.console - ); -} - -// Dialog is the only piece of orientation we have, so the goal is to put it into the center of the screen so we know in which direction the character walks. -// This is only used for multiple NPCs. -void AuctionFarmer::move_dialog_to_center(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer wanted){ - double center_x = 0.0f; - double center_y = 0.0f; - bool offer_visible = false; - - while (center_x < 0.43 || center_x > 0.57){ - context.wait_for_all_requests(); - std::vector> offers = check_offers(env, context); - - for (std::pair offer : offers){ - if (offer.first.item != wanted.item){ - continue; - } - offer_visible = true; - - center_x = offer.second.x + (0.5 * offer.second.width); - center_y = offer.second.y + (0.5 * offer.second.height); - - - // check whether the stop condition is fulfilled by now. - if (!(center_x < 0.43 || center_x > 0.57)){ - break; - } - - uint8_t distance_x = (uint8_t)(center_x * 255); - uint8_t distance_y = (uint8_t)(center_y * 255); - env.console.log(std::to_string(distance_x)); - env.console.log(std::to_string(distance_y)); - - pbf_move_right_joystick(context, distance_x, distance_y, 20, 20); - - break; - } - - if (!offer_visible){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Lost offer dialog for wanted item.", - env.console - ); - } - } -} - -void AuctionFarmer::reset_position(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (ONE_NPC){ - // No movement, player character should always be directly in front of an auctioneer. - return; - } - - // move backwards, TODO: check position(?) and orientation - pbf_move_left_joystick(context, 128, 255, 50, 20); - return; -} - - -uint64_t read_next_bid(VideoStream& stream, ProControllerContext& context, Language language, bool high){ - // How much to cut off from the bid text in order to not read currencies and exclamation marks as numbers. - // Values are pixels for a 1920x1080 screen, negative values are padding - static const std::map> cutoffs = { - { Language::English, {22, 6} }, - { Language::Japanese, {-5, 54} }, - { Language::Spanish, {6, 32} }, - { Language::French, {-5, 45} }, - { Language::German, {-5, 22} }, - { Language::Italian, {-5, 35} }, - { Language::Korean, {-5, 42} }, - { Language::ChineseSimplified, {22, 7} }, - { Language::ChineseTraditional, {22,7} } - }; - - static const std::map high_x = { - { Language::English, 0.75f }, - { Language::Japanese, 0.75f }, - { Language::Spanish, 0.73f }, - { Language::French, 0.68f }, - { Language::German, 0.73f }, - { Language::Italian, 0.75f }, - { Language::Korean, 0.75f }, - { Language::ChineseSimplified, 0.75f }, - { Language::ChineseTraditional, 0.75f } - }; - - static const std::map low_x = { - { Language::English, 0.75f }, - { Language::Japanese, 0.75f }, - { Language::Spanish, 0.75f }, - { Language::French, 0.75f }, - { Language::German, 0.73f }, - { Language::Italian, 0.75f }, - { Language::Korean, 0.75f }, - { Language::ChineseSimplified, 0.75f }, - { Language::ChineseTraditional, 0.75f } - }; - - float box_y = high ? 0.42f : 0.493f; - float box_x = high ? high_x.at(language) : low_x.at(language); - float width = 0.9f - box_x; // max_x is always the same for all languages - OverlayBoxScope box(stream.overlay(), { box_x, box_y, width, 0.048 }); - - std::unordered_map read_bids; - size_t highest_read = 0; - uint64_t read_value = 0; - - // read next bid multiple times since the selection arrow sometimes blocks the first digit - for (size_t i = 0; i < 10; i++){ - VideoSnapshot screen = stream.video().snapshot(); - double screen_scale = (double)screen->width() / 1920.0; - double vertical_padding = 5.0; // small amount of pixels so numbers do not touch the edge of the view when reading them - - ImageViewRGB32 raw_bid_image = extract_box_reference(screen, box); - ImagePixelBox bid_bounding_box = ImageMatch::enclosing_rectangle_with_pixel_filter( - raw_bid_image, - [](Color pixel) { - return (uint32_t)pixel.red() + pixel.green() + pixel.blue() < 250; - }); - - int32_t max_width = static_cast(raw_bid_image.width() - 1); - int32_t max_height = static_cast(raw_bid_image.height() - 1); - int32_t scaled_vertical_padding = static_cast(vertical_padding * screen_scale); - int32_t left_cutoff = static_cast(cutoffs.at(language).first * screen_scale); - int32_t right_cutoff = static_cast(cutoffs.at(language).second * screen_scale); - - ImagePixelBox cut_bid_bounding_box( - std::max(0, std::min(max_width, static_cast(bid_bounding_box.min_x) + left_cutoff)), - std::max(0, std::min(max_height, static_cast(bid_bounding_box.min_y) - scaled_vertical_padding)), - std::max(0, std::min(max_width, static_cast(bid_bounding_box.max_x) - right_cutoff)), - std::max(0, std::min(max_height, static_cast(bid_bounding_box.max_y) + scaled_vertical_padding)) - ); - - uint64_t read_bid = OCR::read_number(stream.logger(), extract_box_reference(raw_bid_image, cut_bid_bounding_box)); - - if (read_bids.find(read_bid) == read_bids.end()){ - read_bids[read_bid] = 0; - } - read_bids[read_bid] += 1; - - if (read_bids[read_bid] > highest_read){ - highest_read = read_bids[read_bid]; - read_value = read_bid; - } - context.wait_for(Milliseconds(20)); - } - - stream.log("Next bid: " + std::to_string(read_value)); - return read_value; -} - -void AuctionFarmer::bid_on_item(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer){ - AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); - - VideoSnapshot offer_screen = env.console.video().snapshot(); - - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - PromptDialogWatcher high_detector(COLOR_RED, { 0.50, 0.40, 0.40, 0.082 }); - PromptDialogWatcher mid_detector(COLOR_PURPLE, { 0.50, 0.475, 0.40, 0.082 }); - PromptDialogWatcher low_detector(COLOR_PURPLE, { 0.50, 0.55, 0.40, 0.082 }); - OverworldWatcher overworld_detector(env.console, COLOR_BLUE); - bool won_auction = true; - bool auction_ongoing = true; - int64_t current_bid = 0; - - context.wait_for_all_requests(); - while (auction_ongoing){ - int ret = wait_until(env.console, context, Milliseconds(5000), { advance_detector, high_detector, mid_detector, low_detector, overworld_detector }); - context.wait_for(Milliseconds(100)); - - switch (ret){ - case 0: - pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); - break; - case 1: - current_bid = read_next_bid(env.console, context, LANGUAGE, true); - pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); - break; - case 2: - current_bid = read_next_bid(env.console, context, LANGUAGE, false); - pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); - break; - case 3: - pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); - break; - case 4: - auction_ongoing = false; - break; - default: - break; - } - context.wait_for_all_requests(); - } - - if (won_auction){ - stats.m_auctions++; - if (current_bid >= 0){ - stats.m_money += current_bid; - } - env.update_stats(); - send_program_notification( - env, NOTIFICATION_AUCTION_WIN, - COLOR_GREEN, "Auction won!", - { - { "Item:", get_auction_item_name(offer.item).display_name() }, - { "Final Bid:", std::to_string(current_bid) }, - } - , "", offer_screen); - } - - return; -} - -void AuctionFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - -#if 0 - check_offers(env, context); - return; - -#else - AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 10, 0); - pbf_wait(context, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - uint8_t year = MAX_YEAR; - - - while (true){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - reset_auctions(env, context, true, year); - stats.m_resets++; - env.update_stats(); - - bool good_offer = false; - while (!good_offer){ - size_t npc_tries = 0; - if (!ONE_NPC){ - pbf_move_right_joystick(context, 128, 255, 2 * TICKS_PER_SECOND, 20); - } - - std::vector> offers = check_offers(env, context); - for (std::pair& offer_pair : offers){ - AuctionOffer offer = offer_pair.first; - if (is_good_offer(offer)){ - try{ - move_to_auctioneer(env, context, offer); - }catch (OperationFailedException& e){ - stats.m_errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - npc_tries++; - // if ONE_NPC the program already tries multiple times without change to compensate for dropped inputs - // at this point it is more likely to be non-recoverable - size_t max_npc_tries = ONE_NPC ? 1 : 3; - - if (npc_tries < max_npc_tries){ - VideoSnapshot screen = env.console.video().snapshot(); - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, e.message(), screen); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to talk to the NPC!", - env.console - ); - } - break; - } - - bid_on_item(env, context, offer); - reset_position(env, context); - - good_offer = true; - } - } - if (!good_offer){ - reset_auctions(env, context, false, year); - stats.m_resets++; - } - - env.update_stats(); - pbf_wait(context, 125); - context.wait_for_all_requests(); - } - } -#endif -} - - - - -} -} -} +/* Auction Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include +#include +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "Pokemon/Pokemon_Strings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/PokemonSV_AuctionItemNameReader.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Resources/PokemonSV_AuctionItemNames.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSV_AuctionFarmer.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +AuctionFarmer_Descriptor::AuctionFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:AuctionFarmer", + STRING_POKEMON + " SV", "Auction Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AuctionFarmer.md", + "Check auctions and bid on items.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +struct AuctionFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : m_resets(m_stats["Resets"]) + , m_auctions(m_stats["Auctions"]) + , m_money(m_stats["Spent Money"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Auctions"); + m_display_order.emplace_back("Spent Money"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_resets; + std::atomic& m_auctions; + std::atomic& m_money; + std::atomic& m_errors; +}; +std::unique_ptr AuctionFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +AuctionFarmer::AuctionFarmer() + : LANGUAGE( + "Game Language:
The language is needed to read which items are offered.", + AuctionItemNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TARGET_ITEMS("Items:
Multiple Items can be selected. The program will bid on any selected item which is offered.") + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_AUCTION_WIN("Auction Win", true, false, ImageAttachmentMode::JPG, {"Notifs"}) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_AUCTION_WIN, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options("Advanced Options: (developer only)") + , ONE_NPC("One NPC:
Check only the NPC you're standing in front of. (Multiple NPCs in development)", LockMode::LOCK_WHILE_RUNNING, true) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(TARGET_ITEMS); + PA_ADD_OPTION(NOTIFICATIONS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(ONE_NPC); + } +} + + +std::vector AuctionFarmer::detect_dialog_boxes(const ImageViewRGB32& screen){ + using namespace Kernels::Waterfill; + + uint32_t MIN_BORDER_THRESHOLD = 0xffc07000; + uint32_t MAX_BORDER_THRESHOLD = 0xffffc550; + + uint32_t MIN_YELLOW_THRESHOLD = 0xffd0b000; + uint32_t MAX_YELLOW_THRESHOLD = 0xffffff30; + + size_t width = screen.width(); + size_t height = screen.height(); + + + std::vector dialog_boxes; + { + PackedBinaryMatrix border_matrix = compress_rgb32_to_binary_range(screen, MIN_BORDER_THRESHOLD, MAX_BORDER_THRESHOLD); + + std::unique_ptr session = make_WaterfillSession(border_matrix); + auto iter = session->make_iterator(50); + WaterfillObject object; + while (iter->find_next(object, true)){ + // Discard objects touching the edge of the screen or bottom right corner where the map is located or if the object is too small + if (object.min_x == 0 || object.min_y == 0 // touching left or top edge + || object.max_x + 1 >= width || object.max_y + 1 >= height // touching right or bottom edge + || (object.max_x > width * 0.82 && object.max_y > height * 0.68) // touches mini map area + || object.width() < width * 0.0926 || object.height() < height * 0.0926 // object is too small + ){ + continue; + } + dialog_boxes.emplace_back(object); + +// static int c = 0; +// extract_box_reference(screen, object).save("image-" + std::to_string(c++) + ".png"); + +#if 1 + // check for yellow inside the orange border + ImagePixelBox border_pixel_box(object); +// ImageFloatBox border_float_box = pixelbox_to_floatbox(screen, border_pixel_box); + ImageViewRGB32 dialog = extract_box_reference(screen, border_pixel_box); + PackedBinaryMatrix yellow_matrix = compress_rgb32_to_binary_range(dialog, MIN_YELLOW_THRESHOLD, MAX_YELLOW_THRESHOLD); + + std::unique_ptr yellow_session = make_WaterfillSession(yellow_matrix); + auto yellow_iter = yellow_session->make_iterator(300); + WaterfillObject yellow_object; + while (yellow_iter->find_next(yellow_object, true)){ + // Discard small objects + if (object.width() < width * 0.0925 || object.height() < height * 0.0925){ + continue; + } + +// extract_box_reference(dialog, yellow_object).save("yellow-" + std::to_string(c++) + ".png"); + +// ImagePixelBox dialog_pixel_box(yellow_object); + ImagePixelBox dialog_pixel_box; + dialog_pixel_box.min_x = border_pixel_box.min_x + yellow_object.min_x; + dialog_pixel_box.min_y = border_pixel_box.min_y + yellow_object.min_y; + dialog_pixel_box.max_x = dialog_pixel_box.min_x + yellow_object.width(); + dialog_pixel_box.max_y = dialog_pixel_box.min_y + yellow_object.height(); + +// ImageFloatBox translated_dialog_box = translate_to_parent(screen, border_float_box, dialog_pixel_box); +// dialog_boxes.emplace_back(translated_dialog_box); + dialog_boxes.emplace_back(dialog_pixel_box); + } +#endif + } + } + return dialog_boxes; +} + + +void AuctionFarmer::reset_auctions(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool do_full_reset, uint8_t& year){ + try{ + if (do_full_reset){ + if (year == MAX_YEAR){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + PokemonSwSh::home_roll_date_enter_game_autorollback(env.console, context, year); + } + save_game_from_overworld(env.program_info(), env.console, context); + + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + PokemonSwSh::home_roll_date_enter_game_autorollback(env.console, context, year); + } + pbf_wait(context, 1 * TICKS_PER_SECOND); + + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + context.wait_for_all_requests(); + reset_game_from_home(env.program_info(), env.console, context, TICKS_PER_SECOND); + }catch (OperationFailedException& e){ + AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); + stats.m_errors++; + env.update_stats(); + throw FatalProgramException(std::move(e)); + } +} + +std::vector> AuctionFarmer::check_offers(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); + + pbf_wait(context, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + std::vector dialog_boxes = detect_dialog_boxes(screen); + std::deque bubbles_boxes; + std::deque offer_overlay_boxes; + std::vector> offers; + + if (dialog_boxes.empty()){ + stats.m_errors++; + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Could not detect any offer dialogs.", screen); + } + + // read dialog bubble + ImageFloatBox top_offer_box(0.05, 0.02, 0.90, 0.49); + ImageFloatBox bottom_offer_box(0.05, 0.49, 0.90, 0.49); + std::vector offer_boxes = {top_offer_box}; + if (LANGUAGE == Language::Spanish || LANGUAGE == Language::ChineseTraditional) { + offer_boxes.emplace_back(bottom_offer_box); + } + + for (ImagePixelBox dialog_box : dialog_boxes){ + for (ImageFloatBox offer_box : offer_boxes) { + // std::cout << "dialog_box: [" + // << dialog_box.min_x << "," << dialog_box.min_y << "] - [" + // << dialog_box.max_x << "," << dialog_box.max_y << "]" << std::endl; + + ImageFloatBox dialog_float_box = pixelbox_to_floatbox(screen, dialog_box); + bubbles_boxes.emplace_back(env.console, dialog_float_box, COLOR_GREEN); + + + // OverlayBoxScope dialog_overlay(env.console, dialog_box, COLOR_DARK_BLUE); + ImageFloatBox translated_offer_box = translate_to_parent( + screen, + dialog_float_box, + floatbox_to_pixelbox(dialog_box.width(), dialog_box.height(), offer_box) + ); + // std::cout << "translated_offer_box: [" + // << translated_offer_box.x << "," << translated_offer_box.y << "] - [" + // << translated_offer_box.width << "," << translated_offer_box.height << "]" << std::endl; + + offer_overlay_boxes.emplace_back(env.console, translated_offer_box, COLOR_BLUE); + + // OverlayBoxScope offer_overlay(env.console, translated_offer_box, COLOR_BLUE); + + ImageViewRGB32 dialog = extract_box_reference(screen, dialog_box); + ImageViewRGB32 offer_image = extract_box_reference(dialog, offer_box); + + // std::cout << offer_image.width() << " x " << offer_image.height() << std::endl; + + + const double LOG10P_THRESHOLD = -1.5; + std::string best_item; + OCR::StringMatchResult result = AuctionItemNameReader::instance().read_substring( + env.console, LANGUAGE, + offer_image, + OCR::BLACK_TEXT_FILTERS() + ); + + result.clear_beyond_log10p(LOG10P_THRESHOLD); + if (best_item.empty() && !result.results.empty()) { + auto iter = result.results.begin(); + if (iter->first < LOG10P_THRESHOLD) { + best_item = iter->second.token; + + AuctionOffer offer{ best_item }; + std::pair pair(offer, dialog_float_box); + offers.emplace_back(pair); + } + } + } + } +// context.wait_for(std::chrono::seconds(100)); + return offers; +} + +bool AuctionFarmer::is_good_offer(AuctionOffer offer){ + // Special handling for Japanese bottle cap items + bool any_bottle_cap = false; + if (LANGUAGE == Language::Japanese){ + any_bottle_cap = (offer.item == "bottle-cap" || offer.item == "gold-bottle-cap") + && (TARGET_ITEMS.find_item("bottle-cap") || TARGET_ITEMS.find_item("gold-bottle-cap")); + } + + return TARGET_ITEMS.find_item(offer.item) || any_bottle_cap ; +} + +// Move to auctioneer and interact +void AuctionFarmer::move_to_auctioneer(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer){ + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + + size_t tries = 0; + while (tries < 10){ + if (!ONE_NPC){ + move_dialog_to_center(env, context, offer); + pbf_move_left_joystick(context, 128, 0, 60, 10); + } + + pbf_press_button(context, BUTTON_A, 20, 100); + int ret = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); + + if (ret == 0){ + return; + } + tries++; + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Too many attempts to talk to the NPC.", + env.console + ); +} + +// Dialog is the only piece of orientation we have, so the goal is to put it into the center of the screen so we know in which direction the character walks. +// This is only used for multiple NPCs. +void AuctionFarmer::move_dialog_to_center(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer wanted){ + double center_x = 0.0f; + double center_y = 0.0f; + bool offer_visible = false; + + while (center_x < 0.43 || center_x > 0.57){ + context.wait_for_all_requests(); + std::vector> offers = check_offers(env, context); + + for (std::pair offer : offers){ + if (offer.first.item != wanted.item){ + continue; + } + offer_visible = true; + + center_x = offer.second.x + (0.5 * offer.second.width); + center_y = offer.second.y + (0.5 * offer.second.height); + + + // check whether the stop condition is fulfilled by now. + if (!(center_x < 0.43 || center_x > 0.57)){ + break; + } + + uint8_t distance_x = (uint8_t)(center_x * 255); + uint8_t distance_y = (uint8_t)(center_y * 255); + env.console.log(std::to_string(distance_x)); + env.console.log(std::to_string(distance_y)); + + pbf_move_right_joystick(context, distance_x, distance_y, 20, 20); + + break; + } + + if (!offer_visible){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Lost offer dialog for wanted item.", + env.console + ); + } + } +} + +void AuctionFarmer::reset_position(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (ONE_NPC){ + // No movement, player character should always be directly in front of an auctioneer. + return; + } + + // move backwards, TODO: check position(?) and orientation + pbf_move_left_joystick(context, 128, 255, 50, 20); + return; +} + + +uint64_t read_next_bid(VideoStream& stream, ProControllerContext& context, Language language, bool high){ + // How much to cut off from the bid text in order to not read currencies and exclamation marks as numbers. + // Values are pixels for a 1920x1080 screen, negative values are padding + static const std::map> cutoffs = { + { Language::English, {22, 6} }, + { Language::Japanese, {-5, 54} }, + { Language::Spanish, {6, 32} }, + { Language::French, {-5, 45} }, + { Language::German, {-5, 22} }, + { Language::Italian, {-5, 35} }, + { Language::Korean, {-5, 42} }, + { Language::ChineseSimplified, {22, 7} }, + { Language::ChineseTraditional, {22,7} } + }; + + static const std::map high_x = { + { Language::English, 0.75f }, + { Language::Japanese, 0.75f }, + { Language::Spanish, 0.73f }, + { Language::French, 0.68f }, + { Language::German, 0.73f }, + { Language::Italian, 0.75f }, + { Language::Korean, 0.75f }, + { Language::ChineseSimplified, 0.75f }, + { Language::ChineseTraditional, 0.75f } + }; + + static const std::map low_x = { + { Language::English, 0.75f }, + { Language::Japanese, 0.75f }, + { Language::Spanish, 0.75f }, + { Language::French, 0.75f }, + { Language::German, 0.73f }, + { Language::Italian, 0.75f }, + { Language::Korean, 0.75f }, + { Language::ChineseSimplified, 0.75f }, + { Language::ChineseTraditional, 0.75f } + }; + + float box_y = high ? 0.42f : 0.493f; + float box_x = high ? high_x.at(language) : low_x.at(language); + float width = 0.9f - box_x; // max_x is always the same for all languages + OverlayBoxScope box(stream.overlay(), { box_x, box_y, width, 0.048 }); + + std::unordered_map read_bids; + size_t highest_read = 0; + uint64_t read_value = 0; + + // read next bid multiple times since the selection arrow sometimes blocks the first digit + for (size_t i = 0; i < 10; i++){ + VideoSnapshot screen = stream.video().snapshot(); + double screen_scale = (double)screen->width() / 1920.0; + double vertical_padding = 5.0; // small amount of pixels so numbers do not touch the edge of the view when reading them + + ImageViewRGB32 raw_bid_image = extract_box_reference(screen, box); + ImagePixelBox bid_bounding_box = ImageMatch::enclosing_rectangle_with_pixel_filter( + raw_bid_image, + [](Color pixel) { + return (uint32_t)pixel.red() + pixel.green() + pixel.blue() < 250; + }); + + int32_t max_width = static_cast(raw_bid_image.width() - 1); + int32_t max_height = static_cast(raw_bid_image.height() - 1); + int32_t scaled_vertical_padding = static_cast(vertical_padding * screen_scale); + int32_t left_cutoff = static_cast(cutoffs.at(language).first * screen_scale); + int32_t right_cutoff = static_cast(cutoffs.at(language).second * screen_scale); + + ImagePixelBox cut_bid_bounding_box( + std::max(0, std::min(max_width, static_cast(bid_bounding_box.min_x) + left_cutoff)), + std::max(0, std::min(max_height, static_cast(bid_bounding_box.min_y) - scaled_vertical_padding)), + std::max(0, std::min(max_width, static_cast(bid_bounding_box.max_x) - right_cutoff)), + std::max(0, std::min(max_height, static_cast(bid_bounding_box.max_y) + scaled_vertical_padding)) + ); + + uint64_t read_bid = OCR::read_number(stream.logger(), extract_box_reference(raw_bid_image, cut_bid_bounding_box)); + + if (read_bids.find(read_bid) == read_bids.end()){ + read_bids[read_bid] = 0; + } + read_bids[read_bid] += 1; + + if (read_bids[read_bid] > highest_read){ + highest_read = read_bids[read_bid]; + read_value = read_bid; + } + context.wait_for(Milliseconds(20)); + } + + stream.log("Next bid: " + std::to_string(read_value)); + return read_value; +} + +void AuctionFarmer::bid_on_item(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer){ + AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); + + VideoSnapshot offer_screen = env.console.video().snapshot(); + + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + PromptDialogWatcher high_detector(COLOR_RED, { 0.50, 0.40, 0.40, 0.082 }); + PromptDialogWatcher mid_detector(COLOR_PURPLE, { 0.50, 0.475, 0.40, 0.082 }); + PromptDialogWatcher low_detector(COLOR_PURPLE, { 0.50, 0.55, 0.40, 0.082 }); + OverworldWatcher overworld_detector(env.console, COLOR_BLUE); + bool won_auction = true; + bool auction_ongoing = true; + int64_t current_bid = 0; + + context.wait_for_all_requests(); + while (auction_ongoing){ + int ret = wait_until(env.console, context, Milliseconds(5000), { advance_detector, high_detector, mid_detector, low_detector, overworld_detector }); + context.wait_for(Milliseconds(100)); + + switch (ret){ + case 0: + pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); + break; + case 1: + current_bid = read_next_bid(env.console, context, LANGUAGE, true); + pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); + break; + case 2: + current_bid = read_next_bid(env.console, context, LANGUAGE, false); + pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); + break; + case 3: + pbf_press_button(context, BUTTON_A, 20, TICKS_PER_SECOND); + break; + case 4: + auction_ongoing = false; + break; + default: + break; + } + context.wait_for_all_requests(); + } + + if (won_auction){ + stats.m_auctions++; + if (current_bid >= 0){ + stats.m_money += current_bid; + } + env.update_stats(); + send_program_notification( + env, NOTIFICATION_AUCTION_WIN, + COLOR_GREEN, "Auction won!", + { + { "Item:", get_auction_item_name(offer.item).display_name() }, + { "Final Bid:", std::to_string(current_bid) }, + } + , "", offer_screen); + } + + return; +} + +void AuctionFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + +#if 0 + check_offers(env, context); + return; + +#else + AuctionFarmer_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 10, 0); + pbf_wait(context, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + uint8_t year = MAX_YEAR; + + + while (true){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + reset_auctions(env, context, true, year); + stats.m_resets++; + env.update_stats(); + + bool good_offer = false; + while (!good_offer){ + size_t npc_tries = 0; + if (!ONE_NPC){ + pbf_move_right_joystick(context, 128, 255, 2 * TICKS_PER_SECOND, 20); + } + + std::vector> offers = check_offers(env, context); + for (std::pair& offer_pair : offers){ + AuctionOffer offer = offer_pair.first; + if (is_good_offer(offer)){ + try{ + move_to_auctioneer(env, context, offer); + }catch (OperationFailedException& e){ + stats.m_errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + npc_tries++; + // if ONE_NPC the program already tries multiple times without change to compensate for dropped inputs + // at this point it is more likely to be non-recoverable + size_t max_npc_tries = ONE_NPC ? 1 : 3; + + if (npc_tries < max_npc_tries){ + VideoSnapshot screen = env.console.video().snapshot(); + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, e.message(), screen); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to talk to the NPC!", + env.console + ); + } + break; + } + + bid_on_item(env, context, offer); + reset_position(env, context); + + good_offer = true; + } + } + if (!good_offer){ + reset_auctions(env, context, false, year); + stats.m_resets++; + } + + env.update_stats(); + pbf_wait(context, 125); + context.wait_for_all_requests(); + } + } +#endif +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h index 2a6983aaf6..222f77882b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_AuctionFarmer.h @@ -1,70 +1,70 @@ -/* Auction Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AuctionFarmer_H -#define PokemonAutomation_PokemonSV_AuctionFarmer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSV/Options/PokemonSV_AuctionItemTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -struct AuctionOffer{ - std::string item; -}; - -class AuctionFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AuctionFarmer_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class AuctionFarmer : public SingleSwitchProgramInstance{ -public: - AuctionFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - OCR::LanguageOCROption LANGUAGE; - AuctionItemTable TARGET_ITEMS; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_AUCTION_WIN; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - BooleanCheckBoxOption ONE_NPC; - - std::vector detect_dialog_boxes(const ImageViewRGB32& screen); - void reset_auctions(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool do_full_reset, uint8_t& year); - std::vector> check_offers(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void move_to_auctioneer(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer wanted); - void move_dialog_to_center(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer); - void bid_on_item(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer); - bool is_good_offer(AuctionOffer); - void reset_position(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - - - - -} -} -} -#endif +/* Auction Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AuctionFarmer_H +#define PokemonAutomation_PokemonSV_AuctionFarmer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSV/Options/PokemonSV_AuctionItemTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +struct AuctionOffer{ + std::string item; +}; + +class AuctionFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AuctionFarmer_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class AuctionFarmer : public SingleSwitchProgramInstance{ +public: + AuctionFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + OCR::LanguageOCROption LANGUAGE; + AuctionItemTable TARGET_ITEMS; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_AUCTION_WIN; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + BooleanCheckBoxOption ONE_NPC; + + std::vector detect_dialog_boxes(const ImageViewRGB32& screen); + void reset_auctions(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool do_full_reset, uint8_t& year); + std::vector> check_offers(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void move_to_auctioneer(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer wanted); + void move_dialog_to_center(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer); + void bid_on_item(SingleSwitchProgramEnvironment& env, ProControllerContext& context, AuctionOffer offer); + bool is_good_offer(AuctionOffer); + void reset_position(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp index 295d882753..6afe378292 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.cpp @@ -1,180 +1,180 @@ -/* BBQ Solo Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h" -#include "PokemonSV_BBQSoloFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -BBQSoloFarmer_Descriptor::BBQSoloFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:BBQSoloFarmer", - STRING_POKEMON + " SV", "BBQ Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/BBQSoloFarmer.md", - "Farm Blueberry Quests in the Terarium for BP.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} -struct BBQSoloFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : questsCompleted(m_stats["Quests Completed"]) - , saves(m_stats["Saves"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Quests Completed"); - m_display_order.emplace_back("Saves"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& questsCompleted; - std::atomic& saves; - std::atomic& errors; -}; -std::unique_ptr BBQSoloFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} -BBQSoloFarmer::BBQSoloFarmer() - : GO_HOME_WHEN_DONE(true) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - & NOTIFICATION_PROGRAM_FINISH, - & NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(BBQ_OPTIONS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void BBQSoloFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - BBQSoloFarmer_Descriptor::Stats& stats = env.current_stats(); - - //Make sure console type is set - if (env.console.state().console_type() == ConsoleType::Unknown) { - throw UserSetupError(env.console, "Console Type (Switch 1 or 2) must be specified."); - } - - //Fly to plaza - open_map_from_overworld(env.program_info(), env.console, context); - fly_to_overworld_from_map(env.program_info(), env.console, context); - - std::vector quest_list; //all quests - std::vector quests_to_do; //do-able quests - uint8_t eggs_hatched = 0; //Track eggs - uint64_t num_completed_quests = 0; - - //Test a specific quest - /* - BBQuests test_quest = BBQuests::catch_water; - bool questTest = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, test_quest, eggs_hatched); - if (questTest){ - env.log("Finished quest."); - } - */ - - while (num_completed_quests < BBQ_OPTIONS.NUM_QUESTS){ - if (BBQ_OPTIONS.OUT_OF_EGGS == BBQOption::OOEggs::Stop && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ - env.log("Stop when out of eggs selected. Stopping program."); - break; - } - - //Get and reroll quests until we can at least one - while (quests_to_do.size() < 1){ - quest_list = read_quests(env.program_info(), env.console, context, BBQ_OPTIONS); - quests_to_do = process_quest_list(env.program_info(), env.console, context, BBQ_OPTIONS, quest_list, eggs_hatched); - - //Clear out the regular quest list. - quest_list.clear(); - } - - for (auto current_quest : quests_to_do){ - //Check if quest was already completed (ex. 500 meters completed while navigating to take a photo) - quest_list = read_quests(env.program_info(), env.console, context, BBQ_OPTIONS); - if (std::find(quest_list.begin(), quest_list.end(), current_quest) != quest_list.end()){ - env.log("Current quest exists on list. Doing quest."); - bool questSuccess = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, current_quest, eggs_hatched); - if (questSuccess){ - env.log("Quest completed successfully."); - stats.questsCompleted++; - env.update_stats(); - num_completed_quests++; - }else{ - env.log("Quest did not complete successfully."); - } - }else{ - //Note: This doesn't account for case such as "sneak up" being added and then completed alongside the next quest - env.log("Current quest does not exist on list. Quest completed at some point."); - stats.questsCompleted++; - env.update_stats(); - num_completed_quests++; - } - quest_list.clear(); - } - //Clear out the todo list - quests_to_do.clear(); - - //Fix the time to prevent running out of years - pbf_wait(context, 250); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - - uint64_t temp_save_num_option = BBQ_OPTIONS.SAVE_NUM_QUESTS; - if (temp_save_num_option != 0 && num_completed_quests % temp_save_num_option == 0){ - env.log("Saving and resetting."); - save_game_from_overworld(env.program_info(), env.console, context); - reset_game(env.program_info(), env.console, context); - stats.saves++; - } - - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - env.update_stats(); - - if (BBQ_OPTIONS.FIX_TIME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - - open_map_from_overworld(env.program_info(), env.console, context); - fly_to_overworld_from_map(env.program_info(), env.console, context); - } - - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* BBQ Solo Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h" +#include "PokemonSV_BBQSoloFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +BBQSoloFarmer_Descriptor::BBQSoloFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:BBQSoloFarmer", + STRING_POKEMON + " SV", "BBQ Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/BBQSoloFarmer.md", + "Farm Blueberry Quests in the Terarium for BP.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} +struct BBQSoloFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : questsCompleted(m_stats["Quests Completed"]) + , saves(m_stats["Saves"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Quests Completed"); + m_display_order.emplace_back("Saves"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& questsCompleted; + std::atomic& saves; + std::atomic& errors; +}; +std::unique_ptr BBQSoloFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} +BBQSoloFarmer::BBQSoloFarmer() + : GO_HOME_WHEN_DONE(true) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + & NOTIFICATION_PROGRAM_FINISH, + & NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(BBQ_OPTIONS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void BBQSoloFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + BBQSoloFarmer_Descriptor::Stats& stats = env.current_stats(); + + //Make sure console type is set + if (env.console.state().console_type() == ConsoleType::Unknown) { + throw UserSetupError(env.console, "Console Type (Switch 1 or 2) must be specified."); + } + + //Fly to plaza + open_map_from_overworld(env.program_info(), env.console, context); + fly_to_overworld_from_map(env.program_info(), env.console, context); + + std::vector quest_list; //all quests + std::vector quests_to_do; //do-able quests + uint8_t eggs_hatched = 0; //Track eggs + uint64_t num_completed_quests = 0; + + //Test a specific quest + /* + BBQuests test_quest = BBQuests::catch_water; + bool questTest = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, test_quest, eggs_hatched); + if (questTest){ + env.log("Finished quest."); + } + */ + + while (num_completed_quests < BBQ_OPTIONS.NUM_QUESTS){ + if (BBQ_OPTIONS.OUT_OF_EGGS == BBQOption::OOEggs::Stop && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ + env.log("Stop when out of eggs selected. Stopping program."); + break; + } + + //Get and reroll quests until we can at least one + while (quests_to_do.size() < 1){ + quest_list = read_quests(env.program_info(), env.console, context, BBQ_OPTIONS); + quests_to_do = process_quest_list(env.program_info(), env.console, context, BBQ_OPTIONS, quest_list, eggs_hatched); + + //Clear out the regular quest list. + quest_list.clear(); + } + + for (auto current_quest : quests_to_do){ + //Check if quest was already completed (ex. 500 meters completed while navigating to take a photo) + quest_list = read_quests(env.program_info(), env.console, context, BBQ_OPTIONS); + if (std::find(quest_list.begin(), quest_list.end(), current_quest) != quest_list.end()){ + env.log("Current quest exists on list. Doing quest."); + bool questSuccess = process_and_do_quest(env, env.console, context, BBQ_OPTIONS, current_quest, eggs_hatched); + if (questSuccess){ + env.log("Quest completed successfully."); + stats.questsCompleted++; + env.update_stats(); + num_completed_quests++; + }else{ + env.log("Quest did not complete successfully."); + } + }else{ + //Note: This doesn't account for case such as "sneak up" being added and then completed alongside the next quest + env.log("Current quest does not exist on list. Quest completed at some point."); + stats.questsCompleted++; + env.update_stats(); + num_completed_quests++; + } + quest_list.clear(); + } + //Clear out the todo list + quests_to_do.clear(); + + //Fix the time to prevent running out of years + pbf_wait(context, 250); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + + uint64_t temp_save_num_option = BBQ_OPTIONS.SAVE_NUM_QUESTS; + if (temp_save_num_option != 0 && num_completed_quests % temp_save_num_option == 0){ + env.log("Saving and resetting."); + save_game_from_overworld(env.program_info(), env.console, context); + reset_game(env.program_info(), env.console, context); + stats.saves++; + } + + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + env.update_stats(); + + if (BBQ_OPTIONS.FIX_TIME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + + open_map_from_overworld(env.program_info(), env.console, context); + fly_to_overworld_from_map(env.program_info(), env.console, context); + } + + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h index 5fd00542fa..1db1ff6544 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BBQSoloFarmer.h @@ -1,44 +1,44 @@ -/* BBQ Solo Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BBQSoloFarmer_H -#define PokemonAutomation_PokemonSV_BBQSoloFarmer_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_BBQOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class BBQSoloFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BBQSoloFarmer_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class BBQSoloFarmer : public SingleSwitchProgramInstance{ -public: - BBQSoloFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - BBQOption BBQ_OPTIONS; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif +/* BBQ Solo Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BBQSoloFarmer_H +#define PokemonAutomation_PokemonSV_BBQSoloFarmer_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_BBQOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class BBQSoloFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BBQSoloFarmer_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class BBQSoloFarmer : public SingleSwitchProgramInstance{ +public: + BBQSoloFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + BBQOption BBQ_OPTIONS; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp index c7b24958f2..51249f88dd 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.cpp @@ -1,1054 +1,1054 @@ -/* Blueberry Catch Photo - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV/Programs/PokemonSV_Terarium.h" -#include "PokemonSV_BlueberryQuests.h" - -#include -#include "PokemonSV_BlueberryCatchPhoto.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -CameraAngle quest_photo_navi( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - CameraAngle angle = CameraAngle::none; - - //Navigate to target - switch (current_quest){ - case BBQuests::photo_fly: case BBQuests::photo_psychic: - console.log("Photo: In-flight/Psychic"); - - //Polar Rest Area - targeting Duosion fixed spawn - central_to_polar_rest(info, console, context); - - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 128, 0, 230, 20); - pbf_move_left_joystick(context, 0, 128, 250, 20); - - break; - case BBQuests::photo_swim: case BBQuests::photo_water: case BBQuests::photo_polar: - console.log("Photo: Swimming/Water/Polar"); - - //Polar Outdoor Classroom 1 - fixed Horsea - central_to_polar_class1(info, console, context); - - pbf_wait(context, 200); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 255, 50, 180, 20); - - angle = CameraAngle::down; - - break; - case BBQuests::photo_coastal: case BBQuests::photo_grass: case BBQuests::photo_dragon: - console.log("Photo: Coastal/Grass/Dragon"); - - //Coastal Plaza - Exeggutor-A - central_to_coastal_plaza(info, console, context); - - pbf_move_left_joystick(context, 0, 115, 400, 20); - - //Jump down - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - ssf_press_button(context, BUTTON_B, 0ms, 800ms); - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); - ssf_press_button(context, BUTTON_B, 0ms, 160ms); - - pbf_wait(context, 100); - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 0, 150, 20); - pbf_press_button(context, BUTTON_B, 20, 20); - pbf_wait(context, 200); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - context.wait_for_all_requests(); - - break; - case BBQuests::photo_canyon: case BBQuests::photo_ghost: case BBQuests::photo_ground: - console.log("Photo: Canyon/Ghost/Ground"); - - //Canyon Plaza - Golett - central_to_canyon_plaza(info, console, context); - - pbf_move_left_joystick(context, 210, 128, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 250, 400); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - break; - case BBQuests::photo_savanna: case BBQuests::photo_normal: case BBQuests::photo_fire: - console.log("Photo: Normal/Fire"); - - //Savanna Plaza - Pride Rock - central_to_savanna_plaza(info, console, context); - - pbf_move_left_joystick(context, 220, 255, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 400, 400); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 255, 128, 20, 50); - - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 100, 50); - pbf_move_left_joystick(context, 0, 0, 20, 50); - - break; - case BBQuests::photo_bug: case BBQuests::photo_rock: - console.log("Photo: Bug/Rock"); - - //Kleavor - central_to_canyon_plaza(info, console, context); - - pbf_move_left_joystick(context, 205, 64, 20, 105); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1500, 300); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - break; - case BBQuests::photo_fairy: - console.log("Photo: Fairy"); - - //Snubbull - Central plaza - open_map_from_overworld(info, console, context); - fly_to_overworld_from_map(info, console, context); - - pbf_move_left_joystick(context, 0, 80, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 2000, 1500, 200); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 255, 0, 10, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - - angle = CameraAngle::down; - break; - case BBQuests::photo_ice: - console.log("Photo: Ice"); - - //Snover - Start at central plaza, fly north-ish - open_map_from_overworld(info, console, context); - fly_to_overworld_from_map(info, console, context); - - pbf_move_left_joystick(context, 0, 0, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1100, 1700, 200); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 0, 128, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - - break; - case BBQuests::photo_flying: case BBQuests::photo_dark: - console.log("Photo: Dark/Flying"); - - //Vullaby/Mandibuzz - central_to_savanna_plaza(info, console, context); - - pbf_move_left_joystick(context, 255, 0, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 128, 0, 550, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 128, 0, 150, 20); - - pbf_move_left_joystick(context, 255, 128, 10, 20); - - angle = CameraAngle::down; - break; - case BBQuests::photo_electric: - console.log("Photo: Electric"); - - //Electabuzz - central_to_canyon_rest(info, console, context); - - pbf_move_left_joystick(context, 255, 255, 10, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 400, 20); - - break; - case BBQuests::photo_fighting: - console.log("Photo: Fighting"); - - //Hitmontop (TERA ICE) - Canyon Plaza or Classroom - central_to_canyon_plaza(info, console, context); - pbf_move_left_joystick(context, 0, 128, 400, 20); - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 0, 100, 20, 50); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 800); - - pbf_press_button(context, BUTTON_PLUS, 20, 100); - context.wait_for_all_requests(); - - break; - case BBQuests::photo_poison: - console.log("Photo: Poison"); - - //Muk-A - area a bit laggy but consistently so - central_to_coastal_plaza(info, console, context); - pbf_move_left_joystick(context, 0, 128, 20, 50); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - if (console.state().console_type() == ConsoleType::Switch1) { - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1400, 300); - } else { //Switch 2 - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1300, 300); - } - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 128, 0, 150, 50); - pbf_move_left_joystick(context, 180, 0, 20, 50); - pbf_wait(context, 200); //Give it time to spawn/load. - context.wait_for_all_requests(); - - angle = CameraAngle::down; - - break; - case BBQuests::photo_steel: - console.log("Photo: Steel"); - - //Dugtrio-A - area a bit laggy but should work most of the time - central_to_coastal_plaza(info, console, context); - pbf_move_left_joystick(context, 0, 128, 20, 50); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - if (console.state().console_type() == ConsoleType::Switch1) { - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 575, 200); - } else { //Switch 2 - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 200); - } - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 0, 128, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid photo quest.", - console - ); - break; - } - - return angle; -} - -void quest_photo( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - bool took_photo = false; - CameraAngle move_camera = CameraAngle::none; - - while(!took_photo){ - EncounterWatcher encounter_watcher(console, COLOR_RED); - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - - move_camera = quest_photo_navi(info, console, context, BBQ_OPTIONS, current_quest); - - //Take photo. - console.log("Taking photo."); - PromptDialogWatcher photo_prompt(COLOR_RED); - OverworldWatcher overworld(console.logger(), COLOR_BLUE); - - pbf_press_dpad(context, DPAD_DOWN, 50, 20); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - if (move_camera == CameraAngle::up){ - pbf_move_right_joystick(context, 128, 0, 50, 20); - }else if (move_camera == CameraAngle::down){ - pbf_move_right_joystick(context, 128, 255, 50, 20); - } - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_A, 20, 50); - - int ret = wait_until( - console, context, - std::chrono::seconds(10), - { photo_prompt } - ); - if (ret != 0){ - console.log("Photo not taken."); - } - - //Mash B until overworld - int exit = run_until( - console, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 2000); - }, - {{ overworld }} - ); - if (exit == 0){ - console.log("Overworld detected."); - } - took_photo = true; - context.wait_for_all_requests(); - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - - if (ret >= 0){ - console.log("Battle menu detected."); - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - console.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - console.log("Detected battle. Running from battle and returning to plaza."); - try{ - //Smoke Ball or Flying type required due to Arena Trap/Magnet Pull - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - battle_menu.move_to_slot(console, context, 3); - pbf_press_button(context, BUTTON_A, 10, 50); - press_Bs_to_back_to_overworld(info, console, context); - return_to_plaza(info, console, context); - }catch (...){ - console.log("Unable to flee."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to flee!", - console - ); - } - } - } - } - context.wait_for_all_requests(); - return_to_plaza(info, console, context); -} - -void quest_catch_navi( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - switch (current_quest){ - case BBQuests::catch_any: case BBQuests::catch_normal: case BBQuests::catch_fire: - console.log("Catch: Any/Normal/Fire"); - - //Savanna Plaza - Pride Rock - central_to_savanna_plaza(info, console, context); - - pbf_move_left_joystick(context, 220, 255, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 400, 400); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 255, 128, 20, 50); - - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 100, 50); - - pbf_move_left_joystick(context, 0, 0, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - - break; - - case BBQuests::catch_psychic: - console.log("Catch: Psychic"); - - //Polar Rest Area - targeting Duosion fixed spawn - central_to_polar_rest(info, console, context); - - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 128, 0, 230, 20); - pbf_move_left_joystick(context, 0, 128, 250, 20); - - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 150, 20); - - break; - - case BBQuests::catch_grass: case BBQuests::catch_dragon: - console.log("Catch: Grass/Dragon"); - - //Coastal Plaza - Exeggutor-A - central_to_coastal_plaza(info, console, context); - - pbf_move_left_joystick(context, 0, 115, 400, 20); - - //Jump down - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - ssf_press_button(context, BUTTON_B, 0ms, 800ms); - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); - ssf_press_button(context, BUTTON_B, 0ms, 160ms); - - pbf_wait(context, 100); - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 0, 350, 20); - pbf_press_button(context, BUTTON_B, 20, 20); - pbf_wait(context, 200); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - break; - case BBQuests::catch_ghost: case BBQuests::catch_ground: - console.log("Catch: Ghost/Ground"); - - //Canyon Plaza - Golett - central_to_canyon_plaza(info, console, context); - - pbf_move_left_joystick(context, 210, 128, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 300, 400); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 0, 0, 10, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 50, 20); - - break; - case BBQuests::catch_fairy: - console.log("Catch: Fairy"); - - //Snubbull - Central plaza - //Tested while snowing, seems fine? - open_map_from_overworld(info, console, context); - fly_to_overworld_from_map(info, console, context); - - pbf_move_left_joystick(context, 0, 80, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 2000, 1500, 200); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 255, 0, 10, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - - break; - case BBQuests::catch_fighting: - console.log("Catch: Fighting"); - - //Hitmontop (TERA ICE) - Canyon Plaza or Classroom - central_to_canyon_plaza(info, console, context); - pbf_move_left_joystick(context, 0, 128, 400, 20); - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 0, 100, 20, 50); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 800); - - break; - - case BBQuests::catch_bug: - console.log("Catch: Bug"); - - central_to_canyon_plaza(info, console, context); - - pbf_move_left_joystick(context, 205, 64, 20, 105); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1650, 500); - break; - case BBQuests::catch_dark: case BBQuests::catch_flying: - console.log("Catch: Dark/Flying"); - - //Vullaby/Mandibuzz - central_to_savanna_plaza(info, console, context); - - pbf_move_left_joystick(context, 255, 40, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 128, 0, 500, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - pbf_move_left_joystick(context, 255, 0, 10, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - - if (console.state().console_type() == ConsoleType::Switch1) { - pbf_move_left_joystick(context, 128, 0, 200, 20); - } else { - pbf_move_left_joystick(context, 128, 0, 170, 20); - } - - pbf_press_button(context, BUTTON_L, 20, 50); - - pbf_move_left_joystick(context, 0, 0, 10, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - - if (console.state().console_type() == ConsoleType::Switch1) { - pbf_move_left_joystick(context, 128, 0, 100, 20); - } else { - pbf_move_left_joystick(context, 128, 0, 120, 20); - } - pbf_wait(context, 400); - context.wait_for_all_requests(); - - break; - case BBQuests::catch_rock: case BBQuests::catch_electric: - console.log("Catch: Rock/Electric"); - - //Geodude-A - open_map_from_overworld(info, console, context); - fly_to_overworld_from_map(info, console, context); - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 70, 0, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 100, 550, 300); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_wait(context, 300); - context.wait_for_all_requests(); - - break; - case BBQuests::catch_steel: - console.log("Catch: Steel"); - - //Dugtrio-A - area a bit laggy but should work most of the time - central_to_coastal_plaza(info, console, context); - pbf_move_left_joystick(context, 0, 128, 20, 50); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - if (console.state().console_type() == ConsoleType::Switch1) { - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 575, 200); - } else { //Switch 2 - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 200); - } - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 0, 128, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 50, 50); - - break; - case BBQuests::catch_poison: - console.log("Catch: Poison"); - - //Muk-A - area a bit laggy but consistently so - central_to_coastal_plaza(info, console, context); - pbf_move_left_joystick(context, 0, 128, 20, 50); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - if (console.state().console_type() == ConsoleType::Switch1) { - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1800, 300); - } else { - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1600, 300); - } - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - //Extra throws for this one - ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); - ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); - ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); - pbf_wait(context, 200); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_ZR, 20, 50); //Withdraw pokemon - - pbf_move_left_joystick(context, 255, 128, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); - ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); - ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); - pbf_wait(context, 200); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_ZR, 20, 50); //Withdraw pokemon - - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 255, 128, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - - break; - case BBQuests::catch_water: case BBQuests::catch_ice: - console.log("Catch: Water/Ice"); - - //Lapras - Tera Bug - central_to_polar_rest(info, console, context); - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 128, 0, 230, 20); - pbf_move_left_joystick(context, 0, 128, 300, 20); - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 20, 0, 20, 50); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 700, 1700, 300); - - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid catch quest.", - console - ); - break; - } - - //Lock on and throw ball - ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); - ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); - ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); - - pbf_wait(context, 300); - context.wait_for_all_requests(); - -} - -void quest_catch_throw_ball( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - Language language, - const std::string& selected_ball -){ - BattleBallReader reader(console, language); - std::string ball_reader = ""; - WallClock start = current_time(); - - console.log("Opening ball menu..."); - while (ball_reader == ""){ - if (current_time() - start > std::chrono::minutes(2)){ - console.log("Timed out trying to read ball after 2 minutes.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out trying to read ball after 2 minutes.", - console - ); - } - - //Mash B to exit anything else - pbf_mash_button(context, BUTTON_B, 125); - context.wait_for_all_requests(); - - //Press X to open Ball menu - pbf_press_button(context, BUTTON_X, 20, 100); - context.wait_for_all_requests(); - - VideoSnapshot screen = console.video().snapshot(); - ball_reader = reader.read_ball(screen); - } - - console.log("Selecting ball."); - int quantity = move_to_ball(reader, console, context, selected_ball); - if (quantity == 0){ - console.log("Unable to find ball."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find ball.", - console - ); - } - if (quantity < 0){ - console.log("Unable to read ball quantity.", COLOR_RED); - } - - //Throw ball - console.log("Throwing ball."); - pbf_mash_button(context, BUTTON_A, 150); - context.wait_for_all_requests(); - - pbf_mash_button(context, BUTTON_B, 900); - context.wait_for_all_requests(); -} - -void quest_catch_handle_battle( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - console.log("Catching Pokemon."); - AdvanceDialogWatcher advance_dialog(COLOR_MAGENTA); - PromptDialogWatcher add_to_party(COLOR_PURPLE); - OverworldWatcher overworld(console.logger(), COLOR_RED); - - uint8_t switch_party_slot = 1; - bool quickball_thrown = false; - bool tera_target = false; - bool use_quickball = BBQ_OPTIONS.QUICKBALL; - - int ret2 = run_until( - console, context, - [&](ProControllerContext& context){ - while (true){ - //Check that battle menu appears - this is in case of swapping pokemon - NormalBattleMenuWatcher menu_before_throw(COLOR_YELLOW); - int bMenu = wait_until( - console, context, - std::chrono::seconds(15), - { menu_before_throw } - ); - if (bMenu < 0){ - console.log("Unable to find menu_before_throw."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find menu_before_throw.", - console - ); - } - - //Check for catch menu - if none it is a tera pokemon - console.log("Checking for ball menu."); - BattleBallReader exists(console, BBQ_OPTIONS.LANGUAGE); - std::string ball_exists = ""; - - pbf_press_button(context, BUTTON_X, 20, 100); - context.wait_for_all_requests(); - - VideoSnapshot screen_ball = console.video().snapshot(); - ball_exists = exists.read_ball(screen_ball); - - if (ball_exists == ""){ - console.log("Could not find ball reader. Tera battle. Using first attack."); - pbf_mash_button(context, BUTTON_B, 125); - context.wait_for_all_requests(); - - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - tera_target = true; - }else{ - //Quick ball occurs before anything else in battle. - //Do not throw if target is a tera pokemon. - if (use_quickball && !quickball_thrown && tera_target == false){ - console.log("Quick Ball option checked. Throwing Quick Ball."); - quest_catch_throw_ball(info, console, context, BBQ_OPTIONS.LANGUAGE, "quick-ball"); - quickball_thrown = true; - }else{ - console.log("Throwing selected ball."); - quest_catch_throw_ball(info, console, context, BBQ_OPTIONS.LANGUAGE, BBQ_OPTIONS.BALL_SELECT.slug()); - } - - //Check for battle menu, if found use fourth attack this turn - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret = wait_until( - console, context, - std::chrono::seconds(4), - { battle_menu } - ); - if (ret == 0){ - console.log("Battle menu detected early. Using fourth attack."); - MoveSelectWatcher move_watcher(COLOR_BLUE); - MoveSelectDetector move_select(COLOR_BLUE); - - int ret_move_select = run_until( - console, context, - [&](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - }, - { move_watcher } - ); - if (ret_move_select != 0){ - console.log("Could not find move select."); - }else{ - console.log("Move select found!"); - } - - context.wait_for_all_requests(); - move_select.move_to_slot(console, context, 3); - pbf_mash_button(context, BUTTON_A, 150); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - //Check for battle menu - //If found after a second, assume out of PP and stop as this is a setup issue - //None of the target pokemon for this program have disable, taunt, etc. - NormalBattleMenuWatcher battle_menu2(COLOR_YELLOW); - int ret3 = wait_until( - console, context, - std::chrono::seconds(4), - { battle_menu2 } - ); - if (ret3 == 0){ - console.log("Battle menu detected early. Out of PP/No move in slot, please check your setup."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Battle menu detected early. Out of PP, please check your setup.", - console - ); - } - }else{ - //Wild pokemon's turn/wait for catch animation - pbf_mash_button(context, BUTTON_B, 900); - context.wait_for_all_requests(); - } - } - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - GradientArrowWatcher fainted(COLOR_BLUE, GradientArrowType::RIGHT, {0.610, 0.523, 0.044, 0.079}); - SwapMenuWatcher swap(COLOR_YELLOW); - int ret2_run = wait_until( - console, context, - std::chrono::seconds(60), - { battle_menu, fainted } - ); - switch (ret2_run){ - case 0: - console.log("Battle menu detected, continuing."); - break; - case 1: - console.log("Detected fainted Pokemon. Switching to next living Pokemon..."); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - if (swap.move_to_slot(console, context, switch_party_slot)){ - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - switch_party_slot++; - } - break; - default: - console.log("Invalid state ret2_run. Out of moves?"); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state ret2_run. Out of moves?", - console - ); - } - - } - }, - { advance_dialog, add_to_party, overworld } - ); - - switch (ret2){ - case 0: - console.log("Advance Dialog detected."); - press_Bs_to_back_to_overworld(info, console, context); - break; - case 1: - console.log("Prompt dialog detected."); - press_Bs_to_back_to_overworld(info, console, context); - break; - case 2: - console.log("Overworld detected."); - break; - default: - console.log("Invalid state in run_battle()."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state in run_battle().", - console - ); - } -} - -void quest_catch( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - EncounterWatcher encounter_watcher(console, COLOR_RED); - - //Navigate to target and start battle - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - - quest_catch_navi(info, console, context, BBQ_OPTIONS, current_quest); - context.wait_for_all_requests(); - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret2 = wait_until( - console, context, - std::chrono::seconds(25), - { battle_menu } - ); - if (ret2 != 0){ - console.log("Did not enter battle. Did target spawn?"); - } - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - - if (ret >= 0){ - console.log("Battle menu detected."); - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - console.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - quest_catch_handle_battle(info, console, context, BBQ_OPTIONS, current_quest); - } - } - - return_to_plaza(info, console, context); - - //Day skip and attempt to respawn fixed encounters - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, true); - roll_date_forward_1(console, context, true); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - - //Heal up and then reset position again. - OverworldWatcher done_healing(console.logger(), COLOR_BLUE); - pbf_move_left_joystick(context, 128, 0, 100, 20); - - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - int exit = run_until( - console, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 2000); - }, - {{ done_healing }} - ); - if (exit == 0){ - console.log("Overworld detected."); - } - open_map_from_overworld(info, console, context); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(info, console, context); - context.wait_for_all_requests(); -} - -void wild_battle_tera( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - bool& tera_self -){ - AdvanceDialogWatcher lost(COLOR_YELLOW); - OverworldWatcher overworld(console.logger(), COLOR_RED); - WallClock start = current_time(); - uint8_t switch_party_slot = 1; - bool first_turn = true; - - int ret2 = run_until( - console, context, - [&](ProControllerContext& context){ - while(true){ - if (current_time() - start > std::chrono::minutes(5)){ - console.log("Timed out during battle after 5 minutes.", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle after 5 minutes.", - console - ); - } - - if (first_turn && tera_self){ - console.log("Turn 1: Tera."); - //Open move menu - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_R, 20, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - - first_turn = false; - } - - NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); - GradientArrowWatcher fainted(COLOR_BLUE, GradientArrowType::RIGHT, {0.610, 0.523, 0.044, 0.079}); - SwapMenuWatcher swap(COLOR_YELLOW); - - context.wait_for_all_requests(); - - int ret3 = wait_until( - console, context, - std::chrono::seconds(90), - { battle_menu, fainted } - ); - switch (ret3){ - case 0: - console.log("Detected battle menu. Pressing A to attack..."); - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - break; - case 1: - console.log("Detected fainted Pokemon. Switching to next living Pokemon..."); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - if (swap.move_to_slot(console, context, switch_party_slot)){ - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - switch_party_slot++; - } - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", - console - ); - } - } - }, - { lost, overworld } - ); - if (ret2 == 0){ - console.log("Lost battle. Mashing B."); - } -} - -} -} -} +/* Blueberry Catch Photo + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV/Programs/PokemonSV_Terarium.h" +#include "PokemonSV_BlueberryQuests.h" + +#include +#include "PokemonSV_BlueberryCatchPhoto.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +CameraAngle quest_photo_navi( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + CameraAngle angle = CameraAngle::none; + + //Navigate to target + switch (current_quest){ + case BBQuests::photo_fly: case BBQuests::photo_psychic: + console.log("Photo: In-flight/Psychic"); + + //Polar Rest Area - targeting Duosion fixed spawn + central_to_polar_rest(info, console, context); + + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 128, 0, 230, 20); + pbf_move_left_joystick(context, 0, 128, 250, 20); + + break; + case BBQuests::photo_swim: case BBQuests::photo_water: case BBQuests::photo_polar: + console.log("Photo: Swimming/Water/Polar"); + + //Polar Outdoor Classroom 1 - fixed Horsea + central_to_polar_class1(info, console, context); + + pbf_wait(context, 200); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 255, 50, 180, 20); + + angle = CameraAngle::down; + + break; + case BBQuests::photo_coastal: case BBQuests::photo_grass: case BBQuests::photo_dragon: + console.log("Photo: Coastal/Grass/Dragon"); + + //Coastal Plaza - Exeggutor-A + central_to_coastal_plaza(info, console, context); + + pbf_move_left_joystick(context, 0, 115, 400, 20); + + //Jump down + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + + pbf_wait(context, 100); + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 0, 150, 20); + pbf_press_button(context, BUTTON_B, 20, 20); + pbf_wait(context, 200); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + context.wait_for_all_requests(); + + break; + case BBQuests::photo_canyon: case BBQuests::photo_ghost: case BBQuests::photo_ground: + console.log("Photo: Canyon/Ghost/Ground"); + + //Canyon Plaza - Golett + central_to_canyon_plaza(info, console, context); + + pbf_move_left_joystick(context, 210, 128, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 250, 400); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + break; + case BBQuests::photo_savanna: case BBQuests::photo_normal: case BBQuests::photo_fire: + console.log("Photo: Normal/Fire"); + + //Savanna Plaza - Pride Rock + central_to_savanna_plaza(info, console, context); + + pbf_move_left_joystick(context, 220, 255, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 400, 400); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 255, 128, 20, 50); + + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 100, 50); + pbf_move_left_joystick(context, 0, 0, 20, 50); + + break; + case BBQuests::photo_bug: case BBQuests::photo_rock: + console.log("Photo: Bug/Rock"); + + //Kleavor + central_to_canyon_plaza(info, console, context); + + pbf_move_left_joystick(context, 205, 64, 20, 105); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1500, 300); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + break; + case BBQuests::photo_fairy: + console.log("Photo: Fairy"); + + //Snubbull - Central plaza + open_map_from_overworld(info, console, context); + fly_to_overworld_from_map(info, console, context); + + pbf_move_left_joystick(context, 0, 80, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 2000, 1500, 200); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 255, 0, 10, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + + angle = CameraAngle::down; + break; + case BBQuests::photo_ice: + console.log("Photo: Ice"); + + //Snover - Start at central plaza, fly north-ish + open_map_from_overworld(info, console, context); + fly_to_overworld_from_map(info, console, context); + + pbf_move_left_joystick(context, 0, 0, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1100, 1700, 200); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 0, 128, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + + break; + case BBQuests::photo_flying: case BBQuests::photo_dark: + console.log("Photo: Dark/Flying"); + + //Vullaby/Mandibuzz + central_to_savanna_plaza(info, console, context); + + pbf_move_left_joystick(context, 255, 0, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 128, 0, 550, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 128, 0, 150, 20); + + pbf_move_left_joystick(context, 255, 128, 10, 20); + + angle = CameraAngle::down; + break; + case BBQuests::photo_electric: + console.log("Photo: Electric"); + + //Electabuzz + central_to_canyon_rest(info, console, context); + + pbf_move_left_joystick(context, 255, 255, 10, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 400, 20); + + break; + case BBQuests::photo_fighting: + console.log("Photo: Fighting"); + + //Hitmontop (TERA ICE) - Canyon Plaza or Classroom + central_to_canyon_plaza(info, console, context); + pbf_move_left_joystick(context, 0, 128, 400, 20); + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 0, 100, 20, 50); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 800); + + pbf_press_button(context, BUTTON_PLUS, 20, 100); + context.wait_for_all_requests(); + + break; + case BBQuests::photo_poison: + console.log("Photo: Poison"); + + //Muk-A - area a bit laggy but consistently so + central_to_coastal_plaza(info, console, context); + pbf_move_left_joystick(context, 0, 128, 20, 50); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + if (console.state().console_type() == ConsoleType::Switch1) { + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1400, 300); + } else { //Switch 2 + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1300, 300); + } + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 128, 0, 150, 50); + pbf_move_left_joystick(context, 180, 0, 20, 50); + pbf_wait(context, 200); //Give it time to spawn/load. + context.wait_for_all_requests(); + + angle = CameraAngle::down; + + break; + case BBQuests::photo_steel: + console.log("Photo: Steel"); + + //Dugtrio-A - area a bit laggy but should work most of the time + central_to_coastal_plaza(info, console, context); + pbf_move_left_joystick(context, 0, 128, 20, 50); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + if (console.state().console_type() == ConsoleType::Switch1) { + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 575, 200); + } else { //Switch 2 + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 200); + } + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 0, 128, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid photo quest.", + console + ); + break; + } + + return angle; +} + +void quest_photo( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + bool took_photo = false; + CameraAngle move_camera = CameraAngle::none; + + while(!took_photo){ + EncounterWatcher encounter_watcher(console, COLOR_RED); + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + + move_camera = quest_photo_navi(info, console, context, BBQ_OPTIONS, current_quest); + + //Take photo. + console.log("Taking photo."); + PromptDialogWatcher photo_prompt(COLOR_RED); + OverworldWatcher overworld(console.logger(), COLOR_BLUE); + + pbf_press_dpad(context, DPAD_DOWN, 50, 20); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + if (move_camera == CameraAngle::up){ + pbf_move_right_joystick(context, 128, 0, 50, 20); + }else if (move_camera == CameraAngle::down){ + pbf_move_right_joystick(context, 128, 255, 50, 20); + } + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_A, 20, 50); + + int ret = wait_until( + console, context, + std::chrono::seconds(10), + { photo_prompt } + ); + if (ret != 0){ + console.log("Photo not taken."); + } + + //Mash B until overworld + int exit = run_until( + console, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 2000); + }, + {{ overworld }} + ); + if (exit == 0){ + console.log("Overworld detected."); + } + took_photo = true; + context.wait_for_all_requests(); + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + + if (ret >= 0){ + console.log("Battle menu detected."); + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + console.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + console.log("Detected battle. Running from battle and returning to plaza."); + try{ + //Smoke Ball or Flying type required due to Arena Trap/Magnet Pull + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + battle_menu.move_to_slot(console, context, 3); + pbf_press_button(context, BUTTON_A, 10, 50); + press_Bs_to_back_to_overworld(info, console, context); + return_to_plaza(info, console, context); + }catch (...){ + console.log("Unable to flee."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to flee!", + console + ); + } + } + } + } + context.wait_for_all_requests(); + return_to_plaza(info, console, context); +} + +void quest_catch_navi( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + switch (current_quest){ + case BBQuests::catch_any: case BBQuests::catch_normal: case BBQuests::catch_fire: + console.log("Catch: Any/Normal/Fire"); + + //Savanna Plaza - Pride Rock + central_to_savanna_plaza(info, console, context); + + pbf_move_left_joystick(context, 220, 255, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 400, 400); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 255, 128, 20, 50); + + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 100, 50); + + pbf_move_left_joystick(context, 0, 0, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + + break; + + case BBQuests::catch_psychic: + console.log("Catch: Psychic"); + + //Polar Rest Area - targeting Duosion fixed spawn + central_to_polar_rest(info, console, context); + + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 128, 0, 230, 20); + pbf_move_left_joystick(context, 0, 128, 250, 20); + + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 150, 20); + + break; + + case BBQuests::catch_grass: case BBQuests::catch_dragon: + console.log("Catch: Grass/Dragon"); + + //Coastal Plaza - Exeggutor-A + central_to_coastal_plaza(info, console, context); + + pbf_move_left_joystick(context, 0, 115, 400, 20); + + //Jump down + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + + pbf_wait(context, 100); + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 0, 350, 20); + pbf_press_button(context, BUTTON_B, 20, 20); + pbf_wait(context, 200); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + break; + case BBQuests::catch_ghost: case BBQuests::catch_ground: + console.log("Catch: Ghost/Ground"); + + //Canyon Plaza - Golett + central_to_canyon_plaza(info, console, context); + + pbf_move_left_joystick(context, 210, 128, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 300, 400); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 0, 0, 10, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 50, 20); + + break; + case BBQuests::catch_fairy: + console.log("Catch: Fairy"); + + //Snubbull - Central plaza + //Tested while snowing, seems fine? + open_map_from_overworld(info, console, context); + fly_to_overworld_from_map(info, console, context); + + pbf_move_left_joystick(context, 0, 80, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 2000, 1500, 200); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 255, 0, 10, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + + break; + case BBQuests::catch_fighting: + console.log("Catch: Fighting"); + + //Hitmontop (TERA ICE) - Canyon Plaza or Classroom + central_to_canyon_plaza(info, console, context); + pbf_move_left_joystick(context, 0, 128, 400, 20); + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 0, 100, 20, 50); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 800); + + break; + + case BBQuests::catch_bug: + console.log("Catch: Bug"); + + central_to_canyon_plaza(info, console, context); + + pbf_move_left_joystick(context, 205, 64, 20, 105); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1650, 500); + break; + case BBQuests::catch_dark: case BBQuests::catch_flying: + console.log("Catch: Dark/Flying"); + + //Vullaby/Mandibuzz + central_to_savanna_plaza(info, console, context); + + pbf_move_left_joystick(context, 255, 40, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 128, 0, 500, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + pbf_move_left_joystick(context, 255, 0, 10, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + + if (console.state().console_type() == ConsoleType::Switch1) { + pbf_move_left_joystick(context, 128, 0, 200, 20); + } else { + pbf_move_left_joystick(context, 128, 0, 170, 20); + } + + pbf_press_button(context, BUTTON_L, 20, 50); + + pbf_move_left_joystick(context, 0, 0, 10, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + + if (console.state().console_type() == ConsoleType::Switch1) { + pbf_move_left_joystick(context, 128, 0, 100, 20); + } else { + pbf_move_left_joystick(context, 128, 0, 120, 20); + } + pbf_wait(context, 400); + context.wait_for_all_requests(); + + break; + case BBQuests::catch_rock: case BBQuests::catch_electric: + console.log("Catch: Rock/Electric"); + + //Geodude-A + open_map_from_overworld(info, console, context); + fly_to_overworld_from_map(info, console, context); + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 70, 0, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 100, 550, 300); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_wait(context, 300); + context.wait_for_all_requests(); + + break; + case BBQuests::catch_steel: + console.log("Catch: Steel"); + + //Dugtrio-A - area a bit laggy but should work most of the time + central_to_coastal_plaza(info, console, context); + pbf_move_left_joystick(context, 0, 128, 20, 50); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + if (console.state().console_type() == ConsoleType::Switch1) { + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 575, 200); + } else { //Switch 2 + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 200, 500, 200); + } + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 0, 128, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 50, 50); + + break; + case BBQuests::catch_poison: + console.log("Catch: Poison"); + + //Muk-A - area a bit laggy but consistently so + central_to_coastal_plaza(info, console, context); + pbf_move_left_joystick(context, 0, 128, 20, 50); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + if (console.state().console_type() == ConsoleType::Switch1) { + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1800, 300); + } else { + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1600, 300); + } + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + //Extra throws for this one + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); + pbf_wait(context, 200); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_ZR, 20, 50); //Withdraw pokemon + + pbf_move_left_joystick(context, 255, 128, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); + pbf_wait(context, 200); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_ZR, 20, 50); //Withdraw pokemon + + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 255, 128, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + + break; + case BBQuests::catch_water: case BBQuests::catch_ice: + console.log("Catch: Water/Ice"); + + //Lapras - Tera Bug + central_to_polar_rest(info, console, context); + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 128, 0, 230, 20); + pbf_move_left_joystick(context, 0, 128, 300, 20); + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 20, 0, 20, 50); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 700, 1700, 300); + + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid catch quest.", + console + ); + break; + } + + //Lock on and throw ball + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); + + pbf_wait(context, 300); + context.wait_for_all_requests(); + +} + +void quest_catch_throw_ball( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + Language language, + const std::string& selected_ball +){ + BattleBallReader reader(console, language); + std::string ball_reader = ""; + WallClock start = current_time(); + + console.log("Opening ball menu..."); + while (ball_reader == ""){ + if (current_time() - start > std::chrono::minutes(2)){ + console.log("Timed out trying to read ball after 2 minutes.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out trying to read ball after 2 minutes.", + console + ); + } + + //Mash B to exit anything else + pbf_mash_button(context, BUTTON_B, 125); + context.wait_for_all_requests(); + + //Press X to open Ball menu + pbf_press_button(context, BUTTON_X, 20, 100); + context.wait_for_all_requests(); + + VideoSnapshot screen = console.video().snapshot(); + ball_reader = reader.read_ball(screen); + } + + console.log("Selecting ball."); + int quantity = move_to_ball(reader, console, context, selected_ball); + if (quantity == 0){ + console.log("Unable to find ball."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find ball.", + console + ); + } + if (quantity < 0){ + console.log("Unable to read ball quantity.", COLOR_RED); + } + + //Throw ball + console.log("Throwing ball."); + pbf_mash_button(context, BUTTON_A, 150); + context.wait_for_all_requests(); + + pbf_mash_button(context, BUTTON_B, 900); + context.wait_for_all_requests(); +} + +void quest_catch_handle_battle( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + console.log("Catching Pokemon."); + AdvanceDialogWatcher advance_dialog(COLOR_MAGENTA); + PromptDialogWatcher add_to_party(COLOR_PURPLE); + OverworldWatcher overworld(console.logger(), COLOR_RED); + + uint8_t switch_party_slot = 1; + bool quickball_thrown = false; + bool tera_target = false; + bool use_quickball = BBQ_OPTIONS.QUICKBALL; + + int ret2 = run_until( + console, context, + [&](ProControllerContext& context){ + while (true){ + //Check that battle menu appears - this is in case of swapping pokemon + NormalBattleMenuWatcher menu_before_throw(COLOR_YELLOW); + int bMenu = wait_until( + console, context, + std::chrono::seconds(15), + { menu_before_throw } + ); + if (bMenu < 0){ + console.log("Unable to find menu_before_throw."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find menu_before_throw.", + console + ); + } + + //Check for catch menu - if none it is a tera pokemon + console.log("Checking for ball menu."); + BattleBallReader exists(console, BBQ_OPTIONS.LANGUAGE); + std::string ball_exists = ""; + + pbf_press_button(context, BUTTON_X, 20, 100); + context.wait_for_all_requests(); + + VideoSnapshot screen_ball = console.video().snapshot(); + ball_exists = exists.read_ball(screen_ball); + + if (ball_exists == ""){ + console.log("Could not find ball reader. Tera battle. Using first attack."); + pbf_mash_button(context, BUTTON_B, 125); + context.wait_for_all_requests(); + + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + tera_target = true; + }else{ + //Quick ball occurs before anything else in battle. + //Do not throw if target is a tera pokemon. + if (use_quickball && !quickball_thrown && tera_target == false){ + console.log("Quick Ball option checked. Throwing Quick Ball."); + quest_catch_throw_ball(info, console, context, BBQ_OPTIONS.LANGUAGE, "quick-ball"); + quickball_thrown = true; + }else{ + console.log("Throwing selected ball."); + quest_catch_throw_ball(info, console, context, BBQ_OPTIONS.LANGUAGE, BBQ_OPTIONS.BALL_SELECT.slug()); + } + + //Check for battle menu, if found use fourth attack this turn + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret = wait_until( + console, context, + std::chrono::seconds(4), + { battle_menu } + ); + if (ret == 0){ + console.log("Battle menu detected early. Using fourth attack."); + MoveSelectWatcher move_watcher(COLOR_BLUE); + MoveSelectDetector move_select(COLOR_BLUE); + + int ret_move_select = run_until( + console, context, + [&](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + }, + { move_watcher } + ); + if (ret_move_select != 0){ + console.log("Could not find move select."); + }else{ + console.log("Move select found!"); + } + + context.wait_for_all_requests(); + move_select.move_to_slot(console, context, 3); + pbf_mash_button(context, BUTTON_A, 150); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + //Check for battle menu + //If found after a second, assume out of PP and stop as this is a setup issue + //None of the target pokemon for this program have disable, taunt, etc. + NormalBattleMenuWatcher battle_menu2(COLOR_YELLOW); + int ret3 = wait_until( + console, context, + std::chrono::seconds(4), + { battle_menu2 } + ); + if (ret3 == 0){ + console.log("Battle menu detected early. Out of PP/No move in slot, please check your setup."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Battle menu detected early. Out of PP, please check your setup.", + console + ); + } + }else{ + //Wild pokemon's turn/wait for catch animation + pbf_mash_button(context, BUTTON_B, 900); + context.wait_for_all_requests(); + } + } + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + GradientArrowWatcher fainted(COLOR_BLUE, GradientArrowType::RIGHT, {0.610, 0.523, 0.044, 0.079}); + SwapMenuWatcher swap(COLOR_YELLOW); + int ret2_run = wait_until( + console, context, + std::chrono::seconds(60), + { battle_menu, fainted } + ); + switch (ret2_run){ + case 0: + console.log("Battle menu detected, continuing."); + break; + case 1: + console.log("Detected fainted Pokemon. Switching to next living Pokemon..."); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + if (swap.move_to_slot(console, context, switch_party_slot)){ + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + switch_party_slot++; + } + break; + default: + console.log("Invalid state ret2_run. Out of moves?"); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state ret2_run. Out of moves?", + console + ); + } + + } + }, + { advance_dialog, add_to_party, overworld } + ); + + switch (ret2){ + case 0: + console.log("Advance Dialog detected."); + press_Bs_to_back_to_overworld(info, console, context); + break; + case 1: + console.log("Prompt dialog detected."); + press_Bs_to_back_to_overworld(info, console, context); + break; + case 2: + console.log("Overworld detected."); + break; + default: + console.log("Invalid state in run_battle()."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state in run_battle().", + console + ); + } +} + +void quest_catch( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + EncounterWatcher encounter_watcher(console, COLOR_RED); + + //Navigate to target and start battle + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + + quest_catch_navi(info, console, context, BBQ_OPTIONS, current_quest); + context.wait_for_all_requests(); + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret2 = wait_until( + console, context, + std::chrono::seconds(25), + { battle_menu } + ); + if (ret2 != 0){ + console.log("Did not enter battle. Did target spawn?"); + } + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + + if (ret >= 0){ + console.log("Battle menu detected."); + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + console.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + quest_catch_handle_battle(info, console, context, BBQ_OPTIONS, current_quest); + } + } + + return_to_plaza(info, console, context); + + //Day skip and attempt to respawn fixed encounters + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, true); + roll_date_forward_1(console, context, true); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + + //Heal up and then reset position again. + OverworldWatcher done_healing(console.logger(), COLOR_BLUE); + pbf_move_left_joystick(context, 128, 0, 100, 20); + + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + int exit = run_until( + console, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 2000); + }, + {{ done_healing }} + ); + if (exit == 0){ + console.log("Overworld detected."); + } + open_map_from_overworld(info, console, context); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(info, console, context); + context.wait_for_all_requests(); +} + +void wild_battle_tera( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + bool& tera_self +){ + AdvanceDialogWatcher lost(COLOR_YELLOW); + OverworldWatcher overworld(console.logger(), COLOR_RED); + WallClock start = current_time(); + uint8_t switch_party_slot = 1; + bool first_turn = true; + + int ret2 = run_until( + console, context, + [&](ProControllerContext& context){ + while(true){ + if (current_time() - start > std::chrono::minutes(5)){ + console.log("Timed out during battle after 5 minutes.", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle after 5 minutes.", + console + ); + } + + if (first_turn && tera_self){ + console.log("Turn 1: Tera."); + //Open move menu + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_R, 20, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + + first_turn = false; + } + + NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); + GradientArrowWatcher fainted(COLOR_BLUE, GradientArrowType::RIGHT, {0.610, 0.523, 0.044, 0.079}); + SwapMenuWatcher swap(COLOR_YELLOW); + + context.wait_for_all_requests(); + + int ret3 = wait_until( + console, context, + std::chrono::seconds(90), + { battle_menu, fainted } + ); + switch (ret3){ + case 0: + console.log("Detected battle menu. Pressing A to attack..."); + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + break; + case 1: + console.log("Detected fainted Pokemon. Switching to next living Pokemon..."); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + if (swap.move_to_slot(console, context, switch_party_slot)){ + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + switch_party_slot++; + } + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", + console + ); + } + } + }, + { lost, overworld } + ); + if (ret2 == 0){ + console.log("Lost battle. Mashing B."); + } +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h index 20526904f3..683debb186 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h @@ -1,82 +1,82 @@ -/* Blueberry Quests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BlueberryCatchPhoto_H -#define PokemonAutomation_PokemonSV_BlueberryCatchPhoto_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h" -#include "PokemonSV/Options/PokemonSV_BBQOption.h" - -using namespace std; - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - -//Navigate to a photo target -CameraAngle quest_photo_navi( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - -//Take picture of a pokemon/location -void quest_photo( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - - -//Navigate to a catch target -void quest_catch_navi( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - -//Select and throw ball -void quest_catch_throw_ball( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - Language language, - const std::string& selected_ball -); - -//Handle catching the target -void quest_catch_handle_battle( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - -//Catch a pokemon -void quest_catch( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - - -//Handle battles for tera-self/defeat-wild-tera. Use first attack until victory. -void wild_battle_tera( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - bool& tera_self -); - -} -} -} -#endif +/* Blueberry Quests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BlueberryCatchPhoto_H +#define PokemonAutomation_PokemonSV_BlueberryCatchPhoto_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h" +#include "PokemonSV/Options/PokemonSV_BBQOption.h" + +using namespace std; + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + +//Navigate to a photo target +CameraAngle quest_photo_navi( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + +//Take picture of a pokemon/location +void quest_photo( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + + +//Navigate to a catch target +void quest_catch_navi( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + +//Select and throw ball +void quest_catch_throw_ball( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + Language language, + const std::string& selected_ball +); + +//Handle catching the target +void quest_catch_handle_battle( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + +//Catch a pokemon +void quest_catch( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + + +//Handle battles for tera-self/defeat-wild-tera. Use first attack until victory. +void wild_battle_tera( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + bool& tera_self +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp index 6a8a0592b3..a861a18603 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.cpp @@ -1,1386 +1,1386 @@ -/* Blueberry Quests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h" -#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" -#include "PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h" -#include "PokemonSV/Programs/PokemonSV_Terarium.h" -#include "PokemonSV_BlueberryQuests.h" - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -const std::map& BBQuests_TOKEN_TO_ENUM(){ - static std::map data{ - {"auto-10", BBQuests::auto_10}, - {"make-tm", BBQuests::make_tm }, - {"pickup-10", BBQuests::pickup_10}, - {"sneak-up", BBQuests::sneak_up}, - {"photo-fly", BBQuests::photo_fly}, - {"photo-swim", BBQuests::photo_swim}, - {"photo-canyon", BBQuests::photo_canyon}, - {"photo-coastal", BBQuests::photo_coastal}, - {"photo-polar", BBQuests::photo_polar}, - {"photo-savanna", BBQuests::photo_savanna}, - {"tera-self-defeat", BBQuests::tera_self_defeat}, - {"travel-500", BBQuests::travel_500}, - {"catch-any", BBQuests::catch_any}, - {"catch-normal", BBQuests::catch_normal}, - {"catch-fighting", BBQuests::catch_fighting}, - {"catch-flying", BBQuests::catch_flying}, - {"catch-poison", BBQuests::catch_poison}, - {"catch-ground", BBQuests::catch_ground}, - {"catch-rock", BBQuests::catch_rock}, - {"catch-bug", BBQuests::catch_bug}, - {"catch-ghost", BBQuests::catch_ghost}, - {"catch-steel", BBQuests::catch_steel}, - {"catch-fire", BBQuests::catch_fire}, - {"catch-water", BBQuests::catch_water}, - {"catch-grass", BBQuests::catch_grass}, - {"catch-electric", BBQuests::catch_electric}, - {"catch-psychic", BBQuests::catch_psychic}, - {"catch-ice", BBQuests::catch_ice}, - {"catch-dragon", BBQuests::catch_dragon}, - {"catch-dark", BBQuests::catch_dark}, - {"catch-fairy", BBQuests::catch_fairy}, - {"wash-pokemon", BBQuests::wash_pokemon}, - {"wild-tera", BBQuests::wild_tera}, - {"auto-30", BBQuests::auto_30}, - {"tera-raid", BBQuests::tera_raid}, - {"sandwich-three", BBQuests::sandwich_three}, - {"bitter-sandwich", BBQuests::bitter_sandwich}, - {"sweet-sandwich", BBQuests::sweet_sandwich}, - {"salty-sandwich", BBQuests::salty_sandwich}, - {"sour-sandwich", BBQuests::sour_sandwich}, - {"spicy-sandwich", BBQuests::spicy_sandwich}, - {"hatch-egg", BBQuests::hatch_egg}, - {"photo-normal", BBQuests::photo_normal}, - {"photo-fighting", BBQuests::photo_fighting}, - {"photo-flying", BBQuests::photo_flying}, - {"photo-poison", BBQuests::photo_poison}, - {"photo-ground", BBQuests::photo_ground}, - {"photo-rock", BBQuests::photo_rock}, - {"photo-bug", BBQuests::photo_bug}, - {"photo-ghost", BBQuests::photo_ghost}, - {"photo-steel", BBQuests::photo_steel}, - {"photo-fire", BBQuests::photo_fire}, - {"photo-water", BBQuests::photo_water}, - {"photo-grass", BBQuests::photo_grass}, - {"photo-electric", BBQuests::photo_electric}, - {"photo-psychic", BBQuests::photo_psychic}, - {"photo-ice", BBQuests::photo_ice}, - {"photo-dragon", BBQuests::photo_dragon}, - {"photo-dark", BBQuests::photo_dark}, - {"photo-fairy", BBQuests::photo_fairy}, - {"ditto-central", BBQuests::ditto_central}, - {"ditto-canyon", BBQuests::ditto_canyon}, - {"ditto-coastal", BBQuests::ditto_coastal}, - {"ditto-polar", BBQuests::ditto_polar}, - {"ditto-savanna", BBQuests::ditto_savanna}, - {"group-canyon", BBQuests::group_canyon}, - {"group-coastal", BBQuests::group_coastal}, - {"group-polar", BBQuests::group_polar}, - {"group-savanna", BBQuests::group_savanna}, - {"group-eyewear", BBQuests::group_eyewear}, - {"group-nonuniform", BBQuests::group_nonuniform}, - {"group-masks", BBQuests::group_masks}, - {"sandwich-four", BBQuests::sandwich_four}, - {"catch-hint", BBQuests::catch_hint}, - {"catch-hint2", BBQuests::catch_hint2}, - {"", BBQuests::UnableToDetect}, - }; - return data; -} - -BBQuests BBQuests_string_to_enum(const std::string& token){ - auto iter = BBQuests_TOKEN_TO_ENUM().find(token); - if (iter == BBQuests_TOKEN_TO_ENUM().end()){ - return BBQuests::UnableToDetect; - } - return iter->second; -} - -int read_BP(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++) { //try 6 times - pbf_press_dpad(context, DPAD_RIGHT, 50, 20); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - }, - {{ right_panel }} - ); - if (result == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - VideoSnapshot screen = stream.video().snapshot(); - ImageRGB32 BP_value = to_blackwhite_rgb32_range( - extract_box_reference(screen, ImageFloatBox(0.866, 0.019, 0.091, 0.041)), - true, - combine_rgb(198, 198, 198), combine_rgb(255, 255, 255) - ); - - //Close panel - pbf_mash_button(context, BUTTON_B, 100); - context.wait_for_all_requests(); - - return OCR::read_number(stream.logger(), BP_value); -} - -std::vector read_quests( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -){ - std::vector quest_list; - - //Open quest list. Wait for it to open. - WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++) { //try 6 times - pbf_press_dpad(context, DPAD_RIGHT, 50, 20); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - }, - {{ right_panel }} - ); - if (result == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - //Read in the initial 4 quests. - stream.log("Reading quests."); - VideoSnapshot screen = stream.video().snapshot(); - BlueberryQuestDetector first_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::FIRST); - BlueberryQuestDetector second_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::SECOND); - BlueberryQuestDetector third_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::THIRD); - BlueberryQuestDetector fourth_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::FOURTH); - - quest_list.push_back(BBQuests_string_to_enum(first_quest_detector.detect_quest(screen))); - quest_list.push_back(BBQuests_string_to_enum(second_quest_detector.detect_quest(screen))); - quest_list.push_back(BBQuests_string_to_enum(third_quest_detector.detect_quest(screen))); - - std::string fourth_quest = fourth_quest_detector.detect_quest(screen); - if (fourth_quest != ""){ - quest_list.push_back(BBQuests_string_to_enum(fourth_quest)); - } - - //Close quest list - pbf_mash_button(context, BUTTON_B, 100); - context.wait_for_all_requests(); - - return quest_list; -} - -std::vector process_quest_list( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - std::vector& quest_list, - uint8_t& eggs_hatched -){ - std::vector quests_to_do; - bool rerolled = false; - std::vector> exclusions_table = BBQ_OPTIONS.QUEST_EXCLUSIONS.copy_snapshot(); - int questpos = 0; - - stream.log("Processing quests."); - //Put all do-able quests into a different list - for (auto n : quest_list){ - if (not_possible_quests.contains(n)){ - stream.log("Quest not possible"); - }else{ - //Check eggs remaining. - if (n == BBQuests::hatch_egg && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ - stream.log("Out of eggs! Quest not possible."); - - switch (BBQ_OPTIONS.OUT_OF_EGGS){ - case BBQOption::OOEggs::Reroll: - { - stream.log("Reroll selected. Rerolling Egg quest. New quest will be run in the next batch of quests."); - //stream.log("Warning: This does not handle/check being out of BP!", COLOR_RED); - - WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 50, 20); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - }, - {{ right_panel }} - ); - if (result == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - rerolled = true; - press_Bs_to_back_to_overworld(info, stream, context); - - break; - } - case BBQOption::OOEggs::KeepGoing: - stream.log("Keep Going selected. Ignoring quest."); - break; - default: - //This case is handled in BBQSoloFarmer. - stream.log("OOEggs is Stop in process_quest_list()."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "OOEggs is Stop in process_quest_list().", - stream - ); - break; - } - } - else{ - bool quest_in_table = false; - for(const std::unique_ptr& row : exclusions_table){ - if(n == row->quest) { - stream.log("Quest found in inclusions/exclusions table."); - quest_in_table = true; - - WhiteButtonWatcher rp2(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result2; - switch (row->action) { - case BBQAction::run: - stream.log("Run selected. Adding quest to list."); - quests_to_do.push_back(n); - break; - case BBQAction::reroll: - stream.log("Reroll selected. Rerolling quest. New quest will be run in the next batch of quests."); - result2 = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 50, 20); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - }, - {{ rp2 }} - ); - if (result2 == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - //Move cursor down to quest - for (int i = 0; i < questpos; i++) { - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - pbf_wait(context, 100); - context.wait_for_all_requests(); - } - - //Reroll - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - //Prevent error/rerolling again at the end (allows program to read the rerolled quests) - rerolled = true; - - press_Bs_to_back_to_overworld(info, stream, context); - break; - case BBQAction::skip: - stream.log("Skip selected. Skipping quest."); - break; - } - } - } - if(!quest_in_table){ - stream.log("Quest not in inclusion/exclusions table. Adding to list."); - quests_to_do.push_back(n); - } - } - } - questpos++; - } - - //Check that quests_to_do is not empty (after completing all quests on the list, be sure to erase it. - //Lag might be a problem in multi - look into making slots like menu-left navigation - if (!rerolled && quests_to_do.size() == 0){ - stream.log("No possible quests! Rerolling all quests."); - - //Open quest panel and reroll all quests. - //This does not handle out of BP. - WhiteButtonWatcher panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 6; i++){ - pbf_press_dpad(context, DPAD_RIGHT, 50, 20); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - }, - {{ panel }} - ); - if (result == 0){ - stream.log("Found quest panel."); - } - context.wait_for_all_requests(); - - for (string::size_type i = 0; i < quest_list.size(); i++){ - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_button(context, BUTTON_A, 20, 50); //Yes. - pbf_wait(context, 100); - context.wait_for_all_requests(); - pbf_press_dpad(context, DPAD_DOWN, 20, 20); - pbf_wait(context, 100); - context.wait_for_all_requests(); - } - //Close quest panel - mash b - press_Bs_to_back_to_overworld(info, stream, context); - } - /* - if (!rerolled && quests_to_do.size() == 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No possible quests! Check language selection.", - stream - ); - } - */ - return quests_to_do; -} - -bool process_and_do_quest( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - BBQOption& BBQ_OPTIONS, - BBQuests current_quest, - uint8_t& eggs_hatched -){ - bool quest_completed = false; - int quest_attempts = 0; - - while (!quest_completed){ - switch (current_quest){ - case BBQuests::make_tm: - quest_make_tm(env.program_info(), console, context); - break; - case BBQuests::travel_500: - quest_travel_500(env.program_info(), console, context); - break; - case BBQuests::tera_self_defeat: - quest_tera_self_defeat(env.program_info(), console, context, BBQ_OPTIONS); - break; - case BBQuests::sneak_up: - quest_sneak_up(env.program_info(), console, context, BBQ_OPTIONS); - break; - case BBQuests::wild_tera: - quest_wild_tera(env.program_info(), console, context, BBQ_OPTIONS); - break; - case BBQuests::wash_pokemon: - quest_wash_pokemon(env.program_info(), console, context); - break; - case BBQuests::hatch_egg: - quest_hatch_egg(env.program_info(), console, context, BBQ_OPTIONS); - break; - case BBQuests::bitter_sandwich: - case BBQuests::salty_sandwich: - case BBQuests::sour_sandwich: - case BBQuests::spicy_sandwich: - case BBQuests::sweet_sandwich: - case BBQuests::sandwich_three: - quest_sandwich(env, console, context, BBQ_OPTIONS, current_quest); - break; - //case BBQuests::pickup_10: - // quest_pickup(env, env.program_info(), console, context, BBQ_OPTIONS); - // break; - case BBQuests::tera_raid: - quest_tera_raid(env, console, context, BBQ_OPTIONS); - break; - case BBQuests::auto_10: - case BBQuests::auto_30: - quest_auto_battle(env, console, context, BBQ_OPTIONS, current_quest); - break; - //All involve taking pictures - case BBQuests::photo_fly: - case BBQuests::photo_swim: - case BBQuests::photo_canyon: - case BBQuests::photo_coastal: - case BBQuests::photo_polar: - case BBQuests::photo_savanna: - case BBQuests::photo_normal: - case BBQuests::photo_fighting: - case BBQuests::photo_flying: - case BBQuests::photo_poison: - case BBQuests::photo_ground: - case BBQuests::photo_rock: - case BBQuests::photo_bug: - case BBQuests::photo_ghost: - case BBQuests::photo_steel: - case BBQuests::photo_fire: - case BBQuests::photo_water: - case BBQuests::photo_grass: - case BBQuests::photo_electric: - case BBQuests::photo_psychic: - case BBQuests::photo_ice: - case BBQuests::photo_dragon: - case BBQuests::photo_dark: - case BBQuests::photo_fairy: - quest_photo(env.program_info(), console, context, BBQ_OPTIONS, current_quest); - break; - //All involve catching a pokemon - case BBQuests::catch_any: - case BBQuests::catch_normal: - case BBQuests::catch_fighting: - case BBQuests::catch_flying: - case BBQuests::catch_poison: - case BBQuests::catch_ground: - case BBQuests::catch_rock: - case BBQuests::catch_bug: - case BBQuests::catch_ghost: - case BBQuests::catch_steel: - case BBQuests::catch_fire: - case BBQuests::catch_water: - case BBQuests::catch_grass: - case BBQuests::catch_electric: - case BBQuests::catch_psychic: - case BBQuests::catch_ice: - case BBQuests::catch_dragon: - case BBQuests::catch_dark: - case BBQuests::catch_fairy: - quest_catch(env.program_info(), console, context, BBQ_OPTIONS, current_quest); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unknown quest selection.", - console - ); - break; - } - - //Validate quest was completed by checking list - std::vector quest_list = read_quests(env.program_info(), console, context, BBQ_OPTIONS); - if (std::find(quest_list.begin(), quest_list.end(), current_quest) != quest_list.end()){ - console.log("Current quest exists on list. Quest did not complete."); - quest_attempts++; - }else{ - console.log("Current quest was not found. Quest completed!"); - if (current_quest == BBQuests::hatch_egg){ - eggs_hatched++; - console.log("Eggs hatched: " + std::to_string(eggs_hatched)); - } - - quest_completed = true; - } - - if (quest_attempts > BBQ_OPTIONS.NUM_RETRIES){ - console.log("Failed to complete a quest multiple times. Skipping it for now.", COLOR_RED); - break; - } - } - return quest_completed; -} - -void quest_make_tm(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Quest: Make TM"); - - //Mount and then dismount in case you're crouched - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_press_button(context, BUTTON_PLUS, 20, 105); - context.wait_for_all_requests(); - - GradientArrowWatcher machine(COLOR_BLUE, GradientArrowType::DOWN, {0.181, 0.127, 0.045, 0.070}); - PromptDialogWatcher makeTM(COLOR_RED); - OverworldWatcher overworld(stream.logger(), COLOR_BLUE); - - pbf_move_left_joystick(context, 255, 0, 100, 20); - pbf_press_button(context, BUTTON_L, 10, 50); - - int enter_machine = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_wait(context, 200); - context.wait_for_all_requests(); - } - }, - {{ machine }} - ); - context.wait_for_all_requests(); - - if (enter_machine == 0){ - stream.log("TM machine entered. Finding TM to make."); - - int make_tm = run_until( - stream, context, - [&](ProControllerContext& context){ - for (int i = 0; i < 229; i++) { //229 is max number of TMs - //click on tm - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - //not craftable, close and move on to next - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_dpad(context, DPAD_RIGHT, 20, 20); - pbf_wait(context, 100); - context.wait_for_all_requests(); - } - }, - {{ makeTM }} - ); - context.wait_for_all_requests(); - - if (make_tm == 0){ - stream.log("Craftable TM found. Making TM"); - - pbf_mash_button(context, BUTTON_A, 220); - context.wait_for_all_requests(); - }else{ - stream.log("Failed to find craftable TM!"); - } - }else{ - stream.log("Failed to enter TM machine!"); - } - - int exit = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 2000); - }, - {{ overworld }} - ); - if (exit == 0){ - stream.log("Overworld detected."); - } - context.wait_for_all_requests(); - - open_map_from_overworld(info, stream, context); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(info, stream, context); - context.wait_for_all_requests(); -} - -void quest_travel_500(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Quest: Travel 500 meters."); - - //Mount and then dismount in case you're crouched - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_press_button(context, BUTTON_PLUS, 20, 105); - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 0, 0, 100, 20); - pbf_move_left_joystick(context, 128, 0, 150, 20); - pbf_move_left_joystick(context, 0, 128, 140, 20); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - for(int j = 0; j < 60; j++){ //One min just to be safe. - pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, - 128, 0, 255, 128, TICKS_PER_SECOND); - } - context.wait_for_all_requests(); - - open_map_from_overworld(info, stream, context); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(info, stream, context); - context.wait_for_all_requests(); -} - -void quest_tera_self_defeat( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -){ - EncounterWatcher encounter_watcher(console, COLOR_RED); - console.log("Quest: Tera-self and defeat any wild."); - //Navigate to target and start battle - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - central_to_canyon_plaza(info, console, context); - - pbf_move_left_joystick(context, 205, 64, 20, 105); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - //Drop on top of Kleavor (plenty of Scyther in the area as well) - if (console.state().console_type() == ConsoleType::Switch1) { - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1650, 300); - } else { //All switch 2s - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1600, 300); - } - - ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); - ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); - ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); - - pbf_wait(context, 300); - context.wait_for_all_requests(); - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret2 = wait_until( - console, context, - std::chrono::seconds(15), - { battle_menu } - ); - if (ret2 != 0){ - console.log("Did not enter battle. Did Kleavor spawn?"); - } - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - - if (ret >= 0){ - console.log("Battle menu detected."); - } - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - console.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - bool tera_self = true; - wild_battle_tera(info, console, context, tera_self); - } - pbf_press_button(context, BUTTON_PLUS, 20, 105); - return_to_plaza(info, console, context); - - //Day skip and attempt to respawn fixed encounters - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, true); - roll_date_forward_1(console, context, true); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - - //Heal up and then reset position again. - OverworldWatcher done_healing(console.logger(), COLOR_BLUE); - pbf_move_left_joystick(context, 128, 0, 100, 20); - - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - int exit = run_until( - console, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 2000); - }, - {{ done_healing }} - ); - if (exit == 0){ - console.log("Overworld detected."); - } - open_map_from_overworld(info, console, context); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(info, console, context); -} - -void quest_sneak_up( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -){ - EncounterWatcher encounter_watcher(console, COLOR_RED); - console.log("Quest: Sneak up."); - //Navigate to target and start battle - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - //Savanna Plaza - Pride Rock - central_to_savanna_plaza(info, console, context); - - pbf_move_left_joystick(context, 220, 255, 10, 20); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 400, 400); - - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 255, 128, 20, 50); - - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 100, 50); - - //Turn slightly for switch 1 - if (console.state().console_type() == ConsoleType::Switch1) { - pbf_move_left_joystick(context, 0, 0, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - } - - ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); - ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); - ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); - - pbf_wait(context, 300); - context.wait_for_all_requests(); - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret2 = wait_until( - console, context, - std::chrono::seconds(15), - { battle_menu } - ); - if (ret2 != 0){ - console.log("Did not enter battle. Did target spawn?"); - } - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - - if (ret >= 0){ - console.log("Battle menu detected."); - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - console.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - OverworldWatcher overworld(console.logger(), COLOR_BLUE); - - int ret2 = run_until( - console, context, - [&](ProControllerContext& context){ - while (true){ - //Flee immediately. Keep trying to flee. - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret2 = wait_until( - console, context, - std::chrono::seconds(60), - { battle_menu } - ); - switch (ret2){ - case 0: - battle_menu.move_to_slot(console, context, 3); - pbf_press_button(context, BUTTON_A, 10, 50); - break; - default: - console.log("Invalid state quest_sneak_up(). Smoke Ball equipped?"); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state quest_sneak_up(). Smoke Ball equipped?", - console - ); - } - } - }, - { overworld } - ); - - switch (ret2){ - case 0: - console.log("Overworld detected."); - break; - default: - console.log("Invalid state in run_battle()."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state in run_battle().", - console - ); - } - } - } - return_to_plaza(info, console, context); - - //Day skip and attempt to respawn fixed encounters - in case quest failed - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, true); - roll_date_forward_1(console, context, true); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - context.wait_for_all_requests(); -} - -void quest_wild_tera( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -){ - EncounterWatcher encounter_watcher(console, COLOR_RED); - console.log("Quest: Defeat a wild tera."); - //Navigate to target and start battle - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - //Canyon Rest Area - central_to_canyon_rest(info, console, context); - - pbf_move_left_joystick(context, 255, 180, 20, 105); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 500, 1300, 150); - - //Skarmory is likely to attack but sometimes there is a different pokemon - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - if (console.state().console_type() == ConsoleType::Switch1) { - pbf_move_left_joystick(context, 50, 0, 20, 105); - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 100, 50); - } else { //Switch 2 - pbf_move_left_joystick(context, 20, 0, 20, 105); - pbf_press_button(context, BUTTON_L, 20, 50); - } - - ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); - ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); - ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); - - pbf_wait(context, 300); - context.wait_for_all_requests(); - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret2 = wait_until( - console, context, - std::chrono::seconds(15), - { battle_menu } - ); - if (ret2 != 0){ - console.log("Did not enter battle."); - } - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - - if (ret >= 0){ - console.log("Battle menu detected."); - } - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - console.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - bool tera_self = false; - wild_battle_tera(info, console, context, tera_self); - } - return_to_plaza(info, console, context); - - //Day skip and attempt to respawn fixed encounters - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, true); - roll_date_forward_1(console, context, true); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - - //Heal up and then reset position again. - OverworldWatcher done_healing(console.logger(), COLOR_BLUE); - pbf_move_left_joystick(context, 128, 0, 100, 20); - - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - int exit = run_until( - console, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 2000); - }, - {{ done_healing }} - ); - if (exit == 0){ - console.log("Overworld detected."); - } - open_map_from_overworld(info, console, context); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(info, console, context); -} - -void quest_wash_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Quest: Give your pokemon a bath!"); - - //Fly to savanna plaza - central_to_savanna_plaza(info, stream, context); - - //Turn around, open picnic - pbf_move_left_joystick(context, 128, 255, 20, 50); - pbf_press_button(context, BUTTON_L, 50, 40); - - picnic_from_overworld(info, stream, context); - - WallClock start = current_time(); - WhiteButtonWatcher wash_button(COLOR_BLUE, WhiteButton::ButtonX, {0.027, 0.548, 0.022, 0.032}); - WhiteButtonWatcher wash_exit_button(COLOR_BLUE, WhiteButton::ButtonB, {0.027, 0.923, 0.021, 0.033}); - WhiteButtonWatcher shower_switch(COLOR_BLUE, WhiteButton::ButtonY, {0.486, 0.870, 0.027, 0.045}); - bool rinsed_once = false; - while (!rinsed_once){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(3)){ - stream.log("Failed to get to rinse after 3 minutes.", COLOR_RED); - break; - } - int ret = wait_until( - stream, context, std::chrono::seconds(60), - { - wash_button, - shower_switch, - wash_exit_button, - } - ); - switch (ret){ - case 0: - stream.log("Wash button found!"); - pbf_mash_button(context, BUTTON_X, 150); - pbf_wait(context, 200); - context.wait_for_all_requests(); - break; - case 1: - stream.log("Rinse button found. Switching to rinse."); - pbf_press_button(context, BUTTON_Y, 40, 50); - rinsed_once = true; - //Move slightly right, as the showerhead is at an angle - pbf_move_left_joystick(context, 255, 0, 30, 30); - context.wait_for_all_requests(); - break; - case 2: - stream.log("In wash. Scrubbing."); - - ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); - ssf_press_left_joystick(context, 0, 128, 0, 50); - ssf_press_left_joystick(context, 255, 128, 50, 100); - ssf_press_left_joystick(context, 0, 128, 150, 50); - - ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); - ssf_press_left_joystick(context, 128, 0, 0, 50); - ssf_press_left_joystick(context, 128, 255, 50, 100); - ssf_press_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 400); - context.wait_for_all_requests(); - break; - } - } - - WhiteButtonWatcher rinse_done(COLOR_BLUE, WhiteButton::ButtonY, {0.028, 0.923, 0.020, 0.034}); - WallClock start2 = current_time(); - int ret3 = run_until( - stream, context, - [&](ProControllerContext& context){ - while (true){ - if (current_time() - start2 > std::chrono::minutes(1)){ - stream.log("Failed to finish rinse after 1 minute.", COLOR_RED); - break; - } - ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); - ssf_press_left_joystick(context, 0, 128, 0, 50); - ssf_press_left_joystick(context, 255, 128, 50, 100); - ssf_press_left_joystick(context, 0, 128, 150, 50); - - ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); - ssf_press_left_joystick(context, 128, 0, 0, 50); - ssf_press_left_joystick(context, 128, 255, 50, 100); - ssf_press_left_joystick(context, 128, 0, 150, 50); - pbf_wait(context, 400); - context.wait_for_all_requests(); - } - }, - { {rinse_done} } - ); - if (ret3 == 0){ - stream.log("Shower completed successfully."); - }else{ - stream.log("Shower did not complete. Backing out."); - pbf_press_button(context, BUTTON_B, 40, 50); - } - - leave_picnic(info, stream, context); - - return_to_plaza(info, stream, context); - context.wait_for_all_requests(); -} - -void quest_hatch_egg( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -){ - console.log("Quest: Hatch an Egg"); - - //Fix time before hatching - if (BBQ_OPTIONS.FIX_TIME_FOR_HATCH){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - } - - //Fly to Savanna Plaza and navigate to the battle court - central_to_savanna_plaza(info, console, context); - - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 128, 0, 500, 50); - - pbf_move_left_joystick(context, 0, 128, 20, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - - //Do this after navigating to prevent egg from hatchining enroute - //Enter box system, navigate to left box, find the first egg, swap it with first pokemon in party - enter_box_system_from_overworld(info, console, context); - context.wait_for(std::chrono::milliseconds(400)); - - //move_to_left_box(context); - BoxCurrentEggDetector egg_detector; - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - bool egg_found = false; - uint8_t row = 0; - uint8_t col = 0; - for ( ; row < 5; row++){ - for (uint8_t j_col = 0; j_col < 6; j_col++){ - col = (row % 2 == 0 ? j_col : 5 - j_col); - move_box_cursor(info, console, context, BoxCursorLocation::SLOTS, row, col); - context.wait_for_all_requests(); - auto snapshot = console.video().snapshot(); - if (sth_in_box_detector.detect(snapshot) && egg_detector.detect(snapshot)){ - console.log("Found egg."); - egg_found = true; - break; - } - } - if (egg_found){ - break; - } - } - - if (!egg_found){ - console.log("No egg found during egg hatching quest!", COLOR_RED); - }else{ - swap_two_box_slots(info, console, context, - BoxCursorLocation::SLOTS, row, col, - BoxCursorLocation::PARTY, 0, 0); - - leave_box_system_to_overworld(info, console, context); - - hatch_eggs_anywhere(info, console, context, true, 1); - - enter_box_system_from_overworld(info, console, context); - context.wait_for(std::chrono::milliseconds(400)); - - swap_two_box_slots(info, console, context, - BoxCursorLocation::PARTY, 0, 0, - BoxCursorLocation::SLOTS, row, col); - - leave_box_system_to_overworld(info, console, context); - - pbf_press_button(context, BUTTON_PLUS, 20, 50); - - return_to_plaza(info, console, context); - context.wait_for_all_requests(); - } -} - -void quest_sandwich( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - stream.log("Quest: Make a singleplayer sandwich"); - - //Polar Plaza - egg basket gets stuck under table in Savanna/Canyon Plaza - central_to_polar_plaza(env.program_info(), stream, context); - - picnic_from_overworld(env.program_info(), stream, context); - - pbf_move_left_joystick(context, 128, 0, 30, 40); - context.wait_for_all_requests(); - - pbf_move_left_joystick(context, 128, 0, 70, 0); - enter_sandwich_recipe_list(env.program_info(), stream, context); - - std::map fillings; - std::map condiments; - - //Avoiding Encounter Power - switch (current_quest){ - case BBQuests::sour_sandwich: - //Apple, Marmalade: Catch Flying 1, Item Drop Ice 1, Egg 1 - fillings = {{"apple", (uint8_t)1}}; - condiments = {{"marmalade", (uint8_t)1}}; - break; - case BBQuests::sweet_sandwich: - //Apple, Butter: Egg 1, Item Drop Ice 1, Raid Steel 1 - fillings = {{"apple", (uint8_t)1}}; - condiments = {{"butter", (uint8_t)1}}; - break; - case BBQuests::spicy_sandwich: - //Apple, Curry Powder: Raid Steel 1, Item Drop Ice 1, Teensy Flying 1 - fillings = {{"apple", (uint8_t)1}}; - condiments = {{"curry-powder", (uint8_t)1}}; - break; - case BBQuests::salty_sandwich: - //Cheese, Salt: Exp Point Electric 1, Raid Normal 1, Catching Psychic 1 - fillings = {{"cheese", (uint8_t)1}}; - condiments = {{"salt", (uint8_t)1}}; - break; - case BBQuests::bitter_sandwich: - //Watercress, Pepper: Item Drop Normal 1, Raid Power Flying 1, Exp Point Fighting 1 - fillings = {{"watercress", (uint8_t)1}}; - condiments = {{"pepper", (uint8_t)1}}; - break; - case BBQuests::sandwich_three: - //Fried Fillet, Noodles, Rice, Chili Sauce: Huge Water 1, Raid Flying 1, Catching Normal 1 - fillings = { {"fried-fillet", (uint8_t)1}, {"noodles", (uint8_t)1}, {"rice", (uint8_t)1} }; - condiments = {{"chili-sauce", (uint8_t)1}}; - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid sandwich selection.", - stream - ); - break; - } - - make_sandwich_preset(env, stream, context, BBQ_OPTIONS.LANGUAGE, fillings, condiments); - - leave_picnic(env.program_info(), stream, context); - - return_to_plaza(env.program_info(), stream, context); - context.wait_for_all_requests(); - -} - -void quest_tera_raid( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - BBQOption& BBQ_OPTIONS -){ - console.log("Quest: Tera Raid"); - - bool started_tera_raid = false; - while (!started_tera_raid){ - EncounterWatcher encounter_watcher(console, COLOR_RED); - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - //Target is a tera raid crystal near the canyon plaza - console.log("Navigating to tera crystal."); - - central_to_canyon_plaza(env.program_info(), console, context); - - pbf_move_left_joystick(context, 0, 128, 375, 20); - pbf_press_button(context, BUTTON_L, 10, 50); - pbf_move_left_joystick(context, 0, 128, 90, 20); - pbf_press_button(context, BUTTON_L, 10, 50); - - //Keep rolling until we get a raid - uint64_t rerolls = 0; - while (!open_raid(console, context) && rerolls < 150){ - env.log("No Tera raid found.", COLOR_ORANGE); - day_skip_from_overworld(console, context); - pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); - rerolls++; - } - started_tera_raid = true; - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - - if (ret >= 0){ - console.log("Battle menu detected."); - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - console.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - console.log("Detected battle. Running from battle."); - try{ - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - battle_menu.move_to_slot(console, context, 3); - pbf_press_button(context, BUTTON_A, 10, 50); - press_Bs_to_back_to_overworld(env.program_info(), console, context); - return_to_plaza(env.program_info(), console, context); - }catch (...){ - console.log("Unable to flee."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to flee!", - console - ); - } - } - } - } - - //Swap to the second pokemon in your party - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_button(context, BUTTON_A, 20, 105); - context.wait_for(std::chrono::milliseconds(400)); - move_box_cursor(env.program_info(), console, context, BoxCursorLocation::PARTY, 1, 0); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_mash_button(context, BUTTON_A, 250); - - bool win = run_tera_battle(env, console, context, BBQ_OPTIONS.BATTLE_AI); - if (win){ - env.log("Won tera raid."); - if (!BBQ_OPTIONS.CATCH_ON_WIN.enabled()){ - exit_tera_win_without_catching(env.program_info(), console, context, 0); - }else{ - if (BBQ_OPTIONS.CATCH_ON_WIN.FIX_TIME_ON_CATCH){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - } - exit_tera_win_by_catching( - env, console, context, - BBQ_OPTIONS.LANGUAGE, - BBQ_OPTIONS.CATCH_ON_WIN.BALL_SELECT.slug(), - 0 - ); - } - }else{ - env.log("Lost tera raid."); - context.wait_for(std::chrono::seconds(3)); - } - - context.wait_for_all_requests(); - return_to_plaza(env.program_info(), console, context); - day_skip_from_overworld(console, context); -} - -void quest_auto_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -){ - stream.log("Quest: Auto Battle 10/30"); - - LetsGoEncounterBotStats stats; - LetsGoEncounterBotTracker tracker(env, stream, context, stats, BBQ_OPTIONS.LANGUAGE); - - uint64_t target_number = 10; - - if (current_quest == BBQuests::auto_30){ - target_number = 30; - } - - while (stats.m_kills < target_number){ - - central_to_chargestone(env.program_info(), stream, context); - - //Wait for spawns - pbf_wait(context, 375); - context.wait_for_all_requests(); - - //Forward and right, stay in the battle court - safe zone - pbf_press_button(context, BUTTON_L, 20, 50); - pbf_move_left_joystick(context, 128, 0, 250, 50); - pbf_move_left_joystick(context, 255, 128, 180, 50); - pbf_press_button(context, BUTTON_L, 20, 50); - - use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 180, 50); - pbf_wait(context, 1500); - context.wait_for_all_requests(); - }); - - context.wait_for_all_requests(); - return_to_plaza(env.program_info(), stream, context); - - OverworldWatcher done_healing(stream.logger(), COLOR_BLUE); - pbf_move_left_joystick(context, 128, 0, 100, 20); - - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - int exit = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 2000); - }, - { { done_healing } } - ); - if (exit == 0){ - stream.log("Overworld detected."); - } - open_map_from_overworld(env.program_info(), stream, context); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(env.program_info(), stream, context); - } -} - - - -} -} -} +/* Blueberry Quests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Inference/PokemonSV_BlueberryQuestDetector.h" +#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRelease.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" +#include "PokemonSV/Programs/Farming/PokemonSV_BlueberryCatchPhoto.h" +#include "PokemonSV/Programs/PokemonSV_Terarium.h" +#include "PokemonSV_BlueberryQuests.h" + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +const std::map& BBQuests_TOKEN_TO_ENUM(){ + static std::map data{ + {"auto-10", BBQuests::auto_10}, + {"make-tm", BBQuests::make_tm }, + {"pickup-10", BBQuests::pickup_10}, + {"sneak-up", BBQuests::sneak_up}, + {"photo-fly", BBQuests::photo_fly}, + {"photo-swim", BBQuests::photo_swim}, + {"photo-canyon", BBQuests::photo_canyon}, + {"photo-coastal", BBQuests::photo_coastal}, + {"photo-polar", BBQuests::photo_polar}, + {"photo-savanna", BBQuests::photo_savanna}, + {"tera-self-defeat", BBQuests::tera_self_defeat}, + {"travel-500", BBQuests::travel_500}, + {"catch-any", BBQuests::catch_any}, + {"catch-normal", BBQuests::catch_normal}, + {"catch-fighting", BBQuests::catch_fighting}, + {"catch-flying", BBQuests::catch_flying}, + {"catch-poison", BBQuests::catch_poison}, + {"catch-ground", BBQuests::catch_ground}, + {"catch-rock", BBQuests::catch_rock}, + {"catch-bug", BBQuests::catch_bug}, + {"catch-ghost", BBQuests::catch_ghost}, + {"catch-steel", BBQuests::catch_steel}, + {"catch-fire", BBQuests::catch_fire}, + {"catch-water", BBQuests::catch_water}, + {"catch-grass", BBQuests::catch_grass}, + {"catch-electric", BBQuests::catch_electric}, + {"catch-psychic", BBQuests::catch_psychic}, + {"catch-ice", BBQuests::catch_ice}, + {"catch-dragon", BBQuests::catch_dragon}, + {"catch-dark", BBQuests::catch_dark}, + {"catch-fairy", BBQuests::catch_fairy}, + {"wash-pokemon", BBQuests::wash_pokemon}, + {"wild-tera", BBQuests::wild_tera}, + {"auto-30", BBQuests::auto_30}, + {"tera-raid", BBQuests::tera_raid}, + {"sandwich-three", BBQuests::sandwich_three}, + {"bitter-sandwich", BBQuests::bitter_sandwich}, + {"sweet-sandwich", BBQuests::sweet_sandwich}, + {"salty-sandwich", BBQuests::salty_sandwich}, + {"sour-sandwich", BBQuests::sour_sandwich}, + {"spicy-sandwich", BBQuests::spicy_sandwich}, + {"hatch-egg", BBQuests::hatch_egg}, + {"photo-normal", BBQuests::photo_normal}, + {"photo-fighting", BBQuests::photo_fighting}, + {"photo-flying", BBQuests::photo_flying}, + {"photo-poison", BBQuests::photo_poison}, + {"photo-ground", BBQuests::photo_ground}, + {"photo-rock", BBQuests::photo_rock}, + {"photo-bug", BBQuests::photo_bug}, + {"photo-ghost", BBQuests::photo_ghost}, + {"photo-steel", BBQuests::photo_steel}, + {"photo-fire", BBQuests::photo_fire}, + {"photo-water", BBQuests::photo_water}, + {"photo-grass", BBQuests::photo_grass}, + {"photo-electric", BBQuests::photo_electric}, + {"photo-psychic", BBQuests::photo_psychic}, + {"photo-ice", BBQuests::photo_ice}, + {"photo-dragon", BBQuests::photo_dragon}, + {"photo-dark", BBQuests::photo_dark}, + {"photo-fairy", BBQuests::photo_fairy}, + {"ditto-central", BBQuests::ditto_central}, + {"ditto-canyon", BBQuests::ditto_canyon}, + {"ditto-coastal", BBQuests::ditto_coastal}, + {"ditto-polar", BBQuests::ditto_polar}, + {"ditto-savanna", BBQuests::ditto_savanna}, + {"group-canyon", BBQuests::group_canyon}, + {"group-coastal", BBQuests::group_coastal}, + {"group-polar", BBQuests::group_polar}, + {"group-savanna", BBQuests::group_savanna}, + {"group-eyewear", BBQuests::group_eyewear}, + {"group-nonuniform", BBQuests::group_nonuniform}, + {"group-masks", BBQuests::group_masks}, + {"sandwich-four", BBQuests::sandwich_four}, + {"catch-hint", BBQuests::catch_hint}, + {"catch-hint2", BBQuests::catch_hint2}, + {"", BBQuests::UnableToDetect}, + }; + return data; +} + +BBQuests BBQuests_string_to_enum(const std::string& token){ + auto iter = BBQuests_TOKEN_TO_ENUM().find(token); + if (iter == BBQuests_TOKEN_TO_ENUM().end()){ + return BBQuests::UnableToDetect; + } + return iter->second; +} + +int read_BP(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 6; i++) { //try 6 times + pbf_press_dpad(context, DPAD_RIGHT, 50, 20); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + }, + {{ right_panel }} + ); + if (result == 0){ + stream.log("Found quest panel."); + } + context.wait_for_all_requests(); + + VideoSnapshot screen = stream.video().snapshot(); + ImageRGB32 BP_value = to_blackwhite_rgb32_range( + extract_box_reference(screen, ImageFloatBox(0.866, 0.019, 0.091, 0.041)), + true, + combine_rgb(198, 198, 198), combine_rgb(255, 255, 255) + ); + + //Close panel + pbf_mash_button(context, BUTTON_B, 100); + context.wait_for_all_requests(); + + return OCR::read_number(stream.logger(), BP_value); +} + +std::vector read_quests( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +){ + std::vector quest_list; + + //Open quest list. Wait for it to open. + WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 6; i++) { //try 6 times + pbf_press_dpad(context, DPAD_RIGHT, 50, 20); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + }, + {{ right_panel }} + ); + if (result == 0){ + stream.log("Found quest panel."); + } + context.wait_for_all_requests(); + + //Read in the initial 4 quests. + stream.log("Reading quests."); + VideoSnapshot screen = stream.video().snapshot(); + BlueberryQuestDetector first_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::FIRST); + BlueberryQuestDetector second_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::SECOND); + BlueberryQuestDetector third_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::THIRD); + BlueberryQuestDetector fourth_quest_detector(stream.logger(), COLOR_GREEN, BBQ_OPTIONS.LANGUAGE, BlueberryQuestDetector::QuestPosition::FOURTH); + + quest_list.push_back(BBQuests_string_to_enum(first_quest_detector.detect_quest(screen))); + quest_list.push_back(BBQuests_string_to_enum(second_quest_detector.detect_quest(screen))); + quest_list.push_back(BBQuests_string_to_enum(third_quest_detector.detect_quest(screen))); + + std::string fourth_quest = fourth_quest_detector.detect_quest(screen); + if (fourth_quest != ""){ + quest_list.push_back(BBQuests_string_to_enum(fourth_quest)); + } + + //Close quest list + pbf_mash_button(context, BUTTON_B, 100); + context.wait_for_all_requests(); + + return quest_list; +} + +std::vector process_quest_list( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + std::vector& quest_list, + uint8_t& eggs_hatched +){ + std::vector quests_to_do; + bool rerolled = false; + std::vector> exclusions_table = BBQ_OPTIONS.QUEST_EXCLUSIONS.copy_snapshot(); + int questpos = 0; + + stream.log("Processing quests."); + //Put all do-able quests into a different list + for (auto n : quest_list){ + if (not_possible_quests.contains(n)){ + stream.log("Quest not possible"); + }else{ + //Check eggs remaining. + if (n == BBQuests::hatch_egg && eggs_hatched >= BBQ_OPTIONS.NUM_EGGS){ + stream.log("Out of eggs! Quest not possible."); + + switch (BBQ_OPTIONS.OUT_OF_EGGS){ + case BBQOption::OOEggs::Reroll: + { + stream.log("Reroll selected. Rerolling Egg quest. New quest will be run in the next batch of quests."); + //stream.log("Warning: This does not handle/check being out of BP!", COLOR_RED); + + WhiteButtonWatcher right_panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 6; i++){ + pbf_press_dpad(context, DPAD_RIGHT, 50, 20); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + }, + {{ right_panel }} + ); + if (result == 0){ + stream.log("Found quest panel."); + } + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + rerolled = true; + press_Bs_to_back_to_overworld(info, stream, context); + + break; + } + case BBQOption::OOEggs::KeepGoing: + stream.log("Keep Going selected. Ignoring quest."); + break; + default: + //This case is handled in BBQSoloFarmer. + stream.log("OOEggs is Stop in process_quest_list()."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "OOEggs is Stop in process_quest_list().", + stream + ); + break; + } + } + else{ + bool quest_in_table = false; + for(const std::unique_ptr& row : exclusions_table){ + if(n == row->quest) { + stream.log("Quest found in inclusions/exclusions table."); + quest_in_table = true; + + WhiteButtonWatcher rp2(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); + int result2; + switch (row->action) { + case BBQAction::run: + stream.log("Run selected. Adding quest to list."); + quests_to_do.push_back(n); + break; + case BBQAction::reroll: + stream.log("Reroll selected. Rerolling quest. New quest will be run in the next batch of quests."); + result2 = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 6; i++){ + pbf_press_dpad(context, DPAD_RIGHT, 50, 20); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + }, + {{ rp2 }} + ); + if (result2 == 0){ + stream.log("Found quest panel."); + } + context.wait_for_all_requests(); + + //Move cursor down to quest + for (int i = 0; i < questpos; i++) { + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + pbf_wait(context, 100); + context.wait_for_all_requests(); + } + + //Reroll + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + //Prevent error/rerolling again at the end (allows program to read the rerolled quests) + rerolled = true; + + press_Bs_to_back_to_overworld(info, stream, context); + break; + case BBQAction::skip: + stream.log("Skip selected. Skipping quest."); + break; + } + } + } + if(!quest_in_table){ + stream.log("Quest not in inclusion/exclusions table. Adding to list."); + quests_to_do.push_back(n); + } + } + } + questpos++; + } + + //Check that quests_to_do is not empty (after completing all quests on the list, be sure to erase it. + //Lag might be a problem in multi - look into making slots like menu-left navigation + if (!rerolled && quests_to_do.size() == 0){ + stream.log("No possible quests! Rerolling all quests."); + + //Open quest panel and reroll all quests. + //This does not handle out of BP. + WhiteButtonWatcher panel(COLOR_BLUE, WhiteButton::ButtonB, {0.484, 0.117, 0.022, 0.037}); + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 6; i++){ + pbf_press_dpad(context, DPAD_RIGHT, 50, 20); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + }, + {{ panel }} + ); + if (result == 0){ + stream.log("Found quest panel."); + } + context.wait_for_all_requests(); + + for (string::size_type i = 0; i < quest_list.size(); i++){ + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_button(context, BUTTON_A, 20, 50); //Yes. + pbf_wait(context, 100); + context.wait_for_all_requests(); + pbf_press_dpad(context, DPAD_DOWN, 20, 20); + pbf_wait(context, 100); + context.wait_for_all_requests(); + } + //Close quest panel - mash b + press_Bs_to_back_to_overworld(info, stream, context); + } + /* + if (!rerolled && quests_to_do.size() == 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No possible quests! Check language selection.", + stream + ); + } + */ + return quests_to_do; +} + +bool process_and_do_quest( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + BBQOption& BBQ_OPTIONS, + BBQuests current_quest, + uint8_t& eggs_hatched +){ + bool quest_completed = false; + int quest_attempts = 0; + + while (!quest_completed){ + switch (current_quest){ + case BBQuests::make_tm: + quest_make_tm(env.program_info(), console, context); + break; + case BBQuests::travel_500: + quest_travel_500(env.program_info(), console, context); + break; + case BBQuests::tera_self_defeat: + quest_tera_self_defeat(env.program_info(), console, context, BBQ_OPTIONS); + break; + case BBQuests::sneak_up: + quest_sneak_up(env.program_info(), console, context, BBQ_OPTIONS); + break; + case BBQuests::wild_tera: + quest_wild_tera(env.program_info(), console, context, BBQ_OPTIONS); + break; + case BBQuests::wash_pokemon: + quest_wash_pokemon(env.program_info(), console, context); + break; + case BBQuests::hatch_egg: + quest_hatch_egg(env.program_info(), console, context, BBQ_OPTIONS); + break; + case BBQuests::bitter_sandwich: + case BBQuests::salty_sandwich: + case BBQuests::sour_sandwich: + case BBQuests::spicy_sandwich: + case BBQuests::sweet_sandwich: + case BBQuests::sandwich_three: + quest_sandwich(env, console, context, BBQ_OPTIONS, current_quest); + break; + //case BBQuests::pickup_10: + // quest_pickup(env, env.program_info(), console, context, BBQ_OPTIONS); + // break; + case BBQuests::tera_raid: + quest_tera_raid(env, console, context, BBQ_OPTIONS); + break; + case BBQuests::auto_10: + case BBQuests::auto_30: + quest_auto_battle(env, console, context, BBQ_OPTIONS, current_quest); + break; + //All involve taking pictures + case BBQuests::photo_fly: + case BBQuests::photo_swim: + case BBQuests::photo_canyon: + case BBQuests::photo_coastal: + case BBQuests::photo_polar: + case BBQuests::photo_savanna: + case BBQuests::photo_normal: + case BBQuests::photo_fighting: + case BBQuests::photo_flying: + case BBQuests::photo_poison: + case BBQuests::photo_ground: + case BBQuests::photo_rock: + case BBQuests::photo_bug: + case BBQuests::photo_ghost: + case BBQuests::photo_steel: + case BBQuests::photo_fire: + case BBQuests::photo_water: + case BBQuests::photo_grass: + case BBQuests::photo_electric: + case BBQuests::photo_psychic: + case BBQuests::photo_ice: + case BBQuests::photo_dragon: + case BBQuests::photo_dark: + case BBQuests::photo_fairy: + quest_photo(env.program_info(), console, context, BBQ_OPTIONS, current_quest); + break; + //All involve catching a pokemon + case BBQuests::catch_any: + case BBQuests::catch_normal: + case BBQuests::catch_fighting: + case BBQuests::catch_flying: + case BBQuests::catch_poison: + case BBQuests::catch_ground: + case BBQuests::catch_rock: + case BBQuests::catch_bug: + case BBQuests::catch_ghost: + case BBQuests::catch_steel: + case BBQuests::catch_fire: + case BBQuests::catch_water: + case BBQuests::catch_grass: + case BBQuests::catch_electric: + case BBQuests::catch_psychic: + case BBQuests::catch_ice: + case BBQuests::catch_dragon: + case BBQuests::catch_dark: + case BBQuests::catch_fairy: + quest_catch(env.program_info(), console, context, BBQ_OPTIONS, current_quest); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unknown quest selection.", + console + ); + break; + } + + //Validate quest was completed by checking list + std::vector quest_list = read_quests(env.program_info(), console, context, BBQ_OPTIONS); + if (std::find(quest_list.begin(), quest_list.end(), current_quest) != quest_list.end()){ + console.log("Current quest exists on list. Quest did not complete."); + quest_attempts++; + }else{ + console.log("Current quest was not found. Quest completed!"); + if (current_quest == BBQuests::hatch_egg){ + eggs_hatched++; + console.log("Eggs hatched: " + std::to_string(eggs_hatched)); + } + + quest_completed = true; + } + + if (quest_attempts > BBQ_OPTIONS.NUM_RETRIES){ + console.log("Failed to complete a quest multiple times. Skipping it for now.", COLOR_RED); + break; + } + } + return quest_completed; +} + +void quest_make_tm(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Quest: Make TM"); + + //Mount and then dismount in case you're crouched + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_press_button(context, BUTTON_PLUS, 20, 105); + context.wait_for_all_requests(); + + GradientArrowWatcher machine(COLOR_BLUE, GradientArrowType::DOWN, {0.181, 0.127, 0.045, 0.070}); + PromptDialogWatcher makeTM(COLOR_RED); + OverworldWatcher overworld(stream.logger(), COLOR_BLUE); + + pbf_move_left_joystick(context, 255, 0, 100, 20); + pbf_press_button(context, BUTTON_L, 10, 50); + + int enter_machine = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_wait(context, 200); + context.wait_for_all_requests(); + } + }, + {{ machine }} + ); + context.wait_for_all_requests(); + + if (enter_machine == 0){ + stream.log("TM machine entered. Finding TM to make."); + + int make_tm = run_until( + stream, context, + [&](ProControllerContext& context){ + for (int i = 0; i < 229; i++) { //229 is max number of TMs + //click on tm + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + //not craftable, close and move on to next + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_dpad(context, DPAD_RIGHT, 20, 20); + pbf_wait(context, 100); + context.wait_for_all_requests(); + } + }, + {{ makeTM }} + ); + context.wait_for_all_requests(); + + if (make_tm == 0){ + stream.log("Craftable TM found. Making TM"); + + pbf_mash_button(context, BUTTON_A, 220); + context.wait_for_all_requests(); + }else{ + stream.log("Failed to find craftable TM!"); + } + }else{ + stream.log("Failed to enter TM machine!"); + } + + int exit = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 2000); + }, + {{ overworld }} + ); + if (exit == 0){ + stream.log("Overworld detected."); + } + context.wait_for_all_requests(); + + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(info, stream, context); + context.wait_for_all_requests(); +} + +void quest_travel_500(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Quest: Travel 500 meters."); + + //Mount and then dismount in case you're crouched + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_press_button(context, BUTTON_PLUS, 20, 105); + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 0, 0, 100, 20); + pbf_move_left_joystick(context, 128, 0, 150, 20); + pbf_move_left_joystick(context, 0, 128, 140, 20); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + for(int j = 0; j < 60; j++){ //One min just to be safe. + pbf_controller_state(context, BUTTON_LCLICK, DPAD_NONE, + 128, 0, 255, 128, TICKS_PER_SECOND); + } + context.wait_for_all_requests(); + + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(info, stream, context); + context.wait_for_all_requests(); +} + +void quest_tera_self_defeat( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +){ + EncounterWatcher encounter_watcher(console, COLOR_RED); + console.log("Quest: Tera-self and defeat any wild."); + //Navigate to target and start battle + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + central_to_canyon_plaza(info, console, context); + + pbf_move_left_joystick(context, 205, 64, 20, 105); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + //Drop on top of Kleavor (plenty of Scyther in the area as well) + if (console.state().console_type() == ConsoleType::Switch1) { + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1650, 300); + } else { //All switch 2s + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 1000, 1600, 300); + } + + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); + + pbf_wait(context, 300); + context.wait_for_all_requests(); + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret2 = wait_until( + console, context, + std::chrono::seconds(15), + { battle_menu } + ); + if (ret2 != 0){ + console.log("Did not enter battle. Did Kleavor spawn?"); + } + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + + if (ret >= 0){ + console.log("Battle menu detected."); + } + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + console.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + bool tera_self = true; + wild_battle_tera(info, console, context, tera_self); + } + pbf_press_button(context, BUTTON_PLUS, 20, 105); + return_to_plaza(info, console, context); + + //Day skip and attempt to respawn fixed encounters + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, true); + roll_date_forward_1(console, context, true); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + + //Heal up and then reset position again. + OverworldWatcher done_healing(console.logger(), COLOR_BLUE); + pbf_move_left_joystick(context, 128, 0, 100, 20); + + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + int exit = run_until( + console, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 2000); + }, + {{ done_healing }} + ); + if (exit == 0){ + console.log("Overworld detected."); + } + open_map_from_overworld(info, console, context); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(info, console, context); +} + +void quest_sneak_up( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +){ + EncounterWatcher encounter_watcher(console, COLOR_RED); + console.log("Quest: Sneak up."); + //Navigate to target and start battle + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + //Savanna Plaza - Pride Rock + central_to_savanna_plaza(info, console, context); + + pbf_move_left_joystick(context, 220, 255, 10, 20); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 600, 400, 400); + + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 255, 128, 20, 50); + + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 100, 50); + + //Turn slightly for switch 1 + if (console.state().console_type() == ConsoleType::Switch1) { + pbf_move_left_joystick(context, 0, 0, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + } + + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); + + pbf_wait(context, 300); + context.wait_for_all_requests(); + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret2 = wait_until( + console, context, + std::chrono::seconds(15), + { battle_menu } + ); + if (ret2 != 0){ + console.log("Did not enter battle. Did target spawn?"); + } + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + + if (ret >= 0){ + console.log("Battle menu detected."); + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + console.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + OverworldWatcher overworld(console.logger(), COLOR_BLUE); + + int ret2 = run_until( + console, context, + [&](ProControllerContext& context){ + while (true){ + //Flee immediately. Keep trying to flee. + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret2 = wait_until( + console, context, + std::chrono::seconds(60), + { battle_menu } + ); + switch (ret2){ + case 0: + battle_menu.move_to_slot(console, context, 3); + pbf_press_button(context, BUTTON_A, 10, 50); + break; + default: + console.log("Invalid state quest_sneak_up(). Smoke Ball equipped?"); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state quest_sneak_up(). Smoke Ball equipped?", + console + ); + } + } + }, + { overworld } + ); + + switch (ret2){ + case 0: + console.log("Overworld detected."); + break; + default: + console.log("Invalid state in run_battle()."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state in run_battle().", + console + ); + } + } + } + return_to_plaza(info, console, context); + + //Day skip and attempt to respawn fixed encounters - in case quest failed + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, true); + roll_date_forward_1(console, context, true); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + context.wait_for_all_requests(); +} + +void quest_wild_tera( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +){ + EncounterWatcher encounter_watcher(console, COLOR_RED); + console.log("Quest: Defeat a wild tera."); + //Navigate to target and start battle + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + //Canyon Rest Area + central_to_canyon_rest(info, console, context); + + pbf_move_left_joystick(context, 255, 180, 20, 105); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + jump_glide_fly(console, context, BBQ_OPTIONS.INVERTED_FLIGHT, 500, 1300, 150); + + //Skarmory is likely to attack but sometimes there is a different pokemon + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + if (console.state().console_type() == ConsoleType::Switch1) { + pbf_move_left_joystick(context, 50, 0, 20, 105); + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 100, 50); + } else { //Switch 2 + pbf_move_left_joystick(context, 20, 0, 20, 105); + pbf_press_button(context, BUTTON_L, 20, 50); + } + + ssf_press_button(context, BUTTON_ZR, 0ms, 1600ms); + ssf_press_button(context, BUTTON_ZL, 800ms, 400ms); + ssf_press_button(context, BUTTON_ZL, 1200ms, 400ms); + + pbf_wait(context, 300); + context.wait_for_all_requests(); + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret2 = wait_until( + console, context, + std::chrono::seconds(15), + { battle_menu } + ); + if (ret2 != 0){ + console.log("Did not enter battle."); + } + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + + if (ret >= 0){ + console.log("Battle menu detected."); + } + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + console.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + bool tera_self = false; + wild_battle_tera(info, console, context, tera_self); + } + return_to_plaza(info, console, context); + + //Day skip and attempt to respawn fixed encounters + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, true); + roll_date_forward_1(console, context, true); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + + //Heal up and then reset position again. + OverworldWatcher done_healing(console.logger(), COLOR_BLUE); + pbf_move_left_joystick(context, 128, 0, 100, 20); + + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + int exit = run_until( + console, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 2000); + }, + {{ done_healing }} + ); + if (exit == 0){ + console.log("Overworld detected."); + } + open_map_from_overworld(info, console, context); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(info, console, context); +} + +void quest_wash_pokemon(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Quest: Give your pokemon a bath!"); + + //Fly to savanna plaza + central_to_savanna_plaza(info, stream, context); + + //Turn around, open picnic + pbf_move_left_joystick(context, 128, 255, 20, 50); + pbf_press_button(context, BUTTON_L, 50, 40); + + picnic_from_overworld(info, stream, context); + + WallClock start = current_time(); + WhiteButtonWatcher wash_button(COLOR_BLUE, WhiteButton::ButtonX, {0.027, 0.548, 0.022, 0.032}); + WhiteButtonWatcher wash_exit_button(COLOR_BLUE, WhiteButton::ButtonB, {0.027, 0.923, 0.021, 0.033}); + WhiteButtonWatcher shower_switch(COLOR_BLUE, WhiteButton::ButtonY, {0.486, 0.870, 0.027, 0.045}); + bool rinsed_once = false; + while (!rinsed_once){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(3)){ + stream.log("Failed to get to rinse after 3 minutes.", COLOR_RED); + break; + } + int ret = wait_until( + stream, context, std::chrono::seconds(60), + { + wash_button, + shower_switch, + wash_exit_button, + } + ); + switch (ret){ + case 0: + stream.log("Wash button found!"); + pbf_mash_button(context, BUTTON_X, 150); + pbf_wait(context, 200); + context.wait_for_all_requests(); + break; + case 1: + stream.log("Rinse button found. Switching to rinse."); + pbf_press_button(context, BUTTON_Y, 40, 50); + rinsed_once = true; + //Move slightly right, as the showerhead is at an angle + pbf_move_left_joystick(context, 255, 0, 30, 30); + context.wait_for_all_requests(); + break; + case 2: + stream.log("In wash. Scrubbing."); + + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); + ssf_press_left_joystick(context, 0, 128, 0, 50); + ssf_press_left_joystick(context, 255, 128, 50, 100); + ssf_press_left_joystick(context, 0, 128, 150, 50); + + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); + ssf_press_left_joystick(context, 128, 0, 0, 50); + ssf_press_left_joystick(context, 128, 255, 50, 100); + ssf_press_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 400); + context.wait_for_all_requests(); + break; + } + } + + WhiteButtonWatcher rinse_done(COLOR_BLUE, WhiteButton::ButtonY, {0.028, 0.923, 0.020, 0.034}); + WallClock start2 = current_time(); + int ret3 = run_until( + stream, context, + [&](ProControllerContext& context){ + while (true){ + if (current_time() - start2 > std::chrono::minutes(1)){ + stream.log("Failed to finish rinse after 1 minute.", COLOR_RED); + break; + } + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); + ssf_press_left_joystick(context, 0, 128, 0, 50); + ssf_press_left_joystick(context, 255, 128, 50, 100); + ssf_press_left_joystick(context, 0, 128, 150, 50); + + ssf_press_button(context, BUTTON_A, 0ms, 1600ms, 0ms); + ssf_press_left_joystick(context, 128, 0, 0, 50); + ssf_press_left_joystick(context, 128, 255, 50, 100); + ssf_press_left_joystick(context, 128, 0, 150, 50); + pbf_wait(context, 400); + context.wait_for_all_requests(); + } + }, + { {rinse_done} } + ); + if (ret3 == 0){ + stream.log("Shower completed successfully."); + }else{ + stream.log("Shower did not complete. Backing out."); + pbf_press_button(context, BUTTON_B, 40, 50); + } + + leave_picnic(info, stream, context); + + return_to_plaza(info, stream, context); + context.wait_for_all_requests(); +} + +void quest_hatch_egg( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +){ + console.log("Quest: Hatch an Egg"); + + //Fix time before hatching + if (BBQ_OPTIONS.FIX_TIME_FOR_HATCH){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + } + + //Fly to Savanna Plaza and navigate to the battle court + central_to_savanna_plaza(info, console, context); + + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 128, 0, 500, 50); + + pbf_move_left_joystick(context, 0, 128, 20, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + + //Do this after navigating to prevent egg from hatchining enroute + //Enter box system, navigate to left box, find the first egg, swap it with first pokemon in party + enter_box_system_from_overworld(info, console, context); + context.wait_for(std::chrono::milliseconds(400)); + + //move_to_left_box(context); + BoxCurrentEggDetector egg_detector; + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + bool egg_found = false; + uint8_t row = 0; + uint8_t col = 0; + for ( ; row < 5; row++){ + for (uint8_t j_col = 0; j_col < 6; j_col++){ + col = (row % 2 == 0 ? j_col : 5 - j_col); + move_box_cursor(info, console, context, BoxCursorLocation::SLOTS, row, col); + context.wait_for_all_requests(); + auto snapshot = console.video().snapshot(); + if (sth_in_box_detector.detect(snapshot) && egg_detector.detect(snapshot)){ + console.log("Found egg."); + egg_found = true; + break; + } + } + if (egg_found){ + break; + } + } + + if (!egg_found){ + console.log("No egg found during egg hatching quest!", COLOR_RED); + }else{ + swap_two_box_slots(info, console, context, + BoxCursorLocation::SLOTS, row, col, + BoxCursorLocation::PARTY, 0, 0); + + leave_box_system_to_overworld(info, console, context); + + hatch_eggs_anywhere(info, console, context, true, 1); + + enter_box_system_from_overworld(info, console, context); + context.wait_for(std::chrono::milliseconds(400)); + + swap_two_box_slots(info, console, context, + BoxCursorLocation::PARTY, 0, 0, + BoxCursorLocation::SLOTS, row, col); + + leave_box_system_to_overworld(info, console, context); + + pbf_press_button(context, BUTTON_PLUS, 20, 50); + + return_to_plaza(info, console, context); + context.wait_for_all_requests(); + } +} + +void quest_sandwich( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + stream.log("Quest: Make a singleplayer sandwich"); + + //Polar Plaza - egg basket gets stuck under table in Savanna/Canyon Plaza + central_to_polar_plaza(env.program_info(), stream, context); + + picnic_from_overworld(env.program_info(), stream, context); + + pbf_move_left_joystick(context, 128, 0, 30, 40); + context.wait_for_all_requests(); + + pbf_move_left_joystick(context, 128, 0, 70, 0); + enter_sandwich_recipe_list(env.program_info(), stream, context); + + std::map fillings; + std::map condiments; + + //Avoiding Encounter Power + switch (current_quest){ + case BBQuests::sour_sandwich: + //Apple, Marmalade: Catch Flying 1, Item Drop Ice 1, Egg 1 + fillings = {{"apple", (uint8_t)1}}; + condiments = {{"marmalade", (uint8_t)1}}; + break; + case BBQuests::sweet_sandwich: + //Apple, Butter: Egg 1, Item Drop Ice 1, Raid Steel 1 + fillings = {{"apple", (uint8_t)1}}; + condiments = {{"butter", (uint8_t)1}}; + break; + case BBQuests::spicy_sandwich: + //Apple, Curry Powder: Raid Steel 1, Item Drop Ice 1, Teensy Flying 1 + fillings = {{"apple", (uint8_t)1}}; + condiments = {{"curry-powder", (uint8_t)1}}; + break; + case BBQuests::salty_sandwich: + //Cheese, Salt: Exp Point Electric 1, Raid Normal 1, Catching Psychic 1 + fillings = {{"cheese", (uint8_t)1}}; + condiments = {{"salt", (uint8_t)1}}; + break; + case BBQuests::bitter_sandwich: + //Watercress, Pepper: Item Drop Normal 1, Raid Power Flying 1, Exp Point Fighting 1 + fillings = {{"watercress", (uint8_t)1}}; + condiments = {{"pepper", (uint8_t)1}}; + break; + case BBQuests::sandwich_three: + //Fried Fillet, Noodles, Rice, Chili Sauce: Huge Water 1, Raid Flying 1, Catching Normal 1 + fillings = { {"fried-fillet", (uint8_t)1}, {"noodles", (uint8_t)1}, {"rice", (uint8_t)1} }; + condiments = {{"chili-sauce", (uint8_t)1}}; + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid sandwich selection.", + stream + ); + break; + } + + make_sandwich_preset(env, stream, context, BBQ_OPTIONS.LANGUAGE, fillings, condiments); + + leave_picnic(env.program_info(), stream, context); + + return_to_plaza(env.program_info(), stream, context); + context.wait_for_all_requests(); + +} + +void quest_tera_raid( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + BBQOption& BBQ_OPTIONS +){ + console.log("Quest: Tera Raid"); + + bool started_tera_raid = false; + while (!started_tera_raid){ + EncounterWatcher encounter_watcher(console, COLOR_RED); + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + //Target is a tera raid crystal near the canyon plaza + console.log("Navigating to tera crystal."); + + central_to_canyon_plaza(env.program_info(), console, context); + + pbf_move_left_joystick(context, 0, 128, 375, 20); + pbf_press_button(context, BUTTON_L, 10, 50); + pbf_move_left_joystick(context, 0, 128, 90, 20); + pbf_press_button(context, BUTTON_L, 10, 50); + + //Keep rolling until we get a raid + uint64_t rerolls = 0; + while (!open_raid(console, context) && rerolls < 150){ + env.log("No Tera raid found.", COLOR_ORANGE); + day_skip_from_overworld(console, context); + pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); + rerolls++; + } + started_tera_raid = true; + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + + if (ret >= 0){ + console.log("Battle menu detected."); + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + console.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + console.log("Detected battle. Running from battle."); + try{ + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + battle_menu.move_to_slot(console, context, 3); + pbf_press_button(context, BUTTON_A, 10, 50); + press_Bs_to_back_to_overworld(env.program_info(), console, context); + return_to_plaza(env.program_info(), console, context); + }catch (...){ + console.log("Unable to flee."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to flee!", + console + ); + } + } + } + } + + //Swap to the second pokemon in your party + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_button(context, BUTTON_A, 20, 105); + context.wait_for(std::chrono::milliseconds(400)); + move_box_cursor(env.program_info(), console, context, BoxCursorLocation::PARTY, 1, 0); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_mash_button(context, BUTTON_A, 250); + + bool win = run_tera_battle(env, console, context, BBQ_OPTIONS.BATTLE_AI); + if (win){ + env.log("Won tera raid."); + if (!BBQ_OPTIONS.CATCH_ON_WIN.enabled()){ + exit_tera_win_without_catching(env.program_info(), console, context, 0); + }else{ + if (BBQ_OPTIONS.CATCH_ON_WIN.FIX_TIME_ON_CATCH){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + } + exit_tera_win_by_catching( + env, console, context, + BBQ_OPTIONS.LANGUAGE, + BBQ_OPTIONS.CATCH_ON_WIN.BALL_SELECT.slug(), + 0 + ); + } + }else{ + env.log("Lost tera raid."); + context.wait_for(std::chrono::seconds(3)); + } + + context.wait_for_all_requests(); + return_to_plaza(env.program_info(), console, context); + day_skip_from_overworld(console, context); +} + +void quest_auto_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +){ + stream.log("Quest: Auto Battle 10/30"); + + LetsGoEncounterBotStats stats; + LetsGoEncounterBotTracker tracker(env, stream, context, stats, BBQ_OPTIONS.LANGUAGE); + + uint64_t target_number = 10; + + if (current_quest == BBQuests::auto_30){ + target_number = 30; + } + + while (stats.m_kills < target_number){ + + central_to_chargestone(env.program_info(), stream, context); + + //Wait for spawns + pbf_wait(context, 375); + context.wait_for_all_requests(); + + //Forward and right, stay in the battle court - safe zone + pbf_press_button(context, BUTTON_L, 20, 50); + pbf_move_left_joystick(context, 128, 0, 250, 50); + pbf_move_left_joystick(context, 255, 128, 180, 50); + pbf_press_button(context, BUTTON_L, 20, 50); + + use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 180, 50); + pbf_wait(context, 1500); + context.wait_for_all_requests(); + }); + + context.wait_for_all_requests(); + return_to_plaza(env.program_info(), stream, context); + + OverworldWatcher done_healing(stream.logger(), COLOR_BLUE); + pbf_move_left_joystick(context, 128, 0, 100, 20); + + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + int exit = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 2000); + }, + { { done_healing } } + ); + if (exit == 0){ + stream.log("Overworld detected."); + } + open_map_from_overworld(env.program_info(), stream, context); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(env.program_info(), stream, context); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h index 48d187b6b6..fa0930a9e9 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_BlueberryQuests.h @@ -1,159 +1,159 @@ -/* Blueberry Quests - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_BlueberryQuests_H -#define PokemonAutomation_PokemonSV_BlueberryQuests_H - -#include -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" -#include "PokemonSV/Options/PokemonSV_BBQOption.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - -BBQuests BBQuests_string_to_enum(const std::string& token); - -enum class CameraAngle{ - none, - up, - down -}; - -//Basic blue quests -const std::set blue_quests = { - BBQuests::auto_10, BBQuests::make_tm, BBQuests::pickup_10, BBQuests::sneak_up, BBQuests::photo_fly, BBQuests::photo_swim, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar, BBQuests::photo_savanna, BBQuests::tera_self_defeat, - BBQuests::travel_500, BBQuests::catch_any, BBQuests::catch_normal, BBQuests::catch_fighting, BBQuests::catch_flying, BBQuests::catch_poison, BBQuests::catch_ground, BBQuests::catch_rock, BBQuests::catch_bug, BBQuests::catch_ghost, BBQuests::catch_steel, - BBQuests::catch_fire, BBQuests::catch_water, BBQuests::catch_grass, BBQuests::catch_electric, BBQuests::catch_psychic, BBQuests::catch_ice, BBQuests::catch_dragon, BBQuests::catch_dark, BBQuests::catch_fairy -}; - -//Red quests that appear at the top when a player completes 10 blues. -//In multiplayer, check if picnic is active before attempting some as only one player can picnic at a time. -const std::set red_quests = { - BBQuests::wash_pokemon, BBQuests::wild_tera, BBQuests::auto_30, BBQuests::tera_raid, BBQuests::sandwich_three, BBQuests::bitter_sandwich, BBQuests::sweet_sandwich, BBQuests::salty_sandwich, BBQuests::sour_sandwich, BBQuests::spicy_sandwich, BBQuests::hatch_egg, - BBQuests::photo_normal, BBQuests::photo_fighting, BBQuests::photo_flying, BBQuests::photo_poison, BBQuests::photo_ground, BBQuests::photo_rock, BBQuests::photo_bug, BBQuests::photo_ghost, BBQuests::photo_steel, BBQuests::photo_fire, BBQuests::photo_water, - BBQuests::photo_grass, BBQuests::photo_electric, BBQuests::photo_psychic, BBQuests::photo_ice, BBQuests::photo_dragon, BBQuests::photo_dark, BBQuests::photo_fairy -}; - -//Multiplayer only. Appears at the top when 3 red quests are completed. -const std::set gold_quests = { - BBQuests::ditto_central, BBQuests::ditto_canyon, BBQuests::ditto_coastal, BBQuests::ditto_polar, BBQuests::ditto_savanna, BBQuests::group_canyon, BBQuests::group_coastal, BBQuests::group_polar, BBQuests::group_savanna, BBQuests::group_eyewear, BBQuests::group_nonuniform, - BBQuests::group_masks, BBQuests::sandwich_four, BBQuests::catch_hint, BBQuests::catch_hint2 -}; - -//Quests that are not currently supported. Gold quests currently excluded as this is singleplayer only right now. -const std::set not_possible_quests = { - BBQuests::UnableToDetect, BBQuests::pickup_10 -}; - - -// Open the BBQ panel and read the current amount of BP -int read_BP(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -//Open the quest panel and read in the current quests. -//Currently only supports singleplayer. -//For multiplayer, we will want keep track of which quest are gold/red and scroll cursor down until all of the current player's blue quests are in. -std::vector read_quests( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -); - -//Determine which quests are possible and which quests are not. (ex. no eggs, reroll egg hatcher.) -//Quests not possible are removed from the list. If the list is empty, then reroll all items. -std::vector process_quest_list( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - std::vector& quest_list, - uint8_t& eggs_hatched -); - -//Take the current quest and calls the function to do it, then checks the quest was successful. Returns true if so. -bool process_and_do_quest( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - BBQOption& BBQ_OPTIONS, - BBQuests current_quest, - uint8_t& eggs_hatched -); - -//Iterate through TMs until a craftable one is found. Make the TM and return to position. -void quest_make_tm( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -//Do laps in central plaza. -void quest_travel_500( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -//Run around until you encounter a pokemon. Tera, then defeat it by spamming your first move. -void quest_tera_self_defeat( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -); - -//Sneak up on a pokemon -void quest_sneak_up( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -); - -//Kill a tera pokemon -void quest_wild_tera( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -); - -//Give bath -void quest_wash_pokemon( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -//Withdraw and hatch an egg -void quest_hatch_egg( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS -); - -//Make a sandwich of type flavor -void quest_sandwich( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - -//Complete a tera raid battle -void quest_tera_raid( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - BBQOption& BBQ_OPTIONS -); - -//Defeat 10/30 pokemon in autobattle -void quest_auto_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - const BBQOption& BBQ_OPTIONS, - BBQuests current_quest -); - -} -} -} -#endif +/* Blueberry Quests + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_BlueberryQuests_H +#define PokemonAutomation_PokemonSV_BlueberryQuests_H + +#include +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" +#include "PokemonSV/Options/PokemonSV_BBQOption.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + +BBQuests BBQuests_string_to_enum(const std::string& token); + +enum class CameraAngle{ + none, + up, + down +}; + +//Basic blue quests +const std::set blue_quests = { + BBQuests::auto_10, BBQuests::make_tm, BBQuests::pickup_10, BBQuests::sneak_up, BBQuests::photo_fly, BBQuests::photo_swim, BBQuests::photo_canyon, BBQuests::photo_coastal, BBQuests::photo_polar, BBQuests::photo_savanna, BBQuests::tera_self_defeat, + BBQuests::travel_500, BBQuests::catch_any, BBQuests::catch_normal, BBQuests::catch_fighting, BBQuests::catch_flying, BBQuests::catch_poison, BBQuests::catch_ground, BBQuests::catch_rock, BBQuests::catch_bug, BBQuests::catch_ghost, BBQuests::catch_steel, + BBQuests::catch_fire, BBQuests::catch_water, BBQuests::catch_grass, BBQuests::catch_electric, BBQuests::catch_psychic, BBQuests::catch_ice, BBQuests::catch_dragon, BBQuests::catch_dark, BBQuests::catch_fairy +}; + +//Red quests that appear at the top when a player completes 10 blues. +//In multiplayer, check if picnic is active before attempting some as only one player can picnic at a time. +const std::set red_quests = { + BBQuests::wash_pokemon, BBQuests::wild_tera, BBQuests::auto_30, BBQuests::tera_raid, BBQuests::sandwich_three, BBQuests::bitter_sandwich, BBQuests::sweet_sandwich, BBQuests::salty_sandwich, BBQuests::sour_sandwich, BBQuests::spicy_sandwich, BBQuests::hatch_egg, + BBQuests::photo_normal, BBQuests::photo_fighting, BBQuests::photo_flying, BBQuests::photo_poison, BBQuests::photo_ground, BBQuests::photo_rock, BBQuests::photo_bug, BBQuests::photo_ghost, BBQuests::photo_steel, BBQuests::photo_fire, BBQuests::photo_water, + BBQuests::photo_grass, BBQuests::photo_electric, BBQuests::photo_psychic, BBQuests::photo_ice, BBQuests::photo_dragon, BBQuests::photo_dark, BBQuests::photo_fairy +}; + +//Multiplayer only. Appears at the top when 3 red quests are completed. +const std::set gold_quests = { + BBQuests::ditto_central, BBQuests::ditto_canyon, BBQuests::ditto_coastal, BBQuests::ditto_polar, BBQuests::ditto_savanna, BBQuests::group_canyon, BBQuests::group_coastal, BBQuests::group_polar, BBQuests::group_savanna, BBQuests::group_eyewear, BBQuests::group_nonuniform, + BBQuests::group_masks, BBQuests::sandwich_four, BBQuests::catch_hint, BBQuests::catch_hint2 +}; + +//Quests that are not currently supported. Gold quests currently excluded as this is singleplayer only right now. +const std::set not_possible_quests = { + BBQuests::UnableToDetect, BBQuests::pickup_10 +}; + + +// Open the BBQ panel and read the current amount of BP +int read_BP(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +//Open the quest panel and read in the current quests. +//Currently only supports singleplayer. +//For multiplayer, we will want keep track of which quest are gold/red and scroll cursor down until all of the current player's blue quests are in. +std::vector read_quests( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +); + +//Determine which quests are possible and which quests are not. (ex. no eggs, reroll egg hatcher.) +//Quests not possible are removed from the list. If the list is empty, then reroll all items. +std::vector process_quest_list( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + std::vector& quest_list, + uint8_t& eggs_hatched +); + +//Take the current quest and calls the function to do it, then checks the quest was successful. Returns true if so. +bool process_and_do_quest( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + BBQOption& BBQ_OPTIONS, + BBQuests current_quest, + uint8_t& eggs_hatched +); + +//Iterate through TMs until a craftable one is found. Make the TM and return to position. +void quest_make_tm( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +//Do laps in central plaza. +void quest_travel_500( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +//Run around until you encounter a pokemon. Tera, then defeat it by spamming your first move. +void quest_tera_self_defeat( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +); + +//Sneak up on a pokemon +void quest_sneak_up( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +); + +//Kill a tera pokemon +void quest_wild_tera( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +); + +//Give bath +void quest_wash_pokemon( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +//Withdraw and hatch an egg +void quest_hatch_egg( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS +); + +//Make a sandwich of type flavor +void quest_sandwich( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + +//Complete a tera raid battle +void quest_tera_raid( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + BBQOption& BBQ_OPTIONS +); + +//Defeat 10/30 pokemon in autobattle +void quest_auto_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + const BBQOption& BBQ_OPTIONS, + BBQuests current_quest +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.cpp index 32009d971d..6e9afdf24f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.cpp @@ -1,256 +1,256 @@ -/* ESP Training - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h" -#include "PokemonSV_ESPTraining.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -ESPTraining_Descriptor::ESPTraining_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:ESPTraining", - STRING_POKEMON + " SV", "ESP Training", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ESPTraining.md", - "Clear the ESP Training to farm EV berries.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ESPTraining_Descriptor::Stats : public StatsTracker{ - Stats() - : m_emotions(m_stats["Emotions Shown"]) - , m_joy(m_stats["Joy"]) - , m_surprise(m_stats["Surprise"]) - , m_excitement(m_stats["Excitement"]) - , m_anger(m_stats["Anger"]) - , m_clears(m_stats["Times Cleared"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Emotions Shown"); - m_display_order.emplace_back("Joy"); - m_display_order.emplace_back("Surprise"); - m_display_order.emplace_back("Excitement"); - m_display_order.emplace_back("Anger"); - m_display_order.emplace_back("Times Cleared"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_emotions; - std::atomic& m_joy; - std::atomic& m_surprise; - std::atomic& m_excitement; - std::atomic& m_anger; - std::atomic& m_clears; - std::atomic& errors; -}; -std::unique_ptr ESPTraining_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} -ESPTraining::ESPTraining() - : ROUNDS( - "Number of times to run:", - LockMode::UNLOCK_WHILE_RUNNING, - 10 - ) - , SAVE( - "Save game between rounds:
Save the game between ESP runs in case of crashes.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - & NOTIFICATION_PROGRAM_FINISH, - & NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(ROUNDS); - PA_ADD_OPTION(SAVE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void ESPTraining::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - ESPTraining_Descriptor::Stats& stats = env.current_stats(); - - for (uint32_t c = 0; c < ROUNDS; c++){ - env.log("Round: " + tostr_u_commas(c)); - - //Initiate dialog with Dendra - //Dendra needs time to turn and face the player - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - pbf_press_button(context, BUTTON_A, 10, 50); - int retD = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); - if (retD < 0){ - env.log("Dialog detected."); - } - pbf_press_button(context, BUTTON_A, 10, 50); - - //Yes let's train - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - //What mode? - Knockout - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - context.wait_for_all_requests(); - - //mash past other dialog - pbf_mash_button(context, BUTTON_A, 360); - - //wait for start - context.wait_for(std::chrono::milliseconds(13000)); - context.wait_for_all_requests(); - - //Detect emotion and press the right button - //151 emotions + pauses but the game is inconsistent and sometimes displays an emotion during the transitions - //Note: can hit the wrong emotion and then the right one right after, as long as its before the timer - bool endflag = true; - while (endflag){ - ESPStartDetector ESPstart; - ESPShowNewEmotionDetector ESPstop; - ESPEmotionDetector detector; - { - //Countdown -> Dialog w/emotion - int ret = wait_until( - env.console, context, - std::chrono::seconds(15), - { { ESPstart } } - ); - if (ret < 0){ - env.log("Timeout waiting for dialog."); - endflag = false; - break; - } - int ret2 = wait_until( - env.console, context, - std::chrono::seconds(5), - { { detector } } - ); - if (ret2 < 0){ - env.log("Timeout waiting for emotion."); - } - - Button emotion_button = BUTTON_X; - - switch (detector.result()){ - case Detection::RED: - env.log("ESPEmotionDetector: Angry - Red - Press X", COLOR_BLACK); - emotion_button = BUTTON_X; - stats.m_emotions++; - stats.m_anger++; - break; - case Detection::YELLOW: - env.log("ESPEmotionDetector: Joy - Yellow - Press A", COLOR_BLACK); - emotion_button = BUTTON_A; - stats.m_emotions++; - stats.m_joy++; - break; - case Detection::BLUE: - env.log("ESPEmotionDetector: Surprised - Blue - Press B", COLOR_BLACK); - emotion_button = BUTTON_B; - stats.m_emotions++; - stats.m_surprise++; - break; - case Detection::GREEN: - env.log("ESPEmotionDetector: Excited - Green - Press Y", COLOR_BLACK); - emotion_button = BUTTON_Y; - stats.m_emotions++; - stats.m_excitement++; - break; - case Detection::GREY: - //Press any button to start next round - //Pressing A tends to make Dendra :D two extra times during the transition so press B instead - //Sometimes this is detected as blue, the B press there also works - env.log("ESPEmotionDetector: Grey - Mash though dialog", COLOR_BLACK); - emotion_button = BUTTON_B; - break; - default: - endflag = false; - break; - } - - // Press button and check it did not drop input. Press again if it did. - // This will result in a duplicate press between phases, but the press will do nothing. - pbf_press_button(context, emotion_button, 10, 50); - env.update_stats(); - - ESPPressedEmotionDetector emotion_press_detected; - int check = wait_until( - env.console, context, - std::chrono::seconds(1), - { { emotion_press_detected } } - ); - if (check < 0){ - env.log("Emotion press not detected in bottom right. Pressing button again."); - pbf_press_button(context, emotion_button, 10, 50); - }else{ - env.log("Emotion press detected."); - } - - //Look for the brief moment the dialog bubble vanishes - ret = wait_until( - env.console, context, - std::chrono::seconds(15), - { { ESPstop } } - ); - if (ret < 0){ - env.log("Timeout waiting for dialog to vanish."); - } - } - context.wait_for_all_requests(); - } - - //Program done, mash B until overworld detected - OverworldWatcher overworld(env.console, COLOR_CYAN); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 700); - }, - {overworld} - ); - if (ret != 0){ - env.console.log("Failed to detect overworld after ending.", COLOR_RED); - } - context.wait_for_all_requests(); - - //Save the game if option checked, then loop again - if(SAVE){ - save_game_from_overworld(env.program_info(), env.console, context); - } - - stats.m_clears++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} +/* ESP Training + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/PokemonSV_ESPEmotionDetector.h" +#include "PokemonSV_ESPTraining.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +ESPTraining_Descriptor::ESPTraining_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:ESPTraining", + STRING_POKEMON + " SV", "ESP Training", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ESPTraining.md", + "Clear the ESP Training to farm EV berries.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ESPTraining_Descriptor::Stats : public StatsTracker{ + Stats() + : m_emotions(m_stats["Emotions Shown"]) + , m_joy(m_stats["Joy"]) + , m_surprise(m_stats["Surprise"]) + , m_excitement(m_stats["Excitement"]) + , m_anger(m_stats["Anger"]) + , m_clears(m_stats["Times Cleared"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Emotions Shown"); + m_display_order.emplace_back("Joy"); + m_display_order.emplace_back("Surprise"); + m_display_order.emplace_back("Excitement"); + m_display_order.emplace_back("Anger"); + m_display_order.emplace_back("Times Cleared"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_emotions; + std::atomic& m_joy; + std::atomic& m_surprise; + std::atomic& m_excitement; + std::atomic& m_anger; + std::atomic& m_clears; + std::atomic& errors; +}; +std::unique_ptr ESPTraining_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} +ESPTraining::ESPTraining() + : ROUNDS( + "Number of times to run:", + LockMode::UNLOCK_WHILE_RUNNING, + 10 + ) + , SAVE( + "Save game between rounds:
Save the game between ESP runs in case of crashes.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + & NOTIFICATION_PROGRAM_FINISH, + & NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(ROUNDS); + PA_ADD_OPTION(SAVE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void ESPTraining::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + ESPTraining_Descriptor::Stats& stats = env.current_stats(); + + for (uint32_t c = 0; c < ROUNDS; c++){ + env.log("Round: " + tostr_u_commas(c)); + + //Initiate dialog with Dendra + //Dendra needs time to turn and face the player + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + pbf_press_button(context, BUTTON_A, 10, 50); + int retD = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); + if (retD < 0){ + env.log("Dialog detected."); + } + pbf_press_button(context, BUTTON_A, 10, 50); + + //Yes let's train + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + //What mode? - Knockout + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + context.wait_for_all_requests(); + + //mash past other dialog + pbf_mash_button(context, BUTTON_A, 360); + + //wait for start + context.wait_for(std::chrono::milliseconds(13000)); + context.wait_for_all_requests(); + + //Detect emotion and press the right button + //151 emotions + pauses but the game is inconsistent and sometimes displays an emotion during the transitions + //Note: can hit the wrong emotion and then the right one right after, as long as its before the timer + bool endflag = true; + while (endflag){ + ESPStartDetector ESPstart; + ESPShowNewEmotionDetector ESPstop; + ESPEmotionDetector detector; + { + //Countdown -> Dialog w/emotion + int ret = wait_until( + env.console, context, + std::chrono::seconds(15), + { { ESPstart } } + ); + if (ret < 0){ + env.log("Timeout waiting for dialog."); + endflag = false; + break; + } + int ret2 = wait_until( + env.console, context, + std::chrono::seconds(5), + { { detector } } + ); + if (ret2 < 0){ + env.log("Timeout waiting for emotion."); + } + + Button emotion_button = BUTTON_X; + + switch (detector.result()){ + case Detection::RED: + env.log("ESPEmotionDetector: Angry - Red - Press X", COLOR_BLACK); + emotion_button = BUTTON_X; + stats.m_emotions++; + stats.m_anger++; + break; + case Detection::YELLOW: + env.log("ESPEmotionDetector: Joy - Yellow - Press A", COLOR_BLACK); + emotion_button = BUTTON_A; + stats.m_emotions++; + stats.m_joy++; + break; + case Detection::BLUE: + env.log("ESPEmotionDetector: Surprised - Blue - Press B", COLOR_BLACK); + emotion_button = BUTTON_B; + stats.m_emotions++; + stats.m_surprise++; + break; + case Detection::GREEN: + env.log("ESPEmotionDetector: Excited - Green - Press Y", COLOR_BLACK); + emotion_button = BUTTON_Y; + stats.m_emotions++; + stats.m_excitement++; + break; + case Detection::GREY: + //Press any button to start next round + //Pressing A tends to make Dendra :D two extra times during the transition so press B instead + //Sometimes this is detected as blue, the B press there also works + env.log("ESPEmotionDetector: Grey - Mash though dialog", COLOR_BLACK); + emotion_button = BUTTON_B; + break; + default: + endflag = false; + break; + } + + // Press button and check it did not drop input. Press again if it did. + // This will result in a duplicate press between phases, but the press will do nothing. + pbf_press_button(context, emotion_button, 10, 50); + env.update_stats(); + + ESPPressedEmotionDetector emotion_press_detected; + int check = wait_until( + env.console, context, + std::chrono::seconds(1), + { { emotion_press_detected } } + ); + if (check < 0){ + env.log("Emotion press not detected in bottom right. Pressing button again."); + pbf_press_button(context, emotion_button, 10, 50); + }else{ + env.log("Emotion press detected."); + } + + //Look for the brief moment the dialog bubble vanishes + ret = wait_until( + env.console, context, + std::chrono::seconds(15), + { { ESPstop } } + ); + if (ret < 0){ + env.log("Timeout waiting for dialog to vanish."); + } + } + context.wait_for_all_requests(); + } + + //Program done, mash B until overworld detected + OverworldWatcher overworld(env.console, COLOR_CYAN); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 700); + }, + {overworld} + ); + if (ret != 0){ + env.console.log("Failed to detect overworld after ending.", COLOR_RED); + } + context.wait_for_all_requests(); + + //Save the game if option checked, then loop again + if(SAVE){ + save_game_from_overworld(env.program_info(), env.console, context); + } + + stats.m_clears++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.h index e6da0a788e..d96c8c9cca 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_ESPTraining.h @@ -1,45 +1,45 @@ -/* ESP Training - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ESPTraining_H -#define PokemonAutomation_PokemonSV_ESPTraining_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class ESPTraining_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ESPTraining_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class ESPTraining : public SingleSwitchProgramInstance{ -public: - ESPTraining(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption ROUNDS; - - BooleanCheckBoxOption SAVE; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif +/* ESP Training + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ESPTraining_H +#define PokemonAutomation_PokemonSV_ESPTraining_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class ESPTraining_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ESPTraining_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class ESPTraining : public SingleSwitchProgramInstance{ +public: + ESPTraining(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption ROUNDS; + + BooleanCheckBoxOption SAVE; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.cpp index 4644639a82..c33f74dd80 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.cpp @@ -1,308 +1,308 @@ -/* Flying Trial Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV_FlyingTrialFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -FlyingTrialFarmer_Descriptor::FlyingTrialFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:FlyingTrialFarmer", - STRING_POKEMON + " SV", "Flying Trial Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/FlyingTrialFarmer.md", - "Farm the flying trial for BP.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - } - ) -{} -struct FlyingTrialFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : m_trials(m_stats["Trials"]) - , m_success(m_stats["Success"]) - , m_fail(m_stats["Fail"]) - , m_saves(m_stats["Save & Reset"]) - { - m_display_order.emplace_back("Trials"); - m_display_order.emplace_back("Success"); - m_display_order.emplace_back("Fail"); - m_display_order.emplace_back("Save & Reset"); - m_aliases["Game Saves"] = "Save & Reset"; - } - std::atomic& m_trials; - std::atomic& m_success; - std::atomic& m_fail; - std::atomic& m_saves; -}; -std::unique_ptr FlyingTrialFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -FlyingTrialFarmer::FlyingTrialFarmer() - : GO_HOME_WHEN_DONE(false) - , NUM_TRIALS( - "Number of Trials to Run (10BP/Trial):", - LockMode::UNLOCK_WHILE_RUNNING, - 1000 - ) - , SAVE_NUM_ROUNDS( - "Save and reset the game after attempting this many trials:
This preserves progress and prevents potential game lags from long runs.
0 disables this option.", - LockMode::UNLOCK_WHILE_RUNNING, - 50 - ) - , FLIGHT_PATH( - "Select the flight path to use:", - { - {FlightPath::FRONT_ENTRY, "path0", "Front gate entry, sharp turn (might be needed if game is on 3.0.0)"}, - {FlightPath::BACK_ENTRY_STRAIGHT, "path1", "Back gate entry, no turn (candidate for waterfill adjustments)"}, - {FlightPath::BACK_ENTRY_SOFT_TURN, "path2", "Back gate entry, soft turn (current release candidate)"}, - {FlightPath::BACK_ENTRY_HARD_TURN, "path3", "Back gate entry, sharp turn (highest location tolerance but tight timer)"} - }, - LockMode::UNLOCK_WHILE_RUNNING, - FlightPath::BACK_ENTRY_SOFT_TURN - ) - , INVERT_CONTROLS_WHILE_FLYING( - "Inverted controls while flying:
" - "Check this option if you have inverted controls on during flying.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NUM_TRIALS); - PA_ADD_OPTION(SAVE_NUM_ROUNDS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(FLIGHT_PATH); - } - PA_ADD_OPTION(INVERT_CONTROLS_WHILE_FLYING); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -bool FlyingTrialFarmer::run_rewards(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Wait until a dialog shows up. - { - AdvanceDialogWatcher dialog(COLOR_RED); - int ret = wait_until( - env.console, context, - std::chrono::seconds(180), - {dialog} - ); - if (ret != 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "End of trial not detected after 3 minutes.", - env.console - ); - } - env.log("Detected end of trial."); - } - - bool trial_passed = false; - while (true){ - OverworldWatcher overworld(env.console, COLOR_CYAN); - AdvanceDialogWatcher dialog_white(COLOR_RED, DialogType::DIALOG_WHITE); - AdvanceDialogWatcher dialog_black(COLOR_RED, DialogType::DIALOG_BLACK); - context.wait_for_all_requests(); - - int ret_finish = wait_until( - env.console, context, - std::chrono::seconds(80), - { - overworld, - dialog_white, - dialog_black - } - ); - context.wait_for_all_requests(); - - switch (ret_finish){ - case 0: // overworld - return trial_passed; - case 1: // white dialog - pbf_press_button(context, BUTTON_B, 160ms, 0ms); - continue; - case 2: // black dialog - pbf_press_button(context, BUTTON_B, 160ms, 0ms); - trial_passed = true; - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No recognized state after 80 seconds.", - env.console - ); - } - } -} - -uint8_t FlyingTrialFarmer::get_final_y_axis(int8_t delta_y){ - if (INVERT_CONTROLS_WHILE_FLYING){ - return 128 - delta_y; - }else{ - return 128 + delta_y; - } -} - -void FlyingTrialFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - FlyingTrialFarmer_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 0); - - for (uint16_t i = 0; i < NUM_TRIALS; i++){ - BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); - context.wait_for_all_requests(); - - int ret_entry = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 10000); - }, - { black_screen } - ); - context.wait_for_all_requests(); - if (ret_entry == 0){ - env.log("Black screen detected. Trial starting..."); - } - - WhiteButtonWatcher whitebutton(COLOR_GREEN, WhiteButton::ButtonY, {0.40, 0.85, 0.20, 0.14}); - context.wait_for_all_requests(); - - int ret_trial_start = wait_until( - env.console, context, - std::chrono::seconds(120), - {whitebutton} - ); - context.wait_for_all_requests(); - if (ret_trial_start == 0){ - env.log("Countdown is over. Starting navigation sequence..."); - - switch (FLIGHT_PATH){ - case FlightPath::FRONT_ENTRY: - pbf_wait(context, 3 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 200, get_final_y_axis( -98), 1 * TICKS_PER_SECOND, 0); - pbf_wait(context, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 2 * TICKS_PER_SECOND, 0); - pbf_wait(context, 1 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, get_final_y_axis( -78), 2 * TICKS_PER_SECOND, 0); - pbf_wait(context, 6 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 115, get_final_y_axis( 0), 1 * TICKS_PER_SECOND, 0); - pbf_wait(context, 7 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, get_final_y_axis( 52), 2 * TICKS_PER_SECOND, 0); - pbf_wait(context, 780); - pbf_move_left_joystick(context, 0, get_final_y_axis( 0), 3 * TICKS_PER_SECOND, 0); - break; - case FlightPath::BACK_ENTRY_STRAIGHT: - pbf_wait(context, 3 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 180, get_final_y_axis(-108), 1 * TICKS_PER_SECOND, 0); - pbf_wait(context, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 240, 0); - pbf_wait(context, 1 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, get_final_y_axis( -78), 2 * TICKS_PER_SECOND, 0); - pbf_wait(context, 13 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, get_final_y_axis( 52), 2 * TICKS_PER_SECOND, 0); - pbf_wait(context, 9 * TICKS_PER_SECOND); - break; - case FlightPath::BACK_ENTRY_SOFT_TURN: -#if 0 - if (env.console.controller().controller_type() == ControllerType::NintendoSwitch_WirelessProController){ - pbf_wait(context, Milliseconds(3000)); - pbf_move_left_joystick(context, 180, get_final_y_axis(-108), Milliseconds(1005), Milliseconds(0)); - pbf_wait(context, Milliseconds(1995)); - pbf_move_left_joystick(context, 40, get_final_y_axis( -78), Milliseconds(1605), Milliseconds(0)); - pbf_wait(context, Milliseconds(1005)); - pbf_move_left_joystick(context, 110, get_final_y_axis( -78), Milliseconds(1995), Milliseconds(0)); - pbf_wait(context, Milliseconds(14040)); - pbf_move_left_joystick(context, 205, get_final_y_axis( 30), Milliseconds(735), Milliseconds(0)); - pbf_wait(context, Milliseconds(9000)); - }else{ -#endif - pbf_wait(context, 3000ms); - pbf_move_left_joystick(context, 180, get_final_y_axis(-108), 1000ms, 0ms); - pbf_wait(context, 2000ms); - pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 1920ms, 0ms); - pbf_wait(context, 1000ms); - pbf_move_left_joystick(context, 110, get_final_y_axis( -78), 2000ms, 0ms); - pbf_wait(context, 14000ms); - pbf_move_left_joystick(context, 205, get_final_y_axis( 37), 1280ms, 0ms); - pbf_wait(context, 9000ms); -// } - break; - case FlightPath::BACK_ENTRY_HARD_TURN: - pbf_wait(context, 3 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 160, get_final_y_axis(-108), 1 * TICKS_PER_SECOND, 0); - pbf_wait(context, 2 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 240, 0); - pbf_wait(context, 1 * TICKS_PER_SECOND); - pbf_move_left_joystick(context, 128, get_final_y_axis( -78), 160, 0); - pbf_wait(context, 2550); - pbf_move_left_joystick(context, 255, get_final_y_axis( 80), 250, 0); - pbf_wait(context, 9 * TICKS_PER_SECOND); - break; - } - } - - if (run_rewards(env, context)){ - stats.m_success++; - }else{ - stats.m_fail++; - } - - stats.m_trials++; - - if (SAVE_NUM_ROUNDS != 0 && stats.m_trials % SAVE_NUM_ROUNDS == 0){ - save_game_from_overworld(env.program_info(), env.console, context); - reset_game(env.program_info(), env.console, context); - stats.m_saves++; - } - - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} +/* Flying Trial Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_FlyingTrialFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +FlyingTrialFarmer_Descriptor::FlyingTrialFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:FlyingTrialFarmer", + STRING_POKEMON + " SV", "Flying Trial Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/FlyingTrialFarmer.md", + "Farm the flying trial for BP.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + } + ) +{} +struct FlyingTrialFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : m_trials(m_stats["Trials"]) + , m_success(m_stats["Success"]) + , m_fail(m_stats["Fail"]) + , m_saves(m_stats["Save & Reset"]) + { + m_display_order.emplace_back("Trials"); + m_display_order.emplace_back("Success"); + m_display_order.emplace_back("Fail"); + m_display_order.emplace_back("Save & Reset"); + m_aliases["Game Saves"] = "Save & Reset"; + } + std::atomic& m_trials; + std::atomic& m_success; + std::atomic& m_fail; + std::atomic& m_saves; +}; +std::unique_ptr FlyingTrialFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +FlyingTrialFarmer::FlyingTrialFarmer() + : GO_HOME_WHEN_DONE(false) + , NUM_TRIALS( + "Number of Trials to Run (10BP/Trial):", + LockMode::UNLOCK_WHILE_RUNNING, + 1000 + ) + , SAVE_NUM_ROUNDS( + "Save and reset the game after attempting this many trials:
This preserves progress and prevents potential game lags from long runs.
0 disables this option.", + LockMode::UNLOCK_WHILE_RUNNING, + 50 + ) + , FLIGHT_PATH( + "Select the flight path to use:", + { + {FlightPath::FRONT_ENTRY, "path0", "Front gate entry, sharp turn (might be needed if game is on 3.0.0)"}, + {FlightPath::BACK_ENTRY_STRAIGHT, "path1", "Back gate entry, no turn (candidate for waterfill adjustments)"}, + {FlightPath::BACK_ENTRY_SOFT_TURN, "path2", "Back gate entry, soft turn (current release candidate)"}, + {FlightPath::BACK_ENTRY_HARD_TURN, "path3", "Back gate entry, sharp turn (highest location tolerance but tight timer)"} + }, + LockMode::UNLOCK_WHILE_RUNNING, + FlightPath::BACK_ENTRY_SOFT_TURN + ) + , INVERT_CONTROLS_WHILE_FLYING( + "Inverted controls while flying:
" + "Check this option if you have inverted controls on during flying.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NUM_TRIALS); + PA_ADD_OPTION(SAVE_NUM_ROUNDS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(FLIGHT_PATH); + } + PA_ADD_OPTION(INVERT_CONTROLS_WHILE_FLYING); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +bool FlyingTrialFarmer::run_rewards(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Wait until a dialog shows up. + { + AdvanceDialogWatcher dialog(COLOR_RED); + int ret = wait_until( + env.console, context, + std::chrono::seconds(180), + {dialog} + ); + if (ret != 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "End of trial not detected after 3 minutes.", + env.console + ); + } + env.log("Detected end of trial."); + } + + bool trial_passed = false; + while (true){ + OverworldWatcher overworld(env.console, COLOR_CYAN); + AdvanceDialogWatcher dialog_white(COLOR_RED, DialogType::DIALOG_WHITE); + AdvanceDialogWatcher dialog_black(COLOR_RED, DialogType::DIALOG_BLACK); + context.wait_for_all_requests(); + + int ret_finish = wait_until( + env.console, context, + std::chrono::seconds(80), + { + overworld, + dialog_white, + dialog_black + } + ); + context.wait_for_all_requests(); + + switch (ret_finish){ + case 0: // overworld + return trial_passed; + case 1: // white dialog + pbf_press_button(context, BUTTON_B, 160ms, 0ms); + continue; + case 2: // black dialog + pbf_press_button(context, BUTTON_B, 160ms, 0ms); + trial_passed = true; + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No recognized state after 80 seconds.", + env.console + ); + } + } +} + +uint8_t FlyingTrialFarmer::get_final_y_axis(int8_t delta_y){ + if (INVERT_CONTROLS_WHILE_FLYING){ + return 128 - delta_y; + }else{ + return 128 + delta_y; + } +} + +void FlyingTrialFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + FlyingTrialFarmer_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 0); + + for (uint16_t i = 0; i < NUM_TRIALS; i++){ + BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); + context.wait_for_all_requests(); + + int ret_entry = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 10000); + }, + { black_screen } + ); + context.wait_for_all_requests(); + if (ret_entry == 0){ + env.log("Black screen detected. Trial starting..."); + } + + WhiteButtonWatcher whitebutton(COLOR_GREEN, WhiteButton::ButtonY, {0.40, 0.85, 0.20, 0.14}); + context.wait_for_all_requests(); + + int ret_trial_start = wait_until( + env.console, context, + std::chrono::seconds(120), + {whitebutton} + ); + context.wait_for_all_requests(); + if (ret_trial_start == 0){ + env.log("Countdown is over. Starting navigation sequence..."); + + switch (FLIGHT_PATH){ + case FlightPath::FRONT_ENTRY: + pbf_wait(context, 3 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 200, get_final_y_axis( -98), 1 * TICKS_PER_SECOND, 0); + pbf_wait(context, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 2 * TICKS_PER_SECOND, 0); + pbf_wait(context, 1 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, get_final_y_axis( -78), 2 * TICKS_PER_SECOND, 0); + pbf_wait(context, 6 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 115, get_final_y_axis( 0), 1 * TICKS_PER_SECOND, 0); + pbf_wait(context, 7 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, get_final_y_axis( 52), 2 * TICKS_PER_SECOND, 0); + pbf_wait(context, 780); + pbf_move_left_joystick(context, 0, get_final_y_axis( 0), 3 * TICKS_PER_SECOND, 0); + break; + case FlightPath::BACK_ENTRY_STRAIGHT: + pbf_wait(context, 3 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 180, get_final_y_axis(-108), 1 * TICKS_PER_SECOND, 0); + pbf_wait(context, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 240, 0); + pbf_wait(context, 1 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, get_final_y_axis( -78), 2 * TICKS_PER_SECOND, 0); + pbf_wait(context, 13 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, get_final_y_axis( 52), 2 * TICKS_PER_SECOND, 0); + pbf_wait(context, 9 * TICKS_PER_SECOND); + break; + case FlightPath::BACK_ENTRY_SOFT_TURN: +#if 0 + if (env.console.controller().controller_type() == ControllerType::NintendoSwitch_WirelessProController){ + pbf_wait(context, Milliseconds(3000)); + pbf_move_left_joystick(context, 180, get_final_y_axis(-108), Milliseconds(1005), Milliseconds(0)); + pbf_wait(context, Milliseconds(1995)); + pbf_move_left_joystick(context, 40, get_final_y_axis( -78), Milliseconds(1605), Milliseconds(0)); + pbf_wait(context, Milliseconds(1005)); + pbf_move_left_joystick(context, 110, get_final_y_axis( -78), Milliseconds(1995), Milliseconds(0)); + pbf_wait(context, Milliseconds(14040)); + pbf_move_left_joystick(context, 205, get_final_y_axis( 30), Milliseconds(735), Milliseconds(0)); + pbf_wait(context, Milliseconds(9000)); + }else{ +#endif + pbf_wait(context, 3000ms); + pbf_move_left_joystick(context, 180, get_final_y_axis(-108), 1000ms, 0ms); + pbf_wait(context, 2000ms); + pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 1920ms, 0ms); + pbf_wait(context, 1000ms); + pbf_move_left_joystick(context, 110, get_final_y_axis( -78), 2000ms, 0ms); + pbf_wait(context, 14000ms); + pbf_move_left_joystick(context, 205, get_final_y_axis( 37), 1280ms, 0ms); + pbf_wait(context, 9000ms); +// } + break; + case FlightPath::BACK_ENTRY_HARD_TURN: + pbf_wait(context, 3 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 160, get_final_y_axis(-108), 1 * TICKS_PER_SECOND, 0); + pbf_wait(context, 2 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 40, get_final_y_axis( -78), 240, 0); + pbf_wait(context, 1 * TICKS_PER_SECOND); + pbf_move_left_joystick(context, 128, get_final_y_axis( -78), 160, 0); + pbf_wait(context, 2550); + pbf_move_left_joystick(context, 255, get_final_y_axis( 80), 250, 0); + pbf_wait(context, 9 * TICKS_PER_SECOND); + break; + } + } + + if (run_rewards(env, context)){ + stats.m_success++; + }else{ + stats.m_fail++; + } + + stats.m_trials++; + + if (SAVE_NUM_ROUNDS != 0 && stats.m_trials % SAVE_NUM_ROUNDS == 0){ + save_game_from_overworld(env.program_info(), env.console, context); + reset_game(env.program_info(), env.console, context); + stats.m_saves++; + } + + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.h index 75d192601b..7d7c331261 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_FlyingTrialFarmer.h @@ -1,62 +1,62 @@ -/* Flying Trial Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_FlyingTrialFarmer_H -#define PokemonAutomation_PokemonSV_FlyingTrialFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class FlyingTrialFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FlyingTrialFarmer_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class FlyingTrialFarmer : public SingleSwitchProgramInstance{ -public: - FlyingTrialFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption NUM_TRIALS; - SimpleIntegerOption SAVE_NUM_ROUNDS; - - enum class FlightPath{ - FRONT_ENTRY, - BACK_ENTRY_STRAIGHT, - BACK_ENTRY_SOFT_TURN, - BACK_ENTRY_HARD_TURN - }; - EnumDropdownOption FLIGHT_PATH; - - BooleanCheckBoxOption INVERT_CONTROLS_WHILE_FLYING; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - bool run_rewards(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - uint8_t get_final_y_axis(int8_t delta_y); -}; - - - -} -} -} -#endif +/* Flying Trial Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_FlyingTrialFarmer_H +#define PokemonAutomation_PokemonSV_FlyingTrialFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class FlyingTrialFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FlyingTrialFarmer_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class FlyingTrialFarmer : public SingleSwitchProgramInstance{ +public: + FlyingTrialFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption NUM_TRIALS; + SimpleIntegerOption SAVE_NUM_ROUNDS; + + enum class FlightPath{ + FRONT_ENTRY, + BACK_ENTRY_STRAIGHT, + BACK_ENTRY_SOFT_TURN, + BACK_ENTRY_HARD_TURN + }; + EnumDropdownOption FLIGHT_PATH; + + BooleanCheckBoxOption INVERT_CONTROLS_WHILE_FLYING; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + bool run_rewards(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + uint8_t get_final_y_axis(int8_t delta_y); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.cpp index 7ad4e7cd23..2f87e9f1a7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.cpp @@ -1,296 +1,296 @@ -/* Gimmighoul Chest Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_GimmighoulChestFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -GimmighoulChestFarmer_Descriptor::GimmighoulChestFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:GimmighoulChestFarmer", - STRING_POKEMON + " SV", "Gimmighoul Chest Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/GimmighoulChestFarmer.md", - "Farm Chest Gimmighoul for coins.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - }, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -struct GimmighoulChestFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : pokemon_fainted(m_stats["Chests farmed"]) - , wild_interrupts(m_stats["Wild interrupts"]) - , resets(m_stats["Resets"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Chests farmed"); - m_display_order.emplace_back("Wild interrupts"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& pokemon_fainted; - std::atomic& wild_interrupts; - std::atomic& resets; - std::atomic& errors; -}; -std::unique_ptr GimmighoulChestFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -GimmighoulChestFarmer::GimmighoulChestFarmer() - : PP( - "First Attack PP:
The amount of PP remaining on your lead's first attack.", - LockMode::LOCK_WHILE_RUNNING, - 15 - ) - , START_LOCATION( - "Start Location:
The start location of your character.", - { - {StartLocation::FlyPoint, "fly-point", "Fly Point - East Province (Area One) Watchtower"}, - {StartLocation::InFrontOfChest, "in-front-of-chest", "In front of chest"}, - }, - LockMode::LOCK_WHILE_RUNNING, - StartLocation::FlyPoint - ) - , GO_HOME_WHEN_DONE(false) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , ADDITIONAL_BATTLE_WAIT_TIME0( - "Additional Battle Wait Time:
Increase this if you are timing out when entering battle.", - LockMode::LOCK_WHILE_RUNNING, - "10000 ms" - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(PP); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - PA_ADD_OPTION(ADDITIONAL_BATTLE_WAIT_TIME0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void GimmighoulChestFarmer::navigate_to_gimmi(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - //Cursor is already in position - fly_to_overworld_from_map(env.program_info(), env.console, context); - pbf_move_left_joystick(context, 0, 0, 158, 0); - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_move_left_joystick(context, 128, 0, 100, 0); - //Climb ladder - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_move_left_joystick(context, 128, 0, 2350, 0); - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_wait(context, 100); - context.wait_for_all_requests(); - //Walk into the wall - pbf_move_left_joystick(context, 128, 0, 200, 100); - context.wait_for_all_requests(); - //Turn back - pbf_move_left_joystick(context, 128, 255, 60, 100); - context.wait_for_all_requests(); - //Position toward chest - pbf_move_left_joystick(context, 128, 0, 30, 0); - context.wait_for_all_requests(); -} - -void GimmighoulChestFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - GimmighoulChestFarmer_Descriptor::Stats& stats = env.current_stats(); - - if (START_LOCATION == StartLocation::FlyPoint){ - //Set starting position by flying - must fly to East Province (Area One) Watchtower, do not move from fly point - open_map_from_overworld(env.program_info(), env.console, context); - fly_to_overworld_from_map(env.program_info(), env.console, context); - pbf_move_left_joystick(context, 0, 0, 158, 0); - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_move_left_joystick(context, 128, 0, 100, 0); - //Climb ladder - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_move_left_joystick(context, 128, 0, 2350, 0); - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_wait(context, 100); - context.wait_for_all_requests(); - //Walk into the wall - pbf_move_left_joystick(context, 128, 0, 200, 100); - context.wait_for_all_requests(); - //Press A in case there's already a chest - //The remaining commands will run harmlessly during the battle intro if there is a chest - pbf_press_button(context, BUTTON_A, 50, 40); - //Turn back - pbf_move_left_joystick(context, 128, 255, 60, 100); - context.wait_for_all_requests(); - //Position toward chest - pbf_move_left_joystick(context, 128, 0, 30, 0); - context.wait_for_all_requests(); - } - //else assuming player is positioned correctly in front of the chest - - uint32_t c = 0; - while(c < PP){ - // Press A to enter battle, assuming there is a chest - env.log("Fetch Attempts: " + tostr_u_commas(c)); - pbf_mash_button(context, BUTTON_A, 125); - pbf_wait(context, 125); //Wait extra to make sure the overworld map vanishes - context.wait_for_all_requests(); - - OverworldWatcher battleStarting(env.console, COLOR_RED); - NormalBattleMenuWatcher battle_detected(COLOR_RED); - int retOverworld = wait_until( - env.console, context, - std::chrono::seconds(5), - {battleStarting, battle_detected} - ); - if (retOverworld != 0) { - //Wait for the battle to load then check for battle menu, if there isn't a battle menu then no chest - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret = wait_until( - env.console, context, - ADDITIONAL_BATTLE_WAIT_TIME0, - { battle_menu } - ); - - if (ret == 0){ - // Attack using your first move - pbf_mash_button(context, BUTTON_A, 90); - c++; - context.wait_for_all_requests(); - OverworldWatcher overworld(env.console, COLOR_RED); - int ret2 = wait_until( - env.console, context, - std::chrono::seconds(120), - { overworld } - ); - if (ret2 != 0){ - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to return to Overworld after two minutes. Did your attack miss or fail to defeat Gimmighoul in one hit?", - env.console - ); - } - stats.pokemon_fainted++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - //Set starting position by flying - move map cursor - open_map_from_overworld(env.program_info(), env.console, context); - pbf_press_button(context, BUTTON_ZR, 50, 40); - pbf_move_left_joystick(context, 48, 192, 10, 0); - navigate_to_gimmi(env, context); - - //Check for tauros interrupt before pressing A - reset position if there was one - ret = wait_until( - env.console, context, - std::chrono::seconds(1), - { battle_menu } - ); - if (ret == 0){ - pbf_mash_button(context, BUTTON_A, 90); - c++; - context.wait_for_all_requests(); - ret2 = wait_until( - env.console, context, - std::chrono::seconds(120), - { overworld } - ); - if (ret2 != 0){ - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to return to Overworld after two minutes.", - env.console - ); - } - //Don't move map cursor this time - open_map_from_overworld(env.program_info(), env.console, context); - navigate_to_gimmi(env, context); - - stats.wild_interrupts++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - } - } - - // Save the game - save_game_from_overworld(env.program_info(), env.console, context); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - - // Date skip - in-game day cycle is 72 mins, so 2 hours is fastest way - // This isn't perfect because 12 hour format but it works - home_to_date_time(env.console, context, true); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, DPAD_RIGHT, 0ms); - ssf_press_button_ptv(context, BUTTON_A, 16ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - ssf_issue_scroll_ptv(context, DPAD_RIGHT, 0ms); - ssf_press_button_ptv(context, BUTTON_A, 16ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - stats.resets++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - } - - if (FIX_TIME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - -} -} -} - +/* Gimmighoul Chest Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_GimmighoulChestFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +GimmighoulChestFarmer_Descriptor::GimmighoulChestFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:GimmighoulChestFarmer", + STRING_POKEMON + " SV", "Gimmighoul Chest Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/GimmighoulChestFarmer.md", + "Farm Chest Gimmighoul for coins.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + }, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +struct GimmighoulChestFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : pokemon_fainted(m_stats["Chests farmed"]) + , wild_interrupts(m_stats["Wild interrupts"]) + , resets(m_stats["Resets"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Chests farmed"); + m_display_order.emplace_back("Wild interrupts"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& pokemon_fainted; + std::atomic& wild_interrupts; + std::atomic& resets; + std::atomic& errors; +}; +std::unique_ptr GimmighoulChestFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +GimmighoulChestFarmer::GimmighoulChestFarmer() + : PP( + "First Attack PP:
The amount of PP remaining on your lead's first attack.", + LockMode::LOCK_WHILE_RUNNING, + 15 + ) + , START_LOCATION( + "Start Location:
The start location of your character.", + { + {StartLocation::FlyPoint, "fly-point", "Fly Point - East Province (Area One) Watchtower"}, + {StartLocation::InFrontOfChest, "in-front-of-chest", "In front of chest"}, + }, + LockMode::LOCK_WHILE_RUNNING, + StartLocation::FlyPoint + ) + , GO_HOME_WHEN_DONE(false) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , ADDITIONAL_BATTLE_WAIT_TIME0( + "Additional Battle Wait Time:
Increase this if you are timing out when entering battle.", + LockMode::LOCK_WHILE_RUNNING, + "10000 ms" + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(PP); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + PA_ADD_OPTION(ADDITIONAL_BATTLE_WAIT_TIME0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void GimmighoulChestFarmer::navigate_to_gimmi(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + //Cursor is already in position + fly_to_overworld_from_map(env.program_info(), env.console, context); + pbf_move_left_joystick(context, 0, 0, 158, 0); + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_move_left_joystick(context, 128, 0, 100, 0); + //Climb ladder + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_move_left_joystick(context, 128, 0, 2350, 0); + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_wait(context, 100); + context.wait_for_all_requests(); + //Walk into the wall + pbf_move_left_joystick(context, 128, 0, 200, 100); + context.wait_for_all_requests(); + //Turn back + pbf_move_left_joystick(context, 128, 255, 60, 100); + context.wait_for_all_requests(); + //Position toward chest + pbf_move_left_joystick(context, 128, 0, 30, 0); + context.wait_for_all_requests(); +} + +void GimmighoulChestFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + GimmighoulChestFarmer_Descriptor::Stats& stats = env.current_stats(); + + if (START_LOCATION == StartLocation::FlyPoint){ + //Set starting position by flying - must fly to East Province (Area One) Watchtower, do not move from fly point + open_map_from_overworld(env.program_info(), env.console, context); + fly_to_overworld_from_map(env.program_info(), env.console, context); + pbf_move_left_joystick(context, 0, 0, 158, 0); + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_move_left_joystick(context, 128, 0, 100, 0); + //Climb ladder + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_move_left_joystick(context, 128, 0, 2350, 0); + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_wait(context, 100); + context.wait_for_all_requests(); + //Walk into the wall + pbf_move_left_joystick(context, 128, 0, 200, 100); + context.wait_for_all_requests(); + //Press A in case there's already a chest + //The remaining commands will run harmlessly during the battle intro if there is a chest + pbf_press_button(context, BUTTON_A, 50, 40); + //Turn back + pbf_move_left_joystick(context, 128, 255, 60, 100); + context.wait_for_all_requests(); + //Position toward chest + pbf_move_left_joystick(context, 128, 0, 30, 0); + context.wait_for_all_requests(); + } + //else assuming player is positioned correctly in front of the chest + + uint32_t c = 0; + while(c < PP){ + // Press A to enter battle, assuming there is a chest + env.log("Fetch Attempts: " + tostr_u_commas(c)); + pbf_mash_button(context, BUTTON_A, 125); + pbf_wait(context, 125); //Wait extra to make sure the overworld map vanishes + context.wait_for_all_requests(); + + OverworldWatcher battleStarting(env.console, COLOR_RED); + NormalBattleMenuWatcher battle_detected(COLOR_RED); + int retOverworld = wait_until( + env.console, context, + std::chrono::seconds(5), + {battleStarting, battle_detected} + ); + if (retOverworld != 0) { + //Wait for the battle to load then check for battle menu, if there isn't a battle menu then no chest + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret = wait_until( + env.console, context, + ADDITIONAL_BATTLE_WAIT_TIME0, + { battle_menu } + ); + + if (ret == 0){ + // Attack using your first move + pbf_mash_button(context, BUTTON_A, 90); + c++; + context.wait_for_all_requests(); + OverworldWatcher overworld(env.console, COLOR_RED); + int ret2 = wait_until( + env.console, context, + std::chrono::seconds(120), + { overworld } + ); + if (ret2 != 0){ + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to return to Overworld after two minutes. Did your attack miss or fail to defeat Gimmighoul in one hit?", + env.console + ); + } + stats.pokemon_fainted++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + //Set starting position by flying - move map cursor + open_map_from_overworld(env.program_info(), env.console, context); + pbf_press_button(context, BUTTON_ZR, 50, 40); + pbf_move_left_joystick(context, 48, 192, 10, 0); + navigate_to_gimmi(env, context); + + //Check for tauros interrupt before pressing A - reset position if there was one + ret = wait_until( + env.console, context, + std::chrono::seconds(1), + { battle_menu } + ); + if (ret == 0){ + pbf_mash_button(context, BUTTON_A, 90); + c++; + context.wait_for_all_requests(); + ret2 = wait_until( + env.console, context, + std::chrono::seconds(120), + { overworld } + ); + if (ret2 != 0){ + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to return to Overworld after two minutes.", + env.console + ); + } + //Don't move map cursor this time + open_map_from_overworld(env.program_info(), env.console, context); + navigate_to_gimmi(env, context); + + stats.wild_interrupts++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + } + } + + // Save the game + save_game_from_overworld(env.program_info(), env.console, context); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + + // Date skip - in-game day cycle is 72 mins, so 2 hours is fastest way + // This isn't perfect because 12 hour format but it works + home_to_date_time(env.console, context, true); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, DPAD_RIGHT, 0ms); + ssf_press_button_ptv(context, BUTTON_A, 16ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + ssf_issue_scroll_ptv(context, DPAD_RIGHT, 0ms); + ssf_press_button_ptv(context, BUTTON_A, 16ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + stats.resets++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + } + + if (FIX_TIME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.h index 10c0d541c1..f516f7e592 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulChestFarmer.h @@ -1,57 +1,57 @@ -/* Gimmighoul Chest Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_GimmighoulChestFarm_H -#define PokemonAutomation_PokemonSwSh_GimmighoulChestFarm_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class GimmighoulChestFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GimmighoulChestFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class GimmighoulChestFarmer : public SingleSwitchProgramInstance{ -public: - GimmighoulChestFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - enum class StartLocation{ - FlyPoint, - InFrontOfChest, - }; - - SimpleIntegerOption PP; - EnumDropdownOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - MillisecondsOption ADDITIONAL_BATTLE_WAIT_TIME0; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void navigate_to_gimmi(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif - - - +/* Gimmighoul Chest Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_GimmighoulChestFarm_H +#define PokemonAutomation_PokemonSwSh_GimmighoulChestFarm_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class GimmighoulChestFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GimmighoulChestFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class GimmighoulChestFarmer : public SingleSwitchProgramInstance{ +public: + GimmighoulChestFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + enum class StartLocation{ + FlyPoint, + InFrontOfChest, + }; + + SimpleIntegerOption PP; + EnumDropdownOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + MillisecondsOption ADDITIONAL_BATTLE_WAIT_TIME0; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void navigate_to_gimmi(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.cpp index 7cb6756cca..432e3939db 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.cpp @@ -1,111 +1,111 @@ -/* Gimmighoul Roaming Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV_GimmighoulRoamingFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -GimmighoulRoamingFarmer_Descriptor::GimmighoulRoamingFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:GimmighoulRoamingFarmer", - STRING_POKEMON + " SV", "Gimmighoul Roaming Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/GimmighoulRoamingFarmer.md", - "Farm roaming Gimmighoul for coins.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -GimmighoulRoamingFarmer::GimmighoulRoamingFarmer() - : SKIPS( - "Number of Attempts:", - LockMode::UNLOCK_WHILE_RUNNING, - 1500 - ) - , GO_HOME_WHEN_DONE(false) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void GimmighoulRoamingFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - // Start in game facing a roaming Gimmighoul somewhere safe. (ex. Pokemon Center since wild Pokemon can't fight you there.) - uint8_t year = MAX_YEAR; - for (uint32_t c = 0; c < SKIPS; c++){ - // Grab coin assuming there is one - env.log("Fetch Attempts: " + tostr_u_commas(c)); - pbf_mash_button(context, BUTTON_A, 90); - pbf_wait(context, 2 * TICKS_PER_SECOND); - - // Save the game - save_game_from_overworld(env.program_info(), env.console, context); - - // Date skip - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, true); - if (year >= MAX_YEAR){ - roll_date_backward_N(env.console, context, MAX_YEAR, true); - year = 0; - }else{ - roll_date_forward_1(env.console, context, true); - year++; - } - - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - // Reset game - reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - } - - if (FIX_TIME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} - +/* Gimmighoul Roaming Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV_GimmighoulRoamingFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +GimmighoulRoamingFarmer_Descriptor::GimmighoulRoamingFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:GimmighoulRoamingFarmer", + STRING_POKEMON + " SV", "Gimmighoul Roaming Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/GimmighoulRoamingFarmer.md", + "Farm roaming Gimmighoul for coins.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +GimmighoulRoamingFarmer::GimmighoulRoamingFarmer() + : SKIPS( + "Number of Attempts:", + LockMode::UNLOCK_WHILE_RUNNING, + 1500 + ) + , GO_HOME_WHEN_DONE(false) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void GimmighoulRoamingFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + // Start in game facing a roaming Gimmighoul somewhere safe. (ex. Pokemon Center since wild Pokemon can't fight you there.) + uint8_t year = MAX_YEAR; + for (uint32_t c = 0; c < SKIPS; c++){ + // Grab coin assuming there is one + env.log("Fetch Attempts: " + tostr_u_commas(c)); + pbf_mash_button(context, BUTTON_A, 90); + pbf_wait(context, 2 * TICKS_PER_SECOND); + + // Save the game + save_game_from_overworld(env.program_info(), env.console, context); + + // Date skip + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, true); + if (year >= MAX_YEAR){ + roll_date_backward_N(env.console, context, MAX_YEAR, true); + year = 0; + }else{ + roll_date_forward_1(env.console, context, true); + year++; + } + + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + // Reset game + reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + } + + if (FIX_TIME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h index 8a569170ca..bc555e725e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_GimmighoulRoamingFarmer.h @@ -1,46 +1,46 @@ -/* Gimmighoul Roaming Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_GimmighoulRoamingFarm_H -#define PokemonAutomation_PokemonSV_GimmighoulRoamingFarm_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class GimmighoulRoamingFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GimmighoulRoamingFarmer_Descriptor(); -}; - -class GimmighoulRoamingFarmer : public SingleSwitchProgramInstance{ -public: - GimmighoulRoamingFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption SKIPS; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Gimmighoul Roaming Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_GimmighoulRoamingFarm_H +#define PokemonAutomation_PokemonSV_GimmighoulRoamingFarm_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class GimmighoulRoamingFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GimmighoulRoamingFarmer_Descriptor(); +}; + +class GimmighoulRoamingFarmer : public SingleSwitchProgramInstance{ +public: + GimmighoulRoamingFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption SKIPS; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.cpp index ddfb80b921..279606ed3e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.cpp @@ -1,148 +1,148 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV_LPFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -LPFarmer_Descriptor::LPFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:LPFarmer", - STRING_POKEMON + " SV", "LP Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/LPFarmer.md", - "Farm LP by day skipping Tera raids.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -struct LPFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : m_skips(m_stats["Day Skips"]) - , m_resets(m_stats["Resets"]) - , m_fetches(m_stats["Fetches"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Day Skips"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Fetches"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_skips; - std::atomic& m_resets; - std::atomic& m_fetches; - std::atomic& m_errors; -}; -std::unique_ptr LPFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -LPFarmer::LPFarmer() - : GO_HOME_WHEN_DONE(false) - , FETCHES( - "Fetches:", - LockMode::UNLOCK_WHILE_RUNNING, - 10000, 1 - ) - , PERIODIC_RESET( - "Periodic Game Reset:
Reset the game after this many skips. This clears up the framerate bug.", - LockMode::UNLOCK_WHILE_RUNNING, - 20, 0, 100 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, -// &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(FETCHES); - PA_ADD_OPTION(PERIODIC_RESET); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void LPFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - LPFarmer_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 10); - - bool first = true; - uint32_t skip_counter = 0; - - for (size_t fetches = 0; fetches < FETCHES;){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (!first){ - day_skip_from_overworld(env.console, context); - pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); - context.wait_for_all_requests(); - stats.m_skips++; - skip_counter++; - env.update_stats(); - } - first = false; - - uint8_t reset_period = PERIODIC_RESET; - if (reset_period != 0 && skip_counter >= reset_period){ - env.log("Resetting game to clear framerate."); - save_game_from_overworld(env.program_info(), env.console, context); - reset_game(env.program_info(), env.console, context); - skip_counter = 0; - } - - if (!open_raid(env.console, context)){ - continue; - } - - fetches++; - stats.m_fetches++; - - close_raid(env.program_info(), env.console, context); - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - - - - - -} -} -} +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV_LPFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +LPFarmer_Descriptor::LPFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:LPFarmer", + STRING_POKEMON + " SV", "LP Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/LPFarmer.md", + "Farm LP by day skipping Tera raids.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +struct LPFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : m_skips(m_stats["Day Skips"]) + , m_resets(m_stats["Resets"]) + , m_fetches(m_stats["Fetches"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Day Skips"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Fetches"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_skips; + std::atomic& m_resets; + std::atomic& m_fetches; + std::atomic& m_errors; +}; +std::unique_ptr LPFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +LPFarmer::LPFarmer() + : GO_HOME_WHEN_DONE(false) + , FETCHES( + "Fetches:", + LockMode::UNLOCK_WHILE_RUNNING, + 10000, 1 + ) + , PERIODIC_RESET( + "Periodic Game Reset:
Reset the game after this many skips. This clears up the framerate bug.", + LockMode::UNLOCK_WHILE_RUNNING, + 20, 0, 100 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, +// &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(FETCHES); + PA_ADD_OPTION(PERIODIC_RESET); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void LPFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + LPFarmer_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 10); + + bool first = true; + uint32_t skip_counter = 0; + + for (size_t fetches = 0; fetches < FETCHES;){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (!first){ + day_skip_from_overworld(env.console, context); + pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); + context.wait_for_all_requests(); + stats.m_skips++; + skip_counter++; + env.update_stats(); + } + first = false; + + uint8_t reset_period = PERIODIC_RESET; + if (reset_period != 0 && skip_counter >= reset_period){ + env.log("Resetting game to clear framerate."); + save_game_from_overworld(env.program_info(), env.console, context); + reset_game(env.program_info(), env.console, context); + skip_counter = 0; + } + + if (!open_raid(env.console, context)){ + continue; + } + + fetches++; + stats.m_fetches++; + + close_raid(env.program_info(), env.console, context); + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.h index e3636f6bd9..f7f36c3b8d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_LPFarmer.h @@ -1,49 +1,49 @@ -/* LP Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_LPFarmer_H -#define PokemonAutomation_PokemonSwSh_LPFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class LPFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LPFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class LPFarmer : public SingleSwitchProgramInstance{ -public: - LPFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption FETCHES; - SimpleIntegerOption PERIODIC_RESET; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif - - - +/* LP Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_LPFarmer_H +#define PokemonAutomation_PokemonSwSh_LPFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class LPFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LPFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class LPFarmer : public SingleSwitchProgramInstance{ +public: + LPFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption FETCHES; + SimpleIntegerOption PERIODIC_RESET; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp index 78888fe266..c2e1eb43aa 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.cpp @@ -1,110 +1,110 @@ -/* Material Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_MaterialFarmer.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -MaterialFarmer_Descriptor::MaterialFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:MaterialFarmer", - STRING_POKEMON + " SV", "Material Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MaterialFarmer.md", - "Farm materials - Happiny dust from Chanseys/Blisseys, for Item Printer.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -std::unique_ptr MaterialFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new MaterialFarmerStats()); -} - - -MaterialFarmer::MaterialFarmer() - : GO_HOME_WHEN_DONE(true) - , MATERIAL_FARMER_OPTIONS( - GroupOption::EnableMode::ALWAYS_ENABLED, - nullptr, - NOTIFICATION_STATUS_UPDATE, - NOTIFICATION_PROGRAM_FINISH, - NOTIFICATION_ERROR_RECOVERABLE, - NOTIFICATION_ERROR_FATAL - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(MATERIAL_FARMER_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void MaterialFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 50); - - // Throw user setup errors early in program - // - Ensure language is set - const Language language = MATERIAL_FARMER_OPTIONS.LANGUAGE; - if (language == Language::None) { - throw UserSetupError(env.console.logger(), "Must set game language option to read ingredient lists."); - } - - // - Ensure audio input is enabled - LetsGoKillSoundDetector audio_detector(env.console, [](float){ return true; }); - wait_until( - env.console, context, - std::chrono::milliseconds(1100), - {audio_detector} - ); - audio_detector.throw_if_no_sound(std::chrono::milliseconds(1000)); - - // start by warping to pokecenter for positioning reasons - if (!MATERIAL_FARMER_OPTIONS.SKIP_WARP_TO_POKECENTER){ - reset_to_pokecenter(env.program_info(), env.console, context); - } - - MaterialFarmerStats& stats = env.current_stats(); - - try{ - run_material_farmer(env, env.console, context, MATERIAL_FARMER_OPTIONS, stats); - }catch (ProgramFinishedException&){} - - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Material Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_MaterialFarmer.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +MaterialFarmer_Descriptor::MaterialFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:MaterialFarmer", + STRING_POKEMON + " SV", "Material Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MaterialFarmer.md", + "Farm materials - Happiny dust from Chanseys/Blisseys, for Item Printer.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +std::unique_ptr MaterialFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new MaterialFarmerStats()); +} + + +MaterialFarmer::MaterialFarmer() + : GO_HOME_WHEN_DONE(true) + , MATERIAL_FARMER_OPTIONS( + GroupOption::EnableMode::ALWAYS_ENABLED, + nullptr, + NOTIFICATION_STATUS_UPDATE, + NOTIFICATION_PROGRAM_FINISH, + NOTIFICATION_ERROR_RECOVERABLE, + NOTIFICATION_ERROR_FATAL + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(MATERIAL_FARMER_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void MaterialFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 50); + + // Throw user setup errors early in program + // - Ensure language is set + const Language language = MATERIAL_FARMER_OPTIONS.LANGUAGE; + if (language == Language::None) { + throw UserSetupError(env.console.logger(), "Must set game language option to read ingredient lists."); + } + + // - Ensure audio input is enabled + LetsGoKillSoundDetector audio_detector(env.console, [](float){ return true; }); + wait_until( + env.console, context, + std::chrono::milliseconds(1100), + {audio_detector} + ); + audio_detector.throw_if_no_sound(std::chrono::milliseconds(1000)); + + // start by warping to pokecenter for positioning reasons + if (!MATERIAL_FARMER_OPTIONS.SKIP_WARP_TO_POKECENTER){ + reset_to_pokecenter(env.program_info(), env.console, context); + } + + MaterialFarmerStats& stats = env.current_stats(); + + try{ + run_material_farmer(env, env.console, context, MATERIAL_FARMER_OPTIONS, stats); + }catch (ProgramFinishedException&){} + + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h index 30b85f4d9b..a2b2edd1f1 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmer.h @@ -1,50 +1,50 @@ -/* Material Farmer - Happiny dust - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MaterialFarmer_H -#define PokemonAutomation_PokemonSV_MaterialFarmer_H - -#include -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" -#include "PokemonSV_MaterialFarmerTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class MaterialFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MaterialFarmer_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class MaterialFarmer : public SingleSwitchProgramInstance{ -public: - MaterialFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - MaterialFarmerOptions MATERIAL_FARMER_OPTIONS; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Material Farmer - Happiny dust + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MaterialFarmer_H +#define PokemonAutomation_PokemonSV_MaterialFarmer_H + +#include +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" +#include "PokemonSV_MaterialFarmerTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class MaterialFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MaterialFarmer_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class MaterialFarmer : public SingleSwitchProgramInstance{ +public: + MaterialFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + MaterialFarmerOptions MATERIAL_FARMER_OPTIONS; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp index fcb9b75890..d0a7075b27 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.cpp @@ -1,870 +1,870 @@ -/* Material Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" -#include "PokemonSV_MaterialFarmerTools.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -MaterialFarmerOptions::~MaterialFarmerOptions(){ -// ENABLE_SANDWICH.remove_listener(*this); -} - -MaterialFarmerOptions::MaterialFarmerOptions( - GroupOption::EnableMode enable_mode, - OCR::LanguageOCROption* language_option, - EventNotificationOption& notif_status_update_option, - EventNotificationOption& notif_program_finish_option, - EventNotificationOption& notif_error_recoverable_option, - EventNotificationOption& notif_error_fatal_option -) - : GroupOption( - "Material Farmer", - LockMode::UNLOCK_WHILE_RUNNING, - enable_mode - ) - , m_language_owner(language_option == nullptr - ? new OCR::LanguageOCROption( - "Game Language:
Required to read sandwich ingredients.", - IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - : nullptr - ) - , RUN_TIME_IN_MINUTES( - "Run Duration:
Run the material farmer for this many minutes.", - LockMode::UNLOCK_WHILE_RUNNING, - 32 - ) -// , SAVE_GAME_BEFORE_SANDWICH( -// "Save Game before each round:", -// LockMode::UNLOCK_WHILE_RUNNING, -// true -// ) -// , SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT("") -// , NUM_SANDWICH_ROUNDS_STATIC_TEXT("") - , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) - , SANDWICH_OPTIONS( - "Make a Sandwich", - &LANGUAGE, - BaseRecipe::non_shiny, - true, - GroupOption::EnableMode::DEFAULT_DISABLED - ) - , AUTO_HEAL_PERCENT( - "Auto-Heal %
Auto-heal if your HP drops below this percentage.", - LockMode::UNLOCK_WHILE_RUNNING, - 75, 0, 100 - ) - , m_advanced_options( - "Advanced Options: (developer only)" - ) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:
" - "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , SKIP_WARP_TO_POKECENTER( - "Skip warping to closest PokeCenter:
" - "This is for debugging the program without waiting for the initial warp.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -// , ENABLE_SANDWICH( -// "Enable Sandwich making:
" -// "This is for boosting spawn rates of specific Pokemon.", -// LockMode::UNLOCK_WHILE_RUNNING, -// false -// ) - , TIME_PER_SANDWICH( - "Time per sandwich:
Number of minutes before resetting sandwich.", - LockMode::UNLOCK_WHILE_RUNNING, - 30, 1, 30 - ) - , NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION( - "Number of forward moves per lets go iteration:
" - "During Let's go autobattling sequence, the number of forward movements before resetting to Pokecenter.", - LockMode::UNLOCK_WHILE_RUNNING, - 13 - ) - , NOTIFICATION_STATUS_UPDATE(notif_status_update_option) - , NOTIFICATION_PROGRAM_FINISH(notif_program_finish_option) - , NOTIFICATION_ERROR_RECOVERABLE(notif_error_recoverable_option) - , NOTIFICATION_ERROR_FATAL(notif_error_fatal_option) -{ - PA_ADD_OPTION(RUN_TIME_IN_MINUTES); -// PA_ADD_OPTION(ENABLE_SANDWICH); -// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH); -// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT); -// PA_ADD_OPTION(NUM_SANDWICH_ROUNDS_STATIC_TEXT); - if (m_language_owner){ - PA_ADD_OPTION(LANGUAGE); - } - PA_ADD_OPTION(SANDWICH_OPTIONS); - PA_ADD_OPTION(AUTO_HEAL_PERCENT); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(m_advanced_options); - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - PA_ADD_OPTION(SKIP_WARP_TO_POKECENTER); - PA_ADD_OPTION(TIME_PER_SANDWICH); - PA_ADD_OPTION(NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); - } - - MaterialFarmerOptions::on_config_value_changed(this); -// ENABLE_SANDWICH.add_listener(*this); -} - -void MaterialFarmerOptions::on_config_value_changed(void* object){ - -// if (MaterialFarmerOptions::ENABLE_SANDWICH){ -// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text( -// "Saves the game before each sandwich.
" -// "Recommended to leave on, as the sandwich maker will reset the game if it detects an error.
" -// ); -// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text( -// "One sandwich per round.
" -// "400-650 Happiny dust per sandwich, with Normal Encounter power level 2.
" -// "(e.g. Chorizo x4, Banana x2, Mayo x3, Whipped Cream x1)
" -// ); -// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::ENABLED); -// }else{ -// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text(""); -// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text("30 minutes per round.
"); -// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::DISABLED); -// } - -} - -// return new start time, so that minutes remaining is rounded up to a multiple of 32 -WallClock new_start_time_after_reset(WallClock old_start_time, uint16_t run_time_in_minutes){ - auto farming_time_remaining = minutes_remaining(old_start_time, std::chrono::minutes(run_time_in_minutes)); - // round up the time to multiple of 32 (30 minutes per sandwich, plus 2 minutes for sandwich making) - size_t desired_minutes_remaining = ((farming_time_remaining.count()/32)+1)*32; - WallClock new_start_time = current_time() + std::chrono::minutes(desired_minutes_remaining) - std::chrono::minutes(run_time_in_minutes); - return new_start_time; -} - - -void run_material_farmer( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -){ - LetsGoEncounterBotTracker encounter_tracker( - env, console, context, - stats, - options.LANGUAGE - ); - WallClock start_time = current_time(); - WallClock last_sandwich_time = WallClock::min(); - LetsGoHpWatcher hp_watcher(COLOR_RED); - - // ensure we save before running the material farmer. - // but no need to save if already saving prior to each sandwich - if (!(options.SANDWICH_OPTIONS.enabled() && options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH)){ - save_game_from_overworld(env.program_info(), console, context); - } - - /* - - Use Let's Go along the path. Fly back to pokecenter when it reaches the end of the path. - - Keeping repeating this for RUN_TIME_IN_MINUTES minutes - */ - size_t consecutive_failures = 0; - size_t max_consecutive_failures = 15; - while (true){ - try{ - while (true){ - // check time left on material farming - auto farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); - console.log( - "Time left in Material Farming: " + - std::to_string(farming_time_remaining.count()) + " min", - COLOR_PURPLE - ); - if (farming_time_remaining < std::chrono::minutes(0)){ - console.log("Time's up. Stop the Material farming program.", COLOR_RED); - return; - } - - // Check time left on sandwich - if (options.SANDWICH_OPTIONS.enabled()){ - auto sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); - console.log( - "Time left on sandwich: " + - std::to_string(sandwich_time_remaining.count()) + " min", - COLOR_PURPLE - ); - if (sandwich_time_remaining < std::chrono::minutes(0)){ - console.log("Sandwich not active. Make a sandwich."); - last_sandwich_time = make_sandwich_material_farm(env, console, context, options, stats); - console.overlay().add_log("Sandwich made."); - - // Log time remaining in Material farming - farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); - console.log( - "Time left in Material Farming: " + - std::to_string(farming_time_remaining.count()) + " min", - COLOR_PURPLE - ); - // Log time remaining on Sandwich - sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); - console.log( - "Time left on sandwich: " + - std::to_string(sandwich_time_remaining.count()) + " min", - COLOR_PURPLE - ); - } - } - - // heal before starting Let's go - console.log("Heal before starting Let's go", COLOR_PURPLE); - console.log("Heal threshold: " + tostr_default(options.AUTO_HEAL_PERCENT), COLOR_PURPLE); - check_hp(env, console, context, options, hp_watcher, stats); - - /* - - Starts from pokemon center. - - Flies to start position. Runs a Let's Go iteration. - - Then returns to pokemon center, regardless of whether - it completes the action or gets caught in a battle - */ - run_from_battles_and_back_to_pokecenter(env, console, context, stats, - [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - // Move to starting position for Let's Go hunting path - stream.log("Move to starting position for Let's Go hunting path.", COLOR_PURPLE); - move_to_start_position_for_letsgo1(env.program_info(), stream, context); - - // run let's go while updating the HP watcher - stream.log("Starting Let's Go hunting path.", COLOR_PURPLE); - run_until( - stream, context, - [&](ProControllerContext& context){ - run_lets_go_iteration(stream, context, encounter_tracker, options.NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); - }, - {hp_watcher} - ); - } - ); - - context.wait_for_all_requests(); - } - }catch (OperationFailedException& e){ - stats.m_errors++; - env.update_stats(); - e.send_notification(env, options.NOTIFICATION_ERROR_RECOVERABLE); - - // save screenshot after operation failed, - // dump_snapshot(console); - - if (options.SAVE_DEBUG_VIDEO){ - // Take a video to give more context for debugging - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - consecutive_failures++; - if (consecutive_failures >= max_consecutive_failures){ - throw e; - } - - env.log("Reset game to handle recoverable error."); - reset_game(env.program_info(), console, context); - stats.m_game_resets++; - env.update_stats(); - - // update start time, so that minutes remaining is rounded up to a multiple of 32 - start_time = new_start_time_after_reset(start_time, options.RUN_TIME_IN_MINUTES); - // also update last sandwich time - last_sandwich_time = WallClock::min(); - } - } -} - - - -void check_hp( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - LetsGoHpWatcher& hp_watcher, - MaterialFarmerStats& stats -){ - double hp = hp_watcher.last_known_value() * 100; - if (0 < hp){ - stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); - }else{ - stream.log("Last Known HP: ?", COLOR_RED); - } - if (0 < hp && hp < options.AUTO_HEAL_PERCENT){ - auto_heal_from_menu_or_overworld(env.program_info(), stream, context, 0, true); - stats.m_autoheals++; - env.update_stats(); - send_program_status_notification(env, options.NOTIFICATION_STATUS_UPDATE); - } -} - - - -// make sandwich then go back to Pokecenter to reset position -// if gets caught up in a battle, try again. -WallClock make_sandwich_material_farm( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -){ - - if (options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH){ - save_game_from_overworld(env.program_info(), stream, context); - } - - WallClock last_sandwich_time = WallClock::min(); - while(last_sandwich_time == WallClock::min()){ - run_from_battles_and_back_to_pokecenter(env, stream, context, stats, - [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - // Orient camera to look at same direction as player character - // - This is needed because when save-load the game, - // the camera angle is different than when just flying to pokecenter - pbf_press_button(context, BUTTON_L, 50, 40); - - // move up towards pokecenter counter - pbf_move_left_joystick(context, 128, 255, 180, 10); - // Orient camera to look at same direction as player character - pbf_press_button(context, BUTTON_L, 50, 40); - // look left - pbf_move_right_joystick(context, 0, 128, 120, 0); - // move toward clearing besides the pokecenter - pbf_move_left_joystick(context, 128, 0, 300, 0); - - // make sandwich - picnic_from_overworld(env.program_info(), stream, context); - pbf_move_left_joystick(context, 128, 0, 100, 40); // walk forward to picnic table - enter_sandwich_recipe_list(env.program_info(), stream, context); - make_sandwich_option(env, stream, context, options.SANDWICH_OPTIONS); - last_sandwich_time = current_time(); - leave_picnic(env.program_info(), stream, context); - - stats.m_sandwiches++; - env.update_stats(); - - } - ); - } - - return last_sandwich_time; -} - -// given the start time, and duration in minutes, return the number of remaining minutes -std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration){ - return std::chrono::minutes(minutes_duration) - - std::chrono::duration_cast(current_time() - start_time); -} - -// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming -void move_to_start_position_for_letsgo0( - VideoStream& stream, - ProControllerContext& context -){ - // Orient camera to look at same direction as player character - // - This is needed because when save-load the game, - // the camera angle is different than when just flying to pokecenter - pbf_press_button(context, BUTTON_L, 50, 40); - - // move up towards pokecenter counter - pbf_move_left_joystick(context, 128, 255, 180, 10); - // Orient camera to look at same direction as player character - pbf_press_button(context, BUTTON_L, 50, 40); - // look left - pbf_move_right_joystick(context, 0, 128, 120, 10); - // move toward clearing besides the pokecenter - pbf_move_left_joystick(context, 128, 0, 300, 10); - - // look right, towards the start position - pbf_move_right_joystick(context, 255, 128, 120, 10); - pbf_move_left_joystick(context, 128, 0, 10, 10); - - // get on ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // Jump - pbf_press_button(context, BUTTON_B, 125, 100); - - // Fly - pbf_press_button(context, BUTTON_B, 50, 10); // Double up this press - pbf_press_button(context, BUTTON_B, 50, 10); // in case one is dropped. - pbf_press_button(context, BUTTON_LCLICK, 50, 0); - // you automatically move forward without pressing any buttons. so just wait - pbf_wait(context, 1400); - - // Glide forward - // pbf_move_left_joystick(context, 128, 0, 2500, 10); - - // arrived at start position. stop flying - pbf_press_button(context, BUTTON_B, 50, 400); - // get off ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // look right - pbf_move_right_joystick(context, 255, 128, 30, 10); - pbf_move_left_joystick(context, 128, 0, 50, 10); - - stream.log("Arrived at Let's go start position", COLOR_PURPLE); - - -} - -// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming -void move_to_start_position_for_letsgo1( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -){ - // Orient camera to look at same direction as player character - // - This is needed because when save-load the game, - // the camera angle is different than when just flying to pokecenter - pbf_press_button(context, BUTTON_L, 50, 40); - - // move up towards pokecenter counter - pbf_move_left_joystick(context, 128, 255, 180, 10); - // Orient camera to look at same direction as player character - pbf_press_button(context, BUTTON_L, 50, 40); - // look left - pbf_move_right_joystick(context, 0, 128, 120, 10); - // move toward clearing besides the pokecenter - pbf_move_left_joystick(context, 128, 0, 300, 10); - - // look right, towards the start position - DirectionDetector direction; - direction.change_direction(info, stream, context, 5.76); - // pbf_move_right_joystick(context, 255, 128, 130, 10); - pbf_move_left_joystick(context, 128, 0, 10, 10); - - // get on ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // Jump - pbf_press_button(context, BUTTON_B, 125, 30); - - // Fly - pbf_press_button(context, BUTTON_B, 50, 10); - pbf_press_button(context, BUTTON_B, 50, 50); // Double click in case of drop - pbf_press_button(context, BUTTON_LCLICK, 50, 0); - - // you automatically move forward when flying without pressing any buttons. - // so, just wait. - pbf_wait(context, 2200); - - // arrived at start position. stop flying - pbf_press_button(context, BUTTON_B, 50, 400); - // get off ride - pbf_press_button(context, BUTTON_PLUS, 50, 50); - - // extra B presses to ensure we stop flying, in case the previous B press - // was dropped. This way, you eventually reset back to Pokecenter, instead - // of flying until an exception is thrown. - pbf_press_button(context, BUTTON_B, 50, 10); - pbf_press_button(context, BUTTON_B, 50, 10); - - // look right - // pbf_move_right_joystick(context, 255, 128, 20, 10); - direction.change_direction(info, stream, context, 5.3); - - // move forward slightly - pbf_move_left_joystick(context, 128, 0, 50, 10); - - stream.log("Arrived at Let's go start position", COLOR_PURPLE); -} - - -// wait, then move forward quickly -void lets_go_movement0(ProControllerContext& context){ - pbf_wait(context, 500); - pbf_move_left_joystick(context, 128, 0, 200, 10); -} - -// wait, then move forward quickly, then wait some more. -void lets_go_movement1(ProControllerContext& context){ - pbf_wait(context, 500); - pbf_move_left_joystick(context, 128, 0, 100, 10); - pbf_wait(context, 100); -} - - -/* -- One iteration of the hunt: -- start at North Province (Area 3) pokecenter, go out and use Let's Go to battle -- move forward and send out lead pokemon to autobattle. When it runs out of pokemon to battle, -move forward again to repeat the cycle. It does this as many times as per num_forward_moves_per_lets_go_iteration. - */ -void run_lets_go_iteration( - VideoStream& stream, - ProControllerContext& context, - LetsGoEncounterBotTracker& encounter_tracker, - int num_forward_moves_per_lets_go_iteration -){ - // - Orient camera to look at same direction as player character - // - This is needed because when save-load the game, the camera points - // in the same direction as the player. - // - But when warping to pokecenter, the camera is facing the player. - pbf_press_button(context, BUTTON_L, 50, 40); - - // zoom out camera - pbf_move_right_joystick(context, 128, 255, 45, 10); - - const bool throw_ball_if_bubble = false; - const int total_iterations = num_forward_moves_per_lets_go_iteration; - - context.wait_for_all_requests(); - for(int i = 0; i < total_iterations; i++){ - use_lets_go_to_clear_in_front(stream, context, encounter_tracker, throw_ball_if_bubble, [&](ProControllerContext& context){ - // Do the following movement while the Let's Go pokemon clearing wild pokemon. - stream.log("Move-forward iteration number: " + std::to_string(i + 1) + "/" + std::to_string(total_iterations), COLOR_PURPLE); - - lets_go_movement1(context); - }); - } - -} - -/* -- This function wraps around an action (e.g. leave the PokeCenter to make a sandwich) so that -we can handle pokemon wild encounters when executing the action. - - note that returning to the PokeCenter is also wrapped, since it's possible to get caught - in a wild encounter when trying to return to the PokeCenter. -- Whenever a battle happens, we run away and after the battle ends, move back to the PokeCenter -- When `action` ends, go back to the PokeCenter. -- i.e. return to Pokecenter regardless of whether the action succeeds or not. -- NOTE: This works differently than `handle_battles_and_back_to_pokecenter` from the Scatterbug program, -where the action will be attempted infinite times if you keep failing. In contrast, this function -only gives you one attempt before returning to the Pokecenter -*/ -void run_from_battles_and_back_to_pokecenter( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerStats& stats, - std::function< - void(ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context) - >&& action -){ - bool attempted_action = false; - // a flag for the case that the action has finished but not yet returned to pokecenter - bool returned_to_pokecenter = false; - while(returned_to_pokecenter == false){ - NormalBattleMenuWatcher battle_menu(COLOR_RED); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - if (!attempted_action){ // We still need to carry out `action` - attempted_action = true; - context.wait_for_all_requests(); - action(env, stream, context); - context.wait_for_all_requests(); - } - - // we have already attempted the action, - // so reset to the Pokecenter - stream.log("Go back to PokeCenter."); - reset_to_pokecenter(env.program_info(), stream, context); - returned_to_pokecenter = true; - }, - {battle_menu} - ); - if (ret == 0){ // battle detected - stats.m_encounters++; - env.update_stats(); - stream.log("Detected battle. Now running away.", COLOR_PURPLE); - stream.overlay().add_log("Detected battle. Now running away."); - try{ - run_from_battle(env.program_info(), stream, context); - }catch (OperationFailedException& e){ - throw FatalProgramException(std::move(e)); - } - } - } -} - - - - -void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Start moving from material farming to item printer."); - fly_from_paldea_to_blueberry_entrance(info, stream, context); - move_from_blueberry_entrance_to_league_club(info, stream, context); - move_from_league_club_entrance_to_item_printer(info, stream, context); -} - -void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - int numAttempts = 0; - const int maxAttempts = 11; - bool isFlySuccessful = false; - - // in order to land on the target fly point semi-consistently, - // the push magnitude can range from 69 to 85 (range of 16). - // On each failure, try increasing/decreasing the push by 1/4 of the max range, - // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment - const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; - while (!isFlySuccessful && numAttempts < maxAttempts){ - // close all menus - pbf_mash_button(context, BUTTON_B, 100); - - numAttempts++; - - open_map_from_overworld(info, stream, context); - - // change from Paldea map to Blueberry map - pbf_press_button(context, BUTTON_L, 50, 300); - - // move cursor to bottom right corner - pbf_move_left_joystick(context, 255, 255, TICKS_PER_SECOND*5, 50); - - // move cursor to Blueberry academy fast travel point (up-left) - // try different magnitudes of cursor push with each failure. - int push_magnitude = 105 + adjustment_table[numAttempts]; - pbf_move_left_joystick(context, 64, 64, (uint16_t)push_magnitude, 50); - - // press A to fly to Blueberry academy - isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); - if (!isFlySuccessful){ - stream.log("Failed to fly to Blueberry academy."); - // dump_snapshot(stream); - } - } - - if (!isFlySuccessful){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to Blueberry academy, five times in a row.", - stream - ); - } -} - -void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - - int numAttempts = 0; - int maxAttempts = 5; - bool isSuccessful = false; - - while (!isSuccessful && numAttempts < maxAttempts){ - if (numAttempts > 0){ // failed at least once - pbf_mash_button(context, BUTTON_B, 100); - open_map_from_overworld(info, stream, context); - fly_to_overworld_from_map(info, stream, context, false); - } - - numAttempts++; - - // move toward entrance gates - pbf_move_left_joystick(context, 190, 0, 200, 50); - - context.wait_for_all_requests(); - - // Wait for detection of Blueberry navigation menu - ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); - GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); - int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }); - if (ret == 0){ - stream.log("Blueberry navigation menu detected."); - }else{ - stream.log("Failed to detect Blueberry navigation menu."); - continue; - } - - // Move selector to League club room - pbf_press_dpad(context, DPAD_UP, 20, 50); - - // Confirm to League club room is selected - ImageFloatBox select_league_club_box(0.038, 0.785, 0.043, 0.081); - GradientArrowWatcher select_league_club(COLOR_RED, GradientArrowType::RIGHT, select_league_club_box, Milliseconds(1000)); - ret = wait_until(stream, context, Milliseconds(5000), { select_league_club }); - if (ret == 0){ - stream.log("League club room selected."); - }else{ - stream.log("Failed to select League club room in navigation menu."); - continue; - } - // press A - pbf_mash_button(context, BUTTON_A, 100); - - // check for overworld - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - ret = wait_until(stream, context, Milliseconds(10000), { overworld }); - if (ret == 0){ - stream.log("Entered League club room."); - }else{ - stream.log("Failed to enter League club room from menu selection."); - continue; - } - - isSuccessful = true; - } - - if (!isSuccessful){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter League club room, five times in a row.", - stream - ); - } - -} - -void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - - // move forwards towards table next to item printer - pbf_move_left_joystick(context, 120, 0, 200, 50); - - // look left towards item printer - pbf_move_left_joystick(context, 0, 128, 10, 50); -} - -void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Start moving from item printer to material farming."); - move_from_item_printer_to_blueberry_entrance(info, stream, context); - fly_from_blueberry_to_north_province_3(info, stream, context); -} - -// assumes you start in the position in front of the item printer, as if you finished using it. -void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - - // look left towards door - pbf_move_left_joystick(context, 0, 128, 10, 50); - - // re-orient camera to look same direction as player - pbf_press_button(context, BUTTON_L, 50, 50); - - // move forward towards door - pbf_move_left_joystick(context, 128, 0, 700, 50); - - context.wait_for_all_requests(); - - stream.log("Wait for detection of Blueberry navigation menu."); - - // Wait for detection of Blueberry navigation menu - ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); - GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); - int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }, Milliseconds(1000)); - if (ret == 0){ - stream.log("Blueberry navigation menu detected."); - }else{ - stream.log("Failed to detect Blueberry navigation menu."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to find the exit from the League room.", - stream - ); - } - - // press A - pbf_mash_button(context, BUTTON_A, 100); - - // check for overworld - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - ret = wait_until(stream, context, std::chrono::seconds(30), { overworld }); - if (ret == 0){ - stream.log("Overworld detected"); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect overworld.", - stream - ); - } -} - - -void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - int numAttempts = 0; - const int maxAttempts = 11; - bool isFlySuccessful = false; - - // in order to land on the target fly point, the push magnitude can range from - // 156 to 172 (range of 16). - // On each failure, try increasing/decreasing the push by 1/4 of the max range, - // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment - const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; - while (!isFlySuccessful && numAttempts < maxAttempts){ - numAttempts++; - - // close all menus - pbf_mash_button(context, BUTTON_B, 100); - - open_map_from_overworld(info, stream, context); - - // change from Blueberry map to Paldea map - pbf_press_button(context, BUTTON_R, 50, 300); - - // zoom out - pbf_press_button(context, BUTTON_ZL, 25, 200); - - // move cursor up-left - // try different magnitudes of cursor push with each failure. - int push_magnitude = 168 + adjustment_table[numAttempts]; - pbf_move_left_joystick(context, 112, 0, (uint16_t)push_magnitude, 50); - - // press A to fly to North province area 3 - isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); - - if (!isFlySuccessful){ - stream.log("Failed to fly to North province area 3."); - // dump_snapshot(console); - } - } - - if (!isFlySuccessful){ - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to North province area 3, ten times in a row.", - stream - ); - - } -} - - - -} -} -} +/* Material Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" +#include "PokemonSV_MaterialFarmerTools.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +MaterialFarmerOptions::~MaterialFarmerOptions(){ +// ENABLE_SANDWICH.remove_listener(*this); +} + +MaterialFarmerOptions::MaterialFarmerOptions( + GroupOption::EnableMode enable_mode, + OCR::LanguageOCROption* language_option, + EventNotificationOption& notif_status_update_option, + EventNotificationOption& notif_program_finish_option, + EventNotificationOption& notif_error_recoverable_option, + EventNotificationOption& notif_error_fatal_option +) + : GroupOption( + "Material Farmer", + LockMode::UNLOCK_WHILE_RUNNING, + enable_mode + ) + , m_language_owner(language_option == nullptr + ? new OCR::LanguageOCROption( + "Game Language:
Required to read sandwich ingredients.", + IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + : nullptr + ) + , RUN_TIME_IN_MINUTES( + "Run Duration:
Run the material farmer for this many minutes.", + LockMode::UNLOCK_WHILE_RUNNING, + 32 + ) +// , SAVE_GAME_BEFORE_SANDWICH( +// "Save Game before each round:", +// LockMode::UNLOCK_WHILE_RUNNING, +// true +// ) +// , SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT("") +// , NUM_SANDWICH_ROUNDS_STATIC_TEXT("") + , LANGUAGE(language_option == nullptr ? *m_language_owner : *language_option) + , SANDWICH_OPTIONS( + "Make a Sandwich", + &LANGUAGE, + BaseRecipe::non_shiny, + true, + GroupOption::EnableMode::DEFAULT_DISABLED + ) + , AUTO_HEAL_PERCENT( + "Auto-Heal %
Auto-heal if your HP drops below this percentage.", + LockMode::UNLOCK_WHILE_RUNNING, + 75, 0, 100 + ) + , m_advanced_options( + "Advanced Options: (developer only)" + ) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:
" + "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , SKIP_WARP_TO_POKECENTER( + "Skip warping to closest PokeCenter:
" + "This is for debugging the program without waiting for the initial warp.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +// , ENABLE_SANDWICH( +// "Enable Sandwich making:
" +// "This is for boosting spawn rates of specific Pokemon.", +// LockMode::UNLOCK_WHILE_RUNNING, +// false +// ) + , TIME_PER_SANDWICH( + "Time per sandwich:
Number of minutes before resetting sandwich.", + LockMode::UNLOCK_WHILE_RUNNING, + 30, 1, 30 + ) + , NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION( + "Number of forward moves per lets go iteration:
" + "During Let's go autobattling sequence, the number of forward movements before resetting to Pokecenter.", + LockMode::UNLOCK_WHILE_RUNNING, + 13 + ) + , NOTIFICATION_STATUS_UPDATE(notif_status_update_option) + , NOTIFICATION_PROGRAM_FINISH(notif_program_finish_option) + , NOTIFICATION_ERROR_RECOVERABLE(notif_error_recoverable_option) + , NOTIFICATION_ERROR_FATAL(notif_error_fatal_option) +{ + PA_ADD_OPTION(RUN_TIME_IN_MINUTES); +// PA_ADD_OPTION(ENABLE_SANDWICH); +// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH); +// PA_ADD_OPTION(SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT); +// PA_ADD_OPTION(NUM_SANDWICH_ROUNDS_STATIC_TEXT); + if (m_language_owner){ + PA_ADD_OPTION(LANGUAGE); + } + PA_ADD_OPTION(SANDWICH_OPTIONS); + PA_ADD_OPTION(AUTO_HEAL_PERCENT); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(m_advanced_options); + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + PA_ADD_OPTION(SKIP_WARP_TO_POKECENTER); + PA_ADD_OPTION(TIME_PER_SANDWICH); + PA_ADD_OPTION(NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); + } + + MaterialFarmerOptions::on_config_value_changed(this); +// ENABLE_SANDWICH.add_listener(*this); +} + +void MaterialFarmerOptions::on_config_value_changed(void* object){ + +// if (MaterialFarmerOptions::ENABLE_SANDWICH){ +// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text( +// "Saves the game before each sandwich.
" +// "Recommended to leave on, as the sandwich maker will reset the game if it detects an error.
" +// ); +// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text( +// "One sandwich per round.
" +// "400-650 Happiny dust per sandwich, with Normal Encounter power level 2.
" +// "(e.g. Chorizo x4, Banana x2, Mayo x3, Whipped Cream x1)
" +// ); +// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::ENABLED); +// }else{ +// SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT.set_text(""); +// NUM_SANDWICH_ROUNDS_STATIC_TEXT.set_text("30 minutes per round.
"); +// MaterialFarmerOptions::SANDWICH_OPTIONS.set_visibility(ConfigOptionState::DISABLED); +// } + +} + +// return new start time, so that minutes remaining is rounded up to a multiple of 32 +WallClock new_start_time_after_reset(WallClock old_start_time, uint16_t run_time_in_minutes){ + auto farming_time_remaining = minutes_remaining(old_start_time, std::chrono::minutes(run_time_in_minutes)); + // round up the time to multiple of 32 (30 minutes per sandwich, plus 2 minutes for sandwich making) + size_t desired_minutes_remaining = ((farming_time_remaining.count()/32)+1)*32; + WallClock new_start_time = current_time() + std::chrono::minutes(desired_minutes_remaining) - std::chrono::minutes(run_time_in_minutes); + return new_start_time; +} + + +void run_material_farmer( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +){ + LetsGoEncounterBotTracker encounter_tracker( + env, console, context, + stats, + options.LANGUAGE + ); + WallClock start_time = current_time(); + WallClock last_sandwich_time = WallClock::min(); + LetsGoHpWatcher hp_watcher(COLOR_RED); + + // ensure we save before running the material farmer. + // but no need to save if already saving prior to each sandwich + if (!(options.SANDWICH_OPTIONS.enabled() && options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH)){ + save_game_from_overworld(env.program_info(), console, context); + } + + /* + - Use Let's Go along the path. Fly back to pokecenter when it reaches the end of the path. + - Keeping repeating this for RUN_TIME_IN_MINUTES minutes + */ + size_t consecutive_failures = 0; + size_t max_consecutive_failures = 15; + while (true){ + try{ + while (true){ + // check time left on material farming + auto farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); + console.log( + "Time left in Material Farming: " + + std::to_string(farming_time_remaining.count()) + " min", + COLOR_PURPLE + ); + if (farming_time_remaining < std::chrono::minutes(0)){ + console.log("Time's up. Stop the Material farming program.", COLOR_RED); + return; + } + + // Check time left on sandwich + if (options.SANDWICH_OPTIONS.enabled()){ + auto sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); + console.log( + "Time left on sandwich: " + + std::to_string(sandwich_time_remaining.count()) + " min", + COLOR_PURPLE + ); + if (sandwich_time_remaining < std::chrono::minutes(0)){ + console.log("Sandwich not active. Make a sandwich."); + last_sandwich_time = make_sandwich_material_farm(env, console, context, options, stats); + console.overlay().add_log("Sandwich made."); + + // Log time remaining in Material farming + farming_time_remaining = minutes_remaining(start_time, std::chrono::minutes(options.RUN_TIME_IN_MINUTES)); + console.log( + "Time left in Material Farming: " + + std::to_string(farming_time_remaining.count()) + " min", + COLOR_PURPLE + ); + // Log time remaining on Sandwich + sandwich_time_remaining = minutes_remaining(last_sandwich_time, std::chrono::minutes(options.TIME_PER_SANDWICH)); + console.log( + "Time left on sandwich: " + + std::to_string(sandwich_time_remaining.count()) + " min", + COLOR_PURPLE + ); + } + } + + // heal before starting Let's go + console.log("Heal before starting Let's go", COLOR_PURPLE); + console.log("Heal threshold: " + tostr_default(options.AUTO_HEAL_PERCENT), COLOR_PURPLE); + check_hp(env, console, context, options, hp_watcher, stats); + + /* + - Starts from pokemon center. + - Flies to start position. Runs a Let's Go iteration. + - Then returns to pokemon center, regardless of whether + it completes the action or gets caught in a battle + */ + run_from_battles_and_back_to_pokecenter(env, console, context, stats, + [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + // Move to starting position for Let's Go hunting path + stream.log("Move to starting position for Let's Go hunting path.", COLOR_PURPLE); + move_to_start_position_for_letsgo1(env.program_info(), stream, context); + + // run let's go while updating the HP watcher + stream.log("Starting Let's Go hunting path.", COLOR_PURPLE); + run_until( + stream, context, + [&](ProControllerContext& context){ + run_lets_go_iteration(stream, context, encounter_tracker, options.NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION); + }, + {hp_watcher} + ); + } + ); + + context.wait_for_all_requests(); + } + }catch (OperationFailedException& e){ + stats.m_errors++; + env.update_stats(); + e.send_notification(env, options.NOTIFICATION_ERROR_RECOVERABLE); + + // save screenshot after operation failed, + // dump_snapshot(console); + + if (options.SAVE_DEBUG_VIDEO){ + // Take a video to give more context for debugging + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + consecutive_failures++; + if (consecutive_failures >= max_consecutive_failures){ + throw e; + } + + env.log("Reset game to handle recoverable error."); + reset_game(env.program_info(), console, context); + stats.m_game_resets++; + env.update_stats(); + + // update start time, so that minutes remaining is rounded up to a multiple of 32 + start_time = new_start_time_after_reset(start_time, options.RUN_TIME_IN_MINUTES); + // also update last sandwich time + last_sandwich_time = WallClock::min(); + } + } +} + + + +void check_hp( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + LetsGoHpWatcher& hp_watcher, + MaterialFarmerStats& stats +){ + double hp = hp_watcher.last_known_value() * 100; + if (0 < hp){ + stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); + }else{ + stream.log("Last Known HP: ?", COLOR_RED); + } + if (0 < hp && hp < options.AUTO_HEAL_PERCENT){ + auto_heal_from_menu_or_overworld(env.program_info(), stream, context, 0, true); + stats.m_autoheals++; + env.update_stats(); + send_program_status_notification(env, options.NOTIFICATION_STATUS_UPDATE); + } +} + + + +// make sandwich then go back to Pokecenter to reset position +// if gets caught up in a battle, try again. +WallClock make_sandwich_material_farm( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +){ + + if (options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH){ + save_game_from_overworld(env.program_info(), stream, context); + } + + WallClock last_sandwich_time = WallClock::min(); + while(last_sandwich_time == WallClock::min()){ + run_from_battles_and_back_to_pokecenter(env, stream, context, stats, + [&](ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + // Orient camera to look at same direction as player character + // - This is needed because when save-load the game, + // the camera angle is different than when just flying to pokecenter + pbf_press_button(context, BUTTON_L, 50, 40); + + // move up towards pokecenter counter + pbf_move_left_joystick(context, 128, 255, 180, 10); + // Orient camera to look at same direction as player character + pbf_press_button(context, BUTTON_L, 50, 40); + // look left + pbf_move_right_joystick(context, 0, 128, 120, 0); + // move toward clearing besides the pokecenter + pbf_move_left_joystick(context, 128, 0, 300, 0); + + // make sandwich + picnic_from_overworld(env.program_info(), stream, context); + pbf_move_left_joystick(context, 128, 0, 100, 40); // walk forward to picnic table + enter_sandwich_recipe_list(env.program_info(), stream, context); + make_sandwich_option(env, stream, context, options.SANDWICH_OPTIONS); + last_sandwich_time = current_time(); + leave_picnic(env.program_info(), stream, context); + + stats.m_sandwiches++; + env.update_stats(); + + } + ); + } + + return last_sandwich_time; +} + +// given the start time, and duration in minutes, return the number of remaining minutes +std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration){ + return std::chrono::minutes(minutes_duration) - + std::chrono::duration_cast(current_time() - start_time); +} + +// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming +void move_to_start_position_for_letsgo0( + VideoStream& stream, + ProControllerContext& context +){ + // Orient camera to look at same direction as player character + // - This is needed because when save-load the game, + // the camera angle is different than when just flying to pokecenter + pbf_press_button(context, BUTTON_L, 50, 40); + + // move up towards pokecenter counter + pbf_move_left_joystick(context, 128, 255, 180, 10); + // Orient camera to look at same direction as player character + pbf_press_button(context, BUTTON_L, 50, 40); + // look left + pbf_move_right_joystick(context, 0, 128, 120, 10); + // move toward clearing besides the pokecenter + pbf_move_left_joystick(context, 128, 0, 300, 10); + + // look right, towards the start position + pbf_move_right_joystick(context, 255, 128, 120, 10); + pbf_move_left_joystick(context, 128, 0, 10, 10); + + // get on ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // Jump + pbf_press_button(context, BUTTON_B, 125, 100); + + // Fly + pbf_press_button(context, BUTTON_B, 50, 10); // Double up this press + pbf_press_button(context, BUTTON_B, 50, 10); // in case one is dropped. + pbf_press_button(context, BUTTON_LCLICK, 50, 0); + // you automatically move forward without pressing any buttons. so just wait + pbf_wait(context, 1400); + + // Glide forward + // pbf_move_left_joystick(context, 128, 0, 2500, 10); + + // arrived at start position. stop flying + pbf_press_button(context, BUTTON_B, 50, 400); + // get off ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // look right + pbf_move_right_joystick(context, 255, 128, 30, 10); + pbf_move_left_joystick(context, 128, 0, 50, 10); + + stream.log("Arrived at Let's go start position", COLOR_PURPLE); + + +} + +// from the North Province (Area 3) pokecenter, move to start position for Happiny dust farming +void move_to_start_position_for_letsgo1( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +){ + // Orient camera to look at same direction as player character + // - This is needed because when save-load the game, + // the camera angle is different than when just flying to pokecenter + pbf_press_button(context, BUTTON_L, 50, 40); + + // move up towards pokecenter counter + pbf_move_left_joystick(context, 128, 255, 180, 10); + // Orient camera to look at same direction as player character + pbf_press_button(context, BUTTON_L, 50, 40); + // look left + pbf_move_right_joystick(context, 0, 128, 120, 10); + // move toward clearing besides the pokecenter + pbf_move_left_joystick(context, 128, 0, 300, 10); + + // look right, towards the start position + DirectionDetector direction; + direction.change_direction(info, stream, context, 5.76); + // pbf_move_right_joystick(context, 255, 128, 130, 10); + pbf_move_left_joystick(context, 128, 0, 10, 10); + + // get on ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // Jump + pbf_press_button(context, BUTTON_B, 125, 30); + + // Fly + pbf_press_button(context, BUTTON_B, 50, 10); + pbf_press_button(context, BUTTON_B, 50, 50); // Double click in case of drop + pbf_press_button(context, BUTTON_LCLICK, 50, 0); + + // you automatically move forward when flying without pressing any buttons. + // so, just wait. + pbf_wait(context, 2200); + + // arrived at start position. stop flying + pbf_press_button(context, BUTTON_B, 50, 400); + // get off ride + pbf_press_button(context, BUTTON_PLUS, 50, 50); + + // extra B presses to ensure we stop flying, in case the previous B press + // was dropped. This way, you eventually reset back to Pokecenter, instead + // of flying until an exception is thrown. + pbf_press_button(context, BUTTON_B, 50, 10); + pbf_press_button(context, BUTTON_B, 50, 10); + + // look right + // pbf_move_right_joystick(context, 255, 128, 20, 10); + direction.change_direction(info, stream, context, 5.3); + + // move forward slightly + pbf_move_left_joystick(context, 128, 0, 50, 10); + + stream.log("Arrived at Let's go start position", COLOR_PURPLE); +} + + +// wait, then move forward quickly +void lets_go_movement0(ProControllerContext& context){ + pbf_wait(context, 500); + pbf_move_left_joystick(context, 128, 0, 200, 10); +} + +// wait, then move forward quickly, then wait some more. +void lets_go_movement1(ProControllerContext& context){ + pbf_wait(context, 500); + pbf_move_left_joystick(context, 128, 0, 100, 10); + pbf_wait(context, 100); +} + + +/* +- One iteration of the hunt: +- start at North Province (Area 3) pokecenter, go out and use Let's Go to battle +- move forward and send out lead pokemon to autobattle. When it runs out of pokemon to battle, +move forward again to repeat the cycle. It does this as many times as per num_forward_moves_per_lets_go_iteration. + */ +void run_lets_go_iteration( + VideoStream& stream, + ProControllerContext& context, + LetsGoEncounterBotTracker& encounter_tracker, + int num_forward_moves_per_lets_go_iteration +){ + // - Orient camera to look at same direction as player character + // - This is needed because when save-load the game, the camera points + // in the same direction as the player. + // - But when warping to pokecenter, the camera is facing the player. + pbf_press_button(context, BUTTON_L, 50, 40); + + // zoom out camera + pbf_move_right_joystick(context, 128, 255, 45, 10); + + const bool throw_ball_if_bubble = false; + const int total_iterations = num_forward_moves_per_lets_go_iteration; + + context.wait_for_all_requests(); + for(int i = 0; i < total_iterations; i++){ + use_lets_go_to_clear_in_front(stream, context, encounter_tracker, throw_ball_if_bubble, [&](ProControllerContext& context){ + // Do the following movement while the Let's Go pokemon clearing wild pokemon. + stream.log("Move-forward iteration number: " + std::to_string(i + 1) + "/" + std::to_string(total_iterations), COLOR_PURPLE); + + lets_go_movement1(context); + }); + } + +} + +/* +- This function wraps around an action (e.g. leave the PokeCenter to make a sandwich) so that +we can handle pokemon wild encounters when executing the action. + - note that returning to the PokeCenter is also wrapped, since it's possible to get caught + in a wild encounter when trying to return to the PokeCenter. +- Whenever a battle happens, we run away and after the battle ends, move back to the PokeCenter +- When `action` ends, go back to the PokeCenter. +- i.e. return to Pokecenter regardless of whether the action succeeds or not. +- NOTE: This works differently than `handle_battles_and_back_to_pokecenter` from the Scatterbug program, +where the action will be attempted infinite times if you keep failing. In contrast, this function +only gives you one attempt before returning to the Pokecenter +*/ +void run_from_battles_and_back_to_pokecenter( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerStats& stats, + std::function< + void(ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context) + >&& action +){ + bool attempted_action = false; + // a flag for the case that the action has finished but not yet returned to pokecenter + bool returned_to_pokecenter = false; + while(returned_to_pokecenter == false){ + NormalBattleMenuWatcher battle_menu(COLOR_RED); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + if (!attempted_action){ // We still need to carry out `action` + attempted_action = true; + context.wait_for_all_requests(); + action(env, stream, context); + context.wait_for_all_requests(); + } + + // we have already attempted the action, + // so reset to the Pokecenter + stream.log("Go back to PokeCenter."); + reset_to_pokecenter(env.program_info(), stream, context); + returned_to_pokecenter = true; + }, + {battle_menu} + ); + if (ret == 0){ // battle detected + stats.m_encounters++; + env.update_stats(); + stream.log("Detected battle. Now running away.", COLOR_PURPLE); + stream.overlay().add_log("Detected battle. Now running away."); + try{ + run_from_battle(env.program_info(), stream, context); + }catch (OperationFailedException& e){ + throw FatalProgramException(std::move(e)); + } + } + } +} + + + + +void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Start moving from material farming to item printer."); + fly_from_paldea_to_blueberry_entrance(info, stream, context); + move_from_blueberry_entrance_to_league_club(info, stream, context); + move_from_league_club_entrance_to_item_printer(info, stream, context); +} + +void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + int numAttempts = 0; + const int maxAttempts = 11; + bool isFlySuccessful = false; + + // in order to land on the target fly point semi-consistently, + // the push magnitude can range from 69 to 85 (range of 16). + // On each failure, try increasing/decreasing the push by 1/4 of the max range, + // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment + const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; + while (!isFlySuccessful && numAttempts < maxAttempts){ + // close all menus + pbf_mash_button(context, BUTTON_B, 100); + + numAttempts++; + + open_map_from_overworld(info, stream, context); + + // change from Paldea map to Blueberry map + pbf_press_button(context, BUTTON_L, 50, 300); + + // move cursor to bottom right corner + pbf_move_left_joystick(context, 255, 255, TICKS_PER_SECOND*5, 50); + + // move cursor to Blueberry academy fast travel point (up-left) + // try different magnitudes of cursor push with each failure. + int push_magnitude = 105 + adjustment_table[numAttempts]; + pbf_move_left_joystick(context, 64, 64, (uint16_t)push_magnitude, 50); + + // press A to fly to Blueberry academy + isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); + if (!isFlySuccessful){ + stream.log("Failed to fly to Blueberry academy."); + // dump_snapshot(stream); + } + } + + if (!isFlySuccessful){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to Blueberry academy, five times in a row.", + stream + ); + } +} + +void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + + int numAttempts = 0; + int maxAttempts = 5; + bool isSuccessful = false; + + while (!isSuccessful && numAttempts < maxAttempts){ + if (numAttempts > 0){ // failed at least once + pbf_mash_button(context, BUTTON_B, 100); + open_map_from_overworld(info, stream, context); + fly_to_overworld_from_map(info, stream, context, false); + } + + numAttempts++; + + // move toward entrance gates + pbf_move_left_joystick(context, 190, 0, 200, 50); + + context.wait_for_all_requests(); + + // Wait for detection of Blueberry navigation menu + ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); + GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); + int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }); + if (ret == 0){ + stream.log("Blueberry navigation menu detected."); + }else{ + stream.log("Failed to detect Blueberry navigation menu."); + continue; + } + + // Move selector to League club room + pbf_press_dpad(context, DPAD_UP, 20, 50); + + // Confirm to League club room is selected + ImageFloatBox select_league_club_box(0.038, 0.785, 0.043, 0.081); + GradientArrowWatcher select_league_club(COLOR_RED, GradientArrowType::RIGHT, select_league_club_box, Milliseconds(1000)); + ret = wait_until(stream, context, Milliseconds(5000), { select_league_club }); + if (ret == 0){ + stream.log("League club room selected."); + }else{ + stream.log("Failed to select League club room in navigation menu."); + continue; + } + // press A + pbf_mash_button(context, BUTTON_A, 100); + + // check for overworld + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + ret = wait_until(stream, context, Milliseconds(10000), { overworld }); + if (ret == 0){ + stream.log("Entered League club room."); + }else{ + stream.log("Failed to enter League club room from menu selection."); + continue; + } + + isSuccessful = true; + } + + if (!isSuccessful){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter League club room, five times in a row.", + stream + ); + } + +} + +void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + + // move forwards towards table next to item printer + pbf_move_left_joystick(context, 120, 0, 200, 50); + + // look left towards item printer + pbf_move_left_joystick(context, 0, 128, 10, 50); +} + +void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Start moving from item printer to material farming."); + move_from_item_printer_to_blueberry_entrance(info, stream, context); + fly_from_blueberry_to_north_province_3(info, stream, context); +} + +// assumes you start in the position in front of the item printer, as if you finished using it. +void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + + // look left towards door + pbf_move_left_joystick(context, 0, 128, 10, 50); + + // re-orient camera to look same direction as player + pbf_press_button(context, BUTTON_L, 50, 50); + + // move forward towards door + pbf_move_left_joystick(context, 128, 0, 700, 50); + + context.wait_for_all_requests(); + + stream.log("Wait for detection of Blueberry navigation menu."); + + // Wait for detection of Blueberry navigation menu + ImageFloatBox select_entrance_box(0.031, 0.193, 0.047, 0.078); + GradientArrowWatcher select_entrance(COLOR_RED, GradientArrowType::RIGHT, select_entrance_box); + int ret = wait_until(stream, context, Milliseconds(5000), { select_entrance }, Milliseconds(1000)); + if (ret == 0){ + stream.log("Blueberry navigation menu detected."); + }else{ + stream.log("Failed to detect Blueberry navigation menu."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to find the exit from the League room.", + stream + ); + } + + // press A + pbf_mash_button(context, BUTTON_A, 100); + + // check for overworld + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + ret = wait_until(stream, context, std::chrono::seconds(30), { overworld }); + if (ret == 0){ + stream.log("Overworld detected"); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect overworld.", + stream + ); + } +} + + +void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + int numAttempts = 0; + const int maxAttempts = 11; + bool isFlySuccessful = false; + + // in order to land on the target fly point, the push magnitude can range from + // 156 to 172 (range of 16). + // On each failure, try increasing/decreasing the push by 1/4 of the max range, + // then 1/2 of the range, then the full range, then back to re-attempts with no adjustment + const std::array adjustment_table = {0, 0, 0, 4, -4, 8, -8, 16, -16, 0, 0, 0}; + while (!isFlySuccessful && numAttempts < maxAttempts){ + numAttempts++; + + // close all menus + pbf_mash_button(context, BUTTON_B, 100); + + open_map_from_overworld(info, stream, context); + + // change from Blueberry map to Paldea map + pbf_press_button(context, BUTTON_R, 50, 300); + + // zoom out + pbf_press_button(context, BUTTON_ZL, 25, 200); + + // move cursor up-left + // try different magnitudes of cursor push with each failure. + int push_magnitude = 168 + adjustment_table[numAttempts]; + pbf_move_left_joystick(context, 112, 0, (uint16_t)push_magnitude, 50); + + // press A to fly to North province area 3 + isFlySuccessful = fly_to_overworld_from_map(info, stream, context, true); + + if (!isFlySuccessful){ + stream.log("Failed to fly to North province area 3."); + // dump_snapshot(console); + } + } + + if (!isFlySuccessful){ + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to North province area 3, ten times in a row.", + stream + ); + + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h index 5fd9960ea3..1313a862f4 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h @@ -1,164 +1,164 @@ -/* Material Farmer - Happiny dust - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MaterialFarmerTools_H -#define PokemonAutomation_PokemonSV_MaterialFarmerTools_H - -#include -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" -#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct MaterialFarmerStats : public LetsGoEncounterBotStats{ - MaterialFarmerStats() - : m_sandwiches(m_stats["Sandwiches"]) - , m_autoheals(m_stats["Auto Heals"]) - , m_game_resets(m_stats["Game Resets"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 4, {"Game Resets", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 5, {"Errors", HIDDEN_IF_ZERO}); - } - std::atomic& m_sandwiches; - std::atomic& m_autoheals; - std::atomic& m_game_resets; - std::atomic& m_errors; -}; - -class MaterialFarmerOptions : public GroupOption, public ConfigOption::Listener{ -public: - ~MaterialFarmerOptions(); - MaterialFarmerOptions( - GroupOption::EnableMode enable_mode, - OCR::LanguageOCROption* language_option, - EventNotificationOption& notif_status_update_option, - EventNotificationOption& notif_program_finish_option, - EventNotificationOption& notif_error_recoverable_option, - EventNotificationOption& notif_error_fatal_option - ); - virtual void on_config_value_changed(void* object) override; - -private: - std::unique_ptr m_language_owner; - -public: - SimpleIntegerOption RUN_TIME_IN_MINUTES; - - -// BooleanCheckBoxOption SAVE_GAME_BEFORE_SANDWICH; -// StaticTextOption SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT; - -// StaticTextOption NUM_SANDWICH_ROUNDS_STATIC_TEXT; - - OCR::LanguageOCROption& LANGUAGE; - SandwichMakerOption SANDWICH_OPTIONS; - FloatingPointOption AUTO_HEAL_PERCENT; - - // Debug options - SectionDividerOption m_advanced_options; - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; - BooleanCheckBoxOption SKIP_WARP_TO_POKECENTER; -// BooleanCheckBoxOption ENABLE_SANDWICH; - SimpleIntegerOption TIME_PER_SANDWICH; - SimpleIntegerOption NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION; - - EventNotificationOption& NOTIFICATION_STATUS_UPDATE; - EventNotificationOption& NOTIFICATION_PROGRAM_FINISH; - EventNotificationOption& NOTIFICATION_ERROR_RECOVERABLE; - EventNotificationOption& NOTIFICATION_ERROR_FATAL; -}; - - - -void run_material_farmer( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -); - -void check_hp( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - LetsGoHpWatcher& hp_watcher, - MaterialFarmerStats& stats -); - -WallClock make_sandwich_material_farm( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerOptions& options, - MaterialFarmerStats& stats -); - -void move_to_start_position_for_letsgo0(VideoStream& stream, ProControllerContext& context); - -void move_to_start_position_for_letsgo1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void lets_go_movement0(ProControllerContext& context); - -void lets_go_movement1(ProControllerContext& context); - -std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration); - -void run_lets_go_iteration( - VideoStream& stream, - ProControllerContext& context, - LetsGoEncounterBotTracker& encounter_tracker, - int num_forward_moves_per_lets_go_iteration -); - -void run_from_battles_and_back_to_pokecenter( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - MaterialFarmerStats& stats, - std::function< - void(ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context) - >&& action -); - - - -void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - - -void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - - -} -} -} -#endif +/* Material Farmer - Happiny dust + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MaterialFarmerTools_H +#define PokemonAutomation_PokemonSV_MaterialFarmerTools_H + +#include +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" +#include "PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct MaterialFarmerStats : public LetsGoEncounterBotStats{ + MaterialFarmerStats() + : m_sandwiches(m_stats["Sandwiches"]) + , m_autoheals(m_stats["Auto Heals"]) + , m_game_resets(m_stats["Game Resets"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 4, {"Game Resets", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 5, {"Errors", HIDDEN_IF_ZERO}); + } + std::atomic& m_sandwiches; + std::atomic& m_autoheals; + std::atomic& m_game_resets; + std::atomic& m_errors; +}; + +class MaterialFarmerOptions : public GroupOption, public ConfigOption::Listener{ +public: + ~MaterialFarmerOptions(); + MaterialFarmerOptions( + GroupOption::EnableMode enable_mode, + OCR::LanguageOCROption* language_option, + EventNotificationOption& notif_status_update_option, + EventNotificationOption& notif_program_finish_option, + EventNotificationOption& notif_error_recoverable_option, + EventNotificationOption& notif_error_fatal_option + ); + virtual void on_config_value_changed(void* object) override; + +private: + std::unique_ptr m_language_owner; + +public: + SimpleIntegerOption RUN_TIME_IN_MINUTES; + + +// BooleanCheckBoxOption SAVE_GAME_BEFORE_SANDWICH; +// StaticTextOption SAVE_GAME_BEFORE_SANDWICH_STATIC_TEXT; + +// StaticTextOption NUM_SANDWICH_ROUNDS_STATIC_TEXT; + + OCR::LanguageOCROption& LANGUAGE; + SandwichMakerOption SANDWICH_OPTIONS; + FloatingPointOption AUTO_HEAL_PERCENT; + + // Debug options + SectionDividerOption m_advanced_options; + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; + BooleanCheckBoxOption SKIP_WARP_TO_POKECENTER; +// BooleanCheckBoxOption ENABLE_SANDWICH; + SimpleIntegerOption TIME_PER_SANDWICH; + SimpleIntegerOption NUM_FORWARD_MOVES_PER_LETS_GO_ITERATION; + + EventNotificationOption& NOTIFICATION_STATUS_UPDATE; + EventNotificationOption& NOTIFICATION_PROGRAM_FINISH; + EventNotificationOption& NOTIFICATION_ERROR_RECOVERABLE; + EventNotificationOption& NOTIFICATION_ERROR_FATAL; +}; + + + +void run_material_farmer( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +); + +void check_hp( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + LetsGoHpWatcher& hp_watcher, + MaterialFarmerStats& stats +); + +WallClock make_sandwich_material_farm( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerOptions& options, + MaterialFarmerStats& stats +); + +void move_to_start_position_for_letsgo0(VideoStream& stream, ProControllerContext& context); + +void move_to_start_position_for_letsgo1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void lets_go_movement0(ProControllerContext& context); + +void lets_go_movement1(ProControllerContext& context); + +std::chrono::minutes minutes_remaining(WallClock start_time, std::chrono::minutes minutes_duration); + +void run_lets_go_iteration( + VideoStream& stream, + ProControllerContext& context, + LetsGoEncounterBotTracker& encounter_tracker, + int num_forward_moves_per_lets_go_iteration +); + +void run_from_battles_and_back_to_pokecenter( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + MaterialFarmerStats& stats, + std::function< + void(ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context) + >&& action +); + + + +void move_from_material_farming_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void fly_from_paldea_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void move_from_blueberry_entrance_to_league_club(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void move_from_league_club_entrance_to_item_printer(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + + +void move_from_item_printer_to_material_farming(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void move_from_item_printer_to_blueberry_entrance(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void fly_from_blueberry_to_north_province_3(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.cpp index 691a173ace..96a67b8638 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.cpp @@ -1,810 +1,810 @@ -/* Tournament Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/PokemonSV_MoneyReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h" -#include "PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h" -#include "PokemonSV_TournamentFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -TournamentFarmer_Descriptor::TournamentFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:TournamentFarmer", - STRING_POKEMON + " SV", "Tournament Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TournamentFarmer.md", - "Farm the Academy Ace Tournament for money and prizes.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -struct TournamentFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : tournaments(m_stats["Tournaments won"]) - , battles(m_stats["Battles fought"]) - , losses(m_stats["Losses"]) - , money(m_stats["Money made"]) - , matches(m_stats["Items matched"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Tournaments won"); - m_display_order.emplace_back("Battles fought"); - m_display_order.emplace_back("Losses"); - m_display_order.emplace_back("Money made"); - m_display_order.emplace_back("Items matched"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& tournaments; - std::atomic& battles; - std::atomic& losses; - std::atomic& money; - std::atomic& matches; - std::atomic& errors; -}; -std::unique_ptr TournamentFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -TournamentFarmer::StopButton::StopButton() - : ButtonOption( - "Stop after Current Tournament:", - "Stop after current Tournament", - 0, 16 - ) -{} -void TournamentFarmer::StopButton::set_idle(){ - this->set_enabled(false); - this->set_text("Stop after current Tournament"); -} -void TournamentFarmer::StopButton::set_ready(){ - this->set_enabled(true); - this->set_text("Stop after current Tournament"); -} -void TournamentFarmer::StopButton::set_pressed(){ - this->set_enabled(false); - this->set_text("Program will stop after current tournament..."); -} - - -TournamentFarmer::~TournamentFarmer(){ - STOP_AFTER_CURRENT.remove_listener(*this); -} -TournamentFarmer::TournamentFarmer() - : NUM_ROUNDS( - "Number of Tournaments to run:", - LockMode::UNLOCK_WHILE_RUNNING, - 100, 0 - ) - , TRY_TO_TERASTILLIZE( - "Use Terastillization:
Tera at the start of battle. Will take longer to complete each tournament but may be worth the attack boost.
This setting is not necessary if you are running a set specifically made to farm the tournament.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , SAVE_NUM_ROUNDS( - "Save every this many tournaments:
Zero disables saving. Will save win or lose.", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 0 - ) - , MONEY_LIMIT( - "Stop after earning this amount of money:
Zero disables this check. Does not count losses. In-game maximum is 9,999,999. This can be set up to 999,999,999.", - LockMode::UNLOCK_WHILE_RUNNING, - 9999999, 0, 999999999 - ) - , HHH_ZOROARK( - "Happy Hour H-Zoroark:
Check this if you have an event Hisuian Zoroark with Happy Hour and Memento as your lead.
Happy Hour must be in its first move slot and Memento must be in its second.
", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:
The language is needed to read the prizes.", - TournamentPrizeNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , TARGET_ITEMS("Items:") - , NOTIFICATION_PRIZE_MATCH("Matching Prize", true, false, ImageAttachmentMode::JPG, { "Notifs" }) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_PRIZE_MATCH, - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_stop_after_current(false) -{ - PA_ADD_OPTION(STOP_AFTER_CURRENT); - PA_ADD_OPTION(NUM_ROUNDS); - PA_ADD_OPTION(TRY_TO_TERASTILLIZE); - PA_ADD_OPTION(SAVE_NUM_ROUNDS); - PA_ADD_OPTION(MONEY_LIMIT); - PA_ADD_OPTION(HHH_ZOROARK); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(TARGET_ITEMS); - PA_ADD_OPTION(NOTIFICATIONS); - - STOP_AFTER_CURRENT.set_idle(); - STOP_AFTER_CURRENT.add_listener(*this); -} - -void TournamentFarmer::on_press(){ - global_logger_tagged().log("Stop after current requested..."); - m_stop_after_current.store(true, std::memory_order_relaxed); - STOP_AFTER_CURRENT.set_pressed(); -} - -//Check and process the amount of money earned at the end of a battle -void TournamentFarmer::check_money(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); - - int top_money = -1; - int bottom_money = -1; - - //There must be a value for top money - //Bottom money only appear after 1st battle and should clear out - for (uint16_t c = 0; c < 3 && top_money == -1; c++){ - VideoSnapshot screen = env.console.video().snapshot(); - ImageFloatBox top_notif(0.745, 0.152, 0.206, 0.083); - ImageFloatBox bottom_notif(0.745, 0.261, 0.220, 0.083); - - ImageRGB32 image_top = to_blackwhite_rgb32_range( - extract_box_reference(screen, top_notif), - true, - combine_rgb(215, 215, 215), combine_rgb(255, 255, 255) - ); - //image_top.save("./image_top.png"); - - //Different color range on the bottom notif ~B0B5B8 - ImageRGB32 image_bottom = to_blackwhite_rgb32_range( - extract_box_reference(screen, bottom_notif), - true, - combine_rgb(130, 130, 130), combine_rgb(240, 240, 240) - ); - //image_bottom.save("./image_bottom.png"); - - top_money = OCR::read_money(env.console, image_top); - bottom_money = OCR::read_money(env.console, image_bottom); - - //dump_image( - // env.console, env.program_info(), - // "battledone", - // screen - //); - - //Filter out low and high numbers in case of misreads - //From bulbapedia: Nemona is lowest at 8640, Penny and Geeta are highest at 16800 - //Max earnings? in one battle: happy hour * amulet coin * (base winnings + (8 * make it rain lv100)) - if (top_money < 8000 || top_money > 80000 ){ - top_money = -1; - } - if (bottom_money < 8000 || bottom_money > 80000){ - bottom_money = -1; - } - } - - if (top_money != -1){ - //If both notification boxes appear take the newer one. - if (bottom_money != -1){ - stats.money += bottom_money; - env.update_stats(); - }else{ - stats.money += top_money; - env.update_stats(); - } - }else{ - env.log("Unable to read money."); - } - -} - - -//Handle a single battle by mashing A until AdvanceDialog (end of battle) is detected -void TournamentFarmer::run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); - - //Only applies if the player has The Hidden Treasure of Area Zero Hisuian Zoroark - if (HHH_ZOROARK){ - env.log("Zoroark option checked."); - - //Use happy hour - env.log("Using Happy Hour."); - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - //If not already dead, use memento and die - NormalBattleMenuWatcher memento(COLOR_RED); - MoveSelectDetector move_select(COLOR_BLUE); - SwapMenuWatcher fainted(COLOR_YELLOW); - int retZ = wait_until( - env.console, context, - std::chrono::seconds(60), - { memento, fainted } - ); - if (retZ == 0){ - env.log("Using Memento to faint."); - pbf_press_button(context, BUTTON_A, 10, 50); - move_select.move_to_slot(env.console, context, 1); - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - context.wait_for_all_requests(); - - //Try six times, in case of paralysis (only applies to Pachirisu's Nuzzle) preventing use of Memento. - int retF = run_until( - env.console, context, - [&](ProControllerContext& context){ - for (size_t c = 0; c < 6; c++){ - NormalBattleMenuWatcher battle_memento(COLOR_RED); - int ret_memento = wait_until( - env.console, context, - std::chrono::seconds(60), - { battle_memento } - ); - if (ret_memento == 0){ - env.log("Attempting to use Memento."); - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - } - } - }, - { fainted } - ); - - if (retF == 0){ - env.log("Swap menu detected."); - }else{ - env.log("Took more than 6 turns to use Memento. Was Zoroark able to faint?", COLOR_RED); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Took more than 6 turns to use Memento. Was Zoroark able to faint?", - env.console - ); - } - - }else if (retZ == 1){ - env.log("Detected swap menu. Assuming Zoroark fainted turn one."); - }else{ - env.log("Timed out after Happy Hour.", COLOR_RED); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out after Happy Hour.", - env.console - ); - } - - //Select 2nd pokemon from swap menu and send it out - fainted.move_to_slot(env.console, context, 1); - pbf_mash_button(context, BUTTON_A, 300); - context.wait_for_all_requests(); - - //Check for battle menu to ensure it's sent out - NormalBattleMenuWatcher resume_battle(COLOR_RED); - int retRes = wait_until( - env.console, context, - std::chrono::seconds(60), - { resume_battle } - ); - if (retRes == 0){ - env.log("Battle menu detected. Second Pokemon has been sent out. Resuming usual battle sequence."); - }else{ - env.log("Could not find battle menu.", COLOR_RED); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Could not find battle menu.", - env.console - ); - } - - } - - //Assuming the player has a charged orb - if (TRY_TO_TERASTILLIZE){ - env.log("Attempting to terastillize."); - //Open move menu - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_R, 20, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - } - - //Mash A until battle finished - AdvanceDialogWatcher end_of_battle(COLOR_YELLOW); - WallClock start = current_time(); - uint8_t switch_party_slot = HHH_ZOROARK ? 2: 1; - int ret_black = run_until( - env.console, context, - [&](ProControllerContext& context){ - for(size_t c = 0; c < 30; c++) { //Sylveon build has 16 PP at max, and Chi-Yu build has 24. - if (current_time() - start > std::chrono::minutes(5)){ - env.log("Timed out during battle after 5 minutes.", COLOR_RED); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle after 5 minutes.", - env.console - ); - } - - GradientArrowWatcher switch_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.40, 0.20, 0.30}); - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - MoveSelectWatcher move_select(COLOR_GREEN); - SwapMenuWatcher fainted(COLOR_RED); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(90), //Tera takes ~25 to 30 seconds each, slightly over 60 seconds if both player and opponent uses in the same turn - { - switch_pokemon, - battle_menu, - move_select, - fainted, - } //End of battle from tera'd ace takes longer, 45 seconds was not enough - ); - switch (ret){ - case 0: - env.log("Detected switch " + STRING_POKEMON + " prompt. Pressing B to not switch..."); - pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); - break; - case 1: - env.log("Detected battle menu. Pressing A to attack..."); - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - break; - case 2: - env.log("Detected move selection. Pressing A to attack..."); - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - break; - case 3: - // Since we can't run from the tournament, loop through all party Pokemon spamming their first move. - env.log("Detected fainted " + STRING_POKEMON + ". Switching to next living " + STRING_POKEMON + "..."); - if (fainted.move_to_slot(env.console, context, switch_party_slot)){ - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - switch_party_slot++; - } - break; - default: - env.log("Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", COLOR_RED); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", - env.console - ); - } - } - }, - { end_of_battle } - ); - if (ret_black == 0){ - env.log("Battle finished."); //Cannot tell if win or loss. - stats.battles++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - //Close dialog and then check money - pbf_press_button(context, BUTTON_B, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - check_money(env, context); - - //Clear any remaining dialog - pbf_mash_button(context, BUTTON_B, 300); - context.wait_for_all_requests(); - }else{ - env.log("Timed out during battle. Stuck, crashed, or took over 30 turns.", COLOR_RED); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle. Stuck, crashed, or took over 30 turns.", - env.console - ); - } - context.wait_for_all_requests(); -} - - -//Check prize and notify if it matches filters after a tournament win -void TournamentFarmer::check_prize(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); - - VideoSnapshot screen = env.console.video().snapshot(); - ImageFloatBox dialog_box(0.259, 0.734, 0.484, 0.158); - ImageViewRGB32 dialog_image = extract_box_reference(screen, dialog_box); - - //bool replace_color_within_range = false; - //ImageRGB32 dialog_filtered = filter_rgb32_range( - // extract_box_reference(screen, dialog_box), - // combine_rgb(50, 135, 162), combine_rgb(167, 244, 255), Color(0), replace_color_within_range - //); - //dialog_filtered.save("./dialog_image.png"); - - const double LOG10P_THRESHOLD = -1.5; - OCR::StringMatchResult result = PokemonSV::TournamentPrizeNameReader::instance().read_substring( - env.console, LANGUAGE, dialog_image, - OCR::BLUE_TEXT_FILTERS() - ); - result.clear_beyond_log10p(LOG10P_THRESHOLD); - if (result.results.empty()){ - env.log("No matching prize name found in dialog box."); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - for (const auto& r : result.results){ - env.console.log("Found prize: " + r.second.token); - if (TARGET_ITEMS.find_item(r.second.token)){ - env.log("Prize matched"); - - stats.matches++; - env.update_stats(); - - send_program_notification( - env, NOTIFICATION_PRIZE_MATCH, - COLOR_GREEN, "Prize matched", - { - { "Item:", get_tournament_prize_name(r.second.token).display_name() }, - } - , "", screen); - break; - } - } -} - - -//Tournament won and over -void TournamentFarmer::handle_end_of_tournament(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); - - //Space out the black screen detection after the "champion" battle - //pbf_wait(context, 700); - //context.wait_for_all_requests(); - - //One more black screen when done to load the academy - BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); - int ret_black_won = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { black_screen } - ); - if (ret_black_won == 0){ - env.log("Tournament complete, waiting for academy."); - } - context.wait_for_all_requests(); - - //Wait for congrats dialog - wait an extra bit since the dialog appears while still loading in - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - int ret_dialog = wait_until(env.console, context, Milliseconds(1000), { advance_detector }); - if (ret_dialog == 0){ - env.log("Dialog detected."); - } - pbf_wait(context, 300); - context.wait_for_all_requests(); - - //Next dialog is prize dialog - wait until all dialog has appeared then check prize - pbf_press_button(context, BUTTON_A, 10, 100); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - check_prize(env, context); - - //Clear remaining dialog - OverworldWatcher overworld(env.console, COLOR_CYAN); - int ret_over = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 700); - }, - { overworld } - ); - if (ret_over != 0){ - env.console.log("Failed to detect overworld.", COLOR_RED); - } - context.wait_for_all_requests(); - - stats.tournaments++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); -} - - -//Fly to academy from west pokemon center after losing. -void return_to_academy_after_loss( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context -){ - env.log("Tournament lost! Navigating back to academy."); - go_to_academy_fly_point(env, stream, context); - - - pbf_wait(context, 100); - context.wait_for_all_requests(); - - env.log("At academy fly point. Heading back to doors."); - pbf_move_left_joystick(context, 0, 128, 8, 0); - pbf_press_button(context, BUTTON_L, 50, 40); - pbf_press_button(context, BUTTON_PLUS, 50, 40); - pbf_press_button(context, BUTTON_B, 50, 40); //Trying to jump/glide over npc spawns - pbf_press_button(context, BUTTON_B, 50, 40); - pbf_move_left_joystick(context, 128, 0, 500, 0); - pbf_press_button(context, BUTTON_B, 50, 40); - pbf_press_button(context, BUTTON_B, 50, 40); - - BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); - int ret_black_lost = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 5000, 0); - }, - { black_screen } - ); - context.wait_for_all_requests(); - if (ret_black_lost == 0){ - env.log("Black screen detected."); - } - - //Wait for academy to load. - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret_academy = wait_until(stream, context, Milliseconds(4000), { overworld }); - if (ret_academy == 0){ - env.log("Entered academy. Walking to tournament entry."); - } - context.wait_for_all_requests(); - - //Move to tournament entry - pbf_move_left_joystick(context, 128, 0, 500, 0); - pbf_move_left_joystick(context, 0, 128, 100, 0); - pbf_move_left_joystick(context, 255, 0, 100, 0); - context.wait_for_all_requests(); -} - -void go_to_academy_fly_point(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - int numAttempts = 0; - int maxAttempts = 5; - - bool isFlySuccessful = false; - - while (!isFlySuccessful && numAttempts < maxAttempts ){ - open_map_from_overworld(env.program_info(), stream, context); - pbf_press_button(context, BUTTON_ZR, 50, 40); - pbf_move_left_joystick(context, 200, 0, 47, 25); - // pbf_move_left_joystick(context, 187, 0, 50, 0); - numAttempts++; - isFlySuccessful = fly_to_overworld_from_map(env.program_info(), stream, context, true); - if (!isFlySuccessful){ - env.log("Unsuccessful fly attempt."); - } - pbf_mash_button(context, BUTTON_B, 100); - } - - if(!isFlySuccessful){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly back to academy!", - stream - ); - } - -} - - - -class TournamentFarmer::ResetOnExit{ -public: - ResetOnExit(StopButton& button) - : m_button(button) - {} - ~ResetOnExit(){ - m_button.set_idle(); - } - -private: - StopButton& m_button; -}; - - - -void TournamentFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); - - m_stop_after_current.store(false, std::memory_order_relaxed); - STOP_AFTER_CURRENT.set_ready(); - ResetOnExit reset_button_on_exit(STOP_AFTER_CURRENT); - - /* - Preconditions: - Last Pokemon Center visited is Mesagzoa West - Sylveon only farming build - ideally with fairy tera - stand in front of tournament entry man - Ride legendary is not the solo pokemon (in case of loss) - Do not have other notifications on screen for money reading (ex. new outbreak) - - Possible improvements to make: - find prize sprites - some code is there, just disabled - find translations for tera shards - other languages: make sure "bottle cap" isn't misread as "bottle of PP Up" - */ - - for (uint32_t c = 0; c < NUM_ROUNDS; c++){ - if (m_stop_after_current.load(std::memory_order_relaxed)){ - break; - } - - env.log("Tournament loop started."); - - // Initiate dialog then mash until first battle starts - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - int ret = wait_until(env.console, context, Milliseconds(7000), { advance_detector }); - if (ret == 0){ - env.log("Dialog detected."); - }else{ - env.log("Dialog not detected."); - } - pbf_mash_button(context, BUTTON_A, 400); - context.wait_for_all_requests(); - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret_battle = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); //it takes a while to load and start - }, - { battle_menu } - ); - if (ret_battle != 0){ - env.console.log("Failed to detect battle start!", COLOR_RED); - } - context.wait_for_all_requests(); - - bool battle_lost = false; - for (uint16_t battles = 0; battles < 4; battles++){ - NormalBattleMenuWatcher battle_menu2(COLOR_YELLOW); //Next battle started - OverworldWatcher overworld(env.console, COLOR_CYAN); //Previous battle was lost - int ret_battle2 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - { battle_menu2, overworld } - ); - context.wait_for_all_requests(); - - switch (ret_battle2){ - case 0: - env.log("Detected battle menu."); - run_battle(env, context); - break; - case 1: - env.log("Detected overworld."); - battle_lost = true; - stats.losses++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - break; - default: - env.log("Failed to detect battle menu or dialog prompt!"); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect battle menu or dialog prompt!", - env.console - ); - break; - } - - //If this is the last battle in the tournament check for overworld in case player lost - if (battles == 3){ - env.log("Final battle of the tournament complete, checking for overworld/loss."); - - //Clear dialog, mash B - pbf_mash_button(context, BUTTON_B, 400); - context.wait_for_all_requests(); - - OverworldWatcher overworld2(env.console, COLOR_RED); - int ret_lost_final = wait_until( - env.console, context, - std::chrono::seconds(3), - { overworld2 } - ); - switch (ret_lost_final){ - case 0: - env.log("Final battle of the tournament lost."); - battle_lost = true; - stats.losses++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - break; - default: - env.log("Final battle of the tournament won."); - break; - } - } - - if (battle_lost){ - return_to_academy_after_loss(env, env.console, context); - break; - } - } - - //Tournament won - if (!battle_lost){ - handle_end_of_tournament(env, context); - } - - env.log("Tournament loop complete."); - - //Save the game if option is set - uint16_t num_rounds_temp = SAVE_NUM_ROUNDS; - if (num_rounds_temp != 0 && ((c + 1) % num_rounds_temp) == 0){ - env.log("Saving game."); - save_game_from_overworld(env.program_info(), env.console, context); - } - - //Break loop and finish program if money limit is hit - uint32_t earnings_temp = MONEY_LIMIT; - if (earnings_temp != 0 && stats.money >= earnings_temp){ - env.log("Money limit hit. Ending program."); - break; - } - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - -} -} -} - +/* Tournament Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/PokemonSV_MoneyReader.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Inference/PokemonSV_TournamentPrizeNameReader.h" +#include "PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h" +#include "PokemonSV_TournamentFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +TournamentFarmer_Descriptor::TournamentFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:TournamentFarmer", + STRING_POKEMON + " SV", "Tournament Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TournamentFarmer.md", + "Farm the Academy Ace Tournament for money and prizes.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +struct TournamentFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : tournaments(m_stats["Tournaments won"]) + , battles(m_stats["Battles fought"]) + , losses(m_stats["Losses"]) + , money(m_stats["Money made"]) + , matches(m_stats["Items matched"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Tournaments won"); + m_display_order.emplace_back("Battles fought"); + m_display_order.emplace_back("Losses"); + m_display_order.emplace_back("Money made"); + m_display_order.emplace_back("Items matched"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& tournaments; + std::atomic& battles; + std::atomic& losses; + std::atomic& money; + std::atomic& matches; + std::atomic& errors; +}; +std::unique_ptr TournamentFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +TournamentFarmer::StopButton::StopButton() + : ButtonOption( + "Stop after Current Tournament:", + "Stop after current Tournament", + 0, 16 + ) +{} +void TournamentFarmer::StopButton::set_idle(){ + this->set_enabled(false); + this->set_text("Stop after current Tournament"); +} +void TournamentFarmer::StopButton::set_ready(){ + this->set_enabled(true); + this->set_text("Stop after current Tournament"); +} +void TournamentFarmer::StopButton::set_pressed(){ + this->set_enabled(false); + this->set_text("Program will stop after current tournament..."); +} + + +TournamentFarmer::~TournamentFarmer(){ + STOP_AFTER_CURRENT.remove_listener(*this); +} +TournamentFarmer::TournamentFarmer() + : NUM_ROUNDS( + "Number of Tournaments to run:", + LockMode::UNLOCK_WHILE_RUNNING, + 100, 0 + ) + , TRY_TO_TERASTILLIZE( + "Use Terastillization:
Tera at the start of battle. Will take longer to complete each tournament but may be worth the attack boost.
This setting is not necessary if you are running a set specifically made to farm the tournament.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , SAVE_NUM_ROUNDS( + "Save every this many tournaments:
Zero disables saving. Will save win or lose.", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 0 + ) + , MONEY_LIMIT( + "Stop after earning this amount of money:
Zero disables this check. Does not count losses. In-game maximum is 9,999,999. This can be set up to 999,999,999.", + LockMode::UNLOCK_WHILE_RUNNING, + 9999999, 0, 999999999 + ) + , HHH_ZOROARK( + "Happy Hour H-Zoroark:
Check this if you have an event Hisuian Zoroark with Happy Hour and Memento as your lead.
Happy Hour must be in its first move slot and Memento must be in its second.
", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:
The language is needed to read the prizes.", + TournamentPrizeNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TARGET_ITEMS("Items:") + , NOTIFICATION_PRIZE_MATCH("Matching Prize", true, false, ImageAttachmentMode::JPG, { "Notifs" }) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_PRIZE_MATCH, + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_stop_after_current(false) +{ + PA_ADD_OPTION(STOP_AFTER_CURRENT); + PA_ADD_OPTION(NUM_ROUNDS); + PA_ADD_OPTION(TRY_TO_TERASTILLIZE); + PA_ADD_OPTION(SAVE_NUM_ROUNDS); + PA_ADD_OPTION(MONEY_LIMIT); + PA_ADD_OPTION(HHH_ZOROARK); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(TARGET_ITEMS); + PA_ADD_OPTION(NOTIFICATIONS); + + STOP_AFTER_CURRENT.set_idle(); + STOP_AFTER_CURRENT.add_listener(*this); +} + +void TournamentFarmer::on_press(){ + global_logger_tagged().log("Stop after current requested..."); + m_stop_after_current.store(true, std::memory_order_relaxed); + STOP_AFTER_CURRENT.set_pressed(); +} + +//Check and process the amount of money earned at the end of a battle +void TournamentFarmer::check_money(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); + + int top_money = -1; + int bottom_money = -1; + + //There must be a value for top money + //Bottom money only appear after 1st battle and should clear out + for (uint16_t c = 0; c < 3 && top_money == -1; c++){ + VideoSnapshot screen = env.console.video().snapshot(); + ImageFloatBox top_notif(0.745, 0.152, 0.206, 0.083); + ImageFloatBox bottom_notif(0.745, 0.261, 0.220, 0.083); + + ImageRGB32 image_top = to_blackwhite_rgb32_range( + extract_box_reference(screen, top_notif), + true, + combine_rgb(215, 215, 215), combine_rgb(255, 255, 255) + ); + //image_top.save("./image_top.png"); + + //Different color range on the bottom notif ~B0B5B8 + ImageRGB32 image_bottom = to_blackwhite_rgb32_range( + extract_box_reference(screen, bottom_notif), + true, + combine_rgb(130, 130, 130), combine_rgb(240, 240, 240) + ); + //image_bottom.save("./image_bottom.png"); + + top_money = OCR::read_money(env.console, image_top); + bottom_money = OCR::read_money(env.console, image_bottom); + + //dump_image( + // env.console, env.program_info(), + // "battledone", + // screen + //); + + //Filter out low and high numbers in case of misreads + //From bulbapedia: Nemona is lowest at 8640, Penny and Geeta are highest at 16800 + //Max earnings? in one battle: happy hour * amulet coin * (base winnings + (8 * make it rain lv100)) + if (top_money < 8000 || top_money > 80000 ){ + top_money = -1; + } + if (bottom_money < 8000 || bottom_money > 80000){ + bottom_money = -1; + } + } + + if (top_money != -1){ + //If both notification boxes appear take the newer one. + if (bottom_money != -1){ + stats.money += bottom_money; + env.update_stats(); + }else{ + stats.money += top_money; + env.update_stats(); + } + }else{ + env.log("Unable to read money."); + } + +} + + +//Handle a single battle by mashing A until AdvanceDialog (end of battle) is detected +void TournamentFarmer::run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); + + //Only applies if the player has The Hidden Treasure of Area Zero Hisuian Zoroark + if (HHH_ZOROARK){ + env.log("Zoroark option checked."); + + //Use happy hour + env.log("Using Happy Hour."); + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + //If not already dead, use memento and die + NormalBattleMenuWatcher memento(COLOR_RED); + MoveSelectDetector move_select(COLOR_BLUE); + SwapMenuWatcher fainted(COLOR_YELLOW); + int retZ = wait_until( + env.console, context, + std::chrono::seconds(60), + { memento, fainted } + ); + if (retZ == 0){ + env.log("Using Memento to faint."); + pbf_press_button(context, BUTTON_A, 10, 50); + move_select.move_to_slot(env.console, context, 1); + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + context.wait_for_all_requests(); + + //Try six times, in case of paralysis (only applies to Pachirisu's Nuzzle) preventing use of Memento. + int retF = run_until( + env.console, context, + [&](ProControllerContext& context){ + for (size_t c = 0; c < 6; c++){ + NormalBattleMenuWatcher battle_memento(COLOR_RED); + int ret_memento = wait_until( + env.console, context, + std::chrono::seconds(60), + { battle_memento } + ); + if (ret_memento == 0){ + env.log("Attempting to use Memento."); + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + } + } + }, + { fainted } + ); + + if (retF == 0){ + env.log("Swap menu detected."); + }else{ + env.log("Took more than 6 turns to use Memento. Was Zoroark able to faint?", COLOR_RED); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Took more than 6 turns to use Memento. Was Zoroark able to faint?", + env.console + ); + } + + }else if (retZ == 1){ + env.log("Detected swap menu. Assuming Zoroark fainted turn one."); + }else{ + env.log("Timed out after Happy Hour.", COLOR_RED); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out after Happy Hour.", + env.console + ); + } + + //Select 2nd pokemon from swap menu and send it out + fainted.move_to_slot(env.console, context, 1); + pbf_mash_button(context, BUTTON_A, 300); + context.wait_for_all_requests(); + + //Check for battle menu to ensure it's sent out + NormalBattleMenuWatcher resume_battle(COLOR_RED); + int retRes = wait_until( + env.console, context, + std::chrono::seconds(60), + { resume_battle } + ); + if (retRes == 0){ + env.log("Battle menu detected. Second Pokemon has been sent out. Resuming usual battle sequence."); + }else{ + env.log("Could not find battle menu.", COLOR_RED); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Could not find battle menu.", + env.console + ); + } + + } + + //Assuming the player has a charged orb + if (TRY_TO_TERASTILLIZE){ + env.log("Attempting to terastillize."); + //Open move menu + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_R, 20, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + } + + //Mash A until battle finished + AdvanceDialogWatcher end_of_battle(COLOR_YELLOW); + WallClock start = current_time(); + uint8_t switch_party_slot = HHH_ZOROARK ? 2: 1; + int ret_black = run_until( + env.console, context, + [&](ProControllerContext& context){ + for(size_t c = 0; c < 30; c++) { //Sylveon build has 16 PP at max, and Chi-Yu build has 24. + if (current_time() - start > std::chrono::minutes(5)){ + env.log("Timed out during battle after 5 minutes.", COLOR_RED); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle after 5 minutes.", + env.console + ); + } + + GradientArrowWatcher switch_pokemon(COLOR_BLUE, GradientArrowType::RIGHT, {0.50, 0.40, 0.20, 0.30}); + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + MoveSelectWatcher move_select(COLOR_GREEN); + SwapMenuWatcher fainted(COLOR_RED); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(90), //Tera takes ~25 to 30 seconds each, slightly over 60 seconds if both player and opponent uses in the same turn + { + switch_pokemon, + battle_menu, + move_select, + fainted, + } //End of battle from tera'd ace takes longer, 45 seconds was not enough + ); + switch (ret){ + case 0: + env.log("Detected switch " + STRING_POKEMON + " prompt. Pressing B to not switch..."); + pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); + break; + case 1: + env.log("Detected battle menu. Pressing A to attack..."); + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + break; + case 2: + env.log("Detected move selection. Pressing A to attack..."); + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + break; + case 3: + // Since we can't run from the tournament, loop through all party Pokemon spamming their first move. + env.log("Detected fainted " + STRING_POKEMON + ". Switching to next living " + STRING_POKEMON + "..."); + if (fainted.move_to_slot(env.console, context, switch_party_slot)){ + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + switch_party_slot++; + } + break; + default: + env.log("Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", COLOR_RED); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", + env.console + ); + } + } + }, + { end_of_battle } + ); + if (ret_black == 0){ + env.log("Battle finished."); //Cannot tell if win or loss. + stats.battles++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + //Close dialog and then check money + pbf_press_button(context, BUTTON_B, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + check_money(env, context); + + //Clear any remaining dialog + pbf_mash_button(context, BUTTON_B, 300); + context.wait_for_all_requests(); + }else{ + env.log("Timed out during battle. Stuck, crashed, or took over 30 turns.", COLOR_RED); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle. Stuck, crashed, or took over 30 turns.", + env.console + ); + } + context.wait_for_all_requests(); +} + + +//Check prize and notify if it matches filters after a tournament win +void TournamentFarmer::check_prize(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); + + VideoSnapshot screen = env.console.video().snapshot(); + ImageFloatBox dialog_box(0.259, 0.734, 0.484, 0.158); + ImageViewRGB32 dialog_image = extract_box_reference(screen, dialog_box); + + //bool replace_color_within_range = false; + //ImageRGB32 dialog_filtered = filter_rgb32_range( + // extract_box_reference(screen, dialog_box), + // combine_rgb(50, 135, 162), combine_rgb(167, 244, 255), Color(0), replace_color_within_range + //); + //dialog_filtered.save("./dialog_image.png"); + + const double LOG10P_THRESHOLD = -1.5; + OCR::StringMatchResult result = PokemonSV::TournamentPrizeNameReader::instance().read_substring( + env.console, LANGUAGE, dialog_image, + OCR::BLUE_TEXT_FILTERS() + ); + result.clear_beyond_log10p(LOG10P_THRESHOLD); + if (result.results.empty()){ + env.log("No matching prize name found in dialog box."); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + for (const auto& r : result.results){ + env.console.log("Found prize: " + r.second.token); + if (TARGET_ITEMS.find_item(r.second.token)){ + env.log("Prize matched"); + + stats.matches++; + env.update_stats(); + + send_program_notification( + env, NOTIFICATION_PRIZE_MATCH, + COLOR_GREEN, "Prize matched", + { + { "Item:", get_tournament_prize_name(r.second.token).display_name() }, + } + , "", screen); + break; + } + } +} + + +//Tournament won and over +void TournamentFarmer::handle_end_of_tournament(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); + + //Space out the black screen detection after the "champion" battle + //pbf_wait(context, 700); + //context.wait_for_all_requests(); + + //One more black screen when done to load the academy + BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); + int ret_black_won = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { black_screen } + ); + if (ret_black_won == 0){ + env.log("Tournament complete, waiting for academy."); + } + context.wait_for_all_requests(); + + //Wait for congrats dialog - wait an extra bit since the dialog appears while still loading in + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + int ret_dialog = wait_until(env.console, context, Milliseconds(1000), { advance_detector }); + if (ret_dialog == 0){ + env.log("Dialog detected."); + } + pbf_wait(context, 300); + context.wait_for_all_requests(); + + //Next dialog is prize dialog - wait until all dialog has appeared then check prize + pbf_press_button(context, BUTTON_A, 10, 100); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + check_prize(env, context); + + //Clear remaining dialog + OverworldWatcher overworld(env.console, COLOR_CYAN); + int ret_over = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 700); + }, + { overworld } + ); + if (ret_over != 0){ + env.console.log("Failed to detect overworld.", COLOR_RED); + } + context.wait_for_all_requests(); + + stats.tournaments++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); +} + + +//Fly to academy from west pokemon center after losing. +void return_to_academy_after_loss( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context +){ + env.log("Tournament lost! Navigating back to academy."); + go_to_academy_fly_point(env, stream, context); + + + pbf_wait(context, 100); + context.wait_for_all_requests(); + + env.log("At academy fly point. Heading back to doors."); + pbf_move_left_joystick(context, 0, 128, 8, 0); + pbf_press_button(context, BUTTON_L, 50, 40); + pbf_press_button(context, BUTTON_PLUS, 50, 40); + pbf_press_button(context, BUTTON_B, 50, 40); //Trying to jump/glide over npc spawns + pbf_press_button(context, BUTTON_B, 50, 40); + pbf_move_left_joystick(context, 128, 0, 500, 0); + pbf_press_button(context, BUTTON_B, 50, 40); + pbf_press_button(context, BUTTON_B, 50, 40); + + BlackScreenOverWatcher black_screen(COLOR_RED, { 0.2, 0.2, 0.6, 0.6 }); + int ret_black_lost = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 5000, 0); + }, + { black_screen } + ); + context.wait_for_all_requests(); + if (ret_black_lost == 0){ + env.log("Black screen detected."); + } + + //Wait for academy to load. + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret_academy = wait_until(stream, context, Milliseconds(4000), { overworld }); + if (ret_academy == 0){ + env.log("Entered academy. Walking to tournament entry."); + } + context.wait_for_all_requests(); + + //Move to tournament entry + pbf_move_left_joystick(context, 128, 0, 500, 0); + pbf_move_left_joystick(context, 0, 128, 100, 0); + pbf_move_left_joystick(context, 255, 0, 100, 0); + context.wait_for_all_requests(); +} + +void go_to_academy_fly_point(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + int numAttempts = 0; + int maxAttempts = 5; + + bool isFlySuccessful = false; + + while (!isFlySuccessful && numAttempts < maxAttempts ){ + open_map_from_overworld(env.program_info(), stream, context); + pbf_press_button(context, BUTTON_ZR, 50, 40); + pbf_move_left_joystick(context, 200, 0, 47, 25); + // pbf_move_left_joystick(context, 187, 0, 50, 0); + numAttempts++; + isFlySuccessful = fly_to_overworld_from_map(env.program_info(), stream, context, true); + if (!isFlySuccessful){ + env.log("Unsuccessful fly attempt."); + } + pbf_mash_button(context, BUTTON_B, 100); + } + + if(!isFlySuccessful){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly back to academy!", + stream + ); + } + +} + + + +class TournamentFarmer::ResetOnExit{ +public: + ResetOnExit(StopButton& button) + : m_button(button) + {} + ~ResetOnExit(){ + m_button.set_idle(); + } + +private: + StopButton& m_button; +}; + + + +void TournamentFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + TournamentFarmer_Descriptor::Stats& stats = env.current_stats(); + + m_stop_after_current.store(false, std::memory_order_relaxed); + STOP_AFTER_CURRENT.set_ready(); + ResetOnExit reset_button_on_exit(STOP_AFTER_CURRENT); + + /* + Preconditions: + Last Pokemon Center visited is Mesagzoa West + Sylveon only farming build - ideally with fairy tera + stand in front of tournament entry man + Ride legendary is not the solo pokemon (in case of loss) + Do not have other notifications on screen for money reading (ex. new outbreak) + + Possible improvements to make: + find prize sprites - some code is there, just disabled + find translations for tera shards + other languages: make sure "bottle cap" isn't misread as "bottle of PP Up" + */ + + for (uint32_t c = 0; c < NUM_ROUNDS; c++){ + if (m_stop_after_current.load(std::memory_order_relaxed)){ + break; + } + + env.log("Tournament loop started."); + + // Initiate dialog then mash until first battle starts + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + int ret = wait_until(env.console, context, Milliseconds(7000), { advance_detector }); + if (ret == 0){ + env.log("Dialog detected."); + }else{ + env.log("Dialog not detected."); + } + pbf_mash_button(context, BUTTON_A, 400); + context.wait_for_all_requests(); + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret_battle = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); //it takes a while to load and start + }, + { battle_menu } + ); + if (ret_battle != 0){ + env.console.log("Failed to detect battle start!", COLOR_RED); + } + context.wait_for_all_requests(); + + bool battle_lost = false; + for (uint16_t battles = 0; battles < 4; battles++){ + NormalBattleMenuWatcher battle_menu2(COLOR_YELLOW); //Next battle started + OverworldWatcher overworld(env.console, COLOR_CYAN); //Previous battle was lost + int ret_battle2 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + { battle_menu2, overworld } + ); + context.wait_for_all_requests(); + + switch (ret_battle2){ + case 0: + env.log("Detected battle menu."); + run_battle(env, context); + break; + case 1: + env.log("Detected overworld."); + battle_lost = true; + stats.losses++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + break; + default: + env.log("Failed to detect battle menu or dialog prompt!"); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect battle menu or dialog prompt!", + env.console + ); + break; + } + + //If this is the last battle in the tournament check for overworld in case player lost + if (battles == 3){ + env.log("Final battle of the tournament complete, checking for overworld/loss."); + + //Clear dialog, mash B + pbf_mash_button(context, BUTTON_B, 400); + context.wait_for_all_requests(); + + OverworldWatcher overworld2(env.console, COLOR_RED); + int ret_lost_final = wait_until( + env.console, context, + std::chrono::seconds(3), + { overworld2 } + ); + switch (ret_lost_final){ + case 0: + env.log("Final battle of the tournament lost."); + battle_lost = true; + stats.losses++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + break; + default: + env.log("Final battle of the tournament won."); + break; + } + } + + if (battle_lost){ + return_to_academy_after_loss(env, env.console, context); + break; + } + } + + //Tournament won + if (!battle_lost){ + handle_end_of_tournament(env, context); + } + + env.log("Tournament loop complete."); + + //Save the game if option is set + uint16_t num_rounds_temp = SAVE_NUM_ROUNDS; + if (num_rounds_temp != 0 && ((c + 1) % num_rounds_temp) == 0){ + env.log("Saving game."); + save_game_from_overworld(env.program_info(), env.console, context); + } + + //Break loop and finish program if money limit is hit + uint32_t earnings_temp = MONEY_LIMIT; + if (earnings_temp != 0 && stats.money >= earnings_temp){ + env.log("Money limit hit. Ending program."); + break; + } + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h index c45f20664a..b9738ff24a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer.h @@ -1,88 +1,88 @@ -/* Tournament Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TournamentFarmer_H -#define PokemonAutomation_PokemonSwSh_TournamentFarmer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/ButtonOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_TournamentPrizeTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -void return_to_academy_after_loss( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context -); - -// attempt to fly back to academy fly point from the West Mesogoza Pokecenter. Will attempt maxAttempts times. -void go_to_academy_fly_point( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context -); - -class TournamentFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TournamentFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class TournamentFarmer : public SingleSwitchProgramInstance, public ButtonListener{ -public: - ~TournamentFarmer(); - TournamentFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - virtual void on_press() override; - -private: - class StopButton : public ButtonOption{ - public: - StopButton(); - void set_idle(); - void set_ready(); - void set_pressed(); - }; - class ResetOnExit; - - StopButton STOP_AFTER_CURRENT; - SimpleIntegerOption NUM_ROUNDS; - BooleanCheckBoxOption TRY_TO_TERASTILLIZE; - SimpleIntegerOption SAVE_NUM_ROUNDS; - SimpleIntegerOption MONEY_LIMIT; - BooleanCheckBoxOption HHH_ZOROARK; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - OCR::LanguageOCROption LANGUAGE; - TournamentPrizeTable TARGET_ITEMS; - EventNotificationOption NOTIFICATION_PRIZE_MATCH; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - std::atomic m_stop_after_current; - - void check_money(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void check_prize(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void handle_end_of_tournament(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif - - - +/* Tournament Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TournamentFarmer_H +#define PokemonAutomation_PokemonSwSh_TournamentFarmer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/ButtonOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_TournamentPrizeTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +void return_to_academy_after_loss( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context +); + +// attempt to fly back to academy fly point from the West Mesogoza Pokecenter. Will attempt maxAttempts times. +void go_to_academy_fly_point( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context +); + +class TournamentFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TournamentFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class TournamentFarmer : public SingleSwitchProgramInstance, public ButtonListener{ +public: + ~TournamentFarmer(); + TournamentFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + virtual void on_press() override; + +private: + class StopButton : public ButtonOption{ + public: + StopButton(); + void set_idle(); + void set_ready(); + void set_pressed(); + }; + class ResetOnExit; + + StopButton STOP_AFTER_CURRENT; + SimpleIntegerOption NUM_ROUNDS; + BooleanCheckBoxOption TRY_TO_TERASTILLIZE; + SimpleIntegerOption SAVE_NUM_ROUNDS; + SimpleIntegerOption MONEY_LIMIT; + BooleanCheckBoxOption HHH_ZOROARK; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + OCR::LanguageOCROption LANGUAGE; + TournamentPrizeTable TARGET_ITEMS; + EventNotificationOption NOTIFICATION_PRIZE_MATCH; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + std::atomic m_stop_after_current; + + void check_money(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void check_prize(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void handle_end_of_tournament(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.cpp b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.cpp index 11a536bacc..8f986b8cbd 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.cpp @@ -1,334 +1,334 @@ -/* Tournament Farmer 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h" -#include "PokemonSV_TournamentFarmer.h" -#include "PokemonSV_TournamentFarmer2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -TournamentFarmer2_Descriptor::TournamentFarmer2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:TournamentFarmer2", - STRING_POKEMON + " SV", "Tournament Farmer 2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TournamentFarmer2.md", - "Farm the Academy Ace Tournament for money and prizes. (version 2)", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -struct TournamentFarmer2_Descriptor::Stats : public StatsTracker{ - Stats() - : tournaments(m_stats["Tournaments"]) - , battles(m_stats["Battles Fought"]) - , wins(m_stats["Wins"]) - , losses(m_stats["Losses"]) -// , money(m_stats["Money Made"]) -// , matches(m_stats["Items Matched"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Tournaments"); - m_display_order.emplace_back("Battles Fought"); - m_display_order.emplace_back("Wins"); - m_display_order.emplace_back("Losses"); -// m_display_order.emplace_back("Money Made"); -// m_display_order.emplace_back("Items Matched"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& tournaments; - std::atomic& battles; - std::atomic& wins; - std::atomic& losses; -// std::atomic& money; -// std::atomic& matches; - std::atomic& errors; -}; -std::unique_ptr TournamentFarmer2_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -TournamentFarmer2::StopButton::StopButton() - : ButtonOption( - "Stop after Current Tournament:", - "Stop after current Tournament", - 0, 16 - ) -{} -void TournamentFarmer2::StopButton::set_idle(){ - this->set_enabled(false); - this->set_text("Stop after current Tournament"); -} -void TournamentFarmer2::StopButton::set_ready(){ - this->set_enabled(true); - this->set_text("Stop after current Tournament"); -} -void TournamentFarmer2::StopButton::set_pressed(){ - this->set_enabled(false); - this->set_text("Program will stop after current tournament..."); -} - - -TournamentFarmer2::~TournamentFarmer2(){ - STOP_AFTER_CURRENT.remove_listener(*this); -} -TournamentFarmer2::TournamentFarmer2() - : NUM_ROUNDS( - "Number of Tournaments to run:", - LockMode::UNLOCK_WHILE_RUNNING, - 100, 0 - ) - , SAVE_NUM_ROUNDS( - "Save every this many tournaments:
Zero disables saving. Will save win or lose.", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 0 - ) - , BATTLE_AI(true) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_stop_after_current(false) -{ - PA_ADD_OPTION(STOP_AFTER_CURRENT); - PA_ADD_OPTION(NUM_ROUNDS); - PA_ADD_OPTION(SAVE_NUM_ROUNDS); - PA_ADD_OPTION(BATTLE_AI); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); - - STOP_AFTER_CURRENT.set_idle(); - STOP_AFTER_CURRENT.add_listener(*this); -} - -void TournamentFarmer2::on_press(){ - global_logger_tagged().log("Stop after current requested..."); - m_stop_after_current.store(true, std::memory_order_relaxed); - STOP_AFTER_CURRENT.set_pressed(); -} - - - -class TournamentFarmer2::ResetOnExit{ -public: - ResetOnExit(StopButton& button) - : m_button(button) - {} - ~ResetOnExit(){ - m_button.set_idle(); - } - -private: - StopButton& m_button; -}; - - - -void TournamentFarmer2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - TournamentFarmer2_Descriptor::Stats& stats = env.current_stats(); - - m_stop_after_current.store(false, std::memory_order_relaxed); - STOP_AFTER_CURRENT.set_ready(); - ResetOnExit reset_button_on_exit(STOP_AFTER_CURRENT); - - - for (uint32_t c = 0; c < NUM_ROUNDS; c++){ - if (m_stop_after_current.load(std::memory_order_relaxed)){ - break; - } - - env.log("Tournament loop started."); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // Initiate dialog then mash until first battle starts - { - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - int ret = wait_until(env.console, context, Milliseconds(7000), { advance_detector }); - if (ret == 0){ - env.log("Dialog detected."); - }else{ - env.log("Dialog not detected."); - } - pbf_mash_button(context, BUTTON_A, 400); - context.wait_for_all_requests(); - } - { - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); //it takes a while to load and start - }, - {battle_menu} - ); - if (ret != 0){ - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect battle start!", - env.console - ); - } - } - context.wait_for_all_requests(); - - stats.tournaments++; - env.update_stats(); - - bool battle_lost = false; - for (uint16_t battles = 0; battles < 4; battles++){ - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); // Next battle started - OverworldWatcher overworld(env.console, COLOR_CYAN); // Previous battle was lost - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - {battle_menu, overworld} - ); - context.wait_for_all_requests(); - - switch (ret){ - case 0: - env.log("Detected battle menu."); - run_singles_battle(env, env.console, context, BATTLE_AI, true); - stats.battles++; - env.update_stats(); - break; - case 1: - env.log("Detected overworld."); - battle_lost = true; - stats.losses++; - env.update_stats(); - break; - default: - env.log("Failed to detect battle menu or dialog prompt!"); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect battle menu or dialog prompt!", - env.console - ); - } - - - if (battles == 3){ - env.log("Final battle of the tournament complete, checking for overworld."); - - context.wait_for_all_requests(); - - /* - - mash B to clear dialog until it reaches the overworld. - - then it looks for the Fast travel icon - - if win: Fast Travel will be detected - - if lose: will time out. - */ - ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - {overworld} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to return to overworld after 2 minutes.", - env.console - ); - } - context.wait_for_all_requests(); - - FastTravelWatcher fast_travel(COLOR_YELLOW, env.console.overlay(), MINIMAP_AREA); - ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); - }, - {fast_travel} - ); - context.wait_for_all_requests(); - - switch (ret){ - case 0: - env.log("Detected fast travel icon."); - env.log("Final battle of the tournament won."); - break; - default: - env.log("Final battle of the tournament lost."); - battle_lost = true; - stats.losses++; - env.update_stats(); - break; - } - } - - - if (battle_lost){ - return_to_academy_after_loss(env, env.console, context); - break; - } - } - - // Tournament won - if (!battle_lost){ - stats.wins++; - env.update_stats(); - } - - env.log("Tournament loop complete."); - - //Save the game if option is set - uint16_t num_rounds_temp = SAVE_NUM_ROUNDS; - if (num_rounds_temp != 0 && ((c + 1) % num_rounds_temp) == 0){ - env.log("Saving game."); - save_game_from_overworld(env.program_info(), env.console, context); - } - - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - - - - -} -} -} +/* Tournament Farmer 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Map/PokemonSV_FastTravelDetector.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/Battles/PokemonSV_SinglesBattler.h" +#include "PokemonSV_TournamentFarmer.h" +#include "PokemonSV_TournamentFarmer2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +TournamentFarmer2_Descriptor::TournamentFarmer2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:TournamentFarmer2", + STRING_POKEMON + " SV", "Tournament Farmer 2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TournamentFarmer2.md", + "Farm the Academy Ace Tournament for money and prizes. (version 2)", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +struct TournamentFarmer2_Descriptor::Stats : public StatsTracker{ + Stats() + : tournaments(m_stats["Tournaments"]) + , battles(m_stats["Battles Fought"]) + , wins(m_stats["Wins"]) + , losses(m_stats["Losses"]) +// , money(m_stats["Money Made"]) +// , matches(m_stats["Items Matched"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Tournaments"); + m_display_order.emplace_back("Battles Fought"); + m_display_order.emplace_back("Wins"); + m_display_order.emplace_back("Losses"); +// m_display_order.emplace_back("Money Made"); +// m_display_order.emplace_back("Items Matched"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& tournaments; + std::atomic& battles; + std::atomic& wins; + std::atomic& losses; +// std::atomic& money; +// std::atomic& matches; + std::atomic& errors; +}; +std::unique_ptr TournamentFarmer2_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +TournamentFarmer2::StopButton::StopButton() + : ButtonOption( + "Stop after Current Tournament:", + "Stop after current Tournament", + 0, 16 + ) +{} +void TournamentFarmer2::StopButton::set_idle(){ + this->set_enabled(false); + this->set_text("Stop after current Tournament"); +} +void TournamentFarmer2::StopButton::set_ready(){ + this->set_enabled(true); + this->set_text("Stop after current Tournament"); +} +void TournamentFarmer2::StopButton::set_pressed(){ + this->set_enabled(false); + this->set_text("Program will stop after current tournament..."); +} + + +TournamentFarmer2::~TournamentFarmer2(){ + STOP_AFTER_CURRENT.remove_listener(*this); +} +TournamentFarmer2::TournamentFarmer2() + : NUM_ROUNDS( + "Number of Tournaments to run:", + LockMode::UNLOCK_WHILE_RUNNING, + 100, 0 + ) + , SAVE_NUM_ROUNDS( + "Save every this many tournaments:
Zero disables saving. Will save win or lose.", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 0 + ) + , BATTLE_AI(true) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_stop_after_current(false) +{ + PA_ADD_OPTION(STOP_AFTER_CURRENT); + PA_ADD_OPTION(NUM_ROUNDS); + PA_ADD_OPTION(SAVE_NUM_ROUNDS); + PA_ADD_OPTION(BATTLE_AI); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); + + STOP_AFTER_CURRENT.set_idle(); + STOP_AFTER_CURRENT.add_listener(*this); +} + +void TournamentFarmer2::on_press(){ + global_logger_tagged().log("Stop after current requested..."); + m_stop_after_current.store(true, std::memory_order_relaxed); + STOP_AFTER_CURRENT.set_pressed(); +} + + + +class TournamentFarmer2::ResetOnExit{ +public: + ResetOnExit(StopButton& button) + : m_button(button) + {} + ~ResetOnExit(){ + m_button.set_idle(); + } + +private: + StopButton& m_button; +}; + + + +void TournamentFarmer2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + TournamentFarmer2_Descriptor::Stats& stats = env.current_stats(); + + m_stop_after_current.store(false, std::memory_order_relaxed); + STOP_AFTER_CURRENT.set_ready(); + ResetOnExit reset_button_on_exit(STOP_AFTER_CURRENT); + + + for (uint32_t c = 0; c < NUM_ROUNDS; c++){ + if (m_stop_after_current.load(std::memory_order_relaxed)){ + break; + } + + env.log("Tournament loop started."); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // Initiate dialog then mash until first battle starts + { + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + int ret = wait_until(env.console, context, Milliseconds(7000), { advance_detector }); + if (ret == 0){ + env.log("Dialog detected."); + }else{ + env.log("Dialog not detected."); + } + pbf_mash_button(context, BUTTON_A, 400); + context.wait_for_all_requests(); + } + { + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); //it takes a while to load and start + }, + {battle_menu} + ); + if (ret != 0){ + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect battle start!", + env.console + ); + } + } + context.wait_for_all_requests(); + + stats.tournaments++; + env.update_stats(); + + bool battle_lost = false; + for (uint16_t battles = 0; battles < 4; battles++){ + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); // Next battle started + OverworldWatcher overworld(env.console, COLOR_CYAN); // Previous battle was lost + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + {battle_menu, overworld} + ); + context.wait_for_all_requests(); + + switch (ret){ + case 0: + env.log("Detected battle menu."); + run_singles_battle(env, env.console, context, BATTLE_AI, true); + stats.battles++; + env.update_stats(); + break; + case 1: + env.log("Detected overworld."); + battle_lost = true; + stats.losses++; + env.update_stats(); + break; + default: + env.log("Failed to detect battle menu or dialog prompt!"); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect battle menu or dialog prompt!", + env.console + ); + } + + + if (battles == 3){ + env.log("Final battle of the tournament complete, checking for overworld."); + + context.wait_for_all_requests(); + + /* + - mash B to clear dialog until it reaches the overworld. + - then it looks for the Fast travel icon + - if win: Fast Travel will be detected + - if lose: will time out. + */ + ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + {overworld} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to return to overworld after 2 minutes.", + env.console + ); + } + context.wait_for_all_requests(); + + FastTravelWatcher fast_travel(COLOR_YELLOW, env.console.overlay(), MINIMAP_AREA); + ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); + }, + {fast_travel} + ); + context.wait_for_all_requests(); + + switch (ret){ + case 0: + env.log("Detected fast travel icon."); + env.log("Final battle of the tournament won."); + break; + default: + env.log("Final battle of the tournament lost."); + battle_lost = true; + stats.losses++; + env.update_stats(); + break; + } + } + + + if (battle_lost){ + return_to_academy_after_loss(env, env.console, context); + break; + } + } + + // Tournament won + if (!battle_lost){ + stats.wins++; + env.update_stats(); + } + + env.log("Tournament loop complete."); + + //Save the game if option is set + uint16_t num_rounds_temp = SAVE_NUM_ROUNDS; + if (num_rounds_temp != 0 && ((c + 1) % num_rounds_temp) == 0){ + env.log("Saving game."); + save_game_from_overworld(env.program_info(), env.console, context); + } + + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.h b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.h index 352c4fdbf4..60ab8f80f8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Farming/PokemonSV_TournamentFarmer2.h @@ -1,63 +1,63 @@ -/* Tournament Farmer 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TournamentFarmer2_H -#define PokemonAutomation_PokemonSwSh_TournamentFarmer2_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/ButtonOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_SinglesAIOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class TournamentFarmer2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TournamentFarmer2_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class TournamentFarmer2 : public SingleSwitchProgramInstance, public ButtonListener{ -public: - ~TournamentFarmer2(); - TournamentFarmer2(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - virtual void on_press() override; - -private: - class StopButton : public ButtonOption{ - public: - StopButton(); - void set_idle(); - void set_ready(); - void set_pressed(); - }; - class ResetOnExit; - - StopButton STOP_AFTER_CURRENT; - SimpleIntegerOption NUM_ROUNDS; - SimpleIntegerOption SAVE_NUM_ROUNDS; - SinglesAIOption BATTLE_AI; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - std::atomic m_stop_after_current; -}; - -} -} -} -#endif - - - +/* Tournament Farmer 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TournamentFarmer2_H +#define PokemonAutomation_PokemonSwSh_TournamentFarmer2_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/ButtonOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_SinglesAIOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class TournamentFarmer2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TournamentFarmer2_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class TournamentFarmer2 : public SingleSwitchProgramInstance, public ButtonListener{ +public: + ~TournamentFarmer2(); + TournamentFarmer2(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + virtual void on_press() override; + +private: + class StopButton : public ButtonOption{ + public: + StopButton(); + void set_idle(); + void set_ready(); + void set_pressed(); + }; + class ResetOnExit; + + StopButton STOP_AFTER_CURRENT; + SimpleIntegerOption NUM_ROUNDS; + SimpleIntegerOption SAVE_NUM_ROUNDS; + SinglesAIOption BATTLE_AI; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + std::atomic m_stop_after_current; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.cpp b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.cpp index 2c3fce201c..02c5eb257f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.cpp @@ -1,89 +1,89 @@ -/* Fast Code Entry (Clipboard) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -//#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/CancellableScope.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_CodeEntry.h" -#include "PokemonSV_ClipboardFastCodeEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -ClipboardFastCodeEntry_Descriptor::ClipboardFastCodeEntry_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSV:ClipboardFastCodeEntry", - STRING_POKEMON + " SV", "Clipboard Fast Code Entry (C-FCE)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ClipboardFastCodeEntry.md", - "Automatically enter a 4, 6, or 8 digit link code from your clipboard.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER, - 1, 4, 1 - ) -{} - -ClipboardFastCodeEntry::ClipboardFastCodeEntry(){ - PA_ADD_OPTION(SETTINGS); -} -void ClipboardFastCodeEntry::update_active_consoles(size_t switch_count){ - SETTINGS.set_active_consoles(switch_count); -} - - -void ClipboardFastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - // Connect the controller. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_R | BUTTON_L, 5, 3); - }); - - QClipboard* clipboard = QApplication::clipboard(); -#if 0 - std::atomic cleared(false); - QMetaObject::invokeMethod(clipboard, [clipboard, &cleared, &env]{ - clipboard->clear(); - cleared.store(true, std::memory_order_release); - env.log("Clipboard cleared."); - }, Qt::QueuedConnection); - - env.log("Clearing clipboard..."); - while (!cleared.load(std::memory_order_acquire)){ - scope.throw_if_cancelled(); - } -#endif - std::string start_text = clipboard->text().toStdString(); - - while (true){ - std::string code = clipboard->text().toStdString(); - if (code != start_text && !code.empty()){ - const char* error = enter_code(env, scope, SETTINGS, code, false, false); - if (error == nullptr){ - return; - } - } - scope.wait_for(std::chrono::milliseconds(1)); - } - -} - - - - - - - - -} -} -} +/* Fast Code Entry (Clipboard) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +//#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/CancellableScope.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_CodeEntry.h" +#include "PokemonSV_ClipboardFastCodeEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +ClipboardFastCodeEntry_Descriptor::ClipboardFastCodeEntry_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSV:ClipboardFastCodeEntry", + STRING_POKEMON + " SV", "Clipboard Fast Code Entry (C-FCE)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ClipboardFastCodeEntry.md", + "Automatically enter a 4, 6, or 8 digit link code from your clipboard.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER, + 1, 4, 1 + ) +{} + +ClipboardFastCodeEntry::ClipboardFastCodeEntry(){ + PA_ADD_OPTION(SETTINGS); +} +void ClipboardFastCodeEntry::update_active_consoles(size_t switch_count){ + SETTINGS.set_active_consoles(switch_count); +} + + +void ClipboardFastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + // Connect the controller. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_R | BUTTON_L, 5, 3); + }); + + QClipboard* clipboard = QApplication::clipboard(); +#if 0 + std::atomic cleared(false); + QMetaObject::invokeMethod(clipboard, [clipboard, &cleared, &env]{ + clipboard->clear(); + cleared.store(true, std::memory_order_release); + env.log("Clipboard cleared."); + }, Qt::QueuedConnection); + + env.log("Clearing clipboard..."); + while (!cleared.load(std::memory_order_acquire)){ + scope.throw_if_cancelled(); + } +#endif + std::string start_text = clipboard->text().toStdString(); + + while (true){ + std::string code = clipboard->text().toStdString(); + if (code != start_text && !code.empty()){ + const char* error = enter_code(env, scope, SETTINGS, code, false, false); + if (error == nullptr){ + return; + } + } + scope.wait_for(std::chrono::milliseconds(1)); + } + +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h index 445eb0675c..7396d8e748 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_ClipboardFastCodeEntry.h @@ -1,42 +1,42 @@ -/* Fast Code Entry (Clipboard) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ClipboardFastCodeEntry_H -#define PokemonAutomation_PokemonSV_ClipboardFastCodeEntry_H - -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSV_CodeEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class ClipboardFastCodeEntry_Descriptor : public MultiSwitchProgramDescriptor{ -public: - ClipboardFastCodeEntry_Descriptor(); -}; - - - - -class ClipboardFastCodeEntry : public MultiSwitchProgramInstance{ -public: - ClipboardFastCodeEntry(); - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - FastCodeEntrySettingsOption SETTINGS; -}; - - - - -} -} -} -#endif +/* Fast Code Entry (Clipboard) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ClipboardFastCodeEntry_H +#define PokemonAutomation_PokemonSV_ClipboardFastCodeEntry_H + +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSV_CodeEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class ClipboardFastCodeEntry_Descriptor : public MultiSwitchProgramDescriptor{ +public: + ClipboardFastCodeEntry_Descriptor(); +}; + + + + +class ClipboardFastCodeEntry : public MultiSwitchProgramInstance{ +public: + ClipboardFastCodeEntry(); + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + FastCodeEntrySettingsOption SETTINGS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.cpp b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.cpp index afe7f9fbf1..6694693e5b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.cpp @@ -1,206 +1,206 @@ -/* Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h" -#include "PokemonSV_CodeEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -FastCodeEntryKeyboardLayout::FastCodeEntryKeyboardLayout() - : GroupOption( - "Keyboard Layouts", - LockMode::UNLOCK_WHILE_RUNNING, - EnableMode::ALWAYS_ENABLED - ) - , CONSOLE(4) -{ - CONSOLE.emplace_back("Switch 0 (Top Left):"); - CONSOLE.emplace_back("Switch 1 (Top Right):"); - CONSOLE.emplace_back("Switch 2 (Bottom Left):"); - CONSOLE.emplace_back("Switch 3 (Bottom Right):"); - PA_ADD_OPTION(CONSOLE[0]); - PA_ADD_OPTION(CONSOLE[1]); - PA_ADD_OPTION(CONSOLE[2]); - PA_ADD_OPTION(CONSOLE[3]); -} -FastCodeEntryKeyboardLayout::~FastCodeEntryKeyboardLayout() = default; - - -FastCodeEntrySettingsOption::FastCodeEntrySettingsOption() - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) -{ - PA_ADD_OPTION(SKIP_PLUS); - PA_ADD_OPTION(KEYBOARD_LAYOUTS); -} -void FastCodeEntrySettingsOption::set_active_consoles(size_t active_consoles){ - for (size_t c = 0; c < 4; c++){ - KEYBOARD_LAYOUTS.CONSOLE[c].set_visibility( - c < active_consoles ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); - } -} - - - -const char* normalize_code(std::string& normalized_code, const std::string& code, bool override_mode){ - static const std::map MAP{ - {'1', '1'}, {'I', '1'}, {'i', '1'}, - {'2', '2'}, - {'3', '3'}, - {'4', '4'}, - {'5', '5'}, - {'6', '6'}, - {'7', '7'}, - {'8', '8'}, - {'9', '9'}, - {'0', '0'}, {'O', '0'}, {'o', '0'}, - - {'Q', 'Q'}, {'q', 'Q'}, - {'W', 'W'}, {'w', 'W'}, - {'E', 'E'}, {'e', 'E'}, - {'R', 'R'}, {'r', 'R'}, - {'T', 'T'}, {'t', 'T'}, - {'Y', 'Y'}, {'y', 'Y'}, - {'U', 'U'}, {'u', 'U'}, - {'P', 'P'}, {'p', 'P'}, - - {'A', 'A'}, {'a', 'A'}, - {'S', 'S'}, {'s', 'S'}, {'Z', 'S'}, {'z', 'S'}, - {'D', 'D'}, {'d', 'D'}, - {'F', 'F'}, {'f', 'F'}, - {'G', 'G'}, {'g', 'G'}, - {'H', 'H'}, {'h', 'H'}, - {'J', 'J'}, {'j', 'J'}, - {'K', 'K'}, {'k', 'K'}, - {'L', 'L'}, {'l', 'L'}, - - {'X', 'X'}, {'x', 'X'}, - {'C', 'C'}, {'c', 'C'}, - {'V', 'V'}, {'v', 'V'}, - {'B', 'B'}, {'b', 'B'}, - {'N', 'N'}, {'n', 'N'}, - {'M', 'M'}, {'m', 'M'}, - }; - - normalized_code.clear(); - - // Prune invalid characters. - bool digits_only = true; - for (char ch : code){ - auto iter = MAP.find(ch); - if (iter == MAP.end()){ - continue; - } - ch = iter->second; - digits_only &= '0' <= ch && ch <= '9'; - normalized_code += ch; - } - - if (override_mode){ - return nullptr; - } - - switch (normalized_code.size()){ - case 4: - if (!digits_only){ - return "4-digit codes must be only digits."; - } - break; - case 6: - break; - case 8: - if (!digits_only){ - return "8-digit codes must be only digits."; - } - break; - default: - return "Invalid code length. Must be 4, 6, or 8 characters long."; - } - - return nullptr; -} - -void enter_code( - ConsoleHandle& console, ProControllerContext& context, - KeyboardLayout keyboard_layout, - const std::string& normalized_code, bool force_keyboard_mode, - bool include_plus, - bool connect_controller_press -){ - if (connect_controller_press){ - // Connect the controller. - pbf_press_button(context, BUTTON_R | BUTTON_L, 5, 3); - } - - if (force_keyboard_mode){ - FastCodeEntry::keyboard_enter_code( - console, context, keyboard_layout, - normalized_code, include_plus - ); - return; - } - - switch (normalized_code.size()){ - case 4: -// enter_digits_str(context, 4, normalized_code.c_str()); - FastCodeEntry::numberpad_enter_code(console, context, normalized_code, include_plus); - break; - case 6: - FastCodeEntry::keyboard_enter_code( - console, context, keyboard_layout, - normalized_code, include_plus - ); - break; - case 8: -// enter_digits_str(context, 8, normalized_code.c_str()); - FastCodeEntry::numberpad_enter_code(console, context, normalized_code, include_plus); - break; - } -} -const char* enter_code( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - const FastCodeEntrySettings& settings, - const std::string& code, bool force_keyboard_mode, - bool connect_controller_press -){ - std::string normalized_code; - const char* error = normalize_code(normalized_code, code, force_keyboard_mode); - if (error){ - return error; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - enter_code( - console, context, - settings.keyboard_layout[console.index()], - normalized_code, force_keyboard_mode, - !settings.skip_plus, - connect_controller_press - ); - }); - - return nullptr; -} - - - -} -} -} +/* Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_KeyboardCodeEntry.h" +#include "PokemonSV_CodeEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +FastCodeEntryKeyboardLayout::FastCodeEntryKeyboardLayout() + : GroupOption( + "Keyboard Layouts", + LockMode::UNLOCK_WHILE_RUNNING, + EnableMode::ALWAYS_ENABLED + ) + , CONSOLE(4) +{ + CONSOLE.emplace_back("Switch 0 (Top Left):"); + CONSOLE.emplace_back("Switch 1 (Top Right):"); + CONSOLE.emplace_back("Switch 2 (Bottom Left):"); + CONSOLE.emplace_back("Switch 3 (Bottom Right):"); + PA_ADD_OPTION(CONSOLE[0]); + PA_ADD_OPTION(CONSOLE[1]); + PA_ADD_OPTION(CONSOLE[2]); + PA_ADD_OPTION(CONSOLE[3]); +} +FastCodeEntryKeyboardLayout::~FastCodeEntryKeyboardLayout() = default; + + +FastCodeEntrySettingsOption::FastCodeEntrySettingsOption() + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) +{ + PA_ADD_OPTION(SKIP_PLUS); + PA_ADD_OPTION(KEYBOARD_LAYOUTS); +} +void FastCodeEntrySettingsOption::set_active_consoles(size_t active_consoles){ + for (size_t c = 0; c < 4; c++){ + KEYBOARD_LAYOUTS.CONSOLE[c].set_visibility( + c < active_consoles ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); + } +} + + + +const char* normalize_code(std::string& normalized_code, const std::string& code, bool override_mode){ + static const std::map MAP{ + {'1', '1'}, {'I', '1'}, {'i', '1'}, + {'2', '2'}, + {'3', '3'}, + {'4', '4'}, + {'5', '5'}, + {'6', '6'}, + {'7', '7'}, + {'8', '8'}, + {'9', '9'}, + {'0', '0'}, {'O', '0'}, {'o', '0'}, + + {'Q', 'Q'}, {'q', 'Q'}, + {'W', 'W'}, {'w', 'W'}, + {'E', 'E'}, {'e', 'E'}, + {'R', 'R'}, {'r', 'R'}, + {'T', 'T'}, {'t', 'T'}, + {'Y', 'Y'}, {'y', 'Y'}, + {'U', 'U'}, {'u', 'U'}, + {'P', 'P'}, {'p', 'P'}, + + {'A', 'A'}, {'a', 'A'}, + {'S', 'S'}, {'s', 'S'}, {'Z', 'S'}, {'z', 'S'}, + {'D', 'D'}, {'d', 'D'}, + {'F', 'F'}, {'f', 'F'}, + {'G', 'G'}, {'g', 'G'}, + {'H', 'H'}, {'h', 'H'}, + {'J', 'J'}, {'j', 'J'}, + {'K', 'K'}, {'k', 'K'}, + {'L', 'L'}, {'l', 'L'}, + + {'X', 'X'}, {'x', 'X'}, + {'C', 'C'}, {'c', 'C'}, + {'V', 'V'}, {'v', 'V'}, + {'B', 'B'}, {'b', 'B'}, + {'N', 'N'}, {'n', 'N'}, + {'M', 'M'}, {'m', 'M'}, + }; + + normalized_code.clear(); + + // Prune invalid characters. + bool digits_only = true; + for (char ch : code){ + auto iter = MAP.find(ch); + if (iter == MAP.end()){ + continue; + } + ch = iter->second; + digits_only &= '0' <= ch && ch <= '9'; + normalized_code += ch; + } + + if (override_mode){ + return nullptr; + } + + switch (normalized_code.size()){ + case 4: + if (!digits_only){ + return "4-digit codes must be only digits."; + } + break; + case 6: + break; + case 8: + if (!digits_only){ + return "8-digit codes must be only digits."; + } + break; + default: + return "Invalid code length. Must be 4, 6, or 8 characters long."; + } + + return nullptr; +} + +void enter_code( + ConsoleHandle& console, ProControllerContext& context, + KeyboardLayout keyboard_layout, + const std::string& normalized_code, bool force_keyboard_mode, + bool include_plus, + bool connect_controller_press +){ + if (connect_controller_press){ + // Connect the controller. + pbf_press_button(context, BUTTON_R | BUTTON_L, 5, 3); + } + + if (force_keyboard_mode){ + FastCodeEntry::keyboard_enter_code( + console, context, keyboard_layout, + normalized_code, include_plus + ); + return; + } + + switch (normalized_code.size()){ + case 4: +// enter_digits_str(context, 4, normalized_code.c_str()); + FastCodeEntry::numberpad_enter_code(console, context, normalized_code, include_plus); + break; + case 6: + FastCodeEntry::keyboard_enter_code( + console, context, keyboard_layout, + normalized_code, include_plus + ); + break; + case 8: +// enter_digits_str(context, 8, normalized_code.c_str()); + FastCodeEntry::numberpad_enter_code(console, context, normalized_code, include_plus); + break; + } +} +const char* enter_code( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + const FastCodeEntrySettings& settings, + const std::string& code, bool force_keyboard_mode, + bool connect_controller_press +){ + std::string normalized_code; + const char* error = normalize_code(normalized_code, code, force_keyboard_mode); + if (error){ + return error; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + enter_code( + console, context, + settings.keyboard_layout[console.index()], + normalized_code, force_keyboard_mode, + !settings.skip_plus, + connect_controller_press + ); + }); + + return nullptr; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h index 3f4ad8cb7c..421874fb84 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h @@ -1,85 +1,85 @@ -/* Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_CodeEntry_H -#define PokemonAutomation_PokemonSV_CodeEntry_H - -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - class CancellableScope; - class ProgramEnvironment; -namespace NintendoSwitch{ - class MultiSwitchProgramEnvironment; -namespace PokemonSV{ - - -class FastCodeEntryKeyboardLayout : public GroupOption{ -public: - FastCodeEntryKeyboardLayout(); - ~FastCodeEntryKeyboardLayout(); - -public: - FixedLimitVector CONSOLE; -}; - - -class FastCodeEntrySettingsOption : public BatchOption{ -public: - FastCodeEntrySettingsOption(); - - void set_active_consoles(size_t active_consoles); - -public: - CodeEntrySkipPlusOption SKIP_PLUS; - FastCodeEntryKeyboardLayout KEYBOARD_LAYOUTS; -}; - -struct FastCodeEntrySettings{ - bool skip_plus = false; - KeyboardLayout keyboard_layout[4]; - - FastCodeEntrySettings() = default; - FastCodeEntrySettings(const FastCodeEntrySettingsOption& settings) - : skip_plus(settings.SKIP_PLUS) - { - keyboard_layout[0] = settings.KEYBOARD_LAYOUTS.CONSOLE[0]; - keyboard_layout[1] = settings.KEYBOARD_LAYOUTS.CONSOLE[1]; - keyboard_layout[2] = settings.KEYBOARD_LAYOUTS.CONSOLE[2]; - keyboard_layout[3] = settings.KEYBOARD_LAYOUTS.CONSOLE[3]; - } -}; - - - -const char* normalize_code(std::string& normalized_code, const std::string& code, bool override_mode = false); - -void enter_code( - ConsoleHandle& console, ProControllerContext& context, - KeyboardLayout keyboard_layout, - const std::string& normalized_code, bool force_keyboard_mode, - bool include_plus, - bool connect_controller_press -); - -const char* enter_code( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - const FastCodeEntrySettings& settings, - const std::string& code, bool force_keyboard_mode, - bool connect_controller_press -); - - - - - -} -} -} -#endif +/* Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_CodeEntry_H +#define PokemonAutomation_PokemonSV_CodeEntry_H + +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + class CancellableScope; + class ProgramEnvironment; +namespace NintendoSwitch{ + class MultiSwitchProgramEnvironment; +namespace PokemonSV{ + + +class FastCodeEntryKeyboardLayout : public GroupOption{ +public: + FastCodeEntryKeyboardLayout(); + ~FastCodeEntryKeyboardLayout(); + +public: + FixedLimitVector CONSOLE; +}; + + +class FastCodeEntrySettingsOption : public BatchOption{ +public: + FastCodeEntrySettingsOption(); + + void set_active_consoles(size_t active_consoles); + +public: + CodeEntrySkipPlusOption SKIP_PLUS; + FastCodeEntryKeyboardLayout KEYBOARD_LAYOUTS; +}; + +struct FastCodeEntrySettings{ + bool skip_plus = false; + KeyboardLayout keyboard_layout[4]; + + FastCodeEntrySettings() = default; + FastCodeEntrySettings(const FastCodeEntrySettingsOption& settings) + : skip_plus(settings.SKIP_PLUS) + { + keyboard_layout[0] = settings.KEYBOARD_LAYOUTS.CONSOLE[0]; + keyboard_layout[1] = settings.KEYBOARD_LAYOUTS.CONSOLE[1]; + keyboard_layout[2] = settings.KEYBOARD_LAYOUTS.CONSOLE[2]; + keyboard_layout[3] = settings.KEYBOARD_LAYOUTS.CONSOLE[3]; + } +}; + + + +const char* normalize_code(std::string& normalized_code, const std::string& code, bool override_mode = false); + +void enter_code( + ConsoleHandle& console, ProControllerContext& context, + KeyboardLayout keyboard_layout, + const std::string& normalized_code, bool force_keyboard_mode, + bool include_plus, + bool connect_controller_press +); + +const char* enter_code( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + const FastCodeEntrySettings& settings, + const std::string& code, bool force_keyboard_mode, + bool connect_controller_press +); + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.cpp b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.cpp index 71e5fec481..bb2f4a5a10 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.cpp @@ -1,157 +1,157 @@ -/* Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV_CodeEntry.h" -#include "PokemonSV_FastCodeEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -FastCodeEntry_Descriptor::FastCodeEntry_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSV:FastCodeEntry", - STRING_POKEMON + " SV", "Fast Code Entry (FCE)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/FastCodeEntry.md", - "Quickly enter a 4, 6, or 8 digit link code.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER, - 1, 4, 1 - ) -{} - -FastCodeEntry::FastCodeEntry() - : MODE( - "Mode:", - { - {Mode::NORMAL, "normal", "Enter Code when clicking Start Program."}, - {Mode::ENTER_ON_PASTE, "on-paste", "Start the program first. Code is entered when you paste into the code box."}, - {Mode::MYSTERY_GIFT, "mystery", "Enter Mystery Gift Code when clicking Start Program."}, - }, - LockMode::LOCK_WHILE_RUNNING, - Mode::NORMAL - ) - , CODE( - "Link Code:
Unless in Mystery Gift mode, code must be 4-digit numeric or 6-digit alphanumeric. (not case sensitive)
" - "(Box is big so it's easy to land your mouse on.)", - LockMode::UNLOCK_WHILE_RUNNING, - "0123", "0123", - true - ) -{ - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(CODE); - PA_ADD_OPTION(SETTINGS); -} -void FastCodeEntry::update_active_consoles(size_t switch_count){ - SETTINGS.set_active_consoles(switch_count); -} - - - - -class FceCodeListener : public ConfigOption::Listener, public TextEditOption::FocusListener{ -public: - FceCodeListener(TextEditOption& code_box) - : m_code_box(code_box) - { - code_box.add_listener(*this); - } - ~FceCodeListener(){ - m_code_box.remove_listener(*this); - } - - virtual void on_config_value_changed(void* object) override{ - std::lock_guard lg(m_lock); - m_cv.notify_all(); - } -// virtual void focus_in() override{ -// std::lock_guard lg(m_lock); -// m_cv.notify_all(); -// } - - void run( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - const FastCodeEntrySettings& settings - ){ -// const QClipboard* clipboard = QApplication::clipboard(); - - std::unique_lock lg(m_lock); - while (true){ - std::string code = m_code_box; -// if (code.empty()){ -// code = clipboard->text().toStdString(); -// } - if (!code.empty()){ - const char* error = enter_code( - env, scope, - settings, - code, false, - false - ); - if (error == nullptr){ - return; - } - } - scope.throw_if_cancelled(); - m_cv.wait_for(lg, std::chrono::milliseconds(1)); - } - } - -private: - TextEditOption& m_code_box; - std::mutex m_lock; - std::condition_variable m_cv; -}; - - -void FastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - if (MODE == Mode::NORMAL || MODE == Mode::MYSTERY_GIFT){ - const char* error = enter_code( - env, scope, - SETTINGS, - CODE, - MODE == Mode::MYSTERY_GIFT ? true : false, - true - ); - if (MODE == Mode::NORMAL && error){ - throw UserSetupError(env.logger(), error); - } - return; - } - - // Connect the controller. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - ssf_press_button_ptv(context, BUTTON_R | BUTTON_L); - }); - - FceCodeListener listener(CODE); - listener.run(env, scope, SETTINGS); - -} - - - -} -} -} +/* Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV_CodeEntry.h" +#include "PokemonSV_FastCodeEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +FastCodeEntry_Descriptor::FastCodeEntry_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSV:FastCodeEntry", + STRING_POKEMON + " SV", "Fast Code Entry (FCE)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/FastCodeEntry.md", + "Quickly enter a 4, 6, or 8 digit link code.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER, + 1, 4, 1 + ) +{} + +FastCodeEntry::FastCodeEntry() + : MODE( + "Mode:", + { + {Mode::NORMAL, "normal", "Enter Code when clicking Start Program."}, + {Mode::ENTER_ON_PASTE, "on-paste", "Start the program first. Code is entered when you paste into the code box."}, + {Mode::MYSTERY_GIFT, "mystery", "Enter Mystery Gift Code when clicking Start Program."}, + }, + LockMode::LOCK_WHILE_RUNNING, + Mode::NORMAL + ) + , CODE( + "Link Code:
Unless in Mystery Gift mode, code must be 4-digit numeric or 6-digit alphanumeric. (not case sensitive)
" + "(Box is big so it's easy to land your mouse on.)", + LockMode::UNLOCK_WHILE_RUNNING, + "0123", "0123", + true + ) +{ + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(CODE); + PA_ADD_OPTION(SETTINGS); +} +void FastCodeEntry::update_active_consoles(size_t switch_count){ + SETTINGS.set_active_consoles(switch_count); +} + + + + +class FceCodeListener : public ConfigOption::Listener, public TextEditOption::FocusListener{ +public: + FceCodeListener(TextEditOption& code_box) + : m_code_box(code_box) + { + code_box.add_listener(*this); + } + ~FceCodeListener(){ + m_code_box.remove_listener(*this); + } + + virtual void on_config_value_changed(void* object) override{ + std::lock_guard lg(m_lock); + m_cv.notify_all(); + } +// virtual void focus_in() override{ +// std::lock_guard lg(m_lock); +// m_cv.notify_all(); +// } + + void run( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + const FastCodeEntrySettings& settings + ){ +// const QClipboard* clipboard = QApplication::clipboard(); + + std::unique_lock lg(m_lock); + while (true){ + std::string code = m_code_box; +// if (code.empty()){ +// code = clipboard->text().toStdString(); +// } + if (!code.empty()){ + const char* error = enter_code( + env, scope, + settings, + code, false, + false + ); + if (error == nullptr){ + return; + } + } + scope.throw_if_cancelled(); + m_cv.wait_for(lg, std::chrono::milliseconds(1)); + } + } + +private: + TextEditOption& m_code_box; + std::mutex m_lock; + std::condition_variable m_cv; +}; + + +void FastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + if (MODE == Mode::NORMAL || MODE == Mode::MYSTERY_GIFT){ + const char* error = enter_code( + env, scope, + SETTINGS, + CODE, + MODE == Mode::MYSTERY_GIFT ? true : false, + true + ); + if (MODE == Mode::NORMAL && error){ + throw UserSetupError(env.logger(), error); + } + return; + } + + // Connect the controller. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + ssf_press_button_ptv(context, BUTTON_R | BUTTON_L); + }); + + FceCodeListener listener(CODE); + listener.run(env, scope, SETTINGS); + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h index cbd57f278e..4c1c5746e8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_FastCodeEntry.h @@ -1,53 +1,53 @@ -/* Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_FastCodeEntry_H -#define PokemonAutomation_PokemonSV_FastCodeEntry_H - -#include "Common/Cpp/Options/TextEditOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSV_CodeEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class FastCodeEntry_Descriptor : public MultiSwitchProgramDescriptor{ -public: - FastCodeEntry_Descriptor(); -}; - - - - -class FastCodeEntry : public MultiSwitchProgramInstance{ -public: - FastCodeEntry(); - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - enum class Mode{ - NORMAL, - ENTER_ON_PASTE, - MYSTERY_GIFT, - }; - EnumDropdownOption MODE; - - TextEditOption CODE; - FastCodeEntrySettingsOption SETTINGS; - -}; - - - - -} -} -} -#endif +/* Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_FastCodeEntry_H +#define PokemonAutomation_PokemonSV_FastCodeEntry_H + +#include "Common/Cpp/Options/TextEditOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSV_CodeEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class FastCodeEntry_Descriptor : public MultiSwitchProgramDescriptor{ +public: + FastCodeEntry_Descriptor(); +}; + + + + +class FastCodeEntry : public MultiSwitchProgramInstance{ +public: + FastCodeEntry(); + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + enum class Mode{ + NORMAL, + ENTER_ON_PASTE, + MYSTERY_GIFT, + }; + EnumDropdownOption MODE; + + TextEditOption CODE; + FastCodeEntrySettingsOption SETTINGS; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp index 2f599cc6dd..757df3f2fb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.cpp @@ -1,201 +1,201 @@ -/* Video Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h" -#include "PokemonSV_CodeEntry.h" -#include "PokemonSV_VideoFastCodeEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -VideoFceSettings::VideoFceSettings() - : GroupOption("Join Settings (V-FCE)", LockMode::UNLOCK_WHILE_RUNNING) - , OCR_METHOD( - "Text Recognition Method:
" - "Each text recognition method has its own strengths and weaknesses. This option lets you choose which method to use.", - { - {VideoFceOcrMethod::RAW_OCR, "raw-ocr", "Raw OCR. No image pre-processing."}, - {VideoFceOcrMethod::BLACK_TEXT, "black-on-white", "Filter: Black Text on White Background"}, - {VideoFceOcrMethod::WHITE_TEXT, "white-on-black", "Filter: White Text on Black Background"}, - {VideoFceOcrMethod::TERA_CARD, "tera-card", "Tera Card"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - VideoFceOcrMethod::TERA_CARD - ) - , SKIP_INITIAL_CODE( - "Skip Initial Code:
" - "If there is already a code up when you start the program, skip it since it's from the last raid.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_OPTION(OCR_METHOD); - PA_ADD_OPTION(SKIP_INITIAL_CODE); -} - - - -void wait_for_video_code_and_join( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - ScreenWatchOption& screen_watcher, - VideoFceSettings& join_method, - const FastCodeEntrySettings& settings -){ - bool skip_initial = join_method.SKIP_INITIAL_CODE; - VideoSnapshot snapshot; - while (true){ - scope.throw_if_cancelled(); - VideoSnapshot current = screen_watcher.screenshot(); - -// env.log("start"); - - if (snapshot && current && - snapshot->width() == current->width() && - snapshot->height() == current->height() - ){ - double rmsd = ImageMatch::pixel_RMSD(snapshot, current); - if (rmsd < 2){ - scope.wait_for(std::chrono::milliseconds(1)); - continue; - } - } - snapshot = std::move(current); -// env.log("done new frame check"); - - if (skip_initial){ - env.log("Waiting for next screen change..."); - skip_initial = false; - continue; - } - - std::string code; - switch (join_method.OCR_METHOD){ - case VideoFceOcrMethod::RAW_OCR: - code = OCR::ocr_read(Language::English, snapshot); - env.log("OCR: " + code); - break; - case VideoFceOcrMethod::BLACK_TEXT:{ - ImageRGB32 filtered = to_blackwhite_rgb32_range(snapshot, true, 0xff000000, 0xff7f7f7f); - code = OCR::ocr_read(Language::English, filtered); - env.log("OCR: " + code); - break; - } - case VideoFceOcrMethod::WHITE_TEXT:{ - ImageRGB32 filtered = to_blackwhite_rgb32_range(snapshot, true, 0xffc0c0c0, 0xffffffff); - code = OCR::ocr_read(Language::English, filtered); - env.log("OCR: " + code); - break; - } - case VideoFceOcrMethod::TERA_CARD: - code = read_raid_code(env.logger(), env.realtime_dispatcher(), snapshot); - } - const char* error = enter_code(env, scope, settings, code, false, false); - if (error == nullptr){ - break; - }else{ - env.log(std::string("Invalid Code: ") + error, COLOR_RED); - } - } -} - - - - - -VideoFastCodeEntry_Descriptor::VideoFastCodeEntry_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSV:VideoFastCodeEntry", - STRING_POKEMON + " SV", "Video Fast Code Entry (V-FCE)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/VideoFastCodeEntry.md", - "Read a 4, 6, or 8 digit link code from someone on your screen and enter it as quickly as possible.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER, - 1, 4, 1 - ) -{} - -VideoFastCodeEntry::VideoFastCodeEntry() - : SCREEN_WATCHER("Capture Box:") - , MODE( - "Mode:", - { - {Mode::MANUAL, "manual", "Manual - Enter code when you start the program."}, - {Mode::AUTOMATIC, "auto", "Automatic - Monitor the region. Automatically enter code when it appears."}, - }, - LockMode::LOCK_WHILE_RUNNING, - Mode::MANUAL - ) - , SKIP_CONNECT_TO_CONTROLLER( - "Skip Connect to Controller:
" - "If you know your controllers are already connected, you can skip this to save 64 milliseconds. (only applies to manual mode)", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(SCREEN_WATCHER); - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(SKIP_CONNECT_TO_CONTROLLER); - PA_ADD_OPTION(JOIN_METHOD); - PA_ADD_OPTION(SETTINGS); - PA_ADD_OPTION(NOTIFICATIONS); - - // Preload the OCR data. - OCR::ensure_instances(Language::English, 6); - preload_code_templates(); -} -void VideoFastCodeEntry::update_active_consoles(size_t switch_count){ - SETTINGS.set_active_consoles(switch_count); -} - - -void VideoFastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - if (MODE == Mode::MANUAL){ - std::string code = read_raid_code(env.logger(), env.realtime_dispatcher(), SCREEN_WATCHER.screenshot()); - const char* error = enter_code(env, scope, SETTINGS, code, false, !SKIP_CONNECT_TO_CONTROLLER); - if (error){ - env.log("No valid code found: " + std::string(error), COLOR_RED); - } - return; - } - - // Connect the controller. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_PLUS, 5, 3); - }); - - // Preload 6 threads to OCR the code. - env.realtime_dispatcher().ensure_threads(6); - - wait_for_video_code_and_join(env, scope, SCREEN_WATCHER, JOIN_METHOD, SETTINGS); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Video Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCodeReader.h" +#include "PokemonSV_CodeEntry.h" +#include "PokemonSV_VideoFastCodeEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +VideoFceSettings::VideoFceSettings() + : GroupOption("Join Settings (V-FCE)", LockMode::UNLOCK_WHILE_RUNNING) + , OCR_METHOD( + "Text Recognition Method:
" + "Each text recognition method has its own strengths and weaknesses. This option lets you choose which method to use.", + { + {VideoFceOcrMethod::RAW_OCR, "raw-ocr", "Raw OCR. No image pre-processing."}, + {VideoFceOcrMethod::BLACK_TEXT, "black-on-white", "Filter: Black Text on White Background"}, + {VideoFceOcrMethod::WHITE_TEXT, "white-on-black", "Filter: White Text on Black Background"}, + {VideoFceOcrMethod::TERA_CARD, "tera-card", "Tera Card"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + VideoFceOcrMethod::TERA_CARD + ) + , SKIP_INITIAL_CODE( + "Skip Initial Code:
" + "If there is already a code up when you start the program, skip it since it's from the last raid.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_OPTION(OCR_METHOD); + PA_ADD_OPTION(SKIP_INITIAL_CODE); +} + + + +void wait_for_video_code_and_join( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + ScreenWatchOption& screen_watcher, + VideoFceSettings& join_method, + const FastCodeEntrySettings& settings +){ + bool skip_initial = join_method.SKIP_INITIAL_CODE; + VideoSnapshot snapshot; + while (true){ + scope.throw_if_cancelled(); + VideoSnapshot current = screen_watcher.screenshot(); + +// env.log("start"); + + if (snapshot && current && + snapshot->width() == current->width() && + snapshot->height() == current->height() + ){ + double rmsd = ImageMatch::pixel_RMSD(snapshot, current); + if (rmsd < 2){ + scope.wait_for(std::chrono::milliseconds(1)); + continue; + } + } + snapshot = std::move(current); +// env.log("done new frame check"); + + if (skip_initial){ + env.log("Waiting for next screen change..."); + skip_initial = false; + continue; + } + + std::string code; + switch (join_method.OCR_METHOD){ + case VideoFceOcrMethod::RAW_OCR: + code = OCR::ocr_read(Language::English, snapshot); + env.log("OCR: " + code); + break; + case VideoFceOcrMethod::BLACK_TEXT:{ + ImageRGB32 filtered = to_blackwhite_rgb32_range(snapshot, true, 0xff000000, 0xff7f7f7f); + code = OCR::ocr_read(Language::English, filtered); + env.log("OCR: " + code); + break; + } + case VideoFceOcrMethod::WHITE_TEXT:{ + ImageRGB32 filtered = to_blackwhite_rgb32_range(snapshot, true, 0xffc0c0c0, 0xffffffff); + code = OCR::ocr_read(Language::English, filtered); + env.log("OCR: " + code); + break; + } + case VideoFceOcrMethod::TERA_CARD: + code = read_raid_code(env.logger(), env.realtime_dispatcher(), snapshot); + } + const char* error = enter_code(env, scope, settings, code, false, false); + if (error == nullptr){ + break; + }else{ + env.log(std::string("Invalid Code: ") + error, COLOR_RED); + } + } +} + + + + + +VideoFastCodeEntry_Descriptor::VideoFastCodeEntry_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSV:VideoFastCodeEntry", + STRING_POKEMON + " SV", "Video Fast Code Entry (V-FCE)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/VideoFastCodeEntry.md", + "Read a 4, 6, or 8 digit link code from someone on your screen and enter it as quickly as possible.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER, + 1, 4, 1 + ) +{} + +VideoFastCodeEntry::VideoFastCodeEntry() + : SCREEN_WATCHER("Capture Box:") + , MODE( + "Mode:", + { + {Mode::MANUAL, "manual", "Manual - Enter code when you start the program."}, + {Mode::AUTOMATIC, "auto", "Automatic - Monitor the region. Automatically enter code when it appears."}, + }, + LockMode::LOCK_WHILE_RUNNING, + Mode::MANUAL + ) + , SKIP_CONNECT_TO_CONTROLLER( + "Skip Connect to Controller:
" + "If you know your controllers are already connected, you can skip this to save 64 milliseconds. (only applies to manual mode)", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(SCREEN_WATCHER); + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(SKIP_CONNECT_TO_CONTROLLER); + PA_ADD_OPTION(JOIN_METHOD); + PA_ADD_OPTION(SETTINGS); + PA_ADD_OPTION(NOTIFICATIONS); + + // Preload the OCR data. + OCR::ensure_instances(Language::English, 6); + preload_code_templates(); +} +void VideoFastCodeEntry::update_active_consoles(size_t switch_count){ + SETTINGS.set_active_consoles(switch_count); +} + + +void VideoFastCodeEntry::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + if (MODE == Mode::MANUAL){ + std::string code = read_raid_code(env.logger(), env.realtime_dispatcher(), SCREEN_WATCHER.screenshot()); + const char* error = enter_code(env, scope, SETTINGS, code, false, !SKIP_CONNECT_TO_CONTROLLER); + if (error){ + env.log("No valid code found: " + std::string(error), COLOR_RED); + } + return; + } + + // Connect the controller. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_PLUS, 5, 3); + }); + + // Preload 6 threads to OCR the code. + env.realtime_dispatcher().ensure_threads(6); + + wait_for_video_code_and_join(env, scope, SCREEN_WATCHER, JOIN_METHOD, SETTINGS); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h index 5964675523..bd33a10df0 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h +++ b/SerialPrograms/Source/PokemonSV/Programs/FastCodeEntry/PokemonSV_VideoFastCodeEntry.h @@ -1,83 +1,83 @@ -/* Video Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_VideoFastCodeEntry_H -#define PokemonAutomation_PokemonSV_VideoFastCodeEntry_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/ScreenWatchOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSV_CodeEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum VideoFceOcrMethod{ - RAW_OCR, - BLACK_TEXT, - WHITE_TEXT, - TERA_CARD, -}; -class VideoFceSettings : public GroupOption{ -public: - VideoFceSettings(); - -public: - EnumDropdownOption OCR_METHOD; - BooleanCheckBoxOption SKIP_INITIAL_CODE; -}; - -void wait_for_video_code_and_join( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - ScreenWatchOption& screen_watcher, - VideoFceSettings& join_method, - const FastCodeEntrySettings& settings -); - - - - - -class VideoFastCodeEntry_Descriptor : public MultiSwitchProgramDescriptor{ -public: - VideoFastCodeEntry_Descriptor(); -}; - - -class VideoFastCodeEntry : public MultiSwitchProgramInstance{ -public: - VideoFastCodeEntry(); - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - ScreenWatchOption SCREEN_WATCHER; - - enum class Mode{ - MANUAL, - AUTOMATIC, - }; - EnumDropdownOption MODE; - - BooleanCheckBoxOption SKIP_CONNECT_TO_CONTROLLER; - - VideoFceSettings JOIN_METHOD; - - FastCodeEntrySettingsOption SETTINGS; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Video Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_VideoFastCodeEntry_H +#define PokemonAutomation_PokemonSV_VideoFastCodeEntry_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/ScreenWatchOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSV_CodeEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum VideoFceOcrMethod{ + RAW_OCR, + BLACK_TEXT, + WHITE_TEXT, + TERA_CARD, +}; +class VideoFceSettings : public GroupOption{ +public: + VideoFceSettings(); + +public: + EnumDropdownOption OCR_METHOD; + BooleanCheckBoxOption SKIP_INITIAL_CODE; +}; + +void wait_for_video_code_and_join( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + ScreenWatchOption& screen_watcher, + VideoFceSettings& join_method, + const FastCodeEntrySettings& settings +); + + + + + +class VideoFastCodeEntry_Descriptor : public MultiSwitchProgramDescriptor{ +public: + VideoFastCodeEntry_Descriptor(); +}; + + +class VideoFastCodeEntry : public MultiSwitchProgramInstance{ +public: + VideoFastCodeEntry(); + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + ScreenWatchOption SCREEN_WATCHER; + + enum class Mode{ + MANUAL, + AUTOMATIC, + }; + EnumDropdownOption MODE; + + BooleanCheckBoxOption SKIP_CONNECT_TO_CONTROLLER; + + VideoFceSettings JOIN_METHOD; + + FastCodeEntrySettingsOption SETTINGS; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.cpp b/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.cpp index 474e7b6a3c..55184bad1a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.cpp @@ -1,211 +1,211 @@ -/* Three-Segment Dudunsparce Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_ThreeSegmentDudunsparceFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -ThreeSegmentDudunsparceFinder_Descriptor::ThreeSegmentDudunsparceFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:ThreeSegmentDudunsparceFinder", - STRING_POKEMON + " SV", "Three-Segment Dudunsparce Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ThreeSegmentDudunsparceFinder.md", - "Check whether a box of Dunsparce contain at least one that evolves into Three-Segment Dudunsparce.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ThreeSegmentDudunsparceFinder_Descriptor::Stats : public StatsTracker{ - Stats() - : m_attempts(m_stats["Attempts"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Attempts"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_attempts; - std::atomic& m_errors; -}; -std::unique_ptr ThreeSegmentDudunsparceFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ThreeSegmentDudunsparceFinder::ThreeSegmentDudunsparceFinder() - : GO_HOME_WHEN_DONE(false) - , HAS_CLONE_RIDE_POKEMON( - "Cloned Ride Legendary 2nd in Party:
" - "Ride legendary cannot be cloned after patch 1.0.1. To preserve the existing clone while hatching eggs, " - "place it as second in party before starting the program.
" - "The program will skip the first row of eggs in the box as a result.", - LockMode::LOCK_WHILE_RUNNING, - false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(HAS_CLONE_RIDE_POKEMON); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void ThreeSegmentDudunsparceFinder::check_one_column( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - uint8_t column_index -){ - enter_box_system_from_overworld(env.program_info(), env.console, context); - const uint8_t expected_empty_slots_in_party = HAS_CLONE_RIDE_POKEMON ? 4 : 5; - if (check_empty_slots_in_party(env.program_info(), env.console, context) != expected_empty_slots_in_party){ - throw_and_log( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Your party should have " + std::to_string(expected_empty_slots_in_party) + " " + STRING_POKEMON + ".", - env.console - ); - } - - load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_FATAL, column_index, HAS_CLONE_RIDE_POKEMON); - const int empty_party_slots = check_empty_slots_in_party(env.program_info(), env.console, context); - if (empty_party_slots == 5){ - env.log("Empty column"); - env.console.overlay().add_log("Empty column"); - return; - } - const int num_pokemon_in_party = 6 - empty_party_slots; - const int menu_index = -1; - // go to bag from box system - enter_menu_from_box_system(env.program_info(), env.console, context, menu_index); - enter_bag_from_menu(env.program_info(), env.console, context); - // move cursor to the "Other Items" tab - for (size_t c = 0; c < 4; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - } - context.wait_for_all_requests(); - // move to candies: - - // Exp M: 3k exp points. from Tera Raid Battles (2★, 3★, 4★) - // Exp L: 10k exp points. from Tera Raid Battles (4★, 5★, 6★, 7★) - // Exp XL: 30k exp points. from Tera Raid Battles (5★, 6★, 7★) - - // - 3 exp L to go to lv 31 from lv 1 - // - 4 Exp L to go to lv 34 from lv 1 - // - 11 exp M to go to lv 32 from lv 1 - // - 1 exp M to go from lv 32 to lv 33 - - // so total 12 exp M per dunsparce. 12 * 30 = 360 exp M - // or 3 expl L + 2 exp M per dunsparce. 90 exp M and 60 exp M - // or 1 exp XL + 2 exp M per dunsparce. 30 exp XL and 60 exp M - - // go down 5 to go to candy XL - for (size_t c = 0; c < 5; c++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - } - // press A to bring up sub menu: "Use this item", "Give to Pokemon", "Cancel" - pbf_press_button(context, BUTTON_A, 20, 105); - // press A again to select "Use this item" - pbf_press_button(context, BUTTON_A, 20, 105); - // now the cursor is on the first pokemon - const int starting_pokemon_in_party = HAS_CLONE_RIDE_POKEMON ? 2 : 1; - for (int i_pokemon = starting_pokemon_in_party; i_pokemon < num_pokemon_in_party; i_pokemon++){ - // go down to the target pokemon - for (int c = 0; c < i_pokemon; c++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - } - // select the pokemon. This will open up the item count "x1" - pbf_press_button(context, BUTTON_A, 20, 105); - // press A again to apply the x1 candy XL to the pokemon - pbf_press_button(context, BUTTON_A, 20, 105); - // wait for some more time to let the level up animation finish - pbf_wait(context, Seconds(1)); - // press A to clear the "dudunsparce grew up to lv 31" message box - pbf_press_button(context, BUTTON_A, 20, 105); - } - - // leave bag and move to menu, enter the first dunsparce's sub-menu - enter_menu_from_bag(env.program_info(), env.console, context, starting_pokemon_in_party, MenuSide::LEFT); - // press A again to go into pokemon status summary screen - pbf_press_button(context, BUTTON_A, 20, 105); - // wait until we are in pokemon status summary screen - PokemonSummaryWatcher summary_watcher; - int ret = wait_until( - env.console, context, - Seconds(3), - {summary_watcher} - ); - if (ret < 0){ - throw_and_log( - env.console, ErrorReport::NO_ERROR_REPORT, - "ThreeSegmentDudunsparceFinder::check_one_column(): No pokemon status summary screen found.", - env.console - ); - } - // move to the moves screen - pbf_press_dpad(context, DPAD_RIGHT, 20, 105); - - for (int i_pokemon = starting_pokemon_in_party; i_pokemon < num_pokemon_in_party; i_pokemon++){ - // press A to open submenu "Remember moves", "Forget a move", "Use TMs to learn moves", "Quit" - pbf_press_button(context, BUTTON_A, 20, 105); - // press A to select "Remember moves" - pbf_press_button(context, BUTTON_A, 20, 105); - // wait until Remember Move list to appear - // XXX - } -} - -void ThreeSegmentDudunsparceFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - ThreeSegmentDudunsparceFinder_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 100); - - try{ - for(uint8_t i = 0; i < 6; i++){ - check_one_column(env, context, i); - } - } catch(OperationFailedException&){ - stats.m_errors++; - env.update_stats(); - throw; - } - - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Three-Segment Dudunsparce Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_ThreeSegmentDudunsparceFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +ThreeSegmentDudunsparceFinder_Descriptor::ThreeSegmentDudunsparceFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:ThreeSegmentDudunsparceFinder", + STRING_POKEMON + " SV", "Three-Segment Dudunsparce Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ThreeSegmentDudunsparceFinder.md", + "Check whether a box of Dunsparce contain at least one that evolves into Three-Segment Dudunsparce.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ThreeSegmentDudunsparceFinder_Descriptor::Stats : public StatsTracker{ + Stats() + : m_attempts(m_stats["Attempts"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Attempts"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_attempts; + std::atomic& m_errors; +}; +std::unique_ptr ThreeSegmentDudunsparceFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ThreeSegmentDudunsparceFinder::ThreeSegmentDudunsparceFinder() + : GO_HOME_WHEN_DONE(false) + , HAS_CLONE_RIDE_POKEMON( + "Cloned Ride Legendary 2nd in Party:
" + "Ride legendary cannot be cloned after patch 1.0.1. To preserve the existing clone while hatching eggs, " + "place it as second in party before starting the program.
" + "The program will skip the first row of eggs in the box as a result.", + LockMode::LOCK_WHILE_RUNNING, + false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(HAS_CLONE_RIDE_POKEMON); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void ThreeSegmentDudunsparceFinder::check_one_column( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + uint8_t column_index +){ + enter_box_system_from_overworld(env.program_info(), env.console, context); + const uint8_t expected_empty_slots_in_party = HAS_CLONE_RIDE_POKEMON ? 4 : 5; + if (check_empty_slots_in_party(env.program_info(), env.console, context) != expected_empty_slots_in_party){ + throw_and_log( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Your party should have " + std::to_string(expected_empty_slots_in_party) + " " + STRING_POKEMON + ".", + env.console + ); + } + + load_one_column_to_party(env, env.console, context, NOTIFICATION_ERROR_FATAL, column_index, HAS_CLONE_RIDE_POKEMON); + const int empty_party_slots = check_empty_slots_in_party(env.program_info(), env.console, context); + if (empty_party_slots == 5){ + env.log("Empty column"); + env.console.overlay().add_log("Empty column"); + return; + } + const int num_pokemon_in_party = 6 - empty_party_slots; + const int menu_index = -1; + // go to bag from box system + enter_menu_from_box_system(env.program_info(), env.console, context, menu_index); + enter_bag_from_menu(env.program_info(), env.console, context); + // move cursor to the "Other Items" tab + for (size_t c = 0; c < 4; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + } + context.wait_for_all_requests(); + // move to candies: + + // Exp M: 3k exp points. from Tera Raid Battles (2★, 3★, 4★) + // Exp L: 10k exp points. from Tera Raid Battles (4★, 5★, 6★, 7★) + // Exp XL: 30k exp points. from Tera Raid Battles (5★, 6★, 7★) + + // - 3 exp L to go to lv 31 from lv 1 + // - 4 Exp L to go to lv 34 from lv 1 + // - 11 exp M to go to lv 32 from lv 1 + // - 1 exp M to go from lv 32 to lv 33 + + // so total 12 exp M per dunsparce. 12 * 30 = 360 exp M + // or 3 expl L + 2 exp M per dunsparce. 90 exp M and 60 exp M + // or 1 exp XL + 2 exp M per dunsparce. 30 exp XL and 60 exp M + + // go down 5 to go to candy XL + for (size_t c = 0; c < 5; c++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + } + // press A to bring up sub menu: "Use this item", "Give to Pokemon", "Cancel" + pbf_press_button(context, BUTTON_A, 20, 105); + // press A again to select "Use this item" + pbf_press_button(context, BUTTON_A, 20, 105); + // now the cursor is on the first pokemon + const int starting_pokemon_in_party = HAS_CLONE_RIDE_POKEMON ? 2 : 1; + for (int i_pokemon = starting_pokemon_in_party; i_pokemon < num_pokemon_in_party; i_pokemon++){ + // go down to the target pokemon + for (int c = 0; c < i_pokemon; c++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + } + // select the pokemon. This will open up the item count "x1" + pbf_press_button(context, BUTTON_A, 20, 105); + // press A again to apply the x1 candy XL to the pokemon + pbf_press_button(context, BUTTON_A, 20, 105); + // wait for some more time to let the level up animation finish + pbf_wait(context, Seconds(1)); + // press A to clear the "dudunsparce grew up to lv 31" message box + pbf_press_button(context, BUTTON_A, 20, 105); + } + + // leave bag and move to menu, enter the first dunsparce's sub-menu + enter_menu_from_bag(env.program_info(), env.console, context, starting_pokemon_in_party, MenuSide::LEFT); + // press A again to go into pokemon status summary screen + pbf_press_button(context, BUTTON_A, 20, 105); + // wait until we are in pokemon status summary screen + PokemonSummaryWatcher summary_watcher; + int ret = wait_until( + env.console, context, + Seconds(3), + {summary_watcher} + ); + if (ret < 0){ + throw_and_log( + env.console, ErrorReport::NO_ERROR_REPORT, + "ThreeSegmentDudunsparceFinder::check_one_column(): No pokemon status summary screen found.", + env.console + ); + } + // move to the moves screen + pbf_press_dpad(context, DPAD_RIGHT, 20, 105); + + for (int i_pokemon = starting_pokemon_in_party; i_pokemon < num_pokemon_in_party; i_pokemon++){ + // press A to open submenu "Remember moves", "Forget a move", "Use TMs to learn moves", "Quit" + pbf_press_button(context, BUTTON_A, 20, 105); + // press A to select "Remember moves" + pbf_press_button(context, BUTTON_A, 20, 105); + // wait until Remember Move list to appear + // XXX + } +} + +void ThreeSegmentDudunsparceFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + ThreeSegmentDudunsparceFinder_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 100); + + try{ + for(uint8_t i = 0; i < 6; i++){ + check_one_column(env, context, i); + } + } catch(OperationFailedException&){ + stats.m_errors++; + env.update_stats(); + throw; + } + + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h b/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h index 86f6bacef8..a82a1bd60b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h +++ b/SerialPrograms/Source/PokemonSV/Programs/FormHunting/PokemonSV_ThreeSegmentDudunsparceFinder.h @@ -1,59 +1,59 @@ -/* Three-Segment Dudunsparce Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ThreeSegmentDudunsparceFinder_H -#define PokemonAutomation_PokemonSV_ThreeSegmentDudunsparceFinder_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class ThreeSegmentDudunsparceFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ThreeSegmentDudunsparceFinder_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ThreeSegmentDudunsparceFinder : public SingleSwitchProgramInstance{ -public: - ThreeSegmentDudunsparceFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void check_one_column( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - uint8_t column_index - ); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - BooleanCheckBoxOption HAS_CLONE_RIDE_POKEMON; - - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Three-Segment Dudunsparce Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ThreeSegmentDudunsparceFinder_H +#define PokemonAutomation_PokemonSV_ThreeSegmentDudunsparceFinder_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class ThreeSegmentDudunsparceFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ThreeSegmentDudunsparceFinder_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ThreeSegmentDudunsparceFinder : public SingleSwitchProgramInstance{ +public: + ThreeSegmentDudunsparceFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void check_one_column( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + uint8_t column_index + ); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + BooleanCheckBoxOption HAS_CLONE_RIDE_POKEMON; + + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.cpp b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.cpp index d0af5128d2..80e51f45bb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.cpp @@ -1,116 +1,116 @@ -/* Autonomous Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV_AutonomousBallThrower.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:AutonomousBallThrower", - STRING_POKEMON + " SV", "Autonomous Ball Thrower", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutonomousBallThrower.md", - "Repeatedly throw a ball until you catch the pokemon.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ - Stats() - : m_balls(m_stats["Balls Thrown"]) - { - m_display_order.emplace_back("Balls Thrown"); - } - std::atomic& m_balls; -}; -std::unique_ptr AutonomousBallThrower_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -AutonomousBallThrower::AutonomousBallThrower() - : LANGUAGE( - "Game Language:", - PokemonNameReader::instance().languages(), - LockMode::UNLOCK_WHILE_RUNNING - ) - , BALL_SELECT( - "Ball Select:", - LockMode::UNLOCK_WHILE_RUNNING, - "poke-ball" - ) - , USE_FIRST_MOVE_IF_CANNOT_THROW_BALL( - "Use 1st Move if Cannot Throw Ball:
" - "If you can't throw a ball because the opponent is semi-invulnerable, use the 1st move instead. " - "Therefore, your first move should be non-damaging to avoid killing the wild " + STRING_POKEMON + ".", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, true) - , NOTIFICATION_CATCH_FAILED("Catch Failed", true, true) - , NOTIFICATIONS({ - &NOTIFICATION_CATCH_SUCCESS, - &NOTIFICATION_CATCH_FAILED, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(USE_FIRST_MOVE_IF_CANNOT_THROW_BALL); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void AutonomousBallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - AutonomousBallThrower_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_LCLICK, 10, 0); - - CatchResults results = basic_catcher( - env.console, context, LANGUAGE, - BALL_SELECT.slug(), 999, - USE_FIRST_MOVE_IF_CANNOT_THROW_BALL, - [&]{ - stats.m_balls++; - env.update_stats(); - } - ); - env.update_stats(); - - send_catch_notification( - env, - NOTIFICATION_CATCH_SUCCESS, - NOTIFICATION_CATCH_FAILED, - nullptr, - BALL_SELECT.slug(), - results.balls_used, - results.result - ); -} - - - -} -} -} +/* Autonomous Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV_AutonomousBallThrower.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:AutonomousBallThrower", + STRING_POKEMON + " SV", "Autonomous Ball Thrower", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutonomousBallThrower.md", + "Repeatedly throw a ball until you catch the pokemon.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ + Stats() + : m_balls(m_stats["Balls Thrown"]) + { + m_display_order.emplace_back("Balls Thrown"); + } + std::atomic& m_balls; +}; +std::unique_ptr AutonomousBallThrower_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +AutonomousBallThrower::AutonomousBallThrower() + : LANGUAGE( + "Game Language:", + PokemonNameReader::instance().languages(), + LockMode::UNLOCK_WHILE_RUNNING + ) + , BALL_SELECT( + "Ball Select:", + LockMode::UNLOCK_WHILE_RUNNING, + "poke-ball" + ) + , USE_FIRST_MOVE_IF_CANNOT_THROW_BALL( + "Use 1st Move if Cannot Throw Ball:
" + "If you can't throw a ball because the opponent is semi-invulnerable, use the 1st move instead. " + "Therefore, your first move should be non-damaging to avoid killing the wild " + STRING_POKEMON + ".", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, true) + , NOTIFICATION_CATCH_FAILED("Catch Failed", true, true) + , NOTIFICATIONS({ + &NOTIFICATION_CATCH_SUCCESS, + &NOTIFICATION_CATCH_FAILED, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(USE_FIRST_MOVE_IF_CANNOT_THROW_BALL); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void AutonomousBallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + AutonomousBallThrower_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_LCLICK, 10, 0); + + CatchResults results = basic_catcher( + env.console, context, LANGUAGE, + BALL_SELECT.slug(), 999, + USE_FIRST_MOVE_IF_CANNOT_THROW_BALL, + [&]{ + stats.m_balls++; + env.update_stats(); + } + ); + env.update_stats(); + + send_catch_notification( + env, + NOTIFICATION_CATCH_SUCCESS, + NOTIFICATION_CATCH_FAILED, + nullptr, + BALL_SELECT.slug(), + results.balls_used, + results.result + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.h b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.h index a4610290fc..f033d3e7a6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.h +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_AutonomousBallThrower.h @@ -1,56 +1,56 @@ -/* Autonomous Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutonomousBallThrower_H -#define PokemonAutomation_PokemonSV_AutonomousBallThrower_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AutonomousBallThrower_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutonomousBallThrower_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - - -class AutonomousBallThrower : public SingleSwitchProgramInstance{ -public: - AutonomousBallThrower(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: -// void throw_ball(VideoStream& stream, ProControllerContext& context); - - OCR::LanguageOCROption LANGUAGE; - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - BooleanCheckBoxOption USE_FIRST_MOVE_IF_CANNOT_THROW_BALL; - - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Autonomous Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutonomousBallThrower_H +#define PokemonAutomation_PokemonSV_AutonomousBallThrower_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AutonomousBallThrower_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutonomousBallThrower_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + + +class AutonomousBallThrower : public SingleSwitchProgramInstance{ +public: + AutonomousBallThrower(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: +// void throw_ball(VideoStream& stream, ProControllerContext& context); + + OCR::LanguageOCROption LANGUAGE; + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + BooleanCheckBoxOption USE_FIRST_MOVE_IF_CANNOT_THROW_BALL; + + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.cpp b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.cpp index 3e8e75f89a..a41e84a449 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.cpp @@ -1,239 +1,239 @@ -/* Clothing Buyer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/PokemonSV_ClothingTopDetector.h" -#include "PokemonSV_ClothingBuyer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -ClothingBuyer_Descriptor::ClothingBuyer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:ClothingBuyer", - STRING_POKEMON + " SV", "Clothing Buyer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ClothingBuyer.md", - "Buy all the clothing in a store.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -ClothingBuyer::ClothingBuyer() - : USE_LP( - "Use LP to purchase:", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , WEAR_NEW_CLOTHES( - "Wear new clothing after purchase:", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , NUM_CATEGORY( - "Number of Categories:
The number of categories of clothing the shop has.", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 5 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(USE_LP); - PA_ADD_OPTION(WEAR_NEW_CLOTHES); - PA_ADD_OPTION(NUM_CATEGORY); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void ClothingBuyer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - /* - * Start at the top of the first category in clothing shop menu. - * Program will buy everything in num of categories. - * Can set num category higher or lower and will still work. - * Lower - can buy only one category by setting to one and starting program on desired clothes type - * Higher - will take longer to finish as it will repeat an already purchased category - * Stop conditions: Out of money/lp, hit catogory count - */ - - uint8_t category_rotation_count = 0; - bool finish_program = false; - while (category_rotation_count < NUM_CATEGORY){ - pbf_press_button(context, BUTTON_A, 20, 100); - - AdvanceDialogWatcher already_purchased(COLOR_RED); - PromptDialogWatcher buy_yes_no(COLOR_CYAN); - PromptDialogWatcher hairstyle_purchase_prompt(COLOR_RED); - int retP = 0; - bool incompatible_hairstyle = false; - - int ret = wait_until( - env.console, context, - std::chrono::seconds(10), - { already_purchased, buy_yes_no } - ); - switch (ret){ - case 0: - env.log("Item already purchased or incompatible hairstyle."); - pbf_press_button(context, BUTTON_A, 10, 100); - - retP = wait_until( - env.console, context, - std::chrono::seconds(2), - { hairstyle_purchase_prompt } - ); - if (retP != 0){ - env.log("Item already purchased."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Item already purchased." - ); - break; - } - env.log("Incompatible hairstyle. Proceed to purchase."); - incompatible_hairstyle = true; - case 1: - { - PromptDialogWatcher wear_yes_no(COLOR_CYAN); - AdvanceDialogWatcher afford_yes_no(COLOR_RED); - AdvanceDialogWatcher afford_yes_no_hairstyle(COLOR_RED); - int retHairstyle; - - env.log("Detected purchase prompt."); - - if (USE_LP){ - env.log("Using LP."); - pbf_press_dpad(context, DPAD_DOWN, 10, 100); - } - env.log("Purchasing."); - //Purchase, then wait a bit more for wear prompt detector. - pbf_press_button(context, BUTTON_A, 10, 100); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - int retWear = wait_until( - env.console, context, - std::chrono::seconds(10), - { wear_yes_no, afford_yes_no } - ); - switch (retWear){ - case 0: - if (!WEAR_NEW_CLOTHES){ - env.log("Do not wear new clothes."); - pbf_press_dpad(context, DPAD_DOWN, 10, 100); - }else{ - env.log("Wear new clothes."); - } - pbf_press_button(context, BUTTON_A, 10, 100); - env.log("Clothing purchased. Selecting next item."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Clothing purchased. Selecting next item." - ); - break; - case 1: - if (!incompatible_hairstyle){ - env.log("Out of Cash/LP."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Out of Cash/LP." - ); - finish_program = true; - }else{ - pbf_press_button(context, BUTTON_A, 10, 100); - retHairstyle = wait_until( - env.console, context, - std::chrono::seconds(2), - { afford_yes_no_hairstyle } - ); - if (retHairstyle == 0){ - env.log("Out of Cash/LP."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Out of Cash/LP." - ); - finish_program = true; - } - } - break; - default: - env.log("Error looking for wear prompt."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Error looking for wear prompt.", - env.console - ); - break; - } - break; - } - default: - env.log("Error looking for purchase prompt."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Error looking for purchase prompt.", - env.console - ); - break; - } - //Out of cash/LP, stop. - if (finish_program){ - break; - } - - env.log("Moving on to next item."); - pbf_press_dpad(context, DPAD_DOWN, 10, 100); - //Wait to load a bit for next item - pbf_wait(context, 100); - context.wait_for_all_requests(); - - ClothingTopWatcher top_item(COLOR_YELLOW); - - int retTop = wait_until( - env.console, context, - std::chrono::seconds(1), - { top_item } - ); - if (retTop == 0){ - env.log("Reached top of category."); - if (NUM_CATEGORY > 1){ - env.log("Category rotation set. Moving to next category."); - pbf_press_dpad(context, DPAD_RIGHT, 10, 100); - pbf_wait(context, 100); - context.wait_for_all_requests(); - category_rotation_count++; - }else{ - env.log("No category rotation. Ending program."); - break; - } - } - - } - env.log("Category num hit. Ending program."); - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} - +/* Clothing Buyer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/PokemonSV_ClothingTopDetector.h" +#include "PokemonSV_ClothingBuyer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +ClothingBuyer_Descriptor::ClothingBuyer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:ClothingBuyer", + STRING_POKEMON + " SV", "Clothing Buyer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ClothingBuyer.md", + "Buy all the clothing in a store.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +ClothingBuyer::ClothingBuyer() + : USE_LP( + "Use LP to purchase:", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , WEAR_NEW_CLOTHES( + "Wear new clothing after purchase:", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , NUM_CATEGORY( + "Number of Categories:
The number of categories of clothing the shop has.", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 5 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(USE_LP); + PA_ADD_OPTION(WEAR_NEW_CLOTHES); + PA_ADD_OPTION(NUM_CATEGORY); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void ClothingBuyer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + /* + * Start at the top of the first category in clothing shop menu. + * Program will buy everything in num of categories. + * Can set num category higher or lower and will still work. + * Lower - can buy only one category by setting to one and starting program on desired clothes type + * Higher - will take longer to finish as it will repeat an already purchased category + * Stop conditions: Out of money/lp, hit catogory count + */ + + uint8_t category_rotation_count = 0; + bool finish_program = false; + while (category_rotation_count < NUM_CATEGORY){ + pbf_press_button(context, BUTTON_A, 20, 100); + + AdvanceDialogWatcher already_purchased(COLOR_RED); + PromptDialogWatcher buy_yes_no(COLOR_CYAN); + PromptDialogWatcher hairstyle_purchase_prompt(COLOR_RED); + int retP = 0; + bool incompatible_hairstyle = false; + + int ret = wait_until( + env.console, context, + std::chrono::seconds(10), + { already_purchased, buy_yes_no } + ); + switch (ret){ + case 0: + env.log("Item already purchased or incompatible hairstyle."); + pbf_press_button(context, BUTTON_A, 10, 100); + + retP = wait_until( + env.console, context, + std::chrono::seconds(2), + { hairstyle_purchase_prompt } + ); + if (retP != 0){ + env.log("Item already purchased."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Item already purchased." + ); + break; + } + env.log("Incompatible hairstyle. Proceed to purchase."); + incompatible_hairstyle = true; + case 1: + { + PromptDialogWatcher wear_yes_no(COLOR_CYAN); + AdvanceDialogWatcher afford_yes_no(COLOR_RED); + AdvanceDialogWatcher afford_yes_no_hairstyle(COLOR_RED); + int retHairstyle; + + env.log("Detected purchase prompt."); + + if (USE_LP){ + env.log("Using LP."); + pbf_press_dpad(context, DPAD_DOWN, 10, 100); + } + env.log("Purchasing."); + //Purchase, then wait a bit more for wear prompt detector. + pbf_press_button(context, BUTTON_A, 10, 100); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + int retWear = wait_until( + env.console, context, + std::chrono::seconds(10), + { wear_yes_no, afford_yes_no } + ); + switch (retWear){ + case 0: + if (!WEAR_NEW_CLOTHES){ + env.log("Do not wear new clothes."); + pbf_press_dpad(context, DPAD_DOWN, 10, 100); + }else{ + env.log("Wear new clothes."); + } + pbf_press_button(context, BUTTON_A, 10, 100); + env.log("Clothing purchased. Selecting next item."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Clothing purchased. Selecting next item." + ); + break; + case 1: + if (!incompatible_hairstyle){ + env.log("Out of Cash/LP."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Out of Cash/LP." + ); + finish_program = true; + }else{ + pbf_press_button(context, BUTTON_A, 10, 100); + retHairstyle = wait_until( + env.console, context, + std::chrono::seconds(2), + { afford_yes_no_hairstyle } + ); + if (retHairstyle == 0){ + env.log("Out of Cash/LP."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Out of Cash/LP." + ); + finish_program = true; + } + } + break; + default: + env.log("Error looking for wear prompt."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Error looking for wear prompt.", + env.console + ); + break; + } + break; + } + default: + env.log("Error looking for purchase prompt."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Error looking for purchase prompt.", + env.console + ); + break; + } + //Out of cash/LP, stop. + if (finish_program){ + break; + } + + env.log("Moving on to next item."); + pbf_press_dpad(context, DPAD_DOWN, 10, 100); + //Wait to load a bit for next item + pbf_wait(context, 100); + context.wait_for_all_requests(); + + ClothingTopWatcher top_item(COLOR_YELLOW); + + int retTop = wait_until( + env.console, context, + std::chrono::seconds(1), + { top_item } + ); + if (retTop == 0){ + env.log("Reached top of category."); + if (NUM_CATEGORY > 1){ + env.log("Category rotation set. Moving to next category."); + pbf_press_dpad(context, DPAD_RIGHT, 10, 100); + pbf_wait(context, 100); + context.wait_for_all_requests(); + category_rotation_count++; + }else{ + env.log("No category rotation. Ending program."); + break; + } + } + + } + env.log("Category num hit. Ending program."); + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.h b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.h index 04137d25ec..1cf076445b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_ClothingBuyer.h @@ -1,49 +1,49 @@ -/* Clothing Buyer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ClothingBuyer_H -#define PokemonAutomation_PokemonSwSh_ClothingBuyer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class ClothingBuyer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ClothingBuyer_Descriptor(); -}; - -class ClothingBuyer : public SingleSwitchProgramInstance{ -public: - ClothingBuyer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - BooleanCheckBoxOption USE_LP; - BooleanCheckBoxOption WEAR_NEW_CLOTHES; - SimpleIntegerOption NUM_CATEGORY; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Clothing Buyer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ClothingBuyer_H +#define PokemonAutomation_PokemonSwSh_ClothingBuyer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class ClothingBuyer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ClothingBuyer_Descriptor(); +}; + +class ClothingBuyer : public SingleSwitchProgramInstance{ +public: + ClothingBuyer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + BooleanCheckBoxOption USE_LP; + BooleanCheckBoxOption WEAR_NEW_CLOTHES; + SimpleIntegerOption NUM_CATEGORY; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.cpp b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.cpp index 55cd9dd821..7efed3fd56 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.cpp @@ -1,246 +1,246 @@ -/* SV Mass Purchase - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_MassPurchase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - using namespace Pokemon; - -MassPurchase_Descriptor::MassPurchase_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:MassPurchase", - STRING_POKEMON + " SV", "Mass Purchase", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MassPurchase.md", - "Purchase a specified amount of items from a shop.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -struct MassPurchase_Descriptor::Stats : public StatsTracker{ - Stats() - : total_items(m_stats["Items Purchased"]) - , skip(m_stats["Skipped"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back(Stat("Items Purchased")); - m_display_order.emplace_back(Stat("Skipped")); - m_display_order.emplace_back(Stat("Errors")); - } - std::atomic& total_items; - std::atomic& skip; - std::atomic& errors; -}; -std::unique_ptr MassPurchase_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -MassPurchase::MassPurchase() - : ITEMS( - "Items to Buy:
The amount of Items to buy from the position of the cursor.", - LockMode::LOCK_WHILE_RUNNING, - 50 - ) - , QUANTITY( - "Quantity to Buy:
The amount of each item to buy. If a clothing store, set to 1.", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 999 - ) - , GO_HOME_WHEN_DONE(false) - , PAY_LP( - "Pay with LP:", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(ITEMS); - PA_ADD_OPTION(QUANTITY); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(PAY_LP); - PA_ADD_OPTION(NOTIFICATIONS); -} - -bool MassPurchase::mass_purchase(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - MassPurchase_Descriptor::Stats& stats = env.current_stats(); - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - AdvanceDialogWatcher dialog(COLOR_CYAN); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(2), - { - overworld, - dialog, - } - ); - context.wait_for(std::chrono::milliseconds(50)); - - switch (ret){ - case 0: - env.log("Error - Stuck in Overworld"); - stats.errors++; - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Stuck in Overworld.", - stream - ); - - case 1: - env.log("Detected full bag. Skipped Item"); - stats.skip++; - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - return true; - - default: - return false; - } -}; - -bool MassPurchase::extra_items(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - MassPurchase_Descriptor::Stats& stats = env.current_stats(); - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - AdvanceDialogWatcher dialog(COLOR_CYAN); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(2), - { - overworld, - dialog, - } - ); - context.wait_for(std::chrono::milliseconds(50)); - - switch (ret){ - case 0: - env.log("Error - Stuck in Overworld"); - stats.errors++; - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "Stuck in Overworld.", - stream - ); - - case 1: - env.log("Detected Extra Item/Reward"); - return true; - - default: - return false; - } -}; - -void PokemonSV::MassPurchase::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - MassPurchase_Descriptor::Stats& stats = env.current_stats(); - - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - uint16_t item_val = ITEMS; - bool skip_item = false; - bool extra = false; - while (item_val != 0){ - uint16_t qt_val = QUANTITY; - pbf_press_button(context, BUTTON_A, 20, 105); - - skip_item = mass_purchase(env, env.console, context); - - if (skip_item){ - pbf_press_button(context, BUTTON_B, 20, 105); - } - - if (!skip_item){ - if (qt_val <= 500){ - uint16_t current = 1; - while (current + 10 <= qt_val){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 10); - current += 10; - } - while (current < qt_val){ - pbf_press_dpad(context, DPAD_UP, 20, 10); - current++; - } - }else{ - uint16_t current = 999; - pbf_press_dpad(context, DPAD_LEFT, 20, 10); - while (current >= qt_val + 10){ - pbf_press_dpad(context, DPAD_LEFT, 20, 10); - current -= 10; - } - while (current > qt_val){ - pbf_press_dpad(context, DPAD_DOWN, 20, 10); - current--; - } - } - - pbf_press_button(context, BUTTON_A, 20, 125); - - if (PAY_LP){ - pbf_press_dpad(context, DPAD_DOWN, 5, 105); - } - - pbf_press_button(context, BUTTON_A, 20, 230); - pbf_press_button(context, BUTTON_A, 20, 105); - extra = extra_items(env, env.console, context); - if (extra){ - pbf_press_button(context, BUTTON_A, 20, 105); - }; - - env.log("Item Purchased"); - stats.total_items++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - - item_val--; - } - - pbf_press_button(context, BUTTON_B, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* SV Mass Purchase + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_MassPurchase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + using namespace Pokemon; + +MassPurchase_Descriptor::MassPurchase_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:MassPurchase", + STRING_POKEMON + " SV", "Mass Purchase", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/MassPurchase.md", + "Purchase a specified amount of items from a shop.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +struct MassPurchase_Descriptor::Stats : public StatsTracker{ + Stats() + : total_items(m_stats["Items Purchased"]) + , skip(m_stats["Skipped"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back(Stat("Items Purchased")); + m_display_order.emplace_back(Stat("Skipped")); + m_display_order.emplace_back(Stat("Errors")); + } + std::atomic& total_items; + std::atomic& skip; + std::atomic& errors; +}; +std::unique_ptr MassPurchase_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +MassPurchase::MassPurchase() + : ITEMS( + "Items to Buy:
The amount of Items to buy from the position of the cursor.", + LockMode::LOCK_WHILE_RUNNING, + 50 + ) + , QUANTITY( + "Quantity to Buy:
The amount of each item to buy. If a clothing store, set to 1.", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 999 + ) + , GO_HOME_WHEN_DONE(false) + , PAY_LP( + "Pay with LP:", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(ITEMS); + PA_ADD_OPTION(QUANTITY); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(PAY_LP); + PA_ADD_OPTION(NOTIFICATIONS); +} + +bool MassPurchase::mass_purchase(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + MassPurchase_Descriptor::Stats& stats = env.current_stats(); + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + AdvanceDialogWatcher dialog(COLOR_CYAN); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(2), + { + overworld, + dialog, + } + ); + context.wait_for(std::chrono::milliseconds(50)); + + switch (ret){ + case 0: + env.log("Error - Stuck in Overworld"); + stats.errors++; + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Stuck in Overworld.", + stream + ); + + case 1: + env.log("Detected full bag. Skipped Item"); + stats.skip++; + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + return true; + + default: + return false; + } +}; + +bool MassPurchase::extra_items(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + MassPurchase_Descriptor::Stats& stats = env.current_stats(); + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + AdvanceDialogWatcher dialog(COLOR_CYAN); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(2), + { + overworld, + dialog, + } + ); + context.wait_for(std::chrono::milliseconds(50)); + + switch (ret){ + case 0: + env.log("Error - Stuck in Overworld"); + stats.errors++; + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "Stuck in Overworld.", + stream + ); + + case 1: + env.log("Detected Extra Item/Reward"); + return true; + + default: + return false; + } +}; + +void PokemonSV::MassPurchase::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + MassPurchase_Descriptor::Stats& stats = env.current_stats(); + + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + uint16_t item_val = ITEMS; + bool skip_item = false; + bool extra = false; + while (item_val != 0){ + uint16_t qt_val = QUANTITY; + pbf_press_button(context, BUTTON_A, 20, 105); + + skip_item = mass_purchase(env, env.console, context); + + if (skip_item){ + pbf_press_button(context, BUTTON_B, 20, 105); + } + + if (!skip_item){ + if (qt_val <= 500){ + uint16_t current = 1; + while (current + 10 <= qt_val){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 10); + current += 10; + } + while (current < qt_val){ + pbf_press_dpad(context, DPAD_UP, 20, 10); + current++; + } + }else{ + uint16_t current = 999; + pbf_press_dpad(context, DPAD_LEFT, 20, 10); + while (current >= qt_val + 10){ + pbf_press_dpad(context, DPAD_LEFT, 20, 10); + current -= 10; + } + while (current > qt_val){ + pbf_press_dpad(context, DPAD_DOWN, 20, 10); + current--; + } + } + + pbf_press_button(context, BUTTON_A, 20, 125); + + if (PAY_LP){ + pbf_press_dpad(context, DPAD_DOWN, 5, 105); + } + + pbf_press_button(context, BUTTON_A, 20, 230); + pbf_press_button(context, BUTTON_A, 20, 105); + extra = extra_items(env, env.console, context); + if (extra){ + pbf_press_button(context, BUTTON_A, 20, 105); + }; + + env.log("Item Purchased"); + stats.total_items++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + + item_val--; + } + + pbf_press_button(context, BUTTON_B, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.h b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.h index f5802a933a..0c73cea689 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.h +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_MassPurchase.h @@ -1,55 +1,55 @@ -/* Mass Purchase - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_MassPurchase_H -#define PokemonAutomation_PokemonSV_MassPurchase_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class MassPurchase_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MassPurchase_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class MassPurchase : public SingleSwitchProgramInstance{ -public: - MassPurchase(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool mass_purchase(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); - bool extra_items(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); - -private: - SimpleIntegerOption ITEMS; - SimpleIntegerOption QUANTITY; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - BooleanCheckBoxOption PAY_LP; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Mass Purchase + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_MassPurchase_H +#define PokemonAutomation_PokemonSV_MassPurchase_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class MassPurchase_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MassPurchase_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class MassPurchase : public SingleSwitchProgramInstance{ +public: + MassPurchase(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool mass_purchase(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); + bool extra_items(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); + +private: + SimpleIntegerOption ITEMS; + SimpleIntegerOption QUANTITY; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + BooleanCheckBoxOption PAY_LP; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.cpp b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.cpp index 16320cd770..12c8fb25ea 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.cpp @@ -1,290 +1,290 @@ -/* Size Checker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_SizeChecker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -SizeChecker_Descriptor::SizeChecker_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:SizeChecker", - STRING_POKEMON + " SV", "Size Checker", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/SizeChecker.md", - "Check boxes of " + STRING_POKEMON + " for size marks.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct SizeChecker_Descriptor::Stats : public StatsTracker{ - Stats() - : m_boxes(m_stats["Boxes Checked"]) - , m_checked(m_stats["Checked"]) - , m_empty(m_stats["Empty Slots"]) - , m_eggs(m_stats["Eggs"]) - , m_mark(m_stats["Mark/Ribbon"]) - { - m_display_order.emplace_back("Boxes Checked"); - m_display_order.emplace_back("Checked"); - m_display_order.emplace_back("Empty Slots"); - m_display_order.emplace_back("Eggs"); - m_display_order.emplace_back("Mark/Ribbon"); - } - std::atomic& m_boxes; - std::atomic& m_checked; - std::atomic& m_empty; - std::atomic& m_eggs; - std::atomic& m_mark; -}; -std::unique_ptr SizeChecker_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -SizeChecker::SizeChecker() - : GO_HOME_WHEN_DONE(false) - , BOXES_TO_CHECK( - "Number of Boxes to Check:", - LockMode::LOCK_WHILE_RUNNING, - 2, 1, 32 - ) - , NOTIFICATION_MARK("Mark/Ribbon Given", true, false, ImageAttachmentMode::JPG, { "Notifs" }) - , NOTIFICATIONS({ - &NOTIFICATION_MARK, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(BOXES_TO_CHECK); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - - -void SizeChecker::enter_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - env.console.log("Enter box mode to check size..."); - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(2)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_check_mode(): Failed to enter box mode after 2 minutes.", - env.console - ); - } - - AdvanceDialogWatcher dialog(COLOR_GREEN); - OverworldWatcher overworld(env.console, COLOR_CYAN); - GradientArrowWatcher prompt(COLOR_YELLOW, GradientArrowType::RIGHT, {0.72, 0.55, 0.05, 0.08}); - BoxWatcher box(COLOR_BLUE); - - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(60), - {dialog, overworld, prompt, box} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - - case 0: // dialog - case 1: // overworld - case 2: // prompt - pbf_press_button(context, BUTTON_A, 20, 5); - continue; - case 3: // box - return; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_check_mode(): No recognized state after 60 seconds.", - env.console - ); - } - } - -} - - - -void SizeChecker::exit_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, VideoSnapshot screen){ - SizeChecker_Descriptor::Stats& stats = env.current_stats(); - env.console.log("Check size and exit box mode..."); - WallClock start = current_time(); - - while (true){ - if (current_time() - start > std::chrono::minutes(2)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "exit_check_mode(): Failed to exit box mode after 2 minutes.", - env.console - ); - } - - DialogBoxWatcher ribbon(COLOR_GREEN, true, std::chrono::milliseconds(250), DialogType::DIALOG_BLACK); - DialogBoxWatcher dialog(COLOR_GREEN, true, std::chrono::milliseconds(250), DialogType::DIALOG_WHITE); - OverworldWatcher overworld(env.console, COLOR_CYAN); - - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(60), - {ribbon, dialog, overworld} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - - case 0: // ribbon - stats.m_mark++; - env.update_stats(); - - send_program_notification( - env, NOTIFICATION_MARK, - COLOR_ORANGE, "Mark/Ribbon Given", - {}, "", - screen - ); - case 1: // dialog - pbf_press_button(context, BUTTON_A, 20, 5); - continue; - case 2: // overworld - return; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "exit_check_mode(): No recognized state after 60 seconds.", - env.console - ); - } - - } - -} - - - -void SizeChecker::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - SizeChecker_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 0); - - // Loop through boxes. - for (uint8_t box = 0; box < BOXES_TO_CHECK; box++){ - enter_check_mode(env, context); - context.wait_for_all_requests(); - - if (box > 0){ - move_to_right_box(context); - } - context.wait_for_all_requests(); - - // Loop through the rows and columns. - for (uint8_t row = 0; row < 5; row++){ - for (uint8_t col = 0; col < 6; col++){ - enter_check_mode(env, context); - context.wait_for_all_requests(); - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); - - SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); - BoxCurrentEggDetector egg_detector; - VideoOverlaySet overlays(env.console.overlay()); - sth_in_box_detector.make_overlays(overlays); - egg_detector.make_overlays(overlays); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - - if (!sth_in_box_detector.detect(screen)){ - env.console.log("Detected empty cell."); - stats.m_empty++; - env.update_stats(); - continue; - } - - if (egg_detector.detect(screen)){ - env.console.log("Detected egg in cell."); - stats.m_eggs++; - env.update_stats(); - continue; - } - context.wait_for_all_requests(); - - // Initiate size checking prompt. - DialogBoxWatcher dialog(COLOR_GREEN, true, std::chrono::milliseconds(250), DialogType::DIALOG_WHITE); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_A, 20, 105); - } - }, - {dialog} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to initiate check after 10 A presses.", - env.console - ); - } - context.wait_for_all_requests(); - - exit_check_mode(env, context, screen); - context.wait_for_all_requests(); - - stats.m_checked++; - env.update_stats(); - } - } - - stats.m_boxes++; - env.update_stats(); - } - - // handle last box space being empty - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} +/* Size Checker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxEggDetector.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_SizeChecker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +SizeChecker_Descriptor::SizeChecker_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:SizeChecker", + STRING_POKEMON + " SV", "Size Checker", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/SizeChecker.md", + "Check boxes of " + STRING_POKEMON + " for size marks.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct SizeChecker_Descriptor::Stats : public StatsTracker{ + Stats() + : m_boxes(m_stats["Boxes Checked"]) + , m_checked(m_stats["Checked"]) + , m_empty(m_stats["Empty Slots"]) + , m_eggs(m_stats["Eggs"]) + , m_mark(m_stats["Mark/Ribbon"]) + { + m_display_order.emplace_back("Boxes Checked"); + m_display_order.emplace_back("Checked"); + m_display_order.emplace_back("Empty Slots"); + m_display_order.emplace_back("Eggs"); + m_display_order.emplace_back("Mark/Ribbon"); + } + std::atomic& m_boxes; + std::atomic& m_checked; + std::atomic& m_empty; + std::atomic& m_eggs; + std::atomic& m_mark; +}; +std::unique_ptr SizeChecker_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +SizeChecker::SizeChecker() + : GO_HOME_WHEN_DONE(false) + , BOXES_TO_CHECK( + "Number of Boxes to Check:", + LockMode::LOCK_WHILE_RUNNING, + 2, 1, 32 + ) + , NOTIFICATION_MARK("Mark/Ribbon Given", true, false, ImageAttachmentMode::JPG, { "Notifs" }) + , NOTIFICATIONS({ + &NOTIFICATION_MARK, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(BOXES_TO_CHECK); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + + +void SizeChecker::enter_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.console.log("Enter box mode to check size..."); + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(2)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_check_mode(): Failed to enter box mode after 2 minutes.", + env.console + ); + } + + AdvanceDialogWatcher dialog(COLOR_GREEN); + OverworldWatcher overworld(env.console, COLOR_CYAN); + GradientArrowWatcher prompt(COLOR_YELLOW, GradientArrowType::RIGHT, {0.72, 0.55, 0.05, 0.08}); + BoxWatcher box(COLOR_BLUE); + + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(60), + {dialog, overworld, prompt, box} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + + case 0: // dialog + case 1: // overworld + case 2: // prompt + pbf_press_button(context, BUTTON_A, 20, 5); + continue; + case 3: // box + return; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_check_mode(): No recognized state after 60 seconds.", + env.console + ); + } + } + +} + + + +void SizeChecker::exit_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, VideoSnapshot screen){ + SizeChecker_Descriptor::Stats& stats = env.current_stats(); + env.console.log("Check size and exit box mode..."); + WallClock start = current_time(); + + while (true){ + if (current_time() - start > std::chrono::minutes(2)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "exit_check_mode(): Failed to exit box mode after 2 minutes.", + env.console + ); + } + + DialogBoxWatcher ribbon(COLOR_GREEN, true, std::chrono::milliseconds(250), DialogType::DIALOG_BLACK); + DialogBoxWatcher dialog(COLOR_GREEN, true, std::chrono::milliseconds(250), DialogType::DIALOG_WHITE); + OverworldWatcher overworld(env.console, COLOR_CYAN); + + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(60), + {ribbon, dialog, overworld} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + + case 0: // ribbon + stats.m_mark++; + env.update_stats(); + + send_program_notification( + env, NOTIFICATION_MARK, + COLOR_ORANGE, "Mark/Ribbon Given", + {}, "", + screen + ); + case 1: // dialog + pbf_press_button(context, BUTTON_A, 20, 5); + continue; + case 2: // overworld + return; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "exit_check_mode(): No recognized state after 60 seconds.", + env.console + ); + } + + } + +} + + + +void SizeChecker::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + SizeChecker_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 0); + + // Loop through boxes. + for (uint8_t box = 0; box < BOXES_TO_CHECK; box++){ + enter_check_mode(env, context); + context.wait_for_all_requests(); + + if (box > 0){ + move_to_right_box(context); + } + context.wait_for_all_requests(); + + // Loop through the rows and columns. + for (uint8_t row = 0; row < 5; row++){ + for (uint8_t col = 0; col < 6; col++){ + enter_check_mode(env, context); + context.wait_for_all_requests(); + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::SLOTS, row, col); + + SomethingInBoxSlotDetector sth_in_box_detector(COLOR_RED); + BoxCurrentEggDetector egg_detector; + VideoOverlaySet overlays(env.console.overlay()); + sth_in_box_detector.make_overlays(overlays); + egg_detector.make_overlays(overlays); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + + if (!sth_in_box_detector.detect(screen)){ + env.console.log("Detected empty cell."); + stats.m_empty++; + env.update_stats(); + continue; + } + + if (egg_detector.detect(screen)){ + env.console.log("Detected egg in cell."); + stats.m_eggs++; + env.update_stats(); + continue; + } + context.wait_for_all_requests(); + + // Initiate size checking prompt. + DialogBoxWatcher dialog(COLOR_GREEN, true, std::chrono::milliseconds(250), DialogType::DIALOG_WHITE); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_A, 20, 105); + } + }, + {dialog} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to initiate check after 10 A presses.", + env.console + ); + } + context.wait_for_all_requests(); + + exit_check_mode(env, context, screen); + context.wait_for_all_requests(); + + stats.m_checked++; + env.update_stats(); + } + } + + stats.m_boxes++; + env.update_stats(); + } + + // handle last box space being empty + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.h b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.h index 5d9045774e..ebbf15ec9a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.h +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_SizeChecker.h @@ -1,56 +1,56 @@ -/* Size Checker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SizeChecker_H -#define PokemonAutomation_PokemonSV_SizeChecker_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class BoxDetector; - - -class SizeChecker_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SizeChecker_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class SizeChecker : public SingleSwitchProgramInstance{ -public: - SizeChecker(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void enter_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void exit_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, VideoSnapshot screen); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption BOXES_TO_CHECK; - EventNotificationOption NOTIFICATION_MARK; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Size Checker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SizeChecker_H +#define PokemonAutomation_PokemonSV_SizeChecker_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class BoxDetector; + + +class SizeChecker_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SizeChecker_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class SizeChecker : public SingleSwitchProgramInstance{ +public: + SizeChecker(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void enter_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void exit_check_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, VideoSnapshot screen); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption BOXES_TO_CHECK; + EventNotificationOption NOTIFICATION_MARK; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.cpp b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.cpp index f0fef8b4af..4b2e7b5bee 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.cpp @@ -1,653 +1,653 @@ -/* Stats Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV_StatsReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -StatsReset_Descriptor::StatsReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:StatsReset", - STRING_POKEMON + " SV", "Stats Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/StatsReset.md", - "Repeatedly catch static encounters until you get the stats you want.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StatsReset_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , balls(m_stats["Balls Thrown"]) - , catches(m_stats["Catches"]) - , matches(m_stats["Matches"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Balls Thrown"); - m_display_order.emplace_back("Catches"); - m_display_order.emplace_back("Matches"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& balls; - std::atomic& catches; - std::atomic& matches; - std::atomic& errors; -}; -std::unique_ptr StatsReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} -StatsReset::StatsReset() - : TARGET( - "Target:
The Pokemon you are resetting for.", - //"Treasures of Ruin: Stand in front of the unsealed vaults of one of the Ruinous Quartet.
" - //"Loyal Three: Stand in front of Okidogi/Munkidori/Fezandipiti.
" - //"Snacksworth Legendary: After unlocking a legendary from Snacksworth, stand in front of it.
" - //"Generic: You are standing in front of a Pokemon that requires an A press to initiate battle.
", - //"Gimmighoul: Stand in front of a Gimmighoul chest.
", - { - {Target::TreasuresOfRuin, "treasures-of-ruin", "Treasures of Ruin"}, - {Target::LoyalThree, "loyal-three", "Loyal Three"}, - {Target::Snacksworth, "snacksworth", "Snacksworth Legendaries + Meloetta"}, - {Target::Generic, "generic", "Indigo Disk Paradoxes (nature only) + Gimmighoul"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::TreasuresOfRuin - ) - , LANGUAGE( - "Game Language:
This field is required so we can read IVs.", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , BALL_SELECT( - "Ball Select:", - LockMode::UNLOCK_WHILE_RUNNING, - "poke-ball" - ) - , QUICKBALL( - "Throw Quick Ball:
Use a Quick Ball on the first turn. If there are moves in the Move Table, they will run after the Quick Ball is thrown.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , FILTERS( - StatsHuntIvJudgeFilterTable_Label_Regular, - { - .action = false, - .shiny = false, - .gender = false, - .nature = true, - } - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - & NOTIFICATION_PROGRAM_FINISH, - & NOTIFICATION_ERROR_FATAL, - }) -{ - { - std::vector> ret; - { - auto row = std::make_unique(FILTERS); - row->iv_atk.set(IvJudgeFilter::NoGood); - ret.emplace_back(std::move(row)); - } - { - auto row = std::make_unique(FILTERS); - row->iv_speed.set(IvJudgeFilter::NoGood); - ret.emplace_back(std::move(row)); - } - FILTERS.set_default(std::move(ret)); - } - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(LANGUAGE); //This is required - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(QUICKBALL); - PA_ADD_OPTION(BATTLE_MOVES); - PA_ADD_OPTION(FILTERS); //Note: None of these can be shiny, and the quartet will have some perfect IVs. - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -bool StatsReset::enter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StatsReset_Descriptor::Stats& stats = env.current_stats(); - - //Press A to talk to target - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - pbf_press_button(context, BUTTON_A, 10, 50); - int retD = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); - if (retD < 0){ - env.log("Dialog not detected."); - } - - switch (TARGET){ - case Target::TreasuresOfRuin: - //~30 seconds to start battle? - pbf_mash_button(context, BUTTON_A, 3250); - context.wait_for_all_requests(); - break; - case Target::LoyalThree: - //Mash through dialog box - pbf_mash_button(context, BUTTON_B, 1300); - context.wait_for_all_requests(); - break; - case Target::Snacksworth: - //The same as generic, but Snacksworth legendaries are not in the dex and skip the caught/summary/add to party menu. - pbf_mash_button(context, BUTTON_B, 250); - context.wait_for_all_requests(); - break; - case Target::Generic: - //Mash A to initiate battle - pbf_mash_button(context, BUTTON_A, 90); - context.wait_for_all_requests(); - break; - default: - throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Unknown Target"); - } - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret = wait_until( - env.console, context, - std::chrono::seconds(15), - { battle_menu } - ); - if (ret != 0){ - stats.errors++; - env.update_stats(); - env.log("Failed to enter battle!", COLOR_RED); - - return false; - /* - OperationFailedException::fire( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Failed to enter battle. Are you facing the Pokemon or in a menu?", - true - ); - */ - } - return true; -} - -void StatsReset::open_ball_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StatsReset_Descriptor::Stats& stats = env.current_stats(); - - BattleBallReader reader(env.console, LANGUAGE); - std::string ball_reader = ""; - WallClock start = current_time(); - - env.log("Opening ball menu..."); - while (ball_reader == ""){ - if (current_time() - start > std::chrono::minutes(2)){ - env.log("Timed out trying to read ball after 2 minutes.", COLOR_RED); - stats.errors++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out trying to read ball after 2 minutes.", - env.console - ); - } - - //Mash B to exit anything else - pbf_mash_button(context, BUTTON_B, 125); - context.wait_for_all_requests(); - - //Press X to open Ball menu - pbf_press_button(context, BUTTON_X, 20, 100); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - ball_reader = reader.read_ball(screen); - } -} - -//Returns target_fainted. If overworld is detected then the target fainted. -//Otherwise if AdvanceDialog is detected the Pokemon was caught or the player lost. -bool StatsReset::run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StatsReset_Descriptor::Stats& stats = env.current_stats(); - - AdvanceDialogWatcher advance_dialog(COLOR_MAGENTA); - OverworldWatcher overworld(env.console, COLOR_BLUE); - - uint8_t switch_party_slot = 1; - - size_t table_turn = 0; - std::vector> move_table = BATTLE_MOVES.copy_snapshot(); - - bool target_fainted = false; - bool out_of_balls = false; - bool quickball_thrown = false; - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - while (true){ - //Check that battle menu appears - this is in case of swapping pokemon - NormalBattleMenuWatcher menu_before_throw(COLOR_YELLOW); - int bMenu = wait_until( - env.console, context, - std::chrono::seconds(15), - { menu_before_throw } - ); - if (bMenu < 0){ - env.console.log("Unable to find menu_before_throw."); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find menu_before_throw.", - env.console - ); - } - - //Quick ball occurs before anything else in battle, so we can throw the ball without worrying about bounce/fainted/etc. - if (QUICKBALL && !quickball_thrown){ - env.log("Quick Ball option checked. Throwing Quick Ball."); - - BattleBallReader reader(env.console, LANGUAGE); - open_ball_menu(env, context); - - env.log("Selecting Quick Ball."); - int quantity = move_to_ball(reader, env.console, context, "quick-ball"); - if (quantity == 0){ - //Stop so user can check they have quick balls. - env.console.log("Unable to find Quick Ball on turn 1."); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find Quick Ball on turn 1.", - env.console - ); - } - if (quantity < 0){ - stats.errors++; - env.update_stats(); - env.console.log("Unable to read ball quantity.", COLOR_RED); - } - - //Throw ball - env.log("Throwing Quick Ball."); - pbf_mash_button(context, BUTTON_A, 150); - context.wait_for_all_requests(); - - quickball_thrown = true; - - stats.balls++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 900); - context.wait_for_all_requests(); - }else if (switch_party_slot == 1 && !move_table.empty() && table_turn < move_table.size()){ - //Lead pokemon not fainted and table has not been completed - //Run through moves in table - env.log("Lead has not fainted, using move."); - - MoveSelectWatcher move_watcher(COLOR_BLUE); - MoveSelectDetector move_select(COLOR_BLUE); - BattleMoveType move = move_table.at(table_turn)->type; - uint8_t move_slot = 0; - - //Leaving room to expand to other battle actions later - switch (move){ - case BattleMoveType::Move1: - move_slot = 0; - break; - case BattleMoveType::Move2: - move_slot = 1; - break; - case BattleMoveType::Move3: - move_slot = 2; - break; - case BattleMoveType::Move4: - move_slot = 3; - break; - } - - //Select and use move - int ret_move_select = run_until( - env.console, context, - [&](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - }, - { move_watcher } - ); - if (ret_move_select != 0){ - env.log("Could not find move select."); - }else{ - env.log("Move select found!"); - } - - context.wait_for_all_requests(); - move_select.move_to_slot(env.console, context, move_slot); - pbf_mash_button(context, BUTTON_A, 150); - pbf_wait(context, 100); - context.wait_for_all_requests(); - table_turn++; - - //Check for battle menu - //If found after a second, assume out of PP and stop as this is a setup issue - //None of the target pokemon for this program have disable, taunt, etc. - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret = wait_until( - env.console, context, - std::chrono::seconds(4), - { battle_menu } - ); - if (ret == 0){ - env.console.log("Battle menu detected early. Out of PP, please check your setup."); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Battle menu detected early. Out of PP, please check your setup.", - env.console - ); - }else{ - env.log("Move successfully used."); - if (table_turn == move_table.size()){ - env.log("End of table reached. Switch to throwing balls."); - } - } - }else{ - BattleBallReader reader(env.console, LANGUAGE); - open_ball_menu(env, context); - - env.log("Selecting ball."); - int quantity = move_to_ball(reader, env.console, context, BALL_SELECT.slug()); - if (quantity == 0){ - out_of_balls = true; - env.console.log("Unable to find appropriate ball/out of balls."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Unable to find appropriate ball/out of balls." - ); - break; - } - if (quantity < 0){ - stats.errors++; - env.update_stats(); - env.console.log("Unable to read ball quantity.", COLOR_RED); - } - - //Throw ball - env.log("Throwing selected ball."); - pbf_mash_button(context, BUTTON_A, 150); - context.wait_for_all_requests(); - - //Check for battle menu - //If found after a second then assume Chi-Yu used Bounce and is invulnerable - //Use first attack this turn! - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - int ret = wait_until( - env.console, context, - std::chrono::seconds(4), - { battle_menu } - ); - if (ret == 0){ - env.console.log("Battle menu detected early. Using first attack."); - pbf_mash_button(context, BUTTON_A, 250); - context.wait_for_all_requests(); - }else{ - //Wild pokemon's turn/wait for catch animation - stats.balls++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 900); - context.wait_for_all_requests(); - } - } - - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - OverworldWatcher overworld(env.console, COLOR_BLUE); - SwapMenuWatcher fainted(COLOR_YELLOW); - int ret2 = wait_until( - env.console, context, - std::chrono::seconds(60), - { battle_menu, fainted } - ); - switch (ret2){ - case 0: - env.log("Battle menu detected, continuing."); - break; - case 1: - env.log("Detected fainted Pokemon. Switching to next living Pokemon..."); - if (fainted.move_to_slot(env.console, context, switch_party_slot)){ - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - switch_party_slot++; - } - break; - default: - env.console.log("Invalid state ret2 run_battle."); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state ret2 run_battle.", - env.console - ); - } - - } - }, - { advance_dialog, overworld } - ); - - switch (ret){ - case 0: - //Non-Snack: dialog appears on caught screen. - //Snack: "target fled somewhere..." - //Lost battle: joy dialog - env.log("Advance Dialog detected. Caught regular target, lost battle, or fainted Snacksworth."); - target_fainted = false; - break; - case 1: - if (TARGET == Target::Snacksworth){ - env.log("Overworld detected. Snacksworth legendary caught, checking box system."); - target_fainted = false; - }else{ - env.log("Overworld detected, target Pokemon fainted."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Overworld detected, target Pokemon fainted." - ); - target_fainted = true; - } - break; - default: - if (out_of_balls){ - target_fainted = true; //Resets game. - env.log("Ran out of selected Pokeball. Resetting."); - break; - } - env.console.log("Invalid state in run_battle()."); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state in run_battle().", - env.console - ); - } - - return target_fainted; -} - -bool StatsReset::check_stats(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StatsReset_Descriptor::Stats& stats = env.current_stats(); - bool match = false; - - // Open box - enter_box_system_from_overworld(env.program_info(), env.console, context); - context.wait_for(std::chrono::milliseconds(400)); - - // Check that the target pokemon was caught - if (check_empty_slots_in_party(env.program_info(), env.console, context) != 0){ - env.console.log("One or more empty slots in party. Target was not caught or user setup error."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "One or more empty slots in party. Target was not caught." - ); - }else{ - stats.catches++; - env.update_stats(); - - // Navigate to last party slot - move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 5, 0); - - // Check the IVs of the newly caught Pokemon - *must be on IV panel* - StatsHuntAction action = StatsHuntAction::Keep; - check_stats_reset_info(env.console, context, LANGUAGE, FILTERS, action); - - switch (action){ - case StatsHuntAction::StopProgram: - match = true; - - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - - env.console.log("Match found!"); - stats.matches++; - env.update_stats(); - break; - case StatsHuntAction::Discard: - match = false; - env.console.log("Stats did not match table settings."); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Stats did not match table settings." - ); - break; - default: - env.console.log("Invalid state."); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Invalid state.", - env.console - ); - } - } - - return match; -} - -void StatsReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // This will only work for Pokemon that you press A to talk to. - // Regular static spawns will have the same stats, resetting won't work. - // Won't apply to the former titan pokemon or the box legends + ogrepon either, as their IVs are locked. - // So this really only applies to the ruinous quartet and loyal three - // Use first attack if target pokemon is invulnerable (Chi-Yu used Bounce) - - assert_16_9_720p_min(env.logger(), env.console); - StatsReset_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 10); - - // Autosave must be off, settings like Tera farmer. - bool stats_matched = false; - while (!stats_matched){ - bool battle_started = false; - for (size_t c = 0; !battle_started; c++){ - battle_started = enter_battle(env, context); - - if (!battle_started){ - env.log("Did not detect battle. Resetting."); - stats.resets++; - env.update_stats(); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - } - - // Try to start battle 3 times. - if (c > 2){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to enter battle after 3 attempts.", - env.console - ); - break; - } - } - - bool target_fainted = run_battle(env, context); - - if (!target_fainted){ - // Close all the dex entry and caught menus - // If the player lost, this closes all dialog from Joy - OverworldWatcher overworld(env.console); - int retOver = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { overworld } - ); - if (retOver != 0){ - env.log("Failed to detect overworld.", COLOR_RED); - }else{ - env.log("Detected overworld."); - } - context.wait_for_all_requests(); - - stats_matched = check_stats(env, context); - } - - if (target_fainted || !stats_matched){ - // Reset game - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Resetting game." - ); - stats.resets++; - env.update_stats(); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - } - } - env.update_stats(); - auto screenshot = env.console.video().snapshot(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Match found!", screenshot, true - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - -} -} -} +/* Stats Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV_StatsReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +StatsReset_Descriptor::StatsReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:StatsReset", + STRING_POKEMON + " SV", "Stats Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/StatsReset.md", + "Repeatedly catch static encounters until you get the stats you want.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StatsReset_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , balls(m_stats["Balls Thrown"]) + , catches(m_stats["Catches"]) + , matches(m_stats["Matches"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Balls Thrown"); + m_display_order.emplace_back("Catches"); + m_display_order.emplace_back("Matches"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& resets; + std::atomic& balls; + std::atomic& catches; + std::atomic& matches; + std::atomic& errors; +}; +std::unique_ptr StatsReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} +StatsReset::StatsReset() + : TARGET( + "Target:
The Pokemon you are resetting for.", + //"Treasures of Ruin: Stand in front of the unsealed vaults of one of the Ruinous Quartet.
" + //"Loyal Three: Stand in front of Okidogi/Munkidori/Fezandipiti.
" + //"Snacksworth Legendary: After unlocking a legendary from Snacksworth, stand in front of it.
" + //"Generic: You are standing in front of a Pokemon that requires an A press to initiate battle.
", + //"Gimmighoul: Stand in front of a Gimmighoul chest.
", + { + {Target::TreasuresOfRuin, "treasures-of-ruin", "Treasures of Ruin"}, + {Target::LoyalThree, "loyal-three", "Loyal Three"}, + {Target::Snacksworth, "snacksworth", "Snacksworth Legendaries + Meloetta"}, + {Target::Generic, "generic", "Indigo Disk Paradoxes (nature only) + Gimmighoul"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::TreasuresOfRuin + ) + , LANGUAGE( + "Game Language:
This field is required so we can read IVs.", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , BALL_SELECT( + "Ball Select:", + LockMode::UNLOCK_WHILE_RUNNING, + "poke-ball" + ) + , QUICKBALL( + "Throw Quick Ball:
Use a Quick Ball on the first turn. If there are moves in the Move Table, they will run after the Quick Ball is thrown.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , FILTERS( + StatsHuntIvJudgeFilterTable_Label_Regular, + { + .action = false, + .shiny = false, + .gender = false, + .nature = true, + } + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + & NOTIFICATION_PROGRAM_FINISH, + & NOTIFICATION_ERROR_FATAL, + }) +{ + { + std::vector> ret; + { + auto row = std::make_unique(FILTERS); + row->iv_atk.set(IvJudgeFilter::NoGood); + ret.emplace_back(std::move(row)); + } + { + auto row = std::make_unique(FILTERS); + row->iv_speed.set(IvJudgeFilter::NoGood); + ret.emplace_back(std::move(row)); + } + FILTERS.set_default(std::move(ret)); + } + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(LANGUAGE); //This is required + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(QUICKBALL); + PA_ADD_OPTION(BATTLE_MOVES); + PA_ADD_OPTION(FILTERS); //Note: None of these can be shiny, and the quartet will have some perfect IVs. + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +bool StatsReset::enter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StatsReset_Descriptor::Stats& stats = env.current_stats(); + + //Press A to talk to target + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + pbf_press_button(context, BUTTON_A, 10, 50); + int retD = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); + if (retD < 0){ + env.log("Dialog not detected."); + } + + switch (TARGET){ + case Target::TreasuresOfRuin: + //~30 seconds to start battle? + pbf_mash_button(context, BUTTON_A, 3250); + context.wait_for_all_requests(); + break; + case Target::LoyalThree: + //Mash through dialog box + pbf_mash_button(context, BUTTON_B, 1300); + context.wait_for_all_requests(); + break; + case Target::Snacksworth: + //The same as generic, but Snacksworth legendaries are not in the dex and skip the caught/summary/add to party menu. + pbf_mash_button(context, BUTTON_B, 250); + context.wait_for_all_requests(); + break; + case Target::Generic: + //Mash A to initiate battle + pbf_mash_button(context, BUTTON_A, 90); + context.wait_for_all_requests(); + break; + default: + throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Unknown Target"); + } + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret = wait_until( + env.console, context, + std::chrono::seconds(15), + { battle_menu } + ); + if (ret != 0){ + stats.errors++; + env.update_stats(); + env.log("Failed to enter battle!", COLOR_RED); + + return false; + /* + OperationFailedException::fire( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Failed to enter battle. Are you facing the Pokemon or in a menu?", + true + ); + */ + } + return true; +} + +void StatsReset::open_ball_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StatsReset_Descriptor::Stats& stats = env.current_stats(); + + BattleBallReader reader(env.console, LANGUAGE); + std::string ball_reader = ""; + WallClock start = current_time(); + + env.log("Opening ball menu..."); + while (ball_reader == ""){ + if (current_time() - start > std::chrono::minutes(2)){ + env.log("Timed out trying to read ball after 2 minutes.", COLOR_RED); + stats.errors++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out trying to read ball after 2 minutes.", + env.console + ); + } + + //Mash B to exit anything else + pbf_mash_button(context, BUTTON_B, 125); + context.wait_for_all_requests(); + + //Press X to open Ball menu + pbf_press_button(context, BUTTON_X, 20, 100); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + ball_reader = reader.read_ball(screen); + } +} + +//Returns target_fainted. If overworld is detected then the target fainted. +//Otherwise if AdvanceDialog is detected the Pokemon was caught or the player lost. +bool StatsReset::run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StatsReset_Descriptor::Stats& stats = env.current_stats(); + + AdvanceDialogWatcher advance_dialog(COLOR_MAGENTA); + OverworldWatcher overworld(env.console, COLOR_BLUE); + + uint8_t switch_party_slot = 1; + + size_t table_turn = 0; + std::vector> move_table = BATTLE_MOVES.copy_snapshot(); + + bool target_fainted = false; + bool out_of_balls = false; + bool quickball_thrown = false; + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + while (true){ + //Check that battle menu appears - this is in case of swapping pokemon + NormalBattleMenuWatcher menu_before_throw(COLOR_YELLOW); + int bMenu = wait_until( + env.console, context, + std::chrono::seconds(15), + { menu_before_throw } + ); + if (bMenu < 0){ + env.console.log("Unable to find menu_before_throw."); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find menu_before_throw.", + env.console + ); + } + + //Quick ball occurs before anything else in battle, so we can throw the ball without worrying about bounce/fainted/etc. + if (QUICKBALL && !quickball_thrown){ + env.log("Quick Ball option checked. Throwing Quick Ball."); + + BattleBallReader reader(env.console, LANGUAGE); + open_ball_menu(env, context); + + env.log("Selecting Quick Ball."); + int quantity = move_to_ball(reader, env.console, context, "quick-ball"); + if (quantity == 0){ + //Stop so user can check they have quick balls. + env.console.log("Unable to find Quick Ball on turn 1."); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find Quick Ball on turn 1.", + env.console + ); + } + if (quantity < 0){ + stats.errors++; + env.update_stats(); + env.console.log("Unable to read ball quantity.", COLOR_RED); + } + + //Throw ball + env.log("Throwing Quick Ball."); + pbf_mash_button(context, BUTTON_A, 150); + context.wait_for_all_requests(); + + quickball_thrown = true; + + stats.balls++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 900); + context.wait_for_all_requests(); + }else if (switch_party_slot == 1 && !move_table.empty() && table_turn < move_table.size()){ + //Lead pokemon not fainted and table has not been completed + //Run through moves in table + env.log("Lead has not fainted, using move."); + + MoveSelectWatcher move_watcher(COLOR_BLUE); + MoveSelectDetector move_select(COLOR_BLUE); + BattleMoveType move = move_table.at(table_turn)->type; + uint8_t move_slot = 0; + + //Leaving room to expand to other battle actions later + switch (move){ + case BattleMoveType::Move1: + move_slot = 0; + break; + case BattleMoveType::Move2: + move_slot = 1; + break; + case BattleMoveType::Move3: + move_slot = 2; + break; + case BattleMoveType::Move4: + move_slot = 3; + break; + } + + //Select and use move + int ret_move_select = run_until( + env.console, context, + [&](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + }, + { move_watcher } + ); + if (ret_move_select != 0){ + env.log("Could not find move select."); + }else{ + env.log("Move select found!"); + } + + context.wait_for_all_requests(); + move_select.move_to_slot(env.console, context, move_slot); + pbf_mash_button(context, BUTTON_A, 150); + pbf_wait(context, 100); + context.wait_for_all_requests(); + table_turn++; + + //Check for battle menu + //If found after a second, assume out of PP and stop as this is a setup issue + //None of the target pokemon for this program have disable, taunt, etc. + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret = wait_until( + env.console, context, + std::chrono::seconds(4), + { battle_menu } + ); + if (ret == 0){ + env.console.log("Battle menu detected early. Out of PP, please check your setup."); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Battle menu detected early. Out of PP, please check your setup.", + env.console + ); + }else{ + env.log("Move successfully used."); + if (table_turn == move_table.size()){ + env.log("End of table reached. Switch to throwing balls."); + } + } + }else{ + BattleBallReader reader(env.console, LANGUAGE); + open_ball_menu(env, context); + + env.log("Selecting ball."); + int quantity = move_to_ball(reader, env.console, context, BALL_SELECT.slug()); + if (quantity == 0){ + out_of_balls = true; + env.console.log("Unable to find appropriate ball/out of balls."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Unable to find appropriate ball/out of balls." + ); + break; + } + if (quantity < 0){ + stats.errors++; + env.update_stats(); + env.console.log("Unable to read ball quantity.", COLOR_RED); + } + + //Throw ball + env.log("Throwing selected ball."); + pbf_mash_button(context, BUTTON_A, 150); + context.wait_for_all_requests(); + + //Check for battle menu + //If found after a second then assume Chi-Yu used Bounce and is invulnerable + //Use first attack this turn! + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + int ret = wait_until( + env.console, context, + std::chrono::seconds(4), + { battle_menu } + ); + if (ret == 0){ + env.console.log("Battle menu detected early. Using first attack."); + pbf_mash_button(context, BUTTON_A, 250); + context.wait_for_all_requests(); + }else{ + //Wild pokemon's turn/wait for catch animation + stats.balls++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 900); + context.wait_for_all_requests(); + } + } + + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + OverworldWatcher overworld(env.console, COLOR_BLUE); + SwapMenuWatcher fainted(COLOR_YELLOW); + int ret2 = wait_until( + env.console, context, + std::chrono::seconds(60), + { battle_menu, fainted } + ); + switch (ret2){ + case 0: + env.log("Battle menu detected, continuing."); + break; + case 1: + env.log("Detected fainted Pokemon. Switching to next living Pokemon..."); + if (fainted.move_to_slot(env.console, context, switch_party_slot)){ + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + switch_party_slot++; + } + break; + default: + env.console.log("Invalid state ret2 run_battle."); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state ret2 run_battle.", + env.console + ); + } + + } + }, + { advance_dialog, overworld } + ); + + switch (ret){ + case 0: + //Non-Snack: dialog appears on caught screen. + //Snack: "target fled somewhere..." + //Lost battle: joy dialog + env.log("Advance Dialog detected. Caught regular target, lost battle, or fainted Snacksworth."); + target_fainted = false; + break; + case 1: + if (TARGET == Target::Snacksworth){ + env.log("Overworld detected. Snacksworth legendary caught, checking box system."); + target_fainted = false; + }else{ + env.log("Overworld detected, target Pokemon fainted."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Overworld detected, target Pokemon fainted." + ); + target_fainted = true; + } + break; + default: + if (out_of_balls){ + target_fainted = true; //Resets game. + env.log("Ran out of selected Pokeball. Resetting."); + break; + } + env.console.log("Invalid state in run_battle()."); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state in run_battle().", + env.console + ); + } + + return target_fainted; +} + +bool StatsReset::check_stats(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StatsReset_Descriptor::Stats& stats = env.current_stats(); + bool match = false; + + // Open box + enter_box_system_from_overworld(env.program_info(), env.console, context); + context.wait_for(std::chrono::milliseconds(400)); + + // Check that the target pokemon was caught + if (check_empty_slots_in_party(env.program_info(), env.console, context) != 0){ + env.console.log("One or more empty slots in party. Target was not caught or user setup error."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "One or more empty slots in party. Target was not caught." + ); + }else{ + stats.catches++; + env.update_stats(); + + // Navigate to last party slot + move_box_cursor(env.program_info(), env.console, context, BoxCursorLocation::PARTY, 5, 0); + + // Check the IVs of the newly caught Pokemon - *must be on IV panel* + StatsHuntAction action = StatsHuntAction::Keep; + check_stats_reset_info(env.console, context, LANGUAGE, FILTERS, action); + + switch (action){ + case StatsHuntAction::StopProgram: + match = true; + + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + + env.console.log("Match found!"); + stats.matches++; + env.update_stats(); + break; + case StatsHuntAction::Discard: + match = false; + env.console.log("Stats did not match table settings."); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Stats did not match table settings." + ); + break; + default: + env.console.log("Invalid state."); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Invalid state.", + env.console + ); + } + } + + return match; +} + +void StatsReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // This will only work for Pokemon that you press A to talk to. + // Regular static spawns will have the same stats, resetting won't work. + // Won't apply to the former titan pokemon or the box legends + ogrepon either, as their IVs are locked. + // So this really only applies to the ruinous quartet and loyal three + // Use first attack if target pokemon is invulnerable (Chi-Yu used Bounce) + + assert_16_9_720p_min(env.logger(), env.console); + StatsReset_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 10); + + // Autosave must be off, settings like Tera farmer. + bool stats_matched = false; + while (!stats_matched){ + bool battle_started = false; + for (size_t c = 0; !battle_started; c++){ + battle_started = enter_battle(env, context); + + if (!battle_started){ + env.log("Did not detect battle. Resetting."); + stats.resets++; + env.update_stats(); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + } + + // Try to start battle 3 times. + if (c > 2){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to enter battle after 3 attempts.", + env.console + ); + break; + } + } + + bool target_fainted = run_battle(env, context); + + if (!target_fainted){ + // Close all the dex entry and caught menus + // If the player lost, this closes all dialog from Joy + OverworldWatcher overworld(env.console); + int retOver = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { overworld } + ); + if (retOver != 0){ + env.log("Failed to detect overworld.", COLOR_RED); + }else{ + env.log("Detected overworld."); + } + context.wait_for_all_requests(); + + stats_matched = check_stats(env, context); + } + + if (target_fainted || !stats_matched){ + // Reset game + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Resetting game." + ); + stats.resets++; + env.update_stats(); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + } + } + env.update_stats(); + auto screenshot = env.console.video().snapshot(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Match found!", screenshot, true + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.h b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.h index 725ddb827c..70a473f0fc 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.h +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsReset.h @@ -1,64 +1,64 @@ -/* Stats Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_StatsReset_H -#define PokemonAutomation_PokemonSV_StatsReset_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSV/Options/PokemonSV_BattleMoveTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class StatsReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StatsReset_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class StatsReset : public SingleSwitchProgramInstance{ -public: - StatsReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - //Can expand targets assuming there's anything else not locked in the DLC - enum class Target{ - TreasuresOfRuin, - LoyalThree, - Snacksworth, - Generic, - }; - EnumDropdownOption TARGET; - - OCR::LanguageOCROption LANGUAGE; - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - BooleanCheckBoxOption QUICKBALL; - BattleMoveTable BATTLE_MOVES; - Pokemon::StatsHuntIvJudgeFilterTable FILTERS; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - bool enter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void open_ball_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool check_stats(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif +/* Stats Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StatsReset_H +#define PokemonAutomation_PokemonSV_StatsReset_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSV/Options/PokemonSV_BattleMoveTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class StatsReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StatsReset_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class StatsReset : public SingleSwitchProgramInstance{ +public: + StatsReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + //Can expand targets assuming there's anything else not locked in the DLC + enum class Target{ + TreasuresOfRuin, + LoyalThree, + Snacksworth, + Generic, + }; + EnumDropdownOption TARGET; + + OCR::LanguageOCROption LANGUAGE; + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + BooleanCheckBoxOption QUICKBALL; + BattleMoveTable BATTLE_MOVES; + Pokemon::StatsHuntIvJudgeFilterTable FILTERS; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + bool enter_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void open_ball_menu(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool check_stats(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.cpp b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.cpp index 5df92ea298..2cf6fbcc2e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.cpp @@ -1,579 +1,579 @@ -/* Stats Reset Event Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Inference/PokemonSV_StatHexagonReader.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV_StatsResetEventBattle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -IvDisplay::IvDisplay() - : GroupOption("Calculated IV Range", LockMode::READ_ONLY) - , hp(false, "HP:", LockMode::READ_ONLY, "-", "") - , atk(false, "Attack:", LockMode::READ_ONLY, "-", "") - , def(false, "Defense:", LockMode::READ_ONLY, "-", "") - , spatk(false, "Special Attack:", LockMode::READ_ONLY, "-", "") - , spdef(false, "Special Defense:", LockMode::READ_ONLY, "-", "") - , speed(false, "Speed:", LockMode::READ_ONLY, "-", "") -{ - PA_ADD_STATIC(hp); - PA_ADD_STATIC(atk); - PA_ADD_STATIC(def); - PA_ADD_STATIC(spatk); - PA_ADD_STATIC(spdef); - PA_ADD_STATIC(speed); -} -std::string IvDisplay::get_range_string(const IvRange& range){ - if (range.low < 0 || range.high < 0){ - return "(invalid or unable to read)"; - } - if (range.low == range.high){ - return std::to_string(range.low); - } - return std::to_string(range.low) + " - " + std::to_string(range.high); -} -void IvDisplay::set(const IvRanges& ivs){ - hp.set(get_range_string(ivs.hp)); - atk.set(get_range_string(ivs.attack)); - def.set(get_range_string(ivs.defense)); - spatk.set(get_range_string(ivs.spatk)); - spdef.set(get_range_string(ivs.spdef)); - speed.set(get_range_string(ivs.speed)); -} - - -StatsResetEventBattle_Descriptor::StatsResetEventBattle_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:StatsResetEventBattle", - STRING_POKEMON + " SV", "Stats Reset - Event Battle", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/StatsResetEventBattle.md", - "Repeatedly catch Bloodmoon Ursaluna or Pecharunt until you get the stats you want.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StatsResetEventBattle_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , catches(m_stats["Catches"]) - , matches(m_stats["Matches"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Catches"); - m_display_order.emplace_back("Matches"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& resets; - std::atomic& catches; - std::atomic& matches; - std::atomic& errors; -}; -std::unique_ptr StatsResetEventBattle_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} -StatsResetEventBattle::StatsResetEventBattle() - : TARGET( - "Target:
The Pokemon you are resetting for.", - { - {Target::Ursaluna, "ursaluna", "Bloodmoon Ursaluna"}, - {Target::Pecharunt, "pecharunt", "Pecharunt"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Target::Ursaluna - ) - , LANGUAGE( - "Game Language:
This field is required so we can read IVs.", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , BALL_SELECT( - "Ball Select:", - LockMode::UNLOCK_WHILE_RUNNING, - "poke-ball" - ) - , TRY_TO_TERASTILLIZE( - "Use Terastillization:
Tera at the start of battle.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) -#if 0 - , FILTERS( - StatsHuntIvJudgeFilterTable_Label_Regular, - { - .action = false, - .shiny = false, - .gender = false, - .nature = false, - } - ) -#endif - , FILTERS0( - StatsHuntIvRangeFilterTable_Label_Regular, - { - .action = false, - .shiny = false, - .gender = false, - .nature = false, - } - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ -#if 0 - { - std::vector> ret; - { - auto row = std::make_unique(FILTERS.feature_flags); - row->iv_atk.set(IvJudgeFilter::NoGood); - ret.emplace_back(std::move(row)); - } - { - auto row = std::make_unique(FILTERS.feature_flags); - row->iv_speed.set(IvJudgeFilter::NoGood); - ret.emplace_back(std::move(row)); - } - FILTERS.set_default(std::move(ret)); - } -#endif - { - std::vector> ret; - { - auto row = std::make_unique(FILTERS0); - row->iv_atk.set(0, 1); - ret.emplace_back(std::move(row)); - } - { - auto row = std::make_unique(FILTERS0); - row->iv_speed.set(0, 1); - ret.emplace_back(std::move(row)); - } - FILTERS0.set_default(std::move(ret)); - FILTERS0.restore_defaults(); - } - PA_ADD_STATIC(CALCULATED_IVS); - PA_ADD_OPTION(TARGET); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(TRY_TO_TERASTILLIZE); - PA_ADD_OPTION(FILTERS0); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void StatsResetEventBattle::enter_battle_ursaluna(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - PromptDialogWatcher prompt_detector(COLOR_YELLOW); - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - - // Initiate dialog with Perrin - pbf_press_button(context, BUTTON_A, 10, 50); - int ret = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); - if (ret == 0){ - env.log("Dialog detected."); - }else{ - env.log("Dialog not detected."); - } - // Yes, ready - pbf_mash_button(context, BUTTON_A, 400); - context.wait_for_all_requests(); - - // Mash B until next dialog select - int retPrompt = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { prompt_detector } - ); - if (retPrompt != 0){ - env.log("Failed to detect prompt dialog!", COLOR_RED); - }else{ - env.log("Detected prompt dialog."); - } - context.wait_for_all_requests(); - - // Pick an option to continue - pbf_mash_button(context, BUTTON_A, 400); - context.wait_for_all_requests(); - - // Mash B until next dialog select (again) -// PromptDialogWatcher prompt_detector2(COLOR_YELLOW); - int retPrompt2 = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { prompt_detector } - ); - if (retPrompt2 != 0){ - env.log("Failed to detect prompt (again) dialog!", COLOR_RED); - }else{ - env.log("Detected prompt (again) dialog."); - } - context.wait_for_all_requests(); - - // Pick an option to continue - pbf_mash_button(context, BUTTON_A, 400); - context.wait_for_all_requests(); - - // Now keep going until the battle starts - int ret_battle = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { battle_menu } - ); - if (ret_battle != 0){ - env.log("Failed to detect battle start!", COLOR_RED); - }else{ - env.log("Battle started."); - } - context.wait_for_all_requests(); -} - -void StatsResetEventBattle::enter_battle_pecharunt(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - AdvanceDialogWatcher advance_detector(COLOR_YELLOW); - AdvanceDialogWatcher advance_detector2(COLOR_YELLOW); - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - - // Talk to Pecharunt - pbf_press_button(context, BUTTON_A, 10, 50); - int ret = wait_until(env.console, context, Milliseconds(6000), { advance_detector }); - if (ret == 0){ - env.log("Dialog detected."); - }else{ - env.log("Dialog not detected."); - } - pbf_mash_button(context, BUTTON_A, 400); - context.wait_for_all_requests(); - - // Do you want to challenge the strange pokemon? - int ret2 = wait_until(env.console, context, Milliseconds(6000), { advance_detector2 }); - if (ret2 == 0){ - env.log("Dialog detected."); - }else{ - env.log("Dialog not detected."); - } - // Mash through, answer Yes. - pbf_mash_button(context, BUTTON_A, 500); - context.wait_for_all_requests(); - - // Mash B until the battle starts - // Note - Sending out Ogerpon/Loyal Three during battle adds time, but the below is more than enough. - int ret_battle = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { battle_menu } - ); - if (ret_battle != 0){ - env.log("Failed to detect battle start!", COLOR_RED); - }else{ - env.log("Battle started."); - } - context.wait_for_all_requests(); -} - -bool StatsResetEventBattle::run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); - - // Assuming the player has a charged orb - if (TRY_TO_TERASTILLIZE){ - env.log("Attempting to terastillize."); - //Open move menu - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_R, 20, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - } - - // Repeatedly use first attack - TeraCatchWatcher catch_menu(COLOR_BLUE); - AdvanceDialogWatcher lost(COLOR_YELLOW); - WallClock start = current_time(); - uint8_t switch_party_slot = 1; - - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - while(true){ - if (current_time() - start > std::chrono::minutes(5)){ - env.log("Timed out during battle after 5 minutes.", COLOR_RED); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle after 5 minutes.", - env.console - ); - } - - NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); - SwapMenuWatcher fainted(COLOR_RED); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(90), - { battle_menu, fainted } - ); - switch (ret){ - case 0: - env.log("Detected battle menu. Pressing A to attack..."); - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - break; - case 1: - env.log("Detected fainted Pokemon. Switching to next living Pokemon..."); - if (fainted.move_to_slot(env.console, context, switch_party_slot)){ - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - switch_party_slot++; - } - break; - default: - env.log("Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", COLOR_RED); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", - env.console - ); - } - } - }, - { catch_menu, lost } - ); - if (ret == 0){ - env.log("Catch prompt detected."); - - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - BattleBallReader reader(env.console, LANGUAGE); - int quantity = move_to_ball(reader, env.console, context, BALL_SELECT.slug()); - if (quantity == 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find appropriate ball. Did you run out?", - env.console - ); - } - if (quantity < 0){ - stats.errors++; - env.update_stats(); - env.log("Unable to read ball quantity.", COLOR_RED); - } - pbf_mash_button(context, BUTTON_A, 125); - context.wait_for_all_requests(); - - stats.catches++; - env.update_stats(); - env.log("Target caught."); - }else{ - env.log("Battle against target lost.", COLOR_RED); - env.update_stats(); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Battle against target lost." - ); - - return false; - } - return true; -} - - -bool StatsResetEventBattle::check_stats_after_win(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // If this is the first advance dialog, it might be linked to pokedex filling so press A and continue - bool first_advance_dialog = true; - - while (true){ - PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); - PromptDialogWatcher view_summary(COLOR_PURPLE, {0.500, 0.470, 0.400, 0.100}); - PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); - PokemonSummaryWatcher summary(COLOR_MAGENTA); - AdvanceDialogWatcher advance(COLOR_YELLOW); - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, std::chrono::seconds(60), - { - add_to_party, - view_summary, - nickname, - summary, - advance, - } - ); - switch (ret){ - case 0: - env.console.log("Detected add-to-party prompt."); - pbf_press_dpad(context, DPAD_DOWN, 20, 60); - continue; - case 1: - env.console.log("Detected cursor over view summary."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 2: - env.console.log("Detected nickname prompt."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 3:{ - env.console.log("Detected summary."); - VideoOverlaySet overlays(env.console.overlay()); - - SummaryStatsReader reader; - reader.make_overlays(overlays); - - pbf_press_dpad(context, DPAD_RIGHT, 20, 230); - context.wait_for_all_requests(); - - auto snapshot = env.console.video().snapshot(); - IvRanges ivs; - try{ - if (TARGET == Target::Ursaluna){ - ivs = reader.calc_ivs(env.logger(), snapshot, { 113, 70, 120, 135, 65, 52 }); - }else{ - ivs = reader.calc_ivs(env.logger(), snapshot, { 88, 88, 160, 88, 88, 88 }); - } - }catch (OperationFailedException& e){ - send_program_recoverable_error_notification( - env, NOTIFICATION_ERROR_RECOVERABLE, - e.message(), - snapshot - ); - return false; - } - - CALCULATED_IVS.set(ivs); - - StatsHuntAction action; - if (TARGET == Target::Ursaluna){ - action = FILTERS0.get_action(false, StatsHuntGenderFilter::Any, NatureCheckerValue::Hardy, ivs); - }else{ - action = FILTERS0.get_action(false, StatsHuntGenderFilter::Any, NatureCheckerValue::Timid, ivs); - } - - return action != StatsHuntAction::Discard; - } - case 4:{ - if (first_advance_dialog){ - env.console.log("Pressing continue, in case it's a new pokedex entry."); - pbf_press_button(context, BUTTON_A, 20, 105); - first_advance_dialog = false; - continue; - }else{ - StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - env.update_stats(); - throw UserSetupError( - env.logger(), - "Did not detect add-to-party prompt. Make sure your party is full and \"Send to Boxes\" is set to \"Manual\"." - ); - } - } - default: - StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "StatsResetEventBattle::check_stats_after_win(): No state detected after 1 minute.", - env.console - ); - } - } -} - -void StatsResetEventBattle::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 10); - - while (true){ - if (TARGET == Target::Ursaluna){ - enter_battle_ursaluna(env, context); - }else{ - enter_battle_pecharunt(env, context); - } - - if (run_battle(env, context) && check_stats_after_win(env, context)){ - break; - } - - // Reset - stats.resets++; - env.update_stats(); - send_program_status_notification( - env, NOTIFICATION_STATUS_UPDATE, - "Resetting game." - ); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - } - stats.matches++; - env.update_stats(); - - auto snapshot = env.console.video().snapshot(); - - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "HP: " + (std::string)CALCULATED_IVS.hp + "\n" + - "Atk: " + (std::string)CALCULATED_IVS.atk + "\n" + - "Def: " + (std::string)CALCULATED_IVS.def + "\n" + - "SpAtk: " + (std::string)CALCULATED_IVS.spatk + "\n" + - "SpDef: " + (std::string)CALCULATED_IVS.spdef + "\n" + - "Speed: " + (std::string)CALCULATED_IVS.speed, - snapshot, - true - ); -} - -} -} -} +/* Stats Reset Event Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Inference/PokemonSV_StatHexagonReader.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_BattleBallReader.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_StatsResetChecker.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV_StatsResetEventBattle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +IvDisplay::IvDisplay() + : GroupOption("Calculated IV Range", LockMode::READ_ONLY) + , hp(false, "HP:", LockMode::READ_ONLY, "-", "") + , atk(false, "Attack:", LockMode::READ_ONLY, "-", "") + , def(false, "Defense:", LockMode::READ_ONLY, "-", "") + , spatk(false, "Special Attack:", LockMode::READ_ONLY, "-", "") + , spdef(false, "Special Defense:", LockMode::READ_ONLY, "-", "") + , speed(false, "Speed:", LockMode::READ_ONLY, "-", "") +{ + PA_ADD_STATIC(hp); + PA_ADD_STATIC(atk); + PA_ADD_STATIC(def); + PA_ADD_STATIC(spatk); + PA_ADD_STATIC(spdef); + PA_ADD_STATIC(speed); +} +std::string IvDisplay::get_range_string(const IvRange& range){ + if (range.low < 0 || range.high < 0){ + return "(invalid or unable to read)"; + } + if (range.low == range.high){ + return std::to_string(range.low); + } + return std::to_string(range.low) + " - " + std::to_string(range.high); +} +void IvDisplay::set(const IvRanges& ivs){ + hp.set(get_range_string(ivs.hp)); + atk.set(get_range_string(ivs.attack)); + def.set(get_range_string(ivs.defense)); + spatk.set(get_range_string(ivs.spatk)); + spdef.set(get_range_string(ivs.spdef)); + speed.set(get_range_string(ivs.speed)); +} + + +StatsResetEventBattle_Descriptor::StatsResetEventBattle_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:StatsResetEventBattle", + STRING_POKEMON + " SV", "Stats Reset - Event Battle", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/StatsResetEventBattle.md", + "Repeatedly catch Bloodmoon Ursaluna or Pecharunt until you get the stats you want.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StatsResetEventBattle_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , catches(m_stats["Catches"]) + , matches(m_stats["Matches"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Catches"); + m_display_order.emplace_back("Matches"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& resets; + std::atomic& catches; + std::atomic& matches; + std::atomic& errors; +}; +std::unique_ptr StatsResetEventBattle_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} +StatsResetEventBattle::StatsResetEventBattle() + : TARGET( + "Target:
The Pokemon you are resetting for.", + { + {Target::Ursaluna, "ursaluna", "Bloodmoon Ursaluna"}, + {Target::Pecharunt, "pecharunt", "Pecharunt"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Target::Ursaluna + ) + , LANGUAGE( + "Game Language:
This field is required so we can read IVs.", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , BALL_SELECT( + "Ball Select:", + LockMode::UNLOCK_WHILE_RUNNING, + "poke-ball" + ) + , TRY_TO_TERASTILLIZE( + "Use Terastillization:
Tera at the start of battle.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) +#if 0 + , FILTERS( + StatsHuntIvJudgeFilterTable_Label_Regular, + { + .action = false, + .shiny = false, + .gender = false, + .nature = false, + } + ) +#endif + , FILTERS0( + StatsHuntIvRangeFilterTable_Label_Regular, + { + .action = false, + .shiny = false, + .gender = false, + .nature = false, + } + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ +#if 0 + { + std::vector> ret; + { + auto row = std::make_unique(FILTERS.feature_flags); + row->iv_atk.set(IvJudgeFilter::NoGood); + ret.emplace_back(std::move(row)); + } + { + auto row = std::make_unique(FILTERS.feature_flags); + row->iv_speed.set(IvJudgeFilter::NoGood); + ret.emplace_back(std::move(row)); + } + FILTERS.set_default(std::move(ret)); + } +#endif + { + std::vector> ret; + { + auto row = std::make_unique(FILTERS0); + row->iv_atk.set(0, 1); + ret.emplace_back(std::move(row)); + } + { + auto row = std::make_unique(FILTERS0); + row->iv_speed.set(0, 1); + ret.emplace_back(std::move(row)); + } + FILTERS0.set_default(std::move(ret)); + FILTERS0.restore_defaults(); + } + PA_ADD_STATIC(CALCULATED_IVS); + PA_ADD_OPTION(TARGET); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(TRY_TO_TERASTILLIZE); + PA_ADD_OPTION(FILTERS0); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void StatsResetEventBattle::enter_battle_ursaluna(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + PromptDialogWatcher prompt_detector(COLOR_YELLOW); + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + + // Initiate dialog with Perrin + pbf_press_button(context, BUTTON_A, 10, 50); + int ret = wait_until(env.console, context, Milliseconds(4000), { advance_detector }); + if (ret == 0){ + env.log("Dialog detected."); + }else{ + env.log("Dialog not detected."); + } + // Yes, ready + pbf_mash_button(context, BUTTON_A, 400); + context.wait_for_all_requests(); + + // Mash B until next dialog select + int retPrompt = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { prompt_detector } + ); + if (retPrompt != 0){ + env.log("Failed to detect prompt dialog!", COLOR_RED); + }else{ + env.log("Detected prompt dialog."); + } + context.wait_for_all_requests(); + + // Pick an option to continue + pbf_mash_button(context, BUTTON_A, 400); + context.wait_for_all_requests(); + + // Mash B until next dialog select (again) +// PromptDialogWatcher prompt_detector2(COLOR_YELLOW); + int retPrompt2 = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { prompt_detector } + ); + if (retPrompt2 != 0){ + env.log("Failed to detect prompt (again) dialog!", COLOR_RED); + }else{ + env.log("Detected prompt (again) dialog."); + } + context.wait_for_all_requests(); + + // Pick an option to continue + pbf_mash_button(context, BUTTON_A, 400); + context.wait_for_all_requests(); + + // Now keep going until the battle starts + int ret_battle = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { battle_menu } + ); + if (ret_battle != 0){ + env.log("Failed to detect battle start!", COLOR_RED); + }else{ + env.log("Battle started."); + } + context.wait_for_all_requests(); +} + +void StatsResetEventBattle::enter_battle_pecharunt(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + AdvanceDialogWatcher advance_detector(COLOR_YELLOW); + AdvanceDialogWatcher advance_detector2(COLOR_YELLOW); + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + + // Talk to Pecharunt + pbf_press_button(context, BUTTON_A, 10, 50); + int ret = wait_until(env.console, context, Milliseconds(6000), { advance_detector }); + if (ret == 0){ + env.log("Dialog detected."); + }else{ + env.log("Dialog not detected."); + } + pbf_mash_button(context, BUTTON_A, 400); + context.wait_for_all_requests(); + + // Do you want to challenge the strange pokemon? + int ret2 = wait_until(env.console, context, Milliseconds(6000), { advance_detector2 }); + if (ret2 == 0){ + env.log("Dialog detected."); + }else{ + env.log("Dialog not detected."); + } + // Mash through, answer Yes. + pbf_mash_button(context, BUTTON_A, 500); + context.wait_for_all_requests(); + + // Mash B until the battle starts + // Note - Sending out Ogerpon/Loyal Three during battle adds time, but the below is more than enough. + int ret_battle = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { battle_menu } + ); + if (ret_battle != 0){ + env.log("Failed to detect battle start!", COLOR_RED); + }else{ + env.log("Battle started."); + } + context.wait_for_all_requests(); +} + +bool StatsResetEventBattle::run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); + + // Assuming the player has a charged orb + if (TRY_TO_TERASTILLIZE){ + env.log("Attempting to terastillize."); + //Open move menu + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_R, 20, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + } + + // Repeatedly use first attack + TeraCatchWatcher catch_menu(COLOR_BLUE); + AdvanceDialogWatcher lost(COLOR_YELLOW); + WallClock start = current_time(); + uint8_t switch_party_slot = 1; + + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + while(true){ + if (current_time() - start > std::chrono::minutes(5)){ + env.log("Timed out during battle after 5 minutes.", COLOR_RED); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle after 5 minutes.", + env.console + ); + } + + NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); + SwapMenuWatcher fainted(COLOR_RED); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(90), + { battle_menu, fainted } + ); + switch (ret){ + case 0: + env.log("Detected battle menu. Pressing A to attack..."); + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + break; + case 1: + env.log("Detected fainted Pokemon. Switching to next living Pokemon..."); + if (fainted.move_to_slot(env.console, context, switch_party_slot)){ + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + switch_party_slot++; + } + break; + default: + env.log("Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", COLOR_RED); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Timed out during battle. Stuck, crashed, or took more than 90 seconds for a turn.", + env.console + ); + } + } + }, + { catch_menu, lost } + ); + if (ret == 0){ + env.log("Catch prompt detected."); + + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + BattleBallReader reader(env.console, LANGUAGE); + int quantity = move_to_ball(reader, env.console, context, BALL_SELECT.slug()); + if (quantity == 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find appropriate ball. Did you run out?", + env.console + ); + } + if (quantity < 0){ + stats.errors++; + env.update_stats(); + env.log("Unable to read ball quantity.", COLOR_RED); + } + pbf_mash_button(context, BUTTON_A, 125); + context.wait_for_all_requests(); + + stats.catches++; + env.update_stats(); + env.log("Target caught."); + }else{ + env.log("Battle against target lost.", COLOR_RED); + env.update_stats(); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Battle against target lost." + ); + + return false; + } + return true; +} + + +bool StatsResetEventBattle::check_stats_after_win(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // If this is the first advance dialog, it might be linked to pokedex filling so press A and continue + bool first_advance_dialog = true; + + while (true){ + PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); + PromptDialogWatcher view_summary(COLOR_PURPLE, {0.500, 0.470, 0.400, 0.100}); + PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); + PokemonSummaryWatcher summary(COLOR_MAGENTA); + AdvanceDialogWatcher advance(COLOR_YELLOW); + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, std::chrono::seconds(60), + { + add_to_party, + view_summary, + nickname, + summary, + advance, + } + ); + switch (ret){ + case 0: + env.console.log("Detected add-to-party prompt."); + pbf_press_dpad(context, DPAD_DOWN, 20, 60); + continue; + case 1: + env.console.log("Detected cursor over view summary."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 2: + env.console.log("Detected nickname prompt."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 3:{ + env.console.log("Detected summary."); + VideoOverlaySet overlays(env.console.overlay()); + + SummaryStatsReader reader; + reader.make_overlays(overlays); + + pbf_press_dpad(context, DPAD_RIGHT, 20, 230); + context.wait_for_all_requests(); + + auto snapshot = env.console.video().snapshot(); + IvRanges ivs; + try{ + if (TARGET == Target::Ursaluna){ + ivs = reader.calc_ivs(env.logger(), snapshot, { 113, 70, 120, 135, 65, 52 }); + }else{ + ivs = reader.calc_ivs(env.logger(), snapshot, { 88, 88, 160, 88, 88, 88 }); + } + }catch (OperationFailedException& e){ + send_program_recoverable_error_notification( + env, NOTIFICATION_ERROR_RECOVERABLE, + e.message(), + snapshot + ); + return false; + } + + CALCULATED_IVS.set(ivs); + + StatsHuntAction action; + if (TARGET == Target::Ursaluna){ + action = FILTERS0.get_action(false, StatsHuntGenderFilter::Any, NatureCheckerValue::Hardy, ivs); + }else{ + action = FILTERS0.get_action(false, StatsHuntGenderFilter::Any, NatureCheckerValue::Timid, ivs); + } + + return action != StatsHuntAction::Discard; + } + case 4:{ + if (first_advance_dialog){ + env.console.log("Pressing continue, in case it's a new pokedex entry."); + pbf_press_button(context, BUTTON_A, 20, 105); + first_advance_dialog = false; + continue; + }else{ + StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + env.update_stats(); + throw UserSetupError( + env.logger(), + "Did not detect add-to-party prompt. Make sure your party is full and \"Send to Boxes\" is set to \"Manual\"." + ); + } + } + default: + StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "StatsResetEventBattle::check_stats_after_win(): No state detected after 1 minute.", + env.console + ); + } + } +} + +void StatsResetEventBattle::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + StatsResetEventBattle_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 10); + + while (true){ + if (TARGET == Target::Ursaluna){ + enter_battle_ursaluna(env, context); + }else{ + enter_battle_pecharunt(env, context); + } + + if (run_battle(env, context) && check_stats_after_win(env, context)){ + break; + } + + // Reset + stats.resets++; + env.update_stats(); + send_program_status_notification( + env, NOTIFICATION_STATUS_UPDATE, + "Resetting game." + ); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + } + stats.matches++; + env.update_stats(); + + auto snapshot = env.console.video().snapshot(); + + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "HP: " + (std::string)CALCULATED_IVS.hp + "\n" + + "Atk: " + (std::string)CALCULATED_IVS.atk + "\n" + + "Def: " + (std::string)CALCULATED_IVS.def + "\n" + + "SpAtk: " + (std::string)CALCULATED_IVS.spatk + "\n" + + "SpDef: " + (std::string)CALCULATED_IVS.spdef + "\n" + + "Speed: " + (std::string)CALCULATED_IVS.speed, + snapshot, + true + ); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.h b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.h index b3295aa4a5..a6c9f5a30c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.h +++ b/SerialPrograms/Source/PokemonSV/Programs/General/PokemonSV_StatsResetEventBattle.h @@ -1,89 +1,89 @@ -/* Stats Reset Event Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_StatsResetEventBattle_H -#define PokemonAutomation_PokemonSV_StatsResetEventBattle_H - -#include "Common/Cpp/Options/StringOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -class IvDisplay : public GroupOption{ -public: - IvDisplay(); - - void set(const IvRanges& ivs); - -private: - static std::string get_range_string(const IvRange& range); - -public: - StringOption hp; - StringOption atk; - StringOption def; - StringOption spatk; - StringOption spdef; - StringOption speed; -}; - - -class StatsResetEventBattle_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StatsResetEventBattle_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class StatsResetEventBattle : public SingleSwitchProgramInstance{ -public: - StatsResetEventBattle(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool check_stats_after_win(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - enum class Target{ - Ursaluna, - Pecharunt, - }; - EnumDropdownOption TARGET; - - IvDisplay CALCULATED_IVS; - - OCR::LanguageOCROption LANGUAGE; - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - BooleanCheckBoxOption TRY_TO_TERASTILLIZE; - -// Pokemon::StatsHuntIvJudgeFilterTable FILTERS; - Pokemon::StatsHuntIvRangeFilterTable FILTERS0; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void enter_battle_ursaluna(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void enter_battle_pecharunt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool check_stats(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - -} -} -} -#endif +/* Stats Reset Event Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_StatsResetEventBattle_H +#define PokemonAutomation_PokemonSV_StatsResetEventBattle_H + +#include "Common/Cpp/Options/StringOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +class IvDisplay : public GroupOption{ +public: + IvDisplay(); + + void set(const IvRanges& ivs); + +private: + static std::string get_range_string(const IvRange& range); + +public: + StringOption hp; + StringOption atk; + StringOption def; + StringOption spatk; + StringOption spdef; + StringOption speed; +}; + + +class StatsResetEventBattle_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StatsResetEventBattle_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class StatsResetEventBattle : public SingleSwitchProgramInstance{ +public: + StatsResetEventBattle(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool check_stats_after_win(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + enum class Target{ + Ursaluna, + Pecharunt, + }; + EnumDropdownOption TARGET; + + IvDisplay CALCULATED_IVS; + + OCR::LanguageOCROption LANGUAGE; + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + BooleanCheckBoxOption TRY_TO_TERASTILLIZE; + +// Pokemon::StatsHuntIvJudgeFilterTable FILTERS; + Pokemon::StatsHuntIvRangeFilterTable FILTERS0; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void enter_battle_ursaluna(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void enter_battle_pecharunt(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool run_battle(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool check_stats(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.cpp b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.cpp index 15351410f8..e8ed2990ce 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.cpp @@ -1,326 +1,326 @@ -/* Clone Items - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_CloneItems-1.0.1.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -CloneItems101_Descriptor::CloneItems101_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:CloneItems1.0.1", - STRING_POKEMON + " SV", "Clone Items (1.0.1)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/CloneItems-101.md", - "Clone items using the add-to-party glitch.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - } - ) -{} -struct CloneItems101_Descriptor::Stats : public StatsTracker{ - Stats() - : m_cloned(m_stats["Cloned"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Cloned"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_cloned; - std::atomic& m_errors; -}; -std::unique_ptr CloneItems101_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -class BattleTeamDetector{ -public: - BattleTeamDetector() - : m_slot1(0.024, 0.187 + 0 * 0.1166, 0.005, 0.100) - , m_slot2(0.024, 0.187 + 1 * 0.1166, 0.005, 0.100) - , m_slot3(0.024, 0.187 + 2 * 0.1166, 0.005, 0.100) - , m_slot4(0.024, 0.187 + 3 * 0.1166, 0.005, 0.100) - , m_slot5(0.024, 0.187 + 4 * 0.1166, 0.005, 0.100) - , m_slot6(0.024, 0.187 + 5 * 0.1166, 0.005, 0.100) - {} - - bool detect(const ImageViewRGB32& screen) const{ - ImageStats stats1 = image_stats(extract_box_reference(screen, m_slot1)); -// cout << stats0.average << stats0.stddev << endl; - if (!is_white(stats1, 500, 20)) return false; - ImageStats stats2 = image_stats(extract_box_reference(screen, m_slot2)); - if (!is_white(stats2, 500, 20)) return false; - ImageStats stats3 = image_stats(extract_box_reference(screen, m_slot3)); - if (!is_white(stats3, 500, 20)) return false; - ImageStats stats4 = image_stats(extract_box_reference(screen, m_slot4)); - if (!is_white(stats4, 500, 20)) return false; - ImageStats stats5 = image_stats(extract_box_reference(screen, m_slot5)); - if (!is_white(stats5, 500, 20)) return false; - ImageStats stats6 = image_stats(extract_box_reference(screen, m_slot6)); - if (!is_white(stats6, 500, 20)) return false; - return true; - } - -private: - ImageFloatBox m_slot1; - ImageFloatBox m_slot2; - ImageFloatBox m_slot3; - ImageFloatBox m_slot4; - ImageFloatBox m_slot5; - ImageFloatBox m_slot6; -}; - - - -CloneItems101::CloneItems101() - : GO_HOME_WHEN_DONE(false) - , ITEMS_TO_CLONE( - "Items to Clone:
Clone this many time.", - LockMode::UNLOCK_WHILE_RUNNING, - 999, 1, 999 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(ITEMS_TO_CLONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -bool CloneItems101::clone_item(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ - CloneItems101_Descriptor::Stats& stats = env.current_stats(); - - bool item_held = false; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "CloneItemFailed", - "Failed to clone an item after 5 minutes." - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - MainMenuWatcher main_menu(COLOR_YELLOW); - GradientArrowWatcher party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); - GradientArrowWatcher party_select_return(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.57, 0.10, 0.08}); - GradientArrowWatcher party_select_back(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.64, 0.10, 0.08}); - AdvanceDialogWatcher dialog(COLOR_CYAN); - GradientArrowWatcher box_slot_one(COLOR_BLUE, GradientArrowType::DOWN, {0.24, 0.16, 0.05, 0.09}); - - PromptDialogDetector return_to_ride_prompt(COLOR_DARKGREEN, {0.500, 0.545, 0.400, 0.100}); - BattleTeamDetector battle_team; - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - { - overworld, - main_menu, - party_select_top, - party_select_return, - party_select_back, - dialog, - box_slot_one, - } - ); - context.wait_for(std::chrono::milliseconds(50)); - - switch (ret){ - case 0: - stream.log("Detected overworld. (unexpected)", COLOR_RED); - stats.m_errors++; - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - case 1: - stream.log("Detected main menu."); - try{ - if (item_held){ - main_menu.move_cursor(env.program_info(), stream, context, MenuSide::RIGHT, 1, true); - pbf_press_button(context, BUTTON_A, 20, 20); - }else{ - main_menu.move_cursor(env.program_info(), stream, context, MenuSide::LEFT, 1, true); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_dpad(context, DPAD_UP, 20, 10); - pbf_press_button(context, BUTTON_A, 20, 20); - } - }catch (OperationFailedException& e){ - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - } - continue; - case 2: - stream.log("Detected 6th slot select top. (unexpected)", COLOR_RED); - stats.m_errors++; - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_dpad(context, DPAD_UP, 10, 10); - continue; - case 3: - stream.log("Detected 6th slot select return. (unexpected)", COLOR_RED); - stats.m_errors++; - pbf_press_button(context, BUTTON_A, 20, 20); - continue; - case 4: - stream.log("Detected 6th slot select back. (unexpected)", COLOR_RED); - stats.m_errors++; - pbf_press_dpad(context, DPAD_UP, 20, 30); - continue; - case 5:{ - stream.log("Detected dialog."); - - // Resolve ambiguities. - VideoSnapshot snapshot = stream.video().snapshot(); - - // Confirmation prompt for returning your ride back to ride form. - if (return_to_ride_prompt.detect(snapshot)){ - pbf_press_button(context, BUTTON_A, 20, 20); - item_held = true; - continue; - } - - // No other recognized ambiguities. - pbf_press_button(context, BUTTON_B, 20, 20); - continue; - } - case 6:{ - stream.log("Detected box slot 1."); - - if (!item_held){ - pbf_press_button(context, BUTTON_B, 20, 105); -// continue; - return true; - } - - VideoSnapshot snapshot = stream.video().snapshot(); - - // Not on the battle teams. - if (!battle_team.detect(snapshot)){ - pbf_press_button(context, BUTTON_X, 20, 10); - pbf_press_button(context, BUTTON_X, 20, 10); - continue; - } - - pbf_press_button(context, BUTTON_L, 20, 40); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_button(context, BUTTON_A, 20, 50); - item_held = false; - - continue; - } - default: - stats.m_errors++; - stream.log("No recognized state after 10 seconds.", COLOR_RED); - return false; -// dump_image_and_throw_recoverable_exception( -// env, console, NOTIFICATION_ERROR_RECOVERABLE, -// "CloneItemNoState", "No recognized state after 10 seconds." -// ); - } - - } -} - -void CloneItems101::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - CloneItems101_Descriptor::Stats& stats = env.current_stats(); - - for (uint16_t cloned = 0; cloned < ITEMS_TO_CLONE;){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (clone_item(env, env.console, context)){ - cloned++; - stats.m_cloned++; - continue; - } -#if 0 - try{ - clone_item(env, env.console, context); - cloned++; - stats.m_cloned++; - continue; - }catch (OperationFailedException& e){ - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - } -#endif - - env.console.log("Attempting to recover by backing out to a known state.", COLOR_RED); - - OverworldWatcher overworld(env.console, COLOR_RED); - MainMenuWatcher main_menu(COLOR_YELLOW); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_B, 20, 230); - } - }, - {overworld, main_menu} - ); - context.wait_for(std::chrono::milliseconds(50)); - if (ret < 0){ - throw_and_log( - env.console, ErrorReport::SEND_ERROR_REPORT, - "Unable to recover from error state.", - env.console - ); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - -} -} -} +/* Clone Items + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_CloneItems-1.0.1.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +CloneItems101_Descriptor::CloneItems101_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:CloneItems1.0.1", + STRING_POKEMON + " SV", "Clone Items (1.0.1)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/CloneItems-101.md", + "Clone items using the add-to-party glitch.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + } + ) +{} +struct CloneItems101_Descriptor::Stats : public StatsTracker{ + Stats() + : m_cloned(m_stats["Cloned"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Cloned"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_cloned; + std::atomic& m_errors; +}; +std::unique_ptr CloneItems101_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +class BattleTeamDetector{ +public: + BattleTeamDetector() + : m_slot1(0.024, 0.187 + 0 * 0.1166, 0.005, 0.100) + , m_slot2(0.024, 0.187 + 1 * 0.1166, 0.005, 0.100) + , m_slot3(0.024, 0.187 + 2 * 0.1166, 0.005, 0.100) + , m_slot4(0.024, 0.187 + 3 * 0.1166, 0.005, 0.100) + , m_slot5(0.024, 0.187 + 4 * 0.1166, 0.005, 0.100) + , m_slot6(0.024, 0.187 + 5 * 0.1166, 0.005, 0.100) + {} + + bool detect(const ImageViewRGB32& screen) const{ + ImageStats stats1 = image_stats(extract_box_reference(screen, m_slot1)); +// cout << stats0.average << stats0.stddev << endl; + if (!is_white(stats1, 500, 20)) return false; + ImageStats stats2 = image_stats(extract_box_reference(screen, m_slot2)); + if (!is_white(stats2, 500, 20)) return false; + ImageStats stats3 = image_stats(extract_box_reference(screen, m_slot3)); + if (!is_white(stats3, 500, 20)) return false; + ImageStats stats4 = image_stats(extract_box_reference(screen, m_slot4)); + if (!is_white(stats4, 500, 20)) return false; + ImageStats stats5 = image_stats(extract_box_reference(screen, m_slot5)); + if (!is_white(stats5, 500, 20)) return false; + ImageStats stats6 = image_stats(extract_box_reference(screen, m_slot6)); + if (!is_white(stats6, 500, 20)) return false; + return true; + } + +private: + ImageFloatBox m_slot1; + ImageFloatBox m_slot2; + ImageFloatBox m_slot3; + ImageFloatBox m_slot4; + ImageFloatBox m_slot5; + ImageFloatBox m_slot6; +}; + + + +CloneItems101::CloneItems101() + : GO_HOME_WHEN_DONE(false) + , ITEMS_TO_CLONE( + "Items to Clone:
Clone this many time.", + LockMode::UNLOCK_WHILE_RUNNING, + 999, 1, 999 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(ITEMS_TO_CLONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +bool CloneItems101::clone_item(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context){ + CloneItems101_Descriptor::Stats& stats = env.current_stats(); + + bool item_held = false; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "CloneItemFailed", + "Failed to clone an item after 5 minutes." + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + MainMenuWatcher main_menu(COLOR_YELLOW); + GradientArrowWatcher party_select_top(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.27, 0.10, 0.08}); + GradientArrowWatcher party_select_return(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.57, 0.10, 0.08}); + GradientArrowWatcher party_select_back(COLOR_GREEN, GradientArrowType::RIGHT, {0.30, 0.64, 0.10, 0.08}); + AdvanceDialogWatcher dialog(COLOR_CYAN); + GradientArrowWatcher box_slot_one(COLOR_BLUE, GradientArrowType::DOWN, {0.24, 0.16, 0.05, 0.09}); + + PromptDialogDetector return_to_ride_prompt(COLOR_DARKGREEN, {0.500, 0.545, 0.400, 0.100}); + BattleTeamDetector battle_team; + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + { + overworld, + main_menu, + party_select_top, + party_select_return, + party_select_back, + dialog, + box_slot_one, + } + ); + context.wait_for(std::chrono::milliseconds(50)); + + switch (ret){ + case 0: + stream.log("Detected overworld. (unexpected)", COLOR_RED); + stats.m_errors++; + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + case 1: + stream.log("Detected main menu."); + try{ + if (item_held){ + main_menu.move_cursor(env.program_info(), stream, context, MenuSide::RIGHT, 1, true); + pbf_press_button(context, BUTTON_A, 20, 20); + }else{ + main_menu.move_cursor(env.program_info(), stream, context, MenuSide::LEFT, 1, true); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_dpad(context, DPAD_UP, 20, 10); + pbf_press_button(context, BUTTON_A, 20, 20); + } + }catch (OperationFailedException& e){ + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + } + continue; + case 2: + stream.log("Detected 6th slot select top. (unexpected)", COLOR_RED); + stats.m_errors++; + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_dpad(context, DPAD_UP, 10, 10); + continue; + case 3: + stream.log("Detected 6th slot select return. (unexpected)", COLOR_RED); + stats.m_errors++; + pbf_press_button(context, BUTTON_A, 20, 20); + continue; + case 4: + stream.log("Detected 6th slot select back. (unexpected)", COLOR_RED); + stats.m_errors++; + pbf_press_dpad(context, DPAD_UP, 20, 30); + continue; + case 5:{ + stream.log("Detected dialog."); + + // Resolve ambiguities. + VideoSnapshot snapshot = stream.video().snapshot(); + + // Confirmation prompt for returning your ride back to ride form. + if (return_to_ride_prompt.detect(snapshot)){ + pbf_press_button(context, BUTTON_A, 20, 20); + item_held = true; + continue; + } + + // No other recognized ambiguities. + pbf_press_button(context, BUTTON_B, 20, 20); + continue; + } + case 6:{ + stream.log("Detected box slot 1."); + + if (!item_held){ + pbf_press_button(context, BUTTON_B, 20, 105); +// continue; + return true; + } + + VideoSnapshot snapshot = stream.video().snapshot(); + + // Not on the battle teams. + if (!battle_team.detect(snapshot)){ + pbf_press_button(context, BUTTON_X, 20, 10); + pbf_press_button(context, BUTTON_X, 20, 10); + continue; + } + + pbf_press_button(context, BUTTON_L, 20, 40); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_button(context, BUTTON_A, 20, 50); + item_held = false; + + continue; + } + default: + stats.m_errors++; + stream.log("No recognized state after 10 seconds.", COLOR_RED); + return false; +// dump_image_and_throw_recoverable_exception( +// env, console, NOTIFICATION_ERROR_RECOVERABLE, +// "CloneItemNoState", "No recognized state after 10 seconds." +// ); + } + + } +} + +void CloneItems101::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + CloneItems101_Descriptor::Stats& stats = env.current_stats(); + + for (uint16_t cloned = 0; cloned < ITEMS_TO_CLONE;){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (clone_item(env, env.console, context)){ + cloned++; + stats.m_cloned++; + continue; + } +#if 0 + try{ + clone_item(env, env.console, context); + cloned++; + stats.m_cloned++; + continue; + }catch (OperationFailedException& e){ + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + } +#endif + + env.console.log("Attempting to recover by backing out to a known state.", COLOR_RED); + + OverworldWatcher overworld(env.console, COLOR_RED); + MainMenuWatcher main_menu(COLOR_YELLOW); + context.wait_for_all_requests(); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_B, 20, 230); + } + }, + {overworld, main_menu} + ); + context.wait_for(std::chrono::milliseconds(50)); + if (ret < 0){ + throw_and_log( + env.console, ErrorReport::SEND_ERROR_REPORT, + "Unable to recover from error state.", + env.console + ); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.h b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.h index 754fe542d5..9c66e84bcb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_CloneItems-1.0.1.h @@ -1,58 +1,58 @@ -/* Clone Items - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_CloneItems_H -#define PokemonAutomation_PokemonSV_CloneItems_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class CloneItems101_Descriptor : public SingleSwitchProgramDescriptor{ -public: - CloneItems101_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class CloneItems101 : public SingleSwitchProgramInstance{ -public: - CloneItems101(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - // Returns true on success. - bool clone_item(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - SimpleIntegerOption ITEMS_TO_CLONE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Clone Items + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_CloneItems_H +#define PokemonAutomation_PokemonSV_CloneItems_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class CloneItems101_Descriptor : public SingleSwitchProgramDescriptor{ +public: + CloneItems101_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class CloneItems101 : public SingleSwitchProgramInstance{ +public: + CloneItems101(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + // Returns true on success. + bool clone_item(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + SimpleIntegerOption ITEMS_TO_CLONE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.cpp b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.cpp index d5a91ee420..f6fd23072f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.cpp @@ -1,535 +1,535 @@ -/* Egg Fetcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" -#include "PokemonSV_RideCloner-1.0.1.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -RideCloner101_Descriptor::RideCloner101_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:RideCloner1.0.1", - STRING_POKEMON + " SV", "Ride Cloner (1.0.1)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/RideCloner-101.md", - "Clone your ride legendary (and its item) using the add-to-party glitch.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - } - ) -{} -struct RideCloner101_Descriptor::Stats : public StatsTracker{ - Stats() - : m_skips(m_stats["Date Skips"]) -// , m_raids(m_stats["Raids"]) - , m_wins(m_stats["Wins"]) - , m_losses(m_stats["Losses"]) - , m_skipped(m_stats["Skipped"]) - , m_errors(m_stats["Errors"]) - , m_shinies(m_stats["Shinies"]) - , m_cloned(m_stats["Cloned"]) - , m_failed(m_stats["Failed"]) - { - m_display_order.emplace_back("Date Skips"); -// m_display_order.emplace_back("Raids"); - m_display_order.emplace_back("Wins"); - m_display_order.emplace_back("Losses"); - m_display_order.emplace_back("Skipped"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Cloned"); - m_display_order.emplace_back("Failed", HIDDEN_IF_ZERO); - } - std::atomic& m_skips; -// std::atomic& m_raids; - std::atomic& m_wins; - std::atomic& m_losses; - std::atomic& m_skipped; - std::atomic& m_errors; - std::atomic& m_shinies; - std::atomic& m_cloned; - std::atomic& m_failed; -}; -std::unique_ptr RideCloner101_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -RideCloner101::RideCloner101() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:", - PokemonNameReader::instance().languages(), - LockMode::UNLOCK_WHILE_RUNNING - ) - , MODE( - "Mode:", - { - {Mode::CLONE_ONLY, "clone-only", "Clone only. Don't stop on a shiny raid."}, - {Mode::SHINY_HUNT, "shiny-hunt", "Shiny Hunt: Save before each raid and catch. Stop if shiny."}, - }, - LockMode::LOCK_WHILE_RUNNING, - Mode::SHINY_HUNT - ) - , RIDES_TO_CLONE( - "Rides to Clone:
Stop program after cloning this many times. Make sure you have enough box space for twice this amount.", - LockMode::UNLOCK_WHILE_RUNNING, - 100, 1, 100 - ) - , MAX_STARS( - "Max Stars:
Skip raids with more than this many stars to save time since you're likely to lose.", - LockMode::UNLOCK_WHILE_RUNNING, - 4, 1, 7 - ) - , BALL_SELECT( - "Ball Select:", - LockMode::UNLOCK_WHILE_RUNNING, - "poke-ball" - ) - , FIX_TIME_ON_CATCH( - "Fix Clock on Catch:
Fix the time when catching so the caught date will be correct.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) - , A_TO_B_DELAY0( - "A-to-B Delay:
The delay between the critical A-to-B press that activates the glitch.", - LockMode::UNLOCK_WHILE_RUNNING, - "64ms" - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_NONSHINY, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(RIDES_TO_CLONE); - PA_ADD_OPTION(MAX_STARS); - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(FIX_TIME_ON_CATCH); - PA_ADD_OPTION(A_TO_B_DELAY0); - PA_ADD_OPTION(BATTLE_AI); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -// Start from the overworld with 5 (non-ride legendary) Pokemon in your -// party. Move your ride legendary into the 6th slot in your party. -void RideCloner101::setup(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Running setup..."); - - bool in_party = false; - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception(info, stream, "RideCloneSetupFailed", "Failed to setup after 5 minutes."); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - MainMenuWatcher main_menu(COLOR_YELLOW); - AdvanceDialogWatcher advance(COLOR_PURPLE); - PromptDialogWatcher prompt(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - { - overworld, - main_menu, - advance, - prompt, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - VideoSnapshot snapshot = stream.video().snapshot(); - - switch (ret){ - case 0: - stream.log("Detected overworld."); - if (in_party){ - return; - } -// pbf_press_button(context, BUTTON_PLUS, 20, 230); - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - case 1: - stream.log("Detected main menu."); - if (advance.detect(snapshot)){ - // If we detect both the dialog and the main menu, it means we - // are selecting who in the party to replace with the ride legendary. - main_menu.move_cursor(info, stream, context, MenuSide::LEFT, 5, false); - pbf_press_button(context, BUTTON_A, 20, 105); - in_party = true; - }else{ - // Otherwise we try to move the ride legendary to the party. - if (main_menu.move_cursor(info, stream, context, MenuSide::LEFT, 6, false)){ - // Success, continue. - pbf_press_button(context, BUTTON_A, 20, 105); - }else{ - // Failed. It's already in our party. - pbf_press_button(context, BUTTON_B, 20, 105); - in_party = true; - } - } - continue; - case 2: - stream.log("Detected dialog."); - if (main_menu.detect(snapshot)){ - // If we detect both the dialog and the main menu, it means we - // are selecting who in the party to replace with the ride legendary. - main_menu.move_cursor(info, stream, context, MenuSide::LEFT, 5, false); - pbf_press_button(context, BUTTON_A, 20, 105); - in_party = true; - }else{ - pbf_press_button(context, BUTTON_A, 20, 105); - } - continue; - case 3: - stream.log("Detected prompt."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - default: - dump_image_and_throw_recoverable_exception(info, stream, "RideCloneSetupFailed", - "setup(): No recognized state after 60 seconds."); - } - } -} -bool RideCloner101::run_post_win( - ProgramEnvironment& env, - ConsoleHandle& console, - ProControllerContext& context -){ - console.log("Running post-win..."); - - RideCloner101_Descriptor::Stats& stats = env.current_stats(); - - if (FIX_TIME_ON_CATCH){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); - } - - TeraResult result = TeraResult::NO_DETECTION; - VideoSnapshot screenshot; - bool add_to_party_menu = false; - bool success = false; - WallClock start = current_time(); - while (true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - env.program_info(), - console, - "RideCloneReturnToOverworldFailed", - "Failed to return to overworld after 5 minutes." - ); - } - - TeraCatchWatcher catch_menu(COLOR_BLUE); - WhiteButtonWatcher next_button( - COLOR_CYAN, - WhiteButton::ButtonA, - {0.8, 0.93, 0.2, 0.07}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::seconds(1) - ); - AdvanceDialogWatcher advance(COLOR_YELLOW); - PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); - PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); - PokemonSummaryWatcher summary(COLOR_MAGENTA); - MainMenuWatcher main_menu(COLOR_BLUE); - OverworldWatcher overworld(console.logger(), COLOR_RED); - context.wait_for_all_requests(); - int ret = wait_until( - console, context, - std::chrono::seconds(60), - { - catch_menu, - next_button, - advance, - add_to_party, - nickname, - summary, - main_menu, - overworld, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0:{ - console.log("Detected catch prompt."); - screenshot = console.video().snapshot(); - - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - BattleBallReader reader(console, LANGUAGE); - int quantity = move_to_ball(reader, console, context, BALL_SELECT.slug()); - if (quantity == 0){ - throw_and_log( - console.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to find appropriate ball. Did you run out?", - console - ); - } - if (quantity < 0){ - console.log("Unable to read ball quantity.", COLOR_RED); - } - pbf_mash_button(context, BUTTON_A, 125); - - continue; - } - case 2: - console.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 3: - console.log("Detected add-to-party prompt."); - add_to_party_menu = true; - if (result == TeraResult::NO_DETECTION){ - pbf_press_dpad(context, DPAD_DOWN, 20, 60); - } - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 4: - console.log("Detected prompt."); - pbf_press_button(context, BUTTON_B, 20, 105); - if (add_to_party_menu){ - success = true; - } - continue; - case 1: - // Next button detector is unreliable. Check if the summary is - // open. If so, fall-through to that. - if (!summary.detect(console.video().snapshot())){ - console.log("Detected possible (A) Next button."); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - console.log("Detected false positive (A) Next button.", COLOR_RED); - case 5: - console.log("Detected summary."); - if (result == TeraResult::NO_DETECTION){ - context.wait_for(std::chrono::milliseconds(500)); - result = run_tera_summary( - env, console, context, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - MODE == Mode::SHINY_HUNT, screenshot, - &stats.m_shinies - ); - } - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 6: - console.log("Detected party swap."); -// context.wait_for(std::chrono::milliseconds(150)); - try{ - if (main_menu.move_cursor(env.program_info(), console, context, MenuSide::LEFT, 5, false)){ - ssf_press_button(context, BUTTON_A, A_TO_B_DELAY0, 160ms); - pbf_press_button(context, BUTTON_B, 20, 230); - } - }catch (OperationFailedException& e){ - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - } - continue; - case 7: - console.log("Detected overworld."); - break; - default: - dump_image_and_throw_recoverable_exception( - env.program_info(), console, "FailedPostRaidWin", - "run_post_win(): No recognized state after 60 seconds." - ); - } - break; - } - - - - - return success; -} - - - - - - - - - - - - - -void RideCloner101::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - RideCloner101_Descriptor::Stats& stats = env.current_stats(); - - - bool first = true; - size_t move_counter = 0; - for (uint16_t items = 0; items < RIDES_TO_CLONE;){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - setup(env.program_info(), env.console, context); - - // Find raid. - while (true){ - env.update_stats(); - if (!first){ - day_skip_from_overworld(env.console, context); - pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); - context.wait_for_all_requests(); - stats.m_skips++; - } - first = false; - - if (!open_raid(env.console, context)){ - continue; - } - context.wait_for(std::chrono::milliseconds(500)); - - VideoSnapshot screen = env.console.video().snapshot(); - TeraCardReader reader(COLOR_RED); - size_t stars = reader.stars(env.logger(),env.program_info(), screen); - if (stars != 0){ - env.log("Detected " + std::to_string(stars) + " star raid.", COLOR_PURPLE); - } - - if (stars > MAX_STARS){ - env.log("Skipping raid...", COLOR_ORANGE); - stats.m_skipped++; - close_raid(env.program_info(), env.console, context); - continue; - } - - // Reopen the raid if we need to do stuff. - bool fix_position = move_counter % 5 == 1; - Mode mode = MODE; - if (fix_position || mode == Mode::SHINY_HUNT){ - close_raid(env.program_info(), env.console, context); - - // Save game because we're shiny-hunting. - if (mode == Mode::SHINY_HUNT){ - save_game_from_overworld(env.program_info(), env.console, context); - } - - // Fix our position. - if (fix_position){ - pbf_move_left_joystick(context, 128, 255, 150, 0); - pbf_move_left_joystick(context, 128, 0, 200, 0); - } - - context.wait_for_all_requests(); - if (open_raid(env.console, context)){ - env.log("Tera raid found!", COLOR_BLUE); - }else{ - env.log("No Tera raid found.", COLOR_ORANGE); - continue; - } - } - - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_mash_button(context, BUTTON_A, 250); - - bool win = run_tera_battle(env, env.console, context, BATTLE_AI); - - if (win){ - stats.m_wins++; - }else{ - stats.m_losses++; - context.wait_for(std::chrono::seconds(3)); - continue; - } - - break; - } - - if (run_post_win(env, env.console, context)){ - items++; - stats.m_cloned++; - pbf_press_button(context, BUTTON_PLUS, 20, 230); - }else{ - stats.m_failed++; - } - - move_counter++; - } - - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - - -} -} -} +/* Egg Fetcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" +#include "PokemonSV_RideCloner-1.0.1.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +RideCloner101_Descriptor::RideCloner101_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:RideCloner1.0.1", + STRING_POKEMON + " SV", "Ride Cloner (1.0.1)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/RideCloner-101.md", + "Clone your ride legendary (and its item) using the add-to-party glitch.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + } + ) +{} +struct RideCloner101_Descriptor::Stats : public StatsTracker{ + Stats() + : m_skips(m_stats["Date Skips"]) +// , m_raids(m_stats["Raids"]) + , m_wins(m_stats["Wins"]) + , m_losses(m_stats["Losses"]) + , m_skipped(m_stats["Skipped"]) + , m_errors(m_stats["Errors"]) + , m_shinies(m_stats["Shinies"]) + , m_cloned(m_stats["Cloned"]) + , m_failed(m_stats["Failed"]) + { + m_display_order.emplace_back("Date Skips"); +// m_display_order.emplace_back("Raids"); + m_display_order.emplace_back("Wins"); + m_display_order.emplace_back("Losses"); + m_display_order.emplace_back("Skipped"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Cloned"); + m_display_order.emplace_back("Failed", HIDDEN_IF_ZERO); + } + std::atomic& m_skips; +// std::atomic& m_raids; + std::atomic& m_wins; + std::atomic& m_losses; + std::atomic& m_skipped; + std::atomic& m_errors; + std::atomic& m_shinies; + std::atomic& m_cloned; + std::atomic& m_failed; +}; +std::unique_ptr RideCloner101_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +RideCloner101::RideCloner101() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:", + PokemonNameReader::instance().languages(), + LockMode::UNLOCK_WHILE_RUNNING + ) + , MODE( + "Mode:", + { + {Mode::CLONE_ONLY, "clone-only", "Clone only. Don't stop on a shiny raid."}, + {Mode::SHINY_HUNT, "shiny-hunt", "Shiny Hunt: Save before each raid and catch. Stop if shiny."}, + }, + LockMode::LOCK_WHILE_RUNNING, + Mode::SHINY_HUNT + ) + , RIDES_TO_CLONE( + "Rides to Clone:
Stop program after cloning this many times. Make sure you have enough box space for twice this amount.", + LockMode::UNLOCK_WHILE_RUNNING, + 100, 1, 100 + ) + , MAX_STARS( + "Max Stars:
Skip raids with more than this many stars to save time since you're likely to lose.", + LockMode::UNLOCK_WHILE_RUNNING, + 4, 1, 7 + ) + , BALL_SELECT( + "Ball Select:", + LockMode::UNLOCK_WHILE_RUNNING, + "poke-ball" + ) + , FIX_TIME_ON_CATCH( + "Fix Clock on Catch:
Fix the time when catching so the caught date will be correct.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) + , A_TO_B_DELAY0( + "A-to-B Delay:
The delay between the critical A-to-B press that activates the glitch.", + LockMode::UNLOCK_WHILE_RUNNING, + "64ms" + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_NONSHINY, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(RIDES_TO_CLONE); + PA_ADD_OPTION(MAX_STARS); + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(FIX_TIME_ON_CATCH); + PA_ADD_OPTION(A_TO_B_DELAY0); + PA_ADD_OPTION(BATTLE_AI); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +// Start from the overworld with 5 (non-ride legendary) Pokemon in your +// party. Move your ride legendary into the 6th slot in your party. +void RideCloner101::setup(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Running setup..."); + + bool in_party = false; + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception(info, stream, "RideCloneSetupFailed", "Failed to setup after 5 minutes."); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + MainMenuWatcher main_menu(COLOR_YELLOW); + AdvanceDialogWatcher advance(COLOR_PURPLE); + PromptDialogWatcher prompt(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + { + overworld, + main_menu, + advance, + prompt, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + VideoSnapshot snapshot = stream.video().snapshot(); + + switch (ret){ + case 0: + stream.log("Detected overworld."); + if (in_party){ + return; + } +// pbf_press_button(context, BUTTON_PLUS, 20, 230); + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + case 1: + stream.log("Detected main menu."); + if (advance.detect(snapshot)){ + // If we detect both the dialog and the main menu, it means we + // are selecting who in the party to replace with the ride legendary. + main_menu.move_cursor(info, stream, context, MenuSide::LEFT, 5, false); + pbf_press_button(context, BUTTON_A, 20, 105); + in_party = true; + }else{ + // Otherwise we try to move the ride legendary to the party. + if (main_menu.move_cursor(info, stream, context, MenuSide::LEFT, 6, false)){ + // Success, continue. + pbf_press_button(context, BUTTON_A, 20, 105); + }else{ + // Failed. It's already in our party. + pbf_press_button(context, BUTTON_B, 20, 105); + in_party = true; + } + } + continue; + case 2: + stream.log("Detected dialog."); + if (main_menu.detect(snapshot)){ + // If we detect both the dialog and the main menu, it means we + // are selecting who in the party to replace with the ride legendary. + main_menu.move_cursor(info, stream, context, MenuSide::LEFT, 5, false); + pbf_press_button(context, BUTTON_A, 20, 105); + in_party = true; + }else{ + pbf_press_button(context, BUTTON_A, 20, 105); + } + continue; + case 3: + stream.log("Detected prompt."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + default: + dump_image_and_throw_recoverable_exception(info, stream, "RideCloneSetupFailed", + "setup(): No recognized state after 60 seconds."); + } + } +} +bool RideCloner101::run_post_win( + ProgramEnvironment& env, + ConsoleHandle& console, + ProControllerContext& context +){ + console.log("Running post-win..."); + + RideCloner101_Descriptor::Stats& stats = env.current_stats(); + + if (FIX_TIME_ON_CATCH){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); + } + + TeraResult result = TeraResult::NO_DETECTION; + VideoSnapshot screenshot; + bool add_to_party_menu = false; + bool success = false; + WallClock start = current_time(); + while (true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + env.program_info(), + console, + "RideCloneReturnToOverworldFailed", + "Failed to return to overworld after 5 minutes." + ); + } + + TeraCatchWatcher catch_menu(COLOR_BLUE); + WhiteButtonWatcher next_button( + COLOR_CYAN, + WhiteButton::ButtonA, + {0.8, 0.93, 0.2, 0.07}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::seconds(1) + ); + AdvanceDialogWatcher advance(COLOR_YELLOW); + PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); + PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); + PokemonSummaryWatcher summary(COLOR_MAGENTA); + MainMenuWatcher main_menu(COLOR_BLUE); + OverworldWatcher overworld(console.logger(), COLOR_RED); + context.wait_for_all_requests(); + int ret = wait_until( + console, context, + std::chrono::seconds(60), + { + catch_menu, + next_button, + advance, + add_to_party, + nickname, + summary, + main_menu, + overworld, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0:{ + console.log("Detected catch prompt."); + screenshot = console.video().snapshot(); + + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + BattleBallReader reader(console, LANGUAGE); + int quantity = move_to_ball(reader, console, context, BALL_SELECT.slug()); + if (quantity == 0){ + throw_and_log( + console.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to find appropriate ball. Did you run out?", + console + ); + } + if (quantity < 0){ + console.log("Unable to read ball quantity.", COLOR_RED); + } + pbf_mash_button(context, BUTTON_A, 125); + + continue; + } + case 2: + console.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 3: + console.log("Detected add-to-party prompt."); + add_to_party_menu = true; + if (result == TeraResult::NO_DETECTION){ + pbf_press_dpad(context, DPAD_DOWN, 20, 60); + } + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 4: + console.log("Detected prompt."); + pbf_press_button(context, BUTTON_B, 20, 105); + if (add_to_party_menu){ + success = true; + } + continue; + case 1: + // Next button detector is unreliable. Check if the summary is + // open. If so, fall-through to that. + if (!summary.detect(console.video().snapshot())){ + console.log("Detected possible (A) Next button."); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + console.log("Detected false positive (A) Next button.", COLOR_RED); + case 5: + console.log("Detected summary."); + if (result == TeraResult::NO_DETECTION){ + context.wait_for(std::chrono::milliseconds(500)); + result = run_tera_summary( + env, console, context, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + MODE == Mode::SHINY_HUNT, screenshot, + &stats.m_shinies + ); + } + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 6: + console.log("Detected party swap."); +// context.wait_for(std::chrono::milliseconds(150)); + try{ + if (main_menu.move_cursor(env.program_info(), console, context, MenuSide::LEFT, 5, false)){ + ssf_press_button(context, BUTTON_A, A_TO_B_DELAY0, 160ms); + pbf_press_button(context, BUTTON_B, 20, 230); + } + }catch (OperationFailedException& e){ + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + } + continue; + case 7: + console.log("Detected overworld."); + break; + default: + dump_image_and_throw_recoverable_exception( + env.program_info(), console, "FailedPostRaidWin", + "run_post_win(): No recognized state after 60 seconds." + ); + } + break; + } + + + + + return success; +} + + + + + + + + + + + + + +void RideCloner101::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + RideCloner101_Descriptor::Stats& stats = env.current_stats(); + + + bool first = true; + size_t move_counter = 0; + for (uint16_t items = 0; items < RIDES_TO_CLONE;){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + setup(env.program_info(), env.console, context); + + // Find raid. + while (true){ + env.update_stats(); + if (!first){ + day_skip_from_overworld(env.console, context); + pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); + context.wait_for_all_requests(); + stats.m_skips++; + } + first = false; + + if (!open_raid(env.console, context)){ + continue; + } + context.wait_for(std::chrono::milliseconds(500)); + + VideoSnapshot screen = env.console.video().snapshot(); + TeraCardReader reader(COLOR_RED); + size_t stars = reader.stars(env.logger(),env.program_info(), screen); + if (stars != 0){ + env.log("Detected " + std::to_string(stars) + " star raid.", COLOR_PURPLE); + } + + if (stars > MAX_STARS){ + env.log("Skipping raid...", COLOR_ORANGE); + stats.m_skipped++; + close_raid(env.program_info(), env.console, context); + continue; + } + + // Reopen the raid if we need to do stuff. + bool fix_position = move_counter % 5 == 1; + Mode mode = MODE; + if (fix_position || mode == Mode::SHINY_HUNT){ + close_raid(env.program_info(), env.console, context); + + // Save game because we're shiny-hunting. + if (mode == Mode::SHINY_HUNT){ + save_game_from_overworld(env.program_info(), env.console, context); + } + + // Fix our position. + if (fix_position){ + pbf_move_left_joystick(context, 128, 255, 150, 0); + pbf_move_left_joystick(context, 128, 0, 200, 0); + } + + context.wait_for_all_requests(); + if (open_raid(env.console, context)){ + env.log("Tera raid found!", COLOR_BLUE); + }else{ + env.log("No Tera raid found.", COLOR_ORANGE); + continue; + } + } + + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_mash_button(context, BUTTON_A, 250); + + bool win = run_tera_battle(env, env.console, context, BATTLE_AI); + + if (win){ + stats.m_wins++; + }else{ + stats.m_losses++; + context.wait_for(std::chrono::seconds(3)); + continue; + } + + break; + } + + if (run_post_win(env, env.console, context)){ + items++; + stats.m_cloned++; + pbf_press_button(context, BUTTON_PLUS, 20, 230); + }else{ + stats.m_failed++; + } + + move_counter++; + } + + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.h b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.h index 79ab256ed2..db6026dc38 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_RideCloner-1.0.1.h @@ -1,84 +1,84 @@ -/* Ride Cloner - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_RideCloner_H -#define PokemonAutomation_PokemonSV_RideCloner_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class RideCloner101_Descriptor : public SingleSwitchProgramDescriptor{ -public: - RideCloner101_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class RideCloner101 : public SingleSwitchProgramInstance{ -public: - RideCloner101(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void setup(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - bool run_post_win( - ProgramEnvironment& env, - ConsoleHandle& console, - ProControllerContext& context - ); - -private: - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - - enum class Mode{ - CLONE_ONLY, - SHINY_HUNT, - }; - EnumDropdownOption MODE; - - SimpleIntegerOption RIDES_TO_CLONE; - - SimpleIntegerOption MAX_STARS; - - PokemonSwSh::PokemonBallSelectOption BALL_SELECT; - BooleanCheckBoxOption FIX_TIME_ON_CATCH; - - MillisecondsOption A_TO_B_DELAY0; - TeraAIOption BATTLE_AI; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Ride Cloner + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_RideCloner_H +#define PokemonAutomation_PokemonSV_RideCloner_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class RideCloner101_Descriptor : public SingleSwitchProgramDescriptor{ +public: + RideCloner101_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class RideCloner101 : public SingleSwitchProgramInstance{ +public: + RideCloner101(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void setup(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + bool run_post_win( + ProgramEnvironment& env, + ConsoleHandle& console, + ProControllerContext& context + ); + +private: + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + + enum class Mode{ + CLONE_ONLY, + SHINY_HUNT, + }; + EnumDropdownOption MODE; + + SimpleIntegerOption RIDES_TO_CLONE; + + SimpleIntegerOption MAX_STARS; + + PokemonSwSh::PokemonBallSelectOption BALL_SELECT; + BooleanCheckBoxOption FIX_TIME_ON_CATCH; + + MillisecondsOption A_TO_B_DELAY0; + TeraAIOption BATTLE_AI; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp index ff51e3a3aa..5faa402c02 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.cpp @@ -1,471 +1,471 @@ -/* Wild Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_WildItemFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -WildItemFarmer_Descriptor::WildItemFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:WildItemFarmer", - Pokemon::STRING_POKEMON + " SV", "Wild Item Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/WildItemFarmer.md", - "Farm an item held by a wild " + Pokemon::STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - -struct WildItemFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : battles(m_stats["Battles"]) - , items(m_stats["Items Cloned"]) - , failed(m_stats["Clone Failed"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Battles"); - m_display_order.emplace_back("Items Cloned"); - m_display_order.emplace_back("Clone Failed", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& battles; - std::atomic& items; - std::atomic& failed; - std::atomic& errors; -}; -std::unique_ptr WildItemFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -WildItemFarmer::WildItemFarmer() - : ITEMS_TO_CLONE( - "Items to Clone:", - LockMode::UNLOCK_WHILE_RUNNING, - 999, 0, 999 - ) -#if 0 - , TRICK_MOVE_SLOT( - "Trick Move Slot:", - { - {0, "slot1", "Slot 1"}, - {1, "slot2", "Slot 2"}, - {2, "slot3", "Slot 3"}, - {3, "slot4", "Slot 4"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - 0 - ) -#endif - , INITIAL_TRICK_PP( - "Initial Trick PP:", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 0, 16 - ) - , VERIFY_ITEM_CLONED( - "Verify Item Cloned:
Verify each run that the item has actually been cloned. " - "This will slow each iteration by a few seconds, but will better detect errors.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , ENABLE_FORWARD_RUN( - "Forward Run:
Run forward a bit before throwing ball. This will correct for " - "the clone moving away, but may cause your position to wander more.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(ITEMS_TO_CLONE); -// PA_ADD_OPTION(TRICK_MOVE_SLOT); - PA_ADD_OPTION(INITIAL_TRICK_PP); - PA_ADD_OPTION(VERIFY_ITEM_CLONED); - PA_ADD_OPTION(ENABLE_FORWARD_RUN); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void WildItemFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - try{ - run_program(env, context); - }catch (...){ - pbf_press_button(context, BUTTON_HOME, 20, 105); - throw; - } -} - -void WildItemFarmer::refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - int move_overwrites = 0; - bool move_selected = false; - while (true){ - WhiteButtonWatcher summary( - COLOR_RED, WhiteButton::ButtonA, - {0.12, 0.67, 0.20, 0.06}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::milliseconds(500) - ); - AdvanceDialogWatcher dialog(COLOR_RED); - GradientArrowWatcher action_select(COLOR_GREEN, GradientArrowType::RIGHT, {0.515, 0.33, 0.05, 0.09}); - GradientArrowWatcher move_select(COLOR_YELLOW, GradientArrowType::RIGHT, {0.05, 0.20, 0.05, 0.09}); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - { - summary, - dialog, - action_select, - move_select, - } - ); - if (move_overwrites >= 2){ - pbf_mash_button(context, BUTTON_B, 50); - return; - } - - switch (ret){ - case 0: - if (move_selected){ - move_overwrites++; - } - move_selected = false; - env.log("Detected Change Moves button. Overwrite count = " + std::to_string(move_overwrites)); - if (move_overwrites >= 2){ - continue; - } - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 1: - env.log("Detected dialog."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 2: - env.log("Detected action select."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 3: - env.log("Detected move select."); - pbf_press_button(context, BUTTON_A, 20, 105); - move_selected = true; - continue; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected while changing moves after 10 seconds.", - env.console - ); - } - } -} - -bool WildItemFarmer::verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu){ - env.log("Verifying that item has been taken..."); - - while (true){ - SwapMenuWatcher swap_menu(COLOR_BLUE); - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - {battle_menu, swap_menu} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - env.log("Detected battle menu..."); - if (!battle_menu.move_to_slot(env.console, context, 1)){ - return false; - } - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - - case 1: - env.log("Detected swap menu..."); - break; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect " + Pokemon::STRING_POKEMON + " select menu.", - env.console - ); - } - - break; - } - - VideoSnapshot screen = env.console.video().snapshot(); - ImageViewRGB32 box = extract_box_reference(screen, ImageFloatBox(0.28, 0.20, 0.03, 0.055)); - ImageStats stats = image_stats(box); - bool item_held = !is_solid(stats, {0.550405, 0.449595, 0.}, 0.20); - - { - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 500); - }, - {battle_menu} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to back out to battle menu.", - env.console - ); - } - } - - return item_held; -} - - -void WildItemFarmer::run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - WildItemFarmer_Descriptor::Stats& stats = env.current_stats(); - - const std::vector> MANUVERS{ - {128, 0}, - {96, 0}, - {160, 0}, - }; - - uint16_t items_cloned = 0; - bool trick_used = false; - bool overworld_seen = false; - int8_t trick_PP = INITIAL_TRICK_PP; - uint8_t consecutive_throw_attempts = 0; - WallClock last_trick_attempt = WallClock::min(); - while (items_cloned < ITEMS_TO_CLONE){ - OverworldWatcher overworld(env.console, COLOR_CYAN); - NormalBattleMenuWatcher battle_menu(COLOR_RED); - MoveSelectWatcher move_select(COLOR_YELLOW); - MainMenuWatcher main_menu(COLOR_GREEN); - PokemonSummaryWatcher summary(COLOR_BLUE); - - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, std::chrono::seconds(120), - { - overworld, - battle_menu, - move_select, - main_menu, - summary, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - env.log("Detected overworld."); - if (trick_used && trick_PP > 0){ - trick_PP--; - if (!VERIFY_ITEM_CLONED){ - items_cloned++; - stats.items++; - env.update_stats(); - } - } - if (!overworld_seen){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - overworld_seen = true; - trick_used = false; - - env.log("Trick PP: " + std::to_string(trick_PP)); - - if (trick_PP <= 0){ - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - } - - if (consecutive_throw_attempts >= MANUVERS.size()){ - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Failed to start battle after " + std::to_string(MANUVERS.size()) + " attempts.", - env.console - ); - } - - pbf_press_button(context, BUTTON_L, 20, 23); - if (ENABLE_FORWARD_RUN){ - const std::pair& direction = MANUVERS[consecutive_throw_attempts]; - pbf_move_left_joystick(context, (uint8_t)direction.first, (uint8_t)direction.second, 50, 0); - } - pbf_mash_button(context, BUTTON_ZR, 250); - pbf_wait(context, 350); - - consecutive_throw_attempts++; - - continue; - - case 1: - env.log("Detected battle menu."); - if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ - env.log("Unable to use move. Assume out of PP."); - trick_PP = 0; -// pbf_mash_button(context, BUTTON_B, 30); -// continue; - } - - consecutive_throw_attempts = 0; - if (overworld_seen){ - stats.battles++; - env.update_stats(); - } - overworld_seen = false; - - if (trick_used && trick_PP > 0 && VERIFY_ITEM_CLONED){ - if (verify_item_held(env, context, battle_menu)){ - items_cloned++; - stats.items++; - env.update_stats(); - }else{ - stats.failed++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Failed to clone item. Possible incorrect encounter.", - env.console - ); - } - } - - if (trick_used || trick_PP <= 0){ - env.log("Running away..."); - if (battle_menu.move_to_slot(env.console, context, 3)){ - pbf_press_button(context, BUTTON_A, 20, 30); - }else{ - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 125); - } - }else{ - env.log("Attempt to select a move."); - if (battle_menu.move_to_slot(env.console, context, 0)){ - pbf_press_button(context, BUTTON_A, 20, 30); - }else{ - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 125); - } - } - continue; - - case 2: - env.log("Detected move select."); - if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ - env.log("Unable to use move. Assume out of PP."); - trick_PP = 0; - pbf_mash_button(context, BUTTON_B, 30); - continue; - } - if (move_select.move_to_slot(env.console, context, 0)){ - pbf_press_button(context, BUTTON_A, 20, 30); - trick_used = true; - last_trick_attempt = current_time(); - }else{ - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 125); - } - continue; - - case 3: - env.log("Detected main menu."); - if (trick_PP > 0){ - env.log("Backing out to overworld..."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - - if (!main_menu.move_cursor(env.program_info(), env.console, context, MenuSide::LEFT, 0)){ - stats.errors++; - env.update_stats(); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - - env.log("Attempting to enter summary..."); - - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - - continue; - - case 4: - env.log("Detected " + Pokemon::STRING_POKEMON + " summary."); - - if (trick_PP > 0){ - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - - pbf_press_dpad(context, DPAD_RIGHT, 20, 230); - - refresh_pp(env, context); - trick_PP = 10; - - pbf_press_button(context, BUTTON_B, 20, 105); - -// throw ProgramFinishedException(env.console, "Out of PP."); - continue; - - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 120 seconds.", - env.console - ); - } - - - } - - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Wild Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_WildItemFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +WildItemFarmer_Descriptor::WildItemFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:WildItemFarmer", + Pokemon::STRING_POKEMON + " SV", "Wild Item Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/WildItemFarmer.md", + "Farm an item held by a wild " + Pokemon::STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + +struct WildItemFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : battles(m_stats["Battles"]) + , items(m_stats["Items Cloned"]) + , failed(m_stats["Clone Failed"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Battles"); + m_display_order.emplace_back("Items Cloned"); + m_display_order.emplace_back("Clone Failed", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& battles; + std::atomic& items; + std::atomic& failed; + std::atomic& errors; +}; +std::unique_ptr WildItemFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +WildItemFarmer::WildItemFarmer() + : ITEMS_TO_CLONE( + "Items to Clone:", + LockMode::UNLOCK_WHILE_RUNNING, + 999, 0, 999 + ) +#if 0 + , TRICK_MOVE_SLOT( + "Trick Move Slot:", + { + {0, "slot1", "Slot 1"}, + {1, "slot2", "Slot 2"}, + {2, "slot3", "Slot 3"}, + {3, "slot4", "Slot 4"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + 0 + ) +#endif + , INITIAL_TRICK_PP( + "Initial Trick PP:", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 0, 16 + ) + , VERIFY_ITEM_CLONED( + "Verify Item Cloned:
Verify each run that the item has actually been cloned. " + "This will slow each iteration by a few seconds, but will better detect errors.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , ENABLE_FORWARD_RUN( + "Forward Run:
Run forward a bit before throwing ball. This will correct for " + "the clone moving away, but may cause your position to wander more.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(ITEMS_TO_CLONE); +// PA_ADD_OPTION(TRICK_MOVE_SLOT); + PA_ADD_OPTION(INITIAL_TRICK_PP); + PA_ADD_OPTION(VERIFY_ITEM_CLONED); + PA_ADD_OPTION(ENABLE_FORWARD_RUN); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void WildItemFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + try{ + run_program(env, context); + }catch (...){ + pbf_press_button(context, BUTTON_HOME, 20, 105); + throw; + } +} + +void WildItemFarmer::refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + int move_overwrites = 0; + bool move_selected = false; + while (true){ + WhiteButtonWatcher summary( + COLOR_RED, WhiteButton::ButtonA, + {0.12, 0.67, 0.20, 0.06}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::milliseconds(500) + ); + AdvanceDialogWatcher dialog(COLOR_RED); + GradientArrowWatcher action_select(COLOR_GREEN, GradientArrowType::RIGHT, {0.515, 0.33, 0.05, 0.09}); + GradientArrowWatcher move_select(COLOR_YELLOW, GradientArrowType::RIGHT, {0.05, 0.20, 0.05, 0.09}); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + { + summary, + dialog, + action_select, + move_select, + } + ); + if (move_overwrites >= 2){ + pbf_mash_button(context, BUTTON_B, 50); + return; + } + + switch (ret){ + case 0: + if (move_selected){ + move_overwrites++; + } + move_selected = false; + env.log("Detected Change Moves button. Overwrite count = " + std::to_string(move_overwrites)); + if (move_overwrites >= 2){ + continue; + } + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 1: + env.log("Detected dialog."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 2: + env.log("Detected action select."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 3: + env.log("Detected move select."); + pbf_press_button(context, BUTTON_A, 20, 105); + move_selected = true; + continue; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected while changing moves after 10 seconds.", + env.console + ); + } + } +} + +bool WildItemFarmer::verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu){ + env.log("Verifying that item has been taken..."); + + while (true){ + SwapMenuWatcher swap_menu(COLOR_BLUE); + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + {battle_menu, swap_menu} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + env.log("Detected battle menu..."); + if (!battle_menu.move_to_slot(env.console, context, 1)){ + return false; + } + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + + case 1: + env.log("Detected swap menu..."); + break; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect " + Pokemon::STRING_POKEMON + " select menu.", + env.console + ); + } + + break; + } + + VideoSnapshot screen = env.console.video().snapshot(); + ImageViewRGB32 box = extract_box_reference(screen, ImageFloatBox(0.28, 0.20, 0.03, 0.055)); + ImageStats stats = image_stats(box); + bool item_held = !is_solid(stats, {0.550405, 0.449595, 0.}, 0.20); + + { + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 500); + }, + {battle_menu} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to back out to battle menu.", + env.console + ); + } + } + + return item_held; +} + + +void WildItemFarmer::run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + WildItemFarmer_Descriptor::Stats& stats = env.current_stats(); + + const std::vector> MANUVERS{ + {128, 0}, + {96, 0}, + {160, 0}, + }; + + uint16_t items_cloned = 0; + bool trick_used = false; + bool overworld_seen = false; + int8_t trick_PP = INITIAL_TRICK_PP; + uint8_t consecutive_throw_attempts = 0; + WallClock last_trick_attempt = WallClock::min(); + while (items_cloned < ITEMS_TO_CLONE){ + OverworldWatcher overworld(env.console, COLOR_CYAN); + NormalBattleMenuWatcher battle_menu(COLOR_RED); + MoveSelectWatcher move_select(COLOR_YELLOW); + MainMenuWatcher main_menu(COLOR_GREEN); + PokemonSummaryWatcher summary(COLOR_BLUE); + + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, std::chrono::seconds(120), + { + overworld, + battle_menu, + move_select, + main_menu, + summary, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + env.log("Detected overworld."); + if (trick_used && trick_PP > 0){ + trick_PP--; + if (!VERIFY_ITEM_CLONED){ + items_cloned++; + stats.items++; + env.update_stats(); + } + } + if (!overworld_seen){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + overworld_seen = true; + trick_used = false; + + env.log("Trick PP: " + std::to_string(trick_PP)); + + if (trick_PP <= 0){ + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + } + + if (consecutive_throw_attempts >= MANUVERS.size()){ + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Failed to start battle after " + std::to_string(MANUVERS.size()) + " attempts.", + env.console + ); + } + + pbf_press_button(context, BUTTON_L, 20, 23); + if (ENABLE_FORWARD_RUN){ + const std::pair& direction = MANUVERS[consecutive_throw_attempts]; + pbf_move_left_joystick(context, (uint8_t)direction.first, (uint8_t)direction.second, 50, 0); + } + pbf_mash_button(context, BUTTON_ZR, 250); + pbf_wait(context, 350); + + consecutive_throw_attempts++; + + continue; + + case 1: + env.log("Detected battle menu."); + if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ + env.log("Unable to use move. Assume out of PP."); + trick_PP = 0; +// pbf_mash_button(context, BUTTON_B, 30); +// continue; + } + + consecutive_throw_attempts = 0; + if (overworld_seen){ + stats.battles++; + env.update_stats(); + } + overworld_seen = false; + + if (trick_used && trick_PP > 0 && VERIFY_ITEM_CLONED){ + if (verify_item_held(env, context, battle_menu)){ + items_cloned++; + stats.items++; + env.update_stats(); + }else{ + stats.failed++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Failed to clone item. Possible incorrect encounter.", + env.console + ); + } + } + + if (trick_used || trick_PP <= 0){ + env.log("Running away..."); + if (battle_menu.move_to_slot(env.console, context, 3)){ + pbf_press_button(context, BUTTON_A, 20, 30); + }else{ + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 125); + } + }else{ + env.log("Attempt to select a move."); + if (battle_menu.move_to_slot(env.console, context, 0)){ + pbf_press_button(context, BUTTON_A, 20, 30); + }else{ + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 125); + } + } + continue; + + case 2: + env.log("Detected move select."); + if (current_time() - std::chrono::seconds(5) < last_trick_attempt){ + env.log("Unable to use move. Assume out of PP."); + trick_PP = 0; + pbf_mash_button(context, BUTTON_B, 30); + continue; + } + if (move_select.move_to_slot(env.console, context, 0)){ + pbf_press_button(context, BUTTON_A, 20, 30); + trick_used = true; + last_trick_attempt = current_time(); + }else{ + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 125); + } + continue; + + case 3: + env.log("Detected main menu."); + if (trick_PP > 0){ + env.log("Backing out to overworld..."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + + if (!main_menu.move_cursor(env.program_info(), env.console, context, MenuSide::LEFT, 0)){ + stats.errors++; + env.update_stats(); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + + env.log("Attempting to enter summary..."); + + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + + continue; + + case 4: + env.log("Detected " + Pokemon::STRING_POKEMON + " summary."); + + if (trick_PP > 0){ + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + + pbf_press_dpad(context, DPAD_RIGHT, 20, 230); + + refresh_pp(env, context); + trick_PP = 10; + + pbf_press_button(context, BUTTON_B, 20, 105); + +// throw ProgramFinishedException(env.console, "Out of PP."); + continue; + + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 120 seconds.", + env.console + ); + } + + + } + + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h index 396532485d..1c6ef9964a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Glitches/PokemonSV_WildItemFarmer.h @@ -1,55 +1,55 @@ -/* Wild Item Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_WildItemFarmer_H -#define PokemonAutomation_PokemonSwSh_WildItemFarmer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class NormalBattleMenuWatcher; - - -class WildItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - WildItemFarmer_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class WildItemFarmer : public SingleSwitchProgramInstance{ -public: - WildItemFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - bool verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu); - void run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - SimpleIntegerOption ITEMS_TO_CLONE; -// IntegerEnumDropdownOption TRICK_MOVE_SLOT; - SimpleIntegerOption INITIAL_TRICK_PP; - BooleanCheckBoxOption VERIFY_ITEM_CLONED; - BooleanCheckBoxOption ENABLE_FORWARD_RUN; - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - -} -} -} -#endif - - - +/* Wild Item Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_WildItemFarmer_H +#define PokemonAutomation_PokemonSwSh_WildItemFarmer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class NormalBattleMenuWatcher; + + +class WildItemFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + WildItemFarmer_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class WildItemFarmer : public SingleSwitchProgramInstance{ +public: + WildItemFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void refresh_pp(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + bool verify_item_held(SingleSwitchProgramEnvironment& env, ProControllerContext& context, NormalBattleMenuWatcher& battle_menu); + void run_program(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + SimpleIntegerOption ITEMS_TO_CLONE; +// IntegerEnumDropdownOption TRICK_MOVE_SLOT; + SimpleIntegerOption INITIAL_TRICK_PP; + BooleanCheckBoxOption VERIFY_ITEM_CLONED; + BooleanCheckBoxOption ENABLE_FORWARD_RUN; + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp index 5caf2fd1ac..7b54f600e6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.cpp @@ -1,163 +1,163 @@ -/* Auto Item Printer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_ItemPrinterTools.h" -#include "PokemonSV_AutoItemPrinter.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - - -AutoItemPrinter_Descriptor::AutoItemPrinter_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:AutoItemPrinter", - STRING_POKEMON + " SV", "Auto Item Printer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoItemPrinter.md", - "Automate the Item Printer for rare items.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct AutoItemPrinter_Descriptor::Stats : public StatsTracker{ - Stats() - : m_rounds(m_stats["Rounds"]) - { - m_display_order.emplace_back("Rounds"); - } - std::atomic& m_rounds; -}; -std::unique_ptr AutoItemPrinter_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -AutoItemPrinter::AutoItemPrinter() - : LANGUAGE( - "Game Language:", - PokemonSwSh::IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NUM_ROUNDS( - "Number of Rounds to Run:", - LockMode::UNLOCK_WHILE_RUNNING, - 100 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(NUM_ROUNDS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void AutoItemPrinter::enter_printing_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - env.console.log("Entering printing mode..."); - - while (true){ - OverworldWatcher overworld(env.console, COLOR_CYAN); - AdvanceDialogWatcher dialog(COLOR_YELLOW); - PromptDialogWatcher prompt(COLOR_YELLOW); - WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); - context.wait_for_all_requests(); - - int ret_printer_entry = wait_until( - env.console, context, - std::chrono::seconds(120), - { material, overworld, dialog, prompt } - ); - context.wait_for_all_requests(); - - switch (ret_printer_entry){ - case 0: // material - env.console.log("Material selection screen detected."); - return; - case 1: // overworld - case 2: // dialog - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 3: // prompt - env.console.log("Prompt detected."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_printing_mode(): No recognized state after 120 seconds.", - env.console - ); - } - } -} - - - - -void AutoItemPrinter::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - AutoItemPrinter_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 0); - - enter_printing_mode(env, context); - - for (uint16_t i = 0; i < NUM_ROUNDS; i++){ - item_printer_start_print( - env.normal_inference_dispatcher(), - env.console, context, LANGUAGE, - ItemPrinterJobs::Jobs_10 - ); - item_printer_finish_print( - env.normal_inference_dispatcher(), - env.console, context, Language::None - ); - - env.console.log("Print completed."); - stats.m_rounds++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} +/* Auto Item Printer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_ItemPrinterTools.h" +#include "PokemonSV_AutoItemPrinter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + + +AutoItemPrinter_Descriptor::AutoItemPrinter_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:AutoItemPrinter", + STRING_POKEMON + " SV", "Auto Item Printer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoItemPrinter.md", + "Automate the Item Printer for rare items.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct AutoItemPrinter_Descriptor::Stats : public StatsTracker{ + Stats() + : m_rounds(m_stats["Rounds"]) + { + m_display_order.emplace_back("Rounds"); + } + std::atomic& m_rounds; +}; +std::unique_ptr AutoItemPrinter_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +AutoItemPrinter::AutoItemPrinter() + : LANGUAGE( + "Game Language:", + PokemonSwSh::IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NUM_ROUNDS( + "Number of Rounds to Run:", + LockMode::UNLOCK_WHILE_RUNNING, + 100 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(NUM_ROUNDS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void AutoItemPrinter::enter_printing_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.console.log("Entering printing mode..."); + + while (true){ + OverworldWatcher overworld(env.console, COLOR_CYAN); + AdvanceDialogWatcher dialog(COLOR_YELLOW); + PromptDialogWatcher prompt(COLOR_YELLOW); + WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); + context.wait_for_all_requests(); + + int ret_printer_entry = wait_until( + env.console, context, + std::chrono::seconds(120), + { material, overworld, dialog, prompt } + ); + context.wait_for_all_requests(); + + switch (ret_printer_entry){ + case 0: // material + env.console.log("Material selection screen detected."); + return; + case 1: // overworld + case 2: // dialog + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 3: // prompt + env.console.log("Prompt detected."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_printing_mode(): No recognized state after 120 seconds.", + env.console + ); + } + } +} + + + + +void AutoItemPrinter::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + AutoItemPrinter_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 0); + + enter_printing_mode(env, context); + + for (uint16_t i = 0; i < NUM_ROUNDS; i++){ + item_printer_start_print( + env.normal_inference_dispatcher(), + env.console, context, LANGUAGE, + ItemPrinterJobs::Jobs_10 + ); + item_printer_finish_print( + env.normal_inference_dispatcher(), + env.console, context, Language::None + ); + + env.console.log("Print completed."); + stats.m_rounds++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h index ba6ba7cd26..79eb2e43af 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_AutoItemPrinter.h @@ -1,55 +1,55 @@ -/* Auto Item Printer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoItemPrinter_H -#define PokemonAutomation_PokemonSV_AutoItemPrinter_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AutoItemPrinter_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoItemPrinter_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - -class AutoItemPrinter : public SingleSwitchProgramInstance{ -public: - AutoItemPrinter(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - OCR::LanguageOCROption LANGUAGE; - SimpleIntegerOption NUM_ROUNDS; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - void enter_printing_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - - - -} -} -} -#endif +/* Auto Item Printer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoItemPrinter_H +#define PokemonAutomation_PokemonSV_AutoItemPrinter_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AutoItemPrinter_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoItemPrinter_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + +class AutoItemPrinter : public SingleSwitchProgramInstance{ +public: + AutoItemPrinter(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + OCR::LanguageOCROption LANGUAGE; + SimpleIntegerOption NUM_ROUNDS; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + void enter_printing_mode(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.cpp index 1ffb398749..105f4a09ba 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.cpp @@ -1,676 +1,676 @@ -/* Item Printer Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonSV_ItemPrinterDatabase.h" -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ -namespace ItemPrinter{ - - -const EnumDropdownDatabase& PrebuiltOptions_Database(){ - static const EnumDropdownDatabase database({ - {PrebuiltOptions::NONE, "none", "---"}, - {PrebuiltOptions::ITEM_BONUS, "item-bonus", "Item Bonus"}, - {PrebuiltOptions::BALL_BONUS, "ball-bonus", "Ball Bonus"}, - - // ordered by category - {PrebuiltOptions::ABILITY_PATCH, "ability-patch", "Ability Patch"}, - {PrebuiltOptions::EXP_CANDY, "exp-candy-xl", "Exp Candy"}, - {PrebuiltOptions::PP_MAX, "pp-max", "PP Max"}, - - {PrebuiltOptions::ASSORTED_BALLS_1, "assorted-balls-1", "Assorted Balls 1"}, - {PrebuiltOptions::ASSORTED_BALLS_2, "assorted-balls-2", "Assorted Balls 2"}, - {PrebuiltOptions::ASSORTED_BALLS_3, "assorted-balls-3", "Assorted Balls 3"}, - - {PrebuiltOptions::MASTER_BALL, "master-ball", "Master Ball"}, - {PrebuiltOptions::FAST_BALL, "fast-ball", "Fast Ball"}, - {PrebuiltOptions::FRIEND_BALL, "friend-ball", "Friend Ball"}, - {PrebuiltOptions::LURE_BALL, "lure-ball", "Lure Ball"}, - {PrebuiltOptions::LEVEL_BALL, "level-ball", "Level Ball"}, - {PrebuiltOptions::HEAVY_BALL, "heavy-ball", "Heavy Ball"}, - {PrebuiltOptions::LOVE_BALL, "love-ball", "Love Ball"}, - {PrebuiltOptions::MOON_BALL, "moon-ball", "Moon Ball"}, - {PrebuiltOptions::DREAM_BALL, "dream-ball", "Dream Ball"}, - {PrebuiltOptions::SPORT_BALL, "sport-ball", "Sport Ball"}, - {PrebuiltOptions::SAFARI_BALL, "safari-ball", "Safari Ball"}, - {PrebuiltOptions::BEAST_BALL, "beast-ball", "Beast Ball"}, - - {PrebuiltOptions::BUG_TERA, "bug-tera-shard", "Bug Tera Shard"}, - {PrebuiltOptions::DARK_TERA, "dark-tera-shard", "Dark Tera Shard"}, - {PrebuiltOptions::DRAGON_TERA, "dragon-tera-shard", "Dragon Tera Shard"}, - {PrebuiltOptions::ELECTRIC_TERA, "electric-tera-shard", "Electric Tera Shard"}, - {PrebuiltOptions::FAIRY_TERA, "fairy-tera-shard", "Fairy Tera Shard"}, - {PrebuiltOptions::FIGHTING_TERA, "fighting-tera-shard", "Fighting Tera Shard"}, - {PrebuiltOptions::FIRE_TERA, "fire-tera-shard", "Fire Tera Shard"}, - {PrebuiltOptions::FLYING_TERA, "flying-tera-shard", "Flying Tera Shard"}, - {PrebuiltOptions::GHOST_TERA, "ghost-tera-shard", "Ghost Tera Shard"}, - {PrebuiltOptions::GRASS_TERA, "grass-tera-shard", "Grass Tera Shard"}, - {PrebuiltOptions::GROUND_TERA, "ground-tera-shard", "Ground Tera Shard"}, - {PrebuiltOptions::ICE_TERA, "ice-tera-shard", "Ice Tera Shard"}, - {PrebuiltOptions::NORMAL_TERA, "normal-tera-shard", "Normal Tera Shard"}, - {PrebuiltOptions::POISON_TERA, "poison-tera-shard", "Poison Tera Shard"}, - {PrebuiltOptions::PSYCHIC_TERA, "psychic-tera-shard", "Psychic Tera Shard"}, - {PrebuiltOptions::ROCK_TERA, "rock-tera-shard", "Rock Tera Shard"}, - {PrebuiltOptions::STEEL_TERA, "steel-tera-shard", "Steel Tera Shard"}, - {PrebuiltOptions::WATER_TERA, "water-tera-shard", "Water Tera Shard"}, - {PrebuiltOptions::STELLAR_TERA, "stellar-tera-shard", "Stellar Tera Shard"}, - - }); - return database; -} - -const EnumDropdownDatabase& PrebuiltOptions_AutoMode_Database(){ - static const EnumDropdownDatabase database({ - - // ordered by category - {PrebuiltOptions::ABILITY_PATCH, "ability-patch", "Ability Patch"}, - {PrebuiltOptions::EXP_CANDY, "exp-candy-xl", "Exp Candy"}, - {PrebuiltOptions::PP_MAX, "pp-max", "PP Max"}, - - {PrebuiltOptions::MASTER_BALL, "master-ball", "Master Ball"}, - {PrebuiltOptions::FAST_BALL, "fast-ball", "Fast Ball"}, - {PrebuiltOptions::FRIEND_BALL, "friend-ball", "Friend Ball"}, - {PrebuiltOptions::LURE_BALL, "lure-ball", "Lure Ball"}, - {PrebuiltOptions::LEVEL_BALL, "level-ball", "Level Ball"}, - {PrebuiltOptions::HEAVY_BALL, "heavy-ball", "Heavy Ball"}, - {PrebuiltOptions::LOVE_BALL, "love-ball", "Love Ball"}, - {PrebuiltOptions::MOON_BALL, "moon-ball", "Moon Ball"}, - {PrebuiltOptions::DREAM_BALL, "dream-ball", "Dream Ball"}, - {PrebuiltOptions::SPORT_BALL, "sport-ball", "Sport Ball"}, - {PrebuiltOptions::SAFARI_BALL, "safari-ball", "Safari Ball"}, - {PrebuiltOptions::BEAST_BALL, "beast-ball", "Beast Ball"}, - - {PrebuiltOptions::BUG_TERA, "bug-tera-shard", "Bug Tera Shard"}, - {PrebuiltOptions::DARK_TERA, "dark-tera-shard", "Dark Tera Shard"}, - {PrebuiltOptions::DRAGON_TERA, "dragon-tera-shard", "Dragon Tera Shard"}, - {PrebuiltOptions::ELECTRIC_TERA, "electric-tera-shard", "Electric Tera Shard"}, - {PrebuiltOptions::FAIRY_TERA, "fairy-tera-shard", "Fairy Tera Shard"}, - {PrebuiltOptions::FIGHTING_TERA, "fighting-tera-shard", "Fighting Tera Shard"}, - {PrebuiltOptions::FIRE_TERA, "fire-tera-shard", "Fire Tera Shard"}, - {PrebuiltOptions::FLYING_TERA, "flying-tera-shard", "Flying Tera Shard"}, - {PrebuiltOptions::GHOST_TERA, "ghost-tera-shard", "Ghost Tera Shard"}, - {PrebuiltOptions::GRASS_TERA, "grass-tera-shard", "Grass Tera Shard"}, - {PrebuiltOptions::GROUND_TERA, "ground-tera-shard", "Ground Tera Shard"}, - {PrebuiltOptions::ICE_TERA, "ice-tera-shard", "Ice Tera Shard"}, - {PrebuiltOptions::NORMAL_TERA, "normal-tera-shard", "Normal Tera Shard"}, - {PrebuiltOptions::POISON_TERA, "poison-tera-shard", "Poison Tera Shard"}, - {PrebuiltOptions::PSYCHIC_TERA, "psychic-tera-shard", "Psychic Tera Shard"}, - {PrebuiltOptions::ROCK_TERA, "rock-tera-shard", "Rock Tera Shard"}, - {PrebuiltOptions::STEEL_TERA, "steel-tera-shard", "Steel Tera Shard"}, - {PrebuiltOptions::WATER_TERA, "water-tera-shard", "Water Tera Shard"}, - {PrebuiltOptions::STELLAR_TERA, "stellar-tera-shard", "Stellar Tera Shard"}, - - }); - return database; -} - - -static const std::vector& ItemPrinter_AllOptions(){ - // - Specific item seeds taken from Anubis's Item printer seeds - // - https://gist.github.com/Lusamine/112d4230919fadd254f0e6dfca850471 - // - How I chose the specific item seeds - // - seeds (and adjacent seeds +/- 2) that didn't also trigger item/ball bonuses. This is because - // accidentally triggering a ball bonus, may prevent you from intentionally triggering an item bonus - // on the next job, and vice versa for the item bonus. - // - seconds value: minimum of 8. ideally less than 20. - // - Confirmation of seeds done with Kurt's ItemPrinterDeGacha tool - static const std::vector database{ - // 2044-05-06 15:33:08 - // Calcium - {2346161588, PrebuiltOptions::ITEM_BONUS, ItemPrinterJobs::Jobs_1, 0}, - - // 2024-06-04 00:37:08 - // Full Restore - {1717461428, PrebuiltOptions::BALL_BONUS, ItemPrinterJobs::Jobs_1, 0}, - - // 958172368, 2000-05-12 22:59:28 - // 16 total Ability Patches - // x36 Dark Tera Shard - // x4 Ability Patch - // x4 Ability Patch - // x4 Ability Patch - // x4 Ability Patch - {958172368, PrebuiltOptions::ABILITY_PATCH, ItemPrinterJobs::Jobs_5, 16}, - - // 1991472489, 2033-02-08 10:48:09 - // 1040000 exp, 28 total Exp. Candy XL - // x10 Exp. Candy XL - // x4 Protein - // x20 Exp. Candy L - // x8 Exp. Candy XL - // x10 Exp. Candy XL - {1991472489, PrebuiltOptions::EXP_CANDY, ItemPrinterJobs::Jobs_5, 28}, - - // 2030-03-11 16:44:09 - // 18 total PP Maxes - // 6x PP Max, 6x PP Max, 14x Honey, 10x Revive, 6x PP Max - {1899477849, PrebuiltOptions::PP_MAX, ItemPrinterJobs::Jobs_5, 18}, - - // 2049-08-18 23:51:08 - {2512943468, PrebuiltOptions::ASSORTED_BALLS_1, ItemPrinterJobs::Jobs_10, 1}, - - // 2031-10-08 07:09:09 - {1949209749, PrebuiltOptions::ASSORTED_BALLS_2, ItemPrinterJobs::Jobs_10, 1}, - - // 2020-03-03 06:38:18 - {1583217498, PrebuiltOptions::ASSORTED_BALLS_3, ItemPrinterJobs::Jobs_10, 1}, - - // 2005-11-07 11:32:08 - // x1 Master Ball - // x1 Master Ball - // x5 Great Ball - // x1 Master Ball - // x1 Master Ball - {1131363128, PrebuiltOptions::MASTER_BALL, ItemPrinterJobs::Jobs_5, 4}, - - // 2034-09-01 02:33:39 - {2040690819, PrebuiltOptions::FAST_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2046-12-11 02:23:17 - {2428107797, PrebuiltOptions::FRIEND_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2057-11-21 04:28:37 - {2773542517, PrebuiltOptions::LURE_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2045-03-17 10:05:38 - {2373357938, PrebuiltOptions::LEVEL_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2029-07-24 11:53:11 - {1879588391, PrebuiltOptions::HEAVY_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2023-05-22 05:36:11 - {1684733771, PrebuiltOptions::LOVE_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2042-10-14 05:56:33 - {2296878993, PrebuiltOptions::MOON_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2054-03-22 09:31:21 - {2657784681, PrebuiltOptions::DREAM_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2009-06-05 20:17:11 - {1244233031, PrebuiltOptions::SPORT_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2049-01-02 01:20:22 - {2493163222, PrebuiltOptions::SAFARI_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2037-02-02 15:37:15 - {2117201835, PrebuiltOptions::BEAST_BALL, ItemPrinterJobs::Jobs_5, 5}, - - // 2246577010, 2041-03-11 01:10:10 - // 134 Normal Tera Shards, 134 total Tera Shards - // x40 Normal Tera Shard - // x28 Normal Tera Shard - // x16 Normal Tera Shard - // x38 Normal Tera Shard - // x12 Normal Tera Shard - {2246577010, PrebuiltOptions::NORMAL_TERA, ItemPrinterJobs::Jobs_5, 134}, - - // 2669513710, 2054-08-05 03:35:10 - // 148 Fire Tera Shards, 148 total Tera Shards - // x40 Fire Tera Shard - // x36 Fire Tera Shard - // x40 Fire Tera Shard - // x32 Fire Tera Shard - // x20 Honey - {2669513710, PrebuiltOptions::FIRE_TERA, ItemPrinterJobs::Jobs_5, 148}, - - // 2419526534, 2046-09-02 18:42:14 - // 120 Water Tera Shards, 154 total Tera Shards - // x40 Water Tera Shard - // x8 Full Restore - // x40 Water Tera Shard - // x34 Flying Tera Shard - // x40 Water Tera Shard - {2419526534, PrebuiltOptions::WATER_TERA, ItemPrinterJobs::Jobs_5, 120}, - - // 1300121653, 2011-03-14 16:54:13 - // 138 Electric Tera Shards, 138 total Tera Shards - // x26 Electric Tera Shard - // x4 Light Clay - // x40 Electric Tera Shard - // x40 Electric Tera Shard - // x32 Electric Tera Shard - {1300121653, PrebuiltOptions::ELECTRIC_TERA, ItemPrinterJobs::Jobs_5, 138}, - - // 1258326250, 2009-11-15 23:04:10 - // 122 Grass Tera Shards, 122 total Tera Shards - // x30 Grass Tera Shard - // x12 Tiny Mushroom - // x38 Grass Tera Shard - // x34 Grass Tera Shard - // x20 Grass Tera Shard - {1258326250, PrebuiltOptions::GRASS_TERA, ItemPrinterJobs::Jobs_5, 122}, - - // 2567326030, 2051-05-10 10:07:10 - // 134 Ice Tera Shards, 134 total Tera Shards - // x38 Ice Tera Shard - // x16 Ice Tera Shard - // x40 Ice Tera Shard - // x40 Ice Tera Shard - // x2 Metal Alloy - {2567326030, PrebuiltOptions::ICE_TERA, ItemPrinterJobs::Jobs_5, 134}, - - // 1510682535, 2017-11-14 18:02:15 - // 132 Fighting Tera Shards, 132 total Tera Shards - // x40 Fighting Tera Shard - // x32 Fighting Tera Shard - // x20 Fighting Tera Shard - // x40 Fighting Tera Shard - // x6 Shiny Stone - {1510682535, PrebuiltOptions::FIGHTING_TERA, ItemPrinterJobs::Jobs_5, 132}, - - // 2041396572, 2034-09-09 06:36:12 - // 140 Poison Tera Shards, 140 total Tera Shards - // x4 Electirizer - // x32 Poison Tera Shard - // x36 Poison Tera Shard - // x38 Poison Tera Shard - // x34 Poison Tera Shard - {2041396572, PrebuiltOptions::POISON_TERA, ItemPrinterJobs::Jobs_5, 140}, - - // 1463321889, 2016-05-15 14:18:09 - // 130 Ground Tera Shards, 130 total Tera Shards - // x10 PP Up - // x28 Ground Tera Shard - // x34 Ground Tera Shard - // x30 Ground Tera Shard - // x38 Ground Tera Shard - {1463321889, PrebuiltOptions::GROUND_TERA, ItemPrinterJobs::Jobs_5, 130}, - - // 1580633500, 2020-02-02 08:51:40 - // 128 Flying Tera Shards, 128 total Tera Shards - // x22 Flying Tera Shard - // x30 Flying Tera Shard - // x28 Flying Tera Shard - // x38 Flying Tera Shard - // x10 Flying Tera Shard - {1580633500, PrebuiltOptions::FLYING_TERA, ItemPrinterJobs::Jobs_5, 128}, - - // 2190593713, 2039-06-02 02:15:13 - // 134 Psychic Tera Shards, 134 total Tera Shards - // x30 Psychic Tera Shard - // x4 Never-Melt Ice - // x28 Psychic Tera Shard - // x36 Psychic Tera Shard - // x40 Psychic Tera Shard - {2190593713, PrebuiltOptions::PSYCHIC_TERA, ItemPrinterJobs::Jobs_5, 134}, - - // 2458109848, 2047-11-23 08:17:28 - // 134 Bug Tera Shards, 134 total Tera Shards - // x4 Ether - // x38 Bug Tera Shard - // x34 Bug Tera Shard - // x32 Bug Tera Shard - // x30 Bug Tera Shard - {2458109848, PrebuiltOptions::BUG_TERA, ItemPrinterJobs::Jobs_5, 134}, - - // 2801954289, 2058-10-16 00:38:09 - // 120 Rock Tera Shards, 120 total Tera Shards - // x40 Rock Tera Shard - // x40 Rock Tera Shard - // x16 Pretty Feather - // x40 Rock Tera Shard - // x18 Stardust - {2801954289, PrebuiltOptions::ROCK_TERA, ItemPrinterJobs::Jobs_5, 120}, - - // 1509904271, 2017-11-05 17:51:11 - // 122 Ghost Tera Shards, 122 total Tera Shards - // x38 Ghost Tera Shard - // x36 Ghost Tera Shard - // x12 Ghost Tera Shard - // x4 Magnet - // x36 Ghost Tera Shard - {1509904271, PrebuiltOptions::GHOST_TERA, ItemPrinterJobs::Jobs_5, 122}, - - // 2155674309, 2038-04-23 22:25:09 - // 136 Dragon Tera Shards, 136 total Tera Shards - // x2 Ability Patch - // x24 Dragon Tera Shard - // x38 Dragon Tera Shard - // x40 Dragon Tera Shard - // x34 Dragon Tera Shard - {2155674309, PrebuiltOptions::DRAGON_TERA, ItemPrinterJobs::Jobs_5, 136}, - - // 2537180413, 2050-05-26 12:20:13 - // 120 Dark Tera Shards, 120 total Tera Shards - // x20 Dark Tera Shard - // x28 Dark Tera Shard - // x32 Dark Tera Shard - // x40 Dark Tera Shard - // x4 Prism Scale - {2537180413, PrebuiltOptions::DARK_TERA, ItemPrinterJobs::Jobs_5, 120}, - - // 1766067369, 2025-12-18 14:16:09 - // 120 Steel Tera Shards, 120 total Tera Shards - // x40 Steel Tera Shard - // x24 Steel Tera Shard - // x38 Steel Tera Shard - // x18 Steel Tera Shard - // x4 Berry Sweet - {1766067369, PrebuiltOptions::STEEL_TERA, ItemPrinterJobs::Jobs_5, 120}, - - // 2183028974, 2039-03-06 12:56:14 - // 120 Fairy Tera Shards, 134 total Tera Shards - // x40 Fairy Tera Shard - // x40 Fairy Tera Shard - // x14 Water Tera Shard - // x12 Tiny Bamboo Shoot - // x40 Fairy Tera Shard - {2183028974, PrebuiltOptions::FAIRY_TERA, ItemPrinterJobs::Jobs_5, 120}, - - // 1165654034, 2006-12-09 08:47:14 - // 88 Stellar Tera Shards, 88 total Tera Shards - // x30 Stellar Tera Shard - // x6 Max Revive - // x28 Stellar Tera Shard - // x30 Stellar Tera Shard - // x2 Clover Sweet - {1165654034, PrebuiltOptions::STELLAR_TERA, ItemPrinterJobs::Jobs_5, 88}, - }; - return database; -}; - -static std::map make_ItemPrinter_option_lookup_by_enum(){ - std::map ret; - for (const ItemPrinterEnumOption& item : ItemPrinter_AllOptions()){ - if (!ret.emplace(item.enum_value, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); - } - } - return ret; -} -const ItemPrinterEnumOption& option_lookup_by_enum(PrebuiltOptions enum_value){ - static const std::map database = make_ItemPrinter_option_lookup_by_enum(); - auto iter = database.find(enum_value); - if (iter != database.end()){ - return *iter->second; - }else{ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); - } -} -static std::map make_ItemPrinter_option_lookup_by_seed(){ - std::map ret; - for (const ItemPrinterEnumOption& item : ItemPrinter_AllOptions()){ - if (!ret.emplace(item.seed, &item).second){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Seed: " + std::to_string(item.seed)); - } - } - return ret; -} -const ItemPrinterEnumOption* option_lookup_by_seed(int64_t seed){ - static const std::map database = make_ItemPrinter_option_lookup_by_seed(); - auto iter = database.find(seed); - if (iter != database.end()){ - return iter->second; - }else{ - return nullptr; - } -} - - - -DateSeed get_date_seed(int64_t seed){ - // This is the function that we would replace with Kurt's seed calculator. - - static const std::map DATABASE{ - {2346161588, {2346161588, {"calcium"}}}, - {2346161588 - 2, {2346161588 - 2, {"stardust"}}}, - {2346161588 - 1, {2346161588 - 1, {"tiny-mushroom"}}}, - {2346161588 + 1, {2346161588 + 1, {"max-ether"}}}, - {2346161588 + 2, {2346161588 + 2, {"electric-tera-shard"}}}, - - {1717461428, {1717461428, {"full-restore"}}}, - {1717461428 - 2, {1717461428 - 2, {"balm-mushroom"}}}, - {1717461428 - 1, {1717461428 - 1, {"revive"}}}, - {1717461428 + 1, {1717461428 + 1, {"fairy-tera-shard"}}}, - {1717461428 + 2, {1717461428 + 2, {"big-bamboo-shoot"}}}, - - {958172368, {958172368, {"dark-tera-shard", "ability-patch", "ability-patch", "ability-patch", "ability-patch"}}}, - {958172368 - 2, {958172368 - 2, {"dark-tera-shard", "revive", "reaper-cloth", "ability-patch", "poison-tera-shard"}}}, - {958172368 - 1, {958172368 - 1, {"dark-tera-shard", "fire-tera-shard", "big-bamboo-shoot", "balm-mushroom", "super-potion"}}}, - {958172368 + 1, {958172368 + 1, {"dark-tera-shard", "pearl", "spell-tag", "flower-sweet", "ribbon-sweet"}}}, - {958172368 + 2, {958172368 + 2, {"dark-tera-shard", "water-stone", "max-potion", "tiny-mushroom", "electric-tera-shard"}}}, - - {1991472489, {1991472489, {"exp-candy-xl", "protein", "exp-candy-l", "exp-candy-xl", "exp-candy-xl"}}}, - {1991472489 - 2, {1991472489 - 2, {"exp-candy-xl", "tiny-bamboo-shoot", "exp-candy-s", "iron", "tiny-bamboo-shoot"}}}, - {1991472489 - 1, {1991472489 - 1, {"exp-candy-xl", "toxic-orb", "rare-bone", "silver-powder", "lucky-egg"}}}, - {1991472489 + 1, {1991472489 + 1, {"exp-candy-xl", "silver-powder", "dubious-disc", "mystic-water", "toxic-orb"}}}, - {1991472489 + 2, {1991472489 + 2, {"exp-candy-xl", "tiny-bamboo-shoot", "toxic-orb", "ice-stone", "charcoal"}}}, - - {2246577010, {2246577010, {"normal-tera-shard", "normal-tera-shard", "normal-tera-shard", "normal-tera-shard", "normal-tera-shard"}}}, - {2246577010 - 2, {2246577010 - 2, {"normal-tera-shard", "exp-candy-l", "star-piece", "tiny-mushroom", "rock-tera-shard"}}}, - {2246577010 - 1, {2246577010 - 1, {"normal-tera-shard", "oval-stone", "ether", "stardust", "steel-tera-shard"}}}, - {2246577010 + 1, {2246577010 + 1, {"normal-tera-shard", "exp-candy-s", "ether", "elixir", "big-pearl"}}}, - {2246577010 + 2, {2246577010 + 2, {"normal-tera-shard", "dragon-tera-shard", "ice-tera-shard", "exp-candy-xl", "black-sludge"}}}, - - {2669513710, {2669513710, {"fire-tera-shard", "fire-tera-shard", "fire-tera-shard", "fire-tera-shard", "honey"}}}, - {2669513710 - 2, {2669513710 - 2, {"fire-tera-shard", "flame-orb", "steel-tera-shard", "fire-stone", "max-revive"}}}, - {2669513710 - 1, {2669513710 - 1, {"fire-tera-shard", "exp-candy-xs", "miracle-seed", "sun-stone", "iron"}}}, - {2669513710 + 1, {2669513710 + 1, {"fire-tera-shard", "poison-tera-shard", "love-sweet", "safety-goggles", "exp-candy-m"}}}, - {2669513710 + 2, {2669513710 + 2, {"fire-tera-shard", "rare-bone", "dubious-disc", "berry-sweet", "hp-up"}}}, - - {2419526534, {2419526534, {"water-tera-shard", "full-restore", "water-tera-shard", "flying-tera-shard", "water-tera-shard"}}}, - {2419526534 - 2, {2419526534 - 2, {"water-tera-shard", "exp-candy-xs", "flame-orb", "exp-candy-s", "honey"}}}, - {2419526534 - 1, {2419526534 - 1, {"water-tera-shard", "never-melt-ice", "rock-tera-shard", "hp-up", "sun-stone"}}}, - {2419526534 + 1, {2419526534 + 1, {"water-tera-shard", "heavy-duty-boots", "moon-stone", "strawberry-sweet", "exp-candy-xs"}}}, - {2419526534 + 2, {2419526534 + 2, {"water-tera-shard", "ghost-tera-shard", "max-revive", "ground-tera-shard", "exp-candy-xl"}}}, - - {1300121653, {1300121653, {"electric-tera-shard", "light-clay", "electric-tera-shard", "electric-tera-shard", "electric-tera-shard"}}}, - {1300121653 - 2, {1300121653 - 2, {"electric-tera-shard", "elixir", "full-restore", "upgrade", "toxic-orb"}}}, - {1300121653 - 1, {1300121653 - 1, {"electric-tera-shard", "exp-candy-xs", "steel-tera-shard", "big-mushroom", "exp-candy-s"}}}, - {1300121653 + 1, {1300121653 + 1, {"electric-tera-shard", "calcium", "ground-tera-shard", "water-tera-shard", "upgrade"}}}, - {1300121653 + 2, {1300121653 + 2, {"electric-tera-shard", "max-potion", "charcoal", "exp-candy-xs", "grass-tera-shard"}}}, - - {1258326250, {1258326250, {"grass-tera-shard", "tiny-mushroom", "grass-tera-shard", "grass-tera-shard", "grass-tera-shard"}}}, - {1258326250 - 2, {1258326250 - 2, {"grass-tera-shard", "pretty-feather", "exp-candy-m", "bug-tera-shard", "tiny-mushroom"}}}, - {1258326250 - 1, {1258326250 - 1, {"grass-tera-shard", "ghost-tera-shard", "bug-tera-shard", "silver-powder", "berry-sweet"}}}, - {1258326250 + 1, {1258326250 + 1, {"grass-tera-shard", "steel-tera-shard", "honey", "strawberry-sweet", "normal-tera-shard"}}}, - {1258326250 + 2, {1258326250 + 2, {"grass-tera-shard", "exp-candy-xl", "exp-candy-xs", "zinc", "dragon-fang"}}}, - - {2567326030, {2567326030, {"ice-tera-shard", "ice-tera-shard", "ice-tera-shard", "ice-tera-shard", "metal-alloy"}}}, - {2567326030 - 2, {2567326030 - 2, {"ice-tera-shard", "pearl-string", "dragon-tera-shard", "sun-stone", "water-tera-shard"}}}, - {2567326030 - 1, {2567326030 - 1, {"ice-tera-shard", "scope-lens", "full-restore", "dubious-disc", "lucky-egg"}}}, - {2567326030 + 1, {2567326030 + 1, {"ice-tera-shard", "poison-barb", "leaf-stone", "cracked-pot", "ghost-tera-shard"}}}, - {2567326030 + 2, {2567326030 + 2, {"ice-tera-shard", "exp-candy-xs", "rock-tera-shard", "loaded-dice", "Pretty Feather"}}}, - - {1510682535, {1510682535, {"fighting-tera-shard", "fighting-tera-shard", "fighting-tera-shard", "fighting-tera-shard", "shiny-stone"}}}, - {1510682535 - 2, {1510682535 - 2, {"fairy-feather", "normal-tera-shard", "air-balloon", "poison-tera-shard", "pearl"}}}, - {1510682535 - 1, {1510682535 - 1, {"strawberry-sweet", "electric-tera-shard", "calcium", "revive", "ghost-tera-shard"}}}, - {1510682535 + 1, {1510682535 + 1, {"miracle-seed", "fighting-tera-shard", "ice-tera-shard", "light-clay", "dark-tera-shard"}}}, - {1510682535 + 2, {1510682535 + 2, {"rare-bone", "max-elixir", "leaf-stone", "metal-alloy", "magmarizer"}}}, - - {2041396572, {2041396572, {"electirizer", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard"}}}, - {2041396572 - 2, {2041396572 - 2, {"electirizer", "upgrade", "zinc", "elixir", "revive"}}}, - {2041396572 - 1, {2041396572 - 1, {"electirizer", "flame-orb", "magmarizer", "hp-up", "pretty-feather"}}}, - {2041396572 + 1, {2041396572 + 1, {"electirizer", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard"}}}, - {2041396572 + 2, {2041396572 + 2, {"electirizer", "pp-up", "rock-tera-shard", "big-mushroom", "light-clay"}}}, - - {1463321889, {1463321889, {"pp-up", "ground-tera-shard", "ground-tera-shard", "ground-tera-shard", "ground-tera-shard"}}}, - {1463321889 - 2, {1463321889 - 2, {"pp-up", "pretty-feather", "max-ether", "big-pearl", "carbos"}}}, - {1463321889 - 1, {1463321889 - 1, {"pp-up", "spell-tag", "bug-tera-shard", "pearl", "fighting-tera-shard"}}}, - {1463321889 + 1, {1463321889 + 1, {"pp-up", "metal-alloy", "full-restore", "pearl", "silver-powder"}}}, - {1463321889 + 2, {1463321889 + 2, {"pp-up", "ghost-tera-shard", "nugget", "safety-goggles", "leftovers"}}}, - - {1580633500, {1580633500, {"flying-tera-shard", "flying-tera-shard", "flying-tera-shard", "flying-tera-shard", "flying-tera-shard"}}}, - {1580633500 - 2, {1580633500 - 2, {"black-glasses", "big-nugget", "max-revive", "pearl-string", "balm-mushroom"}}}, - {1580633500 - 1, {1580633500 - 1, {"loaded-dice", "exp-candy-s", "strawberry-sweet", "never-melt-ice", "moon-stone"}}}, - {1580633500 + 1, {1580633500 + 1, {"water-stone", "rare-bone", "max-ether", "moon-stone", "ability-patch"}}}, - {1580633500 + 2, {1580633500 + 2, {"max-ether", "big-bamboo-shoot", "iron", "big-mushroom", "pearl"}}}, - - {2190593713, {2190593713, {"psychic-tera-shard", "never-melt-ice", "psychic-tera-shard", "psychic-tera-shard", "psychic-tera-shard"}}}, - {2190593713 - 2, {2190593713 - 2, {"psychic-tera-shard", "big-mushroom", "fairy-feather", "fairy-tera-shard", "reaper-cloth"}}}, - {2190593713 - 1, {2190593713 - 1, {"psychic-tera-shard", "electric-tera-shard", "pearl", "stellar-tera-shard", "dawn-stone"}}}, - {2190593713 + 1, {2190593713 + 1, {"psychic-tera-shard", "pearl-string", "twisted-spoon", "big-pearl", "iron"}}}, - {2190593713 + 2, {2190593713 + 2, {"psychic-tera-shard", "heavy-duty-boots", "water-tera-shard", "rock-tera-shard", "twisted-spoon"}}}, - - {2458109848, {2458109848, {"ether", "bug-tera-shard", "bug-tera-shard", "bug-tera-shard", "bug-tera-shard"}}}, - {2458109848 - 2, {2458109848 - 2, {"ether", "big-nugget", "mystic-water", "pretty-feather", "pretty-feather"}}}, - {2458109848 - 1, {2458109848 - 1, {"ether", "psychic-tera-shard", "exp-candy-s", "honey", "sharp-beak"}}}, - {2458109848 + 1, {2458109848 + 1, {"ether", "black-glasses", "fighting-tera-shard", "tiny-bamboo-shoot", "poison-barb"}}}, - {2458109848 + 2, {2458109848 + 2, {"ether", "exp-candy-xl", "normal-tera-shard", "fairy-tera-shard", "balm-mushroom"}}}, - - {2801954289, {2801954289, {"rock-tera-shard", "rock-tera-shard", "pretty-feather", "rock-tera-shard", "stardust"}}}, - {2801954289 - 2, {2801954289 - 2, {"max-revive", "scope-lens", "razor-claw", "big-nugget", "tiny-bamboo-shoot"}}}, - {2801954289 - 1, {2801954289 - 1, {"iron", "dark-tera-shard", "air-balloon", "rare-bone", "ability-patch"}}}, - {2801954289 + 1, {2801954289 + 1, {"normal-tera-shard", "ground-tera-shard", "honey", "upgrade", "honey"}}}, - {2801954289 + 2, {2801954289 + 2, {"heavy-duty-boots", "ice-tera-shard", "sun-stone", "dubious-disc", "pearl"}}}, - - {1509904271, {1509904271, {"ghost-tera-shard", "ghost-tera-shard", "ghost-tera-shard", "magnet", "ghost-tera-shard"}}}, - {1509904271 - 2, {1509904271 - 2, {"ghost-tera-shard", "hyper-potion", "toxic-orb", "magmarizer", "black-glasses"}}}, - {1509904271 - 1, {1509904271 - 1, {"ghost-tera-shard", "black-belt", "pp-up", "ice-tera-shard", "magmarizer"}}}, - {1509904271 + 1, {1509904271 + 1, {"ghost-tera-shard", "big-nugget", "hp-up", "gold-bottle-cap", "big-bamboo-shoot"}}}, - {1509904271 + 2, {1509904271 + 2, {"ghost-tera-shard", "hp-up", "elixir", "water-tera-shard", "pp-up"}}}, - - {2155674309, {2155674309, {"ability-patch", "dragon-tera-shard", "dragon-tera-shard", "dragon-tera-shard", "dragon-tera-shard"}}}, - {2155674309 - 2, {2155674309 - 2, {"comet-shard", "soft-sand", "big-mushroom", "steel-tera-shard", "metronome"}}}, - {2155674309 - 1, {2155674309 - 1, {"pearl", "balm-mushroom", "moon-stone", "protein", "ability-patch"}}}, - {2155674309 + 1, {2155674309 + 1, {"reaper-cloth", "hp-up", "revive", "light-clay", "focus-band"}}}, - {2155674309 + 2, {2155674309 + 2, {"spell-tag", "love-sweet", "fire-tera-shard", "ether", "black-belt"}}}, - - {2537180413, {2537180413, {"dark-tera-shard", "dark-tera-shard", "dark-tera-shard", "dark-tera-shard", "prism-scale"}}}, - {2537180413 - 2, {2537180413 - 2, {"dark-tera-shard", "upgrade", "big-mushroom", "normal-tera-shard", "exp-candy-m"}}}, - {2537180413 - 1, {2537180413 - 1, {"dark-tera-shard", "pp-max", "calcium", "rock-tera-shard", "hard-stone"}}}, - {2537180413 + 1, {2537180413 + 1, {"dark-tera-shard", "leaf-stone", "big-pearl", "comet-shard", "exp-candy-m"}}}, - {2537180413 + 2, {2537180413 + 2, {"dark-tera-shard", "ground-tera-shard", "fairy-tera-shard", "exp-candy-xs", "fighting-tera-shard"}}}, - - {1766067369, {1766067369, {"steel-tera-shard", "steel-tera-shard", "steel-tera-shard", "steel-tera-shard", "berry-sweet"}}}, - {1766067369 - 2, {1766067369 - 2, {"steel-tera-shard", "bug-tera-shard", "exp-candy-xl", "pretty-feather", "silk-scarf"}}}, - {1766067369 - 1, {1766067369 - 1, {"steel-tera-shard", "tiny-mushroom", "super-potion", "sharp-beak", "ice-tera-shard"}}}, - {1766067369 + 1, {1766067369 + 1, {"steel-tera-shard", "moon-stone", "exp-candy-xl", "iron", "exp-candy-xs"}}}, - {1766067369 + 2, {1766067369 + 2, {"steel-tera-shard", "metal-alloy", "ability-patch", "pp-up", "rare-bone"}}}, - - {2183028974, {2183028974, {"fairy-tera-shard", "fairy-tera-shard", "water-tera-shard", "tiny-bamboo-shoot", "fairy-tera-shard"}}}, - {2183028974 - 2, {2183028974 - 2, {"max-elixir", "never-melt-ice", "pearl", "max-potion", "pp-up"}}}, - {2183028974 - 1, {2183028974 - 1, {"full-restore", "psychic-tera-shard", "gold-bottle-cap", "dawn-stone", "never-melt-ice"}}}, - {2183028974 + 1, {2183028974 + 1, {"ice-tera-shard", "twisted-spoon", "exp-candy-s", "max-elixir", "razor-fang"}}}, - {2183028974 + 2, {2183028974 + 2, {"exp-candy-xl", "bug-tera-shard", "star-piece", "hp-up", "bug-tera-shard"}}}, - - {1165654034, {1165654034, {"stellar-tera-shard", "max-revive", "stellar-tera-shard", "stellar-tera-shard", "clover-sweet"}}}, - {1165654034 - 2, {1165654034 - 2, {"stellar-tera-shard", "pp-up", "scope-lens", "electric-tera-shard", "metronome"}}}, - {1165654034 - 1, {1165654034 - 1, {"stellar-tera-shard", "dragon-tera-shard", "honey", "steel-tera-shard", "max-potion"}}}, - {1165654034 + 1, {1165654034 + 1, {"stellar-tera-shard", "full-heal", "toxic-orb", "max-potion", "miracle-seed"}}}, - {1165654034 + 2, {1165654034 + 2, {"stellar-tera-shard", "big-bamboo-shoot", "poison-tera-shard", "honey", "oval-stone"}}}, - - {1131363128, {1131363128, {}, {"master-ball", "master-ball", "great-ball", "master-ball", "master-ball"}}}, - {1131363128 - 2, {1131363128 - 2, {}, {"master-ball", "great-ball", "quick-ball", "luxury-ball", "heal-ball"}}}, - {1131363128 - 1, {1131363128 - 1, {}, {"master-ball", "great-ball", "timer-ball", "fast-ball", "love-ball"}}}, - {1131363128 + 1, {1131363128 + 1, {}, {"master-ball", "premier-ball", "great-ball", "luxury-ball", "heal-ball"}}}, - {1131363128 + 2, {1131363128 + 2, {}, {"master-ball", "quick-ball", "poke-ball", "premier-ball", "poke-ball"}}}, - - {2040690819, {2040690819, {}, {"fast-ball", "fast-ball", "fast-ball", "fast-ball", "fast-ball"}}}, - {2040690819 - 2, {2040690819 - 2, {}, {"fast-ball", "lure-ball", "dream-ball", "friend-ball", "level-ball"}}}, - {2040690819 - 1, {2040690819 - 1, {}, {"fast-ball", "great-ball", "quick-ball", "great-ball", "heal-ball"}}}, - {2040690819 + 1, {2040690819 + 1, {}, {"fast-ball", "dream-ball", "luxury-ball", "luxury-ball", "premier-ball"}}}, - {2040690819 + 2, {2040690819 + 2, {}, {"fast-ball", "luxury-ball", "great-ball", "poke-ball", "premier-ball"}}}, - - {2428107797, {2428107797, {}, {"friend-ball", "friend-ball", "friend-ball", "friend-ball", "friend-ball"}}}, - {2428107797 - 2, {2428107797 - 2, {}, {"friend-ball", "great-ball", "sport-ball", "great-ball", "great-ball"}}}, - {2428107797 - 1, {2428107797 - 1, {}, {"friend-ball", "premier-ball", "heal-ball", "repeat-ball", "nest-ball"}}}, - {2428107797 + 1, {2428107797 + 1, {}, {"friend-ball", "premier-ball", "heavy-ball", "timer-ball", "friend-ball"}}}, - {2428107797 + 2, {2428107797 + 2, {}, {"friend-ball", "heal-ball", "great-ball", "beast-ball", "moon-ball"}}}, - - {2773542517, {2773542517, {}, {"lure-ball", "lure-ball", "lure-ball", "lure-ball", "lure-ball"}}}, - {2773542517 - 2, {2773542517 - 2, {}, {"lure-ball", "premier-ball", "premier-ball", "great-ball", "poke-ball"}}}, - {2773542517 - 1, {2773542517 - 1, {}, {"dream-ball", "poke-ball", "poke-ball", "luxury-ball", "poke-ball"}}}, - {2773542517 + 1, {2773542517 + 1, {}, {"luxury-ball", "premier-ball", "great-ball", "luxury-ball", "fast-ball"}}}, - {2773542517 + 2, {2773542517 + 2, {}, {"timer-ball", "safari-ball", "dive-ball", "poke-ball", "premier-ball"}}}, - - {2373357938, {2373357938, {}, {"level-ball", "level-ball", "level-ball", "level-ball", "level-ball"}}}, - {2373357938 - 2, {2373357938 - 2, {}, {"dusk-ball", "heal-ball", "luxury-ball", "premier-ball", "poke-ball"}}}, - {2373357938 - 1, {2373357938 - 1, {}, {"great-ball", "dive-ball", "dream-ball", "luxury-ball", "luxury-ball"}}}, - {2373357938 + 1, {2373357938 + 1, {}, {"repeat-ball", "heal-ball", "heal-ball", "luxury-ball", "dive-ball"}}}, - {2373357938 + 2, {2373357938 + 2, {}, {"luxury-ball", "master-ball", "premier-ball", "ultra-ball", "heal-ball"}}}, - - {1879588391, {1879588391, {}, {"heavy-ball", "heavy-ball", "heavy-ball", "heavy-ball", "heavy-ball"}}}, - {1879588391 - 2, {1879588391 - 2, {}, {"heavy-ball", "nest-ball", "nest-ball", "heal-ball", "luxury-ball"}}}, - {1879588391 - 1, {1879588391 - 1, {}, {"heavy-ball", "poke-ball", "premier-ball", "premier-ball", "heal-ball"}}}, - {1879588391 + 1, {1879588391 + 1, {}, {"heavy-ball", "heal-ball", "premier-ball", "timer-ball", "premier-ball"}}}, - {1879588391 + 2, {1879588391 + 2, {}, {"heavy-ball", "ultra-ball", "heal-ball", "quick-ball", "beast-ball"}}}, - - {1684733771, {1684733771, {}, {"love-ball", "love-ball", "love-ball", "love-ball", "love-ball"}}}, - {1684733771 - 2, {1684733771 - 2, {}, {"love-ball", "sport-ball", "great-ball", "poke-ball", "poke-ball"}}}, - {1684733771 - 1, {1684733771 - 1, {}, {"love-ball", "poke-ball", "great-ball", "luxury-ball", "master-ball"}}}, - {1684733771 + 1, {1684733771 + 1, {}, {"love-ball", "great-ball", "luxury-ball", "luxury-ball", "poke-ball"}}}, - {1684733771 + 2, {1684733771 + 2, {}, {"love-ball", "luxury-ball", "premier-ball", "poke-ball", "quick-ball"}}}, - - {2296878993, {2296878993, {}, {"moon-ball", "moon-ball", "moon-ball", "moon-ball", "moon-ball"}}}, - {2296878993 - 2, {2296878993 - 2, {}, {"luxury-ball", "timer-ball", "premier-ball", "luxury-ball", "poke-ball"}}}, - {2296878993 - 1, {2296878993 - 1, {}, {"nest-ball", "poke-ball", "heal-ball", "premier-ball", "premier-ball"}}}, - {2296878993 + 1, {2296878993 + 1, {}, {"fast-ball", "heal-ball", "poke-ball", "dusk-ball", "luxury-ball"}}}, - {2296878993 + 2, {2296878993 + 2, {}, {"lure-ball", "heavy-ball", "luxury-ball", "heal-ball", "poke-ball"}}}, - - {2657784681, {2657784681, {}, {"dream-ball", "dream-ball", "dream-ball", "dream-ball", "dream-ball"}}}, - {2657784681 - 2, {2657784681 - 2, {}, {"master-ball", "poke-ball", "luxury-ball", "level-ball", "dream-ball"}}}, - {2657784681 - 1, {2657784681 - 1, {}, {"timer-ball", "beast-ball", "poke-ball", "premier-ball", "heal-ball"}}}, - {2657784681 + 1, {2657784681 + 1, {}, {"heavy-ball", "poke-ball", "friend-ball", "fast-ball", "heavy-ball"}}}, - {2657784681 + 2, {2657784681 + 2, {}, {"luxury-ball", "poke-ball", "luxury-ball", "quick-ball", "friend-ball"}}}, - - {1244233031, {1244233031, {}, {"sport-ball", "sport-ball", "sport-ball", "sport-ball", "sport-ball"}}}, - {1244233031 - 2, {1244233031 - 2, {}, {"sport-ball", "heal-ball", "luxury-ball", "great-ball", "heal-ball"}}}, - {1244233031 - 1, {1244233031 - 1, {}, {"sport-ball", "dream-ball", "level-ball", "poke-ball", "luxury-ball"}}}, - {1244233031 + 1, {1244233031 + 1, {}, {"moon-ball", "heal-ball", "poke-ball", "poke-ball", "heal-ball"}}}, - {1244233031 + 2, {1244233031 + 2, {}, {"moon-ball", "poke-ball", "ultra-ball", "poke-ball", "great-ball"}}}, - - {2493163222, {2493163222, {}, {"safari-ball", "safari-ball", "safari-ball", "safari-ball", "safari-ball"}}}, - {2493163222 - 2, {2493163222 - 2, {}, {"premier-ball", "great-ball", "lure-ball", "ultra-ball", "safari-ball"}}}, - {2493163222 - 1, {2493163222 - 1, {}, {"premier-ball", "great-ball", "poke-ball", "poke-ball", "poke-ball"}}}, - {2493163222 + 1, {2493163222 + 1, {}, {"poke-ball", "poke-ball", "poke-ball", "premier-ball", "great-ball"}}}, - {2493163222 + 2, {2493163222 + 2, {}, {"great-ball", "great-ball", "level-ball", "poke-ball", "safari-ball"}}}, - - {2117201835, {2117201835, {}, {"beast-ball", "beast-ball", "beast-ball", "beast-ball", "beast-ball"}}}, - {2117201835 - 2, {2117201835 - 2, {}, {"luxury-ball", "poke-ball", "lure-ball", "master-ball", "dive-ball"}}}, - {2117201835 - 1, {2117201835 - 1, {}, {"heavy-ball", "premier-ball", "premier-ball", "poke-ball", "level-ball"}}}, - {2117201835 + 1, {2117201835 + 1, {}, {"heal-ball", "great-ball", "luxury-ball", "heavy-ball", "great-ball"}}}, - {2117201835 + 2, {2117201835 + 2, {}, {"poke-ball", "premier-ball", "great-ball", "poke-ball", "dive-ball"}}}, - - {2512943468, {2512943468, {}, {"level-ball", "level-ball", "friend-ball", "lure-ball", "beast-ball", "moon-ball", "fast-ball", "dream-ball", "love-ball", "beast-ball"}}}, - {2512943468 - 2, {2512943468 - 2, {}, {"level-ball", "dusk-ball", "sport-ball", "great-ball", "dusk-ball", "great-ball", "timer-ball", "premier-ball", "premier-ball", "safari-ball"}}}, - {2512943468 - 1, {2512943468 - 1, {}, {"level-ball", "premier-ball", "dream-ball", "beast-ball", "dream-ball", "premier-ball", "luxury-ball", "lure-ball", "luxury-ball", "poke-ball"}}}, - {2512943468 + 1, {2512943468 + 1, {}, {"level-ball", "premier-ball", "sport-ball", "premier-ball", "poke-ball", "great-ball", "great-ball", "poke-ball", "luxury-ball", "dive-ball"}}}, - {2512943468 + 2, {2512943468 + 2, {}, {"level-ball", "lure-ball", "moon-ball", "heal-ball", "heal-ball", "dream-ball", "great-ball", "safari-ball", "premier-ball", "premier-ball"}}}, - - {1949209749, {1949209749, {}, {"love-ball", "dream-ball", "heavy-ball", "lure-ball", "fast-ball", "fast-ball", "safari-ball", "safari-ball", "friend-ball", "heavy-ball"}}}, - {1949209749 - 2, {1949209749 - 2, {}, {"ultra-ball", "luxury-ball", "luxury-ball", "poke-ball", "poke-ball", "moon-ball", "heal-ball", "timer-ball", "dusk-ball", "great-ball"}}}, - {1949209749 - 1, {1949209749 - 1, {}, {"net-ball", "heal-ball", "heavy-ball", "heal-ball", "dive-ball", "great-ball", "great-ball", "premier-ball", "luxury-ball", "love-ball"}}}, - {1949209749 + 1, {1949209749 + 1, {}, {"luxury-ball", "heal-ball", "poke-ball", "poke-ball", "premier-ball", "sport-ball", "luxury-ball", "premier-ball", "poke-ball", "poke-ball"}}}, - {1949209749 + 2, {1949209749 + 2, {}, {"dusk-ball", "lure-ball", "fast-ball", "premier-ball", "great-ball", "luxury-ball", "poke-ball", "safari-ball", "luxury-ball", "premier-ball"}}}, - - {1583217498, {1583217498, {}, {"sport-ball", "master-ball", "fast-ball", "master-ball", "dream-ball", "friend-ball", "lure-ball", "sport-ball", "moon-ball", "dream-ball"}}}, - {1583217498 - 2, {1583217498 - 2, {}, {"heal-ball", "net-ball", "poke-ball", "premier-ball", "poke-ball", "repeat-ball", "luxury-ball", "poke-ball", "great-ball", "heal-ball"}}}, - {1583217498 - 1, {1583217498 - 1, {}, {"poke-ball", "heal-ball", "heavy-ball", "luxury-ball", "moon-ball", "timer-ball", "premier-ball", "great-ball", "great-ball", "friend-ball"}}}, - {1583217498 + 1, {1583217498 + 1, {}, {"level-ball", "dive-ball", "great-ball", "luxury-ball", "moon-ball", "friend-ball", "timer-ball", "heal-ball", "poke-ball", "quick-ball"}}}, - {1583217498 + 2, {1583217498 + 2, {}, {"luxury-ball", "friend-ball", "dream-ball", "heal-ball", "luxury-ball", "great-ball", "premier-ball", "dusk-ball", "level-ball", "beast-ball"}}}, - - // Template -// {1717461428 - 2, {1717461428 - 2, {}, }}, -// {1717461428 - 1, {1717461428 - 1, {}, }}, -// {1717461428 + 1, {1717461428 + 1, {}, }}, -// {1717461428 + 2, {1717461428 + 2, {}, }}, - - }; - - auto iter = DATABASE.find(seed); - if (iter != DATABASE.end()){ - return iter->second; - } - - return DateSeed(); -} - - - - - -} -} -} -} +/* Item Printer Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonSV_ItemPrinterDatabase.h" +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace ItemPrinter{ + + +const EnumDropdownDatabase& PrebuiltOptions_Database(){ + static const EnumDropdownDatabase database({ + {PrebuiltOptions::NONE, "none", "---"}, + {PrebuiltOptions::ITEM_BONUS, "item-bonus", "Item Bonus"}, + {PrebuiltOptions::BALL_BONUS, "ball-bonus", "Ball Bonus"}, + + // ordered by category + {PrebuiltOptions::ABILITY_PATCH, "ability-patch", "Ability Patch"}, + {PrebuiltOptions::EXP_CANDY, "exp-candy-xl", "Exp Candy"}, + {PrebuiltOptions::PP_MAX, "pp-max", "PP Max"}, + + {PrebuiltOptions::ASSORTED_BALLS_1, "assorted-balls-1", "Assorted Balls 1"}, + {PrebuiltOptions::ASSORTED_BALLS_2, "assorted-balls-2", "Assorted Balls 2"}, + {PrebuiltOptions::ASSORTED_BALLS_3, "assorted-balls-3", "Assorted Balls 3"}, + + {PrebuiltOptions::MASTER_BALL, "master-ball", "Master Ball"}, + {PrebuiltOptions::FAST_BALL, "fast-ball", "Fast Ball"}, + {PrebuiltOptions::FRIEND_BALL, "friend-ball", "Friend Ball"}, + {PrebuiltOptions::LURE_BALL, "lure-ball", "Lure Ball"}, + {PrebuiltOptions::LEVEL_BALL, "level-ball", "Level Ball"}, + {PrebuiltOptions::HEAVY_BALL, "heavy-ball", "Heavy Ball"}, + {PrebuiltOptions::LOVE_BALL, "love-ball", "Love Ball"}, + {PrebuiltOptions::MOON_BALL, "moon-ball", "Moon Ball"}, + {PrebuiltOptions::DREAM_BALL, "dream-ball", "Dream Ball"}, + {PrebuiltOptions::SPORT_BALL, "sport-ball", "Sport Ball"}, + {PrebuiltOptions::SAFARI_BALL, "safari-ball", "Safari Ball"}, + {PrebuiltOptions::BEAST_BALL, "beast-ball", "Beast Ball"}, + + {PrebuiltOptions::BUG_TERA, "bug-tera-shard", "Bug Tera Shard"}, + {PrebuiltOptions::DARK_TERA, "dark-tera-shard", "Dark Tera Shard"}, + {PrebuiltOptions::DRAGON_TERA, "dragon-tera-shard", "Dragon Tera Shard"}, + {PrebuiltOptions::ELECTRIC_TERA, "electric-tera-shard", "Electric Tera Shard"}, + {PrebuiltOptions::FAIRY_TERA, "fairy-tera-shard", "Fairy Tera Shard"}, + {PrebuiltOptions::FIGHTING_TERA, "fighting-tera-shard", "Fighting Tera Shard"}, + {PrebuiltOptions::FIRE_TERA, "fire-tera-shard", "Fire Tera Shard"}, + {PrebuiltOptions::FLYING_TERA, "flying-tera-shard", "Flying Tera Shard"}, + {PrebuiltOptions::GHOST_TERA, "ghost-tera-shard", "Ghost Tera Shard"}, + {PrebuiltOptions::GRASS_TERA, "grass-tera-shard", "Grass Tera Shard"}, + {PrebuiltOptions::GROUND_TERA, "ground-tera-shard", "Ground Tera Shard"}, + {PrebuiltOptions::ICE_TERA, "ice-tera-shard", "Ice Tera Shard"}, + {PrebuiltOptions::NORMAL_TERA, "normal-tera-shard", "Normal Tera Shard"}, + {PrebuiltOptions::POISON_TERA, "poison-tera-shard", "Poison Tera Shard"}, + {PrebuiltOptions::PSYCHIC_TERA, "psychic-tera-shard", "Psychic Tera Shard"}, + {PrebuiltOptions::ROCK_TERA, "rock-tera-shard", "Rock Tera Shard"}, + {PrebuiltOptions::STEEL_TERA, "steel-tera-shard", "Steel Tera Shard"}, + {PrebuiltOptions::WATER_TERA, "water-tera-shard", "Water Tera Shard"}, + {PrebuiltOptions::STELLAR_TERA, "stellar-tera-shard", "Stellar Tera Shard"}, + + }); + return database; +} + +const EnumDropdownDatabase& PrebuiltOptions_AutoMode_Database(){ + static const EnumDropdownDatabase database({ + + // ordered by category + {PrebuiltOptions::ABILITY_PATCH, "ability-patch", "Ability Patch"}, + {PrebuiltOptions::EXP_CANDY, "exp-candy-xl", "Exp Candy"}, + {PrebuiltOptions::PP_MAX, "pp-max", "PP Max"}, + + {PrebuiltOptions::MASTER_BALL, "master-ball", "Master Ball"}, + {PrebuiltOptions::FAST_BALL, "fast-ball", "Fast Ball"}, + {PrebuiltOptions::FRIEND_BALL, "friend-ball", "Friend Ball"}, + {PrebuiltOptions::LURE_BALL, "lure-ball", "Lure Ball"}, + {PrebuiltOptions::LEVEL_BALL, "level-ball", "Level Ball"}, + {PrebuiltOptions::HEAVY_BALL, "heavy-ball", "Heavy Ball"}, + {PrebuiltOptions::LOVE_BALL, "love-ball", "Love Ball"}, + {PrebuiltOptions::MOON_BALL, "moon-ball", "Moon Ball"}, + {PrebuiltOptions::DREAM_BALL, "dream-ball", "Dream Ball"}, + {PrebuiltOptions::SPORT_BALL, "sport-ball", "Sport Ball"}, + {PrebuiltOptions::SAFARI_BALL, "safari-ball", "Safari Ball"}, + {PrebuiltOptions::BEAST_BALL, "beast-ball", "Beast Ball"}, + + {PrebuiltOptions::BUG_TERA, "bug-tera-shard", "Bug Tera Shard"}, + {PrebuiltOptions::DARK_TERA, "dark-tera-shard", "Dark Tera Shard"}, + {PrebuiltOptions::DRAGON_TERA, "dragon-tera-shard", "Dragon Tera Shard"}, + {PrebuiltOptions::ELECTRIC_TERA, "electric-tera-shard", "Electric Tera Shard"}, + {PrebuiltOptions::FAIRY_TERA, "fairy-tera-shard", "Fairy Tera Shard"}, + {PrebuiltOptions::FIGHTING_TERA, "fighting-tera-shard", "Fighting Tera Shard"}, + {PrebuiltOptions::FIRE_TERA, "fire-tera-shard", "Fire Tera Shard"}, + {PrebuiltOptions::FLYING_TERA, "flying-tera-shard", "Flying Tera Shard"}, + {PrebuiltOptions::GHOST_TERA, "ghost-tera-shard", "Ghost Tera Shard"}, + {PrebuiltOptions::GRASS_TERA, "grass-tera-shard", "Grass Tera Shard"}, + {PrebuiltOptions::GROUND_TERA, "ground-tera-shard", "Ground Tera Shard"}, + {PrebuiltOptions::ICE_TERA, "ice-tera-shard", "Ice Tera Shard"}, + {PrebuiltOptions::NORMAL_TERA, "normal-tera-shard", "Normal Tera Shard"}, + {PrebuiltOptions::POISON_TERA, "poison-tera-shard", "Poison Tera Shard"}, + {PrebuiltOptions::PSYCHIC_TERA, "psychic-tera-shard", "Psychic Tera Shard"}, + {PrebuiltOptions::ROCK_TERA, "rock-tera-shard", "Rock Tera Shard"}, + {PrebuiltOptions::STEEL_TERA, "steel-tera-shard", "Steel Tera Shard"}, + {PrebuiltOptions::WATER_TERA, "water-tera-shard", "Water Tera Shard"}, + {PrebuiltOptions::STELLAR_TERA, "stellar-tera-shard", "Stellar Tera Shard"}, + + }); + return database; +} + + +static const std::vector& ItemPrinter_AllOptions(){ + // - Specific item seeds taken from Anubis's Item printer seeds + // - https://gist.github.com/Lusamine/112d4230919fadd254f0e6dfca850471 + // - How I chose the specific item seeds + // - seeds (and adjacent seeds +/- 2) that didn't also trigger item/ball bonuses. This is because + // accidentally triggering a ball bonus, may prevent you from intentionally triggering an item bonus + // on the next job, and vice versa for the item bonus. + // - seconds value: minimum of 8. ideally less than 20. + // - Confirmation of seeds done with Kurt's ItemPrinterDeGacha tool + static const std::vector database{ + // 2044-05-06 15:33:08 + // Calcium + {2346161588, PrebuiltOptions::ITEM_BONUS, ItemPrinterJobs::Jobs_1, 0}, + + // 2024-06-04 00:37:08 + // Full Restore + {1717461428, PrebuiltOptions::BALL_BONUS, ItemPrinterJobs::Jobs_1, 0}, + + // 958172368, 2000-05-12 22:59:28 + // 16 total Ability Patches + // x36 Dark Tera Shard + // x4 Ability Patch + // x4 Ability Patch + // x4 Ability Patch + // x4 Ability Patch + {958172368, PrebuiltOptions::ABILITY_PATCH, ItemPrinterJobs::Jobs_5, 16}, + + // 1991472489, 2033-02-08 10:48:09 + // 1040000 exp, 28 total Exp. Candy XL + // x10 Exp. Candy XL + // x4 Protein + // x20 Exp. Candy L + // x8 Exp. Candy XL + // x10 Exp. Candy XL + {1991472489, PrebuiltOptions::EXP_CANDY, ItemPrinterJobs::Jobs_5, 28}, + + // 2030-03-11 16:44:09 + // 18 total PP Maxes + // 6x PP Max, 6x PP Max, 14x Honey, 10x Revive, 6x PP Max + {1899477849, PrebuiltOptions::PP_MAX, ItemPrinterJobs::Jobs_5, 18}, + + // 2049-08-18 23:51:08 + {2512943468, PrebuiltOptions::ASSORTED_BALLS_1, ItemPrinterJobs::Jobs_10, 1}, + + // 2031-10-08 07:09:09 + {1949209749, PrebuiltOptions::ASSORTED_BALLS_2, ItemPrinterJobs::Jobs_10, 1}, + + // 2020-03-03 06:38:18 + {1583217498, PrebuiltOptions::ASSORTED_BALLS_3, ItemPrinterJobs::Jobs_10, 1}, + + // 2005-11-07 11:32:08 + // x1 Master Ball + // x1 Master Ball + // x5 Great Ball + // x1 Master Ball + // x1 Master Ball + {1131363128, PrebuiltOptions::MASTER_BALL, ItemPrinterJobs::Jobs_5, 4}, + + // 2034-09-01 02:33:39 + {2040690819, PrebuiltOptions::FAST_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2046-12-11 02:23:17 + {2428107797, PrebuiltOptions::FRIEND_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2057-11-21 04:28:37 + {2773542517, PrebuiltOptions::LURE_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2045-03-17 10:05:38 + {2373357938, PrebuiltOptions::LEVEL_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2029-07-24 11:53:11 + {1879588391, PrebuiltOptions::HEAVY_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2023-05-22 05:36:11 + {1684733771, PrebuiltOptions::LOVE_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2042-10-14 05:56:33 + {2296878993, PrebuiltOptions::MOON_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2054-03-22 09:31:21 + {2657784681, PrebuiltOptions::DREAM_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2009-06-05 20:17:11 + {1244233031, PrebuiltOptions::SPORT_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2049-01-02 01:20:22 + {2493163222, PrebuiltOptions::SAFARI_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2037-02-02 15:37:15 + {2117201835, PrebuiltOptions::BEAST_BALL, ItemPrinterJobs::Jobs_5, 5}, + + // 2246577010, 2041-03-11 01:10:10 + // 134 Normal Tera Shards, 134 total Tera Shards + // x40 Normal Tera Shard + // x28 Normal Tera Shard + // x16 Normal Tera Shard + // x38 Normal Tera Shard + // x12 Normal Tera Shard + {2246577010, PrebuiltOptions::NORMAL_TERA, ItemPrinterJobs::Jobs_5, 134}, + + // 2669513710, 2054-08-05 03:35:10 + // 148 Fire Tera Shards, 148 total Tera Shards + // x40 Fire Tera Shard + // x36 Fire Tera Shard + // x40 Fire Tera Shard + // x32 Fire Tera Shard + // x20 Honey + {2669513710, PrebuiltOptions::FIRE_TERA, ItemPrinterJobs::Jobs_5, 148}, + + // 2419526534, 2046-09-02 18:42:14 + // 120 Water Tera Shards, 154 total Tera Shards + // x40 Water Tera Shard + // x8 Full Restore + // x40 Water Tera Shard + // x34 Flying Tera Shard + // x40 Water Tera Shard + {2419526534, PrebuiltOptions::WATER_TERA, ItemPrinterJobs::Jobs_5, 120}, + + // 1300121653, 2011-03-14 16:54:13 + // 138 Electric Tera Shards, 138 total Tera Shards + // x26 Electric Tera Shard + // x4 Light Clay + // x40 Electric Tera Shard + // x40 Electric Tera Shard + // x32 Electric Tera Shard + {1300121653, PrebuiltOptions::ELECTRIC_TERA, ItemPrinterJobs::Jobs_5, 138}, + + // 1258326250, 2009-11-15 23:04:10 + // 122 Grass Tera Shards, 122 total Tera Shards + // x30 Grass Tera Shard + // x12 Tiny Mushroom + // x38 Grass Tera Shard + // x34 Grass Tera Shard + // x20 Grass Tera Shard + {1258326250, PrebuiltOptions::GRASS_TERA, ItemPrinterJobs::Jobs_5, 122}, + + // 2567326030, 2051-05-10 10:07:10 + // 134 Ice Tera Shards, 134 total Tera Shards + // x38 Ice Tera Shard + // x16 Ice Tera Shard + // x40 Ice Tera Shard + // x40 Ice Tera Shard + // x2 Metal Alloy + {2567326030, PrebuiltOptions::ICE_TERA, ItemPrinterJobs::Jobs_5, 134}, + + // 1510682535, 2017-11-14 18:02:15 + // 132 Fighting Tera Shards, 132 total Tera Shards + // x40 Fighting Tera Shard + // x32 Fighting Tera Shard + // x20 Fighting Tera Shard + // x40 Fighting Tera Shard + // x6 Shiny Stone + {1510682535, PrebuiltOptions::FIGHTING_TERA, ItemPrinterJobs::Jobs_5, 132}, + + // 2041396572, 2034-09-09 06:36:12 + // 140 Poison Tera Shards, 140 total Tera Shards + // x4 Electirizer + // x32 Poison Tera Shard + // x36 Poison Tera Shard + // x38 Poison Tera Shard + // x34 Poison Tera Shard + {2041396572, PrebuiltOptions::POISON_TERA, ItemPrinterJobs::Jobs_5, 140}, + + // 1463321889, 2016-05-15 14:18:09 + // 130 Ground Tera Shards, 130 total Tera Shards + // x10 PP Up + // x28 Ground Tera Shard + // x34 Ground Tera Shard + // x30 Ground Tera Shard + // x38 Ground Tera Shard + {1463321889, PrebuiltOptions::GROUND_TERA, ItemPrinterJobs::Jobs_5, 130}, + + // 1580633500, 2020-02-02 08:51:40 + // 128 Flying Tera Shards, 128 total Tera Shards + // x22 Flying Tera Shard + // x30 Flying Tera Shard + // x28 Flying Tera Shard + // x38 Flying Tera Shard + // x10 Flying Tera Shard + {1580633500, PrebuiltOptions::FLYING_TERA, ItemPrinterJobs::Jobs_5, 128}, + + // 2190593713, 2039-06-02 02:15:13 + // 134 Psychic Tera Shards, 134 total Tera Shards + // x30 Psychic Tera Shard + // x4 Never-Melt Ice + // x28 Psychic Tera Shard + // x36 Psychic Tera Shard + // x40 Psychic Tera Shard + {2190593713, PrebuiltOptions::PSYCHIC_TERA, ItemPrinterJobs::Jobs_5, 134}, + + // 2458109848, 2047-11-23 08:17:28 + // 134 Bug Tera Shards, 134 total Tera Shards + // x4 Ether + // x38 Bug Tera Shard + // x34 Bug Tera Shard + // x32 Bug Tera Shard + // x30 Bug Tera Shard + {2458109848, PrebuiltOptions::BUG_TERA, ItemPrinterJobs::Jobs_5, 134}, + + // 2801954289, 2058-10-16 00:38:09 + // 120 Rock Tera Shards, 120 total Tera Shards + // x40 Rock Tera Shard + // x40 Rock Tera Shard + // x16 Pretty Feather + // x40 Rock Tera Shard + // x18 Stardust + {2801954289, PrebuiltOptions::ROCK_TERA, ItemPrinterJobs::Jobs_5, 120}, + + // 1509904271, 2017-11-05 17:51:11 + // 122 Ghost Tera Shards, 122 total Tera Shards + // x38 Ghost Tera Shard + // x36 Ghost Tera Shard + // x12 Ghost Tera Shard + // x4 Magnet + // x36 Ghost Tera Shard + {1509904271, PrebuiltOptions::GHOST_TERA, ItemPrinterJobs::Jobs_5, 122}, + + // 2155674309, 2038-04-23 22:25:09 + // 136 Dragon Tera Shards, 136 total Tera Shards + // x2 Ability Patch + // x24 Dragon Tera Shard + // x38 Dragon Tera Shard + // x40 Dragon Tera Shard + // x34 Dragon Tera Shard + {2155674309, PrebuiltOptions::DRAGON_TERA, ItemPrinterJobs::Jobs_5, 136}, + + // 2537180413, 2050-05-26 12:20:13 + // 120 Dark Tera Shards, 120 total Tera Shards + // x20 Dark Tera Shard + // x28 Dark Tera Shard + // x32 Dark Tera Shard + // x40 Dark Tera Shard + // x4 Prism Scale + {2537180413, PrebuiltOptions::DARK_TERA, ItemPrinterJobs::Jobs_5, 120}, + + // 1766067369, 2025-12-18 14:16:09 + // 120 Steel Tera Shards, 120 total Tera Shards + // x40 Steel Tera Shard + // x24 Steel Tera Shard + // x38 Steel Tera Shard + // x18 Steel Tera Shard + // x4 Berry Sweet + {1766067369, PrebuiltOptions::STEEL_TERA, ItemPrinterJobs::Jobs_5, 120}, + + // 2183028974, 2039-03-06 12:56:14 + // 120 Fairy Tera Shards, 134 total Tera Shards + // x40 Fairy Tera Shard + // x40 Fairy Tera Shard + // x14 Water Tera Shard + // x12 Tiny Bamboo Shoot + // x40 Fairy Tera Shard + {2183028974, PrebuiltOptions::FAIRY_TERA, ItemPrinterJobs::Jobs_5, 120}, + + // 1165654034, 2006-12-09 08:47:14 + // 88 Stellar Tera Shards, 88 total Tera Shards + // x30 Stellar Tera Shard + // x6 Max Revive + // x28 Stellar Tera Shard + // x30 Stellar Tera Shard + // x2 Clover Sweet + {1165654034, PrebuiltOptions::STELLAR_TERA, ItemPrinterJobs::Jobs_5, 88}, + }; + return database; +}; + +static std::map make_ItemPrinter_option_lookup_by_enum(){ + std::map ret; + for (const ItemPrinterEnumOption& item : ItemPrinter_AllOptions()){ + if (!ret.emplace(item.enum_value, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Enum: " + std::to_string((int)item.enum_value)); + } + } + return ret; +} +const ItemPrinterEnumOption& option_lookup_by_enum(PrebuiltOptions enum_value){ + static const std::map database = make_ItemPrinter_option_lookup_by_enum(); + auto iter = database.find(enum_value); + if (iter != database.end()){ + return *iter->second; + }else{ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Enum: " + std::to_string((int)enum_value)); + } +} +static std::map make_ItemPrinter_option_lookup_by_seed(){ + std::map ret; + for (const ItemPrinterEnumOption& item : ItemPrinter_AllOptions()){ + if (!ret.emplace(item.seed, &item).second){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Duplicate Seed: " + std::to_string(item.seed)); + } + } + return ret; +} +const ItemPrinterEnumOption* option_lookup_by_seed(int64_t seed){ + static const std::map database = make_ItemPrinter_option_lookup_by_seed(); + auto iter = database.find(seed); + if (iter != database.end()){ + return iter->second; + }else{ + return nullptr; + } +} + + + +DateSeed get_date_seed(int64_t seed){ + // This is the function that we would replace with Kurt's seed calculator. + + static const std::map DATABASE{ + {2346161588, {2346161588, {"calcium"}}}, + {2346161588 - 2, {2346161588 - 2, {"stardust"}}}, + {2346161588 - 1, {2346161588 - 1, {"tiny-mushroom"}}}, + {2346161588 + 1, {2346161588 + 1, {"max-ether"}}}, + {2346161588 + 2, {2346161588 + 2, {"electric-tera-shard"}}}, + + {1717461428, {1717461428, {"full-restore"}}}, + {1717461428 - 2, {1717461428 - 2, {"balm-mushroom"}}}, + {1717461428 - 1, {1717461428 - 1, {"revive"}}}, + {1717461428 + 1, {1717461428 + 1, {"fairy-tera-shard"}}}, + {1717461428 + 2, {1717461428 + 2, {"big-bamboo-shoot"}}}, + + {958172368, {958172368, {"dark-tera-shard", "ability-patch", "ability-patch", "ability-patch", "ability-patch"}}}, + {958172368 - 2, {958172368 - 2, {"dark-tera-shard", "revive", "reaper-cloth", "ability-patch", "poison-tera-shard"}}}, + {958172368 - 1, {958172368 - 1, {"dark-tera-shard", "fire-tera-shard", "big-bamboo-shoot", "balm-mushroom", "super-potion"}}}, + {958172368 + 1, {958172368 + 1, {"dark-tera-shard", "pearl", "spell-tag", "flower-sweet", "ribbon-sweet"}}}, + {958172368 + 2, {958172368 + 2, {"dark-tera-shard", "water-stone", "max-potion", "tiny-mushroom", "electric-tera-shard"}}}, + + {1991472489, {1991472489, {"exp-candy-xl", "protein", "exp-candy-l", "exp-candy-xl", "exp-candy-xl"}}}, + {1991472489 - 2, {1991472489 - 2, {"exp-candy-xl", "tiny-bamboo-shoot", "exp-candy-s", "iron", "tiny-bamboo-shoot"}}}, + {1991472489 - 1, {1991472489 - 1, {"exp-candy-xl", "toxic-orb", "rare-bone", "silver-powder", "lucky-egg"}}}, + {1991472489 + 1, {1991472489 + 1, {"exp-candy-xl", "silver-powder", "dubious-disc", "mystic-water", "toxic-orb"}}}, + {1991472489 + 2, {1991472489 + 2, {"exp-candy-xl", "tiny-bamboo-shoot", "toxic-orb", "ice-stone", "charcoal"}}}, + + {2246577010, {2246577010, {"normal-tera-shard", "normal-tera-shard", "normal-tera-shard", "normal-tera-shard", "normal-tera-shard"}}}, + {2246577010 - 2, {2246577010 - 2, {"normal-tera-shard", "exp-candy-l", "star-piece", "tiny-mushroom", "rock-tera-shard"}}}, + {2246577010 - 1, {2246577010 - 1, {"normal-tera-shard", "oval-stone", "ether", "stardust", "steel-tera-shard"}}}, + {2246577010 + 1, {2246577010 + 1, {"normal-tera-shard", "exp-candy-s", "ether", "elixir", "big-pearl"}}}, + {2246577010 + 2, {2246577010 + 2, {"normal-tera-shard", "dragon-tera-shard", "ice-tera-shard", "exp-candy-xl", "black-sludge"}}}, + + {2669513710, {2669513710, {"fire-tera-shard", "fire-tera-shard", "fire-tera-shard", "fire-tera-shard", "honey"}}}, + {2669513710 - 2, {2669513710 - 2, {"fire-tera-shard", "flame-orb", "steel-tera-shard", "fire-stone", "max-revive"}}}, + {2669513710 - 1, {2669513710 - 1, {"fire-tera-shard", "exp-candy-xs", "miracle-seed", "sun-stone", "iron"}}}, + {2669513710 + 1, {2669513710 + 1, {"fire-tera-shard", "poison-tera-shard", "love-sweet", "safety-goggles", "exp-candy-m"}}}, + {2669513710 + 2, {2669513710 + 2, {"fire-tera-shard", "rare-bone", "dubious-disc", "berry-sweet", "hp-up"}}}, + + {2419526534, {2419526534, {"water-tera-shard", "full-restore", "water-tera-shard", "flying-tera-shard", "water-tera-shard"}}}, + {2419526534 - 2, {2419526534 - 2, {"water-tera-shard", "exp-candy-xs", "flame-orb", "exp-candy-s", "honey"}}}, + {2419526534 - 1, {2419526534 - 1, {"water-tera-shard", "never-melt-ice", "rock-tera-shard", "hp-up", "sun-stone"}}}, + {2419526534 + 1, {2419526534 + 1, {"water-tera-shard", "heavy-duty-boots", "moon-stone", "strawberry-sweet", "exp-candy-xs"}}}, + {2419526534 + 2, {2419526534 + 2, {"water-tera-shard", "ghost-tera-shard", "max-revive", "ground-tera-shard", "exp-candy-xl"}}}, + + {1300121653, {1300121653, {"electric-tera-shard", "light-clay", "electric-tera-shard", "electric-tera-shard", "electric-tera-shard"}}}, + {1300121653 - 2, {1300121653 - 2, {"electric-tera-shard", "elixir", "full-restore", "upgrade", "toxic-orb"}}}, + {1300121653 - 1, {1300121653 - 1, {"electric-tera-shard", "exp-candy-xs", "steel-tera-shard", "big-mushroom", "exp-candy-s"}}}, + {1300121653 + 1, {1300121653 + 1, {"electric-tera-shard", "calcium", "ground-tera-shard", "water-tera-shard", "upgrade"}}}, + {1300121653 + 2, {1300121653 + 2, {"electric-tera-shard", "max-potion", "charcoal", "exp-candy-xs", "grass-tera-shard"}}}, + + {1258326250, {1258326250, {"grass-tera-shard", "tiny-mushroom", "grass-tera-shard", "grass-tera-shard", "grass-tera-shard"}}}, + {1258326250 - 2, {1258326250 - 2, {"grass-tera-shard", "pretty-feather", "exp-candy-m", "bug-tera-shard", "tiny-mushroom"}}}, + {1258326250 - 1, {1258326250 - 1, {"grass-tera-shard", "ghost-tera-shard", "bug-tera-shard", "silver-powder", "berry-sweet"}}}, + {1258326250 + 1, {1258326250 + 1, {"grass-tera-shard", "steel-tera-shard", "honey", "strawberry-sweet", "normal-tera-shard"}}}, + {1258326250 + 2, {1258326250 + 2, {"grass-tera-shard", "exp-candy-xl", "exp-candy-xs", "zinc", "dragon-fang"}}}, + + {2567326030, {2567326030, {"ice-tera-shard", "ice-tera-shard", "ice-tera-shard", "ice-tera-shard", "metal-alloy"}}}, + {2567326030 - 2, {2567326030 - 2, {"ice-tera-shard", "pearl-string", "dragon-tera-shard", "sun-stone", "water-tera-shard"}}}, + {2567326030 - 1, {2567326030 - 1, {"ice-tera-shard", "scope-lens", "full-restore", "dubious-disc", "lucky-egg"}}}, + {2567326030 + 1, {2567326030 + 1, {"ice-tera-shard", "poison-barb", "leaf-stone", "cracked-pot", "ghost-tera-shard"}}}, + {2567326030 + 2, {2567326030 + 2, {"ice-tera-shard", "exp-candy-xs", "rock-tera-shard", "loaded-dice", "Pretty Feather"}}}, + + {1510682535, {1510682535, {"fighting-tera-shard", "fighting-tera-shard", "fighting-tera-shard", "fighting-tera-shard", "shiny-stone"}}}, + {1510682535 - 2, {1510682535 - 2, {"fairy-feather", "normal-tera-shard", "air-balloon", "poison-tera-shard", "pearl"}}}, + {1510682535 - 1, {1510682535 - 1, {"strawberry-sweet", "electric-tera-shard", "calcium", "revive", "ghost-tera-shard"}}}, + {1510682535 + 1, {1510682535 + 1, {"miracle-seed", "fighting-tera-shard", "ice-tera-shard", "light-clay", "dark-tera-shard"}}}, + {1510682535 + 2, {1510682535 + 2, {"rare-bone", "max-elixir", "leaf-stone", "metal-alloy", "magmarizer"}}}, + + {2041396572, {2041396572, {"electirizer", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard"}}}, + {2041396572 - 2, {2041396572 - 2, {"electirizer", "upgrade", "zinc", "elixir", "revive"}}}, + {2041396572 - 1, {2041396572 - 1, {"electirizer", "flame-orb", "magmarizer", "hp-up", "pretty-feather"}}}, + {2041396572 + 1, {2041396572 + 1, {"electirizer", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard", "poison-tera-shard"}}}, + {2041396572 + 2, {2041396572 + 2, {"electirizer", "pp-up", "rock-tera-shard", "big-mushroom", "light-clay"}}}, + + {1463321889, {1463321889, {"pp-up", "ground-tera-shard", "ground-tera-shard", "ground-tera-shard", "ground-tera-shard"}}}, + {1463321889 - 2, {1463321889 - 2, {"pp-up", "pretty-feather", "max-ether", "big-pearl", "carbos"}}}, + {1463321889 - 1, {1463321889 - 1, {"pp-up", "spell-tag", "bug-tera-shard", "pearl", "fighting-tera-shard"}}}, + {1463321889 + 1, {1463321889 + 1, {"pp-up", "metal-alloy", "full-restore", "pearl", "silver-powder"}}}, + {1463321889 + 2, {1463321889 + 2, {"pp-up", "ghost-tera-shard", "nugget", "safety-goggles", "leftovers"}}}, + + {1580633500, {1580633500, {"flying-tera-shard", "flying-tera-shard", "flying-tera-shard", "flying-tera-shard", "flying-tera-shard"}}}, + {1580633500 - 2, {1580633500 - 2, {"black-glasses", "big-nugget", "max-revive", "pearl-string", "balm-mushroom"}}}, + {1580633500 - 1, {1580633500 - 1, {"loaded-dice", "exp-candy-s", "strawberry-sweet", "never-melt-ice", "moon-stone"}}}, + {1580633500 + 1, {1580633500 + 1, {"water-stone", "rare-bone", "max-ether", "moon-stone", "ability-patch"}}}, + {1580633500 + 2, {1580633500 + 2, {"max-ether", "big-bamboo-shoot", "iron", "big-mushroom", "pearl"}}}, + + {2190593713, {2190593713, {"psychic-tera-shard", "never-melt-ice", "psychic-tera-shard", "psychic-tera-shard", "psychic-tera-shard"}}}, + {2190593713 - 2, {2190593713 - 2, {"psychic-tera-shard", "big-mushroom", "fairy-feather", "fairy-tera-shard", "reaper-cloth"}}}, + {2190593713 - 1, {2190593713 - 1, {"psychic-tera-shard", "electric-tera-shard", "pearl", "stellar-tera-shard", "dawn-stone"}}}, + {2190593713 + 1, {2190593713 + 1, {"psychic-tera-shard", "pearl-string", "twisted-spoon", "big-pearl", "iron"}}}, + {2190593713 + 2, {2190593713 + 2, {"psychic-tera-shard", "heavy-duty-boots", "water-tera-shard", "rock-tera-shard", "twisted-spoon"}}}, + + {2458109848, {2458109848, {"ether", "bug-tera-shard", "bug-tera-shard", "bug-tera-shard", "bug-tera-shard"}}}, + {2458109848 - 2, {2458109848 - 2, {"ether", "big-nugget", "mystic-water", "pretty-feather", "pretty-feather"}}}, + {2458109848 - 1, {2458109848 - 1, {"ether", "psychic-tera-shard", "exp-candy-s", "honey", "sharp-beak"}}}, + {2458109848 + 1, {2458109848 + 1, {"ether", "black-glasses", "fighting-tera-shard", "tiny-bamboo-shoot", "poison-barb"}}}, + {2458109848 + 2, {2458109848 + 2, {"ether", "exp-candy-xl", "normal-tera-shard", "fairy-tera-shard", "balm-mushroom"}}}, + + {2801954289, {2801954289, {"rock-tera-shard", "rock-tera-shard", "pretty-feather", "rock-tera-shard", "stardust"}}}, + {2801954289 - 2, {2801954289 - 2, {"max-revive", "scope-lens", "razor-claw", "big-nugget", "tiny-bamboo-shoot"}}}, + {2801954289 - 1, {2801954289 - 1, {"iron", "dark-tera-shard", "air-balloon", "rare-bone", "ability-patch"}}}, + {2801954289 + 1, {2801954289 + 1, {"normal-tera-shard", "ground-tera-shard", "honey", "upgrade", "honey"}}}, + {2801954289 + 2, {2801954289 + 2, {"heavy-duty-boots", "ice-tera-shard", "sun-stone", "dubious-disc", "pearl"}}}, + + {1509904271, {1509904271, {"ghost-tera-shard", "ghost-tera-shard", "ghost-tera-shard", "magnet", "ghost-tera-shard"}}}, + {1509904271 - 2, {1509904271 - 2, {"ghost-tera-shard", "hyper-potion", "toxic-orb", "magmarizer", "black-glasses"}}}, + {1509904271 - 1, {1509904271 - 1, {"ghost-tera-shard", "black-belt", "pp-up", "ice-tera-shard", "magmarizer"}}}, + {1509904271 + 1, {1509904271 + 1, {"ghost-tera-shard", "big-nugget", "hp-up", "gold-bottle-cap", "big-bamboo-shoot"}}}, + {1509904271 + 2, {1509904271 + 2, {"ghost-tera-shard", "hp-up", "elixir", "water-tera-shard", "pp-up"}}}, + + {2155674309, {2155674309, {"ability-patch", "dragon-tera-shard", "dragon-tera-shard", "dragon-tera-shard", "dragon-tera-shard"}}}, + {2155674309 - 2, {2155674309 - 2, {"comet-shard", "soft-sand", "big-mushroom", "steel-tera-shard", "metronome"}}}, + {2155674309 - 1, {2155674309 - 1, {"pearl", "balm-mushroom", "moon-stone", "protein", "ability-patch"}}}, + {2155674309 + 1, {2155674309 + 1, {"reaper-cloth", "hp-up", "revive", "light-clay", "focus-band"}}}, + {2155674309 + 2, {2155674309 + 2, {"spell-tag", "love-sweet", "fire-tera-shard", "ether", "black-belt"}}}, + + {2537180413, {2537180413, {"dark-tera-shard", "dark-tera-shard", "dark-tera-shard", "dark-tera-shard", "prism-scale"}}}, + {2537180413 - 2, {2537180413 - 2, {"dark-tera-shard", "upgrade", "big-mushroom", "normal-tera-shard", "exp-candy-m"}}}, + {2537180413 - 1, {2537180413 - 1, {"dark-tera-shard", "pp-max", "calcium", "rock-tera-shard", "hard-stone"}}}, + {2537180413 + 1, {2537180413 + 1, {"dark-tera-shard", "leaf-stone", "big-pearl", "comet-shard", "exp-candy-m"}}}, + {2537180413 + 2, {2537180413 + 2, {"dark-tera-shard", "ground-tera-shard", "fairy-tera-shard", "exp-candy-xs", "fighting-tera-shard"}}}, + + {1766067369, {1766067369, {"steel-tera-shard", "steel-tera-shard", "steel-tera-shard", "steel-tera-shard", "berry-sweet"}}}, + {1766067369 - 2, {1766067369 - 2, {"steel-tera-shard", "bug-tera-shard", "exp-candy-xl", "pretty-feather", "silk-scarf"}}}, + {1766067369 - 1, {1766067369 - 1, {"steel-tera-shard", "tiny-mushroom", "super-potion", "sharp-beak", "ice-tera-shard"}}}, + {1766067369 + 1, {1766067369 + 1, {"steel-tera-shard", "moon-stone", "exp-candy-xl", "iron", "exp-candy-xs"}}}, + {1766067369 + 2, {1766067369 + 2, {"steel-tera-shard", "metal-alloy", "ability-patch", "pp-up", "rare-bone"}}}, + + {2183028974, {2183028974, {"fairy-tera-shard", "fairy-tera-shard", "water-tera-shard", "tiny-bamboo-shoot", "fairy-tera-shard"}}}, + {2183028974 - 2, {2183028974 - 2, {"max-elixir", "never-melt-ice", "pearl", "max-potion", "pp-up"}}}, + {2183028974 - 1, {2183028974 - 1, {"full-restore", "psychic-tera-shard", "gold-bottle-cap", "dawn-stone", "never-melt-ice"}}}, + {2183028974 + 1, {2183028974 + 1, {"ice-tera-shard", "twisted-spoon", "exp-candy-s", "max-elixir", "razor-fang"}}}, + {2183028974 + 2, {2183028974 + 2, {"exp-candy-xl", "bug-tera-shard", "star-piece", "hp-up", "bug-tera-shard"}}}, + + {1165654034, {1165654034, {"stellar-tera-shard", "max-revive", "stellar-tera-shard", "stellar-tera-shard", "clover-sweet"}}}, + {1165654034 - 2, {1165654034 - 2, {"stellar-tera-shard", "pp-up", "scope-lens", "electric-tera-shard", "metronome"}}}, + {1165654034 - 1, {1165654034 - 1, {"stellar-tera-shard", "dragon-tera-shard", "honey", "steel-tera-shard", "max-potion"}}}, + {1165654034 + 1, {1165654034 + 1, {"stellar-tera-shard", "full-heal", "toxic-orb", "max-potion", "miracle-seed"}}}, + {1165654034 + 2, {1165654034 + 2, {"stellar-tera-shard", "big-bamboo-shoot", "poison-tera-shard", "honey", "oval-stone"}}}, + + {1131363128, {1131363128, {}, {"master-ball", "master-ball", "great-ball", "master-ball", "master-ball"}}}, + {1131363128 - 2, {1131363128 - 2, {}, {"master-ball", "great-ball", "quick-ball", "luxury-ball", "heal-ball"}}}, + {1131363128 - 1, {1131363128 - 1, {}, {"master-ball", "great-ball", "timer-ball", "fast-ball", "love-ball"}}}, + {1131363128 + 1, {1131363128 + 1, {}, {"master-ball", "premier-ball", "great-ball", "luxury-ball", "heal-ball"}}}, + {1131363128 + 2, {1131363128 + 2, {}, {"master-ball", "quick-ball", "poke-ball", "premier-ball", "poke-ball"}}}, + + {2040690819, {2040690819, {}, {"fast-ball", "fast-ball", "fast-ball", "fast-ball", "fast-ball"}}}, + {2040690819 - 2, {2040690819 - 2, {}, {"fast-ball", "lure-ball", "dream-ball", "friend-ball", "level-ball"}}}, + {2040690819 - 1, {2040690819 - 1, {}, {"fast-ball", "great-ball", "quick-ball", "great-ball", "heal-ball"}}}, + {2040690819 + 1, {2040690819 + 1, {}, {"fast-ball", "dream-ball", "luxury-ball", "luxury-ball", "premier-ball"}}}, + {2040690819 + 2, {2040690819 + 2, {}, {"fast-ball", "luxury-ball", "great-ball", "poke-ball", "premier-ball"}}}, + + {2428107797, {2428107797, {}, {"friend-ball", "friend-ball", "friend-ball", "friend-ball", "friend-ball"}}}, + {2428107797 - 2, {2428107797 - 2, {}, {"friend-ball", "great-ball", "sport-ball", "great-ball", "great-ball"}}}, + {2428107797 - 1, {2428107797 - 1, {}, {"friend-ball", "premier-ball", "heal-ball", "repeat-ball", "nest-ball"}}}, + {2428107797 + 1, {2428107797 + 1, {}, {"friend-ball", "premier-ball", "heavy-ball", "timer-ball", "friend-ball"}}}, + {2428107797 + 2, {2428107797 + 2, {}, {"friend-ball", "heal-ball", "great-ball", "beast-ball", "moon-ball"}}}, + + {2773542517, {2773542517, {}, {"lure-ball", "lure-ball", "lure-ball", "lure-ball", "lure-ball"}}}, + {2773542517 - 2, {2773542517 - 2, {}, {"lure-ball", "premier-ball", "premier-ball", "great-ball", "poke-ball"}}}, + {2773542517 - 1, {2773542517 - 1, {}, {"dream-ball", "poke-ball", "poke-ball", "luxury-ball", "poke-ball"}}}, + {2773542517 + 1, {2773542517 + 1, {}, {"luxury-ball", "premier-ball", "great-ball", "luxury-ball", "fast-ball"}}}, + {2773542517 + 2, {2773542517 + 2, {}, {"timer-ball", "safari-ball", "dive-ball", "poke-ball", "premier-ball"}}}, + + {2373357938, {2373357938, {}, {"level-ball", "level-ball", "level-ball", "level-ball", "level-ball"}}}, + {2373357938 - 2, {2373357938 - 2, {}, {"dusk-ball", "heal-ball", "luxury-ball", "premier-ball", "poke-ball"}}}, + {2373357938 - 1, {2373357938 - 1, {}, {"great-ball", "dive-ball", "dream-ball", "luxury-ball", "luxury-ball"}}}, + {2373357938 + 1, {2373357938 + 1, {}, {"repeat-ball", "heal-ball", "heal-ball", "luxury-ball", "dive-ball"}}}, + {2373357938 + 2, {2373357938 + 2, {}, {"luxury-ball", "master-ball", "premier-ball", "ultra-ball", "heal-ball"}}}, + + {1879588391, {1879588391, {}, {"heavy-ball", "heavy-ball", "heavy-ball", "heavy-ball", "heavy-ball"}}}, + {1879588391 - 2, {1879588391 - 2, {}, {"heavy-ball", "nest-ball", "nest-ball", "heal-ball", "luxury-ball"}}}, + {1879588391 - 1, {1879588391 - 1, {}, {"heavy-ball", "poke-ball", "premier-ball", "premier-ball", "heal-ball"}}}, + {1879588391 + 1, {1879588391 + 1, {}, {"heavy-ball", "heal-ball", "premier-ball", "timer-ball", "premier-ball"}}}, + {1879588391 + 2, {1879588391 + 2, {}, {"heavy-ball", "ultra-ball", "heal-ball", "quick-ball", "beast-ball"}}}, + + {1684733771, {1684733771, {}, {"love-ball", "love-ball", "love-ball", "love-ball", "love-ball"}}}, + {1684733771 - 2, {1684733771 - 2, {}, {"love-ball", "sport-ball", "great-ball", "poke-ball", "poke-ball"}}}, + {1684733771 - 1, {1684733771 - 1, {}, {"love-ball", "poke-ball", "great-ball", "luxury-ball", "master-ball"}}}, + {1684733771 + 1, {1684733771 + 1, {}, {"love-ball", "great-ball", "luxury-ball", "luxury-ball", "poke-ball"}}}, + {1684733771 + 2, {1684733771 + 2, {}, {"love-ball", "luxury-ball", "premier-ball", "poke-ball", "quick-ball"}}}, + + {2296878993, {2296878993, {}, {"moon-ball", "moon-ball", "moon-ball", "moon-ball", "moon-ball"}}}, + {2296878993 - 2, {2296878993 - 2, {}, {"luxury-ball", "timer-ball", "premier-ball", "luxury-ball", "poke-ball"}}}, + {2296878993 - 1, {2296878993 - 1, {}, {"nest-ball", "poke-ball", "heal-ball", "premier-ball", "premier-ball"}}}, + {2296878993 + 1, {2296878993 + 1, {}, {"fast-ball", "heal-ball", "poke-ball", "dusk-ball", "luxury-ball"}}}, + {2296878993 + 2, {2296878993 + 2, {}, {"lure-ball", "heavy-ball", "luxury-ball", "heal-ball", "poke-ball"}}}, + + {2657784681, {2657784681, {}, {"dream-ball", "dream-ball", "dream-ball", "dream-ball", "dream-ball"}}}, + {2657784681 - 2, {2657784681 - 2, {}, {"master-ball", "poke-ball", "luxury-ball", "level-ball", "dream-ball"}}}, + {2657784681 - 1, {2657784681 - 1, {}, {"timer-ball", "beast-ball", "poke-ball", "premier-ball", "heal-ball"}}}, + {2657784681 + 1, {2657784681 + 1, {}, {"heavy-ball", "poke-ball", "friend-ball", "fast-ball", "heavy-ball"}}}, + {2657784681 + 2, {2657784681 + 2, {}, {"luxury-ball", "poke-ball", "luxury-ball", "quick-ball", "friend-ball"}}}, + + {1244233031, {1244233031, {}, {"sport-ball", "sport-ball", "sport-ball", "sport-ball", "sport-ball"}}}, + {1244233031 - 2, {1244233031 - 2, {}, {"sport-ball", "heal-ball", "luxury-ball", "great-ball", "heal-ball"}}}, + {1244233031 - 1, {1244233031 - 1, {}, {"sport-ball", "dream-ball", "level-ball", "poke-ball", "luxury-ball"}}}, + {1244233031 + 1, {1244233031 + 1, {}, {"moon-ball", "heal-ball", "poke-ball", "poke-ball", "heal-ball"}}}, + {1244233031 + 2, {1244233031 + 2, {}, {"moon-ball", "poke-ball", "ultra-ball", "poke-ball", "great-ball"}}}, + + {2493163222, {2493163222, {}, {"safari-ball", "safari-ball", "safari-ball", "safari-ball", "safari-ball"}}}, + {2493163222 - 2, {2493163222 - 2, {}, {"premier-ball", "great-ball", "lure-ball", "ultra-ball", "safari-ball"}}}, + {2493163222 - 1, {2493163222 - 1, {}, {"premier-ball", "great-ball", "poke-ball", "poke-ball", "poke-ball"}}}, + {2493163222 + 1, {2493163222 + 1, {}, {"poke-ball", "poke-ball", "poke-ball", "premier-ball", "great-ball"}}}, + {2493163222 + 2, {2493163222 + 2, {}, {"great-ball", "great-ball", "level-ball", "poke-ball", "safari-ball"}}}, + + {2117201835, {2117201835, {}, {"beast-ball", "beast-ball", "beast-ball", "beast-ball", "beast-ball"}}}, + {2117201835 - 2, {2117201835 - 2, {}, {"luxury-ball", "poke-ball", "lure-ball", "master-ball", "dive-ball"}}}, + {2117201835 - 1, {2117201835 - 1, {}, {"heavy-ball", "premier-ball", "premier-ball", "poke-ball", "level-ball"}}}, + {2117201835 + 1, {2117201835 + 1, {}, {"heal-ball", "great-ball", "luxury-ball", "heavy-ball", "great-ball"}}}, + {2117201835 + 2, {2117201835 + 2, {}, {"poke-ball", "premier-ball", "great-ball", "poke-ball", "dive-ball"}}}, + + {2512943468, {2512943468, {}, {"level-ball", "level-ball", "friend-ball", "lure-ball", "beast-ball", "moon-ball", "fast-ball", "dream-ball", "love-ball", "beast-ball"}}}, + {2512943468 - 2, {2512943468 - 2, {}, {"level-ball", "dusk-ball", "sport-ball", "great-ball", "dusk-ball", "great-ball", "timer-ball", "premier-ball", "premier-ball", "safari-ball"}}}, + {2512943468 - 1, {2512943468 - 1, {}, {"level-ball", "premier-ball", "dream-ball", "beast-ball", "dream-ball", "premier-ball", "luxury-ball", "lure-ball", "luxury-ball", "poke-ball"}}}, + {2512943468 + 1, {2512943468 + 1, {}, {"level-ball", "premier-ball", "sport-ball", "premier-ball", "poke-ball", "great-ball", "great-ball", "poke-ball", "luxury-ball", "dive-ball"}}}, + {2512943468 + 2, {2512943468 + 2, {}, {"level-ball", "lure-ball", "moon-ball", "heal-ball", "heal-ball", "dream-ball", "great-ball", "safari-ball", "premier-ball", "premier-ball"}}}, + + {1949209749, {1949209749, {}, {"love-ball", "dream-ball", "heavy-ball", "lure-ball", "fast-ball", "fast-ball", "safari-ball", "safari-ball", "friend-ball", "heavy-ball"}}}, + {1949209749 - 2, {1949209749 - 2, {}, {"ultra-ball", "luxury-ball", "luxury-ball", "poke-ball", "poke-ball", "moon-ball", "heal-ball", "timer-ball", "dusk-ball", "great-ball"}}}, + {1949209749 - 1, {1949209749 - 1, {}, {"net-ball", "heal-ball", "heavy-ball", "heal-ball", "dive-ball", "great-ball", "great-ball", "premier-ball", "luxury-ball", "love-ball"}}}, + {1949209749 + 1, {1949209749 + 1, {}, {"luxury-ball", "heal-ball", "poke-ball", "poke-ball", "premier-ball", "sport-ball", "luxury-ball", "premier-ball", "poke-ball", "poke-ball"}}}, + {1949209749 + 2, {1949209749 + 2, {}, {"dusk-ball", "lure-ball", "fast-ball", "premier-ball", "great-ball", "luxury-ball", "poke-ball", "safari-ball", "luxury-ball", "premier-ball"}}}, + + {1583217498, {1583217498, {}, {"sport-ball", "master-ball", "fast-ball", "master-ball", "dream-ball", "friend-ball", "lure-ball", "sport-ball", "moon-ball", "dream-ball"}}}, + {1583217498 - 2, {1583217498 - 2, {}, {"heal-ball", "net-ball", "poke-ball", "premier-ball", "poke-ball", "repeat-ball", "luxury-ball", "poke-ball", "great-ball", "heal-ball"}}}, + {1583217498 - 1, {1583217498 - 1, {}, {"poke-ball", "heal-ball", "heavy-ball", "luxury-ball", "moon-ball", "timer-ball", "premier-ball", "great-ball", "great-ball", "friend-ball"}}}, + {1583217498 + 1, {1583217498 + 1, {}, {"level-ball", "dive-ball", "great-ball", "luxury-ball", "moon-ball", "friend-ball", "timer-ball", "heal-ball", "poke-ball", "quick-ball"}}}, + {1583217498 + 2, {1583217498 + 2, {}, {"luxury-ball", "friend-ball", "dream-ball", "heal-ball", "luxury-ball", "great-ball", "premier-ball", "dusk-ball", "level-ball", "beast-ball"}}}, + + // Template +// {1717461428 - 2, {1717461428 - 2, {}, }}, +// {1717461428 - 1, {1717461428 - 1, {}, }}, +// {1717461428 + 1, {1717461428 + 1, {}, }}, +// {1717461428 + 2, {1717461428 + 2, {}, }}, + + }; + + auto iter = DATABASE.find(seed); + if (iter != DATABASE.end()){ + return iter->second; + } + + return DateSeed(); +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.h index 92b4c35d29..fe859bfc89 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterDatabase.h @@ -1,127 +1,127 @@ -/* Item Printer Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterDatabase_H -#define PokemonAutomation_PokemonSV_ItemPrinterDatabase_H - -#include "Common/Cpp/Options/EnumDropdownDatabase.h" -#include "PokemonSV_ItemPrinterTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ -namespace ItemPrinter{ - - - -enum class PrebuiltOptions{ - NONE, - ITEM_BONUS, - BALL_BONUS, - - ABILITY_PATCH, - EXP_CANDY, - PP_MAX, - - ASSORTED_BALLS_1, - ASSORTED_BALLS_2, - ASSORTED_BALLS_3, - - MASTER_BALL, - FAST_BALL, - FRIEND_BALL, - LURE_BALL, - LEVEL_BALL, - HEAVY_BALL, - LOVE_BALL, - MOON_BALL, - DREAM_BALL, - SPORT_BALL, - SAFARI_BALL, - BEAST_BALL, - - BUG_TERA, - DARK_TERA, - DRAGON_TERA, - ELECTRIC_TERA, - FAIRY_TERA, - FIGHTING_TERA, - FIRE_TERA, - FLYING_TERA, - GHOST_TERA, - GRASS_TERA, - GROUND_TERA, - ICE_TERA, - NORMAL_TERA, - POISON_TERA, - PSYCHIC_TERA, - ROCK_TERA, - STEEL_TERA, - WATER_TERA, - STELLAR_TERA, -}; -const EnumDropdownDatabase& PrebuiltOptions_Database(); - -const EnumDropdownDatabase& PrebuiltOptions_AutoMode_Database(); - -const EnumDropdownDatabase& PrebuiltOptions_Simple_Database2(); - - -struct ItemPrinterEnumOption{ - int64_t seed; - PrebuiltOptions enum_value; - ItemPrinterJobs jobs; - uint16_t quantity_obtained; // quantity obtained from the given seed, with given number of print jobs (ususally 5 print), with bonus active -}; -const ItemPrinterEnumOption& option_lookup_by_enum(PrebuiltOptions enum_value); -const ItemPrinterEnumOption* option_lookup_by_seed(int64_t seed); - - - -struct DateSeed{ - // Seed details. - int64_t seed; - std::array regular; - std::array item_bonus; - std::array ball_bonus; - - DateSeed() - : seed(0) - {} - - DateSeed( - int64_t p_seed, - std::array p_items, - std::array p_balls = {} - ) - : seed(p_seed) - , item_bonus(std::move(p_items)) - , ball_bonus(std::move(p_balls)) - {} - DateSeed( - int64_t p_seed, - std::array p_regular, - std::array p_item_bonus, - std::array p_ball_bonus - ) - : seed(p_seed) - , regular(std::move(p_regular)) - , item_bonus(std::move(p_item_bonus)) - , ball_bonus(std::move(p_ball_bonus)) - {} - - operator bool() const{ - return seed >= 0; - } -}; -DateSeed get_date_seed(int64_t seed); - - -} -} -} -} -#endif +/* Item Printer Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterDatabase_H +#define PokemonAutomation_PokemonSV_ItemPrinterDatabase_H + +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "PokemonSV_ItemPrinterTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace ItemPrinter{ + + + +enum class PrebuiltOptions{ + NONE, + ITEM_BONUS, + BALL_BONUS, + + ABILITY_PATCH, + EXP_CANDY, + PP_MAX, + + ASSORTED_BALLS_1, + ASSORTED_BALLS_2, + ASSORTED_BALLS_3, + + MASTER_BALL, + FAST_BALL, + FRIEND_BALL, + LURE_BALL, + LEVEL_BALL, + HEAVY_BALL, + LOVE_BALL, + MOON_BALL, + DREAM_BALL, + SPORT_BALL, + SAFARI_BALL, + BEAST_BALL, + + BUG_TERA, + DARK_TERA, + DRAGON_TERA, + ELECTRIC_TERA, + FAIRY_TERA, + FIGHTING_TERA, + FIRE_TERA, + FLYING_TERA, + GHOST_TERA, + GRASS_TERA, + GROUND_TERA, + ICE_TERA, + NORMAL_TERA, + POISON_TERA, + PSYCHIC_TERA, + ROCK_TERA, + STEEL_TERA, + WATER_TERA, + STELLAR_TERA, +}; +const EnumDropdownDatabase& PrebuiltOptions_Database(); + +const EnumDropdownDatabase& PrebuiltOptions_AutoMode_Database(); + +const EnumDropdownDatabase& PrebuiltOptions_Simple_Database2(); + + +struct ItemPrinterEnumOption{ + int64_t seed; + PrebuiltOptions enum_value; + ItemPrinterJobs jobs; + uint16_t quantity_obtained; // quantity obtained from the given seed, with given number of print jobs (ususally 5 print), with bonus active +}; +const ItemPrinterEnumOption& option_lookup_by_enum(PrebuiltOptions enum_value); +const ItemPrinterEnumOption* option_lookup_by_seed(int64_t seed); + + + +struct DateSeed{ + // Seed details. + int64_t seed; + std::array regular; + std::array item_bonus; + std::array ball_bonus; + + DateSeed() + : seed(0) + {} + + DateSeed( + int64_t p_seed, + std::array p_items, + std::array p_balls = {} + ) + : seed(p_seed) + , item_bonus(std::move(p_items)) + , ball_bonus(std::move(p_balls)) + {} + DateSeed( + int64_t p_seed, + std::array p_regular, + std::array p_item_bonus, + std::array p_ball_bonus + ) + : seed(p_seed) + , regular(std::move(p_regular)) + , item_bonus(std::move(p_item_bonus)) + , ball_bonus(std::move(p_ball_bonus)) + {} + + operator bool() const{ + return seed >= 0; + } +}; +DateSeed get_date_seed(int64_t seed); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp index 263f24b18d..41a982570e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.cpp @@ -1,1081 +1,1081 @@ -/* Item Printer RNG - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Qt/TimeQt.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h" -#include "PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_ItemPrinterSeedCalc.h" -#include "PokemonSV_ItemPrinterDatabase.h" -#include "PokemonSV_ItemPrinterRNG.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -ItemPrinterRNG_Descriptor::ItemPrinterRNG_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:ItemPrinterRNG", - Pokemon::STRING_POKEMON + " SV", "Item Printer RNG", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ItemPrinterRNG.md", - "Farm the Item Printer using RNG Manipulation.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} - -struct ItemPrinterRNG_Descriptor::Stats : public StatsTracker{ - Stats() - : iterations(m_stats["Rounds"]) - , prints(m_stats["Prints"]) -// , total_jobs(m_stats["Total Jobs"]) - , frame_hits(m_stats["Frame Hits"]) - , frame_misses(m_stats["Frame Misses"]) - , frame_unknown(m_stats["Unknown Frame"]) - , material_farmer_runs(m_stats["Material Farmer Runs"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Rounds"); - m_display_order.emplace_back("Prints"); -// m_display_order.emplace_back("Total Jobs", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Frame Hits"); - m_display_order.emplace_back("Frame Misses"); - m_display_order.emplace_back("Unknown Frame", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Material Farmer Runs", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& iterations; - std::atomic& prints; -// std::atomic& total_jobs; - std::atomic& frame_hits; - std::atomic& frame_misses; - std::atomic& frame_unknown; - std::atomic& material_farmer_runs; - std::atomic& errors; -}; -std::unique_ptr ItemPrinterRNG_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -ItemPrinterRNG::~ItemPrinterRNG(){ - MATERIAL_FARMER_OPTIONS.remove_listener(*this); - MATERIAL_FARMER_TRIGGER.remove_listener(*this); - DATE_SEED_TABLE.remove_listener(*this); -// AUTO_MATERIAL_FARMING.remove_listener(*this); -} - -ItemPrinterRNG::ItemPrinterRNG() - : LANGUAGE( - "Game Language:", - PokemonSwSh::IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NUM_ITEM_PRINTER_ROUNDS( - "Number of rounds per Item Printer session:
Iterate the rounds table this many times. ", - LockMode::UNLOCK_WHILE_RUNNING, 10 - ) -// , AFTER_ITEM_PRINTER_DONE_EXPLANATION( -// "Then proceed to material farming." -// ) - , OVERLAPPING_BONUS_WARNING( - "WARNING: At least one of the Ball/Item bonuses haven't been fully used up. " - "This can mess up your rewards for subsequent prints.
" - "\nNote: Each Ball/Item bonus lasts for 10 prints." - ) - , MODE( - "Item Printer mode:
", - { - {ItemPrinterMode::STANDARD_MODE, "standard", "Standard Mode: Manually select exactly what is being printed for each print job."}, - {ItemPrinterMode::AUTO_MODE, "auto", "Auto Mode: Select your desired item and its quantity, and items will be automatically printed."}, - }, - LockMode::LOCK_WHILE_RUNNING, - ItemPrinterMode::STANDARD_MODE - ) - , DESIRED_ITEM_TABLE( - "Item Table:
" - "Input your desired item and desired quantity to the table.
" - "Ensure you have enough BP and are maxed out on the following sandwich ingredients: Chorizo, Bananas, Mayonnaise, Whipped Cream. " - "Also, ensure you have a strong lead pokemon for auto-battling, for farming materials.
" - "If there are duplicate items in the table, only the higher quantity will be considered." - ) - , DATE_SEED_TABLE( - "Rounds Table:
Run the following prints in order and repeat. " - "Changes to this table take effect the next time the table starts from the beginning." - ) - , DELAY_MILLIS( - "Delay (Milliseconds):
" - "The delay from when you press A to when the game reads the date for the seed. " - "For OLED Switches, this delay is about 500 milliseconds. For older Switches, this delay is closer to 1500 milliseconds. " - "If the following option is enabled, this delay will be automatically adjusted based on how you miss the frames.", - LockMode::UNLOCK_WHILE_RUNNING, 1000, - 0, 5000 - ) - , ADJUST_DELAY( - "Automatically Adjust Delay:
Adjust the delay, depending on the desired item and the actual print result.", - LockMode::UNLOCK_WHILE_RUNNING, true - ) - , GO_HOME_WHEN_DONE(false) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.", - LockMode::UNLOCK_WHILE_RUNNING, true - ) - , MATERIAL_FARMER_TRIGGER( - "Trigger to start material farmer:
", - { - {MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS, "fixed", "Start Material Farmer when done a certain number of print jobs."}, - {MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST, "happiny-dust", "Start Material Farmer when Happiny Dust is less than a certain number."}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS - ) - , MATERIAL_FARMER_FIXED_NUM_JOBS( - "Print Jobs per Material Farming Session:
" - "Run the material farmer once for this many jobs printed.", - LockMode::UNLOCK_WHILE_RUNNING, 500, - 20, 650 - ) - , MIN_HAPPINY_DUST( - "Minimum Happiny Dust:
" - "Run the material farmer before the number of Happiny Dust drops " - "below this number.
" - "This ensures no other material drops below this number. " - "If a material starts below this threshold, it remains there.
" - "Changes to this number only take place after returning to " - "the item printer, after material farming.", - LockMode::UNLOCK_WHILE_RUNNING, 400, - 1, 999 - ) - , MATERIAL_FARMER_OPTIONS( - GroupOption::EnableMode::DEFAULT_DISABLED, - &LANGUAGE, - NOTIFICATION_STATUS_UPDATE, - NOTIFICATION_PROGRAM_FINISH, - NOTIFICATION_ERROR_RECOVERABLE, - NOTIFICATION_ERROR_FATAL - ) - , ENABLE_SEED_CALC( - "Enable Seed Calculation: (developer only)
" - "Use Kurt's seed calculation instead of hardcoded database. Ensure you have the appropriate resources.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(DESIRED_ITEM_TABLE); - PA_ADD_OPTION(NUM_ITEM_PRINTER_ROUNDS); - PA_ADD_OPTION(DATE_SEED_TABLE); - PA_ADD_OPTION(OVERLAPPING_BONUS_WARNING); - PA_ADD_OPTION(DELAY_MILLIS); - PA_ADD_OPTION(ADJUST_DELAY); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - - PA_ADD_OPTION(MATERIAL_FARMER_TRIGGER); - PA_ADD_OPTION(MATERIAL_FARMER_FIXED_NUM_JOBS); - PA_ADD_OPTION(MIN_HAPPINY_DUST); - PA_ADD_OPTION(MATERIAL_FARMER_OPTIONS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(ENABLE_SEED_CALC); - } - - PA_ADD_OPTION(NOTIFICATIONS); - - ItemPrinterRNG::on_config_value_changed(this); -// AUTO_MATERIAL_FARMING.add_listener(*this); - DATE_SEED_TABLE.add_listener(*this); - MODE.add_listener(*this); - MATERIAL_FARMER_OPTIONS.add_listener(*this); - MATERIAL_FARMER_TRIGGER.add_listener(*this); -} - -void ItemPrinterRNG::on_config_value_changed(void* object){ - - NUM_ITEM_PRINTER_ROUNDS.set_visibility( - MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED - ); - - OVERLAPPING_BONUS_WARNING.set_visibility( - (MODE != ItemPrinterMode::AUTO_MODE) && overlapping_bonus() - ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); - - DESIRED_ITEM_TABLE.set_visibility( - MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); - - DATE_SEED_TABLE.set_visibility( - MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED - ); - - ADJUST_DELAY.set_visibility( - MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED - ); - - MATERIAL_FARMER_TRIGGER.set_visibility( - (MODE != ItemPrinterMode::AUTO_MODE) && MATERIAL_FARMER_OPTIONS.enabled() - ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); - - MATERIAL_FARMER_FIXED_NUM_JOBS.set_visibility( - (MODE != ItemPrinterMode::AUTO_MODE) && MATERIAL_FARMER_OPTIONS.enabled() && (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS) - ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); - - MIN_HAPPINY_DUST.set_visibility( - (MODE != ItemPrinterMode::AUTO_MODE) && MATERIAL_FARMER_OPTIONS.enabled() && (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST) - ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); - - MATERIAL_FARMER_OPTIONS.set_visibility( - MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED - ); - - ENABLE_SEED_CALC.set_visibility( - MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED - ); - -} - - -// - return true if the user is trying to trigger another Ball/Item bonus without -// using up the previous bonus. Doing this can mess up rewards for subsequent prints, -// since a ball bonus interferes with activating an item bonus and vice versa. -// - each Bonus lasts for 10 prints. -bool ItemPrinterRNG::overlapping_bonus(){ - // for each row in table. if ball/item bonus, ensure that sum of prints in subsequent rows >=10 before the next bonus, or end of the table. - uint16_t total_prints_since_last_bonus = 10; - for (std::shared_ptr& table_row : DATE_SEED_TABLE.current_refs()){ - ItemPrinterRngRow& row = static_cast(*table_row); - if (row.desired_item == ItemPrinter::PrebuiltOptions::BALL_BONUS || row.desired_item == ItemPrinter::PrebuiltOptions::ITEM_BONUS){ - if (total_prints_since_last_bonus < 10){ - return true; - } - total_prints_since_last_bonus = 0; - }else{ - total_prints_since_last_bonus += (uint16_t)static_cast(row.jobs); - } - } - - if (total_prints_since_last_bonus < 10){ - return true; - } - - return false; -} - - -ItemPrinterPrizeResult ItemPrinterRNG::run_print_at_date( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const DateTime& date, ItemPrinterJobs jobs -){ - ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); - ItemPrinterPrizeResult prize_result; - bool printed = false; - bool overworld_seen = false; - size_t failures = 0; - std::chrono::seconds next_wait_time = std::chrono::seconds(120); - while (true){ - if (failures >= 5){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to print after 5 attempts.", - env.console - ); - } - context.wait_for_all_requests(); - - OverworldWatcher overworld(env.console, COLOR_BLUE); - AdvanceDialogWatcher dialog(COLOR_RED); - PromptDialogWatcher prompt(COLOR_GREEN); - DateChangeWatcher date_reader(env.console); - WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); - int ret = wait_until( - env.console, context, next_wait_time, - { - overworld, - dialog, - prompt, - date_reader, - material, - } - ); - next_wait_time = std::chrono::seconds(120); - switch (ret){ - case 0: - overworld_seen = true; - if (printed){ - env.log("Detected overworld... (unexpected)", COLOR_RED); - return prize_result; - } - env.log("Detected overworld... Starting print."); - pbf_press_button(context, BUTTON_A, 20, 30); - continue; - - case 1: - env.log("Detected advance dialog."); - pbf_press_button(context, BUTTON_B, 20, 30); - continue; - - case 2:{ - env.log("Detected prompt dialog."); - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, true); - pbf_press_button(context, BUTTON_A, 10, 30); - context.wait_for_all_requests(); - next_wait_time = std::chrono::seconds(5); - continue; - } - case 3:{ - env.log("Detected date change."); - uint16_t delay_mills = DELAY_MILLIS; - - // This is the seed we intend to hit. - uint64_t seed_epoch_millis = to_seconds_since_epoch(date) * 1000; - seed_epoch_millis -= delay_mills; - - // This is the time we intend to set the clock to. - uint64_t threshold = delay_mills + 3000; - uint64_t clock_epoch = (seed_epoch_millis - threshold) / 1000; - clock_epoch /= 60; // Round down to minute. - clock_epoch *= 60; - DateTime set_date = from_seconds_since_epoch(clock_epoch); - - std::chrono::milliseconds trigger_delay(seed_epoch_millis - clock_epoch * 1000); - - VideoOverlaySet overlays(env.console.overlay()); - date_reader.make_overlays(overlays); - date_reader.set_date(env.program_info(), env.console, context, set_date); - - // Commit the date and start the timer. - pbf_press_button(context, BUTTON_A, 20, 30); - WallClock trigger_time = std::chrono::system_clock::now() + trigger_delay; - env.log("Will commit in " + tostr_u_commas(trigger_delay.count()) + " milliseconds."); - - // Re-enter the game. - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context, false); - - if (!prompt.detect(env.console.video().snapshot())){ - env.log("Expected to be on prompt menu. Backing out.", COLOR_RED); - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 500); - continue; - } - - // Wait for trigger time. - context.wait_until(trigger_time); - pbf_press_button(context, BUTTON_A, 10, 10); - continue; - } - case 4:{ - env.log("Detected material selection."); - if (printed){ - return prize_result; - } - if (!overworld_seen){ - pbf_press_button(context, BUTTON_B, 20, 30); - continue; - } - item_printer_start_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE, jobs); - stats.prints++; - env.update_stats(); - printed = true; - prize_result = item_printer_finish_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE); - std::array print_results = prize_result.prizes; - uint64_t seed = to_seconds_since_epoch(date); - int distance_from_target = get_distance_from_target(env.console, stats, print_results, seed); - env.update_stats(); - if ((ADJUST_DELAY || MODE == ItemPrinterMode::AUTO_MODE) && - distance_from_target != 0 && - distance_from_target != std::numeric_limits::min() - ){ - adjust_delay(env.logger(), env, print_results, distance_from_target); - } - -// pbf_press_button(context, BUTTON_B, 20, 30); - continue; - } - default: - failures++; - stats.errors++; - env.update_stats(); - env.console.log("No state detected after 2 minutes.", COLOR_RED); -#if 0 - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 2 minutes.", - env.console - ); -#endif - } - } -} - -void ItemPrinterRNG::adjust_delay( - Logger& logger, - SingleSwitchProgramEnvironment& env, - const std::array& print_results, - int distance_from_target -){ - const int MAX_MISS = 2; - const int16_t ADJUSTMENT_TABLE[MAX_MISS + 1] = {0, 50, 1000}; - - int16_t delay_adjustment; - if (distance_from_target < 0){ - distance_from_target = std::min(-distance_from_target, MAX_MISS); - delay_adjustment = -ADJUSTMENT_TABLE[distance_from_target]; - }else if (distance_from_target > 0){ - distance_from_target = std::min(distance_from_target, MAX_MISS); - delay_adjustment = ADJUSTMENT_TABLE[distance_from_target]; - }else{ - return; - } - - int16_t new_delay = DELAY_MILLIS + delay_adjustment; - new_delay = std::max(new_delay, (int16_t)DELAY_MILLIS.min_value()); - new_delay = std::min(new_delay, (int16_t)DELAY_MILLIS.max_value()); - DELAY_MILLIS.set((uint16_t)new_delay); - logger.log("Current delay: " + std::to_string(new_delay)); - // std::cout << "Current delay:" << new_delay << std::endl; - -} - -int ItemPrinterRNG::get_distance_from_target( - Logger& logger, - ItemPrinterRNG_Descriptor::Stats& stats, - const std::array& print_results, - uint64_t seed -){ - int distance_from_target = std::numeric_limits::min(); - const int MAX_DEVIATION = 10; - for (int current_deviation = 0; current_deviation <= MAX_DEVIATION; current_deviation++){ - ItemPrinter::DateSeed seed_data; - if (ENABLE_SEED_CALC || MODE == ItemPrinterMode::AUTO_MODE){ - seed_data = ItemPrinter::calculate_seed_prizes(seed - current_deviation); - }else{ - seed_data = ItemPrinter::get_date_seed(seed - current_deviation); - } - if (results_approximately_match(print_results, seed_data.regular) || - results_approximately_match(print_results, seed_data.item_bonus) || - results_approximately_match(print_results, seed_data.ball_bonus) - ){ - distance_from_target = -current_deviation; - break; - } - - if (current_deviation == 0){ - continue; - } - - if (ENABLE_SEED_CALC || MODE == ItemPrinterMode::AUTO_MODE){ - seed_data = ItemPrinter::calculate_seed_prizes(seed + current_deviation); - }else{ - seed_data = ItemPrinter::get_date_seed(seed + current_deviation); - } - if (results_approximately_match(print_results, seed_data.regular) || - results_approximately_match(print_results, seed_data.item_bonus) || - results_approximately_match(print_results, seed_data.ball_bonus) - ){ - distance_from_target = current_deviation; - break; - } - } - - if (distance_from_target == std::numeric_limits::min()){ - logger.log("Frame Result: Unable to determine frame.", COLOR_RED); - stats.frame_unknown++; - }else if (distance_from_target < 0){ - logger.log("Frame Result: Missed. (Target - " + std::to_string(-distance_from_target) + ")", COLOR_ORANGE); - stats.frame_misses++; - }else if (distance_from_target > 0){ - logger.log("Frame Result: Missed. (Target + " + std::to_string(distance_from_target) + ")", COLOR_ORANGE); - stats.frame_misses++; - }else{ - logger.log("Frame Result: Target hit", COLOR_BLUE); - stats.frame_hits++; - } - - return distance_from_target; -} - - - -bool ItemPrinterRNG::results_approximately_match( - const std::array& print_results, - const std::array& expected_result -){ - size_t total_items = 0; - size_t mismatches = 0; - for (uint8_t i = 0; i < 10; i++){ - const std::string& x = print_results[i]; - const std::string& y = expected_result[i]; - if (x.empty() || y.empty()){ - continue; - } - - total_items++; - - if (x == y){ - continue; - } - - mismatches++; - } - - if (total_items == 0){ - return false; - } - - return mismatches * 5 <= total_items; -} - -void ItemPrinterRNG::print_again( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - ItemPrinterJobs jobs -) const{ - ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); - - bool printed = false; - while (true){ - context.wait_for_all_requests(); - - OverworldWatcher overworld(env.console, COLOR_BLUE); - AdvanceDialogWatcher dialog(COLOR_RED); -// PromptDialogWatcher prompt(COLOR_GREEN); - WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); - int ret = wait_until( - env.console, context, std::chrono::seconds(120), - { - overworld, - dialog, -// prompt, - material, - } - ); - switch (ret){ - case 0: - env.log("Detected overworld... (unexpected)", COLOR_RED); - return; - - case 1: - env.log("Detected advance dialog."); - pbf_press_button(context, BUTTON_B, 20, 30); - continue; - - case 2:{ - env.log("Detected material selection."); - if (printed){ - return; - } - item_printer_start_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE, jobs); - stats.prints++; - env.update_stats(); - printed = true; - item_printer_finish_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE); - continue; - } - default: - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 2 minutes.", - env.console - ); - } - } -} - -void ItemPrinterRNG::run_item_printer_rng_automode( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - ItemPrinterRNG_Descriptor::Stats& stats -){ - const uint16_t min_happiny_dust = 400; - - MaterialFarmerOptions material_farmer_options( - GroupOption::EnableMode::DEFAULT_ENABLED, - &LANGUAGE, - NOTIFICATION_STATUS_UPDATE, - NOTIFICATION_PROGRAM_FINISH, - NOTIFICATION_ERROR_RECOVERABLE, - NOTIFICATION_ERROR_FATAL - ); - - material_farmer_options.RUN_TIME_IN_MINUTES.set(32); - material_farmer_options.SANDWICH_OPTIONS.set_enabled(true); - material_farmer_options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH = true; - material_farmer_options.SANDWICH_OPTIONS.BASE_RECIPE.set(BaseRecipe::non_shiny); - - // For each job that we print, we increment jobs_counter. - // Each time we run the material farmer, we reset jobs_counter to 0. - uint32_t jobs_counter = 0; - - // Check material quantity when: - // - once when first starting the item printer - // - before starting material farming. If still have material, - // can keep using item printer. But this check is only done once, - // until you farm materials again. - // - when back from material farming - bool done_one_last_material_check_before_mat_farming = false; - uint32_t material_farmer_jobs_period = calc_num_jobs_using_happiny_dust(env, context, min_happiny_dust); - bool have_cleared_out_bonus = false; - std::map obtained_prizes; - - std::vector desired_table = DESIRED_ITEM_TABLE.snapshot(); - for (const ItemPrinterDesiredItemRowSnapshot& desired_row : desired_table){ - std::string desired_slug = ItemPrinter::PrebuiltOptions_AutoMode_Database().find(desired_row.item)->slug; - int16_t desired_quantity = desired_row.quantity; - int16_t obtained_quantity = check_obtained_quantity(obtained_prizes, desired_slug); - - while (obtained_quantity < desired_quantity){ - int16_t quantity_to_print = desired_quantity - obtained_quantity; - std::vector print_table = desired_print_table(desired_row.item, quantity_to_print); - if (!have_cleared_out_bonus){ - // 2323229535, 8 Ability Patches, with no bonus active - // x2 Magnet, x9 Exp. Candy S, x7 Pretty Feather, x2 Ability Patch, x2 Ability Patch, - // x7 Big Pearl, x1 Ability Patch, x1 Ability Patch, x16 Ground Tera Shard, x2 Ability Patch - - // start with printing out 10 just to clear out any lingering bonuses. - ItemPrinterRngRowSnapshot print_10_items = {false, from_seconds_since_epoch(2323229535), ItemPrinterJobs::Jobs_10}; - print_table.insert(print_table.begin(), print_10_items); - have_cleared_out_bonus = true; - } - - for (const ItemPrinterRngRowSnapshot& row : print_table){ - env.console.log(desired_slug + ": " + std::to_string(check_obtained_quantity(obtained_prizes, desired_slug)) + "/" + std::to_string(desired_quantity)); - - // check if need to run material farmer - while (jobs_counter >= material_farmer_jobs_period){ - if (!done_one_last_material_check_before_mat_farming){ - // one more material quantity check before material farming - // if still have material, keep using item printer - material_farmer_jobs_period = calc_num_jobs_using_happiny_dust(env, context, min_happiny_dust); - jobs_counter = 0; - done_one_last_material_check_before_mat_farming = true; - continue; - } - - // Run the material farmer. - run_material_farming_then_return_to_item_printer(env, context, stats, material_farmer_options); - - // Recheck number of Happiny Dust after returning from Material Farming, - // prior to restarting Item printing - material_farmer_jobs_period = calc_num_jobs_using_happiny_dust(env, context, min_happiny_dust); - jobs_counter = 0; - done_one_last_material_check_before_mat_farming = false; - } - - ItemPrinterPrizeResult prize_result = run_print_at_date(env, context, row.date, row.jobs); - std::array prizes = prize_result.prizes; - std::array quantities = prize_result.quantities; - for (size_t i = 0; i < 10; i++){ - obtained_prizes[prizes[i]] += quantities[i]; - } - - jobs_counter += (uint32_t)row.jobs; - env.console.log("Print job counter: " + std::to_string(jobs_counter) + "/" + std::to_string(material_farmer_jobs_period)); - env.console.log("Cumulative prize list:"); - for (const auto& prize : obtained_prizes){ - if (prize.first == ""){ - continue; - } - env.console.log(prize.first + ": " + std::to_string(prize.second)); - } - - } - - obtained_quantity = check_obtained_quantity(obtained_prizes, desired_slug); - } - - - // stats.iterations++; - // env.update_stats(); - } - -} - -int16_t ItemPrinterRNG::check_obtained_quantity(std::map obtained_prizes, std::string desired_slug){ - int16_t obtained_quantity = 0; - auto prize_iter = obtained_prizes.find(desired_slug); - if (prize_iter != obtained_prizes.end()){ - obtained_quantity = prize_iter->second; - } - - return obtained_quantity; -} - - -void ItemPrinterRNG::run_material_farming_then_return_to_item_printer( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - ItemPrinterRNG_Descriptor::Stats& stats, - MaterialFarmerOptions& material_farmer_options -){ - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - move_from_item_printer_to_material_farming(env.program_info(), env.console, context); - { - // Dummy stats since we don't use the material farmer stats. - MaterialFarmerStats mat_farm_stats; - run_material_farmer(env, env.console, context, material_farmer_options, mat_farm_stats); - stats.material_farmer_runs++; - env.update_stats(); - } - move_from_material_farming_to_item_printer(env.program_info(), env.console, context); - -} - -std::vector ItemPrinterRNG::desired_print_table( - ItemPrinter::PrebuiltOptions desired_item, - uint16_t quantity_to_print -){ - ItemPrinter::ItemPrinterEnumOption desired_enum_option = option_lookup_by_enum(desired_item); - - // one bonus bundle is Item/Ball Bonus -> 5 print -> 5 print - // quantity_obtained stores the quantity of the desired item that - // is produced with one 5 print, with the bonus active. - uint16_t num_bonus_bundles = (quantity_to_print + (desired_enum_option.quantity_obtained * 2) - 1)/(desired_enum_option.quantity_obtained * 2); // round up after dividing - - ItemPrinter::PrebuiltOptions bonus_type = get_bonus_type(desired_item); - ItemPrinter::ItemPrinterEnumOption bonus_enum_option = option_lookup_by_enum(bonus_type); - ItemPrinterRngRowSnapshot bonus_snapshot = {false, from_seconds_since_epoch(bonus_enum_option.seed), bonus_enum_option.jobs}; - ItemPrinterRngRowSnapshot desired_item_snapshot = {false, from_seconds_since_epoch(desired_enum_option.seed), desired_enum_option.jobs}; - - std::vector print_table; - for (size_t i = 0; i < num_bonus_bundles; i++){ - print_table.push_back(bonus_snapshot); - // - we assume all the desired item prints are 5 prints, - // since all the single item prints stored in the database are 5 prints. - print_table.push_back(desired_item_snapshot); - print_table.push_back(desired_item_snapshot); - } - - // cout << "Total number of bonus bundles: " << num_bonus_bundles << endl; - // for (const ItemPrinterRngRowSnapshot& row : print_table){ - // cout << (int)row.jobs << ": "; - // std::cout << row.date.year << "-" << (int)row.date.month << "-" << (int)row.date.day << " "; - // std::cout << (int)row.date.hour << ":" << (int)row.date.minute << ":" << (int)row.date.second << endl; - // } - - return print_table; -} - - -ItemPrinter::PrebuiltOptions ItemPrinterRNG::get_bonus_type(ItemPrinter::PrebuiltOptions desired_item){ - // EnumDropdownDatabase database = ItemPrinter::PrebuiltOptions_AutoMode_Database(); - // std::string slug = database.find(desired_item)->slug; - std::string slug = ItemPrinter::PrebuiltOptions_AutoMode_Database().find(desired_item)->slug; - // cout << slug << endl; - if (slug.find("ball") != std::string::npos){ - return ItemPrinter::PrebuiltOptions::BALL_BONUS; - }else{ - return ItemPrinter::PrebuiltOptions::ITEM_BONUS; - } -} - - -void ItemPrinterRNG::run_item_printer_rng( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - ItemPrinterRNG_Descriptor::Stats& stats -){ - // For each job that we print, we increment jobs_counter. - // Each time we run the material farmer, we reset jobs_counter to 0. - uint32_t jobs_counter = 0; - - bool done_one_last_material_check_before_mat_farming = false; - uint32_t material_farmer_jobs_period = MATERIAL_FARMER_FIXED_NUM_JOBS; - if (MATERIAL_FARMER_OPTIONS.enabled() && MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST){ - // Check material quantity when: - // - once when first starting the item printer - // - before starting material farming. If still have material, - // can keep using item printer. But this check is only done once, - // until you farm materials again. - // - when back from material farming - - uint32_t num_jobs_with_happiny_dust = calc_num_jobs_using_happiny_dust(env, context, MIN_HAPPINY_DUST); - material_farmer_jobs_period = num_jobs_with_happiny_dust; - } - - for (uint32_t c = 0; c < NUM_ITEM_PRINTER_ROUNDS; c++){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - std::vector table = DATE_SEED_TABLE.snapshot(); - for (const ItemPrinterRngRowSnapshot& row : table){ - // Cannot run material farmer between chained prints. - if (row.chain){ - print_again(env, context, row.jobs); - jobs_counter += (uint32_t)row.jobs; - continue; - } - - run_print_at_date(env, context, row.date, row.jobs); - jobs_counter += (uint32_t)row.jobs; - - if (!MATERIAL_FARMER_OPTIONS.enabled()){ - continue; - } - - //////////////////////////////////////////////////// - // Material farmer is enabled. - // Check number of print jobs before triggering material farmer. - //////////////////////////////////////////////////// - - if (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS){ - material_farmer_jobs_period = MATERIAL_FARMER_FIXED_NUM_JOBS; - } - env.console.log( - "Print job counter: " - + std::to_string(jobs_counter) - + "/" - + std::to_string(material_farmer_jobs_period) - ); - - // Not ready to run material farmer yet. - if (jobs_counter < material_farmer_jobs_period){ - continue; - } - - if (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST - && !done_one_last_material_check_before_mat_farming - ){ - // one more material quantity check before material farming - // if still have material, keep using item printer - uint32_t num_jobs_with_happiny_dust = calc_num_jobs_using_happiny_dust(env, context, MIN_HAPPINY_DUST); - material_farmer_jobs_period = num_jobs_with_happiny_dust; - jobs_counter = 0; - done_one_last_material_check_before_mat_farming = true; - if (material_farmer_jobs_period > 0){ - continue; - } - } - - // Run the material farmer. - press_Bs_to_back_to_overworld(env.program_info(), env.console, context); - move_from_item_printer_to_material_farming(env.program_info(), env.console, context); - { - // Dummy stats since we don't use the material farmer stats. - MaterialFarmerStats mat_farm_stats; - run_material_farmer(env, env.console, context, MATERIAL_FARMER_OPTIONS, mat_farm_stats); - stats.material_farmer_runs++; - env.update_stats(); - } - move_from_material_farming_to_item_printer(env.program_info(), env.console, context); - - // Recheck number of Happiny Dust after returning from Material Farming, - // prior to restarting Item printing - if (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST){ - uint32_t num_jobs_with_happiny_dust = calc_num_jobs_using_happiny_dust(env, context, MIN_HAPPINY_DUST); - material_farmer_jobs_period = num_jobs_with_happiny_dust; - done_one_last_material_check_before_mat_farming = false; - } - - jobs_counter = 0; - } -// run_print_at_date(env, context, DATE0, 1); -// run_print_at_date(env, context, DATE1, 10); - stats.iterations++; - env.update_stats(); - } -} - -// return number of print jobs we can do, based on how much Happiny Dust we have, -// and how low we allow the Happiny dust to go (min_happiny_dust) -uint32_t ItemPrinterRNG::calc_num_jobs_using_happiny_dust( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - uint16_t min_happiny_dust -){ - uint32_t num_happiny_dust = check_num_happiny_dust(env, context); - - // give a buffer of 50, for a margin of safety. signed int to handle negative numbers - int32_t num_happiny_dust_can_use = num_happiny_dust - MIN_HAPPINY_DUST - 50; - num_happiny_dust_can_use = num_happiny_dust_can_use < 0 ? 0 : num_happiny_dust_can_use; - - // assume 62% value for Happiny Dust to account for item printer wasteage. - uint32_t num_print_jobs = (uint32_t)(num_happiny_dust_can_use * 0.62); // truncate the float back to int - env.console.log("Number of Happiny Dust we have: " + std::to_string(num_happiny_dust)); - env.console.log("Number of Happiny Dust we can use (with some safety margins): " + std::to_string(num_happiny_dust_can_use)); - env.console.log("Number of print jobs we can do before material farming: " + std::to_string(num_print_jobs)); - return num_print_jobs; -} - -uint32_t ItemPrinterRNG::check_num_happiny_dust( - SingleSwitchProgramEnvironment& env, ProControllerContext& context -){ - ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); - env.log("Check how much Happiny Dust we have."); - uint32_t num_happiny_dust; - while (true){ - context.wait_for_all_requests(); - - OverworldWatcher overworld(env.console, COLOR_BLUE); - AdvanceDialogWatcher dialog(COLOR_RED); - PromptDialogWatcher prompt(COLOR_GREEN); - DateChangeWatcher date_reader(env.console); - ItemPrinterMenuWatcher material(COLOR_GREEN); - int ret = wait_until( - env.console, context, std::chrono::seconds(120), - { - overworld, - dialog, - prompt, - material, - } - ); - switch (ret){ - case 0: - env.log("Detected overworld... Entering item printer."); - pbf_press_button(context, BUTTON_A, 20, 30); - continue; - - case 1: - env.log("Detected advance dialog."); - pbf_press_button(context, BUTTON_B, 20, 30); - continue; - - case 2:{ - env.log("Detected prompt dialog. Entering item printer."); - pbf_press_button(context, BUTTON_A, 10, 30); - context.wait_for_all_requests(); - continue; - } - case 3:{ - env.log("Detected material selection."); - ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); - - int8_t happiny_dust_row_num = detector.find_happiny_dust_row_index( - env.normal_inference_dispatcher(), - env.console, context - ); - num_happiny_dust = detector.detect_material_quantity( - env.normal_inference_dispatcher(), - env.console, context, - happiny_dust_row_num - ); - pbf_mash_button(context, BUTTON_B, 100); - return num_happiny_dust; - } - default: - stats.errors++; - env.update_stats(); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 2 minutes.", - env.console - ); - } - } - - return 0; -} - -void ItemPrinterRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - - if (MODE == ItemPrinterMode::AUTO_MODE || MATERIAL_FARMER_OPTIONS.enabled()){ - // - Ensure audio input is enabled - LetsGoKillSoundDetector audio_detector(env.console, [](float){ return true; }); - wait_until( - env.console, context, - std::chrono::milliseconds(1100), - {audio_detector} - ); - audio_detector.throw_if_no_sound(std::chrono::milliseconds(1000)); - } - - try{ - if (MODE == ItemPrinterMode::AUTO_MODE){ - run_item_printer_rng_automode(env, context, stats); - }else{ - run_item_printer_rng(env, context, stats); - } - - }catch (ProgramFinishedException&){} - - if (FIX_TIME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Item Printer RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Qt/TimeQt.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMenuDetector.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterMaterialDetector.h" +#include "PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_ItemPrinterSeedCalc.h" +#include "PokemonSV_ItemPrinterDatabase.h" +#include "PokemonSV_ItemPrinterRNG.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +ItemPrinterRNG_Descriptor::ItemPrinterRNG_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:ItemPrinterRNG", + Pokemon::STRING_POKEMON + " SV", "Item Printer RNG", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ItemPrinterRNG.md", + "Farm the Item Printer using RNG Manipulation.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} + +struct ItemPrinterRNG_Descriptor::Stats : public StatsTracker{ + Stats() + : iterations(m_stats["Rounds"]) + , prints(m_stats["Prints"]) +// , total_jobs(m_stats["Total Jobs"]) + , frame_hits(m_stats["Frame Hits"]) + , frame_misses(m_stats["Frame Misses"]) + , frame_unknown(m_stats["Unknown Frame"]) + , material_farmer_runs(m_stats["Material Farmer Runs"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Rounds"); + m_display_order.emplace_back("Prints"); +// m_display_order.emplace_back("Total Jobs", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Frame Hits"); + m_display_order.emplace_back("Frame Misses"); + m_display_order.emplace_back("Unknown Frame", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Material Farmer Runs", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& iterations; + std::atomic& prints; +// std::atomic& total_jobs; + std::atomic& frame_hits; + std::atomic& frame_misses; + std::atomic& frame_unknown; + std::atomic& material_farmer_runs; + std::atomic& errors; +}; +std::unique_ptr ItemPrinterRNG_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +ItemPrinterRNG::~ItemPrinterRNG(){ + MATERIAL_FARMER_OPTIONS.remove_listener(*this); + MATERIAL_FARMER_TRIGGER.remove_listener(*this); + DATE_SEED_TABLE.remove_listener(*this); +// AUTO_MATERIAL_FARMING.remove_listener(*this); +} + +ItemPrinterRNG::ItemPrinterRNG() + : LANGUAGE( + "Game Language:", + PokemonSwSh::IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NUM_ITEM_PRINTER_ROUNDS( + "Number of rounds per Item Printer session:
Iterate the rounds table this many times. ", + LockMode::UNLOCK_WHILE_RUNNING, 10 + ) +// , AFTER_ITEM_PRINTER_DONE_EXPLANATION( +// "Then proceed to material farming." +// ) + , OVERLAPPING_BONUS_WARNING( + "WARNING: At least one of the Ball/Item bonuses haven't been fully used up. " + "This can mess up your rewards for subsequent prints.
" + "\nNote: Each Ball/Item bonus lasts for 10 prints." + ) + , MODE( + "Item Printer mode:
", + { + {ItemPrinterMode::STANDARD_MODE, "standard", "Standard Mode: Manually select exactly what is being printed for each print job."}, + {ItemPrinterMode::AUTO_MODE, "auto", "Auto Mode: Select your desired item and its quantity, and items will be automatically printed."}, + }, + LockMode::LOCK_WHILE_RUNNING, + ItemPrinterMode::STANDARD_MODE + ) + , DESIRED_ITEM_TABLE( + "Item Table:
" + "Input your desired item and desired quantity to the table.
" + "Ensure you have enough BP and are maxed out on the following sandwich ingredients: Chorizo, Bananas, Mayonnaise, Whipped Cream. " + "Also, ensure you have a strong lead pokemon for auto-battling, for farming materials.
" + "If there are duplicate items in the table, only the higher quantity will be considered." + ) + , DATE_SEED_TABLE( + "Rounds Table:
Run the following prints in order and repeat. " + "Changes to this table take effect the next time the table starts from the beginning." + ) + , DELAY_MILLIS( + "Delay (Milliseconds):
" + "The delay from when you press A to when the game reads the date for the seed. " + "For OLED Switches, this delay is about 500 milliseconds. For older Switches, this delay is closer to 1500 milliseconds. " + "If the following option is enabled, this delay will be automatically adjusted based on how you miss the frames.", + LockMode::UNLOCK_WHILE_RUNNING, 1000, + 0, 5000 + ) + , ADJUST_DELAY( + "Automatically Adjust Delay:
Adjust the delay, depending on the desired item and the actual print result.", + LockMode::UNLOCK_WHILE_RUNNING, true + ) + , GO_HOME_WHEN_DONE(false) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.", + LockMode::UNLOCK_WHILE_RUNNING, true + ) + , MATERIAL_FARMER_TRIGGER( + "Trigger to start material farmer:
", + { + {MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS, "fixed", "Start Material Farmer when done a certain number of print jobs."}, + {MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST, "happiny-dust", "Start Material Farmer when Happiny Dust is less than a certain number."}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS + ) + , MATERIAL_FARMER_FIXED_NUM_JOBS( + "Print Jobs per Material Farming Session:
" + "Run the material farmer once for this many jobs printed.", + LockMode::UNLOCK_WHILE_RUNNING, 500, + 20, 650 + ) + , MIN_HAPPINY_DUST( + "Minimum Happiny Dust:
" + "Run the material farmer before the number of Happiny Dust drops " + "below this number.
" + "This ensures no other material drops below this number. " + "If a material starts below this threshold, it remains there.
" + "Changes to this number only take place after returning to " + "the item printer, after material farming.", + LockMode::UNLOCK_WHILE_RUNNING, 400, + 1, 999 + ) + , MATERIAL_FARMER_OPTIONS( + GroupOption::EnableMode::DEFAULT_DISABLED, + &LANGUAGE, + NOTIFICATION_STATUS_UPDATE, + NOTIFICATION_PROGRAM_FINISH, + NOTIFICATION_ERROR_RECOVERABLE, + NOTIFICATION_ERROR_FATAL + ) + , ENABLE_SEED_CALC( + "Enable Seed Calculation: (developer only)
" + "Use Kurt's seed calculation instead of hardcoded database. Ensure you have the appropriate resources.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(DESIRED_ITEM_TABLE); + PA_ADD_OPTION(NUM_ITEM_PRINTER_ROUNDS); + PA_ADD_OPTION(DATE_SEED_TABLE); + PA_ADD_OPTION(OVERLAPPING_BONUS_WARNING); + PA_ADD_OPTION(DELAY_MILLIS); + PA_ADD_OPTION(ADJUST_DELAY); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + + PA_ADD_OPTION(MATERIAL_FARMER_TRIGGER); + PA_ADD_OPTION(MATERIAL_FARMER_FIXED_NUM_JOBS); + PA_ADD_OPTION(MIN_HAPPINY_DUST); + PA_ADD_OPTION(MATERIAL_FARMER_OPTIONS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(ENABLE_SEED_CALC); + } + + PA_ADD_OPTION(NOTIFICATIONS); + + ItemPrinterRNG::on_config_value_changed(this); +// AUTO_MATERIAL_FARMING.add_listener(*this); + DATE_SEED_TABLE.add_listener(*this); + MODE.add_listener(*this); + MATERIAL_FARMER_OPTIONS.add_listener(*this); + MATERIAL_FARMER_TRIGGER.add_listener(*this); +} + +void ItemPrinterRNG::on_config_value_changed(void* object){ + + NUM_ITEM_PRINTER_ROUNDS.set_visibility( + MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED + ); + + OVERLAPPING_BONUS_WARNING.set_visibility( + (MODE != ItemPrinterMode::AUTO_MODE) && overlapping_bonus() + ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); + + DESIRED_ITEM_TABLE.set_visibility( + MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); + + DATE_SEED_TABLE.set_visibility( + MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED + ); + + ADJUST_DELAY.set_visibility( + MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED + ); + + MATERIAL_FARMER_TRIGGER.set_visibility( + (MODE != ItemPrinterMode::AUTO_MODE) && MATERIAL_FARMER_OPTIONS.enabled() + ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); + + MATERIAL_FARMER_FIXED_NUM_JOBS.set_visibility( + (MODE != ItemPrinterMode::AUTO_MODE) && MATERIAL_FARMER_OPTIONS.enabled() && (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS) + ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); + + MIN_HAPPINY_DUST.set_visibility( + (MODE != ItemPrinterMode::AUTO_MODE) && MATERIAL_FARMER_OPTIONS.enabled() && (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST) + ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); + + MATERIAL_FARMER_OPTIONS.set_visibility( + MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED + ); + + ENABLE_SEED_CALC.set_visibility( + MODE == ItemPrinterMode::AUTO_MODE ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED + ); + +} + + +// - return true if the user is trying to trigger another Ball/Item bonus without +// using up the previous bonus. Doing this can mess up rewards for subsequent prints, +// since a ball bonus interferes with activating an item bonus and vice versa. +// - each Bonus lasts for 10 prints. +bool ItemPrinterRNG::overlapping_bonus(){ + // for each row in table. if ball/item bonus, ensure that sum of prints in subsequent rows >=10 before the next bonus, or end of the table. + uint16_t total_prints_since_last_bonus = 10; + for (std::shared_ptr& table_row : DATE_SEED_TABLE.current_refs()){ + ItemPrinterRngRow& row = static_cast(*table_row); + if (row.desired_item == ItemPrinter::PrebuiltOptions::BALL_BONUS || row.desired_item == ItemPrinter::PrebuiltOptions::ITEM_BONUS){ + if (total_prints_since_last_bonus < 10){ + return true; + } + total_prints_since_last_bonus = 0; + }else{ + total_prints_since_last_bonus += (uint16_t)static_cast(row.jobs); + } + } + + if (total_prints_since_last_bonus < 10){ + return true; + } + + return false; +} + + +ItemPrinterPrizeResult ItemPrinterRNG::run_print_at_date( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const DateTime& date, ItemPrinterJobs jobs +){ + ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); + ItemPrinterPrizeResult prize_result; + bool printed = false; + bool overworld_seen = false; + size_t failures = 0; + std::chrono::seconds next_wait_time = std::chrono::seconds(120); + while (true){ + if (failures >= 5){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to print after 5 attempts.", + env.console + ); + } + context.wait_for_all_requests(); + + OverworldWatcher overworld(env.console, COLOR_BLUE); + AdvanceDialogWatcher dialog(COLOR_RED); + PromptDialogWatcher prompt(COLOR_GREEN); + DateChangeWatcher date_reader(env.console); + WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); + int ret = wait_until( + env.console, context, next_wait_time, + { + overworld, + dialog, + prompt, + date_reader, + material, + } + ); + next_wait_time = std::chrono::seconds(120); + switch (ret){ + case 0: + overworld_seen = true; + if (printed){ + env.log("Detected overworld... (unexpected)", COLOR_RED); + return prize_result; + } + env.log("Detected overworld... Starting print."); + pbf_press_button(context, BUTTON_A, 20, 30); + continue; + + case 1: + env.log("Detected advance dialog."); + pbf_press_button(context, BUTTON_B, 20, 30); + continue; + + case 2:{ + env.log("Detected prompt dialog."); + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, true); + pbf_press_button(context, BUTTON_A, 10, 30); + context.wait_for_all_requests(); + next_wait_time = std::chrono::seconds(5); + continue; + } + case 3:{ + env.log("Detected date change."); + uint16_t delay_mills = DELAY_MILLIS; + + // This is the seed we intend to hit. + uint64_t seed_epoch_millis = to_seconds_since_epoch(date) * 1000; + seed_epoch_millis -= delay_mills; + + // This is the time we intend to set the clock to. + uint64_t threshold = delay_mills + 3000; + uint64_t clock_epoch = (seed_epoch_millis - threshold) / 1000; + clock_epoch /= 60; // Round down to minute. + clock_epoch *= 60; + DateTime set_date = from_seconds_since_epoch(clock_epoch); + + std::chrono::milliseconds trigger_delay(seed_epoch_millis - clock_epoch * 1000); + + VideoOverlaySet overlays(env.console.overlay()); + date_reader.make_overlays(overlays); + date_reader.set_date(env.program_info(), env.console, context, set_date); + + // Commit the date and start the timer. + pbf_press_button(context, BUTTON_A, 20, 30); + WallClock trigger_time = std::chrono::system_clock::now() + trigger_delay; + env.log("Will commit in " + tostr_u_commas(trigger_delay.count()) + " milliseconds."); + + // Re-enter the game. + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context, false); + + if (!prompt.detect(env.console.video().snapshot())){ + env.log("Expected to be on prompt menu. Backing out.", COLOR_RED); + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 500); + continue; + } + + // Wait for trigger time. + context.wait_until(trigger_time); + pbf_press_button(context, BUTTON_A, 10, 10); + continue; + } + case 4:{ + env.log("Detected material selection."); + if (printed){ + return prize_result; + } + if (!overworld_seen){ + pbf_press_button(context, BUTTON_B, 20, 30); + continue; + } + item_printer_start_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE, jobs); + stats.prints++; + env.update_stats(); + printed = true; + prize_result = item_printer_finish_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE); + std::array print_results = prize_result.prizes; + uint64_t seed = to_seconds_since_epoch(date); + int distance_from_target = get_distance_from_target(env.console, stats, print_results, seed); + env.update_stats(); + if ((ADJUST_DELAY || MODE == ItemPrinterMode::AUTO_MODE) && + distance_from_target != 0 && + distance_from_target != std::numeric_limits::min() + ){ + adjust_delay(env.logger(), env, print_results, distance_from_target); + } + +// pbf_press_button(context, BUTTON_B, 20, 30); + continue; + } + default: + failures++; + stats.errors++; + env.update_stats(); + env.console.log("No state detected after 2 minutes.", COLOR_RED); +#if 0 + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 2 minutes.", + env.console + ); +#endif + } + } +} + +void ItemPrinterRNG::adjust_delay( + Logger& logger, + SingleSwitchProgramEnvironment& env, + const std::array& print_results, + int distance_from_target +){ + const int MAX_MISS = 2; + const int16_t ADJUSTMENT_TABLE[MAX_MISS + 1] = {0, 50, 1000}; + + int16_t delay_adjustment; + if (distance_from_target < 0){ + distance_from_target = std::min(-distance_from_target, MAX_MISS); + delay_adjustment = -ADJUSTMENT_TABLE[distance_from_target]; + }else if (distance_from_target > 0){ + distance_from_target = std::min(distance_from_target, MAX_MISS); + delay_adjustment = ADJUSTMENT_TABLE[distance_from_target]; + }else{ + return; + } + + int16_t new_delay = DELAY_MILLIS + delay_adjustment; + new_delay = std::max(new_delay, (int16_t)DELAY_MILLIS.min_value()); + new_delay = std::min(new_delay, (int16_t)DELAY_MILLIS.max_value()); + DELAY_MILLIS.set((uint16_t)new_delay); + logger.log("Current delay: " + std::to_string(new_delay)); + // std::cout << "Current delay:" << new_delay << std::endl; + +} + +int ItemPrinterRNG::get_distance_from_target( + Logger& logger, + ItemPrinterRNG_Descriptor::Stats& stats, + const std::array& print_results, + uint64_t seed +){ + int distance_from_target = std::numeric_limits::min(); + const int MAX_DEVIATION = 10; + for (int current_deviation = 0; current_deviation <= MAX_DEVIATION; current_deviation++){ + ItemPrinter::DateSeed seed_data; + if (ENABLE_SEED_CALC || MODE == ItemPrinterMode::AUTO_MODE){ + seed_data = ItemPrinter::calculate_seed_prizes(seed - current_deviation); + }else{ + seed_data = ItemPrinter::get_date_seed(seed - current_deviation); + } + if (results_approximately_match(print_results, seed_data.regular) || + results_approximately_match(print_results, seed_data.item_bonus) || + results_approximately_match(print_results, seed_data.ball_bonus) + ){ + distance_from_target = -current_deviation; + break; + } + + if (current_deviation == 0){ + continue; + } + + if (ENABLE_SEED_CALC || MODE == ItemPrinterMode::AUTO_MODE){ + seed_data = ItemPrinter::calculate_seed_prizes(seed + current_deviation); + }else{ + seed_data = ItemPrinter::get_date_seed(seed + current_deviation); + } + if (results_approximately_match(print_results, seed_data.regular) || + results_approximately_match(print_results, seed_data.item_bonus) || + results_approximately_match(print_results, seed_data.ball_bonus) + ){ + distance_from_target = current_deviation; + break; + } + } + + if (distance_from_target == std::numeric_limits::min()){ + logger.log("Frame Result: Unable to determine frame.", COLOR_RED); + stats.frame_unknown++; + }else if (distance_from_target < 0){ + logger.log("Frame Result: Missed. (Target - " + std::to_string(-distance_from_target) + ")", COLOR_ORANGE); + stats.frame_misses++; + }else if (distance_from_target > 0){ + logger.log("Frame Result: Missed. (Target + " + std::to_string(distance_from_target) + ")", COLOR_ORANGE); + stats.frame_misses++; + }else{ + logger.log("Frame Result: Target hit", COLOR_BLUE); + stats.frame_hits++; + } + + return distance_from_target; +} + + + +bool ItemPrinterRNG::results_approximately_match( + const std::array& print_results, + const std::array& expected_result +){ + size_t total_items = 0; + size_t mismatches = 0; + for (uint8_t i = 0; i < 10; i++){ + const std::string& x = print_results[i]; + const std::string& y = expected_result[i]; + if (x.empty() || y.empty()){ + continue; + } + + total_items++; + + if (x == y){ + continue; + } + + mismatches++; + } + + if (total_items == 0){ + return false; + } + + return mismatches * 5 <= total_items; +} + +void ItemPrinterRNG::print_again( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + ItemPrinterJobs jobs +) const{ + ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); + + bool printed = false; + while (true){ + context.wait_for_all_requests(); + + OverworldWatcher overworld(env.console, COLOR_BLUE); + AdvanceDialogWatcher dialog(COLOR_RED); +// PromptDialogWatcher prompt(COLOR_GREEN); + WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); + int ret = wait_until( + env.console, context, std::chrono::seconds(120), + { + overworld, + dialog, +// prompt, + material, + } + ); + switch (ret){ + case 0: + env.log("Detected overworld... (unexpected)", COLOR_RED); + return; + + case 1: + env.log("Detected advance dialog."); + pbf_press_button(context, BUTTON_B, 20, 30); + continue; + + case 2:{ + env.log("Detected material selection."); + if (printed){ + return; + } + item_printer_start_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE, jobs); + stats.prints++; + env.update_stats(); + printed = true; + item_printer_finish_print(env.normal_inference_dispatcher(), env.console, context, LANGUAGE); + continue; + } + default: + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 2 minutes.", + env.console + ); + } + } +} + +void ItemPrinterRNG::run_item_printer_rng_automode( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + ItemPrinterRNG_Descriptor::Stats& stats +){ + const uint16_t min_happiny_dust = 400; + + MaterialFarmerOptions material_farmer_options( + GroupOption::EnableMode::DEFAULT_ENABLED, + &LANGUAGE, + NOTIFICATION_STATUS_UPDATE, + NOTIFICATION_PROGRAM_FINISH, + NOTIFICATION_ERROR_RECOVERABLE, + NOTIFICATION_ERROR_FATAL + ); + + material_farmer_options.RUN_TIME_IN_MINUTES.set(32); + material_farmer_options.SANDWICH_OPTIONS.set_enabled(true); + material_farmer_options.SANDWICH_OPTIONS.SAVE_GAME_BEFORE_SANDWICH = true; + material_farmer_options.SANDWICH_OPTIONS.BASE_RECIPE.set(BaseRecipe::non_shiny); + + // For each job that we print, we increment jobs_counter. + // Each time we run the material farmer, we reset jobs_counter to 0. + uint32_t jobs_counter = 0; + + // Check material quantity when: + // - once when first starting the item printer + // - before starting material farming. If still have material, + // can keep using item printer. But this check is only done once, + // until you farm materials again. + // - when back from material farming + bool done_one_last_material_check_before_mat_farming = false; + uint32_t material_farmer_jobs_period = calc_num_jobs_using_happiny_dust(env, context, min_happiny_dust); + bool have_cleared_out_bonus = false; + std::map obtained_prizes; + + std::vector desired_table = DESIRED_ITEM_TABLE.snapshot(); + for (const ItemPrinterDesiredItemRowSnapshot& desired_row : desired_table){ + std::string desired_slug = ItemPrinter::PrebuiltOptions_AutoMode_Database().find(desired_row.item)->slug; + int16_t desired_quantity = desired_row.quantity; + int16_t obtained_quantity = check_obtained_quantity(obtained_prizes, desired_slug); + + while (obtained_quantity < desired_quantity){ + int16_t quantity_to_print = desired_quantity - obtained_quantity; + std::vector print_table = desired_print_table(desired_row.item, quantity_to_print); + if (!have_cleared_out_bonus){ + // 2323229535, 8 Ability Patches, with no bonus active + // x2 Magnet, x9 Exp. Candy S, x7 Pretty Feather, x2 Ability Patch, x2 Ability Patch, + // x7 Big Pearl, x1 Ability Patch, x1 Ability Patch, x16 Ground Tera Shard, x2 Ability Patch + + // start with printing out 10 just to clear out any lingering bonuses. + ItemPrinterRngRowSnapshot print_10_items = {false, from_seconds_since_epoch(2323229535), ItemPrinterJobs::Jobs_10}; + print_table.insert(print_table.begin(), print_10_items); + have_cleared_out_bonus = true; + } + + for (const ItemPrinterRngRowSnapshot& row : print_table){ + env.console.log(desired_slug + ": " + std::to_string(check_obtained_quantity(obtained_prizes, desired_slug)) + "/" + std::to_string(desired_quantity)); + + // check if need to run material farmer + while (jobs_counter >= material_farmer_jobs_period){ + if (!done_one_last_material_check_before_mat_farming){ + // one more material quantity check before material farming + // if still have material, keep using item printer + material_farmer_jobs_period = calc_num_jobs_using_happiny_dust(env, context, min_happiny_dust); + jobs_counter = 0; + done_one_last_material_check_before_mat_farming = true; + continue; + } + + // Run the material farmer. + run_material_farming_then_return_to_item_printer(env, context, stats, material_farmer_options); + + // Recheck number of Happiny Dust after returning from Material Farming, + // prior to restarting Item printing + material_farmer_jobs_period = calc_num_jobs_using_happiny_dust(env, context, min_happiny_dust); + jobs_counter = 0; + done_one_last_material_check_before_mat_farming = false; + } + + ItemPrinterPrizeResult prize_result = run_print_at_date(env, context, row.date, row.jobs); + std::array prizes = prize_result.prizes; + std::array quantities = prize_result.quantities; + for (size_t i = 0; i < 10; i++){ + obtained_prizes[prizes[i]] += quantities[i]; + } + + jobs_counter += (uint32_t)row.jobs; + env.console.log("Print job counter: " + std::to_string(jobs_counter) + "/" + std::to_string(material_farmer_jobs_period)); + env.console.log("Cumulative prize list:"); + for (const auto& prize : obtained_prizes){ + if (prize.first == ""){ + continue; + } + env.console.log(prize.first + ": " + std::to_string(prize.second)); + } + + } + + obtained_quantity = check_obtained_quantity(obtained_prizes, desired_slug); + } + + + // stats.iterations++; + // env.update_stats(); + } + +} + +int16_t ItemPrinterRNG::check_obtained_quantity(std::map obtained_prizes, std::string desired_slug){ + int16_t obtained_quantity = 0; + auto prize_iter = obtained_prizes.find(desired_slug); + if (prize_iter != obtained_prizes.end()){ + obtained_quantity = prize_iter->second; + } + + return obtained_quantity; +} + + +void ItemPrinterRNG::run_material_farming_then_return_to_item_printer( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + ItemPrinterRNG_Descriptor::Stats& stats, + MaterialFarmerOptions& material_farmer_options +){ + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + move_from_item_printer_to_material_farming(env.program_info(), env.console, context); + { + // Dummy stats since we don't use the material farmer stats. + MaterialFarmerStats mat_farm_stats; + run_material_farmer(env, env.console, context, material_farmer_options, mat_farm_stats); + stats.material_farmer_runs++; + env.update_stats(); + } + move_from_material_farming_to_item_printer(env.program_info(), env.console, context); + +} + +std::vector ItemPrinterRNG::desired_print_table( + ItemPrinter::PrebuiltOptions desired_item, + uint16_t quantity_to_print +){ + ItemPrinter::ItemPrinterEnumOption desired_enum_option = option_lookup_by_enum(desired_item); + + // one bonus bundle is Item/Ball Bonus -> 5 print -> 5 print + // quantity_obtained stores the quantity of the desired item that + // is produced with one 5 print, with the bonus active. + uint16_t num_bonus_bundles = (quantity_to_print + (desired_enum_option.quantity_obtained * 2) - 1)/(desired_enum_option.quantity_obtained * 2); // round up after dividing + + ItemPrinter::PrebuiltOptions bonus_type = get_bonus_type(desired_item); + ItemPrinter::ItemPrinterEnumOption bonus_enum_option = option_lookup_by_enum(bonus_type); + ItemPrinterRngRowSnapshot bonus_snapshot = {false, from_seconds_since_epoch(bonus_enum_option.seed), bonus_enum_option.jobs}; + ItemPrinterRngRowSnapshot desired_item_snapshot = {false, from_seconds_since_epoch(desired_enum_option.seed), desired_enum_option.jobs}; + + std::vector print_table; + for (size_t i = 0; i < num_bonus_bundles; i++){ + print_table.push_back(bonus_snapshot); + // - we assume all the desired item prints are 5 prints, + // since all the single item prints stored in the database are 5 prints. + print_table.push_back(desired_item_snapshot); + print_table.push_back(desired_item_snapshot); + } + + // cout << "Total number of bonus bundles: " << num_bonus_bundles << endl; + // for (const ItemPrinterRngRowSnapshot& row : print_table){ + // cout << (int)row.jobs << ": "; + // std::cout << row.date.year << "-" << (int)row.date.month << "-" << (int)row.date.day << " "; + // std::cout << (int)row.date.hour << ":" << (int)row.date.minute << ":" << (int)row.date.second << endl; + // } + + return print_table; +} + + +ItemPrinter::PrebuiltOptions ItemPrinterRNG::get_bonus_type(ItemPrinter::PrebuiltOptions desired_item){ + // EnumDropdownDatabase database = ItemPrinter::PrebuiltOptions_AutoMode_Database(); + // std::string slug = database.find(desired_item)->slug; + std::string slug = ItemPrinter::PrebuiltOptions_AutoMode_Database().find(desired_item)->slug; + // cout << slug << endl; + if (slug.find("ball") != std::string::npos){ + return ItemPrinter::PrebuiltOptions::BALL_BONUS; + }else{ + return ItemPrinter::PrebuiltOptions::ITEM_BONUS; + } +} + + +void ItemPrinterRNG::run_item_printer_rng( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + ItemPrinterRNG_Descriptor::Stats& stats +){ + // For each job that we print, we increment jobs_counter. + // Each time we run the material farmer, we reset jobs_counter to 0. + uint32_t jobs_counter = 0; + + bool done_one_last_material_check_before_mat_farming = false; + uint32_t material_farmer_jobs_period = MATERIAL_FARMER_FIXED_NUM_JOBS; + if (MATERIAL_FARMER_OPTIONS.enabled() && MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST){ + // Check material quantity when: + // - once when first starting the item printer + // - before starting material farming. If still have material, + // can keep using item printer. But this check is only done once, + // until you farm materials again. + // - when back from material farming + + uint32_t num_jobs_with_happiny_dust = calc_num_jobs_using_happiny_dust(env, context, MIN_HAPPINY_DUST); + material_farmer_jobs_period = num_jobs_with_happiny_dust; + } + + for (uint32_t c = 0; c < NUM_ITEM_PRINTER_ROUNDS; c++){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + std::vector table = DATE_SEED_TABLE.snapshot(); + for (const ItemPrinterRngRowSnapshot& row : table){ + // Cannot run material farmer between chained prints. + if (row.chain){ + print_again(env, context, row.jobs); + jobs_counter += (uint32_t)row.jobs; + continue; + } + + run_print_at_date(env, context, row.date, row.jobs); + jobs_counter += (uint32_t)row.jobs; + + if (!MATERIAL_FARMER_OPTIONS.enabled()){ + continue; + } + + //////////////////////////////////////////////////// + // Material farmer is enabled. + // Check number of print jobs before triggering material farmer. + //////////////////////////////////////////////////// + + if (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::FIXED_NUM_PRINT_JOBS){ + material_farmer_jobs_period = MATERIAL_FARMER_FIXED_NUM_JOBS; + } + env.console.log( + "Print job counter: " + + std::to_string(jobs_counter) + + "/" + + std::to_string(material_farmer_jobs_period) + ); + + // Not ready to run material farmer yet. + if (jobs_counter < material_farmer_jobs_period){ + continue; + } + + if (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST + && !done_one_last_material_check_before_mat_farming + ){ + // one more material quantity check before material farming + // if still have material, keep using item printer + uint32_t num_jobs_with_happiny_dust = calc_num_jobs_using_happiny_dust(env, context, MIN_HAPPINY_DUST); + material_farmer_jobs_period = num_jobs_with_happiny_dust; + jobs_counter = 0; + done_one_last_material_check_before_mat_farming = true; + if (material_farmer_jobs_period > 0){ + continue; + } + } + + // Run the material farmer. + press_Bs_to_back_to_overworld(env.program_info(), env.console, context); + move_from_item_printer_to_material_farming(env.program_info(), env.console, context); + { + // Dummy stats since we don't use the material farmer stats. + MaterialFarmerStats mat_farm_stats; + run_material_farmer(env, env.console, context, MATERIAL_FARMER_OPTIONS, mat_farm_stats); + stats.material_farmer_runs++; + env.update_stats(); + } + move_from_material_farming_to_item_printer(env.program_info(), env.console, context); + + // Recheck number of Happiny Dust after returning from Material Farming, + // prior to restarting Item printing + if (MATERIAL_FARMER_TRIGGER == MaterialFarmerTrigger::MINIMUM_HAPPINY_DUST){ + uint32_t num_jobs_with_happiny_dust = calc_num_jobs_using_happiny_dust(env, context, MIN_HAPPINY_DUST); + material_farmer_jobs_period = num_jobs_with_happiny_dust; + done_one_last_material_check_before_mat_farming = false; + } + + jobs_counter = 0; + } +// run_print_at_date(env, context, DATE0, 1); +// run_print_at_date(env, context, DATE1, 10); + stats.iterations++; + env.update_stats(); + } +} + +// return number of print jobs we can do, based on how much Happiny Dust we have, +// and how low we allow the Happiny dust to go (min_happiny_dust) +uint32_t ItemPrinterRNG::calc_num_jobs_using_happiny_dust( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + uint16_t min_happiny_dust +){ + uint32_t num_happiny_dust = check_num_happiny_dust(env, context); + + // give a buffer of 50, for a margin of safety. signed int to handle negative numbers + int32_t num_happiny_dust_can_use = num_happiny_dust - MIN_HAPPINY_DUST - 50; + num_happiny_dust_can_use = num_happiny_dust_can_use < 0 ? 0 : num_happiny_dust_can_use; + + // assume 62% value for Happiny Dust to account for item printer wasteage. + uint32_t num_print_jobs = (uint32_t)(num_happiny_dust_can_use * 0.62); // truncate the float back to int + env.console.log("Number of Happiny Dust we have: " + std::to_string(num_happiny_dust)); + env.console.log("Number of Happiny Dust we can use (with some safety margins): " + std::to_string(num_happiny_dust_can_use)); + env.console.log("Number of print jobs we can do before material farming: " + std::to_string(num_print_jobs)); + return num_print_jobs; +} + +uint32_t ItemPrinterRNG::check_num_happiny_dust( + SingleSwitchProgramEnvironment& env, ProControllerContext& context +){ + ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); + env.log("Check how much Happiny Dust we have."); + uint32_t num_happiny_dust; + while (true){ + context.wait_for_all_requests(); + + OverworldWatcher overworld(env.console, COLOR_BLUE); + AdvanceDialogWatcher dialog(COLOR_RED); + PromptDialogWatcher prompt(COLOR_GREEN); + DateChangeWatcher date_reader(env.console); + ItemPrinterMenuWatcher material(COLOR_GREEN); + int ret = wait_until( + env.console, context, std::chrono::seconds(120), + { + overworld, + dialog, + prompt, + material, + } + ); + switch (ret){ + case 0: + env.log("Detected overworld... Entering item printer."); + pbf_press_button(context, BUTTON_A, 20, 30); + continue; + + case 1: + env.log("Detected advance dialog."); + pbf_press_button(context, BUTTON_B, 20, 30); + continue; + + case 2:{ + env.log("Detected prompt dialog. Entering item printer."); + pbf_press_button(context, BUTTON_A, 10, 30); + context.wait_for_all_requests(); + continue; + } + case 3:{ + env.log("Detected material selection."); + ItemPrinterMaterialDetector detector(COLOR_RED, LANGUAGE); + + int8_t happiny_dust_row_num = detector.find_happiny_dust_row_index( + env.normal_inference_dispatcher(), + env.console, context + ); + num_happiny_dust = detector.detect_material_quantity( + env.normal_inference_dispatcher(), + env.console, context, + happiny_dust_row_num + ); + pbf_mash_button(context, BUTTON_B, 100); + return num_happiny_dust; + } + default: + stats.errors++; + env.update_stats(); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 2 minutes.", + env.console + ); + } + } + + return 0; +} + +void ItemPrinterRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + ItemPrinterRNG_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + + if (MODE == ItemPrinterMode::AUTO_MODE || MATERIAL_FARMER_OPTIONS.enabled()){ + // - Ensure audio input is enabled + LetsGoKillSoundDetector audio_detector(env.console, [](float){ return true; }); + wait_until( + env.console, context, + std::chrono::milliseconds(1100), + {audio_detector} + ); + audio_detector.throw_if_no_sound(std::chrono::milliseconds(1000)); + } + + try{ + if (MODE == ItemPrinterMode::AUTO_MODE){ + run_item_printer_rng_automode(env, context, stats); + }else{ + run_item_printer_rng(env, context, stats); + } + + }catch (ProgramFinishedException&){} + + if (FIX_TIME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h index 3b68b2fc79..d92514f025 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNG.h @@ -1,151 +1,151 @@ -/* Item Printer RNG - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterRNG_H -#define PokemonAutomation_PokemonSV_ItemPrinterRNG_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h" -#include "PokemonSV_ItemPrinterTools.h" -#include "PokemonSV_ItemPrinterRNGTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class ItemPrinterRNG_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ItemPrinterRNG_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class ItemPrinterRNG : public SingleSwitchProgramInstance, public ConfigOption::Listener{ -public: - ~ItemPrinterRNG(); - ItemPrinterRNG(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - enum class MaterialFarmerTrigger{ - FIXED_NUM_PRINT_JOBS, - MINIMUM_HAPPINY_DUST, - }; - - enum class ItemPrinterMode{ - STANDARD_MODE, - AUTO_MODE, - }; - - virtual void on_config_value_changed(void* object) override; - - bool overlapping_bonus(); - - void run_item_printer_rng_automode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, ItemPrinterRNG_Descriptor::Stats& stats); - - void run_item_printer_rng(SingleSwitchProgramEnvironment& env, ProControllerContext& context, ItemPrinterRNG_Descriptor::Stats& stats); - - std::vector desired_print_table( - ItemPrinter::PrebuiltOptions desired_item, - uint16_t quantity_to_print - ); - - // return Ball bonus or item bonus, based on the desired_item - // if the desired_item is a type of ball, return Ball Bonus, else return Item Bonus - ItemPrinter::PrebuiltOptions get_bonus_type(ItemPrinter::PrebuiltOptions desired_item); - - int16_t check_obtained_quantity(std::map obtained_prizes, std::string desired_slug); - - // move from item printer to material farming, run material farmer, then - // return to item printer - void run_material_farming_then_return_to_item_printer( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - ItemPrinterRNG_Descriptor::Stats& stats, - MaterialFarmerOptions& material_farmer_options - ); - - ItemPrinterPrizeResult run_print_at_date( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - const DateTime& date, ItemPrinterJobs jobs - ); - - void print_again( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - ItemPrinterJobs jobs - ) const; - - void adjust_delay( - Logger& logger, - SingleSwitchProgramEnvironment& env, - const std::array& print_results, - int distance_from_target - ); - - int get_distance_from_target( - Logger& logger, - ItemPrinterRNG_Descriptor::Stats& stats, - const std::array& print_results, - uint64_t seed - ); - - bool results_approximately_match( - const std::array& print_results, - const std::array& expected_result - ); - - uint32_t calc_num_jobs_using_happiny_dust( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - uint16_t min_happiny_dust - ); - - uint32_t check_num_happiny_dust( - SingleSwitchProgramEnvironment& env, ProControllerContext& context - ); - -private: - OCR::LanguageOCROption LANGUAGE; - SimpleIntegerOption NUM_ITEM_PRINTER_ROUNDS; - - StaticTextOption OVERLAPPING_BONUS_WARNING; - EnumDropdownOption MODE; - ItemPrinterDesiredItemTable DESIRED_ITEM_TABLE; - ItemPrinterRngTable DATE_SEED_TABLE; - - SimpleIntegerOption DELAY_MILLIS; - BooleanCheckBoxOption ADJUST_DELAY; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - - EnumDropdownOption MATERIAL_FARMER_TRIGGER; - SimpleIntegerOption MATERIAL_FARMER_FIXED_NUM_JOBS; - SimpleIntegerOption MIN_HAPPINY_DUST; - MaterialFarmerOptions MATERIAL_FARMER_OPTIONS; - - BooleanCheckBoxOption ENABLE_SEED_CALC; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Item Printer RNG + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterRNG_H +#define PokemonAutomation_PokemonSV_ItemPrinterRNG_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Programs/Farming/PokemonSV_MaterialFarmerTools.h" +#include "PokemonSV_ItemPrinterTools.h" +#include "PokemonSV_ItemPrinterRNGTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class ItemPrinterRNG_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ItemPrinterRNG_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class ItemPrinterRNG : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + ~ItemPrinterRNG(); + ItemPrinterRNG(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + enum class MaterialFarmerTrigger{ + FIXED_NUM_PRINT_JOBS, + MINIMUM_HAPPINY_DUST, + }; + + enum class ItemPrinterMode{ + STANDARD_MODE, + AUTO_MODE, + }; + + virtual void on_config_value_changed(void* object) override; + + bool overlapping_bonus(); + + void run_item_printer_rng_automode(SingleSwitchProgramEnvironment& env, ProControllerContext& context, ItemPrinterRNG_Descriptor::Stats& stats); + + void run_item_printer_rng(SingleSwitchProgramEnvironment& env, ProControllerContext& context, ItemPrinterRNG_Descriptor::Stats& stats); + + std::vector desired_print_table( + ItemPrinter::PrebuiltOptions desired_item, + uint16_t quantity_to_print + ); + + // return Ball bonus or item bonus, based on the desired_item + // if the desired_item is a type of ball, return Ball Bonus, else return Item Bonus + ItemPrinter::PrebuiltOptions get_bonus_type(ItemPrinter::PrebuiltOptions desired_item); + + int16_t check_obtained_quantity(std::map obtained_prizes, std::string desired_slug); + + // move from item printer to material farming, run material farmer, then + // return to item printer + void run_material_farming_then_return_to_item_printer( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + ItemPrinterRNG_Descriptor::Stats& stats, + MaterialFarmerOptions& material_farmer_options + ); + + ItemPrinterPrizeResult run_print_at_date( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + const DateTime& date, ItemPrinterJobs jobs + ); + + void print_again( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + ItemPrinterJobs jobs + ) const; + + void adjust_delay( + Logger& logger, + SingleSwitchProgramEnvironment& env, + const std::array& print_results, + int distance_from_target + ); + + int get_distance_from_target( + Logger& logger, + ItemPrinterRNG_Descriptor::Stats& stats, + const std::array& print_results, + uint64_t seed + ); + + bool results_approximately_match( + const std::array& print_results, + const std::array& expected_result + ); + + uint32_t calc_num_jobs_using_happiny_dust( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + uint16_t min_happiny_dust + ); + + uint32_t check_num_happiny_dust( + SingleSwitchProgramEnvironment& env, ProControllerContext& context + ); + +private: + OCR::LanguageOCROption LANGUAGE; + SimpleIntegerOption NUM_ITEM_PRINTER_ROUNDS; + + StaticTextOption OVERLAPPING_BONUS_WARNING; + EnumDropdownOption MODE; + ItemPrinterDesiredItemTable DESIRED_ITEM_TABLE; + ItemPrinterRngTable DATE_SEED_TABLE; + + SimpleIntegerOption DELAY_MILLIS; + BooleanCheckBoxOption ADJUST_DELAY; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + + EnumDropdownOption MATERIAL_FARMER_TRIGGER; + SimpleIntegerOption MATERIAL_FARMER_FIXED_NUM_JOBS; + SimpleIntegerOption MIN_HAPPINY_DUST; + MaterialFarmerOptions MATERIAL_FARMER_OPTIONS; + + BooleanCheckBoxOption ENABLE_SEED_CALC; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp index 9aa7c6cdb3..504ddee0db 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.cpp @@ -1,239 +1,239 @@ -/* Item Printer RNG Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/TimeQt.h" -#include "PokemonSV_ItemPrinterRNGTable.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -ItemPrinterRngRow::~ItemPrinterRngRow(){ - chain.remove_listener(*this); - date.remove_listener(*this); - jobs.remove_listener(*this); - desired_item.remove_listener(*this); -} -ItemPrinterRngRow::ItemPrinterRngRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , chain(LockMode::UNLOCK_WHILE_RUNNING, false) - , date( - LockMode::UNLOCK_WHILE_RUNNING, - DateTimeOption::DATE_HOUR_MIN_SEC, - DateTime{2000, 1, 1, 0, 1, 0}, - DateTime{2060, 12, 31, 23, 59, 59}, - DateTime{2024, 6, 4, 0, 37, 8} - ) - , jobs( - ItemPrinterJobs_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ItemPrinterJobs::Jobs_1 - ) - , desired_item( - ItemPrinter::PrebuiltOptions_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ItemPrinter::PrebuiltOptions::BALL_BONUS - ) -{ - PA_ADD_OPTION(chain); - PA_ADD_OPTION(date); - PA_ADD_OPTION(jobs); - PA_ADD_OPTION(desired_item); - - chain.add_listener(*this); - date.add_listener(*this); - jobs.add_listener(*this); - desired_item.add_listener(*this); -} -ItemPrinterRngRow::ItemPrinterRngRow( - EditableTableOption& parent_table, - bool p_chain, const DateTime& p_date, ItemPrinterJobs p_jobs -) - : ItemPrinterRngRow(parent_table) -{ - chain = p_chain; - date.set(p_date); - jobs.set(p_jobs); -} -ItemPrinterRngRowSnapshot ItemPrinterRngRow::snapshot() const{ - return ItemPrinterRngRowSnapshot{chain, date, jobs}; -} -std::unique_ptr ItemPrinterRngRow::clone() const{ - std::unique_ptr ret(new ItemPrinterRngRow(parent())); - ret->chain = (bool)chain; - ret->date.set(date); - ret->jobs.set(jobs); - return ret; -} - - - -// - if desired_item has changed, set the seed (and number of jobs) accordingly -// - if any of date/jobs/chain changes, check if the date and jobs match one of ItemPrinterEnumOption, -// and that chain is disabled. If so, set the desired item to the enum_value. Else set desired_item to NONE. -// - also, hide the date if chain enabled. -// - trigger the listener for the parent table. -void ItemPrinterRngRow::on_config_value_changed(void* object){ - // This is really ugly due to the circular update dependency. - // TODO: Redesign this. - - { - WriteSpinLock lg1(m_pending_lock); - m_pending.emplace_back(object); - } - - bool keep_going; - do{ - std::unique_lock lg(m_update_lock, std::try_to_lock_t()); - if (!lg.owns_lock()){ - return; - } - { - WriteSpinLock lg1(m_pending_lock); - object = m_pending.front(); - m_pending.pop_front(); - } - - ItemPrinterRngTable& table = static_cast(parent()); - - if (object == &desired_item){ - ItemPrinter::PrebuiltOptions option = desired_item; - if (option != ItemPrinter::PrebuiltOptions::NONE){ - const ItemPrinter::ItemPrinterEnumOption& option_data = option_lookup_by_enum(option); - chain = false; - jobs.set(option_data.jobs); - date.set(from_seconds_since_epoch(option_data.seed)); - } - }else if (object == &date || object == &jobs || object == &chain){ - date.set_visibility(chain ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); - const ItemPrinter::ItemPrinterEnumOption* option_data = ItemPrinter::option_lookup_by_seed(to_seconds_since_epoch(date)); -// cout << "option_data = " << option_data << endl; - // seed found in the PrebuiltOptions table, and jobs number matches and chain disabled - if (option_data != nullptr && option_data->jobs == jobs && !chain){ - desired_item.set(option_data->enum_value); - }else{ -// cout << "option_data->jobs = " << (size_t)option_data->jobs << ", jobs = " << jobs.current_value() << ", chain = " << chain << endl; - desired_item.set(ItemPrinter::PrebuiltOptions::NONE); - } - } - - table.report_value_changed(object); - - WriteSpinLock lg1(m_pending_lock); - keep_going = !m_pending.empty(); - }while (keep_going); -} - -ItemPrinterRngTable::ItemPrinterRngTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::UNLOCK_WHILE_RUNNING - ) -{ - // Need to do this separately because this prematurely accesses the table. - set_default(make_defaults()); - restore_defaults(); -} -std::vector ItemPrinterRngTable::make_header() const{ - return std::vector{ - "Continue Previous?", - "Date Seed", - "Jobs to Print", - "Desired Item", - }; -} -std::vector> ItemPrinterRngTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this, false, DateTime{2024, 6, 4, 0, 37, 8}, ItemPrinterJobs::Jobs_1)); - ret.emplace_back(std::make_unique(*this, false, DateTime{2049, 8, 18, 23, 51, 8}, ItemPrinterJobs::Jobs_10)); - ret.emplace_back(std::make_unique(*this, false, DateTime{2024, 6, 4, 0, 37, 8}, ItemPrinterJobs::Jobs_1)); - ret.emplace_back(std::make_unique(*this, false, DateTime{2031, 10, 8, 7, 9, 9}, ItemPrinterJobs::Jobs_10)); - ret.emplace_back(std::make_unique(*this, false, DateTime{2024, 6, 4, 0, 37, 8}, ItemPrinterJobs::Jobs_1)); - ret.emplace_back(std::make_unique(*this, false, DateTime{2020, 3, 3, 6, 38, 18}, ItemPrinterJobs::Jobs_10)); - return ret; -} - - - -ItemPrinterDesiredItemRow::ItemPrinterDesiredItemRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , desired_item( - ItemPrinter::PrebuiltOptions_AutoMode_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ItemPrinter::PrebuiltOptions::ABILITY_PATCH - ) - , desired_quantity( - "", - LockMode::UNLOCK_WHILE_RUNNING, - 999, 1, 999 - ) -{ - PA_ADD_OPTION(desired_item); - PA_ADD_OPTION(desired_quantity); - -} - -ItemPrinterDesiredItemRow::ItemPrinterDesiredItemRow( - EditableTableOption& parent_table, - ItemPrinter::PrebuiltOptions item, uint16_t quantity -) - : ItemPrinterDesiredItemRow(parent_table) -{ - desired_item.set(item); - desired_quantity.set(quantity); -} - -ItemPrinterDesiredItemRowSnapshot ItemPrinterDesiredItemRow::snapshot() const{ - - return ItemPrinterDesiredItemRowSnapshot{desired_item, desired_quantity}; -} - - -std::unique_ptr ItemPrinterDesiredItemRow::clone() const{ - std::unique_ptr ret(new ItemPrinterDesiredItemRow(parent())); - ret->desired_item.set(desired_item); - ret->desired_quantity.set(desired_quantity); - return ret; -} - - -void ItemPrinterDesiredItemRow::on_config_value_changed(void* object){ - -} - -ItemPrinterDesiredItemTable::ItemPrinterDesiredItemTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING - ) -{ - // Need to do this separately because this prematurely accesses the table. - set_default(make_defaults()); - restore_defaults(); -} -std::vector ItemPrinterDesiredItemTable::make_header() const{ - return std::vector{ - "Desired Item", - "Quantity", - }; -} -std::vector> ItemPrinterDesiredItemTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this, ItemPrinter::PrebuiltOptions::ABILITY_PATCH, (uint16_t)999)); - ret.emplace_back(std::make_unique(*this, ItemPrinter::PrebuiltOptions::EXP_CANDY, (uint16_t)999)); - return ret; -} - - -} -} -} +/* Item Printer RNG Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/TimeQt.h" +#include "PokemonSV_ItemPrinterRNGTable.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +ItemPrinterRngRow::~ItemPrinterRngRow(){ + chain.remove_listener(*this); + date.remove_listener(*this); + jobs.remove_listener(*this); + desired_item.remove_listener(*this); +} +ItemPrinterRngRow::ItemPrinterRngRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , chain(LockMode::UNLOCK_WHILE_RUNNING, false) + , date( + LockMode::UNLOCK_WHILE_RUNNING, + DateTimeOption::DATE_HOUR_MIN_SEC, + DateTime{2000, 1, 1, 0, 1, 0}, + DateTime{2060, 12, 31, 23, 59, 59}, + DateTime{2024, 6, 4, 0, 37, 8} + ) + , jobs( + ItemPrinterJobs_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ItemPrinterJobs::Jobs_1 + ) + , desired_item( + ItemPrinter::PrebuiltOptions_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ItemPrinter::PrebuiltOptions::BALL_BONUS + ) +{ + PA_ADD_OPTION(chain); + PA_ADD_OPTION(date); + PA_ADD_OPTION(jobs); + PA_ADD_OPTION(desired_item); + + chain.add_listener(*this); + date.add_listener(*this); + jobs.add_listener(*this); + desired_item.add_listener(*this); +} +ItemPrinterRngRow::ItemPrinterRngRow( + EditableTableOption& parent_table, + bool p_chain, const DateTime& p_date, ItemPrinterJobs p_jobs +) + : ItemPrinterRngRow(parent_table) +{ + chain = p_chain; + date.set(p_date); + jobs.set(p_jobs); +} +ItemPrinterRngRowSnapshot ItemPrinterRngRow::snapshot() const{ + return ItemPrinterRngRowSnapshot{chain, date, jobs}; +} +std::unique_ptr ItemPrinterRngRow::clone() const{ + std::unique_ptr ret(new ItemPrinterRngRow(parent())); + ret->chain = (bool)chain; + ret->date.set(date); + ret->jobs.set(jobs); + return ret; +} + + + +// - if desired_item has changed, set the seed (and number of jobs) accordingly +// - if any of date/jobs/chain changes, check if the date and jobs match one of ItemPrinterEnumOption, +// and that chain is disabled. If so, set the desired item to the enum_value. Else set desired_item to NONE. +// - also, hide the date if chain enabled. +// - trigger the listener for the parent table. +void ItemPrinterRngRow::on_config_value_changed(void* object){ + // This is really ugly due to the circular update dependency. + // TODO: Redesign this. + + { + WriteSpinLock lg1(m_pending_lock); + m_pending.emplace_back(object); + } + + bool keep_going; + do{ + std::unique_lock lg(m_update_lock, std::try_to_lock_t()); + if (!lg.owns_lock()){ + return; + } + { + WriteSpinLock lg1(m_pending_lock); + object = m_pending.front(); + m_pending.pop_front(); + } + + ItemPrinterRngTable& table = static_cast(parent()); + + if (object == &desired_item){ + ItemPrinter::PrebuiltOptions option = desired_item; + if (option != ItemPrinter::PrebuiltOptions::NONE){ + const ItemPrinter::ItemPrinterEnumOption& option_data = option_lookup_by_enum(option); + chain = false; + jobs.set(option_data.jobs); + date.set(from_seconds_since_epoch(option_data.seed)); + } + }else if (object == &date || object == &jobs || object == &chain){ + date.set_visibility(chain ? ConfigOptionState::HIDDEN : ConfigOptionState::ENABLED); + const ItemPrinter::ItemPrinterEnumOption* option_data = ItemPrinter::option_lookup_by_seed(to_seconds_since_epoch(date)); +// cout << "option_data = " << option_data << endl; + // seed found in the PrebuiltOptions table, and jobs number matches and chain disabled + if (option_data != nullptr && option_data->jobs == jobs && !chain){ + desired_item.set(option_data->enum_value); + }else{ +// cout << "option_data->jobs = " << (size_t)option_data->jobs << ", jobs = " << jobs.current_value() << ", chain = " << chain << endl; + desired_item.set(ItemPrinter::PrebuiltOptions::NONE); + } + } + + table.report_value_changed(object); + + WriteSpinLock lg1(m_pending_lock); + keep_going = !m_pending.empty(); + }while (keep_going); +} + +ItemPrinterRngTable::ItemPrinterRngTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::UNLOCK_WHILE_RUNNING + ) +{ + // Need to do this separately because this prematurely accesses the table. + set_default(make_defaults()); + restore_defaults(); +} +std::vector ItemPrinterRngTable::make_header() const{ + return std::vector{ + "Continue Previous?", + "Date Seed", + "Jobs to Print", + "Desired Item", + }; +} +std::vector> ItemPrinterRngTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this, false, DateTime{2024, 6, 4, 0, 37, 8}, ItemPrinterJobs::Jobs_1)); + ret.emplace_back(std::make_unique(*this, false, DateTime{2049, 8, 18, 23, 51, 8}, ItemPrinterJobs::Jobs_10)); + ret.emplace_back(std::make_unique(*this, false, DateTime{2024, 6, 4, 0, 37, 8}, ItemPrinterJobs::Jobs_1)); + ret.emplace_back(std::make_unique(*this, false, DateTime{2031, 10, 8, 7, 9, 9}, ItemPrinterJobs::Jobs_10)); + ret.emplace_back(std::make_unique(*this, false, DateTime{2024, 6, 4, 0, 37, 8}, ItemPrinterJobs::Jobs_1)); + ret.emplace_back(std::make_unique(*this, false, DateTime{2020, 3, 3, 6, 38, 18}, ItemPrinterJobs::Jobs_10)); + return ret; +} + + + +ItemPrinterDesiredItemRow::ItemPrinterDesiredItemRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , desired_item( + ItemPrinter::PrebuiltOptions_AutoMode_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ItemPrinter::PrebuiltOptions::ABILITY_PATCH + ) + , desired_quantity( + "", + LockMode::UNLOCK_WHILE_RUNNING, + 999, 1, 999 + ) +{ + PA_ADD_OPTION(desired_item); + PA_ADD_OPTION(desired_quantity); + +} + +ItemPrinterDesiredItemRow::ItemPrinterDesiredItemRow( + EditableTableOption& parent_table, + ItemPrinter::PrebuiltOptions item, uint16_t quantity +) + : ItemPrinterDesiredItemRow(parent_table) +{ + desired_item.set(item); + desired_quantity.set(quantity); +} + +ItemPrinterDesiredItemRowSnapshot ItemPrinterDesiredItemRow::snapshot() const{ + + return ItemPrinterDesiredItemRowSnapshot{desired_item, desired_quantity}; +} + + +std::unique_ptr ItemPrinterDesiredItemRow::clone() const{ + std::unique_ptr ret(new ItemPrinterDesiredItemRow(parent())); + ret->desired_item.set(desired_item); + ret->desired_quantity.set(desired_quantity); + return ret; +} + + +void ItemPrinterDesiredItemRow::on_config_value_changed(void* object){ + +} + +ItemPrinterDesiredItemTable::ItemPrinterDesiredItemTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING + ) +{ + // Need to do this separately because this prematurely accesses the table. + set_default(make_defaults()); + restore_defaults(); +} +std::vector ItemPrinterDesiredItemTable::make_header() const{ + return std::vector{ + "Desired Item", + "Quantity", + }; +} +std::vector> ItemPrinterDesiredItemTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this, ItemPrinter::PrebuiltOptions::ABILITY_PATCH, (uint16_t)999)); + ret.emplace_back(std::make_unique(*this, ItemPrinter::PrebuiltOptions::EXP_CANDY, (uint16_t)999)); + return ret; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h index f94ef86310..71a62da96e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterRNGTable.h @@ -1,113 +1,113 @@ -/* Item Printer RNG Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterRNGTable_H -#define PokemonAutomation_PokemonSV_ItemPrinterRNGTable_H - -#include -#include -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/DateOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "PokemonSV_ItemPrinterTools.h" -#include "PokemonSV_ItemPrinterDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct ItemPrinterRngRowSnapshot{ - bool chain; - DateTime date; - ItemPrinterJobs jobs; -}; - - -class ItemPrinterRngRow : public EditableTableRow, public ConfigOption::Listener{ -public: - - ~ItemPrinterRngRow(); - ItemPrinterRngRow(EditableTableOption& parent_table); - ItemPrinterRngRow( - EditableTableOption& parent_table, - bool p_chain, const DateTime& p_date, ItemPrinterJobs p_jobs - ); - - ItemPrinterRngRowSnapshot snapshot() const; - - virtual std::unique_ptr clone() const override; - virtual void on_config_value_changed(void* object) override; - -// void set_seed_based_on_desired_item(); - -public: - BooleanCheckBoxCell chain; - DateTimeCell date; - EnumDropdownCell jobs; - EnumDropdownCell desired_item; - -private: - // Brutal work-around for circular callback dependency. - SpinLock m_pending_lock; - std::deque m_pending; - std::mutex m_update_lock; -}; - - -class ItemPrinterRngTable : public EditableTableOption_t{ -public: - ItemPrinterRngTable(std::string label); - virtual std::vector make_header() const override; - std::vector> make_defaults(); - - friend class ItemPrinterRngRow; -}; - -struct ItemPrinterDesiredItemRowSnapshot{ - ItemPrinter::PrebuiltOptions item; - uint16_t quantity; -}; - -class ItemPrinterDesiredItemRow : public EditableTableRow, public ConfigOption::Listener{ -public: - - ItemPrinterDesiredItemRow(EditableTableOption& parent_table); - - ItemPrinterDesiredItemRow( - EditableTableOption& parent_table, - ItemPrinter::PrebuiltOptions item, uint16_t quantity - ); - - ItemPrinterDesiredItemRowSnapshot snapshot() const; - - virtual std::unique_ptr clone() const override; - virtual void on_config_value_changed(void* object) override; - -public: - EnumDropdownCell desired_item; - SimpleIntegerOption desired_quantity; - -}; - -class ItemPrinterDesiredItemTable : public EditableTableOption_t{ -public: - ItemPrinterDesiredItemTable(std::string label); - virtual std::vector make_header() const override; - std::vector> make_defaults(); - - friend class ItemPrinterDesiredItemRow; -}; - - - -} -} -} - -#endif +/* Item Printer RNG Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterRNGTable_H +#define PokemonAutomation_PokemonSV_ItemPrinterRNGTable_H + +#include +#include +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/DateOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "PokemonSV_ItemPrinterTools.h" +#include "PokemonSV_ItemPrinterDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct ItemPrinterRngRowSnapshot{ + bool chain; + DateTime date; + ItemPrinterJobs jobs; +}; + + +class ItemPrinterRngRow : public EditableTableRow, public ConfigOption::Listener{ +public: + + ~ItemPrinterRngRow(); + ItemPrinterRngRow(EditableTableOption& parent_table); + ItemPrinterRngRow( + EditableTableOption& parent_table, + bool p_chain, const DateTime& p_date, ItemPrinterJobs p_jobs + ); + + ItemPrinterRngRowSnapshot snapshot() const; + + virtual std::unique_ptr clone() const override; + virtual void on_config_value_changed(void* object) override; + +// void set_seed_based_on_desired_item(); + +public: + BooleanCheckBoxCell chain; + DateTimeCell date; + EnumDropdownCell jobs; + EnumDropdownCell desired_item; + +private: + // Brutal work-around for circular callback dependency. + SpinLock m_pending_lock; + std::deque m_pending; + std::mutex m_update_lock; +}; + + +class ItemPrinterRngTable : public EditableTableOption_t{ +public: + ItemPrinterRngTable(std::string label); + virtual std::vector make_header() const override; + std::vector> make_defaults(); + + friend class ItemPrinterRngRow; +}; + +struct ItemPrinterDesiredItemRowSnapshot{ + ItemPrinter::PrebuiltOptions item; + uint16_t quantity; +}; + +class ItemPrinterDesiredItemRow : public EditableTableRow, public ConfigOption::Listener{ +public: + + ItemPrinterDesiredItemRow(EditableTableOption& parent_table); + + ItemPrinterDesiredItemRow( + EditableTableOption& parent_table, + ItemPrinter::PrebuiltOptions item, uint16_t quantity + ); + + ItemPrinterDesiredItemRowSnapshot snapshot() const; + + virtual std::unique_ptr clone() const override; + virtual void on_config_value_changed(void* object) override; + +public: + EnumDropdownCell desired_item; + SimpleIntegerOption desired_quantity; + +}; + +class ItemPrinterDesiredItemTable : public EditableTableOption_t{ +public: + ItemPrinterDesiredItemTable(std::string label); + virtual std::vector make_header() const override; + std::vector> make_defaults(); + + friend class ItemPrinterDesiredItemRow; +}; + + + +} +} +} + +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.cpp index 4e8be34cd4..cd8a867c9f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.cpp @@ -1,416 +1,416 @@ -/* Item Printer Seed Calculation - * - * From: https://github.com/PokemonAutomation/ - * - * This file is ported from: - * https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/ItemPrinter.cs - * - * The actual RNG logic is from Anubis. - * - */ - -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Xoroshiro128Plus.h" -#include "PokemonSV_ItemPrinterSeedCalc.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ -namespace ItemPrinter{ - - -const char* item_id_to_slug(int item_id){ - // Taken from: https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/Resources/text/items_en.txt - static const std::map database{ - {1, "master-ball"}, - {2, "ultra-ball"}, - {3, "great-ball"}, - {4, "poke-ball"}, - {5, "safari-ball"}, - {6, "net-ball"}, - {7, "dive-ball"}, - {8, "nest-ball"}, - {9, "repeat-ball"}, - {10, "timer-ball"}, - {11, "luxury-ball"}, - {12, "premier-ball"}, - {13, "dusk-ball"}, - {14, "heal-ball"}, - {15, "quick-ball"}, - - {23, "full-restore"}, - {24, "max-potion"}, - {25, "hyper-potion"}, - {26, "super-potion"}, - {27, "full-heal"}, - {28, "revive"}, - {29, "max-revive"}, - - {38, "ether"}, - {39, "max-ether"}, - {40, "elixir"}, - {41, "max-elixir"}, - - {45, "hp-up"}, - {46, "protein"}, - {47, "iron"}, - {48, "carbos"}, - {49, "calcium"}, - - {51, "pp-up"}, - {52, "zinc"}, - {53, "pp-max"}, - - {80, "sun-stone"}, - {81, "moon-stone"}, - {82, "fire-stone"}, - {83, "thunder-stone"}, - {84, "water-stone"}, - {85, "leaf-stone"}, - {86, "tiny-mushroom"}, - {87, "big-mushroom"}, - {88, "pearl"}, - {89, "big-pearl"}, - {90, "stardust"}, - {91, "star-piece"}, - {92, "nugget"}, - - {94, "honey"}, - - {106, "rare-bone"}, - {107, "shiny-stone"}, - {108, "dusk-stone"}, - {109, "dawn-stone"}, - {110, "oval-stone"}, - - {221, "kings-rock"}, - {222, "silver-powder"}, - {223, "amulet-coin"}, - - {229, "everstone"}, - {230, "focus-band"}, - {231, "lucky-egg"}, - {232, "scope-lens"}, - {233, "metal-coat"}, - {234, "leftovers"}, - {235, "dragon-scale"}, - - {237, "soft-sand"}, - {238, "hard-stone"}, - {239, "miracle-seed"}, - {240, "black-glasses"}, - {241, "black-belt"}, - {242, "magnet"}, - {243, "mystic-water"}, - {244, "sharp-beak"}, - {245, "poison-barb"}, - {246, "never-melt-ice"}, - {247, "spell-tag"}, - {248, "twisted-spoon"}, - {249, "charcoal"}, - {250, "dragon-fang"}, - {251, "silk-scarf"}, - {252, "upgrade"}, - - {269, "light-clay"}, - - {272, "toxic-orb"}, - {273, "flame-orb"}, - - {277, "metronome"}, - - {281, "black-sludge"}, - - {321, "protector"}, - {322, "electirizer"}, - {323, "magmarizer"}, - {324, "dubious-disc"}, - {325, "reaper-cloth"}, - {326, "razor-claw"}, - {327, "razor-fang"}, - - {492, "fast-ball"}, - {493, "level-ball"}, - {494, "lure-ball"}, - {495, "heavy-ball"}, - {496, "love-ball"}, - {497, "friend-ball"}, - {498, "moon-ball"}, - {499, "sport-ball"}, - - {537, "prism-scale"}, - - {541, "air-balloon"}, - - {571, "pretty-feather"}, - - {576, "dream-ball"}, - - {580, "balm-mushroom"}, - {581, "big-nugget"}, - {582, "pearl-string"}, - {583, "comet-shard"}, - - {645, "ability-capsule"}, - - {650, "safety-goggles"}, - - {795, "bottle-cap"}, - {796, "gold-bottle-cap"}, - - {849, "ice-stone"}, - - {851, "beast-ball"}, - - {1109, "strawberry-sweet"}, - {1110, "love-sweet"}, - {1111, "berry-sweet"}, - {1112, "clover-sweet"}, - {1113, "flower-sweet"}, - {1114, "star-sweet"}, - {1115, "ribbon-sweet"}, - - {1120, "heavy-duty-boots"}, - - {1124, "exp-candy-xs"}, - {1125, "exp-candy-s"}, - {1126, "exp-candy-m"}, - {1127, "exp-candy-l"}, - {1128, "exp-candy-xl"}, - - {1253, "cracked-pot"}, - {1254, "chipped-pot"}, - - {1606, "ability-patch"}, - - {1842, "tiny-bamboo-shoot"}, - {1843, "big-bamboo-shoot"}, - - {1862, "normal-tera-shard"}, - {1863, "fire-tera-shard"}, - {1864, "water-tera-shard"}, - {1865, "electric-tera-shard"}, - {1866, "grass-tera-shard"}, - {1867, "ice-tera-shard"}, - {1868, "fighting-tera-shard"}, - {1869, "poison-tera-shard"}, - {1870, "ground-tera-shard"}, - {1871, "flying-tera-shard"}, - {1872, "psychic-tera-shard"}, - {1873, "bug-tera-shard"}, - {1874, "rock-tera-shard"}, - {1875, "ghost-tera-shard"}, - {1876, "dragon-tera-shard"}, - {1877, "dark-tera-shard"}, - {1878, "steel-tera-shard"}, - {1879, "fairy-tera-shard"}, - - {1885, "covert-cloak"}, - {1886, "loaded-dice"}, - - {2401, "fairy-feather"}, - - {2403, "unremarkable-teacup"}, - {2404, "masterpiece-teacup"}, - - {2482, "metal-alloy"}, - - {2549, "stellar-tera-shard"}, - }; - auto iter = database.find(item_id); - if (iter != database.end()){ - return iter->second; - }else{ - return nullptr; - } -} - -struct ItemPrinterItemData{ - const char* slug; - uint16_t weight; - uint8_t min_quantity; - uint8_t max_quantity; -}; - -std::vector make_item_prize_list(){ - // This is taken from: - // https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/Resources/item_table_array.json - // The file itself is originally from a pkNX dump of the game. - const std::string path = "PokemonSV/ItemPrinterItems.json"; - JsonValue json = load_json_file(RESOURCE_PATH() + path); - const JsonArray& array = json - .to_object_throw(path) - .get_array_throw("Table", path); - - std::vector ret; - ret.reserve(array.size()); - - for (const JsonValue& item : array){ - const JsonObject& entry = item.to_object_throw(path) - .get_object_throw("Param", path) - .get_object_throw("Value", path); - int item_id = (int)entry.get_integer_throw("ItemId", path); - const char* slug = item_id_to_slug(item_id); - if (slug == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Item ID: " + std::to_string(item_id)); - } - ret.emplace_back(ItemPrinterItemData{ - slug, - (uint16_t)entry.get_integer_throw("EmergePercent", path), - (uint8_t)entry.get_integer_throw("LotteryItemNumMin", path), - (uint8_t)entry.get_integer_throw("LotteryItemNumMax", path) - }); - } - - return ret; -} -std::vector make_ball_prize_list(){ - // This is taken from: - // https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/Resources/special_item_table_array.json - // The file itself is originally from a pkNX dump of the game. - const std::string path = "PokemonSV/ItemPrinterBalls.json"; - JsonValue json = load_json_file(RESOURCE_PATH() + path); - const JsonArray& array = json - .to_object_throw(path) - .get_array_throw("Table", path)[0] - .to_object_throw(path) - .get_object_throw("Param", path) - .get_array_throw("Table", path); - - std::vector ret; - ret.reserve(array.size()); - - for (const JsonValue& item : array){ - const JsonObject& entry = item.to_object_throw(path); - int item_id = (int)entry.get_integer_throw("ItemId", path); - const char* slug = item_id_to_slug(item_id); - if (slug == nullptr){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Item ID: " + std::to_string(item_id)); - } - ret.emplace_back(ItemPrinterItemData{ - slug, - (uint16_t)entry.get_integer_throw("EmergePercent", path), - (uint8_t)entry.get_integer_throw("LotteryItemNumMin", path), - (uint8_t)entry.get_integer_throw("LotteryItemNumMax", path) - }); - } - - return ret; -} -std::vector make_item_prize_table(const std::vector& prize_list){ - const size_t RAND_SLOTS = 10001; - std::vector ret; - ret.reserve(RAND_SLOTS); - - // Sort by weight. - std::multimap sorted; - for (const ItemPrinterItemData& item : prize_list){ - sorted.emplace(item.weight, &item); - } - - // Handle quirk where the first item has n+1 weight. - ret.emplace_back(); - - for (const auto& item : sorted){ - size_t weight = item.second->weight; - while (weight-- > 0){ - ret.emplace_back(item.second); - } - } - - if (ret.size() != RAND_SLOTS){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sum of weights doesn't match expected value: " + std::to_string(ret.size())); - } - - // Handle quirk where the first item has n+1 weight. - ret[0] = ret[1]; - - return ret; -} - - -std::vector make_item_prize_table(){ - static const std::vector& PRIZE_LIST = make_item_prize_list(); - return make_item_prize_table(PRIZE_LIST); -} -std::vector make_ball_prize_table(){ - static const std::vector& PRIZE_LIST = make_ball_prize_list(); - return make_item_prize_table(PRIZE_LIST); -} - - -enum class PrintMode{ - Regular = 0, - ItemBonus = 1, - BallBonus = 2, -}; - - -std::array calculate_prizes(int64_t seed, PrintMode mode){ - static const std::vector ITEM_TABLE = make_item_prize_table(); - static const std::vector BALL_TABLE = make_ball_prize_table(); - - const std::vector& table = mode == PrintMode::BallBonus - ? BALL_TABLE - : ITEM_TABLE; - - Pokemon::Xoroshiro128Plus rand(seed, 0x82A2B175229D6A5B); - - PrintMode return_mode = PrintMode::Regular; - std::array ret; - for (size_t c = 0; c < 10; c++){ - // Always check for next bonus mode, even if not possible. - uint64_t roll = rand.nextInt(1000); - bool bonus = roll < 20; - - // Determine the item to print. - uint64_t item_roll = rand.nextInt(table.size()); - const ItemPrinterItemData& item = *table[item_roll]; - ret[c] = item.slug; - - // Determine quantity. - if (item.min_quantity != item.max_quantity){ - rand.nextInt(item.max_quantity - item.min_quantity + 1); - } - - // If we're lucky enough to get a bonus mode, pick one. - // Assume the player has both modes unlocked. - // If a bonus mode was previously set, don't recalculate. - if (mode == PrintMode::Regular && bonus && return_mode == PrintMode::Regular){ - return_mode = (PrintMode)(1 + rand.nextInt(2)); - } - - } - - return ret; -} - - - - -DateSeed calculate_seed_prizes(int64_t seed){ - return DateSeed{ - seed, - calculate_prizes(seed, PrintMode::Regular), - calculate_prizes(seed, PrintMode::ItemBonus), - calculate_prizes(seed, PrintMode::BallBonus) - }; -} - - - - -} -} -} -} +/* Item Printer Seed Calculation + * + * From: https://github.com/PokemonAutomation/ + * + * This file is ported from: + * https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/ItemPrinter.cs + * + * The actual RNG logic is from Anubis. + * + */ + +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Xoroshiro128Plus.h" +#include "PokemonSV_ItemPrinterSeedCalc.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace ItemPrinter{ + + +const char* item_id_to_slug(int item_id){ + // Taken from: https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/Resources/text/items_en.txt + static const std::map database{ + {1, "master-ball"}, + {2, "ultra-ball"}, + {3, "great-ball"}, + {4, "poke-ball"}, + {5, "safari-ball"}, + {6, "net-ball"}, + {7, "dive-ball"}, + {8, "nest-ball"}, + {9, "repeat-ball"}, + {10, "timer-ball"}, + {11, "luxury-ball"}, + {12, "premier-ball"}, + {13, "dusk-ball"}, + {14, "heal-ball"}, + {15, "quick-ball"}, + + {23, "full-restore"}, + {24, "max-potion"}, + {25, "hyper-potion"}, + {26, "super-potion"}, + {27, "full-heal"}, + {28, "revive"}, + {29, "max-revive"}, + + {38, "ether"}, + {39, "max-ether"}, + {40, "elixir"}, + {41, "max-elixir"}, + + {45, "hp-up"}, + {46, "protein"}, + {47, "iron"}, + {48, "carbos"}, + {49, "calcium"}, + + {51, "pp-up"}, + {52, "zinc"}, + {53, "pp-max"}, + + {80, "sun-stone"}, + {81, "moon-stone"}, + {82, "fire-stone"}, + {83, "thunder-stone"}, + {84, "water-stone"}, + {85, "leaf-stone"}, + {86, "tiny-mushroom"}, + {87, "big-mushroom"}, + {88, "pearl"}, + {89, "big-pearl"}, + {90, "stardust"}, + {91, "star-piece"}, + {92, "nugget"}, + + {94, "honey"}, + + {106, "rare-bone"}, + {107, "shiny-stone"}, + {108, "dusk-stone"}, + {109, "dawn-stone"}, + {110, "oval-stone"}, + + {221, "kings-rock"}, + {222, "silver-powder"}, + {223, "amulet-coin"}, + + {229, "everstone"}, + {230, "focus-band"}, + {231, "lucky-egg"}, + {232, "scope-lens"}, + {233, "metal-coat"}, + {234, "leftovers"}, + {235, "dragon-scale"}, + + {237, "soft-sand"}, + {238, "hard-stone"}, + {239, "miracle-seed"}, + {240, "black-glasses"}, + {241, "black-belt"}, + {242, "magnet"}, + {243, "mystic-water"}, + {244, "sharp-beak"}, + {245, "poison-barb"}, + {246, "never-melt-ice"}, + {247, "spell-tag"}, + {248, "twisted-spoon"}, + {249, "charcoal"}, + {250, "dragon-fang"}, + {251, "silk-scarf"}, + {252, "upgrade"}, + + {269, "light-clay"}, + + {272, "toxic-orb"}, + {273, "flame-orb"}, + + {277, "metronome"}, + + {281, "black-sludge"}, + + {321, "protector"}, + {322, "electirizer"}, + {323, "magmarizer"}, + {324, "dubious-disc"}, + {325, "reaper-cloth"}, + {326, "razor-claw"}, + {327, "razor-fang"}, + + {492, "fast-ball"}, + {493, "level-ball"}, + {494, "lure-ball"}, + {495, "heavy-ball"}, + {496, "love-ball"}, + {497, "friend-ball"}, + {498, "moon-ball"}, + {499, "sport-ball"}, + + {537, "prism-scale"}, + + {541, "air-balloon"}, + + {571, "pretty-feather"}, + + {576, "dream-ball"}, + + {580, "balm-mushroom"}, + {581, "big-nugget"}, + {582, "pearl-string"}, + {583, "comet-shard"}, + + {645, "ability-capsule"}, + + {650, "safety-goggles"}, + + {795, "bottle-cap"}, + {796, "gold-bottle-cap"}, + + {849, "ice-stone"}, + + {851, "beast-ball"}, + + {1109, "strawberry-sweet"}, + {1110, "love-sweet"}, + {1111, "berry-sweet"}, + {1112, "clover-sweet"}, + {1113, "flower-sweet"}, + {1114, "star-sweet"}, + {1115, "ribbon-sweet"}, + + {1120, "heavy-duty-boots"}, + + {1124, "exp-candy-xs"}, + {1125, "exp-candy-s"}, + {1126, "exp-candy-m"}, + {1127, "exp-candy-l"}, + {1128, "exp-candy-xl"}, + + {1253, "cracked-pot"}, + {1254, "chipped-pot"}, + + {1606, "ability-patch"}, + + {1842, "tiny-bamboo-shoot"}, + {1843, "big-bamboo-shoot"}, + + {1862, "normal-tera-shard"}, + {1863, "fire-tera-shard"}, + {1864, "water-tera-shard"}, + {1865, "electric-tera-shard"}, + {1866, "grass-tera-shard"}, + {1867, "ice-tera-shard"}, + {1868, "fighting-tera-shard"}, + {1869, "poison-tera-shard"}, + {1870, "ground-tera-shard"}, + {1871, "flying-tera-shard"}, + {1872, "psychic-tera-shard"}, + {1873, "bug-tera-shard"}, + {1874, "rock-tera-shard"}, + {1875, "ghost-tera-shard"}, + {1876, "dragon-tera-shard"}, + {1877, "dark-tera-shard"}, + {1878, "steel-tera-shard"}, + {1879, "fairy-tera-shard"}, + + {1885, "covert-cloak"}, + {1886, "loaded-dice"}, + + {2401, "fairy-feather"}, + + {2403, "unremarkable-teacup"}, + {2404, "masterpiece-teacup"}, + + {2482, "metal-alloy"}, + + {2549, "stellar-tera-shard"}, + }; + auto iter = database.find(item_id); + if (iter != database.end()){ + return iter->second; + }else{ + return nullptr; + } +} + +struct ItemPrinterItemData{ + const char* slug; + uint16_t weight; + uint8_t min_quantity; + uint8_t max_quantity; +}; + +std::vector make_item_prize_list(){ + // This is taken from: + // https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/Resources/item_table_array.json + // The file itself is originally from a pkNX dump of the game. + const std::string path = "PokemonSV/ItemPrinterItems.json"; + JsonValue json = load_json_file(RESOURCE_PATH() + path); + const JsonArray& array = json + .to_object_throw(path) + .get_array_throw("Table", path); + + std::vector ret; + ret.reserve(array.size()); + + for (const JsonValue& item : array){ + const JsonObject& entry = item.to_object_throw(path) + .get_object_throw("Param", path) + .get_object_throw("Value", path); + int item_id = (int)entry.get_integer_throw("ItemId", path); + const char* slug = item_id_to_slug(item_id); + if (slug == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Item ID: " + std::to_string(item_id)); + } + ret.emplace_back(ItemPrinterItemData{ + slug, + (uint16_t)entry.get_integer_throw("EmergePercent", path), + (uint8_t)entry.get_integer_throw("LotteryItemNumMin", path), + (uint8_t)entry.get_integer_throw("LotteryItemNumMax", path) + }); + } + + return ret; +} +std::vector make_ball_prize_list(){ + // This is taken from: + // https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/Resources/special_item_table_array.json + // The file itself is originally from a pkNX dump of the game. + const std::string path = "PokemonSV/ItemPrinterBalls.json"; + JsonValue json = load_json_file(RESOURCE_PATH() + path); + const JsonArray& array = json + .to_object_throw(path) + .get_array_throw("Table", path)[0] + .to_object_throw(path) + .get_object_throw("Param", path) + .get_array_throw("Table", path); + + std::vector ret; + ret.reserve(array.size()); + + for (const JsonValue& item : array){ + const JsonObject& entry = item.to_object_throw(path); + int item_id = (int)entry.get_integer_throw("ItemId", path); + const char* slug = item_id_to_slug(item_id); + if (slug == nullptr){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unknown Item ID: " + std::to_string(item_id)); + } + ret.emplace_back(ItemPrinterItemData{ + slug, + (uint16_t)entry.get_integer_throw("EmergePercent", path), + (uint8_t)entry.get_integer_throw("LotteryItemNumMin", path), + (uint8_t)entry.get_integer_throw("LotteryItemNumMax", path) + }); + } + + return ret; +} +std::vector make_item_prize_table(const std::vector& prize_list){ + const size_t RAND_SLOTS = 10001; + std::vector ret; + ret.reserve(RAND_SLOTS); + + // Sort by weight. + std::multimap sorted; + for (const ItemPrinterItemData& item : prize_list){ + sorted.emplace(item.weight, &item); + } + + // Handle quirk where the first item has n+1 weight. + ret.emplace_back(); + + for (const auto& item : sorted){ + size_t weight = item.second->weight; + while (weight-- > 0){ + ret.emplace_back(item.second); + } + } + + if (ret.size() != RAND_SLOTS){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Sum of weights doesn't match expected value: " + std::to_string(ret.size())); + } + + // Handle quirk where the first item has n+1 weight. + ret[0] = ret[1]; + + return ret; +} + + +std::vector make_item_prize_table(){ + static const std::vector& PRIZE_LIST = make_item_prize_list(); + return make_item_prize_table(PRIZE_LIST); +} +std::vector make_ball_prize_table(){ + static const std::vector& PRIZE_LIST = make_ball_prize_list(); + return make_item_prize_table(PRIZE_LIST); +} + + +enum class PrintMode{ + Regular = 0, + ItemBonus = 1, + BallBonus = 2, +}; + + +std::array calculate_prizes(int64_t seed, PrintMode mode){ + static const std::vector ITEM_TABLE = make_item_prize_table(); + static const std::vector BALL_TABLE = make_ball_prize_table(); + + const std::vector& table = mode == PrintMode::BallBonus + ? BALL_TABLE + : ITEM_TABLE; + + Pokemon::Xoroshiro128Plus rand(seed, 0x82A2B175229D6A5B); + + PrintMode return_mode = PrintMode::Regular; + std::array ret; + for (size_t c = 0; c < 10; c++){ + // Always check for next bonus mode, even if not possible. + uint64_t roll = rand.nextInt(1000); + bool bonus = roll < 20; + + // Determine the item to print. + uint64_t item_roll = rand.nextInt(table.size()); + const ItemPrinterItemData& item = *table[item_roll]; + ret[c] = item.slug; + + // Determine quantity. + if (item.min_quantity != item.max_quantity){ + rand.nextInt(item.max_quantity - item.min_quantity + 1); + } + + // If we're lucky enough to get a bonus mode, pick one. + // Assume the player has both modes unlocked. + // If a bonus mode was previously set, don't recalculate. + if (mode == PrintMode::Regular && bonus && return_mode == PrintMode::Regular){ + return_mode = (PrintMode)(1 + rand.nextInt(2)); + } + + } + + return ret; +} + + + + +DateSeed calculate_seed_prizes(int64_t seed){ + return DateSeed{ + seed, + calculate_prizes(seed, PrintMode::Regular), + calculate_prizes(seed, PrintMode::ItemBonus), + calculate_prizes(seed, PrintMode::BallBonus) + }; +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h index 2da0d617b4..f97cacb9bd 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterSeedCalc.h @@ -1,30 +1,30 @@ -/* Item Printer Seed Calculation - * - * From: https://github.com/PokemonAutomation/ - * - * Calculate Item Printer prizes from seed. - * - * This file is ported from: - * https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/ItemPrinter.cs - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterSeedCalc_H -#define PokemonAutomation_PokemonSV_ItemPrinterSeedCalc_H - -#include "PokemonSV_ItemPrinterDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ -namespace ItemPrinter{ - - -DateSeed calculate_seed_prizes(int64_t seed); - - -} -} -} -} -#endif +/* Item Printer Seed Calculation + * + * From: https://github.com/PokemonAutomation/ + * + * Calculate Item Printer prizes from seed. + * + * This file is ported from: + * https://github.com/kwsch/ItemPrinterDeGacha/blob/main/ItemPrinterDeGacha.Core/ItemPrinter.cs + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterSeedCalc_H +#define PokemonAutomation_PokemonSV_ItemPrinterSeedCalc_H + +#include "PokemonSV_ItemPrinterDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ +namespace ItemPrinter{ + + +DateSeed calculate_seed_prizes(int64_t seed); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp index 61faccc4cd..f618e37098 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.cpp @@ -1,143 +1,143 @@ -/* Item Printer Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h" -#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h" -#include "PokemonSV_ItemPrinterTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const EnumDropdownDatabase& ItemPrinterJobs_Database(){ - static const EnumDropdownDatabase database({ - {ItemPrinterJobs::Jobs_1, "1", "1 Job"}, - {ItemPrinterJobs::Jobs_5, "5", "5 Jobs"}, - {ItemPrinterJobs::Jobs_10, "10", "10 Jobs"}, - }); - return database; -} - - - -void item_printer_start_print( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language, ItemPrinterJobs jobs -){ - stream.log("Starting print..."); - - while (true){ - PromptDialogWatcher prompt(COLOR_YELLOW); - WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); - WhiteButtonWatcher handle(COLOR_BLUE, WhiteButton::ButtonA, {0.40, 0.80, 0.20, 0.14}); - context.wait_for_all_requests(); - - int ret_print_start = wait_until( - stream, context, - std::chrono::seconds(120), - { handle, prompt, material } - ); - context.wait_for_all_requests(); - - switch (ret_print_start){ - case 0: // handle - return; - case 1: // prompt - stream.log("Confirming material selection..."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 2:{ // material - ItemPrinterJobsDetector detector(COLOR_RED); - VideoOverlaySet overlays(stream.overlay()); - detector.make_overlays(overlays); - detector.set_print_jobs(dispatcher, stream, context, (uint8_t)jobs); - pbf_press_button(context, BUTTON_X, 20, 230); - continue; - } - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "start_print(): No recognized state after 120 seconds.", - stream - ); - } - } -} -ItemPrinterPrizeResult item_printer_finish_print( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language -){ - stream.log("Finishing print..."); - bool print_finished = false; - - ItemPrinterPrizeResult prize_result; - while (true){ - AdvanceDialogWatcher dialog(COLOR_YELLOW); - WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); - WhiteButtonWatcher handle(COLOR_BLUE, WhiteButton::ButtonA, {0.40, 0.80, 0.20, 0.14}); - WhiteButtonWatcher result(COLOR_CYAN, WhiteButton::ButtonA, {0.87, 0.93, 0.10, 0.06}); - context.wait_for_all_requests(); - - int ret_print_end = wait_until( - stream, context, - std::chrono::seconds(120), - { material, handle, dialog, result } - ); - context.wait_for_all_requests(); - - switch (ret_print_end){ - case 0: // material - stream.log("Material selection screen detected."); - return prize_result; - case 1: // handle - case 2: // dialog - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 3:{ // result - stream.log("Result screen detected."); - if (print_finished){ - continue; - } - - if (language != Language::None){ - ItemPrinterPrizeReader reader(language); - VideoOverlaySet overlays(stream.overlay()); - reader.make_overlays(overlays); - auto snapshot = stream.video().snapshot(); - std::array prizes = reader.read_prizes(stream.logger(), dispatcher, snapshot); - std::array quantities = reader.read_quantity(stream.logger(), dispatcher, snapshot); - prize_result = {prizes, quantities}; -// static int c = 0; -// snapshot->save("test-" + std::to_string(c) + ".png"); - } - - pbf_mash_button(context, BUTTON_A, 1 * TICKS_PER_SECOND); - print_finished = true; - continue; - } - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "finish_print(): No recognized state after 120 seconds.", - stream - ); - } - } -} - - -} -} -} +/* Item Printer Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_WhiteButtonDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterJobsDetector.h" +#include "PokemonSV/Inference/ItemPrinter/PokemonSV_ItemPrinterPrizeReader.h" +#include "PokemonSV_ItemPrinterTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const EnumDropdownDatabase& ItemPrinterJobs_Database(){ + static const EnumDropdownDatabase database({ + {ItemPrinterJobs::Jobs_1, "1", "1 Job"}, + {ItemPrinterJobs::Jobs_5, "5", "5 Jobs"}, + {ItemPrinterJobs::Jobs_10, "10", "10 Jobs"}, + }); + return database; +} + + + +void item_printer_start_print( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language, ItemPrinterJobs jobs +){ + stream.log("Starting print..."); + + while (true){ + PromptDialogWatcher prompt(COLOR_YELLOW); + WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); + WhiteButtonWatcher handle(COLOR_BLUE, WhiteButton::ButtonA, {0.40, 0.80, 0.20, 0.14}); + context.wait_for_all_requests(); + + int ret_print_start = wait_until( + stream, context, + std::chrono::seconds(120), + { handle, prompt, material } + ); + context.wait_for_all_requests(); + + switch (ret_print_start){ + case 0: // handle + return; + case 1: // prompt + stream.log("Confirming material selection..."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 2:{ // material + ItemPrinterJobsDetector detector(COLOR_RED); + VideoOverlaySet overlays(stream.overlay()); + detector.make_overlays(overlays); + detector.set_print_jobs(dispatcher, stream, context, (uint8_t)jobs); + pbf_press_button(context, BUTTON_X, 20, 230); + continue; + } + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "start_print(): No recognized state after 120 seconds.", + stream + ); + } + } +} +ItemPrinterPrizeResult item_printer_finish_print( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language +){ + stream.log("Finishing print..."); + bool print_finished = false; + + ItemPrinterPrizeResult prize_result; + while (true){ + AdvanceDialogWatcher dialog(COLOR_YELLOW); + WhiteButtonWatcher material(COLOR_GREEN, WhiteButton::ButtonX, {0.63, 0.93, 0.17, 0.06}); + WhiteButtonWatcher handle(COLOR_BLUE, WhiteButton::ButtonA, {0.40, 0.80, 0.20, 0.14}); + WhiteButtonWatcher result(COLOR_CYAN, WhiteButton::ButtonA, {0.87, 0.93, 0.10, 0.06}); + context.wait_for_all_requests(); + + int ret_print_end = wait_until( + stream, context, + std::chrono::seconds(120), + { material, handle, dialog, result } + ); + context.wait_for_all_requests(); + + switch (ret_print_end){ + case 0: // material + stream.log("Material selection screen detected."); + return prize_result; + case 1: // handle + case 2: // dialog + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 3:{ // result + stream.log("Result screen detected."); + if (print_finished){ + continue; + } + + if (language != Language::None){ + ItemPrinterPrizeReader reader(language); + VideoOverlaySet overlays(stream.overlay()); + reader.make_overlays(overlays); + auto snapshot = stream.video().snapshot(); + std::array prizes = reader.read_prizes(stream.logger(), dispatcher, snapshot); + std::array quantities = reader.read_quantity(stream.logger(), dispatcher, snapshot); + prize_result = {prizes, quantities}; +// static int c = 0; +// snapshot->save("test-" + std::to_string(c) + ".png"); + } + + pbf_mash_button(context, BUTTON_A, 1 * TICKS_PER_SECOND); + print_finished = true; + continue; + } + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "finish_print(): No recognized state after 120 seconds.", + stream + ); + } + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h index 1374aab845..8659dddbe3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ItemPrinter/PokemonSV_ItemPrinterTools.h @@ -1,52 +1,52 @@ -/* Item Printer Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemPrinterTools_H -#define PokemonAutomation_PokemonSV_ItemPrinterTools_H - -#include -#include "Common/Cpp/Options/EnumDropdownDatabase.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -enum class ItemPrinterJobs{ - Jobs_1 = 1, - Jobs_5 = 5, - Jobs_10 = 10, -}; -const EnumDropdownDatabase& ItemPrinterJobs_Database(); - -struct ItemPrinterPrizeResult{ - std::array prizes; - std::array quantities; -}; - - -void item_printer_start_print( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language, ItemPrinterJobs jobs -); -ItemPrinterPrizeResult item_printer_finish_print( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language -); - - - - -} -} -} -#endif +/* Item Printer Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemPrinterTools_H +#define PokemonAutomation_PokemonSV_ItemPrinterTools_H + +#include +#include "Common/Cpp/Options/EnumDropdownDatabase.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +enum class ItemPrinterJobs{ + Jobs_1 = 1, + Jobs_5 = 5, + Jobs_10 = 10, +}; +const EnumDropdownDatabase& ItemPrinterJobs_Database(); + +struct ItemPrinterPrizeResult{ + std::array prizes; + std::array quantities; +}; + + +void item_printer_start_print( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language, ItemPrinterJobs jobs +); +ItemPrinterPrizeResult item_printer_finish_print( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp index ad9109f082..769d698e8d 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.cpp @@ -1,334 +1,334 @@ -/* Area Zero - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_AreaZero.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -void inside_zero_gate_to_station( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - int station, // 1 - 4 - bool heal_at_station -){ - { - AdvanceDialogWatcher dialog(COLOR_GREEN); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 0); - }, - {dialog} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find warp circle.", - stream - ); - } - } - - - - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(60)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to warp to station after 60 seconds.", - stream - ); - } - - AdvanceDialogWatcher dialog(COLOR_GREEN); - ZeroGateWarpPromptWatcher prompt(COLOR_GREEN); - BlackScreenOverWatcher black_screen(COLOR_RED); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(5), - {dialog, prompt, black_screen} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: - stream.log("Detected dialog."); - pbf_press_button(context, BUTTON_A, 20, 30); - continue; - case 1: - stream.log("Detected prompt."); - prompt.move_cursor(info, stream, context, station - 1); - pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); - continue; - case 2: - stream.log("Black screen is over. Arrive at station."); - break; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to find warp to station 2.", - stream - ); - } - - break; - } - context.wait_for_all_requests(); - context.wait_for(std::chrono::seconds(3)); - - if (heal_at_station){ - stream.log("Moving to bed to heal."); - pbf_move_left_joystick(context, 144, 0, 4 * TICKS_PER_SECOND, 0); - ssf_press_left_joystick(context, 255, 128, 0, 125); - bool healed = false; - while (true){ - AdvanceDialogWatcher dialog(COLOR_GREEN); - PromptDialogWatcher confirm(COLOR_GREEN); - BlackScreenOverWatcher black_screen(COLOR_RED); - OverworldWatcher overworld(stream.logger(), COLOR_BLUE); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(30), - {dialog, confirm, black_screen, overworld} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 1: - stream.log("Detected rest prompt."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 2: - stream.log("Done healing!"); - healed = true; - continue; - case 3: - stream.log("Detected overworld."); - if (healed){ - break; - }else{ - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - } - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Heal at station: No state detected after 30 seconds.", - stream - ); - } - break; - } - } - - stream.log("Exiting station. Waiting for black screen..."); - { - BlackScreenOverWatcher black_screen(COLOR_RED); - int ret = run_until( - stream, context, - [=](ProControllerContext& context){ - if (heal_at_station){ - pbf_move_left_joystick(context, 96, 255, 60 * TICKS_PER_SECOND, 0); - }else{ - pbf_move_left_joystick(context, 0, 255, 60 * TICKS_PER_SECOND, 0); - } - }, - {black_screen} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to exit station after 60 seconds.", - stream - ); - } - } - - stream.log("Exiting station. Waiting for overworld..."); - { - OverworldWatcher overworld(stream.logger(), COLOR_BLUE); - int ret = wait_until( - stream, context, std::chrono::seconds(30), - {overworld} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to load overworld after exiting station for 30 seconds.", - stream - ); - } - } -} - -void return_to_outside_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - open_map_from_overworld(info, stream, context); - pbf_move_left_joystick(context, 96, 96, 5, 50); - fly_to_overworld_from_map(info, stream, context); -} -void return_to_inside_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - return_to_outside_zero_gate(info, stream, context); - - BlackScreenOverWatcher black_screen; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 32, 20, 105); - pbf_mash_button(context, BUTTON_L, 60); - pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 0); - }, - {black_screen} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to enter Zero Gate.", - stream - ); - } - - OverworldWatcher overworld(stream.logger()); - ret = wait_until( - stream, context, std::chrono::seconds(10), - {overworld} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect overworld inside Zero Gate.", - stream - ); - } -} -void return_to_inside_zero_gate_from_picnic( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - BlackScreenOverWatcher black_screen; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 100, 40); - pbf_mash_button(context, BUTTON_L, 60); - pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 0); - }, - {black_screen} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to enter Zero Gate.", - stream - ); - } - - OverworldWatcher overworld(stream.logger()); - ret = wait_until( - stream, context, std::chrono::seconds(10), - {overworld} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect overworld inside Zero Gate.", - stream - ); - } -} - - - - -void inside_zero_gate_to_secret_cave_entrance( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - bool heal_at_station -){ - inside_zero_gate_to_station(info, stream, context, 1, heal_at_station); - - context.wait_for(std::chrono::seconds(3)); - - pbf_move_left_joystick(context, 0, 208, 30, 50); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - - // Leg 1 - ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); - ssf_press_left_joystick(context, 128, 0, 60, 1250); - - // Jump - ssf_press_button(context, BUTTON_B, 1000ms, 800ms); - - // Fly - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in - ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. - - pbf_move_left_joystick(context, 128, 0, 1125, 300); - - - // Leg 2 - ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); - ssf_press_left_joystick(context, 128, 0, 60, 250); - - // Jump - ssf_press_button(context, BUTTON_B, 1000ms, 800ms); - - // Fly - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in - ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. - - pbf_move_left_joystick(context, 128, 0, 250, 0); - pbf_move_left_joystick(context, 112, 0, 250, 0); - pbf_move_left_joystick(context, 128, 0, 752, 0); - pbf_move_left_joystick(context, 96, 0, 300, 0); - pbf_move_left_joystick(context, 128, 0, 630, 250); - -// context.wait_for_all_requests(); - - - // Leg 3 - ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); - ssf_press_left_joystick(context, 128, 0, 180, 550); - - // Fly - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in - ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. - - pbf_move_left_joystick(context, 48, 0, 200, 0); - pbf_move_left_joystick(context, 128, 0, 250, 0); - - -} - - - - -} -} -} +/* Area Zero + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_AreaZero.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +void inside_zero_gate_to_station( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + int station, // 1 - 4 + bool heal_at_station +){ + { + AdvanceDialogWatcher dialog(COLOR_GREEN); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 0); + }, + {dialog} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find warp circle.", + stream + ); + } + } + + + + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(60)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to warp to station after 60 seconds.", + stream + ); + } + + AdvanceDialogWatcher dialog(COLOR_GREEN); + ZeroGateWarpPromptWatcher prompt(COLOR_GREEN); + BlackScreenOverWatcher black_screen(COLOR_RED); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(5), + {dialog, prompt, black_screen} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: + stream.log("Detected dialog."); + pbf_press_button(context, BUTTON_A, 20, 30); + continue; + case 1: + stream.log("Detected prompt."); + prompt.move_cursor(info, stream, context, station - 1); + pbf_mash_button(context, BUTTON_A, 3 * TICKS_PER_SECOND); + continue; + case 2: + stream.log("Black screen is over. Arrive at station."); + break; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to find warp to station 2.", + stream + ); + } + + break; + } + context.wait_for_all_requests(); + context.wait_for(std::chrono::seconds(3)); + + if (heal_at_station){ + stream.log("Moving to bed to heal."); + pbf_move_left_joystick(context, 144, 0, 4 * TICKS_PER_SECOND, 0); + ssf_press_left_joystick(context, 255, 128, 0, 125); + bool healed = false; + while (true){ + AdvanceDialogWatcher dialog(COLOR_GREEN); + PromptDialogWatcher confirm(COLOR_GREEN); + BlackScreenOverWatcher black_screen(COLOR_RED); + OverworldWatcher overworld(stream.logger(), COLOR_BLUE); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(30), + {dialog, confirm, black_screen, overworld} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 1: + stream.log("Detected rest prompt."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 2: + stream.log("Done healing!"); + healed = true; + continue; + case 3: + stream.log("Detected overworld."); + if (healed){ + break; + }else{ + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + } + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Heal at station: No state detected after 30 seconds.", + stream + ); + } + break; + } + } + + stream.log("Exiting station. Waiting for black screen..."); + { + BlackScreenOverWatcher black_screen(COLOR_RED); + int ret = run_until( + stream, context, + [=](ProControllerContext& context){ + if (heal_at_station){ + pbf_move_left_joystick(context, 96, 255, 60 * TICKS_PER_SECOND, 0); + }else{ + pbf_move_left_joystick(context, 0, 255, 60 * TICKS_PER_SECOND, 0); + } + }, + {black_screen} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to exit station after 60 seconds.", + stream + ); + } + } + + stream.log("Exiting station. Waiting for overworld..."); + { + OverworldWatcher overworld(stream.logger(), COLOR_BLUE); + int ret = wait_until( + stream, context, std::chrono::seconds(30), + {overworld} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to load overworld after exiting station for 30 seconds.", + stream + ); + } + } +} + +void return_to_outside_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + open_map_from_overworld(info, stream, context); + pbf_move_left_joystick(context, 96, 96, 5, 50); + fly_to_overworld_from_map(info, stream, context); +} +void return_to_inside_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + return_to_outside_zero_gate(info, stream, context); + + BlackScreenOverWatcher black_screen; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 32, 20, 105); + pbf_mash_button(context, BUTTON_L, 60); + pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 0); + }, + {black_screen} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to enter Zero Gate.", + stream + ); + } + + OverworldWatcher overworld(stream.logger()); + ret = wait_until( + stream, context, std::chrono::seconds(10), + {overworld} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect overworld inside Zero Gate.", + stream + ); + } +} +void return_to_inside_zero_gate_from_picnic( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + BlackScreenOverWatcher black_screen; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 100, 40); + pbf_mash_button(context, BUTTON_L, 60); + pbf_move_left_joystick(context, 128, 0, 10 * TICKS_PER_SECOND, 0); + }, + {black_screen} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to enter Zero Gate.", + stream + ); + } + + OverworldWatcher overworld(stream.logger()); + ret = wait_until( + stream, context, std::chrono::seconds(10), + {overworld} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect overworld inside Zero Gate.", + stream + ); + } +} + + + + +void inside_zero_gate_to_secret_cave_entrance( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + bool heal_at_station +){ + inside_zero_gate_to_station(info, stream, context, 1, heal_at_station); + + context.wait_for(std::chrono::seconds(3)); + + pbf_move_left_joystick(context, 0, 208, 30, 50); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + + // Leg 1 + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); + ssf_press_left_joystick(context, 128, 0, 60, 1250); + + // Jump + ssf_press_button(context, BUTTON_B, 1000ms, 800ms); + + // Fly + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. + + pbf_move_left_joystick(context, 128, 0, 1125, 300); + + + // Leg 2 + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); + ssf_press_left_joystick(context, 128, 0, 60, 250); + + // Jump + ssf_press_button(context, BUTTON_B, 1000ms, 800ms); + + // Fly + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. + + pbf_move_left_joystick(context, 128, 0, 250, 0); + pbf_move_left_joystick(context, 112, 0, 250, 0); + pbf_move_left_joystick(context, 128, 0, 752, 0); + pbf_move_left_joystick(context, 96, 0, 300, 0); + pbf_move_left_joystick(context, 128, 0, 630, 250); + +// context.wait_for_all_requests(); + + + // Leg 3 + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); + ssf_press_left_joystick(context, 128, 0, 180, 550); + + // Fly + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. + + pbf_move_left_joystick(context, 48, 0, 200, 0); + pbf_move_left_joystick(context, 128, 0, 250, 0); + + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.h index 5927f66155..9ddfb0e3c7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_AreaZero.h @@ -1,59 +1,59 @@ -/* Area Zero - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AreaZero_H -#define PokemonAutomation_PokemonSV_AreaZero_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -// After just entering the Zero Gate, go to the specified station. -void inside_zero_gate_to_station( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - int station, // 1 - 4 - bool heal_at_station -); - -// You are inside Area Zero having traveled there via the Zero Gate. Return to -// the zero gate fly spot. -void return_to_outside_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// You are inside Area Zero having traveled there via the Zero Gate. Return to -// inside the zero gate to setup for a subsequent call to "inside_zero_gate_to_station()". -void return_to_inside_zero_gate( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); -void return_to_inside_zero_gate_from_picnic( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - - - -void inside_zero_gate_to_secret_cave_entrance( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool heal_at_station -); - - - -} -} -} -#endif +/* Area Zero + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AreaZero_H +#define PokemonAutomation_PokemonSV_AreaZero_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +// After just entering the Zero Gate, go to the specified station. +void inside_zero_gate_to_station( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + int station, // 1 - 4 + bool heal_at_station +); + +// You are inside Area Zero having traveled there via the Zero Gate. Return to +// the zero gate fly spot. +void return_to_outside_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// You are inside Area Zero having traveled there via the Zero Gate. Return to +// inside the zero gate to setup for a subsequent call to "inside_zero_gate_to_station()". +void return_to_inside_zero_gate( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); +void return_to_inside_zero_gate_from_picnic( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + + + +void inside_zero_gate_to_secret_cave_entrance( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool heal_at_station +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.cpp index 6909ec113f..d46063e6c7 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.cpp @@ -1,221 +1,221 @@ -/* Connect to Integer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_ConnectToInternet.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class NewsDetector : public StaticScreenDetector{ -public: - NewsDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom_white; - ImageFloatBox m_bottom_buttons; -}; -NewsDetector::NewsDetector(Color color) - : m_color(color) - , m_bottom_white(0.15, 0.92, 0.20, 0.06) - , m_bottom_buttons(0.40, 0.92, 0.58, 0.06) -{} -void NewsDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom_white); - items.add(m_color, m_bottom_buttons); -} -bool NewsDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom_white = image_stats(extract_box_reference(screen, m_bottom_white)); - if (!is_white(bottom_white)){ - return false; - } - - ImageStats bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); -// cout << bottom_buttons.average << bottom_buttons.stddev << endl; - if (bottom_buttons.stddev.sum() < 100){ - return false; - } - - return true; -} -class NewsWatcher : public DetectorToFinder{ -public: - NewsWatcher(Color color = COLOR_RED) - : DetectorToFinder("NewsWatcher", std::chrono::milliseconds(1000), color) - {} -}; - - - - -void connect_to_internet_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - WallClock start = current_time(); - bool connected = false; - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "connect_to_internet_from_menu(): Failed to connect to internet after 5 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - MainMenuWatcher main_menu(COLOR_YELLOW); - AdvanceDialogWatcher dialog(COLOR_GREEN); - PromptDialogWatcher prompt(COLOR_CYAN); - NewsWatcher news(COLOR_BLUE); - NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {overworld, main_menu, dialog, prompt, news, battle_menu} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld. (unexpected)", COLOR_RED); - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - case 1: - stream.log("Detected main menu."); - if (connected){ - return; - }else{ - pbf_press_button(context, BUTTON_L, 20, 105); - } - continue; - case 2: - stream.log("Detected dialog."); - connected = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 3: - stream.log("Already connected to internet."); - connected = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 4: - stream.log("Detected news menu..."); - connected = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 5: - stream.log("Detected battle menu..."); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "connect_to_internet_from_menu(): Looks like you got attacked.", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "connect_to_internet_from_menu(): No recognized state after 60 seconds.", - stream - ); - } - } -} -void connect_to_internet_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - WallClock start = current_time(); - bool connected = false; - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "connect_to_internet_from_overworld(): Failed to connect to internet after 5 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - MainMenuWatcher main_menu(COLOR_YELLOW); - AdvanceDialogWatcher dialog(COLOR_GREEN); - PromptDialogWatcher prompt(COLOR_CYAN); - NewsWatcher news(COLOR_BLUE); - NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {overworld, main_menu, dialog, prompt, news, battle_menu} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld."); - if (connected){ - return; - }else{ - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - } - case 1: - stream.log("Detected main menu."); - if (connected){ - pbf_press_button(context, BUTTON_B, 20, 105); - }else{ - pbf_press_button(context, BUTTON_L, 20, 105); - } - continue; - case 2: - stream.log("Detected dialog."); - connected = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 3: - stream.log("Already connected to internet."); - connected = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 4: - stream.log("Detected news menu..."); - connected = true; - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 5: - stream.log("Detected battle menu..."); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "connect_to_internet_from_overworld(): Looks like you got attacked.", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "connect_to_internet_from_overworld(): No recognized state after 60 seconds.", - stream - ); - } - } -} - - - - -} -} -} +/* Connect to Integer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_ConnectToInternet.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class NewsDetector : public StaticScreenDetector{ +public: + NewsDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom_white; + ImageFloatBox m_bottom_buttons; +}; +NewsDetector::NewsDetector(Color color) + : m_color(color) + , m_bottom_white(0.15, 0.92, 0.20, 0.06) + , m_bottom_buttons(0.40, 0.92, 0.58, 0.06) +{} +void NewsDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom_white); + items.add(m_color, m_bottom_buttons); +} +bool NewsDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom_white = image_stats(extract_box_reference(screen, m_bottom_white)); + if (!is_white(bottom_white)){ + return false; + } + + ImageStats bottom_buttons = image_stats(extract_box_reference(screen, m_bottom_buttons)); +// cout << bottom_buttons.average << bottom_buttons.stddev << endl; + if (bottom_buttons.stddev.sum() < 100){ + return false; + } + + return true; +} +class NewsWatcher : public DetectorToFinder{ +public: + NewsWatcher(Color color = COLOR_RED) + : DetectorToFinder("NewsWatcher", std::chrono::milliseconds(1000), color) + {} +}; + + + + +void connect_to_internet_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + WallClock start = current_time(); + bool connected = false; + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "connect_to_internet_from_menu(): Failed to connect to internet after 5 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + MainMenuWatcher main_menu(COLOR_YELLOW); + AdvanceDialogWatcher dialog(COLOR_GREEN); + PromptDialogWatcher prompt(COLOR_CYAN); + NewsWatcher news(COLOR_BLUE); + NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {overworld, main_menu, dialog, prompt, news, battle_menu} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld. (unexpected)", COLOR_RED); + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + case 1: + stream.log("Detected main menu."); + if (connected){ + return; + }else{ + pbf_press_button(context, BUTTON_L, 20, 105); + } + continue; + case 2: + stream.log("Detected dialog."); + connected = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 3: + stream.log("Already connected to internet."); + connected = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 4: + stream.log("Detected news menu..."); + connected = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 5: + stream.log("Detected battle menu..."); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "connect_to_internet_from_menu(): Looks like you got attacked.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "connect_to_internet_from_menu(): No recognized state after 60 seconds.", + stream + ); + } + } +} +void connect_to_internet_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + WallClock start = current_time(); + bool connected = false; + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "connect_to_internet_from_overworld(): Failed to connect to internet after 5 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + MainMenuWatcher main_menu(COLOR_YELLOW); + AdvanceDialogWatcher dialog(COLOR_GREEN); + PromptDialogWatcher prompt(COLOR_CYAN); + NewsWatcher news(COLOR_BLUE); + NormalBattleMenuWatcher battle_menu(COLOR_MAGENTA); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {overworld, main_menu, dialog, prompt, news, battle_menu} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld."); + if (connected){ + return; + }else{ + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + } + case 1: + stream.log("Detected main menu."); + if (connected){ + pbf_press_button(context, BUTTON_B, 20, 105); + }else{ + pbf_press_button(context, BUTTON_L, 20, 105); + } + continue; + case 2: + stream.log("Detected dialog."); + connected = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 3: + stream.log("Already connected to internet."); + connected = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 4: + stream.log("Detected news menu..."); + connected = true; + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 5: + stream.log("Detected battle menu..."); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "connect_to_internet_from_overworld(): Looks like you got attacked.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "connect_to_internet_from_overworld(): No recognized state after 60 seconds.", + stream + ); + } + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.h index 601c942104..5a267e5be2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_ConnectToInternet.h @@ -1,30 +1,30 @@ -/* Connect to Integer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ConnectToInternet_H -#define PokemonAutomation_PokemonSV_ConnectToInternet_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Connect to internet from the main menu. Stay in the main menu. -void connect_to_internet_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// Connect to internet from the overworld. Return to the overworld. -void connect_to_internet_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - - -} -} -} -#endif +/* Connect to Integer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ConnectToInternet_H +#define PokemonAutomation_PokemonSV_ConnectToInternet_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Connect to internet from the main menu. Stay in the main menu. +void connect_to_internet_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// Connect to internet from the overworld. Return to the overworld. +void connect_to_internet_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.cpp index d60ccd5b3b..ec5ae442e8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.cpp @@ -1,191 +1,191 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV_GameEntry.h" - - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class WaitforWhiteLoadScreen : public VisualInferenceCallback{ -public: - WaitforWhiteLoadScreen(bool invert) - : VisualInferenceCallback("LoadingDetector") - , m_box0(0.2, 0.2, 0.6, 0.1) - , m_box1(0.2, 0.7, 0.6, 0.1) - , m_invert(invert) - {} - - virtual void make_overlays(VideoOverlaySet& items) const override{ - items.add(COLOR_RED, m_box0); - items.add(COLOR_RED, m_box1); - } - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - if (!is_white(extract_box_reference(frame, m_box0))){ - return m_invert; - } - if (!is_white(extract_box_reference(frame, m_box1))){ - return m_invert; - } - return !m_invert; - } - -private: - ImageFloatBox m_box0; - ImageFloatBox m_box1; - bool m_invert; -}; - - -bool reset_game_to_gamemenu(ConsoleHandle& console, ProControllerContext& context){ - close_game(console, context); - start_game_from_home( - console, context, - true, - 0, 0, - GameSettings::instance().START_GAME_MASH0 - ); - - Milliseconds timeout = GameSettings::instance().START_GAME_WAIT0; - - { - console.log("Waiting to load game..."); - WaitforWhiteLoadScreen detector(false); - int ret = wait_until( - console, context, - timeout, - {{detector}} - ); - if (ret < 0){ - console.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } - } - { - console.log("Waiting for game menu..."); - WaitforWhiteLoadScreen detector(true); - int ret = wait_until( - console, context, - timeout, - {{detector}} - ); - if (ret < 0){ - console.log("Timed out waiting for game menu.", COLOR_RED); - return false; - } - } - -// // Now the game has opened: -// return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT); - return true; -} - -bool gamemenu_to_ingame(VideoStream& stream, ProControllerContext& context){ - stream.log("Mashing A to enter game..."); - BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); - pbf_mash_button(context, BUTTON_A, GameSettings::instance().ENTER_GAME_MASH0); - context.wait_for_all_requests(); - stream.log("Waiting to enter game..."); - int ret = wait_until( - stream, context, - GameSettings::instance().ENTER_GAME_WAIT0, - {{detector}} - ); - if (ret == 0){ - stream.log("Entered game!"); - return true; - }else{ - stream.log("Timed out waiting to enter game.", COLOR_RED); - return false; - } -} - -bool reset_game_from_home( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - uint16_t post_wait_time -){ - console.log("Resetting game from home..."); - console.overlay().add_log("Reset game", COLOR_WHITE); - bool ok = true; - ok &= reset_game_to_gamemenu(console, context); - ok &= gamemenu_to_ingame(console, context); - if (!ok){ - dump_image(console.logger(), info, console.video(), "StartGame"); - } - console.log("Entered game! Waiting out grace period."); - pbf_wait(context, post_wait_time); - context.wait_for_all_requests(); - return ok; -} -bool reset_game_from_home_zoom_out( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - uint16_t post_wait_time -){ - bool ret = reset_game_from_home(info, console, context, post_wait_time); - - // 5 zooms will guarantee that are fully zoomed out regardless of whether - // we are on the DLC update. - pbf_press_button(context, BUTTON_RCLICK, 20, 105); - pbf_press_button(context, BUTTON_RCLICK, 20, 105); - pbf_press_button(context, BUTTON_RCLICK, 20, 105); - pbf_press_button(context, BUTTON_RCLICK, 20, 105); - pbf_press_button(context, BUTTON_RCLICK, 20, 105); - - return ret; -} - -void reset_game( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context -){ - try{ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - context.wait_for_all_requests(); - if (!reset_game_from_home(info, console, context, 5 * TICKS_PER_SECOND)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to start game.", - console - ); - } - }catch (OperationFailedException& e){ - // To be safe: avoid doing anything outside of game on Switch, - // make game resetting non error recoverable - throw FatalProgramException(std::move(e)); - } -} - - - - - - -} -} -} +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV_GameEntry.h" + + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class WaitforWhiteLoadScreen : public VisualInferenceCallback{ +public: + WaitforWhiteLoadScreen(bool invert) + : VisualInferenceCallback("LoadingDetector") + , m_box0(0.2, 0.2, 0.6, 0.1) + , m_box1(0.2, 0.7, 0.6, 0.1) + , m_invert(invert) + {} + + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(COLOR_RED, m_box0); + items.add(COLOR_RED, m_box1); + } + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + if (!is_white(extract_box_reference(frame, m_box0))){ + return m_invert; + } + if (!is_white(extract_box_reference(frame, m_box1))){ + return m_invert; + } + return !m_invert; + } + +private: + ImageFloatBox m_box0; + ImageFloatBox m_box1; + bool m_invert; +}; + + +bool reset_game_to_gamemenu(ConsoleHandle& console, ProControllerContext& context){ + close_game(console, context); + start_game_from_home( + console, context, + true, + 0, 0, + GameSettings::instance().START_GAME_MASH0 + ); + + Milliseconds timeout = GameSettings::instance().START_GAME_WAIT0; + + { + console.log("Waiting to load game..."); + WaitforWhiteLoadScreen detector(false); + int ret = wait_until( + console, context, + timeout, + {{detector}} + ); + if (ret < 0){ + console.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } + } + { + console.log("Waiting for game menu..."); + WaitforWhiteLoadScreen detector(true); + int ret = wait_until( + console, context, + timeout, + {{detector}} + ); + if (ret < 0){ + console.log("Timed out waiting for game menu.", COLOR_RED); + return false; + } + } + +// // Now the game has opened: +// return openedgame_to_gamemenu(console, context, GameSettings::instance().START_GAME_WAIT); + return true; +} + +bool gamemenu_to_ingame(VideoStream& stream, ProControllerContext& context){ + stream.log("Mashing A to enter game..."); + BlackScreenOverWatcher detector(COLOR_RED, {0.2, 0.2, 0.6, 0.6}); + pbf_mash_button(context, BUTTON_A, GameSettings::instance().ENTER_GAME_MASH0); + context.wait_for_all_requests(); + stream.log("Waiting to enter game..."); + int ret = wait_until( + stream, context, + GameSettings::instance().ENTER_GAME_WAIT0, + {{detector}} + ); + if (ret == 0){ + stream.log("Entered game!"); + return true; + }else{ + stream.log("Timed out waiting to enter game.", COLOR_RED); + return false; + } +} + +bool reset_game_from_home( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + uint16_t post_wait_time +){ + console.log("Resetting game from home..."); + console.overlay().add_log("Reset game", COLOR_WHITE); + bool ok = true; + ok &= reset_game_to_gamemenu(console, context); + ok &= gamemenu_to_ingame(console, context); + if (!ok){ + dump_image(console.logger(), info, console.video(), "StartGame"); + } + console.log("Entered game! Waiting out grace period."); + pbf_wait(context, post_wait_time); + context.wait_for_all_requests(); + return ok; +} +bool reset_game_from_home_zoom_out( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + uint16_t post_wait_time +){ + bool ret = reset_game_from_home(info, console, context, post_wait_time); + + // 5 zooms will guarantee that are fully zoomed out regardless of whether + // we are on the DLC update. + pbf_press_button(context, BUTTON_RCLICK, 20, 105); + pbf_press_button(context, BUTTON_RCLICK, 20, 105); + pbf_press_button(context, BUTTON_RCLICK, 20, 105); + pbf_press_button(context, BUTTON_RCLICK, 20, 105); + pbf_press_button(context, BUTTON_RCLICK, 20, 105); + + return ret; +} + +void reset_game( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context +){ + try{ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + context.wait_for_all_requests(); + if (!reset_game_from_home(info, console, context, 5 * TICKS_PER_SECOND)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to start game.", + console + ); + } + }catch (OperationFailedException& e){ + // To be safe: avoid doing anything outside of game on Switch, + // make game resetting non error recoverable + throw FatalProgramException(std::move(e)); + } +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.h index b89124d671..975e939213 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_GameEntry.h @@ -1,60 +1,60 @@ -/* Game Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_GameEntry_H -#define PokemonAutomation_PokemonSV_GameEntry_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -// From Switch Home menu, reset game and wait until the game menu screen (where -// "Press A" is displayed to enter the game) is shown. -bool reset_game_to_gamemenu(ConsoleHandle& console, ProControllerContext& context); - -// From the game menu screen (where "Press A" is displayed to enter the game), -// mash A to enter the game and wait until the black screen is gone. -bool gamemenu_to_ingame(VideoStream& stream, ProControllerContext& context); - -// From Switch Home menu, start game and wait until the player character appears in game. -// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. -// Return whether it successfully enters the game -bool reset_game_from_home( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - uint16_t post_wait_time = 125 -); -bool reset_game_from_home_zoom_out( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context, - uint16_t post_wait_time = 125 -); - -// From within the game, reset the game. -// Will throw FatalProgramException if it fails to enter the game. -void reset_game( - const ProgramInfo& info, - ConsoleHandle& console, ProControllerContext& context -); - - - - - - -} -} -} -#endif +/* Game Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_GameEntry_H +#define PokemonAutomation_PokemonSV_GameEntry_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +// From Switch Home menu, reset game and wait until the game menu screen (where +// "Press A" is displayed to enter the game) is shown. +bool reset_game_to_gamemenu(ConsoleHandle& console, ProControllerContext& context); + +// From the game menu screen (where "Press A" is displayed to enter the game), +// mash A to enter the game and wait until the black screen is gone. +bool gamemenu_to_ingame(VideoStream& stream, ProControllerContext& context); + +// From Switch Home menu, start game and wait until the player character appears in game. +// post_wait_time: how many ticks to wait after the black screen (shown when loading the map) is over. +// Return whether it successfully enters the game +bool reset_game_from_home( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + uint16_t post_wait_time = 125 +); +bool reset_game_from_home_zoom_out( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context, + uint16_t post_wait_time = 125 +); + +// From within the game, reset the game. +// Will throw FatalProgramException if it fails to enter the game. +void reset_game( + const ProgramInfo& info, + ConsoleHandle& console, ProControllerContext& context +); + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp index 52a8d0abab..1462137330 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.cpp @@ -1,764 +1,764 @@ -/* PokemonSV World Navigation - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/UnexpectedBattleException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Map/PokemonSV_MapDetector.h" -#include "PokemonSV/Inference/PokemonSV_BagDetector.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV_ConnectToInternet.h" -#include "PokemonSV_MenuNavigation.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -void set_time_to_12am_from_home(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ - DateReader reader (console); - VideoOverlaySet overlays(console.overlay()); - reader.make_overlays(overlays); - -// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY); - home_to_date_time(console, context, true); - pbf_press_button(context, BUTTON_A, 20, 50); - - context.wait_for_all_requests(); - - DateTime time = reader.read_date(console, console.video().snapshot()).second; - time.hour = 0; - reader.set_date(info, console, context, time); -// reader.set_hours(info, console, context, 0); - - pbf_press_button(context, BUTTON_A, 20, 30); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); -// resume_game_from_home(console, context); -} - -void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(console, context, true); - - Milliseconds tv = context->timing_variation(); - if (tv == 0ms){ - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll(context, DPAD_LEFT, 0ms, 48ms, 24ms); - - ssf_press_button(context, BUTTON_A, 24ms); - ssf_issue_scroll(context, DPAD_RIGHT, 24ms); - ssf_issue_scroll(context, DPAD_RIGHT, 24ms); - ssf_press_button(context, BUTTON_A, 0ms); - ssf_issue_scroll(context, DPAD_RIGHT, 24ms); - ssf_issue_scroll(context, DPAD_RIGHT, 24ms); - ssf_issue_scroll(context, DPAD_RIGHT, 24ms); - ssf_issue_scroll(context, DPAD_RIGHT, 0ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 160ms, 80ms); - }else{ - ssf_press_button_ptv(context, BUTTON_A, 160ms); - - // Left scroll in case we missed the date menu and landed in the - // language change. - ssf_issue_scroll_ptv(context, DPAD_LEFT); - - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - ssf_press_button_ptv(context, BUTTON_A); - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 160ms); - } - - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(console, context); -} - -void press_Bs_to_back_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, uint16_t seconds_between_b_presses){ - context.wait_for_all_requests(); - OverworldWatcher overworld(stream.logger(), COLOR_RED); - NormalBattleMenuWatcher battle(COLOR_BLUE); - int ret = run_until( - stream, context, - [seconds_between_b_presses](ProControllerContext& context){ - pbf_wait(context, seconds_between_b_presses * TICKS_PER_SECOND); // avoiding pressing B if already in overworld - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, BUTTON_B, 20, seconds_between_b_presses * TICKS_PER_SECOND); - } - }, - {overworld, battle} - ); - if (ret == 1){ - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "press_Bs_to_back_to_overworld(): Unexpectedly detected battle.", - stream - ); - }else if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "press_Bs_to_back_to_overworld(): Unable to detect overworld after 10 button B presses.", - stream - ); - } -} - -void open_map_from_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - bool clear_tutorial -){ - { - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - NormalBattleMenuWatcher battle(COLOR_RED); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(10), - {overworld, battle} - ); - context.wait_for(std::chrono::milliseconds(100)); - if (ret == 0){ - stream.log("Detected overworld."); - pbf_press_button(context, BUTTON_Y, 20, 105); // open map - }else if (ret == 1){ - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "open_map_from_overworld(): Unexpectedly detected battle.", - stream - ); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "open_map_from_overworld(): No overworld state found after 10 seconds.", - stream - ); - } - } - - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(2)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "open_map_from_overworld(): Failed to open map after 2 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - AdvanceDialogWatcher advance_dialog(COLOR_YELLOW); - PromptDialogWatcher prompt_dialog(COLOR_GREEN); - MapWatcher map(COLOR_RED); - NormalBattleMenuWatcher battle(COLOR_RED); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {overworld, advance_dialog, prompt_dialog, map, battle} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld."); - pbf_press_button(context, BUTTON_Y, 20, 105); // open map - continue; - case 1: - stream.log("Detected dialog. Did you fall down?", COLOR_RED); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 2: - stream.log("Detected dialog. Did you fall down?", COLOR_RED); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 3: - stream.log("Detected map."); - stream.overlay().add_log("Map opened", COLOR_WHITE); - if (map.map_in_fixed_view()){ - return; - }else{ // click R joystick to change to fixed view - if (clear_tutorial){ - pbf_press_button(context, BUTTON_A, 20, 105); - } - stream.log("Map in rotate view, fix it"); - stream.overlay().add_log("Change map to fixed view", COLOR_WHITE); - pbf_press_button(context, BUTTON_RCLICK, 20, 105); - continue; - } - case 4: - stream.log("Detected battle."); - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "open_map_from_overworld(): Unexpectedly detected battle.", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "open_map_from_overworld(): No recognized state after 30 seconds.", - stream - ); - } - } -} - - -void enter_box_system_from_overworld( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - context.wait_for_all_requests(); - stream.log("Enter box system from overworld..."); - WallClock start = current_time(); - bool success = false; - while (true){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_box_system_from_overworld(): Failed to enter box system after 3 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - MainMenuWatcher main_menu(COLOR_RED); - GradientArrowWatcher box_slot_one(COLOR_BLUE, GradientArrowType::DOWN, {0.24, 0.16, 0.05, 0.09}); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {overworld, main_menu, box_slot_one} - ); - context.wait_for(std::chrono::milliseconds(100)); - const bool fast_mode = false; - switch (ret){ - case 0: - stream.log("Detected overworld."); - pbf_press_button(context, BUTTON_X, 20, 105); // open menu - continue; - case 1: - stream.log("Detected main menu."); - stream.overlay().add_log("Enter box", COLOR_WHITE); - success = main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 1, fast_mode); - if (success == false){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_box_system_from_overworld(): Cannot move menu cursor to Boxes.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 50); - continue; - case 2: - stream.log("Detected box."); - context.wait_for(std::chrono::milliseconds(200)); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_box_system_from_overworld(): No recognized state after 30 seconds.", - stream - ); - } - } -} - - -void leave_box_system_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Leave box system to overworld..."); - press_Bs_to_back_to_overworld(info, stream, context); -} - - -void open_pokedex_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Opening Pokédex..."); - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::seconds(30)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "open_pokedex_from_overworld(): Failed to open Pokédex after 30 seconds.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - WhiteButtonWatcher pokedex(COLOR_RED, WhiteButton::ButtonY, {0.800, 0.118, 0.030, 0.060}); - - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {overworld, pokedex} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - // Try opening the Pokédex if overworld is detected - pbf_press_button(context, BUTTON_MINUS, 20, 100); - continue; - case 1: - stream.log("Detected Pokédex."); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "open_pokedex_from_overworld(): No recognized state after 30 seconds.", - stream - ); - } - } -} - - -void open_recently_battled_from_pokedex(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Opening recently battled..."); - LetsGoKillWatcher menu(stream.logger(), COLOR_RED, true, {0.23, 0.23, 0.04, 0.20}); - context.wait_for_all_requests(); - - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t i = 0; i < 10; i++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - } - }, - {menu} - ); - if (ret == 0){ - stream.log("Detected Recently Battled menu icon."); - pbf_mash_button(context, BUTTON_A, 150); - pbf_wait(context, 200); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "open_recently_battled_from_pokedex(): Unknown state after 10 dpad down presses.", - stream - ); - } -} - - -void leave_phone_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Exiting to overworld from Rotom Phone..."); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - NormalBattleMenuWatcher battle(COLOR_BLUE); - GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::DOWN, {0.475, 0.465, 0.05, 0.085}); - context.wait_for_all_requests(); - - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_Y, 20, 1000); - } - }, - {overworld, battle, arrow} - ); - switch (ret){ - case 0: - return; - case 1: - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "leave_phone_to_overworld(): Unexpectedly detected battle.", - stream - ); - case 2: - stream.log("Stuck in battle status screen."); - pbf_mash_button(context, BUTTON_B, 200); - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "leave_phone_to_overworld(): Unexpectedly detected battle.", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "leave_phone_to_overworld(): Unknown state after 10 button Y presses.", - stream - ); - } -} - - -void mash_button_till_overworld( - VideoStream& stream, - ProControllerContext& context, - Button button, uint16_t seconds_run -){ - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - context.wait_for_all_requests(); - - int ret = run_until( - stream, context, - [button, seconds_run](ProControllerContext& context){ - ssf_mash1_button(context, button, seconds_run * TICKS_PER_SECOND); - pbf_wait(context, seconds_run * TICKS_PER_SECOND); - }, - {overworld} - ); - - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "mash_button_till_overworld(): Timed out, no recognized state found.", - stream - ); - } -} - -void enter_menu_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int menu_index, - MenuSide side, - bool has_minimap -){ - if (!has_minimap){ - pbf_press_button(context, BUTTON_X, 20, 105); - } - - WallClock start = current_time(); - bool success = false; - - while (true){ - if (current_time() - start > std::chrono::minutes(1)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_overworld(): Failed to enter specified menu after 1 minute.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - MainMenuWatcher main_menu(COLOR_RED); - NormalBattleMenuWatcher battle(COLOR_RED); - context.wait_for_all_requests(); - - int ret = run_until( - stream, context, - [has_minimap](ProControllerContext& context){ - for (int i = 0; i < 10; i++){ - pbf_wait(context, 3 * TICKS_PER_SECOND); - if (!has_minimap){ - // if no minimap, can't detect overworld, so repeatedly press X to cover for button drops - pbf_press_button(context, BUTTON_X, 20, 100); - } - } - }, - {overworld, main_menu, battle} - ); - context.wait_for(std::chrono::milliseconds(100)); - - const bool fast_mode = false; - switch (ret){ - case 0: - stream.log("Detected overworld."); - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - case 1: - stream.log("Detected main menu."); - if (menu_index == -1){ - return; - } - success = main_menu.move_cursor(info, stream, context, side, menu_index, fast_mode); - if (success == false){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_overworld(): Cannot move menu cursor to specified menu.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 105); - return; - case 2: - throw_and_log( - stream.logger(), ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_overworld(): Unexpectedly detected battle.", - stream - ); - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_overworld(): No recognized state after 30 seconds.", - stream - ); - } - } -} - -void enter_menu_from_box_system(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int menu_index, - MenuSide side -){ - WallClock start = current_time(); - bool success = false; - - while (true){ - if (current_time() - start > std::chrono::seconds(20)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_box_system(): Failed to enter specified menu after 20 seconds.", - stream - ); - } - - MainMenuWatcher main_menu(COLOR_RED); - context.wait_for_all_requests(); - - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - // repeatedly pressing B and waiting for three seconds - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_B, 200ms, 3s); - } - }, - {main_menu} - ); - - const bool fast_mode = false; - switch (ret){ - case 0: - stream.log("Detected main menu when going from box system to menu"); - if (menu_index == -1){ - return; - } - success = main_menu.move_cursor(info, stream, context, side, menu_index, fast_mode); - if (success == false){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_box_system(): Cannot move menu cursor to specified menu.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 105); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_box_system(): No recognized state after 30 seconds.", - stream - ); - } - } -} - - -void enter_menu_from_bag(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int menu_index, - MenuSide side -){ - WallClock start = current_time(); - bool success = false; - - while (true){ - if (current_time() - start > std::chrono::seconds(20)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_bag(): Failed to enter specified menu after 20 seconds.", - stream - ); - } - - MainMenuWatcher main_menu(COLOR_RED); - BagWatcher bag_watcher(BagWatcher::FinderType::PRESENT, COLOR_RED); - context.wait_for_all_requests(); - - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - // repeatedly pressing B and waiting for three seconds - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_B, 200ms, 3s); - } - }, - {main_menu, bag_watcher} - ); - - const bool fast_mode = false; - switch (ret){ - case 0: - stream.log("Detected main menu when going from box system to menu"); - if (menu_index == -1){ - return; - } - success = main_menu.move_cursor(info, stream, context, side, menu_index, fast_mode); - if (success == false){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_bag(): Cannot move menu cursor to specified menu.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 105); - return; - case 1: - stream.log("still on bag."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_menu_from_bag(): No recognized state after 30 seconds.", - stream - ); - } - } -} - - -void enter_bag_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - WallClock start = current_time(); - bool success = false; - stream.log("Entering bag from menu"); - - while (true){ - if (current_time() - start > std::chrono::seconds(20)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_bag_from_menu(): Failed to enter specified menu after 20 seconds.", - stream - ); - } - - MainMenuWatcher main_menu(COLOR_RED); - BagWatcher bag_watcher(BagWatcher::FinderType::PRESENT, COLOR_RED); - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - Seconds(5), - {main_menu, bag_watcher} - ); - - const bool fast_mode = false; - switch (ret){ - case 0: - stream.log("Detected main menu."); - success = main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 0, fast_mode); - if (success == false){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_bag_from_menu(): Cannot move menu cursor to specified menu.", - stream - ); - } - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 1: - stream.overlay().add_log("Enter bag"); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "enter_bag_from_menu(): No recognized state after 30 seconds.", - stream - ); - } - } -} - - -void press_button_until_gradient_arrow( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox box_area_to_check, - Button button, - GradientArrowType arrow_type -){ - GradientArrowWatcher arrow(COLOR_RED, arrow_type, box_area_to_check); - int ret = run_until( - stream, context, - [button](ProControllerContext& context){ - pbf_wait(context, 3 * TICKS_PER_SECOND); // avoid pressing button if arrow already detected - for (size_t c = 0; c < 10; c++){ - pbf_press_button(context, button, 20, 3 * TICKS_PER_SECOND); - } - }, - {arrow} - ); - if (ret == 0){ - stream.log("Gradient arrow detected."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect gradient arrow.", - stream - ); - } -} - -void navigate_school_layout_menu( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox arrow_box_start, - ImageFloatBox arrow_box_end, - DpadPosition dpad_button, - uint16_t num_button_presses -){ - GradientArrowWatcher arrow_start(COLOR_RED, GradientArrowType::RIGHT, arrow_box_start); - - int ret = wait_until(stream, context, Milliseconds(5000), { arrow_start }); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "navigate_school_layout_menu: Failed to detect gradient arrow at expected start position.", - stream - ); - } - - for (uint16_t i = 0; i < num_button_presses; i++){ - pbf_press_dpad(context, dpad_button, 20, 105); - } - - GradientArrowWatcher arrow_end(COLOR_RED, GradientArrowType::RIGHT, arrow_box_end); - ret = run_until( - stream, - context, - [dpad_button](ProControllerContext& context){ - for (int i = 0; i < 3; i++){ - pbf_press_dpad(context, dpad_button, 20, 500); - } - }, - { arrow_end } - ); - - if (ret == 0){ - stream.log("navigate_school_layout_menu: Desired item selected."); - }else{ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "navigate_school_layout_menu: Failed to detect gradient arrow at expected end position.", - stream - ); - } -} - - - -} -} -} +/* PokemonSV World Navigation + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/UnexpectedBattleException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Map/PokemonSV_MapDetector.h" +#include "PokemonSV/Inference/PokemonSV_BagDetector.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV_ConnectToInternet.h" +#include "PokemonSV_MenuNavigation.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +void set_time_to_12am_from_home(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ + DateReader reader (console); + VideoOverlaySet overlays(console.overlay()); + reader.make_overlays(overlays); + +// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY); + home_to_date_time(console, context, true); + pbf_press_button(context, BUTTON_A, 20, 50); + + context.wait_for_all_requests(); + + DateTime time = reader.read_date(console, console.video().snapshot()).second; + time.hour = 0; + reader.set_date(info, console, context, time); +// reader.set_hours(info, console, context, 0); + + pbf_press_button(context, BUTTON_A, 20, 30); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); +// resume_game_from_home(console, context); +} + +void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(console, context, true); + + Milliseconds tv = context->timing_variation(); + if (tv == 0ms){ + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll(context, DPAD_LEFT, 0ms, 48ms, 24ms); + + ssf_press_button(context, BUTTON_A, 24ms); + ssf_issue_scroll(context, DPAD_RIGHT, 24ms); + ssf_issue_scroll(context, DPAD_RIGHT, 24ms); + ssf_press_button(context, BUTTON_A, 0ms); + ssf_issue_scroll(context, DPAD_RIGHT, 24ms); + ssf_issue_scroll(context, DPAD_RIGHT, 24ms); + ssf_issue_scroll(context, DPAD_RIGHT, 24ms); + ssf_issue_scroll(context, DPAD_RIGHT, 0ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 160ms, 80ms); + }else{ + ssf_press_button_ptv(context, BUTTON_A, 160ms); + + // Left scroll in case we missed the date menu and landed in the + // language change. + ssf_issue_scroll_ptv(context, DPAD_LEFT); + + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + ssf_press_button_ptv(context, BUTTON_A); + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 160ms); + } + + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(console, context); +} + +void press_Bs_to_back_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, uint16_t seconds_between_b_presses){ + context.wait_for_all_requests(); + OverworldWatcher overworld(stream.logger(), COLOR_RED); + NormalBattleMenuWatcher battle(COLOR_BLUE); + int ret = run_until( + stream, context, + [seconds_between_b_presses](ProControllerContext& context){ + pbf_wait(context, seconds_between_b_presses * TICKS_PER_SECOND); // avoiding pressing B if already in overworld + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, BUTTON_B, 20, seconds_between_b_presses * TICKS_PER_SECOND); + } + }, + {overworld, battle} + ); + if (ret == 1){ + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "press_Bs_to_back_to_overworld(): Unexpectedly detected battle.", + stream + ); + }else if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "press_Bs_to_back_to_overworld(): Unable to detect overworld after 10 button B presses.", + stream + ); + } +} + +void open_map_from_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + bool clear_tutorial +){ + { + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + NormalBattleMenuWatcher battle(COLOR_RED); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(10), + {overworld, battle} + ); + context.wait_for(std::chrono::milliseconds(100)); + if (ret == 0){ + stream.log("Detected overworld."); + pbf_press_button(context, BUTTON_Y, 20, 105); // open map + }else if (ret == 1){ + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "open_map_from_overworld(): Unexpectedly detected battle.", + stream + ); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "open_map_from_overworld(): No overworld state found after 10 seconds.", + stream + ); + } + } + + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(2)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "open_map_from_overworld(): Failed to open map after 2 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + AdvanceDialogWatcher advance_dialog(COLOR_YELLOW); + PromptDialogWatcher prompt_dialog(COLOR_GREEN); + MapWatcher map(COLOR_RED); + NormalBattleMenuWatcher battle(COLOR_RED); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {overworld, advance_dialog, prompt_dialog, map, battle} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld."); + pbf_press_button(context, BUTTON_Y, 20, 105); // open map + continue; + case 1: + stream.log("Detected dialog. Did you fall down?", COLOR_RED); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 2: + stream.log("Detected dialog. Did you fall down?", COLOR_RED); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 3: + stream.log("Detected map."); + stream.overlay().add_log("Map opened", COLOR_WHITE); + if (map.map_in_fixed_view()){ + return; + }else{ // click R joystick to change to fixed view + if (clear_tutorial){ + pbf_press_button(context, BUTTON_A, 20, 105); + } + stream.log("Map in rotate view, fix it"); + stream.overlay().add_log("Change map to fixed view", COLOR_WHITE); + pbf_press_button(context, BUTTON_RCLICK, 20, 105); + continue; + } + case 4: + stream.log("Detected battle."); + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "open_map_from_overworld(): Unexpectedly detected battle.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "open_map_from_overworld(): No recognized state after 30 seconds.", + stream + ); + } + } +} + + +void enter_box_system_from_overworld( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + context.wait_for_all_requests(); + stream.log("Enter box system from overworld..."); + WallClock start = current_time(); + bool success = false; + while (true){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_box_system_from_overworld(): Failed to enter box system after 3 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + MainMenuWatcher main_menu(COLOR_RED); + GradientArrowWatcher box_slot_one(COLOR_BLUE, GradientArrowType::DOWN, {0.24, 0.16, 0.05, 0.09}); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {overworld, main_menu, box_slot_one} + ); + context.wait_for(std::chrono::milliseconds(100)); + const bool fast_mode = false; + switch (ret){ + case 0: + stream.log("Detected overworld."); + pbf_press_button(context, BUTTON_X, 20, 105); // open menu + continue; + case 1: + stream.log("Detected main menu."); + stream.overlay().add_log("Enter box", COLOR_WHITE); + success = main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 1, fast_mode); + if (success == false){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_box_system_from_overworld(): Cannot move menu cursor to Boxes.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 50); + continue; + case 2: + stream.log("Detected box."); + context.wait_for(std::chrono::milliseconds(200)); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_box_system_from_overworld(): No recognized state after 30 seconds.", + stream + ); + } + } +} + + +void leave_box_system_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Leave box system to overworld..."); + press_Bs_to_back_to_overworld(info, stream, context); +} + + +void open_pokedex_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Opening Pokédex..."); + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::seconds(30)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "open_pokedex_from_overworld(): Failed to open Pokédex after 30 seconds.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + WhiteButtonWatcher pokedex(COLOR_RED, WhiteButton::ButtonY, {0.800, 0.118, 0.030, 0.060}); + + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {overworld, pokedex} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + // Try opening the Pokédex if overworld is detected + pbf_press_button(context, BUTTON_MINUS, 20, 100); + continue; + case 1: + stream.log("Detected Pokédex."); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "open_pokedex_from_overworld(): No recognized state after 30 seconds.", + stream + ); + } + } +} + + +void open_recently_battled_from_pokedex(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Opening recently battled..."); + LetsGoKillWatcher menu(stream.logger(), COLOR_RED, true, {0.23, 0.23, 0.04, 0.20}); + context.wait_for_all_requests(); + + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t i = 0; i < 10; i++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + } + }, + {menu} + ); + if (ret == 0){ + stream.log("Detected Recently Battled menu icon."); + pbf_mash_button(context, BUTTON_A, 150); + pbf_wait(context, 200); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "open_recently_battled_from_pokedex(): Unknown state after 10 dpad down presses.", + stream + ); + } +} + + +void leave_phone_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Exiting to overworld from Rotom Phone..."); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + NormalBattleMenuWatcher battle(COLOR_BLUE); + GradientArrowWatcher arrow(COLOR_RED, GradientArrowType::DOWN, {0.475, 0.465, 0.05, 0.085}); + context.wait_for_all_requests(); + + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_Y, 20, 1000); + } + }, + {overworld, battle, arrow} + ); + switch (ret){ + case 0: + return; + case 1: + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "leave_phone_to_overworld(): Unexpectedly detected battle.", + stream + ); + case 2: + stream.log("Stuck in battle status screen."); + pbf_mash_button(context, BUTTON_B, 200); + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "leave_phone_to_overworld(): Unexpectedly detected battle.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "leave_phone_to_overworld(): Unknown state after 10 button Y presses.", + stream + ); + } +} + + +void mash_button_till_overworld( + VideoStream& stream, + ProControllerContext& context, + Button button, uint16_t seconds_run +){ + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + context.wait_for_all_requests(); + + int ret = run_until( + stream, context, + [button, seconds_run](ProControllerContext& context){ + ssf_mash1_button(context, button, seconds_run * TICKS_PER_SECOND); + pbf_wait(context, seconds_run * TICKS_PER_SECOND); + }, + {overworld} + ); + + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "mash_button_till_overworld(): Timed out, no recognized state found.", + stream + ); + } +} + +void enter_menu_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int menu_index, + MenuSide side, + bool has_minimap +){ + if (!has_minimap){ + pbf_press_button(context, BUTTON_X, 20, 105); + } + + WallClock start = current_time(); + bool success = false; + + while (true){ + if (current_time() - start > std::chrono::minutes(1)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_overworld(): Failed to enter specified menu after 1 minute.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + MainMenuWatcher main_menu(COLOR_RED); + NormalBattleMenuWatcher battle(COLOR_RED); + context.wait_for_all_requests(); + + int ret = run_until( + stream, context, + [has_minimap](ProControllerContext& context){ + for (int i = 0; i < 10; i++){ + pbf_wait(context, 3 * TICKS_PER_SECOND); + if (!has_minimap){ + // if no minimap, can't detect overworld, so repeatedly press X to cover for button drops + pbf_press_button(context, BUTTON_X, 20, 100); + } + } + }, + {overworld, main_menu, battle} + ); + context.wait_for(std::chrono::milliseconds(100)); + + const bool fast_mode = false; + switch (ret){ + case 0: + stream.log("Detected overworld."); + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + case 1: + stream.log("Detected main menu."); + if (menu_index == -1){ + return; + } + success = main_menu.move_cursor(info, stream, context, side, menu_index, fast_mode); + if (success == false){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_overworld(): Cannot move menu cursor to specified menu.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 105); + return; + case 2: + throw_and_log( + stream.logger(), ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_overworld(): Unexpectedly detected battle.", + stream + ); + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_overworld(): No recognized state after 30 seconds.", + stream + ); + } + } +} + +void enter_menu_from_box_system(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int menu_index, + MenuSide side +){ + WallClock start = current_time(); + bool success = false; + + while (true){ + if (current_time() - start > std::chrono::seconds(20)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_box_system(): Failed to enter specified menu after 20 seconds.", + stream + ); + } + + MainMenuWatcher main_menu(COLOR_RED); + context.wait_for_all_requests(); + + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + // repeatedly pressing B and waiting for three seconds + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_B, 200ms, 3s); + } + }, + {main_menu} + ); + + const bool fast_mode = false; + switch (ret){ + case 0: + stream.log("Detected main menu when going from box system to menu"); + if (menu_index == -1){ + return; + } + success = main_menu.move_cursor(info, stream, context, side, menu_index, fast_mode); + if (success == false){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_box_system(): Cannot move menu cursor to specified menu.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 105); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_box_system(): No recognized state after 30 seconds.", + stream + ); + } + } +} + + +void enter_menu_from_bag(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int menu_index, + MenuSide side +){ + WallClock start = current_time(); + bool success = false; + + while (true){ + if (current_time() - start > std::chrono::seconds(20)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_bag(): Failed to enter specified menu after 20 seconds.", + stream + ); + } + + MainMenuWatcher main_menu(COLOR_RED); + BagWatcher bag_watcher(BagWatcher::FinderType::PRESENT, COLOR_RED); + context.wait_for_all_requests(); + + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + // repeatedly pressing B and waiting for three seconds + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_B, 200ms, 3s); + } + }, + {main_menu, bag_watcher} + ); + + const bool fast_mode = false; + switch (ret){ + case 0: + stream.log("Detected main menu when going from box system to menu"); + if (menu_index == -1){ + return; + } + success = main_menu.move_cursor(info, stream, context, side, menu_index, fast_mode); + if (success == false){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_bag(): Cannot move menu cursor to specified menu.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 105); + return; + case 1: + stream.log("still on bag."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_menu_from_bag(): No recognized state after 30 seconds.", + stream + ); + } + } +} + + +void enter_bag_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + WallClock start = current_time(); + bool success = false; + stream.log("Entering bag from menu"); + + while (true){ + if (current_time() - start > std::chrono::seconds(20)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_bag_from_menu(): Failed to enter specified menu after 20 seconds.", + stream + ); + } + + MainMenuWatcher main_menu(COLOR_RED); + BagWatcher bag_watcher(BagWatcher::FinderType::PRESENT, COLOR_RED); + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + Seconds(5), + {main_menu, bag_watcher} + ); + + const bool fast_mode = false; + switch (ret){ + case 0: + stream.log("Detected main menu."); + success = main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 0, fast_mode); + if (success == false){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_bag_from_menu(): Cannot move menu cursor to specified menu.", + stream + ); + } + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 1: + stream.overlay().add_log("Enter bag"); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "enter_bag_from_menu(): No recognized state after 30 seconds.", + stream + ); + } + } +} + + +void press_button_until_gradient_arrow( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox box_area_to_check, + Button button, + GradientArrowType arrow_type +){ + GradientArrowWatcher arrow(COLOR_RED, arrow_type, box_area_to_check); + int ret = run_until( + stream, context, + [button](ProControllerContext& context){ + pbf_wait(context, 3 * TICKS_PER_SECOND); // avoid pressing button if arrow already detected + for (size_t c = 0; c < 10; c++){ + pbf_press_button(context, button, 20, 3 * TICKS_PER_SECOND); + } + }, + {arrow} + ); + if (ret == 0){ + stream.log("Gradient arrow detected."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect gradient arrow.", + stream + ); + } +} + +void navigate_school_layout_menu( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox arrow_box_start, + ImageFloatBox arrow_box_end, + DpadPosition dpad_button, + uint16_t num_button_presses +){ + GradientArrowWatcher arrow_start(COLOR_RED, GradientArrowType::RIGHT, arrow_box_start); + + int ret = wait_until(stream, context, Milliseconds(5000), { arrow_start }); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "navigate_school_layout_menu: Failed to detect gradient arrow at expected start position.", + stream + ); + } + + for (uint16_t i = 0; i < num_button_presses; i++){ + pbf_press_dpad(context, dpad_button, 20, 105); + } + + GradientArrowWatcher arrow_end(COLOR_RED, GradientArrowType::RIGHT, arrow_box_end); + ret = run_until( + stream, + context, + [dpad_button](ProControllerContext& context){ + for (int i = 0; i < 3; i++){ + pbf_press_dpad(context, dpad_button, 20, 500); + } + }, + { arrow_end } + ); + + if (ret == 0){ + stream.log("navigate_school_layout_menu: Desired item selected."); + }else{ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "navigate_school_layout_menu: Failed to detect gradient arrow at expected end position.", + stream + ); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.h index 453a14bd71..198327b8f3 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_MenuNavigation.h @@ -1,121 +1,121 @@ -/* PokemonSV Menu Navigation - * - * From: https://github.com/PokemonAutomation/ - * - * Move between different game menu states: overworld, menu, box system, etc. - * The location of the player charater in the overworld is not moved - */ - -#ifndef PokemonAutomation_PokemonSV_MenuNavigation_H -#define PokemonAutomation_PokemonSV_MenuNavigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" - - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -void set_time_to_12am_from_home(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); - -// Perform a No-op day skip that rolls over all the outbreaks and raids. -void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& context); - -// Press B to return to the overworld -void press_Bs_to_back_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - uint16_t seconds_between_b_presses = 3); - -// mashes A button by default -void mash_button_till_overworld( - VideoStream& stream, - ProControllerContext& context, - Button button = BUTTON_A, - uint16_t seconds_run = 360 -); - -// From overworld, open map. Will change map view from rotated to fixed if not already fixed. -void open_map_from_overworld( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - bool clear_tutorial = false -); - -// Enter box system from overworld. -void enter_box_system_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From box system go to overworld. -void leave_box_system_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From overworld, open Pokédex. -void open_pokedex_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From Pokédex, open Recently Battled. -void open_recently_battled_from_pokedex(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From any of the rotom phone apps (Map/Pokédex/Profile) go to overworld. -void leave_phone_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// enter menu and move the cursor to the given side and index, then press the A button (without wait for A button to press) -// if menu_index is -1, return once the menu is detected. -void enter_menu_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int menu_index, - MenuSide side = MenuSide::RIGHT, - bool has_minimap = true -); - -// enter menu from box system and move the cursor to the given side and index, then press the A button (without wait for A -// button to press) -// if menu_index is -1, return once the menu is detected. -void enter_menu_from_box_system(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int menu_index, - MenuSide side = MenuSide::NONE -); - -// enter menu from bag and move the cursor to the given side and index, then press the A button (without wait for A -// button to press) -// if menu_index is -1, return once the menu is detected. -void enter_menu_from_bag(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - int menu_index, - MenuSide side = MenuSide::NONE -); - -// enter bag from any place on the main menu -void enter_bag_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// press given button until gradient arrow appears in given box_area_to_check. -void press_button_until_gradient_arrow( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox box_area_to_check, - Button button = BUTTON_A, - GradientArrowType arrow_type = GradientArrowType::RIGHT -); - -// navigate school layout menu using only gradient arrow detection, without OCR -// first, wait for the gradient arrow to appear within `arrow_box_start`. -// then, press `dpad_button` a certain number of times, as per `num_button_presses`. -// then, watch for the gradient arrow within `arrow_box_end`. -// If arrow not seen, press `dpad_button` a maximum of 3 times, while still watching for the gradient arrow -// If arrow still not seen, throw exception. -void navigate_school_layout_menu( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - ImageFloatBox arrow_box_start, - ImageFloatBox arrow_box_end, - DpadPosition dpad_button, - uint16_t num_button_presses -); - - -} -} -} -#endif +/* PokemonSV Menu Navigation + * + * From: https://github.com/PokemonAutomation/ + * + * Move between different game menu states: overworld, menu, box system, etc. + * The location of the player charater in the overworld is not moved + */ + +#ifndef PokemonAutomation_PokemonSV_MenuNavigation_H +#define PokemonAutomation_PokemonSV_MenuNavigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" + + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +void set_time_to_12am_from_home(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); + +// Perform a No-op day skip that rolls over all the outbreaks and raids. +void day_skip_from_overworld(ConsoleHandle& console, ProControllerContext& context); + +// Press B to return to the overworld +void press_Bs_to_back_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + uint16_t seconds_between_b_presses = 3); + +// mashes A button by default +void mash_button_till_overworld( + VideoStream& stream, + ProControllerContext& context, + Button button = BUTTON_A, + uint16_t seconds_run = 360 +); + +// From overworld, open map. Will change map view from rotated to fixed if not already fixed. +void open_map_from_overworld( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + bool clear_tutorial = false +); + +// Enter box system from overworld. +void enter_box_system_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From box system go to overworld. +void leave_box_system_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From overworld, open Pokédex. +void open_pokedex_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From Pokédex, open Recently Battled. +void open_recently_battled_from_pokedex(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From any of the rotom phone apps (Map/Pokédex/Profile) go to overworld. +void leave_phone_to_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// enter menu and move the cursor to the given side and index, then press the A button (without wait for A button to press) +// if menu_index is -1, return once the menu is detected. +void enter_menu_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int menu_index, + MenuSide side = MenuSide::RIGHT, + bool has_minimap = true +); + +// enter menu from box system and move the cursor to the given side and index, then press the A button (without wait for A +// button to press) +// if menu_index is -1, return once the menu is detected. +void enter_menu_from_box_system(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int menu_index, + MenuSide side = MenuSide::NONE +); + +// enter menu from bag and move the cursor to the given side and index, then press the A button (without wait for A +// button to press) +// if menu_index is -1, return once the menu is detected. +void enter_menu_from_bag(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + int menu_index, + MenuSide side = MenuSide::NONE +); + +// enter bag from any place on the main menu +void enter_bag_from_menu(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// press given button until gradient arrow appears in given box_area_to_check. +void press_button_until_gradient_arrow( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox box_area_to_check, + Button button = BUTTON_A, + GradientArrowType arrow_type = GradientArrowType::RIGHT +); + +// navigate school layout menu using only gradient arrow detection, without OCR +// first, wait for the gradient arrow to appear within `arrow_box_start`. +// then, press `dpad_button` a certain number of times, as per `num_button_presses`. +// then, watch for the gradient arrow within `arrow_box_end`. +// If arrow not seen, press `dpad_button` a maximum of 3 times, while still watching for the gradient arrow +// If arrow still not seen, throw exception. +void navigate_school_layout_menu( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + ImageFloatBox arrow_box_start, + ImageFloatBox arrow_box_end, + DpadPosition dpad_button, + uint16_t num_button_presses +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.cpp index 51f993c64f..d529f83add 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.cpp @@ -1,153 +1,153 @@ -/* Save Game - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_SaveGame.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - -void save_game_from_menu( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - save_game_from_menu_or_overworld(info, stream, context, false); -} - -void save_game_from_overworld( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - save_game_from_menu_or_overworld(info, stream, context, true); -} - - - -void save_game_from_menu_or_overworld( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool return_to_overworld -){ - context.wait_for_all_requests(); - stream.log("Saving game..."); - stream.overlay().add_log("Save game", COLOR_YELLOW); - WallClock start = current_time(); - bool saved = false; - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "save_game_from_menu_or_overworld(): Failed to save game after 5 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - MainMenuWatcher menu(COLOR_RED); - GradientArrowWatcher confirmation(COLOR_YELLOW, GradientArrowType::RIGHT, {0.72, 0.55, 0.05, 0.08}); - AdvanceDialogWatcher finished(COLOR_GREEN); - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {overworld, menu, confirmation, finished} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld."); - if (saved && return_to_overworld){ - return; - } - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - case 1: - if (!saved){ - stream.log("Detected main menu. Saving game..."); - pbf_press_button(context, BUTTON_R, 20, 105); - continue; - } - if (return_to_overworld){ - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - } - return; - case 2: - stream.log("Detected save confirmation prompt."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 3: - stream.log("Detected save finished dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - saved = true; - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "save_game_from_menu_or_overworld(): No recognized state after 60 seconds.", - stream - ); - } - - - - - - } - -} - - -void save_game_tutorial( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - stream.log("Save game from tutorial. Open the menu."); - context.wait_for_all_requests(); - - // open the menu. - MainMenuWatcher menu(COLOR_RED); - int ret0 = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_wait(context, 500); // avoiding pressing X if menu already open - for (size_t i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_X, 20, 500); - } - }, - {menu} - ); - if (ret0 != 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to open menu!", - stream - ); - } - - save_game_from_menu(info, stream, context); - pbf_mash_button(context, BUTTON_B, 200); - -} - - - - -} -} -} +/* Save Game + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_SaveGame.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + +void save_game_from_menu( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + save_game_from_menu_or_overworld(info, stream, context, false); +} + +void save_game_from_overworld( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + save_game_from_menu_or_overworld(info, stream, context, true); +} + + + +void save_game_from_menu_or_overworld( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool return_to_overworld +){ + context.wait_for_all_requests(); + stream.log("Saving game..."); + stream.overlay().add_log("Save game", COLOR_YELLOW); + WallClock start = current_time(); + bool saved = false; + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "save_game_from_menu_or_overworld(): Failed to save game after 5 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + MainMenuWatcher menu(COLOR_RED); + GradientArrowWatcher confirmation(COLOR_YELLOW, GradientArrowType::RIGHT, {0.72, 0.55, 0.05, 0.08}); + AdvanceDialogWatcher finished(COLOR_GREEN); + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {overworld, menu, confirmation, finished} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld."); + if (saved && return_to_overworld){ + return; + } + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + case 1: + if (!saved){ + stream.log("Detected main menu. Saving game..."); + pbf_press_button(context, BUTTON_R, 20, 105); + continue; + } + if (return_to_overworld){ + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + } + return; + case 2: + stream.log("Detected save confirmation prompt."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 3: + stream.log("Detected save finished dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + saved = true; + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "save_game_from_menu_or_overworld(): No recognized state after 60 seconds.", + stream + ); + } + + + + + + } + +} + + +void save_game_tutorial( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + stream.log("Save game from tutorial. Open the menu."); + context.wait_for_all_requests(); + + // open the menu. + MainMenuWatcher menu(COLOR_RED); + int ret0 = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_wait(context, 500); // avoiding pressing X if menu already open + for (size_t i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_X, 20, 500); + } + }, + {menu} + ); + if (ret0 != 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to open menu!", + stream + ); + } + + save_game_from_menu(info, stream, context); + pbf_mash_button(context, BUTTON_B, 200); + +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.h index 5fd741e9a8..a1caf12cb0 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_SaveGame.h @@ -1,47 +1,47 @@ -/* Save Game - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SaveGame_H -#define PokemonAutomation_PokemonSV_SaveGame_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Save game from menu. -void save_game_from_menu( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// Save game from overworld. -void save_game_from_overworld( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// Save game from either menu or overworld. -void save_game_from_menu_or_overworld( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool return_to_overworld -); - -// Save game from overworld in the tutorial, where the minimap isn't available. -void save_game_tutorial( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -} -} -} -#endif +/* Save Game + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SaveGame_H +#define PokemonAutomation_PokemonSV_SaveGame_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Save game from menu. +void save_game_from_menu( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// Save game from overworld. +void save_game_from_overworld( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// Save game from either menu or overworld. +void save_game_from_menu_or_overworld( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool return_to_overworld +); + +// Save game from overworld in the tutorial, where the minimap isn't available. +void save_game_tutorial( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp index 60eaa3fb5c..a0baf0d63a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.cpp @@ -1,216 +1,216 @@ -/* Terarium - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV_Terarium.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -void return_to_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Attempting to return to Central Plaza."); - //Modified version of handle_battles_and_back_to_pokecenter() - bool returned_to_pokecenter = false; - bool laggy = false; - - while(!returned_to_pokecenter){ - EncounterWatcher encounter_watcher(stream, COLOR_RED); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - //Exit any dialogs (ex. Cyrano upgrading BBQs) - OverworldWatcher overworld(stream.logger(), COLOR_RED); - int ret_overworld = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10000); - }, - { overworld } - ); - if (ret_overworld == 0){ - stream.log("Overworld detected."); - } - context.wait_for_all_requests(); - - try{ - open_map_from_overworld(info, stream, context); - }catch (...){ - jump_off_wall_until_map_open(info, stream, context); - } - - //Move cursor to top left corner - even works when at Entrance fly point - pbf_press_button(context, BUTTON_ZL, 40, 100); - pbf_move_left_joystick(context, 0, 0, 500, 40); - - //Now move toward center - if (laggy){ - pbf_move_left_joystick(context, 255, 255, 300, 40); //overshoot by a bit (still works even if not laggy) - }else{ - pbf_move_left_joystick(context, 255, 255, 250, 40); //250 is more accurate but 300 helps with lag - } - pbf_press_button(context, BUTTON_ZR, 40, 100); - - try{ - //The only pokecenter on the map is Central Plaza - fly_to_closest_pokecenter_on_map(info, stream, context); - context.wait_for_all_requests(); - returned_to_pokecenter = true; - }catch(...){ - stream.log("Failed to return to Pokecenter. Closing map and retrying."); - laggy = true; - } - context.wait_for_all_requests(); - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - if (ret == 0){ - stream.log("Battle menu detected."); - encounter_watcher.throw_if_no_sound(); - - bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); - if (is_shiny){ - stream.log("Shiny detected!"); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - throw ProgramFinishedException(); - }else{ - stream.log("Detected battle. Running from battle."); - try{ - //Smoke Ball or Flying type required due to Arena Trap - NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); - battle_menu.move_to_slot(stream, context, 3); - pbf_press_button(context, BUTTON_A, 10, 50); - }catch (...){ - stream.log("Unable to flee."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to flee!", - stream - ); - } - } - } - } - context.wait_for_all_requests(); -} - -void map_move_cursor_fly( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t x, uint8_t y, - uint8_t hold, uint8_t release, - std::string location -){ - stream.log("Attempting to fly to " + location + "."); - - for (int i = 0; i < 3; i++){ - try{ - open_map_from_overworld(info, stream, context); - pbf_move_left_joystick(context, x, y, hold, release); - pbf_press_button(context, BUTTON_ZL, 40, 100); - fly_to_overworld_from_map(info, stream, context); - break; - } - catch(...){ - stream.log("Failed to fly! Closing map and retrying."); - press_Bs_to_back_to_overworld(info, stream, context); - if (i == 2){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to fly to " + location + "!", - stream - ); - } - } - } -} - -void central_to_polar_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 75, 0, 230, 20, "Polar Rest Area"); -} - -void central_to_polar_class1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 0, 20, 150, 20, "Polar Classroom 1"); -} - -void central_to_polar_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 20, 25, 245, 20, "Polar Plaza"); -} - -void central_to_coastal_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 180, 0, 210, 20, "Coastal Plaza"); -} - -void central_to_canyon_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 0, 255, 215, 20, "Canyon Plaza"); -} - -void central_to_savanna_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 165, 255, 180, 20, "Savanna Plaza"); -} - -void central_to_canyon_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 0, 140, 160, 20, "Canyon Rest Area"); -} - -void central_to_savanna_class(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 255, 220, 140, 20, "Savanna Classroom"); -} - -void central_to_chargestone(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - map_move_cursor_fly(info, stream, context, 0, 135, 130, 20, "Chargestone Cavern"); -} - -void jump_glide_fly( - VideoStream& stream, ProControllerContext& context, - bool inverted_flight, - uint16_t hold_up, - uint16_t flight_wait, - uint16_t drop_time -){ - stream.log("Jump, glide, fly."); - - ssf_press_button(context, BUTTON_B, 0ms, 800ms); - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); - ssf_press_button(context, BUTTON_B, 0ms, 160ms); - pbf_wait(context, 100); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_LCLICK, 50, 0); - - - if (inverted_flight){ - pbf_move_left_joystick(context, 128, 255, hold_up, 250); - }else{ - pbf_move_left_joystick(context, 128, 0, hold_up, 250); - } - - pbf_wait(context, flight_wait); - context.wait_for_all_requests(); - - pbf_press_button(context, BUTTON_B, 20, 50); - pbf_wait(context, drop_time); - context.wait_for_all_requests(); -} - -} -} -} +/* Terarium + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV_Terarium.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +void return_to_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Attempting to return to Central Plaza."); + //Modified version of handle_battles_and_back_to_pokecenter() + bool returned_to_pokecenter = false; + bool laggy = false; + + while(!returned_to_pokecenter){ + EncounterWatcher encounter_watcher(stream, COLOR_RED); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + //Exit any dialogs (ex. Cyrano upgrading BBQs) + OverworldWatcher overworld(stream.logger(), COLOR_RED); + int ret_overworld = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10000); + }, + { overworld } + ); + if (ret_overworld == 0){ + stream.log("Overworld detected."); + } + context.wait_for_all_requests(); + + try{ + open_map_from_overworld(info, stream, context); + }catch (...){ + jump_off_wall_until_map_open(info, stream, context); + } + + //Move cursor to top left corner - even works when at Entrance fly point + pbf_press_button(context, BUTTON_ZL, 40, 100); + pbf_move_left_joystick(context, 0, 0, 500, 40); + + //Now move toward center + if (laggy){ + pbf_move_left_joystick(context, 255, 255, 300, 40); //overshoot by a bit (still works even if not laggy) + }else{ + pbf_move_left_joystick(context, 255, 255, 250, 40); //250 is more accurate but 300 helps with lag + } + pbf_press_button(context, BUTTON_ZR, 40, 100); + + try{ + //The only pokecenter on the map is Central Plaza + fly_to_closest_pokecenter_on_map(info, stream, context); + context.wait_for_all_requests(); + returned_to_pokecenter = true; + }catch(...){ + stream.log("Failed to return to Pokecenter. Closing map and retrying."); + laggy = true; + } + context.wait_for_all_requests(); + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + if (ret == 0){ + stream.log("Battle menu detected."); + encounter_watcher.throw_if_no_sound(); + + bool is_shiny = (bool)encounter_watcher.shiny_screenshot(); + if (is_shiny){ + stream.log("Shiny detected!"); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + throw ProgramFinishedException(); + }else{ + stream.log("Detected battle. Running from battle."); + try{ + //Smoke Ball or Flying type required due to Arena Trap + NormalBattleMenuWatcher battle_menu(COLOR_YELLOW); + battle_menu.move_to_slot(stream, context, 3); + pbf_press_button(context, BUTTON_A, 10, 50); + }catch (...){ + stream.log("Unable to flee."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to flee!", + stream + ); + } + } + } + } + context.wait_for_all_requests(); +} + +void map_move_cursor_fly( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t x, uint8_t y, + uint8_t hold, uint8_t release, + std::string location +){ + stream.log("Attempting to fly to " + location + "."); + + for (int i = 0; i < 3; i++){ + try{ + open_map_from_overworld(info, stream, context); + pbf_move_left_joystick(context, x, y, hold, release); + pbf_press_button(context, BUTTON_ZL, 40, 100); + fly_to_overworld_from_map(info, stream, context); + break; + } + catch(...){ + stream.log("Failed to fly! Closing map and retrying."); + press_Bs_to_back_to_overworld(info, stream, context); + if (i == 2){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to fly to " + location + "!", + stream + ); + } + } + } +} + +void central_to_polar_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 75, 0, 230, 20, "Polar Rest Area"); +} + +void central_to_polar_class1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 0, 20, 150, 20, "Polar Classroom 1"); +} + +void central_to_polar_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 20, 25, 245, 20, "Polar Plaza"); +} + +void central_to_coastal_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 180, 0, 210, 20, "Coastal Plaza"); +} + +void central_to_canyon_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 0, 255, 215, 20, "Canyon Plaza"); +} + +void central_to_savanna_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 165, 255, 180, 20, "Savanna Plaza"); +} + +void central_to_canyon_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 0, 140, 160, 20, "Canyon Rest Area"); +} + +void central_to_savanna_class(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 255, 220, 140, 20, "Savanna Classroom"); +} + +void central_to_chargestone(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + map_move_cursor_fly(info, stream, context, 0, 135, 130, 20, "Chargestone Cavern"); +} + +void jump_glide_fly( + VideoStream& stream, ProControllerContext& context, + bool inverted_flight, + uint16_t hold_up, + uint16_t flight_wait, + uint16_t drop_time +){ + stream.log("Jump, glide, fly."); + + ssf_press_button(context, BUTTON_B, 0ms, 800ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); + ssf_press_button(context, BUTTON_B, 0ms, 160ms); + pbf_wait(context, 100); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_LCLICK, 50, 0); + + + if (inverted_flight){ + pbf_move_left_joystick(context, 128, 255, hold_up, 250); + }else{ + pbf_move_left_joystick(context, 128, 0, hold_up, 250); + } + + pbf_wait(context, flight_wait); + context.wait_for_all_requests(); + + pbf_press_button(context, BUTTON_B, 20, 50); + pbf_wait(context, drop_time); + context.wait_for_all_requests(); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.h index 152fc71e40..3adbfd14cb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_Terarium.h @@ -1,70 +1,70 @@ -/* Terarium - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_Terarium_H -#define PokemonAutomation_PokemonSV_Terarium_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Return to Central Plaza from anywhere in the terarium -void return_to_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// Open map from overworld, move cursor to fly location, and fly to location -void map_move_cursor_fly( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - uint8_t x, uint8_t y, - uint8_t hold, uint8_t release, - std::string location -); - -// From central plaza, fly to the polar rest area -void central_to_polar_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to polar outdoor classroom 1 -void central_to_polar_class1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to coastal plaza -void central_to_polar_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to coastal plaza -void central_to_coastal_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to canyon plaza -void central_to_canyon_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to savanna plaza -void central_to_savanna_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to canyon rest area -void central_to_canyon_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to savanna classroom. Warning: extremely laggy area. -void central_to_savanna_class(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// From central plaza, fly to chargestone cavern -void central_to_chargestone(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// Jump straight up into the air and fly. Fly up for hold_up ticks, fly straight for flight_wait ticks, and wait drop_time ticks to fall to the ground. -void jump_glide_fly( - VideoStream& stream, ProControllerContext& context, - bool inverted_flight, - uint16_t hold_up, - uint16_t flight_wait, - uint16_t drop_time -); - - -} -} -} -#endif +/* Terarium + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_Terarium_H +#define PokemonAutomation_PokemonSV_Terarium_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Return to Central Plaza from anywhere in the terarium +void return_to_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// Open map from overworld, move cursor to fly location, and fly to location +void map_move_cursor_fly( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + uint8_t x, uint8_t y, + uint8_t hold, uint8_t release, + std::string location +); + +// From central plaza, fly to the polar rest area +void central_to_polar_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to polar outdoor classroom 1 +void central_to_polar_class1(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to coastal plaza +void central_to_polar_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to coastal plaza +void central_to_coastal_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to canyon plaza +void central_to_canyon_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to savanna plaza +void central_to_savanna_plaza(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to canyon rest area +void central_to_canyon_rest(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to savanna classroom. Warning: extremely laggy area. +void central_to_savanna_class(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// From central plaza, fly to chargestone cavern +void central_to_chargestone(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// Jump straight up into the air and fly. Fly up for hold_up ticks, fly straight for flight_wait ticks, and wait drop_time ticks to fall to the ground. +void jump_glide_fly( + VideoStream& stream, ProControllerContext& context, + bool inverted_flight, + uint16_t hold_up, + uint16_t flight_wait, + uint16_t drop_time +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp index 218dc868db..328fd7314a 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.cpp @@ -1,667 +1,667 @@ -/* PokemonSV World Navigation - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/UnexpectedBattleException.h" -#include "CommonTools/Async/InferenceRoutines.h" -//#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -//#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -//#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -//#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Map/PokemonSV_MapDetector.h" -#include "PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h" -#include "PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV_ConnectToInternet.h" -#include "PokemonSV_WorldNavigation.h" - -#include -#include -#include -#include -#include -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -bool fly_to_overworld_from_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool check_fly_menuitem){ - context.wait_for_all_requests(); - // Press A to bring up the promp dialog on choosing "Fly here", "Set as destination", "Never mind". - pbf_press_button(context, BUTTON_A, 20, 130); - - WallClock start = current_time(); - while (true){ - if (current_time() - start > std::chrono::minutes(2)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "fly_to_overworld_from_map(): Failed to fly from map after 2 minutes.", - stream - ); - } - - int ret = 0; - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - WhiteButtonWatcher map(COLOR_RED, WhiteButton::ButtonY, {0.800, 0.118, 0.030, 0.060}); - GradientArrowWatcher spot_dialog_watcher(COLOR_YELLOW, GradientArrowType::RIGHT, {0.469, 0.500, 0.215, 0.150}); - PromptDialogWatcher confirm_watcher(COLOR_BLUE, {0.686, 0.494, 0.171, 0.163}); - MapFlyMenuWatcher flyMenuItemWatcher(COLOR_BLACK); - MapDestinationMenuWatcher destinationMenuItemWatcher(COLOR_BLACK); - - context.wait_for_all_requests(); - - std::vector callbacks{overworld, map, spot_dialog_watcher, confirm_watcher}; - if (check_fly_menuitem){ - callbacks[2] = flyMenuItemWatcher; - callbacks.push_back(destinationMenuItemWatcher); - } - - ret = wait_until(stream, context, std::chrono::minutes(2), callbacks); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld. Fly successful."); - return true; - case 1: - stream.log("Detected map. Pressing A to open map menu."); - // Press A to bring up the promp dialog on choosing "Fly here", "Set as destination", "Never mind". - pbf_press_button(context, BUTTON_A, 20, 130); - continue; - case 2: - stream.log("Detected fly here prompt dialog."); - stream.overlay().add_log("Fly"); - pbf_press_button(context, BUTTON_A, 20, 130); - continue; - case 3: - stream.log("Detected fly confirmation prompt."); - pbf_press_button(context, BUTTON_A, 20, 130); - continue; - case 4: - stream.log("Detected no fly spot here."); - stream.overlay().add_log("No fly spot", COLOR_RED); - return false; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "fly_to_overworld_from_map(): No recognized state after 2 minutes.", - stream - ); - } - } -} - - -void picnic_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Start picnic from overworld..."); - WallClock start = current_time(); - bool success = false; - while (true){ - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "picnic_from_overworld(): Failed to start picnic after 3 minutes.", - stream - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - MainMenuWatcher main_menu(COLOR_RED); - PicnicWatcher picnic; - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {overworld, main_menu, picnic} - ); - context.wait_for(std::chrono::milliseconds(100)); - const bool fast_mode = false; - switch (ret){ - case 0: - stream.log("Detected overworld."); - pbf_press_button(context, BUTTON_X, 20, 105); // open menu - continue; - case 1: - stream.log("Detected main menu."); - success = main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 2, fast_mode); - if (success == false){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "picnic_from_overworld(): Cannot move menu cursor to picnic.", - stream - ); - } - pbf_mash_button(context, BUTTON_A, 125); // mash button A to enter picnic mode - continue; - case 2: - stream.log("Detected picnic."); - stream.overlay().add_log("Start picnic", COLOR_WHITE); - // extra wait to make sure by the end the player can move. - // the player throwing out pokeballs animation is long. - pbf_wait(context, 1000); - context.wait_for_all_requests(); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "picnic_from_overworld(): No recognized state after 30 seconds.", - stream - ); - } - } -} - -void leave_picnic(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - context.wait_for_all_requests(); - stream.log("Leaving picnic..."); - stream.overlay().add_log("Leaving picnic", COLOR_WHITE); - - pbf_press_button(context, BUTTON_Y, 30, 100); - for(int i = 0; i < 5; i++){ - PromptDialogWatcher prompt(COLOR_RED, {0.595, 0.517, 0.273, 0.131}); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(5), - {prompt} - ); - - if (ret == 0){ - stream.log("Detected end picnic prompt"); - break; - } - - if (i == 4){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "leave_picnic(): Failed to leave picnic after 5 tries.", - stream - ); - } - - // prompt not found, maybe button Y dropped? - pbf_press_button(context, BUTTON_Y, 30, 100); - } - - // We have now the prompt to asking for confirmation of leaving picnic. - // Mash A to confirm - pbf_mash_button(context, BUTTON_A, 150); - context.wait_for_all_requests(); - - // Wait for overworld: - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret = wait_until( - stream, context, - std::chrono::seconds(20), - {overworld} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "leave_picnic(): Failed to detecxt overworld after 20 seconds.", - stream - ); - } - // Wait three more seconds to make sure the player character is free to operate: - context.wait_for(std::chrono::seconds(3)); -} - - -// While in the current map zoom level, detect pokecenter icons and move the map cursor there. -// Return true if succeed. Return false if no visible pokcenter on map -bool detect_closest_pokecenter_and_move_map_cursor_there( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double push_scale -){ - context.wait_for_all_requests(); - const auto snapshot_frame = stream.video().snapshot().frame; - const size_t screen_width = snapshot_frame->width(); - const size_t screen_height = snapshot_frame->height(); - - double closest_icon_x = 0., closest_icon_y = 0.; - double max_dist = DBL_MAX; - const double center_x = 0.5 * screen_width, center_y = 0.5 * screen_height; - { - MapPokeCenterIconWatcher pokecenter_watcher(COLOR_RED, stream.overlay(), MAP_READABLE_AREA); - int ret = wait_until(stream, context, std::chrono::seconds(2), {pokecenter_watcher}); - if (ret != 0){ - stream.log("No visible pokecetner found on map"); - stream.overlay().add_log("No whole PokeCenter icon"); - return false; - } - // Find the detected PokeCenter icon closest to the screen center (where player character is on the map). - for(const auto& box: pokecenter_watcher.found_locations()){ - const double loc_x = (box.x + box.width/2) * screen_width; - const double loc_y = (box.y + box.height/2) * screen_height; - const double x_diff = loc_x - center_x, y_diff = loc_y - center_y; - const double dist2 = x_diff * x_diff + y_diff * y_diff; - std::ostringstream os; - os << "Found pokecenter at box: x=" << box.x << ", y=" << box.y << ", width=" << box.width << ", height=" << box.height << - ", dist to center " << std::sqrt(dist2) << " pixels"; - stream.log(os.str()); - - if (dist2 < max_dist){ - max_dist = dist2; - closest_icon_x = loc_x; closest_icon_y = loc_y; - } - } - stream.log("Found closest pokecenter icon on map: (" + std::to_string(closest_icon_x) + ", " + std::to_string(closest_icon_y) + ")."); - stream.overlay().add_log("Detected PokeCenter icon"); - } - - // Convert the vector from center to the PokeCenter icon into a left joystick movement - const double dif_x = closest_icon_x - center_x; - const double dif_y = closest_icon_y - center_y; - const double magnitude = std::max(std::sqrt(max_dist), 1.0); - const double push_x = dif_x * 64 / magnitude, push_y = dif_y * 64 / magnitude; - - // 0.5 is too large, 0.25 a little too small, 0.30 is a bit too much for a far-away pokecenter - const double scale = push_scale; - - const uint8_t move_x = uint8_t(std::max(std::min(int(round(push_x + 128) + 0.5), 255), 0)); - const uint8_t move_y = uint8_t(std::max(std::min(int(round(push_y + 128) + 0.5), 255), 0)); - - stream.overlay().add_log("Move Cursor to PokeCenter", COLOR_WHITE); - const uint16_t push_time = std::max(uint16_t(magnitude * scale + 0.5), uint16_t(3)); - pbf_move_left_joystick(context, move_x, move_y, push_time, 30); - context.wait_for_all_requests(); - return true; -} - -// While in the current map zoom level, detect pokecenter icons and fly to the closest one. -// Return true if succeed. Return false if no visible pokcenter on map -// Throw Operation failed Exception if detected pokecenter, but failed to fly there. -bool fly_to_visible_closest_pokecenter_cur_zoom_level( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double push_scale -){ - if (!detect_closest_pokecenter_and_move_map_cursor_there(info, stream, context, push_scale)){ - return false; - } - bool check_fly_menuitem = true; - const bool success = fly_to_overworld_from_map(info, stream, context, check_fly_menuitem); - if (success){ - return true; - }else{ - // detected pokecenter, but failed to fly there. - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "fly_to_visible_closest_pokecenter_cur_zoom_level(): Detected pokecenter, but failed to fly there as no \"Fly\" menuitem.", - stream - ); - } - -} - - -void fly_to_closest_pokecenter_on_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - const int MAX_TRY_COUNT = 17; - int try_count = 0; - // Part 1: Tries to detect a pokecenter that is very close to the player - // Zoom in one level onto the map. - // If the player character icon or any wild pokemon icon overlaps with the PokeCenter icon, the code cannot - // detect it. So we zoom in as much as we can to prevent any icon overlap. - - // failures to fly to pokecenter are often when the Switch lags. from my testing, a 1.4-1.5 adjustment factor seems to work - const std::array adjustment_table = {1, 1.4, 1, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 0.9, 0.8, 1.4}; // {1, 1.4, 1.5}; - - while(true){ - try { - pbf_press_button(context, BUTTON_ZR, 40, 100); - // try different magnitudes of cursor push with each failure. - double push_scale = 0.29 * adjustment_table[try_count]; - // std::cout << "push_scale: " << std::to_string(push_scale) << std::endl; - if (fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context, push_scale)){ - return; // success in finding the closest pokecenter. Return. - } - - // no visible pokecenters at this zoom level. Move on to part 2. - break; - }catch (OperationFailedException&){ // pokecenter was detected, but failed to fly there - try_count++; - if (try_count >= MAX_TRY_COUNT){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "fly_to_closest_pokecenter_on_map(): At min warpable map level, pokecenter was detected, but failed to fly there.", - stream - ); - } - stream.log("Failed to find the fly menu item. Restart the closest Pokecenter travel process."); - press_Bs_to_back_to_overworld(info, stream, context); - open_map_from_overworld(info, stream, context); - } - } - - // Part 2: Tries to detect any pokecenter that is overlapped with the player. - // Zoom out to the max warpable level and try pressing on the player character. - stream.log("Zoom to max map level to try searching for Pokecenter again."); - stream.overlay().add_log("Pokecenter Icon occluded"); - pbf_press_button(context, BUTTON_ZL, 40, 100); - pbf_press_button(context, BUTTON_ZL, 40, 100); - - const bool check_fly_menuitem = true; - if (fly_to_overworld_from_map(info, stream, context, check_fly_menuitem)){ - return; // success in flying to the pokecenter that overlaps with the player character at max warpable level. - } - - // Failed to find pokecenter overlapping with player - stream.log("No PokeCenter icon overlapping with the player character on the max warpable level"); - stream.overlay().add_log("No overlapping PokeCenter"); - // press B to close the destination menu item - pbf_press_button(context, BUTTON_B, 60, 100); - - - // Part 3: Tries to detect a pokecenter that is further away from the player, while at max warpable level - try_count = 0; - while(true){ - try { - double push_scale = 0.29 * adjustment_table[try_count]; - // std::cout << "push_scale: " << std::to_string(push_scale) << std::endl; - // Now try finding the closest pokecenter at the max warpable level - if (fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context, push_scale)){ - return; // success in finding the closest pokecenter. Return. - }else{ - // Does not detect any pokecenter on map - stream.overlay().add_log("Still no PokeCenter Found!", COLOR_RED); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "fly_to_closest_pokecenter_on_map(): At max warpable map level, still cannot find PokeCenter icon.", - stream - ); - } - }catch (OperationFailedException& e){ - try_count++; - if (try_count >= MAX_TRY_COUNT){ - // either: - // - pokecenter was detected, but failed to fly there. - // - could not find pokecenter icon. - throw e; - } - stream.log("Failed to find the fly menuitem. Restart the closest Pokecenter travel process."); - press_Bs_to_back_to_overworld(info, stream, context); - open_map_from_overworld(info, stream, context); - // zoom out to max warpable level - pbf_press_button(context, BUTTON_ZL, 40, 100); - } - } -} - -void jump_off_wall_until_map_open(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - for (auto i = 0; i < 3; i++){ - pbf_press_button(context, BUTTON_L, 50, 50); - pbf_press_button(context, BUTTON_B, 50, 50); - pbf_move_left_joystick(context, 128, 255, 100, 50); - context.wait_for_all_requests(); - try{ - open_map_from_overworld(info, stream, context); - break; - } - catch(...){ - stream.log("Failed to open map."); - } - if (i >= 3){ - stream.log("Could not escape wall."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "jump_off_wall_until_map_open(): Could not escape wall.", - stream - ); - } - } -} - -// Open map and teleport back to town pokecenter to reset the hunting path. -void reset_to_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - while (true){ - try { - open_map_from_overworld(info, stream, context); - fly_to_closest_pokecenter_on_map(info, stream, context); - break; - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - -} - -void realign_player(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - PlayerRealignMode realign_mode, - uint8_t move_x, uint8_t move_y, uint16_t move_duration -){ - stream.log("Realigning player direction..."); - switch (realign_mode){ - case PlayerRealignMode::REALIGN_NEW_MARKER: - stream.log("Setting new map marker..."); - open_map_from_overworld(info, stream, context); - pbf_press_button(context, BUTTON_ZR, 20, 105); - pbf_move_left_joystick(context, move_x, move_y, move_duration, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - leave_phone_to_overworld(info, stream, context); - return; - case PlayerRealignMode::REALIGN_OLD_MARKER: - open_map_from_overworld(info, stream, context, false); - leave_phone_to_overworld(info, stream, context); - pbf_press_button(context, BUTTON_L, 20, 105); - return; - case PlayerRealignMode::REALIGN_NO_MARKER: - pbf_move_left_joystick(context, move_x, move_y, move_duration, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_L, 20, 105); - return; - } - -} - - -void walk_forward_until_dialog( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - NavigationMovementMode movement_mode, - uint16_t seconds_timeout, - uint8_t x, - uint8_t y -){ - - DialogBoxWatcher dialog(COLOR_RED, true); - context.wait_for_all_requests(); - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - ssf_press_left_joystick(context, 128, y, 0, seconds_timeout * TICKS_PER_SECOND); - if (movement_mode == NavigationMovementMode::DIRECTIONAL_ONLY){ - pbf_wait(context, seconds_timeout * TICKS_PER_SECOND); - } else if (movement_mode == NavigationMovementMode::DIRECTIONAL_SPAM_A){ - pbf_mash_button(context, BUTTON_A, seconds_timeout * TICKS_PER_SECOND); - // for (size_t j = 0; j < seconds_timeout; j++){ - // pbf_press_button(context, BUTTON_A, 20, 105); - // } - } - }, - {dialog} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: // dialog - stream.log("walk_forward_until_dialog(): Detected dialog."); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "walk_forward_until_dialog(): Timed out. Did not detect dialog.", - stream - ); - } -} - -void walk_forward_while_clear_front_path( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - uint16_t forward_ticks, - uint8_t y, - uint16_t ticks_between_lets_go, - uint16_t delay_after_lets_go -){ - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_R, 20, delay_after_lets_go); - - uint16_t num_ticks_left = forward_ticks; - while (true){ - - if (num_ticks_left < ticks_between_lets_go){ - pbf_move_left_joystick(context, 128, y, num_ticks_left, 20); - context.wait_for_all_requests(); - stream.log("walk_forward_while_clear_front_path() ticks traveled: " + std::to_string(forward_ticks)); - break; - } - - pbf_move_left_joystick(context, 128, y, ticks_between_lets_go, 20); - num_ticks_left -= ticks_between_lets_go; - - context.wait_for_all_requests(); - stream.log("walk_forward_while_clear_front_path() ticks traveled: " + std::to_string(forward_ticks - num_ticks_left)); - - pbf_press_button(context, BUTTON_R, 20, delay_after_lets_go); - - - } -} - - -bool attempt_fly_to_overlapping_flypoint( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -){ - while (true){ - try { - open_map_from_overworld(info, stream, context, false); - context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_ZL, 40, 100); - - return fly_to_overworld_from_map(info, stream, context, true); - - }catch (UnexpectedBattleException&){ - run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); - } - } - -} - -void fly_to_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - if (!attempt_fly_to_overlapping_flypoint(info, stream, context)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to reset to overlapping Pokecenter.", - stream - ); - } -} - -void confirm_no_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - if (attempt_fly_to_overlapping_flypoint(info, stream, context)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Overlapping fly detected, when it wasn't expected.", - stream - ); - } -} - - -void heal_at_pokecenter( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -){ - context.wait_for_all_requests(); - - if (!attempt_fly_to_overlapping_flypoint(info, stream, context)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to fly to pokecenter.", - stream - ); - } - uint16_t seconds_timeout = 60; - - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 20); - // move towards pokecenter - pbf_move_left_joystick(context, 128, 255, 100, 20); - // re-orient camera - pbf_press_button(context, BUTTON_L, 20, 20); - - bool seen_prompt = false; - - while (true){ - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - // TODO: test the Prompt watcher on all languages. Ensure FloatBox is sized correctly. - PromptDialogWatcher prompt(COLOR_YELLOW, {0.50, 0.400, 0.400, 0.080}); // 0.630, 0.400, 0.100, 0.080 // {0.50, 0.40, 0.40, 0.50} - AdvanceDialogWatcher advance_dialog(COLOR_RED); - TutorialWatcher tutorial(COLOR_RED); - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(seconds_timeout), - {overworld, prompt, advance_dialog, tutorial} - ); - context.wait_for(std::chrono::milliseconds(100)); - - switch (ret){ - case 0: // overworld - stream.log("heal_at_pokecenter: Detected overworld."); - if (seen_prompt){ - // if have seen the prompt dialog and are now in overworld, assume we have healed - stream.log("heal_at_pokecenter: Done healing."); - return; - } - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case 1: // prompt - stream.log("heal_at_pokecenter: Detected prompt."); - seen_prompt = true; - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case 2: // advance dialog - stream.log("heal_at_pokecenter: Detected advance dialog."); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - case 3: // tutorial - stream.log("heal_at_pokecenter: Detected tutorial."); - pbf_press_button(context, BUTTON_A, 20, 105); - break; - default: - stream.log("heal_at_pokecenter: Timed out."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to heal at pokecenter.", - stream - ); - } - } -} - - -} -} -} +/* PokemonSV World Navigation + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/UnexpectedBattleException.h" +#include "CommonTools/Async/InferenceRoutines.h" +//#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +//#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +//#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +//#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Map/PokemonSV_MapDetector.h" +#include "PokemonSV/Inference/Map/PokemonSV_MapMenuDetector.h" +#include "PokemonSV/Inference/Map/PokemonSV_MapPokeCenterIconDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_ZeroGateWarpPromptDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/PokemonSV_TutorialDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV_ConnectToInternet.h" +#include "PokemonSV_WorldNavigation.h" + +#include +#include +#include +#include +#include +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +bool fly_to_overworld_from_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool check_fly_menuitem){ + context.wait_for_all_requests(); + // Press A to bring up the promp dialog on choosing "Fly here", "Set as destination", "Never mind". + pbf_press_button(context, BUTTON_A, 20, 130); + + WallClock start = current_time(); + while (true){ + if (current_time() - start > std::chrono::minutes(2)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "fly_to_overworld_from_map(): Failed to fly from map after 2 minutes.", + stream + ); + } + + int ret = 0; + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + WhiteButtonWatcher map(COLOR_RED, WhiteButton::ButtonY, {0.800, 0.118, 0.030, 0.060}); + GradientArrowWatcher spot_dialog_watcher(COLOR_YELLOW, GradientArrowType::RIGHT, {0.469, 0.500, 0.215, 0.150}); + PromptDialogWatcher confirm_watcher(COLOR_BLUE, {0.686, 0.494, 0.171, 0.163}); + MapFlyMenuWatcher flyMenuItemWatcher(COLOR_BLACK); + MapDestinationMenuWatcher destinationMenuItemWatcher(COLOR_BLACK); + + context.wait_for_all_requests(); + + std::vector callbacks{overworld, map, spot_dialog_watcher, confirm_watcher}; + if (check_fly_menuitem){ + callbacks[2] = flyMenuItemWatcher; + callbacks.push_back(destinationMenuItemWatcher); + } + + ret = wait_until(stream, context, std::chrono::minutes(2), callbacks); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld. Fly successful."); + return true; + case 1: + stream.log("Detected map. Pressing A to open map menu."); + // Press A to bring up the promp dialog on choosing "Fly here", "Set as destination", "Never mind". + pbf_press_button(context, BUTTON_A, 20, 130); + continue; + case 2: + stream.log("Detected fly here prompt dialog."); + stream.overlay().add_log("Fly"); + pbf_press_button(context, BUTTON_A, 20, 130); + continue; + case 3: + stream.log("Detected fly confirmation prompt."); + pbf_press_button(context, BUTTON_A, 20, 130); + continue; + case 4: + stream.log("Detected no fly spot here."); + stream.overlay().add_log("No fly spot", COLOR_RED); + return false; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "fly_to_overworld_from_map(): No recognized state after 2 minutes.", + stream + ); + } + } +} + + +void picnic_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Start picnic from overworld..."); + WallClock start = current_time(); + bool success = false; + while (true){ + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "picnic_from_overworld(): Failed to start picnic after 3 minutes.", + stream + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + MainMenuWatcher main_menu(COLOR_RED); + PicnicWatcher picnic; + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {overworld, main_menu, picnic} + ); + context.wait_for(std::chrono::milliseconds(100)); + const bool fast_mode = false; + switch (ret){ + case 0: + stream.log("Detected overworld."); + pbf_press_button(context, BUTTON_X, 20, 105); // open menu + continue; + case 1: + stream.log("Detected main menu."); + success = main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 2, fast_mode); + if (success == false){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "picnic_from_overworld(): Cannot move menu cursor to picnic.", + stream + ); + } + pbf_mash_button(context, BUTTON_A, 125); // mash button A to enter picnic mode + continue; + case 2: + stream.log("Detected picnic."); + stream.overlay().add_log("Start picnic", COLOR_WHITE); + // extra wait to make sure by the end the player can move. + // the player throwing out pokeballs animation is long. + pbf_wait(context, 1000); + context.wait_for_all_requests(); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "picnic_from_overworld(): No recognized state after 30 seconds.", + stream + ); + } + } +} + +void leave_picnic(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + context.wait_for_all_requests(); + stream.log("Leaving picnic..."); + stream.overlay().add_log("Leaving picnic", COLOR_WHITE); + + pbf_press_button(context, BUTTON_Y, 30, 100); + for(int i = 0; i < 5; i++){ + PromptDialogWatcher prompt(COLOR_RED, {0.595, 0.517, 0.273, 0.131}); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(5), + {prompt} + ); + + if (ret == 0){ + stream.log("Detected end picnic prompt"); + break; + } + + if (i == 4){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "leave_picnic(): Failed to leave picnic after 5 tries.", + stream + ); + } + + // prompt not found, maybe button Y dropped? + pbf_press_button(context, BUTTON_Y, 30, 100); + } + + // We have now the prompt to asking for confirmation of leaving picnic. + // Mash A to confirm + pbf_mash_button(context, BUTTON_A, 150); + context.wait_for_all_requests(); + + // Wait for overworld: + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret = wait_until( + stream, context, + std::chrono::seconds(20), + {overworld} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "leave_picnic(): Failed to detecxt overworld after 20 seconds.", + stream + ); + } + // Wait three more seconds to make sure the player character is free to operate: + context.wait_for(std::chrono::seconds(3)); +} + + +// While in the current map zoom level, detect pokecenter icons and move the map cursor there. +// Return true if succeed. Return false if no visible pokcenter on map +bool detect_closest_pokecenter_and_move_map_cursor_there( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double push_scale +){ + context.wait_for_all_requests(); + const auto snapshot_frame = stream.video().snapshot().frame; + const size_t screen_width = snapshot_frame->width(); + const size_t screen_height = snapshot_frame->height(); + + double closest_icon_x = 0., closest_icon_y = 0.; + double max_dist = DBL_MAX; + const double center_x = 0.5 * screen_width, center_y = 0.5 * screen_height; + { + MapPokeCenterIconWatcher pokecenter_watcher(COLOR_RED, stream.overlay(), MAP_READABLE_AREA); + int ret = wait_until(stream, context, std::chrono::seconds(2), {pokecenter_watcher}); + if (ret != 0){ + stream.log("No visible pokecetner found on map"); + stream.overlay().add_log("No whole PokeCenter icon"); + return false; + } + // Find the detected PokeCenter icon closest to the screen center (where player character is on the map). + for(const auto& box: pokecenter_watcher.found_locations()){ + const double loc_x = (box.x + box.width/2) * screen_width; + const double loc_y = (box.y + box.height/2) * screen_height; + const double x_diff = loc_x - center_x, y_diff = loc_y - center_y; + const double dist2 = x_diff * x_diff + y_diff * y_diff; + std::ostringstream os; + os << "Found pokecenter at box: x=" << box.x << ", y=" << box.y << ", width=" << box.width << ", height=" << box.height << + ", dist to center " << std::sqrt(dist2) << " pixels"; + stream.log(os.str()); + + if (dist2 < max_dist){ + max_dist = dist2; + closest_icon_x = loc_x; closest_icon_y = loc_y; + } + } + stream.log("Found closest pokecenter icon on map: (" + std::to_string(closest_icon_x) + ", " + std::to_string(closest_icon_y) + ")."); + stream.overlay().add_log("Detected PokeCenter icon"); + } + + // Convert the vector from center to the PokeCenter icon into a left joystick movement + const double dif_x = closest_icon_x - center_x; + const double dif_y = closest_icon_y - center_y; + const double magnitude = std::max(std::sqrt(max_dist), 1.0); + const double push_x = dif_x * 64 / magnitude, push_y = dif_y * 64 / magnitude; + + // 0.5 is too large, 0.25 a little too small, 0.30 is a bit too much for a far-away pokecenter + const double scale = push_scale; + + const uint8_t move_x = uint8_t(std::max(std::min(int(round(push_x + 128) + 0.5), 255), 0)); + const uint8_t move_y = uint8_t(std::max(std::min(int(round(push_y + 128) + 0.5), 255), 0)); + + stream.overlay().add_log("Move Cursor to PokeCenter", COLOR_WHITE); + const uint16_t push_time = std::max(uint16_t(magnitude * scale + 0.5), uint16_t(3)); + pbf_move_left_joystick(context, move_x, move_y, push_time, 30); + context.wait_for_all_requests(); + return true; +} + +// While in the current map zoom level, detect pokecenter icons and fly to the closest one. +// Return true if succeed. Return false if no visible pokcenter on map +// Throw Operation failed Exception if detected pokecenter, but failed to fly there. +bool fly_to_visible_closest_pokecenter_cur_zoom_level( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double push_scale +){ + if (!detect_closest_pokecenter_and_move_map_cursor_there(info, stream, context, push_scale)){ + return false; + } + bool check_fly_menuitem = true; + const bool success = fly_to_overworld_from_map(info, stream, context, check_fly_menuitem); + if (success){ + return true; + }else{ + // detected pokecenter, but failed to fly there. + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "fly_to_visible_closest_pokecenter_cur_zoom_level(): Detected pokecenter, but failed to fly there as no \"Fly\" menuitem.", + stream + ); + } + +} + + +void fly_to_closest_pokecenter_on_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + const int MAX_TRY_COUNT = 17; + int try_count = 0; + // Part 1: Tries to detect a pokecenter that is very close to the player + // Zoom in one level onto the map. + // If the player character icon or any wild pokemon icon overlaps with the PokeCenter icon, the code cannot + // detect it. So we zoom in as much as we can to prevent any icon overlap. + + // failures to fly to pokecenter are often when the Switch lags. from my testing, a 1.4-1.5 adjustment factor seems to work + const std::array adjustment_table = {1, 1.4, 1, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0, 0.9, 0.8, 1.4}; // {1, 1.4, 1.5}; + + while(true){ + try { + pbf_press_button(context, BUTTON_ZR, 40, 100); + // try different magnitudes of cursor push with each failure. + double push_scale = 0.29 * adjustment_table[try_count]; + // std::cout << "push_scale: " << std::to_string(push_scale) << std::endl; + if (fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context, push_scale)){ + return; // success in finding the closest pokecenter. Return. + } + + // no visible pokecenters at this zoom level. Move on to part 2. + break; + }catch (OperationFailedException&){ // pokecenter was detected, but failed to fly there + try_count++; + if (try_count >= MAX_TRY_COUNT){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "fly_to_closest_pokecenter_on_map(): At min warpable map level, pokecenter was detected, but failed to fly there.", + stream + ); + } + stream.log("Failed to find the fly menu item. Restart the closest Pokecenter travel process."); + press_Bs_to_back_to_overworld(info, stream, context); + open_map_from_overworld(info, stream, context); + } + } + + // Part 2: Tries to detect any pokecenter that is overlapped with the player. + // Zoom out to the max warpable level and try pressing on the player character. + stream.log("Zoom to max map level to try searching for Pokecenter again."); + stream.overlay().add_log("Pokecenter Icon occluded"); + pbf_press_button(context, BUTTON_ZL, 40, 100); + pbf_press_button(context, BUTTON_ZL, 40, 100); + + const bool check_fly_menuitem = true; + if (fly_to_overworld_from_map(info, stream, context, check_fly_menuitem)){ + return; // success in flying to the pokecenter that overlaps with the player character at max warpable level. + } + + // Failed to find pokecenter overlapping with player + stream.log("No PokeCenter icon overlapping with the player character on the max warpable level"); + stream.overlay().add_log("No overlapping PokeCenter"); + // press B to close the destination menu item + pbf_press_button(context, BUTTON_B, 60, 100); + + + // Part 3: Tries to detect a pokecenter that is further away from the player, while at max warpable level + try_count = 0; + while(true){ + try { + double push_scale = 0.29 * adjustment_table[try_count]; + // std::cout << "push_scale: " << std::to_string(push_scale) << std::endl; + // Now try finding the closest pokecenter at the max warpable level + if (fly_to_visible_closest_pokecenter_cur_zoom_level(info, stream, context, push_scale)){ + return; // success in finding the closest pokecenter. Return. + }else{ + // Does not detect any pokecenter on map + stream.overlay().add_log("Still no PokeCenter Found!", COLOR_RED); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "fly_to_closest_pokecenter_on_map(): At max warpable map level, still cannot find PokeCenter icon.", + stream + ); + } + }catch (OperationFailedException& e){ + try_count++; + if (try_count >= MAX_TRY_COUNT){ + // either: + // - pokecenter was detected, but failed to fly there. + // - could not find pokecenter icon. + throw e; + } + stream.log("Failed to find the fly menuitem. Restart the closest Pokecenter travel process."); + press_Bs_to_back_to_overworld(info, stream, context); + open_map_from_overworld(info, stream, context); + // zoom out to max warpable level + pbf_press_button(context, BUTTON_ZL, 40, 100); + } + } +} + +void jump_off_wall_until_map_open(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + for (auto i = 0; i < 3; i++){ + pbf_press_button(context, BUTTON_L, 50, 50); + pbf_press_button(context, BUTTON_B, 50, 50); + pbf_move_left_joystick(context, 128, 255, 100, 50); + context.wait_for_all_requests(); + try{ + open_map_from_overworld(info, stream, context); + break; + } + catch(...){ + stream.log("Failed to open map."); + } + if (i >= 3){ + stream.log("Could not escape wall."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "jump_off_wall_until_map_open(): Could not escape wall.", + stream + ); + } + } +} + +// Open map and teleport back to town pokecenter to reset the hunting path. +void reset_to_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + while (true){ + try { + open_map_from_overworld(info, stream, context); + fly_to_closest_pokecenter_on_map(info, stream, context); + break; + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + +} + +void realign_player(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + PlayerRealignMode realign_mode, + uint8_t move_x, uint8_t move_y, uint16_t move_duration +){ + stream.log("Realigning player direction..."); + switch (realign_mode){ + case PlayerRealignMode::REALIGN_NEW_MARKER: + stream.log("Setting new map marker..."); + open_map_from_overworld(info, stream, context); + pbf_press_button(context, BUTTON_ZR, 20, 105); + pbf_move_left_joystick(context, move_x, move_y, move_duration, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + leave_phone_to_overworld(info, stream, context); + return; + case PlayerRealignMode::REALIGN_OLD_MARKER: + open_map_from_overworld(info, stream, context, false); + leave_phone_to_overworld(info, stream, context); + pbf_press_button(context, BUTTON_L, 20, 105); + return; + case PlayerRealignMode::REALIGN_NO_MARKER: + pbf_move_left_joystick(context, move_x, move_y, move_duration, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_L, 20, 105); + return; + } + +} + + +void walk_forward_until_dialog( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + NavigationMovementMode movement_mode, + uint16_t seconds_timeout, + uint8_t x, + uint8_t y +){ + + DialogBoxWatcher dialog(COLOR_RED, true); + context.wait_for_all_requests(); + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + ssf_press_left_joystick(context, 128, y, 0, seconds_timeout * TICKS_PER_SECOND); + if (movement_mode == NavigationMovementMode::DIRECTIONAL_ONLY){ + pbf_wait(context, seconds_timeout * TICKS_PER_SECOND); + } else if (movement_mode == NavigationMovementMode::DIRECTIONAL_SPAM_A){ + pbf_mash_button(context, BUTTON_A, seconds_timeout * TICKS_PER_SECOND); + // for (size_t j = 0; j < seconds_timeout; j++){ + // pbf_press_button(context, BUTTON_A, 20, 105); + // } + } + }, + {dialog} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: // dialog + stream.log("walk_forward_until_dialog(): Detected dialog."); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "walk_forward_until_dialog(): Timed out. Did not detect dialog.", + stream + ); + } +} + +void walk_forward_while_clear_front_path( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + uint16_t forward_ticks, + uint8_t y, + uint16_t ticks_between_lets_go, + uint16_t delay_after_lets_go +){ + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_R, 20, delay_after_lets_go); + + uint16_t num_ticks_left = forward_ticks; + while (true){ + + if (num_ticks_left < ticks_between_lets_go){ + pbf_move_left_joystick(context, 128, y, num_ticks_left, 20); + context.wait_for_all_requests(); + stream.log("walk_forward_while_clear_front_path() ticks traveled: " + std::to_string(forward_ticks)); + break; + } + + pbf_move_left_joystick(context, 128, y, ticks_between_lets_go, 20); + num_ticks_left -= ticks_between_lets_go; + + context.wait_for_all_requests(); + stream.log("walk_forward_while_clear_front_path() ticks traveled: " + std::to_string(forward_ticks - num_ticks_left)); + + pbf_press_button(context, BUTTON_R, 20, delay_after_lets_go); + + + } +} + + +bool attempt_fly_to_overlapping_flypoint( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +){ + while (true){ + try { + open_map_from_overworld(info, stream, context, false); + context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_ZL, 40, 100); + + return fly_to_overworld_from_map(info, stream, context, true); + + }catch (UnexpectedBattleException&){ + run_battle_press_A(stream, context, BattleStopCondition::STOP_OVERWORLD); + } + } + +} + +void fly_to_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + if (!attempt_fly_to_overlapping_flypoint(info, stream, context)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to reset to overlapping Pokecenter.", + stream + ); + } +} + +void confirm_no_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + if (attempt_fly_to_overlapping_flypoint(info, stream, context)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Overlapping fly detected, when it wasn't expected.", + stream + ); + } +} + + +void heal_at_pokecenter( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +){ + context.wait_for_all_requests(); + + if (!attempt_fly_to_overlapping_flypoint(info, stream, context)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to fly to pokecenter.", + stream + ); + } + uint16_t seconds_timeout = 60; + + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 20); + // move towards pokecenter + pbf_move_left_joystick(context, 128, 255, 100, 20); + // re-orient camera + pbf_press_button(context, BUTTON_L, 20, 20); + + bool seen_prompt = false; + + while (true){ + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + // TODO: test the Prompt watcher on all languages. Ensure FloatBox is sized correctly. + PromptDialogWatcher prompt(COLOR_YELLOW, {0.50, 0.400, 0.400, 0.080}); // 0.630, 0.400, 0.100, 0.080 // {0.50, 0.40, 0.40, 0.50} + AdvanceDialogWatcher advance_dialog(COLOR_RED); + TutorialWatcher tutorial(COLOR_RED); + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(seconds_timeout), + {overworld, prompt, advance_dialog, tutorial} + ); + context.wait_for(std::chrono::milliseconds(100)); + + switch (ret){ + case 0: // overworld + stream.log("heal_at_pokecenter: Detected overworld."); + if (seen_prompt){ + // if have seen the prompt dialog and are now in overworld, assume we have healed + stream.log("heal_at_pokecenter: Done healing."); + return; + } + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case 1: // prompt + stream.log("heal_at_pokecenter: Detected prompt."); + seen_prompt = true; + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case 2: // advance dialog + stream.log("heal_at_pokecenter: Detected advance dialog."); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + case 3: // tutorial + stream.log("heal_at_pokecenter: Detected tutorial."); + pbf_press_button(context, BUTTON_A, 20, 105); + break; + default: + stream.log("heal_at_pokecenter: Timed out."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to heal at pokecenter.", + stream + ); + } + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.h b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.h index e858a7b71d..0c08f7b913 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.h +++ b/SerialPrograms/Source/PokemonSV/Programs/PokemonSV_WorldNavigation.h @@ -1,143 +1,143 @@ -/* PokemonSV World Navigation - * - * From: https://github.com/PokemonAutomation/ - * - * Move player character around the overworld - * - */ - -#ifndef PokemonAutomation_PokemonSV_WorldNavigation_H -#define PokemonAutomation_PokemonSV_WorldNavigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h" - -namespace PokemonAutomation{ - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// From map, press A to fly to a travel spot. -// check_fly_menuitem == true: will detect if the "Fly" menuitem is available. Return false if no "Fly" menuitem (the game -// will be on the map menu opened state). Return true if the flight is successful (the game will be at the overworld). -// check_fly_menuitem == false: will use GradientArrowDetector to check if a map menu is opened. No "Fly" menuitem check. -// The function always returns true. It throws an error in the case of no "Fly" menuitem. But the error message will be about -// timeout running the function. -bool fly_to_overworld_from_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool check_fly_menuitem = false); - -// Assume the user can set up picnic at current location, start picnic from overworld. -void picnic_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// While in picnic, stop picnic and back to overworld. -void leave_picnic(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// While in the current map zoom level, detect pokecenter icons and move the map cursor there. -// Return true if succeed. Return false if no visible pokcenter on map -bool detect_closest_pokecenter_and_move_map_cursor_there( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double push_scale = 0.29 -); - -bool fly_to_visible_closest_pokecenter_cur_zoom_level( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - double push_scale = 0.29 -); - -// While on map (default zoom), move to the closest PokeCenter and fly there. -// The PokeCenter must be already visited before (so having the little wing icon with it) and not occluded -// by other map icons on the most zoomed-in level of the map. -void fly_to_closest_pokecenter_on_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// Attempt to escape being stuck on a wall. -// Repeatedly center camera and try to backwards jump off. -// Finishes when map is successfully open. -void jump_off_wall_until_map_open(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -void reset_to_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - -// align player orientation based on the alignment mode -// if battle detected, propagates UnexpectedBattleException to the calling function -// The direction is specified by (x, y): -// x = 0 : left -// x = 128 : neutral -// x = 255 : right -// y = 0 : up -// y = 128 : neutral -// y = 255 : down -// - REALIGN_NEW_MARKER: place down a map marker, which will align the player towards the marker -// location of the marker is set with move_x, move_y, move_duration -// - REALIGN_OLD_MARKER: assuming a marker is already set, open and close the map, -// which will align the player towards the marker -// - REALIGN_NO_MARKER: move player towards in the direction set by move_x, move_y, move_duration -// then re-align the camera -void realign_player( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - PlayerRealignMode realign_mode, - uint8_t move_x = 0, uint8_t move_y = 0, uint16_t move_duration = 0 -); - - - -void walk_forward_until_dialog( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - NavigationMovementMode movement_mode, - uint16_t seconds_timeout = 10, - uint8_t x = 128, - uint8_t y = 0 -); - -// walk forward while using lets go to clear the path -// forward_ticks: number of ticks to walk forward -// y = 0: walks forward. y = 128: stand in place. y = 255: walk backwards (towards camera) -// ticks_between_lets_go: number of ticks between firing off Let's go to clear the path from wild pokemon -// delay_after_lets_go: number of ticks to wait after firing off Let's go. -void walk_forward_while_clear_front_path( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context, - uint16_t forward_ticks, - uint8_t y = 0, - uint16_t ticks_between_lets_go = 125, - uint16_t delay_after_lets_go = 250 -); - -// fly to the pokecenter that overlaps with the player on the map, and return true. -// if no overlapping pokecenter, return false. -bool attempt_fly_to_overlapping_flypoint( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -); - -// fly to the pokecenter that overlaps with the player on the map -// throw exception if unsuccessful -void fly_to_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -// throw exception if there is a fly point/pokecenter that overlaps with the player on the map -void confirm_no_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - -// heal at the pokecenter, that your character is currently at. -// if not currently at the pokecenter, throws error. -void heal_at_pokecenter( - const ProgramInfo& info, - VideoStream& stream, - ProControllerContext& context -); - - -} -} -} -#endif +/* PokemonSV World Navigation + * + * From: https://github.com/PokemonAutomation/ + * + * Move player character around the overworld + * + */ + +#ifndef PokemonAutomation_PokemonSV_WorldNavigation_H +#define PokemonAutomation_PokemonSV_WorldNavigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Programs/AutoStory/PokemonSV_AutoStoryTools.h" + +namespace PokemonAutomation{ + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// From map, press A to fly to a travel spot. +// check_fly_menuitem == true: will detect if the "Fly" menuitem is available. Return false if no "Fly" menuitem (the game +// will be on the map menu opened state). Return true if the flight is successful (the game will be at the overworld). +// check_fly_menuitem == false: will use GradientArrowDetector to check if a map menu is opened. No "Fly" menuitem check. +// The function always returns true. It throws an error in the case of no "Fly" menuitem. But the error message will be about +// timeout running the function. +bool fly_to_overworld_from_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, bool check_fly_menuitem = false); + +// Assume the user can set up picnic at current location, start picnic from overworld. +void picnic_from_overworld(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// While in picnic, stop picnic and back to overworld. +void leave_picnic(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// While in the current map zoom level, detect pokecenter icons and move the map cursor there. +// Return true if succeed. Return false if no visible pokcenter on map +bool detect_closest_pokecenter_and_move_map_cursor_there( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double push_scale = 0.29 +); + +bool fly_to_visible_closest_pokecenter_cur_zoom_level( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + double push_scale = 0.29 +); + +// While on map (default zoom), move to the closest PokeCenter and fly there. +// The PokeCenter must be already visited before (so having the little wing icon with it) and not occluded +// by other map icons on the most zoomed-in level of the map. +void fly_to_closest_pokecenter_on_map(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// Attempt to escape being stuck on a wall. +// Repeatedly center camera and try to backwards jump off. +// Finishes when map is successfully open. +void jump_off_wall_until_map_open(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +void reset_to_pokecenter(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + +// align player orientation based on the alignment mode +// if battle detected, propagates UnexpectedBattleException to the calling function +// The direction is specified by (x, y): +// x = 0 : left +// x = 128 : neutral +// x = 255 : right +// y = 0 : up +// y = 128 : neutral +// y = 255 : down +// - REALIGN_NEW_MARKER: place down a map marker, which will align the player towards the marker +// location of the marker is set with move_x, move_y, move_duration +// - REALIGN_OLD_MARKER: assuming a marker is already set, open and close the map, +// which will align the player towards the marker +// - REALIGN_NO_MARKER: move player towards in the direction set by move_x, move_y, move_duration +// then re-align the camera +void realign_player( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + PlayerRealignMode realign_mode, + uint8_t move_x = 0, uint8_t move_y = 0, uint16_t move_duration = 0 +); + + + +void walk_forward_until_dialog( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + NavigationMovementMode movement_mode, + uint16_t seconds_timeout = 10, + uint8_t x = 128, + uint8_t y = 0 +); + +// walk forward while using lets go to clear the path +// forward_ticks: number of ticks to walk forward +// y = 0: walks forward. y = 128: stand in place. y = 255: walk backwards (towards camera) +// ticks_between_lets_go: number of ticks between firing off Let's go to clear the path from wild pokemon +// delay_after_lets_go: number of ticks to wait after firing off Let's go. +void walk_forward_while_clear_front_path( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context, + uint16_t forward_ticks, + uint8_t y = 0, + uint16_t ticks_between_lets_go = 125, + uint16_t delay_after_lets_go = 250 +); + +// fly to the pokecenter that overlaps with the player on the map, and return true. +// if no overlapping pokecenter, return false. +bool attempt_fly_to_overlapping_flypoint( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +); + +// fly to the pokecenter that overlaps with the player on the map +// throw exception if unsuccessful +void fly_to_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +// throw exception if there is a fly point/pokecenter that overlaps with the player on the map +void confirm_no_overlapping_flypoint(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + +// heal at the pokecenter, that your character is currently at. +// if not currently at the pokecenter, throws error. +void heal_at_pokecenter( + const ProgramInfo& info, + VideoStream& stream, + ProControllerContext& context +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp index c533a7724a..5eeb87e499 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.cpp @@ -1,351 +1,351 @@ -/* Ingredient Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSV_IngredientSession.h" -#include "Common/Cpp/PrettyPrint.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -IngredientSession::~IngredientSession() = default; - -IngredientSession::IngredientSession( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language, SandwichIngredientType type -) - : m_dispatcher(dispatcher) - , m_stream(stream) - , m_context(context) - , m_language(language) - , m_overlays(stream.overlay()) - , m_type(type) - , m_num_confirmed(0) - , m_arrow(COLOR_CYAN, GradientArrowType::RIGHT, {0.02, 0.15, 0.05, 0.80}) -{ - SandwichIngredientReader reader(m_type, COLOR_CYAN); - reader.make_overlays(m_overlays); -} - - - -PageIngredients IngredientSession::read_screen(std::shared_ptr screen) const{ - PageIngredients ret; - ImageFloatBox box; - if (!m_arrow.detect(box, *screen)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "IngredientSession::read_current_page(): Unable to find cursor.", - m_stream - ); - } - -// cout << box.y << endl; - double slot = (box.y - 0.177778) / 0.0738683; - ret.selected = (int8_t)(slot + 0.5); -// cout << "slot = " << (int)ret.selected << endl; - if (ret.selected < 0 || ret.selected >= 10){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "IngredientSession::read_current_page(): Invalid cursor slot.", - m_stream, - screen - ); - } - - // Read the names of every line and the sprite of the selected line. - ImageMatch::ImageMatchResult image_result; - SandwichIngredientReader reader(m_type); - m_dispatcher.run_in_parallel(0, SandwichIngredientReader::INGREDIENT_PAGE_LINES + 1, [&](size_t index){ - if (index < SandwichIngredientReader::INGREDIENT_PAGE_LINES){ - // Read text at line `index` - OCR::StringMatchResult result = reader.read_ingredient_page_with_ocr(*screen, m_stream.logger(), m_language, index); - result.clear_beyond_log10p(SandwichFillingOCR::MAX_LOG10P); - result.clear_beyond_spread(SandwichFillingOCR::MAX_LOG10P_SPREAD); - for (auto& item : result.results){ - ret.item[index].insert(item.second.token); - } - }else{ - // Read current selected icon - image_result = reader.read_ingredient_page_with_icon_matcher(*screen, ret.selected); - image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); - image_result.log(m_stream.logger(), SandwichIngredientReader::MAX_ALPHA); - image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); - } - }); - -#if 1 - do{ - std::set& ocr_result = ret.item[ret.selected]; - - // Special case where OCR fails and image result returns 1 item. - if (ocr_result.empty() || image_result.results.size() == 1){ - ocr_result.insert(image_result.results.begin()->second); - break; - } - - // Find the items in common between the two detection methods. - std::set common; - for (auto& item : image_result.results){ - auto iter = ocr_result.find(item.second); - if (iter != ocr_result.end()){ - common.insert(item.second); - } - } - - if (common.empty()){ - std::set sprite_result; - for(const auto& p : image_result.results){ - sprite_result.insert(p.second); - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "IngredientSession::read_current_page(): Unable to read selected item. OCR and sprite do not agree on any match: ocr " - + set_to_str(ocr_result) + ", sprite " + set_to_str(sprite_result), - m_stream, - screen - ); - } - if (common.size() > 1){ - std::set sprite_result; - for(const auto& p : image_result.results){ - sprite_result.insert(p.second); - } - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "IngredientSession::read_current_page(): Unable to read selected item. Ambiguous result: " - + set_to_str(ocr_result) + ", " + set_to_str(sprite_result), - m_stream, - screen - ); - } - - ocr_result = std::move(common); - }while (false); -#endif - - return ret; - -} -PageIngredients IngredientSession::read_current_page() const{ - return read_screen(m_stream.video().snapshot()); -} - -// Returns true if a desired ingredient is found somewhere on the page. -// "slug" is set the desired ingredient if the cursor is already on it. -bool IngredientSession::run_move_iteration( - std::string& slug, const std::set& ingredients, - const PageIngredients& page -) const{ - size_t current_index = page.selected; - std::map found_ingredients; - for (size_t c = 0; c < SandwichIngredientReader::INGREDIENT_PAGE_LINES; c++){ - for (const std::string& item : page.item[c]){ - auto iter = ingredients.find(item); - if (iter != ingredients.end()){ - found_ingredients[c] = item; - } - } - } - - if (found_ingredients.size() == 0){ - return false; - } - - size_t target_line_index = 0; - if (std::all_of(found_ingredients.begin(), found_ingredients.end(), [&](const auto& p){return p.first <= current_index;})){ - // If the current cursor is below all the found ingredients, - // we should move to the closest ingredient, which is also at the lowest line among found ingredients. - target_line_index = found_ingredients.rbegin()->first; - }else{ - target_line_index = found_ingredients.begin()->first; - } - - const std::string& item = found_ingredients[target_line_index]; - - // Cursor is already on matching ingredient. - if (current_index == target_line_index){ - m_stream.log("Desired ingredient " + item + " is selected!", COLOR_BLUE); - slug = item; - return true; - } - - m_stream.log("Found desired ingredient " + item + " on current page. Moving towards it...", COLOR_BLUE); - - // Move to it. - while (current_index < target_line_index){ - pbf_press_dpad(m_context, DPAD_DOWN, 10, 30); - current_index++; - } - while (current_index > target_line_index){ - pbf_press_dpad(m_context, DPAD_UP, 10, 30); - current_index--; - } - m_context.wait_for_all_requests(); - m_context.wait_for(std::chrono::seconds(1)); - // slug = item; - return true; -} - - -std::string IngredientSession::move_to_ingredient(const std::set& ingredients) const{ - if (ingredients.empty()){ - m_stream.log("No desired ingredients.", COLOR_RED); - return ""; - } - - size_t not_found_count = 0; - while (true){ - m_context.wait_for_all_requests(); - m_context.wait_for(std::chrono::milliseconds(180)); - PageIngredients page = read_current_page(); - std::string found_ingredient; - if (run_move_iteration(found_ingredient, ingredients, page)){ - if (found_ingredient.empty()){ - continue; - }else{ - return found_ingredient; - } - } - - size_t current = page.selected; - if (current == SandwichIngredientReader::INGREDIENT_PAGE_LINES - 1){ - not_found_count++; - if (not_found_count >= 2){ - m_stream.log("Ingredient not found anywhere.", COLOR_RED); - return ""; - }else{ - m_stream.log("End of page reached without finding ingredient. Wrapping back to beginning.", COLOR_ORANGE); - pbf_press_dpad(m_context, DPAD_DOWN, 20, 105); - continue; - } - } - - m_stream.log("Ingredient not found on current page. Scrolling down.", COLOR_ORANGE); - - // Not found on page. Scroll to next screen - pbf_press_dpad(m_context, DPAD_RIGHT, 10, 30); - - // while (current < INGREDIENT_PAGE_LINES - 1){ - // pbf_press_dpad(m_context, DPAD_DOWN, 10, 30); - // current++; - // } - - } - return ""; -} - - -void IngredientSession::add_ingredients( - VideoStream& stream, ProControllerContext& context, - std::map&& ingredients -){ - // "ingredients" will be what we still need. - // Each time we add an ingredient, it will be removed from the map. - // Loop until there's nothing left. - while (!ingredients.empty()){ - std::set remaining; - for (const auto& item : ingredients){ - remaining.insert(item.first); - } - - std::string found = this->move_to_ingredient(remaining); - if (found.empty()){ - const SandwichIngredientNames& name = get_ingredient_name(*remaining.begin()); - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to find ingredient: \"" + name.display_name() + "\" - Did you run out?", - stream - ); - } - - const SandwichIngredientNames& name = get_ingredient_name(found); - stream.log("Add " + name.display_name() + " as ingredient", COLOR_BLUE); - - // If you don't have enough ingredient, it errors out instead of proceeding - // with less than the desired quantity. - auto iter = ingredients.find(found); - SandwichIngredientReader reader(m_type); - while (iter->second > 0){ - bool ingredient_added = false; - for (int attempt = 0; attempt < 5; attempt++){ - pbf_press_button(context, BUTTON_A, 20, 105); - context.wait_for_all_requests(); - VideoSnapshot image = stream.video().snapshot(); - ImageMatch::ImageMatchResult image_result = - reader.read_confirmed_list_with_icon_matcher(image, m_num_confirmed); - image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); - image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); - image_result.log(stream.logger(), SandwichIngredientReader::MAX_ALPHA); - if (image_result.results.size() > 0){ // confirmed that the ingredient was added - stream.overlay().add_log("Added " + name.display_name()); - m_num_confirmed++; - ingredient_added = true; - iter->second--; - break; - } - } - - if (!ingredient_added){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to add ingredient: \"" + name.display_name() + "\" - Did you run out?", - stream - ); - } - } - ingredients.erase(iter); - } -} - - - -void add_sandwich_ingredients( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language, - std::map&& fillings, - std::map&& condiments -){ - { - IngredientSession session(dispatcher, stream, context, language, SandwichIngredientType::FILLING); - session.add_ingredients(stream, context, std::move(fillings)); - pbf_press_button(context, BUTTON_PLUS, 20, 230); - } - - { - IngredientSession session(dispatcher, stream, context, language, SandwichIngredientType::CONDIMENT); - // If there are herbs, we search first from bottom - if (std::any_of(condiments.begin(), condiments.end(), [&](const auto& p){return p.first.find("herba") != std::string::npos;})){ - pbf_press_dpad(context, DPAD_UP, 20, 105); - } - session.add_ingredients(stream, context, std::move(condiments)); - pbf_press_button(context, BUTTON_PLUS, 20, 230); - } - - pbf_mash_button(context, BUTTON_A, 125); -} - - - - - - -} -} -} +/* Ingredient Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSV_IngredientSession.h" +#include "Common/Cpp/PrettyPrint.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +IngredientSession::~IngredientSession() = default; + +IngredientSession::IngredientSession( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language, SandwichIngredientType type +) + : m_dispatcher(dispatcher) + , m_stream(stream) + , m_context(context) + , m_language(language) + , m_overlays(stream.overlay()) + , m_type(type) + , m_num_confirmed(0) + , m_arrow(COLOR_CYAN, GradientArrowType::RIGHT, {0.02, 0.15, 0.05, 0.80}) +{ + SandwichIngredientReader reader(m_type, COLOR_CYAN); + reader.make_overlays(m_overlays); +} + + + +PageIngredients IngredientSession::read_screen(std::shared_ptr screen) const{ + PageIngredients ret; + ImageFloatBox box; + if (!m_arrow.detect(box, *screen)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "IngredientSession::read_current_page(): Unable to find cursor.", + m_stream + ); + } + +// cout << box.y << endl; + double slot = (box.y - 0.177778) / 0.0738683; + ret.selected = (int8_t)(slot + 0.5); +// cout << "slot = " << (int)ret.selected << endl; + if (ret.selected < 0 || ret.selected >= 10){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "IngredientSession::read_current_page(): Invalid cursor slot.", + m_stream, + screen + ); + } + + // Read the names of every line and the sprite of the selected line. + ImageMatch::ImageMatchResult image_result; + SandwichIngredientReader reader(m_type); + m_dispatcher.run_in_parallel(0, SandwichIngredientReader::INGREDIENT_PAGE_LINES + 1, [&](size_t index){ + if (index < SandwichIngredientReader::INGREDIENT_PAGE_LINES){ + // Read text at line `index` + OCR::StringMatchResult result = reader.read_ingredient_page_with_ocr(*screen, m_stream.logger(), m_language, index); + result.clear_beyond_log10p(SandwichFillingOCR::MAX_LOG10P); + result.clear_beyond_spread(SandwichFillingOCR::MAX_LOG10P_SPREAD); + for (auto& item : result.results){ + ret.item[index].insert(item.second.token); + } + }else{ + // Read current selected icon + image_result = reader.read_ingredient_page_with_icon_matcher(*screen, ret.selected); + image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); + image_result.log(m_stream.logger(), SandwichIngredientReader::MAX_ALPHA); + image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); + } + }); + +#if 1 + do{ + std::set& ocr_result = ret.item[ret.selected]; + + // Special case where OCR fails and image result returns 1 item. + if (ocr_result.empty() || image_result.results.size() == 1){ + ocr_result.insert(image_result.results.begin()->second); + break; + } + + // Find the items in common between the two detection methods. + std::set common; + for (auto& item : image_result.results){ + auto iter = ocr_result.find(item.second); + if (iter != ocr_result.end()){ + common.insert(item.second); + } + } + + if (common.empty()){ + std::set sprite_result; + for(const auto& p : image_result.results){ + sprite_result.insert(p.second); + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "IngredientSession::read_current_page(): Unable to read selected item. OCR and sprite do not agree on any match: ocr " + + set_to_str(ocr_result) + ", sprite " + set_to_str(sprite_result), + m_stream, + screen + ); + } + if (common.size() > 1){ + std::set sprite_result; + for(const auto& p : image_result.results){ + sprite_result.insert(p.second); + } + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "IngredientSession::read_current_page(): Unable to read selected item. Ambiguous result: " + + set_to_str(ocr_result) + ", " + set_to_str(sprite_result), + m_stream, + screen + ); + } + + ocr_result = std::move(common); + }while (false); +#endif + + return ret; + +} +PageIngredients IngredientSession::read_current_page() const{ + return read_screen(m_stream.video().snapshot()); +} + +// Returns true if a desired ingredient is found somewhere on the page. +// "slug" is set the desired ingredient if the cursor is already on it. +bool IngredientSession::run_move_iteration( + std::string& slug, const std::set& ingredients, + const PageIngredients& page +) const{ + size_t current_index = page.selected; + std::map found_ingredients; + for (size_t c = 0; c < SandwichIngredientReader::INGREDIENT_PAGE_LINES; c++){ + for (const std::string& item : page.item[c]){ + auto iter = ingredients.find(item); + if (iter != ingredients.end()){ + found_ingredients[c] = item; + } + } + } + + if (found_ingredients.size() == 0){ + return false; + } + + size_t target_line_index = 0; + if (std::all_of(found_ingredients.begin(), found_ingredients.end(), [&](const auto& p){return p.first <= current_index;})){ + // If the current cursor is below all the found ingredients, + // we should move to the closest ingredient, which is also at the lowest line among found ingredients. + target_line_index = found_ingredients.rbegin()->first; + }else{ + target_line_index = found_ingredients.begin()->first; + } + + const std::string& item = found_ingredients[target_line_index]; + + // Cursor is already on matching ingredient. + if (current_index == target_line_index){ + m_stream.log("Desired ingredient " + item + " is selected!", COLOR_BLUE); + slug = item; + return true; + } + + m_stream.log("Found desired ingredient " + item + " on current page. Moving towards it...", COLOR_BLUE); + + // Move to it. + while (current_index < target_line_index){ + pbf_press_dpad(m_context, DPAD_DOWN, 10, 30); + current_index++; + } + while (current_index > target_line_index){ + pbf_press_dpad(m_context, DPAD_UP, 10, 30); + current_index--; + } + m_context.wait_for_all_requests(); + m_context.wait_for(std::chrono::seconds(1)); + // slug = item; + return true; +} + + +std::string IngredientSession::move_to_ingredient(const std::set& ingredients) const{ + if (ingredients.empty()){ + m_stream.log("No desired ingredients.", COLOR_RED); + return ""; + } + + size_t not_found_count = 0; + while (true){ + m_context.wait_for_all_requests(); + m_context.wait_for(std::chrono::milliseconds(180)); + PageIngredients page = read_current_page(); + std::string found_ingredient; + if (run_move_iteration(found_ingredient, ingredients, page)){ + if (found_ingredient.empty()){ + continue; + }else{ + return found_ingredient; + } + } + + size_t current = page.selected; + if (current == SandwichIngredientReader::INGREDIENT_PAGE_LINES - 1){ + not_found_count++; + if (not_found_count >= 2){ + m_stream.log("Ingredient not found anywhere.", COLOR_RED); + return ""; + }else{ + m_stream.log("End of page reached without finding ingredient. Wrapping back to beginning.", COLOR_ORANGE); + pbf_press_dpad(m_context, DPAD_DOWN, 20, 105); + continue; + } + } + + m_stream.log("Ingredient not found on current page. Scrolling down.", COLOR_ORANGE); + + // Not found on page. Scroll to next screen + pbf_press_dpad(m_context, DPAD_RIGHT, 10, 30); + + // while (current < INGREDIENT_PAGE_LINES - 1){ + // pbf_press_dpad(m_context, DPAD_DOWN, 10, 30); + // current++; + // } + + } + return ""; +} + + +void IngredientSession::add_ingredients( + VideoStream& stream, ProControllerContext& context, + std::map&& ingredients +){ + // "ingredients" will be what we still need. + // Each time we add an ingredient, it will be removed from the map. + // Loop until there's nothing left. + while (!ingredients.empty()){ + std::set remaining; + for (const auto& item : ingredients){ + remaining.insert(item.first); + } + + std::string found = this->move_to_ingredient(remaining); + if (found.empty()){ + const SandwichIngredientNames& name = get_ingredient_name(*remaining.begin()); + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to find ingredient: \"" + name.display_name() + "\" - Did you run out?", + stream + ); + } + + const SandwichIngredientNames& name = get_ingredient_name(found); + stream.log("Add " + name.display_name() + " as ingredient", COLOR_BLUE); + + // If you don't have enough ingredient, it errors out instead of proceeding + // with less than the desired quantity. + auto iter = ingredients.find(found); + SandwichIngredientReader reader(m_type); + while (iter->second > 0){ + bool ingredient_added = false; + for (int attempt = 0; attempt < 5; attempt++){ + pbf_press_button(context, BUTTON_A, 20, 105); + context.wait_for_all_requests(); + VideoSnapshot image = stream.video().snapshot(); + ImageMatch::ImageMatchResult image_result = + reader.read_confirmed_list_with_icon_matcher(image, m_num_confirmed); + image_result.clear_beyond_spread(SandwichIngredientReader::ALPHA_SPREAD); + image_result.clear_beyond_alpha(SandwichIngredientReader::MAX_ALPHA); + image_result.log(stream.logger(), SandwichIngredientReader::MAX_ALPHA); + if (image_result.results.size() > 0){ // confirmed that the ingredient was added + stream.overlay().add_log("Added " + name.display_name()); + m_num_confirmed++; + ingredient_added = true; + iter->second--; + break; + } + } + + if (!ingredient_added){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to add ingredient: \"" + name.display_name() + "\" - Did you run out?", + stream + ); + } + } + ingredients.erase(iter); + } +} + + + +void add_sandwich_ingredients( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language, + std::map&& fillings, + std::map&& condiments +){ + { + IngredientSession session(dispatcher, stream, context, language, SandwichIngredientType::FILLING); + session.add_ingredients(stream, context, std::move(fillings)); + pbf_press_button(context, BUTTON_PLUS, 20, 230); + } + + { + IngredientSession session(dispatcher, stream, context, language, SandwichIngredientType::CONDIMENT); + // If there are herbs, we search first from bottom + if (std::any_of(condiments.begin(), condiments.end(), [&](const auto& p){return p.first.find("herba") != std::string::npos;})){ + pbf_press_dpad(context, DPAD_UP, 20, 105); + } + session.add_ingredients(stream, context, std::move(condiments)); + pbf_press_button(context, BUTTON_PLUS, 20, 230); + } + + pbf_mash_button(context, BUTTON_A, 125); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h index 1d29831119..ee82027936 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h @@ -1,94 +1,94 @@ -/* Ingredient Session - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_IngredientSession_H -#define PokemonAutomation_PokemonSV_IngredientSession_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" - -namespace PokemonAutomation{ - class AsyncDispatcher; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class SandwichIngredientReader; - - - - -struct PageIngredients{ - // the line index of the current selected ingredient, < INGREDIENT_PAGE_LINES - int8_t selected = -1; - std::set item[SandwichIngredientReader::INGREDIENT_PAGE_LINES]; -}; - - -class IngredientSession{ -public: - ~IngredientSession(); - IngredientSession( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language, SandwichIngredientType type - ); - - // Move to any ingredient in the set. Returns the ingredient it moved to. - // Returns empty string if not found. - std::string move_to_ingredient(const std::set& ingredients) const; - - void add_ingredients( - VideoStream& stream, ProControllerContext& context, - std::map&& ingredients - ); - - -public: - PageIngredients read_screen(std::shared_ptr screenshot) const; - PageIngredients read_current_page() const; - bool run_move_iteration( - std::string& slug, const std::set& ingredients, - const PageIngredients& page - ) const; - - -private: - AsyncDispatcher& m_dispatcher; - VideoStream& m_stream; - ProControllerContext& m_context; - Language m_language; - VideoOverlaySet m_overlays; - SandwichIngredientType m_type; - int8_t m_num_confirmed; - GradientArrowDetector m_arrow; -}; - - - -// Starting from the top of the fillings menu, gather all the ingredients. -// When this function returns, the game will be entering the phase where the -// user must stack the fillings. -// If any ingredient is not found or insuffient, it will OperationFailedException::fire. -void add_sandwich_ingredients( - AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - Language language, - std::map&& fillings, // {slug, quantity} - std::map&& condiments -); - - - - -} -} -} -#endif +/* Ingredient Session + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_IngredientSession_H +#define PokemonAutomation_PokemonSV_IngredientSession_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" + +namespace PokemonAutomation{ + class AsyncDispatcher; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class SandwichIngredientReader; + + + + +struct PageIngredients{ + // the line index of the current selected ingredient, < INGREDIENT_PAGE_LINES + int8_t selected = -1; + std::set item[SandwichIngredientReader::INGREDIENT_PAGE_LINES]; +}; + + +class IngredientSession{ +public: + ~IngredientSession(); + IngredientSession( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language, SandwichIngredientType type + ); + + // Move to any ingredient in the set. Returns the ingredient it moved to. + // Returns empty string if not found. + std::string move_to_ingredient(const std::set& ingredients) const; + + void add_ingredients( + VideoStream& stream, ProControllerContext& context, + std::map&& ingredients + ); + + +public: + PageIngredients read_screen(std::shared_ptr screenshot) const; + PageIngredients read_current_page() const; + bool run_move_iteration( + std::string& slug, const std::set& ingredients, + const PageIngredients& page + ) const; + + +private: + AsyncDispatcher& m_dispatcher; + VideoStream& m_stream; + ProControllerContext& m_context; + Language m_language; + VideoOverlaySet m_overlays; + SandwichIngredientType m_type; + int8_t m_num_confirmed; + GradientArrowDetector m_arrow; +}; + + + +// Starting from the top of the fillings menu, gather all the ingredients. +// When this function returns, the game will be entering the phase where the +// user must stack the fillings. +// If any ingredient is not found or insuffient, it will OperationFailedException::fire. +void add_sandwich_ingredients( + AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + Language language, + std::map&& fillings, // {slug, quantity} + std::map&& condiments +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp index a3932aaff2..e4edf76ae1 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.cpp @@ -1,97 +1,97 @@ -/* Sandwich Maker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV_SandwichMaker.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -SandwichMaker_Descriptor::SandwichMaker_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:SandwichMaker", - STRING_POKEMON + " SV", "Sandwich Maker", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/SandwichMaker.md", - "Make a sandwich of your choice.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - -struct SandwichMaker_Descriptor::Stats : public StatsTracker{ - Stats() - : sandwiches(m_stats["Sandwiches"]) - , errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Sandwiches"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& sandwiches; - std::atomic& errors; -}; - -std::unique_ptr SandwichMaker_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -SandwichMaker::SandwichMaker() - : SANDWICH_OPTIONS( - "Sandwich Options", - nullptr, - BaseRecipe::non_shiny, - false, - GroupOption::EnableMode::ALWAYS_ENABLED - ) - , NUM_SANDWICHES( - "Number of sandwiches to make:
Repeatedly make the same sandwich.", - LockMode::UNLOCK_WHILE_RUNNING, - 1, 1, 1000 - ) - , GO_HOME_WHEN_DONE(false) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(SANDWICH_OPTIONS); - PA_ADD_OPTION(NUM_SANDWICHES); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void SandwichMaker::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - SandwichMaker_Descriptor::Stats& stats = env.current_stats(); - - for (int i = 0; i < NUM_SANDWICHES; i++){ - env.console.log("Making sandwich number: " + std::to_string(i+1), COLOR_ORANGE); - stats.sandwiches++; - env.update_stats(); - make_sandwich_option(env, env.console, context, SANDWICH_OPTIONS); - enter_sandwich_recipe_list(env.program_info(), env.console, context); - } - - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} - +/* Sandwich Maker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV_SandwichMaker.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +SandwichMaker_Descriptor::SandwichMaker_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:SandwichMaker", + STRING_POKEMON + " SV", "Sandwich Maker", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/SandwichMaker.md", + "Make a sandwich of your choice.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + +struct SandwichMaker_Descriptor::Stats : public StatsTracker{ + Stats() + : sandwiches(m_stats["Sandwiches"]) + , errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Sandwiches"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& sandwiches; + std::atomic& errors; +}; + +std::unique_ptr SandwichMaker_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +SandwichMaker::SandwichMaker() + : SANDWICH_OPTIONS( + "Sandwich Options", + nullptr, + BaseRecipe::non_shiny, + false, + GroupOption::EnableMode::ALWAYS_ENABLED + ) + , NUM_SANDWICHES( + "Number of sandwiches to make:
Repeatedly make the same sandwich.", + LockMode::UNLOCK_WHILE_RUNNING, + 1, 1, 1000 + ) + , GO_HOME_WHEN_DONE(false) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(SANDWICH_OPTIONS); + PA_ADD_OPTION(NUM_SANDWICHES); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void SandwichMaker::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + SandwichMaker_Descriptor::Stats& stats = env.current_stats(); + + for (int i = 0; i < NUM_SANDWICHES; i++){ + env.console.log("Making sandwich number: " + std::to_string(i+1), COLOR_ORANGE); + stats.sandwiches++; + env.update_stats(); + make_sandwich_option(env, env.console, context, SANDWICH_OPTIONS); + enter_sandwich_recipe_list(env.program_info(), env.console, context); + } + + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h index c2e4273d70..127e979b30 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichMaker.h @@ -1,48 +1,48 @@ -/* Sandwich Maker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichMaker_H -#define PokemonAutomation_PokemonSV_SandwichMaker_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class SandwichMaker_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SandwichMaker_Descriptor(); - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class SandwichMaker : public SingleSwitchProgramInstance{ -public: - SandwichMaker(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SandwichMakerOption SANDWICH_OPTIONS; - SimpleIntegerOption NUM_SANDWICHES; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Sandwich Maker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichMaker_H +#define PokemonAutomation_PokemonSV_SandwichMaker_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class SandwichMaker_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SandwichMaker_Descriptor(); + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class SandwichMaker : public SingleSwitchProgramInstance{ +public: + SandwichMaker(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SandwichMakerOption SANDWICH_OPTIONS; + SimpleIntegerOption NUM_SANDWICHES; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp index 387f59ae13..638db45390 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.cpp @@ -1,1356 +1,1356 @@ -/* Sandwich Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Concurrency/AsyncDispatcher.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h" -#include "PokemonSV/Resources/PokemonSV_FillingsCoordinates.h" -#include "PokemonSV/Resources/PokemonSV_Ingredients.h" -#include "PokemonSV_SandwichRoutines.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h" -#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h" - -// #include -// using std::cout; -// using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -namespace{ - const ImageFloatBox HAND_INITIAL_BOX{0.440, 0.455, 0.112, 0.179}; - const ImageFloatBox INGREDIENT_BOX{0.455, 0.130, 0.090, 0.030}; - -void wait_for_initial_hand( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - SandwichHandWatcher free_hand(SandwichHandType::FREE, HAND_INITIAL_BOX); - int ret = wait_until(stream, context, std::chrono::seconds(30), {free_hand}); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "FreeHandNotDetected", - "Cannot detect hand at start of making a sandwich." - ); - } -} - -} // anonymous namespace - -bool enter_sandwich_recipe_list( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - context.wait_for_all_requests(); - stream.log("Opening sandwich menu at picnic table."); - - // Firt, try pressing button A to bring up the menu to make sandwich - pbf_press_button(context, BUTTON_A, 20, 80); - - WallClock start = current_time(); - bool opened_table_menu = false; - while(true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(1)){ - dump_image_and_throw_recoverable_exception( - info, stream, "FailToSandwich", - "enter_sandwich_recipe_list(): Failed to open sandwich menu after 1 minute." - ); - } - - PicnicWatcher picnic_watcher; - GradientArrowWatcher sandwich_arrow(COLOR_YELLOW, GradientArrowType::RIGHT, {0.551, 0.311, 0.310, 0.106}); - GradientArrowWatcher recipe_arrow(COLOR_YELLOW, GradientArrowType::DOWN, {0.103, 0.074, 0.068, 0.085}); - AdvanceDialogWatcher dialog_watcher(COLOR_RED); - - const int ret = wait_until( - stream, context, - std::chrono::seconds(30), - {picnic_watcher, sandwich_arrow, recipe_arrow, dialog_watcher} - ); - switch (ret){ - case 0: - stream.log("Detected picnic. Maybe button A press dropped."); - // walk forward and press A again - pbf_move_left_joystick(context, 128, 0, 100, 40); - pbf_press_button(context, BUTTON_A, 20, 80); - continue; - case 1: - stream.log("Detected \"make a sandwich\" menu item selection arrrow."); - stream.overlay().add_log("Open sandwich recipes", COLOR_WHITE); - opened_table_menu = true; - pbf_press_button(context, BUTTON_A, 20, 100); - continue; - case 2: - stream.log("Detected recipe selection arrow."); - context.wait_for(std::chrono::seconds(1)); // wait one second to make sure the menu is fully loaded. - return true; - case 3: - stream.log("Detected advance dialog."); - if (opened_table_menu){ - stream.log("Advance dialog after \"make a sandwich\" menu item. No ingredients.", COLOR_RED); - stream.overlay().add_log("No ingredient!", COLOR_RED); - return false; - } - pbf_press_button(context, BUTTON_A, 20, 80); - continue; - default: - dump_image_and_throw_recoverable_exception(info, stream, "NotEnterSandwichList", - "enter_sandwich_recipe_list(): No recognized state after 60 seconds."); - } - } -} - - -bool select_sandwich_recipe( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t target_sandwich_ID -){ - context.wait_for_all_requests(); - stream.log("Choosing sandwich recipe: " + std::to_string(target_sandwich_ID)); - stream.overlay().add_log("Search recipe " + std::to_string(target_sandwich_ID), COLOR_WHITE); - - SandwichRecipeNumberDetector recipe_detector(stream.logger()); - SandwichRecipeSelectionWatcher selection_watcher; - - VideoOverlaySet overlay_set(stream.overlay()); - recipe_detector.make_overlays(overlay_set); - selection_watcher.make_overlays(overlay_set); - - bool found_recipe = false; - int max_move_down_list_attempts = 100; // There are 151 total recipes, so 76 rows. - for (int move_down_list_attempt = 0; move_down_list_attempt < max_move_down_list_attempts; move_down_list_attempt++){ - context.wait_for(std::chrono::milliseconds(200)); - context.wait_for_all_requests(); - - auto snapshot = stream.video().snapshot(); - size_t recipe_IDs[6] = {0, 0, 0, 0, 0, 0}; - recipe_detector.detect_recipes(snapshot, recipe_IDs); - { - std::ostringstream os; - os << "Recipe IDs detected: "; - for(int i = 0; i < 6; i++){ - os << recipe_IDs[i] << ", "; - } - stream.log(os.str()); - } - - size_t min_ID = 300; - for(int i = 0; i < 6; i++){ - if (recipe_IDs[i] > 0 && recipe_IDs[i] < min_ID){ - min_ID = recipe_IDs[i]; - } - } - if (min_ID == 300){ - min_ID = 0; // set case of no recipe ID detected to be 0 min_ID - } - size_t max_ID = *std::max_element(recipe_IDs, recipe_IDs+6); - stream.log("min, max IDs " + std::to_string(min_ID) + ", " + std::to_string(max_ID)); - - if (0 < min_ID && min_ID <= target_sandwich_ID && target_sandwich_ID <= max_ID){ - // target is in this page! - - int target_cell = -1; - for(int i = 0; i < 6; i++){ - if (recipe_IDs[i] == target_sandwich_ID){ - target_cell = i; - break; - } - } - if (target_cell == -1){ // not targe recipe found in this page, probably not enough ingredients - stream.log("Not enough ingredients for target recipe.", COLOR_RED); - stream.overlay().add_log("Not enough ingredients", COLOR_RED); - return false; - } - - stream.log("found recipe in the current page, cell " + std::to_string(target_cell)); - - int ret = wait_until(stream, context, std::chrono::seconds(10), {selection_watcher}); - int selected_cell = selection_watcher.selected_recipe_cell(); - if (ret < 0 || selected_cell < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "RecipeSelectionArrowNotDetected", - "select_sandwich_recipe(): Cannot detect recipe selection arrow." - ); - } - - stream.log("Current selected cell " + std::to_string(selected_cell)); - - if (target_cell == selected_cell){ - // Selected target recipe! - stream.log("Found recipe at cell " + std::to_string(selected_cell)); - stream.overlay().add_log("Found recipe", COLOR_WHITE); - found_recipe = true; - break; - }else if (target_cell == selected_cell + 1){ - stream.log("Move to the right column."); - // Target is in a different column - // Move cursor right. - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - continue; - } - // else, continue moving down the list - } - - // target sandwich recipe is still below the current displayed recipes. - // Move down the list. - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } // end for moving down the recipe list - - overlay_set.clear(); - - if (found_recipe){ - // Press A to enter the pick selection - pbf_press_button(context, BUTTON_A, 30, 100); -// context.wait_for_all_requests(); - - SandwichIngredientArrowWatcher pick_selection(0, COLOR_YELLOW); - while(true){ - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, std::chrono::seconds(3), - {selection_watcher, pick_selection} - ); - - if (ret == 0){ - stream.log("Detected recipe selection. Dropped Button A?"); - pbf_press_button(context, BUTTON_A, 30, 100); - continue; - }else if (ret == 1){ - stream.log("Detected pick selection."); - pbf_press_button(context, BUTTON_A, 30, 100); - continue; - }else{ - stream.log("Entered sandwich minigame."); - break; - } - } - return true; - } - - // we cannot find the receipt - stream.log("Max list traverse attempt reached. Target recipe not found", COLOR_RED); - stream.overlay().add_log("Recipe not found", COLOR_RED); - - return false; -} - -namespace{ - -// expand the hand bounding box so that the hand watcher can pick the hand in the next iteration -ImageFloatBox expand_box(const ImageFloatBox& box){ - const double x = std::max(0.0, box.x - box.width * 1.5); - const double y = std::max(0.0, box.y - box.height * 1.5); - const double width = std::min(box.width*4, 1.0 - x); - const double height = std::min(box.height*4, 1.0 - y); - return ImageFloatBox(x, y, width, height); -} - -ImageFloatBox hand_location_to_box(const std::pair& loc){ - const double hand_width = 0.071, hand_height = 0.106; - return {loc.first - hand_width/2, loc.second - hand_height/2, hand_width, hand_height}; -} - -std::string box_to_string(const ImageFloatBox& box){ - std::ostringstream os; - os << "(" << box.x << ", " << box.y << ", " << box.width << ", " << box.height << ")"; - return os.str(); -} - -/* -- center the cursor by moving the cursor to the edge of the screen, then away from the edge. -- then search the whole screen for the sandwich hand, instead of just the box, and -update the location of the sandwich hand -- return true if successful. else throw an exception -*/ -bool move_then_recover_sandwich_hand_position( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - SandwichHandType& hand_type, - SandwichHandWatcher& hand_watcher, - AsyncCommandSession& move_session -){ - - stream.log("center the cursor: move towards bottom right, then left slightly."); - uint16_t num_ticks_to_move_1 = TICKS_PER_SECOND*4; - uint16_t num_ticks_to_move_2 = 100; - - // center the cursor - if(SandwichHandType::FREE == hand_type){ - // move to bottom right corner, - pbf_move_left_joystick(context, 255, 255, num_ticks_to_move_1, 100); - // move to left slightly - pbf_move_left_joystick(context, 0, 128, num_ticks_to_move_2, 100); - context.wait_for_all_requests(); - } - else if(SandwichHandType::GRABBING == hand_type){ - // center the cursor while holding the A button, so you don't drop the ingredient. - - uint16_t num_ticks_to_move_total = num_ticks_to_move_1 + num_ticks_to_move_2; - uint16_t num_ticks_to_wait = num_ticks_to_move_total + TICKS_PER_SECOND; // add one extra second of waiting - uint16_t num_miliseconds_to_wait = (num_ticks_to_wait*1000)/TICKS_PER_SECOND; - uint16_t num_ticks_to_hold_A = num_ticks_to_wait + TICKS_PER_SECOND*10; // hold A for extra 10 seconds - // the A button hold will be overwritten on the next move_session.dispatch, in the main function - - move_session.dispatch([&](ProControllerContext& context){ - // move to bottom right corner, while holding A - pbf_controller_state(context, BUTTON_A, DPAD_NONE, 255, 255, 128, 128, num_ticks_to_move_1); - - // move to left slightly, while holding A - pbf_controller_state(context, BUTTON_A, DPAD_NONE, 0, 128, 128, 128, num_ticks_to_move_2); - - // keep holding A. - pbf_press_button(context, BUTTON_A, num_ticks_to_hold_A, 0); - // pbf_controller_state(context, BUTTON_A, DPAD_NONE, 128, 128, 128, 128, 3000); - }); - - // - wait long enough for the cursor movement to finish, before we try image matching - // - wait_for_all_requests doesn't work since we want to still hold the A button. - // - this is a workaround until there is a way to wait for a subset of a bunch of overlapping buttons to finish - // - need to make sure the A button hold is long enough to last past this wait. - context.wait_for(Milliseconds(num_miliseconds_to_wait)); - } - - const VideoSnapshot& frame = stream.video().snapshot(); - stream.log("Try to recover sandwich hand location."); - if(hand_watcher.recover_sandwich_hand_position(frame)){ - // sandwich hand detected. - return true; - } - - // if still can't find the sandwich hand, throw a exception - dump_image_and_throw_recoverable_exception( - info, stream, - SANDWICH_HAND_TYPE_NAMES(hand_type) + "SandwichHandNotDetected", - "move_sandwich_hand(): Cannot detect " + SANDWICH_HAND_TYPE_NAMES(hand_type) + " hand." - ); -} - -// return true if the current plate is empty. -// i.e. the current plate label is not yellow. -// Assumes that we are in a grabbing state. -bool check_plate_empty(VideoStream& stream, SandwichPlateDetector::Side target_plate_label, Language language){ - auto screen = stream.video().snapshot(); - // screen.frame->save("test.png"); - - // switch(target_plate_label){ - // case SandwichPlateDetector::Side::LEFT: - // cout << "left" << endl; - // break; - // case SandwichPlateDetector::Side::MIDDLE: - // cout << "middle" << endl; - // break; - // case SandwichPlateDetector::Side::RIGHT: - // cout << "right" << endl; - // break; - // default: - // break; - // } - - stream.log("Check if the plate is empty."); - - SandwichPlateDetector plate_detector = SandwichPlateDetector(stream.logger(), COLOR_RED, language, target_plate_label); - - return !plate_detector.is_label_yellow(screen); -} - -struct HandMoveData{ - ImageFloatBox end_box; - bool plate_empty; -}; - - -/* -- moves the sandwich hand from start_box to end_box -- It detects the location of the sandwich hand, from within the bounds of the last frame's -expanded_hand_bb (i.e. m_box field in SandwichHandLocator). -Then updates the current location of expanded_hand_bb. -Then moves the sandwich hand closer towards end_box. - */ -HandMoveData move_sandwich_hand_and_check_if_plates_empty( - const ProgramInfo& info, - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - SandwichHandType hand_type, - bool pressing_A, - const ImageFloatBox& start_box, - const ImageFloatBox& end_box, - SandwichPlateDetector::Side target_plate_label = SandwichPlateDetector::Side::NOT_APPLICABLE, - Language language = Language::None -){ - context.wait_for_all_requests(); - stream.log("Start moving sandwich hand: " + SANDWICH_HAND_TYPE_NAMES(hand_type) - + " start box " + box_to_string(start_box) + " end box " + box_to_string(end_box)); - - uint8_t joystick_x = 128; - uint8_t joystick_y = 128; - - SandwichHandWatcher hand_watcher(hand_type, start_box); - - // A session that creates a new thread to send button commands to controller - AsyncCommandSession move_session( - context, - stream.logger(), - dispatcher, - context.controller() - ); - - if (pressing_A){ - move_session.dispatch([](ProControllerContext& context){ - pbf_controller_state(context, BUTTON_A, DPAD_NONE, 128, 128, 128, 128, 3000); - }); - } - - const std::pair target_loc(end_box.x + end_box.width/2, end_box.y + end_box.height/2); - - std::pair last_loc(-1, -1); - std::pair speed(-1, -1); - WallClock cur_time, last_time; - VideoOverlaySet overlay_set(stream.overlay()); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - #if 0 - // to intentionally trigger failures in hand detection, for testing recovery - if (SandwichHandType::FREE == hand_type){ - std::pair hand_location(1.0, 1.0); - const ImageFloatBox hand_bb_debug = hand_location_to_box(hand_location); - const ImageFloatBox expanded_hand_bb_debug = expand_box(hand_bb_debug); - hand_watcher.change_box(expanded_hand_bb_debug); - overlay_set.clear(); - overlay_set.add(COLOR_RED, hand_bb_debug); - overlay_set.add(COLOR_BLUE, expanded_hand_bb_debug); - pbf_move_left_joystick(context, 0, 0, TICKS_PER_SECOND*5, 100); // move hand to screen edge - context.wait_for_all_requests(); - } - #endif - - #if 0 - // to intentionally trigger failures in hand detection, for testing recovery - // move hand to edge of screen, while still holding A - if (SandwichHandType::GRABBING == hand_type){ - pbf_controller_state(context, BUTTON_A, DPAD_NONE, 0, 0, 128, 128, TICKS_PER_SECOND*5); - pbf_press_button(context, BUTTON_A, 200, 0); - // pbf_controller_state(context, BUTTON_A, DPAD_NONE, 128, 128, 128, 128, 100); - } - #endif - } - - while(true){ - int ret = wait_until(stream, context, std::chrono::seconds(5), {hand_watcher}); - if (ret < 0){ - // - the sandwich hand might be at the edge of the screen, so move it to the middle - // and try searching the entire screen again - // - move hand to bottom-right, then to the middle - stream.log( - "Failed to detect sandwich hand. It may be at the screen's edge. " - "Try moving the hand to the middle of the screen and try searching again." - ); - - if(move_then_recover_sandwich_hand_position( - info, stream, context, hand_type, hand_watcher, move_session - )){ - continue; - } - - } - - auto cur_loc = hand_watcher.location(); - stream.log("Hand location: " + std::to_string(cur_loc.first) + ", " + std::to_string(cur_loc.second)); - cur_time = current_time(); - - const ImageFloatBox hand_bb = hand_location_to_box(cur_loc); - const ImageFloatBox expanded_hand_bb = expand_box(hand_bb); - hand_watcher.change_box(expanded_hand_bb); - - overlay_set.clear(); - overlay_set.add(COLOR_RED, hand_bb); - overlay_set.add(COLOR_BLUE, expanded_hand_bb); - - std::pair dif(target_loc.first - cur_loc.first, target_loc.second - cur_loc.second); - // console.log("float diff to target: " + std::to_string(dif.first) + ", " + std::to_string(dif.second)); - - - // Reached the Target - if (std::fabs(dif.first) < end_box.width/2 && std::fabs(dif.second) < end_box.height/2){ - stream.log(SANDWICH_HAND_TYPE_NAMES(hand_type) + " hand reached target."); - bool plate_empty = false; - - // check if the plate is empty. but only if the target_plate_label isn't NOT_APPLICABLE. - if (target_plate_label != SandwichPlateDetector::Side::NOT_APPLICABLE){ - plate_empty = check_plate_empty(stream, target_plate_label, language); - } - - move_session.stop_session_and_rethrow(); // Stop the commands - if (hand_type == SandwichHandType::GRABBING){ - // wait for some time to let hand release ingredient - context.wait_for(std::chrono::milliseconds(100)); - } - return {hand_bb, plate_empty}; - } - - // Assume screen width is 16.0, then the screen height is 9.0 - std::pair real_dif(dif.first * 16, dif.second * 9); - double distance = std::sqrt(real_dif.first * real_dif.first + real_dif.second * real_dif.second); - // console.log("scaled diff to target: " + std::to_string(real_dif.first) + ", " + std::to_string(real_dif.second) - // + " distance " + std::to_string(distance)); - - // Build a P-D controller! - - // We assume for a screen distance of 4 (1/4 of the width), we can use max joystick push, 128. - // So for distance of value 1.0, we multiply by 32 to get joystick push - double target_joystick_push = std::min(distance * 32, 128.0); - - std::pair push(real_dif.first * target_joystick_push / distance, real_dif.second * target_joystick_push / distance); - // console.log("push force " + std::to_string(push.first) + ", " + std::to_string(push.second)); - - if (last_loc.first < 0){ - speed = std::make_pair(0.0, 0.0); - }else{ - std::chrono::microseconds time = std::chrono::duration_cast(cur_time - last_time); - double time_s = time.count() / 1000000.0; - std::pair moved((cur_loc.first - last_loc.first) * 16, (cur_loc.second - last_loc.second) * 9); - - // Currently set to zero damping as it seems we don't need them for now - double damping_factor = 0.0; - double damping_multiplier = (-1.0) * damping_factor / time_s; - std::pair damped_push_offset(moved.first * damping_multiplier, moved.second * damping_multiplier); - - push.first += damped_push_offset.first; - push.second += damped_push_offset.second; - } - - joystick_x = (uint8_t) std::max(std::min(int(push.first + 0.5) + 128, 255), 0); - joystick_y = (uint8_t) std::max(std::min(int(push.second + 0.5) + 128, 255), 0); - // console.log("joystick push " + std::to_string(joystick_x) + ", " + std::to_string(joystick_y)); - - // Dispatch a new series of commands that overwrites the last ones - move_session.dispatch([&](ProControllerContext& context){ - if (pressing_A){ - // Note: joystick_x and joystick_y must be defined to outlive `move_session`. -// pbf_controller_state(context, BUTTON_A, DPAD_NONE, joystick_x, joystick_y, 128, 128, 20); - ssf_press_button(context, BUTTON_A, 0ms, 8000ms, 0ms); - } - pbf_move_left_joystick(context, joystick_x, joystick_y, 20, 0); - }); - - stream.log("Moved joystick"); - - last_loc = cur_loc; - last_time = cur_time; - context.wait_for(std::chrono::milliseconds(80)); - } -} - -ImageFloatBox move_sandwich_hand( - const ProgramInfo& info, - AsyncDispatcher& dispatcher, - VideoStream& stream, - ProControllerContext& context, - SandwichHandType hand_type, - bool pressing_A, - const ImageFloatBox& start_box, - const ImageFloatBox& end_box -){ - return move_sandwich_hand_and_check_if_plates_empty( - info, dispatcher, - stream, context, - hand_type, pressing_A, - start_box, end_box, - SandwichPlateDetector::Side::NOT_APPLICABLE, - Language::None - ).end_box; -} - -} // end anonymous namespace - -void finish_sandwich_eating( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - stream.overlay().add_log("Eating", COLOR_WHITE); - PicnicWatcher picnic_watcher; - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for(int i = 0; i < 20; i++){ - pbf_press_button(context, BUTTON_A, 20, 3*TICKS_PER_SECOND - 20); - } - }, - {picnic_watcher} - ); - if (ret < 0){ - dump_image_and_throw_recoverable_exception( - info, stream, "PicnicNotDetected", - "finish_sandwich_eating(): cannot detect picnic after 60 seconds." - ); - } - stream.overlay().add_log("Finish eating", COLOR_WHITE); - stream.log("Finished eating sandwich. Back at picnic."); - context.wait_for(std::chrono::seconds(1)); -} - -namespace{ - -void repeat_press_until( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - std::function button_press, - const std::vector& callbacks, - const std::string &error_name, const std::string &error_message, - std::chrono::milliseconds detection_timeout = std::chrono::seconds(5), - size_t max_presses = 10, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - button_press(); - for(size_t i_try = 0; i_try < max_presses; i_try++){ - context.wait_for_all_requests(); - const int ret = wait_until(stream, context, detection_timeout, callbacks); - if (ret >= 0){ - return; - } - button_press(); - } - - dump_image_and_throw_recoverable_exception( - info, stream, "IngredientListNotDetected", - "enter_custom_sandwich_mode(): cannot detect ingredient list after 50 seconds." - ); -} - -void repeat_button_press_until( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - Button button, uint16_t hold_ticks, uint16_t release_ticks, - const std::vector& callbacks, - const std::string &error_name, const std::string &error_message, - std::chrono::milliseconds iteration_length = std::chrono::seconds(5), - size_t max_presses = 10, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - const std::chrono::milliseconds button_time = std::chrono::milliseconds((hold_ticks + release_ticks) * (1000 / TICKS_PER_SECOND)); - repeat_press_until( - info, stream, context, - [&](){ - pbf_press_button(context, button, hold_ticks, release_ticks); - }, - callbacks, error_name, error_message, iteration_length - button_time, max_presses, - default_video_period, default_audio_period - ); -} - -void repeat_dpad_press_until( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - DpadPosition dpad_position, uint16_t hold_ticks, uint16_t release_ticks, - const std::vector& callbacks, - const std::string &error_name, const std::string &error_message, - std::chrono::milliseconds iteration_length = std::chrono::seconds(5), - size_t max_presses = 10, - std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), - std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) -){ - const std::chrono::milliseconds button_time = std::chrono::milliseconds((hold_ticks + release_ticks) * (1000 / TICKS_PER_SECOND)); - repeat_press_until( - info, stream, context, - [&](){ pbf_press_dpad(context, dpad_position, hold_ticks, release_ticks); }, - callbacks, error_name, error_message, iteration_length - button_time, max_presses, - default_video_period, default_audio_period - ); -} - - -} // anonymous namespace - - -void enter_custom_sandwich_mode( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -){ - context.wait_for_all_requests(); - stream.log("Entering custom sandwich mode."); - stream.overlay().add_log("Custom sandwich", COLOR_WHITE); - - SandwichIngredientArrowWatcher ingredient_selection_arrow(0, COLOR_YELLOW); - repeat_button_press_until( - info, stream, context, BUTTON_X, 40, 80, {ingredient_selection_arrow}, - "IngredientListNotDetected", "enter_custom_sandwich_mode(): cannot detect ingredient list after 50 seconds." - ); -} - -namespace{ - -void finish_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context -){ - stream.log("Finish determining ingredients for two-sweet-herb sandwich."); - stream.overlay().add_log("Finish picking ingredients", COLOR_WHITE); - - wait_for_initial_hand(info, stream, context); - - stream.overlay().add_log("Start making sandwich", COLOR_WHITE); - move_sandwich_hand(info, dispatcher, stream, context, SandwichHandType::FREE, false, HAND_INITIAL_BOX, INGREDIENT_BOX); - // Mash button A to pick and drop ingredients, upper bread and pick. - // Egg Power 3 is applied with only two sweet herb condiments! - pbf_mash_button(context, BUTTON_A, 8 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - stream.overlay().add_log("Built sandwich", COLOR_WHITE); -} - -} // anonymous namespace - -void make_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, - EggSandwichType sandwich_type, size_t sweet_herb_index_last, size_t salty_herb_index_last, size_t bitter_herb_index_last -){ - // The game has at most 5 herbs, in the order of sweet, salty, sour, bitter, spicy: - if (sweet_herb_index_last >= 5){ // sweet index can only be: 0, 1, 2, 3, 4 - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Invalid sweet herb index: " + std::to_string(sweet_herb_index_last) - ); - } - if (salty_herb_index_last >= 4){ // 0, 1, 2, 3 - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Invalid salty herb index: " + std::to_string(salty_herb_index_last) - ); - } - if (bitter_herb_index_last >= 2){ // 0, 1 - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Invalid bitter herb index: " + std::to_string(bitter_herb_index_last) - ); - } - - if (sandwich_type == EggSandwichType::SALTY_SWEET_HERBS && salty_herb_index_last >= sweet_herb_index_last){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Invalid salty and sweet herb indices: " + std::to_string(salty_herb_index_last) + ", " + std::to_string(sweet_herb_index_last) - ); - } - if (sandwich_type == EggSandwichType::BITTER_SWEET_HERBS && bitter_herb_index_last >= sweet_herb_index_last){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Invalid bitter and sweet herb indices: " + std::to_string(bitter_herb_index_last) + ", " + std::to_string(sweet_herb_index_last) - ); - } - - { - // Press button A to add first filling, assumed to be lettuce - DeterminedSandwichIngredientWatcher filling_watcher(SandwichIngredientType::FILLING, 0); - repeat_button_press_until( - info, stream, context, BUTTON_A, 40, 50, {filling_watcher}, - "DeterminedIngredientNotDetected", "make_two_herbs_sandwich(): cannot detect determined lettuce after 50 seconds." - ); - } - - { - // Press button + to go to condiments page - SandwichCondimentsPageWatcher condiments_page_watcher; - repeat_button_press_until( - info, stream, context, BUTTON_PLUS, 40, 60, {condiments_page_watcher}, - "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect condiments page after 50 seconds." - ); - } - - size_t first_herb_index_last = 0; - switch(sandwich_type){ - case EggSandwichType::TWO_SWEET_HERBS: - first_herb_index_last = sweet_herb_index_last; - break; - case EggSandwichType::SALTY_SWEET_HERBS: - first_herb_index_last = salty_herb_index_last; - break; - case EggSandwichType::BITTER_SWEET_HERBS: - first_herb_index_last = bitter_herb_index_last; - break; - default: - throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, - "Invalid EggSandwichType for make_two_herbs_sandwich()"); - } - - auto move_one_up_to_row = [&](size_t row){ - stream.log("Move arrow to row " + std::to_string(row)); - SandwichIngredientArrowWatcher arrow(row); - repeat_dpad_press_until(info, stream, context, DPAD_UP, 10, 30, {arrow}, "IngredientArrowNotDetected", - "make_two_herbs_sandwich(): cannot detect ingredient selection arrow at row " + std::to_string(row) + " after 50 seconds." - ); - }; - - auto press_a_to_determine_herb = [&](size_t herb_index){ - DeterminedSandwichIngredientWatcher herb_watcher(SandwichIngredientType::CONDIMENT, herb_index); - repeat_button_press_until( - info, stream, context, BUTTON_A, 40, 60, {herb_watcher}, "CondimentsPageNotDetected", - "make_two_herbs_sandwich(): cannot detect determined herb at cell " + std::to_string(herb_index) + " after 50 seconds." - ); - }; - - // Press DPAD_UP multiple times to move to the first herb row - for(size_t i = 0; i < first_herb_index_last+1; i++){ - move_one_up_to_row(9 - i); - } - press_a_to_determine_herb(0); // Press A to determine one herb - // Press DPAD_UP against to move to the second herb row - for(size_t i = first_herb_index_last+1; i < sweet_herb_index_last+1; i++){ - move_one_up_to_row(9 - i); - } - press_a_to_determine_herb(1); // Press A to determine the second herb - - { - // Press button + to go to picks page - SandwichPicksPageWatcher picks_page_watcher; - repeat_button_press_until( - info, stream, context, BUTTON_PLUS, 40, 60, {picks_page_watcher}, - "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect picks page after 50 seconds." - ); - } - - // Mesh button A to select the first pick - pbf_mash_button(context, BUTTON_A, 80); - context.wait_for_all_requests(); - - finish_two_herbs_sandwich(info, dispatcher, stream, context); -} - -void make_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, - EggSandwichType sandwich_type, Language language -){ - std::map fillings = {{"lettuce", (uint8_t)1}}; - std::map condiments = {{"sweet-herba-mystica", (uint8_t)1}}; - switch(sandwich_type){ - case EggSandwichType::TWO_SWEET_HERBS: - condiments["sweet-herba-mystica"] = 2; - break; - case EggSandwichType::SALTY_SWEET_HERBS: - condiments["salty-herba-mystica"] = 1; - break; - case EggSandwichType::BITTER_SWEET_HERBS: - condiments["bitter-herba-mystica"] = 1; - break; - default: - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Invalid EggSandwichType for make_two_herbs_sandwich()" - ); - } - add_sandwich_ingredients( - dispatcher, - stream, context, - language, - std::move(fillings), - std::move(condiments) - ); - - finish_two_herbs_sandwich(info, dispatcher, stream, context); -} - -void make_sandwich_option(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, SandwichMakerOption& SANDWICH_OPTIONS){ - const Language language = SANDWICH_OPTIONS.LANGUAGE; - if (language == Language::None){ - throw UserSetupError(stream.logger(), "Must set game language option to read ingredient lists."); - } - - int num_fillings = 0; - int num_condiments = 0; - std::map fillings; - std::map condiments; - - //Add the selected ingredients to the maps if set to custom - if (SANDWICH_OPTIONS.BASE_RECIPE == BaseRecipe::custom){ - stream.log("Custom sandwich selected. Validating ingredients.", COLOR_BLACK); - stream.overlay().add_log("Custom sandwich selected."); - - std::vector> table = SANDWICH_OPTIONS.SANDWICH_INGREDIENTS.copy_snapshot(); - - for (const std::unique_ptr& row : table){ - const std::string& table_item = row->item.slug(); - if (!(table_item == "baguette")) { //ignore baguette - if (std::find(ALL_SANDWICH_FILLINGS_SLUGS().begin(), ALL_SANDWICH_FILLINGS_SLUGS().end(), table_item) != ALL_SANDWICH_FILLINGS_SLUGS().end()){ - fillings[table_item]++; - num_fillings++; - }else{ - condiments[table_item]++; - num_condiments++; - } - }else{ - stream.log("Skipping baguette as it is unobtainable."); - stream.overlay().add_log("Skipping baguette as it is unobtainable.", COLOR_WHITE); - } - } - - if (num_fillings == 0 || num_condiments == 0){ - throw UserSetupError(stream.logger(), "Must have at least one filling and at least one condiment."); - } - - if (num_fillings > 6 || num_condiments > 4){ - throw UserSetupError(stream.logger(), "Number of fillings exceed 6 and/or number of condiments exceed 4."); - } - stream.log("Ingredients validated.", COLOR_BLACK); - stream.overlay().add_log("Ingredients validated.", COLOR_WHITE); - } -else if(SANDWICH_OPTIONS.BASE_RECIPE == BaseRecipe::non_shiny){ - stream.log("Preset sandwich selected.", COLOR_BLACK); - stream.overlay().add_log("Preset sandwich selected."); - - // std::vector table = SANDWICH_OPTIONS.get_premade_ingredients( - // SANDWICH_OPTIONS.get_premade_sandwich_recipe(SANDWICH_OPTIONS.BASE_RECIPE, SANDWICH_OPTIONS.TYPE, SANDWICH_OPTIONS.PARADOX)); - - // The only non-shiny sandwich added at this time is Normal Encounter. - std::vector table = SANDWICH_OPTIONS.get_premade_ingredients(SandwichRecipe::non_shiny_normal); - - for (auto&& s : table){ - if (std::find(ALL_SANDWICH_FILLINGS_SLUGS().begin(), ALL_SANDWICH_FILLINGS_SLUGS().end(), s) != ALL_SANDWICH_FILLINGS_SLUGS().end()){ - fillings[s]++; - num_fillings++; - }else{ - condiments[s]++; - num_condiments++; - } - } - } - //Otherwise get the preset ingredients - else{ - stream.log("Preset sandwich selected.", COLOR_BLACK); - stream.overlay().add_log("Preset sandwich selected."); - - std::vector table = SANDWICH_OPTIONS.get_premade_ingredients( - SANDWICH_OPTIONS.get_premade_sandwich_recipe(SANDWICH_OPTIONS.BASE_RECIPE, SANDWICH_OPTIONS.TYPE, SANDWICH_OPTIONS.PARADOX)); - - for (auto&& s : table){ - if (std::find(ALL_SANDWICH_FILLINGS_SLUGS().begin(), ALL_SANDWICH_FILLINGS_SLUGS().end(), s) != ALL_SANDWICH_FILLINGS_SLUGS().end()){ - fillings[s]++; - num_fillings++; - }else{ - condiments[s]++; - num_condiments++; - } - } - //Insert Herba Mystica if required - if (SandwichMakerOption::two_herba_required(SANDWICH_OPTIONS.BASE_RECIPE)){ - if (SANDWICH_OPTIONS.HERBA_ONE == SANDWICH_OPTIONS.HERBA_TWO){ - condiments.insert(std::make_pair(SANDWICH_OPTIONS.herba_to_string(SANDWICH_OPTIONS.HERBA_ONE), (uint8_t)2)); - }else{ - condiments.insert(std::make_pair(SANDWICH_OPTIONS.herba_to_string(SANDWICH_OPTIONS.HERBA_ONE), (uint8_t)1)); - condiments.insert(std::make_pair(SANDWICH_OPTIONS.herba_to_string(SANDWICH_OPTIONS.HERBA_TWO), (uint8_t)1)); - } - num_condiments++; - num_condiments++; - } - } - - /* - //Print ingredients - cout << "Fillings:" << endl; - for (const auto& [key, value] : fillings){ - std::cout << key << ": " << (int)value << endl; - } - cout << "Condiments:" << endl; - for (const auto& [key, value] : condiments){ - std::cout << key << ": " << (int)value << endl; - } - */ - - make_sandwich_preset(env, stream, context, SANDWICH_OPTIONS.LANGUAGE, fillings, condiments); -} - -void make_sandwich_preset(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, Language language, std::map& fillings, std::map& condiments){ - //Sort the fillings by priority for building (ex. large items on bottom, cherry tomatoes on top) - //std::vector fillings_game_order = {"lettuce", "tomato", "cherry-tomatoes", "cucumber", "pickle", "onion", "red-onion", "green-bell-pepper", "red-bell-pepper", - // "yellow-bell-pepper", "avocado", "bacon", "ham", "prosciutto", "chorizo", "herbed-sausage", "hamburger", "klawf-stick", "smoked-fillet", "fried-fillet", "egg", "potato-tortilla", - // "tofu", "rice", "noodles", "potato-salad", "cheese", "banana", "strawberry", "apple", "kiwi", "pineapple", "jalapeno", "watercress", "basil"}; - std::vector fillings_game_order = { "hamburger", "rice", "noodles", "smoked-fillet", "fried-fillet", "cucumber", "pickle", "tofu", - "chorizo", "herbed-sausage", "potato-tortilla", "klawf-stick", "lettuce", "tomato", "onion", "red-onion", "green-bell-pepper", "red-bell-pepper", "yellow-bell-pepper", "avocado", - "bacon", "ham", "prosciutto", "cheese", "banana", "strawberry", "apple", "kiwi", "pineapple", "jalape\xc3\xb1o", "watercress", "potato-salad", "egg", "basil", "cherry-tomatoes" }; - - //Add keys to new vector and sort - std::vector fillings_sorted; - for (auto i = fillings.begin(); i != fillings.end(); i++){ - fillings_sorted.push_back(i->first); - } - std::unordered_map temp_map; - for (auto i = 0; i < (int)fillings_game_order.size(); i++){ - temp_map[fillings_game_order[i]] = i; - } - auto compare = [&temp_map](const std::string& s, const std::string& s1){ - return temp_map[s] < temp_map[s1]; - }; - std::sort(fillings_sorted.begin(), fillings_sorted.end(), compare); - - /* - //Print sorted fillings - cout << "Sorted fillings:" << endl; - for (auto i : fillings_sorted){ - cout << i << endl; - } - */ - - //Calculate number of plates there will be on the build screen - //Get each ingredient in list order, then get the number of times it appears from the map - //Also store how many of each ingredient is in each plate (ex. 6 onion in first plate and then 3 onion in the next) - int plates = 0; - std::vector plate_amounts; - - for (const std::string& i : fillings_sorted){ - //Add "full" plates - int plate_calcs = (int)(fillings[i] / FillingsCoordinates::instance().get_filling_information(i).servingsPerPlate); - if (plate_calcs != 0){ - plates += plate_calcs; - for (int j = 0; j < plate_calcs; j++){ - plate_amounts.push_back( - (int)(FillingsCoordinates::instance().get_filling_information(i).servingsPerPlate) - *(int)(FillingsCoordinates::instance().get_filling_information(i).piecesPerServing) - ); - } - } - - //Add plates for remaining servings - int plate_remaining = ((int)(fillings[i] % FillingsCoordinates::instance().get_filling_information(i).servingsPerPlate)); - if (plate_remaining != 0){ - plates++; - plate_amounts.push_back(plate_remaining * (int)(FillingsCoordinates::instance().get_filling_information(i).piecesPerServing)); - } - } - //cout << "Number of plates: " << plates << endl; - int plates_string = plates; - stream.log("Number of plates: " + std::to_string(plates_string), COLOR_BLACK); - stream.overlay().add_log("Number of plates: " + std::to_string(plates_string), COLOR_WHITE); - for (const auto& filling: fillings){ - env.log("Require filling " + filling.first + " x" + std::to_string(int(filling.second))); - } - for (const auto& condiment: condiments){ - env.log("Require condiment " + condiment.first + " x" + std::to_string(int(condiment.second))); - } - - //Player must be on default sandwich menu - std::map fillings_copy(fillings); //Making a copy as we need the map for later - enter_custom_sandwich_mode(env.program_info(), stream, context); - add_sandwich_ingredients( - env.normal_inference_dispatcher(), - stream, context, - language, - std::move(fillings_copy), - std::move(condiments) - ); - - run_sandwich_maker(env, stream, context, language, fillings, fillings_sorted, plates); -} - -void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, Language language, std::map& fillings, std::vector& fillings_sorted, int& plates){ - - wait_for_initial_hand(env.program_info(), stream, context); - - //Wait for labels to appear - stream.log("Waiting for labels to appear.", COLOR_BLACK); - stream.overlay().add_log("Waiting for labels to appear.", COLOR_WHITE); - pbf_wait(context, 300); - context.wait_for_all_requests(); - - //Now read in plate labels and store which plate has what - stream.log("Reading plate labels.", COLOR_BLACK); - stream.overlay().add_log("Reading plate labels.", COLOR_WHITE); - - std::vector plate_order; - - SandwichPlateDetector left_plate_detector(stream.logger(), COLOR_RED, language, SandwichPlateDetector::Side::LEFT); - SandwichPlateDetector middle_plate_detector(stream.logger(), COLOR_RED, language, SandwichPlateDetector::Side::MIDDLE); - SandwichPlateDetector right_plate_detector(stream.logger(), COLOR_RED, language, SandwichPlateDetector::Side::RIGHT); - bool left_plate_absent = false; - bool right_plate_absent = false; - { - VideoSnapshot screen = stream.video().snapshot(); - - const int max_read_label_tries = 4; - for (int read_label_try_count = 0; read_label_try_count < max_read_label_tries; ++read_label_try_count){ - std::string center_filling = middle_plate_detector.detect_filling_name(screen); - if (center_filling.empty()){ - if (read_label_try_count + 1 < max_read_label_tries){ - // Wait more time - pbf_wait(context, TICKS_PER_SECOND * 2); - context.wait_for_all_requests(); - screen = stream.video().snapshot(); - continue; - }else{ - stream.log("Read nothing on center plate label."); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No ingredient found on center plate label.", - stream, - std::move(screen) - ); - } - } - stream.log("Read center plate label: " + center_filling); - stream.overlay().add_log("Center plate: " + center_filling); - plate_order.push_back(center_filling); - break; - } - - //Get left (2nd) ingredient - std::string left_filling = left_plate_detector.detect_filling_name(screen); - left_plate_absent = left_filling.empty(); - if (left_plate_absent){ - stream.log("No ingredient found on left label."); - stream.overlay().add_log("No left plate"); - }else{ - stream.log("Read left plate label: " + left_filling); - stream.overlay().add_log("Left plate: " + left_filling); - plate_order.push_back(left_filling); - } - - //Get right (3rd) ingredient - std::string right_filling = right_plate_detector.detect_filling_name(screen); - right_plate_absent = right_filling.empty(); - if (right_plate_absent){ - stream.log("No ingredient found on right label."); - stream.overlay().add_log("No right plate"); - }else{ - stream.log("Read right plate label: " + right_filling); - stream.overlay().add_log("Right plate: " + right_filling); - plate_order.push_back(right_filling); - } - - //Get remaining ingredients if any - //center 1, left 2, right 3, far left 4, far far left/right 5, right 6 - //this differs from the game layout: far right is 5 and far far left/right is 6 in game - //however as long as we stay internally consistent with this numbering it will work - for (int i = 0; i < (plates - 3); i++){ - pbf_press_button(context, BUTTON_R, 20, 180); - context.wait_for_all_requests(); - - screen = stream.video().snapshot(); - left_filling = left_plate_detector.detect_filling_name(screen); - - if (left_filling.empty()){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No ingredient label found on remaining plate " + std::to_string(i) + ".", - stream, - std::move(screen) - ); - } - stream.log("Read remaining plate " + std::to_string(i) + " label: " + left_filling); - stream.overlay().add_log("Remaining plate " + std::to_string(i) + ": " + left_filling); - plate_order.push_back(left_filling); - } - - //Now re-center plates - stream.log("Re-centering plates if needed."); - stream.overlay().add_log("Re-centering plates if needed."); - for (int i = 0; i < (plates - 3); i++){ - pbf_press_button(context, BUTTON_L, 20, 80); - } - - //If a label fails to read it'll cause issues down the line - if ((int)plate_order.size() != plates){ - env.log("Found # plate labels " + std::to_string(plate_order.size()) + ", not same as desired # plates " + std::to_string(plates)); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Number of plate labels did not match number of plates.", - stream, - std::move(screen) - ); - } - } - - //Finally. - stream.log("Start making sandwich", COLOR_BLACK); - stream.overlay().add_log("Start making sandwich.", COLOR_WHITE); - - const ImageFloatBox center_plate{ 0.455, 0.130, 0.090, 0.030 }; - const ImageFloatBox left_plate{ 0.190, 0.136, 0.096, 0.031 }; - const ImageFloatBox right_plate{ 0.715, 0.140, 0.108, 0.033 }; - - ImageFloatBox target_plate = center_plate; - //Initial position handling - auto end_box = move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), - stream, context, - SandwichHandType::FREE, - false, - HAND_INITIAL_BOX, - HAND_INITIAL_BOX - ); - move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), - stream, context, - SandwichHandType::GRABBING, - true, - { 0, 0, 1.0, 1.0 }, - HAND_INITIAL_BOX - ); - context.wait_for_all_requests(); - - //Find fillings and add them in order - for (const std::string& i : fillings_sorted){ - //cout << "Placing " << i << endl; - stream.log("Placing " + i, COLOR_WHITE); - stream.overlay().add_log("Placing " + i, COLOR_WHITE); - - int times_to_place = (int)(FillingsCoordinates::instance().get_filling_information(i).piecesPerServing) * (fillings.find(i)->second); - int placement_number = 0; - - //cout << "Times to place: " << times_to_place << endl; - stream.log("Times to place: " + std::to_string(times_to_place), COLOR_WHITE); - stream.overlay().add_log("Times to place: " + std::to_string(times_to_place), COLOR_WHITE); - - std::vector plate_index; - //Get the plates we want to go to - for (int j = 0; j < (int)plate_order.size(); j++){ - if (i == plate_order.at(j)){ - plate_index.push_back(j); - } - } - - //Target the correct filling plate and place until it is empty - for (int j = 0; j < (int)plate_index.size(); j++){ - //Navigate to plate and set target plate - //cout << "Target plate: " << plate_index.at(j) << endl; - stream.log("Target plate: " + std::to_string(plate_index.at(j)), COLOR_WHITE); - stream.overlay().add_log("Target plate: " + std::to_string(plate_index.at(j)), COLOR_WHITE); - SandwichPlateDetector::Side target_plate_label = SandwichPlateDetector::Side::MIDDLE; - switch (plate_index.at(j)){ - case 0: - target_plate = center_plate; - break; - case 1: - target_plate = left_plate; - target_plate_label = SandwichPlateDetector::Side::LEFT; - break; - case 2: - target_plate = right_plate; - target_plate_label = SandwichPlateDetector::Side::RIGHT; - break; - case 3: case 4: case 5: case 6: - //Press R the appropriate number of times - for (int k = 2; k < plate_index.at(j); k++){ - pbf_press_button(context, BUTTON_R, 20, 80); - } - target_plate = left_plate; - target_plate_label = SandwichPlateDetector::Side::LEFT; - break; - default: - break; - } - - // place down all the ingredients for the current plate. - //Place the fillings until label does not light up yellow on grab/the piece count is not hit - while (true){ - //Break out after placing all pieces of the filling - if (placement_number == times_to_place){ - stream.log("We have placed down enough ingredients of that type, so we assume our current plate is empty. Move on to the next plate/ingredient.", COLOR_ORANGE); - break; - } - - end_box = move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), - stream, context, - SandwichHandType::FREE, - false, - { 0, 0, 1.0, 1.0 }, - target_plate - ); - context.wait_for_all_requests(); - - //Get placement location - ImageFloatBox placement_target = FillingsCoordinates::instance().get_filling_information(i).placementCoordinates.at( - (int)fillings.find(i)->second).at(placement_number); - - HandMoveData hand_move_data = move_sandwich_hand_and_check_if_plates_empty( - env.program_info(), env.realtime_inference_dispatcher(), - stream, context, - SandwichHandType::GRABBING, - true, - expand_box(end_box), - placement_target, - target_plate_label - ); - end_box = hand_move_data.end_box; - context.wait_for_all_requests(); - - // If the current plate is empty, break out of the loop and move on to the next plate. - if (hand_move_data.plate_empty){ - context.wait_for_all_requests(); - stream.log("Our current plate label is NOT yellow, so we assume our current plate is empty. Move on to the next plate.", COLOR_ORANGE); - break; - } - - stream.log("Our current plate label is yellow, so we assume our current plate is NOT empty. Continue with the current plate.", COLOR_YELLOW); - - //If the plate is empty the increment is skipped using the above break - placement_number++; - } - - //Reset plate positions - for (int k = 2; k < plate_index.at(j); k++){ - pbf_press_button(context, BUTTON_L, 20, 80); - } - } - } - - context.wait_for_all_requests(); - context.wait_for(Milliseconds(500)); - stream.log("All ingredients should now be empty. Wait for upper bread.", COLOR_YELLOW); - // Handle top slice by tossing it away - SandwichHandWatcher grabbing_hand(SandwichHandType::GRABBING, { 0, 0, 1.0, 1.0 }); - int ret = wait_until(stream, context, std::chrono::seconds(30), { grabbing_hand }); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "SandwichMaker: Cannot detect grabbing hand when waiting for upper bread.", - stream, - grabbing_hand.last_snapshot() - ); - } - - auto hand_box = hand_location_to_box(grabbing_hand.location()); - - end_box = move_sandwich_hand( - env.program_info(), env.realtime_inference_dispatcher(), - stream, context, - SandwichHandType::GRABBING, - false, - expand_box(hand_box), - center_plate - ); - pbf_mash_button(context, BUTTON_A, 125 * 5); - - env.log("Hand end box " + box_to_string(end_box)); - env.log("Built sandwich", COLOR_BLACK); - // env.console.overlay().add_log("Hand end box " + box_to_string(end_box), COLOR_WHITE); - stream.overlay().add_log("Built sandwich.", COLOR_WHITE); - context.wait_for_all_requests(); - - finish_sandwich_eating(env.program_info(), stream, context); -} - -} -} -} +/* Sandwich Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Concurrency/AsyncDispatcher.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_PicnicDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichHandDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichIngredientDetector.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichRecipeDetector.h" +#include "PokemonSV/Resources/PokemonSV_FillingsCoordinates.h" +#include "PokemonSV/Resources/PokemonSV_Ingredients.h" +#include "PokemonSV_SandwichRoutines.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_IngredientSession.h" +#include "PokemonSV/Inference/Picnics/PokemonSV_SandwichPlateDetector.h" + +// #include +// using std::cout; +// using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +namespace{ + const ImageFloatBox HAND_INITIAL_BOX{0.440, 0.455, 0.112, 0.179}; + const ImageFloatBox INGREDIENT_BOX{0.455, 0.130, 0.090, 0.030}; + +void wait_for_initial_hand( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + SandwichHandWatcher free_hand(SandwichHandType::FREE, HAND_INITIAL_BOX); + int ret = wait_until(stream, context, std::chrono::seconds(30), {free_hand}); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "FreeHandNotDetected", + "Cannot detect hand at start of making a sandwich." + ); + } +} + +} // anonymous namespace + +bool enter_sandwich_recipe_list( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + context.wait_for_all_requests(); + stream.log("Opening sandwich menu at picnic table."); + + // Firt, try pressing button A to bring up the menu to make sandwich + pbf_press_button(context, BUTTON_A, 20, 80); + + WallClock start = current_time(); + bool opened_table_menu = false; + while(true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(1)){ + dump_image_and_throw_recoverable_exception( + info, stream, "FailToSandwich", + "enter_sandwich_recipe_list(): Failed to open sandwich menu after 1 minute." + ); + } + + PicnicWatcher picnic_watcher; + GradientArrowWatcher sandwich_arrow(COLOR_YELLOW, GradientArrowType::RIGHT, {0.551, 0.311, 0.310, 0.106}); + GradientArrowWatcher recipe_arrow(COLOR_YELLOW, GradientArrowType::DOWN, {0.103, 0.074, 0.068, 0.085}); + AdvanceDialogWatcher dialog_watcher(COLOR_RED); + + const int ret = wait_until( + stream, context, + std::chrono::seconds(30), + {picnic_watcher, sandwich_arrow, recipe_arrow, dialog_watcher} + ); + switch (ret){ + case 0: + stream.log("Detected picnic. Maybe button A press dropped."); + // walk forward and press A again + pbf_move_left_joystick(context, 128, 0, 100, 40); + pbf_press_button(context, BUTTON_A, 20, 80); + continue; + case 1: + stream.log("Detected \"make a sandwich\" menu item selection arrrow."); + stream.overlay().add_log("Open sandwich recipes", COLOR_WHITE); + opened_table_menu = true; + pbf_press_button(context, BUTTON_A, 20, 100); + continue; + case 2: + stream.log("Detected recipe selection arrow."); + context.wait_for(std::chrono::seconds(1)); // wait one second to make sure the menu is fully loaded. + return true; + case 3: + stream.log("Detected advance dialog."); + if (opened_table_menu){ + stream.log("Advance dialog after \"make a sandwich\" menu item. No ingredients.", COLOR_RED); + stream.overlay().add_log("No ingredient!", COLOR_RED); + return false; + } + pbf_press_button(context, BUTTON_A, 20, 80); + continue; + default: + dump_image_and_throw_recoverable_exception(info, stream, "NotEnterSandwichList", + "enter_sandwich_recipe_list(): No recognized state after 60 seconds."); + } + } +} + + +bool select_sandwich_recipe( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t target_sandwich_ID +){ + context.wait_for_all_requests(); + stream.log("Choosing sandwich recipe: " + std::to_string(target_sandwich_ID)); + stream.overlay().add_log("Search recipe " + std::to_string(target_sandwich_ID), COLOR_WHITE); + + SandwichRecipeNumberDetector recipe_detector(stream.logger()); + SandwichRecipeSelectionWatcher selection_watcher; + + VideoOverlaySet overlay_set(stream.overlay()); + recipe_detector.make_overlays(overlay_set); + selection_watcher.make_overlays(overlay_set); + + bool found_recipe = false; + int max_move_down_list_attempts = 100; // There are 151 total recipes, so 76 rows. + for (int move_down_list_attempt = 0; move_down_list_attempt < max_move_down_list_attempts; move_down_list_attempt++){ + context.wait_for(std::chrono::milliseconds(200)); + context.wait_for_all_requests(); + + auto snapshot = stream.video().snapshot(); + size_t recipe_IDs[6] = {0, 0, 0, 0, 0, 0}; + recipe_detector.detect_recipes(snapshot, recipe_IDs); + { + std::ostringstream os; + os << "Recipe IDs detected: "; + for(int i = 0; i < 6; i++){ + os << recipe_IDs[i] << ", "; + } + stream.log(os.str()); + } + + size_t min_ID = 300; + for(int i = 0; i < 6; i++){ + if (recipe_IDs[i] > 0 && recipe_IDs[i] < min_ID){ + min_ID = recipe_IDs[i]; + } + } + if (min_ID == 300){ + min_ID = 0; // set case of no recipe ID detected to be 0 min_ID + } + size_t max_ID = *std::max_element(recipe_IDs, recipe_IDs+6); + stream.log("min, max IDs " + std::to_string(min_ID) + ", " + std::to_string(max_ID)); + + if (0 < min_ID && min_ID <= target_sandwich_ID && target_sandwich_ID <= max_ID){ + // target is in this page! + + int target_cell = -1; + for(int i = 0; i < 6; i++){ + if (recipe_IDs[i] == target_sandwich_ID){ + target_cell = i; + break; + } + } + if (target_cell == -1){ // not targe recipe found in this page, probably not enough ingredients + stream.log("Not enough ingredients for target recipe.", COLOR_RED); + stream.overlay().add_log("Not enough ingredients", COLOR_RED); + return false; + } + + stream.log("found recipe in the current page, cell " + std::to_string(target_cell)); + + int ret = wait_until(stream, context, std::chrono::seconds(10), {selection_watcher}); + int selected_cell = selection_watcher.selected_recipe_cell(); + if (ret < 0 || selected_cell < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "RecipeSelectionArrowNotDetected", + "select_sandwich_recipe(): Cannot detect recipe selection arrow." + ); + } + + stream.log("Current selected cell " + std::to_string(selected_cell)); + + if (target_cell == selected_cell){ + // Selected target recipe! + stream.log("Found recipe at cell " + std::to_string(selected_cell)); + stream.overlay().add_log("Found recipe", COLOR_WHITE); + found_recipe = true; + break; + }else if (target_cell == selected_cell + 1){ + stream.log("Move to the right column."); + // Target is in a different column + // Move cursor right. + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + continue; + } + // else, continue moving down the list + } + + // target sandwich recipe is still below the current displayed recipes. + // Move down the list. + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } // end for moving down the recipe list + + overlay_set.clear(); + + if (found_recipe){ + // Press A to enter the pick selection + pbf_press_button(context, BUTTON_A, 30, 100); +// context.wait_for_all_requests(); + + SandwichIngredientArrowWatcher pick_selection(0, COLOR_YELLOW); + while(true){ + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, std::chrono::seconds(3), + {selection_watcher, pick_selection} + ); + + if (ret == 0){ + stream.log("Detected recipe selection. Dropped Button A?"); + pbf_press_button(context, BUTTON_A, 30, 100); + continue; + }else if (ret == 1){ + stream.log("Detected pick selection."); + pbf_press_button(context, BUTTON_A, 30, 100); + continue; + }else{ + stream.log("Entered sandwich minigame."); + break; + } + } + return true; + } + + // we cannot find the receipt + stream.log("Max list traverse attempt reached. Target recipe not found", COLOR_RED); + stream.overlay().add_log("Recipe not found", COLOR_RED); + + return false; +} + +namespace{ + +// expand the hand bounding box so that the hand watcher can pick the hand in the next iteration +ImageFloatBox expand_box(const ImageFloatBox& box){ + const double x = std::max(0.0, box.x - box.width * 1.5); + const double y = std::max(0.0, box.y - box.height * 1.5); + const double width = std::min(box.width*4, 1.0 - x); + const double height = std::min(box.height*4, 1.0 - y); + return ImageFloatBox(x, y, width, height); +} + +ImageFloatBox hand_location_to_box(const std::pair& loc){ + const double hand_width = 0.071, hand_height = 0.106; + return {loc.first - hand_width/2, loc.second - hand_height/2, hand_width, hand_height}; +} + +std::string box_to_string(const ImageFloatBox& box){ + std::ostringstream os; + os << "(" << box.x << ", " << box.y << ", " << box.width << ", " << box.height << ")"; + return os.str(); +} + +/* +- center the cursor by moving the cursor to the edge of the screen, then away from the edge. +- then search the whole screen for the sandwich hand, instead of just the box, and +update the location of the sandwich hand +- return true if successful. else throw an exception +*/ +bool move_then_recover_sandwich_hand_position( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + SandwichHandType& hand_type, + SandwichHandWatcher& hand_watcher, + AsyncCommandSession& move_session +){ + + stream.log("center the cursor: move towards bottom right, then left slightly."); + uint16_t num_ticks_to_move_1 = TICKS_PER_SECOND*4; + uint16_t num_ticks_to_move_2 = 100; + + // center the cursor + if(SandwichHandType::FREE == hand_type){ + // move to bottom right corner, + pbf_move_left_joystick(context, 255, 255, num_ticks_to_move_1, 100); + // move to left slightly + pbf_move_left_joystick(context, 0, 128, num_ticks_to_move_2, 100); + context.wait_for_all_requests(); + } + else if(SandwichHandType::GRABBING == hand_type){ + // center the cursor while holding the A button, so you don't drop the ingredient. + + uint16_t num_ticks_to_move_total = num_ticks_to_move_1 + num_ticks_to_move_2; + uint16_t num_ticks_to_wait = num_ticks_to_move_total + TICKS_PER_SECOND; // add one extra second of waiting + uint16_t num_miliseconds_to_wait = (num_ticks_to_wait*1000)/TICKS_PER_SECOND; + uint16_t num_ticks_to_hold_A = num_ticks_to_wait + TICKS_PER_SECOND*10; // hold A for extra 10 seconds + // the A button hold will be overwritten on the next move_session.dispatch, in the main function + + move_session.dispatch([&](ProControllerContext& context){ + // move to bottom right corner, while holding A + pbf_controller_state(context, BUTTON_A, DPAD_NONE, 255, 255, 128, 128, num_ticks_to_move_1); + + // move to left slightly, while holding A + pbf_controller_state(context, BUTTON_A, DPAD_NONE, 0, 128, 128, 128, num_ticks_to_move_2); + + // keep holding A. + pbf_press_button(context, BUTTON_A, num_ticks_to_hold_A, 0); + // pbf_controller_state(context, BUTTON_A, DPAD_NONE, 128, 128, 128, 128, 3000); + }); + + // - wait long enough for the cursor movement to finish, before we try image matching + // - wait_for_all_requests doesn't work since we want to still hold the A button. + // - this is a workaround until there is a way to wait for a subset of a bunch of overlapping buttons to finish + // - need to make sure the A button hold is long enough to last past this wait. + context.wait_for(Milliseconds(num_miliseconds_to_wait)); + } + + const VideoSnapshot& frame = stream.video().snapshot(); + stream.log("Try to recover sandwich hand location."); + if(hand_watcher.recover_sandwich_hand_position(frame)){ + // sandwich hand detected. + return true; + } + + // if still can't find the sandwich hand, throw a exception + dump_image_and_throw_recoverable_exception( + info, stream, + SANDWICH_HAND_TYPE_NAMES(hand_type) + "SandwichHandNotDetected", + "move_sandwich_hand(): Cannot detect " + SANDWICH_HAND_TYPE_NAMES(hand_type) + " hand." + ); +} + +// return true if the current plate is empty. +// i.e. the current plate label is not yellow. +// Assumes that we are in a grabbing state. +bool check_plate_empty(VideoStream& stream, SandwichPlateDetector::Side target_plate_label, Language language){ + auto screen = stream.video().snapshot(); + // screen.frame->save("test.png"); + + // switch(target_plate_label){ + // case SandwichPlateDetector::Side::LEFT: + // cout << "left" << endl; + // break; + // case SandwichPlateDetector::Side::MIDDLE: + // cout << "middle" << endl; + // break; + // case SandwichPlateDetector::Side::RIGHT: + // cout << "right" << endl; + // break; + // default: + // break; + // } + + stream.log("Check if the plate is empty."); + + SandwichPlateDetector plate_detector = SandwichPlateDetector(stream.logger(), COLOR_RED, language, target_plate_label); + + return !plate_detector.is_label_yellow(screen); +} + +struct HandMoveData{ + ImageFloatBox end_box; + bool plate_empty; +}; + + +/* +- moves the sandwich hand from start_box to end_box +- It detects the location of the sandwich hand, from within the bounds of the last frame's +expanded_hand_bb (i.e. m_box field in SandwichHandLocator). +Then updates the current location of expanded_hand_bb. +Then moves the sandwich hand closer towards end_box. + */ +HandMoveData move_sandwich_hand_and_check_if_plates_empty( + const ProgramInfo& info, + AsyncDispatcher& dispatcher, + VideoStream& stream, + ProControllerContext& context, + SandwichHandType hand_type, + bool pressing_A, + const ImageFloatBox& start_box, + const ImageFloatBox& end_box, + SandwichPlateDetector::Side target_plate_label = SandwichPlateDetector::Side::NOT_APPLICABLE, + Language language = Language::None +){ + context.wait_for_all_requests(); + stream.log("Start moving sandwich hand: " + SANDWICH_HAND_TYPE_NAMES(hand_type) + + " start box " + box_to_string(start_box) + " end box " + box_to_string(end_box)); + + uint8_t joystick_x = 128; + uint8_t joystick_y = 128; + + SandwichHandWatcher hand_watcher(hand_type, start_box); + + // A session that creates a new thread to send button commands to controller + AsyncCommandSession move_session( + context, + stream.logger(), + dispatcher, + context.controller() + ); + + if (pressing_A){ + move_session.dispatch([](ProControllerContext& context){ + pbf_controller_state(context, BUTTON_A, DPAD_NONE, 128, 128, 128, 128, 3000); + }); + } + + const std::pair target_loc(end_box.x + end_box.width/2, end_box.y + end_box.height/2); + + std::pair last_loc(-1, -1); + std::pair speed(-1, -1); + WallClock cur_time, last_time; + VideoOverlaySet overlay_set(stream.overlay()); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + #if 0 + // to intentionally trigger failures in hand detection, for testing recovery + if (SandwichHandType::FREE == hand_type){ + std::pair hand_location(1.0, 1.0); + const ImageFloatBox hand_bb_debug = hand_location_to_box(hand_location); + const ImageFloatBox expanded_hand_bb_debug = expand_box(hand_bb_debug); + hand_watcher.change_box(expanded_hand_bb_debug); + overlay_set.clear(); + overlay_set.add(COLOR_RED, hand_bb_debug); + overlay_set.add(COLOR_BLUE, expanded_hand_bb_debug); + pbf_move_left_joystick(context, 0, 0, TICKS_PER_SECOND*5, 100); // move hand to screen edge + context.wait_for_all_requests(); + } + #endif + + #if 0 + // to intentionally trigger failures in hand detection, for testing recovery + // move hand to edge of screen, while still holding A + if (SandwichHandType::GRABBING == hand_type){ + pbf_controller_state(context, BUTTON_A, DPAD_NONE, 0, 0, 128, 128, TICKS_PER_SECOND*5); + pbf_press_button(context, BUTTON_A, 200, 0); + // pbf_controller_state(context, BUTTON_A, DPAD_NONE, 128, 128, 128, 128, 100); + } + #endif + } + + while(true){ + int ret = wait_until(stream, context, std::chrono::seconds(5), {hand_watcher}); + if (ret < 0){ + // - the sandwich hand might be at the edge of the screen, so move it to the middle + // and try searching the entire screen again + // - move hand to bottom-right, then to the middle + stream.log( + "Failed to detect sandwich hand. It may be at the screen's edge. " + "Try moving the hand to the middle of the screen and try searching again." + ); + + if(move_then_recover_sandwich_hand_position( + info, stream, context, hand_type, hand_watcher, move_session + )){ + continue; + } + + } + + auto cur_loc = hand_watcher.location(); + stream.log("Hand location: " + std::to_string(cur_loc.first) + ", " + std::to_string(cur_loc.second)); + cur_time = current_time(); + + const ImageFloatBox hand_bb = hand_location_to_box(cur_loc); + const ImageFloatBox expanded_hand_bb = expand_box(hand_bb); + hand_watcher.change_box(expanded_hand_bb); + + overlay_set.clear(); + overlay_set.add(COLOR_RED, hand_bb); + overlay_set.add(COLOR_BLUE, expanded_hand_bb); + + std::pair dif(target_loc.first - cur_loc.first, target_loc.second - cur_loc.second); + // console.log("float diff to target: " + std::to_string(dif.first) + ", " + std::to_string(dif.second)); + + + // Reached the Target + if (std::fabs(dif.first) < end_box.width/2 && std::fabs(dif.second) < end_box.height/2){ + stream.log(SANDWICH_HAND_TYPE_NAMES(hand_type) + " hand reached target."); + bool plate_empty = false; + + // check if the plate is empty. but only if the target_plate_label isn't NOT_APPLICABLE. + if (target_plate_label != SandwichPlateDetector::Side::NOT_APPLICABLE){ + plate_empty = check_plate_empty(stream, target_plate_label, language); + } + + move_session.stop_session_and_rethrow(); // Stop the commands + if (hand_type == SandwichHandType::GRABBING){ + // wait for some time to let hand release ingredient + context.wait_for(std::chrono::milliseconds(100)); + } + return {hand_bb, plate_empty}; + } + + // Assume screen width is 16.0, then the screen height is 9.0 + std::pair real_dif(dif.first * 16, dif.second * 9); + double distance = std::sqrt(real_dif.first * real_dif.first + real_dif.second * real_dif.second); + // console.log("scaled diff to target: " + std::to_string(real_dif.first) + ", " + std::to_string(real_dif.second) + // + " distance " + std::to_string(distance)); + + // Build a P-D controller! + + // We assume for a screen distance of 4 (1/4 of the width), we can use max joystick push, 128. + // So for distance of value 1.0, we multiply by 32 to get joystick push + double target_joystick_push = std::min(distance * 32, 128.0); + + std::pair push(real_dif.first * target_joystick_push / distance, real_dif.second * target_joystick_push / distance); + // console.log("push force " + std::to_string(push.first) + ", " + std::to_string(push.second)); + + if (last_loc.first < 0){ + speed = std::make_pair(0.0, 0.0); + }else{ + std::chrono::microseconds time = std::chrono::duration_cast(cur_time - last_time); + double time_s = time.count() / 1000000.0; + std::pair moved((cur_loc.first - last_loc.first) * 16, (cur_loc.second - last_loc.second) * 9); + + // Currently set to zero damping as it seems we don't need them for now + double damping_factor = 0.0; + double damping_multiplier = (-1.0) * damping_factor / time_s; + std::pair damped_push_offset(moved.first * damping_multiplier, moved.second * damping_multiplier); + + push.first += damped_push_offset.first; + push.second += damped_push_offset.second; + } + + joystick_x = (uint8_t) std::max(std::min(int(push.first + 0.5) + 128, 255), 0); + joystick_y = (uint8_t) std::max(std::min(int(push.second + 0.5) + 128, 255), 0); + // console.log("joystick push " + std::to_string(joystick_x) + ", " + std::to_string(joystick_y)); + + // Dispatch a new series of commands that overwrites the last ones + move_session.dispatch([&](ProControllerContext& context){ + if (pressing_A){ + // Note: joystick_x and joystick_y must be defined to outlive `move_session`. +// pbf_controller_state(context, BUTTON_A, DPAD_NONE, joystick_x, joystick_y, 128, 128, 20); + ssf_press_button(context, BUTTON_A, 0ms, 8000ms, 0ms); + } + pbf_move_left_joystick(context, joystick_x, joystick_y, 20, 0); + }); + + stream.log("Moved joystick"); + + last_loc = cur_loc; + last_time = cur_time; + context.wait_for(std::chrono::milliseconds(80)); + } +} + +ImageFloatBox move_sandwich_hand( + const ProgramInfo& info, + AsyncDispatcher& dispatcher, + VideoStream& stream, + ProControllerContext& context, + SandwichHandType hand_type, + bool pressing_A, + const ImageFloatBox& start_box, + const ImageFloatBox& end_box +){ + return move_sandwich_hand_and_check_if_plates_empty( + info, dispatcher, + stream, context, + hand_type, pressing_A, + start_box, end_box, + SandwichPlateDetector::Side::NOT_APPLICABLE, + Language::None + ).end_box; +} + +} // end anonymous namespace + +void finish_sandwich_eating( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + stream.overlay().add_log("Eating", COLOR_WHITE); + PicnicWatcher picnic_watcher; + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for(int i = 0; i < 20; i++){ + pbf_press_button(context, BUTTON_A, 20, 3*TICKS_PER_SECOND - 20); + } + }, + {picnic_watcher} + ); + if (ret < 0){ + dump_image_and_throw_recoverable_exception( + info, stream, "PicnicNotDetected", + "finish_sandwich_eating(): cannot detect picnic after 60 seconds." + ); + } + stream.overlay().add_log("Finish eating", COLOR_WHITE); + stream.log("Finished eating sandwich. Back at picnic."); + context.wait_for(std::chrono::seconds(1)); +} + +namespace{ + +void repeat_press_until( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + std::function button_press, + const std::vector& callbacks, + const std::string &error_name, const std::string &error_message, + std::chrono::milliseconds detection_timeout = std::chrono::seconds(5), + size_t max_presses = 10, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + button_press(); + for(size_t i_try = 0; i_try < max_presses; i_try++){ + context.wait_for_all_requests(); + const int ret = wait_until(stream, context, detection_timeout, callbacks); + if (ret >= 0){ + return; + } + button_press(); + } + + dump_image_and_throw_recoverable_exception( + info, stream, "IngredientListNotDetected", + "enter_custom_sandwich_mode(): cannot detect ingredient list after 50 seconds." + ); +} + +void repeat_button_press_until( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + Button button, uint16_t hold_ticks, uint16_t release_ticks, + const std::vector& callbacks, + const std::string &error_name, const std::string &error_message, + std::chrono::milliseconds iteration_length = std::chrono::seconds(5), + size_t max_presses = 10, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + const std::chrono::milliseconds button_time = std::chrono::milliseconds((hold_ticks + release_ticks) * (1000 / TICKS_PER_SECOND)); + repeat_press_until( + info, stream, context, + [&](){ + pbf_press_button(context, button, hold_ticks, release_ticks); + }, + callbacks, error_name, error_message, iteration_length - button_time, max_presses, + default_video_period, default_audio_period + ); +} + +void repeat_dpad_press_until( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + DpadPosition dpad_position, uint16_t hold_ticks, uint16_t release_ticks, + const std::vector& callbacks, + const std::string &error_name, const std::string &error_message, + std::chrono::milliseconds iteration_length = std::chrono::seconds(5), + size_t max_presses = 10, + std::chrono::milliseconds default_video_period = std::chrono::milliseconds(50), + std::chrono::milliseconds default_audio_period = std::chrono::milliseconds(20) +){ + const std::chrono::milliseconds button_time = std::chrono::milliseconds((hold_ticks + release_ticks) * (1000 / TICKS_PER_SECOND)); + repeat_press_until( + info, stream, context, + [&](){ pbf_press_dpad(context, dpad_position, hold_ticks, release_ticks); }, + callbacks, error_name, error_message, iteration_length - button_time, max_presses, + default_video_period, default_audio_period + ); +} + + +} // anonymous namespace + + +void enter_custom_sandwich_mode( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +){ + context.wait_for_all_requests(); + stream.log("Entering custom sandwich mode."); + stream.overlay().add_log("Custom sandwich", COLOR_WHITE); + + SandwichIngredientArrowWatcher ingredient_selection_arrow(0, COLOR_YELLOW); + repeat_button_press_until( + info, stream, context, BUTTON_X, 40, 80, {ingredient_selection_arrow}, + "IngredientListNotDetected", "enter_custom_sandwich_mode(): cannot detect ingredient list after 50 seconds." + ); +} + +namespace{ + +void finish_two_herbs_sandwich( + const ProgramInfo& info, AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context +){ + stream.log("Finish determining ingredients for two-sweet-herb sandwich."); + stream.overlay().add_log("Finish picking ingredients", COLOR_WHITE); + + wait_for_initial_hand(info, stream, context); + + stream.overlay().add_log("Start making sandwich", COLOR_WHITE); + move_sandwich_hand(info, dispatcher, stream, context, SandwichHandType::FREE, false, HAND_INITIAL_BOX, INGREDIENT_BOX); + // Mash button A to pick and drop ingredients, upper bread and pick. + // Egg Power 3 is applied with only two sweet herb condiments! + pbf_mash_button(context, BUTTON_A, 8 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + stream.overlay().add_log("Built sandwich", COLOR_WHITE); +} + +} // anonymous namespace + +void make_two_herbs_sandwich( + const ProgramInfo& info, AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, + EggSandwichType sandwich_type, size_t sweet_herb_index_last, size_t salty_herb_index_last, size_t bitter_herb_index_last +){ + // The game has at most 5 herbs, in the order of sweet, salty, sour, bitter, spicy: + if (sweet_herb_index_last >= 5){ // sweet index can only be: 0, 1, 2, 3, 4 + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Invalid sweet herb index: " + std::to_string(sweet_herb_index_last) + ); + } + if (salty_herb_index_last >= 4){ // 0, 1, 2, 3 + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Invalid salty herb index: " + std::to_string(salty_herb_index_last) + ); + } + if (bitter_herb_index_last >= 2){ // 0, 1 + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Invalid bitter herb index: " + std::to_string(bitter_herb_index_last) + ); + } + + if (sandwich_type == EggSandwichType::SALTY_SWEET_HERBS && salty_herb_index_last >= sweet_herb_index_last){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Invalid salty and sweet herb indices: " + std::to_string(salty_herb_index_last) + ", " + std::to_string(sweet_herb_index_last) + ); + } + if (sandwich_type == EggSandwichType::BITTER_SWEET_HERBS && bitter_herb_index_last >= sweet_herb_index_last){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Invalid bitter and sweet herb indices: " + std::to_string(bitter_herb_index_last) + ", " + std::to_string(sweet_herb_index_last) + ); + } + + { + // Press button A to add first filling, assumed to be lettuce + DeterminedSandwichIngredientWatcher filling_watcher(SandwichIngredientType::FILLING, 0); + repeat_button_press_until( + info, stream, context, BUTTON_A, 40, 50, {filling_watcher}, + "DeterminedIngredientNotDetected", "make_two_herbs_sandwich(): cannot detect determined lettuce after 50 seconds." + ); + } + + { + // Press button + to go to condiments page + SandwichCondimentsPageWatcher condiments_page_watcher; + repeat_button_press_until( + info, stream, context, BUTTON_PLUS, 40, 60, {condiments_page_watcher}, + "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect condiments page after 50 seconds." + ); + } + + size_t first_herb_index_last = 0; + switch(sandwich_type){ + case EggSandwichType::TWO_SWEET_HERBS: + first_herb_index_last = sweet_herb_index_last; + break; + case EggSandwichType::SALTY_SWEET_HERBS: + first_herb_index_last = salty_herb_index_last; + break; + case EggSandwichType::BITTER_SWEET_HERBS: + first_herb_index_last = bitter_herb_index_last; + break; + default: + throw InternalProgramError(&stream.logger(), PA_CURRENT_FUNCTION, + "Invalid EggSandwichType for make_two_herbs_sandwich()"); + } + + auto move_one_up_to_row = [&](size_t row){ + stream.log("Move arrow to row " + std::to_string(row)); + SandwichIngredientArrowWatcher arrow(row); + repeat_dpad_press_until(info, stream, context, DPAD_UP, 10, 30, {arrow}, "IngredientArrowNotDetected", + "make_two_herbs_sandwich(): cannot detect ingredient selection arrow at row " + std::to_string(row) + " after 50 seconds." + ); + }; + + auto press_a_to_determine_herb = [&](size_t herb_index){ + DeterminedSandwichIngredientWatcher herb_watcher(SandwichIngredientType::CONDIMENT, herb_index); + repeat_button_press_until( + info, stream, context, BUTTON_A, 40, 60, {herb_watcher}, "CondimentsPageNotDetected", + "make_two_herbs_sandwich(): cannot detect determined herb at cell " + std::to_string(herb_index) + " after 50 seconds." + ); + }; + + // Press DPAD_UP multiple times to move to the first herb row + for(size_t i = 0; i < first_herb_index_last+1; i++){ + move_one_up_to_row(9 - i); + } + press_a_to_determine_herb(0); // Press A to determine one herb + // Press DPAD_UP against to move to the second herb row + for(size_t i = first_herb_index_last+1; i < sweet_herb_index_last+1; i++){ + move_one_up_to_row(9 - i); + } + press_a_to_determine_herb(1); // Press A to determine the second herb + + { + // Press button + to go to picks page + SandwichPicksPageWatcher picks_page_watcher; + repeat_button_press_until( + info, stream, context, BUTTON_PLUS, 40, 60, {picks_page_watcher}, + "CondimentsPageNotDetected", "make_two_herbs_sandwich(): cannot detect picks page after 50 seconds." + ); + } + + // Mesh button A to select the first pick + pbf_mash_button(context, BUTTON_A, 80); + context.wait_for_all_requests(); + + finish_two_herbs_sandwich(info, dispatcher, stream, context); +} + +void make_two_herbs_sandwich( + const ProgramInfo& info, AsyncDispatcher& dispatcher, VideoStream& stream, ProControllerContext& context, + EggSandwichType sandwich_type, Language language +){ + std::map fillings = {{"lettuce", (uint8_t)1}}; + std::map condiments = {{"sweet-herba-mystica", (uint8_t)1}}; + switch(sandwich_type){ + case EggSandwichType::TWO_SWEET_HERBS: + condiments["sweet-herba-mystica"] = 2; + break; + case EggSandwichType::SALTY_SWEET_HERBS: + condiments["salty-herba-mystica"] = 1; + break; + case EggSandwichType::BITTER_SWEET_HERBS: + condiments["bitter-herba-mystica"] = 1; + break; + default: + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Invalid EggSandwichType for make_two_herbs_sandwich()" + ); + } + add_sandwich_ingredients( + dispatcher, + stream, context, + language, + std::move(fillings), + std::move(condiments) + ); + + finish_two_herbs_sandwich(info, dispatcher, stream, context); +} + +void make_sandwich_option(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, SandwichMakerOption& SANDWICH_OPTIONS){ + const Language language = SANDWICH_OPTIONS.LANGUAGE; + if (language == Language::None){ + throw UserSetupError(stream.logger(), "Must set game language option to read ingredient lists."); + } + + int num_fillings = 0; + int num_condiments = 0; + std::map fillings; + std::map condiments; + + //Add the selected ingredients to the maps if set to custom + if (SANDWICH_OPTIONS.BASE_RECIPE == BaseRecipe::custom){ + stream.log("Custom sandwich selected. Validating ingredients.", COLOR_BLACK); + stream.overlay().add_log("Custom sandwich selected."); + + std::vector> table = SANDWICH_OPTIONS.SANDWICH_INGREDIENTS.copy_snapshot(); + + for (const std::unique_ptr& row : table){ + const std::string& table_item = row->item.slug(); + if (!(table_item == "baguette")) { //ignore baguette + if (std::find(ALL_SANDWICH_FILLINGS_SLUGS().begin(), ALL_SANDWICH_FILLINGS_SLUGS().end(), table_item) != ALL_SANDWICH_FILLINGS_SLUGS().end()){ + fillings[table_item]++; + num_fillings++; + }else{ + condiments[table_item]++; + num_condiments++; + } + }else{ + stream.log("Skipping baguette as it is unobtainable."); + stream.overlay().add_log("Skipping baguette as it is unobtainable.", COLOR_WHITE); + } + } + + if (num_fillings == 0 || num_condiments == 0){ + throw UserSetupError(stream.logger(), "Must have at least one filling and at least one condiment."); + } + + if (num_fillings > 6 || num_condiments > 4){ + throw UserSetupError(stream.logger(), "Number of fillings exceed 6 and/or number of condiments exceed 4."); + } + stream.log("Ingredients validated.", COLOR_BLACK); + stream.overlay().add_log("Ingredients validated.", COLOR_WHITE); + } +else if(SANDWICH_OPTIONS.BASE_RECIPE == BaseRecipe::non_shiny){ + stream.log("Preset sandwich selected.", COLOR_BLACK); + stream.overlay().add_log("Preset sandwich selected."); + + // std::vector table = SANDWICH_OPTIONS.get_premade_ingredients( + // SANDWICH_OPTIONS.get_premade_sandwich_recipe(SANDWICH_OPTIONS.BASE_RECIPE, SANDWICH_OPTIONS.TYPE, SANDWICH_OPTIONS.PARADOX)); + + // The only non-shiny sandwich added at this time is Normal Encounter. + std::vector table = SANDWICH_OPTIONS.get_premade_ingredients(SandwichRecipe::non_shiny_normal); + + for (auto&& s : table){ + if (std::find(ALL_SANDWICH_FILLINGS_SLUGS().begin(), ALL_SANDWICH_FILLINGS_SLUGS().end(), s) != ALL_SANDWICH_FILLINGS_SLUGS().end()){ + fillings[s]++; + num_fillings++; + }else{ + condiments[s]++; + num_condiments++; + } + } + } + //Otherwise get the preset ingredients + else{ + stream.log("Preset sandwich selected.", COLOR_BLACK); + stream.overlay().add_log("Preset sandwich selected."); + + std::vector table = SANDWICH_OPTIONS.get_premade_ingredients( + SANDWICH_OPTIONS.get_premade_sandwich_recipe(SANDWICH_OPTIONS.BASE_RECIPE, SANDWICH_OPTIONS.TYPE, SANDWICH_OPTIONS.PARADOX)); + + for (auto&& s : table){ + if (std::find(ALL_SANDWICH_FILLINGS_SLUGS().begin(), ALL_SANDWICH_FILLINGS_SLUGS().end(), s) != ALL_SANDWICH_FILLINGS_SLUGS().end()){ + fillings[s]++; + num_fillings++; + }else{ + condiments[s]++; + num_condiments++; + } + } + //Insert Herba Mystica if required + if (SandwichMakerOption::two_herba_required(SANDWICH_OPTIONS.BASE_RECIPE)){ + if (SANDWICH_OPTIONS.HERBA_ONE == SANDWICH_OPTIONS.HERBA_TWO){ + condiments.insert(std::make_pair(SANDWICH_OPTIONS.herba_to_string(SANDWICH_OPTIONS.HERBA_ONE), (uint8_t)2)); + }else{ + condiments.insert(std::make_pair(SANDWICH_OPTIONS.herba_to_string(SANDWICH_OPTIONS.HERBA_ONE), (uint8_t)1)); + condiments.insert(std::make_pair(SANDWICH_OPTIONS.herba_to_string(SANDWICH_OPTIONS.HERBA_TWO), (uint8_t)1)); + } + num_condiments++; + num_condiments++; + } + } + + /* + //Print ingredients + cout << "Fillings:" << endl; + for (const auto& [key, value] : fillings){ + std::cout << key << ": " << (int)value << endl; + } + cout << "Condiments:" << endl; + for (const auto& [key, value] : condiments){ + std::cout << key << ": " << (int)value << endl; + } + */ + + make_sandwich_preset(env, stream, context, SANDWICH_OPTIONS.LANGUAGE, fillings, condiments); +} + +void make_sandwich_preset(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, Language language, std::map& fillings, std::map& condiments){ + //Sort the fillings by priority for building (ex. large items on bottom, cherry tomatoes on top) + //std::vector fillings_game_order = {"lettuce", "tomato", "cherry-tomatoes", "cucumber", "pickle", "onion", "red-onion", "green-bell-pepper", "red-bell-pepper", + // "yellow-bell-pepper", "avocado", "bacon", "ham", "prosciutto", "chorizo", "herbed-sausage", "hamburger", "klawf-stick", "smoked-fillet", "fried-fillet", "egg", "potato-tortilla", + // "tofu", "rice", "noodles", "potato-salad", "cheese", "banana", "strawberry", "apple", "kiwi", "pineapple", "jalapeno", "watercress", "basil"}; + std::vector fillings_game_order = { "hamburger", "rice", "noodles", "smoked-fillet", "fried-fillet", "cucumber", "pickle", "tofu", + "chorizo", "herbed-sausage", "potato-tortilla", "klawf-stick", "lettuce", "tomato", "onion", "red-onion", "green-bell-pepper", "red-bell-pepper", "yellow-bell-pepper", "avocado", + "bacon", "ham", "prosciutto", "cheese", "banana", "strawberry", "apple", "kiwi", "pineapple", "jalape\xc3\xb1o", "watercress", "potato-salad", "egg", "basil", "cherry-tomatoes" }; + + //Add keys to new vector and sort + std::vector fillings_sorted; + for (auto i = fillings.begin(); i != fillings.end(); i++){ + fillings_sorted.push_back(i->first); + } + std::unordered_map temp_map; + for (auto i = 0; i < (int)fillings_game_order.size(); i++){ + temp_map[fillings_game_order[i]] = i; + } + auto compare = [&temp_map](const std::string& s, const std::string& s1){ + return temp_map[s] < temp_map[s1]; + }; + std::sort(fillings_sorted.begin(), fillings_sorted.end(), compare); + + /* + //Print sorted fillings + cout << "Sorted fillings:" << endl; + for (auto i : fillings_sorted){ + cout << i << endl; + } + */ + + //Calculate number of plates there will be on the build screen + //Get each ingredient in list order, then get the number of times it appears from the map + //Also store how many of each ingredient is in each plate (ex. 6 onion in first plate and then 3 onion in the next) + int plates = 0; + std::vector plate_amounts; + + for (const std::string& i : fillings_sorted){ + //Add "full" plates + int plate_calcs = (int)(fillings[i] / FillingsCoordinates::instance().get_filling_information(i).servingsPerPlate); + if (plate_calcs != 0){ + plates += plate_calcs; + for (int j = 0; j < plate_calcs; j++){ + plate_amounts.push_back( + (int)(FillingsCoordinates::instance().get_filling_information(i).servingsPerPlate) + *(int)(FillingsCoordinates::instance().get_filling_information(i).piecesPerServing) + ); + } + } + + //Add plates for remaining servings + int plate_remaining = ((int)(fillings[i] % FillingsCoordinates::instance().get_filling_information(i).servingsPerPlate)); + if (plate_remaining != 0){ + plates++; + plate_amounts.push_back(plate_remaining * (int)(FillingsCoordinates::instance().get_filling_information(i).piecesPerServing)); + } + } + //cout << "Number of plates: " << plates << endl; + int plates_string = plates; + stream.log("Number of plates: " + std::to_string(plates_string), COLOR_BLACK); + stream.overlay().add_log("Number of plates: " + std::to_string(plates_string), COLOR_WHITE); + for (const auto& filling: fillings){ + env.log("Require filling " + filling.first + " x" + std::to_string(int(filling.second))); + } + for (const auto& condiment: condiments){ + env.log("Require condiment " + condiment.first + " x" + std::to_string(int(condiment.second))); + } + + //Player must be on default sandwich menu + std::map fillings_copy(fillings); //Making a copy as we need the map for later + enter_custom_sandwich_mode(env.program_info(), stream, context); + add_sandwich_ingredients( + env.normal_inference_dispatcher(), + stream, context, + language, + std::move(fillings_copy), + std::move(condiments) + ); + + run_sandwich_maker(env, stream, context, language, fillings, fillings_sorted, plates); +} + +void run_sandwich_maker(ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, Language language, std::map& fillings, std::vector& fillings_sorted, int& plates){ + + wait_for_initial_hand(env.program_info(), stream, context); + + //Wait for labels to appear + stream.log("Waiting for labels to appear.", COLOR_BLACK); + stream.overlay().add_log("Waiting for labels to appear.", COLOR_WHITE); + pbf_wait(context, 300); + context.wait_for_all_requests(); + + //Now read in plate labels and store which plate has what + stream.log("Reading plate labels.", COLOR_BLACK); + stream.overlay().add_log("Reading plate labels.", COLOR_WHITE); + + std::vector plate_order; + + SandwichPlateDetector left_plate_detector(stream.logger(), COLOR_RED, language, SandwichPlateDetector::Side::LEFT); + SandwichPlateDetector middle_plate_detector(stream.logger(), COLOR_RED, language, SandwichPlateDetector::Side::MIDDLE); + SandwichPlateDetector right_plate_detector(stream.logger(), COLOR_RED, language, SandwichPlateDetector::Side::RIGHT); + bool left_plate_absent = false; + bool right_plate_absent = false; + { + VideoSnapshot screen = stream.video().snapshot(); + + const int max_read_label_tries = 4; + for (int read_label_try_count = 0; read_label_try_count < max_read_label_tries; ++read_label_try_count){ + std::string center_filling = middle_plate_detector.detect_filling_name(screen); + if (center_filling.empty()){ + if (read_label_try_count + 1 < max_read_label_tries){ + // Wait more time + pbf_wait(context, TICKS_PER_SECOND * 2); + context.wait_for_all_requests(); + screen = stream.video().snapshot(); + continue; + }else{ + stream.log("Read nothing on center plate label."); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No ingredient found on center plate label.", + stream, + std::move(screen) + ); + } + } + stream.log("Read center plate label: " + center_filling); + stream.overlay().add_log("Center plate: " + center_filling); + plate_order.push_back(center_filling); + break; + } + + //Get left (2nd) ingredient + std::string left_filling = left_plate_detector.detect_filling_name(screen); + left_plate_absent = left_filling.empty(); + if (left_plate_absent){ + stream.log("No ingredient found on left label."); + stream.overlay().add_log("No left plate"); + }else{ + stream.log("Read left plate label: " + left_filling); + stream.overlay().add_log("Left plate: " + left_filling); + plate_order.push_back(left_filling); + } + + //Get right (3rd) ingredient + std::string right_filling = right_plate_detector.detect_filling_name(screen); + right_plate_absent = right_filling.empty(); + if (right_plate_absent){ + stream.log("No ingredient found on right label."); + stream.overlay().add_log("No right plate"); + }else{ + stream.log("Read right plate label: " + right_filling); + stream.overlay().add_log("Right plate: " + right_filling); + plate_order.push_back(right_filling); + } + + //Get remaining ingredients if any + //center 1, left 2, right 3, far left 4, far far left/right 5, right 6 + //this differs from the game layout: far right is 5 and far far left/right is 6 in game + //however as long as we stay internally consistent with this numbering it will work + for (int i = 0; i < (plates - 3); i++){ + pbf_press_button(context, BUTTON_R, 20, 180); + context.wait_for_all_requests(); + + screen = stream.video().snapshot(); + left_filling = left_plate_detector.detect_filling_name(screen); + + if (left_filling.empty()){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No ingredient label found on remaining plate " + std::to_string(i) + ".", + stream, + std::move(screen) + ); + } + stream.log("Read remaining plate " + std::to_string(i) + " label: " + left_filling); + stream.overlay().add_log("Remaining plate " + std::to_string(i) + ": " + left_filling); + plate_order.push_back(left_filling); + } + + //Now re-center plates + stream.log("Re-centering plates if needed."); + stream.overlay().add_log("Re-centering plates if needed."); + for (int i = 0; i < (plates - 3); i++){ + pbf_press_button(context, BUTTON_L, 20, 80); + } + + //If a label fails to read it'll cause issues down the line + if ((int)plate_order.size() != plates){ + env.log("Found # plate labels " + std::to_string(plate_order.size()) + ", not same as desired # plates " + std::to_string(plates)); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Number of plate labels did not match number of plates.", + stream, + std::move(screen) + ); + } + } + + //Finally. + stream.log("Start making sandwich", COLOR_BLACK); + stream.overlay().add_log("Start making sandwich.", COLOR_WHITE); + + const ImageFloatBox center_plate{ 0.455, 0.130, 0.090, 0.030 }; + const ImageFloatBox left_plate{ 0.190, 0.136, 0.096, 0.031 }; + const ImageFloatBox right_plate{ 0.715, 0.140, 0.108, 0.033 }; + + ImageFloatBox target_plate = center_plate; + //Initial position handling + auto end_box = move_sandwich_hand( + env.program_info(), env.realtime_inference_dispatcher(), + stream, context, + SandwichHandType::FREE, + false, + HAND_INITIAL_BOX, + HAND_INITIAL_BOX + ); + move_sandwich_hand( + env.program_info(), env.realtime_inference_dispatcher(), + stream, context, + SandwichHandType::GRABBING, + true, + { 0, 0, 1.0, 1.0 }, + HAND_INITIAL_BOX + ); + context.wait_for_all_requests(); + + //Find fillings and add them in order + for (const std::string& i : fillings_sorted){ + //cout << "Placing " << i << endl; + stream.log("Placing " + i, COLOR_WHITE); + stream.overlay().add_log("Placing " + i, COLOR_WHITE); + + int times_to_place = (int)(FillingsCoordinates::instance().get_filling_information(i).piecesPerServing) * (fillings.find(i)->second); + int placement_number = 0; + + //cout << "Times to place: " << times_to_place << endl; + stream.log("Times to place: " + std::to_string(times_to_place), COLOR_WHITE); + stream.overlay().add_log("Times to place: " + std::to_string(times_to_place), COLOR_WHITE); + + std::vector plate_index; + //Get the plates we want to go to + for (int j = 0; j < (int)plate_order.size(); j++){ + if (i == plate_order.at(j)){ + plate_index.push_back(j); + } + } + + //Target the correct filling plate and place until it is empty + for (int j = 0; j < (int)plate_index.size(); j++){ + //Navigate to plate and set target plate + //cout << "Target plate: " << plate_index.at(j) << endl; + stream.log("Target plate: " + std::to_string(plate_index.at(j)), COLOR_WHITE); + stream.overlay().add_log("Target plate: " + std::to_string(plate_index.at(j)), COLOR_WHITE); + SandwichPlateDetector::Side target_plate_label = SandwichPlateDetector::Side::MIDDLE; + switch (plate_index.at(j)){ + case 0: + target_plate = center_plate; + break; + case 1: + target_plate = left_plate; + target_plate_label = SandwichPlateDetector::Side::LEFT; + break; + case 2: + target_plate = right_plate; + target_plate_label = SandwichPlateDetector::Side::RIGHT; + break; + case 3: case 4: case 5: case 6: + //Press R the appropriate number of times + for (int k = 2; k < plate_index.at(j); k++){ + pbf_press_button(context, BUTTON_R, 20, 80); + } + target_plate = left_plate; + target_plate_label = SandwichPlateDetector::Side::LEFT; + break; + default: + break; + } + + // place down all the ingredients for the current plate. + //Place the fillings until label does not light up yellow on grab/the piece count is not hit + while (true){ + //Break out after placing all pieces of the filling + if (placement_number == times_to_place){ + stream.log("We have placed down enough ingredients of that type, so we assume our current plate is empty. Move on to the next plate/ingredient.", COLOR_ORANGE); + break; + } + + end_box = move_sandwich_hand( + env.program_info(), env.realtime_inference_dispatcher(), + stream, context, + SandwichHandType::FREE, + false, + { 0, 0, 1.0, 1.0 }, + target_plate + ); + context.wait_for_all_requests(); + + //Get placement location + ImageFloatBox placement_target = FillingsCoordinates::instance().get_filling_information(i).placementCoordinates.at( + (int)fillings.find(i)->second).at(placement_number); + + HandMoveData hand_move_data = move_sandwich_hand_and_check_if_plates_empty( + env.program_info(), env.realtime_inference_dispatcher(), + stream, context, + SandwichHandType::GRABBING, + true, + expand_box(end_box), + placement_target, + target_plate_label + ); + end_box = hand_move_data.end_box; + context.wait_for_all_requests(); + + // If the current plate is empty, break out of the loop and move on to the next plate. + if (hand_move_data.plate_empty){ + context.wait_for_all_requests(); + stream.log("Our current plate label is NOT yellow, so we assume our current plate is empty. Move on to the next plate.", COLOR_ORANGE); + break; + } + + stream.log("Our current plate label is yellow, so we assume our current plate is NOT empty. Continue with the current plate.", COLOR_YELLOW); + + //If the plate is empty the increment is skipped using the above break + placement_number++; + } + + //Reset plate positions + for (int k = 2; k < plate_index.at(j); k++){ + pbf_press_button(context, BUTTON_L, 20, 80); + } + } + } + + context.wait_for_all_requests(); + context.wait_for(Milliseconds(500)); + stream.log("All ingredients should now be empty. Wait for upper bread.", COLOR_YELLOW); + // Handle top slice by tossing it away + SandwichHandWatcher grabbing_hand(SandwichHandType::GRABBING, { 0, 0, 1.0, 1.0 }); + int ret = wait_until(stream, context, std::chrono::seconds(30), { grabbing_hand }); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "SandwichMaker: Cannot detect grabbing hand when waiting for upper bread.", + stream, + grabbing_hand.last_snapshot() + ); + } + + auto hand_box = hand_location_to_box(grabbing_hand.location()); + + end_box = move_sandwich_hand( + env.program_info(), env.realtime_inference_dispatcher(), + stream, context, + SandwichHandType::GRABBING, + false, + expand_box(hand_box), + center_plate + ); + pbf_mash_button(context, BUTTON_A, 125 * 5); + + env.log("Hand end box " + box_to_string(end_box)); + env.log("Built sandwich", COLOR_BLACK); + // env.console.overlay().add_log("Hand end box " + box_to_string(end_box), COLOR_WHITE); + stream.overlay().add_log("Built sandwich.", COLOR_WHITE); + context.wait_for_all_requests(); + + finish_sandwich_eating(env.program_info(), stream, context); +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h index d0bc78c238..22e47ee4e8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h @@ -1,129 +1,129 @@ -/* Sandwich Routines - * - * From: https://github.com/PokemonAutomation/ - * - * Various functions to do sandwich making related automation. - * This file is used to share sandwich related code among different programs (egg auto, sandwich auto, etc.). - */ - -#ifndef PokemonAutomation_PokemonSV_SandwichRoutines_H -#define PokemonAutomation_PokemonSV_SandwichRoutines_H - -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" - -namespace PokemonAutomation{ - - struct ProgramInfo; - class AsyncDispatcher; - class ProgramEnvironment; - -namespace NintendoSwitch{ -namespace PokemonSV{ - -// Assuming at picnic table, press A to start making sandwich. -// The function returns when the game shows the sandwich recipe menu. -// Return true if it enters the recipe menu. Return false if there is no ingredients on the plyaer character so -// no sandwich can be made. -bool enter_sandwich_recipe_list( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// Starting at sandwich recipe selection menu, select the desired sandwich recipe and press A to enter -// the making sandwich mini game. It will use the first sandwich pick in the sandwich pick selection list. -// sandwich_index: [1, 151]. -// Return true if it successfully finds and starts the recipe. -// Return false if the function fails to find the recipe. This could be that ingredients are not enough, and therefore -// the recipe cell is semi-transparent, failed to be detected. -bool select_sandwich_recipe( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t sandwich_index -); - -// Assuming sandwich is made, press A repeatedly to finish eating animation until returning to picnic -void finish_sandwich_eating( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -// Assuming at sanwich recipe list, press X to enter custom sandwich mode -void enter_custom_sandwich_mode( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context -); - -enum class EggSandwichType{ - GREAT_PEANUT_BUTTER, - TWO_SWEET_HERBS, - BITTER_SWEET_HERBS, - SALTY_SWEET_HERBS -}; - -// Assuming starting at the custom sandwich mode, -// select lettuce (assuming the first entry in the filling list), then select two herbs (two sweets, bitter sweet or salty sweet) in the end -// of the condiments list. The location of herbs are set by `xxx_herb_index_last`: -// if a herb is the last entry, set `xxx_herb_index_last` to 0; -// if a herb is second to last, set `xxx_herb_index_last` to 1; ... -// It will use the first sandwich pick in the sandwich pick selection list. -// After entering sandiwich mini game, it will drop the filling to quickly make a two-herb only sandwich to gain egg power lv 3. -void make_two_herbs_sandwich( - const ProgramInfo& info, AsyncDispatcher& dispatcher, - VideoStream& stream, ProControllerContext& context, - EggSandwichType sandwich_type, - size_t sweet_herb_index_last, - size_t salty_herb_index_last, - size_t bitter_herb_index_last -); -// Assuming starting at the custom sandwich mode, -// select lettuce and two herbs (two sweets, bitter sweet or salty sweet according to `sandwich_type`). -// It will use the first sandwich pick in the sandwich pick selection list. -// After entering sandiwich mini game, it will drop the filling to quickly make a two-herb only sandwich to gain egg power lv 3. -void make_two_herbs_sandwich( - const ProgramInfo& info, - AsyncDispatcher& dispatcher, VideoStream& stream, - ProControllerContext& context, - EggSandwichType sandwich_type, - Language language -); - -// Assuming starting at the sandwich recipe list, -// Process sandwich options and make a custom sandwich by calling make_sandwich_preset -void make_sandwich_option( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - SandwichMakerOption& SANDWICH_OPTIONS -); - -// Assuming starting at the sandwich recipe list, make a sandwich given a preset ingredient/filling list -// calls run_sandwich_maker() when done -// ex. fillings = {{"apple", (uint8_t)1}}; condiments = {{"marmalade", (uint8_t)1}}; -// make_sandwich_preset(env, context, language, fillings, condiments); -void make_sandwich_preset( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - std::map& fillings, - std::map& condiments -); - -// Assuming starting waiting for sandwich hand, -// Take a list of ingredients and make a sandwich -// Not meant to be run directly, use make_sandwich_option() or make_sandwich_preset() instead -// make great pb sandwich does call this directly, as it skips the custom sandwich menu -void run_sandwich_maker( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - std::map& fillings, std::vector& fillings_sorted, - int& plates -); - -} -} -} -#endif +/* Sandwich Routines + * + * From: https://github.com/PokemonAutomation/ + * + * Various functions to do sandwich making related automation. + * This file is used to share sandwich related code among different programs (egg auto, sandwich auto, etc.). + */ + +#ifndef PokemonAutomation_PokemonSV_SandwichRoutines_H +#define PokemonAutomation_PokemonSV_SandwichRoutines_H + +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" + +namespace PokemonAutomation{ + + struct ProgramInfo; + class AsyncDispatcher; + class ProgramEnvironment; + +namespace NintendoSwitch{ +namespace PokemonSV{ + +// Assuming at picnic table, press A to start making sandwich. +// The function returns when the game shows the sandwich recipe menu. +// Return true if it enters the recipe menu. Return false if there is no ingredients on the plyaer character so +// no sandwich can be made. +bool enter_sandwich_recipe_list( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// Starting at sandwich recipe selection menu, select the desired sandwich recipe and press A to enter +// the making sandwich mini game. It will use the first sandwich pick in the sandwich pick selection list. +// sandwich_index: [1, 151]. +// Return true if it successfully finds and starts the recipe. +// Return false if the function fails to find the recipe. This could be that ingredients are not enough, and therefore +// the recipe cell is semi-transparent, failed to be detected. +bool select_sandwich_recipe( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t sandwich_index +); + +// Assuming sandwich is made, press A repeatedly to finish eating animation until returning to picnic +void finish_sandwich_eating( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +// Assuming at sanwich recipe list, press X to enter custom sandwich mode +void enter_custom_sandwich_mode( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context +); + +enum class EggSandwichType{ + GREAT_PEANUT_BUTTER, + TWO_SWEET_HERBS, + BITTER_SWEET_HERBS, + SALTY_SWEET_HERBS +}; + +// Assuming starting at the custom sandwich mode, +// select lettuce (assuming the first entry in the filling list), then select two herbs (two sweets, bitter sweet or salty sweet) in the end +// of the condiments list. The location of herbs are set by `xxx_herb_index_last`: +// if a herb is the last entry, set `xxx_herb_index_last` to 0; +// if a herb is second to last, set `xxx_herb_index_last` to 1; ... +// It will use the first sandwich pick in the sandwich pick selection list. +// After entering sandiwich mini game, it will drop the filling to quickly make a two-herb only sandwich to gain egg power lv 3. +void make_two_herbs_sandwich( + const ProgramInfo& info, AsyncDispatcher& dispatcher, + VideoStream& stream, ProControllerContext& context, + EggSandwichType sandwich_type, + size_t sweet_herb_index_last, + size_t salty_herb_index_last, + size_t bitter_herb_index_last +); +// Assuming starting at the custom sandwich mode, +// select lettuce and two herbs (two sweets, bitter sweet or salty sweet according to `sandwich_type`). +// It will use the first sandwich pick in the sandwich pick selection list. +// After entering sandiwich mini game, it will drop the filling to quickly make a two-herb only sandwich to gain egg power lv 3. +void make_two_herbs_sandwich( + const ProgramInfo& info, + AsyncDispatcher& dispatcher, VideoStream& stream, + ProControllerContext& context, + EggSandwichType sandwich_type, + Language language +); + +// Assuming starting at the sandwich recipe list, +// Process sandwich options and make a custom sandwich by calling make_sandwich_preset +void make_sandwich_option( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + SandwichMakerOption& SANDWICH_OPTIONS +); + +// Assuming starting at the sandwich recipe list, make a sandwich given a preset ingredient/filling list +// calls run_sandwich_maker() when done +// ex. fillings = {{"apple", (uint8_t)1}}; condiments = {{"marmalade", (uint8_t)1}}; +// make_sandwich_preset(env, context, language, fillings, condiments); +void make_sandwich_preset( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + std::map& fillings, + std::map& condiments +); + +// Assuming starting waiting for sandwich hand, +// Take a list of ingredients and make a sandwich +// Not meant to be run directly, use make_sandwich_option() or make_sandwich_preset() instead +// make great pb sandwich does call this directly, as it skips the custom sandwich menu +void run_sandwich_maker( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + std::map& fillings, std::vector& fillings_sorted, + int& plates +); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp index 579d481401..9d5ec30b39 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.cpp @@ -1,557 +1,557 @@ -/* Area Zero Platform - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h" -#include "PokemonSV/Programs/PokemonSV_AreaZero.h" -#include "PokemonSV_LetsGoTools.h" -#include "PokemonSV_AreaZeroPlatform.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -PlatformResetSettings::~PlatformResetSettings(){ - ENCOUNTERS_IN_WINDOW.remove_listener(*this); - KILLS_IN_WINDOW0.remove_listener(*this); - WINDOW_IN_MINUTES.remove_listener(*this); -} -PlatformResetSettings::PlatformResetSettings() - : GroupOption( - "Platform Reset Conditions", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_ENABLED - ) - , m_description( - "A \"Platform Reset\" is when you fly to Zero Gate, then return to the " - "platform. This is usually done to recover from falling off the " - "platform or to reset the spawns on the platform.

" - "The reason for resetting spawns is that over time, the " + STRING_POKEMON + - " can spawn in inaccessible places. When there are too few spawns, the " - "kill and encounter rates will drop to very inefficient levels. " - "Resetting the spawns will fix this, at the cost of also despawning any " - "shinies that have not yet been encountered." - ) - , m_sliding_window("") - , WINDOW_IN_MINUTES( - "Time Window (in minutes):
The sliding time window for which to watch for kills and encounters.", - LockMode::UNLOCK_WHILE_RUNNING, - 10 - ) - , KILLS_IN_WINDOW0( - "Kills in Window:
If the number of kills in the last X seconds has drops below this value, consider resetting.", - LockMode::UNLOCK_WHILE_RUNNING, - 20 - ) - , ENCOUNTERS_IN_WINDOW( - "Encounters in Window:
If the number of encounters in the last X seconds has drops below this value, consider resetting.", - LockMode::UNLOCK_WHILE_RUNNING, - 5 - ) -#if 0 - , RESET_DURATION_MINUTES( - "Reset Duration (minutes):
If you are resetting, reset the game every " - "this many minutes.", - LockMode::UNLOCK_WHILE_RUNNING, - 180 - ) -#endif -{ - PA_ADD_STATIC(m_description); - - PA_ADD_STATIC(m_sliding_window); - PA_ADD_OPTION(WINDOW_IN_MINUTES); - PA_ADD_OPTION(KILLS_IN_WINDOW0); - PA_ADD_OPTION(ENCOUNTERS_IN_WINDOW); - -// PA_ADD_OPTION(RESET_DURATION_MINUTES); - - PlatformResetSettings::on_config_value_changed(this); - - WINDOW_IN_MINUTES.add_listener(*this); - KILLS_IN_WINDOW0.add_listener(*this); - ENCOUNTERS_IN_WINDOW.add_listener(*this); -} - -std::string int_to_text(size_t value, const std::string& unit){ - std::string str = "" + std::to_string(value) + " "; - str += unit; - if (value != 1){ - str += "s"; - } - return str; -} -void PlatformResetSettings::on_config_value_changed(void* object){ - m_sliding_window.set_text( - "Perform a platform reset if there are fewer than " + int_to_text(KILLS_IN_WINDOW0, "kill") + - " and " + int_to_text(ENCOUNTERS_IN_WINDOW, "encounter") + - " in the last " + int_to_text(WINDOW_IN_MINUTES, "minute") + "." - ); -} - - -NavigatePlatformSettings::NavigatePlatformSettings() - : GroupOption("Navigate to Platform Settings", LockMode::UNLOCK_WHILE_RUNNING) - , m_description( - "These settings are used when traveling from Zero Gate to the platform. " - "This can happen either at program start or during a platform reset." - ) - , HEAL_AT_STATION( - "Heal at Station:
If you're passing through the station, take the opportunity to heal up.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , STATION_ARRIVE_PAUSE_SECONDS( - "Station Arrive Pause Time:
Pause for this many seconds after leaving the station. " - "This gives the game time to load and thus reduce the chance of lag affecting the flight path.", - LockMode::UNLOCK_WHILE_RUNNING, - 1 - ) - , MIDAIR_PAUSE_TIME0( - "Mid-Air Pause Time:
Pause for this long before final approach to the platform. " - "Too small and you may crash into the wall above the platform or have reduced spawns. " - "Too large and you may undershoot the platform.", - LockMode::UNLOCK_WHILE_RUNNING, - "400 ms" - ) -{ - PA_ADD_STATIC(m_description); - PA_ADD_OPTION(HEAL_AT_STATION); - PA_ADD_OPTION(STATION_ARRIVE_PAUSE_SECONDS); - PA_ADD_OPTION(MIDAIR_PAUSE_TIME0); -} - - -void inside_zero_gate_to_platform( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool flying_unlocked, - NavigatePlatformSettings& settings -){ - inside_zero_gate_to_station(info, stream, context, 2, settings.HEAL_AT_STATION); - - context.wait_for(std::chrono::seconds(settings.STATION_ARRIVE_PAUSE_SECONDS)); - - // Navigate to platform. -#if 0 - // Don't jump to avoid spawn. - pbf_press_button(context, BUTTON_PLUS, 20, 105); - pbf_move_left_joystick(context, 128, 0, 625, 0); - ssf_press_button(context, BUTTON_B, 0, 50); - pbf_move_left_joystick(context, 128, 0, 250, 0); - pbf_move_left_joystick(context, 160, 0, 600, 0); - pbf_move_left_joystick(context, 128, 0, 1875, 0); -#endif - -#if 0 - // Jump late. - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - ssf_press_joystick(context, true, 128, 0, 315, 500); - - // Jump - ssf_press_button(context, BUTTON_B, 125, 100); - - // Fly - ssf_press_button(context, BUTTON_B, 0, 50); - - pbf_move_left_joystick(context, 144, 0, 1150, 0); - pbf_move_left_joystick(context, 128, 0, 125, NAVIGATE_TO_PLATFORM.MIDAIR_PAUSE_TIME); - - pbf_move_left_joystick(context, 128, 0, 1375, 250); -#endif - -#if 0 - // Jump earlier. - pbf_press_button(context, BUTTON_PLUS, 20, 105); - - ssf_press_joystick(context, true, 128, 0, 280, 500); - - // Jump - ssf_press_button(context, BUTTON_B, 125, 100); - - // Fly - ssf_press_button(context, BUTTON_B, 0, 50); - - pbf_move_left_joystick(context, 144, 0, 1150, 0); - pbf_move_left_joystick(context, 128, 0, 125, NAVIGATE_TO_PLATFORM.MIDAIR_PAUSE_TIME); - - pbf_move_left_joystick(context, 128, 0, 1375, 250); -#endif - -#if 1 - // Jump on the downhill to improve chance of clearing things. - pbf_move_left_joystick(context, 192, 0, 20, 105); - pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); - - ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); - if (!flying_unlocked){ - ssf_press_left_joystick(context, 128, 0, 125, 1250); - }else{ - ssf_press_left_joystick(context, 128, 0, 125, 875); - } - - // Jump - ssf_press_button(context, BUTTON_B, 1000ms, 800ms); - - // Fly - ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in - ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. - - if (!flying_unlocked){ -// ssf_press_left_joystick(context, 128, 0, 375, 875); - pbf_move_left_joystick(context, 144, 0, 700, 0); - pbf_move_left_joystick(context, 128, 0, 1000ms, settings.MIDAIR_PAUSE_TIME0); - pbf_move_left_joystick(context, 128, 0, 875, 250); - }else{ -// ssf_press_button(context, BUTTON_B, 0, 20); -// pbf_move_left_joystick(context, 128, 0, 375, 250); - pbf_move_left_joystick(context, 164, 0, 1000ms, settings.MIDAIR_PAUSE_TIME0); - pbf_press_button(context, BUTTON_LCLICK, 50, 0); - ssf_press_right_joystick(context, 128, 255, 0, 1500); - pbf_move_left_joystick(context, 128, 255, 1600, 125); - - pbf_press_button(context, BUTTON_B, 125, 375); - - } -#endif - -// context.wait_for_all_requests(); - pbf_press_button(context, BUTTON_PLUS, 20, 105); - ssf_press_left_joystick(context, 128, 0, 1 * TICKS_PER_SECOND, 4 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_R, 20, 355); - pbf_press_button(context, BUTTON_R, 20, 105); - - context.wait_for_all_requests(); -} - - -bool read_platform_center( - double& x, double& y, - const ProgramInfo& info, VideoStream& stream -){ - using namespace Kernels::Waterfill; - - VideoSnapshot screen = stream.video().snapshot(); - if (!screen){ - return false; - } - - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(screen, 0xff000040, 0xff8080ff); - -// size_t min_width = screen.width() / 4; -// size_t min_height = screen.height() / 4; - - WaterfillObject biggest; - WaterfillObject object; - - std::unique_ptr session = make_WaterfillSession(matrix); - size_t min_area = screen->width() * screen->height() / 10; - auto iter = session->make_iterator(min_area); - while (iter->find_next(object, false)){ -// if (object.min_y != 0){ -// continue; -// } - if (biggest.area < object.area){ - biggest = std::move(object); - } - } - - if (biggest.area == 0){ - return false; - } - - x = biggest.center_of_gravity_x() / screen->width(); - y = biggest.center_of_gravity_y() / screen->height(); - - return true; -} - - - -void area_zero_platform_run_path0( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - uint64_t iteration_count -){ - // Go back to the wall. - stream.log("Go back to wall..."); - use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ - find_and_center_on_sky(env, stream, context); - pbf_move_right_joystick(context, 128, 255, 80, 0); - pbf_move_left_joystick(context, 176, 255, 30, 0); - pbf_press_button(context, BUTTON_L, 20, 50); - }); - - use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ - // Move to wall. - pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 0); - - // Turn around. - stream.log("Turning towards sky..."); - pbf_move_left_joystick(context, 128, 255, 30, 95); - pbf_press_button(context, BUTTON_L, 20, 50); - }); - - // Move forward and kill everything in your path. - stream.log("Moving towards sky and killing everything..."); - uint16_t duration = 325; - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - find_and_center_on_sky(env, stream, context); - pbf_move_right_joystick(context, 128, 255, 70, 0); - - uint8_t x = 128; - switch (iteration_count % 4){ - case 0: - x = 96; - duration = 250; - break; - case 1: - x = 112; - break; - case 2: - x = 128; - break; - case 3: - x = 112; - break; - } - - ssf_press_button(context, BUTTON_L, 0ms, 160ms); - pbf_move_left_joystick(context, x, 0, duration, 0); - }); - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, duration, 4 * TICKS_PER_SECOND); - }); -} -void area_zero_platform_run_path1( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - uint64_t iteration_count -){ - // Go back to the wall. - stream.log("Go back to wall..."); - pbf_press_button(context, BUTTON_L, 20, 105); - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - find_and_center_on_sky(env, stream, context); - pbf_move_right_joystick(context, 128, 255, 80, 0); - pbf_move_left_joystick(context, 192, 255, 60, 0); - }); - - // Clear path to the wall. - stream.log("Clear path to the wall..."); - pbf_press_button(context, BUTTON_L, 20, 50); - use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 0, 5 * TICKS_PER_SECOND, 0); - - // Turn right. - pbf_move_left_joystick(context, 255, 128, 30, 0); - pbf_press_button(context, BUTTON_L, 20, 50); - }); - - // Clear the wall. - stream.log("Clear the wall..."); - uint16_t duration = 325; - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 255, 128, 125, 0); - pbf_press_button(context, BUTTON_L, 20, 50); - context.wait_for_all_requests(); - - find_and_center_on_sky(env, stream, context); - pbf_move_left_joystick(context, 128, 0, 50, 0); - pbf_press_button(context, BUTTON_L, 20, 30); - - // Move forward. - - uint8_t x = 128; - switch (iteration_count % 4){ - case 0: - x = 96; - duration = 250; - break; - case 1: - x = 112; - break; - case 2: - x = 128; - break; - case 3: - x = 112; - break; - } - - pbf_move_left_joystick(context, x, 0, duration, 0); - }); - - stream.log("Run backwards and wait..."); - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ -// pbf_move_left_joystick(context, 64, 0, 125, 0); -// pbf_press_button(context, BUTTON_L, 20, 105); - pbf_move_left_joystick(context, 128, 255, duration, 4 * TICKS_PER_SECOND); -// pbf_controller_state(context, 0, DPAD_NONE, 255, 255, 120, 128, 3 * TICKS_PER_SECOND); - }); -} - - -void direction_to_stick( - uint8_t& joystick_x, uint8_t& joystick_y, - double direction_x, double direction_y -){ -// cout << "direction = " << direction_x << ", " << direction_y << endl; - - double scale = std::max(std::abs(direction_x), std::abs(direction_y)); - direction_x = 128 / scale * direction_x + 128; - direction_y = 128 / scale * direction_y + 128; - -// cout << "joystick = " << direction_x << ", " << direction_y << endl; - - direction_x = std::min(direction_x, 255.); - direction_x = std::max(direction_x, 0.); - direction_y = std::min(direction_y, 255.); - direction_y = std::max(direction_y, 0.); - - joystick_x = (uint8_t)direction_x; - joystick_y = (uint8_t)direction_y; -} -void choose_path( - Logger& logger, - uint8_t& x, uint8_t& y, uint16_t& duration, - double platform_x, double platform_y -){ - double diff_x = platform_x - 0.62; - double diff_y = platform_y - 0.71; - - logger.log("Move Direction: x = " + tostr_default(diff_x) + ", y = " + tostr_default(diff_y), COLOR_BLUE); - - direction_to_stick(x, y, diff_x, diff_y); - duration = (uint16_t)std::min(std::sqrt(diff_x*diff_x + diff_y*diff_y) * 125 * 12, 400); -} -void turn_angle(ProControllerContext& context, double angle_radians){ - uint8_t turn_x, turn_y; - direction_to_stick(turn_x, turn_y, -std::sin(angle_radians), std::cos(angle_radians)); - pbf_move_left_joystick(context, turn_x, turn_y, 40, 20); - pbf_mash_button(context, BUTTON_L, 60); -} - -void area_zero_platform_run_path2( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - uint64_t iteration_count -){ - stream.log("Look forward and fire..."); - pbf_mash_button(context, BUTTON_L, 60); - - double platform_x, platform_y; - uint16_t duration; - uint8_t move_x, move_y; - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - - stream.log("Find the sky, turn around and fire."); - pbf_move_right_joystick(context, 128, 0, 60, 0); - find_and_center_on_sky(env, stream, context); - context.wait_for(std::chrono::seconds(1)); - pbf_move_left_joystick(context, 128, 255, 40, 85); - pbf_mash_button(context, BUTTON_L, 60); - - pbf_move_right_joystick(context, 128, 255, 250, 0); - context.wait_for_all_requests(); - - stream.log("Finding center of platform..."); - if (!read_platform_center(platform_x, platform_y, env.program_info(), stream)){ - stream.log("Unable to find center of platform.", COLOR_RED); - return; - } - stream.log("Platform center at: x = " + tostr_default(platform_x) + ", y = " + tostr_default(platform_y), COLOR_BLUE); - - choose_path(stream.logger(), move_x, move_y, duration, platform_x, platform_y); - - pbf_move_left_joystick(context, move_x, move_y, 40, 20); - pbf_mash_button(context, BUTTON_L, 60); -// pbf_wait(context, 1250); - }); - use_lets_go_to_clear_in_front(stream, context, tracker, duration > 100, [&](ProControllerContext& context){ - stream.log("Making location correction..."); - pbf_move_left_joystick(context, 128, 0, duration, 0); - - // Optimization, calculate angle to aim you back at the sky. - // This speeds up the "find_and_center_on_sky()" call. - double angle0 = std::atan2(move_x - 128., 128. - move_y); - double angle1 = angle0 >= 0 ? 6.2831853071795864769 - angle0 : -6.2831853071795864769 - angle0; - turn_angle(context, angle1); - - find_and_center_on_sky(env, stream, context); - pbf_move_left_joystick(context, 96, 0, 40, 0); - pbf_mash_button(context, BUTTON_L, 60); - }); - - // One in every 4 iterations: Clear wall of spawns. - if (iteration_count % 4 == 0){ - stream.log("Turning along wall..."); - pbf_move_left_joystick(context, 0, 255, 20, 20); - pbf_mash_button(context, BUTTON_L, 60); - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - context.wait_for(std::chrono::milliseconds(1000)); - - stream.log("Turning back to sky."); - pbf_move_left_joystick(context, 255, 255, 20, 20); - pbf_mash_button(context, BUTTON_L, 60); - find_and_center_on_sky(env, stream, context); - pbf_move_left_joystick(context, 96, 0, 40, 0); - pbf_mash_button(context, BUTTON_L, 60); - }); - } - - if (platform_x < 0.5 || platform_y < 0.5){ - stream.log("Not close enough to desired spot. Skipping forward attack...", COLOR_ORANGE); - return; - } - - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - stream.log("Move forward, fire, and retreat."); - switch (iteration_count % 3){ - case 0: - pbf_move_left_joystick(context, 108, 0, 300, 0); - break; - case 1: - pbf_move_left_joystick(context, 128, 0, 300, 0); - break; - case 2: - pbf_move_left_joystick(context, 144, 0, 300, 0); - break; - } - }); - - use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 4 * TICKS_PER_SECOND, 0); - pbf_move_left_joystick(context, 128, 0, 60, 4 * TICKS_PER_SECOND); - }); -} - - - - - - - -} -} -} +/* Area Zero Platform + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_AreaZeroSkyDetector.h" +#include "PokemonSV/Programs/PokemonSV_AreaZero.h" +#include "PokemonSV_LetsGoTools.h" +#include "PokemonSV_AreaZeroPlatform.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +PlatformResetSettings::~PlatformResetSettings(){ + ENCOUNTERS_IN_WINDOW.remove_listener(*this); + KILLS_IN_WINDOW0.remove_listener(*this); + WINDOW_IN_MINUTES.remove_listener(*this); +} +PlatformResetSettings::PlatformResetSettings() + : GroupOption( + "Platform Reset Conditions", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_ENABLED + ) + , m_description( + "A \"Platform Reset\" is when you fly to Zero Gate, then return to the " + "platform. This is usually done to recover from falling off the " + "platform or to reset the spawns on the platform.

" + "The reason for resetting spawns is that over time, the " + STRING_POKEMON + + " can spawn in inaccessible places. When there are too few spawns, the " + "kill and encounter rates will drop to very inefficient levels. " + "Resetting the spawns will fix this, at the cost of also despawning any " + "shinies that have not yet been encountered." + ) + , m_sliding_window("") + , WINDOW_IN_MINUTES( + "Time Window (in minutes):
The sliding time window for which to watch for kills and encounters.", + LockMode::UNLOCK_WHILE_RUNNING, + 10 + ) + , KILLS_IN_WINDOW0( + "Kills in Window:
If the number of kills in the last X seconds has drops below this value, consider resetting.", + LockMode::UNLOCK_WHILE_RUNNING, + 20 + ) + , ENCOUNTERS_IN_WINDOW( + "Encounters in Window:
If the number of encounters in the last X seconds has drops below this value, consider resetting.", + LockMode::UNLOCK_WHILE_RUNNING, + 5 + ) +#if 0 + , RESET_DURATION_MINUTES( + "Reset Duration (minutes):
If you are resetting, reset the game every " + "this many minutes.", + LockMode::UNLOCK_WHILE_RUNNING, + 180 + ) +#endif +{ + PA_ADD_STATIC(m_description); + + PA_ADD_STATIC(m_sliding_window); + PA_ADD_OPTION(WINDOW_IN_MINUTES); + PA_ADD_OPTION(KILLS_IN_WINDOW0); + PA_ADD_OPTION(ENCOUNTERS_IN_WINDOW); + +// PA_ADD_OPTION(RESET_DURATION_MINUTES); + + PlatformResetSettings::on_config_value_changed(this); + + WINDOW_IN_MINUTES.add_listener(*this); + KILLS_IN_WINDOW0.add_listener(*this); + ENCOUNTERS_IN_WINDOW.add_listener(*this); +} + +std::string int_to_text(size_t value, const std::string& unit){ + std::string str = "" + std::to_string(value) + " "; + str += unit; + if (value != 1){ + str += "s"; + } + return str; +} +void PlatformResetSettings::on_config_value_changed(void* object){ + m_sliding_window.set_text( + "Perform a platform reset if there are fewer than " + int_to_text(KILLS_IN_WINDOW0, "kill") + + " and " + int_to_text(ENCOUNTERS_IN_WINDOW, "encounter") + + " in the last " + int_to_text(WINDOW_IN_MINUTES, "minute") + "." + ); +} + + +NavigatePlatformSettings::NavigatePlatformSettings() + : GroupOption("Navigate to Platform Settings", LockMode::UNLOCK_WHILE_RUNNING) + , m_description( + "These settings are used when traveling from Zero Gate to the platform. " + "This can happen either at program start or during a platform reset." + ) + , HEAL_AT_STATION( + "Heal at Station:
If you're passing through the station, take the opportunity to heal up.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , STATION_ARRIVE_PAUSE_SECONDS( + "Station Arrive Pause Time:
Pause for this many seconds after leaving the station. " + "This gives the game time to load and thus reduce the chance of lag affecting the flight path.", + LockMode::UNLOCK_WHILE_RUNNING, + 1 + ) + , MIDAIR_PAUSE_TIME0( + "Mid-Air Pause Time:
Pause for this long before final approach to the platform. " + "Too small and you may crash into the wall above the platform or have reduced spawns. " + "Too large and you may undershoot the platform.", + LockMode::UNLOCK_WHILE_RUNNING, + "400 ms" + ) +{ + PA_ADD_STATIC(m_description); + PA_ADD_OPTION(HEAL_AT_STATION); + PA_ADD_OPTION(STATION_ARRIVE_PAUSE_SECONDS); + PA_ADD_OPTION(MIDAIR_PAUSE_TIME0); +} + + +void inside_zero_gate_to_platform( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool flying_unlocked, + NavigatePlatformSettings& settings +){ + inside_zero_gate_to_station(info, stream, context, 2, settings.HEAL_AT_STATION); + + context.wait_for(std::chrono::seconds(settings.STATION_ARRIVE_PAUSE_SECONDS)); + + // Navigate to platform. +#if 0 + // Don't jump to avoid spawn. + pbf_press_button(context, BUTTON_PLUS, 20, 105); + pbf_move_left_joystick(context, 128, 0, 625, 0); + ssf_press_button(context, BUTTON_B, 0, 50); + pbf_move_left_joystick(context, 128, 0, 250, 0); + pbf_move_left_joystick(context, 160, 0, 600, 0); + pbf_move_left_joystick(context, 128, 0, 1875, 0); +#endif + +#if 0 + // Jump late. + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + ssf_press_joystick(context, true, 128, 0, 315, 500); + + // Jump + ssf_press_button(context, BUTTON_B, 125, 100); + + // Fly + ssf_press_button(context, BUTTON_B, 0, 50); + + pbf_move_left_joystick(context, 144, 0, 1150, 0); + pbf_move_left_joystick(context, 128, 0, 125, NAVIGATE_TO_PLATFORM.MIDAIR_PAUSE_TIME); + + pbf_move_left_joystick(context, 128, 0, 1375, 250); +#endif + +#if 0 + // Jump earlier. + pbf_press_button(context, BUTTON_PLUS, 20, 105); + + ssf_press_joystick(context, true, 128, 0, 280, 500); + + // Jump + ssf_press_button(context, BUTTON_B, 125, 100); + + // Fly + ssf_press_button(context, BUTTON_B, 0, 50); + + pbf_move_left_joystick(context, 144, 0, 1150, 0); + pbf_move_left_joystick(context, 128, 0, 125, NAVIGATE_TO_PLATFORM.MIDAIR_PAUSE_TIME); + + pbf_move_left_joystick(context, 128, 0, 1375, 250); +#endif + +#if 1 + // Jump on the downhill to improve chance of clearing things. + pbf_move_left_joystick(context, 192, 0, 20, 105); + pbf_press_button(context, BUTTON_L | BUTTON_PLUS, 20, 105); + + ssf_press_button(context, BUTTON_LCLICK, 0ms, 4000ms); + if (!flying_unlocked){ + ssf_press_left_joystick(context, 128, 0, 125, 1250); + }else{ + ssf_press_left_joystick(context, 128, 0, 125, 875); + } + + // Jump + ssf_press_button(context, BUTTON_B, 1000ms, 800ms); + + // Fly + ssf_press_button(context, BUTTON_B, 0ms, 160ms, 80ms); // Double up this press in + ssf_press_button(context, BUTTON_B, 0ms, 160ms); // case one is dropped. + + if (!flying_unlocked){ +// ssf_press_left_joystick(context, 128, 0, 375, 875); + pbf_move_left_joystick(context, 144, 0, 700, 0); + pbf_move_left_joystick(context, 128, 0, 1000ms, settings.MIDAIR_PAUSE_TIME0); + pbf_move_left_joystick(context, 128, 0, 875, 250); + }else{ +// ssf_press_button(context, BUTTON_B, 0, 20); +// pbf_move_left_joystick(context, 128, 0, 375, 250); + pbf_move_left_joystick(context, 164, 0, 1000ms, settings.MIDAIR_PAUSE_TIME0); + pbf_press_button(context, BUTTON_LCLICK, 50, 0); + ssf_press_right_joystick(context, 128, 255, 0, 1500); + pbf_move_left_joystick(context, 128, 255, 1600, 125); + + pbf_press_button(context, BUTTON_B, 125, 375); + + } +#endif + +// context.wait_for_all_requests(); + pbf_press_button(context, BUTTON_PLUS, 20, 105); + ssf_press_left_joystick(context, 128, 0, 1 * TICKS_PER_SECOND, 4 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_R, 20, 355); + pbf_press_button(context, BUTTON_R, 20, 105); + + context.wait_for_all_requests(); +} + + +bool read_platform_center( + double& x, double& y, + const ProgramInfo& info, VideoStream& stream +){ + using namespace Kernels::Waterfill; + + VideoSnapshot screen = stream.video().snapshot(); + if (!screen){ + return false; + } + + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range(screen, 0xff000040, 0xff8080ff); + +// size_t min_width = screen.width() / 4; +// size_t min_height = screen.height() / 4; + + WaterfillObject biggest; + WaterfillObject object; + + std::unique_ptr session = make_WaterfillSession(matrix); + size_t min_area = screen->width() * screen->height() / 10; + auto iter = session->make_iterator(min_area); + while (iter->find_next(object, false)){ +// if (object.min_y != 0){ +// continue; +// } + if (biggest.area < object.area){ + biggest = std::move(object); + } + } + + if (biggest.area == 0){ + return false; + } + + x = biggest.center_of_gravity_x() / screen->width(); + y = biggest.center_of_gravity_y() / screen->height(); + + return true; +} + + + +void area_zero_platform_run_path0( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + uint64_t iteration_count +){ + // Go back to the wall. + stream.log("Go back to wall..."); + use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ + find_and_center_on_sky(env, stream, context); + pbf_move_right_joystick(context, 128, 255, 80, 0); + pbf_move_left_joystick(context, 176, 255, 30, 0); + pbf_press_button(context, BUTTON_L, 20, 50); + }); + + use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ + // Move to wall. + pbf_move_left_joystick(context, 128, 0, 4 * TICKS_PER_SECOND, 0); + + // Turn around. + stream.log("Turning towards sky..."); + pbf_move_left_joystick(context, 128, 255, 30, 95); + pbf_press_button(context, BUTTON_L, 20, 50); + }); + + // Move forward and kill everything in your path. + stream.log("Moving towards sky and killing everything..."); + uint16_t duration = 325; + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + find_and_center_on_sky(env, stream, context); + pbf_move_right_joystick(context, 128, 255, 70, 0); + + uint8_t x = 128; + switch (iteration_count % 4){ + case 0: + x = 96; + duration = 250; + break; + case 1: + x = 112; + break; + case 2: + x = 128; + break; + case 3: + x = 112; + break; + } + + ssf_press_button(context, BUTTON_L, 0ms, 160ms); + pbf_move_left_joystick(context, x, 0, duration, 0); + }); + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, duration, 4 * TICKS_PER_SECOND); + }); +} +void area_zero_platform_run_path1( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + uint64_t iteration_count +){ + // Go back to the wall. + stream.log("Go back to wall..."); + pbf_press_button(context, BUTTON_L, 20, 105); + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + find_and_center_on_sky(env, stream, context); + pbf_move_right_joystick(context, 128, 255, 80, 0); + pbf_move_left_joystick(context, 192, 255, 60, 0); + }); + + // Clear path to the wall. + stream.log("Clear path to the wall..."); + pbf_press_button(context, BUTTON_L, 20, 50); + use_lets_go_to_clear_in_front(stream, context, tracker, false, [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 0, 5 * TICKS_PER_SECOND, 0); + + // Turn right. + pbf_move_left_joystick(context, 255, 128, 30, 0); + pbf_press_button(context, BUTTON_L, 20, 50); + }); + + // Clear the wall. + stream.log("Clear the wall..."); + uint16_t duration = 325; + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 255, 128, 125, 0); + pbf_press_button(context, BUTTON_L, 20, 50); + context.wait_for_all_requests(); + + find_and_center_on_sky(env, stream, context); + pbf_move_left_joystick(context, 128, 0, 50, 0); + pbf_press_button(context, BUTTON_L, 20, 30); + + // Move forward. + + uint8_t x = 128; + switch (iteration_count % 4){ + case 0: + x = 96; + duration = 250; + break; + case 1: + x = 112; + break; + case 2: + x = 128; + break; + case 3: + x = 112; + break; + } + + pbf_move_left_joystick(context, x, 0, duration, 0); + }); + + stream.log("Run backwards and wait..."); + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ +// pbf_move_left_joystick(context, 64, 0, 125, 0); +// pbf_press_button(context, BUTTON_L, 20, 105); + pbf_move_left_joystick(context, 128, 255, duration, 4 * TICKS_PER_SECOND); +// pbf_controller_state(context, 0, DPAD_NONE, 255, 255, 120, 128, 3 * TICKS_PER_SECOND); + }); +} + + +void direction_to_stick( + uint8_t& joystick_x, uint8_t& joystick_y, + double direction_x, double direction_y +){ +// cout << "direction = " << direction_x << ", " << direction_y << endl; + + double scale = std::max(std::abs(direction_x), std::abs(direction_y)); + direction_x = 128 / scale * direction_x + 128; + direction_y = 128 / scale * direction_y + 128; + +// cout << "joystick = " << direction_x << ", " << direction_y << endl; + + direction_x = std::min(direction_x, 255.); + direction_x = std::max(direction_x, 0.); + direction_y = std::min(direction_y, 255.); + direction_y = std::max(direction_y, 0.); + + joystick_x = (uint8_t)direction_x; + joystick_y = (uint8_t)direction_y; +} +void choose_path( + Logger& logger, + uint8_t& x, uint8_t& y, uint16_t& duration, + double platform_x, double platform_y +){ + double diff_x = platform_x - 0.62; + double diff_y = platform_y - 0.71; + + logger.log("Move Direction: x = " + tostr_default(diff_x) + ", y = " + tostr_default(diff_y), COLOR_BLUE); + + direction_to_stick(x, y, diff_x, diff_y); + duration = (uint16_t)std::min(std::sqrt(diff_x*diff_x + diff_y*diff_y) * 125 * 12, 400); +} +void turn_angle(ProControllerContext& context, double angle_radians){ + uint8_t turn_x, turn_y; + direction_to_stick(turn_x, turn_y, -std::sin(angle_radians), std::cos(angle_radians)); + pbf_move_left_joystick(context, turn_x, turn_y, 40, 20); + pbf_mash_button(context, BUTTON_L, 60); +} + +void area_zero_platform_run_path2( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + uint64_t iteration_count +){ + stream.log("Look forward and fire..."); + pbf_mash_button(context, BUTTON_L, 60); + + double platform_x, platform_y; + uint16_t duration; + uint8_t move_x, move_y; + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + + stream.log("Find the sky, turn around and fire."); + pbf_move_right_joystick(context, 128, 0, 60, 0); + find_and_center_on_sky(env, stream, context); + context.wait_for(std::chrono::seconds(1)); + pbf_move_left_joystick(context, 128, 255, 40, 85); + pbf_mash_button(context, BUTTON_L, 60); + + pbf_move_right_joystick(context, 128, 255, 250, 0); + context.wait_for_all_requests(); + + stream.log("Finding center of platform..."); + if (!read_platform_center(platform_x, platform_y, env.program_info(), stream)){ + stream.log("Unable to find center of platform.", COLOR_RED); + return; + } + stream.log("Platform center at: x = " + tostr_default(platform_x) + ", y = " + tostr_default(platform_y), COLOR_BLUE); + + choose_path(stream.logger(), move_x, move_y, duration, platform_x, platform_y); + + pbf_move_left_joystick(context, move_x, move_y, 40, 20); + pbf_mash_button(context, BUTTON_L, 60); +// pbf_wait(context, 1250); + }); + use_lets_go_to_clear_in_front(stream, context, tracker, duration > 100, [&](ProControllerContext& context){ + stream.log("Making location correction..."); + pbf_move_left_joystick(context, 128, 0, duration, 0); + + // Optimization, calculate angle to aim you back at the sky. + // This speeds up the "find_and_center_on_sky()" call. + double angle0 = std::atan2(move_x - 128., 128. - move_y); + double angle1 = angle0 >= 0 ? 6.2831853071795864769 - angle0 : -6.2831853071795864769 - angle0; + turn_angle(context, angle1); + + find_and_center_on_sky(env, stream, context); + pbf_move_left_joystick(context, 96, 0, 40, 0); + pbf_mash_button(context, BUTTON_L, 60); + }); + + // One in every 4 iterations: Clear wall of spawns. + if (iteration_count % 4 == 0){ + stream.log("Turning along wall..."); + pbf_move_left_joystick(context, 0, 255, 20, 20); + pbf_mash_button(context, BUTTON_L, 60); + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + context.wait_for(std::chrono::milliseconds(1000)); + + stream.log("Turning back to sky."); + pbf_move_left_joystick(context, 255, 255, 20, 20); + pbf_mash_button(context, BUTTON_L, 60); + find_and_center_on_sky(env, stream, context); + pbf_move_left_joystick(context, 96, 0, 40, 0); + pbf_mash_button(context, BUTTON_L, 60); + }); + } + + if (platform_x < 0.5 || platform_y < 0.5){ + stream.log("Not close enough to desired spot. Skipping forward attack...", COLOR_ORANGE); + return; + } + + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + stream.log("Move forward, fire, and retreat."); + switch (iteration_count % 3){ + case 0: + pbf_move_left_joystick(context, 108, 0, 300, 0); + break; + case 1: + pbf_move_left_joystick(context, 128, 0, 300, 0); + break; + case 2: + pbf_move_left_joystick(context, 144, 0, 300, 0); + break; + } + }); + + use_lets_go_to_clear_in_front(stream, context, tracker, true, [&](ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 4 * TICKS_PER_SECOND, 0); + pbf_move_left_joystick(context, 128, 0, 60, 4 * TICKS_PER_SECOND); + }); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h index 002f4f03e6..872f1596df 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_AreaZeroPlatform.h @@ -1,110 +1,110 @@ -/* Area Zero Platform - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AreaZeroPlatform_H -#define PokemonAutomation_PokemonSV_AreaZeroPlatform_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class LetsGoEncounterBotTracker; - - -class PlatformResetSettings : public GroupOption, private ConfigOption::Listener{ -public: - ~PlatformResetSettings(); - PlatformResetSettings(); - -private: - virtual void on_config_value_changed(void* object) override; - -public: - StaticTextOption m_description; - StaticTextOption m_sliding_window; - SimpleIntegerOption WINDOW_IN_MINUTES; - SimpleIntegerOption KILLS_IN_WINDOW0; - SimpleIntegerOption ENCOUNTERS_IN_WINDOW; -// SimpleIntegerOption RESET_DURATION_MINUTES; -}; - - - - -class NavigatePlatformSettings : public GroupOption{ -public: - NavigatePlatformSettings(); - -public: - StaticTextOption m_description; - BooleanCheckBoxOption HEAL_AT_STATION; - SimpleIntegerOption STATION_ARRIVE_PAUSE_SECONDS; - MillisecondsOption MIDAIR_PAUSE_TIME0; -}; - -void inside_zero_gate_to_platform( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - bool flying_unlocked, - NavigatePlatformSettings& settings -); - - - - -bool read_platform_center( - double& x, double& y, - const ProgramInfo& info, VideoStream& stream -); - - - -// Send Let's Go pokemon to beat wild pokemon while moving on the Area Zero platform following Path 0. -// It tracks the kill chain by sound detection from `tracker`. The function does not handle any pokemon -// battle encounters (turn-based battles). -void area_zero_platform_run_path0( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - uint64_t iteration_count -); -// Send Let's Go pokemon to beat wild pokemon while moving on the Area Zero platform following Path 1. -// It tracks the kill chain by sound detection from `tracker`. The function does not handle any pokemon -// battle encounters (turn-based battles). -void area_zero_platform_run_path1( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - uint64_t iteration_count -); -// Send Let's Go pokemon to beat wild pokemon while moving on the Area Zero platform following Path 2. -// It tracks the kill chain by sound detection from `tracker`. The function does not handle any pokemon -// battle encounters (turn-based battles). -void area_zero_platform_run_path2( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - uint64_t iteration_count -); - - - - - -} -} -} -#endif +/* Area Zero Platform + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AreaZeroPlatform_H +#define PokemonAutomation_PokemonSV_AreaZeroPlatform_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class LetsGoEncounterBotTracker; + + +class PlatformResetSettings : public GroupOption, private ConfigOption::Listener{ +public: + ~PlatformResetSettings(); + PlatformResetSettings(); + +private: + virtual void on_config_value_changed(void* object) override; + +public: + StaticTextOption m_description; + StaticTextOption m_sliding_window; + SimpleIntegerOption WINDOW_IN_MINUTES; + SimpleIntegerOption KILLS_IN_WINDOW0; + SimpleIntegerOption ENCOUNTERS_IN_WINDOW; +// SimpleIntegerOption RESET_DURATION_MINUTES; +}; + + + + +class NavigatePlatformSettings : public GroupOption{ +public: + NavigatePlatformSettings(); + +public: + StaticTextOption m_description; + BooleanCheckBoxOption HEAL_AT_STATION; + SimpleIntegerOption STATION_ARRIVE_PAUSE_SECONDS; + MillisecondsOption MIDAIR_PAUSE_TIME0; +}; + +void inside_zero_gate_to_platform( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + bool flying_unlocked, + NavigatePlatformSettings& settings +); + + + + +bool read_platform_center( + double& x, double& y, + const ProgramInfo& info, VideoStream& stream +); + + + +// Send Let's Go pokemon to beat wild pokemon while moving on the Area Zero platform following Path 0. +// It tracks the kill chain by sound detection from `tracker`. The function does not handle any pokemon +// battle encounters (turn-based battles). +void area_zero_platform_run_path0( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + uint64_t iteration_count +); +// Send Let's Go pokemon to beat wild pokemon while moving on the Area Zero platform following Path 1. +// It tracks the kill chain by sound detection from `tracker`. The function does not handle any pokemon +// battle encounters (turn-based battles). +void area_zero_platform_run_path1( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + uint64_t iteration_count +); +// Send Let's Go pokemon to beat wild pokemon while moving on the Area Zero platform following Path 2. +// It tracks the kill chain by sound detection from `tracker`. The function does not handle any pokemon +// battle encounters (turn-based battles). +void area_zero_platform_run_path2( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + uint64_t iteration_count +); + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp index 9398761bd6..b5d86eeb9f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.cpp @@ -1,387 +1,387 @@ -/* Let's Go Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" -#include "PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV_LetsGoTools.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -EncounterRateTracker::EncounterRateTracker() - : m_start_time(current_time()) -{} -bool EncounterRateTracker::get_encounters_in_window( - size_t& kills, size_t& encounters, - std::chrono::seconds time_window -){ - WallClock now = current_time(); - WallClock threshold = now - time_window; - - size_t index = std::lower_bound(m_kill_history.begin(), m_kill_history.end(), threshold) - m_kill_history.begin(); -// cout << "kills index = " << index << endl; - kills = m_kill_history.size() - index; - - index = std::lower_bound(m_encounter_history.begin(), m_encounter_history.end(), threshold) - m_encounter_history.begin(); -// cout << "encounters index = " << index << endl; - encounters = m_encounter_history.size() - index; - -// cout << "time_window: " << std::chrono::duration_cast(time_window).count() << endl; -// cout << "m_start_time: " << std::chrono::duration_cast(now - m_start_time).count() << endl; - - return m_start_time <= threshold; -} -void EncounterRateTracker::report_start(WallClock now){ - m_start_time = now; -} -void EncounterRateTracker::report_kill(){ - WallClock now = current_time(); - if (m_kill_history.empty() || m_kill_history.back() < now){ - m_kill_history.push_back(now); - return; - } - - global_logger_tagged().log( - "EncounterRateTracker: Detected that time has travelled backwards. Clearing history.", - COLOR_RED - ); - - m_kill_history.clear(); - m_encounter_history.clear(); - m_start_time = now; - - m_kill_history.push_back(now); -} -void EncounterRateTracker::report_encounter(){ - WallClock now = current_time(); - if (m_encounter_history.empty() || m_encounter_history.back() < now){ - m_encounter_history.push_back(now); - return; - } - - global_logger_tagged().log( - "EncounterRateTracker: Detected that time has travelled backwards. Clearing history.", - COLOR_RED - ); - - m_kill_history.clear(); - m_encounter_history.clear(); - m_start_time = now; - - m_encounter_history.push_back(now); -} - - - - -WallDuration DiscontiguousTimeTracker::last_window_in_realtime( - WallClock realtime_end, - WallDuration last_window_in_virtual_time -){ - if (m_blocks.empty()){ - return WallDuration::zero(); - } - - WallDuration remaining(last_window_in_virtual_time); - - auto iter = m_blocks.rbegin(); - WallClock start; - - do{ - WallDuration block = iter->second - iter->first; - if (remaining > block){ - remaining -= block; - start = iter->first; - }else{ - start = iter->second - remaining; - return realtime_end - start; - } - ++iter; - }while (iter != m_blocks.rend()); - - return WallDuration::zero(); -} - -void DiscontiguousTimeTracker::add_block(WallClock start, WallClock end){ - if (end <= start){ - global_logger_tagged().log( - "DiscontiguousTimeTracker: Dropping invalid time block.", - COLOR_RED - ); - return; - } - if (m_blocks.empty() || start >= m_blocks.back().second){ - m_blocks.emplace_back(start, end); - return; - } - global_logger_tagged().log( - "DiscontiguousTimeTracker: Detected that time has travelled backwards. Clearing history.", - COLOR_RED - ); - m_blocks.clear(); - return; -} - - - - - - -LetsGoEncounterBotTracker::LetsGoEncounterBotTracker( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotStats& stats, - OCR::LanguageOCROption& language -) - : m_env(env) - , m_stream(stream) - , m_context(context) - , m_stats(stats) - , m_language(language) - , m_kill_sound(stream.logger(), [&](float){ - stream.log("Detected kill."); - m_encounter_rate.report_kill(); - stats.m_kills++; - env.update_stats(); - return false; - }) - , m_session(context, stream, {m_kill_sound}) -{} -void LetsGoEncounterBotTracker::process_battle( - bool& caught, bool& should_save, - EncounterWatcher& watcher, EncounterBotCommonOptions& settings -){ - m_encounter_rate.report_encounter(); - m_stats.m_encounters++; - - Language language = m_language; - - std::set slugs; - if (language != Language::None){ - slugs = read_singles_opponent(m_env.program_info(), m_stream, m_context, language); - m_encounter_frequencies += slugs; - m_env.log(m_encounter_frequencies.dump_sorted_map("Encounter Stats:\n")); - } - - bool is_shiny = (bool)watcher.shiny_screenshot(); - if (is_shiny){ - m_stats.m_shinies++; - if (settings.VIDEO_ON_SHINY){ - m_context.wait_for(std::chrono::seconds(3)); - pbf_press_button(m_context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); - } - } - m_env.update_stats(); - - send_encounter_notification( - m_env, - settings.NOTIFICATION_NONSHINY, - settings.NOTIFICATION_SHINY, - language != Language::None, - is_shiny, - {{slugs, is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY}}, - watcher.lowest_error_coefficient(), - watcher.shiny_screenshot(), - &m_encounter_frequencies - ); - - // Set default action: stop program if shiny, otherwise run away. - EncounterActionsEntry action; - action.action = is_shiny - ? EncounterActionsAction::STOP_PROGRAM - : EncounterActionsAction::RUN_AWAY; - - // Iterate the actions table. If found an entry matches the pokemon species, - // set the action to be what specified in the entry. - for (EncounterActionsEntry& entry : settings.ACTIONS_TABLE.snapshot()){ - if (language == Language::None){ - throw UserSetupError(m_stream.logger(), "You must set the game language to use the actions table."); - } - - // See if Pokemon name matches. - auto iter = slugs.find(entry.pokemon); - if (iter == slugs.end()){ - continue; - } - - switch (entry.shininess){ - case EncounterActionsShininess::ANYTHING: - break; - case EncounterActionsShininess::NOT_SHINY: - if (is_shiny){ - continue; - } - break; - case EncounterActionsShininess::SHINY: - if (!is_shiny){ - continue; - } - break; - } - - action = std::move(entry); - } - - // Run the chosen action. - switch (action.action){ - case EncounterActionsAction::RUN_AWAY: - try{ - run_from_battle(m_env.program_info(), m_stream, m_context); - }catch (OperationFailedException& e){ - throw FatalProgramException(std::move(e)); - } - caught = false; - should_save = false; - return; - case EncounterActionsAction::STOP_PROGRAM: - throw ProgramFinishedException(); -// throw ProgramFinishedException(m_stream, "", true); - case EncounterActionsAction::THROW_BALLS: - case EncounterActionsAction::THROW_BALLS_AND_SAVE: - if (language == Language::None){ - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Language is not set."); - } - - CatchResults result = basic_catcher( - m_stream, m_context, - language, - action.ball, action.ball_limit, - settings.USE_FIRST_MOVE_IF_CANNOT_THROW_BALL - ); - send_catch_notification( - m_env, - settings.NOTIFICATION_CATCH_SUCCESS, - settings.NOTIFICATION_CATCH_FAILED, - &slugs, - action.ball, - result.balls_used, - result.result - ); - - switch (result.result){ - case CatchResult::POKEMON_CAUGHT: - case CatchResult::POKEMON_FAINTED: - break; - default: - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to recover from failed catch.", - m_stream - ); - } - - caught = result.result == CatchResult::POKEMON_CAUGHT; - should_save = caught && action.action == EncounterActionsAction::THROW_BALLS_AND_SAVE; - return; - } - - caught = false; - should_save = false; -} - - - - - - - -bool use_lets_go_to_clear_in_front( - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - bool throw_ball_if_bubble, - std::function&& command -){ -// ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = env.current_stats(); - -// static int calls = 0; - stream.log("Clearing what's in front with Let's Go..."); -// cout << calls++ << endl; - - SweatBubbleWatcher bubble(COLOR_GREEN); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_R, 20, 200); - }, - {bubble} - ); -// cout << "asdf" << endl; - if (ret == 0){ - if (throw_ball_if_bubble){ - stream.log("Detected sweat bubble. Throwing ball..."); - pbf_mash_button(context, BUTTON_ZR, 5 * TICKS_PER_SECOND); - }else{ - stream.log("Detected sweat bubble. Will not throw ball."); - } - }else{ - stream.log("Did not detect sweat bubble."); - } - - WallClock last_kill = tracker.last_kill(); - context.wait_for_all_requests(); - std::chrono::seconds timeout(6); - while (true){ - if (command){ -// cout << "running command..." << endl; - command(context); - context.wait_for_all_requests(); - command = nullptr; - }else{ -// cout << "Waiting out... " << timeout.count() << " seconds" << endl; - context.wait_until(last_kill + timeout); - } -// timeout = std::chrono::seconds(3); - if (last_kill == tracker.last_kill()){ -// cout << "no kill" << endl; - break; - } -// cout << "found kill" << endl; - last_kill = tracker.last_kill(); - } - stream.log("Nothing left to clear..."); - tracker.throw_if_no_sound(); - return tracker.last_kill() != WallClock::min(); -} - - - - - - - - - - - - - - - - - -} -} -} +/* Let's Go Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" +#include "PokemonSV/Inference/PokemonSV_SweatBubbleDetector.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV_LetsGoTools.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +EncounterRateTracker::EncounterRateTracker() + : m_start_time(current_time()) +{} +bool EncounterRateTracker::get_encounters_in_window( + size_t& kills, size_t& encounters, + std::chrono::seconds time_window +){ + WallClock now = current_time(); + WallClock threshold = now - time_window; + + size_t index = std::lower_bound(m_kill_history.begin(), m_kill_history.end(), threshold) - m_kill_history.begin(); +// cout << "kills index = " << index << endl; + kills = m_kill_history.size() - index; + + index = std::lower_bound(m_encounter_history.begin(), m_encounter_history.end(), threshold) - m_encounter_history.begin(); +// cout << "encounters index = " << index << endl; + encounters = m_encounter_history.size() - index; + +// cout << "time_window: " << std::chrono::duration_cast(time_window).count() << endl; +// cout << "m_start_time: " << std::chrono::duration_cast(now - m_start_time).count() << endl; + + return m_start_time <= threshold; +} +void EncounterRateTracker::report_start(WallClock now){ + m_start_time = now; +} +void EncounterRateTracker::report_kill(){ + WallClock now = current_time(); + if (m_kill_history.empty() || m_kill_history.back() < now){ + m_kill_history.push_back(now); + return; + } + + global_logger_tagged().log( + "EncounterRateTracker: Detected that time has travelled backwards. Clearing history.", + COLOR_RED + ); + + m_kill_history.clear(); + m_encounter_history.clear(); + m_start_time = now; + + m_kill_history.push_back(now); +} +void EncounterRateTracker::report_encounter(){ + WallClock now = current_time(); + if (m_encounter_history.empty() || m_encounter_history.back() < now){ + m_encounter_history.push_back(now); + return; + } + + global_logger_tagged().log( + "EncounterRateTracker: Detected that time has travelled backwards. Clearing history.", + COLOR_RED + ); + + m_kill_history.clear(); + m_encounter_history.clear(); + m_start_time = now; + + m_encounter_history.push_back(now); +} + + + + +WallDuration DiscontiguousTimeTracker::last_window_in_realtime( + WallClock realtime_end, + WallDuration last_window_in_virtual_time +){ + if (m_blocks.empty()){ + return WallDuration::zero(); + } + + WallDuration remaining(last_window_in_virtual_time); + + auto iter = m_blocks.rbegin(); + WallClock start; + + do{ + WallDuration block = iter->second - iter->first; + if (remaining > block){ + remaining -= block; + start = iter->first; + }else{ + start = iter->second - remaining; + return realtime_end - start; + } + ++iter; + }while (iter != m_blocks.rend()); + + return WallDuration::zero(); +} + +void DiscontiguousTimeTracker::add_block(WallClock start, WallClock end){ + if (end <= start){ + global_logger_tagged().log( + "DiscontiguousTimeTracker: Dropping invalid time block.", + COLOR_RED + ); + return; + } + if (m_blocks.empty() || start >= m_blocks.back().second){ + m_blocks.emplace_back(start, end); + return; + } + global_logger_tagged().log( + "DiscontiguousTimeTracker: Detected that time has travelled backwards. Clearing history.", + COLOR_RED + ); + m_blocks.clear(); + return; +} + + + + + + +LetsGoEncounterBotTracker::LetsGoEncounterBotTracker( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotStats& stats, + OCR::LanguageOCROption& language +) + : m_env(env) + , m_stream(stream) + , m_context(context) + , m_stats(stats) + , m_language(language) + , m_kill_sound(stream.logger(), [&](float){ + stream.log("Detected kill."); + m_encounter_rate.report_kill(); + stats.m_kills++; + env.update_stats(); + return false; + }) + , m_session(context, stream, {m_kill_sound}) +{} +void LetsGoEncounterBotTracker::process_battle( + bool& caught, bool& should_save, + EncounterWatcher& watcher, EncounterBotCommonOptions& settings +){ + m_encounter_rate.report_encounter(); + m_stats.m_encounters++; + + Language language = m_language; + + std::set slugs; + if (language != Language::None){ + slugs = read_singles_opponent(m_env.program_info(), m_stream, m_context, language); + m_encounter_frequencies += slugs; + m_env.log(m_encounter_frequencies.dump_sorted_map("Encounter Stats:\n")); + } + + bool is_shiny = (bool)watcher.shiny_screenshot(); + if (is_shiny){ + m_stats.m_shinies++; + if (settings.VIDEO_ON_SHINY){ + m_context.wait_for(std::chrono::seconds(3)); + pbf_press_button(m_context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 0); + } + } + m_env.update_stats(); + + send_encounter_notification( + m_env, + settings.NOTIFICATION_NONSHINY, + settings.NOTIFICATION_SHINY, + language != Language::None, + is_shiny, + {{slugs, is_shiny ? ShinyType::UNKNOWN_SHINY : ShinyType::NOT_SHINY}}, + watcher.lowest_error_coefficient(), + watcher.shiny_screenshot(), + &m_encounter_frequencies + ); + + // Set default action: stop program if shiny, otherwise run away. + EncounterActionsEntry action; + action.action = is_shiny + ? EncounterActionsAction::STOP_PROGRAM + : EncounterActionsAction::RUN_AWAY; + + // Iterate the actions table. If found an entry matches the pokemon species, + // set the action to be what specified in the entry. + for (EncounterActionsEntry& entry : settings.ACTIONS_TABLE.snapshot()){ + if (language == Language::None){ + throw UserSetupError(m_stream.logger(), "You must set the game language to use the actions table."); + } + + // See if Pokemon name matches. + auto iter = slugs.find(entry.pokemon); + if (iter == slugs.end()){ + continue; + } + + switch (entry.shininess){ + case EncounterActionsShininess::ANYTHING: + break; + case EncounterActionsShininess::NOT_SHINY: + if (is_shiny){ + continue; + } + break; + case EncounterActionsShininess::SHINY: + if (!is_shiny){ + continue; + } + break; + } + + action = std::move(entry); + } + + // Run the chosen action. + switch (action.action){ + case EncounterActionsAction::RUN_AWAY: + try{ + run_from_battle(m_env.program_info(), m_stream, m_context); + }catch (OperationFailedException& e){ + throw FatalProgramException(std::move(e)); + } + caught = false; + should_save = false; + return; + case EncounterActionsAction::STOP_PROGRAM: + throw ProgramFinishedException(); +// throw ProgramFinishedException(m_stream, "", true); + case EncounterActionsAction::THROW_BALLS: + case EncounterActionsAction::THROW_BALLS_AND_SAVE: + if (language == Language::None){ + throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Language is not set."); + } + + CatchResults result = basic_catcher( + m_stream, m_context, + language, + action.ball, action.ball_limit, + settings.USE_FIRST_MOVE_IF_CANNOT_THROW_BALL + ); + send_catch_notification( + m_env, + settings.NOTIFICATION_CATCH_SUCCESS, + settings.NOTIFICATION_CATCH_FAILED, + &slugs, + action.ball, + result.balls_used, + result.result + ); + + switch (result.result){ + case CatchResult::POKEMON_CAUGHT: + case CatchResult::POKEMON_FAINTED: + break; + default: + throw_and_log( + m_stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to recover from failed catch.", + m_stream + ); + } + + caught = result.result == CatchResult::POKEMON_CAUGHT; + should_save = caught && action.action == EncounterActionsAction::THROW_BALLS_AND_SAVE; + return; + } + + caught = false; + should_save = false; +} + + + + + + + +bool use_lets_go_to_clear_in_front( + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + bool throw_ball_if_bubble, + std::function&& command +){ +// ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = env.current_stats(); + +// static int calls = 0; + stream.log("Clearing what's in front with Let's Go..."); +// cout << calls++ << endl; + + SweatBubbleWatcher bubble(COLOR_GREEN); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_R, 20, 200); + }, + {bubble} + ); +// cout << "asdf" << endl; + if (ret == 0){ + if (throw_ball_if_bubble){ + stream.log("Detected sweat bubble. Throwing ball..."); + pbf_mash_button(context, BUTTON_ZR, 5 * TICKS_PER_SECOND); + }else{ + stream.log("Detected sweat bubble. Will not throw ball."); + } + }else{ + stream.log("Did not detect sweat bubble."); + } + + WallClock last_kill = tracker.last_kill(); + context.wait_for_all_requests(); + std::chrono::seconds timeout(6); + while (true){ + if (command){ +// cout << "running command..." << endl; + command(context); + context.wait_for_all_requests(); + command = nullptr; + }else{ +// cout << "Waiting out... " << timeout.count() << " seconds" << endl; + context.wait_until(last_kill + timeout); + } +// timeout = std::chrono::seconds(3); + if (last_kill == tracker.last_kill()){ +// cout << "no kill" << endl; + break; + } +// cout << "found kill" << endl; + last_kill = tracker.last_kill(); + } + stream.log("Nothing left to clear..."); + tracker.throw_if_no_sound(); + return tracker.last_kill() != WallClock::min(); +} + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h index fe1a18a319..e89e066c39 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_LetsGoTools.h @@ -1,188 +1,188 @@ -/* Let's Go Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_LetsGoTools_H -#define PokemonAutomation_PokemonSV_LetsGoTools_H - -#include -#include -#include "Common/Cpp/Time.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceSession.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_EncounterStats.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" - -namespace PokemonAutomation{ - class CancellableScope; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -class EncounterBotCommonOptions; - - - -class EncounterRateTracker{ -public: - EncounterRateTracker(); - - WallClock start_time() const{ - return m_start_time; - } - - // Get the # of encounters in the last specified time window. - // Returns false if the history is less than the window. - bool get_encounters_in_window( - size_t& kills, size_t& encounters, - std::chrono::seconds time_window - ); - - void report_start(WallClock now = current_time()); - void report_kill(); - void report_encounter(); - -private: - WallClock m_start_time; - - // Note that this keeps the entire history. Nothing is dropped. This is - // fine since it's unlikely we'll have enough encounters in one run to - // cause memory issues. - std::deque m_kill_history; - std::deque m_encounter_history; -}; - - -// Consider a virtual timeline that starts and stops relative to the wall clock. -// Now you want to get the last X seconds of the virtual timeline, but on the -// wall clock instead. Because of the starts and stops, the last X seconds -// of virtual time will be less than the last X seconds of real time. -// -// The use case here is the platform reset conditions. Resets are performed if -// the # of encounters in the last X time drops below Y. But only the time -// spent hunting for encounters should count. Time spent in battles or resets -// does not. -// -class DiscontiguousTimeTracker{ -public: - // Returns zero if there is insufficient virtual time. - WallDuration last_window_in_realtime( - WallClock realtime_end, - WallDuration last_window_in_virtual_time - ); - - void add_block(WallClock start, WallClock end); - -private: - std::deque> m_blocks; -}; - - -class LetsGoEncounterBotStats : public StatsTracker{ -public: - LetsGoEncounterBotStats() - : m_kills(m_stats["Kills"]) - , m_encounters(m_stats["Encounters"]) - , m_shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Kills"); - m_display_order.emplace_back("Encounters"); - m_display_order.emplace_back("Shinies"); - } - -public: - std::atomic& m_kills; - std::atomic& m_encounters; - std::atomic& m_shinies; -}; - - - -// Used to track Let's Go kill chain progress, stats. -// It can also run `process_battle()` to handle pokemon battle encounters (turn-based battles) -// according to user options. -class LetsGoEncounterBotTracker{ -public: - LetsGoEncounterBotTracker( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotStats& stats, - OCR::LanguageOCROption& language - ); - - void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(10000)) const{ - m_kill_sound.throw_if_no_sound(min_duration); - } - - WallClock encounter_rate_tracker_start_time() const{ - return m_encounter_rate.start_time(); - } - WallClock last_kill() const{ - return m_kill_sound.last_kill(); - } - const EncounterFrequencies& encounter_frequencies() const{ - return m_encounter_frequencies; - } - - // Get the # of encounters in the last specified time window. - // Returns false if the history is less than the window. - bool get_encounters_in_window( - size_t& kills, size_t& encounters, - std::chrono::seconds time_window - ){ - return m_encounter_rate.get_encounters_in_window(kills, encounters, time_window); - } - void reset_rate_tracker_start_time(){ - m_encounter_rate.report_start(); - } - - // Returns true if you should save the game. - void process_battle( - bool& caught, bool& should_save, - EncounterWatcher& watcher, EncounterBotCommonOptions& settings - ); - -private: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ProControllerContext& m_context; - LetsGoEncounterBotStats& m_stats; - - OCR::LanguageOCROption& m_language; - - EncounterRateTracker m_encounter_rate; - EncounterFrequencies m_encounter_frequencies; - - LetsGoKillSoundDetector m_kill_sound; - InferenceSession m_session; -}; - - - - -// Send your Pokemon out in front in Let's Go. Then run the specified command. -// Don't return until both the command has finished, and it appears the kill -// chain has ended. -// The function tracks kill chain by sound detection from `tracker`. The function -// does not handle any pokemon battle encounters (turn-based battles). -bool use_lets_go_to_clear_in_front( - VideoStream& stream, ProControllerContext& context, - LetsGoEncounterBotTracker& tracker, - bool throw_ball_if_bubble, - std::function&& command -); - - - - -} -} -} -#endif +/* Let's Go Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_LetsGoTools_H +#define PokemonAutomation_PokemonSV_LetsGoTools_H + +#include +#include +#include "Common/Cpp/Time.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceSession.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_EncounterStats.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" + +namespace PokemonAutomation{ + class CancellableScope; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +class EncounterBotCommonOptions; + + + +class EncounterRateTracker{ +public: + EncounterRateTracker(); + + WallClock start_time() const{ + return m_start_time; + } + + // Get the # of encounters in the last specified time window. + // Returns false if the history is less than the window. + bool get_encounters_in_window( + size_t& kills, size_t& encounters, + std::chrono::seconds time_window + ); + + void report_start(WallClock now = current_time()); + void report_kill(); + void report_encounter(); + +private: + WallClock m_start_time; + + // Note that this keeps the entire history. Nothing is dropped. This is + // fine since it's unlikely we'll have enough encounters in one run to + // cause memory issues. + std::deque m_kill_history; + std::deque m_encounter_history; +}; + + +// Consider a virtual timeline that starts and stops relative to the wall clock. +// Now you want to get the last X seconds of the virtual timeline, but on the +// wall clock instead. Because of the starts and stops, the last X seconds +// of virtual time will be less than the last X seconds of real time. +// +// The use case here is the platform reset conditions. Resets are performed if +// the # of encounters in the last X time drops below Y. But only the time +// spent hunting for encounters should count. Time spent in battles or resets +// does not. +// +class DiscontiguousTimeTracker{ +public: + // Returns zero if there is insufficient virtual time. + WallDuration last_window_in_realtime( + WallClock realtime_end, + WallDuration last_window_in_virtual_time + ); + + void add_block(WallClock start, WallClock end); + +private: + std::deque> m_blocks; +}; + + +class LetsGoEncounterBotStats : public StatsTracker{ +public: + LetsGoEncounterBotStats() + : m_kills(m_stats["Kills"]) + , m_encounters(m_stats["Encounters"]) + , m_shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Kills"); + m_display_order.emplace_back("Encounters"); + m_display_order.emplace_back("Shinies"); + } + +public: + std::atomic& m_kills; + std::atomic& m_encounters; + std::atomic& m_shinies; +}; + + + +// Used to track Let's Go kill chain progress, stats. +// It can also run `process_battle()` to handle pokemon battle encounters (turn-based battles) +// according to user options. +class LetsGoEncounterBotTracker{ +public: + LetsGoEncounterBotTracker( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotStats& stats, + OCR::LanguageOCROption& language + ); + + void throw_if_no_sound(std::chrono::milliseconds min_duration = std::chrono::milliseconds(10000)) const{ + m_kill_sound.throw_if_no_sound(min_duration); + } + + WallClock encounter_rate_tracker_start_time() const{ + return m_encounter_rate.start_time(); + } + WallClock last_kill() const{ + return m_kill_sound.last_kill(); + } + const EncounterFrequencies& encounter_frequencies() const{ + return m_encounter_frequencies; + } + + // Get the # of encounters in the last specified time window. + // Returns false if the history is less than the window. + bool get_encounters_in_window( + size_t& kills, size_t& encounters, + std::chrono::seconds time_window + ){ + return m_encounter_rate.get_encounters_in_window(kills, encounters, time_window); + } + void reset_rate_tracker_start_time(){ + m_encounter_rate.report_start(); + } + + // Returns true if you should save the game. + void process_battle( + bool& caught, bool& should_save, + EncounterWatcher& watcher, EncounterBotCommonOptions& settings + ); + +private: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ProControllerContext& m_context; + LetsGoEncounterBotStats& m_stats; + + OCR::LanguageOCROption& m_language; + + EncounterRateTracker m_encounter_rate; + EncounterFrequencies m_encounter_frequencies; + + LetsGoKillSoundDetector m_kill_sound; + InferenceSession m_session; +}; + + + + +// Send your Pokemon out in front in Let's Go. Then run the specified command. +// Don't return until both the command has finished, and it appears the kill +// chain has ended. +// The function tracks kill chain by sound detection from `tracker`. The function +// does not handle any pokemon battle encounters (turn-based battles). +bool use_lets_go_to_clear_in_front( + VideoStream& stream, ProControllerContext& context, + LetsGoEncounterBotTracker& tracker, + bool throw_ball_if_bubble, + std::function&& command +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp index 5db0934358..1230436c4c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.cpp @@ -1,574 +1,574 @@ -/* Shiny Hunt - Area Zero Platform - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" -#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_AreaZero.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV_LetsGoTools.h" -#include "PokemonSV_ShinyHunt-AreaZeroPlatform.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - -ShinyHuntAreaZeroPlatform_Descriptor::ShinyHuntAreaZeroPlatform_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:ShinyHuntAreaZeroPlatform", - STRING_POKEMON + " SV", "Shiny Hunt - Area Zero Platform", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ShinyHunt-AreaZeroPlatform.md", - "Shiny hunt the isolated platform at the bottom of Area Zero.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntAreaZeroPlatform_Descriptor::Stats : public LetsGoEncounterBotStats{ - Stats() - : m_sandwiches(m_stats["Sandwiches"]) - , m_autoheals(m_stats["Auto Heals"]) - , m_platform_resets(m_stats["Platform Resets"]) - , m_game_resets(m_stats["Game Resets"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 4, {"Platform Resets", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 5, {"Game Resets", ALWAYS_HIDDEN}); - m_display_order.insert(m_display_order.begin() + 6, {"Errors", HIDDEN_IF_ZERO}); - } - std::atomic& m_sandwiches; - std::atomic& m_autoheals; - std::atomic& m_platform_resets; - std::atomic& m_game_resets; - std::atomic& m_errors; -}; -std::unique_ptr ShinyHuntAreaZeroPlatform_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -ShinyHuntAreaZeroPlatform::~ShinyHuntAreaZeroPlatform(){ - MODE.remove_listener(*this); -} - -ShinyHuntAreaZeroPlatform::ShinyHuntAreaZeroPlatform() - : LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , MODE( - "Mode:
" - "If starting on the platform, you should stand near the center of the platform facing any direction.
" - "If starting at the Zero Gate fly spot, you should be at the fly spot as if you just flew there." - "
If making a sandwich, you should be at the Zero Gate fly spot as if you just flew there.", - { - {Mode::START_ON_PLATFORM, "platform", "Start on platform."}, - {Mode::START_AT_ZERO_GATE_FLY_SPOT, "zerogate", "Start at Zero Gate fly spot."}, - {Mode::MAKE_SANDWICH, "sandwich", "Make a sandwich."}, - }, - LockMode::LOCK_WHILE_RUNNING, - Mode::START_ON_PLATFORM - ) - , FLYING_UNLOCKED( - "Flying Unlocked:
Check this box if you have unlocked your ride's ability to fly after completing the Indigo Disk DLC.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , PATH0( - "Path:
Traversal path on the platform to trigger encounters.", - { - {Path::PATH0, "path0", "Path 0"}, - {Path::PATH1, "path1", "Path 1"}, - {Path::PATH2, "path2", "Path 2"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - Path::PATH2 - ) - , SANDWICH_RESET_IN_MINUTES( - "Sandwich Reset Time (in minutes):
The time to reset game to make a new sandwich.", - LockMode::UNLOCK_WHILE_RUNNING, - 35 - ) - , SANDWICH_OPTIONS( - "Sandwich Options", - &LANGUAGE, - BaseRecipe::paradox, - false, - GroupOption::EnableMode::ALWAYS_ENABLED - ) - , GO_HOME_WHEN_DONE(true) - , AUTO_HEAL_PERCENT( - "Auto-Heal %
Auto-heal if your HP drops below this percentage.", - LockMode::UNLOCK_WHILE_RUNNING, - 75, 0, 100 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(FLYING_UNLOCKED); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(PATH0); - } - PA_ADD_OPTION(SANDWICH_RESET_IN_MINUTES); - PA_ADD_OPTION(SANDWICH_OPTIONS); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(AUTO_HEAL_PERCENT); - PA_ADD_OPTION(PLATFORM_RESET); - PA_ADD_OPTION(NAVIGATE_TO_PLATFORM); - PA_ADD_OPTION(NOTIFICATIONS); - - ShinyHuntAreaZeroPlatform::on_config_value_changed(this); - - MODE.add_listener(*this); -} - -std::string ShinyHuntAreaZeroPlatform::check_validity() const{ - std::string error = SingleSwitchProgramInstance::check_validity(); - if (!error.empty()){ - return error; - } - if (LANGUAGE == Language::None && MODE == Mode::MAKE_SANDWICH){ - return "Sandwich mode requires selecting a language."; - } - return ""; -} -void ShinyHuntAreaZeroPlatform::on_config_value_changed(void* object){ - ConfigOptionState state = MODE == Mode::MAKE_SANDWICH - ? ConfigOptionState::ENABLED - : ConfigOptionState::HIDDEN; - SANDWICH_RESET_IN_MINUTES.set_visibility(state); - SANDWICH_OPTIONS.set_visibility(state); -} - - - -bool ShinyHuntAreaZeroPlatform::run_traversal(ProControllerContext& context){ - ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); - - const ProgramInfo& info = m_env->program_info(); - VideoStream& stream = m_env->console; - -// if (m_pending_save){ -// save_game_from_overworld(info, console, context); -// m_pending_save = false; -// m_last_save = SavedLocation::AREA_ZERO; -// } - - double hp = m_hp_watcher->last_known_value() * 100; - if (0 < hp){ - stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); - }else{ - stream.log("Last Known HP: ?", COLOR_RED); - } - if (0 < hp && hp < AUTO_HEAL_PERCENT){ - auto_heal_from_menu_or_overworld(info, stream, context, 0, true); - stats.m_autoheals++; - m_env->update_stats(); - } - - WallClock start = current_time(); - - size_t kills = 0, encounters = 0; - std::chrono::minutes window_minutes(PLATFORM_RESET.WINDOW_IN_MINUTES); - WallDuration window = m_time_tracker->last_window_in_realtime(start, window_minutes); - - std::chrono::seconds window_seconds; - bool enough_time; - if (window == WallDuration::zero()){ -// stream.log("Debug Reset Timer: Window not initialized.", COLOR_RED); - - // Not enough history. - enough_time = false; - window = start - m_encounter_tracker->encounter_rate_tracker_start_time(); - window_seconds = std::chrono::duration_cast(window); - m_encounter_tracker->get_encounters_in_window( - kills, encounters, window_seconds - ); - }else{ -// stream.log("Debug Reset Timer: Window started.", COLOR_RED); - - window_seconds = std::chrono::duration_cast(window); - enough_time = m_encounter_tracker->get_encounters_in_window( - kills, encounters, window_seconds - ); - } - stream.log( - "Starting Traversal Iteration: " + tostr_u_commas(m_iterations) + - "\n Time Window (Seconds): " + std::to_string(window_seconds.count()) + - "\n Kills: " + std::to_string(kills) + - "\n Encounters: " + std::to_string(encounters) - ); - - // Check we want to do a platform reset first: - do{ - if (!PLATFORM_RESET.enabled()){ - stream.log("Platform Reset: Disabled", COLOR_ORANGE); - break; - } - if (!enough_time){ - stream.log("Platform Reset: Not enough time has elapsed.", COLOR_ORANGE); - break; - } - if (kills >= PLATFORM_RESET.KILLS_IN_WINDOW0){ - stream.log("Platform Reset: Enough kills in window.", COLOR_ORANGE); - break; - } - if (encounters >= PLATFORM_RESET.ENCOUNTERS_IN_WINDOW){ - stream.log("Platform Reset: Enough encounters in window.", COLOR_ORANGE); - break; - } - - stream.log("Conditions met for platform reset."); - m_pending_platform_reset = true; -// m_state = State::LEAVE_AND_RETURN; - return false; - }while (false); - - // Send Let's Go pokemon to beat wild pokemon while moving on the platform following one path. - // It tracks the kill chain by sound detection from `m_encounter_tracker`. - try{ - switch (PATH0){ - case Path::PATH0: - area_zero_platform_run_path0(*m_env, stream, context, *m_encounter_tracker, m_iterations); - break; - case Path::PATH1: - area_zero_platform_run_path1(*m_env, stream, context, *m_encounter_tracker, m_iterations); - break; - case Path::PATH2: - area_zero_platform_run_path2(*m_env, stream, context, *m_encounter_tracker, m_iterations); - break; - } - m_iterations++; - }catch (...){ - m_time_tracker->add_block(start, current_time()); - throw; - } - - m_time_tracker->add_block(start, current_time()); - - return true; -} - - -struct ResetException{}; - - -void ShinyHuntAreaZeroPlatform::set_flags(SingleSwitchProgramEnvironment& env){ -// ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); -// const ProgramInfo& info = m_env->program_info(); - VideoStream& stream = m_env->console; - - send_program_notification( - *m_env, NOTIFICATION_STATUS_UPDATE, - Color(0), - "Program Status", - {}, m_encounter_tracker->encounter_frequencies().dump_sorted_map("") - ); - - WallClock now = current_time(); - if (MODE == Mode::MAKE_SANDWICH && - m_last_sandwich + std::chrono::minutes(SANDWICH_RESET_IN_MINUTES) < now - ){ - stream.log("Enough time has elapsed. Time to reset sandwich..."); - m_pending_sandwich = true; - } - - int64_t seconds_on_sandwich = std::chrono::duration_cast(now - m_last_sandwich).count(); - stream.log( - std::string("State:\n") + - " Time on Sandwich: " + (m_last_sandwich == WallClock::min() - ? "N/A" - : std::to_string(seconds_on_sandwich)) + " seconds\n" + - " Pending Save: " + (m_pending_save ? "Yes" : "No") + "\n" + - " Pending Platform Reset: " + (m_pending_platform_reset ? "Yes" : "No") + "\n" + - " Pending Sandwich: " + (m_pending_sandwich ? "Yes" : "No") + "\n" + - " Reset after Sandwich: " + (m_reset_on_next_sandwich ? "Yes" : "No") + "\n" - ); - -} -void ShinyHuntAreaZeroPlatform::run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); - const ProgramInfo& info = m_env->program_info(); - VideoStream& stream = m_env->console; - - if (m_pending_save){ - stream.log("Executing: Pending Save..."); - if (m_current_location != Location::ZERO_GATE_FLY_SPOT && m_current_location != Location::AREA_ZERO){ - return_to_outside_zero_gate(info, stream, context); - m_current_location = Location::ZERO_GATE_FLY_SPOT; - } - save_game_from_overworld(info, stream, context); - m_saved_location = m_current_location; - m_pending_save = false; - return; - } - - if (m_pending_sandwich){ - stream.log("Executing: Pending Sandwich..."); - - // If we need to reset, do so now. - if (m_reset_on_next_sandwich){ - throw ResetException(); - } - - // If we're not at Zero Gate, go there now. - if (m_current_location != Location::ZERO_GATE_FLY_SPOT){ - return_to_outside_zero_gate(info, stream, context); - m_current_location = Location::ZERO_GATE_FLY_SPOT; - m_pending_platform_reset = false; - } - - m_reset_on_next_sandwich = true; - - // If we're not saved at Zero Gate, do it now. - if (m_saved_location != Location::ZERO_GATE_FLY_SPOT){ - save_game_from_overworld(info, stream, context); - m_saved_location = m_current_location; - } - - picnic_at_zero_gate(info, stream, context); - pbf_move_left_joystick(context, 128, 0, 70, 0); - enter_sandwich_recipe_list(info, stream, context); - make_sandwich_option(env, stream, context, SANDWICH_OPTIONS); - - stream.log("Sandwich Reset: Starting new sandwich timer..."); - m_last_sandwich = current_time(); - - stats.m_sandwiches++; - m_env->update_stats(); - - leave_picnic(info, stream, context); - return_to_inside_zero_gate_from_picnic(info, stream, context); - inside_zero_gate_to_platform(info, stream, context, FLYING_UNLOCKED, NAVIGATE_TO_PLATFORM); - m_current_location = Location::AREA_ZERO; - - m_pending_sandwich = false; - - m_encounter_tracker->reset_rate_tracker_start_time(); - m_consecutive_failures = 0; - - return; - } - - if (m_pending_platform_reset){ - stream.log("Executing: Platform Reset"); - return_to_inside_zero_gate(info, stream, context); - inside_zero_gate_to_platform(info, stream, context, FLYING_UNLOCKED, NAVIGATE_TO_PLATFORM); - m_current_location = Location::AREA_ZERO; - - stats.m_platform_resets++; - m_env->update_stats(); - - m_pending_platform_reset = false; - m_encounter_tracker->reset_rate_tracker_start_time(); - m_consecutive_failures = 0; - return; - } - - switch (m_current_location){ - case Location::UNKNOWN: - case Location::ZERO_GATE_FLY_SPOT: - case Location::TRAVELING_TO_PLATFORM: - stream.log("Executing: Platform Reset (state-based)..."); - return_to_inside_zero_gate(info, stream, context); - inside_zero_gate_to_platform(info, stream, context, FLYING_UNLOCKED, NAVIGATE_TO_PLATFORM); - m_current_location = Location::AREA_ZERO; - m_pending_platform_reset = false; - m_encounter_tracker->reset_rate_tracker_start_time(); - m_consecutive_failures = 0; - return; - case Location::AREA_ZERO: - stream.log("Executing: Traversal..."); - try{ - run_traversal(context); - }catch (OperationFailedException&){ - m_pending_platform_reset = true; - throw; - } -// m_encounter_tracker->reset_rate_tracker_start_time(); - m_consecutive_failures = 0; - return; - } -} -void ShinyHuntAreaZeroPlatform::set_flags_and_run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - set_flags(env); - - ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); -// const ProgramInfo& info = m_env->program_info(); - VideoStream& stream = m_env->console; - - try{ - run_state(env, context); - }catch (OperationFailedException& e){ - stats.m_errors++; - m_env->update_stats(); - m_consecutive_failures++; - e.send_notification(*m_env, NOTIFICATION_ERROR_RECOVERABLE); - if (m_consecutive_failures >= 3){ - throw_and_log( - stream.logger(), - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 times consecutively." - ); - } - } -} - -void ShinyHuntAreaZeroPlatform::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - m_env = &env; - - ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = env.current_stats(); - - assert_16_9_720p_min(env.logger(), env.console); - - m_iterations = 0; - - LetsGoHpWatcher hp_watcher(COLOR_RED); - m_hp_watcher = &hp_watcher; - - DiscontiguousTimeTracker time_tracker; - m_time_tracker = &time_tracker; - - LetsGoEncounterBotTracker encounter_tracker( - env, env.console, context, - stats, - LANGUAGE - ); - m_encounter_tracker = &encounter_tracker; - - m_saved_location = Location::UNKNOWN; - m_pending_save = false; - m_pending_platform_reset = false; - m_pending_sandwich = false; - m_reset_on_next_sandwich = false; - - switch (MODE){ - case Mode::START_ON_PLATFORM: - m_current_location = Location::AREA_ZERO; -// m_state = State::TRAVERSAL; - break; - case Mode::START_AT_ZERO_GATE_FLY_SPOT: - m_current_location = Location::ZERO_GATE_FLY_SPOT; -// m_state = State::INSIDE_GATE_AND_RETURN; - break; - case Mode::MAKE_SANDWICH: - m_current_location = Location::UNKNOWN; - m_pending_save = false; - m_pending_sandwich = true; -// m_state = State::RESET_SANDWICH; - break; - } - - -// m_pending_save = false; -// m_last_save = SavedLocation::NONE; - m_last_sandwich = WallClock::min(); - - // This is the outer-most program loop that wraps all logic with the - // battle menu detector. If at any time you detect a battle menu, you break - // all the way out here to handle the encounter. This is needed because you - // can get attacked at almost any time while in Area Zero. - m_consecutive_failures = 0; - while (true){ - try{ - env.console.log("Starting encounter loop...", COLOR_PURPLE); - EncounterWatcher encounter_watcher(env.console, COLOR_RED); - run_until( - env.console, context, - [&](ProControllerContext& context){ - // Inner program loop that runs the state machine. - while (true){ - set_flags_and_run_state(env, context); - } - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - hp_watcher, - } - ); - encounter_watcher.throw_if_no_sound(); - - env.console.log("Detected battle.", COLOR_PURPLE); - bool caught, should_save; - encounter_tracker.process_battle( - caught, should_save, - encounter_watcher, ENCOUNTER_BOT_OPTIONS - ); - m_pending_save |= should_save; - if (caught){ - m_reset_on_next_sandwich = false; - } - }catch (ResetException&){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - reset_game_from_home_zoom_out(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - m_current_location = m_saved_location; - stats.m_game_resets++; - m_env->update_stats(); - m_pending_platform_reset = false; - m_reset_on_next_sandwich = false; - }catch (ProgramFinishedException&){ - GO_HOME_WHEN_DONE.run_end_of_program(context); - throw; - } - } - -// GO_HOME_WHEN_DONE.run_end_of_program(context); -// send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Shiny Hunt - Area Zero Platform + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Programs/Eggs/PokemonSV_EggRoutines.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_AreaZero.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV_LetsGoTools.h" +#include "PokemonSV_ShinyHunt-AreaZeroPlatform.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + +ShinyHuntAreaZeroPlatform_Descriptor::ShinyHuntAreaZeroPlatform_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:ShinyHuntAreaZeroPlatform", + STRING_POKEMON + " SV", "Shiny Hunt - Area Zero Platform", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ShinyHunt-AreaZeroPlatform.md", + "Shiny hunt the isolated platform at the bottom of Area Zero.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntAreaZeroPlatform_Descriptor::Stats : public LetsGoEncounterBotStats{ + Stats() + : m_sandwiches(m_stats["Sandwiches"]) + , m_autoheals(m_stats["Auto Heals"]) + , m_platform_resets(m_stats["Platform Resets"]) + , m_game_resets(m_stats["Game Resets"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 4, {"Platform Resets", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 5, {"Game Resets", ALWAYS_HIDDEN}); + m_display_order.insert(m_display_order.begin() + 6, {"Errors", HIDDEN_IF_ZERO}); + } + std::atomic& m_sandwiches; + std::atomic& m_autoheals; + std::atomic& m_platform_resets; + std::atomic& m_game_resets; + std::atomic& m_errors; +}; +std::unique_ptr ShinyHuntAreaZeroPlatform_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +ShinyHuntAreaZeroPlatform::~ShinyHuntAreaZeroPlatform(){ + MODE.remove_listener(*this); +} + +ShinyHuntAreaZeroPlatform::ShinyHuntAreaZeroPlatform() + : LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , MODE( + "Mode:
" + "If starting on the platform, you should stand near the center of the platform facing any direction.
" + "If starting at the Zero Gate fly spot, you should be at the fly spot as if you just flew there." + "
If making a sandwich, you should be at the Zero Gate fly spot as if you just flew there.", + { + {Mode::START_ON_PLATFORM, "platform", "Start on platform."}, + {Mode::START_AT_ZERO_GATE_FLY_SPOT, "zerogate", "Start at Zero Gate fly spot."}, + {Mode::MAKE_SANDWICH, "sandwich", "Make a sandwich."}, + }, + LockMode::LOCK_WHILE_RUNNING, + Mode::START_ON_PLATFORM + ) + , FLYING_UNLOCKED( + "Flying Unlocked:
Check this box if you have unlocked your ride's ability to fly after completing the Indigo Disk DLC.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , PATH0( + "Path:
Traversal path on the platform to trigger encounters.", + { + {Path::PATH0, "path0", "Path 0"}, + {Path::PATH1, "path1", "Path 1"}, + {Path::PATH2, "path2", "Path 2"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + Path::PATH2 + ) + , SANDWICH_RESET_IN_MINUTES( + "Sandwich Reset Time (in minutes):
The time to reset game to make a new sandwich.", + LockMode::UNLOCK_WHILE_RUNNING, + 35 + ) + , SANDWICH_OPTIONS( + "Sandwich Options", + &LANGUAGE, + BaseRecipe::paradox, + false, + GroupOption::EnableMode::ALWAYS_ENABLED + ) + , GO_HOME_WHEN_DONE(true) + , AUTO_HEAL_PERCENT( + "Auto-Heal %
Auto-heal if your HP drops below this percentage.", + LockMode::UNLOCK_WHILE_RUNNING, + 75, 0, 100 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(FLYING_UNLOCKED); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(PATH0); + } + PA_ADD_OPTION(SANDWICH_RESET_IN_MINUTES); + PA_ADD_OPTION(SANDWICH_OPTIONS); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(AUTO_HEAL_PERCENT); + PA_ADD_OPTION(PLATFORM_RESET); + PA_ADD_OPTION(NAVIGATE_TO_PLATFORM); + PA_ADD_OPTION(NOTIFICATIONS); + + ShinyHuntAreaZeroPlatform::on_config_value_changed(this); + + MODE.add_listener(*this); +} + +std::string ShinyHuntAreaZeroPlatform::check_validity() const{ + std::string error = SingleSwitchProgramInstance::check_validity(); + if (!error.empty()){ + return error; + } + if (LANGUAGE == Language::None && MODE == Mode::MAKE_SANDWICH){ + return "Sandwich mode requires selecting a language."; + } + return ""; +} +void ShinyHuntAreaZeroPlatform::on_config_value_changed(void* object){ + ConfigOptionState state = MODE == Mode::MAKE_SANDWICH + ? ConfigOptionState::ENABLED + : ConfigOptionState::HIDDEN; + SANDWICH_RESET_IN_MINUTES.set_visibility(state); + SANDWICH_OPTIONS.set_visibility(state); +} + + + +bool ShinyHuntAreaZeroPlatform::run_traversal(ProControllerContext& context){ + ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); + + const ProgramInfo& info = m_env->program_info(); + VideoStream& stream = m_env->console; + +// if (m_pending_save){ +// save_game_from_overworld(info, console, context); +// m_pending_save = false; +// m_last_save = SavedLocation::AREA_ZERO; +// } + + double hp = m_hp_watcher->last_known_value() * 100; + if (0 < hp){ + stream.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); + }else{ + stream.log("Last Known HP: ?", COLOR_RED); + } + if (0 < hp && hp < AUTO_HEAL_PERCENT){ + auto_heal_from_menu_or_overworld(info, stream, context, 0, true); + stats.m_autoheals++; + m_env->update_stats(); + } + + WallClock start = current_time(); + + size_t kills = 0, encounters = 0; + std::chrono::minutes window_minutes(PLATFORM_RESET.WINDOW_IN_MINUTES); + WallDuration window = m_time_tracker->last_window_in_realtime(start, window_minutes); + + std::chrono::seconds window_seconds; + bool enough_time; + if (window == WallDuration::zero()){ +// stream.log("Debug Reset Timer: Window not initialized.", COLOR_RED); + + // Not enough history. + enough_time = false; + window = start - m_encounter_tracker->encounter_rate_tracker_start_time(); + window_seconds = std::chrono::duration_cast(window); + m_encounter_tracker->get_encounters_in_window( + kills, encounters, window_seconds + ); + }else{ +// stream.log("Debug Reset Timer: Window started.", COLOR_RED); + + window_seconds = std::chrono::duration_cast(window); + enough_time = m_encounter_tracker->get_encounters_in_window( + kills, encounters, window_seconds + ); + } + stream.log( + "Starting Traversal Iteration: " + tostr_u_commas(m_iterations) + + "\n Time Window (Seconds): " + std::to_string(window_seconds.count()) + + "\n Kills: " + std::to_string(kills) + + "\n Encounters: " + std::to_string(encounters) + ); + + // Check we want to do a platform reset first: + do{ + if (!PLATFORM_RESET.enabled()){ + stream.log("Platform Reset: Disabled", COLOR_ORANGE); + break; + } + if (!enough_time){ + stream.log("Platform Reset: Not enough time has elapsed.", COLOR_ORANGE); + break; + } + if (kills >= PLATFORM_RESET.KILLS_IN_WINDOW0){ + stream.log("Platform Reset: Enough kills in window.", COLOR_ORANGE); + break; + } + if (encounters >= PLATFORM_RESET.ENCOUNTERS_IN_WINDOW){ + stream.log("Platform Reset: Enough encounters in window.", COLOR_ORANGE); + break; + } + + stream.log("Conditions met for platform reset."); + m_pending_platform_reset = true; +// m_state = State::LEAVE_AND_RETURN; + return false; + }while (false); + + // Send Let's Go pokemon to beat wild pokemon while moving on the platform following one path. + // It tracks the kill chain by sound detection from `m_encounter_tracker`. + try{ + switch (PATH0){ + case Path::PATH0: + area_zero_platform_run_path0(*m_env, stream, context, *m_encounter_tracker, m_iterations); + break; + case Path::PATH1: + area_zero_platform_run_path1(*m_env, stream, context, *m_encounter_tracker, m_iterations); + break; + case Path::PATH2: + area_zero_platform_run_path2(*m_env, stream, context, *m_encounter_tracker, m_iterations); + break; + } + m_iterations++; + }catch (...){ + m_time_tracker->add_block(start, current_time()); + throw; + } + + m_time_tracker->add_block(start, current_time()); + + return true; +} + + +struct ResetException{}; + + +void ShinyHuntAreaZeroPlatform::set_flags(SingleSwitchProgramEnvironment& env){ +// ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); +// const ProgramInfo& info = m_env->program_info(); + VideoStream& stream = m_env->console; + + send_program_notification( + *m_env, NOTIFICATION_STATUS_UPDATE, + Color(0), + "Program Status", + {}, m_encounter_tracker->encounter_frequencies().dump_sorted_map("") + ); + + WallClock now = current_time(); + if (MODE == Mode::MAKE_SANDWICH && + m_last_sandwich + std::chrono::minutes(SANDWICH_RESET_IN_MINUTES) < now + ){ + stream.log("Enough time has elapsed. Time to reset sandwich..."); + m_pending_sandwich = true; + } + + int64_t seconds_on_sandwich = std::chrono::duration_cast(now - m_last_sandwich).count(); + stream.log( + std::string("State:\n") + + " Time on Sandwich: " + (m_last_sandwich == WallClock::min() + ? "N/A" + : std::to_string(seconds_on_sandwich)) + " seconds\n" + + " Pending Save: " + (m_pending_save ? "Yes" : "No") + "\n" + + " Pending Platform Reset: " + (m_pending_platform_reset ? "Yes" : "No") + "\n" + + " Pending Sandwich: " + (m_pending_sandwich ? "Yes" : "No") + "\n" + + " Reset after Sandwich: " + (m_reset_on_next_sandwich ? "Yes" : "No") + "\n" + ); + +} +void ShinyHuntAreaZeroPlatform::run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); + const ProgramInfo& info = m_env->program_info(); + VideoStream& stream = m_env->console; + + if (m_pending_save){ + stream.log("Executing: Pending Save..."); + if (m_current_location != Location::ZERO_GATE_FLY_SPOT && m_current_location != Location::AREA_ZERO){ + return_to_outside_zero_gate(info, stream, context); + m_current_location = Location::ZERO_GATE_FLY_SPOT; + } + save_game_from_overworld(info, stream, context); + m_saved_location = m_current_location; + m_pending_save = false; + return; + } + + if (m_pending_sandwich){ + stream.log("Executing: Pending Sandwich..."); + + // If we need to reset, do so now. + if (m_reset_on_next_sandwich){ + throw ResetException(); + } + + // If we're not at Zero Gate, go there now. + if (m_current_location != Location::ZERO_GATE_FLY_SPOT){ + return_to_outside_zero_gate(info, stream, context); + m_current_location = Location::ZERO_GATE_FLY_SPOT; + m_pending_platform_reset = false; + } + + m_reset_on_next_sandwich = true; + + // If we're not saved at Zero Gate, do it now. + if (m_saved_location != Location::ZERO_GATE_FLY_SPOT){ + save_game_from_overworld(info, stream, context); + m_saved_location = m_current_location; + } + + picnic_at_zero_gate(info, stream, context); + pbf_move_left_joystick(context, 128, 0, 70, 0); + enter_sandwich_recipe_list(info, stream, context); + make_sandwich_option(env, stream, context, SANDWICH_OPTIONS); + + stream.log("Sandwich Reset: Starting new sandwich timer..."); + m_last_sandwich = current_time(); + + stats.m_sandwiches++; + m_env->update_stats(); + + leave_picnic(info, stream, context); + return_to_inside_zero_gate_from_picnic(info, stream, context); + inside_zero_gate_to_platform(info, stream, context, FLYING_UNLOCKED, NAVIGATE_TO_PLATFORM); + m_current_location = Location::AREA_ZERO; + + m_pending_sandwich = false; + + m_encounter_tracker->reset_rate_tracker_start_time(); + m_consecutive_failures = 0; + + return; + } + + if (m_pending_platform_reset){ + stream.log("Executing: Platform Reset"); + return_to_inside_zero_gate(info, stream, context); + inside_zero_gate_to_platform(info, stream, context, FLYING_UNLOCKED, NAVIGATE_TO_PLATFORM); + m_current_location = Location::AREA_ZERO; + + stats.m_platform_resets++; + m_env->update_stats(); + + m_pending_platform_reset = false; + m_encounter_tracker->reset_rate_tracker_start_time(); + m_consecutive_failures = 0; + return; + } + + switch (m_current_location){ + case Location::UNKNOWN: + case Location::ZERO_GATE_FLY_SPOT: + case Location::TRAVELING_TO_PLATFORM: + stream.log("Executing: Platform Reset (state-based)..."); + return_to_inside_zero_gate(info, stream, context); + inside_zero_gate_to_platform(info, stream, context, FLYING_UNLOCKED, NAVIGATE_TO_PLATFORM); + m_current_location = Location::AREA_ZERO; + m_pending_platform_reset = false; + m_encounter_tracker->reset_rate_tracker_start_time(); + m_consecutive_failures = 0; + return; + case Location::AREA_ZERO: + stream.log("Executing: Traversal..."); + try{ + run_traversal(context); + }catch (OperationFailedException&){ + m_pending_platform_reset = true; + throw; + } +// m_encounter_tracker->reset_rate_tracker_start_time(); + m_consecutive_failures = 0; + return; + } +} +void ShinyHuntAreaZeroPlatform::set_flags_and_run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + set_flags(env); + + ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = m_env->current_stats(); +// const ProgramInfo& info = m_env->program_info(); + VideoStream& stream = m_env->console; + + try{ + run_state(env, context); + }catch (OperationFailedException& e){ + stats.m_errors++; + m_env->update_stats(); + m_consecutive_failures++; + e.send_notification(*m_env, NOTIFICATION_ERROR_RECOVERABLE); + if (m_consecutive_failures >= 3){ + throw_and_log( + stream.logger(), + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 times consecutively." + ); + } + } +} + +void ShinyHuntAreaZeroPlatform::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + m_env = &env; + + ShinyHuntAreaZeroPlatform_Descriptor::Stats& stats = env.current_stats(); + + assert_16_9_720p_min(env.logger(), env.console); + + m_iterations = 0; + + LetsGoHpWatcher hp_watcher(COLOR_RED); + m_hp_watcher = &hp_watcher; + + DiscontiguousTimeTracker time_tracker; + m_time_tracker = &time_tracker; + + LetsGoEncounterBotTracker encounter_tracker( + env, env.console, context, + stats, + LANGUAGE + ); + m_encounter_tracker = &encounter_tracker; + + m_saved_location = Location::UNKNOWN; + m_pending_save = false; + m_pending_platform_reset = false; + m_pending_sandwich = false; + m_reset_on_next_sandwich = false; + + switch (MODE){ + case Mode::START_ON_PLATFORM: + m_current_location = Location::AREA_ZERO; +// m_state = State::TRAVERSAL; + break; + case Mode::START_AT_ZERO_GATE_FLY_SPOT: + m_current_location = Location::ZERO_GATE_FLY_SPOT; +// m_state = State::INSIDE_GATE_AND_RETURN; + break; + case Mode::MAKE_SANDWICH: + m_current_location = Location::UNKNOWN; + m_pending_save = false; + m_pending_sandwich = true; +// m_state = State::RESET_SANDWICH; + break; + } + + +// m_pending_save = false; +// m_last_save = SavedLocation::NONE; + m_last_sandwich = WallClock::min(); + + // This is the outer-most program loop that wraps all logic with the + // battle menu detector. If at any time you detect a battle menu, you break + // all the way out here to handle the encounter. This is needed because you + // can get attacked at almost any time while in Area Zero. + m_consecutive_failures = 0; + while (true){ + try{ + env.console.log("Starting encounter loop...", COLOR_PURPLE); + EncounterWatcher encounter_watcher(env.console, COLOR_RED); + run_until( + env.console, context, + [&](ProControllerContext& context){ + // Inner program loop that runs the state machine. + while (true){ + set_flags_and_run_state(env, context); + } + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + hp_watcher, + } + ); + encounter_watcher.throw_if_no_sound(); + + env.console.log("Detected battle.", COLOR_PURPLE); + bool caught, should_save; + encounter_tracker.process_battle( + caught, should_save, + encounter_watcher, ENCOUNTER_BOT_OPTIONS + ); + m_pending_save |= should_save; + if (caught){ + m_reset_on_next_sandwich = false; + } + }catch (ResetException&){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + reset_game_from_home_zoom_out(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + m_current_location = m_saved_location; + stats.m_game_resets++; + m_env->update_stats(); + m_pending_platform_reset = false; + m_reset_on_next_sandwich = false; + }catch (ProgramFinishedException&){ + GO_HOME_WHEN_DONE.run_end_of_program(context); + throw; + } + } + +// GO_HOME_WHEN_DONE.run_end_of_program(context); +// send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h index 20ed9c9b7c..b03b5c3c0b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-AreaZeroPlatform.h @@ -1,144 +1,144 @@ -/* Shiny Hunt - Area Zero Platform - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ShinyHuntAreaZeroPlatform_H -#define PokemonAutomation_PokemonSV_ShinyHuntAreaZeroPlatform_H - -#include -//#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -//#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" -#include "PokemonSV_AreaZeroPlatform.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class LetsGoHpWatcher; -class DiscontiguousTimeTracker; -class LetsGoEncounterBotTracker; - - - -class ShinyHuntAreaZeroPlatform_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAreaZeroPlatform_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAreaZeroPlatform : public SingleSwitchProgramInstance, public ConfigOption::Listener{ -public: - ~ShinyHuntAreaZeroPlatform(); - ShinyHuntAreaZeroPlatform(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - virtual std::string check_validity() const override; - virtual void on_config_value_changed(void* object) override; - - enum class Location{ - UNKNOWN, - ZERO_GATE_FLY_SPOT, - TRAVELING_TO_PLATFORM, - AREA_ZERO, - }; -// enum class State{ -// TRAVERSAL, -// INSIDE_GATE_AND_RETURN, -// LEAVE_AND_RETURN, -// RESET_AND_RETURN, -// RESET_SANDWICH, -// }; - - void set_flags(SingleSwitchProgramEnvironment& env); - void run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void set_flags_and_run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // Returns true on success. - bool run_traversal(ProControllerContext& context); - - -private: - OCR::LanguageOCROption LANGUAGE; - - enum class Mode{ - START_ON_PLATFORM, - START_AT_ZERO_GATE_FLY_SPOT, - MAKE_SANDWICH, - }; - EnumDropdownOption MODE; - - BooleanCheckBoxOption FLYING_UNLOCKED; - - enum class Path{ - PATH0, - PATH1, - PATH2, - }; - EnumDropdownOption PATH0; - - SimpleIntegerOption SANDWICH_RESET_IN_MINUTES; - SandwichMakerOption SANDWICH_OPTIONS; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - PlatformResetSettings PLATFORM_RESET; - NavigatePlatformSettings NAVIGATE_TO_PLATFORM; - FloatingPointOption AUTO_HEAL_PERCENT; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SingleSwitchProgramEnvironment* m_env; - - LetsGoHpWatcher* m_hp_watcher; - DiscontiguousTimeTracker* m_time_tracker; - LetsGoEncounterBotTracker* m_encounter_tracker; - - uint64_t m_iterations = 0; - Location m_current_location; - Location m_saved_location; -// State m_state; - - // Set to true if we should save on the first available opportunity. - bool m_pending_save; - bool m_pending_platform_reset; - bool m_pending_sandwich; - bool m_reset_on_next_sandwich; - -// enum class SavedLocation{ -// NONE, -// ZERO_GATE_FLY_SPOT, -// AREA_ZERO, -// }; -// SavedLocation m_last_save; - - WallClock m_last_sandwich; - - size_t m_consecutive_failures; -}; - - - - - -} -} -} -#endif +/* Shiny Hunt - Area Zero Platform + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ShinyHuntAreaZeroPlatform_H +#define PokemonAutomation_PokemonSV_ShinyHuntAreaZeroPlatform_H + +#include +//#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +//#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" +#include "PokemonSV_AreaZeroPlatform.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class LetsGoHpWatcher; +class DiscontiguousTimeTracker; +class LetsGoEncounterBotTracker; + + + +class ShinyHuntAreaZeroPlatform_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAreaZeroPlatform_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAreaZeroPlatform : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + ~ShinyHuntAreaZeroPlatform(); + ShinyHuntAreaZeroPlatform(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual std::string check_validity() const override; + virtual void on_config_value_changed(void* object) override; + + enum class Location{ + UNKNOWN, + ZERO_GATE_FLY_SPOT, + TRAVELING_TO_PLATFORM, + AREA_ZERO, + }; +// enum class State{ +// TRAVERSAL, +// INSIDE_GATE_AND_RETURN, +// LEAVE_AND_RETURN, +// RESET_AND_RETURN, +// RESET_SANDWICH, +// }; + + void set_flags(SingleSwitchProgramEnvironment& env); + void run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void set_flags_and_run_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // Returns true on success. + bool run_traversal(ProControllerContext& context); + + +private: + OCR::LanguageOCROption LANGUAGE; + + enum class Mode{ + START_ON_PLATFORM, + START_AT_ZERO_GATE_FLY_SPOT, + MAKE_SANDWICH, + }; + EnumDropdownOption MODE; + + BooleanCheckBoxOption FLYING_UNLOCKED; + + enum class Path{ + PATH0, + PATH1, + PATH2, + }; + EnumDropdownOption PATH0; + + SimpleIntegerOption SANDWICH_RESET_IN_MINUTES; + SandwichMakerOption SANDWICH_OPTIONS; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + PlatformResetSettings PLATFORM_RESET; + NavigatePlatformSettings NAVIGATE_TO_PLATFORM; + FloatingPointOption AUTO_HEAL_PERCENT; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SingleSwitchProgramEnvironment* m_env; + + LetsGoHpWatcher* m_hp_watcher; + DiscontiguousTimeTracker* m_time_tracker; + LetsGoEncounterBotTracker* m_encounter_tracker; + + uint64_t m_iterations = 0; + Location m_current_location; + Location m_saved_location; +// State m_state; + + // Set to true if we should save on the first available opportunity. + bool m_pending_save; + bool m_pending_platform_reset; + bool m_pending_sandwich; + bool m_reset_on_next_sandwich; + +// enum class SavedLocation{ +// NONE, +// ZERO_GATE_FLY_SPOT, +// AREA_ZERO, +// }; +// SavedLocation m_last_save; + + WallClock m_last_sandwich; + + size_t m_consecutive_failures; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp index 0ff07ac4ab..f806e85abf 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.cpp @@ -1,439 +1,439 @@ -/* Shiny Hunt - Scatterbug - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" -#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" -#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" -#include "PokemonSV_LetsGoTools.h" -#include "PokemonSV_ShinyHunt-Scatterbug.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -ShinyHuntScatterbug_Descriptor::ShinyHuntScatterbug_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:ShinyHuntScatterbug", - STRING_POKEMON + " SV", "Shiny Hunt - Scatterbug", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ShinyHunt-Scatterbug.md", - "Shiny hunt Scatterbug.", - FeedbackType::VIDEO_AUDIO, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntScatterbug_Descriptor::Stats : public LetsGoEncounterBotStats{ - Stats() - : m_sandwiches(m_stats["Sandwiches"]) - , m_autoheals(m_stats["Auto Heals"]) - , m_game_resets(m_stats["Game Resets"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 4, {"Game Resets", HIDDEN_IF_ZERO}); - m_display_order.insert(m_display_order.begin() + 5, {"Errors", HIDDEN_IF_ZERO}); - } - std::atomic& m_sandwiches; - std::atomic& m_autoheals; - std::atomic& m_game_resets; - std::atomic& m_errors; -}; -std::unique_ptr ShinyHuntScatterbug_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -ShinyHuntScatterbug::ShinyHuntScatterbug() - : SAVE_GAME_AT_START( - "Save Game at Program Start:
" - "This is to ensure the program can continue after resetting the game. Uncheck this option if you have manually saved the game.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , SANDWICH_OPTIONS( - "Sandwich Options", - &LANGUAGE, - BaseRecipe::shiny, - false, - GroupOption::EnableMode::ALWAYS_ENABLED - ) - , GO_HOME_WHEN_DONE(true) - , AUTO_HEAL_PERCENT( - "Auto-Heal %
Auto-heal if your HP drops below this percentage.", - LockMode::UNLOCK_WHILE_RUNNING, - 75, 0, 100 - ) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:
" - "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , DEBUG_WARP_TO_POKECENTER( - "Whether to change the program to just warping to closest PokeCenter and stopping:
" - "This is for debugging the PokeCenter warping function.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SKIP_SANDWICH( - "Whether to skip making sandwich:
" - "This is for debugging the program without waiting for sandwich making.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(SAVE_GAME_AT_START); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(SANDWICH_OPTIONS); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(AUTO_HEAL_PERCENT); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - PA_ADD_OPTION(DEBUG_WARP_TO_POKECENTER); - PA_ADD_OPTION(SKIP_SANDWICH); - } - - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void ShinyHuntScatterbug::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntScatterbug_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 50); - - assert_16_9_720p_min(env.logger(), env.console); - - if (DEBUG_WARP_TO_POKECENTER){ - reset_to_pokecenter(env.program_info(), env.console, context); - return; - } - - size_t consecutive_failures = 0; - m_pending_save = false; - - if (SAVE_GAME_AT_START){ - save_game_from_overworld(env.program_info(), env.console, context); - } - - LetsGoEncounterBotTracker encounter_tracker( - env, env.console, context, - stats, - LANGUAGE - ); - m_encounter_tracker = &encounter_tracker; - - while(true){ - try{ - run_one_sandwich_iteration(env, context); - consecutive_failures = 0; - }catch(OperationFailedException& e){ - stats.m_errors++; - env.update_stats(); - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - if (SAVE_DEBUG_VIDEO){ - // Take a video to give more context for debugging - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - if (m_pending_save){ - // We have found a pokemon to keep, but before we can save the game to protect the pokemon, an error occurred. - // To not lose the pokemon, don't reset. - env.log("Found an error before we can save the game to protect the newly kept pokemon.", COLOR_RED); - env.log("Don't reset game to protect it.", COLOR_RED); - throw std::move(e); - } - - consecutive_failures++; - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 times in the row.", - env.console - ); - } - - env.log("Reset game to handle recoverable error"); - reset_game(env.program_info(), env.console, context); - ++stats.m_game_resets; - env.update_stats(); - - }catch(ProgramFinishedException&){ - GO_HOME_WHEN_DONE.run_end_of_program(context); - throw; - } - } -} - - -// This function wraps around an action (e.g. go out of PokeCenter to make a sandwich) so that -// we can handle pokemon wild encounters when executing the action. -// Whenever a battle happens, we check shinies and handle battle according to user setting. After battle ends, move -// back to PokeCenter to start the `action` again. -// `action` must be an action starting at the PokeCenter -void ShinyHuntScatterbug::handle_battles_and_back_to_pokecenter( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - std::function&& action -){ - if (m_encounter_tracker == nullptr){ - throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "m_encounter_tracker == nullptr"); - } - - bool action_finished = false; - bool first_iteration = true; - // a flag for the case that the action has finished but not yet returned to pokecenter - bool returned_to_pokecenter = false; - while(action_finished == false || returned_to_pokecenter == false){ - // env.console.overlay().add_log("Calculate what to do next"); - EncounterWatcher encounter_watcher(env.console, COLOR_RED); - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - if (action_finished){ - // `action` is already finished. Now we just try to get back to pokecenter: - reset_to_pokecenter(env.program_info(), env.console, context); - context.wait_for_all_requests(); - returned_to_pokecenter = true; - return; - } - // We still need to carry out `action` - if (first_iteration){ - first_iteration = false; - }else{ - // This is at least the second iteration in the while-loop. - // So a previous round of action failed. - // We need to first re-initialize our position to the PokeCenter - // Use map to fly back to the pokecenter - reset_to_pokecenter(env.program_info(), env.console, context); - } - context.wait_for_all_requests(); - action(env, context); - context.wait_for_all_requests(); - action_finished = true; - }, - { - static_cast(encounter_watcher), - static_cast(encounter_watcher), - } - ); - encounter_watcher.throw_if_no_sound(); - if (ret >= 0){ - env.console.log("Detected battle.", COLOR_PURPLE); - env.console.overlay().add_log("Detected battle"); - try{ - bool caught, should_save; - m_encounter_tracker->process_battle( - caught, should_save, - encounter_watcher, ENCOUNTER_BOT_OPTIONS - ); - if (should_save){ - m_pending_save = should_save; - } - }catch (ProgramFinishedException&){ - GO_HOME_WHEN_DONE.run_end_of_program(context); - throw; - } - } - // Back on the overworld. - } // end while(action_finished == false || returned_to_pokecenter == false) -} - -// Start at Mesagoza South Gate pokecenter, make a sandwich, then use let's go repeatedly until 30 min passes. -// If -void ShinyHuntScatterbug::run_one_sandwich_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyHuntScatterbug_Descriptor::Stats& stats = env.current_stats(); - - bool saved_after_this_sandwich = false; - - WallClock last_sandwich_time = WallClock::min(); - - auto save_if_needed = [&](){ - if (m_pending_save){ - save_game_from_overworld(env.program_info(), env.console, context); - m_pending_save = false; - saved_after_this_sandwich = true; - } - }; - - handle_battles_and_back_to_pokecenter(env, context, - [this, &last_sandwich_time](SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Orient camera to look at same direction as player character - // This is needed because when save-load the game, the camera is reset - // to this location. - pbf_press_button(context, BUTTON_L, 50, 40); - // Move forward - pbf_move_left_joystick(context, 128, 0, 180, 0); - if (!SKIP_SANDWICH){ - picnic_from_overworld(env.program_info(), env.console, context); - - pbf_move_left_joystick(context, 128, 0, 30, 40); - enter_sandwich_recipe_list(env.program_info(), env.console, context); - make_sandwich_option(env, env.console, context, SANDWICH_OPTIONS); - last_sandwich_time = current_time(); - leave_picnic(env.program_info(), env.console, context); - }else{ - last_sandwich_time = current_time(); - } - } - ); - env.console.overlay().add_log("Started Let's Go Paths"); - save_if_needed(); - - // Which path to choose starting at the PokeCenter. - size_t path_id = 0; - const size_t num_paths = 2; - - LetsGoHpWatcher hp_watcher(COLOR_RED); - // In each iteration of this while-loop, it picks a path starting from the pokecenter or the - // last sandwich making spot, use Let's Go along the path, then fly back to pokecenter. - for (;;path_id = (path_id + 1) % num_paths){ - if (last_sandwich_time + std::chrono::minutes(30) < current_time()){ - env.log("Sandwich expires."); - env.console.overlay().add_log("Sandwich expires"); - break; - } - - env.console.log("Starting Let's Go hunting path " + std::to_string(path_id) + "...", COLOR_PURPLE); - env.console.overlay().add_log("Let's Go on Path " + std::to_string(path_id)); - - double hp = hp_watcher.last_known_value() * 100; - if (0 < hp){ - env.console.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); - }else{ - env.console.log("Last Known HP: ?", COLOR_RED); - } - if (0 < hp && hp < AUTO_HEAL_PERCENT){ - auto_heal_from_menu_or_overworld(env.program_info(), env.console, context, 0, true); - stats.m_autoheals++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } - - handle_battles_and_back_to_pokecenter(env, context, - [this, &path_id, &hp_watcher](SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - run_until( - env.console, context, - [&](ProControllerContext& context){ - run_lets_go_iteration(env, context, path_id); - }, - {hp_watcher} - ); - } // end [](...) - ); // end handle_battles_and_back_to_pokecenter() - save_if_needed(); - } // end for (;;path_id = (path_id + 1) % num_paths) - - if (!saved_after_this_sandwich){ - // Reset game to save rare herbs - reset_game(env.program_info(), env.console, context); - ++stats.m_game_resets; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - } -} - -// One iteration of the hunt: -// start at Mesagoza South Gate pokecenter, go out and use Let's Go to battle Scatterbug, -void ShinyHuntScatterbug::run_lets_go_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path_id){ - auto& console = env.console; - // Orient camera to look at same direction as player character - // This is needed because when save-load the game, the camera is reset - // to this location. - pbf_press_button(context, BUTTON_L, 50, 40); - - const bool throw_ball_if_bubble = true; - - auto move_forward_with_lets_go = [&](int num_iterations){ - context.wait_for_all_requests(); - for(int i = 0; i < num_iterations; i++){ - use_lets_go_to_clear_in_front(console, context, *m_encounter_tracker, throw_ball_if_bubble, [&](ProControllerContext& context){ - // Do the following movement while the Let's Go pokemon clearing wild pokemon. - // Slowly Moving forward - pbf_move_left_joystick(context, 128, 105, 800, 0); - }); - } - }; - - if (path_id == 0){ - // move rightward, to the west - pbf_move_left_joystick(context, 255, 128, 100, 20); - // Align camera - pbf_press_button(context, BUTTON_L, 50, 40); - - move_forward_with_lets_go(10); - }else{ // path_id == 1 - // move leftward, to the east - pbf_move_left_joystick(context, 0, 128, 100, 20); - // Align camera - pbf_press_button(context, BUTTON_L, 50, 40); - - move_forward_with_lets_go(5); - - // move rightward, to south - pbf_move_left_joystick(context, 255, 128, 50, 20); - // Align camera - pbf_press_button(context, BUTTON_L, 50, 40); - - move_forward_with_lets_go(5); - } -} - - -} -} -} +/* Shiny Hunt - Scatterbug + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoHpReader.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_IvJudgeReader.h" +#include "PokemonSV/Inference/Battles/PokemonSV_EncounterWatcher.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_WorldNavigation.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/Battles/PokemonSV_Battles.h" +#include "PokemonSV/Programs/Sandwiches/PokemonSV_SandwichRoutines.h" +#include "PokemonSV_LetsGoTools.h" +#include "PokemonSV_ShinyHunt-Scatterbug.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +ShinyHuntScatterbug_Descriptor::ShinyHuntScatterbug_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:ShinyHuntScatterbug", + STRING_POKEMON + " SV", "Shiny Hunt - Scatterbug", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/ShinyHunt-Scatterbug.md", + "Shiny hunt Scatterbug.", + FeedbackType::VIDEO_AUDIO, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntScatterbug_Descriptor::Stats : public LetsGoEncounterBotStats{ + Stats() + : m_sandwiches(m_stats["Sandwiches"]) + , m_autoheals(m_stats["Auto Heals"]) + , m_game_resets(m_stats["Game Resets"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.insert(m_display_order.begin() + 2, {"Sandwiches", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 3, {"Auto Heals", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 4, {"Game Resets", HIDDEN_IF_ZERO}); + m_display_order.insert(m_display_order.begin() + 5, {"Errors", HIDDEN_IF_ZERO}); + } + std::atomic& m_sandwiches; + std::atomic& m_autoheals; + std::atomic& m_game_resets; + std::atomic& m_errors; +}; +std::unique_ptr ShinyHuntScatterbug_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +ShinyHuntScatterbug::ShinyHuntScatterbug() + : SAVE_GAME_AT_START( + "Save Game at Program Start:
" + "This is to ensure the program can continue after resetting the game. Uncheck this option if you have manually saved the game.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , SANDWICH_OPTIONS( + "Sandwich Options", + &LANGUAGE, + BaseRecipe::shiny, + false, + GroupOption::EnableMode::ALWAYS_ENABLED + ) + , GO_HOME_WHEN_DONE(true) + , AUTO_HEAL_PERCENT( + "Auto-Heal %
Auto-heal if your HP drops below this percentage.", + LockMode::UNLOCK_WHILE_RUNNING, + 75, 0, 100 + ) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:
" + "Set this on to save a Switch video everytime an error occurs. You can send the video to developers to help them debug later.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , DEBUG_WARP_TO_POKECENTER( + "Whether to change the program to just warping to closest PokeCenter and stopping:
" + "This is for debugging the PokeCenter warping function.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SKIP_SANDWICH( + "Whether to skip making sandwich:
" + "This is for debugging the program without waiting for sandwich making.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(SAVE_GAME_AT_START); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(SANDWICH_OPTIONS); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(AUTO_HEAL_PERCENT); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + PA_ADD_OPTION(DEBUG_WARP_TO_POKECENTER); + PA_ADD_OPTION(SKIP_SANDWICH); + } + + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void ShinyHuntScatterbug::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntScatterbug_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 50); + + assert_16_9_720p_min(env.logger(), env.console); + + if (DEBUG_WARP_TO_POKECENTER){ + reset_to_pokecenter(env.program_info(), env.console, context); + return; + } + + size_t consecutive_failures = 0; + m_pending_save = false; + + if (SAVE_GAME_AT_START){ + save_game_from_overworld(env.program_info(), env.console, context); + } + + LetsGoEncounterBotTracker encounter_tracker( + env, env.console, context, + stats, + LANGUAGE + ); + m_encounter_tracker = &encounter_tracker; + + while(true){ + try{ + run_one_sandwich_iteration(env, context); + consecutive_failures = 0; + }catch(OperationFailedException& e){ + stats.m_errors++; + env.update_stats(); + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + if (SAVE_DEBUG_VIDEO){ + // Take a video to give more context for debugging + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + if (m_pending_save){ + // We have found a pokemon to keep, but before we can save the game to protect the pokemon, an error occurred. + // To not lose the pokemon, don't reset. + env.log("Found an error before we can save the game to protect the newly kept pokemon.", COLOR_RED); + env.log("Don't reset game to protect it.", COLOR_RED); + throw std::move(e); + } + + consecutive_failures++; + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 times in the row.", + env.console + ); + } + + env.log("Reset game to handle recoverable error"); + reset_game(env.program_info(), env.console, context); + ++stats.m_game_resets; + env.update_stats(); + + }catch(ProgramFinishedException&){ + GO_HOME_WHEN_DONE.run_end_of_program(context); + throw; + } + } +} + + +// This function wraps around an action (e.g. go out of PokeCenter to make a sandwich) so that +// we can handle pokemon wild encounters when executing the action. +// Whenever a battle happens, we check shinies and handle battle according to user setting. After battle ends, move +// back to PokeCenter to start the `action` again. +// `action` must be an action starting at the PokeCenter +void ShinyHuntScatterbug::handle_battles_and_back_to_pokecenter( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + std::function&& action +){ + if (m_encounter_tracker == nullptr){ + throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "m_encounter_tracker == nullptr"); + } + + bool action_finished = false; + bool first_iteration = true; + // a flag for the case that the action has finished but not yet returned to pokecenter + bool returned_to_pokecenter = false; + while(action_finished == false || returned_to_pokecenter == false){ + // env.console.overlay().add_log("Calculate what to do next"); + EncounterWatcher encounter_watcher(env.console, COLOR_RED); + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + if (action_finished){ + // `action` is already finished. Now we just try to get back to pokecenter: + reset_to_pokecenter(env.program_info(), env.console, context); + context.wait_for_all_requests(); + returned_to_pokecenter = true; + return; + } + // We still need to carry out `action` + if (first_iteration){ + first_iteration = false; + }else{ + // This is at least the second iteration in the while-loop. + // So a previous round of action failed. + // We need to first re-initialize our position to the PokeCenter + // Use map to fly back to the pokecenter + reset_to_pokecenter(env.program_info(), env.console, context); + } + context.wait_for_all_requests(); + action(env, context); + context.wait_for_all_requests(); + action_finished = true; + }, + { + static_cast(encounter_watcher), + static_cast(encounter_watcher), + } + ); + encounter_watcher.throw_if_no_sound(); + if (ret >= 0){ + env.console.log("Detected battle.", COLOR_PURPLE); + env.console.overlay().add_log("Detected battle"); + try{ + bool caught, should_save; + m_encounter_tracker->process_battle( + caught, should_save, + encounter_watcher, ENCOUNTER_BOT_OPTIONS + ); + if (should_save){ + m_pending_save = should_save; + } + }catch (ProgramFinishedException&){ + GO_HOME_WHEN_DONE.run_end_of_program(context); + throw; + } + } + // Back on the overworld. + } // end while(action_finished == false || returned_to_pokecenter == false) +} + +// Start at Mesagoza South Gate pokecenter, make a sandwich, then use let's go repeatedly until 30 min passes. +// If +void ShinyHuntScatterbug::run_one_sandwich_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyHuntScatterbug_Descriptor::Stats& stats = env.current_stats(); + + bool saved_after_this_sandwich = false; + + WallClock last_sandwich_time = WallClock::min(); + + auto save_if_needed = [&](){ + if (m_pending_save){ + save_game_from_overworld(env.program_info(), env.console, context); + m_pending_save = false; + saved_after_this_sandwich = true; + } + }; + + handle_battles_and_back_to_pokecenter(env, context, + [this, &last_sandwich_time](SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Orient camera to look at same direction as player character + // This is needed because when save-load the game, the camera is reset + // to this location. + pbf_press_button(context, BUTTON_L, 50, 40); + // Move forward + pbf_move_left_joystick(context, 128, 0, 180, 0); + if (!SKIP_SANDWICH){ + picnic_from_overworld(env.program_info(), env.console, context); + + pbf_move_left_joystick(context, 128, 0, 30, 40); + enter_sandwich_recipe_list(env.program_info(), env.console, context); + make_sandwich_option(env, env.console, context, SANDWICH_OPTIONS); + last_sandwich_time = current_time(); + leave_picnic(env.program_info(), env.console, context); + }else{ + last_sandwich_time = current_time(); + } + } + ); + env.console.overlay().add_log("Started Let's Go Paths"); + save_if_needed(); + + // Which path to choose starting at the PokeCenter. + size_t path_id = 0; + const size_t num_paths = 2; + + LetsGoHpWatcher hp_watcher(COLOR_RED); + // In each iteration of this while-loop, it picks a path starting from the pokecenter or the + // last sandwich making spot, use Let's Go along the path, then fly back to pokecenter. + for (;;path_id = (path_id + 1) % num_paths){ + if (last_sandwich_time + std::chrono::minutes(30) < current_time()){ + env.log("Sandwich expires."); + env.console.overlay().add_log("Sandwich expires"); + break; + } + + env.console.log("Starting Let's Go hunting path " + std::to_string(path_id) + "...", COLOR_PURPLE); + env.console.overlay().add_log("Let's Go on Path " + std::to_string(path_id)); + + double hp = hp_watcher.last_known_value() * 100; + if (0 < hp){ + env.console.log("Last Known HP: " + tostr_default(hp) + "%", COLOR_BLUE); + }else{ + env.console.log("Last Known HP: ?", COLOR_RED); + } + if (0 < hp && hp < AUTO_HEAL_PERCENT){ + auto_heal_from_menu_or_overworld(env.program_info(), env.console, context, 0, true); + stats.m_autoheals++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } + + handle_battles_and_back_to_pokecenter(env, context, + [this, &path_id, &hp_watcher](SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + run_until( + env.console, context, + [&](ProControllerContext& context){ + run_lets_go_iteration(env, context, path_id); + }, + {hp_watcher} + ); + } // end [](...) + ); // end handle_battles_and_back_to_pokecenter() + save_if_needed(); + } // end for (;;path_id = (path_id + 1) % num_paths) + + if (!saved_after_this_sandwich){ + // Reset game to save rare herbs + reset_game(env.program_info(), env.console, context); + ++stats.m_game_resets; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + } +} + +// One iteration of the hunt: +// start at Mesagoza South Gate pokecenter, go out and use Let's Go to battle Scatterbug, +void ShinyHuntScatterbug::run_lets_go_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path_id){ + auto& console = env.console; + // Orient camera to look at same direction as player character + // This is needed because when save-load the game, the camera is reset + // to this location. + pbf_press_button(context, BUTTON_L, 50, 40); + + const bool throw_ball_if_bubble = true; + + auto move_forward_with_lets_go = [&](int num_iterations){ + context.wait_for_all_requests(); + for(int i = 0; i < num_iterations; i++){ + use_lets_go_to_clear_in_front(console, context, *m_encounter_tracker, throw_ball_if_bubble, [&](ProControllerContext& context){ + // Do the following movement while the Let's Go pokemon clearing wild pokemon. + // Slowly Moving forward + pbf_move_left_joystick(context, 128, 105, 800, 0); + }); + } + }; + + if (path_id == 0){ + // move rightward, to the west + pbf_move_left_joystick(context, 255, 128, 100, 20); + // Align camera + pbf_press_button(context, BUTTON_L, 50, 40); + + move_forward_with_lets_go(10); + }else{ // path_id == 1 + // move leftward, to the east + pbf_move_left_joystick(context, 0, 128, 100, 20); + // Align camera + pbf_press_button(context, BUTTON_L, 50, 40); + + move_forward_with_lets_go(5); + + // move rightward, to south + pbf_move_left_joystick(context, 255, 128, 50, 20); + // Align camera + pbf_press_button(context, BUTTON_L, 50, 40); + + move_forward_with_lets_go(5); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h index 4b29bb9721..8d35275ff9 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h +++ b/SerialPrograms/Source/PokemonSV/Programs/ShinyHunting/PokemonSV_ShinyHunt-Scatterbug.h @@ -1,83 +1,83 @@ -/* Shiny Hunt - Scatterbug - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ShinyHuntScatterbug_H -#define PokemonAutomation_PokemonSV_ShinyHuntScatterbug_H - -#include -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" -#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class LetsGoEncounterBotTracker; - - -class ShinyHuntScatterbug_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntScatterbug_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntScatterbug : public SingleSwitchProgramInstance{ -public: - ShinyHuntScatterbug(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_one_sandwich_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - void run_lets_go_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path_id); - - void handle_battles_and_back_to_pokecenter(SingleSwitchProgramEnvironment& env, ProControllerContext& context, - std::function&& action); - - BooleanCheckBoxOption SAVE_GAME_AT_START; - - OCR::LanguageOCROption LANGUAGE; - - SandwichMakerOption SANDWICH_OPTIONS; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - FloatingPointOption AUTO_HEAL_PERCENT; - - // Debug options - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; - BooleanCheckBoxOption DEBUG_WARP_TO_POKECENTER; - BooleanCheckBoxOption SKIP_SANDWICH; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - LetsGoEncounterBotTracker* m_encounter_tracker; - - // Set to true if we should save on the first available opportunity. - bool m_pending_save; -}; - - - - - -} -} -} -#endif +/* Shiny Hunt - Scatterbug + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ShinyHuntScatterbug_H +#define PokemonAutomation_PokemonSV_ShinyHuntScatterbug_H + +#include +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "PokemonSV/Options/PokemonSV_EncounterBotCommon.h" +#include "PokemonSV/Options/PokemonSV_SandwichMakerOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class LetsGoEncounterBotTracker; + + +class ShinyHuntScatterbug_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntScatterbug_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntScatterbug : public SingleSwitchProgramInstance{ +public: + ShinyHuntScatterbug(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_one_sandwich_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + void run_lets_go_iteration(SingleSwitchProgramEnvironment& env, ProControllerContext& context, size_t path_id); + + void handle_battles_and_back_to_pokecenter(SingleSwitchProgramEnvironment& env, ProControllerContext& context, + std::function&& action); + + BooleanCheckBoxOption SAVE_GAME_AT_START; + + OCR::LanguageOCROption LANGUAGE; + + SandwichMakerOption SANDWICH_OPTIONS; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + FloatingPointOption AUTO_HEAL_PERCENT; + + // Debug options + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; + BooleanCheckBoxOption DEBUG_WARP_TO_POKECENTER; + BooleanCheckBoxOption SKIP_SANDWICH; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + LetsGoEncounterBotTracker* m_encounter_tracker; + + // Set to true if we should save on the first available opportunity. + bool m_pending_save; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp index a69ac7e60e..d9e94ede5e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.cpp @@ -1,396 +1,396 @@ -/* Auto Host - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV_AutoHostTools.h" -#include "PokemonSV_AutoHostLobbyWaiter.h" -#include "PokemonSV_AutoHost.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -AutoHost_Descriptor::AutoHost_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:AutoHost", - STRING_POKEMON + " SV", "Auto-Host", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoHost.md", - "Auto-host a Tera raid.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} -struct AutoHost_Descriptor::Stats : public StatsTracker{ - Stats() - : m_raids(m_stats["Raids"]) - , m_empty(m_stats["Empty Raids"]) - , m_full(m_stats["Full Raids"]) - , m_raiders(m_stats["Total Raiders"]) - , m_wins(m_stats["Wins"]) - , m_losses(m_stats["Losses"]) - , m_banned(m_stats["Banned"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Raids"); - m_display_order.emplace_back("Empty Raids"); - m_display_order.emplace_back("Full Raids"); - m_display_order.emplace_back("Total Raiders"); - m_display_order.emplace_back("Wins"); - m_display_order.emplace_back("Losses"); - m_display_order.emplace_back("Banned", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_raids; - std::atomic& m_empty; - std::atomic& m_full; - std::atomic& m_raiders; - std::atomic& m_wins; - std::atomic& m_losses; - std::atomic& m_banned; - std::atomic& m_errors; -}; -std::unique_ptr AutoHost_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -AutoHost::AutoHost() - : SingleSwitchProgramInstance({"Notifs", "LiveHost"}) - , MODE( - "Hosting Mode:", - { - {HostingMode::LOCAL, "local", "Host Locally"}, - {HostingMode::ONLINE_CODED, "online-coded", "Host Online (link code)"}, - {HostingMode::ONLINE_EVERYONE, "online-everyone", "Host Online (everyone)"}, - }, - LockMode::UNLOCK_WHILE_RUNNING, - HostingMode::ONLINE_CODED - ) - , NOTIFICATIONS0({ - &NOTIFICATION_RAID_POST, - &NOTIFICATION_RAID_START, - &NOTIFICATION_JOIN_REPORT, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(MODE); - - // General Auto-Hosting Options - PA_ADD_OPTION(LOBBY_WAIT_DELAY); - PA_ADD_OPTION(START_RAID_PLAYERS); - PA_ADD_OPTION(SHOW_RAID_CODE); - PA_ADD_OPTION(DESCRIPTION); - PA_ADD_OPTION(REMOTE_KILL_SWITCH0); - PA_ADD_OPTION(CONSECUTIVE_FAILURE_PAUSE); - PA_ADD_OPTION(FAILURE_PAUSE_MINUTES); - - PA_ADD_OPTION(ROLLOVER_PREVENTION); - PA_ADD_OPTION(BATTLE_AI); - - // Extended Auto-Hosting Options - PA_ADD_OPTION(BAN_LIST); - PA_ADD_OPTION(JOIN_REPORT); - - PA_ADD_OPTION(NOTIFICATIONS0); -} - - - -WallClock AutoHost::wait_for_lobby_open( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - std::string& lobby_code -){ - VideoOverlaySet overlays(env.console.overlay()); - - TeraLobbyWatcher lobby(env.logger(), env.normal_inference_dispatcher(), COLOR_RED); - lobby.make_overlays(overlays); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(60), - {{lobby, std::chrono::milliseconds(500)}} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to detect Tera lobby after 60 seconds.", - env.console - ); - } - WallClock start_time = current_time(); - context.wait_for(std::chrono::seconds(1)); - - VideoSnapshot snapshot = env.console.video().snapshot(); - lobby_code = lobby.raid_code(env.logger(), env.normal_inference_dispatcher(), snapshot); - std::string code = lobby.raid_code(env.logger(), env.normal_inference_dispatcher(), snapshot); - normalize_code(lobby_code, code); - - send_host_announcement( - env, env.console, - lobby_code, - SHOW_RAID_CODE, - DESCRIPTION, - NOTIFICATION_RAID_POST - ); - - return start_time; -} -void AutoHost::update_stats_on_raid_start(SingleSwitchProgramEnvironment& env, uint8_t player_count){ - AutoHost_Descriptor::Stats& stats = env.current_stats(); - - player_count = std::max(player_count, 1); - - if (player_count == 4){ - stats.m_full++; - } - if (player_count == 1){ - stats.m_empty++; - } - stats.m_raiders += player_count - 1; -} -bool AutoHost::start_raid( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - WallClock start_time, - uint8_t player_count -){ - AutoHost_Descriptor::Stats& stats = env.current_stats(); - - // This is the state machine to actually start the raid. - - while (true){ - AdvanceDialogWatcher dialog(COLOR_YELLOW); - WhiteScreenOverWatcher start_raid(COLOR_BLUE); - TeraBattleMenuWatcher battle_menu(COLOR_CYAN); - context.wait_for_all_requests(); - int ret = run_until( - env.console, context, - [start_time](ProControllerContext& context){ - while (true){ - pbf_press_button(context, BUTTON_A, 20, 105); - context.wait_for_all_requests(); - if (current_time() > start_time + std::chrono::minutes(4)){ - return; - } - } - }, - {dialog, start_raid, battle_menu} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - env.log("Raid timed out!", COLOR_ORANGE); - stats.m_empty++; - return false; - case 1: - env.log("Raid started! (white screen)", COLOR_BLUE); - update_stats_on_raid_start(env, player_count); - return true; - case 2: - env.log("Raid started! (battle menu)", COLOR_BLUE); - update_stats_on_raid_start(env, player_count); - return true; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Stuck in lobby for 4 minutes.", - env.console - ); - } - } -} - - -bool AutoHost::run_lobby( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - std::string& lobby_code, - std::array, 4>& player_names -){ - AutoHost_Descriptor::Stats& stats = env.current_stats(); - - WallClock start_time = wait_for_lobby_open(env, context, lobby_code); - - TeraLobbyWaiter waiter( - env, env.console, context, - 1, - lobby_code, start_time, - LOBBY_WAIT_DELAY, - START_RAID_PLAYERS, - NOTIFICATION_RAID_START, - BAN_LIST, - JOIN_REPORT - ); - - TeraLobbyWaiter::LobbyResult result = waiter.run_lobby(); - player_names = waiter.names(); - - if (result == TeraLobbyWaiter::LobbyResult::BANNED_PLAYER){ - stats.m_banned++; - } - if (result != TeraLobbyWaiter::LobbyResult::RAID_STARTED){ - return false; - } - - return start_raid(env, context, start_time, waiter.last_known_players()); -} - -void AutoHost::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - AutoHost_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 10); - - m_killswitch_time = WallClock::max(); - - std::string report_name = "PokemonSV-AutoHost-JoinReport-" + now_to_filestring() + ".txt"; - MultiLanguageJoinTracker join_tracker(1); - - TeraFailTracker fail_tracker( - env, context, - NOTIFICATION_ERROR_RECOVERABLE, - CONSECUTIVE_FAILURE_PAUSE, - FAILURE_PAUSE_MINUTES - ); - KillSwitchTracker kill_switch(env); - - bool skip_reset = true; - WallClock last_time_fix = WallClock::min(); - while (true){ - env.update_stats(); - - fail_tracker.on_raid_start(); - - if (!skip_reset){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - if (ROLLOVER_PREVENTION){ - WallClock now = current_time(); - if (last_time_fix == WallClock::min() || now - last_time_fix > std::chrono::hours(4)){ - set_time_to_12am_from_home(env.program_info(), env.console, context); - last_time_fix = now; - } - } - reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); - } - skip_reset = false; - - // Check kill-switch now before we go online. - if (MODE != HostingMode::LOCAL){ - kill_switch.check_kill_switch(REMOTE_KILL_SWITCH0); - } - - // Store the mode locally in case the user changes in the middle of - // this iteration. - HostingMode mode = MODE; - - if (mode != HostingMode::LOCAL){ - // Connect to internet. - try{ - connect_to_internet_from_overworld(env.program_info(), env.console, context); - }catch (OperationFailedException& e){ - stats.m_errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - fail_tracker.report_raid_error(); - continue; - } - } - - if (!open_raid(env.console, context)){ - env.log("No Tera raid found.", COLOR_RED); - fail_tracker.report_raid_error(); - continue; - } - env.log("Tera raid found!", COLOR_BLUE); - - context.wait_for(std::chrono::milliseconds(100)); - - BAN_LIST.refresh_online_table(env.logger()); - - try{ - open_hosting_lobby(env, env.console, context, mode); - }catch (OperationFailedException& e){ - stats.m_errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - fail_tracker.report_raid_error(); - continue; - } - - try{ - std::string lobby_code; - std::array, 4> player_names; - - if (!run_lobby(env, context, lobby_code, player_names)){ - continue; - } - env.update_stats(); - - stats.m_raids++; - bool win = run_tera_battle(env, env.console, context, BATTLE_AI); - env.update_stats(); - if (win){ - stats.m_wins++; - }else{ - stats.m_losses++; - } - if (JOIN_REPORT.enabled() && (win || !JOIN_REPORT.wins_only)){ - join_tracker.append(player_names, lobby_code); - join_tracker.dump(report_name); - send_program_notification_with_file( - env, - NOTIFICATION_JOIN_REPORT, - Color(0), - "Join Report", - {}, "", - report_name - ); - } - if (win){ - exit_tera_win_without_catching(env.program_info(), env.console, context, 0); - } - fail_tracker.report_successful_raid(); - }catch (OperationFailedException& e){ - stats.m_errors++; - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - fail_tracker.report_raid_error(); - continue; - } - } -} - - - -} -} -} +/* Auto Host + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV_AutoHostTools.h" +#include "PokemonSV_AutoHostLobbyWaiter.h" +#include "PokemonSV_AutoHost.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +AutoHost_Descriptor::AutoHost_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:AutoHost", + STRING_POKEMON + " SV", "Auto-Host", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/AutoHost.md", + "Auto-host a Tera raid.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} +struct AutoHost_Descriptor::Stats : public StatsTracker{ + Stats() + : m_raids(m_stats["Raids"]) + , m_empty(m_stats["Empty Raids"]) + , m_full(m_stats["Full Raids"]) + , m_raiders(m_stats["Total Raiders"]) + , m_wins(m_stats["Wins"]) + , m_losses(m_stats["Losses"]) + , m_banned(m_stats["Banned"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Raids"); + m_display_order.emplace_back("Empty Raids"); + m_display_order.emplace_back("Full Raids"); + m_display_order.emplace_back("Total Raiders"); + m_display_order.emplace_back("Wins"); + m_display_order.emplace_back("Losses"); + m_display_order.emplace_back("Banned", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_raids; + std::atomic& m_empty; + std::atomic& m_full; + std::atomic& m_raiders; + std::atomic& m_wins; + std::atomic& m_losses; + std::atomic& m_banned; + std::atomic& m_errors; +}; +std::unique_ptr AutoHost_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +AutoHost::AutoHost() + : SingleSwitchProgramInstance({"Notifs", "LiveHost"}) + , MODE( + "Hosting Mode:", + { + {HostingMode::LOCAL, "local", "Host Locally"}, + {HostingMode::ONLINE_CODED, "online-coded", "Host Online (link code)"}, + {HostingMode::ONLINE_EVERYONE, "online-everyone", "Host Online (everyone)"}, + }, + LockMode::UNLOCK_WHILE_RUNNING, + HostingMode::ONLINE_CODED + ) + , NOTIFICATIONS0({ + &NOTIFICATION_RAID_POST, + &NOTIFICATION_RAID_START, + &NOTIFICATION_JOIN_REPORT, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(MODE); + + // General Auto-Hosting Options + PA_ADD_OPTION(LOBBY_WAIT_DELAY); + PA_ADD_OPTION(START_RAID_PLAYERS); + PA_ADD_OPTION(SHOW_RAID_CODE); + PA_ADD_OPTION(DESCRIPTION); + PA_ADD_OPTION(REMOTE_KILL_SWITCH0); + PA_ADD_OPTION(CONSECUTIVE_FAILURE_PAUSE); + PA_ADD_OPTION(FAILURE_PAUSE_MINUTES); + + PA_ADD_OPTION(ROLLOVER_PREVENTION); + PA_ADD_OPTION(BATTLE_AI); + + // Extended Auto-Hosting Options + PA_ADD_OPTION(BAN_LIST); + PA_ADD_OPTION(JOIN_REPORT); + + PA_ADD_OPTION(NOTIFICATIONS0); +} + + + +WallClock AutoHost::wait_for_lobby_open( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + std::string& lobby_code +){ + VideoOverlaySet overlays(env.console.overlay()); + + TeraLobbyWatcher lobby(env.logger(), env.normal_inference_dispatcher(), COLOR_RED); + lobby.make_overlays(overlays); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(60), + {{lobby, std::chrono::milliseconds(500)}} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to detect Tera lobby after 60 seconds.", + env.console + ); + } + WallClock start_time = current_time(); + context.wait_for(std::chrono::seconds(1)); + + VideoSnapshot snapshot = env.console.video().snapshot(); + lobby_code = lobby.raid_code(env.logger(), env.normal_inference_dispatcher(), snapshot); + std::string code = lobby.raid_code(env.logger(), env.normal_inference_dispatcher(), snapshot); + normalize_code(lobby_code, code); + + send_host_announcement( + env, env.console, + lobby_code, + SHOW_RAID_CODE, + DESCRIPTION, + NOTIFICATION_RAID_POST + ); + + return start_time; +} +void AutoHost::update_stats_on_raid_start(SingleSwitchProgramEnvironment& env, uint8_t player_count){ + AutoHost_Descriptor::Stats& stats = env.current_stats(); + + player_count = std::max(player_count, 1); + + if (player_count == 4){ + stats.m_full++; + } + if (player_count == 1){ + stats.m_empty++; + } + stats.m_raiders += player_count - 1; +} +bool AutoHost::start_raid( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + WallClock start_time, + uint8_t player_count +){ + AutoHost_Descriptor::Stats& stats = env.current_stats(); + + // This is the state machine to actually start the raid. + + while (true){ + AdvanceDialogWatcher dialog(COLOR_YELLOW); + WhiteScreenOverWatcher start_raid(COLOR_BLUE); + TeraBattleMenuWatcher battle_menu(COLOR_CYAN); + context.wait_for_all_requests(); + int ret = run_until( + env.console, context, + [start_time](ProControllerContext& context){ + while (true){ + pbf_press_button(context, BUTTON_A, 20, 105); + context.wait_for_all_requests(); + if (current_time() > start_time + std::chrono::minutes(4)){ + return; + } + } + }, + {dialog, start_raid, battle_menu} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + env.log("Raid timed out!", COLOR_ORANGE); + stats.m_empty++; + return false; + case 1: + env.log("Raid started! (white screen)", COLOR_BLUE); + update_stats_on_raid_start(env, player_count); + return true; + case 2: + env.log("Raid started! (battle menu)", COLOR_BLUE); + update_stats_on_raid_start(env, player_count); + return true; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Stuck in lobby for 4 minutes.", + env.console + ); + } + } +} + + +bool AutoHost::run_lobby( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + std::string& lobby_code, + std::array, 4>& player_names +){ + AutoHost_Descriptor::Stats& stats = env.current_stats(); + + WallClock start_time = wait_for_lobby_open(env, context, lobby_code); + + TeraLobbyWaiter waiter( + env, env.console, context, + 1, + lobby_code, start_time, + LOBBY_WAIT_DELAY, + START_RAID_PLAYERS, + NOTIFICATION_RAID_START, + BAN_LIST, + JOIN_REPORT + ); + + TeraLobbyWaiter::LobbyResult result = waiter.run_lobby(); + player_names = waiter.names(); + + if (result == TeraLobbyWaiter::LobbyResult::BANNED_PLAYER){ + stats.m_banned++; + } + if (result != TeraLobbyWaiter::LobbyResult::RAID_STARTED){ + return false; + } + + return start_raid(env, context, start_time, waiter.last_known_players()); +} + +void AutoHost::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + AutoHost_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 10); + + m_killswitch_time = WallClock::max(); + + std::string report_name = "PokemonSV-AutoHost-JoinReport-" + now_to_filestring() + ".txt"; + MultiLanguageJoinTracker join_tracker(1); + + TeraFailTracker fail_tracker( + env, context, + NOTIFICATION_ERROR_RECOVERABLE, + CONSECUTIVE_FAILURE_PAUSE, + FAILURE_PAUSE_MINUTES + ); + KillSwitchTracker kill_switch(env); + + bool skip_reset = true; + WallClock last_time_fix = WallClock::min(); + while (true){ + env.update_stats(); + + fail_tracker.on_raid_start(); + + if (!skip_reset){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + if (ROLLOVER_PREVENTION){ + WallClock now = current_time(); + if (last_time_fix == WallClock::min() || now - last_time_fix > std::chrono::hours(4)){ + set_time_to_12am_from_home(env.program_info(), env.console, context); + last_time_fix = now; + } + } + reset_game_from_home(env.program_info(), env.console, context, 5 * TICKS_PER_SECOND); + } + skip_reset = false; + + // Check kill-switch now before we go online. + if (MODE != HostingMode::LOCAL){ + kill_switch.check_kill_switch(REMOTE_KILL_SWITCH0); + } + + // Store the mode locally in case the user changes in the middle of + // this iteration. + HostingMode mode = MODE; + + if (mode != HostingMode::LOCAL){ + // Connect to internet. + try{ + connect_to_internet_from_overworld(env.program_info(), env.console, context); + }catch (OperationFailedException& e){ + stats.m_errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + fail_tracker.report_raid_error(); + continue; + } + } + + if (!open_raid(env.console, context)){ + env.log("No Tera raid found.", COLOR_RED); + fail_tracker.report_raid_error(); + continue; + } + env.log("Tera raid found!", COLOR_BLUE); + + context.wait_for(std::chrono::milliseconds(100)); + + BAN_LIST.refresh_online_table(env.logger()); + + try{ + open_hosting_lobby(env, env.console, context, mode); + }catch (OperationFailedException& e){ + stats.m_errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + fail_tracker.report_raid_error(); + continue; + } + + try{ + std::string lobby_code; + std::array, 4> player_names; + + if (!run_lobby(env, context, lobby_code, player_names)){ + continue; + } + env.update_stats(); + + stats.m_raids++; + bool win = run_tera_battle(env, env.console, context, BATTLE_AI); + env.update_stats(); + if (win){ + stats.m_wins++; + }else{ + stats.m_losses++; + } + if (JOIN_REPORT.enabled() && (win || !JOIN_REPORT.wins_only)){ + join_tracker.append(player_names, lobby_code); + join_tracker.dump(report_name); + send_program_notification_with_file( + env, + NOTIFICATION_JOIN_REPORT, + Color(0), + "Join Report", + {}, "", + report_name + ); + } + if (win){ + exit_tera_win_without_catching(env.program_info(), env.console, context, 0); + } + fail_tracker.report_successful_raid(); + }catch (OperationFailedException& e){ + stats.m_errors++; + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + fail_tracker.report_raid_error(); + continue; + } + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.h index f88193bea2..8d9ef88a78 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHost.h @@ -1,94 +1,94 @@ -/* Auto Host - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoHost_H -#define PokemonAutomation_PokemonSV_AutoHost_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSV/Options/PokemonSV_PlayerList.h" -#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" -#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV_JoinTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class AutoHost_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoHost_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class AutoHost : public SingleSwitchProgramInstance{ -public: - AutoHost(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - WallClock wait_for_lobby_open( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - std::string& lobby_code - ); - void update_stats_on_raid_start(SingleSwitchProgramEnvironment& env, uint8_t player_count); - bool start_raid( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - WallClock start_time, - uint8_t player_count - ); - bool run_lobby( - SingleSwitchProgramEnvironment& env, ProControllerContext& context, - std::string& lobby_code, - std::array, 4>& player_names - ); - void check_kill_switch(ProgramEnvironment& env); - -private: -// OCR::LanguageOCR LANGUAGE; - - EnumDropdownOption MODE; - - LobbyWaitDelay LOBBY_WAIT_DELAY; - StartRaidPlayers START_RAID_PLAYERS; - ShowRaidCode SHOW_RAID_CODE; - AutoHostDescription DESCRIPTION; - RemoteKillSwitch REMOTE_KILL_SWITCH0; - ConsecutiveFailurePause CONSECUTIVE_FAILURE_PAUSE; - FailurePauseMinutes FAILURE_PAUSE_MINUTES; - - RolloverPrevention ROLLOVER_PREVENTION; - TeraAIOption BATTLE_AI; - - RaidPlayerBanList BAN_LIST; - RaidJoinReportOption JOIN_REPORT; - - RaidPostNotification NOTIFICATION_RAID_POST; - RaidStartNotification NOTIFICATION_RAID_START; - JoinReportNotification NOTIFICATION_JOIN_REPORT; - EventNotificationsOption NOTIFICATIONS0; - - WallClock m_killswitch_time; - std::string m_killswitch_reason; -}; - - - - -} -} -} -#endif +/* Auto Host + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoHost_H +#define PokemonAutomation_PokemonSV_AutoHost_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSV/Options/PokemonSV_PlayerList.h" +#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" +#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV_JoinTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class AutoHost_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoHost_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class AutoHost : public SingleSwitchProgramInstance{ +public: + AutoHost(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + WallClock wait_for_lobby_open( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + std::string& lobby_code + ); + void update_stats_on_raid_start(SingleSwitchProgramEnvironment& env, uint8_t player_count); + bool start_raid( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + WallClock start_time, + uint8_t player_count + ); + bool run_lobby( + SingleSwitchProgramEnvironment& env, ProControllerContext& context, + std::string& lobby_code, + std::array, 4>& player_names + ); + void check_kill_switch(ProgramEnvironment& env); + +private: +// OCR::LanguageOCR LANGUAGE; + + EnumDropdownOption MODE; + + LobbyWaitDelay LOBBY_WAIT_DELAY; + StartRaidPlayers START_RAID_PLAYERS; + ShowRaidCode SHOW_RAID_CODE; + AutoHostDescription DESCRIPTION; + RemoteKillSwitch REMOTE_KILL_SWITCH0; + ConsecutiveFailurePause CONSECUTIVE_FAILURE_PAUSE; + FailurePauseMinutes FAILURE_PAUSE_MINUTES; + + RolloverPrevention ROLLOVER_PREVENTION; + TeraAIOption BATTLE_AI; + + RaidPlayerBanList BAN_LIST; + RaidJoinReportOption JOIN_REPORT; + + RaidPostNotification NOTIFICATION_RAID_POST; + RaidStartNotification NOTIFICATION_RAID_START; + JoinReportNotification NOTIFICATION_JOIN_REPORT; + EventNotificationsOption NOTIFICATIONS0; + + WallClock m_killswitch_time; + std::string m_killswitch_reason; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp index cfe7b93219..4ff726a7bb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.cpp @@ -1,379 +1,379 @@ -/* Auto Host Lobby Waiter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/OCR/OCR_StringNormalization.h" -#include "CommonTools/Async/InferenceSession.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV_AutoHostLobbyWaiter.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -TeraLobbyWaiter::TeraLobbyWaiter( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - uint8_t host_players, - const std::string& lobby_code, WallClock start_time, - SimpleIntegerOption& LOBBY_WAIT_DELAY, - IntegerEnumDropdownOption& START_RAID_PLAYERS, - EventNotificationOption& NOTIFICATION_RAID_START, - RaidPlayerBanList& BAN_LIST, - RaidJoinReportOption& JOIN_REPORT -) - : m_env(env) - , m_stream(stream), m_context(context) - , m_host_players(host_players) - , m_lobby_code(lobby_code), m_start_time(start_time) - , m_lobby_wait_delay(LOBBY_WAIT_DELAY) - , m_start_raid_players(START_RAID_PLAYERS) - , m_notification_raid_start(NOTIFICATION_RAID_START) - , m_dialog(COLOR_YELLOW) - , m_start_raid(COLOR_BLUE) - , m_join_watcher(stream.logger(), env.normal_inference_dispatcher(), COLOR_RED, host_players) - , m_name_watcher(stream.logger(), env.normal_inference_dispatcher(), COLOR_RED, JOIN_REPORT, BAN_LIST, host_players) -{} - -VideoSnapshot TeraLobbyWaiter::synchronize_state(){ - VideoSnapshot snapshot = m_stream.video().snapshot(); - m_join_watcher.process_frame(snapshot, snapshot.timestamp); - m_name_watcher.process_frame(snapshot, snapshot.timestamp); - m_total_players = m_join_watcher.last_known_total_players(); -// m_ready_players = m_join_watcher.last_known_ready_players(); - m_ready_joiners = m_join_watcher.last_known_ready_joiners(); - m_name_watcher.get_last_known_state(m_names, m_bans); - return snapshot; -} - - -std::string TeraLobbyWaiter::check_hat_trick(){ - // Hat trick requires only one host and a fully lobby. - if (m_host_players != 1 || m_total_players != 4){ - return ""; - } - - // All 3 joiners must OCR to the same name in English and be at least - // 4 characters long. (to filter out false positives in other languages) - auto iter1 = m_names[1].find(Language::English); - if (iter1 == m_names[1].end()) return ""; - auto iter2 = m_names[2].find(Language::English); - if (iter2 == m_names[2].end()) return ""; - auto iter3 = m_names[3].find(Language::English); - if (iter3 == m_names[3].end()) return ""; - std::u32string name1 = OCR::normalize_utf32(iter1->second); - if (name1.size() < 4) return ""; - std::u32string name2 = OCR::normalize_utf32(iter2->second); - if (name2.size() < 4) return ""; - std::u32string name3 = OCR::normalize_utf32(iter3->second); - if (name3.size() < 4) return ""; - if (name1 != name2 || name1 != name3){ - return ""; - } - return iter1->second; -} -bool TeraLobbyWaiter::check_bans(bool skip_grace_period){ - if (m_bans.empty()){ - m_ban_timer = WallClock::max(); - return false; - } - if (skip_grace_period){ - return true; - } - -// // Enough people have joined. -// if (m_total_players >= 4){ -// return true; -// } - - // Names are different. - std::set normalized_names; - for (size_t c = m_host_players; c < 4; c++){ - auto iter = m_names[c].find(Language::English); - if (iter == m_names[c].end()){ - continue; - } - normalized_names.insert(OCR::normalize_utf32(iter->second)); - } - if (normalized_names.size() > 1){ - return true; - } - - // First detected banned user. - if (m_ban_timer == WallClock::max()){ - m_ban_timer = current_time(); -// cout << "Start ban timer." << endl; - return false; - } - - // Haven't waited long enough yet. - if (current_time() - m_ban_timer < std::chrono::seconds(10)){ -// cout << "Ban grace period." << endl; - return false; - } - -// cout << "Ban passed." << endl; - - return true; -} - -bool TeraLobbyWaiter::check_start_timeout(){ - uint16_t start_delay = m_lobby_wait_delay; - if (current_time() < m_start_time + std::chrono::seconds(start_delay)){ - return false; - } - if (m_host_players + m_ready_joiners < m_total_players){ - return false; - } - return true; -} -bool TeraLobbyWaiter::check_enough_players(){ - if (m_total_players < (uint8_t)m_start_raid_players.current_value()){ - return false; - } - if (m_host_players + m_ready_joiners < m_total_players){ - return false; - } - return true; -} - - -bool TeraLobbyWaiter::process_hat_trick(const ImageViewRGB32& snapshot){ - std::string name = check_hat_trick(); - if (name.empty()){ - return false; - } - m_stream.log(name + " with the Hat Trick!", COLOR_BLUE); - send_program_notification( - m_env, m_notification_raid_start, - COLOR_PURPLE, - "\U0001FA84\U0001F3A9\u2728 " + name + " with the Hat Trick! \u2728\U0001F3A9\U0001FA84", - {{ - "Start Reason:", - "\U0001FA84\U0001F3A9\u2728 " + name + " Hat Trick! \u2728\U0001F3A9\U0001FA84" - }}, "", - snapshot - ); - return true; -} -bool TeraLobbyWaiter::process_bans(const ImageViewRGB32& snapshot, bool skip_grace_period){ - if (!check_bans(skip_grace_period)){ - return false; - } - - m_env.log("Detected banned user!", COLOR_RED); - std::string message; - for (const TeraLobbyNameMatchResult& user : m_bans){ - m_env.log("Banned User: " + user.to_str(), COLOR_RED); - message += user.to_str(); - message += "\n"; - if (user.notes.empty()){ - message += user.banlist_source + "(no reason provided)"; - }else{ - message += user.banlist_source + user.notes; - } - message += "\n"; - } - send_program_notification( - m_env, m_notification_raid_start, - COLOR_RED, - m_lobby_code.empty() - ? "Raid Cancelled Due to Banned User" - : "Raid (" + m_lobby_code + ") Cancelled Due to Banned User", - {{"Banned User(s):", std::move(message)}}, "", - snapshot - ); - pbf_press_button(m_context, BUTTON_B, 20, 230); - pbf_press_button(m_context, BUTTON_A, 20, 230); - - return true; -} -bool TeraLobbyWaiter::process_start_timeout(const ImageViewRGB32& snapshot){ - uint16_t start_delay = m_lobby_wait_delay; - if (current_time() < m_start_time + std::chrono::seconds(start_delay)){ - return false; - } - if (m_host_players + m_ready_joiners < m_total_players){ - return false; - } - - send_program_notification( - m_env, m_notification_raid_start, - COLOR_GREEN, - m_lobby_code.empty() - ? "Tera Raid is Starting!" - : "Tera Raid (" + m_lobby_code + ") is Starting!", - {{ - "Start Reason:", - "Waited more than " + std::to_string(start_delay) + " seconds." - }}, "", - snapshot - ); - return true; -} -bool TeraLobbyWaiter::process_enough_players(const ImageViewRGB32& snapshot){ - uint8_t start_raid_players = (uint8_t)m_start_raid_players.current_value(); - if (m_total_players < start_raid_players){ - return false; - } - if (m_host_players + m_ready_joiners < m_total_players){ - return false; - } - - m_stream.log("Enough players are ready, attempting to start raid!", COLOR_BLUE); - send_program_notification( - m_env, m_notification_raid_start, - COLOR_GREEN, - m_lobby_code.empty() - ? "Tera Raid is Starting!" - : "Tera Raid (" + m_lobby_code + ") is Starting!", - {{ - "Start Reason:", - "Lobby has reached " + std::to_string(m_total_players) + " players." - }}, "", - snapshot - ); - return true; -} - - -TeraLobbyWaiter::LobbyResult TeraLobbyWaiter::run_lobby(){ - CancellableHolder subcontext(static_cast(m_context)); - InferenceSession session( - subcontext, m_stream, - { - m_dialog, - m_start_raid, - {m_join_watcher, std::chrono::seconds(1)}, // Both of these involve OCR. - {m_name_watcher, std::chrono::seconds(1)} // Let's not spam them at the full frame rate. - } - ); - - WallClock end_time = m_start_time + std::chrono::seconds(170); - int ret = -1; - while (true){ - try{ - subcontext.wait_for(std::chrono::milliseconds(100)); - }catch (OperationCancelledException&){ - ret = session.triggered_index(); - break; - } - - // Read sensors. - m_total_players = m_join_watcher.last_known_total_players(); -// m_ready_players = m_join_watcher.last_known_ready_players(); - m_ready_joiners = m_join_watcher.last_known_ready_joiners(); - m_name_watcher.get_last_known_state(m_names, m_bans); - -// cout << "total = " << (int)m_total_players << ", ready = " << (int)m_ready_players << endl; - - // No events have fired. Keep looping. - if (check_hat_trick().empty() && - !check_bans(false) && - !check_start_timeout() && - !check_enough_players() && - !(end_time < current_time()) - ){ - continue; - } - - // Synchronize the state. - VideoSnapshot snapshot = synchronize_state(); - - // Now we check again with everything fully updated. - - // Hat trick. - if (process_hat_trick(snapshot)){ - return LobbyResult::RAID_STARTED; - } - - // Check bans. - if (process_bans(snapshot, true)){ - return LobbyResult::BANNED_PLAYER; - } - - // Waited long enough. Start raid if everyone is ready. - if (process_start_timeout(snapshot)){ - return LobbyResult::RAID_STARTED; - } - - // Enough players in and all are ready. - if (process_enough_players(snapshot)){ - return LobbyResult::RAID_STARTED; - } - - // Almost out of time. - if (end_time < snapshot.timestamp){ - m_stream.log("Clock running down, attempting to start raid!", COLOR_BLUE); - send_program_notification( - m_env, m_notification_raid_start, - COLOR_GREEN, - m_lobby_code.empty() - ? "Tera Raid is Starting!" - : "Tera Raid (" + m_lobby_code + ") is Starting!", - {{ - "Start Reason:", - "Clock is running out!" - }}, "", - snapshot - ); - return LobbyResult::RAID_STARTED; - } - - // Otherwise, resume looping. - } - - VideoSnapshot snapshot = m_stream.video().snapshot(); - if (ret == 0){ - m_env.log("Raid timed out!", COLOR_ORANGE); - send_program_notification( - m_env, m_notification_raid_start, - COLOR_ORANGE, - m_lobby_code.empty() - ? "Tera Raid timed out with no joiners." - : "Tera Raid (" + m_lobby_code + ") timed out with no joiners.", - {}, "", - snapshot - ); - return LobbyResult::RAID_FAILED; - } - - if (ret == 1){ - m_env.log("Raid unexpectedly started!", COLOR_ORANGE); - send_program_notification( - m_env, m_notification_raid_start, - COLOR_ORANGE, - m_lobby_code.empty() - ? "Tera Raid unexpectedly started!" - : "Tera Raid (" + m_lobby_code + ") unexpectedly started!", - {}, "", - snapshot - ); - return LobbyResult::RAID_STARTED; - } - - throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Invalid session return code."); -} - - - - - - - - - - - -} -} -} +/* Auto Host Lobby Waiter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/OCR/OCR_StringNormalization.h" +#include "CommonTools/Async/InferenceSession.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV_AutoHostLobbyWaiter.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +TeraLobbyWaiter::TeraLobbyWaiter( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + uint8_t host_players, + const std::string& lobby_code, WallClock start_time, + SimpleIntegerOption& LOBBY_WAIT_DELAY, + IntegerEnumDropdownOption& START_RAID_PLAYERS, + EventNotificationOption& NOTIFICATION_RAID_START, + RaidPlayerBanList& BAN_LIST, + RaidJoinReportOption& JOIN_REPORT +) + : m_env(env) + , m_stream(stream), m_context(context) + , m_host_players(host_players) + , m_lobby_code(lobby_code), m_start_time(start_time) + , m_lobby_wait_delay(LOBBY_WAIT_DELAY) + , m_start_raid_players(START_RAID_PLAYERS) + , m_notification_raid_start(NOTIFICATION_RAID_START) + , m_dialog(COLOR_YELLOW) + , m_start_raid(COLOR_BLUE) + , m_join_watcher(stream.logger(), env.normal_inference_dispatcher(), COLOR_RED, host_players) + , m_name_watcher(stream.logger(), env.normal_inference_dispatcher(), COLOR_RED, JOIN_REPORT, BAN_LIST, host_players) +{} + +VideoSnapshot TeraLobbyWaiter::synchronize_state(){ + VideoSnapshot snapshot = m_stream.video().snapshot(); + m_join_watcher.process_frame(snapshot, snapshot.timestamp); + m_name_watcher.process_frame(snapshot, snapshot.timestamp); + m_total_players = m_join_watcher.last_known_total_players(); +// m_ready_players = m_join_watcher.last_known_ready_players(); + m_ready_joiners = m_join_watcher.last_known_ready_joiners(); + m_name_watcher.get_last_known_state(m_names, m_bans); + return snapshot; +} + + +std::string TeraLobbyWaiter::check_hat_trick(){ + // Hat trick requires only one host and a fully lobby. + if (m_host_players != 1 || m_total_players != 4){ + return ""; + } + + // All 3 joiners must OCR to the same name in English and be at least + // 4 characters long. (to filter out false positives in other languages) + auto iter1 = m_names[1].find(Language::English); + if (iter1 == m_names[1].end()) return ""; + auto iter2 = m_names[2].find(Language::English); + if (iter2 == m_names[2].end()) return ""; + auto iter3 = m_names[3].find(Language::English); + if (iter3 == m_names[3].end()) return ""; + std::u32string name1 = OCR::normalize_utf32(iter1->second); + if (name1.size() < 4) return ""; + std::u32string name2 = OCR::normalize_utf32(iter2->second); + if (name2.size() < 4) return ""; + std::u32string name3 = OCR::normalize_utf32(iter3->second); + if (name3.size() < 4) return ""; + if (name1 != name2 || name1 != name3){ + return ""; + } + return iter1->second; +} +bool TeraLobbyWaiter::check_bans(bool skip_grace_period){ + if (m_bans.empty()){ + m_ban_timer = WallClock::max(); + return false; + } + if (skip_grace_period){ + return true; + } + +// // Enough people have joined. +// if (m_total_players >= 4){ +// return true; +// } + + // Names are different. + std::set normalized_names; + for (size_t c = m_host_players; c < 4; c++){ + auto iter = m_names[c].find(Language::English); + if (iter == m_names[c].end()){ + continue; + } + normalized_names.insert(OCR::normalize_utf32(iter->second)); + } + if (normalized_names.size() > 1){ + return true; + } + + // First detected banned user. + if (m_ban_timer == WallClock::max()){ + m_ban_timer = current_time(); +// cout << "Start ban timer." << endl; + return false; + } + + // Haven't waited long enough yet. + if (current_time() - m_ban_timer < std::chrono::seconds(10)){ +// cout << "Ban grace period." << endl; + return false; + } + +// cout << "Ban passed." << endl; + + return true; +} + +bool TeraLobbyWaiter::check_start_timeout(){ + uint16_t start_delay = m_lobby_wait_delay; + if (current_time() < m_start_time + std::chrono::seconds(start_delay)){ + return false; + } + if (m_host_players + m_ready_joiners < m_total_players){ + return false; + } + return true; +} +bool TeraLobbyWaiter::check_enough_players(){ + if (m_total_players < (uint8_t)m_start_raid_players.current_value()){ + return false; + } + if (m_host_players + m_ready_joiners < m_total_players){ + return false; + } + return true; +} + + +bool TeraLobbyWaiter::process_hat_trick(const ImageViewRGB32& snapshot){ + std::string name = check_hat_trick(); + if (name.empty()){ + return false; + } + m_stream.log(name + " with the Hat Trick!", COLOR_BLUE); + send_program_notification( + m_env, m_notification_raid_start, + COLOR_PURPLE, + "\U0001FA84\U0001F3A9\u2728 " + name + " with the Hat Trick! \u2728\U0001F3A9\U0001FA84", + {{ + "Start Reason:", + "\U0001FA84\U0001F3A9\u2728 " + name + " Hat Trick! \u2728\U0001F3A9\U0001FA84" + }}, "", + snapshot + ); + return true; +} +bool TeraLobbyWaiter::process_bans(const ImageViewRGB32& snapshot, bool skip_grace_period){ + if (!check_bans(skip_grace_period)){ + return false; + } + + m_env.log("Detected banned user!", COLOR_RED); + std::string message; + for (const TeraLobbyNameMatchResult& user : m_bans){ + m_env.log("Banned User: " + user.to_str(), COLOR_RED); + message += user.to_str(); + message += "\n"; + if (user.notes.empty()){ + message += user.banlist_source + "(no reason provided)"; + }else{ + message += user.banlist_source + user.notes; + } + message += "\n"; + } + send_program_notification( + m_env, m_notification_raid_start, + COLOR_RED, + m_lobby_code.empty() + ? "Raid Cancelled Due to Banned User" + : "Raid (" + m_lobby_code + ") Cancelled Due to Banned User", + {{"Banned User(s):", std::move(message)}}, "", + snapshot + ); + pbf_press_button(m_context, BUTTON_B, 20, 230); + pbf_press_button(m_context, BUTTON_A, 20, 230); + + return true; +} +bool TeraLobbyWaiter::process_start_timeout(const ImageViewRGB32& snapshot){ + uint16_t start_delay = m_lobby_wait_delay; + if (current_time() < m_start_time + std::chrono::seconds(start_delay)){ + return false; + } + if (m_host_players + m_ready_joiners < m_total_players){ + return false; + } + + send_program_notification( + m_env, m_notification_raid_start, + COLOR_GREEN, + m_lobby_code.empty() + ? "Tera Raid is Starting!" + : "Tera Raid (" + m_lobby_code + ") is Starting!", + {{ + "Start Reason:", + "Waited more than " + std::to_string(start_delay) + " seconds." + }}, "", + snapshot + ); + return true; +} +bool TeraLobbyWaiter::process_enough_players(const ImageViewRGB32& snapshot){ + uint8_t start_raid_players = (uint8_t)m_start_raid_players.current_value(); + if (m_total_players < start_raid_players){ + return false; + } + if (m_host_players + m_ready_joiners < m_total_players){ + return false; + } + + m_stream.log("Enough players are ready, attempting to start raid!", COLOR_BLUE); + send_program_notification( + m_env, m_notification_raid_start, + COLOR_GREEN, + m_lobby_code.empty() + ? "Tera Raid is Starting!" + : "Tera Raid (" + m_lobby_code + ") is Starting!", + {{ + "Start Reason:", + "Lobby has reached " + std::to_string(m_total_players) + " players." + }}, "", + snapshot + ); + return true; +} + + +TeraLobbyWaiter::LobbyResult TeraLobbyWaiter::run_lobby(){ + CancellableHolder subcontext(static_cast(m_context)); + InferenceSession session( + subcontext, m_stream, + { + m_dialog, + m_start_raid, + {m_join_watcher, std::chrono::seconds(1)}, // Both of these involve OCR. + {m_name_watcher, std::chrono::seconds(1)} // Let's not spam them at the full frame rate. + } + ); + + WallClock end_time = m_start_time + std::chrono::seconds(170); + int ret = -1; + while (true){ + try{ + subcontext.wait_for(std::chrono::milliseconds(100)); + }catch (OperationCancelledException&){ + ret = session.triggered_index(); + break; + } + + // Read sensors. + m_total_players = m_join_watcher.last_known_total_players(); +// m_ready_players = m_join_watcher.last_known_ready_players(); + m_ready_joiners = m_join_watcher.last_known_ready_joiners(); + m_name_watcher.get_last_known_state(m_names, m_bans); + +// cout << "total = " << (int)m_total_players << ", ready = " << (int)m_ready_players << endl; + + // No events have fired. Keep looping. + if (check_hat_trick().empty() && + !check_bans(false) && + !check_start_timeout() && + !check_enough_players() && + !(end_time < current_time()) + ){ + continue; + } + + // Synchronize the state. + VideoSnapshot snapshot = synchronize_state(); + + // Now we check again with everything fully updated. + + // Hat trick. + if (process_hat_trick(snapshot)){ + return LobbyResult::RAID_STARTED; + } + + // Check bans. + if (process_bans(snapshot, true)){ + return LobbyResult::BANNED_PLAYER; + } + + // Waited long enough. Start raid if everyone is ready. + if (process_start_timeout(snapshot)){ + return LobbyResult::RAID_STARTED; + } + + // Enough players in and all are ready. + if (process_enough_players(snapshot)){ + return LobbyResult::RAID_STARTED; + } + + // Almost out of time. + if (end_time < snapshot.timestamp){ + m_stream.log("Clock running down, attempting to start raid!", COLOR_BLUE); + send_program_notification( + m_env, m_notification_raid_start, + COLOR_GREEN, + m_lobby_code.empty() + ? "Tera Raid is Starting!" + : "Tera Raid (" + m_lobby_code + ") is Starting!", + {{ + "Start Reason:", + "Clock is running out!" + }}, "", + snapshot + ); + return LobbyResult::RAID_STARTED; + } + + // Otherwise, resume looping. + } + + VideoSnapshot snapshot = m_stream.video().snapshot(); + if (ret == 0){ + m_env.log("Raid timed out!", COLOR_ORANGE); + send_program_notification( + m_env, m_notification_raid_start, + COLOR_ORANGE, + m_lobby_code.empty() + ? "Tera Raid timed out with no joiners." + : "Tera Raid (" + m_lobby_code + ") timed out with no joiners.", + {}, "", + snapshot + ); + return LobbyResult::RAID_FAILED; + } + + if (ret == 1){ + m_env.log("Raid unexpectedly started!", COLOR_ORANGE); + send_program_notification( + m_env, m_notification_raid_start, + COLOR_ORANGE, + m_lobby_code.empty() + ? "Tera Raid unexpectedly started!" + : "Tera Raid (" + m_lobby_code + ") unexpectedly started!", + {}, "", + snapshot + ); + return LobbyResult::RAID_STARTED; + } + + throw InternalProgramError(&m_stream.logger(), PA_CURRENT_FUNCTION, "Invalid session return code."); +} + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.h index 4aebd562af..e2a8bf3fe1 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostLobbyWaiter.h @@ -1,107 +1,107 @@ -/* Auto Host Lobby Waiter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoHosLobbyWaiter_H -#define PokemonAutomation_PokemonSV_AutoHosLobbyWaiter_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Options/PokemonSV_PlayerList.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV_JoinTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class TeraLobbyWaiter{ -public: - TeraLobbyWaiter( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - uint8_t host_players, - const std::string& lobby_code, WallClock start_time, - SimpleIntegerOption& LOBBY_WAIT_DELAY, - IntegerEnumDropdownOption& START_RAID_PLAYERS, - EventNotificationOption& NOTIFICATION_RAID_START, - RaidPlayerBanList& BAN_LIST, - RaidJoinReportOption& JOIN_REPORT - ); - - uint8_t last_known_players(){ - return m_total_players; - } - const std::array, 4>& names(){ - return m_names; - } - - enum class LobbyResult{ - RAID_STARTED, - RAID_FAILED, - BANNED_PLAYER, - }; - LobbyResult run_lobby(); - - -private: - VideoSnapshot synchronize_state(); - - std::string check_hat_trick(); - bool check_bans(bool skip_grace_period); - bool check_start_timeout(); - bool check_enough_players(); - - - bool process_hat_trick(const ImageViewRGB32& snapshot); - bool process_bans(const ImageViewRGB32& snapshot, bool skip_grace_period); - bool process_start_timeout(const ImageViewRGB32& snapshot); - bool process_enough_players(const ImageViewRGB32& snapshot); - - - -private: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ProControllerContext& m_context; - uint8_t m_host_players; - - const std::string& m_lobby_code; - WallClock m_start_time; - - SimpleIntegerOption& m_lobby_wait_delay; - IntegerEnumDropdownOption& m_start_raid_players; - EventNotificationOption& m_notification_raid_start; - - // Sensors - AdvanceDialogWatcher m_dialog; - WhiteScreenOverWatcher m_start_raid; - TeraLobbyJoinWatcher2 m_join_watcher; - TeraLobbyNameWatcher m_name_watcher; - - // Last known state - uint8_t m_total_players = 1; -// uint8_t m_ready_players = 0; - uint8_t m_ready_joiners = 0; - std::array, 4> m_names; - std::vector m_bans; - WallClock m_ban_timer = WallClock::max(); -}; - - - - -} -} -} -#endif +/* Auto Host Lobby Waiter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoHosLobbyWaiter_H +#define PokemonAutomation_PokemonSV_AutoHosLobbyWaiter_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Options/PokemonSV_PlayerList.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV_JoinTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class TeraLobbyWaiter{ +public: + TeraLobbyWaiter( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + uint8_t host_players, + const std::string& lobby_code, WallClock start_time, + SimpleIntegerOption& LOBBY_WAIT_DELAY, + IntegerEnumDropdownOption& START_RAID_PLAYERS, + EventNotificationOption& NOTIFICATION_RAID_START, + RaidPlayerBanList& BAN_LIST, + RaidJoinReportOption& JOIN_REPORT + ); + + uint8_t last_known_players(){ + return m_total_players; + } + const std::array, 4>& names(){ + return m_names; + } + + enum class LobbyResult{ + RAID_STARTED, + RAID_FAILED, + BANNED_PLAYER, + }; + LobbyResult run_lobby(); + + +private: + VideoSnapshot synchronize_state(); + + std::string check_hat_trick(); + bool check_bans(bool skip_grace_period); + bool check_start_timeout(); + bool check_enough_players(); + + + bool process_hat_trick(const ImageViewRGB32& snapshot); + bool process_bans(const ImageViewRGB32& snapshot, bool skip_grace_period); + bool process_start_timeout(const ImageViewRGB32& snapshot); + bool process_enough_players(const ImageViewRGB32& snapshot); + + + +private: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ProControllerContext& m_context; + uint8_t m_host_players; + + const std::string& m_lobby_code; + WallClock m_start_time; + + SimpleIntegerOption& m_lobby_wait_delay; + IntegerEnumDropdownOption& m_start_raid_players; + EventNotificationOption& m_notification_raid_start; + + // Sensors + AdvanceDialogWatcher m_dialog; + WhiteScreenOverWatcher m_start_raid; + TeraLobbyJoinWatcher2 m_join_watcher; + TeraLobbyNameWatcher m_name_watcher; + + // Last known state + uint8_t m_total_players = 1; +// uint8_t m_ready_players = 0; + uint8_t m_ready_joiners = 0; + std::array, 4> m_names; + std::vector m_bans; + WallClock m_ban_timer = WallClock::max(); +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.cpp index 20c1ffdc64..9ce9f1a47e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.cpp @@ -1,206 +1,206 @@ -/* Auto Host Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CancellableScope.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Common/Qt/TimeQt.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/FileDownloader.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" -#include "PokemonSV_AutoHostTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -void send_host_announcement( - ProgramEnvironment& env, VideoStream& host_console, - const std::string& lobby_code, bool show_raid_code, - const std::string& description, - EventNotificationOption& NOTIFICATION_RAID_POST -){ - std::vector> messages; - if (!description.empty()){ - messages.emplace_back("Description:", std::move(description)); - } - - VideoSnapshot snapshot = host_console.video().snapshot(); - if (show_raid_code && !lobby_code.empty()){ - messages.emplace_back("Raid Code:", lobby_code); - } - - send_program_notification( - env, NOTIFICATION_RAID_POST, - Color(0), - "Tera Raid Notification", - messages, "", - snapshot - ); -} - - - -TeraFailTracker::TeraFailTracker( - ProgramEnvironment& env, CancellableScope& scope, - EventNotificationOption& notification_error_recoverable, - ConsecutiveFailurePause& consecutive_failure_pause, - FailurePauseMinutes& failure_pause_minutes -) - : m_env(env) - , m_scope(scope) - , m_notification_error_recoverable(notification_error_recoverable) - , m_consecutive_failure_pause(consecutive_failure_pause) - , m_failure_pause_minutes(failure_pause_minutes) - , m_current_raid_error(false) -{} - -void TeraFailTracker::on_raid_start(){ - if (!m_current_raid_error.load(std::memory_order_relaxed)){ - return; - } - m_current_raid_error.store(false, std::memory_order_relaxed); - - if (m_consecutive_failures > 0 && !m_completed_one){ - throw_and_log( - m_env.logger(), - ErrorReport::NO_ERROR_REPORT, - "Failed 1st raid attempt. Will not retry due to risk of ban." - ); - } - size_t fail_threshold = m_consecutive_failure_pause; - if (m_consecutive_failures >= fail_threshold){ - uint16_t minutes = m_failure_pause_minutes; - if (minutes == 0){ - throw_and_log( - m_env.logger(), - ErrorReport::NO_ERROR_REPORT, - "Failed " + std::to_string(fail_threshold) + " raid(s) in the row. " - "Stopping to prevent possible ban." - ); - }else{ - send_program_recoverable_error_notification( - m_env, m_notification_error_recoverable, - "Failed " + std::to_string(fail_threshold) + " raid(s) in the row. " - "Pausing program for " + std::to_string(minutes) + " minute(s)." - ); - WallClock start_time = current_time(); - while (current_time() < start_time + std::chrono::minutes(m_failure_pause_minutes)){ - m_scope.wait_for(std::chrono::seconds(1)); - } - m_consecutive_failures = 0; - } - } -} -void TeraFailTracker::report_successful_raid(){ - m_completed_one = true; - m_consecutive_failures = 0; -} -void TeraFailTracker::report_raid_error(){ - bool expected = false; - if (m_current_raid_error.compare_exchange_strong(expected, true)){ - m_consecutive_failures++; - m_env.log("Consecutive Failure Count: " + std::to_string(m_consecutive_failures), COLOR_RED); - } -} - - - - -KillSwitchTracker::KillSwitchTracker(ProgramEnvironment& env) - : m_env(env) -{} -void KillSwitchTracker::check_kill_switch(const std::string& kill_switch_url){ - if (kill_switch_url.empty()){ - return; - } - - WallClock start_time = m_env.program_info().start_time; - - if (kill_switch_url.ends_with(".txt")){ - m_env.log("Loading remote kill switch time..."); - try{ - std::string kill_time_str = FileDownloader::download_file(m_env.logger(), kill_switch_url); - m_killswitch_time = parse_utc_time_str(kill_time_str); - }catch (OperationFailedException& e){ - m_env.log("Unable to load kill switch URL: " + e.message(), COLOR_RED); - }catch (ParseException& e){ - m_env.log("Unable to load kill switch URL: " + e.message(), COLOR_RED); - } - }else if (kill_switch_url.ends_with(".json")){ - m_env.log("Loading remote kill switch time..."); - - try{ - JsonValue json = FileDownloader::download_json_file(m_env.logger(), kill_switch_url); - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - throw ParseException("Invalid kill-switch Json."); - } - const std::string* date = obj->get_string("date"); - if (date == nullptr){ - m_env.log("Invalid Kill Switch Json", COLOR_RED); - }else{ - m_killswitch_time = parse_utc_time_str(*date); - } - const std::string* reason = obj->get_string("reason"); - if (date == nullptr){ - m_env.log("Invalid Kill Switch Json", COLOR_RED); - }else{ - m_killswitch_reason = *reason; - } - }catch (OperationFailedException& e){ - m_env.log("Invalid kill-switch JSON: " + e.message(), COLOR_RED); - }catch (ParseException& e){ - m_env.log("Invalid kill-switch JSON: " + e.message(), COLOR_RED); - } - }else{ - throw UserSetupError(m_env.logger(), "Invalid kill switch URL extension."); - } - - WallClock now = current_time(); - m_env.log( - "Start UTC: " + to_utc_time_str(start_time) + - ", Current UTC: " + to_utc_time_str(now) + - ", Kill UTC: " + to_utc_time_str(m_killswitch_time) - ); - if (start_time < m_killswitch_time && now > m_killswitch_time){ - if (m_killswitch_reason.empty()){ - throw_and_log( - m_env.logger(), - ErrorReport::NO_ERROR_REPORT, - "Stopped by remote kill switch. No reason specified." - ); - }else{ - throw_and_log( - m_env.logger(), - ErrorReport::NO_ERROR_REPORT, - "Stopped by remote kill switch. Reason: " + m_killswitch_reason - ); - } - } -} - - - - - - - - - - - - - -} -} -} +/* Auto Host Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CancellableScope.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Common/Qt/TimeQt.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/FileDownloader.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" +#include "PokemonSV_AutoHostTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +void send_host_announcement( + ProgramEnvironment& env, VideoStream& host_console, + const std::string& lobby_code, bool show_raid_code, + const std::string& description, + EventNotificationOption& NOTIFICATION_RAID_POST +){ + std::vector> messages; + if (!description.empty()){ + messages.emplace_back("Description:", std::move(description)); + } + + VideoSnapshot snapshot = host_console.video().snapshot(); + if (show_raid_code && !lobby_code.empty()){ + messages.emplace_back("Raid Code:", lobby_code); + } + + send_program_notification( + env, NOTIFICATION_RAID_POST, + Color(0), + "Tera Raid Notification", + messages, "", + snapshot + ); +} + + + +TeraFailTracker::TeraFailTracker( + ProgramEnvironment& env, CancellableScope& scope, + EventNotificationOption& notification_error_recoverable, + ConsecutiveFailurePause& consecutive_failure_pause, + FailurePauseMinutes& failure_pause_minutes +) + : m_env(env) + , m_scope(scope) + , m_notification_error_recoverable(notification_error_recoverable) + , m_consecutive_failure_pause(consecutive_failure_pause) + , m_failure_pause_minutes(failure_pause_minutes) + , m_current_raid_error(false) +{} + +void TeraFailTracker::on_raid_start(){ + if (!m_current_raid_error.load(std::memory_order_relaxed)){ + return; + } + m_current_raid_error.store(false, std::memory_order_relaxed); + + if (m_consecutive_failures > 0 && !m_completed_one){ + throw_and_log( + m_env.logger(), + ErrorReport::NO_ERROR_REPORT, + "Failed 1st raid attempt. Will not retry due to risk of ban." + ); + } + size_t fail_threshold = m_consecutive_failure_pause; + if (m_consecutive_failures >= fail_threshold){ + uint16_t minutes = m_failure_pause_minutes; + if (minutes == 0){ + throw_and_log( + m_env.logger(), + ErrorReport::NO_ERROR_REPORT, + "Failed " + std::to_string(fail_threshold) + " raid(s) in the row. " + "Stopping to prevent possible ban." + ); + }else{ + send_program_recoverable_error_notification( + m_env, m_notification_error_recoverable, + "Failed " + std::to_string(fail_threshold) + " raid(s) in the row. " + "Pausing program for " + std::to_string(minutes) + " minute(s)." + ); + WallClock start_time = current_time(); + while (current_time() < start_time + std::chrono::minutes(m_failure_pause_minutes)){ + m_scope.wait_for(std::chrono::seconds(1)); + } + m_consecutive_failures = 0; + } + } +} +void TeraFailTracker::report_successful_raid(){ + m_completed_one = true; + m_consecutive_failures = 0; +} +void TeraFailTracker::report_raid_error(){ + bool expected = false; + if (m_current_raid_error.compare_exchange_strong(expected, true)){ + m_consecutive_failures++; + m_env.log("Consecutive Failure Count: " + std::to_string(m_consecutive_failures), COLOR_RED); + } +} + + + + +KillSwitchTracker::KillSwitchTracker(ProgramEnvironment& env) + : m_env(env) +{} +void KillSwitchTracker::check_kill_switch(const std::string& kill_switch_url){ + if (kill_switch_url.empty()){ + return; + } + + WallClock start_time = m_env.program_info().start_time; + + if (kill_switch_url.ends_with(".txt")){ + m_env.log("Loading remote kill switch time..."); + try{ + std::string kill_time_str = FileDownloader::download_file(m_env.logger(), kill_switch_url); + m_killswitch_time = parse_utc_time_str(kill_time_str); + }catch (OperationFailedException& e){ + m_env.log("Unable to load kill switch URL: " + e.message(), COLOR_RED); + }catch (ParseException& e){ + m_env.log("Unable to load kill switch URL: " + e.message(), COLOR_RED); + } + }else if (kill_switch_url.ends_with(".json")){ + m_env.log("Loading remote kill switch time..."); + + try{ + JsonValue json = FileDownloader::download_json_file(m_env.logger(), kill_switch_url); + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + throw ParseException("Invalid kill-switch Json."); + } + const std::string* date = obj->get_string("date"); + if (date == nullptr){ + m_env.log("Invalid Kill Switch Json", COLOR_RED); + }else{ + m_killswitch_time = parse_utc_time_str(*date); + } + const std::string* reason = obj->get_string("reason"); + if (date == nullptr){ + m_env.log("Invalid Kill Switch Json", COLOR_RED); + }else{ + m_killswitch_reason = *reason; + } + }catch (OperationFailedException& e){ + m_env.log("Invalid kill-switch JSON: " + e.message(), COLOR_RED); + }catch (ParseException& e){ + m_env.log("Invalid kill-switch JSON: " + e.message(), COLOR_RED); + } + }else{ + throw UserSetupError(m_env.logger(), "Invalid kill switch URL extension."); + } + + WallClock now = current_time(); + m_env.log( + "Start UTC: " + to_utc_time_str(start_time) + + ", Current UTC: " + to_utc_time_str(now) + + ", Kill UTC: " + to_utc_time_str(m_killswitch_time) + ); + if (start_time < m_killswitch_time && now > m_killswitch_time){ + if (m_killswitch_reason.empty()){ + throw_and_log( + m_env.logger(), + ErrorReport::NO_ERROR_REPORT, + "Stopped by remote kill switch. No reason specified." + ); + }else{ + throw_and_log( + m_env.logger(), + ErrorReport::NO_ERROR_REPORT, + "Stopped by remote kill switch. Reason: " + m_killswitch_reason + ); + } + } +} + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.h index e24712d465..f20d444b90 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_AutoHostTools.h @@ -1,74 +1,74 @@ -/* Auto Host Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AutoHostTools_H -#define PokemonAutomation_PokemonSV_AutoHostTools_H - -#include -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" - -namespace PokemonAutomation{ - class CancellableScope; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -void send_host_announcement( - ProgramEnvironment& env, VideoStream& host_console, - const std::string& lobby_code, bool show_raid_code, - const std::string& description, - EventNotificationOption& NOTIFICATION_RAID_POST -); - - -class TeraFailTracker{ -public: - TeraFailTracker( - ProgramEnvironment& env, CancellableScope& scope, - EventNotificationOption& notification_error_recoverable, - ConsecutiveFailurePause& consecutive_failure_pause, - FailurePauseMinutes& failure_pause_minutes - ); - - void on_raid_start(); - void report_successful_raid(); - void report_raid_error(); - -private: - ProgramEnvironment& m_env; - CancellableScope& m_scope; - EventNotificationOption& m_notification_error_recoverable; - ConsecutiveFailurePause& m_consecutive_failure_pause; - FailurePauseMinutes& m_failure_pause_minutes; - bool m_completed_one = false; - size_t m_consecutive_failures = 0; - std::atomic m_current_raid_error; -}; - - -class KillSwitchTracker{ -public: - KillSwitchTracker(ProgramEnvironment& env); - - void check_kill_switch(const std::string& kill_switch_url); - -private: - ProgramEnvironment& m_env; - WallClock m_killswitch_time; - std::string m_killswitch_reason; -}; - - - - - -} -} -} -#endif +/* Auto Host Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AutoHostTools_H +#define PokemonAutomation_PokemonSV_AutoHostTools_H + +#include +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" + +namespace PokemonAutomation{ + class CancellableScope; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +void send_host_announcement( + ProgramEnvironment& env, VideoStream& host_console, + const std::string& lobby_code, bool show_raid_code, + const std::string& description, + EventNotificationOption& NOTIFICATION_RAID_POST +); + + +class TeraFailTracker{ +public: + TeraFailTracker( + ProgramEnvironment& env, CancellableScope& scope, + EventNotificationOption& notification_error_recoverable, + ConsecutiveFailurePause& consecutive_failure_pause, + FailurePauseMinutes& failure_pause_minutes + ); + + void on_raid_start(); + void report_successful_raid(); + void report_raid_error(); + +private: + ProgramEnvironment& m_env; + CancellableScope& m_scope; + EventNotificationOption& m_notification_error_recoverable; + ConsecutiveFailurePause& m_consecutive_failure_pause; + FailurePauseMinutes& m_failure_pause_minutes; + bool m_completed_one = false; + size_t m_consecutive_failures = 0; + std::atomic m_current_raid_error; +}; + + +class KillSwitchTracker{ +public: + KillSwitchTracker(ProgramEnvironment& env); + + void check_kill_switch(const std::string& kill_switch_url); + +private: + ProgramEnvironment& m_env; + WallClock m_killswitch_time; + std::string m_killswitch_reason; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp index 772e7d208f..6265d47a92 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.cpp @@ -1,447 +1,447 @@ -/* Join Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonTools/OCR/OCR_StringNormalization.h" -#include "CommonTools/OCR/OCR_TextMatcher.h" -#include "PokemonSV_JoinTracker.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -bool check_ban_for_name( - Logger& logger, - std::vector& matches, - const PlayerListRowSnapshot& entry, const std::string& banlist_source, - const std::string& ocr_name, - bool ignore_whitelist -){ - std::u32string normalized_ocr_name = OCR::normalize_utf32(ocr_name); - std::u32string normalized_ban_entry = OCR::normalize_utf32(entry.name); - - size_t distance = OCR::levenshtein_distance( - normalized_ocr_name, - normalized_ban_entry - ); - - if (distance >= normalized_ban_entry.size()){ - return false; - } - - double probability = OCR::random_match_probability( - normalized_ban_entry.size(), - normalized_ban_entry.size() - distance, - language_data(entry.language).random_match_chance - ); - double log10p = std::log10(probability); - - // Not a match. Return now. - if (log10p > entry.log10p && distance != 0){ - return false; - } - - - if (!ignore_whitelist){ - // Matched. Check against the whitelist. - static const std::vector WHITELIST{ - "Kuroneko", - "Kurbo", - "Gael", - "Dhruv", - "Nikki", - "Dani", - "denvoros", - "Halazea", - }; - for (const std::string& name : WHITELIST){ - std::u32string normalized_white_entry = OCR::normalize_utf32(name); - size_t w_distance = OCR::levenshtein_distance( - OCR::normalize_utf32(name), - normalized_ban_entry - ); - if (w_distance >= normalized_white_entry.size()){ - continue; - } - double w_probability = OCR::random_match_probability( - normalized_white_entry.size(), - normalized_white_entry.size() - w_distance, - language_data(entry.language).random_match_chance - ); - double w_log10p = std::log10(w_probability); - if (w_log10p <= entry.log10p){ - if (PreloadSettings::instance().DEVELOPER_MODE){ - logger.log("Cannot ban whitelisted user: " + name + " (log10p = " + tostr_default(w_log10p) + ")", COLOR_RED); - } - return false; - } - } - } - - matches.emplace_back(TeraLobbyNameMatchResult{ - entry, banlist_source, - ocr_name, - to_utf8(normalized_ocr_name), - log10p, distance == 0, - entry.notes - }); - - return true; -} - -bool check_name_against_banlist( - Logger& logger, - std::vector& match_list, - const std::vector& banlist, const std::string& banlist_source, - const std::map& name, - bool ignore_whitelist -){ - bool banned = false; - for (const PlayerListRowSnapshot& entry : banlist){ - if (!entry.enabled){ - continue; - } - auto iter = name.find(entry.language); - if (iter == name.end()){ - throw InternalProgramError( - &logger, - PA_CURRENT_FUNCTION, - "Name was not OCR'ed in the required language." - ); - } - banned |= check_ban_for_name( - logger, - match_list, - entry, banlist_source, - iter->second, - ignore_whitelist - ); - } - return banned; -} -uint8_t check_ban_list( - Logger& logger, - std::vector& match_list, - const std::vector& banlist_local, - const std::vector& banlist_global, - uint8_t host_players, - const std::array, 4>& player_names, - bool ignore_whitelist -){ - // Check each name against ban list. - uint8_t banned_count = 0; - for (size_t c = host_players; c < 4; c++){ - const auto& name = player_names[c]; - if (name.empty()){ - continue; - } - bool banned = false; - - banned |= check_name_against_banlist( - logger, match_list, - banlist_local, "Banned by Host: ", - name, ignore_whitelist - ); - banned |= check_name_against_banlist( - logger, match_list, - banlist_global, "Banned Globally: ", - name, ignore_whitelist - ); - - if (banned){ - banned_count++; - } - } - - return banned_count; -} - - - - - - - -JoinReportRow::JoinReportRow(Language p_language, bool p_enabled) - : StaticTableRow(language_data(p_language).code) - , language(LockMode::UNLOCK_WHILE_RUNNING, language_data(p_language).name) - , enabled(LockMode::UNLOCK_WHILE_RUNNING, p_enabled) -{ - PA_ADD_STATIC(language); - PA_ADD_OPTION(enabled); -} -JoinReportTable::JoinReportTable() - : StaticTableOption( - "Languages to Read:
" - "Attempt to read every player's name in the following languages. " - "Note that all the Latin-based languages are largely the same. So only English is enabled by default.", - LockMode::UNLOCK_WHILE_RUNNING, false - ) -{ - add_row(std::make_unique(Language::English, true)); - add_row(std::make_unique(Language::Japanese, true)); - add_row(std::make_unique(Language::Spanish, false)); - add_row(std::make_unique(Language::French, false)); - add_row(std::make_unique(Language::German, false)); - add_row(std::make_unique(Language::Italian, false)); - add_row(std::make_unique(Language::Korean, true)); - add_row(std::make_unique(Language::ChineseSimplified, true)); - add_row(std::make_unique(Language::ChineseTraditional, true)); - finish_construction(); -} -std::vector JoinReportTable::make_header() const{ - std::vector ret{ - "Language", - "Enabled", - }; - return ret; -} - - -RaidJoinReportOption::RaidJoinReportOption() - : GroupOption( - "Join Reports:", - LockMode::UNLOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_ENABLED - ) - , text( - "Track how many times each IGN has joined and generate a report. " - "This can be used to help identify people who join too many times for " - "the purpose banning.

" - "Note that these reports should not be taken as-is. Many players share " - "the same IGN and text recognition is unreliable. So these reports " - "should not be used for the purpose of automatic banning." - ) - , wins_only( - "Track Wins Only:
Track wins only. Ignore losses and incomplete raids.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_STATIC(text); - PA_ADD_OPTION(table); - PA_ADD_OPTION(wins_only); -} - - - - - - - -void JoinTracker::add(const std::string& name, std::string lobby_code){ - m_database[name].insert(std::move(lobby_code)); -} -std::string JoinTracker::dump(size_t indent) const{ - std::multimap>::value_type*, std::greater> sorted; - - for (const auto& item : m_database){ - sorted.emplace(item.second.size(), &item); - } - - std::string ret; - - for (const auto& item : sorted){ - ret += std::string(indent, ' '); - ret += std::to_string(item.first) + " : "; - ret += item.second->first + " => ("; - bool first = true; - for (const std::string& code : item.second->second){ - if (!first){ - ret += ","; - } - first = false; - ret += code; - } - ret += ")\r\n"; - } - - return ret; -} - - - - -MultiLanguageJoinTracker::MultiLanguageJoinTracker(uint8_t host_players) - : m_host_players(host_players) -{} - - -void MultiLanguageJoinTracker::add(Language language, const std::string& name, std::string lobby_code){ - m_databases[language].add(name, lobby_code); -} -void MultiLanguageJoinTracker::append( - const std::array, 4>& names, - const std::string& lobby_code -){ - for (size_t c = m_host_players; c < 4; c++){ - for (const auto& item : names[c]){ - add(item.first, item.second, lobby_code); - } - } -} -std::string MultiLanguageJoinTracker::dump() const{ - std::string ret; - for (const auto& database : m_databases){ - ret += language_data(database.first).code + ":\r\n"; - ret += database.second.dump(4); - ret += "\r\n"; - } - return ret; -} -void MultiLanguageJoinTracker::dump(const std::string& filename) const{ - std::string str = dump(); - QFile file(QString::fromStdString(filename)); - file.open(QIODevice::WriteOnly); - std::string bom = "\xef\xbb\xbf"; - file.write(bom.c_str(), bom.size()); - file.write(str.c_str(), str.size()); -} - - - - - - -TeraLobbyJoinWatcher2::TeraLobbyJoinWatcher2( - Logger& logger, AsyncDispatcher& dispatcher, Color color, - uint8_t host_players -) - : TeraLobbyReader(logger, dispatcher, color) - , VisualInferenceCallback("TeraLobbyJoinWatcher2") - , m_host_players(host_players) -{} -void TeraLobbyJoinWatcher2::make_overlays(VideoOverlaySet& items) const{ - TeraLobbyReader::make_overlays(items); -} -bool TeraLobbyJoinWatcher2::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // No lobby detected. - if (!detect(frame)){ - return false; - } - - uint8_t total_players = this->total_players(frame); -// uint8_t ready_players = this->ready_players(frame); - uint8_t ready_joiners = this->ready_joiners(frame, m_host_players); - m_last_known_total_players.store(total_players, std::memory_order_relaxed); -// m_last_known_ready_players.store(ready_players, std::memory_order_relaxed); - m_last_known_ready_joiners.store(ready_joiners, std::memory_order_relaxed); - return false; -} - - - -TeraLobbyNameWatcher::TeraLobbyNameWatcher( - Logger& logger, AsyncDispatcher& dispatcher, - Color color, - RaidJoinReportOption& report_settings, - RaidPlayerBanList& ban_settings, - uint8_t host_players -) - : TeraLobbyReader(logger, dispatcher, color) - , VisualInferenceCallback("TeraLobbyNameWatcher") - , m_logger(logger) - , m_report_settings(report_settings) - , m_ban_settings(ban_settings) - , m_host_players(host_players) -{} - -void TeraLobbyNameWatcher::get_last_known_state( - std::array, 4>& names, - std::vector& bans -){ - std::lock_guard lg(m_lock); - names = m_last_known_names; - bans = m_last_known_bans; -} -void TeraLobbyNameWatcher::make_overlays(VideoOverlaySet& items) const{ - TeraLobbyReader::make_overlays(items); -} -bool TeraLobbyNameWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // No lobby detected. - if (!detect(frame)){ - return false; - } - - bool bans_enabled = m_ban_settings.enabled(); - bool report_enabled = m_report_settings.enabled(); - - // Get language list. - std::set languages; - languages.insert(Language::English); - if (report_enabled){ - for (const auto& item : m_report_settings.table.table()){ - const JoinReportRow& row = static_cast(*item); - if (row.enabled){ - languages.insert(language_code_to_enum(item->slug())); - } - } - } - - std::vector banlist_local = m_ban_settings.banlist_local(); - std::vector banlist_global = m_ban_settings.banlist_global(); -// std::vector banslist = m_ban_settings.banlist_combined(); - if (bans_enabled){ - for (const auto& item : banlist_local){ - languages.insert(item.language); - } - for (const auto& item : banlist_global){ - languages.insert(item.language); - } - } - - // Read names. - std::array, 4> names = read_names( - m_logger, languages, frame - ); - - // Process bans. - std::vector match_list; - if (bans_enabled){ - check_ban_list( - m_logger, - match_list, - banlist_local, - banlist_global, - m_host_players, - names, - m_ban_settings.ignore_whitelist - ); - } - - { - std::lock_guard lg(m_lock); -// m_last_known_players.store(players, std::memory_order_relaxed); - m_last_known_names = std::move(names); - m_last_known_bans = std::move(match_list); - } - - return false; -} - - - - - - - - - - -} -} -} +/* Join Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonTools/OCR/OCR_StringNormalization.h" +#include "CommonTools/OCR/OCR_TextMatcher.h" +#include "PokemonSV_JoinTracker.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +bool check_ban_for_name( + Logger& logger, + std::vector& matches, + const PlayerListRowSnapshot& entry, const std::string& banlist_source, + const std::string& ocr_name, + bool ignore_whitelist +){ + std::u32string normalized_ocr_name = OCR::normalize_utf32(ocr_name); + std::u32string normalized_ban_entry = OCR::normalize_utf32(entry.name); + + size_t distance = OCR::levenshtein_distance( + normalized_ocr_name, + normalized_ban_entry + ); + + if (distance >= normalized_ban_entry.size()){ + return false; + } + + double probability = OCR::random_match_probability( + normalized_ban_entry.size(), + normalized_ban_entry.size() - distance, + language_data(entry.language).random_match_chance + ); + double log10p = std::log10(probability); + + // Not a match. Return now. + if (log10p > entry.log10p && distance != 0){ + return false; + } + + + if (!ignore_whitelist){ + // Matched. Check against the whitelist. + static const std::vector WHITELIST{ + "Kuroneko", + "Kurbo", + "Gael", + "Dhruv", + "Nikki", + "Dani", + "denvoros", + "Halazea", + }; + for (const std::string& name : WHITELIST){ + std::u32string normalized_white_entry = OCR::normalize_utf32(name); + size_t w_distance = OCR::levenshtein_distance( + OCR::normalize_utf32(name), + normalized_ban_entry + ); + if (w_distance >= normalized_white_entry.size()){ + continue; + } + double w_probability = OCR::random_match_probability( + normalized_white_entry.size(), + normalized_white_entry.size() - w_distance, + language_data(entry.language).random_match_chance + ); + double w_log10p = std::log10(w_probability); + if (w_log10p <= entry.log10p){ + if (PreloadSettings::instance().DEVELOPER_MODE){ + logger.log("Cannot ban whitelisted user: " + name + " (log10p = " + tostr_default(w_log10p) + ")", COLOR_RED); + } + return false; + } + } + } + + matches.emplace_back(TeraLobbyNameMatchResult{ + entry, banlist_source, + ocr_name, + to_utf8(normalized_ocr_name), + log10p, distance == 0, + entry.notes + }); + + return true; +} + +bool check_name_against_banlist( + Logger& logger, + std::vector& match_list, + const std::vector& banlist, const std::string& banlist_source, + const std::map& name, + bool ignore_whitelist +){ + bool banned = false; + for (const PlayerListRowSnapshot& entry : banlist){ + if (!entry.enabled){ + continue; + } + auto iter = name.find(entry.language); + if (iter == name.end()){ + throw InternalProgramError( + &logger, + PA_CURRENT_FUNCTION, + "Name was not OCR'ed in the required language." + ); + } + banned |= check_ban_for_name( + logger, + match_list, + entry, banlist_source, + iter->second, + ignore_whitelist + ); + } + return banned; +} +uint8_t check_ban_list( + Logger& logger, + std::vector& match_list, + const std::vector& banlist_local, + const std::vector& banlist_global, + uint8_t host_players, + const std::array, 4>& player_names, + bool ignore_whitelist +){ + // Check each name against ban list. + uint8_t banned_count = 0; + for (size_t c = host_players; c < 4; c++){ + const auto& name = player_names[c]; + if (name.empty()){ + continue; + } + bool banned = false; + + banned |= check_name_against_banlist( + logger, match_list, + banlist_local, "Banned by Host: ", + name, ignore_whitelist + ); + banned |= check_name_against_banlist( + logger, match_list, + banlist_global, "Banned Globally: ", + name, ignore_whitelist + ); + + if (banned){ + banned_count++; + } + } + + return banned_count; +} + + + + + + + +JoinReportRow::JoinReportRow(Language p_language, bool p_enabled) + : StaticTableRow(language_data(p_language).code) + , language(LockMode::UNLOCK_WHILE_RUNNING, language_data(p_language).name) + , enabled(LockMode::UNLOCK_WHILE_RUNNING, p_enabled) +{ + PA_ADD_STATIC(language); + PA_ADD_OPTION(enabled); +} +JoinReportTable::JoinReportTable() + : StaticTableOption( + "Languages to Read:
" + "Attempt to read every player's name in the following languages. " + "Note that all the Latin-based languages are largely the same. So only English is enabled by default.", + LockMode::UNLOCK_WHILE_RUNNING, false + ) +{ + add_row(std::make_unique(Language::English, true)); + add_row(std::make_unique(Language::Japanese, true)); + add_row(std::make_unique(Language::Spanish, false)); + add_row(std::make_unique(Language::French, false)); + add_row(std::make_unique(Language::German, false)); + add_row(std::make_unique(Language::Italian, false)); + add_row(std::make_unique(Language::Korean, true)); + add_row(std::make_unique(Language::ChineseSimplified, true)); + add_row(std::make_unique(Language::ChineseTraditional, true)); + finish_construction(); +} +std::vector JoinReportTable::make_header() const{ + std::vector ret{ + "Language", + "Enabled", + }; + return ret; +} + + +RaidJoinReportOption::RaidJoinReportOption() + : GroupOption( + "Join Reports:", + LockMode::UNLOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_ENABLED + ) + , text( + "Track how many times each IGN has joined and generate a report. " + "This can be used to help identify people who join too many times for " + "the purpose banning.

" + "Note that these reports should not be taken as-is. Many players share " + "the same IGN and text recognition is unreliable. So these reports " + "should not be used for the purpose of automatic banning." + ) + , wins_only( + "Track Wins Only:
Track wins only. Ignore losses and incomplete raids.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_STATIC(text); + PA_ADD_OPTION(table); + PA_ADD_OPTION(wins_only); +} + + + + + + + +void JoinTracker::add(const std::string& name, std::string lobby_code){ + m_database[name].insert(std::move(lobby_code)); +} +std::string JoinTracker::dump(size_t indent) const{ + std::multimap>::value_type*, std::greater> sorted; + + for (const auto& item : m_database){ + sorted.emplace(item.second.size(), &item); + } + + std::string ret; + + for (const auto& item : sorted){ + ret += std::string(indent, ' '); + ret += std::to_string(item.first) + " : "; + ret += item.second->first + " => ("; + bool first = true; + for (const std::string& code : item.second->second){ + if (!first){ + ret += ","; + } + first = false; + ret += code; + } + ret += ")\r\n"; + } + + return ret; +} + + + + +MultiLanguageJoinTracker::MultiLanguageJoinTracker(uint8_t host_players) + : m_host_players(host_players) +{} + + +void MultiLanguageJoinTracker::add(Language language, const std::string& name, std::string lobby_code){ + m_databases[language].add(name, lobby_code); +} +void MultiLanguageJoinTracker::append( + const std::array, 4>& names, + const std::string& lobby_code +){ + for (size_t c = m_host_players; c < 4; c++){ + for (const auto& item : names[c]){ + add(item.first, item.second, lobby_code); + } + } +} +std::string MultiLanguageJoinTracker::dump() const{ + std::string ret; + for (const auto& database : m_databases){ + ret += language_data(database.first).code + ":\r\n"; + ret += database.second.dump(4); + ret += "\r\n"; + } + return ret; +} +void MultiLanguageJoinTracker::dump(const std::string& filename) const{ + std::string str = dump(); + QFile file(QString::fromStdString(filename)); + file.open(QIODevice::WriteOnly); + std::string bom = "\xef\xbb\xbf"; + file.write(bom.c_str(), bom.size()); + file.write(str.c_str(), str.size()); +} + + + + + + +TeraLobbyJoinWatcher2::TeraLobbyJoinWatcher2( + Logger& logger, AsyncDispatcher& dispatcher, Color color, + uint8_t host_players +) + : TeraLobbyReader(logger, dispatcher, color) + , VisualInferenceCallback("TeraLobbyJoinWatcher2") + , m_host_players(host_players) +{} +void TeraLobbyJoinWatcher2::make_overlays(VideoOverlaySet& items) const{ + TeraLobbyReader::make_overlays(items); +} +bool TeraLobbyJoinWatcher2::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // No lobby detected. + if (!detect(frame)){ + return false; + } + + uint8_t total_players = this->total_players(frame); +// uint8_t ready_players = this->ready_players(frame); + uint8_t ready_joiners = this->ready_joiners(frame, m_host_players); + m_last_known_total_players.store(total_players, std::memory_order_relaxed); +// m_last_known_ready_players.store(ready_players, std::memory_order_relaxed); + m_last_known_ready_joiners.store(ready_joiners, std::memory_order_relaxed); + return false; +} + + + +TeraLobbyNameWatcher::TeraLobbyNameWatcher( + Logger& logger, AsyncDispatcher& dispatcher, + Color color, + RaidJoinReportOption& report_settings, + RaidPlayerBanList& ban_settings, + uint8_t host_players +) + : TeraLobbyReader(logger, dispatcher, color) + , VisualInferenceCallback("TeraLobbyNameWatcher") + , m_logger(logger) + , m_report_settings(report_settings) + , m_ban_settings(ban_settings) + , m_host_players(host_players) +{} + +void TeraLobbyNameWatcher::get_last_known_state( + std::array, 4>& names, + std::vector& bans +){ + std::lock_guard lg(m_lock); + names = m_last_known_names; + bans = m_last_known_bans; +} +void TeraLobbyNameWatcher::make_overlays(VideoOverlaySet& items) const{ + TeraLobbyReader::make_overlays(items); +} +bool TeraLobbyNameWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // No lobby detected. + if (!detect(frame)){ + return false; + } + + bool bans_enabled = m_ban_settings.enabled(); + bool report_enabled = m_report_settings.enabled(); + + // Get language list. + std::set languages; + languages.insert(Language::English); + if (report_enabled){ + for (const auto& item : m_report_settings.table.table()){ + const JoinReportRow& row = static_cast(*item); + if (row.enabled){ + languages.insert(language_code_to_enum(item->slug())); + } + } + } + + std::vector banlist_local = m_ban_settings.banlist_local(); + std::vector banlist_global = m_ban_settings.banlist_global(); +// std::vector banslist = m_ban_settings.banlist_combined(); + if (bans_enabled){ + for (const auto& item : banlist_local){ + languages.insert(item.language); + } + for (const auto& item : banlist_global){ + languages.insert(item.language); + } + } + + // Read names. + std::array, 4> names = read_names( + m_logger, languages, frame + ); + + // Process bans. + std::vector match_list; + if (bans_enabled){ + check_ban_list( + m_logger, + match_list, + banlist_local, + banlist_global, + m_host_players, + names, + m_ban_settings.ignore_whitelist + ); + } + + { + std::lock_guard lg(m_lock); +// m_last_known_players.store(players, std::memory_order_relaxed); + m_last_known_names = std::move(names); + m_last_known_bans = std::move(match_list); + } + + return false; +} + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h index daeb9ff7ab..72494488bc 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_JoinTracker.h @@ -1,157 +1,157 @@ -/* Join Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_JoinTracker_H -#define PokemonAutomation_PokemonSV_JoinTracker_H - -#include -#include -#include -#include -#include -#include "CommonFramework/Language.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/StaticTableOption.h" -#include "CommonFramework/Options/LabelCellOption.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// On the lobby of a Tera raid, check if any of the players are banned. -// Returns the # of players banned. -uint8_t check_ban_list( - Logger& logger, - std::vector& match_list, - const std::vector& ban_list, - const std::array, 4>& player_names, - bool include_host, bool ignore_whitelist -); - - - - -class JoinReportRow : public StaticTableRow{ -public: - JoinReportRow(Language p_language, bool p_enabled); - - LabelCellOption language; - BooleanCheckBoxCell enabled; -}; -class JoinReportTable : public StaticTableOption{ -public: - JoinReportTable(); - virtual std::vector make_header() const; -}; - - - -class RaidJoinReportOption : public GroupOption{ -public: - RaidJoinReportOption(); - -public: - StaticTextOption text; - JoinReportTable table; - BooleanCheckBoxOption wins_only; -}; - - - - -class JoinTracker{ -public: - void add(const std::string& name, std::string lobby_code); - std::string dump(size_t indent = 0) const; - -private: - std::map> m_database; -}; - -class MultiLanguageJoinTracker{ -public: - MultiLanguageJoinTracker(uint8_t host_players); - - void add(Language language, const std::string& name, std::string lobby_code); - void append( - const std::array, 4>& names, - const std::string& lobby_code - ); - - std::string dump() const; - void dump(const std::string& filename) const; - -private: - uint8_t m_host_players; - std::map m_databases; -}; - - - - -class TeraLobbyJoinWatcher2 : public TeraLobbyReader, public VisualInferenceCallback{ -public: - TeraLobbyJoinWatcher2( - Logger& logger, AsyncDispatcher& dispatcher, Color color, - uint8_t host_players - ); - - uint8_t last_known_total_players() const{ return m_last_known_total_players.load(std::memory_order_relaxed); } -// uint8_t last_known_ready_players() const{ return m_last_known_ready_players.load(std::memory_order_relaxed); } - uint8_t last_known_ready_joiners() const{ return m_last_known_ready_joiners.load(std::memory_order_relaxed); } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - uint8_t m_host_players; - std::atomic m_last_known_total_players = 0; -// std::atomic m_last_known_ready_players = 0; - std::atomic m_last_known_ready_joiners = 0; -}; - - -class TeraLobbyNameWatcher : public TeraLobbyReader, public VisualInferenceCallback{ -public: - TeraLobbyNameWatcher( - Logger& logger, AsyncDispatcher& dispatcher, Color color, - RaidJoinReportOption& report_settings, - RaidPlayerBanList& ban_settings, - uint8_t host_players - ); - - void get_last_known_state( - std::array, 4>& names, - std::vector& bans - ); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - RaidJoinReportOption& m_report_settings; - RaidPlayerBanList& m_ban_settings; - uint8_t m_host_players; - - mutable std::mutex m_lock; - std::array, 4> m_last_known_names; - std::vector m_last_known_bans; -}; - - - - - - -} -} -} -#endif +/* Join Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_JoinTracker_H +#define PokemonAutomation_PokemonSV_JoinTracker_H + +#include +#include +#include +#include +#include +#include "CommonFramework/Language.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/StaticTableOption.h" +#include "CommonFramework/Options/LabelCellOption.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// On the lobby of a Tera raid, check if any of the players are banned. +// Returns the # of players banned. +uint8_t check_ban_list( + Logger& logger, + std::vector& match_list, + const std::vector& ban_list, + const std::array, 4>& player_names, + bool include_host, bool ignore_whitelist +); + + + + +class JoinReportRow : public StaticTableRow{ +public: + JoinReportRow(Language p_language, bool p_enabled); + + LabelCellOption language; + BooleanCheckBoxCell enabled; +}; +class JoinReportTable : public StaticTableOption{ +public: + JoinReportTable(); + virtual std::vector make_header() const; +}; + + + +class RaidJoinReportOption : public GroupOption{ +public: + RaidJoinReportOption(); + +public: + StaticTextOption text; + JoinReportTable table; + BooleanCheckBoxOption wins_only; +}; + + + + +class JoinTracker{ +public: + void add(const std::string& name, std::string lobby_code); + std::string dump(size_t indent = 0) const; + +private: + std::map> m_database; +}; + +class MultiLanguageJoinTracker{ +public: + MultiLanguageJoinTracker(uint8_t host_players); + + void add(Language language, const std::string& name, std::string lobby_code); + void append( + const std::array, 4>& names, + const std::string& lobby_code + ); + + std::string dump() const; + void dump(const std::string& filename) const; + +private: + uint8_t m_host_players; + std::map m_databases; +}; + + + + +class TeraLobbyJoinWatcher2 : public TeraLobbyReader, public VisualInferenceCallback{ +public: + TeraLobbyJoinWatcher2( + Logger& logger, AsyncDispatcher& dispatcher, Color color, + uint8_t host_players + ); + + uint8_t last_known_total_players() const{ return m_last_known_total_players.load(std::memory_order_relaxed); } +// uint8_t last_known_ready_players() const{ return m_last_known_ready_players.load(std::memory_order_relaxed); } + uint8_t last_known_ready_joiners() const{ return m_last_known_ready_joiners.load(std::memory_order_relaxed); } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + uint8_t m_host_players; + std::atomic m_last_known_total_players = 0; +// std::atomic m_last_known_ready_players = 0; + std::atomic m_last_known_ready_joiners = 0; +}; + + +class TeraLobbyNameWatcher : public TeraLobbyReader, public VisualInferenceCallback{ +public: + TeraLobbyNameWatcher( + Logger& logger, AsyncDispatcher& dispatcher, Color color, + RaidJoinReportOption& report_settings, + RaidPlayerBanList& ban_settings, + uint8_t host_players + ); + + void get_last_known_state( + std::array, 4>& names, + std::vector& bans + ); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + RaidJoinReportOption& m_report_settings; + RaidPlayerBanList& m_ban_settings; + uint8_t m_host_players; + + mutable std::mutex m_lock; + std::array, 4> m_last_known_names; + std::vector m_last_known_bans; +}; + + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.cpp index 2f84332eac..1efec17c65 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.cpp @@ -1,359 +1,359 @@ -/* Tera Battler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV_TeraBattler.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// If two Switches send commands at exactly the same time, it may cause the -// Switches to desync and fork the battle state. So we use this lock prevent -// any two Switches from sending commands too close to each other. -std::mutex tera_battle_throttle_lock; - - -enum class BattleMenuResult{ - RESUME_CURRENT_TURN, - RESUME_ADVANCE_TURN, - BATTLE_WON, - BATTLE_LOST, -}; -BattleMenuResult run_battle_menu( - VideoStream& stream, ProControllerContext& context, - TeraBattleMenuDetector& battle_menu, - TeraCatchWatcher& catch_menu, - OverworldWatcher& overworld, - const TeraMoveEntry& move -){ - stream.log("Current Move Selection: " + move.to_str()); - switch (move.type){ - case TeraMoveType::Wait:{ - int ret = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, move.seconds * TICKS_PER_SECOND); - }, - {catch_menu, overworld} - ); - switch (ret){ - case 0: return BattleMenuResult::BATTLE_WON; - case 1: return BattleMenuResult::BATTLE_LOST; - } - return BattleMenuResult::RESUME_ADVANCE_TURN; - } - case TeraMoveType::Move1: - case TeraMoveType::Move2: - case TeraMoveType::Move3: - case TeraMoveType::Move4: - if (battle_menu.move_to_slot(stream, context, 0)){ - pbf_press_button(context, BUTTON_A, 20, 10); - } - break; - case TeraMoveType::Cheer_AllOut: - case TeraMoveType::Cheer_HangTough: - case TeraMoveType::Cheer_HealUp: - if (battle_menu.move_to_slot(stream, context, 1)){ - pbf_press_button(context, BUTTON_A, 20, 10); - } - break; - } - return BattleMenuResult::RESUME_CURRENT_TURN; -} -bool run_cheer_select( - VideoStream& stream, ProControllerContext& context, - CheerSelectDetector& cheer_select_menu, - TeraMoveEntry& move -){ - uint8_t index = 0; - switch (move.type){ - case TeraMoveType::Cheer_AllOut: - index = 0; - break; - case TeraMoveType::Cheer_HangTough: - index = 1; - break; - case TeraMoveType::Cheer_HealUp: - index = 2; - break; - default: - pbf_press_button(context, BUTTON_B, 20, 10); - return false; - } - if (cheer_select_menu.move_to_slot(stream, context, index)){ - std::lock_guard lg(tera_battle_throttle_lock); - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - } - return true; -} -bool run_move_select( - VideoStream& stream, ProControllerContext& context, - TeraAIOption& battle_AI, - TerastallizingDetector& terastallizing, - MoveSelectWatcher& move_select_menu, - TeraMoveEntry& move, size_t consecutive_move_select -){ - uint8_t index = 0; - switch (move.type){ - case TeraMoveType::Move1: - index = 0; - break; - case TeraMoveType::Move2: - index = 1; - break; - case TeraMoveType::Move3: - index = 2; - break; - case TeraMoveType::Move4: - index = 3; - break; - default: - pbf_press_button(context, BUTTON_B, 20, 10); - return false; - } - - // If we end up here consecutively too many times, the move is - // probably disabled. Select a different move. - if (consecutive_move_select > 3){ - stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); -// pbf_press_dpad(context, DPAD_DOWN, 20, 40); - index++; - if (index >= 4){ - index = 0; - } - move.type = (TeraMoveType)((uint8_t)TeraMoveType::Move1 + index); - } - - do{ - if (!battle_AI.TRY_TO_TERASTILLIZE){ - stream.log("Skipping Terastallization. Reason: Disabled by settings."); - break; - } - if (consecutive_move_select > 1){ - stream.log("Skipping Terastallization. Reason: Previously failed move select."); - break; - } - if (!terastallizing.detect(stream.video().snapshot())){ - stream.log("Skipping Terastallization. Reason: Not ready."); - break; - } - - stream.log("Attempting to Terastallize..."); - pbf_press_button(context, BUTTON_R, 20, 4 * TICKS_PER_SECOND); - }while (false); - - if (move_select_menu.move_to_slot(stream, context, index)){ - pbf_press_button(context, BUTTON_A, 20, 10); - } - return true; -} -bool run_target_select( - VideoStream& stream, ProControllerContext& context, - TeraTargetSelectDetector& target_select_menu, - TeraMoveEntry& move -){ - switch (move.type){ - case TeraMoveType::Move1: - case TeraMoveType::Move2: - case TeraMoveType::Move3: - case TeraMoveType::Move4:{ - target_select_menu.move_to_slot(stream, context, (uint8_t)move.target); - std::lock_guard lg(tera_battle_throttle_lock); - pbf_press_button(context, BUTTON_A, 20, 40); - context.wait_for_all_requests(); - return true; - } - default: - pbf_press_button(context, BUTTON_B, 20, 10); - return false; - } -} - - - - -bool run_tera_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - TeraAIOption& battle_AI -){ - stream.log("Starting tera battle routine..."); - - size_t turn = 0; - std::vector move_table = battle_AI.MOVE_TABLE.snapshot(); - TeraMoveEntry current_move{TeraMoveType::Move1, 0, TeraTarget::Opponent}; - if (!move_table.empty()){ - current_move = move_table[0]; - } - - size_t consecutive_timeouts = 0; - size_t consecutive_move_select = 0; - bool battle_menu_seen = false; - bool next_turn_on_battle_menu = false; - while (true){ - // Warning, this terastallizing detector isn't used in the wait_until() below. - TerastallizingDetector terastallizing(COLOR_ORANGE); - VideoOverlaySet overlay_set(stream.overlay()); - terastallizing.make_overlays(overlay_set); - - TeraBattleMenuWatcher battle_menu(COLOR_RED); - CheerSelectWatcher cheer_select_menu(COLOR_YELLOW); - MoveSelectWatcher move_select_menu(COLOR_YELLOW); - TargetSelectWatcher target_select_menu(COLOR_CYAN); - WhiteButtonWatcher next_button( - COLOR_CYAN, - WhiteButton::ButtonA, - {0.8, 0.93, 0.2, 0.07}, - WhiteButtonWatcher::FinderType::PRESENT, - // This can false positive against the back (B) button while in the - // lobby. So don't trigger this unless we see the battle menu first. - // At the same time, there's a possibility that we miss the battle - // menu if the raid is won before it even loads. And this can only - // happen if the raid was uncatchable to begin with. - std::chrono::seconds(battle_menu_seen ? 5 : 180) - ); - TeraCatchWatcher catch_menu(COLOR_BLUE); - OverworldWatcher overworld(stream.logger(), COLOR_GREEN); - context.wait_for_all_requests(); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 4; c++){ - pbf_wait(context, 30 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_B, 20, 0); - } - }, - { - battle_menu, - cheer_select_menu, - move_select_menu, - target_select_menu, - next_button, - catch_menu, - overworld, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0:{ - stream.log("Detected battle menu."); - battle_menu_seen = true; - - // If we enter here, we advance to the next turn. - if (next_turn_on_battle_menu){ - stream.log("Detected battle menu. Turn: " + std::to_string(turn)); - turn++; - // Reset the move to the table entry in case we were forced to - // change moves due to move being unselectable. - if (move_table.empty()){ - current_move = TeraMoveEntry{TeraMoveType::Move1, 0, TeraTarget::Opponent}; - }else if (turn < move_table.size()){ - current_move = move_table[turn]; - }else{ - current_move = move_table.back(); - } - next_turn_on_battle_menu = false; - } - - stream.log("Current Move Selection: " + current_move.to_str()); - BattleMenuResult battle_menu_result = run_battle_menu( - stream, context, - battle_menu, - catch_menu, - overworld, - current_move - ); - switch (battle_menu_result){ - case BattleMenuResult::RESUME_CURRENT_TURN: - continue; - case BattleMenuResult::RESUME_ADVANCE_TURN: - next_turn_on_battle_menu = true; - continue; - case BattleMenuResult::BATTLE_WON: - stream.log("Detected a win!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_B, 30); - return true; - case BattleMenuResult::BATTLE_LOST: - stream.log("Detected a loss!", COLOR_ORANGE); - return false; - } - } - case 1:{ - stream.log("Detected cheer select. Turn: " + std::to_string(turn)); - if (run_cheer_select(stream, context, cheer_select_menu, current_move)){ - next_turn_on_battle_menu = true; - } - continue; - } - case 2:{ - stream.log("Detected move select. Turn: " + std::to_string(turn)); - consecutive_move_select++; - run_move_select( - stream, context, - battle_AI, - terastallizing, - move_select_menu, - current_move, - consecutive_move_select - ); - continue; - } - case 3: - stream.log("Detected target select. Turn: " + std::to_string(turn)); - consecutive_move_select = 0; - if (run_target_select(stream, context, target_select_menu, current_move)){ - next_turn_on_battle_menu = true; - } - continue; - case 4: - stream.log("Detected item rewards menu!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_B, 30); - return true; - case 5: - stream.log("Detected catch menu!", COLOR_BLUE); - pbf_mash_button(context, BUTTON_B, 30); - return true; - case 6: - stream.log("Detected a loss!", COLOR_ORANGE); - return false; - default: - consecutive_timeouts++; - if (consecutive_timeouts == 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No state detected after 6 minutes.", - stream - ); - } - stream.log("Unable to detect any state for 2 minutes. Mashing B...", COLOR_RED); - pbf_mash_button(context, BUTTON_B, 250); - } - } - - return false; -} - - - - - - - - - -} -} -} +/* Tera Battler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Battles/PokemonSV_NormalBattleMenus.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV_TeraBattler.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// If two Switches send commands at exactly the same time, it may cause the +// Switches to desync and fork the battle state. So we use this lock prevent +// any two Switches from sending commands too close to each other. +std::mutex tera_battle_throttle_lock; + + +enum class BattleMenuResult{ + RESUME_CURRENT_TURN, + RESUME_ADVANCE_TURN, + BATTLE_WON, + BATTLE_LOST, +}; +BattleMenuResult run_battle_menu( + VideoStream& stream, ProControllerContext& context, + TeraBattleMenuDetector& battle_menu, + TeraCatchWatcher& catch_menu, + OverworldWatcher& overworld, + const TeraMoveEntry& move +){ + stream.log("Current Move Selection: " + move.to_str()); + switch (move.type){ + case TeraMoveType::Wait:{ + int ret = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, move.seconds * TICKS_PER_SECOND); + }, + {catch_menu, overworld} + ); + switch (ret){ + case 0: return BattleMenuResult::BATTLE_WON; + case 1: return BattleMenuResult::BATTLE_LOST; + } + return BattleMenuResult::RESUME_ADVANCE_TURN; + } + case TeraMoveType::Move1: + case TeraMoveType::Move2: + case TeraMoveType::Move3: + case TeraMoveType::Move4: + if (battle_menu.move_to_slot(stream, context, 0)){ + pbf_press_button(context, BUTTON_A, 20, 10); + } + break; + case TeraMoveType::Cheer_AllOut: + case TeraMoveType::Cheer_HangTough: + case TeraMoveType::Cheer_HealUp: + if (battle_menu.move_to_slot(stream, context, 1)){ + pbf_press_button(context, BUTTON_A, 20, 10); + } + break; + } + return BattleMenuResult::RESUME_CURRENT_TURN; +} +bool run_cheer_select( + VideoStream& stream, ProControllerContext& context, + CheerSelectDetector& cheer_select_menu, + TeraMoveEntry& move +){ + uint8_t index = 0; + switch (move.type){ + case TeraMoveType::Cheer_AllOut: + index = 0; + break; + case TeraMoveType::Cheer_HangTough: + index = 1; + break; + case TeraMoveType::Cheer_HealUp: + index = 2; + break; + default: + pbf_press_button(context, BUTTON_B, 20, 10); + return false; + } + if (cheer_select_menu.move_to_slot(stream, context, index)){ + std::lock_guard lg(tera_battle_throttle_lock); + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + } + return true; +} +bool run_move_select( + VideoStream& stream, ProControllerContext& context, + TeraAIOption& battle_AI, + TerastallizingDetector& terastallizing, + MoveSelectWatcher& move_select_menu, + TeraMoveEntry& move, size_t consecutive_move_select +){ + uint8_t index = 0; + switch (move.type){ + case TeraMoveType::Move1: + index = 0; + break; + case TeraMoveType::Move2: + index = 1; + break; + case TeraMoveType::Move3: + index = 2; + break; + case TeraMoveType::Move4: + index = 3; + break; + default: + pbf_press_button(context, BUTTON_B, 20, 10); + return false; + } + + // If we end up here consecutively too many times, the move is + // probably disabled. Select a different move. + if (consecutive_move_select > 3){ + stream.log("Failed to select a move 3 times. Choosing a different move.", COLOR_RED); +// pbf_press_dpad(context, DPAD_DOWN, 20, 40); + index++; + if (index >= 4){ + index = 0; + } + move.type = (TeraMoveType)((uint8_t)TeraMoveType::Move1 + index); + } + + do{ + if (!battle_AI.TRY_TO_TERASTILLIZE){ + stream.log("Skipping Terastallization. Reason: Disabled by settings."); + break; + } + if (consecutive_move_select > 1){ + stream.log("Skipping Terastallization. Reason: Previously failed move select."); + break; + } + if (!terastallizing.detect(stream.video().snapshot())){ + stream.log("Skipping Terastallization. Reason: Not ready."); + break; + } + + stream.log("Attempting to Terastallize..."); + pbf_press_button(context, BUTTON_R, 20, 4 * TICKS_PER_SECOND); + }while (false); + + if (move_select_menu.move_to_slot(stream, context, index)){ + pbf_press_button(context, BUTTON_A, 20, 10); + } + return true; +} +bool run_target_select( + VideoStream& stream, ProControllerContext& context, + TeraTargetSelectDetector& target_select_menu, + TeraMoveEntry& move +){ + switch (move.type){ + case TeraMoveType::Move1: + case TeraMoveType::Move2: + case TeraMoveType::Move3: + case TeraMoveType::Move4:{ + target_select_menu.move_to_slot(stream, context, (uint8_t)move.target); + std::lock_guard lg(tera_battle_throttle_lock); + pbf_press_button(context, BUTTON_A, 20, 40); + context.wait_for_all_requests(); + return true; + } + default: + pbf_press_button(context, BUTTON_B, 20, 10); + return false; + } +} + + + + +bool run_tera_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + TeraAIOption& battle_AI +){ + stream.log("Starting tera battle routine..."); + + size_t turn = 0; + std::vector move_table = battle_AI.MOVE_TABLE.snapshot(); + TeraMoveEntry current_move{TeraMoveType::Move1, 0, TeraTarget::Opponent}; + if (!move_table.empty()){ + current_move = move_table[0]; + } + + size_t consecutive_timeouts = 0; + size_t consecutive_move_select = 0; + bool battle_menu_seen = false; + bool next_turn_on_battle_menu = false; + while (true){ + // Warning, this terastallizing detector isn't used in the wait_until() below. + TerastallizingDetector terastallizing(COLOR_ORANGE); + VideoOverlaySet overlay_set(stream.overlay()); + terastallizing.make_overlays(overlay_set); + + TeraBattleMenuWatcher battle_menu(COLOR_RED); + CheerSelectWatcher cheer_select_menu(COLOR_YELLOW); + MoveSelectWatcher move_select_menu(COLOR_YELLOW); + TargetSelectWatcher target_select_menu(COLOR_CYAN); + WhiteButtonWatcher next_button( + COLOR_CYAN, + WhiteButton::ButtonA, + {0.8, 0.93, 0.2, 0.07}, + WhiteButtonWatcher::FinderType::PRESENT, + // This can false positive against the back (B) button while in the + // lobby. So don't trigger this unless we see the battle menu first. + // At the same time, there's a possibility that we miss the battle + // menu if the raid is won before it even loads. And this can only + // happen if the raid was uncatchable to begin with. + std::chrono::seconds(battle_menu_seen ? 5 : 180) + ); + TeraCatchWatcher catch_menu(COLOR_BLUE); + OverworldWatcher overworld(stream.logger(), COLOR_GREEN); + context.wait_for_all_requests(); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 4; c++){ + pbf_wait(context, 30 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_B, 20, 0); + } + }, + { + battle_menu, + cheer_select_menu, + move_select_menu, + target_select_menu, + next_button, + catch_menu, + overworld, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0:{ + stream.log("Detected battle menu."); + battle_menu_seen = true; + + // If we enter here, we advance to the next turn. + if (next_turn_on_battle_menu){ + stream.log("Detected battle menu. Turn: " + std::to_string(turn)); + turn++; + // Reset the move to the table entry in case we were forced to + // change moves due to move being unselectable. + if (move_table.empty()){ + current_move = TeraMoveEntry{TeraMoveType::Move1, 0, TeraTarget::Opponent}; + }else if (turn < move_table.size()){ + current_move = move_table[turn]; + }else{ + current_move = move_table.back(); + } + next_turn_on_battle_menu = false; + } + + stream.log("Current Move Selection: " + current_move.to_str()); + BattleMenuResult battle_menu_result = run_battle_menu( + stream, context, + battle_menu, + catch_menu, + overworld, + current_move + ); + switch (battle_menu_result){ + case BattleMenuResult::RESUME_CURRENT_TURN: + continue; + case BattleMenuResult::RESUME_ADVANCE_TURN: + next_turn_on_battle_menu = true; + continue; + case BattleMenuResult::BATTLE_WON: + stream.log("Detected a win!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_B, 30); + return true; + case BattleMenuResult::BATTLE_LOST: + stream.log("Detected a loss!", COLOR_ORANGE); + return false; + } + } + case 1:{ + stream.log("Detected cheer select. Turn: " + std::to_string(turn)); + if (run_cheer_select(stream, context, cheer_select_menu, current_move)){ + next_turn_on_battle_menu = true; + } + continue; + } + case 2:{ + stream.log("Detected move select. Turn: " + std::to_string(turn)); + consecutive_move_select++; + run_move_select( + stream, context, + battle_AI, + terastallizing, + move_select_menu, + current_move, + consecutive_move_select + ); + continue; + } + case 3: + stream.log("Detected target select. Turn: " + std::to_string(turn)); + consecutive_move_select = 0; + if (run_target_select(stream, context, target_select_menu, current_move)){ + next_turn_on_battle_menu = true; + } + continue; + case 4: + stream.log("Detected item rewards menu!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_B, 30); + return true; + case 5: + stream.log("Detected catch menu!", COLOR_BLUE); + pbf_mash_button(context, BUTTON_B, 30); + return true; + case 6: + stream.log("Detected a loss!", COLOR_ORANGE); + return false; + default: + consecutive_timeouts++; + if (consecutive_timeouts == 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No state detected after 6 minutes.", + stream + ); + } + stream.log("Unable to detect any state for 2 minutes. Mashing B...", COLOR_RED); + pbf_mash_button(context, BUTTON_B, 250); + } + } + + return false; +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h index 58c939b9da..42b6913f7f 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h @@ -1,33 +1,33 @@ -/* Tera Battler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraBattler_H -#define PokemonAutomation_PokemonSV_TeraBattler_H - -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -// Run a tera battle until you either win or lose. -bool run_tera_battle( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - TeraAIOption& battle_AI -); - - - - -} -} -} -#endif +/* Tera Battler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraBattler_H +#define PokemonAutomation_PokemonSV_TeraBattler_H + +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +// Run a tera battle until you either win or lose. +bool run_tera_battle( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + TeraAIOption& battle_AI +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp index 43666908b8..50d45145d8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.cpp @@ -1,687 +1,687 @@ -/* Tera Multi-Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -//#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h" -#include "PokemonSV_TeraRoutines.h" -#include "PokemonSV_TeraBattler.h" -#include "PokemonSV_AutoHostTools.h" -#include "PokemonSV_AutoHostLobbyWaiter.h" -#include "PokemonSV_TeraMultiFarmer.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -GeneralHostingOptions::GeneralHostingOptions() - : GroupOption("Hosting Options", LockMode::UNLOCK_WHILE_RUNNING) -{ - PA_ADD_OPTION(LOBBY_WAIT_DELAY); - PA_ADD_OPTION(START_RAID_PLAYERS); - PA_ADD_OPTION(SHOW_RAID_CODE); - PA_ADD_OPTION(DESCRIPTION); - PA_ADD_OPTION(REMOTE_KILL_SWITCH); - PA_ADD_OPTION(CONSECUTIVE_FAILURE_PAUSE); - PA_ADD_OPTION(FAILURE_PAUSE_MINUTES); -} - - - - -TeraFarmerPerConsoleOptions::~TeraFarmerPerConsoleOptions(){ - catch_on_win.remove_listener(*this); -} -TeraFarmerPerConsoleOptions::TeraFarmerPerConsoleOptions(std::string label, const LanguageSet& languages, bool host) - : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) - , is_host_label("This is the host Switch.") - , language("Game Language:", languages, LockMode::LOCK_WHILE_RUNNING, true) - , catch_on_win( - "Catch the " + STRING_POKEMON + ":", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , ball_select( - "Ball Select:", - LockMode::UNLOCK_WHILE_RUNNING, - "poke-ball" - ) -{ - PA_ADD_STATIC(is_host_label); - PA_ADD_OPTION(language); - PA_ADD_OPTION(keyboard_layout); - PA_ADD_OPTION(catch_on_win); - PA_ADD_OPTION(ball_select); - PA_ADD_OPTION(battle_ai); - - set_host(host); - - catch_on_win.add_listener(*this); -} -void TeraFarmerPerConsoleOptions::set_host(bool is_host){ - this->is_host = is_host; - TeraFarmerPerConsoleOptions::on_config_value_changed(this); -} -void TeraFarmerPerConsoleOptions::on_config_value_changed(void* object){ - if (this->is_host){ - is_host_label.set_visibility(ConfigOptionState::ENABLED); - catch_on_win.set_visibility(ConfigOptionState::DISABLED); - ball_select.set_visibility(ConfigOptionState::DISABLED); - }else{ - is_host_label.set_visibility(ConfigOptionState::HIDDEN); - catch_on_win.set_visibility(ConfigOptionState::ENABLED); - ball_select.set_visibility(catch_on_win ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED); - } -} - - - -TeraMultiFarmer_Descriptor::TeraMultiFarmer_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSV:TeraMultiFarmer", - STRING_POKEMON + " SV", "Tera Multi-Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TeraMultiFarmer.md", - "Farm items and " + STRING_POKEMON + " from your own Tera raid using multiple Switches.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 2, 4, 2 - ) -{} -struct TeraMultiFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : m_raids(m_stats["Raids"]) - , m_empty(m_stats["Empty Raids"]) - , m_full(m_stats["Full Raids"]) - , m_joiners(m_stats["Total Joiners"]) - , m_wins(m_stats["Wins"]) - , m_losses(m_stats["Losses"]) - , m_banned(m_stats["Banned"]) - , m_errors(m_stats["Errors"]) - { - m_display_order.emplace_back("Raids"); - m_display_order.emplace_back("Empty Raids", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Full Raids", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Total Joiners", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Wins"); - m_display_order.emplace_back("Losses"); - m_display_order.emplace_back("Banned", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - std::atomic& m_raids; - std::atomic& m_empty; - std::atomic& m_full; - std::atomic& m_joiners; - std::atomic& m_wins; - std::atomic& m_losses; - std::atomic& m_banned; - std::atomic& m_errors; -}; -std::unique_ptr TeraMultiFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -TeraMultiFarmer::~TeraMultiFarmer(){ - HOSTING_MODE.remove_listener(*this); - HOSTING_SWITCH.remove_listener(*this); -} -TeraMultiFarmer::TeraMultiFarmer() - : HOSTING_SWITCH( - "Host Switch:
This is the Switch that hosts the raid.", - { - {0, "switch0", "Switch 0 (Top Left)"}, - {1, "switch1", "Switch 1 (Top Right)"}, - {2, "switch2", "Switch 2 (Bottom Left)"}, - {3, "switch3", "Switch 3 (Bottom Right)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , MAX_WINS( - "Max Wins:
Stop program after winning this many times.", - LockMode::UNLOCK_WHILE_RUNNING, - 999, 1, 999 - ) - , HOSTING_MODE( - "Mode:", - { - {Mode::FARM_ALONE, "farm-alone", "Farm by yourself."}, - {Mode::HOST_LOCALLY, "host-locally", "Host remaining slots locally."}, - {Mode::HOST_ONLINE, "host-online", "Host remaining slots online."}, - }, - LockMode::LOCK_WHILE_RUNNING, - Mode::FARM_ALONE - ) - , RECOVERY_MODE( - "Recovery Mode:", - { - {RecoveryMode::STOP_ON_ERROR, "stop-on-error", "Stop on any error."}, - {RecoveryMode::SAVE_AND_RESET, "save-and-reset", "Save before each raid. Reset on errors."}, - }, - LockMode::LOCK_WHILE_RUNNING, - RecoveryMode::SAVE_AND_RESET - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_RAID_POST, - &NOTIFICATION_RAID_START, - &NOTIFICATION_JOIN_REPORT, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - const LanguageSet& languages = PokemonNameReader::instance().languages(); - size_t host = HOSTING_SWITCH.current_value(); - PLAYERS[0].reset(new TeraFarmerPerConsoleOptions("Switch 0 (Top Left)", languages, host == 0)); - PLAYERS[1].reset(new TeraFarmerPerConsoleOptions("Switch 1 (Top Right)", languages, host == 1)); - PLAYERS[2].reset(new TeraFarmerPerConsoleOptions("Switch 2 (Bottom Left)", languages, host == 2)); - PLAYERS[3].reset(new TeraFarmerPerConsoleOptions("Switch 3 (Bottom Right)", languages, host == 3)); - - PA_ADD_OPTION(HOSTING_SWITCH); - PA_ADD_OPTION(MAX_WINS); - - // General Auto-Hosting Options - PA_ADD_OPTION(HOSTING_MODE); - PA_ADD_OPTION(HOSTING_OPTIONS); - - PA_ADD_OPTION(*PLAYERS[0]); - PA_ADD_OPTION(*PLAYERS[1]); - PA_ADD_OPTION(*PLAYERS[2]); - PA_ADD_OPTION(*PLAYERS[3]); - - PA_ADD_OPTION(ROLLOVER_PREVENTION); -// PA_ADD_OPTION(RECOVERY_MODE); - - // Extended Auto-Hosting Options - PA_ADD_OPTION(BAN_LIST); - PA_ADD_OPTION(JOIN_REPORT); - - PA_ADD_OPTION(NOTIFICATIONS); - - TeraMultiFarmer::on_config_value_changed(this); - - HOSTING_SWITCH.add_listener(*this); - HOSTING_MODE.add_listener(*this); -} -void TeraMultiFarmer::update_active_consoles(size_t switch_count){ - for (size_t c = 0; c < 4; c ++){ - PLAYERS[c]->set_visibility(c < switch_count ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); - } -} -void TeraMultiFarmer::on_config_value_changed(void* object){ - size_t host = HOSTING_SWITCH.current_value(); - for (size_t c = 0; c < 4; c++){ - PLAYERS[c]->set_host(host == c); - } - - ConfigOptionState hosting = HOSTING_MODE == Mode::FARM_ALONE - ? ConfigOptionState::HIDDEN - : ConfigOptionState::ENABLED; - HOSTING_OPTIONS.set_visibility(hosting); - BAN_LIST.set_visibility(hosting); - JOIN_REPORT.set_visibility(hosting); -} - - -void TeraMultiFarmer::reset_host(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - if (ROLLOVER_PREVENTION){ - WallClock now = current_time(); - if (m_last_time_fix == WallClock::min() || now - m_last_time_fix > std::chrono::hours(4)){ - set_time_to_12am_from_home(info, console, context); - m_last_time_fix = now; - } - } - reset_game_from_home(info, console, context, 5 * TICKS_PER_SECOND); -} -void TeraMultiFarmer::reset_joiner(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - reset_game_from_home(info, console, context, 5 * TICKS_PER_SECOND); -} -bool TeraMultiFarmer::run_raid_host(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context){ - TeraMultiFarmer_Descriptor::Stats& stats = env.current_stats(); - TeraFarmerPerConsoleOptions& option = *PLAYERS[console.index()]; - - stats.m_raids++; - env.update_stats(); - bool win = run_tera_battle(env, console, context, option.battle_ai); - - if (win){ - stats.m_wins++; - env.update_stats(); - if (HOSTING_MODE == Mode::HOST_ONLINE){ - exit_tera_win_without_catching(env.program_info(), console, context, 0); - } - reset_host(env.program_info(), console, context); - if (HOSTING_MODE == Mode::HOST_ONLINE){ - connect_to_internet_from_overworld(env.program_info(), console, context); - } - }else{ - stats.m_losses++; - env.update_stats(); - } - - open_raid(console, context); - - return win; -} -void TeraMultiFarmer::run_raid_joiner(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context){ - TeraFarmerPerConsoleOptions& option = *PLAYERS[console.index()]; - - bool win = run_tera_battle(env, console, context, option.battle_ai); - - if (win){ - if (option.catch_on_win){ - exit_tera_win_by_catching(env, console, context, option.language, option.ball_select.slug(), 0); - }else{ - exit_tera_win_without_catching(env.program_info(), console, context, 0); - } - } - - if (RECOVERY_MODE == RecoveryMode::SAVE_AND_RESET){ - pbf_press_button(context, BUTTON_X, 20, 105); - save_game_from_menu(env.program_info(), console, context); - } - - enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); -} -void TeraMultiFarmer::join_lobby( - ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, - size_t host_index, const std::string& normalized_code -){ - if (console.index() == host_index){ - return; - } - - TeraMultiFarmer_Descriptor::Stats& stats = env.current_stats(); - -// cout << "Joining Lobby" << endl; - - bool seen_code_entry = false; -// bool seen_dialog = false; - size_t attempts = 0; - while (true){ -// cout << "Looping..." << endl; - - if (attempts >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to join lobby 3 times.", - console - ); - } - - CodeEntryWatcher code_entry(COLOR_GREEN); - TeraLobbyWatcher lobby(console.logger(), env.normal_inference_dispatcher(), COLOR_RED); - AdvanceDialogWatcher dialog(COLOR_YELLOW); - TeraRaidSearchWatcher raid_search(COLOR_CYAN, std::chrono::seconds(5)); - context.wait_for_all_requests(); - context.wait_for(std::chrono::seconds(3)); - int ret = wait_until( - console, context, std::chrono::seconds(60), - { - code_entry, - lobby, - dialog, - raid_search, - } - ); - switch (ret){ - case 0: - console.log("Detected code entry.", COLOR_RED); - if (seen_code_entry){ - console.log("Failed to enter code! Backing out and trying again...", COLOR_RED); - stats.m_errors++; - attempts++; - pbf_press_button(context, BUTTON_X, 20, 480); - enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); - seen_code_entry = false; - continue; - } - seen_code_entry = true; - enter_code( - console, context, - PLAYERS[console.index()]->keyboard_layout, - normalized_code, - false, - true, - false - ); - context.wait_for(std::chrono::seconds(1)); - continue; - case 1: - console.log("Entered raid lobby!"); - pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); - break; - case 2: - console.log("Detected dialog...", COLOR_ORANGE); -// seen_dialog = true; - pbf_press_button(context, BUTTON_B, 20, 230); - continue; - case 3: -#if 0 - if (!seen_dialog){ - context.wait_for(std::chrono::seconds(1)); - continue; - } -#endif - console.log("Wrong code! Backing out and trying again...", COLOR_RED); - stats.m_errors++; - attempts++; - pbf_press_button(context, BUTTON_B, 20, 230); - enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); - seen_code_entry = false; - continue; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to join lobby.", - console - ); - } - break; - } -} -bool TeraMultiFarmer::run_raid( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - std::string& lobby_code, - std::array, 4>& player_names -){ - TeraMultiFarmer_Descriptor::Stats& stats = env.current_stats(); - size_t host_index = HOSTING_SWITCH.current_value(); - ConsoleHandle& host_console = env.consoles[host_index]; - ProControllerContext host_context(scope, host_console.pro_controller()); - - // Get everyone ready. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - try{ - if (console.index() == host_index){ - TeraCardReader card_detector(COLOR_RED); - if (!card_detector.detect(console.video().snapshot())){ - if (HOSTING_MODE == Mode::HOST_ONLINE){ - connect_to_internet_from_overworld(env.program_info(), console, context); - } - open_raid(console, context); - } - }else{ - enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); - } - }catch (OperationFailedException&){ - stats.m_errors++; - m_reset_required[console.index()] = true; - throw; - } - }); - - if (HOSTING_MODE != Mode::FARM_ALONE){ - BAN_LIST.refresh_online_table(env.logger()); - } - - // Open lobby and read code. - WallClock lobby_start_time; - try{ - TeraLobbyReader lobby_reader(host_console.logger(), env.normal_inference_dispatcher()); - open_hosting_lobby( - env, host_console, host_context, - HOSTING_MODE == Mode::HOST_ONLINE - ? HostingMode::ONLINE_CODED - : HostingMode::LOCAL - ); - lobby_start_time = current_time(); - std::string code = lobby_reader.raid_code( - env.logger(), - env.normal_inference_dispatcher(), - host_console.video().snapshot() - ); - -// code.back() = '0'; - - const char* error = normalize_code(lobby_code, code); - if (error){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to read raid code.", - host_console - ); - } - }catch (OperationFailedException&){ - stats.m_errors++; - m_reset_required[host_index] = true; - throw; - } - -// normalized_code[0] = '0'; - - // Join the lobby with local joiners. If anything throws, we need to reset everyone. - try{ - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - join_lobby(env, console, context, host_index, lobby_code); - }); - }catch (OperationFailedException&){ - stats.m_errors++; - m_reset_required[0] = true; - m_reset_required[1] = true; - m_reset_required[2] = true; - m_reset_required[3] = true; - throw; - } - -#if 1 - // Put it up on auto-host. - if (HOSTING_MODE != Mode::FARM_ALONE){ - send_host_announcement( - env, host_console, - lobby_code, - HOSTING_OPTIONS.SHOW_RAID_CODE, - HOSTING_OPTIONS.DESCRIPTION, - NOTIFICATION_RAID_POST - ); - - TeraLobbyWaiter waiter( - env, host_console, host_context, - (uint8_t)env.consoles.size(), - lobby_code, lobby_start_time, - HOSTING_OPTIONS.LOBBY_WAIT_DELAY, - HOSTING_OPTIONS.START_RAID_PLAYERS, - NOTIFICATION_RAID_START, - BAN_LIST, - JOIN_REPORT - ); - - TeraLobbyWaiter::LobbyResult result = waiter.run_lobby(); - player_names = waiter.names(); - - if (result == TeraLobbyWaiter::LobbyResult::BANNED_PLAYER){ - stats.m_banned++; - m_reset_required[0] = true; - m_reset_required[1] = true; - m_reset_required[2] = true; - m_reset_required[3] = true; - } - if (result != TeraLobbyWaiter::LobbyResult::RAID_STARTED){ - return false; - } - - uint8_t hosts = (uint8_t)env.consoles.size(); - uint8_t players = waiter.last_known_players(); - stats.m_joiners += players - hosts; - if (players == 4){ - stats.m_full++; - }else if (players == hosts){ - stats.m_empty++; - } - } -#endif - - bool win = false; - - // Start the raid. - pbf_mash_button(host_context, BUTTON_A, 10 * TICKS_PER_SECOND); - - // Run the raid. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - try{ - if (console.index() == host_index){ - win = run_raid_host(env, console, context); - }else{ - run_raid_joiner(env, console, context); - } - }catch (OperationFailedException&){ - // Host throws. Reset the host and keep going. - stats.m_errors++; - env.update_stats(); - m_reset_required[console.index()] = true; - throw; - } - }); - - return win; -} -void TeraMultiFarmer::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - size_t host_index = HOSTING_SWITCH.current_value(); - if (host_index >= env.consoles.size()){ - throw UserSetupError(env.logger(), "The host Switch doesn't exist."); - } - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - assert_16_9_720p_min(console.logger(), console); - }); - -// Mode mode = MODE; -// ConsoleHandle& host_console = env.consoles[host_index]; -// BotBaseContext host_context(scope, host_console.botbase()); - - std::string report_name = "PokemonSV-AutoHost-JoinReport-" + now_to_filestring() + ".txt"; - MultiLanguageJoinTracker join_tracker((uint8_t)env.consoles.size()); - - m_reset_required[0] = false; - m_reset_required[1] = false; - m_reset_required[2] = false; - m_reset_required[3] = false; - - if (RECOVERY_MODE == RecoveryMode::SAVE_AND_RESET){ - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - if (console.index() != host_index){ - // Do 2 presses in quick succession in case one drops or is - // needed to connect the controller. - pbf_press_button(context, BUTTON_X, 5, 5); - pbf_press_button(context, BUTTON_X, 20, 105); - save_game_from_menu(env.program_info(), console, context); - }else{ - pbf_press_button(context, BUTTON_L, 5, 5); - } - }); - } - - TeraFailTracker fail_tracker( - env, scope, - NOTIFICATION_ERROR_RECOVERABLE, - HOSTING_OPTIONS.CONSECUTIVE_FAILURE_PAUSE, - HOSTING_OPTIONS.FAILURE_PAUSE_MINUTES - ); - KillSwitchTracker kill_switch(env); - - m_last_time_fix = WallClock::min(); - for (uint16_t wins = 0; wins < MAX_WINS;){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // We don't care about fail tracking if we're alone. No chance of ban. - if (HOSTING_MODE != Mode::FARM_ALONE){ - fail_tracker.on_raid_start(); - } - - // Reset all errored Switches. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - if (!m_reset_required[index]){ - return; - } - if (index == host_index){ - reset_host(env.program_info(), console, context); - }else{ - reset_joiner(env.program_info(), console, context); - } - m_reset_required[index] = false; - }); - - // Check kill-switch now before we go online. - if (HOSTING_MODE == Mode::HOST_ONLINE){ - kill_switch.check_kill_switch(HOSTING_OPTIONS.REMOTE_KILL_SWITCH); - } - - try{ - std::string lobby_code; - std::array, 4> player_names; - bool win = run_raid(env, scope, lobby_code, player_names); - if (win){ - wins++; - } - if (HOSTING_MODE != Mode::FARM_ALONE && JOIN_REPORT.enabled() && (win || !JOIN_REPORT.wins_only)){ - join_tracker.append(player_names, lobby_code); - join_tracker.dump(report_name); - send_program_notification_with_file( - env, - NOTIFICATION_JOIN_REPORT, - Color(0), - "Join Report", - {}, "", - report_name - ); - } - fail_tracker.report_successful_raid(); - }catch (OperationFailedException& e){ - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - if (RECOVERY_MODE != RecoveryMode::SAVE_AND_RESET){ - // Iterate the errored Switches. If a non-host has errored, - // rethrow the exception to stop the program. - for (size_t c = 0; c < 4; c++){ - if (m_reset_required[c] && c != host_index){ - throw; - } - } - } - fail_tracker.report_raid_error(); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Tera Multi-Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +//#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/FastCodeEntry/PokemonSV_CodeEntry.h" +#include "PokemonSV_TeraRoutines.h" +#include "PokemonSV_TeraBattler.h" +#include "PokemonSV_AutoHostTools.h" +#include "PokemonSV_AutoHostLobbyWaiter.h" +#include "PokemonSV_TeraMultiFarmer.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +GeneralHostingOptions::GeneralHostingOptions() + : GroupOption("Hosting Options", LockMode::UNLOCK_WHILE_RUNNING) +{ + PA_ADD_OPTION(LOBBY_WAIT_DELAY); + PA_ADD_OPTION(START_RAID_PLAYERS); + PA_ADD_OPTION(SHOW_RAID_CODE); + PA_ADD_OPTION(DESCRIPTION); + PA_ADD_OPTION(REMOTE_KILL_SWITCH); + PA_ADD_OPTION(CONSECUTIVE_FAILURE_PAUSE); + PA_ADD_OPTION(FAILURE_PAUSE_MINUTES); +} + + + + +TeraFarmerPerConsoleOptions::~TeraFarmerPerConsoleOptions(){ + catch_on_win.remove_listener(*this); +} +TeraFarmerPerConsoleOptions::TeraFarmerPerConsoleOptions(std::string label, const LanguageSet& languages, bool host) + : GroupOption(std::move(label), LockMode::UNLOCK_WHILE_RUNNING) + , is_host_label("This is the host Switch.") + , language("Game Language:", languages, LockMode::LOCK_WHILE_RUNNING, true) + , catch_on_win( + "Catch the " + STRING_POKEMON + ":", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , ball_select( + "Ball Select:", + LockMode::UNLOCK_WHILE_RUNNING, + "poke-ball" + ) +{ + PA_ADD_STATIC(is_host_label); + PA_ADD_OPTION(language); + PA_ADD_OPTION(keyboard_layout); + PA_ADD_OPTION(catch_on_win); + PA_ADD_OPTION(ball_select); + PA_ADD_OPTION(battle_ai); + + set_host(host); + + catch_on_win.add_listener(*this); +} +void TeraFarmerPerConsoleOptions::set_host(bool is_host){ + this->is_host = is_host; + TeraFarmerPerConsoleOptions::on_config_value_changed(this); +} +void TeraFarmerPerConsoleOptions::on_config_value_changed(void* object){ + if (this->is_host){ + is_host_label.set_visibility(ConfigOptionState::ENABLED); + catch_on_win.set_visibility(ConfigOptionState::DISABLED); + ball_select.set_visibility(ConfigOptionState::DISABLED); + }else{ + is_host_label.set_visibility(ConfigOptionState::HIDDEN); + catch_on_win.set_visibility(ConfigOptionState::ENABLED); + ball_select.set_visibility(catch_on_win ? ConfigOptionState::ENABLED : ConfigOptionState::DISABLED); + } +} + + + +TeraMultiFarmer_Descriptor::TeraMultiFarmer_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSV:TeraMultiFarmer", + STRING_POKEMON + " SV", "Tera Multi-Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TeraMultiFarmer.md", + "Farm items and " + STRING_POKEMON + " from your own Tera raid using multiple Switches.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 2, 4, 2 + ) +{} +struct TeraMultiFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : m_raids(m_stats["Raids"]) + , m_empty(m_stats["Empty Raids"]) + , m_full(m_stats["Full Raids"]) + , m_joiners(m_stats["Total Joiners"]) + , m_wins(m_stats["Wins"]) + , m_losses(m_stats["Losses"]) + , m_banned(m_stats["Banned"]) + , m_errors(m_stats["Errors"]) + { + m_display_order.emplace_back("Raids"); + m_display_order.emplace_back("Empty Raids", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Full Raids", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Total Joiners", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Wins"); + m_display_order.emplace_back("Losses"); + m_display_order.emplace_back("Banned", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + std::atomic& m_raids; + std::atomic& m_empty; + std::atomic& m_full; + std::atomic& m_joiners; + std::atomic& m_wins; + std::atomic& m_losses; + std::atomic& m_banned; + std::atomic& m_errors; +}; +std::unique_ptr TeraMultiFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +TeraMultiFarmer::~TeraMultiFarmer(){ + HOSTING_MODE.remove_listener(*this); + HOSTING_SWITCH.remove_listener(*this); +} +TeraMultiFarmer::TeraMultiFarmer() + : HOSTING_SWITCH( + "Host Switch:
This is the Switch that hosts the raid.", + { + {0, "switch0", "Switch 0 (Top Left)"}, + {1, "switch1", "Switch 1 (Top Right)"}, + {2, "switch2", "Switch 2 (Bottom Left)"}, + {3, "switch3", "Switch 3 (Bottom Right)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , MAX_WINS( + "Max Wins:
Stop program after winning this many times.", + LockMode::UNLOCK_WHILE_RUNNING, + 999, 1, 999 + ) + , HOSTING_MODE( + "Mode:", + { + {Mode::FARM_ALONE, "farm-alone", "Farm by yourself."}, + {Mode::HOST_LOCALLY, "host-locally", "Host remaining slots locally."}, + {Mode::HOST_ONLINE, "host-online", "Host remaining slots online."}, + }, + LockMode::LOCK_WHILE_RUNNING, + Mode::FARM_ALONE + ) + , RECOVERY_MODE( + "Recovery Mode:", + { + {RecoveryMode::STOP_ON_ERROR, "stop-on-error", "Stop on any error."}, + {RecoveryMode::SAVE_AND_RESET, "save-and-reset", "Save before each raid. Reset on errors."}, + }, + LockMode::LOCK_WHILE_RUNNING, + RecoveryMode::SAVE_AND_RESET + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_RAID_POST, + &NOTIFICATION_RAID_START, + &NOTIFICATION_JOIN_REPORT, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + const LanguageSet& languages = PokemonNameReader::instance().languages(); + size_t host = HOSTING_SWITCH.current_value(); + PLAYERS[0].reset(new TeraFarmerPerConsoleOptions("Switch 0 (Top Left)", languages, host == 0)); + PLAYERS[1].reset(new TeraFarmerPerConsoleOptions("Switch 1 (Top Right)", languages, host == 1)); + PLAYERS[2].reset(new TeraFarmerPerConsoleOptions("Switch 2 (Bottom Left)", languages, host == 2)); + PLAYERS[3].reset(new TeraFarmerPerConsoleOptions("Switch 3 (Bottom Right)", languages, host == 3)); + + PA_ADD_OPTION(HOSTING_SWITCH); + PA_ADD_OPTION(MAX_WINS); + + // General Auto-Hosting Options + PA_ADD_OPTION(HOSTING_MODE); + PA_ADD_OPTION(HOSTING_OPTIONS); + + PA_ADD_OPTION(*PLAYERS[0]); + PA_ADD_OPTION(*PLAYERS[1]); + PA_ADD_OPTION(*PLAYERS[2]); + PA_ADD_OPTION(*PLAYERS[3]); + + PA_ADD_OPTION(ROLLOVER_PREVENTION); +// PA_ADD_OPTION(RECOVERY_MODE); + + // Extended Auto-Hosting Options + PA_ADD_OPTION(BAN_LIST); + PA_ADD_OPTION(JOIN_REPORT); + + PA_ADD_OPTION(NOTIFICATIONS); + + TeraMultiFarmer::on_config_value_changed(this); + + HOSTING_SWITCH.add_listener(*this); + HOSTING_MODE.add_listener(*this); +} +void TeraMultiFarmer::update_active_consoles(size_t switch_count){ + for (size_t c = 0; c < 4; c ++){ + PLAYERS[c]->set_visibility(c < switch_count ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); + } +} +void TeraMultiFarmer::on_config_value_changed(void* object){ + size_t host = HOSTING_SWITCH.current_value(); + for (size_t c = 0; c < 4; c++){ + PLAYERS[c]->set_host(host == c); + } + + ConfigOptionState hosting = HOSTING_MODE == Mode::FARM_ALONE + ? ConfigOptionState::HIDDEN + : ConfigOptionState::ENABLED; + HOSTING_OPTIONS.set_visibility(hosting); + BAN_LIST.set_visibility(hosting); + JOIN_REPORT.set_visibility(hosting); +} + + +void TeraMultiFarmer::reset_host(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + if (ROLLOVER_PREVENTION){ + WallClock now = current_time(); + if (m_last_time_fix == WallClock::min() || now - m_last_time_fix > std::chrono::hours(4)){ + set_time_to_12am_from_home(info, console, context); + m_last_time_fix = now; + } + } + reset_game_from_home(info, console, context, 5 * TICKS_PER_SECOND); +} +void TeraMultiFarmer::reset_joiner(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + reset_game_from_home(info, console, context, 5 * TICKS_PER_SECOND); +} +bool TeraMultiFarmer::run_raid_host(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context){ + TeraMultiFarmer_Descriptor::Stats& stats = env.current_stats(); + TeraFarmerPerConsoleOptions& option = *PLAYERS[console.index()]; + + stats.m_raids++; + env.update_stats(); + bool win = run_tera_battle(env, console, context, option.battle_ai); + + if (win){ + stats.m_wins++; + env.update_stats(); + if (HOSTING_MODE == Mode::HOST_ONLINE){ + exit_tera_win_without_catching(env.program_info(), console, context, 0); + } + reset_host(env.program_info(), console, context); + if (HOSTING_MODE == Mode::HOST_ONLINE){ + connect_to_internet_from_overworld(env.program_info(), console, context); + } + }else{ + stats.m_losses++; + env.update_stats(); + } + + open_raid(console, context); + + return win; +} +void TeraMultiFarmer::run_raid_joiner(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context){ + TeraFarmerPerConsoleOptions& option = *PLAYERS[console.index()]; + + bool win = run_tera_battle(env, console, context, option.battle_ai); + + if (win){ + if (option.catch_on_win){ + exit_tera_win_by_catching(env, console, context, option.language, option.ball_select.slug(), 0); + }else{ + exit_tera_win_without_catching(env.program_info(), console, context, 0); + } + } + + if (RECOVERY_MODE == RecoveryMode::SAVE_AND_RESET){ + pbf_press_button(context, BUTTON_X, 20, 105); + save_game_from_menu(env.program_info(), console, context); + } + + enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); +} +void TeraMultiFarmer::join_lobby( + ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, + size_t host_index, const std::string& normalized_code +){ + if (console.index() == host_index){ + return; + } + + TeraMultiFarmer_Descriptor::Stats& stats = env.current_stats(); + +// cout << "Joining Lobby" << endl; + + bool seen_code_entry = false; +// bool seen_dialog = false; + size_t attempts = 0; + while (true){ +// cout << "Looping..." << endl; + + if (attempts >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to join lobby 3 times.", + console + ); + } + + CodeEntryWatcher code_entry(COLOR_GREEN); + TeraLobbyWatcher lobby(console.logger(), env.normal_inference_dispatcher(), COLOR_RED); + AdvanceDialogWatcher dialog(COLOR_YELLOW); + TeraRaidSearchWatcher raid_search(COLOR_CYAN, std::chrono::seconds(5)); + context.wait_for_all_requests(); + context.wait_for(std::chrono::seconds(3)); + int ret = wait_until( + console, context, std::chrono::seconds(60), + { + code_entry, + lobby, + dialog, + raid_search, + } + ); + switch (ret){ + case 0: + console.log("Detected code entry.", COLOR_RED); + if (seen_code_entry){ + console.log("Failed to enter code! Backing out and trying again...", COLOR_RED); + stats.m_errors++; + attempts++; + pbf_press_button(context, BUTTON_X, 20, 480); + enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); + seen_code_entry = false; + continue; + } + seen_code_entry = true; + enter_code( + console, context, + PLAYERS[console.index()]->keyboard_layout, + normalized_code, + false, + true, + false + ); + context.wait_for(std::chrono::seconds(1)); + continue; + case 1: + console.log("Entered raid lobby!"); + pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); + break; + case 2: + console.log("Detected dialog...", COLOR_ORANGE); +// seen_dialog = true; + pbf_press_button(context, BUTTON_B, 20, 230); + continue; + case 3: +#if 0 + if (!seen_dialog){ + context.wait_for(std::chrono::seconds(1)); + continue; + } +#endif + console.log("Wrong code! Backing out and trying again...", COLOR_RED); + stats.m_errors++; + attempts++; + pbf_press_button(context, BUTTON_B, 20, 230); + enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); + seen_code_entry = false; + continue; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to join lobby.", + console + ); + } + break; + } +} +bool TeraMultiFarmer::run_raid( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + std::string& lobby_code, + std::array, 4>& player_names +){ + TeraMultiFarmer_Descriptor::Stats& stats = env.current_stats(); + size_t host_index = HOSTING_SWITCH.current_value(); + ConsoleHandle& host_console = env.consoles[host_index]; + ProControllerContext host_context(scope, host_console.pro_controller()); + + // Get everyone ready. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + try{ + if (console.index() == host_index){ + TeraCardReader card_detector(COLOR_RED); + if (!card_detector.detect(console.video().snapshot())){ + if (HOSTING_MODE == Mode::HOST_ONLINE){ + connect_to_internet_from_overworld(env.program_info(), console, context); + } + open_raid(console, context); + } + }else{ + enter_tera_search(env.program_info(), console, context, HOSTING_MODE == Mode::HOST_ONLINE); + } + }catch (OperationFailedException&){ + stats.m_errors++; + m_reset_required[console.index()] = true; + throw; + } + }); + + if (HOSTING_MODE != Mode::FARM_ALONE){ + BAN_LIST.refresh_online_table(env.logger()); + } + + // Open lobby and read code. + WallClock lobby_start_time; + try{ + TeraLobbyReader lobby_reader(host_console.logger(), env.normal_inference_dispatcher()); + open_hosting_lobby( + env, host_console, host_context, + HOSTING_MODE == Mode::HOST_ONLINE + ? HostingMode::ONLINE_CODED + : HostingMode::LOCAL + ); + lobby_start_time = current_time(); + std::string code = lobby_reader.raid_code( + env.logger(), + env.normal_inference_dispatcher(), + host_console.video().snapshot() + ); + +// code.back() = '0'; + + const char* error = normalize_code(lobby_code, code); + if (error){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to read raid code.", + host_console + ); + } + }catch (OperationFailedException&){ + stats.m_errors++; + m_reset_required[host_index] = true; + throw; + } + +// normalized_code[0] = '0'; + + // Join the lobby with local joiners. If anything throws, we need to reset everyone. + try{ + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + join_lobby(env, console, context, host_index, lobby_code); + }); + }catch (OperationFailedException&){ + stats.m_errors++; + m_reset_required[0] = true; + m_reset_required[1] = true; + m_reset_required[2] = true; + m_reset_required[3] = true; + throw; + } + +#if 1 + // Put it up on auto-host. + if (HOSTING_MODE != Mode::FARM_ALONE){ + send_host_announcement( + env, host_console, + lobby_code, + HOSTING_OPTIONS.SHOW_RAID_CODE, + HOSTING_OPTIONS.DESCRIPTION, + NOTIFICATION_RAID_POST + ); + + TeraLobbyWaiter waiter( + env, host_console, host_context, + (uint8_t)env.consoles.size(), + lobby_code, lobby_start_time, + HOSTING_OPTIONS.LOBBY_WAIT_DELAY, + HOSTING_OPTIONS.START_RAID_PLAYERS, + NOTIFICATION_RAID_START, + BAN_LIST, + JOIN_REPORT + ); + + TeraLobbyWaiter::LobbyResult result = waiter.run_lobby(); + player_names = waiter.names(); + + if (result == TeraLobbyWaiter::LobbyResult::BANNED_PLAYER){ + stats.m_banned++; + m_reset_required[0] = true; + m_reset_required[1] = true; + m_reset_required[2] = true; + m_reset_required[3] = true; + } + if (result != TeraLobbyWaiter::LobbyResult::RAID_STARTED){ + return false; + } + + uint8_t hosts = (uint8_t)env.consoles.size(); + uint8_t players = waiter.last_known_players(); + stats.m_joiners += players - hosts; + if (players == 4){ + stats.m_full++; + }else if (players == hosts){ + stats.m_empty++; + } + } +#endif + + bool win = false; + + // Start the raid. + pbf_mash_button(host_context, BUTTON_A, 10 * TICKS_PER_SECOND); + + // Run the raid. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + try{ + if (console.index() == host_index){ + win = run_raid_host(env, console, context); + }else{ + run_raid_joiner(env, console, context); + } + }catch (OperationFailedException&){ + // Host throws. Reset the host and keep going. + stats.m_errors++; + env.update_stats(); + m_reset_required[console.index()] = true; + throw; + } + }); + + return win; +} +void TeraMultiFarmer::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + size_t host_index = HOSTING_SWITCH.current_value(); + if (host_index >= env.consoles.size()){ + throw UserSetupError(env.logger(), "The host Switch doesn't exist."); + } + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + assert_16_9_720p_min(console.logger(), console); + }); + +// Mode mode = MODE; +// ConsoleHandle& host_console = env.consoles[host_index]; +// BotBaseContext host_context(scope, host_console.botbase()); + + std::string report_name = "PokemonSV-AutoHost-JoinReport-" + now_to_filestring() + ".txt"; + MultiLanguageJoinTracker join_tracker((uint8_t)env.consoles.size()); + + m_reset_required[0] = false; + m_reset_required[1] = false; + m_reset_required[2] = false; + m_reset_required[3] = false; + + if (RECOVERY_MODE == RecoveryMode::SAVE_AND_RESET){ + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + if (console.index() != host_index){ + // Do 2 presses in quick succession in case one drops or is + // needed to connect the controller. + pbf_press_button(context, BUTTON_X, 5, 5); + pbf_press_button(context, BUTTON_X, 20, 105); + save_game_from_menu(env.program_info(), console, context); + }else{ + pbf_press_button(context, BUTTON_L, 5, 5); + } + }); + } + + TeraFailTracker fail_tracker( + env, scope, + NOTIFICATION_ERROR_RECOVERABLE, + HOSTING_OPTIONS.CONSECUTIVE_FAILURE_PAUSE, + HOSTING_OPTIONS.FAILURE_PAUSE_MINUTES + ); + KillSwitchTracker kill_switch(env); + + m_last_time_fix = WallClock::min(); + for (uint16_t wins = 0; wins < MAX_WINS;){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // We don't care about fail tracking if we're alone. No chance of ban. + if (HOSTING_MODE != Mode::FARM_ALONE){ + fail_tracker.on_raid_start(); + } + + // Reset all errored Switches. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + if (!m_reset_required[index]){ + return; + } + if (index == host_index){ + reset_host(env.program_info(), console, context); + }else{ + reset_joiner(env.program_info(), console, context); + } + m_reset_required[index] = false; + }); + + // Check kill-switch now before we go online. + if (HOSTING_MODE == Mode::HOST_ONLINE){ + kill_switch.check_kill_switch(HOSTING_OPTIONS.REMOTE_KILL_SWITCH); + } + + try{ + std::string lobby_code; + std::array, 4> player_names; + bool win = run_raid(env, scope, lobby_code, player_names); + if (win){ + wins++; + } + if (HOSTING_MODE != Mode::FARM_ALONE && JOIN_REPORT.enabled() && (win || !JOIN_REPORT.wins_only)){ + join_tracker.append(player_names, lobby_code); + join_tracker.dump(report_name); + send_program_notification_with_file( + env, + NOTIFICATION_JOIN_REPORT, + Color(0), + "Join Report", + {}, "", + report_name + ); + } + fail_tracker.report_successful_raid(); + }catch (OperationFailedException& e){ + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + if (RECOVERY_MODE != RecoveryMode::SAVE_AND_RESET){ + // Iterate the errored Switches. If a non-host has errored, + // rethrow the exception to stop the program. + for (size_t c = 0; c < 4; c++){ + if (m_reset_required[c] && c != host_index){ + throw; + } + } + } + fail_tracker.report_raid_error(); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h index 97bf13aa2b..62fa146223 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraMultiFarmer.h @@ -1,149 +1,149 @@ -/* Tera Multi-Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraMultiFarmer_H -#define PokemonAutomation_PokemonSV_TeraMultiFarmer_H - -#include "Common/Cpp/Time.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" -#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" -#include "PokemonSV/Options/PokemonSV_PlayerList.h" -#include "PokemonSV_AutoHostTools.h" -#include "PokemonSV_JoinTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -class GeneralHostingOptions : public GroupOption{ -public: - GeneralHostingOptions(); - - LobbyWaitDelay LOBBY_WAIT_DELAY; - StartRaidPlayers START_RAID_PLAYERS; - ShowRaidCode SHOW_RAID_CODE; - AutoHostDescription DESCRIPTION; - RemoteKillSwitch REMOTE_KILL_SWITCH; - ConsecutiveFailurePause CONSECUTIVE_FAILURE_PAUSE; - FailurePauseMinutes FAILURE_PAUSE_MINUTES; -}; - - - -class TeraFarmerPerConsoleOptions : public GroupOption, public ConfigOption::Listener{ -public: - ~TeraFarmerPerConsoleOptions(); - TeraFarmerPerConsoleOptions(std::string label, const LanguageSet& languages, bool host); - - void set_host(bool is_host); - virtual void on_config_value_changed(void* object) override; - -public: - bool is_host; - StaticTextOption is_host_label; - OCR::LanguageOCROption language; - KeyboardLayoutOption keyboard_layout; - - BooleanCheckBoxOption catch_on_win; - PokemonSwSh::PokemonBallSelectOption ball_select; - - TeraAIOption battle_ai; -}; - - - -class TeraMultiFarmer_Descriptor : public MultiSwitchProgramDescriptor{ -public: - TeraMultiFarmer_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - -class TeraMultiFarmer : public MultiSwitchProgramInstance, private ConfigOption::Listener{ -public: - ~TeraMultiFarmer(); - TeraMultiFarmer(); - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - - virtual void on_config_value_changed(void* object) override; - -private: - void reset_host(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); - void reset_joiner(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); - - bool run_raid_host(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context); - void run_raid_joiner(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context); - void join_lobby( - ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, - size_t host_index, const std::string& normalized_code - ); - - bool run_raid( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - std::string& lobby_code, - std::array, 4>& player_names - ); - -private: - IntegerEnumDropdownOption HOSTING_SWITCH; - SimpleIntegerOption MAX_WINS; - - enum class Mode{ - FARM_ALONE, - HOST_LOCALLY, - HOST_ONLINE, - }; - EnumDropdownOption HOSTING_MODE; - - GeneralHostingOptions HOSTING_OPTIONS; - - // Per-console Options - std::unique_ptr PLAYERS[4]; - - enum class RecoveryMode{ - STOP_ON_ERROR, - SAVE_AND_RESET, - }; - EnumDropdownOption RECOVERY_MODE; - RolloverPrevention ROLLOVER_PREVENTION; - - // Extended Auto-host Options - RaidPlayerBanList BAN_LIST; - RaidJoinReportOption JOIN_REPORT; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - RaidPostNotification NOTIFICATION_RAID_POST; - RaidStartNotification NOTIFICATION_RAID_START; - JoinReportNotification NOTIFICATION_JOIN_REPORT; - EventNotificationsOption NOTIFICATIONS; - - WallClock m_last_time_fix; -// std::atomic m_raid_error; - bool m_reset_required[4]; -}; - - - - -} -} -} -#endif +/* Tera Multi-Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraMultiFarmer_H +#define PokemonAutomation_PokemonSV_TeraMultiFarmer_H + +#include "Common/Cpp/Time.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_CodeEntrySettingsOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" +#include "PokemonSV/Options/PokemonSV_AutoHostOptions.h" +#include "PokemonSV/Options/PokemonSV_PlayerList.h" +#include "PokemonSV_AutoHostTools.h" +#include "PokemonSV_JoinTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +class GeneralHostingOptions : public GroupOption{ +public: + GeneralHostingOptions(); + + LobbyWaitDelay LOBBY_WAIT_DELAY; + StartRaidPlayers START_RAID_PLAYERS; + ShowRaidCode SHOW_RAID_CODE; + AutoHostDescription DESCRIPTION; + RemoteKillSwitch REMOTE_KILL_SWITCH; + ConsecutiveFailurePause CONSECUTIVE_FAILURE_PAUSE; + FailurePauseMinutes FAILURE_PAUSE_MINUTES; +}; + + + +class TeraFarmerPerConsoleOptions : public GroupOption, public ConfigOption::Listener{ +public: + ~TeraFarmerPerConsoleOptions(); + TeraFarmerPerConsoleOptions(std::string label, const LanguageSet& languages, bool host); + + void set_host(bool is_host); + virtual void on_config_value_changed(void* object) override; + +public: + bool is_host; + StaticTextOption is_host_label; + OCR::LanguageOCROption language; + KeyboardLayoutOption keyboard_layout; + + BooleanCheckBoxOption catch_on_win; + PokemonSwSh::PokemonBallSelectOption ball_select; + + TeraAIOption battle_ai; +}; + + + +class TeraMultiFarmer_Descriptor : public MultiSwitchProgramDescriptor{ +public: + TeraMultiFarmer_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + +class TeraMultiFarmer : public MultiSwitchProgramInstance, private ConfigOption::Listener{ +public: + ~TeraMultiFarmer(); + TeraMultiFarmer(); + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + + virtual void on_config_value_changed(void* object) override; + +private: + void reset_host(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); + void reset_joiner(const ProgramInfo& info, ConsoleHandle& console, ProControllerContext& context); + + bool run_raid_host(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context); + void run_raid_joiner(ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context); + void join_lobby( + ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, + size_t host_index, const std::string& normalized_code + ); + + bool run_raid( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + std::string& lobby_code, + std::array, 4>& player_names + ); + +private: + IntegerEnumDropdownOption HOSTING_SWITCH; + SimpleIntegerOption MAX_WINS; + + enum class Mode{ + FARM_ALONE, + HOST_LOCALLY, + HOST_ONLINE, + }; + EnumDropdownOption HOSTING_MODE; + + GeneralHostingOptions HOSTING_OPTIONS; + + // Per-console Options + std::unique_ptr PLAYERS[4]; + + enum class RecoveryMode{ + STOP_ON_ERROR, + SAVE_AND_RESET, + }; + EnumDropdownOption RECOVERY_MODE; + RolloverPrevention ROLLOVER_PREVENTION; + + // Extended Auto-host Options + RaidPlayerBanList BAN_LIST; + RaidJoinReportOption JOIN_REPORT; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + RaidPostNotification NOTIFICATION_RAID_POST; + RaidStartNotification NOTIFICATION_RAID_START; + JoinReportNotification NOTIFICATION_JOIN_REPORT; + EventNotificationsOption NOTIFICATIONS; + + WallClock m_last_time_fix; +// std::atomic m_raid_error; + bool m_reset_required[4]; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.cpp index e30a416516..7c8a825cc8 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.cpp @@ -1,246 +1,246 @@ -/* Tera Roller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV_TeraRoller.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -TeraRoller_Descriptor::TeraRoller_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:TeraRoller", - STRING_POKEMON + " SV", "Tera Roller", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TeraRoller.md", - "Roll Tera raids to find shiny " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -struct TeraRoller_Descriptor::Stats : public StatsTracker{ - Stats() - : m_skips(m_stats["Date Skips"]) - , m_resets(m_stats["Resets"]) - , m_raids(m_stats["Raids"]) - , m_skipped(m_stats["Skipped"]) - , m_errors(m_stats["Errors"]) - , m_shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Date Skips"); - m_display_order.emplace_back("Resets"); - m_display_order.emplace_back("Raids"); - m_display_order.emplace_back("Skipped"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - std::atomic& m_skips; - std::atomic& m_resets; - std::atomic& m_raids; - std::atomic& m_skipped; - std::atomic& m_errors; - std::atomic& m_shinies; -}; -std::unique_ptr TeraRoller_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - - -TeraRoller::TeraRoller() - : FILTER0(7, false) - , CHECK_ONLY_FIRST( - "Check Only the First Pokédex Page:
Reduce time per reset at the expense of not checking repeated encounters.", - LockMode::UNLOCK_WHILE_RUNNING, - false - ) - , PERIODIC_RESET( - "Periodic Game Reset:
Reset the game after this many skips. This clears up the framerate bug.", - LockMode::UNLOCK_WHILE_RUNNING, - 20, 0, 100 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , m_notification_noop("", false, false) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(FILTER0); - PA_ADD_OPTION(CHECK_ONLY_FIRST); - PA_ADD_OPTION(PERIODIC_RESET); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void TeraRoller::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - TeraRoller_Descriptor::Stats& stats = env.current_stats(); - - // Connect the controller - pbf_press_button(context, BUTTON_L, 10, 10); - - bool first = true; - uint32_t skip_counter = 0; - - while (true){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (!first){ - day_skip_from_overworld(env.console, context); - pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); - context.wait_for_all_requests(); - stats.m_skips++; - skip_counter++; - env.update_stats(); - } - first = false; - - uint8_t reset_period = PERIODIC_RESET; - if (reset_period != 0 && skip_counter >= reset_period){ - env.log("Resetting game to clear framerate."); - save_game_from_overworld(env.program_info(), env.console, context); - reset_game(env.program_info(), env.console, context); - skip_counter = 0; - stats.m_resets++; - } - - TeraRaidData raid_data; - TeraRollFilter::FilterResult result = FILTER0.run_filter( - env.program_info(), env.console, context, - raid_data - ); - switch (result){ - case TeraRollFilter::FilterResult::NO_RAID: - continue; - case TeraRollFilter::FilterResult::FAILED: - stats.m_raids++; - stats.m_skipped++; - continue; - case TeraRollFilter::FilterResult::PASSED: - stats.m_raids++; - break; - } - - - // Enter tera raid battle alone - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_mash_button(context, BUTTON_A, 250); - context.wait_for_all_requests(); -// overlay_set.clear(); - env.console.log("Entering tera raid..."); - env.console.overlay().add_log("Entering tera raid...", COLOR_WHITE); - - // Run away from the tera raid battle - run_from_tera_battle(env.program_info(), env.console, context); - context.wait_for_all_requests(); - - env.console.log("Checking if tera raid is shiny..."); - env.console.overlay().add_log("Checking Pokédex...", COLOR_WHITE); - open_pokedex_from_overworld(env.program_info(), env.console, context); - open_recently_battled_from_pokedex(env.program_info(), env.console, context); - - // Since encountering the same species within 5 encounters is possible, - // loop through all 5 candidates of recently battled pokemon for shinies - for (int i = 0; i < 5; i++){ - BoxShinyWatcher shiny_detector(COLOR_YELLOW, {0.187, 0.196, 0.028, 0.046}); - context.wait_for_all_requests(); - - int ret = wait_until( - env.console, context, - std::chrono::seconds(1), - {shiny_detector} - ); - - if (ret == 0){ - env.console.log("Found a shiny tera raid!", COLOR_GREEN); - env.console.overlay().add_log("Shiny!", COLOR_GREEN); - stats.m_shinies += 1; - - pbf_wait(context, 500); // Wait enough time for the Pokemon sprite to load - context.wait_for_all_requests(); - send_encounter_notification( - env, - m_notification_noop, - NOTIFICATION_SHINY, - false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), - env.console.video().snapshot() - ); - - leave_phone_to_overworld(env.program_info(), env.console, context); - save_game_from_overworld(env.program_info(), env.console, context); - - throw ProgramFinishedException(); - } - - if (CHECK_ONLY_FIRST) { // Check only the first Pokédex page - break; - }else if (i < 4){ // Check the remaining four Pokédex pages - pbf_press_dpad(context, DPAD_RIGHT, 10, 20); - } - } - - env.console.log("Not a shiny tera raid..."); - env.console.overlay().add_log("Not shiny", COLOR_WHITE); - leave_phone_to_overworld(env.program_info(), env.console, context); - - pbf_wait(context, 50); - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - - - - - - -} -} -} +/* Tera Roller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxShinyDetector.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV_TeraRoller.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +TeraRoller_Descriptor::TeraRoller_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:TeraRoller", + STRING_POKEMON + " SV", "Tera Roller", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TeraRoller.md", + "Roll Tera raids to find shiny " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +struct TeraRoller_Descriptor::Stats : public StatsTracker{ + Stats() + : m_skips(m_stats["Date Skips"]) + , m_resets(m_stats["Resets"]) + , m_raids(m_stats["Raids"]) + , m_skipped(m_stats["Skipped"]) + , m_errors(m_stats["Errors"]) + , m_shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Date Skips"); + m_display_order.emplace_back("Resets"); + m_display_order.emplace_back("Raids"); + m_display_order.emplace_back("Skipped"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + std::atomic& m_skips; + std::atomic& m_resets; + std::atomic& m_raids; + std::atomic& m_skipped; + std::atomic& m_errors; + std::atomic& m_shinies; +}; +std::unique_ptr TeraRoller_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + + +TeraRoller::TeraRoller() + : FILTER0(7, false) + , CHECK_ONLY_FIRST( + "Check Only the First Pokédex Page:
Reduce time per reset at the expense of not checking repeated encounters.", + LockMode::UNLOCK_WHILE_RUNNING, + false + ) + , PERIODIC_RESET( + "Periodic Game Reset:
Reset the game after this many skips. This clears up the framerate bug.", + LockMode::UNLOCK_WHILE_RUNNING, + 20, 0, 100 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , m_notification_noop("", false, false) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(FILTER0); + PA_ADD_OPTION(CHECK_ONLY_FIRST); + PA_ADD_OPTION(PERIODIC_RESET); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void TeraRoller::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + TeraRoller_Descriptor::Stats& stats = env.current_stats(); + + // Connect the controller + pbf_press_button(context, BUTTON_L, 10, 10); + + bool first = true; + uint32_t skip_counter = 0; + + while (true){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (!first){ + day_skip_from_overworld(env.console, context); + pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); + context.wait_for_all_requests(); + stats.m_skips++; + skip_counter++; + env.update_stats(); + } + first = false; + + uint8_t reset_period = PERIODIC_RESET; + if (reset_period != 0 && skip_counter >= reset_period){ + env.log("Resetting game to clear framerate."); + save_game_from_overworld(env.program_info(), env.console, context); + reset_game(env.program_info(), env.console, context); + skip_counter = 0; + stats.m_resets++; + } + + TeraRaidData raid_data; + TeraRollFilter::FilterResult result = FILTER0.run_filter( + env.program_info(), env.console, context, + raid_data + ); + switch (result){ + case TeraRollFilter::FilterResult::NO_RAID: + continue; + case TeraRollFilter::FilterResult::FAILED: + stats.m_raids++; + stats.m_skipped++; + continue; + case TeraRollFilter::FilterResult::PASSED: + stats.m_raids++; + break; + } + + + // Enter tera raid battle alone + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_mash_button(context, BUTTON_A, 250); + context.wait_for_all_requests(); +// overlay_set.clear(); + env.console.log("Entering tera raid..."); + env.console.overlay().add_log("Entering tera raid...", COLOR_WHITE); + + // Run away from the tera raid battle + run_from_tera_battle(env.program_info(), env.console, context); + context.wait_for_all_requests(); + + env.console.log("Checking if tera raid is shiny..."); + env.console.overlay().add_log("Checking Pokédex...", COLOR_WHITE); + open_pokedex_from_overworld(env.program_info(), env.console, context); + open_recently_battled_from_pokedex(env.program_info(), env.console, context); + + // Since encountering the same species within 5 encounters is possible, + // loop through all 5 candidates of recently battled pokemon for shinies + for (int i = 0; i < 5; i++){ + BoxShinyWatcher shiny_detector(COLOR_YELLOW, {0.187, 0.196, 0.028, 0.046}); + context.wait_for_all_requests(); + + int ret = wait_until( + env.console, context, + std::chrono::seconds(1), + {shiny_detector} + ); + + if (ret == 0){ + env.console.log("Found a shiny tera raid!", COLOR_GREEN); + env.console.overlay().add_log("Shiny!", COLOR_GREEN); + stats.m_shinies += 1; + + pbf_wait(context, 500); // Wait enough time for the Pokemon sprite to load + context.wait_for_all_requests(); + send_encounter_notification( + env, + m_notification_noop, + NOTIFICATION_SHINY, + false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), + env.console.video().snapshot() + ); + + leave_phone_to_overworld(env.program_info(), env.console, context); + save_game_from_overworld(env.program_info(), env.console, context); + + throw ProgramFinishedException(); + } + + if (CHECK_ONLY_FIRST) { // Check only the first Pokédex page + break; + }else if (i < 4){ // Check the remaining four Pokédex pages + pbf_press_dpad(context, DPAD_RIGHT, 10, 20); + } + } + + env.console.log("Not a shiny tera raid..."); + env.console.overlay().add_log("Not shiny", COLOR_WHITE); + leave_phone_to_overworld(env.program_info(), env.console, context); + + pbf_wait(context, 50); + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.h index 649d78ed4b..82a456ae47 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoller.h @@ -1,59 +1,59 @@ -/* Tera Roller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraRoller_H -#define PokemonAutomation_PokemonSV_TeraRoller_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSV/Options/PokemonSV_TeraRollFilter.h" - -namespace PokemonAutomation{ - struct VideoSnapshot; -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class TeraRoller_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TeraRoller_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class TeraRoller : public SingleSwitchProgramInstance{ -public: - TeraRoller(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - TeraRollFilter FILTER0; - - BooleanCheckBoxOption CHECK_ONLY_FIRST; - SimpleIntegerOption PERIODIC_RESET; - - // Notifications - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption m_notification_noop; - EventNotificationsOption NOTIFICATIONS; - -}; - - - - -} -} -} -#endif +/* Tera Roller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraRoller_H +#define PokemonAutomation_PokemonSV_TeraRoller_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSV/Options/PokemonSV_TeraRollFilter.h" + +namespace PokemonAutomation{ + struct VideoSnapshot; +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class TeraRoller_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TeraRoller_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class TeraRoller : public SingleSwitchProgramInstance{ +public: + TeraRoller(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + TeraRollFilter FILTER0; + + BooleanCheckBoxOption CHECK_ONLY_FIRST; + SimpleIntegerOption PERIODIC_RESET; + + // Notifications + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption m_notification_noop; + EventNotificationsOption NOTIFICATIONS; + +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp index cc44a732be..a8561d746e 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.cpp @@ -1,756 +1,756 @@ -/* Tera Exit Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/FrozenImageDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" -#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" -#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" -#include "PokemonSV/Inference/PokemonSV_PokePortalDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h" -#include "PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h" -#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" -#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" -#include "PokemonSV_TeraRoutines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -bool open_raid(VideoStream& stream, ProControllerContext& context){ - stream.log("Opening raid..."); - while (true){ - TeraCardWatcher card_detector(COLOR_RED); - AdvanceDialogWatcher dialog(COLOR_YELLOW); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - // Do 2 presses in quick succession in case one drops or is - // needed to connect the controller. - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_press_button(context, BUTTON_A, 20, 355); - }, - { - card_detector, - dialog, - } - ); - switch (ret){ - case 0: - stream.log("Tera raid found!", COLOR_BLUE); - return true; - case 1: - stream.log("Detect possible uncatchable dialog...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - default: - stream.log("No Tera raid found.", COLOR_ORANGE); - return false; - } - } -} -void close_raid(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Closing raid..."); - - WallClock start = current_time(); - while (true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - info, stream, "CloseRaidFailed", - "Failed to return to overworld after 5 minutes." - ); - } - - TeraCardWatcher card_detector(COLOR_RED); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {card_detector, overworld} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 1: - stream.log("Detected overworld."); - return; - default: - dump_image_and_throw_recoverable_exception(info, stream, "CloseRaidFailed", - "close_raid(): No recognized state after 60 seconds."); - } - } -} - - - -void open_hosting_lobby( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - HostingMode mode -){ - bool recovery_mode = false; - WallClock start = current_time(); - while (true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(2)){ - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "OpenLobbyFailed", - "Unable to open Tera lobby after 2 minutes." - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - if (recovery_mode){ - context.wait_for_all_requests(); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_B, 20, 980); - }, - {overworld} - ); - if (ret < 0){ - continue; - } - stream.log("Detected overworld. Recovery finished."); - recovery_mode = true; - } - -// AdvanceDialogWatcher dialog(COLOR_GREEN); - TeraCardWatcher card_detector(COLOR_YELLOW); - TeraLobbyWatcher lobby(stream.logger(), env.normal_inference_dispatcher(), COLOR_BLUE); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - { - overworld, -// dialog, - card_detector, - {lobby, std::chrono::milliseconds(500)} - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld."); - recovery_mode = false; - if (!open_raid(stream, context)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "No Tera raid found.", - stream - ); - } - continue; -#if 0 - case 1: - stream.log("Detect possible uncatchable dialog...", COLOR_ORANGE); - pbf_press_button(context, BUTTON_B, 20, 230); - continue; -#endif - case 1: - stream.log("Detected Tera card."); - if (mode != HostingMode::LOCAL){ - pbf_press_button(context, BUTTON_A, 20, 230); - if (mode == HostingMode::ONLINE_EVERYONE){ - pbf_press_dpad(context, DPAD_DOWN, 20, 105); - } - } - pbf_press_button(context, BUTTON_A, 20, 230); - continue; - case 2: - stream.log("Detected Tera lobby."); - return; - default: - stream.log("No state detected after 30 seconds. Backing out...", COLOR_RED); - pbf_press_button(context, BUTTON_B, 20, 230); - recovery_mode = true; - } - } -} - - - - - -void enter_tera_search( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - bool connect_to_internet -){ - WallClock start = current_time(); - bool connected = false; - while (true){ - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - info, stream, "EnterTeraSearchFailed", - "enter_tera_search(): Failed to enter Tera search." - ); - } - - OverworldWatcher overworld(stream.logger(), COLOR_RED); - MainMenuWatcher main_menu(COLOR_YELLOW); - PokePortalWatcher poke_portal(COLOR_GREEN); - TeraRaidSearchWatcher raid_search(COLOR_CYAN); - CodeEntryWatcher code_entry(COLOR_PURPLE); - AdvanceDialogWatcher dialog(COLOR_BLUE); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(30), - { - overworld, - main_menu, - poke_portal, - raid_search, - code_entry, - dialog, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected overworld."); - pbf_press_button(context, BUTTON_X, 20, 105); - continue; - case 1: - stream.log("Detected main menu."); - if (connect_to_internet && !connected){ - connect_to_internet_from_menu(info, stream, context); - connected = true; - continue; - } - if (main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 3)){ - pbf_press_button(context, BUTTON_A, 20, 230); - } - continue; - case 2: - stream.log("Detected Poke Portal."); - if (poke_portal.move_cursor(info, stream, context, 1)){ - pbf_press_button(context, BUTTON_A, 20, 230); - } - continue; - case 3: - stream.log("Detected Tera Raid Search."); - if (raid_search.move_cursor_to_search(info, stream, context)){ - pbf_press_button(context, BUTTON_A, 20, 105); - } - continue; - case 4: - stream.log("Detected Code Entry."); - return; - case 5: - stream.log("Detected Dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - default: - dump_image_and_throw_recoverable_exception( - info, stream, "EnterTeraSearchFailed", - "enter_tera_search(): No recognized state after 30 seconds." - ); - } - } -} - - - - - -void stop_if_enough_rare_items( - VideoStream& stream, ProControllerContext& context, - size_t stop_on_sparkly_items -){ - if (stop_on_sparkly_items == 0){ - return; - } - size_t sparkly_items = SparklyItemDetector::count_sparkly_items(stream, context); - stream.log("Sparkly Items Detected: " + std::to_string(sparkly_items), COLOR_BLUE); - if (sparkly_items >= stop_on_sparkly_items){ - throw_and_log( - stream.logger(), - "Found a raid with " + std::to_string(sparkly_items) + " rare items!", - stream - ); - } -} - - -void exit_tera_win_without_catching( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t stop_on_sparkly_items -){ - stream.log("Exiting raid without catching..."); - - WallClock start = current_time(); - while (true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - info, stream, "ExitTeraWinFailed", - "Failed to return to overworld after 5 minutes." - ); - } - - TeraCatchWatcher catch_menu(COLOR_BLUE); - WhiteButtonWatcher next_button( - COLOR_CYAN, - WhiteButton::ButtonA, - {0.8, 0.93, 0.2, 0.07}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::seconds(1) - ); - AdvanceDialogWatcher dialog(COLOR_YELLOW); - OverworldWatcher overworld(stream.logger(), COLOR_RED); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - {catch_menu, next_button, dialog, overworld} - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected catch prompt."); - catch_menu.move_to_slot(stream, context, 1); -// pbf_press_dpad(context, DPAD_DOWN, 20, 30); - pbf_mash_button(context, BUTTON_A, 30); - pbf_mash_button(context, BUTTON_B, 125); - continue; - case 1: - stream.log("Detected possible (A) Next button."); - stop_if_enough_rare_items(stream, context, stop_on_sparkly_items); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 2: - stream.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - break; - case 3: - stream.log("Detected overworld."); - return; - default: - dump_image_and_throw_recoverable_exception( - info, stream, "ExitTeraWinFailed", - "exit_tera_win_without_catching(): No recognized state after 60 seconds." - ); - } - } -} - - -void exit_tera_win_by_catching( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, - size_t stop_on_sparkly_items -){ - stream.log("Exiting raid with catching..."); - - VideoSnapshot screenshot; - WallClock start = current_time(); - while (true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "ExitTeraWinFailed", - "Failed to return to overworld after 5 minutes." - ); - } - - TeraCatchWatcher catch_menu(COLOR_BLUE); - WhiteButtonWatcher next_button( - COLOR_CYAN, - WhiteButton::ButtonA, - {0.8, 0.93, 0.2, 0.07}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::seconds(1) - ); - AdvanceDialogWatcher advance(COLOR_YELLOW); - PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); - PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); - MainMenuWatcher main_menu(COLOR_BLUE); - OverworldWatcher overworld(stream.logger(), COLOR_RED); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - { - catch_menu, - next_button, - advance, - add_to_party, - nickname, - main_menu, - overworld, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0:{ - stream.log("Detected catch prompt."); - screenshot = stream.video().snapshot(); - - catch_menu.move_to_slot(stream, context, 0); - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - BattleBallReader reader(stream, language); - int quantity = move_to_ball(reader, stream, context, ball_slug); - if (quantity == 0){ - throw_and_log( - stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to find appropriate ball. Did you run out?", - stream - ); - } - if (quantity < 0){ - stream.log("Unable to read ball quantity.", COLOR_RED); - } - pbf_mash_button(context, BUTTON_A, 125); - - continue; - } - case 1: - stream.log("Detected (A) Next button."); - stop_if_enough_rare_items(stream, context, stop_on_sparkly_items); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 2: - stream.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 3: - stream.log("Detected add-to-party prompt."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 4: - stream.log("Detected nickname prompt."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 5: - stream.log("Detected unexpected main menu.", COLOR_RED); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 6: - stream.log("Detected overworld."); - return; - default: - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "ExitTeraWinFailed", - "exit_tera_win_by_catching(): No recognized state after 60 seconds." - ); - } - } -} - - -TeraResult exit_tera_win_by_catching( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, - EventNotificationOption& notification_nonshiny, - EventNotificationOption& notification_shiny, - bool stop_on_shiny, size_t stop_on_sparkly_items, - std::atomic* stat_shinies -){ - stream.log("Exiting raid with catching..."); - - TeraResult result = TeraResult::NO_DETECTION; - VideoSnapshot screenshot; - WallClock start = current_time(); - while (true){ - context.wait_for_all_requests(); - if (current_time() - start > std::chrono::minutes(5)){ - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "ExitTeraWinFailed", - "Failed to return to overworld after 5 minutes." - ); - } - - TeraCatchWatcher catch_menu(COLOR_BLUE); - WhiteButtonWatcher next_button( - COLOR_CYAN, - WhiteButton::ButtonA, - {0.8, 0.93, 0.2, 0.07}, - WhiteButtonWatcher::FinderType::PRESENT, - std::chrono::seconds(1) - ); - AdvanceDialogWatcher advance(COLOR_YELLOW); - PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); - PromptDialogWatcher view_summary(COLOR_PURPLE, {0.500, 0.470, 0.400, 0.100}); - PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); - PokemonSummaryWatcher summary(COLOR_MAGENTA); - MainMenuWatcher main_menu(COLOR_BLUE); - OverworldWatcher overworld(stream.logger(), COLOR_RED); - context.wait_for_all_requests(); - int ret = wait_until( - stream, context, - std::chrono::seconds(60), - { - catch_menu, - next_button, - advance, - add_to_party, - view_summary, - nickname, - summary, - main_menu, - overworld, - } - ); - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0:{ - stream.log("Detected catch prompt."); - screenshot = stream.video().snapshot(); - - catch_menu.move_to_slot(stream, context, 0); - pbf_press_button(context, BUTTON_A, 20, 150); - context.wait_for_all_requests(); - - BattleBallReader reader(stream, language); - int quantity = move_to_ball(reader, stream, context, ball_slug); - if (quantity == 0){ - throw_and_log( - stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to find appropriate ball. Did you run out?", - stream - ); - } - if (quantity < 0){ - stream.log("Unable to read ball quantity.", COLOR_RED); - } - pbf_mash_button(context, BUTTON_A, 125); - - continue; - } - case 2: - stream.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 3: - stream.log("Detected add-to-party prompt."); - if (result == TeraResult::NO_DETECTION){ - pbf_press_dpad(context, DPAD_DOWN, 20, 60); -// pbf_press_button(context, BUTTON_A, 20, 105); - }else{ - pbf_press_button(context, BUTTON_B, 20, 105); - } - continue; - case 4: - stream.log("Detected cursor over view summary."); - pbf_press_button(context, BUTTON_A, 20, 105); - continue; - case 5: - stream.log("Detected nickname prompt."); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 1: - // Next button detector is unreliable. Check if the summary is - // open. If so, fall-through to that. - if (!summary.detect(stream.video().snapshot())){ - stream.log("Detected possible (A) Next button."); - stop_if_enough_rare_items(stream, context, stop_on_sparkly_items); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_B, 20, 105); - break; - } - stream.log("Detected false positive (A) Next button.", COLOR_RED); - case 6: - stream.log("Detected summary."); - if (result == TeraResult::NO_DETECTION){ - context.wait_for(std::chrono::milliseconds(500)); - result = run_tera_summary( - env, stream, context, - notification_nonshiny, - notification_shiny, - stop_on_shiny, screenshot, - stat_shinies - ); - } - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 7: - stream.log("Detected unexpected main menu.", COLOR_RED); - pbf_press_button(context, BUTTON_B, 20, 105); - continue; - case 8: - stream.log("Detected overworld."); - if (stop_on_shiny && result == TeraResult::NO_DETECTION){ - throw UserSetupError( - stream.logger(), - "Unable to find " + STRING_POKEMON + " summary to check for shininess. " - "Make sure your party is full and \"Send to Boxes\" is set to \"Manual\"." - ); - } - return result; - default: - dump_image_and_throw_recoverable_exception( - env.program_info(), stream, "ExitTeraWinFailed", - "exit_tera_win_by_catching(): No recognized state after 60 seconds." - ); - } - } -} - - - - -TeraResult run_tera_summary( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - EventNotificationOption& notification_nonshiny, - EventNotificationOption& notification_shiny, - bool stop_on_shiny, const ImageViewRGB32& battle_screenshot, - std::atomic* stat_shinies -){ - stream.log("Reading summary..."); - - VideoSnapshot screen = stream.video().snapshot(); - PokemonSummaryDetector reader; - if (reader.is_shiny(screen)){ - if (stat_shinies != nullptr){ - (*stat_shinies)++; - } - send_encounter_notification( - env, - notification_nonshiny, - notification_shiny, - false, true, - {{{}, ShinyType::UNKNOWN_SHINY}}, - std::nan(""), - battle_screenshot - ); - if (stop_on_shiny){ - throw ProgramFinishedException(); - } - return TeraResult::SHINY; - }else{ - send_encounter_notification( - env, - notification_nonshiny, - notification_shiny, - false, false, - {{{}, ShinyType::NOT_SHINY}}, - std::nan("") - ); - return TeraResult::NOT_SHINY; - } -} - - -void run_from_tera_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ - stream.log("Running away from tera raid battle..."); - - WallClock start = current_time(); - while (true){ - // Having a lot of Abilities activating can take a while, setting 3 minutes to be safe - if (current_time() - start > std::chrono::minutes(3)){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_from_tera_battle(): Failed to run away from tera raid battle after 3 minutes.", - stream - ); - } - - TeraBattleMenuWatcher battle_menu(COLOR_GREEN); - OverworldWatcher overworld(stream.logger(), COLOR_CYAN); - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::minutes(1), - {battle_menu, overworld} - ); - - context.wait_for(std::chrono::milliseconds(100)); - switch (ret){ - case 0: - stream.log("Detected tera raid battle menu, running away..."); - stream.overlay().add_log("Running away...", COLOR_WHITE); - battle_menu.move_to_slot(stream, context, 2); - pbf_mash_button(context, BUTTON_A, 800); - continue; - case 1: - stream.log("Detected overworld."); - return; - default: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "run_from_tera_battle(): No recognized state after 1 minutes.", - stream - ); - } - } -} - - - - -bool is_sparkling_raid(VideoStream& stream, ProControllerContext& context){ -// cout << "is_sparkling_raid()" << endl; - - FrozenImageDetector static_map( - COLOR_RED, - {0.890, 0.800, 0.030, 0.060}, - std::chrono::seconds(1), 20 - ); - - context.wait_for_all_requests(); - - int ret = wait_until( - stream, context, - std::chrono::seconds(2), - {static_map} - ); - - if (ret == 0){ - stream.log("Did not detect sparkling raid", COLOR_ORANGE); - return false; - } - stream.log("Detected sparkling raid", COLOR_ORANGE); - return true; -} - - - - - - - - - -} -} -} +/* Tera Exit Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/FrozenImageDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Battles/PokemonSV_TeraBattleMenus.h" +#include "PokemonSV/Inference/PokemonSV_PokemonSummaryReader.h" +#include "PokemonSV/Inference/PokemonSV_MainMenuDetector.h" +#include "PokemonSV/Inference/PokemonSV_PokePortalDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_OverworldDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraCardDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraRaidSearchDetector.h" +#include "PokemonSV/Inference/Tera/PokemonSV_TeraRewardsReader.h" +#include "PokemonSV/Programs/PokemonSV_ConnectToInternet.h" +#include "PokemonSV/Programs/Battles/PokemonSV_BasicCatcher.h" +#include "PokemonSV_TeraRoutines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +bool open_raid(VideoStream& stream, ProControllerContext& context){ + stream.log("Opening raid..."); + while (true){ + TeraCardWatcher card_detector(COLOR_RED); + AdvanceDialogWatcher dialog(COLOR_YELLOW); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + // Do 2 presses in quick succession in case one drops or is + // needed to connect the controller. + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_press_button(context, BUTTON_A, 20, 355); + }, + { + card_detector, + dialog, + } + ); + switch (ret){ + case 0: + stream.log("Tera raid found!", COLOR_BLUE); + return true; + case 1: + stream.log("Detect possible uncatchable dialog...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + default: + stream.log("No Tera raid found.", COLOR_ORANGE); + return false; + } + } +} +void close_raid(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Closing raid..."); + + WallClock start = current_time(); + while (true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + info, stream, "CloseRaidFailed", + "Failed to return to overworld after 5 minutes." + ); + } + + TeraCardWatcher card_detector(COLOR_RED); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {card_detector, overworld} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 1: + stream.log("Detected overworld."); + return; + default: + dump_image_and_throw_recoverable_exception(info, stream, "CloseRaidFailed", + "close_raid(): No recognized state after 60 seconds."); + } + } +} + + + +void open_hosting_lobby( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + HostingMode mode +){ + bool recovery_mode = false; + WallClock start = current_time(); + while (true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(2)){ + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "OpenLobbyFailed", + "Unable to open Tera lobby after 2 minutes." + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + if (recovery_mode){ + context.wait_for_all_requests(); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_B, 20, 980); + }, + {overworld} + ); + if (ret < 0){ + continue; + } + stream.log("Detected overworld. Recovery finished."); + recovery_mode = true; + } + +// AdvanceDialogWatcher dialog(COLOR_GREEN); + TeraCardWatcher card_detector(COLOR_YELLOW); + TeraLobbyWatcher lobby(stream.logger(), env.normal_inference_dispatcher(), COLOR_BLUE); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + { + overworld, +// dialog, + card_detector, + {lobby, std::chrono::milliseconds(500)} + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld."); + recovery_mode = false; + if (!open_raid(stream, context)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "No Tera raid found.", + stream + ); + } + continue; +#if 0 + case 1: + stream.log("Detect possible uncatchable dialog...", COLOR_ORANGE); + pbf_press_button(context, BUTTON_B, 20, 230); + continue; +#endif + case 1: + stream.log("Detected Tera card."); + if (mode != HostingMode::LOCAL){ + pbf_press_button(context, BUTTON_A, 20, 230); + if (mode == HostingMode::ONLINE_EVERYONE){ + pbf_press_dpad(context, DPAD_DOWN, 20, 105); + } + } + pbf_press_button(context, BUTTON_A, 20, 230); + continue; + case 2: + stream.log("Detected Tera lobby."); + return; + default: + stream.log("No state detected after 30 seconds. Backing out...", COLOR_RED); + pbf_press_button(context, BUTTON_B, 20, 230); + recovery_mode = true; + } + } +} + + + + + +void enter_tera_search( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + bool connect_to_internet +){ + WallClock start = current_time(); + bool connected = false; + while (true){ + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + info, stream, "EnterTeraSearchFailed", + "enter_tera_search(): Failed to enter Tera search." + ); + } + + OverworldWatcher overworld(stream.logger(), COLOR_RED); + MainMenuWatcher main_menu(COLOR_YELLOW); + PokePortalWatcher poke_portal(COLOR_GREEN); + TeraRaidSearchWatcher raid_search(COLOR_CYAN); + CodeEntryWatcher code_entry(COLOR_PURPLE); + AdvanceDialogWatcher dialog(COLOR_BLUE); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(30), + { + overworld, + main_menu, + poke_portal, + raid_search, + code_entry, + dialog, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected overworld."); + pbf_press_button(context, BUTTON_X, 20, 105); + continue; + case 1: + stream.log("Detected main menu."); + if (connect_to_internet && !connected){ + connect_to_internet_from_menu(info, stream, context); + connected = true; + continue; + } + if (main_menu.move_cursor(info, stream, context, MenuSide::RIGHT, 3)){ + pbf_press_button(context, BUTTON_A, 20, 230); + } + continue; + case 2: + stream.log("Detected Poke Portal."); + if (poke_portal.move_cursor(info, stream, context, 1)){ + pbf_press_button(context, BUTTON_A, 20, 230); + } + continue; + case 3: + stream.log("Detected Tera Raid Search."); + if (raid_search.move_cursor_to_search(info, stream, context)){ + pbf_press_button(context, BUTTON_A, 20, 105); + } + continue; + case 4: + stream.log("Detected Code Entry."); + return; + case 5: + stream.log("Detected Dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + default: + dump_image_and_throw_recoverable_exception( + info, stream, "EnterTeraSearchFailed", + "enter_tera_search(): No recognized state after 30 seconds." + ); + } + } +} + + + + + +void stop_if_enough_rare_items( + VideoStream& stream, ProControllerContext& context, + size_t stop_on_sparkly_items +){ + if (stop_on_sparkly_items == 0){ + return; + } + size_t sparkly_items = SparklyItemDetector::count_sparkly_items(stream, context); + stream.log("Sparkly Items Detected: " + std::to_string(sparkly_items), COLOR_BLUE); + if (sparkly_items >= stop_on_sparkly_items){ + throw_and_log( + stream.logger(), + "Found a raid with " + std::to_string(sparkly_items) + " rare items!", + stream + ); + } +} + + +void exit_tera_win_without_catching( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t stop_on_sparkly_items +){ + stream.log("Exiting raid without catching..."); + + WallClock start = current_time(); + while (true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + info, stream, "ExitTeraWinFailed", + "Failed to return to overworld after 5 minutes." + ); + } + + TeraCatchWatcher catch_menu(COLOR_BLUE); + WhiteButtonWatcher next_button( + COLOR_CYAN, + WhiteButton::ButtonA, + {0.8, 0.93, 0.2, 0.07}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::seconds(1) + ); + AdvanceDialogWatcher dialog(COLOR_YELLOW); + OverworldWatcher overworld(stream.logger(), COLOR_RED); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + {catch_menu, next_button, dialog, overworld} + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected catch prompt."); + catch_menu.move_to_slot(stream, context, 1); +// pbf_press_dpad(context, DPAD_DOWN, 20, 30); + pbf_mash_button(context, BUTTON_A, 30); + pbf_mash_button(context, BUTTON_B, 125); + continue; + case 1: + stream.log("Detected possible (A) Next button."); + stop_if_enough_rare_items(stream, context, stop_on_sparkly_items); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 2: + stream.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + break; + case 3: + stream.log("Detected overworld."); + return; + default: + dump_image_and_throw_recoverable_exception( + info, stream, "ExitTeraWinFailed", + "exit_tera_win_without_catching(): No recognized state after 60 seconds." + ); + } + } +} + + +void exit_tera_win_by_catching( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, + size_t stop_on_sparkly_items +){ + stream.log("Exiting raid with catching..."); + + VideoSnapshot screenshot; + WallClock start = current_time(); + while (true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "ExitTeraWinFailed", + "Failed to return to overworld after 5 minutes." + ); + } + + TeraCatchWatcher catch_menu(COLOR_BLUE); + WhiteButtonWatcher next_button( + COLOR_CYAN, + WhiteButton::ButtonA, + {0.8, 0.93, 0.2, 0.07}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::seconds(1) + ); + AdvanceDialogWatcher advance(COLOR_YELLOW); + PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); + PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); + MainMenuWatcher main_menu(COLOR_BLUE); + OverworldWatcher overworld(stream.logger(), COLOR_RED); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + { + catch_menu, + next_button, + advance, + add_to_party, + nickname, + main_menu, + overworld, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0:{ + stream.log("Detected catch prompt."); + screenshot = stream.video().snapshot(); + + catch_menu.move_to_slot(stream, context, 0); + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + BattleBallReader reader(stream, language); + int quantity = move_to_ball(reader, stream, context, ball_slug); + if (quantity == 0){ + throw_and_log( + stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to find appropriate ball. Did you run out?", + stream + ); + } + if (quantity < 0){ + stream.log("Unable to read ball quantity.", COLOR_RED); + } + pbf_mash_button(context, BUTTON_A, 125); + + continue; + } + case 1: + stream.log("Detected (A) Next button."); + stop_if_enough_rare_items(stream, context, stop_on_sparkly_items); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 2: + stream.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 3: + stream.log("Detected add-to-party prompt."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 4: + stream.log("Detected nickname prompt."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 5: + stream.log("Detected unexpected main menu.", COLOR_RED); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 6: + stream.log("Detected overworld."); + return; + default: + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "ExitTeraWinFailed", + "exit_tera_win_by_catching(): No recognized state after 60 seconds." + ); + } + } +} + + +TeraResult exit_tera_win_by_catching( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, + EventNotificationOption& notification_nonshiny, + EventNotificationOption& notification_shiny, + bool stop_on_shiny, size_t stop_on_sparkly_items, + std::atomic* stat_shinies +){ + stream.log("Exiting raid with catching..."); + + TeraResult result = TeraResult::NO_DETECTION; + VideoSnapshot screenshot; + WallClock start = current_time(); + while (true){ + context.wait_for_all_requests(); + if (current_time() - start > std::chrono::minutes(5)){ + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "ExitTeraWinFailed", + "Failed to return to overworld after 5 minutes." + ); + } + + TeraCatchWatcher catch_menu(COLOR_BLUE); + WhiteButtonWatcher next_button( + COLOR_CYAN, + WhiteButton::ButtonA, + {0.8, 0.93, 0.2, 0.07}, + WhiteButtonWatcher::FinderType::PRESENT, + std::chrono::seconds(1) + ); + AdvanceDialogWatcher advance(COLOR_YELLOW); + PromptDialogWatcher add_to_party(COLOR_PURPLE, {0.500, 0.395, 0.400, 0.100}); + PromptDialogWatcher view_summary(COLOR_PURPLE, {0.500, 0.470, 0.400, 0.100}); + PromptDialogWatcher nickname(COLOR_GREEN, {0.500, 0.545, 0.400, 0.100}); + PokemonSummaryWatcher summary(COLOR_MAGENTA); + MainMenuWatcher main_menu(COLOR_BLUE); + OverworldWatcher overworld(stream.logger(), COLOR_RED); + context.wait_for_all_requests(); + int ret = wait_until( + stream, context, + std::chrono::seconds(60), + { + catch_menu, + next_button, + advance, + add_to_party, + view_summary, + nickname, + summary, + main_menu, + overworld, + } + ); + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0:{ + stream.log("Detected catch prompt."); + screenshot = stream.video().snapshot(); + + catch_menu.move_to_slot(stream, context, 0); + pbf_press_button(context, BUTTON_A, 20, 150); + context.wait_for_all_requests(); + + BattleBallReader reader(stream, language); + int quantity = move_to_ball(reader, stream, context, ball_slug); + if (quantity == 0){ + throw_and_log( + stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to find appropriate ball. Did you run out?", + stream + ); + } + if (quantity < 0){ + stream.log("Unable to read ball quantity.", COLOR_RED); + } + pbf_mash_button(context, BUTTON_A, 125); + + continue; + } + case 2: + stream.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 3: + stream.log("Detected add-to-party prompt."); + if (result == TeraResult::NO_DETECTION){ + pbf_press_dpad(context, DPAD_DOWN, 20, 60); +// pbf_press_button(context, BUTTON_A, 20, 105); + }else{ + pbf_press_button(context, BUTTON_B, 20, 105); + } + continue; + case 4: + stream.log("Detected cursor over view summary."); + pbf_press_button(context, BUTTON_A, 20, 105); + continue; + case 5: + stream.log("Detected nickname prompt."); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 1: + // Next button detector is unreliable. Check if the summary is + // open. If so, fall-through to that. + if (!summary.detect(stream.video().snapshot())){ + stream.log("Detected possible (A) Next button."); + stop_if_enough_rare_items(stream, context, stop_on_sparkly_items); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_B, 20, 105); + break; + } + stream.log("Detected false positive (A) Next button.", COLOR_RED); + case 6: + stream.log("Detected summary."); + if (result == TeraResult::NO_DETECTION){ + context.wait_for(std::chrono::milliseconds(500)); + result = run_tera_summary( + env, stream, context, + notification_nonshiny, + notification_shiny, + stop_on_shiny, screenshot, + stat_shinies + ); + } + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 7: + stream.log("Detected unexpected main menu.", COLOR_RED); + pbf_press_button(context, BUTTON_B, 20, 105); + continue; + case 8: + stream.log("Detected overworld."); + if (stop_on_shiny && result == TeraResult::NO_DETECTION){ + throw UserSetupError( + stream.logger(), + "Unable to find " + STRING_POKEMON + " summary to check for shininess. " + "Make sure your party is full and \"Send to Boxes\" is set to \"Manual\"." + ); + } + return result; + default: + dump_image_and_throw_recoverable_exception( + env.program_info(), stream, "ExitTeraWinFailed", + "exit_tera_win_by_catching(): No recognized state after 60 seconds." + ); + } + } +} + + + + +TeraResult run_tera_summary( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + EventNotificationOption& notification_nonshiny, + EventNotificationOption& notification_shiny, + bool stop_on_shiny, const ImageViewRGB32& battle_screenshot, + std::atomic* stat_shinies +){ + stream.log("Reading summary..."); + + VideoSnapshot screen = stream.video().snapshot(); + PokemonSummaryDetector reader; + if (reader.is_shiny(screen)){ + if (stat_shinies != nullptr){ + (*stat_shinies)++; + } + send_encounter_notification( + env, + notification_nonshiny, + notification_shiny, + false, true, + {{{}, ShinyType::UNKNOWN_SHINY}}, + std::nan(""), + battle_screenshot + ); + if (stop_on_shiny){ + throw ProgramFinishedException(); + } + return TeraResult::SHINY; + }else{ + send_encounter_notification( + env, + notification_nonshiny, + notification_shiny, + false, false, + {{{}, ShinyType::NOT_SHINY}}, + std::nan("") + ); + return TeraResult::NOT_SHINY; + } +} + + +void run_from_tera_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context){ + stream.log("Running away from tera raid battle..."); + + WallClock start = current_time(); + while (true){ + // Having a lot of Abilities activating can take a while, setting 3 minutes to be safe + if (current_time() - start > std::chrono::minutes(3)){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_from_tera_battle(): Failed to run away from tera raid battle after 3 minutes.", + stream + ); + } + + TeraBattleMenuWatcher battle_menu(COLOR_GREEN); + OverworldWatcher overworld(stream.logger(), COLOR_CYAN); + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::minutes(1), + {battle_menu, overworld} + ); + + context.wait_for(std::chrono::milliseconds(100)); + switch (ret){ + case 0: + stream.log("Detected tera raid battle menu, running away..."); + stream.overlay().add_log("Running away...", COLOR_WHITE); + battle_menu.move_to_slot(stream, context, 2); + pbf_mash_button(context, BUTTON_A, 800); + continue; + case 1: + stream.log("Detected overworld."); + return; + default: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "run_from_tera_battle(): No recognized state after 1 minutes.", + stream + ); + } + } +} + + + + +bool is_sparkling_raid(VideoStream& stream, ProControllerContext& context){ +// cout << "is_sparkling_raid()" << endl; + + FrozenImageDetector static_map( + COLOR_RED, + {0.890, 0.800, 0.030, 0.060}, + std::chrono::seconds(1), 20 + ); + + context.wait_for_all_requests(); + + int ret = wait_until( + stream, context, + std::chrono::seconds(2), + {static_map} + ); + + if (ret == 0){ + stream.log("Did not detect sparkling raid", COLOR_ORANGE); + return false; + } + stream.log("Detected sparkling raid", COLOR_ORANGE); + return true; +} + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h index 35d0b90b0b..bde480ee3b 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h @@ -1,123 +1,123 @@ -/* Tera Exit Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraExitRoutines_H -#define PokemonAutomation_PokemonSV_TeraExitRoutines_H - -#include -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; - class EventNotificationOption; - class ImageViewRGB32; - struct ProgramInfo; -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - - - -// While in the overworld, attempt to enter a raid in front of you. -bool open_raid(VideoStream& stream, ProControllerContext& context); - -// While viewing a raid card, close and return to the overworld. -void close_raid(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - - -enum class HostingMode{ - LOCAL, - ONLINE_CODED, - ONLINE_EVERYONE, -}; -void open_hosting_lobby( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - HostingMode mode -); - - -// From overworld or main menu => Code entry for tera raid. -void enter_tera_search( - const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, - bool connect_to_internet -); - - - - - -// Exit a Tera raid after winning without catching. -// The entry point is with the catch/no-catch option up. -// Upon returning, you will be in the overworld. -void exit_tera_win_without_catching( - const ProgramInfo& info, - VideoStream& stream, ProControllerContext& context, - size_t stop_on_sparkly_items -); - - -// Exit a Tera raid after winning by catching. -// The entry point is with the catch/no-catch option up. -// Does not check for shininess. -void exit_tera_win_by_catching( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, - size_t stop_on_sparkly_items -); - - - -enum class TeraResult{ - NO_DETECTION, - NOT_SHINY, - SHINY, -}; - -// Exit a Tera raid after winning by catching. -// The entry point is with the catch/no-catch option up. -// Returns the result of the caught Pokemon. -// Upon returning, you will be in the overworld except if it is shiny and -// "stop_on_shiny == true', then you will be in the summary of the shiny. -TeraResult exit_tera_win_by_catching( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, - EventNotificationOption& notification_nonshiny, - EventNotificationOption& notification_shiny, - bool stop_on_shiny, size_t stop_on_sparkly_items, - std::atomic* stat_shinies -); - - - -TeraResult run_tera_summary( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - EventNotificationOption& notification_nonshiny, - EventNotificationOption& notification_shiny, - bool stop_on_shiny, const ImageViewRGB32& battle_screenshot, - std::atomic* stat_shinies -); - -// Run away from tera battle. -void run_from_tera_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); - -bool is_sparkling_raid(VideoStream& stream, ProControllerContext& context); - - -} -} -} -#endif +/* Tera Exit Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraExitRoutines_H +#define PokemonAutomation_PokemonSV_TeraExitRoutines_H + +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; + class EventNotificationOption; + class ImageViewRGB32; + struct ProgramInfo; +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + + + +// While in the overworld, attempt to enter a raid in front of you. +bool open_raid(VideoStream& stream, ProControllerContext& context); + +// While viewing a raid card, close and return to the overworld. +void close_raid(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + + +enum class HostingMode{ + LOCAL, + ONLINE_CODED, + ONLINE_EVERYONE, +}; +void open_hosting_lobby( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + HostingMode mode +); + + +// From overworld or main menu => Code entry for tera raid. +void enter_tera_search( + const ProgramInfo& info, VideoStream& stream, ProControllerContext& context, + bool connect_to_internet +); + + + + + +// Exit a Tera raid after winning without catching. +// The entry point is with the catch/no-catch option up. +// Upon returning, you will be in the overworld. +void exit_tera_win_without_catching( + const ProgramInfo& info, + VideoStream& stream, ProControllerContext& context, + size_t stop_on_sparkly_items +); + + +// Exit a Tera raid after winning by catching. +// The entry point is with the catch/no-catch option up. +// Does not check for shininess. +void exit_tera_win_by_catching( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, + size_t stop_on_sparkly_items +); + + + +enum class TeraResult{ + NO_DETECTION, + NOT_SHINY, + SHINY, +}; + +// Exit a Tera raid after winning by catching. +// The entry point is with the catch/no-catch option up. +// Returns the result of the caught Pokemon. +// Upon returning, you will be in the overworld except if it is shiny and +// "stop_on_shiny == true', then you will be in the summary of the shiny. +TeraResult exit_tera_win_by_catching( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, + EventNotificationOption& notification_nonshiny, + EventNotificationOption& notification_shiny, + bool stop_on_shiny, size_t stop_on_sparkly_items, + std::atomic* stat_shinies +); + + + +TeraResult run_tera_summary( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + EventNotificationOption& notification_nonshiny, + EventNotificationOption& notification_shiny, + bool stop_on_shiny, const ImageViewRGB32& battle_screenshot, + std::atomic* stat_shinies +); + +// Run away from tera battle. +void run_from_tera_battle(const ProgramInfo& info, VideoStream& stream, ProControllerContext& context); + +bool is_sparkling_raid(VideoStream& stream, ProControllerContext& context); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.cpp b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.cpp index 7908bd30a7..b9ed065ba2 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.cpp @@ -1,344 +1,344 @@ -/* Tera Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV/Programs/PokemonSV_GameEntry.h" -#include "PokemonSV/Programs/PokemonSV_SaveGame.h" -#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" -#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" -#include "PokemonSV_TeraSelfFarmer.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -TeraSelfFarmer_Descriptor::TeraSelfFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSV:TeraSelfFarmer", - STRING_POKEMON + " SV", "Tera Self Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TeraSelfFarmer.md", - "Farm items and " + STRING_POKEMON + " from Tera raids. Can also hunt for shiny and high reward raids.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -struct TeraSelfFarmer_Descriptor::Stats : public StatsTracker{ - Stats() - : m_skips(m_stats["Date Skips"]) - , m_raids(m_stats["Raids"]) - , m_wins(m_stats["Wins"]) - , m_losses(m_stats["Losses"]) - , m_skipped(m_stats["Skipped"]) - , m_errors(m_stats["Errors"]) - , m_caught(m_stats["Caught"]) - , m_shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Date Skips"); - m_display_order.emplace_back("Raids"); - m_display_order.emplace_back("Wins"); - m_display_order.emplace_back("Losses"); - m_display_order.emplace_back("Skipped"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Caught", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - std::atomic& m_skips; - std::atomic& m_raids; - std::atomic& m_wins; - std::atomic& m_losses; - std::atomic& m_skipped; - std::atomic& m_errors; - std::atomic& m_caught; - std::atomic& m_shinies; -}; -std::unique_ptr TeraSelfFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -TeraFarmerStopConditions::TeraFarmerStopConditions() - : GroupOption("Stop Conditions", LockMode::UNLOCK_WHILE_RUNNING) - , MAX_CATCHES( - "Max Catches:
Stop program after catching this many " + STRING_POKEMON + ".", - LockMode::UNLOCK_WHILE_RUNNING, - 50, 1, 999 - ) - , STOP_ON_SHINY( - "Stop on Shiny: (requires catching the " + STRING_POKEMON + ")
" - "Stop the program if a shiny is found. Resetting the game will return you to the front of this (shiny) raid so it can be hosted again.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , STOP_ON_RARE_ITEMS( - "Stop on Rare Items:
" - "Stop the program if the rewards contain at least this many rare (sparkly) items. Set to zero to disable this feature and never stop for item rewards.
" - "Note that the program can only see the first 8 item rewards. It will not scroll down.", - LockMode::UNLOCK_WHILE_RUNNING, - 0, 0, 8 - ) -{ - PA_ADD_OPTION(MAX_CATCHES); - PA_ADD_OPTION(STOP_ON_SHINY); - PA_ADD_OPTION(STOP_ON_RARE_ITEMS); -} - - -TeraSelfFarmer::~TeraSelfFarmer(){ - CATCH_ON_WIN.remove_listener(*this); -} -TeraSelfFarmer::TeraSelfFarmer() - : LANGUAGE( - "Game Language:", - PokemonNameReader::instance().languages(), - LockMode::UNLOCK_WHILE_RUNNING - ) - , FILTER(4, true) - , PERIODIC_RESET( - "Periodic Game Reset:
Reset the game after this many skips. This clears up the framerate bug.", - LockMode::UNLOCK_WHILE_RUNNING, - 20, 0, 100 - ) - , CATCH_ON_WIN(true) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_NONSHINY, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(FILTER); - PA_ADD_OPTION(BATTLE_AI); - PA_ADD_OPTION(PERIODIC_RESET); - PA_ADD_OPTION(CATCH_ON_WIN); - PA_ADD_OPTION(STOP_CONDITIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - CATCH_ON_WIN.add_listener(*this); -} -void TeraSelfFarmer::on_config_value_changed(void* object){ - STOP_CONDITIONS.STOP_ON_SHINY.set_visibility( - CATCH_ON_WIN.enabled() ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN - ); -} - - -bool TeraSelfFarmer::run_raid(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - env.console.log("Running raid..."); - - TeraSelfFarmer_Descriptor::Stats& stats = env.current_stats(); - - bool win = run_tera_battle(env, env.console, context, BATTLE_AI); - - if (win){ - stats.m_wins++; - }else{ - stats.m_losses++; - context.wait_for(std::chrono::seconds(3)); - return false; - } - - if (!CATCH_ON_WIN.enabled()){ - exit_tera_win_without_catching(env.program_info(), env.console, context, STOP_CONDITIONS.STOP_ON_RARE_ITEMS); - return true; - } - - VideoSnapshot battle_snapshot = env.console.video().snapshot(); - - - if (CATCH_ON_WIN.FIX_TIME_ON_CATCH){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - - m_number_caught++; - stats.m_caught++; - - exit_tera_win_by_catching( - env, env.console, context, - LANGUAGE, - CATCH_ON_WIN.BALL_SELECT.slug(), - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - STOP_CONDITIONS.STOP_ON_SHINY, - STOP_CONDITIONS.STOP_ON_RARE_ITEMS, - &stats.m_shinies - ); - return true; -} - - -void TeraSelfFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - assert_16_9_720p_min(env.logger(), env.console); - - TeraSelfFarmer_Descriptor::Stats& stats = env.current_stats(); - - if (FILTER.MIN_STARS > FILTER.MAX_STARS){ - throw UserSetupError(env.console, "Error in the settings, \"Min Stars\" is bigger than \"Max Stars\"."); - } - - if (FILTER.SKIP_NON_HERBA && FILTER.MAX_STARS < 5){ - throw UserSetupError(env.console, "Error in the settings, Skip Non-Herba Raids is checked but Max Stars is less than 5."); - } - - m_number_caught = 0; - - // Connect the controller. - pbf_press_button(context, BUTTON_L, 10, 10); - - bool first = true; - uint32_t skip_counter = 0; - - while (true){ - if (m_number_caught >= STOP_CONDITIONS.MAX_CATCHES){ - break; - } - - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (!first){ - day_skip_from_overworld(env.console, context); - pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); - context.wait_for_all_requests(); - stats.m_skips++; - skip_counter++; - env.update_stats(); - } - first = false; - - uint8_t reset_period = PERIODIC_RESET; - if (reset_period != 0 && skip_counter >= reset_period){ - env.log("Resetting game to clear framerate."); - save_game_from_overworld(env.program_info(), env.console, context); - reset_game(env.program_info(), env.console, context); - skip_counter = 0; -// stats.m_resets++; - } - - TeraRaidData raid_data; - TeraRollFilter::FilterResult result = FILTER.run_filter( - env.program_info(), env.console, context, - raid_data - ); - switch (result){ - case TeraRollFilter::FilterResult::NO_RAID: - continue; - case TeraRollFilter::FilterResult::FAILED: - stats.m_raids++; - stats.m_skipped++; - continue; - case TeraRollFilter::FilterResult::PASSED: - stats.m_raids++; - break; - } - - - close_raid(env.program_info(), env.console, context); - save_game_from_overworld(env.program_info(), env.console, context); - - context.wait_for_all_requests(); - if (open_raid(env.console, context)){ - env.log("Tera raid found!", COLOR_BLUE); - }else{ - env.log("No Tera raid found.", COLOR_ORANGE); - continue; - } - - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_mash_button(context, BUTTON_A, 250); - bool raid_won = run_raid(env, context); - { - std::stringstream ss; - ss << "You "; - if (raid_won){ - ss << "won"; - }else{ - ss << "lost"; - } - - std::string stars = raid_data.stars == 0 - ? "?" - : std::to_string(raid_data.stars); - std::string tera_type = raid_data.tera_type.empty() - ? "unknown tera type" - : raid_data.tera_type; - - std::string pokemon; - if (raid_data.species.empty()){ - pokemon = "unknown " + Pokemon::STRING_POKEMON; - }else if (raid_data.species.size() == 1){ - pokemon = *raid_data.species.begin(); - }else{ - pokemon = set_to_str(raid_data.species); - } - - ss << " a " << stars << "* " << tera_type << " " << pokemon << " raid"; - env.log(ss.str()); - env.console.overlay().add_log(ss.str(), COLOR_GREEN); - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - - - - - - -} -} -} +/* Tera Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV/Programs/PokemonSV_GameEntry.h" +#include "PokemonSV/Programs/PokemonSV_SaveGame.h" +#include "PokemonSV/Programs/PokemonSV_MenuNavigation.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraRoutines.h" +#include "PokemonSV/Programs/TeraRaids/PokemonSV_TeraBattler.h" +#include "PokemonSV_TeraSelfFarmer.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +TeraSelfFarmer_Descriptor::TeraSelfFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSV:TeraSelfFarmer", + STRING_POKEMON + " SV", "Tera Self Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/TeraSelfFarmer.md", + "Farm items and " + STRING_POKEMON + " from Tera raids. Can also hunt for shiny and high reward raids.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +struct TeraSelfFarmer_Descriptor::Stats : public StatsTracker{ + Stats() + : m_skips(m_stats["Date Skips"]) + , m_raids(m_stats["Raids"]) + , m_wins(m_stats["Wins"]) + , m_losses(m_stats["Losses"]) + , m_skipped(m_stats["Skipped"]) + , m_errors(m_stats["Errors"]) + , m_caught(m_stats["Caught"]) + , m_shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Date Skips"); + m_display_order.emplace_back("Raids"); + m_display_order.emplace_back("Wins"); + m_display_order.emplace_back("Losses"); + m_display_order.emplace_back("Skipped"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Caught", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + std::atomic& m_skips; + std::atomic& m_raids; + std::atomic& m_wins; + std::atomic& m_losses; + std::atomic& m_skipped; + std::atomic& m_errors; + std::atomic& m_caught; + std::atomic& m_shinies; +}; +std::unique_ptr TeraSelfFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +TeraFarmerStopConditions::TeraFarmerStopConditions() + : GroupOption("Stop Conditions", LockMode::UNLOCK_WHILE_RUNNING) + , MAX_CATCHES( + "Max Catches:
Stop program after catching this many " + STRING_POKEMON + ".", + LockMode::UNLOCK_WHILE_RUNNING, + 50, 1, 999 + ) + , STOP_ON_SHINY( + "Stop on Shiny: (requires catching the " + STRING_POKEMON + ")
" + "Stop the program if a shiny is found. Resetting the game will return you to the front of this (shiny) raid so it can be hosted again.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , STOP_ON_RARE_ITEMS( + "Stop on Rare Items:
" + "Stop the program if the rewards contain at least this many rare (sparkly) items. Set to zero to disable this feature and never stop for item rewards.
" + "Note that the program can only see the first 8 item rewards. It will not scroll down.", + LockMode::UNLOCK_WHILE_RUNNING, + 0, 0, 8 + ) +{ + PA_ADD_OPTION(MAX_CATCHES); + PA_ADD_OPTION(STOP_ON_SHINY); + PA_ADD_OPTION(STOP_ON_RARE_ITEMS); +} + + +TeraSelfFarmer::~TeraSelfFarmer(){ + CATCH_ON_WIN.remove_listener(*this); +} +TeraSelfFarmer::TeraSelfFarmer() + : LANGUAGE( + "Game Language:", + PokemonNameReader::instance().languages(), + LockMode::UNLOCK_WHILE_RUNNING + ) + , FILTER(4, true) + , PERIODIC_RESET( + "Periodic Game Reset:
Reset the game after this many skips. This clears up the framerate bug.", + LockMode::UNLOCK_WHILE_RUNNING, + 20, 0, 100 + ) + , CATCH_ON_WIN(true) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_NONSHINY, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(FILTER); + PA_ADD_OPTION(BATTLE_AI); + PA_ADD_OPTION(PERIODIC_RESET); + PA_ADD_OPTION(CATCH_ON_WIN); + PA_ADD_OPTION(STOP_CONDITIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + CATCH_ON_WIN.add_listener(*this); +} +void TeraSelfFarmer::on_config_value_changed(void* object){ + STOP_CONDITIONS.STOP_ON_SHINY.set_visibility( + CATCH_ON_WIN.enabled() ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN + ); +} + + +bool TeraSelfFarmer::run_raid(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + env.console.log("Running raid..."); + + TeraSelfFarmer_Descriptor::Stats& stats = env.current_stats(); + + bool win = run_tera_battle(env, env.console, context, BATTLE_AI); + + if (win){ + stats.m_wins++; + }else{ + stats.m_losses++; + context.wait_for(std::chrono::seconds(3)); + return false; + } + + if (!CATCH_ON_WIN.enabled()){ + exit_tera_win_without_catching(env.program_info(), env.console, context, STOP_CONDITIONS.STOP_ON_RARE_ITEMS); + return true; + } + + VideoSnapshot battle_snapshot = env.console.video().snapshot(); + + + if (CATCH_ON_WIN.FIX_TIME_ON_CATCH){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().GAME_TO_HOME_DELAY1); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + + m_number_caught++; + stats.m_caught++; + + exit_tera_win_by_catching( + env, env.console, context, + LANGUAGE, + CATCH_ON_WIN.BALL_SELECT.slug(), + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + STOP_CONDITIONS.STOP_ON_SHINY, + STOP_CONDITIONS.STOP_ON_RARE_ITEMS, + &stats.m_shinies + ); + return true; +} + + +void TeraSelfFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + assert_16_9_720p_min(env.logger(), env.console); + + TeraSelfFarmer_Descriptor::Stats& stats = env.current_stats(); + + if (FILTER.MIN_STARS > FILTER.MAX_STARS){ + throw UserSetupError(env.console, "Error in the settings, \"Min Stars\" is bigger than \"Max Stars\"."); + } + + if (FILTER.SKIP_NON_HERBA && FILTER.MAX_STARS < 5){ + throw UserSetupError(env.console, "Error in the settings, Skip Non-Herba Raids is checked but Max Stars is less than 5."); + } + + m_number_caught = 0; + + // Connect the controller. + pbf_press_button(context, BUTTON_L, 10, 10); + + bool first = true; + uint32_t skip_counter = 0; + + while (true){ + if (m_number_caught >= STOP_CONDITIONS.MAX_CATCHES){ + break; + } + + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (!first){ + day_skip_from_overworld(env.console, context); + pbf_wait(context, GameSettings::instance().RAID_SPAWN_DELAY0); + context.wait_for_all_requests(); + stats.m_skips++; + skip_counter++; + env.update_stats(); + } + first = false; + + uint8_t reset_period = PERIODIC_RESET; + if (reset_period != 0 && skip_counter >= reset_period){ + env.log("Resetting game to clear framerate."); + save_game_from_overworld(env.program_info(), env.console, context); + reset_game(env.program_info(), env.console, context); + skip_counter = 0; +// stats.m_resets++; + } + + TeraRaidData raid_data; + TeraRollFilter::FilterResult result = FILTER.run_filter( + env.program_info(), env.console, context, + raid_data + ); + switch (result){ + case TeraRollFilter::FilterResult::NO_RAID: + continue; + case TeraRollFilter::FilterResult::FAILED: + stats.m_raids++; + stats.m_skipped++; + continue; + case TeraRollFilter::FilterResult::PASSED: + stats.m_raids++; + break; + } + + + close_raid(env.program_info(), env.console, context); + save_game_from_overworld(env.program_info(), env.console, context); + + context.wait_for_all_requests(); + if (open_raid(env.console, context)){ + env.log("Tera raid found!", COLOR_BLUE); + }else{ + env.log("No Tera raid found.", COLOR_ORANGE); + continue; + } + + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_mash_button(context, BUTTON_A, 250); + bool raid_won = run_raid(env, context); + { + std::stringstream ss; + ss << "You "; + if (raid_won){ + ss << "won"; + }else{ + ss << "lost"; + } + + std::string stars = raid_data.stars == 0 + ? "?" + : std::to_string(raid_data.stars); + std::string tera_type = raid_data.tera_type.empty() + ? "unknown tera type" + : raid_data.tera_type; + + std::string pokemon; + if (raid_data.species.empty()){ + pokemon = "unknown " + Pokemon::STRING_POKEMON; + }else if (raid_data.species.size() == 1){ + pokemon = *raid_data.species.begin(); + }else{ + pokemon = set_to_str(raid_data.species); + } + + ss << " a " << stars << "* " << tera_type << " " << pokemon << " raid"; + env.log(ss.str()); + env.console.overlay().add_log(ss.str(), COLOR_GREEN); + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h index d5160c1b4b..0d4626cd11 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TeraRaids/PokemonSV_TeraSelfFarmer.h @@ -1,92 +1,92 @@ -/* Tera Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TeraSelfFarmer_H -#define PokemonAutomation_PokemonSV_TeraSelfFarmer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSV/Options/PokemonSV_TeraRollFilter.h" -#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" -#include "PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h" - -namespace PokemonAutomation{ - struct VideoSnapshot; -namespace NintendoSwitch{ -namespace PokemonSV{ - -class TeraSelfFarmer; - - -class TeraSelfFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TeraSelfFarmer_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; - -}; - - - - -class TeraFarmerStopConditions : public GroupOption{ -public: - TeraFarmerStopConditions(); - - SimpleIntegerOption MAX_CATCHES; - BooleanCheckBoxOption STOP_ON_SHINY; - SimpleIntegerOption STOP_ON_RARE_ITEMS; -}; - - - -class TeraSelfFarmer : public SingleSwitchProgramInstance, public ConfigOption::Listener{ -public: - ~TeraSelfFarmer(); - TeraSelfFarmer(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - virtual void on_config_value_changed(void* object) override; - bool run_raid(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - friend class TeraFarmerCatchOnWin; - - OCR::LanguageOCROption LANGUAGE; - -// TeraFarmerOpponentFilter FILTER; - TeraRollFilter FILTER; - TeraAIOption BATTLE_AI; - SimpleIntegerOption PERIODIC_RESET; - TeraFarmerCatchOnWin CATCH_ON_WIN; - TeraFarmerStopConditions STOP_CONDITIONS; - - // Notifications - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; - - uint16_t m_number_caught; - - // Per iteration flags. -// bool m_battle_finished; -// bool m_caught; -// bool m_summary_read; -}; - - - - -} -} -} -#endif +/* Tera Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TeraSelfFarmer_H +#define PokemonAutomation_PokemonSV_TeraSelfFarmer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSV/Options/PokemonSV_TeraRollFilter.h" +#include "PokemonSV/Options/PokemonSV_TeraAIOption.h" +#include "PokemonSV/Options/PokemonSV_TeraCatchOnWinOption.h" + +namespace PokemonAutomation{ + struct VideoSnapshot; +namespace NintendoSwitch{ +namespace PokemonSV{ + +class TeraSelfFarmer; + + +class TeraSelfFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TeraSelfFarmer_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; + +}; + + + + +class TeraFarmerStopConditions : public GroupOption{ +public: + TeraFarmerStopConditions(); + + SimpleIntegerOption MAX_CATCHES; + BooleanCheckBoxOption STOP_ON_SHINY; + SimpleIntegerOption STOP_ON_RARE_ITEMS; +}; + + + +class TeraSelfFarmer : public SingleSwitchProgramInstance, public ConfigOption::Listener{ +public: + ~TeraSelfFarmer(); + TeraSelfFarmer(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + virtual void on_config_value_changed(void* object) override; + bool run_raid(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + friend class TeraFarmerCatchOnWin; + + OCR::LanguageOCROption LANGUAGE; + +// TeraFarmerOpponentFilter FILTER; + TeraRollFilter FILTER; + TeraAIOption BATTLE_AI; + SimpleIntegerOption PERIODIC_RESET; + TeraFarmerCatchOnWin CATCH_ON_WIN; + TeraFarmerStopConditions STOP_CONDITIONS; + + // Notifications + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; + + uint16_t m_number_caught; + + // Per iteration flags. +// bool m_battle_finished; +// bool m_caught; +// bool m_summary_read; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.cpp b/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.cpp index c44c3e6ecf..5ebfbfe0c6 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.cpp @@ -1,110 +1,110 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "CommonTools/Async/InferenceSession.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h" -#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" -#include "PokemonSV_SoundListener.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - - -SoundListener_Descriptor::SoundListener_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonLA:SoundListener", - STRING_POKEMON + " LA", "Sound Listener", - "", - "Test sound detectors listening to audio stream.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {} - ) -{} - - -SoundListener::SoundListener() - : SOUND_TYPE("Which Sound to Detect", - { - {SoundType::Shiny, "shiny", "Shiny Sound"}, - {SoundType::LetsGoKill, "lets-go-kill", "Let's Go Kill"}, - }, - LockMode::LOCK_WHILE_RUNNING, - SoundType::Shiny - ) - , STOP_ON_DETECTED_SOUND( - "Stop on the detected sound
Stop program when the sound is detected.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(SOUND_TYPE); - PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); -} - - -// void search_alpha_roar_from_audio_dump(); - -void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Connect the controller. - // pbf_move_right_joystick(context, 0, 255, 10, 0); - - // search_alpha_roar_from_audio_dump(); - // return; - - std::cout << "Running audio test program." << std::endl; - - std::unique_ptr detector; - auto action = [&](float error_coefficient) -> bool{ - // This lambda function will be called when the sound is detected. - // Its return will determine whether to stop the program: - return STOP_ON_DETECTED_SOUND; - }; - - SoundType type = SOUND_TYPE; - switch (type){ - case SoundType::Shiny: - detector = std::make_unique(env.console, action); - break; - case SoundType::LetsGoKill: - detector = std::make_unique(env.console, action); - break; - default: - throw InternalProgramError( - &env.logger(), PA_CURRENT_FUNCTION, - "Not such sound detector as sound type " + std::to_string((size_t)type) - ); - } - -#if 0 - ShinySoundDetector detector0(env.console, action); - LetsGoKillSoundDetector detector1(env.console, action); - InferenceSession session( - context, env.console, - {detector0, detector1} - ); -#else - InferenceSession session( - context, env.console, - {*detector} - ); -#endif - context.wait_until_cancel(); - - std::cout << "Audio test program Sound listener finished." << std::endl; -} - - - -} -} -} +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "CommonTools/Async/InferenceSession.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSV/Inference/Battles/PokemonSV_ShinySoundDetector.h" +#include "PokemonSV/Inference/Overworld/PokemonSV_LetsGoKillDetector.h" +#include "PokemonSV_SoundListener.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + + +SoundListener_Descriptor::SoundListener_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonLA:SoundListener", + STRING_POKEMON + " LA", "Sound Listener", + "", + "Test sound detectors listening to audio stream.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {} + ) +{} + + +SoundListener::SoundListener() + : SOUND_TYPE("Which Sound to Detect", + { + {SoundType::Shiny, "shiny", "Shiny Sound"}, + {SoundType::LetsGoKill, "lets-go-kill", "Let's Go Kill"}, + }, + LockMode::LOCK_WHILE_RUNNING, + SoundType::Shiny + ) + , STOP_ON_DETECTED_SOUND( + "Stop on the detected sound
Stop program when the sound is detected.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(SOUND_TYPE); + PA_ADD_OPTION(STOP_ON_DETECTED_SOUND); +} + + +// void search_alpha_roar_from_audio_dump(); + +void SoundListener::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Connect the controller. + // pbf_move_right_joystick(context, 0, 255, 10, 0); + + // search_alpha_roar_from_audio_dump(); + // return; + + std::cout << "Running audio test program." << std::endl; + + std::unique_ptr detector; + auto action = [&](float error_coefficient) -> bool{ + // This lambda function will be called when the sound is detected. + // Its return will determine whether to stop the program: + return STOP_ON_DETECTED_SOUND; + }; + + SoundType type = SOUND_TYPE; + switch (type){ + case SoundType::Shiny: + detector = std::make_unique(env.console, action); + break; + case SoundType::LetsGoKill: + detector = std::make_unique(env.console, action); + break; + default: + throw InternalProgramError( + &env.logger(), PA_CURRENT_FUNCTION, + "Not such sound detector as sound type " + std::to_string((size_t)type) + ); + } + +#if 0 + ShinySoundDetector detector0(env.console, action); + LetsGoKillSoundDetector detector1(env.console, action); + InferenceSession session( + context, env.console, + {detector0, detector1} + ); +#else + InferenceSession session( + context, env.console, + {*detector} + ); +#endif + context.wait_until_cancel(); + + std::cout << "Audio test program Sound listener finished." << std::endl; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.h b/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.h index 747f29dc3f..c66e87b1cb 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.h +++ b/SerialPrograms/Source/PokemonSV/Programs/TestPrograms/PokemonSV_SoundListener.h @@ -1,47 +1,47 @@ -/* Sound Listener - * - * From: https://github.com/PokemonAutomation/ - * - * Debug program to test all kinds of sound detectors. - */ - -#ifndef PokemonAutomation_PokemonSV_SoundListener_H -#define PokemonAutomation_PokemonSV_SoundListener_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SoundListener_Descriptor(); -}; - - -class SoundListener : public SingleSwitchProgramInstance{ -public: - SoundListener(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - enum class SoundType{ - Shiny, - LetsGoKill, - }; - EnumDropdownOption SOUND_TYPE; - BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; -}; - - - - -} -} -} -#endif +/* Sound Listener + * + * From: https://github.com/PokemonAutomation/ + * + * Debug program to test all kinds of sound detectors. + */ + +#ifndef PokemonAutomation_PokemonSV_SoundListener_H +#define PokemonAutomation_PokemonSV_SoundListener_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class SoundListener_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SoundListener_Descriptor(); +}; + + +class SoundListener : public SingleSwitchProgramInstance{ +public: + SoundListener(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + enum class SoundType{ + Shiny, + LetsGoKill, + }; + EnumDropdownOption SOUND_TYPE; + BooleanCheckBoxOption STOP_ON_DETECTED_SOUND; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.cpp b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.cpp index 352ab46f83..0eeaeaa65c 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.cpp @@ -1,102 +1,102 @@ -/* Self Box Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -//#include "PokemonSV/PokemonSV_Settings.h" -#include "PokemonSV_TradeRoutines.h" -#include "PokemonSV_SelfBoxTrade.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - using namespace Pokemon; - - -SelfBoxTrade_Descriptor::SelfBoxTrade_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSV:SelfBoxTrade", - STRING_POKEMON + " SV", "Self Box Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonSV/SelfBoxTrade.md", - "Trade boxes of " + STRING_POKEMON + " between two local Switches.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 2, 2, 2 - ) -{} -std::unique_ptr SelfBoxTrade_Descriptor::make_stats() const{ - return std::unique_ptr(new TradeStats()); -} - - - -SelfBoxTrade::SelfBoxTrade() - : BOXES_TO_TRADE( - "Number of Boxes to Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 32 - ) - , START_ROW( - "Starting Row of 1st Box:", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 5 - ) - , START_COL( - "Starting Column of 1st Box:", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 6 - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(START_ROW); - PA_ADD_OPTION(START_COL); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void SelfBoxTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - TradeStats& stats = env.current_stats(); - env.update_stats(); - - uint8_t start_row = START_ROW - 1; - uint8_t start_col = START_COL - 1; - - for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ - if (box != 0){ - env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ - move_to_right_box(context); -// pbf_press_dpad(context, DPAD_RIGHT, 20, 30); -// pbf_press_dpad(context, DPAD_DOWN, 20, 30); -// pbf_press_dpad(context, DPAD_DOWN, 20, 30); -// pbf_press_dpad(context, DPAD_DOWN, 20, 30); - }); - } - trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats, start_row, start_col); - start_row = 0; - start_col = 0; - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Self Box Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +//#include "PokemonSV/PokemonSV_Settings.h" +#include "PokemonSV_TradeRoutines.h" +#include "PokemonSV_SelfBoxTrade.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + using namespace Pokemon; + + +SelfBoxTrade_Descriptor::SelfBoxTrade_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSV:SelfBoxTrade", + STRING_POKEMON + " SV", "Self Box Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonSV/SelfBoxTrade.md", + "Trade boxes of " + STRING_POKEMON + " between two local Switches.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 2, 2, 2 + ) +{} +std::unique_ptr SelfBoxTrade_Descriptor::make_stats() const{ + return std::unique_ptr(new TradeStats()); +} + + + +SelfBoxTrade::SelfBoxTrade() + : BOXES_TO_TRADE( + "Number of Boxes to Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 32 + ) + , START_ROW( + "Starting Row of 1st Box:", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 5 + ) + , START_COL( + "Starting Column of 1st Box:", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 6 + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(START_ROW); + PA_ADD_OPTION(START_COL); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void SelfBoxTrade::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + TradeStats& stats = env.current_stats(); + env.update_stats(); + + uint8_t start_row = START_ROW - 1; + uint8_t start_col = START_COL - 1; + + for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ + if (box != 0){ + env.run_in_parallel(scope, [](ConsoleHandle& console, ProControllerContext& context){ + move_to_right_box(context); +// pbf_press_dpad(context, DPAD_RIGHT, 20, 30); +// pbf_press_dpad(context, DPAD_DOWN, 20, 30); +// pbf_press_dpad(context, DPAD_DOWN, 20, 30); +// pbf_press_dpad(context, DPAD_DOWN, 20, 30); + }); + } + trade_current_box(env, scope, NOTIFICATION_STATUS_UPDATE, stats, start_row, start_col); + start_row = 0; + start_col = 0; + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.h b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.h index 45f3cd3419..ed977b96aa 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_SelfBoxTrade.h @@ -1,48 +1,48 @@ -/* Self Box Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_SelfBoxTrade_H -#define PokemonAutomation_PokemonSV_SelfBoxTrade_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class SelfBoxTrade_Descriptor : public MultiSwitchProgramDescriptor{ -public: - SelfBoxTrade_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class SelfBoxTrade : public MultiSwitchProgramInstance{ -public: - SelfBoxTrade(); - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - SimpleIntegerOption BOXES_TO_TRADE; - - SimpleIntegerOption START_ROW; - SimpleIntegerOption START_COL; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; -}; - - - - -} -} -} -#endif +/* Self Box Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_SelfBoxTrade_H +#define PokemonAutomation_PokemonSV_SelfBoxTrade_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class SelfBoxTrade_Descriptor : public MultiSwitchProgramDescriptor{ +public: + SelfBoxTrade_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class SelfBoxTrade : public MultiSwitchProgramInstance{ +public: + SelfBoxTrade(); + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + SimpleIntegerOption BOXES_TO_TRADE; + + SimpleIntegerOption START_ROW; + SimpleIntegerOption START_COL; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.cpp b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.cpp index 6886860f33..89b5b8d483 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.cpp +++ b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.cpp @@ -1,213 +1,213 @@ -/* Trade Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" -#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" -#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" -#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" -#include "PokemonSV_TradeRoutines.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - - -TradeStats::TradeStats() - : m_trades(m_stats["Trades"]) - , m_errors(m_stats["Errors"]) -{ - m_display_order.emplace_back("Trades"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); -} - - -class TradeWarningDetector : public StaticScreenDetector{ -public: - TradeWarningDetector(Color color) - : m_color(color) -// , m_box_top(0.30, 0.33, 0.40, 0.02) -// , m_box_bot(0.30, 0.65, 0.40, 0.02) - , m_box_left(0.25, 0.33, 0.02, 0.34) - , m_box_right(0.73, 0.33, 0.02, 0.34) - {} - virtual void make_overlays(VideoOverlaySet& items) const override{ -// items.add(m_color, m_box_top); -// items.add(m_color, m_box_bot); - items.add(m_color, m_box_left); - items.add(m_color, m_box_right); - } - virtual bool detect(const ImageViewRGB32& screen) override{ - ImageStats box_top = image_stats(extract_box_reference(screen, m_box_left)); - if (!is_solid(box_top, {0.11424, 0.310539, 0.575221}, 0.30)){ - return false; - } - ImageStats box_bot = image_stats(extract_box_reference(screen, m_box_right)); - if (!is_solid(box_bot, {0.11424, 0.310539, 0.575221}, 0.30)){ - return false; - } - return true; - } - -protected: - Color m_color; -// ImageFloatBox m_box_top; -// ImageFloatBox m_box_bot; - ImageFloatBox m_box_left; - ImageFloatBox m_box_right; -}; -class TradeWarningFinder : public DetectorToFinder{ -public: - TradeWarningFinder(Color color) - : DetectorToFinder("TradeWarningFinder", std::chrono::milliseconds(250), color) - {} -}; - - - -class TradeDoneDetector : public StaticScreenDetector{ -public: - TradeDoneDetector(VideoOverlay& overlay) - : m_cursor(COLOR_RED, GradientArrowType::DOWN, {0.24, 0.17, 0.38, 0.55}) - , m_slot(COLOR_RED, true) - {} - virtual void make_overlays(VideoOverlaySet& items) const override{ - m_cursor.make_overlays(items); - m_slot.make_overlays(items); - } - virtual bool detect(const ImageViewRGB32& screen) override{ - bool cursor_ok = m_cursor.detect(screen); - bool slot_ok = m_slot.detect(screen); -// cout << "cursor = " << cursor_ok << ", slot_ok = " << slot_ok << endl; - return cursor_ok && slot_ok; - } - -private: - GradientArrowDetector m_cursor; - SomethingInBoxSlotDetector m_slot; -}; -class TradeDoneHold : public DetectorToFinder{ -public: - TradeDoneHold(VideoOverlay& overlay) - : DetectorToFinder("AdvanceDialogHold", std::chrono::milliseconds(500), overlay) - {} -}; - - - -void trade_current_pokemon( - VideoStream& stream, ProControllerContext& context, - MultiConsoleErrorState& tracker, - TradeStats& stats -){ - tracker.check_unrecoverable_error(stream.logger()); - context.wait_for_all_requests(); - - // Make sure there is something to trade. - { - SomethingInBoxSlotDetector detector(COLOR_CYAN, true); - if (!detector.detect(stream.video().snapshot())){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Box slot is empty."); - } - } - - - // Wait for black screen. - { - BlackScreenOverWatcher black_screen(COLOR_CYAN); - int ret = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 120 * TICKS_PER_SECOND); - }, - {{black_screen}} - ); - if (ret < 0){ - stats.m_errors++; - tracker.report_unrecoverable_error(stream, "Failed to detect start of trade after 2 minutes."); - } - stream.log("Detected start of trade."); - context.wait_for(std::chrono::milliseconds(100)); - tracker.check_unrecoverable_error(stream.logger()); - } - - - TradeDoneHold trade_done(stream.overlay()); - - while (true){ - AdvanceDialogWatcher dialog(COLOR_YELLOW, DialogType::DIALOG_ALL, std::chrono::seconds(2)); - PromptDialogWatcher learn_move(COLOR_BLUE); - - int ret = wait_until( - stream, context, std::chrono::minutes(2), - {dialog, trade_done, learn_move} - ); - switch (ret){ - case 0: - stream.log("Detected dialog."); - pbf_press_button(context, BUTTON_B, 20, 105); - break; - case 1: - stream.log("Detected box. Trade completed."); - tracker.check_unrecoverable_error(stream.logger()); - context.wait_for(std::chrono::milliseconds(500)); - return; - case 2: - stream.log("Detected move learn."); - pbf_press_button(context, BUTTON_B, 20, 105); - break; - default: - stats.m_errors++; - - tracker.report_unrecoverable_error(stream, "Failed to return to box after 2 minutes after a trade."); - } - } -} - - -void trade_current_box( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - EventNotificationOption& notifications, - TradeStats& stats, - uint8_t start_row, uint8_t start_col -){ - for (uint8_t row = start_row; row < 5; row++){ - for (uint8_t col = start_col; col < 6; col++){ - env.update_stats(); - send_program_status_notification(env, notifications); - - MultiConsoleErrorState error_state; - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - VideoOverlaySet overlays(console.overlay()); - - move_box_cursor(env.program_info(), console, context, BoxCursorLocation::SLOTS, row, col); - - trade_current_pokemon(console, context, error_state, stats); - }); - stats.m_trades++; - } - start_col = 0; - } -} - - - - -} -} -} +/* Trade Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_GradientArrowDetector.h" +#include "PokemonSV/Inference/Dialogs/PokemonSV_DialogDetector.h" +#include "PokemonSV/Inference/Boxes/PokemonSV_BoxDetection.h" +#include "PokemonSV/Programs/Boxes/PokemonSV_BoxRoutines.h" +#include "PokemonSV_TradeRoutines.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + + +TradeStats::TradeStats() + : m_trades(m_stats["Trades"]) + , m_errors(m_stats["Errors"]) +{ + m_display_order.emplace_back("Trades"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); +} + + +class TradeWarningDetector : public StaticScreenDetector{ +public: + TradeWarningDetector(Color color) + : m_color(color) +// , m_box_top(0.30, 0.33, 0.40, 0.02) +// , m_box_bot(0.30, 0.65, 0.40, 0.02) + , m_box_left(0.25, 0.33, 0.02, 0.34) + , m_box_right(0.73, 0.33, 0.02, 0.34) + {} + virtual void make_overlays(VideoOverlaySet& items) const override{ +// items.add(m_color, m_box_top); +// items.add(m_color, m_box_bot); + items.add(m_color, m_box_left); + items.add(m_color, m_box_right); + } + virtual bool detect(const ImageViewRGB32& screen) override{ + ImageStats box_top = image_stats(extract_box_reference(screen, m_box_left)); + if (!is_solid(box_top, {0.11424, 0.310539, 0.575221}, 0.30)){ + return false; + } + ImageStats box_bot = image_stats(extract_box_reference(screen, m_box_right)); + if (!is_solid(box_bot, {0.11424, 0.310539, 0.575221}, 0.30)){ + return false; + } + return true; + } + +protected: + Color m_color; +// ImageFloatBox m_box_top; +// ImageFloatBox m_box_bot; + ImageFloatBox m_box_left; + ImageFloatBox m_box_right; +}; +class TradeWarningFinder : public DetectorToFinder{ +public: + TradeWarningFinder(Color color) + : DetectorToFinder("TradeWarningFinder", std::chrono::milliseconds(250), color) + {} +}; + + + +class TradeDoneDetector : public StaticScreenDetector{ +public: + TradeDoneDetector(VideoOverlay& overlay) + : m_cursor(COLOR_RED, GradientArrowType::DOWN, {0.24, 0.17, 0.38, 0.55}) + , m_slot(COLOR_RED, true) + {} + virtual void make_overlays(VideoOverlaySet& items) const override{ + m_cursor.make_overlays(items); + m_slot.make_overlays(items); + } + virtual bool detect(const ImageViewRGB32& screen) override{ + bool cursor_ok = m_cursor.detect(screen); + bool slot_ok = m_slot.detect(screen); +// cout << "cursor = " << cursor_ok << ", slot_ok = " << slot_ok << endl; + return cursor_ok && slot_ok; + } + +private: + GradientArrowDetector m_cursor; + SomethingInBoxSlotDetector m_slot; +}; +class TradeDoneHold : public DetectorToFinder{ +public: + TradeDoneHold(VideoOverlay& overlay) + : DetectorToFinder("AdvanceDialogHold", std::chrono::milliseconds(500), overlay) + {} +}; + + + +void trade_current_pokemon( + VideoStream& stream, ProControllerContext& context, + MultiConsoleErrorState& tracker, + TradeStats& stats +){ + tracker.check_unrecoverable_error(stream.logger()); + context.wait_for_all_requests(); + + // Make sure there is something to trade. + { + SomethingInBoxSlotDetector detector(COLOR_CYAN, true); + if (!detector.detect(stream.video().snapshot())){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Box slot is empty."); + } + } + + + // Wait for black screen. + { + BlackScreenOverWatcher black_screen(COLOR_CYAN); + int ret = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 120 * TICKS_PER_SECOND); + }, + {{black_screen}} + ); + if (ret < 0){ + stats.m_errors++; + tracker.report_unrecoverable_error(stream, "Failed to detect start of trade after 2 minutes."); + } + stream.log("Detected start of trade."); + context.wait_for(std::chrono::milliseconds(100)); + tracker.check_unrecoverable_error(stream.logger()); + } + + + TradeDoneHold trade_done(stream.overlay()); + + while (true){ + AdvanceDialogWatcher dialog(COLOR_YELLOW, DialogType::DIALOG_ALL, std::chrono::seconds(2)); + PromptDialogWatcher learn_move(COLOR_BLUE); + + int ret = wait_until( + stream, context, std::chrono::minutes(2), + {dialog, trade_done, learn_move} + ); + switch (ret){ + case 0: + stream.log("Detected dialog."); + pbf_press_button(context, BUTTON_B, 20, 105); + break; + case 1: + stream.log("Detected box. Trade completed."); + tracker.check_unrecoverable_error(stream.logger()); + context.wait_for(std::chrono::milliseconds(500)); + return; + case 2: + stream.log("Detected move learn."); + pbf_press_button(context, BUTTON_B, 20, 105); + break; + default: + stats.m_errors++; + + tracker.report_unrecoverable_error(stream, "Failed to return to box after 2 minutes after a trade."); + } + } +} + + +void trade_current_box( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + EventNotificationOption& notifications, + TradeStats& stats, + uint8_t start_row, uint8_t start_col +){ + for (uint8_t row = start_row; row < 5; row++){ + for (uint8_t col = start_col; col < 6; col++){ + env.update_stats(); + send_program_status_notification(env, notifications); + + MultiConsoleErrorState error_state; + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + VideoOverlaySet overlays(console.overlay()); + + move_box_cursor(env.program_info(), console, context, BoxCursorLocation::SLOTS, row, col); + + trade_current_pokemon(console, context, error_state, stats); + }); + stats.m_trades++; + } + start_col = 0; + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h index fcb280b15f..0dbb269dbc 100644 --- a/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h +++ b/SerialPrograms/Source/PokemonSV/Programs/Trading/PokemonSV_TradeRoutines.h @@ -1,49 +1,49 @@ -/* Trade Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TradeRoutines_H -#define PokemonAutomation_PokemonSV_TradeRoutines_H - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/MultiConsoleErrors.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -struct TradeStats : public StatsTracker{ - TradeStats(); - std::atomic& m_trades; - std::atomic& m_errors; -}; - - - - -void trade_current_pokemon( - VideoStream& stream, ProControllerContext& context, - MultiConsoleErrorState& tracker, - TradeStats& stats -); -void trade_current_box( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - EventNotificationOption& notifications, - TradeStats& stats, - uint8_t start_row, uint8_t start_col -); - - - - -} -} -} -#endif +/* Trade Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TradeRoutines_H +#define PokemonAutomation_PokemonSV_TradeRoutines_H + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/MultiConsoleErrors.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +struct TradeStats : public StatsTracker{ + TradeStats(); + std::atomic& m_trades; + std::atomic& m_errors; +}; + + + + +void trade_current_pokemon( + VideoStream& stream, ProControllerContext& context, + MultiConsoleErrorState& tracker, + TradeStats& stats +); +void trade_current_box( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + EventNotificationOption& notifications, + TradeStats& stats, + uint8_t start_row, uint8_t start_col +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.cpp b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.cpp index 38e746d99b..9c31182a6e 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.cpp +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.cpp @@ -1,110 +1,110 @@ -/* Auction Item Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSV_AuctionItemNames.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct AuctionItemNameDatabase{ - AuctionItemNameDatabase(); - - static const AuctionItemNameDatabase& instance(){ - static AuctionItemNameDatabase database; - return database; - } - - static const std::string NULL_SLUG; - std::vector ordered_list; - std::map database; - std::map reverse_lookup; -}; -const std::string AuctionItemNameDatabase::NULL_SLUG; - - -AuctionItemNameDatabase::AuctionItemNameDatabase() -{ - // Load a list of auction item slugs in the desired order: - // ["potion", "fresh-water", ... ] - std::string path_slugs = RESOURCE_PATH() + "PokemonSV/Auction/AuctionItemList.json"; - JsonValue json_slugs = load_json_file(path_slugs); - JsonArray& slugs = json_slugs.to_array_throw(path_slugs); - - // Load a map of auction item slugs to item names in all languages, e.g.: - // { - // "potion": { - // "eng": "Potion", - // "deu": "Trank", - // ... - // }, - // .... - // } - std::string path_disp = RESOURCE_PATH() + "PokemonSV/Auction/AuctionItemNameDisplay.json"; - JsonValue json_disp = load_json_file(path_disp); - JsonObject& item_disp = json_disp.to_object_throw(path_disp); - - for (auto& item : slugs){ - std::string& slug = item.to_string_throw(path_slugs); - - JsonObject& auction_item_name_dict = item_disp.get_object_throw(slug, path_disp); - std::string& display_name = auction_item_name_dict.get_string_throw("eng", path_disp); - - ordered_list.push_back(slug); - database[std::move(slug)].m_display_name = std::move(display_name); - } - - for (const auto& item : database){ - reverse_lookup[item.second.m_display_name] = item.first; - } -} - -const AuctionItemNames& get_auction_item_name(const std::string& slug){ - const std::map& database = AuctionItemNameDatabase::instance().database; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Auction item slug not found in database: " + slug - ); - } - return iter->second; -} -const std::string& parse_auction_item_name(const std::string& display_name){ - const std::map& database = AuctionItemNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Auction item name not found in database: " + display_name - ); - } - return iter->second; -} -const std::string& parse_auction_item_name_nothrow(const std::string& display_name){ - const std::map& database = AuctionItemNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - return AuctionItemNameDatabase::NULL_SLUG; - } - return iter->second; -} - - -const std::vector& AUCTION_ITEM_SLUGS(){ - return AuctionItemNameDatabase::instance().ordered_list; -} - - -} -} -} +/* Auction Item Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSV_AuctionItemNames.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct AuctionItemNameDatabase{ + AuctionItemNameDatabase(); + + static const AuctionItemNameDatabase& instance(){ + static AuctionItemNameDatabase database; + return database; + } + + static const std::string NULL_SLUG; + std::vector ordered_list; + std::map database; + std::map reverse_lookup; +}; +const std::string AuctionItemNameDatabase::NULL_SLUG; + + +AuctionItemNameDatabase::AuctionItemNameDatabase() +{ + // Load a list of auction item slugs in the desired order: + // ["potion", "fresh-water", ... ] + std::string path_slugs = RESOURCE_PATH() + "PokemonSV/Auction/AuctionItemList.json"; + JsonValue json_slugs = load_json_file(path_slugs); + JsonArray& slugs = json_slugs.to_array_throw(path_slugs); + + // Load a map of auction item slugs to item names in all languages, e.g.: + // { + // "potion": { + // "eng": "Potion", + // "deu": "Trank", + // ... + // }, + // .... + // } + std::string path_disp = RESOURCE_PATH() + "PokemonSV/Auction/AuctionItemNameDisplay.json"; + JsonValue json_disp = load_json_file(path_disp); + JsonObject& item_disp = json_disp.to_object_throw(path_disp); + + for (auto& item : slugs){ + std::string& slug = item.to_string_throw(path_slugs); + + JsonObject& auction_item_name_dict = item_disp.get_object_throw(slug, path_disp); + std::string& display_name = auction_item_name_dict.get_string_throw("eng", path_disp); + + ordered_list.push_back(slug); + database[std::move(slug)].m_display_name = std::move(display_name); + } + + for (const auto& item : database){ + reverse_lookup[item.second.m_display_name] = item.first; + } +} + +const AuctionItemNames& get_auction_item_name(const std::string& slug){ + const std::map& database = AuctionItemNameDatabase::instance().database; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Auction item slug not found in database: " + slug + ); + } + return iter->second; +} +const std::string& parse_auction_item_name(const std::string& display_name){ + const std::map& database = AuctionItemNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Auction item name not found in database: " + display_name + ); + } + return iter->second; +} +const std::string& parse_auction_item_name_nothrow(const std::string& display_name){ + const std::map& database = AuctionItemNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + return AuctionItemNameDatabase::NULL_SLUG; + } + return iter->second; +} + + +const std::vector& AUCTION_ITEM_SLUGS(){ + return AuctionItemNameDatabase::instance().ordered_list; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.h index dfccacda84..2decb1317d 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_AuctionItemNames.h @@ -1,39 +1,39 @@ -/* Auction Item Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_AuctionItemNames_H -#define PokemonAutomation_PokemonSV_AuctionItemNames_H - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class AuctionItemNames{ -public: - const std::string& display_name() const{ return m_display_name; } - -private: - friend struct AuctionItemNameDatabase; - - std::string m_display_name; -}; - - -const AuctionItemNames& get_auction_item_name(const std::string& slug); -const std::string& parse_auction_item_name(const std::string& display_name); -const std::string& parse_auction_item_name_nothrow(const std::string& display_name); - -const std::vector& AUCTION_ITEM_SLUGS(); - - -} -} -} -#endif +/* Auction Item Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_AuctionItemNames_H +#define PokemonAutomation_PokemonSV_AuctionItemNames_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class AuctionItemNames{ +public: + const std::string& display_name() const{ return m_display_name; } + +private: + friend struct AuctionItemNameDatabase; + + std::string m_display_name; +}; + + +const AuctionItemNames& get_auction_item_name(const std::string& slug); +const std::string& parse_auction_item_name(const std::string& display_name); +const std::string& parse_auction_item_name_nothrow(const std::string& display_name); + +const std::vector& AUCTION_ITEM_SLUGS(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_FillingsCoordinates.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_FillingsCoordinates.h index a611b36e1e..5273338c4d 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_FillingsCoordinates.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_FillingsCoordinates.h @@ -1,148 +1,148 @@ -/* Fillings Coordinates - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_FillingsCoordinates_H -#define PokemonAutomation_PokemonSV_FillingsCoordinates_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -class FillingsCoordinates{ - - struct FillingInfo{ - uint8_t piecesPerServing; - uint8_t servingsPerPlate; - std::map> placementCoordinates; - }; - - //Easy to place fillings. Three pieces per serving. Cucumber, Pickle, etc. Works with Lettuce, Onion, others as well. - const std::map> flatCircleFilling { //Number of servings, Coordinates for each piece - {1, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //One serving, three pieces - {2, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //Two servings, six pieces - {3, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //Three servings, etc. - {4, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - {5, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - {6, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - }; - - //Hamburger, potato salad, etc. Intended for recipe use. If you do 1 serving each of mutliple big items they'll end up stacking in the center. - const std::map> bigSingleFilling { - {1, { {0.470, 0.507, 0.060, 0.055} }}, //One serving, one piece. If only one place in the center - {2, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //Two pieces, left and right - {3, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055} }}, //Three pieces, left right then center - {4, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //l r l r - {5, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055} }}, //l r l r c - {6, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - }; - - //This is for basil as it has four pieces per serving - const std::map> fourPiecesFilling { - {1, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, //left, center left, center right, right - {2, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, - {3, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, - {4, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, - {5, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, - {6, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, - {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, - }; - - //Cherry tomato - custom coordinates due to placement issues - const std::map> cherryTomatoCustom { - {1, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - {2, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056} }}, - {3, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, - {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058} }}, - {4, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, - {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058}, {0.412, 0.462, 0.062, 0.067}, {0.495, 0.459, 0.061, 0.064}, {0.578, 0.464, 0.061, 0.056} }}, - {5, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, - {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058}, {0.412, 0.462, 0.062, 0.067}, {0.495, 0.459, 0.061, 0.064}, {0.578, 0.464, 0.061, 0.056}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - {6, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, - {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058}, {0.412, 0.462, 0.062, 0.067}, {0.495, 0.459, 0.061, 0.064}, {0.578, 0.464, 0.061, 0.056}, - {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, - }; - - const std::map SandwichFillingsData{ - {"baguette", {0, 0, flatCircleFilling}}, - {"lettuce", {3, 1, flatCircleFilling}}, - {"tomato", {3, 1, flatCircleFilling}}, - {"cherry-tomatoes", {3, 3, cherryTomatoCustom}}, - {"cucumber", {3, 2, flatCircleFilling}}, - {"pickle", {3, 2, flatCircleFilling}}, - {"onion", {3, 2, flatCircleFilling}}, - {"red-onion", {3, 2, flatCircleFilling}}, - {"green-bell-pepper", {3, 2, flatCircleFilling}}, - {"red-bell-pepper", {3, 2, flatCircleFilling}}, - {"yellow-bell-pepper", {3, 2, flatCircleFilling}}, - {"avocado", {3, 2, flatCircleFilling}}, - {"bacon", {3, 1, flatCircleFilling}}, - {"ham", {3, 2, flatCircleFilling}}, - {"prosciutto", {3, 2, flatCircleFilling}}, - {"chorizo", {3, 2, flatCircleFilling}}, - {"herbed-sausage", {3, 2, flatCircleFilling}}, - {"hamburger", {1, 1, bigSingleFilling}}, - {"klawf-stick", {3, 1, flatCircleFilling}}, - {"smoked-fillet", {3, 1, flatCircleFilling}}, - {"fried-fillet", {1, 1, bigSingleFilling}}, - {"egg", {3, 1, flatCircleFilling}}, - {"potato-tortilla", {1, 1, bigSingleFilling}}, - {"tofu", {3, 1, flatCircleFilling}}, - {"rice", {1, 1, bigSingleFilling}}, - {"noodles", {1, 1, bigSingleFilling}}, - {"potato-salad", {1, 1, bigSingleFilling}}, - {"cheese", {3, 1, flatCircleFilling}}, - {"banana", {3, 2, flatCircleFilling}}, - {"strawberry", {3, 2, flatCircleFilling}}, - {"apple", {3, 2, flatCircleFilling}}, - {"kiwi", {3, 2, flatCircleFilling}}, - {"pineapple", {3, 2, flatCircleFilling}}, - {"jalape\xc3\xb1o", {3, 2, flatCircleFilling}}, - {"watercress", {3, 2, flatCircleFilling}}, - {"basil", {4, 1, fourPiecesFilling}}, - }; - -public: - FillingInfo get_filling_information(std::string filling){ - auto iter = SandwichFillingsData.find(filling); - return iter->second; - } - - static FillingsCoordinates& instance(){ - static FillingsCoordinates self; - return self; - } - - -}; -} -} -} -#endif +/* Fillings Coordinates + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_FillingsCoordinates_H +#define PokemonAutomation_PokemonSV_FillingsCoordinates_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +class FillingsCoordinates{ + + struct FillingInfo{ + uint8_t piecesPerServing; + uint8_t servingsPerPlate; + std::map> placementCoordinates; + }; + + //Easy to place fillings. Three pieces per serving. Cucumber, Pickle, etc. Works with Lettuce, Onion, others as well. + const std::map> flatCircleFilling { //Number of servings, Coordinates for each piece + {1, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //One serving, three pieces + {2, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //Two servings, six pieces + {3, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //Three servings, etc. + {4, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + {5, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + {6, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + }; + + //Hamburger, potato salad, etc. Intended for recipe use. If you do 1 serving each of mutliple big items they'll end up stacking in the center. + const std::map> bigSingleFilling { + {1, { {0.470, 0.507, 0.060, 0.055} }}, //One serving, one piece. If only one place in the center + {2, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //Two pieces, left and right + {3, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055} }}, //Three pieces, left right then center + {4, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, //l r l r + {5, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055} }}, //l r l r c + {6, { {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + }; + + //This is for basil as it has four pieces per serving + const std::map> fourPiecesFilling { + {1, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, //left, center left, center right, right + {2, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, + {3, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, + {4, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, + {5, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, + {6, { {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072}, + {0.344, 0.498, 0.064, 0.052} , {0.424, 0.498, 0.064, 0.053}, {0.504, 0.498, 0.061, 0.055}, {0.573, 0.475, 0.076, 0.072} }}, + }; + + //Cherry tomato - custom coordinates due to placement issues + const std::map> cherryTomatoCustom { + {1, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + {2, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056} }}, + {3, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, + {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058} }}, + {4, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, + {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058}, {0.412, 0.462, 0.062, 0.067}, {0.495, 0.459, 0.061, 0.064}, {0.578, 0.464, 0.061, 0.056} }}, + {5, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, + {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058}, {0.412, 0.462, 0.062, 0.067}, {0.495, 0.459, 0.061, 0.064}, {0.578, 0.464, 0.061, 0.056}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + {6, { {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.382, 0.466, 0.064, 0.053}, {0.468, 0.467, 0.064, 0.050}, {0.551, 0.463, 0.064, 0.056}, + {0.339, 0.484, 0.059, 0.055}, {0.428, 0.486, 0.060, 0.056}, {0.528, 0.484, 0.063, 0.058}, {0.412, 0.462, 0.062, 0.067}, {0.495, 0.459, 0.061, 0.064}, {0.578, 0.464, 0.061, 0.056}, + {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055}, {0.386, 0.507, 0.060, 0.055}, {0.470, 0.507, 0.060, 0.055}, {0.554, 0.507, 0.060, 0.055} }}, + }; + + const std::map SandwichFillingsData{ + {"baguette", {0, 0, flatCircleFilling}}, + {"lettuce", {3, 1, flatCircleFilling}}, + {"tomato", {3, 1, flatCircleFilling}}, + {"cherry-tomatoes", {3, 3, cherryTomatoCustom}}, + {"cucumber", {3, 2, flatCircleFilling}}, + {"pickle", {3, 2, flatCircleFilling}}, + {"onion", {3, 2, flatCircleFilling}}, + {"red-onion", {3, 2, flatCircleFilling}}, + {"green-bell-pepper", {3, 2, flatCircleFilling}}, + {"red-bell-pepper", {3, 2, flatCircleFilling}}, + {"yellow-bell-pepper", {3, 2, flatCircleFilling}}, + {"avocado", {3, 2, flatCircleFilling}}, + {"bacon", {3, 1, flatCircleFilling}}, + {"ham", {3, 2, flatCircleFilling}}, + {"prosciutto", {3, 2, flatCircleFilling}}, + {"chorizo", {3, 2, flatCircleFilling}}, + {"herbed-sausage", {3, 2, flatCircleFilling}}, + {"hamburger", {1, 1, bigSingleFilling}}, + {"klawf-stick", {3, 1, flatCircleFilling}}, + {"smoked-fillet", {3, 1, flatCircleFilling}}, + {"fried-fillet", {1, 1, bigSingleFilling}}, + {"egg", {3, 1, flatCircleFilling}}, + {"potato-tortilla", {1, 1, bigSingleFilling}}, + {"tofu", {3, 1, flatCircleFilling}}, + {"rice", {1, 1, bigSingleFilling}}, + {"noodles", {1, 1, bigSingleFilling}}, + {"potato-salad", {1, 1, bigSingleFilling}}, + {"cheese", {3, 1, flatCircleFilling}}, + {"banana", {3, 2, flatCircleFilling}}, + {"strawberry", {3, 2, flatCircleFilling}}, + {"apple", {3, 2, flatCircleFilling}}, + {"kiwi", {3, 2, flatCircleFilling}}, + {"pineapple", {3, 2, flatCircleFilling}}, + {"jalape\xc3\xb1o", {3, 2, flatCircleFilling}}, + {"watercress", {3, 2, flatCircleFilling}}, + {"basil", {4, 1, fourPiecesFilling}}, + }; + +public: + FillingInfo get_filling_information(std::string filling){ + auto iter = SandwichFillingsData.find(filling); + return iter->second; + } + + static FillingsCoordinates& instance(){ + static FillingsCoordinates self; + return self; + } + + +}; +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.cpp b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.cpp index 674381e0f5..3f30ac1344 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.cpp +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.cpp @@ -1,150 +1,150 @@ -/* Pokemon Scarlet/Violet Sandwich Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSV_Ingredients.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - - -std::vector make_ALL_SANDWICH_FILLINGS_SLUGS(){ - std::vector ret; - for (const auto& item : SANDWICH_FILLINGS_DATABASE()){ - ret.emplace_back(item.first); - } - return ret; -} -const std::vector& ALL_SANDWICH_FILLINGS_SLUGS(){ - static std::vector database = make_ALL_SANDWICH_FILLINGS_SLUGS(); - return database; -} - -std::vector make_ALL_SANDWICH_CONDIMENTS_SLUGS(){ - std::vector ret; - for (const auto& item : SANDWICH_CONDIMENTS_DATABASE()){ - ret.emplace_back(item.first); - } - return ret; -} -const std::vector& ALL_SANDWICH_CONDIMENTS_SLUGS(){ - static std::vector database = make_ALL_SANDWICH_CONDIMENTS_SLUGS(); - return database; -} - - - -struct IngredientNameDatabase{ - IngredientNameDatabase(); - - static const IngredientNameDatabase& instance(){ - static IngredientNameDatabase database; - return database; - } - - std::map database; - std::map m_display_name_to_slug; -}; -IngredientNameDatabase::IngredientNameDatabase(){ - { - std::string path = RESOURCE_PATH() + "PokemonSV/Picnic/SandwichFillingOCR.json"; - JsonValue json = load_json_file(path); - JsonObject& object = json.to_object_throw(path); - for (const auto& language_block : object){ - Language language = language_code_to_enum(language_block.first); - const JsonObject& per_language = language_block.second.to_object_throw(path); - for (const auto& slug : per_language){ - const JsonArray& names = slug.second.to_array_throw(path); - if (names.empty()){ - throw JsonParseException(path, "Expected at least one name for: " + language_block.first + " : " + slug.first); - } - database[slug.first].m_display_names[language] = names[0].to_string_throw(); - } - } - for (auto& item : database){ - auto iter = item.second.m_display_names.find(Language::English); - if (iter == item.second.m_display_names.end()){ - throw JsonParseException(path, "English not found for: " + item.first); - } - item.second.m_display_name = iter->second; - m_display_name_to_slug[iter->second] = item.first; - } - } - { - std::string path = RESOURCE_PATH() + "PokemonSV/Picnic/SandwichCondimentOCR.json"; - JsonValue json = load_json_file(path); - JsonObject& object = json.to_object_throw(path); - for (const auto& language_block : object){ - Language language = language_code_to_enum(language_block.first); - const JsonObject& per_language = language_block.second.to_object_throw(path); - for (const auto& slug : per_language){ - const JsonArray& names = slug.second.to_array_throw(path); - if (names.empty()){ - throw JsonParseException(path, "Expected at least one name for: " + language_block.first + " : " + slug.first); - } - database[slug.first].m_display_names[language] = names[0].to_string_throw(); - } - } - for (auto& item : database){ - auto iter = item.second.m_display_names.find(Language::English); - if (iter == item.second.m_display_names.end()){ - throw JsonParseException(path, "English not found for: " + item.first); - } - item.second.m_display_name = iter->second; - m_display_name_to_slug[iter->second] = item.first; - } - } -} - -const SandwichIngredientNames& get_ingredient_name(const std::string& slug){ - const std::map& database = IngredientNameDatabase::instance().database; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Ingredient slug not found in database: " + slug - ); - } - return iter->second; -} - -const std::string& parse_ingredient_name(const std::string& display_name){ - const std::map& database = IngredientNameDatabase::instance().m_display_name_to_slug; - auto iter = database.find(display_name); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Ingredient name not found in database: " + display_name - ); - } - return iter->second; -} - - - - - - -const SpriteDatabase& SANDWICH_FILLINGS_DATABASE(){ - static const SpriteDatabase database("PokemonSV/Picnic/SandwichFillingSprites.png", "PokemonSV/Picnic/SandwichFillingSprites.json"); - return database; -} - -const SpriteDatabase& SANDWICH_CONDIMENTS_DATABASE(){ - static const SpriteDatabase database("PokemonSV/Picnic/SandwichCondimentSprites.png", "PokemonSV/Picnic/SandwichCondimentSprites.json"); - return database; -} - - - -} -} -} +/* Pokemon Scarlet/Violet Sandwich Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSV_Ingredients.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + + +std::vector make_ALL_SANDWICH_FILLINGS_SLUGS(){ + std::vector ret; + for (const auto& item : SANDWICH_FILLINGS_DATABASE()){ + ret.emplace_back(item.first); + } + return ret; +} +const std::vector& ALL_SANDWICH_FILLINGS_SLUGS(){ + static std::vector database = make_ALL_SANDWICH_FILLINGS_SLUGS(); + return database; +} + +std::vector make_ALL_SANDWICH_CONDIMENTS_SLUGS(){ + std::vector ret; + for (const auto& item : SANDWICH_CONDIMENTS_DATABASE()){ + ret.emplace_back(item.first); + } + return ret; +} +const std::vector& ALL_SANDWICH_CONDIMENTS_SLUGS(){ + static std::vector database = make_ALL_SANDWICH_CONDIMENTS_SLUGS(); + return database; +} + + + +struct IngredientNameDatabase{ + IngredientNameDatabase(); + + static const IngredientNameDatabase& instance(){ + static IngredientNameDatabase database; + return database; + } + + std::map database; + std::map m_display_name_to_slug; +}; +IngredientNameDatabase::IngredientNameDatabase(){ + { + std::string path = RESOURCE_PATH() + "PokemonSV/Picnic/SandwichFillingOCR.json"; + JsonValue json = load_json_file(path); + JsonObject& object = json.to_object_throw(path); + for (const auto& language_block : object){ + Language language = language_code_to_enum(language_block.first); + const JsonObject& per_language = language_block.second.to_object_throw(path); + for (const auto& slug : per_language){ + const JsonArray& names = slug.second.to_array_throw(path); + if (names.empty()){ + throw JsonParseException(path, "Expected at least one name for: " + language_block.first + " : " + slug.first); + } + database[slug.first].m_display_names[language] = names[0].to_string_throw(); + } + } + for (auto& item : database){ + auto iter = item.second.m_display_names.find(Language::English); + if (iter == item.second.m_display_names.end()){ + throw JsonParseException(path, "English not found for: " + item.first); + } + item.second.m_display_name = iter->second; + m_display_name_to_slug[iter->second] = item.first; + } + } + { + std::string path = RESOURCE_PATH() + "PokemonSV/Picnic/SandwichCondimentOCR.json"; + JsonValue json = load_json_file(path); + JsonObject& object = json.to_object_throw(path); + for (const auto& language_block : object){ + Language language = language_code_to_enum(language_block.first); + const JsonObject& per_language = language_block.second.to_object_throw(path); + for (const auto& slug : per_language){ + const JsonArray& names = slug.second.to_array_throw(path); + if (names.empty()){ + throw JsonParseException(path, "Expected at least one name for: " + language_block.first + " : " + slug.first); + } + database[slug.first].m_display_names[language] = names[0].to_string_throw(); + } + } + for (auto& item : database){ + auto iter = item.second.m_display_names.find(Language::English); + if (iter == item.second.m_display_names.end()){ + throw JsonParseException(path, "English not found for: " + item.first); + } + item.second.m_display_name = iter->second; + m_display_name_to_slug[iter->second] = item.first; + } + } +} + +const SandwichIngredientNames& get_ingredient_name(const std::string& slug){ + const std::map& database = IngredientNameDatabase::instance().database; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Ingredient slug not found in database: " + slug + ); + } + return iter->second; +} + +const std::string& parse_ingredient_name(const std::string& display_name){ + const std::map& database = IngredientNameDatabase::instance().m_display_name_to_slug; + auto iter = database.find(display_name); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Ingredient name not found in database: " + display_name + ); + } + return iter->second; +} + + + + + + +const SpriteDatabase& SANDWICH_FILLINGS_DATABASE(){ + static const SpriteDatabase database("PokemonSV/Picnic/SandwichFillingSprites.png", "PokemonSV/Picnic/SandwichFillingSprites.json"); + return database; +} + +const SpriteDatabase& SANDWICH_CONDIMENTS_DATABASE(){ + static const SpriteDatabase database("PokemonSV/Picnic/SandwichCondimentSprites.png", "PokemonSV/Picnic/SandwichCondimentSprites.json"); + return database; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.h index f62d818157..cfe51ad403 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_Ingredients.h @@ -1,46 +1,46 @@ -/* Pokemon Scarlet/Violet Ingredients - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_Ingredients_H -#define PokemonAutomation_PokemonSV_Ingredients_H - -#include -#include -#include "CommonFramework/Language.h" -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const std::vector& ALL_SANDWICH_FILLINGS_SLUGS(); -const std::vector& ALL_SANDWICH_CONDIMENTS_SLUGS(); - -class SandwichIngredientNames{ -public: - const std::string& display_name() const{ return m_display_name; } - -private: - friend struct IngredientNameDatabase; - - std::string m_display_name; - std::map m_display_names; -}; - -const SandwichIngredientNames& get_ingredient_name(const std::string& slug); -const std::string& parse_ingredient_name(const std::string& display_name); - - - -const SpriteDatabase& SANDWICH_FILLINGS_DATABASE(); -const SpriteDatabase& SANDWICH_CONDIMENTS_DATABASE(); - - -} -} -} -#endif +/* Pokemon Scarlet/Violet Ingredients + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_Ingredients_H +#define PokemonAutomation_PokemonSV_Ingredients_H + +#include +#include +#include "CommonFramework/Language.h" +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const std::vector& ALL_SANDWICH_FILLINGS_SLUGS(); +const std::vector& ALL_SANDWICH_CONDIMENTS_SLUGS(); + +class SandwichIngredientNames{ +public: + const std::string& display_name() const{ return m_display_name; } + +private: + friend struct IngredientNameDatabase; + + std::string m_display_name; + std::map m_display_names; +}; + +const SandwichIngredientNames& get_ingredient_name(const std::string& slug); +const std::string& parse_ingredient_name(const std::string& display_name); + + + +const SpriteDatabase& SANDWICH_FILLINGS_DATABASE(); +const SpriteDatabase& SANDWICH_CONDIMENTS_DATABASE(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.cpp b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.cpp index 7e2ca4ae1b..9a92a6ada0 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.cpp +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.cpp @@ -1,21 +1,21 @@ -/* Pokemon Scarlet/Violet Item Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSV_ItemSprites.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -const SpriteDatabase& AUCTION_ITEM_SPRITES(){ - static const SpriteDatabase database("PokemonSV/Auction/AuctionItemSprites.png", "PokemonSV/Auction/AuctionItemSprites.json"); - return database; -} - - -} -} -} +/* Pokemon Scarlet/Violet Item Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSV_ItemSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +const SpriteDatabase& AUCTION_ITEM_SPRITES(){ + static const SpriteDatabase database("PokemonSV/Auction/AuctionItemSprites.png", "PokemonSV/Auction/AuctionItemSprites.json"); + return database; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.h index e16107a27e..c8f7f75de2 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_ItemSprites.h @@ -1,22 +1,22 @@ -/* Pokemon Scarlet/Violet Item Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_ItemSprites_H -#define PokemonAutomation_PokemonSV_ItemSprites_H - -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const SpriteDatabase& AUCTION_ITEM_SPRITES(); - -} -} -} -#endif +/* Pokemon Scarlet/Violet Item Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_ItemSprites_H +#define PokemonAutomation_PokemonSV_ItemSprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const SpriteDatabase& AUCTION_ITEM_SPRITES(); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.cpp b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.cpp index 10f3ad24c6..96c909f2d7 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.cpp +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.cpp @@ -1,68 +1,68 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonSV/Resources/PokemonSV_PokemonSprites.h" -#include "PokemonSV_NameDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -using namespace Pokemon; - - -StringSelectDatabase make_name_database(const std::vector& slugs){ - const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); - - StringSelectDatabase database; - for (const std::string& slug : slugs){ - const PokemonNames& name = get_pokemon_name(slug); - const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); - if (sprite){ - database.add_entry(StringSelectEntry( - slug, - name.display_name(), - sprite->icon - )); - }else{ - global_logger_tagged().log("No sprite for: " + slug); - database.add_entry(StringSelectEntry( - slug, - name.display_name() - )); - } - } - return database; -} -StringSelectDatabase make_ALL_POKEMON_NAMES(){ - // For now, use sprites to determine if it's in the game. - const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); - - std::vector slugs; - for (std::string& slug : load_pokemon_slug_json_list("Pokemon/Pokedex/Pokedex-National.json")){ - const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); - if (sprite != nullptr){ - slugs.emplace_back(std::move(slug)); - } - } - - return make_name_database(slugs); -} - - -const StringSelectDatabase& ALL_POKEMON_NAMES(){ - static const StringSelectDatabase database = make_ALL_POKEMON_NAMES(); - return database; -} - - - - -} -} -} +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonSV/Resources/PokemonSV_PokemonSprites.h" +#include "PokemonSV_NameDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +using namespace Pokemon; + + +StringSelectDatabase make_name_database(const std::vector& slugs){ + const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); + + StringSelectDatabase database; + for (const std::string& slug : slugs){ + const PokemonNames& name = get_pokemon_name(slug); + const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); + if (sprite){ + database.add_entry(StringSelectEntry( + slug, + name.display_name(), + sprite->icon + )); + }else{ + global_logger_tagged().log("No sprite for: " + slug); + database.add_entry(StringSelectEntry( + slug, + name.display_name() + )); + } + } + return database; +} +StringSelectDatabase make_ALL_POKEMON_NAMES(){ + // For now, use sprites to determine if it's in the game. + const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); + + std::vector slugs; + for (std::string& slug : load_pokemon_slug_json_list("Pokemon/Pokedex/Pokedex-National.json")){ + const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); + if (sprite != nullptr){ + slugs.emplace_back(std::move(slug)); + } + } + + return make_name_database(slugs); +} + + +const StringSelectDatabase& ALL_POKEMON_NAMES(){ + static const StringSelectDatabase database = make_ALL_POKEMON_NAMES(); + return database; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.h index 1653d4bb3c..778fbeeaa1 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_NameDatabase.h @@ -1,22 +1,22 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -StringSelectDatabase make_name_database(const std::vector& slugs); - -const StringSelectDatabase& ALL_POKEMON_NAMES(); - - - -} -} -} +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +StringSelectDatabase make_name_database(const std::vector& slugs); + +const StringSelectDatabase& ALL_POKEMON_NAMES(); + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.cpp b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.cpp index 95199ce1d0..95434183e5 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.cpp +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.cpp @@ -1,74 +1,74 @@ -/* Pokemon Scarlet/Violet Pokemon Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Globals.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonSV_PokemonSprites.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - -const SpriteDatabase& ALL_POKEMON_SPRITES(){ -#if QT_VERSION_MAJOR == 6 - QImageReader::setAllocationLimit(0); -#endif - static const SpriteDatabase database("PokemonSV/PokemonSprites.png", "PokemonSV/PokemonSprites.json"); - return database; -} - -const SpriteDatabase& ALL_POKEMON_SILHOUETTES(){ -#if QT_VERSION_MAJOR == 6 - QImageReader::setAllocationLimit(0); -#endif - static const SpriteDatabase database("PokemonSV/PokemonSilhouettes.png", "PokemonSV/PokemonSprites.json"); - return database; -} - -const std::array TERA_TYPE_NAMES = { - "Bug", - "Dark", - "Dragon", - "Electric", - "Fairy", - "Fighting", - "Fire", - "Flying", - "Ghost", - "Grass", - "Ground", - "Ice", - "Normal", - "Poison", - "Psychic", - "Rock", - "Steel", - "Water", -}; -std::array BUILD_TERA_TYPE_ICONS(){ - const std::string image_folder_path = RESOURCE_PATH() + "PokemonSV/TeraTypes/"; - - std::array ret; - for (size_t i = 0; i < NUM_TERA_TYPE; i++){ - const auto& type_name = TERA_TYPE_NAMES[i]; - const std::string image_path = image_folder_path + type_name + ".png"; - - // Trim the image to remove 0-alpha boundaries. - ImageRGB32 image(ImageMatch::trim_image_alpha(ImageRGB32(image_path)).copy()); - ret[i] = std::move(image); - } - - return ret; -} -const std::array& ALL_TERA_TYPE_ICONS(){ - const static auto icons = BUILD_TERA_TYPE_ICONS(); - return icons; -} - -} -} -} +/* Pokemon Scarlet/Violet Pokemon Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Globals.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonSV_PokemonSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + +const SpriteDatabase& ALL_POKEMON_SPRITES(){ +#if QT_VERSION_MAJOR == 6 + QImageReader::setAllocationLimit(0); +#endif + static const SpriteDatabase database("PokemonSV/PokemonSprites.png", "PokemonSV/PokemonSprites.json"); + return database; +} + +const SpriteDatabase& ALL_POKEMON_SILHOUETTES(){ +#if QT_VERSION_MAJOR == 6 + QImageReader::setAllocationLimit(0); +#endif + static const SpriteDatabase database("PokemonSV/PokemonSilhouettes.png", "PokemonSV/PokemonSprites.json"); + return database; +} + +const std::array TERA_TYPE_NAMES = { + "Bug", + "Dark", + "Dragon", + "Electric", + "Fairy", + "Fighting", + "Fire", + "Flying", + "Ghost", + "Grass", + "Ground", + "Ice", + "Normal", + "Poison", + "Psychic", + "Rock", + "Steel", + "Water", +}; +std::array BUILD_TERA_TYPE_ICONS(){ + const std::string image_folder_path = RESOURCE_PATH() + "PokemonSV/TeraTypes/"; + + std::array ret; + for (size_t i = 0; i < NUM_TERA_TYPE; i++){ + const auto& type_name = TERA_TYPE_NAMES[i]; + const std::string image_path = image_folder_path + type_name + ".png"; + + // Trim the image to remove 0-alpha boundaries. + ImageRGB32 image(ImageMatch::trim_image_alpha(ImageRGB32(image_path)).copy()); + ret[i] = std::move(image); + } + + return ret; +} +const std::array& ALL_TERA_TYPE_ICONS(){ + const static auto icons = BUILD_TERA_TYPE_ICONS(); + return icons; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.h index 548e3ca1fe..91e1704403 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_PokemonSprites.h @@ -1,50 +1,50 @@ -/* Pokemon Scarlet/Violet Pokemon Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_PokemonSprites_H -#define PokemonAutomation_PokemonSV_PokemonSprites_H - -#include -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -const SpriteDatabase& ALL_POKEMON_SPRITES(); - -const SpriteDatabase& ALL_POKEMON_SILHOUETTES(); - -enum class TeraType{ - Bug, - Dark, - Dragon, - Electric, - Fairy, - Fighting, - Fire, - Flying, - Ghost, - Grass, - Ground, - Ice, - Normal, - Poison, - Psychic, - Rock, - Steel, - Water, -}; -constexpr size_t NUM_TERA_TYPE = 18; -extern const std::array TERA_TYPE_NAMES; -const std::array& ALL_TERA_TYPE_ICONS(); - - -} -} -} -#endif +/* Pokemon Scarlet/Violet Pokemon Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_PokemonSprites_H +#define PokemonAutomation_PokemonSV_PokemonSprites_H + +#include +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +const SpriteDatabase& ALL_POKEMON_SPRITES(); + +const SpriteDatabase& ALL_POKEMON_SILHOUETTES(); + +enum class TeraType{ + Bug, + Dark, + Dragon, + Electric, + Fairy, + Fighting, + Fire, + Flying, + Ghost, + Grass, + Ground, + Ice, + Normal, + Poison, + Psychic, + Rock, + Steel, + Water, +}; +constexpr size_t NUM_TERA_TYPE = 18; +extern const std::array TERA_TYPE_NAMES; +const std::array& ALL_TERA_TYPE_ICONS(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.cpp b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.cpp index 3b71803dbb..2a9588abff 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.cpp +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.cpp @@ -1,109 +1,109 @@ -/* Tournament Prize Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSV_TournamentPrizeNames.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -struct TournamentPrizeNameDatabase{ - TournamentPrizeNameDatabase(); - - static const TournamentPrizeNameDatabase& instance(){ - static TournamentPrizeNameDatabase database; - return database; - } - - static const std::string NULL_SLUG; - std::vector ordered_list; - std::map database; - std::map reverse_lookup; -}; -const std::string TournamentPrizeNameDatabase::NULL_SLUG; - -TournamentPrizeNameDatabase::TournamentPrizeNameDatabase() -{ - // Load a list of tournament prize slugs in the desired order: - // ["potion", "fresh-water", ... ] - std::string path_slugs = RESOURCE_PATH() + "PokemonSV/AAT/TournamentPrizeList.json"; - JsonValue json_slugs = load_json_file(path_slugs); - JsonArray& slugs = json_slugs.to_array_throw(path_slugs); - - // Load a map of tournament prize slugs to item names in all languages, e.g.: - // { - // "potion": { - // "eng": "Potion", - // "deu": "Trank", - // ... - // }, - // .... - // } - std::string path_disp = RESOURCE_PATH() + "PokemonSV/AAT/TournamentPrizeNameDisplay.json"; - JsonValue json_disp = load_json_file(path_disp); - JsonObject& item_disp = json_disp.to_object_throw(path_disp); - - for (auto& item : slugs){ - std::string& slug = item.to_string_throw(path_slugs); - - JsonObject& auction_item_name_dict = item_disp.get_object_throw(slug, path_disp); - std::string& display_name = auction_item_name_dict.get_string_throw("eng", path_disp); - - ordered_list.push_back(slug); - database[std::move(slug)].m_display_name = std::move(display_name); - } - - for (const auto& item : database){ - reverse_lookup[item.second.m_display_name] = item.first; - } -} - -const TournamentPrizeNames& get_tournament_prize_name(const std::string& slug){ - const std::map& database = TournamentPrizeNameDatabase::instance().database; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Tournament prize slug not found in database: " + slug - ); - } - return iter->second; -} -const std::string& parse_tournament_prize_name(const std::string& display_name){ - const std::map& database = TournamentPrizeNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Tournament prize name not found in database: " + display_name - ); - } - return iter->second; -} -const std::string& parse_tournament_prize_name_nothrow(const std::string& display_name){ - const std::map& database = TournamentPrizeNameDatabase::instance().reverse_lookup; - auto iter = database.find(display_name); - if (iter == database.end()){ - return TournamentPrizeNameDatabase::NULL_SLUG; - } - return iter->second; -} - - -const std::vector& TOURNAMENT_PRIZE_SLUGS(){ - return TournamentPrizeNameDatabase::instance().ordered_list; -} - - -} -} -} +/* Tournament Prize Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSV_TournamentPrizeNames.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +struct TournamentPrizeNameDatabase{ + TournamentPrizeNameDatabase(); + + static const TournamentPrizeNameDatabase& instance(){ + static TournamentPrizeNameDatabase database; + return database; + } + + static const std::string NULL_SLUG; + std::vector ordered_list; + std::map database; + std::map reverse_lookup; +}; +const std::string TournamentPrizeNameDatabase::NULL_SLUG; + +TournamentPrizeNameDatabase::TournamentPrizeNameDatabase() +{ + // Load a list of tournament prize slugs in the desired order: + // ["potion", "fresh-water", ... ] + std::string path_slugs = RESOURCE_PATH() + "PokemonSV/AAT/TournamentPrizeList.json"; + JsonValue json_slugs = load_json_file(path_slugs); + JsonArray& slugs = json_slugs.to_array_throw(path_slugs); + + // Load a map of tournament prize slugs to item names in all languages, e.g.: + // { + // "potion": { + // "eng": "Potion", + // "deu": "Trank", + // ... + // }, + // .... + // } + std::string path_disp = RESOURCE_PATH() + "PokemonSV/AAT/TournamentPrizeNameDisplay.json"; + JsonValue json_disp = load_json_file(path_disp); + JsonObject& item_disp = json_disp.to_object_throw(path_disp); + + for (auto& item : slugs){ + std::string& slug = item.to_string_throw(path_slugs); + + JsonObject& auction_item_name_dict = item_disp.get_object_throw(slug, path_disp); + std::string& display_name = auction_item_name_dict.get_string_throw("eng", path_disp); + + ordered_list.push_back(slug); + database[std::move(slug)].m_display_name = std::move(display_name); + } + + for (const auto& item : database){ + reverse_lookup[item.second.m_display_name] = item.first; + } +} + +const TournamentPrizeNames& get_tournament_prize_name(const std::string& slug){ + const std::map& database = TournamentPrizeNameDatabase::instance().database; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Tournament prize slug not found in database: " + slug + ); + } + return iter->second; +} +const std::string& parse_tournament_prize_name(const std::string& display_name){ + const std::map& database = TournamentPrizeNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Tournament prize name not found in database: " + display_name + ); + } + return iter->second; +} +const std::string& parse_tournament_prize_name_nothrow(const std::string& display_name){ + const std::map& database = TournamentPrizeNameDatabase::instance().reverse_lookup; + auto iter = database.find(display_name); + if (iter == database.end()){ + return TournamentPrizeNameDatabase::NULL_SLUG; + } + return iter->second; +} + + +const std::vector& TOURNAMENT_PRIZE_SLUGS(){ + return TournamentPrizeNameDatabase::instance().ordered_list; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h index fa789e33f1..2da8b20877 100644 --- a/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h +++ b/SerialPrograms/Source/PokemonSV/Resources/PokemonSV_TournamentPrizeNames.h @@ -1,39 +1,39 @@ -/* Tournament Prize Names - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSV_TournamentPrizeNames_H -#define PokemonAutomation_PokemonSV_TournamentPrizeNames_H - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSV{ - - -class TournamentPrizeNames{ -public: - const std::string& display_name() const { return m_display_name; } - -private: - friend struct TournamentPrizeNameDatabase; - - std::string m_display_name; -}; - - -const TournamentPrizeNames& get_tournament_prize_name(const std::string& slug); -const std::string& parse_tournament_prize_name(const std::string& display_name); -const std::string& parse_tournament_prize_name_nothrow(const std::string& display_name); - -const std::vector& TOURNAMENT_PRIZE_SLUGS(); - - -} -} -} -#endif +/* Tournament Prize Names + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSV_TournamentPrizeNames_H +#define PokemonAutomation_PokemonSV_TournamentPrizeNames_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSV{ + + +class TournamentPrizeNames{ +public: + const std::string& display_name() const { return m_display_name; } + +private: + friend struct TournamentPrizeNameDatabase; + + std::string m_display_name; +}; + + +const TournamentPrizeNames& get_tournament_prize_name(const std::string& slug); +const std::string& parse_tournament_prize_name(const std::string& display_name); +const std::string& parse_tournament_prize_name_nothrow(const std::string& display_name); + +const std::vector& TOURNAMENT_PRIZE_SLUGS(); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp index 5f49a45fd9..6f6c0543b6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.cpp @@ -1,124 +1,124 @@ -/* Auto Host Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh_Commands_AutoHosts.h" -//#include "PokemonSwSh_Messages_AutoHosts.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void connect_to_internet( - ProControllerContext& context, - Milliseconds open_ycomm_delay, - Milliseconds connect_to_internet_delay -){ - ssf_press_button(context, BUTTON_Y, open_ycomm_delay, 80ms); - - // Move the cursor as far away from Link Trade and Surprise Trade as possible. - // This is added safety in case connect to internet takes too long. - ssf_issue_scroll(context, SSF_SCROLL_UP, 40ms, 40ms, 40ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 40ms, 40ms, 40ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 40ms, 40ms, 40ms); - - // Connect to internet. - ssf_press_button(context, BUTTON_PLUS, 24ms); - - // Mash B to get out of YCOMM. - ssf_mash1_button(context, BUTTON_B, connect_to_internet_delay); -} -void home_to_add_friends( - ProControllerContext& context, - uint8_t user_slot, - uint8_t scroll_down, - bool fix_cursor -){ -// cout << "scroll_down = " << (int)scroll_down << endl; - - // Scroll to correct user. - // Do 2 up-scrolls instead of one. In the event that an error leaves you in - // the game instead of the Switch Home, these button presses will actually - // start the raid - which can kill the den. This will move the cursor over - // "Quit" instead of "Ready to Battle!". - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - for (uint8_t c = 0; c < user_slot; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - } - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - - // Enter user profile. - ssf_press_button_ptv(context, BUTTON_A, 2000ms); - - if (fix_cursor){ - // Force cursor to bottom, then up one to FRs. - for (uint8_t c = 0; c < 40; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); - } - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); - } - - ssf_do_nothing(context, 50); - ssf_issue_scroll_ptv(context, DPAD_RIGHT); - while (scroll_down--){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } -} -void accept_FRs( - ConsoleHandle& console, ProControllerContext& context, - uint8_t slot, bool fix_cursor, - Milliseconds game_to_home_delay_safe, - Milliseconds auto_fr_duration, - bool tolerate_system_update_window_slow -){ - if (slot > 7){ - slot = 7; - } - - // Go to Switch Home menu. - pbf_press_button(context, BUTTON_HOME, 80ms, game_to_home_delay_safe); - - home_to_add_friends(context, slot, 0, fix_cursor); - - // Mash A. - pbf_mash_button(context, BUTTON_A, auto_fr_duration); - - // Return to Switch Home menu. (or game) - if (console.video().snapshot()){ - console.log("Entering game using inference..."); - pbf_press_button(context, BUTTON_HOME, 20, 180); - NintendoSwitch::resume_game_from_home(console, context); - }else{ - console.log("Entering game without inference...", COLOR_RED); - settings_to_enter_game_den_lobby( - context, - tolerate_system_update_window_slow, false, - GameSettings::instance().ENTER_SWITCH_POKEMON0, - GameSettings::instance().EXIT_SWITCH_POKEMON0 - ); - } - pbf_wait(context, 300); -} - - - - -} -} -} - - +/* Auto Host Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh_Commands_AutoHosts.h" +//#include "PokemonSwSh_Messages_AutoHosts.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void connect_to_internet( + ProControllerContext& context, + Milliseconds open_ycomm_delay, + Milliseconds connect_to_internet_delay +){ + ssf_press_button(context, BUTTON_Y, open_ycomm_delay, 80ms); + + // Move the cursor as far away from Link Trade and Surprise Trade as possible. + // This is added safety in case connect to internet takes too long. + ssf_issue_scroll(context, SSF_SCROLL_UP, 40ms, 40ms, 40ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 40ms, 40ms, 40ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 40ms, 40ms, 40ms); + + // Connect to internet. + ssf_press_button(context, BUTTON_PLUS, 24ms); + + // Mash B to get out of YCOMM. + ssf_mash1_button(context, BUTTON_B, connect_to_internet_delay); +} +void home_to_add_friends( + ProControllerContext& context, + uint8_t user_slot, + uint8_t scroll_down, + bool fix_cursor +){ +// cout << "scroll_down = " << (int)scroll_down << endl; + + // Scroll to correct user. + // Do 2 up-scrolls instead of one. In the event that an error leaves you in + // the game instead of the Switch Home, these button presses will actually + // start the raid - which can kill the den. This will move the cursor over + // "Quit" instead of "Ready to Battle!". + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + for (uint8_t c = 0; c < user_slot; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + } + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + + // Enter user profile. + ssf_press_button_ptv(context, BUTTON_A, 2000ms); + + if (fix_cursor){ + // Force cursor to bottom, then up one to FRs. + for (uint8_t c = 0; c < 40; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms); + } + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP); + } + + ssf_do_nothing(context, 50); + ssf_issue_scroll_ptv(context, DPAD_RIGHT); + while (scroll_down--){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } +} +void accept_FRs( + ConsoleHandle& console, ProControllerContext& context, + uint8_t slot, bool fix_cursor, + Milliseconds game_to_home_delay_safe, + Milliseconds auto_fr_duration, + bool tolerate_system_update_window_slow +){ + if (slot > 7){ + slot = 7; + } + + // Go to Switch Home menu. + pbf_press_button(context, BUTTON_HOME, 80ms, game_to_home_delay_safe); + + home_to_add_friends(context, slot, 0, fix_cursor); + + // Mash A. + pbf_mash_button(context, BUTTON_A, auto_fr_duration); + + // Return to Switch Home menu. (or game) + if (console.video().snapshot()){ + console.log("Entering game using inference..."); + pbf_press_button(context, BUTTON_HOME, 20, 180); + NintendoSwitch::resume_game_from_home(console, context); + }else{ + console.log("Entering game without inference...", COLOR_RED); + settings_to_enter_game_den_lobby( + context, + tolerate_system_update_window_slow, false, + GameSettings::instance().ENTER_SWITCH_POKEMON0, + GameSettings::instance().EXIT_SWITCH_POKEMON0 + ); + } + pbf_wait(context, 300); +} + + + + +} +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h index 2c78740091..ade2c55101 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h @@ -1,44 +1,44 @@ -/* Auto Host Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Commands_AutoHosts_H -#define PokemonAutomation_PokemonSwSh_Commands_AutoHosts_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void connect_to_internet( - ProControllerContext& context, - Milliseconds open_ycomm_delay, - Milliseconds connect_to_internet_delay -); -void home_to_add_friends( - ProControllerContext& context, - uint8_t user_slot, - uint8_t scroll_down, - bool fix_cursor -); -void accept_FRs( - ConsoleHandle& console, ProControllerContext& context, - uint8_t slot, bool fix_cursor, - Milliseconds game_to_home_delay_safe, - Milliseconds auto_fr_duration, - bool tolerate_system_update_window_slow -); - - - - -} -} -} -#endif +/* Auto Host Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Commands_AutoHosts_H +#define PokemonAutomation_PokemonSwSh_Commands_AutoHosts_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void connect_to_internet( + ProControllerContext& context, + Milliseconds open_ycomm_delay, + Milliseconds connect_to_internet_delay +); +void home_to_add_friends( + ProControllerContext& context, + uint8_t user_slot, + uint8_t scroll_down, + bool fix_cursor +); +void accept_FRs( + ConsoleHandle& console, ProControllerContext& context, + uint8_t slot, bool fix_cursor, + Milliseconds game_to_home_delay_safe, + Milliseconds auto_fr_duration, + bool tolerate_system_update_window_slow +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp index 7d531ce069..40039e3967 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.cpp @@ -1,245 +1,245 @@ -/* Auto Host Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -//#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "Controllers/ControllerTypes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -//#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h" -#include "PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh_Commands_DateSpam.h" -//#include "PokemonSwSh_Messages_DateSpam.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void rollback_year_skip_forward( - ConsoleHandle& console, ProControllerContext& context -){ - ConsoleType type = console.state().console_type(); - if (is_switch1(type)){ - roll_date_backward_N(console, context, MAX_YEAR, true); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); -// ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); - return; - } - - if (is_switch2(type)){ - roll_date_backward_N(console, context, MAX_YEAR, true); - roll_date_forward_1(console, context, true); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - -void home_roll_date_enter_game( - ConsoleHandle& console, ProControllerContext& context, - bool rollback_year -){ - // From the Switch home menu, roll the date, then re-enter the game. - home_to_date_time(console, context, true); - - if (rollback_year){ - rollback_year_skip_forward(console, context); - }else{ - roll_date_forward_1(console, context, true); - } - - settings_to_enter_game(context, true); - resume_game_from_home(console, context, true); -} -void home_roll_date_enter_game_autorollback( - ConsoleHandle& console, ProControllerContext& context, - uint8_t& year -){ - // This version automatically handles the 2060 roll-back. - if (year >= MAX_YEAR){ - home_roll_date_enter_game(console, context, true); - year = 0; - }else{ - home_roll_date_enter_game(console, context, false); - } - year++; -} - - - - - -void touch_date_from_home_switch1( - ConsoleHandle& console, ProControllerContext& context, - Milliseconds settings_to_home_delay -){ - home_to_date_time(console, context, true); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - - ssf_press_button_ptv(context, BUTTON_A, 0ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_press_button_ptv(context, BUTTON_A, 0ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT, 0ms); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 16ms); - ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); -} -void touch_date_from_home_switch2( - ConsoleHandle& console, ProControllerContext& context, - Milliseconds settings_to_home_delay -){ - home_to_date_time(console, context, true); - - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); - - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); - - ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); -} -void touch_date_from_home( - ConsoleHandle& console, ProControllerContext& context, - Milliseconds settings_to_home_delay -){ - wait_for_home(console, context); - - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - touch_date_from_home_switch1(console, context, settings_to_home_delay); - return; - } - if (is_switch2(type)){ - touch_date_from_home_switch2(console, context, settings_to_home_delay); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - -void rollback_hours_from_home_switch1( - ConsoleHandle& console, ProControllerContext& context, - uint8_t hours, - Milliseconds settings_to_home_delay -){ - home_to_date_time(console, context, true); - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - - ssf_press_button_ptv(context, BUTTON_A, 0ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - for (uint8_t c = 0; c < hours; c++){ - ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); - } - ssf_press_button_ptv(context, BUTTON_A, 0ms); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); - - ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); - ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); -} -void rollback_hours_from_home_switch2( - ConsoleHandle& console, ProControllerContext& context, - uint8_t hours, - Milliseconds settings_to_home_delay -){ - home_to_date_time(console, context, true); - - ssf_press_button(context, BUTTON_A, 216ms, 80ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - for (uint8_t c = 0; c < hours; c++){ - ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); - } - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - ssf_press_button(context, BUTTON_A, 264ms, 80ms); - - ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); -} - - -void rollback_hours_from_home( - ConsoleHandle& console, ProControllerContext& context, - uint8_t hours, - Milliseconds settings_to_home_delay -){ - wait_for_home(console, context); - - ConsoleType type = console.state().console_type(); - - if (is_switch1(type)){ - rollback_hours_from_home_switch1(console, context, hours, settings_to_home_delay); - return; - } - if (is_switch2(type)){ - rollback_hours_from_home_switch2(console, context, hours, settings_to_home_delay); - return; - } - - throw UserSetupError( - console.logger(), - "Please select a valid Switch console type." - ); -} - - - - - -} - -} -} - +/* Auto Host Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +//#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "Controllers/ControllerTypes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +//#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h" +#include "PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh_Commands_DateSpam.h" +//#include "PokemonSwSh_Messages_DateSpam.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void rollback_year_skip_forward( + ConsoleHandle& console, ProControllerContext& context +){ + ConsoleType type = console.state().console_type(); + if (is_switch1(type)){ + roll_date_backward_N(console, context, MAX_YEAR, true); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); +// ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT, 24ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); + return; + } + + if (is_switch2(type)){ + roll_date_backward_N(console, context, MAX_YEAR, true); + roll_date_forward_1(console, context, true); + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + +void home_roll_date_enter_game( + ConsoleHandle& console, ProControllerContext& context, + bool rollback_year +){ + // From the Switch home menu, roll the date, then re-enter the game. + home_to_date_time(console, context, true); + + if (rollback_year){ + rollback_year_skip_forward(console, context); + }else{ + roll_date_forward_1(console, context, true); + } + + settings_to_enter_game(context, true); + resume_game_from_home(console, context, true); +} +void home_roll_date_enter_game_autorollback( + ConsoleHandle& console, ProControllerContext& context, + uint8_t& year +){ + // This version automatically handles the 2060 roll-back. + if (year >= MAX_YEAR){ + home_roll_date_enter_game(console, context, true); + year = 0; + }else{ + home_roll_date_enter_game(console, context, false); + } + year++; +} + + + + + +void touch_date_from_home_switch1( + ConsoleHandle& console, ProControllerContext& context, + Milliseconds settings_to_home_delay +){ + home_to_date_time(console, context, true); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + + ssf_press_button_ptv(context, BUTTON_A, 0ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_press_button_ptv(context, BUTTON_A, 0ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_UP, 16ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT, 0ms); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_LEFT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN, 16ms); + ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); +} +void touch_date_from_home_switch2( + ConsoleHandle& console, ProControllerContext& context, + Milliseconds settings_to_home_delay +){ + home_to_date_time(console, context, true); + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_UP, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); + + ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); +} +void touch_date_from_home( + ConsoleHandle& console, ProControllerContext& context, + Milliseconds settings_to_home_delay +){ + wait_for_home(console, context); + + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + touch_date_from_home_switch1(console, context, settings_to_home_delay); + return; + } + if (is_switch2(type)){ + touch_date_from_home_switch2(console, context, settings_to_home_delay); + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + +void rollback_hours_from_home_switch1( + ConsoleHandle& console, ProControllerContext& context, + uint8_t hours, + Milliseconds settings_to_home_delay +){ + home_to_date_time(console, context, true); + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + + ssf_press_button_ptv(context, BUTTON_A, 0ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + for (uint8_t c = 0; c < hours; c++){ + ssf_issue_scroll_ptv(context, SSF_SCROLL_DOWN); + } + ssf_press_button_ptv(context, BUTTON_A, 0ms); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + ssf_issue_scroll_ptv(context, SSF_SCROLL_RIGHT); + + ssf_press_button_ptv(context, BUTTON_A, 160ms, 80ms); + ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); +} +void rollback_hours_from_home_switch2( + ConsoleHandle& console, ProControllerContext& context, + uint8_t hours, + Milliseconds settings_to_home_delay +){ + home_to_date_time(console, context, true); + + ssf_press_button(context, BUTTON_A, 216ms, 80ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + for (uint8_t c = 0; c < hours; c++){ + ssf_issue_scroll(context, SSF_SCROLL_DOWN, 112ms, 48ms, 24ms); + } + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + ssf_press_button(context, BUTTON_A, 264ms, 80ms); + + ssf_press_button(context, BUTTON_HOME, settings_to_home_delay, 80ms); +} + + +void rollback_hours_from_home( + ConsoleHandle& console, ProControllerContext& context, + uint8_t hours, + Milliseconds settings_to_home_delay +){ + wait_for_home(console, context); + + ConsoleType type = console.state().console_type(); + + if (is_switch1(type)){ + rollback_hours_from_home_switch1(console, context, hours, settings_to_home_delay); + return; + } + if (is_switch2(type)){ + rollback_hours_from_home_switch2(console, context, hours, settings_to_home_delay); + return; + } + + throw UserSetupError( + console.logger(), + "Please select a valid Switch console type." + ); +} + + + + + +} + +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h index 33c1bd07d0..8d9e064f61 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h @@ -1,42 +1,42 @@ -/* Date Spamming Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Commands_DateSpam_H -#define PokemonAutomation_PokemonSwSh_Commands_DateSpam_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -constexpr uint8_t MAX_YEAR = 60; - - -namespace PokemonSwSh{ - -//void neutral_date_skip (ProControllerContext& context); -//void roll_date_forward_1 (ProControllerContext& context, bool fast); -//void roll_date_backward_N (ProControllerContext& context, uint8_t skips, bool fast); -//void home_roll_date_enter_game (ConsoleHandle& console, ProControllerContext& context, bool rollback_year); -void home_roll_date_enter_game_autorollback (ConsoleHandle& console, ProControllerContext& context, uint8_t& year); -void touch_date_from_home ( - ConsoleHandle& console, ProControllerContext& context, - Milliseconds settings_to_home_delay -); -void rollback_hours_from_home( - ConsoleHandle& console, ProControllerContext& context, - uint8_t hours, - Milliseconds settings_to_home_delay -); - -} - -} -} -#endif +/* Date Spamming Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Commands_DateSpam_H +#define PokemonAutomation_PokemonSwSh_Commands_DateSpam_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +constexpr uint8_t MAX_YEAR = 60; + + +namespace PokemonSwSh{ + +//void neutral_date_skip (ProControllerContext& context); +//void roll_date_forward_1 (ProControllerContext& context, bool fast); +//void roll_date_backward_N (ProControllerContext& context, uint8_t skips, bool fast); +//void home_roll_date_enter_game (ConsoleHandle& console, ProControllerContext& context, bool rollback_year); +void home_roll_date_enter_game_autorollback (ConsoleHandle& console, ProControllerContext& context, uint8_t& year); +void touch_date_from_home ( + ConsoleHandle& console, ProControllerContext& context, + Milliseconds settings_to_home_delay +); +void rollback_hours_from_home( + ConsoleHandle& console, ProControllerContext& context, + uint8_t hours, + Milliseconds settings_to_home_delay +); + +} + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp index ce95d41c21..8e95ba78ba 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.cpp @@ -1,75 +1,75 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh_Commands_EggRoutines.h" -//#include "PokemonSwSh_Messages_EggRoutines.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void eggfetcher_loop(ProControllerContext& context){ - ssf_press_left_joystick(context, STICK_MAX, STICK_MAX, 50, 50); - ssf_press_left_joystick(context, STICK_MAX, 160, 0, 510); - ssf_press_button(context, BUTTON_A, 1360ms); - ssf_press_button(context, BUTTON_A, 1360ms); - ssf_press_button(context, BUTTON_A, 1360ms); - ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 50, 390); - ssf_mash1_button(context, BUTTON_B, 90); - ssf_do_nothing(context, 300); - - ssf_press_left_joystick(context, 192, STICK_MIN, 120, 120); - ssf_press_left_joystick(context, STICK_MAX, STICK_MIN, 120, 120); -} -void move_while_mashing_B(ProControllerContext& context, Milliseconds duration){ - // Hold the joystick to the right for the entire duration. - ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 0ms, duration); - - // While the above is running, spam B. - ssf_mash1_button(context, BUTTON_B, duration); -} -void spin_and_mash_A(ProControllerContext& context, Milliseconds duration){ - for (Milliseconds c = 0ms; c < duration; c += 1280ms){ - ssf_press_left_joystick(context, STICK_CENTER, STICK_MAX, 0ms, 320ms); - ssf_press_button(context, BUTTON_A, 160ms); - ssf_press_button(context, BUTTON_A, 160ms); - - ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 0ms, 320ms); - ssf_press_button(context, BUTTON_A, 160ms); - ssf_press_button(context, BUTTON_A, 160ms); - - ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 0ms, 320ms); - ssf_press_button(context, BUTTON_A, 160ms); - ssf_press_button(context, BUTTON_A, 160ms); - - ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 0ms, 320ms); - ssf_press_button(context, BUTTON_A, 160ms); - ssf_press_button(context, BUTTON_A, 160ms); - } -} -void travel_to_spin_location(ProControllerContext& context){ - ssf_press_left_joystick(context, STICK_MAX, 144, 100, 250); - ssf_press_button(context, BUTTON_A, 800ms); - ssf_press_button(context, BUTTON_A, 400ms); - ssf_press_left_joystick(context, STICK_MAX, STICK_MAX, 50, 50); -} -void travel_back_to_lady(ProControllerContext& context){ - ssf_press_left_joystick(context, STICK_CENTER, STICK_MAX, 30, 30); - ssf_press_left_joystick(context, STICK_MAX, 144, 260, 260); - ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 50, 400); - ssf_mash1_button(context, BUTTON_B, 100); - ssf_do_nothing(context, 300); - ssf_press_left_joystick(context, 192, STICK_MIN, 120, 120); - ssf_press_left_joystick(context, STICK_MAX, STICK_MIN, 120, 120); -} - - - -} -} - +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh_Commands_EggRoutines.h" +//#include "PokemonSwSh_Messages_EggRoutines.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void eggfetcher_loop(ProControllerContext& context){ + ssf_press_left_joystick(context, STICK_MAX, STICK_MAX, 50, 50); + ssf_press_left_joystick(context, STICK_MAX, 160, 0, 510); + ssf_press_button(context, BUTTON_A, 1360ms); + ssf_press_button(context, BUTTON_A, 1360ms); + ssf_press_button(context, BUTTON_A, 1360ms); + ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 50, 390); + ssf_mash1_button(context, BUTTON_B, 90); + ssf_do_nothing(context, 300); + + ssf_press_left_joystick(context, 192, STICK_MIN, 120, 120); + ssf_press_left_joystick(context, STICK_MAX, STICK_MIN, 120, 120); +} +void move_while_mashing_B(ProControllerContext& context, Milliseconds duration){ + // Hold the joystick to the right for the entire duration. + ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 0ms, duration); + + // While the above is running, spam B. + ssf_mash1_button(context, BUTTON_B, duration); +} +void spin_and_mash_A(ProControllerContext& context, Milliseconds duration){ + for (Milliseconds c = 0ms; c < duration; c += 1280ms){ + ssf_press_left_joystick(context, STICK_CENTER, STICK_MAX, 0ms, 320ms); + ssf_press_button(context, BUTTON_A, 160ms); + ssf_press_button(context, BUTTON_A, 160ms); + + ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 0ms, 320ms); + ssf_press_button(context, BUTTON_A, 160ms); + ssf_press_button(context, BUTTON_A, 160ms); + + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 0ms, 320ms); + ssf_press_button(context, BUTTON_A, 160ms); + ssf_press_button(context, BUTTON_A, 160ms); + + ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 0ms, 320ms); + ssf_press_button(context, BUTTON_A, 160ms); + ssf_press_button(context, BUTTON_A, 160ms); + } +} +void travel_to_spin_location(ProControllerContext& context){ + ssf_press_left_joystick(context, STICK_MAX, 144, 100, 250); + ssf_press_button(context, BUTTON_A, 800ms); + ssf_press_button(context, BUTTON_A, 400ms); + ssf_press_left_joystick(context, STICK_MAX, STICK_MAX, 50, 50); +} +void travel_back_to_lady(ProControllerContext& context){ + ssf_press_left_joystick(context, STICK_CENTER, STICK_MAX, 30, 30); + ssf_press_left_joystick(context, STICK_MAX, 144, 260, 260); + ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 50, 400); + ssf_mash1_button(context, BUTTON_B, 100); + ssf_do_nothing(context, 300); + ssf_press_left_joystick(context, 192, STICK_MIN, 120, 120); + ssf_press_left_joystick(context, STICK_MAX, STICK_MIN, 120, 120); +} + + + +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h index 0bef06f628..b5a57be09c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h @@ -1,29 +1,29 @@ -/* Egg Routines - * - * From: https://github.com/PokemonAutomation/ - * - * This file requires (PABB_PABOTBASE_LEVEL >= 31). - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Commands_EggRoutines_H -#define PokemonAutomation_PokemonSwSh_Commands_EggRoutines_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void eggfetcher_loop (ProControllerContext& context); -void move_while_mashing_B (ProControllerContext& context, Milliseconds duration); -void spin_and_mash_A (ProControllerContext& context, Milliseconds duration); -void travel_to_spin_location(ProControllerContext& context); -void travel_back_to_lady (ProControllerContext& context); - - - - -} -} -#endif +/* Egg Routines + * + * From: https://github.com/PokemonAutomation/ + * + * This file requires (PABB_PABOTBASE_LEVEL >= 31). + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Commands_EggRoutines_H +#define PokemonAutomation_PokemonSwSh_Commands_EggRoutines_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void eggfetcher_loop (ProControllerContext& context); +void move_while_mashing_B (ProControllerContext& context, Milliseconds duration); +void spin_and_mash_A (ProControllerContext& context, Milliseconds duration); +void travel_to_spin_location(ProControllerContext& context); +void travel_back_to_lady (ProControllerContext& context); + + + + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp index 281c54a9bb..28022817c9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.cpp @@ -1,218 +1,218 @@ -/* Game Entry Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_Commands_GameEntry.h" -//#include "PokemonSwSh_Messages_GameEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void resume_game_no_interact_old(ProControllerContext& context, bool tolerate_update_menu){ - Milliseconds HOME_TO_GAME_DELAY = GameSettings::instance().HOME_TO_GAME_DELAY0; - if (tolerate_update_menu){ - pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_button(context, BUTTON_A, 80ms, HOME_TO_GAME_DELAY); - }else{ - pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); - } -} -void resume_game_back_out_old(ProControllerContext& context, bool tolerate_update_menu, uint16_t mash_B_time){ - Milliseconds HOME_TO_GAME_DELAY = GameSettings::instance().HOME_TO_GAME_DELAY0; - if (tolerate_update_menu){ - pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_button(context, BUTTON_A, 80ms, HOME_TO_GAME_DELAY); - pbf_mash_button(context, BUTTON_B, mash_B_time); - }else{ - pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); - } -} -void resume_game_front_of_den_nowatts(ProControllerContext& context, bool tolerate_update_menu){ - resume_game_back_out_old(context, tolerate_update_menu, 400); -} - -void fast_reset_game( - ProControllerContext& context, - Milliseconds start_game_mash, Milliseconds start_game_wait, - Milliseconds enter_game_mash, Milliseconds enter_game_wait -){ - // Fastest setting. No internet needed and no update menu. - ssf_mash1_button(context, BUTTON_X, 50); - - // Use mashing to ensure that the X press succeeds. If it fails, the SR - // will fail and can kill a den for the autohosts. - ssf_mash2_button(context, BUTTON_X, BUTTON_A, 3s + start_game_mash); - ssf_mash1_button(context, BUTTON_X, start_game_wait); - - ssf_mash_AZs(context, enter_game_mash); - pbf_wait(context, enter_game_wait); -} - -void reset_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu -){ - if (!ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET && !tolerate_update_menu){ - fast_reset_game( - context, - GameSettings::instance().START_GAME_MASH0, - GameSettings::instance().START_GAME_WAIT0, - GameSettings::instance().ENTER_GAME_MASH0, - GameSettings::instance().ENTER_GAME_WAIT0 - ); - return; - } - - close_game(console, context); - start_game_from_home(context, tolerate_update_menu, 0, 0, false); -} -void settings_to_enter_game(ProControllerContext& context, bool fast){ - if (fast){ - // 100 ticks for the first press isn't enough to finish the animation. - // But since the HOME button has delayed effect, we start pressing the 2nd - // press before the animation finishes. - ssf_press_button(context, BUTTON_HOME, 800ms, 160ms); - ssf_press_button(context, BUTTON_HOME, 160ms, 160ms); - }else{ - ssf_press_button(context, BUTTON_HOME, 1600ms, 160ms); - ssf_press_button(context, BUTTON_HOME, 160ms, 160ms); - } -} -void settings_to_enter_game_den_lobby( - ProControllerContext& context, - bool tolerate_update_menu, bool fast, - Milliseconds enter_switch_pokemon_delay, - Milliseconds exit_switch_pokemon_delay -){ - settings_to_enter_game(context, fast); - pbf_wait(context, 90); - if (tolerate_update_menu){ - // home home -// ssf_press_button2(BUTTON_HOME, 100, 10); - // lobby-switch update-yes - ssf_press_dpad(context, DPAD_DOWN, 80ms); - ssf_press_dpad(context, DPAD_UP, 80ms); - // lobby-switch update-start - ssf_press_button(context, BUTTON_A, enter_switch_pokemon_delay, 80ms); - // lobby-select lobby-switch - ssf_press_dpad(context, DPAD_LEFT, 80ms); - // lobby-select lobby-switch - ssf_press_button(context, BUTTON_A, enter_switch_pokemon_delay); - // lobby-confirm lobby-select - ssf_press_button(context, BUTTON_Y, 80ms); - ssf_press_dpad(context, DPAD_LEFT, 80ms); - // lobby-confirm lobby-select - ssf_press_button(context, BUTTON_A, exit_switch_pokemon_delay); - // lobby-switch lobby-switch - }else{ - pbf_wait(context, 50); - } -} -void start_game_from_home( - ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot, - uint8_t user_slot, - bool backup_save -){ - // Start the game with the specified "game_slot" and "user_slot". - // If "game_slot" is zero, it uses whatever the cursor is on. - // If "user_slot" is zero, it uses whatever the cursor is on. - - if (game_slot != 0){ - ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); - for (uint8_t c = 1; c < game_slot; c++){ - ssf_press_dpad_ptv(context, DPAD_RIGHT, 80ms); - } - } - - if (tolerate_update_menu){ - // If the update menu isn't there, these will get swallowed by the opening - // animation for the select user menu. - pbf_press_button(context, BUTTON_A, 20, 35); // Choose game - pbf_press_dpad(context, DPAD_UP, 20, 0); // Skip the update window. - } - - bool START_GAME_REQUIRES_INTERNET = ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET; - Milliseconds START_GAME_MASH = GameSettings::instance().START_GAME_MASH0; - - if (!START_GAME_REQUIRES_INTERNET && user_slot == 0){ - // Mash your way into the game. - pbf_mash_button(context, BUTTON_A, START_GAME_MASH); - }else{ - pbf_press_button(context, BUTTON_A, 20, 160); // Enter select user menu. - if (user_slot != 0){ - // Move to correct user. - for (uint8_t c = 0; c < 8; c++){ - ssf_issue_scroll_ptv(context, DPAD_LEFT, 160ms, 160ms); - } -// pbf_wait(50); - for (uint8_t c = 1; c < user_slot; c++){ - ssf_issue_scroll_ptv(context, DPAD_RIGHT, 160ms, 160ms); - } - } - pbf_press_button(context, BUTTON_A, 20, 20); // Enter game - - // Switch to mashing ZR instead of A to get into the game. - // Mash your way into the game. - Milliseconds duration = START_GAME_MASH; - if (START_GAME_REQUIRES_INTERNET){ - // Need to wait a bit longer for the internet check. - duration += ConsoleSettings::instance().START_GAME_INTERNET_CHECK_DELAY0; - } - pbf_mash_button(context, BUTTON_ZR, duration); - } - - pbf_wait(context, GameSettings::instance().START_GAME_WAIT0); - enter_game( - context, - backup_save, - GameSettings::instance().ENTER_GAME_MASH0, - GameSettings::instance().ENTER_GAME_WAIT0 - ); -} - -void enter_game( - ProControllerContext& context, - bool backup_save, - Milliseconds enter_game_mash, - Milliseconds enter_game_wait -){ - if (backup_save){ - pbf_wait(context, enter_game_mash); - ssf_press_dpad(context, DPAD_UP, 0ms, 80ms); - ssf_press_button(context, BUTTON_B | BUTTON_X, 1000ms, 80ms); - ssf_mash_AZs(context, 5000ms); - if (enter_game_wait > 4s){ - pbf_wait(context, enter_game_wait - 4s); - } - }else{ - ssf_mash_AZs(context, enter_game_mash); - pbf_wait(context, enter_game_wait); - } -} - - - - - - -} -} -} - +/* Game Entry Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_Commands_GameEntry.h" +//#include "PokemonSwSh_Messages_GameEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void resume_game_no_interact_old(ProControllerContext& context, bool tolerate_update_menu){ + Milliseconds HOME_TO_GAME_DELAY = GameSettings::instance().HOME_TO_GAME_DELAY0; + if (tolerate_update_menu){ + pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_button(context, BUTTON_A, 80ms, HOME_TO_GAME_DELAY); + }else{ + pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); + } +} +void resume_game_back_out_old(ProControllerContext& context, bool tolerate_update_menu, uint16_t mash_B_time){ + Milliseconds HOME_TO_GAME_DELAY = GameSettings::instance().HOME_TO_GAME_DELAY0; + if (tolerate_update_menu){ + pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_button(context, BUTTON_A, 80ms, HOME_TO_GAME_DELAY); + pbf_mash_button(context, BUTTON_B, mash_B_time); + }else{ + pbf_press_button(context, BUTTON_HOME, 80ms, HOME_TO_GAME_DELAY); + } +} +void resume_game_front_of_den_nowatts(ProControllerContext& context, bool tolerate_update_menu){ + resume_game_back_out_old(context, tolerate_update_menu, 400); +} + +void fast_reset_game( + ProControllerContext& context, + Milliseconds start_game_mash, Milliseconds start_game_wait, + Milliseconds enter_game_mash, Milliseconds enter_game_wait +){ + // Fastest setting. No internet needed and no update menu. + ssf_mash1_button(context, BUTTON_X, 50); + + // Use mashing to ensure that the X press succeeds. If it fails, the SR + // will fail and can kill a den for the autohosts. + ssf_mash2_button(context, BUTTON_X, BUTTON_A, 3s + start_game_mash); + ssf_mash1_button(context, BUTTON_X, start_game_wait); + + ssf_mash_AZs(context, enter_game_mash); + pbf_wait(context, enter_game_wait); +} + +void reset_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu +){ + if (!ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET && !tolerate_update_menu){ + fast_reset_game( + context, + GameSettings::instance().START_GAME_MASH0, + GameSettings::instance().START_GAME_WAIT0, + GameSettings::instance().ENTER_GAME_MASH0, + GameSettings::instance().ENTER_GAME_WAIT0 + ); + return; + } + + close_game(console, context); + start_game_from_home(context, tolerate_update_menu, 0, 0, false); +} +void settings_to_enter_game(ProControllerContext& context, bool fast){ + if (fast){ + // 100 ticks for the first press isn't enough to finish the animation. + // But since the HOME button has delayed effect, we start pressing the 2nd + // press before the animation finishes. + ssf_press_button(context, BUTTON_HOME, 800ms, 160ms); + ssf_press_button(context, BUTTON_HOME, 160ms, 160ms); + }else{ + ssf_press_button(context, BUTTON_HOME, 1600ms, 160ms); + ssf_press_button(context, BUTTON_HOME, 160ms, 160ms); + } +} +void settings_to_enter_game_den_lobby( + ProControllerContext& context, + bool tolerate_update_menu, bool fast, + Milliseconds enter_switch_pokemon_delay, + Milliseconds exit_switch_pokemon_delay +){ + settings_to_enter_game(context, fast); + pbf_wait(context, 90); + if (tolerate_update_menu){ + // home home +// ssf_press_button2(BUTTON_HOME, 100, 10); + // lobby-switch update-yes + ssf_press_dpad(context, DPAD_DOWN, 80ms); + ssf_press_dpad(context, DPAD_UP, 80ms); + // lobby-switch update-start + ssf_press_button(context, BUTTON_A, enter_switch_pokemon_delay, 80ms); + // lobby-select lobby-switch + ssf_press_dpad(context, DPAD_LEFT, 80ms); + // lobby-select lobby-switch + ssf_press_button(context, BUTTON_A, enter_switch_pokemon_delay); + // lobby-confirm lobby-select + ssf_press_button(context, BUTTON_Y, 80ms); + ssf_press_dpad(context, DPAD_LEFT, 80ms); + // lobby-confirm lobby-select + ssf_press_button(context, BUTTON_A, exit_switch_pokemon_delay); + // lobby-switch lobby-switch + }else{ + pbf_wait(context, 50); + } +} +void start_game_from_home( + ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot, + uint8_t user_slot, + bool backup_save +){ + // Start the game with the specified "game_slot" and "user_slot". + // If "game_slot" is zero, it uses whatever the cursor is on. + // If "user_slot" is zero, it uses whatever the cursor is on. + + if (game_slot != 0){ + ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); + for (uint8_t c = 1; c < game_slot; c++){ + ssf_press_dpad_ptv(context, DPAD_RIGHT, 80ms); + } + } + + if (tolerate_update_menu){ + // If the update menu isn't there, these will get swallowed by the opening + // animation for the select user menu. + pbf_press_button(context, BUTTON_A, 20, 35); // Choose game + pbf_press_dpad(context, DPAD_UP, 20, 0); // Skip the update window. + } + + bool START_GAME_REQUIRES_INTERNET = ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET; + Milliseconds START_GAME_MASH = GameSettings::instance().START_GAME_MASH0; + + if (!START_GAME_REQUIRES_INTERNET && user_slot == 0){ + // Mash your way into the game. + pbf_mash_button(context, BUTTON_A, START_GAME_MASH); + }else{ + pbf_press_button(context, BUTTON_A, 20, 160); // Enter select user menu. + if (user_slot != 0){ + // Move to correct user. + for (uint8_t c = 0; c < 8; c++){ + ssf_issue_scroll_ptv(context, DPAD_LEFT, 160ms, 160ms); + } +// pbf_wait(50); + for (uint8_t c = 1; c < user_slot; c++){ + ssf_issue_scroll_ptv(context, DPAD_RIGHT, 160ms, 160ms); + } + } + pbf_press_button(context, BUTTON_A, 20, 20); // Enter game + + // Switch to mashing ZR instead of A to get into the game. + // Mash your way into the game. + Milliseconds duration = START_GAME_MASH; + if (START_GAME_REQUIRES_INTERNET){ + // Need to wait a bit longer for the internet check. + duration += ConsoleSettings::instance().START_GAME_INTERNET_CHECK_DELAY0; + } + pbf_mash_button(context, BUTTON_ZR, duration); + } + + pbf_wait(context, GameSettings::instance().START_GAME_WAIT0); + enter_game( + context, + backup_save, + GameSettings::instance().ENTER_GAME_MASH0, + GameSettings::instance().ENTER_GAME_WAIT0 + ); +} + +void enter_game( + ProControllerContext& context, + bool backup_save, + Milliseconds enter_game_mash, + Milliseconds enter_game_wait +){ + if (backup_save){ + pbf_wait(context, enter_game_mash); + ssf_press_dpad(context, DPAD_UP, 0ms, 80ms); + ssf_press_button(context, BUTTON_B | BUTTON_X, 1000ms, 80ms); + ssf_mash_AZs(context, 5000ms); + if (enter_game_wait > 4s){ + pbf_wait(context, enter_game_wait - 4s); + } + }else{ + ssf_mash_AZs(context, enter_game_mash); + pbf_wait(context, enter_game_wait); + } +} + + + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h index 90284de5ed..7d36ee54f7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h @@ -1,60 +1,60 @@ -/* Game Entry Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Commands_GameEntry_H -#define PokemonAutomation_PokemonSwSh_Commands_GameEntry_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void resume_game_no_interact_old (ProControllerContext& device, bool tolerate_update_menu); -void resume_game_back_out_old (ProControllerContext& device, bool tolerate_update_menu, uint16_t mash_B_time); -void resume_game_front_of_den_nowatts (ProControllerContext& device, bool tolerate_update_menu); -void settings_to_enter_game (ProControllerContext& device, bool fast); -void settings_to_enter_game_den_lobby( - ProControllerContext& device, - bool tolerate_update_menu, bool fast, - Milliseconds enter_switch_pokemon_delay, - Milliseconds exit_switch_pokemon_delay -); -void enter_game( - ProControllerContext& device, - bool backup_save, - Milliseconds enter_game_mash, - Milliseconds enter_game_wait -); -void start_game_from_home( - ProControllerContext& device, - bool tolerate_update_menu, - uint8_t game_slot, - uint8_t user_slot, - bool backup_save -); -void fast_reset_game( - ProControllerContext& device, - Milliseconds start_game_mash, - Milliseconds start_game_wait, - Milliseconds enter_game_mash, - Milliseconds enter_game_wait -); -void reset_game_from_home( - ConsoleHandle& console, ProControllerContext& device, - bool tolerate_update_menu -); - - - - -} -} -} -#endif +/* Game Entry Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Commands_GameEntry_H +#define PokemonAutomation_PokemonSwSh_Commands_GameEntry_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void resume_game_no_interact_old (ProControllerContext& device, bool tolerate_update_menu); +void resume_game_back_out_old (ProControllerContext& device, bool tolerate_update_menu, uint16_t mash_B_time); +void resume_game_front_of_den_nowatts (ProControllerContext& device, bool tolerate_update_menu); +void settings_to_enter_game (ProControllerContext& device, bool fast); +void settings_to_enter_game_den_lobby( + ProControllerContext& device, + bool tolerate_update_menu, bool fast, + Milliseconds enter_switch_pokemon_delay, + Milliseconds exit_switch_pokemon_delay +); +void enter_game( + ProControllerContext& device, + bool backup_save, + Milliseconds enter_game_mash, + Milliseconds enter_game_wait +); +void start_game_from_home( + ProControllerContext& device, + bool tolerate_update_menu, + uint8_t game_slot, + uint8_t user_slot, + bool backup_save +); +void fast_reset_game( + ProControllerContext& device, + Milliseconds start_game_mash, + Milliseconds start_game_wait, + Milliseconds enter_game_mash, + Milliseconds enter_game_wait +); +void reset_game_from_home( + ConsoleHandle& console, ProControllerContext& device, + bool tolerate_update_menu +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp index bc1f0f8277..b6e7c248d4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.cpp @@ -1,30 +1,30 @@ -/* Misc. Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "ClientSource/Libraries/MessageConverter.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh_Commands_Misc.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void IoA_backout(ProControllerContext& context, Milliseconds pokemon_to_menu_delay){ - // Back out to menu. - // Prepend each B press by a DOWN press so that the B gets - // swallowed while in the summary. - ssf_press_dpad(context, DPAD_DOWN, 40ms, 120ms); - ssf_press_button(context, BUTTON_B, 480ms, 80ms); - ssf_press_dpad(context, DPAD_DOWN, 40ms, 120ms); - ssf_press_button(context, BUTTON_B, pokemon_to_menu_delay, 80ms); -} - - - -} -} - - +/* Misc. Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "ClientSource/Libraries/MessageConverter.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh_Commands_Misc.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void IoA_backout(ProControllerContext& context, Milliseconds pokemon_to_menu_delay){ + // Back out to menu. + // Prepend each B press by a DOWN press so that the B gets + // swallowed while in the summary. + ssf_press_dpad(context, DPAD_DOWN, 40ms, 120ms); + ssf_press_button(context, BUTTON_B, 480ms, 80ms); + ssf_press_dpad(context, DPAD_DOWN, 40ms, 120ms); + ssf_press_button(context, BUTTON_B, pokemon_to_menu_delay, 80ms); +} + + + +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h index f3b7af7631..441092924b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h +++ b/SerialPrograms/Source/PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h @@ -1,22 +1,22 @@ -/* Misc. Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Commands_Misc_H -#define PokemonAutomation_PokemonSwSh_Commands_Misc_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ - - -void IoA_backout (ProControllerContext& context, Milliseconds pokemon_to_menu_delay); - - - -} -} -#endif +/* Misc. Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Commands_Misc_H +#define PokemonAutomation_PokemonSwSh_Commands_Misc_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ + + +void IoA_backout (ProControllerContext& context, Milliseconds pokemon_to_menu_delay); + + + +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.cpp index 6a2c977afe..ebfef98025 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.cpp @@ -1,130 +1,130 @@ -/* Ball Sprite Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" -#include "PokemonSwSh_BattleBallReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const double BattleBallReader::MAX_ALPHA = 0.29; -const double BattleBallReader::ALPHA_SPREAD = 0.02; - - -ImageMatch::ExactImageDictionaryMatcher make_BALL_SPRITE_MATCHER(){ - ImageMatch::ExactImageDictionaryMatcher matcher({1, 128}); - for (const auto& item : ALL_POKEBALL_SPRITES()){ - matcher.add(item.first, item.second.sprite.copy()); - } - return matcher; -} -const ImageMatch::ExactImageDictionaryMatcher& BALL_SPRITE_MATCHER(){ - static ImageMatch::ExactImageDictionaryMatcher matcher = make_BALL_SPRITE_MATCHER(); - return matcher; -} - - - -BattleBallReader::BattleBallReader( - VideoStream& stream, - Language language -) - : m_matcher(BALL_SPRITE_MATCHER()) - , m_name_reader(PokeballNameReader::instance()) - , m_language(language) - , m_stream(stream) - , m_box_sprite(stream.overlay(), {0.649, 0.624, 0.0335, 0.060}) - , m_box_name(stream.overlay(), {0.710, 0.624, 0.18, 0.060}) - , m_box_quantity(stream.overlay(), {0.895, 0.624, 0.059, 0.060}) -{} - -std::string BattleBallReader::read_ball(const ImageViewRGB32& screen) const{ - if (!screen){ - return ""; - } - - ImageMatch::ImageMatchResult sprite_result; - { - sprite_result = m_matcher.match(screen, m_box_sprite, 2, ALPHA_SPREAD); - sprite_result.log(m_stream.logger(), 0.50); - if (!sprite_result.results.empty() && sprite_result.results.begin()->first > MAX_ALPHA){ - sprite_result.results.clear(); - } - } - if (sprite_result.results.empty()){ - ImageViewRGB32 sprite = extract_box_reference(screen, m_box_sprite); - ImageStats stats = image_stats(sprite); - if (stats.stddev.sum() > 20){ - dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Sprite", screen); - } - } - - OCR::StringMatchResult name_result; - { - ImageViewRGB32 cropped = extract_box_reference(screen, m_box_name); - name_result = m_name_reader.read_substring( - m_stream.logger(), m_language, cropped, - OCR::WHITE_TEXT_FILTERS() - ); - } - if (name_result.results.size() != 1){ - dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Name", screen); - } - - if (sprite_result.results.empty()){ - if (name_result.results.size() == 1){ - return name_result.results.begin()->second.token; - } - return ""; - } - - if (sprite_result.results.size() == 1){ - return sprite_result.results.begin()->second; - } - - std::set ocr_slugs; - for (const auto& item : name_result.results){ - ocr_slugs.insert(item.second.token); - } - - std::vector overlap; - for (const auto& item : sprite_result.results){ - auto iter = ocr_slugs.find(item.second); - if (iter != ocr_slugs.end()){ - overlap.emplace_back(item.second); - } - } - if (overlap.size() != 1){ - dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-SpriteNameMismatch", screen); - return ""; - } - return overlap[0]; -} -uint16_t BattleBallReader::read_quantity(const ImageViewRGB32& screen) const{ - ImageRGB32 image = to_blackwhite_rgb32_range( - extract_box_reference(screen, m_box_quantity), - true, - 0xff808080, 0xffffffff - ); - int qty = OCR::read_number(m_stream.logger(), image); - return (uint16_t)std::max(qty, 0); -} - - - - - - -} -} -} +/* Ball Sprite Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" +#include "PokemonSwSh_BattleBallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const double BattleBallReader::MAX_ALPHA = 0.29; +const double BattleBallReader::ALPHA_SPREAD = 0.02; + + +ImageMatch::ExactImageDictionaryMatcher make_BALL_SPRITE_MATCHER(){ + ImageMatch::ExactImageDictionaryMatcher matcher({1, 128}); + for (const auto& item : ALL_POKEBALL_SPRITES()){ + matcher.add(item.first, item.second.sprite.copy()); + } + return matcher; +} +const ImageMatch::ExactImageDictionaryMatcher& BALL_SPRITE_MATCHER(){ + static ImageMatch::ExactImageDictionaryMatcher matcher = make_BALL_SPRITE_MATCHER(); + return matcher; +} + + + +BattleBallReader::BattleBallReader( + VideoStream& stream, + Language language +) + : m_matcher(BALL_SPRITE_MATCHER()) + , m_name_reader(PokeballNameReader::instance()) + , m_language(language) + , m_stream(stream) + , m_box_sprite(stream.overlay(), {0.649, 0.624, 0.0335, 0.060}) + , m_box_name(stream.overlay(), {0.710, 0.624, 0.18, 0.060}) + , m_box_quantity(stream.overlay(), {0.895, 0.624, 0.059, 0.060}) +{} + +std::string BattleBallReader::read_ball(const ImageViewRGB32& screen) const{ + if (!screen){ + return ""; + } + + ImageMatch::ImageMatchResult sprite_result; + { + sprite_result = m_matcher.match(screen, m_box_sprite, 2, ALPHA_SPREAD); + sprite_result.log(m_stream.logger(), 0.50); + if (!sprite_result.results.empty() && sprite_result.results.begin()->first > MAX_ALPHA){ + sprite_result.results.clear(); + } + } + if (sprite_result.results.empty()){ + ImageViewRGB32 sprite = extract_box_reference(screen, m_box_sprite); + ImageStats stats = image_stats(sprite); + if (stats.stddev.sum() > 20){ + dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Sprite", screen); + } + } + + OCR::StringMatchResult name_result; + { + ImageViewRGB32 cropped = extract_box_reference(screen, m_box_name); + name_result = m_name_reader.read_substring( + m_stream.logger(), m_language, cropped, + OCR::WHITE_TEXT_FILTERS() + ); + } + if (name_result.results.size() != 1){ + dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-Name", screen); + } + + if (sprite_result.results.empty()){ + if (name_result.results.size() == 1){ + return name_result.results.begin()->second.token; + } + return ""; + } + + if (sprite_result.results.size() == 1){ + return sprite_result.results.begin()->second; + } + + std::set ocr_slugs; + for (const auto& item : name_result.results){ + ocr_slugs.insert(item.second.token); + } + + std::vector overlap; + for (const auto& item : sprite_result.results){ + auto iter = ocr_slugs.find(item.second); + if (iter != ocr_slugs.end()){ + overlap.emplace_back(item.second); + } + } + if (overlap.size() != 1){ + dump_image(m_stream.logger(), ProgramInfo(), "BattleBallReader-SpriteNameMismatch", screen); + return ""; + } + return overlap[0]; +} +uint16_t BattleBallReader::read_quantity(const ImageViewRGB32& screen) const{ + ImageRGB32 image = to_blackwhite_rgb32_range( + extract_box_reference(screen, m_box_quantity), + true, + 0xff808080, 0xffffffff + ); + int qty = OCR::read_number(m_stream.logger(), image); + return (uint16_t)std::max(qty, 0); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h index c678111685..7daca6382d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h @@ -1,52 +1,52 @@ -/* In-Battle Ball Inventory Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BattleBallInventoryReader_H -#define PokemonAutomation_PokemonSwSh_BattleBallInventoryReader_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/ImageMatch/ExactImageDictionaryMatcher.h" -#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - - -class BattleBallReader{ - static const double MAX_ALPHA; - static const double ALPHA_SPREAD; - -public: - BattleBallReader( - VideoStream& stream, - Language language - ); - -public: - std::string read_ball(const ImageViewRGB32& screen) const; - uint16_t read_quantity(const ImageViewRGB32& screen) const; - -private: - const ImageMatch::ExactImageDictionaryMatcher& m_matcher; - const PokeballNameReader& m_name_reader; - Language m_language; - VideoStream& m_stream; - OverlayBoxScope m_box_sprite; - OverlayBoxScope m_box_name; - OverlayBoxScope m_box_quantity; -}; - - - - -} -} -} -#endif +/* In-Battle Ball Inventory Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BattleBallInventoryReader_H +#define PokemonAutomation_PokemonSwSh_BattleBallInventoryReader_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/ImageMatch/ExactImageDictionaryMatcher.h" +#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + + +class BattleBallReader{ + static const double MAX_ALPHA; + static const double ALPHA_SPREAD; + +public: + BattleBallReader( + VideoStream& stream, + Language language + ); + +public: + std::string read_ball(const ImageViewRGB32& screen) const; + uint16_t read_quantity(const ImageViewRGB32& screen) const; + +private: + const ImageMatch::ExactImageDictionaryMatcher& m_matcher; + const PokeballNameReader& m_name_reader; + Language m_language; + VideoStream& m_stream; + OverlayBoxScope m_box_sprite; + OverlayBoxScope m_box_name; + OverlayBoxScope m_box_quantity; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.cpp index b04d225807..4b7e932af7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.cpp @@ -1,66 +1,66 @@ -/* Battle Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_BattleDialogDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -BattleDialogDetector::BattleDialogDetector(Color color) - : m_color(color) - , m_bottom(0.50, 0.89, 0.40, 0.07) - , m_left(0.01, 0.82, 0.03, 0.07) - , m_right(0.97, 0.87, 0.02, 0.09) -{} -void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_bottom); - items.add(m_color, m_left); - items.add(m_color, m_right); -} -bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << "bottom: " << bottom.average << bottom.stddev << endl; - if (!is_grey(bottom, 0, 200, 10)){ - return false; - } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << "left: " << left.average << left.stddev << endl; - if (!is_grey(left, 0, 200, 5)){ - return false; - } - ImageStats right = image_stats(extract_box_reference(screen, m_right)); -// cout << "right: " << right.average << right.stddev << endl; - if (!is_grey(right, 0, 200, 5)){ - return false; - } - - if (euclidean_distance(left.average, right.average) > 10){ - return false; - } - if (left.average.sum() > bottom.average.sum()){ - return false; - } - if (right.average.sum() > bottom.average.sum()){ - return false; - } - - return true; -} - - -} -} -} +/* Battle Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_BattleDialogDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +BattleDialogDetector::BattleDialogDetector(Color color) + : m_color(color) + , m_bottom(0.50, 0.89, 0.40, 0.07) + , m_left(0.01, 0.82, 0.03, 0.07) + , m_right(0.97, 0.87, 0.02, 0.09) +{} +void BattleDialogDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_bottom); + items.add(m_color, m_left); + items.add(m_color, m_right); +} +bool BattleDialogDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << "bottom: " << bottom.average << bottom.stddev << endl; + if (!is_grey(bottom, 0, 200, 10)){ + return false; + } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << "left: " << left.average << left.stddev << endl; + if (!is_grey(left, 0, 200, 5)){ + return false; + } + ImageStats right = image_stats(extract_box_reference(screen, m_right)); +// cout << "right: " << right.average << right.stddev << endl; + if (!is_grey(right, 0, 200, 5)){ + return false; + } + + if (euclidean_distance(left.average, right.average) > 10){ + return false; + } + if (left.average.sum() > bottom.average.sum()){ + return false; + } + if (right.average.sum() > bottom.average.sum()){ + return false; + } + + return true; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h index 2f74196e7a..bb31084cf3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h @@ -1,39 +1,39 @@ -/* Battle Dialog Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BattleDialogDetector_H -#define PokemonAutomation_PokemonSwSh_BattleDialogDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class BattleDialogDetector : public StaticScreenDetector{ -public: - BattleDialogDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - ImageFloatBox m_bottom; - ImageFloatBox m_left; - ImageFloatBox m_right; -}; - - - -} -} -} -#endif +/* Battle Dialog Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BattleDialogDetector_H +#define PokemonAutomation_PokemonSwSh_BattleDialogDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class BattleDialogDetector : public StaticScreenDetector{ +public: + BattleDialogDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + ImageFloatBox m_bottom; + ImageFloatBox m_left; + ImageFloatBox m_right; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.cpp index fc794dff15..6b5d47f104 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.cpp @@ -1,109 +1,109 @@ -/* Encounter Dialog Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonSwSh_BattleDialogTracker.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -EncounterDialogTracker::EncounterDialogTracker( - Logger& logger, - StaticScreenDetector& dialog_detector -) - : VisualInferenceCallback("EncounterDialogTracker") - , m_logger(logger) - , m_dialog_detector(dialog_detector) - , m_end_dialog(current_time()) - , m_dialog_on(false) - , m_state(EncounterState::BEFORE_ANYTHING) - , m_wild_animation_duration(0) - , m_your_animation_duration(0) -{} - -void EncounterDialogTracker::make_overlays(VideoOverlaySet& items) const{ - m_dialog_detector.make_overlays(items); -} -bool EncounterDialogTracker::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ - bool dialog_on = m_dialog_detector.detect(screen); -// cout << dialog_on << endl; - if (dialog_on == m_dialog_on.load(std::memory_order_relaxed)){ - return false; - } - m_dialog_on.store(dialog_on, std::memory_order_release); - - if (!dialog_on){ - m_end_dialog = timestamp; - m_logger.log("DialogTracker: Dialog on -> off. Starting timer.", COLOR_PURPLE); - return false; - } - - std::chrono::milliseconds gap_duration = std::chrono::duration_cast(timestamp - m_end_dialog); - m_logger.log( - "DialogTracker: Dialog off -> on. " + - tostr_default(gap_duration.count() / 1000.) + " seconds", - COLOR_PURPLE - ); - -// static int c = 0; -// screen.save("test-" + std::to_string(c++) + ".png"); - - EncounterState state = m_state.load(std::memory_order_relaxed); - switch (state){ - case EncounterState::BEFORE_ANYTHING: - m_state.store((EncounterState)((size_t)state + 1), std::memory_order_release); - m_logger.log("DialogTracker: Starting wild animation.", COLOR_PURPLE); - break; - case EncounterState::WILD_ANIMATION: - m_wild_animation_duration = gap_duration; - m_state.store((EncounterState)((size_t)state + 1), std::memory_order_release); - m_logger.log("DialogTracker: Starting your animation.", COLOR_PURPLE); - break; - case EncounterState::YOUR_ANIMATION: - m_your_animation_duration = gap_duration; - m_state.store((EncounterState)((size_t)state + 1), std::memory_order_release); - m_logger.log("DialogTracker: Starting post-entry.", COLOR_PURPLE); - break; - case EncounterState::POST_ENTRY: - m_logger.log("DialogTracker: Starting post-entry.", COLOR_PURPLE); - break; - } - return false; -} -void EncounterDialogTracker::push_end(WallClock timestamp){ - std::chrono::milliseconds gap_duration = std::chrono::duration_cast(timestamp - m_end_dialog); - m_logger.log( - "DialogTracker: End " + - tostr_default(gap_duration.count() / 1000.) + " seconds", - COLOR_PURPLE - ); - EncounterState state = m_state.load(std::memory_order_relaxed); - switch (state){ - case EncounterState::BEFORE_ANYTHING: - break; - case EncounterState::WILD_ANIMATION: - m_wild_animation_duration = gap_duration; - break; - case EncounterState::YOUR_ANIMATION: - m_your_animation_duration = gap_duration; - break; - case EncounterState::POST_ENTRY: - break; - } -} - - - -} -} -} +/* Encounter Dialog Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonSwSh_BattleDialogTracker.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +EncounterDialogTracker::EncounterDialogTracker( + Logger& logger, + StaticScreenDetector& dialog_detector +) + : VisualInferenceCallback("EncounterDialogTracker") + , m_logger(logger) + , m_dialog_detector(dialog_detector) + , m_end_dialog(current_time()) + , m_dialog_on(false) + , m_state(EncounterState::BEFORE_ANYTHING) + , m_wild_animation_duration(0) + , m_your_animation_duration(0) +{} + +void EncounterDialogTracker::make_overlays(VideoOverlaySet& items) const{ + m_dialog_detector.make_overlays(items); +} +bool EncounterDialogTracker::process_frame(const ImageViewRGB32& screen, WallClock timestamp){ + bool dialog_on = m_dialog_detector.detect(screen); +// cout << dialog_on << endl; + if (dialog_on == m_dialog_on.load(std::memory_order_relaxed)){ + return false; + } + m_dialog_on.store(dialog_on, std::memory_order_release); + + if (!dialog_on){ + m_end_dialog = timestamp; + m_logger.log("DialogTracker: Dialog on -> off. Starting timer.", COLOR_PURPLE); + return false; + } + + std::chrono::milliseconds gap_duration = std::chrono::duration_cast(timestamp - m_end_dialog); + m_logger.log( + "DialogTracker: Dialog off -> on. " + + tostr_default(gap_duration.count() / 1000.) + " seconds", + COLOR_PURPLE + ); + +// static int c = 0; +// screen.save("test-" + std::to_string(c++) + ".png"); + + EncounterState state = m_state.load(std::memory_order_relaxed); + switch (state){ + case EncounterState::BEFORE_ANYTHING: + m_state.store((EncounterState)((size_t)state + 1), std::memory_order_release); + m_logger.log("DialogTracker: Starting wild animation.", COLOR_PURPLE); + break; + case EncounterState::WILD_ANIMATION: + m_wild_animation_duration = gap_duration; + m_state.store((EncounterState)((size_t)state + 1), std::memory_order_release); + m_logger.log("DialogTracker: Starting your animation.", COLOR_PURPLE); + break; + case EncounterState::YOUR_ANIMATION: + m_your_animation_duration = gap_duration; + m_state.store((EncounterState)((size_t)state + 1), std::memory_order_release); + m_logger.log("DialogTracker: Starting post-entry.", COLOR_PURPLE); + break; + case EncounterState::POST_ENTRY: + m_logger.log("DialogTracker: Starting post-entry.", COLOR_PURPLE); + break; + } + return false; +} +void EncounterDialogTracker::push_end(WallClock timestamp){ + std::chrono::milliseconds gap_duration = std::chrono::duration_cast(timestamp - m_end_dialog); + m_logger.log( + "DialogTracker: End " + + tostr_default(gap_duration.count() / 1000.) + " seconds", + COLOR_PURPLE + ); + EncounterState state = m_state.load(std::memory_order_relaxed); + switch (state){ + case EncounterState::BEFORE_ANYTHING: + break; + case EncounterState::WILD_ANIMATION: + m_wild_animation_duration = gap_duration; + break; + case EncounterState::YOUR_ANIMATION: + m_your_animation_duration = gap_duration; + break; + case EncounterState::POST_ENTRY: + break; + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h index cf646b5e8d..db88d9c5f3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h @@ -1,64 +1,64 @@ -/* Encounter Dialog Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterDialogTracker_H -#define PokemonAutomation_PokemonSwSh_EncounterDialogTracker_H - -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -enum class EncounterState{ - BEFORE_ANYTHING, - WILD_ANIMATION, - YOUR_ANIMATION, - POST_ENTRY, -}; - - -class EncounterDialogTracker : public VisualInferenceCallback{ -public: - EncounterDialogTracker( - Logger& logger, - StaticScreenDetector& dialog_detector - ); - - // Thread-safe - bool dialog_on() const{ return m_dialog_on.load(std::memory_order_acquire); } - EncounterState encounter_state() const{ return m_state.load(std::memory_order_acquire); } - - // Not thread-safe - std::chrono::milliseconds wild_animation_duration() const{ return m_wild_animation_duration; } - std::chrono::milliseconds your_animation_duration() const{ return m_your_animation_duration; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - using VisualInferenceCallback::process_frame; - void push_end(WallClock timestamp = current_time()); - -private: - Logger& m_logger; - StaticScreenDetector& m_dialog_detector; - WallClock m_end_dialog; - - std::atomic m_dialog_on; - std::atomic m_state; - - std::chrono::milliseconds m_wild_animation_duration; - std::chrono::milliseconds m_your_animation_duration; -}; - - -} -} -} -#endif +/* Encounter Dialog Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterDialogTracker_H +#define PokemonAutomation_PokemonSwSh_EncounterDialogTracker_H + +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +enum class EncounterState{ + BEFORE_ANYTHING, + WILD_ANIMATION, + YOUR_ANIMATION, + POST_ENTRY, +}; + + +class EncounterDialogTracker : public VisualInferenceCallback{ +public: + EncounterDialogTracker( + Logger& logger, + StaticScreenDetector& dialog_detector + ); + + // Thread-safe + bool dialog_on() const{ return m_dialog_on.load(std::memory_order_acquire); } + EncounterState encounter_state() const{ return m_state.load(std::memory_order_acquire); } + + // Not thread-safe + std::chrono::milliseconds wild_animation_duration() const{ return m_wild_animation_duration; } + std::chrono::milliseconds your_animation_duration() const{ return m_your_animation_duration; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + using VisualInferenceCallback::process_frame; + void push_end(WallClock timestamp = current_time()); + +private: + Logger& m_logger; + StaticScreenDetector& m_dialog_detector; + WallClock m_end_dialog; + + std::atomic m_dialog_on; + std::atomic m_state; + + std::chrono::milliseconds m_wild_animation_duration; + std::chrono::milliseconds m_your_animation_duration; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.cpp index 9e020e6a11..094f010edc 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.cpp @@ -1,269 +1,269 @@ -/* Battle Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/ColorClustering.h" -#include "PokemonSwSh_BattleMenuDetector.h" - -//#include -//using std::cout; -//using std::endl; - -//#define DEBUG_StandardBattleMenuDetector - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -StandardBattleMenuDetector::StandardBattleMenuDetector( - bool den, - Color color -) - : m_den(den) - , m_color(color) - , m_ball_left (0.912, 0.452, 0.02, 0.03) - , m_ball_right (0.970, 0.452, 0.02, 0.03) - , m_icon_fight (0.923, 0.576 + 0 * 0.1075, 0.05, 0.080) - , m_icon_pokemon(0.923, 0.576 + 1 * 0.1075, 0.05, 0.080) - , m_icon_bag (0.923, 0.576 + 2 * 0.1075, 0.05, 0.080) - , m_icon_run (0.923, 0.576 + 3 * 0.1075, 0.05, 0.080) - , m_text_fight (0.830, 0.576 + 0 * 0.1075, 0.08, 0.080) - , m_text_pokemon(0.830, 0.576 + 1 * 0.1075, 0.08, 0.080) - , m_text_bag (0.830, 0.576 + 2 * 0.1075, 0.08, 0.080) - , m_text_run (0.830, 0.576 + 3 * 0.1075, 0.08, 0.080) -// , m_status0 (0.280, 0.870, 0.015, 0.030) - , m_status1 (0.165, 0.945, 0.100, 0.015) -{} -void StandardBattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - if (!m_den){ - items.add(m_color, m_ball_left); - items.add(m_color, m_ball_right); - }else{ - items.add(m_color, m_status1); - } - items.add(m_color, m_icon_fight); - items.add(m_color, m_icon_pokemon); - items.add(m_color, m_icon_bag); - items.add(m_color, m_icon_run); - items.add(m_color, m_text_fight); - items.add(m_color, m_text_pokemon); - items.add(m_color, m_text_bag); - items.add(m_color, m_text_run); -} -bool StandardBattleMenuDetector::detect(const ImageViewRGB32& screen){ - if (!m_den){ - if (!is_white(extract_box_reference(screen, m_ball_left))){ - return false; - } - if (!is_white(extract_box_reference(screen, m_ball_right))){ - return false; - } - }else{ - ImageStats health = image_stats(extract_box_reference(screen, m_status1)); - if (!is_white(health)){ -// cout << "Failed: m_status1" << endl; -// extract_box_reference(screen, m_status1).save("test.png"); - return false; - } - } - - bool fight; - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Fight Text 0" << endl; -#endif - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_fight), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_fight), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - if (!fight){ -// cout << "Failed: m_text_fight" << endl; - return false; - } - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Pokemon Text" << endl; -#endif - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_pokemon), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_pokemon), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - if (!fight){ -// cout << "Failed: m_text_pokemon" << endl; - return false; - } - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Bag Text" << endl; -#endif - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_bag), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_bag), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - if (!fight){ -// cout << "Failed: m_text_bag" << endl; - return false; - } - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Run Text" << endl; -#endif - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_run), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_run), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - if (!fight){ -// cout << "Failed: m_text_run" << endl; - return false; - } - - -#if 1 -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Fight Symbol 0" << endl; -#endif - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_icon_fight), - Color(255, 255, 255), 1.7, - Color(153, 75, 112), 1.0 - ); -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Fight Symbol 1" << endl; -#endif - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_icon_fight), - Color(0, 0, 0), 1.4, - Color(185, 6, 40), 1.0 - ); - fight |= !fight && cluster_fit_2( // Max raid Fight button is a bit different. - extract_box_reference(screen, m_icon_fight), - Color(0, 0, 0), 1.7, - Color(182, 33, 82), 1.0 - ); - if (!fight){ -// cout << "Failed: m_icon_fight" << endl; - return false; - } - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Pokemon Symbol" << endl; -#endif - bool pokemon = false; - pokemon |= !pokemon && cluster_fit_2( - extract_box_reference(screen, m_icon_pokemon), - Color(255, 255, 255), 3.1, - Color(126, 224, 142), 1.0 - ); - pokemon |= !pokemon && cluster_fit_2( - extract_box_reference(screen, m_icon_pokemon), - Color(0, 0, 0), 2.7, - Color(8, 158, 18), 1.0 - ); - if (!pokemon){ -// cout << "Failed: m_icon_pokemon" << endl; - return false; - } - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Bag Symbol" << endl; -#endif - bool bag = false; - bag |= !bag && cluster_fit_2( - extract_box_reference(screen, m_icon_bag), - Color(255, 255, 255), 2.4, - Color(236, 192, 124), 1.0 - ); - bag |= !bag && cluster_fit_2( - extract_box_reference(screen, m_icon_bag), - Color(0, 0, 0), 1.9, - Color(215, 120, 11), 1.0 - ); - if (!bag){ -// cout << "Failed: m_icon_bag" << endl; - return false; - } - -#ifdef DEBUG_StandardBattleMenuDetector - cout << "=============> Run Symbol" << endl; -#endif - bool run = false; - run |= !run && cluster_fit_2( - extract_box_reference(screen, m_icon_run), - Color(255, 255, 255), 2.3, - Color(216, 150, 230), 1.0 - ); - run |= !run && cluster_fit_2( - extract_box_reference(screen, m_icon_run), - Color(0, 0, 0), 1.9, - Color(179, 15, 195), 1.0 - ); - if (!run){ -// cout << "Failed: m_icon_run" << endl; - return false; - } -#endif - -// image.save("battle-menu.png"); - return true; -} - - -StandardBattleMenuWatcher::StandardBattleMenuWatcher(bool den, Color color) - : StandardBattleMenuDetector(den, color) - , VisualInferenceCallback("StandardBattleMenuWatcher") -{} -void StandardBattleMenuWatcher::make_overlays(VideoOverlaySet& items) const{ - return StandardBattleMenuDetector::make_overlays(items); -} -bool StandardBattleMenuWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // Need 5 consecutive successful detections. - if (!detect(frame)){ - m_trigger_count = 0; - return false; - } - m_trigger_count++; - return m_trigger_count >= 5; -} - - - - - -} -} -} +/* Battle Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/ColorClustering.h" +#include "PokemonSwSh_BattleMenuDetector.h" + +//#include +//using std::cout; +//using std::endl; + +//#define DEBUG_StandardBattleMenuDetector + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +StandardBattleMenuDetector::StandardBattleMenuDetector( + bool den, + Color color +) + : m_den(den) + , m_color(color) + , m_ball_left (0.912, 0.452, 0.02, 0.03) + , m_ball_right (0.970, 0.452, 0.02, 0.03) + , m_icon_fight (0.923, 0.576 + 0 * 0.1075, 0.05, 0.080) + , m_icon_pokemon(0.923, 0.576 + 1 * 0.1075, 0.05, 0.080) + , m_icon_bag (0.923, 0.576 + 2 * 0.1075, 0.05, 0.080) + , m_icon_run (0.923, 0.576 + 3 * 0.1075, 0.05, 0.080) + , m_text_fight (0.830, 0.576 + 0 * 0.1075, 0.08, 0.080) + , m_text_pokemon(0.830, 0.576 + 1 * 0.1075, 0.08, 0.080) + , m_text_bag (0.830, 0.576 + 2 * 0.1075, 0.08, 0.080) + , m_text_run (0.830, 0.576 + 3 * 0.1075, 0.08, 0.080) +// , m_status0 (0.280, 0.870, 0.015, 0.030) + , m_status1 (0.165, 0.945, 0.100, 0.015) +{} +void StandardBattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + if (!m_den){ + items.add(m_color, m_ball_left); + items.add(m_color, m_ball_right); + }else{ + items.add(m_color, m_status1); + } + items.add(m_color, m_icon_fight); + items.add(m_color, m_icon_pokemon); + items.add(m_color, m_icon_bag); + items.add(m_color, m_icon_run); + items.add(m_color, m_text_fight); + items.add(m_color, m_text_pokemon); + items.add(m_color, m_text_bag); + items.add(m_color, m_text_run); +} +bool StandardBattleMenuDetector::detect(const ImageViewRGB32& screen){ + if (!m_den){ + if (!is_white(extract_box_reference(screen, m_ball_left))){ + return false; + } + if (!is_white(extract_box_reference(screen, m_ball_right))){ + return false; + } + }else{ + ImageStats health = image_stats(extract_box_reference(screen, m_status1)); + if (!is_white(health)){ +// cout << "Failed: m_status1" << endl; +// extract_box_reference(screen, m_status1).save("test.png"); + return false; + } + } + + bool fight; + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Fight Text 0" << endl; +#endif + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_fight), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_fight), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + if (!fight){ +// cout << "Failed: m_text_fight" << endl; + return false; + } + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Pokemon Text" << endl; +#endif + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_pokemon), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_pokemon), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + if (!fight){ +// cout << "Failed: m_text_pokemon" << endl; + return false; + } + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Bag Text" << endl; +#endif + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_bag), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_bag), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + if (!fight){ +// cout << "Failed: m_text_bag" << endl; + return false; + } + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Run Text" << endl; +#endif + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_run), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_run), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + if (!fight){ +// cout << "Failed: m_text_run" << endl; + return false; + } + + +#if 1 +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Fight Symbol 0" << endl; +#endif + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_icon_fight), + Color(255, 255, 255), 1.7, + Color(153, 75, 112), 1.0 + ); +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Fight Symbol 1" << endl; +#endif + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_icon_fight), + Color(0, 0, 0), 1.4, + Color(185, 6, 40), 1.0 + ); + fight |= !fight && cluster_fit_2( // Max raid Fight button is a bit different. + extract_box_reference(screen, m_icon_fight), + Color(0, 0, 0), 1.7, + Color(182, 33, 82), 1.0 + ); + if (!fight){ +// cout << "Failed: m_icon_fight" << endl; + return false; + } + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Pokemon Symbol" << endl; +#endif + bool pokemon = false; + pokemon |= !pokemon && cluster_fit_2( + extract_box_reference(screen, m_icon_pokemon), + Color(255, 255, 255), 3.1, + Color(126, 224, 142), 1.0 + ); + pokemon |= !pokemon && cluster_fit_2( + extract_box_reference(screen, m_icon_pokemon), + Color(0, 0, 0), 2.7, + Color(8, 158, 18), 1.0 + ); + if (!pokemon){ +// cout << "Failed: m_icon_pokemon" << endl; + return false; + } + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Bag Symbol" << endl; +#endif + bool bag = false; + bag |= !bag && cluster_fit_2( + extract_box_reference(screen, m_icon_bag), + Color(255, 255, 255), 2.4, + Color(236, 192, 124), 1.0 + ); + bag |= !bag && cluster_fit_2( + extract_box_reference(screen, m_icon_bag), + Color(0, 0, 0), 1.9, + Color(215, 120, 11), 1.0 + ); + if (!bag){ +// cout << "Failed: m_icon_bag" << endl; + return false; + } + +#ifdef DEBUG_StandardBattleMenuDetector + cout << "=============> Run Symbol" << endl; +#endif + bool run = false; + run |= !run && cluster_fit_2( + extract_box_reference(screen, m_icon_run), + Color(255, 255, 255), 2.3, + Color(216, 150, 230), 1.0 + ); + run |= !run && cluster_fit_2( + extract_box_reference(screen, m_icon_run), + Color(0, 0, 0), 1.9, + Color(179, 15, 195), 1.0 + ); + if (!run){ +// cout << "Failed: m_icon_run" << endl; + return false; + } +#endif + +// image.save("battle-menu.png"); + return true; +} + + +StandardBattleMenuWatcher::StandardBattleMenuWatcher(bool den, Color color) + : StandardBattleMenuDetector(den, color) + , VisualInferenceCallback("StandardBattleMenuWatcher") +{} +void StandardBattleMenuWatcher::make_overlays(VideoOverlaySet& items) const{ + return StandardBattleMenuDetector::make_overlays(items); +} +bool StandardBattleMenuWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // Need 5 consecutive successful detections. + if (!detect(frame)){ + m_trigger_count = 0; + return false; + } + m_trigger_count++; + return m_trigger_count >= 5; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h index 4b2badbdc7..d6c6e77420 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h @@ -1,64 +1,64 @@ -/* Battle Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BattleMenuDetector_H -#define PokemonAutomation_PokemonSwSh_BattleMenuDetector_H - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class StandardBattleMenuDetector : public StaticScreenDetector{ -public: - StandardBattleMenuDetector(bool den, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - bool m_den; - - Color m_color; - ImageFloatBox m_ball_left; - ImageFloatBox m_ball_right; - ImageFloatBox m_icon_fight; - ImageFloatBox m_icon_pokemon; - ImageFloatBox m_icon_bag; - ImageFloatBox m_icon_run; - ImageFloatBox m_text_fight; - ImageFloatBox m_text_pokemon; - ImageFloatBox m_text_bag; - ImageFloatBox m_text_run; - -// ImageFloatBox m_status0; - ImageFloatBox m_status1; -}; - - -class StandardBattleMenuWatcher : public StandardBattleMenuDetector, public VisualInferenceCallback{ -public: - StandardBattleMenuWatcher(bool den, Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - using VisualInferenceCallback::process_frame; - -private: - size_t m_trigger_count = 0; -}; - - - -} -} -} -#endif +/* Battle Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BattleMenuDetector_H +#define PokemonAutomation_PokemonSwSh_BattleMenuDetector_H + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class StandardBattleMenuDetector : public StaticScreenDetector{ +public: + StandardBattleMenuDetector(bool den, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + bool m_den; + + Color m_color; + ImageFloatBox m_ball_left; + ImageFloatBox m_ball_right; + ImageFloatBox m_icon_fight; + ImageFloatBox m_icon_pokemon; + ImageFloatBox m_icon_bag; + ImageFloatBox m_icon_run; + ImageFloatBox m_text_fight; + ImageFloatBox m_text_pokemon; + ImageFloatBox m_text_bag; + ImageFloatBox m_text_run; + +// ImageFloatBox m_status0; + ImageFloatBox m_status1; +}; + + +class StandardBattleMenuWatcher : public StandardBattleMenuDetector, public VisualInferenceCallback{ +public: + StandardBattleMenuWatcher(bool den, Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + using VisualInferenceCallback::process_frame; + +private: + size_t m_trigger_count = 0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.cpp index f16eea9e63..51fc2bdba9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.cpp @@ -1,86 +1,86 @@ -/* Experience Gain Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_ExperienceGainDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ExperienceGainDetector::~ExperienceGainDetector(){} -ExperienceGainDetector::ExperienceGainDetector(Color color) - : m_color(color) - , m_dialog(color) - , m_rows(6) -{ - const double SHIFT_X = 0.0325; - const double SHIFT_Y = 0.126; - for (size_t c = 0; c < 6; c++){ - m_rows.emplace_back( - std::piecewise_construct, - std::forward_as_tuple(0.255 , 0.04 + c*SHIFT_Y, 0.18 - c*SHIFT_X, 0.08), - std::forward_as_tuple(0.475 - c*SHIFT_X, 0.04 + c*SHIFT_Y, 0.05 , 0.08) - ); - } -} - -void ExperienceGainDetector::make_overlays(VideoOverlaySet& items) const{ - m_dialog.make_overlays(items); - for (const auto& item : m_rows){ - items.add(m_color, item.first); - items.add(m_color, item.second); - } -} -bool ExperienceGainDetector::detect(const ImageViewRGB32& screen){ - if (!m_dialog.detect(screen)){ - return false; - } - - for (auto& row : m_rows){ - ImageStats stats0 = image_stats(extract_box_reference(screen, row.first)); -// cout << stats0.average << " " << stats0.stddev << endl; - if (!is_grey(stats0, 400, 1000)){ - return false; - } - ImageStats stats1 = image_stats(extract_box_reference(screen, row.second)); -// cout << stats1.average << " " << stats1.stddev << endl; - if (!is_white(stats1)){ - return false; - } - if (stats0.average.sum() > stats1.average.sum()){ - return false; - } - } - - return true; -} - - -ExperienceGainWatcher::ExperienceGainWatcher(Color color) - : ExperienceGainDetector(color) - , VisualInferenceCallback("ExperienceGainWatcher") -{} -void ExperienceGainWatcher::make_overlays(VideoOverlaySet& items) const{ - ExperienceGainDetector::make_overlays(items); -} -bool ExperienceGainWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - - - - -} -} -} +/* Experience Gain Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_ExperienceGainDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ExperienceGainDetector::~ExperienceGainDetector(){} +ExperienceGainDetector::ExperienceGainDetector(Color color) + : m_color(color) + , m_dialog(color) + , m_rows(6) +{ + const double SHIFT_X = 0.0325; + const double SHIFT_Y = 0.126; + for (size_t c = 0; c < 6; c++){ + m_rows.emplace_back( + std::piecewise_construct, + std::forward_as_tuple(0.255 , 0.04 + c*SHIFT_Y, 0.18 - c*SHIFT_X, 0.08), + std::forward_as_tuple(0.475 - c*SHIFT_X, 0.04 + c*SHIFT_Y, 0.05 , 0.08) + ); + } +} + +void ExperienceGainDetector::make_overlays(VideoOverlaySet& items) const{ + m_dialog.make_overlays(items); + for (const auto& item : m_rows){ + items.add(m_color, item.first); + items.add(m_color, item.second); + } +} +bool ExperienceGainDetector::detect(const ImageViewRGB32& screen){ + if (!m_dialog.detect(screen)){ + return false; + } + + for (auto& row : m_rows){ + ImageStats stats0 = image_stats(extract_box_reference(screen, row.first)); +// cout << stats0.average << " " << stats0.stddev << endl; + if (!is_grey(stats0, 400, 1000)){ + return false; + } + ImageStats stats1 = image_stats(extract_box_reference(screen, row.second)); +// cout << stats1.average << " " << stats1.stddev << endl; + if (!is_white(stats1)){ + return false; + } + if (stats0.average.sum() > stats1.average.sum()){ + return false; + } + } + + return true; +} + + +ExperienceGainWatcher::ExperienceGainWatcher(Color color) + : ExperienceGainDetector(color) + , VisualInferenceCallback("ExperienceGainWatcher") +{} +void ExperienceGainWatcher::make_overlays(VideoOverlaySet& items) const{ + ExperienceGainDetector::make_overlays(items); +} +bool ExperienceGainWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h index 7fcbca2f98..b1ebadb041 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h @@ -1,47 +1,47 @@ -/* Battle Won Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BattleWonDetector_H -#define PokemonAutomation_PokemonSwSh_BattleWonDetector_H - -#include "Common/Cpp/Containers/FixedLimitVector.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetector.h" -#include "PokemonSwSh_BattleDialogDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ExperienceGainDetector : public StaticScreenDetector{ -public: - ~ExperienceGainDetector(); - ExperienceGainDetector(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool detect(const ImageViewRGB32& screen) override; - -private: - Color m_color; - BattleDialogDetector m_dialog; - FixedLimitVector> m_rows; -}; - - -class ExperienceGainWatcher : public ExperienceGainDetector, public VisualInferenceCallback{ -public: - ExperienceGainWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; -}; - - -} -} -} -#endif +/* Battle Won Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BattleWonDetector_H +#define PokemonAutomation_PokemonSwSh_BattleWonDetector_H + +#include "Common/Cpp/Containers/FixedLimitVector.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetector.h" +#include "PokemonSwSh_BattleDialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ExperienceGainDetector : public StaticScreenDetector{ +public: + ~ExperienceGainDetector(); + ExperienceGainDetector(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool detect(const ImageViewRGB32& screen) override; + +private: + Color m_color; + BattleDialogDetector m_dialog; + FixedLimitVector> m_rows; +}; + + +class ExperienceGainWatcher : public ExperienceGainDetector, public VisualInferenceCallback{ +public: + ExperienceGainWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.cpp index fdc2df0762..58a70ce586 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.cpp @@ -1,53 +1,53 @@ -/* Start Battle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSwSh_StartBattleDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -StartBattleWatcher::StartBattleWatcher(Color color) - : VisualInferenceCallback("StartBattleWatcher") - , m_color(color) - , m_screen_box(0.2, 0.2, 0.6, 0.6) -{} -void StartBattleWatcher::make_overlays(VideoOverlaySet& items) const{ - items.add(m_color, m_screen_box); -} -bool StartBattleWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ImageViewRGB32 image = extract_box_reference(frame, m_screen_box); - ImageStats stats = image_stats(image); - - // White screen. - if (stats.average.sum() > 600 && stats.stddev.sum() < 10){ - return true; - } - - // Grey text box. - bool dialog = stats.stddev.sum() > 50; - dialog &= m_dialog.detect(frame); - if (dialog){ -// cout << stats0.stddev.sum() << endl; - } - return dialog; -} - - - -} -} -} +/* Start Battle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSwSh_StartBattleDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +StartBattleWatcher::StartBattleWatcher(Color color) + : VisualInferenceCallback("StartBattleWatcher") + , m_color(color) + , m_screen_box(0.2, 0.2, 0.6, 0.6) +{} +void StartBattleWatcher::make_overlays(VideoOverlaySet& items) const{ + items.add(m_color, m_screen_box); +} +bool StartBattleWatcher::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ImageViewRGB32 image = extract_box_reference(frame, m_screen_box); + ImageStats stats = image_stats(image); + + // White screen. + if (stats.average.sum() > 600 && stats.stddev.sum() < 10){ + return true; + } + + // Grey text box. + bool dialog = stats.stddev.sum() > 50; + dialog &= m_dialog.detect(frame); + if (dialog){ +// cout << stats0.stddev.sum() << endl; + } + return dialog; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h index ea115e96e6..a849c7ae2b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h @@ -1,42 +1,42 @@ -/* Start Battle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StartBattleDetector_H -#define PokemonAutomation_PokemonSwSh_StartBattleDetector_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class StartBattleWatcher : public VisualInferenceCallback{ -public: - StartBattleWatcher(Color color = COLOR_RED); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - Color m_color; - ImageFloatBox m_screen_box; - BattleDialogDetector m_dialog; -}; - - - - - - - -} -} -} -#endif - +/* Start Battle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StartBattleDetector_H +#define PokemonAutomation_PokemonSwSh_StartBattleDetector_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class StartBattleWatcher : public VisualInferenceCallback{ +public: + StartBattleWatcher(Color color = COLOR_RED); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + Color m_color; + ImageFloatBox m_screen_box; + BattleDialogDetector m_dialog; +}; + + + + + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.cpp index 17fe63be10..3c8bb7fd5c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.cpp @@ -1,197 +1,197 @@ -/* Beam Setter - * - * From: https://github.com/PokemonAutomation/ - * - * - * Drop a wishing piece and determine if it is red or purple. - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/Tools/StatAccumulator.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/InferenceThrottler.h" -#include "CommonTools/Images/ImageTools.h" -#include "CommonTools/TrendInference/TimeWindowStatTracker.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh_BeamSetter.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -BeamSetter::BeamSetter(ProgramEnvironment& /*env*/, VideoStream& stream, ProControllerContext& context) - // : m_env(env) - : m_stream(stream) - , m_context(context) - , m_text_box0(stream.overlay(), {0.400, 0.825, 0.05, 0.05}, COLOR_RED) - , m_text_box1(stream.overlay(), {0.250, 0.900, 0.05, 0.05}, COLOR_RED) - , m_box(stream.overlay(), {0.10, 0.005, 0.8, 0.470}, COLOR_RED) -{ - for (size_t c = 0; c < 32; c++){ - m_boxes.emplace_back(0.10 + 0.025*c, 0.005, 0.025, 0.470); - } -} - - - - -BeamSetter::Detection BeamSetter::run( - bool save_screenshot, - Milliseconds timeout, - double min_brightness, - double min_euclidean, - double min_delta_ratio, - double min_sigma_ratio -){ - // Grab baseline image. - VideoSnapshot baseline_image = m_stream.video().snapshot(); - if (!baseline_image){ - m_stream.log("BeamSetter(): Screenshot failed.", COLOR_PURPLE); - return Detection::NO_DETECTION; - } - - std::vector baseline_values(m_boxes.size()); - std::vector baseline_ratios(m_boxes.size()); - for (size_t c = 0; c < m_boxes.size(); c++){ - baseline_values[c] = image_average(extract_box_reference(baseline_image, m_boxes[c])); - baseline_ratios[c] = baseline_values[c] / baseline_values[c].sum(); - } - - // Drop the wishing piece. - pbf_press_button(m_context, BUTTON_A, 10, 10); - m_context.wait_for_all_requests(); - - bool low_stddev_flag = false; - - std::vector> trackers; - for (size_t c = 0; c < m_boxes.size(); c++){ - trackers.emplace_back(std::chrono::milliseconds(1000)); - } - - InferenceThrottler throttler(timeout, std::chrono::milliseconds(50)); - - VideoSnapshot last_screenshot = baseline_image; - do{ - // Take screenshot. - VideoSnapshot current_screenshot = m_stream.video().snapshot(); - if (!current_screenshot){ - m_stream.log("BeamSetter(): Screenshot failed.", COLOR_PURPLE); - return Detection::NO_DETECTION; - } - - // Text detection. - double text_stddev = image_stddev(extract_box_reference(current_screenshot, m_text_box0)).sum(); - text_stddev = std::max(text_stddev, image_stddev(extract_box_reference(current_screenshot, m_text_box1)).sum()); - if (text_stddev < 10){ - low_stddev_flag = true; - } - - ImageRGB32 baseline_diff = image_diff_greyscale(baseline_image, current_screenshot); - auto now = current_time(); - - bool purple = false; - size_t best_index = 0; - double best_euclidean = 0; - double best_stddev = 0; - double best_brightness = 0; - double best_delta = 0; - double best_sigma = 0; - for (size_t c = 0; c < m_boxes.size(); c++){ - FloatStatAccumulator stats = trackers[c].accumulate_all(); - - ImageViewRGB32 previous_box = extract_box_reference(last_screenshot, m_boxes[c]); - ImageViewRGB32 current_box = extract_box_reference(current_screenshot, m_boxes[c]); - - FloatPixel current_average = image_average(current_box); - double delta = ImageMatch::pixel_RMSD(current_box, previous_box); - - double sigma = 0; - if (stats.count() >= 5){ - sigma = stats.diff_metric(delta); - } - - double stddev = current_average.stddev(); - double brightness = current_average.sum(); - double average_euclidean_diff = image_average(extract_box_reference(baseline_diff, m_boxes[c])).r; - - if (best_sigma <= sigma){ - best_index = c; - best_euclidean = average_euclidean_diff; - best_stddev = stddev; - best_brightness = brightness; -// max_diff_delta = delta; - best_delta = delta; - best_sigma = sigma; - } - - bool required = true; - required &= brightness >= min_brightness; - required &= average_euclidean_diff >= min_euclidean; - - required &= delta / stddev >= min_delta_ratio; - required &= sigma / stddev >= min_sigma_ratio; - - if (required){ - purple = true; - }else{ - trackers[c].push(delta, now); - } - - if (best_sigma <= sigma && required == purple){ - best_index = c; - best_euclidean = average_euclidean_diff; - best_stddev = stddev; - best_brightness = brightness; -// max_diff_delta = delta; - best_delta = delta; - best_sigma = sigma; - } - } - - std::string str = "BeamReader: column = " + std::to_string(best_index); - - str += ", stddev = " + tostr_default(best_stddev); - str += ", brightness = " + tostr_default(best_brightness); - str += ", euclidean = " + tostr_default(best_euclidean); - str += ", delta = " + tostr_default(best_delta); - str += ", sigma = " + tostr_default(best_sigma); - - if (purple){ - m_stream.log(str, COLOR_BLUE); - m_stream.log("BeamReader(): Purple beam found!", COLOR_BLUE); - if (save_screenshot){ - current_screenshot->save("PurpleBeam-" + now_to_filestring() + ".png"); - } - return Detection::PURPLE; - }else{ - m_stream.log(str, COLOR_PURPLE); - } - - if (low_stddev_flag && text_stddev > 100){ - m_stream.log("BeamReader(): No beam detected with text. Resetting.", COLOR_BLUE); - return Detection::RED_ASSUMED; - } - - last_screenshot = std::move(current_screenshot); - }while (!throttler.end_iteration(m_context)); - - return Detection::NO_DETECTION; -} - - - - -} -} -} - - +/* Beam Setter + * + * From: https://github.com/PokemonAutomation/ + * + * + * Drop a wishing piece and determine if it is red or purple. + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/Tools/StatAccumulator.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/InferenceThrottler.h" +#include "CommonTools/Images/ImageTools.h" +#include "CommonTools/TrendInference/TimeWindowStatTracker.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh_BeamSetter.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +BeamSetter::BeamSetter(ProgramEnvironment& /*env*/, VideoStream& stream, ProControllerContext& context) + // : m_env(env) + : m_stream(stream) + , m_context(context) + , m_text_box0(stream.overlay(), {0.400, 0.825, 0.05, 0.05}, COLOR_RED) + , m_text_box1(stream.overlay(), {0.250, 0.900, 0.05, 0.05}, COLOR_RED) + , m_box(stream.overlay(), {0.10, 0.005, 0.8, 0.470}, COLOR_RED) +{ + for (size_t c = 0; c < 32; c++){ + m_boxes.emplace_back(0.10 + 0.025*c, 0.005, 0.025, 0.470); + } +} + + + + +BeamSetter::Detection BeamSetter::run( + bool save_screenshot, + Milliseconds timeout, + double min_brightness, + double min_euclidean, + double min_delta_ratio, + double min_sigma_ratio +){ + // Grab baseline image. + VideoSnapshot baseline_image = m_stream.video().snapshot(); + if (!baseline_image){ + m_stream.log("BeamSetter(): Screenshot failed.", COLOR_PURPLE); + return Detection::NO_DETECTION; + } + + std::vector baseline_values(m_boxes.size()); + std::vector baseline_ratios(m_boxes.size()); + for (size_t c = 0; c < m_boxes.size(); c++){ + baseline_values[c] = image_average(extract_box_reference(baseline_image, m_boxes[c])); + baseline_ratios[c] = baseline_values[c] / baseline_values[c].sum(); + } + + // Drop the wishing piece. + pbf_press_button(m_context, BUTTON_A, 10, 10); + m_context.wait_for_all_requests(); + + bool low_stddev_flag = false; + + std::vector> trackers; + for (size_t c = 0; c < m_boxes.size(); c++){ + trackers.emplace_back(std::chrono::milliseconds(1000)); + } + + InferenceThrottler throttler(timeout, std::chrono::milliseconds(50)); + + VideoSnapshot last_screenshot = baseline_image; + do{ + // Take screenshot. + VideoSnapshot current_screenshot = m_stream.video().snapshot(); + if (!current_screenshot){ + m_stream.log("BeamSetter(): Screenshot failed.", COLOR_PURPLE); + return Detection::NO_DETECTION; + } + + // Text detection. + double text_stddev = image_stddev(extract_box_reference(current_screenshot, m_text_box0)).sum(); + text_stddev = std::max(text_stddev, image_stddev(extract_box_reference(current_screenshot, m_text_box1)).sum()); + if (text_stddev < 10){ + low_stddev_flag = true; + } + + ImageRGB32 baseline_diff = image_diff_greyscale(baseline_image, current_screenshot); + auto now = current_time(); + + bool purple = false; + size_t best_index = 0; + double best_euclidean = 0; + double best_stddev = 0; + double best_brightness = 0; + double best_delta = 0; + double best_sigma = 0; + for (size_t c = 0; c < m_boxes.size(); c++){ + FloatStatAccumulator stats = trackers[c].accumulate_all(); + + ImageViewRGB32 previous_box = extract_box_reference(last_screenshot, m_boxes[c]); + ImageViewRGB32 current_box = extract_box_reference(current_screenshot, m_boxes[c]); + + FloatPixel current_average = image_average(current_box); + double delta = ImageMatch::pixel_RMSD(current_box, previous_box); + + double sigma = 0; + if (stats.count() >= 5){ + sigma = stats.diff_metric(delta); + } + + double stddev = current_average.stddev(); + double brightness = current_average.sum(); + double average_euclidean_diff = image_average(extract_box_reference(baseline_diff, m_boxes[c])).r; + + if (best_sigma <= sigma){ + best_index = c; + best_euclidean = average_euclidean_diff; + best_stddev = stddev; + best_brightness = brightness; +// max_diff_delta = delta; + best_delta = delta; + best_sigma = sigma; + } + + bool required = true; + required &= brightness >= min_brightness; + required &= average_euclidean_diff >= min_euclidean; + + required &= delta / stddev >= min_delta_ratio; + required &= sigma / stddev >= min_sigma_ratio; + + if (required){ + purple = true; + }else{ + trackers[c].push(delta, now); + } + + if (best_sigma <= sigma && required == purple){ + best_index = c; + best_euclidean = average_euclidean_diff; + best_stddev = stddev; + best_brightness = brightness; +// max_diff_delta = delta; + best_delta = delta; + best_sigma = sigma; + } + } + + std::string str = "BeamReader: column = " + std::to_string(best_index); + + str += ", stddev = " + tostr_default(best_stddev); + str += ", brightness = " + tostr_default(best_brightness); + str += ", euclidean = " + tostr_default(best_euclidean); + str += ", delta = " + tostr_default(best_delta); + str += ", sigma = " + tostr_default(best_sigma); + + if (purple){ + m_stream.log(str, COLOR_BLUE); + m_stream.log("BeamReader(): Purple beam found!", COLOR_BLUE); + if (save_screenshot){ + current_screenshot->save("PurpleBeam-" + now_to_filestring() + ".png"); + } + return Detection::PURPLE; + }else{ + m_stream.log(str, COLOR_PURPLE); + } + + if (low_stddev_flag && text_stddev > 100){ + m_stream.log("BeamReader(): No beam detected with text. Resetting.", COLOR_BLUE); + return Detection::RED_ASSUMED; + } + + last_screenshot = std::move(current_screenshot); + }while (!throttler.end_iteration(m_context)); + + return Detection::NO_DETECTION; +} + + + + +} +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h index 8fedf634a0..9ff71f3257 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h @@ -1,64 +1,64 @@ -/* Beam Setter - * - * From: https://github.com/PokemonAutomation/ - * - * - * Drop a wishing piece and determine if it is red or purple. - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BeamSetter_H -#define PokemonAutomation_PokemonSwSh_BeamSetter_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BeamSetter{ -public: - enum Detection{ - NO_DETECTION, - RED_DETECTED, - RED_ASSUMED, - PURPLE, - }; - -public: - BeamSetter( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context - ); - - Detection run( - bool save_screenshot, - Milliseconds timeout, - double min_brightness, - double min_euclidean, - double min_delta_ratio, - double min_sigma_ratio - ); - - -private: - VideoStream& m_stream; - ProControllerContext& m_context; - OverlayBoxScope m_text_box0; - OverlayBoxScope m_text_box1; - OverlayBoxScope m_box; - std::vector m_boxes; -}; - - - - -} -} -} -#endif +/* Beam Setter + * + * From: https://github.com/PokemonAutomation/ + * + * + * Drop a wishing piece and determine if it is red or purple. + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BeamSetter_H +#define PokemonAutomation_PokemonSwSh_BeamSetter_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BeamSetter{ +public: + enum Detection{ + NO_DETECTION, + RED_DETECTED, + RED_ASSUMED, + PURPLE, + }; + +public: + BeamSetter( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context + ); + + Detection run( + bool save_screenshot, + Milliseconds timeout, + double min_brightness, + double min_euclidean, + double min_delta_ratio, + double min_sigma_ratio + ); + + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + OverlayBoxScope m_text_box0; + OverlayBoxScope m_text_box1; + OverlayBoxScope m_box; + std::vector m_boxes; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.cpp index 47d1aa4d96..4f10b2cf45 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.cpp @@ -1,130 +1,130 @@ -/* Den Sprite Identifier - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "CommonTools/ImageMatch/FilterToAlpha.h" -#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "PokemonSwSh_DenMonReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ImageMatch::SilhouetteDictionaryMatcher make_DEN_SPRITE_MATCHER(){ - ImageMatch::SilhouetteDictionaryMatcher matcher; - for (const auto& item : ALL_POKEMON_SILHOUETTES()){ - matcher.add(item.first, item.second.sprite); - } - return matcher; -} -const ImageMatch::SilhouetteDictionaryMatcher& DEN_SPRITE_MATCHER(){ - static ImageMatch::SilhouetteDictionaryMatcher matcher = make_DEN_SPRITE_MATCHER(); - return matcher; -} - - - - -DenMonReader::DenMonReader(Logger& logger, VideoOverlay& overlay) - : m_matcher(DEN_SPRITE_MATCHER()) - , m_logger(logger) - , m_white(overlay, {0.800, 0.200, 0.150, 0.100}) - , m_den_color(overlay, {0.400, 0.050, 0.200, 0.100}) - , m_lair_pink(overlay, {0.575, 0.035, 0.050, 0.100}) - , m_sprite(overlay, {0.098, 0.23, 0.285, 0.41}) -{} - - -DenMonReadResults DenMonReader::read(const ImageViewRGB32& screen) const{ - DenMonReadResults results; - if (!screen){ - return results; - } - - ImageStats white = image_stats(extract_box_reference(screen, m_white)); - if (!is_solid(white, {0.303079, 0.356564, 0.340357})){ - return results; - } - do{ - ImageStats den_color = image_stats(extract_box_reference(screen, m_den_color)); - - if (is_solid(den_color, {0.593023, 0.204651, 0.202326})){ - results.type = DenMonReadResults::RED_BEAM; - m_logger.log("Den Type: Red Beam", COLOR_BLUE); - break; - } - if (is_solid(den_color, {0.580866, 0.378132, 0.0410021})){ - results.type = DenMonReadResults::PURPLE_BEAM; - m_logger.log("Den Type: Purple Beam", COLOR_BLUE); - break; - } - - ImageStats lair_pink = image_stats(extract_box_reference(screen, m_lair_pink)); -// cout << lair_pink.average << lair_pink.stddev << endl; - - if (is_solid(lair_pink, {0.448155, 0.177504, 0.374341})){ - results.type = DenMonReadResults::MAX_LAIR; - m_logger.log("Den Type: Max Lair", COLOR_BLUE); - break; - } - - return results; - }while (false); - - - ImageViewRGB32 cropped = extract_box_reference(screen, m_sprite); -// cropped.save("processed.png"); -// cropped = ImageMatch::black_filter_to_alpha(cropped); - - // Find the bounding box of the silhouette. - const ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( - cropped, - // The filter is a lambda function that returns true on silhouette pixels. - // We treat dark pixels as silhouette pixels. - [](Color pixel){ - return (uint32_t)pixel.red() + pixel.green() + pixel.blue() < 100; - } - ); - ImageRGB32 processed = extract_box_reference(cropped, box).copy(); - // Set black pixels to have 255 alpha while other pixels 0 alpha. - ImageMatch::set_alpha_black(processed); - - results.slugs = m_matcher.match(processed, ALPHA_SPREAD); - results.slugs.log(m_logger, MAX_ALPHA); - - results.slugs.clear_beyond_alpha(MAX_ALPHA); - - return results; -} - - - -DenMonSelectData::DenMonSelectData(){ - m_database.add_entry(StringSelectEntry("", "(none)")); - for (const auto& item : ALL_POKEMON_SPRITES()){ - m_database.add_entry(StringSelectEntry(item.first, item.first, item.second.icon)); - } -} -DenMonSelectOption::DenMonSelectOption(std::string label) - : StringSelectOption( - std::move(label), - DenMonSelectData::m_database, - LockMode::LOCK_WHILE_RUNNING, - "" - ) -{} - - -} -} -} +/* Den Sprite Identifier + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "CommonTools/ImageMatch/FilterToAlpha.h" +#include "CommonTools/ImageMatch/SilhouetteDictionaryMatcher.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "PokemonSwSh_DenMonReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ImageMatch::SilhouetteDictionaryMatcher make_DEN_SPRITE_MATCHER(){ + ImageMatch::SilhouetteDictionaryMatcher matcher; + for (const auto& item : ALL_POKEMON_SILHOUETTES()){ + matcher.add(item.first, item.second.sprite); + } + return matcher; +} +const ImageMatch::SilhouetteDictionaryMatcher& DEN_SPRITE_MATCHER(){ + static ImageMatch::SilhouetteDictionaryMatcher matcher = make_DEN_SPRITE_MATCHER(); + return matcher; +} + + + + +DenMonReader::DenMonReader(Logger& logger, VideoOverlay& overlay) + : m_matcher(DEN_SPRITE_MATCHER()) + , m_logger(logger) + , m_white(overlay, {0.800, 0.200, 0.150, 0.100}) + , m_den_color(overlay, {0.400, 0.050, 0.200, 0.100}) + , m_lair_pink(overlay, {0.575, 0.035, 0.050, 0.100}) + , m_sprite(overlay, {0.098, 0.23, 0.285, 0.41}) +{} + + +DenMonReadResults DenMonReader::read(const ImageViewRGB32& screen) const{ + DenMonReadResults results; + if (!screen){ + return results; + } + + ImageStats white = image_stats(extract_box_reference(screen, m_white)); + if (!is_solid(white, {0.303079, 0.356564, 0.340357})){ + return results; + } + do{ + ImageStats den_color = image_stats(extract_box_reference(screen, m_den_color)); + + if (is_solid(den_color, {0.593023, 0.204651, 0.202326})){ + results.type = DenMonReadResults::RED_BEAM; + m_logger.log("Den Type: Red Beam", COLOR_BLUE); + break; + } + if (is_solid(den_color, {0.580866, 0.378132, 0.0410021})){ + results.type = DenMonReadResults::PURPLE_BEAM; + m_logger.log("Den Type: Purple Beam", COLOR_BLUE); + break; + } + + ImageStats lair_pink = image_stats(extract_box_reference(screen, m_lair_pink)); +// cout << lair_pink.average << lair_pink.stddev << endl; + + if (is_solid(lair_pink, {0.448155, 0.177504, 0.374341})){ + results.type = DenMonReadResults::MAX_LAIR; + m_logger.log("Den Type: Max Lair", COLOR_BLUE); + break; + } + + return results; + }while (false); + + + ImageViewRGB32 cropped = extract_box_reference(screen, m_sprite); +// cropped.save("processed.png"); +// cropped = ImageMatch::black_filter_to_alpha(cropped); + + // Find the bounding box of the silhouette. + const ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + cropped, + // The filter is a lambda function that returns true on silhouette pixels. + // We treat dark pixels as silhouette pixels. + [](Color pixel){ + return (uint32_t)pixel.red() + pixel.green() + pixel.blue() < 100; + } + ); + ImageRGB32 processed = extract_box_reference(cropped, box).copy(); + // Set black pixels to have 255 alpha while other pixels 0 alpha. + ImageMatch::set_alpha_black(processed); + + results.slugs = m_matcher.match(processed, ALPHA_SPREAD); + results.slugs.log(m_logger, MAX_ALPHA); + + results.slugs.clear_beyond_alpha(MAX_ALPHA); + + return results; +} + + + +DenMonSelectData::DenMonSelectData(){ + m_database.add_entry(StringSelectEntry("", "(none)")); + for (const auto& item : ALL_POKEMON_SPRITES()){ + m_database.add_entry(StringSelectEntry(item.first, item.first, item.second.icon)); + } +} +DenMonSelectOption::DenMonSelectOption(std::string label) + : StringSelectOption( + std::move(label), + DenMonSelectData::m_database, + LockMode::LOCK_WHILE_RUNNING, + "" + ) +{} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h index 7a12c46831..b254de856f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h @@ -1,76 +1,76 @@ -/* Den Mon Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DenMonReader_H -#define PokemonAutomation_PokemonSwSh_DenMonReader_H - -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Options/StringSelectOption.h" -#include "CommonTools/ImageMatch/ImageMatchResult.h" - -namespace PokemonAutomation{ - namespace ImageMatch{ - class SilhouetteDictionaryMatcher; - }; - class Logger; - class VideoOverlay; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -struct DenMonReadResults{ - enum DenType{ - NOT_DETECTED, - RED_BEAM, - PURPLE_BEAM, - MAX_LAIR, - }; - - // TODO: Star count. - // TODO: Types - DenType type = NOT_DETECTED; - ImageMatch::ImageMatchResult slugs; - -}; - -class DenMonReader{ - static constexpr double MAX_ALPHA = 100; - static constexpr double ALPHA_SPREAD = 20; - -public: - DenMonReader(Logger& logger, VideoOverlay& overlay); - - DenMonReadResults read(const ImageViewRGB32& screen) const; - -private: - const ImageMatch::SilhouetteDictionaryMatcher& m_matcher; - Logger& m_logger; - OverlayBoxScope m_white; - OverlayBoxScope m_den_color; - OverlayBoxScope m_lair_pink; - OverlayBoxScope m_sprite; -}; - - - - -struct DenMonSelectData{ - DenMonSelectData(); - StringSelectDatabase m_database; -}; - -class DenMonSelectOption : private DenMonSelectData, public StringSelectOption{ -public: - DenMonSelectOption(std::string label); -}; - - - -} -} -} -#endif +/* Den Mon Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DenMonReader_H +#define PokemonAutomation_PokemonSwSh_DenMonReader_H + +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Options/StringSelectOption.h" +#include "CommonTools/ImageMatch/ImageMatchResult.h" + +namespace PokemonAutomation{ + namespace ImageMatch{ + class SilhouetteDictionaryMatcher; + }; + class Logger; + class VideoOverlay; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +struct DenMonReadResults{ + enum DenType{ + NOT_DETECTED, + RED_BEAM, + PURPLE_BEAM, + MAX_LAIR, + }; + + // TODO: Star count. + // TODO: Types + DenType type = NOT_DETECTED; + ImageMatch::ImageMatchResult slugs; + +}; + +class DenMonReader{ + static constexpr double MAX_ALPHA = 100; + static constexpr double ALPHA_SPREAD = 20; + +public: + DenMonReader(Logger& logger, VideoOverlay& overlay); + + DenMonReadResults read(const ImageViewRGB32& screen) const; + +private: + const ImageMatch::SilhouetteDictionaryMatcher& m_matcher; + Logger& m_logger; + OverlayBoxScope m_white; + OverlayBoxScope m_den_color; + OverlayBoxScope m_lair_pink; + OverlayBoxScope m_sprite; +}; + + + + +struct DenMonSelectData{ + DenMonSelectData(); + StringSelectDatabase m_database; +}; + +class DenMonSelectOption : private DenMonSelectData, public StringSelectOption{ +public: + DenMonSelectOption(std::string label); +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.cpp index 8ddfafe782..543643843a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.cpp @@ -1,97 +1,97 @@ -/* Raid Catch Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/ColorClustering.h" -#include "PokemonSwSh_RaidCatchDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -RaidCatchDetector::RaidCatchDetector(VideoOverlay& overlay) - : VisualInferenceCallback("RaidCatchDetector") - , m_left0 (0.82, 0.85 + 0 * 0.078, 0.01, 0.04) - , m_right0(0.96, 0.85 + 0 * 0.078, 0.01, 0.04) -// , m_left1 (0.82, 0.85 + 1 * 0.078, 0.01, 0.04) -// , m_right1(0.96, 0.85 + 1 * 0.078, 0.01, 0.04) - , m_text0 (0.82, 0.84 + 0 * 0.078, 0.15, 0.06) - , m_text1 (0.82, 0.84 + 1 * 0.078, 0.15, 0.06) - , m_arrow(overlay, ImageFloatBox(0.75, 0.82, 0.10, 0.10)) -{} -void RaidCatchDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_left0); - items.add(COLOR_RED, m_right0); -// items.add(COLOR_RED, m_left1); -// items.add(COLOR_RED, m_right1); - items.add(COLOR_RED, m_text0); - items.add(COLOR_RED, m_text1); - m_arrow.make_overlays(items); -} -bool RaidCatchDetector::detect(const ImageViewRGB32& screen){ - ImageStats left0 = image_stats(extract_box_reference(screen, m_left0)); - if (!is_black(left0)){ - return false; - } - ImageStats right0 = image_stats(extract_box_reference(screen, m_right0)); - if (!is_black(right0)){ - return false; - } - if (euclidean_distance(left0.average, right0.average) > 10) return false; -#if 0 - ImageStats left1 = image_stats(extract_box_reference(screen, m_left1)); - if (!is_white(left1)){ - return false; - } - ImageStats right1 = image_stats(extract_box_reference(screen, m_right1)); - if (!is_white(right1)){ - return false; - } - if (euclidean_distance(left1.average, right1.average) > 10) return false; -#endif - -// cout << "==================" << endl; - if (!cluster_fit_2( - extract_box_reference(screen, m_text0), - Color(0, 0, 0), 0.90, - Color(255, 255, 255), 0.10 - )){ - return false; - } -// cout << "------------------" << endl; - if (!cluster_fit_2( - extract_box_reference(screen, m_text1), - Color(255, 255, 255), 0.90, - Color(0, 0, 0), 0.10 - )){ - return false; - } - - if (!m_arrow.detect(screen)){ - return false; - } - - return true; -} -bool RaidCatchDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // Need 5 consecutive successful detections. - if (!detect(frame)){ - m_trigger_count = 0; - return false; - } - m_trigger_count++; - return m_trigger_count >= 5; -} - - - - -} -} -} - +/* Raid Catch Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/ColorClustering.h" +#include "PokemonSwSh_RaidCatchDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +RaidCatchDetector::RaidCatchDetector(VideoOverlay& overlay) + : VisualInferenceCallback("RaidCatchDetector") + , m_left0 (0.82, 0.85 + 0 * 0.078, 0.01, 0.04) + , m_right0(0.96, 0.85 + 0 * 0.078, 0.01, 0.04) +// , m_left1 (0.82, 0.85 + 1 * 0.078, 0.01, 0.04) +// , m_right1(0.96, 0.85 + 1 * 0.078, 0.01, 0.04) + , m_text0 (0.82, 0.84 + 0 * 0.078, 0.15, 0.06) + , m_text1 (0.82, 0.84 + 1 * 0.078, 0.15, 0.06) + , m_arrow(overlay, ImageFloatBox(0.75, 0.82, 0.10, 0.10)) +{} +void RaidCatchDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_left0); + items.add(COLOR_RED, m_right0); +// items.add(COLOR_RED, m_left1); +// items.add(COLOR_RED, m_right1); + items.add(COLOR_RED, m_text0); + items.add(COLOR_RED, m_text1); + m_arrow.make_overlays(items); +} +bool RaidCatchDetector::detect(const ImageViewRGB32& screen){ + ImageStats left0 = image_stats(extract_box_reference(screen, m_left0)); + if (!is_black(left0)){ + return false; + } + ImageStats right0 = image_stats(extract_box_reference(screen, m_right0)); + if (!is_black(right0)){ + return false; + } + if (euclidean_distance(left0.average, right0.average) > 10) return false; +#if 0 + ImageStats left1 = image_stats(extract_box_reference(screen, m_left1)); + if (!is_white(left1)){ + return false; + } + ImageStats right1 = image_stats(extract_box_reference(screen, m_right1)); + if (!is_white(right1)){ + return false; + } + if (euclidean_distance(left1.average, right1.average) > 10) return false; +#endif + +// cout << "==================" << endl; + if (!cluster_fit_2( + extract_box_reference(screen, m_text0), + Color(0, 0, 0), 0.90, + Color(255, 255, 255), 0.10 + )){ + return false; + } +// cout << "------------------" << endl; + if (!cluster_fit_2( + extract_box_reference(screen, m_text1), + Color(255, 255, 255), 0.90, + Color(0, 0, 0), 0.10 + )){ + return false; + } + + if (!m_arrow.detect(screen)){ + return false; + } + + return true; +} +bool RaidCatchDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // Need 5 consecutive successful detections. + if (!detect(frame)){ + m_trigger_count = 0; + return false; + } + m_trigger_count++; + return m_trigger_count >= 5; +} + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h index 25114161eb..3f0951f742 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h @@ -1,46 +1,46 @@ -/* Raid Catch Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_RaidCatchDetector_H -#define PokemonAutomation_PokemonSwSh_RaidCatchDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class RaidCatchDetector : public VisualInferenceCallback{ -public: - RaidCatchDetector(VideoOverlay& overlay); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - ImageFloatBox m_left0; - ImageFloatBox m_right0; -// ImageFloatBox m_left1; -// ImageFloatBox m_right1; - ImageFloatBox m_text0; - ImageFloatBox m_text1; - SelectionArrowFinder m_arrow; - - size_t m_trigger_count = 0; -}; - - -} -} -} -#endif - +/* Raid Catch Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_RaidCatchDetector_H +#define PokemonAutomation_PokemonSwSh_RaidCatchDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class RaidCatchDetector : public VisualInferenceCallback{ +public: + RaidCatchDetector(VideoOverlay& overlay); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + ImageFloatBox m_left0; + ImageFloatBox m_right0; +// ImageFloatBox m_left1; +// ImageFloatBox m_right1; + ImageFloatBox m_text0; + ImageFloatBox m_text1; + SelectionArrowFinder m_arrow; + + size_t m_trigger_count = 0; +}; + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.cpp index 632029452b..d5dc027173 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.cpp @@ -1,101 +1,101 @@ -/* Raid Lobby Reader - * - * From: https://github.com/PokemonAutomation/ - * - * - * Determine if a raid is full and ready to start early. - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "PokemonSwSh_RaidLobbyReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -RaidLobbyReader::RaidLobbyReader(Logger& logger, VideoOverlay& overlay) - : m_logger(logger) - , m_checkbox0(overlay, {0.593, 0.337 + 0.0775*0, 0.034, 0.06}) - , m_checkbox1(overlay, {0.593, 0.337 + 0.0775*1, 0.034, 0.06}) - , m_checkbox2(overlay, {0.593, 0.337 + 0.0775*2, 0.034, 0.06}) - , m_checkbox3(overlay, {0.593, 0.337 + 0.0775*3, 0.034, 0.06}) - , m_spritebox0(overlay, {0.820, 0.337 + 0.0775*0, 0.034, 0.06}) - , m_spritebox1(overlay, {0.820, 0.337 + 0.0775*1, 0.034, 0.06}) - , m_spritebox2(overlay, {0.820, 0.337 + 0.0775*2, 0.034, 0.06}) - , m_spritebox3(overlay, {0.820, 0.337 + 0.0775*3, 0.034, 0.06}) -{} - -RaidLobbyState RaidLobbyReader::read(const ImageViewRGB32& screen){ - if (!screen){ - m_logger.log("RaidLobbyReader(): Screenshot failed.", COLOR_PURPLE); - return RaidLobbyState(); - } - - std::string str; - - FloatPixel average0 = image_average(extract_box_reference(screen, m_checkbox0)); - FloatPixel average1 = image_average(extract_box_reference(screen, m_checkbox1)); - FloatPixel average2 = image_average(extract_box_reference(screen, m_checkbox2)); - FloatPixel average3 = image_average(extract_box_reference(screen, m_checkbox3)); - double distance1 = euclidean_distance(average0, average1); - double distance2 = euclidean_distance(average0, average2); - double distance3 = euclidean_distance(average0, average3); - str += "Ready = {"; - str += tostr_default(0) + ", "; - str += tostr_default(distance1) + ", "; - str += tostr_default(distance2) + ", "; - str += tostr_default(distance3) + "}"; - - double stddev0 = image_stddev(extract_box_reference(screen, m_spritebox0)).sum(); - double stddev1 = image_stddev(extract_box_reference(screen, m_spritebox1)).sum(); - double stddev2 = image_stddev(extract_box_reference(screen, m_spritebox2)).sum(); - double stddev3 = image_stddev(extract_box_reference(screen, m_spritebox3)).sum(); - str += ", Sprites = {"; - str += tostr_default(stddev0) + ", "; - str += tostr_default(stddev1) + ", "; - str += tostr_default(stddev2) + ", "; - str += tostr_default(stddev3) + "}"; - - m_logger.log("RaidLobbyReader(): " + str, COLOR_PURPLE); - - const double PLAYER_READY = 100; - const double PLAYER_EXISTS = 20; - - RaidLobbyState state; - state.valid = true; - state.player0 = stddev0 < PLAYER_EXISTS - ? RaidLobbySlot::EMPTY - : RaidLobbySlot::NOT_READY; - state.player1 = stddev1 < PLAYER_EXISTS - ? RaidLobbySlot::EMPTY - : distance1 > PLAYER_READY - ? RaidLobbySlot::READY - : RaidLobbySlot::NOT_READY; - state.player2 = stddev2 < PLAYER_EXISTS - ? RaidLobbySlot::EMPTY - : distance2 > PLAYER_READY - ? RaidLobbySlot::READY - : RaidLobbySlot::NOT_READY; - state.player3 = stddev3 < PLAYER_EXISTS - ? RaidLobbySlot::EMPTY - : distance3 > PLAYER_READY - ? RaidLobbySlot::READY - : RaidLobbySlot::NOT_READY; - return state; -} - - -} -} -} - - +/* Raid Lobby Reader + * + * From: https://github.com/PokemonAutomation/ + * + * + * Determine if a raid is full and ready to start early. + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "PokemonSwSh_RaidLobbyReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +RaidLobbyReader::RaidLobbyReader(Logger& logger, VideoOverlay& overlay) + : m_logger(logger) + , m_checkbox0(overlay, {0.593, 0.337 + 0.0775*0, 0.034, 0.06}) + , m_checkbox1(overlay, {0.593, 0.337 + 0.0775*1, 0.034, 0.06}) + , m_checkbox2(overlay, {0.593, 0.337 + 0.0775*2, 0.034, 0.06}) + , m_checkbox3(overlay, {0.593, 0.337 + 0.0775*3, 0.034, 0.06}) + , m_spritebox0(overlay, {0.820, 0.337 + 0.0775*0, 0.034, 0.06}) + , m_spritebox1(overlay, {0.820, 0.337 + 0.0775*1, 0.034, 0.06}) + , m_spritebox2(overlay, {0.820, 0.337 + 0.0775*2, 0.034, 0.06}) + , m_spritebox3(overlay, {0.820, 0.337 + 0.0775*3, 0.034, 0.06}) +{} + +RaidLobbyState RaidLobbyReader::read(const ImageViewRGB32& screen){ + if (!screen){ + m_logger.log("RaidLobbyReader(): Screenshot failed.", COLOR_PURPLE); + return RaidLobbyState(); + } + + std::string str; + + FloatPixel average0 = image_average(extract_box_reference(screen, m_checkbox0)); + FloatPixel average1 = image_average(extract_box_reference(screen, m_checkbox1)); + FloatPixel average2 = image_average(extract_box_reference(screen, m_checkbox2)); + FloatPixel average3 = image_average(extract_box_reference(screen, m_checkbox3)); + double distance1 = euclidean_distance(average0, average1); + double distance2 = euclidean_distance(average0, average2); + double distance3 = euclidean_distance(average0, average3); + str += "Ready = {"; + str += tostr_default(0) + ", "; + str += tostr_default(distance1) + ", "; + str += tostr_default(distance2) + ", "; + str += tostr_default(distance3) + "}"; + + double stddev0 = image_stddev(extract_box_reference(screen, m_spritebox0)).sum(); + double stddev1 = image_stddev(extract_box_reference(screen, m_spritebox1)).sum(); + double stddev2 = image_stddev(extract_box_reference(screen, m_spritebox2)).sum(); + double stddev3 = image_stddev(extract_box_reference(screen, m_spritebox3)).sum(); + str += ", Sprites = {"; + str += tostr_default(stddev0) + ", "; + str += tostr_default(stddev1) + ", "; + str += tostr_default(stddev2) + ", "; + str += tostr_default(stddev3) + "}"; + + m_logger.log("RaidLobbyReader(): " + str, COLOR_PURPLE); + + const double PLAYER_READY = 100; + const double PLAYER_EXISTS = 20; + + RaidLobbyState state; + state.valid = true; + state.player0 = stddev0 < PLAYER_EXISTS + ? RaidLobbySlot::EMPTY + : RaidLobbySlot::NOT_READY; + state.player1 = stddev1 < PLAYER_EXISTS + ? RaidLobbySlot::EMPTY + : distance1 > PLAYER_READY + ? RaidLobbySlot::READY + : RaidLobbySlot::NOT_READY; + state.player2 = stddev2 < PLAYER_EXISTS + ? RaidLobbySlot::EMPTY + : distance2 > PLAYER_READY + ? RaidLobbySlot::READY + : RaidLobbySlot::NOT_READY; + state.player3 = stddev3 < PLAYER_EXISTS + ? RaidLobbySlot::EMPTY + : distance3 > PLAYER_READY + ? RaidLobbySlot::READY + : RaidLobbySlot::NOT_READY; + return state; +} + + +} +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h index 59f2f85ad7..fcc77cc2e2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h @@ -1,81 +1,81 @@ -/* Raid Lobby Reader - * - * From: https://github.com/PokemonAutomation/ - * - * - * Determine if a raid is full and ready to start early. - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_RaidLobbyReader_H -#define PokemonAutomation_PokemonSwSh_RaidLobbyReader_H - -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -enum class RaidLobbySlot{ - EMPTY, - NOT_READY, - READY, -}; - -struct RaidLobbyState{ - bool valid = false; - RaidLobbySlot player0 = RaidLobbySlot::EMPTY; - RaidLobbySlot player1 = RaidLobbySlot::EMPTY; - RaidLobbySlot player2 = RaidLobbySlot::EMPTY; - RaidLobbySlot player3 = RaidLobbySlot::EMPTY; - - bool raid_is_full() const{ - return - player0 != RaidLobbySlot::EMPTY && - player1 != RaidLobbySlot::EMPTY && - player2 != RaidLobbySlot::EMPTY && - player3 != RaidLobbySlot::EMPTY; - } - bool raiders_are_ready() const{ - return - player1 != RaidLobbySlot::NOT_READY && - player2 != RaidLobbySlot::NOT_READY && - player3 != RaidLobbySlot::NOT_READY; - } - - size_t raiders() const{ - size_t count = 0; - if (player1 != RaidLobbySlot::EMPTY) count++; - if (player2 != RaidLobbySlot::EMPTY) count++; - if (player3 != RaidLobbySlot::EMPTY) count++; - return count; - } -}; - - -class RaidLobbyReader{ -public: - RaidLobbyReader(Logger& logger, VideoOverlay& overlay); - - RaidLobbyState read(const ImageViewRGB32& screen); - -private: - Logger& m_logger; - OverlayBoxScope m_checkbox0; - OverlayBoxScope m_checkbox1; - OverlayBoxScope m_checkbox2; - OverlayBoxScope m_checkbox3; - OverlayBoxScope m_spritebox0; - OverlayBoxScope m_spritebox1; - OverlayBoxScope m_spritebox2; - OverlayBoxScope m_spritebox3; -}; - - -} -} -} -#endif - +/* Raid Lobby Reader + * + * From: https://github.com/PokemonAutomation/ + * + * + * Determine if a raid is full and ready to start early. + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_RaidLobbyReader_H +#define PokemonAutomation_PokemonSwSh_RaidLobbyReader_H + +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +enum class RaidLobbySlot{ + EMPTY, + NOT_READY, + READY, +}; + +struct RaidLobbyState{ + bool valid = false; + RaidLobbySlot player0 = RaidLobbySlot::EMPTY; + RaidLobbySlot player1 = RaidLobbySlot::EMPTY; + RaidLobbySlot player2 = RaidLobbySlot::EMPTY; + RaidLobbySlot player3 = RaidLobbySlot::EMPTY; + + bool raid_is_full() const{ + return + player0 != RaidLobbySlot::EMPTY && + player1 != RaidLobbySlot::EMPTY && + player2 != RaidLobbySlot::EMPTY && + player3 != RaidLobbySlot::EMPTY; + } + bool raiders_are_ready() const{ + return + player1 != RaidLobbySlot::NOT_READY && + player2 != RaidLobbySlot::NOT_READY && + player3 != RaidLobbySlot::NOT_READY; + } + + size_t raiders() const{ + size_t count = 0; + if (player1 != RaidLobbySlot::EMPTY) count++; + if (player2 != RaidLobbySlot::EMPTY) count++; + if (player3 != RaidLobbySlot::EMPTY) count++; + return count; + } +}; + + +class RaidLobbyReader{ +public: + RaidLobbyReader(Logger& logger, VideoOverlay& overlay); + + RaidLobbyState read(const ImageViewRGB32& screen); + +private: + Logger& m_logger; + OverlayBoxScope m_checkbox0; + OverlayBoxScope m_checkbox1; + OverlayBoxScope m_checkbox2; + OverlayBoxScope m_checkbox3; + OverlayBoxScope m_spritebox0; + OverlayBoxScope m_spritebox1; + OverlayBoxScope m_spritebox2; + OverlayBoxScope m_spritebox3; +}; + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.cpp index a9a6816522..013caeb597 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.cpp @@ -1,19 +1,19 @@ -/* IV Checker Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_BoxGenderDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -BoxGenderDetector::BoxGenderDetector(Color color) : Pokemon::BoxGenderDetector({0.720, 0.028, 0.229, 0.056}, 0.01f, color) {} - - -} -} -} - +/* IV Checker Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_BoxGenderDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +BoxGenderDetector::BoxGenderDetector(Color color) : Pokemon::BoxGenderDetector({0.720, 0.028, 0.229, 0.056}, 0.01f, color) {} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h index 9a10f03e88..e51d25403d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h @@ -1,29 +1,29 @@ -/* Box Gender Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BoxGenderDetector_H -#define PokemonAutomation_PokemonSwSh_BoxGenderDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_BoxGenderDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BoxGenderDetector : public Pokemon::BoxGenderDetector{ - -public: - BoxGenderDetector(Color color = COLOR_RED); - -}; - - -} -} -} -#endif +/* Box Gender Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BoxGenderDetector_H +#define PokemonAutomation_PokemonSwSh_BoxGenderDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_BoxGenderDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BoxGenderDetector : public Pokemon::BoxGenderDetector{ + +public: + BoxGenderDetector(Color color = COLOR_RED); + +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.cpp index 47b4e6da67..6dd589e96d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.cpp @@ -1,83 +1,83 @@ -/* IV Checker Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/ImageFilter.h" -#include "PokemonSwSh_BoxNatureDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -BoxNatureDetector::BoxNatureDetector(VideoOverlay& overlay) - : m_box_atk(overlay, { 0.689, 0.198 + 1 * 0.0515, 0.084, 0.047}) - , m_box_def(overlay, { 0.689, 0.198 + 2 * 0.0515, 0.084, 0.047}) - , m_box_spatk(overlay, { 0.689, 0.198 + 3 * 0.0515, 0.084, 0.047}) - , m_box_spdef(overlay, { 0.689, 0.198 + 4 * 0.0515, 0.084, 0.047}) - , m_box_spd(overlay, { 0.689, 0.198 + 5 * 0.0515, 0.084, 0.047}) -{} - -NaturePlusMinus BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame, const ImageFloatBox& box){ - const bool replace_color_within_range = true; - - //Filter out background - white/gray - ImageRGB32 filtered_region = filter_rgb32_range( - extract_box_reference(frame, box), - combine_rgb(215, 215, 215), combine_rgb(255, 255, 255), Color(0), replace_color_within_range - ); - ImageStats stats = image_stats(filtered_region); - - //filtered_region.save("./filtered_only.png"); - //cout << stats.average.r << endl; - //cout << stats.average.g << endl; - //cout << stats.average.b << endl; - - if (stats.average.b > stats.average.r + 50){ - return NaturePlusMinus::MINUS; - }else if (stats.average.r > stats.average.b + 50){ - return NaturePlusMinus::PLUS; - } - return NaturePlusMinus::NEUTRAL; -} - -NatureReader::Results BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame){ - NatureReader::Results results; - NaturePlusMinus stats[5]; - int statPlus = -1; - int statMinus = -1; - - stats[0] = read(logger, frame, m_box_atk); - stats[1] = read(logger, frame, m_box_def); - stats[2] = read(logger, frame, m_box_spatk); - stats[3] = read(logger, frame, m_box_spdef); - stats[4] = read(logger, frame, m_box_spd); - - for (int i = 0; i < 5; i++){ - if (stats[i] == NaturePlusMinus::PLUS){ - statPlus = i; - }else if (stats[i] == NaturePlusMinus::MINUS){ - statMinus = i; - } - } - - results.nature = NatureCheckerValue_helphinder_to_enum(std::make_pair(statPlus, statMinus)); - return results; -} - - -} -} -} - +/* IV Checker Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/ImageFilter.h" +#include "PokemonSwSh_BoxNatureDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +BoxNatureDetector::BoxNatureDetector(VideoOverlay& overlay) + : m_box_atk(overlay, { 0.689, 0.198 + 1 * 0.0515, 0.084, 0.047}) + , m_box_def(overlay, { 0.689, 0.198 + 2 * 0.0515, 0.084, 0.047}) + , m_box_spatk(overlay, { 0.689, 0.198 + 3 * 0.0515, 0.084, 0.047}) + , m_box_spdef(overlay, { 0.689, 0.198 + 4 * 0.0515, 0.084, 0.047}) + , m_box_spd(overlay, { 0.689, 0.198 + 5 * 0.0515, 0.084, 0.047}) +{} + +NaturePlusMinus BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame, const ImageFloatBox& box){ + const bool replace_color_within_range = true; + + //Filter out background - white/gray + ImageRGB32 filtered_region = filter_rgb32_range( + extract_box_reference(frame, box), + combine_rgb(215, 215, 215), combine_rgb(255, 255, 255), Color(0), replace_color_within_range + ); + ImageStats stats = image_stats(filtered_region); + + //filtered_region.save("./filtered_only.png"); + //cout << stats.average.r << endl; + //cout << stats.average.g << endl; + //cout << stats.average.b << endl; + + if (stats.average.b > stats.average.r + 50){ + return NaturePlusMinus::MINUS; + }else if (stats.average.r > stats.average.b + 50){ + return NaturePlusMinus::PLUS; + } + return NaturePlusMinus::NEUTRAL; +} + +NatureReader::Results BoxNatureDetector::read(Logger& logger, const ImageViewRGB32& frame){ + NatureReader::Results results; + NaturePlusMinus stats[5]; + int statPlus = -1; + int statMinus = -1; + + stats[0] = read(logger, frame, m_box_atk); + stats[1] = read(logger, frame, m_box_def); + stats[2] = read(logger, frame, m_box_spatk); + stats[3] = read(logger, frame, m_box_spdef); + stats[4] = read(logger, frame, m_box_spd); + + for (int i = 0; i < 5; i++){ + if (stats[i] == NaturePlusMinus::PLUS){ + statPlus = i; + }else if (stats[i] == NaturePlusMinus::MINUS){ + statMinus = i; + } + } + + results.nature = NatureCheckerValue_helphinder_to_enum(std::make_pair(statPlus, statMinus)); + return results; +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h index 889ddc8350..4c81007e26 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h @@ -1,46 +1,46 @@ -/* IV Checker Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BoxNatureDetector_H -#define PokemonAutomation_PokemonSwSh_BoxNatureDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_NatureReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - -enum class NaturePlusMinus{ - NEUTRAL = 0, - PLUS, - MINUS, -}; - -class BoxNatureDetector{ -public: - BoxNatureDetector(VideoOverlay& overlay); - - NatureReader::Results read(Logger& logger, const ImageViewRGB32& frame); - -private: - NaturePlusMinus read(Logger& logger, const ImageViewRGB32& frame, const ImageFloatBox& box); - -private: - OverlayBoxScope m_box_atk; - OverlayBoxScope m_box_def; - OverlayBoxScope m_box_spatk; - OverlayBoxScope m_box_spdef; - OverlayBoxScope m_box_spd; -}; - - - -} -} -} -#endif +/* IV Checker Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BoxNatureDetector_H +#define PokemonAutomation_PokemonSwSh_BoxNatureDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_NatureReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + +enum class NaturePlusMinus{ + NEUTRAL = 0, + PLUS, + MINUS, +}; + +class BoxNatureDetector{ +public: + BoxNatureDetector(VideoOverlay& overlay); + + NatureReader::Results read(Logger& logger, const ImageViewRGB32& frame); + +private: + NaturePlusMinus read(Logger& logger, const ImageViewRGB32& frame, const ImageFloatBox& box); + +private: + OverlayBoxScope m_box_atk; + OverlayBoxScope m_box_def; + OverlayBoxScope m_box_spatk; + OverlayBoxScope m_box_spdef; + OverlayBoxScope m_box_spd; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.cpp index 12916f0b2d..da4f101a9f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.cpp @@ -1,42 +1,42 @@ -/* Box Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSwSh_BoxShinySymbolDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -namespace{ - ImageFloatBox SHINY_BOX{0.969, 0.145, 0.024, 0.040}; -} - -void BoxShinySymbolDetector::make_overlays(VideoOverlaySet& items){ - items.add(COLOR_RED, SHINY_BOX); -} - -bool BoxShinySymbolDetector::detect(const ImageViewRGB32& screen){ - const ImageStats symbol = image_stats(extract_box_reference(screen, SHINY_BOX)); - if (PreloadSettings::debug().COLOR_CHECK){ - cout << "Symbol region stddev " << symbol.stddev.to_string() << " (sum " << symbol.stddev.sum() << "), threshold: 50" << endl; - } - return symbol.stddev.sum() > 50; -} - -} -} -} +/* Box Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSwSh_BoxShinySymbolDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +namespace{ + ImageFloatBox SHINY_BOX{0.969, 0.145, 0.024, 0.040}; +} + +void BoxShinySymbolDetector::make_overlays(VideoOverlaySet& items){ + items.add(COLOR_RED, SHINY_BOX); +} + +bool BoxShinySymbolDetector::detect(const ImageViewRGB32& screen){ + const ImageStats symbol = image_stats(extract_box_reference(screen, SHINY_BOX)); + if (PreloadSettings::debug().COLOR_CHECK){ + cout << "Symbol region stddev " << symbol.stddev.to_string() << " (sum " << symbol.stddev.sum() << "), threshold: 50" << endl; + } + return symbol.stddev.sum() > 50; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h index 8524d8b9e9..315608f874 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h @@ -1,37 +1,37 @@ -/* Box Shiny Symbol Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Check shiny symbol when viewing pokemon in a storage box. - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BoxShinySymbolDetector_H -#define PokemonAutomation_PokemonSwSh_BoxShinySymbolDetector_H - - -namespace PokemonAutomation{ - -class ImageViewRGB32; -class VideoOverlaySet; - -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BoxShinySymbolDetector{ -public: - static void make_overlays(VideoOverlaySet& items); - - static bool detect(const ImageViewRGB32& screen); -}; - - - -} -} -} - -#endif - +/* Box Shiny Symbol Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Check shiny symbol when viewing pokemon in a storage box. + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BoxShinySymbolDetector_H +#define PokemonAutomation_PokemonSwSh_BoxShinySymbolDetector_H + + +namespace PokemonAutomation{ + +class ImageViewRGB32; +class VideoOverlaySet; + +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BoxShinySymbolDetector{ +public: + static void make_overlays(VideoOverlaySet& items); + + static bool detect(const ImageViewRGB32& screen); +}; + + + +} +} +} + +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.cpp index 3405b76829..d87ba65b80 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.cpp @@ -1,72 +1,72 @@ -/* Dialog Triangle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include - -#include "Common/Cpp/Color.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_DialogBoxDetector.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -namespace{ - // This box covers all possible locations of the black triangle arrow - std::array BLACK_BOXES{{ - {0.254, 0.806, 0.012, 0.052}, - {0.730, 0.806, 0.016, 0.068}, - {0.741, 0.880, 0.005, 0.055}, - {0.710, 0.880, 0.007, 0.055}, - }}; -} - - -BlackDialogBoxDetector::BlackDialogBoxDetector( - bool stop_on_detected -) - : VisualInferenceCallback("BlackDialogBoxDetector") - , m_stop_on_detected(stop_on_detected) -{} - - -void BlackDialogBoxDetector::make_overlays(VideoOverlaySet& items) const{ - for(const auto& box : BLACK_BOXES){ - items.add(COLOR_RED, box); - } -} - - -bool BlackDialogBoxDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool detected = true; - for(const auto& box : BLACK_BOXES){ - if (is_black(extract_box_reference(frame, box), 180, 30) == false){ - detected = false; - break; - } - } - - m_detected.store(detected, std::memory_order_release); - - return detected && m_stop_on_detected; -} - - - - - -} -} -} - +/* Dialog Triangle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include + +#include "Common/Cpp/Color.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_DialogBoxDetector.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +namespace{ + // This box covers all possible locations of the black triangle arrow + std::array BLACK_BOXES{{ + {0.254, 0.806, 0.012, 0.052}, + {0.730, 0.806, 0.016, 0.068}, + {0.741, 0.880, 0.005, 0.055}, + {0.710, 0.880, 0.007, 0.055}, + }}; +} + + +BlackDialogBoxDetector::BlackDialogBoxDetector( + bool stop_on_detected +) + : VisualInferenceCallback("BlackDialogBoxDetector") + , m_stop_on_detected(stop_on_detected) +{} + + +void BlackDialogBoxDetector::make_overlays(VideoOverlaySet& items) const{ + for(const auto& box : BLACK_BOXES){ + items.add(COLOR_RED, box); + } +} + + +bool BlackDialogBoxDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool detected = true; + for(const auto& box : BLACK_BOXES){ + if (is_black(extract_box_reference(frame, box), 180, 30) == false){ + detected = false; + break; + } + } + + m_detected.store(detected, std::memory_order_release); + + return detected && m_stop_on_detected; +} + + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h index 81d3876582..07048967f5 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h @@ -1,44 +1,44 @@ -/* Dialog Box Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DialogBoxDetector_H -#define PokemonAutomation_PokemonSwSh_DialogBoxDetector_H - -#include -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -// Detect the black dialog box. It is used in places like releasing pokemon in box storage. -class BlackDialogBoxDetector : public VisualInferenceCallback{ -public: - BlackDialogBoxDetector(bool stop_on_detected); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - - std::atomic m_detected; -}; - - - - - -} -} -} -#endif +/* Dialog Box Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DialogBoxDetector_H +#define PokemonAutomation_PokemonSwSh_DialogBoxDetector_H + +#include +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +// Detect the black dialog box. It is used in places like releasing pokemon in box storage. +class BlackDialogBoxDetector : public VisualInferenceCallback{ +public: + BlackDialogBoxDetector(bool stop_on_detected); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + + std::atomic m_detected; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.cpp index fa6b7ef28b..7bb48e81e6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.cpp @@ -1,109 +1,109 @@ -/* Dialog Triangle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Color.h" -#include "Common/Cpp/AbstractLogger.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSwSh_DialogTriangleDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -namespace{ - // This box covers all possible locations of the black triangle arrow - ImageFloatBox BLACK_TRIANGLE_BOX{0.771, 0.901, 0.031, 0.069}; -} - -class DialogTriangleMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - DialogTriangleMatcher(); - static const DialogTriangleMatcher& instance(); -}; - - -DialogTriangleMatcher::DialogTriangleMatcher() - : WaterfillTemplateMatcher( - "PokemonSwSh/DialogBlackTriangle.png", - Color(0,0,0), Color(30, 30, 30), 50 - ) -{ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.1; -} - -const DialogTriangleMatcher& DialogTriangleMatcher::instance(){ - static DialogTriangleMatcher matcher; - return matcher; -} - - - -DialogTriangleDetector::DialogTriangleDetector( - Logger& logger, VideoOverlay& overlay, - bool stop_on_detected -) - : VisualInferenceCallback("DialogTriangleDetector") - , m_logger(logger) - , m_stop_on_detected(stop_on_detected) -{} - - -void DialogTriangleDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, BLACK_TRIANGLE_BOX); -} -bool DialogTriangleDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - const std::vector> filters = { - {combine_rgb(0, 0, 0), combine_rgb(50, 50, 50)} - }; - - const double screen_rel_size = (frame.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 500.0); - - const bool detected = match_template_by_waterfill( - extract_box_reference(frame, BLACK_TRIANGLE_BOX), - DialogTriangleMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 80, - [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); - - if (detected){ - m_logger.log("Detected dialog black triangle.", COLOR_PURPLE); - } - - m_detected.store(detected, std::memory_order_release); - -#if 0 - if (detected){ - static size_t c = 0; - frame.save("DialogTriangleDetectorTriggered-" + std::to_string(c++) + ".png"); - } -#endif - - return detected && m_stop_on_detected; -} - - - - - -} -} -} - +/* Dialog Triangle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Color.h" +#include "Common/Cpp/AbstractLogger.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSwSh_DialogTriangleDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +namespace{ + // This box covers all possible locations of the black triangle arrow + ImageFloatBox BLACK_TRIANGLE_BOX{0.771, 0.901, 0.031, 0.069}; +} + +class DialogTriangleMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + DialogTriangleMatcher(); + static const DialogTriangleMatcher& instance(); +}; + + +DialogTriangleMatcher::DialogTriangleMatcher() + : WaterfillTemplateMatcher( + "PokemonSwSh/DialogBlackTriangle.png", + Color(0,0,0), Color(30, 30, 30), 50 + ) +{ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.1; +} + +const DialogTriangleMatcher& DialogTriangleMatcher::instance(){ + static DialogTriangleMatcher matcher; + return matcher; +} + + + +DialogTriangleDetector::DialogTriangleDetector( + Logger& logger, VideoOverlay& overlay, + bool stop_on_detected +) + : VisualInferenceCallback("DialogTriangleDetector") + , m_logger(logger) + , m_stop_on_detected(stop_on_detected) +{} + + +void DialogTriangleDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, BLACK_TRIANGLE_BOX); +} +bool DialogTriangleDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + const std::vector> filters = { + {combine_rgb(0, 0, 0), combine_rgb(50, 50, 50)} + }; + + const double screen_rel_size = (frame.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 500.0); + + const bool detected = match_template_by_waterfill( + extract_box_reference(frame, BLACK_TRIANGLE_BOX), + DialogTriangleMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 80, + [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); + + if (detected){ + m_logger.log("Detected dialog black triangle.", COLOR_PURPLE); + } + + m_detected.store(detected, std::memory_order_release); + +#if 0 + if (detected){ + static size_t c = 0; + frame.save("DialogTriangleDetectorTriggered-" + std::to_string(c++) + ".png"); + } +#endif + + return detected && m_stop_on_detected; +} + + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h index 24f10a433e..75e13f409a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h @@ -1,51 +1,51 @@ -/* Dialog Triangle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DialogTriangleDetector_H -#define PokemonAutomation_PokemonSwSh_DialogTriangleDetector_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -// Detect the black triangle arrow in the lower right portion of the white dialog box. -// The dialog box shows up when talking to npcs. -class DialogTriangleDetector : public VisualInferenceCallback{ -public: - DialogTriangleDetector( - Logger& logger, VideoOverlay& overlay, - bool stop_on_detected - ); - - bool detected() const{ - return m_detected.load(std::memory_order_acquire); - } - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - Logger& m_logger; - bool m_stop_on_detected; - - std::atomic m_detected; -}; - - - - - -} -} -} -#endif +/* Dialog Triangle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DialogTriangleDetector_H +#define PokemonAutomation_PokemonSwSh_DialogTriangleDetector_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +// Detect the black triangle arrow in the lower right portion of the white dialog box. +// The dialog box shows up when talking to npcs. +class DialogTriangleDetector : public VisualInferenceCallback{ +public: + DialogTriangleDetector( + Logger& logger, VideoOverlay& overlay, + bool stop_on_detected + ); + + bool detected() const{ + return m_detected.load(std::memory_order_acquire); + } + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + Logger& m_logger; + bool m_stop_on_detected; + + std::atomic m_detected; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp index c62f1a85bb..daac098b08 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp @@ -1,82 +1,82 @@ -/* Fishing Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_MarkFinder.h" -#include "PokemonSwSh_FishingDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -FishingMissDetector::FishingMissDetector() - : VisualInferenceCallback("FishingMissDetector") - , m_hook_box(0.1, 0.15, 0.8, 0.4) - , m_miss_box(0.3, 0.9, 0.4, 0.05) -{} -void FishingMissDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_hook_box); - items.add(COLOR_RED, m_miss_box); -} -bool FishingMissDetector::detect(const ImageViewRGB32& frame){ - ImageViewRGB32 miss_image = extract_box_reference(frame, m_miss_box); - ImageStats miss_stats = image_stats(miss_image); - if (!is_white(miss_stats)){ - return false; - } - - ImageViewRGB32 hook_image = extract_box_reference(frame, m_hook_box); - if (image_stddev(hook_image).sum() < 50){ - return false; - } - - return true; -} -bool FishingMissDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -FishingHookDetector::FishingHookDetector(VideoOverlay& overlay) - : VisualInferenceCallback("FishingHookDetector") - , m_overlay(overlay) - , m_hook_box(0.1, 0.15, 0.8, 0.4) -{} -void FishingHookDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_hook_box); -} -bool FishingHookDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ImageViewRGB32 hook_image = extract_box_reference(frame, m_hook_box); - - std::vector exclamation_marks = find_exclamation_marks(hook_image); - for (const ImagePixelBox& mark : exclamation_marks){ - ImageFloatBox box = translate_to_parent(frame, m_hook_box, mark); - m_marks.emplace_back(m_overlay, box, COLOR_YELLOW); - } - -// if (!exclamation_marks.empty()){ -// frame.save("test.png"); -// } - - return !exclamation_marks.empty(); -} - - - - - - - - - - - -} -} -} - +/* Fishing Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_MarkFinder.h" +#include "PokemonSwSh_FishingDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +FishingMissDetector::FishingMissDetector() + : VisualInferenceCallback("FishingMissDetector") + , m_hook_box(0.1, 0.15, 0.8, 0.4) + , m_miss_box(0.3, 0.9, 0.4, 0.05) +{} +void FishingMissDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_hook_box); + items.add(COLOR_RED, m_miss_box); +} +bool FishingMissDetector::detect(const ImageViewRGB32& frame){ + ImageViewRGB32 miss_image = extract_box_reference(frame, m_miss_box); + ImageStats miss_stats = image_stats(miss_image); + if (!is_white(miss_stats)){ + return false; + } + + ImageViewRGB32 hook_image = extract_box_reference(frame, m_hook_box); + if (image_stddev(hook_image).sum() < 50){ + return false; + } + + return true; +} +bool FishingMissDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +FishingHookDetector::FishingHookDetector(VideoOverlay& overlay) + : VisualInferenceCallback("FishingHookDetector") + , m_overlay(overlay) + , m_hook_box(0.1, 0.15, 0.8, 0.4) +{} +void FishingHookDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_hook_box); +} +bool FishingHookDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ImageViewRGB32 hook_image = extract_box_reference(frame, m_hook_box); + + std::vector exclamation_marks = find_exclamation_marks(hook_image); + for (const ImagePixelBox& mark : exclamation_marks){ + ImageFloatBox box = translate_to_parent(frame, m_hook_box, mark); + m_marks.emplace_back(m_overlay, box, COLOR_YELLOW); + } + +// if (!exclamation_marks.empty()){ +// frame.save("test.png"); +// } + + return !exclamation_marks.empty(); +} + + + + + + + + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h index f5318f8473..0028c7e838 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h @@ -1,51 +1,51 @@ -/* Fishing Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_FishingDetector_H -#define PokemonAutomation_PokemonSwSh_FishingDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class VideoOverlay; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class FishingMissDetector : public VisualInferenceCallback{ -public: - FishingMissDetector(); - - bool detect(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_hook_box; - ImageFloatBox m_miss_box; -}; - -class FishingHookDetector : public VisualInferenceCallback{ -public: - FishingHookDetector(VideoOverlay& overlay); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - VideoOverlay& m_overlay; - ImageFloatBox m_hook_box; - std::deque m_marks; -}; - - - -} -} -} -#endif +/* Fishing Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_FishingDetector_H +#define PokemonAutomation_PokemonSwSh_FishingDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class VideoOverlay; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class FishingMissDetector : public VisualInferenceCallback{ +public: + FishingMissDetector(); + + bool detect(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_hook_box; + ImageFloatBox m_miss_box; +}; + +class FishingHookDetector : public VisualInferenceCallback{ +public: + FishingHookDetector(VideoOverlay& overlay); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + VideoOverlay& m_overlay; + ImageFloatBox m_hook_box; + std::deque m_marks; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.cpp index ca7b4d0219..21473db3b0 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.cpp @@ -1,77 +1,77 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "PokemonSwSh_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const IvJudgeReader& IV_READER(){ - const static Pokemon::IvJudgeReader reader("PokemonSwSh/IVCheckerOCR.json"); - return reader; -} - - - - -IvJudgeReaderScope::IvJudgeReaderScope(VideoOverlay& overlay, Language language) - : m_language(language) - , m_box0(overlay, {0.777, 0.198 + 0 * 0.0515, 0.2, 0.0515}) - , m_box1(overlay, {0.777, 0.198 + 1 * 0.0515, 0.2, 0.0515}) - , m_box2(overlay, {0.777, 0.198 + 2 * 0.0515, 0.2, 0.0515}) - , m_box3(overlay, {0.777, 0.198 + 3 * 0.0515, 0.2, 0.0515}) - , m_box4(overlay, {0.777, 0.198 + 4 * 0.0515, 0.2, 0.0515}) - , m_box5(overlay, {0.777, 0.198 + 5 * 0.0515, 0.2, 0.0515}) -{} - - - - -IvJudgeValue IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ - ImageViewRGB32 image = extract_box_reference(frame, box); - OCR::StringMatchResult result = IV_READER().read_substring( - logger, m_language, image, - OCR::BLACK_TEXT_FILTERS() - ); - result.clear_beyond_log10p(IvJudgeReader::MAX_LOG10P); - if (result.results.size() != 1){ - return IvJudgeValue::UnableToDetect; - } - return IV_JUDGE_VALUE_STRINGS().get_enum(result.results.begin()->second.token); -} -IvJudgeReader::Results IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame){ - IvJudgeReader::Results results; - if (m_language != Language::None){ - results.hp = read(logger, frame, m_box0); - results.attack = read(logger, frame, m_box1); - results.defense = read(logger, frame, m_box2); - results.spatk = read(logger, frame, m_box3); - results.spdef = read(logger, frame, m_box4); - results.speed = read(logger, frame, m_box5); - } - return results; -} - -std::vector IvJudgeReaderScope::dump_images(const ImageViewRGB32& frame){ - std::vector images; - images.emplace_back(extract_box_reference(frame, m_box0)); - images.emplace_back(extract_box_reference(frame, m_box1)); - images.emplace_back(extract_box_reference(frame, m_box2)); - images.emplace_back(extract_box_reference(frame, m_box3)); - images.emplace_back(extract_box_reference(frame, m_box4)); - images.emplace_back(extract_box_reference(frame, m_box5)); - return images; -} - - - -} -} -} - +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "PokemonSwSh_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const IvJudgeReader& IV_READER(){ + const static Pokemon::IvJudgeReader reader("PokemonSwSh/IVCheckerOCR.json"); + return reader; +} + + + + +IvJudgeReaderScope::IvJudgeReaderScope(VideoOverlay& overlay, Language language) + : m_language(language) + , m_box0(overlay, {0.777, 0.198 + 0 * 0.0515, 0.2, 0.0515}) + , m_box1(overlay, {0.777, 0.198 + 1 * 0.0515, 0.2, 0.0515}) + , m_box2(overlay, {0.777, 0.198 + 2 * 0.0515, 0.2, 0.0515}) + , m_box3(overlay, {0.777, 0.198 + 3 * 0.0515, 0.2, 0.0515}) + , m_box4(overlay, {0.777, 0.198 + 4 * 0.0515, 0.2, 0.0515}) + , m_box5(overlay, {0.777, 0.198 + 5 * 0.0515, 0.2, 0.0515}) +{} + + + + +IvJudgeValue IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box){ + ImageViewRGB32 image = extract_box_reference(frame, box); + OCR::StringMatchResult result = IV_READER().read_substring( + logger, m_language, image, + OCR::BLACK_TEXT_FILTERS() + ); + result.clear_beyond_log10p(IvJudgeReader::MAX_LOG10P); + if (result.results.size() != 1){ + return IvJudgeValue::UnableToDetect; + } + return IV_JUDGE_VALUE_STRINGS().get_enum(result.results.begin()->second.token); +} +IvJudgeReader::Results IvJudgeReaderScope::read(Logger& logger, const ImageViewRGB32& frame){ + IvJudgeReader::Results results; + if (m_language != Language::None){ + results.hp = read(logger, frame, m_box0); + results.attack = read(logger, frame, m_box1); + results.defense = read(logger, frame, m_box2); + results.spatk = read(logger, frame, m_box3); + results.spdef = read(logger, frame, m_box4); + results.speed = read(logger, frame, m_box5); + } + return results; +} + +std::vector IvJudgeReaderScope::dump_images(const ImageViewRGB32& frame){ + std::vector images; + images.emplace_back(extract_box_reference(frame, m_box0)); + images.emplace_back(extract_box_reference(frame, m_box1)); + images.emplace_back(extract_box_reference(frame, m_box2)); + images.emplace_back(extract_box_reference(frame, m_box3)); + images.emplace_back(extract_box_reference(frame, m_box4)); + images.emplace_back(extract_box_reference(frame, m_box5)); + return images; +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h index 224d4fc82d..42e9d92129 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h @@ -1,48 +1,48 @@ -/* IV Judge Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_IvJudgeReader_H -#define PokemonAutomation_PokemonSwSh_IvJudgeReader_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - - -const IvJudgeReader& IV_READER(); - - -class IvJudgeReaderScope{ -public: - IvJudgeReaderScope(VideoOverlay& overlay, Language language); - - IvJudgeReader::Results read(Logger& logger, const ImageViewRGB32& frame); - - std::vector dump_images(const ImageViewRGB32& frame); - -private: - IvJudgeValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); - -private: - Language m_language; - OverlayBoxScope m_box0; - OverlayBoxScope m_box1; - OverlayBoxScope m_box2; - OverlayBoxScope m_box3; - OverlayBoxScope m_box4; - OverlayBoxScope m_box5; -}; - - - -} -} -} -#endif +/* IV Judge Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_IvJudgeReader_H +#define PokemonAutomation_PokemonSwSh_IvJudgeReader_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "Pokemon/Inference/Pokemon_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + + +const IvJudgeReader& IV_READER(); + + +class IvJudgeReaderScope{ +public: + IvJudgeReaderScope(VideoOverlay& overlay, Language language); + + IvJudgeReader::Results read(Logger& logger, const ImageViewRGB32& frame); + + std::vector dump_images(const ImageViewRGB32& frame); + +private: + IvJudgeValue read(Logger& logger, const ImageViewRGB32& frame, const OverlayBoxScope& box); + +private: + Language m_language; + OverlayBoxScope m_box0; + OverlayBoxScope m_box1; + OverlayBoxScope m_box2; + OverlayBoxScope m_box3; + OverlayBoxScope m_box4; + OverlayBoxScope m_box5; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.cpp index 98626c869b..0f8ec018c6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.cpp @@ -1,174 +1,174 @@ -/* Mark Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" -#include "PokemonSwSh_MarkFinder.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -void generate_exclamation_mark(){ - ImageRGB32 image("ExclamationMark1.png"); - image = image.scale_to(image.width() / 4, image.height() / 4); - uint32_t* ptr = image.data(); - size_t words = image.bytes_per_row() / sizeof(uint32_t); - for (size_t r = 0; r < image.height(); r++){ - for (size_t c = 0; c < image.width(); c++){ - uint32_t& pixel = ptr[r * words + c]; - Color color(pixel); - uint32_t red = color.red(); - uint32_t green = color.green(); - uint32_t blue = color.blue(); - if (red < 192 && green < 192){ - pixel = 0xff000000; - } - if (blue > red + 20){ - pixel = 0xff000000; - } - } - } - image.save("test.png"); -} - - - -class ExclamationMatcher : public ImageMatch::SubObjectTemplateMatcher{ -public: - static const ExclamationMatcher& instance(){ - static ExclamationMatcher matcher; - return matcher; - } - - ExclamationMatcher() - : SubObjectTemplateMatcher("PokemonSwSh/ExclamationMark1-Template.png", 80) - { - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - m_matcher.image_template(), - 160, 255, - 0, 160, - 0, 192 - ); - std::vector objects = find_objects_inplace(matrix, 20); - if (objects.size() != 2){ - throw FileException( - nullptr, PA_CURRENT_FUNCTION, - "Failed to find exactly two objects in resource.", - m_path - ); - } - size_t index = 0; - if (objects[0].area < objects[1].area){ - index = 1; - } - set_subobject(objects[index]); - } - -}; - - - - - -const ImageMatch::ExactImageMatcher& QUESTION_TOP(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSwSh/QuestionTop.png"); - return matcher; -} - -bool is_question_mark(const ImageViewRGB32& image, const WaterfillObject& object){ - size_t width = object.width(); - size_t height = object.height(); - - if (width > 2 * height){ - return false; - } - if (height > 2 * width){ - return false; - } - - ImageViewRGB32 scaled = extract_box_reference(image, object); -// scaled = scaled.scaled(exclamation_mark.width(), exclamation_mark.height()); - double rmsd = QUESTION_TOP().rmsd(scaled); -// double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); - if (rmsd <= 100){ -// cout << "is_question_mark(): rmsd = " << rmsd << endl; - } - return rmsd <= 100; -} - -std::vector find_exclamation_marks(const ImageViewRGB32& image){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - image, - 160, 255, - 0, 160, - 0, 192 - ); - std::vector objects = find_objects_inplace(matrix, 20); -#if 0 - cout << "objects = " << objects.size() << endl; - static int c = 0; - for (const auto& object : objects){ - extract_box_reference(image, object).save("test-" + std::to_string(c++) + ".png"); - } -#endif - std::vector ret; - for (const WaterfillObject& object : objects){ - if (object.area < 100){ - continue; - } - ImagePixelBox object_box; - if (ExclamationMatcher::instance().matches(object_box, image, object)){ - ret.emplace_back(object_box); -// static int c = 0; -// extract_box_reference(image, object).save("test-" + std::to_string(c++) + ".png"); - } - } -// cout << ret.size() << endl; - return ret; -} -std::vector find_question_marks(const ImageViewRGB32& image){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( - image, - 0, 128, - 0, 255, - 128, 255 - ); - std::vector objects = find_objects_inplace(matrix, 50); - std::vector ret; -#if 1 - for (const WaterfillObject& object : objects){ - if (is_question_mark(image, object)){ - ret.emplace_back( - ImagePixelBox( - object.min_x, object.min_y, - object.max_x, object.max_y + object.height() / 3 - ) - ); - } - } -#endif - return ret; -} - - - - -} -} -} +/* Mark Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "CommonTools/ImageMatch/SubObjectTemplateMatcher.h" +#include "PokemonSwSh_MarkFinder.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +void generate_exclamation_mark(){ + ImageRGB32 image("ExclamationMark1.png"); + image = image.scale_to(image.width() / 4, image.height() / 4); + uint32_t* ptr = image.data(); + size_t words = image.bytes_per_row() / sizeof(uint32_t); + for (size_t r = 0; r < image.height(); r++){ + for (size_t c = 0; c < image.width(); c++){ + uint32_t& pixel = ptr[r * words + c]; + Color color(pixel); + uint32_t red = color.red(); + uint32_t green = color.green(); + uint32_t blue = color.blue(); + if (red < 192 && green < 192){ + pixel = 0xff000000; + } + if (blue > red + 20){ + pixel = 0xff000000; + } + } + } + image.save("test.png"); +} + + + +class ExclamationMatcher : public ImageMatch::SubObjectTemplateMatcher{ +public: + static const ExclamationMatcher& instance(){ + static ExclamationMatcher matcher; + return matcher; + } + + ExclamationMatcher() + : SubObjectTemplateMatcher("PokemonSwSh/ExclamationMark1-Template.png", 80) + { + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + m_matcher.image_template(), + 160, 255, + 0, 160, + 0, 192 + ); + std::vector objects = find_objects_inplace(matrix, 20); + if (objects.size() != 2){ + throw FileException( + nullptr, PA_CURRENT_FUNCTION, + "Failed to find exactly two objects in resource.", + m_path + ); + } + size_t index = 0; + if (objects[0].area < objects[1].area){ + index = 1; + } + set_subobject(objects[index]); + } + +}; + + + + + +const ImageMatch::ExactImageMatcher& QUESTION_TOP(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSwSh/QuestionTop.png"); + return matcher; +} + +bool is_question_mark(const ImageViewRGB32& image, const WaterfillObject& object){ + size_t width = object.width(); + size_t height = object.height(); + + if (width > 2 * height){ + return false; + } + if (height > 2 * width){ + return false; + } + + ImageViewRGB32 scaled = extract_box_reference(image, object); +// scaled = scaled.scaled(exclamation_mark.width(), exclamation_mark.height()); + double rmsd = QUESTION_TOP().rmsd(scaled); +// double rmsd = ImageMatch::pixel_RMSD(exclamation_mark, scaled); + if (rmsd <= 100){ +// cout << "is_question_mark(): rmsd = " << rmsd << endl; + } + return rmsd <= 100; +} + +std::vector find_exclamation_marks(const ImageViewRGB32& image){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + image, + 160, 255, + 0, 160, + 0, 192 + ); + std::vector objects = find_objects_inplace(matrix, 20); +#if 0 + cout << "objects = " << objects.size() << endl; + static int c = 0; + for (const auto& object : objects){ + extract_box_reference(image, object).save("test-" + std::to_string(c++) + ".png"); + } +#endif + std::vector ret; + for (const WaterfillObject& object : objects){ + if (object.area < 100){ + continue; + } + ImagePixelBox object_box; + if (ExclamationMatcher::instance().matches(object_box, image, object)){ + ret.emplace_back(object_box); +// static int c = 0; +// extract_box_reference(image, object).save("test-" + std::to_string(c++) + ".png"); + } + } +// cout << ret.size() << endl; + return ret; +} +std::vector find_question_marks(const ImageViewRGB32& image){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_range( + image, + 0, 128, + 0, 255, + 128, 255 + ); + std::vector objects = find_objects_inplace(matrix, 50); + std::vector ret; +#if 1 + for (const WaterfillObject& object : objects){ + if (is_question_mark(image, object)){ + ret.emplace_back( + ImagePixelBox( + object.min_x, object.min_y, + object.max_x, object.max_y + object.height() / 3 + ) + ); + } + } +#endif + return ret; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h index 2e1f06cd1d..64779c6604 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h @@ -1,25 +1,25 @@ -/* Mark Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MarkFinder_H -#define PokemonAutomation_PokemonSwSh_MarkFinder_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -std::vector find_exclamation_marks(const ImageViewRGB32& image); -std::vector find_question_marks(const ImageViewRGB32& image); - - -} -} -} -#endif +/* Mark Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MarkFinder_H +#define PokemonAutomation_PokemonSwSh_MarkFinder_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +std::vector find_exclamation_marks(const ImageViewRGB32& image); +std::vector find_question_marks(const ImageViewRGB32& image); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.cpp index 5a64133fd4..780312f9c7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.cpp @@ -1,100 +1,100 @@ -/* Pokemon Sprite Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/ImageMatch/ImageCropper.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "PokemonSwSh_PokemonSpriteReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -PokemonSpriteMatcherExact::PokemonSpriteMatcherExact(const std::set* subset) - : ExactImageDictionaryMatcher({1, 256}) -{ - for (const auto& item : ALL_POKEMON_SPRITES()){ - if (subset == nullptr || subset->find(item.first) != subset->end()){ -// cout << item.first << endl; - add(item.first, item.second.sprite.copy()); - } - } -} -PokemonLeftSpriteMatcherExact::PokemonLeftSpriteMatcherExact(const std::set* subset) - : ExactImageDictionaryMatcher({1, 256}) -{ - for (const auto& item : ALL_POKEMON_SPRITES()){ - if (subset == nullptr || subset->find(item.first) != subset->end()){ -// cout << item.first << endl; - const ImageViewRGB32& sprite = item.second.sprite; - size_t width = sprite.width(); - size_t height = sprite.height(); - add(item.first, sprite.sub_image(0, 0, width/2, height).copy()); - } - } -} - - - - - - -PokemonSpriteMatcherCropped::PokemonSpriteMatcherCropped(const std::set* subset, double min_euclidean_distance) - : CroppedImageDictionaryMatcher({1, 256}) - , m_min_euclidean_distance_squared(min_euclidean_distance * min_euclidean_distance) -{ - for (const auto& item : ALL_POKEMON_SPRITES()){ - if (subset == nullptr || subset->find(item.first) != subset->end()){ -// cout << item.first << endl; - add(item.first, item.second.sprite); - } - } -} - -auto PokemonSpriteMatcherCropped::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ - ImageStats border = image_border_stats(image); -// cout << border.average << border.stddev << endl; -// image.save("image1.png"); - ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( - image, - [&](Color pixel){ -// if (qAlpha(pixel) == 0){ -// return false; -// } -// FloatPixel p(pixel); -// cout << p << endl; - double r = (double)pixel.red() - border.average.r; - double g = (double)pixel.green() - border.average.g; - double b = (double)pixel.blue() - border.average.b; - bool stop = r*r + g*g + b*b >= m_min_euclidean_distance_squared; - if (stop){ -// FloatPixel p(pixel); -// cout << p << " : " << r << " " << g << " " << b << endl; - } - return stop; - } - ); - std::vector ret; - ret.emplace_back(extract_box_reference(image, box)); - return ret; -} - - - - - - - - -} -} -} +/* Pokemon Sprite Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/ImageMatch/ImageCropper.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "PokemonSwSh_PokemonSpriteReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +PokemonSpriteMatcherExact::PokemonSpriteMatcherExact(const std::set* subset) + : ExactImageDictionaryMatcher({1, 256}) +{ + for (const auto& item : ALL_POKEMON_SPRITES()){ + if (subset == nullptr || subset->find(item.first) != subset->end()){ +// cout << item.first << endl; + add(item.first, item.second.sprite.copy()); + } + } +} +PokemonLeftSpriteMatcherExact::PokemonLeftSpriteMatcherExact(const std::set* subset) + : ExactImageDictionaryMatcher({1, 256}) +{ + for (const auto& item : ALL_POKEMON_SPRITES()){ + if (subset == nullptr || subset->find(item.first) != subset->end()){ +// cout << item.first << endl; + const ImageViewRGB32& sprite = item.second.sprite; + size_t width = sprite.width(); + size_t height = sprite.height(); + add(item.first, sprite.sub_image(0, 0, width/2, height).copy()); + } + } +} + + + + + + +PokemonSpriteMatcherCropped::PokemonSpriteMatcherCropped(const std::set* subset, double min_euclidean_distance) + : CroppedImageDictionaryMatcher({1, 256}) + , m_min_euclidean_distance_squared(min_euclidean_distance * min_euclidean_distance) +{ + for (const auto& item : ALL_POKEMON_SPRITES()){ + if (subset == nullptr || subset->find(item.first) != subset->end()){ +// cout << item.first << endl; + add(item.first, item.second.sprite); + } + } +} + +auto PokemonSpriteMatcherCropped::get_crop_candidates(const ImageViewRGB32& image) const -> std::vector{ + ImageStats border = image_border_stats(image); +// cout << border.average << border.stddev << endl; +// image.save("image1.png"); + ImagePixelBox box = ImageMatch::enclosing_rectangle_with_pixel_filter( + image, + [&](Color pixel){ +// if (qAlpha(pixel) == 0){ +// return false; +// } +// FloatPixel p(pixel); +// cout << p << endl; + double r = (double)pixel.red() - border.average.r; + double g = (double)pixel.green() - border.average.g; + double b = (double)pixel.blue() - border.average.b; + bool stop = r*r + g*g + b*b >= m_min_euclidean_distance_squared; + if (stop){ +// FloatPixel p(pixel); +// cout << p << " : " << r << " " << g << " " << b << endl; + } + return stop; + } + ); + std::vector ret; + ret.emplace_back(extract_box_reference(image, box)); + return ret; +} + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h index 74c46dfaed..8c7aed7178 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h @@ -1,50 +1,50 @@ -/* Pokemon Sprite Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_PokemonSpriteReader_H -#define PokemonAutomation_PokemonSwSh_PokemonSpriteReader_H - -#include -#include "CommonTools/ImageMatch/ExactImageDictionaryMatcher.h" -#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class PokemonSpriteMatcherExact : public ImageMatch::ExactImageDictionaryMatcher{ -public: - PokemonSpriteMatcherExact(const std::set* subset); -}; - -// Used by Max Lair when there's an item blocking the right side. -class PokemonLeftSpriteMatcherExact : public ImageMatch::ExactImageDictionaryMatcher{ -public: - PokemonLeftSpriteMatcherExact(const std::set* subset); -}; - - - -class PokemonSpriteMatcherCropped : public ImageMatch::CroppedImageDictionaryMatcher{ -public: - PokemonSpriteMatcherCropped(const std::set* subset, double min_euclidean_distance = 100); - -private: - virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; - -private: - double m_min_euclidean_distance_squared; -}; - - - - - -} -} -} -#endif +/* Pokemon Sprite Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_PokemonSpriteReader_H +#define PokemonAutomation_PokemonSwSh_PokemonSpriteReader_H + +#include +#include "CommonTools/ImageMatch/ExactImageDictionaryMatcher.h" +#include "CommonTools/ImageMatch/CroppedImageDictionaryMatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class PokemonSpriteMatcherExact : public ImageMatch::ExactImageDictionaryMatcher{ +public: + PokemonSpriteMatcherExact(const std::set* subset); +}; + +// Used by Max Lair when there's an item blocking the right side. +class PokemonLeftSpriteMatcherExact : public ImageMatch::ExactImageDictionaryMatcher{ +public: + PokemonLeftSpriteMatcherExact(const std::set* subset); +}; + + + +class PokemonSpriteMatcherCropped : public ImageMatch::CroppedImageDictionaryMatcher{ +public: + PokemonSpriteMatcherCropped(const std::set* subset, double min_euclidean_distance = 100); + +private: + virtual std::vector get_crop_candidates(const ImageViewRGB32& image) const override; + +private: + double m_min_euclidean_distance_squared; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.cpp index eebf35882f..99d02fdf91 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.cpp @@ -1,63 +1,63 @@ -/* Quantity Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/OCR/OCR_NumberReader.h" -#include "PokemonSwSh_QuantityReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -std::string ReadableQuantity999::to_str() const{ - if (unknown){ - return "?"; - } - std::string str = std::to_string(quantity); - if (read_error){ - str += "?"; - } - return str; -} - -void ReadableQuantity999::update_with_ocr( - int16_t new_quantity, - int16_t max_quantity_differential -){ - // Currently a read error. Keep last value. - if (new_quantity < 0){ - read_error = true; - return; - } - - if (unknown){ - unknown = false; - read_error = false; - quantity = new_quantity; - return; - } - - unknown = false; - if (max_quantity_differential < 0){ - read_error = false; - }else{ - read_error = std::abs(quantity - new_quantity) > max_quantity_differential; - } - quantity = new_quantity; -} -void ReadableQuantity999::update_with_ocr( - Logger& logger, const ImageViewRGB32& image, - int16_t max_quantity_differential -){ - return update_with_ocr((int16_t)OCR::read_number(logger, image), max_quantity_differential); -} - - - - -} -} -} +/* Quantity Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/OCR/OCR_NumberReader.h" +#include "PokemonSwSh_QuantityReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +std::string ReadableQuantity999::to_str() const{ + if (unknown){ + return "?"; + } + std::string str = std::to_string(quantity); + if (read_error){ + str += "?"; + } + return str; +} + +void ReadableQuantity999::update_with_ocr( + int16_t new_quantity, + int16_t max_quantity_differential +){ + // Currently a read error. Keep last value. + if (new_quantity < 0){ + read_error = true; + return; + } + + if (unknown){ + unknown = false; + read_error = false; + quantity = new_quantity; + return; + } + + unknown = false; + if (max_quantity_differential < 0){ + read_error = false; + }else{ + read_error = std::abs(quantity - new_quantity) > max_quantity_differential; + } + quantity = new_quantity; +} +void ReadableQuantity999::update_with_ocr( + Logger& logger, const ImageViewRGB32& image, + int16_t max_quantity_differential +){ + return update_with_ocr((int16_t)OCR::read_number(logger, image), max_quantity_differential); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h index 944a85d2ca..75412c9ef6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h @@ -1,43 +1,43 @@ -/* Quantity Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_QuantityReader_H -#define PokemonAutomation_PokemonSwSh_QuantityReader_H - -#include -#include -#include "CommonFramework/Logging/Logger.h" - -namespace PokemonAutomation{ - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -struct ReadableQuantity999{ - bool read_error = false; - bool unknown = true; - uint16_t quantity = 0; - - std::string to_str() const; - - void update_with_ocr( - int16_t new_quantity, - int16_t max_quantity_differential = -1 - ); - void update_with_ocr( - Logger& logger, const ImageViewRGB32& image, - int16_t max_quantity_differential = -1 - ); -}; - - - - -} -} -} -#endif +/* Quantity Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_QuantityReader_H +#define PokemonAutomation_PokemonSwSh_QuantityReader_H + +#include +#include +#include "CommonFramework/Logging/Logger.h" + +namespace PokemonAutomation{ + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +struct ReadableQuantity999{ + bool read_error = false; + bool unknown = true; + uint16_t quantity = 0; + + std::string to_str() const; + + void update_with_ocr( + int16_t new_quantity, + int16_t max_quantity_differential = -1 + ); + void update_with_ocr( + Logger& logger, const ImageViewRGB32& image, + int16_t max_quantity_differential = -1 + ); +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.cpp index 3c8cfc0060..fb4cba847d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.cpp @@ -1,101 +1,101 @@ -/* Receive Pokemon (Orange Background) Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSwSh_ReceivePokemonDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ReceivePokemonDetector::ReceivePokemonDetector(bool stop_on_detected) - : VisualInferenceCallback("ReceivePokemonDetector") - , m_stop_on_detected(stop_on_detected) - , m_box_top(0.2, 0.02, 0.78, 0.02) - , m_box_top_right(0.93, 0.02, 0.05, 0.1) - , m_box_bot_left(0.02, 0.85, 0.1, 0.1) - , m_has_been_orange(false) - , m_triggered(false) -{} -void ReceivePokemonDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box_top); - items.add(COLOR_RED, m_box_top_right); - items.add(COLOR_RED, m_box_bot_left); -} - -bool ReceivePokemonDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool ret = receive_is_over(frame); - bool triggered = m_triggered.load(std::memory_order_acquire); - m_triggered.store(triggered | ret, std::memory_order_release); -// cout << "m_has_been_orange = " << m_has_been_orange << endl; - return ret && m_stop_on_detected; -} -bool ReceivePokemonDetector::receive_is_over(const ImageViewRGB32& frame){ - ImageStats stats0 = image_stats(extract_box_reference(frame, m_box_top)); - ImageStats stats1 = image_stats(extract_box_reference(frame, m_box_top_right)); - ImageStats stats2 = image_stats(extract_box_reference(frame, m_box_bot_left)); - - FloatPixel expected(193, 78, 56); - FloatPixel actual0 = stats0.average; - FloatPixel actual1 = stats1.average; - FloatPixel actual2 = stats2.average; - -// cout << actual0 << actual1 << actual2 << endl; - - if (actual0.sum() < 100){ - return m_has_been_orange; - } - if (actual1.sum() < 100){ - return m_has_been_orange; - } - if (actual2.sum() < 100){ - return m_has_been_orange; - } - - expected /= expected.sum(); - actual0 /= actual0.sum(); - actual1 /= actual1.sum(); - actual2 /= actual2.sum(); - - double distance0 = euclidean_distance(expected, actual0); - double distance1 = euclidean_distance(expected, actual1); - double distance2 = euclidean_distance(expected, actual2); - - if (euclidean_distance(actual0, actual1) > 10){ - return m_has_been_orange; - } - if (euclidean_distance(actual0, actual2) > 10){ - return m_has_been_orange; - } - if (euclidean_distance(actual1, actual2) > 10){ - return m_has_been_orange; - } - if (stats0.stddev.sum() > 10 || distance0 > 0.2){ - return m_has_been_orange; - } - if (stats1.stddev.sum() > 10 || distance1 > 0.2){ - return m_has_been_orange; - } - if (stats2.stddev.sum() > 10 || distance2 > 0.2){ - return m_has_been_orange; - } - - m_has_been_orange = true; - return false; -} - - -} -} -} +/* Receive Pokemon (Orange Background) Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSwSh_ReceivePokemonDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ReceivePokemonDetector::ReceivePokemonDetector(bool stop_on_detected) + : VisualInferenceCallback("ReceivePokemonDetector") + , m_stop_on_detected(stop_on_detected) + , m_box_top(0.2, 0.02, 0.78, 0.02) + , m_box_top_right(0.93, 0.02, 0.05, 0.1) + , m_box_bot_left(0.02, 0.85, 0.1, 0.1) + , m_has_been_orange(false) + , m_triggered(false) +{} +void ReceivePokemonDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box_top); + items.add(COLOR_RED, m_box_top_right); + items.add(COLOR_RED, m_box_bot_left); +} + +bool ReceivePokemonDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool ret = receive_is_over(frame); + bool triggered = m_triggered.load(std::memory_order_acquire); + m_triggered.store(triggered | ret, std::memory_order_release); +// cout << "m_has_been_orange = " << m_has_been_orange << endl; + return ret && m_stop_on_detected; +} +bool ReceivePokemonDetector::receive_is_over(const ImageViewRGB32& frame){ + ImageStats stats0 = image_stats(extract_box_reference(frame, m_box_top)); + ImageStats stats1 = image_stats(extract_box_reference(frame, m_box_top_right)); + ImageStats stats2 = image_stats(extract_box_reference(frame, m_box_bot_left)); + + FloatPixel expected(193, 78, 56); + FloatPixel actual0 = stats0.average; + FloatPixel actual1 = stats1.average; + FloatPixel actual2 = stats2.average; + +// cout << actual0 << actual1 << actual2 << endl; + + if (actual0.sum() < 100){ + return m_has_been_orange; + } + if (actual1.sum() < 100){ + return m_has_been_orange; + } + if (actual2.sum() < 100){ + return m_has_been_orange; + } + + expected /= expected.sum(); + actual0 /= actual0.sum(); + actual1 /= actual1.sum(); + actual2 /= actual2.sum(); + + double distance0 = euclidean_distance(expected, actual0); + double distance1 = euclidean_distance(expected, actual1); + double distance2 = euclidean_distance(expected, actual2); + + if (euclidean_distance(actual0, actual1) > 10){ + return m_has_been_orange; + } + if (euclidean_distance(actual0, actual2) > 10){ + return m_has_been_orange; + } + if (euclidean_distance(actual1, actual2) > 10){ + return m_has_been_orange; + } + if (stats0.stddev.sum() > 10 || distance0 > 0.2){ + return m_has_been_orange; + } + if (stats1.stddev.sum() > 10 || distance1 > 0.2){ + return m_has_been_orange; + } + if (stats2.stddev.sum() > 10 || distance2 > 0.2){ + return m_has_been_orange; + } + + m_has_been_orange = true; + return false; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h index c409c8ccba..e7c37b4f97 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h @@ -1,47 +1,47 @@ -/* Receive Pokemon (Orange Background) Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Returns true after a orange background has been detected - * and has ended. - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ReceivePokemonDetector_H -#define PokemonAutomation_PokemonSwSh_ReceivePokemonDetector_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ReceivePokemonDetector : public VisualInferenceCallback{ -public: - ReceivePokemonDetector(bool stop_on_detected); - - bool triggered() const{ return m_triggered.load(std::memory_order_acquire); } - bool receive_is_over(const ImageViewRGB32& frame); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - bool m_stop_on_detected; - ImageFloatBox m_box_top; - ImageFloatBox m_box_top_right; - ImageFloatBox m_box_bot_left; - bool m_has_been_orange; - - std::atomic m_triggered; -}; - - -} -} -} -#endif +/* Receive Pokemon (Orange Background) Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Returns true after a orange background has been detected + * and has ended. + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ReceivePokemonDetector_H +#define PokemonAutomation_PokemonSwSh_ReceivePokemonDetector_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ReceivePokemonDetector : public VisualInferenceCallback{ +public: + ReceivePokemonDetector(bool stop_on_detected); + + bool triggered() const{ return m_triggered.load(std::memory_order_acquire); } + bool receive_is_over(const ImageViewRGB32& frame); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + bool m_stop_on_detected; + ImageFloatBox m_box_top; + ImageFloatBox m_box_top_right; + ImageFloatBox m_box_bot_left; + bool m_has_been_orange; + + std::atomic m_triggered; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.cpp index feb49d4055..3893429778 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.cpp @@ -1,218 +1,218 @@ -/* In-Battle Arrow Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "PokemonSwSh_SelectionArrowFinder.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const ImageMatch::ExactImageMatcher& SELECTION_ARROW(){ - static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSwSh/BattleArrow.png"); - return matcher; -} - -bool is_selection_arrow(const ImageViewRGB32& image, const WaterfillObject& object){ - double area_ratio = (double)object.area_ratio(); - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "Object area: " << object.area << ", area ratio: " << area_ratio - << " bound [0.4, 0.5]" << std::endl; - dump_debug_image(global_logger_command_line(), "PokemonSwSh/SelectionArrowFinder", "is_selection_arrow", extract_box_reference(image, object)); - } - if (area_ratio < 0.4 || area_ratio > 0.5){ - return false; - } - - ImageRGB32 cropped = extract_box_reference(image, object).copy(); - auto packed_matrix = object.packed_matrix(); - size_t matrix_width = packed_matrix->width(); - size_t matrix_height = packed_matrix->height(); - try{ - filter_by_mask( - std::move(packed_matrix), - cropped, - COLOR_WHITE, - true - ); - }catch (InternalProgramError&){ - global_logger_tagged().log( - "Mismatching matrix and image size.\n" - " Image: " + std::to_string(image.width()) + "x" + std::to_string(image.height()) + - " Cropped: " + std::to_string(cropped.width()) + "x" + std::to_string(cropped.height()) + - " Matrix: " + std::to_string(matrix_width) + "x" + std::to_string(matrix_height) + - " Object: " + std::to_string(object.width()) + "x" + std::to_string(object.height()) + - " Object X: " + std::to_string(object.min_x) + "-" + std::to_string(object.max_x) + - " Object Y: " + std::to_string(object.min_y) + "-" + std::to_string(object.max_y), - COLOR_RED - ); - dump_image(global_logger_tagged(), ProgramInfo(), "is_selection_arrow_size_mismatch", image); - throw; - } - - - double rmsd = SELECTION_ARROW().rmsd(cropped); - - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "rmsd: " << rmsd << ", threshold 130" << std::endl; - } - return rmsd <= 130; -} -std::vector find_selection_arrows(const ImageViewRGB32& image, size_t min_area){ - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "Match SwSh selection arrow by waterfill, size range (" << min_area << ", SIZE_MAX) " - << "input image size " << image.width() << " x " << image.height() << std::endl; - } - PackedBinaryMatrix matrix = compress_rgb32_to_binary_max(image, 63, 63, 63); - auto session = make_WaterfillSession(matrix); - auto finder = session->make_iterator(min_area); - std::vector ret; - WaterfillObject object; - while (finder->find_next(object, true)){ - if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ - std::cout << "Found object: " << object.min_x << "-" << object.max_x << ", " << object.min_y << "-" << object.max_y << std::endl; - } - if (is_selection_arrow(image, object)){ - ret.emplace_back(object); - } - } - return ret; -} - - - -SelectionArrowFinder::SelectionArrowFinder(VideoOverlay& overlay, const ImageFloatBox& box) - : VisualInferenceCallback("SelectionArrowFinder") - , m_overlay(overlay) - , m_box(box) -{} -void SelectionArrowFinder::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_YELLOW, m_box); -} -bool SelectionArrowFinder::detect(const ImageViewRGB32& screen){ - const double screen_scale = screen.height() / 1080.0; - // Smallest arrow takes at least 600 pixels on 1920x1080 screen. - const size_t min_arrow_area = size_t(600.0 * screen_scale * screen_scale); - std::vector arrows = find_selection_arrows( - extract_box_reference(screen, m_box), min_arrow_area); - - m_arrow_boxes.clear(); - for (const ImagePixelBox& mark : arrows){ - m_arrow_boxes.emplace_back(m_overlay, translate_to_parent(screen, m_box, mark), COLOR_MAGENTA); - } - return !m_arrow_boxes.empty(); -} -bool SelectionArrowFinder::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - detect(frame); -// cout << m_arrow_boxes.size() << endl; - return !m_arrow_boxes.empty(); -} - - - -BattleMoveArrowFinder::BattleMoveArrowFinder(VideoOverlay& overlay) - : SelectionArrowFinder(overlay, ImageFloatBox(0.640, 0.600, 0.055, 0.380)) - , m_arrow_slot(-1) -{} - -int8_t BattleMoveArrowFinder::get_slot(){ - return m_arrow_slot.load(std::memory_order_acquire); -} -int8_t BattleMoveArrowFinder::detect(const ImageViewRGB32& screen){ - SelectionArrowFinder::detect(screen); - - if (m_arrow_boxes.empty()){ - return -1; - } - - const ImageFloatBox& arrow = m_arrow_boxes[0]; - double arrow_y_center = arrow.y + arrow.height * 0.5; - - int8_t slot = arrow_slot(arrow_y_center); - m_arrow_slot.store(slot, std::memory_order_release); - return slot; -} -bool BattleMoveArrowFinder::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - detect(frame); - return false; -} - -int8_t BattleMoveArrowFinder::arrow_slot(double y_center){ - if (y_center < 0){ - return -1; - } - y_center -= 0.647222; - y_center /= 0.0962963; - return (int8_t)(y_center + 0.5); -} - - - -RetrieveEggArrowFinder::RetrieveEggArrowFinder(VideoOverlay& overlay) - : SelectionArrowFinder(overlay, ImageFloatBox(0.597, 0.640, 0.166, 0.071)) -{} - - -CheckNurseryArrowFinder::CheckNurseryArrowFinder(VideoOverlay& overlay) - : SelectionArrowFinder(overlay, ImageFloatBox(0.419, 0.570, 0.290, 0.084)) -{} - - -StoragePokemonMenuArrowFinder::StoragePokemonMenuArrowFinder(VideoOverlay& overlay) - : SelectionArrowFinder(overlay, ImageFloatBox(0.555, 0.413, 0.177, 0.078)) -{} - - -RotomPhoneMenuArrowFinder::RotomPhoneMenuArrowFinder(VideoOverlay& overlay) - : m_overlay_set(overlay) -{ - for(size_t i_row = 0; i_row < 2; i_row++){ - for(size_t j_col = 0; j_col < 5; j_col++){ - ImageFloatBox box(0.047 + j_col*0.183, 0.175 + 0.333*i_row, 0.059, 0.104); - m_overlay_set.add(COLOR_YELLOW, box); - } - } -} - -int RotomPhoneMenuArrowFinder::detect(const ImageViewRGB32& screen){ - const double screen_scale = screen.height() / 1080.0; - const size_t min_arrow_area = size_t(1400 * screen_scale * screen_scale); - for (size_t i_row = 0; i_row < 2; i_row++){ - for (size_t j_col = 0; j_col < 5; j_col++){ - ImageFloatBox box(0.047 + j_col*0.183, 0.175 + 0.333*i_row, 0.059, 0.104); - std::vector arrows = find_selection_arrows( - extract_box_reference(screen, box), min_arrow_area); - if (arrows.size() > 0){ - return (int)(i_row * 5 + j_col); - } - } - } - return -1; -} - -} -} -} +/* In-Battle Arrow Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "PokemonSwSh_SelectionArrowFinder.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const ImageMatch::ExactImageMatcher& SELECTION_ARROW(){ + static ImageMatch::ExactImageMatcher matcher(RESOURCE_PATH() + "PokemonSwSh/BattleArrow.png"); + return matcher; +} + +bool is_selection_arrow(const ImageViewRGB32& image, const WaterfillObject& object){ + double area_ratio = (double)object.area_ratio(); + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "Object area: " << object.area << ", area ratio: " << area_ratio + << " bound [0.4, 0.5]" << std::endl; + dump_debug_image(global_logger_command_line(), "PokemonSwSh/SelectionArrowFinder", "is_selection_arrow", extract_box_reference(image, object)); + } + if (area_ratio < 0.4 || area_ratio > 0.5){ + return false; + } + + ImageRGB32 cropped = extract_box_reference(image, object).copy(); + auto packed_matrix = object.packed_matrix(); + size_t matrix_width = packed_matrix->width(); + size_t matrix_height = packed_matrix->height(); + try{ + filter_by_mask( + std::move(packed_matrix), + cropped, + COLOR_WHITE, + true + ); + }catch (InternalProgramError&){ + global_logger_tagged().log( + "Mismatching matrix and image size.\n" + " Image: " + std::to_string(image.width()) + "x" + std::to_string(image.height()) + + " Cropped: " + std::to_string(cropped.width()) + "x" + std::to_string(cropped.height()) + + " Matrix: " + std::to_string(matrix_width) + "x" + std::to_string(matrix_height) + + " Object: " + std::to_string(object.width()) + "x" + std::to_string(object.height()) + + " Object X: " + std::to_string(object.min_x) + "-" + std::to_string(object.max_x) + + " Object Y: " + std::to_string(object.min_y) + "-" + std::to_string(object.max_y), + COLOR_RED + ); + dump_image(global_logger_tagged(), ProgramInfo(), "is_selection_arrow_size_mismatch", image); + throw; + } + + + double rmsd = SELECTION_ARROW().rmsd(cropped); + + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "rmsd: " << rmsd << ", threshold 130" << std::endl; + } + return rmsd <= 130; +} +std::vector find_selection_arrows(const ImageViewRGB32& image, size_t min_area){ + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "Match SwSh selection arrow by waterfill, size range (" << min_area << ", SIZE_MAX) " + << "input image size " << image.width() << " x " << image.height() << std::endl; + } + PackedBinaryMatrix matrix = compress_rgb32_to_binary_max(image, 63, 63, 63); + auto session = make_WaterfillSession(matrix); + auto finder = session->make_iterator(min_area); + std::vector ret; + WaterfillObject object; + while (finder->find_next(object, true)){ + if (PreloadSettings::debug().IMAGE_TEMPLATE_MATCHING){ + std::cout << "Found object: " << object.min_x << "-" << object.max_x << ", " << object.min_y << "-" << object.max_y << std::endl; + } + if (is_selection_arrow(image, object)){ + ret.emplace_back(object); + } + } + return ret; +} + + + +SelectionArrowFinder::SelectionArrowFinder(VideoOverlay& overlay, const ImageFloatBox& box) + : VisualInferenceCallback("SelectionArrowFinder") + , m_overlay(overlay) + , m_box(box) +{} +void SelectionArrowFinder::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_YELLOW, m_box); +} +bool SelectionArrowFinder::detect(const ImageViewRGB32& screen){ + const double screen_scale = screen.height() / 1080.0; + // Smallest arrow takes at least 600 pixels on 1920x1080 screen. + const size_t min_arrow_area = size_t(600.0 * screen_scale * screen_scale); + std::vector arrows = find_selection_arrows( + extract_box_reference(screen, m_box), min_arrow_area); + + m_arrow_boxes.clear(); + for (const ImagePixelBox& mark : arrows){ + m_arrow_boxes.emplace_back(m_overlay, translate_to_parent(screen, m_box, mark), COLOR_MAGENTA); + } + return !m_arrow_boxes.empty(); +} +bool SelectionArrowFinder::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + detect(frame); +// cout << m_arrow_boxes.size() << endl; + return !m_arrow_boxes.empty(); +} + + + +BattleMoveArrowFinder::BattleMoveArrowFinder(VideoOverlay& overlay) + : SelectionArrowFinder(overlay, ImageFloatBox(0.640, 0.600, 0.055, 0.380)) + , m_arrow_slot(-1) +{} + +int8_t BattleMoveArrowFinder::get_slot(){ + return m_arrow_slot.load(std::memory_order_acquire); +} +int8_t BattleMoveArrowFinder::detect(const ImageViewRGB32& screen){ + SelectionArrowFinder::detect(screen); + + if (m_arrow_boxes.empty()){ + return -1; + } + + const ImageFloatBox& arrow = m_arrow_boxes[0]; + double arrow_y_center = arrow.y + arrow.height * 0.5; + + int8_t slot = arrow_slot(arrow_y_center); + m_arrow_slot.store(slot, std::memory_order_release); + return slot; +} +bool BattleMoveArrowFinder::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + detect(frame); + return false; +} + +int8_t BattleMoveArrowFinder::arrow_slot(double y_center){ + if (y_center < 0){ + return -1; + } + y_center -= 0.647222; + y_center /= 0.0962963; + return (int8_t)(y_center + 0.5); +} + + + +RetrieveEggArrowFinder::RetrieveEggArrowFinder(VideoOverlay& overlay) + : SelectionArrowFinder(overlay, ImageFloatBox(0.597, 0.640, 0.166, 0.071)) +{} + + +CheckNurseryArrowFinder::CheckNurseryArrowFinder(VideoOverlay& overlay) + : SelectionArrowFinder(overlay, ImageFloatBox(0.419, 0.570, 0.290, 0.084)) +{} + + +StoragePokemonMenuArrowFinder::StoragePokemonMenuArrowFinder(VideoOverlay& overlay) + : SelectionArrowFinder(overlay, ImageFloatBox(0.555, 0.413, 0.177, 0.078)) +{} + + +RotomPhoneMenuArrowFinder::RotomPhoneMenuArrowFinder(VideoOverlay& overlay) + : m_overlay_set(overlay) +{ + for(size_t i_row = 0; i_row < 2; i_row++){ + for(size_t j_col = 0; j_col < 5; j_col++){ + ImageFloatBox box(0.047 + j_col*0.183, 0.175 + 0.333*i_row, 0.059, 0.104); + m_overlay_set.add(COLOR_YELLOW, box); + } + } +} + +int RotomPhoneMenuArrowFinder::detect(const ImageViewRGB32& screen){ + const double screen_scale = screen.height() / 1080.0; + const size_t min_arrow_area = size_t(1400 * screen_scale * screen_scale); + for (size_t i_row = 0; i_row < 2; i_row++){ + for (size_t j_col = 0; j_col < 5; j_col++){ + ImageFloatBox box(0.047 + j_col*0.183, 0.175 + 0.333*i_row, 0.059, 0.104); + std::vector arrows = find_selection_arrows( + extract_box_reference(screen, box), min_arrow_area); + if (arrows.size() > 0){ + return (int)(i_row * 5 + j_col); + } + } + } + return -1; +} + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h index 9d6eb94115..90fe768057 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h @@ -1,97 +1,97 @@ -/* Selection Arrow Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SelectionArrowFinder_H -#define PokemonAutomation_PokemonSwSh_SelectionArrowFinder_H - -#include -#include -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class SelectionArrowFinder : public VisualInferenceCallback{ -public: - SelectionArrowFinder(VideoOverlay& overlay, const ImageFloatBox& box); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -protected: - VideoOverlay& m_overlay; - ImageFloatBox m_box; - std::deque m_arrow_boxes; -}; - - - -class BattleMoveArrowFinder : public SelectionArrowFinder{ -public: - BattleMoveArrowFinder(VideoOverlay& overlay); - - int8_t get_slot(); - - // These are not thread safe. - int8_t detect(const ImageViewRGB32& screen); - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - - -private: - int8_t arrow_slot(double y_center); - - -private: - std::atomic m_arrow_slot; -}; - - -// Selection arrow for the dialog of the egg lady when you would like to retrieve an egg. -class RetrieveEggArrowFinder : public SelectionArrowFinder{ -public: - RetrieveEggArrowFinder(VideoOverlay& overlay); -}; - - -// Selection arrow for the dialog of the egg lady when you check the condition of the pokemon -// in the Pokemon Nursery, where there is no egg. -class CheckNurseryArrowFinder : public SelectionArrowFinder{ -public: - CheckNurseryArrowFinder(VideoOverlay& overlay); -}; - - -// Selection arrow for the menu of the pokemon in a pokemon storage box. -// The menuitems are: "Move", "Check summary", "Check held item", "Change markings", ... -class StoragePokemonMenuArrowFinder : public SelectionArrowFinder{ -public: - StoragePokemonMenuArrowFinder(VideoOverlay& overlay); -}; - -// The arrow that points to one of the ten apps on Rotom Phone menu -class RotomPhoneMenuArrowFinder{ -public: - RotomPhoneMenuArrowFinder(VideoOverlay& overlay); - - // Detect which app is selected by the arrow. Return the index of the app - // The order is: from top to bottom, from left to right. - // If no arrow found, return -1. - int detect(const ImageViewRGB32& screen); - -private: - VideoOverlaySet m_overlay_set; -}; - - -} -} -} -#endif +/* Selection Arrow Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SelectionArrowFinder_H +#define PokemonAutomation_PokemonSwSh_SelectionArrowFinder_H + +#include +#include +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class SelectionArrowFinder : public VisualInferenceCallback{ +public: + SelectionArrowFinder(VideoOverlay& overlay, const ImageFloatBox& box); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +protected: + VideoOverlay& m_overlay; + ImageFloatBox m_box; + std::deque m_arrow_boxes; +}; + + + +class BattleMoveArrowFinder : public SelectionArrowFinder{ +public: + BattleMoveArrowFinder(VideoOverlay& overlay); + + int8_t get_slot(); + + // These are not thread safe. + int8_t detect(const ImageViewRGB32& screen); + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + + +private: + int8_t arrow_slot(double y_center); + + +private: + std::atomic m_arrow_slot; +}; + + +// Selection arrow for the dialog of the egg lady when you would like to retrieve an egg. +class RetrieveEggArrowFinder : public SelectionArrowFinder{ +public: + RetrieveEggArrowFinder(VideoOverlay& overlay); +}; + + +// Selection arrow for the dialog of the egg lady when you check the condition of the pokemon +// in the Pokemon Nursery, where there is no egg. +class CheckNurseryArrowFinder : public SelectionArrowFinder{ +public: + CheckNurseryArrowFinder(VideoOverlay& overlay); +}; + + +// Selection arrow for the menu of the pokemon in a pokemon storage box. +// The menuitems are: "Move", "Check summary", "Check held item", "Change markings", ... +class StoragePokemonMenuArrowFinder : public SelectionArrowFinder{ +public: + StoragePokemonMenuArrowFinder(VideoOverlay& overlay); +}; + +// The arrow that points to one of the ten apps on Rotom Phone menu +class RotomPhoneMenuArrowFinder{ +public: + RotomPhoneMenuArrowFinder(VideoOverlay& overlay); + + // Detect which app is selected by the arrow. Return the index of the app + // The order is: from top to bottom, from left to right. + // If no arrow found, return -1. + int detect(const ImageViewRGB32& screen); + +private: + VideoOverlaySet m_overlay_set; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.cpp index f3807c0639..af15b33627 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.cpp @@ -1,110 +1,110 @@ -/* Summary Shiny Symbol - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/ColorClustering.h" -#include "CommonTools/InferenceThrottler.h" -#include "PokemonSwSh_SummaryShinySymbolDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -SummaryShinySymbolDetector::SummaryShinySymbolDetector(Logger& logger, VideoOverlay& overlay) - : m_logger(logger) - , m_state0_box(overlay, {0.02, 0.84, 0.1, 0.1}) - , m_state1_box(overlay, {0.02, 0.97, 0.5, 0.02}) - , m_symbol_box(overlay, {0.08, 0.53, 0.02, 0.05}) -{} - -SummaryShinySymbolDetector::Detection SummaryShinySymbolDetector::detect(const ImageViewRGB32& screen){ - { - ImageStats stats = image_stats(extract_box_reference(screen, m_state1_box)); - if (!is_black(stats)){ - return Detection::NO_DETECTION; - } - } - { - ImageStats stats = image_stats(extract_box_reference(screen, m_state0_box)); - if (!is_solid(stats, {0.70, 0.07, 0.23}, 0.2, 10)){ - return Detection::NO_DETECTION; - } - } - - ImageViewRGB32 symbol = extract_box_reference(screen, m_symbol_box); - if (cluster_fit_2( - symbol, - Color(255, 255, 255), 0.84, - Color(156, 33, 80), 0.16, - 0.1 - )){ -// symbol.save("test.png"); - return Detection::SHINY; - } - if (cluster_fit_2( - symbol, - Color(255, 255, 255), 0.92, - Color(0, 0, 0), 0.08, - 0.1 - )){ - return Detection::NOT_SHINY; - } - - return Detection::NO_DETECTION; -} -SummaryShinySymbolDetector::Detection SummaryShinySymbolDetector::wait_for_detection( - CancellableScope& scope, VideoFeed& feed, - std::chrono::seconds timeout -){ - Detection last_detection = Detection::NO_DETECTION; - size_t confirmations = 0; - - InferenceThrottler throttler(timeout); - while (true){ - scope.throw_if_cancelled(); - - Detection detection = detect(feed.snapshot()); - if (detection == last_detection){ - confirmations++; - }else{ - last_detection = detection; - confirmations = 0; - } - if (last_detection != Detection::NO_DETECTION && confirmations >= 10){ - break; - } - - if (throttler.end_iteration(scope)){ - last_detection = Detection::NO_DETECTION; - break; - } - } - - switch (last_detection){ - case Detection::NO_DETECTION: - m_logger.log("SummaryShinySymbolDetector: Nothing found after timeout.", COLOR_RED); - break; - case Detection::NOT_SHINY: - m_logger.log("SummaryShinySymbolDetector: Not shiny.", COLOR_PURPLE); - break; - case Detection::SHINY: - m_logger.log("SummaryShinySymbolDetector: Shiny!", COLOR_BLUE); - break; - } - return last_detection; -} - - - -} -} -} +/* Summary Shiny Symbol + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/ColorClustering.h" +#include "CommonTools/InferenceThrottler.h" +#include "PokemonSwSh_SummaryShinySymbolDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +SummaryShinySymbolDetector::SummaryShinySymbolDetector(Logger& logger, VideoOverlay& overlay) + : m_logger(logger) + , m_state0_box(overlay, {0.02, 0.84, 0.1, 0.1}) + , m_state1_box(overlay, {0.02, 0.97, 0.5, 0.02}) + , m_symbol_box(overlay, {0.08, 0.53, 0.02, 0.05}) +{} + +SummaryShinySymbolDetector::Detection SummaryShinySymbolDetector::detect(const ImageViewRGB32& screen){ + { + ImageStats stats = image_stats(extract_box_reference(screen, m_state1_box)); + if (!is_black(stats)){ + return Detection::NO_DETECTION; + } + } + { + ImageStats stats = image_stats(extract_box_reference(screen, m_state0_box)); + if (!is_solid(stats, {0.70, 0.07, 0.23}, 0.2, 10)){ + return Detection::NO_DETECTION; + } + } + + ImageViewRGB32 symbol = extract_box_reference(screen, m_symbol_box); + if (cluster_fit_2( + symbol, + Color(255, 255, 255), 0.84, + Color(156, 33, 80), 0.16, + 0.1 + )){ +// symbol.save("test.png"); + return Detection::SHINY; + } + if (cluster_fit_2( + symbol, + Color(255, 255, 255), 0.92, + Color(0, 0, 0), 0.08, + 0.1 + )){ + return Detection::NOT_SHINY; + } + + return Detection::NO_DETECTION; +} +SummaryShinySymbolDetector::Detection SummaryShinySymbolDetector::wait_for_detection( + CancellableScope& scope, VideoFeed& feed, + std::chrono::seconds timeout +){ + Detection last_detection = Detection::NO_DETECTION; + size_t confirmations = 0; + + InferenceThrottler throttler(timeout); + while (true){ + scope.throw_if_cancelled(); + + Detection detection = detect(feed.snapshot()); + if (detection == last_detection){ + confirmations++; + }else{ + last_detection = detection; + confirmations = 0; + } + if (last_detection != Detection::NO_DETECTION && confirmations >= 10){ + break; + } + + if (throttler.end_iteration(scope)){ + last_detection = Detection::NO_DETECTION; + break; + } + } + + switch (last_detection){ + case Detection::NO_DETECTION: + m_logger.log("SummaryShinySymbolDetector: Nothing found after timeout.", COLOR_RED); + break; + case Detection::NOT_SHINY: + m_logger.log("SummaryShinySymbolDetector: Not shiny.", COLOR_PURPLE); + break; + case Detection::SHINY: + m_logger.log("SummaryShinySymbolDetector: Shiny!", COLOR_BLUE); + break; + } + return last_detection; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h index a6c2ba0c9b..e8a2fd8cb6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h @@ -1,55 +1,55 @@ -/* Summary Shiny Symbol - * - * From: https://github.com/PokemonAutomation/ - * - * - * Check shiny symbol in the party pokemon info screen. - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SummaryShinySymbolDetector_H -#define PokemonAutomation_PokemonSwSh_SummaryShinySymbolDetector_H - -#include -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" - -namespace PokemonAutomation{ - class CancellableScope; - class VideoFeed; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class SummaryShinySymbolDetector{ -public: - enum Detection{ - NO_DETECTION, - NOT_SHINY, - SHINY, - }; - -public: - SummaryShinySymbolDetector(Logger& logger, VideoOverlay& overlay); - - Detection detect(const ImageViewRGB32& screen); - Detection wait_for_detection( - CancellableScope& scope, VideoFeed& feed, - std::chrono::seconds timeout = std::chrono::seconds(10) - ); - -private: - Logger& m_logger; - OverlayBoxScope m_state0_box; - OverlayBoxScope m_state1_box; - OverlayBoxScope m_symbol_box; -}; - - - -} -} -} - -#endif - +/* Summary Shiny Symbol + * + * From: https://github.com/PokemonAutomation/ + * + * + * Check shiny symbol in the party pokemon info screen. + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SummaryShinySymbolDetector_H +#define PokemonAutomation_PokemonSwSh_SummaryShinySymbolDetector_H + +#include +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" + +namespace PokemonAutomation{ + class CancellableScope; + class VideoFeed; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class SummaryShinySymbolDetector{ +public: + enum Detection{ + NO_DETECTION, + NOT_SHINY, + SHINY, + }; + +public: + SummaryShinySymbolDetector(Logger& logger, VideoOverlay& overlay); + + Detection detect(const ImageViewRGB32& screen); + Detection wait_for_detection( + CancellableScope& scope, VideoFeed& feed, + std::chrono::seconds timeout = std::chrono::seconds(10) + ); + +private: + Logger& m_logger; + OverlayBoxScope m_state0_box; + OverlayBoxScope m_state1_box; + OverlayBoxScope m_symbol_box; +}; + + + +} +} +} + +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.cpp index 51d27250a3..08339ef4a8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.cpp @@ -1,270 +1,270 @@ -/* Type Symbol Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/CancellableScope.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonSwSh_TypeSymbolFinder.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - - -size_t distance_sqr(const ImagePixelBox& a, const ImagePixelBox& b){ - bool overlap_x = a.min_x <= b.max_x && b.min_x <= a.max_x; - bool overlap_y = a.min_y <= b.max_y && b.min_y <= a.max_y; - if (overlap_x && overlap_y){ - return 0; - } - - size_t dist_x = 0; - if (!overlap_x){ - dist_x = a.max_x < b.min_x - ? b.min_x - a.max_x - : a.min_x - b.max_x; - } - - size_t dist_y = 0; - if (!overlap_y){ - dist_y = a.max_y < b.min_y - ? b.min_y - a.max_y - : a.min_y - b.max_y; - } - - return dist_x*dist_x + dist_y*dist_y; -} - - -std::pair match_type_symbol(const ImageViewRGB32& image){ - size_t width = image.width(); - size_t height = image.height(); - if (width * height < 100){ - return {1.0, PokemonType::NONE}; - } - if (width > 2 * height){ - return {1.0, PokemonType::NONE}; - } - if (height > 2 * width){ - return {1.0, PokemonType::NONE}; - } - ImageStats stats = image_stats(image); - if (stats.stddev.sum() < 50){ - return {1.0, PokemonType::NONE}; - } - -// static int c = 0; -// image.save("test-" + std::to_string(threshold) + "-" + std::to_string(c++) + ".png"); - -// std::map rank; - double best_score = 0.4; - PokemonType best_type = PokemonType::NONE; - for (const auto& item : all_type_sprites()){ -// if (threshold != 700 || id != 55){ -// continue; -// } - double rmsd_alpha = item.second.matcher().diff(image); - -// item.second.matcher().m_image.save("sprite.png"); -// cout << item.second.slug() << ": " << rmsd_alpha << endl; - -#if 0 - // Handicap fairy due to white and pink being too similar in color and - // false positiving on the background. - if (item.first == PokemonType::FAIRY){ - rmsd_ratio *= 1.5; - } - - // Bonus for dark because or large contrast. - if (item.first == PokemonType::DARK){ - rmsd_ratio *= 0.8; - } -#endif - - if (best_score > rmsd_alpha){ - best_score = rmsd_alpha; - best_type = item.first; -// cout << item.second.slug() << ": " << stats.stddev << endl; - } - } - -// if (best_type != PokemonType::NONE){ -// cout << get_type_slug(best_type) << ": " << best_score << endl; -// } - return {best_score, best_type}; -} - -void find_symbol_candidates( - std::multimap>& candidates, - const ImageViewRGB32& image, - PackedBinaryMatrix& matrix, double max_area_ratio -){ - size_t max_area = (size_t)(image.width() * image.height() * max_area_ratio); - std::vector objects = find_objects_inplace(matrix, 20); - -// static int index = 0; - - std::map objmap; - for (size_t c = 0; c < objects.size(); c++){ - if (objects[c].area > max_area){ - continue; - } - objmap[c] = objects[c]; - -// image.copy( -// objects[c].min_x, objects[c].min_y, objects[c].width(), objects[c].height() -// ).save("test-" + std::to_string(index++) + ".png"); - } - -// cout << "begin = " << objmap.size() << endl; - - // Merge nearby objects. - bool changed; - do{ - changed = false; - for (auto iter0 = objmap.begin(); iter0 != objmap.end(); ++iter0){ - for (auto iter1 = objmap.begin(); iter1 != objmap.end();){ - if (iter0->first >= iter1->first){ - ++iter1; - continue; - } - const WaterfillObject& obj0 = iter0->second; - const WaterfillObject& obj1 = iter1->second; - size_t distance = distance_sqr( - ImagePixelBox(obj0.min_x, obj0.min_y, obj0.max_x, obj0.max_y), - ImagePixelBox(obj1.min_x, obj1.min_y, obj1.max_x, obj1.max_y) - ); - if (distance < 5*5){ - iter0->second.merge_assume_no_overlap(iter1->second); - iter1 = objmap.erase(iter1); - changed = true; - }else{ - ++iter1; - } - } - } - }while (changed); - -// cout << "merged = " << objmap.size() << endl; - - // Identify objects. - for (const auto& item : objmap){ - ImageViewRGB32 img = extract_box_reference(image, item.second); - std::pair result = match_type_symbol(img); - if (result.second != PokemonType::NONE){ - const WaterfillObject& obj = item.second; - candidates.emplace( - result.first, - std::pair( - result.second, - ImagePixelBox(obj.min_x, obj.min_y, obj.max_x, obj.max_y) - ) - ); - } - } - -// cout << "candidates = " << candidates.size() << endl; -} - - - -std::multimap> find_symbols( - const ImageViewRGB32& image, double max_area_ratio -){ - std::multimap> candidates; - - { - std::vector matrices = compress_rgb32_to_binary_range( - image, - { - {0xff909090, 0xffffffff}, - {0xffa0a0a0, 0xffffffff}, - {0xffb0b0b0, 0xffffffff}, - {0xffc0c0c0, 0xffffffff}, - {0xffd0d0d0, 0xffffffff}, - {0xffe0e0e0, 0xffffffff}, - } - ); - for (PackedBinaryMatrix& matrix : matrices){ - find_symbol_candidates(candidates, image, matrix, max_area_ratio); - } - } - - std::multimap> filtered; - for (const auto& candidate : candidates){ -// cout << get_type_slug(candidate.second.first) << ": " << candidate.first << endl; -// hits.emplace_back(overlay, translate_to_parent(screen, box, candidate.second.second.box), COLOR_GREEN); - - bool is_dupe = false; - for (const auto& item : filtered){ - if (distance_sqr(candidate.second.second, item.second.second) == 0){ - is_dupe = true; - break; - } - } - if (!is_dupe){ - filtered.emplace(candidate); - } - } - -#if 0 - for (const auto& item : filtered){ -// cout << get_type_slug(item.second.first) << ": " << item.first << " - [" << item.second.second.center_x() << "," << item.second.second.center_y() << "]" << endl; - const ImagePixelBox& box = item.second.second; - ImageViewRGB32 img = image.sub_image( - box.min_x, box.min_y, - box.width(), box.height() - ); -// img.save("test-" + std::to_string(c++) + ".png"); - } -#endif - - return filtered; -} - - - - - -void test_find_symbols( - CancellableScope& scope, - VideoOverlay& overlay, - const ImageFloatBox& box, - const ImageViewRGB32& screen, double max_area_ratio -){ - ImageViewRGB32 image = extract_box_reference(screen, box); - - std::multimap> candidates = find_symbols(image, max_area_ratio); - - - std::deque hits; -// hits.clear(); - cout << "---------------" << endl; - for (const auto& item : candidates){ - cout << POKEMON_TYPE_SLUGS().get_string(item.second.first) << ": " << item.first << endl; - hits.emplace_back(overlay, translate_to_parent(screen, box, item.second.second), COLOR_GREEN); - } - - scope.wait_for(std::chrono::seconds(10)); -} - - - - - -} -} -} +/* Type Symbol Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/CancellableScope.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonSwSh_TypeSymbolFinder.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + + +size_t distance_sqr(const ImagePixelBox& a, const ImagePixelBox& b){ + bool overlap_x = a.min_x <= b.max_x && b.min_x <= a.max_x; + bool overlap_y = a.min_y <= b.max_y && b.min_y <= a.max_y; + if (overlap_x && overlap_y){ + return 0; + } + + size_t dist_x = 0; + if (!overlap_x){ + dist_x = a.max_x < b.min_x + ? b.min_x - a.max_x + : a.min_x - b.max_x; + } + + size_t dist_y = 0; + if (!overlap_y){ + dist_y = a.max_y < b.min_y + ? b.min_y - a.max_y + : a.min_y - b.max_y; + } + + return dist_x*dist_x + dist_y*dist_y; +} + + +std::pair match_type_symbol(const ImageViewRGB32& image){ + size_t width = image.width(); + size_t height = image.height(); + if (width * height < 100){ + return {1.0, PokemonType::NONE}; + } + if (width > 2 * height){ + return {1.0, PokemonType::NONE}; + } + if (height > 2 * width){ + return {1.0, PokemonType::NONE}; + } + ImageStats stats = image_stats(image); + if (stats.stddev.sum() < 50){ + return {1.0, PokemonType::NONE}; + } + +// static int c = 0; +// image.save("test-" + std::to_string(threshold) + "-" + std::to_string(c++) + ".png"); + +// std::map rank; + double best_score = 0.4; + PokemonType best_type = PokemonType::NONE; + for (const auto& item : all_type_sprites()){ +// if (threshold != 700 || id != 55){ +// continue; +// } + double rmsd_alpha = item.second.matcher().diff(image); + +// item.second.matcher().m_image.save("sprite.png"); +// cout << item.second.slug() << ": " << rmsd_alpha << endl; + +#if 0 + // Handicap fairy due to white and pink being too similar in color and + // false positiving on the background. + if (item.first == PokemonType::FAIRY){ + rmsd_ratio *= 1.5; + } + + // Bonus for dark because or large contrast. + if (item.first == PokemonType::DARK){ + rmsd_ratio *= 0.8; + } +#endif + + if (best_score > rmsd_alpha){ + best_score = rmsd_alpha; + best_type = item.first; +// cout << item.second.slug() << ": " << stats.stddev << endl; + } + } + +// if (best_type != PokemonType::NONE){ +// cout << get_type_slug(best_type) << ": " << best_score << endl; +// } + return {best_score, best_type}; +} + +void find_symbol_candidates( + std::multimap>& candidates, + const ImageViewRGB32& image, + PackedBinaryMatrix& matrix, double max_area_ratio +){ + size_t max_area = (size_t)(image.width() * image.height() * max_area_ratio); + std::vector objects = find_objects_inplace(matrix, 20); + +// static int index = 0; + + std::map objmap; + for (size_t c = 0; c < objects.size(); c++){ + if (objects[c].area > max_area){ + continue; + } + objmap[c] = objects[c]; + +// image.copy( +// objects[c].min_x, objects[c].min_y, objects[c].width(), objects[c].height() +// ).save("test-" + std::to_string(index++) + ".png"); + } + +// cout << "begin = " << objmap.size() << endl; + + // Merge nearby objects. + bool changed; + do{ + changed = false; + for (auto iter0 = objmap.begin(); iter0 != objmap.end(); ++iter0){ + for (auto iter1 = objmap.begin(); iter1 != objmap.end();){ + if (iter0->first >= iter1->first){ + ++iter1; + continue; + } + const WaterfillObject& obj0 = iter0->second; + const WaterfillObject& obj1 = iter1->second; + size_t distance = distance_sqr( + ImagePixelBox(obj0.min_x, obj0.min_y, obj0.max_x, obj0.max_y), + ImagePixelBox(obj1.min_x, obj1.min_y, obj1.max_x, obj1.max_y) + ); + if (distance < 5*5){ + iter0->second.merge_assume_no_overlap(iter1->second); + iter1 = objmap.erase(iter1); + changed = true; + }else{ + ++iter1; + } + } + } + }while (changed); + +// cout << "merged = " << objmap.size() << endl; + + // Identify objects. + for (const auto& item : objmap){ + ImageViewRGB32 img = extract_box_reference(image, item.second); + std::pair result = match_type_symbol(img); + if (result.second != PokemonType::NONE){ + const WaterfillObject& obj = item.second; + candidates.emplace( + result.first, + std::pair( + result.second, + ImagePixelBox(obj.min_x, obj.min_y, obj.max_x, obj.max_y) + ) + ); + } + } + +// cout << "candidates = " << candidates.size() << endl; +} + + + +std::multimap> find_symbols( + const ImageViewRGB32& image, double max_area_ratio +){ + std::multimap> candidates; + + { + std::vector matrices = compress_rgb32_to_binary_range( + image, + { + {0xff909090, 0xffffffff}, + {0xffa0a0a0, 0xffffffff}, + {0xffb0b0b0, 0xffffffff}, + {0xffc0c0c0, 0xffffffff}, + {0xffd0d0d0, 0xffffffff}, + {0xffe0e0e0, 0xffffffff}, + } + ); + for (PackedBinaryMatrix& matrix : matrices){ + find_symbol_candidates(candidates, image, matrix, max_area_ratio); + } + } + + std::multimap> filtered; + for (const auto& candidate : candidates){ +// cout << get_type_slug(candidate.second.first) << ": " << candidate.first << endl; +// hits.emplace_back(overlay, translate_to_parent(screen, box, candidate.second.second.box), COLOR_GREEN); + + bool is_dupe = false; + for (const auto& item : filtered){ + if (distance_sqr(candidate.second.second, item.second.second) == 0){ + is_dupe = true; + break; + } + } + if (!is_dupe){ + filtered.emplace(candidate); + } + } + +#if 0 + for (const auto& item : filtered){ +// cout << get_type_slug(item.second.first) << ": " << item.first << " - [" << item.second.second.center_x() << "," << item.second.second.center_y() << "]" << endl; + const ImagePixelBox& box = item.second.second; + ImageViewRGB32 img = image.sub_image( + box.min_x, box.min_y, + box.width(), box.height() + ); +// img.save("test-" + std::to_string(c++) + ".png"); + } +#endif + + return filtered; +} + + + + + +void test_find_symbols( + CancellableScope& scope, + VideoOverlay& overlay, + const ImageFloatBox& box, + const ImageViewRGB32& screen, double max_area_ratio +){ + ImageViewRGB32 image = extract_box_reference(screen, box); + + std::multimap> candidates = find_symbols(image, max_area_ratio); + + + std::deque hits; +// hits.clear(); + cout << "---------------" << endl; + for (const auto& item : candidates){ + cout << POKEMON_TYPE_SLUGS().get_string(item.second.first) << ": " << item.first << endl; + hits.emplace_back(overlay, translate_to_parent(screen, box, item.second.second), COLOR_GREEN); + } + + scope.wait_for(std::chrono::seconds(10)); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h index 2541fb9fd3..3287a87ba6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h @@ -1,39 +1,39 @@ -/* Type Symbol Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TypeSymbolFinder_H -#define PokemonAutomation_PokemonSwSh_TypeSymbolFinder_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; - class VideoOverlay; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -// Find all type symbols inside the image. -std::multimap> find_symbols( - const ImageViewRGB32& image, double max_area_ratio -); - - - -void test_find_symbols( - ProgramEnvironment& env, - VideoOverlay& overlay, - const ImageFloatBox& box, - const ImageViewRGB32& screen, double max_area_ratio = 0.20 -); - - -} -} -} -#endif +/* Type Symbol Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TypeSymbolFinder_H +#define PokemonAutomation_PokemonSwSh_TypeSymbolFinder_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; + class VideoOverlay; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +// Find all type symbols inside the image. +std::multimap> find_symbols( + const ImageViewRGB32& image, double max_area_ratio +); + + + +void test_find_symbols( + ProgramEnvironment& env, + VideoOverlay& overlay, + const ImageFloatBox& box, + const ImageViewRGB32& screen, double max_area_ratio = 0.20 +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.cpp index 085a6a099f..d0f16d1793 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.cpp @@ -1,122 +1,122 @@ -/* Y-Comm Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" -#include "PokemonSwSh_YCommDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -YCommMenuDetector::YCommMenuDetector(bool is_on) - : VisualInferenceCallback("YCommMenuDetector") - , m_is_on(is_on) - , m_top(0.600, 0.020, 0.100, 0.040) - , m_bottom(0.100, 0.970, 0.400, 0.020) -{} -void YCommMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_top); - items.add(COLOR_RED, m_bottom); -} - -bool YCommMenuDetector::detect(const ImageViewRGB32& screen){ - ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); -// cout << bottom.average << bottom.stddev << endl; - if (!is_black(bottom)){ - return false; - } - - ImageStats top = image_stats(extract_box_reference(screen, m_top)); -// cout << top.average << top.stddev << endl; - if (!is_solid(top, {0.0819777, 0.124031, 0.793991}, 0.25)){ - return false; - } - - return true; -} - -bool YCommMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return m_is_on ? detect(frame) : !detect(frame); -} - - -namespace{ - -ImageFloatBox YCOMM_ICON_BOX{0.007, 0.944, 0.032, 0.054}; - -} - -class YCommIconMatcher : public ImageMatch::WaterfillTemplateMatcher{ -public: - YCommIconMatcher(); - static const YCommIconMatcher& instance(); -}; - - -YCommIconMatcher::YCommIconMatcher() - : WaterfillTemplateMatcher( - "PokemonSwSh/YComm.png", - Color(0,0,255), Color(100, 100, 255), 50 - ) -{ - m_aspect_ratio_lower = 0.9; - m_aspect_ratio_upper = 1.1; - m_area_ratio_lower = 0.9; - m_area_ratio_upper = 1.2; -} - -const YCommIconMatcher& YCommIconMatcher::instance(){ - static YCommIconMatcher matcher; - return matcher; -} - - -YCommIconDetector::YCommIconDetector(bool is_on) - : VisualInferenceCallback("YCommIconDetector") - , m_is_on(is_on) -{} - -void YCommIconDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, YCOMM_ICON_BOX); -} - -bool YCommIconDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - - const std::vector> filters = { - {combine_rgb(0, 0, 150), combine_rgb(100, 100, 255)} - }; - - const double screen_rel_size = (frame.height() / 1080.0); - const size_t min_size = size_t(screen_rel_size * screen_rel_size * 350.0); - - const bool detected = match_template_by_waterfill( - extract_box_reference(frame, YCOMM_ICON_BOX), - YCommIconMatcher::instance(), - filters, - {min_size, SIZE_MAX}, - 120, - [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } - ); - - return m_is_on ? detected : !detected; -} - - - -} -} -} +/* Y-Comm Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Kernels/Waterfill/Kernels_Waterfill_Types.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "CommonTools/ImageMatch/WaterfillTemplateMatcher.h" +#include "PokemonSwSh_YCommDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +YCommMenuDetector::YCommMenuDetector(bool is_on) + : VisualInferenceCallback("YCommMenuDetector") + , m_is_on(is_on) + , m_top(0.600, 0.020, 0.100, 0.040) + , m_bottom(0.100, 0.970, 0.400, 0.020) +{} +void YCommMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_top); + items.add(COLOR_RED, m_bottom); +} + +bool YCommMenuDetector::detect(const ImageViewRGB32& screen){ + ImageStats bottom = image_stats(extract_box_reference(screen, m_bottom)); +// cout << bottom.average << bottom.stddev << endl; + if (!is_black(bottom)){ + return false; + } + + ImageStats top = image_stats(extract_box_reference(screen, m_top)); +// cout << top.average << top.stddev << endl; + if (!is_solid(top, {0.0819777, 0.124031, 0.793991}, 0.25)){ + return false; + } + + return true; +} + +bool YCommMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return m_is_on ? detect(frame) : !detect(frame); +} + + +namespace{ + +ImageFloatBox YCOMM_ICON_BOX{0.007, 0.944, 0.032, 0.054}; + +} + +class YCommIconMatcher : public ImageMatch::WaterfillTemplateMatcher{ +public: + YCommIconMatcher(); + static const YCommIconMatcher& instance(); +}; + + +YCommIconMatcher::YCommIconMatcher() + : WaterfillTemplateMatcher( + "PokemonSwSh/YComm.png", + Color(0,0,255), Color(100, 100, 255), 50 + ) +{ + m_aspect_ratio_lower = 0.9; + m_aspect_ratio_upper = 1.1; + m_area_ratio_lower = 0.9; + m_area_ratio_upper = 1.2; +} + +const YCommIconMatcher& YCommIconMatcher::instance(){ + static YCommIconMatcher matcher; + return matcher; +} + + +YCommIconDetector::YCommIconDetector(bool is_on) + : VisualInferenceCallback("YCommIconDetector") + , m_is_on(is_on) +{} + +void YCommIconDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, YCOMM_ICON_BOX); +} + +bool YCommIconDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + + const std::vector> filters = { + {combine_rgb(0, 0, 150), combine_rgb(100, 100, 255)} + }; + + const double screen_rel_size = (frame.height() / 1080.0); + const size_t min_size = size_t(screen_rel_size * screen_rel_size * 350.0); + + const bool detected = match_template_by_waterfill( + extract_box_reference(frame, YCOMM_ICON_BOX), + YCommIconMatcher::instance(), + filters, + {min_size, SIZE_MAX}, + 120, + [](Kernels::Waterfill::WaterfillObject& object) -> bool { return true; } + ); + + return m_is_on ? detected : !detected; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h index 202482226f..e40189a93e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h @@ -1,59 +1,59 @@ -/* Y-Comm Menu Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_YCommDetector_H -#define PokemonAutomation_PokemonSwSh_YCommDetector_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - -class Logger; - -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class YCommMenuDetector : public VisualInferenceCallback{ -public: - YCommMenuDetector(bool is_on); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - bool m_is_on; - ImageFloatBox m_top; - ImageFloatBox m_bottom; -}; - -// Detect the blue Y letter as the Y Comm symbol in the lower left corner of the screen on the -// overworld, when Y Comm is active. -class YCommIconDetector : public VisualInferenceCallback{ -public: - // If `is_on` is true, `process_frame()` returns true if it finds the Y letter. - // Otherwise, `process_frame()` returns true if the Y letter is not found. - YCommIconDetector(bool is_on); - - virtual void make_overlays(VideoOverlaySet& items) const override; - - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - bool m_is_on; -}; - - - - - -} -} -} -#endif +/* Y-Comm Menu Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_YCommDetector_H +#define PokemonAutomation_PokemonSwSh_YCommDetector_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + +class Logger; + +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class YCommMenuDetector : public VisualInferenceCallback{ +public: + YCommMenuDetector(bool is_on); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + bool m_is_on; + ImageFloatBox m_top; + ImageFloatBox m_bottom; +}; + +// Detect the blue Y letter as the Y Comm symbol in the lower left corner of the screen on the +// overworld, when Y Comm is active. +class YCommIconDetector : public VisualInferenceCallback{ +public: + // If `is_on` is true, `process_frame()` returns true if it finds the Y letter. + // Otherwise, `process_frame()` returns true if the Y letter is not found. + YCommIconDetector(bool is_on); + + virtual void make_overlays(VideoOverlaySet& items) const override; + + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + bool m_is_on; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.cpp index 5fc1778eca..b8c870267e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.cpp @@ -1,103 +1,103 @@ -/* Orbeetle Attack Animation Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Detects whether Orbeetle's animation is special or physical. - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh_OrbeetleAttackAnimationDetector.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -OrbeetleAttackAnimationDetector::OrbeetleAttackAnimationDetector(VideoStream& stream, ProControllerContext& context) - : m_stream(stream) - , m_context(context) - , m_box(stream.overlay(), {0.86, 0.2, 0.1, 0.15}) -{} - - -OrbeetleAttackAnimationDetector::Detection OrbeetleAttackAnimationDetector::run(bool save_screenshot, bool log_values) -{ - // Grab baseline image. - VideoSnapshot baseline_image = m_stream.video().snapshot(); - if (!baseline_image){ - m_stream.log("Orbeetle Attack Animation: Screenshot failed.", COLOR_PURPLE); - return Detection::NO_DETECTION; - } - - if (save_screenshot){ - //baseline_image->save("orbeetle-baseline-" + now_to_filestring() + ".png"); - dump_debug_image(m_stream.logger(), "rng", "orbeetle-baseline", baseline_image); - } - - FloatPixel baseline_values = image_average(extract_box_reference(baseline_image, m_box)); - FloatPixel baseline_ratios = baseline_values / baseline_values.sum(); - - - // Play the attack animation. - pbf_press_button(m_context, BUTTON_RCLICK, 10, 155); - m_context.wait_for_all_requests(); - - - // Grab the animation image. - VideoSnapshot animation_image = m_stream.video().snapshot(); - if (!animation_image){ - m_stream.log("Orbeetle Attack Animation: Screenshot failed.", COLOR_PURPLE); - return Detection::NO_DETECTION; - } - - FloatPixel animation_values = image_average(extract_box_reference(animation_image, m_box)); - FloatPixel animation_ratios = animation_values / animation_values.sum(); - - if (log_values){ - m_stream.log("Orbeetle baseline value red: " + std::to_string(baseline_values.r)); - m_stream.log("Orbeetle attack value red: " + std::to_string(animation_values.r)); - m_stream.log("Orbeetle baseline value green: " + std::to_string(baseline_values.g)); - m_stream.log("Orbeetle attack value green: " + std::to_string(animation_values.g)); - m_stream.log("Orbeetle baseline value blue: " + std::to_string(baseline_values.b)); - m_stream.log("Orbeetle attack value blue: " + std::to_string(animation_values.b)); - - m_stream.log("Orbeetle baseline ratio red: " + std::to_string(baseline_ratios.r)); - m_stream.log("Orbeetle attack ratio red: " + std::to_string(animation_ratios.r)); - m_stream.log("Orbeetle baseline ratio green: " + std::to_string(baseline_ratios.g)); - m_stream.log("Orbeetle attack ratio green: " + std::to_string(animation_ratios.g)); - m_stream.log("Orbeetle baseline ratio blue: " + std::to_string(baseline_ratios.b)); - m_stream.log("Orbeetle attack ratio blue: " + std::to_string(animation_ratios.b)); - } - - if ((animation_ratios.r >= 1.4 * baseline_ratios.r) -// && (animation_ratios.g <= 0.85 * baseline_ratios.g) -// && (animation_ratios.b <= 0.85 * baseline_ratios.b) - ) - { - if (save_screenshot){ - //animation_image->save("orbeetle-attack-special-" + now_to_filestring() + ".png"); - dump_debug_image(m_stream.logger(), "rng", "orbeetle-special", animation_image); - } - m_stream.log("Orbeetle Attack Animation: Special animation detected."); - return Detection::SPECIAL; - } - if (save_screenshot){ - animation_image->save("orbeetle-attack-physical-" + now_to_filestring() + ".png"); - dump_debug_image(m_stream.logger(), "rng", "orbeetle-physical", animation_image); - } - m_stream.log("Orbeetle Attack Animation: Physical animation detected."); - return Detection::PHYSICAL; -} - - - -} -} -} +/* Orbeetle Attack Animation Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Detects whether Orbeetle's animation is special or physical. + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh_OrbeetleAttackAnimationDetector.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +OrbeetleAttackAnimationDetector::OrbeetleAttackAnimationDetector(VideoStream& stream, ProControllerContext& context) + : m_stream(stream) + , m_context(context) + , m_box(stream.overlay(), {0.86, 0.2, 0.1, 0.15}) +{} + + +OrbeetleAttackAnimationDetector::Detection OrbeetleAttackAnimationDetector::run(bool save_screenshot, bool log_values) +{ + // Grab baseline image. + VideoSnapshot baseline_image = m_stream.video().snapshot(); + if (!baseline_image){ + m_stream.log("Orbeetle Attack Animation: Screenshot failed.", COLOR_PURPLE); + return Detection::NO_DETECTION; + } + + if (save_screenshot){ + //baseline_image->save("orbeetle-baseline-" + now_to_filestring() + ".png"); + dump_debug_image(m_stream.logger(), "rng", "orbeetle-baseline", baseline_image); + } + + FloatPixel baseline_values = image_average(extract_box_reference(baseline_image, m_box)); + FloatPixel baseline_ratios = baseline_values / baseline_values.sum(); + + + // Play the attack animation. + pbf_press_button(m_context, BUTTON_RCLICK, 10, 155); + m_context.wait_for_all_requests(); + + + // Grab the animation image. + VideoSnapshot animation_image = m_stream.video().snapshot(); + if (!animation_image){ + m_stream.log("Orbeetle Attack Animation: Screenshot failed.", COLOR_PURPLE); + return Detection::NO_DETECTION; + } + + FloatPixel animation_values = image_average(extract_box_reference(animation_image, m_box)); + FloatPixel animation_ratios = animation_values / animation_values.sum(); + + if (log_values){ + m_stream.log("Orbeetle baseline value red: " + std::to_string(baseline_values.r)); + m_stream.log("Orbeetle attack value red: " + std::to_string(animation_values.r)); + m_stream.log("Orbeetle baseline value green: " + std::to_string(baseline_values.g)); + m_stream.log("Orbeetle attack value green: " + std::to_string(animation_values.g)); + m_stream.log("Orbeetle baseline value blue: " + std::to_string(baseline_values.b)); + m_stream.log("Orbeetle attack value blue: " + std::to_string(animation_values.b)); + + m_stream.log("Orbeetle baseline ratio red: " + std::to_string(baseline_ratios.r)); + m_stream.log("Orbeetle attack ratio red: " + std::to_string(animation_ratios.r)); + m_stream.log("Orbeetle baseline ratio green: " + std::to_string(baseline_ratios.g)); + m_stream.log("Orbeetle attack ratio green: " + std::to_string(animation_ratios.g)); + m_stream.log("Orbeetle baseline ratio blue: " + std::to_string(baseline_ratios.b)); + m_stream.log("Orbeetle attack ratio blue: " + std::to_string(animation_ratios.b)); + } + + if ((animation_ratios.r >= 1.4 * baseline_ratios.r) +// && (animation_ratios.g <= 0.85 * baseline_ratios.g) +// && (animation_ratios.b <= 0.85 * baseline_ratios.b) + ) + { + if (save_screenshot){ + //animation_image->save("orbeetle-attack-special-" + now_to_filestring() + ".png"); + dump_debug_image(m_stream.logger(), "rng", "orbeetle-special", animation_image); + } + m_stream.log("Orbeetle Attack Animation: Special animation detected."); + return Detection::SPECIAL; + } + if (save_screenshot){ + animation_image->save("orbeetle-attack-physical-" + now_to_filestring() + ".png"); + dump_debug_image(m_stream.logger(), "rng", "orbeetle-physical", animation_image); + } + m_stream.log("Orbeetle Attack Animation: Physical animation detected."); + return Detection::PHYSICAL; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h index 6cca35b9fe..763728842f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h @@ -1,48 +1,48 @@ -/* Orbeetle Attack Animation Detector - * - * From: https://github.com/PokemonAutomation/ - * - * - * Detects whether Orbeetle's animation is special or physical. - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_OrbeetleAttackAnimationDetector_H -#define PokemonAutomation_PokemonSwSh_OrbeetleAttackAnimationDetector_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class OrbeetleAttackAnimationDetector{ -public: - enum Detection{ - NO_DETECTION, - SPECIAL, - PHYSICAL, - }; - -public: - OrbeetleAttackAnimationDetector(VideoStream& stream, ProControllerContext& context); - - Detection run(bool save_screenshot, bool log_values); - - -private: - VideoStream& m_stream; - ProControllerContext& m_context; - OverlayBoxScope m_box; -}; - - - -} -} -} -#endif +/* Orbeetle Attack Animation Detector + * + * From: https://github.com/PokemonAutomation/ + * + * + * Detects whether Orbeetle's animation is special or physical. + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_OrbeetleAttackAnimationDetector_H +#define PokemonAutomation_PokemonSwSh_OrbeetleAttackAnimationDetector_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class OrbeetleAttackAnimationDetector{ +public: + enum Detection{ + NO_DETECTION, + SPECIAL, + PHYSICAL, + }; + +public: + OrbeetleAttackAnimationDetector(VideoStream& stream, ProControllerContext& context); + + Detection run(bool save_screenshot, bool log_values); + + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + OverlayBoxScope m_box; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.cpp index 6f4140c79f..bce8f276d4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.cpp @@ -1,161 +1,161 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_ShinyEncounterDetector.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const ShinyDetectionBattle SHINY_BATTLE_REGULAR {false, {0.5, 0.05, 0.5, 0.70}, std::chrono::milliseconds(2300)}; -const ShinyDetectionBattle SHINY_BATTLE_RAID {true, {0.3, 0.01, 0.7, 0.75}, std::chrono::milliseconds(3900)}; - - - -ShinyEncounterTracker::ShinyEncounterTracker( - Logger& logger, VideoOverlay& overlay, - const ShinyDetectionBattle& battle_settings -) - : VisualInferenceCallback("ShinyEncounterTracker") - , m_battle_settings(battle_settings) - , m_logger(logger) -// , m_overlay(overlay) - , m_battle_menu(battle_settings.den) - , m_dialog_tracker(logger, m_dialog_detector) - , m_sparkle_tracker(logger, overlay, m_sparkles, battle_settings.detection_box) -{} -void ShinyEncounterTracker::make_overlays(VideoOverlaySet& items) const{ - m_battle_menu.make_overlays(items); - m_dialog_tracker.make_overlays(items); - m_sparkle_tracker.make_overlays(items); -} -bool ShinyEncounterTracker::process_frame(const VideoSnapshot& frame){ - if (!frame){ - return false; - } - - size_t width = frame->width(); - size_t height = frame->height(); - - if (height < 720){ - throw UserSetupError(m_logger, "Video resolution must be at least 720p."); - } - double aspect_ratio = (double)width / height; - if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ - throw UserSetupError(m_logger, "Video aspect ratio must be 16:9."); - } - - bool battle_menu = m_battle_menu.process_frame(frame); - if (battle_menu){ - m_dialog_tracker.push_end(frame.timestamp); - return true; - } - - m_dialog_tracker.process_frame(frame); - m_sparkle_tracker.process_frame(frame); - - switch (m_dialog_tracker.encounter_state()){ - case EncounterState::BEFORE_ANYTHING: - break; - case EncounterState::WILD_ANIMATION: - m_best_wild.add_frame(frame.frame, m_sparkles); - break; - case EncounterState::YOUR_ANIMATION: - break; - case EncounterState::POST_ENTRY: - break; - } - - return false; -} - -ShinyType determine_shiny_status( - double& alpha, - Logger& logger, - const ShinyDetectionBattle& battle_settings, - const EncounterDialogTracker& dialog_tracker, - const ShinySparkleAggregator& sparkles -){ - alpha = sparkles.best_overall(); - - std::chrono::milliseconds dialog_duration = dialog_tracker.wild_animation_duration(); - std::chrono::milliseconds min_delay = battle_settings.dialog_delay_when_shiny - std::chrono::milliseconds(300); - std::chrono::milliseconds max_delay = battle_settings.dialog_delay_when_shiny + std::chrono::milliseconds(500); - if (min_delay <= dialog_duration && dialog_duration <= max_delay){ - alpha += GameSettings::instance().SHINY_DIALOG_ALPHA; - } - - double best_star = sparkles.best_star(); - double best_square = sparkles.best_square(); - - logger.log( - "ShinyDetector: Overall Alpha = " + tostr_default(alpha) + - ", Star Alpha = " + tostr_default(best_star) + - ", Square Alpha = " + tostr_default(best_square), - COLOR_PURPLE - ); - - if (alpha < GameSettings::instance().SHINY_ALPHA_THRESHOLD){ - logger.log("ShinyDetector: Not Shiny.", COLOR_PURPLE); - return ShinyType::NOT_SHINY; - } - if (best_star > 0 && best_star > best_square){ - logger.log("ShinyDetector: Detected Star Shiny!", COLOR_BLUE); - return ShinyType::STAR_SHINY; - } - if (best_square > 0 && best_square > best_star * 2){ - logger.log("ShinyDetector: Detected Square Shiny!", COLOR_BLUE); - return ShinyType::SQUARE_SHINY; - } - - logger.log("ShinyDetector: Detected Shiny! But ambiguous shiny type.", COLOR_BLUE); - return ShinyType::UNKNOWN_SHINY; -} - - -ShinyDetectionResult detect_shiny_battle( - VideoStream& stream, CancellableScope& scope, - const ShinyDetectionBattle& battle_settings, - std::chrono::seconds timeout -){ - ShinyEncounterTracker tracker(stream.logger(), stream.overlay(), battle_settings); - int result = wait_until( - stream, scope, timeout, - {{tracker}} - ); - if (result < 0){ - stream.log("ShinyDetector: Battle menu not found after timeout.", COLOR_RED); - return ShinyDetectionResult{ShinyType::UNKNOWN, 0, std::make_shared()}; - } - double alpha; - ShinyType shiny_type = determine_shiny_status( - alpha, - stream.logger(), - battle_settings, - tracker.dialog_tracker(), - tracker.sparkles_wild() - ); - return ShinyDetectionResult{shiny_type, alpha, tracker.sparkles_wild().best_image()}; -} - - - - - -} -} -} +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_ShinyEncounterDetector.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const ShinyDetectionBattle SHINY_BATTLE_REGULAR {false, {0.5, 0.05, 0.5, 0.70}, std::chrono::milliseconds(2300)}; +const ShinyDetectionBattle SHINY_BATTLE_RAID {true, {0.3, 0.01, 0.7, 0.75}, std::chrono::milliseconds(3900)}; + + + +ShinyEncounterTracker::ShinyEncounterTracker( + Logger& logger, VideoOverlay& overlay, + const ShinyDetectionBattle& battle_settings +) + : VisualInferenceCallback("ShinyEncounterTracker") + , m_battle_settings(battle_settings) + , m_logger(logger) +// , m_overlay(overlay) + , m_battle_menu(battle_settings.den) + , m_dialog_tracker(logger, m_dialog_detector) + , m_sparkle_tracker(logger, overlay, m_sparkles, battle_settings.detection_box) +{} +void ShinyEncounterTracker::make_overlays(VideoOverlaySet& items) const{ + m_battle_menu.make_overlays(items); + m_dialog_tracker.make_overlays(items); + m_sparkle_tracker.make_overlays(items); +} +bool ShinyEncounterTracker::process_frame(const VideoSnapshot& frame){ + if (!frame){ + return false; + } + + size_t width = frame->width(); + size_t height = frame->height(); + + if (height < 720){ + throw UserSetupError(m_logger, "Video resolution must be at least 720p."); + } + double aspect_ratio = (double)width / height; + if (aspect_ratio < 1.77 || aspect_ratio > 1.78){ + throw UserSetupError(m_logger, "Video aspect ratio must be 16:9."); + } + + bool battle_menu = m_battle_menu.process_frame(frame); + if (battle_menu){ + m_dialog_tracker.push_end(frame.timestamp); + return true; + } + + m_dialog_tracker.process_frame(frame); + m_sparkle_tracker.process_frame(frame); + + switch (m_dialog_tracker.encounter_state()){ + case EncounterState::BEFORE_ANYTHING: + break; + case EncounterState::WILD_ANIMATION: + m_best_wild.add_frame(frame.frame, m_sparkles); + break; + case EncounterState::YOUR_ANIMATION: + break; + case EncounterState::POST_ENTRY: + break; + } + + return false; +} + +ShinyType determine_shiny_status( + double& alpha, + Logger& logger, + const ShinyDetectionBattle& battle_settings, + const EncounterDialogTracker& dialog_tracker, + const ShinySparkleAggregator& sparkles +){ + alpha = sparkles.best_overall(); + + std::chrono::milliseconds dialog_duration = dialog_tracker.wild_animation_duration(); + std::chrono::milliseconds min_delay = battle_settings.dialog_delay_when_shiny - std::chrono::milliseconds(300); + std::chrono::milliseconds max_delay = battle_settings.dialog_delay_when_shiny + std::chrono::milliseconds(500); + if (min_delay <= dialog_duration && dialog_duration <= max_delay){ + alpha += GameSettings::instance().SHINY_DIALOG_ALPHA; + } + + double best_star = sparkles.best_star(); + double best_square = sparkles.best_square(); + + logger.log( + "ShinyDetector: Overall Alpha = " + tostr_default(alpha) + + ", Star Alpha = " + tostr_default(best_star) + + ", Square Alpha = " + tostr_default(best_square), + COLOR_PURPLE + ); + + if (alpha < GameSettings::instance().SHINY_ALPHA_THRESHOLD){ + logger.log("ShinyDetector: Not Shiny.", COLOR_PURPLE); + return ShinyType::NOT_SHINY; + } + if (best_star > 0 && best_star > best_square){ + logger.log("ShinyDetector: Detected Star Shiny!", COLOR_BLUE); + return ShinyType::STAR_SHINY; + } + if (best_square > 0 && best_square > best_star * 2){ + logger.log("ShinyDetector: Detected Square Shiny!", COLOR_BLUE); + return ShinyType::SQUARE_SHINY; + } + + logger.log("ShinyDetector: Detected Shiny! But ambiguous shiny type.", COLOR_BLUE); + return ShinyType::UNKNOWN_SHINY; +} + + +ShinyDetectionResult detect_shiny_battle( + VideoStream& stream, CancellableScope& scope, + const ShinyDetectionBattle& battle_settings, + std::chrono::seconds timeout +){ + ShinyEncounterTracker tracker(stream.logger(), stream.overlay(), battle_settings); + int result = wait_until( + stream, scope, timeout, + {{tracker}} + ); + if (result < 0){ + stream.log("ShinyDetector: Battle menu not found after timeout.", COLOR_RED); + return ShinyDetectionResult{ShinyType::UNKNOWN, 0, std::make_shared()}; + } + double alpha; + ShinyType shiny_type = determine_shiny_status( + alpha, + stream.logger(), + battle_settings, + tracker.dialog_tracker(), + tracker.sparkles_wild() + ); + return ShinyDetectionResult{shiny_type, alpha, tracker.sparkles_wild().best_image()}; +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h index f131a9893f..6057f7951a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h @@ -1,93 +1,93 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyEncounterDetector_H -#define PokemonAutomation_PokemonSwSh_ShinyEncounterDetector_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "Pokemon/Pokemon_DataTypes.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h" -#include "PokemonSwSh_ShinySparkleSet.h" - -namespace PokemonAutomation{ - class CancellableScope; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -struct ShinyDetectionBattle{ - bool den; - ImageFloatBox detection_box; - std::chrono::milliseconds dialog_delay_when_shiny; -}; -extern const ShinyDetectionBattle SHINY_BATTLE_REGULAR; -extern const ShinyDetectionBattle SHINY_BATTLE_RAID; - - - - -class ShinyEncounterTracker : public VisualInferenceCallback{ -public: - ShinyEncounterTracker( - Logger& logger, VideoOverlay& overlay, - const ShinyDetectionBattle& battle_settings - ); - - const EncounterDialogTracker& dialog_tracker() const{ return m_dialog_tracker; } - const ShinySparkleAggregator& sparkles_wild() const{ return m_best_wild; } - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const VideoSnapshot& frame) override; - - ShinyType get_results() const; - - -private: - ShinyDetectionBattle m_battle_settings; - - Logger& m_logger; -// VideoOverlay& m_overlay; - - StandardBattleMenuWatcher m_battle_menu; - - BattleDialogDetector m_dialog_detector; - EncounterDialogTracker m_dialog_tracker; - - ShinySparkleSetSwSh m_sparkles; - ShinySparkleTracker m_sparkle_tracker; - - ShinySparkleAggregator m_best_wild; -}; - -ShinyType determine_shiny_status( - double& alpha, - Logger& logger, - const ShinyDetectionBattle& battle_settings, - const EncounterDialogTracker& dialog_tracker, - const ShinySparkleAggregator& sparkles -); - - - - -ShinyDetectionResult detect_shiny_battle( - VideoStream& stream, CancellableScope& scope, - const ShinyDetectionBattle& battle_settings, - std::chrono::seconds timeout -); - - - - -} -} -} -#endif +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyEncounterDetector_H +#define PokemonAutomation_PokemonSwSh_ShinyEncounterDetector_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "Pokemon/Pokemon_DataTypes.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleDialogTracker.h" +#include "PokemonSwSh_ShinySparkleSet.h" + +namespace PokemonAutomation{ + class CancellableScope; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +struct ShinyDetectionBattle{ + bool den; + ImageFloatBox detection_box; + std::chrono::milliseconds dialog_delay_when_shiny; +}; +extern const ShinyDetectionBattle SHINY_BATTLE_REGULAR; +extern const ShinyDetectionBattle SHINY_BATTLE_RAID; + + + + +class ShinyEncounterTracker : public VisualInferenceCallback{ +public: + ShinyEncounterTracker( + Logger& logger, VideoOverlay& overlay, + const ShinyDetectionBattle& battle_settings + ); + + const EncounterDialogTracker& dialog_tracker() const{ return m_dialog_tracker; } + const ShinySparkleAggregator& sparkles_wild() const{ return m_best_wild; } + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const VideoSnapshot& frame) override; + + ShinyType get_results() const; + + +private: + ShinyDetectionBattle m_battle_settings; + + Logger& m_logger; +// VideoOverlay& m_overlay; + + StandardBattleMenuWatcher m_battle_menu; + + BattleDialogDetector m_dialog_detector; + EncounterDialogTracker m_dialog_tracker; + + ShinySparkleSetSwSh m_sparkles; + ShinySparkleTracker m_sparkle_tracker; + + ShinySparkleAggregator m_best_wild; +}; + +ShinyType determine_shiny_status( + double& alpha, + Logger& logger, + const ShinyDetectionBattle& battle_settings, + const EncounterDialogTracker& dialog_tracker, + const ShinySparkleAggregator& sparkles +); + + + + +ShinyDetectionResult detect_shiny_battle( + VideoStream& stream, CancellableScope& scope, + const ShinyDetectionBattle& battle_settings, + std::chrono::seconds timeout +); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp index f8ab279659..0e2bbc43c4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.cpp @@ -1,170 +1,170 @@ -/* Shiny Sparkle Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_SparkleDetectorRadial.h" -#include "PokemonSwSh_SparkleDetectorSquare.h" -#include "PokemonSwSh_ShinySparkleSet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -ShinySparkleSetSwSh::~ShinySparkleSetSwSh(){} -void ShinySparkleSetSwSh::clear(){ - balls.clear(); - stars.clear(); - squares.clear(); - lines.clear(); - m_alpha_overall = 0; - m_alpha_star = 0; - m_alpha_square = 0; -} - -std::string ShinySparkleSetSwSh::to_str() const{ - std::ostringstream ss; - if (m_alpha_overall < 1.0){ - return ""; - } - ss << "SparkleDetector"; - if (!balls.empty()){ - ss << " - Balls: " << balls.size(); - } - if (!stars.empty()){ - ss << " - Stars: " << stars.size(); - } - if (!squares.empty()){ - ss << " - Squares: " << squares.size(); - } - if (!lines.empty()){ - ss << " - Lines: " << lines.size(); - } - ss << " - (alpha = " << m_alpha_overall << ")"; - return ss.str(); -} -void ShinySparkleSetSwSh::draw_boxes( - VideoOverlaySet& overlays, - const ImageViewRGB32& frame, - const ImageFloatBox& inference_box -) const{ - for (const ImagePixelBox& box : balls){ - overlays.add(COLOR_GREEN, translate_to_parent(frame, inference_box, box)); - } - for (const ImagePixelBox& box : stars){ - overlays.add(COLOR_BLUE, translate_to_parent(frame, inference_box, box)); - } - for (const ImagePixelBox& box : squares){ - overlays.add(COLOR_MAGENTA, translate_to_parent(frame, inference_box, box)); - } - for (const ImagePixelBox& box : lines){ - overlays.add(COLOR_YELLOW, translate_to_parent(frame, inference_box, box)); - } -} -void ShinySparkleSetSwSh::update_alphas(){ - const GameSettings& settings = GameSettings::instance(); - double ball_alpha = settings.BALL_SPARKLE_ALPHA * balls.size(); - double star_alpha = settings.STAR_SPARKLE_ALPHA * stars.size(); - double square_alpha = settings.SQUARE_SPARKLE_ALPHA * squares.size(); - double line_alpha = std::min(settings.LINE_SPARKLE_ALPHA * lines.size(), square_alpha); - m_alpha_overall = ball_alpha + star_alpha + square_alpha + line_alpha; - m_alpha_star = star_alpha; - m_alpha_square = square_alpha + line_alpha; -} - - - - -ShinySparkleSetSwSh find_sparkles(size_t screen_area, WaterfillSession& session){ - ShinySparkleSetSwSh sparkles; - auto finder = session.make_iterator(20); - WaterfillObject object; - while (finder->find_next(object, true)){ - RadialSparkleDetector radial_sparkle(screen_area, object); - if (radial_sparkle.is_ball()){ - sparkles.balls.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); - continue; - } - if (radial_sparkle.is_star()){ - sparkles.stars.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); - continue; - } - if (is_line_sparkle(object)){ - sparkles.lines.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); - continue; - } - if (is_square_sparkle(object)){ - sparkles.squares.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); - continue; - } - } - return sparkles; -} -void ShinySparkleSetSwSh::read_from_image(size_t screen_area, const ImageViewRGB32& image){ - clear(); - if (!image){ - return; - } - - std::vector matrices = compress_rgb32_to_binary_range( - image, - { - {0xffa0a000, 0xffffffff}, - {0xffb0b000, 0xffffffff}, - {0xffc0c000, 0xffffffff}, - {0xffd0d000, 0xffffffff}, - } - ); - auto session = make_WaterfillSession(); - - double best_alpha = 0; - for (PackedBinaryMatrix& matrix : matrices){ - session->set_source(matrix); - ShinySparkleSetSwSh sparkles = find_sparkles(screen_area, *session); - sparkles.update_alphas(); - double alpha = sparkles.alpha_overall(); - if (best_alpha < alpha){ - best_alpha = alpha; - *this = std::move(sparkles); - } - } -} - - - - -void ShinySparkleAggregator::add_frame(const std::shared_ptr& image, const ShinySparkleSetSwSh& sparkles){ - m_best_overall = std::max(m_best_overall, sparkles.alpha_overall()); - - double current_star = sparkles.alpha_star(); - double current_square = sparkles.alpha_square(); - - m_best_star = std::max(m_best_star, current_star); - m_best_square = std::max(m_best_square, current_square); - - double type_alpha = std::max(current_star, current_square); - if (m_best_type < type_alpha){ - m_best_type = type_alpha; - m_best_image = image; - } -} - - - - - - -} -} -} - - +/* Shiny Sparkle Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_SparkleDetectorRadial.h" +#include "PokemonSwSh_SparkleDetectorSquare.h" +#include "PokemonSwSh_ShinySparkleSet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +ShinySparkleSetSwSh::~ShinySparkleSetSwSh(){} +void ShinySparkleSetSwSh::clear(){ + balls.clear(); + stars.clear(); + squares.clear(); + lines.clear(); + m_alpha_overall = 0; + m_alpha_star = 0; + m_alpha_square = 0; +} + +std::string ShinySparkleSetSwSh::to_str() const{ + std::ostringstream ss; + if (m_alpha_overall < 1.0){ + return ""; + } + ss << "SparkleDetector"; + if (!balls.empty()){ + ss << " - Balls: " << balls.size(); + } + if (!stars.empty()){ + ss << " - Stars: " << stars.size(); + } + if (!squares.empty()){ + ss << " - Squares: " << squares.size(); + } + if (!lines.empty()){ + ss << " - Lines: " << lines.size(); + } + ss << " - (alpha = " << m_alpha_overall << ")"; + return ss.str(); +} +void ShinySparkleSetSwSh::draw_boxes( + VideoOverlaySet& overlays, + const ImageViewRGB32& frame, + const ImageFloatBox& inference_box +) const{ + for (const ImagePixelBox& box : balls){ + overlays.add(COLOR_GREEN, translate_to_parent(frame, inference_box, box)); + } + for (const ImagePixelBox& box : stars){ + overlays.add(COLOR_BLUE, translate_to_parent(frame, inference_box, box)); + } + for (const ImagePixelBox& box : squares){ + overlays.add(COLOR_MAGENTA, translate_to_parent(frame, inference_box, box)); + } + for (const ImagePixelBox& box : lines){ + overlays.add(COLOR_YELLOW, translate_to_parent(frame, inference_box, box)); + } +} +void ShinySparkleSetSwSh::update_alphas(){ + const GameSettings& settings = GameSettings::instance(); + double ball_alpha = settings.BALL_SPARKLE_ALPHA * balls.size(); + double star_alpha = settings.STAR_SPARKLE_ALPHA * stars.size(); + double square_alpha = settings.SQUARE_SPARKLE_ALPHA * squares.size(); + double line_alpha = std::min(settings.LINE_SPARKLE_ALPHA * lines.size(), square_alpha); + m_alpha_overall = ball_alpha + star_alpha + square_alpha + line_alpha; + m_alpha_star = star_alpha; + m_alpha_square = square_alpha + line_alpha; +} + + + + +ShinySparkleSetSwSh find_sparkles(size_t screen_area, WaterfillSession& session){ + ShinySparkleSetSwSh sparkles; + auto finder = session.make_iterator(20); + WaterfillObject object; + while (finder->find_next(object, true)){ + RadialSparkleDetector radial_sparkle(screen_area, object); + if (radial_sparkle.is_ball()){ + sparkles.balls.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); + continue; + } + if (radial_sparkle.is_star()){ + sparkles.stars.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); + continue; + } + if (is_line_sparkle(object)){ + sparkles.lines.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); + continue; + } + if (is_square_sparkle(object)){ + sparkles.squares.emplace_back(object.min_x, object.min_y, object.max_x, object.max_y); + continue; + } + } + return sparkles; +} +void ShinySparkleSetSwSh::read_from_image(size_t screen_area, const ImageViewRGB32& image){ + clear(); + if (!image){ + return; + } + + std::vector matrices = compress_rgb32_to_binary_range( + image, + { + {0xffa0a000, 0xffffffff}, + {0xffb0b000, 0xffffffff}, + {0xffc0c000, 0xffffffff}, + {0xffd0d000, 0xffffffff}, + } + ); + auto session = make_WaterfillSession(); + + double best_alpha = 0; + for (PackedBinaryMatrix& matrix : matrices){ + session->set_source(matrix); + ShinySparkleSetSwSh sparkles = find_sparkles(screen_area, *session); + sparkles.update_alphas(); + double alpha = sparkles.alpha_overall(); + if (best_alpha < alpha){ + best_alpha = alpha; + *this = std::move(sparkles); + } + } +} + + + + +void ShinySparkleAggregator::add_frame(const std::shared_ptr& image, const ShinySparkleSetSwSh& sparkles){ + m_best_overall = std::max(m_best_overall, sparkles.alpha_overall()); + + double current_star = sparkles.alpha_star(); + double current_square = sparkles.alpha_square(); + + m_best_star = std::max(m_best_star, current_star); + m_best_square = std::max(m_best_square, current_square); + + double type_alpha = std::max(current_star, current_square); + if (m_best_type < type_alpha){ + m_best_type = type_alpha; + m_best_image = image; + } +} + + + + + + +} +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h index 7324f1783e..00f7d8d210 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleSet.h @@ -1,75 +1,75 @@ -/* Shiny Sparkle Set - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinySparkleSet_H -#define PokemonAutomation_PokemonSwSh_ShinySparkleSet_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "Pokemon/Pokemon_ShinySparkleSet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class ShinySparkleSetSwSh : public Pokemon::ShinySparkleSet{ -public: - std::vector balls; - std::vector stars; - std::vector squares; - std::vector lines; - - virtual ~ShinySparkleSetSwSh(); - virtual void clear() override; - - double alpha_overall() const{ return m_alpha_overall; } - double alpha_star() const{ return m_alpha_star; } - double alpha_square() const{ return m_alpha_square; } - - virtual std::string to_str() const override; - virtual void read_from_image(size_t screen_area, const ImageViewRGB32& image) override; - - virtual void draw_boxes( - VideoOverlaySet& overlays, - const ImageViewRGB32& frame, - const ImageFloatBox& inference_box - ) const override; - -private: - void update_alphas(); - - double m_alpha_overall = 0; - double m_alpha_star = 0; - double m_alpha_square = 0; -}; - - - -class ShinySparkleAggregator{ -public: - double best_overall() const{ return m_best_overall; } - double best_star() const{ return m_best_star; } - double best_square() const{ return m_best_square; } - const std::shared_ptr& best_image() const{ return m_best_image; } - - void add_frame(const std::shared_ptr& image, const ShinySparkleSetSwSh& sparkles); - -private: - double m_best_overall = 0; - double m_best_star = 0; - double m_best_square = 0; - double m_best_type = 0; - std::shared_ptr m_best_image; -}; - - - - -} -} -} -#endif +/* Shiny Sparkle Set + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinySparkleSet_H +#define PokemonAutomation_PokemonSwSh_ShinySparkleSet_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "Pokemon/Pokemon_ShinySparkleSet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class ShinySparkleSetSwSh : public Pokemon::ShinySparkleSet{ +public: + std::vector balls; + std::vector stars; + std::vector squares; + std::vector lines; + + virtual ~ShinySparkleSetSwSh(); + virtual void clear() override; + + double alpha_overall() const{ return m_alpha_overall; } + double alpha_star() const{ return m_alpha_star; } + double alpha_square() const{ return m_alpha_square; } + + virtual std::string to_str() const override; + virtual void read_from_image(size_t screen_area, const ImageViewRGB32& image) override; + + virtual void draw_boxes( + VideoOverlaySet& overlays, + const ImageViewRGB32& frame, + const ImageFloatBox& inference_box + ) const override; + +private: + void update_alphas(); + + double m_alpha_overall = 0; + double m_alpha_star = 0; + double m_alpha_square = 0; +}; + + + +class ShinySparkleAggregator{ +public: + double best_overall() const{ return m_best_overall; } + double best_star() const{ return m_best_star; } + double best_square() const{ return m_best_square; } + const std::shared_ptr& best_image() const{ return m_best_image; } + + void add_frame(const std::shared_ptr& image, const ShinySparkleSetSwSh& sparkles); + +private: + double m_best_overall = 0; + double m_best_star = 0; + double m_best_square = 0; + double m_best_type = 0; + std::shared_ptr m_best_image; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.cpp index 68d562225d..fab2dafdb5 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.cpp @@ -1,213 +1,213 @@ -/* Shiny Sparkle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonTools/Images/WaterfillUtilities.h" -#include "PokemonSwSh_SparkleDetectorRadial.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const double STAR_SPARKLE_ANGLE_TOLERANCE_DEGREES = 10.; - - -RadialSparkleDetector::~RadialSparkleDetector(){} -RadialSparkleDetector::RadialSparkleDetector(size_t screen_area, const WaterfillObject& object) - : m_object(object) -{ - if (object.area < 20){ - return; - } - - double area_1080p = 1920 * 1080; - double area_current = (double)screen_area; - if (object.area * area_1080p > 10000 * area_current){ - return; - } - - const size_t stop = (size_t)(0.85 * object.area); - std::tie(m_matrix, m_radius_sqr) = remove_center_pixels(object, stop); - - // Find new regions. - PackedBinaryMatrix matrix = m_matrix.copy(); - auto session = make_WaterfillSession(matrix); - auto finder = session->make_iterator(1); - WaterfillObject obj; - while (finder->find_next(obj, false)){ - m_regions.emplace(obj.area, std::move(obj)); - } - -// cout << m_matrix.dump() << endl; -} - -bool RadialSparkleDetector::is_ball() const{ - // Fewer than 4 regions, cannot be a ball. - if (m_regions.size() < 4){ - return false; - } - - size_t width = m_object.width(); - size_t height = m_object.height(); - - // Make sure area is less than 2/3 of the box. -// cout << "area = " << m_box.area * 2 << ", box = " << (uint64_t)width * height << endl; - if (m_object.area * 3 > (uint64_t)width * height * 2){ -// cout << "bad area" << endl; - return false; - } - - // Compute angles for the 4 largest regions. - ptrdiff_t center_x = (ptrdiff_t)(m_object.center_of_gravity_x() - m_object.min_x); - ptrdiff_t center_y = (ptrdiff_t)(m_object.center_of_gravity_y() - m_object.min_y); - std::set angles; - { - size_t c = 0; - for (const auto& region : m_regions){ - ptrdiff_t x = (ptrdiff_t)region.second.center_of_gravity_x() - center_x; - ptrdiff_t y = (ptrdiff_t)region.second.center_of_gravity_y() - center_y; - double angle = std::atan2(y, x) * 57.29577951308232; - if (angle < 0){ - angle += 360; - } - angles.insert(angle); - c++; - if (c >= 4){ - break; - } - } - } - - // Verify angles are aligned to the corners. - for (double angle : angles){ - double n = angle - 45; - double q = std::round(n / 90.); - double m = n - 90. * q; - if (std::abs(m) > STAR_SPARKLE_ANGLE_TOLERANCE_DEGREES){ - return false; - } - } - - // Verify that all live pixels are near the diagonals. - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - if (!m_matrix.get(c, r)){ - continue; - } - double distance = std::sqrt(center_x*center_x + center_y*center_y); - ptrdiff_t dist_x = std::abs((ptrdiff_t)c - center_x); - ptrdiff_t dist_y = std::abs((ptrdiff_t)r - center_y); - ptrdiff_t dist = std::abs(dist_y - dist_x); - if (dist > 2 + distance / 5.){ - return false; - } - } - } - - return true; -} -bool RadialSparkleDetector::is_star() const{ - // Fewer than 5 regions, cannot be a star. - if (m_regions.size() < 5){ - return false; - } - - size_t width = m_object.width(); - size_t height = m_object.height(); - - // Area is too small. - if (width * height < 100){ - return false; - } - - // Make sure dimensions are roughly square-ish. - if (width > 2 * height || height > 2 * width){ - return false; - } - - // Compute angles for the 5 largest regions. - ptrdiff_t center_x = (ptrdiff_t)(m_object.center_of_gravity_x() - m_object.min_x); - ptrdiff_t center_y = (ptrdiff_t)(m_object.center_of_gravity_y() - m_object.min_y); - std::set angles; - size_t c = 0; - for (const auto& region : m_regions){ - ptrdiff_t x = (ptrdiff_t)region.second.center_of_gravity_x() - center_x; - ptrdiff_t y = (ptrdiff_t)region.second.center_of_gravity_y() - center_y; - double angle = std::atan2(y, x) * 57.29577951308232; - if (angle < 0){ - angle += 360; - } - angles.insert(angle); - c++; - if (c >= 5){ - break; - } - } - - // Attempt best fit. - bool match = false; - for (double angle : angles){ - size_t bad = 0; - uint8_t points = 0; - for (double test : angles){ - double n = test - angle; - double q = std::round(n / 72.); - points |= (size_t)1 << ((size_t)q % 5); - double m = n - 72. * q; - if (std::abs(m) > STAR_SPARKLE_ANGLE_TOLERANCE_DEGREES){ - bad++; - } - } - - // Not all 5 points are detected. - if ((points & 0x1f) != 0x1f){ - continue; - } - - // Bad angles. - if (bad <= 0){ - match = true; - break; - } - } - - return match; -} - - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Shiny Sparkle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonTools/Images/WaterfillUtilities.h" +#include "PokemonSwSh_SparkleDetectorRadial.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const double STAR_SPARKLE_ANGLE_TOLERANCE_DEGREES = 10.; + + +RadialSparkleDetector::~RadialSparkleDetector(){} +RadialSparkleDetector::RadialSparkleDetector(size_t screen_area, const WaterfillObject& object) + : m_object(object) +{ + if (object.area < 20){ + return; + } + + double area_1080p = 1920 * 1080; + double area_current = (double)screen_area; + if (object.area * area_1080p > 10000 * area_current){ + return; + } + + const size_t stop = (size_t)(0.85 * object.area); + std::tie(m_matrix, m_radius_sqr) = remove_center_pixels(object, stop); + + // Find new regions. + PackedBinaryMatrix matrix = m_matrix.copy(); + auto session = make_WaterfillSession(matrix); + auto finder = session->make_iterator(1); + WaterfillObject obj; + while (finder->find_next(obj, false)){ + m_regions.emplace(obj.area, std::move(obj)); + } + +// cout << m_matrix.dump() << endl; +} + +bool RadialSparkleDetector::is_ball() const{ + // Fewer than 4 regions, cannot be a ball. + if (m_regions.size() < 4){ + return false; + } + + size_t width = m_object.width(); + size_t height = m_object.height(); + + // Make sure area is less than 2/3 of the box. +// cout << "area = " << m_box.area * 2 << ", box = " << (uint64_t)width * height << endl; + if (m_object.area * 3 > (uint64_t)width * height * 2){ +// cout << "bad area" << endl; + return false; + } + + // Compute angles for the 4 largest regions. + ptrdiff_t center_x = (ptrdiff_t)(m_object.center_of_gravity_x() - m_object.min_x); + ptrdiff_t center_y = (ptrdiff_t)(m_object.center_of_gravity_y() - m_object.min_y); + std::set angles; + { + size_t c = 0; + for (const auto& region : m_regions){ + ptrdiff_t x = (ptrdiff_t)region.second.center_of_gravity_x() - center_x; + ptrdiff_t y = (ptrdiff_t)region.second.center_of_gravity_y() - center_y; + double angle = std::atan2(y, x) * 57.29577951308232; + if (angle < 0){ + angle += 360; + } + angles.insert(angle); + c++; + if (c >= 4){ + break; + } + } + } + + // Verify angles are aligned to the corners. + for (double angle : angles){ + double n = angle - 45; + double q = std::round(n / 90.); + double m = n - 90. * q; + if (std::abs(m) > STAR_SPARKLE_ANGLE_TOLERANCE_DEGREES){ + return false; + } + } + + // Verify that all live pixels are near the diagonals. + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + if (!m_matrix.get(c, r)){ + continue; + } + double distance = std::sqrt(center_x*center_x + center_y*center_y); + ptrdiff_t dist_x = std::abs((ptrdiff_t)c - center_x); + ptrdiff_t dist_y = std::abs((ptrdiff_t)r - center_y); + ptrdiff_t dist = std::abs(dist_y - dist_x); + if (dist > 2 + distance / 5.){ + return false; + } + } + } + + return true; +} +bool RadialSparkleDetector::is_star() const{ + // Fewer than 5 regions, cannot be a star. + if (m_regions.size() < 5){ + return false; + } + + size_t width = m_object.width(); + size_t height = m_object.height(); + + // Area is too small. + if (width * height < 100){ + return false; + } + + // Make sure dimensions are roughly square-ish. + if (width > 2 * height || height > 2 * width){ + return false; + } + + // Compute angles for the 5 largest regions. + ptrdiff_t center_x = (ptrdiff_t)(m_object.center_of_gravity_x() - m_object.min_x); + ptrdiff_t center_y = (ptrdiff_t)(m_object.center_of_gravity_y() - m_object.min_y); + std::set angles; + size_t c = 0; + for (const auto& region : m_regions){ + ptrdiff_t x = (ptrdiff_t)region.second.center_of_gravity_x() - center_x; + ptrdiff_t y = (ptrdiff_t)region.second.center_of_gravity_y() - center_y; + double angle = std::atan2(y, x) * 57.29577951308232; + if (angle < 0){ + angle += 360; + } + angles.insert(angle); + c++; + if (c >= 5){ + break; + } + } + + // Attempt best fit. + bool match = false; + for (double angle : angles){ + size_t bad = 0; + uint8_t points = 0; + for (double test : angles){ + double n = test - angle; + double q = std::round(n / 72.); + points |= (size_t)1 << ((size_t)q % 5); + double m = n - 72. * q; + if (std::abs(m) > STAR_SPARKLE_ANGLE_TOLERANCE_DEGREES){ + bad++; + } + } + + // Not all 5 points are detected. + if ((points & 0x1f) != 0x1f){ + continue; + } + + // Bad angles. + if (bad <= 0){ + match = true; + break; + } + } + + return match; +} + + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h index 2eb63ec232..6c48fe27eb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorRadial.h @@ -1,47 +1,47 @@ -/* Shiny Sparkle Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SparkleDetector_H -#define PokemonAutomation_PokemonSwSh_SparkleDetector_H - -#include -#include -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -struct RadialSparkleDetector{ - using WaterfillObject = Kernels::Waterfill::WaterfillObject; - -public: - ~RadialSparkleDetector(); - RadialSparkleDetector(size_t screen_area, const WaterfillObject& obj); - - bool is_ball() const; - bool is_star() const; - -private: - const WaterfillObject& m_object; - PackedBinaryMatrix m_matrix; - - uint64_t m_radius_sqr; - std::multimap m_regions; -}; - - - - - -} -} -} -#endif +/* Shiny Sparkle Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SparkleDetector_H +#define PokemonAutomation_PokemonSwSh_SparkleDetector_H + +#include +#include +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +struct RadialSparkleDetector{ + using WaterfillObject = Kernels::Waterfill::WaterfillObject; + +public: + ~RadialSparkleDetector(); + RadialSparkleDetector(size_t screen_area, const WaterfillObject& obj); + + bool is_ball() const; + bool is_star() const; + +private: + const WaterfillObject& m_object; + PackedBinaryMatrix m_matrix; + + uint64_t m_radius_sqr; + std::multimap m_regions; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.cpp index 61647da557..24dfa894a3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.cpp @@ -1,721 +1,721 @@ -/* Square Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonTools/Images/DistanceToLine.h" -#include "PokemonSwSh_SparkleDetectorSquare.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -// Remove the background of 1's from "matrix". -// Return the background itself. -WaterfillObject remove_background(PackedBinaryMatrix& matrix){ - size_t width = matrix.width(); - size_t height = matrix.height(); - - std::unique_ptr session = make_WaterfillSession(matrix); - - WaterfillObject background; - for (size_t c = 0; c < width; c++){ - WaterfillObject object; - if (session->find_object_on_bit(object, true, c, 0)){ - background.merge_assume_no_overlap(object); - } - if (session->find_object_on_bit(object, true, c, height - 1)){ - background.merge_assume_no_overlap(object); - } - } - for (size_t r = 0; r < height; r++){ - WaterfillObject object; - if (session->find_object_on_bit(object, true, 0, r)){ - background.merge_assume_no_overlap(object); - } - if (session->find_object_on_bit(object, true, width - 1, r)){ - background.merge_assume_no_overlap(object); - } - } - return background; -} - - -// Remove the hole of 1's from "matrix" at location (x, y). -// Return the total area of the hole. -size_t remove_hole(PackedBinaryMatrix& matrix, size_t x, size_t y){ - std::unique_ptr session = make_WaterfillSession(matrix); - WaterfillObject object; - if (!session->find_object_on_bit(object, false, x, y)){ - return 0; - } - return object.area; -} - - -// Check if the object has a valid hole characteristic of a square. -bool check_hole( - WaterfillObject& background, - const PackedBinaryMatrix& object, - size_t box_area, size_t object_area, - size_t center_x, size_t center_y -){ - PackedBinaryMatrix inverted = object.copy(); - inverted.invert(); - - // Edge area is too large relative to the entire enclosing box. - background = remove_background(inverted); -// cout << "background_area = " << background.area << endl; -// if (background_area * 3 > box_area * 2){ -// return false; -// } - - // Hole is too small or doesn't exist. - size_t hole_area = remove_hole(inverted, center_x, center_y); -// cout << "hole_area = " << hole_area << endl; - if (hole_area < 20){ - return false; - } - - // Non-center hole area is more than 1/4 of the total hole area. - size_t total_hole_area = box_area - background.area - object_area; - size_t non_center_hole_area = total_hole_area - hole_area; - if (non_center_hole_area * 4 > total_hole_area){ -// cout << "bad hole" << endl; - return false; - } - - return true; -} - - -// Given object of 1's, zero all, but the locally furthest points. -// Return the list of locally furthest points. -struct Point2{ - size_t x = 0; - size_t y = 0; - double distance = 0; - double angle = 0; - bool remove = false; - - bool operator==(const Point2& point) const{ - return x == point.x && y == point.y; - } -}; -std::vector keep_furthest_points(const PackedBinaryMatrix& matrix, size_t center_x, size_t center_y){ - size_t width = matrix.width(); - size_t height = matrix.height(); - - std::vector points; - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - // Not part of the object. - if (!matrix.get(c, r)){ - continue; - } - - size_t my_dx2 = c - center_x; - size_t my_dy2 = r - center_y; - my_dx2 *= my_dx2; - my_dy2 *= my_dy2; - - { - size_t dx2 = c + 1 - center_x; - dx2 *= dx2; - if (dx2 > my_dx2 && c + 1 < width && matrix.get(c + 1, r)){ - continue; - } - } - { - size_t dx2 = c - 1 - center_x; - dx2 *= dx2; - if (dx2 > my_dx2 && c > 0 && matrix.get(c - 1, r)){ - continue; - } - } - { - size_t dy2 = r + 1 - center_y; - dy2 *= dy2; - if (dy2 > my_dy2 && r + 1 < height && matrix.get(c, r + 1)){ - continue; - } - } - { - size_t dy2 = r - 1 - center_y; - dy2 *= dy2; - if (dy2 > my_dy2 && r > 0 && matrix.get(c, r - 1)){ - continue; - } - } - - size_t my_distance = my_dx2 + my_dy2; - { - size_t dx2 = c + 1 - center_x; - size_t dy2 = r + 1 - center_y; - dx2 *= dx2; - dy2 *= dy2; - if (dx2 + dy2 > my_distance && c + 1 < width && r + 1 < height && matrix.get(c + 1, r + 1)){ - continue; - } - } - { - size_t dx2 = c - 1 - center_x; - size_t dy2 = r + 1 - center_y; - dx2 *= dx2; - dy2 *= dy2; - if (dx2 + dy2 > my_distance && c > 0 && r + 1 < height && matrix.get(c - 1, r + 1)){ - continue; - } - } - { - size_t dx2 = c + 1 - center_x; - size_t dy2 = r - 1 - center_y; - dx2 *= dx2; - dy2 *= dy2; - if (dx2 + dy2 > my_distance && c + 1 < width && r > 0 && matrix.get(c + 1, r - 1)){ - continue; - } - } - { - size_t dx2 = c - 1 - center_x; - size_t dy2 = r - 1 - center_y; - dx2 *= dx2; - dy2 *= dy2; - if (dx2 + dy2 > my_distance && c > 0 && r > 0 && matrix.get(c - 1, r - 1)){ - continue; - } - } - points.emplace_back( - Point2{c, r, std::sqrt(my_distance), 0, false} - ); - } - } - return points; -} - - -// Merge points that are close together - keeping the one that is further away. -void merge_nearby_points(std::map points, double min_distance_diff = 0.2){ - // Merge points that are close together. - const int DISTANCE_THRESHOLD = 5 * 5; - bool changed; - do{ - if (points.size() < 4){ - return; - } - - // Iterate adjacent points and merge points that are close together. - changed = false; - auto iter = points.begin(); - Point2* last = &iter->second; - ++iter; - for (; iter != points.end(); ++iter){ - Point2* current = &iter->second; - size_t dx = current->x - last->x; - size_t dy = current->y - last->y; - uint64_t distance = dx*dx + dy*dy; - if (distance < DISTANCE_THRESHOLD){ - if (current->distance + min_distance_diff < last->distance){ - current->remove = true; - changed = true; - } - if (current->distance > last->distance + min_distance_diff){ - last->remove = true; - changed = true; - } - } - last = current; - } - { - Point2* current = &points.begin()->second; - size_t dx = current->x - last->x; - size_t dy = current->y - last->y; - uint64_t distance = dx*dx + dy*dy; - if (distance < DISTANCE_THRESHOLD){ - if (current->distance + min_distance_diff < last->distance){ - current->remove = true; - changed = true; - } - if (current->distance > last->distance + min_distance_diff){ - last->remove = true; - changed = true; - } - } -// last = current; - } - - // Remove points marked for removal. - for (iter = points.begin(); iter != points.end();){ - if (iter->second.remove){ -// cout << "remove" << endl; - iter = points.erase(iter); - }else{ - ++iter; - } - } -// cout << "asdf" << endl; - }while (changed); -} - - -// Find the corner that is opposite to the specified corner. -// Returns false if no such corner is found. -bool find_opposite_corner( - const std::map& points_by_angle, - const Point2& source_corner, - Point2& opposite_corner -){ - double best_opposite = 0; - for (const auto& point : points_by_angle){ - double diff = point.second.angle - source_corner.angle; - if (diff >= 180){ - diff -= 360; - } - if (diff <= -180){ - diff += 360; - } - diff = std::abs(diff); - if (best_opposite < diff){ - best_opposite = diff; - opposite_corner = point.second; - } - } - if (best_opposite < 160){ -// cout << "bad angle = " << best_opposite << endl; - return false; - } - return true; -} - - -// -// An fmod() variant that reduces to [0, 360) degrees. -// -double normalize_angle_0_360_new(double angle){ - while (angle < 0){ - angle += 360; - } - while (angle >= 360){ - angle -= 360; - } - return angle; -} - - -// Get all the pixels that border the background. -std::multimap> get_edge_pixels( - const PackedBinaryMatrix& object, - const WaterfillObject& background, - size_t center_x, size_t center_y, - double base_angle -){ - size_t width = object.width(); - size_t height = object.height(); - - std::multimap> edge_pixels; - if (background.area == 0){ - // No background. Grab the entire edge. - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - // Not part of the object. - if (!object.get(c, r)){ - continue; - } - if (c == 0 || r == 0 || c == width - 1 || r == height - 1){ - double angle = std::atan2( - (ptrdiff_t)r - (ptrdiff_t)center_y, - (ptrdiff_t)c - (ptrdiff_t)center_x - ) * 57.295779513082320877; - angle = normalize_angle_0_360_new(angle - base_angle); - edge_pixels.emplace( - angle, - std::pair{c, r} - ); - } - } - } - return edge_pixels; - } - - PackedBinaryMatrix background_matrix = background.object->submatrix(0, 0, width, height); - for (size_t r = 0; r < height; r++){ - for (size_t c = 0; c < width; c++){ - // Not part of the object. - if (!object.get(c, r)){ - continue; - } - if (c == 0 || r == 0 || c == width - 1 || r == height - 1 || - background_matrix.get(c - 1, r) || - background_matrix.get(c + 1, r) || - background_matrix.get(c, r - 1) || - background_matrix.get(c, r + 1) - ){ - double angle = std::atan2( - (ptrdiff_t)r - (ptrdiff_t)center_y, - (ptrdiff_t)c - (ptrdiff_t)center_x - ) * 57.295779513082320877; - angle = normalize_angle_0_360_new(angle - base_angle); - edge_pixels.emplace( - angle, - std::pair{c, r} - ); - } - } - } - return edge_pixels; -} - - -double area_of_triangle( - ptrdiff_t x0, ptrdiff_t y0, - ptrdiff_t x1, ptrdiff_t y1, - ptrdiff_t x2, ptrdiff_t y2 -){ - return ((double)(x0 - x2) * (y1 - y0) - (double)(x0 - x1) * (y2 - y0)) * 0.5; -} - - -// -// Given a set of points, "points_by_angle" with angles "point_lo_angle" -// and "point_hi_angle", compute the sum of squares of distances of the -// points to the line that intersects: -// [point_lo_x, point_lo_y] -// [point_hi_x, point_hi_y] -// -double sum_squares_from_line( - const std::multimap>& points_by_angle, - double point_lo_angle, size_t point_lo_x, size_t point_lo_y, - double point_hi_angle, size_t point_hi_x, size_t point_hi_y -){ -// cout << "Point 0: angle = " << point_lo_angle << ", [" << point_lo_x << "," << point_lo_y << "]" << endl; -// cout << "Point 1: angle = " << point_hi_angle << ", [" << point_hi_x << "," << point_hi_y << "]" << endl; - -// size_t count = 0; -// double sum = 0; - double sum_sqr = 0; - - auto iter0 = points_by_angle.lower_bound(point_lo_angle); - auto iter1 = points_by_angle.lower_bound(point_hi_angle); - DistanceToLine calc( - point_lo_x, point_lo_y, - point_hi_x, point_hi_y - ); - for (; iter0 != iter1; ++iter0){ - double dist_sqr = calc.distance_squared(iter0->second.first, iter0->second.second); -// cout << "(" << iter0->second.first << "," << iter0->second.second << "), dist_sqr = " << dist_sqr << endl; - sum_sqr += dist_sqr; - } -// cout << "average distance = " << sum / count << endl; - return sum_sqr; -} - - - -bool is_square_sparkle(const Kernels::Waterfill::WaterfillObject& object, double max_deviation){ - size_t width = object.width(); - size_t height = object.height(); -// cout << "width = " << width << endl; -// cout << "height = " << height << endl; - if (width < 10 || height < 10){ - return false; - } - - size_t box_area = width * height; - const PackedBinaryMatrix matrix = object.packed_matrix(); - - size_t center_x = (size_t)object.center_of_gravity_x() - object.min_x; - size_t center_y = (size_t)object.center_of_gravity_y() - object.min_y; - - - // Check the hole. - WaterfillObject background; - if (!check_hole(background, matrix, box_area, object.area, center_x, center_y)){ - return false; - } - - std::vector corner_candidates = keep_furthest_points(matrix, center_x, center_y); -// cout << matrix.dump() << endl; -// for (const Point2& point : corner_candidates){ -// cout << "(" << point.x << ", " << point.y << ")" << endl; -// } - - // Too few points. - if (corner_candidates.size() < 4){ -// cout << "too few points" << endl; - return false; - } - - - // Calculate angles. - Point2 far_corner0; - std::map points_by_angle; - { - for (auto& point : corner_candidates){ - double angle = std::atan2( - (int64_t)(point.y - center_y), - (int64_t)(point.x - center_x) - ) * 57.295779513082320877; - - point.angle = angle; - points_by_angle.emplace(angle, point); - if (far_corner0.distance < point.distance){ - far_corner0 = point; - } -// cout << angle << " : distance = " << point.distance << ": " << point.x << ", " << point.y << endl; - } - if (points_by_angle.size() < 4){ - return false; - } - corner_candidates.clear(); - } - - - // Merge points that are close together. - merge_nearby_points(points_by_angle); - if (points_by_angle.size() < 4){ - return false; - } - -#if 0 - for (const auto& point : points_by_angle){ - cout << point.first - << " : distance = " << point.second.distance - << ": " << point.second.x << ", " << point.second.y << endl; - } -#endif - - - // Look for a point opposite to the furthest. - Point2 far_corner1; - if (!find_opposite_corner(points_by_angle, far_corner0, far_corner1)){ - return false; - } - double far_corner1_angle = normalize_angle_0_360_new(far_corner1.angle - far_corner0.angle); -// cout << "far_corner1_angle = " << far_corner1_angle << endl; - - - // Build sets of points on each edge. - std::map edge0; - std::map edge1; - for (const auto& point : points_by_angle){ - // Skip the two far corners. - if (point.second == far_corner0 || point.second == far_corner1){ - continue; - } - double diff = normalize_angle_0_360_new(point.second.angle - far_corner0.angle); - if (diff < far_corner1_angle){ - edge0[diff] = point.second; - }else{ - edge1[diff] = point.second; - } - } - - - // Get all the edge pixels. - std::multimap> edge_pixels = get_edge_pixels( - matrix, background, - center_x, center_y, far_corner0.angle - ); - if (edge_pixels.empty()){ - return false; - } -// cout << "edge_pixels.size() = " << edge_pixels.size() << endl; -// for (const auto& item : points_by_angle){ -// cout << item.first << " : distance = " << item.second.distance << ", (" << item.second.x << "," << item.second.y << ")" << endl; -// } - - - PackedBinaryMatrix test(width, height); - for (const auto& item : edge_pixels){ - test.set(item.second.first, item.second.second, true); - } -// cout << test.dump() << endl; - - - // Attempt to find linear regression fit. - double size_scaling = (double)1 / (width + height); - for (const auto& near_corner0 : edge0){ - double lo = std::max(near_corner0.first + 160, far_corner1_angle); - double hi = std::min(near_corner0.first + 200, 360.); - - auto near_corner1_iter0 = edge1.lower_bound(lo); - auto near_corner1_iter1 = edge1.upper_bound(hi); - if (near_corner1_iter0 == near_corner1_iter1){ - // No compatible corner. - continue; - } -// cout << near_corner1_iter0->first -// << " : distance = " << near_corner1_iter0->second.distance -// << ", (" << near_corner1_iter0->second.x -// << "," << near_corner1_iter0->second.y << ")" << endl; - - // Calculate things on 2 of the edges. - double sum_edge0 = sum_squares_from_line( - edge_pixels, - 0, far_corner0.x, far_corner0.y, - near_corner0.first, near_corner0.second.x, near_corner0.second.y - ); - double sum_edge1 = sum_squares_from_line( - edge_pixels, - near_corner0.first, near_corner0.second.x, near_corner0.second.y, - far_corner1_angle, far_corner1.x, far_corner1.y - ); -// cout << "sum_edge0 = " << sum_edge0 << endl; -// cout << "sum_edge1 = " << sum_edge1 << endl; - double area0 = area_of_triangle( - center_x, center_y, - far_corner0.x, far_corner0.y, - near_corner0.second.x, near_corner0.second.y - ); - double area1 = area_of_triangle( - center_x, center_y, - near_corner0.second.x, near_corner0.second.y, - far_corner1.x, far_corner1.y - ); - - // Iterate through the candidate corners on the other side. - for (; near_corner1_iter0 != near_corner1_iter1; ++near_corner1_iter0){ - double sum_edge2 = sum_squares_from_line( - edge_pixels, - far_corner1_angle, far_corner1.x, far_corner1.y, - near_corner1_iter0->first, near_corner1_iter0->second.x, near_corner1_iter0->second.y - ); - double sum_edge3 = sum_squares_from_line( - edge_pixels, - near_corner1_iter0->first, near_corner1_iter0->second.x, near_corner1_iter0->second.y, - 360, far_corner0.x, far_corner0.y - ); - double area2 = area_of_triangle( - center_x, center_y, - far_corner1.x, far_corner1.y, - near_corner1_iter0->second.x, near_corner1_iter0->second.y - ); - double area3 = area_of_triangle( - center_x, center_y, - near_corner1_iter0->second.x, near_corner1_iter0->second.y, - far_corner0.x, far_corner0.y - ); - - double sum_squares = sum_edge0 + sum_edge1 + sum_edge2 + sum_edge3; - double normalized_distance = std::sqrt(sum_squares / edge_pixels.size()); - - normalized_distance *= size_scaling; -// cout << "normalized_distance = " << normalized_distance << endl; - - // Too much deviation from edges. - if (normalized_distance > max_deviation){ - continue; - } - - double regression_area = area0 + area1 + area2 + area3; - size_t actual_object_area = width * height - background.area; -// cout << "area = " << regression_area << " / " << actual_object_area << endl; - - if (actual_object_area < regression_area){ - continue; - } - -// cout << "image: " << c << endl; -// cout << "normalized_distance = " << normalized_distance << endl; -// dump_matrix(submatrix, center_x, center_y, points_by_angle); - return true; - } - } - - return false; -} - - - - -bool is_line_sparkle(const Kernels::Waterfill::WaterfillObject& object, size_t min_pixel_width){ - size_t width = object.width(); - size_t height = object.height(); - if (width < 5 || height < 5){ - return false; - } - if (width < min_pixel_width){ - return false; - } - if ((size_t)width * width < object.area * 50){ - return false; - } - if (width < height * 10){ - return false; - } - - PackedBinaryMatrix matrix = object.packed_matrix(); - - // Make sure it's actually a line. - - std::vector heights(width); - bool row_ok = false; -// cout << "{"; - for (size_t r = 0; r < matrix.height(); r++){ -// cout << " {"; - size_t length = 0; - size_t longest = 0; - for (size_t c = 0; c < matrix.width(); c++){ -// cout << matrix[r][c] << ", "; - if (matrix.get(c, r)){ - length++; - longest = std::max(longest, length); - heights[c]++; - }else{ - length = 0; - } - } -// cout << "}," << endl; - if (length >= min_pixel_width){ - row_ok = true; - } - } -// cout << "}" << endl; - if (!row_ok){ - return false; - } - - // Make sure the bulge is not on the edge. - size_t thickest = 0; - size_t thickest_column = 0; - for (size_t c = 0; c < width; c++){ - size_t h = heights[c]; -// cout << h << ", "; - if (thickest < h){ - thickest = h; - thickest_column = c; - } - } - - size_t diff_left = thickest_column; - size_t diff_right = width - thickest_column; -// cout << diff_left << " : " << diff_right << endl; - if (diff_left * 10 < diff_right){ -// cout << "line is off-center" << endl; - return false; - } - if (diff_right * 10 < diff_left){ -// cout << "line is off-center" << endl; - return false; - } - -// cout << width << " x " << height << endl; - - return true; -} - - - -} -} -} +/* Square Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonTools/Images/DistanceToLine.h" +#include "PokemonSwSh_SparkleDetectorSquare.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +// Remove the background of 1's from "matrix". +// Return the background itself. +WaterfillObject remove_background(PackedBinaryMatrix& matrix){ + size_t width = matrix.width(); + size_t height = matrix.height(); + + std::unique_ptr session = make_WaterfillSession(matrix); + + WaterfillObject background; + for (size_t c = 0; c < width; c++){ + WaterfillObject object; + if (session->find_object_on_bit(object, true, c, 0)){ + background.merge_assume_no_overlap(object); + } + if (session->find_object_on_bit(object, true, c, height - 1)){ + background.merge_assume_no_overlap(object); + } + } + for (size_t r = 0; r < height; r++){ + WaterfillObject object; + if (session->find_object_on_bit(object, true, 0, r)){ + background.merge_assume_no_overlap(object); + } + if (session->find_object_on_bit(object, true, width - 1, r)){ + background.merge_assume_no_overlap(object); + } + } + return background; +} + + +// Remove the hole of 1's from "matrix" at location (x, y). +// Return the total area of the hole. +size_t remove_hole(PackedBinaryMatrix& matrix, size_t x, size_t y){ + std::unique_ptr session = make_WaterfillSession(matrix); + WaterfillObject object; + if (!session->find_object_on_bit(object, false, x, y)){ + return 0; + } + return object.area; +} + + +// Check if the object has a valid hole characteristic of a square. +bool check_hole( + WaterfillObject& background, + const PackedBinaryMatrix& object, + size_t box_area, size_t object_area, + size_t center_x, size_t center_y +){ + PackedBinaryMatrix inverted = object.copy(); + inverted.invert(); + + // Edge area is too large relative to the entire enclosing box. + background = remove_background(inverted); +// cout << "background_area = " << background.area << endl; +// if (background_area * 3 > box_area * 2){ +// return false; +// } + + // Hole is too small or doesn't exist. + size_t hole_area = remove_hole(inverted, center_x, center_y); +// cout << "hole_area = " << hole_area << endl; + if (hole_area < 20){ + return false; + } + + // Non-center hole area is more than 1/4 of the total hole area. + size_t total_hole_area = box_area - background.area - object_area; + size_t non_center_hole_area = total_hole_area - hole_area; + if (non_center_hole_area * 4 > total_hole_area){ +// cout << "bad hole" << endl; + return false; + } + + return true; +} + + +// Given object of 1's, zero all, but the locally furthest points. +// Return the list of locally furthest points. +struct Point2{ + size_t x = 0; + size_t y = 0; + double distance = 0; + double angle = 0; + bool remove = false; + + bool operator==(const Point2& point) const{ + return x == point.x && y == point.y; + } +}; +std::vector keep_furthest_points(const PackedBinaryMatrix& matrix, size_t center_x, size_t center_y){ + size_t width = matrix.width(); + size_t height = matrix.height(); + + std::vector points; + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + // Not part of the object. + if (!matrix.get(c, r)){ + continue; + } + + size_t my_dx2 = c - center_x; + size_t my_dy2 = r - center_y; + my_dx2 *= my_dx2; + my_dy2 *= my_dy2; + + { + size_t dx2 = c + 1 - center_x; + dx2 *= dx2; + if (dx2 > my_dx2 && c + 1 < width && matrix.get(c + 1, r)){ + continue; + } + } + { + size_t dx2 = c - 1 - center_x; + dx2 *= dx2; + if (dx2 > my_dx2 && c > 0 && matrix.get(c - 1, r)){ + continue; + } + } + { + size_t dy2 = r + 1 - center_y; + dy2 *= dy2; + if (dy2 > my_dy2 && r + 1 < height && matrix.get(c, r + 1)){ + continue; + } + } + { + size_t dy2 = r - 1 - center_y; + dy2 *= dy2; + if (dy2 > my_dy2 && r > 0 && matrix.get(c, r - 1)){ + continue; + } + } + + size_t my_distance = my_dx2 + my_dy2; + { + size_t dx2 = c + 1 - center_x; + size_t dy2 = r + 1 - center_y; + dx2 *= dx2; + dy2 *= dy2; + if (dx2 + dy2 > my_distance && c + 1 < width && r + 1 < height && matrix.get(c + 1, r + 1)){ + continue; + } + } + { + size_t dx2 = c - 1 - center_x; + size_t dy2 = r + 1 - center_y; + dx2 *= dx2; + dy2 *= dy2; + if (dx2 + dy2 > my_distance && c > 0 && r + 1 < height && matrix.get(c - 1, r + 1)){ + continue; + } + } + { + size_t dx2 = c + 1 - center_x; + size_t dy2 = r - 1 - center_y; + dx2 *= dx2; + dy2 *= dy2; + if (dx2 + dy2 > my_distance && c + 1 < width && r > 0 && matrix.get(c + 1, r - 1)){ + continue; + } + } + { + size_t dx2 = c - 1 - center_x; + size_t dy2 = r - 1 - center_y; + dx2 *= dx2; + dy2 *= dy2; + if (dx2 + dy2 > my_distance && c > 0 && r > 0 && matrix.get(c - 1, r - 1)){ + continue; + } + } + points.emplace_back( + Point2{c, r, std::sqrt(my_distance), 0, false} + ); + } + } + return points; +} + + +// Merge points that are close together - keeping the one that is further away. +void merge_nearby_points(std::map points, double min_distance_diff = 0.2){ + // Merge points that are close together. + const int DISTANCE_THRESHOLD = 5 * 5; + bool changed; + do{ + if (points.size() < 4){ + return; + } + + // Iterate adjacent points and merge points that are close together. + changed = false; + auto iter = points.begin(); + Point2* last = &iter->second; + ++iter; + for (; iter != points.end(); ++iter){ + Point2* current = &iter->second; + size_t dx = current->x - last->x; + size_t dy = current->y - last->y; + uint64_t distance = dx*dx + dy*dy; + if (distance < DISTANCE_THRESHOLD){ + if (current->distance + min_distance_diff < last->distance){ + current->remove = true; + changed = true; + } + if (current->distance > last->distance + min_distance_diff){ + last->remove = true; + changed = true; + } + } + last = current; + } + { + Point2* current = &points.begin()->second; + size_t dx = current->x - last->x; + size_t dy = current->y - last->y; + uint64_t distance = dx*dx + dy*dy; + if (distance < DISTANCE_THRESHOLD){ + if (current->distance + min_distance_diff < last->distance){ + current->remove = true; + changed = true; + } + if (current->distance > last->distance + min_distance_diff){ + last->remove = true; + changed = true; + } + } +// last = current; + } + + // Remove points marked for removal. + for (iter = points.begin(); iter != points.end();){ + if (iter->second.remove){ +// cout << "remove" << endl; + iter = points.erase(iter); + }else{ + ++iter; + } + } +// cout << "asdf" << endl; + }while (changed); +} + + +// Find the corner that is opposite to the specified corner. +// Returns false if no such corner is found. +bool find_opposite_corner( + const std::map& points_by_angle, + const Point2& source_corner, + Point2& opposite_corner +){ + double best_opposite = 0; + for (const auto& point : points_by_angle){ + double diff = point.second.angle - source_corner.angle; + if (diff >= 180){ + diff -= 360; + } + if (diff <= -180){ + diff += 360; + } + diff = std::abs(diff); + if (best_opposite < diff){ + best_opposite = diff; + opposite_corner = point.second; + } + } + if (best_opposite < 160){ +// cout << "bad angle = " << best_opposite << endl; + return false; + } + return true; +} + + +// +// An fmod() variant that reduces to [0, 360) degrees. +// +double normalize_angle_0_360_new(double angle){ + while (angle < 0){ + angle += 360; + } + while (angle >= 360){ + angle -= 360; + } + return angle; +} + + +// Get all the pixels that border the background. +std::multimap> get_edge_pixels( + const PackedBinaryMatrix& object, + const WaterfillObject& background, + size_t center_x, size_t center_y, + double base_angle +){ + size_t width = object.width(); + size_t height = object.height(); + + std::multimap> edge_pixels; + if (background.area == 0){ + // No background. Grab the entire edge. + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + // Not part of the object. + if (!object.get(c, r)){ + continue; + } + if (c == 0 || r == 0 || c == width - 1 || r == height - 1){ + double angle = std::atan2( + (ptrdiff_t)r - (ptrdiff_t)center_y, + (ptrdiff_t)c - (ptrdiff_t)center_x + ) * 57.295779513082320877; + angle = normalize_angle_0_360_new(angle - base_angle); + edge_pixels.emplace( + angle, + std::pair{c, r} + ); + } + } + } + return edge_pixels; + } + + PackedBinaryMatrix background_matrix = background.object->submatrix(0, 0, width, height); + for (size_t r = 0; r < height; r++){ + for (size_t c = 0; c < width; c++){ + // Not part of the object. + if (!object.get(c, r)){ + continue; + } + if (c == 0 || r == 0 || c == width - 1 || r == height - 1 || + background_matrix.get(c - 1, r) || + background_matrix.get(c + 1, r) || + background_matrix.get(c, r - 1) || + background_matrix.get(c, r + 1) + ){ + double angle = std::atan2( + (ptrdiff_t)r - (ptrdiff_t)center_y, + (ptrdiff_t)c - (ptrdiff_t)center_x + ) * 57.295779513082320877; + angle = normalize_angle_0_360_new(angle - base_angle); + edge_pixels.emplace( + angle, + std::pair{c, r} + ); + } + } + } + return edge_pixels; +} + + +double area_of_triangle( + ptrdiff_t x0, ptrdiff_t y0, + ptrdiff_t x1, ptrdiff_t y1, + ptrdiff_t x2, ptrdiff_t y2 +){ + return ((double)(x0 - x2) * (y1 - y0) - (double)(x0 - x1) * (y2 - y0)) * 0.5; +} + + +// +// Given a set of points, "points_by_angle" with angles "point_lo_angle" +// and "point_hi_angle", compute the sum of squares of distances of the +// points to the line that intersects: +// [point_lo_x, point_lo_y] +// [point_hi_x, point_hi_y] +// +double sum_squares_from_line( + const std::multimap>& points_by_angle, + double point_lo_angle, size_t point_lo_x, size_t point_lo_y, + double point_hi_angle, size_t point_hi_x, size_t point_hi_y +){ +// cout << "Point 0: angle = " << point_lo_angle << ", [" << point_lo_x << "," << point_lo_y << "]" << endl; +// cout << "Point 1: angle = " << point_hi_angle << ", [" << point_hi_x << "," << point_hi_y << "]" << endl; + +// size_t count = 0; +// double sum = 0; + double sum_sqr = 0; + + auto iter0 = points_by_angle.lower_bound(point_lo_angle); + auto iter1 = points_by_angle.lower_bound(point_hi_angle); + DistanceToLine calc( + point_lo_x, point_lo_y, + point_hi_x, point_hi_y + ); + for (; iter0 != iter1; ++iter0){ + double dist_sqr = calc.distance_squared(iter0->second.first, iter0->second.second); +// cout << "(" << iter0->second.first << "," << iter0->second.second << "), dist_sqr = " << dist_sqr << endl; + sum_sqr += dist_sqr; + } +// cout << "average distance = " << sum / count << endl; + return sum_sqr; +} + + + +bool is_square_sparkle(const Kernels::Waterfill::WaterfillObject& object, double max_deviation){ + size_t width = object.width(); + size_t height = object.height(); +// cout << "width = " << width << endl; +// cout << "height = " << height << endl; + if (width < 10 || height < 10){ + return false; + } + + size_t box_area = width * height; + const PackedBinaryMatrix matrix = object.packed_matrix(); + + size_t center_x = (size_t)object.center_of_gravity_x() - object.min_x; + size_t center_y = (size_t)object.center_of_gravity_y() - object.min_y; + + + // Check the hole. + WaterfillObject background; + if (!check_hole(background, matrix, box_area, object.area, center_x, center_y)){ + return false; + } + + std::vector corner_candidates = keep_furthest_points(matrix, center_x, center_y); +// cout << matrix.dump() << endl; +// for (const Point2& point : corner_candidates){ +// cout << "(" << point.x << ", " << point.y << ")" << endl; +// } + + // Too few points. + if (corner_candidates.size() < 4){ +// cout << "too few points" << endl; + return false; + } + + + // Calculate angles. + Point2 far_corner0; + std::map points_by_angle; + { + for (auto& point : corner_candidates){ + double angle = std::atan2( + (int64_t)(point.y - center_y), + (int64_t)(point.x - center_x) + ) * 57.295779513082320877; + + point.angle = angle; + points_by_angle.emplace(angle, point); + if (far_corner0.distance < point.distance){ + far_corner0 = point; + } +// cout << angle << " : distance = " << point.distance << ": " << point.x << ", " << point.y << endl; + } + if (points_by_angle.size() < 4){ + return false; + } + corner_candidates.clear(); + } + + + // Merge points that are close together. + merge_nearby_points(points_by_angle); + if (points_by_angle.size() < 4){ + return false; + } + +#if 0 + for (const auto& point : points_by_angle){ + cout << point.first + << " : distance = " << point.second.distance + << ": " << point.second.x << ", " << point.second.y << endl; + } +#endif + + + // Look for a point opposite to the furthest. + Point2 far_corner1; + if (!find_opposite_corner(points_by_angle, far_corner0, far_corner1)){ + return false; + } + double far_corner1_angle = normalize_angle_0_360_new(far_corner1.angle - far_corner0.angle); +// cout << "far_corner1_angle = " << far_corner1_angle << endl; + + + // Build sets of points on each edge. + std::map edge0; + std::map edge1; + for (const auto& point : points_by_angle){ + // Skip the two far corners. + if (point.second == far_corner0 || point.second == far_corner1){ + continue; + } + double diff = normalize_angle_0_360_new(point.second.angle - far_corner0.angle); + if (diff < far_corner1_angle){ + edge0[diff] = point.second; + }else{ + edge1[diff] = point.second; + } + } + + + // Get all the edge pixels. + std::multimap> edge_pixels = get_edge_pixels( + matrix, background, + center_x, center_y, far_corner0.angle + ); + if (edge_pixels.empty()){ + return false; + } +// cout << "edge_pixels.size() = " << edge_pixels.size() << endl; +// for (const auto& item : points_by_angle){ +// cout << item.first << " : distance = " << item.second.distance << ", (" << item.second.x << "," << item.second.y << ")" << endl; +// } + + + PackedBinaryMatrix test(width, height); + for (const auto& item : edge_pixels){ + test.set(item.second.first, item.second.second, true); + } +// cout << test.dump() << endl; + + + // Attempt to find linear regression fit. + double size_scaling = (double)1 / (width + height); + for (const auto& near_corner0 : edge0){ + double lo = std::max(near_corner0.first + 160, far_corner1_angle); + double hi = std::min(near_corner0.first + 200, 360.); + + auto near_corner1_iter0 = edge1.lower_bound(lo); + auto near_corner1_iter1 = edge1.upper_bound(hi); + if (near_corner1_iter0 == near_corner1_iter1){ + // No compatible corner. + continue; + } +// cout << near_corner1_iter0->first +// << " : distance = " << near_corner1_iter0->second.distance +// << ", (" << near_corner1_iter0->second.x +// << "," << near_corner1_iter0->second.y << ")" << endl; + + // Calculate things on 2 of the edges. + double sum_edge0 = sum_squares_from_line( + edge_pixels, + 0, far_corner0.x, far_corner0.y, + near_corner0.first, near_corner0.second.x, near_corner0.second.y + ); + double sum_edge1 = sum_squares_from_line( + edge_pixels, + near_corner0.first, near_corner0.second.x, near_corner0.second.y, + far_corner1_angle, far_corner1.x, far_corner1.y + ); +// cout << "sum_edge0 = " << sum_edge0 << endl; +// cout << "sum_edge1 = " << sum_edge1 << endl; + double area0 = area_of_triangle( + center_x, center_y, + far_corner0.x, far_corner0.y, + near_corner0.second.x, near_corner0.second.y + ); + double area1 = area_of_triangle( + center_x, center_y, + near_corner0.second.x, near_corner0.second.y, + far_corner1.x, far_corner1.y + ); + + // Iterate through the candidate corners on the other side. + for (; near_corner1_iter0 != near_corner1_iter1; ++near_corner1_iter0){ + double sum_edge2 = sum_squares_from_line( + edge_pixels, + far_corner1_angle, far_corner1.x, far_corner1.y, + near_corner1_iter0->first, near_corner1_iter0->second.x, near_corner1_iter0->second.y + ); + double sum_edge3 = sum_squares_from_line( + edge_pixels, + near_corner1_iter0->first, near_corner1_iter0->second.x, near_corner1_iter0->second.y, + 360, far_corner0.x, far_corner0.y + ); + double area2 = area_of_triangle( + center_x, center_y, + far_corner1.x, far_corner1.y, + near_corner1_iter0->second.x, near_corner1_iter0->second.y + ); + double area3 = area_of_triangle( + center_x, center_y, + near_corner1_iter0->second.x, near_corner1_iter0->second.y, + far_corner0.x, far_corner0.y + ); + + double sum_squares = sum_edge0 + sum_edge1 + sum_edge2 + sum_edge3; + double normalized_distance = std::sqrt(sum_squares / edge_pixels.size()); + + normalized_distance *= size_scaling; +// cout << "normalized_distance = " << normalized_distance << endl; + + // Too much deviation from edges. + if (normalized_distance > max_deviation){ + continue; + } + + double regression_area = area0 + area1 + area2 + area3; + size_t actual_object_area = width * height - background.area; +// cout << "area = " << regression_area << " / " << actual_object_area << endl; + + if (actual_object_area < regression_area){ + continue; + } + +// cout << "image: " << c << endl; +// cout << "normalized_distance = " << normalized_distance << endl; +// dump_matrix(submatrix, center_x, center_y, points_by_angle); + return true; + } + } + + return false; +} + + + + +bool is_line_sparkle(const Kernels::Waterfill::WaterfillObject& object, size_t min_pixel_width){ + size_t width = object.width(); + size_t height = object.height(); + if (width < 5 || height < 5){ + return false; + } + if (width < min_pixel_width){ + return false; + } + if ((size_t)width * width < object.area * 50){ + return false; + } + if (width < height * 10){ + return false; + } + + PackedBinaryMatrix matrix = object.packed_matrix(); + + // Make sure it's actually a line. + + std::vector heights(width); + bool row_ok = false; +// cout << "{"; + for (size_t r = 0; r < matrix.height(); r++){ +// cout << " {"; + size_t length = 0; + size_t longest = 0; + for (size_t c = 0; c < matrix.width(); c++){ +// cout << matrix[r][c] << ", "; + if (matrix.get(c, r)){ + length++; + longest = std::max(longest, length); + heights[c]++; + }else{ + length = 0; + } + } +// cout << "}," << endl; + if (length >= min_pixel_width){ + row_ok = true; + } + } +// cout << "}" << endl; + if (!row_ok){ + return false; + } + + // Make sure the bulge is not on the edge. + size_t thickest = 0; + size_t thickest_column = 0; + for (size_t c = 0; c < width; c++){ + size_t h = heights[c]; +// cout << h << ", "; + if (thickest < h){ + thickest = h; + thickest_column = c; + } + } + + size_t diff_left = thickest_column; + size_t diff_right = width - thickest_column; +// cout << diff_left << " : " << diff_right << endl; + if (diff_left * 10 < diff_right){ +// cout << "line is off-center" << endl; + return false; + } + if (diff_right * 10 < diff_left){ +// cout << "line is off-center" << endl; + return false; + } + +// cout << width << " x " << height << endl; + + return true; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h index 0a356a7aa1..cc71b11b62 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_SparkleDetectorSquare.h @@ -1,37 +1,37 @@ -/* Square Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SquareDetector_H -#define PokemonAutomation_PokemonSwSh_SquareDetector_H - -#include - -namespace PokemonAutomation{ -namespace Kernels{ -namespace Waterfill{ - -class WaterfillObject; - -} -} -} - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -bool is_square_sparkle(const Kernels::Waterfill::WaterfillObject& object, double max_deviation = 0.04); -bool is_line_sparkle(const Kernels::Waterfill::WaterfillObject& object, size_t min_pixel_width = 100); - - - - -} -} -} -#endif +/* Square Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SquareDetector_H +#define PokemonAutomation_PokemonSwSh_SquareDetector_H + +#include + +namespace PokemonAutomation{ +namespace Kernels{ +namespace Waterfill{ + +class WaterfillObject; + +} +} +} + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +bool is_square_sparkle(const Kernels::Waterfill::WaterfillObject& object, double max_deviation = 0.04); +bool is_line_sparkle(const Kernels::Waterfill::WaterfillObject& object, size_t min_pixel_width = 100); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.cpp b/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.cpp index a20360a58d..14508a21de 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.cpp @@ -1,52 +1,52 @@ -/* Berry Tree Rustling Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "CommonTools/Audio/SpectrogramMatcher.h" -#include "CommonTools/Audio/AudioTemplateCache.h" -#include "PokemonSwSh_BerryTreeRustlingSoundDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -BerryTreeRustlingSoundDetector::BerryTreeRustlingSoundDetector( - VideoStream& stream, - DetectedCallback detected_callback, - float threshold -) - // Use a red as the detection color because the Levelball is made using red apricorns. - : AudioPerSpectrumDetectorBase( - stream.logger(), - "BerryTreeRustlingSoundDetector", - "Berry tree rustling sound", - COLOR_RED, - detected_callback - ) - , m_threshold(threshold) -{} - - -float BerryTreeRustlingSoundDetector::get_score_threshold() const{ - return m_threshold; -} - -std::unique_ptr BerryTreeRustlingSoundDetector::build_spectrogram_matcher(size_t sample_rate){ - return std::make_unique( - "Berry Rustle", - AudioTemplateCache::instance().get_throw("PokemonSwSh/BerryTreeRustlingSound", sample_rate), - SpectrogramMatcher::Mode::RAW, sample_rate, - 2000, - 1 - ); -} - - - -} -} -} +/* Berry Tree Rustling Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "CommonTools/Audio/SpectrogramMatcher.h" +#include "CommonTools/Audio/AudioTemplateCache.h" +#include "PokemonSwSh_BerryTreeRustlingSoundDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +BerryTreeRustlingSoundDetector::BerryTreeRustlingSoundDetector( + VideoStream& stream, + DetectedCallback detected_callback, + float threshold +) + // Use a red as the detection color because the Levelball is made using red apricorns. + : AudioPerSpectrumDetectorBase( + stream.logger(), + "BerryTreeRustlingSoundDetector", + "Berry tree rustling sound", + COLOR_RED, + detected_callback + ) + , m_threshold(threshold) +{} + + +float BerryTreeRustlingSoundDetector::get_score_threshold() const{ + return m_threshold; +} + +std::unique_ptr BerryTreeRustlingSoundDetector::build_spectrogram_matcher(size_t sample_rate){ + return std::make_unique( + "Berry Rustle", + AudioTemplateCache::instance().get_throw("PokemonSwSh/BerryTreeRustlingSound", sample_rate), + SpectrogramMatcher::Mode::RAW, sample_rate, + 2000, + 1 + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h b/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h index 500b9d9cb6..dcfd394ea2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h +++ b/SerialPrograms/Source/PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h @@ -1,44 +1,44 @@ -/* Berry Tree Rustling Sound Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BerryTreeRustlingSoundDetector_H -#define PokemonAutomation_PokemonSwSh_BerryTreeRustlingSoundDetector_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" - -namespace PokemonAutomation{ - class SpectrogramMatcher; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BerryTreeRustlingSoundDetector : public AudioPerSpectrumDetectorBase{ -public: - // Warning: The callback will be called from the audio inference thread. - BerryTreeRustlingSoundDetector( - VideoStream& stream, - DetectedCallback detected_callback, - float threshold - ); - - // Implement AudioPerSpectrumDetectorBase::get_score_threshold() - virtual float get_score_threshold() const override; - -protected: - // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() - virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; - - float m_threshold; -}; - - - - -} -} -} -#endif +/* Berry Tree Rustling Sound Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BerryTreeRustlingSoundDetector_H +#define PokemonAutomation_PokemonSwSh_BerryTreeRustlingSoundDetector_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/Audio/AudioPerSpectrumDetectorBase.h" + +namespace PokemonAutomation{ + class SpectrogramMatcher; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BerryTreeRustlingSoundDetector : public AudioPerSpectrumDetectorBase{ +public: + // Warning: The callback will be called from the audio inference thread. + BerryTreeRustlingSoundDetector( + VideoStream& stream, + DetectedCallback detected_callback, + float threshold + ); + + // Implement AudioPerSpectrumDetectorBase::get_score_threshold() + virtual float get_score_threshold() const override; + +protected: + // Implement AudioPerSpectrumDetectorBase::build_spectrogram_matcher() + virtual std::unique_ptr build_spectrogram_matcher(size_t sample_rate) override; + + float m_threshold; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.cpp b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.cpp index 3f438b298a..ee8f339b4d 100644 --- a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.cpp +++ b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.cpp @@ -1,100 +1,100 @@ -/* Generate IV Checker OCR Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_GenerateIVCheckerOCR.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const std::string IVCheckerOptionOCR::TOKENS[]{ - "No Good", - "Decent", - "Pretty Good", - "Very Good", - "Fantastic", - "Best", - "Hyper trained!", -}; - - - -GenerateIVCheckerOCR_Descriptor::GenerateIVCheckerOCR_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:GenerateIVCheckerOCR", - STRING_POKEMON + " SwSh", "Generate IV Checker OCR Data", - "", - "Generate IV Checker OCR Data", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {} - ) -{} - - - -GenerateIVCheckerOCR::GenerateIVCheckerOCR() - : LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING - ) - , HP("HP:", IvJudgeValue::Best) - , ATTACK("Attack:", IvJudgeValue::Best) - , DEFENSE("Defense:", IvJudgeValue::Best) - , SPATK("Sp. Atk:", IvJudgeValue::Best) - , SPDEF("Sp. Def:", IvJudgeValue::Best) - , SPEED("Speed:", IvJudgeValue::Best) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(HP); - PA_ADD_OPTION(ATTACK); - PA_ADD_OPTION(DEFENSE); - PA_ADD_OPTION(SPATK); - PA_ADD_OPTION(SPDEF); - PA_ADD_OPTION(SPEED); -} - - -void GenerateIVCheckerOCR::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - IvJudgeReaderScope reader(env.console, LANGUAGE); - - std::string path = "IVCheckerOCR/"; - path += language_data(LANGUAGE).code; - - QDir dir(QString::fromStdString(path)); - if (!dir.exists()){ - dir.mkpath("."); - } - path += "/"; - - VideoSnapshot screen = env.console.video().snapshot(); - std::vector images = reader.dump_images(screen); - - std::string now = now_to_filestring(); - - const EnumDropdownDatabase& database = IvJudgeValue_Database(); - images[0].save(path + database.find(HP)->display + "-" + now + "a.png"); - images[1].save(path + database.find(ATTACK)->display + "-" + now + "b.png"); - images[2].save(path + database.find(DEFENSE)->display + "-" + now + "c.png"); - images[3].save(path + database.find(SPATK)->display + "-" + now + "d.png"); - images[4].save(path + database.find(SPDEF)->display + "-" + now + "e.png"); - images[5].save(path + database.find(SPEED)->display + "-" + now + "f.png"); - -} - - - -} -} -} - +/* Generate IV Checker OCR Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_GenerateIVCheckerOCR.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const std::string IVCheckerOptionOCR::TOKENS[]{ + "No Good", + "Decent", + "Pretty Good", + "Very Good", + "Fantastic", + "Best", + "Hyper trained!", +}; + + + +GenerateIVCheckerOCR_Descriptor::GenerateIVCheckerOCR_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:GenerateIVCheckerOCR", + STRING_POKEMON + " SwSh", "Generate IV Checker OCR Data", + "", + "Generate IV Checker OCR Data", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {} + ) +{} + + + +GenerateIVCheckerOCR::GenerateIVCheckerOCR() + : LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING + ) + , HP("HP:", IvJudgeValue::Best) + , ATTACK("Attack:", IvJudgeValue::Best) + , DEFENSE("Defense:", IvJudgeValue::Best) + , SPATK("Sp. Atk:", IvJudgeValue::Best) + , SPDEF("Sp. Def:", IvJudgeValue::Best) + , SPEED("Speed:", IvJudgeValue::Best) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(HP); + PA_ADD_OPTION(ATTACK); + PA_ADD_OPTION(DEFENSE); + PA_ADD_OPTION(SPATK); + PA_ADD_OPTION(SPDEF); + PA_ADD_OPTION(SPEED); +} + + +void GenerateIVCheckerOCR::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + IvJudgeReaderScope reader(env.console, LANGUAGE); + + std::string path = "IVCheckerOCR/"; + path += language_data(LANGUAGE).code; + + QDir dir(QString::fromStdString(path)); + if (!dir.exists()){ + dir.mkpath("."); + } + path += "/"; + + VideoSnapshot screen = env.console.video().snapshot(); + std::vector images = reader.dump_images(screen); + + std::string now = now_to_filestring(); + + const EnumDropdownDatabase& database = IvJudgeValue_Database(); + images[0].save(path + database.find(HP)->display + "-" + now + "a.png"); + images[1].save(path + database.find(ATTACK)->display + "-" + now + "b.png"); + images[2].save(path + database.find(DEFENSE)->display + "-" + now + "c.png"); + images[3].save(path + database.find(SPATK)->display + "-" + now + "d.png"); + images[4].save(path + database.find(SPDEF)->display + "-" + now + "e.png"); + images[5].save(path + database.find(SPEED)->display + "-" + now + "f.png"); + +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h index 356853590b..4b29202ac2 100644 --- a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h +++ b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h @@ -1,73 +1,73 @@ -/* Generate IV Checker OCR Data - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_GenerateIVCheckerOCR_H -#define PokemonAutomation_PokemonSwSh_GenerateIVCheckerOCR_H - -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Pokemon_IvJudge.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - - -class IVCheckerOptionOCR : public EnumDropdownOption{ -public: - static const std::string TOKENS[]; - -public: - IVCheckerOptionOCR(std::string label, IvJudgeValue default_value) - : EnumDropdownOption( - std::move(label), - IvJudgeValue_Database(), - LockMode::LOCK_WHILE_RUNNING, - default_value - ) - {} -}; - - - -class GenerateIVCheckerOCR_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GenerateIVCheckerOCR_Descriptor(); -}; - - - -class GenerateIVCheckerOCR : public SingleSwitchProgramInstance{ -public: - enum Mode{ - READ_AND_SAVE, - GENERATE_TRAINING_DATA, - }; - -public: - GenerateIVCheckerOCR(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - OCR::LanguageOCROption LANGUAGE; - IVCheckerOptionOCR HP; - IVCheckerOptionOCR ATTACK; - IVCheckerOptionOCR DEFENSE; - IVCheckerOptionOCR SPATK; - IVCheckerOptionOCR SPDEF; - IVCheckerOptionOCR SPEED; -}; - - - -} -} -} -#endif +/* Generate IV Checker OCR Data + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_GenerateIVCheckerOCR_H +#define PokemonAutomation_PokemonSwSh_GenerateIVCheckerOCR_H + +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_IvJudge.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + + +class IVCheckerOptionOCR : public EnumDropdownOption{ +public: + static const std::string TOKENS[]; + +public: + IVCheckerOptionOCR(std::string label, IvJudgeValue default_value) + : EnumDropdownOption( + std::move(label), + IvJudgeValue_Database(), + LockMode::LOCK_WHILE_RUNNING, + default_value + ) + {} +}; + + + +class GenerateIVCheckerOCR_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GenerateIVCheckerOCR_Descriptor(); +}; + + + +class GenerateIVCheckerOCR : public SingleSwitchProgramInstance{ +public: + enum Mode{ + READ_AND_SAVE, + GENERATE_TRAINING_DATA, + }; + +public: + GenerateIVCheckerOCR(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + OCR::LanguageOCROption LANGUAGE; + IVCheckerOptionOCR HP; + IVCheckerOptionOCR ATTACK; + IVCheckerOptionOCR DEFENSE; + IVCheckerOptionOCR SPATK; + IVCheckerOptionOCR SPDEF; + IVCheckerOptionOCR SPEED; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.cpp b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.cpp index 283ac60378..db242f2b57 100644 --- a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.cpp +++ b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.cpp @@ -1,211 +1,211 @@ -/* Generate Pokemon Name OCR Data (Pokedex) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh_GenerateNameOCRPokedex.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - - -GenerateNameOCRDataPokedex_Descriptor::GenerateNameOCRDataPokedex_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:GenerateNameOCRPokedex", - STRING_POKEMON + " SwSh", "Generate " + STRING_POKEMON + " Name OCR Data", - "", - "Generate " + STRING_POKEMON + " Name OCR data by iterating the " + STRING_POKEDEX + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - - -GenerateNameOCRDataPokedex::GenerateNameOCRDataPokedex() - : LANGUAGE( - "Game Language:", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING - ) - , POKEDEX( - "" + STRING_POKEDEX + ":", - { - {Pokedex::Galar, "galar", "Galar"}, - {Pokedex::IsleOfArmor, "isle-of-armor", "Isle of Armor"}, - {Pokedex::CrownTundra, "crown-tundra", "Crown Tundra"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Pokedex::Galar - ) - , MODE( - "Mode:", - { - {Mode::SaveToJson, "save-to-json", "Read names and save to JSON."}, - {Mode::GenerateTrainingData, "generate-training-data", "Generate training data."}, - }, - LockMode::LOCK_WHILE_RUNNING, - Mode::GenerateTrainingData - ) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(POKEDEX); - PA_ADD_OPTION(MODE); -} - -void GenerateNameOCRDataPokedex::read( - JsonArray& output, - Logger& logger, - const ImageViewRGB32& image -) const{ - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - logger, LANGUAGE, image, - OCR::BLACK_OR_WHITE_TEXT_FILTERS() - ); - if (result.results.empty()){ - output.push_back(""); - }else{ - output.push_back(result.results.begin()->second.token); - } -} - -void GenerateNameOCRDataPokedex::dump_images( - const std::vector& expected, - size_t index, - const ImageViewRGB32& image -) const{ - if (index >= expected.size()){ - return; - } - - std::string path = "PokemonNameOCR/"; - path += language_data(LANGUAGE).code; - - QDir dir(QString::fromStdString(path)); - if (!dir.exists()){ - dir.mkpath("."); - } - - path += "/"; - path += expected[index]; - path += "-"; - path += now_to_filestring(); - path += ".png"; - image.save(path); - -// OCR::make_OCR_filter(image).apply(image); -} - -void GenerateNameOCRDataPokedex::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - - std::string dex_name; - size_t dex_size = 0; - switch (POKEDEX){ - case Pokedex::Galar: - dex_name = "Galar"; - dex_size = 400; - break; - case Pokedex::IsleOfArmor: - dex_name = "IsleOfArmor"; - dex_size = 211; - break; - case Pokedex::CrownTundra: - dex_name = "CrownTundra"; - dex_size = 210; - break; - } - - OverlayBoxScope box0(env.console, {0.75, 0.146 + 0 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - OverlayBoxScope box1(env.console, {0.75, 0.146 + 1 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - OverlayBoxScope box2(env.console, {0.75, 0.146 + 2 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - OverlayBoxScope box3(env.console, {0.75, 0.146 + 3 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - OverlayBoxScope box4(env.console, {0.75, 0.146 + 4 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - OverlayBoxScope box5(env.console, {0.75, 0.146 + 5 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - OverlayBoxScope box6(env.console, {0.75, 0.146 + 6 * 0.1115, 0.18, 0.059}, COLOR_BLUE); - - std::vector expected; - JsonArray actual; -// OCR::DictionaryOCR& dictionary = m_reader.dictionary(LANGUAGE); - - if (MODE == Mode::GenerateTrainingData){ - std::string path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-" + dex_name + ".json"; - JsonValue json = load_json_file(path); - JsonArray& array = json.to_array_throw(path); - for (const auto& item : array){ - expected.emplace_back(item.to_string_throw(path)); - } - } - - for (size_t c = 1; c <= dex_size; c += 7){ - context.wait_for_all_requests(); - - if (c + 6 > dex_size){ - c = dex_size - 6; - } -// cout << "dex: " << c << endl; - - VideoSnapshot frame = env.console.video().snapshot(); - ImageViewRGB32 image0 = extract_box_reference(frame, box0); - ImageViewRGB32 image1 = extract_box_reference(frame, box1); - ImageViewRGB32 image2 = extract_box_reference(frame, box2); - ImageViewRGB32 image3 = extract_box_reference(frame, box3); - ImageViewRGB32 image4 = extract_box_reference(frame, box4); - ImageViewRGB32 image5 = extract_box_reference(frame, box5); - ImageViewRGB32 image6 = extract_box_reference(frame, box6); - -// image1.save("test.png"); - - switch (MODE){ - case Mode::SaveToJson: - read(actual, env.console, image0); - read(actual, env.console, image1); - read(actual, env.console, image2); - read(actual, env.console, image3); - read(actual, env.console, image4); - read(actual, env.console, image5); - read(actual, env.console, image6); - break; - case Mode::GenerateTrainingData: - dump_images(expected, c - 1 + 0, image0); - dump_images(expected, c - 1 + 1, image1); - dump_images(expected, c - 1 + 2, image2); - dump_images(expected, c - 1 + 3, image3); - dump_images(expected, c - 1 + 4, image4); - dump_images(expected, c - 1 + 5, image5); - dump_images(expected, c - 1 + 6, image6); - break; - } - - pbf_press_dpad(context, DPAD_RIGHT, 10, TICKS_PER_SECOND); - } - - if (MODE == Mode::SaveToJson){ - actual.dump("PokedexReadData.json"); - } - -} - - - -} -} -} +/* Generate Pokemon Name OCR Data (Pokedex) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh_GenerateNameOCRPokedex.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + + +GenerateNameOCRDataPokedex_Descriptor::GenerateNameOCRDataPokedex_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:GenerateNameOCRPokedex", + STRING_POKEMON + " SwSh", "Generate " + STRING_POKEMON + " Name OCR Data", + "", + "Generate " + STRING_POKEMON + " Name OCR data by iterating the " + STRING_POKEDEX + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + + +GenerateNameOCRDataPokedex::GenerateNameOCRDataPokedex() + : LANGUAGE( + "Game Language:", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING + ) + , POKEDEX( + "" + STRING_POKEDEX + ":", + { + {Pokedex::Galar, "galar", "Galar"}, + {Pokedex::IsleOfArmor, "isle-of-armor", "Isle of Armor"}, + {Pokedex::CrownTundra, "crown-tundra", "Crown Tundra"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Pokedex::Galar + ) + , MODE( + "Mode:", + { + {Mode::SaveToJson, "save-to-json", "Read names and save to JSON."}, + {Mode::GenerateTrainingData, "generate-training-data", "Generate training data."}, + }, + LockMode::LOCK_WHILE_RUNNING, + Mode::GenerateTrainingData + ) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(POKEDEX); + PA_ADD_OPTION(MODE); +} + +void GenerateNameOCRDataPokedex::read( + JsonArray& output, + Logger& logger, + const ImageViewRGB32& image +) const{ + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + logger, LANGUAGE, image, + OCR::BLACK_OR_WHITE_TEXT_FILTERS() + ); + if (result.results.empty()){ + output.push_back(""); + }else{ + output.push_back(result.results.begin()->second.token); + } +} + +void GenerateNameOCRDataPokedex::dump_images( + const std::vector& expected, + size_t index, + const ImageViewRGB32& image +) const{ + if (index >= expected.size()){ + return; + } + + std::string path = "PokemonNameOCR/"; + path += language_data(LANGUAGE).code; + + QDir dir(QString::fromStdString(path)); + if (!dir.exists()){ + dir.mkpath("."); + } + + path += "/"; + path += expected[index]; + path += "-"; + path += now_to_filestring(); + path += ".png"; + image.save(path); + +// OCR::make_OCR_filter(image).apply(image); +} + +void GenerateNameOCRDataPokedex::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + + std::string dex_name; + size_t dex_size = 0; + switch (POKEDEX){ + case Pokedex::Galar: + dex_name = "Galar"; + dex_size = 400; + break; + case Pokedex::IsleOfArmor: + dex_name = "IsleOfArmor"; + dex_size = 211; + break; + case Pokedex::CrownTundra: + dex_name = "CrownTundra"; + dex_size = 210; + break; + } + + OverlayBoxScope box0(env.console, {0.75, 0.146 + 0 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + OverlayBoxScope box1(env.console, {0.75, 0.146 + 1 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + OverlayBoxScope box2(env.console, {0.75, 0.146 + 2 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + OverlayBoxScope box3(env.console, {0.75, 0.146 + 3 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + OverlayBoxScope box4(env.console, {0.75, 0.146 + 4 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + OverlayBoxScope box5(env.console, {0.75, 0.146 + 5 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + OverlayBoxScope box6(env.console, {0.75, 0.146 + 6 * 0.1115, 0.18, 0.059}, COLOR_BLUE); + + std::vector expected; + JsonArray actual; +// OCR::DictionaryOCR& dictionary = m_reader.dictionary(LANGUAGE); + + if (MODE == Mode::GenerateTrainingData){ + std::string path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-" + dex_name + ".json"; + JsonValue json = load_json_file(path); + JsonArray& array = json.to_array_throw(path); + for (const auto& item : array){ + expected.emplace_back(item.to_string_throw(path)); + } + } + + for (size_t c = 1; c <= dex_size; c += 7){ + context.wait_for_all_requests(); + + if (c + 6 > dex_size){ + c = dex_size - 6; + } +// cout << "dex: " << c << endl; + + VideoSnapshot frame = env.console.video().snapshot(); + ImageViewRGB32 image0 = extract_box_reference(frame, box0); + ImageViewRGB32 image1 = extract_box_reference(frame, box1); + ImageViewRGB32 image2 = extract_box_reference(frame, box2); + ImageViewRGB32 image3 = extract_box_reference(frame, box3); + ImageViewRGB32 image4 = extract_box_reference(frame, box4); + ImageViewRGB32 image5 = extract_box_reference(frame, box5); + ImageViewRGB32 image6 = extract_box_reference(frame, box6); + +// image1.save("test.png"); + + switch (MODE){ + case Mode::SaveToJson: + read(actual, env.console, image0); + read(actual, env.console, image1); + read(actual, env.console, image2); + read(actual, env.console, image3); + read(actual, env.console, image4); + read(actual, env.console, image5); + read(actual, env.console, image6); + break; + case Mode::GenerateTrainingData: + dump_images(expected, c - 1 + 0, image0); + dump_images(expected, c - 1 + 1, image1); + dump_images(expected, c - 1 + 2, image2); + dump_images(expected, c - 1 + 3, image3); + dump_images(expected, c - 1 + 4, image4); + dump_images(expected, c - 1 + 5, image5); + dump_images(expected, c - 1 + 6, image6); + break; + } + + pbf_press_dpad(context, DPAD_RIGHT, 10, TICKS_PER_SECOND); + } + + if (MODE == Mode::SaveToJson){ + actual.dump("PokedexReadData.json"); + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h index ea09ba2c09..257b3e2843 100644 --- a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h +++ b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h @@ -1,69 +1,69 @@ -/* Generate Pokemon Name OCR Data (Pokedex) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_GenerateNameOCRData_H -#define PokemonAutomation_PokemonSwSh_GenerateNameOCRData_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - - -namespace PokemonAutomation{ - class JsonArray; - class ImageViewRGB32; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class GenerateNameOCRDataPokedex_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GenerateNameOCRDataPokedex_Descriptor(); -}; - - - -class GenerateNameOCRDataPokedex : public SingleSwitchProgramInstance{ -public: - GenerateNameOCRDataPokedex(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void read( - JsonArray& output, - Logger& logger, - const ImageViewRGB32& image - ) const; - void dump_images( - const std::vector& expected, - size_t index, - const ImageViewRGB32& image - ) const; - -private: - OCR::LanguageOCROption LANGUAGE; - - enum class Pokedex{ - Galar, - IsleOfArmor, - CrownTundra, - }; - EnumDropdownOption POKEDEX; - - enum class Mode{ - SaveToJson, - GenerateTrainingData, - }; - EnumDropdownOption MODE; -}; - - - -} -} -} -#endif +/* Generate Pokemon Name OCR Data (Pokedex) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_GenerateNameOCRData_H +#define PokemonAutomation_PokemonSwSh_GenerateNameOCRData_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + + +namespace PokemonAutomation{ + class JsonArray; + class ImageViewRGB32; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class GenerateNameOCRDataPokedex_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GenerateNameOCRDataPokedex_Descriptor(); +}; + + + +class GenerateNameOCRDataPokedex : public SingleSwitchProgramInstance{ +public: + GenerateNameOCRDataPokedex(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void read( + JsonArray& output, + Logger& logger, + const ImageViewRGB32& image + ) const; + void dump_images( + const std::vector& expected, + size_t index, + const ImageViewRGB32& image + ) const; + +private: + OCR::LanguageOCROption LANGUAGE; + + enum class Pokedex{ + Galar, + IsleOfArmor, + CrownTundra, + }; + EnumDropdownOption POKEDEX; + + enum class Mode{ + SaveToJson, + GenerateTrainingData, + }; + EnumDropdownOption MODE; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.cpp b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.cpp index b8d51c8c28..3dc667f13c 100644 --- a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.cpp +++ b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.cpp @@ -1,240 +1,240 @@ -/* Generate Pokemon Sprite Data (Pokedex) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h" -#include "PokemonSwSh_GeneratePokedexSprites.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -using namespace Pokemon; - - -GeneratePokedexSprites_Descriptor::GeneratePokedexSprites_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:GeneratePokedexSprites", - STRING_POKEMON + " SwSh", "Generate " + STRING_POKEMON + " Sprite Data", - "", - "Generate " + STRING_POKEMON + " Sprite data by iterating the " + STRING_POKEDEX + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - -GeneratePokedexSprites::GeneratePokedexSprites() - : LANGUAGE( - "Game Language:", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING - ) - , HORIZONTAL_FRAMES( - "Frames per 360 Degree Horizontal Rotation:", - LockMode::LOCK_WHILE_RUNNING, - 10 - ) - , ANIMATION_FRAMES( - "Animation Frames per Camera Angle:", - LockMode::LOCK_WHILE_RUNNING, - 2 - ) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(HORIZONTAL_FRAMES); - PA_ADD_OPTION(ANIMATION_FRAMES); -} - - -class GenerateDexModelSession{ - static constexpr uint16_t HORIZONTAL_360 = 160; - static constexpr uint16_t VERTICAL_90 = 40; - -public: - GenerateDexModelSession( - VideoStream& stream, ProControllerContext& context, - size_t horizontal_frames = 10, - size_t animation_frames = 2 - ) - : m_stream(stream), m_context(context) - , m_path("PokedexSprites/") - , m_horizontal_frames(horizontal_frames) - , m_vertical_frames(horizontal_frames * 40 / HORIZONTAL_360 + 1) - , m_animation_frames(animation_frames) -// , m_frames_per_form(m_horizontal_frames * m_vertical_frames * (m_animation_frames + 1)) - { -// cout << "frames/form = " << m_frames_per_form << endl; - } - - -public: - void save_image(const std::string& slug, bool is_shiny, size_t form_index, size_t image_index); - void iterate_form(const std::string& slug, bool shiny, size_t form_index); - void iterate_species(); - void iterate_dex(); - -private: - VideoStream& m_stream; - ProControllerContext& m_context; - - std::string m_path; - - size_t m_horizontal_frames; - size_t m_vertical_frames; - size_t m_animation_frames; -// size_t m_frames_per_form; - - std::set m_processed_slugs; -}; - - - - -void GenerateDexModelSession::save_image(const std::string& slug, bool is_shiny, size_t form_index, size_t image_index){ - m_context.wait_for_all_requests(); - VideoSnapshot screen = m_stream.video().snapshot(); - ImageViewRGB32 cropped = extract_box_reference(screen, ImageFloatBox(0.20, 0.01, 0.60, 0.93)); - - std::string filename = m_path + slug + "/" + slug; - filename += is_shiny ? "_shiny" : "_nonshiny"; - filename += "_f" + std::to_string(form_index); - filename += "_#" + std::to_string(image_index); - filename += ".jpg"; - cropped.save(filename); -} -void GenerateDexModelSession::iterate_form(const std::string& slug, bool shiny, size_t form_index){ - size_t image_index = 0; - - uint16_t step = 160 / (uint16_t)m_horizontal_frames + 1; - - // Stills - for (size_t y = 0; y < m_vertical_frames; y++){ - for (size_t x = 0; x < m_horizontal_frames; x++){ - pbf_press_dpad(m_context, DPAD_RIGHT, step, 50); - save_image(slug, shiny, form_index, image_index++); - } - pbf_press_dpad(m_context, DPAD_DOWN, step, 50); - } - pbf_press_dpad(m_context, DPAD_UP, 125, 0); - - // Motion - pbf_press_button(m_context, BUTTON_A, 20, 30); - for (size_t y = 0; y < m_vertical_frames; y++){ - for (size_t x = 0; x < m_horizontal_frames; x++){ - pbf_press_dpad(m_context, DPAD_RIGHT, step, 50); - for (size_t t = 0; t < m_animation_frames; t++){ - save_image(slug, shiny, form_index, image_index++); - m_context.wait_for(std::chrono::milliseconds(500)); - } - } - pbf_press_dpad(m_context, DPAD_DOWN, step, 50); - } - pbf_press_dpad(m_context, DPAD_UP, 125, 0); -} -void GenerateDexModelSession::iterate_species(){ - ImageFloatBox SPRITE_BOX(0.45, 0.13, 0.06, 0.09); - ImageFloatBox LABEL_BOX(0.85, 0.13, 0.05, 0.09); - ImageFloatBox SHINY_BOX(0.90, 0.14, 0.03, 0.06); - ImageRGB32 start_sprite; - ImageRGB32 start_label; - ImageRGB32 start_shiny; - std::string slug; - bool is_shiny; - { - VideoSnapshot screen = m_stream.video().snapshot(); - start_sprite = extract_box_reference(screen, SPRITE_BOX).copy(); - start_label = extract_box_reference(screen, LABEL_BOX).copy(); - start_shiny = extract_box_reference(screen, SHINY_BOX).copy(); - is_shiny = image_stats(start_shiny).stddev.sum() > 100; - - ImageFloatBox NAME_BOX(0.641, 0.134, 0.210, 0.080); - PokemonNameReader reader(ALL_POKEMON_SLUGS()); - OCR::StringMatchResult result = reader.read_substring( - m_stream.logger(), Language::English, - extract_box_reference(screen, NAME_BOX), - OCR::WHITE_TEXT_FILTERS() - ); - if (result.results.empty()){ - m_stream.log("Unable to read " + STRING_POKEMON + "name.", COLOR_RED); - return; - } - slug = result.results.begin()->second.token; - } - -#if 1 - if (m_processed_slugs.contains(slug)){ -// m_console.log("Skipping already processed " + STRING_POKEMON + ".", COLOR_BLUE); -// return; - throw ProgramFinishedException(); - } - m_processed_slugs.insert(slug); -#endif - - std::filesystem::create_directories(m_path + slug); - - size_t non_shiny_index = 0; - size_t shiny_index = 0; - - double rmsd; - do{ -// cout << "shiny = " << is_shiny; - - size_t& index = is_shiny ? shiny_index : non_shiny_index; - - pbf_press_button(m_context, BUTTON_A, 20, 230); - iterate_form(slug, is_shiny, index); - pbf_press_button(m_context, BUTTON_B, 20, 230); - pbf_press_dpad(m_context, DPAD_RIGHT, 20, 105); - m_context.wait_for_all_requests(); - - index++; - - VideoSnapshot screen = m_stream.video().snapshot(); - ImageViewRGB32 current_sprite = extract_box_reference(screen, SPRITE_BOX); - ImageViewRGB32 current_label = extract_box_reference(screen, LABEL_BOX); - ImageViewRGB32 current_shiny = extract_box_reference(screen, SHINY_BOX); - is_shiny = image_stats(current_shiny).stddev.sum() > 100; - double rmsd0 = ImageMatch::pixel_RMSD(start_sprite, current_sprite); - double rmsd1 = ImageMatch::pixel_RMSD(start_label, current_label); - double rmsd2 = ImageMatch::pixel_RMSD(start_shiny, current_shiny); - rmsd = rmsd0 + rmsd1 + rmsd2; -// cout << ", rmsd = " << rmsd << endl; - }while (rmsd > 5); -} -void GenerateDexModelSession::iterate_dex(){ - while (true){ - iterate_species(); - pbf_press_dpad(m_context, DPAD_DOWN, 20, 105); - m_context.wait_for_all_requests(); - } -} - - - - - - -void GeneratePokedexSprites::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - GenerateDexModelSession session(env.console, context); - session.iterate_dex(); -} - - - -} -} -} +/* Generate Pokemon Sprite Data (Pokedex) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h" +#include "PokemonSwSh_GeneratePokedexSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +using namespace Pokemon; + + +GeneratePokedexSprites_Descriptor::GeneratePokedexSprites_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:GeneratePokedexSprites", + STRING_POKEMON + " SwSh", "Generate " + STRING_POKEMON + " Sprite Data", + "", + "Generate " + STRING_POKEMON + " Sprite data by iterating the " + STRING_POKEDEX + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + +GeneratePokedexSprites::GeneratePokedexSprites() + : LANGUAGE( + "Game Language:", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING + ) + , HORIZONTAL_FRAMES( + "Frames per 360 Degree Horizontal Rotation:", + LockMode::LOCK_WHILE_RUNNING, + 10 + ) + , ANIMATION_FRAMES( + "Animation Frames per Camera Angle:", + LockMode::LOCK_WHILE_RUNNING, + 2 + ) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(HORIZONTAL_FRAMES); + PA_ADD_OPTION(ANIMATION_FRAMES); +} + + +class GenerateDexModelSession{ + static constexpr uint16_t HORIZONTAL_360 = 160; + static constexpr uint16_t VERTICAL_90 = 40; + +public: + GenerateDexModelSession( + VideoStream& stream, ProControllerContext& context, + size_t horizontal_frames = 10, + size_t animation_frames = 2 + ) + : m_stream(stream), m_context(context) + , m_path("PokedexSprites/") + , m_horizontal_frames(horizontal_frames) + , m_vertical_frames(horizontal_frames * 40 / HORIZONTAL_360 + 1) + , m_animation_frames(animation_frames) +// , m_frames_per_form(m_horizontal_frames * m_vertical_frames * (m_animation_frames + 1)) + { +// cout << "frames/form = " << m_frames_per_form << endl; + } + + +public: + void save_image(const std::string& slug, bool is_shiny, size_t form_index, size_t image_index); + void iterate_form(const std::string& slug, bool shiny, size_t form_index); + void iterate_species(); + void iterate_dex(); + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + + std::string m_path; + + size_t m_horizontal_frames; + size_t m_vertical_frames; + size_t m_animation_frames; +// size_t m_frames_per_form; + + std::set m_processed_slugs; +}; + + + + +void GenerateDexModelSession::save_image(const std::string& slug, bool is_shiny, size_t form_index, size_t image_index){ + m_context.wait_for_all_requests(); + VideoSnapshot screen = m_stream.video().snapshot(); + ImageViewRGB32 cropped = extract_box_reference(screen, ImageFloatBox(0.20, 0.01, 0.60, 0.93)); + + std::string filename = m_path + slug + "/" + slug; + filename += is_shiny ? "_shiny" : "_nonshiny"; + filename += "_f" + std::to_string(form_index); + filename += "_#" + std::to_string(image_index); + filename += ".jpg"; + cropped.save(filename); +} +void GenerateDexModelSession::iterate_form(const std::string& slug, bool shiny, size_t form_index){ + size_t image_index = 0; + + uint16_t step = 160 / (uint16_t)m_horizontal_frames + 1; + + // Stills + for (size_t y = 0; y < m_vertical_frames; y++){ + for (size_t x = 0; x < m_horizontal_frames; x++){ + pbf_press_dpad(m_context, DPAD_RIGHT, step, 50); + save_image(slug, shiny, form_index, image_index++); + } + pbf_press_dpad(m_context, DPAD_DOWN, step, 50); + } + pbf_press_dpad(m_context, DPAD_UP, 125, 0); + + // Motion + pbf_press_button(m_context, BUTTON_A, 20, 30); + for (size_t y = 0; y < m_vertical_frames; y++){ + for (size_t x = 0; x < m_horizontal_frames; x++){ + pbf_press_dpad(m_context, DPAD_RIGHT, step, 50); + for (size_t t = 0; t < m_animation_frames; t++){ + save_image(slug, shiny, form_index, image_index++); + m_context.wait_for(std::chrono::milliseconds(500)); + } + } + pbf_press_dpad(m_context, DPAD_DOWN, step, 50); + } + pbf_press_dpad(m_context, DPAD_UP, 125, 0); +} +void GenerateDexModelSession::iterate_species(){ + ImageFloatBox SPRITE_BOX(0.45, 0.13, 0.06, 0.09); + ImageFloatBox LABEL_BOX(0.85, 0.13, 0.05, 0.09); + ImageFloatBox SHINY_BOX(0.90, 0.14, 0.03, 0.06); + ImageRGB32 start_sprite; + ImageRGB32 start_label; + ImageRGB32 start_shiny; + std::string slug; + bool is_shiny; + { + VideoSnapshot screen = m_stream.video().snapshot(); + start_sprite = extract_box_reference(screen, SPRITE_BOX).copy(); + start_label = extract_box_reference(screen, LABEL_BOX).copy(); + start_shiny = extract_box_reference(screen, SHINY_BOX).copy(); + is_shiny = image_stats(start_shiny).stddev.sum() > 100; + + ImageFloatBox NAME_BOX(0.641, 0.134, 0.210, 0.080); + PokemonNameReader reader(ALL_POKEMON_SLUGS()); + OCR::StringMatchResult result = reader.read_substring( + m_stream.logger(), Language::English, + extract_box_reference(screen, NAME_BOX), + OCR::WHITE_TEXT_FILTERS() + ); + if (result.results.empty()){ + m_stream.log("Unable to read " + STRING_POKEMON + "name.", COLOR_RED); + return; + } + slug = result.results.begin()->second.token; + } + +#if 1 + if (m_processed_slugs.contains(slug)){ +// m_console.log("Skipping already processed " + STRING_POKEMON + ".", COLOR_BLUE); +// return; + throw ProgramFinishedException(); + } + m_processed_slugs.insert(slug); +#endif + + std::filesystem::create_directories(m_path + slug); + + size_t non_shiny_index = 0; + size_t shiny_index = 0; + + double rmsd; + do{ +// cout << "shiny = " << is_shiny; + + size_t& index = is_shiny ? shiny_index : non_shiny_index; + + pbf_press_button(m_context, BUTTON_A, 20, 230); + iterate_form(slug, is_shiny, index); + pbf_press_button(m_context, BUTTON_B, 20, 230); + pbf_press_dpad(m_context, DPAD_RIGHT, 20, 105); + m_context.wait_for_all_requests(); + + index++; + + VideoSnapshot screen = m_stream.video().snapshot(); + ImageViewRGB32 current_sprite = extract_box_reference(screen, SPRITE_BOX); + ImageViewRGB32 current_label = extract_box_reference(screen, LABEL_BOX); + ImageViewRGB32 current_shiny = extract_box_reference(screen, SHINY_BOX); + is_shiny = image_stats(current_shiny).stddev.sum() > 100; + double rmsd0 = ImageMatch::pixel_RMSD(start_sprite, current_sprite); + double rmsd1 = ImageMatch::pixel_RMSD(start_label, current_label); + double rmsd2 = ImageMatch::pixel_RMSD(start_shiny, current_shiny); + rmsd = rmsd0 + rmsd1 + rmsd2; +// cout << ", rmsd = " << rmsd << endl; + }while (rmsd > 5); +} +void GenerateDexModelSession::iterate_dex(){ + while (true){ + iterate_species(); + pbf_press_dpad(m_context, DPAD_DOWN, 20, 105); + m_context.wait_for_all_requests(); + } +} + + + + + + +void GeneratePokedexSprites::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + GenerateDexModelSession session(env.console, context); + session.iterate_dex(); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h index c79eb67e2a..e9d5b8afa0 100644 --- a/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h +++ b/SerialPrograms/Source/PokemonSwSh/InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h @@ -1,44 +1,44 @@ -/* Generate Pokemon Sprite Data (Pokedex) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_GeneratePokedexSprites_H -#define PokemonAutomation_PokemonSwSh_GeneratePokedexSprites_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class GeneratePokedexSprites_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GeneratePokedexSprites_Descriptor(); -}; - - - -class GeneratePokedexSprites : public SingleSwitchProgramInstance{ -public: - GeneratePokedexSprites(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - OCR::LanguageOCROption LANGUAGE; - SimpleIntegerOption HORIZONTAL_FRAMES; - SimpleIntegerOption ANIMATION_FRAMES; -}; - - - -} -} -} -#endif +/* Generate Pokemon Sprite Data (Pokedex) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_GeneratePokedexSprites_H +#define PokemonAutomation_PokemonSwSh_GeneratePokedexSprites_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class GeneratePokedexSprites_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GeneratePokedexSprites_Descriptor(); +}; + + + +class GeneratePokedexSprites : public SingleSwitchProgramInstance{ +public: + GeneratePokedexSprites(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + OCR::LanguageOCROption LANGUAGE; + SimpleIntegerOption HORIZONTAL_FRAMES; + SimpleIntegerOption ANIMATION_FRAMES; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.cpp index 5b05776062..1eec42c310 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.cpp @@ -1,29 +1,29 @@ -/* Max Lair AI - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/CRC32.h" -//#include "CommonFramework/Environment/Environment.h" -#include "PokemonSwSh_MaxLair_AI.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -int random(int min, int max){ -// uint64_t seed = x86_rdtsc(); - uint64_t seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); - seed = pabb_crc32(0, &seed, sizeof(seed)); - seed %= (max - min + 1); - return (int)seed + min; -} - - -} -} -} -} +/* Max Lair AI + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/CRC32.h" +//#include "CommonFramework/Environment/Environment.h" +#include "PokemonSwSh_MaxLair_AI.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +int random(int min, int max){ +// uint64_t seed = x86_rdtsc(); + uint64_t seed = std::chrono::high_resolution_clock::now().time_since_epoch().count(); + seed = pabb_crc32(0, &seed, sizeof(seed)); + seed %= (max - min + 1); + return (int)seed + min; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h index 296cdc446a..d9815de113 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h @@ -1,78 +1,78 @@ -/* Max Lair AI - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_H -#define PokemonAutomation_PokemonSwSh_MaxLair_AI_H - -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -int random(int min, int max); - - - -// 0 for top Pokemon -// 1 for middle Pokemon -// 2 for bottom Pokemon -int8_t select_starter( - Logger& logger, - const GlobalState& state, - size_t player_index, - const std::string options[3] -); - -// 0 for left-most path. -// 1 for 2nd from left. -// 2 ... -std::vector select_path( - Logger& logger, - const GlobalState& state, - size_t player_index -); - -// Return -1 if no selecting an item. -int8_t select_item( - Logger& logger, - const GlobalState& state, - size_t player_index -); - -// Professor offers to exchange a Pokemon. -bool should_swap_with_professor( - Logger& logger, - const GlobalState& state, - size_t player_index -); - -// Return 0 - 3 for move position. 2nd parameter is dmax. -std::pair select_move( - Logger& logger, - const GlobalState& state, - size_t player_index -); - -// Swap with newly caught Pokemon. -bool should_swap_with_newly_caught( - Logger& logger, - const GlobalState& state, - size_t player_index, - const std::string options[2] -); - - - - -} -} -} -} -#endif +/* Max Lair AI + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_H +#define PokemonAutomation_PokemonSwSh_MaxLair_AI_H + +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +int random(int min, int max); + + + +// 0 for top Pokemon +// 1 for middle Pokemon +// 2 for bottom Pokemon +int8_t select_starter( + Logger& logger, + const GlobalState& state, + size_t player_index, + const std::string options[3] +); + +// 0 for left-most path. +// 1 for 2nd from left. +// 2 ... +std::vector select_path( + Logger& logger, + const GlobalState& state, + size_t player_index +); + +// Return -1 if no selecting an item. +int8_t select_item( + Logger& logger, + const GlobalState& state, + size_t player_index +); + +// Professor offers to exchange a Pokemon. +bool should_swap_with_professor( + Logger& logger, + const GlobalState& state, + size_t player_index +); + +// Return 0 - 3 for move position. 2nd parameter is dmax. +std::pair select_move( + Logger& logger, + const GlobalState& state, + size_t player_index +); + +// Swap with newly caught Pokemon. +bool should_swap_with_newly_caught( + Logger& logger, + const GlobalState& state, + size_t player_index, + const std::string options[2] +); + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.cpp index fe8ee6bffd..63e9bcd4b5 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.cpp @@ -1,295 +1,295 @@ -/* Max Lair AI Path Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh_MaxLair_AI_PathMatchup.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -struct PathMatchDatabase{ - std::map> rentals_by_type; - std::map> type_vs_boss; - - static const PathMatchDatabase& instance(){ - static PathMatchDatabase database; - return database; - } - -private: - PathMatchDatabase(){ - std::string path = RESOURCE_PATH() + "PokemonSwSh/MaxLair/path_tree.json"; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - { - JsonObject& obj = root.get_object_throw("rental_by_type", path); - for (const auto& type : POKEMON_TYPE_SLUGS()){ - if (type.first == PokemonType::NONE){ - continue; - } - JsonArray& array = obj.get_array_throw(type.second, path); - std::set& set = rentals_by_type[type.first]; - for (auto& item : array){ - std::string& str = item.to_string_throw(path); - set.insert(std::move(str)); - } - } - } - - JsonObject& node = root.get_object_throw("base_node", path).get_object_throw("hash_table"); - for (auto& item : node){ - std::map& boss = type_vs_boss[item.first]; - - JsonObject& obj = item.second.to_object_throw(path).get_object_throw("hash_table", path); - - for (const auto& type : POKEMON_TYPE_SLUGS()){ - if (type.first == PokemonType::NONE){ - continue; - } - boss[type.first] = obj.get_double_throw(type.second, path); - } - } - } - - -}; - - -const std::set& rentals_by_type(PokemonType type){ - const PathMatchDatabase& database = PathMatchDatabase::instance(); - auto iter = database.rentals_by_type.find(type); - if (iter == database.rentals_by_type.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Type: " + std::to_string((int)type)); - } - return iter->second; -} - -double type_vs_boss(PokemonType type, const std::string& boss_slug){ - const PathMatchDatabase& database = PathMatchDatabase::instance(); - - auto iter0 = database.type_vs_boss.find(boss_slug); - if (iter0 == database.type_vs_boss.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Boss: " + boss_slug); - } - - auto iter1 = iter0->second.find(type); - if (iter1 == iter0->second.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Type: " + std::to_string((int)type)); - } - - return iter1->second; -} -double type_vs_boss(PokemonType type, PokemonType boss_type){ - using namespace papkmnlib; - - Type pkmnlib_type = serial_type_to_pkmnlib(boss_type); - - double weight = 0; - size_t count = 0; - for (const auto& item : all_bosses_by_dex()){ - const Pokemon& boss = get_pokemon(item.second); - if (boss_type == PokemonType::NONE || boss.has_type(pkmnlib_type)){ - weight += type_vs_boss(type, boss.name()); - count++; - } - } - - return weight / (double)count; -} - - - - - - - - - - - - - -void append_subpath( - std::vector>& paths, - const PathNode& node, - const std::vector>& subpaths -){ - for (const auto& item : subpaths){ - paths.emplace_back(); - std::vector& path = paths.back(); - path.emplace_back(node); - path.insert(path.end(), item.begin(), item.end()); - } -} -std::vector> generate_paths( - const PathMap& map, uint8_t wins, int8_t side -){ - std::vector> ret; - - if (wins == 0){ - append_subpath(ret, {0, map.mon1[0]}, generate_paths(map, 1, 0)); - append_subpath(ret, {1, map.mon1[1]}, generate_paths(map, 1, 1)); - return ret; - } - - if (side == -1){ - return ret; - } - - if (wins == 1){ - std::vector> left = generate_paths(map, 2, 0); - std::vector> right = generate_paths(map, 2, 1); - switch (map.path_type){ - case 0: - if (side == 0){ - append_subpath(ret, {0, map.mon2[0]}, left); - append_subpath(ret, {1, map.mon2[1]}, left); - append_subpath(ret, {2, map.mon2[2]}, left); - }else{ - append_subpath(ret, {0, map.mon2[2]}, left); - append_subpath(ret, {1, map.mon2[3]}, right); - } - break; - case 1: - if (side == 0){ - append_subpath(ret, {0, map.mon2[0]}, left); - append_subpath(ret, {1, map.mon2[1]}, left); - }else{ - append_subpath(ret, {0, map.mon2[1]}, left); - append_subpath(ret, {1, map.mon2[2]}, right); - append_subpath(ret, {2, map.mon2[3]}, right); - } - break; - case 2: - if (side == 0){ - append_subpath(ret, {0, map.mon2[0]}, left); - append_subpath(ret, {1, map.mon2[1]}, right); - }else{ - append_subpath(ret, {0, map.mon2[2]}, right); - append_subpath(ret, {1, map.mon2[3]}, right); - } - break; - } - return ret; - } - - if (wins == 2){ - switch (map.path_type){ - case 0: - if (side == 0){ - ret.emplace_back(std::vector{PathNode{0, map.mon3[0]}}); - ret.emplace_back(std::vector{PathNode{1, map.mon3[1]}}); - }else{ - ret.emplace_back(std::vector{PathNode{0, map.mon3[1]}}); - ret.emplace_back(std::vector{PathNode{1, map.mon3[2]}}); - ret.emplace_back(std::vector{PathNode{2, map.mon3[3]}}); - } - break; - case 1: - if (side == 0){ - ret.emplace_back(std::vector{PathNode{0, map.mon3[0]}}); - ret.emplace_back(std::vector{PathNode{1, map.mon3[1]}}); - ret.emplace_back(std::vector{PathNode{2, map.mon3[2]}}); - }else{ - ret.emplace_back(std::vector{PathNode{0, map.mon3[2]}}); - ret.emplace_back(std::vector{PathNode{1, map.mon3[3]}}); - } - break; - case 2: - if (side == 0){ - ret.emplace_back(std::vector{PathNode{0, map.mon3[0]}}); - ret.emplace_back(std::vector{PathNode{1, map.mon3[1]}}); - }else{ - ret.emplace_back(std::vector{PathNode{0, map.mon3[1]}}); - ret.emplace_back(std::vector{PathNode{1, map.mon3[2]}}); - ret.emplace_back(std::vector{PathNode{2, map.mon3[3]}}); - } - break; - } - return ret; - } - - return ret; -} - - -template -double evaluate_path(const Boss& boss, const std::vector& path){ - if (path.size() > 3){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Path is longer than 3: " + std::to_string(path.size())); - } - const double weights[] = {1, 2, 3}; - double weight = 0; - - size_t battle_index = 3 - path.size(); - size_t node_index = 0; - for (; battle_index < 3; node_index++, battle_index++){ - weight += type_vs_boss(path[node_index].type, boss) * weights[battle_index]; - } - return weight; -} - - -std::vector select_path( - Logger* logger, - const std::string& boss, - const PathMap& pathmap, uint8_t wins, int8_t path_side -){ -// if (boss.empty() && state.path.boss == PokemonType::NONE){ -// logger.log("No information known about boss.", COLOR_ORANGE); -// return {}; -// } - - std::vector> paths = generate_paths(pathmap, wins, path_side); - if (paths.empty()){ - if (logger){ - logger->log("No available paths due to read errors.", COLOR_RED); - } - return {}; - } - - std::multimap, std::greater> rank; - if (boss.empty()){ - for (const std::vector& path : paths){ - rank.emplace(evaluate_path(pathmap.boss, path), path); - } - }else{ - for (const std::vector& path : paths){ - rank.emplace(evaluate_path(boss, path), path); - } - } - std::string str = "Available Paths:\n"; - for (const auto& path : rank){ - str += std::to_string(path.first); - str += " : "; - str += dump_path(path.second); - str += "\n"; - } - if (logger){ - logger->log(str); - } - - return std::move(rank.begin()->second); -} - - - - -} -} -} -} +/* Max Lair AI Path Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh_MaxLair_AI_PathMatchup.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +struct PathMatchDatabase{ + std::map> rentals_by_type; + std::map> type_vs_boss; + + static const PathMatchDatabase& instance(){ + static PathMatchDatabase database; + return database; + } + +private: + PathMatchDatabase(){ + std::string path = RESOURCE_PATH() + "PokemonSwSh/MaxLair/path_tree.json"; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + { + JsonObject& obj = root.get_object_throw("rental_by_type", path); + for (const auto& type : POKEMON_TYPE_SLUGS()){ + if (type.first == PokemonType::NONE){ + continue; + } + JsonArray& array = obj.get_array_throw(type.second, path); + std::set& set = rentals_by_type[type.first]; + for (auto& item : array){ + std::string& str = item.to_string_throw(path); + set.insert(std::move(str)); + } + } + } + + JsonObject& node = root.get_object_throw("base_node", path).get_object_throw("hash_table"); + for (auto& item : node){ + std::map& boss = type_vs_boss[item.first]; + + JsonObject& obj = item.second.to_object_throw(path).get_object_throw("hash_table", path); + + for (const auto& type : POKEMON_TYPE_SLUGS()){ + if (type.first == PokemonType::NONE){ + continue; + } + boss[type.first] = obj.get_double_throw(type.second, path); + } + } + } + + +}; + + +const std::set& rentals_by_type(PokemonType type){ + const PathMatchDatabase& database = PathMatchDatabase::instance(); + auto iter = database.rentals_by_type.find(type); + if (iter == database.rentals_by_type.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Type: " + std::to_string((int)type)); + } + return iter->second; +} + +double type_vs_boss(PokemonType type, const std::string& boss_slug){ + const PathMatchDatabase& database = PathMatchDatabase::instance(); + + auto iter0 = database.type_vs_boss.find(boss_slug); + if (iter0 == database.type_vs_boss.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Boss: " + boss_slug); + } + + auto iter1 = iter0->second.find(type); + if (iter1 == iter0->second.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Type: " + std::to_string((int)type)); + } + + return iter1->second; +} +double type_vs_boss(PokemonType type, PokemonType boss_type){ + using namespace papkmnlib; + + Type pkmnlib_type = serial_type_to_pkmnlib(boss_type); + + double weight = 0; + size_t count = 0; + for (const auto& item : all_bosses_by_dex()){ + const Pokemon& boss = get_pokemon(item.second); + if (boss_type == PokemonType::NONE || boss.has_type(pkmnlib_type)){ + weight += type_vs_boss(type, boss.name()); + count++; + } + } + + return weight / (double)count; +} + + + + + + + + + + + + + +void append_subpath( + std::vector>& paths, + const PathNode& node, + const std::vector>& subpaths +){ + for (const auto& item : subpaths){ + paths.emplace_back(); + std::vector& path = paths.back(); + path.emplace_back(node); + path.insert(path.end(), item.begin(), item.end()); + } +} +std::vector> generate_paths( + const PathMap& map, uint8_t wins, int8_t side +){ + std::vector> ret; + + if (wins == 0){ + append_subpath(ret, {0, map.mon1[0]}, generate_paths(map, 1, 0)); + append_subpath(ret, {1, map.mon1[1]}, generate_paths(map, 1, 1)); + return ret; + } + + if (side == -1){ + return ret; + } + + if (wins == 1){ + std::vector> left = generate_paths(map, 2, 0); + std::vector> right = generate_paths(map, 2, 1); + switch (map.path_type){ + case 0: + if (side == 0){ + append_subpath(ret, {0, map.mon2[0]}, left); + append_subpath(ret, {1, map.mon2[1]}, left); + append_subpath(ret, {2, map.mon2[2]}, left); + }else{ + append_subpath(ret, {0, map.mon2[2]}, left); + append_subpath(ret, {1, map.mon2[3]}, right); + } + break; + case 1: + if (side == 0){ + append_subpath(ret, {0, map.mon2[0]}, left); + append_subpath(ret, {1, map.mon2[1]}, left); + }else{ + append_subpath(ret, {0, map.mon2[1]}, left); + append_subpath(ret, {1, map.mon2[2]}, right); + append_subpath(ret, {2, map.mon2[3]}, right); + } + break; + case 2: + if (side == 0){ + append_subpath(ret, {0, map.mon2[0]}, left); + append_subpath(ret, {1, map.mon2[1]}, right); + }else{ + append_subpath(ret, {0, map.mon2[2]}, right); + append_subpath(ret, {1, map.mon2[3]}, right); + } + break; + } + return ret; + } + + if (wins == 2){ + switch (map.path_type){ + case 0: + if (side == 0){ + ret.emplace_back(std::vector{PathNode{0, map.mon3[0]}}); + ret.emplace_back(std::vector{PathNode{1, map.mon3[1]}}); + }else{ + ret.emplace_back(std::vector{PathNode{0, map.mon3[1]}}); + ret.emplace_back(std::vector{PathNode{1, map.mon3[2]}}); + ret.emplace_back(std::vector{PathNode{2, map.mon3[3]}}); + } + break; + case 1: + if (side == 0){ + ret.emplace_back(std::vector{PathNode{0, map.mon3[0]}}); + ret.emplace_back(std::vector{PathNode{1, map.mon3[1]}}); + ret.emplace_back(std::vector{PathNode{2, map.mon3[2]}}); + }else{ + ret.emplace_back(std::vector{PathNode{0, map.mon3[2]}}); + ret.emplace_back(std::vector{PathNode{1, map.mon3[3]}}); + } + break; + case 2: + if (side == 0){ + ret.emplace_back(std::vector{PathNode{0, map.mon3[0]}}); + ret.emplace_back(std::vector{PathNode{1, map.mon3[1]}}); + }else{ + ret.emplace_back(std::vector{PathNode{0, map.mon3[1]}}); + ret.emplace_back(std::vector{PathNode{1, map.mon3[2]}}); + ret.emplace_back(std::vector{PathNode{2, map.mon3[3]}}); + } + break; + } + return ret; + } + + return ret; +} + + +template +double evaluate_path(const Boss& boss, const std::vector& path){ + if (path.size() > 3){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Path is longer than 3: " + std::to_string(path.size())); + } + const double weights[] = {1, 2, 3}; + double weight = 0; + + size_t battle_index = 3 - path.size(); + size_t node_index = 0; + for (; battle_index < 3; node_index++, battle_index++){ + weight += type_vs_boss(path[node_index].type, boss) * weights[battle_index]; + } + return weight; +} + + +std::vector select_path( + Logger* logger, + const std::string& boss, + const PathMap& pathmap, uint8_t wins, int8_t path_side +){ +// if (boss.empty() && state.path.boss == PokemonType::NONE){ +// logger.log("No information known about boss.", COLOR_ORANGE); +// return {}; +// } + + std::vector> paths = generate_paths(pathmap, wins, path_side); + if (paths.empty()){ + if (logger){ + logger->log("No available paths due to read errors.", COLOR_RED); + } + return {}; + } + + std::multimap, std::greater> rank; + if (boss.empty()){ + for (const std::vector& path : paths){ + rank.emplace(evaluate_path(pathmap.boss, path), path); + } + }else{ + for (const std::vector& path : paths){ + rank.emplace(evaluate_path(boss, path), path); + } + } + std::string str = "Available Paths:\n"; + for (const auto& path : rank){ + str += std::to_string(path.first); + str += " : "; + str += dump_path(path.second); + str += "\n"; + } + if (logger){ + logger->log(str); + } + + return std::move(rank.begin()->second); +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h index 6f78a6963c..d8ed6cc901 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_PathMatchup.h @@ -1,46 +1,46 @@ -/* Max Lair AI Path Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_PathMatchup_H -#define PokemonAutomation_PokemonSwSh_MaxLair_AI_PathMatchup_H - -#include -#include -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Pokemon_Types.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -const std::set& rentals_by_type(PokemonType type); -double type_vs_boss(PokemonType type, const std::string& boss_slug); -double type_vs_boss(PokemonType type, PokemonType boss_type); - - - -std::vector> generate_paths( - const PathMap& map, uint8_t wins, int8_t side -); - - -std::vector select_path( - Logger* logger, - const std::string& boss, - const PathMap& pathmap, uint8_t wins, int8_t path_side -); - - - -} -} -} -} -#endif +/* Max Lair AI Path Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_PathMatchup_H +#define PokemonAutomation_PokemonSwSh_MaxLair_AI_PathMatchup_H + +#include +#include +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Pokemon_Types.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +const std::set& rentals_by_type(PokemonType type); +double type_vs_boss(PokemonType type, const std::string& boss_slug); +double type_vs_boss(PokemonType type, PokemonType boss_type); + + + +std::vector> generate_paths( + const PathMap& map, uint8_t wins, int8_t side +); + + +std::vector select_path( + Logger* logger, + const std::string& boss, + const PathMap& pathmap, uint8_t wins, int8_t path_side +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.cpp index 3cf85bfb9e..7bef040050 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.cpp @@ -1,86 +1,86 @@ -/* Max Lair AI Rental/Boss Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -struct MatchupDatabase{ - std::map> map; - - static const MatchupDatabase& instance(){ - static MatchupDatabase database; - return database; - } - - double get(const std::string& rental, const std::string& boss) const{ - auto iter0 = map.find(rental); - if (iter0 == map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Rental not found: " + rental); - } - auto iter1 = iter0->second.find(boss); - if (iter1 == iter0->second.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Boss not found: " + rental); - } - return iter1->second; - } - -private: - MatchupDatabase(){ - std::string path = RESOURCE_PATH() + "PokemonSwSh/MaxLair/boss_matchup_LUT.json"; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - for (auto& item0 : root){ - std::map& sub = map[item0.first]; - JsonObject& obj = item0.second.to_object_throw(path); - for (auto& item1 : obj){ - sub[item1.first] = item1.second.to_double_throw(path); - } - } - } -}; - -double rental_vs_boss_matchup(const std::string& rental, const std::string& boss){ - return MatchupDatabase::instance().get(rental, boss); -} -double rental_vs_boss_matchup(const std::string& rental, const std::vector& bosses){ - using namespace papkmnlib; - - double score = 0; - if (bosses.empty()){ - const auto& all_bosses = all_boss_pokemon(); - for (const auto& boss : all_bosses){ - score += rental_vs_boss_matchup(rental, boss.second.name()); - } - score /= bosses.size(); - }else{ - for (const std::string& boss : bosses){ - score += rental_vs_boss_matchup(rental, boss); - } - score /= bosses.size(); - } - return score; -} - - - - - -} -} -} -} +/* Max Lair AI Rental/Boss Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +struct MatchupDatabase{ + std::map> map; + + static const MatchupDatabase& instance(){ + static MatchupDatabase database; + return database; + } + + double get(const std::string& rental, const std::string& boss) const{ + auto iter0 = map.find(rental); + if (iter0 == map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Rental not found: " + rental); + } + auto iter1 = iter0->second.find(boss); + if (iter1 == iter0->second.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Boss not found: " + rental); + } + return iter1->second; + } + +private: + MatchupDatabase(){ + std::string path = RESOURCE_PATH() + "PokemonSwSh/MaxLair/boss_matchup_LUT.json"; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + for (auto& item0 : root){ + std::map& sub = map[item0.first]; + JsonObject& obj = item0.second.to_object_throw(path); + for (auto& item1 : obj){ + sub[item1.first] = item1.second.to_double_throw(path); + } + } + } +}; + +double rental_vs_boss_matchup(const std::string& rental, const std::string& boss){ + return MatchupDatabase::instance().get(rental, boss); +} +double rental_vs_boss_matchup(const std::string& rental, const std::vector& bosses){ + using namespace papkmnlib; + + double score = 0; + if (bosses.empty()){ + const auto& all_bosses = all_boss_pokemon(); + for (const auto& boss : all_bosses){ + score += rental_vs_boss_matchup(rental, boss.second.name()); + } + score /= bosses.size(); + }else{ + for (const std::string& boss : bosses){ + score += rental_vs_boss_matchup(rental, boss); + } + score /= bosses.size(); + } + return score; +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h index 8c967413b5..fd66edc976 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_RentalBossMatchup.h @@ -1,28 +1,28 @@ -/* Max Lair AI Rental/Boss Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_RentalBossMatchup_H -#define PokemonAutomation_PokemonSwSh_MaxLair_AI_RentalBossMatchup_H - -#include -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -double rental_vs_boss_matchup(const std::string& rental, const std::string& boss); -double rental_vs_boss_matchup(const std::string& rental, const std::vector& bosses); - - - -} -} -} -} -#endif +/* Max Lair AI Rental/Boss Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_RentalBossMatchup_H +#define PokemonAutomation_PokemonSwSh_MaxLair_AI_RentalBossMatchup_H + +#include +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +double rental_vs_boss_matchup(const std::string& rental, const std::string& boss); +double rental_vs_boss_matchup(const std::string& rental, const std::vector& bosses); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectItem.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectItem.cpp index 327cf11475..6a4a0c9fd1 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectItem.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectItem.cpp @@ -1,38 +1,38 @@ -/* Max Lair AI Select Item - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -// Return -1 if no selecting an item. -int8_t select_item( - Logger& logger, - const GlobalState& state, - size_t player_index -){ - logger.log( - "Player " + std::to_string(player_index) + - ": Selecting an item... State =>\n" + state.dump(), - COLOR_PURPLE - ); - - // Can't do anything since there's no item detection yet. -// return random(0, 4); - return 0; -} - - - -} -} -} -} +/* Max Lair AI Select Item + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +// Return -1 if no selecting an item. +int8_t select_item( + Logger& logger, + const GlobalState& state, + size_t player_index +){ + logger.log( + "Player " + std::to_string(player_index) + + ": Selecting an item... State =>\n" + state.dump(), + COLOR_PURPLE + ); + + // Can't do anything since there's no item detection yet. +// return random(0, 4); + return 0; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectMove.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectMove.cpp index f5419a3bb4..46ce273fc1 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectMove.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectMove.cpp @@ -1,162 +1,162 @@ -/* Max Lair AI Select Move - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" -#include "PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_AI_Tools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -std::pair select_move_ai( - Logger& logger, - const GlobalState& state, - size_t player_index -){ - using namespace papkmnlib; - - // Build PkmnLib classes. - Pokemon boss = get_pokemon(*state.opponent.begin()); - boss.set_hp_ratio(state.opponent_hp); - - std::unique_ptr self; - std::vector> teammates; - - for (size_t c = 0; c < 4; c++){ - const PlayerState& player = state.players[c]; - if (player.pokemon.empty()){ - continue; - } - - std::unique_ptr pokemon = convert_player_to_pkmnlib(player); - pokemon->transform_from_ditto(boss); - - if (c == player_index){ - self = std::move(pokemon); - }else{ - teammates.emplace_back(std::move(pokemon)); - } - } - - // TODO: Proper field detection. - Field field; - field.set_default_field(boss.name()); - - std::vector teammates_v; - for (const std::unique_ptr& item : teammates){ - teammates_v.emplace_back(item.get()); - } - - std::multimap, std::greater> rank; - - // No dmax. - if (state.players[player_index].dmax_turns_left <= 0){ - for (size_t c = 0; c < self->num_moves(); c++){ - if (self->pp(c) <= 0){ - continue; - } - if (state.players[player_index].move_blocked[c]){ - continue; - } - double score = calc_move_score(*self, boss, teammates_v, c, field); - rank.emplace( - score, - std::pair{(uint8_t)c, false} - ); - } - } - - // Dmax - self->set_is_dynamax(true); - if (state.players[player_index].dmax_turns_left > 0 || state.players[player_index].can_dmax){ - for (size_t c = 0; c < self->num_moves(); c++){ - if (self->pp(c) <= 0){ - continue; - } - if (state.players[player_index].move_blocked[c]){ - continue; - } - double score = calc_move_score(*self, boss, teammates_v, c, field); - rank.emplace( - score, - std::pair{(uint8_t)c, true} - ); - } - } - - // Print options and scores. - std::string move_dump = "Move Score:\n"; - for (const auto& move : rank){ - uint8_t slot = move.second.first; - move_dump += std::to_string(move.first) + " : "; - move_dump += move.second.second - ? self->max_move(slot).name() - : self->move(slot).name(); - move_dump += "\n"; - } - logger.log(move_dump); - - if (rank.empty()){ - logger.log("Unable to calculate moves. Picking a random move...", COLOR_RED); - return {(uint8_t)random(0, 3), false}; - } - if (rank.begin()->first < 0){ - logger.log("No viable moves found. Picking a random move...", COLOR_RED); - return {(uint8_t)random(0, 3), false}; - } - - return rank.begin()->second; -} - - - - - -// Return 0 - 3 for move position. 2nd parameter is dmax. -std::pair select_move( - Logger& logger, - const GlobalState& state, - size_t player_index -){ - logger.log( - "Player " + std::to_string(player_index) + - ": Selecting a move... State =>\n" + state.dump(), - COLOR_PURPLE - ); - - if (state.opponent.empty()){ - logger.log("Don't know who the opponent is. Picking a random move...", COLOR_RED); - return {(uint8_t)random(0, 3), false}; - } - - const PlayerState& player = state.players[player_index]; - const MaxLairMon* self = get_maxlair_mon_nothrow(player.pokemon); - if (self == nullptr){ - logger.log("Don't know what you are. Picking a random move...", COLOR_RED); - return {(uint8_t)random(0, 3), false}; - } - - std::pair result = select_move_ai(logger, state, player_index); - if (player.move_blocked[result.first]){ - logger.log("AI picked an unusable move. Picking random move to avoid hanging...", COLOR_RED); - return {(uint8_t)random(0, 3), false}; - } - - return result; -} - - - -} -} -} -} +/* Max Lair AI Select Move + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" +#include "PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_AI_Tools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +std::pair select_move_ai( + Logger& logger, + const GlobalState& state, + size_t player_index +){ + using namespace papkmnlib; + + // Build PkmnLib classes. + Pokemon boss = get_pokemon(*state.opponent.begin()); + boss.set_hp_ratio(state.opponent_hp); + + std::unique_ptr self; + std::vector> teammates; + + for (size_t c = 0; c < 4; c++){ + const PlayerState& player = state.players[c]; + if (player.pokemon.empty()){ + continue; + } + + std::unique_ptr pokemon = convert_player_to_pkmnlib(player); + pokemon->transform_from_ditto(boss); + + if (c == player_index){ + self = std::move(pokemon); + }else{ + teammates.emplace_back(std::move(pokemon)); + } + } + + // TODO: Proper field detection. + Field field; + field.set_default_field(boss.name()); + + std::vector teammates_v; + for (const std::unique_ptr& item : teammates){ + teammates_v.emplace_back(item.get()); + } + + std::multimap, std::greater> rank; + + // No dmax. + if (state.players[player_index].dmax_turns_left <= 0){ + for (size_t c = 0; c < self->num_moves(); c++){ + if (self->pp(c) <= 0){ + continue; + } + if (state.players[player_index].move_blocked[c]){ + continue; + } + double score = calc_move_score(*self, boss, teammates_v, c, field); + rank.emplace( + score, + std::pair{(uint8_t)c, false} + ); + } + } + + // Dmax + self->set_is_dynamax(true); + if (state.players[player_index].dmax_turns_left > 0 || state.players[player_index].can_dmax){ + for (size_t c = 0; c < self->num_moves(); c++){ + if (self->pp(c) <= 0){ + continue; + } + if (state.players[player_index].move_blocked[c]){ + continue; + } + double score = calc_move_score(*self, boss, teammates_v, c, field); + rank.emplace( + score, + std::pair{(uint8_t)c, true} + ); + } + } + + // Print options and scores. + std::string move_dump = "Move Score:\n"; + for (const auto& move : rank){ + uint8_t slot = move.second.first; + move_dump += std::to_string(move.first) + " : "; + move_dump += move.second.second + ? self->max_move(slot).name() + : self->move(slot).name(); + move_dump += "\n"; + } + logger.log(move_dump); + + if (rank.empty()){ + logger.log("Unable to calculate moves. Picking a random move...", COLOR_RED); + return {(uint8_t)random(0, 3), false}; + } + if (rank.begin()->first < 0){ + logger.log("No viable moves found. Picking a random move...", COLOR_RED); + return {(uint8_t)random(0, 3), false}; + } + + return rank.begin()->second; +} + + + + + +// Return 0 - 3 for move position. 2nd parameter is dmax. +std::pair select_move( + Logger& logger, + const GlobalState& state, + size_t player_index +){ + logger.log( + "Player " + std::to_string(player_index) + + ": Selecting a move... State =>\n" + state.dump(), + COLOR_PURPLE + ); + + if (state.opponent.empty()){ + logger.log("Don't know who the opponent is. Picking a random move...", COLOR_RED); + return {(uint8_t)random(0, 3), false}; + } + + const PlayerState& player = state.players[player_index]; + const MaxLairMon* self = get_maxlair_mon_nothrow(player.pokemon); + if (self == nullptr){ + logger.log("Don't know what you are. Picking a random move...", COLOR_RED); + return {(uint8_t)random(0, 3), false}; + } + + std::pair result = select_move_ai(logger, state, player_index); + if (player.move_blocked[result.first]){ + logger.log("AI picked an unusable move. Picking random move to avoid hanging...", COLOR_RED); + return {(uint8_t)random(0, 3), false}; + } + + return result; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectPath.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectPath.cpp index 0f83517c1f..295c4d51ae 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectPath.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectPath.cpp @@ -1,82 +1,82 @@ -/* Max Lair AI Select Path - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_AI_PathMatchup.h" - -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - - - - - - - - - -// 0 for left-most path. -// 1 for 2nd from left. -// 2 ... -std::vector select_path( - Logger& logger, - const GlobalState& state, - size_t player_index -){ - logger.log( - "Player " + std::to_string(player_index) + - ": Choosing a path... State =>\n" + state.dump(), - COLOR_PURPLE - ); - - std::vector> paths = generate_paths(state.path, state.wins, state.path_side); - if (paths.empty()){ - return {}; - } - -// cout << "Paths = " << paths.size() << endl; -#if 0 - std::string str = "Available Paths:\n"; - for (const auto& path : paths){ - for (const auto& item : path){ - str += "["; - str += std::to_string(item.path_slot); - str += ":"; - str += get_type_slug(item.type); - str += "] "; - } - str += "\n"; - } - logger.log(str); - - // Can't do anything since there's no path detection yet. - return paths[random(0, (int)paths.size() - 1)][0].path_slot; -#endif - - std::vector path = select_path( - &logger, - state.boss, - state.path, state.wins, state.path_side - ); - if (path.empty()){ - return {}; - } - return path; -} - - - -} -} -} -} +/* Max Lair AI Select Path + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_AI_PathMatchup.h" + +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + + + + + + + + + +// 0 for left-most path. +// 1 for 2nd from left. +// 2 ... +std::vector select_path( + Logger& logger, + const GlobalState& state, + size_t player_index +){ + logger.log( + "Player " + std::to_string(player_index) + + ": Choosing a path... State =>\n" + state.dump(), + COLOR_PURPLE + ); + + std::vector> paths = generate_paths(state.path, state.wins, state.path_side); + if (paths.empty()){ + return {}; + } + +// cout << "Paths = " << paths.size() << endl; +#if 0 + std::string str = "Available Paths:\n"; + for (const auto& path : paths){ + for (const auto& item : path){ + str += "["; + str += std::to_string(item.path_slot); + str += ":"; + str += get_type_slug(item.type); + str += "] "; + } + str += "\n"; + } + logger.log(str); + + // Can't do anything since there's no path detection yet. + return paths[random(0, (int)paths.size() - 1)][0].path_slot; +#endif + + std::vector path = select_path( + &logger, + state.boss, + state.path, state.wins, state.path_side + ); + if (path.empty()){ + return {}; + } + return path; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectStarter.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectStarter.cpp index 0f0d973a9e..0e815ae341 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectStarter.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SelectStarter.cpp @@ -1,74 +1,74 @@ -/* Max Lair AI Select Starter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" -#include "PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_AI_Tools.h" -#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -// 0 for top Pokemon -// 1 for middle Pokemon -// 2 for bottom Pokemon -int8_t select_starter( - Logger& logger, - const GlobalState& state, - size_t player_index, - const std::string options[3] -){ - logger.log( - "Player " + std::to_string(player_index) + - ": Choosing a starter... State =>\n" + state.dump(), - COLOR_PURPLE - ); - - using namespace papkmnlib; - - std::vector bosses = get_boss_candidates(state); - if (bosses.empty()){ - logger.log("Cannot pick a starter since there are no boss candidates.", COLOR_RED); - return 0; - } - - std::multimap> rank; - for (uint8_t c = 0; c < 3; c++){ - if (options[c].empty()){ - continue; - } -// const Pokemon& rental = get_pokemon(options[c]); - double score = 0; - for (const Pokemon* boss : bosses){ -// score += evaluate_matchup(rental, *boss, {}, 4); - score += rental_vs_boss_matchup(options[c], boss->name()); - } - score /= bosses.size(); - rank.emplace(score, c); - } - if (rank.empty()){ - logger.log("Cannot pick a starter since none of the choices could be read.", COLOR_RED); - return 0; - } - - std::string dump = "Selection Score:\n"; - for (const auto& item : rank){ - dump += std::to_string(item.first) + " : " + options[item.second] + "\n"; - } - logger.log(dump); - - return rank.begin()->second; -} - - - -} -} -} -} +/* Max Lair AI Select Starter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" +#include "PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_AI_Tools.h" +#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +// 0 for top Pokemon +// 1 for middle Pokemon +// 2 for bottom Pokemon +int8_t select_starter( + Logger& logger, + const GlobalState& state, + size_t player_index, + const std::string options[3] +){ + logger.log( + "Player " + std::to_string(player_index) + + ": Choosing a starter... State =>\n" + state.dump(), + COLOR_PURPLE + ); + + using namespace papkmnlib; + + std::vector bosses = get_boss_candidates(state); + if (bosses.empty()){ + logger.log("Cannot pick a starter since there are no boss candidates.", COLOR_RED); + return 0; + } + + std::multimap> rank; + for (uint8_t c = 0; c < 3; c++){ + if (options[c].empty()){ + continue; + } +// const Pokemon& rental = get_pokemon(options[c]); + double score = 0; + for (const Pokemon* boss : bosses){ +// score += evaluate_matchup(rental, *boss, {}, 4); + score += rental_vs_boss_matchup(options[c], boss->name()); + } + score /= bosses.size(); + rank.emplace(score, c); + } + if (rank.empty()){ + logger.log("Cannot pick a starter since none of the choices could be read.", COLOR_RED); + return 0; + } + + std::string dump = "Selection Score:\n"; + for (const auto& item : rank){ + dump += std::to_string(item.first) + " : " + options[item.second] + "\n"; + } + logger.log(dump); + + return rank.begin()->second; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapCatch.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapCatch.cpp index 193c5952ff..b178fc30eb 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapCatch.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapCatch.cpp @@ -1,102 +1,102 @@ -/* Max Lair AI Swap with Newly Caught - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_AI_Tools.h" -#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - - - -// Swap with newly caught Pokemon. -bool should_swap_with_newly_caught( - Logger& logger, - const GlobalState& state, - size_t player_index, - const std::string options[2] -){ - logger.log( - "Player " + std::to_string(player_index) + - ": Deciding whether to swap with newly caught... State =>\n" + state.dump(), - COLOR_PURPLE - ); - - using namespace papkmnlib; - - if (options[1].empty()){ - logger.log("Unable to read replacement candidate. Taking if you have the least HP.", COLOR_RED); - return swap_if_least_hp(state, player_index); - } - - - std::vector rental_candidates_on_path = - get_rental_candidates_on_path_pkmnlib(state); - - std::vector boss_candidates_on_path = - get_boss_candidates(state); - - std::unique_ptr current_team[4]; - current_team[0] = convert_player_to_pkmnlib(state.players[0]); - current_team[1] = convert_player_to_pkmnlib(state.players[1]); - current_team[2] = convert_player_to_pkmnlib(state.players[2]); - current_team[3] = convert_player_to_pkmnlib(state.players[3]); - - std::multimap> rank; - for (int8_t c = -1; c < 4; c++){ - const Pokemon* hypothetical_team[4]; - hypothetical_team[0] = current_team[0].get(); - hypothetical_team[1] = current_team[1].get(); - hypothetical_team[2] = current_team[2].get(); - hypothetical_team[3] = current_team[3].get(); - if (c >= 0){ - hypothetical_team[c] = &get_pokemon(options[1]); - } - double score = evaluate_hypothetical_team( - state, - hypothetical_team, - rental_candidates_on_path, - boss_candidates_on_path - ); - rank.emplace(score, c); - } - - if (rank.empty()){ - logger.log("Unable to compute decisions. Taking if you have the least HP.", COLOR_RED); - return swap_if_least_hp(state, player_index); - } - - std::string dump = "Selection Score:\n"; - for (const auto& item : rank){ - dump += std::to_string(item.first) + " : "; - if (item.second < 0){ - dump += "Nobody"; - }else{ - dump += "Player " + std::to_string(item.second); - } - dump += "\n"; - } - logger.log(dump); - - return rank.begin()->second == (int8_t)player_index; -} - - - -} -} -} -} +/* Max Lair AI Swap with Newly Caught + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_AI_Tools.h" +#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + + + +// Swap with newly caught Pokemon. +bool should_swap_with_newly_caught( + Logger& logger, + const GlobalState& state, + size_t player_index, + const std::string options[2] +){ + logger.log( + "Player " + std::to_string(player_index) + + ": Deciding whether to swap with newly caught... State =>\n" + state.dump(), + COLOR_PURPLE + ); + + using namespace papkmnlib; + + if (options[1].empty()){ + logger.log("Unable to read replacement candidate. Taking if you have the least HP.", COLOR_RED); + return swap_if_least_hp(state, player_index); + } + + + std::vector rental_candidates_on_path = + get_rental_candidates_on_path_pkmnlib(state); + + std::vector boss_candidates_on_path = + get_boss_candidates(state); + + std::unique_ptr current_team[4]; + current_team[0] = convert_player_to_pkmnlib(state.players[0]); + current_team[1] = convert_player_to_pkmnlib(state.players[1]); + current_team[2] = convert_player_to_pkmnlib(state.players[2]); + current_team[3] = convert_player_to_pkmnlib(state.players[3]); + + std::multimap> rank; + for (int8_t c = -1; c < 4; c++){ + const Pokemon* hypothetical_team[4]; + hypothetical_team[0] = current_team[0].get(); + hypothetical_team[1] = current_team[1].get(); + hypothetical_team[2] = current_team[2].get(); + hypothetical_team[3] = current_team[3].get(); + if (c >= 0){ + hypothetical_team[c] = &get_pokemon(options[1]); + } + double score = evaluate_hypothetical_team( + state, + hypothetical_team, + rental_candidates_on_path, + boss_candidates_on_path + ); + rank.emplace(score, c); + } + + if (rank.empty()){ + logger.log("Unable to compute decisions. Taking if you have the least HP.", COLOR_RED); + return swap_if_least_hp(state, player_index); + } + + std::string dump = "Selection Score:\n"; + for (const auto& item : rank){ + dump += std::to_string(item.first) + " : "; + if (item.second < 0){ + dump += "Nobody"; + }else{ + dump += "Player " + std::to_string(item.second); + } + dump += "\n"; + } + logger.log(dump); + + return rank.begin()->second == (int8_t)player_index; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapProfessor.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapProfessor.cpp index 1086368a6f..c7d48011cb 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapProfessor.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_SwapProfessor.cpp @@ -1,168 +1,168 @@ -/* Max Lair AI Swap with Professor - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" -#include "PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_AI_Tools.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -// Professor offers to exchange a Pokemon. -bool should_swap_with_professor( - Logger& logger, - const GlobalState& state, - size_t player_index -){ - logger.log( - "Player " + std::to_string(player_index) + - ": Deciding whether to swap with professor... State =>\n" + state.dump(), - COLOR_PURPLE - ); - - using namespace papkmnlib; - - uint8_t lives = 4; - - - std::vector rental_candidates_on_path = - get_rental_candidates_on_path_pkmnlib(state); - - std::vector boss_candidates_on_path = - get_boss_candidates(state); - - std::unique_ptr current_team[4]; - current_team[0] = convert_player_to_pkmnlib(state.players[0]); - current_team[1] = convert_player_to_pkmnlib(state.players[1]); - current_team[2] = convert_player_to_pkmnlib(state.players[2]); - current_team[3] = convert_player_to_pkmnlib(state.players[3]); - - - // Find the "average" rental against this boss. - std::multimap list; - for (const Pokemon* boss : boss_candidates_on_path){ - for (const auto& rental : all_rental_pokemon()){ - if (state.seen.find(rental.first) != state.seen.end()){ - continue; - } - list.emplace(evaluate_matchup(rental.second, *boss, {}, lives), &rental.second); - } - } - if (list.empty()){ - throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, "Opponent candidate list is empty."); - } - size_t midpoint = list.size() / 2; - for (size_t c = 0; c < midpoint; c++){ - list.erase(list.begin()); - } - const Pokemon* average_rental = list.begin()->second; - list.clear(); - - - - std::multimap> rank; -#if 0 - { - const Pokemon* hypothetical_team[4]; - hypothetical_team[0] = current_team[0].get(); - hypothetical_team[1] = current_team[1].get(); - hypothetical_team[2] = current_team[2].get(); - hypothetical_team[3] = current_team[3].get(); - double score = evaluate_hypothetical_team( - state, - hypothetical_team, - rental_candidates_on_path, - boss_candidates_on_path - ); - rank.emplace(score, -1); - } - for (int8_t c = 0; c < 4; c++){ - const Pokemon* hypothetical_team[4]; - hypothetical_team[0] = current_team[0].get(); - hypothetical_team[1] = current_team[1].get(); - hypothetical_team[2] = current_team[2].get(); - hypothetical_team[3] = current_team[3].get(); - - double score = 0; - size_t count = 0; - for (const auto& mon : all_rental_pokemon()){ - if (state.seen.find(mon.first) != state.seen.end()){ - continue; - } - logger.log(std::to_string(count)); - hypothetical_team[c] = &mon.second; - score += evaluate_hypothetical_team( - state, - hypothetical_team, - rental_candidates_on_path, - boss_candidates_on_path - ); - count++; - } -// cout << "total score = " << score << endl; -// cout << "candidates = " << rental_candidates_on_path.size() << endl; - score /= count; - - rank.emplace(score, c); - } -#endif - for (int8_t c = -1; c < 4; c++){ - const Pokemon* hypothetical_team[4]; - hypothetical_team[0] = current_team[0].get(); - hypothetical_team[1] = current_team[1].get(); - hypothetical_team[2] = current_team[2].get(); - hypothetical_team[3] = current_team[3].get(); - if (c >= 0){ - hypothetical_team[c] = average_rental; - } - double score = evaluate_hypothetical_team( - state, - hypothetical_team, - rental_candidates_on_path, - boss_candidates_on_path - ); - rank.emplace(score, c); - } - - - if (rank.empty()){ - logger.log("Unable to compute decisions. Taking if you have the least HP.", COLOR_RED); - return swap_if_least_hp(state, player_index); - } - - std::string dump = "Selection Score:\n"; - for (const auto& item : rank){ - dump += std::to_string(item.first) + " : "; - if (item.second < 0){ - dump += "Nobody"; - }else{ - dump += "Player " + std::to_string(item.second); - } - dump += "\n"; - } - logger.log(dump); - - return rank.begin()->second == (int8_t)player_index; - - -// return swap_if_least_hp(state, player_index); -} - - - -} -} -} -} +/* Max Lair AI Swap with Professor + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" +#include "PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_AI_Tools.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +// Professor offers to exchange a Pokemon. +bool should_swap_with_professor( + Logger& logger, + const GlobalState& state, + size_t player_index +){ + logger.log( + "Player " + std::to_string(player_index) + + ": Deciding whether to swap with professor... State =>\n" + state.dump(), + COLOR_PURPLE + ); + + using namespace papkmnlib; + + uint8_t lives = 4; + + + std::vector rental_candidates_on_path = + get_rental_candidates_on_path_pkmnlib(state); + + std::vector boss_candidates_on_path = + get_boss_candidates(state); + + std::unique_ptr current_team[4]; + current_team[0] = convert_player_to_pkmnlib(state.players[0]); + current_team[1] = convert_player_to_pkmnlib(state.players[1]); + current_team[2] = convert_player_to_pkmnlib(state.players[2]); + current_team[3] = convert_player_to_pkmnlib(state.players[3]); + + + // Find the "average" rental against this boss. + std::multimap list; + for (const Pokemon* boss : boss_candidates_on_path){ + for (const auto& rental : all_rental_pokemon()){ + if (state.seen.find(rental.first) != state.seen.end()){ + continue; + } + list.emplace(evaluate_matchup(rental.second, *boss, {}, lives), &rental.second); + } + } + if (list.empty()){ + throw InternalProgramError(&logger, PA_CURRENT_FUNCTION, "Opponent candidate list is empty."); + } + size_t midpoint = list.size() / 2; + for (size_t c = 0; c < midpoint; c++){ + list.erase(list.begin()); + } + const Pokemon* average_rental = list.begin()->second; + list.clear(); + + + + std::multimap> rank; +#if 0 + { + const Pokemon* hypothetical_team[4]; + hypothetical_team[0] = current_team[0].get(); + hypothetical_team[1] = current_team[1].get(); + hypothetical_team[2] = current_team[2].get(); + hypothetical_team[3] = current_team[3].get(); + double score = evaluate_hypothetical_team( + state, + hypothetical_team, + rental_candidates_on_path, + boss_candidates_on_path + ); + rank.emplace(score, -1); + } + for (int8_t c = 0; c < 4; c++){ + const Pokemon* hypothetical_team[4]; + hypothetical_team[0] = current_team[0].get(); + hypothetical_team[1] = current_team[1].get(); + hypothetical_team[2] = current_team[2].get(); + hypothetical_team[3] = current_team[3].get(); + + double score = 0; + size_t count = 0; + for (const auto& mon : all_rental_pokemon()){ + if (state.seen.find(mon.first) != state.seen.end()){ + continue; + } + logger.log(std::to_string(count)); + hypothetical_team[c] = &mon.second; + score += evaluate_hypothetical_team( + state, + hypothetical_team, + rental_candidates_on_path, + boss_candidates_on_path + ); + count++; + } +// cout << "total score = " << score << endl; +// cout << "candidates = " << rental_candidates_on_path.size() << endl; + score /= count; + + rank.emplace(score, c); + } +#endif + for (int8_t c = -1; c < 4; c++){ + const Pokemon* hypothetical_team[4]; + hypothetical_team[0] = current_team[0].get(); + hypothetical_team[1] = current_team[1].get(); + hypothetical_team[2] = current_team[2].get(); + hypothetical_team[3] = current_team[3].get(); + if (c >= 0){ + hypothetical_team[c] = average_rental; + } + double score = evaluate_hypothetical_team( + state, + hypothetical_team, + rental_candidates_on_path, + boss_candidates_on_path + ); + rank.emplace(score, c); + } + + + if (rank.empty()){ + logger.log("Unable to compute decisions. Taking if you have the least HP.", COLOR_RED); + return swap_if_least_hp(state, player_index); + } + + std::string dump = "Selection Score:\n"; + for (const auto& item : rank){ + dump += std::to_string(item.first) + " : "; + if (item.second < 0){ + dump += "Nobody"; + }else{ + dump += "Player " + std::to_string(item.second); + } + dump += "\n"; + } + logger.log(dump); + + return rank.begin()->second == (int8_t)player_index; + + +// return swap_if_least_hp(state, player_index); +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.cpp index fa8db53ae8..12117dd32d 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.cpp @@ -1,265 +1,265 @@ -/* Max Lair AI Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" -#include "PokemonSwSh_MaxLair_AI_Tools.h" -#include "PokemonSwSh_MaxLair_AI_PathMatchup.h" -#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -std::unique_ptr convert_player_to_pkmnlib(const PlayerState& player){ - using namespace papkmnlib; - if (player.pokemon.empty()){ - return nullptr; - } - std::unique_ptr pokemon(new Pokemon(get_pokemon(player.pokemon))); - pokemon->set_hp_ratio(player.health.value.dead ? 0 : player.health.value.hp); - pokemon->set_is_dynamax(player.dmax_turns_left > 0); - size_t move_count = std::min(pokemon->num_moves(), (size_t)4); - for (size_t i = 0; i < move_count; i++){ - int8_t pp = player.pp[i]; - if (pp < 0){ - pp = pokemon->move(i).pp(); - } - pokemon->update_pp(i, pp); - } - return pokemon; -} - - - - -std::set get_rental_candidates_on_path( - const std::vector& path, - const std::set& exclusions -){ - std::set candidates; - for (const PathNode& node : path){ - for (const std::string& rental : rentals_by_type(node.type)){ - if (exclusions.find(rental) == exclusions.end()){ - candidates.insert(rental); - } - } - } - return candidates; -} -std::set get_rental_candidates_on_path(const GlobalState& state){ - return get_rental_candidates_on_path(state.last_best_path, state.seen); -} -std::vector get_rental_candidates_on_path_pkmnlib(const GlobalState& state){ - std::vector candidates; - for (const std::string& candidate : get_rental_candidates_on_path(state)){ - candidates.emplace_back(&papkmnlib::get_pokemon(candidate)); - } - return candidates; -} -std::vector get_boss_candidates(const GlobalState& state){ - using namespace papkmnlib; - std::vector candidates; - if (state.boss.empty()){ - PokemonType boss_type = state.path.boss; - Type pkmnlib_type = serial_type_to_pkmnlib(boss_type); - for (const auto& item : all_boss_pokemon()){ - const Pokemon& boss = get_pokemon(item.first); - if (boss_type == PokemonType::NONE || boss.has_type(pkmnlib_type)){ - candidates.emplace_back(&boss); - } - } - }else{ - candidates.emplace_back(&get_pokemon(state.boss)); - } - return candidates; -} - - - - - -double rental_vs_boss_matchup(const std::string& rental, const std::vector& bosses){ - using namespace papkmnlib; - - if (bosses.empty()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Boss list cannot be empty."); - } - double score = 0; - if (rental.empty()){ - for (const Pokemon* boss : bosses){ - for (const auto& candidate : all_rental_pokemon()){ - score += rental_vs_boss_matchup(candidate.first, boss->name()); - } - } - score /= bosses.size() * all_rental_pokemon().size(); - }else{ - for (const Pokemon* boss : bosses){ - score += rental_vs_boss_matchup(rental, boss->name()); - } - score /= bosses.size(); - } - return score; -} -double rental_vs_boss_matchup(const papkmnlib::Pokemon* rental, const std::vector& bosses){ - return rental_vs_boss_matchup(rental == nullptr ? "" : rental->name(), bosses); -} - - - -double evaluate_hypothetical_team( - const GlobalState& state, - const papkmnlib::Pokemon* team[4], - const std::vector& rental_candidates_on_path, - const std::vector& boss_candidates_on_path -){ - using namespace papkmnlib; - - uint8_t lives = 4; - - double total = 0; - for (size_t c = 0; c < 4; c++){ - double score = rental_vs_boss_matchup(team[c], boss_candidates_on_path); - - // Adjust for HP. - if (team[c] != nullptr){ - double hp = team[c]->hp_ratio(); - if (hp >= 0){ - score *= (hp + lives - 1) / lives; - } - } - - // NPCs are stupid. - if (state.players[c].console_id < 0){ - score *= 0.5; - } - - total += score; - } - return total; -} - - -#if 0 -double evaluate_hypothetical_team( - const GlobalState& state, - const papkmnlib::Pokemon* team[4], - const std::vector& rental_candidates_on_path, - const std::vector& boss_candidates_on_path -){ - using namespace papkmnlib; - -#if 1 - uint8_t lives = 4; - - double rental_weight = 3 - state.wins; - double boss_weight = 2; - - double sum = 0; - size_t count = 0; - -// static std::mutex lock; -// std::lock_guard lg(lock); - -// cout << team[0]->dump() << endl; -// cout << team[1]->dump() << endl; -// cout << team[2]->dump() << endl; -// cout << team[3]->dump() << endl; - - for (size_t c = 0; c < 4; c++){ -// cout << "Player: " << c << endl; - if (state.players[c].console_id < 0){ - continue; - } - const Pokemon* attacker = team[c]; - if (attacker == nullptr){ - continue; - } - - std::vector npcs; - for (size_t i = 0; i < 4; i++){ - if (c != i && team[i] != nullptr){ - npcs.emplace_back(team[i]); - } - } -// cout << "npcs.size() = " << npcs.size() << endl; - -// auto time0 = current_time(); - double rental_score = evaluate_average_matchup( - *attacker, - rental_candidates_on_path, - npcs, lives - ); - double boss_score = evaluate_average_matchup( - *attacker, - boss_candidates_on_path, - npcs, lives - ); -// auto time1 = current_time(); -// cout << std::chrono::duration_cast(time1 - time0).count() << endl; - - double weighted_score = get_weighted_score( - rental_score, rental_weight, - boss_score, boss_weight - ); - -// cout << "rental_score = " << rental_score << endl; -// cout << "boss_score = " << boss_score << endl; -// cout << "weighted_score = " << weighted_score << endl; - - sum += weighted_score; - count++; - } - - if (count == 0){ - return 0; - } - return sum / (double)count; -#endif -} -#endif - - - - -bool swap_if_least_hp( - const GlobalState& state, - size_t player_index -){ - double least_hp = 1.0; - int player = -1; - - for (int c = 0; c < 4; c++){ - double hp = state.players[c].health.value.hp; - if (hp < 0){ - continue; - } - - if (least_hp > hp){ - least_hp = hp; - player = c; - } - } - - return (int)player_index == player; -} - - - - -} -} -} -} +/* Max Lair AI Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" +#include "PokemonSwSh_MaxLair_AI_Tools.h" +#include "PokemonSwSh_MaxLair_AI_PathMatchup.h" +#include "PokemonSwSh_MaxLair_AI_RentalBossMatchup.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +std::unique_ptr convert_player_to_pkmnlib(const PlayerState& player){ + using namespace papkmnlib; + if (player.pokemon.empty()){ + return nullptr; + } + std::unique_ptr pokemon(new Pokemon(get_pokemon(player.pokemon))); + pokemon->set_hp_ratio(player.health.value.dead ? 0 : player.health.value.hp); + pokemon->set_is_dynamax(player.dmax_turns_left > 0); + size_t move_count = std::min(pokemon->num_moves(), (size_t)4); + for (size_t i = 0; i < move_count; i++){ + int8_t pp = player.pp[i]; + if (pp < 0){ + pp = pokemon->move(i).pp(); + } + pokemon->update_pp(i, pp); + } + return pokemon; +} + + + + +std::set get_rental_candidates_on_path( + const std::vector& path, + const std::set& exclusions +){ + std::set candidates; + for (const PathNode& node : path){ + for (const std::string& rental : rentals_by_type(node.type)){ + if (exclusions.find(rental) == exclusions.end()){ + candidates.insert(rental); + } + } + } + return candidates; +} +std::set get_rental_candidates_on_path(const GlobalState& state){ + return get_rental_candidates_on_path(state.last_best_path, state.seen); +} +std::vector get_rental_candidates_on_path_pkmnlib(const GlobalState& state){ + std::vector candidates; + for (const std::string& candidate : get_rental_candidates_on_path(state)){ + candidates.emplace_back(&papkmnlib::get_pokemon(candidate)); + } + return candidates; +} +std::vector get_boss_candidates(const GlobalState& state){ + using namespace papkmnlib; + std::vector candidates; + if (state.boss.empty()){ + PokemonType boss_type = state.path.boss; + Type pkmnlib_type = serial_type_to_pkmnlib(boss_type); + for (const auto& item : all_boss_pokemon()){ + const Pokemon& boss = get_pokemon(item.first); + if (boss_type == PokemonType::NONE || boss.has_type(pkmnlib_type)){ + candidates.emplace_back(&boss); + } + } + }else{ + candidates.emplace_back(&get_pokemon(state.boss)); + } + return candidates; +} + + + + + +double rental_vs_boss_matchup(const std::string& rental, const std::vector& bosses){ + using namespace papkmnlib; + + if (bosses.empty()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Boss list cannot be empty."); + } + double score = 0; + if (rental.empty()){ + for (const Pokemon* boss : bosses){ + for (const auto& candidate : all_rental_pokemon()){ + score += rental_vs_boss_matchup(candidate.first, boss->name()); + } + } + score /= bosses.size() * all_rental_pokemon().size(); + }else{ + for (const Pokemon* boss : bosses){ + score += rental_vs_boss_matchup(rental, boss->name()); + } + score /= bosses.size(); + } + return score; +} +double rental_vs_boss_matchup(const papkmnlib::Pokemon* rental, const std::vector& bosses){ + return rental_vs_boss_matchup(rental == nullptr ? "" : rental->name(), bosses); +} + + + +double evaluate_hypothetical_team( + const GlobalState& state, + const papkmnlib::Pokemon* team[4], + const std::vector& rental_candidates_on_path, + const std::vector& boss_candidates_on_path +){ + using namespace papkmnlib; + + uint8_t lives = 4; + + double total = 0; + for (size_t c = 0; c < 4; c++){ + double score = rental_vs_boss_matchup(team[c], boss_candidates_on_path); + + // Adjust for HP. + if (team[c] != nullptr){ + double hp = team[c]->hp_ratio(); + if (hp >= 0){ + score *= (hp + lives - 1) / lives; + } + } + + // NPCs are stupid. + if (state.players[c].console_id < 0){ + score *= 0.5; + } + + total += score; + } + return total; +} + + +#if 0 +double evaluate_hypothetical_team( + const GlobalState& state, + const papkmnlib::Pokemon* team[4], + const std::vector& rental_candidates_on_path, + const std::vector& boss_candidates_on_path +){ + using namespace papkmnlib; + +#if 1 + uint8_t lives = 4; + + double rental_weight = 3 - state.wins; + double boss_weight = 2; + + double sum = 0; + size_t count = 0; + +// static std::mutex lock; +// std::lock_guard lg(lock); + +// cout << team[0]->dump() << endl; +// cout << team[1]->dump() << endl; +// cout << team[2]->dump() << endl; +// cout << team[3]->dump() << endl; + + for (size_t c = 0; c < 4; c++){ +// cout << "Player: " << c << endl; + if (state.players[c].console_id < 0){ + continue; + } + const Pokemon* attacker = team[c]; + if (attacker == nullptr){ + continue; + } + + std::vector npcs; + for (size_t i = 0; i < 4; i++){ + if (c != i && team[i] != nullptr){ + npcs.emplace_back(team[i]); + } + } +// cout << "npcs.size() = " << npcs.size() << endl; + +// auto time0 = current_time(); + double rental_score = evaluate_average_matchup( + *attacker, + rental_candidates_on_path, + npcs, lives + ); + double boss_score = evaluate_average_matchup( + *attacker, + boss_candidates_on_path, + npcs, lives + ); +// auto time1 = current_time(); +// cout << std::chrono::duration_cast(time1 - time0).count() << endl; + + double weighted_score = get_weighted_score( + rental_score, rental_weight, + boss_score, boss_weight + ); + +// cout << "rental_score = " << rental_score << endl; +// cout << "boss_score = " << boss_score << endl; +// cout << "weighted_score = " << weighted_score << endl; + + sum += weighted_score; + count++; + } + + if (count == 0){ + return 0; + } + return sum / (double)count; +#endif +} +#endif + + + + +bool swap_if_least_hp( + const GlobalState& state, + size_t player_index +){ + double least_hp = 1.0; + int player = -1; + + for (int c = 0; c < 4; c++){ + double hp = state.players[c].health.value.hp; + if (hp < 0){ + continue; + } + + if (least_hp > hp){ + least_hp = hp; + player = c; + } + } + + return (int)player_index == player; +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.h index 8c73bbdee8..9b06415fb7 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI_Tools.h @@ -1,51 +1,51 @@ -/* Max Lair AI Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_Tools_H -#define PokemonAutomation_PokemonSwSh_MaxLair_AI_Tools_H - -#include -#include "CommonFramework/Logging/Logger.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -std::unique_ptr convert_player_to_pkmnlib(const PlayerState& player); - - -std::vector get_rental_candidates_on_path_pkmnlib(const GlobalState& state); -std::vector get_boss_candidates(const GlobalState& state); - - -double evaluate_hypothetical_team( - const GlobalState& state, - const papkmnlib::Pokemon* team[4], - const std::vector& rental_candidates_on_path, - const std::vector& boss_candidates_on_path -); - - - -bool swap_if_least_hp( - const GlobalState& state, - size_t player_index -); - - - - - -} -} -} -} -#endif +/* Max Lair AI Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_AI_Tools_H +#define PokemonAutomation_PokemonSwSh_MaxLair_AI_Tools_H + +#include +#include "CommonFramework/Logging/Logger.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +std::unique_ptr convert_player_to_pkmnlib(const PlayerState& player); + + +std::vector get_rental_candidates_on_path_pkmnlib(const GlobalState& state); +std::vector get_boss_candidates(const GlobalState& state); + + +double evaluate_hypothetical_team( + const GlobalState& state, + const papkmnlib::Pokemon* team[4], + const std::vector& rental_candidates_on_path, + const std::vector& boss_candidates_on_path +); + + + +bool swap_if_least_hp( + const GlobalState& state, + size_t player_index +); + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.cpp index f04d1166d5..4ab3c2c4e6 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.cpp @@ -1,158 +1,158 @@ -/* Catch Screen Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h" -#include "PokemonSwSh_MaxLair_CatchScreenTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -CaughtPokemonScreen::CaughtPokemonScreen(VideoStream& stream, ProControllerContext& context) - : m_stream(stream) - , m_context(context) - , m_total(count_catches(stream.overlay(), stream.video().snapshot())) -{ - if (m_total == 0 || m_total > 4){ - stream.log("Detected " + std::to_string(m_total) + " catches. Something is wrong.", COLOR_RED); - } -} - -size_t CaughtPokemonScreen::total() const{ - return m_total; -} -const CaughtPokemon& CaughtPokemonScreen::operator[](size_t position) const{ - return m_mons[position]; -} -bool CaughtPokemonScreen::current_position() const{ - return m_current_position; -} -bool CaughtPokemonScreen::is_summary() const{ - return m_in_summary; -} - -void CaughtPokemonScreen::enter_summary(){ - SummaryShinySymbolDetector detector(m_stream.logger(), m_stream.overlay()); - if (m_in_summary){ - // Make sure we're actually in the summary screen. - process_detection(detector.wait_for_detection(m_context, m_stream.video())); - return; - } - - pbf_press_button(m_context, BUTTON_A, 10, 100); - pbf_press_dpad(m_context, DPAD_DOWN, 10, 50); - pbf_press_button(m_context, BUTTON_A, 10, 0); - m_context.wait_for_all_requests(); - - Detection detection = detector.wait_for_detection(m_context, m_stream.video()); - m_in_summary = true; - process_detection(detection); -} -void CaughtPokemonScreen::leave_summary(){ - if (!m_in_summary){ - return; - } - - // Make sure we're actually in the summary screen. - SummaryShinySymbolDetector detector(m_stream.logger(), m_stream.overlay()); - process_detection(detector.wait_for_detection(m_context, m_stream.video())); - - pbf_press_button(m_context, BUTTON_B, 10, TICKS_PER_SECOND); - - PokemonCaughtMenuDetector caught_menu; - - int result = wait_until( - m_stream, m_context, - std::chrono::seconds(10), - {{caught_menu}} - ); - - switch (result){ - case 0: - pbf_wait(m_context, 125); - m_context.wait_for_all_requests(); - break; - default: -// auto snapshot = m_stream.video().snapshot(); -// dump_image(m_stream, m_env.program_info(), "CaughtMenu", snapshot); - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect caught menu.", - m_stream - ); - } - - m_in_summary = false; -} -void CaughtPokemonScreen::scroll_down(){ - pbf_press_dpad(m_context, DPAD_DOWN, 10, TICKS_PER_SECOND); - m_context.wait_for_all_requests(); - m_current_position++; - if (m_current_position >= m_total){ - m_current_position = 0; - } - if (m_in_summary){ - SummaryShinySymbolDetector detector(m_stream.logger(), m_stream.overlay()); - Detection detection = detector.wait_for_detection(m_context, m_stream.video()); - process_detection(detection); - } -} -void CaughtPokemonScreen::scroll_to(size_t position){ - while (m_current_position != position){ - scroll_down(); - } -} -void CaughtPokemonScreen::process_detection(Detection detection){ - CaughtPokemon& mon = m_mons[m_current_position]; - switch (detection){ - case SummaryShinySymbolDetector::Detection::NO_DETECTION: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to detect summary screen.", - m_stream - ); - case SummaryShinySymbolDetector::Detection::NOT_SHINY: - if (!mon.read){ - m_stream.log("Not shiny.", COLOR_BLUE); - mon.shiny = false; - mon.read = true; - }else if (mon.shiny){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Fatal Inconsistency: Expected to see a non-shiny.", - m_stream - ); - } - break; - case SummaryShinySymbolDetector::Detection::SHINY: - if (!mon.read){ - m_stream.log("Found shiny!", COLOR_BLUE); - mon.shiny = true; - mon.read = true; - }else if (!mon.shiny){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Fatal Inconsistency: Expected to see a shiny.", - m_stream - ); - } - break; - } -} - - - -} -} -} -} +/* Catch Screen Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h" +#include "PokemonSwSh_MaxLair_CatchScreenTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +CaughtPokemonScreen::CaughtPokemonScreen(VideoStream& stream, ProControllerContext& context) + : m_stream(stream) + , m_context(context) + , m_total(count_catches(stream.overlay(), stream.video().snapshot())) +{ + if (m_total == 0 || m_total > 4){ + stream.log("Detected " + std::to_string(m_total) + " catches. Something is wrong.", COLOR_RED); + } +} + +size_t CaughtPokemonScreen::total() const{ + return m_total; +} +const CaughtPokemon& CaughtPokemonScreen::operator[](size_t position) const{ + return m_mons[position]; +} +bool CaughtPokemonScreen::current_position() const{ + return m_current_position; +} +bool CaughtPokemonScreen::is_summary() const{ + return m_in_summary; +} + +void CaughtPokemonScreen::enter_summary(){ + SummaryShinySymbolDetector detector(m_stream.logger(), m_stream.overlay()); + if (m_in_summary){ + // Make sure we're actually in the summary screen. + process_detection(detector.wait_for_detection(m_context, m_stream.video())); + return; + } + + pbf_press_button(m_context, BUTTON_A, 10, 100); + pbf_press_dpad(m_context, DPAD_DOWN, 10, 50); + pbf_press_button(m_context, BUTTON_A, 10, 0); + m_context.wait_for_all_requests(); + + Detection detection = detector.wait_for_detection(m_context, m_stream.video()); + m_in_summary = true; + process_detection(detection); +} +void CaughtPokemonScreen::leave_summary(){ + if (!m_in_summary){ + return; + } + + // Make sure we're actually in the summary screen. + SummaryShinySymbolDetector detector(m_stream.logger(), m_stream.overlay()); + process_detection(detector.wait_for_detection(m_context, m_stream.video())); + + pbf_press_button(m_context, BUTTON_B, 10, TICKS_PER_SECOND); + + PokemonCaughtMenuDetector caught_menu; + + int result = wait_until( + m_stream, m_context, + std::chrono::seconds(10), + {{caught_menu}} + ); + + switch (result){ + case 0: + pbf_wait(m_context, 125); + m_context.wait_for_all_requests(); + break; + default: +// auto snapshot = m_stream.video().snapshot(); +// dump_image(m_stream, m_env.program_info(), "CaughtMenu", snapshot); + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect caught menu.", + m_stream + ); + } + + m_in_summary = false; +} +void CaughtPokemonScreen::scroll_down(){ + pbf_press_dpad(m_context, DPAD_DOWN, 10, TICKS_PER_SECOND); + m_context.wait_for_all_requests(); + m_current_position++; + if (m_current_position >= m_total){ + m_current_position = 0; + } + if (m_in_summary){ + SummaryShinySymbolDetector detector(m_stream.logger(), m_stream.overlay()); + Detection detection = detector.wait_for_detection(m_context, m_stream.video()); + process_detection(detection); + } +} +void CaughtPokemonScreen::scroll_to(size_t position){ + while (m_current_position != position){ + scroll_down(); + } +} +void CaughtPokemonScreen::process_detection(Detection detection){ + CaughtPokemon& mon = m_mons[m_current_position]; + switch (detection){ + case SummaryShinySymbolDetector::Detection::NO_DETECTION: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to detect summary screen.", + m_stream + ); + case SummaryShinySymbolDetector::Detection::NOT_SHINY: + if (!mon.read){ + m_stream.log("Not shiny.", COLOR_BLUE); + mon.shiny = false; + mon.read = true; + }else if (mon.shiny){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Fatal Inconsistency: Expected to see a non-shiny.", + m_stream + ); + } + break; + case SummaryShinySymbolDetector::Detection::SHINY: + if (!mon.read){ + m_stream.log("Found shiny!", COLOR_BLUE); + mon.shiny = true; + mon.read = true; + }else if (!mon.shiny){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Fatal Inconsistency: Expected to see a shiny.", + m_stream + ); + } + break; + } +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h index 7d64234fea..428d33828f 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h @@ -1,61 +1,61 @@ -/* Catch Screen Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_CatchScreenTracker_H -#define PokemonAutomation_PokemonSwSh_MaxLair_CatchScreenTracker_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -struct CaughtPokemon{ - bool read = false; - bool shiny = false; -}; - -class CaughtPokemonScreen{ - using Detection = SummaryShinySymbolDetector::Detection; - -public: - CaughtPokemonScreen(VideoStream& stream, ProControllerContext& context); - - size_t total() const; - const CaughtPokemon& operator[](size_t position) const; - - bool current_position() const; - bool is_summary() const; - - void enter_summary(); - void leave_summary(); - void scroll_down(); - void scroll_to(size_t position); - -private: - void process_detection(Detection detection); - -private: - VideoStream& m_stream; - ProControllerContext& m_context; - size_t m_total; - size_t m_current_position = 0; - bool m_in_summary = false; - CaughtPokemon m_mons[4]; -}; - - - -} -} -} -} -#endif +/* Catch Screen Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_CatchScreenTracker_H +#define PokemonAutomation_PokemonSwSh_MaxLair_CatchScreenTracker_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +struct CaughtPokemon{ + bool read = false; + bool shiny = false; +}; + +class CaughtPokemonScreen{ + using Detection = SummaryShinySymbolDetector::Detection; + +public: + CaughtPokemonScreen(VideoStream& stream, ProControllerContext& context); + + size_t total() const; + const CaughtPokemon& operator[](size_t position) const; + + bool current_position() const; + bool is_summary() const; + + void enter_summary(); + void leave_summary(); + void scroll_down(); + void scroll_to(size_t position); + +private: + void process_detection(Detection detection); + +private: + VideoStream& m_stream; + ProControllerContext& m_context; + size_t m_total; + size_t m_current_position = 0; + bool m_in_summary = false; + CaughtPokemon m_mons[4]; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.cpp index 93879cb668..586918bad1 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.cpp @@ -1,184 +1,184 @@ -/* Max Lair Notifications - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include "CommonFramework/Globals.h" -//#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh_MaxLair_Notifications.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -std::string pokemon_name(const std::string& slug, const std::string& empty_string){ - if (slug.empty()){ - return empty_string; - } - return get_pokemon_name(get_maxlair_slugs(slug).name_slug).display_name(); -} - - -void send_status_notification( - MultiSwitchProgramEnvironment& env, - AdventureRuntime& runtime -){ - std::string status_str = "Status:\n"; - std::vector> embeds; - { - std::string str = pokemon_name(runtime.last_boss, "N/A"); - status_str += "Last Boss: " + str + "\n"; - embeds.emplace_back("Last Boss:", std::move(str)); - } - { - std::string str = runtime.path_stats.to_str(StatsTracker::DISPLAY_ON_SCREEN); - status_str += "Current Path: " + str + "\n"; - embeds.emplace_back("Current Path:", std::move(str)); - } - for (size_t c = 0; c < env.consoles.size(); c++){ - const ConsoleRuntime& stats = runtime.consoles[c]; - std::string label = "Console " + std::to_string(c) + ":"; - std::string str; - str += "Ore: " + stats.ore.to_str(); - str += " - Normal Balls: " + stats.normal_balls.to_str(); - str += " - Boss Balls: " + stats.boss_balls.to_str(); - status_str += label + " - " + str + "\n"; - embeds.emplace_back(std::move(label), str); - } - env.log(status_str); - send_program_notification( - env, runtime.notification_status, - Color(), - "Max Lair Status Update", - embeds, "" - ); -} - -void send_raid_notification( - ProgramEnvironment& env, - VideoStream& stream, - AutoHostNotificationOption& settings, - const std::string& code, - const std::string& slug, - const PathStats& path_stats, - const StatsTracker& session_stats -){ - if (!settings.enabled()){ - return; - } - - VideoSnapshot screen = stream.video().snapshot(); - - std::vector> embeds; - - { - std::string description = settings.DESCRIPTION; - if (!description.empty()){ - embeds.emplace_back("Description:", std::move(description)); - } - } - - embeds.emplace_back( - "Current " + STRING_POKEMON, - pokemon_name(slug, "Unable to detect.") - ); - - { - std::string code_str; - if (code.empty()){ - code_str = "None"; - } - embeds.emplace_back("Raid Code:", std::move(code_str)); - } - - if (path_stats.runs() > 0){ - embeds.emplace_back("Current Path:", path_stats.to_str(StatsTracker::DISPLAY_ON_SCREEN)); - } - - send_program_notification( - env, settings.NOTIFICATION, - Color(), - "Max Lair Notification", - embeds, "", - screen, false - ); - -} - - -void send_shiny_notification( - ProgramEnvironment& env, - Logger& logger, EventNotificationOption& settings, - size_t console_index, size_t shinies, - const std::set* slugs, - const PathStats& path_stats, - const Stats& session_stats, - const ImageViewRGB32& image -){ - std::vector> embeds; - embeds.emplace_back( - "Adventure Result:", - shinies == 1 - ? "Shiny on console " + std::to_string(console_index) + "!" - : std::to_string(shinies) + " shinies on console " + std::to_string(console_index) + "!" - ); - if (slugs){ - std::string str; - if (slugs->empty()){ - str = "None - Unable to detect."; - }else if (slugs->size() == 1){ -// str += get_pokemon_name(*slugs->begin()).display_name(); - const PokemonNames* names = get_pokemon_name_nothrow(*slugs->begin()); - if (names){ - str += names->display_name(); - }else{ - str += *slugs->begin(); - } - }else{ - str += "Ambiguous: "; - bool first = true; - for (const std::string& slug : *slugs){ - if (!first){ - str += ", "; - } - first = false; -// str += get_pokemon_name(slug).display_name(); - const PokemonNames* names = get_pokemon_name_nothrow(slug); - if (names){ - str += names->display_name(); - }else{ - str += slug; - } - } - } - embeds.emplace_back(STRING_POKEMON + ":", std::move(str)); - } - if (path_stats.runs() > 0){ - embeds.emplace_back("Current Path:", path_stats.to_str(StatsTracker::DISPLAY_ON_SCREEN)); - } - - send_program_notification( - env, settings, - Pokemon::COLOR_STAR_SHINY, - "Max Lair Shiny Notification", - embeds, "", - image, true - ); -} - - - -} -} -} -} +/* Max Lair Notifications + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include "CommonFramework/Globals.h" +//#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh_MaxLair_Notifications.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +std::string pokemon_name(const std::string& slug, const std::string& empty_string){ + if (slug.empty()){ + return empty_string; + } + return get_pokemon_name(get_maxlair_slugs(slug).name_slug).display_name(); +} + + +void send_status_notification( + MultiSwitchProgramEnvironment& env, + AdventureRuntime& runtime +){ + std::string status_str = "Status:\n"; + std::vector> embeds; + { + std::string str = pokemon_name(runtime.last_boss, "N/A"); + status_str += "Last Boss: " + str + "\n"; + embeds.emplace_back("Last Boss:", std::move(str)); + } + { + std::string str = runtime.path_stats.to_str(StatsTracker::DISPLAY_ON_SCREEN); + status_str += "Current Path: " + str + "\n"; + embeds.emplace_back("Current Path:", std::move(str)); + } + for (size_t c = 0; c < env.consoles.size(); c++){ + const ConsoleRuntime& stats = runtime.consoles[c]; + std::string label = "Console " + std::to_string(c) + ":"; + std::string str; + str += "Ore: " + stats.ore.to_str(); + str += " - Normal Balls: " + stats.normal_balls.to_str(); + str += " - Boss Balls: " + stats.boss_balls.to_str(); + status_str += label + " - " + str + "\n"; + embeds.emplace_back(std::move(label), str); + } + env.log(status_str); + send_program_notification( + env, runtime.notification_status, + Color(), + "Max Lair Status Update", + embeds, "" + ); +} + +void send_raid_notification( + ProgramEnvironment& env, + VideoStream& stream, + AutoHostNotificationOption& settings, + const std::string& code, + const std::string& slug, + const PathStats& path_stats, + const StatsTracker& session_stats +){ + if (!settings.enabled()){ + return; + } + + VideoSnapshot screen = stream.video().snapshot(); + + std::vector> embeds; + + { + std::string description = settings.DESCRIPTION; + if (!description.empty()){ + embeds.emplace_back("Description:", std::move(description)); + } + } + + embeds.emplace_back( + "Current " + STRING_POKEMON, + pokemon_name(slug, "Unable to detect.") + ); + + { + std::string code_str; + if (code.empty()){ + code_str = "None"; + } + embeds.emplace_back("Raid Code:", std::move(code_str)); + } + + if (path_stats.runs() > 0){ + embeds.emplace_back("Current Path:", path_stats.to_str(StatsTracker::DISPLAY_ON_SCREEN)); + } + + send_program_notification( + env, settings.NOTIFICATION, + Color(), + "Max Lair Notification", + embeds, "", + screen, false + ); + +} + + +void send_shiny_notification( + ProgramEnvironment& env, + Logger& logger, EventNotificationOption& settings, + size_t console_index, size_t shinies, + const std::set* slugs, + const PathStats& path_stats, + const Stats& session_stats, + const ImageViewRGB32& image +){ + std::vector> embeds; + embeds.emplace_back( + "Adventure Result:", + shinies == 1 + ? "Shiny on console " + std::to_string(console_index) + "!" + : std::to_string(shinies) + " shinies on console " + std::to_string(console_index) + "!" + ); + if (slugs){ + std::string str; + if (slugs->empty()){ + str = "None - Unable to detect."; + }else if (slugs->size() == 1){ +// str += get_pokemon_name(*slugs->begin()).display_name(); + const PokemonNames* names = get_pokemon_name_nothrow(*slugs->begin()); + if (names){ + str += names->display_name(); + }else{ + str += *slugs->begin(); + } + }else{ + str += "Ambiguous: "; + bool first = true; + for (const std::string& slug : *slugs){ + if (!first){ + str += ", "; + } + first = false; +// str += get_pokemon_name(slug).display_name(); + const PokemonNames* names = get_pokemon_name_nothrow(slug); + if (names){ + str += names->display_name(); + }else{ + str += slug; + } + } + } + embeds.emplace_back(STRING_POKEMON + ":", std::move(str)); + } + if (path_stats.runs() > 0){ + embeds.emplace_back("Current Path:", path_stats.to_str(StatsTracker::DISPLAY_ON_SCREEN)); + } + + send_program_notification( + env, settings, + Pokemon::COLOR_STAR_SHINY, + "Max Lair Shiny Notification", + embeds, "", + image, true + ); +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h index 5d2ec734f0..47b226fac7 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h @@ -1,57 +1,57 @@ -/* Max Lair Notifications - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Notifications_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Notifications_H - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" -#include "PokemonSwSh_MaxLair_Stats.h" -#include "PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -std::string pokemon_name(const std::string& slug, const std::string& empty_string); - - - -void send_status_notification( - MultiSwitchProgramEnvironment& env, - AdventureRuntime& runtime -); - -void send_raid_notification( - ProgramEnvironment& env, - VideoStream& stream, - AutoHostNotificationOption& settings, - const std::string& code, - const std::string& slug, - const PathStats& path_stats, - const StatsTracker& session_stats -); - -void send_shiny_notification( - ProgramEnvironment& env, - Logger& logger, EventNotificationOption& settings, - size_t console_index, size_t shinies, - const std::set* slugs, - const PathStats& path_stats, - const Stats& session_stats, - const ImageViewRGB32& image -); - - -} -} -} -} -#endif +/* Max Lair Notifications + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Notifications_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Notifications_H + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" +#include "PokemonSwSh_MaxLair_Stats.h" +#include "PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +std::string pokemon_name(const std::string& slug, const std::string& empty_string); + + + +void send_status_notification( + MultiSwitchProgramEnvironment& env, + AdventureRuntime& runtime +); + +void send_raid_notification( + ProgramEnvironment& env, + VideoStream& stream, + AutoHostNotificationOption& settings, + const std::string& code, + const std::string& slug, + const PathStats& path_stats, + const StatsTracker& session_stats +); + +void send_shiny_notification( + ProgramEnvironment& env, + Logger& logger, EventNotificationOption& settings, + size_t console_index, size_t shinies, + const std::set* slugs, + const PathStats& path_stats, + const Stats& session_stats, + const ImageViewRGB32& image +); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp index c50625c40d..7af9d103dd 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.cpp @@ -1,188 +1,188 @@ -/* Max Lair State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Pokemon/Pokemon_Types.h" -#include "PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -std::string PlayerState::dump() const{ - std::string str; - str += console_id < 0 ? "NPC" : "Switch " + std::to_string(console_id); - str += " - mon:"; - str += pokemon.empty() ? "?" : pokemon; - str += " - item:"; - str += item.empty() ? "?" : item; - str += " - dmax-turns-left:"; - str += std::to_string((int)dmax_turns_left); - str += " - can-dmax:"; - str += can_dmax ? "yes" : "no"; - str += " - HP:"; - str += health.value.hp < 0 ? "?" : std::to_string(100*health.value.hp); - str += "% - dead:"; - str += health.value.dead < 0 ? "?" : (health.value.dead ? "yes" : "no"); - str += " - PP:{"; - for (size_t c = 0; c < 4; c++){ - str += std::to_string(pp[c]); - if (c + 1 < 4){ - str += ", "; - } - } - str += "} - blocked:{"; - for (size_t c = 0; c < 4; c++){ - str += move_blocked[c] ? "1" : "0"; - if (c + 1 < 4){ - str += ", "; - } - } - str += "}"; - return str; -} -void PlayerState::clear_battle_state(){ - dmax_turns_left = -1; - for (size_t c = 0; c < 4 ; c++){ - move_blocked[c] = false; - } -} - -std::string PathMap::dump() const{ - std::string str; - str += " Path Type: " + std::to_string((int)path_type); - str += "\n"; - { - str += " Row 3: "; - bool first = true; - for (size_t c = 0; c < 4; c++){ - if (!first){ - str += ", "; - } - first = false; - str += POKEMON_TYPE_SLUGS().get_string(mon3[c]); - } - str += "\n"; - } - { - str += " Row 2: "; - bool first = true; - for (size_t c = 0; c < 4; c++){ - if (!first){ - str += ", "; - } - first = false; - str += POKEMON_TYPE_SLUGS().get_string(mon2[c]); - } - str += "\n"; - } - { - str += " Row 1: "; - bool first = true; - for (size_t c = 0; c < 2; c++){ - if (!first){ - str += ", "; - } - first = false; - str += POKEMON_TYPE_SLUGS().get_string(mon1[c]); - } - str += "\n"; - } - return str; -} - -std::string dump_path(const std::vector& path){ - std::string str; - for (const auto& item : path){ - str += "["; - str += std::to_string(item.path_slot); - str += ":"; - str += POKEMON_TYPE_SLUGS().get_string(item.type); - str += "] "; - } - return str; -} - - - -std::string GlobalState::dump() const{ - std::string str; - str += " boss:"; - if (boss.empty()){ - str += "? (" + POKEMON_TYPE_SLUGS().get_string(path.boss) + ")"; - }else{ - str += boss; - } - str += " - wins:" + std::to_string(wins); - str += " - lives:"; - str += lives_left < 0 ? "?" : std::to_string(lives_left); - str += " - opponent:"; - if (opponent.empty()){ - str += "?"; - }else if (opponent.size() == 1){ - str += *opponent.begin(); - }else{ - str += set_to_str(opponent); - } - str += " - HP:"; - str += opponent_hp < 0 ? "?" : std::to_string(100 * opponent_hp); - str += "% - slot:"; - str += std::to_string(move_slot); - str += "\n"; - str += " Player 0: " + players[0].dump() + "\n"; - str += " Player 1: " + players[1].dump() + "\n"; - str += " Player 2: " + players[2].dump() + "\n"; - str += " Player 3: " + players[3].dump() + "\n"; - str += path.dump(); - switch (path_side){ - case 0: str += " current-side: left"; break; - case 1: str += " current-side: right"; break; - default: str += " current-side: ?"; break; - } - str += "\n"; - str += " Best Remaining Path: " + dump_path(last_best_path) + "\n"; - str += " Seen: " + set_to_str(seen) + "\n"; - return str; -} -void GlobalState::clear_battle_state(){ - opponent.clear(); - opponent_hp = -1; - move_slot = 0; - players[0].clear_battle_state(); - players[1].clear_battle_state(); - players[2].clear_battle_state(); - players[3].clear_battle_state(); -} -void GlobalState::add_seen(const std::string& mon){ - if (!mon.empty()){ - seen.insert(mon); - } -} -size_t GlobalState::find_player_index(size_t console_id) const{ - for (size_t c = 0; c < 4; c++){ - if (players[c].console_id == (int8_t)console_id){ - return c; - } - } - return console_id; -} - - - - - - - - - - -} -} -} -} +/* Max Lair State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Pokemon/Pokemon_Types.h" +#include "PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +std::string PlayerState::dump() const{ + std::string str; + str += console_id < 0 ? "NPC" : "Switch " + std::to_string(console_id); + str += " - mon:"; + str += pokemon.empty() ? "?" : pokemon; + str += " - item:"; + str += item.empty() ? "?" : item; + str += " - dmax-turns-left:"; + str += std::to_string((int)dmax_turns_left); + str += " - can-dmax:"; + str += can_dmax ? "yes" : "no"; + str += " - HP:"; + str += health.value.hp < 0 ? "?" : std::to_string(100*health.value.hp); + str += "% - dead:"; + str += health.value.dead < 0 ? "?" : (health.value.dead ? "yes" : "no"); + str += " - PP:{"; + for (size_t c = 0; c < 4; c++){ + str += std::to_string(pp[c]); + if (c + 1 < 4){ + str += ", "; + } + } + str += "} - blocked:{"; + for (size_t c = 0; c < 4; c++){ + str += move_blocked[c] ? "1" : "0"; + if (c + 1 < 4){ + str += ", "; + } + } + str += "}"; + return str; +} +void PlayerState::clear_battle_state(){ + dmax_turns_left = -1; + for (size_t c = 0; c < 4 ; c++){ + move_blocked[c] = false; + } +} + +std::string PathMap::dump() const{ + std::string str; + str += " Path Type: " + std::to_string((int)path_type); + str += "\n"; + { + str += " Row 3: "; + bool first = true; + for (size_t c = 0; c < 4; c++){ + if (!first){ + str += ", "; + } + first = false; + str += POKEMON_TYPE_SLUGS().get_string(mon3[c]); + } + str += "\n"; + } + { + str += " Row 2: "; + bool first = true; + for (size_t c = 0; c < 4; c++){ + if (!first){ + str += ", "; + } + first = false; + str += POKEMON_TYPE_SLUGS().get_string(mon2[c]); + } + str += "\n"; + } + { + str += " Row 1: "; + bool first = true; + for (size_t c = 0; c < 2; c++){ + if (!first){ + str += ", "; + } + first = false; + str += POKEMON_TYPE_SLUGS().get_string(mon1[c]); + } + str += "\n"; + } + return str; +} + +std::string dump_path(const std::vector& path){ + std::string str; + for (const auto& item : path){ + str += "["; + str += std::to_string(item.path_slot); + str += ":"; + str += POKEMON_TYPE_SLUGS().get_string(item.type); + str += "] "; + } + return str; +} + + + +std::string GlobalState::dump() const{ + std::string str; + str += " boss:"; + if (boss.empty()){ + str += "? (" + POKEMON_TYPE_SLUGS().get_string(path.boss) + ")"; + }else{ + str += boss; + } + str += " - wins:" + std::to_string(wins); + str += " - lives:"; + str += lives_left < 0 ? "?" : std::to_string(lives_left); + str += " - opponent:"; + if (opponent.empty()){ + str += "?"; + }else if (opponent.size() == 1){ + str += *opponent.begin(); + }else{ + str += set_to_str(opponent); + } + str += " - HP:"; + str += opponent_hp < 0 ? "?" : std::to_string(100 * opponent_hp); + str += "% - slot:"; + str += std::to_string(move_slot); + str += "\n"; + str += " Player 0: " + players[0].dump() + "\n"; + str += " Player 1: " + players[1].dump() + "\n"; + str += " Player 2: " + players[2].dump() + "\n"; + str += " Player 3: " + players[3].dump() + "\n"; + str += path.dump(); + switch (path_side){ + case 0: str += " current-side: left"; break; + case 1: str += " current-side: right"; break; + default: str += " current-side: ?"; break; + } + str += "\n"; + str += " Best Remaining Path: " + dump_path(last_best_path) + "\n"; + str += " Seen: " + set_to_str(seen) + "\n"; + return str; +} +void GlobalState::clear_battle_state(){ + opponent.clear(); + opponent_hp = -1; + move_slot = 0; + players[0].clear_battle_state(); + players[1].clear_battle_state(); + players[2].clear_battle_state(); + players[3].clear_battle_state(); +} +void GlobalState::add_seen(const std::string& mon){ + if (!mon.empty()){ + seen.insert(mon); + } +} +size_t GlobalState::find_player_index(size_t console_id) const{ + for (size_t c = 0; c < 4; c++){ + if (players[c].console_id == (int8_t)console_id){ + return c; + } + } + return console_id; +} + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h index 37e0134457..41c2b8793b 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h @@ -1,184 +1,184 @@ -/* Max Lair State - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_State_H -#define PokemonAutomation_PokemonSwSh_MaxLair_State_H - -#include -#include -#include -#include "Common/Cpp/Time.h" -#include "Pokemon/Pokemon_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -template -struct TimestampedValue{ - TimestampedValue(const TimestampedValue& x) - : timestamp(x.timestamp) - , value(x.value) - {} - void operator=(const TimestampedValue& x){ - timestamp = x.timestamp; - value = x.value; - } - - TimestampedValue() - : timestamp(WallClock::min()) - , value() - {} - TimestampedValue(Type p_value) - : timestamp(current_time()) - , value(std::move(p_value)) - {} - TimestampedValue(Type p_value, WallClock timestamp) - : timestamp(timestamp) - , value(std::move(p_value)) - {} - void operator=(Type x){ - timestamp = current_time(); - value = std::move(x); - } - - operator Type() const{ - return value; - } - - WallClock timestamp; - Type value; -}; - - -struct Health{ - double hp = -1; // [0.0 - 1.0], -1 means unknown. - int8_t dead = -1; // 1 = dead, 0 = alive, -1 = unknown. -}; - - -struct PlayerState{ - int8_t console_id = -1; // -1 means NPC - std::string pokemon; - std::string item; - int8_t dmax_turns_left = -1; // -1 means unknown - bool can_dmax = false; - TimestampedValue health; - int8_t pp[4] = {-1, -1, -1, -1}; // -1 means unknown - - // Battle State - bool move_blocked[4] = {false, false, false, false}; - - void clear_battle_state(); - - std::string dump() const; -}; - - - -/* - Path 0 - X - // \\ - X X X X - \/ \\ / - O O - /\\ \ - X X X X - \//\/ - X X - \/ - X - - Path 1 - X - // \\ - X X X X - \ //\/ - O O - / \ / \ - X X X X - \/\\/ - X X - \/ - X - - Path 2 - X - // \\ - X X X X - \/ \\ / - O O - / // \ - X X X X - \/ \/ - X X - \/ - X -*/ - -struct PathMap{ - int8_t path_type = -1; - PokemonType boss = PokemonType::NONE; - PokemonType mon3[4] = {PokemonType::NONE, PokemonType::NONE, PokemonType::NONE, PokemonType::NONE}; - PokemonType mon2[4] = {PokemonType::NONE, PokemonType::NONE, PokemonType::NONE, PokemonType::NONE}; - PokemonType mon1[2] = {PokemonType::NONE, PokemonType::NONE}; - - std::string dump() const; -}; - -struct PathNode{ - uint8_t path_slot; - PokemonType type; -}; -std::string dump_path(const std::vector& path); - - -struct GlobalState{ - // Timestamp when this state was issued. - WallClock timestamp = WallClock::min(); - - bool adventure_started = false; - - std::string boss; - - PathMap path; - int8_t path_side = -1; // -1 = unknown, 0 = left, 1 = right - std::vector last_best_path; - - uint8_t wins = 0; - int8_t lives_left = -1; // -1 means unknown - - PlayerState players[4]; - - std::set seen; - void add_seen(const std::string& mon); - - // Battle State - std::set opponent; - TimestampedValue opponent_hp = -1; - uint8_t move_slot = 0; - - size_t find_player_index(size_t console_id) const; - void clear_battle_state(); - - std::string dump() const; -}; - - - - - - - -} -} -} -} -#endif +/* Max Lair State + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_State_H +#define PokemonAutomation_PokemonSwSh_MaxLair_State_H + +#include +#include +#include +#include "Common/Cpp/Time.h" +#include "Pokemon/Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +template +struct TimestampedValue{ + TimestampedValue(const TimestampedValue& x) + : timestamp(x.timestamp) + , value(x.value) + {} + void operator=(const TimestampedValue& x){ + timestamp = x.timestamp; + value = x.value; + } + + TimestampedValue() + : timestamp(WallClock::min()) + , value() + {} + TimestampedValue(Type p_value) + : timestamp(current_time()) + , value(std::move(p_value)) + {} + TimestampedValue(Type p_value, WallClock timestamp) + : timestamp(timestamp) + , value(std::move(p_value)) + {} + void operator=(Type x){ + timestamp = current_time(); + value = std::move(x); + } + + operator Type() const{ + return value; + } + + WallClock timestamp; + Type value; +}; + + +struct Health{ + double hp = -1; // [0.0 - 1.0], -1 means unknown. + int8_t dead = -1; // 1 = dead, 0 = alive, -1 = unknown. +}; + + +struct PlayerState{ + int8_t console_id = -1; // -1 means NPC + std::string pokemon; + std::string item; + int8_t dmax_turns_left = -1; // -1 means unknown + bool can_dmax = false; + TimestampedValue health; + int8_t pp[4] = {-1, -1, -1, -1}; // -1 means unknown + + // Battle State + bool move_blocked[4] = {false, false, false, false}; + + void clear_battle_state(); + + std::string dump() const; +}; + + + +/* + Path 0 + X + // \\ + X X X X + \/ \\ / + O O + /\\ \ + X X X X + \//\/ + X X + \/ + X + + Path 1 + X + // \\ + X X X X + \ //\/ + O O + / \ / \ + X X X X + \/\\/ + X X + \/ + X + + Path 2 + X + // \\ + X X X X + \/ \\ / + O O + / // \ + X X X X + \/ \/ + X X + \/ + X +*/ + +struct PathMap{ + int8_t path_type = -1; + PokemonType boss = PokemonType::NONE; + PokemonType mon3[4] = {PokemonType::NONE, PokemonType::NONE, PokemonType::NONE, PokemonType::NONE}; + PokemonType mon2[4] = {PokemonType::NONE, PokemonType::NONE, PokemonType::NONE, PokemonType::NONE}; + PokemonType mon1[2] = {PokemonType::NONE, PokemonType::NONE}; + + std::string dump() const; +}; + +struct PathNode{ + uint8_t path_slot; + PokemonType type; +}; +std::string dump_path(const std::vector& path); + + +struct GlobalState{ + // Timestamp when this state was issued. + WallClock timestamp = WallClock::min(); + + bool adventure_started = false; + + std::string boss; + + PathMap path; + int8_t path_side = -1; // -1 = unknown, 0 = left, 1 = right + std::vector last_best_path; + + uint8_t wins = 0; + int8_t lives_left = -1; // -1 means unknown + + PlayerState players[4]; + + std::set seen; + void add_seen(const std::string& mon); + + // Battle State + std::set opponent; + TimestampedValue opponent_hp = -1; + uint8_t move_slot = 0; + + size_t find_player_index(size_t console_id) const; + void clear_battle_state(); + + std::string dump() const; +}; + + + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.cpp index ee7177e2df..6eb0fb71b6 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.cpp @@ -1,217 +1,217 @@ -/* Max Lair State Machine - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Containers/FixedLimitVector.tpp" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/FrozenImageDetector.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h" -#include "PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -AdventureRuntime::~AdventureRuntime() = default; -AdventureRuntime::AdventureRuntime( - FixedLimitVector& consoles, - const size_t p_host_index, - const Consoles& p_console_settings, - const EndBattleDecider& p_actions, - const bool p_go_home_when_done, - HostingSettings& p_hosting_settings, - EventNotificationOption& p_notification_status, - EventNotificationOption& p_notification_shiny, - Stats& p_session_stats -) - : host_index(p_host_index) - , console_settings(p_console_settings) - , actions(p_actions) - , go_home_when_done(p_go_home_when_done) - , hosting_settings(p_hosting_settings) - , notification_status(p_notification_status) - , notification_shiny(p_notification_shiny) - , ocr_watchdog(p_console_settings.active_consoles()) - , session_stats(p_session_stats) -{ - for (size_t c = 0; c < p_console_settings.active_consoles(); c++){ - ocr_watchdog.emplace_back(consoles[c].logger()); - } -} - - -StateMachineAction run_state_iteration( - AdventureRuntime& runtime, size_t console_index, - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - bool save_path, - GlobalStateTracker& global_state, - const EndBattleDecider& decider, - const ImageViewRGB32& entrance -){ - GlobalState state = global_state.infer_actual_state(console_index); -// uint8_t wins = state.wins; - bool starting = true; - for (size_t c = 0; c < 4; c++){ - if (state.players[c].console_id == (int8_t)console_index){ - starting = false; - break; - } - } - - PokemonSelectMenuDetector pokemon_select(false); - PokemonSwapMenuDetector pokemon_swap(false); - PathSelectDetector path_select; - ItemSelectDetector item_menu(false); - ProfessorSwapDetector professor_swap(console.overlay(), !starting); - BattleMenuDetector battle_menu; - RaidCatchDetector catch_select(console.overlay()); - PokemonCaughtMenuDetector caught_menu; - EntranceDetector entrance_detector(entrance); - FrozenImageDetector frozen_screen(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(30), 10); - - int result = wait_until( - console, context, - std::chrono::seconds(300), - { - {starting - ? (VisualInferenceCallback&)pokemon_select - : (VisualInferenceCallback&)pokemon_swap - }, - {path_select}, - {item_menu}, - {professor_swap}, - {battle_menu}, - {catch_select}, - {caught_menu}, - {entrance_detector}, - {frozen_screen}, - }, - std::chrono::milliseconds(200) - ); - - switch (result){ - case 0: - if (starting){ - console.log("Current State: " + STRING_POKEMON + " Select"); - run_select_pokemon( - console_index, - console, context, - global_state, - runtime.ocr_watchdog[console_index], - runtime.console_settings[console_index] - ); - return StateMachineAction::KEEP_GOING; - }else{ - console.log("Current State: " + STRING_POKEMON + " Swap"); - run_swap_pokemon( - console_index, - runtime, - console, context, - global_state, - runtime.console_settings[console_index] - ); - return StateMachineAction::KEEP_GOING; - } - case 1: - console.log("Current State: Path Select"); - run_path_select(env, console_index, console, context, global_state); - return StateMachineAction::KEEP_GOING; - case 2: - console.log("Current State: Item Select"); - run_item_select(console_index, console, context, global_state); - return StateMachineAction::KEEP_GOING; - case 3: - console.log("Current State: Professor Swap"); - run_professor_swap(console_index, runtime, console, context, global_state); - return StateMachineAction::KEEP_GOING; - case 4: - console.log("Current State: Move Select"); - return run_move_select( - env, console_index, - console, context, - runtime.ocr_watchdog[console_index], - global_state, - runtime.console_settings[console_index], - battle_menu.dmaxed(), - battle_menu.cheer() - ); - case 5: - console.log("Current State: Catch Select"); - return throw_balls( - runtime, - env, console_index, - console, context, - runtime.console_settings[console_index].language, - runtime.ocr_watchdog[console_index], - global_state, - decider - ); - case 6: - console.log("Current State: Caught Menu"); - return run_caught_screen( - runtime, - env, console_index, - console, context, - global_state, decider, - entrance - ); - case 7: - console.log("Current State: Entrance"); - run_entrance( - runtime, - env, console_index, - console, context, - save_path, - global_state - ); - return StateMachineAction::DONE_WITH_ADVENTURE; - case 8: - console.log("Current State: Frozen Screen", COLOR_RED); -// pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); -// context.wait_for_all_requests(); -// return StateMachineAction::KEEP_GOING; - return StateMachineAction::RESET_RECOVER; - default: - console.log("Program hang. No state detected after 5 minutes.", COLOR_RED); - dump_image(console.logger(), MODULE_NAME, console.video(), "ProgramHang"); - global_state.mark_as_dead(console_index); - return StateMachineAction::RESET_RECOVER; - } - - -} - - - - -} -} -} -} +/* Max Lair State Machine + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Containers/FixedLimitVector.tpp" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/FrozenImageDetector.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h" +#include "PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +AdventureRuntime::~AdventureRuntime() = default; +AdventureRuntime::AdventureRuntime( + FixedLimitVector& consoles, + const size_t p_host_index, + const Consoles& p_console_settings, + const EndBattleDecider& p_actions, + const bool p_go_home_when_done, + HostingSettings& p_hosting_settings, + EventNotificationOption& p_notification_status, + EventNotificationOption& p_notification_shiny, + Stats& p_session_stats +) + : host_index(p_host_index) + , console_settings(p_console_settings) + , actions(p_actions) + , go_home_when_done(p_go_home_when_done) + , hosting_settings(p_hosting_settings) + , notification_status(p_notification_status) + , notification_shiny(p_notification_shiny) + , ocr_watchdog(p_console_settings.active_consoles()) + , session_stats(p_session_stats) +{ + for (size_t c = 0; c < p_console_settings.active_consoles(); c++){ + ocr_watchdog.emplace_back(consoles[c].logger()); + } +} + + +StateMachineAction run_state_iteration( + AdventureRuntime& runtime, size_t console_index, + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + bool save_path, + GlobalStateTracker& global_state, + const EndBattleDecider& decider, + const ImageViewRGB32& entrance +){ + GlobalState state = global_state.infer_actual_state(console_index); +// uint8_t wins = state.wins; + bool starting = true; + for (size_t c = 0; c < 4; c++){ + if (state.players[c].console_id == (int8_t)console_index){ + starting = false; + break; + } + } + + PokemonSelectMenuDetector pokemon_select(false); + PokemonSwapMenuDetector pokemon_swap(false); + PathSelectDetector path_select; + ItemSelectDetector item_menu(false); + ProfessorSwapDetector professor_swap(console.overlay(), !starting); + BattleMenuDetector battle_menu; + RaidCatchDetector catch_select(console.overlay()); + PokemonCaughtMenuDetector caught_menu; + EntranceDetector entrance_detector(entrance); + FrozenImageDetector frozen_screen(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(30), 10); + + int result = wait_until( + console, context, + std::chrono::seconds(300), + { + {starting + ? (VisualInferenceCallback&)pokemon_select + : (VisualInferenceCallback&)pokemon_swap + }, + {path_select}, + {item_menu}, + {professor_swap}, + {battle_menu}, + {catch_select}, + {caught_menu}, + {entrance_detector}, + {frozen_screen}, + }, + std::chrono::milliseconds(200) + ); + + switch (result){ + case 0: + if (starting){ + console.log("Current State: " + STRING_POKEMON + " Select"); + run_select_pokemon( + console_index, + console, context, + global_state, + runtime.ocr_watchdog[console_index], + runtime.console_settings[console_index] + ); + return StateMachineAction::KEEP_GOING; + }else{ + console.log("Current State: " + STRING_POKEMON + " Swap"); + run_swap_pokemon( + console_index, + runtime, + console, context, + global_state, + runtime.console_settings[console_index] + ); + return StateMachineAction::KEEP_GOING; + } + case 1: + console.log("Current State: Path Select"); + run_path_select(env, console_index, console, context, global_state); + return StateMachineAction::KEEP_GOING; + case 2: + console.log("Current State: Item Select"); + run_item_select(console_index, console, context, global_state); + return StateMachineAction::KEEP_GOING; + case 3: + console.log("Current State: Professor Swap"); + run_professor_swap(console_index, runtime, console, context, global_state); + return StateMachineAction::KEEP_GOING; + case 4: + console.log("Current State: Move Select"); + return run_move_select( + env, console_index, + console, context, + runtime.ocr_watchdog[console_index], + global_state, + runtime.console_settings[console_index], + battle_menu.dmaxed(), + battle_menu.cheer() + ); + case 5: + console.log("Current State: Catch Select"); + return throw_balls( + runtime, + env, console_index, + console, context, + runtime.console_settings[console_index].language, + runtime.ocr_watchdog[console_index], + global_state, + decider + ); + case 6: + console.log("Current State: Caught Menu"); + return run_caught_screen( + runtime, + env, console_index, + console, context, + global_state, decider, + entrance + ); + case 7: + console.log("Current State: Entrance"); + run_entrance( + runtime, + env, console_index, + console, context, + save_path, + global_state + ); + return StateMachineAction::DONE_WITH_ADVENTURE; + case 8: + console.log("Current State: Frozen Screen", COLOR_RED); +// pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); +// context.wait_for_all_requests(); +// return StateMachineAction::KEEP_GOING; + return StateMachineAction::RESET_RECOVER; + default: + console.log("Program hang. No state detected after 5 minutes.", COLOR_RED); + dump_image(console.logger(), MODULE_NAME, console.video(), "ProgramHang"); + global_state.mark_as_dead(console_index); + return StateMachineAction::RESET_RECOVER; + } + + +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h index ff2f8ea33d..77c5a19b6a 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h @@ -1,112 +1,112 @@ -/* Max Lair State Machine - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_StateMachine_H -#define PokemonAutomation_PokemonSwSh_MaxLair_StateMachine_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/FailureWatchdog.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h" -#include "PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -enum class ConsoleState{ - CONSOLE_DEAD, - POKEMON_SELECT, - PATH_SELECT, - ITEM_SELECT, - MOVE_SELECT, - CATCH_SELECT, - POKEMON_SWAP, - CAUGHT_MENU, -}; - - - -enum class StateMachineAction{ - KEEP_GOING, - DONE_WITH_ADVENTURE, - STOP_PROGRAM, - RESET_RECOVER, -}; - - -struct ConsoleRuntime{ - ReadableQuantity999 ore; - ReadableQuantity999 normal_balls; - ReadableQuantity999 boss_balls; -}; - -struct AdventureRuntime{ - ~AdventureRuntime(); - AdventureRuntime( - FixedLimitVector& consoles, - const size_t p_host_index, - const Consoles& p_console_settings, - const EndBattleDecider& p_actions, - const bool p_go_home_when_done, - HostingSettings& p_hosting_settings, - EventNotificationOption& p_notification_status, - EventNotificationOption& p_notification_shiny, - Stats& p_session_stats - ); - - const size_t host_index; - const Consoles& console_settings; - const EndBattleDecider& actions; - const bool go_home_when_done; - HostingSettings& hosting_settings; - EventNotificationOption& notification_status; - EventNotificationOption& notification_shiny; - - FixedLimitVector ocr_watchdog; - - Stats& session_stats; - - PathStats path_stats; - std::string last_boss; - ConsoleRuntime consoles[4]; - - // State lock to protect fields of this class. - SpinLock m_lock; - - // A lock to allow timed-serialization of Switches. - // For example: Don't let multiple Switches simultaneously choose to swap with Pokemon. - std::mutex m_delay_lock; -}; - - -// Return true if done. -StateMachineAction run_state_iteration( - AdventureRuntime& runtime, size_t console_index, - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - bool save_path, - GlobalStateTracker& state_tracker, - const EndBattleDecider& boss_action, - const ImageViewRGB32& entrance -); - - - -} -} -} -} -#endif +/* Max Lair State Machine + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_StateMachine_H +#define PokemonAutomation_PokemonSwSh_MaxLair_StateMachine_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/FailureWatchdog.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h" +#include "PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +enum class ConsoleState{ + CONSOLE_DEAD, + POKEMON_SELECT, + PATH_SELECT, + ITEM_SELECT, + MOVE_SELECT, + CATCH_SELECT, + POKEMON_SWAP, + CAUGHT_MENU, +}; + + + +enum class StateMachineAction{ + KEEP_GOING, + DONE_WITH_ADVENTURE, + STOP_PROGRAM, + RESET_RECOVER, +}; + + +struct ConsoleRuntime{ + ReadableQuantity999 ore; + ReadableQuantity999 normal_balls; + ReadableQuantity999 boss_balls; +}; + +struct AdventureRuntime{ + ~AdventureRuntime(); + AdventureRuntime( + FixedLimitVector& consoles, + const size_t p_host_index, + const Consoles& p_console_settings, + const EndBattleDecider& p_actions, + const bool p_go_home_when_done, + HostingSettings& p_hosting_settings, + EventNotificationOption& p_notification_status, + EventNotificationOption& p_notification_shiny, + Stats& p_session_stats + ); + + const size_t host_index; + const Consoles& console_settings; + const EndBattleDecider& actions; + const bool go_home_when_done; + HostingSettings& hosting_settings; + EventNotificationOption& notification_status; + EventNotificationOption& notification_shiny; + + FixedLimitVector ocr_watchdog; + + Stats& session_stats; + + PathStats path_stats; + std::string last_boss; + ConsoleRuntime consoles[4]; + + // State lock to protect fields of this class. + SpinLock m_lock; + + // A lock to allow timed-serialization of Switches. + // For example: Don't let multiple Switches simultaneously choose to swap with Pokemon. + std::mutex m_delay_lock; +}; + + +// Return true if done. +StateMachineAction run_state_iteration( + AdventureRuntime& runtime, size_t console_index, + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + bool save_path, + GlobalStateTracker& state_tracker, + const EndBattleDecider& boss_action, + const ImageViewRGB32& entrance +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.cpp index 16124066a2..3491fd0cff 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.cpp @@ -1,540 +1,540 @@ -/* Max Lair State Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "Common/Compiler.h" -#include "Common/Cpp/AbstractLogger.h" -#include "PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -GlobalStateTracker::GlobalStateTracker(CancellableScope& scope, size_t consoles) - : m_count(consoles) -{ - auto timestamp = current_time(); - for (size_t c = 0; c < 4; c++){ - m_master_consoles[c].timestamp = timestamp; - } - update_groups_unprotected(); - attach(scope); -} -GlobalStateTracker::~GlobalStateTracker(){ - detach(); -} -std::pair GlobalStateTracker::dump(){ - std::lock_guard lg(m_lock); - std::string str; - for (size_t c = 0; c < m_count; c++){ - str += "Switch " + std::to_string(c) + ": (group " + std::to_string(m_groups[c]) + ")\n"; - str += m_consoles[c].dump(); - } -#if 0 - for (size_t c = 0; c < m_count; c++){ - str += "Inferred " + std::to_string(c) + ":\n"; - str += compute_inferred_unprotected(c).dump(); - } -#endif - return {m_state_epoch, str}; -} -bool GlobalStateTracker::cancel(std::exception_ptr exception) noexcept{ - if (Cancellable::cancel(std::move(exception))){ - return true; - } - std::lock_guard lg(m_lock); - m_cv.notify_all(); - return false; -} -void GlobalStateTracker::push_update(size_t index){ - std::lock_guard lg(m_lock); - m_state_epoch++; - m_master_consoles[index] = m_consoles[index]; - m_master_consoles[index].timestamp = current_time(); - m_cv.notify_all(); -} - -GlobalState GlobalStateTracker::infer_actual_state(size_t index){ - std::lock_guard lg(m_lock); - return infer_actual_state_unprotected(index); -} - -bool GlobalStateTracker::group_is_up_to_date(uint8_t group, time_point time_min){ - for (size_t c = 0; c < m_count; c++){ - // Skip non-matching groups. - if (m_groups[c] != group){ - continue; - } - if (m_pending_sync[c] == SyncState::NOT_CALLED){ - return false; - } - } - return true; -} -bool GlobalStateTracker::group_sync_completed(uint8_t group){ - for (size_t c = 0; c < m_count; c++){ - // Skip non-matching groups. - if (m_groups[c] != group){ - continue; - } - if (m_pending_sync[c] != SyncState::DONE){ - return false; - } - } - return true; -} -void GlobalStateTracker::group_clear_status(uint8_t group){ - for (size_t c = 0; c < m_count; c++){ - // Skip non-matching groups. - if (m_groups[c] != group){ - continue; - } - m_pending_sync[c] = SyncState::NOT_CALLED; - } -} -void GlobalStateTracker::mark_as_dead(size_t index){ - std::lock_guard lg(m_lock); - m_state_epoch++; - m_groups[index] = 4; -} - -GlobalState GlobalStateTracker::synchronize( - Logger& logger, size_t index, std::chrono::milliseconds window -){ - std::unique_lock lg(m_lock); - m_state_epoch++; - - time_point timestamp = current_time(); - logger.log("Synchronizing...", COLOR_MAGENTA); - - m_master_consoles[index] = m_consoles[index]; - m_master_consoles[index].timestamp = timestamp; - m_pending_sync[index] = SyncState::WAITING; - - if (group_is_up_to_date(m_groups[index], timestamp - window)){ - // We're the last one. Wake everyone up and return result. - m_cv.notify_all(); - m_pending_sync[index] = SyncState::DONE; - return infer_actual_state_unprotected(index); - } - - // Not the last one. Need to wait. - time_point time_limit = timestamp + window; - while (true){ - m_cv.wait_until(lg, time_limit); - - throw_if_cancelled(); - - time_point now = current_time(); - if (now > time_limit){ - m_state_epoch++; - logger.log("GlobalStateTracker::synchronize() timed out.", COLOR_RED); - group_clear_status(m_groups[index]); - update_groups_unprotected(); - return infer_actual_state_unprotected(index); - } - - if (group_is_up_to_date(m_groups[index], now - window)){ - break; - } - } - - m_state_epoch++; - m_pending_sync[index] = SyncState::DONE; - - if (!group_sync_completed(m_groups[index])){ - // Not the last one out. Just return. - return infer_actual_state_unprotected(index); - } - - // Last one out, clear and return. - group_clear_status(m_groups[index]); - update_groups_unprotected(); - return infer_actual_state_unprotected(index); -} - - - - -// -// This is more-or-less AI code for detecting forks and merging discrepancies. -// - - -template -Type merge_majority_vote( - const uint8_t groups[4], - size_t count, uint8_t group, - Lambda&& lambda -){ - std::map map; - for (size_t c = 0; c < count; c++){ - if (group != groups[c]){ - continue; - } - const Type& value = lambda(c); - map[value]++; - } - size_t best_count = 0; - Type best_value{}; - for (const auto& item : map){ - if (best_count <= item.second){ - best_count = item.second; - best_value = item.first; - } - } - return best_value; -} -template -Type merge_majority_vote( - const uint8_t groups[4], - size_t count, uint8_t group, Type null_value, - Lambda&& lambda -){ - std::map map; - for (size_t c = 0; c < count; c++){ - if (group != groups[c]){ - continue; - } - const Type& value = lambda(c); - if (value != null_value){ - map[value]++; - } - } - size_t best_count = 0; - Type best_value = null_value; - for (const auto& item : map){ - if (best_count <= item.second){ - best_count = item.second; - best_value = item.first; - } - } - return best_value; -} -template -Type merge_majority_vote( - const uint8_t groups[4], - size_t count, uint8_t group, Type null_value, - GlobalState states[4], - WallClock min_valid_time, - Lambda&& lambda -){ - std::map map; - for (size_t c = 0; c < count; c++){ - if (group != groups[c]){ - continue; - } - const Type& value = lambda(c); - if (value != null_value && states[c].timestamp >= min_valid_time){ - map[value]++; - } - } - size_t best_count = 0; - Type best_value = null_value; - for (const auto& item : map){ - if (best_count <= item.second){ - best_count = item.second; - best_value = item.first; - } - } - return best_value; -} -template -TimestampedValue merge_hp( - const uint8_t groups[4], - size_t count, uint8_t group, - Lambda&& lambda -){ -#if 0 - double sum = 0; - size_t num = 0; - for (size_t c = 0; c < count; c++){ - if (group != groups[c]){ - continue; - } - double value = lambda(c); - if (value < 0){ - continue; - } - sum += value; - num++; - } - return num == 0 ? -1 : sum / num; -#endif - TimestampedValue latest(-1, WallClock::min()); - for (size_t c = 0; c < count; c++){ - if (group != groups[c]){ - continue; - } - const TimestampedValue& current = lambda(c); - if (latest.timestamp < current.timestamp && current >= 0){ - latest = current; - } - } - return latest; -} - - - -std::set merge_sets(const std::vector*>& sets){ - std::map map; - for (const std::set* set : sets){ - if (set == nullptr){ - continue; - } - for (const std::string& str : *set){ - map[str]++; - } - } - if (map.empty()){ - return std::set(); - } - std::multimap> sorted; - for (const auto& item : map){ - sorted.emplace(item.second, item.first); - } - size_t count = sorted.begin()->first; - std::set ret; - for (const auto& item : sorted){ - if (item.first != count){ - break; - } - ret.insert(item.second); - } - return ret; -} - -void GlobalStateTracker::merge_timestamp(uint8_t group, GlobalState& state){ - for (size_t c = 0; c < m_count; c++){ - if (group != m_groups[c]){ - continue; - } - state.timestamp = std::max(state.timestamp, m_master_consoles[c].timestamp); - } -} -void GlobalStateTracker::merge_boss(uint8_t group, GlobalState& state){ - state.boss = merge_majority_vote( - m_groups, m_count, group, "", - [&](size_t index){ return m_master_consoles[index].boss; } - ); -} -#if 0 -void GlobalStateTracker::merge_boss_type(uint8_t group, GlobalState& state){ - state.boss_type = merge_majority_vote( - m_groups, m_count, group, PokemonType::NONE, - [&](size_t index){ return m_master_consoles[index].boss_type; } - ); -} -#endif -void GlobalStateTracker::merge_path(uint8_t group, GlobalState& state){ -// WallClock latest = WallClock::min(); - for (size_t c = 0; c < m_count; c++){ - if (group != m_groups[c]){ - continue; - } - if (m_master_consoles[c].path.path_type >= 0){ - state.path = m_master_consoles[c].path; - state.last_best_path = m_master_consoles[c].last_best_path; - return; - } - } -} -void GlobalStateTracker::merge_path_side(uint8_t group, GlobalState& state){ - state.path_side = merge_majority_vote( - m_groups, m_count, group, -1, - [&](size_t index){ return m_master_consoles[index].path_side; } - ); -} -void GlobalStateTracker::merge_seen(uint8_t group, GlobalState& state){ - std::set merged; - for (size_t c = 0; c < m_count; c++){ - if (group != m_groups[c]){ - continue; - } - for (const std::string& mon : m_master_consoles[c].seen){ - merged.insert(mon); - } - } - state.seen = std::move(merged); -} -void GlobalStateTracker::merge_wins(uint8_t group, GlobalState& state){ - state.wins = merge_majority_vote( - m_groups, m_count, group, - [&](size_t index){ return m_master_consoles[index].wins; } - ); -} -void GlobalStateTracker::merge_opponent_species(uint8_t group, GlobalState& state){ - state.opponent = merge_sets({ - 0 < m_count && m_groups[0] == group ? &m_master_consoles[0].opponent : nullptr, - 1 < m_count && m_groups[1] == group ? &m_master_consoles[1].opponent : nullptr, - 2 < m_count && m_groups[2] == group ? &m_master_consoles[2].opponent : nullptr, - 3 < m_count && m_groups[3] == group ? &m_master_consoles[3].opponent : nullptr, - }); -} -void GlobalStateTracker::merge_opponent_hp(uint8_t group, GlobalState& state){ - state.opponent_hp = merge_hp( - m_groups, m_count, group, - [&](size_t index){ return m_master_consoles[index].opponent_hp; } - ); -} -void GlobalStateTracker::merge_player_species(uint8_t group, PlayerState& player, size_t player_index){ - // Check if it's self-reported. - do{ - if (player.console_id < 0){ - break; - } - if (group != m_groups[player.console_id]){ - return; - } - std::string self_reported_mon = m_master_consoles[player.console_id].players[player_index].pokemon; - if (!self_reported_mon.empty()){ - player.pokemon = std::move(self_reported_mon); - return; - } - }while (false); - - // Otherwise, do majority vote. - player.pokemon = merge_majority_vote( - m_groups, m_count, group, "", - [&](size_t index){ return m_master_consoles[index].players[player_index].pokemon; } - ); -} -void GlobalStateTracker::merge_player_console_id(uint8_t group, PlayerState& player, size_t player_index){ - for (size_t c = 0; c < m_count; c++){ - if (group != m_groups[c]){ - player.console_id = -1; - continue; - } - int8_t console_id = m_master_consoles[c].players[player_index].console_id; - if (console_id >= 0){ - player.console_id = console_id; - break; - } - } -} -void GlobalStateTracker::merge_player_item(uint8_t group, PlayerState& player, size_t player_index){ - player.item = merge_majority_vote( - m_groups, m_count, group, "", - [&](size_t index){ return m_master_consoles[index].players[player_index].item; } - ); -} -#if 0 -void GlobalStateTracker::merge_player_dead(uint8_t group, PlayerState& player, size_t player_index, time_point now){ - player.is_dead = merge_majority_vote( - m_groups, m_count, group, -1, - m_master_consoles, now - std::chrono::seconds(12), - [&](size_t index){ return m_master_consoles[index].players[player_index].is_dead; } - ); -} -void GlobalStateTracker::merge_player_hp(uint8_t group, PlayerState& player, size_t player_index){ - player.hp = merge_hp( - m_groups, m_count, group, - [&](size_t index){ return m_master_consoles[index].players[player_index].hp; } - ); -} -#endif -void GlobalStateTracker::merge_player_health(uint8_t group, PlayerState& player, size_t player_index){ - TimestampedValue latest(Health(), WallClock::min()); - for (size_t c = 0; c < m_count; c++){ - if (group != m_groups[c]){ - continue; - } - const TimestampedValue& current = m_master_consoles[c].players[player_index].health; - if (latest.timestamp < current.timestamp && current.value.hp >= 0){ - latest = current; - } - } - player.health = latest; -} -void GlobalStateTracker::merge_player_dmax_turns_left(uint8_t group, PlayerState& player, size_t player_index){ - player.dmax_turns_left = merge_majority_vote( - m_groups, m_count, group, -1, - [&](size_t index){ return m_master_consoles[index].players[player_index].dmax_turns_left; } - ); -} -void GlobalStateTracker::merge_player_can_dmax(uint8_t group, PlayerState& player, size_t player_index){ - // Ability to dmax is self-reporting. - for (size_t c = 0; c < m_count; c++){ - if (group != m_groups[c]){ - continue; - } - player.can_dmax |= m_master_consoles[c].players[player_index].can_dmax; - } -} -void GlobalStateTracker::merge_player_pp(uint8_t group, PlayerState& player, size_t player_index, size_t move_index){ - player.pp[move_index] = merge_majority_vote( - m_groups, m_count, group, -1, - [&](size_t index){ return m_master_consoles[index].players[player_index].pp[move_index]; } - ); -} -void GlobalStateTracker::merge_player_move_blocked(uint8_t group, PlayerState& player, size_t player_index, size_t move_index){ - player.move_blocked[move_index] = merge_majority_vote( - m_groups, m_count, group, false, - [&](size_t index){ return m_master_consoles[index].players[player_index].move_blocked[move_index]; } - ); -} - - -GlobalState GlobalStateTracker::infer_actual_state_unprotected(size_t index){ - uint8_t group = m_groups[index]; - - GlobalState state; - merge_timestamp(group, state); - merge_boss(group, state); - merge_path(group, state); - merge_path_side(group, state); - merge_seen(group, state); - - merge_wins(group, state); - merge_opponent_species(group, state); - merge_opponent_hp(group, state); - - for (size_t player_index = 0; player_index < 4; player_index++){ - PlayerState& player = state.players[player_index]; - merge_player_console_id(group, player, player_index); - merge_player_species(group, player, player_index); - merge_player_item(group, player, player_index); -// merge_player_dead(group, player, player_index, state.timestamp); -// merge_player_hp(group, player, player_index); - merge_player_health(group, player, player_index); - merge_player_dmax_turns_left(group, player, player_index); - merge_player_can_dmax(group, player, player_index); - for (size_t c = 0; c < 4; c++){ - merge_player_pp(group, player, player_index, c); - merge_player_move_blocked(group, player, player_index, c); - } - } - - return state; -} -void GlobalStateTracker::update_groups_unprotected(){ -#if 0 - // Assume everyone's in a different universe. - m_groups[0] = 0; - m_groups[1] = 1; - m_groups[2] = 2; - m_groups[3] = 3; -#endif -#if 1 - // Assume everyone's in the same universe. - m_groups[0] = 0; - m_groups[1] = 0; - m_groups[2] = 0; - m_groups[3] = 0; -#endif -} - - - - -} -} -} -} +/* Max Lair State Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "Common/Compiler.h" +#include "Common/Cpp/AbstractLogger.h" +#include "PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +GlobalStateTracker::GlobalStateTracker(CancellableScope& scope, size_t consoles) + : m_count(consoles) +{ + auto timestamp = current_time(); + for (size_t c = 0; c < 4; c++){ + m_master_consoles[c].timestamp = timestamp; + } + update_groups_unprotected(); + attach(scope); +} +GlobalStateTracker::~GlobalStateTracker(){ + detach(); +} +std::pair GlobalStateTracker::dump(){ + std::lock_guard lg(m_lock); + std::string str; + for (size_t c = 0; c < m_count; c++){ + str += "Switch " + std::to_string(c) + ": (group " + std::to_string(m_groups[c]) + ")\n"; + str += m_consoles[c].dump(); + } +#if 0 + for (size_t c = 0; c < m_count; c++){ + str += "Inferred " + std::to_string(c) + ":\n"; + str += compute_inferred_unprotected(c).dump(); + } +#endif + return {m_state_epoch, str}; +} +bool GlobalStateTracker::cancel(std::exception_ptr exception) noexcept{ + if (Cancellable::cancel(std::move(exception))){ + return true; + } + std::lock_guard lg(m_lock); + m_cv.notify_all(); + return false; +} +void GlobalStateTracker::push_update(size_t index){ + std::lock_guard lg(m_lock); + m_state_epoch++; + m_master_consoles[index] = m_consoles[index]; + m_master_consoles[index].timestamp = current_time(); + m_cv.notify_all(); +} + +GlobalState GlobalStateTracker::infer_actual_state(size_t index){ + std::lock_guard lg(m_lock); + return infer_actual_state_unprotected(index); +} + +bool GlobalStateTracker::group_is_up_to_date(uint8_t group, time_point time_min){ + for (size_t c = 0; c < m_count; c++){ + // Skip non-matching groups. + if (m_groups[c] != group){ + continue; + } + if (m_pending_sync[c] == SyncState::NOT_CALLED){ + return false; + } + } + return true; +} +bool GlobalStateTracker::group_sync_completed(uint8_t group){ + for (size_t c = 0; c < m_count; c++){ + // Skip non-matching groups. + if (m_groups[c] != group){ + continue; + } + if (m_pending_sync[c] != SyncState::DONE){ + return false; + } + } + return true; +} +void GlobalStateTracker::group_clear_status(uint8_t group){ + for (size_t c = 0; c < m_count; c++){ + // Skip non-matching groups. + if (m_groups[c] != group){ + continue; + } + m_pending_sync[c] = SyncState::NOT_CALLED; + } +} +void GlobalStateTracker::mark_as_dead(size_t index){ + std::lock_guard lg(m_lock); + m_state_epoch++; + m_groups[index] = 4; +} + +GlobalState GlobalStateTracker::synchronize( + Logger& logger, size_t index, std::chrono::milliseconds window +){ + std::unique_lock lg(m_lock); + m_state_epoch++; + + time_point timestamp = current_time(); + logger.log("Synchronizing...", COLOR_MAGENTA); + + m_master_consoles[index] = m_consoles[index]; + m_master_consoles[index].timestamp = timestamp; + m_pending_sync[index] = SyncState::WAITING; + + if (group_is_up_to_date(m_groups[index], timestamp - window)){ + // We're the last one. Wake everyone up and return result. + m_cv.notify_all(); + m_pending_sync[index] = SyncState::DONE; + return infer_actual_state_unprotected(index); + } + + // Not the last one. Need to wait. + time_point time_limit = timestamp + window; + while (true){ + m_cv.wait_until(lg, time_limit); + + throw_if_cancelled(); + + time_point now = current_time(); + if (now > time_limit){ + m_state_epoch++; + logger.log("GlobalStateTracker::synchronize() timed out.", COLOR_RED); + group_clear_status(m_groups[index]); + update_groups_unprotected(); + return infer_actual_state_unprotected(index); + } + + if (group_is_up_to_date(m_groups[index], now - window)){ + break; + } + } + + m_state_epoch++; + m_pending_sync[index] = SyncState::DONE; + + if (!group_sync_completed(m_groups[index])){ + // Not the last one out. Just return. + return infer_actual_state_unprotected(index); + } + + // Last one out, clear and return. + group_clear_status(m_groups[index]); + update_groups_unprotected(); + return infer_actual_state_unprotected(index); +} + + + + +// +// This is more-or-less AI code for detecting forks and merging discrepancies. +// + + +template +Type merge_majority_vote( + const uint8_t groups[4], + size_t count, uint8_t group, + Lambda&& lambda +){ + std::map map; + for (size_t c = 0; c < count; c++){ + if (group != groups[c]){ + continue; + } + const Type& value = lambda(c); + map[value]++; + } + size_t best_count = 0; + Type best_value{}; + for (const auto& item : map){ + if (best_count <= item.second){ + best_count = item.second; + best_value = item.first; + } + } + return best_value; +} +template +Type merge_majority_vote( + const uint8_t groups[4], + size_t count, uint8_t group, Type null_value, + Lambda&& lambda +){ + std::map map; + for (size_t c = 0; c < count; c++){ + if (group != groups[c]){ + continue; + } + const Type& value = lambda(c); + if (value != null_value){ + map[value]++; + } + } + size_t best_count = 0; + Type best_value = null_value; + for (const auto& item : map){ + if (best_count <= item.second){ + best_count = item.second; + best_value = item.first; + } + } + return best_value; +} +template +Type merge_majority_vote( + const uint8_t groups[4], + size_t count, uint8_t group, Type null_value, + GlobalState states[4], + WallClock min_valid_time, + Lambda&& lambda +){ + std::map map; + for (size_t c = 0; c < count; c++){ + if (group != groups[c]){ + continue; + } + const Type& value = lambda(c); + if (value != null_value && states[c].timestamp >= min_valid_time){ + map[value]++; + } + } + size_t best_count = 0; + Type best_value = null_value; + for (const auto& item : map){ + if (best_count <= item.second){ + best_count = item.second; + best_value = item.first; + } + } + return best_value; +} +template +TimestampedValue merge_hp( + const uint8_t groups[4], + size_t count, uint8_t group, + Lambda&& lambda +){ +#if 0 + double sum = 0; + size_t num = 0; + for (size_t c = 0; c < count; c++){ + if (group != groups[c]){ + continue; + } + double value = lambda(c); + if (value < 0){ + continue; + } + sum += value; + num++; + } + return num == 0 ? -1 : sum / num; +#endif + TimestampedValue latest(-1, WallClock::min()); + for (size_t c = 0; c < count; c++){ + if (group != groups[c]){ + continue; + } + const TimestampedValue& current = lambda(c); + if (latest.timestamp < current.timestamp && current >= 0){ + latest = current; + } + } + return latest; +} + + + +std::set merge_sets(const std::vector*>& sets){ + std::map map; + for (const std::set* set : sets){ + if (set == nullptr){ + continue; + } + for (const std::string& str : *set){ + map[str]++; + } + } + if (map.empty()){ + return std::set(); + } + std::multimap> sorted; + for (const auto& item : map){ + sorted.emplace(item.second, item.first); + } + size_t count = sorted.begin()->first; + std::set ret; + for (const auto& item : sorted){ + if (item.first != count){ + break; + } + ret.insert(item.second); + } + return ret; +} + +void GlobalStateTracker::merge_timestamp(uint8_t group, GlobalState& state){ + for (size_t c = 0; c < m_count; c++){ + if (group != m_groups[c]){ + continue; + } + state.timestamp = std::max(state.timestamp, m_master_consoles[c].timestamp); + } +} +void GlobalStateTracker::merge_boss(uint8_t group, GlobalState& state){ + state.boss = merge_majority_vote( + m_groups, m_count, group, "", + [&](size_t index){ return m_master_consoles[index].boss; } + ); +} +#if 0 +void GlobalStateTracker::merge_boss_type(uint8_t group, GlobalState& state){ + state.boss_type = merge_majority_vote( + m_groups, m_count, group, PokemonType::NONE, + [&](size_t index){ return m_master_consoles[index].boss_type; } + ); +} +#endif +void GlobalStateTracker::merge_path(uint8_t group, GlobalState& state){ +// WallClock latest = WallClock::min(); + for (size_t c = 0; c < m_count; c++){ + if (group != m_groups[c]){ + continue; + } + if (m_master_consoles[c].path.path_type >= 0){ + state.path = m_master_consoles[c].path; + state.last_best_path = m_master_consoles[c].last_best_path; + return; + } + } +} +void GlobalStateTracker::merge_path_side(uint8_t group, GlobalState& state){ + state.path_side = merge_majority_vote( + m_groups, m_count, group, -1, + [&](size_t index){ return m_master_consoles[index].path_side; } + ); +} +void GlobalStateTracker::merge_seen(uint8_t group, GlobalState& state){ + std::set merged; + for (size_t c = 0; c < m_count; c++){ + if (group != m_groups[c]){ + continue; + } + for (const std::string& mon : m_master_consoles[c].seen){ + merged.insert(mon); + } + } + state.seen = std::move(merged); +} +void GlobalStateTracker::merge_wins(uint8_t group, GlobalState& state){ + state.wins = merge_majority_vote( + m_groups, m_count, group, + [&](size_t index){ return m_master_consoles[index].wins; } + ); +} +void GlobalStateTracker::merge_opponent_species(uint8_t group, GlobalState& state){ + state.opponent = merge_sets({ + 0 < m_count && m_groups[0] == group ? &m_master_consoles[0].opponent : nullptr, + 1 < m_count && m_groups[1] == group ? &m_master_consoles[1].opponent : nullptr, + 2 < m_count && m_groups[2] == group ? &m_master_consoles[2].opponent : nullptr, + 3 < m_count && m_groups[3] == group ? &m_master_consoles[3].opponent : nullptr, + }); +} +void GlobalStateTracker::merge_opponent_hp(uint8_t group, GlobalState& state){ + state.opponent_hp = merge_hp( + m_groups, m_count, group, + [&](size_t index){ return m_master_consoles[index].opponent_hp; } + ); +} +void GlobalStateTracker::merge_player_species(uint8_t group, PlayerState& player, size_t player_index){ + // Check if it's self-reported. + do{ + if (player.console_id < 0){ + break; + } + if (group != m_groups[player.console_id]){ + return; + } + std::string self_reported_mon = m_master_consoles[player.console_id].players[player_index].pokemon; + if (!self_reported_mon.empty()){ + player.pokemon = std::move(self_reported_mon); + return; + } + }while (false); + + // Otherwise, do majority vote. + player.pokemon = merge_majority_vote( + m_groups, m_count, group, "", + [&](size_t index){ return m_master_consoles[index].players[player_index].pokemon; } + ); +} +void GlobalStateTracker::merge_player_console_id(uint8_t group, PlayerState& player, size_t player_index){ + for (size_t c = 0; c < m_count; c++){ + if (group != m_groups[c]){ + player.console_id = -1; + continue; + } + int8_t console_id = m_master_consoles[c].players[player_index].console_id; + if (console_id >= 0){ + player.console_id = console_id; + break; + } + } +} +void GlobalStateTracker::merge_player_item(uint8_t group, PlayerState& player, size_t player_index){ + player.item = merge_majority_vote( + m_groups, m_count, group, "", + [&](size_t index){ return m_master_consoles[index].players[player_index].item; } + ); +} +#if 0 +void GlobalStateTracker::merge_player_dead(uint8_t group, PlayerState& player, size_t player_index, time_point now){ + player.is_dead = merge_majority_vote( + m_groups, m_count, group, -1, + m_master_consoles, now - std::chrono::seconds(12), + [&](size_t index){ return m_master_consoles[index].players[player_index].is_dead; } + ); +} +void GlobalStateTracker::merge_player_hp(uint8_t group, PlayerState& player, size_t player_index){ + player.hp = merge_hp( + m_groups, m_count, group, + [&](size_t index){ return m_master_consoles[index].players[player_index].hp; } + ); +} +#endif +void GlobalStateTracker::merge_player_health(uint8_t group, PlayerState& player, size_t player_index){ + TimestampedValue latest(Health(), WallClock::min()); + for (size_t c = 0; c < m_count; c++){ + if (group != m_groups[c]){ + continue; + } + const TimestampedValue& current = m_master_consoles[c].players[player_index].health; + if (latest.timestamp < current.timestamp && current.value.hp >= 0){ + latest = current; + } + } + player.health = latest; +} +void GlobalStateTracker::merge_player_dmax_turns_left(uint8_t group, PlayerState& player, size_t player_index){ + player.dmax_turns_left = merge_majority_vote( + m_groups, m_count, group, -1, + [&](size_t index){ return m_master_consoles[index].players[player_index].dmax_turns_left; } + ); +} +void GlobalStateTracker::merge_player_can_dmax(uint8_t group, PlayerState& player, size_t player_index){ + // Ability to dmax is self-reporting. + for (size_t c = 0; c < m_count; c++){ + if (group != m_groups[c]){ + continue; + } + player.can_dmax |= m_master_consoles[c].players[player_index].can_dmax; + } +} +void GlobalStateTracker::merge_player_pp(uint8_t group, PlayerState& player, size_t player_index, size_t move_index){ + player.pp[move_index] = merge_majority_vote( + m_groups, m_count, group, -1, + [&](size_t index){ return m_master_consoles[index].players[player_index].pp[move_index]; } + ); +} +void GlobalStateTracker::merge_player_move_blocked(uint8_t group, PlayerState& player, size_t player_index, size_t move_index){ + player.move_blocked[move_index] = merge_majority_vote( + m_groups, m_count, group, false, + [&](size_t index){ return m_master_consoles[index].players[player_index].move_blocked[move_index]; } + ); +} + + +GlobalState GlobalStateTracker::infer_actual_state_unprotected(size_t index){ + uint8_t group = m_groups[index]; + + GlobalState state; + merge_timestamp(group, state); + merge_boss(group, state); + merge_path(group, state); + merge_path_side(group, state); + merge_seen(group, state); + + merge_wins(group, state); + merge_opponent_species(group, state); + merge_opponent_hp(group, state); + + for (size_t player_index = 0; player_index < 4; player_index++){ + PlayerState& player = state.players[player_index]; + merge_player_console_id(group, player, player_index); + merge_player_species(group, player, player_index); + merge_player_item(group, player, player_index); +// merge_player_dead(group, player, player_index, state.timestamp); +// merge_player_hp(group, player, player_index); + merge_player_health(group, player, player_index); + merge_player_dmax_turns_left(group, player, player_index); + merge_player_can_dmax(group, player, player_index); + for (size_t c = 0; c < 4; c++){ + merge_player_pp(group, player, player_index, c); + merge_player_move_blocked(group, player, player_index, c); + } + } + + return state; +} +void GlobalStateTracker::update_groups_unprotected(){ +#if 0 + // Assume everyone's in a different universe. + m_groups[0] = 0; + m_groups[1] = 1; + m_groups[2] = 2; + m_groups[3] = 3; +#endif +#if 1 + // Assume everyone's in the same universe. + m_groups[0] = 0; + m_groups[1] = 0; + m_groups[2] = 0; + m_groups[3] = 0; +#endif +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h index 06bd971180..3612ae20da 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h @@ -1,120 +1,120 @@ -/* Max Lair State Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_StateTracker_H -#define PokemonAutomation_PokemonSwSh_MaxLair_StateTracker_H - -#include -#include -#include "Common/Cpp/CancellableScope.h" -#include "PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class GlobalStateTracker final : public Cancellable{ - using time_point = WallClock; -public: - GlobalStateTracker(CancellableScope& scope, size_t consoles); - virtual ~GlobalStateTracker(); - virtual bool cancel(std::exception_ptr exception) noexcept override; - - // Access the local copy for this console. - // This one is safe to directly access. - GlobalState& operator[](size_t index){ - return m_consoles[index]; - } - - // Push the local copy into the master shared copy. - void push_update(size_t index); - - // Get the inferred state from all the known states. - GlobalState infer_actual_state(size_t index); - - // Attempt to synchronize with other consoles. - GlobalState synchronize( - Logger& logger, size_t index, - std::chrono::milliseconds window = std::chrono::seconds(5) - ); - - void mark_as_dead(size_t index); - - std::pair dump(); - - - -private: - // Recompute the group assignments. - void update_groups_unprotected(); - bool group_is_up_to_date(uint8_t group, time_point time_min); - bool group_sync_completed(uint8_t group); - void group_clear_status(uint8_t group); - GlobalState infer_actual_state_unprotected(size_t index); - - -private: - void merge_timestamp (uint8_t group, GlobalState& state); - void merge_boss (uint8_t group, GlobalState& state); -// void merge_boss_type (uint8_t group, GlobalState& state); - void merge_path (uint8_t group, GlobalState& state); - void merge_path_side (uint8_t group, GlobalState& state); - void merge_seen (uint8_t group, GlobalState& state); - - void merge_wins (uint8_t group, GlobalState& state); - void merge_opponent_species (uint8_t group, GlobalState& state); - void merge_opponent_hp (uint8_t group, GlobalState& state); - - void merge_player_console_id (uint8_t group, PlayerState& player, size_t player_index); - void merge_player_species (uint8_t group, PlayerState& player, size_t player_index); - void merge_player_item (uint8_t group, PlayerState& player, size_t player_index); -// void merge_player_dead (uint8_t group, PlayerState& player, size_t player_index, time_point now); -// void merge_player_hp (uint8_t group, PlayerState& player, size_t player_index); - void merge_player_health (uint8_t group, PlayerState& player, size_t player_index); - void merge_player_dmax_turns_left (uint8_t group, PlayerState& player, size_t player_index); - void merge_player_can_dmax (uint8_t group, PlayerState& player, size_t player_index); - void merge_player_pp (uint8_t group, PlayerState& player, size_t player_index, size_t move_index); - void merge_player_move_blocked (uint8_t group, PlayerState& player, size_t player_index, size_t move_index); - - -private: - std::mutex m_lock; - std::condition_variable m_cv; - - uint64_t m_state_epoch = 0; - - size_t m_count; - GlobalState m_consoles[4]; - -// SpinLock m_lock; - - enum class SyncState{ - NOT_CALLED, - WAITING, - DONE - }; - - SyncState m_pending_sync[4] = { - SyncState::NOT_CALLED, - SyncState::NOT_CALLED, - SyncState::NOT_CALLED, - SyncState::NOT_CALLED - }; - GlobalState m_master_consoles[4]; - - uint8_t m_groups[4]; -}; - - - -} -} -} -} -#endif +/* Max Lair State Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_StateTracker_H +#define PokemonAutomation_PokemonSwSh_MaxLair_StateTracker_H + +#include +#include +#include "Common/Cpp/CancellableScope.h" +#include "PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class GlobalStateTracker final : public Cancellable{ + using time_point = WallClock; +public: + GlobalStateTracker(CancellableScope& scope, size_t consoles); + virtual ~GlobalStateTracker(); + virtual bool cancel(std::exception_ptr exception) noexcept override; + + // Access the local copy for this console. + // This one is safe to directly access. + GlobalState& operator[](size_t index){ + return m_consoles[index]; + } + + // Push the local copy into the master shared copy. + void push_update(size_t index); + + // Get the inferred state from all the known states. + GlobalState infer_actual_state(size_t index); + + // Attempt to synchronize with other consoles. + GlobalState synchronize( + Logger& logger, size_t index, + std::chrono::milliseconds window = std::chrono::seconds(5) + ); + + void mark_as_dead(size_t index); + + std::pair dump(); + + + +private: + // Recompute the group assignments. + void update_groups_unprotected(); + bool group_is_up_to_date(uint8_t group, time_point time_min); + bool group_sync_completed(uint8_t group); + void group_clear_status(uint8_t group); + GlobalState infer_actual_state_unprotected(size_t index); + + +private: + void merge_timestamp (uint8_t group, GlobalState& state); + void merge_boss (uint8_t group, GlobalState& state); +// void merge_boss_type (uint8_t group, GlobalState& state); + void merge_path (uint8_t group, GlobalState& state); + void merge_path_side (uint8_t group, GlobalState& state); + void merge_seen (uint8_t group, GlobalState& state); + + void merge_wins (uint8_t group, GlobalState& state); + void merge_opponent_species (uint8_t group, GlobalState& state); + void merge_opponent_hp (uint8_t group, GlobalState& state); + + void merge_player_console_id (uint8_t group, PlayerState& player, size_t player_index); + void merge_player_species (uint8_t group, PlayerState& player, size_t player_index); + void merge_player_item (uint8_t group, PlayerState& player, size_t player_index); +// void merge_player_dead (uint8_t group, PlayerState& player, size_t player_index, time_point now); +// void merge_player_hp (uint8_t group, PlayerState& player, size_t player_index); + void merge_player_health (uint8_t group, PlayerState& player, size_t player_index); + void merge_player_dmax_turns_left (uint8_t group, PlayerState& player, size_t player_index); + void merge_player_can_dmax (uint8_t group, PlayerState& player, size_t player_index); + void merge_player_pp (uint8_t group, PlayerState& player, size_t player_index, size_t move_index); + void merge_player_move_blocked (uint8_t group, PlayerState& player, size_t player_index, size_t move_index); + + +private: + std::mutex m_lock; + std::condition_variable m_cv; + + uint64_t m_state_epoch = 0; + + size_t m_count; + GlobalState m_consoles[4]; + +// SpinLock m_lock; + + enum class SyncState{ + NOT_CALLED, + WAITING, + DONE + }; + + SyncState m_pending_sync[4] = { + SyncState::NOT_CALLED, + SyncState::NOT_CALLED, + SyncState::NOT_CALLED, + SyncState::NOT_CALLED + }; + GlobalState m_master_consoles[4]; + + uint8_t m_groups[4]; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h index ea0e91959f..9501d4aed4 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h @@ -1,111 +1,111 @@ -/* Max Lair Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Stats_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Stats_H - -#include "CommonFramework/ProgramStats/StatsTracking.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -struct Stats : public StatsTracker{ - Stats() - : m_runs(m_stats["Runs"]) - , m_errors(m_stats["Errors"]) - , m_wins(m_stats["Wins"]) - , m_catches(m_stats["Catches"]) - , m_shinies(m_stats["Shinies"]) - , m_shiny_legendary(m_stats["Shiny Legendary"]) - { - m_display_order.emplace_back("Runs"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Wins"); - m_display_order.emplace_back("Catches"); - m_display_order.emplace_back("Shinies"); - m_display_order.emplace_back("Shiny Legendary", HIDDEN_IF_ZERO); - } - - void add_run(size_t catches){ - m_runs++; - m_catches += catches; - if (catches >= 4){ - m_wins++; - } - } - void add_error(){ - m_errors++; - } - void add_shiny(){ - m_shinies++; - } - void add_shiny_legendary(){ - m_shiny_legendary++; - } - - -private: - std::atomic& m_runs; - std::atomic& m_errors; - std::atomic& m_wins; - std::atomic& m_catches; - std::atomic& m_shinies; - std::atomic& m_shiny_legendary; -}; - - -class PathStats : public StatsTracker{ -public: - PathStats() - : m_runs(m_stats["Runs"]) - , m_wins(m_stats["Wins"]) - { - m_display_order.emplace_back("Runs"); - m_display_order.emplace_back("Wins"); - } - - void clear(){ -// cout << "PathStats::clear()" << endl; - m_wins.store(0, std::memory_order_release); - m_runs.store(0, std::memory_order_release); - } - void add_run(bool win){ -// cout << "PathStats::add_run(): " << win << endl; - m_runs++; - if (win){ - m_wins++; - } - } - - uint64_t runs() const{ -// cout << "PathStats::runs()" << m_runs << endl; - return m_runs.load(std::memory_order_relaxed); - } - uint64_t wins() const{ - return m_wins.load(std::memory_order_relaxed); - } - double win_ratio() const{ - uint64_t runs = m_runs.load(std::memory_order_acquire); - uint64_t wins = m_wins.load(std::memory_order_acquire); - return (double)wins / (double)runs; - } - - -private: - std::atomic& m_runs; - std::atomic& m_wins; -}; - - - -} -} -} -} -#endif +/* Max Lair Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Stats_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Stats_H + +#include "CommonFramework/ProgramStats/StatsTracking.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +struct Stats : public StatsTracker{ + Stats() + : m_runs(m_stats["Runs"]) + , m_errors(m_stats["Errors"]) + , m_wins(m_stats["Wins"]) + , m_catches(m_stats["Catches"]) + , m_shinies(m_stats["Shinies"]) + , m_shiny_legendary(m_stats["Shiny Legendary"]) + { + m_display_order.emplace_back("Runs"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Wins"); + m_display_order.emplace_back("Catches"); + m_display_order.emplace_back("Shinies"); + m_display_order.emplace_back("Shiny Legendary", HIDDEN_IF_ZERO); + } + + void add_run(size_t catches){ + m_runs++; + m_catches += catches; + if (catches >= 4){ + m_wins++; + } + } + void add_error(){ + m_errors++; + } + void add_shiny(){ + m_shinies++; + } + void add_shiny_legendary(){ + m_shiny_legendary++; + } + + +private: + std::atomic& m_runs; + std::atomic& m_errors; + std::atomic& m_wins; + std::atomic& m_catches; + std::atomic& m_shinies; + std::atomic& m_shiny_legendary; +}; + + +class PathStats : public StatsTracker{ +public: + PathStats() + : m_runs(m_stats["Runs"]) + , m_wins(m_stats["Wins"]) + { + m_display_order.emplace_back("Runs"); + m_display_order.emplace_back("Wins"); + } + + void clear(){ +// cout << "PathStats::clear()" << endl; + m_wins.store(0, std::memory_order_release); + m_runs.store(0, std::memory_order_release); + } + void add_run(bool win){ +// cout << "PathStats::add_run(): " << win << endl; + m_runs++; + if (win){ + m_wins++; + } + } + + uint64_t runs() const{ +// cout << "PathStats::runs()" << m_runs << endl; + return m_runs.load(std::memory_order_relaxed); + } + uint64_t wins() const{ + return m_wins.load(std::memory_order_relaxed); + } + double win_ratio() const{ + uint64_t runs = m_runs.load(std::memory_order_acquire); + uint64_t wins = m_wins.load(std::memory_order_acquire); + return (double)wins / (double)runs; + } + + +private: + std::atomic& m_runs; + std::atomic& m_wins; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.cpp index 37edebe1ab..055ff82fb5 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.cpp @@ -1,564 +1,564 @@ -/* Max Lair Detect Battle Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/CancellableScope.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/ColorClustering.h" -#include "Pokemon/Inference/Pokemon_ReadHpBar.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" -#include "PokemonSwSh_MaxLair_Detect_HPPP.h" -#include "PokemonSwSh_MaxLair_Detect_BattleMenu.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -BattleMenuDetector::BattleMenuDetector() - : VisualInferenceCallback("BattleMenuDetector") - , m_icon_fight (0.923, 0.576 + 1 * 0.1075, 0.05, 0.080) - , m_icon_pokemon(0.923, 0.576 + 2 * 0.1075, 0.05, 0.080) - , m_icon_run (0.923, 0.576 + 3 * 0.1075, 0.05, 0.080) - , m_text_fight (0.830, 0.576 + 1 * 0.1075, 0.08, 0.080) - , m_text_pokemon(0.830, 0.576 + 2 * 0.1075, 0.08, 0.080) - , m_text_run (0.830, 0.576 + 3 * 0.1075, 0.08, 0.080) - , m_icon_cheer (0.923, 0.636 + 1 * 0.1075, 0.05, 0.020) -// , m_info_left (0.907, 0.500, 0.02, 0.03) -// , m_info_right (0.970, 0.500, 0.02, 0.03) - , m_status0 (0.280, 0.870, 0.015, 0.030) - , m_status1 (0.165, 0.945, 0.100, 0.015) -{} -void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_YELLOW, m_icon_fight); - items.add(COLOR_YELLOW, m_icon_pokemon); - items.add(COLOR_YELLOW, m_icon_run); - items.add(COLOR_YELLOW, m_text_fight); - items.add(COLOR_YELLOW, m_text_pokemon); - items.add(COLOR_YELLOW, m_text_run); - items.add(COLOR_YELLOW, m_icon_cheer); - items.add(COLOR_YELLOW, m_status0); - items.add(COLOR_YELLOW, m_status1); -} -bool BattleMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - // Need 5 consecutive successful detections. - if (!detect(frame)){ - m_trigger_count = 0; - return false; - } - m_trigger_count++; - return m_trigger_count >= 5; -} - - -bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ - bool fight; - - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_fight), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_fight), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - if (!fight){ -// cout << "Fight out" << endl; - return false; - } - - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_pokemon), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_pokemon), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - if (!fight){ -// cout << "Pokemon out" << endl; - return false; - } - - fight = false; - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_run), - Color(0, 0, 0), 0.1, - Color(255, 255, 255), 0.9 - ); - fight |= !fight && cluster_fit_2( - extract_box_reference(screen, m_text_run), - Color(0, 0, 0), 0.9, - Color(255, 255, 255), 0.1 - ); - if (!fight){ -// cout << "Run out" << endl; - return false; - } - -// cout << "===============" << endl; - - fight = false; - fight |= !fight && cluster_fit_2( // Not selected (red on white) - extract_box_reference(screen, m_icon_fight), - Color(255, 255, 255), 1.7, - Color(153, 75, 112), 1.0 - ); - fight |= !fight && cluster_fit_2( // Selected (red on black) - extract_box_reference(screen, m_icon_fight), - Color(0, 0, 0), 1.4, - Color(185, 6, 40), 1.0 - ); - fight |= !fight && cluster_fit_2( // Max raid Fight button is a bit different. - extract_box_reference(screen, m_icon_fight), - Color(0, 0, 0), 1.7, - Color(182, 33, 82), 1.0 - ); -// cout << "===============" << endl; - if (!fight){ - fight = cluster_fit_2( // Cheer - extract_box_reference(screen, m_icon_cheer), - Color(0, 0, 0), 1.0, - Color(9, 162, 218), 1.0, - 0.2, 60 - ); -// cout << "fight = " << fight << endl; - m_cheer = fight; - } - if (!fight){ -// cout << "Failed: m_icon_fight" << endl; - return false; - } - - bool pokemon = false; - pokemon |= !pokemon && cluster_fit_2( - extract_box_reference(screen, m_icon_pokemon), - Color(255, 255, 255), 3.1, - Color(126, 224, 142), 1.0 - ); - pokemon |= !pokemon && cluster_fit_2( - extract_box_reference(screen, m_icon_pokemon), - Color(0, 0, 0), 2.7, - Color(8, 158, 18), 1.0 - ); - if (!pokemon){ -// cout << "Failed: m_icon_pokemon" << endl; - return false; - } - - bool run = false; - run |= !run && cluster_fit_2( - extract_box_reference(screen, m_icon_run), - Color(255, 255, 255), 2.3, - Color(216, 150, 230), 1.0 - ); - run |= !run && cluster_fit_2( - extract_box_reference(screen, m_icon_run), - Color(0, 0, 0), 1.9, - Color(179, 15, 195), 1.0 - ); - if (!run){ -// cout << "Failed: m_icon_run" << endl; - return false; - } - - - // Check for white status bar in bottom left corner. - ImageStats status = image_stats(extract_box_reference(screen, m_status0)); - ImageStats health = image_stats(extract_box_reference(screen, m_status1)); -// extract_box_reference(screen, m_status1).save("test.png"); -// cout << status.average << ", " << status.stddev << endl; -// cout << health.average << ", " << health.stddev << endl; - if (is_white(status, 500, 20) && is_white(health)){ - m_dmaxed = false; - return true; - } - - // Check the semi-transparent red status bar if you're dmaxed. - if (is_solid(status, {0.618001, 0.145809, 0.23619}, 0.15, 40) && - is_solid(health, {0.615249, 0.102789, 0.281963}, 0.15, 40) - ){ - m_dmaxed = true; - return true; - } - - -// image.save("battle-menu.png"); - return false; -} - - - - -BattleMenuReader::BattleMenuReader( - VideoOverlay& overlay, - Language language, - OcrFailureWatchdog& ocr_watchdog -) - : m_language(language) - , m_ocr_watchdog(ocr_watchdog) - , m_opponent_name(overlay, {0.3, 0.010, 0.4, 0.10}, COLOR_BLUE) - , m_summary_opponent_name(overlay, {0.200, 0.100, 0.300, 0.065}, COLOR_BLUE) - , m_summary_opponent_types(overlay, {0.200, 0.170, 0.300, 0.050}, COLOR_BLUE) - , m_own_name(overlay, {0.060, 0.860, 0.160, 0.045}, COLOR_BLUE) - , m_own_sprite(overlay, {0.002, 0.860, 0.060, 0.100}, COLOR_BLUE) - , m_opponent_hp(overlay, {0.360, 0.120, 0.280, 0.005}, COLOR_BLUE) - , m_own_hp(overlay, {0.069, 0.914, 0.204, 0.006}, COLOR_BLUE) - , m_hp0(overlay, {0.073, 0.096 + 0*0.096, 0.052, 0.005}, COLOR_BLUE) - , m_hp1(overlay, {0.073, 0.096 + 1*0.096, 0.052, 0.005}, COLOR_BLUE) - , m_hp2(overlay, {0.073, 0.096 + 2*0.096, 0.052, 0.005}, COLOR_BLUE) - , m_sprite0(overlay, {0.010, 0.040 + 0*0.096, 0.052, 0.061}, COLOR_BLUE) - , m_sprite1(overlay, {0.010, 0.040 + 1*0.096, 0.052, 0.061}, COLOR_BLUE) - , m_sprite2(overlay, {0.010, 0.040 + 2*0.096, 0.052, 0.061}, COLOR_BLUE) - , m_pp0(overlay, {0.902, 0.710 - 1*0.097, 0.070, 0.063}, COLOR_BLUE) - , m_pp1(overlay, {0.902, 0.710 + 0*0.097, 0.070, 0.063}, COLOR_BLUE) - , m_pp2(overlay, {0.902, 0.710 + 1*0.097, 0.070, 0.063}, COLOR_BLUE) - , m_pp3(overlay, {0.902, 0.710 + 2*0.097, 0.070, 0.063}, COLOR_BLUE) - , m_dmax(overlay, {0.541, 0.779, 0.105, 0.186}, COLOR_BLUE) -{} - -std::set BattleMenuReader::read_opponent( - Logger& logger, CancellableScope& scope, - VideoFeed& feed -) const{ - std::set result; - - VideoSnapshot screen; - for (size_t c = 0; c < 3; c++){ - screen = feed.snapshot(); - ImageViewRGB32 image = extract_box_reference(screen, m_opponent_name); - result = read_pokemon_name(logger, m_language, m_ocr_watchdog, image); - if (!result.empty()){ - return result; - } - logger.log("Failed to read opponent name. Retrying in 1 second...", COLOR_ORANGE); - scope.wait_for(std::chrono::seconds(1)); - } -// dump_image(logger, MODULE_NAME, "MaxLair-read_opponent", screen); - return result; -} -std::set BattleMenuReader::read_opponent_in_summary(Logger& logger, const ImageViewRGB32& screen) const{ - // Start by reading the types. - PokemonType type0, type1; - { - ImageViewRGB32 types = extract_box_reference(screen, m_summary_opponent_types); - std::multimap> candidates = find_symbols(types, 0.2); - - std::string type_str = "Type Read Result:\n"; - for (const auto& item : candidates){ - type_str += " " + POKEMON_TYPE_SLUGS().get_string(item.second.first) + " : " + tostr_default(item.first ) + "\n"; - } - logger.log(type_str); - - type0 = PokemonType::NONE; - type1 = PokemonType::NONE; - { - auto iter = candidates.begin(); - if (iter != candidates.end()){ - type0 = iter->second.first; - ++iter; - } - if (iter != candidates.end()){ - type1 = iter->second.first; - ++iter; - } - } - } - - // Compile a list of all possible mons that match the type. - std::set allowed_slugs; - for (const auto& item : maxlair_slugs()){ - const MaxLairMon& mon = get_maxlair_mon(item.first); - if ((type0 == mon.type[0] && type1 == mon.type[1]) || - (type0 == mon.type[1] && type1 == mon.type[0]) - ){ - allowed_slugs.insert(item.first); - } - } - - // Special case for stunfisk-galar which changes types. - if (type1 == PokemonType::NONE){ - switch (type0){ - case PokemonType::ELECTRIC: - case PokemonType::GRASS: - case PokemonType::FAIRY: - case PokemonType::PSYCHIC: - allowed_slugs.insert("stunfisk-galar"); - break; - default:; - } - } - - if (allowed_slugs.size() == 1){ - return allowed_slugs; - } - - - // Now we read the name. - std::set name_slugs; - { - ImageViewRGB32 name = extract_box_reference(screen, m_summary_opponent_name); - - // We can use a weaker threshold here since we are cross-checking with the type. - name_slugs = read_pokemon_name(logger, m_language, m_ocr_watchdog, name, -1.0); - } - - // See if there's anything in common between the slugs that match the type - // and the slugs that match the OCR'ed name. - std::set common_slugs; - for (const std::string& slug : name_slugs){ - if (allowed_slugs.find(slug) != allowed_slugs.end()){ - common_slugs.insert(slug); - } - } - -// for (const auto& slug : allowed_slugs){ -// cout << "allowed_slugs = " << slug << endl; -// } -// for (const auto& slug : name_slugs){ -// cout << "name_slugs = " << slug << endl; -// } - - if (common_slugs.size() == 1){ - logger.log("Disambiguation succeeded: " + *common_slugs.begin(), COLOR_BLUE); - return common_slugs; - } - - - // Special case: Korean Clefairy - // Reason: Korean OCR cannot read the character: 삐 - if (m_language == Language::Korean && - name_slugs.empty() && - type0 == PokemonType::FAIRY && - type1 == PokemonType::NONE - ){ - logger.log("Known case that cannot be read: Korean Clefairy", COLOR_RED); - return {"clefairy"}; - } - - - - static std::set KNOWN_BAD_SLUGS{ - "basculin-blue-striped", - "basculin-red-striped", - "lycanroc-midday", - "lycanroc-midnight", -// "stunfisk-galar", // After using terrain pulse. - }; - bool error = true; - for (const std::string& slug : common_slugs){ - auto iter = KNOWN_BAD_SLUGS.find(slug); - if (iter != KNOWN_BAD_SLUGS.end()){ - error = false; - logger.log("Known case that cannot be disambiguated: (" + slug + ") Skipping error report.", COLOR_RED); - break; - } - } - - // At this point we're out of options. - if (error){ - dump_image(logger, MODULE_NAME, "DisambiguateBoss", screen); - } - - return common_slugs; -} -std::string BattleMenuReader::read_own_mon(Logger& logger, const ImageViewRGB32& screen) const{ - return read_pokemon_name_sprite( - logger, - m_ocr_watchdog, - screen, - m_own_sprite, - m_own_name, m_language, - false - ); -} - -double BattleMenuReader::read_opponent_hp(Logger& logger, const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_opponent_hp); -// image.save("test.png"); - -// ImageStats stats = image_stats(image); -// cout << stats.average << " - " << stats.stddev << endl; - -#if 0 - double hp = read_hp_bar(image); - logger.log("Opponent HP: " + (hp < 0 ? "?" : std::to_string(100 * hp)) + "%"); - if (hp < 0){ - dump_image(logger, screen, "BattleMenuReader-read_opponent_hp"); - } - return hp; -#endif - return read_hp_bar(logger, image); -} -double BattleMenuReader::read_own_hp(Logger& logger, const ImageViewRGB32& screen) const{ - ImageViewRGB32 image = extract_box_reference(screen, m_own_hp); -// image.save("test.png"); -#if 0 - double hp = read_hp_bar(image); - logger.log("Your HP: " + (hp < 0 ? "?" : std::to_string(100 * hp)) + "%"); - if (hp == 0){ - hp = 0.001; - } - if (hp < 0){ - dump_image(logger, screen, "BattleMenuReader-read_own_hp"); - } -#endif - return read_hp_bar(logger, image); -} -void BattleMenuReader::read_hp(Logger& logger, const ImageViewRGB32& screen, Health health[4], size_t player_index){ - Health tmp_hp[4]; - tmp_hp[0] = {read_own_hp(logger, screen), false}; - tmp_hp[1] = read_in_battle_hp_box(logger, extract_box_reference(screen, m_sprite0), extract_box_reference(screen, m_hp0)); - tmp_hp[2] = read_in_battle_hp_box(logger, extract_box_reference(screen, m_sprite1), extract_box_reference(screen, m_hp1)); - tmp_hp[3] = read_in_battle_hp_box(logger, extract_box_reference(screen, m_sprite2), extract_box_reference(screen, m_hp2)); - bool bad = false; - for (size_t c = 0; c < 4; c++){ - bad |= tmp_hp[c].hp < 0; - health[(c + player_index) % 4] = tmp_hp[c]; - } - - if (bad){ -// dump_image(logger, MODULE_NAME, "BattlePartyReader-ReadHP", screen); - } -} -void BattleMenuReader::read_own_pp(Logger& logger, const ImageViewRGB32& screen, int8_t pp[4]) const{ - pp[0] = read_pp_text(logger, extract_box_reference(screen, m_pp0)); - pp[1] = read_pp_text(logger, extract_box_reference(screen, m_pp1)); - pp[2] = read_pp_text(logger, extract_box_reference(screen, m_pp2)); - pp[3] = read_pp_text(logger, extract_box_reference(screen, m_pp3)); - if (pp[0] < 0 && pp[1] < 0 && pp[2] < 0 && pp[3] < 0){ -// dump_image(logger, MODULE_NAME, "BattleMenuReader-read_own_pp", screen); - return; - } -#if 0 - bool ok = pp[0] > 0 || pp[1] > 0 || pp[2] > 0 || pp[3] > 0; - if (ok){ - for (size_t c = 0; c < 4; c++){ - pp[c] = std::max(pp[c], (int8_t)0); - } - } -#endif -} - - -bool dmax_circle_ready(const ImageViewRGB32& image){ - size_t w = image.width(); - size_t h = image.height(); - if (w * h <= 1){ - return false; - } - - w = 200; - h = 200; - ImageRGB32 processed = image.scale_to(w, h); - if (image_stats(processed).stddev.sum() < 75){ - return false; - } -// cout << image_stats(processed).stddev.sum() << endl; - - - size_t total = 0; - FloatPixel sum; - FloatPixel sqr_sum; - for (size_t r = 0; r < h; r++){ - for (size_t c = 0; c < w; c++){ - int dy = (int)r - 100; - int dx = (int)c - 100; - if (dy < -60){ -// processed.setPixelColor(c, r, COLOR_BLUE); - continue; - } - if (-25 < dy && dy < 55){ -// processed.setPixelColor(c, r, COLOR_BLUE); - continue; - } - if (dx*dx + dy*dy < 72*72){ -// processed.setPixelColor(c, r, COLOR_BLUE); - continue; - } - if (dx*dx + dy*dy > 80*80){ -// processed.setPixelColor(c, r, COLOR_BLUE); - continue; - } - FloatPixel p(processed.pixel(c, r)); - total++; - sum += p; - sqr_sum += p * p; - } - } -// processed.save("test.png"); - -// size_t total = (size_t)w * (size_t)h; - double totalf = (double)total; - FloatPixel variance = (sqr_sum - sum*sum / totalf) / (totalf - 1); - ImageStats stats{ - sum / totalf, - FloatPixel( - std::sqrt(variance.r), - std::sqrt(variance.g), - std::sqrt(variance.b) - ), - total - }; -// cout << stats.average << stats.stddev << endl; - - if (stats.average.r < 128){ - return false; - } - return is_solid(stats, {0.684591, 0.000481775, 0.314928}, 0.15, 50); - -// ImageStats stats = image_stats(processed); -} -bool BattleMenuReader::can_dmax(const ImageViewRGB32& screen) const{ - return dmax_circle_ready(extract_box_reference(screen, m_dmax)); -} - - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} -} +/* Max Lair Detect Battle Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/CancellableScope.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/ColorClustering.h" +#include "Pokemon/Inference/Pokemon_ReadHpBar.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" +#include "PokemonSwSh_MaxLair_Detect_HPPP.h" +#include "PokemonSwSh_MaxLair_Detect_BattleMenu.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +BattleMenuDetector::BattleMenuDetector() + : VisualInferenceCallback("BattleMenuDetector") + , m_icon_fight (0.923, 0.576 + 1 * 0.1075, 0.05, 0.080) + , m_icon_pokemon(0.923, 0.576 + 2 * 0.1075, 0.05, 0.080) + , m_icon_run (0.923, 0.576 + 3 * 0.1075, 0.05, 0.080) + , m_text_fight (0.830, 0.576 + 1 * 0.1075, 0.08, 0.080) + , m_text_pokemon(0.830, 0.576 + 2 * 0.1075, 0.08, 0.080) + , m_text_run (0.830, 0.576 + 3 * 0.1075, 0.08, 0.080) + , m_icon_cheer (0.923, 0.636 + 1 * 0.1075, 0.05, 0.020) +// , m_info_left (0.907, 0.500, 0.02, 0.03) +// , m_info_right (0.970, 0.500, 0.02, 0.03) + , m_status0 (0.280, 0.870, 0.015, 0.030) + , m_status1 (0.165, 0.945, 0.100, 0.015) +{} +void BattleMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_YELLOW, m_icon_fight); + items.add(COLOR_YELLOW, m_icon_pokemon); + items.add(COLOR_YELLOW, m_icon_run); + items.add(COLOR_YELLOW, m_text_fight); + items.add(COLOR_YELLOW, m_text_pokemon); + items.add(COLOR_YELLOW, m_text_run); + items.add(COLOR_YELLOW, m_icon_cheer); + items.add(COLOR_YELLOW, m_status0); + items.add(COLOR_YELLOW, m_status1); +} +bool BattleMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + // Need 5 consecutive successful detections. + if (!detect(frame)){ + m_trigger_count = 0; + return false; + } + m_trigger_count++; + return m_trigger_count >= 5; +} + + +bool BattleMenuDetector::detect(const ImageViewRGB32& screen){ + bool fight; + + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_fight), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_fight), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + if (!fight){ +// cout << "Fight out" << endl; + return false; + } + + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_pokemon), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_pokemon), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + if (!fight){ +// cout << "Pokemon out" << endl; + return false; + } + + fight = false; + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_run), + Color(0, 0, 0), 0.1, + Color(255, 255, 255), 0.9 + ); + fight |= !fight && cluster_fit_2( + extract_box_reference(screen, m_text_run), + Color(0, 0, 0), 0.9, + Color(255, 255, 255), 0.1 + ); + if (!fight){ +// cout << "Run out" << endl; + return false; + } + +// cout << "===============" << endl; + + fight = false; + fight |= !fight && cluster_fit_2( // Not selected (red on white) + extract_box_reference(screen, m_icon_fight), + Color(255, 255, 255), 1.7, + Color(153, 75, 112), 1.0 + ); + fight |= !fight && cluster_fit_2( // Selected (red on black) + extract_box_reference(screen, m_icon_fight), + Color(0, 0, 0), 1.4, + Color(185, 6, 40), 1.0 + ); + fight |= !fight && cluster_fit_2( // Max raid Fight button is a bit different. + extract_box_reference(screen, m_icon_fight), + Color(0, 0, 0), 1.7, + Color(182, 33, 82), 1.0 + ); +// cout << "===============" << endl; + if (!fight){ + fight = cluster_fit_2( // Cheer + extract_box_reference(screen, m_icon_cheer), + Color(0, 0, 0), 1.0, + Color(9, 162, 218), 1.0, + 0.2, 60 + ); +// cout << "fight = " << fight << endl; + m_cheer = fight; + } + if (!fight){ +// cout << "Failed: m_icon_fight" << endl; + return false; + } + + bool pokemon = false; + pokemon |= !pokemon && cluster_fit_2( + extract_box_reference(screen, m_icon_pokemon), + Color(255, 255, 255), 3.1, + Color(126, 224, 142), 1.0 + ); + pokemon |= !pokemon && cluster_fit_2( + extract_box_reference(screen, m_icon_pokemon), + Color(0, 0, 0), 2.7, + Color(8, 158, 18), 1.0 + ); + if (!pokemon){ +// cout << "Failed: m_icon_pokemon" << endl; + return false; + } + + bool run = false; + run |= !run && cluster_fit_2( + extract_box_reference(screen, m_icon_run), + Color(255, 255, 255), 2.3, + Color(216, 150, 230), 1.0 + ); + run |= !run && cluster_fit_2( + extract_box_reference(screen, m_icon_run), + Color(0, 0, 0), 1.9, + Color(179, 15, 195), 1.0 + ); + if (!run){ +// cout << "Failed: m_icon_run" << endl; + return false; + } + + + // Check for white status bar in bottom left corner. + ImageStats status = image_stats(extract_box_reference(screen, m_status0)); + ImageStats health = image_stats(extract_box_reference(screen, m_status1)); +// extract_box_reference(screen, m_status1).save("test.png"); +// cout << status.average << ", " << status.stddev << endl; +// cout << health.average << ", " << health.stddev << endl; + if (is_white(status, 500, 20) && is_white(health)){ + m_dmaxed = false; + return true; + } + + // Check the semi-transparent red status bar if you're dmaxed. + if (is_solid(status, {0.618001, 0.145809, 0.23619}, 0.15, 40) && + is_solid(health, {0.615249, 0.102789, 0.281963}, 0.15, 40) + ){ + m_dmaxed = true; + return true; + } + + +// image.save("battle-menu.png"); + return false; +} + + + + +BattleMenuReader::BattleMenuReader( + VideoOverlay& overlay, + Language language, + OcrFailureWatchdog& ocr_watchdog +) + : m_language(language) + , m_ocr_watchdog(ocr_watchdog) + , m_opponent_name(overlay, {0.3, 0.010, 0.4, 0.10}, COLOR_BLUE) + , m_summary_opponent_name(overlay, {0.200, 0.100, 0.300, 0.065}, COLOR_BLUE) + , m_summary_opponent_types(overlay, {0.200, 0.170, 0.300, 0.050}, COLOR_BLUE) + , m_own_name(overlay, {0.060, 0.860, 0.160, 0.045}, COLOR_BLUE) + , m_own_sprite(overlay, {0.002, 0.860, 0.060, 0.100}, COLOR_BLUE) + , m_opponent_hp(overlay, {0.360, 0.120, 0.280, 0.005}, COLOR_BLUE) + , m_own_hp(overlay, {0.069, 0.914, 0.204, 0.006}, COLOR_BLUE) + , m_hp0(overlay, {0.073, 0.096 + 0*0.096, 0.052, 0.005}, COLOR_BLUE) + , m_hp1(overlay, {0.073, 0.096 + 1*0.096, 0.052, 0.005}, COLOR_BLUE) + , m_hp2(overlay, {0.073, 0.096 + 2*0.096, 0.052, 0.005}, COLOR_BLUE) + , m_sprite0(overlay, {0.010, 0.040 + 0*0.096, 0.052, 0.061}, COLOR_BLUE) + , m_sprite1(overlay, {0.010, 0.040 + 1*0.096, 0.052, 0.061}, COLOR_BLUE) + , m_sprite2(overlay, {0.010, 0.040 + 2*0.096, 0.052, 0.061}, COLOR_BLUE) + , m_pp0(overlay, {0.902, 0.710 - 1*0.097, 0.070, 0.063}, COLOR_BLUE) + , m_pp1(overlay, {0.902, 0.710 + 0*0.097, 0.070, 0.063}, COLOR_BLUE) + , m_pp2(overlay, {0.902, 0.710 + 1*0.097, 0.070, 0.063}, COLOR_BLUE) + , m_pp3(overlay, {0.902, 0.710 + 2*0.097, 0.070, 0.063}, COLOR_BLUE) + , m_dmax(overlay, {0.541, 0.779, 0.105, 0.186}, COLOR_BLUE) +{} + +std::set BattleMenuReader::read_opponent( + Logger& logger, CancellableScope& scope, + VideoFeed& feed +) const{ + std::set result; + + VideoSnapshot screen; + for (size_t c = 0; c < 3; c++){ + screen = feed.snapshot(); + ImageViewRGB32 image = extract_box_reference(screen, m_opponent_name); + result = read_pokemon_name(logger, m_language, m_ocr_watchdog, image); + if (!result.empty()){ + return result; + } + logger.log("Failed to read opponent name. Retrying in 1 second...", COLOR_ORANGE); + scope.wait_for(std::chrono::seconds(1)); + } +// dump_image(logger, MODULE_NAME, "MaxLair-read_opponent", screen); + return result; +} +std::set BattleMenuReader::read_opponent_in_summary(Logger& logger, const ImageViewRGB32& screen) const{ + // Start by reading the types. + PokemonType type0, type1; + { + ImageViewRGB32 types = extract_box_reference(screen, m_summary_opponent_types); + std::multimap> candidates = find_symbols(types, 0.2); + + std::string type_str = "Type Read Result:\n"; + for (const auto& item : candidates){ + type_str += " " + POKEMON_TYPE_SLUGS().get_string(item.second.first) + " : " + tostr_default(item.first ) + "\n"; + } + logger.log(type_str); + + type0 = PokemonType::NONE; + type1 = PokemonType::NONE; + { + auto iter = candidates.begin(); + if (iter != candidates.end()){ + type0 = iter->second.first; + ++iter; + } + if (iter != candidates.end()){ + type1 = iter->second.first; + ++iter; + } + } + } + + // Compile a list of all possible mons that match the type. + std::set allowed_slugs; + for (const auto& item : maxlair_slugs()){ + const MaxLairMon& mon = get_maxlair_mon(item.first); + if ((type0 == mon.type[0] && type1 == mon.type[1]) || + (type0 == mon.type[1] && type1 == mon.type[0]) + ){ + allowed_slugs.insert(item.first); + } + } + + // Special case for stunfisk-galar which changes types. + if (type1 == PokemonType::NONE){ + switch (type0){ + case PokemonType::ELECTRIC: + case PokemonType::GRASS: + case PokemonType::FAIRY: + case PokemonType::PSYCHIC: + allowed_slugs.insert("stunfisk-galar"); + break; + default:; + } + } + + if (allowed_slugs.size() == 1){ + return allowed_slugs; + } + + + // Now we read the name. + std::set name_slugs; + { + ImageViewRGB32 name = extract_box_reference(screen, m_summary_opponent_name); + + // We can use a weaker threshold here since we are cross-checking with the type. + name_slugs = read_pokemon_name(logger, m_language, m_ocr_watchdog, name, -1.0); + } + + // See if there's anything in common between the slugs that match the type + // and the slugs that match the OCR'ed name. + std::set common_slugs; + for (const std::string& slug : name_slugs){ + if (allowed_slugs.find(slug) != allowed_slugs.end()){ + common_slugs.insert(slug); + } + } + +// for (const auto& slug : allowed_slugs){ +// cout << "allowed_slugs = " << slug << endl; +// } +// for (const auto& slug : name_slugs){ +// cout << "name_slugs = " << slug << endl; +// } + + if (common_slugs.size() == 1){ + logger.log("Disambiguation succeeded: " + *common_slugs.begin(), COLOR_BLUE); + return common_slugs; + } + + + // Special case: Korean Clefairy + // Reason: Korean OCR cannot read the character: 삐 + if (m_language == Language::Korean && + name_slugs.empty() && + type0 == PokemonType::FAIRY && + type1 == PokemonType::NONE + ){ + logger.log("Known case that cannot be read: Korean Clefairy", COLOR_RED); + return {"clefairy"}; + } + + + + static std::set KNOWN_BAD_SLUGS{ + "basculin-blue-striped", + "basculin-red-striped", + "lycanroc-midday", + "lycanroc-midnight", +// "stunfisk-galar", // After using terrain pulse. + }; + bool error = true; + for (const std::string& slug : common_slugs){ + auto iter = KNOWN_BAD_SLUGS.find(slug); + if (iter != KNOWN_BAD_SLUGS.end()){ + error = false; + logger.log("Known case that cannot be disambiguated: (" + slug + ") Skipping error report.", COLOR_RED); + break; + } + } + + // At this point we're out of options. + if (error){ + dump_image(logger, MODULE_NAME, "DisambiguateBoss", screen); + } + + return common_slugs; +} +std::string BattleMenuReader::read_own_mon(Logger& logger, const ImageViewRGB32& screen) const{ + return read_pokemon_name_sprite( + logger, + m_ocr_watchdog, + screen, + m_own_sprite, + m_own_name, m_language, + false + ); +} + +double BattleMenuReader::read_opponent_hp(Logger& logger, const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_opponent_hp); +// image.save("test.png"); + +// ImageStats stats = image_stats(image); +// cout << stats.average << " - " << stats.stddev << endl; + +#if 0 + double hp = read_hp_bar(image); + logger.log("Opponent HP: " + (hp < 0 ? "?" : std::to_string(100 * hp)) + "%"); + if (hp < 0){ + dump_image(logger, screen, "BattleMenuReader-read_opponent_hp"); + } + return hp; +#endif + return read_hp_bar(logger, image); +} +double BattleMenuReader::read_own_hp(Logger& logger, const ImageViewRGB32& screen) const{ + ImageViewRGB32 image = extract_box_reference(screen, m_own_hp); +// image.save("test.png"); +#if 0 + double hp = read_hp_bar(image); + logger.log("Your HP: " + (hp < 0 ? "?" : std::to_string(100 * hp)) + "%"); + if (hp == 0){ + hp = 0.001; + } + if (hp < 0){ + dump_image(logger, screen, "BattleMenuReader-read_own_hp"); + } +#endif + return read_hp_bar(logger, image); +} +void BattleMenuReader::read_hp(Logger& logger, const ImageViewRGB32& screen, Health health[4], size_t player_index){ + Health tmp_hp[4]; + tmp_hp[0] = {read_own_hp(logger, screen), false}; + tmp_hp[1] = read_in_battle_hp_box(logger, extract_box_reference(screen, m_sprite0), extract_box_reference(screen, m_hp0)); + tmp_hp[2] = read_in_battle_hp_box(logger, extract_box_reference(screen, m_sprite1), extract_box_reference(screen, m_hp1)); + tmp_hp[3] = read_in_battle_hp_box(logger, extract_box_reference(screen, m_sprite2), extract_box_reference(screen, m_hp2)); + bool bad = false; + for (size_t c = 0; c < 4; c++){ + bad |= tmp_hp[c].hp < 0; + health[(c + player_index) % 4] = tmp_hp[c]; + } + + if (bad){ +// dump_image(logger, MODULE_NAME, "BattlePartyReader-ReadHP", screen); + } +} +void BattleMenuReader::read_own_pp(Logger& logger, const ImageViewRGB32& screen, int8_t pp[4]) const{ + pp[0] = read_pp_text(logger, extract_box_reference(screen, m_pp0)); + pp[1] = read_pp_text(logger, extract_box_reference(screen, m_pp1)); + pp[2] = read_pp_text(logger, extract_box_reference(screen, m_pp2)); + pp[3] = read_pp_text(logger, extract_box_reference(screen, m_pp3)); + if (pp[0] < 0 && pp[1] < 0 && pp[2] < 0 && pp[3] < 0){ +// dump_image(logger, MODULE_NAME, "BattleMenuReader-read_own_pp", screen); + return; + } +#if 0 + bool ok = pp[0] > 0 || pp[1] > 0 || pp[2] > 0 || pp[3] > 0; + if (ok){ + for (size_t c = 0; c < 4; c++){ + pp[c] = std::max(pp[c], (int8_t)0); + } + } +#endif +} + + +bool dmax_circle_ready(const ImageViewRGB32& image){ + size_t w = image.width(); + size_t h = image.height(); + if (w * h <= 1){ + return false; + } + + w = 200; + h = 200; + ImageRGB32 processed = image.scale_to(w, h); + if (image_stats(processed).stddev.sum() < 75){ + return false; + } +// cout << image_stats(processed).stddev.sum() << endl; + + + size_t total = 0; + FloatPixel sum; + FloatPixel sqr_sum; + for (size_t r = 0; r < h; r++){ + for (size_t c = 0; c < w; c++){ + int dy = (int)r - 100; + int dx = (int)c - 100; + if (dy < -60){ +// processed.setPixelColor(c, r, COLOR_BLUE); + continue; + } + if (-25 < dy && dy < 55){ +// processed.setPixelColor(c, r, COLOR_BLUE); + continue; + } + if (dx*dx + dy*dy < 72*72){ +// processed.setPixelColor(c, r, COLOR_BLUE); + continue; + } + if (dx*dx + dy*dy > 80*80){ +// processed.setPixelColor(c, r, COLOR_BLUE); + continue; + } + FloatPixel p(processed.pixel(c, r)); + total++; + sum += p; + sqr_sum += p * p; + } + } +// processed.save("test.png"); + +// size_t total = (size_t)w * (size_t)h; + double totalf = (double)total; + FloatPixel variance = (sqr_sum - sum*sum / totalf) / (totalf - 1); + ImageStats stats{ + sum / totalf, + FloatPixel( + std::sqrt(variance.r), + std::sqrt(variance.g), + std::sqrt(variance.b) + ), + total + }; +// cout << stats.average << stats.stddev << endl; + + if (stats.average.r < 128){ + return false; + } + return is_solid(stats, {0.684591, 0.000481775, 0.314928}, 0.15, 50); + +// ImageStats stats = image_stats(processed); +} +bool BattleMenuReader::can_dmax(const ImageViewRGB32& screen) const{ + return dmax_circle_ready(extract_box_reference(screen, m_dmax)); +} + + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h index bb79aca5b4..f93c7b9fbc 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h @@ -1,113 +1,113 @@ -/* Max Lair Detect Battle Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_BattleMenu_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_BattleMenu_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Logging/Logger.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/FailureWatchdog.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ - class CancellableScope; - class VideoFeed; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class BattleMenuDetector : public VisualInferenceCallback{ -public: - BattleMenuDetector(); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - bool dmaxed() const{ return m_dmaxed; } - bool cheer() const{ return m_cheer; } - - -private: - ImageFloatBox m_icon_fight; - ImageFloatBox m_icon_pokemon; - ImageFloatBox m_icon_run; - ImageFloatBox m_text_fight; - ImageFloatBox m_text_pokemon; - ImageFloatBox m_text_run; - ImageFloatBox m_icon_cheer; // Specific for Italian -// ImageFloatBox m_info_left; -// ImageFloatBox m_info_right; - ImageFloatBox m_status0; - ImageFloatBox m_status1; - - size_t m_trigger_count = 0; - bool m_dmaxed = false; - bool m_cheer = false; -}; - - - -class BattleMenuReader{ -public: - BattleMenuReader( - VideoOverlay& overlay, - Language language, - OcrFailureWatchdog& ocr_watchdog - ); - - std::set read_opponent( - Logger& logger, CancellableScope& scope, - VideoFeed& feed - ) const; - std::set read_opponent_in_summary(Logger& logger, const ImageViewRGB32& screen) const; - - std::string read_own_mon(Logger& logger, const ImageViewRGB32& screen) const; - - double read_opponent_hp(Logger& logger, const ImageViewRGB32& screen) const; - double read_own_hp(Logger& logger, const ImageViewRGB32& screen) const; - void read_hp(Logger& logger, const ImageViewRGB32& screen, Health health[4], size_t player_index); - void read_own_pp(Logger& logger, const ImageViewRGB32& screen, int8_t pp[4]) const; - bool can_dmax(const ImageViewRGB32& screen) const; - -private: - Language m_language; - OcrFailureWatchdog& m_ocr_watchdog; - OverlayBoxScope m_opponent_name; - OverlayBoxScope m_summary_opponent_name; - OverlayBoxScope m_summary_opponent_types; - - OverlayBoxScope m_own_name; - OverlayBoxScope m_own_sprite; - - OverlayBoxScope m_opponent_hp; - OverlayBoxScope m_own_hp; - - OverlayBoxScope m_hp0; - OverlayBoxScope m_hp1; - OverlayBoxScope m_hp2; - OverlayBoxScope m_sprite0; - OverlayBoxScope m_sprite1; - OverlayBoxScope m_sprite2; - - OverlayBoxScope m_pp0; - OverlayBoxScope m_pp1; - OverlayBoxScope m_pp2; - OverlayBoxScope m_pp3; - OverlayBoxScope m_dmax; -}; - - - -} -} -} -} -#endif +/* Max Lair Detect Battle Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_BattleMenu_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_BattleMenu_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Logging/Logger.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/FailureWatchdog.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ + class CancellableScope; + class VideoFeed; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class BattleMenuDetector : public VisualInferenceCallback{ +public: + BattleMenuDetector(); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + bool dmaxed() const{ return m_dmaxed; } + bool cheer() const{ return m_cheer; } + + +private: + ImageFloatBox m_icon_fight; + ImageFloatBox m_icon_pokemon; + ImageFloatBox m_icon_run; + ImageFloatBox m_text_fight; + ImageFloatBox m_text_pokemon; + ImageFloatBox m_text_run; + ImageFloatBox m_icon_cheer; // Specific for Italian +// ImageFloatBox m_info_left; +// ImageFloatBox m_info_right; + ImageFloatBox m_status0; + ImageFloatBox m_status1; + + size_t m_trigger_count = 0; + bool m_dmaxed = false; + bool m_cheer = false; +}; + + + +class BattleMenuReader{ +public: + BattleMenuReader( + VideoOverlay& overlay, + Language language, + OcrFailureWatchdog& ocr_watchdog + ); + + std::set read_opponent( + Logger& logger, CancellableScope& scope, + VideoFeed& feed + ) const; + std::set read_opponent_in_summary(Logger& logger, const ImageViewRGB32& screen) const; + + std::string read_own_mon(Logger& logger, const ImageViewRGB32& screen) const; + + double read_opponent_hp(Logger& logger, const ImageViewRGB32& screen) const; + double read_own_hp(Logger& logger, const ImageViewRGB32& screen) const; + void read_hp(Logger& logger, const ImageViewRGB32& screen, Health health[4], size_t player_index); + void read_own_pp(Logger& logger, const ImageViewRGB32& screen, int8_t pp[4]) const; + bool can_dmax(const ImageViewRGB32& screen) const; + +private: + Language m_language; + OcrFailureWatchdog& m_ocr_watchdog; + OverlayBoxScope m_opponent_name; + OverlayBoxScope m_summary_opponent_name; + OverlayBoxScope m_summary_opponent_types; + + OverlayBoxScope m_own_name; + OverlayBoxScope m_own_sprite; + + OverlayBoxScope m_opponent_hp; + OverlayBoxScope m_own_hp; + + OverlayBoxScope m_hp0; + OverlayBoxScope m_hp1; + OverlayBoxScope m_hp2; + OverlayBoxScope m_sprite0; + OverlayBoxScope m_sprite1; + OverlayBoxScope m_sprite2; + + OverlayBoxScope m_pp0; + OverlayBoxScope m_pp1; + OverlayBoxScope m_pp2; + OverlayBoxScope m_pp3; + OverlayBoxScope m_dmax; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.cpp index 760552ce53..c53ccc5ca6 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.cpp @@ -1,133 +1,133 @@ -/* Max Lair Detect Battle Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_MaxLair_Detect_EndBattle.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -PokemonCaughtMenuDetector::PokemonCaughtMenuDetector() - : VisualInferenceCallback("PokemonCaughtMenuDetector") - , m_top_white(0.550, 0.020, 0.400, 0.020) - , m_caught_left(0.500, 0.080, 0.050, 0.070) - , m_caught_right(0.930, 0.080, 0.050, 0.070) - , m_middle_pink(0.930, 0.300, 0.050, 0.200) - , m_bottom_white(0.550, 0.900, 0.400, 0.020) - , m_bottom_black(0.100, 0.970, 0.600, 0.020) - , m_bottom_options(0.920, 0.970, 0.070, 0.020) -{} -void PokemonCaughtMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_MAGENTA, m_top_white); - items.add(COLOR_MAGENTA, m_caught_left); - items.add(COLOR_MAGENTA, m_caught_right); - items.add(COLOR_MAGENTA, m_middle_pink); - items.add(COLOR_MAGENTA, m_bottom_white); - items.add(COLOR_MAGENTA, m_bottom_black); - items.add(COLOR_MAGENTA, m_bottom_options); -} -bool PokemonCaughtMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - - -bool PokemonCaughtMenuDetector::detect(const ImageViewRGB32& screen){ - ImageStats top_white = image_stats(extract_box_reference(screen, m_top_white)); -// cout << top_white.average << ", " << top_white.stddev << endl; - if (!is_solid(top_white, {0.316068, 0.341966, 0.341966})){ -// cout << "Failed: m_top_white" << endl; - return false; - } - ImageStats caught_left = image_stats(extract_box_reference(screen, m_caught_left)); - if (!is_black(caught_left)){ -// cout << "Failed: m_caught_left" << endl; - return false; - } - ImageStats caught_right = image_stats(extract_box_reference(screen, m_caught_right)); - if (!is_black(caught_right)){ -// cout << "Failed: m_caught_right" << endl; - return false; - } - if (euclidean_distance(caught_left.average, caught_right.average) > 10){ -// cout << "Bad left/right distance." << endl; - return false; - } - ImageStats middle_pink = image_stats(extract_box_reference(screen, m_middle_pink)); - if (!is_solid(middle_pink, {0.485975, 0.0980567, 0.415969})){ -// cout << middle_pink.average << ", " << middle_pink.stddev << endl; -// cout << "Failed: m_middle_pink" << endl; - return false; - } - ImageStats bottom_white = image_stats(extract_box_reference(screen, m_bottom_white)); -// cout << bottom_white.average << ", " << bottom_white.stddev << endl; - if (!is_solid(bottom_white, {0.331264, 0.332167, 0.336569}, 0.1, 20)){ - return false; - } - ImageStats bottom_black = image_stats(extract_box_reference(screen, m_bottom_black)); - if (!is_black(bottom_black)){ - return false; - } - ImageStats bottom_options = image_stats(extract_box_reference(screen, m_bottom_options)); - if (bottom_options.stddev.sum() < 30){ - return false; - } - - return true; -} - - - -size_t count_catches(VideoOverlay& overlay, const ImageViewRGB32& screen){ - OverlayBoxScope box0(overlay, {0.780, 0.400 + 0*0.133, 0.030, 0.030}, COLOR_BLUE); - OverlayBoxScope box1(overlay, {0.780, 0.400 + 1*0.133, 0.030, 0.030}, COLOR_BLUE); - OverlayBoxScope box2(overlay, {0.780, 0.400 + 2*0.133, 0.030, 0.030}, COLOR_BLUE); - OverlayBoxScope box3(overlay, {0.780, 0.400 + 3*0.133, 0.030, 0.030}, COLOR_BLUE); - - size_t count = 0; - if (is_black(image_stats(extract_box_reference(screen, box0)))){ - count++; - } - if (is_white(image_stats(extract_box_reference(screen, box1)))){ - count++; - } - if (is_white(image_stats(extract_box_reference(screen, box2)))){ - count++; - } - if (is_white(image_stats(extract_box_reference(screen, box3)))){ - count++; - } - - return count; -} - - - - - - - - - - - - - - - - - -} -} -} -} +/* Max Lair Detect Battle Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_MaxLair_Detect_EndBattle.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +PokemonCaughtMenuDetector::PokemonCaughtMenuDetector() + : VisualInferenceCallback("PokemonCaughtMenuDetector") + , m_top_white(0.550, 0.020, 0.400, 0.020) + , m_caught_left(0.500, 0.080, 0.050, 0.070) + , m_caught_right(0.930, 0.080, 0.050, 0.070) + , m_middle_pink(0.930, 0.300, 0.050, 0.200) + , m_bottom_white(0.550, 0.900, 0.400, 0.020) + , m_bottom_black(0.100, 0.970, 0.600, 0.020) + , m_bottom_options(0.920, 0.970, 0.070, 0.020) +{} +void PokemonCaughtMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_MAGENTA, m_top_white); + items.add(COLOR_MAGENTA, m_caught_left); + items.add(COLOR_MAGENTA, m_caught_right); + items.add(COLOR_MAGENTA, m_middle_pink); + items.add(COLOR_MAGENTA, m_bottom_white); + items.add(COLOR_MAGENTA, m_bottom_black); + items.add(COLOR_MAGENTA, m_bottom_options); +} +bool PokemonCaughtMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + + +bool PokemonCaughtMenuDetector::detect(const ImageViewRGB32& screen){ + ImageStats top_white = image_stats(extract_box_reference(screen, m_top_white)); +// cout << top_white.average << ", " << top_white.stddev << endl; + if (!is_solid(top_white, {0.316068, 0.341966, 0.341966})){ +// cout << "Failed: m_top_white" << endl; + return false; + } + ImageStats caught_left = image_stats(extract_box_reference(screen, m_caught_left)); + if (!is_black(caught_left)){ +// cout << "Failed: m_caught_left" << endl; + return false; + } + ImageStats caught_right = image_stats(extract_box_reference(screen, m_caught_right)); + if (!is_black(caught_right)){ +// cout << "Failed: m_caught_right" << endl; + return false; + } + if (euclidean_distance(caught_left.average, caught_right.average) > 10){ +// cout << "Bad left/right distance." << endl; + return false; + } + ImageStats middle_pink = image_stats(extract_box_reference(screen, m_middle_pink)); + if (!is_solid(middle_pink, {0.485975, 0.0980567, 0.415969})){ +// cout << middle_pink.average << ", " << middle_pink.stddev << endl; +// cout << "Failed: m_middle_pink" << endl; + return false; + } + ImageStats bottom_white = image_stats(extract_box_reference(screen, m_bottom_white)); +// cout << bottom_white.average << ", " << bottom_white.stddev << endl; + if (!is_solid(bottom_white, {0.331264, 0.332167, 0.336569}, 0.1, 20)){ + return false; + } + ImageStats bottom_black = image_stats(extract_box_reference(screen, m_bottom_black)); + if (!is_black(bottom_black)){ + return false; + } + ImageStats bottom_options = image_stats(extract_box_reference(screen, m_bottom_options)); + if (bottom_options.stddev.sum() < 30){ + return false; + } + + return true; +} + + + +size_t count_catches(VideoOverlay& overlay, const ImageViewRGB32& screen){ + OverlayBoxScope box0(overlay, {0.780, 0.400 + 0*0.133, 0.030, 0.030}, COLOR_BLUE); + OverlayBoxScope box1(overlay, {0.780, 0.400 + 1*0.133, 0.030, 0.030}, COLOR_BLUE); + OverlayBoxScope box2(overlay, {0.780, 0.400 + 2*0.133, 0.030, 0.030}, COLOR_BLUE); + OverlayBoxScope box3(overlay, {0.780, 0.400 + 3*0.133, 0.030, 0.030}, COLOR_BLUE); + + size_t count = 0; + if (is_black(image_stats(extract_box_reference(screen, box0)))){ + count++; + } + if (is_white(image_stats(extract_box_reference(screen, box1)))){ + count++; + } + if (is_white(image_stats(extract_box_reference(screen, box2)))){ + count++; + } + if (is_white(image_stats(extract_box_reference(screen, box3)))){ + count++; + } + + return count; +} + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h index 1203428f99..c854a29b31 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_EndBattle.h @@ -1,53 +1,53 @@ -/* Max Lair Detect End Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_EndBattle_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_EndBattle_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - class VideoOverlay; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class PokemonCaughtMenuDetector : public VisualInferenceCallback{ -public: - PokemonCaughtMenuDetector(); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - ImageFloatBox m_top_white; - ImageFloatBox m_caught_left; - ImageFloatBox m_caught_right; - ImageFloatBox m_middle_pink; - ImageFloatBox m_bottom_white; - ImageFloatBox m_bottom_black; - ImageFloatBox m_bottom_options; - -}; - - - - -size_t count_catches(VideoOverlay& overlay, const ImageViewRGB32& screen); - - - - -} -} -} -} -#endif +/* Max Lair Detect End Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_EndBattle_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_EndBattle_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + class VideoOverlay; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class PokemonCaughtMenuDetector : public VisualInferenceCallback{ +public: + PokemonCaughtMenuDetector(); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + ImageFloatBox m_top_white; + ImageFloatBox m_caught_left; + ImageFloatBox m_caught_right; + ImageFloatBox m_middle_pink; + ImageFloatBox m_bottom_white; + ImageFloatBox m_bottom_black; + ImageFloatBox m_bottom_options; + +}; + + + + +size_t count_catches(VideoOverlay& overlay, const ImageViewRGB32& screen); + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.cpp index 4dc758854a..34c4fe4e5b 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.cpp @@ -1,58 +1,58 @@ -/* Max Lair Detect Entrance - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "PokemonSwSh_MaxLair_Detect_Entrance.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -EntranceDetector::EntranceDetector(const ImageViewRGB32& entrance_screen) - : VisualInferenceCallback("EntranceDetector") - , m_box0(0.020, 0.020, 0.500, 0.750) - , m_watch_box(extract_box_reference(entrance_screen, m_box0)) -{} -void EntranceDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_DARKGREEN, m_box0); -} -bool EntranceDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -bool EntranceDetector::detect(const ImageViewRGB32& screen){ - if (!screen){ - return false; - } - - ImageRGB32 copy; - - ImageViewRGB32 image = extract_box_reference(screen, m_box0); - if (image.width() != (size_t)m_watch_box.width() || image.height() != (size_t)m_watch_box.height()){ - copy = image.scale_to(m_watch_box.width(), m_watch_box.height()); - image = copy; - } - - double diff = ImageMatch::pixel_RMSD(m_watch_box, image); -// cout << diff << endl; - - return diff < 20; -} - - - -} -} -} -} +/* Max Lair Detect Entrance + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "PokemonSwSh_MaxLair_Detect_Entrance.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +EntranceDetector::EntranceDetector(const ImageViewRGB32& entrance_screen) + : VisualInferenceCallback("EntranceDetector") + , m_box0(0.020, 0.020, 0.500, 0.750) + , m_watch_box(extract_box_reference(entrance_screen, m_box0)) +{} +void EntranceDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_DARKGREEN, m_box0); +} +bool EntranceDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +bool EntranceDetector::detect(const ImageViewRGB32& screen){ + if (!screen){ + return false; + } + + ImageRGB32 copy; + + ImageViewRGB32 image = extract_box_reference(screen, m_box0); + if (image.width() != (size_t)m_watch_box.width() || image.height() != (size_t)m_watch_box.height()){ + copy = image.scale_to(m_watch_box.width(), m_watch_box.height()); + image = copy; + } + + double diff = ImageMatch::pixel_RMSD(m_watch_box, image); +// cout << diff << endl; + + return diff < 20; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h index fda5041505..63ee836376 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h @@ -1,42 +1,42 @@ -/* Max Lair Detect Entrance - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_Entrance_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_Entrance_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class EntranceDetector : public VisualInferenceCallback{ -public: - EntranceDetector(const ImageViewRGB32& entrance_screen); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - ImageFloatBox m_box0; - ImageViewRGB32 m_watch_box; - std::shared_ptr m_entrance_screen; -}; - - - -} -} -} -} -#endif +/* Max Lair Detect Entrance + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_Entrance_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_Entrance_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class EntranceDetector : public VisualInferenceCallback{ +public: + EntranceDetector(const ImageViewRGB32& entrance_screen); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + ImageFloatBox m_box0; + ImageViewRGB32 m_watch_box; + std::shared_ptr m_entrance_screen; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.cpp index 7ef51f2af9..53ba84ba40 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.cpp @@ -1,213 +1,213 @@ -/* Max Lair Detect PP - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Qt/StringToolsQt.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/OCR/OCR_StringNormalization.h" -#include "CommonTools/OCR/OCR_RawOCR.h" -#include "Pokemon/Inference/Pokemon_ReadHpBar.h" -#include "PokemonSwSh_MaxLair_Detect_HPPP.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -Health read_in_battle_hp_box(Logger& logger, const ImageViewRGB32& sprite, const ImageViewRGB32& hp_bar){ - ImageStats stats = image_stats(sprite); -// cout << stats.average << stats.stddev << endl; - if (is_solid(stats, {0., 0.389943, 0.610057})){ - logger.log("HP Read: Dead", COLOR_BLUE); - return {0, 1}; - } - double hp = read_hp_bar(logger, hp_bar); - if (hp == 0){ - return {0, -1}; - } - return {hp, 0}; -} - - - - - - -int8_t parse_pp(const std::string& current, const std::string& total){ -// cout << current << " " << total << endl; - if (total[0] == '0'){ - return -1; - } - uint32_t num_current = atoi(current.c_str()); - uint32_t num_total = atoi(total.c_str()); - if (num_current > num_total){ - return -1; - } - if (num_current > 64 || num_total > 64){ - return -1; - } - if (num_total == 1){ - return (int8_t)num_current; - } - if (num_total % 5 != 0){ - return -1; - } - return (int8_t)num_current; -} -int8_t parse_pp(const std::string& str){ - // Clean up and split into tokens deliminated by '/'. - std::vector tokens; - tokens.emplace_back(); - for (char ch : str){ - if (ch <= 32){ - continue; - } - if ('0' <= ch && ch <= '9'){ - tokens.back() += ch; - continue; - } - if (ch == 'o' || ch == 'O'){ - tokens.back() += '0'; - continue; - } - if (ch == 'A'){ - tokens.back() += '4'; - continue; - } - if (ch == '/'){ - tokens.emplace_back(); - continue; - } - } - - if (tokens.size() > 2){ - return -1; - } - if (tokens.size() == 2){ - return parse_pp(tokens[0], tokens[1]); - } - - const std::string& value = tokens[0]; - if (value.empty()){ - return 0; - } - - for (size_t c = value.size(); c > 1;){ - char ch = value[--c]; - if (ch != '1' && ch != '7'){ - continue; - } - int8_t val = parse_pp( - value.substr(0, c), - value.substr(c + 1) - ); - if (val >= 0){ - return val; - } - val = parse_pp( - value.substr(0, c), - value.substr(c) - ); - if (val >= 0){ - return val; - } - } - - return -1; -} - -int8_t read_pp_text(Logger& logger, const ImageViewRGB32& image){ - if (image.width() == 0 || image.height() == 0){ - return -1; - } - - std::vector> filters{ - {0xff000000, 0xff404040}, - {0xff808080, 0xffffffff}, - }; - bool ok = false; - ImageRGB32 processed; -// cout << "============" << endl; - for (const auto& item : filters){ - size_t text_pixels; - processed = to_blackwhite_rgb32_range( - text_pixels, image, - false, - item.first, item.second - ); - double text_ratio = 1.0 - (double)text_pixels / (image.width() * image.height()); -// cout << "text_ratio = " << text_ratio << endl; - if (0.02 <= text_ratio && text_ratio <= 0.50){ - ok = true; - break; - } - } - if (!ok){ - logger.log("OCR Result: Invalid text ratio.", COLOR_RED); - return -1; - } - - - std::string ocr_text = OCR::ocr_read(Language::English, processed); - - ocr_text = to_utf8(OCR::run_character_reductions(to_utf32(ocr_text))); - int8_t pp = parse_pp(ocr_text); - - std::string str; - str += "OCR Result: \""; - for (char ch : ocr_text){ - if (ch != '\r' && ch != '\n'){ - str += ch; - } - } - str += "\" -> ("; - str += pp < 0 ? "? PP)" : std::to_string((int)pp) + " PP)"; - logger.log(str, pp < 0 ? COLOR_RED : COLOR_BLUE); - - return pp; -} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} -} +/* Max Lair Detect PP + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Qt/StringToolsQt.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/OCR/OCR_StringNormalization.h" +#include "CommonTools/OCR/OCR_RawOCR.h" +#include "Pokemon/Inference/Pokemon_ReadHpBar.h" +#include "PokemonSwSh_MaxLair_Detect_HPPP.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +Health read_in_battle_hp_box(Logger& logger, const ImageViewRGB32& sprite, const ImageViewRGB32& hp_bar){ + ImageStats stats = image_stats(sprite); +// cout << stats.average << stats.stddev << endl; + if (is_solid(stats, {0., 0.389943, 0.610057})){ + logger.log("HP Read: Dead", COLOR_BLUE); + return {0, 1}; + } + double hp = read_hp_bar(logger, hp_bar); + if (hp == 0){ + return {0, -1}; + } + return {hp, 0}; +} + + + + + + +int8_t parse_pp(const std::string& current, const std::string& total){ +// cout << current << " " << total << endl; + if (total[0] == '0'){ + return -1; + } + uint32_t num_current = atoi(current.c_str()); + uint32_t num_total = atoi(total.c_str()); + if (num_current > num_total){ + return -1; + } + if (num_current > 64 || num_total > 64){ + return -1; + } + if (num_total == 1){ + return (int8_t)num_current; + } + if (num_total % 5 != 0){ + return -1; + } + return (int8_t)num_current; +} +int8_t parse_pp(const std::string& str){ + // Clean up and split into tokens deliminated by '/'. + std::vector tokens; + tokens.emplace_back(); + for (char ch : str){ + if (ch <= 32){ + continue; + } + if ('0' <= ch && ch <= '9'){ + tokens.back() += ch; + continue; + } + if (ch == 'o' || ch == 'O'){ + tokens.back() += '0'; + continue; + } + if (ch == 'A'){ + tokens.back() += '4'; + continue; + } + if (ch == '/'){ + tokens.emplace_back(); + continue; + } + } + + if (tokens.size() > 2){ + return -1; + } + if (tokens.size() == 2){ + return parse_pp(tokens[0], tokens[1]); + } + + const std::string& value = tokens[0]; + if (value.empty()){ + return 0; + } + + for (size_t c = value.size(); c > 1;){ + char ch = value[--c]; + if (ch != '1' && ch != '7'){ + continue; + } + int8_t val = parse_pp( + value.substr(0, c), + value.substr(c + 1) + ); + if (val >= 0){ + return val; + } + val = parse_pp( + value.substr(0, c), + value.substr(c) + ); + if (val >= 0){ + return val; + } + } + + return -1; +} + +int8_t read_pp_text(Logger& logger, const ImageViewRGB32& image){ + if (image.width() == 0 || image.height() == 0){ + return -1; + } + + std::vector> filters{ + {0xff000000, 0xff404040}, + {0xff808080, 0xffffffff}, + }; + bool ok = false; + ImageRGB32 processed; +// cout << "============" << endl; + for (const auto& item : filters){ + size_t text_pixels; + processed = to_blackwhite_rgb32_range( + text_pixels, image, + false, + item.first, item.second + ); + double text_ratio = 1.0 - (double)text_pixels / (image.width() * image.height()); +// cout << "text_ratio = " << text_ratio << endl; + if (0.02 <= text_ratio && text_ratio <= 0.50){ + ok = true; + break; + } + } + if (!ok){ + logger.log("OCR Result: Invalid text ratio.", COLOR_RED); + return -1; + } + + + std::string ocr_text = OCR::ocr_read(Language::English, processed); + + ocr_text = to_utf8(OCR::run_character_reductions(to_utf32(ocr_text))); + int8_t pp = parse_pp(ocr_text); + + std::string str; + str += "OCR Result: \""; + for (char ch : ocr_text){ + if (ch != '\r' && ch != '\n'){ + str += ch; + } + } + str += "\" -> ("; + str += pp < 0 ? "? PP)" : std::to_string((int)pp) + " PP)"; + logger.log(str, pp < 0 ? COLOR_RED : COLOR_BLUE); + + return pp; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h index 6093878f0d..3a12ad6cf1 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h @@ -1,31 +1,31 @@ -/* Max Lair Detect HP and PP - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_HPPP_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_HPPP_H - -#include -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ - class Logger; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -//double read_hp_bar(Logger& logger, const ImageViewRGB32& image); -Health read_in_battle_hp_box(Logger& logger, const ImageViewRGB32& sprite, const ImageViewRGB32& hp_bar); -int8_t read_pp_text(Logger& logger, const ImageViewRGB32& image); - - -} -} -} -} -#endif +/* Max Lair Detect HP and PP + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_HPPP_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_HPPP_H + +#include +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ + class Logger; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +//double read_hp_bar(Logger& logger, const ImageViewRGB32& image); +Health read_in_battle_hp_box(Logger& logger, const ImageViewRGB32& sprite, const ImageViewRGB32& hp_bar); +int8_t read_pp_text(Logger& logger, const ImageViewRGB32& image); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.cpp index 0691c9cfe6..f3500a6d77 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.cpp @@ -1,57 +1,57 @@ -/* Max Lair Detect Item Select Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -ItemSelectDetector::ItemSelectDetector(bool stop_no_detect) - : VisualInferenceCallback("ItemSelectDetector") - , m_stop_on_no_detect(stop_no_detect) - , m_bottom_main(0.100, 0.970, 0.600, 0.020) - , m_bottom_right(0.920, 0.970, 0.070, 0.020) - , m_blue(0.600, 0.020, 0.200, 0.060) -{} -void ItemSelectDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_BLUE, m_bottom_main); - items.add(COLOR_BLUE, m_bottom_right); - items.add(COLOR_BLUE, m_blue); -} -bool ItemSelectDetector::detect(const ImageViewRGB32& screen) const{ - ImageStats bottom_main = image_stats(extract_box_reference(screen, m_bottom_main)); -// cout << bottom_main.average << ", " << bottom_main.stddev << endl; - if (!is_black(bottom_main)){ - return false; - } - ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << bottom_right.average << ", " << bottom_right.stddev << endl; - if (bottom_right.stddev.sum() < 30){ - return false; - } - ImageStats blue = image_stats(extract_box_reference(screen, m_blue)); -// cout << blue.average << ", " << blue.stddev << endl; - if (!is_solid(blue, {0.0286572, 0.40799, 0.563353})){ - return false; - } - return true; -} -bool ItemSelectDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return m_stop_on_no_detect - ? !detect(frame) - : detect(frame); -} - - -} -} -} -} +/* Max Lair Detect Item Select Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +ItemSelectDetector::ItemSelectDetector(bool stop_no_detect) + : VisualInferenceCallback("ItemSelectDetector") + , m_stop_on_no_detect(stop_no_detect) + , m_bottom_main(0.100, 0.970, 0.600, 0.020) + , m_bottom_right(0.920, 0.970, 0.070, 0.020) + , m_blue(0.600, 0.020, 0.200, 0.060) +{} +void ItemSelectDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_BLUE, m_bottom_main); + items.add(COLOR_BLUE, m_bottom_right); + items.add(COLOR_BLUE, m_blue); +} +bool ItemSelectDetector::detect(const ImageViewRGB32& screen) const{ + ImageStats bottom_main = image_stats(extract_box_reference(screen, m_bottom_main)); +// cout << bottom_main.average << ", " << bottom_main.stddev << endl; + if (!is_black(bottom_main)){ + return false; + } + ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << bottom_right.average << ", " << bottom_right.stddev << endl; + if (bottom_right.stddev.sum() < 30){ + return false; + } + ImageStats blue = image_stats(extract_box_reference(screen, m_blue)); +// cout << blue.average << ", " << blue.stddev << endl; + if (!is_solid(blue, {0.0286572, 0.40799, 0.563353})){ + return false; + } + return true; +} +bool ItemSelectDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return m_stop_on_no_detect + ? !detect(frame) + : detect(frame); +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h index c2e299b1f4..9054c7c789 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h @@ -1,41 +1,41 @@ -/* Max Lair Detect Item Select Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_ItemSelectMenu_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_ItemSelectMenu_H - -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class ItemSelectDetector : public VisualInferenceCallback{ -public: - ItemSelectDetector(bool stop_no_detect); - - bool detect(const ImageViewRGB32& screen) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - bool m_stop_on_no_detect; - ImageFloatBox m_bottom_main; - ImageFloatBox m_bottom_right; - ImageFloatBox m_blue; -}; - - -} -} -} -} -#endif +/* Max Lair Detect Item Select Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_ItemSelectMenu_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_ItemSelectMenu_H + +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class ItemSelectDetector : public VisualInferenceCallback{ +public: + ItemSelectDetector(bool stop_no_detect); + + bool detect(const ImageViewRGB32& screen) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + bool m_stop_on_no_detect; + ImageFloatBox m_bottom_main; + ImageFloatBox m_bottom_right; + ImageFloatBox m_blue; +}; + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.cpp index 93c55ccb19..ec71672aed 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.cpp @@ -1,175 +1,175 @@ -/* Max Lair Detect Lobby - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/ImageTools/ImageDiff.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_MaxLair_Detect_Lobby.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -#if 1 -LobbyDetector::LobbyDetector(bool invert) - : VisualInferenceCallback("LobbyDetector") - , m_invert(invert) - , m_pink (0.575, 0.035, 0.050, 0.100) - , m_white(0.800, 0.200, 0.150, 0.100) -{} -void LobbyDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_pink); - items.add(COLOR_RED, m_white); -} -bool LobbyDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} -bool LobbyDetector::detect(const ImageViewRGB32& screen){ - ImageStats stats0 = image_stats(extract_box_reference(screen, m_pink)); - ImageStats stats1 = image_stats(extract_box_reference(screen, m_white)); -// cout << stats0.average << ", " << stats0.stddev << endl; -// cout << stats1.average << ", " << stats1.stddev << endl; - if (!is_solid(stats0, {0.444944, 0.150562, 0.404494})){ - return m_invert; - } - if (!is_solid(stats1, {0.303079, 0.356564, 0.340357})){ - return m_invert; - } - return !m_invert; -} -#endif - - -LobbyDoneConnecting::LobbyDoneConnecting() - : VisualInferenceCallback("LobbyDoneConnecting") - , m_box(0.600, 0.820, 0.080, 0.100) - , m_player0(0.669, 0.337 + 0.0775*1, 0.100, 0.06) -{} -void LobbyDoneConnecting::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box); - items.add(COLOR_RED, m_player0); -} -bool LobbyDoneConnecting::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} -bool LobbyDoneConnecting::detect(const ImageViewRGB32& screen){ - ImageStats stats0 = image_stats(extract_box_reference(screen, m_box)); -// cout << stats0.average << ", " << stats0.stddev << endl; - if (is_grey(stats0, 0, 200)){ - return false; - } - ImageStats player0 = image_stats(extract_box_reference(screen, m_player0)); -// cout << player0.average << player0.stddev << endl; - if (is_white(player0, 300, 20)){ - return false; - } -// screen.save("test.png"); - return true; -} - - - -LobbyJoinedDetector::LobbyJoinedDetector(size_t consoles, bool invert) - : VisualInferenceCallback("LobbyJoinedDetector") - , m_consoles(consoles) - , m_invert(invert) - , m_box0(0.705, 0.337 + 0.0775*0, 0.034, 0.06) - , m_box1(0.705, 0.337 + 0.0775*1, 0.034, 0.06) - , m_box2(0.705, 0.337 + 0.0775*2, 0.034, 0.06) - , m_box3(0.705, 0.337 + 0.0775*3, 0.034, 0.06) - , m_player0(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) - , m_player1(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) - , m_player2(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) - , m_player3(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) -{} -void LobbyJoinedDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box0); - items.add(COLOR_RED, m_box1); - items.add(COLOR_RED, m_box2); - items.add(COLOR_RED, m_box3); - m_player0.make_overlays(items); - m_player1.make_overlays(items); - m_player2.make_overlays(items); - m_player3.make_overlays(items); -} - -size_t LobbyJoinedDetector::joined(const ImageViewRGB32& screen, WallClock timestamp){ - size_t count = 0; - if (m_player0.process_frame(extract_box_reference(screen, m_box0), timestamp)) count++; - if (m_player1.process_frame(extract_box_reference(screen, m_box1), timestamp)) count++; - if (m_player2.process_frame(extract_box_reference(screen, m_box2), timestamp)) count++; - if (m_player3.process_frame(extract_box_reference(screen, m_box3), timestamp)) count++; - return count; -} - -bool LobbyJoinedDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return m_invert - ? joined(frame, timestamp) < m_consoles - : joined(frame, timestamp) >= m_consoles; -} - - - - -LobbyReadyDetector::LobbyReadyDetector() - : VisualInferenceCallback("LobbyReadyDetector") - , m_checkbox0(0.669, 0.337 + 0.0775*0, 0.034, 0.06) - , m_checkbox1(0.669, 0.337 + 0.0775*1, 0.034, 0.06) - , m_checkbox2(0.669, 0.337 + 0.0775*2, 0.034, 0.06) - , m_checkbox3(0.669, 0.337 + 0.0775*3, 0.034, 0.06) -{} -void LobbyReadyDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_checkbox0); - items.add(COLOR_RED, m_checkbox1); - items.add(COLOR_RED, m_checkbox2); - items.add(COLOR_RED, m_checkbox3); -} -size_t LobbyReadyDetector::ready_players(const ImageViewRGB32& screen){ - size_t ready = 0; - ImageStats stats0 = image_stats(extract_box_reference(screen, m_checkbox0)); - ImageStats stats1 = image_stats(extract_box_reference(screen, m_checkbox1)); - ImageStats stats2 = image_stats(extract_box_reference(screen, m_checkbox2)); - ImageStats stats3 = image_stats(extract_box_reference(screen, m_checkbox3)); - if (stats0.stddev.sum() > 50) ready++; - if (stats1.stddev.sum() > 50) ready++; - if (stats2.stddev.sum() > 50) ready++; - if (stats3.stddev.sum() > 50) ready++; - return ready; -} -bool LobbyReadyDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return detect(frame); -} - -LobbyMinReadyDetector::LobbyMinReadyDetector(size_t consoles, bool invert) - : m_consoles(consoles) - , m_invert(invert) -{} -bool LobbyMinReadyDetector::detect(const ImageViewRGB32& screen){ - return m_invert - ? ready_players(screen) < m_consoles - : ready_players(screen) >= m_consoles; -} - -LobbyAllReadyDetector::LobbyAllReadyDetector(size_t consoles) - : m_consoles(consoles) -{} -bool LobbyAllReadyDetector::detect(const ImageViewRGB32& screen){ - return ready_players(screen) >= m_consoles; -} - - -} -} -} -} +/* Max Lair Detect Lobby + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/ImageTools/ImageDiff.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_MaxLair_Detect_Lobby.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +#if 1 +LobbyDetector::LobbyDetector(bool invert) + : VisualInferenceCallback("LobbyDetector") + , m_invert(invert) + , m_pink (0.575, 0.035, 0.050, 0.100) + , m_white(0.800, 0.200, 0.150, 0.100) +{} +void LobbyDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_pink); + items.add(COLOR_RED, m_white); +} +bool LobbyDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} +bool LobbyDetector::detect(const ImageViewRGB32& screen){ + ImageStats stats0 = image_stats(extract_box_reference(screen, m_pink)); + ImageStats stats1 = image_stats(extract_box_reference(screen, m_white)); +// cout << stats0.average << ", " << stats0.stddev << endl; +// cout << stats1.average << ", " << stats1.stddev << endl; + if (!is_solid(stats0, {0.444944, 0.150562, 0.404494})){ + return m_invert; + } + if (!is_solid(stats1, {0.303079, 0.356564, 0.340357})){ + return m_invert; + } + return !m_invert; +} +#endif + + +LobbyDoneConnecting::LobbyDoneConnecting() + : VisualInferenceCallback("LobbyDoneConnecting") + , m_box(0.600, 0.820, 0.080, 0.100) + , m_player0(0.669, 0.337 + 0.0775*1, 0.100, 0.06) +{} +void LobbyDoneConnecting::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box); + items.add(COLOR_RED, m_player0); +} +bool LobbyDoneConnecting::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} +bool LobbyDoneConnecting::detect(const ImageViewRGB32& screen){ + ImageStats stats0 = image_stats(extract_box_reference(screen, m_box)); +// cout << stats0.average << ", " << stats0.stddev << endl; + if (is_grey(stats0, 0, 200)){ + return false; + } + ImageStats player0 = image_stats(extract_box_reference(screen, m_player0)); +// cout << player0.average << player0.stddev << endl; + if (is_white(player0, 300, 20)){ + return false; + } +// screen.save("test.png"); + return true; +} + + + +LobbyJoinedDetector::LobbyJoinedDetector(size_t consoles, bool invert) + : VisualInferenceCallback("LobbyJoinedDetector") + , m_consoles(consoles) + , m_invert(invert) + , m_box0(0.705, 0.337 + 0.0775*0, 0.034, 0.06) + , m_box1(0.705, 0.337 + 0.0775*1, 0.034, 0.06) + , m_box2(0.705, 0.337 + 0.0775*2, 0.034, 0.06) + , m_box3(0.705, 0.337 + 0.0775*3, 0.034, 0.06) + , m_player0(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) + , m_player1(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) + , m_player2(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) + , m_player3(COLOR_CYAN, {0, 0, 1, 0.5}, std::chrono::seconds(1), 10) +{} +void LobbyJoinedDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box0); + items.add(COLOR_RED, m_box1); + items.add(COLOR_RED, m_box2); + items.add(COLOR_RED, m_box3); + m_player0.make_overlays(items); + m_player1.make_overlays(items); + m_player2.make_overlays(items); + m_player3.make_overlays(items); +} + +size_t LobbyJoinedDetector::joined(const ImageViewRGB32& screen, WallClock timestamp){ + size_t count = 0; + if (m_player0.process_frame(extract_box_reference(screen, m_box0), timestamp)) count++; + if (m_player1.process_frame(extract_box_reference(screen, m_box1), timestamp)) count++; + if (m_player2.process_frame(extract_box_reference(screen, m_box2), timestamp)) count++; + if (m_player3.process_frame(extract_box_reference(screen, m_box3), timestamp)) count++; + return count; +} + +bool LobbyJoinedDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return m_invert + ? joined(frame, timestamp) < m_consoles + : joined(frame, timestamp) >= m_consoles; +} + + + + +LobbyReadyDetector::LobbyReadyDetector() + : VisualInferenceCallback("LobbyReadyDetector") + , m_checkbox0(0.669, 0.337 + 0.0775*0, 0.034, 0.06) + , m_checkbox1(0.669, 0.337 + 0.0775*1, 0.034, 0.06) + , m_checkbox2(0.669, 0.337 + 0.0775*2, 0.034, 0.06) + , m_checkbox3(0.669, 0.337 + 0.0775*3, 0.034, 0.06) +{} +void LobbyReadyDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_checkbox0); + items.add(COLOR_RED, m_checkbox1); + items.add(COLOR_RED, m_checkbox2); + items.add(COLOR_RED, m_checkbox3); +} +size_t LobbyReadyDetector::ready_players(const ImageViewRGB32& screen){ + size_t ready = 0; + ImageStats stats0 = image_stats(extract_box_reference(screen, m_checkbox0)); + ImageStats stats1 = image_stats(extract_box_reference(screen, m_checkbox1)); + ImageStats stats2 = image_stats(extract_box_reference(screen, m_checkbox2)); + ImageStats stats3 = image_stats(extract_box_reference(screen, m_checkbox3)); + if (stats0.stddev.sum() > 50) ready++; + if (stats1.stddev.sum() > 50) ready++; + if (stats2.stddev.sum() > 50) ready++; + if (stats3.stddev.sum() > 50) ready++; + return ready; +} +bool LobbyReadyDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return detect(frame); +} + +LobbyMinReadyDetector::LobbyMinReadyDetector(size_t consoles, bool invert) + : m_consoles(consoles) + , m_invert(invert) +{} +bool LobbyMinReadyDetector::detect(const ImageViewRGB32& screen){ + return m_invert + ? ready_players(screen) < m_consoles + : ready_players(screen) >= m_consoles; +} + +LobbyAllReadyDetector::LobbyAllReadyDetector(size_t consoles) + : m_consoles(consoles) +{} +bool LobbyAllReadyDetector::detect(const ImageViewRGB32& screen){ + return ready_players(screen) >= m_consoles; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h index 42b15c2b39..2d5b1d18c4 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h @@ -1,120 +1,120 @@ -/* Max Lair Detect Lobby - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_Lobby_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_Lobby_H - -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "CommonTools/VisualDetectors/FrozenImageDetector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -#if 1 -class LobbyDetector : public VisualInferenceCallback{ -public: - LobbyDetector(bool invert); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - bool m_invert; - ImageFloatBox m_pink; - ImageFloatBox m_white; -}; -#endif - - -class LobbyDoneConnecting : public VisualInferenceCallback{ -public: - LobbyDoneConnecting(); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - ImageFloatBox m_box; - ImageFloatBox m_player0; -}; - - -class LobbyJoinedDetector : public VisualInferenceCallback{ -public: - LobbyJoinedDetector(size_t consoles, bool invert); - - size_t joined(const ImageViewRGB32& screen, WallClock timestamp); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - size_t m_consoles; - bool m_invert; - - ImageFloatBox m_box0; - ImageFloatBox m_box1; - ImageFloatBox m_box2; - ImageFloatBox m_box3; - - FrozenImageDetector m_player0; - FrozenImageDetector m_player1; - FrozenImageDetector m_player2; - FrozenImageDetector m_player3; -}; - - -// Detects when all joiners are readied up. -class LobbyReadyDetector : public VisualInferenceCallback{ -public: - LobbyReadyDetector(); - - size_t ready_players(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - virtual bool detect(const ImageViewRGB32& screen) = 0; - - -private: - ImageFloatBox m_checkbox0; - ImageFloatBox m_checkbox1; - ImageFloatBox m_checkbox2; - ImageFloatBox m_checkbox3; -}; - -class LobbyMinReadyDetector : public LobbyReadyDetector{ -public: - LobbyMinReadyDetector(size_t consoles, bool invert); - virtual bool detect(const ImageViewRGB32& screen) override; -private: - size_t m_consoles; - bool m_invert; -}; -class LobbyAllReadyDetector : public LobbyReadyDetector{ -public: - LobbyAllReadyDetector(size_t consoles); - virtual bool detect(const ImageViewRGB32& screen) override; -private: - size_t m_consoles; -}; - - - -} -} -} -} -#endif +/* Max Lair Detect Lobby + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_Lobby_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_Lobby_H + +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "CommonTools/VisualDetectors/FrozenImageDetector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +#if 1 +class LobbyDetector : public VisualInferenceCallback{ +public: + LobbyDetector(bool invert); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + bool m_invert; + ImageFloatBox m_pink; + ImageFloatBox m_white; +}; +#endif + + +class LobbyDoneConnecting : public VisualInferenceCallback{ +public: + LobbyDoneConnecting(); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + ImageFloatBox m_box; + ImageFloatBox m_player0; +}; + + +class LobbyJoinedDetector : public VisualInferenceCallback{ +public: + LobbyJoinedDetector(size_t consoles, bool invert); + + size_t joined(const ImageViewRGB32& screen, WallClock timestamp); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + size_t m_consoles; + bool m_invert; + + ImageFloatBox m_box0; + ImageFloatBox m_box1; + ImageFloatBox m_box2; + ImageFloatBox m_box3; + + FrozenImageDetector m_player0; + FrozenImageDetector m_player1; + FrozenImageDetector m_player2; + FrozenImageDetector m_player3; +}; + + +// Detects when all joiners are readied up. +class LobbyReadyDetector : public VisualInferenceCallback{ +public: + LobbyReadyDetector(); + + size_t ready_players(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + virtual bool detect(const ImageViewRGB32& screen) = 0; + + +private: + ImageFloatBox m_checkbox0; + ImageFloatBox m_checkbox1; + ImageFloatBox m_checkbox2; + ImageFloatBox m_checkbox3; +}; + +class LobbyMinReadyDetector : public LobbyReadyDetector{ +public: + LobbyMinReadyDetector(size_t consoles, bool invert); + virtual bool detect(const ImageViewRGB32& screen) override; +private: + size_t m_consoles; + bool m_invert; +}; +class LobbyAllReadyDetector : public LobbyReadyDetector{ +public: + LobbyAllReadyDetector(size_t consoles); + virtual bool detect(const ImageViewRGB32& screen) override; +private: + size_t m_consoles; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp index 0fe6db938e..fb32d8ea45 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.cpp @@ -1,173 +1,173 @@ -/* Max Lair Detect Path Map - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh_MaxLair_Detect_PathMap.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -bool read_type_array( - VideoStream& stream, - const ImageViewRGB32& screen, - const ImageFloatBox& box, - std::deque& hits, - size_t count, - PokemonType* type, ImagePixelBox* boxes -){ - ImageViewRGB32 image = extract_box_reference(screen, box); - for (size_t c = 0; c < count; c++){ - type[c] = PokemonType::NONE; - } - - std::multimap> candidates = find_symbols(image, 0.20); - if (candidates.size() < count){ -// dump_image(console, screen, "ReadPath"); - return false; - } - - std::multimap*> sorted; -// std::deque hits; - hits.clear(); - size_t c = 0; - for (const auto& item : candidates){ - hits.emplace_back(stream.overlay(), translate_to_parent(screen, box, item.second.second), COLOR_GREEN); - sorted.emplace(item.second.second.min_x, &item.second); - c++; - if (c >= count){ - break; - } - } - - c = 0; - for (const auto& item : sorted){ - type[c] = item.second->first; - if (boxes != nullptr){ - boxes[c] = item.second->second; - } - c++; - } - - return true; -} - -std::shared_ptr read_type_array_retry( - VideoStream& stream, CancellableScope& scope, - const ImageFloatBox& box, - std::deque& hits, - size_t count, - PokemonType* type, ImagePixelBox* boxes, - size_t max_attempts = 3 -){ - VideoSnapshot screen; - for (size_t c = 0; c < max_attempts; c++){ - screen = stream.video().snapshot(); - if (read_type_array(stream, screen, box, hits, count, type, boxes)){ - return nullptr; - } - scope.wait_for(std::chrono::milliseconds(200)); - } - return std::move(screen.frame); -} - - -bool read_path( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - PathMap& path, - const ImageFloatBox& box -){ - context.wait_for_all_requests(); - - std::deque hits; - - std::shared_ptr error_image; - error_image = read_type_array_retry(stream, context, box, hits, 2, path.mon1, nullptr); - if (error_image){ - dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); - return false; - } - - pbf_move_right_joystick(context, 128, 0, 70, 50); - context.wait_for_all_requests(); - ImagePixelBox boxes[4]; - error_image = read_type_array_retry(stream, context, box, hits, 4, path.mon2, boxes); - if (error_image){ - dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); - return false; - } - - while (true){ - pbf_move_right_joystick(context, 128, 0, 80, 50); - context.wait_for_all_requests(); - - error_image = read_type_array_retry(stream, context, box, hits, 4, path.mon3, nullptr); - if (!error_image){ - break; - } - pbf_move_right_joystick(context, 128, 0, 20, 50); - context.wait_for_all_requests(); - error_image = read_type_array_retry(stream, context, box, hits, 4, path.mon3, nullptr); - if (!error_image){ - break; - } - - dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); - return false; - } - - pbf_move_right_joystick(context, 128, 0, 125, 50); - context.wait_for_all_requests(); - - error_image = read_type_array_retry(stream, context, box, hits, 1, &path.boss, nullptr); - if (error_image){ - dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); - return false; - } - - - - if (boxes[0].min_y < boxes[2].min_y && - boxes[2].min_y < boxes[1].min_y && - boxes[1].min_y < boxes[3].min_y - ){ - path.path_type = 2; - return true; - } - if ( - boxes[3].min_y > boxes[0].min_y && - boxes[0].min_y > boxes[1].min_y && - boxes[0].min_y > boxes[2].min_y - ){ - path.path_type = 1; - return true; - } - if ( - boxes[2].min_y < boxes[0].min_y && - boxes[0].min_y < boxes[1].min_y && - boxes[1].min_y < boxes[3].min_y - ){ - path.path_type = 0; - return true; - } - - return false; -} - - - -} -} -} -} +/* Max Lair Detect Path Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/Inference/PokemonSwSh_TypeSymbolFinder.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh_MaxLair_Detect_PathMap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +bool read_type_array( + VideoStream& stream, + const ImageViewRGB32& screen, + const ImageFloatBox& box, + std::deque& hits, + size_t count, + PokemonType* type, ImagePixelBox* boxes +){ + ImageViewRGB32 image = extract_box_reference(screen, box); + for (size_t c = 0; c < count; c++){ + type[c] = PokemonType::NONE; + } + + std::multimap> candidates = find_symbols(image, 0.20); + if (candidates.size() < count){ +// dump_image(console, screen, "ReadPath"); + return false; + } + + std::multimap*> sorted; +// std::deque hits; + hits.clear(); + size_t c = 0; + for (const auto& item : candidates){ + hits.emplace_back(stream.overlay(), translate_to_parent(screen, box, item.second.second), COLOR_GREEN); + sorted.emplace(item.second.second.min_x, &item.second); + c++; + if (c >= count){ + break; + } + } + + c = 0; + for (const auto& item : sorted){ + type[c] = item.second->first; + if (boxes != nullptr){ + boxes[c] = item.second->second; + } + c++; + } + + return true; +} + +std::shared_ptr read_type_array_retry( + VideoStream& stream, CancellableScope& scope, + const ImageFloatBox& box, + std::deque& hits, + size_t count, + PokemonType* type, ImagePixelBox* boxes, + size_t max_attempts = 3 +){ + VideoSnapshot screen; + for (size_t c = 0; c < max_attempts; c++){ + screen = stream.video().snapshot(); + if (read_type_array(stream, screen, box, hits, count, type, boxes)){ + return nullptr; + } + scope.wait_for(std::chrono::milliseconds(200)); + } + return std::move(screen.frame); +} + + +bool read_path( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + PathMap& path, + const ImageFloatBox& box +){ + context.wait_for_all_requests(); + + std::deque hits; + + std::shared_ptr error_image; + error_image = read_type_array_retry(stream, context, box, hits, 2, path.mon1, nullptr); + if (error_image){ + dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); + return false; + } + + pbf_move_right_joystick(context, 128, 0, 70, 50); + context.wait_for_all_requests(); + ImagePixelBox boxes[4]; + error_image = read_type_array_retry(stream, context, box, hits, 4, path.mon2, boxes); + if (error_image){ + dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); + return false; + } + + while (true){ + pbf_move_right_joystick(context, 128, 0, 80, 50); + context.wait_for_all_requests(); + + error_image = read_type_array_retry(stream, context, box, hits, 4, path.mon3, nullptr); + if (!error_image){ + break; + } + pbf_move_right_joystick(context, 128, 0, 20, 50); + context.wait_for_all_requests(); + error_image = read_type_array_retry(stream, context, box, hits, 4, path.mon3, nullptr); + if (!error_image){ + break; + } + + dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); + return false; + } + + pbf_move_right_joystick(context, 128, 0, 125, 50); + context.wait_for_all_requests(); + + error_image = read_type_array_retry(stream, context, box, hits, 1, &path.boss, nullptr); + if (error_image){ + dump_image(stream.logger(), env.program_info(), "ReadPath", *error_image); + return false; + } + + + + if (boxes[0].min_y < boxes[2].min_y && + boxes[2].min_y < boxes[1].min_y && + boxes[1].min_y < boxes[3].min_y + ){ + path.path_type = 2; + return true; + } + if ( + boxes[3].min_y > boxes[0].min_y && + boxes[0].min_y > boxes[1].min_y && + boxes[0].min_y > boxes[2].min_y + ){ + path.path_type = 1; + return true; + } + if ( + boxes[2].min_y < boxes[0].min_y && + boxes[0].min_y < boxes[1].min_y && + boxes[1].min_y < boxes[3].min_y + ){ + path.path_type = 0; + return true; + } + + return false; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.h index 96030f32aa..81eaab1d14 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathMap.h @@ -1,47 +1,47 @@ -/* Max Lair Detect Path Map - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathMap_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathMap_H - -#include -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_Types.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -bool read_type_array( - VideoStream& stream, - const ImageViewRGB32& screen, - const ImageFloatBox& box, - std::deque& hits, - size_t count, - PokemonType* type, ImagePixelBox* boxes -); - - -bool read_path( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - PathMap& path, - const ImageFloatBox& box -); - - -} -} -} -} -#endif +/* Max Lair Detect Path Map + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathMap_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathMap_H + +#include +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_Types.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +bool read_type_array( + VideoStream& stream, + const ImageViewRGB32& screen, + const ImageFloatBox& box, + std::deque& hits, + size_t count, + PokemonType* type, ImagePixelBox* boxes +); + + +bool read_path( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + PathMap& path, + const ImageFloatBox& box +); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp index d3296b3bb6..540d3bfff2 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.cpp @@ -1,293 +1,293 @@ -/* Max Lair Detect Path Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "Pokemon/Inference/Pokemon_ReadHpBar.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h" -#include "PokemonSwSh_MaxLair_Detect_PathSide.h" -#include "PokemonSwSh_MaxLair_Detect_PathMap.h" -#include "PokemonSwSh_MaxLair_Detect_PathSelect.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -PathScreenDetector::PathScreenDetector() - : VisualInferenceCallback("PathScreenDetector") - , m_bottom_main(0.100, 0.970, 0.600, 0.020) - , m_main(0.100, 0.100, 0.800, 0.600) - , m_box0(0.074, 0.420 + 0*0.16315, 0.020, 0.007) - , m_box1(0.074, 0.420 + 1*0.16315, 0.020, 0.007) - , m_box2(0.074, 0.420 + 2*0.16315, 0.020, 0.007) - , m_box3(0.074, 0.420 + 3*0.16315, 0.020, 0.007) -{} -void PathScreenDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_CYAN, m_bottom_main); - items.add(COLOR_CYAN, m_main); - items.add(COLOR_CYAN, m_box0); - items.add(COLOR_CYAN, m_box1); - items.add(COLOR_CYAN, m_box2); - items.add(COLOR_CYAN, m_box3); -} - -bool PathScreenDetector::detect(const ImageViewRGB32& screen) const{ - ImageStats box0 = image_stats(extract_box_reference(screen, m_box0)); - if (!is_white(box0, 500, 40)){ -// global_logger().log("box0 out"); - return false; - } - ImageStats box1 = image_stats(extract_box_reference(screen, m_box1)); - if (!is_white(box1, 500, 40)){ -// global_logger().log("box1 out"); -// cout << "box1 = " << box1.average << box1.stddev << endl; - return false; - } - ImageStats box2 = image_stats(extract_box_reference(screen, m_box2)); - if (!is_white(box2, 500, 40)){ -// global_logger().log("box2 out"); -// cout << "box2 = " << box2.average << box2.stddev << endl; - return false; - } - ImageStats box3 = image_stats(extract_box_reference(screen, m_box3)); - if (!is_white(box3, 500, 40)){ -// global_logger().log("box3 out"); -// cout << "box3 = " << box3.average << box3.stddev << endl; - return false; - } - - ImageStats bottom_main = image_stats(extract_box_reference(screen, m_bottom_main)); - if (!is_black(bottom_main)){ -// global_logger().log("m_bottom_main out"); - return false; - } - ImageStats main = image_stats(extract_box_reference(screen, m_main)); -// cout << main.average << main.stddev << endl; - if (main.stddev.sum() < 50){ -// global_logger().log("m_main out"); - return false; - } - return true; -} -bool PathScreenDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool ret = detect(frame); -// global_logger().log(std::to_string(ret)); - return ret; -} - - - - - -PathSelectDetector::PathSelectDetector() - : m_bottom_right(0.920, 0.970, 0.070, 0.020) - , m_dialog_left(0.257, 0.807, 0.015, 0.030) - , m_dialog_middle(0.500, 0.880, 0.180, 0.050) -// , m_dialog_right(0.710, 0.880, 0.030, 0.050) - , m_left(0.050, 0.100, 0.200, 0.700) -{} -void PathSelectDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_CYAN, m_bottom_right); - items.add(COLOR_CYAN, m_dialog_left); - items.add(COLOR_CYAN, m_dialog_middle); -// items.add(COLOR_CYAN, m_dialog_right); - items.add(COLOR_CYAN, m_left); -} -bool PathSelectDetector::detect(const ImageViewRGB32& screen) const{ - if (!PathScreenDetector::detect(screen)){ - return false; - } - - ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); - if (bottom_right.stddev.sum() < 30){ -// cout << "m_bottom_right = " << bottom_right.average << bottom_right.stddev << endl; -// global_logger().log("m_bottom_right out"); - return false; - } - ImageStats dialog_left = image_stats(extract_box_reference(screen, m_dialog_left)); - if (!is_grey(dialog_left, 0, 200)){ -// global_logger().log("m_dialog_left out"); - return false; - } - ImageStats dialog_middle = image_stats(extract_box_reference(screen, m_dialog_middle)); - if (!is_grey(dialog_middle, 0, 300)){ -// global_logger().log("m_dialog_middle out"); - return false; - } -// ImageStats dialog_right = image_stats(extract_box_reference(screen, m_dialog_right)); -// if (!is_grey(dialog_right, 0, 200)){ -// return false; -// } - ImageStats left = image_stats(extract_box_reference(screen, m_left)); -// cout << left.average << left.stddev << endl; - if (left.stddev.sum() < 100){ -// global_logger().log("m_left out"); - return false; - } -// if (euclidean_distance(dialog_left.average, dialog_right.average) > 10){ -// return false; -// } - if (dialog_left.average.sum() > dialog_middle.average.sum()){ -// global_logger_tagged().log("dialog out"); - return false; - } -// if (dialog_right.average.sum() > dialog_middle.average.sum()){ -// return false; -// } - return true; -} -bool PathSelectDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - bool ret = detect(frame); -// global_logger().log(std::to_string(ret)); - return ret; -} - - - - - - - - - - - - - -PathReader::PathReader(VideoOverlay& overlay, size_t player_index) - : m_player_index(player_index) - , m_path(overlay, {0.150, 0.020, 0.800, 0.780}) - , m_sprite0(overlay, {0.002, 0.345 + 0*0.16315, 0.071, 0.102}) - , m_sprite1(overlay, {0.002, 0.345 + 1*0.16315, 0.071, 0.102}) - , m_sprite2(overlay, {0.002, 0.345 + 2*0.16315, 0.071, 0.102}) - , m_sprite3(overlay, {0.002, 0.345 + 3*0.16315, 0.071, 0.102}) - , m_hp0(overlay, {0.074, 0.435 + 0*0.16315, player_index == 0 ? 0.052 : 0.041, 0.005}) - , m_hp1(overlay, {0.074, 0.435 + 1*0.16315, player_index == 1 ? 0.052 : 0.041, 0.005}) - , m_hp2(overlay, {0.074, 0.435 + 2*0.16315, player_index == 2 ? 0.052 : 0.041, 0.005}) - , m_hp3(overlay, {0.074, 0.435 + 3*0.16315, player_index == 3 ? 0.052 : 0.041, 0.005}) -{} - - -void PathReader::read_sprites(Logger& logger, const ImageViewRGB32& screen, std::string slugs[4]) const{ - slugs[0] = read_pokemon_sprite_with_item(logger, screen, m_sprite0); - slugs[1] = read_pokemon_sprite_with_item(logger, screen, m_sprite1); - slugs[2] = read_pokemon_sprite_with_item(logger, screen, m_sprite2); - slugs[3] = read_pokemon_sprite_with_item(logger, screen, m_sprite3); - if (slugs[0].empty() || slugs[1].empty() || slugs[2].empty() || slugs[3].empty()){ - dump_image(logger, MODULE_NAME, "PathPartyReader-ReadSprites", screen); - } -} -void PathReader::read_sprites( - Logger& logger, - GlobalState& state, - const ImageViewRGB32& screen -) const{ - std::string mons[4]; - read_sprites(logger, screen, mons); - state.add_seen(mons[0]); - state.add_seen(mons[1]); - state.add_seen(mons[2]); - state.add_seen(mons[3]); - if (!mons[0].empty()) state.players[0].pokemon = mons[0]; - if (!mons[1].empty()) state.players[1].pokemon = mons[1]; - if (!mons[2].empty()) state.players[2].pokemon = mons[2]; - if (!mons[3].empty()) state.players[3].pokemon = mons[3]; -} - - -void PathReader::read_hp(Logger& logger, const ImageViewRGB32& screen, double hp[4]) const{ - hp[0] = read_hp_bar(logger, extract_box_reference(screen, m_hp0)); - hp[1] = read_hp_bar(logger, extract_box_reference(screen, m_hp1)); - hp[2] = read_hp_bar(logger, extract_box_reference(screen, m_hp2)); - hp[3] = read_hp_bar(logger, extract_box_reference(screen, m_hp3)); - if (hp[0] < 0 || hp[1] < 0 || hp[2] < 0 || hp[3] < 0){ - dump_image(logger, MODULE_NAME, "PathPartyReader-ReadHP", screen); - } -} -void PathReader::read_hp( - Logger& logger, - GlobalState& state, - const ImageViewRGB32& screen -) const{ - double hp[4]; - read_hp(logger, screen, hp); - if (hp[0] >= 0) state.players[0].health.value.hp = hp[0]; - if (hp[1] >= 0) state.players[1].health.value.hp = hp[1]; - if (hp[2] >= 0) state.players[2].health.value.hp = hp[2]; - if (hp[3] >= 0) state.players[3].health.value.hp = hp[3]; - state.players[0].health.value.dead = 0; - state.players[1].health.value.dead = 0; - state.players[2].health.value.dead = 0; - state.players[3].health.value.dead = 0; -} - - - - - - -void PathReader::read_path( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - GlobalState& state -){ - PathMap path; - if (MaxLairInternal::read_path(env, stream, context, path, m_path)){ - stream.log("Path Detection:\n" + path.dump(), COLOR_BLUE); - state.path = path; - }else{ - stream.log("Path Detection: Failed", COLOR_RED); - } -} - - - - -void PathReader::read_side( - Logger& logger, - GlobalState& state, - const ImageViewRGB32& screen -){ - int8_t path_side = MaxLairInternal::read_side(extract_box_reference(screen, m_path)); - switch (path_side){ - case 0: - logger.log("Path Detection: Left side", COLOR_BLUE); - break; - case 1: - logger.log("Path Detection: Right side", COLOR_BLUE); - break; - default: - logger.log("Path Detection: Unable to read.", COLOR_RED); - dump_image(logger, MODULE_NAME, "ReadPathSide", screen); - break; - } - state.path_side = path_side; -} - - - - - - - - - - - -} -} -} -} +/* Max Lair Detect Path Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "Pokemon/Inference/Pokemon_ReadHpBar.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h" +#include "PokemonSwSh_MaxLair_Detect_PathSide.h" +#include "PokemonSwSh_MaxLair_Detect_PathMap.h" +#include "PokemonSwSh_MaxLair_Detect_PathSelect.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +PathScreenDetector::PathScreenDetector() + : VisualInferenceCallback("PathScreenDetector") + , m_bottom_main(0.100, 0.970, 0.600, 0.020) + , m_main(0.100, 0.100, 0.800, 0.600) + , m_box0(0.074, 0.420 + 0*0.16315, 0.020, 0.007) + , m_box1(0.074, 0.420 + 1*0.16315, 0.020, 0.007) + , m_box2(0.074, 0.420 + 2*0.16315, 0.020, 0.007) + , m_box3(0.074, 0.420 + 3*0.16315, 0.020, 0.007) +{} +void PathScreenDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_CYAN, m_bottom_main); + items.add(COLOR_CYAN, m_main); + items.add(COLOR_CYAN, m_box0); + items.add(COLOR_CYAN, m_box1); + items.add(COLOR_CYAN, m_box2); + items.add(COLOR_CYAN, m_box3); +} + +bool PathScreenDetector::detect(const ImageViewRGB32& screen) const{ + ImageStats box0 = image_stats(extract_box_reference(screen, m_box0)); + if (!is_white(box0, 500, 40)){ +// global_logger().log("box0 out"); + return false; + } + ImageStats box1 = image_stats(extract_box_reference(screen, m_box1)); + if (!is_white(box1, 500, 40)){ +// global_logger().log("box1 out"); +// cout << "box1 = " << box1.average << box1.stddev << endl; + return false; + } + ImageStats box2 = image_stats(extract_box_reference(screen, m_box2)); + if (!is_white(box2, 500, 40)){ +// global_logger().log("box2 out"); +// cout << "box2 = " << box2.average << box2.stddev << endl; + return false; + } + ImageStats box3 = image_stats(extract_box_reference(screen, m_box3)); + if (!is_white(box3, 500, 40)){ +// global_logger().log("box3 out"); +// cout << "box3 = " << box3.average << box3.stddev << endl; + return false; + } + + ImageStats bottom_main = image_stats(extract_box_reference(screen, m_bottom_main)); + if (!is_black(bottom_main)){ +// global_logger().log("m_bottom_main out"); + return false; + } + ImageStats main = image_stats(extract_box_reference(screen, m_main)); +// cout << main.average << main.stddev << endl; + if (main.stddev.sum() < 50){ +// global_logger().log("m_main out"); + return false; + } + return true; +} +bool PathScreenDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool ret = detect(frame); +// global_logger().log(std::to_string(ret)); + return ret; +} + + + + + +PathSelectDetector::PathSelectDetector() + : m_bottom_right(0.920, 0.970, 0.070, 0.020) + , m_dialog_left(0.257, 0.807, 0.015, 0.030) + , m_dialog_middle(0.500, 0.880, 0.180, 0.050) +// , m_dialog_right(0.710, 0.880, 0.030, 0.050) + , m_left(0.050, 0.100, 0.200, 0.700) +{} +void PathSelectDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_CYAN, m_bottom_right); + items.add(COLOR_CYAN, m_dialog_left); + items.add(COLOR_CYAN, m_dialog_middle); +// items.add(COLOR_CYAN, m_dialog_right); + items.add(COLOR_CYAN, m_left); +} +bool PathSelectDetector::detect(const ImageViewRGB32& screen) const{ + if (!PathScreenDetector::detect(screen)){ + return false; + } + + ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); + if (bottom_right.stddev.sum() < 30){ +// cout << "m_bottom_right = " << bottom_right.average << bottom_right.stddev << endl; +// global_logger().log("m_bottom_right out"); + return false; + } + ImageStats dialog_left = image_stats(extract_box_reference(screen, m_dialog_left)); + if (!is_grey(dialog_left, 0, 200)){ +// global_logger().log("m_dialog_left out"); + return false; + } + ImageStats dialog_middle = image_stats(extract_box_reference(screen, m_dialog_middle)); + if (!is_grey(dialog_middle, 0, 300)){ +// global_logger().log("m_dialog_middle out"); + return false; + } +// ImageStats dialog_right = image_stats(extract_box_reference(screen, m_dialog_right)); +// if (!is_grey(dialog_right, 0, 200)){ +// return false; +// } + ImageStats left = image_stats(extract_box_reference(screen, m_left)); +// cout << left.average << left.stddev << endl; + if (left.stddev.sum() < 100){ +// global_logger().log("m_left out"); + return false; + } +// if (euclidean_distance(dialog_left.average, dialog_right.average) > 10){ +// return false; +// } + if (dialog_left.average.sum() > dialog_middle.average.sum()){ +// global_logger_tagged().log("dialog out"); + return false; + } +// if (dialog_right.average.sum() > dialog_middle.average.sum()){ +// return false; +// } + return true; +} +bool PathSelectDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + bool ret = detect(frame); +// global_logger().log(std::to_string(ret)); + return ret; +} + + + + + + + + + + + + + +PathReader::PathReader(VideoOverlay& overlay, size_t player_index) + : m_player_index(player_index) + , m_path(overlay, {0.150, 0.020, 0.800, 0.780}) + , m_sprite0(overlay, {0.002, 0.345 + 0*0.16315, 0.071, 0.102}) + , m_sprite1(overlay, {0.002, 0.345 + 1*0.16315, 0.071, 0.102}) + , m_sprite2(overlay, {0.002, 0.345 + 2*0.16315, 0.071, 0.102}) + , m_sprite3(overlay, {0.002, 0.345 + 3*0.16315, 0.071, 0.102}) + , m_hp0(overlay, {0.074, 0.435 + 0*0.16315, player_index == 0 ? 0.052 : 0.041, 0.005}) + , m_hp1(overlay, {0.074, 0.435 + 1*0.16315, player_index == 1 ? 0.052 : 0.041, 0.005}) + , m_hp2(overlay, {0.074, 0.435 + 2*0.16315, player_index == 2 ? 0.052 : 0.041, 0.005}) + , m_hp3(overlay, {0.074, 0.435 + 3*0.16315, player_index == 3 ? 0.052 : 0.041, 0.005}) +{} + + +void PathReader::read_sprites(Logger& logger, const ImageViewRGB32& screen, std::string slugs[4]) const{ + slugs[0] = read_pokemon_sprite_with_item(logger, screen, m_sprite0); + slugs[1] = read_pokemon_sprite_with_item(logger, screen, m_sprite1); + slugs[2] = read_pokemon_sprite_with_item(logger, screen, m_sprite2); + slugs[3] = read_pokemon_sprite_with_item(logger, screen, m_sprite3); + if (slugs[0].empty() || slugs[1].empty() || slugs[2].empty() || slugs[3].empty()){ + dump_image(logger, MODULE_NAME, "PathPartyReader-ReadSprites", screen); + } +} +void PathReader::read_sprites( + Logger& logger, + GlobalState& state, + const ImageViewRGB32& screen +) const{ + std::string mons[4]; + read_sprites(logger, screen, mons); + state.add_seen(mons[0]); + state.add_seen(mons[1]); + state.add_seen(mons[2]); + state.add_seen(mons[3]); + if (!mons[0].empty()) state.players[0].pokemon = mons[0]; + if (!mons[1].empty()) state.players[1].pokemon = mons[1]; + if (!mons[2].empty()) state.players[2].pokemon = mons[2]; + if (!mons[3].empty()) state.players[3].pokemon = mons[3]; +} + + +void PathReader::read_hp(Logger& logger, const ImageViewRGB32& screen, double hp[4]) const{ + hp[0] = read_hp_bar(logger, extract_box_reference(screen, m_hp0)); + hp[1] = read_hp_bar(logger, extract_box_reference(screen, m_hp1)); + hp[2] = read_hp_bar(logger, extract_box_reference(screen, m_hp2)); + hp[3] = read_hp_bar(logger, extract_box_reference(screen, m_hp3)); + if (hp[0] < 0 || hp[1] < 0 || hp[2] < 0 || hp[3] < 0){ + dump_image(logger, MODULE_NAME, "PathPartyReader-ReadHP", screen); + } +} +void PathReader::read_hp( + Logger& logger, + GlobalState& state, + const ImageViewRGB32& screen +) const{ + double hp[4]; + read_hp(logger, screen, hp); + if (hp[0] >= 0) state.players[0].health.value.hp = hp[0]; + if (hp[1] >= 0) state.players[1].health.value.hp = hp[1]; + if (hp[2] >= 0) state.players[2].health.value.hp = hp[2]; + if (hp[3] >= 0) state.players[3].health.value.hp = hp[3]; + state.players[0].health.value.dead = 0; + state.players[1].health.value.dead = 0; + state.players[2].health.value.dead = 0; + state.players[3].health.value.dead = 0; +} + + + + + + +void PathReader::read_path( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + GlobalState& state +){ + PathMap path; + if (MaxLairInternal::read_path(env, stream, context, path, m_path)){ + stream.log("Path Detection:\n" + path.dump(), COLOR_BLUE); + state.path = path; + }else{ + stream.log("Path Detection: Failed", COLOR_RED); + } +} + + + + +void PathReader::read_side( + Logger& logger, + GlobalState& state, + const ImageViewRGB32& screen +){ + int8_t path_side = MaxLairInternal::read_side(extract_box_reference(screen, m_path)); + switch (path_side){ + case 0: + logger.log("Path Detection: Left side", COLOR_BLUE); + break; + case 1: + logger.log("Path Detection: Right side", COLOR_BLUE); + break; + default: + logger.log("Path Detection: Unable to read.", COLOR_RED); + dump_image(logger, MODULE_NAME, "ReadPathSide", screen); + break; + } + state.path_side = path_side; +} + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h index b76a50dd0d..710b4338ea 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h @@ -1,124 +1,124 @@ -/* Max Lair Detect Path Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSelect_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSelect_H - -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -class PathScreenDetector : public VisualInferenceCallback{ -public: - PathScreenDetector(); - - bool detect(const ImageViewRGB32& screen) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; - -private: - ImageFloatBox m_bottom_main; - ImageFloatBox m_main; - ImageFloatBox m_box0; - ImageFloatBox m_box1; - ImageFloatBox m_box2; - ImageFloatBox m_box3; -}; - - -class PathSelectDetector : public PathScreenDetector{ -public: - PathSelectDetector(); - - bool detect(const ImageViewRGB32& screen) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - ImageFloatBox m_bottom_right; - ImageFloatBox m_dialog_left; - ImageFloatBox m_dialog_middle; -// ImageFloatBox m_dialog_right; - ImageFloatBox m_left; -}; - - - - -class PathReader{ -public: - PathReader(VideoOverlay& overlay, size_t player_index); - - void read_sprites( - Logger& logger, - GlobalState& state, - const ImageViewRGB32& screen - ) const; - void read_hp( - Logger& logger, - GlobalState& state, - const ImageViewRGB32& screen - ) const; - - - void read_path( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - GlobalState& state - ); - - - // Determine which side you're on (left or right) in the path. - // -1 = unknown - // 0 = left - // 1 = right - void read_side( - Logger& logger, - GlobalState& state, - const ImageViewRGB32& screen - ); - - -public: - void read_sprites(Logger& logger, const ImageViewRGB32& screen, std::string slugs[4]) const; - void read_hp(Logger& logger, const ImageViewRGB32& screen, double hp[4]) const; - - static int8_t read_side(const ImageViewRGB32& image, int p_min_rgb_sum); - -private: - size_t m_player_index; - OverlayBoxScope m_path; - OverlayBoxScope m_sprite0; - OverlayBoxScope m_sprite1; - OverlayBoxScope m_sprite2; - OverlayBoxScope m_sprite3; - OverlayBoxScope m_hp0; - OverlayBoxScope m_hp1; - OverlayBoxScope m_hp2; - OverlayBoxScope m_hp3; -}; - - - - -} -} -} -} -#endif +/* Max Lair Detect Path Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSelect_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSelect_H + +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_State.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +class PathScreenDetector : public VisualInferenceCallback{ +public: + PathScreenDetector(); + + bool detect(const ImageViewRGB32& screen) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override; + +private: + ImageFloatBox m_bottom_main; + ImageFloatBox m_main; + ImageFloatBox m_box0; + ImageFloatBox m_box1; + ImageFloatBox m_box2; + ImageFloatBox m_box3; +}; + + +class PathSelectDetector : public PathScreenDetector{ +public: + PathSelectDetector(); + + bool detect(const ImageViewRGB32& screen) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + ImageFloatBox m_bottom_right; + ImageFloatBox m_dialog_left; + ImageFloatBox m_dialog_middle; +// ImageFloatBox m_dialog_right; + ImageFloatBox m_left; +}; + + + + +class PathReader{ +public: + PathReader(VideoOverlay& overlay, size_t player_index); + + void read_sprites( + Logger& logger, + GlobalState& state, + const ImageViewRGB32& screen + ) const; + void read_hp( + Logger& logger, + GlobalState& state, + const ImageViewRGB32& screen + ) const; + + + void read_path( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + GlobalState& state + ); + + + // Determine which side you're on (left or right) in the path. + // -1 = unknown + // 0 = left + // 1 = right + void read_side( + Logger& logger, + GlobalState& state, + const ImageViewRGB32& screen + ); + + +public: + void read_sprites(Logger& logger, const ImageViewRGB32& screen, std::string slugs[4]) const; + void read_hp(Logger& logger, const ImageViewRGB32& screen, double hp[4]) const; + + static int8_t read_side(const ImageViewRGB32& image, int p_min_rgb_sum); + +private: + size_t m_player_index; + OverlayBoxScope m_path; + OverlayBoxScope m_sprite0; + OverlayBoxScope m_sprite1; + OverlayBoxScope m_sprite2; + OverlayBoxScope m_sprite3; + OverlayBoxScope m_hp0; + OverlayBoxScope m_hp1; + OverlayBoxScope m_hp2; + OverlayBoxScope m_hp3; +}; + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp index 00a4908ab3..a8682c3dc8 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.cpp @@ -1,366 +1,366 @@ -/* Max Lair Detect Path Side - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/DistanceToLine.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonSwSh_MaxLair_Detect_PathSide.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - -const double ARROW_MAX_DISTANCE = 0.04; - -bool is_arrow_pointed_up( - const PackedBinaryMatrix& matrix, - PackedBinaryMatrix& inverted, - const WaterfillObject& object -){ - size_t width = matrix.width(); - size_t height = matrix.height(); - - std::unique_ptr session = make_WaterfillSession(inverted); - - // Verify left edge. - WaterfillObject region0; - { - size_t topL_x = 0; - for (; topL_x < width; topL_x++){ - if (matrix.get(topL_x, 0)){ - break; - } - } - size_t left_y = 0; - for (; left_y < height; left_y++){ - if (matrix.get(0, left_y)){ - break; - } - } - - DistanceToLine calc( - topL_x, 0, - 0, left_y - ); -// cout << "topL_x = " << topL_x << endl; -// cout << "left_y = " << left_y << endl; - - if (!session->find_object_on_bit(region0, true, 0, 0)){ - return false; - } -// PackedBinaryMatrix matrix0 = region0.packed_matrix(); -// cout << region0.packed_matrix().dump() << endl; - - size_t border_count = 0; - double border_sumsqr = 0; - for (size_t r = region0.min_y; r < region0.max_y; r++){ - for (size_t c = region0.min_x; c < region0.max_x; c++){ - if (!region0.object->get(c, r)){ - continue; - } - - if ((c > 0 && matrix.get(c - 1, r)) || - (c + 1 < width && matrix.get(c + 1, r)) || - (r > 0 && matrix.get(c, r - 1)) || - (r + 1 < height && matrix.get(c, r + 1)) - ){ - border_count++; - border_sumsqr += calc.distance_squared(c, r); - } - } - } - - double distance = std::sqrt(border_sumsqr / border_count) / width; -// cout << "left = " << distance << endl; - if (distance > ARROW_MAX_DISTANCE){ - return false; - } - } - - // Verify right edge. - WaterfillObject region1; - { - size_t topR_x = width - 1; - size_t right_y = 0; - for (; right_y < height; right_y++){ - if (matrix.get(topR_x, right_y)){ - break; - } - } - for (; topR_x > 0; topR_x--){ - if (matrix.get(topR_x, 0) == 1){ - break; - } - } - - DistanceToLine calc( - topR_x, 0, - width - 1, right_y - ); - -// cout << "width = " << width << endl; -// cout << "topR_x = " << topR_x << endl; -// cout << "right_y = " << right_y << endl; -// cout << inverted.dump() << endl; -// cout << inverted.dump_tiles() << endl; - - if (!session->find_object_on_bit(region1, true, width - 1, 0)){ - return false; - } -// cout << inverted.dump() << endl; -// cout << inverted.dump_tiles() << endl; - -// cout << region1.object.dump() << endl; -// cout << region1.packed_matrix().dump() << endl; -// cout << region1.packed_matrix().dump_tiles() << endl; -// cout << region1.width() << " x " << region1.height() << endl; - - size_t border_count = 0; - double border_sumsqr = 0; - for (size_t r = region1.min_y; r < region1.max_y; r++){ - for (size_t c = region1.min_x; c < region1.max_x; c++){ - if (!region1.object->get(c, r)){ - continue; - } - if ((c > 0 && matrix.get(c - 1, r)) || - (c + 1 < width && matrix.get(c + 1, r)) || - (r > 0 && matrix.get(c, r - 1)) || - (r + 1 < height && matrix.get(c, r + 1)) - ){ - border_count++; - border_sumsqr += calc.distance_squared(c, r); - } - } - } - - double distance = std::sqrt(border_sumsqr / border_count) / width; -// cout << "right = " << distance << endl; - if (distance > ARROW_MAX_DISTANCE){ - return false; - } - } - - // Verify bottom. - WaterfillObject region2; - if (!session->find_object_on_bit(region2, false, width - 1, height - 1)){ - return false; - } - - if (region0.area + region1.area + region2.area < 0.9 * object.area){ - return false; - } - -// cout << "good!" << endl; - - return true; -} -bool is_arrow_pointed_corner( - const PackedBinaryMatrix& matrix, - PackedBinaryMatrix& inverted -){ - size_t width = matrix.width(); - size_t height = matrix.height(); - - std::unique_ptr session = make_WaterfillSession(inverted); - - // Verify right edge. - { - size_t right_y = 0; - for (; right_y < height; right_y++){ - if (matrix.get(width - 1, right_y)){ - break; - } - } - - DistanceToLine calc( - 0, 0, - width - 1, right_y - ); - - WaterfillObject region0; - if (!session->find_object_on_bit(region0, true, width - 1, 0)){ - return false; - } - - size_t border_count = 0; - double border_sumsqr = 0; - for (size_t r = region0.min_y; r < region0.max_y; r++){ - for (size_t c = region0.min_x; c < region0.max_x; c++){ - if (!region0.object->get(c, r)){ - continue; - } - if ((c > 0 && matrix.get(c - 1, r)) || - (c + 1 < width && matrix.get(c + 1, r)) || - (r > 0 && matrix.get(c, r - 1)) || - (r + 1 < height && matrix.get(c, r + 1)) - ){ - border_count++; - border_sumsqr += calc.distance_squared(c, r); - } - } - } - - double distance = std::sqrt(border_sumsqr / border_count) / width; -// cout << "right = " << distance << endl; - if (distance > ARROW_MAX_DISTANCE){ - return false; - } - } - - // Verify left edge. - { - size_t bottom_x = 0; - for (; bottom_x < width; bottom_x++){ - if (matrix.get(bottom_x, height - 1)){ - break; - } - } - - DistanceToLine calc( - 0, 0, - bottom_x, height - 1 - ); - - WaterfillObject region1; - if (!session->find_object_on_bit(region1, true, 0, height - 1)){ - return false; - } - - size_t border_count = 0; - double border_sumsqr = 0; - for (size_t r = region1.min_y; r < region1.max_y; r++){ - for (size_t c = region1.min_x; c < region1.max_x; c++){ - if (!region1.object->get(c, r)){ - continue; - } - if ((c > 0 && matrix.get(c - 1, r)) || - (c + 1 < width && matrix.get(c + 1, r)) || - (r > 0 && matrix.get(c, r - 1)) || - (r + 1 < height && matrix.get(c, r + 1)) - ){ - border_count++; - border_sumsqr += calc.distance_squared(c, r); - } - } - } - - double distance = std::sqrt(border_sumsqr / border_count) / width; -// cout << "bottom = " << distance << endl; - if (distance > ARROW_MAX_DISTANCE){ - return false; - } - } - - return true; -} - - -bool is_arrow(const ImageViewRGB32& image, const WaterfillObject& object){ - double area_ratio = object.area_ratio(); - if (area_ratio < 0.35 || area_ratio > 0.55){ - return false; - } - double aspect_ratio = object.aspect_ratio(); - if (aspect_ratio < 0.5 || aspect_ratio > 2.0){ - return false; - } - - ImageRGB32 cropped = extract_box_reference(image, object).copy(); - - PackedBinaryMatrix matrix = object.packed_matrix(); - filter_by_mask(matrix, cropped, Color(0), true); - - - ImageStats stats = image_stats(cropped); - if (!is_white(stats, 500, 100)){ - return false; - } - - PackedBinaryMatrix inverted = matrix.copy(); - inverted.invert(); - -// static int c = 0; -// std::string file = "test-" + std::to_string(c++) + ".png"; -// cout << object.min_x << endl; -// cropped0.save(file); - - if (is_arrow_pointed_up(matrix, inverted, object)){ -// cout << "up" << endl; -// cropped0.save(file); - return true; - } - - if (is_arrow_pointed_corner(matrix, inverted)){ -// cout << "up" << endl; -// cropped0.save(file); - return true; - } - - return false; -} - - - -int8_t read_side(WaterfillSession& session, const ImageViewRGB32& image, uint8_t pixel_threshold){ - PackedBinaryMatrix matrix = compress_rgb32_to_binary_min( - image, pixel_threshold, pixel_threshold, pixel_threshold - ); - -// cout << "pixel_threshold = " << (int)pixel_threshold << endl; - session.set_source(matrix); - - auto finder = session.make_iterator(300); - WaterfillObject arrow; - WaterfillObject object; - size_t count = 0; - while (finder->find_next(object, true)){ - if (is_arrow(image, object)){ - count++; - arrow = object; - } - } -// cout << "count = " << count << endl; - if (count != 1){ - return -1; - } - -// cout << arrow.min_x << " | " << (size_t)image.width() / 3 << endl; - - return arrow.min_x < (size_t)image.width() / 3 - ? 0 - : 1; -} - -int8_t read_side(const ImageViewRGB32& image){ - auto session = make_WaterfillSession(); - int8_t ret; - if ((ret = read_side(*session, image, 160)) != -1) return ret; - if ((ret = read_side(*session, image, 176)) != -1) return ret; - if ((ret = read_side(*session, image, 192)) != -1) return ret; - if ((ret = read_side(*session, image, 208)) != -1) return ret; - if ((ret = read_side(*session, image, 224)) != -1) return ret; - return ret; -} - - - -} -} -} -} +/* Max Lair Detect Path Side + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/DistanceToLine.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonSwSh_MaxLair_Detect_PathSide.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + +const double ARROW_MAX_DISTANCE = 0.04; + +bool is_arrow_pointed_up( + const PackedBinaryMatrix& matrix, + PackedBinaryMatrix& inverted, + const WaterfillObject& object +){ + size_t width = matrix.width(); + size_t height = matrix.height(); + + std::unique_ptr session = make_WaterfillSession(inverted); + + // Verify left edge. + WaterfillObject region0; + { + size_t topL_x = 0; + for (; topL_x < width; topL_x++){ + if (matrix.get(topL_x, 0)){ + break; + } + } + size_t left_y = 0; + for (; left_y < height; left_y++){ + if (matrix.get(0, left_y)){ + break; + } + } + + DistanceToLine calc( + topL_x, 0, + 0, left_y + ); +// cout << "topL_x = " << topL_x << endl; +// cout << "left_y = " << left_y << endl; + + if (!session->find_object_on_bit(region0, true, 0, 0)){ + return false; + } +// PackedBinaryMatrix matrix0 = region0.packed_matrix(); +// cout << region0.packed_matrix().dump() << endl; + + size_t border_count = 0; + double border_sumsqr = 0; + for (size_t r = region0.min_y; r < region0.max_y; r++){ + for (size_t c = region0.min_x; c < region0.max_x; c++){ + if (!region0.object->get(c, r)){ + continue; + } + + if ((c > 0 && matrix.get(c - 1, r)) || + (c + 1 < width && matrix.get(c + 1, r)) || + (r > 0 && matrix.get(c, r - 1)) || + (r + 1 < height && matrix.get(c, r + 1)) + ){ + border_count++; + border_sumsqr += calc.distance_squared(c, r); + } + } + } + + double distance = std::sqrt(border_sumsqr / border_count) / width; +// cout << "left = " << distance << endl; + if (distance > ARROW_MAX_DISTANCE){ + return false; + } + } + + // Verify right edge. + WaterfillObject region1; + { + size_t topR_x = width - 1; + size_t right_y = 0; + for (; right_y < height; right_y++){ + if (matrix.get(topR_x, right_y)){ + break; + } + } + for (; topR_x > 0; topR_x--){ + if (matrix.get(topR_x, 0) == 1){ + break; + } + } + + DistanceToLine calc( + topR_x, 0, + width - 1, right_y + ); + +// cout << "width = " << width << endl; +// cout << "topR_x = " << topR_x << endl; +// cout << "right_y = " << right_y << endl; +// cout << inverted.dump() << endl; +// cout << inverted.dump_tiles() << endl; + + if (!session->find_object_on_bit(region1, true, width - 1, 0)){ + return false; + } +// cout << inverted.dump() << endl; +// cout << inverted.dump_tiles() << endl; + +// cout << region1.object.dump() << endl; +// cout << region1.packed_matrix().dump() << endl; +// cout << region1.packed_matrix().dump_tiles() << endl; +// cout << region1.width() << " x " << region1.height() << endl; + + size_t border_count = 0; + double border_sumsqr = 0; + for (size_t r = region1.min_y; r < region1.max_y; r++){ + for (size_t c = region1.min_x; c < region1.max_x; c++){ + if (!region1.object->get(c, r)){ + continue; + } + if ((c > 0 && matrix.get(c - 1, r)) || + (c + 1 < width && matrix.get(c + 1, r)) || + (r > 0 && matrix.get(c, r - 1)) || + (r + 1 < height && matrix.get(c, r + 1)) + ){ + border_count++; + border_sumsqr += calc.distance_squared(c, r); + } + } + } + + double distance = std::sqrt(border_sumsqr / border_count) / width; +// cout << "right = " << distance << endl; + if (distance > ARROW_MAX_DISTANCE){ + return false; + } + } + + // Verify bottom. + WaterfillObject region2; + if (!session->find_object_on_bit(region2, false, width - 1, height - 1)){ + return false; + } + + if (region0.area + region1.area + region2.area < 0.9 * object.area){ + return false; + } + +// cout << "good!" << endl; + + return true; +} +bool is_arrow_pointed_corner( + const PackedBinaryMatrix& matrix, + PackedBinaryMatrix& inverted +){ + size_t width = matrix.width(); + size_t height = matrix.height(); + + std::unique_ptr session = make_WaterfillSession(inverted); + + // Verify right edge. + { + size_t right_y = 0; + for (; right_y < height; right_y++){ + if (matrix.get(width - 1, right_y)){ + break; + } + } + + DistanceToLine calc( + 0, 0, + width - 1, right_y + ); + + WaterfillObject region0; + if (!session->find_object_on_bit(region0, true, width - 1, 0)){ + return false; + } + + size_t border_count = 0; + double border_sumsqr = 0; + for (size_t r = region0.min_y; r < region0.max_y; r++){ + for (size_t c = region0.min_x; c < region0.max_x; c++){ + if (!region0.object->get(c, r)){ + continue; + } + if ((c > 0 && matrix.get(c - 1, r)) || + (c + 1 < width && matrix.get(c + 1, r)) || + (r > 0 && matrix.get(c, r - 1)) || + (r + 1 < height && matrix.get(c, r + 1)) + ){ + border_count++; + border_sumsqr += calc.distance_squared(c, r); + } + } + } + + double distance = std::sqrt(border_sumsqr / border_count) / width; +// cout << "right = " << distance << endl; + if (distance > ARROW_MAX_DISTANCE){ + return false; + } + } + + // Verify left edge. + { + size_t bottom_x = 0; + for (; bottom_x < width; bottom_x++){ + if (matrix.get(bottom_x, height - 1)){ + break; + } + } + + DistanceToLine calc( + 0, 0, + bottom_x, height - 1 + ); + + WaterfillObject region1; + if (!session->find_object_on_bit(region1, true, 0, height - 1)){ + return false; + } + + size_t border_count = 0; + double border_sumsqr = 0; + for (size_t r = region1.min_y; r < region1.max_y; r++){ + for (size_t c = region1.min_x; c < region1.max_x; c++){ + if (!region1.object->get(c, r)){ + continue; + } + if ((c > 0 && matrix.get(c - 1, r)) || + (c + 1 < width && matrix.get(c + 1, r)) || + (r > 0 && matrix.get(c, r - 1)) || + (r + 1 < height && matrix.get(c, r + 1)) + ){ + border_count++; + border_sumsqr += calc.distance_squared(c, r); + } + } + } + + double distance = std::sqrt(border_sumsqr / border_count) / width; +// cout << "bottom = " << distance << endl; + if (distance > ARROW_MAX_DISTANCE){ + return false; + } + } + + return true; +} + + +bool is_arrow(const ImageViewRGB32& image, const WaterfillObject& object){ + double area_ratio = object.area_ratio(); + if (area_ratio < 0.35 || area_ratio > 0.55){ + return false; + } + double aspect_ratio = object.aspect_ratio(); + if (aspect_ratio < 0.5 || aspect_ratio > 2.0){ + return false; + } + + ImageRGB32 cropped = extract_box_reference(image, object).copy(); + + PackedBinaryMatrix matrix = object.packed_matrix(); + filter_by_mask(matrix, cropped, Color(0), true); + + + ImageStats stats = image_stats(cropped); + if (!is_white(stats, 500, 100)){ + return false; + } + + PackedBinaryMatrix inverted = matrix.copy(); + inverted.invert(); + +// static int c = 0; +// std::string file = "test-" + std::to_string(c++) + ".png"; +// cout << object.min_x << endl; +// cropped0.save(file); + + if (is_arrow_pointed_up(matrix, inverted, object)){ +// cout << "up" << endl; +// cropped0.save(file); + return true; + } + + if (is_arrow_pointed_corner(matrix, inverted)){ +// cout << "up" << endl; +// cropped0.save(file); + return true; + } + + return false; +} + + + +int8_t read_side(WaterfillSession& session, const ImageViewRGB32& image, uint8_t pixel_threshold){ + PackedBinaryMatrix matrix = compress_rgb32_to_binary_min( + image, pixel_threshold, pixel_threshold, pixel_threshold + ); + +// cout << "pixel_threshold = " << (int)pixel_threshold << endl; + session.set_source(matrix); + + auto finder = session.make_iterator(300); + WaterfillObject arrow; + WaterfillObject object; + size_t count = 0; + while (finder->find_next(object, true)){ + if (is_arrow(image, object)){ + count++; + arrow = object; + } + } +// cout << "count = " << count << endl; + if (count != 1){ + return -1; + } + +// cout << arrow.min_x << " | " << (size_t)image.width() / 3 << endl; + + return arrow.min_x < (size_t)image.width() / 3 + ? 0 + : 1; +} + +int8_t read_side(const ImageViewRGB32& image){ + auto session = make_WaterfillSession(); + int8_t ret; + if ((ret = read_side(*session, image, 160)) != -1) return ret; + if ((ret = read_side(*session, image, 176)) != -1) return ret; + if ((ret = read_side(*session, image, 192)) != -1) return ret; + if ((ret = read_side(*session, image, 208)) != -1) return ret; + if ((ret = read_side(*session, image, 224)) != -1) return ret; + return ret; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h index dfb08012e1..c5752627f3 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSide.h @@ -1,27 +1,27 @@ -/* Max Lair Detect Path Side - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSide_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSide_H - -#include -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -int8_t read_side(const ImageViewRGB32& image); - - -} -} -} -} -#endif +/* Max Lair Detect Path Side + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSide_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PathSide_H + +#include +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +int8_t read_side(const ImageViewRGB32& image); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.cpp index 7b0ca4501b..dcc99b72ca 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.cpp @@ -1,400 +1,400 @@ -/* Max Lair Pokemon Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" -#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ -using namespace Pokemon; - - -struct SpeciesReadDatabase{ - - static constexpr double CROPPED_MAX_ALPHA = 0.30; - static constexpr double CROPPED_ALPHA_SPREAD = 0.03; - - static constexpr double RETRY_ALPHA = 0.25; - - static constexpr double EXACT_MAX_ALPHA = 0.30; - static constexpr double EXACT_ALPHA_SPREAD = 0.02; - - - std::map> ocr_map; - std::map> sprite_map; - - std::unique_ptr name_reader; - std::unique_ptr sprite_reader; - std::unique_ptr exact_sprite_reader; - std::unique_ptr exact_leftsprite_reader; - - static SpeciesReadDatabase& instance(){ - static SpeciesReadDatabase data; - return data; - } - - SpeciesReadDatabase(){ - std::set ocr_set; - std::set sprite_set; - - for (const auto& item0 : maxlair_slugs()){ - const std::string& maxlair_slug = item0.first; - { - const std::string& slug = item0.second.name_slug; - ocr_map[slug].insert(maxlair_slug); - ocr_set.insert(slug); - } - for (const auto& slug : item0.second.sprite_slugs){ - sprite_map[slug].insert(maxlair_slug); - sprite_set.insert(slug); - } - } - - name_reader.reset(new PokemonNameReader(ocr_set)); - sprite_reader.reset(new PokemonSpriteMatcherCropped(&sprite_set)); - exact_sprite_reader.reset(new PokemonSpriteMatcherExact(&sprite_set)); - exact_leftsprite_reader.reset(new PokemonLeftSpriteMatcherExact(&sprite_set)); - } -}; - - - -std::string read_boss_sprite(VideoStream& stream){ - DenMonReader reader(stream.logger(), stream.overlay()); - DenMonReadResults results = reader.read(stream.video().snapshot()); - - std::string sprite_slug; - { - auto iter = results.slugs.results.begin(); - if (iter == results.slugs.results.end()){ - return ""; - } - sprite_slug = std::move(iter->second); - } - - const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); - auto iter = database.sprite_map.find(sprite_slug); - if (iter == database.sprite_map.end()){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Slug doesn't exist in sprite map: " + sprite_slug - ); - } - if (iter->second.empty()){ - throw InternalProgramError( - &stream.logger(), PA_CURRENT_FUNCTION, - "Sprite map is empty for slug: " + sprite_slug - ); - } - return *iter->second.begin(); -} - - -std::set read_pokemon_name( - Logger& logger, Language language, - OcrFailureWatchdog& ocr_watchdog, - const ImageViewRGB32& image, - double max_log10p -){ - const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); - -// OCR::MatchResult result = PokemonNameReader::instance().read_substring(language, image); -// image.save("test.png"); - OCR::StringMatchResult result = database.name_reader->read_substring( - logger, language, image, - OCR::BLACK_OR_WHITE_TEXT_FILTERS(), - 0.01, 0.50, - max_log10p - ); -// result.log(logger); - if (result.results.empty()){ - ocr_watchdog.push_result(false); - return {}; - } - ocr_watchdog.push_result(true); - - // Convert OCR slugs to MaxLair name slugs. - std::set ret; - for (const auto& hit : result.results){ - auto iter = database.ocr_map.find(hit.second.token); - if (iter == database.ocr_map.end()){ - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Slug doesn't exist in OCR map: " + hit.second.token - ); - } - for (const std::string& item : iter->second){ - ret.insert(item); - } - } - - return ret; -} - - -ImageMatch::ImageMatchResult read_pokemon_sprite_set( - Logger& logger, - const ImageViewRGB32& screen, - const ImageFloatBox& box, - bool allow_exact_match_fallback -){ - using namespace papkmnlib; - - const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); - const std::map& RENTALS = all_rental_pokemon(); - - // Try with cropped matcher. - ImageFloatBox large_box = box; - large_box.height += 0.002; -// large_box.width -= 0.010; -// large_box.x += 0.005; - ImageViewRGB32 image = extract_box_reference(screen, large_box); - -// image.save("test.png"); - - double max_alpha = SpeciesReadDatabase::CROPPED_MAX_ALPHA; - - ImageMatch::ImageMatchResult result = database.sprite_reader->match(image, SpeciesReadDatabase::CROPPED_ALPHA_SPREAD); -// result.log(logger, SpeciesReadDatabase::CROPPED_MAX_ALPHA); - - // Try with exact matcher. - if (allow_exact_match_fallback){ - if (result.results.size() != 1 || result.results.begin()->first > SpeciesReadDatabase::RETRY_ALPHA){ - logger.log("Retrying with exact sprite matcher..."); - max_alpha = SpeciesReadDatabase::EXACT_MAX_ALPHA; - result = database.exact_sprite_reader->match( - screen, box, - 5, - SpeciesReadDatabase::EXACT_ALPHA_SPREAD - ); - } - } - - // Convert slugs to MaxLair slugs. - std::multimap filtered; - for (auto& item : result.results){ - auto iter = database.sprite_map.find(item.second); - if (iter == database.sprite_map.end()){ - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Slug doesn't exist in sprite map: " + item.second - ); - } - if (iter->second.empty()){ - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Sprite map is empty for slug: " + item.second - ); - } -// item.second = *iter->second.begin(); - - // Include it only if it's a valid rental Pokemon. - const std::string& slug = *iter->second.begin(); - if (RENTALS.find(slug) != RENTALS.end()){ - filtered.emplace(item.first, slug); - } - } - result.results = std::move(filtered); - - result.log(logger, max_alpha); - result.clear_beyond_alpha(max_alpha); - - return result; -} - - - - -ImageMatch::ImageMatchResult read_pokemon_sprite_set_with_item( - Logger& logger, - const ImageViewRGB32& screen, const ImageFloatBox& box -){ - const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); - - // Try with cropped matcher. - ImageFloatBox large_box = box; - large_box.height += 0.002; - large_box.width -= 0.010; - large_box.x += 0.005; - ImageViewRGB32 image = extract_box_reference(screen, large_box); - - double max_alpha = SpeciesReadDatabase::CROPPED_MAX_ALPHA; - - ImageMatch::ImageMatchResult result = database.sprite_reader->match(image, SpeciesReadDatabase::CROPPED_ALPHA_SPREAD); -// result.results.clear(); -// result.log(logger, SpeciesReadDatabase::CROPPED_MAX_ALPHA); - - // Try with exact matcher. - if (result.results.empty() || result.results.begin()->first > SpeciesReadDatabase::RETRY_ALPHA){ - logger.log("Retrying with left-side exact sprite matcher..."); - max_alpha = SpeciesReadDatabase::EXACT_MAX_ALPHA; - ImageFloatBox half_box = box; - half_box.width /= 2; - result = database.exact_leftsprite_reader->match(screen, half_box, 5, SpeciesReadDatabase::EXACT_ALPHA_SPREAD); - } - - // Convert slugs to MaxLair slugs. - for (auto& item : result.results){ - auto iter = database.sprite_map.find(item.second); - if (iter == database.sprite_map.end()){ - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Slug doesn't exist in sprite map: " + item.second - ); - } - if (iter->second.empty()){ - throw InternalProgramError( - &logger, PA_CURRENT_FUNCTION, - "Sprite map is empty for slug: " + item.second - ); - } - item.second = *iter->second.begin(); - } - - result.log(logger, max_alpha); - result.clear_beyond_alpha(max_alpha); - - return result; -} -std::string read_pokemon_sprite_with_item( - Logger& logger, - const ImageViewRGB32& screen, const ImageFloatBox& box -){ - using namespace papkmnlib; - - ImageMatch::ImageMatchResult result = read_pokemon_sprite_set_with_item(logger, screen, box); - auto iter = result.results.begin(); - if (iter == result.results.end()){ - return ""; - } - if (iter->first > SpeciesReadDatabase::CROPPED_MAX_ALPHA){ - logger.log("No good sprite match found.", COLOR_RED); - return ""; - } - if (result.results.size() > 2){ - logger.log("Multiple \"ok\" sprite matches with no clear winner.", COLOR_RED); - return ""; - } - - const std::map& RENTALS = all_rental_pokemon(); - if (RENTALS.find(iter->second) == RENTALS.end()){ - logger.log("Read " + STRING_POKEMON + " sprite is not a valid rental.", COLOR_RED); - return ""; - } - - return std::move(iter->second); -} - - -std::string read_pokemon_name_sprite( - Logger& logger, - OcrFailureWatchdog& ocr_watchdog, - const ImageViewRGB32& screen, - const ImageFloatBox& sprite_box, - const ImageFloatBox& name_box, Language language, - bool allow_exact_match_fallback -){ - using namespace papkmnlib; - - const std::map& RENTALS = all_rental_pokemon(); - - ImageViewRGB32 image = extract_box_reference(screen, name_box); - - std::set ocr_slugs; - for (const std::string& slug : read_pokemon_name(logger, language, ocr_watchdog, image)){ - // Only include candidates that are valid rental Pokemon. - auto iter = RENTALS.find(slug); - if (iter != RENTALS.end()){ - ocr_slugs.insert(slug); - } - } - bool ocr_hit = !ocr_slugs.empty(); - bool ocr_unique = ocr_hit && ocr_slugs.size() == 1; -// if (!ocr_hit){ -// dump_image(logger, MODULE_NAME, "MaxLair-read_name_sprite", screen); -// } - - ImageMatch::ImageMatchResult result = read_pokemon_sprite_set( - logger, - screen, - sprite_box, - allow_exact_match_fallback - ); - auto iter = result.results.begin(); - bool sprite_hit = iter != result.results.end() && iter->first <= SpeciesReadDatabase::CROPPED_MAX_ALPHA; -// if (!sprite_hit || result.results.size() > 1){ -// dump_image(logger, MODULE_NAME, "MaxLair-read_name_sprite", screen); -// } - - // No hit on sprite. Use OCR. - if (!sprite_hit){ - std::string ret = ocr_unique ? *ocr_slugs.begin() : ""; - logger.log("Failed to read sprite. Using OCR result: " + ret, COLOR_RED); -// dump_image(logger, screen, "MaxLair-read_name_sprite"); - return ret; - } - - // No hit on OCR. Use sprite. - if (!ocr_hit){ - std::string ret = sprite_hit ? std::move(iter->second) : ""; - logger.log("Failed to read name. Using sprite result: " + ret, COLOR_RED); -// dump_image(logger, screen, "MaxLair-read_name_sprite"); - return ret; - } - - // If any are in common to both, pick the best one. - std::multimap common; - for (const auto& item : result.results){ - if (ocr_slugs.find(item.second) != ocr_slugs.end()){ - common.emplace(item.first, item.second); - } - } - if (!common.empty()){ - logger.log("Sprite and OCR agree. Picking best one: " + common.begin()->second, COLOR_BLUE); - return std::move(common.begin()->second); - } - - // This is where things get bad since OCR and sprites disagree. - dump_image(logger, MODULE_NAME, "MaxLair-read_name_sprite", screen); - - // If there is only one sprite match, use it. - if (result.results.size() == 1){ - logger.log("Sprite and OCR disagree. Attempt to arbitrate... Picking: " + result.results.begin()->second, COLOR_RED); - return std::move(result.results.begin()->second); - } - - // If there is only one OCR match, use it. - if (ocr_slugs.size() == 1){ - logger.log("Sprite and OCR disagree. Attempt to arbitrate... Picking: " + *ocr_slugs.begin(), COLOR_RED); - return *ocr_slugs.begin(); - } - - // At this point, both OCR and sprites have multiple items in completely disjoint sets. - logger.log("Sprite and OCR disagree so badly that no arbitration will be attempted.", COLOR_RED); - return ""; -} - - - - - -} -} -} -} +/* Max Lair Pokemon Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh/Inference/PokemonSwSh_PokemonSpriteReader.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" +#include "PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ +using namespace Pokemon; + + +struct SpeciesReadDatabase{ + + static constexpr double CROPPED_MAX_ALPHA = 0.30; + static constexpr double CROPPED_ALPHA_SPREAD = 0.03; + + static constexpr double RETRY_ALPHA = 0.25; + + static constexpr double EXACT_MAX_ALPHA = 0.30; + static constexpr double EXACT_ALPHA_SPREAD = 0.02; + + + std::map> ocr_map; + std::map> sprite_map; + + std::unique_ptr name_reader; + std::unique_ptr sprite_reader; + std::unique_ptr exact_sprite_reader; + std::unique_ptr exact_leftsprite_reader; + + static SpeciesReadDatabase& instance(){ + static SpeciesReadDatabase data; + return data; + } + + SpeciesReadDatabase(){ + std::set ocr_set; + std::set sprite_set; + + for (const auto& item0 : maxlair_slugs()){ + const std::string& maxlair_slug = item0.first; + { + const std::string& slug = item0.second.name_slug; + ocr_map[slug].insert(maxlair_slug); + ocr_set.insert(slug); + } + for (const auto& slug : item0.second.sprite_slugs){ + sprite_map[slug].insert(maxlair_slug); + sprite_set.insert(slug); + } + } + + name_reader.reset(new PokemonNameReader(ocr_set)); + sprite_reader.reset(new PokemonSpriteMatcherCropped(&sprite_set)); + exact_sprite_reader.reset(new PokemonSpriteMatcherExact(&sprite_set)); + exact_leftsprite_reader.reset(new PokemonLeftSpriteMatcherExact(&sprite_set)); + } +}; + + + +std::string read_boss_sprite(VideoStream& stream){ + DenMonReader reader(stream.logger(), stream.overlay()); + DenMonReadResults results = reader.read(stream.video().snapshot()); + + std::string sprite_slug; + { + auto iter = results.slugs.results.begin(); + if (iter == results.slugs.results.end()){ + return ""; + } + sprite_slug = std::move(iter->second); + } + + const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); + auto iter = database.sprite_map.find(sprite_slug); + if (iter == database.sprite_map.end()){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Slug doesn't exist in sprite map: " + sprite_slug + ); + } + if (iter->second.empty()){ + throw InternalProgramError( + &stream.logger(), PA_CURRENT_FUNCTION, + "Sprite map is empty for slug: " + sprite_slug + ); + } + return *iter->second.begin(); +} + + +std::set read_pokemon_name( + Logger& logger, Language language, + OcrFailureWatchdog& ocr_watchdog, + const ImageViewRGB32& image, + double max_log10p +){ + const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); + +// OCR::MatchResult result = PokemonNameReader::instance().read_substring(language, image); +// image.save("test.png"); + OCR::StringMatchResult result = database.name_reader->read_substring( + logger, language, image, + OCR::BLACK_OR_WHITE_TEXT_FILTERS(), + 0.01, 0.50, + max_log10p + ); +// result.log(logger); + if (result.results.empty()){ + ocr_watchdog.push_result(false); + return {}; + } + ocr_watchdog.push_result(true); + + // Convert OCR slugs to MaxLair name slugs. + std::set ret; + for (const auto& hit : result.results){ + auto iter = database.ocr_map.find(hit.second.token); + if (iter == database.ocr_map.end()){ + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Slug doesn't exist in OCR map: " + hit.second.token + ); + } + for (const std::string& item : iter->second){ + ret.insert(item); + } + } + + return ret; +} + + +ImageMatch::ImageMatchResult read_pokemon_sprite_set( + Logger& logger, + const ImageViewRGB32& screen, + const ImageFloatBox& box, + bool allow_exact_match_fallback +){ + using namespace papkmnlib; + + const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); + const std::map& RENTALS = all_rental_pokemon(); + + // Try with cropped matcher. + ImageFloatBox large_box = box; + large_box.height += 0.002; +// large_box.width -= 0.010; +// large_box.x += 0.005; + ImageViewRGB32 image = extract_box_reference(screen, large_box); + +// image.save("test.png"); + + double max_alpha = SpeciesReadDatabase::CROPPED_MAX_ALPHA; + + ImageMatch::ImageMatchResult result = database.sprite_reader->match(image, SpeciesReadDatabase::CROPPED_ALPHA_SPREAD); +// result.log(logger, SpeciesReadDatabase::CROPPED_MAX_ALPHA); + + // Try with exact matcher. + if (allow_exact_match_fallback){ + if (result.results.size() != 1 || result.results.begin()->first > SpeciesReadDatabase::RETRY_ALPHA){ + logger.log("Retrying with exact sprite matcher..."); + max_alpha = SpeciesReadDatabase::EXACT_MAX_ALPHA; + result = database.exact_sprite_reader->match( + screen, box, + 5, + SpeciesReadDatabase::EXACT_ALPHA_SPREAD + ); + } + } + + // Convert slugs to MaxLair slugs. + std::multimap filtered; + for (auto& item : result.results){ + auto iter = database.sprite_map.find(item.second); + if (iter == database.sprite_map.end()){ + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Slug doesn't exist in sprite map: " + item.second + ); + } + if (iter->second.empty()){ + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Sprite map is empty for slug: " + item.second + ); + } +// item.second = *iter->second.begin(); + + // Include it only if it's a valid rental Pokemon. + const std::string& slug = *iter->second.begin(); + if (RENTALS.find(slug) != RENTALS.end()){ + filtered.emplace(item.first, slug); + } + } + result.results = std::move(filtered); + + result.log(logger, max_alpha); + result.clear_beyond_alpha(max_alpha); + + return result; +} + + + + +ImageMatch::ImageMatchResult read_pokemon_sprite_set_with_item( + Logger& logger, + const ImageViewRGB32& screen, const ImageFloatBox& box +){ + const SpeciesReadDatabase& database = SpeciesReadDatabase::instance(); + + // Try with cropped matcher. + ImageFloatBox large_box = box; + large_box.height += 0.002; + large_box.width -= 0.010; + large_box.x += 0.005; + ImageViewRGB32 image = extract_box_reference(screen, large_box); + + double max_alpha = SpeciesReadDatabase::CROPPED_MAX_ALPHA; + + ImageMatch::ImageMatchResult result = database.sprite_reader->match(image, SpeciesReadDatabase::CROPPED_ALPHA_SPREAD); +// result.results.clear(); +// result.log(logger, SpeciesReadDatabase::CROPPED_MAX_ALPHA); + + // Try with exact matcher. + if (result.results.empty() || result.results.begin()->first > SpeciesReadDatabase::RETRY_ALPHA){ + logger.log("Retrying with left-side exact sprite matcher..."); + max_alpha = SpeciesReadDatabase::EXACT_MAX_ALPHA; + ImageFloatBox half_box = box; + half_box.width /= 2; + result = database.exact_leftsprite_reader->match(screen, half_box, 5, SpeciesReadDatabase::EXACT_ALPHA_SPREAD); + } + + // Convert slugs to MaxLair slugs. + for (auto& item : result.results){ + auto iter = database.sprite_map.find(item.second); + if (iter == database.sprite_map.end()){ + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Slug doesn't exist in sprite map: " + item.second + ); + } + if (iter->second.empty()){ + throw InternalProgramError( + &logger, PA_CURRENT_FUNCTION, + "Sprite map is empty for slug: " + item.second + ); + } + item.second = *iter->second.begin(); + } + + result.log(logger, max_alpha); + result.clear_beyond_alpha(max_alpha); + + return result; +} +std::string read_pokemon_sprite_with_item( + Logger& logger, + const ImageViewRGB32& screen, const ImageFloatBox& box +){ + using namespace papkmnlib; + + ImageMatch::ImageMatchResult result = read_pokemon_sprite_set_with_item(logger, screen, box); + auto iter = result.results.begin(); + if (iter == result.results.end()){ + return ""; + } + if (iter->first > SpeciesReadDatabase::CROPPED_MAX_ALPHA){ + logger.log("No good sprite match found.", COLOR_RED); + return ""; + } + if (result.results.size() > 2){ + logger.log("Multiple \"ok\" sprite matches with no clear winner.", COLOR_RED); + return ""; + } + + const std::map& RENTALS = all_rental_pokemon(); + if (RENTALS.find(iter->second) == RENTALS.end()){ + logger.log("Read " + STRING_POKEMON + " sprite is not a valid rental.", COLOR_RED); + return ""; + } + + return std::move(iter->second); +} + + +std::string read_pokemon_name_sprite( + Logger& logger, + OcrFailureWatchdog& ocr_watchdog, + const ImageViewRGB32& screen, + const ImageFloatBox& sprite_box, + const ImageFloatBox& name_box, Language language, + bool allow_exact_match_fallback +){ + using namespace papkmnlib; + + const std::map& RENTALS = all_rental_pokemon(); + + ImageViewRGB32 image = extract_box_reference(screen, name_box); + + std::set ocr_slugs; + for (const std::string& slug : read_pokemon_name(logger, language, ocr_watchdog, image)){ + // Only include candidates that are valid rental Pokemon. + auto iter = RENTALS.find(slug); + if (iter != RENTALS.end()){ + ocr_slugs.insert(slug); + } + } + bool ocr_hit = !ocr_slugs.empty(); + bool ocr_unique = ocr_hit && ocr_slugs.size() == 1; +// if (!ocr_hit){ +// dump_image(logger, MODULE_NAME, "MaxLair-read_name_sprite", screen); +// } + + ImageMatch::ImageMatchResult result = read_pokemon_sprite_set( + logger, + screen, + sprite_box, + allow_exact_match_fallback + ); + auto iter = result.results.begin(); + bool sprite_hit = iter != result.results.end() && iter->first <= SpeciesReadDatabase::CROPPED_MAX_ALPHA; +// if (!sprite_hit || result.results.size() > 1){ +// dump_image(logger, MODULE_NAME, "MaxLair-read_name_sprite", screen); +// } + + // No hit on sprite. Use OCR. + if (!sprite_hit){ + std::string ret = ocr_unique ? *ocr_slugs.begin() : ""; + logger.log("Failed to read sprite. Using OCR result: " + ret, COLOR_RED); +// dump_image(logger, screen, "MaxLair-read_name_sprite"); + return ret; + } + + // No hit on OCR. Use sprite. + if (!ocr_hit){ + std::string ret = sprite_hit ? std::move(iter->second) : ""; + logger.log("Failed to read name. Using sprite result: " + ret, COLOR_RED); +// dump_image(logger, screen, "MaxLair-read_name_sprite"); + return ret; + } + + // If any are in common to both, pick the best one. + std::multimap common; + for (const auto& item : result.results){ + if (ocr_slugs.find(item.second) != ocr_slugs.end()){ + common.emplace(item.first, item.second); + } + } + if (!common.empty()){ + logger.log("Sprite and OCR agree. Picking best one: " + common.begin()->second, COLOR_BLUE); + return std::move(common.begin()->second); + } + + // This is where things get bad since OCR and sprites disagree. + dump_image(logger, MODULE_NAME, "MaxLair-read_name_sprite", screen); + + // If there is only one sprite match, use it. + if (result.results.size() == 1){ + logger.log("Sprite and OCR disagree. Attempt to arbitrate... Picking: " + result.results.begin()->second, COLOR_RED); + return std::move(result.results.begin()->second); + } + + // If there is only one OCR match, use it. + if (ocr_slugs.size() == 1){ + logger.log("Sprite and OCR disagree. Attempt to arbitrate... Picking: " + *ocr_slugs.begin(), COLOR_RED); + return *ocr_slugs.begin(); + } + + // At this point, both OCR and sprites have multiple items in completely disjoint sets. + logger.log("Sprite and OCR disagree so badly that no arbitration will be attempted.", COLOR_RED); + return ""; +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h index e05c5c8553..01ec990a50 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h @@ -1,59 +1,59 @@ -/* Max Lair Pokemon Reader - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonReader_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonReader_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/FailureWatchdog.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -std::string read_boss_sprite(VideoStream& stream); - - -// OCR the Pokemon name and return all possible candidates. -std::set read_pokemon_name( - Logger& logger, Language language, - OcrFailureWatchdog& ocr_watchdog, - const ImageViewRGB32& image, - double max_log10p = -1.4 -); - - -// Read a Pokemon sprite. The sprite may be partially obstructed -// on the right side by an item. -std::string read_pokemon_sprite_with_item( - Logger& logger, - const ImageViewRGB32& screen, const ImageFloatBox& box -); - - - -// Use both OCR and sprite to read the Pokemon. It will try to -// arbitrate conflicts. -std::string read_pokemon_name_sprite( - Logger& logger, - OcrFailureWatchdog& ocr_watchdog, - const ImageViewRGB32& screen, - const ImageFloatBox& sprite_box, - const ImageFloatBox& name_box, Language language, - bool allow_exact_match_fallback -); - - - -} -} -} -} -#endif +/* Max Lair Pokemon Reader + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonReader_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonReader_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/FailureWatchdog.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +std::string read_boss_sprite(VideoStream& stream); + + +// OCR the Pokemon name and return all possible candidates. +std::set read_pokemon_name( + Logger& logger, Language language, + OcrFailureWatchdog& ocr_watchdog, + const ImageViewRGB32& image, + double max_log10p = -1.4 +); + + +// Read a Pokemon sprite. The sprite may be partially obstructed +// on the right side by an item. +std::string read_pokemon_sprite_with_item( + Logger& logger, + const ImageViewRGB32& screen, const ImageFloatBox& box +); + + + +// Use both OCR and sprite to read the Pokemon. It will try to +// arbitrate conflicts. +std::string read_pokemon_name_sprite( + Logger& logger, + OcrFailureWatchdog& ocr_watchdog, + const ImageViewRGB32& screen, + const ImageFloatBox& sprite_box, + const ImageFloatBox& name_box, Language language, + bool allow_exact_match_fallback +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.cpp index 25a3c38650..9d0363ddaf 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.cpp @@ -1,145 +1,145 @@ -/* Max Lair Detect Pokemon Select Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" -#include "PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -PokemonSelectMenuDetector::PokemonSelectMenuDetector(bool stop_no_detect) - : VisualInferenceCallback("PokemonSelectMenuDetector") - , m_stop_on_no_detect(stop_no_detect) - , m_box0(0.02, 0.02, 0.40, 0.04) -// , m_box1(overlay, 0.09, 0.18, 0.30, 0.10) - , m_box1(0.10, 0.18, 0.27, 0.12) - , m_box2(0.50, 0.02, 0.15, 0.03) - , m_box3(0.55, 0.07, 0.10, 0.05) -// , m_box4(overlay, 0.87, 0.17, 0.03, 0.20) -// , m_box5(overlay, 0.87, 0.43, 0.03, 0.20) -// , m_box6(overlay, 0.87, 0.69, 0.03, 0.20) - , m_select0(0.630, 0.270 + 0*0.258, 0.030, 0.100) - , m_select1(0.630, 0.270 + 1*0.258, 0.030, 0.100) - , m_select2(0.630, 0.270 + 2*0.258, 0.030, 0.100) -{} -void PokemonSelectMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_box0); - items.add(COLOR_RED, m_box1); - items.add(COLOR_RED, m_box2); - items.add(COLOR_RED, m_box3); - items.add(COLOR_RED, m_select0); - items.add(COLOR_RED, m_select1); - items.add(COLOR_RED, m_select2); -} -bool PokemonSelectMenuDetector::is_pink(const ImageStats& stats){ - if (stats.average.sum() < 400){ - return false; - } - return is_solid(stats, {0.448935, 0.176565, 0.3745}); -} -bool PokemonSelectMenuDetector::detect(const ImageViewRGB32& screen) const{ - ImageStats box0 = image_stats(extract_box_reference(screen, m_box0)); - if (!is_pink(box0)) return false; - ImageStats box1 = image_stats(extract_box_reference(screen, m_box1)); - if (!is_pink(box1)) return false; - ImageStats box2 = image_stats(extract_box_reference(screen, m_box2)); - if (!is_solid(box2, {0.53822, 0.077108, 0.384672})) return false; - ImageStats box3 = image_stats(extract_box_reference(screen, m_box3)); -// cout << box3.average << box3.stddev << endl; - if (!is_solid(box3, {0.316905, 0.339245, 0.34385})) return false; -// ImageStats box4 = pixel_stats(extract_box(screen, m_box4)); -// if (!is_white(box4)) return false; -// ImageStats box5 = pixel_stats(extract_box(screen, m_box5)); -// if (!is_white(box5)) return false; -// ImageStats box6 = pixel_stats(extract_box(screen, m_box6)); -// if (!is_white(box6)) return false; - - if (euclidean_distance(box0.average, box1.average) > 10) return false; -// if (euclidean_distance(box0.average, box2.average) > 10) return false; -// if (euclidean_distance(box3.average, box4.average) > 10) return false; -// if (euclidean_distance(box3.average, box5.average) > 10) return false; -/// if (euclidean_distance(box3.average, box6.average) > 10) return false; - - double select0 = image_average(extract_box_reference(screen, m_select0)).sum(); - if (select0 < 200) return true; -// double select1 = image_average(extract_box(screen, m_select1)).sum(); -// if (select1 < 200) return true; -// double select2 = image_average(extract_box(screen, m_select2)).sum(); -// if (select2 < 200) return true; - return false; -} -bool PokemonSelectMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return m_stop_on_no_detect - ? !detect(frame) - : detect(frame); -} - - -PokemonSelectMenuReader::PokemonSelectMenuReader( - Logger& logger, - VideoOverlay& overlay, - Language language, - OcrFailureWatchdog& ocr_watchdog -) - : m_logger(logger) - , m_language(language) - , m_ocr_watchdog(ocr_watchdog) - , m_sprite0(overlay, {0.481, 0.178 + 0*0.258, 0.071, 0.103}) - , m_sprite1(overlay, {0.481, 0.178 + 1*0.258, 0.071, 0.103}) - , m_sprite2(overlay, {0.481, 0.178 + 2*0.258, 0.071, 0.103}) - , m_name0(overlay, {0.485, 0.285 + 0*0.258, 0.180, 0.045}) - , m_name1(overlay, {0.485, 0.285 + 1*0.258, 0.180, 0.045}) - , m_name2(overlay, {0.485, 0.285 + 2*0.258, 0.180, 0.045}) - , m_player0(overlay, {0.200, 0.335 + 0*0.090, 0.200, 0.060}) - , m_player1(overlay, {0.200, 0.335 + 1*0.090, 0.200, 0.060}) - , m_player2(overlay, {0.200, 0.335 + 2*0.090, 0.200, 0.060}) - , m_player3(overlay, {0.200, 0.335 + 3*0.090, 0.200, 0.060}) -{} -int8_t PokemonSelectMenuReader::who_is_selecting(const ImageViewRGB32& screen) const{ -// cout << slot0.average << ", " << slot0.stddev << endl; - ImageStats slot3 = image_stats(extract_box_reference(screen, m_player3)); - if (slot3.stddev.sum() > 30) return 3; - ImageStats slot2 = image_stats(extract_box_reference(screen, m_player2)); - if (slot2.stddev.sum() > 30) return 2; - ImageStats slot1 = image_stats(extract_box_reference(screen, m_player1)); - if (slot1.stddev.sum() > 30) return 1; - ImageStats slot0 = image_stats(extract_box_reference(screen, m_player0)); - if (slot0.stddev.sum() > 30) return 0; - return -1; -} -std::string PokemonSelectMenuReader::read_option(const ImageViewRGB32& screen, size_t index){ - switch (index){ - case 0: return read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite0, m_name0, m_language, true); - case 1: return read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite1, m_name1, m_language, true); - case 2: return read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite2, m_name2, m_language, true); - } - return ""; -} - - - - - - - - - - -} -} -} -} +/* Max Lair Detect Pokemon Select Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" +#include "PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +PokemonSelectMenuDetector::PokemonSelectMenuDetector(bool stop_no_detect) + : VisualInferenceCallback("PokemonSelectMenuDetector") + , m_stop_on_no_detect(stop_no_detect) + , m_box0(0.02, 0.02, 0.40, 0.04) +// , m_box1(overlay, 0.09, 0.18, 0.30, 0.10) + , m_box1(0.10, 0.18, 0.27, 0.12) + , m_box2(0.50, 0.02, 0.15, 0.03) + , m_box3(0.55, 0.07, 0.10, 0.05) +// , m_box4(overlay, 0.87, 0.17, 0.03, 0.20) +// , m_box5(overlay, 0.87, 0.43, 0.03, 0.20) +// , m_box6(overlay, 0.87, 0.69, 0.03, 0.20) + , m_select0(0.630, 0.270 + 0*0.258, 0.030, 0.100) + , m_select1(0.630, 0.270 + 1*0.258, 0.030, 0.100) + , m_select2(0.630, 0.270 + 2*0.258, 0.030, 0.100) +{} +void PokemonSelectMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_box0); + items.add(COLOR_RED, m_box1); + items.add(COLOR_RED, m_box2); + items.add(COLOR_RED, m_box3); + items.add(COLOR_RED, m_select0); + items.add(COLOR_RED, m_select1); + items.add(COLOR_RED, m_select2); +} +bool PokemonSelectMenuDetector::is_pink(const ImageStats& stats){ + if (stats.average.sum() < 400){ + return false; + } + return is_solid(stats, {0.448935, 0.176565, 0.3745}); +} +bool PokemonSelectMenuDetector::detect(const ImageViewRGB32& screen) const{ + ImageStats box0 = image_stats(extract_box_reference(screen, m_box0)); + if (!is_pink(box0)) return false; + ImageStats box1 = image_stats(extract_box_reference(screen, m_box1)); + if (!is_pink(box1)) return false; + ImageStats box2 = image_stats(extract_box_reference(screen, m_box2)); + if (!is_solid(box2, {0.53822, 0.077108, 0.384672})) return false; + ImageStats box3 = image_stats(extract_box_reference(screen, m_box3)); +// cout << box3.average << box3.stddev << endl; + if (!is_solid(box3, {0.316905, 0.339245, 0.34385})) return false; +// ImageStats box4 = pixel_stats(extract_box(screen, m_box4)); +// if (!is_white(box4)) return false; +// ImageStats box5 = pixel_stats(extract_box(screen, m_box5)); +// if (!is_white(box5)) return false; +// ImageStats box6 = pixel_stats(extract_box(screen, m_box6)); +// if (!is_white(box6)) return false; + + if (euclidean_distance(box0.average, box1.average) > 10) return false; +// if (euclidean_distance(box0.average, box2.average) > 10) return false; +// if (euclidean_distance(box3.average, box4.average) > 10) return false; +// if (euclidean_distance(box3.average, box5.average) > 10) return false; +/// if (euclidean_distance(box3.average, box6.average) > 10) return false; + + double select0 = image_average(extract_box_reference(screen, m_select0)).sum(); + if (select0 < 200) return true; +// double select1 = image_average(extract_box(screen, m_select1)).sum(); +// if (select1 < 200) return true; +// double select2 = image_average(extract_box(screen, m_select2)).sum(); +// if (select2 < 200) return true; + return false; +} +bool PokemonSelectMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return m_stop_on_no_detect + ? !detect(frame) + : detect(frame); +} + + +PokemonSelectMenuReader::PokemonSelectMenuReader( + Logger& logger, + VideoOverlay& overlay, + Language language, + OcrFailureWatchdog& ocr_watchdog +) + : m_logger(logger) + , m_language(language) + , m_ocr_watchdog(ocr_watchdog) + , m_sprite0(overlay, {0.481, 0.178 + 0*0.258, 0.071, 0.103}) + , m_sprite1(overlay, {0.481, 0.178 + 1*0.258, 0.071, 0.103}) + , m_sprite2(overlay, {0.481, 0.178 + 2*0.258, 0.071, 0.103}) + , m_name0(overlay, {0.485, 0.285 + 0*0.258, 0.180, 0.045}) + , m_name1(overlay, {0.485, 0.285 + 1*0.258, 0.180, 0.045}) + , m_name2(overlay, {0.485, 0.285 + 2*0.258, 0.180, 0.045}) + , m_player0(overlay, {0.200, 0.335 + 0*0.090, 0.200, 0.060}) + , m_player1(overlay, {0.200, 0.335 + 1*0.090, 0.200, 0.060}) + , m_player2(overlay, {0.200, 0.335 + 2*0.090, 0.200, 0.060}) + , m_player3(overlay, {0.200, 0.335 + 3*0.090, 0.200, 0.060}) +{} +int8_t PokemonSelectMenuReader::who_is_selecting(const ImageViewRGB32& screen) const{ +// cout << slot0.average << ", " << slot0.stddev << endl; + ImageStats slot3 = image_stats(extract_box_reference(screen, m_player3)); + if (slot3.stddev.sum() > 30) return 3; + ImageStats slot2 = image_stats(extract_box_reference(screen, m_player2)); + if (slot2.stddev.sum() > 30) return 2; + ImageStats slot1 = image_stats(extract_box_reference(screen, m_player1)); + if (slot1.stddev.sum() > 30) return 1; + ImageStats slot0 = image_stats(extract_box_reference(screen, m_player0)); + if (slot0.stddev.sum() > 30) return 0; + return -1; +} +std::string PokemonSelectMenuReader::read_option(const ImageViewRGB32& screen, size_t index){ + switch (index){ + case 0: return read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite0, m_name0, m_language, true); + case 1: return read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite1, m_name1, m_language, true); + case 2: return read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite2, m_name2, m_language, true); + } + return ""; +} + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h index 3e5ed2b333..03b4a25c0b 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h @@ -1,99 +1,99 @@ -/* Max Lair Detect Pokemon Select Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSelectMenu_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSelectMenu_H - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/FailureWatchdog.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ - struct ImageStats; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class PokemonSelectMenuDetector : public VisualInferenceCallback{ -public: - PokemonSelectMenuDetector(bool stop_no_detect); - - bool detect(const ImageViewRGB32& screen) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - static bool is_pink(const ImageStats& stats); - - -private: - bool m_stop_on_no_detect; - ImageFloatBox m_box0; - ImageFloatBox m_box1; - ImageFloatBox m_box2; - ImageFloatBox m_box3; -// ImageFloatBox m_box4; -// ImageFloatBox m_box5; -// ImageFloatBox m_box6; - ImageFloatBox m_select0; - ImageFloatBox m_select1; - ImageFloatBox m_select2; -}; - - - -struct PokemonSelectMenuState{ - // Index of your current selection. - // -1 means it's not your turn to choose. - int index = -1; - - // Pokemon selection options. - std::string option[3]; -}; - -class PokemonSelectMenuReader{ -public: - PokemonSelectMenuReader( - Logger& logger, - VideoOverlay& overlay, - Language language, - OcrFailureWatchdog& ocr_watchdog - ); - - int8_t who_is_selecting(const ImageViewRGB32& screen) const; - - std::string read_option(const ImageViewRGB32& screen, size_t index); -// void read_options(const ImageViewRGB32& screen, std::string option[3]); - - -private: - Logger& m_logger; - Language m_language; - OcrFailureWatchdog& m_ocr_watchdog; - OverlayBoxScope m_sprite0; - OverlayBoxScope m_sprite1; - OverlayBoxScope m_sprite2; - OverlayBoxScope m_name0; - OverlayBoxScope m_name1; - OverlayBoxScope m_name2; - OverlayBoxScope m_player0; - OverlayBoxScope m_player1; - OverlayBoxScope m_player2; - OverlayBoxScope m_player3; -}; - - - -} -} -} -} -#endif +/* Max Lair Detect Pokemon Select Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSelectMenu_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSelectMenu_H + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/FailureWatchdog.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ + struct ImageStats; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class PokemonSelectMenuDetector : public VisualInferenceCallback{ +public: + PokemonSelectMenuDetector(bool stop_no_detect); + + bool detect(const ImageViewRGB32& screen) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + static bool is_pink(const ImageStats& stats); + + +private: + bool m_stop_on_no_detect; + ImageFloatBox m_box0; + ImageFloatBox m_box1; + ImageFloatBox m_box2; + ImageFloatBox m_box3; +// ImageFloatBox m_box4; +// ImageFloatBox m_box5; +// ImageFloatBox m_box6; + ImageFloatBox m_select0; + ImageFloatBox m_select1; + ImageFloatBox m_select2; +}; + + + +struct PokemonSelectMenuState{ + // Index of your current selection. + // -1 means it's not your turn to choose. + int index = -1; + + // Pokemon selection options. + std::string option[3]; +}; + +class PokemonSelectMenuReader{ +public: + PokemonSelectMenuReader( + Logger& logger, + VideoOverlay& overlay, + Language language, + OcrFailureWatchdog& ocr_watchdog + ); + + int8_t who_is_selecting(const ImageViewRGB32& screen) const; + + std::string read_option(const ImageViewRGB32& screen, size_t index); +// void read_options(const ImageViewRGB32& screen, std::string option[3]); + + +private: + Logger& m_logger; + Language m_language; + OcrFailureWatchdog& m_ocr_watchdog; + OverlayBoxScope m_sprite0; + OverlayBoxScope m_sprite1; + OverlayBoxScope m_sprite2; + OverlayBoxScope m_name0; + OverlayBoxScope m_name1; + OverlayBoxScope m_name2; + OverlayBoxScope m_player0; + OverlayBoxScope m_player1; + OverlayBoxScope m_player2; + OverlayBoxScope m_player3; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.cpp index 6610bb8512..ab6d12978d 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.cpp @@ -1,176 +1,176 @@ -/* Max Lair Detect Pokemon Swap Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "Pokemon/Inference/Pokemon_ReadHpBar.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h" -#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" -#include "PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -PokemonSwapMenuDetector::PokemonSwapMenuDetector(bool stop_no_detect) - : VisualInferenceCallback("PokemonSwapMenuDetector") - , m_stop_on_no_detect(stop_no_detect) - , m_pink0(0.150, 0.015, 0.270, 0.050) - , m_pink1(0.100, 0.260, 0.270, 0.040) - , m_pink2(0.150, 0.700, 0.090, 0.150) - , m_white0(0.600, 0.015, 0.370, 0.040) - , m_white1(0.520, 0.130, 0.450, 0.050) -// , m_bottom(overlay, 0.35, 0.80, 0.10, 0.10) -// , m_box0(overlay, 0.87, 0.22, 0.03, 0.20) -// , m_box1(overlay, 0.87, 0.48, 0.03, 0.20) - , m_bottom_main(0.100, 0.970, 0.600, 0.020) - , m_bottom_right(0.920, 0.970, 0.070, 0.020) -{} -void PokemonSwapMenuDetector::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_pink0); - items.add(COLOR_RED, m_pink1); - items.add(COLOR_RED, m_pink2); - items.add(COLOR_RED, m_white0); - items.add(COLOR_RED, m_white1); - items.add(COLOR_RED, m_bottom_main); - items.add(COLOR_RED, m_bottom_right); -} -bool PokemonSwapMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - return m_stop_on_no_detect - ? !detect(frame) - : detect(frame); -} -bool PokemonSwapMenuDetector::detect(const ImageViewRGB32& screen) const{ - ImageStats pink0 = image_stats(extract_box_reference(screen, m_pink0)); - if (!is_solid(pink0, {0.448591, 0.176516, 0.374892}, 0.1, 20)) return false; - ImageStats pink1 = image_stats(extract_box_reference(screen, m_pink1)); - if (!is_solid(pink1, {0.448591, 0.176516, 0.374892}, 0.1, 20)) return false; - ImageStats pink2 = image_stats(extract_box_reference(screen, m_pink2)); - if (!is_solid(pink2, {0.464402, 0.156018, 0.379581}, 0.1, 20)) return false; - ImageStats white0 = image_stats(extract_box_reference(screen, m_white0)); -// cout << white0.average << ", " << white0.stddev << endl; - if (!is_solid(white0, {0.318115, 0.33587, 0.346015})) return false; - ImageStats white1 = image_stats(extract_box_reference(screen, m_white1)); -// cout << white.average << ", " << white.stddev << endl; - if (!is_solid(white1, {0.310994, 0.344503, 0.344503})) return false; -// ImageStats bottom = pixel_stats(extract_box(screen, m_bottom)); -// if (!is_white(bottom)) return false; -// ImageStats box0 = pixel_stats(extract_box(screen, m_box0)); -// if (!is_white(box0)) return false; -// ImageStats box1 = pixel_stats(extract_box(screen, m_box1)); -// if (!is_white(box1)) return false; - - ImageStats bottom_main = image_stats(extract_box_reference(screen, m_bottom_main)); -// cout << bottom_main.average << ", " << bottom_main.stddev << endl; - if (!is_black(bottom_main)){ - return false; - } - ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); -// cout << bottom_right.average << ", " << bottom_right.stddev << endl; - if (bottom_right.stddev.sum() < 30){ - return false; - } - -// cout << pink0.average << ", " << pink0.stddev << endl; -// cout << pink1.average << ", " << pink1.stddev << endl; - return true; -} - - - -PokemonSwapMenuReader::PokemonSwapMenuReader( - Logger& logger, - VideoOverlay& overlay, - Language language, - OcrFailureWatchdog& ocr_watchdog -) - : m_logger(logger) - , m_language(language), m_ocr_watchdog(ocr_watchdog) - , m_sprite0(overlay, {0.481, 0.235 + 0*0.258, 0.071, 0.103}) - , m_sprite1(overlay, {0.481, 0.235 + 1*0.258, 0.071, 0.103}) - , m_name0(overlay, {0.485, 0.335 + 0*0.258, 0.180, 0.045}) - , m_name1(overlay, {0.485, 0.335 + 1*0.258, 0.180, 0.045}) - , m_select0(overlay, {0.630, 0.320 + 0*0.258, 0.030, 0.100}) - , m_select1(overlay, {0.630, 0.320 + 1*0.258, 0.030, 0.100}) - , m_pp0(overlay, {0.900, 0.207 + 0*0.060, 0.070, 0.045}) - , m_pp1(overlay, {0.900, 0.207 + 1*0.060, 0.070, 0.045}) - , m_pp2(overlay, {0.900, 0.207 + 2*0.060, 0.070, 0.045}) - , m_pp3(overlay, {0.900, 0.207 + 3*0.060, 0.070, 0.045}) - , m_hp0(overlay, {0.226, 0.3435 + 0*0.089, 0.112, 0.005}) - , m_hp1(overlay, {0.226, 0.3435 + 1*0.089, 0.112, 0.005}) - , m_hp2(overlay, {0.226, 0.3435 + 2*0.089, 0.112, 0.005}) - , m_hp3(overlay, {0.226, 0.3435 + 3*0.089, 0.112, 0.005}) -{} -bool PokemonSwapMenuReader::my_turn(const ImageViewRGB32& screen){ - double box0 = image_average(extract_box_reference(screen, m_select0)).sum(); - if (box0 < 200) return true; - double box1 = image_average(extract_box_reference(screen, m_select1)).sum(); - if (box1 < 200) return true; - return false; -} -void PokemonSwapMenuReader::read_options(const ImageViewRGB32& screen, std::string option[2]){ - option[0] = read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite0, m_name0, m_language, true); - option[1] = read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite1, m_name1, m_language, true); -} - -void PokemonSwapMenuReader::read_hp(const ImageViewRGB32& screen, double hp[4]){ - hp[0] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp0)); - hp[1] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp1)); - hp[2] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp2)); - hp[3] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp3)); - if (hp[0] < 0 || hp[1] < 0 || hp[2] < 0 || hp[3] < 0){ - dump_image(m_logger, MODULE_NAME, "PokemonSwapMenuReader-read_hp", screen); - } -} -void PokemonSwapMenuReader::read_pp(const ImageViewRGB32& screen, int8_t pp[4]){ - pp[0] = read_pp_text(m_logger, extract_box_reference(screen, m_pp0)); - pp[1] = read_pp_text(m_logger, extract_box_reference(screen, m_pp1)); - pp[2] = read_pp_text(m_logger, extract_box_reference(screen, m_pp2)); - pp[3] = read_pp_text(m_logger, extract_box_reference(screen, m_pp3)); - if (pp[0] < 0 && pp[1] < 0 && pp[2] < 0 && pp[3] < 0){ - dump_image(m_logger, MODULE_NAME, "PokemonSwapMenuReader-read_pp", screen); - return; - } -} - - - - - - - - - - - - - - - - - - - - - - - - - -} -} -} -} +/* Max Lair Detect Pokemon Swap Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "Pokemon/Inference/Pokemon_ReadHpBar.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_HPPP.h" +#include "PokemonSwSh_MaxLair_Detect_PokemonReader.h" +#include "PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +PokemonSwapMenuDetector::PokemonSwapMenuDetector(bool stop_no_detect) + : VisualInferenceCallback("PokemonSwapMenuDetector") + , m_stop_on_no_detect(stop_no_detect) + , m_pink0(0.150, 0.015, 0.270, 0.050) + , m_pink1(0.100, 0.260, 0.270, 0.040) + , m_pink2(0.150, 0.700, 0.090, 0.150) + , m_white0(0.600, 0.015, 0.370, 0.040) + , m_white1(0.520, 0.130, 0.450, 0.050) +// , m_bottom(overlay, 0.35, 0.80, 0.10, 0.10) +// , m_box0(overlay, 0.87, 0.22, 0.03, 0.20) +// , m_box1(overlay, 0.87, 0.48, 0.03, 0.20) + , m_bottom_main(0.100, 0.970, 0.600, 0.020) + , m_bottom_right(0.920, 0.970, 0.070, 0.020) +{} +void PokemonSwapMenuDetector::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_pink0); + items.add(COLOR_RED, m_pink1); + items.add(COLOR_RED, m_pink2); + items.add(COLOR_RED, m_white0); + items.add(COLOR_RED, m_white1); + items.add(COLOR_RED, m_bottom_main); + items.add(COLOR_RED, m_bottom_right); +} +bool PokemonSwapMenuDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + return m_stop_on_no_detect + ? !detect(frame) + : detect(frame); +} +bool PokemonSwapMenuDetector::detect(const ImageViewRGB32& screen) const{ + ImageStats pink0 = image_stats(extract_box_reference(screen, m_pink0)); + if (!is_solid(pink0, {0.448591, 0.176516, 0.374892}, 0.1, 20)) return false; + ImageStats pink1 = image_stats(extract_box_reference(screen, m_pink1)); + if (!is_solid(pink1, {0.448591, 0.176516, 0.374892}, 0.1, 20)) return false; + ImageStats pink2 = image_stats(extract_box_reference(screen, m_pink2)); + if (!is_solid(pink2, {0.464402, 0.156018, 0.379581}, 0.1, 20)) return false; + ImageStats white0 = image_stats(extract_box_reference(screen, m_white0)); +// cout << white0.average << ", " << white0.stddev << endl; + if (!is_solid(white0, {0.318115, 0.33587, 0.346015})) return false; + ImageStats white1 = image_stats(extract_box_reference(screen, m_white1)); +// cout << white.average << ", " << white.stddev << endl; + if (!is_solid(white1, {0.310994, 0.344503, 0.344503})) return false; +// ImageStats bottom = pixel_stats(extract_box(screen, m_bottom)); +// if (!is_white(bottom)) return false; +// ImageStats box0 = pixel_stats(extract_box(screen, m_box0)); +// if (!is_white(box0)) return false; +// ImageStats box1 = pixel_stats(extract_box(screen, m_box1)); +// if (!is_white(box1)) return false; + + ImageStats bottom_main = image_stats(extract_box_reference(screen, m_bottom_main)); +// cout << bottom_main.average << ", " << bottom_main.stddev << endl; + if (!is_black(bottom_main)){ + return false; + } + ImageStats bottom_right = image_stats(extract_box_reference(screen, m_bottom_right)); +// cout << bottom_right.average << ", " << bottom_right.stddev << endl; + if (bottom_right.stddev.sum() < 30){ + return false; + } + +// cout << pink0.average << ", " << pink0.stddev << endl; +// cout << pink1.average << ", " << pink1.stddev << endl; + return true; +} + + + +PokemonSwapMenuReader::PokemonSwapMenuReader( + Logger& logger, + VideoOverlay& overlay, + Language language, + OcrFailureWatchdog& ocr_watchdog +) + : m_logger(logger) + , m_language(language), m_ocr_watchdog(ocr_watchdog) + , m_sprite0(overlay, {0.481, 0.235 + 0*0.258, 0.071, 0.103}) + , m_sprite1(overlay, {0.481, 0.235 + 1*0.258, 0.071, 0.103}) + , m_name0(overlay, {0.485, 0.335 + 0*0.258, 0.180, 0.045}) + , m_name1(overlay, {0.485, 0.335 + 1*0.258, 0.180, 0.045}) + , m_select0(overlay, {0.630, 0.320 + 0*0.258, 0.030, 0.100}) + , m_select1(overlay, {0.630, 0.320 + 1*0.258, 0.030, 0.100}) + , m_pp0(overlay, {0.900, 0.207 + 0*0.060, 0.070, 0.045}) + , m_pp1(overlay, {0.900, 0.207 + 1*0.060, 0.070, 0.045}) + , m_pp2(overlay, {0.900, 0.207 + 2*0.060, 0.070, 0.045}) + , m_pp3(overlay, {0.900, 0.207 + 3*0.060, 0.070, 0.045}) + , m_hp0(overlay, {0.226, 0.3435 + 0*0.089, 0.112, 0.005}) + , m_hp1(overlay, {0.226, 0.3435 + 1*0.089, 0.112, 0.005}) + , m_hp2(overlay, {0.226, 0.3435 + 2*0.089, 0.112, 0.005}) + , m_hp3(overlay, {0.226, 0.3435 + 3*0.089, 0.112, 0.005}) +{} +bool PokemonSwapMenuReader::my_turn(const ImageViewRGB32& screen){ + double box0 = image_average(extract_box_reference(screen, m_select0)).sum(); + if (box0 < 200) return true; + double box1 = image_average(extract_box_reference(screen, m_select1)).sum(); + if (box1 < 200) return true; + return false; +} +void PokemonSwapMenuReader::read_options(const ImageViewRGB32& screen, std::string option[2]){ + option[0] = read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite0, m_name0, m_language, true); + option[1] = read_pokemon_name_sprite(m_logger, m_ocr_watchdog, screen, m_sprite1, m_name1, m_language, true); +} + +void PokemonSwapMenuReader::read_hp(const ImageViewRGB32& screen, double hp[4]){ + hp[0] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp0)); + hp[1] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp1)); + hp[2] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp2)); + hp[3] = read_hp_bar(m_logger, extract_box_reference(screen, m_hp3)); + if (hp[0] < 0 || hp[1] < 0 || hp[2] < 0 || hp[3] < 0){ + dump_image(m_logger, MODULE_NAME, "PokemonSwapMenuReader-read_hp", screen); + } +} +void PokemonSwapMenuReader::read_pp(const ImageViewRGB32& screen, int8_t pp[4]){ + pp[0] = read_pp_text(m_logger, extract_box_reference(screen, m_pp0)); + pp[1] = read_pp_text(m_logger, extract_box_reference(screen, m_pp1)); + pp[2] = read_pp_text(m_logger, extract_box_reference(screen, m_pp2)); + pp[3] = read_pp_text(m_logger, extract_box_reference(screen, m_pp3)); + if (pp[0] < 0 && pp[1] < 0 && pp[2] < 0 && pp[3] < 0){ + dump_image(m_logger, MODULE_NAME, "PokemonSwapMenuReader-read_pp", screen); + return; + } +} + + + + + + + + + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h index a0314477a0..06d92c3c53 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h @@ -1,99 +1,99 @@ -/* Max Lair Detect Pokemon Swap Menu - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSwapMenu_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSwapMenu_H - -#include "Common/Cpp/AbstractLogger.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/FailureWatchdog.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class PokemonSwapMenuDetector : public VisualInferenceCallback{ -public: - PokemonSwapMenuDetector(bool stop_no_detect); - - bool detect(const ImageViewRGB32& screen) const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - -private: - bool m_stop_on_no_detect; - ImageFloatBox m_pink0; - ImageFloatBox m_pink1; - ImageFloatBox m_pink2; - ImageFloatBox m_white0; - ImageFloatBox m_white1; -// ImageFloatBox m_bottom; -// ImageFloatBox m_box0; -// ImageFloatBox m_box1; - ImageFloatBox m_bottom_main; - ImageFloatBox m_bottom_right; -}; - - - -struct PokemonSwapMenuState{ - // Index of your current selection. - // -1 means it's not your turn to choose. - int index = -1; - - // Pokemon selection options. - std::string option[2]; -}; - -class PokemonSwapMenuReader{ -public: - PokemonSwapMenuReader( - Logger& logger, - VideoOverlay& overlay, - Language language, - OcrFailureWatchdog& ocr_watchdog - ); - - bool my_turn(const ImageViewRGB32& screen); - - void read_options(const ImageViewRGB32& screen, std::string option[2]); - void read_hp(const ImageViewRGB32& screen, double hp[4]); - void read_pp(const ImageViewRGB32& screen, int8_t pp[4]); - - -private: - Logger& m_logger; - Language m_language; - OcrFailureWatchdog& m_ocr_watchdog; - OverlayBoxScope m_sprite0; - OverlayBoxScope m_sprite1; - OverlayBoxScope m_name0; - OverlayBoxScope m_name1; - OverlayBoxScope m_select0; - OverlayBoxScope m_select1; - OverlayBoxScope m_pp0; - OverlayBoxScope m_pp1; - OverlayBoxScope m_pp2; - OverlayBoxScope m_pp3; - OverlayBoxScope m_hp0; - OverlayBoxScope m_hp1; - OverlayBoxScope m_hp2; - OverlayBoxScope m_hp3; -}; - - - -} -} -} -} -#endif +/* Max Lair Detect Pokemon Swap Menu + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSwapMenu_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_PokemonSwapMenu_H + +#include "Common/Cpp/AbstractLogger.h" +#include "CommonFramework/Language.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/FailureWatchdog.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class PokemonSwapMenuDetector : public VisualInferenceCallback{ +public: + PokemonSwapMenuDetector(bool stop_no_detect); + + bool detect(const ImageViewRGB32& screen) const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + +private: + bool m_stop_on_no_detect; + ImageFloatBox m_pink0; + ImageFloatBox m_pink1; + ImageFloatBox m_pink2; + ImageFloatBox m_white0; + ImageFloatBox m_white1; +// ImageFloatBox m_bottom; +// ImageFloatBox m_box0; +// ImageFloatBox m_box1; + ImageFloatBox m_bottom_main; + ImageFloatBox m_bottom_right; +}; + + + +struct PokemonSwapMenuState{ + // Index of your current selection. + // -1 means it's not your turn to choose. + int index = -1; + + // Pokemon selection options. + std::string option[2]; +}; + +class PokemonSwapMenuReader{ +public: + PokemonSwapMenuReader( + Logger& logger, + VideoOverlay& overlay, + Language language, + OcrFailureWatchdog& ocr_watchdog + ); + + bool my_turn(const ImageViewRGB32& screen); + + void read_options(const ImageViewRGB32& screen, std::string option[2]); + void read_hp(const ImageViewRGB32& screen, double hp[4]); + void read_pp(const ImageViewRGB32& screen, int8_t pp[4]); + + +private: + Logger& m_logger; + Language m_language; + OcrFailureWatchdog& m_ocr_watchdog; + OverlayBoxScope m_sprite0; + OverlayBoxScope m_sprite1; + OverlayBoxScope m_name0; + OverlayBoxScope m_name1; + OverlayBoxScope m_select0; + OverlayBoxScope m_select1; + OverlayBoxScope m_pp0; + OverlayBoxScope m_pp1; + OverlayBoxScope m_pp2; + OverlayBoxScope m_pp3; + OverlayBoxScope m_hp0; + OverlayBoxScope m_hp1; + OverlayBoxScope m_hp2; + OverlayBoxScope m_hp3; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.cpp index 524eafb51c..a8dd7bb9d4 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.cpp @@ -1,59 +1,59 @@ -/* Max Lair Detect Professor Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "PokemonSwSh_MaxLair_Detect_ProfessorSwap.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -ProfessorSwapDetector::ProfessorSwapDetector(VideoOverlay& overlay, bool enable) - : SelectionArrowFinder(overlay, ImageFloatBox(0.600, 0.600, 0.200, 0.200)) - , m_enabled(enable) -// , m_dialog0(0.257, 0.807, 0.015, 0.030) -// , m_dialog1(0.710, 0.880, 0.030, 0.050) - , m_bottom_main(0.100, 0.970, 0.600, 0.020) -{ -} -void ProfessorSwapDetector::make_overlays(VideoOverlaySet& items) const{ - SelectionArrowFinder::make_overlays(items); -// items.add(COLOR_YELLOW, m_dialog0); -// items.add(COLOR_YELLOW, m_dialog1); - items.add(COLOR_YELLOW, m_bottom_main); -} -bool ProfessorSwapDetector::detect(const ImageViewRGB32& screen){ -// ImageStats dialog_left = image_stats(extract_box_reference(screen, m_dialog0)); -// if (!is_grey(dialog_left, 0, 200)){ -// return false; -// } -// ImageStats dialog_right = image_stats(extract_box_reference(screen, m_dialog1)); -// if (!is_grey(dialog_right, 0, 200)){ -// return false; -// } - ImageStats dialog_left = image_stats(extract_box_reference(screen, m_bottom_main)); - if (!is_black(dialog_left)){ - return false; - } - return SelectionArrowFinder::detect(screen); -} -bool ProfessorSwapDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - if (!m_enabled){ - return false; - } - return detect(frame); -} - - - - -} -} -} -} +/* Max Lair Detect Professor Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "PokemonSwSh_MaxLair_Detect_ProfessorSwap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +ProfessorSwapDetector::ProfessorSwapDetector(VideoOverlay& overlay, bool enable) + : SelectionArrowFinder(overlay, ImageFloatBox(0.600, 0.600, 0.200, 0.200)) + , m_enabled(enable) +// , m_dialog0(0.257, 0.807, 0.015, 0.030) +// , m_dialog1(0.710, 0.880, 0.030, 0.050) + , m_bottom_main(0.100, 0.970, 0.600, 0.020) +{ +} +void ProfessorSwapDetector::make_overlays(VideoOverlaySet& items) const{ + SelectionArrowFinder::make_overlays(items); +// items.add(COLOR_YELLOW, m_dialog0); +// items.add(COLOR_YELLOW, m_dialog1); + items.add(COLOR_YELLOW, m_bottom_main); +} +bool ProfessorSwapDetector::detect(const ImageViewRGB32& screen){ +// ImageStats dialog_left = image_stats(extract_box_reference(screen, m_dialog0)); +// if (!is_grey(dialog_left, 0, 200)){ +// return false; +// } +// ImageStats dialog_right = image_stats(extract_box_reference(screen, m_dialog1)); +// if (!is_grey(dialog_right, 0, 200)){ +// return false; +// } + ImageStats dialog_left = image_stats(extract_box_reference(screen, m_bottom_main)); + if (!is_black(dialog_left)){ + return false; + } + return SelectionArrowFinder::detect(screen); +} +bool ProfessorSwapDetector::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + if (!m_enabled){ + return false; + } + return detect(frame); +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h index 7a43f5402f..e504fdf8d5 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ProfessorSwap.h @@ -1,43 +1,43 @@ -/* Max Lair Detect Professor Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_ProfessorSwap_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_ProfessorSwap_H - -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class ProfessorSwapDetector : public SelectionArrowFinder{ -public: - ProfessorSwapDetector(VideoOverlay& overlay, bool enable); - - bool detect(const ImageViewRGB32& screen); - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - bool m_enabled; -// ImageFloatBox m_dialog0; -// ImageFloatBox m_dialog1; - ImageFloatBox m_bottom_main; -}; - - - - - -} -} -} -} -#endif +/* Max Lair Detect Professor Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Detect_ProfessorSwap_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Detect_ProfessorSwap_H + +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class ProfessorSwapDetector : public SelectionArrowFinder{ +public: + ProfessorSwapDetector(VideoOverlay& overlay, bool enable); + + bool detect(const ImageViewRGB32& screen); + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + bool m_enabled; +// ImageFloatBox m_dialog0; +// ImageFloatBox m_dialog1; + ImageFloatBox m_bottom_main; +}; + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.cpp index 4b20ed439e..8823208fe3 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.cpp @@ -1,63 +1,63 @@ -/* Max Lair Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_MaxLair_Options.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -const std::string MODULE_NAME = "Max Lair"; -const std::chrono::milliseconds INFERENCE_RATE = std::chrono::milliseconds(200); - - - - -HostingSwitch::HostingSwitch() - : IntegerEnumDropdownOption( - "Host Switch:
This is the Switch that hosts the raid.", - { - {0, "switch0", "Switch 0 (Top Left)"}, - {1, "switch1", "Switch 1 (Top Right)"}, - {2, "switch2", "Switch 2 (Bottom Left)"}, - {3, "switch3", "Switch 3 (Bottom Right)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) -{} -std::string HostingSwitch::check_validity(size_t consoles) const{ - if (current_value() >= consoles){ - return "Host Switch cannot be larger than " + std::to_string(consoles - 1) + - " since you only have " + std::to_string(consoles) + " Switch(es) enabled."; - } - return std::string(); -} - -BossSlotOption::BossSlotOption() - : IntegerEnumDropdownOption( - "Boss Slot:", - { - {0, "anything", "Anything is fine"}, - {1, "slot1", "Slot 1"}, - {2, "slot2", "Slot 2"}, - {3, "slot3", "Slot 3"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) -{} - - - - -} -} -} -} +/* Max Lair Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_MaxLair_Options.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +const std::string MODULE_NAME = "Max Lair"; +const std::chrono::milliseconds INFERENCE_RATE = std::chrono::milliseconds(200); + + + + +HostingSwitch::HostingSwitch() + : IntegerEnumDropdownOption( + "Host Switch:
This is the Switch that hosts the raid.", + { + {0, "switch0", "Switch 0 (Top Left)"}, + {1, "switch1", "Switch 1 (Top Right)"}, + {2, "switch2", "Switch 2 (Bottom Left)"}, + {3, "switch3", "Switch 3 (Bottom Right)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) +{} +std::string HostingSwitch::check_validity(size_t consoles) const{ + if (current_value() >= consoles){ + return "Host Switch cannot be larger than " + std::to_string(consoles - 1) + + " since you only have " + std::to_string(consoles) + " Switch(es) enabled."; + } + return std::string(); +} + +BossSlotOption::BossSlotOption() + : IntegerEnumDropdownOption( + "Boss Slot:", + { + {0, "anything", "Anything is fine"}, + {1, "slot1", "Slot 1"}, + {2, "slot2", "Slot 2"}, + {3, "slot3", "Slot 3"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) +{} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h index fcb190a986..d0fd590fef 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h @@ -1,74 +1,74 @@ -/* Max Lair Options - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Options_H - -#include -#include "Common/Compiler.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -extern const std::string MODULE_NAME; -extern const std::chrono::milliseconds INFERENCE_RATE; - - - - -class HostingSwitch : public IntegerEnumDropdownOption{ -public: - HostingSwitch(); - std::string check_validity(size_t consoles) const; -}; - - - -class BossSlotOption : public IntegerEnumDropdownOption{ -public: - BossSlotOption(); -}; - - - - -enum class CaughtScreenAction{ - STOP_PROGRAM, - TAKE_NON_BOSS_SHINY_AND_CONTINUE, - RESET, -}; -class EndBattleDecider{ -public: - virtual const std::string& normal_ball( - size_t console_index - ) const = 0; - virtual const std::string& boss_ball( - size_t console_index, const std::string& boss_slug - ) const = 0; - virtual CaughtScreenAction end_adventure_action( - size_t console_index, const std::string& boss_slug, - const PathStats& path_stats, - bool any_shiny, bool boss_is_shiny - ) const = 0; -}; - - - - - - - - -} -} -} -} -#endif +/* Max Lair Options + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Options_H + +#include +#include "Common/Compiler.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +extern const std::string MODULE_NAME; +extern const std::chrono::milliseconds INFERENCE_RATE; + + + + +class HostingSwitch : public IntegerEnumDropdownOption{ +public: + HostingSwitch(); + std::string check_validity(size_t consoles) const; +}; + + + +class BossSlotOption : public IntegerEnumDropdownOption{ +public: + BossSlotOption(); +}; + + + + +enum class CaughtScreenAction{ + STOP_PROGRAM, + TAKE_NON_BOSS_SHINY_AND_CONTINUE, + RESET, +}; +class EndBattleDecider{ +public: + virtual const std::string& normal_ball( + size_t console_index + ) const = 0; + virtual const std::string& boss_ball( + size_t console_index, const std::string& boss_slug + ) const = 0; + virtual CaughtScreenAction end_adventure_action( + size_t console_index, const std::string& boss_slug, + const PathStats& path_stats, + bool any_shiny, bool boss_is_shiny + ) const = 0; +}; + + + + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.cpp index b0c7e336eb..003a55c03b 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.cpp @@ -1,80 +1,80 @@ -/* Max Lair Boss Action - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "Pokemon/Resources/Pokemon_PokeballNames.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh_MaxLair_Options_BossAction.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - - -const EnumDropdownDatabase& BossAction_Database(){ - static const EnumDropdownDatabase database({ - {BossAction::CATCH_AND_STOP_PROGRAM, "always-stop", "Always stop program."}, - {BossAction::CATCH_AND_STOP_IF_SHINY, "stop-if-shiny", "Stop if shiny."}, - }); - return database; -} - -BossActionRow::BossActionRow(std::string slug, const std::string& name_slug, const std::string& sprite_slug) - : StaticTableRow(std::move(slug)) - , pokemon(LockMode::LOCK_WHILE_RUNNING, get_pokemon_name(name_slug).display_name(), ALL_POKEMON_SPRITES().get_throw(sprite_slug).icon) - , action(BossAction_Database(), LockMode::LOCK_WHILE_RUNNING, BossAction::CATCH_AND_STOP_IF_SHINY) - , ball("poke-ball") -{ - PA_ADD_STATIC(pokemon); - add_option(action, "Action"); - add_option(ball, "Ball"); -} - - -BossActionTable::BossActionTable() - : StaticTableOption("Boss Actions:", LockMode::LOCK_WHILE_RUNNING) -{ - for (const auto& item : all_bosses_by_dex()){ -// cout << item.second << endl; - const MaxLairSlugs& slugs = get_maxlair_slugs(item.second); - const std::string& sprite_slug = *slugs.sprite_slugs.begin(); - const std::string& name_slug = slugs.name_slug; - add_row(std::make_unique(item.second, name_slug, sprite_slug)); - } - finish_construction(); -} -std::vector BossActionTable::make_header() const{ - std::vector ret{ - STRING_POKEMON, - "Action", - STRING_POKEBALL - }; - return ret; -} - - - - - - -} -} -} -} +/* Max Lair Boss Action + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "Pokemon/Resources/Pokemon_PokeballNames.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh_MaxLair_Options_BossAction.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + + +const EnumDropdownDatabase& BossAction_Database(){ + static const EnumDropdownDatabase database({ + {BossAction::CATCH_AND_STOP_PROGRAM, "always-stop", "Always stop program."}, + {BossAction::CATCH_AND_STOP_IF_SHINY, "stop-if-shiny", "Stop if shiny."}, + }); + return database; +} + +BossActionRow::BossActionRow(std::string slug, const std::string& name_slug, const std::string& sprite_slug) + : StaticTableRow(std::move(slug)) + , pokemon(LockMode::LOCK_WHILE_RUNNING, get_pokemon_name(name_slug).display_name(), ALL_POKEMON_SPRITES().get_throw(sprite_slug).icon) + , action(BossAction_Database(), LockMode::LOCK_WHILE_RUNNING, BossAction::CATCH_AND_STOP_IF_SHINY) + , ball("poke-ball") +{ + PA_ADD_STATIC(pokemon); + add_option(action, "Action"); + add_option(ball, "Ball"); +} + + +BossActionTable::BossActionTable() + : StaticTableOption("Boss Actions:", LockMode::LOCK_WHILE_RUNNING) +{ + for (const auto& item : all_bosses_by_dex()){ +// cout << item.second << endl; + const MaxLairSlugs& slugs = get_maxlair_slugs(item.second); + const std::string& sprite_slug = *slugs.sprite_slugs.begin(); + const std::string& name_slug = slugs.name_slug; + add_row(std::make_unique(item.second, name_slug, sprite_slug)); + } + finish_construction(); +} +std::vector BossActionTable::make_header() const{ + std::vector ret{ + STRING_POKEMON, + "Action", + STRING_POKEBALL + }; + return ret; +} + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.h index 3e228c5089..8765e5d351 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_BossAction.h @@ -1,50 +1,50 @@ -/* Max Lair Boss Action - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_BossAction_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Options_BossAction_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/StaticTableOption.h" -#include "CommonFramework/Options/LabelCellOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -enum class BossAction{ - CATCH_AND_STOP_PROGRAM, - CATCH_AND_STOP_IF_SHINY, -}; - - -class BossActionRow : public StaticTableRow{ -public: - BossActionRow(std::string slug, const std::string& name_slug, const std::string& sprite_slug); - - LabelCellOption pokemon; - EnumDropdownCell action; - PokemonBallSelectCell ball; -}; - -class BossActionTable : public StaticTableOption{ -public: - BossActionTable(); - virtual std::vector make_header() const; -}; - - - - - -} -} -} -} -#endif +/* Max Lair Boss Action + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_BossAction_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Options_BossAction_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/StaticTableOption.h" +#include "CommonFramework/Options/LabelCellOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +enum class BossAction{ + CATCH_AND_STOP_PROGRAM, + CATCH_AND_STOP_IF_SHINY, +}; + + +class BossActionRow : public StaticTableRow{ +public: + BossActionRow(std::string slug, const std::string& name_slug, const std::string& sprite_slug); + + LabelCellOption pokemon; + EnumDropdownCell action; + PokemonBallSelectCell ball; +}; + +class BossActionTable : public StaticTableOption{ +public: + BossActionTable(); + virtual std::vector make_header() const; +}; + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp index 0b205ff98c..5de2991410 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.cpp @@ -1,160 +1,160 @@ -/* Max Lair Consoles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh_MaxLair_Options_Consoles.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - -using namespace Pokemon; - - -CaughtScreenActionOption::CaughtScreenActionOption( - bool take_non_shiny, bool reset_if_high_winrate, - std::string label, CaughtScreenAction default_action -) - : EnumDropdownOption( - std::move(label), - { - {CaughtScreenAction::STOP_PROGRAM, "stop-program", "Stop Program"}, - {CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, "continue", take_non_shiny - ? "Continue Running. (Take any shiny non-boss " + STRING_POKEMON + " along the way.)" - : "Continue Running" - }, - {CaughtScreenAction::RESET, "reset", !reset_if_high_winrate - ? "Reset Game" - : take_non_shiny - ? "Reset Game if win-rate is above the threshold. Otherwise take any non-boss shinies and continue." - : "Reset Game if win-rate is above the threshold. Otherwise continue running." - }, - }, - LockMode::LOCK_WHILE_RUNNING, - default_action - ) -{} - -CaughtScreenActionsOption::CaughtScreenActionsOption( - bool host_tooltip, bool winrate_reset_tooltip, - CaughtScreenAction default_no_shinies, - CaughtScreenAction default_shiny_nonboss, - CaughtScreenAction default_shiny_boss -) - : GroupOption("End Adventure Actions", LockMode::LOCK_WHILE_RUNNING) - , no_shinies(false, winrate_reset_tooltip, "No Shinies:", default_no_shinies) - , shiny_nonboss( - true, winrate_reset_tooltip, - "Boss is not shiny, but something else is:
" - "If this is set to continue and there are multiple shinies, the program will take the highest one on the list.", - default_shiny_nonboss - ) - , shiny_boss( - true, winrate_reset_tooltip, - "Boss/Legendary is Shiny:
If there are multiple shinies where one is the boss, this option still applies.

" - "For safety reasons, this program will NEVER automatically take a boss. " - "Likewise, the settings here are intentionally worded so that it's impossible to ask the program to take a boss. " - "Because taking a boss is irreversible, we refuse to automate it and require you to do it manually to avoid any mistakes.", - default_shiny_boss - ) - , description( - std::string("Choosing \"Reset Game\" has the effect of preserving your balls at the cost of paying ore. (10 ore per reset after enough resets) " - "Therefore, you should start with plenty of ore to avoid running out.") + - ( - host_tooltip - ? "
If this is the hosting Switch, \"Reset Game\" also has the effect of preserving the path. " - "So if you have a path with a high win rate, set both \"No Shinies\" and \"Shiny Non-Boss\" to \"Reset Game\" to grind for the boss." - : "" - ) - ) -{ - PA_ADD_OPTION(no_shinies); - PA_ADD_OPTION(shiny_nonboss); - PA_ADD_OPTION(shiny_boss); - PA_ADD_STATIC(description); -} - - - - - -ConsoleSpecificOptions::ConsoleSpecificOptions(std::string label, const LanguageSet& languages, bool host) - : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) - , is_host_label("This is the host Switch.") - , language("Game Language:", languages, LockMode::LOCK_WHILE_RUNNING, true) -{ - ConsoleSpecificOptions::set_host(host); - PA_ADD_STATIC(is_host_label); - PA_ADD_OPTION(language); -} -void ConsoleSpecificOptions::set_host(bool is_host){ - this->is_host = is_host; - is_host_label.set_visibility(is_host ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); -} - - - - - -Consoles::~Consoles(){ - HOST.remove_listener(*this); -} -Consoles::Consoles(const ConsoleSpecificOptionsFactory& factory) - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_languages(PokemonNameReader::instance().languages()) -{ - PLAYERS[0] = factory.make("Switch 0 (Top Left)", m_languages, true); - PLAYERS[1] = factory.make("Switch 1 (Top Right)", m_languages, false); - PLAYERS[2] = factory.make("Switch 2 (Bottom Left)", m_languages, false); - PLAYERS[3] = factory.make("Switch 3 (Bottom Right)", m_languages, false); - - PA_ADD_OPTION(HOST); - add_option(*PLAYERS[0], "Console0"); - add_option(*PLAYERS[1], "Console1"); - add_option(*PLAYERS[2], "Console2"); - add_option(*PLAYERS[3], "Console3"); - - set_active_consoles(1); - - HOST.add_listener(*this); -} -size_t Consoles::active_consoles() const{ - return m_active_consoles; -} -void Consoles::set_active_consoles(size_t consoles){ -// cout << "Consoles::set_active_consoles() = " << consoles << endl; - size_t c = 0; - for (; c < consoles; c++){ - PLAYERS[c]->set_visibility(ConfigOptionState::ENABLED); - } - for (; c < 4; c++){ - PLAYERS[c]->set_visibility(ConfigOptionState::HIDDEN); - } - m_active_consoles = consoles; -} -void Consoles::on_config_value_changed(void* object){ - size_t host_index = HOST.current_value(); - for (size_t c = 0; c < 4; c++){ - PLAYERS[c]->set_host(c == host_index); - } -} - - - - - -} -} -} -} +/* Max Lair Consoles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh_MaxLair_Options_Consoles.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + +using namespace Pokemon; + + +CaughtScreenActionOption::CaughtScreenActionOption( + bool take_non_shiny, bool reset_if_high_winrate, + std::string label, CaughtScreenAction default_action +) + : EnumDropdownOption( + std::move(label), + { + {CaughtScreenAction::STOP_PROGRAM, "stop-program", "Stop Program"}, + {CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, "continue", take_non_shiny + ? "Continue Running. (Take any shiny non-boss " + STRING_POKEMON + " along the way.)" + : "Continue Running" + }, + {CaughtScreenAction::RESET, "reset", !reset_if_high_winrate + ? "Reset Game" + : take_non_shiny + ? "Reset Game if win-rate is above the threshold. Otherwise take any non-boss shinies and continue." + : "Reset Game if win-rate is above the threshold. Otherwise continue running." + }, + }, + LockMode::LOCK_WHILE_RUNNING, + default_action + ) +{} + +CaughtScreenActionsOption::CaughtScreenActionsOption( + bool host_tooltip, bool winrate_reset_tooltip, + CaughtScreenAction default_no_shinies, + CaughtScreenAction default_shiny_nonboss, + CaughtScreenAction default_shiny_boss +) + : GroupOption("End Adventure Actions", LockMode::LOCK_WHILE_RUNNING) + , no_shinies(false, winrate_reset_tooltip, "No Shinies:", default_no_shinies) + , shiny_nonboss( + true, winrate_reset_tooltip, + "Boss is not shiny, but something else is:
" + "If this is set to continue and there are multiple shinies, the program will take the highest one on the list.", + default_shiny_nonboss + ) + , shiny_boss( + true, winrate_reset_tooltip, + "Boss/Legendary is Shiny:
If there are multiple shinies where one is the boss, this option still applies.

" + "For safety reasons, this program will NEVER automatically take a boss. " + "Likewise, the settings here are intentionally worded so that it's impossible to ask the program to take a boss. " + "Because taking a boss is irreversible, we refuse to automate it and require you to do it manually to avoid any mistakes.", + default_shiny_boss + ) + , description( + std::string("Choosing \"Reset Game\" has the effect of preserving your balls at the cost of paying ore. (10 ore per reset after enough resets) " + "Therefore, you should start with plenty of ore to avoid running out.") + + ( + host_tooltip + ? "
If this is the hosting Switch, \"Reset Game\" also has the effect of preserving the path. " + "So if you have a path with a high win rate, set both \"No Shinies\" and \"Shiny Non-Boss\" to \"Reset Game\" to grind for the boss." + : "" + ) + ) +{ + PA_ADD_OPTION(no_shinies); + PA_ADD_OPTION(shiny_nonboss); + PA_ADD_OPTION(shiny_boss); + PA_ADD_STATIC(description); +} + + + + + +ConsoleSpecificOptions::ConsoleSpecificOptions(std::string label, const LanguageSet& languages, bool host) + : GroupOption(std::move(label), LockMode::LOCK_WHILE_RUNNING) + , is_host_label("This is the host Switch.") + , language("Game Language:", languages, LockMode::LOCK_WHILE_RUNNING, true) +{ + ConsoleSpecificOptions::set_host(host); + PA_ADD_STATIC(is_host_label); + PA_ADD_OPTION(language); +} +void ConsoleSpecificOptions::set_host(bool is_host){ + this->is_host = is_host; + is_host_label.set_visibility(is_host ? ConfigOptionState::ENABLED : ConfigOptionState::HIDDEN); +} + + + + + +Consoles::~Consoles(){ + HOST.remove_listener(*this); +} +Consoles::Consoles(const ConsoleSpecificOptionsFactory& factory) + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_languages(PokemonNameReader::instance().languages()) +{ + PLAYERS[0] = factory.make("Switch 0 (Top Left)", m_languages, true); + PLAYERS[1] = factory.make("Switch 1 (Top Right)", m_languages, false); + PLAYERS[2] = factory.make("Switch 2 (Bottom Left)", m_languages, false); + PLAYERS[3] = factory.make("Switch 3 (Bottom Right)", m_languages, false); + + PA_ADD_OPTION(HOST); + add_option(*PLAYERS[0], "Console0"); + add_option(*PLAYERS[1], "Console1"); + add_option(*PLAYERS[2], "Console2"); + add_option(*PLAYERS[3], "Console3"); + + set_active_consoles(1); + + HOST.add_listener(*this); +} +size_t Consoles::active_consoles() const{ + return m_active_consoles; +} +void Consoles::set_active_consoles(size_t consoles){ +// cout << "Consoles::set_active_consoles() = " << consoles << endl; + size_t c = 0; + for (; c < consoles; c++){ + PLAYERS[c]->set_visibility(ConfigOptionState::ENABLED); + } + for (; c < 4; c++){ + PLAYERS[c]->set_visibility(ConfigOptionState::HIDDEN); + } + m_active_consoles = consoles; +} +void Consoles::on_config_value_changed(void* object){ + size_t host_index = HOST.current_value(); + for (size_t c = 0; c < 4; c++){ + PLAYERS[c]->set_host(c == host_index); + } +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h index 8f08f3516c..a93942bc94 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h @@ -1,102 +1,102 @@ -/* Max Lair Consoles - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_Consoles_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Options_Consoles_H - -#include -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Language.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "PokemonSwSh_MaxLair_Options.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -class CaughtScreenActionOption : public EnumDropdownOption{ -public: - CaughtScreenActionOption( - bool take_non_shiny, bool reset_if_high_winrate, - std::string label, CaughtScreenAction default_action - ); -}; -class CaughtScreenActionsOption : public GroupOption{ -public: - CaughtScreenActionsOption( - bool host_tooltip, bool winrate_reset_tooltip, - CaughtScreenAction default_no_shinies = CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, - CaughtScreenAction default_shiny_nonboss = CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, - CaughtScreenAction default_shiny_boss = CaughtScreenAction::STOP_PROGRAM - ); - - CaughtScreenActionOption no_shinies; - CaughtScreenActionOption shiny_nonboss; - CaughtScreenActionOption shiny_boss; - StaticTextOption description; -}; - - - - - -class ConsoleSpecificOptions : public GroupOption{ -public: - ConsoleSpecificOptions(std::string label, const LanguageSet& languages, bool host); - - virtual void set_host(bool is_host); - - - bool is_host; - StaticTextOption is_host_label; - OCR::LanguageOCROption language; -}; -class ConsoleSpecificOptionsFactory{ -public: - virtual std::unique_ptr make( - std::string label, - const LanguageSet& languages, - bool is_host - ) const = 0; -}; - - - -class Consoles : public BatchOption, private ConfigOption::Listener{ -public: - ~Consoles(); - Consoles(const ConsoleSpecificOptionsFactory& factory); - - size_t active_consoles() const; - void set_active_consoles(size_t consoles); - - const ConsoleSpecificOptions& operator[](size_t index) const{ - return *PLAYERS[index]; - } - - virtual void on_config_value_changed(void* object) override; - -private: - LanguageSet m_languages; - size_t m_active_consoles; -public: - HostingSwitch HOST; - std::unique_ptr PLAYERS[4]; -}; - - - - -} -} -} -} -#endif +/* Max Lair Consoles + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_Consoles_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Options_Consoles_H + +#include +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Language.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "PokemonSwSh_MaxLair_Options.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +class CaughtScreenActionOption : public EnumDropdownOption{ +public: + CaughtScreenActionOption( + bool take_non_shiny, bool reset_if_high_winrate, + std::string label, CaughtScreenAction default_action + ); +}; +class CaughtScreenActionsOption : public GroupOption{ +public: + CaughtScreenActionsOption( + bool host_tooltip, bool winrate_reset_tooltip, + CaughtScreenAction default_no_shinies = CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, + CaughtScreenAction default_shiny_nonboss = CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, + CaughtScreenAction default_shiny_boss = CaughtScreenAction::STOP_PROGRAM + ); + + CaughtScreenActionOption no_shinies; + CaughtScreenActionOption shiny_nonboss; + CaughtScreenActionOption shiny_boss; + StaticTextOption description; +}; + + + + + +class ConsoleSpecificOptions : public GroupOption{ +public: + ConsoleSpecificOptions(std::string label, const LanguageSet& languages, bool host); + + virtual void set_host(bool is_host); + + + bool is_host; + StaticTextOption is_host_label; + OCR::LanguageOCROption language; +}; +class ConsoleSpecificOptionsFactory{ +public: + virtual std::unique_ptr make( + std::string label, + const LanguageSet& languages, + bool is_host + ) const = 0; +}; + + + +class Consoles : public BatchOption, private ConfigOption::Listener{ +public: + ~Consoles(); + Consoles(const ConsoleSpecificOptionsFactory& factory); + + size_t active_consoles() const; + void set_active_consoles(size_t consoles); + + const ConsoleSpecificOptions& operator[](size_t index) const{ + return *PLAYERS[index]; + } + + virtual void on_config_value_changed(void* object) override; + +private: + LanguageSet m_languages; + size_t m_active_consoles; +public: + HostingSwitch HOST; + std::unique_ptr PLAYERS[4]; +}; + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.cpp index 827d2385bd..2ced230315 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.cpp @@ -1,93 +1,93 @@ -/* Max Lair Hosting - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_MaxLair_Options_Hosting.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -HostingSettings::~HostingSettings(){ - MODE.remove_listener(*this); -} -HostingSettings::HostingSettings() - : GroupOption("Hosting Options", LockMode::LOCK_WHILE_RUNNING) - , MODE( - "Mode:", - { - {HostingMode::NOT_HOSTING, "none", "Not Hosting: Run by yourself using only Switches controlled by this program."}, - {HostingMode::HOST_LOCALLY, "local", "Host Locally: Allow other local Switches to join."}, - {HostingMode::HOST_ONLINE, "online", "Host Online: Allow other people online to join."}, - }, - LockMode::LOCK_WHILE_RUNNING, - HostingMode::NOT_HOSTING - ) - , RAID_CODE( - "Raid Code:
Required if using multiple Switches. " - "Random code is strongly recommended when hosting to ensure your own Switches get in.", - 8, 4, "" - ) - , CONNECT_TO_INTERNET_DELAY0( - "Connect to Internet Delay:
Time from \"Connect to Internet\" to when you're ready to start adventure.", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) - , START_DELAY0( - "Start Delay:
Wait this long before entering the lobby.

" - "If two Switches open a lobby at the same time, they might not see each other and " - "thus fail to join each other. If you are joining someone else's auto-host, you " - "will want to set this to 3 seconds or more to make sure that the host opens the " - "lobby before everyone else tries to join.", - LockMode::LOCK_WHILE_RUNNING, - "0 s" - ) - , LOBBY_WAIT_DELAY0( - "Lobby Wait Delay:
Wait this long before starting raid. Start time is 3 minutes minus this number.", - LockMode::LOCK_WHILE_RUNNING, - "60 s" - ) - , NOTIFICATIONS("Live-Hosting Announcements", true) -{ - PA_ADD_OPTION(MODE); - PA_ADD_OPTION(RAID_CODE); - PA_ADD_OPTION(CONNECT_TO_INTERNET_DELAY0); - PA_ADD_OPTION(START_DELAY0); - PA_ADD_OPTION(LOBBY_WAIT_DELAY0); - PA_ADD_OPTION(NOTIFICATIONS); - - MODE.add_listener(*this); -} -std::string HostingSettings::check_validity(size_t consoles) const{ - if (consoles != 1 && !RAID_CODE.code_enabled()){ - return "You must use a code when running with multiple Switches."; - } - return std::string(); -} -void HostingSettings::on_config_value_changed(void* object){ - HostingMode mode = MODE; - if (mode == HostingMode::HOST_ONLINE){ - CONNECT_TO_INTERNET_DELAY0.set_visibility(ConfigOptionState::ENABLED); - }else{ - CONNECT_TO_INTERNET_DELAY0.set_visibility(ConfigOptionState::DISABLED); - } - if (mode != HostingMode::NOT_HOSTING){ - START_DELAY0.set_visibility(ConfigOptionState::ENABLED); - NOTIFICATIONS.set_visibility(ConfigOptionState::ENABLED); - }else{ - START_DELAY0.set_visibility(ConfigOptionState::DISABLED); - NOTIFICATIONS.set_visibility(ConfigOptionState::DISABLED); - } -} - - - -} -} -} -} +/* Max Lair Hosting + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_MaxLair_Options_Hosting.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +HostingSettings::~HostingSettings(){ + MODE.remove_listener(*this); +} +HostingSettings::HostingSettings() + : GroupOption("Hosting Options", LockMode::LOCK_WHILE_RUNNING) + , MODE( + "Mode:", + { + {HostingMode::NOT_HOSTING, "none", "Not Hosting: Run by yourself using only Switches controlled by this program."}, + {HostingMode::HOST_LOCALLY, "local", "Host Locally: Allow other local Switches to join."}, + {HostingMode::HOST_ONLINE, "online", "Host Online: Allow other people online to join."}, + }, + LockMode::LOCK_WHILE_RUNNING, + HostingMode::NOT_HOSTING + ) + , RAID_CODE( + "Raid Code:
Required if using multiple Switches. " + "Random code is strongly recommended when hosting to ensure your own Switches get in.", + 8, 4, "" + ) + , CONNECT_TO_INTERNET_DELAY0( + "Connect to Internet Delay:
Time from \"Connect to Internet\" to when you're ready to start adventure.", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) + , START_DELAY0( + "Start Delay:
Wait this long before entering the lobby.

" + "If two Switches open a lobby at the same time, they might not see each other and " + "thus fail to join each other. If you are joining someone else's auto-host, you " + "will want to set this to 3 seconds or more to make sure that the host opens the " + "lobby before everyone else tries to join.", + LockMode::LOCK_WHILE_RUNNING, + "0 s" + ) + , LOBBY_WAIT_DELAY0( + "Lobby Wait Delay:
Wait this long before starting raid. Start time is 3 minutes minus this number.", + LockMode::LOCK_WHILE_RUNNING, + "60 s" + ) + , NOTIFICATIONS("Live-Hosting Announcements", true) +{ + PA_ADD_OPTION(MODE); + PA_ADD_OPTION(RAID_CODE); + PA_ADD_OPTION(CONNECT_TO_INTERNET_DELAY0); + PA_ADD_OPTION(START_DELAY0); + PA_ADD_OPTION(LOBBY_WAIT_DELAY0); + PA_ADD_OPTION(NOTIFICATIONS); + + MODE.add_listener(*this); +} +std::string HostingSettings::check_validity(size_t consoles) const{ + if (consoles != 1 && !RAID_CODE.code_enabled()){ + return "You must use a code when running with multiple Switches."; + } + return std::string(); +} +void HostingSettings::on_config_value_changed(void* object){ + HostingMode mode = MODE; + if (mode == HostingMode::HOST_ONLINE){ + CONNECT_TO_INTERNET_DELAY0.set_visibility(ConfigOptionState::ENABLED); + }else{ + CONNECT_TO_INTERNET_DELAY0.set_visibility(ConfigOptionState::DISABLED); + } + if (mode != HostingMode::NOT_HOSTING){ + START_DELAY0.set_visibility(ConfigOptionState::ENABLED); + NOTIFICATIONS.set_visibility(ConfigOptionState::ENABLED); + }else{ + START_DELAY0.set_visibility(ConfigOptionState::DISABLED); + NOTIFICATIONS.set_visibility(ConfigOptionState::DISABLED); + } +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h index 725e3c4e26..bf7d7863f0 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h @@ -1,53 +1,53 @@ -/* Max Lair Hosting - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_Hosting_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Options_Hosting_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/RandomCodeOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -enum class HostingMode{ - NOT_HOSTING, - HOST_LOCALLY, - HOST_ONLINE, -}; - -class HostingSettings : public GroupOption, private ConfigOption::Listener{ -public: - ~HostingSettings(); - HostingSettings(); - using GroupOption::check_validity; - std::string check_validity(size_t consoles) const; - - virtual void on_config_value_changed(void* object) override; - - EnumDropdownOption MODE; - RandomCodeOption RAID_CODE; - MillisecondsOption CONNECT_TO_INTERNET_DELAY0; - MillisecondsOption START_DELAY0; - MillisecondsOption LOBBY_WAIT_DELAY0; - - AutoHostNotificationOption NOTIFICATIONS; -}; - - - -} -} -} -} -#endif +/* Max Lair Hosting + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Options_Hosting_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Options_Hosting_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/RandomCodeOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +enum class HostingMode{ + NOT_HOSTING, + HOST_LOCALLY, + HOST_ONLINE, +}; + +class HostingSettings : public GroupOption, private ConfigOption::Listener{ +public: + ~HostingSettings(); + HostingSettings(); + using GroupOption::check_validity; + std::string check_validity(size_t consoles) const; + + virtual void on_config_value_changed(void* object) override; + + EnumDropdownOption MODE; + RandomCodeOption RAID_CODE; + MillisecondsOption CONNECT_TO_INTERNET_DELAY0; + MillisecondsOption START_DELAY0; + MillisecondsOption LOBBY_WAIT_DELAY0; + + AutoHostNotificationOption NOTIFICATIONS; +}; + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.cpp index e7ed64d32a..52f26d85d3 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.cpp @@ -1,222 +1,222 @@ -/* Max Lair (Boss Finder) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "Program/PokemonSwSh_MaxLair_Run_Adventure.h" -#include "PokemonSwSh_MaxLair_BossFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace MaxLairInternal; - - - -MaxLairBossFinder_Descriptor::MaxLairBossFinder_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSwSh:MaxLair-BossFinder", - STRING_POKEMON + " SwSh", "Max Lair - Boss Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MaxLair-BossFinder.md", - "Auto Max Lair 2.0 - Run adventures until you find the boss you want. Once you find your boss, switch to the other programs to shiny hunt it.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 1, 4, 1 - ) -{} -std::unique_ptr MaxLairBossFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -class MaxLairBossFinder_ConsoleOptions : public ConsoleSpecificOptions{ -public: - MaxLairBossFinder_ConsoleOptions(std::string label, const LanguageSet& languages, bool host) - : ConsoleSpecificOptions(std::move(label), languages, host) - , normal_ball( - "Normal Ball: Ball for catching non-boss " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "poke-ball" - ) - { - PA_ADD_OPTION(normal_ball); - } - - PokemonBallSelectOption normal_ball; -}; - -class MaxLairBossFinder_ConsoleFactory : public ConsoleSpecificOptionsFactory{ -public: - virtual std::unique_ptr make( - std::string label, - const LanguageSet& languages, - bool host - ) const override{ - return std::unique_ptr(new MaxLairBossFinder_ConsoleOptions(std::move(label), languages, host)); - } -}; - - -MaxLairBossFinder::MaxLairBossFinder() - : MultiSwitchProgramInstance({"Notifs", "LiveHost"}) - , GO_HOME_WHEN_DONE(false) - , CONSOLES(MaxLairBossFinder_ConsoleFactory()) - , NOTIFICATION_STATUS("Status Update", true, false) - , NOTIFICATION_SHINY("Shiny Catch", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) - , NOTIFICATIONS({ - &HOSTING.NOTIFICATIONS.NOTIFICATION, - &NOTIFICATION_STATUS, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(CONSOLES); - PA_ADD_OPTION(BOSS_LIST); - PA_ADD_OPTION(HOSTING); - - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - PA_ADD_OPTION(NOTIFICATIONS); -} - -std::string MaxLairBossFinder::check_validity() const{ - std::string error = MultiSwitchProgramInstance::check_validity(); - if (!error.empty()){ - return error; - } - - size_t active_consoles = CONSOLES.active_consoles(); - error = CONSOLES.HOST.check_validity(active_consoles); - if (!error.empty()){ - return error; - } - error = HOSTING.check_validity(active_consoles); - if (!error.empty()){ - return error; - } - return std::string(); -} -void MaxLairBossFinder::update_active_consoles(size_t switch_count){ - CONSOLES.set_active_consoles(switch_count); -} - - - - -class EndBattleDecider_BossFinder : public EndBattleDecider{ -public: - EndBattleDecider_BossFinder(const Consoles& consoles, const BossActionTable& boss_list) - : m_consoles(consoles) - , m_boss_list(boss_list) - {} - virtual const std::string& normal_ball( - size_t console_index - ) const override{ - return console(console_index).normal_ball.slug(); - } - virtual const std::string& boss_ball( - size_t console_index, const std::string& boss_slug - ) const override{ - return get_filter(boss_slug).ball.slug(); - } - virtual CaughtScreenAction end_adventure_action( - size_t console_index, const std::string& boss_slug, - const PathStats& path_stats, - bool any_shiny, bool boss_is_shiny - ) const override{ - if (boss_slug.empty()){ - return CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE; - } - switch (get_filter(boss_slug).action){ - case BossAction::CATCH_AND_STOP_PROGRAM: - return CaughtScreenAction::STOP_PROGRAM; - case BossAction::CATCH_AND_STOP_IF_SHINY: - return boss_is_shiny - ? CaughtScreenAction::STOP_PROGRAM - : CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid enum."); - } - - -private: - const BossActionRow& get_filter(const std::string& boss_slug) const{ - for (const StaticTableRow* row : m_boss_list.table()){ - const BossActionRow& filter = static_cast(*row); - if (boss_slug == filter.slug()){ - return filter; - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unrecognized boss slug: " + boss_slug); - } - -private: - const MaxLairBossFinder_ConsoleOptions& console(size_t index) const{ - return static_cast(m_consoles[index]); - } - - const Consoles& m_consoles; - const BossActionTable& m_boss_list; - -}; - - - - - -void MaxLairBossFinder::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - size_t host_index = CONSOLES.HOST.current_value(); - if (host_index >= env.consoles.size()){ - throw UserSetupError(env.logger(), "Invalid Host Switch"); - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - assert_16_9_720p_min(console, console); - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - }); - - EndBattleDecider_BossFinder decider(CONSOLES, BOSS_LIST); - - loop_adventures( - env, scope, CONSOLES, - host_index, 0, - decider, - GO_HOME_WHEN_DONE, - HOSTING, - TOUCH_DATE_INTERVAL, - NOTIFICATION_STATUS, - NOTIFICATION_SHINY - ); - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Max Lair (Boss Finder) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "Program/PokemonSwSh_MaxLair_Run_Adventure.h" +#include "PokemonSwSh_MaxLair_BossFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace MaxLairInternal; + + + +MaxLairBossFinder_Descriptor::MaxLairBossFinder_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSwSh:MaxLair-BossFinder", + STRING_POKEMON + " SwSh", "Max Lair - Boss Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MaxLair-BossFinder.md", + "Auto Max Lair 2.0 - Run adventures until you find the boss you want. Once you find your boss, switch to the other programs to shiny hunt it.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 1, 4, 1 + ) +{} +std::unique_ptr MaxLairBossFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +class MaxLairBossFinder_ConsoleOptions : public ConsoleSpecificOptions{ +public: + MaxLairBossFinder_ConsoleOptions(std::string label, const LanguageSet& languages, bool host) + : ConsoleSpecificOptions(std::move(label), languages, host) + , normal_ball( + "Normal Ball: Ball for catching non-boss " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "poke-ball" + ) + { + PA_ADD_OPTION(normal_ball); + } + + PokemonBallSelectOption normal_ball; +}; + +class MaxLairBossFinder_ConsoleFactory : public ConsoleSpecificOptionsFactory{ +public: + virtual std::unique_ptr make( + std::string label, + const LanguageSet& languages, + bool host + ) const override{ + return std::unique_ptr(new MaxLairBossFinder_ConsoleOptions(std::move(label), languages, host)); + } +}; + + +MaxLairBossFinder::MaxLairBossFinder() + : MultiSwitchProgramInstance({"Notifs", "LiveHost"}) + , GO_HOME_WHEN_DONE(false) + , CONSOLES(MaxLairBossFinder_ConsoleFactory()) + , NOTIFICATION_STATUS("Status Update", true, false) + , NOTIFICATION_SHINY("Shiny Catch", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) + , NOTIFICATIONS({ + &HOSTING.NOTIFICATIONS.NOTIFICATION, + &NOTIFICATION_STATUS, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(CONSOLES); + PA_ADD_OPTION(BOSS_LIST); + PA_ADD_OPTION(HOSTING); + + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + PA_ADD_OPTION(NOTIFICATIONS); +} + +std::string MaxLairBossFinder::check_validity() const{ + std::string error = MultiSwitchProgramInstance::check_validity(); + if (!error.empty()){ + return error; + } + + size_t active_consoles = CONSOLES.active_consoles(); + error = CONSOLES.HOST.check_validity(active_consoles); + if (!error.empty()){ + return error; + } + error = HOSTING.check_validity(active_consoles); + if (!error.empty()){ + return error; + } + return std::string(); +} +void MaxLairBossFinder::update_active_consoles(size_t switch_count){ + CONSOLES.set_active_consoles(switch_count); +} + + + + +class EndBattleDecider_BossFinder : public EndBattleDecider{ +public: + EndBattleDecider_BossFinder(const Consoles& consoles, const BossActionTable& boss_list) + : m_consoles(consoles) + , m_boss_list(boss_list) + {} + virtual const std::string& normal_ball( + size_t console_index + ) const override{ + return console(console_index).normal_ball.slug(); + } + virtual const std::string& boss_ball( + size_t console_index, const std::string& boss_slug + ) const override{ + return get_filter(boss_slug).ball.slug(); + } + virtual CaughtScreenAction end_adventure_action( + size_t console_index, const std::string& boss_slug, + const PathStats& path_stats, + bool any_shiny, bool boss_is_shiny + ) const override{ + if (boss_slug.empty()){ + return CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE; + } + switch (get_filter(boss_slug).action){ + case BossAction::CATCH_AND_STOP_PROGRAM: + return CaughtScreenAction::STOP_PROGRAM; + case BossAction::CATCH_AND_STOP_IF_SHINY: + return boss_is_shiny + ? CaughtScreenAction::STOP_PROGRAM + : CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid enum."); + } + + +private: + const BossActionRow& get_filter(const std::string& boss_slug) const{ + for (const StaticTableRow* row : m_boss_list.table()){ + const BossActionRow& filter = static_cast(*row); + if (boss_slug == filter.slug()){ + return filter; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Unrecognized boss slug: " + boss_slug); + } + +private: + const MaxLairBossFinder_ConsoleOptions& console(size_t index) const{ + return static_cast(m_consoles[index]); + } + + const Consoles& m_consoles; + const BossActionTable& m_boss_list; + +}; + + + + + +void MaxLairBossFinder::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + size_t host_index = CONSOLES.HOST.current_value(); + if (host_index >= env.consoles.size()){ + throw UserSetupError(env.logger(), "Invalid Host Switch"); + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + assert_16_9_720p_min(console, console); + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + }); + + EndBattleDecider_BossFinder decider(CONSOLES, BOSS_LIST); + + loop_adventures( + env, scope, CONSOLES, + host_index, 0, + decider, + GO_HOME_WHEN_DONE, + HOSTING, + TOUCH_DATE_INTERVAL, + NOTIFICATION_STATUS, + NOTIFICATION_SHINY + ); + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.h index b8d66f8b49..387cf04401 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_BossFinder.h @@ -1,63 +1,63 @@ -/* Max Lair (Boss Finder) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_BossFinder_H -#define PokemonAutomation_PokemonSwSh_MaxLair_BossFinder_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "Options/PokemonSwSh_MaxLair_Options.h" -#include "Options/PokemonSwSh_MaxLair_Options_Consoles.h" -#include "Options/PokemonSwSh_MaxLair_Options_Hosting.h" -#include "Options/PokemonSwSh_MaxLair_Options_BossAction.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class MaxLairBossFinder_Descriptor : public MultiSwitchProgramDescriptor{ -public: - MaxLairBossFinder_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class MaxLairBossFinder : public MultiSwitchProgramInstance{ -public: - MaxLairBossFinder(); - - virtual std::string check_validity() const override; - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - MaxLairInternal::Consoles CONSOLES; - MaxLairInternal::BossActionTable BOSS_LIST; - MaxLairInternal::HostingSettings HOSTING; - - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Max Lair (Boss Finder) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_BossFinder_H +#define PokemonAutomation_PokemonSwSh_MaxLair_BossFinder_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "Options/PokemonSwSh_MaxLair_Options.h" +#include "Options/PokemonSwSh_MaxLair_Options_Consoles.h" +#include "Options/PokemonSwSh_MaxLair_Options_Hosting.h" +#include "Options/PokemonSwSh_MaxLair_Options_BossAction.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class MaxLairBossFinder_Descriptor : public MultiSwitchProgramDescriptor{ +public: + MaxLairBossFinder_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class MaxLairBossFinder : public MultiSwitchProgramInstance{ +public: + MaxLairBossFinder(); + + virtual std::string check_validity() const override; + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + MaxLairInternal::Consoles CONSOLES; + MaxLairInternal::BossActionTable BOSS_LIST; + MaxLairInternal::HostingSettings HOSTING; + + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.cpp index 94aa474a8b..55dc7b56ae 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.cpp @@ -1,221 +1,221 @@ -/* Max Lair (Normal Mode) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "Program/PokemonSwSh_MaxLair_Run_Adventure.h" -#include "PokemonSwSh_MaxLair_Standard.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace MaxLairInternal; - - - -MaxLairStandard_Descriptor::MaxLairStandard_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSwSh:MaxLair-Standard", - STRING_POKEMON + " SwSh", "Max Lair - Standard", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MaxLair-Standard.md", - "Auto Max Lair 2.0 - Run Dynamax Adventures until a shiny legendary is found.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 1, 4, 1 - ) -{} -std::unique_ptr MaxLairStandard_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -class MaxLairStandard_ConsoleOptions : public ConsoleSpecificOptions{ -public: - MaxLairStandard_ConsoleOptions( - std::string label, - const LanguageSet& languages, - bool host - ) - : ConsoleSpecificOptions(std::move(label), languages, host) - , normal_ball( - "Normal Ball: Ball for catching non-boss " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "poke-ball" - ) - , boss_ball( - "Boss Ball: Ball for catching the boss/legendary " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "poke-ball" - ) - , actions(true, false) - { - PA_ADD_OPTION(normal_ball); - PA_ADD_OPTION(boss_ball); - PA_ADD_OPTION(actions); - } - - PokemonBallSelectOption normal_ball; - PokemonBallSelectOption boss_ball; - CaughtScreenActionsOption actions; -}; -class MaxLairStandard_ConsoleFactory : public ConsoleSpecificOptionsFactory{ -public: - virtual std::unique_ptr make( - std::string label, - const LanguageSet& languages, - bool is_host - ) const override{ - return std::unique_ptr(new MaxLairStandard_ConsoleOptions(std::move(label), languages, is_host)); - } -}; - - -MaxLairStandard::MaxLairStandard() - : MultiSwitchProgramInstance({"Notifs", "LiveHost"}) - , GO_HOME_WHEN_DONE(false) - , CONSOLES(MaxLairStandard_ConsoleFactory()) - , NOTIFICATION_STATUS("Status Update", true, false) - , NOTIFICATION_SHINY("Shiny Catch", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) - , NOTIFICATIONS({ - &HOSTING.NOTIFICATIONS.NOTIFICATION, - &NOTIFICATION_STATUS, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(BOSS_SLOT); - - PA_ADD_OPTION(CONSOLES); - PA_ADD_OPTION(HOSTING); - - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - PA_ADD_OPTION(NOTIFICATIONS); -} - -std::string MaxLairStandard::check_validity() const{ - std::string error = MultiSwitchProgramInstance::check_validity(); - if (!error.empty()){ - return error; - } - - size_t active_consoles = CONSOLES.active_consoles(); - error = CONSOLES.HOST.check_validity(active_consoles); - if (!error.empty()){ - return error; - } - error = HOSTING.check_validity(active_consoles); - if (!error.empty()){ - return error; - } - return std::string(); -} -void MaxLairStandard::update_active_consoles(size_t switch_count){ - CONSOLES.set_active_consoles(switch_count); -} - - - - - -class EndBattleDecider_Standard : public EndBattleDecider{ -public: - EndBattleDecider_Standard(const Consoles& consoles) - : m_consoles(consoles) - {} - virtual const std::string& normal_ball( - size_t console_index - ) const override{ - return console(console_index).normal_ball.slug(); - } - virtual const std::string& boss_ball( - size_t console_index, const std::string& boss_slug - ) const override{ - return console(console_index).boss_ball.slug(); - } - virtual CaughtScreenAction end_adventure_action( - size_t console_index, const std::string& boss_slug, - const PathStats& path_stats, - bool any_shiny, bool boss_is_shiny - ) const override{ - const CaughtScreenActionsOption& actions = console(console_index).actions; - if (boss_is_shiny){ - return actions.shiny_boss; - } - if (any_shiny){ - return actions.shiny_nonboss; - } - return actions.no_shinies; - } - -private: - const MaxLairStandard_ConsoleOptions& console(size_t index) const{ - return static_cast(m_consoles[index]); - } - - const Consoles& m_consoles; -}; - - - - -void MaxLairStandard::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - size_t host_index = CONSOLES.HOST.current_value(); - if (host_index >= env.consoles.size()){ - throw UserSetupError(env.logger(), "Invalid Host Switch"); - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - assert_16_9_720p_min(console, console); - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - }); - - EndBattleDecider_Standard decider(CONSOLES); - - loop_adventures( - env, scope, CONSOLES, - host_index, BOSS_SLOT.current_value(), - decider, - GO_HOME_WHEN_DONE, - HOSTING, - TOUCH_DATE_INTERVAL, - NOTIFICATION_STATUS, - NOTIFICATION_SHINY - ); - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - -} -} -} +/* Max Lair (Normal Mode) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "Program/PokemonSwSh_MaxLair_Run_Adventure.h" +#include "PokemonSwSh_MaxLair_Standard.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace MaxLairInternal; + + + +MaxLairStandard_Descriptor::MaxLairStandard_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSwSh:MaxLair-Standard", + STRING_POKEMON + " SwSh", "Max Lair - Standard", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MaxLair-Standard.md", + "Auto Max Lair 2.0 - Run Dynamax Adventures until a shiny legendary is found.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 1, 4, 1 + ) +{} +std::unique_ptr MaxLairStandard_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +class MaxLairStandard_ConsoleOptions : public ConsoleSpecificOptions{ +public: + MaxLairStandard_ConsoleOptions( + std::string label, + const LanguageSet& languages, + bool host + ) + : ConsoleSpecificOptions(std::move(label), languages, host) + , normal_ball( + "Normal Ball: Ball for catching non-boss " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "poke-ball" + ) + , boss_ball( + "Boss Ball: Ball for catching the boss/legendary " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "poke-ball" + ) + , actions(true, false) + { + PA_ADD_OPTION(normal_ball); + PA_ADD_OPTION(boss_ball); + PA_ADD_OPTION(actions); + } + + PokemonBallSelectOption normal_ball; + PokemonBallSelectOption boss_ball; + CaughtScreenActionsOption actions; +}; +class MaxLairStandard_ConsoleFactory : public ConsoleSpecificOptionsFactory{ +public: + virtual std::unique_ptr make( + std::string label, + const LanguageSet& languages, + bool is_host + ) const override{ + return std::unique_ptr(new MaxLairStandard_ConsoleOptions(std::move(label), languages, is_host)); + } +}; + + +MaxLairStandard::MaxLairStandard() + : MultiSwitchProgramInstance({"Notifs", "LiveHost"}) + , GO_HOME_WHEN_DONE(false) + , CONSOLES(MaxLairStandard_ConsoleFactory()) + , NOTIFICATION_STATUS("Status Update", true, false) + , NOTIFICATION_SHINY("Shiny Catch", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) + , NOTIFICATIONS({ + &HOSTING.NOTIFICATIONS.NOTIFICATION, + &NOTIFICATION_STATUS, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(BOSS_SLOT); + + PA_ADD_OPTION(CONSOLES); + PA_ADD_OPTION(HOSTING); + + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + PA_ADD_OPTION(NOTIFICATIONS); +} + +std::string MaxLairStandard::check_validity() const{ + std::string error = MultiSwitchProgramInstance::check_validity(); + if (!error.empty()){ + return error; + } + + size_t active_consoles = CONSOLES.active_consoles(); + error = CONSOLES.HOST.check_validity(active_consoles); + if (!error.empty()){ + return error; + } + error = HOSTING.check_validity(active_consoles); + if (!error.empty()){ + return error; + } + return std::string(); +} +void MaxLairStandard::update_active_consoles(size_t switch_count){ + CONSOLES.set_active_consoles(switch_count); +} + + + + + +class EndBattleDecider_Standard : public EndBattleDecider{ +public: + EndBattleDecider_Standard(const Consoles& consoles) + : m_consoles(consoles) + {} + virtual const std::string& normal_ball( + size_t console_index + ) const override{ + return console(console_index).normal_ball.slug(); + } + virtual const std::string& boss_ball( + size_t console_index, const std::string& boss_slug + ) const override{ + return console(console_index).boss_ball.slug(); + } + virtual CaughtScreenAction end_adventure_action( + size_t console_index, const std::string& boss_slug, + const PathStats& path_stats, + bool any_shiny, bool boss_is_shiny + ) const override{ + const CaughtScreenActionsOption& actions = console(console_index).actions; + if (boss_is_shiny){ + return actions.shiny_boss; + } + if (any_shiny){ + return actions.shiny_nonboss; + } + return actions.no_shinies; + } + +private: + const MaxLairStandard_ConsoleOptions& console(size_t index) const{ + return static_cast(m_consoles[index]); + } + + const Consoles& m_consoles; +}; + + + + +void MaxLairStandard::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + size_t host_index = CONSOLES.HOST.current_value(); + if (host_index >= env.consoles.size()){ + throw UserSetupError(env.logger(), "Invalid Host Switch"); + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + assert_16_9_720p_min(console, console); + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + }); + + EndBattleDecider_Standard decider(CONSOLES); + + loop_adventures( + env, scope, CONSOLES, + host_index, BOSS_SLOT.current_value(), + decider, + GO_HOME_WHEN_DONE, + HOSTING, + TOUCH_DATE_INTERVAL, + NOTIFICATION_STATUS, + NOTIFICATION_SHINY + ); + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.h index c535ec16c9..7a2231b2cd 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_Standard.h @@ -1,68 +1,68 @@ -/* Max Lair (Standard Mode) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Standard_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Standard_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "Options/PokemonSwSh_MaxLair_Options.h" -#include "Options/PokemonSwSh_MaxLair_Options_Consoles.h" -#include "Options/PokemonSwSh_MaxLair_Options_Hosting.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class MaxLairStandard_Descriptor : public MultiSwitchProgramDescriptor{ -public: - MaxLairStandard_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class MaxLairStandard : public MultiSwitchProgramInstance{ -public: - enum class StopCondition{ - STOP_ON_SHINY_LEGENDARY, - STOP_ON_NOTHING, - }; - -public: - MaxLairStandard(); - - virtual std::string check_validity() const override; - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - MaxLairInternal::BossSlotOption BOSS_SLOT; - - MaxLairInternal::Consoles CONSOLES; - MaxLairInternal::HostingSettings HOSTING; - - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Max Lair (Standard Mode) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Standard_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Standard_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "Options/PokemonSwSh_MaxLair_Options.h" +#include "Options/PokemonSwSh_MaxLair_Options_Consoles.h" +#include "Options/PokemonSwSh_MaxLair_Options_Hosting.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class MaxLairStandard_Descriptor : public MultiSwitchProgramDescriptor{ +public: + MaxLairStandard_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class MaxLairStandard : public MultiSwitchProgramInstance{ +public: + enum class StopCondition{ + STOP_ON_SHINY_LEGENDARY, + STOP_ON_NOTHING, + }; + +public: + MaxLairStandard(); + + virtual std::string check_validity() const override; + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + MaxLairInternal::BossSlotOption BOSS_SLOT; + + MaxLairInternal::Consoles CONSOLES; + MaxLairInternal::HostingSettings HOSTING; + + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.cpp index d3219b8e87..019f7db1e3 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.cpp @@ -1,277 +1,277 @@ -/* Max Lair (Strong-Boss Mode) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/StartupChecks/VideoResolutionCheck.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "Program/PokemonSwSh_MaxLair_Run_Adventure.h" -#include "PokemonSwSh_MaxLair_StrongBoss.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace MaxLairInternal; - - - -MaxLairStrongBoss_Descriptor::MaxLairStrongBoss_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSwSh:MaxLair-StrongBoss", - STRING_POKEMON + " SwSh", "Max Lair - Strong Boss", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MaxLair-StrongBoss.md", - "Auto Max Lair 2.0 - Run Dynamax Adventures and intelligently reset to keep paths that have high win rates.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER, - 1, 4, 1 - ) -{} -std::unique_ptr MaxLairStrongBoss_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -class MaxLairStrongBoss_ConsoleOptions : public ConsoleSpecificOptions{ -public: - MaxLairStrongBoss_ConsoleOptions(std::string label, const LanguageSet& languages, bool host) - : ConsoleSpecificOptions(std::move(label), languages, host) - , normal_ball( - "Normal Ball: Ball for catching non-boss " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "poke-ball" - ) - , boss_ball( - "Boss Ball: Ball for catching the boss/legendary " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "poke-ball" - ) - , actions_non_host(false, false) - , actions_host( - false, true, - CaughtScreenAction::RESET, - CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, - CaughtScreenAction::STOP_PROGRAM - ) - { - if (host){ - actions_non_host.set_visibility(ConfigOptionState::HIDDEN); - }else{ - actions_host.set_visibility(ConfigOptionState::ENABLED); - } - PA_ADD_OPTION(normal_ball); - PA_ADD_OPTION(boss_ball); - PA_ADD_OPTION(actions_non_host); - PA_ADD_OPTION(actions_host); - } - - const CaughtScreenActionsOption& actions() const{ - return is_host ? actions_host : actions_non_host; - } - virtual void set_host(bool is_host) override{ - ConsoleSpecificOptions::set_host(is_host); - if (is_host){ - actions_host.set_visibility(ConfigOptionState::ENABLED); - actions_non_host.set_visibility(ConfigOptionState::HIDDEN); - }else{ - actions_host.set_visibility(ConfigOptionState::HIDDEN); - actions_non_host.set_visibility(ConfigOptionState::ENABLED); - } - } - - PokemonBallSelectOption normal_ball; - PokemonBallSelectOption boss_ball; - CaughtScreenActionsOption actions_non_host; - CaughtScreenActionsOption actions_host; -}; -class MaxLairStrongBoss_ConsoleFactory : public ConsoleSpecificOptionsFactory{ -public: - virtual std::unique_ptr make(std::string label, const LanguageSet& languages, bool is_host) const override{ - return std::unique_ptr(new MaxLairStrongBoss_ConsoleOptions(std::move(label), languages, is_host)); - } -}; - - -MaxLairStrongBoss::MaxLairStrongBoss() - : MultiSwitchProgramInstance({"Notifs", "LiveHost"}) - , GO_HOME_WHEN_DONE(false) - , MIN_WIN_RATE( - "Minimum Win Rate:
" - "Keep the path if the win rate stays above this ratio. This is done by resetting the host.", - LockMode::LOCK_WHILE_RUNNING, - 0.75, 0, 1.0 - ) - , CONSOLES(MaxLairStrongBoss_ConsoleFactory()) - , NOTIFICATION_STATUS("Status Update", true, false) - , NOTIFICATION_SHINY("Shiny Catch", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) - , NOTIFICATIONS({ - &HOSTING.NOTIFICATIONS.NOTIFICATION, - &NOTIFICATION_STATUS, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(MIN_WIN_RATE); - PA_ADD_OPTION(BOSS_SLOT); - - PA_ADD_OPTION(CONSOLES); - PA_ADD_OPTION(HOSTING); - - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - PA_ADD_OPTION(NOTIFICATIONS); -} - -std::string MaxLairStrongBoss::check_validity() const{ - std::string error = MultiSwitchProgramInstance::check_validity(); - if (!error.empty()){ - return error; - } - - size_t active_consoles = CONSOLES.active_consoles(); - error = CONSOLES.HOST.check_validity(active_consoles); - if (!error.empty()){ - return error; - } - error = HOSTING.check_validity(active_consoles); - if (!error.empty()){ - return error; - } - return std::string(); -} -void MaxLairStrongBoss::update_active_consoles(size_t switch_count){ - CONSOLES.set_active_consoles(switch_count); -} - - - - - -class EndBattleDecider_StrongBoss : public EndBattleDecider{ -public: - EndBattleDecider_StrongBoss( - Logger& logger, - const Consoles& consoles, size_t host_index, - double min_win_ratio - ) - : m_logger(logger) - , m_consoles(consoles) - , m_host_index(host_index) - , m_min_win_ratio(min_win_ratio) - {} - virtual const std::string& normal_ball( - size_t console_index - ) const override{ - return console(console_index).normal_ball.slug(); - } - virtual const std::string& boss_ball( - size_t console_index, const std::string& boss_slug - ) const override{ - return console(console_index).boss_ball.slug(); - } - virtual CaughtScreenAction end_adventure_action( - size_t console_index, const std::string& boss_slug, - const PathStats& path_stats, - bool any_shiny, bool boss_is_shiny - ) const override{ - const CaughtScreenActionsOption& actions = console(console_index).actions(); - CaughtScreenAction action; - do{ - if (boss_is_shiny){ - action = actions.shiny_boss; - break; - } - if (any_shiny){ - action = actions.shiny_nonboss; - break; - } - action = actions.no_shinies; - }while (false); - if (action != CaughtScreenAction::RESET || console_index != m_host_index){ - return action; - } - double win_ratio = path_stats.win_ratio(); - if (win_ratio >= m_min_win_ratio){ - m_logger.log("Win Ratio = " + tostr_default(win_ratio) + ": Resetting to keep path.", COLOR_BLUE); - return CaughtScreenAction::RESET; - }else{ - m_logger.log("Win Ratio = " + tostr_default(win_ratio) + ": Continuing to get new path.", COLOR_BLUE); - return CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE; - } - } - -private: - const MaxLairStrongBoss_ConsoleOptions& console(size_t index) const{ - return static_cast(m_consoles[index]); - } - - Logger& m_logger; - const Consoles& m_consoles; - size_t m_host_index; - double m_min_win_ratio; -}; - - - -void MaxLairStrongBoss::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - size_t host_index = CONSOLES.HOST.current_value(); - if (host_index >= env.consoles.size()){ - throw UserSetupError(env.logger(), "Invalid Host Switch"); - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - assert_16_9_720p_min(console, console); - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - }); - - EndBattleDecider_StrongBoss decider( - env.logger(), - CONSOLES, host_index, - MIN_WIN_RATE - ); - - loop_adventures( - env, scope, CONSOLES, - host_index, BOSS_SLOT.current_value(), - decider, - GO_HOME_WHEN_DONE, - HOSTING, - TOUCH_DATE_INTERVAL, - NOTIFICATION_STATUS, - NOTIFICATION_SHINY - ); - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - - - -} -} -} +/* Max Lair (Strong-Boss Mode) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/StartupChecks/VideoResolutionCheck.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "Program/PokemonSwSh_MaxLair_Run_Adventure.h" +#include "PokemonSwSh_MaxLair_StrongBoss.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace MaxLairInternal; + + + +MaxLairStrongBoss_Descriptor::MaxLairStrongBoss_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSwSh:MaxLair-StrongBoss", + STRING_POKEMON + " SwSh", "Max Lair - Strong Boss", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MaxLair-StrongBoss.md", + "Auto Max Lair 2.0 - Run Dynamax Adventures and intelligently reset to keep paths that have high win rates.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER, + 1, 4, 1 + ) +{} +std::unique_ptr MaxLairStrongBoss_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +class MaxLairStrongBoss_ConsoleOptions : public ConsoleSpecificOptions{ +public: + MaxLairStrongBoss_ConsoleOptions(std::string label, const LanguageSet& languages, bool host) + : ConsoleSpecificOptions(std::move(label), languages, host) + , normal_ball( + "Normal Ball: Ball for catching non-boss " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "poke-ball" + ) + , boss_ball( + "Boss Ball: Ball for catching the boss/legendary " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "poke-ball" + ) + , actions_non_host(false, false) + , actions_host( + false, true, + CaughtScreenAction::RESET, + CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE, + CaughtScreenAction::STOP_PROGRAM + ) + { + if (host){ + actions_non_host.set_visibility(ConfigOptionState::HIDDEN); + }else{ + actions_host.set_visibility(ConfigOptionState::ENABLED); + } + PA_ADD_OPTION(normal_ball); + PA_ADD_OPTION(boss_ball); + PA_ADD_OPTION(actions_non_host); + PA_ADD_OPTION(actions_host); + } + + const CaughtScreenActionsOption& actions() const{ + return is_host ? actions_host : actions_non_host; + } + virtual void set_host(bool is_host) override{ + ConsoleSpecificOptions::set_host(is_host); + if (is_host){ + actions_host.set_visibility(ConfigOptionState::ENABLED); + actions_non_host.set_visibility(ConfigOptionState::HIDDEN); + }else{ + actions_host.set_visibility(ConfigOptionState::HIDDEN); + actions_non_host.set_visibility(ConfigOptionState::ENABLED); + } + } + + PokemonBallSelectOption normal_ball; + PokemonBallSelectOption boss_ball; + CaughtScreenActionsOption actions_non_host; + CaughtScreenActionsOption actions_host; +}; +class MaxLairStrongBoss_ConsoleFactory : public ConsoleSpecificOptionsFactory{ +public: + virtual std::unique_ptr make(std::string label, const LanguageSet& languages, bool is_host) const override{ + return std::unique_ptr(new MaxLairStrongBoss_ConsoleOptions(std::move(label), languages, is_host)); + } +}; + + +MaxLairStrongBoss::MaxLairStrongBoss() + : MultiSwitchProgramInstance({"Notifs", "LiveHost"}) + , GO_HOME_WHEN_DONE(false) + , MIN_WIN_RATE( + "Minimum Win Rate:
" + "Keep the path if the win rate stays above this ratio. This is done by resetting the host.", + LockMode::LOCK_WHILE_RUNNING, + 0.75, 0, 1.0 + ) + , CONSOLES(MaxLairStrongBoss_ConsoleFactory()) + , NOTIFICATION_STATUS("Status Update", true, false) + , NOTIFICATION_SHINY("Shiny Catch", true, true, ImageAttachmentMode::JPG, {"Notifs", "Showcase"}) + , NOTIFICATIONS({ + &HOSTING.NOTIFICATIONS.NOTIFICATION, + &NOTIFICATION_STATUS, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(MIN_WIN_RATE); + PA_ADD_OPTION(BOSS_SLOT); + + PA_ADD_OPTION(CONSOLES); + PA_ADD_OPTION(HOSTING); + + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + PA_ADD_OPTION(NOTIFICATIONS); +} + +std::string MaxLairStrongBoss::check_validity() const{ + std::string error = MultiSwitchProgramInstance::check_validity(); + if (!error.empty()){ + return error; + } + + size_t active_consoles = CONSOLES.active_consoles(); + error = CONSOLES.HOST.check_validity(active_consoles); + if (!error.empty()){ + return error; + } + error = HOSTING.check_validity(active_consoles); + if (!error.empty()){ + return error; + } + return std::string(); +} +void MaxLairStrongBoss::update_active_consoles(size_t switch_count){ + CONSOLES.set_active_consoles(switch_count); +} + + + + + +class EndBattleDecider_StrongBoss : public EndBattleDecider{ +public: + EndBattleDecider_StrongBoss( + Logger& logger, + const Consoles& consoles, size_t host_index, + double min_win_ratio + ) + : m_logger(logger) + , m_consoles(consoles) + , m_host_index(host_index) + , m_min_win_ratio(min_win_ratio) + {} + virtual const std::string& normal_ball( + size_t console_index + ) const override{ + return console(console_index).normal_ball.slug(); + } + virtual const std::string& boss_ball( + size_t console_index, const std::string& boss_slug + ) const override{ + return console(console_index).boss_ball.slug(); + } + virtual CaughtScreenAction end_adventure_action( + size_t console_index, const std::string& boss_slug, + const PathStats& path_stats, + bool any_shiny, bool boss_is_shiny + ) const override{ + const CaughtScreenActionsOption& actions = console(console_index).actions(); + CaughtScreenAction action; + do{ + if (boss_is_shiny){ + action = actions.shiny_boss; + break; + } + if (any_shiny){ + action = actions.shiny_nonboss; + break; + } + action = actions.no_shinies; + }while (false); + if (action != CaughtScreenAction::RESET || console_index != m_host_index){ + return action; + } + double win_ratio = path_stats.win_ratio(); + if (win_ratio >= m_min_win_ratio){ + m_logger.log("Win Ratio = " + tostr_default(win_ratio) + ": Resetting to keep path.", COLOR_BLUE); + return CaughtScreenAction::RESET; + }else{ + m_logger.log("Win Ratio = " + tostr_default(win_ratio) + ": Continuing to get new path.", COLOR_BLUE); + return CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE; + } + } + +private: + const MaxLairStrongBoss_ConsoleOptions& console(size_t index) const{ + return static_cast(m_consoles[index]); + } + + Logger& m_logger; + const Consoles& m_consoles; + size_t m_host_index; + double m_min_win_ratio; +}; + + + +void MaxLairStrongBoss::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + size_t host_index = CONSOLES.HOST.current_value(); + if (host_index >= env.consoles.size()){ + throw UserSetupError(env.logger(), "Invalid Host Switch"); + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + assert_16_9_720p_min(console, console); + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + }); + + EndBattleDecider_StrongBoss decider( + env.logger(), + CONSOLES, host_index, + MIN_WIN_RATE + ); + + loop_adventures( + env, scope, CONSOLES, + host_index, BOSS_SLOT.current_value(), + decider, + GO_HOME_WHEN_DONE, + HOSTING, + TOUCH_DATE_INTERVAL, + NOTIFICATION_STATUS, + NOTIFICATION_SHINY + ); + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.h index b34b34ee46..c12e86ef9a 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/PokemonSwSh_MaxLair_StrongBoss.h @@ -1,72 +1,72 @@ -/* Max Lair (Strong-Boss Mode) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_StrongBoss_H -#define PokemonAutomation_PokemonSwSh_MaxLair_StrongBoss_H - -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "Options/PokemonSwSh_MaxLair_Options.h" -#include "Options/PokemonSwSh_MaxLair_Options_Consoles.h" -#include "Options/PokemonSwSh_MaxLair_Options_Hosting.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class MaxLairStrongBoss_Descriptor : public MultiSwitchProgramDescriptor{ -public: - MaxLairStrongBoss_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - -class MaxLairStrongBoss : public MultiSwitchProgramInstance{ -public: - enum class StopCondition{ - STOP_ON_SHINY_LEGENDARY, - STOP_ON_NOTHING, - }; - -public: - MaxLairStrongBoss(); - - virtual std::string check_validity() const override; - virtual void update_active_consoles(size_t switch_count) override; - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - FloatingPointOption MIN_WIN_RATE; - MaxLairInternal::BossSlotOption BOSS_SLOT; - - MaxLairInternal::Consoles CONSOLES; - MaxLairInternal::HostingSettings HOSTING; - - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - EventNotificationOption NOTIFICATION_STATUS; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; -}; - - - - - -} -} -} -#endif +/* Max Lair (Strong-Boss Mode) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_StrongBoss_H +#define PokemonAutomation_PokemonSwSh_MaxLair_StrongBoss_H + +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "Options/PokemonSwSh_MaxLair_Options.h" +#include "Options/PokemonSwSh_MaxLair_Options_Consoles.h" +#include "Options/PokemonSwSh_MaxLair_Options_Hosting.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class MaxLairStrongBoss_Descriptor : public MultiSwitchProgramDescriptor{ +public: + MaxLairStrongBoss_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + +class MaxLairStrongBoss : public MultiSwitchProgramInstance{ +public: + enum class StopCondition{ + STOP_ON_SHINY_LEGENDARY, + STOP_ON_NOTHING, + }; + +public: + MaxLairStrongBoss(); + + virtual std::string check_validity() const override; + virtual void update_active_consoles(size_t switch_count) override; + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + FloatingPointOption MIN_WIN_RATE; + MaxLairInternal::BossSlotOption BOSS_SLOT; + + MaxLairInternal::Consoles CONSOLES; + MaxLairInternal::HostingSettings HOSTING; + + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + EventNotificationOption NOTIFICATION_STATUS; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.cpp index 8368ee7ed4..5ae777b12f 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.cpp @@ -1,211 +1,211 @@ -/* Max Lair Run Adventure - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ErrorReports/ErrorReports.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" -#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h" -#include "PokemonSwSh_MaxLair_Run_Adventure.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -AdventureResult run_adventure( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - size_t boss_slot, - AdventureRuntime& runtime -){ - env.log("Starting new adventure..."); - env.update_stats(); - - send_status_notification(env, runtime); - - std::shared_ptr entrance[4]; - GlobalStateTracker state_tracker(scope, env.consoles.size()); - - if (!start_adventure( - env, scope, - state_tracker, - entrance, - env.consoles[runtime.host_index], boss_slot, - runtime.hosting_settings, - runtime.path_stats, - runtime.session_stats, - runtime.consoles - )){ - runtime.session_stats.add_error(); - return AdventureResult::START_ERROR; - } - - uint64_t epoch = 0; - SpinLock lock; - - std::atomic stop(false); - std::atomic error(false); - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - StateMachineAction action; - while (true){ - // Dump current state, but don't spam if nothing has changed. - { - WriteSpinLock lg(lock); - std::pair status = state_tracker.dump(); - if (status.first > epoch){ - console.log("State Tracker\n" + status.second); - epoch = status.first; - } - } - - size_t index = console.index(); - action = run_state_iteration( - runtime, index, - env, console, context, boss_slot != 0 && console.index() == runtime.host_index, - state_tracker, runtime.actions, - *entrance[index] - ); - switch (action){ - case StateMachineAction::KEEP_GOING: - continue; - case StateMachineAction::DONE_WITH_ADVENTURE: - env.log("End of adventure.", COLOR_PURPLE); - return; - case StateMachineAction::STOP_PROGRAM: - env.log("End of adventure. Stop program requested...", COLOR_PURPLE); - if (runtime.go_home_when_done){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - } - stop.store(true, std::memory_order_release); - return; - case StateMachineAction::RESET_RECOVER: - env.log("Error detected. Attempting to correct by resetting...", COLOR_RED); - runtime.session_stats.add_error(); - error.store(true, std::memory_order_release); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - reset_game_from_home_with_inference(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - return; - } - } - }); - - std::string boss = state_tracker.infer_actual_state(0).boss; - if (!boss.empty()){ - runtime.last_boss = std::move(boss); - } - - if (stop.load(std::memory_order_acquire)){ - return AdventureResult::STOP_PROGRAM; - } -// if (error.load(std::memory_order_acquire)){ -// return AdventureResult::START_ERROR; -// } - return AdventureResult::FINISHED; -} - - - - - -void loop_adventures( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - const Consoles& consoles, - size_t host_index, size_t boss_slot, - const EndBattleDecider& decider, - bool go_home_when_done, - HostingSettings& HOSTING, - TouchDateIntervalOption& TOUCH_DATE_INTERVAL, - EventNotificationOption& notification_status, - EventNotificationOption& notification_shiny -){ - Stats& stats = env.current_stats(); - - AdventureRuntime runtime( - env.consoles, - host_index, - consoles, - decider, - go_home_when_done, - HOSTING, - notification_status, - notification_shiny, - stats - ); - - size_t restart_count = 0; - while (true){ - // Touch the date. - if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - env.log("Touching date to prevent rollover."); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_back_out(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 5 * TICKS_PER_SECOND); - }); - } - - AdventureResult result = run_adventure(env, scope, boss_slot, runtime); - switch (result){ - case AdventureResult::FINISHED: - restart_count = 0; - continue; - case AdventureResult::STOP_PROGRAM: - return; - case AdventureResult::START_ERROR: - restart_count++; - if (restart_count == 3){ - report_error( - &env.logger(), - env.program_info(), - "Error", - {{"Message:", "Failed to start adventure 3 times in the row."}} - ); - throw_and_log( - env.logger(), ErrorReport::SEND_ERROR_REPORT, - "Failed to start adventure 3 times in the row." - ); - } - env.log("Failed to start adventure. Resetting all Switches...", COLOR_RED); - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - reset_game_from_home_with_inference(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }); - continue; - } - } -} - - - - - - - - - - - - - - - - - - - - - - -} -} -} -} +/* Max Lair Run Adventure + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ErrorReports/ErrorReports.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" +#include "PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h" +#include "PokemonSwSh_MaxLair_Run_Adventure.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +AdventureResult run_adventure( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + size_t boss_slot, + AdventureRuntime& runtime +){ + env.log("Starting new adventure..."); + env.update_stats(); + + send_status_notification(env, runtime); + + std::shared_ptr entrance[4]; + GlobalStateTracker state_tracker(scope, env.consoles.size()); + + if (!start_adventure( + env, scope, + state_tracker, + entrance, + env.consoles[runtime.host_index], boss_slot, + runtime.hosting_settings, + runtime.path_stats, + runtime.session_stats, + runtime.consoles + )){ + runtime.session_stats.add_error(); + return AdventureResult::START_ERROR; + } + + uint64_t epoch = 0; + SpinLock lock; + + std::atomic stop(false); + std::atomic error(false); + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + StateMachineAction action; + while (true){ + // Dump current state, but don't spam if nothing has changed. + { + WriteSpinLock lg(lock); + std::pair status = state_tracker.dump(); + if (status.first > epoch){ + console.log("State Tracker\n" + status.second); + epoch = status.first; + } + } + + size_t index = console.index(); + action = run_state_iteration( + runtime, index, + env, console, context, boss_slot != 0 && console.index() == runtime.host_index, + state_tracker, runtime.actions, + *entrance[index] + ); + switch (action){ + case StateMachineAction::KEEP_GOING: + continue; + case StateMachineAction::DONE_WITH_ADVENTURE: + env.log("End of adventure.", COLOR_PURPLE); + return; + case StateMachineAction::STOP_PROGRAM: + env.log("End of adventure. Stop program requested...", COLOR_PURPLE); + if (runtime.go_home_when_done){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + } + stop.store(true, std::memory_order_release); + return; + case StateMachineAction::RESET_RECOVER: + env.log("Error detected. Attempting to correct by resetting...", COLOR_RED); + runtime.session_stats.add_error(); + error.store(true, std::memory_order_release); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + reset_game_from_home_with_inference(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + return; + } + } + }); + + std::string boss = state_tracker.infer_actual_state(0).boss; + if (!boss.empty()){ + runtime.last_boss = std::move(boss); + } + + if (stop.load(std::memory_order_acquire)){ + return AdventureResult::STOP_PROGRAM; + } +// if (error.load(std::memory_order_acquire)){ +// return AdventureResult::START_ERROR; +// } + return AdventureResult::FINISHED; +} + + + + + +void loop_adventures( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + const Consoles& consoles, + size_t host_index, size_t boss_slot, + const EndBattleDecider& decider, + bool go_home_when_done, + HostingSettings& HOSTING, + TouchDateIntervalOption& TOUCH_DATE_INTERVAL, + EventNotificationOption& notification_status, + EventNotificationOption& notification_shiny +){ + Stats& stats = env.current_stats(); + + AdventureRuntime runtime( + env.consoles, + host_index, + consoles, + decider, + go_home_when_done, + HOSTING, + notification_status, + notification_shiny, + stats + ); + + size_t restart_count = 0; + while (true){ + // Touch the date. + if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + env.log("Touching date to prevent rollover."); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_back_out(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 5 * TICKS_PER_SECOND); + }); + } + + AdventureResult result = run_adventure(env, scope, boss_slot, runtime); + switch (result){ + case AdventureResult::FINISHED: + restart_count = 0; + continue; + case AdventureResult::STOP_PROGRAM: + return; + case AdventureResult::START_ERROR: + restart_count++; + if (restart_count == 3){ + report_error( + &env.logger(), + env.program_info(), + "Error", + {{"Message:", "Failed to start adventure 3 times in the row."}} + ); + throw_and_log( + env.logger(), ErrorReport::SEND_ERROR_REPORT, + "Failed to start adventure 3 times in the row." + ); + } + env.log("Failed to start adventure. Resetting all Switches...", COLOR_RED); + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + reset_game_from_home_with_inference(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }); + continue; + } + } +} + + + + + + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.h index 2bc8f54ca3..578aba8ed9 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Adventure.h @@ -1,46 +1,46 @@ -/* Max Lair Run Adventure - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Adventure_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Adventure_H - -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -enum class AdventureResult{ - FINISHED, - STOP_PROGRAM, - START_ERROR, -}; - - -void loop_adventures( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - const Consoles& consoles, - size_t host_index, size_t boss_slot, - const EndBattleDecider& decider, - bool go_home_when_done, - HostingSettings& HOSTING, - TouchDateIntervalOption& TOUCH_DATE_INTERVAL, - EventNotificationOption& notification_status, - EventNotificationOption& notification_shiny -); - - -} -} -} -} -#endif +/* Max Lair Run Adventure + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Adventure_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Adventure_H + +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +enum class AdventureResult{ + FINISHED, + STOP_PROGRAM, + START_ERROR, +}; + + +void loop_adventures( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + const Consoles& consoles, + size_t host_index, size_t boss_slot, + const EndBattleDecider& decider, + bool go_home_when_done, + HostingSettings& HOSTING, + TouchDateIntervalOption& TOUCH_DATE_INTERVAL, + EventNotificationOption& notification_status, + EventNotificationOption& notification_shiny +); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp index 678a2ddba1..625ee755b4 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.cpp @@ -1,381 +1,381 @@ -/* Max Lair Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -//#include "PokemonSwSh_MaxLair_Run_CaughtScreen.h" -#include "PokemonSwSh_MaxLair_Run_Battle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -bool read_battle_menu( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, size_t player_index, - OcrFailureWatchdog& ocr_watchdog, - GlobalState& state, - const ConsoleSpecificOptions& settings, - bool currently_dmaxed, bool cheer_only -){ - PlayerState& player = state.players[player_index]; - - VideoOverlaySet boxes(stream.overlay()); - BattleMenuReader reader(stream.overlay(), settings.language, ocr_watchdog); - BattleMoveArrowFinder arrow_finder(stream.overlay()); - arrow_finder.make_overlays(boxes); - - - // Read raid mon. - do{ - std::set mon = reader.read_opponent(stream.logger(), context, stream.video()); - if (mon.size() == 1){ - state.opponent = std::move(mon); - break; - } - if (mon.size() > 1){ - stream.log("Ambiguous Read Result: " + set_to_str(mon), COLOR_PURPLE); - if (state.opponent.size() == 1 && mon.find(*state.opponent.begin()) != mon.end()){ - stream.log("Using previous known value to disambiguate: " + set_to_str(mon), COLOR_PURPLE); - break; - } - } - if (state.opponent.size() == 1){ - stream.log("Failed to read opponent from battle. Using previously known value: " + set_to_str(state.opponent), COLOR_ORANGE); - break; - } - - stream.log("Unable to read opponent from battle. Attempting to read from summary.", COLOR_ORANGE); - pbf_press_button(context, BUTTON_Y, 10, TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - mon = reader.read_opponent_in_summary(stream.logger(), stream.video().snapshot()); - pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); - state.opponent = std::move(mon); - - if (state.wins == 3 && !state.boss.empty()){ - if (!state.opponent.empty() && *state.opponent.begin() != state.boss){ - stream.log("Inconsistent Boss: Expected " + state.boss + ", Read: " + *state.opponent.begin(), COLOR_RED); - } - state.opponent = {state.boss}; - break; - } - }while (false); - context.wait_for_all_requests(); - - const std::string& opponent = state.opponent.empty() - ? "" - : *state.opponent.begin(); - - if (state.wins != 3 && is_boss(opponent)){ - stream.log("Boss found before 3 wins. Something is seriously out-of-sync.", COLOR_RED); - dump_image(stream.logger(), MODULE_NAME, stream.video(), "BossBeforeEnd"); -// send_program_telemetry( -// env.logger(), true, COLOR_RED, MODULE_NAME, -// "Error", -// {{"Message:", "Boss found before 3 wins."}}, -// "" -// ); - return false; - } - - // Infer the boss if we don't know it. - if (state.boss.empty() && state.wins == 3){ - state.boss = opponent; - } - - // Read misc. - VideoSnapshot screen = stream.video().snapshot(); - state.opponent_hp = reader.read_opponent_hp(stream.logger(), screen); - if (cheer_only){ - player.dmax_turns_left = 0; - player.health = Health{0, 1}; - player.can_dmax = false; - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - return true; - } - - if (currently_dmaxed){ - player.dmax_turns_left--; - if (player.dmax_turns_left <= 0){ - stream.log("State Inconsistency: dmax_turns_left <= 0 && currently_dmaxed == true", COLOR_RED); - player.dmax_turns_left = 1; - } - }else{ - std::string name = reader.read_own_mon(stream.logger(), screen); - if (!name.empty()){ - state.players[player_index].pokemon = std::move(name); - } - if (player.dmax_turns_left > 1){ - stream.log("State Inconsistency: dmax_turns_left > 0 && currently_dmaxed == false", COLOR_RED); - state.move_slot = 0; - } - if (player.dmax_turns_left == 1){ - stream.log("End of Dmax."); - state.move_slot = 0; - } - player.dmax_turns_left = 0; - } - - Health health[4]; - reader.read_hp(stream.logger(), screen, health, player_index); - if (health[0].hp >= 0) state.players[0].health = health[0]; - if (health[1].hp >= 0) state.players[1].health = health[1]; - if (health[2].hp >= 0) state.players[2].health = health[2]; - if (health[3].hp >= 0) state.players[3].health = health[3]; - - - for (size_t attempts = 0; attempts < 5; attempts++){ - // Enter move selection to read PP. - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - - // Clear move blocked status. - player.move_blocked[0] = false; - player.move_blocked[1] = false; - player.move_blocked[2] = false; - player.move_blocked[3] = false; - - screen = stream.video().snapshot(); - - int8_t pp[4] = {-1, -1, -1, -1}; - reader.read_own_pp(stream.logger(), screen, pp); - player.pp[0] = pp[0]; - player.pp[1] = pp[1]; - player.pp[2] = pp[2]; - player.pp[3] = pp[3]; - - player.can_dmax = reader.can_dmax(screen); - - // Read move slot. - // int8_t move_slot = arrow_finder.get_slot(); - int8_t move_slot = arrow_finder.detect(screen); - if (move_slot < 0){ - stream.log("Unable to detect move slot.", COLOR_RED); -// dump_image(stream.logger(), MODULE_NAME, "MoveSlot", screen); -// pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); -// pbf_press_dpad(context, DPAD_RIGHT, 2 * TICKS_PER_SECOND, 0); -// pbf_press_dpad(context, DPAD_UP, 2 * TICKS_PER_SECOND, 0); -// move_slot = 0; - pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); - continue; - }else{ - stream.log("Current Move Slot: " + std::to_string(move_slot), COLOR_BLUE); - } - if (move_slot != state.move_slot){ - stream.log( - "Move Slot Mismatch: Expected = " + std::to_string(state.move_slot) + ", Actual = " + std::to_string(move_slot), - COLOR_RED - ); - } - state.move_slot = move_slot; - - return true; - } - - dump_image(stream.logger(), MODULE_NAME, "MoveSlot", screen); - return true; -} - - -StateMachineAction run_move_select( - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - OcrFailureWatchdog& ocr_watchdog, - GlobalStateTracker& state_tracker, - const ConsoleSpecificOptions& settings, - bool currently_dmaxed, bool cheer_only -){ - GlobalState& state = state_tracker[console_index]; - size_t player_index = state.find_player_index(console_index); - PlayerState& player = state.players[player_index]; - - - if (!read_battle_menu( - env, stream, context, player_index, - ocr_watchdog, - state, settings, - currently_dmaxed, cheer_only - )){ - return StateMachineAction::RESET_RECOVER; - } - - - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - - bool all_moves_blocked = false; - - while (true){ - stream.log("Selecting move..."); - - if (cheer_only){ - stream.log("Choosing move Cheer. (you are dead)", COLOR_PURPLE); -// pbf_mash_button(context, BUTTON_A, 2 * TICKS_PER_SECOND); -// context.wait_for_all_requests(); - break; - } - - std::pair move = select_move( - stream.logger(), - inferred, - player_index - ); - stream.log("Choosing move " + std::to_string((int)move.first) + (move.second ? " (dmax)." : "."), COLOR_PURPLE); - - if (player.can_dmax && move.second){ - pbf_press_dpad(context, DPAD_LEFT, 10, 50); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - player.dmax_turns_left = 3; - } - while (state.move_slot != move.first){ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - state.move_slot++; - state.move_slot %= 4; - } - - // Enter the move. - if (all_moves_blocked){ - // If we had trouble selecting a move, then we're probably stuck in a self-target loop. - // Force target the opponent. - stream.log("Force targeting opponent due to inability to select a move after multiple attempts...", COLOR_RED); - pbf_press_button(context, BUTTON_A, 20, 2 * TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_UP, 2 * TICKS_PER_SECOND, 0); - } - pbf_mash_button(context, BUTTON_A, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - -// inference.stop(); - - // Back out and look for battle menu. This indicates that the move wasn't selectable. - BattleMenuDetector detector; - int result = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); - }, - {{detector}}, - INFERENCE_RATE - ); - - // No battle menu detected, we're good. - if (result < 0){ - player.move_blocked[state.move_slot] = false; - break; - } - - // Battle menu detected. It means the move wasn't selectable. - - stream.log("Move not selectable.", COLOR_RED); - player.move_blocked[state.move_slot] = true; - - bool no_moves = true; - for (size_t c = 0; c < 4; c++){ - no_moves &= player.move_blocked[c]; - } - if (no_moves){ - stream.log("All moves reported as blocked. This is impossible. Clearing state.", COLOR_RED); - for (size_t c = 0; c < 4; c++){ - player.move_blocked[c] = false; - } - all_moves_blocked = true; - } - - state_tracker.push_update(console_index); - - // Reset position. - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_RIGHT, 2 * TICKS_PER_SECOND, 0); - pbf_press_dpad(context, DPAD_UP, 2 * TICKS_PER_SECOND, 0); - state.move_slot = 0; - - inferred = state_tracker.infer_actual_state(console_index); -// inferred.players[player_index].move_blocked[state.move_slot] = true; - - } - -// inference.stop(); - return StateMachineAction::KEEP_GOING; -} - - - -StateMachineAction throw_balls( - AdventureRuntime& runtime, - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - Language language, - OcrFailureWatchdog& ocr_watchdog, - GlobalStateTracker& state_tracker, - const EndBattleDecider& decider -){ - GlobalState& state = state_tracker[console_index]; - state.clear_battle_state(); - - state.wins++; - state.players[0].health.value.dead = 0; - state.players[1].health.value.dead = 0; - state.players[2].health.value.dead = 0; - state.players[3].health.value.dead = 0; - - - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - - - std::string ball; - - bool boss = inferred.wins == 4; - if (boss){ - ball = decider.boss_ball(console_index, inferred.boss); - }else{ - ball = decider.normal_ball(console_index); - } - - BattleBallReader reader(stream, language); - pbf_press_button(context, BUTTON_A, 50, 75); - context.wait_for_all_requests(); - - int16_t balls = move_to_ball(reader, stream, context, ball); - if (balls != 0){ - pbf_mash_button(context, BUTTON_A, 1000ms); - }else{ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to find appropriate ball. Did you run out?", - stream - ); - } - - ReadableQuantity999& stat = boss - ? runtime.consoles[console_index].boss_balls - : runtime.consoles[console_index].normal_balls; - - stat.update_with_ocr(balls, boss ? -1 : 1); - stat.quantity = (uint16_t)std::max((int)stat.quantity - 1, 0); - - return StateMachineAction::KEEP_GOING; -} - - - - -} -} -} -} +/* Max Lair Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +//#include "PokemonSwSh_MaxLair_Run_CaughtScreen.h" +#include "PokemonSwSh_MaxLair_Run_Battle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +bool read_battle_menu( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, size_t player_index, + OcrFailureWatchdog& ocr_watchdog, + GlobalState& state, + const ConsoleSpecificOptions& settings, + bool currently_dmaxed, bool cheer_only +){ + PlayerState& player = state.players[player_index]; + + VideoOverlaySet boxes(stream.overlay()); + BattleMenuReader reader(stream.overlay(), settings.language, ocr_watchdog); + BattleMoveArrowFinder arrow_finder(stream.overlay()); + arrow_finder.make_overlays(boxes); + + + // Read raid mon. + do{ + std::set mon = reader.read_opponent(stream.logger(), context, stream.video()); + if (mon.size() == 1){ + state.opponent = std::move(mon); + break; + } + if (mon.size() > 1){ + stream.log("Ambiguous Read Result: " + set_to_str(mon), COLOR_PURPLE); + if (state.opponent.size() == 1 && mon.find(*state.opponent.begin()) != mon.end()){ + stream.log("Using previous known value to disambiguate: " + set_to_str(mon), COLOR_PURPLE); + break; + } + } + if (state.opponent.size() == 1){ + stream.log("Failed to read opponent from battle. Using previously known value: " + set_to_str(state.opponent), COLOR_ORANGE); + break; + } + + stream.log("Unable to read opponent from battle. Attempting to read from summary.", COLOR_ORANGE); + pbf_press_button(context, BUTTON_Y, 10, TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + mon = reader.read_opponent_in_summary(stream.logger(), stream.video().snapshot()); + pbf_mash_button(context, BUTTON_B, 3 * TICKS_PER_SECOND); + state.opponent = std::move(mon); + + if (state.wins == 3 && !state.boss.empty()){ + if (!state.opponent.empty() && *state.opponent.begin() != state.boss){ + stream.log("Inconsistent Boss: Expected " + state.boss + ", Read: " + *state.opponent.begin(), COLOR_RED); + } + state.opponent = {state.boss}; + break; + } + }while (false); + context.wait_for_all_requests(); + + const std::string& opponent = state.opponent.empty() + ? "" + : *state.opponent.begin(); + + if (state.wins != 3 && is_boss(opponent)){ + stream.log("Boss found before 3 wins. Something is seriously out-of-sync.", COLOR_RED); + dump_image(stream.logger(), MODULE_NAME, stream.video(), "BossBeforeEnd"); +// send_program_telemetry( +// env.logger(), true, COLOR_RED, MODULE_NAME, +// "Error", +// {{"Message:", "Boss found before 3 wins."}}, +// "" +// ); + return false; + } + + // Infer the boss if we don't know it. + if (state.boss.empty() && state.wins == 3){ + state.boss = opponent; + } + + // Read misc. + VideoSnapshot screen = stream.video().snapshot(); + state.opponent_hp = reader.read_opponent_hp(stream.logger(), screen); + if (cheer_only){ + player.dmax_turns_left = 0; + player.health = Health{0, 1}; + player.can_dmax = false; + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + return true; + } + + if (currently_dmaxed){ + player.dmax_turns_left--; + if (player.dmax_turns_left <= 0){ + stream.log("State Inconsistency: dmax_turns_left <= 0 && currently_dmaxed == true", COLOR_RED); + player.dmax_turns_left = 1; + } + }else{ + std::string name = reader.read_own_mon(stream.logger(), screen); + if (!name.empty()){ + state.players[player_index].pokemon = std::move(name); + } + if (player.dmax_turns_left > 1){ + stream.log("State Inconsistency: dmax_turns_left > 0 && currently_dmaxed == false", COLOR_RED); + state.move_slot = 0; + } + if (player.dmax_turns_left == 1){ + stream.log("End of Dmax."); + state.move_slot = 0; + } + player.dmax_turns_left = 0; + } + + Health health[4]; + reader.read_hp(stream.logger(), screen, health, player_index); + if (health[0].hp >= 0) state.players[0].health = health[0]; + if (health[1].hp >= 0) state.players[1].health = health[1]; + if (health[2].hp >= 0) state.players[2].health = health[2]; + if (health[3].hp >= 0) state.players[3].health = health[3]; + + + for (size_t attempts = 0; attempts < 5; attempts++){ + // Enter move selection to read PP. + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + + // Clear move blocked status. + player.move_blocked[0] = false; + player.move_blocked[1] = false; + player.move_blocked[2] = false; + player.move_blocked[3] = false; + + screen = stream.video().snapshot(); + + int8_t pp[4] = {-1, -1, -1, -1}; + reader.read_own_pp(stream.logger(), screen, pp); + player.pp[0] = pp[0]; + player.pp[1] = pp[1]; + player.pp[2] = pp[2]; + player.pp[3] = pp[3]; + + player.can_dmax = reader.can_dmax(screen); + + // Read move slot. + // int8_t move_slot = arrow_finder.get_slot(); + int8_t move_slot = arrow_finder.detect(screen); + if (move_slot < 0){ + stream.log("Unable to detect move slot.", COLOR_RED); +// dump_image(stream.logger(), MODULE_NAME, "MoveSlot", screen); +// pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); +// pbf_press_dpad(context, DPAD_RIGHT, 2 * TICKS_PER_SECOND, 0); +// pbf_press_dpad(context, DPAD_UP, 2 * TICKS_PER_SECOND, 0); +// move_slot = 0; + pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); + continue; + }else{ + stream.log("Current Move Slot: " + std::to_string(move_slot), COLOR_BLUE); + } + if (move_slot != state.move_slot){ + stream.log( + "Move Slot Mismatch: Expected = " + std::to_string(state.move_slot) + ", Actual = " + std::to_string(move_slot), + COLOR_RED + ); + } + state.move_slot = move_slot; + + return true; + } + + dump_image(stream.logger(), MODULE_NAME, "MoveSlot", screen); + return true; +} + + +StateMachineAction run_move_select( + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + OcrFailureWatchdog& ocr_watchdog, + GlobalStateTracker& state_tracker, + const ConsoleSpecificOptions& settings, + bool currently_dmaxed, bool cheer_only +){ + GlobalState& state = state_tracker[console_index]; + size_t player_index = state.find_player_index(console_index); + PlayerState& player = state.players[player_index]; + + + if (!read_battle_menu( + env, stream, context, player_index, + ocr_watchdog, + state, settings, + currently_dmaxed, cheer_only + )){ + return StateMachineAction::RESET_RECOVER; + } + + + GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); + + bool all_moves_blocked = false; + + while (true){ + stream.log("Selecting move..."); + + if (cheer_only){ + stream.log("Choosing move Cheer. (you are dead)", COLOR_PURPLE); +// pbf_mash_button(context, BUTTON_A, 2 * TICKS_PER_SECOND); +// context.wait_for_all_requests(); + break; + } + + std::pair move = select_move( + stream.logger(), + inferred, + player_index + ); + stream.log("Choosing move " + std::to_string((int)move.first) + (move.second ? " (dmax)." : "."), COLOR_PURPLE); + + if (player.can_dmax && move.second){ + pbf_press_dpad(context, DPAD_LEFT, 10, 50); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + player.dmax_turns_left = 3; + } + while (state.move_slot != move.first){ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + state.move_slot++; + state.move_slot %= 4; + } + + // Enter the move. + if (all_moves_blocked){ + // If we had trouble selecting a move, then we're probably stuck in a self-target loop. + // Force target the opponent. + stream.log("Force targeting opponent due to inability to select a move after multiple attempts...", COLOR_RED); + pbf_press_button(context, BUTTON_A, 20, 2 * TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_UP, 2 * TICKS_PER_SECOND, 0); + } + pbf_mash_button(context, BUTTON_A, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + +// inference.stop(); + + // Back out and look for battle menu. This indicates that the move wasn't selectable. + BattleMenuDetector detector; + int result = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 5 * TICKS_PER_SECOND); + }, + {{detector}}, + INFERENCE_RATE + ); + + // No battle menu detected, we're good. + if (result < 0){ + player.move_blocked[state.move_slot] = false; + break; + } + + // Battle menu detected. It means the move wasn't selectable. + + stream.log("Move not selectable.", COLOR_RED); + player.move_blocked[state.move_slot] = true; + + bool no_moves = true; + for (size_t c = 0; c < 4; c++){ + no_moves &= player.move_blocked[c]; + } + if (no_moves){ + stream.log("All moves reported as blocked. This is impossible. Clearing state.", COLOR_RED); + for (size_t c = 0; c < 4; c++){ + player.move_blocked[c] = false; + } + all_moves_blocked = true; + } + + state_tracker.push_update(console_index); + + // Reset position. + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_RIGHT, 2 * TICKS_PER_SECOND, 0); + pbf_press_dpad(context, DPAD_UP, 2 * TICKS_PER_SECOND, 0); + state.move_slot = 0; + + inferred = state_tracker.infer_actual_state(console_index); +// inferred.players[player_index].move_blocked[state.move_slot] = true; + + } + +// inference.stop(); + return StateMachineAction::KEEP_GOING; +} + + + +StateMachineAction throw_balls( + AdventureRuntime& runtime, + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + Language language, + OcrFailureWatchdog& ocr_watchdog, + GlobalStateTracker& state_tracker, + const EndBattleDecider& decider +){ + GlobalState& state = state_tracker[console_index]; + state.clear_battle_state(); + + state.wins++; + state.players[0].health.value.dead = 0; + state.players[1].health.value.dead = 0; + state.players[2].health.value.dead = 0; + state.players[3].health.value.dead = 0; + + + GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); + + + std::string ball; + + bool boss = inferred.wins == 4; + if (boss){ + ball = decider.boss_ball(console_index, inferred.boss); + }else{ + ball = decider.normal_ball(console_index); + } + + BattleBallReader reader(stream, language); + pbf_press_button(context, BUTTON_A, 50, 75); + context.wait_for_all_requests(); + + int16_t balls = move_to_ball(reader, stream, context, ball); + if (balls != 0){ + pbf_mash_button(context, BUTTON_A, 1000ms); + }else{ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to find appropriate ball. Did you run out?", + stream + ); + } + + ReadableQuantity999& stat = boss + ? runtime.consoles[console_index].boss_balls + : runtime.consoles[console_index].normal_balls; + + stat.update_with_ocr(balls, boss ? -1 : 1); + stat.quantity = (uint16_t)std::max((int)stat.quantity - 1, 0); + + return StateMachineAction::KEEP_GOING; +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h index 2d7fb5bf33..5bb17b59f0 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Battle.h @@ -1,46 +1,46 @@ -/* Max Lair Run Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Battle_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Battle_H - -#include "CommonFramework/Language.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -StateMachineAction run_move_select( - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - OcrFailureWatchdog& ocr_watchdog, - GlobalStateTracker& state_tracker, - const ConsoleSpecificOptions& settings, - bool currently_dmaxed, bool cheer_only -); - -StateMachineAction throw_balls( - AdventureRuntime& runtime, - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - Language language, - OcrFailureWatchdog& ocr_watchdog, - GlobalStateTracker& state_tracker, - const EndBattleDecider& decider -); - - - -} -} -} -} -#endif +/* Max Lair Run Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Battle_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Battle_H + +#include "CommonFramework/Language.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +StateMachineAction run_move_select( + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + OcrFailureWatchdog& ocr_watchdog, + GlobalStateTracker& state_tracker, + const ConsoleSpecificOptions& settings, + bool currently_dmaxed, bool cheer_only +); + +StateMachineAction throw_balls( + AdventureRuntime& runtime, + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + Language language, + OcrFailureWatchdog& ocr_watchdog, + GlobalStateTracker& state_tracker, + const EndBattleDecider& decider +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.cpp index b43142398e..a11307b9e2 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.cpp @@ -1,199 +1,199 @@ -/* Max Lair Run Caught Screen - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h" -#include "PokemonSwSh_MaxLair_Run_CaughtScreen.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -StateMachineAction mash_A_to_entrance( - AdventureRuntime& runtime, - VideoStream& stream, ProControllerContext& context, - const ImageViewRGB32& entrance -){ - EntranceDetector entrance_detector(entrance); - - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 60 * TICKS_PER_SECOND); - }, - {{entrance_detector}}, - INFERENCE_RATE - ); - - if (result < 0){ - stream.log("Failed to detect entrance.", COLOR_RED); - runtime.session_stats.add_error(); - dump_image(stream.logger(), MODULE_NAME, stream.video(), "FailedToDetectEntrance"); - return StateMachineAction::RESET_RECOVER; - } - return StateMachineAction::KEEP_GOING; -} - - -void synchronize_caught_screen( - size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -){ - context.wait_for_all_requests(); - state_tracker.synchronize(stream.logger(), console_index, std::chrono::seconds(60)); -} - - -StateMachineAction run_caught_screen( - AdventureRuntime& runtime, - ProgramEnvironment& env, size_t console_index, - ConsoleHandle& console, ProControllerContext& context, - GlobalStateTracker& state_tracker, - const EndBattleDecider& decider, - const ImageViewRGB32& entrance -){ - bool is_host = console_index == runtime.host_index; - - pbf_wait(context, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - CaughtPokemonScreen tracker(console, context); - runtime.session_stats.add_run(tracker.total()); - if (is_host){ - runtime.path_stats.add_run(tracker.total() >= 4); -// cout << runtime.path_stats.to_str() << endl; - } - - // Scroll over everything. This checks them for shinies. - tracker.enter_summary(); - for (size_t c = 0; c < tracker.total(); c++){ - tracker.scroll_to(c); - } - - // Get all the shinies. - bool boss_is_shiny = false; - std::vector shinies; - for (size_t c = 0; c < tracker.total(); c++){ - if (!tracker[c].shiny){ - continue; - } - shinies.emplace_back(c); - runtime.session_stats.add_shiny(); - if (c == 3){ - boss_is_shiny = true; - runtime.session_stats.add_shiny_legendary(); - } - } - - // If anything is shiny, take a video. - if (!shinies.empty()){ - tracker.scroll_to(shinies.back()); - tracker.leave_summary(); - context.wait_for(std::chrono::seconds(1)); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - // Screencap all the shinies and send notifications. - for (size_t index : shinies){ - tracker.scroll_to(index); - tracker.leave_summary(); - VideoSnapshot screen = console.video().snapshot(); - - WriteSpinLock lg(runtime.m_lock); - send_shiny_notification( - env, console.logger(), - runtime.notification_shiny, - console_index, shinies.size(), - nullptr, - runtime.path_stats, - runtime.session_stats, - screen - ); - } - - - const std::string& boss = state_tracker[console_index].boss; - CaughtScreenAction action = - decider.end_adventure_action( - console_index, boss, - runtime.path_stats, - !shinies.empty(), boss_is_shiny - ); - - switch (action){ - case CaughtScreenAction::STOP_PROGRAM: - console.log("Stopping program...", COLOR_PURPLE); - synchronize_caught_screen(console_index, console, context, state_tracker); - return StateMachineAction::STOP_PROGRAM; - - case CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE: - if (is_host){ - runtime.path_stats.clear(); - } - if (shinies.empty() || shinies[0] == 3){ - console.log("Quitting back to entrance.", COLOR_PURPLE); - tracker.leave_summary(); - synchronize_caught_screen(console_index, console, context, state_tracker); - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); - return mash_A_to_entrance(runtime, console, context, entrance); - }else{ - console.log("Taking non-shiny boss and returning to entrance...", COLOR_BLUE); - tracker.scroll_to(shinies[0]); - tracker.enter_summary(); // Enter summary to verify you're on the right mon. - tracker.leave_summary(); - synchronize_caught_screen(console_index, console, context, state_tracker); - StateMachineAction state = mash_A_to_entrance(runtime, console, context, entrance); - if (state == StateMachineAction::RESET_RECOVER){ - throw_and_log( - console.logger(), - ErrorReport::NO_ERROR_REPORT, - "Unable to take " + Pokemon::STRING_POKEMON + ". Did you forget to disable nicknames?", - console - ); - } - return state; - } - - case CaughtScreenAction::RESET: - console.log("Resetting game...", COLOR_BLUE); - synchronize_caught_screen(console_index, console, context, state_tracker); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - reset_game_from_home_with_inference( - console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - return StateMachineAction::DONE_WITH_ADVENTURE; - } - - throw InternalProgramError(&console.logger(), PA_CURRENT_FUNCTION, "Invalid enum."); -} - - -} -} -} -} +/* Max Lair Run Caught Screen + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_CatchScreenTracker.h" +#include "PokemonSwSh_MaxLair_Run_CaughtScreen.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +StateMachineAction mash_A_to_entrance( + AdventureRuntime& runtime, + VideoStream& stream, ProControllerContext& context, + const ImageViewRGB32& entrance +){ + EntranceDetector entrance_detector(entrance); + + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 60 * TICKS_PER_SECOND); + }, + {{entrance_detector}}, + INFERENCE_RATE + ); + + if (result < 0){ + stream.log("Failed to detect entrance.", COLOR_RED); + runtime.session_stats.add_error(); + dump_image(stream.logger(), MODULE_NAME, stream.video(), "FailedToDetectEntrance"); + return StateMachineAction::RESET_RECOVER; + } + return StateMachineAction::KEEP_GOING; +} + + +void synchronize_caught_screen( + size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +){ + context.wait_for_all_requests(); + state_tracker.synchronize(stream.logger(), console_index, std::chrono::seconds(60)); +} + + +StateMachineAction run_caught_screen( + AdventureRuntime& runtime, + ProgramEnvironment& env, size_t console_index, + ConsoleHandle& console, ProControllerContext& context, + GlobalStateTracker& state_tracker, + const EndBattleDecider& decider, + const ImageViewRGB32& entrance +){ + bool is_host = console_index == runtime.host_index; + + pbf_wait(context, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + CaughtPokemonScreen tracker(console, context); + runtime.session_stats.add_run(tracker.total()); + if (is_host){ + runtime.path_stats.add_run(tracker.total() >= 4); +// cout << runtime.path_stats.to_str() << endl; + } + + // Scroll over everything. This checks them for shinies. + tracker.enter_summary(); + for (size_t c = 0; c < tracker.total(); c++){ + tracker.scroll_to(c); + } + + // Get all the shinies. + bool boss_is_shiny = false; + std::vector shinies; + for (size_t c = 0; c < tracker.total(); c++){ + if (!tracker[c].shiny){ + continue; + } + shinies.emplace_back(c); + runtime.session_stats.add_shiny(); + if (c == 3){ + boss_is_shiny = true; + runtime.session_stats.add_shiny_legendary(); + } + } + + // If anything is shiny, take a video. + if (!shinies.empty()){ + tracker.scroll_to(shinies.back()); + tracker.leave_summary(); + context.wait_for(std::chrono::seconds(1)); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + // Screencap all the shinies and send notifications. + for (size_t index : shinies){ + tracker.scroll_to(index); + tracker.leave_summary(); + VideoSnapshot screen = console.video().snapshot(); + + WriteSpinLock lg(runtime.m_lock); + send_shiny_notification( + env, console.logger(), + runtime.notification_shiny, + console_index, shinies.size(), + nullptr, + runtime.path_stats, + runtime.session_stats, + screen + ); + } + + + const std::string& boss = state_tracker[console_index].boss; + CaughtScreenAction action = + decider.end_adventure_action( + console_index, boss, + runtime.path_stats, + !shinies.empty(), boss_is_shiny + ); + + switch (action){ + case CaughtScreenAction::STOP_PROGRAM: + console.log("Stopping program...", COLOR_PURPLE); + synchronize_caught_screen(console_index, console, context, state_tracker); + return StateMachineAction::STOP_PROGRAM; + + case CaughtScreenAction::TAKE_NON_BOSS_SHINY_AND_CONTINUE: + if (is_host){ + runtime.path_stats.clear(); + } + if (shinies.empty() || shinies[0] == 3){ + console.log("Quitting back to entrance.", COLOR_PURPLE); + tracker.leave_summary(); + synchronize_caught_screen(console_index, console, context, state_tracker); + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); + return mash_A_to_entrance(runtime, console, context, entrance); + }else{ + console.log("Taking non-shiny boss and returning to entrance...", COLOR_BLUE); + tracker.scroll_to(shinies[0]); + tracker.enter_summary(); // Enter summary to verify you're on the right mon. + tracker.leave_summary(); + synchronize_caught_screen(console_index, console, context, state_tracker); + StateMachineAction state = mash_A_to_entrance(runtime, console, context, entrance); + if (state == StateMachineAction::RESET_RECOVER){ + throw_and_log( + console.logger(), + ErrorReport::NO_ERROR_REPORT, + "Unable to take " + Pokemon::STRING_POKEMON + ". Did you forget to disable nicknames?", + console + ); + } + return state; + } + + case CaughtScreenAction::RESET: + console.log("Resetting game...", COLOR_BLUE); + synchronize_caught_screen(console_index, console, context, state_tracker); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + reset_game_from_home_with_inference( + console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + return StateMachineAction::DONE_WITH_ADVENTURE; + } + + throw InternalProgramError(&console.logger(), PA_CURRENT_FUNCTION, "Invalid enum."); +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h index eca2f8efd9..a243d74171 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_CaughtScreen.h @@ -1,35 +1,35 @@ -/* Max Lair Run Caught Screen - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_CaughtScreen_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_CaughtScreen_H - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -StateMachineAction run_caught_screen( - AdventureRuntime& runtime, - ProgramEnvironment& env, size_t console_index, - ConsoleHandle& console, ProControllerContext& context, - GlobalStateTracker& state_tracker, - const EndBattleDecider& decider, - const ImageViewRGB32& entrance -); - - - -} -} -} -} -#endif +/* Max Lair Run Caught Screen + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_CaughtScreen_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_CaughtScreen_H + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +StateMachineAction run_caught_screen( + AdventureRuntime& runtime, + ProgramEnvironment& env, size_t console_index, + ConsoleHandle& console, ProControllerContext& context, + GlobalStateTracker& state_tracker, + const EndBattleDecider& decider, + const ImageViewRGB32& entrance +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.cpp index 7bbac8d37a..9822363235 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.cpp @@ -1,170 +1,170 @@ -/* Max Lair Enter Lobby - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/ImageManip.h" -#include "CommonTools/Images/ImageFilter.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Programs/PokemonSwSh_Internet.h" -#include "PokemonSwSh_MaxLair_Run_EnterLobby.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - -class GreyDialogDetector : public VisualInferenceCallback{ -public: - GreyDialogDetector() - : VisualInferenceCallback("GreyDialogDetector") - , m_box0(0.180, 0.815, 0.015, 0.030) - , m_box1(0.785, 0.840, 0.030, 0.050) - {} - - bool detect(const ImageViewRGB32& screen){ - ImageStats stats0 = image_stats(extract_box_reference(screen, m_box0)); - if (!is_grey(stats0, 0, 200, 10)){ - return false; - } - ImageStats stats1 = image_stats(extract_box_reference(screen, m_box1)); - if (!is_grey(stats1, 0, 200, 10)){ - return false; - } - return true; - } - virtual void make_overlays(VideoOverlaySet& items) const override{ - items.add(COLOR_RED, m_box0); - items.add(COLOR_RED, m_box1); - } - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ - return detect(frame); - } - -private: - ImageFloatBox m_box0; - ImageFloatBox m_box1; -}; - - - - -std::shared_ptr enter_lobby( - VideoStream& stream, ProControllerContext& context, - size_t boss_slot, bool connect_to_internet, - ReadableQuantity999& ore -){ - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - - if (connect_to_internet){ - connect_to_internet_with_inference(stream, context); - } - - VideoOverlaySet boxes(stream.overlay()); - SelectionArrowFinder arrow_detector(stream.overlay(), ImageFloatBox(0.350, 0.450, 0.500, 0.400)); - GreyDialogDetector dialog_detector; - arrow_detector.make_overlays(boxes); - dialog_detector.make_overlays(boxes); - -// OverlayBoxScope ore_box(stream.overlay(), {0.900, 0.015, 0.020, 0.040}); - OverlayBoxScope ore_box(stream.overlay(), {0.930, 0.050, 0.065, 0.010}); - OverlayBoxScope ore_quantity(stream.overlay(), {0.945, 0.010, 0.0525, 0.050}); - - size_t presses = 0; - size_t arrow_count = 0; - size_t ore_dialog_count = 0; - while (presses < 50){ - presses++; - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - VideoSnapshot screen = stream.video().snapshot(); - if (!arrow_detector.detect(screen)){ - continue; - } - - arrow_count++; - - stream.log("Detected dialog prompt."); -// screen.save("test.png"); - - // We need to pay ore. - ImageStats ore_stats = image_stats(extract_box_reference(screen, ore_box)); - if (is_solid(ore_stats, {0.594724, 0.405276, 0.})){ - stream.log("Need to pay ore.", COLOR_PURPLE); - - arrow_count = 0; - ImageRGB32 image = to_blackwhite_rgb32_range( - extract_box_reference(screen, ore_quantity), - true, - 0xff808080, 0xffffffff - ); - ImageRGB32 filtered = pad_image(image, 10, 0xffffffff); - ore.update_with_ocr(stream.logger(), filtered); - - if (ore.quantity < 20){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "You have less than 20 ore. Program stopped. (Quantity: " + ore.to_str() + ")", - stream - ); - } - - ore_dialog_count++; - if (ore_dialog_count >= 2){ - OperationFailedException::fire( - ErrorReport::NO_ERROR_REPORT, - "Unable to start adventure. Are you out of ore? (Quantity: " + ore.to_str() + ")", - stream - ); - } - - continue; - } - - // Detected save dialog. - if (dialog_detector.detect(screen)){ - stream.log("Detected save dialog."); - context.wait_for_all_requests(); - VideoSnapshot entrance = stream.video().snapshot(); - pbf_press_button(context, BUTTON_A, 10, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - return std::move(entrance.frame); - } - - // Select a boss. - if (arrow_count == 2){ - stream.log("Detected boss selection."); - if (boss_slot > 0){ - for (size_t c = 1; c < boss_slot; c++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - }else{ - pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); - } - } - } - - return std::make_shared(); -} - - - -} -} -} -} +/* Max Lair Enter Lobby + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/ImageManip.h" +#include "CommonTools/Images/ImageFilter.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Programs/PokemonSwSh_Internet.h" +#include "PokemonSwSh_MaxLair_Run_EnterLobby.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + +class GreyDialogDetector : public VisualInferenceCallback{ +public: + GreyDialogDetector() + : VisualInferenceCallback("GreyDialogDetector") + , m_box0(0.180, 0.815, 0.015, 0.030) + , m_box1(0.785, 0.840, 0.030, 0.050) + {} + + bool detect(const ImageViewRGB32& screen){ + ImageStats stats0 = image_stats(extract_box_reference(screen, m_box0)); + if (!is_grey(stats0, 0, 200, 10)){ + return false; + } + ImageStats stats1 = image_stats(extract_box_reference(screen, m_box1)); + if (!is_grey(stats1, 0, 200, 10)){ + return false; + } + return true; + } + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(COLOR_RED, m_box0); + items.add(COLOR_RED, m_box1); + } + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override{ + return detect(frame); + } + +private: + ImageFloatBox m_box0; + ImageFloatBox m_box1; +}; + + + + +std::shared_ptr enter_lobby( + VideoStream& stream, ProControllerContext& context, + size_t boss_slot, bool connect_to_internet, + ReadableQuantity999& ore +){ + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + + if (connect_to_internet){ + connect_to_internet_with_inference(stream, context); + } + + VideoOverlaySet boxes(stream.overlay()); + SelectionArrowFinder arrow_detector(stream.overlay(), ImageFloatBox(0.350, 0.450, 0.500, 0.400)); + GreyDialogDetector dialog_detector; + arrow_detector.make_overlays(boxes); + dialog_detector.make_overlays(boxes); + +// OverlayBoxScope ore_box(stream.overlay(), {0.900, 0.015, 0.020, 0.040}); + OverlayBoxScope ore_box(stream.overlay(), {0.930, 0.050, 0.065, 0.010}); + OverlayBoxScope ore_quantity(stream.overlay(), {0.945, 0.010, 0.0525, 0.050}); + + size_t presses = 0; + size_t arrow_count = 0; + size_t ore_dialog_count = 0; + while (presses < 50){ + presses++; + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + VideoSnapshot screen = stream.video().snapshot(); + if (!arrow_detector.detect(screen)){ + continue; + } + + arrow_count++; + + stream.log("Detected dialog prompt."); +// screen.save("test.png"); + + // We need to pay ore. + ImageStats ore_stats = image_stats(extract_box_reference(screen, ore_box)); + if (is_solid(ore_stats, {0.594724, 0.405276, 0.})){ + stream.log("Need to pay ore.", COLOR_PURPLE); + + arrow_count = 0; + ImageRGB32 image = to_blackwhite_rgb32_range( + extract_box_reference(screen, ore_quantity), + true, + 0xff808080, 0xffffffff + ); + ImageRGB32 filtered = pad_image(image, 10, 0xffffffff); + ore.update_with_ocr(stream.logger(), filtered); + + if (ore.quantity < 20){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "You have less than 20 ore. Program stopped. (Quantity: " + ore.to_str() + ")", + stream + ); + } + + ore_dialog_count++; + if (ore_dialog_count >= 2){ + OperationFailedException::fire( + ErrorReport::NO_ERROR_REPORT, + "Unable to start adventure. Are you out of ore? (Quantity: " + ore.to_str() + ")", + stream + ); + } + + continue; + } + + // Detected save dialog. + if (dialog_detector.detect(screen)){ + stream.log("Detected save dialog."); + context.wait_for_all_requests(); + VideoSnapshot entrance = stream.video().snapshot(); + pbf_press_button(context, BUTTON_A, 10, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + return std::move(entrance.frame); + } + + // Select a boss. + if (arrow_count == 2){ + stream.log("Detected boss selection."); + if (boss_slot > 0){ + for (size_t c = 1; c < boss_slot; c++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + }else{ + pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); + } + } + } + + return std::make_shared(); +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.h index dbd6c6df0f..f94e6d4e4f 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_EnterLobby.h @@ -1,33 +1,33 @@ -/* Max Lair Enter Lobby - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_EnterLobby_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_EnterLobby_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -std::shared_ptr enter_lobby( - VideoStream& stream, ProControllerContext& context, - size_t boss_slot, bool connect_to_internet, - ReadableQuantity999& ore -); - - - -} -} -} -} -#endif +/* Max Lair Enter Lobby + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_EnterLobby_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_EnterLobby_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +std::shared_ptr enter_lobby( + VideoStream& stream, ProControllerContext& context, + size_t boss_slot, bool connect_to_internet, + ReadableQuantity999& ore +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.cpp index eb3a6bdc9e..fc546d8cad 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.cpp @@ -1,64 +1,64 @@ -/* Max Lair Run Entrance - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh_MaxLair_Run_Entrance.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_entrance( - AdventureRuntime& runtime, - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - bool save_path, - GlobalStateTracker& state_tracker -){ - GlobalState& state = state_tracker[console_index]; - - if (!state.adventure_started){ - stream.log("Failed to start raid.", COLOR_RED); - runtime.session_stats.add_error(); - }else if (state.wins == 0){ - stream.log("Lost on first raid.", COLOR_PURPLE); - runtime.session_stats.add_run(0); - if (console_index == runtime.host_index){ - runtime.path_stats.clear(); - } - } - - - OverlayBoxScope box(stream.overlay(), {0.782, 0.850, 0.030, 0.050}); - - pbf_wait(context, 2 * TICKS_PER_SECOND); - while (true){ - if (save_path){ - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - }else{ - pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); - } - context.wait_for_all_requests(); - - VideoSnapshot screen = stream.video().snapshot(); - ImageStats stats = image_stats(extract_box_reference(screen, box)); - if (!is_grey(stats, 400, 1000)){ - break; - } - } -} - - - -} -} -} -} +/* Max Lair Run Entrance + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh_MaxLair_Run_Entrance.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_entrance( + AdventureRuntime& runtime, + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + bool save_path, + GlobalStateTracker& state_tracker +){ + GlobalState& state = state_tracker[console_index]; + + if (!state.adventure_started){ + stream.log("Failed to start raid.", COLOR_RED); + runtime.session_stats.add_error(); + }else if (state.wins == 0){ + stream.log("Lost on first raid.", COLOR_PURPLE); + runtime.session_stats.add_run(0); + if (console_index == runtime.host_index){ + runtime.path_stats.clear(); + } + } + + + OverlayBoxScope box(stream.overlay(), {0.782, 0.850, 0.030, 0.050}); + + pbf_wait(context, 2 * TICKS_PER_SECOND); + while (true){ + if (save_path){ + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + }else{ + pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); + } + context.wait_for_all_requests(); + + VideoSnapshot screen = stream.video().snapshot(); + ImageStats stats = image_stats(extract_box_reference(screen, box)); + if (!is_grey(stats, 400, 1000)){ + break; + } + } +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h index 3185cf2151..36156faaac 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Entrance.h @@ -1,35 +1,35 @@ -/* Max Lair Run Entrance - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Entrance_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Entrance_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_entrance( - AdventureRuntime& runtime, - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - bool save_path, - GlobalStateTracker& state_tracker -); - - - -} -} -} -} -#endif +/* Max Lair Run Entrance + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Entrance_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Entrance_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_entrance( + AdventureRuntime& runtime, + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + bool save_path, + GlobalStateTracker& state_tracker +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.cpp index 7398672cb1..7451d62958 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.cpp @@ -1,70 +1,70 @@ -/* Max Lair Item - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_Run_ItemSelect.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_item_select( - size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -){ - GlobalState& state = state_tracker[console_index]; - size_t player_index = state.find_player_index(console_index); - - PathReader reader(stream.overlay(), player_index); - { - VideoSnapshot screen = stream.video().snapshot(); - reader.read_sprites(stream.logger(), state, screen); - reader.read_hp(stream.logger(), state, screen); - } - - - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - - int8_t item_index = select_item(stream.logger(), inferred, player_index); - stream.log("Choosing item " + std::to_string((int)item_index) + ".", COLOR_PURPLE); - - if (item_index < 0){ - pbf_press_button(context, BUTTON_B, 10, 50); - return; - } - for (int8_t c = 0; c < item_index; c++){ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } - pbf_press_button(context, BUTTON_A, 10, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Wait until we exit the window. - ItemSelectDetector item_menu(true); - wait_until( - stream, context, - std::chrono::seconds(480), - {{item_menu}}, - INFERENCE_RATE - ); - - pbf_wait(context, 1 * TICKS_PER_SECOND); -} - - - -} -} -} -} +/* Max Lair Item + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_ItemSelectMenu.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_Run_ItemSelect.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_item_select( + size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +){ + GlobalState& state = state_tracker[console_index]; + size_t player_index = state.find_player_index(console_index); + + PathReader reader(stream.overlay(), player_index); + { + VideoSnapshot screen = stream.video().snapshot(); + reader.read_sprites(stream.logger(), state, screen); + reader.read_hp(stream.logger(), state, screen); + } + + + GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); + + int8_t item_index = select_item(stream.logger(), inferred, player_index); + stream.log("Choosing item " + std::to_string((int)item_index) + ".", COLOR_PURPLE); + + if (item_index < 0){ + pbf_press_button(context, BUTTON_B, 10, 50); + return; + } + for (int8_t c = 0; c < item_index; c++){ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } + pbf_press_button(context, BUTTON_A, 10, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Wait until we exit the window. + ItemSelectDetector item_menu(true); + wait_until( + stream, context, + std::chrono::seconds(480), + {{item_menu}}, + INFERENCE_RATE + ); + + pbf_wait(context, 1 * TICKS_PER_SECOND); +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h index 8e4fae17d7..63ad00ac38 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ItemSelect.h @@ -1,32 +1,32 @@ -/* Max Lair Run Item Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_ItemSelect_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_ItemSelect_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_item_select( - size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -); - - - -} -} -} -} -#endif +/* Max Lair Run Item Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_ItemSelect_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_ItemSelect_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_item_select( + size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.cpp index 1d75d18995..2046cc062b 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.cpp @@ -1,77 +1,77 @@ -/* Max Lair Run Path Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_Run_PathSelect.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_path_select( - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -){ - GlobalState& state = state_tracker[console_index]; - size_t player_index = state.find_player_index(console_index); - - PathReader reader(stream.overlay(), player_index); - context.wait_for(std::chrono::milliseconds(500)); - - VideoSnapshot screen = stream.video().snapshot(); - reader.read_sprites(stream.logger(), state, screen); - reader.read_hp(stream.logger(), state, screen); - - if (state.wins == 0){ - reader.read_path(env, stream, context, state); - }else{ - reader.read_side(stream.logger(), state, screen); - } - - - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - - - // Select the path. - std::vector path = select_path(stream.logger(), inferred, player_index); - uint8_t slot; - if (path.empty()){ - stream.log("No available paths due to read errors. Picking left-most path.", COLOR_RED); - slot = 0; - }else{ - slot = path[0].path_slot; - } - state.last_best_path = std::move(path); - - stream.log("Choosing path " + std::to_string((int)slot) + ".", COLOR_PURPLE); - - for (uint8_t c = 0; c < slot; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 10, 50); - } - pbf_mash_button(context, BUTTON_A, 1000ms); - pbf_wait(context, 5000ms); - context.wait_for_all_requests(); -} - - - -} -} -} -} +/* Max Lair Run Path Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_BattleMenu.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_Run_PathSelect.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_path_select( + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +){ + GlobalState& state = state_tracker[console_index]; + size_t player_index = state.find_player_index(console_index); + + PathReader reader(stream.overlay(), player_index); + context.wait_for(std::chrono::milliseconds(500)); + + VideoSnapshot screen = stream.video().snapshot(); + reader.read_sprites(stream.logger(), state, screen); + reader.read_hp(stream.logger(), state, screen); + + if (state.wins == 0){ + reader.read_path(env, stream, context, state); + }else{ + reader.read_side(stream.logger(), state, screen); + } + + + GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); + + + // Select the path. + std::vector path = select_path(stream.logger(), inferred, player_index); + uint8_t slot; + if (path.empty()){ + stream.log("No available paths due to read errors. Picking left-most path.", COLOR_RED); + slot = 0; + }else{ + slot = path[0].path_slot; + } + state.last_best_path = std::move(path); + + stream.log("Choosing path " + std::to_string((int)slot) + ".", COLOR_PURPLE); + + for (uint8_t c = 0; c < slot; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 10, 50); + } + pbf_mash_button(context, BUTTON_A, 1000ms); + pbf_wait(context, 5000ms); + context.wait_for_all_requests(); +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h index ada862290a..a27fa0cdcc 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PathSelect.h @@ -1,32 +1,32 @@ -/* Max Lair Run Path Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_PathSelect_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_PathSelect_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_path_select( - ProgramEnvironment& env, size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -); - - -} -} -} -} -#endif +/* Max Lair Run Path Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_PathSelect_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_PathSelect_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_path_select( + ProgramEnvironment& env, size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.cpp index f3afd18ea3..025b74853c 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.cpp @@ -1,110 +1,110 @@ -/* Max Lair Run Pokemon Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" -#include "PokemonSwSh_MaxLair_Run_PokemonSelect.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_select_pokemon( - size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker, - OcrFailureWatchdog& ocr_watchdog, - const ConsoleSpecificOptions& settings -){ - GlobalState& state = state_tracker[console_index]; - - state.adventure_started = true; - - stream.log("Switch " + std::to_string(console_index) + "'s turn to select."); - - // Wait for the screen to finish loading. - context.wait_for(std::chrono::milliseconds(500)); - - - PokemonSelectMenuReader reader( - stream.logger(), - stream.overlay(), - settings.language, - ocr_watchdog - ); - - - std::string options[3]; - -// // Wait for bottom row to reload. -// pbf_wait(context, 50); -// context.wait_for_all_requests(); - - // Read the bottom two options first. - VideoSnapshot screen = stream.video().snapshot(); - options[1] = reader.read_option(screen, 1); - options[2] = reader.read_option(screen, 2); - -// reader.read_options(screen, options); - int8_t player_index = reader.who_is_selecting(screen); - if (player_index >= 0){ - state.players[player_index].console_id = (int8_t)console_index; - }else{ - player_index = 0; - } - - // Scroll down one to move the arrow off the top row. Then we can read it. - pbf_press_dpad(context, DPAD_DOWN, 10, 80); - context.wait_for_all_requests(); - screen = stream.video().snapshot(); - options[0] = reader.read_option(screen, 0); - - state.add_seen(options[0]); - state.add_seen(options[1]); - state.add_seen(options[2]); - - -// GlobalState inferred = state_tracker.synchronize(env, console, console_index); - state_tracker.push_update(console_index); - GlobalState inferred = state_tracker.infer_actual_state(console_index); - - - // Make your selection. - int8_t selection = select_starter(stream.logger(), inferred, player_index, options); - stream.log("Choosing option " + std::to_string((int)selection) + ".", COLOR_PURPLE); - switch (selection){ - case 0: - pbf_press_dpad(context, DPAD_UP, 10, 50); - break; - case 1: - break; - case 2: - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - break; - } - pbf_press_button(context, BUTTON_A, 10, 50); - context.wait_for_all_requests(); - - // Update state. - if (player_index >= 0){ - state.players[console_index].pokemon = std::move(options[selection]); - } - - -} - - - - - -} -} -} -} +/* Max Lair Run Pokemon Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" +#include "PokemonSwSh_MaxLair_Run_PokemonSelect.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_select_pokemon( + size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker, + OcrFailureWatchdog& ocr_watchdog, + const ConsoleSpecificOptions& settings +){ + GlobalState& state = state_tracker[console_index]; + + state.adventure_started = true; + + stream.log("Switch " + std::to_string(console_index) + "'s turn to select."); + + // Wait for the screen to finish loading. + context.wait_for(std::chrono::milliseconds(500)); + + + PokemonSelectMenuReader reader( + stream.logger(), + stream.overlay(), + settings.language, + ocr_watchdog + ); + + + std::string options[3]; + +// // Wait for bottom row to reload. +// pbf_wait(context, 50); +// context.wait_for_all_requests(); + + // Read the bottom two options first. + VideoSnapshot screen = stream.video().snapshot(); + options[1] = reader.read_option(screen, 1); + options[2] = reader.read_option(screen, 2); + +// reader.read_options(screen, options); + int8_t player_index = reader.who_is_selecting(screen); + if (player_index >= 0){ + state.players[player_index].console_id = (int8_t)console_index; + }else{ + player_index = 0; + } + + // Scroll down one to move the arrow off the top row. Then we can read it. + pbf_press_dpad(context, DPAD_DOWN, 10, 80); + context.wait_for_all_requests(); + screen = stream.video().snapshot(); + options[0] = reader.read_option(screen, 0); + + state.add_seen(options[0]); + state.add_seen(options[1]); + state.add_seen(options[2]); + + +// GlobalState inferred = state_tracker.synchronize(env, console, console_index); + state_tracker.push_update(console_index); + GlobalState inferred = state_tracker.infer_actual_state(console_index); + + + // Make your selection. + int8_t selection = select_starter(stream.logger(), inferred, player_index, options); + stream.log("Choosing option " + std::to_string((int)selection) + ".", COLOR_PURPLE); + switch (selection){ + case 0: + pbf_press_dpad(context, DPAD_UP, 10, 50); + break; + case 1: + break; + case 2: + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + break; + } + pbf_press_button(context, BUTTON_A, 10, 50); + context.wait_for_all_requests(); + + // Update state. + if (player_index >= 0){ + state.players[console_index].pokemon = std::move(options[selection]); + } + + +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h index 3ec851b1ba..f86df405dd 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSelect.h @@ -1,36 +1,36 @@ -/* Max Lair Run Pokemon Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSelect_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSelect_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "CommonTools/FailureWatchdog.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_select_pokemon( - size_t console_index, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker, - OcrFailureWatchdog& ocr_watchdog, - const ConsoleSpecificOptions& settings -); - - - -} -} -} -} -#endif +/* Max Lair Run Pokemon Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSelect_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSelect_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "CommonTools/FailureWatchdog.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_select_pokemon( + size_t console_index, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker, + OcrFailureWatchdog& ocr_watchdog, + const ConsoleSpecificOptions& settings +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.cpp index c4c34b4833..f47b70bb4a 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.cpp @@ -1,126 +1,126 @@ -/* Max Lair Run Pokemon Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_Run_PokemonSwap.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_swap_pokemon( - size_t console_index, - AdventureRuntime& runtime, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker, - const ConsoleSpecificOptions& settings -){ - GlobalState& state = state_tracker[console_index]; - size_t player_index = state.find_player_index(console_index); - PlayerState& player = state.players[player_index]; - - - // Wait for bottom row to reload. - context.wait_for(std::chrono::milliseconds(100)); - - - PokemonSwapMenuReader reader( - stream.logger(), stream.overlay(), - settings.language, - runtime.ocr_watchdog[console_index] - ); - PokemonSwapMenuDetector menu(false); - - // Now read the options. - std::string options[2]; - VideoSnapshot screen = stream.video().snapshot(); - reader.read_options(screen, options); - reader.read_pp(screen, player.pp); - - // Read HP of party. - double hp[4]; - reader.read_hp(screen,hp); - if (hp[0] >= 0) state.players[0].health = Health{hp[0], 0}; - if (hp[1] >= 0) state.players[1].health = Health{hp[1], 0}; - if (hp[2] >= 0) state.players[2].health = Health{hp[2], 0}; - if (hp[3] >= 0) state.players[3].health = Health{hp[3], 0}; - - state.add_seen(options[0]); - state.add_seen(options[1]); - - - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - - - // Make your selection. - bool swap = should_swap_with_newly_caught(stream.logger(), inferred, player_index, options); - if (swap){ - stream.log("Choosing to swap for: " + options[1], COLOR_PURPLE); - std::lock_guard lg(runtime.m_delay_lock); - pbf_mash_button(context, BUTTON_A, TICKS_PER_SECOND); - context.wait_for_all_requests(); - }else{ - stream.log("Choosing not to swap.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - -#if 1 - // Wait until we exit the window. - { - BlackScreenWatcher detector; - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, swap ? BUTTON_A : BUTTON_B, 30 * TICKS_PER_SECOND); - }, - {{detector}} - ); - if (result < 0){ - stream.log("Timed out waiting for black screen.", COLOR_RED); - }else{ - stream.log("Found path screen. Reading party..."); - } - } -#endif - { - PathScreenDetector detector; - int result = wait_until( - stream, context, - std::chrono::seconds(30), - {{detector}}, - INFERENCE_RATE - ); - if (result < 0){ - stream.log("Timed out waiting for path screen.", COLOR_RED); - return; - } - } - - stream.log("Found path screen. Reading party..."); - context.wait_for(std::chrono::milliseconds(100)); - - PathReader path_reader(stream.overlay(), player_index); - auto snapshot = stream.video().snapshot(); - path_reader.read_sprites(stream.logger(), state, snapshot); - path_reader.read_hp(stream.logger(), state, snapshot); -} - - - - -} -} -} -} +/* Max Lair Run Pokemon Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSwapMenu.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_Run_PokemonSwap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_swap_pokemon( + size_t console_index, + AdventureRuntime& runtime, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker, + const ConsoleSpecificOptions& settings +){ + GlobalState& state = state_tracker[console_index]; + size_t player_index = state.find_player_index(console_index); + PlayerState& player = state.players[player_index]; + + + // Wait for bottom row to reload. + context.wait_for(std::chrono::milliseconds(100)); + + + PokemonSwapMenuReader reader( + stream.logger(), stream.overlay(), + settings.language, + runtime.ocr_watchdog[console_index] + ); + PokemonSwapMenuDetector menu(false); + + // Now read the options. + std::string options[2]; + VideoSnapshot screen = stream.video().snapshot(); + reader.read_options(screen, options); + reader.read_pp(screen, player.pp); + + // Read HP of party. + double hp[4]; + reader.read_hp(screen,hp); + if (hp[0] >= 0) state.players[0].health = Health{hp[0], 0}; + if (hp[1] >= 0) state.players[1].health = Health{hp[1], 0}; + if (hp[2] >= 0) state.players[2].health = Health{hp[2], 0}; + if (hp[3] >= 0) state.players[3].health = Health{hp[3], 0}; + + state.add_seen(options[0]); + state.add_seen(options[1]); + + + GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); + + + // Make your selection. + bool swap = should_swap_with_newly_caught(stream.logger(), inferred, player_index, options); + if (swap){ + stream.log("Choosing to swap for: " + options[1], COLOR_PURPLE); + std::lock_guard lg(runtime.m_delay_lock); + pbf_mash_button(context, BUTTON_A, TICKS_PER_SECOND); + context.wait_for_all_requests(); + }else{ + stream.log("Choosing not to swap.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + +#if 1 + // Wait until we exit the window. + { + BlackScreenWatcher detector; + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, swap ? BUTTON_A : BUTTON_B, 30 * TICKS_PER_SECOND); + }, + {{detector}} + ); + if (result < 0){ + stream.log("Timed out waiting for black screen.", COLOR_RED); + }else{ + stream.log("Found path screen. Reading party..."); + } + } +#endif + { + PathScreenDetector detector; + int result = wait_until( + stream, context, + std::chrono::seconds(30), + {{detector}}, + INFERENCE_RATE + ); + if (result < 0){ + stream.log("Timed out waiting for path screen.", COLOR_RED); + return; + } + } + + stream.log("Found path screen. Reading party..."); + context.wait_for(std::chrono::milliseconds(100)); + + PathReader path_reader(stream.overlay(), player_index); + auto snapshot = stream.video().snapshot(); + path_reader.read_sprites(stream.logger(), state, snapshot); + path_reader.read_hp(stream.logger(), state, snapshot); +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h index 279af250a3..2254305bc1 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_PokemonSwap.h @@ -1,34 +1,34 @@ -/* Max Lair Run Pokemon Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSwap_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSwap_H - -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_swap_pokemon( - size_t console_index, - AdventureRuntime& runtime, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker, - const ConsoleSpecificOptions& settings -); - - - -} -} -} -} -#endif +/* Max Lair Run Pokemon Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSwap_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_PokemonSwap_H + +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Consoles.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_swap_pokemon( + size_t console_index, + AdventureRuntime& runtime, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker, + const ConsoleSpecificOptions& settings +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.cpp index 4ffa4e8ec7..370419d38d 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.cpp @@ -1,98 +1,98 @@ -/* Max Lair Run Professor Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" -#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" -#include "PokemonSwSh_MaxLair_Run_ProfessorSwap.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_professor_swap( - size_t console_index, - AdventureRuntime& runtime, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -){ - GlobalState& state = state_tracker[console_index]; - size_t player_index = state.find_player_index(console_index); - - PathReader reader(stream.overlay(), player_index); - { - VideoSnapshot screen = stream.video().snapshot(); - reader.read_sprites(stream.logger(), state, screen); - reader.read_hp(stream.logger(), state, screen); - } - - - GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); - - - bool swap = should_swap_with_professor(stream.logger(), inferred, player_index); - if (swap){ - stream.log("Choosing to swap.", COLOR_PURPLE); - std::lock_guard lg(runtime.m_delay_lock); - pbf_mash_button(context, BUTTON_A, 1000ms); - context.wait_for_all_requests(); - }else{ - stream.log("Choosing not to swap.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1000ms); - } - context.wait_for_all_requests(); - - - // Wait until we exit the window. - { - BlackScreenWatcher detector; - int result = wait_until( - stream, context, - std::chrono::seconds(30), - {detector} - ); - if (result < 0){ - stream.log("Timed out waiting for black screen.", COLOR_RED); - return; - } - } - - { - PathScreenDetector detector; - int result = wait_until( - stream, context, - std::chrono::seconds(30), - {detector}, - INFERENCE_RATE - ); - if (result < 0){ - stream.log("Timed out waiting for path screen.", COLOR_RED); - return; - } - } - - stream.log("Found path screen. Reading party..."); - context.wait_for(std::chrono::milliseconds(100)); - - VideoSnapshot screen = stream.video().snapshot(); - reader.read_sprites(stream.logger(), state, screen); - reader.read_hp(stream.logger(), state, screen); -} - - - - -} -} -} -} +/* Max Lair Run Professor Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PathSelect.h" +#include "PokemonSwSh/MaxLair/AI/PokemonSwSh_MaxLair_AI.h" +#include "PokemonSwSh_MaxLair_Run_ProfessorSwap.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_professor_swap( + size_t console_index, + AdventureRuntime& runtime, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +){ + GlobalState& state = state_tracker[console_index]; + size_t player_index = state.find_player_index(console_index); + + PathReader reader(stream.overlay(), player_index); + { + VideoSnapshot screen = stream.video().snapshot(); + reader.read_sprites(stream.logger(), state, screen); + reader.read_hp(stream.logger(), state, screen); + } + + + GlobalState inferred = state_tracker.synchronize(stream.logger(), console_index); + + + bool swap = should_swap_with_professor(stream.logger(), inferred, player_index); + if (swap){ + stream.log("Choosing to swap.", COLOR_PURPLE); + std::lock_guard lg(runtime.m_delay_lock); + pbf_mash_button(context, BUTTON_A, 1000ms); + context.wait_for_all_requests(); + }else{ + stream.log("Choosing not to swap.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1000ms); + } + context.wait_for_all_requests(); + + + // Wait until we exit the window. + { + BlackScreenWatcher detector; + int result = wait_until( + stream, context, + std::chrono::seconds(30), + {detector} + ); + if (result < 0){ + stream.log("Timed out waiting for black screen.", COLOR_RED); + return; + } + } + + { + PathScreenDetector detector; + int result = wait_until( + stream, context, + std::chrono::seconds(30), + {detector}, + INFERENCE_RATE + ); + if (result < 0){ + stream.log("Timed out waiting for path screen.", COLOR_RED); + return; + } + } + + stream.log("Found path screen. Reading party..."); + context.wait_for(std::chrono::milliseconds(100)); + + VideoSnapshot screen = stream.video().snapshot(); + reader.read_sprites(stream.logger(), state, screen); + reader.read_hp(stream.logger(), state, screen); +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h index 3776f245a7..96ceef3e9b 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_ProfessorSwap.h @@ -1,34 +1,34 @@ -/* Max Lair Run Professor Swap - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_ProfessorSwap_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_ProfessorSwap_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -void run_professor_swap( - size_t console_index, - AdventureRuntime& runtime, - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker -); - - - -} -} -} -} -#endif +/* Max Lair Run Professor Swap + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_ProfessorSwap_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_ProfessorSwap_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +void run_professor_swap( + size_t console_index, + AdventureRuntime& runtime, + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.cpp index df3a56dfa1..2f23c3fc08 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.cpp @@ -1,479 +1,479 @@ -/* Max Lair Run Start - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" -#include "PokemonSwSh_MaxLair_Run_EnterLobby.h" -#include "PokemonSwSh_MaxLair_Run_Start.h" -#include "PokemonSwSh_MaxLair_Run_StartSolo.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -bool abort_if_error(MultiSwitchProgramEnvironment& env, CancellableScope& scope, const std::atomic& errors){ - if (errors.load(std::memory_order_acquire)){ - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - pbf_mash_button(context, BUTTON_B, 8 * TICKS_PER_SECOND); - }); - return true; - } - return false; -} - -bool wait_for_all_join( - VideoStream& stream, ProControllerContext& context, - const ImageViewRGB32& entrance, - size_t start_players -){ - LobbyJoinedDetector joined_detector(start_players, false); - EntranceDetector entrance_detector(entrance); - int result = wait_until( - stream, context, - std::chrono::seconds(10), - { - {joined_detector}, - {entrance_detector}, - }, - INFERENCE_RATE - ); - switch (result){ - case 0: - stream.log("Detected " + std::to_string(start_players) + " players in lobby!"); - return true; - case 1: - stream.log("Detected entrance... Did you get disconnected?", COLOR_RED); -// dump_image(stream, MODULE_NAME, "wait_for_all_join", stream.video().snapshot()); - return false; - default: - stream.log("Timed out waiting for everyone to join.", COLOR_RED); -// dump_image(stream, MODULE_NAME, "wait_for_all_join", stream.video().snapshot()); - return false; - } -} - -class AllJoinedTracker final : public Cancellable{ -public: - AllJoinedTracker( - CancellableScope& scope, size_t consoles, - WallClock time_limit - ) - : m_time_limit(time_limit) - , m_consoles(consoles) - , m_counter(0) - { - attach(scope); - } - virtual ~AllJoinedTracker(){} - - bool report_joined(){ - std::unique_lock lg(m_lock); - m_counter++; - if (m_counter >= m_consoles){ - m_cv.notify_all(); - return true; - } - while (true){ - m_cv.wait_until(lg, m_time_limit); - throw_if_cancelled(); - if (m_counter >= m_consoles){ - return true; - } - if (current_time() > m_time_limit){ - return false; - } - } - } - - virtual bool cancel(std::exception_ptr exception) noexcept override{ - if (Cancellable::cancel(std::move(exception))){ - return true; - } - std::lock_guard lg(m_lock); - m_cv.notify_all(); - return false; - } - -private: - std::mutex m_lock; - std::condition_variable m_cv; - - WallClock m_time_limit; - size_t m_consoles; - size_t m_counter; -}; - - - - - - -bool start_raid_local( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - GlobalStateTracker& state_tracker, - std::shared_ptr entrance[4], - ConsoleHandle& host, size_t boss_slot, - const HostingSettings& settings, - ConsoleRuntime console_stats[4] -){ - if (env.consoles.size() == 1){ - ProControllerContext context(scope, host.pro_controller()); - return start_raid_self_solo( - host, context, - state_tracker, entrance[0], boss_slot, console_stats[0].ore - ); - } - - env.log("Entering lobby..."); - - std::string code = settings.RAID_CODE.get_code(); - - std::atomic errors(0); - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - bool is_host = index == host.index(); - - entrance[index] = enter_lobby( - console, context, - is_host ? boss_slot : 0, - settings.MODE == HostingMode::HOST_ONLINE, - console_stats[index].ore - ); - if (!*entrance[index]){ - errors.fetch_add(1); - return; - } - }); - if (errors.load(std::memory_order_acquire) != 0){ - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 8 * TICKS_PER_SECOND); - }); - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - GlobalState& state = state_tracker[index]; - bool is_host = index == host.index(); - - // Read boss. - if (is_host){ - state.boss = read_boss_sprite(console); - } - - // Enter code. - if (!code.empty() && env.consoles.size() > 1){ - pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); - FastCodeEntry::numberpad_enter_code(console, context, code, true); - pbf_wait(context, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - } - }); - - // Open lobby. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Delay to prevent the Switches from forming separate lobbies. - if (env.consoles.size() > 1 && console.index() != host.index()){ - pbf_wait(context, 3 * TICKS_PER_SECOND); - } - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - }); - - auto time_limit = current_time() + settings.LOBBY_WAIT_DELAY0.get(); - - AllJoinedTracker joined_tracker(scope, env.consoles.size(), time_limit); - - // Wait for all Switches to join. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - - // Wait for a player to show up. This lets you ready up. - if (!wait_for_a_player(console, context, *entrance[index], time_limit)){ - errors.fetch_add(1); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Wait for all consoles to join. - if (!joined_tracker.report_joined()){ - console.log("Not everyone was able to join.", COLOR_RED); - errors.fetch_add(1); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - if (!wait_for_all_join(console, context, *entrance[index], env.consoles.size())){ - console.log("Switches joined into different raids.", COLOR_RED); - errors.fetch_add(1); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - // Ready up and wait for lobby to be ready. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Ready up. - context.wait_for(std::chrono::seconds(1)); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Wait - size_t index = console.index(); - if (!wait_for_lobby_ready(console, context, *entrance[index], env.consoles.size(), env.consoles.size(), time_limit)){ - errors.fetch_add(1); - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Start - if (!start_adventure(console, context, env.consoles.size())){ - errors.fetch_add(1); - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - return true; -} - -bool start_raid_host( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - GlobalStateTracker& state_tracker, - std::shared_ptr entrance[4], - ConsoleHandle& host, size_t boss_slot, - HostingSettings& settings, - const PathStats& path_stats, - const StatsTracker& session_stats, - ConsoleRuntime console_stats[4] -){ - if (env.consoles.size() == 1){ - ProControllerContext context(scope, host.pro_controller()); - return start_raid_host_solo( - env, host, context, - state_tracker, - entrance[0], boss_slot, - settings, - path_stats, session_stats, - console_stats[0].ore - ); - } - - env.log("Entering lobby..."); - - std::string code = settings.RAID_CODE.get_code(); - std::string boss; - - std::atomic errors(0); - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - bool is_host = index == host.index(); - - entrance[index] = enter_lobby( - console, context, - is_host ? boss_slot : 0, - settings.MODE == HostingMode::HOST_ONLINE, - console_stats[index].ore - ); - if (!*entrance[index]){ - errors.fetch_add(1); - return; - } - }); - if (errors.load(std::memory_order_acquire) != 0){ - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 8 * TICKS_PER_SECOND); - }); - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - GlobalState& state = state_tracker[index]; - bool is_host = index == host.index(); - - // Read boss. - if (is_host){ - boss = read_boss_sprite(console); - state.boss = boss; - } - - // Enter Code - if (!code.empty()){ - pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); - FastCodeEntry::numberpad_enter_code(console, context, code, true); - pbf_wait(context, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - } - }); - - // Start delay. - scope.wait_for(settings.START_DELAY0); - - // Open lobby. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // If you start the raids at the same time, they won't find each other. - if (console.index() != host.index()){ - pbf_wait(context, 3 * TICKS_PER_SECOND); - } - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - }); - - auto time_limit = current_time() + settings.LOBBY_WAIT_DELAY0.get(); - - AllJoinedTracker joined_tracker(scope, env.consoles.size(), time_limit); - - // Wait for all Switches to join. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Wait for a player to show up. This lets you ready up. - size_t index = console.index(); - if (!wait_for_a_player(console, context, *entrance[index], time_limit)){ - errors.fetch_add(1); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Wait for all consoles to join. - if (!joined_tracker.report_joined()){ - console.log("Not everyone was able to join.", COLOR_RED); - errors.fetch_add(1); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - size_t index = console.index(); - if (!wait_for_all_join(console, context, *entrance[index], env.consoles.size())){ - console.log("Switches joined into different raids.", COLOR_RED); - errors.fetch_add(1); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - send_raid_notification( - env, - host, - settings.NOTIFICATIONS, - code, - boss, - path_stats, session_stats - ); - - // Ready up and wait for lobby to be ready. - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Ready up. - context.wait_for(std::chrono::seconds(1)); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Wait - size_t index = console.index(); - if (!wait_for_lobby_ready(console, context, *entrance[index], env.consoles.size(), 4, time_limit)){ - errors.fetch_add(1); - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ - // Start - if (!start_adventure(console, context, env.consoles.size())){ - errors.fetch_add(1); - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return; - } - }); - if (abort_if_error(env, scope, errors)){ - return false; - } - - return true; -} - - - -bool start_adventure( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - GlobalStateTracker& state_tracker, - std::shared_ptr entrance[4], - ConsoleHandle& host, size_t boss_slot, - HostingSettings& settings, - const PathStats& path_stats, - const StatsTracker& session_stats, - ConsoleRuntime console_stats[4] -){ - switch (settings.MODE){ - case HostingMode::NOT_HOSTING: - return start_raid_local(env, scope, state_tracker, entrance, host, boss_slot, settings, console_stats); - case HostingMode::HOST_LOCALLY: - case HostingMode::HOST_ONLINE: - return start_raid_host( - env, scope, - state_tracker, - entrance, - host, boss_slot, - settings, - path_stats, session_stats, - console_stats - ); - } - throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Invalid mode enum."); -} - - - - - - - - - - -} -} -} -} +/* Max Lair Run Start + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" +#include "PokemonSwSh_MaxLair_Run_EnterLobby.h" +#include "PokemonSwSh_MaxLair_Run_Start.h" +#include "PokemonSwSh_MaxLair_Run_StartSolo.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +bool abort_if_error(MultiSwitchProgramEnvironment& env, CancellableScope& scope, const std::atomic& errors){ + if (errors.load(std::memory_order_acquire)){ + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + pbf_mash_button(context, BUTTON_B, 8 * TICKS_PER_SECOND); + }); + return true; + } + return false; +} + +bool wait_for_all_join( + VideoStream& stream, ProControllerContext& context, + const ImageViewRGB32& entrance, + size_t start_players +){ + LobbyJoinedDetector joined_detector(start_players, false); + EntranceDetector entrance_detector(entrance); + int result = wait_until( + stream, context, + std::chrono::seconds(10), + { + {joined_detector}, + {entrance_detector}, + }, + INFERENCE_RATE + ); + switch (result){ + case 0: + stream.log("Detected " + std::to_string(start_players) + " players in lobby!"); + return true; + case 1: + stream.log("Detected entrance... Did you get disconnected?", COLOR_RED); +// dump_image(stream, MODULE_NAME, "wait_for_all_join", stream.video().snapshot()); + return false; + default: + stream.log("Timed out waiting for everyone to join.", COLOR_RED); +// dump_image(stream, MODULE_NAME, "wait_for_all_join", stream.video().snapshot()); + return false; + } +} + +class AllJoinedTracker final : public Cancellable{ +public: + AllJoinedTracker( + CancellableScope& scope, size_t consoles, + WallClock time_limit + ) + : m_time_limit(time_limit) + , m_consoles(consoles) + , m_counter(0) + { + attach(scope); + } + virtual ~AllJoinedTracker(){} + + bool report_joined(){ + std::unique_lock lg(m_lock); + m_counter++; + if (m_counter >= m_consoles){ + m_cv.notify_all(); + return true; + } + while (true){ + m_cv.wait_until(lg, m_time_limit); + throw_if_cancelled(); + if (m_counter >= m_consoles){ + return true; + } + if (current_time() > m_time_limit){ + return false; + } + } + } + + virtual bool cancel(std::exception_ptr exception) noexcept override{ + if (Cancellable::cancel(std::move(exception))){ + return true; + } + std::lock_guard lg(m_lock); + m_cv.notify_all(); + return false; + } + +private: + std::mutex m_lock; + std::condition_variable m_cv; + + WallClock m_time_limit; + size_t m_consoles; + size_t m_counter; +}; + + + + + + +bool start_raid_local( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + GlobalStateTracker& state_tracker, + std::shared_ptr entrance[4], + ConsoleHandle& host, size_t boss_slot, + const HostingSettings& settings, + ConsoleRuntime console_stats[4] +){ + if (env.consoles.size() == 1){ + ProControllerContext context(scope, host.pro_controller()); + return start_raid_self_solo( + host, context, + state_tracker, entrance[0], boss_slot, console_stats[0].ore + ); + } + + env.log("Entering lobby..."); + + std::string code = settings.RAID_CODE.get_code(); + + std::atomic errors(0); + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + bool is_host = index == host.index(); + + entrance[index] = enter_lobby( + console, context, + is_host ? boss_slot : 0, + settings.MODE == HostingMode::HOST_ONLINE, + console_stats[index].ore + ); + if (!*entrance[index]){ + errors.fetch_add(1); + return; + } + }); + if (errors.load(std::memory_order_acquire) != 0){ + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 8 * TICKS_PER_SECOND); + }); + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + GlobalState& state = state_tracker[index]; + bool is_host = index == host.index(); + + // Read boss. + if (is_host){ + state.boss = read_boss_sprite(console); + } + + // Enter code. + if (!code.empty() && env.consoles.size() > 1){ + pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); + FastCodeEntry::numberpad_enter_code(console, context, code, true); + pbf_wait(context, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + } + }); + + // Open lobby. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Delay to prevent the Switches from forming separate lobbies. + if (env.consoles.size() > 1 && console.index() != host.index()){ + pbf_wait(context, 3 * TICKS_PER_SECOND); + } + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + }); + + auto time_limit = current_time() + settings.LOBBY_WAIT_DELAY0.get(); + + AllJoinedTracker joined_tracker(scope, env.consoles.size(), time_limit); + + // Wait for all Switches to join. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + + // Wait for a player to show up. This lets you ready up. + if (!wait_for_a_player(console, context, *entrance[index], time_limit)){ + errors.fetch_add(1); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Wait for all consoles to join. + if (!joined_tracker.report_joined()){ + console.log("Not everyone was able to join.", COLOR_RED); + errors.fetch_add(1); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + if (!wait_for_all_join(console, context, *entrance[index], env.consoles.size())){ + console.log("Switches joined into different raids.", COLOR_RED); + errors.fetch_add(1); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + // Ready up and wait for lobby to be ready. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Ready up. + context.wait_for(std::chrono::seconds(1)); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Wait + size_t index = console.index(); + if (!wait_for_lobby_ready(console, context, *entrance[index], env.consoles.size(), env.consoles.size(), time_limit)){ + errors.fetch_add(1); + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Start + if (!start_adventure(console, context, env.consoles.size())){ + errors.fetch_add(1); + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + return true; +} + +bool start_raid_host( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + GlobalStateTracker& state_tracker, + std::shared_ptr entrance[4], + ConsoleHandle& host, size_t boss_slot, + HostingSettings& settings, + const PathStats& path_stats, + const StatsTracker& session_stats, + ConsoleRuntime console_stats[4] +){ + if (env.consoles.size() == 1){ + ProControllerContext context(scope, host.pro_controller()); + return start_raid_host_solo( + env, host, context, + state_tracker, + entrance[0], boss_slot, + settings, + path_stats, session_stats, + console_stats[0].ore + ); + } + + env.log("Entering lobby..."); + + std::string code = settings.RAID_CODE.get_code(); + std::string boss; + + std::atomic errors(0); + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + bool is_host = index == host.index(); + + entrance[index] = enter_lobby( + console, context, + is_host ? boss_slot : 0, + settings.MODE == HostingMode::HOST_ONLINE, + console_stats[index].ore + ); + if (!*entrance[index]){ + errors.fetch_add(1); + return; + } + }); + if (errors.load(std::memory_order_acquire) != 0){ + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 8 * TICKS_PER_SECOND); + }); + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + GlobalState& state = state_tracker[index]; + bool is_host = index == host.index(); + + // Read boss. + if (is_host){ + boss = read_boss_sprite(console); + state.boss = boss; + } + + // Enter Code + if (!code.empty()){ + pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); + FastCodeEntry::numberpad_enter_code(console, context, code, true); + pbf_wait(context, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + } + }); + + // Start delay. + scope.wait_for(settings.START_DELAY0); + + // Open lobby. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // If you start the raids at the same time, they won't find each other. + if (console.index() != host.index()){ + pbf_wait(context, 3 * TICKS_PER_SECOND); + } + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + }); + + auto time_limit = current_time() + settings.LOBBY_WAIT_DELAY0.get(); + + AllJoinedTracker joined_tracker(scope, env.consoles.size(), time_limit); + + // Wait for all Switches to join. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Wait for a player to show up. This lets you ready up. + size_t index = console.index(); + if (!wait_for_a_player(console, context, *entrance[index], time_limit)){ + errors.fetch_add(1); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Wait for all consoles to join. + if (!joined_tracker.report_joined()){ + console.log("Not everyone was able to join.", COLOR_RED); + errors.fetch_add(1); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + size_t index = console.index(); + if (!wait_for_all_join(console, context, *entrance[index], env.consoles.size())){ + console.log("Switches joined into different raids.", COLOR_RED); + errors.fetch_add(1); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + send_raid_notification( + env, + host, + settings.NOTIFICATIONS, + code, + boss, + path_stats, session_stats + ); + + // Ready up and wait for lobby to be ready. + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Ready up. + context.wait_for(std::chrono::seconds(1)); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Wait + size_t index = console.index(); + if (!wait_for_lobby_ready(console, context, *entrance[index], env.consoles.size(), 4, time_limit)){ + errors.fetch_add(1); + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + env.run_in_parallel(scope, [&](ConsoleHandle& console, ProControllerContext& context){ + // Start + if (!start_adventure(console, context, env.consoles.size())){ + errors.fetch_add(1); + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return; + } + }); + if (abort_if_error(env, scope, errors)){ + return false; + } + + return true; +} + + + +bool start_adventure( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + GlobalStateTracker& state_tracker, + std::shared_ptr entrance[4], + ConsoleHandle& host, size_t boss_slot, + HostingSettings& settings, + const PathStats& path_stats, + const StatsTracker& session_stats, + ConsoleRuntime console_stats[4] +){ + switch (settings.MODE){ + case HostingMode::NOT_HOSTING: + return start_raid_local(env, scope, state_tracker, entrance, host, boss_slot, settings, console_stats); + case HostingMode::HOST_LOCALLY: + case HostingMode::HOST_ONLINE: + return start_raid_host( + env, scope, + state_tracker, + entrance, + host, boss_slot, + settings, + path_stats, session_stats, + console_stats + ); + } + throw InternalProgramError(&env.logger(), PA_CURRENT_FUNCTION, "Invalid mode enum."); +} + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h index 72ee2ff58a..e11a0cb0a1 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_Start.h @@ -1,40 +1,40 @@ -/* Max Lair Run Start - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Start_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Start_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -// Returns true if adventure started. False if you errored and are back at the entrance. -bool start_adventure( - MultiSwitchProgramEnvironment& env, CancellableScope& scope, - GlobalStateTracker& state_tracker, - std::shared_ptr entrance[4], - ConsoleHandle& host, size_t boss_slot, - HostingSettings& settings, - const PathStats& path_stats, - const StatsTracker& session_stats, - ConsoleRuntime console_stats[4] -); - - - -} -} -} -} -#endif +/* Max Lair Run Start + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_Start_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_Start_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateMachine.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +// Returns true if adventure started. False if you errored and are back at the entrance. +bool start_adventure( + MultiSwitchProgramEnvironment& env, CancellableScope& scope, + GlobalStateTracker& state_tracker, + std::shared_ptr entrance[4], + ConsoleHandle& host, size_t boss_slot, + HostingSettings& settings, + const PathStats& path_stats, + const StatsTracker& session_stats, + ConsoleRuntime console_stats[4] +); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.cpp b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.cpp index 074e89d700..79416c6efb 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.cpp +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.cpp @@ -1,242 +1,242 @@ -/* Max Lair Run Start (Solo) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" -#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" -#include "PokemonSwSh_MaxLair_Run_EnterLobby.h" -#include "PokemonSwSh_MaxLair_Run_StartSolo.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - - -bool wait_for_a_player( - VideoStream& stream, ProControllerContext& context, - const ImageViewRGB32& entrance, - WallClock time_limit -){ - LobbyDoneConnecting done_connecting_detector; - EntranceDetector entrance_detector(entrance); - PokemonSelectMenuDetector false_start_detector(false); - - int result = wait_until( - stream, context, - time_limit, - { - {done_connecting_detector}, - {entrance_detector}, - {false_start_detector}, - }, - INFERENCE_RATE - ); - switch (result){ - case 0: - stream.log("Connected to lobby."); - break; - case 1: - stream.log("Detected entrance... Did you get disconnected?", COLOR_RED); - return false; - case 2: - stream.log("Detected false start. Did you join the wrong lobby?", COLOR_RED); - return false; - default: - stream.log("Timed out connecting to lobby.", COLOR_RED); - return false; - } - return true; -} - -bool wait_for_lobby_ready( - VideoStream& stream, ProControllerContext& context, - const ImageViewRGB32& entrance, - size_t min_players, - size_t start_players, - WallClock time_limit -){ - LobbyAllReadyDetector ready_detector(start_players); - EntranceDetector entrance_detector(entrance); - PokemonSelectMenuDetector false_start_detector(false); - - int result = wait_until( - stream, context, - time_limit, - { - {ready_detector}, - {entrance_detector}, - }, - INFERENCE_RATE - ); - switch (result){ - case 0: - stream.log("Detected lobby ready..."); - return true; - case 1: - stream.log("Detected entrance... Did you get disconnected?", COLOR_RED); - return false; - case 2: - stream.log("Detected false start. Did you join the wrong lobby?", COLOR_RED); - return false; - } - return true; -} -bool start_adventure( - VideoStream& stream, ProControllerContext& context, - size_t consoles -){ - LobbyMinReadyDetector ready_detector(consoles, true); - if (ready_detector.ready_players(stream.video().snapshot()) < consoles){ - stream.log("Number of players less than expected. Did someone join the wrong lobby?", COLOR_RED); - return false; - } - - // Press A until you're not in the lobby anymore. - LobbyDetector lobby_detector(true); - int result = run_until( - stream, context, - [](ProControllerContext& context){ - for (size_t c = 0; c < 180; c++){ - pbf_press_button(context, BUTTON_A, 10, 115); - context.wait_for_all_requests(); - } - }, - {{lobby_detector}}, - INFERENCE_RATE - ); - switch (result){ - case 0: - return true; - default: - stream.log("Timed out starting raid.", COLOR_RED); - return false; - } -} - - - - -bool start_raid_self_solo( - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker, - std::shared_ptr& entrance, size_t boss_slot, - ReadableQuantity999& ore -){ - stream.log("Entering lobby..."); - - GlobalState& state = state_tracker[0]; - - // Enter lobby. - entrance = enter_lobby(stream, context, boss_slot, false, ore); - if (!*entrance){ - return false; - } - - // Read boss. - state.boss = read_boss_sprite(stream); - - // Start raid. - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - return true; -} - -bool start_raid_host_solo( - ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, - GlobalStateTracker& state_tracker, - std::shared_ptr& entrance, size_t boss_slot, - HostingSettings& settings, - const PathStats& path_stats, - const StatsTracker& session_stats, - ReadableQuantity999& ore -){ - console.log("Entering lobby..."); - - GlobalState& state = state_tracker[0]; - - // Start delay. - context.wait_for(settings.START_DELAY0); - - // Enter lobby. - entrance = enter_lobby( - console, context, boss_slot, - settings.MODE == HostingMode::HOST_ONLINE, - ore - ); - if (!*entrance){ - return false; - } - - // Read boss. - state.boss = read_boss_sprite(console); - - // Enter code. - std::string code = settings.RAID_CODE.get_code(); - if (!code.empty()){ - pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); - FastCodeEntry::numberpad_enter_code(console, context, code, true); - pbf_wait(context, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - send_raid_notification( - env, - console, - settings.NOTIFICATIONS, - code, - state.boss, - path_stats, session_stats - ); - - // Open lobby. - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - auto time_limit = current_time() + settings.LOBBY_WAIT_DELAY0.get(); - - if (!wait_for_a_player(console, context, *entrance, time_limit)){ - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return start_raid_self_solo(console, context, state_tracker, entrance, boss_slot, ore); - } - - // Ready up. - context.wait_for(std::chrono::seconds(1)); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Wait - if (!wait_for_lobby_ready(console, context, *entrance, 1, 4, time_limit)){ - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return false; - } - - // Start - context.wait_for_all_requests(); - if (!start_adventure(console, context, 1)){ - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - return false; - } - - return true; -} - - - -} -} -} -} +/* Max Lair Run Start (Solo) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonReader.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Lobby.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_Entrance.h" +#include "PokemonSwSh/MaxLair/Inference/PokemonSwSh_MaxLair_Detect_PokemonSelectMenu.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Notifications.h" +#include "PokemonSwSh_MaxLair_Run_EnterLobby.h" +#include "PokemonSwSh_MaxLair_Run_StartSolo.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + + +bool wait_for_a_player( + VideoStream& stream, ProControllerContext& context, + const ImageViewRGB32& entrance, + WallClock time_limit +){ + LobbyDoneConnecting done_connecting_detector; + EntranceDetector entrance_detector(entrance); + PokemonSelectMenuDetector false_start_detector(false); + + int result = wait_until( + stream, context, + time_limit, + { + {done_connecting_detector}, + {entrance_detector}, + {false_start_detector}, + }, + INFERENCE_RATE + ); + switch (result){ + case 0: + stream.log("Connected to lobby."); + break; + case 1: + stream.log("Detected entrance... Did you get disconnected?", COLOR_RED); + return false; + case 2: + stream.log("Detected false start. Did you join the wrong lobby?", COLOR_RED); + return false; + default: + stream.log("Timed out connecting to lobby.", COLOR_RED); + return false; + } + return true; +} + +bool wait_for_lobby_ready( + VideoStream& stream, ProControllerContext& context, + const ImageViewRGB32& entrance, + size_t min_players, + size_t start_players, + WallClock time_limit +){ + LobbyAllReadyDetector ready_detector(start_players); + EntranceDetector entrance_detector(entrance); + PokemonSelectMenuDetector false_start_detector(false); + + int result = wait_until( + stream, context, + time_limit, + { + {ready_detector}, + {entrance_detector}, + }, + INFERENCE_RATE + ); + switch (result){ + case 0: + stream.log("Detected lobby ready..."); + return true; + case 1: + stream.log("Detected entrance... Did you get disconnected?", COLOR_RED); + return false; + case 2: + stream.log("Detected false start. Did you join the wrong lobby?", COLOR_RED); + return false; + } + return true; +} +bool start_adventure( + VideoStream& stream, ProControllerContext& context, + size_t consoles +){ + LobbyMinReadyDetector ready_detector(consoles, true); + if (ready_detector.ready_players(stream.video().snapshot()) < consoles){ + stream.log("Number of players less than expected. Did someone join the wrong lobby?", COLOR_RED); + return false; + } + + // Press A until you're not in the lobby anymore. + LobbyDetector lobby_detector(true); + int result = run_until( + stream, context, + [](ProControllerContext& context){ + for (size_t c = 0; c < 180; c++){ + pbf_press_button(context, BUTTON_A, 10, 115); + context.wait_for_all_requests(); + } + }, + {{lobby_detector}}, + INFERENCE_RATE + ); + switch (result){ + case 0: + return true; + default: + stream.log("Timed out starting raid.", COLOR_RED); + return false; + } +} + + + + +bool start_raid_self_solo( + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker, + std::shared_ptr& entrance, size_t boss_slot, + ReadableQuantity999& ore +){ + stream.log("Entering lobby..."); + + GlobalState& state = state_tracker[0]; + + // Enter lobby. + entrance = enter_lobby(stream, context, boss_slot, false, ore); + if (!*entrance){ + return false; + } + + // Read boss. + state.boss = read_boss_sprite(stream); + + // Start raid. + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + return true; +} + +bool start_raid_host_solo( + ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, + GlobalStateTracker& state_tracker, + std::shared_ptr& entrance, size_t boss_slot, + HostingSettings& settings, + const PathStats& path_stats, + const StatsTracker& session_stats, + ReadableQuantity999& ore +){ + console.log("Entering lobby..."); + + GlobalState& state = state_tracker[0]; + + // Start delay. + context.wait_for(settings.START_DELAY0); + + // Enter lobby. + entrance = enter_lobby( + console, context, boss_slot, + settings.MODE == HostingMode::HOST_ONLINE, + ore + ); + if (!*entrance){ + return false; + } + + // Read boss. + state.boss = read_boss_sprite(console); + + // Enter code. + std::string code = settings.RAID_CODE.get_code(); + if (!code.empty()){ + pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); + FastCodeEntry::numberpad_enter_code(console, context, code, true); + pbf_wait(context, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + send_raid_notification( + env, + console, + settings.NOTIFICATIONS, + code, + state.boss, + path_stats, session_stats + ); + + // Open lobby. + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + auto time_limit = current_time() + settings.LOBBY_WAIT_DELAY0.get(); + + if (!wait_for_a_player(console, context, *entrance, time_limit)){ + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return start_raid_self_solo(console, context, state_tracker, entrance, boss_slot, ore); + } + + // Ready up. + context.wait_for(std::chrono::seconds(1)); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Wait + if (!wait_for_lobby_ready(console, context, *entrance, 1, 4, time_limit)){ + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return false; + } + + // Start + context.wait_for_all_requests(); + if (!start_adventure(console, context, 1)){ + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + return false; + } + + return true; +} + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.h b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.h index 6671f838cc..4dfe4bc1da 100644 --- a/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.h +++ b/SerialPrograms/Source/PokemonSwSh/MaxLair/Program/PokemonSwSh_MaxLair_Run_StartSolo.h @@ -1,66 +1,66 @@ -/* Max Lair Run Start (Solo) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_StartSolo_H -#define PokemonAutomation_PokemonSwSh_MaxLair_Run_StartSolo_H - -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h" -#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h" -#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - -bool wait_for_a_player( - VideoStream& stream, ProControllerContext& context, - const ImageViewRGB32& entrance, - WallClock time_limit -); -bool wait_for_lobby_ready( - VideoStream& stream, ProControllerContext& context, - const ImageViewRGB32& entrance, - size_t min_players, - size_t start_players, - WallClock time_limit -); -bool start_adventure( - VideoStream& stream, ProControllerContext& context, - size_t consoles -); - - -bool start_raid_self_solo( - VideoStream& stream, ProControllerContext& context, - GlobalStateTracker& state_tracker, - std::shared_ptr& entrance, size_t boss_slot, - ReadableQuantity999& ore -); - -bool start_raid_host_solo( - ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, - GlobalStateTracker& state_tracker, - std::shared_ptr& entrance, size_t boss_slot, - HostingSettings& settings, - const PathStats& path_stats, - const StatsTracker& session_stats, - ReadableQuantity999& ore -); - - -} -} -} -} -#endif +/* Max Lair Run Start (Solo) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLair_Run_StartSolo_H +#define PokemonAutomation_PokemonSwSh_MaxLair_Run_StartSolo_H + +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSwSh/Inference/PokemonSwSh_QuantityReader.h" +#include "PokemonSwSh/MaxLair/Options/PokemonSwSh_MaxLair_Options_Hosting.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_Stats.h" +#include "PokemonSwSh/MaxLair/Framework/PokemonSwSh_MaxLair_StateTracker.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + +bool wait_for_a_player( + VideoStream& stream, ProControllerContext& context, + const ImageViewRGB32& entrance, + WallClock time_limit +); +bool wait_for_lobby_ready( + VideoStream& stream, ProControllerContext& context, + const ImageViewRGB32& entrance, + size_t min_players, + size_t start_players, + WallClock time_limit +); +bool start_adventure( + VideoStream& stream, ProControllerContext& context, + size_t consoles +); + + +bool start_raid_self_solo( + VideoStream& stream, ProControllerContext& context, + GlobalStateTracker& state_tracker, + std::shared_ptr& entrance, size_t boss_slot, + ReadableQuantity999& ore +); + +bool start_raid_host_solo( + ProgramEnvironment& env, ConsoleHandle& console, ProControllerContext& context, + GlobalStateTracker& state_tracker, + std::shared_ptr& entrance, size_t boss_slot, + HostingSettings& settings, + const PathStats& path_stats, + const StatsTracker& session_stats, + ReadableQuantity999& ore +); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.cpp b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.cpp index 1fd360de8f..8e90cd7869 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.cpp @@ -1,81 +1,81 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_EncounterFilterEnums.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -const EnumDropdownDatabase& EncounterAction_Database(){ - static const EnumDropdownDatabase database({ - {EncounterAction::StopProgram, "stop", "Stop Program"}, - {EncounterAction::RunAway, "run", "Run Away"}, - {EncounterAction::ThrowBalls, "throw-balls", "Throw balls."}, - {EncounterAction::ThrowBallsAndSave, "throw-balls-and-save", "Throw balls. Save if caught."}, - }); - return database; -} - - - -const EnumDropdownDatabase& ShinyFilter_Normal_Database(){ - static const EnumDropdownDatabase database({ - {ShinyFilter::ANYTHING, "anything", "Anything"}, - {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, - {ShinyFilter::ANY_SHINY, "any-shiny", "Any Shiny"}, - {ShinyFilter::STAR_ONLY, "star-shiny", "Star Shiny"}, - {ShinyFilter::SQUARE_ONLY, "square-shiny", "Square Shiny"}, -// {ShinyFilter::NOTHING, "nothing", "Nothing"}, - }); - return database; -} -const EnumDropdownDatabase& ShinyFilter_StopRareStars_Database(){ - static const EnumDropdownDatabase database({ - {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, - {ShinyFilter::ANY_SHINY, "any-shiny", "Any Shiny"}, - {ShinyFilter::STAR_ONLY, "star-shiny", "Star Shiny"}, - }); - return database; -} -const EnumDropdownDatabase& ShinyFilter_TableRareStars_Database(){ - static const EnumDropdownDatabase database({ - {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, - {ShinyFilter::SQUARE_ONLY, "square-shiny", "Square Shiny"}, - }); - return database; -} - - - -const std::vector ShinyFilter_NAMES{ - "Anything", - "Not Shiny", - "Any Shiny", - "Star Shiny", - "Square Shiny", - "Nothing", -}; -const std::map ShinyFilter_MAP{ - {ShinyFilter_NAMES[0], ShinyFilter::ANYTHING}, - {ShinyFilter_NAMES[1], ShinyFilter::NOT_SHINY}, - {ShinyFilter_NAMES[2], ShinyFilter::ANY_SHINY}, - {ShinyFilter_NAMES[3], ShinyFilter::STAR_ONLY}, - {ShinyFilter_NAMES[4], ShinyFilter::SQUARE_ONLY}, - {ShinyFilter_NAMES[5], ShinyFilter::NOTHING}, -}; - - - - - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_EncounterFilterEnums.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +const EnumDropdownDatabase& EncounterAction_Database(){ + static const EnumDropdownDatabase database({ + {EncounterAction::StopProgram, "stop", "Stop Program"}, + {EncounterAction::RunAway, "run", "Run Away"}, + {EncounterAction::ThrowBalls, "throw-balls", "Throw balls."}, + {EncounterAction::ThrowBallsAndSave, "throw-balls-and-save", "Throw balls. Save if caught."}, + }); + return database; +} + + + +const EnumDropdownDatabase& ShinyFilter_Normal_Database(){ + static const EnumDropdownDatabase database({ + {ShinyFilter::ANYTHING, "anything", "Anything"}, + {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, + {ShinyFilter::ANY_SHINY, "any-shiny", "Any Shiny"}, + {ShinyFilter::STAR_ONLY, "star-shiny", "Star Shiny"}, + {ShinyFilter::SQUARE_ONLY, "square-shiny", "Square Shiny"}, +// {ShinyFilter::NOTHING, "nothing", "Nothing"}, + }); + return database; +} +const EnumDropdownDatabase& ShinyFilter_StopRareStars_Database(){ + static const EnumDropdownDatabase database({ + {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, + {ShinyFilter::ANY_SHINY, "any-shiny", "Any Shiny"}, + {ShinyFilter::STAR_ONLY, "star-shiny", "Star Shiny"}, + }); + return database; +} +const EnumDropdownDatabase& ShinyFilter_TableRareStars_Database(){ + static const EnumDropdownDatabase database({ + {ShinyFilter::NOT_SHINY, "not-shiny", "Not Shiny"}, + {ShinyFilter::SQUARE_ONLY, "square-shiny", "Square Shiny"}, + }); + return database; +} + + + +const std::vector ShinyFilter_NAMES{ + "Anything", + "Not Shiny", + "Any Shiny", + "Star Shiny", + "Square Shiny", + "Nothing", +}; +const std::map ShinyFilter_MAP{ + {ShinyFilter_NAMES[0], ShinyFilter::ANYTHING}, + {ShinyFilter_NAMES[1], ShinyFilter::NOT_SHINY}, + {ShinyFilter_NAMES[2], ShinyFilter::ANY_SHINY}, + {ShinyFilter_NAMES[3], ShinyFilter::STAR_ONLY}, + {ShinyFilter_NAMES[4], ShinyFilter::SQUARE_ONLY}, + {ShinyFilter_NAMES[5], ShinyFilter::NOTHING}, +}; + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h index d939263b1c..3c029c142c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterEnums.h @@ -1,77 +1,77 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterEnums_H -#define PokemonAutomation_PokemonSwSh_EncounterFilterEnums_H - -#include -#include -#include -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -enum class EncounterAction{ - StopProgram, - RunAway, - ThrowBalls, - ThrowBallsAndSave, -}; -const EnumDropdownDatabase& EncounterAction_Database(); - - -class EncounterActionCell : public EnumDropdownCell{ -public: - EncounterActionCell() - : EnumDropdownCell( - EncounterAction_Database(), - LockMode::LOCK_WHILE_RUNNING, - EncounterAction::StopProgram - ) - {} -}; - - - -enum class ShinyFilter{ - ANYTHING, - NOT_SHINY, - ANY_SHINY, - STAR_ONLY, - SQUARE_ONLY, - NOTHING, -}; -const EnumDropdownDatabase& ShinyFilter_Normal_Database(); -const EnumDropdownDatabase& ShinyFilter_StopRareStars_Database(); -const EnumDropdownDatabase& ShinyFilter_TableRareStars_Database(); - -class ShinyFilterCell : public EnumDropdownCell{ -public: - ShinyFilterCell(bool rare_stars) - : EnumDropdownCell( - rare_stars ? ShinyFilter_TableRareStars_Database() : ShinyFilter_Normal_Database(), - LockMode::LOCK_WHILE_RUNNING, - ShinyFilter::NOT_SHINY - ) - {} -}; - - -extern const std::vector ShinyFilter_NAMES; -extern const std::map ShinyFilter_MAP; - - - - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterEnums_H +#define PokemonAutomation_PokemonSwSh_EncounterFilterEnums_H + +#include +#include +#include +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +enum class EncounterAction{ + StopProgram, + RunAway, + ThrowBalls, + ThrowBallsAndSave, +}; +const EnumDropdownDatabase& EncounterAction_Database(); + + +class EncounterActionCell : public EnumDropdownCell{ +public: + EncounterActionCell() + : EnumDropdownCell( + EncounterAction_Database(), + LockMode::LOCK_WHILE_RUNNING, + EncounterAction::StopProgram + ) + {} +}; + + + +enum class ShinyFilter{ + ANYTHING, + NOT_SHINY, + ANY_SHINY, + STAR_ONLY, + SQUARE_ONLY, + NOTHING, +}; +const EnumDropdownDatabase& ShinyFilter_Normal_Database(); +const EnumDropdownDatabase& ShinyFilter_StopRareStars_Database(); +const EnumDropdownDatabase& ShinyFilter_TableRareStars_Database(); + +class ShinyFilterCell : public EnumDropdownCell{ +public: + ShinyFilterCell(bool rare_stars) + : EnumDropdownCell( + rare_stars ? ShinyFilter_TableRareStars_Database() : ShinyFilter_Normal_Database(), + LockMode::LOCK_WHILE_RUNNING, + ShinyFilter::NOT_SHINY + ) + {} +}; + + +extern const std::vector ShinyFilter_NAMES; +extern const std::map ShinyFilter_MAP; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.cpp b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.cpp index b5b46c9dbb..390a1e5f64 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.cpp @@ -1,109 +1,109 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_EncounterFilterEnums.h" -#include "PokemonSwSh_EncounterFilterOption.h" -#include "PokemonSwSh_EncounterFilterWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - - -#if 0 -EncounterFilterOption::EncounterFilterOption(bool rare_stars, bool enable_overrides) - : m_rare_stars(rare_stars) - , m_enable_overrides(enable_overrides) - , m_shiny_filter_default(ShinyFilter::ANY_SHINY) - , m_shiny_filter_current(m_shiny_filter_default) - , m_table(rare_stars) -{} -void EncounterFilterOption::load_json(const JsonValue& json){ - using namespace Pokemon; - - const JsonObject* obj = json.to_object(); - - const std::string* str = obj->get_string("ShinyFilter"); - if (str != nullptr){ - auto iter = ShinyFilter_MAP.find(*str); - if (iter != ShinyFilter_MAP.end()){ - m_shiny_filter_current = iter->second; - } - } - - if (m_enable_overrides){ - const JsonValue* value = obj->get_value("Overrides"); - if (value != nullptr){ - m_table.load_json(*value); - } - } -} -JsonValue EncounterFilterOption::to_json() const{ - JsonObject obj; - obj["ShinyFilter"] = ShinyFilter_NAMES[(size_t)m_shiny_filter_current.load(std::memory_order_relaxed)]; - if (m_enable_overrides){ - obj["Overrides"] = m_table.to_json(); - } - return obj; -} -void EncounterFilterOption::restore_defaults(){ - m_shiny_filter_current = m_shiny_filter_default; - m_table.restore_defaults(); -} -ConfigWidget* EncounterFilterOption::make_QtWidget(QWidget& parent){ - return new EncounterFilterWidget(parent, *this); -} -#endif - - - - - -EncounterFilterOption2::EncounterFilterOption2(bool rare_stars, bool enable_overrides) - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , SHINY_FILTER( - "Stop on:", - rare_stars ? ShinyFilter_StopRareStars_Database() : ShinyFilter_Normal_Database(), - LockMode::UNLOCK_WHILE_RUNNING, - ShinyFilter::ANY_SHINY - ) - , FILTER_TABLE(rare_stars) -{ - PA_ADD_OPTION(SHINY_FILTER); - if (enable_overrides){ - PA_ADD_OPTION(FILTER_TABLE); - } -} - - - - - - - - - - - - - - - - - - - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_EncounterFilterEnums.h" +#include "PokemonSwSh_EncounterFilterOption.h" +#include "PokemonSwSh_EncounterFilterWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + + +#if 0 +EncounterFilterOption::EncounterFilterOption(bool rare_stars, bool enable_overrides) + : m_rare_stars(rare_stars) + , m_enable_overrides(enable_overrides) + , m_shiny_filter_default(ShinyFilter::ANY_SHINY) + , m_shiny_filter_current(m_shiny_filter_default) + , m_table(rare_stars) +{} +void EncounterFilterOption::load_json(const JsonValue& json){ + using namespace Pokemon; + + const JsonObject* obj = json.to_object(); + + const std::string* str = obj->get_string("ShinyFilter"); + if (str != nullptr){ + auto iter = ShinyFilter_MAP.find(*str); + if (iter != ShinyFilter_MAP.end()){ + m_shiny_filter_current = iter->second; + } + } + + if (m_enable_overrides){ + const JsonValue* value = obj->get_value("Overrides"); + if (value != nullptr){ + m_table.load_json(*value); + } + } +} +JsonValue EncounterFilterOption::to_json() const{ + JsonObject obj; + obj["ShinyFilter"] = ShinyFilter_NAMES[(size_t)m_shiny_filter_current.load(std::memory_order_relaxed)]; + if (m_enable_overrides){ + obj["Overrides"] = m_table.to_json(); + } + return obj; +} +void EncounterFilterOption::restore_defaults(){ + m_shiny_filter_current = m_shiny_filter_default; + m_table.restore_defaults(); +} +ConfigWidget* EncounterFilterOption::make_QtWidget(QWidget& parent){ + return new EncounterFilterWidget(parent, *this); +} +#endif + + + + + +EncounterFilterOption2::EncounterFilterOption2(bool rare_stars, bool enable_overrides) + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , SHINY_FILTER( + "Stop on:", + rare_stars ? ShinyFilter_StopRareStars_Database() : ShinyFilter_Normal_Database(), + LockMode::UNLOCK_WHILE_RUNNING, + ShinyFilter::ANY_SHINY + ) + , FILTER_TABLE(rare_stars) +{ + PA_ADD_OPTION(SHINY_FILTER); + if (enable_overrides){ + PA_ADD_OPTION(FILTER_TABLE); + } +} + + + + + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h index 482de20643..b0257ae00a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h @@ -1,67 +1,67 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterOption_H -#define PokemonAutomation_PokemonSwSh_EncounterFilterOption_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "PokemonSwSh_EncounterFilterOverride.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -#if 0 -class EncounterFilterOption : public ConfigOption{ -public: - EncounterFilterOption(bool rare_stars, bool enable_overrides); - - ShinyFilter shiny_filter() const{ return m_shiny_filter_current.load(std::memory_order_relaxed); } - std::vector> copy_snapshot() const{ - return m_table.copy_snapshot(); - } - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - virtual void restore_defaults() override; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - -private: - friend class EncounterFilterWidget; - - const bool m_rare_stars; - const bool m_enable_overrides; - - const ShinyFilter m_shiny_filter_default; - std::atomic m_shiny_filter_current; - - EncounterFilterTable m_table; -}; -#endif - - - - -class EncounterFilterOption2 : public BatchOption{ -public: - EncounterFilterOption2(bool rare_stars, bool enable_overrides); - -public: - EnumDropdownOption SHINY_FILTER; - EncounterFilterTable FILTER_TABLE; -}; - - - - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterOption_H +#define PokemonAutomation_PokemonSwSh_EncounterFilterOption_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "PokemonSwSh_EncounterFilterOverride.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +#if 0 +class EncounterFilterOption : public ConfigOption{ +public: + EncounterFilterOption(bool rare_stars, bool enable_overrides); + + ShinyFilter shiny_filter() const{ return m_shiny_filter_current.load(std::memory_order_relaxed); } + std::vector> copy_snapshot() const{ + return m_table.copy_snapshot(); + } + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + virtual void restore_defaults() override; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + +private: + friend class EncounterFilterWidget; + + const bool m_rare_stars; + const bool m_enable_overrides; + + const ShinyFilter m_shiny_filter_default; + std::atomic m_shiny_filter_current; + + EncounterFilterTable m_table; +}; +#endif + + + + +class EncounterFilterOption2 : public BatchOption{ +public: + EncounterFilterOption2(bool rare_stars, bool enable_overrides); + +public: + EnumDropdownOption SHINY_FILTER; + EncounterFilterTable FILTER_TABLE; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp index fc6fb79bbb..85b7ee80e3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.cpp @@ -1,138 +1,138 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h" -#include "PokemonSwSh_EncounterFilterOverride.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - - - -EncounterFilterOverride::~EncounterFilterOverride(){ - action.remove_listener(*this); -} -EncounterFilterOverride::EncounterFilterOverride(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , pokemon(COMBINED_DEX_NAMES(), LockMode::UNLOCK_WHILE_RUNNING, "rookidee") - , shininess(static_cast(parent_table).rare_stars) - , ball_limit(LockMode::UNLOCK_WHILE_RUNNING, 40, 1, 999) -{ - PA_ADD_OPTION(pokemon); - PA_ADD_OPTION(shininess); - PA_ADD_OPTION(action); - PA_ADD_OPTION(pokeball); - PA_ADD_OPTION(ball_limit); - action.add_listener(*this); -} -void EncounterFilterOverride::load_json(const JsonValue& json){ - EditableTableRow::load_json(json); - - // Parse old format for backwards compatibility. - const JsonObject* obj = json.to_object(); - if (obj == nullptr){ - return; - } - - const JsonValue* value; - value = obj->get_value("Species"); - if (value != nullptr){ - pokemon.load_json(*value); - } - value = obj->get_value("ShinyFilter"); - if (value != nullptr){ - shininess.load_json(*value); - } - value = obj->get_value("Action"); - if (value != nullptr){ - action.load_json(*value); - } - value = obj->get_value("Ball"); - if (value != nullptr){ - pokeball.load_json(*value); - } -} -std::unique_ptr EncounterFilterOverride::clone() const{ - std::unique_ptr ret(new EncounterFilterOverride(parent())); - ret->pokemon.set_by_index(pokemon.index()); - ret->shininess.set(shininess); - ret->action.set(action); - ret->pokeball.set_by_index(pokeball.index()); - ret->ball_limit.set(ball_limit); - return ret; -} -void EncounterFilterOverride::on_config_value_changed(void* object){ - switch ((EncounterAction)action){ - case EncounterAction::StopProgram: - case EncounterAction::RunAway: - pokeball.set_visibility(ConfigOptionState::DISABLED); - break; - case EncounterAction::ThrowBalls: - case EncounterAction::ThrowBallsAndSave: - pokeball.set_visibility(ConfigOptionState::ENABLED); - break; - } -} - - - -EncounterFilterTable::EncounterFilterTable(bool p_rare_stars) - : EditableTableOption( - p_rare_stars - ? "Overrides:
" - "The game language must be properly set to read " + STRING_POKEMON + " names. " - "If more than one override applies, the last one will be chosen.
" - "Due to the extreme rarity of star shinies (1 in 6 million), " - "the filters here will not allow you to run from them. " - "If you get a star shiny, catch it and cherish it." - : - "Overrides:
" - "The game language must be properly set to read " + STRING_POKEMON + " names.
" - "If more than one override applies, the last one will be chosen.", - LockMode::UNLOCK_WHILE_RUNNING - ) - , rare_stars(p_rare_stars) -{} -std::vector> EncounterFilterTable::copy_snapshot() const{ - return EditableTableOption::copy_snapshot(); -} -std::vector EncounterFilterTable::make_header() const{ - return std::vector{ - STRING_POKEMON, - "Shininess", - "Action", - STRING_POKEBALL, - "Ball Limit", - }; -} -std::unique_ptr EncounterFilterTable::make_row(){ - return std::unique_ptr(new EncounterFilterOverride(*this)); -} - - - - - - - - - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h" +#include "PokemonSwSh_EncounterFilterOverride.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + + + +EncounterFilterOverride::~EncounterFilterOverride(){ + action.remove_listener(*this); +} +EncounterFilterOverride::EncounterFilterOverride(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , pokemon(COMBINED_DEX_NAMES(), LockMode::UNLOCK_WHILE_RUNNING, "rookidee") + , shininess(static_cast(parent_table).rare_stars) + , ball_limit(LockMode::UNLOCK_WHILE_RUNNING, 40, 1, 999) +{ + PA_ADD_OPTION(pokemon); + PA_ADD_OPTION(shininess); + PA_ADD_OPTION(action); + PA_ADD_OPTION(pokeball); + PA_ADD_OPTION(ball_limit); + action.add_listener(*this); +} +void EncounterFilterOverride::load_json(const JsonValue& json){ + EditableTableRow::load_json(json); + + // Parse old format for backwards compatibility. + const JsonObject* obj = json.to_object(); + if (obj == nullptr){ + return; + } + + const JsonValue* value; + value = obj->get_value("Species"); + if (value != nullptr){ + pokemon.load_json(*value); + } + value = obj->get_value("ShinyFilter"); + if (value != nullptr){ + shininess.load_json(*value); + } + value = obj->get_value("Action"); + if (value != nullptr){ + action.load_json(*value); + } + value = obj->get_value("Ball"); + if (value != nullptr){ + pokeball.load_json(*value); + } +} +std::unique_ptr EncounterFilterOverride::clone() const{ + std::unique_ptr ret(new EncounterFilterOverride(parent())); + ret->pokemon.set_by_index(pokemon.index()); + ret->shininess.set(shininess); + ret->action.set(action); + ret->pokeball.set_by_index(pokeball.index()); + ret->ball_limit.set(ball_limit); + return ret; +} +void EncounterFilterOverride::on_config_value_changed(void* object){ + switch ((EncounterAction)action){ + case EncounterAction::StopProgram: + case EncounterAction::RunAway: + pokeball.set_visibility(ConfigOptionState::DISABLED); + break; + case EncounterAction::ThrowBalls: + case EncounterAction::ThrowBallsAndSave: + pokeball.set_visibility(ConfigOptionState::ENABLED); + break; + } +} + + + +EncounterFilterTable::EncounterFilterTable(bool p_rare_stars) + : EditableTableOption( + p_rare_stars + ? "Overrides:
" + "The game language must be properly set to read " + STRING_POKEMON + " names. " + "If more than one override applies, the last one will be chosen.
" + "Due to the extreme rarity of star shinies (1 in 6 million), " + "the filters here will not allow you to run from them. " + "If you get a star shiny, catch it and cherish it." + : + "Overrides:
" + "The game language must be properly set to read " + STRING_POKEMON + " names.
" + "If more than one override applies, the last one will be chosen.", + LockMode::UNLOCK_WHILE_RUNNING + ) + , rare_stars(p_rare_stars) +{} +std::vector> EncounterFilterTable::copy_snapshot() const{ + return EditableTableOption::copy_snapshot(); +} +std::vector EncounterFilterTable::make_header() const{ + return std::vector{ + STRING_POKEMON, + "Shininess", + "Action", + STRING_POKEBALL, + "Ball Limit", + }; +} +std::unique_ptr EncounterFilterTable::make_row(){ + return std::unique_ptr(new EncounterFilterOverride(*this)); +} + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.h b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.h index ee96fe6774..3db7a717c2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOverride.h @@ -1,65 +1,65 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterOverride_H -#define PokemonAutomation_PokemonSwSh_EncounterFilterOverride_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/EditableTableOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" -#include "PokemonSwSh_EncounterFilterEnums.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -struct EncounterActionFull{ - EncounterAction action; - std::string pokeball_slug; - uint16_t ball_limit = 999; -}; - - -class EncounterFilterOverride : public EditableTableRow, private ConfigOption::Listener{ -public: - ~EncounterFilterOverride(); - EncounterFilterOverride(EditableTableOption& parent_table); - virtual void load_json(const JsonValue& json) override; - virtual std::unique_ptr clone() const override; - - virtual void on_config_value_changed(void* object) override; - -public: - StringSelectCell pokemon; - ShinyFilterCell shininess; - EncounterActionCell action; - PokemonBallSelectCell pokeball; - SimpleIntegerCell ball_limit; -}; - - -// Cannot use "EditableTableOption_t<>" since the row class takes an extra -// parameter. -class EncounterFilterTable : public EditableTableOption{ -public: - EncounterFilterTable(bool rare_stars); - std::vector> copy_snapshot() const; - virtual std::vector make_header() const override; - virtual std::unique_ptr make_row() override; - -public: - const bool rare_stars; -}; - - - - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterOverride_H +#define PokemonAutomation_PokemonSwSh_EncounterFilterOverride_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/EditableTableOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" +#include "PokemonSwSh_EncounterFilterEnums.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +struct EncounterActionFull{ + EncounterAction action; + std::string pokeball_slug; + uint16_t ball_limit = 999; +}; + + +class EncounterFilterOverride : public EditableTableRow, private ConfigOption::Listener{ +public: + ~EncounterFilterOverride(); + EncounterFilterOverride(EditableTableOption& parent_table); + virtual void load_json(const JsonValue& json) override; + virtual std::unique_ptr clone() const override; + + virtual void on_config_value_changed(void* object) override; + +public: + StringSelectCell pokemon; + ShinyFilterCell shininess; + EncounterActionCell action; + PokemonBallSelectCell pokeball; + SimpleIntegerCell ball_limit; +}; + + +// Cannot use "EditableTableOption_t<>" since the row class takes an extra +// parameter. +class EncounterFilterTable : public EditableTableOption{ +public: + EncounterFilterTable(bool rare_stars); + std::vector> copy_snapshot() const; + virtual std::vector make_header() const override; + virtual std::unique_ptr make_row() override; + +public: + const bool rare_stars; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.cpp b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.cpp index 2bebcd3c66..895d85544d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.cpp @@ -1,103 +1,103 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Qt/NoWheelComboBox.h" -#include "PokemonSwSh_EncounterFilterEnums.h" -#include "PokemonSwSh_EncounterFilterWidget.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -#if 0 -EncounterFilterWidget::EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value) - : QWidget(&parent) - , ConfigWidget(value, *this) - , m_value(value) -{ - QVBoxLayout* layout = new QVBoxLayout(this); - layout->setContentsMargins(0, 0, 0, 0); -// QLabel* text = new QLabel(value.label(), this); -// layout->addWidget(text); - - { -// QWidget* widget = new QWidget(this); - - QHBoxLayout* hbox = new QHBoxLayout(); - layout->addLayout(hbox); - hbox->addWidget(new QLabel("Stop on:")); - - m_shininess = new NoWheelComboBox(this); - hbox->addWidget(m_shininess); - if (m_value.m_rare_stars){ - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANYTHING])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANY_SHINY])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::STAR_ONLY])); - }else{ - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANYTHING])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::NOT_SHINY])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANY_SHINY])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::STAR_ONLY])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::SQUARE_ONLY])); - m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::NOTHING])); - } - ShinyFilter current = m_value.m_shiny_filter_current; - for (int c = 0; c < m_shininess->count(); c++){ - if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ - m_shininess->setCurrentIndex(c); - break; - } - } - connect( - m_shininess, static_cast(&QComboBox::currentIndexChanged), - this, [this](int index){ - if (index < 0){ - return; - } - - std::string text = m_shininess->itemText(index).toStdString(); - auto iter = ShinyFilter_MAP.find(text); - if (iter == ShinyFilter_MAP.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid option: " + text); - } - m_value.m_shiny_filter_current = iter->second; - } - ); - } - - if (m_value.m_enable_overrides){ - layout->addSpacing(5); - m_table = value.m_table.make_QtWidget(*this); - layout->addWidget(&m_table->widget()); - } -} -void EncounterFilterWidget::update_value(){ - ShinyFilter current = m_value.m_shiny_filter_current; - for (int c = 0; c < m_shininess->count(); c++){ - if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ - m_shininess->setCurrentIndex(c); - break; - } - } -} -void EncounterFilterWidget::update_visibility(){ - ConfigWidget::update_visibility(); - if (m_table){ - m_table->update_visibility(); - } -} -#endif - - - -} -} -} +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Qt/NoWheelComboBox.h" +#include "PokemonSwSh_EncounterFilterEnums.h" +#include "PokemonSwSh_EncounterFilterWidget.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +#if 0 +EncounterFilterWidget::EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value) + : QWidget(&parent) + , ConfigWidget(value, *this) + , m_value(value) +{ + QVBoxLayout* layout = new QVBoxLayout(this); + layout->setContentsMargins(0, 0, 0, 0); +// QLabel* text = new QLabel(value.label(), this); +// layout->addWidget(text); + + { +// QWidget* widget = new QWidget(this); + + QHBoxLayout* hbox = new QHBoxLayout(); + layout->addLayout(hbox); + hbox->addWidget(new QLabel("Stop on:")); + + m_shininess = new NoWheelComboBox(this); + hbox->addWidget(m_shininess); + if (m_value.m_rare_stars){ + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANYTHING])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANY_SHINY])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::STAR_ONLY])); + }else{ + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANYTHING])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::NOT_SHINY])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::ANY_SHINY])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::STAR_ONLY])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::SQUARE_ONLY])); + m_shininess->addItem(QString::fromStdString(ShinyFilter_NAMES[(int)ShinyFilter::NOTHING])); + } + ShinyFilter current = m_value.m_shiny_filter_current; + for (int c = 0; c < m_shininess->count(); c++){ + if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ + m_shininess->setCurrentIndex(c); + break; + } + } + connect( + m_shininess, static_cast(&QComboBox::currentIndexChanged), + this, [this](int index){ + if (index < 0){ + return; + } + + std::string text = m_shininess->itemText(index).toStdString(); + auto iter = ShinyFilter_MAP.find(text); + if (iter == ShinyFilter_MAP.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid option: " + text); + } + m_value.m_shiny_filter_current = iter->second; + } + ); + } + + if (m_value.m_enable_overrides){ + layout->addSpacing(5); + m_table = value.m_table.make_QtWidget(*this); + layout->addWidget(&m_table->widget()); + } +} +void EncounterFilterWidget::update_value(){ + ShinyFilter current = m_value.m_shiny_filter_current; + for (int c = 0; c < m_shininess->count(); c++){ + if (m_shininess->itemText(c).toStdString() == ShinyFilter_NAMES[(int)current]){ + m_shininess->setCurrentIndex(c); + break; + } + } +} +void EncounterFilterWidget::update_visibility(){ + ConfigWidget::update_visibility(); + if (m_table){ + m_table->update_visibility(); + } +} +#endif + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.h b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.h index 37d3ed977a..51aacc4125 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterWidget.h @@ -1,42 +1,42 @@ -/* Encounter Filter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterWidget_H -#define PokemonAutomation_PokemonSwSh_EncounterFilterWidget_H - -#include -#include "Common/Qt/Options/ConfigWidget.h" -#include "PokemonSwSh_EncounterFilterOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - - -#if 0 -class EncounterFilterWidget : public QWidget, public ConfigWidget{ -public: - EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value); - - virtual void update_value() override; - virtual void update_visibility() override; - -private: - EncounterFilterOption& m_value; - - QComboBox* m_shininess = nullptr; - ConfigWidget* m_table = nullptr; -}; -#endif - - - -} -} -} -#endif +/* Encounter Filter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterFilterWidget_H +#define PokemonAutomation_PokemonSwSh_EncounterFilterWidget_H + +#include +#include "Common/Qt/Options/ConfigWidget.h" +#include "PokemonSwSh_EncounterFilterOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + + +#if 0 +class EncounterFilterWidget : public QWidget, public ConfigWidget{ +public: + EncounterFilterWidget(QWidget& parent, EncounterFilterOption& value); + + virtual void update_value() override; + virtual void update_visibility() override; + +private: + EncounterFilterOption& m_value; + + QComboBox* m_shininess = nullptr; + ConfigWidget* m_table = nullptr; +}; +#endif + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.cpp b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.cpp index eed0a07949..8b7cb5b44c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.cpp @@ -1,45 +1,45 @@ -/* Auto-Host Notification - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_AutoHostNotification.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -AutoHostNotificationOption::AutoHostNotificationOption(std::string label, bool max_lair) - : GroupOption( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_DISABLED - ) - , DESCRIPTION( - "Description:", - LockMode::LOCK_WHILE_RUNNING, - "", - max_lair - ? "Auto-Hosting Lugia\nCode: Random" - : "Den 123: Square Shiny\nIGN: Kimberly\nCode: 1234-5678\nFC: SW-1234-5678-9012" - ) - , SHOW_STATS( - "Show Stats: Show program stats for this session.", - LockMode::LOCK_WHILE_RUNNING, - true - ) -// , SCREENSHOT("Notification Screenshot:
Attach screenshot of the den to notifications.") - , NOTIFICATION("Hosting Announcements", true, false, ImageAttachmentMode::JPG, {"LiveHost"}) -{ - PA_ADD_OPTION(DESCRIPTION); - PA_ADD_OPTION(SHOW_STATS); -// PA_ADD_OPTION(SCREENSHOT); -} - - - -} -} -} +/* Auto-Host Notification + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_AutoHostNotification.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +AutoHostNotificationOption::AutoHostNotificationOption(std::string label, bool max_lair) + : GroupOption( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_DISABLED + ) + , DESCRIPTION( + "Description:", + LockMode::LOCK_WHILE_RUNNING, + "", + max_lair + ? "Auto-Hosting Lugia\nCode: Random" + : "Den 123: Square Shiny\nIGN: Kimberly\nCode: 1234-5678\nFC: SW-1234-5678-9012" + ) + , SHOW_STATS( + "Show Stats: Show program stats for this session.", + LockMode::LOCK_WHILE_RUNNING, + true + ) +// , SCREENSHOT("Notification Screenshot:
Attach screenshot of the den to notifications.") + , NOTIFICATION("Hosting Announcements", true, false, ImageAttachmentMode::JPG, {"LiveHost"}) +{ + PA_ADD_OPTION(DESCRIPTION); + PA_ADD_OPTION(SHOW_STATS); +// PA_ADD_OPTION(SCREENSHOT); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h index 48c6c752bf..abba03501f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h @@ -1,39 +1,39 @@ -/* Auto-Host Notification - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_AutoHostNotification_H -#define PokemonAutomation_PokemonSwSh_AutoHostNotification_H - -#include "Common/Cpp/Options/GroupOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TextEditOption.h" -//#include "CommonFramework/Options/ScreenshotFormatOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -//#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class AutoHostNotificationOption : public GroupOption{ -public: - AutoHostNotificationOption(std::string label, bool max_lair); - - TextEditOption DESCRIPTION; - BooleanCheckBoxOption SHOW_STATS; -// ScreenshotOption SCREENSHOT; - - EventNotificationOption NOTIFICATION; -}; - - - - -} -} -} -#endif +/* Auto-Host Notification + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_AutoHostNotification_H +#define PokemonAutomation_PokemonSwSh_AutoHostNotification_H + +#include "Common/Cpp/Options/GroupOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TextEditOption.h" +//#include "CommonFramework/Options/ScreenshotFormatOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +//#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class AutoHostNotificationOption : public GroupOption{ +public: + AutoHostNotificationOption(std::string label, bool max_lair); + + TextEditOption DESCRIPTION; + BooleanCheckBoxOption SHOW_STATS; +// ScreenshotOption SCREENSHOT; + + EventNotificationOption NOTIFICATION; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp index 07ab046b64..084984dca6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.cpp @@ -1,76 +1,76 @@ -/* Pokemon Ball Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokeballNames.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" -#include "PokemonSwSh_BallSelectOption.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -StringSelectDatabase make_all_balls_database(){ - StringSelectDatabase ret; - for (const auto& slug : POKEBALL_SLUGS()){ -// cout << "slug = " << slug << endl; - const PokeballNames& data = get_pokeball_name(slug); - const SpriteDatabase::Sprite* sprite = ALL_POKEBALL_SPRITES().get_nothrow(slug); - if (sprite == nullptr){ - ret.add_entry(StringSelectEntry(slug, data.display_name())); - global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); - }else{ - ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); - } - } - return ret; -} -const StringSelectDatabase& ALL_BALLS_SELECT_DATABASE(){ - static StringSelectDatabase database = make_all_balls_database(); - return database; -} - - - - -PokemonBallSelectCell::PokemonBallSelectCell( - const std::string& default_slug -) - : StringSelectCell( - ALL_BALLS_SELECT_DATABASE(), - LockMode::LOCK_WHILE_RUNNING, - default_slug - ) -{} - - - -PokemonBallSelectOption::PokemonBallSelectOption( - std::string label, - LockMode lock_while_running, - const std::string& default_slug -) - : StringSelectOption( - std::move(label), - ALL_BALLS_SELECT_DATABASE(), - lock_while_running, - default_slug - ) -{} - - - - -} -} -} +/* Pokemon Ball Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokeballNames.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h" +#include "PokemonSwSh_BallSelectOption.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +StringSelectDatabase make_all_balls_database(){ + StringSelectDatabase ret; + for (const auto& slug : POKEBALL_SLUGS()){ +// cout << "slug = " << slug << endl; + const PokeballNames& data = get_pokeball_name(slug); + const SpriteDatabase::Sprite* sprite = ALL_POKEBALL_SPRITES().get_nothrow(slug); + if (sprite == nullptr){ + ret.add_entry(StringSelectEntry(slug, data.display_name())); + global_logger_tagged().log("Missing sprite for: " + slug, COLOR_RED); + }else{ + ret.add_entry(StringSelectEntry(slug, data.display_name(), sprite->icon)); + } + } + return ret; +} +const StringSelectDatabase& ALL_BALLS_SELECT_DATABASE(){ + static StringSelectDatabase database = make_all_balls_database(); + return database; +} + + + + +PokemonBallSelectCell::PokemonBallSelectCell( + const std::string& default_slug +) + : StringSelectCell( + ALL_BALLS_SELECT_DATABASE(), + LockMode::LOCK_WHILE_RUNNING, + default_slug + ) +{} + + + +PokemonBallSelectOption::PokemonBallSelectOption( + std::string label, + LockMode lock_while_running, + const std::string& default_slug +) + : StringSelectOption( + std::move(label), + ALL_BALLS_SELECT_DATABASE(), + lock_while_running, + default_slug + ) +{} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h index 6e1cecd12b..de87409f05 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h @@ -1,37 +1,37 @@ -/* Pokemon Ball Select - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_PokemonBallSelect_H -#define PokemonAutomation_PokemonSwSh_PokemonBallSelect_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class PokemonBallSelectCell : public StringSelectCell{ -public: - PokemonBallSelectCell(const std::string& default_slug = ""); -}; - - -class PokemonBallSelectOption : public StringSelectOption{ -public: - PokemonBallSelectOption( - std::string label, - LockMode lock_while_running, - const std::string& default_slug = "" - ); -}; - - -} -} -} -#endif +/* Pokemon Ball Select + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_PokemonBallSelect_H +#define PokemonAutomation_PokemonSwSh_PokemonBallSelect_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class PokemonBallSelectCell : public StringSelectCell{ +public: + PokemonBallSelectCell(const std::string& default_slug = ""); +}; + + +class PokemonBallSelectOption : public StringSelectOption{ +public: + PokemonBallSelectOption( + std::string label, + LockMode lock_while_running, + const std::string& default_slug = "" + ); +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_Catchability.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_Catchability.h index 328ed45d43..5c583f7da0 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_Catchability.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_Catchability.h @@ -1,47 +1,47 @@ -/* Catchability Selector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Catchability_H -#define PokemonAutomation_PokemonSwSh_Catchability_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -enum class Catchability{ - ALWAYS_CATCHABLE, - MAYBE_UNCATCHABLE, - ALWAYS_UNCATCHABLE, -}; - - -class CatchabilitySelectorOption : public EnumDropdownOption{ -public: - CatchabilitySelectorOption() - : EnumDropdownOption( - "" + Pokemon::STRING_POKEMON + " Catchability", - { - {Catchability::ALWAYS_CATCHABLE, "always", "Always Catchable"}, - {Catchability::MAYBE_UNCATCHABLE, "maybe", "Maybe Uncatchable"}, - {Catchability::ALWAYS_UNCATCHABLE, "never", "Never Catchable"}, - }, - LockMode::LOCK_WHILE_RUNNING, - Catchability::ALWAYS_CATCHABLE - ) - {} -}; - - - -} -} -} -#endif +/* Catchability Selector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Catchability_H +#define PokemonAutomation_PokemonSwSh_Catchability_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +enum class Catchability{ + ALWAYS_CATCHABLE, + MAYBE_UNCATCHABLE, + ALWAYS_UNCATCHABLE, +}; + + +class CatchabilitySelectorOption : public EnumDropdownOption{ +public: + CatchabilitySelectorOption() + : EnumDropdownOption( + "" + Pokemon::STRING_POKEMON + " Catchability", + { + {Catchability::ALWAYS_CATCHABLE, "always", "Always Catchable"}, + {Catchability::MAYBE_UNCATCHABLE, "maybe", "Maybe Uncatchable"}, + {Catchability::ALWAYS_UNCATCHABLE, "never", "Never Catchable"}, + }, + LockMode::LOCK_WHILE_RUNNING, + Catchability::ALWAYS_CATCHABLE + ) + {} +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.cpp b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.cpp index 1b9edfff5b..6bb6df5261 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.cpp @@ -1,114 +1,114 @@ -/* Cram-o-matic Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_CramomaticTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const EnumDropdownDatabase& BallType_Database(){ - static const EnumDropdownDatabase database({ - {CramomaticBallType::Poke, "poke", "Poké Ball"}, - {CramomaticBallType::Great, "great", "Great Ball"}, - {CramomaticBallType::Shop1, "shop1", "Shop 1 (Ultra Ball, Net Ball, Dusk Ball, Premier Ball)"}, - {CramomaticBallType::Shop2, "shop2", "Shop 2 (Repeat Ball, Dive Ball, Quick Ball, Nest Ball, Heal Ball, Timer Ball, Luxury Ball)"}, - {CramomaticBallType::Apricorn, "apricorn", "Apricorn (Level Ball, Lure Ball, Moon Ball, Friend Ball, Love Ball, Fast Ball, Heavy Ball)"}, - {CramomaticBallType::Safari, "safari", "Safari Ball"}, - {CramomaticBallType::Sport, "sport", "Sport Ball (uses two different Apricorn colors)"}, - }); - return database; -} - - - -CramomaticRow::CramomaticRow(EditableTableOption& parent_table) - : EditableTableRow(parent_table) - , ball_type(BallType_Database(), LockMode::LOCK_WHILE_RUNNING, CramomaticBallType::Apricorn) - , is_bonus(LockMode::LOCK_WHILE_RUNNING, false) - , priority(LockMode::LOCK_WHILE_RUNNING, 0) -{ - PA_ADD_OPTION(ball_type); - PA_ADD_OPTION(is_bonus); - PA_ADD_OPTION(priority); -} - -CramomaticRow::CramomaticRow(EditableTableOption& parent_table, CramomaticBallType p_ball_type, bool p_is_bonus, uint16_t p_priority) - : CramomaticRow(parent_table) -{ - ball_type.set(p_ball_type); - is_bonus = p_is_bonus; - priority.set(p_priority); -} - -std::unique_ptr CramomaticRow::clone() const{ - std::unique_ptr ret(new CramomaticRow(parent())); - ret->ball_type.set_value(ball_type.current_value()); - ret->is_bonus = is_bonus.current_value(); - ret->priority.set(priority.current_value()); - return ret; -} - - -CramomaticTable::CramomaticTable(std::string label) - : EditableTableOption_t( - std::move(label), - LockMode::LOCK_WHILE_RUNNING, - make_defaults() - ) -{} - - -std::vector CramomaticTable::selected_balls() const{ - std::vector> table = copy_snapshot(); - std::vector selections; - for (const std::unique_ptr& row : table){ - CramomaticSelection selection; - selection.ball_type = CramomaticBallType(row->ball_type.current_value()); - selection.is_bonus = row->is_bonus.current_value(); - selection.priority = row->priority.current_value(); - - selections.emplace_back(selection); - } - return selections; -} - - - - -std::vector CramomaticTable::make_header() const{ - return std::vector{ - "Ball", "Only Bonus", "Priority", - }; -} - -std::vector> CramomaticTable::make_defaults(){ - std::vector> ret; - ret.emplace_back(std::make_unique(*this, CramomaticBallType::Apricorn, true, (uint16_t)1)); - ret.emplace_back(std::make_unique(*this, CramomaticBallType::Apricorn, false, (uint16_t)0)); - return ret; -} - - - - - - - - - - - - - - - - - -} -} -} +/* Cram-o-matic Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_CramomaticTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const EnumDropdownDatabase& BallType_Database(){ + static const EnumDropdownDatabase database({ + {CramomaticBallType::Poke, "poke", "Poké Ball"}, + {CramomaticBallType::Great, "great", "Great Ball"}, + {CramomaticBallType::Shop1, "shop1", "Shop 1 (Ultra Ball, Net Ball, Dusk Ball, Premier Ball)"}, + {CramomaticBallType::Shop2, "shop2", "Shop 2 (Repeat Ball, Dive Ball, Quick Ball, Nest Ball, Heal Ball, Timer Ball, Luxury Ball)"}, + {CramomaticBallType::Apricorn, "apricorn", "Apricorn (Level Ball, Lure Ball, Moon Ball, Friend Ball, Love Ball, Fast Ball, Heavy Ball)"}, + {CramomaticBallType::Safari, "safari", "Safari Ball"}, + {CramomaticBallType::Sport, "sport", "Sport Ball (uses two different Apricorn colors)"}, + }); + return database; +} + + + +CramomaticRow::CramomaticRow(EditableTableOption& parent_table) + : EditableTableRow(parent_table) + , ball_type(BallType_Database(), LockMode::LOCK_WHILE_RUNNING, CramomaticBallType::Apricorn) + , is_bonus(LockMode::LOCK_WHILE_RUNNING, false) + , priority(LockMode::LOCK_WHILE_RUNNING, 0) +{ + PA_ADD_OPTION(ball_type); + PA_ADD_OPTION(is_bonus); + PA_ADD_OPTION(priority); +} + +CramomaticRow::CramomaticRow(EditableTableOption& parent_table, CramomaticBallType p_ball_type, bool p_is_bonus, uint16_t p_priority) + : CramomaticRow(parent_table) +{ + ball_type.set(p_ball_type); + is_bonus = p_is_bonus; + priority.set(p_priority); +} + +std::unique_ptr CramomaticRow::clone() const{ + std::unique_ptr ret(new CramomaticRow(parent())); + ret->ball_type.set_value(ball_type.current_value()); + ret->is_bonus = is_bonus.current_value(); + ret->priority.set(priority.current_value()); + return ret; +} + + +CramomaticTable::CramomaticTable(std::string label) + : EditableTableOption_t( + std::move(label), + LockMode::LOCK_WHILE_RUNNING, + make_defaults() + ) +{} + + +std::vector CramomaticTable::selected_balls() const{ + std::vector> table = copy_snapshot(); + std::vector selections; + for (const std::unique_ptr& row : table){ + CramomaticSelection selection; + selection.ball_type = CramomaticBallType(row->ball_type.current_value()); + selection.is_bonus = row->is_bonus.current_value(); + selection.priority = row->priority.current_value(); + + selections.emplace_back(selection); + } + return selections; +} + + + + +std::vector CramomaticTable::make_header() const{ + return std::vector{ + "Ball", "Only Bonus", "Priority", + }; +} + +std::vector> CramomaticTable::make_defaults(){ + std::vector> ret; + ret.emplace_back(std::make_unique(*this, CramomaticBallType::Apricorn, true, (uint16_t)1)); + ret.emplace_back(std::make_unique(*this, CramomaticBallType::Apricorn, false, (uint16_t)0)); + return ret; +} + + + + + + + + + + + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h index 236d9e5465..8e20b2821e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h @@ -1,69 +1,69 @@ -/* Cram-o-matic Table - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_CramomaticTable_H -#define PokemonAutomation_PokemonSwSh_CramomaticTable_H - -#include "Common/Cpp/Options/EditableTableOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -enum class CramomaticBallType -{ - Poke, - Great, - Shop1, - Shop2, - Apricorn, - Safari, - Sport -}; - -struct CramomaticSelection -{ - CramomaticBallType ball_type; - bool is_bonus; - uint16_t priority; -}; - -class CramomaticRow : public EditableTableRow{ -public: - CramomaticRow(EditableTableOption& parent_table); - CramomaticRow(EditableTableOption& parent_table, CramomaticBallType p_ball_type, bool p_is_bonus, uint16_t p_priority); - virtual std::unique_ptr clone() const; - -public: - EnumDropdownCell ball_type; - BooleanCheckBoxCell is_bonus; - SimpleIntegerCell priority; -}; - - - -class CramomaticTable : public EditableTableOption_t{ -public: - CramomaticTable(std::string label); - - std::vector selected_balls() const; - - virtual std::vector make_header() const; - - std::vector> make_defaults(); -}; - - - - - -} -} -} -#endif +/* Cram-o-matic Table + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_CramomaticTable_H +#define PokemonAutomation_PokemonSwSh_CramomaticTable_H + +#include "Common/Cpp/Options/EditableTableOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +enum class CramomaticBallType +{ + Poke, + Great, + Shop1, + Shop2, + Apricorn, + Safari, + Sport +}; + +struct CramomaticSelection +{ + CramomaticBallType ball_type; + bool is_bonus; + uint16_t priority; +}; + +class CramomaticRow : public EditableTableRow{ +public: + CramomaticRow(EditableTableOption& parent_table); + CramomaticRow(EditableTableOption& parent_table, CramomaticBallType p_ball_type, bool p_is_bonus, uint16_t p_priority); + virtual std::unique_ptr clone() const; + +public: + EnumDropdownCell ball_type; + BooleanCheckBoxCell is_bonus; + SimpleIntegerCell priority; +}; + + + +class CramomaticTable : public EditableTableOption_t{ +public: + CramomaticTable(std::string label); + + std::vector selected_balls() const; + + virtual std::vector make_header() const; + + std::vector> make_defaults(); +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.cpp b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.cpp index e2552534c7..20edcda81b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.cpp @@ -1,86 +1,86 @@ -/* Date Toucher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Json/JsonValue.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateToucher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -TimeRollbackHoursOption::TimeRollbackHoursOption() - : SimpleIntegerOption( - "Time Rollback (in hours):
Periodically roll back the time to keep the weather the same. If set to zero, this feature is disabled.", - LockMode::LOCK_WHILE_RUNNING, - 1, 0, 11 - ) -{} - - - - - -TouchDateIntervalOption::TouchDateIntervalOption() - : m_hours( - "Rollover Prevention:
Prevent a date-skip by touching the date every this many hours. If set to zero, this feature is disabled.", - LockMode::LOCK_WHILE_RUNNING, - 4, 0, 11 - ) -{ - reset_state(); -} - - -void TouchDateIntervalOption::load_json(const JsonValue& json){ - m_hours.load_json(json); -} -JsonValue TouchDateIntervalOption::to_json() const{ - return m_hours.to_json(); -} -std::string TouchDateIntervalOption::check_validity() const{ - return m_hours.check_validity(); -} -void TouchDateIntervalOption::restore_defaults(){ - m_hours.restore_defaults(); -} -void TouchDateIntervalOption::reset_state(){ - WriteSpinLock lg(m_lock); - m_last_touch = WallClock::min(); -} -ConfigWidget* TouchDateIntervalOption::make_QtWidget(QWidget& parent){ - return m_hours.make_QtWidget(parent); -} - - -bool TouchDateIntervalOption::ok_to_touch_now(){ - uint8_t hours = m_hours; - if (hours == 0){ - return false; - } - auto now = current_time(); - WriteSpinLock lg(m_lock); - if (now < m_last_touch + std::chrono::hours(hours)){ - return false; - } - m_last_touch = now; - return true; -} -void TouchDateIntervalOption::touch_now_from_home_if_needed(ConsoleHandle& console, ProControllerContext& context){ - if (!ok_to_touch_now()){ - return; - } - touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); -} - - - -} -} -} - +/* Date Toucher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Json/JsonValue.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateToucher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +TimeRollbackHoursOption::TimeRollbackHoursOption() + : SimpleIntegerOption( + "Time Rollback (in hours):
Periodically roll back the time to keep the weather the same. If set to zero, this feature is disabled.", + LockMode::LOCK_WHILE_RUNNING, + 1, 0, 11 + ) +{} + + + + + +TouchDateIntervalOption::TouchDateIntervalOption() + : m_hours( + "Rollover Prevention:
Prevent a date-skip by touching the date every this many hours. If set to zero, this feature is disabled.", + LockMode::LOCK_WHILE_RUNNING, + 4, 0, 11 + ) +{ + reset_state(); +} + + +void TouchDateIntervalOption::load_json(const JsonValue& json){ + m_hours.load_json(json); +} +JsonValue TouchDateIntervalOption::to_json() const{ + return m_hours.to_json(); +} +std::string TouchDateIntervalOption::check_validity() const{ + return m_hours.check_validity(); +} +void TouchDateIntervalOption::restore_defaults(){ + m_hours.restore_defaults(); +} +void TouchDateIntervalOption::reset_state(){ + WriteSpinLock lg(m_lock); + m_last_touch = WallClock::min(); +} +ConfigWidget* TouchDateIntervalOption::make_QtWidget(QWidget& parent){ + return m_hours.make_QtWidget(parent); +} + + +bool TouchDateIntervalOption::ok_to_touch_now(){ + uint8_t hours = m_hours; + if (hours == 0){ + return false; + } + auto now = current_time(); + WriteSpinLock lg(m_lock); + if (now < m_last_touch + std::chrono::hours(hours)){ + return false; + } + m_last_touch = now; + return true; +} +void TouchDateIntervalOption::touch_now_from_home_if_needed(ConsoleHandle& console, ProControllerContext& context){ + if (!ok_to_touch_now()){ + return; + } + touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.h index b0b9e16f68..5657539207 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_DateToucher.h @@ -1,55 +1,55 @@ -/* Date Toucher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_DateToucher_H -#define PokemonAutomation_DateToucher_H - -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class TimeRollbackHoursOption : public SimpleIntegerOption{ -public: - TimeRollbackHoursOption(); -}; - -class TouchDateIntervalOption : public ConfigOption{ -public: - TouchDateIntervalOption(); - - virtual void load_json(const JsonValue& json) override; - virtual JsonValue to_json() const override; - - // Returns error message if invalid. Otherwise returns empty string. - virtual std::string check_validity() const override; - - virtual void restore_defaults() override; - virtual void reset_state() override final; - - virtual ConfigWidget* make_QtWidget(QWidget& parent) override; - - bool ok_to_touch_now(); - void touch_now_from_home_if_needed(ConsoleHandle& console, ProControllerContext& context); - -private: - SimpleIntegerOption m_hours; - - SpinLock m_lock; - WallClock m_last_touch; -}; - - - -} -} -} -#endif +/* Date Toucher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_DateToucher_H +#define PokemonAutomation_DateToucher_H + +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class TimeRollbackHoursOption : public SimpleIntegerOption{ +public: + TimeRollbackHoursOption(); +}; + +class TouchDateIntervalOption : public ConfigOption{ +public: + TouchDateIntervalOption(); + + virtual void load_json(const JsonValue& json) override; + virtual JsonValue to_json() const override; + + // Returns error message if invalid. Otherwise returns empty string. + virtual std::string check_validity() const override; + + virtual void restore_defaults() override; + virtual void reset_state() override final; + + virtual ConfigWidget* make_QtWidget(QWidget& parent) override; + + bool ok_to_touch_now(); + void touch_now_from_home_if_needed(ConsoleHandle& console, ProControllerContext& context); + +private: + SimpleIntegerOption m_hours; + + SpinLock m_lock; + WallClock m_last_touch; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.cpp b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.cpp index b3d0817aa0..ab3de89c2d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.cpp @@ -1,41 +1,41 @@ -/* Egg Step Count Dropdown - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Pokemon/Resources/Pokemon_EggSteps.h" -#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" -#include "PokemonSwSh_EggStepOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -const Pokemon::EggStepDatabase& EGGSTEP_DATABASE(){ - static Pokemon::EggStepDatabase database("PokemonSwSh/EggSteps.json", &ALL_POKEMON_SPRITES()); - return database; -} - - - -EggStepCountOption::EggStepCountOption() - : StringSelectOption( - "Step Count:", - EGGSTEP_DATABASE().database(), - LockMode::LOCK_WHILE_RUNNING, - "grookey" - ) -{} - -EggStepCountOption::operator uint16_t() const{ - return (uint16_t)EGGSTEP_DATABASE().step_count(this->slug()); -} - - - -} -} -} +/* Egg Step Count Dropdown + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Pokemon/Resources/Pokemon_EggSteps.h" +#include "PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h" +#include "PokemonSwSh_EggStepOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +const Pokemon::EggStepDatabase& EGGSTEP_DATABASE(){ + static Pokemon::EggStepDatabase database("PokemonSwSh/EggSteps.json", &ALL_POKEMON_SPRITES()); + return database; +} + + + +EggStepCountOption::EggStepCountOption() + : StringSelectOption( + "Step Count:", + EGGSTEP_DATABASE().database(), + LockMode::LOCK_WHILE_RUNNING, + "grookey" + ) +{} + +EggStepCountOption::operator uint16_t() const{ + return (uint16_t)EGGSTEP_DATABASE().step_count(this->slug()); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.h index 6ad1182465..f6bb93c0da 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EggStepOption.h @@ -1,33 +1,33 @@ -/* Egg Step Count Dropdown - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggStepOption_H -#define PokemonAutomation_PokemonSwSh_EggStepOption_H - -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - - -class EggStepCountOption : public StringSelectOption{ -public: - EggStepCountOption(); - - operator uint16_t() const; -}; - - - - -} -} -} -#endif - +/* Egg Step Count Dropdown + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggStepOption_H +#define PokemonAutomation_PokemonSwSh_EggStepOption_H + +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + + +class EggStepCountOption : public StringSelectOption{ +public: + EggStepCountOption(); + + operator uint16_t() const; +}; + + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h index dc5f8e9bbf..5d34ae196c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h @@ -1,72 +1,72 @@ -/* Encounter Bot Common - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterBotCommon_H -#define PokemonAutomation_PokemonSwSh_EncounterBotCommon_H - -#include "Common/Cpp/Options/BatchOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationOption.h" -#include "EncounterFilter/PokemonSwSh_EncounterFilterOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class EncounterBotCommonOptions : public BatchOption{ -public: - EncounterBotCommonOptions(bool rare_stars, bool enable_overrides) - : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) - , FILTER(rare_stars, enable_overrides) - , VIDEO_ON_SHINY( - "Video Capture:
Take a video of the encounter if it is shiny.", - LockMode::UNLOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , NOTIFICATION_CATCH_SUCCESS( - "Catch Success", - true, false, - {"Notifs"} - ) - , NOTIFICATION_CATCH_FAILED( - "Catch Failed", - true, true, - {"Notifs"} - ) - { - PA_ADD_OPTION(FILTER); - PA_ADD_OPTION(VIDEO_ON_SHINY); - } - - EncounterFilterOption2 FILTER; - BooleanCheckBoxOption VIDEO_ON_SHINY; - - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; -}; - - - - -} -} -} -#endif +/* Encounter Bot Common + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterBotCommon_H +#define PokemonAutomation_PokemonSwSh_EncounterBotCommon_H + +#include "Common/Cpp/Options/BatchOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationOption.h" +#include "EncounterFilter/PokemonSwSh_EncounterFilterOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class EncounterBotCommonOptions : public BatchOption{ +public: + EncounterBotCommonOptions(bool rare_stars, bool enable_overrides) + : BatchOption(LockMode::UNLOCK_WHILE_RUNNING) + , FILTER(rare_stars, enable_overrides) + , VIDEO_ON_SHINY( + "Video Capture:
Take a video of the encounter if it is shiny.", + LockMode::UNLOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , NOTIFICATION_CATCH_SUCCESS( + "Catch Success", + true, false, + {"Notifs"} + ) + , NOTIFICATION_CATCH_FAILED( + "Catch Failed", + true, true, + {"Notifs"} + ) + { + PA_ADD_OPTION(FILTER); + PA_ADD_OPTION(VIDEO_ON_SHINY); + } + + EncounterFilterOption2 FILTER; + BooleanCheckBoxOption VIDEO_ON_SHINY; + + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_RegiSelector.h b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_RegiSelector.h index 1b33bc63c3..76e01c0932 100644 --- a/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_RegiSelector.h +++ b/SerialPrograms/Source/PokemonSwSh/Options/PokemonSwSh_RegiSelector.h @@ -1,49 +1,49 @@ -/* Regi Selector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_RegiSelector_H -#define PokemonAutomation_PokemonSwSh_RegiSelector_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -enum class RegiGolem{ - Regirock, - Regice, - Registeel, - Regieleki, - Regidrago, -}; - -class RegiSelectorOption : public EnumDropdownOption{ -public: - RegiSelectorOption() - : EnumDropdownOption( - "Name of Regi:", - { - {RegiGolem::Regirock, "regirock", "Regirock"}, - {RegiGolem::Regice, "regice", "Regice"}, - {RegiGolem::Registeel, "registeel", "Registeel"}, - {RegiGolem::Regieleki, "regieleki", "Regieleki"}, - {RegiGolem::Regidrago, "regidrago", "Regidrago"}, - }, - LockMode::LOCK_WHILE_RUNNING, - RegiGolem::Registeel - ) - {} -}; - - - - -} -} -} -#endif +/* Regi Selector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_RegiSelector_H +#define PokemonAutomation_PokemonSwSh_RegiSelector_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +enum class RegiGolem{ + Regirock, + Regice, + Registeel, + Regieleki, + Regidrago, +}; + +class RegiSelectorOption : public EnumDropdownOption{ +public: + RegiSelectorOption() + : EnumDropdownOption( + "Name of Regi:", + { + {RegiGolem::Regirock, "regirock", "Regirock"}, + {RegiGolem::Regice, "regice", "Regice"}, + {RegiGolem::Registeel, "registeel", "Registeel"}, + {RegiGolem::Regieleki, "regieleki", "Regieleki"}, + {RegiGolem::Regidrago, "regidrago", "Regidrago"}, + }, + LockMode::LOCK_WHILE_RUNNING, + RegiGolem::Registeel + ) + {} +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.cpp index f329125da6..ba7537fab3 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.cpp @@ -1,461 +1,461 @@ -/* PkmnLib Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh_PkmnLib_Battle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -void calc_damage_range( - uint8_t power, - uint8_t level, uint16_t attack, uint16_t defense, double modifier, - uint16_t& lower_bound, uint16_t& upper_bound -){ - // this calculates the damage ranges for an attack - // every division is integer division except for the attack and defense ratio so no need for casting - double attack_defense = (double)attack / (double)defense; - - int base_damage = (int)((((2 * (int)level) / 5 + 2) * power * (attack_defense)) / 50 + 2); - - // so, the modifier is usually just one, but we can calculate it before hand based on targets, weather, etc. - int bottom_base = base_damage * 85 / 100; - - // BUG: there is currently a bug when calculating damage - // due to all of the integer math that happens, the "modifier" - // is actually often calculated one step at a time - // so, the upper-end might be a little high in some cases - - // update the output "inputs" - lower_bound = (uint16_t)(bottom_base * modifier); - upper_bound = (uint16_t)(base_damage * modifier); - // done -} - -double ability_damage_multiplier(const Pokemon& attacker, const Pokemon& defender, const Move& move){ - - // final multiplier that we're going to modify - double multiplier = 1.0; - - const std::string& attacker_ability = attacker.ability(); - const std::string& defender_ability = defender.ability(); -// const std::string& move_name = attack_move.name(); - Type move_type = move.type(); - - do{ - if (attacker_ability == "mold-breaker") break; - if (attacker_ability == "turboblaze") break; - if (attacker_ability == "teravolt") break; - if (attacker_ability == "tinted-lens"){ - if (damage_multiplier(move_type, defender.type1(), defender.type2()) < 1.0){ - multiplier *= 2.0; - } - break; - } - - switch (move_type){ - case Type::ground: - if (defender_ability == "levitate"){ - if (move == "thousand-arrows"){ - multiplier = 1.0; - }else{ - multiplier = 0.0; - } - } - break; - - case Type::water: - if (defender_ability == "water-absorb" || - defender_ability == "storm-drain" || - defender_ability == "dry-skin" - ){ -// multiplier = -1.0; - multiplier = 0.0; - } - break; - - case Type::fire: - if (defender_ability == "flash-fire"){ -// multiplier = -1.0; - multiplier = 0.0; - }else if (defender_ability == "fluffy" || defender_ability == "dry-skin"){ - multiplier = 2.0; - }else if (defender_ability == "thick-fat" || defender_ability == "heatproof"){ - multiplier = 0.5; - } - break; - - case Type::grass: - if (defender_ability == "sap-sipper"){ -// multiplier = -1.0; - multiplier = 0.0; - } - break; - - case Type::electric: - if (defender_ability == "lightning-rod" || - defender_ability == "motor-drive" || - defender_ability == "volt-absorb" - ){ -// multiplier = -1.0; - multiplier = 0.0; - } - break; - - case Type::ice: - if (defender_ability == "thick-fat"){ - multiplier = 0.5; - } - break; - - default:; - } - }while (false); - - if (attacker_ability == "iron-fist"){ - static std::set MOVES{ - verify_move_slug("bullet-punch"), - verify_move_slug("comet-punch"), - verify_move_slug("dizzy-punch"), - verify_move_slug("double-iron-bash"), - verify_move_slug("drain-punch"), - verify_move_slug("dynamic-punch"), - verify_move_slug("fire-punch"), - verify_move_slug("focus-punch"), - verify_move_slug("hammer-arm"), - verify_move_slug("ice-hammer"), - verify_move_slug("ice-punch"), - verify_move_slug("mach-punch"), - verify_move_slug("mega-punch"), - verify_move_slug("meteor-mash"), - verify_move_slug("plasma-fists"), - verify_move_slug("power-up-punch"), - verify_move_slug("shadow-punch"), - verify_move_slug("sky-uppercut"), - verify_move_slug("surging-strikes"), - verify_move_slug("thunder-punch"), - verify_move_slug("wicked-blow"), - }; - if (MOVES.find(move.name()) != MOVES.end()){ - multiplier *= 1.2; - } - }else if (attacker_ability == "strong-jaw"){ - static std::set MOVES{ - verify_move_slug("bite"), - verify_move_slug("crunch"), - verify_move_slug("fire-fang"), - verify_move_slug("fishious-rend"), - verify_move_slug("hyper-fang"), - verify_move_slug("ice-fang"), - verify_move_slug("jaw-lock"), - verify_move_slug("poison-fang"), - verify_move_slug("psychic-fangs"), - verify_move_slug("thunder-fang"), - }; - if (MOVES.find(move.name()) != MOVES.end()){ - multiplier *= 1.5; - } - }else if (attacker_ability == "adaptability"){ - if (move_type == attacker.type1() || move_type == attacker.type2()){ - multiplier *= (4.0 / 3.0); - } - } - - return multiplier; -} - -double weather_damage_multiplier(Move& move, const Field& field){ - - double modifier = 1.0; - -// const std::string& attacker_ability = attacker.ability(); -// const std::string& defender_ability = defender.ability(); -// const std::string& move_name = move.name(); - Type move_type = move.type(); - - switch (field.weather()){ - case Weather::CLEAR: - if (move == "weather-ball"){ - move.set_type(Type::normal); - } - break; - case Weather::SUN: - if (move == "solar-beam"){ - modifier *= 2.0; - }else if (move == "thunder" || move == "hurricane"){ - modifier *= (0.5 / 0.7); - }else if (move == "weather-ball"){ - move.set_type(Type::fire); - modifier *= 2.0; - } - - if (move_type == Type::fire){ - modifier *= 1.5; - }else if (move_type == Type::water){ - modifier *= 0.5; - } - break; - case Weather::RAIN: - if (move == "solar-beam"){ - modifier *= 0.5; - }else if (move == "thunder" || move == "hurricane"){ - modifier *= (1.0 / 0.7); - }else if (move == "weather-ball"){ - move.set_type(Type::water); - modifier *= 2.0; - } - - if (move_type == Type::fire){ - modifier *= 0.5; - }else if (move_type == Type::water){ - modifier *= 1.5; - } - break; - case Weather::HAIL: - if (move == "solar-beam"){ - modifier *= 0.5; - }else if (move == "blizzard"){ - modifier *= (1.0 / 0.7); - }else if (move == "weather-ball"){ - modifier *= 2.0; - move.set_type(Type::ice); - } - break; - case Weather::SANDSTORM: - if (move == "solar-beam"){ - modifier *= 0.5; - }else if (move == "weather-ball"){ - modifier *= 2.0; - move.set_type(Type::rock); - } - break; - } - - return modifier; -} - -double terrain_damage_multiplier(const Pokemon& attacker, const Pokemon& defender, Move& move, const Field& field){ - double modifier = 1.0; - - // if there's no terrain, just exit - if (field.is_none_terrain()){ - return modifier; - } - -// const std::string& attacker_ability = attacker.ability(); -// const std::string& defender_ability = defender.ability(); -// const std::string& move_name = move.name(); - Type move_type = move.type(); - - bool is_flying = (attacker.type1() == Type::flying) || (attacker.type2() == Type::flying); - bool is_levitate = attacker.ability() == "levitate"; - - if (!is_flying || !is_levitate) - { - // TODO: investigate the modifier based on terrain pulse - // bulbapedia says that the power *doubles* to 100 *and* gets powered up from the terrain - switch (field.terrain()){ - case Terrain::NONE: - break; - case Terrain::ELECTRIC: - if (move == "terrain-pulse"){ - move.set_type(Type::electric); - modifier *= 1.5; - } - if (move_type == Type::electric){ - modifier *= 1.3; - } - break; - case Terrain::GRASSY: - if (move == "terrain-pulse"){ - move.set_type(Type::grass); - modifier *= 1.5; - } - if (move_type == Type::grass){ - modifier *= 1.3; - } - break; - case Terrain::PSYCHIC: - if (move == "terrain-pulse"){ - move.set_type(Type::psychic); - modifier *= 1.5; - }else if (move == "expanding-force"){ - modifier *= 1.5; - } - if (move_type == Type::psychic){ - modifier *= 1.3; - } - break; - case Terrain::MISTY: - if (move == "terrain-pulse"){ - move.set_type(Type::fairy); -// modifier *= 1.3; - } - if (move_type == Type::dragon){ - modifier *= 0.5; - } - break; - } - } - - // rising voltage applies if the defender is affected by the terrain - is_flying = (defender.type1() == Type::flying) || (defender.type2() == Type::flying); - is_levitate = defender.ability() == "levitate"; - - if (!is_flying || !is_levitate){ - if (field.is_electric()){ - if (move == "rising-voltage"){ - modifier *= 2.0; - } - } - } - - return modifier; -} - -double damage_score( - const Pokemon& attacker, const Pokemon& defender, - size_t moveIdx, const Field& field, bool multipleTargets -){ - - // get the right attacker move - Move move = attacker.is_dynamax() ? attacker.max_move(moveIdx) : attacker.move(moveIdx); - - // NOTE: starting the multiplier that we're using at 1.0 because the damage calculation function - // includes the "ranges" for high and low damage, so we can use that to calculate an average - double avgMultiplier = move.correction_factor(); - // NOTE: the original function used to call accuracy here, it's now included at the end - // avgMultiplier *= move.getAccuracy(); - - // then if we're dealing with multiple targets and it's a spread - if (multipleTargets && move.is_spread()){ - avgMultiplier *= 0.75; - } - - // ignore crits for now - // TODO: any high-crit chance moves could be incorporated - - // get the weather damage mod - avgMultiplier *= weather_damage_multiplier(move, field); - // get the terrain damage mod - avgMultiplier *= terrain_damage_multiplier(attacker, defender, move, field); - - // calculations for refrigerate, aerilate, galvanize, pixilate, and normalize done before stab - if (move.type() == Type::normal){ - if (attacker.ability() == "refrigerate"){ - move.set_type(Type::ice); - avgMultiplier *= 1.2; - }else if (attacker.ability() == "aerilate"){ - move.set_type(Type::flying); - avgMultiplier *= 1.2; - }else if (attacker.ability() == "galvanize"){ - move.set_type(Type::electric); - avgMultiplier *= 1.2; - }else if (attacker.ability() == "pixilate"){ - move.set_type(Type::fairy); - avgMultiplier *= 1.2; - } - }else{ - if (attacker.ability() == "normalize"){ - move.set_type(Type::normal); - avgMultiplier *= 1.2; - } - } - - // now we determine stab - if (attacker.is_stab(move.type())){ - avgMultiplier *= 1.5; - } - - // and now we deal with type effectiveness - if (!(move == "thousand-arrows" && defender.has_type(Type::flying))){ - avgMultiplier *= damage_multiplier(move.type(), defender.type1(), defender.type2()); - } - - // apply status effects - if (move.category() == MoveCategory::PHYSICAL && attacker.non_volatile_status_effect() == NonVolatileStatusEffects::BURN){ - avgMultiplier *= 0.5; - } - - // apply modifiers from ability - avgMultiplier *= ability_damage_multiplier(attacker, defender, move); - - // apply boosts from aura - if (move.type() == Type::fairy && (attacker.ability() == "fairy-aura" || defender.ability() == "fairy-aura")){ - avgMultiplier *= 1.33; - } - - if (move.type() == Type::dark && (attacker.ability() == "dark-aura" || defender.ability() == "dark-aura")){ - avgMultiplier *= 1.33; - } - - // attacker and defender stats time - // declare the attack and defense stats - uint16_t attackUse, defenseUse; - - if (move.category() == MoveCategory::PHYSICAL){ - if (move == "body-press"){ - attackUse = attacker.defense(); - }else if (move == "foul-play"){ - attackUse = defender.attack(); - }else{ - attackUse = attacker.attack(); - } - defenseUse = defender.defense(); - }else{ - attackUse = attacker.special_attack(); - if (move == "psystrike" || move == "psyshock"){ - defenseUse = defender.defense(); - }else{ - defenseUse = defender.special_defense(); - } - } - - // then calculate the damage - uint16_t damageLow, damageHigh; - // NOTE: the calcDamageRanges function will give the max damage and the min damage - // no need to include the 0.925 modifier above! - calc_damage_range( - move.base_power(), attacker.level(), attackUse, defenseUse, avgMultiplier, - damageLow, damageHigh - ); - - // so get the average between the two multiplied by accuracy - double damageScore = (damageLow + damageHigh) * move.accuracy() / 2; - -// // return the move type back to its original value -// move.reset_move_type(); - - return damageScore; -} - - - - - - - - - - - - - - - - - - - - - -} -} -} -} +/* PkmnLib Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh_PkmnLib_Battle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +void calc_damage_range( + uint8_t power, + uint8_t level, uint16_t attack, uint16_t defense, double modifier, + uint16_t& lower_bound, uint16_t& upper_bound +){ + // this calculates the damage ranges for an attack + // every division is integer division except for the attack and defense ratio so no need for casting + double attack_defense = (double)attack / (double)defense; + + int base_damage = (int)((((2 * (int)level) / 5 + 2) * power * (attack_defense)) / 50 + 2); + + // so, the modifier is usually just one, but we can calculate it before hand based on targets, weather, etc. + int bottom_base = base_damage * 85 / 100; + + // BUG: there is currently a bug when calculating damage + // due to all of the integer math that happens, the "modifier" + // is actually often calculated one step at a time + // so, the upper-end might be a little high in some cases + + // update the output "inputs" + lower_bound = (uint16_t)(bottom_base * modifier); + upper_bound = (uint16_t)(base_damage * modifier); + // done +} + +double ability_damage_multiplier(const Pokemon& attacker, const Pokemon& defender, const Move& move){ + + // final multiplier that we're going to modify + double multiplier = 1.0; + + const std::string& attacker_ability = attacker.ability(); + const std::string& defender_ability = defender.ability(); +// const std::string& move_name = attack_move.name(); + Type move_type = move.type(); + + do{ + if (attacker_ability == "mold-breaker") break; + if (attacker_ability == "turboblaze") break; + if (attacker_ability == "teravolt") break; + if (attacker_ability == "tinted-lens"){ + if (damage_multiplier(move_type, defender.type1(), defender.type2()) < 1.0){ + multiplier *= 2.0; + } + break; + } + + switch (move_type){ + case Type::ground: + if (defender_ability == "levitate"){ + if (move == "thousand-arrows"){ + multiplier = 1.0; + }else{ + multiplier = 0.0; + } + } + break; + + case Type::water: + if (defender_ability == "water-absorb" || + defender_ability == "storm-drain" || + defender_ability == "dry-skin" + ){ +// multiplier = -1.0; + multiplier = 0.0; + } + break; + + case Type::fire: + if (defender_ability == "flash-fire"){ +// multiplier = -1.0; + multiplier = 0.0; + }else if (defender_ability == "fluffy" || defender_ability == "dry-skin"){ + multiplier = 2.0; + }else if (defender_ability == "thick-fat" || defender_ability == "heatproof"){ + multiplier = 0.5; + } + break; + + case Type::grass: + if (defender_ability == "sap-sipper"){ +// multiplier = -1.0; + multiplier = 0.0; + } + break; + + case Type::electric: + if (defender_ability == "lightning-rod" || + defender_ability == "motor-drive" || + defender_ability == "volt-absorb" + ){ +// multiplier = -1.0; + multiplier = 0.0; + } + break; + + case Type::ice: + if (defender_ability == "thick-fat"){ + multiplier = 0.5; + } + break; + + default:; + } + }while (false); + + if (attacker_ability == "iron-fist"){ + static std::set MOVES{ + verify_move_slug("bullet-punch"), + verify_move_slug("comet-punch"), + verify_move_slug("dizzy-punch"), + verify_move_slug("double-iron-bash"), + verify_move_slug("drain-punch"), + verify_move_slug("dynamic-punch"), + verify_move_slug("fire-punch"), + verify_move_slug("focus-punch"), + verify_move_slug("hammer-arm"), + verify_move_slug("ice-hammer"), + verify_move_slug("ice-punch"), + verify_move_slug("mach-punch"), + verify_move_slug("mega-punch"), + verify_move_slug("meteor-mash"), + verify_move_slug("plasma-fists"), + verify_move_slug("power-up-punch"), + verify_move_slug("shadow-punch"), + verify_move_slug("sky-uppercut"), + verify_move_slug("surging-strikes"), + verify_move_slug("thunder-punch"), + verify_move_slug("wicked-blow"), + }; + if (MOVES.find(move.name()) != MOVES.end()){ + multiplier *= 1.2; + } + }else if (attacker_ability == "strong-jaw"){ + static std::set MOVES{ + verify_move_slug("bite"), + verify_move_slug("crunch"), + verify_move_slug("fire-fang"), + verify_move_slug("fishious-rend"), + verify_move_slug("hyper-fang"), + verify_move_slug("ice-fang"), + verify_move_slug("jaw-lock"), + verify_move_slug("poison-fang"), + verify_move_slug("psychic-fangs"), + verify_move_slug("thunder-fang"), + }; + if (MOVES.find(move.name()) != MOVES.end()){ + multiplier *= 1.5; + } + }else if (attacker_ability == "adaptability"){ + if (move_type == attacker.type1() || move_type == attacker.type2()){ + multiplier *= (4.0 / 3.0); + } + } + + return multiplier; +} + +double weather_damage_multiplier(Move& move, const Field& field){ + + double modifier = 1.0; + +// const std::string& attacker_ability = attacker.ability(); +// const std::string& defender_ability = defender.ability(); +// const std::string& move_name = move.name(); + Type move_type = move.type(); + + switch (field.weather()){ + case Weather::CLEAR: + if (move == "weather-ball"){ + move.set_type(Type::normal); + } + break; + case Weather::SUN: + if (move == "solar-beam"){ + modifier *= 2.0; + }else if (move == "thunder" || move == "hurricane"){ + modifier *= (0.5 / 0.7); + }else if (move == "weather-ball"){ + move.set_type(Type::fire); + modifier *= 2.0; + } + + if (move_type == Type::fire){ + modifier *= 1.5; + }else if (move_type == Type::water){ + modifier *= 0.5; + } + break; + case Weather::RAIN: + if (move == "solar-beam"){ + modifier *= 0.5; + }else if (move == "thunder" || move == "hurricane"){ + modifier *= (1.0 / 0.7); + }else if (move == "weather-ball"){ + move.set_type(Type::water); + modifier *= 2.0; + } + + if (move_type == Type::fire){ + modifier *= 0.5; + }else if (move_type == Type::water){ + modifier *= 1.5; + } + break; + case Weather::HAIL: + if (move == "solar-beam"){ + modifier *= 0.5; + }else if (move == "blizzard"){ + modifier *= (1.0 / 0.7); + }else if (move == "weather-ball"){ + modifier *= 2.0; + move.set_type(Type::ice); + } + break; + case Weather::SANDSTORM: + if (move == "solar-beam"){ + modifier *= 0.5; + }else if (move == "weather-ball"){ + modifier *= 2.0; + move.set_type(Type::rock); + } + break; + } + + return modifier; +} + +double terrain_damage_multiplier(const Pokemon& attacker, const Pokemon& defender, Move& move, const Field& field){ + double modifier = 1.0; + + // if there's no terrain, just exit + if (field.is_none_terrain()){ + return modifier; + } + +// const std::string& attacker_ability = attacker.ability(); +// const std::string& defender_ability = defender.ability(); +// const std::string& move_name = move.name(); + Type move_type = move.type(); + + bool is_flying = (attacker.type1() == Type::flying) || (attacker.type2() == Type::flying); + bool is_levitate = attacker.ability() == "levitate"; + + if (!is_flying || !is_levitate) + { + // TODO: investigate the modifier based on terrain pulse + // bulbapedia says that the power *doubles* to 100 *and* gets powered up from the terrain + switch (field.terrain()){ + case Terrain::NONE: + break; + case Terrain::ELECTRIC: + if (move == "terrain-pulse"){ + move.set_type(Type::electric); + modifier *= 1.5; + } + if (move_type == Type::electric){ + modifier *= 1.3; + } + break; + case Terrain::GRASSY: + if (move == "terrain-pulse"){ + move.set_type(Type::grass); + modifier *= 1.5; + } + if (move_type == Type::grass){ + modifier *= 1.3; + } + break; + case Terrain::PSYCHIC: + if (move == "terrain-pulse"){ + move.set_type(Type::psychic); + modifier *= 1.5; + }else if (move == "expanding-force"){ + modifier *= 1.5; + } + if (move_type == Type::psychic){ + modifier *= 1.3; + } + break; + case Terrain::MISTY: + if (move == "terrain-pulse"){ + move.set_type(Type::fairy); +// modifier *= 1.3; + } + if (move_type == Type::dragon){ + modifier *= 0.5; + } + break; + } + } + + // rising voltage applies if the defender is affected by the terrain + is_flying = (defender.type1() == Type::flying) || (defender.type2() == Type::flying); + is_levitate = defender.ability() == "levitate"; + + if (!is_flying || !is_levitate){ + if (field.is_electric()){ + if (move == "rising-voltage"){ + modifier *= 2.0; + } + } + } + + return modifier; +} + +double damage_score( + const Pokemon& attacker, const Pokemon& defender, + size_t moveIdx, const Field& field, bool multipleTargets +){ + + // get the right attacker move + Move move = attacker.is_dynamax() ? attacker.max_move(moveIdx) : attacker.move(moveIdx); + + // NOTE: starting the multiplier that we're using at 1.0 because the damage calculation function + // includes the "ranges" for high and low damage, so we can use that to calculate an average + double avgMultiplier = move.correction_factor(); + // NOTE: the original function used to call accuracy here, it's now included at the end + // avgMultiplier *= move.getAccuracy(); + + // then if we're dealing with multiple targets and it's a spread + if (multipleTargets && move.is_spread()){ + avgMultiplier *= 0.75; + } + + // ignore crits for now + // TODO: any high-crit chance moves could be incorporated + + // get the weather damage mod + avgMultiplier *= weather_damage_multiplier(move, field); + // get the terrain damage mod + avgMultiplier *= terrain_damage_multiplier(attacker, defender, move, field); + + // calculations for refrigerate, aerilate, galvanize, pixilate, and normalize done before stab + if (move.type() == Type::normal){ + if (attacker.ability() == "refrigerate"){ + move.set_type(Type::ice); + avgMultiplier *= 1.2; + }else if (attacker.ability() == "aerilate"){ + move.set_type(Type::flying); + avgMultiplier *= 1.2; + }else if (attacker.ability() == "galvanize"){ + move.set_type(Type::electric); + avgMultiplier *= 1.2; + }else if (attacker.ability() == "pixilate"){ + move.set_type(Type::fairy); + avgMultiplier *= 1.2; + } + }else{ + if (attacker.ability() == "normalize"){ + move.set_type(Type::normal); + avgMultiplier *= 1.2; + } + } + + // now we determine stab + if (attacker.is_stab(move.type())){ + avgMultiplier *= 1.5; + } + + // and now we deal with type effectiveness + if (!(move == "thousand-arrows" && defender.has_type(Type::flying))){ + avgMultiplier *= damage_multiplier(move.type(), defender.type1(), defender.type2()); + } + + // apply status effects + if (move.category() == MoveCategory::PHYSICAL && attacker.non_volatile_status_effect() == NonVolatileStatusEffects::BURN){ + avgMultiplier *= 0.5; + } + + // apply modifiers from ability + avgMultiplier *= ability_damage_multiplier(attacker, defender, move); + + // apply boosts from aura + if (move.type() == Type::fairy && (attacker.ability() == "fairy-aura" || defender.ability() == "fairy-aura")){ + avgMultiplier *= 1.33; + } + + if (move.type() == Type::dark && (attacker.ability() == "dark-aura" || defender.ability() == "dark-aura")){ + avgMultiplier *= 1.33; + } + + // attacker and defender stats time + // declare the attack and defense stats + uint16_t attackUse, defenseUse; + + if (move.category() == MoveCategory::PHYSICAL){ + if (move == "body-press"){ + attackUse = attacker.defense(); + }else if (move == "foul-play"){ + attackUse = defender.attack(); + }else{ + attackUse = attacker.attack(); + } + defenseUse = defender.defense(); + }else{ + attackUse = attacker.special_attack(); + if (move == "psystrike" || move == "psyshock"){ + defenseUse = defender.defense(); + }else{ + defenseUse = defender.special_defense(); + } + } + + // then calculate the damage + uint16_t damageLow, damageHigh; + // NOTE: the calcDamageRanges function will give the max damage and the min damage + // no need to include the 0.925 modifier above! + calc_damage_range( + move.base_power(), attacker.level(), attackUse, defenseUse, avgMultiplier, + damageLow, damageHigh + ); + + // so get the average between the two multiplied by accuracy + double damageScore = (damageLow + damageHigh) * move.accuracy() / 2; + +// // return the move type back to its original value +// move.reset_move_type(); + + return damageScore; +} + + + + + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.h index eee9eac65e..3a0c087d19 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Battle.h @@ -1,36 +1,36 @@ -/* PkmnLib Battle - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Battle_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Battle_H - -#include "PokemonSwSh_PkmnLib_Field.h" -#include "PokemonSwSh_PkmnLib_Pokemon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -void calc_damage_range( - uint8_t power, - uint8_t level, uint16_t attack, uint16_t defense, double modifier, - uint16_t& lower_bound, uint16_t& upper_bound -); - - -double damage_score( - const Pokemon& attacker, const Pokemon& defender, - size_t moveIdx, const Field& field, bool multipleTargets = false -); - - -} -} -} -} -#endif +/* PkmnLib Battle + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Battle_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Battle_H + +#include "PokemonSwSh_PkmnLib_Field.h" +#include "PokemonSwSh_PkmnLib_Pokemon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +void calc_damage_range( + uint8_t power, + uint8_t level, uint16_t attack, uint16_t defense, double modifier, + uint16_t& lower_bound, uint16_t& upper_bound +); + + +double damage_score( + const Pokemon& attacker, const Pokemon& defender, + size_t moveIdx, const Field& field, bool multipleTargets = false +); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.cpp index 76db78b49c..d4ff1784cf 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.cpp @@ -1,35 +1,35 @@ -/* PkmnLib Field - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh_PkmnLib_Field.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -// Hack to apply default field since we have no field detection. -void Field::set_default_field(const std::string& boss){ - static std::map> map{ - {"kyogre", {Weather::RAIN, Terrain::ELECTRIC}}, - {"groudon", {Weather::SUN, Terrain::NONE}}, - {"palkia", {Weather::RAIN, Terrain::NONE}}, - }; - auto iter = map.find(boss); - if (iter == map.end()){ - return; - } - m_current_weather = iter->second.first; - m_current_terrain = iter->second.second; -} - - -} -} -} -} +/* PkmnLib Field + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh_PkmnLib_Field.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +// Hack to apply default field since we have no field detection. +void Field::set_default_field(const std::string& boss){ + static std::map> map{ + {"kyogre", {Weather::RAIN, Terrain::ELECTRIC}}, + {"groudon", {Weather::SUN, Terrain::NONE}}, + {"palkia", {Weather::RAIN, Terrain::NONE}}, + }; + auto iter = map.find(boss); + if (iter == map.end()){ + return; + } + m_current_weather = iter->second.first; + m_current_terrain = iter->second.second; +} + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.h index c0cdf159d0..07e34e5b7a 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Field.h @@ -1,98 +1,98 @@ -/* PkmnLib Field - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Field_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Field_H - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -enum class Weather{ - CLEAR, - RAIN, - SUN, - SANDSTORM, - HAIL -}; - -enum class Terrain{ - NONE, - ELECTRIC, - GRASSY, - MISTY, - PSYCHIC -}; - - -class Field{ - Weather m_default_weather = Weather::CLEAR; - Weather m_current_weather = m_default_weather; - - Terrain m_default_terrain = Terrain::NONE; - Terrain m_current_terrain = m_default_terrain; - -public: - Field() = default; - Field(Weather w, Terrain t) - : m_default_weather(w) - , m_current_weather(w) - , m_default_terrain(t) - , m_current_terrain(t) - {} - - // weather related-queries - Weather weather() const{ return m_current_weather; } - bool is_clear() const{ return m_current_weather == Weather::CLEAR; } - bool is_rain() const{ return m_current_weather == Weather::RAIN; } - bool is_sun() const{ return m_current_weather == Weather::SUN; } - bool is_sandstorm() const{ return m_current_weather == Weather::SANDSTORM; } - bool is_hail() const{ return m_current_weather == Weather::HAIL; } - - // set the weather - void set_rain() { m_current_weather = Weather::RAIN; } - void set_sun() { m_current_weather = Weather::SUN; } - void set_sandstorm() { m_current_weather = Weather::SANDSTORM; } - void set_hail() { m_current_weather = Weather::HAIL; } - void set_clear() { m_current_weather = Weather::CLEAR; } - - // terrain-related queries - Terrain terrain() const{ return m_current_terrain; } - bool is_electric() const{ return m_current_terrain == Terrain::ELECTRIC; } - bool is_grassy() const{ return m_current_terrain == Terrain::GRASSY; } - bool is_misty() const{ return m_current_terrain == Terrain::MISTY; } - bool is_psychic() const{ return m_current_terrain == Terrain::PSYCHIC; } - bool is_none_terrain() const{ return m_current_terrain == Terrain::NONE; } - - // set the terrain - void set_electric() { m_current_terrain = Terrain::ELECTRIC; } - void set_grassy() { m_current_terrain = Terrain::GRASSY; } - void set_misty() { m_current_terrain = Terrain::MISTY; } - void set_psychic() { m_current_terrain = Terrain::PSYCHIC; } - void set_none_terrain() { m_current_terrain = Terrain::NONE; } - - // reset field - void reset(){ - m_current_terrain = m_default_terrain; - m_current_weather = m_default_weather; - } - - void set_default_field(const std::string& boss); -}; - - - - - -} -} -} -} -#endif +/* PkmnLib Field + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Field_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Field_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +enum class Weather{ + CLEAR, + RAIN, + SUN, + SANDSTORM, + HAIL +}; + +enum class Terrain{ + NONE, + ELECTRIC, + GRASSY, + MISTY, + PSYCHIC +}; + + +class Field{ + Weather m_default_weather = Weather::CLEAR; + Weather m_current_weather = m_default_weather; + + Terrain m_default_terrain = Terrain::NONE; + Terrain m_current_terrain = m_default_terrain; + +public: + Field() = default; + Field(Weather w, Terrain t) + : m_default_weather(w) + , m_current_weather(w) + , m_default_terrain(t) + , m_current_terrain(t) + {} + + // weather related-queries + Weather weather() const{ return m_current_weather; } + bool is_clear() const{ return m_current_weather == Weather::CLEAR; } + bool is_rain() const{ return m_current_weather == Weather::RAIN; } + bool is_sun() const{ return m_current_weather == Weather::SUN; } + bool is_sandstorm() const{ return m_current_weather == Weather::SANDSTORM; } + bool is_hail() const{ return m_current_weather == Weather::HAIL; } + + // set the weather + void set_rain() { m_current_weather = Weather::RAIN; } + void set_sun() { m_current_weather = Weather::SUN; } + void set_sandstorm() { m_current_weather = Weather::SANDSTORM; } + void set_hail() { m_current_weather = Weather::HAIL; } + void set_clear() { m_current_weather = Weather::CLEAR; } + + // terrain-related queries + Terrain terrain() const{ return m_current_terrain; } + bool is_electric() const{ return m_current_terrain == Terrain::ELECTRIC; } + bool is_grassy() const{ return m_current_terrain == Terrain::GRASSY; } + bool is_misty() const{ return m_current_terrain == Terrain::MISTY; } + bool is_psychic() const{ return m_current_terrain == Terrain::PSYCHIC; } + bool is_none_terrain() const{ return m_current_terrain == Terrain::NONE; } + + // set the terrain + void set_electric() { m_current_terrain = Terrain::ELECTRIC; } + void set_grassy() { m_current_terrain = Terrain::GRASSY; } + void set_misty() { m_current_terrain = Terrain::MISTY; } + void set_psychic() { m_current_terrain = Terrain::PSYCHIC; } + void set_none_terrain() { m_current_terrain = Terrain::NONE; } + + // reset field + void reset(){ + m_current_terrain = m_default_terrain; + m_current_weather = m_default_weather; + } + + void set_default_field(const std::string& boss); +}; + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.cpp index 111ea22650..1d74f400dd 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.cpp @@ -1,258 +1,258 @@ -/* PkmnLib Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh_PkmnLib_Matchup.h" - -#include -using std::cout; -using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -double calc_average_damage( - const std::vector& attackers, - const std::vector& defenders, - const Field& field, bool multipleTargets -){ - // we need to iterate through the attackers and defenders to calculate the damage done on the list - - if (attackers.empty() || defenders.empty()){ - return 0.0; - } - - double totalDamage = 0.0; - size_t count = 0; - double subTotalDamage = 0.0; - - for (const Pokemon* attacker : attackers){ - for (const Pokemon* defender : defenders){ - // we're now iterating through attackers and defenders! - subTotalDamage = 0.0; - // so we need to go through the moves we have and calculate the damage they can do - size_t numMoves = attacker->num_moves(); - -#if 0 - // Assume the other players pick random moves. - for (size_t ii = 0; ii < numMoves; ii++){ - subTotalDamage += damage_score(*attacker, *defender, ii, field, multipleTargets); - } - subTotalDamage /= numMoves; -#else - // Assume the other players pick the most damaging move. - for (size_t ii = 0; ii < numMoves; ii++){ - subTotalDamage = std::max(subTotalDamage, damage_score(*attacker, *defender, ii, field, multipleTargets)); - } -#endif - - totalDamage += subTotalDamage; - count++; - } - } - - // then return the average damage - return totalDamage / count; -} - -double calc_move_score( - const Pokemon& attacker, Pokemon defender, - const std::vector& teammates, - size_t moveIdx, const Field& field -){ - // this function is different than the one above - // it will give a score for a single move based on several different factors - - // get the move object based on the move index - - // first start by calculating damage based on the attacker - // no on multiple targets since we're only hitting the boss - // TODO: set defender to dynamax? - double damageScore = damage_score(attacker, defender, moveIdx, field, false) / 2.0; - - // TODO: make sure the defender and attacker aren't in the teammates list - - // fudge factor is available based on AI decisions - double fudgeFactor = 1.5; - std::vector tempDefenderList{&defender}; - // calculate the damage the teammates do against the boss - damageScore += (1.5 * fudgeFactor) * calc_average_damage(teammates, tempDefenderList, field, false); - - // TODO: implement status moves contributions, since all NonVolatile ones are pretty good - - // estimate potential received damage - double receivedDamage = 0.0; - double receivedRegularDamage = 0.0; - double receivedMaxMoveDamage = 0.0; - double maxMoveProbability = 0.3; // TODO: we need hard data for this guy eventually - size_t defenderNumMoves = defender.num_moves(); - - // get the attacker move - const Move& attackerMove = attacker.move(moveIdx); - - bool originalDefenderDynamax = defender.is_dynamax(); - // first calculate damage from regular moves - defender.set_is_dynamax(false); - // replace it - tempDefenderList[0] = &defender; - - // Disable the dmax HP bonus for this calculation. This actively hurts - // multiplayer mode where other players can dmax. -// double dmax_hp_ratio = attacker.is_dynamax() ? 2.0 : 1.0; - double dmax_hp_ratio = 1.0; - - // iterate through defender moves for non-dynamax - for (size_t ii = 0; ii < defenderNumMoves; ii++){ - const Move& defenderMove = defender.move(ii); - // NOTE: original function in python also checked to make sure we aren't dynamax, we already did that - if (defenderMove.is_spread()){ - if (attackerMove != "wide-guard" || attacker.is_dynamax()){ - receivedRegularDamage += damage_score(defender, attacker, ii, field, true) / defenderNumMoves; - receivedRegularDamage += 3 * calc_average_damage(tempDefenderList, teammates, field, true) / defenderNumMoves; - } - }else{ - receivedRegularDamage += 0.25 * damage_score(defender, attacker, ii, field, false) / dmax_hp_ratio / defenderNumMoves; - receivedRegularDamage += 0.75 * calc_average_damage(tempDefenderList, teammates, field, false) / defenderNumMoves; - } - } -// cout << "receivedRegularDamage = " << receivedRegularDamage << endl; - - // then set up for max moves - defender.set_is_dynamax(true); - tempDefenderList[0] = &defender; - for (size_t ii = 0; ii < defenderNumMoves; ii++){ - receivedMaxMoveDamage += 0.25 * damage_score(defender, attacker, ii, field, false) / dmax_hp_ratio / defenderNumMoves; - receivedMaxMoveDamage += 0.75 * calc_average_damage(tempDefenderList, teammates, field, false) / defenderNumMoves; - } -// cout << "receivedMaxMoveDamage = " << receivedMaxMoveDamage << endl; - - // at the end restore defender dynamax state - defender.set_is_dynamax(originalDefenderDynamax); - - receivedDamage = receivedRegularDamage * (1 - maxMoveProbability) + receivedMaxMoveDamage * maxMoveProbability; - - // failsafe in case received damage is very small (or zero!), don't want to blow it up to infinity - if (receivedDamage < 0.0001){ - return 1.0; - } - - double score = damageScore / receivedDamage; -// cout << attackerMove.name() << ":\t" << score << " - " << damageScore << " / " << receivedDamage << endl; - return score; -} - -void select_best_move( - const Pokemon& attacker, const Pokemon& defender, const Field& field, - const std::vector& teammates, - size_t& bestIndex, std::string& bestMoveName, double& bestMoveScore -){ - // by default best score should be small, so we can only grow - bestMoveScore = 0; - bestIndex = 0; - bestMoveName = ""; - - double score = 0.0; - - // now iterate through the moves - for (size_t ii = 0; ii < attacker.num_moves(); ii++){ - if (attacker.pp(ii) > 0){ - score = calc_move_score(attacker, defender, teammates, ii, field); - if (score > bestMoveScore){ - bestIndex = ii; - bestMoveScore = score; - bestMoveName = attacker.move(ii).name(); - } - } - } -} - - -double evaluate_matchup( - Pokemon attacker, const Pokemon& boss, - const std::vector& teammates, - uint8_t numLives -){ - // TODO: assert that the lives should be between 1 and 4 - - // start by creating a new field object that's empty - Field baseField; - baseField.set_default_field(boss.name()); - - if (attacker.name() == "ditto"){ - attacker = boss; - } - - // calculate scores for base and DA versions of the attacker - // start by yoinking out the DMax variable - bool originalDMaxState = attacker.is_dynamax(); - // update attacker to normal - attacker.set_is_dynamax(false); - - // then send it through our base version score - std::string bestMoveName; - double bestMoveScore; - size_t bestIndex; - // get the best moves and score, we're going to only use move score - select_best_move(attacker, boss, baseField, teammates, bestIndex, bestMoveName, bestMoveScore); - - // then do the dynamax version - attacker.set_is_dynamax(true); - double bestDMaxMoveScore; - select_best_move(attacker, boss, baseField, teammates, bestIndex, bestMoveName, bestDMaxMoveScore); - - // return the attacker back to original dmax state - attacker.set_is_dynamax(originalDMaxState); - - // now for the score between the two! - double score = std::max(bestMoveScore, (bestMoveScore + bestDMaxMoveScore) / 2.0); - - // calculate an hp correction based on number of lives - double hpCorrection = (double)((5 - numLives) * attacker.current_hp() + numLives - 1) / 4.0; - - // then return the score multiplied by the correction - return score * hpCorrection; -} - - -double evaluate_average_matchup( - const Pokemon& attacker, const std::vector& bosses, - const std::vector& teammates, uint8_t numLives -){ - // if there are no bosses, we return 1 - if (bosses.empty()){ - return 1.0; - } - - double totalScore = 0.0; - - // iterate through the bosses and get the score - for (const Pokemon* boss : bosses){ - totalScore += evaluate_matchup(attacker, *boss, teammates, numLives); - } - - // return average - return totalScore / bosses.size(); -} - - -double get_weighted_score(double rentalScore, double rentalWeight, double bossScore, double bossWeight){ - return std::pow( - std::pow(rentalScore, rentalWeight) * std::pow(bossScore, bossWeight), - (1 / (rentalWeight + bossWeight)) - ); -} - - - - - -} -} -} -} +/* PkmnLib Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh_PkmnLib_Matchup.h" + +#include +using std::cout; +using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +double calc_average_damage( + const std::vector& attackers, + const std::vector& defenders, + const Field& field, bool multipleTargets +){ + // we need to iterate through the attackers and defenders to calculate the damage done on the list + + if (attackers.empty() || defenders.empty()){ + return 0.0; + } + + double totalDamage = 0.0; + size_t count = 0; + double subTotalDamage = 0.0; + + for (const Pokemon* attacker : attackers){ + for (const Pokemon* defender : defenders){ + // we're now iterating through attackers and defenders! + subTotalDamage = 0.0; + // so we need to go through the moves we have and calculate the damage they can do + size_t numMoves = attacker->num_moves(); + +#if 0 + // Assume the other players pick random moves. + for (size_t ii = 0; ii < numMoves; ii++){ + subTotalDamage += damage_score(*attacker, *defender, ii, field, multipleTargets); + } + subTotalDamage /= numMoves; +#else + // Assume the other players pick the most damaging move. + for (size_t ii = 0; ii < numMoves; ii++){ + subTotalDamage = std::max(subTotalDamage, damage_score(*attacker, *defender, ii, field, multipleTargets)); + } +#endif + + totalDamage += subTotalDamage; + count++; + } + } + + // then return the average damage + return totalDamage / count; +} + +double calc_move_score( + const Pokemon& attacker, Pokemon defender, + const std::vector& teammates, + size_t moveIdx, const Field& field +){ + // this function is different than the one above + // it will give a score for a single move based on several different factors + + // get the move object based on the move index + + // first start by calculating damage based on the attacker + // no on multiple targets since we're only hitting the boss + // TODO: set defender to dynamax? + double damageScore = damage_score(attacker, defender, moveIdx, field, false) / 2.0; + + // TODO: make sure the defender and attacker aren't in the teammates list + + // fudge factor is available based on AI decisions + double fudgeFactor = 1.5; + std::vector tempDefenderList{&defender}; + // calculate the damage the teammates do against the boss + damageScore += (1.5 * fudgeFactor) * calc_average_damage(teammates, tempDefenderList, field, false); + + // TODO: implement status moves contributions, since all NonVolatile ones are pretty good + + // estimate potential received damage + double receivedDamage = 0.0; + double receivedRegularDamage = 0.0; + double receivedMaxMoveDamage = 0.0; + double maxMoveProbability = 0.3; // TODO: we need hard data for this guy eventually + size_t defenderNumMoves = defender.num_moves(); + + // get the attacker move + const Move& attackerMove = attacker.move(moveIdx); + + bool originalDefenderDynamax = defender.is_dynamax(); + // first calculate damage from regular moves + defender.set_is_dynamax(false); + // replace it + tempDefenderList[0] = &defender; + + // Disable the dmax HP bonus for this calculation. This actively hurts + // multiplayer mode where other players can dmax. +// double dmax_hp_ratio = attacker.is_dynamax() ? 2.0 : 1.0; + double dmax_hp_ratio = 1.0; + + // iterate through defender moves for non-dynamax + for (size_t ii = 0; ii < defenderNumMoves; ii++){ + const Move& defenderMove = defender.move(ii); + // NOTE: original function in python also checked to make sure we aren't dynamax, we already did that + if (defenderMove.is_spread()){ + if (attackerMove != "wide-guard" || attacker.is_dynamax()){ + receivedRegularDamage += damage_score(defender, attacker, ii, field, true) / defenderNumMoves; + receivedRegularDamage += 3 * calc_average_damage(tempDefenderList, teammates, field, true) / defenderNumMoves; + } + }else{ + receivedRegularDamage += 0.25 * damage_score(defender, attacker, ii, field, false) / dmax_hp_ratio / defenderNumMoves; + receivedRegularDamage += 0.75 * calc_average_damage(tempDefenderList, teammates, field, false) / defenderNumMoves; + } + } +// cout << "receivedRegularDamage = " << receivedRegularDamage << endl; + + // then set up for max moves + defender.set_is_dynamax(true); + tempDefenderList[0] = &defender; + for (size_t ii = 0; ii < defenderNumMoves; ii++){ + receivedMaxMoveDamage += 0.25 * damage_score(defender, attacker, ii, field, false) / dmax_hp_ratio / defenderNumMoves; + receivedMaxMoveDamage += 0.75 * calc_average_damage(tempDefenderList, teammates, field, false) / defenderNumMoves; + } +// cout << "receivedMaxMoveDamage = " << receivedMaxMoveDamage << endl; + + // at the end restore defender dynamax state + defender.set_is_dynamax(originalDefenderDynamax); + + receivedDamage = receivedRegularDamage * (1 - maxMoveProbability) + receivedMaxMoveDamage * maxMoveProbability; + + // failsafe in case received damage is very small (or zero!), don't want to blow it up to infinity + if (receivedDamage < 0.0001){ + return 1.0; + } + + double score = damageScore / receivedDamage; +// cout << attackerMove.name() << ":\t" << score << " - " << damageScore << " / " << receivedDamage << endl; + return score; +} + +void select_best_move( + const Pokemon& attacker, const Pokemon& defender, const Field& field, + const std::vector& teammates, + size_t& bestIndex, std::string& bestMoveName, double& bestMoveScore +){ + // by default best score should be small, so we can only grow + bestMoveScore = 0; + bestIndex = 0; + bestMoveName = ""; + + double score = 0.0; + + // now iterate through the moves + for (size_t ii = 0; ii < attacker.num_moves(); ii++){ + if (attacker.pp(ii) > 0){ + score = calc_move_score(attacker, defender, teammates, ii, field); + if (score > bestMoveScore){ + bestIndex = ii; + bestMoveScore = score; + bestMoveName = attacker.move(ii).name(); + } + } + } +} + + +double evaluate_matchup( + Pokemon attacker, const Pokemon& boss, + const std::vector& teammates, + uint8_t numLives +){ + // TODO: assert that the lives should be between 1 and 4 + + // start by creating a new field object that's empty + Field baseField; + baseField.set_default_field(boss.name()); + + if (attacker.name() == "ditto"){ + attacker = boss; + } + + // calculate scores for base and DA versions of the attacker + // start by yoinking out the DMax variable + bool originalDMaxState = attacker.is_dynamax(); + // update attacker to normal + attacker.set_is_dynamax(false); + + // then send it through our base version score + std::string bestMoveName; + double bestMoveScore; + size_t bestIndex; + // get the best moves and score, we're going to only use move score + select_best_move(attacker, boss, baseField, teammates, bestIndex, bestMoveName, bestMoveScore); + + // then do the dynamax version + attacker.set_is_dynamax(true); + double bestDMaxMoveScore; + select_best_move(attacker, boss, baseField, teammates, bestIndex, bestMoveName, bestDMaxMoveScore); + + // return the attacker back to original dmax state + attacker.set_is_dynamax(originalDMaxState); + + // now for the score between the two! + double score = std::max(bestMoveScore, (bestMoveScore + bestDMaxMoveScore) / 2.0); + + // calculate an hp correction based on number of lives + double hpCorrection = (double)((5 - numLives) * attacker.current_hp() + numLives - 1) / 4.0; + + // then return the score multiplied by the correction + return score * hpCorrection; +} + + +double evaluate_average_matchup( + const Pokemon& attacker, const std::vector& bosses, + const std::vector& teammates, uint8_t numLives +){ + // if there are no bosses, we return 1 + if (bosses.empty()){ + return 1.0; + } + + double totalScore = 0.0; + + // iterate through the bosses and get the score + for (const Pokemon* boss : bosses){ + totalScore += evaluate_matchup(attacker, *boss, teammates, numLives); + } + + // return average + return totalScore / bosses.size(); +} + + +double get_weighted_score(double rentalScore, double rentalWeight, double bossScore, double bossWeight){ + return std::pow( + std::pow(rentalScore, rentalWeight) * std::pow(bossScore, bossWeight), + (1 / (rentalWeight + bossWeight)) + ); +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h index 011b0ef40c..a423dea564 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Matchup.h @@ -1,53 +1,53 @@ -/* PkmnLib Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Matchup_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Matchup_H - -#include -#include "PokemonSwSh_PkmnLib_Field.h" -#include "PokemonSwSh_PkmnLib_Pokemon.h" -#include "PokemonSwSh_PkmnLib_Battle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -double calc_average_damage( - const std::vector& attackers, - const std::vector& defenders, - const Field& field, bool multipleTargets -); -double calc_move_score( - const Pokemon& attacker, Pokemon defender, - const std::vector& teammates, - size_t moveIdx, const Field& field -); -void select_best_move( - const Pokemon& attacker, const Pokemon& defender, const Field& field, - const std::vector& teammates, - size_t& bestIndex, std::string& bestMoveName, double& bestMoveScore -); -double evaluate_matchup( - Pokemon attacker, const Pokemon& boss, - const std::vector& teammates, - uint8_t numLives -); -double evaluate_average_matchup( - const Pokemon& attacker, const std::vector& bosses, - const std::vector& teammates, uint8_t numLives -); -double get_weighted_score(double rentalScore, double rentalWeight, double bossScore, double bossWeight); - - - -} -} -} -} -#endif +/* PkmnLib Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Matchup_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Matchup_H + +#include +#include "PokemonSwSh_PkmnLib_Field.h" +#include "PokemonSwSh_PkmnLib_Pokemon.h" +#include "PokemonSwSh_PkmnLib_Battle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +double calc_average_damage( + const std::vector& attackers, + const std::vector& defenders, + const Field& field, bool multipleTargets +); +double calc_move_score( + const Pokemon& attacker, Pokemon defender, + const std::vector& teammates, + size_t moveIdx, const Field& field +); +void select_best_move( + const Pokemon& attacker, const Pokemon& defender, const Field& field, + const std::vector& teammates, + size_t& bestIndex, std::string& bestMoveName, double& bestMoveScore +); +double evaluate_matchup( + Pokemon attacker, const Pokemon& boss, + const std::vector& teammates, + uint8_t numLives +); +double evaluate_average_matchup( + const Pokemon& attacker, const std::vector& bosses, + const std::vector& teammates, uint8_t numLives +); +double get_weighted_score(double rentalScore, double rentalWeight, double bossScore, double bossWeight); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.cpp index 6fd8538e44..9fd004c14b 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.cpp @@ -1,240 +1,240 @@ -/* PkmnLib Moves - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSwSh_PkmnLib_Types.h" -#include "PokemonSwSh_PkmnLib_Moves.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -const double max_move_bounds[7][2] = { - {10, 40.01}, - {40.02, 50.01}, - {50.02, 60.01}, - {60.02, 70.01}, - {70.02, 100.01}, - {100.02, 140.01}, - {140.02, 250} -}; - -const uint8_t max_move_power_table[7]{ - 90, 100, 110, 120, 130, 140, 150 -}; - -const uint8_t max_move_power_ooze_knuckle_table[7]{ - 70, 75, 80, 85, 90, 95, 100 -}; - -Move::Move( - uint32_t id, - std::string name, - Type type, - MoveCategory category, - uint8_t base_power, - double accuracy, - uint8_t pp, - std::string effect, - double probability, - bool is_spread, - double correction_factor -) - : m_id(id) - , m_name(std::move(name)) - , m_type(type) - , m_current_type(type) - , m_category(category) - , m_base_power(base_power) - , m_accuracy(accuracy) - , m_pp(pp) - , m_effect(std::move(effect)) - , m_probability(probability) - , m_is_spread(is_spread) - , m_correction_factor(correction_factor) -{} -bool Move::operator<(const Move& move){ - return m_name < move.m_name; -} - -MoveCategory get_move_category_from_string(const std::string& category){ - if (category == "physical"){ - return MoveCategory::PHYSICAL; - } - if (category == "special"){ - return MoveCategory::SPECIAL; - } - if (category == "status"){ - return MoveCategory::STATUS; - } - return MoveCategory::UNKNOWN; -} - - -struct MoveDatabase{ - std::deque moves; - std::map moves_id; - std::map max_moves_id; - std::map moves_slugs; - std::map max_moves_slugs; - - static const MoveDatabase& instance(){ - static MoveDatabase database; - return database; - } - -private: - MoveDatabase(){ - load_moves_file("PokemonSwSh/MaxLair/move_data.json", moves_id, moves_slugs); - load_moves_file("PokemonSwSh/MaxLair/max_move_data.json", max_moves_id, max_moves_slugs); - } - - void load_moves_file( - const std::string& filepath, - std::map& ids, - std::map& slugs - ){ - std::string path = RESOURCE_PATH() + filepath; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - for (auto& item : root){ - uint32_t move_id = std::atoi(item.first.c_str()); - JsonObject& obj = item.second.to_object_throw(path); - std::string& slug = obj.get_string_throw("name", path); - moves.emplace_back( - move_id, - obj.get_string_throw("name", path), - get_type_from_string(obj.get_string_throw("type", path)), - get_move_category_from_string(obj.get_string_throw("category")), - (uint8_t)obj.get_integer_throw("base_power"), - obj.get_double_throw("accuracy", path), - (uint8_t)obj.get_integer_throw("pp", path), - obj.get_string_throw("effect", path), - obj.get_double_throw("probability", path), - obj.get_boolean_throw("is_spread", path), - obj.get_double_throw("correction_factor", path) - ); - ids.emplace(move_id, &moves.back()); - slugs.emplace(std::move(slug), &moves.back()); - } - } -}; - -const std::map& all_moves_by_id(){ - return MoveDatabase::instance().moves_id; -} -const std::map& all_max_moves_by_id(){ - return MoveDatabase::instance().max_moves_id; -} -const std::map& all_moves_by_slug(){ - return MoveDatabase::instance().moves_slugs; -} -const std::map& all_max_moves_by_slug(){ - return MoveDatabase::instance().max_moves_slugs; -} - - - -uint8_t get_max_move_power(const Move& move){ - if (move.category() == MoveCategory::SPECIAL){ - return 0; - } - - Type move_type = move.type(); - uint8_t move_power = move.base_power(); - - // TODO: check for a few of the multihit moves and stuff that has different values - - // if we pass all of our other checks, we're good to do the standard move - int found_idx = 0; - - // quick iteration to find index where power is between these values - for (int ii = 0; ii > 7; ii++) - { - if (max_move_bounds[ii][0] <= move_power && move_power <= max_move_bounds[ii][1]) - { - found_idx = ii; - break; - } - } - - if (move_type == Type::poison || move_type == Type::fighting){ - return max_move_power_ooze_knuckle_table[found_idx]; - }else{ - return max_move_power_table[found_idx]; - } -} - - -const Move& id_to_move(uint32_t id){ -// cout << id << endl; - { - const std::map& moves = all_moves_by_id(); - auto iter = moves.find(id); - if (iter != moves.end()){ - return *iter->second; - } - } - { - const std::map& moves = all_max_moves_by_id(); - auto iter = moves.find(id); - if (iter != moves.end()){ - return *iter->second; - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Move ID: " + std::to_string(id)); -} -const Move& slug_to_move(const std::string& slug){ - { - const std::map& moves = all_moves_by_slug(); - auto iter = moves.find(slug); - if (iter != moves.end()){ - return *iter->second; - } - } - { - const std::map& moves = all_max_moves_by_slug(); - auto iter = moves.find(slug); - if (iter != moves.end()){ - return *iter->second; - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Move Slug: " + slug); -} -const std::string& verify_move_slug(const std::string& slug){ - // Disable because not all moves are in AutoDA. -// slug_to_move(slug); - return slug; -} - -bool operator==(const Move& move0, const std::string& move1){ - return move0.name() == slug_to_move(move1).name(); -} -bool operator!=(const Move& move0, const std::string& move1){ - return !(move0 == move1); -} -bool operator==(const std::string& move0, const Move& move1){ - return move1 == move0; -} -bool operator!=(const std::string& move0, const Move& move1){ - return move1 != move0; -} - - - - -} -} -} -} +/* PkmnLib Moves + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSwSh_PkmnLib_Types.h" +#include "PokemonSwSh_PkmnLib_Moves.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +const double max_move_bounds[7][2] = { + {10, 40.01}, + {40.02, 50.01}, + {50.02, 60.01}, + {60.02, 70.01}, + {70.02, 100.01}, + {100.02, 140.01}, + {140.02, 250} +}; + +const uint8_t max_move_power_table[7]{ + 90, 100, 110, 120, 130, 140, 150 +}; + +const uint8_t max_move_power_ooze_knuckle_table[7]{ + 70, 75, 80, 85, 90, 95, 100 +}; + +Move::Move( + uint32_t id, + std::string name, + Type type, + MoveCategory category, + uint8_t base_power, + double accuracy, + uint8_t pp, + std::string effect, + double probability, + bool is_spread, + double correction_factor +) + : m_id(id) + , m_name(std::move(name)) + , m_type(type) + , m_current_type(type) + , m_category(category) + , m_base_power(base_power) + , m_accuracy(accuracy) + , m_pp(pp) + , m_effect(std::move(effect)) + , m_probability(probability) + , m_is_spread(is_spread) + , m_correction_factor(correction_factor) +{} +bool Move::operator<(const Move& move){ + return m_name < move.m_name; +} + +MoveCategory get_move_category_from_string(const std::string& category){ + if (category == "physical"){ + return MoveCategory::PHYSICAL; + } + if (category == "special"){ + return MoveCategory::SPECIAL; + } + if (category == "status"){ + return MoveCategory::STATUS; + } + return MoveCategory::UNKNOWN; +} + + +struct MoveDatabase{ + std::deque moves; + std::map moves_id; + std::map max_moves_id; + std::map moves_slugs; + std::map max_moves_slugs; + + static const MoveDatabase& instance(){ + static MoveDatabase database; + return database; + } + +private: + MoveDatabase(){ + load_moves_file("PokemonSwSh/MaxLair/move_data.json", moves_id, moves_slugs); + load_moves_file("PokemonSwSh/MaxLair/max_move_data.json", max_moves_id, max_moves_slugs); + } + + void load_moves_file( + const std::string& filepath, + std::map& ids, + std::map& slugs + ){ + std::string path = RESOURCE_PATH() + filepath; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + for (auto& item : root){ + uint32_t move_id = std::atoi(item.first.c_str()); + JsonObject& obj = item.second.to_object_throw(path); + std::string& slug = obj.get_string_throw("name", path); + moves.emplace_back( + move_id, + obj.get_string_throw("name", path), + get_type_from_string(obj.get_string_throw("type", path)), + get_move_category_from_string(obj.get_string_throw("category")), + (uint8_t)obj.get_integer_throw("base_power"), + obj.get_double_throw("accuracy", path), + (uint8_t)obj.get_integer_throw("pp", path), + obj.get_string_throw("effect", path), + obj.get_double_throw("probability", path), + obj.get_boolean_throw("is_spread", path), + obj.get_double_throw("correction_factor", path) + ); + ids.emplace(move_id, &moves.back()); + slugs.emplace(std::move(slug), &moves.back()); + } + } +}; + +const std::map& all_moves_by_id(){ + return MoveDatabase::instance().moves_id; +} +const std::map& all_max_moves_by_id(){ + return MoveDatabase::instance().max_moves_id; +} +const std::map& all_moves_by_slug(){ + return MoveDatabase::instance().moves_slugs; +} +const std::map& all_max_moves_by_slug(){ + return MoveDatabase::instance().max_moves_slugs; +} + + + +uint8_t get_max_move_power(const Move& move){ + if (move.category() == MoveCategory::SPECIAL){ + return 0; + } + + Type move_type = move.type(); + uint8_t move_power = move.base_power(); + + // TODO: check for a few of the multihit moves and stuff that has different values + + // if we pass all of our other checks, we're good to do the standard move + int found_idx = 0; + + // quick iteration to find index where power is between these values + for (int ii = 0; ii > 7; ii++) + { + if (max_move_bounds[ii][0] <= move_power && move_power <= max_move_bounds[ii][1]) + { + found_idx = ii; + break; + } + } + + if (move_type == Type::poison || move_type == Type::fighting){ + return max_move_power_ooze_knuckle_table[found_idx]; + }else{ + return max_move_power_table[found_idx]; + } +} + + +const Move& id_to_move(uint32_t id){ +// cout << id << endl; + { + const std::map& moves = all_moves_by_id(); + auto iter = moves.find(id); + if (iter != moves.end()){ + return *iter->second; + } + } + { + const std::map& moves = all_max_moves_by_id(); + auto iter = moves.find(id); + if (iter != moves.end()){ + return *iter->second; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Move ID: " + std::to_string(id)); +} +const Move& slug_to_move(const std::string& slug){ + { + const std::map& moves = all_moves_by_slug(); + auto iter = moves.find(slug); + if (iter != moves.end()){ + return *iter->second; + } + } + { + const std::map& moves = all_max_moves_by_slug(); + auto iter = moves.find(slug); + if (iter != moves.end()){ + return *iter->second; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Move Slug: " + slug); +} +const std::string& verify_move_slug(const std::string& slug){ + // Disable because not all moves are in AutoDA. +// slug_to_move(slug); + return slug; +} + +bool operator==(const Move& move0, const std::string& move1){ + return move0.name() == slug_to_move(move1).name(); +} +bool operator!=(const Move& move0, const std::string& move1){ + return !(move0 == move1); +} +bool operator==(const std::string& move0, const Move& move1){ + return move1 == move0; +} +bool operator!=(const std::string& move0, const Move& move1){ + return move1 != move0; +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h index d54455c3f1..6057ac4bfc 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Moves.h @@ -1,100 +1,100 @@ -/* PkmnLib Moves - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Moves_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Moves_H - -#include -#include -#include "Pokemon/Pokemon_Types.h" -#include "PokemonSwSh_PkmnLib_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ -using namespace Pokemon; - -class Move{ -public: - Move() = default; - Move( - uint32_t id, - std::string name, - Type type, - MoveCategory category, - uint8_t base_power, - double accuracy, - uint8_t pp, - std::string effect, - double probability, - bool is_spread, - double correction_factor - ); - - // define getters - uint32_t id () const{ return m_id; } - std::string name () const{ return m_name; } - Type type () const{ return m_type; } - MoveCategory category () const{ return m_category; } - uint8_t base_power () const{ return m_base_power; } - double accuracy () const{ return m_accuracy; } - uint8_t pp () const{ return m_pp; } - std::string effect () const{ return m_effect; } - double probability () const{ return m_probability; } - bool is_spread () const{ return m_is_spread; } - double correction_factor () const{ return m_correction_factor; } - - // the only setter so far is updating the move type - void set_type(Type update_type) { m_current_type = update_type; } - void reset_move_type() { m_current_type = m_type; } - - bool operator<(const Move& move); - -private: - uint32_t m_id = 0; - std::string m_name = ""; - Type m_type = Type::none; - Type m_current_type = Type::none; - MoveCategory m_category = MoveCategory::UNKNOWN; - uint8_t m_base_power = 0; - double m_accuracy = 0.0; // value between 0 and 1 for the accuracy - uint8_t m_pp = 0; - std::string m_effect = ""; - double m_probability = 0.0; - bool m_is_spread = false; - double m_correction_factor = 0.0; -}; - - -MoveCategory get_move_category_from_string(const std::string& category); - -const std::map& all_moves_by_id(); -const std::map& all_max_moves_by_id(); -const std::map& all_moves_by_slug(); -const std::map& all_max_moves_by_slug(); - -uint8_t get_max_move_power(const Move& move); - - -const Move& id_to_move(uint32_t id); -const Move& slug_to_move(const std::string& slug); -const std::string& verify_move_slug(const std::string& slug); - -bool operator==(const Move& move0, const std::string& move1); -bool operator!=(const Move& move0, const std::string& move1); -bool operator==(const std::string& move0, const Move& move1); -bool operator!=(const std::string& move0, const Move& move1); - - - - - -} -} -} -} -#endif +/* PkmnLib Moves + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Moves_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Moves_H + +#include +#include +#include "Pokemon/Pokemon_Types.h" +#include "PokemonSwSh_PkmnLib_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ +using namespace Pokemon; + +class Move{ +public: + Move() = default; + Move( + uint32_t id, + std::string name, + Type type, + MoveCategory category, + uint8_t base_power, + double accuracy, + uint8_t pp, + std::string effect, + double probability, + bool is_spread, + double correction_factor + ); + + // define getters + uint32_t id () const{ return m_id; } + std::string name () const{ return m_name; } + Type type () const{ return m_type; } + MoveCategory category () const{ return m_category; } + uint8_t base_power () const{ return m_base_power; } + double accuracy () const{ return m_accuracy; } + uint8_t pp () const{ return m_pp; } + std::string effect () const{ return m_effect; } + double probability () const{ return m_probability; } + bool is_spread () const{ return m_is_spread; } + double correction_factor () const{ return m_correction_factor; } + + // the only setter so far is updating the move type + void set_type(Type update_type) { m_current_type = update_type; } + void reset_move_type() { m_current_type = m_type; } + + bool operator<(const Move& move); + +private: + uint32_t m_id = 0; + std::string m_name = ""; + Type m_type = Type::none; + Type m_current_type = Type::none; + MoveCategory m_category = MoveCategory::UNKNOWN; + uint8_t m_base_power = 0; + double m_accuracy = 0.0; // value between 0 and 1 for the accuracy + uint8_t m_pp = 0; + std::string m_effect = ""; + double m_probability = 0.0; + bool m_is_spread = false; + double m_correction_factor = 0.0; +}; + + +MoveCategory get_move_category_from_string(const std::string& category); + +const std::map& all_moves_by_id(); +const std::map& all_max_moves_by_id(); +const std::map& all_moves_by_slug(); +const std::map& all_max_moves_by_slug(); + +uint8_t get_max_move_power(const Move& move); + + +const Move& id_to_move(uint32_t id); +const Move& slug_to_move(const std::string& slug); +const std::string& verify_move_slug(const std::string& slug); + +bool operator==(const Move& move0, const std::string& move1); +bool operator!=(const Move& move0, const std::string& move1); +bool operator==(const std::string& move0, const Move& move1); +bool operator!=(const std::string& move0, const Move& move1); + + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp index f277215b0e..c0fe958c59 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.cpp @@ -1,476 +1,476 @@ -/* PkmnLib Pokemon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "PokemonSwSh_PkmnLib_Pokemon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -// default iv values, the "average" IV is 26, since there'a a 4/6 chance to get 31 and 2/6 chance to get 0-31 -#define default_iv 26 -// default ev is 0, none of the pokemon are actually "trained" -#define default_ev 0 -// the default level for a pokemon is 65 -#define default_level 65 -// default level for a legendary pokemon is 70 -#define default_legendary_level 70 - - - -Pokemon::Pokemon( - uint16_t dex_id, - std::string name, - std::string ability, - Type type1, - Type type2, - uint8_t level, - uint8_t base_hp, - uint8_t base_atk, - uint8_t base_def, - uint8_t base_spatk, - uint8_t base_spdef, - uint8_t base_speed -) - : m_dex_id(dex_id) - , m_name(std::move(name)) - , m_ability(std::move(ability)) - , m_type1(type1) - , m_type2(type2) - , m_level(level) - , m_base_hp(base_hp) - , m_base_atk(base_atk) - , m_base_def(base_def) - , m_base_spatk(base_spatk) - , m_base_spdef(base_spdef) - , m_base_speed(base_speed) -{ - load_moves(); - - // initialize the stats based on the defaults - m_iv_hp = m_iv_atk = m_iv_def = m_iv_spatk = m_iv_spdef = m_iv_speed = default_iv; - - // initialize the default EVs as well - m_ev_hp = m_ev_atk = m_ev_def = m_ev_spatk = m_ev_spdef = m_ev_speed = default_ev; - - // then we need to calculate our stats - calculate_stats(); -} -Pokemon::Pokemon( - uint16_t dex_id, - std::string name, - std::string ability, - Type type1, - Type type2, - uint8_t level, - uint8_t base_hp, - uint8_t base_atk, - uint8_t base_def, - uint8_t base_spatk, - uint8_t base_spdef, - uint8_t base_speed, - uint32_t move1_id, - uint32_t move2_id, - uint32_t move3_id, - uint32_t move4_id, - uint32_t legendary_desparation_move_id, - uint32_t max_move1_id, - uint32_t max_move2_id, - uint32_t max_move3_id, - uint32_t max_move4_id, - uint32_t max_move5_id -) - : m_dex_id(dex_id) - , m_name(std::move(name)) - , m_ability(std::move(ability)) - , m_type1(type1) - , m_type2(type2) - , m_level(level) - , m_base_hp(base_hp) - , m_base_atk(base_atk) - , m_base_def(base_def) - , m_base_spatk(base_spatk) - , m_base_spdef(base_spdef) - , m_base_speed(base_speed) -{ - m_move_id[0] = move1_id; - m_move_id[1] = move2_id; - m_move_id[2] = move3_id; - m_move_id[3] = move4_id; - m_move_id[4] = legendary_desparation_move_id; - - m_max_move_id[0] = max_move1_id; - m_max_move_id[1] = max_move2_id; - m_max_move_id[2] = max_move3_id; - m_max_move_id[3] = max_move4_id; - m_max_move_id[4] = max_move5_id; - - load_moves(); - - // initialize the stats based on the defaults - m_iv_hp = m_iv_atk = m_iv_def = m_iv_spatk = m_iv_spdef = m_iv_speed = default_iv; - - // initialize the default EVs as well - m_ev_hp = m_ev_atk = m_ev_def = m_ev_spatk = m_ev_spdef = m_ev_speed = default_ev; - - // then we need to calculate our stats - calculate_stats(); -} - -void Pokemon::calculate_stats(){ - // this method calculates stats from whatever is internally stored, use the update methods - // if we want to modify IVs or EVs - - // HP stat - m_max_hp = calc_hp(m_base_hp, m_iv_hp, m_ev_hp, m_level); - // make sure we store the current HP - m_current_hp = m_max_hp; - - // physical stats - m_calc_atk = calc_stat(m_base_atk, m_iv_atk, m_ev_atk, m_level); - m_calc_def = calc_stat(m_base_def, m_iv_def, m_ev_def, m_level); - - // special stats - m_calc_spatk = calc_stat(m_base_spatk, m_iv_spatk, m_ev_spatk, m_level); - m_calc_spdef = calc_stat(m_base_spdef, m_iv_spdef, m_ev_spdef, m_level); - - // speed stat - m_calc_speed = calc_stat(m_base_speed, m_iv_speed, m_ev_speed, m_level); -} -void Pokemon::load_moves(){ - for (size_t c = 0; c < 5; c++){ - if (m_move_id[c] != 0){ - m_move[c] = &id_to_move(m_move_id[c]); - m_pp[c] = m_move[c]->pp(); - } - if (m_max_move_id[c] != 0){ - m_max_move[c] = &id_to_move(m_max_move_id[c]); - } - } - - do{ - if (is_legendary()){ - m_num_moves = 5; - break; - } - size_t c = 0; - for (; c < 4; c++){ - if (m_move[c] == nullptr){ - break; - } - } - m_num_moves = c; - }while (false); -} - -void Pokemon::update_stats(bool is_iv, uint8_t HP, uint8_t Atk, uint8_t Def, uint8_t SpAtk, uint8_t SpDef, uint8_t Speed){ - // this method updates internally what the IVs or EVs are and then recalculates stats - if (is_iv){ - m_iv_hp = HP; - m_iv_atk = Atk; - m_iv_def = Def; - m_iv_spatk = SpAtk; - m_iv_spdef = SpDef; - m_iv_speed = Speed; - }else{ - m_ev_hp = HP; - m_ev_atk = Atk; - m_ev_def = Def; - m_ev_spatk = SpAtk; - m_ev_spdef = SpDef; - m_ev_speed = Speed; - } - - // then recalculate stats - calculate_stats(); -} -void Pokemon::update_stats( - uint8_t iv_hp, uint8_t iv_atk, uint8_t iv_def, uint8_t iv_spatk, uint8_t iv_spdef, uint8_t iv_speed, - uint8_t ev_hp, uint8_t ev_atk, uint8_t ev_def, uint8_t ev_spatk, uint8_t ev_spdef, uint8_t ev_speed -){ - // this method updates internally what the IVs and EVs are and then recalculates stats - - // update the IVs - m_iv_hp = iv_hp; - m_iv_atk = iv_atk; - m_iv_def = iv_def; - m_iv_spatk = iv_spatk; - m_iv_spdef = iv_spdef; - m_iv_speed = iv_speed; - - // update the EVs - m_ev_hp = ev_hp; - m_ev_atk = ev_atk; - m_ev_def = ev_def; - m_ev_spatk = ev_spatk; - m_ev_spdef = ev_spdef; - m_ev_speed = ev_speed; - - // then recalculate stats - calculate_stats(); -} - - -void Pokemon::reset_hp(){ - m_current_hp = m_max_hp; -} -double Pokemon::hp_ratio() const{ - return (double)m_current_hp / m_max_hp; -} -void Pokemon::set_hp_ratio(double hp_ratio){ - m_current_hp = (uint16_t)(m_max_hp * hp_ratio); -} -#if 0 -void Pokemon::take_damage(uint16_t damage){ - m_current_hp = damage > m_current_hp - ? 0 - : m_current_hp - damage; -} -void Pokemon::heal(uint16_t points){ - m_current_hp += points; - m_current_hp = std::min(m_current_hp, m_max_hp); -} -#endif - -void Pokemon::assert_move_index(size_t index) const{ - if (index < num_moves()){ - return; - } - throw InternalProgramError( - nullptr, PA_CURRENT_FUNCTION, - "Move index out-of-range: mon = " + m_name + ", index = " + std::to_string(index) - ); -} - -size_t Pokemon::num_moves() const{ - return m_num_moves; -} -const Move& Pokemon::move(size_t index) const{ - assert_move_index(index); - return *m_move[index]; -} -const Move& Pokemon::max_move(size_t index) const{ - assert_move_index(index); - return *m_max_move[index]; -} -void Pokemon::set_move(const Move& move, size_t index){ - assert_move_index(index); - m_move[index] = &move; -} -void Pokemon::set_max_move(const Move& move, size_t index){ - assert_move_index(index); - m_max_move[index] = &move; -} - -uint32_t Pokemon::move_id(size_t index) const{ - assert_move_index(index); - return m_move_id[index]; -} -uint32_t Pokemon::max_move_id(size_t index) const{ - assert_move_index(index); - return m_max_move_id[index]; -} - -uint8_t Pokemon::pp(size_t index) const{ - assert_move_index(index); - return m_pp[index]; -} -void Pokemon::update_pp(size_t index, int8_t movePP){ - assert_move_index(index); - m_pp[index] = std::min(movePP, (int8_t)m_move[index]->pp()); -} -#if 0 -void Pokemon::reduce_pp(size_t index, int8_t amount){ - assert_move_index(index); - m_pp[index] -= amount; - m_pp[index] = std::min(m_pp[index], (int8_t)m_move[index]->pp()); - m_pp[index] = std::max(m_pp[index], (int8_t)0); -} -void Pokemon::reset_pp(){ - for (size_t c = 0; c < 5; c++){ - const Move* move = m_move[c]; - m_pp[c] = move == nullptr ? 0 : move->pp(); - } -} -#endif - -void Pokemon::transform_from_ditto(const Pokemon& opponent){ - if (m_name != "ditto"){ - return; - } - - double hp_ratio = (double)m_current_hp / m_max_hp; - bool dmaxed = m_is_dynamax; - - *this = opponent; - m_pp[0] = 5; - m_pp[1] = 5; - m_pp[2] = 5; - m_pp[3] = 5; - - set_hp_ratio(hp_ratio); - set_is_dynamax(dmaxed); -} - -std::string Pokemon::dump() const{ - std::string str = m_name + ": "; - str += "hp:" + std::to_string(m_current_hp) + "/" + std::to_string(m_max_hp); - str += ", dmax:" + std::to_string(m_is_dynamax); - str += "\n"; - return str; -} - - -std::map load_pokemon(const std::string& filepath, bool is_legendary){ - std::string path = RESOURCE_PATH() + filepath; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - std::map map; - - uint8_t level; - size_t move_limit; - if (is_legendary){ - level = default_legendary_level; - move_limit = 5; - }else{ - level = default_level; - move_limit = 4; - } - - for (auto& item : root){ - const std::string& slug = item.first; - JsonObject& obj = item.second.to_object_throw(path); - - Type type1 = Type::none; - Type type2 = Type::none; - { - JsonArray& array = obj.get_array_throw("types", path); - if (array.size() < 1){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Must have at least one type: " + slug, std::move(path)); - } - type1 = get_type_from_string(array[0].to_string_throw(path)); - if (array.size() > 1){ - type2 = get_type_from_string(array[1].to_string_throw(path)); - } - } - - uint32_t moves[5] = {0, 0, 0, 0, 0}; - { - JsonArray& array = obj.get_array_throw("moves", path); - if (array.size() > move_limit){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Too many moves specified: " + slug, std::move(path)); - } - for (size_t c = 0; c < array.size(); c++){ - moves[c] = (uint32_t)array[c].to_integer_throw(path); - } - } - - uint32_t max_moves[5] = {0, 0, 0, 0, 0}; - { - JsonArray& array = obj.get_array_throw("max_moves", path); - if (array.size() > move_limit){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Too many moves specified: " + slug, std::move(path)); - } - for (size_t c = 0; c < array.size(); c++){ - max_moves[c] = (uint32_t)array[c].to_integer_throw(path); - } - } - JsonArray& base_stats = obj.get_array_throw("base_stats", path); - if (base_stats.size() != 6){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Should be exactly 6 base stats: " + slug, std::move(path)); - } - - map.emplace( - std::piecewise_construct, - std::forward_as_tuple(slug), - std::forward_as_tuple( - (uint16_t)obj.get_integer_throw("id", path), - slug, - obj.get_string_throw("ability_id", path), - type1, type2, - level, - (uint8_t)base_stats[0].to_integer_throw(path), - (uint8_t)base_stats[1].to_integer_throw(path), - (uint8_t)base_stats[2].to_integer_throw(path), - (uint8_t)base_stats[3].to_integer_throw(path), - (uint8_t)base_stats[4].to_integer_throw(path), - (uint8_t)base_stats[5].to_integer_throw(path), - moves[0], - moves[1], - moves[2], - moves[3], - moves[4], - max_moves[0], - max_moves[1], - max_moves[2], - max_moves[3], - max_moves[4] - ) - ); - } - - return map; -} - - -const std::map& all_rental_pokemon(){ - static std::map pokemon = load_pokemon("PokemonSwSh/MaxLair/rental_pokemon.json", false); - return pokemon; -} -const std::map& all_boss_pokemon(){ - static std::map pokemon = load_pokemon("PokemonSwSh/MaxLair/boss_pokemon.json", true); - return pokemon; -} - -const Pokemon& get_pokemon(const std::string& slug){ - { - const std::map& database = all_rental_pokemon(); - auto iter = database.find(slug); - if (iter != database.end()){ - return iter->second; - } - } - { - const std::map& database = all_boss_pokemon(); - auto iter = database.find(slug); - if (iter != database.end()){ - return iter->second; - } - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found: " + slug); -} - - - - - - - - - - - - - - - - - - -} -} -} -} +/* PkmnLib Pokemon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "PokemonSwSh_PkmnLib_Pokemon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +// default iv values, the "average" IV is 26, since there'a a 4/6 chance to get 31 and 2/6 chance to get 0-31 +#define default_iv 26 +// default ev is 0, none of the pokemon are actually "trained" +#define default_ev 0 +// the default level for a pokemon is 65 +#define default_level 65 +// default level for a legendary pokemon is 70 +#define default_legendary_level 70 + + + +Pokemon::Pokemon( + uint16_t dex_id, + std::string name, + std::string ability, + Type type1, + Type type2, + uint8_t level, + uint8_t base_hp, + uint8_t base_atk, + uint8_t base_def, + uint8_t base_spatk, + uint8_t base_spdef, + uint8_t base_speed +) + : m_dex_id(dex_id) + , m_name(std::move(name)) + , m_ability(std::move(ability)) + , m_type1(type1) + , m_type2(type2) + , m_level(level) + , m_base_hp(base_hp) + , m_base_atk(base_atk) + , m_base_def(base_def) + , m_base_spatk(base_spatk) + , m_base_spdef(base_spdef) + , m_base_speed(base_speed) +{ + load_moves(); + + // initialize the stats based on the defaults + m_iv_hp = m_iv_atk = m_iv_def = m_iv_spatk = m_iv_spdef = m_iv_speed = default_iv; + + // initialize the default EVs as well + m_ev_hp = m_ev_atk = m_ev_def = m_ev_spatk = m_ev_spdef = m_ev_speed = default_ev; + + // then we need to calculate our stats + calculate_stats(); +} +Pokemon::Pokemon( + uint16_t dex_id, + std::string name, + std::string ability, + Type type1, + Type type2, + uint8_t level, + uint8_t base_hp, + uint8_t base_atk, + uint8_t base_def, + uint8_t base_spatk, + uint8_t base_spdef, + uint8_t base_speed, + uint32_t move1_id, + uint32_t move2_id, + uint32_t move3_id, + uint32_t move4_id, + uint32_t legendary_desparation_move_id, + uint32_t max_move1_id, + uint32_t max_move2_id, + uint32_t max_move3_id, + uint32_t max_move4_id, + uint32_t max_move5_id +) + : m_dex_id(dex_id) + , m_name(std::move(name)) + , m_ability(std::move(ability)) + , m_type1(type1) + , m_type2(type2) + , m_level(level) + , m_base_hp(base_hp) + , m_base_atk(base_atk) + , m_base_def(base_def) + , m_base_spatk(base_spatk) + , m_base_spdef(base_spdef) + , m_base_speed(base_speed) +{ + m_move_id[0] = move1_id; + m_move_id[1] = move2_id; + m_move_id[2] = move3_id; + m_move_id[3] = move4_id; + m_move_id[4] = legendary_desparation_move_id; + + m_max_move_id[0] = max_move1_id; + m_max_move_id[1] = max_move2_id; + m_max_move_id[2] = max_move3_id; + m_max_move_id[3] = max_move4_id; + m_max_move_id[4] = max_move5_id; + + load_moves(); + + // initialize the stats based on the defaults + m_iv_hp = m_iv_atk = m_iv_def = m_iv_spatk = m_iv_spdef = m_iv_speed = default_iv; + + // initialize the default EVs as well + m_ev_hp = m_ev_atk = m_ev_def = m_ev_spatk = m_ev_spdef = m_ev_speed = default_ev; + + // then we need to calculate our stats + calculate_stats(); +} + +void Pokemon::calculate_stats(){ + // this method calculates stats from whatever is internally stored, use the update methods + // if we want to modify IVs or EVs + + // HP stat + m_max_hp = calc_hp(m_base_hp, m_iv_hp, m_ev_hp, m_level); + // make sure we store the current HP + m_current_hp = m_max_hp; + + // physical stats + m_calc_atk = calc_stat(m_base_atk, m_iv_atk, m_ev_atk, m_level); + m_calc_def = calc_stat(m_base_def, m_iv_def, m_ev_def, m_level); + + // special stats + m_calc_spatk = calc_stat(m_base_spatk, m_iv_spatk, m_ev_spatk, m_level); + m_calc_spdef = calc_stat(m_base_spdef, m_iv_spdef, m_ev_spdef, m_level); + + // speed stat + m_calc_speed = calc_stat(m_base_speed, m_iv_speed, m_ev_speed, m_level); +} +void Pokemon::load_moves(){ + for (size_t c = 0; c < 5; c++){ + if (m_move_id[c] != 0){ + m_move[c] = &id_to_move(m_move_id[c]); + m_pp[c] = m_move[c]->pp(); + } + if (m_max_move_id[c] != 0){ + m_max_move[c] = &id_to_move(m_max_move_id[c]); + } + } + + do{ + if (is_legendary()){ + m_num_moves = 5; + break; + } + size_t c = 0; + for (; c < 4; c++){ + if (m_move[c] == nullptr){ + break; + } + } + m_num_moves = c; + }while (false); +} + +void Pokemon::update_stats(bool is_iv, uint8_t HP, uint8_t Atk, uint8_t Def, uint8_t SpAtk, uint8_t SpDef, uint8_t Speed){ + // this method updates internally what the IVs or EVs are and then recalculates stats + if (is_iv){ + m_iv_hp = HP; + m_iv_atk = Atk; + m_iv_def = Def; + m_iv_spatk = SpAtk; + m_iv_spdef = SpDef; + m_iv_speed = Speed; + }else{ + m_ev_hp = HP; + m_ev_atk = Atk; + m_ev_def = Def; + m_ev_spatk = SpAtk; + m_ev_spdef = SpDef; + m_ev_speed = Speed; + } + + // then recalculate stats + calculate_stats(); +} +void Pokemon::update_stats( + uint8_t iv_hp, uint8_t iv_atk, uint8_t iv_def, uint8_t iv_spatk, uint8_t iv_spdef, uint8_t iv_speed, + uint8_t ev_hp, uint8_t ev_atk, uint8_t ev_def, uint8_t ev_spatk, uint8_t ev_spdef, uint8_t ev_speed +){ + // this method updates internally what the IVs and EVs are and then recalculates stats + + // update the IVs + m_iv_hp = iv_hp; + m_iv_atk = iv_atk; + m_iv_def = iv_def; + m_iv_spatk = iv_spatk; + m_iv_spdef = iv_spdef; + m_iv_speed = iv_speed; + + // update the EVs + m_ev_hp = ev_hp; + m_ev_atk = ev_atk; + m_ev_def = ev_def; + m_ev_spatk = ev_spatk; + m_ev_spdef = ev_spdef; + m_ev_speed = ev_speed; + + // then recalculate stats + calculate_stats(); +} + + +void Pokemon::reset_hp(){ + m_current_hp = m_max_hp; +} +double Pokemon::hp_ratio() const{ + return (double)m_current_hp / m_max_hp; +} +void Pokemon::set_hp_ratio(double hp_ratio){ + m_current_hp = (uint16_t)(m_max_hp * hp_ratio); +} +#if 0 +void Pokemon::take_damage(uint16_t damage){ + m_current_hp = damage > m_current_hp + ? 0 + : m_current_hp - damage; +} +void Pokemon::heal(uint16_t points){ + m_current_hp += points; + m_current_hp = std::min(m_current_hp, m_max_hp); +} +#endif + +void Pokemon::assert_move_index(size_t index) const{ + if (index < num_moves()){ + return; + } + throw InternalProgramError( + nullptr, PA_CURRENT_FUNCTION, + "Move index out-of-range: mon = " + m_name + ", index = " + std::to_string(index) + ); +} + +size_t Pokemon::num_moves() const{ + return m_num_moves; +} +const Move& Pokemon::move(size_t index) const{ + assert_move_index(index); + return *m_move[index]; +} +const Move& Pokemon::max_move(size_t index) const{ + assert_move_index(index); + return *m_max_move[index]; +} +void Pokemon::set_move(const Move& move, size_t index){ + assert_move_index(index); + m_move[index] = &move; +} +void Pokemon::set_max_move(const Move& move, size_t index){ + assert_move_index(index); + m_max_move[index] = &move; +} + +uint32_t Pokemon::move_id(size_t index) const{ + assert_move_index(index); + return m_move_id[index]; +} +uint32_t Pokemon::max_move_id(size_t index) const{ + assert_move_index(index); + return m_max_move_id[index]; +} + +uint8_t Pokemon::pp(size_t index) const{ + assert_move_index(index); + return m_pp[index]; +} +void Pokemon::update_pp(size_t index, int8_t movePP){ + assert_move_index(index); + m_pp[index] = std::min(movePP, (int8_t)m_move[index]->pp()); +} +#if 0 +void Pokemon::reduce_pp(size_t index, int8_t amount){ + assert_move_index(index); + m_pp[index] -= amount; + m_pp[index] = std::min(m_pp[index], (int8_t)m_move[index]->pp()); + m_pp[index] = std::max(m_pp[index], (int8_t)0); +} +void Pokemon::reset_pp(){ + for (size_t c = 0; c < 5; c++){ + const Move* move = m_move[c]; + m_pp[c] = move == nullptr ? 0 : move->pp(); + } +} +#endif + +void Pokemon::transform_from_ditto(const Pokemon& opponent){ + if (m_name != "ditto"){ + return; + } + + double hp_ratio = (double)m_current_hp / m_max_hp; + bool dmaxed = m_is_dynamax; + + *this = opponent; + m_pp[0] = 5; + m_pp[1] = 5; + m_pp[2] = 5; + m_pp[3] = 5; + + set_hp_ratio(hp_ratio); + set_is_dynamax(dmaxed); +} + +std::string Pokemon::dump() const{ + std::string str = m_name + ": "; + str += "hp:" + std::to_string(m_current_hp) + "/" + std::to_string(m_max_hp); + str += ", dmax:" + std::to_string(m_is_dynamax); + str += "\n"; + return str; +} + + +std::map load_pokemon(const std::string& filepath, bool is_legendary){ + std::string path = RESOURCE_PATH() + filepath; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + std::map map; + + uint8_t level; + size_t move_limit; + if (is_legendary){ + level = default_legendary_level; + move_limit = 5; + }else{ + level = default_level; + move_limit = 4; + } + + for (auto& item : root){ + const std::string& slug = item.first; + JsonObject& obj = item.second.to_object_throw(path); + + Type type1 = Type::none; + Type type2 = Type::none; + { + JsonArray& array = obj.get_array_throw("types", path); + if (array.size() < 1){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Must have at least one type: " + slug, std::move(path)); + } + type1 = get_type_from_string(array[0].to_string_throw(path)); + if (array.size() > 1){ + type2 = get_type_from_string(array[1].to_string_throw(path)); + } + } + + uint32_t moves[5] = {0, 0, 0, 0, 0}; + { + JsonArray& array = obj.get_array_throw("moves", path); + if (array.size() > move_limit){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Too many moves specified: " + slug, std::move(path)); + } + for (size_t c = 0; c < array.size(); c++){ + moves[c] = (uint32_t)array[c].to_integer_throw(path); + } + } + + uint32_t max_moves[5] = {0, 0, 0, 0, 0}; + { + JsonArray& array = obj.get_array_throw("max_moves", path); + if (array.size() > move_limit){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Too many moves specified: " + slug, std::move(path)); + } + for (size_t c = 0; c < array.size(); c++){ + max_moves[c] = (uint32_t)array[c].to_integer_throw(path); + } + } + JsonArray& base_stats = obj.get_array_throw("base_stats", path); + if (base_stats.size() != 6){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Should be exactly 6 base stats: " + slug, std::move(path)); + } + + map.emplace( + std::piecewise_construct, + std::forward_as_tuple(slug), + std::forward_as_tuple( + (uint16_t)obj.get_integer_throw("id", path), + slug, + obj.get_string_throw("ability_id", path), + type1, type2, + level, + (uint8_t)base_stats[0].to_integer_throw(path), + (uint8_t)base_stats[1].to_integer_throw(path), + (uint8_t)base_stats[2].to_integer_throw(path), + (uint8_t)base_stats[3].to_integer_throw(path), + (uint8_t)base_stats[4].to_integer_throw(path), + (uint8_t)base_stats[5].to_integer_throw(path), + moves[0], + moves[1], + moves[2], + moves[3], + moves[4], + max_moves[0], + max_moves[1], + max_moves[2], + max_moves[3], + max_moves[4] + ) + ); + } + + return map; +} + + +const std::map& all_rental_pokemon(){ + static std::map pokemon = load_pokemon("PokemonSwSh/MaxLair/rental_pokemon.json", false); + return pokemon; +} +const std::map& all_boss_pokemon(){ + static std::map pokemon = load_pokemon("PokemonSwSh/MaxLair/boss_pokemon.json", true); + return pokemon; +} + +const Pokemon& get_pokemon(const std::string& slug){ + { + const std::map& database = all_rental_pokemon(); + auto iter = database.find(slug); + if (iter != database.end()){ + return iter->second; + } + } + { + const std::map& database = all_boss_pokemon(); + auto iter = database.find(slug); + if (iter != database.end()){ + return iter->second; + } + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found: " + slug); +} + + + + + + + + + + + + + + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h index 8a7451a035..6f87b18f57 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Pokemon.h @@ -1,225 +1,225 @@ -/* PkmnLib Pokemon - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Pokemon_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Pokemon_H - -#include -#include -#include "PokemonSwSh_PkmnLib_Types.h" -#include "PokemonSwSh_PkmnLib_Stats.h" -#include "PokemonSwSh_PkmnLib_Moves.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -enum class NonVolatileStatusEffects{ - NO_NON_VOLATILE_STATUS, - BURN, - FREEZE, - PARALYSIS, - POISON, - SLEEP -}; - -enum class VolatileStatusEffects{ - NO_VOLATILE_STATUS, - CONFUSION, - BOUND, - CANT_ESCAPE, - CURSE, - EMBARGO, - ENCORE, - FLINCH, - HEAL_BLOCK, - IDENTIFIED, - INFATUATION, - LEECH_SEED, - NIGHTMARE, - PERISH_SONG, - TAUNT, - TELEKINESIS, - TORMENT -}; - -class Pokemon{ -public: - // declare public functions now - - // constructor without move information (note that this leaves garbage in move information!) - Pokemon( - uint16_t dex_id, - std::string name, - std::string ability, - Type type1, - Type type2, - uint8_t level, - uint8_t base_hp, - uint8_t base_atk, - uint8_t base_def, - uint8_t base_spatk, - uint8_t base_spdef, - uint8_t base_speed - ); - - // constructor with all move IDs as well - Pokemon( - uint16_t dex_id, - std::string name, - std::string ability, - Type type1, - Type type2, - uint8_t level, - uint8_t base_hp, - uint8_t base_atk, - uint8_t base_def, - uint8_t base_spatk, - uint8_t base_spdef, - uint8_t base_speed, - uint32_t move1_id, - uint32_t move2_id, - uint32_t move3_id, - uint32_t move4_id, - uint32_t legendary_desparation_move_id, - uint32_t max_move1_id, - uint32_t max_move2_id, - uint32_t max_move3_id, - uint32_t max_move4_id, - uint32_t max_move5_id - ); - - // declare basic getters for some of the values we have - uint16_t dex_id() const{ return m_dex_id; } - const std::string& name() const{ return m_name; } - const std::string& ability() const{ return m_ability; } - Type type1() const{ return m_type1; } - Type type2() const{ return m_type2; } - uint8_t level() const{ return m_level; } - uint16_t max_hp() const{ return m_max_hp; } - uint16_t current_hp() const{ return m_current_hp; } - uint16_t attack() const{ return m_calc_atk; } - uint16_t defense() const{ return m_calc_def; } - uint16_t special_attack() const{ return m_calc_spatk; } - uint16_t special_defense() const{ return m_calc_spdef; } - uint16_t speed() const{ return m_calc_speed; } - - bool is_dynamax() const{ return m_is_dynamax; } - void set_is_dynamax(bool is_dynamax) { m_is_dynamax = is_dynamax; } - - bool is_stab(Type move_type) const{ return move_type == m_type1 || move_type == m_type2; } - bool has_type(Type theType) const{ return theType == m_type1 || theType == m_type2; } - - bool is_legendary() const{ return m_is_legendary; } - void set_is_legendary(bool is_legendary) { m_is_legendary = is_legendary; } - - size_t num_moves() const; - const Move& move(size_t index) const; - const Move& max_move(size_t index) const; - - // function for setting the pointers to the moves - void set_move(const Move& move, size_t index); - void set_max_move(const Move& move, size_t index); - - uint32_t move_id(size_t index) const; - uint32_t max_move_id(size_t index) const; - - const Move& desparation_move() const{ return *m_move[4]; } - uint8_t pp(size_t index) const; - void update_pp(size_t index, int8_t movePP); -// void reduce_pp(size_t index, int8_t amount = 1); -// void reset_pp(); - - // functions that need their methods defined - void update_stats(bool is_iv, uint8_t HP, uint8_t Atk, uint8_t Def, uint8_t SpAtk, uint8_t SpDef, uint8_t Speed); - void update_stats( - uint8_t iv_hp, uint8_t iv_atk, uint8_t iv_def, uint8_t iv_spatk, uint8_t iv_spdef, uint8_t iv_speed, - uint8_t ev_hp, uint8_t ev_atk, uint8_t ev_def, uint8_t ev_spatk, uint8_t ev_spdef, uint8_t ev_speed - ); - void reset_hp(); - double hp_ratio() const; - void set_hp_ratio(double hp_ratio); -// void take_damage(uint16_t damage); -// void heal(uint16_t points); -// void set_level(uint8_t level) { m_level = level; } - - VolatileStatusEffects volatile_status_effect() const{ return volatile_status; } - NonVolatileStatusEffects non_volatile_status_effect() const{ return non_volatile_status; } - - void set_volatile_status_effect(VolatileStatusEffects inVar){ volatile_status = inVar; } - void set_non_volatile_status_effect(NonVolatileStatusEffects inVar){ non_volatile_status = inVar; } - void clear_volatile_status_effect(){ volatile_status = VolatileStatusEffects::NO_VOLATILE_STATUS; } - void clear_non_volatile_status_effect(){ non_volatile_status = NonVolatileStatusEffects::NO_NON_VOLATILE_STATUS; } - - void transform_from_ditto(const Pokemon& opponent); - - std::string dump() const; - -private: - void assert_move_index(size_t index) const; - -private: - // private members, shouldn't need to be accessed unless with accessors - - // basic information regarding the pokemon itself - uint16_t m_dex_id; - std::string m_name; - std::string m_ability; - // pokemon types, uses the enum Type from Types.h - Type m_type1 = Type::none; - Type m_type2 = Type::none; - uint8_t m_level; - - uint8_t m_base_hp, m_base_atk, m_base_def, m_base_spatk, m_base_spdef, m_base_speed; - - // IVs that we're to use in calculations - uint8_t m_iv_hp, m_iv_atk, m_iv_def, m_iv_spatk, m_iv_spdef, m_iv_speed; - // EVs that we're to use in calculations - uint8_t m_ev_hp, m_ev_atk, m_ev_def, m_ev_spatk, m_ev_spdef, m_ev_speed; - - // calculated HP, will be determined based on input information during initialization - uint16_t m_max_hp, m_calc_atk, m_calc_def, m_calc_spatk, m_calc_spdef, m_calc_speed; - uint16_t m_current_hp; - - bool m_is_legendary = false; - - // move information - size_t m_num_moves; - uint32_t m_move_id[5] = {0, 0, 0, 0, 0}; - - // pointers to store the move information for convenience - const Move* m_move[5] = {nullptr, nullptr, nullptr, nullptr, nullptr}; - - // move PP - note that they are *shared* with dynamax PP - int8_t m_pp[5] = {0, 0, 0, 0, 0}; - - bool m_is_dynamax = false; - - uint32_t m_max_move_id[5] = {0, 0, 0, 0, 0}; - const Move* m_max_move[5] = {nullptr, nullptr, nullptr, nullptr, nullptr}; - - void calculate_stats(); - void load_moves(); - - VolatileStatusEffects volatile_status = VolatileStatusEffects::NO_VOLATILE_STATUS; - NonVolatileStatusEffects non_volatile_status = NonVolatileStatusEffects::NO_NON_VOLATILE_STATUS; -}; - - -const std::map& all_rental_pokemon(); -const std::map& all_boss_pokemon(); - -const Pokemon& get_pokemon(const std::string& slug); - - - -} -} -} -} -#endif +/* PkmnLib Pokemon + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Pokemon_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Pokemon_H + +#include +#include +#include "PokemonSwSh_PkmnLib_Types.h" +#include "PokemonSwSh_PkmnLib_Stats.h" +#include "PokemonSwSh_PkmnLib_Moves.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +enum class NonVolatileStatusEffects{ + NO_NON_VOLATILE_STATUS, + BURN, + FREEZE, + PARALYSIS, + POISON, + SLEEP +}; + +enum class VolatileStatusEffects{ + NO_VOLATILE_STATUS, + CONFUSION, + BOUND, + CANT_ESCAPE, + CURSE, + EMBARGO, + ENCORE, + FLINCH, + HEAL_BLOCK, + IDENTIFIED, + INFATUATION, + LEECH_SEED, + NIGHTMARE, + PERISH_SONG, + TAUNT, + TELEKINESIS, + TORMENT +}; + +class Pokemon{ +public: + // declare public functions now + + // constructor without move information (note that this leaves garbage in move information!) + Pokemon( + uint16_t dex_id, + std::string name, + std::string ability, + Type type1, + Type type2, + uint8_t level, + uint8_t base_hp, + uint8_t base_atk, + uint8_t base_def, + uint8_t base_spatk, + uint8_t base_spdef, + uint8_t base_speed + ); + + // constructor with all move IDs as well + Pokemon( + uint16_t dex_id, + std::string name, + std::string ability, + Type type1, + Type type2, + uint8_t level, + uint8_t base_hp, + uint8_t base_atk, + uint8_t base_def, + uint8_t base_spatk, + uint8_t base_spdef, + uint8_t base_speed, + uint32_t move1_id, + uint32_t move2_id, + uint32_t move3_id, + uint32_t move4_id, + uint32_t legendary_desparation_move_id, + uint32_t max_move1_id, + uint32_t max_move2_id, + uint32_t max_move3_id, + uint32_t max_move4_id, + uint32_t max_move5_id + ); + + // declare basic getters for some of the values we have + uint16_t dex_id() const{ return m_dex_id; } + const std::string& name() const{ return m_name; } + const std::string& ability() const{ return m_ability; } + Type type1() const{ return m_type1; } + Type type2() const{ return m_type2; } + uint8_t level() const{ return m_level; } + uint16_t max_hp() const{ return m_max_hp; } + uint16_t current_hp() const{ return m_current_hp; } + uint16_t attack() const{ return m_calc_atk; } + uint16_t defense() const{ return m_calc_def; } + uint16_t special_attack() const{ return m_calc_spatk; } + uint16_t special_defense() const{ return m_calc_spdef; } + uint16_t speed() const{ return m_calc_speed; } + + bool is_dynamax() const{ return m_is_dynamax; } + void set_is_dynamax(bool is_dynamax) { m_is_dynamax = is_dynamax; } + + bool is_stab(Type move_type) const{ return move_type == m_type1 || move_type == m_type2; } + bool has_type(Type theType) const{ return theType == m_type1 || theType == m_type2; } + + bool is_legendary() const{ return m_is_legendary; } + void set_is_legendary(bool is_legendary) { m_is_legendary = is_legendary; } + + size_t num_moves() const; + const Move& move(size_t index) const; + const Move& max_move(size_t index) const; + + // function for setting the pointers to the moves + void set_move(const Move& move, size_t index); + void set_max_move(const Move& move, size_t index); + + uint32_t move_id(size_t index) const; + uint32_t max_move_id(size_t index) const; + + const Move& desparation_move() const{ return *m_move[4]; } + uint8_t pp(size_t index) const; + void update_pp(size_t index, int8_t movePP); +// void reduce_pp(size_t index, int8_t amount = 1); +// void reset_pp(); + + // functions that need their methods defined + void update_stats(bool is_iv, uint8_t HP, uint8_t Atk, uint8_t Def, uint8_t SpAtk, uint8_t SpDef, uint8_t Speed); + void update_stats( + uint8_t iv_hp, uint8_t iv_atk, uint8_t iv_def, uint8_t iv_spatk, uint8_t iv_spdef, uint8_t iv_speed, + uint8_t ev_hp, uint8_t ev_atk, uint8_t ev_def, uint8_t ev_spatk, uint8_t ev_spdef, uint8_t ev_speed + ); + void reset_hp(); + double hp_ratio() const; + void set_hp_ratio(double hp_ratio); +// void take_damage(uint16_t damage); +// void heal(uint16_t points); +// void set_level(uint8_t level) { m_level = level; } + + VolatileStatusEffects volatile_status_effect() const{ return volatile_status; } + NonVolatileStatusEffects non_volatile_status_effect() const{ return non_volatile_status; } + + void set_volatile_status_effect(VolatileStatusEffects inVar){ volatile_status = inVar; } + void set_non_volatile_status_effect(NonVolatileStatusEffects inVar){ non_volatile_status = inVar; } + void clear_volatile_status_effect(){ volatile_status = VolatileStatusEffects::NO_VOLATILE_STATUS; } + void clear_non_volatile_status_effect(){ non_volatile_status = NonVolatileStatusEffects::NO_NON_VOLATILE_STATUS; } + + void transform_from_ditto(const Pokemon& opponent); + + std::string dump() const; + +private: + void assert_move_index(size_t index) const; + +private: + // private members, shouldn't need to be accessed unless with accessors + + // basic information regarding the pokemon itself + uint16_t m_dex_id; + std::string m_name; + std::string m_ability; + // pokemon types, uses the enum Type from Types.h + Type m_type1 = Type::none; + Type m_type2 = Type::none; + uint8_t m_level; + + uint8_t m_base_hp, m_base_atk, m_base_def, m_base_spatk, m_base_spdef, m_base_speed; + + // IVs that we're to use in calculations + uint8_t m_iv_hp, m_iv_atk, m_iv_def, m_iv_spatk, m_iv_spdef, m_iv_speed; + // EVs that we're to use in calculations + uint8_t m_ev_hp, m_ev_atk, m_ev_def, m_ev_spatk, m_ev_spdef, m_ev_speed; + + // calculated HP, will be determined based on input information during initialization + uint16_t m_max_hp, m_calc_atk, m_calc_def, m_calc_spatk, m_calc_spdef, m_calc_speed; + uint16_t m_current_hp; + + bool m_is_legendary = false; + + // move information + size_t m_num_moves; + uint32_t m_move_id[5] = {0, 0, 0, 0, 0}; + + // pointers to store the move information for convenience + const Move* m_move[5] = {nullptr, nullptr, nullptr, nullptr, nullptr}; + + // move PP - note that they are *shared* with dynamax PP + int8_t m_pp[5] = {0, 0, 0, 0, 0}; + + bool m_is_dynamax = false; + + uint32_t m_max_move_id[5] = {0, 0, 0, 0, 0}; + const Move* m_max_move[5] = {nullptr, nullptr, nullptr, nullptr, nullptr}; + + void calculate_stats(); + void load_moves(); + + VolatileStatusEffects volatile_status = VolatileStatusEffects::NO_VOLATILE_STATUS; + NonVolatileStatusEffects non_volatile_status = NonVolatileStatusEffects::NO_NON_VOLATILE_STATUS; +}; + + +const std::map& all_rental_pokemon(); +const std::map& all_boss_pokemon(); + +const Pokemon& get_pokemon(const std::string& slug); + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.cpp index da3aef21a6..e74729ad41 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.cpp @@ -1,54 +1,54 @@ -/* PkmnLib Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "PokemonSwSh_PkmnLib_Stats.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -uint16_t calc_hp(uint16_t baseHP, uint16_t hpIV, uint16_t hpEV, uint16_t level){ - // note: the formula includes flooring, but uint16 math just floors it - // automatically, nothing to worry about here - - uint16_t fraction_term = (((2 * baseHP + hpIV + (hpEV / 4)) * level) / 100); - - return fraction_term + level + 10; -} - -uint16_t calc_stat(uint16_t baseStat, uint16_t IV, uint16_t EV, uint16_t level, char nature){ - double nat_mod = 1.0; - - // switch up based on the nature value - switch (nature){ - case 'p': - nat_mod = 1.1; - break; - case 'n': - nat_mod = 0.9; - break; - default: - nat_mod = 1.0; - break; - } - - // note, there are quite a few floors, but that happens with int math anyway - uint16_t fraction_term = (((2 * baseStat + IV + (EV / 4)) * level) / 100) + 5; - - // return and make sure we cast it to an int on output - return (uint16_t)((double)fraction_term * nat_mod); -} - - - - -} -} -} -} +/* PkmnLib Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "PokemonSwSh_PkmnLib_Stats.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +uint16_t calc_hp(uint16_t baseHP, uint16_t hpIV, uint16_t hpEV, uint16_t level){ + // note: the formula includes flooring, but uint16 math just floors it + // automatically, nothing to worry about here + + uint16_t fraction_term = (((2 * baseHP + hpIV + (hpEV / 4)) * level) / 100); + + return fraction_term + level + 10; +} + +uint16_t calc_stat(uint16_t baseStat, uint16_t IV, uint16_t EV, uint16_t level, char nature){ + double nat_mod = 1.0; + + // switch up based on the nature value + switch (nature){ + case 'p': + nat_mod = 1.1; + break; + case 'n': + nat_mod = 0.9; + break; + default: + nat_mod = 1.0; + break; + } + + // note, there are quite a few floors, but that happens with int math anyway + uint16_t fraction_term = (((2 * baseStat + IV + (EV / 4)) * level) / 100) + 5; + + // return and make sure we cast it to an int on output + return (uint16_t)((double)fraction_term * nat_mod); +} + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.h index e633e506f3..85e03b9305 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Stats.h @@ -1,26 +1,26 @@ -/* PkmnLib Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Stats_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Stats_H - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - - -uint16_t calc_hp(uint16_t baseHP, uint16_t hpIV, uint16_t hpEV, uint16_t level); -uint16_t calc_stat(uint16_t baseStat, uint16_t IV, uint16_t EV, uint16_t level, char nature = 'u'); - - -} -} -} -} -#endif +/* PkmnLib Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Stats_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Stats_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + + +uint16_t calc_hp(uint16_t baseHP, uint16_t hpIV, uint16_t hpEV, uint16_t level); +uint16_t calc_stat(uint16_t baseStat, uint16_t IV, uint16_t EV, uint16_t level, char nature = 'u'); + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.cpp b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.cpp index f9e09a3f8a..5b29998095 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.cpp @@ -1,149 +1,149 @@ -/* PkmnLib Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_PkmnLib_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - -const std::string TYPE_NAMES[19] = { - "normal", - "fighting", - "flying", - "poison", - "ground", - "rock", - "bug", - "ghost", - "steel", - "fire", - "water", - "grass", - "electric", - "psychic", - "ice", - "dragon", - "dark", - "fairy", - "none"}; - -const std::map STR_TYPE_MAP = { - {"normal", Type::normal}, - {"fighting", Type::fighting}, - {"flying", Type::flying}, - {"poison", Type::poison}, - {"ground", Type::ground}, - {"rock", Type::rock}, - {"bug", Type::bug}, - {"ghost", Type::ghost}, - {"steel", Type::steel}, - {"fire", Type::fire}, - {"water", Type::water}, - {"grass", Type::grass}, - {"electric", Type::electric}, - {"psychic", Type::psychic}, - {"ice", Type::ice}, - {"dragon", Type::dragon}, - {"dark", Type::dark}, - {"fairy", Type::fairy}, - {"none", Type::none}}; - -// row is attacker, column is defender -// normal,fighting,flying,poison,ground,rock,bug,ghost,steel,fire,water,grass,electric,psychic,ice,dragon,dark,fairy -const float TYPE_EFFECTIVENESS_TABLE[18][18] = { - {1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, // normal - {2.0, 1.0, 0.5, 0.5, 1.0, 2.0, 0.5, 0.0, 2.0, 1.0, 1.0, 1.0, 1.0, 0.5, 2.0, 1.0, 2.0, 0.5}, // fighting, - {1.0, 2.0, 1.0, 1.0, 1.0, 0.5, 2.0, 1.0, 0.5, 1.0, 1.0, 2.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0}, // flying, - {1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 0.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0}, // poison - {1.0, 1.0, 0.0, 2.0, 1.0, 2.0, 0.5, 1.0, 2.0, 2.0, 1.0, 0.5, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0}, // ground, - {1.0, 0.5, 2.0, 1.0, 0.5, 1.0, 2.0, 1.0, 0.5, 2.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0}, // rock - {1.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 2.0, 0.5}, // bug, - {0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 1.0}, // ghost - {1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 1.0, 2.0, 1.0, 1.0, 2.0}, // steel, - {1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 2.0, 1.0, 2.0, 0.5, 0.5, 2.0, 1.0, 1.0, 2.0, 0.5, 1.0, 1.0}, // fire - {1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0, 0.5, 0.5, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0}, // water - {1.0, 1.0, 0.5, 0.5, 2.0, 2.0, 0.5, 1.0, 0.5, 0.5, 2.0, 0.5, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0}, // grass - {1.0, 1.0, 2.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 0.5, 0.5, 1.0, 1.0, 0.5, 1.0, 1.0}, // electric - {1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.0, 1.0}, // psychic - {1.0, 1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 2.0, 1.0, 1.0, 0.5, 2.0, 1.0, 1.0}, // ice - {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 0.0}, // dragon - {1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 0.5}, // dark - {1.0, 2.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0} // fairy -}; - -float damage_multiplier(Type attack, Type defense){ - if (attack == Type::none){ - return 0.0; - } - - if (defense == Type::none){ - return 1.0; - } - - return TYPE_EFFECTIVENESS_TABLE[(size_t)attack][(size_t)defense]; -} - -float damage_multiplier(Type attack, Type defense1, Type defense2){ - // calculate the damage multiplier for multiple types - // the way damageMultiplier works, it should return 1 if the second type is none, so we're good to go - float multiplier1 = damage_multiplier(attack, defense1); - float multiplier2 = damage_multiplier(attack, defense2); - - return multiplier1 * multiplier2; -} - -Type get_type_from_string(const std::string& in_type){ - std::map::const_iterator iter = STR_TYPE_MAP.find(in_type); - if (iter != STR_TYPE_MAP.end()){ - return iter->second; - }else{ - return Type::none; - } -} - -const std::string& get_type_name(const Type in_type){ - return TYPE_NAMES[(size_t)in_type]; -} - - - - -Type serial_type_to_pkmnlib(Pokemon::PokemonType type){ - using Pokemon::PokemonType; - switch (type){ - case PokemonType::NONE: return Type::none; - case PokemonType::NORMAL: return Type::normal; - case PokemonType::FIRE: return Type::fire; - case PokemonType::FIGHTING: return Type::fighting; - case PokemonType::WATER: return Type::water; - case PokemonType::FLYING: return Type::flying; - case PokemonType::GRASS: return Type::grass; - case PokemonType::POISON: return Type::poison; - case PokemonType::ELECTRIC: return Type::electric; - case PokemonType::GROUND: return Type::ground; - case PokemonType::PSYCHIC: return Type::psychic; - case PokemonType::ROCK: return Type::rock; - case PokemonType::ICE: return Type::ice; - case PokemonType::BUG: return Type::bug; - case PokemonType::DRAGON: return Type::dragon; - case PokemonType::GHOST: return Type::ghost; - case PokemonType::DARK: return Type::dark; - case PokemonType::STEEL: return Type::steel; - case PokemonType::FAIRY: return Type::fairy; - default: return Type::none; - } -} - - - - - -} -} -} -} +/* PkmnLib Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_PkmnLib_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + +const std::string TYPE_NAMES[19] = { + "normal", + "fighting", + "flying", + "poison", + "ground", + "rock", + "bug", + "ghost", + "steel", + "fire", + "water", + "grass", + "electric", + "psychic", + "ice", + "dragon", + "dark", + "fairy", + "none"}; + +const std::map STR_TYPE_MAP = { + {"normal", Type::normal}, + {"fighting", Type::fighting}, + {"flying", Type::flying}, + {"poison", Type::poison}, + {"ground", Type::ground}, + {"rock", Type::rock}, + {"bug", Type::bug}, + {"ghost", Type::ghost}, + {"steel", Type::steel}, + {"fire", Type::fire}, + {"water", Type::water}, + {"grass", Type::grass}, + {"electric", Type::electric}, + {"psychic", Type::psychic}, + {"ice", Type::ice}, + {"dragon", Type::dragon}, + {"dark", Type::dark}, + {"fairy", Type::fairy}, + {"none", Type::none}}; + +// row is attacker, column is defender +// normal,fighting,flying,poison,ground,rock,bug,ghost,steel,fire,water,grass,electric,psychic,ice,dragon,dark,fairy +const float TYPE_EFFECTIVENESS_TABLE[18][18] = { + {1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 0.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, // normal + {2.0, 1.0, 0.5, 0.5, 1.0, 2.0, 0.5, 0.0, 2.0, 1.0, 1.0, 1.0, 1.0, 0.5, 2.0, 1.0, 2.0, 0.5}, // fighting, + {1.0, 2.0, 1.0, 1.0, 1.0, 0.5, 2.0, 1.0, 0.5, 1.0, 1.0, 2.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0}, // flying, + {1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 0.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0}, // poison + {1.0, 1.0, 0.0, 2.0, 1.0, 2.0, 0.5, 1.0, 2.0, 2.0, 1.0, 0.5, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0}, // ground, + {1.0, 0.5, 2.0, 1.0, 0.5, 1.0, 2.0, 1.0, 0.5, 2.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0}, // rock + {1.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 2.0, 0.5}, // bug, + {0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 1.0}, // ghost + {1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 0.5, 0.5, 1.0, 0.5, 1.0, 2.0, 1.0, 1.0, 2.0}, // steel, + {1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 2.0, 1.0, 2.0, 0.5, 0.5, 2.0, 1.0, 1.0, 2.0, 0.5, 1.0, 1.0}, // fire + {1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0, 1.0, 1.0, 2.0, 0.5, 0.5, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0}, // water + {1.0, 1.0, 0.5, 0.5, 2.0, 2.0, 0.5, 1.0, 0.5, 0.5, 2.0, 0.5, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0}, // grass + {1.0, 1.0, 2.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 0.5, 0.5, 1.0, 1.0, 0.5, 1.0, 1.0}, // electric + {1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.0, 1.0}, // psychic + {1.0, 1.0, 2.0, 1.0, 2.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5, 2.0, 1.0, 1.0, 0.5, 2.0, 1.0, 1.0}, // ice + {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 0.0}, // dragon + {1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 0.5, 0.5}, // dark + {1.0, 2.0, 1.0, 0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 1.0} // fairy +}; + +float damage_multiplier(Type attack, Type defense){ + if (attack == Type::none){ + return 0.0; + } + + if (defense == Type::none){ + return 1.0; + } + + return TYPE_EFFECTIVENESS_TABLE[(size_t)attack][(size_t)defense]; +} + +float damage_multiplier(Type attack, Type defense1, Type defense2){ + // calculate the damage multiplier for multiple types + // the way damageMultiplier works, it should return 1 if the second type is none, so we're good to go + float multiplier1 = damage_multiplier(attack, defense1); + float multiplier2 = damage_multiplier(attack, defense2); + + return multiplier1 * multiplier2; +} + +Type get_type_from_string(const std::string& in_type){ + std::map::const_iterator iter = STR_TYPE_MAP.find(in_type); + if (iter != STR_TYPE_MAP.end()){ + return iter->second; + }else{ + return Type::none; + } +} + +const std::string& get_type_name(const Type in_type){ + return TYPE_NAMES[(size_t)in_type]; +} + + + + +Type serial_type_to_pkmnlib(Pokemon::PokemonType type){ + using Pokemon::PokemonType; + switch (type){ + case PokemonType::NONE: return Type::none; + case PokemonType::NORMAL: return Type::normal; + case PokemonType::FIRE: return Type::fire; + case PokemonType::FIGHTING: return Type::fighting; + case PokemonType::WATER: return Type::water; + case PokemonType::FLYING: return Type::flying; + case PokemonType::GRASS: return Type::grass; + case PokemonType::POISON: return Type::poison; + case PokemonType::ELECTRIC: return Type::electric; + case PokemonType::GROUND: return Type::ground; + case PokemonType::PSYCHIC: return Type::psychic; + case PokemonType::ROCK: return Type::rock; + case PokemonType::ICE: return Type::ice; + case PokemonType::BUG: return Type::bug; + case PokemonType::DRAGON: return Type::dragon; + case PokemonType::GHOST: return Type::ghost; + case PokemonType::DARK: return Type::dark; + case PokemonType::STEEL: return Type::steel; + case PokemonType::FAIRY: return Type::fairy; + default: return Type::none; + } +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.h b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.h index 7210ecda1d..69cbedef08 100644 --- a/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.h +++ b/SerialPrograms/Source/PokemonSwSh/PkmnLib/PokemonSwSh_PkmnLib_Types.h @@ -1,57 +1,57 @@ -/* PkmnLib Types - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Types_H -#define _PokemonAutomation_PokemonSwSh_PkmnLib_Types_H - -#include -#include -#include "Pokemon/Pokemon_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace papkmnlib{ - -enum class Type{ - normal = 0, - fighting, - flying, - poison, - ground, - rock, - bug, - ghost, - steel, - fire, - water, - grass, - electric, - psychic, - ice, - dragon, - dark, - fairy, - none -}; - -float damage_multiplier(Type attack, Type defense); -float damage_multiplier(Type attack, Type defense1, Type defense2); -Type get_type_from_string(const std::string& in_type); -const std::string& get_type_name(Type in_type); - - - -Type serial_type_to_pkmnlib(Pokemon::PokemonType type); - - - - -} -} -} -} -#endif +/* PkmnLib Types + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef _PokemonAutomation_PokemonSwSh_PkmnLib_Types_H +#define _PokemonAutomation_PokemonSwSh_PkmnLib_Types_H + +#include +#include +#include "Pokemon/Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace papkmnlib{ + +enum class Type{ + normal = 0, + fighting, + flying, + poison, + ground, + rock, + bug, + ghost, + steel, + fire, + water, + grass, + electric, + psychic, + ice, + dragon, + dark, + fairy, + none +}; + +float damage_multiplier(Type attack, Type defense); +float damage_multiplier(Type attack, Type defense1, Type defense2); +Type get_type_from_string(const std::string& in_type); +const std::string& get_type_name(Type in_type); + + + +Type serial_type_to_pkmnlib(Pokemon::PokemonType type); + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp index b70948dfe2..9e7708bfe4 100644 --- a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.cpp @@ -1,225 +1,225 @@ -/* Pokemon Sword/Shield Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "PokemonSwSh_Panels.h" - -#include "PokemonSwSh_Settings.h" - -#include "Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h" -#include "Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h" - -#include "Programs/General/PokemonSwSh_MassRelease.h" -#include "Programs/General/PokemonSwSh_SurpriseTrade.h" -#include "Programs/General/PokemonSwSh_TradeBot.h" -#include "Programs/General/PokemonSwSh_ClothingBuyer.h" -#include "Programs/General/PokemonSwSh_BallThrower.h" -#include "Programs/General/PokemonSwSh_AutonomousBallThrower.h" -#include "Programs/General/PokemonSwSh_DexRecFinder.h" -#include "Programs/General/PokemonSwSh_BoxReorderNationalDex.h" - -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h" -#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h" - -#include "Programs/DenHunting/PokemonSwSh_BeamReset.h" -#include "Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h" -#include "Programs/DenHunting/PokemonSwSh_EventBeamFinder.h" -#include "Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h" -#include "Programs/DenHunting/PokemonSwSh_DaySkipperEU.h" -#include "Programs/DenHunting/PokemonSwSh_DaySkipperUS.h" -#include "Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h" - -#include "Programs/Hosting/PokemonSwSh_DenRoller.h" -#include "Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h" -#include "Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h" - -#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset.h" -#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h" -#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h" -#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h" - -#include "Programs/EggPrograms/PokemonSwSh_EggAutonomous.h" -#include "Programs/EggPrograms/PokemonSwSh_EggFetcher2.h" -#include "Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h" -#include "Programs/EggPrograms/PokemonSwSh_EggHatcher.h" -#include "Programs/EggPrograms/PokemonSwSh_EggCombined2.h" -#include "Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h" -#include "Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h" -#include "Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h" - -#include "Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h" -#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h" -#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h" -#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h" -#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h" -#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h" -#include "Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h" - -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h" -#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h" -#include "Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h" - -#include "Programs/RNG/PokemonSwSh_CramomaticRNG.h" -#include "Programs/RNG/PokemonSwSh_DailyHighlightRNG.h" -#include "Programs/RNG/PokemonSwSh_SeedFinder.h" - -#include "Programs/PokemonSwSh_SynchronizedSpinning.h" -#include "Programs/PokemonSwSh_RaidItemFarmerOKHO.h" - -#include "MaxLair/PokemonSwSh_MaxLair_Standard.h" -#include "MaxLair/PokemonSwSh_MaxLair_StrongBoss.h" -#include "MaxLair/PokemonSwSh_MaxLair_BossFinder.h" - -#include "Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h" -#include "InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h" -#include "InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h" -#include "InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -PanelListFactory::PanelListFactory() - : PanelListDescriptor(Pokemon::STRING_POKEMON + " Sword and Shield") -{} - -std::vector PanelListFactory::make_panels() const{ - std::vector ret; - - ret.emplace_back("---- Settings ----"); - ret.emplace_back(make_settings()); - - ret.emplace_back("---- QoL Macros ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- General ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Date-Spam Farmers ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back(make_single_switch_program()); - } - - ret.emplace_back("---- Den Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); -#ifdef PA_OFFICIAL - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); -#endif - - ret.emplace_back("---- Hosting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Eggs ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - if (PreloadSettings::instance().NAUGHTY_MODE || PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back(make_single_switch_program()); - } - - ret.emplace_back("---- Non-Shiny Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Shiny Hunting ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- RNG ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - ret.emplace_back("---- Multi-Switch Programs ----"); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - - ret.emplace_back("---- Auto Max Lair 2.0 ----"); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - ret.emplace_back(make_multi_switch_program()); - - ret.emplace_back("---- Deprecated Programs ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Untested/Beta/WIP ----"); - ret.emplace_back(make_single_switch_program()); - } - if (PreloadSettings::instance().DEVELOPER_MODE){ - ret.emplace_back("---- Developer Tools ----"); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - ret.emplace_back(make_single_switch_program()); - } - - return ret; -} - - - - - - -} -} -} +/* Pokemon Sword/Shield Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "PokemonSwSh_Panels.h" + +#include "PokemonSwSh_Settings.h" + +#include "Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h" +#include "Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h" + +#include "Programs/General/PokemonSwSh_MassRelease.h" +#include "Programs/General/PokemonSwSh_SurpriseTrade.h" +#include "Programs/General/PokemonSwSh_TradeBot.h" +#include "Programs/General/PokemonSwSh_ClothingBuyer.h" +#include "Programs/General/PokemonSwSh_BallThrower.h" +#include "Programs/General/PokemonSwSh_AutonomousBallThrower.h" +#include "Programs/General/PokemonSwSh_DexRecFinder.h" +#include "Programs/General/PokemonSwSh_BoxReorderNationalDex.h" + +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h" +#include "Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h" + +#include "Programs/DenHunting/PokemonSwSh_BeamReset.h" +#include "Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h" +#include "Programs/DenHunting/PokemonSwSh_EventBeamFinder.h" +#include "Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h" +#include "Programs/DenHunting/PokemonSwSh_DaySkipperEU.h" +#include "Programs/DenHunting/PokemonSwSh_DaySkipperUS.h" +#include "Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h" + +#include "Programs/Hosting/PokemonSwSh_DenRoller.h" +#include "Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h" +#include "Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h" + +#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset.h" +#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h" +#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h" +#include "Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h" + +#include "Programs/EggPrograms/PokemonSwSh_EggAutonomous.h" +#include "Programs/EggPrograms/PokemonSwSh_EggFetcher2.h" +#include "Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h" +#include "Programs/EggPrograms/PokemonSwSh_EggHatcher.h" +#include "Programs/EggPrograms/PokemonSwSh_EggCombined2.h" +#include "Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h" +#include "Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h" +#include "Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h" + +#include "Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h" +#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h" +#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h" +#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h" +#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h" +#include "Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h" +#include "Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h" + +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h" +#include "Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h" +#include "Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h" + +#include "Programs/RNG/PokemonSwSh_CramomaticRNG.h" +#include "Programs/RNG/PokemonSwSh_DailyHighlightRNG.h" +#include "Programs/RNG/PokemonSwSh_SeedFinder.h" + +#include "Programs/PokemonSwSh_SynchronizedSpinning.h" +#include "Programs/PokemonSwSh_RaidItemFarmerOKHO.h" + +#include "MaxLair/PokemonSwSh_MaxLair_Standard.h" +#include "MaxLair/PokemonSwSh_MaxLair_StrongBoss.h" +#include "MaxLair/PokemonSwSh_MaxLair_BossFinder.h" + +#include "Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h" +#include "InferenceTraining/PokemonSwSh_GenerateIVCheckerOCR.h" +#include "InferenceTraining/PokemonSwSh_GenerateNameOCRPokedex.h" +#include "InferenceTraining/PokemonSwSh_GeneratePokedexSprites.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +PanelListFactory::PanelListFactory() + : PanelListDescriptor(Pokemon::STRING_POKEMON + " Sword and Shield") +{} + +std::vector PanelListFactory::make_panels() const{ + std::vector ret; + + ret.emplace_back("---- Settings ----"); + ret.emplace_back(make_settings()); + + ret.emplace_back("---- QoL Macros ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- General ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Date-Spam Farmers ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back(make_single_switch_program()); + } + + ret.emplace_back("---- Den Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); +#ifdef PA_OFFICIAL + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); +#endif + + ret.emplace_back("---- Hosting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Eggs ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + if (PreloadSettings::instance().NAUGHTY_MODE || PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back(make_single_switch_program()); + } + + ret.emplace_back("---- Non-Shiny Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Shiny Hunting ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- RNG ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + ret.emplace_back("---- Multi-Switch Programs ----"); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + + ret.emplace_back("---- Auto Max Lair 2.0 ----"); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + ret.emplace_back(make_multi_switch_program()); + + ret.emplace_back("---- Deprecated Programs ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Untested/Beta/WIP ----"); + ret.emplace_back(make_single_switch_program()); + } + if (PreloadSettings::instance().DEVELOPER_MODE){ + ret.emplace_back("---- Developer Tools ----"); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + ret.emplace_back(make_single_switch_program()); + } + + return ret; +} + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.h b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.h index a935e18ad0..b6ba35c81c 100644 --- a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.h +++ b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Panels.h @@ -1,30 +1,30 @@ -/* Pokemon Sword/Shield Panels - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwordShieldPanels_H -#define PokemonAutomation_PokemonSwordShieldPanels_H - -#include "CommonFramework/Panels/PanelList.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class PanelListFactory : public PanelListDescriptor{ -public: - PanelListFactory(); -private: - virtual std::vector make_panels() const override; -}; - - - -} -} -} -#endif +/* Pokemon Sword/Shield Panels + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwordShieldPanels_H +#define PokemonAutomation_PokemonSwordShieldPanels_H + +#include "CommonFramework/Panels/PanelList.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class PanelListFactory : public PanelListDescriptor{ +public: + PanelListFactory(); +private: + virtual std::vector make_panels() const override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.cpp b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.cpp index 8d5f51f2e6..24e932763c 100644 --- a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.cpp +++ b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.cpp @@ -1,321 +1,321 @@ -/* Pokemon Sword/Shield Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_Settings.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - - -GameSettings& GameSettings::instance(){ - static GameSettings settings; - return settings; -} -GameSettings::GameSettings() - : BatchOption(LockMode::LOCK_WHILE_RUNNING) - , m_egg_options("Egg Options:") - , AUTO_DEPOSIT( - "Auto-Deposit:
true = Send " + STRING_POKEMON + " to boxes is \"Automatic\".
false = Send " + STRING_POKEMON + " to boxes is \"Manual\".", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , EGG_FETCH_EXTRA_LINE( - "Egg Fetch Extra Line:
true = The daycare lady has an extra line of text in Japanese. Set this to true if you are running any of the egg programs in a Japanese game.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , FETCH_EGG_MASH_DELAY0( - "Fetch Egg Mash Delay:
Time needed to mash B to fetch an egg and return to overworld when auto-deposit is on.", - LockMode::LOCK_WHILE_RUNNING, - "6400 ms" - ) - , m_den_options("Den Options:") - , DODGE_UNCATCHABLE_PROMPT_FAST( - "Dodge Uncatchable Prompt Fast:
Which method to use to bypass the uncatchable " + STRING_POKEMON + " prompt?
true = Use a fast (but potentially unreliable) method.
false = Use a slower (by about 5 seconds) method.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , m_advanced_options("Advanced Options: You shouldn't need to touch anything below here.") - , m_general_options("General Timings:") - , AUTO_FR_DURATION0( - "Auto-FR Duration:
Time to accept FRs before returning to den lobby.", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , m_menu_navigation("Menu Navigation Timings:") - , OVERWORLD_TO_MENU_DELAY0( - "Overworld to Menu Delay:
Delay to bring up the menu when pressing X in the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "960 ms" - ) - , MENU_TO_OVERWORLD_DELAY0( - "Menu to Overworld Delay:
Delay to go from menu back to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , GAME_TO_HOME_DELAY_FAST0( - "Game to Home Delay (fast):
" - "Delay from pressing home to entering the the Switch home menu. This affects the speed of date-spamming programs.", - LockMode::LOCK_WHILE_RUNNING, - "800 ms" - ) - , GAME_TO_HOME_DELAY_SAFE0( - "Game to Home Delay (safe):
" - "Delay from pressing home to entering the the Switch home menu. This affects the speed of date-spamming programs.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , HOME_TO_GAME_DELAY0( - "Home to Game Delay:
Delay to enter game from home menu.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , OPEN_YCOMM_DELAY0( - "Open Y-COMM Delay:
Time needed to open Y-COMM.", - LockMode::LOCK_WHILE_RUNNING, - "1600 ms" - ) - , ENTER_PROFILE_DELAY0( - "Enter Profile Delay:
Delay to enter your Switch profile.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , m_start_game_timings("Start Game Timings:") - , START_GAME_MASH0( - "1. Start Game Mash:
Mash A for this long to start the game.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , START_GAME_WAIT0( - "2. Start Game Wait:
Wait this long for the game to load.", - LockMode::LOCK_WHILE_RUNNING, - "20000 ms" - ) - , ENTER_GAME_MASH0( - "3. Enter Game Mash:
Mash A for this long to enter the game.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , ENTER_GAME_WAIT0( - "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "11000 ms" - ) - , m_den_timings("Den Timings:") - , ENTER_OFFLINE_DEN_DELAY0( - "Enter Offline Game Delay:
Time needed to enter a den on final button press.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , REENTER_DEN_DELAY0( - "Re-enter Den Delay:
Time from exiting den after a day-skip to when you can collect watts and re-enter it.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , COLLECT_WATTS_OFFLINE_DELAY0( - "Collect Watts Delay (offline):", - LockMode::LOCK_WHILE_RUNNING, - "640 ms" - ) - , COLLECT_WATTS_ONLINE_DELAY0( - "Collect Watts Delay (online):", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , UNCATCHABLE_PROMPT_DELAY0( - "Uncatchable Prompt Delay:
Time needed to bypass uncatchable pokemon prompt.", - LockMode::LOCK_WHILE_RUNNING, - "880 ms" - ) - , OPEN_LOCAL_DEN_LOBBY_DELAY0( - "Open Local Den Lobby Delay:
Time needed to open a den lobby on local connection.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , ENTER_SWITCH_POKEMON0( - "Enter Switch " + STRING_POKEMON + ":
Time needed to enter Switch " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "4000 ms" - ) - , EXIT_SWITCH_POKEMON0( - "Exit Switch " + STRING_POKEMON + ":
Time needed to exit Switch " + STRING_POKEMON + " back to den lobby.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , FULL_LOBBY_TIMER0( - "Full Lobby Timer:
Always 3 minutes.", - LockMode::LOCK_WHILE_RUNNING, - "180 s" - ) - , m_box_timings("Box Timings: (for egg programs)") -// , BOX_SCROLL_DELAY1( -// "Box Scroll Delay:
Delay to move the cursor.", -// LockMode::LOCK_WHILE_RUNNING, -// "200 ms" -// ) - , BOX_CHANGE_DELAY0( - "Box Change Delay:
Delay to change boxes.", - LockMode::LOCK_WHILE_RUNNING, - "640 ms" - ) - , BOX_PICKUP_DROP_DELAY0( - "Box Pickup/Drop Delay:
Delay to pickup/drop " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - "720 ms" - ) - , MENU_TO_POKEMON_DELAY0( - "Menu To " + STRING_POKEMON + " Delay:
Delay to enter " + STRING_POKEMON + " menu.", - LockMode::LOCK_WHILE_RUNNING, - "2400 ms" - ) - , POKEMON_TO_BOX_DELAY0( - "" + STRING_POKEMON + " to Box Delay:
Delay to enter box system.", - LockMode::LOCK_WHILE_RUNNING, - "2400 ms" - ) - , BOX_TO_POKEMON_DELAY0( - "Box to " + STRING_POKEMON + " Delay:
Delay to exit box system.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , POKEMON_TO_MENU_DELAY0( - "" + STRING_POKEMON + " to Menu Delay:
Delay to return to menu.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , m_shiny_detection("Shiny Detection:") - , SHINY_ALPHA_THRESHOLD( - "Shiny Threshold:
Threshold to detect a shiny encounter.", - LockMode::LOCK_WHILE_RUNNING, - 2.0, 0 - ) - , BALL_SPARKLE_ALPHA( - "Ball Sparkle Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 0.4, 0 - ) - , STAR_SPARKLE_ALPHA( - "Star Sparkle Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 0.5, 0 - ) - , SQUARE_SPARKLE_ALPHA( - "Ball Sparkle Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 0.3, 0 - ) - , LINE_SPARKLE_ALPHA( - "Line Sparkle Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 0.3, 0 - ) - , SHINY_DIALOG_ALPHA( - "Shiny Dialog Alpha:", - LockMode::LOCK_WHILE_RUNNING, - 1.2, 0 - ) -// , m_experimental("Experimental/Beta Features:") -{ - PA_ADD_STATIC(m_egg_options); - PA_ADD_OPTION(AUTO_DEPOSIT); - PA_ADD_OPTION(EGG_FETCH_EXTRA_LINE); - PA_ADD_OPTION(FETCH_EGG_MASH_DELAY0); - - PA_ADD_STATIC(m_den_options); - PA_ADD_OPTION(DODGE_UNCATCHABLE_PROMPT_FAST); - - PA_ADD_STATIC(m_advanced_options); - - PA_ADD_STATIC(m_general_options); - PA_ADD_OPTION(AUTO_FR_DURATION0); - - PA_ADD_STATIC(m_menu_navigation); - PA_ADD_OPTION(OVERWORLD_TO_MENU_DELAY0); - PA_ADD_OPTION(MENU_TO_OVERWORLD_DELAY0); - PA_ADD_OPTION(GAME_TO_HOME_DELAY_FAST0); - PA_ADD_OPTION(GAME_TO_HOME_DELAY_SAFE0); - PA_ADD_OPTION(HOME_TO_GAME_DELAY0); - PA_ADD_OPTION(OPEN_YCOMM_DELAY0); - PA_ADD_OPTION(ENTER_PROFILE_DELAY0); - - PA_ADD_STATIC(m_start_game_timings); - PA_ADD_OPTION(START_GAME_MASH0); - PA_ADD_OPTION(START_GAME_WAIT0); - PA_ADD_OPTION(ENTER_GAME_MASH0); - PA_ADD_OPTION(ENTER_GAME_WAIT0); - - PA_ADD_STATIC(m_den_timings); - PA_ADD_OPTION(ENTER_OFFLINE_DEN_DELAY0); - PA_ADD_OPTION(REENTER_DEN_DELAY0); - PA_ADD_OPTION(COLLECT_WATTS_OFFLINE_DELAY0); - PA_ADD_OPTION(COLLECT_WATTS_ONLINE_DELAY0); - PA_ADD_OPTION(UNCATCHABLE_PROMPT_DELAY0); - PA_ADD_OPTION(OPEN_LOCAL_DEN_LOBBY_DELAY0); - PA_ADD_OPTION(ENTER_SWITCH_POKEMON0); - PA_ADD_OPTION(EXIT_SWITCH_POKEMON0); - PA_ADD_OPTION(FULL_LOBBY_TIMER0); - - PA_ADD_STATIC(m_box_timings); -// PA_ADD_OPTION(BOX_SCROLL_DELAY1); - PA_ADD_OPTION(BOX_CHANGE_DELAY0); - PA_ADD_OPTION(BOX_PICKUP_DROP_DELAY0); - PA_ADD_OPTION(MENU_TO_POKEMON_DELAY0); - PA_ADD_OPTION(POKEMON_TO_BOX_DELAY0); - PA_ADD_OPTION(BOX_TO_POKEMON_DELAY0); - PA_ADD_OPTION(POKEMON_TO_MENU_DELAY0); - - PA_ADD_STATIC(m_shiny_detection); - PA_ADD_OPTION(SHINY_ALPHA_THRESHOLD); - PA_ADD_OPTION(BALL_SPARKLE_ALPHA); - PA_ADD_OPTION(STAR_SPARKLE_ALPHA); - PA_ADD_OPTION(SQUARE_SPARKLE_ALPHA); - PA_ADD_OPTION(LINE_SPARKLE_ALPHA); - PA_ADD_OPTION(SHINY_DIALOG_ALPHA); - -// PA_ADD_STATIC(m_experimental); -} - - - - - -GameSettings_Descriptor::GameSettings_Descriptor() - : PanelDescriptor( - Color(), - "PokemonSwSh:GlobalSettings", - STRING_POKEMON + " SwSh", "Game Settings", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/PokemonSettings.md", - "Global " + STRING_POKEMON + " Sword and Shield Settings" - ) -{} - - - -GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) - : SettingsPanelInstance(descriptor) - , settings(GameSettings::instance()) -{ - PA_ADD_OPTION(settings); -} - - - - - -} -} -} - - - - - - +/* Pokemon Sword/Shield Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_Settings.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + + +GameSettings& GameSettings::instance(){ + static GameSettings settings; + return settings; +} +GameSettings::GameSettings() + : BatchOption(LockMode::LOCK_WHILE_RUNNING) + , m_egg_options("Egg Options:") + , AUTO_DEPOSIT( + "Auto-Deposit:
true = Send " + STRING_POKEMON + " to boxes is \"Automatic\".
false = Send " + STRING_POKEMON + " to boxes is \"Manual\".", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , EGG_FETCH_EXTRA_LINE( + "Egg Fetch Extra Line:
true = The daycare lady has an extra line of text in Japanese. Set this to true if you are running any of the egg programs in a Japanese game.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , FETCH_EGG_MASH_DELAY0( + "Fetch Egg Mash Delay:
Time needed to mash B to fetch an egg and return to overworld when auto-deposit is on.", + LockMode::LOCK_WHILE_RUNNING, + "6400 ms" + ) + , m_den_options("Den Options:") + , DODGE_UNCATCHABLE_PROMPT_FAST( + "Dodge Uncatchable Prompt Fast:
Which method to use to bypass the uncatchable " + STRING_POKEMON + " prompt?
true = Use a fast (but potentially unreliable) method.
false = Use a slower (by about 5 seconds) method.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , m_advanced_options("Advanced Options: You shouldn't need to touch anything below here.") + , m_general_options("General Timings:") + , AUTO_FR_DURATION0( + "Auto-FR Duration:
Time to accept FRs before returning to den lobby.", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , m_menu_navigation("Menu Navigation Timings:") + , OVERWORLD_TO_MENU_DELAY0( + "Overworld to Menu Delay:
Delay to bring up the menu when pressing X in the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "960 ms" + ) + , MENU_TO_OVERWORLD_DELAY0( + "Menu to Overworld Delay:
Delay to go from menu back to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , GAME_TO_HOME_DELAY_FAST0( + "Game to Home Delay (fast):
" + "Delay from pressing home to entering the the Switch home menu. This affects the speed of date-spamming programs.", + LockMode::LOCK_WHILE_RUNNING, + "800 ms" + ) + , GAME_TO_HOME_DELAY_SAFE0( + "Game to Home Delay (safe):
" + "Delay from pressing home to entering the the Switch home menu. This affects the speed of date-spamming programs.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , HOME_TO_GAME_DELAY0( + "Home to Game Delay:
Delay to enter game from home menu.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , OPEN_YCOMM_DELAY0( + "Open Y-COMM Delay:
Time needed to open Y-COMM.", + LockMode::LOCK_WHILE_RUNNING, + "1600 ms" + ) + , ENTER_PROFILE_DELAY0( + "Enter Profile Delay:
Delay to enter your Switch profile.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , m_start_game_timings("Start Game Timings:") + , START_GAME_MASH0( + "1. Start Game Mash:
Mash A for this long to start the game.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , START_GAME_WAIT0( + "2. Start Game Wait:
Wait this long for the game to load.", + LockMode::LOCK_WHILE_RUNNING, + "20000 ms" + ) + , ENTER_GAME_MASH0( + "3. Enter Game Mash:
Mash A for this long to enter the game.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , ENTER_GAME_WAIT0( + "4. Enter Game Wait:
Wait this long for the game to enter the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "11000 ms" + ) + , m_den_timings("Den Timings:") + , ENTER_OFFLINE_DEN_DELAY0( + "Enter Offline Game Delay:
Time needed to enter a den on final button press.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , REENTER_DEN_DELAY0( + "Re-enter Den Delay:
Time from exiting den after a day-skip to when you can collect watts and re-enter it.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , COLLECT_WATTS_OFFLINE_DELAY0( + "Collect Watts Delay (offline):", + LockMode::LOCK_WHILE_RUNNING, + "640 ms" + ) + , COLLECT_WATTS_ONLINE_DELAY0( + "Collect Watts Delay (online):", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , UNCATCHABLE_PROMPT_DELAY0( + "Uncatchable Prompt Delay:
Time needed to bypass uncatchable pokemon prompt.", + LockMode::LOCK_WHILE_RUNNING, + "880 ms" + ) + , OPEN_LOCAL_DEN_LOBBY_DELAY0( + "Open Local Den Lobby Delay:
Time needed to open a den lobby on local connection.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , ENTER_SWITCH_POKEMON0( + "Enter Switch " + STRING_POKEMON + ":
Time needed to enter Switch " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "4000 ms" + ) + , EXIT_SWITCH_POKEMON0( + "Exit Switch " + STRING_POKEMON + ":
Time needed to exit Switch " + STRING_POKEMON + " back to den lobby.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , FULL_LOBBY_TIMER0( + "Full Lobby Timer:
Always 3 minutes.", + LockMode::LOCK_WHILE_RUNNING, + "180 s" + ) + , m_box_timings("Box Timings: (for egg programs)") +// , BOX_SCROLL_DELAY1( +// "Box Scroll Delay:
Delay to move the cursor.", +// LockMode::LOCK_WHILE_RUNNING, +// "200 ms" +// ) + , BOX_CHANGE_DELAY0( + "Box Change Delay:
Delay to change boxes.", + LockMode::LOCK_WHILE_RUNNING, + "640 ms" + ) + , BOX_PICKUP_DROP_DELAY0( + "Box Pickup/Drop Delay:
Delay to pickup/drop " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + "720 ms" + ) + , MENU_TO_POKEMON_DELAY0( + "Menu To " + STRING_POKEMON + " Delay:
Delay to enter " + STRING_POKEMON + " menu.", + LockMode::LOCK_WHILE_RUNNING, + "2400 ms" + ) + , POKEMON_TO_BOX_DELAY0( + "" + STRING_POKEMON + " to Box Delay:
Delay to enter box system.", + LockMode::LOCK_WHILE_RUNNING, + "2400 ms" + ) + , BOX_TO_POKEMON_DELAY0( + "Box to " + STRING_POKEMON + " Delay:
Delay to exit box system.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , POKEMON_TO_MENU_DELAY0( + "" + STRING_POKEMON + " to Menu Delay:
Delay to return to menu.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , m_shiny_detection("Shiny Detection:") + , SHINY_ALPHA_THRESHOLD( + "Shiny Threshold:
Threshold to detect a shiny encounter.", + LockMode::LOCK_WHILE_RUNNING, + 2.0, 0 + ) + , BALL_SPARKLE_ALPHA( + "Ball Sparkle Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 0.4, 0 + ) + , STAR_SPARKLE_ALPHA( + "Star Sparkle Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 0.5, 0 + ) + , SQUARE_SPARKLE_ALPHA( + "Ball Sparkle Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 0.3, 0 + ) + , LINE_SPARKLE_ALPHA( + "Line Sparkle Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 0.3, 0 + ) + , SHINY_DIALOG_ALPHA( + "Shiny Dialog Alpha:", + LockMode::LOCK_WHILE_RUNNING, + 1.2, 0 + ) +// , m_experimental("Experimental/Beta Features:") +{ + PA_ADD_STATIC(m_egg_options); + PA_ADD_OPTION(AUTO_DEPOSIT); + PA_ADD_OPTION(EGG_FETCH_EXTRA_LINE); + PA_ADD_OPTION(FETCH_EGG_MASH_DELAY0); + + PA_ADD_STATIC(m_den_options); + PA_ADD_OPTION(DODGE_UNCATCHABLE_PROMPT_FAST); + + PA_ADD_STATIC(m_advanced_options); + + PA_ADD_STATIC(m_general_options); + PA_ADD_OPTION(AUTO_FR_DURATION0); + + PA_ADD_STATIC(m_menu_navigation); + PA_ADD_OPTION(OVERWORLD_TO_MENU_DELAY0); + PA_ADD_OPTION(MENU_TO_OVERWORLD_DELAY0); + PA_ADD_OPTION(GAME_TO_HOME_DELAY_FAST0); + PA_ADD_OPTION(GAME_TO_HOME_DELAY_SAFE0); + PA_ADD_OPTION(HOME_TO_GAME_DELAY0); + PA_ADD_OPTION(OPEN_YCOMM_DELAY0); + PA_ADD_OPTION(ENTER_PROFILE_DELAY0); + + PA_ADD_STATIC(m_start_game_timings); + PA_ADD_OPTION(START_GAME_MASH0); + PA_ADD_OPTION(START_GAME_WAIT0); + PA_ADD_OPTION(ENTER_GAME_MASH0); + PA_ADD_OPTION(ENTER_GAME_WAIT0); + + PA_ADD_STATIC(m_den_timings); + PA_ADD_OPTION(ENTER_OFFLINE_DEN_DELAY0); + PA_ADD_OPTION(REENTER_DEN_DELAY0); + PA_ADD_OPTION(COLLECT_WATTS_OFFLINE_DELAY0); + PA_ADD_OPTION(COLLECT_WATTS_ONLINE_DELAY0); + PA_ADD_OPTION(UNCATCHABLE_PROMPT_DELAY0); + PA_ADD_OPTION(OPEN_LOCAL_DEN_LOBBY_DELAY0); + PA_ADD_OPTION(ENTER_SWITCH_POKEMON0); + PA_ADD_OPTION(EXIT_SWITCH_POKEMON0); + PA_ADD_OPTION(FULL_LOBBY_TIMER0); + + PA_ADD_STATIC(m_box_timings); +// PA_ADD_OPTION(BOX_SCROLL_DELAY1); + PA_ADD_OPTION(BOX_CHANGE_DELAY0); + PA_ADD_OPTION(BOX_PICKUP_DROP_DELAY0); + PA_ADD_OPTION(MENU_TO_POKEMON_DELAY0); + PA_ADD_OPTION(POKEMON_TO_BOX_DELAY0); + PA_ADD_OPTION(BOX_TO_POKEMON_DELAY0); + PA_ADD_OPTION(POKEMON_TO_MENU_DELAY0); + + PA_ADD_STATIC(m_shiny_detection); + PA_ADD_OPTION(SHINY_ALPHA_THRESHOLD); + PA_ADD_OPTION(BALL_SPARKLE_ALPHA); + PA_ADD_OPTION(STAR_SPARKLE_ALPHA); + PA_ADD_OPTION(SQUARE_SPARKLE_ALPHA); + PA_ADD_OPTION(LINE_SPARKLE_ALPHA); + PA_ADD_OPTION(SHINY_DIALOG_ALPHA); + +// PA_ADD_STATIC(m_experimental); +} + + + + + +GameSettings_Descriptor::GameSettings_Descriptor() + : PanelDescriptor( + Color(), + "PokemonSwSh:GlobalSettings", + STRING_POKEMON + " SwSh", "Game Settings", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/PokemonSettings.md", + "Global " + STRING_POKEMON + " Sword and Shield Settings" + ) +{} + + + +GameSettingsPanel::GameSettingsPanel(const GameSettings_Descriptor& descriptor) + : SettingsPanelInstance(descriptor) + , settings(GameSettings::instance()) +{ + PA_ADD_OPTION(settings); +} + + + + + +} +} +} + + + + + + diff --git a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.h b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.h index 04cc6b087c..08036bba69 100644 --- a/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.h +++ b/SerialPrograms/Source/PokemonSwSh/PokemonSwSh_Settings.h @@ -1,105 +1,105 @@ -/* Pokemon Sword/Shield Settings - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Settings_H -#define PokemonAutomation_PokemonSwSh_Settings_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Panels/SettingsPanel.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class GameSettings : public BatchOption{ - GameSettings(); -public: - static GameSettings& instance(); - - SectionDividerOption m_egg_options; - BooleanCheckBoxOption AUTO_DEPOSIT; - BooleanCheckBoxOption EGG_FETCH_EXTRA_LINE; - MillisecondsOption FETCH_EGG_MASH_DELAY0; - - SectionDividerOption m_den_options; - BooleanCheckBoxOption DODGE_UNCATCHABLE_PROMPT_FAST; - - SectionDividerOption m_advanced_options; - - SectionDividerOption m_general_options; - MillisecondsOption AUTO_FR_DURATION0; - - SectionDividerOption m_menu_navigation; - MillisecondsOption OVERWORLD_TO_MENU_DELAY0; - MillisecondsOption MENU_TO_OVERWORLD_DELAY0; - MillisecondsOption GAME_TO_HOME_DELAY_FAST0; - MillisecondsOption GAME_TO_HOME_DELAY_SAFE0; - MillisecondsOption HOME_TO_GAME_DELAY0; - MillisecondsOption OPEN_YCOMM_DELAY0; - MillisecondsOption ENTER_PROFILE_DELAY0; - - SectionDividerOption m_start_game_timings; - MillisecondsOption START_GAME_MASH0; - MillisecondsOption START_GAME_WAIT0; - MillisecondsOption ENTER_GAME_MASH0; - MillisecondsOption ENTER_GAME_WAIT0; - - SectionDividerOption m_den_timings; - MillisecondsOption ENTER_OFFLINE_DEN_DELAY0; - MillisecondsOption REENTER_DEN_DELAY0; - MillisecondsOption COLLECT_WATTS_OFFLINE_DELAY0; - MillisecondsOption COLLECT_WATTS_ONLINE_DELAY0; - MillisecondsOption UNCATCHABLE_PROMPT_DELAY0; - MillisecondsOption OPEN_LOCAL_DEN_LOBBY_DELAY0; - MillisecondsOption ENTER_SWITCH_POKEMON0; - MillisecondsOption EXIT_SWITCH_POKEMON0; - MillisecondsOption FULL_LOBBY_TIMER0; - - SectionDividerOption m_box_timings; -// MillisecondsOption BOX_SCROLL_DELAY1; - MillisecondsOption BOX_CHANGE_DELAY0; - MillisecondsOption BOX_PICKUP_DROP_DELAY0; - MillisecondsOption MENU_TO_POKEMON_DELAY0; - MillisecondsOption POKEMON_TO_BOX_DELAY0; - MillisecondsOption BOX_TO_POKEMON_DELAY0; - MillisecondsOption POKEMON_TO_MENU_DELAY0; - - SectionDividerOption m_shiny_detection; - FloatingPointOption SHINY_ALPHA_THRESHOLD; - - FloatingPointOption BALL_SPARKLE_ALPHA; - FloatingPointOption STAR_SPARKLE_ALPHA; - FloatingPointOption SQUARE_SPARKLE_ALPHA; - FloatingPointOption LINE_SPARKLE_ALPHA; - - FloatingPointOption SHINY_DIALOG_ALPHA; -}; - - - - -class GameSettings_Descriptor : public PanelDescriptor{ -public: - GameSettings_Descriptor(); -}; - - -class GameSettingsPanel : public SettingsPanelInstance{ -public: - GameSettingsPanel(const GameSettings_Descriptor& descriptor); -private: - GameSettings& settings; -}; - - -} -} -} -#endif +/* Pokemon Sword/Shield Settings + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Settings_H +#define PokemonAutomation_PokemonSwSh_Settings_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Panels/SettingsPanel.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class GameSettings : public BatchOption{ + GameSettings(); +public: + static GameSettings& instance(); + + SectionDividerOption m_egg_options; + BooleanCheckBoxOption AUTO_DEPOSIT; + BooleanCheckBoxOption EGG_FETCH_EXTRA_LINE; + MillisecondsOption FETCH_EGG_MASH_DELAY0; + + SectionDividerOption m_den_options; + BooleanCheckBoxOption DODGE_UNCATCHABLE_PROMPT_FAST; + + SectionDividerOption m_advanced_options; + + SectionDividerOption m_general_options; + MillisecondsOption AUTO_FR_DURATION0; + + SectionDividerOption m_menu_navigation; + MillisecondsOption OVERWORLD_TO_MENU_DELAY0; + MillisecondsOption MENU_TO_OVERWORLD_DELAY0; + MillisecondsOption GAME_TO_HOME_DELAY_FAST0; + MillisecondsOption GAME_TO_HOME_DELAY_SAFE0; + MillisecondsOption HOME_TO_GAME_DELAY0; + MillisecondsOption OPEN_YCOMM_DELAY0; + MillisecondsOption ENTER_PROFILE_DELAY0; + + SectionDividerOption m_start_game_timings; + MillisecondsOption START_GAME_MASH0; + MillisecondsOption START_GAME_WAIT0; + MillisecondsOption ENTER_GAME_MASH0; + MillisecondsOption ENTER_GAME_WAIT0; + + SectionDividerOption m_den_timings; + MillisecondsOption ENTER_OFFLINE_DEN_DELAY0; + MillisecondsOption REENTER_DEN_DELAY0; + MillisecondsOption COLLECT_WATTS_OFFLINE_DELAY0; + MillisecondsOption COLLECT_WATTS_ONLINE_DELAY0; + MillisecondsOption UNCATCHABLE_PROMPT_DELAY0; + MillisecondsOption OPEN_LOCAL_DEN_LOBBY_DELAY0; + MillisecondsOption ENTER_SWITCH_POKEMON0; + MillisecondsOption EXIT_SWITCH_POKEMON0; + MillisecondsOption FULL_LOBBY_TIMER0; + + SectionDividerOption m_box_timings; +// MillisecondsOption BOX_SCROLL_DELAY1; + MillisecondsOption BOX_CHANGE_DELAY0; + MillisecondsOption BOX_PICKUP_DROP_DELAY0; + MillisecondsOption MENU_TO_POKEMON_DELAY0; + MillisecondsOption POKEMON_TO_BOX_DELAY0; + MillisecondsOption BOX_TO_POKEMON_DELAY0; + MillisecondsOption POKEMON_TO_MENU_DELAY0; + + SectionDividerOption m_shiny_detection; + FloatingPointOption SHINY_ALPHA_THRESHOLD; + + FloatingPointOption BALL_SPARKLE_ALPHA; + FloatingPointOption STAR_SPARKLE_ALPHA; + FloatingPointOption SQUARE_SPARKLE_ALPHA; + FloatingPointOption LINE_SPARKLE_ALPHA; + + FloatingPointOption SHINY_DIALOG_ALPHA; +}; + + + + +class GameSettings_Descriptor : public PanelDescriptor{ +public: + GameSettings_Descriptor(); +}; + + +class GameSettingsPanel : public SettingsPanelInstance{ +public: + GameSettingsPanel(const GameSettings_Descriptor& descriptor); +private: + GameSettings& settings; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.cpp index 0563932ff8..f8cc3a008b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.cpp @@ -1,103 +1,103 @@ -/* Berry Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateSpam-BerryFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -BerryFarmer_Descriptor::BerryFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:BerryFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Berry Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-BerryFarmer.md", - "Farm berries.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - - -BerryFarmer::BerryFarmer() - : SKIPS( - "Number of Fetch Attempts:", - LockMode::LOCK_WHILE_RUNNING, - 100000 - ) - , SAVE_ITERATIONS0( - "Save Every this Many Fetches:
(zero disables saving): ", - LockMode::LOCK_WHILE_RUNNING, - 100 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(SAVE_ITERATIONS0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void BerryFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - uint8_t year = MAX_YEAR; - uint16_t save_count = 0; - for (uint32_t c = 0; c < SKIPS; c++){ - env.log("Fetch Attempts: " + tostr_u_commas(c)); - - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - - pbf_press_button(context, BUTTON_A, 10, 10); - pbf_mash_button(context, BUTTON_ZL, 385); - pbf_mash_button(context, BUTTON_B, 600); - - if (SAVE_ITERATIONS0 != 0){ - save_count++; - if (save_count >= SAVE_ITERATIONS0){ - save_count = 0; - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 20, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_ZL, 20, 3 * TICKS_PER_SECOND); - } - } - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Berry Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateSpam-BerryFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +BerryFarmer_Descriptor::BerryFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:BerryFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Berry Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-BerryFarmer.md", + "Farm berries.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + + +BerryFarmer::BerryFarmer() + : SKIPS( + "Number of Fetch Attempts:", + LockMode::LOCK_WHILE_RUNNING, + 100000 + ) + , SAVE_ITERATIONS0( + "Save Every this Many Fetches:
(zero disables saving): ", + LockMode::LOCK_WHILE_RUNNING, + 100 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(SAVE_ITERATIONS0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void BerryFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + uint8_t year = MAX_YEAR; + uint16_t save_count = 0; + for (uint32_t c = 0; c < SKIPS; c++){ + env.log("Fetch Attempts: " + tostr_u_commas(c)); + + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + + pbf_press_button(context, BUTTON_A, 10, 10); + pbf_mash_button(context, BUTTON_ZL, 385); + pbf_mash_button(context, BUTTON_B, 600); + + if (SAVE_ITERATIONS0 != 0){ + save_count++; + if (save_count >= SAVE_ITERATIONS0){ + save_count = 0; + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 20, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_ZL, 20, 3 * TICKS_PER_SECOND); + } + } + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h index 022f3ca5fb..788499bd1e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer.h @@ -1,49 +1,49 @@ -/* Berry Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BerryFarmer_H -#define PokemonAutomation_PokemonSwSh_BerryFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BerryFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BerryFarmer_Descriptor(); -}; - - - -class BerryFarmer : public SingleSwitchProgramInstance{ -public: - BerryFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption SKIPS; - SimpleIntegerOption SAVE_ITERATIONS0; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Berry Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BerryFarmer_H +#define PokemonAutomation_PokemonSwSh_BerryFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BerryFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BerryFarmer_Descriptor(); +}; + + + +class BerryFarmer : public SingleSwitchProgramInstance{ +public: + BerryFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption SKIPS; + SimpleIntegerOption SAVE_ITERATIONS0; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.cpp index 9ea50e93c0..4467d3d448 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.cpp @@ -1,359 +1,359 @@ -/* Berry Farmer 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/Time.h" -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_DateSpam-BerryFarmer2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -BerryFarmer2_Descriptor::BerryFarmer2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:BerryFarmer2", - STRING_POKEMON + " SwSh", "Date Spam - Berry Farmer 2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-BerryFarmer2.md", - "Farm berries using Feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -class BerryFarmer2_Descriptor::Stats : public ShinyHuntTracker{ -public: - Stats() - : ShinyHuntTracker(true) - , days(m_stats["Days"]) - , shakes(m_stats["Shakes"]) - { - m_display_order.insert(m_display_order.begin() + 0, Stat("Days")); - m_display_order.insert(m_display_order.begin() + 1, Stat("Shakes")); - } - -public: - std::atomic& days; - std::atomic& shakes; -}; -std::unique_ptr BerryFarmer2_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -BerryFarmer2::BerryFarmer2() - : REQUIRES_AUDIO( - html_color_text( - "Rustling detection uses sound. Make sure you have the correct audio input set.", - COLOR_BLUE - ) - ) - , FETCH_ATTEMPTS( - "Number of Fetch Attempts:", - LockMode::UNLOCK_WHILE_RUNNING, - 100000 - ) - , SAVE_ITERATIONS0( - "Save Every this Many Fetches:
(zero disables saving): ", - LockMode::UNLOCK_WHILE_RUNNING, - 100 - ) - , ENCOUNTER_BOT_OPTIONS(false, true) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::UNLOCK_WHILE_RUNNING, - "10 s" - ) -// , START_BATTLE_TIMEOUT( -// "Start Battle Timeout:
After a battle is detected, wait this long to flee in seconds.", -// LockMode::LOCK_WHILE_RUNNING, -// 15 -// ) - , RUSTLING_INTERVAL( - "Rustling Interval:
How much time between two rustling sounds has to pass to be considered slow rustling in ms.", - LockMode::UNLOCK_WHILE_RUNNING, - 1350 - ) - , RUSTLING_TIMEOUT0( - "Rustling Timeout:
Wait this many ticks to detect rustling.", - LockMode::UNLOCK_WHILE_RUNNING, - "3200 ms" - ) - , SECONDARY_ATTEMPT_MASH_TIME0( - "Secondary attempt mash time:
Mash ZL this many ticks for secondary fetch attempts.", - LockMode::UNLOCK_WHILE_RUNNING, - "1920 ms" - ) - , SOUND_THRESHOLD( - "Maximum Sound Error Coefficient", - LockMode::UNLOCK_WHILE_RUNNING, - 0.75, 0, 1.0 - ) -{ - PA_ADD_OPTION(REQUIRES_AUDIO); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(FETCH_ATTEMPTS); - PA_ADD_OPTION(SAVE_ITERATIONS0); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -// PA_ADD_OPTION(START_BATTLE_TIMEOUT); - PA_ADD_OPTION(RUSTLING_INTERVAL); - PA_ADD_OPTION(RUSTLING_TIMEOUT0); - PA_ADD_OPTION(SECONDARY_ATTEMPT_MASH_TIME0); - PA_ADD_OPTION(SOUND_THRESHOLD); -} - - -BerryFarmer2::Rustling BerryFarmer2::check_rustling(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - BerryFarmer2_Descriptor::Stats& stats = env.current_stats(); - - // wait some time in order to not detect rustling from previous fetch attempt - pbf_wait(context, 80); - context.wait_for_all_requests(); - - BerryTreeRustlingSoundDetector initial_rustling_detector( - env.console, [&](float error_coefficient) -> bool { - // Warning: This callback will be run from a different thread than this function. - return true; - }, - (float)SOUND_THRESHOLD - ); - - BerryTreeRustlingSoundDetector secondary_rustling_detector( - env.console, [&](float error_coefficient) -> bool { - // Warning: This callback will be run from a different thread than this function. - return true; - }, - (float)SOUND_THRESHOLD - ); - - StandardBattleMenuWatcher battle_menu_detector(false); - StartBattleWatcher start_battle_detector; - - Rustling result = Rustling::No; - int ret = run_until( - env.console, context, - [&](ProControllerContext& context){ - pbf_wait(context, RUSTLING_TIMEOUT0); - context.wait_for_all_requests(); - }, - { {initial_rustling_detector}, {battle_menu_detector}, {start_battle_detector} } - ); - switch (ret){ - case 0:{ - env.console.log("BerryFarmer: Initial Rustling detected."); - WallClock initial_rustling_time = current_time(); - result = Rustling::Slow; - - int ret1 = run_until( - env.console, context, - [&](ProControllerContext& context){ - pbf_wait(context, RUSTLING_TIMEOUT0); - context.wait_for_all_requests(); - }, - { {secondary_rustling_detector} } - ); - - if (ret1 == 0){ - env.console.log("BerryFarmer: Secondary Rustling detected."); - WallClock secondary_rustling_time = current_time(); - if (std::chrono::duration_cast(secondary_rustling_time - initial_rustling_time).count() <= RUSTLING_INTERVAL){ - result = Rustling::Fast; - } - } - break; - } - case 1: - env.log("Unexpected battle menu.", COLOR_RED); - stats.add_error(); - env.update_stats(); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); - result = Rustling::Battle; - break; - case 2:{ - env.console.log("BerryFarmer: Battle Start detected."); -// wait_until(env.console, context, std::chrono::seconds(START_BATTLE_TIMEOUT), { battle_menu_detector }); - - // Detect shiny. - ShinyDetectionResult encounter_result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - bool stop = handler.handle_standard_encounter_end_battle(encounter_result, EXIT_BATTLE_TIMEOUT0); - if (stop){ - throw ProgramFinishedException(); - } - - result = Rustling::Battle; - break; - } - default: - result = Rustling::No; - } - - context.wait_for_all_requests(); - return result; -} - -uint16_t BerryFarmer2::do_secondary_attempts(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Rustling rustling){ - BerryFarmer2_Descriptor::Stats& stats = env.current_stats(); - - uint8_t no_rustling = (rustling == Rustling::No) ? 1 : 0; - Rustling current_rustling = rustling; - uint16_t attempts = 0; - - while ((current_rustling == Rustling::Slow || current_rustling == Rustling::No) && no_rustling < 3) { - /* Slow or No rustling, not in Battle! */ - pbf_mash_button(context, BUTTON_ZL, 240); - pbf_mash_button(context, BUTTON_B, 10); - attempts++; - stats.shakes++; - - current_rustling = check_rustling(env, context); - - if (current_rustling == Rustling::No){ - no_rustling++; - } - } - /* Fast rustling, in Battle or too many times No rustling */ - if (no_rustling >= 3){ - return attempts; - } - if (current_rustling == Rustling::Fast){ - // this is the last tree interaction for this time skip - pbf_mash_button(context, BUTTON_ZL, SECONDARY_ATTEMPT_MASH_TIME0); - pbf_mash_button(context, BUTTON_B, 10); - attempts++; - stats.shakes++; - current_rustling = check_rustling(env, context); - } - if (current_rustling == Rustling::Battle){ - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - env.console.log("Clearing dialog boxes..."); -// run_away(env.console, context, EXIT_BATTLE_TIMEOUT); -// context.wait_for_all_requests(); - } - return attempts; -} - -void BerryFarmer2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - BerryFarmer2_Descriptor::Stats& stats = env.current_stats(); - - uint8_t year = MAX_YEAR; - uint16_t save_count = 0; - uint32_t c = 0; - while (c < FETCH_ATTEMPTS){ - env.update_stats(); - uint16_t iteration_attempts = 1; - env.log("Fetch Attempts: " + tostr_u_commas(c)); - - home_roll_date_enter_game_autorollback(env.console, context, year); - stats.days++; - // Interact with the tree - pbf_mash_button(context, BUTTON_ZL, 375); - pbf_mash_button(context, BUTTON_B, 10); - stats.shakes++; - - // Rustling after the first fetch attempt - Rustling current_rustling = check_rustling(env, context); - - switch (current_rustling){ - case Rustling::Battle: - pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); - run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); - break; - case Rustling::Fast: - // Do nothing -> stop current tree session - break; - case Rustling::No: - case Rustling::Slow: - iteration_attempts += do_secondary_attempts(env, context, current_rustling); - break; - } - - // end tree session - pbf_mash_button(context, BUTTON_B, iteration_attempts > 1 ? 800 : 600); - - c += iteration_attempts; - - uint16_t save_iterations = SAVE_ITERATIONS0; - if (save_iterations != 0){ - save_count += iteration_attempts; - if (save_count >= save_iterations){ - save_count = 0; - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 20, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_ZL, 20, 3 * TICKS_PER_SECOND); - } - } - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - } - VideoSnapshot screen = env.console.video().snapshot(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, "", screen); -} -} - - - -} -} - +/* Berry Farmer 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Options/Environment/ThemeSelectorOption.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/Sounds/PokemonSwSh_BerryTreeRustlingSoundDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_DateSpam-BerryFarmer2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +BerryFarmer2_Descriptor::BerryFarmer2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:BerryFarmer2", + STRING_POKEMON + " SwSh", "Date Spam - Berry Farmer 2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-BerryFarmer2.md", + "Farm berries using Feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +class BerryFarmer2_Descriptor::Stats : public ShinyHuntTracker{ +public: + Stats() + : ShinyHuntTracker(true) + , days(m_stats["Days"]) + , shakes(m_stats["Shakes"]) + { + m_display_order.insert(m_display_order.begin() + 0, Stat("Days")); + m_display_order.insert(m_display_order.begin() + 1, Stat("Shakes")); + } + +public: + std::atomic& days; + std::atomic& shakes; +}; +std::unique_ptr BerryFarmer2_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +BerryFarmer2::BerryFarmer2() + : REQUIRES_AUDIO( + html_color_text( + "Rustling detection uses sound. Make sure you have the correct audio input set.", + COLOR_BLUE + ) + ) + , FETCH_ATTEMPTS( + "Number of Fetch Attempts:", + LockMode::UNLOCK_WHILE_RUNNING, + 100000 + ) + , SAVE_ITERATIONS0( + "Save Every this Many Fetches:
(zero disables saving): ", + LockMode::UNLOCK_WHILE_RUNNING, + 100 + ) + , ENCOUNTER_BOT_OPTIONS(false, true) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::UNLOCK_WHILE_RUNNING, + "10 s" + ) +// , START_BATTLE_TIMEOUT( +// "Start Battle Timeout:
After a battle is detected, wait this long to flee in seconds.", +// LockMode::LOCK_WHILE_RUNNING, +// 15 +// ) + , RUSTLING_INTERVAL( + "Rustling Interval:
How much time between two rustling sounds has to pass to be considered slow rustling in ms.", + LockMode::UNLOCK_WHILE_RUNNING, + 1350 + ) + , RUSTLING_TIMEOUT0( + "Rustling Timeout:
Wait this many ticks to detect rustling.", + LockMode::UNLOCK_WHILE_RUNNING, + "3200 ms" + ) + , SECONDARY_ATTEMPT_MASH_TIME0( + "Secondary attempt mash time:
Mash ZL this many ticks for secondary fetch attempts.", + LockMode::UNLOCK_WHILE_RUNNING, + "1920 ms" + ) + , SOUND_THRESHOLD( + "Maximum Sound Error Coefficient", + LockMode::UNLOCK_WHILE_RUNNING, + 0.75, 0, 1.0 + ) +{ + PA_ADD_OPTION(REQUIRES_AUDIO); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(FETCH_ATTEMPTS); + PA_ADD_OPTION(SAVE_ITERATIONS0); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +// PA_ADD_OPTION(START_BATTLE_TIMEOUT); + PA_ADD_OPTION(RUSTLING_INTERVAL); + PA_ADD_OPTION(RUSTLING_TIMEOUT0); + PA_ADD_OPTION(SECONDARY_ATTEMPT_MASH_TIME0); + PA_ADD_OPTION(SOUND_THRESHOLD); +} + + +BerryFarmer2::Rustling BerryFarmer2::check_rustling(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + BerryFarmer2_Descriptor::Stats& stats = env.current_stats(); + + // wait some time in order to not detect rustling from previous fetch attempt + pbf_wait(context, 80); + context.wait_for_all_requests(); + + BerryTreeRustlingSoundDetector initial_rustling_detector( + env.console, [&](float error_coefficient) -> bool { + // Warning: This callback will be run from a different thread than this function. + return true; + }, + (float)SOUND_THRESHOLD + ); + + BerryTreeRustlingSoundDetector secondary_rustling_detector( + env.console, [&](float error_coefficient) -> bool { + // Warning: This callback will be run from a different thread than this function. + return true; + }, + (float)SOUND_THRESHOLD + ); + + StandardBattleMenuWatcher battle_menu_detector(false); + StartBattleWatcher start_battle_detector; + + Rustling result = Rustling::No; + int ret = run_until( + env.console, context, + [&](ProControllerContext& context){ + pbf_wait(context, RUSTLING_TIMEOUT0); + context.wait_for_all_requests(); + }, + { {initial_rustling_detector}, {battle_menu_detector}, {start_battle_detector} } + ); + switch (ret){ + case 0:{ + env.console.log("BerryFarmer: Initial Rustling detected."); + WallClock initial_rustling_time = current_time(); + result = Rustling::Slow; + + int ret1 = run_until( + env.console, context, + [&](ProControllerContext& context){ + pbf_wait(context, RUSTLING_TIMEOUT0); + context.wait_for_all_requests(); + }, + { {secondary_rustling_detector} } + ); + + if (ret1 == 0){ + env.console.log("BerryFarmer: Secondary Rustling detected."); + WallClock secondary_rustling_time = current_time(); + if (std::chrono::duration_cast(secondary_rustling_time - initial_rustling_time).count() <= RUSTLING_INTERVAL){ + result = Rustling::Fast; + } + } + break; + } + case 1: + env.log("Unexpected battle menu.", COLOR_RED); + stats.add_error(); + env.update_stats(); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); + result = Rustling::Battle; + break; + case 2:{ + env.console.log("BerryFarmer: Battle Start detected."); +// wait_until(env.console, context, std::chrono::seconds(START_BATTLE_TIMEOUT), { battle_menu_detector }); + + // Detect shiny. + ShinyDetectionResult encounter_result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + bool stop = handler.handle_standard_encounter_end_battle(encounter_result, EXIT_BATTLE_TIMEOUT0); + if (stop){ + throw ProgramFinishedException(); + } + + result = Rustling::Battle; + break; + } + default: + result = Rustling::No; + } + + context.wait_for_all_requests(); + return result; +} + +uint16_t BerryFarmer2::do_secondary_attempts(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Rustling rustling){ + BerryFarmer2_Descriptor::Stats& stats = env.current_stats(); + + uint8_t no_rustling = (rustling == Rustling::No) ? 1 : 0; + Rustling current_rustling = rustling; + uint16_t attempts = 0; + + while ((current_rustling == Rustling::Slow || current_rustling == Rustling::No) && no_rustling < 3) { + /* Slow or No rustling, not in Battle! */ + pbf_mash_button(context, BUTTON_ZL, 240); + pbf_mash_button(context, BUTTON_B, 10); + attempts++; + stats.shakes++; + + current_rustling = check_rustling(env, context); + + if (current_rustling == Rustling::No){ + no_rustling++; + } + } + /* Fast rustling, in Battle or too many times No rustling */ + if (no_rustling >= 3){ + return attempts; + } + if (current_rustling == Rustling::Fast){ + // this is the last tree interaction for this time skip + pbf_mash_button(context, BUTTON_ZL, SECONDARY_ATTEMPT_MASH_TIME0); + pbf_mash_button(context, BUTTON_B, 10); + attempts++; + stats.shakes++; + current_rustling = check_rustling(env, context); + } + if (current_rustling == Rustling::Battle){ + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + env.console.log("Clearing dialog boxes..."); +// run_away(env.console, context, EXIT_BATTLE_TIMEOUT); +// context.wait_for_all_requests(); + } + return attempts; +} + +void BerryFarmer2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + BerryFarmer2_Descriptor::Stats& stats = env.current_stats(); + + uint8_t year = MAX_YEAR; + uint16_t save_count = 0; + uint32_t c = 0; + while (c < FETCH_ATTEMPTS){ + env.update_stats(); + uint16_t iteration_attempts = 1; + env.log("Fetch Attempts: " + tostr_u_commas(c)); + + home_roll_date_enter_game_autorollback(env.console, context, year); + stats.days++; + // Interact with the tree + pbf_mash_button(context, BUTTON_ZL, 375); + pbf_mash_button(context, BUTTON_B, 10); + stats.shakes++; + + // Rustling after the first fetch attempt + Rustling current_rustling = check_rustling(env, context); + + switch (current_rustling){ + case Rustling::Battle: + pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); + run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); + break; + case Rustling::Fast: + // Do nothing -> stop current tree session + break; + case Rustling::No: + case Rustling::Slow: + iteration_attempts += do_secondary_attempts(env, context, current_rustling); + break; + } + + // end tree session + pbf_mash_button(context, BUTTON_B, iteration_attempts > 1 ? 800 : 600); + + c += iteration_attempts; + + uint16_t save_iterations = SAVE_ITERATIONS0; + if (save_iterations != 0){ + save_count += iteration_attempts; + if (save_count >= save_iterations){ + save_count = 0; + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 20, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_ZL, 20, 3 * TICKS_PER_SECOND); + } + } + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + } + VideoSnapshot screen = env.console.video().snapshot(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, "", screen); +} +} + + + +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h index f3e47ae577..588d29e639 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-BerryFarmer2.h @@ -1,82 +1,82 @@ -/* Berry Farmer 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BerryFarmer2_H -#define PokemonAutomation_PokemonSwSh_BerryFarmer2_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class BerryFarmer2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BerryFarmer2_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class BerryFarmer2 : public SingleSwitchProgramInstance{ -public: - BerryFarmer2(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - enum Rustling{ - No, - Slow, - Fast, - Battle - }; - -private: - Rustling check_rustling(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - uint16_t do_secondary_attempts(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Rustling last_rustling); - -private: - StaticTextOption REQUIRES_AUDIO; - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption FETCH_ATTEMPTS; - SimpleIntegerOption SAVE_ITERATIONS0; - - EncounterBotLanguage LANGUAGE; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -// SimpleIntegerOption START_BATTLE_TIMEOUT; - SimpleIntegerOption RUSTLING_INTERVAL; - MillisecondsOption RUSTLING_TIMEOUT0; - MillisecondsOption SECONDARY_ATTEMPT_MASH_TIME0; - FloatingPointOption SOUND_THRESHOLD; -}; - - -} -} -} -#endif - - - +/* Berry Farmer 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BerryFarmer2_H +#define PokemonAutomation_PokemonSwSh_BerryFarmer2_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class BerryFarmer2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BerryFarmer2_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class BerryFarmer2 : public SingleSwitchProgramInstance{ +public: + BerryFarmer2(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + enum Rustling{ + No, + Slow, + Fast, + Battle + }; + +private: + Rustling check_rustling(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + uint16_t do_secondary_attempts(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Rustling last_rustling); + +private: + StaticTextOption REQUIRES_AUDIO; + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption FETCH_ATTEMPTS; + SimpleIntegerOption SAVE_ITERATIONS0; + + EncounterBotLanguage LANGUAGE; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +// SimpleIntegerOption START_BATTLE_TIMEOUT; + SimpleIntegerOption RUSTLING_INTERVAL; + MillisecondsOption RUSTLING_TIMEOUT0; + MillisecondsOption SECONDARY_ATTEMPT_MASH_TIME0; + FloatingPointOption SOUND_THRESHOLD; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.cpp index 844881a893..77e0da474f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.cpp @@ -1,103 +1,103 @@ -/* Daily Highlight Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateSpam-DailyHighlightFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -DailyHighlightFarmer_Descriptor::DailyHighlightFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DailyHighlightFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Daily Highlight Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-DailyHighlightFarmer.md", - "Farm the daily highlight watt trader in Crown Tundra.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - - -DailyHighlightFarmer::DailyHighlightFarmer() - : SKIPS( - "Number of Purchase Attempts:", - LockMode::LOCK_WHILE_RUNNING, - 100000 - ) - , SAVE_ITERATIONS0( - "Save Every this Many Fetches:
(zero disables saving): ", - LockMode::LOCK_WHILE_RUNNING, - 100 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(SAVE_ITERATIONS0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void DailyHighlightFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - uint8_t year = MAX_YEAR; - uint16_t save_count = 0; - for (uint32_t c = 0; c < SKIPS; c++){ - env.log("Fetch Attempts: " + tostr_u_commas(c)); - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - - pbf_press_button(context, BUTTON_A, 10, 110); - pbf_press_button(context, BUTTON_ZL, 10, 40); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - pbf_mash_button(context, BUTTON_ZL, 400); - pbf_mash_button(context, BUTTON_B, 700); - - if (SAVE_ITERATIONS0 != 0){ - save_count++; - if (save_count >= SAVE_ITERATIONS0){ - save_count = 0; - pbf_mash_button(context, BUTTON_B, 2000ms); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 160ms, 2000ms); - pbf_press_button(context, BUTTON_ZL, 160ms, 3000ms); - } - } - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} - +/* Daily Highlight Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateSpam-DailyHighlightFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +DailyHighlightFarmer_Descriptor::DailyHighlightFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DailyHighlightFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Daily Highlight Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-DailyHighlightFarmer.md", + "Farm the daily highlight watt trader in Crown Tundra.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + + +DailyHighlightFarmer::DailyHighlightFarmer() + : SKIPS( + "Number of Purchase Attempts:", + LockMode::LOCK_WHILE_RUNNING, + 100000 + ) + , SAVE_ITERATIONS0( + "Save Every this Many Fetches:
(zero disables saving): ", + LockMode::LOCK_WHILE_RUNNING, + 100 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(SAVE_ITERATIONS0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void DailyHighlightFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + uint8_t year = MAX_YEAR; + uint16_t save_count = 0; + for (uint32_t c = 0; c < SKIPS; c++){ + env.log("Fetch Attempts: " + tostr_u_commas(c)); + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + + pbf_press_button(context, BUTTON_A, 10, 110); + pbf_press_button(context, BUTTON_ZL, 10, 40); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + pbf_mash_button(context, BUTTON_ZL, 400); + pbf_mash_button(context, BUTTON_B, 700); + + if (SAVE_ITERATIONS0 != 0){ + save_count++; + if (save_count >= SAVE_ITERATIONS0){ + save_count = 0; + pbf_mash_button(context, BUTTON_B, 2000ms); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 160ms, 2000ms); + pbf_press_button(context, BUTTON_ZL, 160ms, 3000ms); + } + } + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h index 8df33dce59..ebac95f055 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-DailyHighlightFarmer.h @@ -1,49 +1,49 @@ -/* Daily Highlight Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightFarmer_H -#define PokemonAutomation_PokemonSwSh_DailyHighlightFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DailyHighlightFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DailyHighlightFarmer_Descriptor(); -}; - - - -class DailyHighlightFarmer : public SingleSwitchProgramInstance{ -public: - DailyHighlightFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption SKIPS; - SimpleIntegerOption SAVE_ITERATIONS0; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Daily Highlight Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightFarmer_H +#define PokemonAutomation_PokemonSwSh_DailyHighlightFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DailyHighlightFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DailyHighlightFarmer_Descriptor(); +}; + + + +class DailyHighlightFarmer : public SingleSwitchProgramInstance{ +public: + DailyHighlightFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption SKIPS; + SimpleIntegerOption SAVE_ITERATIONS0; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.cpp index 99ab147be0..8c018e74ca 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.cpp @@ -1,91 +1,91 @@ -/* Loto Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateSpam-LotoFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -LotoFarmer_Descriptor::LotoFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:LotoFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Loto Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-LotoFarmer.md", - "Farm the Loto ID.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - - -LotoFarmer::LotoFarmer() - : SKIPS( - "Number of Loto Attempts:", - LockMode::LOCK_WHILE_RUNNING, - 100000 - ) - , MASH_B_DURATION0( - "Mash B for this long to exit the dialog:
(Some languages like German need to increase this.)", - LockMode::LOCK_WHILE_RUNNING, - "9000 ms" - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(MASH_B_DURATION0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void LotoFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - uint8_t year = MAX_YEAR; - for (uint32_t c = 0; c < SKIPS; c++){ - env.log("Fetch Attempts: " + tostr_u_commas(c)); - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - - pbf_press_button(context, BUTTON_A, 10, 90); - pbf_press_button(context, BUTTON_B, 10, 70); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); - pbf_mash_button(context, BUTTON_ZL, 490); - pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* Loto Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateSpam-LotoFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +LotoFarmer_Descriptor::LotoFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:LotoFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Loto Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-LotoFarmer.md", + "Farm the Loto ID.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + + +LotoFarmer::LotoFarmer() + : SKIPS( + "Number of Loto Attempts:", + LockMode::LOCK_WHILE_RUNNING, + 100000 + ) + , MASH_B_DURATION0( + "Mash B for this long to exit the dialog:
(Some languages like German need to increase this.)", + LockMode::LOCK_WHILE_RUNNING, + "9000 ms" + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(MASH_B_DURATION0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void LotoFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + uint8_t year = MAX_YEAR; + for (uint32_t c = 0; c < SKIPS; c++){ + env.log("Fetch Attempts: " + tostr_u_commas(c)); + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + + pbf_press_button(context, BUTTON_A, 10, 90); + pbf_press_button(context, BUTTON_B, 10, 70); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); + pbf_mash_button(context, BUTTON_ZL, 490); + pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h index e4d6016802..0f4061dce9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-LotoFarmer.h @@ -1,50 +1,50 @@ -/* Loto Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_LotoFarmer_H -#define PokemonAutomation_PokemonSwSh_LotoFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class LotoFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - LotoFarmer_Descriptor(); -}; - - - -class LotoFarmer : public SingleSwitchProgramInstance{ -public: - LotoFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption SKIPS; - MillisecondsOption MASH_B_DURATION0; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Loto Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_LotoFarmer_H +#define PokemonAutomation_PokemonSwSh_LotoFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class LotoFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + LotoFarmer_Descriptor(); +}; + + + +class LotoFarmer : public SingleSwitchProgramInstance{ +public: + LotoFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption SKIPS; + MillisecondsOption MASH_B_DURATION0; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.cpp index 26f8714f11..ed46ed3615 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.cpp @@ -1,173 +1,173 @@ -/* Poke Jobs Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateSpam-PokeJobsFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - - -PokeJobsFarmer_Descriptor::PokeJobsFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:PokeJobsFarmer", - STRING_POKEMON + " SwSh", - "Date Spam - " + STRING_POKEJOB + "s Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-PokeJobsFarmer.md", - "Farm " + STRING_POKEJOB + "s.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -PokeJobsFarmer::PokeJobsFarmer() - : SKIPS( - "Number of days:", - LockMode::LOCK_WHILE_RUNNING, - 200 - ) - , CONCURRENCY( - "Number of concurrent " + STRING_POKEJOB + "s per day:", - LockMode::LOCK_WHILE_RUNNING, - 2 - ) - , MENU_INDEX( - "Index of " + STRING_POKEJOB + "s in Rotom menu:", - LockMode::LOCK_WHILE_RUNNING, - 3 - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MASH_B_DURATION0( - "Mash B for this long upon completion of " + STRING_POKEJOB + ":", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(CONCURRENCY); - PA_ADD_OPTION(MENU_INDEX); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(MASH_B_DURATION0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -static void enter_jobs(ProControllerContext& context, uint16_t index){ - // Enter menu - pbf_press_button(context, BUTTON_A, 10, 90); - pbf_press_button(context, BUTTON_B, 10, 90); - // Select entry - for (uint16_t i = 1; i < index; i++){ - ssf_press_dpad_ptv(context, DPAD_DOWN, 160ms); - } - pbf_press_button(context, BUTTON_A, 80ms, 5000ms); // Wait for animation to complete -} - -void PokeJobsFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - uint8_t year = MAX_YEAR; - - // Play it safe in case some menu is open - pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); - - for (uint32_t c = 0; c < SKIPS; c++){ - if (MAX_YEAR <= year){ - // Roll back to 2001 - env.log("Rolling back!"); - ssf_press_button_ptv(context, BUTTON_B, 80ms); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); - - // Get rid of new jobs notification by entering Poke Jobs and leaving immediately - enter_jobs(context, MENU_INDEX); - pbf_mash_button(context, BUTTON_B, 5000ms); - } - - // Start new jobs - for (uint16_t j = 1; j <= CONCURRENCY; j++){ - env.log("Starting job #" + tostr_u_commas(j) + " in year " + tostr_u_commas(2000 + year)); - - // Enter Poke Jobs - enter_jobs(context, MENU_INDEX); - - // Select first Poke Job - env.log("#### Select first " + STRING_POKEJOB); - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - pbf_press_button(context, BUTTON_A, 80ms, 3000ms); - - // Select all Pokemons - env.log("#### Select all"); - pbf_press_button(context, BUTTON_X, 10, 90); - - // Send to Poke Job - env.log("#### Send to " + STRING_POKEJOB); - pbf_press_button(context, BUTTON_B, 80ms, 2000ms); - pbf_mash_button(context, BUTTON_A, 6000ms); // Mash until animation starts - - // Wait for animation to end and exit Poke Jobs - env.log("#### Exit " + STRING_POKEJOB + "s"); - pbf_mash_button(context, BUTTON_B, 5000ms); - } - - env.log("Skipping one year..."); - - // Go to home menu - env.log("#### Go to Switch home menu"); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - - // Skip frame - env.log("#### Skip frame"); - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 1000ms); - - // Get rid of new jobs notification by entering Poke Jobs and leaving immediately - enter_jobs(context, MENU_INDEX); - pbf_mash_button(context, BUTTON_B, 5000ms); - - // Complete jobs - for (uint16_t j = 1; j <= CONCURRENCY; j++){ - env.log("Completing job #" + tostr_u_commas(j) + " in year " + tostr_u_commas(2000 + year)); - - // Enter Poke Jobs - enter_jobs(context, MENU_INDEX); - - // Select first Poke Job - env.log("#### Select first " + STRING_POKEJOB); - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - pbf_press_button(context, BUTTON_A, 80ms, 10000ms); // Wait for animation to complete - - // Skip through wall of text and exit - env.log("#### Exit " + STRING_POKEJOB + "s"); - pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); - } - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} +/* Poke Jobs Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateSpam-PokeJobsFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + + +PokeJobsFarmer_Descriptor::PokeJobsFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:PokeJobsFarmer", + STRING_POKEMON + " SwSh", + "Date Spam - " + STRING_POKEJOB + "s Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-PokeJobsFarmer.md", + "Farm " + STRING_POKEJOB + "s.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +PokeJobsFarmer::PokeJobsFarmer() + : SKIPS( + "Number of days:", + LockMode::LOCK_WHILE_RUNNING, + 200 + ) + , CONCURRENCY( + "Number of concurrent " + STRING_POKEJOB + "s per day:", + LockMode::LOCK_WHILE_RUNNING, + 2 + ) + , MENU_INDEX( + "Index of " + STRING_POKEJOB + "s in Rotom menu:", + LockMode::LOCK_WHILE_RUNNING, + 3 + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MASH_B_DURATION0( + "Mash B for this long upon completion of " + STRING_POKEJOB + ":", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(CONCURRENCY); + PA_ADD_OPTION(MENU_INDEX); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(MASH_B_DURATION0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +static void enter_jobs(ProControllerContext& context, uint16_t index){ + // Enter menu + pbf_press_button(context, BUTTON_A, 10, 90); + pbf_press_button(context, BUTTON_B, 10, 90); + // Select entry + for (uint16_t i = 1; i < index; i++){ + ssf_press_dpad_ptv(context, DPAD_DOWN, 160ms); + } + pbf_press_button(context, BUTTON_A, 80ms, 5000ms); // Wait for animation to complete +} + +void PokeJobsFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + uint8_t year = MAX_YEAR; + + // Play it safe in case some menu is open + pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); + + for (uint32_t c = 0; c < SKIPS; c++){ + if (MAX_YEAR <= year){ + // Roll back to 2001 + env.log("Rolling back!"); + ssf_press_button_ptv(context, BUTTON_B, 80ms); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); + + // Get rid of new jobs notification by entering Poke Jobs and leaving immediately + enter_jobs(context, MENU_INDEX); + pbf_mash_button(context, BUTTON_B, 5000ms); + } + + // Start new jobs + for (uint16_t j = 1; j <= CONCURRENCY; j++){ + env.log("Starting job #" + tostr_u_commas(j) + " in year " + tostr_u_commas(2000 + year)); + + // Enter Poke Jobs + enter_jobs(context, MENU_INDEX); + + // Select first Poke Job + env.log("#### Select first " + STRING_POKEJOB); + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + pbf_press_button(context, BUTTON_A, 80ms, 3000ms); + + // Select all Pokemons + env.log("#### Select all"); + pbf_press_button(context, BUTTON_X, 10, 90); + + // Send to Poke Job + env.log("#### Send to " + STRING_POKEJOB); + pbf_press_button(context, BUTTON_B, 80ms, 2000ms); + pbf_mash_button(context, BUTTON_A, 6000ms); // Mash until animation starts + + // Wait for animation to end and exit Poke Jobs + env.log("#### Exit " + STRING_POKEJOB + "s"); + pbf_mash_button(context, BUTTON_B, 5000ms); + } + + env.log("Skipping one year..."); + + // Go to home menu + env.log("#### Go to Switch home menu"); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + + // Skip frame + env.log("#### Skip frame"); + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 1000ms); + + // Get rid of new jobs notification by entering Poke Jobs and leaving immediately + enter_jobs(context, MENU_INDEX); + pbf_mash_button(context, BUTTON_B, 5000ms); + + // Complete jobs + for (uint16_t j = 1; j <= CONCURRENCY; j++){ + env.log("Completing job #" + tostr_u_commas(j) + " in year " + tostr_u_commas(2000 + year)); + + // Enter Poke Jobs + enter_jobs(context, MENU_INDEX); + + // Select first Poke Job + env.log("#### Select first " + STRING_POKEJOB); + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + pbf_press_button(context, BUTTON_A, 80ms, 10000ms); // Wait for animation to complete + + // Skip through wall of text and exit + env.log("#### Exit " + STRING_POKEJOB + "s"); + pbf_mash_button(context, BUTTON_B, MASH_B_DURATION0); + } + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h index 16558b69ba..af71968d48 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-PokeJobsFarmer.h @@ -1,52 +1,52 @@ -/* PokeJobs Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_PokeJobsFarmer_H -#define PokemonAutomation_PokemonSwSh_PokeJobsFarmer_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class PokeJobsFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PokeJobsFarmer_Descriptor(); -}; - -class PokeJobsFarmer : public SingleSwitchProgramInstance{ -public: - PokeJobsFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption SKIPS; - SimpleIntegerOption CONCURRENCY; - SimpleIntegerOption MENU_INDEX; - - SectionDividerOption m_advanced_options; - - MillisecondsOption MASH_B_DURATION0; - - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* PokeJobs Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_PokeJobsFarmer_H +#define PokemonAutomation_PokemonSwSh_PokeJobsFarmer_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class PokeJobsFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PokeJobsFarmer_Descriptor(); +}; + +class PokeJobsFarmer : public SingleSwitchProgramInstance{ +public: + PokeJobsFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption SKIPS; + SimpleIntegerOption CONCURRENCY; + SimpleIntegerOption MENU_INDEX; + + SectionDividerOption m_advanced_options; + + MillisecondsOption MASH_B_DURATION0; + + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.cpp index 4251e6c50c..abea6fe1e8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.cpp @@ -1,100 +1,100 @@ -/* Stow-On-Side Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateSpam-StowOnSideFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -StowOnSideFarmer_Descriptor::StowOnSideFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:StowOnSideFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Stow-On-Side Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-StowOnSideFarmer.md", - "Farm the Stow-on-Side items dealer.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - - -StowOnSideFarmer::StowOnSideFarmer() - : SKIPS( - "Number of Purchase Attempts:", - LockMode::LOCK_WHILE_RUNNING, - 100000 - ) - , SAVE_ITERATIONS0( - "Save Every this Many Fetches:
(zero disables saving): ", - LockMode::LOCK_WHILE_RUNNING, - 100 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(SAVE_ITERATIONS0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void StowOnSideFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - uint8_t year = MAX_YEAR; - uint16_t save_count = 0; - for (uint32_t c = 0; c < SKIPS; c++){ - env.log("Fetch Attempts: " + tostr_u_commas(c)); - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - - ssf_press_button_ptv(context, BUTTON_A, 160ms); - pbf_mash_button(context, BUTTON_ZL, 385); - pbf_mash_button(context, BUTTON_B, 700); - - if (SAVE_ITERATIONS0 != 0){ - save_count++; - if (save_count >= SAVE_ITERATIONS0){ - save_count = 0; - pbf_mash_button(context, BUTTON_B, 2000ms); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 160ms, 2000ms); - pbf_press_button(context, BUTTON_ZL, 160ms, 3000ms); - } - } - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* Stow-On-Side Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateSpam-StowOnSideFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +StowOnSideFarmer_Descriptor::StowOnSideFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:StowOnSideFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Stow-On-Side Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-StowOnSideFarmer.md", + "Farm the Stow-on-Side items dealer.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + + +StowOnSideFarmer::StowOnSideFarmer() + : SKIPS( + "Number of Purchase Attempts:", + LockMode::LOCK_WHILE_RUNNING, + 100000 + ) + , SAVE_ITERATIONS0( + "Save Every this Many Fetches:
(zero disables saving): ", + LockMode::LOCK_WHILE_RUNNING, + 100 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(SAVE_ITERATIONS0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void StowOnSideFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + uint8_t year = MAX_YEAR; + uint16_t save_count = 0; + for (uint32_t c = 0; c < SKIPS; c++){ + env.log("Fetch Attempts: " + tostr_u_commas(c)); + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + + ssf_press_button_ptv(context, BUTTON_A, 160ms); + pbf_mash_button(context, BUTTON_ZL, 385); + pbf_mash_button(context, BUTTON_B, 700); + + if (SAVE_ITERATIONS0 != 0){ + save_count++; + if (save_count >= SAVE_ITERATIONS0){ + save_count = 0; + pbf_mash_button(context, BUTTON_B, 2000ms); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 160ms, 2000ms); + pbf_press_button(context, BUTTON_ZL, 160ms, 3000ms); + } + } + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h index f8b7445b47..c7bfdcf7ab 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-StowOnSideFarmer.h @@ -1,49 +1,49 @@ -/* Stow-On-Side Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StowOnSideFarmer_H -#define PokemonAutomation_PokemonSwSh_StowOnSideFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class StowOnSideFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StowOnSideFarmer_Descriptor(); -}; - - - -class StowOnSideFarmer : public SingleSwitchProgramInstance{ -public: - StowOnSideFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption SKIPS; - SimpleIntegerOption SAVE_ITERATIONS0; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Stow-On-Side Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StowOnSideFarmer_H +#define PokemonAutomation_PokemonSwSh_StowOnSideFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class StowOnSideFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StowOnSideFarmer_Descriptor(); +}; + + + +class StowOnSideFarmer : public SingleSwitchProgramInstance{ +public: + StowOnSideFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption SKIPS; + SimpleIntegerOption SAVE_ITERATIONS0; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.cpp index 48ede4f866..99cf04deed 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.cpp @@ -1,117 +1,117 @@ -/* Watt Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DateSpam-WattFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -WattFarmer_Descriptor::WattFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:WattFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Watt Farmer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-WattFarmer.md", - "Farm watts. (7.2 seconds/fetch, 1 million watts/hour with a tick-precise controller)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - - -WattFarmer::WattFarmer() - : GRIP_MENU_WAIT0( - "Exit Grip Menu Delay:
" - "Wait this long after leaving the grip menu to allow for the Switch to reestablish local connection.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , EXIT_DEN_WAIT( - "Exit Den Wait Time:
" - "Wait this long after backing out of the den before date skipping.", - LockMode::LOCK_WHILE_RUNNING, - "1720 ms" - ) - , SKIPS( - "Number of Fetch Attempts:", - LockMode::LOCK_WHILE_RUNNING, - 33334 - ) - , SAVE_ITERATIONS0( - "Save Every this Many Fetches:
(zero disables saving): ", - LockMode::LOCK_WHILE_RUNNING, - 100 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(GRIP_MENU_WAIT0); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(EXIT_DEN_WAIT); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(SAVE_ITERATIONS0); - PA_ADD_OPTION(NOTIFICATIONS); -} - -void WattFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - pbf_wait(context, GRIP_MENU_WAIT0); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - uint8_t year = MAX_YEAR; - uint16_t save_count = 0; - for (uint32_t c = 0; c < SKIPS; c++){ - env.log("Fetch Attempts: " + tostr_u_commas(c)); - - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - - ssf_press_button_ptv(context, BUTTON_A, 40ms); - pbf_mash_button(context, BUTTON_B, EXIT_DEN_WAIT); - - if (SAVE_ITERATIONS0 != 0){ - save_count++; - if (save_count >= SAVE_ITERATIONS0){ - save_count = 0; - pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 20, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_ZL, 20, 3 * TICKS_PER_SECOND); - } - } - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} - +/* Watt Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DateSpam-WattFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +WattFarmer_Descriptor::WattFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:WattFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Watt Farmer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DateSpam-WattFarmer.md", + "Farm watts. (7.2 seconds/fetch, 1 million watts/hour with a tick-precise controller)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + + +WattFarmer::WattFarmer() + : GRIP_MENU_WAIT0( + "Exit Grip Menu Delay:
" + "Wait this long after leaving the grip menu to allow for the Switch to reestablish local connection.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , EXIT_DEN_WAIT( + "Exit Den Wait Time:
" + "Wait this long after backing out of the den before date skipping.", + LockMode::LOCK_WHILE_RUNNING, + "1720 ms" + ) + , SKIPS( + "Number of Fetch Attempts:", + LockMode::LOCK_WHILE_RUNNING, + 33334 + ) + , SAVE_ITERATIONS0( + "Save Every this Many Fetches:
(zero disables saving): ", + LockMode::LOCK_WHILE_RUNNING, + 100 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(GRIP_MENU_WAIT0); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(EXIT_DEN_WAIT); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(SAVE_ITERATIONS0); + PA_ADD_OPTION(NOTIFICATIONS); +} + +void WattFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + pbf_wait(context, GRIP_MENU_WAIT0); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + uint8_t year = MAX_YEAR; + uint16_t save_count = 0; + for (uint32_t c = 0; c < SKIPS; c++){ + env.log("Fetch Attempts: " + tostr_u_commas(c)); + + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + + ssf_press_button_ptv(context, BUTTON_A, 40ms); + pbf_mash_button(context, BUTTON_B, EXIT_DEN_WAIT); + + if (SAVE_ITERATIONS0 != 0){ + save_count++; + if (save_count >= SAVE_ITERATIONS0){ + save_count = 0; + pbf_mash_button(context, BUTTON_B, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 20, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_ZL, 20, 3 * TICKS_PER_SECOND); + } + } + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h index 6c31c6f2b4..ff4131982c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattFarmer.h @@ -1,53 +1,53 @@ -/* Watt Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_WattFarmer_H -#define PokemonAutomation_PokemonSwSh_WattFarmer_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class WattFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - WattFarmer_Descriptor(); -}; - - - -class WattFarmer : public SingleSwitchProgramInstance{ -public: - WattFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - MillisecondsOption GRIP_MENU_WAIT0; - MillisecondsOption EXIT_DEN_WAIT; - - SimpleIntegerOption SKIPS; - SimpleIntegerOption SAVE_ITERATIONS0; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif - - - +/* Watt Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_WattFarmer_H +#define PokemonAutomation_PokemonSwSh_WattFarmer_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class WattFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + WattFarmer_Descriptor(); +}; + + + +class WattFarmer : public SingleSwitchProgramInstance{ +public: + WattFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + MillisecondsOption GRIP_MENU_WAIT0; + MillisecondsOption EXIT_DEN_WAIT; + + SimpleIntegerOption SKIPS; + SimpleIntegerOption SAVE_ITERATIONS0; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp index 38cfadbce1..62e78e34bb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.cpp @@ -1,194 +1,194 @@ -/* Watt Trader Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh_DateSpam-WattTraderFarmer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -WattTraderFarmer_Descriptor::WattTraderFarmer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:WattTraderFarmer", - STRING_POKEMON + " SwSh", "Date Spam - Watt Trader Farmer", - "", - "Buy as much stuff from a watt trader as possible - day skipping as needed to reroll items.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -class WattTraderFarmer_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : day_skips(m_stats["Day Skips"]) - , items_probed(m_stats["Items Probed"]) - , failed(m_stats["Failed"]) - , success(m_stats["Success"]) - , errors(m_stats["Errors"]) - { - m_display_order.insert(m_display_order.begin() + 0, Stat("Day Skips")); - m_display_order.insert(m_display_order.begin() + 1, Stat("Items Probed")); - m_display_order.insert(m_display_order.begin() + 2, Stat("Failed")); - m_display_order.insert(m_display_order.begin() + 3, Stat("Success")); - m_display_order.insert(m_display_order.begin() + 4, Stat("Errors")); - } - -public: - std::atomic& day_skips; - std::atomic& items_probed; - std::atomic& failed; - std::atomic& success; - std::atomic& errors; -}; -std::unique_ptr WattTraderFarmer_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -WattTraderFarmer::WattTraderFarmer(){ - -} - - - -class BuyCursorDetector : public SelectionArrowFinder{ -public: - BuyCursorDetector(VideoOverlay& overlay) - : SelectionArrowFinder(overlay, ImageFloatBox(0.448775, 0.087129, 0.062361, 0.596040)) - {} -}; -class BuyQuantityDetector : public VisualInferenceCallback{ -public: - BuyQuantityDetector() - : VisualInferenceCallback("BuyQuantityDetector") - , m_box(0.814031, 0.681188, 0.170379, 0.045545) - {} - virtual void make_overlays(VideoOverlaySet& items) const override{ - items.add(COLOR_GREEN, m_box); - } - virtual bool process_frame(const VideoSnapshot& frame) override{ - ImageStats stats = image_stats(extract_box_reference(frame, m_box)); - return is_solid(stats, {0.62963, 0.37037, 0.}); - } - -private: - ImageFloatBox m_box; -}; - - - -void WattTraderFarmer::buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); - - bool purchased = false; - while (true){ - DialogTriangleDetector dialog(env.logger(), env.console, true); - BuyCursorDetector item_select(env.console); - BuyQuantityDetector quantity; - context.wait_for_all_requests(); - int ret = wait_until( - env.console, context, - std::chrono::seconds(10), - { - dialog, - item_select, - quantity, - } - ); - context.wait_for(200ms); - switch (ret){ - case 0: - env.log("Detected dialog...", COLOR_BLUE); - if (!purchased){ - stats.failed++; - env.update_stats(); - } - pbf_press_button(context, BUTTON_B, 200ms, 800ms); - return; - case 1: - env.log("Detected item select...", COLOR_BLUE); - if (purchased){ - return; - } - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - continue; - case 2: - env.log("Detected quantity select...", COLOR_BLUE); - stats.success++; - env.update_stats(); - pbf_press_dpad(context, DPAD_DOWN, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - purchased = true; - continue; - default: - env.log("No recognized state after 5 seconds.", COLOR_RED); - stats.errors++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 5000ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - continue; - } - } -} - - - -void WattTraderFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); - - uint8_t year = MAX_YEAR; - while (true){ - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - pbf_press_button(context, BUTTON_A, 200ms, 800ms); - - for (size_t c = 0; c < 7; c++){ - buy_one(env, context); - stats.items_probed++; - env.update_stats(); - pbf_press_dpad(context, DPAD_DOWN, 200ms, 200ms); - } - - pbf_mash_button(context, BUTTON_B, 5000ms); - - // Tap HOME and quickly spam B. The B spamming ensures that we don't - // accidentally update the system if the system update window pops up. - ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); - pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); - - home_roll_date_enter_game_autorollback(env.console, context, year); - pbf_mash_button(context, BUTTON_B, 90); - stats.day_skips++; - env.update_stats(); - } -} - - - - - -} -} -} +/* Watt Trader Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/PokemonSwSh_DialogTriangleDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh_DateSpam-WattTraderFarmer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +WattTraderFarmer_Descriptor::WattTraderFarmer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:WattTraderFarmer", + STRING_POKEMON + " SwSh", "Date Spam - Watt Trader Farmer", + "", + "Buy as much stuff from a watt trader as possible - day skipping as needed to reroll items.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +class WattTraderFarmer_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : day_skips(m_stats["Day Skips"]) + , items_probed(m_stats["Items Probed"]) + , failed(m_stats["Failed"]) + , success(m_stats["Success"]) + , errors(m_stats["Errors"]) + { + m_display_order.insert(m_display_order.begin() + 0, Stat("Day Skips")); + m_display_order.insert(m_display_order.begin() + 1, Stat("Items Probed")); + m_display_order.insert(m_display_order.begin() + 2, Stat("Failed")); + m_display_order.insert(m_display_order.begin() + 3, Stat("Success")); + m_display_order.insert(m_display_order.begin() + 4, Stat("Errors")); + } + +public: + std::atomic& day_skips; + std::atomic& items_probed; + std::atomic& failed; + std::atomic& success; + std::atomic& errors; +}; +std::unique_ptr WattTraderFarmer_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +WattTraderFarmer::WattTraderFarmer(){ + +} + + + +class BuyCursorDetector : public SelectionArrowFinder{ +public: + BuyCursorDetector(VideoOverlay& overlay) + : SelectionArrowFinder(overlay, ImageFloatBox(0.448775, 0.087129, 0.062361, 0.596040)) + {} +}; +class BuyQuantityDetector : public VisualInferenceCallback{ +public: + BuyQuantityDetector() + : VisualInferenceCallback("BuyQuantityDetector") + , m_box(0.814031, 0.681188, 0.170379, 0.045545) + {} + virtual void make_overlays(VideoOverlaySet& items) const override{ + items.add(COLOR_GREEN, m_box); + } + virtual bool process_frame(const VideoSnapshot& frame) override{ + ImageStats stats = image_stats(extract_box_reference(frame, m_box)); + return is_solid(stats, {0.62963, 0.37037, 0.}); + } + +private: + ImageFloatBox m_box; +}; + + + +void WattTraderFarmer::buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); + + bool purchased = false; + while (true){ + DialogTriangleDetector dialog(env.logger(), env.console, true); + BuyCursorDetector item_select(env.console); + BuyQuantityDetector quantity; + context.wait_for_all_requests(); + int ret = wait_until( + env.console, context, + std::chrono::seconds(10), + { + dialog, + item_select, + quantity, + } + ); + context.wait_for(200ms); + switch (ret){ + case 0: + env.log("Detected dialog...", COLOR_BLUE); + if (!purchased){ + stats.failed++; + env.update_stats(); + } + pbf_press_button(context, BUTTON_B, 200ms, 800ms); + return; + case 1: + env.log("Detected item select...", COLOR_BLUE); + if (purchased){ + return; + } + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + continue; + case 2: + env.log("Detected quantity select...", COLOR_BLUE); + stats.success++; + env.update_stats(); + pbf_press_dpad(context, DPAD_DOWN, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + purchased = true; + continue; + default: + env.log("No recognized state after 5 seconds.", COLOR_RED); + stats.errors++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 5000ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + continue; + } + } +} + + + +void WattTraderFarmer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + WattTraderFarmer_Descriptor::Stats& stats = env.current_stats(); + + uint8_t year = MAX_YEAR; + while (true){ + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + pbf_press_button(context, BUTTON_A, 200ms, 800ms); + + for (size_t c = 0; c < 7; c++){ + buy_one(env, context); + stats.items_probed++; + env.update_stats(); + pbf_press_dpad(context, DPAD_DOWN, 200ms, 200ms); + } + + pbf_mash_button(context, BUTTON_B, 5000ms); + + // Tap HOME and quickly spam B. The B spamming ensures that we don't + // accidentally update the system if the system update window pops up. + ssf_press_button(context, BUTTON_HOME, 120ms, 160ms); + pbf_mash_button(context, BUTTON_B, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0.get() - 120ms); + + home_roll_date_enter_game_autorollback(env.console, context, year); + pbf_mash_button(context, BUTTON_B, 90); + stats.day_skips++; + env.update_stats(); + } +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h index 11727252c3..5ec1db3b76 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DateSpamFarmers/PokemonSwSh_DateSpam-WattTraderFarmer.h @@ -1,47 +1,47 @@ -/* Watt Trader Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_WattTraderFarmer_H -#define PokemonAutomation_PokemonSwSh_WattTraderFarmer_H - -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class WattTraderFarmer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - WattTraderFarmer_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class WattTraderFarmer : public SingleSwitchProgramInstance{ -public: - WattTraderFarmer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - -}; - - - -} -} -} -#endif - - - +/* Watt Trader Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_WattTraderFarmer_H +#define PokemonAutomation_PokemonSwSh_WattTraderFarmer_H + +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class WattTraderFarmer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + WattTraderFarmer_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class WattTraderFarmer : public SingleSwitchProgramInstance{ +public: + WattTraderFarmer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void buy_one(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + +}; + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp index c9c7519f15..9052f92131 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.cpp @@ -1,86 +1,86 @@ -/* Beam Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh_BeamReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -BeamReset_Descriptor::BeamReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:BeamReset", - STRING_POKEMON + " SwSh", "Beam Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/BeamReset.md", - "Reset a beam until you see a purple beam.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -BeamReset::BeamReset() - : DELAY_BEFORE_RESET0( - "Delay before Reset:", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , EXTRA_LINE( - "Extra Line:
(German has an extra line of text.)", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(DELAY_BEFORE_RESET0); - PA_ADD_OPTION(EXTRA_LINE); -} - -void BeamReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - while (true){ - // Talk to den. - pbf_press_button(context, BUTTON_A, 10, 450); - if (EXTRA_LINE){ - pbf_press_button(context, BUTTON_A, 10, 300); - } - pbf_press_button(context, BUTTON_A, 10, 300); - - // Drop wishing piece. - pbf_press_button(context, BUTTON_A, 10, 70); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - - for (uint16_t c = 0; c < 4; c++){ - pbf_press_button(context, BUTTON_HOME, 10, 10); - pbf_press_button(context, BUTTON_HOME, 10, 220); - } - pbf_wait(context, DELAY_BEFORE_RESET0); - - reset_game_from_home(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - } -} - - - -} -} -} +/* Beam Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh_BeamReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +BeamReset_Descriptor::BeamReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:BeamReset", + STRING_POKEMON + " SwSh", "Beam Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/BeamReset.md", + "Reset a beam until you see a purple beam.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +BeamReset::BeamReset() + : DELAY_BEFORE_RESET0( + "Delay before Reset:", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , EXTRA_LINE( + "Extra Line:
(German has an extra line of text.)", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(DELAY_BEFORE_RESET0); + PA_ADD_OPTION(EXTRA_LINE); +} + +void BeamReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + while (true){ + // Talk to den. + pbf_press_button(context, BUTTON_A, 10, 450); + if (EXTRA_LINE){ + pbf_press_button(context, BUTTON_A, 10, 300); + } + pbf_press_button(context, BUTTON_A, 10, 300); + + // Drop wishing piece. + pbf_press_button(context, BUTTON_A, 10, 70); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + + for (uint16_t c = 0; c < 4; c++){ + pbf_press_button(context, BUTTON_HOME, 10, 10); + pbf_press_button(context, BUTTON_HOME, 10, 220); + } + pbf_wait(context, DELAY_BEFORE_RESET0); + + reset_game_from_home(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.h index d1e8f80295..55efd8f293 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_BeamReset.h @@ -1,47 +1,47 @@ -/* Beam Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BeamReset_H -#define PokemonAutomation_PokemonSwSh_BeamReset_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BeamReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BeamReset_Descriptor(); -}; - - - -class BeamReset : public SingleSwitchProgramInstance{ -public: - BeamReset(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - MillisecondsOption DELAY_BEFORE_RESET0; - BooleanCheckBoxOption EXTRA_LINE; -}; - - -} -} -} -#endif - - - +/* Beam Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BeamReset_H +#define PokemonAutomation_PokemonSwSh_BeamReset_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BeamReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BeamReset_Descriptor(); +}; + + + +class BeamReset : public SingleSwitchProgramInstance{ +public: + BeamReset(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + MillisecondsOption DELAY_BEFORE_RESET0; + BooleanCheckBoxOption EXTRA_LINE; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp index 346cc12669..39dcaf8b29 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.cpp @@ -1,223 +1,223 @@ -/* Day Skipper (EU) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_OFFICIAL - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_DaySkipperStats.h" -#include "PokemonSwSh_DaySkipperEU.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -DaySkipperEU_Descriptor::DaySkipperEU_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DaySkipperEU", - STRING_POKEMON + " SwSh", "Day Skipper (EU)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperEU.md", - "A day skipper for EU date format that. (Switch 1: ~7500 skips/hour, Switch 2: 5655 skips/hour)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - // ControllerFeature::NintendoSwitch_DateSkip, - } - ) -{} -std::unique_ptr DaySkipperEU_Descriptor::make_stats() const{ - return std::unique_ptr(new SkipperStats()); -} - - - -DaySkipperEU::DaySkipperEU() - : SKIPS( - "Number of Frame Skips:", - LockMode::LOCK_WHILE_RUNNING, - 10 - ) - , REAL_LIFE_YEAR( - "Real Life Year:", - LockMode::LOCK_WHILE_RUNNING, - std::min(current_year(), (uint16_t)2060), - 2000, 2060 - ) - , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRESS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , CORRECTION_SKIPS( - "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", - LockMode::LOCK_WHILE_RUNNING, - 1000 - ) -{ - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(REAL_LIFE_YEAR); - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CORRECTION_SKIPS); -} - - - -void DaySkipperEU::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch1; - - bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - // Setup globals. - uint8_t real_life_year = (uint8_t)( - REAL_LIFE_YEAR < 2000 ? 0 : - REAL_LIFE_YEAR > 2060 ? 60 : REAL_LIFE_YEAR - 2000 - ); - uint8_t year = 60; - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZR, 5, 5); - - // Setup starting state. - init_view(context); - rollback_year_full(context, false); - year = 0; - - uint16_t correct_count = 0; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - if (needs_inference){ - increment_day_with_feedback(env.console, context, false); - }else{ - increment_day(context, false); - } - - - correct_count++; - year++; - remaining_skips--; - stats.issued++; -// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); - env.update_stats(); - - if (year >= 60){ - if (real_life_year <= 36){ - rollback_year_sync(context); - year = real_life_year; - }else{ - rollback_year_full(context, false); - year = 0; - } - } - if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ - correct_count = 0; - auto_recovery(context); - } - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - pbf_wait(context, 15 * TICKS_PER_SECOND); - while (true){ - ssf_press_button(context, BUTTON_A, 15000ms); - } -} -void DaySkipperEU::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch2; - - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ - throw UserSetupError( - env.logger(), - "This program requires a tick precise wired controller." - ); - } - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZR, 5, 5); - - // Setup starting state. - init_view(context); - - uint8_t day = 1; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - increment_day_eu(context); - - if (day == 31){ - day = 1; - }else{ - day++; - remaining_skips--; - stats.issued++; - env.update_stats(); - } - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - while (true){ - ssf_press_button(context, BUTTON_A, 760ms); - for (int c = 0; c < 10; c++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - } - ssf_press_button(context, BUTTON_A, 14000ms, 80ms); - } -} - - - - -void DaySkipperEU::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ConsoleType console_type = env.console.state().console_type(); - if (is_switch1(console_type)){ - run_switch1(env, context); - return; - } - if (is_switch2(console_type)){ - run_switch2(env, context); - return; - } - throw UserSetupError( - env.console, - "Please select a valid Switch console type." - ); -} - - -} -} -} -#endif +/* Day Skipper (EU) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_OFFICIAL + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_DaySkipperStats.h" +#include "PokemonSwSh_DaySkipperEU.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +DaySkipperEU_Descriptor::DaySkipperEU_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DaySkipperEU", + STRING_POKEMON + " SwSh", "Day Skipper (EU)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperEU.md", + "A day skipper for EU date format that. (Switch 1: ~7500 skips/hour, Switch 2: 5655 skips/hour)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + // ControllerFeature::NintendoSwitch_DateSkip, + } + ) +{} +std::unique_ptr DaySkipperEU_Descriptor::make_stats() const{ + return std::unique_ptr(new SkipperStats()); +} + + + +DaySkipperEU::DaySkipperEU() + : SKIPS( + "Number of Frame Skips:", + LockMode::LOCK_WHILE_RUNNING, + 10 + ) + , REAL_LIFE_YEAR( + "Real Life Year:", + LockMode::LOCK_WHILE_RUNNING, + std::min(current_year(), (uint16_t)2060), + 2000, 2060 + ) + , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRESS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , CORRECTION_SKIPS( + "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", + LockMode::LOCK_WHILE_RUNNING, + 1000 + ) +{ + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(REAL_LIFE_YEAR); + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CORRECTION_SKIPS); +} + + + +void DaySkipperEU::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch1; + + bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + // Setup globals. + uint8_t real_life_year = (uint8_t)( + REAL_LIFE_YEAR < 2000 ? 0 : + REAL_LIFE_YEAR > 2060 ? 60 : REAL_LIFE_YEAR - 2000 + ); + uint8_t year = 60; + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZR, 5, 5); + + // Setup starting state. + init_view(context); + rollback_year_full(context, false); + year = 0; + + uint16_t correct_count = 0; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + if (needs_inference){ + increment_day_with_feedback(env.console, context, false); + }else{ + increment_day(context, false); + } + + + correct_count++; + year++; + remaining_skips--; + stats.issued++; +// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); + env.update_stats(); + + if (year >= 60){ + if (real_life_year <= 36){ + rollback_year_sync(context); + year = real_life_year; + }else{ + rollback_year_full(context, false); + year = 0; + } + } + if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ + correct_count = 0; + auto_recovery(context); + } + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + pbf_wait(context, 15 * TICKS_PER_SECOND); + while (true){ + ssf_press_button(context, BUTTON_A, 15000ms); + } +} +void DaySkipperEU::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch2; + + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + throw UserSetupError( + env.logger(), + "This program requires a tick precise wired controller." + ); + } + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZR, 5, 5); + + // Setup starting state. + init_view(context); + + uint8_t day = 1; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + increment_day_eu(context); + + if (day == 31){ + day = 1; + }else{ + day++; + remaining_skips--; + stats.issued++; + env.update_stats(); + } + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + while (true){ + ssf_press_button(context, BUTTON_A, 760ms); + for (int c = 0; c < 10; c++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + } + ssf_press_button(context, BUTTON_A, 14000ms, 80ms); + } +} + + + + +void DaySkipperEU::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ConsoleType console_type = env.console.state().console_type(); + if (is_switch1(console_type)){ + run_switch1(env, context); + return; + } + if (is_switch2(console_type)){ + run_switch2(env, context); + return; + } + throw UserSetupError( + env.console, + "Please select a valid Switch console type." + ); +} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.h index 5950bf32c2..fadda3107a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperEU.h @@ -1,57 +1,57 @@ -/* Day Skipper (EU) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DaySkipperEU_H -#define PokemonAutomation_PokemonSwSh_DaySkipperEU_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DaySkipperEU_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DaySkipperEU_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class DaySkipperEU : public SingleSwitchProgramInstance{ -public: - DaySkipperEU(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - SimpleIntegerOption SKIPS; - SimpleIntegerOption REAL_LIFE_YEAR; - - EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption CORRECTION_SKIPS; -}; - - -} -} -} -#endif - - - +/* Day Skipper (EU) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DaySkipperEU_H +#define PokemonAutomation_PokemonSwSh_DaySkipperEU_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DaySkipperEU_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DaySkipperEU_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class DaySkipperEU : public SingleSwitchProgramInstance{ +public: + DaySkipperEU(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + SimpleIntegerOption SKIPS; + SimpleIntegerOption REAL_LIFE_YEAR; + + EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption CORRECTION_SKIPS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp index 66fb693ae8..717779568a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.cpp @@ -1,231 +1,231 @@ -/* Day Skipper (JPN) - 7.8k version - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_OFFICIAL - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_DaySkipperStats.h" -#include "PokemonSwSh_DaySkipperJPN-7.8k.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -DaySkipperJPN7p8k_Descriptor::DaySkipperJPN7p8k_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DaySkipperJPN7p8k", - STRING_POKEMON + " SwSh", "Day Skipper (JPN) - 7.8k", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperJPN-7.8k.md", - "A faster, but less reliable Japanese date skipper. (7800 skips/hour)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - ControllerFeature::NintendoSwitch_DateSkip, - } - ) -{} -std::unique_ptr DaySkipperJPN7p8k_Descriptor::make_stats() const{ - return std::unique_ptr(new SkipperStats()); -} - - - -DaySkipperJPN7p8k::DaySkipperJPN7p8k() - : SKIPS( - "Number of Frame Skips:", - LockMode::LOCK_WHILE_RUNNING, - 10 - ) - , START_DATE( - "Start Date:", - LockMode::LOCK_WHILE_RUNNING, - DateTimeOption::Level::DATE, - DateTime{2000, 1, 1}, DateTime{2060, 12, 31}, - DateTime{2000, 1, 1} - ) - , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRESS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , CORRECTION_SKIPS( - "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", - LockMode::LOCK_WHILE_RUNNING, - 1000 - ) -{ - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(START_DATE); - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CORRECTION_SKIPS); -} - - -const uint8_t DAYS_PER_MONTH[] = { - 31, // January - 28, // February - 31, // March - 30, // April - 31, // May - 30, // June - 31, // July - 31, // August - 30, // September - 31, // October - 30, // November - 31, // December -}; -uint8_t days_in_month(uint8_t year, uint8_t month){ - return month != 2 - ? DAYS_PER_MONTH[month - 1] - : (year & 0x3) ? 28 : 29; -} -typedef struct{ - uint8_t year; - uint8_t month; - uint8_t day; -} DateSmall; - -bool is_start(const DateSmall* date){ - return date->year != 0 || date->month != 1 || date->day != 1; -} -bool date_increment_day(ProControllerContext& context, DateSmall* date, bool press){ - using namespace DateSkippers::Switch1; - - uint8_t days = days_in_month(date->year, date->month); - if (date->day != days){ - if (press){ - increment_day(context, false); - } - date->day++; - return true; - } - - date->day = 1; - date->month++; - if (date->month > 12){ - date->month = 1; - date->year++; - } - if (date->year > 60){ - date->year = 0; - } - - if (!press){ - return is_start(date); - } - - if (date->month != 1){ - increment_month(context, DAYS_PER_MONTH[date->month - 1]); - return true; - } - - if (date->year != 0){ - increment_all(context); - return true; - } - - increment_all_rollback(context); - return false; -} - -void DaySkipperJPN7p8k::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch1; - - if (env.console.state().console_type() != ConsoleType::Switch1){ - throw UserSetupError( - env.logger(), - "This program only works on the Switch 1." - ); - } - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ - throw UserSetupError( - env.logger(), - "This program requires a tick precise wired controller." - ); - } - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - // Setup globals. - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZL, 5, 5); - - DateTime start_date = START_DATE; - - // Sanitize starting date. - uint16_t year = (uint16_t)start_date.year; - if (year < 2000) year = 2000; - if (year > 2060) year = 2060; - - DateSmall date; - date.year = (uint8_t)(year - 2000); - date.month = (uint8_t)start_date.month; - date.day = (uint8_t)start_date.day; - if (date.month < 1) date.month = 1; - if (date.month > 12) date.month = 12; - if (date.day < 1) date.day = 1; - { - uint8_t day = days_in_month(date.year, date.month); - if (date.day > day) date.day = day; - } - - // Setup starting state. - init_view(context); - - uint16_t correct_count = 0; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - if (date_increment_day(context, &date, true)){ - correct_count++; - remaining_skips--; - stats.issued++; - env.log("Expected Date: " + std::to_string(date.year + 2000) + "/" + std::to_string(date.month) + "/" + std::to_string(date.day)); -// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); - env.update_stats(); - } - if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ - correct_count = 0; - auto_recovery(context); - } - - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - pbf_wait(context, 15 * TICKS_PER_SECOND); - while (true){ - ssf_press_button(context, BUTTON_A, 15000ms); - } -} - - - -} -} -} -#endif +/* Day Skipper (JPN) - 7.8k version + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_OFFICIAL + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_DaySkipperStats.h" +#include "PokemonSwSh_DaySkipperJPN-7.8k.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +DaySkipperJPN7p8k_Descriptor::DaySkipperJPN7p8k_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DaySkipperJPN7p8k", + STRING_POKEMON + " SwSh", "Day Skipper (JPN) - 7.8k", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperJPN-7.8k.md", + "A faster, but less reliable Japanese date skipper. (7800 skips/hour)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + ControllerFeature::NintendoSwitch_DateSkip, + } + ) +{} +std::unique_ptr DaySkipperJPN7p8k_Descriptor::make_stats() const{ + return std::unique_ptr(new SkipperStats()); +} + + + +DaySkipperJPN7p8k::DaySkipperJPN7p8k() + : SKIPS( + "Number of Frame Skips:", + LockMode::LOCK_WHILE_RUNNING, + 10 + ) + , START_DATE( + "Start Date:", + LockMode::LOCK_WHILE_RUNNING, + DateTimeOption::Level::DATE, + DateTime{2000, 1, 1}, DateTime{2060, 12, 31}, + DateTime{2000, 1, 1} + ) + , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRESS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , CORRECTION_SKIPS( + "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", + LockMode::LOCK_WHILE_RUNNING, + 1000 + ) +{ + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(START_DATE); + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CORRECTION_SKIPS); +} + + +const uint8_t DAYS_PER_MONTH[] = { + 31, // January + 28, // February + 31, // March + 30, // April + 31, // May + 30, // June + 31, // July + 31, // August + 30, // September + 31, // October + 30, // November + 31, // December +}; +uint8_t days_in_month(uint8_t year, uint8_t month){ + return month != 2 + ? DAYS_PER_MONTH[month - 1] + : (year & 0x3) ? 28 : 29; +} +typedef struct{ + uint8_t year; + uint8_t month; + uint8_t day; +} DateSmall; + +bool is_start(const DateSmall* date){ + return date->year != 0 || date->month != 1 || date->day != 1; +} +bool date_increment_day(ProControllerContext& context, DateSmall* date, bool press){ + using namespace DateSkippers::Switch1; + + uint8_t days = days_in_month(date->year, date->month); + if (date->day != days){ + if (press){ + increment_day(context, false); + } + date->day++; + return true; + } + + date->day = 1; + date->month++; + if (date->month > 12){ + date->month = 1; + date->year++; + } + if (date->year > 60){ + date->year = 0; + } + + if (!press){ + return is_start(date); + } + + if (date->month != 1){ + increment_month(context, DAYS_PER_MONTH[date->month - 1]); + return true; + } + + if (date->year != 0){ + increment_all(context); + return true; + } + + increment_all_rollback(context); + return false; +} + +void DaySkipperJPN7p8k::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch1; + + if (env.console.state().console_type() != ConsoleType::Switch1){ + throw UserSetupError( + env.logger(), + "This program only works on the Switch 1." + ); + } + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + throw UserSetupError( + env.logger(), + "This program requires a tick precise wired controller." + ); + } + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + // Setup globals. + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZL, 5, 5); + + DateTime start_date = START_DATE; + + // Sanitize starting date. + uint16_t year = (uint16_t)start_date.year; + if (year < 2000) year = 2000; + if (year > 2060) year = 2060; + + DateSmall date; + date.year = (uint8_t)(year - 2000); + date.month = (uint8_t)start_date.month; + date.day = (uint8_t)start_date.day; + if (date.month < 1) date.month = 1; + if (date.month > 12) date.month = 12; + if (date.day < 1) date.day = 1; + { + uint8_t day = days_in_month(date.year, date.month); + if (date.day > day) date.day = day; + } + + // Setup starting state. + init_view(context); + + uint16_t correct_count = 0; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + if (date_increment_day(context, &date, true)){ + correct_count++; + remaining_skips--; + stats.issued++; + env.log("Expected Date: " + std::to_string(date.year + 2000) + "/" + std::to_string(date.month) + "/" + std::to_string(date.day)); +// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); + env.update_stats(); + } + if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ + correct_count = 0; + auto_recovery(context); + } + + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + pbf_wait(context, 15 * TICKS_PER_SECOND); + while (true){ + ssf_press_button(context, BUTTON_A, 15000ms); + } +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h index e18661a310..677f0a93af 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN-7.8k.h @@ -1,53 +1,53 @@ -/* Day Skipper (JPN) - 7.8k version - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DaySkipperJPN7p8k_H -#define PokemonAutomation_PokemonSwSh_DaySkipperJPN7p8k_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/DateOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DaySkipperJPN7p8k_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DaySkipperJPN7p8k_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class DaySkipperJPN7p8k : public SingleSwitchProgramInstance{ -public: - DaySkipperJPN7p8k(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption SKIPS; - DateTimeOption START_DATE; - - EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption CORRECTION_SKIPS; -}; - - -} -} -} -#endif - - - +/* Day Skipper (JPN) - 7.8k version + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DaySkipperJPN7p8k_H +#define PokemonAutomation_PokemonSwSh_DaySkipperJPN7p8k_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/DateOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DaySkipperJPN7p8k_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DaySkipperJPN7p8k_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class DaySkipperJPN7p8k : public SingleSwitchProgramInstance{ +public: + DaySkipperJPN7p8k(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption SKIPS; + DateTimeOption START_DATE; + + EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption CORRECTION_SKIPS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp index cd06c4ef5c..3f1728a331 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.cpp @@ -1,203 +1,203 @@ -/* Day Skipper (JPN) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_OFFICIAL - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_DaySkipperStats.h" -#include "PokemonSwSh_DaySkipperJPN.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -DaySkipperJPN_Descriptor::DaySkipperJPN_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DaySkipperJPN", - STRING_POKEMON + " SwSh", "Day Skipper (JPN)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperJPN.md", - "A day skipper for Japanese date format. (Switch 1: 7600 skips/hour, Switch 2: 5655 skips/hour)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - // ControllerFeature::NintendoSwitch_DateSkip, - } - ) -{} - -std::unique_ptr DaySkipperJPN_Descriptor::make_stats() const{ - return std::unique_ptr(new SkipperStats()); -} - - - -DaySkipperJPN::DaySkipperJPN() - : SKIPS( - "Number of Frame Skips:", - LockMode::LOCK_WHILE_RUNNING, - 10 - ) - , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRESS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , CORRECTION_SKIPS( - "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", - LockMode::LOCK_WHILE_RUNNING, - 1000 - ) -{ - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CORRECTION_SKIPS); -} - - - -void DaySkipperJPN::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch1; - - bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - // Setup globals. - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZR, 5, 5); - - // Setup starting state. - init_view(context); - - uint8_t day = 1; - uint16_t correct_count = 0; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - if (needs_inference){ - increment_day_with_feedback(env.console, context, false); - }else{ - increment_day(context, false); - } - - if (day == 31){ - day = 1; - }else{ - correct_count++; - day++; - remaining_skips--; - stats.issued++; -// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); - env.update_stats(); - } - if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ - correct_count = 0; - auto_recovery(context); - } - - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - pbf_wait(context, 15 * TICKS_PER_SECOND); - while (true){ - ssf_press_button(context, BUTTON_A, 15000ms); - } -} -void DaySkipperJPN::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch2; - - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ - throw UserSetupError( - env.logger(), - "This program requires a tick precise wired controller." - ); - } - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZR, 5, 5); - - // Setup starting state. - init_view(context); - - uint8_t day = 1; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - increment_day_jp(context); - - if (day == 31){ - day = 1; - }else{ - day++; - remaining_skips--; - stats.issued++; - env.update_stats(); - } - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - while (true){ - ssf_press_button(context, BUTTON_A, 760ms); - for (int c = 0; c < 10; c++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - } - ssf_press_button(context, BUTTON_A, 14000ms, 80ms); - } -} - - - -void DaySkipperJPN::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ConsoleType console_type = env.console.state().console_type(); - if (is_switch1(console_type)){ - run_switch1(env, context); - return; - } - if (is_switch2(console_type)){ - run_switch2(env, context); - return; - } - throw UserSetupError( - env.console, - "Please select a valid Switch console type." - ); -} - - -} -} -} -#endif +/* Day Skipper (JPN) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_OFFICIAL + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_DaySkipperStats.h" +#include "PokemonSwSh_DaySkipperJPN.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +DaySkipperJPN_Descriptor::DaySkipperJPN_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DaySkipperJPN", + STRING_POKEMON + " SwSh", "Day Skipper (JPN)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperJPN.md", + "A day skipper for Japanese date format. (Switch 1: 7600 skips/hour, Switch 2: 5655 skips/hour)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + // ControllerFeature::NintendoSwitch_DateSkip, + } + ) +{} + +std::unique_ptr DaySkipperJPN_Descriptor::make_stats() const{ + return std::unique_ptr(new SkipperStats()); +} + + + +DaySkipperJPN::DaySkipperJPN() + : SKIPS( + "Number of Frame Skips:", + LockMode::LOCK_WHILE_RUNNING, + 10 + ) + , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRESS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , CORRECTION_SKIPS( + "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", + LockMode::LOCK_WHILE_RUNNING, + 1000 + ) +{ + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CORRECTION_SKIPS); +} + + + +void DaySkipperJPN::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch1; + + bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + // Setup globals. + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZR, 5, 5); + + // Setup starting state. + init_view(context); + + uint8_t day = 1; + uint16_t correct_count = 0; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + if (needs_inference){ + increment_day_with_feedback(env.console, context, false); + }else{ + increment_day(context, false); + } + + if (day == 31){ + day = 1; + }else{ + correct_count++; + day++; + remaining_skips--; + stats.issued++; +// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); + env.update_stats(); + } + if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ + correct_count = 0; + auto_recovery(context); + } + + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + pbf_wait(context, 15 * TICKS_PER_SECOND); + while (true){ + ssf_press_button(context, BUTTON_A, 15000ms); + } +} +void DaySkipperJPN::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch2; + + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + throw UserSetupError( + env.logger(), + "This program requires a tick precise wired controller." + ); + } + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZR, 5, 5); + + // Setup starting state. + init_view(context); + + uint8_t day = 1; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + increment_day_jp(context); + + if (day == 31){ + day = 1; + }else{ + day++; + remaining_skips--; + stats.issued++; + env.update_stats(); + } + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + while (true){ + ssf_press_button(context, BUTTON_A, 760ms); + for (int c = 0; c < 10; c++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + } + ssf_press_button(context, BUTTON_A, 14000ms, 80ms); + } +} + + + +void DaySkipperJPN::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ConsoleType console_type = env.console.state().console_type(); + if (is_switch1(console_type)){ + run_switch1(env, context); + return; + } + if (is_switch2(console_type)){ + run_switch2(env, context); + return; + } + throw UserSetupError( + env.console, + "Please select a valid Switch console type." + ); +} + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h index 705630cc2a..d338e55a13 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperJPN.h @@ -1,55 +1,55 @@ -/* Day Skipper (JPN) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DaySkipperJPN_H -#define PokemonAutomation_PokemonSwSh_DaySkipperJPN_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DaySkipperJPN_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DaySkipperJPN_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class DaySkipperJPN : public SingleSwitchProgramInstance{ -public: - DaySkipperJPN(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - SimpleIntegerOption SKIPS; - - EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption CORRECTION_SKIPS; -}; - - -} -} -} -#endif - - - +/* Day Skipper (JPN) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DaySkipperJPN_H +#define PokemonAutomation_PokemonSwSh_DaySkipperJPN_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DaySkipperJPN_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DaySkipperJPN_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class DaySkipperJPN : public SingleSwitchProgramInstance{ +public: + DaySkipperJPN(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + SimpleIntegerOption SKIPS; + + EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption CORRECTION_SKIPS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperStats.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperStats.h index 6ae26c2b1c..2d92622edb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperStats.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperStats.h @@ -1,47 +1,47 @@ -/* Day Skipper Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DaySkipperStats_H -#define PokemonAutomation_PokemonSwSh_DaySkipperStats_H - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class SkipperStats : public StatsTracker{ -public: - SkipperStats() - : runs(m_stats["Runs"]) - , issued(m_stats["Skips Issued"]) - { - m_display_order.emplace_back(Stat("Runs")); - m_display_order.emplace_back(Stat("Skips Issued")); - } - - virtual std::string to_str(PrintMode mode) const override{ - if (total_skips == 0){ - return StatsTracker::to_str(mode); - }else{ - return - "Skips Issued: " + tostr_u_commas(issued) + - " - Skips Remaining: " + tostr_u_commas(total_skips - issued.load(std::memory_order_relaxed)); - } - } - - std::atomic& runs; - std::atomic& issued; - uint64_t total_skips = 0; -}; - - -} -} -} -#endif +/* Day Skipper Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DaySkipperStats_H +#define PokemonAutomation_PokemonSwSh_DaySkipperStats_H + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class SkipperStats : public StatsTracker{ +public: + SkipperStats() + : runs(m_stats["Runs"]) + , issued(m_stats["Skips Issued"]) + { + m_display_order.emplace_back(Stat("Runs")); + m_display_order.emplace_back(Stat("Skips Issued")); + } + + virtual std::string to_str(PrintMode mode) const override{ + if (total_skips == 0){ + return StatsTracker::to_str(mode); + }else{ + return + "Skips Issued: " + tostr_u_commas(issued) + + " - Skips Remaining: " + tostr_u_commas(total_skips - issued.load(std::memory_order_relaxed)); + } + } + + std::atomic& runs; + std::atomic& issued; + uint64_t total_skips = 0; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp index 704f9c3053..32ffbe5e48 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.cpp @@ -1,224 +1,224 @@ -/* Day Skipper (US) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifdef PA_OFFICIAL - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_DaySkipperStats.h" -#include "PokemonSwSh_DaySkipperUS.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -DaySkipperUS_Descriptor::DaySkipperUS_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DaySkipperUS", - STRING_POKEMON + " SwSh", "Day Skipper (US)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperUS.md", - "A day skipper for US date format that. (Switch 1: ~7100 skips/hour, Switch 2: 5443 skips/hour)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - { - ControllerFeature::TickPrecise, - ControllerFeature::NintendoSwitch_ProController, - // ControllerFeature::NintendoSwitch_DateSkip, - } - ) -{} -std::unique_ptr DaySkipperUS_Descriptor::make_stats() const{ - return std::unique_ptr(new SkipperStats()); -} - - - -DaySkipperUS::DaySkipperUS() - : SKIPS( - "Number of Frame Skips:", - LockMode::LOCK_WHILE_RUNNING, - 10 - ) - , REAL_LIFE_YEAR( - "Real Life Year:", - LockMode::LOCK_WHILE_RUNNING, - std::min(current_year(), (uint16_t)2060), - 2000, 2060 - ) - , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRESS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , CORRECTION_SKIPS( - "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", - LockMode::LOCK_WHILE_RUNNING, - 1000 - ) -{ - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(REAL_LIFE_YEAR); - PA_ADD_OPTION(NOTIFICATIONS); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CORRECTION_SKIPS); -} - - - -void DaySkipperUS::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch1; - - bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - // Setup globals. - uint8_t real_life_year = (uint8_t)( - REAL_LIFE_YEAR < 2000 ? 0 : - REAL_LIFE_YEAR > 2060 ? 60 : REAL_LIFE_YEAR - 2000 - ); - uint8_t year = 60; - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZR, 5, 5); - - // Setup starting state. - init_view(context); - rollback_year_full(context, true); - year = 0; - - uint16_t correct_count = 0; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - if (needs_inference){ - increment_day_with_feedback(env.console, context, true); - }else{ - increment_day(context, true); - } - - - correct_count++; - year++; - remaining_skips--; - stats.issued++; -// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); - env.update_stats(); - - if (year >= 60){ - if (real_life_year <= 36){ - rollback_year_sync(context); - year = real_life_year; - }else{ - rollback_year_full(context, true); - year = 0; - } - } - if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ - correct_count = 0; - auto_recovery(context); - } - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - pbf_wait(context, 15 * TICKS_PER_SECOND); - while (true){ - ssf_press_button(context, BUTTON_A, 15000ms); - } -} -void DaySkipperUS::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - using namespace DateSkippers::Switch2; - - if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ - throw UserSetupError( - env.logger(), - "This program requires a tick precise wired controller." - ); - } - - SkipperStats& stats = env.current_stats(); - stats.total_skips = SKIPS; - stats.runs++; - - uint32_t remaining_skips = SKIPS; - - // Connect - pbf_press_button(context, BUTTON_ZR, 5, 5); - - // Setup starting state. - init_view(context); - - uint8_t day = 1; - while (remaining_skips > 0){ - send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); - - increment_day_us(context); - - if (day == 31){ - day = 1; - }else{ - day++; - remaining_skips--; - stats.issued++; - env.update_stats(); - } - } - - // Prevent the Switch from sleeping and the time from advancing. - context.wait_for_all_requests(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - - while (true){ - ssf_press_button(context, BUTTON_A, 760ms); - for (int c = 0; c < 10; c++){ - ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); - } - ssf_press_button(context, BUTTON_A, 14000ms, 80ms); - } -} - - - - - -void DaySkipperUS::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ConsoleType console_type = env.console.state().console_type(); - if (is_switch1(console_type)){ - run_switch1(env, context); - return; - } - if (is_switch2(console_type)){ - run_switch2(env, context); - return; - } - throw UserSetupError( - env.console, - "Please select a valid Switch console type." - ); -} - - - -} -} -} -#endif +/* Day Skipper (US) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifdef PA_OFFICIAL + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_DateSkippers.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_DaySkipperStats.h" +#include "PokemonSwSh_DaySkipperUS.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +DaySkipperUS_Descriptor::DaySkipperUS_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DaySkipperUS", + STRING_POKEMON + " SwSh", "Day Skipper (US)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DaySkipperUS.md", + "A day skipper for US date format that. (Switch 1: ~7100 skips/hour, Switch 2: 5443 skips/hour)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + { + ControllerFeature::TickPrecise, + ControllerFeature::NintendoSwitch_ProController, + // ControllerFeature::NintendoSwitch_DateSkip, + } + ) +{} +std::unique_ptr DaySkipperUS_Descriptor::make_stats() const{ + return std::unique_ptr(new SkipperStats()); +} + + + +DaySkipperUS::DaySkipperUS() + : SKIPS( + "Number of Frame Skips:", + LockMode::LOCK_WHILE_RUNNING, + 10 + ) + , REAL_LIFE_YEAR( + "Real Life Year:", + LockMode::LOCK_WHILE_RUNNING, + std::min(current_year(), (uint16_t)2060), + 2000, 2060 + ) + , NOTIFICATION_PROGRESS_UPDATE("Progress Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRESS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , CORRECTION_SKIPS( + "Auto-Correct Interval:
Run auto-recovery every this # of skips. Zero disables the auto-corrections.", + LockMode::LOCK_WHILE_RUNNING, + 1000 + ) +{ + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(REAL_LIFE_YEAR); + PA_ADD_OPTION(NOTIFICATIONS); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CORRECTION_SKIPS); +} + + + +void DaySkipperUS::run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch1; + + bool needs_inference = context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz; + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + // Setup globals. + uint8_t real_life_year = (uint8_t)( + REAL_LIFE_YEAR < 2000 ? 0 : + REAL_LIFE_YEAR > 2060 ? 60 : REAL_LIFE_YEAR - 2000 + ); + uint8_t year = 60; + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZR, 5, 5); + + // Setup starting state. + init_view(context); + rollback_year_full(context, true); + year = 0; + + uint16_t correct_count = 0; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + if (needs_inference){ + increment_day_with_feedback(env.console, context, true); + }else{ + increment_day(context, true); + } + + + correct_count++; + year++; + remaining_skips--; + stats.issued++; +// env.log("Skips Remaining: " + tostr_u_commas(remaining_skips)); + env.update_stats(); + + if (year >= 60){ + if (real_life_year <= 36){ + rollback_year_sync(context); + year = real_life_year; + }else{ + rollback_year_full(context, true); + year = 0; + } + } + if (CORRECTION_SKIPS != 0 && correct_count == CORRECTION_SKIPS){ + correct_count = 0; + auto_recovery(context); + } + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + pbf_wait(context, 15 * TICKS_PER_SECOND); + while (true){ + ssf_press_button(context, BUTTON_A, 15000ms); + } +} +void DaySkipperUS::run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + using namespace DateSkippers::Switch2; + + if (context->performance_class() != ControllerPerformanceClass::SerialPABotBase_Wired_125Hz){ + throw UserSetupError( + env.logger(), + "This program requires a tick precise wired controller." + ); + } + + SkipperStats& stats = env.current_stats(); + stats.total_skips = SKIPS; + stats.runs++; + + uint32_t remaining_skips = SKIPS; + + // Connect + pbf_press_button(context, BUTTON_ZR, 5, 5); + + // Setup starting state. + init_view(context); + + uint8_t day = 1; + while (remaining_skips > 0){ + send_program_status_notification(env, NOTIFICATION_PROGRESS_UPDATE); + + increment_day_us(context); + + if (day == 31){ + day = 1; + }else{ + day++; + remaining_skips--; + stats.issued++; + env.update_stats(); + } + } + + // Prevent the Switch from sleeping and the time from advancing. + context.wait_for_all_requests(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + + while (true){ + ssf_press_button(context, BUTTON_A, 760ms); + for (int c = 0; c < 10; c++){ + ssf_issue_scroll(context, SSF_SCROLL_RIGHT, 24ms, 48ms, 24ms); + } + ssf_press_button(context, BUTTON_A, 14000ms, 80ms); + } +} + + + + + +void DaySkipperUS::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ConsoleType console_type = env.console.state().console_type(); + if (is_switch1(console_type)){ + run_switch1(env, context); + return; + } + if (is_switch2(console_type)){ + run_switch2(env, context); + return; + } + throw UserSetupError( + env.console, + "Please select a valid Switch console type." + ); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.h index 772b5c9e92..c89e6e3481 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_DaySkipperUS.h @@ -1,56 +1,56 @@ -/* Day Skipper (US) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DaySkipperUS_H -#define PokemonAutomation_PokemonSwSh_DaySkipperUS_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DaySkipperUS_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DaySkipperUS_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class DaySkipperUS : public SingleSwitchProgramInstance{ -public: - DaySkipperUS(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - SimpleIntegerOption SKIPS; - SimpleIntegerOption REAL_LIFE_YEAR; - - EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption CORRECTION_SKIPS; -}; - - -} -} -} -#endif - - - +/* Day Skipper (US) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DaySkipperUS_H +#define PokemonAutomation_PokemonSwSh_DaySkipperUS_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DaySkipperUS_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DaySkipperUS_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class DaySkipperUS : public SingleSwitchProgramInstance{ +public: + DaySkipperUS(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void run_switch1(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void run_switch2(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + SimpleIntegerOption SKIPS; + SimpleIntegerOption REAL_LIFE_YEAR; + + EventNotificationOption NOTIFICATION_PROGRESS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption CORRECTION_SKIPS; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp index 42a59ba057..6fa68e65d2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.cpp @@ -1,106 +1,106 @@ -/* Event Beam Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_EventBeamFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -EventBeamFinder_Descriptor::EventBeamFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EventBeamFinder", - STRING_POKEMON + " SwSh", "Event Beam Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EventBeamFinder.md", - "Drop wishing pieces until you find an event den.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -EventBeamFinder::EventBeamFinder() - : WAIT_TIME_IN_DEN0( - "Wait time in Den:", - LockMode::LOCK_WHILE_RUNNING, - "5800 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(WAIT_TIME_IN_DEN0); -} - - -void EventBeamFinder::goto_near_den(ProControllerContext& context) const{ - ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 375, 375); - pbf_wait(context, 50); - ssf_press_button(context, BUTTON_PLUS, 800ms); - ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 100, 5); - ssf_press_button(context, BUTTON_L, 800ms); - ssf_press_button(context, BUTTON_PLUS, 800ms); - ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 370, 370); -} -void EventBeamFinder::goto_far_den(ProControllerContext& context) const{ - ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 992, 992); - pbf_wait(context, 50); - ssf_press_button(context, BUTTON_PLUS, 800ms); - ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 100, 5); - ssf_press_button(context, BUTTON_L, 800ms); - ssf_press_button(context, BUTTON_PLUS, 800ms); - ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 300, 300); -} -void EventBeamFinder::drop_wishing_piece(ProControllerContext& context) const{ - ssf_press_button(context, BUTTON_A, 1600ms, 80ms); - ssf_press_button(context, BUTTON_A, 1200ms, 80ms); - ssf_press_button(context, BUTTON_A, 40ms); - pbf_mash_button(context, BUTTON_B, 500); - ssf_press_button(context, BUTTON_A, WAIT_TIME_IN_DEN0, 80ms); - pbf_mash_button(context, BUTTON_B, 600); -} -void EventBeamFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - pbf_mash_button(context, BUTTON_B, 700); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - bool parity = false; - while (true){ - // Fly back to daycare. - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - pbf_mash_button(context, BUTTON_A, 700); - - // Goto den. - if (parity){ - goto_far_den(context); - }else{ - goto_near_den(context); - } - parity = !parity; - - // Drop wishing piece and see what you get. - drop_wishing_piece(context); - } -} - - - -} -} -} +/* Event Beam Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_EventBeamFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +EventBeamFinder_Descriptor::EventBeamFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EventBeamFinder", + STRING_POKEMON + " SwSh", "Event Beam Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EventBeamFinder.md", + "Drop wishing pieces until you find an event den.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +EventBeamFinder::EventBeamFinder() + : WAIT_TIME_IN_DEN0( + "Wait time in Den:", + LockMode::LOCK_WHILE_RUNNING, + "5800 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(WAIT_TIME_IN_DEN0); +} + + +void EventBeamFinder::goto_near_den(ProControllerContext& context) const{ + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 375, 375); + pbf_wait(context, 50); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_MAX, STICK_CENTER, 100, 5); + ssf_press_button(context, BUTTON_L, 800ms); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 370, 370); +} +void EventBeamFinder::goto_far_den(ProControllerContext& context) const{ + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 992, 992); + pbf_wait(context, 50); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 100, 5); + ssf_press_button(context, BUTTON_L, 800ms); + ssf_press_button(context, BUTTON_PLUS, 800ms); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 300, 300); +} +void EventBeamFinder::drop_wishing_piece(ProControllerContext& context) const{ + ssf_press_button(context, BUTTON_A, 1600ms, 80ms); + ssf_press_button(context, BUTTON_A, 1200ms, 80ms); + ssf_press_button(context, BUTTON_A, 40ms); + pbf_mash_button(context, BUTTON_B, 500); + ssf_press_button(context, BUTTON_A, WAIT_TIME_IN_DEN0, 80ms); + pbf_mash_button(context, BUTTON_B, 600); +} +void EventBeamFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + pbf_mash_button(context, BUTTON_B, 700); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + bool parity = false; + while (true){ + // Fly back to daycare. + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + pbf_mash_button(context, BUTTON_A, 700); + + // Goto den. + if (parity){ + goto_far_den(context); + }else{ + goto_near_den(context); + } + parity = !parity; + + // Drop wishing piece and see what you get. + drop_wishing_piece(context); + } +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.h index a601dda7e2..c421e87ccb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_EventBeamFinder.h @@ -1,49 +1,49 @@ -/* Event Beam Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EventBeamFinder_H -#define PokemonAutomation_PokemonSwSh_EventBeamFinder_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EventBeamFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EventBeamFinder_Descriptor(); -}; - - - -class EventBeamFinder : public SingleSwitchProgramInstance{ -public: - EventBeamFinder(); - - - void goto_near_den(ProControllerContext& context) const; - void goto_far_den(ProControllerContext& context) const; - void drop_wishing_piece(ProControllerContext& context) const; - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - MillisecondsOption WAIT_TIME_IN_DEN0; -}; - - -} -} -} -#endif - - - +/* Event Beam Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EventBeamFinder_H +#define PokemonAutomation_PokemonSwSh_EventBeamFinder_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EventBeamFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EventBeamFinder_Descriptor(); +}; + + + +class EventBeamFinder : public SingleSwitchProgramInstance{ +public: + EventBeamFinder(); + + + void goto_near_den(ProControllerContext& context) const; + void goto_far_den(ProControllerContext& context) const; + void drop_wishing_piece(ProControllerContext& context) const; + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + MillisecondsOption WAIT_TIME_IN_DEN0; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.cpp index 05e106e388..28b5807da2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.cpp @@ -1,248 +1,248 @@ -/* Purple Beam Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_PurpleBeamFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -PurpleBeamFinder_Descriptor::PurpleBeamFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:PurpleBeamFinder", - STRING_POKEMON + " SwSh", "Purple Beam Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/PurpleBeamFinder.md", - "Automatically reset for a purple beam.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct PurpleBeamFinder_Descriptor::Stats : public StatsTracker{ - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , timeouts(m_stats["Timeouts"]) - , red_detected(m_stats["Red Detected"]) - , red_presumed(m_stats["Red Presumed"]) - , red(m_stats["Red"]) - , purple(m_stats["Purple"]) - { - m_display_order.emplace_back(Stat("Attempts")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Timeouts")); -// m_display_order.emplace_back(Stat("Red Detected")); -// m_display_order.emplace_back(Stat("Red Presumed")); - m_display_order.emplace_back(Stat("Red")); - m_display_order.emplace_back(Stat("Purple")); - m_aliases["Red Detected"] = "Red"; - m_aliases["Red Presumed"] = "Red"; - } - std::atomic& attempts; - std::atomic& errors; - std::atomic& timeouts; - std::atomic& red_detected; - std::atomic& red_presumed; - std::atomic& red; - std::atomic& purple; -}; -std::unique_ptr PurpleBeamFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -PurpleBeamFinder::PurpleBeamFinder() - : NOTIFICATION_RED_BEAM("Red Beam", false, false) - , NOTIFICATION_PURPLE_BEAM("Purple Beam", true, true, ImageAttachmentMode::JPG) - , NOTIFICATIONS({ - &NOTIFICATION_RED_BEAM, - &NOTIFICATION_PURPLE_BEAM, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: Don't adjust these unless you're having problems." - ) - , SAVE_SCREENSHOT( - "Screenshot Purple Beams: (for debugging purposes)", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , TIMEOUT_DELAY0( - "Timeout Delay:
Reset if no beam is detected after this long.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) -// , MAX_STDDEV( -// "Maximum Standard Deviation:
Range: 0 - 768", -// 10, 0, 768 -// ) - , MIN_BRIGHTNESS( - "Minimum Brightness:
Range: 0 - 768", - LockMode::LOCK_WHILE_RUNNING, - 500, 0, 768 - ) - , MIN_EUCLIDEAN( - "Minimum Euclidean Distance:
Range: 0 - 443", - LockMode::LOCK_WHILE_RUNNING, - 15, 0, 443 - ) - , MIN_DELTA_STDDEV_RATIO( - "Minimum Delta/Stddev Ratio:", - LockMode::LOCK_WHILE_RUNNING, - 5.0, 0 - ) - , MIN_SIGMA_STDDEV_RATIO( - "Minimum Sigma/Stddev Ratio:", - LockMode::LOCK_WHILE_RUNNING, - 5.0, 0 - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(NOTIFICATIONS); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(TIMEOUT_DELAY0); - PA_ADD_OPTION(MIN_BRIGHTNESS); - PA_ADD_OPTION(MIN_EUCLIDEAN); - PA_ADD_OPTION(MIN_DELTA_STDDEV_RATIO); - PA_ADD_OPTION(MIN_SIGMA_STDDEV_RATIO); - } -} - - - - -bool PurpleBeamFinder::run(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - PurpleBeamFinder_Descriptor::Stats& stats = env.current_stats(); - - SelectionArrowFinder arrow_detector(env.console.overlay(), {0.5, 0.5, 0.3, 0.3}); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 1000); - }, - { arrow_detector } - ); - if (ret < 0){ - env.log("Failed to detect cursor.", COLOR_RED); - stats.errors++; - return false; - } - env.log("Detected initial prompt."); - - pbf_mash_button(context, BUTTON_A, 50); - pbf_wait(context, 100); - context.wait_for_all_requests(); - - ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_press_button(context, BUTTON_A, 10, 300); - }, - { arrow_detector } - ); - if (ret < 0){ - env.log("Failed to detect save confirmation.", COLOR_RED); - stats.errors++; - return false; - } - env.log("Detected save confirmation."); - - BeamSetter::Detection detection; - { - BeamSetter setter(env, env.console, context); - detection = setter.run( - SAVE_SCREENSHOT, - TIMEOUT_DELAY0, - MIN_BRIGHTNESS, - MIN_EUCLIDEAN, - MIN_DELTA_STDDEV_RATIO, - MIN_SIGMA_STDDEV_RATIO - ); - stats.attempts++; - } - switch (detection){ - case BeamSetter::NO_DETECTION: - stats.timeouts++; - send_program_status_notification(env, NOTIFICATION_RED_BEAM, "Red Beam..."); - return false; - case BeamSetter::RED_DETECTED: - stats.red_detected++; - send_program_status_notification(env, NOTIFICATION_RED_BEAM, "Red Beam..."); - return false; - case BeamSetter::RED_ASSUMED: - stats.red_presumed++; - send_program_status_notification(env, NOTIFICATION_RED_BEAM, "Red Beam..."); - return false; - case BeamSetter::PURPLE: - stats.purple++; - return true; - } - - return false; -} - -void PurpleBeamFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - pbf_mash_button(context, BUTTON_B, 100); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - context.wait_for_all_requests(); - - while (true){ - bool exit = run(env, context); - env.update_stats(); - if (exit){ - break; - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - - context.wait_for(std::chrono::seconds(2)); - send_program_finished_notification( - env, NOTIFICATION_PURPLE_BEAM, - "Found a purple beam!", - env.console.video().snapshot() - ); - while (true){ - pbf_press_button(context, BUTTON_B, 20, 20); - pbf_press_button(context, BUTTON_LCLICK, 20, 20); - } -} - - - - - -} -} -} - +/* Purple Beam Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_BeamSetter.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_PurpleBeamFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +PurpleBeamFinder_Descriptor::PurpleBeamFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:PurpleBeamFinder", + STRING_POKEMON + " SwSh", "Purple Beam Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/PurpleBeamFinder.md", + "Automatically reset for a purple beam.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct PurpleBeamFinder_Descriptor::Stats : public StatsTracker{ + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , timeouts(m_stats["Timeouts"]) + , red_detected(m_stats["Red Detected"]) + , red_presumed(m_stats["Red Presumed"]) + , red(m_stats["Red"]) + , purple(m_stats["Purple"]) + { + m_display_order.emplace_back(Stat("Attempts")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Timeouts")); +// m_display_order.emplace_back(Stat("Red Detected")); +// m_display_order.emplace_back(Stat("Red Presumed")); + m_display_order.emplace_back(Stat("Red")); + m_display_order.emplace_back(Stat("Purple")); + m_aliases["Red Detected"] = "Red"; + m_aliases["Red Presumed"] = "Red"; + } + std::atomic& attempts; + std::atomic& errors; + std::atomic& timeouts; + std::atomic& red_detected; + std::atomic& red_presumed; + std::atomic& red; + std::atomic& purple; +}; +std::unique_ptr PurpleBeamFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +PurpleBeamFinder::PurpleBeamFinder() + : NOTIFICATION_RED_BEAM("Red Beam", false, false) + , NOTIFICATION_PURPLE_BEAM("Purple Beam", true, true, ImageAttachmentMode::JPG) + , NOTIFICATIONS({ + &NOTIFICATION_RED_BEAM, + &NOTIFICATION_PURPLE_BEAM, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: Don't adjust these unless you're having problems." + ) + , SAVE_SCREENSHOT( + "Screenshot Purple Beams: (for debugging purposes)", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , TIMEOUT_DELAY0( + "Timeout Delay:
Reset if no beam is detected after this long.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) +// , MAX_STDDEV( +// "Maximum Standard Deviation:
Range: 0 - 768", +// 10, 0, 768 +// ) + , MIN_BRIGHTNESS( + "Minimum Brightness:
Range: 0 - 768", + LockMode::LOCK_WHILE_RUNNING, + 500, 0, 768 + ) + , MIN_EUCLIDEAN( + "Minimum Euclidean Distance:
Range: 0 - 443", + LockMode::LOCK_WHILE_RUNNING, + 15, 0, 443 + ) + , MIN_DELTA_STDDEV_RATIO( + "Minimum Delta/Stddev Ratio:", + LockMode::LOCK_WHILE_RUNNING, + 5.0, 0 + ) + , MIN_SIGMA_STDDEV_RATIO( + "Minimum Sigma/Stddev Ratio:", + LockMode::LOCK_WHILE_RUNNING, + 5.0, 0 + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(NOTIFICATIONS); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(TIMEOUT_DELAY0); + PA_ADD_OPTION(MIN_BRIGHTNESS); + PA_ADD_OPTION(MIN_EUCLIDEAN); + PA_ADD_OPTION(MIN_DELTA_STDDEV_RATIO); + PA_ADD_OPTION(MIN_SIGMA_STDDEV_RATIO); + } +} + + + + +bool PurpleBeamFinder::run(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + PurpleBeamFinder_Descriptor::Stats& stats = env.current_stats(); + + SelectionArrowFinder arrow_detector(env.console.overlay(), {0.5, 0.5, 0.3, 0.3}); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 1000); + }, + { arrow_detector } + ); + if (ret < 0){ + env.log("Failed to detect cursor.", COLOR_RED); + stats.errors++; + return false; + } + env.log("Detected initial prompt."); + + pbf_mash_button(context, BUTTON_A, 50); + pbf_wait(context, 100); + context.wait_for_all_requests(); + + ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_press_button(context, BUTTON_A, 10, 300); + }, + { arrow_detector } + ); + if (ret < 0){ + env.log("Failed to detect save confirmation.", COLOR_RED); + stats.errors++; + return false; + } + env.log("Detected save confirmation."); + + BeamSetter::Detection detection; + { + BeamSetter setter(env, env.console, context); + detection = setter.run( + SAVE_SCREENSHOT, + TIMEOUT_DELAY0, + MIN_BRIGHTNESS, + MIN_EUCLIDEAN, + MIN_DELTA_STDDEV_RATIO, + MIN_SIGMA_STDDEV_RATIO + ); + stats.attempts++; + } + switch (detection){ + case BeamSetter::NO_DETECTION: + stats.timeouts++; + send_program_status_notification(env, NOTIFICATION_RED_BEAM, "Red Beam..."); + return false; + case BeamSetter::RED_DETECTED: + stats.red_detected++; + send_program_status_notification(env, NOTIFICATION_RED_BEAM, "Red Beam..."); + return false; + case BeamSetter::RED_ASSUMED: + stats.red_presumed++; + send_program_status_notification(env, NOTIFICATION_RED_BEAM, "Red Beam..."); + return false; + case BeamSetter::PURPLE: + stats.purple++; + return true; + } + + return false; +} + +void PurpleBeamFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + pbf_mash_button(context, BUTTON_B, 100); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + context.wait_for_all_requests(); + + while (true){ + bool exit = run(env, context); + env.update_stats(); + if (exit){ + break; + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + + context.wait_for(std::chrono::seconds(2)); + send_program_finished_notification( + env, NOTIFICATION_PURPLE_BEAM, + "Found a purple beam!", + env.console.video().snapshot() + ); + while (true){ + pbf_press_button(context, BUTTON_B, 20, 20); + pbf_press_button(context, BUTTON_LCLICK, 20, 20); + } +} + + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h index 0991bef521..b4d23e84a6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/DenHunting/PokemonSwSh_PurpleBeamFinder.h @@ -1,63 +1,63 @@ -/* Purple Beam Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_PurpleBeamFinder_H -#define PokemonAutomation_PokemonSwSh_PurpleBeamFinder_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class PurpleBeamFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - PurpleBeamFinder_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class PurpleBeamFinder : public SingleSwitchProgramInstance{ -public: - PurpleBeamFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool run(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - -private: - StartInGripOrGameOption START_LOCATION; - - EventNotificationOption NOTIFICATION_RED_BEAM; - EventNotificationOption NOTIFICATION_PURPLE_BEAM; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - BooleanCheckBoxOption SAVE_SCREENSHOT; - MillisecondsOption TIMEOUT_DELAY0; -// FloatingPoint MAX_STDDEV; - FloatingPointOption MIN_BRIGHTNESS; - FloatingPointOption MIN_EUCLIDEAN; - FloatingPointOption MIN_DELTA_STDDEV_RATIO; - FloatingPointOption MIN_SIGMA_STDDEV_RATIO; -}; - - -} -} -} -#endif - +/* Purple Beam Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_PurpleBeamFinder_H +#define PokemonAutomation_PokemonSwSh_PurpleBeamFinder_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class PurpleBeamFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + PurpleBeamFinder_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class PurpleBeamFinder : public SingleSwitchProgramInstance{ +public: + PurpleBeamFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool run(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + +private: + StartInGripOrGameOption START_LOCATION; + + EventNotificationOption NOTIFICATION_RED_BEAM; + EventNotificationOption NOTIFICATION_PURPLE_BEAM; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + BooleanCheckBoxOption SAVE_SCREENSHOT; + MillisecondsOption TIMEOUT_DELAY0; +// FloatingPoint MAX_STDDEV; + FloatingPointOption MIN_BRIGHTNESS; + FloatingPointOption MIN_EUCLIDEAN; + FloatingPointOption MIN_DELTA_STDDEV_RATIO; + FloatingPointOption MIN_SIGMA_STDDEV_RATIO; +}; + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.cpp index 677028f67e..00f0b8d2b6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.cpp @@ -1,891 +1,891 @@ -/* Egg Autonomous - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh_EggHelpers.h" -#include "PokemonSwSh_EggAutonomous.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h" - -namespace PokemonAutomation{ - -using namespace Pokemon; - -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -namespace{ - -// We assume Pokemon app is always at row 0, col 1 -const size_t POKEMON_APP_INDEX = 1; -// We assume Town Map app is always at row 1, col 0 -const size_t TOWN_MAP_APP_INDEX = 5; - - -} - - -EggAutonomous_Descriptor::EggAutonomous_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EggAutonomous", - STRING_POKEMON + " SwSh", "Egg Autonomous", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggAutonomous.md", - "Automatically fetch+hatch eggs and keep all shinies.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -class EggAutonomous_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : m_hatched(m_stats["Eggs Hatched"]) - , m_errors(m_stats["Errors"]) - , m_fetch_attempts(m_stats["Fetch Attempts"]) - , m_fetch_success(m_stats["Fetch Success"]) - , m_shinies(m_stats["Shinies"]) - { - m_display_order.emplace_back("Eggs Hatched"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Fetch Attempts"); - m_display_order.emplace_back("Fetch Success"); - m_display_order.emplace_back("Shinies"); - } - - std::atomic& m_hatched; - std::atomic& m_errors; - std::atomic& m_fetch_attempts; - std::atomic& m_fetch_success; - std::atomic& m_shinies; -}; -std::unique_ptr EggAutonomous_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -EggAutonomous::EggAutonomous() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:
Required to read IVs.", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - false - ) - , MAX_KEEPERS( - "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " - "This number plus the number of " + STRING_POKEMON + " in the box left to your current box must not exceed 30. " - "Otherwise, the program will break when that box is full.", - LockMode::LOCK_WHILE_RUNNING, - 10, 1, 30 - ) - , LOOPS_PER_FETCH( - "Bike Loops Per Fetch:
Fetch an egg after doing this many bike loops on Route 5.", - LockMode::LOCK_WHILE_RUNNING, - 1, 1 - ) - , NUM_EGGS_IN_COLUMN( - "Num Eggs in Column:
How many eggs already deposited in the first column in Box 1.", - { - {0, "0", "0"}, - {1, "1", "1"}, - {2, "2", "2"}, - {3, "3", "3"}, - {4, "4", "4"}, - {5, "5", "5"}, - }, - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , AUTO_SAVING( - "Auto-Saving:
Automatically save the game to recover from crashes and allow eggs to be unhatched.
" - "(Unhatching eggs can be useful for obtaining breeding parents by rehatching a perfect egg in a game with a different language.)

" - "To collect (unhatched) eggs with the desired stats, set this option to \"Save before every batch\". " - "Then set the Action Table below to \"Stop Program\" on the desired stats. " - "Once the program stops on the baby with the desired stats, you can manually reset the game and it will revert to an egg in your party.", - { - {AutoSave::NoAutoSave, "none", "No auto-saving. (No error/crash recovery.)"}, - {AutoSave::AfterStartAndKeep, "start-and-keep", "Save at beginning and after obtaining each baby that is kept. (Allows for error/crash recovery.)"}, - {AutoSave::EveryBatch, "every-batch", "Save before every batch. (Allows you to unhatch eggs.)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - AutoSave::AfterStartAndKeep - ) - , FILTERS0( - StatsHuntIvJudgeFilterTable_Label_Eggs, - { - .action = true, - .shiny = true, - .gender = true, - .nature = true, - } - ) - , DEBUG_PROCESSING_HATCHED( - "Debug the part of program after all eggs hatched", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SAVE_DEBUG_VIDEO( - "Save debug videos to Switch:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_NONSHINY_KEEP( - "Non-Shiny Keep", - true, true, ImageAttachmentMode::JPG, - {"Notifs"} - ) - , NOTIFICATION_SHINY( - "Shiny Hatch", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) - , m_notification_noop("", false, false) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_NONSHINY_KEEP, - &NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - // PA_ADD_OPTION(STEPS_TO_HATCH); - - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(MAX_KEEPERS); - PA_ADD_OPTION(LOOPS_PER_FETCH); - PA_ADD_OPTION(NUM_EGGS_IN_COLUMN); - PA_ADD_OPTION(AUTO_SAVING); - PA_ADD_OPTION(FILTERS0); - PA_ADD_OPTION(NOTIFICATIONS); - - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(DEBUG_PROCESSING_HATCHED); - PA_ADD_OPTION(SAVE_DEBUG_VIDEO); - } -} - -void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - auto& stats = env.current_stats(); - env.update_stats(); - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - if (DEBUG_PROCESSING_HATCHED){ // only for debugging - const bool need_taxi = true; - process_hatched_pokemon(env, context, stats, need_taxi); - return; - } - - - if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ - save_game(env, context); - m_num_eggs_in_storage_when_game_saved = static_cast(NUM_EGGS_IN_COLUMN.current_value()); - } - m_num_eggs_retrieved = static_cast(NUM_EGGS_IN_COLUMN.current_value()); - - m_num_pokemon_kept = 0; - - m_player_at_loop_start = false; - - // while(run_batch(env, context, stats)){} - - size_t consecutive_failures = 0; - while(m_num_pokemon_kept < MAX_KEEPERS){ - try{ - if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ - env.log("Touching date to prevent rollover."); - env.console.overlay().add_log("Touching date", COLOR_WHITE); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - - // Hatch one batch of eggs. If run_batch() returns true, stop the egg loop. - if (run_batch(env, context, stats)){ - break; - } - env.log("stats: " + stats.to_str(StatsTracker::DISPLAY_ON_SCREEN)); - // We successfully finish one egg loop iteration without any error thrown. - // So we reset the failure counter. - consecutive_failures = 0; - }catch (OperationFailedException& e){ - stats.m_errors++; - env.update_stats(); - e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); - - if (SAVE_DEBUG_VIDEO){ - // Take a video to give more context for debugging - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - - // If there is no auto save, then we shouldn't reset to game to lose previous progress. - if (AUTO_SAVING == AutoSave::NoAutoSave){ - throw; - } - - consecutive_failures++; - if (consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed 3 batches in the row.", - env.console - ); - } - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - env.console.overlay().add_log("Reset game", COLOR_WHITE); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - - m_player_at_loop_start = false; - m_num_eggs_retrieved = m_num_eggs_in_storage_when_game_saved; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - -// Run one iteration of the egg loop: -// - Hatch five eggs while fetch five eggs. -// - Check if pokemon needs to be kept. Keep them if needed. -// - Put five eggs from storage to party. Save game if needed. -// Return true if the egg loop should stop. -bool EggAutonomous::run_batch( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats -){ - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - if (m_player_at_loop_start == false){ // reset position - const bool fly_from_overworld = true; // fly from menu - call_flying_taxi(env, context, fly_from_overworld); - } - - size_t bike_loop_count = 0; - const size_t MAX_BIKE_LOOP_COUNT = 100; - size_t num_eggs_hatched = 0; - m_player_at_loop_start = false; - - // Each iteration in the while-loop is made by: - // - bike loops of LOOPS_PER_FETCH times. Bike loops begin at lady or nursery front door, end at lady. - // - if not enough eggs fetched, talk to lady to try fetching an egg. - while (num_eggs_hatched < 5 || m_num_eggs_retrieved < 5){ - // Detect when Y-Comm icon disappears. This is the time an egg is hatching - const bool y_comm_visible_when_egg_hatching = false; - YCommIconDetector egg_hatching_detector(y_comm_visible_when_egg_hatching); - - bool restart_bike_loop = false; - for (size_t i_bike_loop = 0; i_bike_loop < this->LOOPS_PER_FETCH && bike_loop_count < MAX_BIKE_LOOP_COUNT;){ - context.wait_for_all_requests(); - // +1 here because video overlay is for general users. General users start counts at 1, while us programmers start count at 0. - if (restart_bike_loop){ - env.console.overlay().add_log("Restart loop " + std::to_string(bike_loop_count+1), COLOR_WHITE); - restart_bike_loop = false; - }else{ - env.console.overlay().add_log("Loop " + std::to_string(bike_loop_count+1), COLOR_WHITE); - } - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - travel_to_spin_location(context); - travel_back_to_lady(context); - }, - {{egg_hatching_detector}} - ); - - if (ret < 0){ // we are at nursery lady; no egg hatching detected - ++i_bike_loop; - ++bike_loop_count; - continue; - } - - // Egg hatching - do{ - ++num_eggs_hatched; - stats.m_hatched++; - env.update_stats(); - wait_for_egg_hatched(env, context, stats, num_eggs_hatched); - if (num_eggs_hatched == 5){ - // We hatched all five eggs. No more eggs can hatch. Go to next loop - break; - } - // Now we see if we can hatch one more egg. - ret = run_until( - env.console, context, - [](ProControllerContext& context){ - // Try move a little to hatch more: - // We move toward lower-left so that it wont hit the lady or enter the Nursory. - pbf_move_left_joystick(context, 0, 255, 100, 10); - }, - {{egg_hatching_detector}} - ); - } while(ret == 0); - // now no more hatching in this bike loop - // We either cannot find a consecutive hatch any more or we already hatch five of them - - if (num_eggs_hatched == 5 && m_num_eggs_retrieved == 5){ - m_player_at_loop_start = false; - break; - } - - // Now we either cannot find a consecutive hatch any more, or we already hatch five for them, but - // we still need to fetch more eggs - - // Use fly to reset the location because now we don't know where the player character is. - const bool fly_from_overworld = true; - call_flying_taxi(env, context, fly_from_overworld); - restart_bike_loop = true; - // We don't update i_bike_loop here because we haven't finished one full bike loop due to egg hatching - } // end one bike loop - - if (bike_loop_count >= MAX_BIKE_LOOP_COUNT){ - env.log("Reached max number of bike loops " + std::to_string(MAX_BIKE_LOOP_COUNT)); - env.console.overlay().add_log("Error: max loops " + std::to_string(MAX_BIKE_LOOP_COUNT), COLOR_WHITE); - env.log("Take a screenshot of party to debug."); - // Now take a photo at the player's party for dumping debug info: - // Enter Rotom Phone menu - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - // Select Pokemon App - navigate_to_menu_app(env, env.console, context, POKEMON_APP_INDEX, NOTIFICATION_ERROR_RECOVERABLE); - // From menu enter Pokemon App - ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); - context.wait_for_all_requests(); - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Max number of loops reached. Not enough eggs in party?", - env.console - ); - } - - context.wait_for_all_requests(); - if (m_num_eggs_retrieved < 5){ - // Update num_eggs_retrieved - m_num_eggs_retrieved = talk_to_lady_to_fetch_egg(env, context, stats, m_num_eggs_retrieved); - if (num_eggs_hatched == 5 && m_num_eggs_retrieved == 5){ - m_player_at_loop_start = true; - break; - } - } - } - - // - Go to pokemon storage. - // - Check the hatched pokemon, keep shiny pokemon and those that match the stats requirements. Release the rest. - // - Retrieve the stored egg column to the party. - // - Call flying taxi to reset player location if needed - // Return true if the program should stop - size_t last_num_pokemon_kept = m_num_pokemon_kept; - if (process_hatched_pokemon(env, context, stats, !m_player_at_loop_start)){ - // While checking hatched pokemon, we find that We need to stop the program: - return true; - } - m_num_eggs_retrieved = 0; - // after process_hatched_pokemon(), the player location is at the start of bike loop - m_player_at_loop_start = true; - - bool save = false; - switch (AUTO_SAVING){ - case AutoSave::NoAutoSave: - break; - case AutoSave::AfterStartAndKeep: - save = (last_num_pokemon_kept != m_num_pokemon_kept); - break; - case AutoSave::EveryBatch: - save = true; - break; - default: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid saving option."); - } - - if (save){ - save_game(env, context); - m_num_eggs_in_storage_when_game_saved = 0; - } - - context.wait_for_all_requests(); - return false; -} - -void EggAutonomous::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - context.wait_for_all_requests(); - env.log("Save game."); - env.console.overlay().add_log("Save game", COLOR_WHITE); - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R, 80ms, 2000ms); - pbf_mash_button(context, BUTTON_A, 500ms); - mash_B_until_y_comm_icon(env, context, "Cannot detect end of saving game."); -} - -void EggAutonomous::call_flying_taxi( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - bool fly_from_overworld -){ - context.wait_for_all_requests(); - env.log("Fly to reset position"); - env.console.overlay().add_log("Call Flying Taxi", COLOR_WHITE); - if (fly_from_overworld){ - // Open menu - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - } - - navigate_to_menu_app(env, env.console, context, TOWN_MAP_APP_INDEX, NOTIFICATION_ERROR_RECOVERABLE); - - fly_home(context, false); - mash_B_until_y_comm_icon(env, context, "Cannot detect end of flying taxi animation."); -} - -void EggAutonomous::wait_for_egg_hatched( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats, - size_t num_hatched_eggs -){ - env.console.overlay().add_log("Egg hatching " + std::to_string(num_hatched_eggs) + "/5", COLOR_GREEN); - const bool y_comm_visible_at_end_of_egg_hatching = true; - YCommIconDetector end_egg_hatching_detector(y_comm_visible_at_end_of_egg_hatching); - const int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 60 * TICKS_PER_SECOND); - }, - {{end_egg_hatching_detector}} - ); - if (ret > 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect egg hatching ends.", - env.console - ); - } -} - -size_t EggAutonomous::talk_to_lady_to_fetch_egg( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats, - size_t num_eggs_retrieved -){ - env.log("Fetching egg"); - stats.m_fetch_attempts++; - env.update_stats(); - // collect_egg(context); - RetrieveEggArrowFinder egg_arrow_detector(env.console); - CheckNurseryArrowFinder no_egg_arrow_detector(env.console); - - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - for (size_t i_hatched = 0; i_hatched < 2; i_hatched++){ - pbf_press_button(context, BUTTON_A, 20, 150); - } - pbf_wait(context, 200); - }, - { - egg_arrow_detector, - no_egg_arrow_detector, - } - ); - - const bool y_comm_visible_at_end_of_dialog = true; - YCommIconDetector dialog_over_detector(y_comm_visible_at_end_of_dialog); - switch (ret){ - case 0: - ++num_eggs_retrieved; - env.log("Found egg"); - env.console.overlay().add_log("Found egg " + std::to_string(num_eggs_retrieved) + "/5", COLOR_WHITE); - stats.m_fetch_success++; - env.update_stats(); - // Press A to get the egg - ssf_press_button(context, BUTTON_A, 320ms, 160ms); - - ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 30s); - }, - {{dialog_over_detector}} - ); - break; - - case 1: - env.log("No egg"); - env.console.overlay().add_log("No egg", COLOR_WHITE); - run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 5s); - }, - {{dialog_over_detector}} - ); - return num_eggs_retrieved; -// break; - - default: - env.log("Daycare lady not found."); - env.console.overlay().add_log("No daycare lady", COLOR_WHITE); - return num_eggs_retrieved; -// OperationFailedException::fire( -// ErrorReport::SEND_ERROR_REPORT, -// "Cannot detect dialog selection arrow when talking to Nursery lady.", -// env.console -// ); - } - - // If dialog over is not detected: - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect end of Nursery lady dialog. No Y-Comm mark found.", - env.console - ); - } - - return num_eggs_retrieved; -} - -// After all five eggs hatched and another five eggs deposit into the first column of the box, -// call this function to: -// - Go to pokemon storage. -// - Check the hatched pokemon, keep shiny pokemon and those that match the stats requirements. Release the rest. -// - Retrieve the stored egg column to the party. -// - Call flying taxi to reset player location if needed -// Return true if the program should stop -bool EggAutonomous::process_hatched_pokemon( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats, - bool need_taxi -){ - env.log("Checking hatched pokemon."); - env.console.overlay().add_log("Checking hatched pokemon", COLOR_WHITE); - - // Press X to open menu - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - - navigate_to_menu_app(env, env.console, context, POKEMON_APP_INDEX, NOTIFICATION_ERROR_RECOVERABLE); - - const Milliseconds BOX_CHANGE_DELAY = GameSettings::instance().BOX_CHANGE_DELAY0; - const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - - // From menu enter Pokemon App - ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); - // From Pokemon App to storage box - ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, EGG_BUTTON_HOLD_DELAY); - // Move left down to the first hatched pokemon in the party - box_scroll(context, DPAD_LEFT); - box_scroll(context, DPAD_DOWN); - - context.wait_for_all_requests(); - { - // Define the scope of video overlay rendering for various checks: - VideoOverlaySet overlay_set(env.console.overlay()); - BoxShinySymbolDetector::make_overlays(overlay_set); - BoxGenderDetector gender_detector; - gender_detector.make_overlays(overlay_set); - IvJudgeReaderScope iv_reader(env.console.overlay(), LANGUAGE); - BoxNatureDetector nature_detector(env.console.overlay()); - - for (size_t i_hatched = 0; i_hatched < 5; i_hatched++){ - pbf_wait(context, 50); // wait for a while to make sure the pokemon stats are loaded. - context.wait_for_all_requests(); - auto screen = env.console.video().snapshot(); - - bool shiny = BoxShinySymbolDetector::detect(screen); - if (shiny){ - env.log("Pokemon " + std::to_string(i_hatched) + " is shiny!", COLOR_BLUE); - env.console.overlay().add_log("Pokemon " + std::to_string(i_hatched+1) + "/5 is shiny!", COLOR_YELLOW); - stats.m_shinies++; - env.update_stats(); - send_encounter_notification( - env, - m_notification_noop, - NOTIFICATION_SHINY, - false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), - screen - ); - }else{ - env.log("Pokemon " + std::to_string(i_hatched) + " is not shiny.", COLOR_PURPLE); - env.console.overlay().add_log("Pokemon " + std::to_string(i_hatched+1) + "/5 not shiny", COLOR_WHITE); - } - // Note: we assume the pokemon storage UI is in the state of judging pokemon stats. - // In this way we can detect pokemon stats. - - IvJudgeReader::Results IVs = iv_reader.read(env.console, screen); - StatsHuntGenderFilter gender = gender_detector.detect(screen); - env.log(IVs.to_string(), COLOR_GREEN); - env.log("Gender: " + gender_to_string(gender), COLOR_GREEN); - NatureReader::Results nature = nature_detector.read(env.console.logger(), screen); - - StatsHuntAction action = FILTERS0.get_action(shiny, gender, nature.nature, IVs); - - auto send_keep_notification = [&](){ - if (!shiny){ - send_encounter_notification( - env, - NOTIFICATION_NONSHINY_KEEP, - NOTIFICATION_SHINY, - false, false, {}, std::nan(""), - screen - ); - } - }; - switch (action){ - case StatsHuntAction::StopProgram: - env.log("Program stop requested..."); - env.console.overlay().add_log("Request program stop", COLOR_WHITE); - send_keep_notification(); - return true; - case StatsHuntAction::Keep: - env.log("Moving Pokemon to keep box...", COLOR_BLUE); - m_num_pokemon_kept++; - env.console.overlay().add_log("Keep pokemon " + std::to_string(m_num_pokemon_kept) + "/" + std::to_string(MAX_KEEPERS), COLOR_YELLOW); - send_keep_notification(); - - // Press A twice to pick the pokemon - ssf_press_button_ptv(context, BUTTON_A, 480ms, EGG_BUTTON_HOLD_DELAY); - ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); - - // Move it rightward, so that it stays on top of the box area - box_scroll(context, DPAD_RIGHT); - // Press Button L to change to the box on the left - ssf_press_button_ptv(context, BUTTON_L, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - - // Because we don't know which place in the box to place the pokemon, we will - // throw the pokemon in the all-box view. So it automatically sit in the first empty slot - // in the box: - - // Move it three times upward, so that it stays on top of the "Box List" button - box_scroll(context, DPAD_UP); - box_scroll(context, DPAD_UP); - box_scroll(context, DPAD_UP); - - // Press the button to go to box list view - ssf_press_button_ptv(context, BUTTON_A, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - // Press button A to drop the pokemon into the box - ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); - // Press button B to go back to the last box - ssf_press_button_ptv(context, BUTTON_B, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - // Press button R to change to the box on the right, the box with the next batch of eggs - ssf_press_button_ptv(context, BUTTON_R, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - // Move cursor left to point to the last slot in the party - box_scroll(context, DPAD_LEFT); - // Move cursor downward three times so that it goes to the original place (second slot in the party) - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_DOWN); - - if (m_num_pokemon_kept >= MAX_KEEPERS){ - env.log("Max keepers reached. Stopping program..."); - env.console.overlay().add_log("Max Keepers reached.", COLOR_WHITE); - return true; - } - break; - case StatsHuntAction::Discard: - env.log("Releasing Pokemon...", COLOR_PURPLE); - env.console.overlay().add_log("Release Pokemon", COLOR_WHITE); - - // ssf_press_button2(context, BUTTON_A, 60, 10); - // ssf_press_dpad2(context, DPAD_UP, BOX_SCROLL_DELAY, EGG_BUTTON_HOLD_DELAY); - // ssf_press_dpad2(context, DPAD_UP, BOX_SCROLL_DELAY, EGG_BUTTON_HOLD_DELAY); - // ssf_press_button2(context, BUTTON_A, 125, 10); - // ssf_press_dpad2(context, DPAD_UP, BOX_SCROLL_DELAY, EGG_BUTTON_HOLD_DELAY); - // pbf_mash_button(context, BUTTON_A, 180); - - // Press A to open pokemon menu - pbf_press_button(context, BUTTON_A, 20, 50); - context.wait_for_all_requests(); - StoragePokemonMenuArrowFinder pokemon_menu_detector(env.console.overlay()); - int ret = wait_until( - env.console, context, std::chrono::seconds(10), - {{pokemon_menu_detector}} - ); - if (ret != 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect pokemon menu in storage box.", - env.console - ); - } - - const bool stop_on_detected = true; - BlackDialogBoxDetector dialog_detector(stop_on_detected); - VideoOverlaySet dialog_overlay_set(env.console); - dialog_detector.make_overlays(dialog_overlay_set); - - // Move cursor upward two times to point to "Release" menu item - pbf_press_dpad(context, DPAD_UP, 20, 20); - pbf_press_dpad(context, DPAD_UP, 20, 20); - - // Press A to release - pbf_press_button(context, BUTTON_A, 20, 105); - // Move cursor from "Not release" to "release". - pbf_press_dpad(context, DPAD_UP, 20, 30); - // Press A to confirm release, wait for a while to let the next dialog box pop up. - pbf_press_button(context, BUTTON_A, 20, 200); - - context.wait_for_all_requests(); - ret = wait_until( - env.console, context, std::chrono::seconds(10), - {{dialog_detector}} - ); - if (ret != 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Miss second dialog when releasing pokemon.", - env.console - ); - } - pbf_press_button(context, BUTTON_A, 20, 100); - - size_t dialog_count = 0; - const size_t max_dialog_count = 6; - for (; dialog_count < max_dialog_count; dialog_count++){ - context.wait_for_all_requests(); - if (!dialog_detector.process_frame(env.console.video().snapshot(), current_time())){ - break; - } - pbf_press_button(context, BUTTON_A, 20, 100); - } - if (dialog_count == max_dialog_count){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unexpected dialogs when releasing pokemon.", - env.console - ); - } - break; - } - } - } - - // Get eggs to party: - - // Move cursor to the first slot in the box - box_scroll(context, DPAD_UP); - box_scroll(context, DPAD_RIGHT); - - // Press Y twice to change selection method to group selection - pbf_press_button(context, BUTTON_Y, EGG_BUTTON_HOLD_DELAY, 400ms); - pbf_press_button(context, BUTTON_Y, EGG_BUTTON_HOLD_DELAY, 400ms); - - // Press A to start selection - pbf_press_button(context, BUTTON_A, EGG_BUTTON_HOLD_DELAY, 400ms); - // Move down to selection the entire column - for (size_t c = 0; c < 4; c++){ - box_scroll(context, DPAD_DOWN); - } - // Press A to finish the selection - ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); - - // Move cursor to the second slot in the party - box_scroll(context, DPAD_LEFT); - box_scroll(context, DPAD_DOWN); - - // Press A to finish dropping the egg column - ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); - - // leave pokemon box, back to pokemon app - ssf_press_button(context, BUTTON_B, GameSettings::instance().BOX_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); - // Back out to menu. - ssf_press_button(context, BUTTON_B, GameSettings::instance().POKEMON_TO_MENU_DELAY0, EGG_BUTTON_HOLD_DELAY); - - if (need_taxi){ - bool fly_from_overworld = false; // fly from menu - call_flying_taxi(env, context, fly_from_overworld); - }else{ - // Leave menu, go back to overworld - const bool y_comm_visible = true; - YCommIconDetector y_comm_detector(y_comm_visible); - const int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 5000ms); - }, - {{y_comm_detector}} - ); - if (ret > 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect Y-Comm after leaving menu.", - env.console - ); - } - } - - return false; -} - -void EggAutonomous::mash_B_until_y_comm_icon( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const std::string& error_msg -){ - context.wait_for_all_requests(); - const bool y_comm_visible = true; - YCommIconDetector y_comm_detector(y_comm_visible); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10s); - }, - {y_comm_detector} - ); - if (ret != 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - error_msg + " No Y-Comm mark found.", - env.console - ); - } -} - - - - -} -} -} - +/* Egg Autonomous + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/PokemonSwSh_BoxGenderDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_BoxShinySymbolDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_DialogBoxDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSwSh/Inference/PokemonSwSh_BoxNatureDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh_EggHelpers.h" +#include "PokemonSwSh_EggAutonomous.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h" + +namespace PokemonAutomation{ + +using namespace Pokemon; + +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +namespace{ + +// We assume Pokemon app is always at row 0, col 1 +const size_t POKEMON_APP_INDEX = 1; +// We assume Town Map app is always at row 1, col 0 +const size_t TOWN_MAP_APP_INDEX = 5; + + +} + + +EggAutonomous_Descriptor::EggAutonomous_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EggAutonomous", + STRING_POKEMON + " SwSh", "Egg Autonomous", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggAutonomous.md", + "Automatically fetch+hatch eggs and keep all shinies.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +class EggAutonomous_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : m_hatched(m_stats["Eggs Hatched"]) + , m_errors(m_stats["Errors"]) + , m_fetch_attempts(m_stats["Fetch Attempts"]) + , m_fetch_success(m_stats["Fetch Success"]) + , m_shinies(m_stats["Shinies"]) + { + m_display_order.emplace_back("Eggs Hatched"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Fetch Attempts"); + m_display_order.emplace_back("Fetch Success"); + m_display_order.emplace_back("Shinies"); + } + + std::atomic& m_hatched; + std::atomic& m_errors; + std::atomic& m_fetch_attempts; + std::atomic& m_fetch_success; + std::atomic& m_shinies; +}; +std::unique_ptr EggAutonomous_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +EggAutonomous::EggAutonomous() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:
Required to read IVs.", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + false + ) + , MAX_KEEPERS( + "Max Keepers:
Stop the program after keeping this many " + STRING_POKEMON + ". " + "This number plus the number of " + STRING_POKEMON + " in the box left to your current box must not exceed 30. " + "Otherwise, the program will break when that box is full.", + LockMode::LOCK_WHILE_RUNNING, + 10, 1, 30 + ) + , LOOPS_PER_FETCH( + "Bike Loops Per Fetch:
Fetch an egg after doing this many bike loops on Route 5.", + LockMode::LOCK_WHILE_RUNNING, + 1, 1 + ) + , NUM_EGGS_IN_COLUMN( + "Num Eggs in Column:
How many eggs already deposited in the first column in Box 1.", + { + {0, "0", "0"}, + {1, "1", "1"}, + {2, "2", "2"}, + {3, "3", "3"}, + {4, "4", "4"}, + {5, "5", "5"}, + }, + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , AUTO_SAVING( + "Auto-Saving:
Automatically save the game to recover from crashes and allow eggs to be unhatched.
" + "(Unhatching eggs can be useful for obtaining breeding parents by rehatching a perfect egg in a game with a different language.)

" + "To collect (unhatched) eggs with the desired stats, set this option to \"Save before every batch\". " + "Then set the Action Table below to \"Stop Program\" on the desired stats. " + "Once the program stops on the baby with the desired stats, you can manually reset the game and it will revert to an egg in your party.", + { + {AutoSave::NoAutoSave, "none", "No auto-saving. (No error/crash recovery.)"}, + {AutoSave::AfterStartAndKeep, "start-and-keep", "Save at beginning and after obtaining each baby that is kept. (Allows for error/crash recovery.)"}, + {AutoSave::EveryBatch, "every-batch", "Save before every batch. (Allows you to unhatch eggs.)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + AutoSave::AfterStartAndKeep + ) + , FILTERS0( + StatsHuntIvJudgeFilterTable_Label_Eggs, + { + .action = true, + .shiny = true, + .gender = true, + .nature = true, + } + ) + , DEBUG_PROCESSING_HATCHED( + "Debug the part of program after all eggs hatched", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SAVE_DEBUG_VIDEO( + "Save debug videos to Switch:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_NONSHINY_KEEP( + "Non-Shiny Keep", + true, true, ImageAttachmentMode::JPG, + {"Notifs"} + ) + , NOTIFICATION_SHINY( + "Shiny Hatch", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) + , m_notification_noop("", false, false) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_NONSHINY_KEEP, + &NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + // PA_ADD_OPTION(STEPS_TO_HATCH); + + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(MAX_KEEPERS); + PA_ADD_OPTION(LOOPS_PER_FETCH); + PA_ADD_OPTION(NUM_EGGS_IN_COLUMN); + PA_ADD_OPTION(AUTO_SAVING); + PA_ADD_OPTION(FILTERS0); + PA_ADD_OPTION(NOTIFICATIONS); + + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(DEBUG_PROCESSING_HATCHED); + PA_ADD_OPTION(SAVE_DEBUG_VIDEO); + } +} + +void EggAutonomous::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + auto& stats = env.current_stats(); + env.update_stats(); + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + if (DEBUG_PROCESSING_HATCHED){ // only for debugging + const bool need_taxi = true; + process_hatched_pokemon(env, context, stats, need_taxi); + return; + } + + + if (AUTO_SAVING == AutoSave::AfterStartAndKeep){ + save_game(env, context); + m_num_eggs_in_storage_when_game_saved = static_cast(NUM_EGGS_IN_COLUMN.current_value()); + } + m_num_eggs_retrieved = static_cast(NUM_EGGS_IN_COLUMN.current_value()); + + m_num_pokemon_kept = 0; + + m_player_at_loop_start = false; + + // while(run_batch(env, context, stats)){} + + size_t consecutive_failures = 0; + while(m_num_pokemon_kept < MAX_KEEPERS){ + try{ + if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ + env.log("Touching date to prevent rollover."); + env.console.overlay().add_log("Touching date", COLOR_WHITE); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + + // Hatch one batch of eggs. If run_batch() returns true, stop the egg loop. + if (run_batch(env, context, stats)){ + break; + } + env.log("stats: " + stats.to_str(StatsTracker::DISPLAY_ON_SCREEN)); + // We successfully finish one egg loop iteration without any error thrown. + // So we reset the failure counter. + consecutive_failures = 0; + }catch (OperationFailedException& e){ + stats.m_errors++; + env.update_stats(); + e.send_notification(env, NOTIFICATION_ERROR_RECOVERABLE); + + if (SAVE_DEBUG_VIDEO){ + // Take a video to give more context for debugging + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 2 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + + // If there is no auto save, then we shouldn't reset to game to lose previous progress. + if (AUTO_SAVING == AutoSave::NoAutoSave){ + throw; + } + + consecutive_failures++; + if (consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed 3 batches in the row.", + env.console + ); + } + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + env.console.overlay().add_log("Reset game", COLOR_WHITE); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + + m_player_at_loop_start = false; + m_num_eggs_retrieved = m_num_eggs_in_storage_when_game_saved; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + +// Run one iteration of the egg loop: +// - Hatch five eggs while fetch five eggs. +// - Check if pokemon needs to be kept. Keep them if needed. +// - Put five eggs from storage to party. Save game if needed. +// Return true if the egg loop should stop. +bool EggAutonomous::run_batch( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats +){ + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + if (m_player_at_loop_start == false){ // reset position + const bool fly_from_overworld = true; // fly from menu + call_flying_taxi(env, context, fly_from_overworld); + } + + size_t bike_loop_count = 0; + const size_t MAX_BIKE_LOOP_COUNT = 100; + size_t num_eggs_hatched = 0; + m_player_at_loop_start = false; + + // Each iteration in the while-loop is made by: + // - bike loops of LOOPS_PER_FETCH times. Bike loops begin at lady or nursery front door, end at lady. + // - if not enough eggs fetched, talk to lady to try fetching an egg. + while (num_eggs_hatched < 5 || m_num_eggs_retrieved < 5){ + // Detect when Y-Comm icon disappears. This is the time an egg is hatching + const bool y_comm_visible_when_egg_hatching = false; + YCommIconDetector egg_hatching_detector(y_comm_visible_when_egg_hatching); + + bool restart_bike_loop = false; + for (size_t i_bike_loop = 0; i_bike_loop < this->LOOPS_PER_FETCH && bike_loop_count < MAX_BIKE_LOOP_COUNT;){ + context.wait_for_all_requests(); + // +1 here because video overlay is for general users. General users start counts at 1, while us programmers start count at 0. + if (restart_bike_loop){ + env.console.overlay().add_log("Restart loop " + std::to_string(bike_loop_count+1), COLOR_WHITE); + restart_bike_loop = false; + }else{ + env.console.overlay().add_log("Loop " + std::to_string(bike_loop_count+1), COLOR_WHITE); + } + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + travel_to_spin_location(context); + travel_back_to_lady(context); + }, + {{egg_hatching_detector}} + ); + + if (ret < 0){ // we are at nursery lady; no egg hatching detected + ++i_bike_loop; + ++bike_loop_count; + continue; + } + + // Egg hatching + do{ + ++num_eggs_hatched; + stats.m_hatched++; + env.update_stats(); + wait_for_egg_hatched(env, context, stats, num_eggs_hatched); + if (num_eggs_hatched == 5){ + // We hatched all five eggs. No more eggs can hatch. Go to next loop + break; + } + // Now we see if we can hatch one more egg. + ret = run_until( + env.console, context, + [](ProControllerContext& context){ + // Try move a little to hatch more: + // We move toward lower-left so that it wont hit the lady or enter the Nursory. + pbf_move_left_joystick(context, 0, 255, 100, 10); + }, + {{egg_hatching_detector}} + ); + } while(ret == 0); + // now no more hatching in this bike loop + // We either cannot find a consecutive hatch any more or we already hatch five of them + + if (num_eggs_hatched == 5 && m_num_eggs_retrieved == 5){ + m_player_at_loop_start = false; + break; + } + + // Now we either cannot find a consecutive hatch any more, or we already hatch five for them, but + // we still need to fetch more eggs + + // Use fly to reset the location because now we don't know where the player character is. + const bool fly_from_overworld = true; + call_flying_taxi(env, context, fly_from_overworld); + restart_bike_loop = true; + // We don't update i_bike_loop here because we haven't finished one full bike loop due to egg hatching + } // end one bike loop + + if (bike_loop_count >= MAX_BIKE_LOOP_COUNT){ + env.log("Reached max number of bike loops " + std::to_string(MAX_BIKE_LOOP_COUNT)); + env.console.overlay().add_log("Error: max loops " + std::to_string(MAX_BIKE_LOOP_COUNT), COLOR_WHITE); + env.log("Take a screenshot of party to debug."); + // Now take a photo at the player's party for dumping debug info: + // Enter Rotom Phone menu + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + // Select Pokemon App + navigate_to_menu_app(env, env.console, context, POKEMON_APP_INDEX, NOTIFICATION_ERROR_RECOVERABLE); + // From menu enter Pokemon App + ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); + context.wait_for_all_requests(); + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Max number of loops reached. Not enough eggs in party?", + env.console + ); + } + + context.wait_for_all_requests(); + if (m_num_eggs_retrieved < 5){ + // Update num_eggs_retrieved + m_num_eggs_retrieved = talk_to_lady_to_fetch_egg(env, context, stats, m_num_eggs_retrieved); + if (num_eggs_hatched == 5 && m_num_eggs_retrieved == 5){ + m_player_at_loop_start = true; + break; + } + } + } + + // - Go to pokemon storage. + // - Check the hatched pokemon, keep shiny pokemon and those that match the stats requirements. Release the rest. + // - Retrieve the stored egg column to the party. + // - Call flying taxi to reset player location if needed + // Return true if the program should stop + size_t last_num_pokemon_kept = m_num_pokemon_kept; + if (process_hatched_pokemon(env, context, stats, !m_player_at_loop_start)){ + // While checking hatched pokemon, we find that We need to stop the program: + return true; + } + m_num_eggs_retrieved = 0; + // after process_hatched_pokemon(), the player location is at the start of bike loop + m_player_at_loop_start = true; + + bool save = false; + switch (AUTO_SAVING){ + case AutoSave::NoAutoSave: + break; + case AutoSave::AfterStartAndKeep: + save = (last_num_pokemon_kept != m_num_pokemon_kept); + break; + case AutoSave::EveryBatch: + save = true; + break; + default: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid saving option."); + } + + if (save){ + save_game(env, context); + m_num_eggs_in_storage_when_game_saved = 0; + } + + context.wait_for_all_requests(); + return false; +} + +void EggAutonomous::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + context.wait_for_all_requests(); + env.log("Save game."); + env.console.overlay().add_log("Save game", COLOR_WHITE); + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R, 80ms, 2000ms); + pbf_mash_button(context, BUTTON_A, 500ms); + mash_B_until_y_comm_icon(env, context, "Cannot detect end of saving game."); +} + +void EggAutonomous::call_flying_taxi( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + bool fly_from_overworld +){ + context.wait_for_all_requests(); + env.log("Fly to reset position"); + env.console.overlay().add_log("Call Flying Taxi", COLOR_WHITE); + if (fly_from_overworld){ + // Open menu + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + } + + navigate_to_menu_app(env, env.console, context, TOWN_MAP_APP_INDEX, NOTIFICATION_ERROR_RECOVERABLE); + + fly_home(context, false); + mash_B_until_y_comm_icon(env, context, "Cannot detect end of flying taxi animation."); +} + +void EggAutonomous::wait_for_egg_hatched( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats, + size_t num_hatched_eggs +){ + env.console.overlay().add_log("Egg hatching " + std::to_string(num_hatched_eggs) + "/5", COLOR_GREEN); + const bool y_comm_visible_at_end_of_egg_hatching = true; + YCommIconDetector end_egg_hatching_detector(y_comm_visible_at_end_of_egg_hatching); + const int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 60 * TICKS_PER_SECOND); + }, + {{end_egg_hatching_detector}} + ); + if (ret > 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect egg hatching ends.", + env.console + ); + } +} + +size_t EggAutonomous::talk_to_lady_to_fetch_egg( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats, + size_t num_eggs_retrieved +){ + env.log("Fetching egg"); + stats.m_fetch_attempts++; + env.update_stats(); + // collect_egg(context); + RetrieveEggArrowFinder egg_arrow_detector(env.console); + CheckNurseryArrowFinder no_egg_arrow_detector(env.console); + + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + for (size_t i_hatched = 0; i_hatched < 2; i_hatched++){ + pbf_press_button(context, BUTTON_A, 20, 150); + } + pbf_wait(context, 200); + }, + { + egg_arrow_detector, + no_egg_arrow_detector, + } + ); + + const bool y_comm_visible_at_end_of_dialog = true; + YCommIconDetector dialog_over_detector(y_comm_visible_at_end_of_dialog); + switch (ret){ + case 0: + ++num_eggs_retrieved; + env.log("Found egg"); + env.console.overlay().add_log("Found egg " + std::to_string(num_eggs_retrieved) + "/5", COLOR_WHITE); + stats.m_fetch_success++; + env.update_stats(); + // Press A to get the egg + ssf_press_button(context, BUTTON_A, 320ms, 160ms); + + ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 30s); + }, + {{dialog_over_detector}} + ); + break; + + case 1: + env.log("No egg"); + env.console.overlay().add_log("No egg", COLOR_WHITE); + run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 5s); + }, + {{dialog_over_detector}} + ); + return num_eggs_retrieved; +// break; + + default: + env.log("Daycare lady not found."); + env.console.overlay().add_log("No daycare lady", COLOR_WHITE); + return num_eggs_retrieved; +// OperationFailedException::fire( +// ErrorReport::SEND_ERROR_REPORT, +// "Cannot detect dialog selection arrow when talking to Nursery lady.", +// env.console +// ); + } + + // If dialog over is not detected: + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect end of Nursery lady dialog. No Y-Comm mark found.", + env.console + ); + } + + return num_eggs_retrieved; +} + +// After all five eggs hatched and another five eggs deposit into the first column of the box, +// call this function to: +// - Go to pokemon storage. +// - Check the hatched pokemon, keep shiny pokemon and those that match the stats requirements. Release the rest. +// - Retrieve the stored egg column to the party. +// - Call flying taxi to reset player location if needed +// Return true if the program should stop +bool EggAutonomous::process_hatched_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats, + bool need_taxi +){ + env.log("Checking hatched pokemon."); + env.console.overlay().add_log("Checking hatched pokemon", COLOR_WHITE); + + // Press X to open menu + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + + navigate_to_menu_app(env, env.console, context, POKEMON_APP_INDEX, NOTIFICATION_ERROR_RECOVERABLE); + + const Milliseconds BOX_CHANGE_DELAY = GameSettings::instance().BOX_CHANGE_DELAY0; + const Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + + // From menu enter Pokemon App + ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); + // From Pokemon App to storage box + ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, EGG_BUTTON_HOLD_DELAY); + // Move left down to the first hatched pokemon in the party + box_scroll(context, DPAD_LEFT); + box_scroll(context, DPAD_DOWN); + + context.wait_for_all_requests(); + { + // Define the scope of video overlay rendering for various checks: + VideoOverlaySet overlay_set(env.console.overlay()); + BoxShinySymbolDetector::make_overlays(overlay_set); + BoxGenderDetector gender_detector; + gender_detector.make_overlays(overlay_set); + IvJudgeReaderScope iv_reader(env.console.overlay(), LANGUAGE); + BoxNatureDetector nature_detector(env.console.overlay()); + + for (size_t i_hatched = 0; i_hatched < 5; i_hatched++){ + pbf_wait(context, 50); // wait for a while to make sure the pokemon stats are loaded. + context.wait_for_all_requests(); + auto screen = env.console.video().snapshot(); + + bool shiny = BoxShinySymbolDetector::detect(screen); + if (shiny){ + env.log("Pokemon " + std::to_string(i_hatched) + " is shiny!", COLOR_BLUE); + env.console.overlay().add_log("Pokemon " + std::to_string(i_hatched+1) + "/5 is shiny!", COLOR_YELLOW); + stats.m_shinies++; + env.update_stats(); + send_encounter_notification( + env, + m_notification_noop, + NOTIFICATION_SHINY, + false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), + screen + ); + }else{ + env.log("Pokemon " + std::to_string(i_hatched) + " is not shiny.", COLOR_PURPLE); + env.console.overlay().add_log("Pokemon " + std::to_string(i_hatched+1) + "/5 not shiny", COLOR_WHITE); + } + // Note: we assume the pokemon storage UI is in the state of judging pokemon stats. + // In this way we can detect pokemon stats. + + IvJudgeReader::Results IVs = iv_reader.read(env.console, screen); + StatsHuntGenderFilter gender = gender_detector.detect(screen); + env.log(IVs.to_string(), COLOR_GREEN); + env.log("Gender: " + gender_to_string(gender), COLOR_GREEN); + NatureReader::Results nature = nature_detector.read(env.console.logger(), screen); + + StatsHuntAction action = FILTERS0.get_action(shiny, gender, nature.nature, IVs); + + auto send_keep_notification = [&](){ + if (!shiny){ + send_encounter_notification( + env, + NOTIFICATION_NONSHINY_KEEP, + NOTIFICATION_SHINY, + false, false, {}, std::nan(""), + screen + ); + } + }; + switch (action){ + case StatsHuntAction::StopProgram: + env.log("Program stop requested..."); + env.console.overlay().add_log("Request program stop", COLOR_WHITE); + send_keep_notification(); + return true; + case StatsHuntAction::Keep: + env.log("Moving Pokemon to keep box...", COLOR_BLUE); + m_num_pokemon_kept++; + env.console.overlay().add_log("Keep pokemon " + std::to_string(m_num_pokemon_kept) + "/" + std::to_string(MAX_KEEPERS), COLOR_YELLOW); + send_keep_notification(); + + // Press A twice to pick the pokemon + ssf_press_button_ptv(context, BUTTON_A, 480ms, EGG_BUTTON_HOLD_DELAY); + ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); + + // Move it rightward, so that it stays on top of the box area + box_scroll(context, DPAD_RIGHT); + // Press Button L to change to the box on the left + ssf_press_button_ptv(context, BUTTON_L, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + + // Because we don't know which place in the box to place the pokemon, we will + // throw the pokemon in the all-box view. So it automatically sit in the first empty slot + // in the box: + + // Move it three times upward, so that it stays on top of the "Box List" button + box_scroll(context, DPAD_UP); + box_scroll(context, DPAD_UP); + box_scroll(context, DPAD_UP); + + // Press the button to go to box list view + ssf_press_button_ptv(context, BUTTON_A, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + // Press button A to drop the pokemon into the box + ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); + // Press button B to go back to the last box + ssf_press_button_ptv(context, BUTTON_B, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + // Press button R to change to the box on the right, the box with the next batch of eggs + ssf_press_button_ptv(context, BUTTON_R, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + // Move cursor left to point to the last slot in the party + box_scroll(context, DPAD_LEFT); + // Move cursor downward three times so that it goes to the original place (second slot in the party) + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_DOWN); + + if (m_num_pokemon_kept >= MAX_KEEPERS){ + env.log("Max keepers reached. Stopping program..."); + env.console.overlay().add_log("Max Keepers reached.", COLOR_WHITE); + return true; + } + break; + case StatsHuntAction::Discard: + env.log("Releasing Pokemon...", COLOR_PURPLE); + env.console.overlay().add_log("Release Pokemon", COLOR_WHITE); + + // ssf_press_button2(context, BUTTON_A, 60, 10); + // ssf_press_dpad2(context, DPAD_UP, BOX_SCROLL_DELAY, EGG_BUTTON_HOLD_DELAY); + // ssf_press_dpad2(context, DPAD_UP, BOX_SCROLL_DELAY, EGG_BUTTON_HOLD_DELAY); + // ssf_press_button2(context, BUTTON_A, 125, 10); + // ssf_press_dpad2(context, DPAD_UP, BOX_SCROLL_DELAY, EGG_BUTTON_HOLD_DELAY); + // pbf_mash_button(context, BUTTON_A, 180); + + // Press A to open pokemon menu + pbf_press_button(context, BUTTON_A, 20, 50); + context.wait_for_all_requests(); + StoragePokemonMenuArrowFinder pokemon_menu_detector(env.console.overlay()); + int ret = wait_until( + env.console, context, std::chrono::seconds(10), + {{pokemon_menu_detector}} + ); + if (ret != 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect pokemon menu in storage box.", + env.console + ); + } + + const bool stop_on_detected = true; + BlackDialogBoxDetector dialog_detector(stop_on_detected); + VideoOverlaySet dialog_overlay_set(env.console); + dialog_detector.make_overlays(dialog_overlay_set); + + // Move cursor upward two times to point to "Release" menu item + pbf_press_dpad(context, DPAD_UP, 20, 20); + pbf_press_dpad(context, DPAD_UP, 20, 20); + + // Press A to release + pbf_press_button(context, BUTTON_A, 20, 105); + // Move cursor from "Not release" to "release". + pbf_press_dpad(context, DPAD_UP, 20, 30); + // Press A to confirm release, wait for a while to let the next dialog box pop up. + pbf_press_button(context, BUTTON_A, 20, 200); + + context.wait_for_all_requests(); + ret = wait_until( + env.console, context, std::chrono::seconds(10), + {{dialog_detector}} + ); + if (ret != 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Miss second dialog when releasing pokemon.", + env.console + ); + } + pbf_press_button(context, BUTTON_A, 20, 100); + + size_t dialog_count = 0; + const size_t max_dialog_count = 6; + for (; dialog_count < max_dialog_count; dialog_count++){ + context.wait_for_all_requests(); + if (!dialog_detector.process_frame(env.console.video().snapshot(), current_time())){ + break; + } + pbf_press_button(context, BUTTON_A, 20, 100); + } + if (dialog_count == max_dialog_count){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unexpected dialogs when releasing pokemon.", + env.console + ); + } + break; + } + } + } + + // Get eggs to party: + + // Move cursor to the first slot in the box + box_scroll(context, DPAD_UP); + box_scroll(context, DPAD_RIGHT); + + // Press Y twice to change selection method to group selection + pbf_press_button(context, BUTTON_Y, EGG_BUTTON_HOLD_DELAY, 400ms); + pbf_press_button(context, BUTTON_Y, EGG_BUTTON_HOLD_DELAY, 400ms); + + // Press A to start selection + pbf_press_button(context, BUTTON_A, EGG_BUTTON_HOLD_DELAY, 400ms); + // Move down to selection the entire column + for (size_t c = 0; c < 4; c++){ + box_scroll(context, DPAD_DOWN); + } + // Press A to finish the selection + ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); + + // Move cursor to the second slot in the party + box_scroll(context, DPAD_LEFT); + box_scroll(context, DPAD_DOWN); + + // Press A to finish dropping the egg column + ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); + + // leave pokemon box, back to pokemon app + ssf_press_button(context, BUTTON_B, GameSettings::instance().BOX_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); + // Back out to menu. + ssf_press_button(context, BUTTON_B, GameSettings::instance().POKEMON_TO_MENU_DELAY0, EGG_BUTTON_HOLD_DELAY); + + if (need_taxi){ + bool fly_from_overworld = false; // fly from menu + call_flying_taxi(env, context, fly_from_overworld); + }else{ + // Leave menu, go back to overworld + const bool y_comm_visible = true; + YCommIconDetector y_comm_detector(y_comm_visible); + const int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 5000ms); + }, + {{y_comm_detector}} + ); + if (ret > 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect Y-Comm after leaving menu.", + env.console + ); + } + } + + return false; +} + +void EggAutonomous::mash_B_until_y_comm_icon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const std::string& error_msg +){ + context.wait_for_all_requests(); + const bool y_comm_visible = true; + YCommIconDetector y_comm_detector(y_comm_visible); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10s); + }, + {y_comm_detector} + ); + if (ret != 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + error_msg + " No Y-Comm mark found.", + env.console + ); + } +} + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.h index a4790bafac..766c7a15a4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggAutonomous.h @@ -1,151 +1,151 @@ -/* Egg Autonomous - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggAutonomous_H -#define PokemonAutomation_PokemonSwSh_EggAutonomous_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -// #include "PokemonSwSh/Options/PokemonSwSh_EggStepCount.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EggAutonomous_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggAutonomous_Descriptor(); - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class EggAutonomous : public SingleSwitchProgramInstance{ -public: - EggAutonomous(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - // Run one iteration of the egg loop: - // - Hatch five eggs while fetch five eggs. - // - Check if pokemon needs to be kept. Keep them if needed. - // - Put five eggs from storage to party. Save game if needed. - // Return true if the egg loop should stop. - bool run_batch( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats - ); - - void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - - // Call flying taxi to reset player character position to Nursery front door. - // fly_from_overworld: if true, the game is in the overworld while calling this function. If false, the game is in the menu. - // Note: the cursor in the menu must already be at Town Map. - void call_flying_taxi( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - bool fly_from_overworld - ); - - // After detecting egg hatching, call this function to wait entil the end of the hatching. - // num_hatched_eggs: how many eggs hatched (including the current hatching one) - void wait_for_egg_hatched( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats, - size_t num_hatched_eggs - ); - - // Call this function when standing in front of the lady to fetch one egg. - // Return updated `num_eggs_retrieved` to reflect change in fetched eggs. - size_t talk_to_lady_to_fetch_egg( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats, - size_t num_eggs_retrieved - ); - - // After all five eggs hatched and another five eggs deposit into the first column of the box, - // call this function to: - // - Go to pokemon storage. - // - Check the hatched pokemon, keep shiny pokemon and those that match the stats requirements. Release the rest. - // - Retrieve the stored egg column to the party. - // - Call flying taxi to reset player location if needed - // Return true if the program should stop - bool process_hatched_pokemon( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - EggAutonomous_Descriptor::Stats& stats, - bool need_taxi - ); - - // Used to wait until Y-Comm icon shows up. - // Throw error if it does not find it after 10 sec. - void mash_B_until_y_comm_icon( - SingleSwitchProgramEnvironment& env, - ProControllerContext& context, - const std::string& error_msg - ); - - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - // EggStepCountOption STEPS_TO_HATCH; - - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - - SimpleIntegerOption MAX_KEEPERS; - SimpleIntegerOption LOOPS_PER_FETCH; - IntegerEnumDropdownOption NUM_EGGS_IN_COLUMN; - - enum class AutoSave{ - NoAutoSave, - AfterStartAndKeep, - EveryBatch, - }; - EnumDropdownOption AUTO_SAVING; - - Pokemon::StatsHuntIvJudgeFilterTable FILTERS0; - - BooleanCheckBoxOption DEBUG_PROCESSING_HATCHED; - BooleanCheckBoxOption SAVE_DEBUG_VIDEO; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationOption NOTIFICATION_NONSHINY_KEEP; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationOption m_notification_noop; - EventNotificationsOption NOTIFICATIONS; - - // How many pokemon have been kept so far. These pokemon are shiny or met certain stats requirement. - size_t m_num_pokemon_kept = 0; - - // How many eggs have been placed behind a game save. - // This is used so that if we recover from an error, we know how many eggs are in storage. - size_t m_num_eggs_in_storage_when_game_saved = 0; - // How many eggs are already deposited to storage so far. - size_t m_num_eggs_retrieved = 0; - - // Is player's location at the bike loop start - bool m_player_at_loop_start = false; -}; - - -} -} -} -#endif +/* Egg Autonomous + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggAutonomous_H +#define PokemonAutomation_PokemonSwSh_EggAutonomous_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "Pokemon/Options/Pokemon_StatsHuntFilter.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +// #include "PokemonSwSh/Options/PokemonSwSh_EggStepCount.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EggAutonomous_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggAutonomous_Descriptor(); + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class EggAutonomous : public SingleSwitchProgramInstance{ +public: + EggAutonomous(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + // Run one iteration of the egg loop: + // - Hatch five eggs while fetch five eggs. + // - Check if pokemon needs to be kept. Keep them if needed. + // - Put five eggs from storage to party. Save game if needed. + // Return true if the egg loop should stop. + bool run_batch( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats + ); + + void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + + // Call flying taxi to reset player character position to Nursery front door. + // fly_from_overworld: if true, the game is in the overworld while calling this function. If false, the game is in the menu. + // Note: the cursor in the menu must already be at Town Map. + void call_flying_taxi( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + bool fly_from_overworld + ); + + // After detecting egg hatching, call this function to wait entil the end of the hatching. + // num_hatched_eggs: how many eggs hatched (including the current hatching one) + void wait_for_egg_hatched( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats, + size_t num_hatched_eggs + ); + + // Call this function when standing in front of the lady to fetch one egg. + // Return updated `num_eggs_retrieved` to reflect change in fetched eggs. + size_t talk_to_lady_to_fetch_egg( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats, + size_t num_eggs_retrieved + ); + + // After all five eggs hatched and another five eggs deposit into the first column of the box, + // call this function to: + // - Go to pokemon storage. + // - Check the hatched pokemon, keep shiny pokemon and those that match the stats requirements. Release the rest. + // - Retrieve the stored egg column to the party. + // - Call flying taxi to reset player location if needed + // Return true if the program should stop + bool process_hatched_pokemon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + EggAutonomous_Descriptor::Stats& stats, + bool need_taxi + ); + + // Used to wait until Y-Comm icon shows up. + // Throw error if it does not find it after 10 sec. + void mash_B_until_y_comm_icon( + SingleSwitchProgramEnvironment& env, + ProControllerContext& context, + const std::string& error_msg + ); + + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + // EggStepCountOption STEPS_TO_HATCH; + + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + + SimpleIntegerOption MAX_KEEPERS; + SimpleIntegerOption LOOPS_PER_FETCH; + IntegerEnumDropdownOption NUM_EGGS_IN_COLUMN; + + enum class AutoSave{ + NoAutoSave, + AfterStartAndKeep, + EveryBatch, + }; + EnumDropdownOption AUTO_SAVING; + + Pokemon::StatsHuntIvJudgeFilterTable FILTERS0; + + BooleanCheckBoxOption DEBUG_PROCESSING_HATCHED; + BooleanCheckBoxOption SAVE_DEBUG_VIDEO; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationOption NOTIFICATION_NONSHINY_KEEP; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationOption m_notification_noop; + EventNotificationsOption NOTIFICATIONS; + + // How many pokemon have been kept so far. These pokemon are shiny or met certain stats requirement. + size_t m_num_pokemon_kept = 0; + + // How many eggs have been placed behind a game save. + // This is used so that if we recover from an error, we know how many eggs are in storage. + size_t m_num_eggs_in_storage_when_game_saved = 0; + // How many eggs are already deposited to storage so far. + size_t m_num_eggs_retrieved = 0; + + // Is player's location at the bike loop start + bool m_player_at_loop_start = false; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp index 863f505efa..b5d54b421f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.cpp @@ -1,108 +1,108 @@ -/* Egg Combined 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_EggCombinedShared.h" -#include "PokemonSwSh_EggCombined2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -EggCombined2_Descriptor::EggCombined2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EggCombined2", - STRING_POKEMON + " SwSh", "Egg Combined 2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggCombined2.md", - "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -EggCombined2::EggCombined2() - : BOXES_TO_HATCH( - "Boxes to Hatch:", - LockMode::LOCK_WHILE_RUNNING, - 32, 0, 32 - ) - , FETCHES_PER_BATCH( - "Fetches per Batch:
For each batch of eggs, attempt this many egg fetches.", - LockMode::LOCK_WHILE_RUNNING, - 6.0, 0, 7 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SAFETY_TIME0( - "Safety Time:
Additional time added to the spinning.", - LockMode::LOCK_WHILE_RUNNING, - "12 s" - ) - , EARLY_HATCH_SAFETY0( - "Early Hatch Safety:
Eggs will not hatch early by more than this period.", - LockMode::LOCK_WHILE_RUNNING, - "5 s" - ) - , HATCH_DELAY0( - "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", - LockMode::LOCK_WHILE_RUNNING, - "88 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(BOXES_TO_HATCH); - PA_ADD_OPTION(STEPS_TO_HATCH); - PA_ADD_OPTION(FETCHES_PER_BATCH); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SAFETY_TIME0); - PA_ADD_OPTION(EARLY_HATCH_SAFETY0); - PA_ADD_OPTION(HATCH_DELAY0); -} - -void EggCombined2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - EggCombinedSession session{ - BOXES_TO_HATCH, - STEPS_TO_HATCH, - (float)FETCHES_PER_BATCH, - SAFETY_TIME0, - EARLY_HATCH_SAFETY0, - HATCH_DELAY0, - TOUCH_DATE_INTERVAL - }; - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - session.eggcombined2_body(env.console, context); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} - +/* Egg Combined 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_EggCombinedShared.h" +#include "PokemonSwSh_EggCombined2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +EggCombined2_Descriptor::EggCombined2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EggCombined2", + STRING_POKEMON + " SwSh", "Egg Combined 2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggCombined2.md", + "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +EggCombined2::EggCombined2() + : BOXES_TO_HATCH( + "Boxes to Hatch:", + LockMode::LOCK_WHILE_RUNNING, + 32, 0, 32 + ) + , FETCHES_PER_BATCH( + "Fetches per Batch:
For each batch of eggs, attempt this many egg fetches.", + LockMode::LOCK_WHILE_RUNNING, + 6.0, 0, 7 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SAFETY_TIME0( + "Safety Time:
Additional time added to the spinning.", + LockMode::LOCK_WHILE_RUNNING, + "12 s" + ) + , EARLY_HATCH_SAFETY0( + "Early Hatch Safety:
Eggs will not hatch early by more than this period.", + LockMode::LOCK_WHILE_RUNNING, + "5 s" + ) + , HATCH_DELAY0( + "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", + LockMode::LOCK_WHILE_RUNNING, + "88 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(BOXES_TO_HATCH); + PA_ADD_OPTION(STEPS_TO_HATCH); + PA_ADD_OPTION(FETCHES_PER_BATCH); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SAFETY_TIME0); + PA_ADD_OPTION(EARLY_HATCH_SAFETY0); + PA_ADD_OPTION(HATCH_DELAY0); +} + +void EggCombined2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + EggCombinedSession session{ + BOXES_TO_HATCH, + STEPS_TO_HATCH, + (float)FETCHES_PER_BATCH, + SAFETY_TIME0, + EARLY_HATCH_SAFETY0, + HATCH_DELAY0, + TOUCH_DATE_INTERVAL + }; + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + session.eggcombined2_body(env.console, context); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.h index b67014bd33..969a0bf5d0 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombined2.h @@ -1,58 +1,58 @@ -/* Egg Combined 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggCombined2_H -#define PokemonAutomation_PokemonSwSh_EggCombined2_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EggStepOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EggCombined2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggCombined2_Descriptor(); -}; - - - -class EggCombined2 : public SingleSwitchProgramInstance{ -public: - EggCombined2(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - SimpleIntegerOption BOXES_TO_HATCH; - EggStepCountOption STEPS_TO_HATCH; - FloatingPointOption FETCHES_PER_BATCH; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption SAFETY_TIME0; - MillisecondsOption EARLY_HATCH_SAFETY0; - MillisecondsOption HATCH_DELAY0; -}; - - -} -} -} -#endif +/* Egg Combined 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggCombined2_H +#define PokemonAutomation_PokemonSwSh_EggCombined2_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EggStepOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EggCombined2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggCombined2_Descriptor(); +}; + + + +class EggCombined2 : public SingleSwitchProgramInstance{ +public: + EggCombined2(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + SimpleIntegerOption BOXES_TO_HATCH; + EggStepCountOption STEPS_TO_HATCH; + FloatingPointOption FETCHES_PER_BATCH; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption SAFETY_TIME0; + MillisecondsOption EARLY_HATCH_SAFETY0; + MillisecondsOption HATCH_DELAY0; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombinedShared.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombinedShared.h index b5c62e2e4f..4d515aed20 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombinedShared.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggCombinedShared.h @@ -1,272 +1,272 @@ -/* Egg Combined Shared Libraries - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggCombinedShared_H -#define PokemonAutomation_PokemonSwSh_EggCombinedShared_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh_EggHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -typedef struct{ - uint8_t fetches; - Milliseconds spin_duration; - Milliseconds total_duration; -} EggCombinedBlock; - -struct EggCombinedSession{ - uint8_t BOXES_TO_HATCH; - uint16_t STEPS_TO_HATCH; - float FETCHES_PER_BATCH; - Milliseconds SAFETY_TIME; - Milliseconds EARLY_HATCH_SAFETY; - Milliseconds HATCH_DELAY; - TouchDateIntervalOption& TOUCH_DATE_INTERVAL; - - EggCombinedBlock sanitize_fetch_count(uint8_t desired_fetches, Milliseconds duration){ - // The amount of time during egg-fetches that counts towards incubation. - const Milliseconds FETCH_TRAVEL_TIME = TRAVEL_RIGHT_DURATION + GO_TO_LADY_DURATION; - - EggCombinedBlock block; - - // Cap the # of fetches to 7 because things can ugly at larger values. - block.fetches = desired_fetches; - if (desired_fetches == 0){ - block.spin_duration = 0ms; - block.total_duration = TRAVEL_RIGHT_DURATION; - return block; - } - if (block.fetches > 7){ - block.fetches = 7; - } - - // Divide the incubation time by the # of fetches. But don't let the fetch - // interval drop below the FETCH_TRAVEL_TIME. - block.total_duration = duration / block.fetches; - if (block.total_duration >= FETCH_TRAVEL_TIME){ - block.spin_duration = block.total_duration - FETCH_TRAVEL_TIME; - }else{ - block.fetches = (uint8_t)(duration / FETCH_TRAVEL_TIME); - block.spin_duration = 0ms; - block.total_duration = block.fetches == 0 - ? TRAVEL_RIGHT_DURATION - : FETCH_TRAVEL_TIME; - } - - return block; - } - void withdraw_column_shiftR(ProControllerContext& context, uint8_t column){ - menu_to_box(context, false); - party_to_column(context, column); - pickup_column(context, false); - ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0, EGG_BUTTON_HOLD_DELAY); - column_to_party(context, column); - ssf_press_button(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0, EGG_BUTTON_HOLD_DELAY); - box_to_menu(context); - } - void deposit_column_shiftL(ProControllerContext& context, uint8_t column){ - menu_to_box(context, true); - pickup_column(context, true); - party_to_column(context, column); - ssf_press_button(context, BUTTON_L, GameSettings::instance().BOX_CHANGE_DELAY0, EGG_BUTTON_HOLD_DELAY); - ssf_press_button(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0, EGG_BUTTON_HOLD_DELAY); - box_to_menu(context); - } - uint8_t swap_party_shift(ProControllerContext& context, uint8_t column){ - menu_to_box(context, true); - pickup_column(context, true); - - Milliseconds BOX_CHANGE_DELAY = GameSettings::instance().BOX_CHANGE_DELAY0; - Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - - // Move to column. - party_to_column(context, column); - ssf_press_button(context, BUTTON_L, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - ssf_press_button(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); - - // Move to next column. - column++; - if (column < 6){ - box_scroll(context, DPAD_RIGHT); - }else{ - column = 0; - ssf_press_button(context, BUTTON_R, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - box_scroll(context, DPAD_RIGHT); - box_scroll(context, DPAD_RIGHT); - } - - pickup_column(context, false); - - // Move to party. - ssf_press_button(context, BUTTON_R, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); - column_to_party(context, column); - ssf_press_button(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); - - // Return to menu. - box_to_menu(context); - - return column; - } - -#define TRAVEL_TO_SPIN_SPOT_DURATION (300 * 8ms) -//#define TRAVEL_BACK_TO_LADY_DURATION (30 + 260 + (580) + 120 + 120 * 0) -#define TRAVEL_BACK_TO_LADY_DURATION ((30 + 260 + (620) + 120 + 120 * 0) * 8ms) - - void eggcombined2_run_batch( - ProControllerContext& context, - Milliseconds INCUBATION_DELAY_LOWER, - Milliseconds remaining_travel_duration, - uint8_t column, - uint8_t fetches, - bool last_batch - ){ - const Milliseconds MIN_TRAVEL_TIME = TRAVEL_TO_SPIN_SPOT_DURATION + TRAVEL_BACK_TO_LADY_DURATION; - - // Trim off TRAVEL_TO_SPIN_SPOT_DURATION for the last iteration. - Milliseconds loop_incubation = INCUBATION_DELAY_LOWER < TRAVEL_TO_SPIN_SPOT_DURATION - ? 0ms - : INCUBATION_DELAY_LOWER - TRAVEL_TO_SPIN_SPOT_DURATION; - - while (fetches > 1 && loop_incubation >= MIN_TRAVEL_TIME){ - Milliseconds period = loop_incubation / (fetches - 1); - Milliseconds spin = 0ms; - if (period >= MIN_TRAVEL_TIME){ - spin = period - MIN_TRAVEL_TIME; - spin = spin / 1024 * 1024; - } - - collect_egg(context); - collect_egg_mash_out(context, GameSettings::instance().AUTO_DEPOSIT); - - travel_to_spin_location(context); - spin_and_mash_A(context, spin); - travel_back_to_lady(context); - - fetches--; - loop_incubation -= MIN_TRAVEL_TIME + spin; - remaining_travel_duration -= MIN_TRAVEL_TIME + spin; - } - - // Last fetch. - if (fetches > 0){ - collect_egg(context); - collect_egg_mash_out(context, GameSettings::instance().AUTO_DEPOSIT); - fetches--; - } - travel_to_spin_location(context); - - // Hatch eggs. - if (remaining_travel_duration >= END_BATCH_MASH_B_DURATION){ - spin_and_mash_A(context, remaining_travel_duration - END_BATCH_MASH_B_DURATION); - pbf_mash_button(context, BUTTON_B, END_BATCH_MASH_B_DURATION); - }else{ - spin_and_mash_A(context, remaining_travel_duration); - } - - if (fetches == 0){ - // Swap party. - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - if (last_batch){ - deposit_column_shiftL(context, column); - ssf_press_button(context, BUTTON_B, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0, 160ms); - }else{ - swap_party_shift(context, column); - fly_home_goto_lady(context, false); - } - return; - } - - // Additional fetches. - fly_home_goto_lady(context, true); - while (fetches-- > 0){ - collect_egg(context); - collect_egg_mash_out(context, GameSettings::instance().AUTO_DEPOSIT); - eggfetcher_loop(context); - } - - // Swap party. - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - if (last_batch){ - deposit_column_shiftL(context, column); - }else{ - swap_party_shift(context, column); - } - ssf_press_button(context, BUTTON_B, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0, 160ms); - } - - void eggcombined2_body(ConsoleHandle& console, ProControllerContext& context){ - if (BOXES_TO_HATCH == 0){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - return; - } - - // Calculate lower/upper bounds for incubation time. - const Milliseconds INCUBATION_DELAY_UPPER = (uint16_t)((uint32_t)STEPS_TO_HATCH * 2 * (uint32_t)103180 >> 16) * 8ms; - const Milliseconds INCUBATION_DELAY_LOWER = INCUBATION_DELAY_UPPER >= EARLY_HATCH_SAFETY - ? INCUBATION_DELAY_UPPER - EARLY_HATCH_SAFETY - : 0ms; - - const Milliseconds FINISH_DELAY = HATCH_DELAY + SAFETY_TIME; - - float fetches_per_batch = FETCHES_PER_BATCH; - if (fetches_per_batch < 0){ - fetches_per_batch = 0; - } - - float fetch_residual = 0; - - // Withdraw party. - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - withdraw_column_shiftR(context, 0); - fly_home_goto_lady(context, false); - - for (uint8_t box = 0; box < BOXES_TO_HATCH; box++){ - for (uint8_t column = 0; column < 6; column++){ - // Touch the date. - if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ - console.log("Touching date to prevent rollover."); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - - fetch_residual += fetches_per_batch; - uint8_t fetches = (uint8_t)fetch_residual; - eggcombined2_run_batch( - context, - INCUBATION_DELAY_LOWER, - INCUBATION_DELAY_UPPER + FINISH_DELAY, - column, - fetches, - box == BOXES_TO_HATCH - 1 && column == 5 - ); - fetch_residual -= (float)fetches; - } - } - - // Finish - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - } - -}; - - - -} -} -} -#endif - +/* Egg Combined Shared Libraries + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggCombinedShared_H +#define PokemonAutomation_PokemonSwSh_EggCombinedShared_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh_EggHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +typedef struct{ + uint8_t fetches; + Milliseconds spin_duration; + Milliseconds total_duration; +} EggCombinedBlock; + +struct EggCombinedSession{ + uint8_t BOXES_TO_HATCH; + uint16_t STEPS_TO_HATCH; + float FETCHES_PER_BATCH; + Milliseconds SAFETY_TIME; + Milliseconds EARLY_HATCH_SAFETY; + Milliseconds HATCH_DELAY; + TouchDateIntervalOption& TOUCH_DATE_INTERVAL; + + EggCombinedBlock sanitize_fetch_count(uint8_t desired_fetches, Milliseconds duration){ + // The amount of time during egg-fetches that counts towards incubation. + const Milliseconds FETCH_TRAVEL_TIME = TRAVEL_RIGHT_DURATION + GO_TO_LADY_DURATION; + + EggCombinedBlock block; + + // Cap the # of fetches to 7 because things can ugly at larger values. + block.fetches = desired_fetches; + if (desired_fetches == 0){ + block.spin_duration = 0ms; + block.total_duration = TRAVEL_RIGHT_DURATION; + return block; + } + if (block.fetches > 7){ + block.fetches = 7; + } + + // Divide the incubation time by the # of fetches. But don't let the fetch + // interval drop below the FETCH_TRAVEL_TIME. + block.total_duration = duration / block.fetches; + if (block.total_duration >= FETCH_TRAVEL_TIME){ + block.spin_duration = block.total_duration - FETCH_TRAVEL_TIME; + }else{ + block.fetches = (uint8_t)(duration / FETCH_TRAVEL_TIME); + block.spin_duration = 0ms; + block.total_duration = block.fetches == 0 + ? TRAVEL_RIGHT_DURATION + : FETCH_TRAVEL_TIME; + } + + return block; + } + void withdraw_column_shiftR(ProControllerContext& context, uint8_t column){ + menu_to_box(context, false); + party_to_column(context, column); + pickup_column(context, false); + ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0, EGG_BUTTON_HOLD_DELAY); + column_to_party(context, column); + ssf_press_button(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0, EGG_BUTTON_HOLD_DELAY); + box_to_menu(context); + } + void deposit_column_shiftL(ProControllerContext& context, uint8_t column){ + menu_to_box(context, true); + pickup_column(context, true); + party_to_column(context, column); + ssf_press_button(context, BUTTON_L, GameSettings::instance().BOX_CHANGE_DELAY0, EGG_BUTTON_HOLD_DELAY); + ssf_press_button(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0, EGG_BUTTON_HOLD_DELAY); + box_to_menu(context); + } + uint8_t swap_party_shift(ProControllerContext& context, uint8_t column){ + menu_to_box(context, true); + pickup_column(context, true); + + Milliseconds BOX_CHANGE_DELAY = GameSettings::instance().BOX_CHANGE_DELAY0; + Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + + // Move to column. + party_to_column(context, column); + ssf_press_button(context, BUTTON_L, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + ssf_press_button(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); + + // Move to next column. + column++; + if (column < 6){ + box_scroll(context, DPAD_RIGHT); + }else{ + column = 0; + ssf_press_button(context, BUTTON_R, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + box_scroll(context, DPAD_RIGHT); + box_scroll(context, DPAD_RIGHT); + } + + pickup_column(context, false); + + // Move to party. + ssf_press_button(context, BUTTON_R, BOX_CHANGE_DELAY, EGG_BUTTON_HOLD_DELAY); + column_to_party(context, column); + ssf_press_button(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, EGG_BUTTON_HOLD_DELAY); + + // Return to menu. + box_to_menu(context); + + return column; + } + +#define TRAVEL_TO_SPIN_SPOT_DURATION (300 * 8ms) +//#define TRAVEL_BACK_TO_LADY_DURATION (30 + 260 + (580) + 120 + 120 * 0) +#define TRAVEL_BACK_TO_LADY_DURATION ((30 + 260 + (620) + 120 + 120 * 0) * 8ms) + + void eggcombined2_run_batch( + ProControllerContext& context, + Milliseconds INCUBATION_DELAY_LOWER, + Milliseconds remaining_travel_duration, + uint8_t column, + uint8_t fetches, + bool last_batch + ){ + const Milliseconds MIN_TRAVEL_TIME = TRAVEL_TO_SPIN_SPOT_DURATION + TRAVEL_BACK_TO_LADY_DURATION; + + // Trim off TRAVEL_TO_SPIN_SPOT_DURATION for the last iteration. + Milliseconds loop_incubation = INCUBATION_DELAY_LOWER < TRAVEL_TO_SPIN_SPOT_DURATION + ? 0ms + : INCUBATION_DELAY_LOWER - TRAVEL_TO_SPIN_SPOT_DURATION; + + while (fetches > 1 && loop_incubation >= MIN_TRAVEL_TIME){ + Milliseconds period = loop_incubation / (fetches - 1); + Milliseconds spin = 0ms; + if (period >= MIN_TRAVEL_TIME){ + spin = period - MIN_TRAVEL_TIME; + spin = spin / 1024 * 1024; + } + + collect_egg(context); + collect_egg_mash_out(context, GameSettings::instance().AUTO_DEPOSIT); + + travel_to_spin_location(context); + spin_and_mash_A(context, spin); + travel_back_to_lady(context); + + fetches--; + loop_incubation -= MIN_TRAVEL_TIME + spin; + remaining_travel_duration -= MIN_TRAVEL_TIME + spin; + } + + // Last fetch. + if (fetches > 0){ + collect_egg(context); + collect_egg_mash_out(context, GameSettings::instance().AUTO_DEPOSIT); + fetches--; + } + travel_to_spin_location(context); + + // Hatch eggs. + if (remaining_travel_duration >= END_BATCH_MASH_B_DURATION){ + spin_and_mash_A(context, remaining_travel_duration - END_BATCH_MASH_B_DURATION); + pbf_mash_button(context, BUTTON_B, END_BATCH_MASH_B_DURATION); + }else{ + spin_and_mash_A(context, remaining_travel_duration); + } + + if (fetches == 0){ + // Swap party. + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + if (last_batch){ + deposit_column_shiftL(context, column); + ssf_press_button(context, BUTTON_B, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0, 160ms); + }else{ + swap_party_shift(context, column); + fly_home_goto_lady(context, false); + } + return; + } + + // Additional fetches. + fly_home_goto_lady(context, true); + while (fetches-- > 0){ + collect_egg(context); + collect_egg_mash_out(context, GameSettings::instance().AUTO_DEPOSIT); + eggfetcher_loop(context); + } + + // Swap party. + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + if (last_batch){ + deposit_column_shiftL(context, column); + }else{ + swap_party_shift(context, column); + } + ssf_press_button(context, BUTTON_B, GameSettings::instance().MENU_TO_OVERWORLD_DELAY0, 160ms); + } + + void eggcombined2_body(ConsoleHandle& console, ProControllerContext& context){ + if (BOXES_TO_HATCH == 0){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + return; + } + + // Calculate lower/upper bounds for incubation time. + const Milliseconds INCUBATION_DELAY_UPPER = (uint16_t)((uint32_t)STEPS_TO_HATCH * 2 * (uint32_t)103180 >> 16) * 8ms; + const Milliseconds INCUBATION_DELAY_LOWER = INCUBATION_DELAY_UPPER >= EARLY_HATCH_SAFETY + ? INCUBATION_DELAY_UPPER - EARLY_HATCH_SAFETY + : 0ms; + + const Milliseconds FINISH_DELAY = HATCH_DELAY + SAFETY_TIME; + + float fetches_per_batch = FETCHES_PER_BATCH; + if (fetches_per_batch < 0){ + fetches_per_batch = 0; + } + + float fetch_residual = 0; + + // Withdraw party. + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + withdraw_column_shiftR(context, 0); + fly_home_goto_lady(context, false); + + for (uint8_t box = 0; box < BOXES_TO_HATCH; box++){ + for (uint8_t column = 0; column < 6; column++){ + // Touch the date. + if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ + console.log("Touching date to prevent rollover."); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + + fetch_residual += fetches_per_batch; + uint8_t fetches = (uint8_t)fetch_residual; + eggcombined2_run_batch( + context, + INCUBATION_DELAY_LOWER, + INCUBATION_DELAY_UPPER + FINISH_DELAY, + column, + fetches, + box == BOXES_TO_HATCH - 1 && column == 5 + ); + fetch_residual -= (float)fetches; + } + } + + // Finish + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + } + +}; + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.cpp index 1a0a675847..4a11600621 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.cpp @@ -1,103 +1,103 @@ -/* Egg Fetcher 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_EggHelpers.h" -#include "PokemonSwSh_EggFetcher2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -EggFetcher2_Descriptor::EggFetcher2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EggFetcher2", - STRING_POKEMON + " SwSh", "Egg Fetcher 2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggFetcher2.md", - "Fetch eggs without hatching them.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -EggFetcher2::EggFetcher2() - : MAX_FETCH_ATTEMPTS( - "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", - LockMode::LOCK_WHILE_RUNNING, - 2000 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void EggFetcher2::run_eggfetcher( - Logger& logger, ProControllerContext& context, - bool deposit_automatically, - uint16_t attempts -) const{ - if (attempts == 0){ - return; - } - - uint16_t c = 0; - - // 1st Fetch: Get into position. - { - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - fly_home_collect_egg(context, true); - collect_egg_mash_out(context, deposit_automatically); - - c++; - if (c >= attempts){ - return; - } - } - - // Now we are in steady state. - for (; c < attempts; c++){ - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - eggfetcher_loop(context); - collect_egg(context); - collect_egg_mash_out(context, deposit_automatically); - } -} - -void EggFetcher2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - run_eggfetcher(env.console, context, GameSettings::instance().AUTO_DEPOSIT, MAX_FETCH_ATTEMPTS); - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* Egg Fetcher 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_EggHelpers.h" +#include "PokemonSwSh_EggFetcher2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +EggFetcher2_Descriptor::EggFetcher2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EggFetcher2", + STRING_POKEMON + " SwSh", "Egg Fetcher 2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggFetcher2.md", + "Fetch eggs without hatching them.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +EggFetcher2::EggFetcher2() + : MAX_FETCH_ATTEMPTS( + "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", + LockMode::LOCK_WHILE_RUNNING, + 2000 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void EggFetcher2::run_eggfetcher( + Logger& logger, ProControllerContext& context, + bool deposit_automatically, + uint16_t attempts +) const{ + if (attempts == 0){ + return; + } + + uint16_t c = 0; + + // 1st Fetch: Get into position. + { + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + fly_home_collect_egg(context, true); + collect_egg_mash_out(context, deposit_automatically); + + c++; + if (c >= attempts){ + return; + } + } + + // Now we are in steady state. + for (; c < attempts; c++){ + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + eggfetcher_loop(context); + collect_egg(context); + collect_egg_mash_out(context, deposit_automatically); + } +} + +void EggFetcher2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + run_eggfetcher(env.console, context, GameSettings::instance().AUTO_DEPOSIT, MAX_FETCH_ATTEMPTS); + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.h index 56ffa28af0..ecf23d36fe 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcher2.h @@ -1,47 +1,47 @@ -/* Egg Fetcher 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggFetcher2_H -#define PokemonAutomation_PokemonSwSh_EggFetcher2_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "PokemonSwSh_EggHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EggFetcher2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggFetcher2_Descriptor(); -}; - - - -class EggFetcher2 : public SingleSwitchProgramInstance{ -public: - EggFetcher2(); - - void run_eggfetcher(Logger& logger, ProControllerContext& context, bool deposit_automatically, uint16_t attempts) const; - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption MAX_FETCH_ATTEMPTS; - - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Egg Fetcher 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggFetcher2_H +#define PokemonAutomation_PokemonSwSh_EggFetcher2_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "PokemonSwSh_EggHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EggFetcher2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggFetcher2_Descriptor(); +}; + + + +class EggFetcher2 : public SingleSwitchProgramInstance{ +public: + EggFetcher2(); + + void run_eggfetcher(Logger& logger, ProControllerContext& context, bool deposit_automatically, uint16_t attempts) const; + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption MAX_FETCH_ATTEMPTS; + + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.cpp index 2f13d0580f..abd582b093 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.cpp @@ -1,159 +1,159 @@ -/* Egg Fetcher Multiple - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_EggHelpers.h" -#include "PokemonSwSh_EggFetcherMultiple.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -std::tuple get_location(uint16_t index){ - uint16_t box = index / 30; - index = index % 30; - - uint16_t row = index / 6; - index = index % 6; - - uint16_t column = index; - return { box, row, column }; -} - -EggFetcherMultiple_Descriptor::EggFetcherMultiple_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EggFetcherMultiple", - STRING_POKEMON + " SwSh", "Egg Fetcher Multiple", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggFetcherMultiple.md", - "Fetch eggs from multiple species without hatching them.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -EggFetcherMultiple::EggFetcherMultiple() - : POKEMON_SPECIES_COUNT( - "Breed this many species:", - LockMode::LOCK_WHILE_RUNNING, - 30 - ) - , MAX_FETCH_ATTEMPTS_PER_SPECIES( - "Fetch this many times per species:", - LockMode::LOCK_WHILE_RUNNING, - 10 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(POKEMON_SPECIES_COUNT); - PA_ADD_OPTION(MAX_FETCH_ATTEMPTS_PER_SPECIES); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void EggFetcherMultiple::run_eggfetcher( - Logger& logger, ProControllerContext& context, - bool deposit_automatically, - uint16_t attempts -) const{ - if (attempts == 0){ - return; - } - - uint16_t c = 0; - - // 1st Fetch: Get into position. - { - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - fly_home_collect_egg(context, true); - collect_egg_mash_out(context, deposit_automatically); - - c++; - if (c >= attempts){ - return; - } - } - - // Now we are in steady state. - for (; c < attempts; c++){ - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - eggfetcher_loop(context); - collect_egg(context); - collect_egg_mash_out(context, deposit_automatically); - } -} - -void EggFetcherMultiple::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - for (uint16_t s = 0; s < POKEMON_SPECIES_COUNT; ++s){ - fly_home_collect_egg(context, true); - - //remove the second pokemon from the daycare - pbf_press_button(context, BUTTON_A , 160ms, 1500ms); - pbf_press_button(context, BUTTON_A , 160ms, 1500ms); - pbf_press_button(context, BUTTON_A , 160ms, 1000ms); - pbf_press_dpad (context, DPAD_DOWN, 160ms, 1000ms); - pbf_press_button(context, BUTTON_A , 160ms, 1000ms); - pbf_mash_button (context, BUTTON_B , 5000ms); - - //add a new second pokemon from the daycare - pbf_press_button(context, BUTTON_A, 160ms, 1000ms); - pbf_press_button(context, BUTTON_A, 160ms, 1000ms); - pbf_press_button(context, BUTTON_A, 160ms, 1500ms); - pbf_press_button(context, BUTTON_A, 160ms, 2000ms); - auto [box, row, column] = get_location(s); - if (row == 0 && column == 0 && box != 0){ - box = 1; - }else{ - box = 0; - } - for (uint16_t b = 0; b < box; ++b){ - pbf_press_button(context, BUTTON_R, 160ms, 1000ms); - } - for (uint16_t r = 0; r < row; ++r){ - pbf_press_dpad(context, DPAD_DOWN, 160ms, 1000ms); - } - for (uint16_t c = 0; c < column; ++c){ - pbf_press_dpad(context, DPAD_RIGHT, 160ms, 1000ms); - } - pbf_press_button(context, BUTTON_A, 160ms, 1000ms); - pbf_press_button(context, BUTTON_A, 160ms, 2000ms); - pbf_press_button(context, BUTTON_A, 160ms, 1000ms); - pbf_press_button(context, BUTTON_A, 160ms, 5000ms); - pbf_press_button(context, BUTTON_A, 160ms, 1000ms); - pbf_press_button(context, BUTTON_A, 160ms, 1000ms); - - run_eggfetcher(env.console, context, GameSettings::instance().AUTO_DEPOSIT, MAX_FETCH_ATTEMPTS_PER_SPECIES); - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* Egg Fetcher Multiple + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_EggHelpers.h" +#include "PokemonSwSh_EggFetcherMultiple.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +std::tuple get_location(uint16_t index){ + uint16_t box = index / 30; + index = index % 30; + + uint16_t row = index / 6; + index = index % 6; + + uint16_t column = index; + return { box, row, column }; +} + +EggFetcherMultiple_Descriptor::EggFetcherMultiple_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EggFetcherMultiple", + STRING_POKEMON + " SwSh", "Egg Fetcher Multiple", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggFetcherMultiple.md", + "Fetch eggs from multiple species without hatching them.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +EggFetcherMultiple::EggFetcherMultiple() + : POKEMON_SPECIES_COUNT( + "Breed this many species:", + LockMode::LOCK_WHILE_RUNNING, + 30 + ) + , MAX_FETCH_ATTEMPTS_PER_SPECIES( + "Fetch this many times per species:", + LockMode::LOCK_WHILE_RUNNING, + 10 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(POKEMON_SPECIES_COUNT); + PA_ADD_OPTION(MAX_FETCH_ATTEMPTS_PER_SPECIES); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void EggFetcherMultiple::run_eggfetcher( + Logger& logger, ProControllerContext& context, + bool deposit_automatically, + uint16_t attempts +) const{ + if (attempts == 0){ + return; + } + + uint16_t c = 0; + + // 1st Fetch: Get into position. + { + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + fly_home_collect_egg(context, true); + collect_egg_mash_out(context, deposit_automatically); + + c++; + if (c >= attempts){ + return; + } + } + + // Now we are in steady state. + for (; c < attempts; c++){ + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + eggfetcher_loop(context); + collect_egg(context); + collect_egg_mash_out(context, deposit_automatically); + } +} + +void EggFetcherMultiple::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + for (uint16_t s = 0; s < POKEMON_SPECIES_COUNT; ++s){ + fly_home_collect_egg(context, true); + + //remove the second pokemon from the daycare + pbf_press_button(context, BUTTON_A , 160ms, 1500ms); + pbf_press_button(context, BUTTON_A , 160ms, 1500ms); + pbf_press_button(context, BUTTON_A , 160ms, 1000ms); + pbf_press_dpad (context, DPAD_DOWN, 160ms, 1000ms); + pbf_press_button(context, BUTTON_A , 160ms, 1000ms); + pbf_mash_button (context, BUTTON_B , 5000ms); + + //add a new second pokemon from the daycare + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + pbf_press_button(context, BUTTON_A, 160ms, 1500ms); + pbf_press_button(context, BUTTON_A, 160ms, 2000ms); + auto [box, row, column] = get_location(s); + if (row == 0 && column == 0 && box != 0){ + box = 1; + }else{ + box = 0; + } + for (uint16_t b = 0; b < box; ++b){ + pbf_press_button(context, BUTTON_R, 160ms, 1000ms); + } + for (uint16_t r = 0; r < row; ++r){ + pbf_press_dpad(context, DPAD_DOWN, 160ms, 1000ms); + } + for (uint16_t c = 0; c < column; ++c){ + pbf_press_dpad(context, DPAD_RIGHT, 160ms, 1000ms); + } + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + pbf_press_button(context, BUTTON_A, 160ms, 2000ms); + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + pbf_press_button(context, BUTTON_A, 160ms, 5000ms); + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + pbf_press_button(context, BUTTON_A, 160ms, 1000ms); + + run_eggfetcher(env.console, context, GameSettings::instance().AUTO_DEPOSIT, MAX_FETCH_ATTEMPTS_PER_SPECIES); + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h index 25a9f9242a..7507f923f0 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggFetcherMultiple.h @@ -1,48 +1,48 @@ -/* Egg Fetcher Multiple - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggFetcherMultiple_H -#define PokemonAutomation_PokemonSwSh_EggFetcherMultiple_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "PokemonSwSh_EggHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EggFetcherMultiple_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggFetcherMultiple_Descriptor(); -}; - - - -class EggFetcherMultiple : public SingleSwitchProgramInstance{ -public: - EggFetcherMultiple(); - - void run_eggfetcher(Logger& logger, ProControllerContext& context, bool deposit_automatically, uint16_t attempts) const; - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption POKEMON_SPECIES_COUNT; - SimpleIntegerOption MAX_FETCH_ATTEMPTS_PER_SPECIES; - - EventNotificationsOption NOTIFICATIONS; -}; - - - -} -} -} -#endif +/* Egg Fetcher Multiple + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggFetcherMultiple_H +#define PokemonAutomation_PokemonSwSh_EggFetcherMultiple_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "PokemonSwSh_EggHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EggFetcherMultiple_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggFetcherMultiple_Descriptor(); +}; + + + +class EggFetcherMultiple : public SingleSwitchProgramInstance{ +public: + EggFetcherMultiple(); + + void run_eggfetcher(Logger& logger, ProControllerContext& context, bool deposit_automatically, uint16_t attempts) const; + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption POKEMON_SPECIES_COUNT; + SimpleIntegerOption MAX_FETCH_ATTEMPTS_PER_SPECIES; + + EventNotificationsOption NOTIFICATIONS; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.cpp index fd6f7390bf..df36817d18 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.cpp @@ -1,178 +1,178 @@ -/* Egg Hatcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh_EggHelpers.h" -#include "PokemonSwSh_EggHatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -EggHatcher_Descriptor::EggHatcher_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EggHatcher", - STRING_POKEMON + " SwSh", "Egg Hatcher", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggHatcher.md", - "Hatch eggs from boxes.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -void withdraw_column(ProControllerContext& context, uint8_t column){ - menu_to_box(context, false); - party_to_column(context, column); - pickup_column(context, false); - column_to_party(context, column); - ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); - box_to_menu(context); -} -void deposit_column(ProControllerContext& context, uint8_t column){ - menu_to_box(context, true); - pickup_column(context, true); - party_to_column(context, column); - ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); - box_to_menu(context); -} -uint8_t swap_party(ProControllerContext& context, uint8_t column){ - menu_to_box(context, true); - pickup_column(context, true); - - Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; - - // Move to column. - party_to_column(context, column); - ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, 100ms); - - // Move to next column. - column++; - if (column < 6){ - box_scroll(context, DPAD_RIGHT); - }else{ - column = 0; - ssf_press_button_ptv(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0, 100ms); - box_scroll(context, DPAD_RIGHT); - box_scroll(context, DPAD_RIGHT); - } - - pickup_column(context, false); - - // Move to party. - column_to_party(context, column); - ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY); - - // Return to menu. - box_to_menu(context); - - return column; -} - - -EggHatcher::EggHatcher() - : BOXES_TO_HATCH( - "Boxes to Hatch:", - LockMode::LOCK_WHILE_RUNNING, - 3 - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SAFETY_TIME1( - "Safety Time:
Additional time added to the spinning.", - LockMode::LOCK_WHILE_RUNNING, - "12 s" - ) - , HATCH_DELAY0( - "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", - LockMode::LOCK_WHILE_RUNNING, - "88 s" - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(BOXES_TO_HATCH); - PA_ADD_OPTION(STEPS_TO_HATCH); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SAFETY_TIME1); - PA_ADD_OPTION(HATCH_DELAY0); - PA_ADD_OPTION(NOTIFICATIONS); -} -void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Calculate upper bounds for incubation time. - Milliseconds INCUBATION_DELAY_UPPER = (uint16_t)((uint32_t)STEPS_TO_HATCH * 2 * (uint32_t)103180 >> 16) * 8ms; - Milliseconds TOTAL_DELAY = INCUBATION_DELAY_UPPER + HATCH_DELAY0.get() + SAFETY_TIME1.get() - TRAVEL_RIGHT_DURATION; - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - bool party_is_empty = true; - for (uint8_t box = 0; box < BOXES_TO_HATCH; box++){ - for (uint8_t column = 0; column < 6; column++){ - // Get eggs from box. - ssf_press_button_ptv(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - if (party_is_empty){ - withdraw_column(context, column); - party_is_empty = false; - }else if (column == 0){ - swap_party(context, 5); - }else{ - swap_party(context, column - 1); - } - - fly_home(context, false); - - // Travel to spin location. - pbf_move_left_joystick(context, STICK_MAX, STICK_CENTER, TRAVEL_RIGHT_DURATION, 0ms); - - // Spin -#if 0 - spin_and_mash_A(TOTAL_DELAY); -#else - if (TOTAL_DELAY >= END_BATCH_MASH_B_DURATION){ - spin_and_mash_A(context, TOTAL_DELAY - END_BATCH_MASH_B_DURATION); - pbf_mash_button(context, BUTTON_B, END_BATCH_MASH_B_DURATION); - }else{ - spin_and_mash_A(context, TOTAL_DELAY); - } -#endif - } - } - - Milliseconds OVERWORLD_TO_MENU_DELAY = GameSettings::instance().OVERWORLD_TO_MENU_DELAY0; - - if (!party_is_empty){ - ssf_press_button_ptv(context, BUTTON_X, OVERWORLD_TO_MENU_DELAY); - deposit_column(context, 5); - ssf_press_button_ptv(context, BUTTON_X, OVERWORLD_TO_MENU_DELAY); - } - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* Egg Hatcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh_EggHelpers.h" +#include "PokemonSwSh_EggHatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +EggHatcher_Descriptor::EggHatcher_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EggHatcher", + STRING_POKEMON + " SwSh", "Egg Hatcher", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggHatcher.md", + "Hatch eggs from boxes.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +void withdraw_column(ProControllerContext& context, uint8_t column){ + menu_to_box(context, false); + party_to_column(context, column); + pickup_column(context, false); + column_to_party(context, column); + ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); + box_to_menu(context); +} +void deposit_column(ProControllerContext& context, uint8_t column){ + menu_to_box(context, true); + pickup_column(context, true); + party_to_column(context, column); + ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0); + box_to_menu(context); +} +uint8_t swap_party(ProControllerContext& context, uint8_t column){ + menu_to_box(context, true); + pickup_column(context, true); + + Milliseconds BOX_PICKUP_DROP_DELAY = GameSettings::instance().BOX_PICKUP_DROP_DELAY0; + + // Move to column. + party_to_column(context, column); + ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY, 100ms); + + // Move to next column. + column++; + if (column < 6){ + box_scroll(context, DPAD_RIGHT); + }else{ + column = 0; + ssf_press_button_ptv(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0, 100ms); + box_scroll(context, DPAD_RIGHT); + box_scroll(context, DPAD_RIGHT); + } + + pickup_column(context, false); + + // Move to party. + column_to_party(context, column); + ssf_press_button_ptv(context, BUTTON_A, BOX_PICKUP_DROP_DELAY); + + // Return to menu. + box_to_menu(context); + + return column; +} + + +EggHatcher::EggHatcher() + : BOXES_TO_HATCH( + "Boxes to Hatch:", + LockMode::LOCK_WHILE_RUNNING, + 3 + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SAFETY_TIME1( + "Safety Time:
Additional time added to the spinning.", + LockMode::LOCK_WHILE_RUNNING, + "12 s" + ) + , HATCH_DELAY0( + "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", + LockMode::LOCK_WHILE_RUNNING, + "88 s" + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(BOXES_TO_HATCH); + PA_ADD_OPTION(STEPS_TO_HATCH); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SAFETY_TIME1); + PA_ADD_OPTION(HATCH_DELAY0); + PA_ADD_OPTION(NOTIFICATIONS); +} +void EggHatcher::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Calculate upper bounds for incubation time. + Milliseconds INCUBATION_DELAY_UPPER = (uint16_t)((uint32_t)STEPS_TO_HATCH * 2 * (uint32_t)103180 >> 16) * 8ms; + Milliseconds TOTAL_DELAY = INCUBATION_DELAY_UPPER + HATCH_DELAY0.get() + SAFETY_TIME1.get() - TRAVEL_RIGHT_DURATION; + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + bool party_is_empty = true; + for (uint8_t box = 0; box < BOXES_TO_HATCH; box++){ + for (uint8_t column = 0; column < 6; column++){ + // Get eggs from box. + ssf_press_button_ptv(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + if (party_is_empty){ + withdraw_column(context, column); + party_is_empty = false; + }else if (column == 0){ + swap_party(context, 5); + }else{ + swap_party(context, column - 1); + } + + fly_home(context, false); + + // Travel to spin location. + pbf_move_left_joystick(context, STICK_MAX, STICK_CENTER, TRAVEL_RIGHT_DURATION, 0ms); + + // Spin +#if 0 + spin_and_mash_A(TOTAL_DELAY); +#else + if (TOTAL_DELAY >= END_BATCH_MASH_B_DURATION){ + spin_and_mash_A(context, TOTAL_DELAY - END_BATCH_MASH_B_DURATION); + pbf_mash_button(context, BUTTON_B, END_BATCH_MASH_B_DURATION); + }else{ + spin_and_mash_A(context, TOTAL_DELAY); + } +#endif + } + } + + Milliseconds OVERWORLD_TO_MENU_DELAY = GameSettings::instance().OVERWORLD_TO_MENU_DELAY0; + + if (!party_is_empty){ + ssf_press_button_ptv(context, BUTTON_X, OVERWORLD_TO_MENU_DELAY); + deposit_column(context, 5); + ssf_press_button_ptv(context, BUTTON_X, OVERWORLD_TO_MENU_DELAY); + } + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.h index ebcf2ff567..d54a4d151b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHatcher.h @@ -1,55 +1,55 @@ -/* Egg Hatcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggHatcher_H -#define PokemonAutomation_PokemonSwSh_EggHatcher_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_EggStepOption.h" -//#include "PokemonSwSh_EggHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EggHatcher_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggHatcher_Descriptor(); -}; - - - -class EggHatcher : public SingleSwitchProgramInstance{ -public: - EggHatcher(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption BOXES_TO_HATCH; - EggStepCountOption STEPS_TO_HATCH; - - SectionDividerOption m_advanced_options; - MillisecondsOption SAFETY_TIME1; - MillisecondsOption HATCH_DELAY0; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Egg Hatcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggHatcher_H +#define PokemonAutomation_PokemonSwSh_EggHatcher_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_EggStepOption.h" +//#include "PokemonSwSh_EggHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EggHatcher_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggHatcher_Descriptor(); +}; + + + +class EggHatcher : public SingleSwitchProgramInstance{ +public: + EggHatcher(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption BOXES_TO_HATCH; + EggStepCountOption STEPS_TO_HATCH; + + SectionDividerOption m_advanced_options; + MillisecondsOption SAFETY_TIME1; + MillisecondsOption HATCH_DELAY0; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h index 09cfca6746..182b2da471 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggHelpers.h @@ -1,158 +1,158 @@ -/* EggHelpers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggHelpers_H -#define PokemonAutomation_PokemonSwSh_EggHelpers_H - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -#define GO_TO_LADY_DURATION (51 * 8ms) -#define TRAVEL_RIGHT_DURATION (300 * 8ms) -#define END_BATCH_MASH_B_DURATION (20 * TICKS_PER_SECOND * 8ms) - - -// Collect egg. -static void collect_egg(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 960ms); - if (GameSettings::instance().EGG_FETCH_EXTRA_LINE){ - ssf_press_button(context, BUTTON_A, 960ms); - } - ssf_press_button(context, BUTTON_A, 80ms, 80ms); -} -static void collect_egg_mash_out(ProControllerContext& context, bool deposit_automatically){ - Milliseconds FETCH_EGG_MASH_DELAY = GameSettings::instance().FETCH_EGG_MASH_DELAY0; - pbf_mash_button( - context, - BUTTON_B, - deposit_automatically - ? FETCH_EGG_MASH_DELAY - : FETCH_EGG_MASH_DELAY + 1920ms - ); -} - - -// Fly Home: Used by everything. -// Assume the selected app in the menu is Town Map. -static void fly_home(ProControllerContext& context, char from_overworld){ - if (from_overworld){ - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - } - ssf_press_button(context, BUTTON_A, 3200ms, 160ms); - ssf_press_right_joystick(context, 160, 96, 160ms, 160ms); - pbf_mash_button(context, BUTTON_A, 480); -} - -// Assume the selected app in the menu is Twon Map. -static void fly_home_goto_lady(ProControllerContext& context, char from_overworld){ - fly_home(context, from_overworld); - - // Go to lady. - // If you change this, you MUST update "GO_TO_LADY_DURATION". - ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 20, 10); - ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 90, 45); -} - -// Assume the selected app in the menu is Twon Map. -static void fly_home_collect_egg(ProControllerContext& context, char from_overworld){ - fly_home_goto_lady(context, from_overworld); - collect_egg(context); -} - - - -// EggHatcher+EggCombined Helpers - -//#define EGG_BUTTON_HOLD_DELAY 10 -static const Milliseconds EGG_BUTTON_HOLD_DELAY = 80ms; - -// - From game menu to pokemon storage box -// - Move cursor to the second pokemon in the party, aka first hatched pokemon in the party -// - Press button Y two times to change pokemon selection to group selection -static void menu_to_box(ProControllerContext& context, bool from_map){ - if (from_map){ - box_scroll(context, DPAD_UP); - box_scroll(context, DPAD_RIGHT); - } - ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); - ssf_press_button_ptv(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, EGG_BUTTON_HOLD_DELAY); - box_scroll(context, DPAD_LEFT); - box_scroll(context, DPAD_DOWN); - ssf_press_button_ptv(context, BUTTON_Y, 240ms, EGG_BUTTON_HOLD_DELAY); - ssf_press_button_ptv(context, BUTTON_Y, 240ms, EGG_BUTTON_HOLD_DELAY); -} -static void box_to_menu(ProControllerContext& context){ - // There are two states here which need to be merged: - // 1. The depositing column was empty. The party has been swapped and - // it's sitting in the box with no held pokemon. - // 2. The depositing column was not empty. The party swap failed and - // it's sitting in the box holding on the party pokemon. - // - // Double press B quickly here to back out of the box. - // In state (1): The 1st B will begin back out of the box. The 2nd B will - // be swallowed by the animation. - // In state (2): The 1st B will drop the party pokemon. The 2nd B will - // back out of the box. - - ssf_press_button_ptv(context, BUTTON_B, 160ms, EGG_BUTTON_HOLD_DELAY); - ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().BOX_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); - - // Back out to menu. - ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().POKEMON_TO_MENU_DELAY0, EGG_BUTTON_HOLD_DELAY); - - box_scroll(context, DPAD_LEFT); - box_scroll(context, DPAD_DOWN); -} - -static void party_to_column(ProControllerContext& context, uint8_t column){ - box_scroll(context, DPAD_UP); - column++; - if (column <= 3){ - for (uint8_t c = 0; c != column; c++){ - box_scroll(context, DPAD_RIGHT); - } - }else{ - for (uint8_t c = 7; c != column; c--){ - box_scroll(context, DPAD_LEFT); - } - } -} -static void column_to_party(ProControllerContext& context, uint8_t column){ - column++; - if (column <= 3){ - for (uint8_t c = column; c != 0; c--){ - box_scroll(context, DPAD_LEFT); - } - }else{ - for (uint8_t c = column; c != 7; c++){ - box_scroll(context, DPAD_RIGHT); - } - } - box_scroll(context, DPAD_DOWN); -} - -static void pickup_column(ProControllerContext& context, char party){ - ssf_press_button_ptv(context, BUTTON_A, 160ms, EGG_BUTTON_HOLD_DELAY); - if (party){ - box_scroll(context, DPAD_UP); - } - box_scroll(context, DPAD_UP); - ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0, EGG_BUTTON_HOLD_DELAY); -} - - - - -} -} -} -#endif +/* EggHelpers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggHelpers_H +#define PokemonAutomation_PokemonSwSh_EggHelpers_H + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +#define GO_TO_LADY_DURATION (51 * 8ms) +#define TRAVEL_RIGHT_DURATION (300 * 8ms) +#define END_BATCH_MASH_B_DURATION (20 * TICKS_PER_SECOND * 8ms) + + +// Collect egg. +static void collect_egg(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 960ms); + if (GameSettings::instance().EGG_FETCH_EXTRA_LINE){ + ssf_press_button(context, BUTTON_A, 960ms); + } + ssf_press_button(context, BUTTON_A, 80ms, 80ms); +} +static void collect_egg_mash_out(ProControllerContext& context, bool deposit_automatically){ + Milliseconds FETCH_EGG_MASH_DELAY = GameSettings::instance().FETCH_EGG_MASH_DELAY0; + pbf_mash_button( + context, + BUTTON_B, + deposit_automatically + ? FETCH_EGG_MASH_DELAY + : FETCH_EGG_MASH_DELAY + 1920ms + ); +} + + +// Fly Home: Used by everything. +// Assume the selected app in the menu is Town Map. +static void fly_home(ProControllerContext& context, char from_overworld){ + if (from_overworld){ + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + } + ssf_press_button(context, BUTTON_A, 3200ms, 160ms); + ssf_press_right_joystick(context, 160, 96, 160ms, 160ms); + pbf_mash_button(context, BUTTON_A, 480); +} + +// Assume the selected app in the menu is Twon Map. +static void fly_home_goto_lady(ProControllerContext& context, char from_overworld){ + fly_home(context, from_overworld); + + // Go to lady. + // If you change this, you MUST update "GO_TO_LADY_DURATION". + ssf_press_left_joystick(context, STICK_MIN, STICK_CENTER, 20, 10); + ssf_press_left_joystick(context, STICK_CENTER, STICK_MIN, 90, 45); +} + +// Assume the selected app in the menu is Twon Map. +static void fly_home_collect_egg(ProControllerContext& context, char from_overworld){ + fly_home_goto_lady(context, from_overworld); + collect_egg(context); +} + + + +// EggHatcher+EggCombined Helpers + +//#define EGG_BUTTON_HOLD_DELAY 10 +static const Milliseconds EGG_BUTTON_HOLD_DELAY = 80ms; + +// - From game menu to pokemon storage box +// - Move cursor to the second pokemon in the party, aka first hatched pokemon in the party +// - Press button Y two times to change pokemon selection to group selection +static void menu_to_box(ProControllerContext& context, bool from_map){ + if (from_map){ + box_scroll(context, DPAD_UP); + box_scroll(context, DPAD_RIGHT); + } + ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); + ssf_press_button_ptv(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, EGG_BUTTON_HOLD_DELAY); + box_scroll(context, DPAD_LEFT); + box_scroll(context, DPAD_DOWN); + ssf_press_button_ptv(context, BUTTON_Y, 240ms, EGG_BUTTON_HOLD_DELAY); + ssf_press_button_ptv(context, BUTTON_Y, 240ms, EGG_BUTTON_HOLD_DELAY); +} +static void box_to_menu(ProControllerContext& context){ + // There are two states here which need to be merged: + // 1. The depositing column was empty. The party has been swapped and + // it's sitting in the box with no held pokemon. + // 2. The depositing column was not empty. The party swap failed and + // it's sitting in the box holding on the party pokemon. + // + // Double press B quickly here to back out of the box. + // In state (1): The 1st B will begin back out of the box. The 2nd B will + // be swallowed by the animation. + // In state (2): The 1st B will drop the party pokemon. The 2nd B will + // back out of the box. + + ssf_press_button_ptv(context, BUTTON_B, 160ms, EGG_BUTTON_HOLD_DELAY); + ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().BOX_TO_POKEMON_DELAY0, EGG_BUTTON_HOLD_DELAY); + + // Back out to menu. + ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().POKEMON_TO_MENU_DELAY0, EGG_BUTTON_HOLD_DELAY); + + box_scroll(context, DPAD_LEFT); + box_scroll(context, DPAD_DOWN); +} + +static void party_to_column(ProControllerContext& context, uint8_t column){ + box_scroll(context, DPAD_UP); + column++; + if (column <= 3){ + for (uint8_t c = 0; c != column; c++){ + box_scroll(context, DPAD_RIGHT); + } + }else{ + for (uint8_t c = 7; c != column; c--){ + box_scroll(context, DPAD_LEFT); + } + } +} +static void column_to_party(ProControllerContext& context, uint8_t column){ + column++; + if (column <= 3){ + for (uint8_t c = column; c != 0; c--){ + box_scroll(context, DPAD_LEFT); + } + }else{ + for (uint8_t c = column; c != 7; c++){ + box_scroll(context, DPAD_RIGHT); + } + } + box_scroll(context, DPAD_DOWN); +} + +static void pickup_column(ProControllerContext& context, char party){ + ssf_press_button_ptv(context, BUTTON_A, 160ms, EGG_BUTTON_HOLD_DELAY); + if (party){ + box_scroll(context, DPAD_UP); + } + box_scroll(context, DPAD_UP); + ssf_press_button_ptv(context, BUTTON_A, GameSettings::instance().BOX_PICKUP_DROP_DELAY0, EGG_BUTTON_HOLD_DELAY); +} + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp index 934103ff7f..1b85b87936 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.cpp @@ -1,134 +1,134 @@ -/* Egg Super-Combined 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "Pokemon/Pokemon_Strings.h" -//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h" -#include "PokemonSwSh_EggCombinedShared.h" -#include "PokemonSwSh_EggSuperCombined2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -EggSuperCombined2_Descriptor::EggSuperCombined2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:EggSuperCombined2", - STRING_POKEMON + " SwSh", "Egg Super-Combined 2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggSuperCombined2.md", - "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -EggSuperCombined2::EggSuperCombined2() - : BOXES_TO_RELEASE( - "Boxes to Release:
Start by releasing this many boxes.", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 32 - ) - , BOXES_TO_SKIP( - "Boxes to Skip:
Then skip this many boxes.", - LockMode::LOCK_WHILE_RUNNING, - 1, 0, 32 - ) - , BOXES_TO_HATCH( - "Boxes to Hatch:", - LockMode::LOCK_WHILE_RUNNING, - 31, 0, 32 - ) - , FETCHES_PER_BATCH( - "Fetches per Batch:
For each batch of eggs, attempt this many egg fetches.", - LockMode::LOCK_WHILE_RUNNING, - 6.0, 0, 7 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SAFETY_TIME0( - "Safety Time:
Additional time added to the spinning.", - LockMode::LOCK_WHILE_RUNNING, - "12 s" - ) - , EARLY_HATCH_SAFETY0( - "Early Hatch Time:
Eggs should not hatch more than this much early.", - LockMode::LOCK_WHILE_RUNNING, - "5 s" - ) - , HATCH_DELAY0( - "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", - LockMode::LOCK_WHILE_RUNNING, - "88 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(BOXES_TO_RELEASE); - PA_ADD_OPTION(BOXES_TO_SKIP); - PA_ADD_OPTION(BOXES_TO_HATCH); - PA_ADD_OPTION(STEPS_TO_HATCH); - PA_ADD_OPTION(FETCHES_PER_BATCH); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SAFETY_TIME0); - PA_ADD_OPTION(EARLY_HATCH_SAFETY0); - PA_ADD_OPTION(HATCH_DELAY0); -} - -void EggSuperCombined2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - EggCombinedSession session{ - BOXES_TO_HATCH, - STEPS_TO_HATCH, - (float)FETCHES_PER_BATCH, - SAFETY_TIME0, - EARLY_HATCH_SAFETY0, - HATCH_DELAY0, - TOUCH_DATE_INTERVAL - }; - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - // Mass Release - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - ssf_press_button(context, BUTTON_A, 1600ms); - ssf_press_button(context, BUTTON_R, 2000ms); - release_boxes(context, BOXES_TO_RELEASE); - - // Skip Boxes - for (uint8_t c = 0; c <= BOXES_TO_SKIP; c++){ - ssf_press_button(context, BUTTON_R, 480ms); - } - pbf_mash_button(context, BUTTON_B, 600); - - session.eggcombined2_body(env.console, context); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} - +/* Egg Super-Combined 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "Pokemon/Pokemon_Strings.h" +//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h" +#include "PokemonSwSh_EggCombinedShared.h" +#include "PokemonSwSh_EggSuperCombined2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +EggSuperCombined2_Descriptor::EggSuperCombined2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:EggSuperCombined2", + STRING_POKEMON + " SwSh", "Egg Super-Combined 2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/EggSuperCombined2.md", + "Fetch and hatch eggs at the same time. (Fastest - 1700 eggs/day for 5120-step)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +EggSuperCombined2::EggSuperCombined2() + : BOXES_TO_RELEASE( + "Boxes to Release:
Start by releasing this many boxes.", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 32 + ) + , BOXES_TO_SKIP( + "Boxes to Skip:
Then skip this many boxes.", + LockMode::LOCK_WHILE_RUNNING, + 1, 0, 32 + ) + , BOXES_TO_HATCH( + "Boxes to Hatch:", + LockMode::LOCK_WHILE_RUNNING, + 31, 0, 32 + ) + , FETCHES_PER_BATCH( + "Fetches per Batch:
For each batch of eggs, attempt this many egg fetches.", + LockMode::LOCK_WHILE_RUNNING, + 6.0, 0, 7 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SAFETY_TIME0( + "Safety Time:
Additional time added to the spinning.", + LockMode::LOCK_WHILE_RUNNING, + "12 s" + ) + , EARLY_HATCH_SAFETY0( + "Early Hatch Time:
Eggs should not hatch more than this much early.", + LockMode::LOCK_WHILE_RUNNING, + "5 s" + ) + , HATCH_DELAY0( + "Hatch Delay:
Total animation time for hatching 5 eggs when there are no shinies.", + LockMode::LOCK_WHILE_RUNNING, + "88 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(BOXES_TO_RELEASE); + PA_ADD_OPTION(BOXES_TO_SKIP); + PA_ADD_OPTION(BOXES_TO_HATCH); + PA_ADD_OPTION(STEPS_TO_HATCH); + PA_ADD_OPTION(FETCHES_PER_BATCH); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SAFETY_TIME0); + PA_ADD_OPTION(EARLY_HATCH_SAFETY0); + PA_ADD_OPTION(HATCH_DELAY0); +} + +void EggSuperCombined2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + EggCombinedSession session{ + BOXES_TO_HATCH, + STEPS_TO_HATCH, + (float)FETCHES_PER_BATCH, + SAFETY_TIME0, + EARLY_HATCH_SAFETY0, + HATCH_DELAY0, + TOUCH_DATE_INTERVAL + }; + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + // Mass Release + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + ssf_press_button(context, BUTTON_A, 1600ms); + ssf_press_button(context, BUTTON_R, 2000ms); + release_boxes(context, BOXES_TO_RELEASE); + + // Skip Boxes + for (uint8_t c = 0; c <= BOXES_TO_SKIP; c++){ + ssf_press_button(context, BUTTON_R, 480ms); + } + pbf_mash_button(context, BUTTON_B, 600); + + session.eggcombined2_body(env.console, context); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h index 1ecd4f7894..3ad998d4c0 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_EggSuperCombined2.h @@ -1,60 +1,60 @@ -/* Egg Super-Combined 2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EggSuperCombined2_H -#define PokemonAutomation_PokemonSwSh_EggSuperCombined2_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EggStepOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class EggSuperCombined2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - EggSuperCombined2_Descriptor(); -}; - - - -class EggSuperCombined2 : public SingleSwitchProgramInstance{ -public: - EggSuperCombined2(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - SimpleIntegerOption BOXES_TO_RELEASE; - SimpleIntegerOption BOXES_TO_SKIP; - SimpleIntegerOption BOXES_TO_HATCH; - EggStepCountOption STEPS_TO_HATCH; - FloatingPointOption FETCHES_PER_BATCH; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption SAFETY_TIME0; - MillisecondsOption EARLY_HATCH_SAFETY0; - MillisecondsOption HATCH_DELAY0; -}; - - -} -} -} -#endif +/* Egg Super-Combined 2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EggSuperCombined2_H +#define PokemonAutomation_PokemonSwSh_EggSuperCombined2_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EggStepOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class EggSuperCombined2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + EggSuperCombined2_Descriptor(); +}; + + + +class EggSuperCombined2 : public SingleSwitchProgramInstance{ +public: + EggSuperCombined2(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + SimpleIntegerOption BOXES_TO_RELEASE; + SimpleIntegerOption BOXES_TO_SKIP; + SimpleIntegerOption BOXES_TO_HATCH; + EggStepCountOption STEPS_TO_HATCH; + FloatingPointOption FETCHES_PER_BATCH; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption SAFETY_TIME0; + MillisecondsOption EARLY_HATCH_SAFETY0; + MillisecondsOption HATCH_DELAY0; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.cpp index 17f285675d..211a875684 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.cpp @@ -1,139 +1,139 @@ -/* God Egg Duplication - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_GodEggDuplication.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -GodEggDuplication_Descriptor::GodEggDuplication_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:GodEggDuplication", - STRING_POKEMON + " SwSh", "God Egg Duplication", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/GodEggDuplication.md", - "Mass duplicate " + STRING_POKEMON + " with the God Egg.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} - - - -GodEggDuplication::GodEggDuplication() - : MAX_FETCH_ATTEMPTS( - "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", - LockMode::LOCK_WHILE_RUNNING, - 2000 - ) - , PARTY_ROUND_ROBIN( - "Party Round Robin:
Cycle through this many party members.", - LockMode::LOCK_WHILE_RUNNING, - 6, 1, 6 - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); - PA_ADD_OPTION(PARTY_ROUND_ROBIN); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void GodEggDuplication::collect_godegg(ProControllerContext& context, uint8_t party_slot) const{ - pbf_wait(context, 50); - ssf_press_button_ptv(context, BUTTON_B, 800ms); - ssf_press_button_ptv(context, BUTTON_B, 800ms); - pbf_wait(context, 225); - - // "You received an Egg from the Nursery worker!" - ssf_press_button_ptv(context, BUTTON_B, 2400ms); - - // "Where do you want to send the Egg to?" - ssf_press_button_ptv(context, BUTTON_A, 800ms); - - // (extra line of text for French) - ssf_press_button_ptv(context, BUTTON_B, 800ms); - - // "Please select a Pokemon to swap from your party." - ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().MENU_TO_POKEMON_DELAY0); - - // Select the party member. - for (uint8_t c = 0; c < party_slot; c++){ - ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); - } - ssf_press_button_ptv(context, BUTTON_A, 2400ms); - pbf_mash_button(context, BUTTON_B, 500); -} -void GodEggDuplication::run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const{ - if (attempts == 0){ - return; - } - - uint8_t items = PARTY_ROUND_ROBIN > 6 ? 6 : PARTY_ROUND_ROBIN; - uint8_t party_slot = 0; - - uint16_t c = 0; - - // 1st Fetch: Get into position. - { - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - fly_home_collect_egg(context, true); - collect_godegg(context, party_slot++); - if (party_slot >= items){ - party_slot = 0; - } - - c++; - if (c >= attempts){ - return; - } - } - - // Now we are in steady state. - for (; c < attempts; c++){ - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - eggfetcher_loop(context); - collect_egg(context); - collect_godegg(context, party_slot++); - if (party_slot >= items){ - party_slot = 0; - } - } -} - -void GodEggDuplication::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - run_program(env.console, context, MAX_FETCH_ATTEMPTS); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - -} -} -} - +/* God Egg Duplication + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_GodEggDuplication.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +GodEggDuplication_Descriptor::GodEggDuplication_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:GodEggDuplication", + STRING_POKEMON + " SwSh", "God Egg Duplication", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/GodEggDuplication.md", + "Mass duplicate " + STRING_POKEMON + " with the God Egg.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} + + + +GodEggDuplication::GodEggDuplication() + : MAX_FETCH_ATTEMPTS( + "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", + LockMode::LOCK_WHILE_RUNNING, + 2000 + ) + , PARTY_ROUND_ROBIN( + "Party Round Robin:
Cycle through this many party members.", + LockMode::LOCK_WHILE_RUNNING, + 6, 1, 6 + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); + PA_ADD_OPTION(PARTY_ROUND_ROBIN); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void GodEggDuplication::collect_godegg(ProControllerContext& context, uint8_t party_slot) const{ + pbf_wait(context, 50); + ssf_press_button_ptv(context, BUTTON_B, 800ms); + ssf_press_button_ptv(context, BUTTON_B, 800ms); + pbf_wait(context, 225); + + // "You received an Egg from the Nursery worker!" + ssf_press_button_ptv(context, BUTTON_B, 2400ms); + + // "Where do you want to send the Egg to?" + ssf_press_button_ptv(context, BUTTON_A, 800ms); + + // (extra line of text for French) + ssf_press_button_ptv(context, BUTTON_B, 800ms); + + // "Please select a Pokemon to swap from your party." + ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().MENU_TO_POKEMON_DELAY0); + + // Select the party member. + for (uint8_t c = 0; c < party_slot; c++){ + ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); + } + ssf_press_button_ptv(context, BUTTON_A, 2400ms); + pbf_mash_button(context, BUTTON_B, 500); +} +void GodEggDuplication::run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const{ + if (attempts == 0){ + return; + } + + uint8_t items = PARTY_ROUND_ROBIN > 6 ? 6 : PARTY_ROUND_ROBIN; + uint8_t party_slot = 0; + + uint16_t c = 0; + + // 1st Fetch: Get into position. + { + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + fly_home_collect_egg(context, true); + collect_godegg(context, party_slot++); + if (party_slot >= items){ + party_slot = 0; + } + + c++; + if (c >= attempts){ + return; + } + } + + // Now we are in steady state. + for (; c < attempts; c++){ + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + eggfetcher_loop(context); + collect_egg(context); + collect_godegg(context, party_slot++); + if (party_slot >= items){ + party_slot = 0; + } + } +} + +void GodEggDuplication::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + run_program(env.console, context, MAX_FETCH_ATTEMPTS); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h index 1eddcbf1ae..32a41b3da2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggDuplication.h @@ -1,49 +1,49 @@ -/* God Egg Duplication - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_GodEggDuplication_H -#define PokemonAutomation_PokemonSwSh_GodEggDuplication_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh_EggHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class GodEggDuplication_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GodEggDuplication_Descriptor(); -}; - - - -class GodEggDuplication : public SingleSwitchProgramInstance{ -public: - GodEggDuplication(); - - void collect_godegg(ProControllerContext& context, uint8_t party_slot) const; - void run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const; - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption MAX_FETCH_ATTEMPTS; - SimpleIntegerOption PARTY_ROUND_ROBIN; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* God Egg Duplication + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_GodEggDuplication_H +#define PokemonAutomation_PokemonSwSh_GodEggDuplication_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh_EggHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class GodEggDuplication_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GodEggDuplication_Descriptor(); +}; + + + +class GodEggDuplication : public SingleSwitchProgramInstance{ +public: + GodEggDuplication(); + + void collect_godegg(ProControllerContext& context, uint8_t party_slot) const; + void run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const; + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption MAX_FETCH_ATTEMPTS; + SimpleIntegerOption PARTY_ROUND_ROBIN; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp index 2bc756a994..1c983074c2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.cpp @@ -1,191 +1,191 @@ -/* God Egg Item Duplication - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h" -#include "PokemonSwSh_GodEggItemDupe.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -GodEggItemDupe_Descriptor::GodEggItemDupe_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:GodEggItemDupe", - STRING_POKEMON + " SwSh", "God Egg Item Duplication", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/GodEggItemDuplication.md", - "Mass duplicate items with the God Egg.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} - - - -GodEggItemDupe::GodEggItemDupe() - : MAX_FETCH_ATTEMPTS( - "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", - LockMode::LOCK_WHILE_RUNNING, - 2000 - ) - , PARTY_ROUND_ROBIN( - "Party Round Robin:
Cycle through this many party members.", - LockMode::LOCK_WHILE_RUNNING, - 6, 1, 6 - ) - , DETACH_BEFORE_RELEASE( - "Detach before Release:
Needed for items like Rusted Sword/Shield.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); - PA_ADD_OPTION(PARTY_ROUND_ROBIN); - PA_ADD_OPTION(DETACH_BEFORE_RELEASE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - -void GodEggItemDupe::collect_godegg( - ProControllerContext& context, - uint8_t party_slot, - bool map_to_pokemon, - bool pokemon_to_map -) const{ - pbf_wait(context, 50); - ssf_press_button_ptv(context, BUTTON_B, 800ms); - ssf_press_button_ptv(context, BUTTON_B, 800ms); - pbf_wait(context, 225); - - // "You received an Egg from the Nursery worker!" - ssf_press_button_ptv(context, BUTTON_B, 2400ms); - - // "Where do you want to send the Egg to?" - ssf_press_button_ptv(context, BUTTON_A, 800ms); - - // (extra line of text for French) - ssf_press_button_ptv(context, BUTTON_B, 800ms); - - // "Please select a Pokemon to swap from your party." - ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().MENU_TO_POKEMON_DELAY0); - - // Select the party member. - for (uint8_t c = 0; c < party_slot; c++){ - ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); - } - ssf_press_button_ptv(context, BUTTON_A, 2400ms); - pbf_mash_button(context, BUTTON_B, 500); - - // Enter box - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - if (map_to_pokemon){ - ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_RIGHT, 160ms, 80ms); - } - ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, 80ms); - ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, 80ms); - - if (DETACH_BEFORE_RELEASE){ - // Detach item - ssf_press_button(context, BUTTON_A, 400ms, 160ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); - ssf_press_button(context, BUTTON_A, 1200ms, 160ms); - ssf_press_button(context, BUTTON_A, 1200ms, 160ms); - ssf_press_button(context, BUTTON_A, 800ms, 160ms); - - // Release - release(context); - }else{ - // Release (item detaches automatically) - ssf_press_button(context, BUTTON_A, 480ms, 160ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); - ssf_press_button(context, BUTTON_A, 1000ms, 160ms); - ssf_press_dpad_ptv(context, DPAD_UP, 80ms); - ssf_mash_AZs(context, 180); - } - - // Back out to menu. - if (pokemon_to_map){ - box_to_menu(context); - ssf_press_button(context, BUTTON_B, 2000ms, 50ms); - }else{ - pbf_mash_button(context, BUTTON_B, 700); - } -} -void GodEggItemDupe::run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const{ - if (attempts == 0){ - return; - } - - uint8_t items = PARTY_ROUND_ROBIN > 6 ? 6 : PARTY_ROUND_ROBIN; - uint8_t party_slot = 0; - - uint16_t c = 0; - - // 1st Fetch: Get into position. - { - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - fly_home_collect_egg(context, true); - collect_godegg(context, party_slot++, true, false); - if (party_slot >= items){ - party_slot = 0; - } - - c++; - if (c >= attempts){ - return; - } - } - - // Now we are in steady state. - for (; c < attempts; c++){ - logger.log("Fetch Attempts: " + tostr_u_commas(c)); - eggfetcher_loop(context); - collect_egg(context); - collect_godegg(context, party_slot++, false, false); - if (party_slot >= items){ - party_slot = 0; - } - } -} - -void GodEggItemDupe::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - run_program(env.console, context, MAX_FETCH_ATTEMPTS); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* God Egg Item Duplication + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_EggRoutines.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h" +#include "PokemonSwSh_GodEggItemDupe.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +GodEggItemDupe_Descriptor::GodEggItemDupe_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:GodEggItemDupe", + STRING_POKEMON + " SwSh", "God Egg Item Duplication", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/GodEggItemDuplication.md", + "Mass duplicate items with the God Egg.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} + + + +GodEggItemDupe::GodEggItemDupe() + : MAX_FETCH_ATTEMPTS( + "Fetch this many times:
This puts a limit on how many eggs you can get so you don't make a mess of your boxes for fetching too many.", + LockMode::LOCK_WHILE_RUNNING, + 2000 + ) + , PARTY_ROUND_ROBIN( + "Party Round Robin:
Cycle through this many party members.", + LockMode::LOCK_WHILE_RUNNING, + 6, 1, 6 + ) + , DETACH_BEFORE_RELEASE( + "Detach before Release:
Needed for items like Rusted Sword/Shield.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(MAX_FETCH_ATTEMPTS); + PA_ADD_OPTION(PARTY_ROUND_ROBIN); + PA_ADD_OPTION(DETACH_BEFORE_RELEASE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + +void GodEggItemDupe::collect_godegg( + ProControllerContext& context, + uint8_t party_slot, + bool map_to_pokemon, + bool pokemon_to_map +) const{ + pbf_wait(context, 50); + ssf_press_button_ptv(context, BUTTON_B, 800ms); + ssf_press_button_ptv(context, BUTTON_B, 800ms); + pbf_wait(context, 225); + + // "You received an Egg from the Nursery worker!" + ssf_press_button_ptv(context, BUTTON_B, 2400ms); + + // "Where do you want to send the Egg to?" + ssf_press_button_ptv(context, BUTTON_A, 800ms); + + // (extra line of text for French) + ssf_press_button_ptv(context, BUTTON_B, 800ms); + + // "Please select a Pokemon to swap from your party." + ssf_press_button_ptv(context, BUTTON_B, GameSettings::instance().MENU_TO_POKEMON_DELAY0); + + // Select the party member. + for (uint8_t c = 0; c < party_slot; c++){ + ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); + } + ssf_press_button_ptv(context, BUTTON_A, 2400ms); + pbf_mash_button(context, BUTTON_B, 500); + + // Enter box + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + if (map_to_pokemon){ + ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_RIGHT, 160ms, 80ms); + } + ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, 80ms); + ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, 80ms); + + if (DETACH_BEFORE_RELEASE){ + // Detach item + ssf_press_button(context, BUTTON_A, 400ms, 160ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); + ssf_press_button(context, BUTTON_A, 1200ms, 160ms); + ssf_press_button(context, BUTTON_A, 1200ms, 160ms); + ssf_press_button(context, BUTTON_A, 800ms, 160ms); + + // Release + release(context); + }else{ + // Release (item detaches automatically) + ssf_press_button(context, BUTTON_A, 480ms, 160ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms); + ssf_press_button(context, BUTTON_A, 1000ms, 160ms); + ssf_press_dpad_ptv(context, DPAD_UP, 80ms); + ssf_mash_AZs(context, 180); + } + + // Back out to menu. + if (pokemon_to_map){ + box_to_menu(context); + ssf_press_button(context, BUTTON_B, 2000ms, 50ms); + }else{ + pbf_mash_button(context, BUTTON_B, 700); + } +} +void GodEggItemDupe::run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const{ + if (attempts == 0){ + return; + } + + uint8_t items = PARTY_ROUND_ROBIN > 6 ? 6 : PARTY_ROUND_ROBIN; + uint8_t party_slot = 0; + + uint16_t c = 0; + + // 1st Fetch: Get into position. + { + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + fly_home_collect_egg(context, true); + collect_godegg(context, party_slot++, true, false); + if (party_slot >= items){ + party_slot = 0; + } + + c++; + if (c >= attempts){ + return; + } + } + + // Now we are in steady state. + for (; c < attempts; c++){ + logger.log("Fetch Attempts: " + tostr_u_commas(c)); + eggfetcher_loop(context); + collect_egg(context); + collect_godegg(context, party_slot++, false, false); + if (party_slot >= items){ + party_slot = 0; + } + } +} + +void GodEggItemDupe::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 400); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + run_program(env.console, context, MAX_FETCH_ATTEMPTS); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h index 1cbb92d1ce..a273b4d31e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/EggPrograms/PokemonSwSh_GodEggItemDupe.h @@ -1,50 +1,50 @@ -/* God Egg Item Duplication - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_GodEggItemDupe_H -#define PokemonAutomation_PokemonSwSh_GodEggItemDupe_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh_EggHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class GodEggItemDupe_Descriptor : public SingleSwitchProgramDescriptor{ -public: - GodEggItemDupe_Descriptor(); -}; - - - -class GodEggItemDupe : public SingleSwitchProgramInstance{ -public: - GodEggItemDupe(); - - void collect_godegg(ProControllerContext& context, uint8_t party_slot, bool map_to_pokemon, bool pokemon_to_map) const; - void run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const; - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption MAX_FETCH_ATTEMPTS; - SimpleIntegerOption PARTY_ROUND_ROBIN; - BooleanCheckBoxOption DETACH_BEFORE_RELEASE; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* God Egg Item Duplication + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_GodEggItemDupe_H +#define PokemonAutomation_PokemonSwSh_GodEggItemDupe_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh_EggHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class GodEggItemDupe_Descriptor : public SingleSwitchProgramDescriptor{ +public: + GodEggItemDupe_Descriptor(); +}; + + + +class GodEggItemDupe : public SingleSwitchProgramInstance{ +public: + GodEggItemDupe(); + + void collect_godegg(ProControllerContext& context, uint8_t party_slot, bool map_to_pokemon, bool pokemon_to_map) const; + void run_program(Logger& logger, ProControllerContext& context, uint16_t attempts) const; + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption MAX_FETCH_ATTEMPTS; + SimpleIntegerOption PARTY_ROUND_ROBIN; + BooleanCheckBoxOption DETACH_BEFORE_RELEASE; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp index 3e90466244..8892d72512 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.cpp @@ -1,196 +1,196 @@ -/* Autonomous Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_AutonomousBallThrower.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:AutonomousBallThrower", - STRING_POKEMON + " SwSh", "Autonomous Ball Thrower", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/AutonomousBallThrower.md", - "Repeatedly throw a ball and reset until you catch the pokemon.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ - Stats() - : pokemon_caught(m_stats["Pokemon caught"]) - , pokemon_fainted(m_stats["Pokemon fainted"]) - , own_fainted(m_stats["Own fainted"]) - , out_of_balls(m_stats["Out of balls"]) - , errors(m_stats["Errors"]) - , total_balls_thrown(m_stats["Total balls thrown"]) - { - m_display_order.emplace_back(Stat("Pokemon caught")); - m_display_order.emplace_back(Stat("Pokemon fainted")); - m_display_order.emplace_back(Stat("Own fainted")); - m_display_order.emplace_back(Stat("Out of balls")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Total balls thrown")); - } - - std::atomic& pokemon_caught; - std::atomic& pokemon_fainted; - std::atomic& own_fainted; - std::atomic& out_of_balls; - std::atomic& errors; - std::atomic& total_balls_thrown; -}; -std::unique_ptr AutonomousBallThrower_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -AutonomousBallThrower::AutonomousBallThrower() - : GO_HOME_WHEN_DONE(false) - , BALL_SELECT( - "Ball Select:", - LockMode::LOCK_WHILE_RUNNING, - "master-ball" - ) - , LANGUAGE( - "Game Language:", - { - Language::English, - Language::Japanese, - Language::Spanish, - Language::French, - Language::German, - Language::Italian, - Language::Korean, - Language::ChineseSimplified, - Language::ChineseTraditional, - }, - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_CATCH_SUCCESS, - &NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void AutonomousBallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - AutonomousBallThrower_Descriptor::Stats& stats = env.current_stats(); - - bool pokemon_caught = false; - while (!pokemon_caught){ - context.wait_for_all_requests(); - env.log("Wait for a pokemon to attack you.", COLOR_PURPLE); - { - StandardBattleMenuWatcher fight_detector(false); - int result = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - //TODO edit here for what to do - pbf_wait(context, 1 * TICKS_PER_SECOND); - } - }, - {{fight_detector}} - ); - if (result == 0){ - env.log("New fight detected.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); - } - } - - CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); - switch (result.result){ - case CatchResult::POKEMON_CAUGHT: - pokemon_caught = true; - stats.pokemon_caught++; - break; - case CatchResult::POKEMON_FAINTED: - stats.pokemon_fainted++; - break; - case CatchResult::OWN_FAINTED: - stats.own_fainted++; - break; - case CatchResult::OUT_OF_BALLS: - stats.out_of_balls++; - break; - case CatchResult::BALL_LIMIT_REACHED: - case CatchResult::CANNOT_THROW_BALL: - case CatchResult::TIMED_OUT: - stats.errors++; - break; - } - stats.total_balls_thrown += result.balls_used; - env.update_stats(); - - if (pokemon_caught){ - send_program_status_notification( - env, NOTIFICATION_CATCH_SUCCESS, - "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." - ); - }else{ - send_program_status_notification( - env, NOTIFICATION_CATCH_FAILED, - "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." - ); - } - - if (!pokemon_caught){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - } - - env.log("Result Found!", COLOR_BLUE); - - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Caught the " + STRING_POKEMON - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} +/* Autonomous Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_AutonomousBallThrower.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +AutonomousBallThrower_Descriptor::AutonomousBallThrower_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:AutonomousBallThrower", + STRING_POKEMON + " SwSh", "Autonomous Ball Thrower", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/AutonomousBallThrower.md", + "Repeatedly throw a ball and reset until you catch the pokemon.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct AutonomousBallThrower_Descriptor::Stats : public StatsTracker{ + Stats() + : pokemon_caught(m_stats["Pokemon caught"]) + , pokemon_fainted(m_stats["Pokemon fainted"]) + , own_fainted(m_stats["Own fainted"]) + , out_of_balls(m_stats["Out of balls"]) + , errors(m_stats["Errors"]) + , total_balls_thrown(m_stats["Total balls thrown"]) + { + m_display_order.emplace_back(Stat("Pokemon caught")); + m_display_order.emplace_back(Stat("Pokemon fainted")); + m_display_order.emplace_back(Stat("Own fainted")); + m_display_order.emplace_back(Stat("Out of balls")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Total balls thrown")); + } + + std::atomic& pokemon_caught; + std::atomic& pokemon_fainted; + std::atomic& own_fainted; + std::atomic& out_of_balls; + std::atomic& errors; + std::atomic& total_balls_thrown; +}; +std::unique_ptr AutonomousBallThrower_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +AutonomousBallThrower::AutonomousBallThrower() + : GO_HOME_WHEN_DONE(false) + , BALL_SELECT( + "Ball Select:", + LockMode::LOCK_WHILE_RUNNING, + "master-ball" + ) + , LANGUAGE( + "Game Language:", + { + Language::English, + Language::Japanese, + Language::Spanish, + Language::French, + Language::German, + Language::Italian, + Language::Korean, + Language::ChineseSimplified, + Language::ChineseTraditional, + }, + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_CATCH_SUCCESS, + &NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void AutonomousBallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + AutonomousBallThrower_Descriptor::Stats& stats = env.current_stats(); + + bool pokemon_caught = false; + while (!pokemon_caught){ + context.wait_for_all_requests(); + env.log("Wait for a pokemon to attack you.", COLOR_PURPLE); + { + StandardBattleMenuWatcher fight_detector(false); + int result = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + //TODO edit here for what to do + pbf_wait(context, 1 * TICKS_PER_SECOND); + } + }, + {{fight_detector}} + ); + if (result == 0){ + env.log("New fight detected.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1 * TICKS_PER_SECOND); + } + } + + CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); + switch (result.result){ + case CatchResult::POKEMON_CAUGHT: + pokemon_caught = true; + stats.pokemon_caught++; + break; + case CatchResult::POKEMON_FAINTED: + stats.pokemon_fainted++; + break; + case CatchResult::OWN_FAINTED: + stats.own_fainted++; + break; + case CatchResult::OUT_OF_BALLS: + stats.out_of_balls++; + break; + case CatchResult::BALL_LIMIT_REACHED: + case CatchResult::CANNOT_THROW_BALL: + case CatchResult::TIMED_OUT: + stats.errors++; + break; + } + stats.total_balls_thrown += result.balls_used; + env.update_stats(); + + if (pokemon_caught){ + send_program_status_notification( + env, NOTIFICATION_CATCH_SUCCESS, + "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." + ); + }else{ + send_program_status_notification( + env, NOTIFICATION_CATCH_FAILED, + "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." + ); + } + + if (!pokemon_caught){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + } + + env.log("Result Found!", COLOR_BLUE); + + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Caught the " + STRING_POKEMON + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.h index f6fbc690ec..f62c245e49 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_AutonomousBallThrower.h @@ -1,52 +1,52 @@ -/* Autonomous Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_AutonomousStatsReset_H -#define PokemonAutomation_PokemonSwSh_AutonomousStatsReset_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class AutonomousBallThrower_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutonomousBallThrower_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class AutonomousBallThrower : public SingleSwitchProgramInstance{ -public: - AutonomousBallThrower(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - PokemonBallSelectOption BALL_SELECT; - OCR::LanguageOCROption LANGUAGE; - - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Autonomous Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_AutonomousStatsReset_H +#define PokemonAutomation_PokemonSwSh_AutonomousStatsReset_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class AutonomousBallThrower_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutonomousBallThrower_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class AutonomousBallThrower : public SingleSwitchProgramInstance{ +public: + AutonomousBallThrower(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + PokemonBallSelectOption BALL_SELECT; + OCR::LanguageOCROption LANGUAGE; + + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp index ab79d3ee4d..fa27ede9d6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.cpp @@ -1,58 +1,58 @@ -/* Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_BallThrower.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -BallThrower_Descriptor::BallThrower_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:BallThrower", - STRING_POKEMON + " SwSh", "Ball Thrower", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/BallThrower.md", - "Blindly throw balls at the opposing " + STRING_POKEMON + " until it catches.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -BallThrower::BallThrower(){ - PA_ADD_OPTION(START_LOCATION); -} - -void BallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); - }else{ - pbf_press_button(context, BUTTON_X, 5, 5); - } - - while (true){ - pbf_press_button(context, BUTTON_X, 50, 50); - pbf_press_button(context, BUTTON_A, 50, 50); - pbf_mash_button(context, BUTTON_B, 100); - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); -} - - - -} -} -} +/* Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_BallThrower.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +BallThrower_Descriptor::BallThrower_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:BallThrower", + STRING_POKEMON + " SwSh", "Ball Thrower", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/BallThrower.md", + "Blindly throw balls at the opposing " + STRING_POKEMON + " until it catches.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +BallThrower::BallThrower(){ + PA_ADD_OPTION(START_LOCATION); +} + +void BallThrower::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); + }else{ + pbf_press_button(context, BUTTON_X, 5, 5); + } + + while (true){ + pbf_press_button(context, BUTTON_X, 50, 50); + pbf_press_button(context, BUTTON_A, 50, 50); + pbf_mash_button(context, BUTTON_B, 100); + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.h index 5f96a4fad9..00918d2243 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BallThrower.h @@ -1,41 +1,41 @@ -/* Ball Thrower - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BallThrower_H -#define PokemonAutomation_PokemonSwSh_BallThrower_H - -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BallThrower_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BallThrower_Descriptor(); -}; - - - -class BallThrower : public SingleSwitchProgramInstance{ -public: - BallThrower(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; -}; - -} -} -} -#endif - - - +/* Ball Thrower + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BallThrower_H +#define PokemonAutomation_PokemonSwSh_BallThrower_H + +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BallThrower_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BallThrower_Descriptor(); +}; + + + +class BallThrower : public SingleSwitchProgramInstance{ +public: + BallThrower(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.cpp index f5191960d4..a73972c541 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.cpp @@ -1,238 +1,238 @@ -/* Box Reorder National Dex - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include -#include "CommonFramework/Language.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_BoxReorderNationalDex.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -namespace{ - -constexpr uint16_t k_wait_after_move = (uint16_t)(TICKS_PER_SECOND / 1.5); -constexpr std::chrono::milliseconds k_wait_after_read = std::chrono::milliseconds(200); - -// A location can be represented as a uint16_t, meaning the order of the location starting at the first box. -// This function decodes this location into box ID and in-box 2D location. -std::tuple get_location(size_t index){ - uint16_t box = (uint16_t)(index / 30); - index = index % 30; - - uint16_t row = (uint16_t)(index / 6); - index = index % 6; - - uint16_t column = (uint16_t)(index); - return { box, row, column }; -} - -// Move cursor from one location to another -// The location is represented as a uint16_t, meaning the order of the location starting at the first box. -// Decode this location into box ID and in-box 2D location by `get_location()` -uint16_t move_to_location(Logger& logger, ProControllerContext& context, uint16_t from, uint16_t to){ - auto [from_box, from_row, from_column] = get_location(from); - auto [to_box, to_row, to_column] = get_location(to); - - std::ostringstream ss; - ss << "Moving from location index " << from << "(" << from_box << "/" << from_row << "/" << from_column << ")"; - ss << " to location index " << to << "(" << to_box << "/" << to_row << "/" << to_column << ")"; - logger.log(ss.str()); - - int difference_box = to_box - from_box; - int difference_row = to_row - from_row; - int difference_column = to_column - from_column; - - // TODO: can make this more efficient by moving past grid boundary to appear at the other side - - for (int i = 0; i < difference_box; ++i){ - pbf_press_button(context, BUTTON_R, 10, k_wait_after_move); - } - for (int i = 0; i > difference_box; --i){ - pbf_press_button(context, BUTTON_L, 10, k_wait_after_move); - } - - for (int i = 0; i < difference_row; ++i){ - pbf_press_dpad(context, DPAD_DOWN, 10, k_wait_after_move); - } - for (int i = 0; i > difference_row; --i){ - pbf_press_dpad(context, DPAD_UP, 10, k_wait_after_move); - } - - for (int i = 0; i < difference_column; ++i){ - pbf_press_dpad(context, DPAD_RIGHT, 10, k_wait_after_move); - } - for (int i = 0; i > difference_column; --i){ - pbf_press_dpad(context, DPAD_LEFT, 10, k_wait_after_move); - } - return to; -} - -// Read the current displayed pokemon name. Return the pokemon slug. -// -// A slug is a unique name used in a program, different than the name that is displayed to user on UI. -// In most cases, a pokemon slug is the lower-case version of the Pokemon name, but there are some cases -// like the slug of the Pokemon Mr. Mime is "mr-mime". -std::string read_selected_pokemon( - VideoStream& stream, ProControllerContext& context, - Language language -){ - context.wait_for_all_requests(); - OverlayBoxScope box(stream.overlay(), ImageFloatBox(0.76, 0.08, 0.15, 0.064)); - context.wait_for(k_wait_after_read); - - VideoSnapshot screen = stream.video().snapshot(); - ImageViewRGB32 frame = extract_box_reference(screen, box); - - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - stream.logger(), language, frame, - OCR::BLACK_TEXT_FILTERS() - ); - result.log(stream.logger(), PokemonNameReader::MAX_LOG10P); -// assert(result.results.size() == 1); - if (result.results.size() != 1){ - return ""; - } - return result.results.begin()->second.token; -} - -// Move through some pokemon according to the box location order and read their names. -// Return a list of pokemon slugs. -std::vector read_all_pokemon( - Logger& logger, - VideoStream& stream, ProControllerContext& context, - uint16_t pokemon_count, - Language language -){ - std::vector pokemons; - uint16_t current_location = 0; - for (uint16_t i = 0; i < pokemon_count; ++i){ - current_location = move_to_location(logger, context, current_location, i); - pokemons.push_back(read_selected_pokemon(stream, context, language)); - } - return pokemons; -} - -} - -BoxReorderNationalDex_Descriptor::BoxReorderNationalDex_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:BoxReorderNationalDex", - STRING_POKEMON + " SwSh", "Box Reorder National Dex", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/BoxReorderNationalDex.md", - "Order boxes of " + STRING_POKEMON + ".", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -BoxReorderNationalDex::BoxReorderNationalDex() - : LANGUAGE( - "Game Language:
This needs to be set correctly for " + STRING_POKEMON + " to be identified correctly.", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , POKEMON_COUNT( - "Number of " + STRING_POKEMON + " to order:", - LockMode::LOCK_WHILE_RUNNING, - 30 - ) - , DODGE_SYSTEM_UPDATE_WINDOW( - "Dodge System Update Window:", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(POKEMON_COUNT); - PA_ADD_OPTION(DODGE_SYSTEM_UPDATE_WINDOW); -} - -void BoxReorderNationalDex::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, DODGE_SYSTEM_UPDATE_WINDOW); - }else{ - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - } - - // Read all the pokemon and return a list of their slugs in the current box order. - std::vector current_order = read_all_pokemon(env.console, env.console, context, POKEMON_COUNT, LANGUAGE); - - // The list of pokemon slugs in national order. - const std::vector& dex_slugs = NATIONAL_DEX_SLUGS(); - // Build a map of slug -> national dex ID for fast lookup - std::map dex_slug_order; - for(size_t i = 0; i < dex_slugs.size(); ++i){ - dex_slug_order.emplace(dex_slugs[i], i); - } - - // Sort the read pokemon by the dex order. - std::vector sorted_order = current_order; - - std::sort(sorted_order.begin(), sorted_order.end(), [&](const std::string& str1, const std::string& str2){ - const size_t id1 = dex_slug_order.find(str1)->second; - const size_t id2 = dex_slug_order.find(str2)->second; - return id1 < id2; - }); - - // Now the cursor is at the last pokemon: - uint16_t current_location = POKEMON_COUNT - 1; - for (uint16_t index = 0; index < current_order.size(); ++index){ - if (current_order[index] == sorted_order[index]){ - continue; - } - - const auto it = std::find(current_order.begin() + index, current_order.end(), sorted_order[index]); - // Where the pokemon should be moved from - const uint16_t unsorted_location = (uint16_t)(it - current_order.begin()); - // Where the pokemon should be moved to - const uint16_t sorted_location = index; - - std::ostringstream ss; - ss << "Swapping " << current_order[unsorted_location] << " at location index " << unsorted_location << " and " << current_order[sorted_location] << " at location index " << sorted_location; - env.console.log(ss.str()); - // Move the cursor to the unsorted_location - current_location = move_to_location(env.console, context, current_location, unsorted_location); - // Press A to grab the pokemon - pbf_press_button(context, BUTTON_A, 10, k_wait_after_move); - // Move the cursor to the sorted_location - current_location = move_to_location(env.console, context, current_location, sorted_location); - // Press A to finish swapping the pokemon - pbf_press_button(context, BUTTON_A, 10, k_wait_after_move); - // Now the order in the box is changed, update `current_order` to reflect this change. - std::swap(current_order[unsorted_location], current_order[sorted_location]); - } - - // Go to Switch home menu - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); -} - - - -} -} -} - +/* Box Reorder National Dex + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include +#include "CommonFramework/Language.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_BoxReorderNationalDex.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +namespace{ + +constexpr uint16_t k_wait_after_move = (uint16_t)(TICKS_PER_SECOND / 1.5); +constexpr std::chrono::milliseconds k_wait_after_read = std::chrono::milliseconds(200); + +// A location can be represented as a uint16_t, meaning the order of the location starting at the first box. +// This function decodes this location into box ID and in-box 2D location. +std::tuple get_location(size_t index){ + uint16_t box = (uint16_t)(index / 30); + index = index % 30; + + uint16_t row = (uint16_t)(index / 6); + index = index % 6; + + uint16_t column = (uint16_t)(index); + return { box, row, column }; +} + +// Move cursor from one location to another +// The location is represented as a uint16_t, meaning the order of the location starting at the first box. +// Decode this location into box ID and in-box 2D location by `get_location()` +uint16_t move_to_location(Logger& logger, ProControllerContext& context, uint16_t from, uint16_t to){ + auto [from_box, from_row, from_column] = get_location(from); + auto [to_box, to_row, to_column] = get_location(to); + + std::ostringstream ss; + ss << "Moving from location index " << from << "(" << from_box << "/" << from_row << "/" << from_column << ")"; + ss << " to location index " << to << "(" << to_box << "/" << to_row << "/" << to_column << ")"; + logger.log(ss.str()); + + int difference_box = to_box - from_box; + int difference_row = to_row - from_row; + int difference_column = to_column - from_column; + + // TODO: can make this more efficient by moving past grid boundary to appear at the other side + + for (int i = 0; i < difference_box; ++i){ + pbf_press_button(context, BUTTON_R, 10, k_wait_after_move); + } + for (int i = 0; i > difference_box; --i){ + pbf_press_button(context, BUTTON_L, 10, k_wait_after_move); + } + + for (int i = 0; i < difference_row; ++i){ + pbf_press_dpad(context, DPAD_DOWN, 10, k_wait_after_move); + } + for (int i = 0; i > difference_row; --i){ + pbf_press_dpad(context, DPAD_UP, 10, k_wait_after_move); + } + + for (int i = 0; i < difference_column; ++i){ + pbf_press_dpad(context, DPAD_RIGHT, 10, k_wait_after_move); + } + for (int i = 0; i > difference_column; --i){ + pbf_press_dpad(context, DPAD_LEFT, 10, k_wait_after_move); + } + return to; +} + +// Read the current displayed pokemon name. Return the pokemon slug. +// +// A slug is a unique name used in a program, different than the name that is displayed to user on UI. +// In most cases, a pokemon slug is the lower-case version of the Pokemon name, but there are some cases +// like the slug of the Pokemon Mr. Mime is "mr-mime". +std::string read_selected_pokemon( + VideoStream& stream, ProControllerContext& context, + Language language +){ + context.wait_for_all_requests(); + OverlayBoxScope box(stream.overlay(), ImageFloatBox(0.76, 0.08, 0.15, 0.064)); + context.wait_for(k_wait_after_read); + + VideoSnapshot screen = stream.video().snapshot(); + ImageViewRGB32 frame = extract_box_reference(screen, box); + + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + stream.logger(), language, frame, + OCR::BLACK_TEXT_FILTERS() + ); + result.log(stream.logger(), PokemonNameReader::MAX_LOG10P); +// assert(result.results.size() == 1); + if (result.results.size() != 1){ + return ""; + } + return result.results.begin()->second.token; +} + +// Move through some pokemon according to the box location order and read their names. +// Return a list of pokemon slugs. +std::vector read_all_pokemon( + Logger& logger, + VideoStream& stream, ProControllerContext& context, + uint16_t pokemon_count, + Language language +){ + std::vector pokemons; + uint16_t current_location = 0; + for (uint16_t i = 0; i < pokemon_count; ++i){ + current_location = move_to_location(logger, context, current_location, i); + pokemons.push_back(read_selected_pokemon(stream, context, language)); + } + return pokemons; +} + +} + +BoxReorderNationalDex_Descriptor::BoxReorderNationalDex_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:BoxReorderNationalDex", + STRING_POKEMON + " SwSh", "Box Reorder National Dex", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/BoxReorderNationalDex.md", + "Order boxes of " + STRING_POKEMON + ".", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +BoxReorderNationalDex::BoxReorderNationalDex() + : LANGUAGE( + "Game Language:
This needs to be set correctly for " + STRING_POKEMON + " to be identified correctly.", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , POKEMON_COUNT( + "Number of " + STRING_POKEMON + " to order:", + LockMode::LOCK_WHILE_RUNNING, + 30 + ) + , DODGE_SYSTEM_UPDATE_WINDOW( + "Dodge System Update Window:", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(POKEMON_COUNT); + PA_ADD_OPTION(DODGE_SYSTEM_UPDATE_WINDOW); +} + +void BoxReorderNationalDex::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, DODGE_SYSTEM_UPDATE_WINDOW); + }else{ + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + } + + // Read all the pokemon and return a list of their slugs in the current box order. + std::vector current_order = read_all_pokemon(env.console, env.console, context, POKEMON_COUNT, LANGUAGE); + + // The list of pokemon slugs in national order. + const std::vector& dex_slugs = NATIONAL_DEX_SLUGS(); + // Build a map of slug -> national dex ID for fast lookup + std::map dex_slug_order; + for(size_t i = 0; i < dex_slugs.size(); ++i){ + dex_slug_order.emplace(dex_slugs[i], i); + } + + // Sort the read pokemon by the dex order. + std::vector sorted_order = current_order; + + std::sort(sorted_order.begin(), sorted_order.end(), [&](const std::string& str1, const std::string& str2){ + const size_t id1 = dex_slug_order.find(str1)->second; + const size_t id2 = dex_slug_order.find(str2)->second; + return id1 < id2; + }); + + // Now the cursor is at the last pokemon: + uint16_t current_location = POKEMON_COUNT - 1; + for (uint16_t index = 0; index < current_order.size(); ++index){ + if (current_order[index] == sorted_order[index]){ + continue; + } + + const auto it = std::find(current_order.begin() + index, current_order.end(), sorted_order[index]); + // Where the pokemon should be moved from + const uint16_t unsorted_location = (uint16_t)(it - current_order.begin()); + // Where the pokemon should be moved to + const uint16_t sorted_location = index; + + std::ostringstream ss; + ss << "Swapping " << current_order[unsorted_location] << " at location index " << unsorted_location << " and " << current_order[sorted_location] << " at location index " << sorted_location; + env.console.log(ss.str()); + // Move the cursor to the unsorted_location + current_location = move_to_location(env.console, context, current_location, unsorted_location); + // Press A to grab the pokemon + pbf_press_button(context, BUTTON_A, 10, k_wait_after_move); + // Move the cursor to the sorted_location + current_location = move_to_location(env.console, context, current_location, sorted_location); + // Press A to finish swapping the pokemon + pbf_press_button(context, BUTTON_A, 10, k_wait_after_move); + // Now the order in the box is changed, update `current_order` to reflect this change. + std::swap(current_order[unsorted_location], current_order[sorted_location]); + } + + // Go to Switch home menu + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.h index d7bc2f11e7..686b01815e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_BoxReorderNationalDex.h @@ -1,46 +1,46 @@ -/* Box Reorder National Dex - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Ordering_H -#define PokemonAutomation_PokemonSwSh_Ordering_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class BoxReorderNationalDex_Descriptor : public SingleSwitchProgramDescriptor{ -public: - BoxReorderNationalDex_Descriptor(); -}; - - - -class BoxReorderNationalDex : public SingleSwitchProgramInstance{ -public: - BoxReorderNationalDex(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - OCR::LanguageOCROption LANGUAGE; - SimpleIntegerOption POKEMON_COUNT; - BooleanCheckBoxOption DODGE_SYSTEM_UPDATE_WINDOW; -}; - - -} -} -} -#endif - +/* Box Reorder National Dex + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Ordering_H +#define PokemonAutomation_PokemonSwSh_Ordering_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class BoxReorderNationalDex_Descriptor : public SingleSwitchProgramDescriptor{ +public: + BoxReorderNationalDex_Descriptor(); +}; + + + +class BoxReorderNationalDex : public SingleSwitchProgramInstance{ +public: + BoxReorderNationalDex(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + OCR::LanguageOCROption LANGUAGE; + SimpleIntegerOption POKEMON_COUNT; + BooleanCheckBoxOption DODGE_SYSTEM_UPDATE_WINDOW; +}; + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.cpp index cac441c514..731c6c68e8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.cpp @@ -1,67 +1,67 @@ -/* Clothing Buyer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_ClothingBuyer.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -ClothingBuyer_Descriptor::ClothingBuyer_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ClothingBuyer", - STRING_POKEMON + " SwSh", "Clothing Buyer", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ClothingBuyer.md", - "Buy out all the clothing in a store.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -ClothingBuyer::ClothingBuyer() - : CATEGORY_ROTATION( - "Rotate Categories:
This slows down the program, but ensures it will cover all categories.", - LockMode::LOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(CATEGORY_ROTATION); -} - -void ClothingBuyer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - } - - while (true){ - pbf_press_button(context, BUTTON_A, 10, 90); - if (CATEGORY_ROTATION){ - pbf_press_dpad(context, DPAD_RIGHT, 10, 40); - } - pbf_press_button(context, BUTTON_A, 10, 90); - pbf_press_button(context, BUTTON_A, 10, 90); - pbf_press_dpad(context, DPAD_DOWN, 10, 40); - } -} - - -} -} -} +/* Clothing Buyer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_ClothingBuyer.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +ClothingBuyer_Descriptor::ClothingBuyer_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ClothingBuyer", + STRING_POKEMON + " SwSh", "Clothing Buyer", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ClothingBuyer.md", + "Buy out all the clothing in a store.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +ClothingBuyer::ClothingBuyer() + : CATEGORY_ROTATION( + "Rotate Categories:
This slows down the program, but ensures it will cover all categories.", + LockMode::LOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(CATEGORY_ROTATION); +} + +void ClothingBuyer::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + } + + while (true){ + pbf_press_button(context, BUTTON_A, 10, 90); + if (CATEGORY_ROTATION){ + pbf_press_dpad(context, DPAD_RIGHT, 10, 40); + } + pbf_press_button(context, BUTTON_A, 10, 90); + pbf_press_button(context, BUTTON_A, 10, 90); + pbf_press_dpad(context, DPAD_DOWN, 10, 40); + } +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.h index 01e3f17eb9..ea8a8b2d5e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_ClothingBuyer.h @@ -1,45 +1,45 @@ -/* Clothing Buyer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ClothingBuyer_H -#define PokemonAutomation_PokemonSwSh_ClothingBuyer_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ClothingBuyer_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ClothingBuyer_Descriptor(); -}; - - - -class ClothingBuyer : public SingleSwitchProgramInstance{ -public: - ClothingBuyer(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - BooleanCheckBoxOption CATEGORY_ROTATION; -}; - - - -} -} -} -#endif - - - +/* Clothing Buyer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ClothingBuyer_H +#define PokemonAutomation_PokemonSwSh_ClothingBuyer_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ClothingBuyer_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ClothingBuyer_Descriptor(); +}; + + + +class ClothingBuyer : public SingleSwitchProgramInstance{ +public: + ClothingBuyer(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + BooleanCheckBoxOption CATEGORY_ROTATION; +}; + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.cpp index cb8fa3e5d1..aeba825908 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.cpp @@ -1,256 +1,256 @@ -/* Pokedex Recommendation Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h" -#include "PokemonSwSh_DexRecFinder.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - - -DexRecFinder_Descriptor::DexRecFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DexRecFinder", - STRING_POKEMON + " SwSh", "Dex Rec Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DexRecFinder.md", - "Search for a " + STRING_POKEDEX + " recommendation by date-spamming.", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -struct DexRecFinder_Descriptor::Stats : public StatsTracker{ - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Read Errors"]) - , excluded(m_stats["Excluded"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back(Stat("Attempts")); - m_display_order.emplace_back(Stat("Read Errors")); - m_display_order.emplace_back(Stat("Excluded")); - m_display_order.emplace_back(Stat("Matches")); - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& excluded; - std::atomic& matches; -}; -std::unique_ptr DexRecFinder_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -DexRecFilters::DexRecFilters() - : GroupOption( - "Stop Automatically (requires video feedback)", - LockMode::LOCK_WHILE_RUNNING, - GroupOption::EnableMode::DEFAULT_ENABLED - ) - , LANGUAGE( - "Game Language:
This needs to be set correctly for stop filters to work correctly.", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , DESIRED( - "Desired " + STRING_POKEMON + ":
Stop when it finds this " + STRING_POKEMON + ". Requires the language be set.", - COMBINED_DEX_NAMES(), - LockMode::LOCK_WHILE_RUNNING, - "ralts" - ) - , EXCLUSIONS( - "Exclusions:
Do not stop on these " + STRING_POKEMON + " even if the desired " + STRING_POKEMON + " is found. " - "Use this to avoid dex recs that include other " + STRING_POKEMON + " in the spawn pool you don't want.", - STRING_POKEMON, COMBINED_DEX_NAMES(), "grubbin" - ) -{ - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(DESIRED); - PA_ADD_OPTION(EXCLUSIONS); -} - - - -DexRecFinder::DexRecFinder() - : GO_HOME_WHEN_DONE(false) - , VIEW_TIME0( - "View Time:
View the " + STRING_POKEDEX + " for this long before continuing.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true, ImageAttachmentMode::JPG) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , ENTER_POKEDEX_TIME0( - "Enter " + STRING_POKEDEX + " Time:
Wait this long for the " + STRING_POKEDEX + " to open.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , BACK_OUT_TIME0( - "Back Out Time:
Mash B for this long to return to the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(FILTERS); - PA_ADD_OPTION(VIEW_TIME0); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(ENTER_POKEDEX_TIME0); - PA_ADD_OPTION(BACK_OUT_TIME0); -} - - -void DexRecFinder::read_line( - bool& found, - bool& excluded, - bool& bad_read, - Logger& logger, - Language language, - const ImageViewRGB32& frame, - const ImageFloatBox& box, - const std::set& desired, - const std::set& exclusions -){ - ImageViewRGB32 image = extract_box_reference(frame, box); - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - logger, language, image, - OCR::BLACK_TEXT_FILTERS() - ); - if (result.results.empty()){ - bad_read = true; - return; - } - for (const auto& hit : result.results){ - if (desired.find(hit.second.token) != desired.end()){ - found = true; - } - if (exclusions.find(hit.second.token) != exclusions.end()){ - excluded = true; - } - } -} - -void DexRecFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - } - - std::set desired; - desired.insert(FILTERS.DESIRED.slug()); - - std::set exclusions; - for (std::string& slug : FILTERS.EXCLUSIONS.all_slugs()){ - exclusions.insert(std::move(slug)); - } - - DexRecFinder_Descriptor::Stats& stats = env.current_stats(); - - while (true){ - home_to_date_time(env.console, context, true); - neutral_date_skip(env.console, context); - settings_to_enter_game(context, true); - pbf_mash_button(context, BUTTON_B, 90); - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - - if (FILTERS.enabled()){ - context.wait_for_all_requests(); - OverlayBoxScope box0(env.console, ImageFloatBox(0.75, 0.531 + 0 * 0.1115, 0.18, 0.059)); - OverlayBoxScope box1(env.console, ImageFloatBox(0.75, 0.531 + 1 * 0.1115, 0.18, 0.059)); - OverlayBoxScope box2(env.console, ImageFloatBox(0.75, 0.531 + 2 * 0.1115, 0.18, 0.059)); - OverlayBoxScope box3(env.console, ImageFloatBox(0.75, 0.531 + 3 * 0.1115, 0.18, 0.059)); - pbf_press_button(context, BUTTON_A, 80ms, ENTER_POKEDEX_TIME0); - context.wait_for_all_requests(); - - VideoSnapshot frame = env.console.video().snapshot(); - bool found = false; - bool excluded = false; - bool bad_read = false; - if (!frame){ - bad_read = true; - }else{ - read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box0, desired, exclusions); - read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box1, desired, exclusions); - read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box2, desired, exclusions); - read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box3, desired, exclusions); - } - - stats.attempts++; - if (found){ - if (excluded){ - env.log("Found desired, but contains exclusion.", COLOR_BLUE); - stats.excluded++; - }else{ - env.log("Found a match!", COLOR_BLUE); - stats.matches++; - break; - } - } - if (bad_read){ - env.log("Read Errors. Pausing for user to see.", COLOR_RED); - stats.errors++; - pbf_wait(context, VIEW_TIME0); - } - }else{ - stats.attempts++; -// stats.errors++; - pbf_press_button(context, BUTTON_A, 80ms, ENTER_POKEDEX_TIME0); - pbf_wait(context, VIEW_TIME0); - } - env.update_stats(); - - pbf_mash_button(context, BUTTON_B, BACK_OUT_TIME0); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - } - - env.update_stats(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Found a match!", - env.console.video().snapshot(), false - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} +/* Pokedex Recommendation Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_NeutralDateSkip.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h" +#include "PokemonSwSh_DexRecFinder.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + + +DexRecFinder_Descriptor::DexRecFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DexRecFinder", + STRING_POKEMON + " SwSh", "Dex Rec Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DexRecFinder.md", + "Search for a " + STRING_POKEDEX + " recommendation by date-spamming.", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +struct DexRecFinder_Descriptor::Stats : public StatsTracker{ + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Read Errors"]) + , excluded(m_stats["Excluded"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back(Stat("Attempts")); + m_display_order.emplace_back(Stat("Read Errors")); + m_display_order.emplace_back(Stat("Excluded")); + m_display_order.emplace_back(Stat("Matches")); + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& excluded; + std::atomic& matches; +}; +std::unique_ptr DexRecFinder_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +DexRecFilters::DexRecFilters() + : GroupOption( + "Stop Automatically (requires video feedback)", + LockMode::LOCK_WHILE_RUNNING, + GroupOption::EnableMode::DEFAULT_ENABLED + ) + , LANGUAGE( + "Game Language:
This needs to be set correctly for stop filters to work correctly.", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , DESIRED( + "Desired " + STRING_POKEMON + ":
Stop when it finds this " + STRING_POKEMON + ". Requires the language be set.", + COMBINED_DEX_NAMES(), + LockMode::LOCK_WHILE_RUNNING, + "ralts" + ) + , EXCLUSIONS( + "Exclusions:
Do not stop on these " + STRING_POKEMON + " even if the desired " + STRING_POKEMON + " is found. " + "Use this to avoid dex recs that include other " + STRING_POKEMON + " in the spawn pool you don't want.", + STRING_POKEMON, COMBINED_DEX_NAMES(), "grubbin" + ) +{ + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(DESIRED); + PA_ADD_OPTION(EXCLUSIONS); +} + + + +DexRecFinder::DexRecFinder() + : GO_HOME_WHEN_DONE(false) + , VIEW_TIME0( + "View Time:
View the " + STRING_POKEDEX + " for this long before continuing.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true, ImageAttachmentMode::JPG) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , ENTER_POKEDEX_TIME0( + "Enter " + STRING_POKEDEX + " Time:
Wait this long for the " + STRING_POKEDEX + " to open.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , BACK_OUT_TIME0( + "Back Out Time:
Mash B for this long to return to the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(FILTERS); + PA_ADD_OPTION(VIEW_TIME0); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(ENTER_POKEDEX_TIME0); + PA_ADD_OPTION(BACK_OUT_TIME0); +} + + +void DexRecFinder::read_line( + bool& found, + bool& excluded, + bool& bad_read, + Logger& logger, + Language language, + const ImageViewRGB32& frame, + const ImageFloatBox& box, + const std::set& desired, + const std::set& exclusions +){ + ImageViewRGB32 image = extract_box_reference(frame, box); + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + logger, language, image, + OCR::BLACK_TEXT_FILTERS() + ); + if (result.results.empty()){ + bad_read = true; + return; + } + for (const auto& hit : result.results){ + if (desired.find(hit.second.token) != desired.end()){ + found = true; + } + if (exclusions.find(hit.second.token) != exclusions.end()){ + excluded = true; + } + } +} + +void DexRecFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + } + + std::set desired; + desired.insert(FILTERS.DESIRED.slug()); + + std::set exclusions; + for (std::string& slug : FILTERS.EXCLUSIONS.all_slugs()){ + exclusions.insert(std::move(slug)); + } + + DexRecFinder_Descriptor::Stats& stats = env.current_stats(); + + while (true){ + home_to_date_time(env.console, context, true); + neutral_date_skip(env.console, context); + settings_to_enter_game(context, true); + pbf_mash_button(context, BUTTON_B, 90); + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + + if (FILTERS.enabled()){ + context.wait_for_all_requests(); + OverlayBoxScope box0(env.console, ImageFloatBox(0.75, 0.531 + 0 * 0.1115, 0.18, 0.059)); + OverlayBoxScope box1(env.console, ImageFloatBox(0.75, 0.531 + 1 * 0.1115, 0.18, 0.059)); + OverlayBoxScope box2(env.console, ImageFloatBox(0.75, 0.531 + 2 * 0.1115, 0.18, 0.059)); + OverlayBoxScope box3(env.console, ImageFloatBox(0.75, 0.531 + 3 * 0.1115, 0.18, 0.059)); + pbf_press_button(context, BUTTON_A, 80ms, ENTER_POKEDEX_TIME0); + context.wait_for_all_requests(); + + VideoSnapshot frame = env.console.video().snapshot(); + bool found = false; + bool excluded = false; + bool bad_read = false; + if (!frame){ + bad_read = true; + }else{ + read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box0, desired, exclusions); + read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box1, desired, exclusions); + read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box2, desired, exclusions); + read_line(found, excluded, bad_read, env.console, FILTERS.LANGUAGE, frame, box3, desired, exclusions); + } + + stats.attempts++; + if (found){ + if (excluded){ + env.log("Found desired, but contains exclusion.", COLOR_BLUE); + stats.excluded++; + }else{ + env.log("Found a match!", COLOR_BLUE); + stats.matches++; + break; + } + } + if (bad_read){ + env.log("Read Errors. Pausing for user to see.", COLOR_RED); + stats.errors++; + pbf_wait(context, VIEW_TIME0); + } + }else{ + stats.attempts++; +// stats.errors++; + pbf_press_button(context, BUTTON_A, 80ms, ENTER_POKEDEX_TIME0); + pbf_wait(context, VIEW_TIME0); + } + env.update_stats(); + + pbf_mash_button(context, BUTTON_B, BACK_OUT_TIME0); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + } + + env.update_stats(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Found a match!", + env.console.video().snapshot(), false + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.h index ebd0e73f3c..d7980ec798 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_DexRecFinder.h @@ -1,85 +1,85 @@ -/* Pokedex Recommendation Finder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DexRecFinder_H -#define PokemonAutomation_PokemonSwSh_DexRecFinder_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonTools/Options/StringSelectTableOption.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class DexRecFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DexRecFinder_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class DexRecFilters : public GroupOption{ -public: - DexRecFilters(); - - OCR::LanguageOCROption LANGUAGE; - StringSelectOption DESIRED; - StringSelectTableOption EXCLUSIONS; -}; - - -class DexRecFinder : public SingleSwitchProgramInstance{ -public: - DexRecFinder(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void read_line( - bool& found, - bool& excluded, - bool& bad_read, - Logger& logger, - Language language, - const ImageViewRGB32& frame, - const ImageFloatBox& box, - const std::set& desired, - const std::set& exclusions - ); - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - DexRecFilters FILTERS; - MillisecondsOption VIEW_TIME0; - - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption ENTER_POKEDEX_TIME0; - MillisecondsOption BACK_OUT_TIME0; -}; - -} -} -} -#endif - - - +/* Pokedex Recommendation Finder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DexRecFinder_H +#define PokemonAutomation_PokemonSwSh_DexRecFinder_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonTools/Options/StringSelectTableOption.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class DexRecFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DexRecFinder_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class DexRecFilters : public GroupOption{ +public: + DexRecFilters(); + + OCR::LanguageOCROption LANGUAGE; + StringSelectOption DESIRED; + StringSelectTableOption EXCLUSIONS; +}; + + +class DexRecFinder : public SingleSwitchProgramInstance{ +public: + DexRecFinder(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void read_line( + bool& found, + bool& excluded, + bool& bad_read, + Logger& logger, + Language language, + const ImageViewRGB32& frame, + const ImageFloatBox& box, + const std::set& desired, + const std::set& exclusions + ); + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + DexRecFilters FILTERS; + MillisecondsOption VIEW_TIME0; + + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption ENTER_POKEDEX_TIME0; + MillisecondsOption BACK_OUT_TIME0; +}; + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.cpp index a34b49facf..ebaaa2a05e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.cpp @@ -1,69 +1,69 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h" -#include "PokemonSwSh_MassRelease.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -MassRelease_Descriptor::MassRelease_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:MassRelease", - STRING_POKEMON + " SwSh", "Mass Release", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MassRelease.md", - "Mass release boxes of " + STRING_POKEMON + ".", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} - - - -MassRelease::MassRelease() - : BOXES_TO_RELEASE( - "Number of Boxes to Release:", - LockMode::LOCK_WHILE_RUNNING, - 2, 0, 32 - ) - , DODGE_SYSTEM_UPDATE_WINDOW( - "Dodge System Update Window:", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(BOXES_TO_RELEASE); - PA_ADD_OPTION(DODGE_SYSTEM_UPDATE_WINDOW); -} - -void MassRelease::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, DODGE_SYSTEM_UPDATE_WINDOW); - }else{ - pbf_press_button(context, BUTTON_LCLICK, 5, 5); - } - - release_boxes(context, BOXES_TO_RELEASE); - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); -} - - - -} -} -} - +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h" +#include "PokemonSwSh_MassRelease.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +MassRelease_Descriptor::MassRelease_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:MassRelease", + STRING_POKEMON + " SwSh", "Mass Release", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MassRelease.md", + "Mass release boxes of " + STRING_POKEMON + ".", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} + + + +MassRelease::MassRelease() + : BOXES_TO_RELEASE( + "Number of Boxes to Release:", + LockMode::LOCK_WHILE_RUNNING, + 2, 0, 32 + ) + , DODGE_SYSTEM_UPDATE_WINDOW( + "Dodge System Update Window:", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(BOXES_TO_RELEASE); + PA_ADD_OPTION(DODGE_SYSTEM_UPDATE_WINDOW); +} + +void MassRelease::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, DODGE_SYSTEM_UPDATE_WINDOW); + }else{ + pbf_press_button(context, BUTTON_LCLICK, 5, 5); + } + + release_boxes(context, BOXES_TO_RELEASE); + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.h index fbac8c2ee9..47959d8885 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_MassRelease.h @@ -1,44 +1,44 @@ -/* Mass Release - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MassRelease_H -#define PokemonAutomation_PokemonSwSh_MassRelease_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class MassRelease_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MassRelease_Descriptor(); -}; - - - -class MassRelease : public SingleSwitchProgramInstance{ -public: - MassRelease(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption BOXES_TO_RELEASE; - BooleanCheckBoxOption DODGE_SYSTEM_UPDATE_WINDOW; -}; - - -} -} -} -#endif - +/* Mass Release + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MassRelease_H +#define PokemonAutomation_PokemonSwSh_MassRelease_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class MassRelease_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MassRelease_Descriptor(); +}; + + + +class MassRelease : public SingleSwitchProgramInstance{ +public: + MassRelease(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption BOXES_TO_RELEASE; + BooleanCheckBoxOption DODGE_SYSTEM_UPDATE_WINDOW; +}; + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp index 47c9a2e336..e63e008aff 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.cpp @@ -1,151 +1,151 @@ -/* Surprise Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh_SurpriseTrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -SurpriseTrade_Descriptor::SurpriseTrade_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:SurpriseTrade", - STRING_POKEMON + " SwSh", "Surprise Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/SurpriseTrade.md", - "Surprise trade away boxes of " + STRING_POKEMON, - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -SurpriseTrade::SurpriseTrade() - : BOXES_TO_TRADE( - "Number of Boxes to Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2 - ) - , INITIAL_WAIT0( - "Time to wait for a Trade Partner:", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , TRADE_ANIMATION0( - "Trade Animation Time:", - LockMode::LOCK_WHILE_RUNNING, - "23 s" - ) - , EVOLVE_DELAY0( - "Evolve Delay:", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(INITIAL_WAIT0); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(TRADE_ANIMATION0); - PA_ADD_OPTION(EVOLVE_DELAY0); -} - - -void SurpriseTrade::trade_slot(ProControllerContext& context, uint8_t slot, bool next_box) const{ - ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); - ssf_press_dpad(context, DPAD_DOWN, 80ms); - ssf_press_button(context, BUTTON_A, 2240ms, 160ms); - - if (next_box){ - ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0); - } - - // Move to slot - while (slot >= 6){ - box_scroll(context, DPAD_DOWN); - slot -= 6; - } - while (slot > 0){ - box_scroll(context, DPAD_RIGHT); - slot--; - } - - ssf_press_button(context, BUTTON_A, 400ms); - ssf_press_button(context, BUTTON_A, 4000ms); - ssf_press_button(context, BUTTON_A, 800ms); - ssf_press_button(context, BUTTON_A, 800ms); - - pbf_mash_button(context, BUTTON_B, INITIAL_WAIT0); - - // This is a state-merging operation. - // If we just finished a trade, this will start the animation for it. - // If we failed the previous trade and are stuck in the wrong parity, this - // is a no-op that will correct the parity and setup the next trade. - ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0); - pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); -} - -void SurpriseTrade::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ - // At this point, we MUST be in the overworld with no pending trade. - // Otherwise the box transition will fail. Therefore we add a cleanup - // stage after each box to make sure we are in this state. - trade_slot(context, 0, box != 0); - - for (uint8_t c = 1; c < 30; c++){ - trade_slot(context, c, false); - } - - // If the previous trade isn't done, either wait to finish or cancel it. - // Two iterations of this will merge all the following states: - // 1. The last trade finished successfully. Both iterations are no-ops. - // 2. The last trade was slightly too slow. The 1st iteration - // will finish it. The 2nd iteration is a no-op. - // 3. The last trade was very slow. The 1st iteration is suppressed - // because the trade is in progress. The 2nd iteration finishes it. - // 4. No partner was ever found. The 1st iteration will cancel the trade. - for (uint8_t c = 0; c < 2; c++){ - ssf_press_button(context, BUTTON_Y, 2000ms); - ssf_press_dpad(context, DPAD_DOWN, 160ms); - ssf_press_button(context, BUTTON_A, 2240ms); - ssf_press_button(context, BUTTON_B, 2240ms); - ssf_press_button(context, BUTTON_B, 1600ms); - ssf_press_button(context, BUTTON_A, 800ms); - pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); - } - - // Wait out any new pokedex entries or trade evolutions. - pbf_mash_button(context, BUTTON_B, EVOLVE_DELAY0); - } - - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); -} - - -} -} -} +/* Surprise Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh_SurpriseTrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +SurpriseTrade_Descriptor::SurpriseTrade_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:SurpriseTrade", + STRING_POKEMON + " SwSh", "Surprise Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/SurpriseTrade.md", + "Surprise trade away boxes of " + STRING_POKEMON, + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +SurpriseTrade::SurpriseTrade() + : BOXES_TO_TRADE( + "Number of Boxes to Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2 + ) + , INITIAL_WAIT0( + "Time to wait for a Trade Partner:", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , TRADE_ANIMATION0( + "Trade Animation Time:", + LockMode::LOCK_WHILE_RUNNING, + "23 s" + ) + , EVOLVE_DELAY0( + "Evolve Delay:", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(INITIAL_WAIT0); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(TRADE_ANIMATION0); + PA_ADD_OPTION(EVOLVE_DELAY0); +} + + +void SurpriseTrade::trade_slot(ProControllerContext& context, uint8_t slot, bool next_box) const{ + ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); + ssf_press_dpad(context, DPAD_DOWN, 80ms); + ssf_press_button(context, BUTTON_A, 2240ms, 160ms); + + if (next_box){ + ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0); + } + + // Move to slot + while (slot >= 6){ + box_scroll(context, DPAD_DOWN); + slot -= 6; + } + while (slot > 0){ + box_scroll(context, DPAD_RIGHT); + slot--; + } + + ssf_press_button(context, BUTTON_A, 400ms); + ssf_press_button(context, BUTTON_A, 4000ms); + ssf_press_button(context, BUTTON_A, 800ms); + ssf_press_button(context, BUTTON_A, 800ms); + + pbf_mash_button(context, BUTTON_B, INITIAL_WAIT0); + + // This is a state-merging operation. + // If we just finished a trade, this will start the animation for it. + // If we failed the previous trade and are stuck in the wrong parity, this + // is a no-op that will correct the parity and setup the next trade. + ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0); + pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); +} + +void SurpriseTrade::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ + // At this point, we MUST be in the overworld with no pending trade. + // Otherwise the box transition will fail. Therefore we add a cleanup + // stage after each box to make sure we are in this state. + trade_slot(context, 0, box != 0); + + for (uint8_t c = 1; c < 30; c++){ + trade_slot(context, c, false); + } + + // If the previous trade isn't done, either wait to finish or cancel it. + // Two iterations of this will merge all the following states: + // 1. The last trade finished successfully. Both iterations are no-ops. + // 2. The last trade was slightly too slow. The 1st iteration + // will finish it. The 2nd iteration is a no-op. + // 3. The last trade was very slow. The 1st iteration is suppressed + // because the trade is in progress. The 2nd iteration finishes it. + // 4. No partner was ever found. The 1st iteration will cancel the trade. + for (uint8_t c = 0; c < 2; c++){ + ssf_press_button(context, BUTTON_Y, 2000ms); + ssf_press_dpad(context, DPAD_DOWN, 160ms); + ssf_press_button(context, BUTTON_A, 2240ms); + ssf_press_button(context, BUTTON_B, 2240ms); + ssf_press_button(context, BUTTON_B, 1600ms); + ssf_press_button(context, BUTTON_A, 800ms); + pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); + } + + // Wait out any new pokedex entries or trade evolutions. + pbf_mash_button(context, BUTTON_B, EVOLVE_DELAY0); + } + + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.h index 75486b956c..58cfe9b1f5 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_SurpriseTrade.h @@ -1,54 +1,54 @@ -/* Surprise Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SurpriseTrade_H -#define PokemonAutomation_PokemonSwSh_SurpriseTrade_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class SurpriseTrade_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SurpriseTrade_Descriptor(); -}; - - - -class SurpriseTrade : public SingleSwitchProgramInstance{ -public: - SurpriseTrade(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void trade_slot(ProControllerContext& context, uint8_t slot, bool next_box) const; - -private: - StartInGripOrGameOption START_LOCATION; - - SimpleIntegerOption BOXES_TO_TRADE; - MillisecondsOption INITIAL_WAIT0; - SectionDividerOption m_advanced_options; - MillisecondsOption TRADE_ANIMATION0; - MillisecondsOption EVOLVE_DELAY0; -}; - - -} -} -} -#endif - - - +/* Surprise Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SurpriseTrade_H +#define PokemonAutomation_PokemonSwSh_SurpriseTrade_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class SurpriseTrade_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SurpriseTrade_Descriptor(); +}; + + + +class SurpriseTrade : public SingleSwitchProgramInstance{ +public: + SurpriseTrade(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void trade_slot(ProControllerContext& context, uint8_t slot, bool next_box) const; + +private: + StartInGripOrGameOption START_LOCATION; + + SimpleIntegerOption BOXES_TO_TRADE; + MillisecondsOption INITIAL_WAIT0; + SectionDividerOption m_advanced_options; + MillisecondsOption TRADE_ANIMATION0; + MillisecondsOption EVOLVE_DELAY0; +}; + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp index dab05ce56d..cba7b5a535 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.cpp @@ -1,217 +1,217 @@ -/* TradeBot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh_TradeBot.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -TradeBot_Descriptor::TradeBot_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:TradeBot", - STRING_POKEMON + " SwSh", "Trade Bot", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/TradeBot.md", - "Surprise trade with a code for hosting giveaways.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -TradeBot::TradeBot() - : TRADE_CODE( - "Trade Code:", - 8, - "1280 0000" - ) - , BOXES_TO_TRADE( - "Number of Boxes to Trade:", - LockMode::LOCK_WHILE_RUNNING, - 2 - ) - , LINK_TRADE_EXTRA_LINE( - "Link Trade Extra Line:
Set this if you are playing in German.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , SEARCH_DELAY0( - "Time to wait for a Trade Partner:", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) - , CONFIRM_DELAY0( - "Time to wait for Partner to Confirm:", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) - , TRADE_START0( - "Time for Trade to Start:", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) - , TRADE_COMMUNICATION0( - "Communication Window:", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , TRADE_ANIMATION0( - "Trade Animation Time:", - LockMode::LOCK_WHILE_RUNNING, - "23 s" - ) - , EVOLVE_DELAY0( - "Evolve Delay:", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - - PA_ADD_OPTION(TRADE_CODE); - PA_ADD_OPTION(BOXES_TO_TRADE); - PA_ADD_OPTION(LINK_TRADE_EXTRA_LINE); - PA_ADD_OPTION(SEARCH_DELAY0); - PA_ADD_OPTION(CONFIRM_DELAY0); - PA_ADD_OPTION(TRADE_START0); - PA_ADD_OPTION(TRADE_COMMUNICATION0); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(TRADE_ANIMATION0); - PA_ADD_OPTION(EVOLVE_DELAY0); -} - - -void TradeBot::trade_slot( - ConsoleHandle& console, ProControllerContext& context, - const std::string& code, uint8_t slot -) const{ - ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); - ssf_press_button(context, BUTTON_A, 1200ms, 160ms); - ssf_press_dpad(context, DPAD_DOWN, 80ms); - ssf_press_button(context, BUTTON_A, 1600ms, 160ms); - if (LINK_TRADE_EXTRA_LINE){ - ssf_press_button(context, BUTTON_B, 400ms, 160ms); - } - ssf_press_button(context, BUTTON_B, 1600ms, 160ms); - ssf_press_dpad(context, DPAD_UP, 80ms); - ssf_press_button(context, BUTTON_A, 40ms); - ssf_press_button(context, BUTTON_B, 40ms); - - FastCodeEntry::numberpad_enter_code(console, context, code, true); - ssf_press_button(context, BUTTON_PLUS, 1600ms); - ssf_press_button(context, BUTTON_B, 1000ms, 80ms); - ssf_press_button(context, BUTTON_A, 400ms, 80ms); - pbf_mash_button(context, BUTTON_B, 400); - - pbf_wait(context, SEARCH_DELAY0); - - // If we're not in a trade, enter Y-COMM to avoid a connection at this point. - ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); - ssf_press_button(context, BUTTON_A, 1600ms, 160ms); - ssf_press_button(context, BUTTON_B, 640ms, 80ms); - - // Move to slot - while (slot >= 6){ - box_scroll(context, DPAD_DOWN); - slot -= 6; - } - while (slot > 0){ - box_scroll(context, DPAD_RIGHT); - slot--; - } - - // Select Pokemon - ssf_press_button(context, BUTTON_A, 800ms); - ssf_press_button(context, BUTTON_A, CONFIRM_DELAY0); - - // Start Trade - ssf_press_button(context, BUTTON_A, TRADE_START0); - - // Cancel out - for (Milliseconds c = 0ms; c < TRADE_COMMUNICATION0.get() + TRADE_ANIMATION0.get(); c += 2400ms){ - ssf_press_button(context, BUTTON_B, 800ms); - ssf_press_button(context, BUTTON_B, 800ms); - ssf_press_button(context, BUTTON_A, 800ms); - } -} - -void TradeBot::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - std::string code = TRADE_CODE.to_str(); - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ - for (uint8_t c = 0; c < 30; c++){ - trade_slot(env.console, context, code, c); - } - - // If the previous trade isn't done, either wait to finish or cancel it. - // Two iterations of this will merge all the following states: - // 1. The last trade finished successfully. Both iterations are no-ops. - // 2. The last trade was slightly too slow. The 1st iteration - // will finish it. The 2nd iteration is a no-op. - // 3. The last trade was very slow. The 1st iteration is suppressed - // because the trade is in progress. The 2nd iteration finishes it. - // 4. No partner was ever found. The 1st iteration will cancel the trade. - for (uint8_t c = 0; c < 2; c++){ - ssf_press_button(context, BUTTON_Y, 2000ms); - ssf_press_button(context, BUTTON_A, 2240ms); - ssf_press_button(context, BUTTON_B, 2240ms); - ssf_press_button(context, BUTTON_B, 1600ms); - ssf_press_button(context, BUTTON_A, 800ms); - pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); - } - - // Wait out any new pokedex entries or trade evolutions. - pbf_mash_button(context, BUTTON_B, EVOLVE_DELAY0); - - // Change boxes. - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, 80ms); - ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, 80ms); - ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0, 80ms); - pbf_mash_button( - context, BUTTON_B, - GameSettings::instance().BOX_TO_POKEMON_DELAY0.get() + - GameSettings::instance().POKEMON_TO_MENU_DELAY0.get() + - GameSettings::instance().OVERWORLD_TO_MENU_DELAY0.get() - ); - } - - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); -} - - -} -} -} - - - - - - - +/* TradeBot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh_TradeBot.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +TradeBot_Descriptor::TradeBot_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:TradeBot", + STRING_POKEMON + " SwSh", "Trade Bot", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/TradeBot.md", + "Surprise trade with a code for hosting giveaways.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +TradeBot::TradeBot() + : TRADE_CODE( + "Trade Code:", + 8, + "1280 0000" + ) + , BOXES_TO_TRADE( + "Number of Boxes to Trade:", + LockMode::LOCK_WHILE_RUNNING, + 2 + ) + , LINK_TRADE_EXTRA_LINE( + "Link Trade Extra Line:
Set this if you are playing in German.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , SEARCH_DELAY0( + "Time to wait for a Trade Partner:", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) + , CONFIRM_DELAY0( + "Time to wait for Partner to Confirm:", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) + , TRADE_START0( + "Time for Trade to Start:", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) + , TRADE_COMMUNICATION0( + "Communication Window:", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , TRADE_ANIMATION0( + "Trade Animation Time:", + LockMode::LOCK_WHILE_RUNNING, + "23 s" + ) + , EVOLVE_DELAY0( + "Evolve Delay:", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + + PA_ADD_OPTION(TRADE_CODE); + PA_ADD_OPTION(BOXES_TO_TRADE); + PA_ADD_OPTION(LINK_TRADE_EXTRA_LINE); + PA_ADD_OPTION(SEARCH_DELAY0); + PA_ADD_OPTION(CONFIRM_DELAY0); + PA_ADD_OPTION(TRADE_START0); + PA_ADD_OPTION(TRADE_COMMUNICATION0); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(TRADE_ANIMATION0); + PA_ADD_OPTION(EVOLVE_DELAY0); +} + + +void TradeBot::trade_slot( + ConsoleHandle& console, ProControllerContext& context, + const std::string& code, uint8_t slot +) const{ + ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); + ssf_press_button(context, BUTTON_A, 1200ms, 160ms); + ssf_press_dpad(context, DPAD_DOWN, 80ms); + ssf_press_button(context, BUTTON_A, 1600ms, 160ms); + if (LINK_TRADE_EXTRA_LINE){ + ssf_press_button(context, BUTTON_B, 400ms, 160ms); + } + ssf_press_button(context, BUTTON_B, 1600ms, 160ms); + ssf_press_dpad(context, DPAD_UP, 80ms); + ssf_press_button(context, BUTTON_A, 40ms); + ssf_press_button(context, BUTTON_B, 40ms); + + FastCodeEntry::numberpad_enter_code(console, context, code, true); + ssf_press_button(context, BUTTON_PLUS, 1600ms); + ssf_press_button(context, BUTTON_B, 1000ms, 80ms); + ssf_press_button(context, BUTTON_A, 400ms, 80ms); + pbf_mash_button(context, BUTTON_B, 400); + + pbf_wait(context, SEARCH_DELAY0); + + // If we're not in a trade, enter Y-COMM to avoid a connection at this point. + ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 400ms); + ssf_press_button(context, BUTTON_A, 1600ms, 160ms); + ssf_press_button(context, BUTTON_B, 640ms, 80ms); + + // Move to slot + while (slot >= 6){ + box_scroll(context, DPAD_DOWN); + slot -= 6; + } + while (slot > 0){ + box_scroll(context, DPAD_RIGHT); + slot--; + } + + // Select Pokemon + ssf_press_button(context, BUTTON_A, 800ms); + ssf_press_button(context, BUTTON_A, CONFIRM_DELAY0); + + // Start Trade + ssf_press_button(context, BUTTON_A, TRADE_START0); + + // Cancel out + for (Milliseconds c = 0ms; c < TRADE_COMMUNICATION0.get() + TRADE_ANIMATION0.get(); c += 2400ms){ + ssf_press_button(context, BUTTON_B, 800ms); + ssf_press_button(context, BUTTON_B, 800ms); + ssf_press_button(context, BUTTON_A, 800ms); + } +} + +void TradeBot::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + std::string code = TRADE_CODE.to_str(); + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + for (uint8_t box = 0; box < BOXES_TO_TRADE; box++){ + for (uint8_t c = 0; c < 30; c++){ + trade_slot(env.console, context, code, c); + } + + // If the previous trade isn't done, either wait to finish or cancel it. + // Two iterations of this will merge all the following states: + // 1. The last trade finished successfully. Both iterations are no-ops. + // 2. The last trade was slightly too slow. The 1st iteration + // will finish it. The 2nd iteration is a no-op. + // 3. The last trade was very slow. The 1st iteration is suppressed + // because the trade is in progress. The 2nd iteration finishes it. + // 4. No partner was ever found. The 1st iteration will cancel the trade. + for (uint8_t c = 0; c < 2; c++){ + ssf_press_button(context, BUTTON_Y, 2000ms); + ssf_press_button(context, BUTTON_A, 2240ms); + ssf_press_button(context, BUTTON_B, 2240ms); + ssf_press_button(context, BUTTON_B, 1600ms); + ssf_press_button(context, BUTTON_A, 800ms); + pbf_mash_button(context, BUTTON_B, TRADE_ANIMATION0); + } + + // Wait out any new pokedex entries or trade evolutions. + pbf_mash_button(context, BUTTON_B, EVOLVE_DELAY0); + + // Change boxes. + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, 80ms); + ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, 80ms); + ssf_press_button(context, BUTTON_R, GameSettings::instance().BOX_CHANGE_DELAY0, 80ms); + pbf_mash_button( + context, BUTTON_B, + GameSettings::instance().BOX_TO_POKEMON_DELAY0.get() + + GameSettings::instance().POKEMON_TO_MENU_DELAY0.get() + + GameSettings::instance().OVERWORLD_TO_MENU_DELAY0.get() + ); + } + + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); +} + + +} +} +} + + + + + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.h b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.h index b8c291648f..54bebc317e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/General/PokemonSwSh_TradeBot.h @@ -1,65 +1,65 @@ -/* TradeBot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TradeBot_H -#define PokemonAutomation_PokemonSwSh_TradeBot_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/Cpp/Options/FixedCodeOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class TradeBot_Descriptor : public SingleSwitchProgramDescriptor{ -public: - TradeBot_Descriptor(); -}; - - - -class TradeBot : public SingleSwitchProgramInstance{ -public: - TradeBot(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - void trade_slot( - ConsoleHandle& console, ProControllerContext& context, - const std::string& code, uint8_t slot - ) const; - -private: - StartInGripOrGameOption START_LOCATION; - - FixedCodeOption TRADE_CODE; - SimpleIntegerOption BOXES_TO_TRADE; - BooleanCheckBoxOption LINK_TRADE_EXTRA_LINE; - MillisecondsOption SEARCH_DELAY0; - MillisecondsOption CONFIRM_DELAY0; - MillisecondsOption TRADE_START0; - MillisecondsOption TRADE_COMMUNICATION0; - SectionDividerOption m_advanced_options; - MillisecondsOption TRADE_ANIMATION0; - MillisecondsOption EVOLVE_DELAY0; -}; - - - -} -} -} -#endif - - - +/* TradeBot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TradeBot_H +#define PokemonAutomation_PokemonSwSh_TradeBot_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/Cpp/Options/FixedCodeOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class TradeBot_Descriptor : public SingleSwitchProgramDescriptor{ +public: + TradeBot_Descriptor(); +}; + + + +class TradeBot : public SingleSwitchProgramInstance{ +public: + TradeBot(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + void trade_slot( + ConsoleHandle& console, ProControllerContext& context, + const std::string& code, uint8_t slot + ) const; + +private: + StartInGripOrGameOption START_LOCATION; + + FixedCodeOption TRADE_CODE; + SimpleIntegerOption BOXES_TO_TRADE; + BooleanCheckBoxOption LINK_TRADE_EXTRA_LINE; + MillisecondsOption SEARCH_DELAY0; + MillisecondsOption CONFIRM_DELAY0; + MillisecondsOption TRADE_START0; + MillisecondsOption TRADE_COMMUNICATION0; + SectionDividerOption m_advanced_options; + MillisecondsOption TRADE_ANIMATION0; + MillisecondsOption EVOLVE_DELAY0; +}; + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.cpp index 95d9430090..2f17c42bf4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.cpp @@ -1,245 +1,245 @@ -/* Multi-Game Auto-Host - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Common/Cpp/ExpressionEvaluator.h" -//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_DenTools.h" -#include "PokemonSwSh_AutoHostStats.h" -#include "PokemonSwSh_AutoHost.h" -#include "PokemonSwSh_AutoHost-MultiGame.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -AutoHostMultiGame_Descriptor::AutoHostMultiGame_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:AutoHostMultiGame", - STRING_POKEMON + " SwSh", "Auto-Host Multi-Game", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/AutoHost-MultiGame.md", - "Run AutoHost-Rolling across multiple game saves. (Up to 16 dens!)", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} -std::unique_ptr AutoHostMultiGame_Descriptor::make_stats() const{ - return std::unique_ptr(new AutoHostStats()); -} - - - -AutoHostMultiGame::AutoHostMultiGame() - : SingleSwitchProgramInstance({"Notifs", "LiveHost"}) - , RAID_CODE(8) - , HOST_ONLINE("Host Online:", LockMode::LOCK_WHILE_RUNNING, true) - , LOBBY_WAIT_DELAY0( - "Lobby Wait Delay:
Wait this long before starting raid. Start time is 3 minutes minus this number.", - LockMode::LOCK_WHILE_RUNNING, - "60 s" - ) - , GAME_LIST(true) - , FR_FORWARD_ACCEPT( - "Forward Friend Accept:
Accept FRs this many raids in the future.", - LockMode::LOCK_WHILE_RUNNING, - 1 - ) - , HOSTING_NOTIFICATIONS("Live-Hosting Announcements", false) - , NOTIFICATIONS({ - &HOSTING_NOTIFICATIONS.NOTIFICATION, - &NOTIFICATION_ERROR_FATAL, - }) - , m_internet_settings( - "Internet Settings: Increase these if your internet is slow." - ) - , CONNECT_TO_INTERNET_DELAY0( - "Connect to Internet Delay:
Time from \"Connect to Internet\" to when you're ready to enter den.", - LockMode::LOCK_WHILE_RUNNING, - "60000 ms" - ) - , ENTER_ONLINE_DEN_DELAY0( - "Enter Online Den Delay:
\"Communicating\" when entering den while online.", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , OPEN_ONLINE_DEN_LOBBY_DELAY0( - "Open Online Den Delay:
Delay from \"Invite Others\" to when the clock starts ticking.", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , RAID_START_TO_EXIT_DELAY0( - "Raid Start to Exit Delay:
Time from start raid to reset. (when not selecting move)", - LockMode::LOCK_WHILE_RUNNING, - "15 s" - ) - , DELAY_TO_SELECT_MOVE0( - "Delay to Select Move:
This + above = time from start raid to select move.", - LockMode::LOCK_WHILE_RUNNING, - "32 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(RAID_CODE); - PA_ADD_OPTION(HOST_ONLINE); - PA_ADD_OPTION(LOBBY_WAIT_DELAY0); - PA_ADD_OPTION(GAME_LIST); - PA_ADD_OPTION(FR_FORWARD_ACCEPT); - PA_ADD_OPTION(HOSTING_NOTIFICATIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_OPTION(m_internet_settings); - PA_ADD_OPTION(CONNECT_TO_INTERNET_DELAY0); - PA_ADD_OPTION(ENTER_ONLINE_DEN_DELAY0); - PA_ADD_OPTION(OPEN_ONLINE_DEN_LOBBY_DELAY0); - PA_ADD_OPTION(RAID_START_TO_EXIT_DELAY0); - PA_ADD_OPTION(DELAY_TO_SELECT_MOVE0); -} - - - - -void AutoHostMultiGame::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - Milliseconds start_raid_delay = HOST_ONLINE - ? OPEN_ONLINE_DEN_LOBBY_DELAY0 - : GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0; - const Milliseconds lobby_wait_delay = LOBBY_WAIT_DELAY0.get() < start_raid_delay - ? 0ms - : LOBBY_WAIT_DELAY0.get() - start_raid_delay; - - std::vector> list = GAME_LIST.copy_snapshot(); - - // Scan den list for any rolling dens. - bool enable_touch = true; - for (uint8_t index = 0; index < list.size(); index++){ - const MultiHostSlot& game = *list[index]; -// if (game.user_slot == 0){ -// break; -// } - if (game.skips > 0){ - enable_touch = false; - break; - } - } - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - if (enable_touch){ - TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); - } - - uint32_t raids = 0; - bool game_slot_flipped = false; - while (true){ - env.log("Beginning from start of game list."); - for (uint8_t index = 0; index < list.size(); index++){ - env.update_stats(); - - const MultiHostSlot& game = *list[index]; -// if (game.user_slot == 0){ -// break; -// } - - env.log("Raids Attempted: " + tostr_u_commas(raids++)); - - // Start game. - rollback_date_from_home(env.console, context, game.skips); - - // Sanitize game slot. - uint8_t game_slot = (uint8_t)game.game_slot.current_value(); - if (game_slot > 2){ - game_slot = 0; - } - - // Calculate current game slot. - switch (game_slot){ - case 0: - break; - case 1: - game_slot = game_slot_flipped ? 2 : 0; - break; - case 2: - game_slot = game_slot_flipped ? 0 : 2; - break; - } - start_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, - game_slot, - (uint8_t)game.user_slot.current_value(), - game.backup_save - ); - if (game_slot == 2){ - game_slot_flipped = !game_slot_flipped; - } - - // Calculate accept_FR_slot. - size_t FR_index = index; - for (uint8_t c = 0; c < FR_FORWARD_ACCEPT; c++){ - FR_index++; - if (FR_index >= list.size()){ - FR_index = 0; - } - } - - // Run auto-host. - const MultiHostSlot& fr_game = *list[FR_index]; - run_autohost( - env, env.console, context, - game.always_catchable - ? Catchability::ALWAYS_CATCHABLE - : Catchability::MAYBE_UNCATCHABLE, - (uint8_t)game.skips, - game.use_raid_code ? &RAID_CODE : nullptr, lobby_wait_delay, - HOST_ONLINE, fr_game.accept_FRs ? (uint8_t)fr_game.user_slot.current_value() : 0, - game.move_slot, game.dynamax, 0, - HOSTING_NOTIFICATIONS, - CONNECT_TO_INTERNET_DELAY0, - ENTER_ONLINE_DEN_DELAY0, - OPEN_ONLINE_DEN_LOBBY_DELAY0, - RAID_START_TO_EXIT_DELAY0, - DELAY_TO_SELECT_MOVE0 - ); - - // Exit game. - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - close_game(env.console, context); - - // Post-raid delay. - pbf_wait(context, game.post_raid_delay); - - // Touch the date. - if (enable_touch){ - TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); - } - } - } -} - - - -} -} -} - +/* Multi-Game Auto-Host + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Common/Cpp/ExpressionEvaluator.h" +//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_DenTools.h" +#include "PokemonSwSh_AutoHostStats.h" +#include "PokemonSwSh_AutoHost.h" +#include "PokemonSwSh_AutoHost-MultiGame.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +AutoHostMultiGame_Descriptor::AutoHostMultiGame_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:AutoHostMultiGame", + STRING_POKEMON + " SwSh", "Auto-Host Multi-Game", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/AutoHost-MultiGame.md", + "Run AutoHost-Rolling across multiple game saves. (Up to 16 dens!)", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} +std::unique_ptr AutoHostMultiGame_Descriptor::make_stats() const{ + return std::unique_ptr(new AutoHostStats()); +} + + + +AutoHostMultiGame::AutoHostMultiGame() + : SingleSwitchProgramInstance({"Notifs", "LiveHost"}) + , RAID_CODE(8) + , HOST_ONLINE("Host Online:", LockMode::LOCK_WHILE_RUNNING, true) + , LOBBY_WAIT_DELAY0( + "Lobby Wait Delay:
Wait this long before starting raid. Start time is 3 minutes minus this number.", + LockMode::LOCK_WHILE_RUNNING, + "60 s" + ) + , GAME_LIST(true) + , FR_FORWARD_ACCEPT( + "Forward Friend Accept:
Accept FRs this many raids in the future.", + LockMode::LOCK_WHILE_RUNNING, + 1 + ) + , HOSTING_NOTIFICATIONS("Live-Hosting Announcements", false) + , NOTIFICATIONS({ + &HOSTING_NOTIFICATIONS.NOTIFICATION, + &NOTIFICATION_ERROR_FATAL, + }) + , m_internet_settings( + "Internet Settings: Increase these if your internet is slow." + ) + , CONNECT_TO_INTERNET_DELAY0( + "Connect to Internet Delay:
Time from \"Connect to Internet\" to when you're ready to enter den.", + LockMode::LOCK_WHILE_RUNNING, + "60000 ms" + ) + , ENTER_ONLINE_DEN_DELAY0( + "Enter Online Den Delay:
\"Communicating\" when entering den while online.", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , OPEN_ONLINE_DEN_LOBBY_DELAY0( + "Open Online Den Delay:
Delay from \"Invite Others\" to when the clock starts ticking.", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , RAID_START_TO_EXIT_DELAY0( + "Raid Start to Exit Delay:
Time from start raid to reset. (when not selecting move)", + LockMode::LOCK_WHILE_RUNNING, + "15 s" + ) + , DELAY_TO_SELECT_MOVE0( + "Delay to Select Move:
This + above = time from start raid to select move.", + LockMode::LOCK_WHILE_RUNNING, + "32 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(RAID_CODE); + PA_ADD_OPTION(HOST_ONLINE); + PA_ADD_OPTION(LOBBY_WAIT_DELAY0); + PA_ADD_OPTION(GAME_LIST); + PA_ADD_OPTION(FR_FORWARD_ACCEPT); + PA_ADD_OPTION(HOSTING_NOTIFICATIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_OPTION(m_internet_settings); + PA_ADD_OPTION(CONNECT_TO_INTERNET_DELAY0); + PA_ADD_OPTION(ENTER_ONLINE_DEN_DELAY0); + PA_ADD_OPTION(OPEN_ONLINE_DEN_LOBBY_DELAY0); + PA_ADD_OPTION(RAID_START_TO_EXIT_DELAY0); + PA_ADD_OPTION(DELAY_TO_SELECT_MOVE0); +} + + + + +void AutoHostMultiGame::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + Milliseconds start_raid_delay = HOST_ONLINE + ? OPEN_ONLINE_DEN_LOBBY_DELAY0 + : GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0; + const Milliseconds lobby_wait_delay = LOBBY_WAIT_DELAY0.get() < start_raid_delay + ? 0ms + : LOBBY_WAIT_DELAY0.get() - start_raid_delay; + + std::vector> list = GAME_LIST.copy_snapshot(); + + // Scan den list for any rolling dens. + bool enable_touch = true; + for (uint8_t index = 0; index < list.size(); index++){ + const MultiHostSlot& game = *list[index]; +// if (game.user_slot == 0){ +// break; +// } + if (game.skips > 0){ + enable_touch = false; + break; + } + } + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + if (enable_touch){ + TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); + } + + uint32_t raids = 0; + bool game_slot_flipped = false; + while (true){ + env.log("Beginning from start of game list."); + for (uint8_t index = 0; index < list.size(); index++){ + env.update_stats(); + + const MultiHostSlot& game = *list[index]; +// if (game.user_slot == 0){ +// break; +// } + + env.log("Raids Attempted: " + tostr_u_commas(raids++)); + + // Start game. + rollback_date_from_home(env.console, context, game.skips); + + // Sanitize game slot. + uint8_t game_slot = (uint8_t)game.game_slot.current_value(); + if (game_slot > 2){ + game_slot = 0; + } + + // Calculate current game slot. + switch (game_slot){ + case 0: + break; + case 1: + game_slot = game_slot_flipped ? 2 : 0; + break; + case 2: + game_slot = game_slot_flipped ? 0 : 2; + break; + } + start_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, + game_slot, + (uint8_t)game.user_slot.current_value(), + game.backup_save + ); + if (game_slot == 2){ + game_slot_flipped = !game_slot_flipped; + } + + // Calculate accept_FR_slot. + size_t FR_index = index; + for (uint8_t c = 0; c < FR_FORWARD_ACCEPT; c++){ + FR_index++; + if (FR_index >= list.size()){ + FR_index = 0; + } + } + + // Run auto-host. + const MultiHostSlot& fr_game = *list[FR_index]; + run_autohost( + env, env.console, context, + game.always_catchable + ? Catchability::ALWAYS_CATCHABLE + : Catchability::MAYBE_UNCATCHABLE, + (uint8_t)game.skips, + game.use_raid_code ? &RAID_CODE : nullptr, lobby_wait_delay, + HOST_ONLINE, fr_game.accept_FRs ? (uint8_t)fr_game.user_slot.current_value() : 0, + game.move_slot, game.dynamax, 0, + HOSTING_NOTIFICATIONS, + CONNECT_TO_INTERNET_DELAY0, + ENTER_ONLINE_DEN_DELAY0, + OPEN_ONLINE_DEN_LOBBY_DELAY0, + RAID_START_TO_EXIT_DELAY0, + DELAY_TO_SELECT_MOVE0 + ); + + // Exit game. + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + close_game(env.console, context); + + // Post-raid delay. + pbf_wait(context, game.post_raid_delay); + + // Touch the date. + if (enable_touch){ + TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); + } + } + } +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h index f7d4dfd1f3..1c7f4814a3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-MultiGame.h @@ -1,67 +1,67 @@ -/* Multi-Game Auto-Host - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_AutoHostMultiGame_H -#define PokemonAutomation_PokemonSwSh_AutoHostMultiGame_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/RandomCodeOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class AutoHostMultiGame_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoHostMultiGame_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class AutoHostMultiGame : public SingleSwitchProgramInstance{ -public: - AutoHostMultiGame(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrClosedOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - RandomCodeOption RAID_CODE; - BooleanCheckBoxOption HOST_ONLINE; - MillisecondsOption LOBBY_WAIT_DELAY0; - MultiHostTable GAME_LIST; - SimpleIntegerOption FR_FORWARD_ACCEPT; - - AutoHostNotificationOption HOSTING_NOTIFICATIONS; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_internet_settings; - MillisecondsOption CONNECT_TO_INTERNET_DELAY0; - MillisecondsOption ENTER_ONLINE_DEN_DELAY0; - MillisecondsOption OPEN_ONLINE_DEN_LOBBY_DELAY0; - MillisecondsOption RAID_START_TO_EXIT_DELAY0; - MillisecondsOption DELAY_TO_SELECT_MOVE0; -}; - - - -} -} -} -#endif +/* Multi-Game Auto-Host + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_AutoHostMultiGame_H +#define PokemonAutomation_PokemonSwSh_AutoHostMultiGame_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/RandomCodeOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "Common/PokemonSwSh/PokemonSwSh_MultiHostTable.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class AutoHostMultiGame_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoHostMultiGame_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class AutoHostMultiGame : public SingleSwitchProgramInstance{ +public: + AutoHostMultiGame(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrClosedOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + RandomCodeOption RAID_CODE; + BooleanCheckBoxOption HOST_ONLINE; + MillisecondsOption LOBBY_WAIT_DELAY0; + MultiHostTable GAME_LIST; + SimpleIntegerOption FR_FORWARD_ACCEPT; + + AutoHostNotificationOption HOSTING_NOTIFICATIONS; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_internet_settings; + MillisecondsOption CONNECT_TO_INTERNET_DELAY0; + MillisecondsOption ENTER_ONLINE_DEN_DELAY0; + MillisecondsOption OPEN_ONLINE_DEN_LOBBY_DELAY0; + MillisecondsOption RAID_START_TO_EXIT_DELAY0; + MillisecondsOption DELAY_TO_SELECT_MOVE0; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.cpp index 7f262f4251..c6f4473d73 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.cpp @@ -1,232 +1,232 @@ -/* Rolling Auto-Host - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_DenTools.h" -#include "PokemonSwSh_AutoHostStats.h" -#include "PokemonSwSh_AutoHost.h" -#include "PokemonSwSh_AutoHost-Rolling.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -AutoHostRolling_Descriptor::AutoHostRolling_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:AutoHostRolling", - STRING_POKEMON + " SwSh", "Auto-Host Rolling", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/AutoHost-Rolling.md", - "Roll N days, host, SR and repeat. Also supports hard-locks and soft-locks.", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} -std::unique_ptr AutoHostRolling_Descriptor::make_stats() const{ - return std::unique_ptr(new AutoHostStats()); -} - - - -AutoHostRolling::AutoHostRolling() - : SingleSwitchProgramInstance({"Notifs", "LiveHost"}) - , RAID_CODE(8) - , SKIPS("Day Skips:", LockMode::LOCK_WHILE_RUNNING, 3) - , BACKUP_SAVE( - "Load Backup Save:
For backup save soft-locking method.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , HOST_ONLINE("Host Online:", LockMode::LOCK_WHILE_RUNNING, true) - , LOBBY_WAIT_DELAY0( - "Lobby Wait Delay:
Wait this long before starting raid. Start time is 3 minutes minus this number.", - LockMode::LOCK_WHILE_RUNNING, - "60 s" - ) - , FRIEND_ACCEPT_USER_SLOT( - "Friend Request Accept Slot:
Zero disables friend accepts.", - LockMode::LOCK_WHILE_RUNNING, - 0, 0, 8 - ) - , EXTRA_DELAY_BETWEEN_RAIDS0( - "Extra Delay Between Raids:
May aid in farming.", - LockMode::LOCK_WHILE_RUNNING, - "0 s" - ) - , MOVE_SLOT( - "1st Move Select Slot:
Zero disables 1st move select.", - LockMode::LOCK_WHILE_RUNNING, - 0, 0, 4 - ) - , DYNAMAX( - "1st Move Dynamax:
Dynamax on first move. (only applies if above option is non-zero)", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , TROLL_HOSTING( - "Troll Hosting: (requires 1st move select)
0 disables the troll hosting option, 1 attacks the first ally, 2 attacks the second one, 3 attacks the third one. Dynamaxing will disable this option.", - LockMode::LOCK_WHILE_RUNNING, - 0, 0, 3 - ) - , ALTERNATE_GAMES( - "Alternate Games:
Alternate hosting between 1st and 2nd games. Host from both Sword and Shield.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , HOSTING_NOTIFICATIONS("Live-Hosting Announcements", false) - , NOTIFICATIONS({ - &HOSTING_NOTIFICATIONS.NOTIFICATION, - &NOTIFICATION_ERROR_FATAL, - }) - , m_internet_settings( - "Internet Settings: Increase these if your internet is slow." - ) - , CONNECT_TO_INTERNET_DELAY0( - "Connect to Internet Delay:
Time from \"Connect to Internet\" to when you're ready to enter den.", - LockMode::LOCK_WHILE_RUNNING, - "60000 ms" - ) - , ENTER_ONLINE_DEN_DELAY0( - "Enter Online Den Delay:
\"Communicating\" when entering den while online.", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , OPEN_ONLINE_DEN_LOBBY_DELAY0( - "Open Online Den Delay:
Delay from \"Invite Others\" to when the clock starts ticking.", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) - , RAID_START_TO_EXIT_DELAY0( - "Raid Start to Exit Delay:
Time from start raid to reset. (when not selecting move)", - LockMode::LOCK_WHILE_RUNNING, - "15 s" - ) - , DELAY_TO_SELECT_MOVE0( - "Delay to Select Move:
This + above = time from start raid to select move.", - LockMode::LOCK_WHILE_RUNNING, - "32 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(RAID_CODE); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(BACKUP_SAVE); - PA_ADD_OPTION(HOST_ONLINE); - PA_ADD_OPTION(LOBBY_WAIT_DELAY0); - PA_ADD_OPTION(CATCHABILITY); - PA_ADD_OPTION(FRIEND_ACCEPT_USER_SLOT); - PA_ADD_OPTION(EXTRA_DELAY_BETWEEN_RAIDS0); - PA_ADD_OPTION(MOVE_SLOT); - PA_ADD_OPTION(DYNAMAX); - PA_ADD_OPTION(TROLL_HOSTING); - PA_ADD_OPTION(ALTERNATE_GAMES); - PA_ADD_OPTION(HOSTING_NOTIFICATIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_OPTION(m_internet_settings); - PA_ADD_OPTION(CONNECT_TO_INTERNET_DELAY0); - PA_ADD_OPTION(ENTER_ONLINE_DEN_DELAY0); - PA_ADD_OPTION(OPEN_ONLINE_DEN_LOBBY_DELAY0); - PA_ADD_OPTION(RAID_START_TO_EXIT_DELAY0); - PA_ADD_OPTION(DELAY_TO_SELECT_MOVE0); -} - - - -void AutoHostRolling::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - Milliseconds start_raid_delay = HOST_ONLINE - ? OPEN_ONLINE_DEN_LOBBY_DELAY0 - : GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0; - const Milliseconds lobby_wait_delay = LOBBY_WAIT_DELAY0.get() < start_raid_delay - ? 0ms - : LOBBY_WAIT_DELAY0.get() - start_raid_delay; - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - if (SKIPS == 0){ - TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); - } - rollback_date_from_home(env.console, context, SKIPS); - if (env.console.video().snapshot()){ - NintendoSwitch::resume_game_from_home(env.console, context); - }else{ - resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - } - - for (uint32_t raids = 0;; raids++){ - env.log("Raids Attempted: " + tostr_u_commas(raids)); - env.update_stats(); - - run_autohost( - env, env.console, context, - CATCHABILITY, SKIPS, - &RAID_CODE, lobby_wait_delay, - HOST_ONLINE, FRIEND_ACCEPT_USER_SLOT, - MOVE_SLOT, DYNAMAX, TROLL_HOSTING, - HOSTING_NOTIFICATIONS, - CONNECT_TO_INTERNET_DELAY0, - ENTER_ONLINE_DEN_DELAY0, - OPEN_ONLINE_DEN_LOBBY_DELAY0, - RAID_START_TO_EXIT_DELAY0, - DELAY_TO_SELECT_MOVE0 - ); - - // Exit game. - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - close_game(env.console, context); - - // Post-raid delay. - pbf_wait(context, EXTRA_DELAY_BETWEEN_RAIDS0); - - // Touch the date. - if (SKIPS == 0){ - TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); - }else{ - rollback_date_from_home(env.console, context, SKIPS); - } - - start_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, - ALTERNATE_GAMES ? 2 : 0, 0, - BACKUP_SAVE - ); - } -} - - - -} -} -} - - - - - - - +/* Rolling Auto-Host + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_DenTools.h" +#include "PokemonSwSh_AutoHostStats.h" +#include "PokemonSwSh_AutoHost.h" +#include "PokemonSwSh_AutoHost-Rolling.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +AutoHostRolling_Descriptor::AutoHostRolling_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:AutoHostRolling", + STRING_POKEMON + " SwSh", "Auto-Host Rolling", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/AutoHost-Rolling.md", + "Roll N days, host, SR and repeat. Also supports hard-locks and soft-locks.", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} +std::unique_ptr AutoHostRolling_Descriptor::make_stats() const{ + return std::unique_ptr(new AutoHostStats()); +} + + + +AutoHostRolling::AutoHostRolling() + : SingleSwitchProgramInstance({"Notifs", "LiveHost"}) + , RAID_CODE(8) + , SKIPS("Day Skips:", LockMode::LOCK_WHILE_RUNNING, 3) + , BACKUP_SAVE( + "Load Backup Save:
For backup save soft-locking method.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , HOST_ONLINE("Host Online:", LockMode::LOCK_WHILE_RUNNING, true) + , LOBBY_WAIT_DELAY0( + "Lobby Wait Delay:
Wait this long before starting raid. Start time is 3 minutes minus this number.", + LockMode::LOCK_WHILE_RUNNING, + "60 s" + ) + , FRIEND_ACCEPT_USER_SLOT( + "Friend Request Accept Slot:
Zero disables friend accepts.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 8 + ) + , EXTRA_DELAY_BETWEEN_RAIDS0( + "Extra Delay Between Raids:
May aid in farming.", + LockMode::LOCK_WHILE_RUNNING, + "0 s" + ) + , MOVE_SLOT( + "1st Move Select Slot:
Zero disables 1st move select.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 4 + ) + , DYNAMAX( + "1st Move Dynamax:
Dynamax on first move. (only applies if above option is non-zero)", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , TROLL_HOSTING( + "Troll Hosting: (requires 1st move select)
0 disables the troll hosting option, 1 attacks the first ally, 2 attacks the second one, 3 attacks the third one. Dynamaxing will disable this option.", + LockMode::LOCK_WHILE_RUNNING, + 0, 0, 3 + ) + , ALTERNATE_GAMES( + "Alternate Games:
Alternate hosting between 1st and 2nd games. Host from both Sword and Shield.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , HOSTING_NOTIFICATIONS("Live-Hosting Announcements", false) + , NOTIFICATIONS({ + &HOSTING_NOTIFICATIONS.NOTIFICATION, + &NOTIFICATION_ERROR_FATAL, + }) + , m_internet_settings( + "Internet Settings: Increase these if your internet is slow." + ) + , CONNECT_TO_INTERNET_DELAY0( + "Connect to Internet Delay:
Time from \"Connect to Internet\" to when you're ready to enter den.", + LockMode::LOCK_WHILE_RUNNING, + "60000 ms" + ) + , ENTER_ONLINE_DEN_DELAY0( + "Enter Online Den Delay:
\"Communicating\" when entering den while online.", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , OPEN_ONLINE_DEN_LOBBY_DELAY0( + "Open Online Den Delay:
Delay from \"Invite Others\" to when the clock starts ticking.", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) + , RAID_START_TO_EXIT_DELAY0( + "Raid Start to Exit Delay:
Time from start raid to reset. (when not selecting move)", + LockMode::LOCK_WHILE_RUNNING, + "15 s" + ) + , DELAY_TO_SELECT_MOVE0( + "Delay to Select Move:
This + above = time from start raid to select move.", + LockMode::LOCK_WHILE_RUNNING, + "32 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(RAID_CODE); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(BACKUP_SAVE); + PA_ADD_OPTION(HOST_ONLINE); + PA_ADD_OPTION(LOBBY_WAIT_DELAY0); + PA_ADD_OPTION(CATCHABILITY); + PA_ADD_OPTION(FRIEND_ACCEPT_USER_SLOT); + PA_ADD_OPTION(EXTRA_DELAY_BETWEEN_RAIDS0); + PA_ADD_OPTION(MOVE_SLOT); + PA_ADD_OPTION(DYNAMAX); + PA_ADD_OPTION(TROLL_HOSTING); + PA_ADD_OPTION(ALTERNATE_GAMES); + PA_ADD_OPTION(HOSTING_NOTIFICATIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_OPTION(m_internet_settings); + PA_ADD_OPTION(CONNECT_TO_INTERNET_DELAY0); + PA_ADD_OPTION(ENTER_ONLINE_DEN_DELAY0); + PA_ADD_OPTION(OPEN_ONLINE_DEN_LOBBY_DELAY0); + PA_ADD_OPTION(RAID_START_TO_EXIT_DELAY0); + PA_ADD_OPTION(DELAY_TO_SELECT_MOVE0); +} + + + +void AutoHostRolling::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + Milliseconds start_raid_delay = HOST_ONLINE + ? OPEN_ONLINE_DEN_LOBBY_DELAY0 + : GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0; + const Milliseconds lobby_wait_delay = LOBBY_WAIT_DELAY0.get() < start_raid_delay + ? 0ms + : LOBBY_WAIT_DELAY0.get() - start_raid_delay; + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + if (SKIPS == 0){ + TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); + } + rollback_date_from_home(env.console, context, SKIPS); + if (env.console.video().snapshot()){ + NintendoSwitch::resume_game_from_home(env.console, context); + }else{ + resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + } + + for (uint32_t raids = 0;; raids++){ + env.log("Raids Attempted: " + tostr_u_commas(raids)); + env.update_stats(); + + run_autohost( + env, env.console, context, + CATCHABILITY, SKIPS, + &RAID_CODE, lobby_wait_delay, + HOST_ONLINE, FRIEND_ACCEPT_USER_SLOT, + MOVE_SLOT, DYNAMAX, TROLL_HOSTING, + HOSTING_NOTIFICATIONS, + CONNECT_TO_INTERNET_DELAY0, + ENTER_ONLINE_DEN_DELAY0, + OPEN_ONLINE_DEN_LOBBY_DELAY0, + RAID_START_TO_EXIT_DELAY0, + DELAY_TO_SELECT_MOVE0 + ); + + // Exit game. + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + close_game(env.console, context); + + // Post-raid delay. + pbf_wait(context, EXTRA_DELAY_BETWEEN_RAIDS0); + + // Touch the date. + if (SKIPS == 0){ + TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); + }else{ + rollback_date_from_home(env.console, context, SKIPS); + } + + start_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, + ALTERNATE_GAMES ? 2 : 0, 0, + BACKUP_SAVE + ); + } +} + + + +} +} +} + + + + + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h index 9979d1fe42..0c9855d892 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost-Rolling.h @@ -1,78 +1,78 @@ -/* Rolling Auto-Host - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_AutoHostRolling_H -#define PokemonAutomation_PokemonSwSh_AutoHostRolling_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/RandomCodeOption.h" -//#include "CommonFramework/Options/ScreenshotFormatOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -//#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" -#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class AutoHostRolling_Descriptor : public SingleSwitchProgramDescriptor{ -public: - AutoHostRolling_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class AutoHostRolling : public SingleSwitchProgramInstance{ -public: - AutoHostRolling(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - RandomCodeOption RAID_CODE; - SimpleIntegerOption SKIPS; - BooleanCheckBoxOption BACKUP_SAVE; - BooleanCheckBoxOption HOST_ONLINE; - MillisecondsOption LOBBY_WAIT_DELAY0; - CatchabilitySelectorOption CATCHABILITY; - SimpleIntegerOption FRIEND_ACCEPT_USER_SLOT; - MillisecondsOption EXTRA_DELAY_BETWEEN_RAIDS0; - - SimpleIntegerOption MOVE_SLOT; - BooleanCheckBoxOption DYNAMAX; - SimpleIntegerOption TROLL_HOSTING; - - BooleanCheckBoxOption ALTERNATE_GAMES; - - AutoHostNotificationOption HOSTING_NOTIFICATIONS; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_internet_settings; - MillisecondsOption CONNECT_TO_INTERNET_DELAY0; - MillisecondsOption ENTER_ONLINE_DEN_DELAY0; - MillisecondsOption OPEN_ONLINE_DEN_LOBBY_DELAY0; - MillisecondsOption RAID_START_TO_EXIT_DELAY0; - MillisecondsOption DELAY_TO_SELECT_MOVE0; -}; - - - -} -} -} -#endif - +/* Rolling Auto-Host + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_AutoHostRolling_H +#define PokemonAutomation_PokemonSwSh_AutoHostRolling_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/RandomCodeOption.h" +//#include "CommonFramework/Options/ScreenshotFormatOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +//#include "NintendoSwitch/Options/NintendoSwitch_FriendCodeListOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" +#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class AutoHostRolling_Descriptor : public SingleSwitchProgramDescriptor{ +public: + AutoHostRolling_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class AutoHostRolling : public SingleSwitchProgramInstance{ +public: + AutoHostRolling(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + RandomCodeOption RAID_CODE; + SimpleIntegerOption SKIPS; + BooleanCheckBoxOption BACKUP_SAVE; + BooleanCheckBoxOption HOST_ONLINE; + MillisecondsOption LOBBY_WAIT_DELAY0; + CatchabilitySelectorOption CATCHABILITY; + SimpleIntegerOption FRIEND_ACCEPT_USER_SLOT; + MillisecondsOption EXTRA_DELAY_BETWEEN_RAIDS0; + + SimpleIntegerOption MOVE_SLOT; + BooleanCheckBoxOption DYNAMAX; + SimpleIntegerOption TROLL_HOSTING; + + BooleanCheckBoxOption ALTERNATE_GAMES; + + AutoHostNotificationOption HOSTING_NOTIFICATIONS; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_internet_settings; + MillisecondsOption CONNECT_TO_INTERNET_DELAY0; + MillisecondsOption ENTER_ONLINE_DEN_DELAY0; + MillisecondsOption OPEN_ONLINE_DEN_LOBBY_DELAY0; + MillisecondsOption RAID_START_TO_EXIT_DELAY0; + MillisecondsOption DELAY_TO_SELECT_MOVE0; +}; + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.cpp index 5df6b56e1d..b70f2b445e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.cpp @@ -1,259 +1,259 @@ -/* Auto-Hosting - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h" -#include "PokemonSwSh/Programs/PokemonSwSh_Internet.h" -#include "PokemonSwSh_DenTools.h" -#include "PokemonSwSh_AutoHostStats.h" -#include "PokemonSwSh_LobbyWait.h" -#include "PokemonSwSh_AutoHost.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -bool connect_to_internet( - VideoStream& stream, ProControllerContext& context, - bool host_online, - Milliseconds connect_to_internet_delay -){ - if (!host_online){ - return true; - } - if (!stream.video().snapshot()){ - connect_to_internet(context, GameSettings::instance().OPEN_YCOMM_DELAY0, connect_to_internet_delay); - return true; - } - if (connect_to_internet_with_inference( - stream, context, - std::chrono::seconds(5), connect_to_internet_delay - )){ - return true; - } - return false; -} - -void send_raid_notification( - ProgramEnvironment& env, - VideoStream& stream, - AutoHostNotificationOption& settings, - const std::string& code, - const ImageViewRGB32& screenshot, - const DenMonReadResults& results, - const StatsTracker& stats_tracker -){ - if (!settings.enabled()){ - return; - } - - std::vector> embeds; - - std::string description = settings.DESCRIPTION; - if (!description.empty()){ - embeds.emplace_back("Description:", description); - } - - std::string slugs; - - if (results.type == DenMonReadResults::NOT_DETECTED){ - slugs += "Unable to detect - Not in den lobby."; - }else if (results.slugs.results.empty()){ - slugs += "Unable to detect."; - }else if (results.slugs.results.size() == 1){ - slugs += results.slugs.results.begin()->second; - }else{ - slugs += "Ambiguous: "; - size_t c = 0; - for (const auto& item : results.slugs.results){ - if (c > 0){ - slugs += ", "; - } - slugs += item.second; - c++; - if (c >= 5){ - break; - } - } - if (c < results.slugs.results.size()){ - slugs += ", ("; - slugs += std::to_string(results.slugs.results.size() - c); - slugs += " more...)"; - } - } - embeds.emplace_back("Current " + STRING_POKEMON + ":", slugs); - - embeds.emplace_back("Raid Code:", code.empty() ? "None" : code); - - send_program_notification( - env, settings.NOTIFICATION, - Color(), - "Max Raid Notification", - embeds, "", - screenshot, false - ); - -} - - -void run_autohost( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - Catchability catchability, uint8_t skips, - const RandomCodeOption* raid_code, Milliseconds lobby_wait_delay, - bool host_online, uint8_t accept_FR_slot, - uint8_t move_slot, bool dynamax, uint8_t troll_hosting, - AutoHostNotificationOption& notifications, - Milliseconds connect_to_internet_delay, - Milliseconds enter_online_den_delay, - Milliseconds open_online_den_lobby_delay, - Milliseconds raid_start_to_exit_delay, - Milliseconds delay_to_select_move -){ - AutoHostStats& stats = env.current_stats(); - - roll_den( - console, context, - enter_online_den_delay, - open_online_den_lobby_delay, - skips, - catchability - ); - context.wait_for_all_requests(); - - if (!connect_to_internet( - console, context, - host_online, - connect_to_internet_delay - )){ - stats.add_timeout(); - env.log("Timed out waiting for internet connection. Skipping raid.", COLOR_RED); - return; - } - - { - DenMonReader reader(console.logger(), console.overlay()); - enter_den(context, enter_online_den_delay, skips != 0, host_online); - context.wait_for_all_requests(); - - // Make sure we're actually in a den. - VideoSnapshot screen = console.video().snapshot(); - DenMonReadResults results; - if (screen){ - results = reader.read(screen); - switch (results.type){ - case DenMonReadResults::RED_BEAM: - case DenMonReadResults::PURPLE_BEAM: - break; - default: - console.log("Failed to detect den lobby. Skipping raid.", COLOR_RED); - return; - } - } - - std::string code; - if (raid_code){ - code = raid_code->get_code(); - } - if (!code.empty()){ - char str[8]; - for (size_t c = 0; c < 8; c++){ - str[c] = code[c] + '0'; - } - env.log("Next Raid Code: " + std::string(str, sizeof(str))); - pbf_press_button(context, BUTTON_PLUS, 5, 145); - FastCodeEntry::numberpad_enter_code(console, context, code, true); - pbf_wait(context, 180); - pbf_press_button(context, BUTTON_A, 5, 95); - } - context.wait_for_all_requests(); - - screen = console.video().snapshot(); - send_raid_notification( - env, - console, - notifications, - code, - screen, results, stats - ); - } - - enter_lobby(context, open_online_den_lobby_delay, host_online, catchability); - - // Accept friend requests while we wait. - RaidLobbyState raid_state = raid_lobby_wait( - console, context, - host_online, - accept_FR_slot, - lobby_wait_delay - ); - - // Start Raid - pbf_press_dpad(context, DPAD_UP, 5, 45); - - // Mash A until it's time to close the game. - if (console.video().snapshot()){ - BlackScreenOverWatcher black_screen; - int ret = run_until( - console, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, raid_start_to_exit_delay); - }, - {black_screen} - ); - if (ret == 0){ - env.log("Raid has Started!", COLOR_BLUE); - stats.add_raid(raid_state.raiders()); - }else{ - env.log("Timed out waiting for raid to start.", COLOR_RED); - stats.add_timeout(); - } - }else{ - pbf_mash_button(context, BUTTON_A, raid_start_to_exit_delay); - } - - // Select a move. - if (move_slot > 0){ - pbf_wait(context, delay_to_select_move); - pbf_press_button(context, BUTTON_A, 20, 80); - if (dynamax){ - pbf_press_dpad(context, DPAD_LEFT, 20, 30); - pbf_press_button(context, BUTTON_A, 20, 60); - } - for (uint8_t c = 1; c < move_slot; c++){ - pbf_press_dpad(context, DPAD_DOWN, 20, 30); - } - pbf_press_button(context, BUTTON_A, 20, 80); - - // Disable the troll hosting option if the dynamax is set to TRUE. - if (!dynamax && troll_hosting > 0){ - pbf_press_dpad(context, DPAD_DOWN, 20, 80); - for (uint8_t c = 0; c < troll_hosting; c++){ - pbf_press_dpad(context, DPAD_RIGHT, 20, 80); - } - } - - pbf_press_button(context, BUTTON_A, 20, 980); - } -} - - - - -} -} -} +/* Auto-Hosting + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h" +#include "PokemonSwSh/Programs/PokemonSwSh_Internet.h" +#include "PokemonSwSh_DenTools.h" +#include "PokemonSwSh_AutoHostStats.h" +#include "PokemonSwSh_LobbyWait.h" +#include "PokemonSwSh_AutoHost.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +bool connect_to_internet( + VideoStream& stream, ProControllerContext& context, + bool host_online, + Milliseconds connect_to_internet_delay +){ + if (!host_online){ + return true; + } + if (!stream.video().snapshot()){ + connect_to_internet(context, GameSettings::instance().OPEN_YCOMM_DELAY0, connect_to_internet_delay); + return true; + } + if (connect_to_internet_with_inference( + stream, context, + std::chrono::seconds(5), connect_to_internet_delay + )){ + return true; + } + return false; +} + +void send_raid_notification( + ProgramEnvironment& env, + VideoStream& stream, + AutoHostNotificationOption& settings, + const std::string& code, + const ImageViewRGB32& screenshot, + const DenMonReadResults& results, + const StatsTracker& stats_tracker +){ + if (!settings.enabled()){ + return; + } + + std::vector> embeds; + + std::string description = settings.DESCRIPTION; + if (!description.empty()){ + embeds.emplace_back("Description:", description); + } + + std::string slugs; + + if (results.type == DenMonReadResults::NOT_DETECTED){ + slugs += "Unable to detect - Not in den lobby."; + }else if (results.slugs.results.empty()){ + slugs += "Unable to detect."; + }else if (results.slugs.results.size() == 1){ + slugs += results.slugs.results.begin()->second; + }else{ + slugs += "Ambiguous: "; + size_t c = 0; + for (const auto& item : results.slugs.results){ + if (c > 0){ + slugs += ", "; + } + slugs += item.second; + c++; + if (c >= 5){ + break; + } + } + if (c < results.slugs.results.size()){ + slugs += ", ("; + slugs += std::to_string(results.slugs.results.size() - c); + slugs += " more...)"; + } + } + embeds.emplace_back("Current " + STRING_POKEMON + ":", slugs); + + embeds.emplace_back("Raid Code:", code.empty() ? "None" : code); + + send_program_notification( + env, settings.NOTIFICATION, + Color(), + "Max Raid Notification", + embeds, "", + screenshot, false + ); + +} + + +void run_autohost( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + Catchability catchability, uint8_t skips, + const RandomCodeOption* raid_code, Milliseconds lobby_wait_delay, + bool host_online, uint8_t accept_FR_slot, + uint8_t move_slot, bool dynamax, uint8_t troll_hosting, + AutoHostNotificationOption& notifications, + Milliseconds connect_to_internet_delay, + Milliseconds enter_online_den_delay, + Milliseconds open_online_den_lobby_delay, + Milliseconds raid_start_to_exit_delay, + Milliseconds delay_to_select_move +){ + AutoHostStats& stats = env.current_stats(); + + roll_den( + console, context, + enter_online_den_delay, + open_online_den_lobby_delay, + skips, + catchability + ); + context.wait_for_all_requests(); + + if (!connect_to_internet( + console, context, + host_online, + connect_to_internet_delay + )){ + stats.add_timeout(); + env.log("Timed out waiting for internet connection. Skipping raid.", COLOR_RED); + return; + } + + { + DenMonReader reader(console.logger(), console.overlay()); + enter_den(context, enter_online_den_delay, skips != 0, host_online); + context.wait_for_all_requests(); + + // Make sure we're actually in a den. + VideoSnapshot screen = console.video().snapshot(); + DenMonReadResults results; + if (screen){ + results = reader.read(screen); + switch (results.type){ + case DenMonReadResults::RED_BEAM: + case DenMonReadResults::PURPLE_BEAM: + break; + default: + console.log("Failed to detect den lobby. Skipping raid.", COLOR_RED); + return; + } + } + + std::string code; + if (raid_code){ + code = raid_code->get_code(); + } + if (!code.empty()){ + char str[8]; + for (size_t c = 0; c < 8; c++){ + str[c] = code[c] + '0'; + } + env.log("Next Raid Code: " + std::string(str, sizeof(str))); + pbf_press_button(context, BUTTON_PLUS, 5, 145); + FastCodeEntry::numberpad_enter_code(console, context, code, true); + pbf_wait(context, 180); + pbf_press_button(context, BUTTON_A, 5, 95); + } + context.wait_for_all_requests(); + + screen = console.video().snapshot(); + send_raid_notification( + env, + console, + notifications, + code, + screen, results, stats + ); + } + + enter_lobby(context, open_online_den_lobby_delay, host_online, catchability); + + // Accept friend requests while we wait. + RaidLobbyState raid_state = raid_lobby_wait( + console, context, + host_online, + accept_FR_slot, + lobby_wait_delay + ); + + // Start Raid + pbf_press_dpad(context, DPAD_UP, 5, 45); + + // Mash A until it's time to close the game. + if (console.video().snapshot()){ + BlackScreenOverWatcher black_screen; + int ret = run_until( + console, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, raid_start_to_exit_delay); + }, + {black_screen} + ); + if (ret == 0){ + env.log("Raid has Started!", COLOR_BLUE); + stats.add_raid(raid_state.raiders()); + }else{ + env.log("Timed out waiting for raid to start.", COLOR_RED); + stats.add_timeout(); + } + }else{ + pbf_mash_button(context, BUTTON_A, raid_start_to_exit_delay); + } + + // Select a move. + if (move_slot > 0){ + pbf_wait(context, delay_to_select_move); + pbf_press_button(context, BUTTON_A, 20, 80); + if (dynamax){ + pbf_press_dpad(context, DPAD_LEFT, 20, 30); + pbf_press_button(context, BUTTON_A, 20, 60); + } + for (uint8_t c = 1; c < move_slot; c++){ + pbf_press_dpad(context, DPAD_DOWN, 20, 30); + } + pbf_press_button(context, BUTTON_A, 20, 80); + + // Disable the troll hosting option if the dynamax is set to TRUE. + if (!dynamax && troll_hosting > 0){ + pbf_press_dpad(context, DPAD_DOWN, 20, 80); + for (uint8_t c = 0; c < troll_hosting; c++){ + pbf_press_dpad(context, DPAD_RIGHT, 20, 80); + } + } + + pbf_press_button(context, BUTTON_A, 20, 980); + } +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.h index 97324ed1bb..30a3be4375 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHost.h @@ -1,62 +1,62 @@ -/* Auto-Hosting - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_AutoHost_H -#define PokemonAutomation_PokemonSwSh_AutoHost_H - -#include "Common/Cpp/Options/RandomCodeOption.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" -#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" - -namespace PokemonAutomation{ - struct ProgramInfo; - class ProgramEnvironment; - class StatsTracker; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -bool connect_to_internet( - VideoStream& stream, ProControllerContext& context, - bool host_online, - Milliseconds connect_to_internet_delay -); - -void send_raid_notification( - const ProgramEnvironment& env, - VideoStream& stream, - AutoHostNotificationOption& settings, - const std::string& code, - const ImageViewRGB32& screenshot, - const DenMonReadResults& results, - const StatsTracker& stats_tracker -); - - -void run_autohost( - ProgramEnvironment& env, - ConsoleHandle& console, ProControllerContext& context, - Catchability catchability, uint8_t skips, - const RandomCodeOption* raid_code, Milliseconds lobby_wait_delay, - bool host_online, uint8_t accept_FR_slot, - uint8_t move_slot, bool dynamax, uint8_t troll_hosting, - AutoHostNotificationOption& notifications, - Milliseconds connect_to_internet_delay, - Milliseconds enter_online_den_delay, - Milliseconds open_online_den_lobby_delay, - Milliseconds raid_start_to_exit_delay, - Milliseconds delay_to_select_move -); - - -} -} -} -#endif +/* Auto-Hosting + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_AutoHost_H +#define PokemonAutomation_PokemonSwSh_AutoHost_H + +#include "Common/Cpp/Options/RandomCodeOption.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" +#include "PokemonSwSh/Options/PokemonSwSh_AutoHostNotification.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" + +namespace PokemonAutomation{ + struct ProgramInfo; + class ProgramEnvironment; + class StatsTracker; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +bool connect_to_internet( + VideoStream& stream, ProControllerContext& context, + bool host_online, + Milliseconds connect_to_internet_delay +); + +void send_raid_notification( + const ProgramEnvironment& env, + VideoStream& stream, + AutoHostNotificationOption& settings, + const std::string& code, + const ImageViewRGB32& screenshot, + const DenMonReadResults& results, + const StatsTracker& stats_tracker +); + + +void run_autohost( + ProgramEnvironment& env, + ConsoleHandle& console, ProControllerContext& context, + Catchability catchability, uint8_t skips, + const RandomCodeOption* raid_code, Milliseconds lobby_wait_delay, + bool host_online, uint8_t accept_FR_slot, + uint8_t move_slot, bool dynamax, uint8_t troll_hosting, + AutoHostNotificationOption& notifications, + Milliseconds connect_to_internet_delay, + Milliseconds enter_online_den_delay, + Milliseconds open_online_den_lobby_delay, + Milliseconds raid_start_to_exit_delay, + Milliseconds delay_to_select_move +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.cpp index a69fa15172..a930735b21 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.cpp @@ -1,48 +1,48 @@ -/* Auto-Hosting Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_AutoHostStats.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -AutoHostStats::AutoHostStats() - : m_raids(m_stats["Raids"]) - , m_timeouts(m_stats["Timeouts"]) - , m_empty(m_stats["Empty Raids"]) - , m_full(m_stats["Full Raids"]) - , m_total(m_stats["Total Raiders"]) -{ - m_display_order.emplace_back("Raids"); - m_display_order.emplace_back("Timeouts"); - m_display_order.emplace_back("Empty Raids"); - m_display_order.emplace_back("Full Raids"); - m_display_order.emplace_back("Total Raiders"); -} - -void AutoHostStats::add_raid(size_t raiders){ - m_raids++; - m_total += raiders; - if (raiders == 0){ - m_empty++; - } - if (raiders == 3){ - m_full++; - } -} -void AutoHostStats::add_timeout(){ - m_timeouts++; -} - - - -} -} -} - +/* Auto-Hosting Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_AutoHostStats.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +AutoHostStats::AutoHostStats() + : m_raids(m_stats["Raids"]) + , m_timeouts(m_stats["Timeouts"]) + , m_empty(m_stats["Empty Raids"]) + , m_full(m_stats["Full Raids"]) + , m_total(m_stats["Total Raiders"]) +{ + m_display_order.emplace_back("Raids"); + m_display_order.emplace_back("Timeouts"); + m_display_order.emplace_back("Empty Raids"); + m_display_order.emplace_back("Full Raids"); + m_display_order.emplace_back("Total Raiders"); +} + +void AutoHostStats::add_raid(size_t raiders){ + m_raids++; + m_total += raiders; + if (raiders == 0){ + m_empty++; + } + if (raiders == 3){ + m_full++; + } +} +void AutoHostStats::add_timeout(){ + m_timeouts++; +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.h index 64b26cbb47..a0b4d1eade 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_AutoHostStats.h @@ -1,36 +1,36 @@ -/* Auto-Hosting Stats - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_AutoHostStats_H -#define PokemonAutomation_PokemonSwSh_AutoHostStats_H - -#include "CommonFramework/ProgramStats/StatsTracking.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class AutoHostStats : public StatsTracker{ -public: - AutoHostStats(); - - void add_raid(size_t raiders); - void add_timeout(); - -private: - std::atomic& m_raids; - std::atomic& m_timeouts; - std::atomic& m_empty; - std::atomic& m_full; - std::atomic& m_total; -}; - - -} -} -} -#endif +/* Auto-Hosting Stats + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_AutoHostStats_H +#define PokemonAutomation_PokemonSwSh_AutoHostStats_H + +#include "CommonFramework/ProgramStats/StatsTracking.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class AutoHostStats : public StatsTracker{ +public: + AutoHostStats(); + + void add_raid(size_t raiders); + void add_timeout(); + +private: + std::atomic& m_raids; + std::atomic& m_timeouts; + std::atomic& m_empty; + std::atomic& m_full; + std::atomic& m_total; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.cpp index 7ec24c4490..3dfbaa9c7b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.cpp @@ -1,206 +1,206 @@ -/* Den Roller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_DenTools.h" -#include "PokemonSwSh_DenRoller.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -DenRoller_Descriptor::DenRoller_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DenRoller", - STRING_POKEMON + " SwSh", "Den Roller", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DenRoller.md", - "Roll den to the N'th day, SR and repeat.", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -struct DenRoller_Descriptor::Stats : public StatsTracker{ - Stats() - : rolls(m_stats["Rolls"]) - , skips(m_stats["Day Skips"]) - , errors(m_stats["Errors"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back(Stat("Rolls")); - m_display_order.emplace_back(Stat("Day Skips")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Matches")); - } - std::atomic& rolls; - std::atomic& skips; - std::atomic& errors; - std::atomic& matches; -}; -std::unique_ptr DenRoller_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -DenRoller::DenRoller() - : SKIPS( - "Number of Skips:", - LockMode::LOCK_WHILE_RUNNING, - 3, 0, 60 - ) - , FILTER( - "Desired " + STRING_POKEMON + ":
" - "Automatically stop when this " + STRING_POKEMON + " is rolled. Video output is required." - ) - , VIEW_TIME0( - "View Time:
Wait this long before restting. This wait is skipped if the desired " + - STRING_POKEMON + " is set since the program will be watching it for you.", - LockMode::LOCK_WHILE_RUNNING, - "5 s" - ) - , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true, ImageAttachmentMode::JPG) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , READ_DELAY0( - "Read Delay:
Wait this long before attempting to " + - STRING_POKEMON + ". This needs to be long enough for the silhouette to load.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(SKIPS); - PA_ADD_OPTION(FILTER); - PA_ADD_OPTION(CATCHABILITY); - PA_ADD_OPTION(VIEW_TIME0); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(READ_DELAY0); -} - - - - -void DenRoller::ring_bell(ProControllerContext& context, int count) const{ - for (int c = 0; c < count; c++){ - pbf_press_button(context, BUTTON_LCLICK, 5, 10); - } - pbf_wait(context, 200); -} - -void DenRoller::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DenRoller_Descriptor::Stats& stats = env.current_stats(); - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - rollback_date_from_home(env.console, context, SKIPS); - if (env.console.video().snapshot()){ - NintendoSwitch::resume_game_from_home(env.console, context); - }else{ - resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - } - - - VideoSnapshot screen; - while (true){ - roll_den(env.console, context, 0ms, 0ms, SKIPS, CATCHABILITY); - - size_t desired_index = FILTER.index(); - std::string desired_slug = FILTER.slug(); - - if (desired_index == 0){ - ring_bell(context, 20); - }else{ - context.wait_for_all_requests(); - } - stats.rolls++; - stats.skips += SKIPS; - - { - DenMonReader reader(env.console, env.console); - - enter_den(context, 0ms, SKIPS != 0, false); - - if (desired_index != 0){ - pbf_wait(context, READ_DELAY0); - } - context.wait_for_all_requests(); - - screen = env.console.video().snapshot(); - DenMonReadResults results = reader.read(screen); - - // Give user time to look at the mon. - if (desired_index == 0){ - // No filter enabled. Keep going. - pbf_wait(context, VIEW_TIME0); - }else if (results.slugs.results.empty()){ - // No detection. Keep going. - stats.errors++; - dump_image(env.console, env.program_info(), "ReadDenMon", screen); - pbf_wait(context, VIEW_TIME0); - }else{ - // Check if we got what we wanted. - for (const auto& item : results.slugs.results){ - if (item.second == desired_slug){ - stats.matches++; - goto StopProgram; - } - } - } - } - env.update_stats(); - - // Add a little extra wait time since correctness matters here. - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - - rollback_date_from_home(env.console, context, SKIPS); -// reset_game_from_home(TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - -StopProgram: - env.update_stats(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Found a match!", - screen, false - ); -} - - - -} -} -} +/* Den Roller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_DenTools.h" +#include "PokemonSwSh_DenRoller.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +DenRoller_Descriptor::DenRoller_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DenRoller", + STRING_POKEMON + " SwSh", "Den Roller", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DenRoller.md", + "Roll den to the N'th day, SR and repeat.", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +struct DenRoller_Descriptor::Stats : public StatsTracker{ + Stats() + : rolls(m_stats["Rolls"]) + , skips(m_stats["Day Skips"]) + , errors(m_stats["Errors"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back(Stat("Rolls")); + m_display_order.emplace_back(Stat("Day Skips")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Matches")); + } + std::atomic& rolls; + std::atomic& skips; + std::atomic& errors; + std::atomic& matches; +}; +std::unique_ptr DenRoller_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +DenRoller::DenRoller() + : SKIPS( + "Number of Skips:", + LockMode::LOCK_WHILE_RUNNING, + 3, 0, 60 + ) + , FILTER( + "Desired " + STRING_POKEMON + ":
" + "Automatically stop when this " + STRING_POKEMON + " is rolled. Video output is required." + ) + , VIEW_TIME0( + "View Time:
Wait this long before restting. This wait is skipped if the desired " + + STRING_POKEMON + " is set since the program will be watching it for you.", + LockMode::LOCK_WHILE_RUNNING, + "5 s" + ) + , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true, ImageAttachmentMode::JPG) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , READ_DELAY0( + "Read Delay:
Wait this long before attempting to " + + STRING_POKEMON + ". This needs to be long enough for the silhouette to load.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(SKIPS); + PA_ADD_OPTION(FILTER); + PA_ADD_OPTION(CATCHABILITY); + PA_ADD_OPTION(VIEW_TIME0); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(READ_DELAY0); +} + + + + +void DenRoller::ring_bell(ProControllerContext& context, int count) const{ + for (int c = 0; c < count; c++){ + pbf_press_button(context, BUTTON_LCLICK, 5, 10); + } + pbf_wait(context, 200); +} + +void DenRoller::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DenRoller_Descriptor::Stats& stats = env.current_stats(); + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + rollback_date_from_home(env.console, context, SKIPS); + if (env.console.video().snapshot()){ + NintendoSwitch::resume_game_from_home(env.console, context); + }else{ + resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + } + + + VideoSnapshot screen; + while (true){ + roll_den(env.console, context, 0ms, 0ms, SKIPS, CATCHABILITY); + + size_t desired_index = FILTER.index(); + std::string desired_slug = FILTER.slug(); + + if (desired_index == 0){ + ring_bell(context, 20); + }else{ + context.wait_for_all_requests(); + } + stats.rolls++; + stats.skips += SKIPS; + + { + DenMonReader reader(env.console, env.console); + + enter_den(context, 0ms, SKIPS != 0, false); + + if (desired_index != 0){ + pbf_wait(context, READ_DELAY0); + } + context.wait_for_all_requests(); + + screen = env.console.video().snapshot(); + DenMonReadResults results = reader.read(screen); + + // Give user time to look at the mon. + if (desired_index == 0){ + // No filter enabled. Keep going. + pbf_wait(context, VIEW_TIME0); + }else if (results.slugs.results.empty()){ + // No detection. Keep going. + stats.errors++; + dump_image(env.console, env.program_info(), "ReadDenMon", screen); + pbf_wait(context, VIEW_TIME0); + }else{ + // Check if we got what we wanted. + for (const auto& item : results.slugs.results){ + if (item.second == desired_slug){ + stats.matches++; + goto StopProgram; + } + } + } + } + env.update_stats(); + + // Add a little extra wait time since correctness matters here. + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + + rollback_date_from_home(env.console, context, SKIPS); +// reset_game_from_home(TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + +StopProgram: + env.update_stats(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Found a match!", + screen, false + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.h index 1412252200..5a9c374706 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenRoller.h @@ -1,62 +1,62 @@ -/* Den Roller - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DenRoller_H -#define PokemonAutomation_PokemonSwSh_DenRoller_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DenRoller_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DenRoller_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class DenRoller : public SingleSwitchProgramInstance{ -public: - DenRoller(); - - void ring_bell(ProControllerContext& context, int count) const; - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption SKIPS; - DenMonSelectOption FILTER; - - CatchabilitySelectorOption CATCHABILITY; - MillisecondsOption VIEW_TIME0; - - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption READ_DELAY0; -}; - - - - -} -} -} -#endif +/* Den Roller + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DenRoller_H +#define PokemonAutomation_PokemonSwSh_DenRoller_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_DenMonReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DenRoller_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DenRoller_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class DenRoller : public SingleSwitchProgramInstance{ +public: + DenRoller(); + + void ring_bell(ProControllerContext& context, int count) const; + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption SKIPS; + DenMonSelectOption FILTER; + + CatchabilitySelectorOption CATCHABILITY; + MillisecondsOption VIEW_TIME0; + + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption READ_DELAY0; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp index 51e86d5899..06cda28c3f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.cpp @@ -1,161 +1,161 @@ -/* Den Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_DenTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void enter_den( - ProControllerContext& context, - Milliseconds ENTER_ONLINE_DEN_DELAY, - bool watts, - bool online -){ - if (!online){ - if (!watts){ - ssf_press_button(context, BUTTON_A, GameSettings::instance().ENTER_OFFLINE_DEN_DELAY0, 160ms); - }else{ - // This is the critical den-rolling path. It needs to be fast. - ssf_mash_AZs(context, GameSettings::instance().COLLECT_WATTS_OFFLINE_DELAY0); - pbf_wait(context, GameSettings::instance().ENTER_OFFLINE_DEN_DELAY0); - } - }else{ - if (!watts){ - ssf_press_button(context, BUTTON_A, ENTER_ONLINE_DEN_DELAY, 400ms); - }else{ - ssf_press_button(context, BUTTON_A, GameSettings::instance().COLLECT_WATTS_ONLINE_DELAY0, 400ms); - ssf_press_button(context, BUTTON_B, 800ms, 400ms); - ssf_press_button(context, BUTTON_B, ENTER_ONLINE_DEN_DELAY, 400ms); - } - } -} - - -void enter_lobby( - ProControllerContext& context, - Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, - bool online, - Catchability catchability -){ - if (online){ - switch (catchability){ - case Catchability::ALWAYS_CATCHABLE: - ssf_press_button(context, BUTTON_A, OPEN_ONLINE_DEN_LOBBY_DELAY); - return; - case Catchability::MAYBE_UNCATCHABLE: - case Catchability::ALWAYS_UNCATCHABLE: - ssf_press_button(context, BUTTON_A, GameSettings::instance().UNCATCHABLE_PROMPT_DELAY0); - ssf_press_button(context, BUTTON_A, OPEN_ONLINE_DEN_LOBBY_DELAY); - return; - } - } - - switch (catchability){ - case Catchability::ALWAYS_CATCHABLE: - ssf_press_button(context, BUTTON_A, GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0); - return; - case Catchability::MAYBE_UNCATCHABLE: - ssf_press_button(context, BUTTON_A, GameSettings::instance().UNCATCHABLE_PROMPT_DELAY0); - ssf_press_button(context, BUTTON_A, GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0); - - if (!GameSettings::instance().DODGE_UNCATCHABLE_PROMPT_FAST){ - // lobby-switch switch-box - ssf_press_dpad(context, DPAD_LEFT, 80ms); - // lobby-switch switch-party-red - ssf_press_button(context, BUTTON_A, GameSettings::instance().ENTER_SWITCH_POKEMON0); - // switch-box switch-confirm - ssf_press_button(context, BUTTON_Y, 80ms); - ssf_press_dpad(context, DPAD_LEFT, 80ms); - // switch-party-blue switch-confirm - ssf_press_button(context, BUTTON_A, GameSettings::instance().EXIT_SWITCH_POKEMON0); - // lobby-switch lobby-switch - } - return; - case Catchability::ALWAYS_UNCATCHABLE: - ssf_press_button(context, BUTTON_A, GameSettings::instance().UNCATCHABLE_PROMPT_DELAY0); - ssf_press_button(context, BUTTON_A, GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0); - return; - } -} - - -void roll_den( - ConsoleHandle& console, ProControllerContext& context, - Milliseconds ENTER_ONLINE_DEN_DELAY, - Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, - uint8_t skips, Catchability catchability -){ - if (skips > 60){ - skips = 60; - } - for (uint8_t c = 0; c < skips; c++){ - enter_den(context, ENTER_ONLINE_DEN_DELAY, c != 0, false); - enter_lobby(context, OPEN_ONLINE_DEN_LOBBY_DELAY, false, catchability); - - // Skip forward. - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 80ms); - home_to_date_time(console, context, true); - roll_date_forward_1(console, context, false); - - // Enter game - if (console.video().snapshot()){ - console.log("Entering game using inference..."); - pbf_press_button(context, BUTTON_HOME, 10, 90); - NintendoSwitch::resume_game_from_home(console, context); - }else{ - console.log("Entering game without inference...", COLOR_RED); - settings_to_enter_game_den_lobby( - context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, true, - GameSettings::instance().ENTER_SWITCH_POKEMON0, - GameSettings::instance().EXIT_SWITCH_POKEMON0 - ); - } - - // Exit Raid - ssf_press_button(context, BUTTON_B, 960ms, 400ms); - ssf_press_button(context, BUTTON_A, GameSettings::instance().REENTER_DEN_DELAY0, 400ms); - } -} -void rollback_date_from_home(ConsoleHandle& console, ProControllerContext& context, uint8_t skips){ - if (skips == 0){ - return; - } - if (skips > 60){ - skips = 60; - } - home_to_date_time(console, context, true); - roll_date_backward_N(console, context, skips, false); -// pbf_wait(5); - - // Note that it is possible for this return animation to run longer than - // "SETTINGS_TO_HOME_DELAY" and swallow a subsequent button press. - // Therefore the caller needs to be able to tolerate this. - ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); -} - - - - - - - -} -} -} +/* Den Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateForward1.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_RollDateBackwardN.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_DenTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void enter_den( + ProControllerContext& context, + Milliseconds ENTER_ONLINE_DEN_DELAY, + bool watts, + bool online +){ + if (!online){ + if (!watts){ + ssf_press_button(context, BUTTON_A, GameSettings::instance().ENTER_OFFLINE_DEN_DELAY0, 160ms); + }else{ + // This is the critical den-rolling path. It needs to be fast. + ssf_mash_AZs(context, GameSettings::instance().COLLECT_WATTS_OFFLINE_DELAY0); + pbf_wait(context, GameSettings::instance().ENTER_OFFLINE_DEN_DELAY0); + } + }else{ + if (!watts){ + ssf_press_button(context, BUTTON_A, ENTER_ONLINE_DEN_DELAY, 400ms); + }else{ + ssf_press_button(context, BUTTON_A, GameSettings::instance().COLLECT_WATTS_ONLINE_DELAY0, 400ms); + ssf_press_button(context, BUTTON_B, 800ms, 400ms); + ssf_press_button(context, BUTTON_B, ENTER_ONLINE_DEN_DELAY, 400ms); + } + } +} + + +void enter_lobby( + ProControllerContext& context, + Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, + bool online, + Catchability catchability +){ + if (online){ + switch (catchability){ + case Catchability::ALWAYS_CATCHABLE: + ssf_press_button(context, BUTTON_A, OPEN_ONLINE_DEN_LOBBY_DELAY); + return; + case Catchability::MAYBE_UNCATCHABLE: + case Catchability::ALWAYS_UNCATCHABLE: + ssf_press_button(context, BUTTON_A, GameSettings::instance().UNCATCHABLE_PROMPT_DELAY0); + ssf_press_button(context, BUTTON_A, OPEN_ONLINE_DEN_LOBBY_DELAY); + return; + } + } + + switch (catchability){ + case Catchability::ALWAYS_CATCHABLE: + ssf_press_button(context, BUTTON_A, GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0); + return; + case Catchability::MAYBE_UNCATCHABLE: + ssf_press_button(context, BUTTON_A, GameSettings::instance().UNCATCHABLE_PROMPT_DELAY0); + ssf_press_button(context, BUTTON_A, GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0); + + if (!GameSettings::instance().DODGE_UNCATCHABLE_PROMPT_FAST){ + // lobby-switch switch-box + ssf_press_dpad(context, DPAD_LEFT, 80ms); + // lobby-switch switch-party-red + ssf_press_button(context, BUTTON_A, GameSettings::instance().ENTER_SWITCH_POKEMON0); + // switch-box switch-confirm + ssf_press_button(context, BUTTON_Y, 80ms); + ssf_press_dpad(context, DPAD_LEFT, 80ms); + // switch-party-blue switch-confirm + ssf_press_button(context, BUTTON_A, GameSettings::instance().EXIT_SWITCH_POKEMON0); + // lobby-switch lobby-switch + } + return; + case Catchability::ALWAYS_UNCATCHABLE: + ssf_press_button(context, BUTTON_A, GameSettings::instance().UNCATCHABLE_PROMPT_DELAY0); + ssf_press_button(context, BUTTON_A, GameSettings::instance().OPEN_LOCAL_DEN_LOBBY_DELAY0); + return; + } +} + + +void roll_den( + ConsoleHandle& console, ProControllerContext& context, + Milliseconds ENTER_ONLINE_DEN_DELAY, + Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, + uint8_t skips, Catchability catchability +){ + if (skips > 60){ + skips = 60; + } + for (uint8_t c = 0; c < skips; c++){ + enter_den(context, ENTER_ONLINE_DEN_DELAY, c != 0, false); + enter_lobby(context, OPEN_ONLINE_DEN_LOBBY_DELAY, false, catchability); + + // Skip forward. + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 80ms); + home_to_date_time(console, context, true); + roll_date_forward_1(console, context, false); + + // Enter game + if (console.video().snapshot()){ + console.log("Entering game using inference..."); + pbf_press_button(context, BUTTON_HOME, 10, 90); + NintendoSwitch::resume_game_from_home(console, context); + }else{ + console.log("Entering game without inference...", COLOR_RED); + settings_to_enter_game_den_lobby( + context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, true, + GameSettings::instance().ENTER_SWITCH_POKEMON0, + GameSettings::instance().EXIT_SWITCH_POKEMON0 + ); + } + + // Exit Raid + ssf_press_button(context, BUTTON_B, 960ms, 400ms); + ssf_press_button(context, BUTTON_A, GameSettings::instance().REENTER_DEN_DELAY0, 400ms); + } +} +void rollback_date_from_home(ConsoleHandle& console, ProControllerContext& context, uint8_t skips){ + if (skips == 0){ + return; + } + if (skips > 60){ + skips = 60; + } + home_to_date_time(console, context, true); + roll_date_backward_N(console, context, skips, false); +// pbf_wait(5); + + // Note that it is possible for this return animation to run longer than + // "SETTINGS_TO_HOME_DELAY" and swallow a subsequent button press. + // Therefore the caller needs to be able to tolerate this. + ssf_press_button(context, BUTTON_HOME, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0, 160ms); +} + + + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h index f67389acc8..668c38b1ef 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h @@ -1,50 +1,50 @@ -/* Den Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DenTools_H -#define PokemonAutomation_PokemonSwSh_DenTools_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void enter_den( - ProControllerContext& context, - Milliseconds ENTER_ONLINE_DEN_DELAY, - bool watts, - bool online -); -void enter_lobby( - ProControllerContext& context, - Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, - bool online, - Catchability catchability -); - -void roll_den( - ConsoleHandle& console, ProControllerContext& context, - Milliseconds ENTER_ONLINE_DEN_DELAY, - Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, - uint8_t skips, Catchability catchability -); -void rollback_date_from_home( - ConsoleHandle& console, ProControllerContext& context, - uint8_t skips -); - - - - - -} -} -} -#endif +/* Den Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DenTools_H +#define PokemonAutomation_PokemonSwSh_DenTools_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" +#include "PokemonSwSh/Options/PokemonSwSh_Catchability.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void enter_den( + ProControllerContext& context, + Milliseconds ENTER_ONLINE_DEN_DELAY, + bool watts, + bool online +); +void enter_lobby( + ProControllerContext& context, + Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, + bool online, + Catchability catchability +); + +void roll_den( + ConsoleHandle& console, ProControllerContext& context, + Milliseconds ENTER_ONLINE_DEN_DELAY, + Milliseconds OPEN_ONLINE_DEN_LOBBY_DELAY, + uint8_t skips, Catchability catchability +); +void rollback_date_from_home( + ConsoleHandle& console, ProControllerContext& context, + uint8_t skips +); + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_LobbyWait.h b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_LobbyWait.h index 46e1abbd0e..7759302eaa 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_LobbyWait.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/Hosting/PokemonSwSh_LobbyWait.h @@ -1,108 +1,108 @@ -/* Lobby Wait - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_LobbyWait_H -#define PokemonAutomation_PokemonSwSh_LobbyWait_H - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -static RaidLobbyState raid_lobby_wait( - ConsoleHandle& console, ProControllerContext& context, - bool HOST_ONLINE, - uint8_t accept_FR_slot, - Milliseconds lobby_wait_delay -){ - Milliseconds GAME_TO_HOME_DELAY_SAFE = GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0; - Milliseconds AUTO_FR_DURATION = GameSettings::instance().AUTO_FR_DURATION0; - bool TOLERATE_SYSTEM_UPDATE_MENU_SLOW = ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW; - Milliseconds FULL_LOBBY_TIMER = GameSettings::instance().FULL_LOBBY_TIMER0; - - context.wait_for_all_requests(); - WallClock start = current_time(); - WallClock deadline_start_time = start + lobby_wait_delay; - WallClock deadline_lobby_limit = start + FULL_LOBBY_TIMER; - RaidLobbyReader inference(console.logger(), console.overlay()); - RaidLobbyState state; - - if (HOST_ONLINE && accept_FR_slot > 0){ - accept_FRs( - console, context, - accept_FR_slot - 1, true, - GAME_TO_HOME_DELAY_SAFE, - AUTO_FR_DURATION, - TOLERATE_SYSTEM_UPDATE_MENU_SLOW - ); - context.wait_for_all_requests(); - WallDuration time_elapsed = current_time() - start; - WallDuration delay = time_elapsed; - - while (true){ - state = inference.read(console.video().snapshot()); - if (state.valid && state.raid_is_full() && state.raiders_are_ready()){ - return state; - } - time_elapsed = current_time() - start; - if (time_elapsed + delay >= lobby_wait_delay){ - break; - } - accept_FRs( - console, context, - accept_FR_slot - 1, false, - GAME_TO_HOME_DELAY_SAFE, - AUTO_FR_DURATION, - TOLERATE_SYSTEM_UPDATE_MENU_SLOW - ); - context.wait_for_all_requests(); - } - } - - while (true){ - state = inference.read(console.video().snapshot()); - if (state.valid && state.raid_is_full() && state.raiders_are_ready()){ - return state; - } - if (current_time() > deadline_start_time){ - break; - } - context.wait_for(std::chrono::milliseconds(1000)); - } - -// context.wait_for_all_requests(); - - while (true){ - if (!state.valid || state.raiders_are_ready()){ - return state; - } - if (current_time() > deadline_lobby_limit){ - return state; - } - context.wait_for(std::chrono::milliseconds(1000)); - state = inference.read(console.video().snapshot()); - } -} - - - -} -} -} -#endif - +/* Lobby Wait + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_LobbyWait_H +#define PokemonAutomation_PokemonSwSh_LobbyWait_H + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidLobbyReader.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +static RaidLobbyState raid_lobby_wait( + ConsoleHandle& console, ProControllerContext& context, + bool HOST_ONLINE, + uint8_t accept_FR_slot, + Milliseconds lobby_wait_delay +){ + Milliseconds GAME_TO_HOME_DELAY_SAFE = GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0; + Milliseconds AUTO_FR_DURATION = GameSettings::instance().AUTO_FR_DURATION0; + bool TOLERATE_SYSTEM_UPDATE_MENU_SLOW = ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW; + Milliseconds FULL_LOBBY_TIMER = GameSettings::instance().FULL_LOBBY_TIMER0; + + context.wait_for_all_requests(); + WallClock start = current_time(); + WallClock deadline_start_time = start + lobby_wait_delay; + WallClock deadline_lobby_limit = start + FULL_LOBBY_TIMER; + RaidLobbyReader inference(console.logger(), console.overlay()); + RaidLobbyState state; + + if (HOST_ONLINE && accept_FR_slot > 0){ + accept_FRs( + console, context, + accept_FR_slot - 1, true, + GAME_TO_HOME_DELAY_SAFE, + AUTO_FR_DURATION, + TOLERATE_SYSTEM_UPDATE_MENU_SLOW + ); + context.wait_for_all_requests(); + WallDuration time_elapsed = current_time() - start; + WallDuration delay = time_elapsed; + + while (true){ + state = inference.read(console.video().snapshot()); + if (state.valid && state.raid_is_full() && state.raiders_are_ready()){ + return state; + } + time_elapsed = current_time() - start; + if (time_elapsed + delay >= lobby_wait_delay){ + break; + } + accept_FRs( + console, context, + accept_FR_slot - 1, false, + GAME_TO_HOME_DELAY_SAFE, + AUTO_FR_DURATION, + TOLERATE_SYSTEM_UPDATE_MENU_SLOW + ); + context.wait_for_all_requests(); + } + } + + while (true){ + state = inference.read(console.video().snapshot()); + if (state.valid && state.raid_is_full() && state.raiders_are_ready()){ + return state; + } + if (current_time() > deadline_start_time){ + break; + } + context.wait_for(std::chrono::milliseconds(1000)); + } + +// context.wait_for_all_requests(); + + while (true){ + if (!state.valid || state.raiders_are_ready()){ + return state; + } + if (current_time() > deadline_lobby_limit){ + return state; + } + context.wait_for(std::chrono::milliseconds(1000)); + state = inference.read(console.video().snapshot()); + } +} + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.cpp index 566be69847..cc22a1ce82 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.cpp @@ -1,306 +1,306 @@ -/* Stats Reset - Calyrex - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_StatsReset-Calyrex.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -StatsResetCalyrex_Descriptor::StatsResetCalyrex_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:StatsResetCalyrex", - STRING_POKEMON + " SwSh", "Stats Reset - Calyrex", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset-Calyrex.md", - "Repeatedly catch calyrex (and its horse) until you get the stats you want.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StatsResetCalyrex_Descriptor::Stats : public StatsTracker{ - Stats() - : pokemon_caught(m_stats["Pokemon caught"]) - , pokemon_fainted(m_stats["Pokemon fainted"]) - , own_fainted(m_stats["Own fainted"]) - , out_of_balls(m_stats["Out of balls"]) - , errors(m_stats["Errors"]) - , total_balls_thrown(m_stats["Total balls thrown"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back(Stat("Pokemon caught")); - m_display_order.emplace_back(Stat("Pokemon fainted")); - m_display_order.emplace_back(Stat("Own fainted")); - m_display_order.emplace_back(Stat("Out of balls")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Total balls thrown")); - m_display_order.emplace_back(Stat("Matches")); - } - - std::atomic& pokemon_caught; - std::atomic& pokemon_fainted; - std::atomic& own_fainted; - std::atomic& out_of_balls; - std::atomic& errors; - std::atomic& total_balls_thrown; - std::atomic& matches; -}; -std::unique_ptr StatsResetCalyrex_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -StatsResetCalyrex::StatsResetCalyrex() - : GO_HOME_WHEN_DONE(false) - , BALL_SELECT( - "Ball Select:", - LockMode::LOCK_WHILE_RUNNING, - "master-ball" - ) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , CHECK_CALYREX_STATS( - "Check Calyrex stats", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , CALYREX_HP("Calyrex HP:") - , CALYREX_ATTACK("Calyrex Attack:", IvJudgeFilter::NoGood) - , CALYREX_DEFENSE("Calyrex Defense:") - , CALYREX_SPATK("Calyrex Sp. Atk:") - , CALYREX_SPDEF("Calyrex Sp. Def:") - , CALYREX_SPEED("Calyrex Speed:") - , CHECK_HORSE_STATS( - "Check Horse stats", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , HORSE_HP("Horse HP:") - , HORSE_ATTACK("Horse Attack:", IvJudgeFilter::NoGood) - , HORSE_DEFENSE("Horse Defense:") - , HORSE_SPATK("Horse Sp. Atk:") - , HORSE_SPDEF("Horse Sp. Def:") - , HORSE_SPEED("Horse Speed:") - , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_CATCH_SUCCESS, - &NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(CHECK_CALYREX_STATS); - PA_ADD_OPTION(CALYREX_HP); - PA_ADD_OPTION(CALYREX_ATTACK); - PA_ADD_OPTION(CALYREX_DEFENSE); - PA_ADD_OPTION(CALYREX_SPATK); - PA_ADD_OPTION(CALYREX_SPDEF); - PA_ADD_OPTION(CALYREX_SPEED); - - PA_ADD_OPTION(CHECK_HORSE_STATS); - PA_ADD_OPTION(HORSE_HP); - PA_ADD_OPTION(HORSE_ATTACK); - PA_ADD_OPTION(HORSE_DEFENSE); - PA_ADD_OPTION(HORSE_SPATK); - PA_ADD_OPTION(HORSE_SPDEF); - PA_ADD_OPTION(HORSE_SPEED); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void StatsResetCalyrex::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - StatsResetCalyrex_Descriptor::Stats& stats = env.current_stats(); - - bool match_found = false; - while (!match_found){ - - bool calyrex_caught = false; - while (!calyrex_caught){ - env.log("Talk to calyrex.", COLOR_PURPLE); - context.wait_for_all_requests(); - { - StandardBattleMenuWatcher fight_detector(false); - int result = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - } - }, - {{fight_detector}} - ); - if (result == 0){ - env.log("New fight detected, let's begin to throw balls.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1000ms); - } - } - - pbf_mash_button(context, BUTTON_B, 1000ms); - CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); - switch (result.result){ - case CatchResult::POKEMON_CAUGHT: - calyrex_caught = true; - stats.pokemon_caught++; - break; - case CatchResult::POKEMON_FAINTED: - stats.pokemon_fainted++; - break; - case CatchResult::OWN_FAINTED: - stats.own_fainted++; - break; - case CatchResult::OUT_OF_BALLS: - stats.out_of_balls++; - break; - case CatchResult::BALL_LIMIT_REACHED: - case CatchResult::CANNOT_THROW_BALL: - case CatchResult::TIMED_OUT: - stats.errors++; - break; - } - stats.total_balls_thrown += result.balls_used; - env.update_stats(); - - if (calyrex_caught){ - send_program_status_notification( - env, NOTIFICATION_CATCH_SUCCESS, - "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." - ); - }else{ - send_program_status_notification( - env, NOTIFICATION_CATCH_FAILED, - "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." - ); - } - - if (!calyrex_caught){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - } - - env.log("Unfuse calyrex.", COLOR_PURPLE); - for (int i = 0; i < 40; i++){ - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - } - pbf_press_button(context, BUTTON_X , 80ms, 1500ms); - pbf_press_dpad (context, DPAD_RIGHT, 80ms, 500ms); - pbf_press_dpad (context, DPAD_RIGHT, 80ms, 500ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_dpad (context, DPAD_LEFT , 80ms, 500ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 500ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 2000ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - context.wait_for_all_requests(); - - env.log("Check the stats.", COLOR_PURPLE); - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_B, 80ms, 1000ms); - } - pbf_press_button(context, BUTTON_X , 80ms, 2000ms); - pbf_press_dpad (context, DPAD_LEFT, 80ms, 500ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_button(context, BUTTON_R , 80ms, 3000ms); - pbf_press_dpad (context, DPAD_LEFT, 80ms, 1000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); - - if (CHECK_HORSE_STATS){ - context.wait_for_all_requests(); - IvJudgeReaderScope reader(env.console, LANGUAGE); - IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); - bool horse_ok = true; - horse_ok &= HORSE_HP.matches(stats.errors, results.hp); - horse_ok &= HORSE_ATTACK.matches(stats.errors, results.attack); - horse_ok &= HORSE_DEFENSE.matches(stats.errors, results.defense); - horse_ok &= HORSE_SPATK.matches(stats.errors, results.spatk); - horse_ok &= HORSE_SPDEF.matches(stats.errors, results.spdef); - horse_ok &= HORSE_SPEED.matches(stats.errors, results.speed); - if (horse_ok){ - match_found = true; - } - } - if (CHECK_CALYREX_STATS){ - pbf_press_dpad(context, DPAD_UP, 80ms, 1000ms); - context.wait_for_all_requests(); - - IvJudgeReaderScope reader(env.console, LANGUAGE); - IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); - bool calyrex_ok = true; - calyrex_ok &= CALYREX_HP.matches(stats.errors, results.hp); - calyrex_ok &= CALYREX_ATTACK.matches(stats.errors, results.attack); - calyrex_ok &= CALYREX_DEFENSE.matches(stats.errors, results.defense); - calyrex_ok &= CALYREX_SPATK.matches(stats.errors, results.spatk); - calyrex_ok &= CALYREX_SPDEF.matches(stats.errors, results.spdef); - calyrex_ok &= CALYREX_SPEED.matches(stats.errors, results.speed); - if (calyrex_ok){ - match_found = true; - } - } - if (!match_found){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - } - stats.matches++; - env.log("Result Found!", COLOR_BLUE); - env.update_stats(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Found a perfect match!" - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} +/* Stats Reset - Calyrex + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_StatsReset-Calyrex.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +StatsResetCalyrex_Descriptor::StatsResetCalyrex_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:StatsResetCalyrex", + STRING_POKEMON + " SwSh", "Stats Reset - Calyrex", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset-Calyrex.md", + "Repeatedly catch calyrex (and its horse) until you get the stats you want.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StatsResetCalyrex_Descriptor::Stats : public StatsTracker{ + Stats() + : pokemon_caught(m_stats["Pokemon caught"]) + , pokemon_fainted(m_stats["Pokemon fainted"]) + , own_fainted(m_stats["Own fainted"]) + , out_of_balls(m_stats["Out of balls"]) + , errors(m_stats["Errors"]) + , total_balls_thrown(m_stats["Total balls thrown"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back(Stat("Pokemon caught")); + m_display_order.emplace_back(Stat("Pokemon fainted")); + m_display_order.emplace_back(Stat("Own fainted")); + m_display_order.emplace_back(Stat("Out of balls")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Total balls thrown")); + m_display_order.emplace_back(Stat("Matches")); + } + + std::atomic& pokemon_caught; + std::atomic& pokemon_fainted; + std::atomic& own_fainted; + std::atomic& out_of_balls; + std::atomic& errors; + std::atomic& total_balls_thrown; + std::atomic& matches; +}; +std::unique_ptr StatsResetCalyrex_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +StatsResetCalyrex::StatsResetCalyrex() + : GO_HOME_WHEN_DONE(false) + , BALL_SELECT( + "Ball Select:", + LockMode::LOCK_WHILE_RUNNING, + "master-ball" + ) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , CHECK_CALYREX_STATS( + "Check Calyrex stats", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , CALYREX_HP("Calyrex HP:") + , CALYREX_ATTACK("Calyrex Attack:", IvJudgeFilter::NoGood) + , CALYREX_DEFENSE("Calyrex Defense:") + , CALYREX_SPATK("Calyrex Sp. Atk:") + , CALYREX_SPDEF("Calyrex Sp. Def:") + , CALYREX_SPEED("Calyrex Speed:") + , CHECK_HORSE_STATS( + "Check Horse stats", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , HORSE_HP("Horse HP:") + , HORSE_ATTACK("Horse Attack:", IvJudgeFilter::NoGood) + , HORSE_DEFENSE("Horse Defense:") + , HORSE_SPATK("Horse Sp. Atk:") + , HORSE_SPDEF("Horse Sp. Def:") + , HORSE_SPEED("Horse Speed:") + , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_CATCH_SUCCESS, + &NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(CHECK_CALYREX_STATS); + PA_ADD_OPTION(CALYREX_HP); + PA_ADD_OPTION(CALYREX_ATTACK); + PA_ADD_OPTION(CALYREX_DEFENSE); + PA_ADD_OPTION(CALYREX_SPATK); + PA_ADD_OPTION(CALYREX_SPDEF); + PA_ADD_OPTION(CALYREX_SPEED); + + PA_ADD_OPTION(CHECK_HORSE_STATS); + PA_ADD_OPTION(HORSE_HP); + PA_ADD_OPTION(HORSE_ATTACK); + PA_ADD_OPTION(HORSE_DEFENSE); + PA_ADD_OPTION(HORSE_SPATK); + PA_ADD_OPTION(HORSE_SPDEF); + PA_ADD_OPTION(HORSE_SPEED); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void StatsResetCalyrex::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + StatsResetCalyrex_Descriptor::Stats& stats = env.current_stats(); + + bool match_found = false; + while (!match_found){ + + bool calyrex_caught = false; + while (!calyrex_caught){ + env.log("Talk to calyrex.", COLOR_PURPLE); + context.wait_for_all_requests(); + { + StandardBattleMenuWatcher fight_detector(false); + int result = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + } + }, + {{fight_detector}} + ); + if (result == 0){ + env.log("New fight detected, let's begin to throw balls.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1000ms); + } + } + + pbf_mash_button(context, BUTTON_B, 1000ms); + CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); + switch (result.result){ + case CatchResult::POKEMON_CAUGHT: + calyrex_caught = true; + stats.pokemon_caught++; + break; + case CatchResult::POKEMON_FAINTED: + stats.pokemon_fainted++; + break; + case CatchResult::OWN_FAINTED: + stats.own_fainted++; + break; + case CatchResult::OUT_OF_BALLS: + stats.out_of_balls++; + break; + case CatchResult::BALL_LIMIT_REACHED: + case CatchResult::CANNOT_THROW_BALL: + case CatchResult::TIMED_OUT: + stats.errors++; + break; + } + stats.total_balls_thrown += result.balls_used; + env.update_stats(); + + if (calyrex_caught){ + send_program_status_notification( + env, NOTIFICATION_CATCH_SUCCESS, + "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." + ); + }else{ + send_program_status_notification( + env, NOTIFICATION_CATCH_FAILED, + "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." + ); + } + + if (!calyrex_caught){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + } + + env.log("Unfuse calyrex.", COLOR_PURPLE); + for (int i = 0; i < 40; i++){ + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + } + pbf_press_button(context, BUTTON_X , 80ms, 1500ms); + pbf_press_dpad (context, DPAD_RIGHT, 80ms, 500ms); + pbf_press_dpad (context, DPAD_RIGHT, 80ms, 500ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_dpad (context, DPAD_LEFT , 80ms, 500ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 500ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 2000ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + context.wait_for_all_requests(); + + env.log("Check the stats.", COLOR_PURPLE); + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_B, 80ms, 1000ms); + } + pbf_press_button(context, BUTTON_X , 80ms, 2000ms); + pbf_press_dpad (context, DPAD_LEFT, 80ms, 500ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_button(context, BUTTON_R , 80ms, 3000ms); + pbf_press_dpad (context, DPAD_LEFT, 80ms, 1000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); + + if (CHECK_HORSE_STATS){ + context.wait_for_all_requests(); + IvJudgeReaderScope reader(env.console, LANGUAGE); + IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); + bool horse_ok = true; + horse_ok &= HORSE_HP.matches(stats.errors, results.hp); + horse_ok &= HORSE_ATTACK.matches(stats.errors, results.attack); + horse_ok &= HORSE_DEFENSE.matches(stats.errors, results.defense); + horse_ok &= HORSE_SPATK.matches(stats.errors, results.spatk); + horse_ok &= HORSE_SPDEF.matches(stats.errors, results.spdef); + horse_ok &= HORSE_SPEED.matches(stats.errors, results.speed); + if (horse_ok){ + match_found = true; + } + } + if (CHECK_CALYREX_STATS){ + pbf_press_dpad(context, DPAD_UP, 80ms, 1000ms); + context.wait_for_all_requests(); + + IvJudgeReaderScope reader(env.console, LANGUAGE); + IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); + bool calyrex_ok = true; + calyrex_ok &= CALYREX_HP.matches(stats.errors, results.hp); + calyrex_ok &= CALYREX_ATTACK.matches(stats.errors, results.attack); + calyrex_ok &= CALYREX_DEFENSE.matches(stats.errors, results.defense); + calyrex_ok &= CALYREX_SPATK.matches(stats.errors, results.spatk); + calyrex_ok &= CALYREX_SPDEF.matches(stats.errors, results.spdef); + calyrex_ok &= CALYREX_SPEED.matches(stats.errors, results.speed); + if (calyrex_ok){ + match_found = true; + } + } + if (!match_found){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + } + stats.matches++; + env.log("Result Found!", COLOR_BLUE); + env.update_stats(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Found a perfect match!" + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h index 1c432b54a2..c323741375 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Calyrex.h @@ -1,73 +1,73 @@ -/* Stats Reset - Calyrex - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StatsResetCalyrex_H -#define PokemonAutomation_PokemonSwSh_StatsResetCalyrex_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "Pokemon/Options/Pokemon_IvJudgeOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class StatsResetCalyrex_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StatsResetCalyrex_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class StatsResetCalyrex : public SingleSwitchProgramInstance{ -public: - StatsResetCalyrex(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - PokemonBallSelectOption BALL_SELECT; - OCR::LanguageOCROption LANGUAGE; - - BooleanCheckBoxOption CHECK_CALYREX_STATS; - IVJudgeFilterOption CALYREX_HP; - IVJudgeFilterOption CALYREX_ATTACK; - IVJudgeFilterOption CALYREX_DEFENSE; - IVJudgeFilterOption CALYREX_SPATK; - IVJudgeFilterOption CALYREX_SPDEF; - IVJudgeFilterOption CALYREX_SPEED; - - BooleanCheckBoxOption CHECK_HORSE_STATS; - IVJudgeFilterOption HORSE_HP; - IVJudgeFilterOption HORSE_ATTACK; - IVJudgeFilterOption HORSE_DEFENSE; - IVJudgeFilterOption HORSE_SPATK; - IVJudgeFilterOption HORSE_SPDEF; - IVJudgeFilterOption HORSE_SPEED; - - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Stats Reset - Calyrex + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StatsResetCalyrex_H +#define PokemonAutomation_PokemonSwSh_StatsResetCalyrex_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "Pokemon/Options/Pokemon_IvJudgeOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class StatsResetCalyrex_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StatsResetCalyrex_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class StatsResetCalyrex : public SingleSwitchProgramInstance{ +public: + StatsResetCalyrex(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + PokemonBallSelectOption BALL_SELECT; + OCR::LanguageOCROption LANGUAGE; + + BooleanCheckBoxOption CHECK_CALYREX_STATS; + IVJudgeFilterOption CALYREX_HP; + IVJudgeFilterOption CALYREX_ATTACK; + IVJudgeFilterOption CALYREX_DEFENSE; + IVJudgeFilterOption CALYREX_SPATK; + IVJudgeFilterOption CALYREX_SPDEF; + IVJudgeFilterOption CALYREX_SPEED; + + BooleanCheckBoxOption CHECK_HORSE_STATS; + IVJudgeFilterOption HORSE_HP; + IVJudgeFilterOption HORSE_ATTACK; + IVJudgeFilterOption HORSE_DEFENSE; + IVJudgeFilterOption HORSE_SPATK; + IVJudgeFilterOption HORSE_SPDEF; + IVJudgeFilterOption HORSE_SPEED; + + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.cpp index cb45458cc1..6eb0e47b17 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.cpp @@ -1,234 +1,234 @@ -/* Stats Reset - Moltres - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_StatsReset-Moltres.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -StatsResetMoltres_Descriptor::StatsResetMoltres_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:StatsResetMoltres", - STRING_POKEMON + " SwSh", "Stats Reset - Moltres", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset-Moltres.md", - "Repeatedly catch moltres until you get the stats you want.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StatsResetMoltres_Descriptor::Stats : public StatsTracker{ - Stats() - : resets(m_stats["Resets"]) - , errors(m_stats["Errors"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back(Stat("Resets")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Matches")); - } - - std::atomic& resets; - std::atomic& errors; - std::atomic& matches; -}; -std::unique_ptr StatsResetMoltres_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - - -StatsResetMoltres::StatsResetMoltres() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , HP("HP:") - , ATTACK("Attack:", IvJudgeFilter::NoGood) - , DEFENSE("Defense:") - , SPATK("Sp. Atk:") - , SPDEF("Sp. Def:") - , SPEED("Speed:") - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(HP); - PA_ADD_OPTION(ATTACK); - PA_ADD_OPTION(DEFENSE); - PA_ADD_OPTION(SPATK); - PA_ADD_OPTION(SPDEF); - PA_ADD_OPTION(SPEED); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void StatsResetMoltres::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - StatsResetMoltres_Descriptor::Stats& stats = env.current_stats(); - - while (true){ - context.wait_for_all_requests(); - env.log("Wait for moltres to attack you.", COLOR_PURPLE); - { - StandardBattleMenuWatcher fight_detector(false); - int result = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - pbf_wait(context, 1000ms); - } - }, - {{fight_detector}} - ); - if (result == 0){ - env.log("New fight detected.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1000ms); - } - } - - context.wait_for_all_requests(); - CatchResults result = basic_catcher(env.console, context, LANGUAGE, "master-ball", 999); - if (result.result != CatchResult::POKEMON_CAUGHT){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Unable to catch Moltres.", - env.console - ); - } - - context.wait_for_all_requests(); - env.log("Exit the fight.", COLOR_PURPLE); - for (int i = 0; i < 20; i++){ - pbf_press_button(context, BUTTON_B, 80ms, 1000ms); - } - - context.wait_for_all_requests(); - env.log("Check the stats.", COLOR_PURPLE); - pbf_press_button(context, BUTTON_X , 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_dpad (context, DPAD_UP , 80ms, 500ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_button(context, BUTTON_R , 80ms, 3000ms); - pbf_press_dpad (context, DPAD_LEFT, 80ms, 1000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); - - context.wait_for_all_requests(); - IvJudgeReaderScope reader(env.console, LANGUAGE); - IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); - bool ok = true; - ok &= HP.matches(stats.errors, results.hp); - ok &= ATTACK.matches(stats.errors, results.attack); - ok &= DEFENSE.matches(stats.errors, results.defense); - ok &= SPATK.matches(stats.errors, results.spatk); - ok &= SPDEF.matches(stats.errors, results.spdef); - ok &= SPEED.matches(stats.errors, results.speed); - env.update_stats(); - if (ok){ - break; - }else{ - stats.resets++; - env.update_stats(); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - - context.wait_for_all_requests(); - env.log("Wait for moltres to attack you.", COLOR_PURPLE); - { - StandardBattleMenuWatcher fight_detector(false); - int ret = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - pbf_wait(context, 1000ms); - } - }, - {{fight_detector}} - ); - if (ret == 0){ - env.log("New fight detected.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1000ms); - pbf_press_dpad(context, DPAD_UP , 80ms, 1000ms); - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - } - } - for (int i = 0; i < 10; i++){ - pbf_press_button(context, BUTTON_B, 80ms, 1000ms); - } - - context.wait_for_all_requests(); - env.log("Let's camp.", COLOR_PURPLE); - pbf_press_button(context, BUTTON_X , 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_dpad (context, DPAD_RIGHT, 80ms, 1000ms); - pbf_press_dpad (context, DPAD_DOWN , 80ms, 1000ms); - pbf_press_button(context, BUTTON_A , 80ms, 8000ms); - pbf_press_button(context, BUTTON_X , 80ms, 1000ms); - pbf_press_dpad (context, DPAD_LEFT , 80ms, 1000ms); - pbf_press_button(context, BUTTON_A , 80ms, 7000ms); - - context.wait_for_all_requests(); - env.log("Let's save.", COLOR_PURPLE); - pbf_press_button(context, BUTTON_X , 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_R , 80ms, 1000ms); - pbf_press_button(context, BUTTON_A , 80ms, 1000ms); - pbf_press_button(context, BUTTON_A , 80ms, 1000ms); - } - } - - env.log("Result Found!", COLOR_BLUE); - stats.matches++; - - env.update_stats(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Found a perfect match!" - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} +/* Stats Reset - Moltres + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_StatsReset-Moltres.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +StatsResetMoltres_Descriptor::StatsResetMoltres_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:StatsResetMoltres", + STRING_POKEMON + " SwSh", "Stats Reset - Moltres", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset-Moltres.md", + "Repeatedly catch moltres until you get the stats you want.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StatsResetMoltres_Descriptor::Stats : public StatsTracker{ + Stats() + : resets(m_stats["Resets"]) + , errors(m_stats["Errors"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back(Stat("Resets")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Matches")); + } + + std::atomic& resets; + std::atomic& errors; + std::atomic& matches; +}; +std::unique_ptr StatsResetMoltres_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + + +StatsResetMoltres::StatsResetMoltres() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , HP("HP:") + , ATTACK("Attack:", IvJudgeFilter::NoGood) + , DEFENSE("Defense:") + , SPATK("Sp. Atk:") + , SPDEF("Sp. Def:") + , SPEED("Speed:") + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(HP); + PA_ADD_OPTION(ATTACK); + PA_ADD_OPTION(DEFENSE); + PA_ADD_OPTION(SPATK); + PA_ADD_OPTION(SPDEF); + PA_ADD_OPTION(SPEED); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void StatsResetMoltres::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + StatsResetMoltres_Descriptor::Stats& stats = env.current_stats(); + + while (true){ + context.wait_for_all_requests(); + env.log("Wait for moltres to attack you.", COLOR_PURPLE); + { + StandardBattleMenuWatcher fight_detector(false); + int result = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + pbf_wait(context, 1000ms); + } + }, + {{fight_detector}} + ); + if (result == 0){ + env.log("New fight detected.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1000ms); + } + } + + context.wait_for_all_requests(); + CatchResults result = basic_catcher(env.console, context, LANGUAGE, "master-ball", 999); + if (result.result != CatchResult::POKEMON_CAUGHT){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Unable to catch Moltres.", + env.console + ); + } + + context.wait_for_all_requests(); + env.log("Exit the fight.", COLOR_PURPLE); + for (int i = 0; i < 20; i++){ + pbf_press_button(context, BUTTON_B, 80ms, 1000ms); + } + + context.wait_for_all_requests(); + env.log("Check the stats.", COLOR_PURPLE); + pbf_press_button(context, BUTTON_X , 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_dpad (context, DPAD_UP , 80ms, 500ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_button(context, BUTTON_R , 80ms, 3000ms); + pbf_press_dpad (context, DPAD_LEFT, 80ms, 1000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); + + context.wait_for_all_requests(); + IvJudgeReaderScope reader(env.console, LANGUAGE); + IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); + bool ok = true; + ok &= HP.matches(stats.errors, results.hp); + ok &= ATTACK.matches(stats.errors, results.attack); + ok &= DEFENSE.matches(stats.errors, results.defense); + ok &= SPATK.matches(stats.errors, results.spatk); + ok &= SPDEF.matches(stats.errors, results.spdef); + ok &= SPEED.matches(stats.errors, results.speed); + env.update_stats(); + if (ok){ + break; + }else{ + stats.resets++; + env.update_stats(); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + + context.wait_for_all_requests(); + env.log("Wait for moltres to attack you.", COLOR_PURPLE); + { + StandardBattleMenuWatcher fight_detector(false); + int ret = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + pbf_wait(context, 1000ms); + } + }, + {{fight_detector}} + ); + if (ret == 0){ + env.log("New fight detected.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1000ms); + pbf_press_dpad(context, DPAD_UP , 80ms, 1000ms); + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + } + } + for (int i = 0; i < 10; i++){ + pbf_press_button(context, BUTTON_B, 80ms, 1000ms); + } + + context.wait_for_all_requests(); + env.log("Let's camp.", COLOR_PURPLE); + pbf_press_button(context, BUTTON_X , 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_dpad (context, DPAD_RIGHT, 80ms, 1000ms); + pbf_press_dpad (context, DPAD_DOWN , 80ms, 1000ms); + pbf_press_button(context, BUTTON_A , 80ms, 8000ms); + pbf_press_button(context, BUTTON_X , 80ms, 1000ms); + pbf_press_dpad (context, DPAD_LEFT , 80ms, 1000ms); + pbf_press_button(context, BUTTON_A , 80ms, 7000ms); + + context.wait_for_all_requests(); + env.log("Let's save.", COLOR_PURPLE); + pbf_press_button(context, BUTTON_X , 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_R , 80ms, 1000ms); + pbf_press_button(context, BUTTON_A , 80ms, 1000ms); + pbf_press_button(context, BUTTON_A , 80ms, 1000ms); + } + } + + env.log("Result Found!", COLOR_BLUE); + stats.matches++; + + env.update_stats(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Found a perfect match!" + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h index 67a8bc5a1a..ca261e780b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Moltres.h @@ -1,58 +1,58 @@ -/* Stats Reset - Moltres - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StatsResetMoltres_H -#define PokemonAutomation_PokemonSwSh_StatsResetMoltres_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "Pokemon/Options/Pokemon_IvJudgeOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class StatsResetMoltres_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StatsResetMoltres_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class StatsResetMoltres : public SingleSwitchProgramInstance{ -public: - StatsResetMoltres(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - IVJudgeFilterOption HP; - IVJudgeFilterOption ATTACK; - IVJudgeFilterOption DEFENSE; - IVJudgeFilterOption SPATK; - IVJudgeFilterOption SPDEF; - IVJudgeFilterOption SPEED; - - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Stats Reset - Moltres + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StatsResetMoltres_H +#define PokemonAutomation_PokemonSwSh_StatsResetMoltres_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Pokemon/Options/Pokemon_IvJudgeOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class StatsResetMoltres_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StatsResetMoltres_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class StatsResetMoltres : public SingleSwitchProgramInstance{ +public: + StatsResetMoltres(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + IVJudgeFilterOption HP; + IVJudgeFilterOption ATTACK; + IVJudgeFilterOption DEFENSE; + IVJudgeFilterOption SPATK; + IVJudgeFilterOption SPDEF; + IVJudgeFilterOption SPEED; + + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.cpp index c33ba62bca..211af63797 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.cpp @@ -1,245 +1,245 @@ -/* Stats Reset - Regi - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_StatsReset-Regi.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -StatsResetRegi_Descriptor::StatsResetRegi_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:StatsResetRegi", - STRING_POKEMON + " SwSh", "Stats Reset - Regi", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset-Regi.md", - "Repeatedly catch regi until you get the stats you want.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StatsResetRegi_Descriptor::Stats : public StatsTracker{ - Stats() - : pokemon_caught(m_stats["Pokemon caught"]) - , pokemon_fainted(m_stats["Pokemon fainted"]) - , own_fainted(m_stats["Own fainted"]) - , out_of_balls(m_stats["Out of balls"]) - , errors(m_stats["Errors"]) - , total_balls_thrown(m_stats["Total balls thrown"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back(Stat("Pokemon caught")); - m_display_order.emplace_back(Stat("Pokemon fainted")); - m_display_order.emplace_back(Stat("Own fainted")); - m_display_order.emplace_back(Stat("Out of balls")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Total balls thrown")); - m_display_order.emplace_back(Stat("Matches")); - } - - std::atomic& pokemon_caught; - std::atomic& pokemon_fainted; - std::atomic& own_fainted; - std::atomic& out_of_balls; - std::atomic& errors; - std::atomic& total_balls_thrown; - std::atomic& matches; -}; -std::unique_ptr StatsResetRegi_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -StatsResetRegi::StatsResetRegi() - : GO_HOME_WHEN_DONE(false) - , BALL_SELECT( - "Ball Select:", - LockMode::LOCK_WHILE_RUNNING, - "master-ball" - ) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , HP("HP:") - , ATTACK("Attack:", IvJudgeFilter::NoGood) - , DEFENSE("Defense:") - , SPATK("Sp. Atk:") - , SPDEF("Sp. Def:") - , SPEED("Speed:") - , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) - , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_CATCH_SUCCESS, - &NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(BALL_SELECT); - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(HP); - PA_ADD_OPTION(ATTACK); - PA_ADD_OPTION(DEFENSE); - PA_ADD_OPTION(SPATK); - PA_ADD_OPTION(SPDEF); - PA_ADD_OPTION(SPEED); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void StatsResetRegi::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - StatsResetRegi_Descriptor::Stats& stats = env.current_stats(); - - bool match_found = false; - while (!match_found){ - - bool regi_caught = false; - while (!regi_caught){ - env.log("Talk to regi.", COLOR_PURPLE); - context.wait_for_all_requests(); - { - StandardBattleMenuWatcher fight_detector(false); - int result = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - pbf_press_button(context, BUTTON_A, 80ms, 1000ms); - } - }, - {{fight_detector}} - ); - if (result == 0){ - env.log("New fight detected, let's begin to throw balls.", COLOR_PURPLE); - pbf_mash_button(context, BUTTON_B, 1000ms); - } - } - - env.log("Catch regi.", COLOR_PURPLE); - CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); - switch (result.result){ - case CatchResult::POKEMON_CAUGHT: - regi_caught = true; - stats.pokemon_caught++; - break; - case CatchResult::POKEMON_FAINTED: - stats.pokemon_fainted++; - break; - case CatchResult::OWN_FAINTED: - stats.own_fainted++; - break; - case CatchResult::OUT_OF_BALLS: - stats.out_of_balls++; - break; - case CatchResult::BALL_LIMIT_REACHED: - case CatchResult::CANNOT_THROW_BALL: - case CatchResult::TIMED_OUT: - stats.errors++; - break; - } - stats.total_balls_thrown += result.balls_used; - env.update_stats(); - - if (regi_caught){ - send_program_status_notification( - env, NOTIFICATION_CATCH_SUCCESS, - "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." - ); - }else{ - send_program_status_notification( - env, NOTIFICATION_CATCH_FAILED, - "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." - ); - } - - if (!regi_caught){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - } - - env.log("Check the stats.", COLOR_PURPLE); - for (int i = 0; i < 20; i++){ - pbf_press_button(context, BUTTON_B, 80ms, 1000ms); - } - pbf_press_button(context, BUTTON_X , 80ms, 2000ms); - pbf_press_dpad (context, DPAD_RIGHT, 80ms, 500ms); - pbf_press_button(context, BUTTON_A , 80ms, 2000ms); - pbf_press_button(context, BUTTON_R , 80ms, 3000ms); - pbf_press_dpad (context, DPAD_LEFT , 80ms, 1000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); - pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); - - context.wait_for_all_requests(); - IvJudgeReaderScope reader(env.console, LANGUAGE); - IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); - bool ok = true; - ok &= HP.matches(stats.errors, results.hp); - ok &= ATTACK.matches(stats.errors, results.attack); - ok &= DEFENSE.matches(stats.errors, results.defense); - ok &= SPATK.matches(stats.errors, results.spatk); - ok &= SPDEF.matches(stats.errors, results.spdef); - ok &= SPEED.matches(stats.errors, results.speed); - env.update_stats(); - match_found = ok; - - if (!match_found){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - } - - env.log("Result Found!", COLOR_BLUE); - stats.matches++; - - env.update_stats(); - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Found a perfect match!" - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} +/* Stats Reset - Regi + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_StatsReset-Regi.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +StatsResetRegi_Descriptor::StatsResetRegi_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:StatsResetRegi", + STRING_POKEMON + " SwSh", "Stats Reset - Regi", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset-Regi.md", + "Repeatedly catch regi until you get the stats you want.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StatsResetRegi_Descriptor::Stats : public StatsTracker{ + Stats() + : pokemon_caught(m_stats["Pokemon caught"]) + , pokemon_fainted(m_stats["Pokemon fainted"]) + , own_fainted(m_stats["Own fainted"]) + , out_of_balls(m_stats["Out of balls"]) + , errors(m_stats["Errors"]) + , total_balls_thrown(m_stats["Total balls thrown"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back(Stat("Pokemon caught")); + m_display_order.emplace_back(Stat("Pokemon fainted")); + m_display_order.emplace_back(Stat("Own fainted")); + m_display_order.emplace_back(Stat("Out of balls")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Total balls thrown")); + m_display_order.emplace_back(Stat("Matches")); + } + + std::atomic& pokemon_caught; + std::atomic& pokemon_fainted; + std::atomic& own_fainted; + std::atomic& out_of_balls; + std::atomic& errors; + std::atomic& total_balls_thrown; + std::atomic& matches; +}; +std::unique_ptr StatsResetRegi_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +StatsResetRegi::StatsResetRegi() + : GO_HOME_WHEN_DONE(false) + , BALL_SELECT( + "Ball Select:", + LockMode::LOCK_WHILE_RUNNING, + "master-ball" + ) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , HP("HP:") + , ATTACK("Attack:", IvJudgeFilter::NoGood) + , DEFENSE("Defense:") + , SPATK("Sp. Atk:") + , SPDEF("Sp. Def:") + , SPEED("Speed:") + , NOTIFICATION_CATCH_SUCCESS("Catch Success", true, false, std::chrono::seconds(3600)) + , NOTIFICATION_CATCH_FAILED("Catch Failed", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_CATCH_SUCCESS, + &NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(BALL_SELECT); + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(HP); + PA_ADD_OPTION(ATTACK); + PA_ADD_OPTION(DEFENSE); + PA_ADD_OPTION(SPATK); + PA_ADD_OPTION(SPDEF); + PA_ADD_OPTION(SPEED); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void StatsResetRegi::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + StatsResetRegi_Descriptor::Stats& stats = env.current_stats(); + + bool match_found = false; + while (!match_found){ + + bool regi_caught = false; + while (!regi_caught){ + env.log("Talk to regi.", COLOR_PURPLE); + context.wait_for_all_requests(); + { + StandardBattleMenuWatcher fight_detector(false); + int result = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + pbf_press_button(context, BUTTON_A, 80ms, 1000ms); + } + }, + {{fight_detector}} + ); + if (result == 0){ + env.log("New fight detected, let's begin to throw balls.", COLOR_PURPLE); + pbf_mash_button(context, BUTTON_B, 1000ms); + } + } + + env.log("Catch regi.", COLOR_PURPLE); + CatchResults result = basic_catcher(env.console, context, LANGUAGE, BALL_SELECT.slug(), 999); + switch (result.result){ + case CatchResult::POKEMON_CAUGHT: + regi_caught = true; + stats.pokemon_caught++; + break; + case CatchResult::POKEMON_FAINTED: + stats.pokemon_fainted++; + break; + case CatchResult::OWN_FAINTED: + stats.own_fainted++; + break; + case CatchResult::OUT_OF_BALLS: + stats.out_of_balls++; + break; + case CatchResult::BALL_LIMIT_REACHED: + case CatchResult::CANNOT_THROW_BALL: + case CatchResult::TIMED_OUT: + stats.errors++; + break; + } + stats.total_balls_thrown += result.balls_used; + env.update_stats(); + + if (regi_caught){ + send_program_status_notification( + env, NOTIFICATION_CATCH_SUCCESS, + "Threw " + std::to_string(result.balls_used) + " ball(s) and caught it." + ); + }else{ + send_program_status_notification( + env, NOTIFICATION_CATCH_FAILED, + "Threw " + std::to_string(result.balls_used) + " ball(s) and did not catch it." + ); + } + + if (!regi_caught){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + } + + env.log("Check the stats.", COLOR_PURPLE); + for (int i = 0; i < 20; i++){ + pbf_press_button(context, BUTTON_B, 80ms, 1000ms); + } + pbf_press_button(context, BUTTON_X , 80ms, 2000ms); + pbf_press_dpad (context, DPAD_RIGHT, 80ms, 500ms); + pbf_press_button(context, BUTTON_A , 80ms, 2000ms); + pbf_press_button(context, BUTTON_R , 80ms, 3000ms); + pbf_press_dpad (context, DPAD_LEFT , 80ms, 1000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); + pbf_press_dpad (context, DPAD_UP , 80ms, 1000ms); + + context.wait_for_all_requests(); + IvJudgeReaderScope reader(env.console, LANGUAGE); + IvJudgeReader::Results results = reader.read(env.console, env.console.video().snapshot()); + bool ok = true; + ok &= HP.matches(stats.errors, results.hp); + ok &= ATTACK.matches(stats.errors, results.attack); + ok &= DEFENSE.matches(stats.errors, results.defense); + ok &= SPATK.matches(stats.errors, results.spatk); + ok &= SPDEF.matches(stats.errors, results.spdef); + ok &= SPEED.matches(stats.errors, results.speed); + env.update_stats(); + match_found = ok; + + if (!match_found){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + } + + env.log("Result Found!", COLOR_BLUE); + stats.matches++; + + env.update_stats(); + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Found a perfect match!" + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h index a62a688988..000b9fb576 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset-Regi.h @@ -1,62 +1,62 @@ -/* Stats Reset - Regi - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StatsResetRegi_H -#define PokemonAutomation_PokemonSwSh_StatsResetRegi_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "Pokemon/Options/Pokemon_IvJudgeOption.h" -#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class StatsResetRegi_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StatsResetRegi_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class StatsResetRegi : public SingleSwitchProgramInstance{ -public: - StatsResetRegi(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - PokemonBallSelectOption BALL_SELECT; - OCR::LanguageOCROption LANGUAGE; - IVJudgeFilterOption HP; - IVJudgeFilterOption ATTACK; - IVJudgeFilterOption DEFENSE; - IVJudgeFilterOption SPATK; - IVJudgeFilterOption SPDEF; - IVJudgeFilterOption SPEED; - - EventNotificationOption NOTIFICATION_CATCH_SUCCESS; - EventNotificationOption NOTIFICATION_CATCH_FAILED; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Stats Reset - Regi + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StatsResetRegi_H +#define PokemonAutomation_PokemonSwSh_StatsResetRegi_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "Pokemon/Options/Pokemon_IvJudgeOption.h" +#include "PokemonSwSh/Options/PokemonSwSh_BallSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class StatsResetRegi_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StatsResetRegi_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class StatsResetRegi : public SingleSwitchProgramInstance{ +public: + StatsResetRegi(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + PokemonBallSelectOption BALL_SELECT; + OCR::LanguageOCROption LANGUAGE; + IVJudgeFilterOption HP; + IVJudgeFilterOption ATTACK; + IVJudgeFilterOption DEFENSE; + IVJudgeFilterOption SPATK; + IVJudgeFilterOption SPDEF; + IVJudgeFilterOption SPEED; + + EventNotificationOption NOTIFICATION_CATCH_SUCCESS; + EventNotificationOption NOTIFICATION_CATCH_FAILED; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.cpp index 0f0ec8c2da..1af552f425 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.cpp @@ -1,194 +1,194 @@ -/* Stats Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh_StatsReset.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -StatsReset_Descriptor::StatsReset_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:StatsReset", - STRING_POKEMON + " SwSh", "Stats Reset", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset.md", - "Repeatedly receive gift " + STRING_POKEMON + " until you get the stats you want.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct StatsReset_Descriptor::Stats : public StatsTracker{ - Stats() - : attempts(m_stats["Attempts"]) - , errors(m_stats["Errors"]) - , matches(m_stats["Matches"]) - { - m_display_order.emplace_back(Stat("Attempts")); - m_display_order.emplace_back(Stat("Errors")); - m_display_order.emplace_back(Stat("Matches")); - } - - std::atomic& attempts; - std::atomic& errors; - std::atomic& matches; -}; -std::unique_ptr StatsReset_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -StatsReset::StatsReset() - : GO_HOME_WHEN_DONE(false) - , LANGUAGE( - "Game Language:", - IV_READER().languages(), - LockMode::LOCK_WHILE_RUNNING - ) - , POKEMON( - "Gift " + STRING_POKEMON + ":", - { - {GiftPokemon::TypeNull, "type-null", "Type: Null"}, - {GiftPokemon::Cosmog, "cosmog", "Cosmog"}, - {GiftPokemon::Poipole, "poipole", "Poipole"}, - }, - LockMode::LOCK_WHILE_RUNNING, - GiftPokemon::TypeNull - ) - , HP("HP:") - , ATTACK("Attack:", IvJudgeFilter::NoGood) - , DEFENSE("Defense:") - , SPATK("Sp. Atk:") - , SPDEF("Sp. Def:") - , SPEED("Speed:") - , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true, ImageAttachmentMode::JPG) - , NOTIFICATIONS({ - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(POKEMON); - PA_ADD_OPTION(HP); - PA_ADD_OPTION(ATTACK); - PA_ADD_OPTION(DEFENSE); - PA_ADD_OPTION(SPATK); - PA_ADD_OPTION(SPDEF); - PA_ADD_OPTION(SPEED); - - PA_ADD_OPTION(NOTIFICATIONS); -} - - - -void StatsReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - StatsReset_Descriptor::Stats& stats = env.current_stats(); - - VideoSnapshot screen; - while (true){ - env.update_stats(); - - context.wait_for_all_requests(); - { - BlackScreenOverWatcher detector; - int result = run_until( - env.console, context, - [this](ProControllerContext& context){ - if (POKEMON == GiftPokemon::TypeNull){ - pbf_mash_button(context, BUTTON_A, 10s); - }else{ - pbf_mash_button(context, BUTTON_A, 5s); - } - pbf_mash_button(context, BUTTON_B, 20s); - }, - {{detector}} - ); - if (result == 0){ - env.log(STRING_POKEMON + " receive menu detected.", COLOR_PURPLE); - }else{ - env.log(STRING_POKEMON + " receive menu timed out.", COLOR_RED); - } - } - stats.attempts++; - - pbf_mash_button(context, BUTTON_B, 1000ms); - - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - box_scroll(context, DPAD_RIGHT); - ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, 160ms); - ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, 160ms); - context.wait_for_all_requests(); - - { - IvJudgeReaderScope reader(env.console, LANGUAGE); - screen = env.console.video().snapshot(); - IvJudgeReader::Results results = reader.read(env.console, screen); - bool ok = true; - ok &= HP.matches(stats.errors, results.hp); - ok &= ATTACK.matches(stats.errors, results.attack); - ok &= DEFENSE.matches(stats.errors, results.defense); - ok &= SPATK.matches(stats.errors, results.spatk); - ok &= SPDEF.matches(stats.errors, results.spdef); - ok &= SPEED.matches(stats.errors, results.speed); - if (ok){ - break; - } - } - - // Add a little extra wait time since correctness matters here. - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - - stats.matches++; - env.update_stats(); - env.log("Result Found!", COLOR_BLUE); - - pbf_wait(context, 5000ms); - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); - - send_program_finished_notification( - env, NOTIFICATION_PROGRAM_FINISH, - "Found a match!", - screen, false - ); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} +/* Stats Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_IvJudgeReader.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh_StatsReset.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +StatsReset_Descriptor::StatsReset_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:StatsReset", + STRING_POKEMON + " SwSh", "Stats Reset", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/StatsReset.md", + "Repeatedly receive gift " + STRING_POKEMON + " until you get the stats you want.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct StatsReset_Descriptor::Stats : public StatsTracker{ + Stats() + : attempts(m_stats["Attempts"]) + , errors(m_stats["Errors"]) + , matches(m_stats["Matches"]) + { + m_display_order.emplace_back(Stat("Attempts")); + m_display_order.emplace_back(Stat("Errors")); + m_display_order.emplace_back(Stat("Matches")); + } + + std::atomic& attempts; + std::atomic& errors; + std::atomic& matches; +}; +std::unique_ptr StatsReset_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +StatsReset::StatsReset() + : GO_HOME_WHEN_DONE(false) + , LANGUAGE( + "Game Language:", + IV_READER().languages(), + LockMode::LOCK_WHILE_RUNNING + ) + , POKEMON( + "Gift " + STRING_POKEMON + ":", + { + {GiftPokemon::TypeNull, "type-null", "Type: Null"}, + {GiftPokemon::Cosmog, "cosmog", "Cosmog"}, + {GiftPokemon::Poipole, "poipole", "Poipole"}, + }, + LockMode::LOCK_WHILE_RUNNING, + GiftPokemon::TypeNull + ) + , HP("HP:") + , ATTACK("Attack:", IvJudgeFilter::NoGood) + , DEFENSE("Defense:") + , SPATK("Sp. Atk:") + , SPDEF("Sp. Def:") + , SPEED("Speed:") + , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true, ImageAttachmentMode::JPG) + , NOTIFICATIONS({ + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(POKEMON); + PA_ADD_OPTION(HP); + PA_ADD_OPTION(ATTACK); + PA_ADD_OPTION(DEFENSE); + PA_ADD_OPTION(SPATK); + PA_ADD_OPTION(SPDEF); + PA_ADD_OPTION(SPEED); + + PA_ADD_OPTION(NOTIFICATIONS); +} + + + +void StatsReset::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + StatsReset_Descriptor::Stats& stats = env.current_stats(); + + VideoSnapshot screen; + while (true){ + env.update_stats(); + + context.wait_for_all_requests(); + { + BlackScreenOverWatcher detector; + int result = run_until( + env.console, context, + [this](ProControllerContext& context){ + if (POKEMON == GiftPokemon::TypeNull){ + pbf_mash_button(context, BUTTON_A, 10s); + }else{ + pbf_mash_button(context, BUTTON_A, 5s); + } + pbf_mash_button(context, BUTTON_B, 20s); + }, + {{detector}} + ); + if (result == 0){ + env.log(STRING_POKEMON + " receive menu detected.", COLOR_PURPLE); + }else{ + env.log(STRING_POKEMON + " receive menu timed out.", COLOR_RED); + } + } + stats.attempts++; + + pbf_mash_button(context, BUTTON_B, 1000ms); + + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + box_scroll(context, DPAD_RIGHT); + ssf_press_button(context, BUTTON_A, GameSettings::instance().MENU_TO_POKEMON_DELAY0, 160ms); + ssf_press_button(context, BUTTON_R, GameSettings::instance().POKEMON_TO_BOX_DELAY0, 160ms); + context.wait_for_all_requests(); + + { + IvJudgeReaderScope reader(env.console, LANGUAGE); + screen = env.console.video().snapshot(); + IvJudgeReader::Results results = reader.read(env.console, screen); + bool ok = true; + ok &= HP.matches(stats.errors, results.hp); + ok &= ATTACK.matches(stats.errors, results.attack); + ok &= DEFENSE.matches(stats.errors, results.defense); + ok &= SPATK.matches(stats.errors, results.spatk); + ok &= SPDEF.matches(stats.errors, results.spdef); + ok &= SPEED.matches(stats.errors, results.speed); + if (ok){ + break; + } + } + + // Add a little extra wait time since correctness matters here. + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + + stats.matches++; + env.update_stats(); + env.log("Result Found!", COLOR_BLUE); + + pbf_wait(context, 5000ms); + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); + + send_program_finished_notification( + env, NOTIFICATION_PROGRAM_FINISH, + "Found a match!", + screen, false + ); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.h b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.h index 3482e56357..f9c7a04d3f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/NonShinyHunting/PokemonSwSh_StatsReset.h @@ -1,68 +1,68 @@ -/* Stats Reset - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StatsReset_H -#define PokemonAutomation_PokemonSwSh_StatsReset_H - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_IvJudgeOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class StatsReset_Descriptor : public SingleSwitchProgramDescriptor{ -public: - StatsReset_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class StatsReset : public SingleSwitchProgramInstance{ -public: - StatsReset(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - OCR::LanguageOCROption LANGUAGE; - - enum class GiftPokemon{ - TypeNull, - Cosmog, - Poipole, - }; - EnumDropdownOption POKEMON; - - IVJudgeFilterOption HP; - IVJudgeFilterOption ATTACK; - IVJudgeFilterOption DEFENSE; - IVJudgeFilterOption SPATK; - IVJudgeFilterOption SPDEF; - IVJudgeFilterOption SPEED; - - EventNotificationOption NOTIFICATION_PROGRAM_FINISH; - EventNotificationsOption NOTIFICATIONS; -}; - - -} -} -} -#endif +/* Stats Reset + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StatsReset_H +#define PokemonAutomation_PokemonSwSh_StatsReset_H + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_IvJudgeOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class StatsReset_Descriptor : public SingleSwitchProgramDescriptor{ +public: + StatsReset_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class StatsReset : public SingleSwitchProgramInstance{ +public: + StatsReset(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + OCR::LanguageOCROption LANGUAGE; + + enum class GiftPokemon{ + TypeNull, + Cosmog, + Poipole, + }; + EnumDropdownOption POKEMON; + + IVJudgeFilterOption HP; + IVJudgeFilterOption ATTACK; + IVJudgeFilterOption DEFENSE; + IVJudgeFilterOption SPATK; + IVJudgeFilterOption SPDEF; + IVJudgeFilterOption SPEED; + + EventNotificationOption NOTIFICATION_PROGRAM_FINISH; + EventNotificationsOption NOTIFICATIONS; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.cpp index 15a7a27fc8..9333b6e27c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.cpp @@ -1,97 +1,97 @@ -/* Overworld Movement - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh_OverworldMovement.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void move_in_circle_up(ProControllerContext& context, bool counter_clockwise){ -// cout << "up" << endl; - if (counter_clockwise){ - pbf_move_left_joystick(context, 255, 128, 16, 0); - pbf_move_left_joystick(context, 255, 0, 16, 0); - pbf_move_left_joystick(context, 128, 0, 16, 0); - pbf_move_left_joystick(context, 0, 0, 16, 0); - pbf_move_left_joystick(context, 0, 128, 16, 0); - pbf_move_left_joystick(context, 0, 255, 16, 0); - pbf_move_left_joystick(context, 128, 255, 16, 0); - pbf_move_left_joystick(context, 255, 255, 16, 0); - }else{ - pbf_move_left_joystick(context, 0, 128, 16, 0); - pbf_move_left_joystick(context, 0, 0, 16, 0); - pbf_move_left_joystick(context, 128, 0, 16, 0); - pbf_move_left_joystick(context, 255, 0, 16, 0); - pbf_move_left_joystick(context, 255, 128, 16, 0); - pbf_move_left_joystick(context, 255, 255, 16, 0); - pbf_move_left_joystick(context, 128, 255, 16, 0); - pbf_move_left_joystick(context, 0, 255, 16, 0); - } -} -void move_in_circle_down(ProControllerContext& context, bool counter_clockwise){ - if (counter_clockwise){ - pbf_move_left_joystick(context, 0, 128, 16, 0); - pbf_move_left_joystick(context, 0, 255, 16, 0); - pbf_move_left_joystick(context, 128, 255, 16, 0); - pbf_move_left_joystick(context, 255, 255, 16, 0); - pbf_move_left_joystick(context, 255, 128, 16, 0); - pbf_move_left_joystick(context, 255, 0, 24, 0); - pbf_move_left_joystick(context, 128, 0, 24, 0); - pbf_move_left_joystick(context, 0, 0, 24, 0); - }else{ - pbf_move_left_joystick(context, 255, 128, 16, 0); - pbf_move_left_joystick(context, 255, 255, 16, 0); - pbf_move_left_joystick(context, 128, 255, 16, 0); - pbf_move_left_joystick(context, 0, 255, 16, 0); - pbf_move_left_joystick(context, 0, 128, 16, 0); - pbf_move_left_joystick(context, 0, 0, 24, 0); - pbf_move_left_joystick(context, 128, 0, 24, 0); - pbf_move_left_joystick(context, 255, 0, 24, 0); - } -} -void circle_in_place(ProControllerContext& context, bool counter_clockwise){ - if (counter_clockwise){ - pbf_move_left_joystick(context, 0, 128, 64, 0); // Correct for bias. - pbf_move_left_joystick(context, 128, 255, 32, 0); - pbf_move_left_joystick(context, 255, 255, 32, 0); - pbf_move_left_joystick(context, 255, 128, 32, 0); - pbf_move_left_joystick(context, 255, 0, 32, 0); - pbf_move_left_joystick(context, 128, 0, 32, 0); - pbf_move_left_joystick(context, 0, 0, 32, 0); - pbf_move_left_joystick(context, 0, 128, 32, 0); - pbf_move_left_joystick(context, 0, 255, 32, 0); - pbf_move_left_joystick(context, 255, 128, 16, 0); // Correct for bias. - }else{ - pbf_move_left_joystick(context, 255, 128, 64, 0); // Correct for bias. - pbf_move_left_joystick(context, 128, 255, 32, 0); - pbf_move_left_joystick(context, 0, 255, 32, 0); - pbf_move_left_joystick(context, 0, 128, 32, 0); - pbf_move_left_joystick(context, 0, 0, 32, 0); - pbf_move_left_joystick(context, 128, 0, 32, 0); - pbf_move_left_joystick(context, 255, 0, 32, 0); - pbf_move_left_joystick(context, 255, 128, 32, 0); - pbf_move_left_joystick(context, 255, 255, 32, 0); - pbf_move_left_joystick(context, 0, 128, 16, 0); // Correct for bias. - } -} -void move_in_line(ProControllerContext& context, bool horizontal){ - if (horizontal){ - pbf_move_left_joystick(context, 0, 128, 128, 32); - pbf_move_left_joystick(context, 255, 128, 128, 32); - }else{ - pbf_move_left_joystick(context, 128, 255, 128, 32); - pbf_move_left_joystick(context, 128, 0, 128, 32); - } -} - - -} -} -} - +/* Overworld Movement + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh_OverworldMovement.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void move_in_circle_up(ProControllerContext& context, bool counter_clockwise){ +// cout << "up" << endl; + if (counter_clockwise){ + pbf_move_left_joystick(context, 255, 128, 16, 0); + pbf_move_left_joystick(context, 255, 0, 16, 0); + pbf_move_left_joystick(context, 128, 0, 16, 0); + pbf_move_left_joystick(context, 0, 0, 16, 0); + pbf_move_left_joystick(context, 0, 128, 16, 0); + pbf_move_left_joystick(context, 0, 255, 16, 0); + pbf_move_left_joystick(context, 128, 255, 16, 0); + pbf_move_left_joystick(context, 255, 255, 16, 0); + }else{ + pbf_move_left_joystick(context, 0, 128, 16, 0); + pbf_move_left_joystick(context, 0, 0, 16, 0); + pbf_move_left_joystick(context, 128, 0, 16, 0); + pbf_move_left_joystick(context, 255, 0, 16, 0); + pbf_move_left_joystick(context, 255, 128, 16, 0); + pbf_move_left_joystick(context, 255, 255, 16, 0); + pbf_move_left_joystick(context, 128, 255, 16, 0); + pbf_move_left_joystick(context, 0, 255, 16, 0); + } +} +void move_in_circle_down(ProControllerContext& context, bool counter_clockwise){ + if (counter_clockwise){ + pbf_move_left_joystick(context, 0, 128, 16, 0); + pbf_move_left_joystick(context, 0, 255, 16, 0); + pbf_move_left_joystick(context, 128, 255, 16, 0); + pbf_move_left_joystick(context, 255, 255, 16, 0); + pbf_move_left_joystick(context, 255, 128, 16, 0); + pbf_move_left_joystick(context, 255, 0, 24, 0); + pbf_move_left_joystick(context, 128, 0, 24, 0); + pbf_move_left_joystick(context, 0, 0, 24, 0); + }else{ + pbf_move_left_joystick(context, 255, 128, 16, 0); + pbf_move_left_joystick(context, 255, 255, 16, 0); + pbf_move_left_joystick(context, 128, 255, 16, 0); + pbf_move_left_joystick(context, 0, 255, 16, 0); + pbf_move_left_joystick(context, 0, 128, 16, 0); + pbf_move_left_joystick(context, 0, 0, 24, 0); + pbf_move_left_joystick(context, 128, 0, 24, 0); + pbf_move_left_joystick(context, 255, 0, 24, 0); + } +} +void circle_in_place(ProControllerContext& context, bool counter_clockwise){ + if (counter_clockwise){ + pbf_move_left_joystick(context, 0, 128, 64, 0); // Correct for bias. + pbf_move_left_joystick(context, 128, 255, 32, 0); + pbf_move_left_joystick(context, 255, 255, 32, 0); + pbf_move_left_joystick(context, 255, 128, 32, 0); + pbf_move_left_joystick(context, 255, 0, 32, 0); + pbf_move_left_joystick(context, 128, 0, 32, 0); + pbf_move_left_joystick(context, 0, 0, 32, 0); + pbf_move_left_joystick(context, 0, 128, 32, 0); + pbf_move_left_joystick(context, 0, 255, 32, 0); + pbf_move_left_joystick(context, 255, 128, 16, 0); // Correct for bias. + }else{ + pbf_move_left_joystick(context, 255, 128, 64, 0); // Correct for bias. + pbf_move_left_joystick(context, 128, 255, 32, 0); + pbf_move_left_joystick(context, 0, 255, 32, 0); + pbf_move_left_joystick(context, 0, 128, 32, 0); + pbf_move_left_joystick(context, 0, 0, 32, 0); + pbf_move_left_joystick(context, 128, 0, 32, 0); + pbf_move_left_joystick(context, 255, 0, 32, 0); + pbf_move_left_joystick(context, 255, 128, 32, 0); + pbf_move_left_joystick(context, 255, 255, 32, 0); + pbf_move_left_joystick(context, 0, 128, 16, 0); // Correct for bias. + } +} +void move_in_line(ProControllerContext& context, bool horizontal){ + if (horizontal){ + pbf_move_left_joystick(context, 0, 128, 128, 32); + pbf_move_left_joystick(context, 255, 128, 128, 32); + }else{ + pbf_move_left_joystick(context, 128, 255, 128, 32); + pbf_move_left_joystick(context, 128, 0, 128, 32); + } +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.h b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.h index 42d8af7794..e6953723ae 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldMovement.h @@ -1,25 +1,25 @@ -/* Overworld Movement - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_OverworldMovement_H -#define PokemonAutomation_PokemonSwSh_OverworldMovement_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void move_in_circle_up(ProControllerContext& context, bool counter_clockwise); -void move_in_circle_down(ProControllerContext& context, bool counter_clockwise); -void circle_in_place(ProControllerContext& context, bool counter_clockwise); -void move_in_line(ProControllerContext& context, bool horizontal); - -} -} -} -#endif +/* Overworld Movement + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_OverworldMovement_H +#define PokemonAutomation_PokemonSwSh_OverworldMovement_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void move_in_circle_up(ProControllerContext& context, bool counter_clockwise); +void move_in_circle_down(ProControllerContext& context, bool counter_clockwise); +void circle_in_place(ProControllerContext& context, bool counter_clockwise); +void move_in_line(ProControllerContext& context, bool horizontal); + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.cpp index d5009736ea..c93e4aad42 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.cpp @@ -1,300 +1,300 @@ -/* Overworld Mark Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoOverlay.h" -#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h" -#include "PokemonSwSh_OverworldTargetTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const std::vector MARK_PRIORITY_STRINGS{ - "Exclamation Marks Only (Ignore Question Marks)", - "Prioritize Exclamation Marks", - "No Preference", - "Prioritize Question Marks", - "Question Marks Only (Ignore Exclamation Marks)", -}; - - - -const double OverworldTargetTracker::OVERWORLD_CENTER_X = 0.50; -const double OverworldTargetTracker::OVERWORLD_CENTER_Y = 0.70; - - -OverworldTargetTracker::OverworldTargetTracker( - Logger& logger, VideoOverlay& overlay, - std::chrono::milliseconds window, - double mark_offset, - MarkPriority mark_priority, - double max_alpha -) - : VisualInferenceCallback("OverworldTargetTracker") - , m_logger(logger) - , m_overlay(overlay) - , m_window(window) - , m_mark_offset(mark_offset) - , m_mark_priority(mark_priority) - , m_max_alpha(max_alpha) - , m_search_area(0.0, 0.2, 1.0, 0.8) - , m_stop_on_target(false) -{ - m_best_target.first = -1; -} -void OverworldTargetTracker::make_overlays(VideoOverlaySet& items) const{ - items.add(COLOR_RED, m_search_area); -} - -void OverworldTargetTracker::set_stop_on_target(bool stop){ - m_stop_on_target.store(stop, std::memory_order_release); -} -void OverworldTargetTracker::clear_detections(){ - WriteSpinLock lg(m_lock, "OverworldTargetTracker::clear_detections()"); - m_best_target.first = -1; - m_detection_boxes.clear(); - m_exclamations.clear(); - m_questions.clear(); -} -bool OverworldTargetTracker::has_good_target(){ -// m_logger.log("has_good_target()"); - ReadSpinLock lg(m_lock, "OverworldTargetTracker::has_good_target()"); - if (m_best_target.first < 0){ -// m_logger.log("has_good_target(): < 0"); - return false; - } -// m_logger.log("has_good_target(): " + std::to_string(m_best_target.first)); - return m_best_target.first <= m_max_alpha; -} -std::pair OverworldTargetTracker::best_target() const{ - ReadSpinLock lg(m_lock, "OverworldTargetTracker::best_target()"); - return m_best_target; -} - - -void OverworldTargetTracker::populate_targets( - std::multimap& scored_targets, - const std::vector& targets -){ -#if 0 - cout << "Targets:" << endl; - for (const auto& item : targets){ - cout << " " << item.box.x << " - " << item.box.x + item.box.width - << " x " << item.box.y << " - " << item.box.y + item.box.height << endl; - } -#endif - -// cout << "Candidates:" << endl; - for (size_t c = 0; c < targets.size(); c++){ - double overlap = 0; - const ImageFloatBox& box0 = targets[c].box; - for (size_t i = 0; i < targets.size(); i++){ - const ImageFloatBox& box1 = targets[i].box; - double min_x = std::max(box0.x, box1.x); - double max_x = std::min(box0.x + box0.width, box1.x + box1.width); - if (min_x >= max_x){ - continue; - } - double min_y = std::max(box0.y, box1.y); - double max_y = std::min(box0.y + box0.height, box1.y + box1.height); - if (min_y >= max_y){ - continue; - } - overlap += (max_x - min_x) * (max_y - min_y); - } - double score = targets[c].trajectory.distance_in_ticks / overlap; - scored_targets.emplace(score, targets[c]); -// cout << " " << score << " = " -// << (int)targets[c].trajectory.joystick_x << ", " -// << (int)targets[c].trajectory.joystick_y << endl; - } -} - -void OverworldTargetTracker::populate_targets( - std::multimap& scored_targets, - const std::deque& marks, - OverworldMark mark -){ - std::vector targets; - for (const Mark& item : marks){ - const ImageFloatBox& box = item.box; - double delta_x = box.x + box.width / 2 - OVERWORLD_CENTER_X; - double delta_y = box.y + box.height * (1.0 + m_mark_offset) - OVERWORLD_CENTER_Y; - Trajectory trajectory = get_trajectory_float(delta_x, delta_y); - targets.emplace_back(OverworldTarget{mark, box, trajectory, delta_x, delta_y}); - } - populate_targets(scored_targets, targets); -} - -bool OverworldTargetTracker::save_target(std::multimap::iterator target){ -#if 1 - m_logger.log( - std::string("Best Target: ") + - (target->second.mark == OverworldMark::EXCLAMATION_MARK ? "Exclamation" : "Question") + - " at [" + - tostr_default(target->second.delta_x) + " , " + - tostr_default(-target->second.delta_y) + "], alpha = " + - tostr_default(target->first), - COLOR_ORANGE - ); -#endif -// WriteSpinLock lg(m_lock, "OverworldTargetTracker::save_target()"); - m_best_target = *target; - return target->first <= m_max_alpha && m_stop_on_target.load(std::memory_order_acquire); -// return target->first <= m_max_alpha; -} - -bool OverworldTargetTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ - ImageViewRGB32 image = extract_box_reference(frame, m_search_area); - - std::vector exclamation_marks = find_exclamation_marks(image); - std::vector question_marks = find_question_marks(image); -// question_marks.clear(); - - WriteSpinLock lg(m_lock, "OverworldTargetTracker::on_frame()"); - - // Clear out old detections. - auto oldest = timestamp - m_window; - while (!m_exclamations.empty() && m_exclamations[0].timestamp < oldest){ - m_exclamations.pop_front(); - } - while (!m_questions.empty() && m_questions[0].timestamp < oldest){ - m_questions.pop_front(); - } - - - m_detection_boxes.clear(); - for (const ImagePixelBox& mark : exclamation_marks){ - ImageFloatBox box = translate_to_parent(frame, m_search_area, mark); -// box.x -= box.width * 1.5; -// box.width *= 4; -// box.height *= 1.5; - m_exclamations.emplace_back(Mark{timestamp, box}); - m_detection_boxes.emplace_back(m_overlay, box, COLOR_MAGENTA); -// cout << "asdf = " << exclamations.size() << endl; - } - for (const ImagePixelBox& mark : question_marks){ - ImageFloatBox box = translate_to_parent(frame, m_search_area, mark); - box.x -= box.width * 0.5; - box.width *= 2; - box.height *= 1.5; - m_questions.emplace_back(Mark{timestamp, box}); - m_detection_boxes.emplace_back(m_overlay, box, COLOR_BLUE); -// cout << "qwer = " << questions.size() << endl; - } - - - // Build targets. - - switch (m_mark_priority){ - case MarkPriority::EXCLAMATION_ONLY:{ - std::multimap targets; - populate_targets(targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); - if (!targets.empty()){ - return save_target(targets.begin()); - } - break; - } - case MarkPriority::PRIORITIZE_EXCLAMATION:{ - std::multimap exclamation_targets; - std::multimap question_targets; - populate_targets(exclamation_targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); - populate_targets(question_targets, m_questions, OverworldMark::QUESTION_MARK); - - auto target0 = exclamation_targets.begin(); - auto target1 = question_targets.begin(); - - // See if we have any good target. - if (!exclamation_targets.empty()){ -// cout << "Exclamation = " << target0->first << endl; - } - if (!question_targets.empty()){ -// cout << "Question = " << target1->first << endl; - } - if (!exclamation_targets.empty() && target0->first <= m_max_alpha){ -// cout << "Pick Exclamation" << endl; - return save_target(target0); - } - if (!question_targets.empty() && target1->first <= m_max_alpha){ -// cout << "Pick Question" << endl; - return save_target(target1); - } - - // No good targets. Pick the next best one for logging purposes. - std::multimap targets; - if (!exclamation_targets.empty()){ - targets.emplace(target0->first, target0->second); - } - if (!question_targets.empty()){ - targets.emplace(target1->first, target1->second); - } - if (!targets.empty()){ - return save_target(targets.begin()); - } - break; - } - case MarkPriority::NO_PREFERENCE:{ - std::multimap targets; - populate_targets(targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); - populate_targets(targets, m_questions, OverworldMark::QUESTION_MARK); - if (!targets.empty()){ - return save_target(targets.begin()); - } - break; - } - case MarkPriority::PRIORITIZE_QUESTION:{ - std::multimap exclamation_targets; - std::multimap question_targets; - populate_targets(exclamation_targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); - populate_targets(question_targets, m_questions, OverworldMark::QUESTION_MARK); - - auto target0 = exclamation_targets.begin(); - auto target1 = question_targets.begin(); - - // See if we have any good target. - if (!question_targets.empty() && target1->first <= m_max_alpha){ - return save_target(target1); - } - if (!exclamation_targets.empty() && target0->first <= m_max_alpha){ - return save_target(target0); - } - - // No good targets. Pick the next best one for logging purposes. - std::multimap targets; - if (!question_targets.empty()){ - targets.emplace(target1->first, target1->second); - } - if (!exclamation_targets.empty()){ - targets.emplace(target0->first, target0->second); - } - if (!targets.empty()){ - return save_target(targets.begin()); - } - break; - } - case MarkPriority::QUESTION_ONLY:{ - std::multimap targets; - populate_targets(targets, m_questions, OverworldMark::QUESTION_MARK); - if (!targets.empty()){ - return save_target(targets.begin()); - } - break; - } - } - - m_best_target.first = -1; - return false; -} - - - -} -} -} - +/* Overworld Mark Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoOverlay.h" +#include "PokemonSwSh/Inference/PokemonSwSh_MarkFinder.h" +#include "PokemonSwSh_OverworldTargetTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const std::vector MARK_PRIORITY_STRINGS{ + "Exclamation Marks Only (Ignore Question Marks)", + "Prioritize Exclamation Marks", + "No Preference", + "Prioritize Question Marks", + "Question Marks Only (Ignore Exclamation Marks)", +}; + + + +const double OverworldTargetTracker::OVERWORLD_CENTER_X = 0.50; +const double OverworldTargetTracker::OVERWORLD_CENTER_Y = 0.70; + + +OverworldTargetTracker::OverworldTargetTracker( + Logger& logger, VideoOverlay& overlay, + std::chrono::milliseconds window, + double mark_offset, + MarkPriority mark_priority, + double max_alpha +) + : VisualInferenceCallback("OverworldTargetTracker") + , m_logger(logger) + , m_overlay(overlay) + , m_window(window) + , m_mark_offset(mark_offset) + , m_mark_priority(mark_priority) + , m_max_alpha(max_alpha) + , m_search_area(0.0, 0.2, 1.0, 0.8) + , m_stop_on_target(false) +{ + m_best_target.first = -1; +} +void OverworldTargetTracker::make_overlays(VideoOverlaySet& items) const{ + items.add(COLOR_RED, m_search_area); +} + +void OverworldTargetTracker::set_stop_on_target(bool stop){ + m_stop_on_target.store(stop, std::memory_order_release); +} +void OverworldTargetTracker::clear_detections(){ + WriteSpinLock lg(m_lock, "OverworldTargetTracker::clear_detections()"); + m_best_target.first = -1; + m_detection_boxes.clear(); + m_exclamations.clear(); + m_questions.clear(); +} +bool OverworldTargetTracker::has_good_target(){ +// m_logger.log("has_good_target()"); + ReadSpinLock lg(m_lock, "OverworldTargetTracker::has_good_target()"); + if (m_best_target.first < 0){ +// m_logger.log("has_good_target(): < 0"); + return false; + } +// m_logger.log("has_good_target(): " + std::to_string(m_best_target.first)); + return m_best_target.first <= m_max_alpha; +} +std::pair OverworldTargetTracker::best_target() const{ + ReadSpinLock lg(m_lock, "OverworldTargetTracker::best_target()"); + return m_best_target; +} + + +void OverworldTargetTracker::populate_targets( + std::multimap& scored_targets, + const std::vector& targets +){ +#if 0 + cout << "Targets:" << endl; + for (const auto& item : targets){ + cout << " " << item.box.x << " - " << item.box.x + item.box.width + << " x " << item.box.y << " - " << item.box.y + item.box.height << endl; + } +#endif + +// cout << "Candidates:" << endl; + for (size_t c = 0; c < targets.size(); c++){ + double overlap = 0; + const ImageFloatBox& box0 = targets[c].box; + for (size_t i = 0; i < targets.size(); i++){ + const ImageFloatBox& box1 = targets[i].box; + double min_x = std::max(box0.x, box1.x); + double max_x = std::min(box0.x + box0.width, box1.x + box1.width); + if (min_x >= max_x){ + continue; + } + double min_y = std::max(box0.y, box1.y); + double max_y = std::min(box0.y + box0.height, box1.y + box1.height); + if (min_y >= max_y){ + continue; + } + overlap += (max_x - min_x) * (max_y - min_y); + } + double score = targets[c].trajectory.distance_in_ticks / overlap; + scored_targets.emplace(score, targets[c]); +// cout << " " << score << " = " +// << (int)targets[c].trajectory.joystick_x << ", " +// << (int)targets[c].trajectory.joystick_y << endl; + } +} + +void OverworldTargetTracker::populate_targets( + std::multimap& scored_targets, + const std::deque& marks, + OverworldMark mark +){ + std::vector targets; + for (const Mark& item : marks){ + const ImageFloatBox& box = item.box; + double delta_x = box.x + box.width / 2 - OVERWORLD_CENTER_X; + double delta_y = box.y + box.height * (1.0 + m_mark_offset) - OVERWORLD_CENTER_Y; + Trajectory trajectory = get_trajectory_float(delta_x, delta_y); + targets.emplace_back(OverworldTarget{mark, box, trajectory, delta_x, delta_y}); + } + populate_targets(scored_targets, targets); +} + +bool OverworldTargetTracker::save_target(std::multimap::iterator target){ +#if 1 + m_logger.log( + std::string("Best Target: ") + + (target->second.mark == OverworldMark::EXCLAMATION_MARK ? "Exclamation" : "Question") + + " at [" + + tostr_default(target->second.delta_x) + " , " + + tostr_default(-target->second.delta_y) + "], alpha = " + + tostr_default(target->first), + COLOR_ORANGE + ); +#endif +// WriteSpinLock lg(m_lock, "OverworldTargetTracker::save_target()"); + m_best_target = *target; + return target->first <= m_max_alpha && m_stop_on_target.load(std::memory_order_acquire); +// return target->first <= m_max_alpha; +} + +bool OverworldTargetTracker::process_frame(const ImageViewRGB32& frame, WallClock timestamp){ + ImageViewRGB32 image = extract_box_reference(frame, m_search_area); + + std::vector exclamation_marks = find_exclamation_marks(image); + std::vector question_marks = find_question_marks(image); +// question_marks.clear(); + + WriteSpinLock lg(m_lock, "OverworldTargetTracker::on_frame()"); + + // Clear out old detections. + auto oldest = timestamp - m_window; + while (!m_exclamations.empty() && m_exclamations[0].timestamp < oldest){ + m_exclamations.pop_front(); + } + while (!m_questions.empty() && m_questions[0].timestamp < oldest){ + m_questions.pop_front(); + } + + + m_detection_boxes.clear(); + for (const ImagePixelBox& mark : exclamation_marks){ + ImageFloatBox box = translate_to_parent(frame, m_search_area, mark); +// box.x -= box.width * 1.5; +// box.width *= 4; +// box.height *= 1.5; + m_exclamations.emplace_back(Mark{timestamp, box}); + m_detection_boxes.emplace_back(m_overlay, box, COLOR_MAGENTA); +// cout << "asdf = " << exclamations.size() << endl; + } + for (const ImagePixelBox& mark : question_marks){ + ImageFloatBox box = translate_to_parent(frame, m_search_area, mark); + box.x -= box.width * 0.5; + box.width *= 2; + box.height *= 1.5; + m_questions.emplace_back(Mark{timestamp, box}); + m_detection_boxes.emplace_back(m_overlay, box, COLOR_BLUE); +// cout << "qwer = " << questions.size() << endl; + } + + + // Build targets. + + switch (m_mark_priority){ + case MarkPriority::EXCLAMATION_ONLY:{ + std::multimap targets; + populate_targets(targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); + if (!targets.empty()){ + return save_target(targets.begin()); + } + break; + } + case MarkPriority::PRIORITIZE_EXCLAMATION:{ + std::multimap exclamation_targets; + std::multimap question_targets; + populate_targets(exclamation_targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); + populate_targets(question_targets, m_questions, OverworldMark::QUESTION_MARK); + + auto target0 = exclamation_targets.begin(); + auto target1 = question_targets.begin(); + + // See if we have any good target. + if (!exclamation_targets.empty()){ +// cout << "Exclamation = " << target0->first << endl; + } + if (!question_targets.empty()){ +// cout << "Question = " << target1->first << endl; + } + if (!exclamation_targets.empty() && target0->first <= m_max_alpha){ +// cout << "Pick Exclamation" << endl; + return save_target(target0); + } + if (!question_targets.empty() && target1->first <= m_max_alpha){ +// cout << "Pick Question" << endl; + return save_target(target1); + } + + // No good targets. Pick the next best one for logging purposes. + std::multimap targets; + if (!exclamation_targets.empty()){ + targets.emplace(target0->first, target0->second); + } + if (!question_targets.empty()){ + targets.emplace(target1->first, target1->second); + } + if (!targets.empty()){ + return save_target(targets.begin()); + } + break; + } + case MarkPriority::NO_PREFERENCE:{ + std::multimap targets; + populate_targets(targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); + populate_targets(targets, m_questions, OverworldMark::QUESTION_MARK); + if (!targets.empty()){ + return save_target(targets.begin()); + } + break; + } + case MarkPriority::PRIORITIZE_QUESTION:{ + std::multimap exclamation_targets; + std::multimap question_targets; + populate_targets(exclamation_targets, m_exclamations, OverworldMark::EXCLAMATION_MARK); + populate_targets(question_targets, m_questions, OverworldMark::QUESTION_MARK); + + auto target0 = exclamation_targets.begin(); + auto target1 = question_targets.begin(); + + // See if we have any good target. + if (!question_targets.empty() && target1->first <= m_max_alpha){ + return save_target(target1); + } + if (!exclamation_targets.empty() && target0->first <= m_max_alpha){ + return save_target(target0); + } + + // No good targets. Pick the next best one for logging purposes. + std::multimap targets; + if (!question_targets.empty()){ + targets.emplace(target1->first, target1->second); + } + if (!exclamation_targets.empty()){ + targets.emplace(target0->first, target0->second); + } + if (!targets.empty()){ + return save_target(targets.begin()); + } + break; + } + case MarkPriority::QUESTION_ONLY:{ + std::multimap targets; + populate_targets(targets, m_questions, OverworldMark::QUESTION_MARK); + if (!targets.empty()){ + return save_target(targets.begin()); + } + break; + } + } + + m_best_target.first = -1; + return false; +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.h b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.h index 6b969b15dc..55563133e9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTargetTracker.h @@ -1,124 +1,124 @@ -/* Overworld Target Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_OverworldTargetTracker_H -#define PokemonAutomation_PokemonSwSh_OverworldTargetTracker_H - -#include -#include -#include -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Concurrency/SpinLock.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" -#include "PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -enum class OverworldMark{ - EXCLAMATION_MARK, - QUESTION_MARK, -}; - -enum class MarkPriority{ - EXCLAMATION_ONLY, - PRIORITIZE_EXCLAMATION, - NO_PREFERENCE, - PRIORITIZE_QUESTION, - QUESTION_ONLY, -}; -extern const std::vector MARK_PRIORITY_STRINGS; - -struct OverworldTarget{ - OverworldMark mark; - ImageFloatBox box; - Trajectory trajectory; - double delta_x; - double delta_y; -}; - - -class OverworldTargetTracker : public VisualInferenceCallback{ -public: - static const double OVERWORLD_CENTER_X; - static const double OVERWORLD_CENTER_Y; - -public: - OverworldTargetTracker( - Logger& logger, VideoOverlay& overlay, - std::chrono::milliseconds window, - double mark_offset, - MarkPriority mark_priority, - double max_alpha - ); - - // If set to true, this inference object will not return true on - // "on_frame()" callbacks. - void set_stop_on_target(bool stop); - - void clear_detections(); - - bool has_good_target(); - - // Get the best target as of right now. - // The return value is only valid if the first element is non-negative. - std::pair best_target() const; - - virtual void make_overlays(VideoOverlaySet& items) const override; - virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; - - -private: - struct Mark{ - WallClock timestamp; - ImageFloatBox box; - }; - - static void populate_targets( - std::multimap& scored_targets, - const std::vector& targets - ); - void populate_targets( - std::multimap& scored_targets, - const std::deque& marks, - OverworldMark mark - ); - - bool save_target(std::multimap::iterator target); - - -private: - Logger& m_logger; - VideoOverlay& m_overlay; - std::chrono::milliseconds m_window; - double m_mark_offset; - MarkPriority m_mark_priority; - double m_max_alpha; - - ImageFloatBox m_search_area; - std::deque m_detection_boxes; - - // Sliding window of detections. - std::deque m_exclamations; - std::deque m_questions; - - std::atomic m_stop_on_target; - mutable SpinLock m_lock; - std::pair m_best_target; -}; - - - - - -} -} -} -#endif +/* Overworld Target Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_OverworldTargetTracker_H +#define PokemonAutomation_PokemonSwSh_OverworldTargetTracker_H + +#include +#include +#include +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Concurrency/SpinLock.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/InferenceCallbacks/VisualInferenceCallback.h" +#include "PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +enum class OverworldMark{ + EXCLAMATION_MARK, + QUESTION_MARK, +}; + +enum class MarkPriority{ + EXCLAMATION_ONLY, + PRIORITIZE_EXCLAMATION, + NO_PREFERENCE, + PRIORITIZE_QUESTION, + QUESTION_ONLY, +}; +extern const std::vector MARK_PRIORITY_STRINGS; + +struct OverworldTarget{ + OverworldMark mark; + ImageFloatBox box; + Trajectory trajectory; + double delta_x; + double delta_y; +}; + + +class OverworldTargetTracker : public VisualInferenceCallback{ +public: + static const double OVERWORLD_CENTER_X; + static const double OVERWORLD_CENTER_Y; + +public: + OverworldTargetTracker( + Logger& logger, VideoOverlay& overlay, + std::chrono::milliseconds window, + double mark_offset, + MarkPriority mark_priority, + double max_alpha + ); + + // If set to true, this inference object will not return true on + // "on_frame()" callbacks. + void set_stop_on_target(bool stop); + + void clear_detections(); + + bool has_good_target(); + + // Get the best target as of right now. + // The return value is only valid if the first element is non-negative. + std::pair best_target() const; + + virtual void make_overlays(VideoOverlaySet& items) const override; + virtual bool process_frame(const ImageViewRGB32& frame, WallClock timestamp) override final; + + +private: + struct Mark{ + WallClock timestamp; + ImageFloatBox box; + }; + + static void populate_targets( + std::multimap& scored_targets, + const std::vector& targets + ); + void populate_targets( + std::multimap& scored_targets, + const std::deque& marks, + OverworldMark mark + ); + + bool save_target(std::multimap::iterator target); + + +private: + Logger& m_logger; + VideoOverlay& m_overlay; + std::chrono::milliseconds m_window; + double m_mark_offset; + MarkPriority m_mark_priority; + double m_max_alpha; + + ImageFloatBox m_search_area; + std::deque m_detection_boxes; + + // Sliding window of detections. + std::deque m_exclamations; + std::deque m_questions; + + std::atomic m_stop_on_target; + mutable SpinLock m_lock; + std::pair m_best_target; +}; + + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.cpp index 0bcf0f508c..4eec9c417a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.cpp @@ -1,98 +1,98 @@ -/* Overworld Trajectory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "PokemonSwSh_OverworldTrajectory.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -const Trajectory TRAJECTORY_TABLE[8][6] = { - {{400,128, 0},{420,160, 0},{420,190, 0},{480,208, 0},{480,208, 0},{480,208, 0},}, - {{210,128, 0},{220,164, 0},{250,200, 0},{280,208, 0},{300,209, 0},{320,209, 0},}, - {{120,128, 0},{120,192, 0},{140,209, 0},{180,224, 0},{220,224, 0},{260,232, 0},}, - {{ 60,128, 0},{ 65,224, 0},{ 95,255, 32},{125,255, 48},{160,255, 48},{200,255, 48},}, - {{ 0,128,128},{ 40,255,110},{ 70,255,105},{100,255,100},{130,255, 95},{160,255, 90},}, - {{ 35,128,255},{ 45,255,255},{ 70,255,170},{ 90,255,160},{115,255,140},{140,255,128},}, - {{ 55,128,255},{ 60,192,255},{ 75,255,255},{ 90,255,192},{110,255,176},{135,255,144},}, - {{ 75,128,255},{ 80,160,255},{ 85,216,255},{ 95,255,224},{115,255,192},{130,255,176},}, -}; -Trajectory get_trajectory_int(int delta_x, int delta_y){ - delta_x = std::max(delta_x, -5); - delta_x = std::min(delta_x, +5); - delta_y = std::max(delta_y, -4); - delta_y = std::min(delta_y, +3); - - if (delta_x < 0){ - Trajectory entry = get_trajectory_int(-delta_x, delta_y); - entry.joystick_x = (uint8_t)(256 - entry.joystick_x); - return entry; - } - - return TRAJECTORY_TABLE[delta_y + 4][delta_x]; -} -Trajectory get_trajectory_float(double delta_x, double delta_y){ - delta_x *= 10; - delta_y *= 10; - - int int_x = (int)std::floor(delta_x); - int int_y = (int)std::floor(delta_y); - - double frac_x = delta_x - int_x; - double frac_y = delta_y - int_y; - - Trajectory corner11 = get_trajectory_int(int_x, int_y); - Trajectory corner01 = get_trajectory_int(int_x + 1, int_y); - Trajectory corner10 = get_trajectory_int(int_x, int_y + 1); - Trajectory corner00 = get_trajectory_int(int_x + 1, int_y + 1); - - double top_x = corner11.joystick_x * (1.0 - frac_x) + corner01.joystick_x * frac_x; - double bot_x = corner10.joystick_x * (1.0 - frac_x) + corner00.joystick_x * frac_x; - double x = top_x * (1.0 - frac_y) + bot_x * frac_y; -// cout << "top_x = " << top_x << endl; -// cout << "bot_x = " << bot_x << endl; -// cout << "x = " << x << endl; - - double top_y = corner11.joystick_y * (1.0 - frac_y) + corner10.joystick_y * frac_y; - double bot_y = corner01.joystick_y * (1.0 - frac_y) + corner00.joystick_y * frac_y; - double y = top_y * (1.0 - frac_x) + bot_y * frac_x; - - double top_d = corner11.distance_in_ticks * (1.0 - frac_x) + corner01.distance_in_ticks * frac_x; - double bot_d = corner10.distance_in_ticks * (1.0 - frac_x) + corner00.distance_in_ticks * frac_x; - double d = top_d * (1.0 - frac_y) + bot_d * frac_y; - - x -= 128; - y -= 128; - double scale = std::max(std::abs(x), std::abs(y)); - if (scale == 0){ - x = 128; - y = 128; - }else{ - scale = 128 / scale; - x *= scale; - y *= scale; - } - x += 128; - y += 128; - - d = std::max(d, 0.0); - d = std::min(d, 65535.); - x = std::max(x, 0.0); - y = std::max(y, 0.0); - x = std::min(x, 255.); - y = std::min(y, 255.); - - return Trajectory{(uint16_t)d, (uint8_t)x, (uint8_t)y}; -} - - -} -} -} +/* Overworld Trajectory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "PokemonSwSh_OverworldTrajectory.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +const Trajectory TRAJECTORY_TABLE[8][6] = { + {{400,128, 0},{420,160, 0},{420,190, 0},{480,208, 0},{480,208, 0},{480,208, 0},}, + {{210,128, 0},{220,164, 0},{250,200, 0},{280,208, 0},{300,209, 0},{320,209, 0},}, + {{120,128, 0},{120,192, 0},{140,209, 0},{180,224, 0},{220,224, 0},{260,232, 0},}, + {{ 60,128, 0},{ 65,224, 0},{ 95,255, 32},{125,255, 48},{160,255, 48},{200,255, 48},}, + {{ 0,128,128},{ 40,255,110},{ 70,255,105},{100,255,100},{130,255, 95},{160,255, 90},}, + {{ 35,128,255},{ 45,255,255},{ 70,255,170},{ 90,255,160},{115,255,140},{140,255,128},}, + {{ 55,128,255},{ 60,192,255},{ 75,255,255},{ 90,255,192},{110,255,176},{135,255,144},}, + {{ 75,128,255},{ 80,160,255},{ 85,216,255},{ 95,255,224},{115,255,192},{130,255,176},}, +}; +Trajectory get_trajectory_int(int delta_x, int delta_y){ + delta_x = std::max(delta_x, -5); + delta_x = std::min(delta_x, +5); + delta_y = std::max(delta_y, -4); + delta_y = std::min(delta_y, +3); + + if (delta_x < 0){ + Trajectory entry = get_trajectory_int(-delta_x, delta_y); + entry.joystick_x = (uint8_t)(256 - entry.joystick_x); + return entry; + } + + return TRAJECTORY_TABLE[delta_y + 4][delta_x]; +} +Trajectory get_trajectory_float(double delta_x, double delta_y){ + delta_x *= 10; + delta_y *= 10; + + int int_x = (int)std::floor(delta_x); + int int_y = (int)std::floor(delta_y); + + double frac_x = delta_x - int_x; + double frac_y = delta_y - int_y; + + Trajectory corner11 = get_trajectory_int(int_x, int_y); + Trajectory corner01 = get_trajectory_int(int_x + 1, int_y); + Trajectory corner10 = get_trajectory_int(int_x, int_y + 1); + Trajectory corner00 = get_trajectory_int(int_x + 1, int_y + 1); + + double top_x = corner11.joystick_x * (1.0 - frac_x) + corner01.joystick_x * frac_x; + double bot_x = corner10.joystick_x * (1.0 - frac_x) + corner00.joystick_x * frac_x; + double x = top_x * (1.0 - frac_y) + bot_x * frac_y; +// cout << "top_x = " << top_x << endl; +// cout << "bot_x = " << bot_x << endl; +// cout << "x = " << x << endl; + + double top_y = corner11.joystick_y * (1.0 - frac_y) + corner10.joystick_y * frac_y; + double bot_y = corner01.joystick_y * (1.0 - frac_y) + corner00.joystick_y * frac_y; + double y = top_y * (1.0 - frac_x) + bot_y * frac_x; + + double top_d = corner11.distance_in_ticks * (1.0 - frac_x) + corner01.distance_in_ticks * frac_x; + double bot_d = corner10.distance_in_ticks * (1.0 - frac_x) + corner00.distance_in_ticks * frac_x; + double d = top_d * (1.0 - frac_y) + bot_d * frac_y; + + x -= 128; + y -= 128; + double scale = std::max(std::abs(x), std::abs(y)); + if (scale == 0){ + x = 128; + y = 128; + }else{ + scale = 128 / scale; + x *= scale; + y *= scale; + } + x += 128; + y += 128; + + d = std::max(d, 0.0); + d = std::min(d, 65535.); + x = std::max(x, 0.0); + y = std::max(y, 0.0); + x = std::min(x, 255.); + y = std::min(y, 255.); + + return Trajectory{(uint16_t)d, (uint8_t)x, (uint8_t)y}; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h index fff3b8b55c..9980263146 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrajectory.h @@ -1,28 +1,28 @@ -/* Overworld Trajectory - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_OverworldTrajectory_H -#define PokemonAutomation_PokemonSwSh_OverworldTrajectory_H - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -struct Trajectory{ - uint16_t distance_in_ticks; - uint8_t joystick_x; - uint8_t joystick_y; -}; - -Trajectory get_trajectory_float(double delta_x, double delta_y); - - -} -} -} -#endif +/* Overworld Trajectory + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_OverworldTrajectory_H +#define PokemonAutomation_PokemonSwSh_OverworldTrajectory_H + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +struct Trajectory{ + uint16_t distance_in_ticks; + uint8_t joystick_x; + uint8_t joystick_y; +}; + +Trajectory get_trajectory_float(double delta_x, double delta_y); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.cpp index 98bebbcb4b..ee1f19450d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.cpp @@ -1,105 +1,105 @@ -/* Overworld Trigger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Compiler.h" -#include "Common/Cpp/Exceptions.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh_OverworldMovement.h" -#include "PokemonSwSh_OverworldTrigger.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -OverworldTrigger::OverworldTrigger(OverworldTargetTracker& target_tracker) - : m_target_tracker(target_tracker) -{} -void OverworldTrigger::whistle(ProControllerContext& context, bool rotate){ - context.wait_for_all_requests(); - m_target_tracker.set_stop_on_target(false); - - if (rotate){ - pbf_move_right_joystick(context, 192, 255, 50, 70); - } - pbf_press_button(context, BUTTON_LCLICK, 5, 0); - pbf_mash_button(context, BUTTON_B, 120); - - context.wait_for_all_requests(); - m_target_tracker.set_stop_on_target(true); - if (m_target_tracker.has_good_target()){ - throw OperationCancelledException(); - } - - pbf_mash_button(context, BUTTON_B, 40); - - context.wait_for_all_requests(); - m_target_tracker.set_stop_on_target(false); -} - - -void OverworldTrigger_Whistle::run(ProControllerContext& context){ - whistle(context, !m_first_after_battle); - m_first_after_battle = false; -} - - -OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction( - OverworldTargetTracker& target_tracker, - bool whistle_first, - size_t whistle_count, - size_t action_count -) - : OverworldTrigger(target_tracker) - , m_whistle_first(whistle_first) - , m_whistle_count(whistle_count) - , m_action_count(action_count) -{} -void OverworldTrigger_WhistleStaticAction::run(ProControllerContext& context){ - if (m_whistle_first){ - whistle_loop(context); - action_loop(context); - }else{ - action_loop(context); - whistle_loop(context); - } -} -void OverworldTrigger_WhistleStaticAction::whistle_loop(ProControllerContext& context){ - for (size_t c = 0; c < m_whistle_count; c++){ - whistle(context, !m_first_after_battle); - m_first_after_battle = false; - } -} -void OverworldTrigger_WhistleStaticAction::action_loop(ProControllerContext& context){ - m_target_tracker.set_stop_on_target(true); - context.wait_for_all_requests(); - for (size_t c = 0; c < m_action_count; c++){ - action(context); - m_first_after_battle = false; - } - context.wait_for_all_requests(); - m_target_tracker.set_stop_on_target(false); -} - - -void OverworldTrigger_WhistleCircle::action(ProControllerContext& context){ - circle_in_place(context, rand() % 2); -} -void OverworldTrigger_WhistleHorizontal::action(ProControllerContext& context){ - move_in_line(context, true); -} -void OverworldTrigger_WhistleVertical::action(ProControllerContext& context){ - move_in_line(context, false); -} - - - -} -} -} - - - +/* Overworld Trigger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Compiler.h" +#include "Common/Cpp/Exceptions.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh_OverworldMovement.h" +#include "PokemonSwSh_OverworldTrigger.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +OverworldTrigger::OverworldTrigger(OverworldTargetTracker& target_tracker) + : m_target_tracker(target_tracker) +{} +void OverworldTrigger::whistle(ProControllerContext& context, bool rotate){ + context.wait_for_all_requests(); + m_target_tracker.set_stop_on_target(false); + + if (rotate){ + pbf_move_right_joystick(context, 192, 255, 50, 70); + } + pbf_press_button(context, BUTTON_LCLICK, 5, 0); + pbf_mash_button(context, BUTTON_B, 120); + + context.wait_for_all_requests(); + m_target_tracker.set_stop_on_target(true); + if (m_target_tracker.has_good_target()){ + throw OperationCancelledException(); + } + + pbf_mash_button(context, BUTTON_B, 40); + + context.wait_for_all_requests(); + m_target_tracker.set_stop_on_target(false); +} + + +void OverworldTrigger_Whistle::run(ProControllerContext& context){ + whistle(context, !m_first_after_battle); + m_first_after_battle = false; +} + + +OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction( + OverworldTargetTracker& target_tracker, + bool whistle_first, + size_t whistle_count, + size_t action_count +) + : OverworldTrigger(target_tracker) + , m_whistle_first(whistle_first) + , m_whistle_count(whistle_count) + , m_action_count(action_count) +{} +void OverworldTrigger_WhistleStaticAction::run(ProControllerContext& context){ + if (m_whistle_first){ + whistle_loop(context); + action_loop(context); + }else{ + action_loop(context); + whistle_loop(context); + } +} +void OverworldTrigger_WhistleStaticAction::whistle_loop(ProControllerContext& context){ + for (size_t c = 0; c < m_whistle_count; c++){ + whistle(context, !m_first_after_battle); + m_first_after_battle = false; + } +} +void OverworldTrigger_WhistleStaticAction::action_loop(ProControllerContext& context){ + m_target_tracker.set_stop_on_target(true); + context.wait_for_all_requests(); + for (size_t c = 0; c < m_action_count; c++){ + action(context); + m_first_after_battle = false; + } + context.wait_for_all_requests(); + m_target_tracker.set_stop_on_target(false); +} + + +void OverworldTrigger_WhistleCircle::action(ProControllerContext& context){ + circle_in_place(context, rand() % 2); +} +void OverworldTrigger_WhistleHorizontal::action(ProControllerContext& context){ + move_in_line(context, true); +} +void OverworldTrigger_WhistleVertical::action(ProControllerContext& context){ + move_in_line(context, false); +} + + + +} +} +} + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.h b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.h index b7b6c7e5e6..64802b503f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_OverworldTrigger.h @@ -1,94 +1,94 @@ -/* Overworld Trigger - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_OverworldTrigger_H -#define PokemonAutomation_PokemonSwSh_OverworldTrigger_H - -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh_OverworldTargetTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class OverworldTrigger{ -public: - OverworldTrigger(OverworldTargetTracker& target_tracker); - virtual ~OverworldTrigger() = default; - - virtual void run(ProControllerContext& context) = 0; - -protected: - void whistle(ProControllerContext& context, bool rotate); - -protected: - OverworldTargetTracker& m_target_tracker; -}; - - - -class OverworldTrigger_Whistle : public OverworldTrigger{ -public: - using OverworldTrigger::OverworldTrigger; - virtual void run(ProControllerContext& context) override; - -private: - bool m_first_after_battle = true; -}; - - -class OverworldTrigger_WhistleStaticAction : public OverworldTrigger{ -public: - OverworldTrigger_WhistleStaticAction( - OverworldTargetTracker& target_tracker, - bool whistle_first, - size_t whistle_count, - size_t action_count - ); - virtual void run(ProControllerContext& context) override; - -protected: - virtual void action(ProControllerContext& context) = 0; - -private: - void whistle_loop(ProControllerContext& context); - void action_loop(ProControllerContext& context); - -private: - bool m_whistle_first; - size_t m_whistle_count; - size_t m_action_count; - bool m_first_after_battle = true; -}; - - -class OverworldTrigger_WhistleCircle : public OverworldTrigger_WhistleStaticAction{ -public: - using OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction; - virtual void action(ProControllerContext& context) override; -}; - - -class OverworldTrigger_WhistleHorizontal : public OverworldTrigger_WhistleStaticAction{ -public: - using OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction; - virtual void action(ProControllerContext& context) override; -}; - - -class OverworldTrigger_WhistleVertical : public OverworldTrigger_WhistleStaticAction{ -public: - using OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction; - virtual void action(ProControllerContext& context) override; -}; - - - -} -} -} -#endif +/* Overworld Trigger + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_OverworldTrigger_H +#define PokemonAutomation_PokemonSwSh_OverworldTrigger_H + +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh_OverworldTargetTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class OverworldTrigger{ +public: + OverworldTrigger(OverworldTargetTracker& target_tracker); + virtual ~OverworldTrigger() = default; + + virtual void run(ProControllerContext& context) = 0; + +protected: + void whistle(ProControllerContext& context, bool rotate); + +protected: + OverworldTargetTracker& m_target_tracker; +}; + + + +class OverworldTrigger_Whistle : public OverworldTrigger{ +public: + using OverworldTrigger::OverworldTrigger; + virtual void run(ProControllerContext& context) override; + +private: + bool m_first_after_battle = true; +}; + + +class OverworldTrigger_WhistleStaticAction : public OverworldTrigger{ +public: + OverworldTrigger_WhistleStaticAction( + OverworldTargetTracker& target_tracker, + bool whistle_first, + size_t whistle_count, + size_t action_count + ); + virtual void run(ProControllerContext& context) override; + +protected: + virtual void action(ProControllerContext& context) = 0; + +private: + void whistle_loop(ProControllerContext& context); + void action_loop(ProControllerContext& context); + +private: + bool m_whistle_first; + size_t m_whistle_count; + size_t m_action_count; + bool m_first_after_battle = true; +}; + + +class OverworldTrigger_WhistleCircle : public OverworldTrigger_WhistleStaticAction{ +public: + using OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction; + virtual void action(ProControllerContext& context) override; +}; + + +class OverworldTrigger_WhistleHorizontal : public OverworldTrigger_WhistleStaticAction{ +public: + using OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction; + virtual void action(ProControllerContext& context) override; +}; + + +class OverworldTrigger_WhistleVertical : public OverworldTrigger_WhistleStaticAction{ +public: + using OverworldTrigger_WhistleStaticAction::OverworldTrigger_WhistleStaticAction; + virtual void action(ProControllerContext& context) override; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp index c7c8cc4d52..e505141b9d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.cpp @@ -1,450 +1,450 @@ -/* Shiny Hunt Autonomous - Overworld - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_OverworldMovement.h" -#include "PokemonSwSh_OverworldTrajectory.h" -#include "PokemonSwSh_OverworldTrigger.h" -#include "PokemonSwSh_ShinyHuntAutonomous-Overworld.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousOverworld_Descriptor::ShinyHuntAutonomousOverworld_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousOverworld", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Overworld", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Overworld.md", - "Automatically shiny hunt overworld " + STRING_POKEMON + " with video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntAutonomousOverworld_Descriptor::Stats : public ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(true) - , m_resets(m_stats["Resets"]) - { - m_display_order.insert(m_display_order.begin() + 2, Stat("Resets")); - m_aliases["Unexpected Battles"] = "Errors"; - } - std::atomic& m_resets; -}; -std::unique_ptr ShinyHuntAutonomousOverworld_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ShinyHuntAutonomousOverworld::ShinyHuntAutonomousOverworld() - : GO_HOME_WHEN_DONE(false) - , TIME_ROLLBACK_HOURS( - "Time Rollback (in hours):
Periodically roll back the time to keep the weather the same. If set to zero, this feature is disabled.", - LockMode::LOCK_WHILE_RUNNING, - 1, 0, 11 - ) - , MARK_OFFSET( - "Mark Offset:
Aim this far below the bottom of the exclamation/question mark. 1.0 is the height of the mark. " - "Increase this value when the " + STRING_POKEMON + " are large.", - LockMode::LOCK_WHILE_RUNNING, - 0.5, 0, 20 - ) - , MARK_PRIORITY( - "Mark Priority:
Favor exclamation marks or question marks?", - { - {MarkPriority::EXCLAMATION_ONLY, "exclamation-only", "Exclamation Marks Only (Ignore Question Marks)"}, - {MarkPriority::PRIORITIZE_EXCLAMATION, "prioritize-exclamation", "Prioritize Exclamation Marks"}, - {MarkPriority::NO_PREFERENCE, "no-preference", "No Preference"}, - {MarkPriority::PRIORITIZE_QUESTION, "prioritize-question", "Prioritize Question Marks"}, - {MarkPriority::QUESTION_ONLY, "question-only", "Question Marks Only (Ignore Exclamation Marks)"}, - }, - LockMode::LOCK_WHILE_RUNNING, - MarkPriority::PRIORITIZE_EXCLAMATION - ) - , TRIGGER_METHOD( - "Trigger Method:
How to trigger an overworld reaction mark?", - { - {TriggerMethod::WhistleOnly, "whistle-only", "Whistle Only"}, - {TriggerMethod::Whistle3Circle1, "whistle3-circle1", "Whistle 3 times, then circle once."}, - {TriggerMethod::Circle3Whistle3, "circle3-whistle3", "Circle 3 times, then whistle 3 times."}, - {TriggerMethod::CircleOnly, "circle-only", "Circle Only"}, - {TriggerMethod::Horizontal, "horizontal", "Horizontal Line Only"}, - {TriggerMethod::Whistle3Horizontal1, "whistle3-horizontal1", "Whistle 3 times, then do horizontal line once."}, - {TriggerMethod::Horizontal3Whistle3, "horizontal3-whistle3", "Do horizontal line 3 times, then whistle 3 times."}, - {TriggerMethod::Vertical, "vertical", "Vertical Line Only"}, - {TriggerMethod::Whistle3Vertical1, "whistle3-vertical1", "Whistle 3 times, then do vertical line once."}, - {TriggerMethod::Vertical3Whistle3, "vertical3-whistle3", "Do vertical line 3 times, then whistle 3 times."}, - }, - LockMode::LOCK_WHILE_RUNNING, - TriggerMethod::Whistle3Circle1 - ) - , MAX_MOVE_DURATION0( - "Maximum Move Duration:
Do not move in the same direction for more than this long." - " If you set this too high, you may wander too far from the grassy area.", - LockMode::LOCK_WHILE_RUNNING, - "1600 ms" - ) - , MAX_TARGET_ALPHA( - "Max Target Alpha:
Ignore all targets with alpha larger than this. Set to zero to ignore all marks.", - LockMode::LOCK_WHILE_RUNNING, - 70000, 0 - ) - , ENCOUNTER_BOT_OPTIONS(true, true) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , WATCHDOG_TIMER0( - "Watchdog Timer:
Reset the game if you go this long without any encounters.", - LockMode::LOCK_WHILE_RUNNING, - "60 s" - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) - , TARGET_CIRCLING( - "Target Circling:
After moving towards a " + STRING_POKEMON + ", make a circle." - " This increases the chance of encountering the " + STRING_POKEMON + " if it has moved or if the trajectory missed.", - LockMode::LOCK_WHILE_RUNNING, - true - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(MARK_OFFSET); - PA_ADD_OPTION(MARK_PRIORITY); - PA_ADD_OPTION(TRIGGER_METHOD); - PA_ADD_OPTION(MAX_MOVE_DURATION0); - PA_ADD_OPTION(MAX_TARGET_ALPHA); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(WATCHDOG_TIMER0); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); - PA_ADD_OPTION(TARGET_CIRCLING); -} - - - - -bool ShinyHuntAutonomousOverworld::find_encounter( - VideoStream& stream, ProControllerContext& context, - ShinyHuntAutonomousOverworld_Descriptor::Stats& stats, - WallClock expiration -) const{ - OverlayBoxScope self( - stream.overlay(), - { - OverworldTargetTracker::OVERWORLD_CENTER_X - 0.02, - OverworldTargetTracker::OVERWORLD_CENTER_Y - 0.05, - 0.04, - 0.1 - }, - COLOR_CYAN - ); - - OverworldTargetTracker target_tracker( - stream.logger(), stream.overlay(), - std::chrono::milliseconds(1000), - MARK_OFFSET, - MARK_PRIORITY, - MAX_TARGET_ALPHA - ); - - std::unique_ptr trigger; - switch (TRIGGER_METHOD){ - case TriggerMethod::WhistleOnly: - trigger.reset(new OverworldTrigger_Whistle(target_tracker)); - break; - case TriggerMethod::Whistle3Circle1: - trigger.reset(new OverworldTrigger_WhistleCircle(target_tracker, true, 3, 1)); - break; - case TriggerMethod::Circle3Whistle3: - trigger.reset(new OverworldTrigger_WhistleCircle(target_tracker, false, 3, 3)); - break; - case TriggerMethod::CircleOnly: - trigger.reset(new OverworldTrigger_WhistleCircle(target_tracker, false, 0, 1)); - break; - case TriggerMethod::Horizontal: - trigger.reset(new OverworldTrigger_WhistleHorizontal(target_tracker, false, 0, 1)); - break; - case TriggerMethod::Whistle3Horizontal1: - trigger.reset(new OverworldTrigger_WhistleHorizontal(target_tracker, true, 3, 1)); - break; - case TriggerMethod::Horizontal3Whistle3: - trigger.reset(new OverworldTrigger_WhistleHorizontal(target_tracker, false, 3, 3)); - break; - case TriggerMethod::Vertical: - trigger.reset(new OverworldTrigger_WhistleVertical(target_tracker, false, 0, 1)); - break; - case TriggerMethod::Whistle3Vertical1: - trigger.reset(new OverworldTrigger_WhistleVertical(target_tracker, true, 3, 1)); - break; - case TriggerMethod::Vertical3Whistle3: - trigger.reset(new OverworldTrigger_WhistleVertical(target_tracker, false, 3, 3)); - break; - } - - while (true){ - // Time expired. - if (current_time() > expiration){ - return false; - } - - target_tracker.clear_detections(); - - // Run trigger. - { - StandardBattleMenuWatcher battle_menu_detector(false); - StartBattleWatcher start_battle_detector; - - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - trigger->run(context); - }, - { - {battle_menu_detector}, - {start_battle_detector}, - {target_tracker}, - } - ); - - switch (result){ - case 0: - stream.log("Unexpected Battle.", COLOR_RED); - return false; - case 1: - stream.log("Battle started!"); - return true; - } - } - - std::pair target = target_tracker.best_target(); - target_tracker.clear_detections(); - -// env.log("target: " + std::to_string(target.first)); - - if (target.first < 0){ - stream.log("No targets found.", COLOR_ORANGE); - continue; - } - if (target.first > MAX_TARGET_ALPHA){ - stream.log( - std::string("Target too Weak: ") + - (target.second.mark == OverworldMark::EXCLAMATION_MARK ? "Exclamation" : "Question") + - " at [" + - tostr_default(target.second.delta_x) + " , " + - tostr_default(-target.second.delta_y) + "], alpha = " + - tostr_default(target.first), - COLOR_ORANGE - ); - continue; - } - - if (charge_at_target(stream, context, target)){ - return true; - } - } -} - - -bool ShinyHuntAutonomousOverworld::charge_at_target( - VideoStream& stream, ProControllerContext& context, - const std::pair& target -) const{ - OverlayBoxScope target_box(stream.overlay(), target.second.box, COLOR_YELLOW); - stream.log( - std::string("Best Target: ") + - (target.second.mark == OverworldMark::EXCLAMATION_MARK ? "Exclamation" : "Question") + - " at [" + - tostr_default(target.second.delta_x) + " , " + - tostr_default(-target.second.delta_y) + "], alpha = " + - tostr_default(target.first), - COLOR_PURPLE - ); - - const Trajectory& trajectory = target.second.trajectory; - double angle = std::atan2( - (double)trajectory.joystick_y - 128, - (double)trajectory.joystick_x - 128 - ) * 57.295779513082320877; - stream.log( - "Trajectory: Distance = " + std::to_string(trajectory.distance_in_ticks) + - ", Direction = " + tostr_default(-angle) + " degrees" - ); - - Milliseconds duration = (trajectory.distance_in_ticks + 16) * 8ms; - duration = std::min(duration, MAX_MOVE_DURATION0); - - - StandardBattleMenuWatcher battle_menu_detector(false); - StartBattleWatcher start_battle_detector; - OverworldTargetTracker target_tracker( - stream.logger(), stream.overlay(), - std::chrono::milliseconds(1000), - MARK_OFFSET, - MARK_PRIORITY, - MAX_TARGET_ALPHA - ); - - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - // Move to target. - pbf_move_left_joystick( - context, - trajectory.joystick_x, - trajectory.joystick_y, - duration, 0ms - ); - - // Circle Maneuver - if (TARGET_CIRCLING){ - if (trajectory.joystick_y < 64 && - 64 <= trajectory.joystick_x && trajectory.joystick_x <= 192 - ){ - move_in_circle_up(context, trajectory.joystick_x > 128); - }else{ - move_in_circle_down(context, trajectory.joystick_x <= 128); - } - } - }, - { - {battle_menu_detector}, - {start_battle_detector}, - {target_tracker}, - } - ); - - switch (result){ - case 0: - stream.log("Unexpected Battle.", COLOR_RED); - return true; - case 1: - stream.log("Battle started!"); - return true; - default: - return false; - } -} - - - - - - -void ShinyHuntAutonomousOverworld::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - srand((unsigned)time(nullptr)); - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - pbf_move_right_joystick(context, 128, 255, TICKS_PER_SECOND, 0); - - WallDuration TIMEOUT = WATCHDOG_TIMER0; - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - - ShinyHuntAutonomousOverworld_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - // Encounter Loop - auto last = current_time(); - while (true){ - // Touch the date. - if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - last_touch += PERIOD; - } - - auto now = current_time(); - if (now - last > TIMEOUT){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - stats.m_resets++; - last = current_time(); - continue; - } - - context.wait_for_all_requests(); - - bool battle = find_encounter(env.console, context, stats, last + TIMEOUT); - if (!battle){ - continue; - } - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); -// shininess = ShinyDetection::SQUARE_SHINY; - - bool stop = handler.handle_standard_encounter_end_battle(result, EXIT_BATTLE_TIMEOUT0); - if (stop){ - break; - } - - last = current_time(); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} - +/* Shiny Hunt Autonomous - Overworld + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_OverworldMovement.h" +#include "PokemonSwSh_OverworldTrajectory.h" +#include "PokemonSwSh_OverworldTrigger.h" +#include "PokemonSwSh_ShinyHuntAutonomous-Overworld.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousOverworld_Descriptor::ShinyHuntAutonomousOverworld_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousOverworld", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Overworld", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Overworld.md", + "Automatically shiny hunt overworld " + STRING_POKEMON + " with video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntAutonomousOverworld_Descriptor::Stats : public ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(true) + , m_resets(m_stats["Resets"]) + { + m_display_order.insert(m_display_order.begin() + 2, Stat("Resets")); + m_aliases["Unexpected Battles"] = "Errors"; + } + std::atomic& m_resets; +}; +std::unique_ptr ShinyHuntAutonomousOverworld_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ShinyHuntAutonomousOverworld::ShinyHuntAutonomousOverworld() + : GO_HOME_WHEN_DONE(false) + , TIME_ROLLBACK_HOURS( + "Time Rollback (in hours):
Periodically roll back the time to keep the weather the same. If set to zero, this feature is disabled.", + LockMode::LOCK_WHILE_RUNNING, + 1, 0, 11 + ) + , MARK_OFFSET( + "Mark Offset:
Aim this far below the bottom of the exclamation/question mark. 1.0 is the height of the mark. " + "Increase this value when the " + STRING_POKEMON + " are large.", + LockMode::LOCK_WHILE_RUNNING, + 0.5, 0, 20 + ) + , MARK_PRIORITY( + "Mark Priority:
Favor exclamation marks or question marks?", + { + {MarkPriority::EXCLAMATION_ONLY, "exclamation-only", "Exclamation Marks Only (Ignore Question Marks)"}, + {MarkPriority::PRIORITIZE_EXCLAMATION, "prioritize-exclamation", "Prioritize Exclamation Marks"}, + {MarkPriority::NO_PREFERENCE, "no-preference", "No Preference"}, + {MarkPriority::PRIORITIZE_QUESTION, "prioritize-question", "Prioritize Question Marks"}, + {MarkPriority::QUESTION_ONLY, "question-only", "Question Marks Only (Ignore Exclamation Marks)"}, + }, + LockMode::LOCK_WHILE_RUNNING, + MarkPriority::PRIORITIZE_EXCLAMATION + ) + , TRIGGER_METHOD( + "Trigger Method:
How to trigger an overworld reaction mark?", + { + {TriggerMethod::WhistleOnly, "whistle-only", "Whistle Only"}, + {TriggerMethod::Whistle3Circle1, "whistle3-circle1", "Whistle 3 times, then circle once."}, + {TriggerMethod::Circle3Whistle3, "circle3-whistle3", "Circle 3 times, then whistle 3 times."}, + {TriggerMethod::CircleOnly, "circle-only", "Circle Only"}, + {TriggerMethod::Horizontal, "horizontal", "Horizontal Line Only"}, + {TriggerMethod::Whistle3Horizontal1, "whistle3-horizontal1", "Whistle 3 times, then do horizontal line once."}, + {TriggerMethod::Horizontal3Whistle3, "horizontal3-whistle3", "Do horizontal line 3 times, then whistle 3 times."}, + {TriggerMethod::Vertical, "vertical", "Vertical Line Only"}, + {TriggerMethod::Whistle3Vertical1, "whistle3-vertical1", "Whistle 3 times, then do vertical line once."}, + {TriggerMethod::Vertical3Whistle3, "vertical3-whistle3", "Do vertical line 3 times, then whistle 3 times."}, + }, + LockMode::LOCK_WHILE_RUNNING, + TriggerMethod::Whistle3Circle1 + ) + , MAX_MOVE_DURATION0( + "Maximum Move Duration:
Do not move in the same direction for more than this long." + " If you set this too high, you may wander too far from the grassy area.", + LockMode::LOCK_WHILE_RUNNING, + "1600 ms" + ) + , MAX_TARGET_ALPHA( + "Max Target Alpha:
Ignore all targets with alpha larger than this. Set to zero to ignore all marks.", + LockMode::LOCK_WHILE_RUNNING, + 70000, 0 + ) + , ENCOUNTER_BOT_OPTIONS(true, true) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , WATCHDOG_TIMER0( + "Watchdog Timer:
Reset the game if you go this long without any encounters.", + LockMode::LOCK_WHILE_RUNNING, + "60 s" + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) + , TARGET_CIRCLING( + "Target Circling:
After moving towards a " + STRING_POKEMON + ", make a circle." + " This increases the chance of encountering the " + STRING_POKEMON + " if it has moved or if the trajectory missed.", + LockMode::LOCK_WHILE_RUNNING, + true + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(MARK_OFFSET); + PA_ADD_OPTION(MARK_PRIORITY); + PA_ADD_OPTION(TRIGGER_METHOD); + PA_ADD_OPTION(MAX_MOVE_DURATION0); + PA_ADD_OPTION(MAX_TARGET_ALPHA); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(WATCHDOG_TIMER0); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); + PA_ADD_OPTION(TARGET_CIRCLING); +} + + + + +bool ShinyHuntAutonomousOverworld::find_encounter( + VideoStream& stream, ProControllerContext& context, + ShinyHuntAutonomousOverworld_Descriptor::Stats& stats, + WallClock expiration +) const{ + OverlayBoxScope self( + stream.overlay(), + { + OverworldTargetTracker::OVERWORLD_CENTER_X - 0.02, + OverworldTargetTracker::OVERWORLD_CENTER_Y - 0.05, + 0.04, + 0.1 + }, + COLOR_CYAN + ); + + OverworldTargetTracker target_tracker( + stream.logger(), stream.overlay(), + std::chrono::milliseconds(1000), + MARK_OFFSET, + MARK_PRIORITY, + MAX_TARGET_ALPHA + ); + + std::unique_ptr trigger; + switch (TRIGGER_METHOD){ + case TriggerMethod::WhistleOnly: + trigger.reset(new OverworldTrigger_Whistle(target_tracker)); + break; + case TriggerMethod::Whistle3Circle1: + trigger.reset(new OverworldTrigger_WhistleCircle(target_tracker, true, 3, 1)); + break; + case TriggerMethod::Circle3Whistle3: + trigger.reset(new OverworldTrigger_WhistleCircle(target_tracker, false, 3, 3)); + break; + case TriggerMethod::CircleOnly: + trigger.reset(new OverworldTrigger_WhistleCircle(target_tracker, false, 0, 1)); + break; + case TriggerMethod::Horizontal: + trigger.reset(new OverworldTrigger_WhistleHorizontal(target_tracker, false, 0, 1)); + break; + case TriggerMethod::Whistle3Horizontal1: + trigger.reset(new OverworldTrigger_WhistleHorizontal(target_tracker, true, 3, 1)); + break; + case TriggerMethod::Horizontal3Whistle3: + trigger.reset(new OverworldTrigger_WhistleHorizontal(target_tracker, false, 3, 3)); + break; + case TriggerMethod::Vertical: + trigger.reset(new OverworldTrigger_WhistleVertical(target_tracker, false, 0, 1)); + break; + case TriggerMethod::Whistle3Vertical1: + trigger.reset(new OverworldTrigger_WhistleVertical(target_tracker, true, 3, 1)); + break; + case TriggerMethod::Vertical3Whistle3: + trigger.reset(new OverworldTrigger_WhistleVertical(target_tracker, false, 3, 3)); + break; + } + + while (true){ + // Time expired. + if (current_time() > expiration){ + return false; + } + + target_tracker.clear_detections(); + + // Run trigger. + { + StandardBattleMenuWatcher battle_menu_detector(false); + StartBattleWatcher start_battle_detector; + + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + trigger->run(context); + }, + { + {battle_menu_detector}, + {start_battle_detector}, + {target_tracker}, + } + ); + + switch (result){ + case 0: + stream.log("Unexpected Battle.", COLOR_RED); + return false; + case 1: + stream.log("Battle started!"); + return true; + } + } + + std::pair target = target_tracker.best_target(); + target_tracker.clear_detections(); + +// env.log("target: " + std::to_string(target.first)); + + if (target.first < 0){ + stream.log("No targets found.", COLOR_ORANGE); + continue; + } + if (target.first > MAX_TARGET_ALPHA){ + stream.log( + std::string("Target too Weak: ") + + (target.second.mark == OverworldMark::EXCLAMATION_MARK ? "Exclamation" : "Question") + + " at [" + + tostr_default(target.second.delta_x) + " , " + + tostr_default(-target.second.delta_y) + "], alpha = " + + tostr_default(target.first), + COLOR_ORANGE + ); + continue; + } + + if (charge_at_target(stream, context, target)){ + return true; + } + } +} + + +bool ShinyHuntAutonomousOverworld::charge_at_target( + VideoStream& stream, ProControllerContext& context, + const std::pair& target +) const{ + OverlayBoxScope target_box(stream.overlay(), target.second.box, COLOR_YELLOW); + stream.log( + std::string("Best Target: ") + + (target.second.mark == OverworldMark::EXCLAMATION_MARK ? "Exclamation" : "Question") + + " at [" + + tostr_default(target.second.delta_x) + " , " + + tostr_default(-target.second.delta_y) + "], alpha = " + + tostr_default(target.first), + COLOR_PURPLE + ); + + const Trajectory& trajectory = target.second.trajectory; + double angle = std::atan2( + (double)trajectory.joystick_y - 128, + (double)trajectory.joystick_x - 128 + ) * 57.295779513082320877; + stream.log( + "Trajectory: Distance = " + std::to_string(trajectory.distance_in_ticks) + + ", Direction = " + tostr_default(-angle) + " degrees" + ); + + Milliseconds duration = (trajectory.distance_in_ticks + 16) * 8ms; + duration = std::min(duration, MAX_MOVE_DURATION0); + + + StandardBattleMenuWatcher battle_menu_detector(false); + StartBattleWatcher start_battle_detector; + OverworldTargetTracker target_tracker( + stream.logger(), stream.overlay(), + std::chrono::milliseconds(1000), + MARK_OFFSET, + MARK_PRIORITY, + MAX_TARGET_ALPHA + ); + + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + // Move to target. + pbf_move_left_joystick( + context, + trajectory.joystick_x, + trajectory.joystick_y, + duration, 0ms + ); + + // Circle Maneuver + if (TARGET_CIRCLING){ + if (trajectory.joystick_y < 64 && + 64 <= trajectory.joystick_x && trajectory.joystick_x <= 192 + ){ + move_in_circle_up(context, trajectory.joystick_x > 128); + }else{ + move_in_circle_down(context, trajectory.joystick_x <= 128); + } + } + }, + { + {battle_menu_detector}, + {start_battle_detector}, + {target_tracker}, + } + ); + + switch (result){ + case 0: + stream.log("Unexpected Battle.", COLOR_RED); + return true; + case 1: + stream.log("Battle started!"); + return true; + default: + return false; + } +} + + + + + + +void ShinyHuntAutonomousOverworld::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + srand((unsigned)time(nullptr)); + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + pbf_move_right_joystick(context, 128, 255, TICKS_PER_SECOND, 0); + + WallDuration TIMEOUT = WATCHDOG_TIMER0; + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + + ShinyHuntAutonomousOverworld_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + // Encounter Loop + auto last = current_time(); + while (true){ + // Touch the date. + if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + last_touch += PERIOD; + } + + auto now = current_time(); + if (now - last > TIMEOUT){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + stats.m_resets++; + last = current_time(); + continue; + } + + context.wait_for_all_requests(); + + bool battle = find_encounter(env.console, context, stats, last + TIMEOUT); + if (!battle){ + continue; + } + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); +// shininess = ShinyDetection::SQUARE_SHINY; + + bool stop = handler.handle_standard_encounter_end_battle(result, EXIT_BATTLE_TIMEOUT0); + if (stop){ + break; + } + + last = current_time(); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h index 4d396f8d7e..cd4018970d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/OverworldBot/PokemonSwSh_ShinyHuntAutonomous-Overworld.h @@ -1,100 +1,100 @@ -/* Shiny Hunt Autonomous - Overworld - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousOverworld_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousOverworld_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/FloatingPointOption.h" -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" -#include "PokemonSwSh_OverworldTargetTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class ShinyHuntAutonomousOverworld_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousOverworld_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousOverworld : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousOverworld(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - - -private: - bool find_encounter( - VideoStream& stream, ProControllerContext& context, - ShinyHuntAutonomousOverworld_Descriptor::Stats& stats, - WallClock expiration - ) const; - - bool charge_at_target( - VideoStream& stream, ProControllerContext& context, - const std::pair& target - ) const; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption TIME_ROLLBACK_HOURS; - - EncounterBotLanguage LANGUAGE; - - FloatingPointOption MARK_OFFSET; - EnumDropdownOption MARK_PRIORITY; - - enum class TriggerMethod{ - WhistleOnly, - Whistle3Circle1, - Circle3Whistle3, - CircleOnly, - Horizontal, - Whistle3Horizontal1, - Horizontal3Whistle3, - Vertical, - Whistle3Vertical1, - Vertical3Whistle3, - }; - EnumDropdownOption TRIGGER_METHOD; - - MillisecondsOption MAX_MOVE_DURATION0; - FloatingPointOption MAX_TARGET_ALPHA; - - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption WATCHDOG_TIMER0; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; - BooleanCheckBoxOption TARGET_CIRCLING; -}; - - -} -} -} -#endif +/* Shiny Hunt Autonomous - Overworld + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousOverworld_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousOverworld_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/FloatingPointOption.h" +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" +#include "PokemonSwSh_OverworldTargetTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class ShinyHuntAutonomousOverworld_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousOverworld_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousOverworld : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousOverworld(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + + +private: + bool find_encounter( + VideoStream& stream, ProControllerContext& context, + ShinyHuntAutonomousOverworld_Descriptor::Stats& stats, + WallClock expiration + ) const; + + bool charge_at_target( + VideoStream& stream, ProControllerContext& context, + const std::pair& target + ) const; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption TIME_ROLLBACK_HOURS; + + EncounterBotLanguage LANGUAGE; + + FloatingPointOption MARK_OFFSET; + EnumDropdownOption MARK_PRIORITY; + + enum class TriggerMethod{ + WhistleOnly, + Whistle3Circle1, + Circle3Whistle3, + CircleOnly, + Horizontal, + Whistle3Horizontal1, + Horizontal3Whistle3, + Vertical, + Whistle3Vertical1, + Vertical3Whistle3, + }; + EnumDropdownOption TRIGGER_METHOD; + + MillisecondsOption MAX_MOVE_DURATION0; + FloatingPointOption MAX_TARGET_ALPHA; + + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption WATCHDOG_TIMER0; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; + BooleanCheckBoxOption TARGET_CIRCLING; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.cpp index d0def4efbd..77942738f3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.cpp @@ -1,230 +1,230 @@ -/* Basic Pokemon Catcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh_BasicCatcher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -// Returns the # of slots scrolled. Returns -1 if not found. -int move_to_ball( - const BattleBallReader& reader, - VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug, - bool forward, int attempts, Milliseconds delay -){ - VideoSnapshot frame = stream.video().snapshot(); - std::string first_ball = reader.read_ball(frame); - if (first_ball == ball_slug){ - return 0; - } - - size_t repeat_counter = 0; - for (int c = 1; c < attempts; c++){ - pbf_press_dpad(context, forward ? DPAD_RIGHT : DPAD_LEFT, 80ms, delay); - context.wait_for_all_requests(); - frame = stream.video().snapshot(); - std::string current_ball = reader.read_ball(frame); - if (current_ball == ball_slug){ - return c; - } - if (current_ball == first_ball){ - repeat_counter++; - if (repeat_counter == 3){ - return -1; - } - } - } - return -1; -} - -// Returns the quantity of the ball. -// Returns -1 if unable to read. -int16_t move_to_ball( - const BattleBallReader& reader, VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug -){ - // Search forward at high speed. - int ret = move_to_ball(reader, stream, context, ball_slug, true, 100, 320ms); - if (ret < 0){ - return 0; - } - if (ret == 0){ - uint16_t quantity = reader.read_quantity(stream.video().snapshot()); - return quantity == 0 ? -1 : quantity; - } - - // Wait a second to let the video catch up. - pbf_wait(context, 1000ms); - context.wait_for_all_requests(); - - // Now try again in reverse at a lower speed in case we overshot. - // This will return immediately if we got it right the first time. - ret = move_to_ball(reader, stream, context, ball_slug, false, 5, 1000ms); - if (ret < 0){ - return 0; - } - if (ret > 0){ - stream.log("Fast ball scrolling overshot by " + std::to_string(ret) + " slot(s).", COLOR_RED); - } - uint16_t quantity = reader.read_quantity(stream.video().snapshot()); - return quantity == 0 ? -1 : quantity; -} - - -CatchResults throw_balls( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit -){ - uint16_t balls_used = 0; - while (true){ - { - BattleBallReader reader(stream, language); - - pbf_mash_button(context, BUTTON_X, 125); - context.wait_for_all_requests(); - - bool success = move_to_ball(reader, stream, context, ball_slug); - if (!success){ - return {CatchResult::OUT_OF_BALLS, balls_used}; - } - - pbf_mash_button(context, BUTTON_A, 125); - context.wait_for_all_requests(); - } - balls_used++; - - auto start = current_time(); - - StandardBattleMenuWatcher menu_detector(false); - ExperienceGainWatcher experience_detector; - int result = wait_until( - stream, context, - std::chrono::seconds(60), - { - {menu_detector}, - {experience_detector}, - } - ); - switch (result){ - case 0: - if (current_time() < start + std::chrono::seconds(5)){ - stream.log("BasicCatcher: Unable to throw ball.", COLOR_RED); - return {CatchResult::CANNOT_THROW_BALL, balls_used}; - } - stream.log("BasicCatcher: Failed to catch.", COLOR_ORANGE); - if (balls_used >= ball_limit){ - stream.log("Reached the limit of " + std::to_string(ball_limit) + " balls.", COLOR_RED); - return {CatchResult::BALL_LIMIT_REACHED, balls_used}; - } - continue; - case 1: - stream.log("BasicCatcher: End of battle detected.", COLOR_PURPLE); - return {CatchResult::POKEMON_FAINTED, balls_used}; - default: - stream.log("BasicCatcher: Timed out.", COLOR_RED); - return {CatchResult::TIMED_OUT, balls_used}; - } - } -} - - -CatchResults basic_catcher( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit -){ - context.wait_for_all_requests(); - stream.log("Attempting to catch with: " + ball_slug); - - CatchResults results = throw_balls(stream, context, language, ball_slug, ball_limit); - switch (results.result){ - case CatchResult::OUT_OF_BALLS: - case CatchResult::CANNOT_THROW_BALL: - case CatchResult::BALL_LIMIT_REACHED: - case CatchResult::TIMED_OUT: - return results; - default:; - } - - - // Need to distinguish between caught or faint. - - - // Wait for end of battle. -// console.video().snapshot()->save("test0.png"); - { - stream.log("Waiting for black screen end..."); - BlackScreenOverWatcher black_screen_detector; - run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); - }, - {{black_screen_detector}} - ); - stream.log("Waiting for black screen end... Found!"); - } - - // Look for the orange caught screen. -// console.video().snapshot()->save("test1.png"); -// context.wait_for(std::chrono::milliseconds(5000)); - { - ReceivePokemonDetector caught_detector(true); - - int result = run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 4 * TICKS_PER_SECOND); - }, - {{caught_detector}} - ); - - switch (result){ - case 0: - stream.log("BasicCatcher: The wild " + STRING_POKEMON + " was caught!", COLOR_BLUE); - break; - default: - stream.log("BasicCatcher: The wild " + STRING_POKEMON + " fainted.", COLOR_RED); - results.result = CatchResult::POKEMON_FAINTED; - return results; - } - } - -// pbf_wait(context, 5 * TICKS_PER_SECOND); -// console.video().snapshot()->save("test2.png"); - { - stream.log("Waiting for black screen end..."); - BlackScreenOverWatcher black_screen_detector; - run_until( - stream, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); - }, - {{black_screen_detector}} - ); - stream.log("Waiting for black screen end... Found!"); - } - - results.result = CatchResult::POKEMON_CAUGHT; - return results; -} - - -} -} -} +/* Basic Pokemon Catcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_ExperienceGainDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh_BasicCatcher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +// Returns the # of slots scrolled. Returns -1 if not found. +int move_to_ball( + const BattleBallReader& reader, + VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug, + bool forward, int attempts, Milliseconds delay +){ + VideoSnapshot frame = stream.video().snapshot(); + std::string first_ball = reader.read_ball(frame); + if (first_ball == ball_slug){ + return 0; + } + + size_t repeat_counter = 0; + for (int c = 1; c < attempts; c++){ + pbf_press_dpad(context, forward ? DPAD_RIGHT : DPAD_LEFT, 80ms, delay); + context.wait_for_all_requests(); + frame = stream.video().snapshot(); + std::string current_ball = reader.read_ball(frame); + if (current_ball == ball_slug){ + return c; + } + if (current_ball == first_ball){ + repeat_counter++; + if (repeat_counter == 3){ + return -1; + } + } + } + return -1; +} + +// Returns the quantity of the ball. +// Returns -1 if unable to read. +int16_t move_to_ball( + const BattleBallReader& reader, VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug +){ + // Search forward at high speed. + int ret = move_to_ball(reader, stream, context, ball_slug, true, 100, 320ms); + if (ret < 0){ + return 0; + } + if (ret == 0){ + uint16_t quantity = reader.read_quantity(stream.video().snapshot()); + return quantity == 0 ? -1 : quantity; + } + + // Wait a second to let the video catch up. + pbf_wait(context, 1000ms); + context.wait_for_all_requests(); + + // Now try again in reverse at a lower speed in case we overshot. + // This will return immediately if we got it right the first time. + ret = move_to_ball(reader, stream, context, ball_slug, false, 5, 1000ms); + if (ret < 0){ + return 0; + } + if (ret > 0){ + stream.log("Fast ball scrolling overshot by " + std::to_string(ret) + " slot(s).", COLOR_RED); + } + uint16_t quantity = reader.read_quantity(stream.video().snapshot()); + return quantity == 0 ? -1 : quantity; +} + + +CatchResults throw_balls( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit +){ + uint16_t balls_used = 0; + while (true){ + { + BattleBallReader reader(stream, language); + + pbf_mash_button(context, BUTTON_X, 125); + context.wait_for_all_requests(); + + bool success = move_to_ball(reader, stream, context, ball_slug); + if (!success){ + return {CatchResult::OUT_OF_BALLS, balls_used}; + } + + pbf_mash_button(context, BUTTON_A, 125); + context.wait_for_all_requests(); + } + balls_used++; + + auto start = current_time(); + + StandardBattleMenuWatcher menu_detector(false); + ExperienceGainWatcher experience_detector; + int result = wait_until( + stream, context, + std::chrono::seconds(60), + { + {menu_detector}, + {experience_detector}, + } + ); + switch (result){ + case 0: + if (current_time() < start + std::chrono::seconds(5)){ + stream.log("BasicCatcher: Unable to throw ball.", COLOR_RED); + return {CatchResult::CANNOT_THROW_BALL, balls_used}; + } + stream.log("BasicCatcher: Failed to catch.", COLOR_ORANGE); + if (balls_used >= ball_limit){ + stream.log("Reached the limit of " + std::to_string(ball_limit) + " balls.", COLOR_RED); + return {CatchResult::BALL_LIMIT_REACHED, balls_used}; + } + continue; + case 1: + stream.log("BasicCatcher: End of battle detected.", COLOR_PURPLE); + return {CatchResult::POKEMON_FAINTED, balls_used}; + default: + stream.log("BasicCatcher: Timed out.", COLOR_RED); + return {CatchResult::TIMED_OUT, balls_used}; + } + } +} + + +CatchResults basic_catcher( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit +){ + context.wait_for_all_requests(); + stream.log("Attempting to catch with: " + ball_slug); + + CatchResults results = throw_balls(stream, context, language, ball_slug, ball_limit); + switch (results.result){ + case CatchResult::OUT_OF_BALLS: + case CatchResult::CANNOT_THROW_BALL: + case CatchResult::BALL_LIMIT_REACHED: + case CatchResult::TIMED_OUT: + return results; + default:; + } + + + // Need to distinguish between caught or faint. + + + // Wait for end of battle. +// console.video().snapshot()->save("test0.png"); + { + stream.log("Waiting for black screen end..."); + BlackScreenOverWatcher black_screen_detector; + run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 120 * TICKS_PER_SECOND); + }, + {{black_screen_detector}} + ); + stream.log("Waiting for black screen end... Found!"); + } + + // Look for the orange caught screen. +// console.video().snapshot()->save("test1.png"); +// context.wait_for(std::chrono::milliseconds(5000)); + { + ReceivePokemonDetector caught_detector(true); + + int result = run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 4 * TICKS_PER_SECOND); + }, + {{caught_detector}} + ); + + switch (result){ + case 0: + stream.log("BasicCatcher: The wild " + STRING_POKEMON + " was caught!", COLOR_BLUE); + break; + default: + stream.log("BasicCatcher: The wild " + STRING_POKEMON + " fainted.", COLOR_RED); + results.result = CatchResult::POKEMON_FAINTED; + return results; + } + } + +// pbf_wait(context, 5 * TICKS_PER_SECOND); +// console.video().snapshot()->save("test2.png"); + { + stream.log("Waiting for black screen end..."); + BlackScreenOverWatcher black_screen_detector; + run_until( + stream, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, 10 * TICKS_PER_SECOND); + }, + {{black_screen_detector}} + ); + stream.log("Waiting for black screen end... Found!"); + } + + results.result = CatchResult::POKEMON_CAUGHT; + return results; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h index 0395a99c37..e68aeabdd7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h @@ -1,46 +1,46 @@ -/* Basic Pokemon Catcher - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BasicCatcher_H -#define PokemonAutomation_PokemonSwSh_BasicCatcher_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -// Returns the quantity of the ball. -// Returns -1 if unable to read. -int16_t move_to_ball( - const BattleBallReader& reader, VideoStream& stream, ProControllerContext& context, - const std::string& ball_slug -); - - -struct CatchResults{ - CatchResult result; - uint16_t balls_used; -}; -CatchResults basic_catcher( - VideoStream& stream, ProControllerContext& context, - Language language, - const std::string& ball_slug, uint16_t ball_limit -); - - - -} -} -} -#endif +/* Basic Pokemon Catcher + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BasicCatcher_H +#define PokemonAutomation_PokemonSwSh_BasicCatcher_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleBallReader.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +// Returns the quantity of the ball. +// Returns -1 if unable to read. +int16_t move_to_ball( + const BattleBallReader& reader, VideoStream& stream, ProControllerContext& context, + const std::string& ball_slug +); + + +struct CatchResults{ + CatchResult result; + uint16_t balls_used; +}; +CatchResults basic_catcher( + VideoStream& stream, ProControllerContext& context, + Language language, + const std::string& ball_slug, uint16_t ball_limit +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h index 86ca1d2fea..f3da662fb2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h @@ -1,26 +1,26 @@ -/* Box Helpers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_BoxHelpers_H -#define PokemonAutomation_PokemonSwSh_BoxHelpers_H - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -static inline void box_scroll(ProControllerContext& context, DpadPosition direction){ - ssf_press_dpad_ptv(context, direction, 200ms, 104ms); -} - - - -} -} -} -#endif +/* Box Helpers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_BoxHelpers_H +#define PokemonAutomation_PokemonSwSh_BoxHelpers_H + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +static inline void box_scroll(ProControllerContext& context, DpadPosition direction){ + ssf_press_dpad_ptv(context, direction, 200ms, 104ms); +} + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.cpp index 9cc8316fbe..c75ed27359 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.cpp @@ -1,162 +1,162 @@ -/* Encounter Detection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -//#include "Common/NintendoSwitch/NintendoSwitch_Protocol_PushButtons.h" -//#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InterruptableCommands.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh_EncounterDetection.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -StandardEncounterDetection::StandardEncounterDetection( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - const EncounterFilterOption2& filter, - ShinyType shininess, - std::chrono::milliseconds read_name_delay -) - : m_env(env) - , m_stream(stream) - , m_context(context) - , m_language(language) - , m_filter(filter) - , m_shininess(shininess) - , m_read_name_delay(read_name_delay) -{} -bool StandardEncounterDetection::is_shiny() const{ - switch (m_shininess){ - case ShinyType::UNKNOWN: - case ShinyType::NOT_SHINY: - return false; - case ShinyType::MAYBE_SHINY: - case ShinyType::UNKNOWN_SHINY: - case ShinyType::STAR_SHINY: - case ShinyType::SQUARE_SHINY: - return true; - } - return false; -} -const std::set* StandardEncounterDetection::candidates(){ - if (m_language == Language::None){ - m_name_read = true; - return nullptr; - } - - if (m_name_read){ - return &m_candidates; - } - - OverlayBoxScope box(m_stream.overlay(), ImageFloatBox(0.76, 0.04, 0.15, 0.044)); - m_context.wait_for(m_read_name_delay); - - VideoSnapshot screen = m_stream.video().snapshot(); - ImageViewRGB32 frame = extract_box_reference(screen, box); - - OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( - m_stream.logger(), m_language, frame, - OCR::BLACK_TEXT_FILTERS() - ); - if (result.results.empty()){ - dump_image( - m_stream.logger(), m_env.program_info(), - "StandardEncounterDetection-NameOCR-" + language_data(m_language).code, - screen - ); - }else{ - m_candidates.clear(); - for (const auto& item : result.results){ - m_candidates.insert(item.second.token); - } - } - - m_name_read = true; - return &m_candidates; -} - -bool filter_match(ShinyType detection, ShinyFilter filter){ - if (detection == ShinyType::UNKNOWN){ - return false; - } - - switch (filter){ - case ShinyFilter::ANYTHING: - return true; - case ShinyFilter::NOT_SHINY: - return detection == ShinyType::NOT_SHINY; - case ShinyFilter::ANY_SHINY: - return detection != ShinyType::NOT_SHINY; - case ShinyFilter::STAR_ONLY: - return detection == ShinyType::STAR_SHINY || detection == ShinyType::UNKNOWN_SHINY; - case ShinyFilter::SQUARE_ONLY: - return detection == ShinyType::SQUARE_SHINY || detection == ShinyType::UNKNOWN_SHINY; - case ShinyFilter::NOTHING: - return false; - } - - return false; -} - -EncounterActionFull StandardEncounterDetection::get_action(){ - if (m_shininess == ShinyType::UNKNOWN){ - return {EncounterAction::RunAway, ""}; - } - - EncounterActionFull action; - action.action = filter_match(m_shininess, m_filter.SHINY_FILTER) - ? EncounterAction::StopProgram - : EncounterAction::RunAway; - -// const std::vector& overrides = m_filter.overrides(); - std::vector> overrides = m_filter.FILTER_TABLE.copy_snapshot(); - - if (overrides.empty()){ - return action; - } - - const std::set* candidates = this->candidates(); - if (candidates != nullptr){ - for (const std::unique_ptr& override : overrides){ - // Not a token match. - if (candidates->find(override->pokemon.slug()) == candidates->end()){ - continue; - } - -// cout << "m_shininess = " << (int)m_shininess << " : " << (int)(ShinyFilter)override->shininess << endl; - - // Not a shiny filter match. - if (!filter_match(m_shininess, override->shininess)){ - continue; - } - - action.action = override->action; - action.pokeball_slug = override->pokeball.slug(); - action.ball_limit = override->ball_limit; - } - } - - return action; -} - - - - -} -} -} - +/* Encounter Detection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +//#include "Common/NintendoSwitch/NintendoSwitch_Protocol_PushButtons.h" +//#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InterruptableCommands.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh_EncounterDetection.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +StandardEncounterDetection::StandardEncounterDetection( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + const EncounterFilterOption2& filter, + ShinyType shininess, + std::chrono::milliseconds read_name_delay +) + : m_env(env) + , m_stream(stream) + , m_context(context) + , m_language(language) + , m_filter(filter) + , m_shininess(shininess) + , m_read_name_delay(read_name_delay) +{} +bool StandardEncounterDetection::is_shiny() const{ + switch (m_shininess){ + case ShinyType::UNKNOWN: + case ShinyType::NOT_SHINY: + return false; + case ShinyType::MAYBE_SHINY: + case ShinyType::UNKNOWN_SHINY: + case ShinyType::STAR_SHINY: + case ShinyType::SQUARE_SHINY: + return true; + } + return false; +} +const std::set* StandardEncounterDetection::candidates(){ + if (m_language == Language::None){ + m_name_read = true; + return nullptr; + } + + if (m_name_read){ + return &m_candidates; + } + + OverlayBoxScope box(m_stream.overlay(), ImageFloatBox(0.76, 0.04, 0.15, 0.044)); + m_context.wait_for(m_read_name_delay); + + VideoSnapshot screen = m_stream.video().snapshot(); + ImageViewRGB32 frame = extract_box_reference(screen, box); + + OCR::StringMatchResult result = PokemonNameReader::instance().read_substring( + m_stream.logger(), m_language, frame, + OCR::BLACK_TEXT_FILTERS() + ); + if (result.results.empty()){ + dump_image( + m_stream.logger(), m_env.program_info(), + "StandardEncounterDetection-NameOCR-" + language_data(m_language).code, + screen + ); + }else{ + m_candidates.clear(); + for (const auto& item : result.results){ + m_candidates.insert(item.second.token); + } + } + + m_name_read = true; + return &m_candidates; +} + +bool filter_match(ShinyType detection, ShinyFilter filter){ + if (detection == ShinyType::UNKNOWN){ + return false; + } + + switch (filter){ + case ShinyFilter::ANYTHING: + return true; + case ShinyFilter::NOT_SHINY: + return detection == ShinyType::NOT_SHINY; + case ShinyFilter::ANY_SHINY: + return detection != ShinyType::NOT_SHINY; + case ShinyFilter::STAR_ONLY: + return detection == ShinyType::STAR_SHINY || detection == ShinyType::UNKNOWN_SHINY; + case ShinyFilter::SQUARE_ONLY: + return detection == ShinyType::SQUARE_SHINY || detection == ShinyType::UNKNOWN_SHINY; + case ShinyFilter::NOTHING: + return false; + } + + return false; +} + +EncounterActionFull StandardEncounterDetection::get_action(){ + if (m_shininess == ShinyType::UNKNOWN){ + return {EncounterAction::RunAway, ""}; + } + + EncounterActionFull action; + action.action = filter_match(m_shininess, m_filter.SHINY_FILTER) + ? EncounterAction::StopProgram + : EncounterAction::RunAway; + +// const std::vector& overrides = m_filter.overrides(); + std::vector> overrides = m_filter.FILTER_TABLE.copy_snapshot(); + + if (overrides.empty()){ + return action; + } + + const std::set* candidates = this->candidates(); + if (candidates != nullptr){ + for (const std::unique_ptr& override : overrides){ + // Not a token match. + if (candidates->find(override->pokemon.slug()) == candidates->end()){ + continue; + } + +// cout << "m_shininess = " << (int)m_shininess << " : " << (int)(ShinyFilter)override->shininess << endl; + + // Not a shiny filter match. + if (!filter_match(m_shininess, override->shininess)){ + continue; + } + + action.action = override->action; + action.pokeball_slug = override->pokeball.slug(); + action.ball_limit = override->ball_limit; + } + } + + return action; +} + + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h index 78a7ee9f32..c3d9038908 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h @@ -1,63 +1,63 @@ -/* Encounter Detection - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterTracker_H -#define PokemonAutomation_PokemonSwSh_EncounterTracker_H - -#include "CommonFramework/Language.h" -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class StandardEncounterDetection{ -public: - StandardEncounterDetection( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - const EncounterFilterOption2& filter, - ShinyType shininess, - std::chrono::milliseconds read_name_delay = std::chrono::milliseconds(500) - ); - - bool is_shiny() const; - ShinyType shininess() const{ return m_shininess; } - - // nullptr = disabled - // empty set = unable to detect - const std::set* candidates(); - - EncounterActionFull get_action(); - -private: - ProgramEnvironment& m_env; - VideoStream& m_stream; - ProControllerContext& m_context; - - const Language m_language; - - const EncounterFilterOption2& m_filter; - const ShinyType m_shininess; - const std::chrono::milliseconds m_read_name_delay; - - bool m_name_read = false; - std::set m_candidates; -}; - - - - -} -} -} -#endif +/* Encounter Detection + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterTracker_H +#define PokemonAutomation_PokemonSwSh_EncounterTracker_H + +#include "CommonFramework/Language.h" +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/Options/EncounterFilter/PokemonSwSh_EncounterFilterOption.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class StandardEncounterDetection{ +public: + StandardEncounterDetection( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + const EncounterFilterOption2& filter, + ShinyType shininess, + std::chrono::milliseconds read_name_delay = std::chrono::milliseconds(500) + ); + + bool is_shiny() const; + ShinyType shininess() const{ return m_shininess; } + + // nullptr = disabled + // empty set = unable to detect + const std::set* candidates(); + + EncounterActionFull get_action(); + +private: + ProgramEnvironment& m_env; + VideoStream& m_stream; + ProControllerContext& m_context; + + const Language m_language; + + const EncounterFilterOption2& m_filter; + const ShinyType m_shininess; + const std::chrono::milliseconds m_read_name_delay; + + bool m_name_read = false; + std::set m_candidates; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.cpp index 052bf0e444..5f82b3d986 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.cpp @@ -1,319 +1,319 @@ -/* Encounter Handler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Exceptions/FatalProgramException.h" -#include "CommonFramework/Tools/ProgramEnvironment.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "CommonTools/VisualDetectors/BlackScreenDetector.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" -#include "PokemonSwSh_EncounterHandler.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void take_video(ProControllerContext& context){ - pbf_wait(context, 5 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); -// context->wait_for_all_requests(); -} -void run_away( - VideoStream& stream, ProControllerContext& context, - Milliseconds exit_battle_time -){ - pbf_press_dpad(context, DPAD_UP, 10, 0); - pbf_press_button(context, BUTTON_A, 250ms, 750ms); - - BlackScreenOverWatcher black_screen_detector; - StandardBattleMenuWatcher battle_menu(false, COLOR_GREEN); - while (true){ - context.wait_for_all_requests(); - int ret = run_until( - stream, context, - [exit_battle_time](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, exit_battle_time); - }, - { - black_screen_detector, - battle_menu, - } - ); - switch (ret){ - case 0: - context->logger().log("Detected end of battle!"); - return; - case 1: - context->logger().log("Detected unexpected battle menu!", COLOR_RED); - pbf_press_dpad(context, DPAD_DOWN, 3000ms, 0ms); - pbf_press_button(context, BUTTON_A, 80ms, 0ms); - continue; - default: - context->logger().log("Unable to detect end of battle. Assume successful run away.", COLOR_ORANGE); - return; -#if 0 - throw OperationFailedException( - ErrorReport::SEND_ERROR_REPORT, - "Unable to run away. Are you stuck in the battle?", - stream - ); -#endif - } - } -} - - - - -StandardEncounterHandler::StandardEncounterHandler( - ProgramEnvironment& env, - VideoStream& stream, ProControllerContext& context, - Language language, - EncounterBotCommonOptions& settings, - ShinyHuntTracker& session_stats -) - : m_env(env) - , m_context(context) - , m_stream(stream) - , m_language(language) - , m_settings(settings) - , m_session_stats(session_stats) -// , m_notification_sender(settings.notification_level) -{} - - -void StandardEncounterHandler::update_frequencies(StandardEncounterDetection& encounter){ - const std::set* slugs = encounter.candidates(); - if (slugs){ - m_frequencies += *slugs; - m_env.log(m_frequencies.dump_sorted_map("Encounter Stats:\n")); - } -} -void StandardEncounterHandler::run_away_and_update_stats( - StandardEncounterDetection& encounter, - Milliseconds exit_battle_time, - const ShinyDetectionResult& result -){ - // Read the name. - const std::set* candidates_ptr = encounter.candidates(); - - run_away(m_stream, m_context, exit_battle_time); - - update_frequencies(encounter); - - const std::set& candidates = candidates_ptr - ? *candidates_ptr - : std::set(); - send_encounter_notification( - m_env, - m_settings.NOTIFICATION_NONSHINY, - m_settings.NOTIFICATION_SHINY, - candidates_ptr, is_likely_shiny(result.shiny_type), - {{candidates, result.shiny_type}}, result.alpha, - result.get_best_screenshot(), - &m_frequencies - ); -} - - -bool StandardEncounterHandler::handle_standard_encounter(const ShinyDetectionResult& result){ - if (result.shiny_type == ShinyType::UNKNOWN){ - m_stream.log("Unable to determine result of battle.", COLOR_RED); - m_session_stats.add_error(); - m_consecutive_failures++; - if (m_consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "3 consecutive failed encounter detections.", - m_stream - ); - } - return false; - } - m_consecutive_failures = 0; - - m_session_stats += result.shiny_type; - m_env.update_stats(); - - if (result.shiny_type == ShinyType::UNKNOWN){ - pbf_mash_button(m_context, BUTTON_B, TICKS_PER_SECOND); - return false; - } - - StandardEncounterDetection encounter( - m_env, m_stream, m_context, - m_language, - m_settings.FILTER, - result.shiny_type - ); - - update_frequencies(encounter); - - const std::set* candidates_ptr = encounter.candidates(); - const std::set& candidates = candidates_ptr - ? *candidates_ptr - : std::set(); - send_encounter_notification( - m_env, - m_settings.NOTIFICATION_NONSHINY, - m_settings.NOTIFICATION_SHINY, - candidates_ptr, is_likely_shiny(result.shiny_type), - {{candidates, result.shiny_type}}, result.alpha, - result.get_best_screenshot(), - &m_frequencies - ); - - if (m_settings.VIDEO_ON_SHINY && encounter.is_shiny()){ - take_video(m_context); - } - - return encounter.get_action().action == EncounterAction::StopProgram; -} -bool StandardEncounterHandler::handle_standard_encounter_end_battle( - const ShinyDetectionResult& result, - Milliseconds exit_battle_time -){ - if (result.shiny_type == ShinyType::UNKNOWN){ - m_stream.log("Unable to determine result of battle.", COLOR_RED); - m_session_stats.add_error(); - m_consecutive_failures++; - if (m_consecutive_failures >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "3 consecutive failed encounter detections.", - m_stream - ); - } - return false; - } - m_consecutive_failures = 0; - - m_session_stats += result.shiny_type; - m_env.update_stats(); - - StandardEncounterDetection encounter( - m_env, m_stream, m_context, - m_language, - m_settings.FILTER, - result.shiny_type - ); - - if (m_settings.VIDEO_ON_SHINY && encounter.is_shiny()){ - take_video(m_context); - } - - EncounterActionFull action = encounter.get_action(); - -// cout << "action = " << (int)action.first << " : " << action.second << endl; - - // Fast run-away sequence to save time. - if (action.action == EncounterAction::RunAway){ - run_away_and_update_stats(encounter, exit_battle_time, result); - return false; - } - - update_frequencies(encounter); - const std::set* candidates_ptr = encounter.candidates(); - const std::set& candidates = candidates_ptr - ? *candidates_ptr - : std::set(); - send_encounter_notification( - m_env, - m_settings.NOTIFICATION_NONSHINY, - m_settings.NOTIFICATION_SHINY, - candidates_ptr, is_likely_shiny(result.shiny_type), - {{candidates, result.shiny_type}}, result.alpha, - result.get_best_screenshot(), - &m_frequencies - ); - - switch (action.action){ - case EncounterAction::StopProgram: - return true; - case EncounterAction::RunAway: - return false; - case EncounterAction::ThrowBalls:{ - CatchResults results = basic_catcher( - m_stream, m_context, - m_language, - action.pokeball_slug, - action.ball_limit - ); - send_catch_notification( - m_env, - m_settings.NOTIFICATION_CATCH_SUCCESS, - m_settings.NOTIFICATION_CATCH_FAILED, - encounter.candidates(), - action.pokeball_slug, - results.balls_used, - results.result - ); - switch (results.result){ - case CatchResult::POKEMON_CAUGHT: - case CatchResult::POKEMON_FAINTED: - break; - default: - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to recover from failed catch.", - m_stream - ); - } - return false; - } - case EncounterAction::ThrowBallsAndSave:{ - CatchResults results = basic_catcher( - m_stream, m_context, - m_language, - action.pokeball_slug, - action.ball_limit - ); - send_catch_notification( - m_env, - m_settings.NOTIFICATION_CATCH_SUCCESS, - m_settings.NOTIFICATION_CATCH_FAILED, - encounter.candidates(), - action.pokeball_slug, - results.balls_used, - results.result - ); - switch (results.result){ - case CatchResult::POKEMON_CAUGHT: - pbf_mash_button(m_context, BUTTON_B, 2 * TICKS_PER_SECOND); - pbf_press_button(m_context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); // Save game. - pbf_press_button(m_context, BUTTON_R, 20, 150); - pbf_press_button(m_context, BUTTON_A, 10, 500); - break; - case CatchResult::POKEMON_FAINTED: - pbf_mash_button(m_context, BUTTON_B, 2 * TICKS_PER_SECOND); - break; - default: - throw_and_log( - m_stream.logger(), ErrorReport::NO_ERROR_REPORT, - "Unable to recover from failed catch.", - m_stream - ); - } - return false; - } - } - - return false; -} - - - -} -} -} +/* Encounter Handler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Exceptions/FatalProgramException.h" +#include "CommonFramework/Tools/ProgramEnvironment.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "CommonTools/VisualDetectors/BlackScreenDetector.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BasicCatcher.h" +#include "PokemonSwSh_EncounterHandler.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void take_video(ProControllerContext& context){ + pbf_wait(context, 5 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_CAPTURE, 2 * TICKS_PER_SECOND, 5 * TICKS_PER_SECOND); +// context->wait_for_all_requests(); +} +void run_away( + VideoStream& stream, ProControllerContext& context, + Milliseconds exit_battle_time +){ + pbf_press_dpad(context, DPAD_UP, 10, 0); + pbf_press_button(context, BUTTON_A, 250ms, 750ms); + + BlackScreenOverWatcher black_screen_detector; + StandardBattleMenuWatcher battle_menu(false, COLOR_GREEN); + while (true){ + context.wait_for_all_requests(); + int ret = run_until( + stream, context, + [exit_battle_time](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, exit_battle_time); + }, + { + black_screen_detector, + battle_menu, + } + ); + switch (ret){ + case 0: + context->logger().log("Detected end of battle!"); + return; + case 1: + context->logger().log("Detected unexpected battle menu!", COLOR_RED); + pbf_press_dpad(context, DPAD_DOWN, 3000ms, 0ms); + pbf_press_button(context, BUTTON_A, 80ms, 0ms); + continue; + default: + context->logger().log("Unable to detect end of battle. Assume successful run away.", COLOR_ORANGE); + return; +#if 0 + throw OperationFailedException( + ErrorReport::SEND_ERROR_REPORT, + "Unable to run away. Are you stuck in the battle?", + stream + ); +#endif + } + } +} + + + + +StandardEncounterHandler::StandardEncounterHandler( + ProgramEnvironment& env, + VideoStream& stream, ProControllerContext& context, + Language language, + EncounterBotCommonOptions& settings, + ShinyHuntTracker& session_stats +) + : m_env(env) + , m_context(context) + , m_stream(stream) + , m_language(language) + , m_settings(settings) + , m_session_stats(session_stats) +// , m_notification_sender(settings.notification_level) +{} + + +void StandardEncounterHandler::update_frequencies(StandardEncounterDetection& encounter){ + const std::set* slugs = encounter.candidates(); + if (slugs){ + m_frequencies += *slugs; + m_env.log(m_frequencies.dump_sorted_map("Encounter Stats:\n")); + } +} +void StandardEncounterHandler::run_away_and_update_stats( + StandardEncounterDetection& encounter, + Milliseconds exit_battle_time, + const ShinyDetectionResult& result +){ + // Read the name. + const std::set* candidates_ptr = encounter.candidates(); + + run_away(m_stream, m_context, exit_battle_time); + + update_frequencies(encounter); + + const std::set& candidates = candidates_ptr + ? *candidates_ptr + : std::set(); + send_encounter_notification( + m_env, + m_settings.NOTIFICATION_NONSHINY, + m_settings.NOTIFICATION_SHINY, + candidates_ptr, is_likely_shiny(result.shiny_type), + {{candidates, result.shiny_type}}, result.alpha, + result.get_best_screenshot(), + &m_frequencies + ); +} + + +bool StandardEncounterHandler::handle_standard_encounter(const ShinyDetectionResult& result){ + if (result.shiny_type == ShinyType::UNKNOWN){ + m_stream.log("Unable to determine result of battle.", COLOR_RED); + m_session_stats.add_error(); + m_consecutive_failures++; + if (m_consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "3 consecutive failed encounter detections.", + m_stream + ); + } + return false; + } + m_consecutive_failures = 0; + + m_session_stats += result.shiny_type; + m_env.update_stats(); + + if (result.shiny_type == ShinyType::UNKNOWN){ + pbf_mash_button(m_context, BUTTON_B, TICKS_PER_SECOND); + return false; + } + + StandardEncounterDetection encounter( + m_env, m_stream, m_context, + m_language, + m_settings.FILTER, + result.shiny_type + ); + + update_frequencies(encounter); + + const std::set* candidates_ptr = encounter.candidates(); + const std::set& candidates = candidates_ptr + ? *candidates_ptr + : std::set(); + send_encounter_notification( + m_env, + m_settings.NOTIFICATION_NONSHINY, + m_settings.NOTIFICATION_SHINY, + candidates_ptr, is_likely_shiny(result.shiny_type), + {{candidates, result.shiny_type}}, result.alpha, + result.get_best_screenshot(), + &m_frequencies + ); + + if (m_settings.VIDEO_ON_SHINY && encounter.is_shiny()){ + take_video(m_context); + } + + return encounter.get_action().action == EncounterAction::StopProgram; +} +bool StandardEncounterHandler::handle_standard_encounter_end_battle( + const ShinyDetectionResult& result, + Milliseconds exit_battle_time +){ + if (result.shiny_type == ShinyType::UNKNOWN){ + m_stream.log("Unable to determine result of battle.", COLOR_RED); + m_session_stats.add_error(); + m_consecutive_failures++; + if (m_consecutive_failures >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "3 consecutive failed encounter detections.", + m_stream + ); + } + return false; + } + m_consecutive_failures = 0; + + m_session_stats += result.shiny_type; + m_env.update_stats(); + + StandardEncounterDetection encounter( + m_env, m_stream, m_context, + m_language, + m_settings.FILTER, + result.shiny_type + ); + + if (m_settings.VIDEO_ON_SHINY && encounter.is_shiny()){ + take_video(m_context); + } + + EncounterActionFull action = encounter.get_action(); + +// cout << "action = " << (int)action.first << " : " << action.second << endl; + + // Fast run-away sequence to save time. + if (action.action == EncounterAction::RunAway){ + run_away_and_update_stats(encounter, exit_battle_time, result); + return false; + } + + update_frequencies(encounter); + const std::set* candidates_ptr = encounter.candidates(); + const std::set& candidates = candidates_ptr + ? *candidates_ptr + : std::set(); + send_encounter_notification( + m_env, + m_settings.NOTIFICATION_NONSHINY, + m_settings.NOTIFICATION_SHINY, + candidates_ptr, is_likely_shiny(result.shiny_type), + {{candidates, result.shiny_type}}, result.alpha, + result.get_best_screenshot(), + &m_frequencies + ); + + switch (action.action){ + case EncounterAction::StopProgram: + return true; + case EncounterAction::RunAway: + return false; + case EncounterAction::ThrowBalls:{ + CatchResults results = basic_catcher( + m_stream, m_context, + m_language, + action.pokeball_slug, + action.ball_limit + ); + send_catch_notification( + m_env, + m_settings.NOTIFICATION_CATCH_SUCCESS, + m_settings.NOTIFICATION_CATCH_FAILED, + encounter.candidates(), + action.pokeball_slug, + results.balls_used, + results.result + ); + switch (results.result){ + case CatchResult::POKEMON_CAUGHT: + case CatchResult::POKEMON_FAINTED: + break; + default: + throw_and_log( + m_stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to recover from failed catch.", + m_stream + ); + } + return false; + } + case EncounterAction::ThrowBallsAndSave:{ + CatchResults results = basic_catcher( + m_stream, m_context, + m_language, + action.pokeball_slug, + action.ball_limit + ); + send_catch_notification( + m_env, + m_settings.NOTIFICATION_CATCH_SUCCESS, + m_settings.NOTIFICATION_CATCH_FAILED, + encounter.candidates(), + action.pokeball_slug, + results.balls_used, + results.result + ); + switch (results.result){ + case CatchResult::POKEMON_CAUGHT: + pbf_mash_button(m_context, BUTTON_B, 2 * TICKS_PER_SECOND); + pbf_press_button(m_context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); // Save game. + pbf_press_button(m_context, BUTTON_R, 20, 150); + pbf_press_button(m_context, BUTTON_A, 10, 500); + break; + case CatchResult::POKEMON_FAINTED: + pbf_mash_button(m_context, BUTTON_B, 2 * TICKS_PER_SECOND); + break; + default: + throw_and_log( + m_stream.logger(), ErrorReport::NO_ERROR_REPORT, + "Unable to recover from failed catch.", + m_stream + ); + } + return false; + } + } + + return false; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h index 97263fb762..5a55e4c387 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h @@ -1,73 +1,73 @@ -/* Encounter Handler - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_EncounterHandler_H -#define PokemonAutomation_PokemonSwSh_EncounterHandler_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_EncounterStats.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class StandardEncounterHandler{ -public: - StandardEncounterHandler( - ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, - Language language, - EncounterBotCommonOptions& settings, - ShinyHuntTracker& session_stats - ); - - - // Return true if program should stop. - bool handle_standard_encounter(const ShinyDetectionResult& result); - bool handle_standard_encounter_end_battle( - const ShinyDetectionResult& result, - Milliseconds exit_battle_time - ); - - -private: - void update_frequencies(StandardEncounterDetection& encounter); - void run_away_and_update_stats( - StandardEncounterDetection& encounter, - Milliseconds exit_battle_time, - const ShinyDetectionResult& result - ); - -private: - ProgramEnvironment& m_env; - ProControllerContext& m_context; - VideoStream& m_stream; - const Language m_language; - EncounterBotCommonOptions& m_settings; - - EncounterFrequencies m_frequencies; - ShinyHuntTracker& m_session_stats; - size_t m_consecutive_failures = 0; - -// EncounterNotificationSender m_notification_sender; -}; - - -void take_video(ProControllerContext& context); -void run_away( - VideoStream& stream, ProControllerContext& context, - Milliseconds exit_battle_time -); - - -} -} -} -#endif +/* Encounter Handler + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_EncounterHandler_H +#define PokemonAutomation_PokemonSwSh_EncounterHandler_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_EncounterStats.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterDetection.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class StandardEncounterHandler{ +public: + StandardEncounterHandler( + ProgramEnvironment& env, VideoStream& stream, ProControllerContext& context, + Language language, + EncounterBotCommonOptions& settings, + ShinyHuntTracker& session_stats + ); + + + // Return true if program should stop. + bool handle_standard_encounter(const ShinyDetectionResult& result); + bool handle_standard_encounter_end_battle( + const ShinyDetectionResult& result, + Milliseconds exit_battle_time + ); + + +private: + void update_frequencies(StandardEncounterDetection& encounter); + void run_away_and_update_stats( + StandardEncounterDetection& encounter, + Milliseconds exit_battle_time, + const ShinyDetectionResult& result + ); + +private: + ProgramEnvironment& m_env; + ProControllerContext& m_context; + VideoStream& m_stream; + const Language m_language; + EncounterBotCommonOptions& m_settings; + + EncounterFrequencies m_frequencies; + ShinyHuntTracker& m_session_stats; + size_t m_consecutive_failures = 0; + +// EncounterNotificationSender m_notification_sender; +}; + + +void take_video(ProControllerContext& context); +void run_away( + VideoStream& stream, ProControllerContext& context, + Milliseconds exit_battle_time +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.cpp index 4d5e4a0ef8..c05cd382d7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.cpp @@ -1,189 +1,189 @@ -/* Start Game - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/InferenceThrottler.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh_GameEntry.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -void resume_game_no_interact( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu -){ - bool video_available = (bool)console.video().snapshot(); - if (video_available){ - resume_game_from_home(console, context); - }else{ - resume_game_no_interact_old(context, tolerate_update_menu); - } -} -void resume_game_back_out( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, uint16_t mash_B_time -){ - bool video_available = (bool)console.video().snapshot(); - if (video_available){ - resume_game_from_home(console, context); - }else{ - resume_game_back_out_old(context, tolerate_update_menu, mash_B_time); - } -} - - - - -void enter_loading_game( - VideoStream& stream, ProControllerContext& context, - bool backup_save, - uint16_t post_wait_time -){ - openedgame_to_gamemenu(stream, context, GameSettings::instance().START_GAME_WAIT0); - - stream.log("enter_loading_game(): Game Loaded. Entering game...", COLOR_PURPLE); - enter_game(context, backup_save, GameSettings::instance().ENTER_GAME_MASH0, 0ms); - context.wait_for_all_requests(); - - // Wait to enter game. - { - Milliseconds timeout = GameSettings::instance().ENTER_GAME_WAIT0; - - OverlayBoxScope box(stream.overlay(), {0.2, 0.2, 0.6, 0.6}); - - bool black_found = false; - - InferenceThrottler throttler(timeout); - while (true){ - context.throw_if_cancelled(); - - VideoSnapshot screen = stream.video().snapshot(); - if (!screen){ - stream.log("enter_loading_game(): Screenshot failed.", COLOR_PURPLE); - throttler.set_period(std::chrono::milliseconds(1000)); - }else{ - bool black = is_black(extract_box_reference(screen, box)); - if (black){ - if (!black_found){ - stream.log("enter_loading_game(): Game entry started.", COLOR_PURPLE); - } - black_found = true; - }else if (black_found){ - break; - } - } - - if (throttler.end_iteration(context)){ - stream.log("enter_loading_game(): Game entry timed out. Proceeding with default start delay.", COLOR_RED); - break; - } - } - } - stream.log("start_game_with_inference(): Game started.", COLOR_PURPLE); - - if (post_wait_time != 0){ - pbf_wait(context, post_wait_time); - } -} - -void start_game_from_home_with_inference( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot, - uint8_t user_slot, - bool backup_save, - uint16_t post_wait_time -){ - NintendoSwitch::start_game_from_home( - console, - context, - tolerate_update_menu, - game_slot, - user_slot, - GameSettings::instance().START_GAME_MASH0 - ); - - // Wait for game to load. - enter_loading_game(console, context, backup_save, post_wait_time); -} - - -void reset_game_from_home_with_inference( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - bool backup_save, - uint16_t post_wait_time -){ - bool video_available = (bool)console.video().snapshot(); - if (video_available || - ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || - tolerate_update_menu - ){ -// cout << "close game" << endl; - close_game(console, context); -// cout << "start_game_from_home_with_inference game" << endl; - start_game_from_home_with_inference( - console, context, tolerate_update_menu, 0, 0, backup_save, post_wait_time - ); - return; - } - - fast_reset_game(context, GameSettings::instance().START_GAME_MASH0, 0ms, 0ms, 0ms); - context.wait_for_all_requests(); - - // Wait for game to load. - enter_loading_game(console, context, backup_save, post_wait_time); -} - - -void start_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot, - uint8_t user_slot, - bool backup_save, - uint16_t post_wait_time -){ - bool video_available = (bool)console.video().snapshot(); - if (video_available || - ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || - tolerate_update_menu - ){ -// cout << "close game" << endl; - close_game(console, context); -// cout << "start_game_from_home_with_inference game" << endl; - start_game_from_home_with_inference( - console, context, tolerate_update_menu, game_slot, user_slot, backup_save, post_wait_time - ); - return; - } - - fast_reset_game(context, GameSettings::instance().START_GAME_MASH0, 0ms, 0ms, 0ms); - context.wait_for_all_requests(); - - // Wait for game to load. - enter_loading_game(console, context, backup_save, post_wait_time); -} - - -} -} -} +/* Start Game + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/VideoPipeline/VideoOverlayScopes.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/InferenceThrottler.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh_GameEntry.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +void resume_game_no_interact( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu +){ + bool video_available = (bool)console.video().snapshot(); + if (video_available){ + resume_game_from_home(console, context); + }else{ + resume_game_no_interact_old(context, tolerate_update_menu); + } +} +void resume_game_back_out( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, uint16_t mash_B_time +){ + bool video_available = (bool)console.video().snapshot(); + if (video_available){ + resume_game_from_home(console, context); + }else{ + resume_game_back_out_old(context, tolerate_update_menu, mash_B_time); + } +} + + + + +void enter_loading_game( + VideoStream& stream, ProControllerContext& context, + bool backup_save, + uint16_t post_wait_time +){ + openedgame_to_gamemenu(stream, context, GameSettings::instance().START_GAME_WAIT0); + + stream.log("enter_loading_game(): Game Loaded. Entering game...", COLOR_PURPLE); + enter_game(context, backup_save, GameSettings::instance().ENTER_GAME_MASH0, 0ms); + context.wait_for_all_requests(); + + // Wait to enter game. + { + Milliseconds timeout = GameSettings::instance().ENTER_GAME_WAIT0; + + OverlayBoxScope box(stream.overlay(), {0.2, 0.2, 0.6, 0.6}); + + bool black_found = false; + + InferenceThrottler throttler(timeout); + while (true){ + context.throw_if_cancelled(); + + VideoSnapshot screen = stream.video().snapshot(); + if (!screen){ + stream.log("enter_loading_game(): Screenshot failed.", COLOR_PURPLE); + throttler.set_period(std::chrono::milliseconds(1000)); + }else{ + bool black = is_black(extract_box_reference(screen, box)); + if (black){ + if (!black_found){ + stream.log("enter_loading_game(): Game entry started.", COLOR_PURPLE); + } + black_found = true; + }else if (black_found){ + break; + } + } + + if (throttler.end_iteration(context)){ + stream.log("enter_loading_game(): Game entry timed out. Proceeding with default start delay.", COLOR_RED); + break; + } + } + } + stream.log("start_game_with_inference(): Game started.", COLOR_PURPLE); + + if (post_wait_time != 0){ + pbf_wait(context, post_wait_time); + } +} + +void start_game_from_home_with_inference( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot, + uint8_t user_slot, + bool backup_save, + uint16_t post_wait_time +){ + NintendoSwitch::start_game_from_home( + console, + context, + tolerate_update_menu, + game_slot, + user_slot, + GameSettings::instance().START_GAME_MASH0 + ); + + // Wait for game to load. + enter_loading_game(console, context, backup_save, post_wait_time); +} + + +void reset_game_from_home_with_inference( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + bool backup_save, + uint16_t post_wait_time +){ + bool video_available = (bool)console.video().snapshot(); + if (video_available || + ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || + tolerate_update_menu + ){ +// cout << "close game" << endl; + close_game(console, context); +// cout << "start_game_from_home_with_inference game" << endl; + start_game_from_home_with_inference( + console, context, tolerate_update_menu, 0, 0, backup_save, post_wait_time + ); + return; + } + + fast_reset_game(context, GameSettings::instance().START_GAME_MASH0, 0ms, 0ms, 0ms); + context.wait_for_all_requests(); + + // Wait for game to load. + enter_loading_game(console, context, backup_save, post_wait_time); +} + + +void start_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot, + uint8_t user_slot, + bool backup_save, + uint16_t post_wait_time +){ + bool video_available = (bool)console.video().snapshot(); + if (video_available || + ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET || + tolerate_update_menu + ){ +// cout << "close game" << endl; + close_game(console, context); +// cout << "start_game_from_home_with_inference game" << endl; + start_game_from_home_with_inference( + console, context, tolerate_update_menu, game_slot, user_slot, backup_save, post_wait_time + ); + return; + } + + fast_reset_game(context, GameSettings::instance().START_GAME_MASH0, 0ms, 0ms, 0ms); + context.wait_for_all_requests(); + + // Wait for game to load. + enter_loading_game(console, context, backup_save, post_wait_time); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.h index ae10494a7e..9348ea8ac6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_GameEntry.h @@ -1,63 +1,63 @@ -/* Start Game - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_StartGame_H -#define PokemonAutomation_PokemonSwSh_StartGame_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void resume_game_no_interact( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu -); -void resume_game_back_out( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, uint16_t mash_B_time -); - - - -// Start the game with the specified "game_slot" and "user_slot". -// If "game_slot" is zero, it uses whatever the cursor is on. -// If "user_slot" is zero, it uses whatever the cursor is on. -void start_game_from_home_with_inference( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot = 0, - uint8_t user_slot = 0, - bool backup_save = false, - uint16_t post_wait_time = 1 * TICKS_PER_SECOND -); - -void reset_game_from_home_with_inference( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - bool backup_save = false, - uint16_t post_wait_time = 1 * TICKS_PER_SECOND -); - -void start_game_from_home( - ConsoleHandle& console, ProControllerContext& context, - bool tolerate_update_menu, - uint8_t game_slot = 0, - uint8_t user_slot = 0, - bool backup_save = false, - uint16_t post_wait_time = 1 * TICKS_PER_SECOND -); - - - -} -} -} -#endif +/* Start Game + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_StartGame_H +#define PokemonAutomation_PokemonSwSh_StartGame_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void resume_game_no_interact( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu +); +void resume_game_back_out( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, uint16_t mash_B_time +); + + + +// Start the game with the specified "game_slot" and "user_slot". +// If "game_slot" is zero, it uses whatever the cursor is on. +// If "user_slot" is zero, it uses whatever the cursor is on. +void start_game_from_home_with_inference( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot = 0, + uint8_t user_slot = 0, + bool backup_save = false, + uint16_t post_wait_time = 1 * TICKS_PER_SECOND +); + +void reset_game_from_home_with_inference( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + bool backup_save = false, + uint16_t post_wait_time = 1 * TICKS_PER_SECOND +); + +void start_game_from_home( + ConsoleHandle& console, ProControllerContext& context, + bool tolerate_update_menu, + uint8_t game_slot = 0, + uint8_t user_slot = 0, + bool backup_save = false, + uint16_t post_wait_time = 1 * TICKS_PER_SECOND +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.cpp index bc03594431..b3ee731127 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.cpp @@ -1,84 +1,84 @@ -/* Internet - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Notifications/ProgramInfo.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" -#include "PokemonSwSh_Internet.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -bool connect_to_internet_with_inference( - VideoStream& stream, ProControllerContext& context, - Milliseconds post_wait_time, - Milliseconds timeout_ticks -){ - stream.log("Connecting to internet..."); - // Enter Y-COMM. - bool ok = true; -// cout << "Waiting for Y-COMM to open..." << endl; - { - YCommMenuDetector detector(true); - if (!detector.detect(stream.video().snapshot())){ - pbf_press_button(context, BUTTON_Y, 10, TICKS_PER_SECOND); - context.wait_for_all_requests(); - } - int result = wait_until( - stream, context, - std::chrono::seconds(10), - {{detector}} - ); - if (result == 0){ - stream.log("Y-COMM detected."); - }else{ - stream.log("Failed to detect Y-COMM after timeout.", COLOR_RED); - dump_image(stream.logger(), ProgramInfo(), "connect_to_internet_with_inference", stream.video().snapshot()); - ok = false; - } - } - - // Connect to internet. - context.wait_for(std::chrono::seconds(1)); - pbf_press_dpad(context, DPAD_UP, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_mash_button(context, BUTTON_PLUS, TICKS_PER_SECOND); - context.wait_for_all_requests(); - -// cout << "Waiting for Y-COMM to close..." << endl; - // Mash B until you leave Y-COMM. - { - YCommMenuDetector detector(false); - int result = run_until( - stream, context, - [&](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_B, timeout_ticks); - }, - {{detector}} - ); - if (result == 0){ - stream.log("Y-COMM no longer detected. Assume done connected to internet."); - }else{ - stream.log("Failed to see Y-COMM go away after timeout.", COLOR_RED); - ok = false; - } - } - - // Extra wait. - context.wait_for(post_wait_time); - - return ok; -} - - -} -} -} +/* Internet + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Notifications/ProgramInfo.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" +#include "PokemonSwSh_Internet.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +bool connect_to_internet_with_inference( + VideoStream& stream, ProControllerContext& context, + Milliseconds post_wait_time, + Milliseconds timeout_ticks +){ + stream.log("Connecting to internet..."); + // Enter Y-COMM. + bool ok = true; +// cout << "Waiting for Y-COMM to open..." << endl; + { + YCommMenuDetector detector(true); + if (!detector.detect(stream.video().snapshot())){ + pbf_press_button(context, BUTTON_Y, 10, TICKS_PER_SECOND); + context.wait_for_all_requests(); + } + int result = wait_until( + stream, context, + std::chrono::seconds(10), + {{detector}} + ); + if (result == 0){ + stream.log("Y-COMM detected."); + }else{ + stream.log("Failed to detect Y-COMM after timeout.", COLOR_RED); + dump_image(stream.logger(), ProgramInfo(), "connect_to_internet_with_inference", stream.video().snapshot()); + ok = false; + } + } + + // Connect to internet. + context.wait_for(std::chrono::seconds(1)); + pbf_press_dpad(context, DPAD_UP, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_mash_button(context, BUTTON_PLUS, TICKS_PER_SECOND); + context.wait_for_all_requests(); + +// cout << "Waiting for Y-COMM to close..." << endl; + // Mash B until you leave Y-COMM. + { + YCommMenuDetector detector(false); + int result = run_until( + stream, context, + [&](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_B, timeout_ticks); + }, + {{detector}} + ); + if (result == 0){ + stream.log("Y-COMM no longer detected. Assume done connected to internet."); + }else{ + stream.log("Failed to see Y-COMM go away after timeout.", COLOR_RED); + ok = false; + } + } + + // Extra wait. + context.wait_for(post_wait_time); + + return ok; +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.h index df1b42ed5a..8d5ab1fe83 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_Internet.h @@ -1,33 +1,33 @@ -/* Internet - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_Internet_H -#define PokemonAutomation_PokemonSwSh_Internet_H - -#include -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace std::chrono_literals; - - -bool connect_to_internet_with_inference( - VideoStream& stream, ProControllerContext& context, - Milliseconds post_wait_time = 3000ms, - Milliseconds timeout_ticks = 120s -); - - - -} -} -} -#endif +/* Internet + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_Internet_H +#define PokemonAutomation_PokemonSwSh_Internet_H + +#include +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace std::chrono_literals; + + +bool connect_to_internet_with_inference( + VideoStream& stream, ProControllerContext& context, + Milliseconds post_wait_time = 3000ms, + Milliseconds timeout_ticks = 120s +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.cpp index fec51ef325..168524ba45 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.cpp @@ -1,66 +1,66 @@ -/* Start Game - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Tools/ErrorDumper.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" -#include "PokemonSwSh_MenuNavigation.h" -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void navigate_to_menu_app( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - size_t target_app_index, - EventNotificationOption& notification_option -){ - context.wait_for_all_requests(); - RotomPhoneMenuArrowFinder menu_arrow_detector(stream.overlay()); - auto snapshot = stream.video().snapshot(); - const int cur_app_index = menu_arrow_detector.detect(snapshot); - if (cur_app_index < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect Rotom phone menu.", - stream, - std::move(snapshot) - ); - } - stream.log("Detect menu cursor at " + std::to_string(cur_app_index) + "."); - - const int cur_row = cur_app_index / 5; - const int cur_col = cur_app_index % 5; - - const int target_row = (int)target_app_index / 5; - const int target_col = (int)target_app_index % 5; - - const DpadPosition dir = (cur_col < target_col ? DPAD_RIGHT : DPAD_LEFT); - const int steps = std::abs(cur_col - target_col); - for(int i = 0; i < steps; i++){ - box_scroll(context, dir); - } - - if (cur_row < target_row){ - box_scroll(context, DPAD_DOWN); - }else if (cur_row > target_row){ - box_scroll(context, DPAD_UP); - } - - context.wait_for_all_requests(); - return; -} - - - -} -} -} +/* Start Game + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Tools/ErrorDumper.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Programs/PokemonSwSh_BoxHelpers.h" +#include "PokemonSwSh_MenuNavigation.h" +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void navigate_to_menu_app( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + size_t target_app_index, + EventNotificationOption& notification_option +){ + context.wait_for_all_requests(); + RotomPhoneMenuArrowFinder menu_arrow_detector(stream.overlay()); + auto snapshot = stream.video().snapshot(); + const int cur_app_index = menu_arrow_detector.detect(snapshot); + if (cur_app_index < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect Rotom phone menu.", + stream, + std::move(snapshot) + ); + } + stream.log("Detect menu cursor at " + std::to_string(cur_app_index) + "."); + + const int cur_row = cur_app_index / 5; + const int cur_col = cur_app_index % 5; + + const int target_row = (int)target_app_index / 5; + const int target_col = (int)target_app_index % 5; + + const DpadPosition dir = (cur_col < target_col ? DPAD_RIGHT : DPAD_LEFT); + const int steps = std::abs(cur_col - target_col); + for(int i = 0; i < steps; i++){ + box_scroll(context, dir); + } + + if (cur_row < target_row){ + box_scroll(context, DPAD_DOWN); + }else if (cur_row > target_row){ + box_scroll(context, DPAD_UP); + } + + context.wait_for_all_requests(); + return; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h index 2c62bbc02c..bb436c0b48 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h @@ -1,36 +1,36 @@ -/* Menu Navigation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MenuNavigation_H -#define PokemonAutomation_PokemonSwSh_MenuNavigation_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" - -namespace PokemonAutomation{ - class EventNotificationOption; - class ProgramEnvironment; -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -// When Rotom Phone menu is opened, move the cursor to the target app. -// The target app index is from 0 to 9, in the order of top to bottom, left to right. -// e.g. by default, Pokemon app is at index 1, while Town Map app is at index 5. -// The function detects the current cursor location. So the function works on any initial cursor location. -// Will OperationFailedException::fire when failed to detect menu -void navigate_to_menu_app( - ProgramEnvironment& env, - VideoStream& stream, - ProControllerContext& context, - size_t app_index, - EventNotificationOption& notification_option -); - - -} -} -} -#endif +/* Menu Navigation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MenuNavigation_H +#define PokemonAutomation_PokemonSwSh_MenuNavigation_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" + +namespace PokemonAutomation{ + class EventNotificationOption; + class ProgramEnvironment; +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +// When Rotom Phone menu is opened, move the cursor to the target app. +// The target app index is from 0 to 9, in the order of top to bottom, left to right. +// e.g. by default, Pokemon app is at index 1, while Town Map app is at index 5. +// The function detects the current cursor location. So the function works on any initial cursor location. +// Will OperationFailedException::fire when failed to detect menu +void navigate_to_menu_app( + ProgramEnvironment& env, + VideoStream& stream, + ProControllerContext& context, + size_t app_index, + EventNotificationOption& notification_option +); + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.cpp index 631920ffdd..9382c013cb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.cpp @@ -1,212 +1,212 @@ -/* OHKO Raid Farmer - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h" -#include "PokemonSwSh_RaidItemFarmerOKHO.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -RaidItemFarmerOHKO_Descriptor::RaidItemFarmerOHKO_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSwSh:RaidItemFarmerOHKO", - STRING_POKEMON + " SwSh", "Raid Item Farmer (OHKO)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/RaidItemFarmerOHKO.md", - "Farm items from raids that can be OHKO'ed. (requires multiple Switches)", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, - FasterIfTickPrecise::NOT_FASTER, - 2, 4, 2 - ) -{} - - - -RaidItemFarmerOHKO::RaidItemFarmerOHKO() - : BACKUP_SAVE( - "Load Backup Save:
For backup save soft-locking method.", - LockMode::LOCK_WHILE_RUNNING, - false - ) -// , m_advanced_options( -// "Advanced Options: You should not need to touch anything below here." -// ) - , WAIT_FOR_STAMP_DELAY0( - "Wait for Stamp Delay:
Wait this long for the stamp to show up.", - LockMode::LOCK_WHILE_RUNNING, - "3000 ms" - ) - , ENTER_STAMP_MASH_DURATION0( - "Enter Stamp Mash Duration:
Mash A this long to enter a raid from its stamp.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) - , RAID_START_MASH_DURATION0( - "Raid Start Mash Duration:
Mash A this long to start raid.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) - , RAID_START_TO_ATTACK_DELAY0( - "Raid Start to Attack Delay:
Time from start raid to when the raiders attack.
" - "Do not over-optimize this timing unless you are running with 4 Switches. The Wishiwashi NPC will break the program.", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) - , ATTACK_TO_CATCH_DELAY0( - "Attack to Catch Delay:
Time from when you attack to when the catch selection appears.
" - "Do not over-optimize this timing unless you are running with 4 Switches. The Clefairy NPC's Follow Me will break the program.", - LockMode::LOCK_WHILE_RUNNING, - "18 s" - ) - , RETURN_TO_OVERWORLD_DELAY0( - "Return to Overworld Delay:
Time from when you don't catch to when you return to the overworld.", - LockMode::LOCK_WHILE_RUNNING, - "18 s" - ) - , TOUCH_DATE_INTERVAL0( - "Rollover Prevention:
Prevent the den from rolling over by periodically touching the date. If set to zero, this feature is disabled.", - LockMode::LOCK_WHILE_RUNNING, - "4 hours" - ) -{ - PA_ADD_OPTION(BACKUP_SAVE); -// PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(WAIT_FOR_STAMP_DELAY0); - PA_ADD_OPTION(ENTER_STAMP_MASH_DURATION0); - PA_ADD_OPTION(RAID_START_MASH_DURATION0); - PA_ADD_OPTION(RAID_START_TO_ATTACK_DELAY0); - PA_ADD_OPTION(ATTACK_TO_CATCH_DELAY0); - PA_ADD_OPTION(RETURN_TO_OVERWORLD_DELAY0); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL0); -} - -void RaidItemFarmerOHKO::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - ProControllerContext host(scope, env.consoles[0].pro_controller()); - size_t switches = env.consoles.size(); - - WallDuration TOUCH_DATE_INTERVAL = TOUCH_DATE_INTERVAL0; - - env.run_in_parallel( - scope, - [](ConsoleHandle& console, ProControllerContext& context){ - grip_menu_connect_go_home(context); - } - ); - - WallClock last_touch = current_time(); - if (TOUCH_DATE_INTERVAL > 0ms){ - touch_date_from_home(env.consoles[0], host, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - last_touch = current_time(); - } - env.run_in_parallel( - scope, - [](ConsoleHandle& console, ProControllerContext& context){ - if (console.index() == 0){ - resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - }else{ - resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); - } - } - ); - - - for (uint32_t raids = 0;; raids++){ - env.log("Raids Completed: " + tostr_u_commas(raids)); - - host.wait_for_all_requests(); - env.run_in_parallel( - scope, - [&](ConsoleHandle& console, ProControllerContext& context){ - if (console.index() == 0){ - enter_den(context, 0ms, false, false); - }else{ - pbf_press_button(context, BUTTON_Y, 80ms, GameSettings::instance().OPEN_YCOMM_DELAY0); - pbf_press_dpad(context, DPAD_UP, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_press_button(context, BUTTON_X, 10, 10); - } - } - ); - - enter_lobby(host, 0ms, false, Catchability::ALWAYS_CATCHABLE); - - host.wait_for_all_requests(); - env.run_in_parallel( - scope, 1, switches, - [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_wait(context, WAIT_FOR_STAMP_DELAY0); - pbf_press_button(context, BUTTON_X, 10, 10); - pbf_press_dpad(context, DPAD_RIGHT, 10, 10); - pbf_mash_button(context, BUTTON_A, ENTER_STAMP_MASH_DURATION0); - } - ); - - // Start Raid - pbf_press_dpad(host, DPAD_UP, 5, 45); - - host.wait_for_all_requests(); - env.run_in_parallel( - scope, - [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, RAID_START_MASH_DURATION0); - pbf_wait(context, RAID_START_TO_ATTACK_DELAY0); - pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); - pbf_wait(context, ATTACK_TO_CATCH_DELAY0); - - if (console.index() == 0){ - // Add a little extra wait time since correctness matters here. - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - - close_game(console, context); - - // Touch the date. - if (TOUCH_DATE_INTERVAL > 0ms && current_time() - last_touch >= TOUCH_DATE_INTERVAL){ - touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - last_touch += TOUCH_DATE_INTERVAL; - } - start_game_from_home_with_inference( - console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, - 0, 0, - BACKUP_SAVE - ); - }else{ - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - Milliseconds delay = RETURN_TO_OVERWORLD_DELAY0; - if (delay > 5000ms){ - pbf_mash_button(context, BUTTON_A, delay - 5000ms); - pbf_mash_button(context, BUTTON_B, 5000ms); - }else{ - pbf_mash_button(context, BUTTON_A, delay); - } - } - } - ); - - - } - -} - - - -} -} -} +/* OHKO Raid Farmer + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +//#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Device.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/Hosting/PokemonSwSh_DenTools.h" +#include "PokemonSwSh_RaidItemFarmerOKHO.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +RaidItemFarmerOHKO_Descriptor::RaidItemFarmerOHKO_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSwSh:RaidItemFarmerOHKO", + STRING_POKEMON + " SwSh", "Raid Item Farmer (OHKO)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/RaidItemFarmerOHKO.md", + "Farm items from raids that can be OHKO'ed. (requires multiple Switches)", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS}, + FasterIfTickPrecise::NOT_FASTER, + 2, 4, 2 + ) +{} + + + +RaidItemFarmerOHKO::RaidItemFarmerOHKO() + : BACKUP_SAVE( + "Load Backup Save:
For backup save soft-locking method.", + LockMode::LOCK_WHILE_RUNNING, + false + ) +// , m_advanced_options( +// "Advanced Options: You should not need to touch anything below here." +// ) + , WAIT_FOR_STAMP_DELAY0( + "Wait for Stamp Delay:
Wait this long for the stamp to show up.", + LockMode::LOCK_WHILE_RUNNING, + "3000 ms" + ) + , ENTER_STAMP_MASH_DURATION0( + "Enter Stamp Mash Duration:
Mash A this long to enter a raid from its stamp.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) + , RAID_START_MASH_DURATION0( + "Raid Start Mash Duration:
Mash A this long to start raid.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) + , RAID_START_TO_ATTACK_DELAY0( + "Raid Start to Attack Delay:
Time from start raid to when the raiders attack.
" + "Do not over-optimize this timing unless you are running with 4 Switches. The Wishiwashi NPC will break the program.", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) + , ATTACK_TO_CATCH_DELAY0( + "Attack to Catch Delay:
Time from when you attack to when the catch selection appears.
" + "Do not over-optimize this timing unless you are running with 4 Switches. The Clefairy NPC's Follow Me will break the program.", + LockMode::LOCK_WHILE_RUNNING, + "18 s" + ) + , RETURN_TO_OVERWORLD_DELAY0( + "Return to Overworld Delay:
Time from when you don't catch to when you return to the overworld.", + LockMode::LOCK_WHILE_RUNNING, + "18 s" + ) + , TOUCH_DATE_INTERVAL0( + "Rollover Prevention:
Prevent the den from rolling over by periodically touching the date. If set to zero, this feature is disabled.", + LockMode::LOCK_WHILE_RUNNING, + "4 hours" + ) +{ + PA_ADD_OPTION(BACKUP_SAVE); +// PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(WAIT_FOR_STAMP_DELAY0); + PA_ADD_OPTION(ENTER_STAMP_MASH_DURATION0); + PA_ADD_OPTION(RAID_START_MASH_DURATION0); + PA_ADD_OPTION(RAID_START_TO_ATTACK_DELAY0); + PA_ADD_OPTION(ATTACK_TO_CATCH_DELAY0); + PA_ADD_OPTION(RETURN_TO_OVERWORLD_DELAY0); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL0); +} + +void RaidItemFarmerOHKO::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + ProControllerContext host(scope, env.consoles[0].pro_controller()); + size_t switches = env.consoles.size(); + + WallDuration TOUCH_DATE_INTERVAL = TOUCH_DATE_INTERVAL0; + + env.run_in_parallel( + scope, + [](ConsoleHandle& console, ProControllerContext& context){ + grip_menu_connect_go_home(context); + } + ); + + WallClock last_touch = current_time(); + if (TOUCH_DATE_INTERVAL > 0ms){ + touch_date_from_home(env.consoles[0], host, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + last_touch = current_time(); + } + env.run_in_parallel( + scope, + [](ConsoleHandle& console, ProControllerContext& context){ + if (console.index() == 0){ + resume_game_front_of_den_nowatts(context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + }else{ + resume_game_no_interact(console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW); + } + } + ); + + + for (uint32_t raids = 0;; raids++){ + env.log("Raids Completed: " + tostr_u_commas(raids)); + + host.wait_for_all_requests(); + env.run_in_parallel( + scope, + [&](ConsoleHandle& console, ProControllerContext& context){ + if (console.index() == 0){ + enter_den(context, 0ms, false, false); + }else{ + pbf_press_button(context, BUTTON_Y, 80ms, GameSettings::instance().OPEN_YCOMM_DELAY0); + pbf_press_dpad(context, DPAD_UP, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_press_button(context, BUTTON_X, 10, 10); + } + } + ); + + enter_lobby(host, 0ms, false, Catchability::ALWAYS_CATCHABLE); + + host.wait_for_all_requests(); + env.run_in_parallel( + scope, 1, switches, + [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_wait(context, WAIT_FOR_STAMP_DELAY0); + pbf_press_button(context, BUTTON_X, 10, 10); + pbf_press_dpad(context, DPAD_RIGHT, 10, 10); + pbf_mash_button(context, BUTTON_A, ENTER_STAMP_MASH_DURATION0); + } + ); + + // Start Raid + pbf_press_dpad(host, DPAD_UP, 5, 45); + + host.wait_for_all_requests(); + env.run_in_parallel( + scope, + [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, RAID_START_MASH_DURATION0); + pbf_wait(context, RAID_START_TO_ATTACK_DELAY0); + pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); + pbf_wait(context, ATTACK_TO_CATCH_DELAY0); + + if (console.index() == 0){ + // Add a little extra wait time since correctness matters here. + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + + close_game(console, context); + + // Touch the date. + if (TOUCH_DATE_INTERVAL > 0ms && current_time() - last_touch >= TOUCH_DATE_INTERVAL){ + touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + last_touch += TOUCH_DATE_INTERVAL; + } + start_game_from_home_with_inference( + console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_SLOW, + 0, 0, + BACKUP_SAVE + ); + }else{ + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + Milliseconds delay = RETURN_TO_OVERWORLD_DELAY0; + if (delay > 5000ms){ + pbf_mash_button(context, BUTTON_A, delay - 5000ms); + pbf_mash_button(context, BUTTON_B, 5000ms); + }else{ + pbf_mash_button(context, BUTTON_A, delay); + } + } + } + ); + + + } + +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.h index 1699b7f4d2..9b9352f1f2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_RaidItemFarmerOKHO.h @@ -1,50 +1,50 @@ -/* Raid Item Farmer (OHKO) - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_RaidItemFarmerOHKO_H -#define PokemonAutomation_PokemonSwSh_RaidItemFarmerOHKO_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class RaidItemFarmerOHKO_Descriptor : public MultiSwitchProgramDescriptor{ -public: - RaidItemFarmerOHKO_Descriptor(); -}; - - - -class RaidItemFarmerOHKO : public MultiSwitchProgramInstance{ -public: - RaidItemFarmerOHKO(); - - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; - -private: - BooleanCheckBoxOption BACKUP_SAVE; -// SectionDivider m_advanced_options; - MillisecondsOption WAIT_FOR_STAMP_DELAY0; - MillisecondsOption ENTER_STAMP_MASH_DURATION0; - MillisecondsOption RAID_START_MASH_DURATION0; - MillisecondsOption RAID_START_TO_ATTACK_DELAY0; - MillisecondsOption ATTACK_TO_CATCH_DELAY0; - MillisecondsOption RETURN_TO_OVERWORLD_DELAY0; - MillisecondsOption TOUCH_DATE_INTERVAL0; -}; - - - - -} -} -} -#endif +/* Raid Item Farmer (OHKO) + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_RaidItemFarmerOHKO_H +#define PokemonAutomation_PokemonSwSh_RaidItemFarmerOHKO_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class RaidItemFarmerOHKO_Descriptor : public MultiSwitchProgramDescriptor{ +public: + RaidItemFarmerOHKO_Descriptor(); +}; + + + +class RaidItemFarmerOHKO : public MultiSwitchProgramInstance{ +public: + RaidItemFarmerOHKO(); + + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; + +private: + BooleanCheckBoxOption BACKUP_SAVE; +// SectionDivider m_advanced_options; + MillisecondsOption WAIT_FOR_STAMP_DELAY0; + MillisecondsOption ENTER_STAMP_MASH_DURATION0; + MillisecondsOption RAID_START_MASH_DURATION0; + MillisecondsOption RAID_START_TO_ATTACK_DELAY0; + MillisecondsOption ATTACK_TO_CATCH_DELAY0; + MillisecondsOption RETURN_TO_OVERWORLD_DELAY0; + MillisecondsOption TOUCH_DATE_INTERVAL0; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h index 49a065cbbf..b31d5cf417 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_ReleaseHelpers.h @@ -1,70 +1,70 @@ -/* Mass Release Helpers - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ReleaseHelpers_H -#define PokemonAutomation_PokemonSwSh_ReleaseHelpers_H - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_BoxHelpers.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -// Release one pokemon in box -static void release(ProControllerContext& context){ - ssf_press_button(context, BUTTON_A, 600ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); - ssf_press_button(context, BUTTON_A, 1000ms, 80ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms, 80ms); -// ssf_press_button(context, BUTTON_A, 150); -// ssf_press_button(context, BUTTON_A, 40); - ssf_mash_AZs(context, 230); -} -static void release_box(ProControllerContext& context){ - for (uint8_t row = 0; row < 5; row++){ - if (row != 0){ - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_RIGHT); - box_scroll(context, DPAD_RIGHT); - } - for (uint8_t col = 0; col < 6; col++){ - if (col != 0){ - box_scroll(context, DPAD_RIGHT); - } - release(context); - } - } -} -static void release_boxes(ProControllerContext& context, uint8_t boxes){ - if (boxes == 0){ - return; - } - release_box(context); - - Milliseconds box_change_delay = GameSettings::instance().BOX_CHANGE_DELAY0; - for (uint8_t box = 1; box < boxes; box++){ - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_DOWN); - box_scroll(context, DPAD_RIGHT); - box_scroll(context, DPAD_RIGHT); - ssf_press_button_ptv(context, BUTTON_R, box_change_delay, 104ms); - release_box(context); - } -} - - - -} -} -} -#endif - +/* Mass Release Helpers + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ReleaseHelpers_H +#define PokemonAutomation_PokemonSwSh_ReleaseHelpers_H + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_BoxHelpers.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +// Release one pokemon in box +static void release(ProControllerContext& context){ + ssf_press_button(context, BUTTON_A, 600ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_UP, 160ms, 80ms); + ssf_press_button(context, BUTTON_A, 1000ms, 80ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 120ms, 80ms); +// ssf_press_button(context, BUTTON_A, 150); +// ssf_press_button(context, BUTTON_A, 40); + ssf_mash_AZs(context, 230); +} +static void release_box(ProControllerContext& context){ + for (uint8_t row = 0; row < 5; row++){ + if (row != 0){ + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_RIGHT); + box_scroll(context, DPAD_RIGHT); + } + for (uint8_t col = 0; col < 6; col++){ + if (col != 0){ + box_scroll(context, DPAD_RIGHT); + } + release(context); + } + } +} +static void release_boxes(ProControllerContext& context, uint8_t boxes){ + if (boxes == 0){ + return; + } + release_box(context); + + Milliseconds box_change_delay = GameSettings::instance().BOX_CHANGE_DELAY0; + for (uint8_t box = 1; box < boxes; box++){ + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_DOWN); + box_scroll(context, DPAD_RIGHT); + box_scroll(context, DPAD_RIGHT); + ssf_press_button_ptv(context, BUTTON_R, box_change_delay, 104ms); + release_box(context); + } +} + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.cpp index c4bfdadf2c..6891eca5c8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.cpp @@ -1,57 +1,57 @@ -/* Synchronized Spinning - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_SynchronizedSpinning.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -SynchronizedSpinning_Descriptor::SynchronizedSpinning_Descriptor() - : MultiSwitchProgramDescriptor( - "PokemonSwSh:SynchronizedSpinning", - STRING_POKEMON + " SwSh", "Synchronized Spinning", "", - "Don't ask... seriously, don't ask...", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER, - 1, 4, 1 - ) -{} - - - -SynchronizedSpinning::SynchronizedSpinning(){} - -void SynchronizedSpinning::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ - env.run_in_parallel( - scope, - [&](ConsoleHandle& console, ProControllerContext& context){ - pbf_move_left_joystick(context, 128, 255, 5, 20); - while (true){ - pbf_move_left_joystick(context, 128, 0, 5, 0); - pbf_move_left_joystick(context, 255, 0, 5, 0); - pbf_move_left_joystick(context, 255, 128, 5, 0); - pbf_move_left_joystick(context, 255, 255, 5, 0); - pbf_move_left_joystick(context, 128, 255, 5, 0); - pbf_move_left_joystick(context, 0, 255, 5, 0); - pbf_move_left_joystick(context, 0, 128, 5, 0); - pbf_move_left_joystick(context, 0, 0, 5, 0); - } - } - ); -} - - - -} -} -} +/* Synchronized Spinning + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_SynchronizedSpinning.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +SynchronizedSpinning_Descriptor::SynchronizedSpinning_Descriptor() + : MultiSwitchProgramDescriptor( + "PokemonSwSh:SynchronizedSpinning", + STRING_POKEMON + " SwSh", "Synchronized Spinning", "", + "Don't ask... seriously, don't ask...", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER, + 1, 4, 1 + ) +{} + + + +SynchronizedSpinning::SynchronizedSpinning(){} + +void SynchronizedSpinning::program(MultiSwitchProgramEnvironment& env, CancellableScope& scope){ + env.run_in_parallel( + scope, + [&](ConsoleHandle& console, ProControllerContext& context){ + pbf_move_left_joystick(context, 128, 255, 5, 20); + while (true){ + pbf_move_left_joystick(context, 128, 0, 5, 0); + pbf_move_left_joystick(context, 255, 0, 5, 0); + pbf_move_left_joystick(context, 255, 128, 5, 0); + pbf_move_left_joystick(context, 255, 255, 5, 0); + pbf_move_left_joystick(context, 128, 255, 5, 0); + pbf_move_left_joystick(context, 0, 255, 5, 0); + pbf_move_left_joystick(context, 0, 128, 5, 0); + pbf_move_left_joystick(context, 0, 0, 5, 0); + } + } + ); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.h b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.h index 1f730cfad8..1e9856cc4b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/PokemonSwSh_SynchronizedSpinning.h @@ -1,37 +1,37 @@ -/* Synchronized Spinning - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SynchronizedSpinning_H -#define PokemonAutomation_PokemonSwSh_SynchronizedSpinning_H - -#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class SynchronizedSpinning_Descriptor : public MultiSwitchProgramDescriptor{ -public: - SynchronizedSpinning_Descriptor(); -}; - - - -class SynchronizedSpinning : public MultiSwitchProgramInstance{ -public: - SynchronizedSpinning(); - - virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; -}; - - - - -} -} -} -#endif +/* Synchronized Spinning + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SynchronizedSpinning_H +#define PokemonAutomation_PokemonSwSh_SynchronizedSpinning_H + +#include "NintendoSwitch/NintendoSwitch_MultiSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class SynchronizedSpinning_Descriptor : public MultiSwitchProgramDescriptor{ +public: + SynchronizedSpinning_Descriptor(); +}; + + + +class SynchronizedSpinning : public MultiSwitchProgramInstance{ +public: + SynchronizedSpinning(); + + virtual void program(MultiSwitchProgramEnvironment& env, CancellableScope& scope) override; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.cpp index d4fd68c61b..d6ae2e78e2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.cpp @@ -1,63 +1,63 @@ -/* Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh_FastCodeEntry.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -FastCodeEntry_Descriptor::FastCodeEntry_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:FastCodeEntry", - STRING_POKEMON + " SwSh", "Fast Code Entry (FCE)", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/FastCodeEntry.md", - "Force your way into raids by entering 8-digit codes in under 1 second.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - - - -FastCodeEntry::FastCodeEntry() - : RAID_CODE( - "Raid Code:", - 8, - "9107 3091" - ) - , INITIAL_DELAY0( - "Initial Delay:
Wait this long before entering the code.", - LockMode::LOCK_WHILE_RUNNING, - "0 ms" - ) -{ - PA_ADD_OPTION(RAID_CODE); - PA_ADD_OPTION(INITIAL_DELAY0); -} - -void FastCodeEntry::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - std::string code = RAID_CODE.to_str(); - - pbf_wait(context, INITIAL_DELAY0); - - pbf_press_button(context, BUTTON_PLUS, 5, 5); - pbf_press_button(context, BUTTON_PLUS, 5, 5); - NintendoSwitch::FastCodeEntry::numberpad_enter_code(env.console, context, code, true); -} - - - -} -} -} +/* Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/FastCodeEntry/NintendoSwitch_NumberCodeEntry.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh_FastCodeEntry.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +FastCodeEntry_Descriptor::FastCodeEntry_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:FastCodeEntry", + STRING_POKEMON + " SwSh", "Fast Code Entry (FCE)", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/FastCodeEntry.md", + "Force your way into raids by entering 8-digit codes in under 1 second.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + + + +FastCodeEntry::FastCodeEntry() + : RAID_CODE( + "Raid Code:", + 8, + "9107 3091" + ) + , INITIAL_DELAY0( + "Initial Delay:
Wait this long before entering the code.", + LockMode::LOCK_WHILE_RUNNING, + "0 ms" + ) +{ + PA_ADD_OPTION(RAID_CODE); + PA_ADD_OPTION(INITIAL_DELAY0); +} + +void FastCodeEntry::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + std::string code = RAID_CODE.to_str(); + + pbf_wait(context, INITIAL_DELAY0); + + pbf_press_button(context, BUTTON_PLUS, 5, 5); + pbf_press_button(context, BUTTON_PLUS, 5, 5); + NintendoSwitch::FastCodeEntry::numberpad_enter_code(env.console, context, code, true); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h index 34c9a3404b..684f8f8314 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FastCodeEntry.h @@ -1,46 +1,46 @@ -/* Fast Code Entry - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_FastCodeEntry_H -#define PokemonAutomation_PokemonSwSh_FastCodeEntry_H - -#include "Common/Cpp/Options/FixedCodeOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class FastCodeEntry_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FastCodeEntry_Descriptor(); -}; - - - -class FastCodeEntry : public SingleSwitchProgramInstance{ -public: - FastCodeEntry(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - FixedCodeOption RAID_CODE; - MillisecondsOption INITIAL_DELAY0; -}; - - - - -} -} -} -#endif - - - +/* Fast Code Entry + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_FastCodeEntry_H +#define PokemonAutomation_PokemonSwSh_FastCodeEntry_H + +#include "Common/Cpp/Options/FixedCodeOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class FastCodeEntry_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FastCodeEntry_Descriptor(); +}; + + + +class FastCodeEntry : public SingleSwitchProgramInstance{ +public: + FastCodeEntry(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + FixedCodeOption RAID_CODE; + MillisecondsOption INITIAL_DELAY0; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.cpp index 5ffd46be93..b6079facb6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.cpp @@ -1,93 +1,93 @@ -/* Friend Search Disconnect - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" -#include "PokemonSwSh_FriendSearchDisconnect.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -FriendSearchDisconnect_Descriptor::FriendSearchDisconnect_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:FriendSearchDisconnect", - STRING_POKEMON + " SwSh", "Friend Search Disconnect", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/FriendSearchDisconnect.md", - "Disconnect from the internet using the friend search method.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController} - ) -{} - - - -FriendSearchDisconnect::FriendSearchDisconnect() - : USER_SLOT( - "User Slot:
Use this profile to disconnect.", - LockMode::LOCK_WHILE_RUNNING, - 1, 1, 8 - ) -{ - PA_ADD_OPTION(USER_SLOT); -} - -void FriendSearchDisconnect::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - context.wait_for_all_requests(); - - auto snapshot = env.console.video().snapshot(); - if (snapshot){ - HomeMenuWatcher home_menu(env.console); - int ret = wait_until( - env.console, context, - 5000ms, - {home_menu} - ); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Home menu not detected after 5 seconds.", - env.console - ); - } - } - - ConsoleType type = env.console.state().console_type(); - uint8_t scroll_down_slots = 0; - if (is_switch1(type)){ - scroll_down_slots = 1; - }else if (is_switch2(type)){ - scroll_down_slots = 3; - }else{ - throw UserSetupError( - env.logger(), - "Please select a valid Switch console type." - ); - } - - home_to_add_friends(context, USER_SLOT - 1, scroll_down_slots, true); - - // Enter friend search. - pbf_mash_button(context, BUTTON_A, 2000ms); - settings_to_enter_game(context, true); -} - - -} -} -} +/* Friend Search Disconnect + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Inference/NintendoSwitch_HomeMenuDetector.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_AutoHosts.h" +#include "PokemonSwSh_FriendSearchDisconnect.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +FriendSearchDisconnect_Descriptor::FriendSearchDisconnect_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:FriendSearchDisconnect", + STRING_POKEMON + " SwSh", "Friend Search Disconnect", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/FriendSearchDisconnect.md", + "Disconnect from the internet using the friend search method.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController} + ) +{} + + + +FriendSearchDisconnect::FriendSearchDisconnect() + : USER_SLOT( + "User Slot:
Use this profile to disconnect.", + LockMode::LOCK_WHILE_RUNNING, + 1, 1, 8 + ) +{ + PA_ADD_OPTION(USER_SLOT); +} + +void FriendSearchDisconnect::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + context.wait_for_all_requests(); + + auto snapshot = env.console.video().snapshot(); + if (snapshot){ + HomeMenuWatcher home_menu(env.console); + int ret = wait_until( + env.console, context, + 5000ms, + {home_menu} + ); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Home menu not detected after 5 seconds.", + env.console + ); + } + } + + ConsoleType type = env.console.state().console_type(); + uint8_t scroll_down_slots = 0; + if (is_switch1(type)){ + scroll_down_slots = 1; + }else if (is_switch2(type)){ + scroll_down_slots = 3; + }else{ + throw UserSetupError( + env.logger(), + "Please select a valid Switch console type." + ); + } + + home_to_add_friends(context, USER_SLOT - 1, scroll_down_slots, true); + + // Enter friend search. + pbf_mash_button(context, BUTTON_A, 2000ms); + settings_to_enter_game(context, true); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h index d82b43c3bf..035a447c1a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/QoLMacros/PokemonSwSh_FriendSearchDisconnect.h @@ -1,42 +1,42 @@ -/* Friend Search Disconnect - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_FriendSearchDisconnect_H -#define PokemonAutomation_PokemonSwSh_FriendSearchDisconnect_H - -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class FriendSearchDisconnect_Descriptor : public SingleSwitchProgramDescriptor{ -public: - FriendSearchDisconnect_Descriptor(); -}; - - - -class FriendSearchDisconnect : public SingleSwitchProgramInstance{ -public: - FriendSearchDisconnect(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - SimpleIntegerOption USER_SLOT; -}; - - - - -} -} -} -#endif - +/* Friend Search Disconnect + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_FriendSearchDisconnect_H +#define PokemonAutomation_PokemonSwSh_FriendSearchDisconnect_H + +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class FriendSearchDisconnect_Descriptor : public SingleSwitchProgramDescriptor{ +public: + FriendSearchDisconnect_Descriptor(); +}; + + + +class FriendSearchDisconnect : public SingleSwitchProgramInstance{ +public: + FriendSearchDisconnect(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + SimpleIntegerOption USER_SLOT; +}; + + + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.cpp index 42a4ae2692..a30fc6e758 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.cpp @@ -1,198 +1,198 @@ -/* Basic RNG manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -Xoroshiro128PlusState find_rng_state( - VideoStream& stream, - ProControllerContext& context, - bool save_screenshots, - bool log_image_values -){ - OrbeetleAttackAnimationDetector detector(stream, context); - uint64_t last_bits0 = 0; - uint64_t last_bits1 = 0; - - for (size_t i = 0; i < 128; i++){ - context.wait_for_all_requests(); - std::string text = std::to_string(i + 1) + "/128"; - stream.log("RNG: Attack animation " + text); - OrbeetleAttackAnimationDetector::Detection detection = detector.run(save_screenshots, log_image_values); - uint64_t last_bit = 0; - switch (detection){ - case OrbeetleAttackAnimationDetector::NO_DETECTION: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Attack animation could not be detected.", - stream - ); - case OrbeetleAttackAnimationDetector::SPECIAL: - text += " : Special"; - last_bit = 1; - break; - case OrbeetleAttackAnimationDetector::PHYSICAL: - text += " : Physical"; - last_bit = 0; - break; - } - stream.overlay().add_log(text, COLOR_BLUE); - pbf_wait(context, 180); - - if (i < 64){ - last_bits0 += last_bit << (63 - i); - }else{ - last_bits1 += last_bit << (63 - (i - 64)); - } - } - Xoroshiro128Plus rng = Xoroshiro128Plus::xoroshiro128plus_from_last_bits(std::pair(last_bits0, last_bits1)); - - for (size_t j = 0; j < 128; j++){ - rng.next(); - } - stream.log("RNG: state[0] = " + tostr_hex(rng.get_state().s0)); - stream.log("RNG: state[1] = " + tostr_hex(rng.get_state().s1)); - return rng.get_state(); -} - -Xoroshiro128PlusState refind_rng_state( - VideoStream& stream, - ProControllerContext& context, - Xoroshiro128PlusState last_known_state, - size_t min_advances, - size_t max_advances, - bool save_screenshots, - bool log_image_values -) { - return refind_rng_state_and_animations(stream, context, last_known_state, min_advances, max_advances, save_screenshots, log_image_values).first; -} - -std::pair refind_rng_state_and_animations( - VideoStream& stream, - ProControllerContext& context, - Xoroshiro128PlusState last_known_state, - size_t min_advances, - size_t max_advances, - bool save_screenshots, - bool log_image_values -) -{ - Xoroshiro128Plus rng(last_known_state.s0, last_known_state.s1); - for (size_t i = 0; i < min_advances; i++){ - rng.next(); - } - OrbeetleAttackAnimationDetector detector(stream, context); - size_t possible_indices = SIZE_MAX; - std::vector sequence = {}; - std::vector last_bit_sequence = rng.generate_last_bit_sequence(max_advances - min_advances); - size_t distance = 0; - - size_t i = 0; - while (possible_indices > 1){ - context.wait_for_all_requests(); - - std::string text = std::to_string(++i) + "/?"; - OrbeetleAttackAnimationDetector::Detection detection = detector.run(save_screenshots, log_image_values); - switch (detection){ - case OrbeetleAttackAnimationDetector::NO_DETECTION: - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Attack animation could not be detected.", - stream - ); - case OrbeetleAttackAnimationDetector::SPECIAL: - text += " : Special"; - sequence.emplace_back(true); - break; - case OrbeetleAttackAnimationDetector::PHYSICAL: - text += " : Physical"; - sequence.emplace_back(false); - break; - } - stream.overlay().add_log(text, COLOR_BLUE); - pbf_wait(context, 180); - - std::vector::iterator last_bit_start = std::search(last_bit_sequence.begin(), last_bit_sequence.end(), sequence.begin(), sequence.end()); - possible_indices = 0; - distance = 0; - while (last_bit_start != last_bit_sequence.end()){ - possible_indices++; - distance = std::distance(last_bit_sequence.begin(), last_bit_start); - - last_bit_start++; - last_bit_start = std::search(last_bit_start, last_bit_sequence.end(), sequence.begin(), sequence.end()); - } - } - if (possible_indices == 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Detected sequence of attack motions does not exist in expected range.", - stream - ); - } - - distance += sequence.size(); - stream.log("RNG: needed " + std::to_string(sequence.size()) + " animations."); - stream.log("RNG: new state is " + std::to_string(distance + min_advances) + " advances from last known state."); - for (size_t advance = 0; advance < distance; advance++){ - rng.next(); - } - stream.log("RNG: state[0] = " + tostr_hex(rng.get_state().s0)); - stream.log("RNG: state[1] = " + tostr_hex(rng.get_state().s1)); - - return { rng.get_state(), sequence.size() }; -} - - -void do_rng_advances( - VideoStream& stream, ProControllerContext& context, - Xoroshiro128Plus& rng, - size_t advances, - Milliseconds press_duration, - Milliseconds release_duration -){ - Milliseconds tv = context->timing_variation(); - for (size_t i = 0; i < advances; i++){ - if ((i + 1) % 10 == 0){ - std::string text = std::to_string(i + 1) + "/" + std::to_string(advances); - stream.log("RNG advance: " + text); - stream.overlay().add_log("Advancing: " + text, COLOR_GREEN); - } - pbf_press_button( - context, - BUTTON_RCLICK, - press_duration + tv, - release_duration + tv - ); - rng.next(); - } - pbf_wait(context, 1000ms); -} - -Xoroshiro128PlusState predict_state_after_menu_close(Xoroshiro128PlusState current_state, uint8_t num_npcs) { - Xoroshiro128Plus rng(current_state); - - for (size_t i = 0; i < num_npcs; i++) { - rng.nextInt(91); - } - rng.next(); - rng.nextInt(61); - - return rng.get_state(); -} - - -} -} -} +/* Basic RNG manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh/Inference/RNG/PokemonSwSh_OrbeetleAttackAnimationDetector.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +Xoroshiro128PlusState find_rng_state( + VideoStream& stream, + ProControllerContext& context, + bool save_screenshots, + bool log_image_values +){ + OrbeetleAttackAnimationDetector detector(stream, context); + uint64_t last_bits0 = 0; + uint64_t last_bits1 = 0; + + for (size_t i = 0; i < 128; i++){ + context.wait_for_all_requests(); + std::string text = std::to_string(i + 1) + "/128"; + stream.log("RNG: Attack animation " + text); + OrbeetleAttackAnimationDetector::Detection detection = detector.run(save_screenshots, log_image_values); + uint64_t last_bit = 0; + switch (detection){ + case OrbeetleAttackAnimationDetector::NO_DETECTION: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Attack animation could not be detected.", + stream + ); + case OrbeetleAttackAnimationDetector::SPECIAL: + text += " : Special"; + last_bit = 1; + break; + case OrbeetleAttackAnimationDetector::PHYSICAL: + text += " : Physical"; + last_bit = 0; + break; + } + stream.overlay().add_log(text, COLOR_BLUE); + pbf_wait(context, 180); + + if (i < 64){ + last_bits0 += last_bit << (63 - i); + }else{ + last_bits1 += last_bit << (63 - (i - 64)); + } + } + Xoroshiro128Plus rng = Xoroshiro128Plus::xoroshiro128plus_from_last_bits(std::pair(last_bits0, last_bits1)); + + for (size_t j = 0; j < 128; j++){ + rng.next(); + } + stream.log("RNG: state[0] = " + tostr_hex(rng.get_state().s0)); + stream.log("RNG: state[1] = " + tostr_hex(rng.get_state().s1)); + return rng.get_state(); +} + +Xoroshiro128PlusState refind_rng_state( + VideoStream& stream, + ProControllerContext& context, + Xoroshiro128PlusState last_known_state, + size_t min_advances, + size_t max_advances, + bool save_screenshots, + bool log_image_values +) { + return refind_rng_state_and_animations(stream, context, last_known_state, min_advances, max_advances, save_screenshots, log_image_values).first; +} + +std::pair refind_rng_state_and_animations( + VideoStream& stream, + ProControllerContext& context, + Xoroshiro128PlusState last_known_state, + size_t min_advances, + size_t max_advances, + bool save_screenshots, + bool log_image_values +) +{ + Xoroshiro128Plus rng(last_known_state.s0, last_known_state.s1); + for (size_t i = 0; i < min_advances; i++){ + rng.next(); + } + OrbeetleAttackAnimationDetector detector(stream, context); + size_t possible_indices = SIZE_MAX; + std::vector sequence = {}; + std::vector last_bit_sequence = rng.generate_last_bit_sequence(max_advances - min_advances); + size_t distance = 0; + + size_t i = 0; + while (possible_indices > 1){ + context.wait_for_all_requests(); + + std::string text = std::to_string(++i) + "/?"; + OrbeetleAttackAnimationDetector::Detection detection = detector.run(save_screenshots, log_image_values); + switch (detection){ + case OrbeetleAttackAnimationDetector::NO_DETECTION: + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Attack animation could not be detected.", + stream + ); + case OrbeetleAttackAnimationDetector::SPECIAL: + text += " : Special"; + sequence.emplace_back(true); + break; + case OrbeetleAttackAnimationDetector::PHYSICAL: + text += " : Physical"; + sequence.emplace_back(false); + break; + } + stream.overlay().add_log(text, COLOR_BLUE); + pbf_wait(context, 180); + + std::vector::iterator last_bit_start = std::search(last_bit_sequence.begin(), last_bit_sequence.end(), sequence.begin(), sequence.end()); + possible_indices = 0; + distance = 0; + while (last_bit_start != last_bit_sequence.end()){ + possible_indices++; + distance = std::distance(last_bit_sequence.begin(), last_bit_start); + + last_bit_start++; + last_bit_start = std::search(last_bit_start, last_bit_sequence.end(), sequence.begin(), sequence.end()); + } + } + if (possible_indices == 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Detected sequence of attack motions does not exist in expected range.", + stream + ); + } + + distance += sequence.size(); + stream.log("RNG: needed " + std::to_string(sequence.size()) + " animations."); + stream.log("RNG: new state is " + std::to_string(distance + min_advances) + " advances from last known state."); + for (size_t advance = 0; advance < distance; advance++){ + rng.next(); + } + stream.log("RNG: state[0] = " + tostr_hex(rng.get_state().s0)); + stream.log("RNG: state[1] = " + tostr_hex(rng.get_state().s1)); + + return { rng.get_state(), sequence.size() }; +} + + +void do_rng_advances( + VideoStream& stream, ProControllerContext& context, + Xoroshiro128Plus& rng, + size_t advances, + Milliseconds press_duration, + Milliseconds release_duration +){ + Milliseconds tv = context->timing_variation(); + for (size_t i = 0; i < advances; i++){ + if ((i + 1) % 10 == 0){ + std::string text = std::to_string(i + 1) + "/" + std::to_string(advances); + stream.log("RNG advance: " + text); + stream.overlay().add_log("Advancing: " + text, COLOR_GREEN); + } + pbf_press_button( + context, + BUTTON_RCLICK, + press_duration + tv, + release_duration + tv + ); + rng.next(); + } + pbf_wait(context, 1000ms); +} + +Xoroshiro128PlusState predict_state_after_menu_close(Xoroshiro128PlusState current_state, uint8_t num_npcs) { + Xoroshiro128Plus rng(current_state); + + for (size_t i = 0; i < num_npcs; i++) { + rng.nextInt(91); + } + rng.next(); + rng.nextInt(61); + + return rng.get_state(); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h index 5814bb01cb..28edbb284f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h @@ -1,65 +1,65 @@ -/* Basic RNG manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "Pokemon/Pokemon_Xoroshiro128Plus.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - -// Performs 128 Orbeetle attack animations. -// Returns the state after those animations. -Xoroshiro128PlusState find_rng_state( - VideoStream& stream, ProControllerContext& context, - bool save_screenshots, bool log_values -); - -// Performs Orbeetle attack animations until only one possible state is left. -// Returns the state after those animations. -Xoroshiro128PlusState refind_rng_state( - VideoStream& stream, - ProControllerContext& context, - Xoroshiro128PlusState last_known_state, - size_t min_advances, - size_t max_advances, - bool save_screenshots, - bool log_values -); - -// Performs Orbeetle attack animations until only one possible state is left. -// Returns a pair: -// first: current RNG state -// second: the number of animations required to find the state -std::pair refind_rng_state_and_animations( - VideoStream& stream, - ProControllerContext& context, - Xoroshiro128PlusState last_known_state, - size_t min_advances, - size_t max_advances, - bool save_screenshots, - bool log_values -); - -void do_rng_advances( - VideoStream& stream, ProControllerContext& context, - Xoroshiro128Plus& rng, - size_t advances, - Milliseconds press_duration, - Milliseconds release_duration -); - -Xoroshiro128PlusState predict_state_after_menu_close(Xoroshiro128PlusState current_state, uint8_t num_npcs); - - - -} -} -} +/* Basic RNG manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "Pokemon/Pokemon_Xoroshiro128Plus.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + +// Performs 128 Orbeetle attack animations. +// Returns the state after those animations. +Xoroshiro128PlusState find_rng_state( + VideoStream& stream, ProControllerContext& context, + bool save_screenshots, bool log_values +); + +// Performs Orbeetle attack animations until only one possible state is left. +// Returns the state after those animations. +Xoroshiro128PlusState refind_rng_state( + VideoStream& stream, + ProControllerContext& context, + Xoroshiro128PlusState last_known_state, + size_t min_advances, + size_t max_advances, + bool save_screenshots, + bool log_values +); + +// Performs Orbeetle attack animations until only one possible state is left. +// Returns a pair: +// first: current RNG state +// second: the number of animations required to find the state +std::pair refind_rng_state_and_animations( + VideoStream& stream, + ProControllerContext& context, + Xoroshiro128PlusState last_known_state, + size_t min_advances, + size_t max_advances, + bool save_screenshots, + bool log_values +); + +void do_rng_advances( + VideoStream& stream, ProControllerContext& context, + Xoroshiro128Plus& rng, + size_t advances, + Milliseconds press_duration, + Milliseconds release_duration +); + +Xoroshiro128PlusState predict_state_after_menu_close(Xoroshiro128PlusState current_state, uint8_t num_npcs); + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp index ee108d314c..109a1338b7 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.cpp @@ -1,578 +1,578 @@ -/* Cram-o-matic RNG Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - * Credit goes to Anubis for discovering how the Cram-o-matic works - * and for the original code to calculate how many advances are needed - * to get the wanted balls. - * - */ - -#include -#include -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonFramework/Tools/DebugDumper.h" -#include "CommonTools/Images/SolidColorTest.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" -#include "Pokemon/Inference/Pokemon_NameReader.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - -CramomaticRNG_Descriptor::CramomaticRNG_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:CramomaticRNG", - STRING_POKEMON + " SwSh", "Cram-o-matic RNG", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/CramomaticRNG.md", - "Perform RNG manipulation to get rare balls from the Cram-o-matic.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -class CramomaticRNG_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : iterations(m_stats["Iterations"]) - , reads(m_stats["Seed Reads"]) - , errors(m_stats["Errors"]) - , total_balls(m_stats["Balls"]) - , apri_balls(m_stats["Apriballs"]) - , sport_safari_balls(m_stats["Safari/Sport Balls"]) - , bonus(m_stats["Bonus"]) - { - m_display_order.emplace_back("Iterations"); - m_display_order.emplace_back("Seed Reads"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Balls"); - m_display_order.emplace_back("Apriballs"); - m_display_order.emplace_back("Safari/Sport Balls"); - m_display_order.emplace_back("Bonus", HIDDEN_IF_ZERO); - } - -public: - std::atomic& iterations; - std::atomic& reads; - std::atomic& errors; - std::atomic& total_balls; - std::atomic& apri_balls; - std::atomic& sport_safari_balls; - std::atomic& bonus; -}; -std::unique_ptr CramomaticRNG_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -CramomaticRNG::CramomaticRNG() - : LANGUAGE( - "Game Language:
Required to read the ball received.", - PokemonNameReader::instance().languages(), - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NUM_APRICORN_ONE( - "Primary Apricorns:
Number of Apricorns in the selected slot.", - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , NUM_APRICORN_TWO( - "Secondary Apricorns:
Number of Apricorns in the slot below the selected one.", - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , NUM_NPCS( - "NPCs:
Number of NPCs in the dojo, including " + STRING_POKEMON + ".", - LockMode::LOCK_WHILE_RUNNING, - 21 - ) - , BALL_TABLE( - "Wanted Balls:
Exact kind depends on the currently selected apricorn." - ) - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MAX_PRIORITY_ADVANCES( - "Priority Advances:
How many advances to check when checking for higher priority selections.", - LockMode::LOCK_WHILE_RUNNING, - 300 - ) - , MAX_UNKNOWN_ADVANCES( - "Max Unknown advances:
How many advances to check when updating the rng state.", - LockMode::LOCK_WHILE_RUNNING, - 300 - ) - , ADVANCE_PRESS_DURATION( - "Advance Press Duration:
" - "Hold the button down for this long to advance once.
" - "For tick-imprecise controllers, this number will be increased automatically.", - LockMode::LOCK_WHILE_RUNNING, - "80 ms" - ) - , ADVANCE_RELEASE_DURATION( - "Advance Release Duration:
" - "After releasing the button, wait this long before pressing it again.
" - "For tick-imprecise controllers, this number will be increased automatically.", - LockMode::LOCK_WHILE_RUNNING, - "80 ms" - ) - , SAVE_SCREENSHOTS( - "Save Debug Screenshots:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , LOG_VALUES( - "Log Animation Values:
", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(NUM_APRICORN_ONE); - PA_ADD_OPTION(NUM_APRICORN_TWO); - PA_ADD_OPTION(NUM_NPCS); - PA_ADD_OPTION(BALL_TABLE); - - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(MAX_PRIORITY_ADVANCES); - PA_ADD_OPTION(MAX_UNKNOWN_ADVANCES); - PA_ADD_OPTION(ADVANCE_PRESS_DURATION); - PA_ADD_OPTION(ADVANCE_RELEASE_DURATION); - PA_ADD_OPTION(SAVE_SCREENSHOTS); - PA_ADD_OPTION(LOG_VALUES); -} - -void CramomaticRNG::navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - pbf_press_button(context, BUTTON_X, 10, 125); - pbf_press_button(context, BUTTON_A, 20, 10); - pbf_wait(context, 2000ms); -} - -CramomaticTarget CramomaticRNG::calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, std::vector selected_balls){ - Xoroshiro128Plus rng(state); - size_t advances = 0; - uint16_t priority_advances = 0; - std::vector possible_targets; - - std::sort(selected_balls.begin(), selected_balls.end(), [](CramomaticSelection sel1, CramomaticSelection sel2) { return sel1.priority > sel2.priority; }); - // priority_advances only starts counting up after the first good result is found - while (priority_advances <= MAX_PRIORITY_ADVANCES){ - // calculate the result for the current temp_rng state - Xoroshiro128PlusState temp_state = predict_state_after_menu_close(rng.get_state(), NUM_NPCS); - Xoroshiro128Plus temp_rng(temp_state); - - - /*uint64_t item_roll =*/ temp_rng.nextInt(4); - uint64_t ball_roll = temp_rng.nextInt(100); - bool is_safari_sport = temp_rng.nextInt(1000) == 0; - bool is_bonus = false; - - if (is_safari_sport || ball_roll == 99){ - is_bonus = temp_rng.nextInt(1000) == 0; - }else{ - is_bonus = temp_rng.nextInt(100) == 0; - } - - CramomaticBallType type; - if (is_safari_sport){ - type = CramomaticBallType::Safari; - }else if (ball_roll < 25){ - type = CramomaticBallType::Poke; - }else if (ball_roll < 50){ - type = CramomaticBallType::Great; - }else if (ball_roll < 75){ - type = CramomaticBallType::Shop1; - }else if (ball_roll < 99){ - type = CramomaticBallType::Shop2; - }else{ - type = CramomaticBallType::Apricorn; - } - - - // check whether the result is a good result - for (size_t i = 0; i < selected_balls.size(); i++){ - CramomaticSelection selection = selected_balls[i]; - if (!selection.is_bonus || is_bonus){ - if (is_safari_sport){ - if (selection.ball_type == CramomaticBallType::Safari || selection.ball_type == CramomaticBallType::Sport){ - type = selection.ball_type; - } - } - - if (selection.ball_type == type){ - CramomaticTarget target; - target.ball_type = type; - target.is_bonus = is_bonus; - target.needed_advances = advances; - possible_targets.emplace_back(target); - - priority_advances = 0; - - uint16_t priority = selection.priority; - selected_balls.erase( - std::remove_if(selected_balls.begin(), selected_balls.end() - , [priority](CramomaticSelection sel) { return sel.priority <= priority; }) - , selected_balls.end()); - break; - } - - } - } - if (possible_targets.size() > 0){ - if (selected_balls.empty()){ - //priority_advances = MAX_PRIORITY_ADVANCES + 1; - break; - } - priority_advances++; - } - - rng.next(); - advances++; - } - - // Choose the first result which doesn't overshadow a higher priority choice. - // Ignores rng advances done by NPCs when the menu closes - while (possible_targets.size() > 1){ - auto last_target = possible_targets.end() - 1; - auto second_to_last_target = possible_targets.end() - 2; - - if ((*last_target).needed_advances - (*second_to_last_target).needed_advances > MAX_PRIORITY_ADVANCES){ - possible_targets.erase(last_target); - }else{ - possible_targets.erase(second_to_last_target); - } - } - - return possible_targets[0]; -} - -void CramomaticRNG::leave_to_overworld_and_interact(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - pbf_press_button(context, BUTTON_B, 2000ms, 40ms); - pbf_press_button(context, BUTTON_B, 10, 70); - - pbf_mash_button(context, BUTTON_A, 320); - pbf_wait(context, 125); -} - -void CramomaticRNG::choose_apricorn(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool sport){ - // check whether the bag is open - context.wait_for_all_requests(); - VideoOverlaySet boxes(env.console); - SelectionArrowFinder bag_arrow_detector(env.console, ImageFloatBox(0.465, 0.195, 0.054, 0.57)); - bag_arrow_detector.make_overlays(boxes); - - int ret = wait_until(env.console, context, Milliseconds(5000), { bag_arrow_detector }); - if (ret < 0){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Could not detect bag.", - env.console - ); - } - - // select the apricorn(s) - pbf_wait(context, 1000ms); - pbf_press_button(context, BUTTON_A, 10, 30); - if (sport){ - pbf_press_dpad(context, DPAD_DOWN, 20, 10); - } - pbf_press_button(context, BUTTON_A, 10, 30); - pbf_press_button(context, BUTTON_A, 10, 30); - if (sport){ - pbf_press_dpad(context, DPAD_UP, 20, 10); - } - pbf_press_button(context, BUTTON_A, 10, 30); - - pbf_mash_button(context, BUTTON_A, 5000ms); -} - -std::pair CramomaticRNG::receive_ball(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // receive ball and refuse to use the cram-o-matic again - VideoOverlaySet boxes(env.console); - - SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.350, 0.450, 0.500, 0.400)); - arrow_detector.make_overlays(boxes); - - OverlayBoxScope dialog_text(env.console, {0.21, 0.80, 0.53, 0.17}); - OverlayBoxScope dialog_box(env.console, {0.70, 0.90, 0.03, 0.05}); - const double LOG10P_THRESHOLD = -1.5; - std::string best_ball; - - size_t presses = 0; - bool arrow_detected = false; - - while (presses < 30 && !arrow_detected){ - presses++; - pbf_press_button(context, BUTTON_B, 10, 165); - context.wait_for_all_requests(); - - VideoSnapshot screen = env.console.video().snapshot(); - if (SAVE_SCREENSHOTS){ - dump_debug_image(env.logger(), "cramomatic-rng", "receive", screen); - } - - // If we detect a dialog box, attempt to read the ball that was received. - ImageStats stats = image_stats(extract_box_reference(screen, dialog_box)); -// cout << stats.average << stats.stddev << endl; - if (is_grey(stats, 0, 200, 5)){ - OCR::StringMatchResult result = PokeballNameReader::instance().read_substring( - env.console, LANGUAGE, - extract_box_reference(screen, dialog_text), - {{0xff007f7f, 0xffc0ffff}} - ); - result.clear_beyond_log10p(LOG10P_THRESHOLD); - if (best_ball.empty() && !result.results.empty()){ - auto iter = result.results.begin(); - if (iter->first < LOG10P_THRESHOLD){ - best_ball = iter->second.token; - } - } - } - - if (arrow_detector.detect(screen)){ - arrow_detected = true; - } - } - pbf_press_button(context, BUTTON_B, 80ms, 1000ms); - return {arrow_detected, best_ball}; -} - -void CramomaticRNG::recover_from_wrong_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - // Mash the B button to exit potential menus or dialog boxes - pbf_mash_button(context, BUTTON_B, 30s); - - // take a step in case Hyde repositioned the player - pbf_move_left_joystick(context, 128, 0, 1000ms, 80ms); - - context.wait_for_all_requests(); -} - - -void CramomaticRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - CramomaticRNG_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - std::vector selections = BALL_TABLE.selected_balls(); - if (selections.empty()){ - throw UserSetupError(env.console, "At least one type of ball needs to be selected!"); - } - - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - static const std::set APRIBALLS{ - "fast-ball", - "friend-ball", - "lure-ball", - "level-ball", - "heavy-ball", - "love-ball", - "moon-ball", - }; - static const std::set RARE_BALLS{ - "sport-ball", - "safari-ball", - }; - - Xoroshiro128Plus rng(0, 0); - bool is_state_valid = false; - uint32_t num_apricorn_one = NUM_APRICORN_ONE; - uint32_t num_apricorn_two = NUM_APRICORN_TWO; - - // if there is no Sport Ball in the selected balls we ignore num_apricorn_two - bool sport_wanted = false; - for (CramomaticSelection selection : selections){ - if (selection.ball_type == CramomaticBallType::Sport){ - sport_wanted = true; - break; - } - } - - size_t iteration = 0; - uint16_t state_errors = 0; - uint16_t apricorn_selection_errors = 0; - while (num_apricorn_one > 4 && (!sport_wanted || num_apricorn_two > 2)){ - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - - // Touch the date. - if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ - env.log("Touching date to prevent rollover."); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); - touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - - env.console.log("Cram-o-matic RNG iteration: " + std::to_string(iteration)); - navigate_to_party(env, context); - context.wait_for_all_requests(); - - if (!is_state_valid){ - rng = Xoroshiro128Plus(find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES)); -// rng = Xoroshiro128Plus(100, 10000); - is_state_valid = true; - stats.reads++; - }else{ - rng = Xoroshiro128Plus(refind_rng_state(env.console, context, rng.get_state(), 0, MAX_UNKNOWN_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES)); - stats.reads++; - } - env.update_stats(); - - Xoroshiro128PlusState rng_state = rng.get_state(); - if (rng_state.s0 == 0 && rng_state.s1 == 0){ - stats.errors++; - env.update_stats(); - - state_errors++; - if (state_errors >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Detected invalid RNG state three times in a row.", - env.console - ); - } - VideoSnapshot screen = env.console.video().snapshot(); - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Detected invalid RNG state.", screen); - recover_from_wrong_state(env, context); - is_state_valid = false; - continue; - } - - CramomaticTarget target = calculate_target(env, rng.get_state(), BALL_TABLE.selected_balls()); - bool sport = target.ball_type == CramomaticBallType::Sport; - env.console.log("Needed advances: " + std::to_string(target.needed_advances)); - num_apricorn_one -= sport ? 2 : 4; - num_apricorn_two -= sport ? 2 : 0; - - do_rng_advances( - env.console, context, - rng, - target.needed_advances, - ADVANCE_PRESS_DURATION, - ADVANCE_RELEASE_DURATION - ); - leave_to_overworld_and_interact(env, context); - - try{ - choose_apricorn(env, context, sport); - }catch (OperationFailedException& e){ - stats.errors++; - env.update_stats(); - - apricorn_selection_errors++; - if (apricorn_selection_errors >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Could not detect the bag three times on a row.", - env.console - ); - } - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, e.message(), e.screenshot()); - is_state_valid = false; - recover_from_wrong_state(env, context); - continue; - } - - std::pair result = receive_ball(env, context); - - // Update ball stats. - if (!result.second.empty()){ - stats.total_balls++; - } - auto iter = APRIBALLS.find(result.second); - if (iter != APRIBALLS.end()){ - stats.apri_balls++; - } - iter = RARE_BALLS.find(result.second); - if (iter != RARE_BALLS.end()){ - stats.sport_safari_balls++; - } - - // Out of apricorns. - if (!result.first || num_apricorn_one <= 4 || (sport_wanted && num_apricorn_two <= 2)){ - throw_and_log(env.console, "Out of apricorns.", env.console); - } - - -#if 0 -// cout << "Ball Slug = " << ball << endl; - if (result.first || num_apricorn_one <= 4 || (sport_wanted && num_apricorn_two <= 2)){ - }else{ - is_state_valid = false; - stats.errors++; - } -#endif - -#if 0 - if (!ball.empty() || num_apricorn_one <= 4 || (sport_wanted && num_apricorn_two <= 2)){ - int amount = target.is_bonus ? 5 : 1; - if (target.is_bonus){ - stats.bonus++; - } - if (target.ball_type == CramomaticBallType::Apricorn){ - stats.apri_balls += amount; - }else if (target.ball_type == CramomaticBallType::Sport || target.ball_type == CramomaticBallType::Safari){ - stats.sport_safari_balls += amount; - } - stats.total_balls += amount; - }else{ - is_state_valid = false; - stats.errors++; - } -#endif - env.update_stats(); - - state_errors = 0; - apricorn_selection_errors = 0; - - iteration++; - stats.iterations++; - env.update_stats(); - } - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - -} -} -} +/* Cram-o-matic RNG Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + * Credit goes to Anubis for discovering how the Cram-o-matic works + * and for the original code to calculate how many advances are needed + * to get the wanted balls. + * + */ + +#include +#include +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonFramework/Tools/DebugDumper.h" +#include "CommonTools/Images/SolidColorTest.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Inference/Pokemon_PokeballNameReader.h" +#include "Pokemon/Inference/Pokemon_NameReader.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + +CramomaticRNG_Descriptor::CramomaticRNG_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:CramomaticRNG", + STRING_POKEMON + " SwSh", "Cram-o-matic RNG", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/CramomaticRNG.md", + "Perform RNG manipulation to get rare balls from the Cram-o-matic.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +class CramomaticRNG_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : iterations(m_stats["Iterations"]) + , reads(m_stats["Seed Reads"]) + , errors(m_stats["Errors"]) + , total_balls(m_stats["Balls"]) + , apri_balls(m_stats["Apriballs"]) + , sport_safari_balls(m_stats["Safari/Sport Balls"]) + , bonus(m_stats["Bonus"]) + { + m_display_order.emplace_back("Iterations"); + m_display_order.emplace_back("Seed Reads"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Balls"); + m_display_order.emplace_back("Apriballs"); + m_display_order.emplace_back("Safari/Sport Balls"); + m_display_order.emplace_back("Bonus", HIDDEN_IF_ZERO); + } + +public: + std::atomic& iterations; + std::atomic& reads; + std::atomic& errors; + std::atomic& total_balls; + std::atomic& apri_balls; + std::atomic& sport_safari_balls; + std::atomic& bonus; +}; +std::unique_ptr CramomaticRNG_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +CramomaticRNG::CramomaticRNG() + : LANGUAGE( + "Game Language:
Required to read the ball received.", + PokemonNameReader::instance().languages(), + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NUM_APRICORN_ONE( + "Primary Apricorns:
Number of Apricorns in the selected slot.", + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , NUM_APRICORN_TWO( + "Secondary Apricorns:
Number of Apricorns in the slot below the selected one.", + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , NUM_NPCS( + "NPCs:
Number of NPCs in the dojo, including " + STRING_POKEMON + ".", + LockMode::LOCK_WHILE_RUNNING, + 21 + ) + , BALL_TABLE( + "Wanted Balls:
Exact kind depends on the currently selected apricorn." + ) + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MAX_PRIORITY_ADVANCES( + "Priority Advances:
How many advances to check when checking for higher priority selections.", + LockMode::LOCK_WHILE_RUNNING, + 300 + ) + , MAX_UNKNOWN_ADVANCES( + "Max Unknown advances:
How many advances to check when updating the rng state.", + LockMode::LOCK_WHILE_RUNNING, + 300 + ) + , ADVANCE_PRESS_DURATION( + "Advance Press Duration:
" + "Hold the button down for this long to advance once.
" + "For tick-imprecise controllers, this number will be increased automatically.", + LockMode::LOCK_WHILE_RUNNING, + "80 ms" + ) + , ADVANCE_RELEASE_DURATION( + "Advance Release Duration:
" + "After releasing the button, wait this long before pressing it again.
" + "For tick-imprecise controllers, this number will be increased automatically.", + LockMode::LOCK_WHILE_RUNNING, + "80 ms" + ) + , SAVE_SCREENSHOTS( + "Save Debug Screenshots:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , LOG_VALUES( + "Log Animation Values:
", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(NUM_APRICORN_ONE); + PA_ADD_OPTION(NUM_APRICORN_TWO); + PA_ADD_OPTION(NUM_NPCS); + PA_ADD_OPTION(BALL_TABLE); + + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(MAX_PRIORITY_ADVANCES); + PA_ADD_OPTION(MAX_UNKNOWN_ADVANCES); + PA_ADD_OPTION(ADVANCE_PRESS_DURATION); + PA_ADD_OPTION(ADVANCE_RELEASE_DURATION); + PA_ADD_OPTION(SAVE_SCREENSHOTS); + PA_ADD_OPTION(LOG_VALUES); +} + +void CramomaticRNG::navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + pbf_press_button(context, BUTTON_X, 10, 125); + pbf_press_button(context, BUTTON_A, 20, 10); + pbf_wait(context, 2000ms); +} + +CramomaticTarget CramomaticRNG::calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, std::vector selected_balls){ + Xoroshiro128Plus rng(state); + size_t advances = 0; + uint16_t priority_advances = 0; + std::vector possible_targets; + + std::sort(selected_balls.begin(), selected_balls.end(), [](CramomaticSelection sel1, CramomaticSelection sel2) { return sel1.priority > sel2.priority; }); + // priority_advances only starts counting up after the first good result is found + while (priority_advances <= MAX_PRIORITY_ADVANCES){ + // calculate the result for the current temp_rng state + Xoroshiro128PlusState temp_state = predict_state_after_menu_close(rng.get_state(), NUM_NPCS); + Xoroshiro128Plus temp_rng(temp_state); + + + /*uint64_t item_roll =*/ temp_rng.nextInt(4); + uint64_t ball_roll = temp_rng.nextInt(100); + bool is_safari_sport = temp_rng.nextInt(1000) == 0; + bool is_bonus = false; + + if (is_safari_sport || ball_roll == 99){ + is_bonus = temp_rng.nextInt(1000) == 0; + }else{ + is_bonus = temp_rng.nextInt(100) == 0; + } + + CramomaticBallType type; + if (is_safari_sport){ + type = CramomaticBallType::Safari; + }else if (ball_roll < 25){ + type = CramomaticBallType::Poke; + }else if (ball_roll < 50){ + type = CramomaticBallType::Great; + }else if (ball_roll < 75){ + type = CramomaticBallType::Shop1; + }else if (ball_roll < 99){ + type = CramomaticBallType::Shop2; + }else{ + type = CramomaticBallType::Apricorn; + } + + + // check whether the result is a good result + for (size_t i = 0; i < selected_balls.size(); i++){ + CramomaticSelection selection = selected_balls[i]; + if (!selection.is_bonus || is_bonus){ + if (is_safari_sport){ + if (selection.ball_type == CramomaticBallType::Safari || selection.ball_type == CramomaticBallType::Sport){ + type = selection.ball_type; + } + } + + if (selection.ball_type == type){ + CramomaticTarget target; + target.ball_type = type; + target.is_bonus = is_bonus; + target.needed_advances = advances; + possible_targets.emplace_back(target); + + priority_advances = 0; + + uint16_t priority = selection.priority; + selected_balls.erase( + std::remove_if(selected_balls.begin(), selected_balls.end() + , [priority](CramomaticSelection sel) { return sel.priority <= priority; }) + , selected_balls.end()); + break; + } + + } + } + if (possible_targets.size() > 0){ + if (selected_balls.empty()){ + //priority_advances = MAX_PRIORITY_ADVANCES + 1; + break; + } + priority_advances++; + } + + rng.next(); + advances++; + } + + // Choose the first result which doesn't overshadow a higher priority choice. + // Ignores rng advances done by NPCs when the menu closes + while (possible_targets.size() > 1){ + auto last_target = possible_targets.end() - 1; + auto second_to_last_target = possible_targets.end() - 2; + + if ((*last_target).needed_advances - (*second_to_last_target).needed_advances > MAX_PRIORITY_ADVANCES){ + possible_targets.erase(last_target); + }else{ + possible_targets.erase(second_to_last_target); + } + } + + return possible_targets[0]; +} + +void CramomaticRNG::leave_to_overworld_and_interact(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + pbf_press_button(context, BUTTON_B, 2000ms, 40ms); + pbf_press_button(context, BUTTON_B, 10, 70); + + pbf_mash_button(context, BUTTON_A, 320); + pbf_wait(context, 125); +} + +void CramomaticRNG::choose_apricorn(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool sport){ + // check whether the bag is open + context.wait_for_all_requests(); + VideoOverlaySet boxes(env.console); + SelectionArrowFinder bag_arrow_detector(env.console, ImageFloatBox(0.465, 0.195, 0.054, 0.57)); + bag_arrow_detector.make_overlays(boxes); + + int ret = wait_until(env.console, context, Milliseconds(5000), { bag_arrow_detector }); + if (ret < 0){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Could not detect bag.", + env.console + ); + } + + // select the apricorn(s) + pbf_wait(context, 1000ms); + pbf_press_button(context, BUTTON_A, 10, 30); + if (sport){ + pbf_press_dpad(context, DPAD_DOWN, 20, 10); + } + pbf_press_button(context, BUTTON_A, 10, 30); + pbf_press_button(context, BUTTON_A, 10, 30); + if (sport){ + pbf_press_dpad(context, DPAD_UP, 20, 10); + } + pbf_press_button(context, BUTTON_A, 10, 30); + + pbf_mash_button(context, BUTTON_A, 5000ms); +} + +std::pair CramomaticRNG::receive_ball(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // receive ball and refuse to use the cram-o-matic again + VideoOverlaySet boxes(env.console); + + SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.350, 0.450, 0.500, 0.400)); + arrow_detector.make_overlays(boxes); + + OverlayBoxScope dialog_text(env.console, {0.21, 0.80, 0.53, 0.17}); + OverlayBoxScope dialog_box(env.console, {0.70, 0.90, 0.03, 0.05}); + const double LOG10P_THRESHOLD = -1.5; + std::string best_ball; + + size_t presses = 0; + bool arrow_detected = false; + + while (presses < 30 && !arrow_detected){ + presses++; + pbf_press_button(context, BUTTON_B, 10, 165); + context.wait_for_all_requests(); + + VideoSnapshot screen = env.console.video().snapshot(); + if (SAVE_SCREENSHOTS){ + dump_debug_image(env.logger(), "cramomatic-rng", "receive", screen); + } + + // If we detect a dialog box, attempt to read the ball that was received. + ImageStats stats = image_stats(extract_box_reference(screen, dialog_box)); +// cout << stats.average << stats.stddev << endl; + if (is_grey(stats, 0, 200, 5)){ + OCR::StringMatchResult result = PokeballNameReader::instance().read_substring( + env.console, LANGUAGE, + extract_box_reference(screen, dialog_text), + {{0xff007f7f, 0xffc0ffff}} + ); + result.clear_beyond_log10p(LOG10P_THRESHOLD); + if (best_ball.empty() && !result.results.empty()){ + auto iter = result.results.begin(); + if (iter->first < LOG10P_THRESHOLD){ + best_ball = iter->second.token; + } + } + } + + if (arrow_detector.detect(screen)){ + arrow_detected = true; + } + } + pbf_press_button(context, BUTTON_B, 80ms, 1000ms); + return {arrow_detected, best_ball}; +} + +void CramomaticRNG::recover_from_wrong_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + // Mash the B button to exit potential menus or dialog boxes + pbf_mash_button(context, BUTTON_B, 30s); + + // take a step in case Hyde repositioned the player + pbf_move_left_joystick(context, 128, 0, 1000ms, 80ms); + + context.wait_for_all_requests(); +} + + +void CramomaticRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + CramomaticRNG_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + std::vector selections = BALL_TABLE.selected_balls(); + if (selections.empty()){ + throw UserSetupError(env.console, "At least one type of ball needs to be selected!"); + } + + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + static const std::set APRIBALLS{ + "fast-ball", + "friend-ball", + "lure-ball", + "level-ball", + "heavy-ball", + "love-ball", + "moon-ball", + }; + static const std::set RARE_BALLS{ + "sport-ball", + "safari-ball", + }; + + Xoroshiro128Plus rng(0, 0); + bool is_state_valid = false; + uint32_t num_apricorn_one = NUM_APRICORN_ONE; + uint32_t num_apricorn_two = NUM_APRICORN_TWO; + + // if there is no Sport Ball in the selected balls we ignore num_apricorn_two + bool sport_wanted = false; + for (CramomaticSelection selection : selections){ + if (selection.ball_type == CramomaticBallType::Sport){ + sport_wanted = true; + break; + } + } + + size_t iteration = 0; + uint16_t state_errors = 0; + uint16_t apricorn_selection_errors = 0; + while (num_apricorn_one > 4 && (!sport_wanted || num_apricorn_two > 2)){ + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + + // Touch the date. + if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ + env.log("Touching date to prevent rollover."); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); + touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + + env.console.log("Cram-o-matic RNG iteration: " + std::to_string(iteration)); + navigate_to_party(env, context); + context.wait_for_all_requests(); + + if (!is_state_valid){ + rng = Xoroshiro128Plus(find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES)); +// rng = Xoroshiro128Plus(100, 10000); + is_state_valid = true; + stats.reads++; + }else{ + rng = Xoroshiro128Plus(refind_rng_state(env.console, context, rng.get_state(), 0, MAX_UNKNOWN_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES)); + stats.reads++; + } + env.update_stats(); + + Xoroshiro128PlusState rng_state = rng.get_state(); + if (rng_state.s0 == 0 && rng_state.s1 == 0){ + stats.errors++; + env.update_stats(); + + state_errors++; + if (state_errors >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Detected invalid RNG state three times in a row.", + env.console + ); + } + VideoSnapshot screen = env.console.video().snapshot(); + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Detected invalid RNG state.", screen); + recover_from_wrong_state(env, context); + is_state_valid = false; + continue; + } + + CramomaticTarget target = calculate_target(env, rng.get_state(), BALL_TABLE.selected_balls()); + bool sport = target.ball_type == CramomaticBallType::Sport; + env.console.log("Needed advances: " + std::to_string(target.needed_advances)); + num_apricorn_one -= sport ? 2 : 4; + num_apricorn_two -= sport ? 2 : 0; + + do_rng_advances( + env.console, context, + rng, + target.needed_advances, + ADVANCE_PRESS_DURATION, + ADVANCE_RELEASE_DURATION + ); + leave_to_overworld_and_interact(env, context); + + try{ + choose_apricorn(env, context, sport); + }catch (OperationFailedException& e){ + stats.errors++; + env.update_stats(); + + apricorn_selection_errors++; + if (apricorn_selection_errors >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Could not detect the bag three times on a row.", + env.console + ); + } + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, e.message(), e.screenshot()); + is_state_valid = false; + recover_from_wrong_state(env, context); + continue; + } + + std::pair result = receive_ball(env, context); + + // Update ball stats. + if (!result.second.empty()){ + stats.total_balls++; + } + auto iter = APRIBALLS.find(result.second); + if (iter != APRIBALLS.end()){ + stats.apri_balls++; + } + iter = RARE_BALLS.find(result.second); + if (iter != RARE_BALLS.end()){ + stats.sport_safari_balls++; + } + + // Out of apricorns. + if (!result.first || num_apricorn_one <= 4 || (sport_wanted && num_apricorn_two <= 2)){ + throw_and_log(env.console, "Out of apricorns.", env.console); + } + + +#if 0 +// cout << "Ball Slug = " << ball << endl; + if (result.first || num_apricorn_one <= 4 || (sport_wanted && num_apricorn_two <= 2)){ + }else{ + is_state_valid = false; + stats.errors++; + } +#endif + +#if 0 + if (!ball.empty() || num_apricorn_one <= 4 || (sport_wanted && num_apricorn_two <= 2)){ + int amount = target.is_bonus ? 5 : 1; + if (target.is_bonus){ + stats.bonus++; + } + if (target.ball_type == CramomaticBallType::Apricorn){ + stats.apri_balls += amount; + }else if (target.ball_type == CramomaticBallType::Sport || target.ball_type == CramomaticBallType::Safari){ + stats.sport_safari_balls += amount; + } + stats.total_balls += amount; + }else{ + is_state_valid = false; + stats.errors++; + } +#endif + env.update_stats(); + + state_errors = 0; + apricorn_selection_errors = 0; + + iteration++; + stats.iterations++; + env.update_stats(); + } + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h index f93f12a698..d0446be41e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_CramomaticRNG.h @@ -1,85 +1,85 @@ -/* Cram-o-matic RNG Manipulation - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_CramomaticRNG_H -#define PokemonAutomation_PokemonSwSh_CramomaticRNG_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Pokemon_Xoroshiro128Plus.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class CramomaticRNG_Descriptor : public SingleSwitchProgramDescriptor{ -public: - CramomaticRNG_Descriptor(); - - class Stats; - virtual std::unique_ptr make_stats() const override; -}; - -struct CramomaticTarget{ - CramomaticBallType ball_type; - bool is_bonus; - size_t needed_advances; -}; - -class CramomaticRNG : public SingleSwitchProgramInstance{ -public: - CramomaticRNG(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - OCR::LanguageOCROption LANGUAGE; - SimpleIntegerOption NUM_APRICORN_ONE; - SimpleIntegerOption NUM_APRICORN_TWO; - SimpleIntegerOption NUM_NPCS; - CramomaticTable BALL_TABLE; - - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption MAX_PRIORITY_ADVANCES; - SimpleIntegerOption MAX_UNKNOWN_ADVANCES; - MillisecondsOption ADVANCE_PRESS_DURATION; - MillisecondsOption ADVANCE_RELEASE_DURATION; - BooleanCheckBoxOption SAVE_SCREENSHOTS; - BooleanCheckBoxOption LOG_VALUES; - - void navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - CramomaticTarget calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, std::vector wanted_balls); - void leave_to_overworld_and_interact(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void choose_apricorn(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool sport); - std::pair receive_ball(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void recover_from_wrong_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); -}; - - - - -} -} -} -#endif - - - +/* Cram-o-matic RNG Manipulation + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_CramomaticRNG_H +#define PokemonAutomation_PokemonSwSh_CramomaticRNG_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_Xoroshiro128Plus.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_CramomaticTable.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class CramomaticRNG_Descriptor : public SingleSwitchProgramDescriptor{ +public: + CramomaticRNG_Descriptor(); + + class Stats; + virtual std::unique_ptr make_stats() const override; +}; + +struct CramomaticTarget{ + CramomaticBallType ball_type; + bool is_bonus; + size_t needed_advances; +}; + +class CramomaticRNG : public SingleSwitchProgramInstance{ +public: + CramomaticRNG(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + OCR::LanguageOCROption LANGUAGE; + SimpleIntegerOption NUM_APRICORN_ONE; + SimpleIntegerOption NUM_APRICORN_TWO; + SimpleIntegerOption NUM_NPCS; + CramomaticTable BALL_TABLE; + + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption MAX_PRIORITY_ADVANCES; + SimpleIntegerOption MAX_UNKNOWN_ADVANCES; + MillisecondsOption ADVANCE_PRESS_DURATION; + MillisecondsOption ADVANCE_RELEASE_DURATION; + BooleanCheckBoxOption SAVE_SCREENSHOTS; + BooleanCheckBoxOption LOG_VALUES; + + void navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + CramomaticTarget calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, std::vector wanted_balls); + void leave_to_overworld_and_interact(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void choose_apricorn(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool sport); + std::pair receive_ball(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void recover_from_wrong_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp index 21cba2a2e7..bb62d08012 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.cpp @@ -1,580 +1,580 @@ -/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw - * - */ - -#include "CommonFramework/Exceptions/ProgramFinishedException.h" -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" -#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" -#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h" - - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - - -const DailyHighlightDatabase& DAILY_HIGHLIGHT_DATABASE() { - static DailyHighlightDatabase database("PokemonSwSh/DailyHighlights.json"); - return database; -} - - -DailyHighlightRNG_Descriptor::DailyHighlightRNG_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:DailyHighlightRNG", - STRING_POKEMON + " SwSh", "Daily Highlight RNG", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DailyHighlightRNG.md", - "Perform RNG manipulation to get rare items from the daily highlight trader.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} - -struct DailyHighlightRNG_Descriptor::Stats : public StatsTracker{ -public: - Stats() - : iterations(m_stats["Iterations"]) - , reads(m_stats["Seed Reads"]) - , errors(m_stats["Errors"]) - , highlights(m_stats["Highlights"]) - { - m_display_order.emplace_back("Iterations"); - m_display_order.emplace_back("Seed Reads"); - m_display_order.emplace_back("Highlights"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - } - -public: - std::atomic& iterations; - std::atomic& reads; - std::atomic& errors; - std::atomic& highlights; -}; -std::unique_ptr DailyHighlightRNG_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - -DailyHighlightRNG::DailyHighlightRNG() - : NUM_HIGHLIGHTS( - "Number of Highlights:
How many daily highlights should be bought.
Zero will run until you stop the program.", - LockMode::UNLOCK_WHILE_RUNNING, 0) - , FIX_TIME_WHEN_DONE( - "Fix Time when Done:
Fix the time after the program finishes.
Doesn't do anything if Number of Highlights is 0.", - LockMode::UNLOCK_WHILE_RUNNING, false) - , GO_HOME_WHEN_DONE(false) - , SAVE_INTERVAL( - "Save Every this Many Day Skips:
Zero disables saving.", - LockMode::UNLOCK_WHILE_RUNNING, - 20 - ) - , CALIBRATION_INTERAVAL( - "Calibrate the Number of NPCs this Many Day Skips:
Zero will only calibrate once.", - LockMode::UNLOCK_WHILE_RUNNING, - 10 - ) - , HIGHLIGHT_SELECTION( - "Desired Highlights:", - "Highlight", - DAILY_HIGHLIGHT_DATABASE().database(), - "dream-ball") - , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) - , NOTIFICATIONS({ - &NOTIFICATION_STATUS_UPDATE, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_RECOVERABLE, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MAX_EXPECTED_NPCS( - "Max Expected NPCs:
How many NPCs are expected in the area at most.", - LockMode::LOCK_WHILE_RUNNING, - 8 - ) - , CALIBRATION_REPEATS( - "Calibration Repeats:
How many times the number of NPCs is checked per calibration.", - LockMode::LOCK_WHILE_RUNNING, - 5 - ) - , CALIBRATION_THRESHOLD( - "Calibration Treshold:
How many NPC counts need to be the same.
This needs to be less than or equal to Calibration Repeats.", - LockMode::LOCK_WHILE_RUNNING, - 3 - ) - , MAX_UNKNOWN_ADVANCES( - "Max Unknown Advances:
How many advances to check when updating the rng state.", - LockMode::LOCK_WHILE_RUNNING, - 100000 - ) - , ADVANCE_PRESS_DURATION( - "Advance Press Duration:
Hold the button down for this long to advance once.", - LockMode::LOCK_WHILE_RUNNING, - "80 ms" - ) - , ADVANCE_RELEASE_DURATION( - "Advance Release Duration:
After releasing the button, wait this long before pressing it again.", - LockMode::LOCK_WHILE_RUNNING, - "80 ms" - ) - , SAVE_SCREENSHOTS( - "Save Debug Screenshots:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , LOG_VALUES( - "Log Animation Values:
", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - - PA_ADD_OPTION(NUM_HIGHLIGHTS); - PA_ADD_OPTION(FIX_TIME_WHEN_DONE); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(SAVE_INTERVAL); - PA_ADD_OPTION(CALIBRATION_INTERAVAL); - PA_ADD_OPTION(HIGHLIGHT_SELECTION); - - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CALIBRATION_REPEATS); - PA_ADD_OPTION(CALIBRATION_THRESHOLD); - PA_ADD_OPTION(MAX_EXPECTED_NPCS); - PA_ADD_OPTION(MAX_UNKNOWN_ADVANCES); - PA_ADD_OPTION(ADVANCE_PRESS_DURATION); - PA_ADD_OPTION(ADVANCE_RELEASE_DURATION); - PA_ADD_OPTION(SAVE_SCREENSHOTS); - PA_ADD_OPTION(LOG_VALUES); -} - -void DailyHighlightRNG::move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - pbf_move_right_joystick(context, 255, 128, 460ms, 80ms); - pbf_move_left_joystick(context, 128, 0, 1280ms, 80ms); -} - -void DailyHighlightRNG::interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - VideoOverlaySet boxes(env.console); - SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); - arrow_detector.make_overlays(boxes); - YCommIconDetector y_comm_icon_detector(true); - size_t tries = 0; - - while (true) { - if (tries >= 5) { - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Failed to talk to the trader.", - env.console - ); - } - context.wait_for_all_requests(); - int ret = wait_until(env.console, context, 500ms, { y_comm_icon_detector, arrow_detector }); - if (ret == -1 || ret == 0) { - tries++; - pbf_press_button(context, BUTTON_A, 80ms, 80ms); - } - else if (ret == 1) { - return; - } - } -} - -void DailyHighlightRNG::buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - // The player is expected to be in main dialog of the trader - env.log("Buying Highlight."); - env.console.overlay().add_log("Buying Highlight!", COLOR_WHITE); - pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); - - pbf_press_button(context, BUTTON_A, 160ms, 160ms); - context.wait_for_all_requests(); - - VideoOverlaySet boxes(env.console); - SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); - arrow_detector.make_overlays(boxes); - - int ret = run_until( - env.console, - context, - [](ProControllerContext& context) { - pbf_mash_button(context, BUTTON_A, 20000ms); - }, - { {arrow_detector} } - ); - - if (ret < 0) { - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Could not detect dialog.", - env.console - ); - } -} - -void DailyHighlightRNG::navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_wait(context, 200ms); - navigate_to_menu_app(env, env.console, context, 1, NOTIFICATION_ERROR_FATAL); - pbf_press_button(context, BUTTON_A, 80ms, 3000ms); -} - -void DailyHighlightRNG::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - env.log("Saving."); - env.console.overlay().add_log("Saving!", COLOR_WHITE); - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_wait(context, 200ms); - pbf_press_button(context, BUTTON_R, 80ms, 2000ms); - pbf_mash_button(context, BUTTON_A, 500ms); - - return_to_overworld(env, context); -} - -uint8_t DailyHighlightRNG::calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng) { - env.log("Calibrating NPC count."); - env.console.overlay().add_log("Calibrating NPC count.", COLOR_WHITE); - - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - size_t max_expected_npcs = MAX_EXPECTED_NPCS; - size_t calibration_repeats = CALIBRATION_REPEATS; - size_t calibration_threshold = CALIBRATION_THRESHOLD; - size_t finished_calibration_steps = 0; - std::vector npc_counts(max_expected_npcs, 0); - while (finished_calibration_steps < calibration_repeats) { - env.log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats)); - env.console.overlay().add_log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats), COLOR_WHITE); - - return_to_overworld(env, context); - navigate_to_party(env, context); - - Xoroshiro128PlusState state_before_menu_close(rng.get_state()); - std::pair result = refind_rng_state_and_animations(env.console, context, rng.get_state(), 0, 100, SAVE_SCREENSHOTS, LOG_VALUES); - Xoroshiro128PlusState new_state = result.first; - uint64_t additional_advances = result.second; - - // Calculate state for possible NPC counts - std::vector rng_states; - - for (uint8_t npcs = 0; npcs <= max_expected_npcs; npcs++) { - Xoroshiro128PlusState temp_state = predict_state_after_menu_close(state_before_menu_close, npcs); - Xoroshiro128Plus temp_rng(temp_state); - - // Do advances that were needed to refind current state - for (size_t i = 0; i < additional_advances; i++) { - temp_rng.next(); - } - rng_states.push_back(temp_rng.get_state()); - } - - // Compare current state to expected states - uint8_t num_npcs = 0; - uint8_t possible_choices = 0; - for (uint8_t i = 0; i <= max_expected_npcs; i++) { - if (rng_states[i].s0 == new_state.s0 && rng_states[i].s1 == new_state.s1) { - num_npcs = i; - possible_choices++; - } - } - rng.state = new_state; - - stats.reads++; - - // Add another calibration round if multiple npcs counts are possible - if (possible_choices > 1) { - env.log("NPC count is ambiguous."); - env.console.overlay().add_log("NPC count is ambiguous. Repeat calibration.", COLOR_WHITE); - continue; - } - - env.console.log("Calculated there are " + std::to_string(num_npcs) + " NPCs."); - env.console.overlay().add_log(std::to_string(num_npcs) + " NPCs", COLOR_WHITE); - npc_counts[num_npcs]++; - finished_calibration_steps++; - - if (npc_counts[num_npcs] >= calibration_threshold) { - env.console.log("Final Calibration: " + std::to_string(num_npcs) + " NPCs."); - env.console.overlay().add_log("Final Calibration: " + std::to_string(num_npcs) + " NPCs", COLOR_WHITE); - - return num_npcs; - } - } - - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "NPC is in the wrong state or an unexpected number of NPCs is in the area.", - env.console - ); -} - -size_t DailyHighlightRNG::calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights) { - Xoroshiro128Plus rng(state); - size_t advances = 0; - bool found_advance_amount = false; - - std::vector> ranges; - for (std::string slug : wanted_highlights) { - ranges.push_back(DAILY_HIGHLIGHT_DATABASE().get_range_for_slug(slug)); - } - - while (!found_advance_amount) { - // Calculate the result for the current temp_rng state - - Xoroshiro128PlusState temp_state = predict_state_after_menu_close(rng.get_state(), num_npcs); - Xoroshiro128Plus temp_rng(temp_state); - - uint64_t highlight_roll = temp_rng.nextInt(1000); - - for (auto& range : ranges) { - if (range.first <= highlight_roll && range.second >= highlight_roll) { - found_advance_amount = true; - env.console.log("Target highlight roll: " + std::to_string(highlight_roll)); - } - } - - if (!found_advance_amount) { - rng.next(); - advances++; - } - } - - return advances; -} - -void DailyHighlightRNG::prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { - env.log("Prepare player position."); - env.console.overlay().add_log("Reset Player Position.", COLOR_WHITE); - - // Open map - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_wait(context, 200ms); - navigate_to_menu_app(env, env.console, context, 5, NOTIFICATION_ERROR_RECOVERABLE); - pbf_wait(context, 200ms); - pbf_press_button(context, BUTTON_A, 160ms, 4000ms); - - // Fly to Snowslide Slope - pbf_move_left_joystick(context, 200, 210, 160ms, 160ms); - pbf_move_left_joystick(context, 150, 165, 160ms, 160ms); - pbf_mash_button(context, BUTTON_A, 1500ms); - return_to_overworld(env, context); -} - -void DailyHighlightRNG::return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection) { - context.wait_for_all_requests(); - env.console.log("Returning to the overworld."); - YCommIconDetector y_comm_icon_detector(true); - int ret = run_until( - env.console, context, - [](ProControllerContext& context) { - pbf_mash_button(context, BUTTON_B, 20000ms); - }, - { {y_comm_icon_detector} } - ); - if (ret != 0) { - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - stats.errors++; - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Cannot detect the Y-Comm icon.", - env.console - ); - } - - // Sometimes Y-Comm is detected before button presses are accepted again - if (wait_after_detection) { - context.wait_for(300ms); - } -} - -void DailyHighlightRNG::advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year) { - context.wait_for(200ms); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - home_to_date_time(env.console, context, true); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - context.wait_for_all_requests(); - - VideoOverlaySet overlays(env.console.overlay()); - DateChangeWatcher date_reader(env.console); - date_reader.make_overlays(overlays); - - DateTime date{ 2000, 12, 31, 1, 0, 0 }; // 31st December for fixed Normal weather - - if (year >= MAX_YEAR) { - date_reader.set_date(env.program_info(), env.console, context, date); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - year = 1; - } - - date.year += year; - date_reader.set_date(env.program_info(), env.console, context, date); - pbf_press_button(context, BUTTON_A, 160ms, 240ms); - - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context, false); - year++; -} - - -void DailyHighlightRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - std::vector wanted_highlights = HIGHLIGHT_SELECTION.all_slugs(); - if (wanted_highlights.empty()){ - throw UserSetupError(env.console, "At least one highlight item needs to be selected!"); - } - - if (START_LOCATION.start_in_grip_menu()) { - grip_menu_connect_go_home(context); - } - else { - pbf_press_button(context, BUTTON_B, 80ms, 80ms); - } - - - Xoroshiro128Plus rng(0, 0); - uint8_t num_npcs = 0; - size_t iterations = 0; - size_t assumed_successful_iterations = 0; - size_t bought_highlights = 0; - uint8_t year = MAX_YEAR; - uint16_t state_errors = 0; - - while (bought_highlights < NUM_HIGHLIGHTS || NUM_HIGHLIGHTS <= 0){ - iterations++; - stats.iterations++; - env.update_stats(); - send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); - env.console.log("Daily Highlight RNG iteration: " + std::to_string(iterations)); - env.console.overlay().add_log("Iteration: " + std::to_string(iterations), COLOR_WHITE); - - if (SAVE_INTERVAL > 0 && iterations % SAVE_INTERVAL == 0) { - save_game(env, context); - } - - return_to_overworld(env, context); - - if (assumed_successful_iterations <= 0) { - prepare_game_state(env, context); - - // open and close the menu and immediately walk to the trader - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - return_to_overworld(env, context); - move_to_trader(env, context); - interact_with_trader(env, context); - - return_to_overworld(env, context); - } - - advance_date(env, context, year); - navigate_to_party(env, context); - context.wait_for_all_requests(); - - // (Re-)Find RNG state - if (assumed_successful_iterations <= 0) { - env.log("Finding initial rng state."); - env.console.overlay().add_log("Initial RNG state:", COLOR_WHITE); - rng = Xoroshiro128Plus(find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES)); - stats.reads++; - } else { - env.log("Refinding rng state."); - env.console.overlay().add_log("New RNG state:", COLOR_WHITE); - rng = Xoroshiro128Plus(refind_rng_state(env.console, context, rng.get_state(), 0, MAX_UNKNOWN_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES)); - stats.reads++; - } - - Xoroshiro128PlusState rng_state = rng.get_state(); - if (rng_state.s0 == 0 && rng_state.s1 == 0){ - stats.errors++; - env.update_stats(); - - state_errors++; - if (state_errors >= 3){ - OperationFailedException::fire( - ErrorReport::SEND_ERROR_REPORT, - "Detected invalid RNG state three times in a row.", - env.console - ); - } - VideoSnapshot screen = env.console.video().snapshot(); - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Detected invalid RNG state.", screen); - assumed_successful_iterations = 0; - continue; - } - - // Calibrate number of NPCs in the area and check whether the trader is in the slow state - if ((CALIBRATION_INTERAVAL > 0 && assumed_successful_iterations % CALIBRATION_INTERAVAL == 0) || assumed_successful_iterations <= 0) { - try { - num_npcs = calibrate_num_npc_from_party(env, context, rng); - } - catch (OperationFailedException& exception) { - send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, exception.message(), exception.screenshot()); - assumed_successful_iterations = 0; - stats.errors++; - continue; - } - } - - // Do required advances - size_t target_advances = calculate_target(env, rng.get_state(), num_npcs, HIGHLIGHT_SELECTION.all_slugs()); - env.console.log("Needed advances: " + std::to_string(target_advances)); - do_rng_advances(env.console, context, rng, target_advances, ADVANCE_PRESS_DURATION, ADVANCE_RELEASE_DURATION); - - // Talk to NPC and buy highlight - return_to_overworld(env, context, false); - interact_with_trader(env, context); - if (assumed_successful_iterations >= 2) { - buy_highlight(env, context); - bought_highlights++; - stats.highlights++; - } - return_to_overworld(env, context); - - env.update_stats(); - assumed_successful_iterations++; - state_errors = 0; - } - - if (FIX_TIME_WHEN_DONE) { - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_A, 20, 105); - pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_from_home(env.console, context); - } - GO_HOME_WHEN_DONE.run_end_of_program(context); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, "Finished buying " + std::to_string(bought_highlights) + " daily highlights!", env.console.video().snapshot()); -} - - -} -} -} +/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw + * + */ + +#include "CommonFramework/Exceptions/ProgramFinishedException.h" +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "NintendoSwitch/Programs/DateManip/NintendoSwitch_DateManip.h" +#include "NintendoSwitch/Programs/NintendoSwitch_GameEntry.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SelectionArrowFinder.h" +#include "PokemonSwSh/Inference/PokemonSwSh_YCommDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_MenuNavigation.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h" + + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + + +const DailyHighlightDatabase& DAILY_HIGHLIGHT_DATABASE() { + static DailyHighlightDatabase database("PokemonSwSh/DailyHighlights.json"); + return database; +} + + +DailyHighlightRNG_Descriptor::DailyHighlightRNG_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:DailyHighlightRNG", + STRING_POKEMON + " SwSh", "Daily Highlight RNG", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/DailyHighlightRNG.md", + "Perform RNG manipulation to get rare items from the daily highlight trader.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} + +struct DailyHighlightRNG_Descriptor::Stats : public StatsTracker{ +public: + Stats() + : iterations(m_stats["Iterations"]) + , reads(m_stats["Seed Reads"]) + , errors(m_stats["Errors"]) + , highlights(m_stats["Highlights"]) + { + m_display_order.emplace_back("Iterations"); + m_display_order.emplace_back("Seed Reads"); + m_display_order.emplace_back("Highlights"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + } + +public: + std::atomic& iterations; + std::atomic& reads; + std::atomic& errors; + std::atomic& highlights; +}; +std::unique_ptr DailyHighlightRNG_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + +DailyHighlightRNG::DailyHighlightRNG() + : NUM_HIGHLIGHTS( + "Number of Highlights:
How many daily highlights should be bought.
Zero will run until you stop the program.", + LockMode::UNLOCK_WHILE_RUNNING, 0) + , FIX_TIME_WHEN_DONE( + "Fix Time when Done:
Fix the time after the program finishes.
Doesn't do anything if Number of Highlights is 0.", + LockMode::UNLOCK_WHILE_RUNNING, false) + , GO_HOME_WHEN_DONE(false) + , SAVE_INTERVAL( + "Save Every this Many Day Skips:
Zero disables saving.", + LockMode::UNLOCK_WHILE_RUNNING, + 20 + ) + , CALIBRATION_INTERAVAL( + "Calibrate the Number of NPCs this Many Day Skips:
Zero will only calibrate once.", + LockMode::UNLOCK_WHILE_RUNNING, + 10 + ) + , HIGHLIGHT_SELECTION( + "Desired Highlights:", + "Highlight", + DAILY_HIGHLIGHT_DATABASE().database(), + "dream-ball") + , NOTIFICATION_STATUS_UPDATE("Status Update", true, false, std::chrono::seconds(3600)) + , NOTIFICATIONS({ + &NOTIFICATION_STATUS_UPDATE, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_RECOVERABLE, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MAX_EXPECTED_NPCS( + "Max Expected NPCs:
How many NPCs are expected in the area at most.", + LockMode::LOCK_WHILE_RUNNING, + 8 + ) + , CALIBRATION_REPEATS( + "Calibration Repeats:
How many times the number of NPCs is checked per calibration.", + LockMode::LOCK_WHILE_RUNNING, + 5 + ) + , CALIBRATION_THRESHOLD( + "Calibration Treshold:
How many NPC counts need to be the same.
This needs to be less than or equal to Calibration Repeats.", + LockMode::LOCK_WHILE_RUNNING, + 3 + ) + , MAX_UNKNOWN_ADVANCES( + "Max Unknown Advances:
How many advances to check when updating the rng state.", + LockMode::LOCK_WHILE_RUNNING, + 100000 + ) + , ADVANCE_PRESS_DURATION( + "Advance Press Duration:
Hold the button down for this long to advance once.", + LockMode::LOCK_WHILE_RUNNING, + "80 ms" + ) + , ADVANCE_RELEASE_DURATION( + "Advance Release Duration:
After releasing the button, wait this long before pressing it again.", + LockMode::LOCK_WHILE_RUNNING, + "80 ms" + ) + , SAVE_SCREENSHOTS( + "Save Debug Screenshots:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , LOG_VALUES( + "Log Animation Values:
", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + + PA_ADD_OPTION(NUM_HIGHLIGHTS); + PA_ADD_OPTION(FIX_TIME_WHEN_DONE); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(SAVE_INTERVAL); + PA_ADD_OPTION(CALIBRATION_INTERAVAL); + PA_ADD_OPTION(HIGHLIGHT_SELECTION); + + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CALIBRATION_REPEATS); + PA_ADD_OPTION(CALIBRATION_THRESHOLD); + PA_ADD_OPTION(MAX_EXPECTED_NPCS); + PA_ADD_OPTION(MAX_UNKNOWN_ADVANCES); + PA_ADD_OPTION(ADVANCE_PRESS_DURATION); + PA_ADD_OPTION(ADVANCE_RELEASE_DURATION); + PA_ADD_OPTION(SAVE_SCREENSHOTS); + PA_ADD_OPTION(LOG_VALUES); +} + +void DailyHighlightRNG::move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + pbf_move_right_joystick(context, 255, 128, 460ms, 80ms); + pbf_move_left_joystick(context, 128, 0, 1280ms, 80ms); +} + +void DailyHighlightRNG::interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + VideoOverlaySet boxes(env.console); + SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); + arrow_detector.make_overlays(boxes); + YCommIconDetector y_comm_icon_detector(true); + size_t tries = 0; + + while (true) { + if (tries >= 5) { + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Failed to talk to the trader.", + env.console + ); + } + context.wait_for_all_requests(); + int ret = wait_until(env.console, context, 500ms, { y_comm_icon_detector, arrow_detector }); + if (ret == -1 || ret == 0) { + tries++; + pbf_press_button(context, BUTTON_A, 80ms, 80ms); + } + else if (ret == 1) { + return; + } + } +} + +void DailyHighlightRNG::buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + // The player is expected to be in main dialog of the trader + env.log("Buying Highlight."); + env.console.overlay().add_log("Buying Highlight!", COLOR_WHITE); + pbf_press_dpad(context, DPAD_DOWN, 160ms, 160ms); + + pbf_press_button(context, BUTTON_A, 160ms, 160ms); + context.wait_for_all_requests(); + + VideoOverlaySet boxes(env.console); + SelectionArrowFinder arrow_detector(env.console, ImageFloatBox(0.5, 0.58, 0.2, 0.08)); + arrow_detector.make_overlays(boxes); + + int ret = run_until( + env.console, + context, + [](ProControllerContext& context) { + pbf_mash_button(context, BUTTON_A, 20000ms); + }, + { {arrow_detector} } + ); + + if (ret < 0) { + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Could not detect dialog.", + env.console + ); + } +} + +void DailyHighlightRNG::navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_wait(context, 200ms); + navigate_to_menu_app(env, env.console, context, 1, NOTIFICATION_ERROR_FATAL); + pbf_press_button(context, BUTTON_A, 80ms, 3000ms); +} + +void DailyHighlightRNG::save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + env.log("Saving."); + env.console.overlay().add_log("Saving!", COLOR_WHITE); + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_wait(context, 200ms); + pbf_press_button(context, BUTTON_R, 80ms, 2000ms); + pbf_mash_button(context, BUTTON_A, 500ms); + + return_to_overworld(env, context); +} + +uint8_t DailyHighlightRNG::calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng) { + env.log("Calibrating NPC count."); + env.console.overlay().add_log("Calibrating NPC count.", COLOR_WHITE); + + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + size_t max_expected_npcs = MAX_EXPECTED_NPCS; + size_t calibration_repeats = CALIBRATION_REPEATS; + size_t calibration_threshold = CALIBRATION_THRESHOLD; + size_t finished_calibration_steps = 0; + std::vector npc_counts(max_expected_npcs, 0); + while (finished_calibration_steps < calibration_repeats) { + env.log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats)); + env.console.overlay().add_log("Calibration: " + std::to_string(finished_calibration_steps+1) + "/" + std::to_string(calibration_repeats), COLOR_WHITE); + + return_to_overworld(env, context); + navigate_to_party(env, context); + + Xoroshiro128PlusState state_before_menu_close(rng.get_state()); + std::pair result = refind_rng_state_and_animations(env.console, context, rng.get_state(), 0, 100, SAVE_SCREENSHOTS, LOG_VALUES); + Xoroshiro128PlusState new_state = result.first; + uint64_t additional_advances = result.second; + + // Calculate state for possible NPC counts + std::vector rng_states; + + for (uint8_t npcs = 0; npcs <= max_expected_npcs; npcs++) { + Xoroshiro128PlusState temp_state = predict_state_after_menu_close(state_before_menu_close, npcs); + Xoroshiro128Plus temp_rng(temp_state); + + // Do advances that were needed to refind current state + for (size_t i = 0; i < additional_advances; i++) { + temp_rng.next(); + } + rng_states.push_back(temp_rng.get_state()); + } + + // Compare current state to expected states + uint8_t num_npcs = 0; + uint8_t possible_choices = 0; + for (uint8_t i = 0; i <= max_expected_npcs; i++) { + if (rng_states[i].s0 == new_state.s0 && rng_states[i].s1 == new_state.s1) { + num_npcs = i; + possible_choices++; + } + } + rng.state = new_state; + + stats.reads++; + + // Add another calibration round if multiple npcs counts are possible + if (possible_choices > 1) { + env.log("NPC count is ambiguous."); + env.console.overlay().add_log("NPC count is ambiguous. Repeat calibration.", COLOR_WHITE); + continue; + } + + env.console.log("Calculated there are " + std::to_string(num_npcs) + " NPCs."); + env.console.overlay().add_log(std::to_string(num_npcs) + " NPCs", COLOR_WHITE); + npc_counts[num_npcs]++; + finished_calibration_steps++; + + if (npc_counts[num_npcs] >= calibration_threshold) { + env.console.log("Final Calibration: " + std::to_string(num_npcs) + " NPCs."); + env.console.overlay().add_log("Final Calibration: " + std::to_string(num_npcs) + " NPCs", COLOR_WHITE); + + return num_npcs; + } + } + + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "NPC is in the wrong state or an unexpected number of NPCs is in the area.", + env.console + ); +} + +size_t DailyHighlightRNG::calculate_target(SingleSwitchProgramEnvironment& env, Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights) { + Xoroshiro128Plus rng(state); + size_t advances = 0; + bool found_advance_amount = false; + + std::vector> ranges; + for (std::string slug : wanted_highlights) { + ranges.push_back(DAILY_HIGHLIGHT_DATABASE().get_range_for_slug(slug)); + } + + while (!found_advance_amount) { + // Calculate the result for the current temp_rng state + + Xoroshiro128PlusState temp_state = predict_state_after_menu_close(rng.get_state(), num_npcs); + Xoroshiro128Plus temp_rng(temp_state); + + uint64_t highlight_roll = temp_rng.nextInt(1000); + + for (auto& range : ranges) { + if (range.first <= highlight_roll && range.second >= highlight_roll) { + found_advance_amount = true; + env.console.log("Target highlight roll: " + std::to_string(highlight_roll)); + } + } + + if (!found_advance_amount) { + rng.next(); + advances++; + } + } + + return advances; +} + +void DailyHighlightRNG::prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context) { + env.log("Prepare player position."); + env.console.overlay().add_log("Reset Player Position.", COLOR_WHITE); + + // Open map + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_wait(context, 200ms); + navigate_to_menu_app(env, env.console, context, 5, NOTIFICATION_ERROR_RECOVERABLE); + pbf_wait(context, 200ms); + pbf_press_button(context, BUTTON_A, 160ms, 4000ms); + + // Fly to Snowslide Slope + pbf_move_left_joystick(context, 200, 210, 160ms, 160ms); + pbf_move_left_joystick(context, 150, 165, 160ms, 160ms); + pbf_mash_button(context, BUTTON_A, 1500ms); + return_to_overworld(env, context); +} + +void DailyHighlightRNG::return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection) { + context.wait_for_all_requests(); + env.console.log("Returning to the overworld."); + YCommIconDetector y_comm_icon_detector(true); + int ret = run_until( + env.console, context, + [](ProControllerContext& context) { + pbf_mash_button(context, BUTTON_B, 20000ms); + }, + { {y_comm_icon_detector} } + ); + if (ret != 0) { + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + stats.errors++; + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Cannot detect the Y-Comm icon.", + env.console + ); + } + + // Sometimes Y-Comm is detected before button presses are accepted again + if (wait_after_detection) { + context.wait_for(300ms); + } +} + +void DailyHighlightRNG::advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year) { + context.wait_for(200ms); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + home_to_date_time(env.console, context, true); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + context.wait_for_all_requests(); + + VideoOverlaySet overlays(env.console.overlay()); + DateChangeWatcher date_reader(env.console); + date_reader.make_overlays(overlays); + + DateTime date{ 2000, 12, 31, 1, 0, 0 }; // 31st December for fixed Normal weather + + if (year >= MAX_YEAR) { + date_reader.set_date(env.program_info(), env.console, context, date); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + year = 1; + } + + date.year += year; + date_reader.set_date(env.program_info(), env.console, context, date); + pbf_press_button(context, BUTTON_A, 160ms, 240ms); + + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context, false); + year++; +} + + +void DailyHighlightRNG::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + DailyHighlightRNG_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + std::vector wanted_highlights = HIGHLIGHT_SELECTION.all_slugs(); + if (wanted_highlights.empty()){ + throw UserSetupError(env.console, "At least one highlight item needs to be selected!"); + } + + if (START_LOCATION.start_in_grip_menu()) { + grip_menu_connect_go_home(context); + } + else { + pbf_press_button(context, BUTTON_B, 80ms, 80ms); + } + + + Xoroshiro128Plus rng(0, 0); + uint8_t num_npcs = 0; + size_t iterations = 0; + size_t assumed_successful_iterations = 0; + size_t bought_highlights = 0; + uint8_t year = MAX_YEAR; + uint16_t state_errors = 0; + + while (bought_highlights < NUM_HIGHLIGHTS || NUM_HIGHLIGHTS <= 0){ + iterations++; + stats.iterations++; + env.update_stats(); + send_program_status_notification(env, NOTIFICATION_STATUS_UPDATE); + env.console.log("Daily Highlight RNG iteration: " + std::to_string(iterations)); + env.console.overlay().add_log("Iteration: " + std::to_string(iterations), COLOR_WHITE); + + if (SAVE_INTERVAL > 0 && iterations % SAVE_INTERVAL == 0) { + save_game(env, context); + } + + return_to_overworld(env, context); + + if (assumed_successful_iterations <= 0) { + prepare_game_state(env, context); + + // open and close the menu and immediately walk to the trader + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + return_to_overworld(env, context); + move_to_trader(env, context); + interact_with_trader(env, context); + + return_to_overworld(env, context); + } + + advance_date(env, context, year); + navigate_to_party(env, context); + context.wait_for_all_requests(); + + // (Re-)Find RNG state + if (assumed_successful_iterations <= 0) { + env.log("Finding initial rng state."); + env.console.overlay().add_log("Initial RNG state:", COLOR_WHITE); + rng = Xoroshiro128Plus(find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES)); + stats.reads++; + } else { + env.log("Refinding rng state."); + env.console.overlay().add_log("New RNG state:", COLOR_WHITE); + rng = Xoroshiro128Plus(refind_rng_state(env.console, context, rng.get_state(), 0, MAX_UNKNOWN_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES)); + stats.reads++; + } + + Xoroshiro128PlusState rng_state = rng.get_state(); + if (rng_state.s0 == 0 && rng_state.s1 == 0){ + stats.errors++; + env.update_stats(); + + state_errors++; + if (state_errors >= 3){ + OperationFailedException::fire( + ErrorReport::SEND_ERROR_REPORT, + "Detected invalid RNG state three times in a row.", + env.console + ); + } + VideoSnapshot screen = env.console.video().snapshot(); + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, "Detected invalid RNG state.", screen); + assumed_successful_iterations = 0; + continue; + } + + // Calibrate number of NPCs in the area and check whether the trader is in the slow state + if ((CALIBRATION_INTERAVAL > 0 && assumed_successful_iterations % CALIBRATION_INTERAVAL == 0) || assumed_successful_iterations <= 0) { + try { + num_npcs = calibrate_num_npc_from_party(env, context, rng); + } + catch (OperationFailedException& exception) { + send_program_recoverable_error_notification(env, NOTIFICATION_ERROR_RECOVERABLE, exception.message(), exception.screenshot()); + assumed_successful_iterations = 0; + stats.errors++; + continue; + } + } + + // Do required advances + size_t target_advances = calculate_target(env, rng.get_state(), num_npcs, HIGHLIGHT_SELECTION.all_slugs()); + env.console.log("Needed advances: " + std::to_string(target_advances)); + do_rng_advances(env.console, context, rng, target_advances, ADVANCE_PRESS_DURATION, ADVANCE_RELEASE_DURATION); + + // Talk to NPC and buy highlight + return_to_overworld(env, context, false); + interact_with_trader(env, context); + if (assumed_successful_iterations >= 2) { + buy_highlight(env, context); + bought_highlights++; + stats.highlights++; + } + return_to_overworld(env, context); + + env.update_stats(); + assumed_successful_iterations++; + state_errors = 0; + } + + if (FIX_TIME_WHEN_DONE) { + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_A, 20, 105); + pbf_press_button(context, BUTTON_HOME, 160ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_from_home(env.console, context); + } + GO_HOME_WHEN_DONE.run_end_of_program(context); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH, "Finished buying " + std::to_string(bought_highlights) + " daily highlights!", env.console.video().snapshot()); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h index 5bbc37a1d8..3176a3923e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_DailyHighlightRNG.h @@ -1,88 +1,88 @@ -/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw/htmlview - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H -#define PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "CommonTools/Options/LanguageOCROption.h" -#include "CommonTools/Options/StringSelectTableOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Pokemon_Xoroshiro128Plus.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class DailyHighlightRNG_Descriptor : public SingleSwitchProgramDescriptor{ -public: - DailyHighlightRNG_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - -class DailyHighlightRNG : public SingleSwitchProgramInstance{ -public: - DailyHighlightRNG(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - SimpleIntegerOption NUM_HIGHLIGHTS; - BooleanCheckBoxOption FIX_TIME_WHEN_DONE; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - SimpleIntegerOption SAVE_INTERVAL; - SimpleIntegerOption CALIBRATION_INTERAVAL; - StringSelectTableOption HIGHLIGHT_SELECTION; - - EventNotificationOption NOTIFICATION_STATUS_UPDATE; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - SimpleIntegerOption MAX_EXPECTED_NPCS; - SimpleIntegerOption CALIBRATION_REPEATS; - SimpleIntegerOption CALIBRATION_THRESHOLD; - SimpleIntegerOption MAX_UNKNOWN_ADVANCES; - MillisecondsOption ADVANCE_PRESS_DURATION; - MillisecondsOption ADVANCE_RELEASE_DURATION; - BooleanCheckBoxOption SAVE_SCREENSHOTS; - BooleanCheckBoxOption LOG_VALUES; - - void move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection = true); - void buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - uint8_t calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng); - void navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - size_t calculate_target(SingleSwitchProgramEnvironment& env, Pokemon::Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights); - void prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); - void advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year); -}; - - - - -} -} -} -#endif - - - +/* RNG Manipulation of the Highlight Watt Trader in the Snowslide Slope area in the Crown Tundra + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + * Based on Anubis' findings: https://docs.google.com/spreadsheets/u/0/d/1pNYtCJKRh_efX9LvzjCiA-0n2lGSFnVmSWwmPzgSOMw/htmlview + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H +#define PokemonAutomation_PokemonSwSh_DailyHighlightRNG_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "CommonTools/Options/LanguageOCROption.h" +#include "CommonTools/Options/StringSelectTableOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Pokemon_Xoroshiro128Plus.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class DailyHighlightRNG_Descriptor : public SingleSwitchProgramDescriptor{ +public: + DailyHighlightRNG_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + +class DailyHighlightRNG : public SingleSwitchProgramInstance{ +public: + DailyHighlightRNG(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + SimpleIntegerOption NUM_HIGHLIGHTS; + BooleanCheckBoxOption FIX_TIME_WHEN_DONE; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + SimpleIntegerOption SAVE_INTERVAL; + SimpleIntegerOption CALIBRATION_INTERAVAL; + StringSelectTableOption HIGHLIGHT_SELECTION; + + EventNotificationOption NOTIFICATION_STATUS_UPDATE; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + SimpleIntegerOption MAX_EXPECTED_NPCS; + SimpleIntegerOption CALIBRATION_REPEATS; + SimpleIntegerOption CALIBRATION_THRESHOLD; + SimpleIntegerOption MAX_UNKNOWN_ADVANCES; + MillisecondsOption ADVANCE_PRESS_DURATION; + MillisecondsOption ADVANCE_RELEASE_DURATION; + BooleanCheckBoxOption SAVE_SCREENSHOTS; + BooleanCheckBoxOption LOG_VALUES; + + void move_to_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void interact_with_trader(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void return_to_overworld(SingleSwitchProgramEnvironment& env, ProControllerContext& context, bool wait_after_detection = true); + void buy_highlight(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + uint8_t calibrate_num_npc_from_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context, Pokemon::Xoroshiro128Plus& rng); + void navigate_to_party(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + size_t calculate_target(SingleSwitchProgramEnvironment& env, Pokemon::Xoroshiro128PlusState state, uint8_t num_npcs, std::vector wanted_highlights); + void prepare_game_state(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void save_game(SingleSwitchProgramEnvironment& env, ProControllerContext& context); + void advance_date(SingleSwitchProgramEnvironment& env, ProControllerContext& context, uint8_t& year); +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.cpp index 2287478f13..979c78f60c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.cpp @@ -1,138 +1,138 @@ -/* RNG Manipulation SeedFinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/PrettyPrint.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" -#include "PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h" - -#include - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -using namespace Pokemon; - -SeedFinder_Descriptor::SeedFinder_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:SeedFinder", - STRING_POKEMON + " SwSh", "Seed Finder", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/SeedFinder.md", - "Finds the current state to be used for manual RNG manipulation.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - -SeedFinder::SeedFinder() - : STATE_0( - false, - "state[0]:", - LockMode::LOCK_WHILE_RUNNING, - "", - "" - ) - , STATE_1( - false, - "state[1]:", - LockMode::LOCK_WHILE_RUNNING, - "", - "" - ) - , UPDATE_STATE( - "Update State:
Use the last known state to update the rng state.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , MIN_ADVANCES( - "Min Advances:", - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , MAX_ADVANCES( - "Max Advances:", - LockMode::LOCK_WHILE_RUNNING, - 10000 - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , SAVE_SCREENSHOTS( - "Save Debug Screenshots:", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , LOG_VALUES( - "Log Animation Values:
", - LockMode::LOCK_WHILE_RUNNING, - false - ) - -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(STATE_0); - PA_ADD_OPTION(STATE_1); - PA_ADD_OPTION(UPDATE_STATE); - PA_ADD_OPTION(MIN_ADVANCES); - PA_ADD_OPTION(MAX_ADVANCES); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(SAVE_SCREENSHOTS); - PA_ADD_OPTION(LOG_VALUES); -} - - - -void SeedFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - Xoroshiro128PlusState state(0, 0); - // sanitize STATE_0 and STATE_1 and make ints - if (UPDATE_STATE){ - try{ - state.s0 = std::stoull(STATE_0, nullptr, 16); - state.s1 = std::stoull(STATE_1, nullptr, 16); - }catch (std::invalid_argument&){ - throw UserSetupError(env.console, "State is invalid."); - }catch (std::out_of_range&){ - throw UserSetupError(env.console, "State is invalid. Are there any extra characters?"); - } - - // clean up STATE_0 and STATE_1 - env.console.log("Known state: " + tostr_hex(state.s0)); - env.console.log("Known state: " + tostr_hex(state.s1)); - STATE_0.set(tostr_hex(state.s0)); - STATE_1.set(tostr_hex(state.s1)); - } - - - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_dpad(context, DPAD_LEFT, 5, 5); - } - - - if (UPDATE_STATE){ - state = refind_rng_state(env.console, context, state, MIN_ADVANCES, MAX_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES); - }else{ - state = find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES); - } - - // show state to the user - STATE_0.set(tostr_hex(state.s0)); - STATE_1.set(tostr_hex(state.s1)); -} - - -} -} -} +/* RNG Manipulation SeedFinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_BasicRNG.h" +#include "PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h" + +#include + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +using namespace Pokemon; + +SeedFinder_Descriptor::SeedFinder_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:SeedFinder", + STRING_POKEMON + " SwSh", "Seed Finder", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/SeedFinder.md", + "Finds the current state to be used for manual RNG manipulation.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + +SeedFinder::SeedFinder() + : STATE_0( + false, + "state[0]:", + LockMode::LOCK_WHILE_RUNNING, + "", + "" + ) + , STATE_1( + false, + "state[1]:", + LockMode::LOCK_WHILE_RUNNING, + "", + "" + ) + , UPDATE_STATE( + "Update State:
Use the last known state to update the rng state.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , MIN_ADVANCES( + "Min Advances:", + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , MAX_ADVANCES( + "Max Advances:", + LockMode::LOCK_WHILE_RUNNING, + 10000 + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , SAVE_SCREENSHOTS( + "Save Debug Screenshots:", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , LOG_VALUES( + "Log Animation Values:
", + LockMode::LOCK_WHILE_RUNNING, + false + ) + +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(STATE_0); + PA_ADD_OPTION(STATE_1); + PA_ADD_OPTION(UPDATE_STATE); + PA_ADD_OPTION(MIN_ADVANCES); + PA_ADD_OPTION(MAX_ADVANCES); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(SAVE_SCREENSHOTS); + PA_ADD_OPTION(LOG_VALUES); +} + + + +void SeedFinder::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + Xoroshiro128PlusState state(0, 0); + // sanitize STATE_0 and STATE_1 and make ints + if (UPDATE_STATE){ + try{ + state.s0 = std::stoull(STATE_0, nullptr, 16); + state.s1 = std::stoull(STATE_1, nullptr, 16); + }catch (std::invalid_argument&){ + throw UserSetupError(env.console, "State is invalid."); + }catch (std::out_of_range&){ + throw UserSetupError(env.console, "State is invalid. Are there any extra characters?"); + } + + // clean up STATE_0 and STATE_1 + env.console.log("Known state: " + tostr_hex(state.s0)); + env.console.log("Known state: " + tostr_hex(state.s1)); + STATE_0.set(tostr_hex(state.s0)); + STATE_1.set(tostr_hex(state.s1)); + } + + + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_dpad(context, DPAD_LEFT, 5, 5); + } + + + if (UPDATE_STATE){ + state = refind_rng_state(env.console, context, state, MIN_ADVANCES, MAX_ADVANCES, SAVE_SCREENSHOTS, LOG_VALUES); + }else{ + state = find_rng_state(env.console, context, SAVE_SCREENSHOTS, LOG_VALUES); + } + + // show state to the user + STATE_0.set(tostr_hex(state.s0)); + STATE_1.set(tostr_hex(state.s1)); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h index ecf12d8529..d72b881cc3 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/RNG/PokemonSwSh_SeedFinder.h @@ -1,56 +1,56 @@ -/* RNG Manipulation SeedFinder - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_SeedFinder_H -#define PokemonAutomation_PokemonSwSh_SeedFinder_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/StringOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -class SeedFinder_Descriptor : public SingleSwitchProgramDescriptor{ -public: - SeedFinder_Descriptor(); -}; - - -class SeedFinder : public SingleSwitchProgramInstance{ -public: - SeedFinder(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - - StringOption STATE_0; - StringOption STATE_1; - BooleanCheckBoxOption UPDATE_STATE; - SimpleIntegerOption MIN_ADVANCES; - SimpleIntegerOption MAX_ADVANCES; - - SectionDividerOption m_advanced_options; - BooleanCheckBoxOption SAVE_SCREENSHOTS; - BooleanCheckBoxOption LOG_VALUES; -}; - - - - -} -} -} -#endif - - - +/* RNG Manipulation SeedFinder + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_SeedFinder_H +#define PokemonAutomation_PokemonSwSh_SeedFinder_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/StringOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +class SeedFinder_Descriptor : public SingleSwitchProgramDescriptor{ +public: + SeedFinder_Descriptor(); +}; + + +class SeedFinder : public SingleSwitchProgramInstance{ +public: + SeedFinder(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + + StringOption STATE_0; + StringOption STATE_1; + BooleanCheckBoxOption UPDATE_STATE; + SimpleIntegerOption MIN_ADVANCES; + SimpleIntegerOption MAX_ADVANCES; + + SectionDividerOption m_advanced_options; + BooleanCheckBoxOption SAVE_SCREENSHOTS; + BooleanCheckBoxOption LOG_VALUES; +}; + + + + +} +} +} +#endif + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.cpp index cd859f76b8..50dc478979 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.cpp @@ -1,180 +1,180 @@ -/* Shiny Hunt Autonomous - Berry Tree - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_ShinyHuntAutonomous-BerryTree.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousBerryTree_Descriptor::ShinyHuntAutonomousBerryTree_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousBerryTree", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Berry Tree", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-BerryTree.md", - "Automatically hunt for shiny berry tree " + STRING_POKEMON + " using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::MUCH_FASTER - ) -{} -std::unique_ptr ShinyHuntAutonomousBerryTree_Descriptor::make_stats() const{ - return std::unique_ptr(new ShinyHuntTracker(true)); -} - - - -ShinyHuntAutonomousBerryTree::ShinyHuntAutonomousBerryTree() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(false, true) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -} - - - - -void ShinyHuntAutonomousBerryTree::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - ShinyHuntTracker& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - uint8_t year = MAX_YEAR; - while (true){ - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - home_roll_date_enter_game_autorollback(env.console, context, year); -// home_to_date_time(context, true, true); -// neutral_date_skip(context); -// settings_to_enter_game(context, true); - pbf_mash_button(context, BUTTON_B, 90); - context.wait_for_all_requests(); - - { - StandardBattleMenuWatcher battle_menu_detector(false); - StartBattleWatcher start_battle_detector; - - int result = run_until( - env.console, context, - [](ProControllerContext& context){ - pbf_mash_button(context, BUTTON_A, 60s); - }, - { - {battle_menu_detector}, - {start_battle_detector}, - } - ); - - switch (result){ - case 0: - env.log("Unexpected battle menu.", COLOR_RED); - stats.add_error(); - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 1000ms); - run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); - continue; - case 1: - env.log("Battle started!"); - break; - default: - stats.add_error(); - env.update_stats(); - env.log("Timed out."); - continue; - } - } - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); - - bool stop = handler.handle_standard_encounter_end_battle( - result, EXIT_BATTLE_TIMEOUT0 - ); - if (stop){ - break; - } -// pbf_mash_button(context, BUTTON_B, 10s); - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - - home_to_date_time(env.console, context, false); - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_press_button(context, BUTTON_A, 5, 10); - pbf_press_button(context, BUTTON_HOME, 80ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - - if (!GO_HOME_WHEN_DONE){ - pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); -} - - - - -} -} -} +/* Shiny Hunt Autonomous - Berry Tree + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Programs/DateSpam/NintendoSwitch_HomeToDateTime.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_ShinyHuntAutonomous-BerryTree.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousBerryTree_Descriptor::ShinyHuntAutonomousBerryTree_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousBerryTree", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Berry Tree", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-BerryTree.md", + "Automatically hunt for shiny berry tree " + STRING_POKEMON + " using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::MUCH_FASTER + ) +{} +std::unique_ptr ShinyHuntAutonomousBerryTree_Descriptor::make_stats() const{ + return std::unique_ptr(new ShinyHuntTracker(true)); +} + + + +ShinyHuntAutonomousBerryTree::ShinyHuntAutonomousBerryTree() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(false, true) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +} + + + + +void ShinyHuntAutonomousBerryTree::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + ShinyHuntTracker& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + uint8_t year = MAX_YEAR; + while (true){ + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + home_roll_date_enter_game_autorollback(env.console, context, year); +// home_to_date_time(context, true, true); +// neutral_date_skip(context); +// settings_to_enter_game(context, true); + pbf_mash_button(context, BUTTON_B, 90); + context.wait_for_all_requests(); + + { + StandardBattleMenuWatcher battle_menu_detector(false); + StartBattleWatcher start_battle_detector; + + int result = run_until( + env.console, context, + [](ProControllerContext& context){ + pbf_mash_button(context, BUTTON_A, 60s); + }, + { + {battle_menu_detector}, + {start_battle_detector}, + } + ); + + switch (result){ + case 0: + env.log("Unexpected battle menu.", COLOR_RED); + stats.add_error(); + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 1000ms); + run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); + continue; + case 1: + env.log("Battle started!"); + break; + default: + stats.add_error(); + env.update_stats(); + env.log("Timed out."); + continue; + } + } + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); + + bool stop = handler.handle_standard_encounter_end_battle( + result, EXIT_BATTLE_TIMEOUT0 + ); + if (stop){ + break; + } +// pbf_mash_button(context, BUTTON_B, 10s); + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + + home_to_date_time(env.console, context, false); + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_press_button(context, BUTTON_A, 5, 10); + pbf_press_button(context, BUTTON_HOME, 80ms, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + + if (!GO_HOME_WHEN_DONE){ + pbf_press_button(context, BUTTON_HOME, 80ms, GameSettings::instance().HOME_TO_GAME_DELAY0); + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h index 996f24b2db..9286b00989 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-BerryTree.h @@ -1,56 +1,56 @@ -/* Shiny Hunt Autonomous - BerryTree - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousBerryTree_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousBerryTree_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class ShinyHuntAutonomousBerryTree_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousBerryTree_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousBerryTree : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousBerryTree(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - - EncounterBotLanguage LANGUAGE; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -}; - -} -} -} -#endif +/* Shiny Hunt Autonomous - BerryTree + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousBerryTree_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousBerryTree_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class ShinyHuntAutonomousBerryTree_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousBerryTree_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousBerryTree : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousBerryTree(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + + EncounterBotLanguage LANGUAGE; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.cpp index 2c49591909..57f342ef09 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.cpp @@ -1,202 +1,202 @@ -/* Shiny Hunt Autonomous - Fishing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_ShinyHuntAutonomous-Fishing.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousFishing_Descriptor::ShinyHuntAutonomousFishing_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousFishing", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Fishing", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Fishing.md", - "Automatically hunt for shiny fishing " + STRING_POKEMON + " using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntAutonomousFishing_Descriptor::Stats : public ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(true) - , m_misses(m_stats["Misses"]) - { - m_display_order.insert(m_display_order.begin() + 1, Stat("Misses")); - m_aliases["Timeouts"] = "Errors"; - m_aliases["Unexpected Battles"] = "Errors"; - } - std::atomic& m_misses; -}; -std::unique_ptr ShinyHuntAutonomousFishing_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ShinyHuntAutonomousFishing::ShinyHuntAutonomousFishing() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(true, true) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld and for the fish to reappear.", - LockMode::LOCK_WHILE_RUNNING, - "10000 ms" - ) - , FISH_RESPAWN_TIME0( - "Fish Respawn Time:
Wait this long for fish to respawn.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); - PA_ADD_OPTION(FISH_RESPAWN_TIME0); -} - - - -void ShinyHuntAutonomousFishing::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - - ShinyHuntAutonomousFishing_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - while (true){ - // Touch the date. - if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - last_touch += PERIOD; - } - - pbf_wait(context, FISH_RESPAWN_TIME0); - context.wait_for_all_requests(); - - // Trigger encounter. - { - pbf_press_button(context, BUTTON_A, 10, 10); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - context.wait_for_all_requests(); - - FishingMissDetector miss_detector; - FishingHookDetector hook_detector(env.console); - StandardBattleMenuWatcher menu_detector(false); - int result = wait_until( - env.console, context, - std::chrono::seconds(12), - { - {miss_detector}, - {hook_detector}, - {menu_detector}, - } - ); - switch (result){ - case 0: - env.log("Missed a hook.", COLOR_RED); - stats.m_misses++; - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - case 1: - env.log("Detected hook!", COLOR_PURPLE); - ssf_press_button_ptv(context, BUTTON_A, 120ms); -// pbf_mash_button(context, BUTTON_A, TICKS_PER_SECOND); - break; - case 2: - env.log("Unexpected battle menu.", COLOR_RED); - stats.add_error(); - env.update_stats(); - run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); - continue; - default: - env.log("Timed out.", COLOR_RED); - stats.add_error(); - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - } - context.wait_for(std::chrono::seconds(3)); - if (miss_detector.detect(env.console.video().snapshot())){ - env.log("False alarm! We actually missed.", COLOR_RED); - stats.m_misses++; - pbf_mash_button(context, BUTTON_B, 2000ms); - continue; - } - } - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); - - bool stop = handler.handle_standard_encounter_end_battle(result, EXIT_BATTLE_TIMEOUT0); - if (stop){ - break; - } - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} - +/* Shiny Hunt Autonomous - Fishing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonSwSh/Inference/PokemonSwSh_FishingDetector.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_ShinyHuntAutonomous-Fishing.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousFishing_Descriptor::ShinyHuntAutonomousFishing_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousFishing", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Fishing", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Fishing.md", + "Automatically hunt for shiny fishing " + STRING_POKEMON + " using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntAutonomousFishing_Descriptor::Stats : public ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(true) + , m_misses(m_stats["Misses"]) + { + m_display_order.insert(m_display_order.begin() + 1, Stat("Misses")); + m_aliases["Timeouts"] = "Errors"; + m_aliases["Unexpected Battles"] = "Errors"; + } + std::atomic& m_misses; +}; +std::unique_ptr ShinyHuntAutonomousFishing_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ShinyHuntAutonomousFishing::ShinyHuntAutonomousFishing() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(true, true) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld and for the fish to reappear.", + LockMode::LOCK_WHILE_RUNNING, + "10000 ms" + ) + , FISH_RESPAWN_TIME0( + "Fish Respawn Time:
Wait this long for fish to respawn.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); + PA_ADD_OPTION(FISH_RESPAWN_TIME0); +} + + + +void ShinyHuntAutonomousFishing::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + + ShinyHuntAutonomousFishing_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + while (true){ + // Touch the date. + if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + last_touch += PERIOD; + } + + pbf_wait(context, FISH_RESPAWN_TIME0); + context.wait_for_all_requests(); + + // Trigger encounter. + { + pbf_press_button(context, BUTTON_A, 10, 10); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + context.wait_for_all_requests(); + + FishingMissDetector miss_detector; + FishingHookDetector hook_detector(env.console); + StandardBattleMenuWatcher menu_detector(false); + int result = wait_until( + env.console, context, + std::chrono::seconds(12), + { + {miss_detector}, + {hook_detector}, + {menu_detector}, + } + ); + switch (result){ + case 0: + env.log("Missed a hook.", COLOR_RED); + stats.m_misses++; + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + case 1: + env.log("Detected hook!", COLOR_PURPLE); + ssf_press_button_ptv(context, BUTTON_A, 120ms); +// pbf_mash_button(context, BUTTON_A, TICKS_PER_SECOND); + break; + case 2: + env.log("Unexpected battle menu.", COLOR_RED); + stats.add_error(); + env.update_stats(); + run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); + continue; + default: + env.log("Timed out.", COLOR_RED); + stats.add_error(); + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + } + context.wait_for(std::chrono::seconds(3)); + if (miss_detector.detect(env.console.video().snapshot())){ + env.log("False alarm! We actually missed.", COLOR_RED); + stats.m_misses++; + pbf_mash_button(context, BUTTON_B, 2000ms); + continue; + } + } + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); + + bool stop = handler.handle_standard_encounter_end_battle(result, EXIT_BATTLE_TIMEOUT0); + if (stop){ + break; + } + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h index 93aad6102c..5d4f994ef1 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Fishing.h @@ -1,61 +1,61 @@ -/* Shiny Hunt Autonomous - Fishing - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousFishing_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousFishing_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class ShinyHuntAutonomousFishing_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousFishing_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousFishing : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousFishing(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TimeRollbackHoursOption TIME_ROLLBACK_HOURS; - - EncounterBotLanguage LANGUAGE; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; - MillisecondsOption FISH_RESPAWN_TIME0; -}; - - -} -} -} -#endif +/* Shiny Hunt Autonomous - Fishing + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousFishing_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousFishing_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class ShinyHuntAutonomousFishing_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousFishing_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousFishing : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousFishing(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TimeRollbackHoursOption TIME_ROLLBACK_HOURS; + + EncounterBotLanguage LANGUAGE; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; + MillisecondsOption FISH_RESPAWN_TIME0; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.cpp index 4eb325cbe7..5a226265f1 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.cpp @@ -1,185 +1,185 @@ -/* Shiny Hunt Autonomous - IoA Trade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "CommonFramework/GlobalSettingsPanel.h" -#include "CommonFramework/VideoPipeline/VideoFeed.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "Pokemon/Pokemon_Notification.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_ShinyHuntAutonomous-IoATrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -ShinyHuntAutonomousIoATrade_Descriptor::ShinyHuntAutonomousIoATrade_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousIoATrade", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - IoA Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-IoATrade.md", - "Hunt for shiny Isle of Armor trade using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr ShinyHuntAutonomousIoATrade_Descriptor::make_stats() const{ - return std::unique_ptr(new ShinyHuntTracker(false)); -} - - - -ShinyHuntAutonomousIoATrade::ShinyHuntAutonomousIoATrade() - : GO_HOME_WHEN_DONE(false) - , VIDEO_ON_SHINY( - "Video Capture:
Take a video of the encounter if it is shiny.", - LockMode::LOCK_WHILE_RUNNING, - true - ) - , NOTIFICATION_NONSHINY( - "Non-Shiny Encounter", - true, false, - {"Notifs"}, - std::chrono::seconds(3600) - ) - , NOTIFICATION_SHINY( - "Shiny Encounter", - true, true, ImageAttachmentMode::JPG, - {"Notifs", "Showcase"} - ) -// , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true) - , NOTIFICATIONS({ - &NOTIFICATION_NONSHINY, - &NOTIFICATION_SHINY, -// &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , MASH_TO_TRADE_DELAY0( - "Mash to Trade Delay:
Time to perform the trade.", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) - , RUN_FROM_EVERYTHING( - "Run from Everything:
Run from everything - even if it is shiny. (For testing only.)", - LockMode::LOCK_WHILE_RUNNING, - false - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(VIDEO_ON_SHINY); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(MASH_TO_TRADE_DELAY0); - if (PreloadSettings::instance().DEVELOPER_MODE){ - PA_ADD_OPTION(RUN_FROM_EVERYTHING); - } -} - - -void ShinyHuntAutonomousIoATrade::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - ShinyHuntTracker& stats = env.current_stats(); - - while (true){ - env.update_stats(); - - pbf_press_button(context, BUTTON_A, 20, 100); - pbf_press_button(context, BUTTON_A, 20, 60); - pbf_press_button(context, BUTTON_A, 20, 100); - pbf_press_button(context, BUTTON_A, 20, 50); - pbf_press_button(context, BUTTON_A, 160ms, GameSettings::instance().POKEMON_TO_BOX_DELAY0); - pbf_press_dpad(context, DPAD_LEFT, 20, 10); - pbf_mash_button(context, BUTTON_A, MASH_TO_TRADE_DELAY0); - - // Enter box system. - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_dpad(context, DPAD_RIGHT, 20, 10); - pbf_press_button(context, BUTTON_A, 160ms, GameSettings::instance().MENU_TO_POKEMON_DELAY0); - - // View summary. - pbf_press_button(context, BUTTON_A, 20, 100); - pbf_press_button(context, BUTTON_A, 20, 0); - context.wait_for_all_requests(); - - SummaryShinySymbolDetector::Detection detection; - { - SummaryShinySymbolDetector detector(env.console, env.console); - detection = detector.wait_for_detection(context, env.console); -// detection = SummaryShinySymbolDetector::SHINY; - } - switch (detection){ - case SummaryShinySymbolDetector::NO_DETECTION: - stats.add_error(); - break; - case SummaryShinySymbolDetector::NOT_SHINY: - stats.add_non_shiny(); - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - false, false, {{{}, ShinyType::NOT_SHINY}}, std::nan(""), - ImageViewRGB32() - ); - break; - case SummaryShinySymbolDetector::SHINY: - stats.add_unknown_shiny(); - send_encounter_notification( - env, - NOTIFICATION_NONSHINY, - NOTIFICATION_SHINY, - false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), - env.console.video().snapshot() - ); - if (VIDEO_ON_SHINY){ - pbf_wait(context, 1 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); - } - if (!RUN_FROM_EVERYTHING){ - goto StopProgram; - } - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - -StopProgram: - env.update_stats(); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - -} -} -} - +/* Shiny Hunt Autonomous - IoA Trade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "CommonFramework/GlobalSettingsPanel.h" +#include "CommonFramework/VideoPipeline/VideoFeed.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "Pokemon/Pokemon_Notification.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonSwSh/Inference/PokemonSwSh_SummaryShinySymbolDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_ShinyHuntAutonomous-IoATrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +ShinyHuntAutonomousIoATrade_Descriptor::ShinyHuntAutonomousIoATrade_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousIoATrade", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - IoA Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-IoATrade.md", + "Hunt for shiny Isle of Armor trade using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr ShinyHuntAutonomousIoATrade_Descriptor::make_stats() const{ + return std::unique_ptr(new ShinyHuntTracker(false)); +} + + + +ShinyHuntAutonomousIoATrade::ShinyHuntAutonomousIoATrade() + : GO_HOME_WHEN_DONE(false) + , VIDEO_ON_SHINY( + "Video Capture:
Take a video of the encounter if it is shiny.", + LockMode::LOCK_WHILE_RUNNING, + true + ) + , NOTIFICATION_NONSHINY( + "Non-Shiny Encounter", + true, false, + {"Notifs"}, + std::chrono::seconds(3600) + ) + , NOTIFICATION_SHINY( + "Shiny Encounter", + true, true, ImageAttachmentMode::JPG, + {"Notifs", "Showcase"} + ) +// , NOTIFICATION_PROGRAM_FINISH("Program Finished", true, true) + , NOTIFICATIONS({ + &NOTIFICATION_NONSHINY, + &NOTIFICATION_SHINY, +// &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , MASH_TO_TRADE_DELAY0( + "Mash to Trade Delay:
Time to perform the trade.", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) + , RUN_FROM_EVERYTHING( + "Run from Everything:
Run from everything - even if it is shiny. (For testing only.)", + LockMode::LOCK_WHILE_RUNNING, + false + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(VIDEO_ON_SHINY); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(MASH_TO_TRADE_DELAY0); + if (PreloadSettings::instance().DEVELOPER_MODE){ + PA_ADD_OPTION(RUN_FROM_EVERYTHING); + } +} + + +void ShinyHuntAutonomousIoATrade::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + ShinyHuntTracker& stats = env.current_stats(); + + while (true){ + env.update_stats(); + + pbf_press_button(context, BUTTON_A, 20, 100); + pbf_press_button(context, BUTTON_A, 20, 60); + pbf_press_button(context, BUTTON_A, 20, 100); + pbf_press_button(context, BUTTON_A, 20, 50); + pbf_press_button(context, BUTTON_A, 160ms, GameSettings::instance().POKEMON_TO_BOX_DELAY0); + pbf_press_dpad(context, DPAD_LEFT, 20, 10); + pbf_mash_button(context, BUTTON_A, MASH_TO_TRADE_DELAY0); + + // Enter box system. + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_dpad(context, DPAD_RIGHT, 20, 10); + pbf_press_button(context, BUTTON_A, 160ms, GameSettings::instance().MENU_TO_POKEMON_DELAY0); + + // View summary. + pbf_press_button(context, BUTTON_A, 20, 100); + pbf_press_button(context, BUTTON_A, 20, 0); + context.wait_for_all_requests(); + + SummaryShinySymbolDetector::Detection detection; + { + SummaryShinySymbolDetector detector(env.console, env.console); + detection = detector.wait_for_detection(context, env.console); +// detection = SummaryShinySymbolDetector::SHINY; + } + switch (detection){ + case SummaryShinySymbolDetector::NO_DETECTION: + stats.add_error(); + break; + case SummaryShinySymbolDetector::NOT_SHINY: + stats.add_non_shiny(); + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + false, false, {{{}, ShinyType::NOT_SHINY}}, std::nan(""), + ImageViewRGB32() + ); + break; + case SummaryShinySymbolDetector::SHINY: + stats.add_unknown_shiny(); + send_encounter_notification( + env, + NOTIFICATION_NONSHINY, + NOTIFICATION_SHINY, + false, true, {{{}, ShinyType::UNKNOWN_SHINY}}, std::nan(""), + env.console.video().snapshot() + ); + if (VIDEO_ON_SHINY){ + pbf_wait(context, 1 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_CAPTURE, 2000ms, 5000ms); + } + if (!RUN_FROM_EVERYTHING){ + goto StopProgram; + } + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + +StopProgram: + env.update_stats(); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h index 542d66c072..34629f8118 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-IoATrade.h @@ -1,57 +1,57 @@ -/* Shiny Hunt Autonomous - IoATrade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousIoATrade_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousIoATrade_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntAutonomousIoATrade_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousIoATrade_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousIoATrade : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousIoATrade(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - BooleanCheckBoxOption VIDEO_ON_SHINY; - EventNotificationOption NOTIFICATION_NONSHINY; - EventNotificationOption NOTIFICATION_SHINY; - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption MASH_TO_TRADE_DELAY0; - BooleanCheckBoxOption RUN_FROM_EVERYTHING; -}; - - -} -} -} -#endif +/* Shiny Hunt Autonomous - IoATrade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousIoATrade_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousIoATrade_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntAutonomousIoATrade_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousIoATrade_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousIoATrade : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousIoATrade(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + BooleanCheckBoxOption VIDEO_ON_SHINY; + EventNotificationOption NOTIFICATION_NONSHINY; + EventNotificationOption NOTIFICATION_SHINY; + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption MASH_TO_TRADE_DELAY0; + BooleanCheckBoxOption RUN_FROM_EVERYTHING; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.cpp index 428cbb4674..51fed2514b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.cpp @@ -1,170 +1,170 @@ -/* Shiny Hunt Autonomous - Regi - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Exceptions/OperationFailedException.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h" -#include "PokemonSwSh_ShinyHuntAutonomous-Regi.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousRegi_Descriptor::ShinyHuntAutonomousRegi_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousRegi", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Regi", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Regi.md", - "Automatically hunt for shiny Regi using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr ShinyHuntAutonomousRegi_Descriptor::make_stats() const{ - return std::unique_ptr( - new ShinyHuntTracker( - true, - {{"Light Resets", "Errors"}} - ) - ); -} - - - -ShinyHuntAutonomousRegi::ShinyHuntAutonomousRegi() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(false, false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) - , POST_BATTLE_MASH_TIME0( - "Post-Battle Mash:
After each battle, mash B for this long to clear the dialogs.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , TRANSITION_DELAY0( - "Transition Delay:
Time to enter/exit the building.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(REGI_NAME); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); - PA_ADD_OPTION(POST_BATTLE_MASH_TIME0); - PA_ADD_OPTION(TRANSITION_DELAY0); -} - - - - -void ShinyHuntAutonomousRegi::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - ShinyHuntTracker& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - bool error = false; - while (true){ - pbf_mash_button(context, BUTTON_B, POST_BATTLE_MASH_TIME0); - move_to_corner(env.console, context, error, TRANSITION_DELAY0); - if (error){ - env.update_stats(); - error = false; - } - - // Touch the date. - if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ - env.log("Touching date to prevent rollover."); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - - // Do the light puzzle. - run_regi_light_puzzle(env.console, context, REGI_NAME, stats.encounters()); - - // Start the encounter. - pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); - context.wait_for_all_requests(); - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); -// shininess = ShinyDetection::SQUARE_SHINY; - if (result.shiny_type == ShinyType::UNKNOWN){ - stats.add_error(); - pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); - run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); - error = true; - continue; - } - - bool stop = handler.handle_standard_encounter_end_battle( - result, EXIT_BATTLE_TIMEOUT0 - ); - if (stop){ - break; - } - } - - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - -} -} -} - - +/* Shiny Hunt Autonomous - Regi + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Exceptions/OperationFailedException.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h" +#include "PokemonSwSh_ShinyHuntAutonomous-Regi.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousRegi_Descriptor::ShinyHuntAutonomousRegi_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousRegi", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Regi", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Regi.md", + "Automatically hunt for shiny Regi using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr ShinyHuntAutonomousRegi_Descriptor::make_stats() const{ + return std::unique_ptr( + new ShinyHuntTracker( + true, + {{"Light Resets", "Errors"}} + ) + ); +} + + + +ShinyHuntAutonomousRegi::ShinyHuntAutonomousRegi() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(false, false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) + , POST_BATTLE_MASH_TIME0( + "Post-Battle Mash:
After each battle, mash B for this long to clear the dialogs.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , TRANSITION_DELAY0( + "Transition Delay:
Time to enter/exit the building.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(REGI_NAME); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); + PA_ADD_OPTION(POST_BATTLE_MASH_TIME0); + PA_ADD_OPTION(TRANSITION_DELAY0); +} + + + + +void ShinyHuntAutonomousRegi::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + ShinyHuntTracker& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + bool error = false; + while (true){ + pbf_mash_button(context, BUTTON_B, POST_BATTLE_MASH_TIME0); + move_to_corner(env.console, context, error, TRANSITION_DELAY0); + if (error){ + env.update_stats(); + error = false; + } + + // Touch the date. + if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ + env.log("Touching date to prevent rollover."); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + + // Do the light puzzle. + run_regi_light_puzzle(env.console, context, REGI_NAME, stats.encounters()); + + // Start the encounter. + pbf_mash_button(context, BUTTON_A, 5 * TICKS_PER_SECOND); + context.wait_for_all_requests(); + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); +// shininess = ShinyDetection::SQUARE_SHINY; + if (result.shiny_type == ShinyType::UNKNOWN){ + stats.add_error(); + pbf_mash_button(context, BUTTON_B, TICKS_PER_SECOND); + run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); + error = true; + continue; + } + + bool stop = handler.handle_standard_encounter_end_battle( + result, EXIT_BATTLE_TIMEOUT0 + ); + if (stop){ + break; + } + } + + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + +} +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h index 64292eedd6..9591404415 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regi.h @@ -1,63 +1,63 @@ -/* Shiny Hunt Autonomous - Regi - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegi_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegi_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" -#include "PokemonSwSh/Options/PokemonSwSh_RegiSelector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class ShinyHuntAutonomousRegi_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousRegi_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousRegi : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousRegi(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - EncounterBotLanguage LANGUAGE; - - RegiSelectorOption REGI_NAME; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; - MillisecondsOption POST_BATTLE_MASH_TIME0; - MillisecondsOption TRANSITION_DELAY0; -}; - -} -} -} -#endif +/* Shiny Hunt Autonomous - Regi + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegi_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegi_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" +#include "PokemonSwSh/Options/PokemonSwSh_RegiSelector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class ShinyHuntAutonomousRegi_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousRegi_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousRegi : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousRegi(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + EncounterBotLanguage LANGUAGE; + + RegiSelectorOption REGI_NAME; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; + MillisecondsOption POST_BATTLE_MASH_TIME0; + MillisecondsOption TRANSITION_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.cpp index 4fd0ce7fd4..fb48e1b310 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.cpp @@ -1,188 +1,188 @@ -/* Shiny Hunt Autonomous - Regigigas2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousRegigigas2_Descriptor::ShinyHuntAutonomousRegigigas2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousRegigigas2", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Regigigas2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Regigigas2.md", - "Automatically hunt for shiny Regigigas using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr ShinyHuntAutonomousRegigigas2_Descriptor::make_stats() const{ - return std::unique_ptr( - new ShinyHuntTracker( - true, - {{"Timeouts", "Errors"}} - ) - ); -} - - - -ShinyHuntAutonomousRegigigas2::ShinyHuntAutonomousRegigigas2() - : GO_HOME_WHEN_DONE(false) - , REVERSAL_PP( - "Reversal PP:
The amount of Reversal PP you are saved with.", - LockMode::LOCK_WHILE_RUNNING, - 24 - ) - , ENCOUNTER_BOT_OPTIONS(false, false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , CATCH_TO_OVERWORLD_DELAY0( - "Catch to Overworld Delay:", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(REVERSAL_PP); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CATCH_TO_OVERWORLD_DELAY0); -} - - - -bool ShinyHuntAutonomousRegigigas2::kill_and_return(VideoStream& stream, ProControllerContext& context) const{ - pbf_mash_button(context, BUTTON_A, 4000ms); - - RaidCatchDetector detector(stream.overlay()); - int result = wait_until( - stream, context, - std::chrono::seconds(30), - {{detector}} - ); - switch (result){ - case 0: - ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); - pbf_press_button(context, BUTTON_A, 80ms, CATCH_TO_OVERWORLD_DELAY0); - return true; - default: - stream.log("Raid Catch Menu not found.", COLOR_RED); - return false; - } -} -void ShinyHuntAutonomousRegigigas2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - ShinyHuntTracker& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - Language::None, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - while (true){ - for (uint8_t pp = REVERSAL_PP; pp > 0; pp--){ - env.log("Starting Regigigas Encounter: " + tostr_u_commas(stats.encounters() + 1)); - - pbf_mash_button(context, BUTTON_A, 18s); - context.wait_for_all_requests(); - - { - StartBattleWatcher detector; - int result = wait_until( - env.console, context, - std::chrono::seconds(30), - {{detector}} - ); - if (result < 0){ - stats.add_error(); - env.update_stats(); - break; - } - env.log("Detected battle start."); - } - - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_RAID, - std::chrono::seconds(30) - ); -// shininess = ShinyDetection::STAR_SHINY; - - bool stop = handler.handle_standard_encounter(result); - if (stop){ - goto StopProgram; - } - - if (result.shiny_type == ShinyType::UNKNOWN){ - stats.add_error(); - env.update_stats(); - break; - } - - kill_and_return(env.console, context); - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - } - - -StopProgram: - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} - - +/* Shiny Hunt Autonomous - Regigigas2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/Dens/PokemonSwSh_RaidCatchDetector.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousRegigigas2_Descriptor::ShinyHuntAutonomousRegigigas2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousRegigigas2", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Regigigas2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Regigigas2.md", + "Automatically hunt for shiny Regigigas using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr ShinyHuntAutonomousRegigigas2_Descriptor::make_stats() const{ + return std::unique_ptr( + new ShinyHuntTracker( + true, + {{"Timeouts", "Errors"}} + ) + ); +} + + + +ShinyHuntAutonomousRegigigas2::ShinyHuntAutonomousRegigigas2() + : GO_HOME_WHEN_DONE(false) + , REVERSAL_PP( + "Reversal PP:
The amount of Reversal PP you are saved with.", + LockMode::LOCK_WHILE_RUNNING, + 24 + ) + , ENCOUNTER_BOT_OPTIONS(false, false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , CATCH_TO_OVERWORLD_DELAY0( + "Catch to Overworld Delay:", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(REVERSAL_PP); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CATCH_TO_OVERWORLD_DELAY0); +} + + + +bool ShinyHuntAutonomousRegigigas2::kill_and_return(VideoStream& stream, ProControllerContext& context) const{ + pbf_mash_button(context, BUTTON_A, 4000ms); + + RaidCatchDetector detector(stream.overlay()); + int result = wait_until( + stream, context, + std::chrono::seconds(30), + {{detector}} + ); + switch (result){ + case 0: + ssf_press_dpad_ptv(context, DPAD_DOWN, 80ms); + pbf_press_button(context, BUTTON_A, 80ms, CATCH_TO_OVERWORLD_DELAY0); + return true; + default: + stream.log("Raid Catch Menu not found.", COLOR_RED); + return false; + } +} +void ShinyHuntAutonomousRegigigas2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + ShinyHuntTracker& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + Language::None, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + while (true){ + for (uint8_t pp = REVERSAL_PP; pp > 0; pp--){ + env.log("Starting Regigigas Encounter: " + tostr_u_commas(stats.encounters() + 1)); + + pbf_mash_button(context, BUTTON_A, 18s); + context.wait_for_all_requests(); + + { + StartBattleWatcher detector; + int result = wait_until( + env.console, context, + std::chrono::seconds(30), + {{detector}} + ); + if (result < 0){ + stats.add_error(); + env.update_stats(); + break; + } + env.log("Detected battle start."); + } + + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_RAID, + std::chrono::seconds(30) + ); +// shininess = ShinyDetection::STAR_SHINY; + + bool stop = handler.handle_standard_encounter(result); + if (stop){ + goto StopProgram; + } + + if (result.shiny_type == ShinyType::UNKNOWN){ + stats.add_error(); + env.update_stats(); + break; + } + + kill_and_return(env.console, context); + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + TOUCH_DATE_INTERVAL.touch_now_from_home_if_needed(env.console, context); + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + } + + +StopProgram: + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h index 6a7472deed..22b49ab525 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Regigigas2.h @@ -1,60 +1,60 @@ -/* Shiny Hunt Autonomous - Regigigas2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegigigas2_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegigigas2_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -//#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntAutonomousRegigigas2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousRegigigas2_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousRegigigas2 : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousRegigigas2(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - bool kill_and_return(VideoStream& stream, ProControllerContext& context) const; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - SimpleIntegerOption REVERSAL_PP; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption CATCH_TO_OVERWORLD_DELAY0; -}; - -} -} -} -#endif +/* Shiny Hunt Autonomous - Regigigas2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegigigas2_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousRegigigas2_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +//#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntAutonomousRegigigas2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousRegigigas2_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousRegigigas2 : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousRegigigas2(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + bool kill_and_return(VideoStream& stream, ProControllerContext& context) const; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + SimpleIntegerOption REVERSAL_PP; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption CATCH_TO_OVERWORLD_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.cpp index 1d0f793d30..c06ed540f2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.cpp @@ -1,140 +1,140 @@ -/* Shiny Hunt Autonomous - Strong Spawn - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -//#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousStrongSpawn_Descriptor::ShinyHuntAutonomousStrongSpawn_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousStrongSpawn", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Strong Spawn", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-StrongSpawn.md", - "Automatically hunt for shiny strong spawns using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr ShinyHuntAutonomousStrongSpawn_Descriptor::make_stats() const{ - return std::unique_ptr( - new ShinyHuntTracker( - true, - {{"Timeouts", "Errors"}} - ) - ); -} - - - -ShinyHuntAutonomousStrongSpawn::ShinyHuntAutonomousStrongSpawn() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(true, false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) -// , m_advanced_options( -// "Advanced Options: You should not need to touch anything below here." -// ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(LANGUAGE); - - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - -// if (PERSISTENT_SETTINGS().developer_mode){ -// PA_ADD_STATIC(m_advanced_options); -// } -} - - - -void ShinyHuntAutonomousStrongSpawn::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - - ShinyHuntTracker& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - while (true){ - WallClock now = current_time(); - if (TIME_ROLLBACK_HOURS > 0 && now - last_touch >= PERIOD){ - rollback_hours_from_home( - env.console, context, - TIME_ROLLBACK_HOURS, - ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0 - ); - last_touch += PERIOD; - } - reset_game_from_home_with_inference( - env.console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST - ); - env.log("Starting Encounter: " + tostr_u_commas(stats.encounters() + 1)); - context.wait_for_all_requests(); - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); - - bool stop = handler.handle_standard_encounter(result); - if (stop){ - break; - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} - +/* Shiny Hunt Autonomous - Strong Spawn + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +//#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousStrongSpawn_Descriptor::ShinyHuntAutonomousStrongSpawn_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousStrongSpawn", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Strong Spawn", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-StrongSpawn.md", + "Automatically hunt for shiny strong spawns using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr ShinyHuntAutonomousStrongSpawn_Descriptor::make_stats() const{ + return std::unique_ptr( + new ShinyHuntTracker( + true, + {{"Timeouts", "Errors"}} + ) + ); +} + + + +ShinyHuntAutonomousStrongSpawn::ShinyHuntAutonomousStrongSpawn() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(true, false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) +// , m_advanced_options( +// "Advanced Options: You should not need to touch anything below here." +// ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(LANGUAGE); + + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + +// if (PERSISTENT_SETTINGS().developer_mode){ +// PA_ADD_STATIC(m_advanced_options); +// } +} + + + +void ShinyHuntAutonomousStrongSpawn::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + + ShinyHuntTracker& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + while (true){ + WallClock now = current_time(); + if (TIME_ROLLBACK_HOURS > 0 && now - last_touch >= PERIOD){ + rollback_hours_from_home( + env.console, context, + TIME_ROLLBACK_HOURS, + ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0 + ); + last_touch += PERIOD; + } + reset_game_from_home_with_inference( + env.console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST + ); + env.log("Starting Encounter: " + tostr_u_commas(stats.encounters() + 1)); + context.wait_for_all_requests(); + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); + + bool stop = handler.handle_standard_encounter(result); + if (stop){ + break; + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h index 693a460343..4b5ebb3931 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-StrongSpawn.h @@ -1,56 +1,56 @@ -/* Shiny Hunt Autonomous - StrongSpawn - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousStrongSpawn_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousStrongSpawn_H - -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - - -class ShinyHuntAutonomousStrongSpawn_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousStrongSpawn_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousStrongSpawn : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousStrongSpawn(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TimeRollbackHoursOption TIME_ROLLBACK_HOURS; - - EncounterBotLanguage LANGUAGE; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - -// SectionDivider m_advanced_options; -}; - -} -} -} -#endif +/* Shiny Hunt Autonomous - StrongSpawn + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousStrongSpawn_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousStrongSpawn_H + +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + + +class ShinyHuntAutonomousStrongSpawn_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousStrongSpawn_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousStrongSpawn : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousStrongSpawn(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TimeRollbackHoursOption TIME_ROLLBACK_HOURS; + + EncounterBotLanguage LANGUAGE; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + +// SectionDivider m_advanced_options; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.cpp index aa24a1782f..6ce29f4788 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.cpp @@ -1,184 +1,184 @@ -/* Shiny Hunt Autonomous - Swords Of Justice - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousSwordsOfJustice_Descriptor::ShinyHuntAutonomousSwordsOfJustice_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousSwordsOfJustice", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Swords Of Justice", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-SwordsOfJustice.md", - "Automatically hunt for shiny Sword of Justice using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -std::unique_ptr ShinyHuntAutonomousSwordsOfJustice_Descriptor::make_stats() const{ - return std::unique_ptr( - new ShinyHuntTracker( - true, - {{"Timeouts", "Errors"}} - ) - ); -} - - - -ShinyHuntAutonomousSwordsOfJustice::ShinyHuntAutonomousSwordsOfJustice() - : GO_HOME_WHEN_DONE(false) - , AIRPLANE_MODE( - "Airplane Mode:
Enable if airplane mode is on.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , ENCOUNTER_BOT_OPTIONS(true, false) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) - , POST_BATTLE_MASH_TIME0( - "Post-Battle Mash:
After each battle, mash B for this long before entering the camp.", - LockMode::LOCK_WHILE_RUNNING, - "1000 ms" - ) - , ENTER_CAMP_DELAY0( - "Enter Camp Delay:", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(AIRPLANE_MODE); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); - PA_ADD_OPTION(POST_BATTLE_MASH_TIME0); - PA_ADD_OPTION(ENTER_CAMP_DELAY0); -} - - - -void ShinyHuntAutonomousSwordsOfJustice::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - - ShinyHuntTracker& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - while (true){ - // Touch the date. - if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - last_touch += PERIOD; - } - - // Trigger encounter. - pbf_mash_button(context, BUTTON_B, POST_BATTLE_MASH_TIME0); - pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_A, 160ms, ENTER_CAMP_DELAY0); - if (AIRPLANE_MODE){ - pbf_press_button(context, BUTTON_A, 20, 100); - pbf_press_button(context, BUTTON_A, 20, 100); - } - pbf_press_button(context, BUTTON_X, 20, 50); - pbf_press_dpad(context, DPAD_LEFT, 20, 20); - env.log("Starting Encounter: " + tostr_u_commas(stats.encounters() + 1)); - pbf_press_button(context, BUTTON_A, 20, 0); - context.wait_for_all_requests(); - - { - // Wait for start of battle. - StandardBattleMenuWatcher battle_menu_detector(false); - StartBattleWatcher start_back_detector; - wait_until( - env.console, context, - std::chrono::seconds(30), - { - {battle_menu_detector}, - {start_back_detector}, - } - ); - } - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); -// shininess = ShinyDetection::SQUARE_SHINY; - - bool stop = handler.handle_standard_encounter_end_battle( - result, EXIT_BATTLE_TIMEOUT0 - ); - if (stop){ - break; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - - - -} -} -} +/* Shiny Hunt Autonomous - Swords Of Justice + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousSwordsOfJustice_Descriptor::ShinyHuntAutonomousSwordsOfJustice_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousSwordsOfJustice", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Swords Of Justice", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-SwordsOfJustice.md", + "Automatically hunt for shiny Sword of Justice using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +std::unique_ptr ShinyHuntAutonomousSwordsOfJustice_Descriptor::make_stats() const{ + return std::unique_ptr( + new ShinyHuntTracker( + true, + {{"Timeouts", "Errors"}} + ) + ); +} + + + +ShinyHuntAutonomousSwordsOfJustice::ShinyHuntAutonomousSwordsOfJustice() + : GO_HOME_WHEN_DONE(false) + , AIRPLANE_MODE( + "Airplane Mode:
Enable if airplane mode is on.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , ENCOUNTER_BOT_OPTIONS(true, false) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) + , POST_BATTLE_MASH_TIME0( + "Post-Battle Mash:
After each battle, mash B for this long before entering the camp.", + LockMode::LOCK_WHILE_RUNNING, + "1000 ms" + ) + , ENTER_CAMP_DELAY0( + "Enter Camp Delay:", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(AIRPLANE_MODE); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); + PA_ADD_OPTION(POST_BATTLE_MASH_TIME0); + PA_ADD_OPTION(ENTER_CAMP_DELAY0); +} + + + +void ShinyHuntAutonomousSwordsOfJustice::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + + ShinyHuntTracker& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + while (true){ + // Touch the date. + if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + last_touch += PERIOD; + } + + // Trigger encounter. + pbf_mash_button(context, BUTTON_B, POST_BATTLE_MASH_TIME0); + pbf_press_button(context, BUTTON_X, 160ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_A, 160ms, ENTER_CAMP_DELAY0); + if (AIRPLANE_MODE){ + pbf_press_button(context, BUTTON_A, 20, 100); + pbf_press_button(context, BUTTON_A, 20, 100); + } + pbf_press_button(context, BUTTON_X, 20, 50); + pbf_press_dpad(context, DPAD_LEFT, 20, 20); + env.log("Starting Encounter: " + tostr_u_commas(stats.encounters() + 1)); + pbf_press_button(context, BUTTON_A, 20, 0); + context.wait_for_all_requests(); + + { + // Wait for start of battle. + StandardBattleMenuWatcher battle_menu_detector(false); + StartBattleWatcher start_back_detector; + wait_until( + env.console, context, + std::chrono::seconds(30), + { + {battle_menu_detector}, + {start_back_detector}, + } + ); + } + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); +// shininess = ShinyDetection::SQUARE_SHINY; + + bool stop = handler.handle_standard_encounter_end_battle( + result, EXIT_BATTLE_TIMEOUT0 + ); + if (stop){ + break; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h index 87af0f19d3..9010de3f77 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-SwordsOfJustice.h @@ -1,64 +1,64 @@ -/* Shiny Hunt Autonomous - Swords Of Justice - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousSwordsOfJustice_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousSwordsOfJustice_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -using namespace Pokemon; - - -class ShinyHuntAutonomousSwordsOfJustice_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousSwordsOfJustice_Descriptor(); - - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousSwordsOfJustice : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousSwordsOfJustice(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TimeRollbackHoursOption TIME_ROLLBACK_HOURS; - - EncounterBotLanguage LANGUAGE; - - BooleanCheckBoxOption AIRPLANE_MODE; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; - MillisecondsOption POST_BATTLE_MASH_TIME0; - MillisecondsOption ENTER_CAMP_DELAY0; -}; - -} -} -} -#endif +/* Shiny Hunt Autonomous - Swords Of Justice + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousSwordsOfJustice_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousSwordsOfJustice_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +using namespace Pokemon; + + +class ShinyHuntAutonomousSwordsOfJustice_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousSwordsOfJustice_Descriptor(); + + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousSwordsOfJustice : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousSwordsOfJustice(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TimeRollbackHoursOption TIME_ROLLBACK_HOURS; + + EncounterBotLanguage LANGUAGE; + + BooleanCheckBoxOption AIRPLANE_MODE; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; + MillisecondsOption POST_BATTLE_MASH_TIME0; + MillisecondsOption ENTER_CAMP_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.cpp index 9e798e8014..53ddc8b14e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.cpp @@ -1,175 +1,175 @@ -/* Shiny Hunt Autonomous - Whistling - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Notifications/ProgramNotifications.h" -#include "CommonTools/Async/InferenceRoutines.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" -#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" -#include "PokemonSwSh_ShinyHuntAutonomous-Whistling.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyHuntAutonomousWhistling_Descriptor::ShinyHuntAutonomousWhistling_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntAutonomousWhistling", - STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Whistling", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Whistling.md", - "Stand in one place and whistle. Shiny hunt everything that attacks you using video feedback.", - FeedbackType::REQUIRED, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::NOT_FASTER - ) -{} -struct ShinyHuntAutonomousWhistling_Descriptor::Stats : public ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(true) - , m_unexpected_battles(m_stats["Unexpected Battles"]) - { - m_display_order.insert(m_display_order.begin() + 2, Stat("Unexpected Battles")); - m_aliases["Timeouts"] = "Errors"; - } - std::atomic& m_unexpected_battles; -}; -std::unique_ptr ShinyHuntAutonomousWhistling_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - - -ShinyHuntAutonomousWhistling::ShinyHuntAutonomousWhistling() - : GO_HOME_WHEN_DONE(false) - , ENCOUNTER_BOT_OPTIONS(true, true) - , NOTIFICATIONS({ - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, - &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, - &NOTIFICATION_PROGRAM_FINISH, - &NOTIFICATION_ERROR_FATAL, - }) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , EXIT_BATTLE_TIMEOUT0( - "Exit Battle Timeout:
After running, wait this long to return to overworld.", - LockMode::LOCK_WHILE_RUNNING, - "10 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GO_HOME_WHEN_DONE); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(LANGUAGE); - PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); - PA_ADD_OPTION(NOTIFICATIONS); - - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); -} - - - -void ShinyHuntAutonomousWhistling::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - - ShinyHuntAutonomousWhistling_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - StandardEncounterHandler handler( - env, env.console, context, - LANGUAGE, - ENCOUNTER_BOT_OPTIONS, - stats - ); - - while (true){ - // Touch the date. - if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - last_touch += PERIOD; - } - - context.wait_for_all_requests(); - { - StandardBattleMenuWatcher battle_menu_detector(false); - StartBattleWatcher start_battle_detector; - - int result = run_until( - env.console, context, - [](ProControllerContext& context){ - while (true){ - pbf_mash_button(context, BUTTON_LCLICK, 1000ms); - pbf_move_right_joystick(context, 192, 128, 1000ms, 0ms); - } - }, - { - {battle_menu_detector}, - {start_battle_detector}, - } - ); - - switch (result){ - case 0: - env.log("Unexpected battle menu.", COLOR_RED); - stats.m_unexpected_battles++; - env.update_stats(); - pbf_mash_button(context, BUTTON_B, 1000ms); - run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); - continue; - case 1: - env.log("Battle started!"); - break; - } - } - - // Detect shiny. - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - SHINY_BATTLE_REGULAR, - std::chrono::seconds(30) - ); - - bool stop = handler.handle_standard_encounter_end_battle( - result, EXIT_BATTLE_TIMEOUT0 - ); - if (stop){ - break; - } - } - - env.update_stats(); - send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); - GO_HOME_WHEN_DONE.run_end_of_program(context); -} - - - -} -} -} - +/* Shiny Hunt Autonomous - Whistling + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Notifications/ProgramNotifications.h" +#include "CommonTools/Async/InferenceRoutines.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_StartBattleDetector.h" +#include "PokemonSwSh/Inference/Battles/PokemonSwSh_BattleMenuDetector.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh/Programs/PokemonSwSh_EncounterHandler.h" +#include "PokemonSwSh_ShinyHuntAutonomous-Whistling.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyHuntAutonomousWhistling_Descriptor::ShinyHuntAutonomousWhistling_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntAutonomousWhistling", + STRING_POKEMON + " SwSh", "Shiny Hunt Autonomous - Whistling", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntAutonomous-Whistling.md", + "Stand in one place and whistle. Shiny hunt everything that attacks you using video feedback.", + FeedbackType::REQUIRED, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::NOT_FASTER + ) +{} +struct ShinyHuntAutonomousWhistling_Descriptor::Stats : public ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(true) + , m_unexpected_battles(m_stats["Unexpected Battles"]) + { + m_display_order.insert(m_display_order.begin() + 2, Stat("Unexpected Battles")); + m_aliases["Timeouts"] = "Errors"; + } + std::atomic& m_unexpected_battles; +}; +std::unique_ptr ShinyHuntAutonomousWhistling_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + + +ShinyHuntAutonomousWhistling::ShinyHuntAutonomousWhistling() + : GO_HOME_WHEN_DONE(false) + , ENCOUNTER_BOT_OPTIONS(true, true) + , NOTIFICATIONS({ + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_NONSHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_SHINY, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_SUCCESS, + &ENCOUNTER_BOT_OPTIONS.NOTIFICATION_CATCH_FAILED, + &NOTIFICATION_PROGRAM_FINISH, + &NOTIFICATION_ERROR_FATAL, + }) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , EXIT_BATTLE_TIMEOUT0( + "Exit Battle Timeout:
After running, wait this long to return to overworld.", + LockMode::LOCK_WHILE_RUNNING, + "10 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GO_HOME_WHEN_DONE); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(LANGUAGE); + PA_ADD_OPTION(ENCOUNTER_BOT_OPTIONS); + PA_ADD_OPTION(NOTIFICATIONS); + + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(EXIT_BATTLE_TIMEOUT0); +} + + + +void ShinyHuntAutonomousWhistling::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + + ShinyHuntAutonomousWhistling_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + StandardEncounterHandler handler( + env, env.console, context, + LANGUAGE, + ENCOUNTER_BOT_OPTIONS, + stats + ); + + while (true){ + // Touch the date. + if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + last_touch += PERIOD; + } + + context.wait_for_all_requests(); + { + StandardBattleMenuWatcher battle_menu_detector(false); + StartBattleWatcher start_battle_detector; + + int result = run_until( + env.console, context, + [](ProControllerContext& context){ + while (true){ + pbf_mash_button(context, BUTTON_LCLICK, 1000ms); + pbf_move_right_joystick(context, 192, 128, 1000ms, 0ms); + } + }, + { + {battle_menu_detector}, + {start_battle_detector}, + } + ); + + switch (result){ + case 0: + env.log("Unexpected battle menu.", COLOR_RED); + stats.m_unexpected_battles++; + env.update_stats(); + pbf_mash_button(context, BUTTON_B, 1000ms); + run_away(env.console, context, EXIT_BATTLE_TIMEOUT0); + continue; + case 1: + env.log("Battle started!"); + break; + } + } + + // Detect shiny. + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + SHINY_BATTLE_REGULAR, + std::chrono::seconds(30) + ); + + bool stop = handler.handle_standard_encounter_end_battle( + result, EXIT_BATTLE_TIMEOUT0 + ); + if (stop){ + break; + } + } + + env.update_stats(); + send_program_finished_notification(env, NOTIFICATION_PROGRAM_FINISH); + GO_HOME_WHEN_DONE.run_end_of_program(context); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h index 1495141a18..fcc0e1373c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntAutonomous/PokemonSwSh_ShinyHuntAutonomous-Whistling.h @@ -1,60 +1,60 @@ -/* Shiny Hunt Autonomous - Whistling - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousWhistling_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousWhistling_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "CommonFramework/Notifications/EventNotificationsTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - - -class ShinyHuntAutonomousWhistling_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntAutonomousWhistling_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class ShinyHuntAutonomousWhistling : public SingleSwitchProgramInstance{ -public: - ShinyHuntAutonomousWhistling(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - GoHomeWhenDoneOption GO_HOME_WHEN_DONE; - TimeRollbackHoursOption TIME_ROLLBACK_HOURS; - - EncounterBotLanguage LANGUAGE; - EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; - - EventNotificationsOption NOTIFICATIONS; - - SectionDividerOption m_advanced_options; - MillisecondsOption EXIT_BATTLE_TIMEOUT0; -}; - -} -} -} -#endif +/* Shiny Hunt Autonomous - Whistling + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousWhistling_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntAutonomousWhistling_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "CommonFramework/Notifications/EventNotificationsTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_GoHomeWhenDoneOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "Pokemon/Options/Pokemon_EncounterBotOptions.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_EncounterBotCommon.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + + +class ShinyHuntAutonomousWhistling_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntAutonomousWhistling_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class ShinyHuntAutonomousWhistling : public SingleSwitchProgramInstance{ +public: + ShinyHuntAutonomousWhistling(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + GoHomeWhenDoneOption GO_HOME_WHEN_DONE; + TimeRollbackHoursOption TIME_ROLLBACK_HOURS; + + EncounterBotLanguage LANGUAGE; + EncounterBotCommonOptions ENCOUNTER_BOT_OPTIONS; + + EventNotificationsOption NOTIFICATIONS; + + SectionDividerOption m_advanced_options; + MillisecondsOption EXIT_BATTLE_TIMEOUT0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.cpp index 4fffef55e8..7523efdf8a 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.cpp @@ -1,311 +1,311 @@ -/* Curry Hunter - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Globals.h" -#include "CommonTools/Async/InferenceSession.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/ShinyHuntTracker.h" -#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h" -//#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleDetector.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_CurryHunter.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -CurryHunter_Descriptor::CurryHunter_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:CurryHunter", - STRING_POKEMON + " SwSh", "Curry Hunter", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/CurryHunter.md", - "Cooks curry to attract " + STRING_POKEMON + " to your camp. " - "(This program cannot detect shinies. You must check manually or with " + STRING_POKEMON + " HOME.)", - FeedbackType::OPTIONAL_, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} -struct CurryHunter_Descriptor::Stats : public ShinyHuntTracker{ - Stats() - : ShinyHuntTracker(true) - , m_attempts(m_stats["Attempts"]) - { - for (auto& item : m_display_order){ - item.display_mode = HIDDEN_IF_ZERO; - } - m_display_order.insert(m_display_order.begin(), Stat("Attempts")); - } - std::atomic& m_attempts; -}; -std::unique_ptr CurryHunter_Descriptor::make_stats() const{ - return std::unique_ptr(new Stats()); -} - - -CurryHunter::CurryHunter() - : WALK_UP_DELAY0( - "Walk up Delay:
Wait this long for the " + STRING_POKEMON + " to walk up to you.", - LockMode::LOCK_WHILE_RUNNING, - "2000 ms" - ) - , SMALL_POKEMON( - "Small " + STRING_POKEMON + ":
If there are small " + STRING_POKEMON + ", increase this number by 30. You may have to adjust the number and check what works best for your area.", - LockMode::LOCK_WHILE_RUNNING, - 0 - ) - , TAKE_VIDEO( - "Take Videos:
Take a video after each cooking iteration. This will spam your album with videos.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , ITERATIONS( - "Iterations:
# of cooking attempts.", - LockMode::LOCK_WHILE_RUNNING, - 999 - ) -{ - PA_ADD_OPTION(WALK_UP_DELAY0); - PA_ADD_OPTION(SMALL_POKEMON); - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TAKE_VIDEO); - PA_ADD_OPTION(ITERATIONS); -} - - - -void CurryHunter::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_R, 5, 50); - } - - - CurryHunter_Descriptor::Stats& stats = env.current_stats(); - env.update_stats(); - - - // Select the cooking option. - pbf_press_button(context, BUTTON_X, 5, 125); - pbf_press_dpad(context, DPAD_RIGHT, 5, 100); - pbf_press_button(context, BUTTON_A, 5, 125); - pbf_press_button(context, BUTTON_A, 5, 300); - - - for (uint32_t it = 0; it < ITERATIONS; it++){ - // Which ingredient do you want to use? - pbf_press_button(context, BUTTON_A, 5, 75); // Get rid of the pop-up menu. - pbf_press_button(context, BUTTON_A, 5, 150); // 75. english text is longer. - pbf_press_button(context, BUTTON_A, 5, 100); // Ingredient is now selected. - - // Which berries do you want to use? - pbf_press_button(context, BUTTON_A, 5, 75); // Get rid of the pop-up menu. - pbf_press_button(context, BUTTON_A, 5, 75); - pbf_press_dpad(context, DPAD_UP, 5, 75); - pbf_press_button(context, BUTTON_A, 5, 125); - pbf_press_button(context, BUTTON_PLUS, 5, 200); // 125. english text is longer. - pbf_press_button(context, BUTTON_A, 5, 1000); // Berries are now selected as well. - - - // Around 17 seconds of A mashing for the first curry cooking phase. - for (uint16_t c = 0; c < 2100; c = c + 10){ - pbf_press_button(context, BUTTON_A, 5, 5); - } - - // Slowing down to not burn the curry. - for (uint16_t c = 0; c < 300; c = c + 25){ - pbf_press_button(context, BUTTON_A, 5, 20); - } - pbf_wait(context, 170); - - - // Do circles with the joystick. Each circle has ten positions. - for (uint16_t i = 0; i < 2350; i = i + 50){ - pbf_move_right_joystick(context, 128, 255, 5, 0); - pbf_move_right_joystick(context, 202, 231, 5, 0); - pbf_move_right_joystick(context, 249, 167, 5, 0); - pbf_move_right_joystick(context, 249, 88, 5, 0); - pbf_move_right_joystick(context, 202, 24, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_move_right_joystick(context, 53, 24, 5, 0); - pbf_move_right_joystick(context, 6, 88, 5, 0); - pbf_move_right_joystick(context, 6, 167, 5, 0); - pbf_move_right_joystick(context, 53, 231, 5, 0); - } - - - // Last step for the curry cooking part. - pbf_wait(context, 425); - pbf_press_button(context, BUTTON_A, 5, 2250); - - // Press A when it shows your curry, and its class. - pbf_press_button(context, BUTTON_A, 5, 1500); - pbf_press_button(context, BUTTON_A, 5, 500); - // You are now back to the camping with your 6 Pokemon, and hopefully a curry Pokemon. - - { - context.wait_for_all_requests(); - - ReceivePokemonDetector receive_detector(false); -// ShinySparkleDetector shiny_detector( -// env.console, env.console, -// ImageFloatBox(0.1, 0.01, 0.8, 0.77) -// ); - InferenceSession inference( - context, env.console, - { - {receive_detector}, -// {shiny_detector}, - } - ); - - // Default implementation of the "attract curry Pokemon" routine. - pbf_move_left_joystick(context, 0x80, 0x00, 40, 5); // Move up a bit to avoid talking to your pokemon. - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 55, 0); // Right - for (uint16_t i = 0; i< 2; i++){ - pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - } - - - // This routine gives better odds of attracting a low Pokemon if the option is enabled. - if (SMALL_POKEMON>0){ - pbf_move_left_joystick(context, 0x80, 0xff, SMALL_POKEMON, 0); - - for (uint16_t i = 0; i<2; i++){ - pbf_move_left_joystick(context, 0x00, 0x80, 30, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0x00, 0x80, 30, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0x00, 0x80, 30, 0); // Left - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 30, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 30, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - pbf_move_left_joystick(context, 0xff, 0x80, 30, 0); // Right - pbf_press_button(context, BUTTON_A, 5, 5); - } - - } - - // Give the pokemon the time to come to us. - pbf_wait(context, WALK_UP_DELAY0); - - // Record the encounter. - if (TAKE_VIDEO){ - pbf_press_button(context, BUTTON_CAPTURE, 250, 500); - }else{ - pbf_wait(context, 750); - } - - - // At this point, let's assume we have attracted the curry pokemon. - // Now we need to add it to our party while making sure this won't break anything if there is - // No curry encounter. - // This sequence seems to work because when you whistle at a curry encounter, your camera - // Automatically focuses on it, while it doesn't do that for your pokemons. - - // "a [wild pokemon] came to your camp !" - pbf_press_button(context, BUTTON_A, 5, 250); - - // "[wild pokemon] seems to want to come with you!" - pbf_press_button(context, BUTTON_A, 5, 200); - - // "do you want to adopt it ?" - pbf_press_button(context, BUTTON_A, 5, 200); - - // "you adopted [wild pokemon]!" - pbf_press_button(context, BUTTON_A, 5, 200); - - // "[wild pokemon] entered into a poke ball" - pbf_press_button(context, BUTTON_A, 5, 800); - - // "[wild pokemon] has been sent to the PC" - pbf_press_button(context, BUTTON_A, 5, 375); - - - context.wait_for_all_requests(); - ShinyType shininess = ShinyType::NOT_SHINY; - if (receive_detector.triggered()){ -// shininess = shiny_detector.results(); -#if 1 - stats.add_non_shiny(); -#else - switch (shininess){ - case ShinyType::UNKNOWN: - case ShinyType::NOT_SHINY: - stats.add_non_shiny(); - break; - case ShinyType::UNKNOWN_SHINY: - stats.add_unknown_shiny(); - break; - case ShinyType::STAR_SHINY: - stats.add_star_shiny(); - break; - case ShinyType::SQUARE_SHINY: - stats.add_square_shiny(); - break; - - } -#endif - } - - stats.m_attempts++; - env.update_stats(); - if (shininess != ShinyType::NOT_SHINY){ - pbf_press_button(context, BUTTON_CAPTURE, 250, 500); - } - } - - - // If you talked to the curry Pokemon too early, you can end up talking to one of your Pokemon - // Once you reach this part of the program. The following sequence ensures that you - // Are in a correct state to cook again. - pbf_move_left_joystick(context, 0xff, 0x80, 125, 5); - pbf_move_left_joystick(context, 0x80, 0x00, 125, 5); - pbf_move_left_joystick(context, 0x80, 0x00, 5, 50); - pbf_press_button(context, BUTTON_A, 5, 250); // Wait 2 seconds to be sure the following X press won't be dropped. - - // And now we cook another curry. - pbf_press_button(context, BUTTON_X, 5, 125); - pbf_press_button(context, BUTTON_A, 5, 125); - pbf_press_button(context, BUTTON_A, 5, 300); - } - - - // Not really relevant here, but for programs that finish, go to - // Switch home to idle. - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); -} - - - - -} -} -} +/* Curry Hunter + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Globals.h" +#include "CommonTools/Async/InferenceSession.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/ShinyHuntTracker.h" +#include "PokemonSwSh/Inference/PokemonSwSh_ReceivePokemonDetector.h" +//#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinySparkleDetector.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_CurryHunter.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +CurryHunter_Descriptor::CurryHunter_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:CurryHunter", + STRING_POKEMON + " SwSh", "Curry Hunter", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/CurryHunter.md", + "Cooks curry to attract " + STRING_POKEMON + " to your camp. " + "(This program cannot detect shinies. You must check manually or with " + STRING_POKEMON + " HOME.)", + FeedbackType::OPTIONAL_, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} +struct CurryHunter_Descriptor::Stats : public ShinyHuntTracker{ + Stats() + : ShinyHuntTracker(true) + , m_attempts(m_stats["Attempts"]) + { + for (auto& item : m_display_order){ + item.display_mode = HIDDEN_IF_ZERO; + } + m_display_order.insert(m_display_order.begin(), Stat("Attempts")); + } + std::atomic& m_attempts; +}; +std::unique_ptr CurryHunter_Descriptor::make_stats() const{ + return std::unique_ptr(new Stats()); +} + + +CurryHunter::CurryHunter() + : WALK_UP_DELAY0( + "Walk up Delay:
Wait this long for the " + STRING_POKEMON + " to walk up to you.", + LockMode::LOCK_WHILE_RUNNING, + "2000 ms" + ) + , SMALL_POKEMON( + "Small " + STRING_POKEMON + ":
If there are small " + STRING_POKEMON + ", increase this number by 30. You may have to adjust the number and check what works best for your area.", + LockMode::LOCK_WHILE_RUNNING, + 0 + ) + , TAKE_VIDEO( + "Take Videos:
Take a video after each cooking iteration. This will spam your album with videos.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , ITERATIONS( + "Iterations:
# of cooking attempts.", + LockMode::LOCK_WHILE_RUNNING, + 999 + ) +{ + PA_ADD_OPTION(WALK_UP_DELAY0); + PA_ADD_OPTION(SMALL_POKEMON); + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TAKE_VIDEO); + PA_ADD_OPTION(ITERATIONS); +} + + + +void CurryHunter::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_R, 5, 50); + } + + + CurryHunter_Descriptor::Stats& stats = env.current_stats(); + env.update_stats(); + + + // Select the cooking option. + pbf_press_button(context, BUTTON_X, 5, 125); + pbf_press_dpad(context, DPAD_RIGHT, 5, 100); + pbf_press_button(context, BUTTON_A, 5, 125); + pbf_press_button(context, BUTTON_A, 5, 300); + + + for (uint32_t it = 0; it < ITERATIONS; it++){ + // Which ingredient do you want to use? + pbf_press_button(context, BUTTON_A, 5, 75); // Get rid of the pop-up menu. + pbf_press_button(context, BUTTON_A, 5, 150); // 75. english text is longer. + pbf_press_button(context, BUTTON_A, 5, 100); // Ingredient is now selected. + + // Which berries do you want to use? + pbf_press_button(context, BUTTON_A, 5, 75); // Get rid of the pop-up menu. + pbf_press_button(context, BUTTON_A, 5, 75); + pbf_press_dpad(context, DPAD_UP, 5, 75); + pbf_press_button(context, BUTTON_A, 5, 125); + pbf_press_button(context, BUTTON_PLUS, 5, 200); // 125. english text is longer. + pbf_press_button(context, BUTTON_A, 5, 1000); // Berries are now selected as well. + + + // Around 17 seconds of A mashing for the first curry cooking phase. + for (uint16_t c = 0; c < 2100; c = c + 10){ + pbf_press_button(context, BUTTON_A, 5, 5); + } + + // Slowing down to not burn the curry. + for (uint16_t c = 0; c < 300; c = c + 25){ + pbf_press_button(context, BUTTON_A, 5, 20); + } + pbf_wait(context, 170); + + + // Do circles with the joystick. Each circle has ten positions. + for (uint16_t i = 0; i < 2350; i = i + 50){ + pbf_move_right_joystick(context, 128, 255, 5, 0); + pbf_move_right_joystick(context, 202, 231, 5, 0); + pbf_move_right_joystick(context, 249, 167, 5, 0); + pbf_move_right_joystick(context, 249, 88, 5, 0); + pbf_move_right_joystick(context, 202, 24, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_move_right_joystick(context, 53, 24, 5, 0); + pbf_move_right_joystick(context, 6, 88, 5, 0); + pbf_move_right_joystick(context, 6, 167, 5, 0); + pbf_move_right_joystick(context, 53, 231, 5, 0); + } + + + // Last step for the curry cooking part. + pbf_wait(context, 425); + pbf_press_button(context, BUTTON_A, 5, 2250); + + // Press A when it shows your curry, and its class. + pbf_press_button(context, BUTTON_A, 5, 1500); + pbf_press_button(context, BUTTON_A, 5, 500); + // You are now back to the camping with your 6 Pokemon, and hopefully a curry Pokemon. + + { + context.wait_for_all_requests(); + + ReceivePokemonDetector receive_detector(false); +// ShinySparkleDetector shiny_detector( +// env.console, env.console, +// ImageFloatBox(0.1, 0.01, 0.8, 0.77) +// ); + InferenceSession inference( + context, env.console, + { + {receive_detector}, +// {shiny_detector}, + } + ); + + // Default implementation of the "attract curry Pokemon" routine. + pbf_move_left_joystick(context, 0x80, 0x00, 40, 5); // Move up a bit to avoid talking to your pokemon. + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 55, 0); // Right + for (uint16_t i = 0; i< 2; i++){ + pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0x00, 0x80, 27, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 27, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + } + + + // This routine gives better odds of attracting a low Pokemon if the option is enabled. + if (SMALL_POKEMON>0){ + pbf_move_left_joystick(context, 0x80, 0xff, SMALL_POKEMON, 0); + + for (uint16_t i = 0; i<2; i++){ + pbf_move_left_joystick(context, 0x00, 0x80, 30, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0x00, 0x80, 30, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0x00, 0x80, 30, 0); // Left + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 30, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 30, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + pbf_move_left_joystick(context, 0xff, 0x80, 30, 0); // Right + pbf_press_button(context, BUTTON_A, 5, 5); + } + + } + + // Give the pokemon the time to come to us. + pbf_wait(context, WALK_UP_DELAY0); + + // Record the encounter. + if (TAKE_VIDEO){ + pbf_press_button(context, BUTTON_CAPTURE, 250, 500); + }else{ + pbf_wait(context, 750); + } + + + // At this point, let's assume we have attracted the curry pokemon. + // Now we need to add it to our party while making sure this won't break anything if there is + // No curry encounter. + // This sequence seems to work because when you whistle at a curry encounter, your camera + // Automatically focuses on it, while it doesn't do that for your pokemons. + + // "a [wild pokemon] came to your camp !" + pbf_press_button(context, BUTTON_A, 5, 250); + + // "[wild pokemon] seems to want to come with you!" + pbf_press_button(context, BUTTON_A, 5, 200); + + // "do you want to adopt it ?" + pbf_press_button(context, BUTTON_A, 5, 200); + + // "you adopted [wild pokemon]!" + pbf_press_button(context, BUTTON_A, 5, 200); + + // "[wild pokemon] entered into a poke ball" + pbf_press_button(context, BUTTON_A, 5, 800); + + // "[wild pokemon] has been sent to the PC" + pbf_press_button(context, BUTTON_A, 5, 375); + + + context.wait_for_all_requests(); + ShinyType shininess = ShinyType::NOT_SHINY; + if (receive_detector.triggered()){ +// shininess = shiny_detector.results(); +#if 1 + stats.add_non_shiny(); +#else + switch (shininess){ + case ShinyType::UNKNOWN: + case ShinyType::NOT_SHINY: + stats.add_non_shiny(); + break; + case ShinyType::UNKNOWN_SHINY: + stats.add_unknown_shiny(); + break; + case ShinyType::STAR_SHINY: + stats.add_star_shiny(); + break; + case ShinyType::SQUARE_SHINY: + stats.add_square_shiny(); + break; + + } +#endif + } + + stats.m_attempts++; + env.update_stats(); + if (shininess != ShinyType::NOT_SHINY){ + pbf_press_button(context, BUTTON_CAPTURE, 250, 500); + } + } + + + // If you talked to the curry Pokemon too early, you can end up talking to one of your Pokemon + // Once you reach this part of the program. The following sequence ensures that you + // Are in a correct state to cook again. + pbf_move_left_joystick(context, 0xff, 0x80, 125, 5); + pbf_move_left_joystick(context, 0x80, 0x00, 125, 5); + pbf_move_left_joystick(context, 0x80, 0x00, 5, 50); + pbf_press_button(context, BUTTON_A, 5, 250); // Wait 2 seconds to be sure the following X press won't be dropped. + + // And now we cook another curry. + pbf_press_button(context, BUTTON_X, 5, 125); + pbf_press_button(context, BUTTON_A, 5, 125); + pbf_press_button(context, BUTTON_A, 5, 300); + } + + + // Not really relevant here, but for programs that finish, go to + // Switch home to idle. + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h index df90fff426..002de3881b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_CurryHunter.h @@ -1,50 +1,50 @@ -/* Curry Bot - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_CurryHunter_H -#define PokemonAutomation_PokemonSwSh_CurryHunter_H - -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class CurryHunter_Descriptor : public SingleSwitchProgramDescriptor{ -public: - CurryHunter_Descriptor(); - - struct Stats; - virtual std::unique_ptr make_stats() const override; -}; - - - -class CurryHunter : public SingleSwitchProgramInstance{ -public: - CurryHunter(); - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - MillisecondsOption WALK_UP_DELAY0; - SimpleIntegerOption SMALL_POKEMON; - BooleanCheckBoxOption TAKE_VIDEO; - SimpleIntegerOption ITERATIONS; -}; - - - - -} -} -} -#endif +/* Curry Bot + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_CurryHunter_H +#define PokemonAutomation_PokemonSwSh_CurryHunter_H + +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class CurryHunter_Descriptor : public SingleSwitchProgramDescriptor{ +public: + CurryHunter_Descriptor(); + + struct Stats; + virtual std::unique_ptr make_stats() const override; +}; + + + +class CurryHunter : public SingleSwitchProgramInstance{ +public: + CurryHunter(); + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + MillisecondsOption WALK_UP_DELAY0; + SimpleIntegerOption SMALL_POKEMON; + BooleanCheckBoxOption TAKE_VIDEO; + SimpleIntegerOption ITERATIONS; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp index 4cf8136d0d..f0bcfb27bf 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.cpp @@ -1,175 +1,175 @@ -/* Multiple Game Fossil - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_MultiGameFossil.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -MultiGameFossil_Descriptor::MultiGameFossil_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:MultiGameFossil", - STRING_POKEMON + " SwSh", "Multi-Game Fossil Revive", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MultiGameFossil.md", - "Revive fossils. Supports multiple saves so you can go afk for longer than 5 hours.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {ControllerFeature::NintendoSwitch_ProController}, - FasterIfTickPrecise::FASTER - ) -{} - - - -MultiGameFossil::MultiGameFossil(){ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(GAME_LIST); -} - -void run_fossil_batch( - ConsoleHandle& console, - ProControllerContext& context, - const FossilGame& batch, - bool* game_slot_flipped, - bool save_and_exit -){ - // Sanitize Slots - uint8_t game_slot = (uint8_t)batch.game_slot.current_value(); - uint8_t user_slot = (uint8_t)batch.user_slot.current_value(); - if (game_slot > 2){ - game_slot = 0; - } - - console.log( - std::string("Batch:") + - "\nGame Slot: " + std::to_string(game_slot) + - "\nUser Slot: " + std::to_string(user_slot) + - "\nFossil: " + std::to_string(batch.fossil.current_value()) + - "\nRevives: " + std::to_string(batch.revives) - ); - - // Calculate current game slot. - switch (game_slot){ - case 0: - break; - case 1: - game_slot = *game_slot_flipped ? 2 : 0; - break; - case 2: - game_slot = *game_slot_flipped ? 0 : 2; - break; - } - - start_game_from_home( - console, context, - ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, - game_slot, - user_slot, - false - ); - if (game_slot == 2){ - *game_slot_flipped = !*game_slot_flipped; - } - - // Revive -#if 1 - for (uint16_t c = 0; c < batch.revives; c++){ -#if 1 - ssf_mash_AZs(context, 170); - pbf_wait(context, 65); -#else - ssf_mash_AZs(context, 50); - pbf_wait(context, 140); - ssf_press_button1(context, BUTTON_A, 160); -#endif - switch (batch.fossil){ - case Fossil::Dracozolt: - ssf_press_button_ptv(context, BUTTON_A, 1280ms); - break; - case Fossil::Arctozolt: - ssf_press_button_ptv(context, BUTTON_A, 1280ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); - break; - case Fossil::Dracovish: - ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); - ssf_press_button_ptv(context, BUTTON_A, 1280ms); - break; - case Fossil::Arctovish: - ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); - ssf_press_button_ptv(context, BUTTON_A, 1280ms); - ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); - break; - } - - if (context->performance_class() == ControllerPerformanceClass::SysbotBase){ - ssf_mash_AZs(context, 4000ms); - }else{ - ssf_mash_AZs(context, 3200ms); - } - pbf_mash_button( - context, - BUTTON_B, - GameSettings::instance().AUTO_DEPOSIT ? 1400 : 1520 - ); - } - pbf_wait(context, 100); -#endif - - if (!save_and_exit){ -// ssf_press_button2(BUTTON_HOME, GAME_TO_HOME_DELAY_SAFE, 10); - return; - } - - // Save game. - ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); - ssf_press_button(context, BUTTON_R, 1200ms, 160ms); - ssf_press_button(context, BUTTON_A, 4000ms, 80ms); - - // Exit game. - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); - close_game(console, context); -} - - -void MultiGameFossil::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - std::vector> list = GAME_LIST.copy_snapshot(); - -// FossilGame2 batch; - - size_t games = list.size(); - - bool game_slot_flipped = false; - for (size_t c = 0; c < games; c++){ -// batch = GAME_LIST2[c]; - run_fossil_batch(env.console, context, *list[c], &game_slot_flipped, c + 1 < games); - } - - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); -} - - - -} -} -} - +/* Multiple Game Fossil + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_MultiGameFossil.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +MultiGameFossil_Descriptor::MultiGameFossil_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:MultiGameFossil", + STRING_POKEMON + " SwSh", "Multi-Game Fossil Revive", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/MultiGameFossil.md", + "Revive fossils. Supports multiple saves so you can go afk for longer than 5 hours.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {ControllerFeature::NintendoSwitch_ProController}, + FasterIfTickPrecise::FASTER + ) +{} + + + +MultiGameFossil::MultiGameFossil(){ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(GAME_LIST); +} + +void run_fossil_batch( + ConsoleHandle& console, + ProControllerContext& context, + const FossilGame& batch, + bool* game_slot_flipped, + bool save_and_exit +){ + // Sanitize Slots + uint8_t game_slot = (uint8_t)batch.game_slot.current_value(); + uint8_t user_slot = (uint8_t)batch.user_slot.current_value(); + if (game_slot > 2){ + game_slot = 0; + } + + console.log( + std::string("Batch:") + + "\nGame Slot: " + std::to_string(game_slot) + + "\nUser Slot: " + std::to_string(user_slot) + + "\nFossil: " + std::to_string(batch.fossil.current_value()) + + "\nRevives: " + std::to_string(batch.revives) + ); + + // Calculate current game slot. + switch (game_slot){ + case 0: + break; + case 1: + game_slot = *game_slot_flipped ? 2 : 0; + break; + case 2: + game_slot = *game_slot_flipped ? 0 : 2; + break; + } + + start_game_from_home( + console, context, + ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, + game_slot, + user_slot, + false + ); + if (game_slot == 2){ + *game_slot_flipped = !*game_slot_flipped; + } + + // Revive +#if 1 + for (uint16_t c = 0; c < batch.revives; c++){ +#if 1 + ssf_mash_AZs(context, 170); + pbf_wait(context, 65); +#else + ssf_mash_AZs(context, 50); + pbf_wait(context, 140); + ssf_press_button1(context, BUTTON_A, 160); +#endif + switch (batch.fossil){ + case Fossil::Dracozolt: + ssf_press_button_ptv(context, BUTTON_A, 1280ms); + break; + case Fossil::Arctozolt: + ssf_press_button_ptv(context, BUTTON_A, 1280ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); + break; + case Fossil::Dracovish: + ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); + ssf_press_button_ptv(context, BUTTON_A, 1280ms); + break; + case Fossil::Arctovish: + ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); + ssf_press_button_ptv(context, BUTTON_A, 1280ms); + ssf_press_dpad_ptv(context, DPAD_DOWN, 40ms); + break; + } + + if (context->performance_class() == ControllerPerformanceClass::SysbotBase){ + ssf_mash_AZs(context, 4000ms); + }else{ + ssf_mash_AZs(context, 3200ms); + } + pbf_mash_button( + context, + BUTTON_B, + GameSettings::instance().AUTO_DEPOSIT ? 1400 : 1520 + ); + } + pbf_wait(context, 100); +#endif + + if (!save_and_exit){ +// ssf_press_button2(BUTTON_HOME, GAME_TO_HOME_DELAY_SAFE, 10); + return; + } + + // Save game. + ssf_press_button(context, BUTTON_X, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0, 160ms); + ssf_press_button(context, BUTTON_R, 1200ms, 160ms); + ssf_press_button(context, BUTTON_A, 4000ms, 80ms); + + // Exit game. + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 80ms); + close_game(console, context); +} + + +void MultiGameFossil::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + std::vector> list = GAME_LIST.copy_snapshot(); + +// FossilGame2 batch; + + size_t games = list.size(); + + bool game_slot_flipped = false; + for (size_t c = 0; c < games; c++){ +// batch = GAME_LIST2[c]; + run_fossil_batch(env.console, context, *list[c], &game_slot_flipped, c + 1 < games); + } + + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0, 160ms); +} + + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h index 27a0a733b4..02c404f7ff 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_MultiGameFossil.h @@ -1,42 +1,42 @@ -/* Multiple Game Fossil - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MultiGameFossil_H -#define PokemonAutomation_PokemonSwSh_MultiGameFossil_H - -#include "Common/PokemonSwSh/PokemonSwSh_FossilTable.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class MultiGameFossil_Descriptor : public SingleSwitchProgramDescriptor{ -public: - MultiGameFossil_Descriptor(); -}; - - - -class MultiGameFossil : public SingleSwitchProgramInstance{ -public: - MultiGameFossil(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrClosedOption START_LOCATION; - FossilTable GAME_LIST; -}; - - -} -} -} -#endif - +/* Multiple Game Fossil + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MultiGameFossil_H +#define PokemonAutomation_PokemonSwSh_MultiGameFossil_H + +#include "Common/PokemonSwSh/PokemonSwSh_FossilTable.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class MultiGameFossil_Descriptor : public SingleSwitchProgramDescriptor{ +public: + MultiGameFossil_Descriptor(); +}; + + + +class MultiGameFossil : public SingleSwitchProgramInstance{ +public: + MultiGameFossil(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrClosedOption START_LOCATION; + FossilTable GAME_LIST; +}; + + +} +} +} +#endif + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.cpp index 5765d475be..4737961d39 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.cpp @@ -1,126 +1,126 @@ -/* Regi Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "PokemonSwSh_ShinyHunt-Regi.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void move_to_corner( - Logger& logger, ProControllerContext& context, - bool correction, Milliseconds TRANSITION_DELAY -){ - if (correction){ - logger.log("Performing auto-correction."); - // Move down to building exit and exit. - pbf_move_left_joystick(context, 128, 255, 4000ms, TRANSITION_DELAY); - pbf_move_left_joystick(context, 128, 255, 2400ms, TRANSITION_DELAY); - - // Navigate back into the corner. - pbf_move_left_joystick(context, 255, 64, 200, 0); - pbf_move_left_joystick(context, 120, 0, 250, 0); - pbf_move_left_joystick(context, 255, 100, 150, 10); - }else{ - // Move to corner. - pbf_move_left_joystick(context, 255, 100, 300, 10); - } -} - - -void regirock(ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 232, 169, 0); - pbf_move_left_joystick(context, 128, 255, 135, 0); - pbf_move_left_joystick(context, 0, 128, 109, 0); - pbf_move_left_joystick(context, 128, 0, 140, 0); - pbf_move_left_joystick(context, 226, 255, 90, 0); - pbf_move_left_joystick(context, 128, 0, 20, 0); - pbf_mash_button(context, BUTTON_A, 5000ms); - pbf_move_left_joystick(context, 128, 0, 200, 0); -} -void regice(ProControllerContext& context){ - pbf_move_left_joystick(context, 80, 255, 182, 0); - pbf_move_left_joystick(context, 0, 128, 114, 0); - pbf_move_left_joystick(context, 128, 255, 56, 0); - pbf_move_left_joystick(context, 32, 0, 76, 0); - pbf_move_left_joystick(context, 0, 128, 54, 0); - pbf_move_left_joystick(context, 255, 68, 153, 0); - pbf_move_left_joystick(context, 128, 0, 20, 0); - pbf_mash_button(context, BUTTON_A, 5000ms); - pbf_move_left_joystick(context, 128, 0, 170, 0); -} -void registeel(ProControllerContext& context){ - pbf_move_left_joystick(context, 0, 232, 169, 0); - pbf_move_left_joystick(context, 192, 255, 64, 0); - pbf_move_left_joystick(context, 64, 255, 64, 0); - pbf_move_left_joystick(context, 0, 128, 110, 0); - pbf_move_left_joystick(context, 64, 0, 68, 0); - pbf_move_left_joystick(context, 192, 0, 66, 0); - pbf_move_left_joystick(context, 230, 255, 90, 0); - pbf_move_left_joystick(context, 128, 0, 50, 0); - pbf_mash_button(context, BUTTON_A, 5000ms); - pbf_move_left_joystick(context, 128, 0, 250, 0); -} -void regieleki(ProControllerContext& context){ - pbf_move_left_joystick(context, 16, 255, 162, 0); - pbf_move_left_joystick(context, 64, 255, 52, 0); - pbf_move_left_joystick(context, 200, 255, 52, 0); - pbf_move_left_joystick(context, 0, 50, 122, 0); - pbf_move_left_joystick(context, 0, 206, 93, 0); - pbf_move_left_joystick(context, 208, 0, 78, 0); - pbf_move_left_joystick(context, 60, 0, 80, 0); - pbf_mash_button(context, BUTTON_A, 5000ms); - pbf_move_left_joystick(context, 216, 0, 170, 0); -} -void regidrago(ProControllerContext& context){ - pbf_move_left_joystick(context, 16, 255, 160, 0); - pbf_move_left_joystick(context, 72, 255, 50, 0); - pbf_move_left_joystick(context, 48, 255, 106, 0); - pbf_move_left_joystick(context, 128, 0, 48, 0); - pbf_move_left_joystick(context, 0, 56, 60, 0); - pbf_move_left_joystick(context, 64, 0, 60, 0); - pbf_move_left_joystick(context, 255, 152, 80, 0); - pbf_move_left_joystick(context, 128, 0, 20, 0); - pbf_mash_button(context, BUTTON_A, 5000ms); - pbf_move_left_joystick(context, 128, 0, 180, 0); -} - -void run_regi_light_puzzle( - Logger& logger, ProControllerContext& context, - RegiGolem regi, uint64_t encounter -){ - switch (regi){ - case RegiGolem::Regirock: - regirock(context); - logger.log("Starting Regirock Encounter: " + tostr_u_commas(encounter + 1)); - break; - case RegiGolem::Regice: - regice(context); - logger.log("Starting Regice Encounter: " + tostr_u_commas(encounter + 1)); - break; - case RegiGolem::Registeel: - registeel(context); - logger.log("Starting Registeel Encounter: " + tostr_u_commas(encounter + 1)); - break; - case RegiGolem::Regieleki: - regieleki(context); - logger.log("Starting Regieleki Encounter: " + tostr_u_commas(encounter + 1)); - break; - case RegiGolem::Regidrago: - regidrago(context); - logger.log("Starting Regidrago Encounter: " + tostr_u_commas(encounter + 1)); - break; - } -} - - -} -} -} - +/* Regi Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "PokemonSwSh_ShinyHunt-Regi.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void move_to_corner( + Logger& logger, ProControllerContext& context, + bool correction, Milliseconds TRANSITION_DELAY +){ + if (correction){ + logger.log("Performing auto-correction."); + // Move down to building exit and exit. + pbf_move_left_joystick(context, 128, 255, 4000ms, TRANSITION_DELAY); + pbf_move_left_joystick(context, 128, 255, 2400ms, TRANSITION_DELAY); + + // Navigate back into the corner. + pbf_move_left_joystick(context, 255, 64, 200, 0); + pbf_move_left_joystick(context, 120, 0, 250, 0); + pbf_move_left_joystick(context, 255, 100, 150, 10); + }else{ + // Move to corner. + pbf_move_left_joystick(context, 255, 100, 300, 10); + } +} + + +void regirock(ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 232, 169, 0); + pbf_move_left_joystick(context, 128, 255, 135, 0); + pbf_move_left_joystick(context, 0, 128, 109, 0); + pbf_move_left_joystick(context, 128, 0, 140, 0); + pbf_move_left_joystick(context, 226, 255, 90, 0); + pbf_move_left_joystick(context, 128, 0, 20, 0); + pbf_mash_button(context, BUTTON_A, 5000ms); + pbf_move_left_joystick(context, 128, 0, 200, 0); +} +void regice(ProControllerContext& context){ + pbf_move_left_joystick(context, 80, 255, 182, 0); + pbf_move_left_joystick(context, 0, 128, 114, 0); + pbf_move_left_joystick(context, 128, 255, 56, 0); + pbf_move_left_joystick(context, 32, 0, 76, 0); + pbf_move_left_joystick(context, 0, 128, 54, 0); + pbf_move_left_joystick(context, 255, 68, 153, 0); + pbf_move_left_joystick(context, 128, 0, 20, 0); + pbf_mash_button(context, BUTTON_A, 5000ms); + pbf_move_left_joystick(context, 128, 0, 170, 0); +} +void registeel(ProControllerContext& context){ + pbf_move_left_joystick(context, 0, 232, 169, 0); + pbf_move_left_joystick(context, 192, 255, 64, 0); + pbf_move_left_joystick(context, 64, 255, 64, 0); + pbf_move_left_joystick(context, 0, 128, 110, 0); + pbf_move_left_joystick(context, 64, 0, 68, 0); + pbf_move_left_joystick(context, 192, 0, 66, 0); + pbf_move_left_joystick(context, 230, 255, 90, 0); + pbf_move_left_joystick(context, 128, 0, 50, 0); + pbf_mash_button(context, BUTTON_A, 5000ms); + pbf_move_left_joystick(context, 128, 0, 250, 0); +} +void regieleki(ProControllerContext& context){ + pbf_move_left_joystick(context, 16, 255, 162, 0); + pbf_move_left_joystick(context, 64, 255, 52, 0); + pbf_move_left_joystick(context, 200, 255, 52, 0); + pbf_move_left_joystick(context, 0, 50, 122, 0); + pbf_move_left_joystick(context, 0, 206, 93, 0); + pbf_move_left_joystick(context, 208, 0, 78, 0); + pbf_move_left_joystick(context, 60, 0, 80, 0); + pbf_mash_button(context, BUTTON_A, 5000ms); + pbf_move_left_joystick(context, 216, 0, 170, 0); +} +void regidrago(ProControllerContext& context){ + pbf_move_left_joystick(context, 16, 255, 160, 0); + pbf_move_left_joystick(context, 72, 255, 50, 0); + pbf_move_left_joystick(context, 48, 255, 106, 0); + pbf_move_left_joystick(context, 128, 0, 48, 0); + pbf_move_left_joystick(context, 0, 56, 60, 0); + pbf_move_left_joystick(context, 64, 0, 60, 0); + pbf_move_left_joystick(context, 255, 152, 80, 0); + pbf_move_left_joystick(context, 128, 0, 20, 0); + pbf_mash_button(context, BUTTON_A, 5000ms); + pbf_move_left_joystick(context, 128, 0, 180, 0); +} + +void run_regi_light_puzzle( + Logger& logger, ProControllerContext& context, + RegiGolem regi, uint64_t encounter +){ + switch (regi){ + case RegiGolem::Regirock: + regirock(context); + logger.log("Starting Regirock Encounter: " + tostr_u_commas(encounter + 1)); + break; + case RegiGolem::Regice: + regice(context); + logger.log("Starting Regice Encounter: " + tostr_u_commas(encounter + 1)); + break; + case RegiGolem::Registeel: + registeel(context); + logger.log("Starting Registeel Encounter: " + tostr_u_commas(encounter + 1)); + break; + case RegiGolem::Regieleki: + regieleki(context); + logger.log("Starting Regieleki Encounter: " + tostr_u_commas(encounter + 1)); + break; + case RegiGolem::Regidrago: + regidrago(context); + logger.log("Starting Regidrago Encounter: " + tostr_u_commas(encounter + 1)); + break; + } +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h index dc953c346d..8b00caa07f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHunt-Regi.h @@ -1,35 +1,35 @@ -/* Regi Routines - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_RegiPatterns_H -#define PokemonAutomation_PokemonSwSh_RegiPatterns_H - -#include "Common/Cpp/AbstractLogger.h" -#include "Common/Cpp/Time.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "PokemonSwSh/Options/PokemonSwSh_RegiSelector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void move_to_corner( - Logger& logger, ProControllerContext& context, - bool correction, Milliseconds TRANSITION_DELAY -); - -void run_regi_light_puzzle( - Logger& logger, ProControllerContext& context, - RegiGolem regi, uint64_t encounter -); - - - -} -} -} -#endif +/* Regi Routines + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_RegiPatterns_H +#define PokemonAutomation_PokemonSwSh_RegiPatterns_H + +#include "Common/Cpp/AbstractLogger.h" +#include "Common/Cpp/Time.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "PokemonSwSh/Options/PokemonSwSh_RegiSelector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void move_to_corner( + Logger& logger, ProControllerContext& context, + bool correction, Milliseconds TRANSITION_DELAY +); + +void run_regi_light_puzzle( + Logger& logger, ProControllerContext& context, + RegiGolem regi, uint64_t encounter +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.cpp index 385792eb5f..2874c391c2 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.cpp @@ -1,82 +1,82 @@ -/* Shiny Hunting Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh_ShinyHuntTools.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void run_away_with_lights(ProControllerContext& context){ -// set_leds(context, true); - pbf_press_dpad(context, DPAD_UP, 10, 0); - pbf_press_button(context, BUTTON_A, 10, 3 * TICKS_PER_SECOND); -// set_leds(context, false); -} -void enter_summary(ProControllerContext& context, bool regi_move_right){ - pbf_press_dpad(context, DPAD_DOWN, 10, 0); - pbf_press_button(context, BUTTON_A, 10, 2 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 10, 200); - if (regi_move_right){ - pbf_move_left_joystick(context, 255, 128, 20, 30); - } - pbf_press_dpad(context, DPAD_DOWN, 10, 0); - pbf_press_button(context, BUTTON_A, 10, 10); // For Regi, this clears the dialog after running. -} -void close_game_if_overworld( - ConsoleHandle& console, ProControllerContext& context, - bool touch_date, - uint8_t rollback_hours -){ - // Enter Y-COMM. - ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 80ms); - - // Move the cursor as far away from Link Trade and Surprise Trade as possible. - // This is added safety in case connect to internet takes too long. - pbf_press_dpad(context, DPAD_UP, 5, 0); - pbf_move_right_joystick(context, 128, 0, 5, 0); - pbf_press_dpad(context, DPAD_RIGHT, 5, 0); - - // Connect to internet. - pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); - - // Enter Switch Home. - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - - if (touch_date){ - touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - } - if (rollback_hours > 0){ - rollback_hours_from_home(console, context, rollback_hours, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - } - - // Enter profile. - pbf_press_dpad(context, DPAD_UP, 10, 10); - pbf_press_button(context, BUTTON_A, 80ms, GameSettings::instance().ENTER_PROFILE_DELAY0); - - // Back out. - pbf_press_dpad(context, DPAD_LEFT, 10, 10); - pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_DOWN, 10, 10); - - // Close and restart game. - close_game(console, context); - pbf_press_button(context, BUTTON_HOME, 10, 190); -} - - -} -} -} - +/* Shiny Hunting Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Routines.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +//#include "PokemonSwSh/Commands/PokemonSwSh_Commands_GameEntry.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh_ShinyHuntTools.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void run_away_with_lights(ProControllerContext& context){ +// set_leds(context, true); + pbf_press_dpad(context, DPAD_UP, 10, 0); + pbf_press_button(context, BUTTON_A, 10, 3 * TICKS_PER_SECOND); +// set_leds(context, false); +} +void enter_summary(ProControllerContext& context, bool regi_move_right){ + pbf_press_dpad(context, DPAD_DOWN, 10, 0); + pbf_press_button(context, BUTTON_A, 10, 2 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 10, 200); + if (regi_move_right){ + pbf_move_left_joystick(context, 255, 128, 20, 30); + } + pbf_press_dpad(context, DPAD_DOWN, 10, 0); + pbf_press_button(context, BUTTON_A, 10, 10); // For Regi, this clears the dialog after running. +} +void close_game_if_overworld( + ConsoleHandle& console, ProControllerContext& context, + bool touch_date, + uint8_t rollback_hours +){ + // Enter Y-COMM. + ssf_press_button(context, BUTTON_Y, GameSettings::instance().OPEN_YCOMM_DELAY0, 80ms); + + // Move the cursor as far away from Link Trade and Surprise Trade as possible. + // This is added safety in case connect to internet takes too long. + pbf_press_dpad(context, DPAD_UP, 5, 0); + pbf_move_right_joystick(context, 128, 0, 5, 0); + pbf_press_dpad(context, DPAD_RIGHT, 5, 0); + + // Connect to internet. + pbf_press_button(context, BUTTON_PLUS, 10, TICKS_PER_SECOND); + + // Enter Switch Home. + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + + if (touch_date){ + touch_date_from_home(console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + } + if (rollback_hours > 0){ + rollback_hours_from_home(console, context, rollback_hours, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + } + + // Enter profile. + pbf_press_dpad(context, DPAD_UP, 10, 10); + pbf_press_button(context, BUTTON_A, 80ms, GameSettings::instance().ENTER_PROFILE_DELAY0); + + // Back out. + pbf_press_dpad(context, DPAD_LEFT, 10, 10); + pbf_press_button(context, BUTTON_B, 10, TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_DOWN, 10, 10); + + // Close and restart game. + close_game(console, context); + pbf_press_button(context, BUTTON_HOME, 10, 190); +} + + +} +} +} + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.h index a6a01d322c..19615b35a5 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntTools.h @@ -1,32 +1,32 @@ -/* Shiny Hunting Tools - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntingTools_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntingTools_H - -#include "CommonFramework/Tools/VideoStream.h" -#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -void run_away_with_lights(ProControllerContext& context); -void enter_summary(ProControllerContext& context, bool regi_move_right); -void close_game_if_overworld( - ConsoleHandle& console, ProControllerContext& context, - bool touch_date, - uint8_t rollback_hours -); - - - -} -} -} -#endif +/* Shiny Hunting Tools + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntingTools_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntingTools_H + +#include "CommonFramework/Tools/VideoStream.h" +#include "NintendoSwitch/Controllers/NintendoSwitch_ProController.h" +#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +void run_away_with_lights(ProControllerContext& context); +void enter_summary(ProControllerContext& context, bool regi_move_right); +void close_game_if_overworld( + ConsoleHandle& console, ProControllerContext& context, + bool touch_date, + uint8_t rollback_hours +); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp index 4629f6cae2..b61d94b45d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.cpp @@ -1,153 +1,153 @@ -/* ShinyHuntUnattended-IoATrade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_ShinyHuntTools.h" -#include "PokemonSwSh_ShinyHuntUnattended-IoATrade.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -ShinyHuntUnattendedIoATrade_Descriptor::ShinyHuntUnattendedIoATrade_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntUnattendedIoATrade", - STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - IoA Trade", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-IoATrade.md", - "Hunt for shiny Isle of Armor trade. Stop when a shiny is found.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -ShinyHuntUnattendedIoATrade::ShinyHuntUnattendedIoATrade() - : START_TO_RUN_DELAY0( - "Start to Run Delay:
This needs to be carefully calibrated.", - LockMode::LOCK_WHILE_RUNNING, - "10080 ms" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , FLY_DURATION0( - "Fly Duration:", - LockMode::LOCK_WHILE_RUNNING, - "6400 ms" - ) - , MOVE_DURATION0( - "Move to Beartic Duration:", - LockMode::LOCK_WHILE_RUNNING, - "2400 ms" - ) - , MASH_TO_TRADE_DELAY0( - "Mash to Trade Delay:
Time to perform the trade.", - LockMode::LOCK_WHILE_RUNNING, - "30 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(START_TO_RUN_DELAY0); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(FLY_DURATION0); - PA_ADD_OPTION(MOVE_DURATION0); - PA_ADD_OPTION(MASH_TO_TRADE_DELAY0); -} - -void ShinyHuntUnattendedIoATrade::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - for (uint32_t c = 0; ; c++){ - env.log("Starting Trade: " + tostr_u_commas(c + 1)); - - pbf_press_button(context, BUTTON_A, 10, 100); - pbf_press_button(context, BUTTON_A, 10, 60); - pbf_press_button(context, BUTTON_A, 10, 100); - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_press_button(context, BUTTON_A, 80ms, GameSettings::instance().POKEMON_TO_BOX_DELAY0); - pbf_press_dpad(context, DPAD_LEFT, 10, 10); - pbf_mash_button(context, BUTTON_A, MASH_TO_TRADE_DELAY0); - - if (true){ - // Enter box system. - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_dpad(context, DPAD_RIGHT, 10, 10); - pbf_press_button(context, BUTTON_A, 80ms, GameSettings::instance().MENU_TO_POKEMON_DELAY0); - - // Move item from 2nd party member to 1st. - pbf_press_button(context, BUTTON_X, 10, 50); - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - pbf_press_dpad(context, DPAD_UP, 10, 50); - pbf_press_button(context, BUTTON_A, 10, 50); - - // Back out to menu. - // Prepend each B press by a DOWN press so that the B gets - // swallowed while in the summary. - IoA_backout(context, GameSettings::instance().POKEMON_TO_MENU_DELAY0); - - // Enter map. - pbf_press_dpad(context, DPAD_LEFT, 10, 0); - pbf_move_left_joystick(context, 128, 255, 10, 0); - }else{ - pbf_press_dpad(context, DPAD_DOWN, 10, 50); - } - pbf_press_button(context, BUTTON_A, 10, 350); - - // Fly to Route 10. - pbf_press_button(context, BUTTON_L, 10, 100); - pbf_press_button(context, BUTTON_L, 10, 100); - pbf_press_dpad(context, DPAD_RIGHT, 15, 10); - pbf_press_dpad(context, DPAD_DOWN, 30, 10); - pbf_mash_button(context, BUTTON_A, FLY_DURATION0); - - // Move to Beartic. - pbf_move_left_joystick(context, 240, 0, MOVE_DURATION0, 0ms); - - pbf_wait(context, START_TO_RUN_DELAY0); - - // Run away. - run_away_with_lights(context); - - // Enter Pokemon menu if shiny. - enter_summary(context, false); - - // Conditional close game. - close_game_if_overworld( - env.console, - context, - TOUCH_DATE_INTERVAL.ok_to_touch_now(), - 0 - ); - - start_game_from_home_with_inference(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 0, 0, false); - } - -// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); -} - - - -} -} -} +/* ShinyHuntUnattended-IoATrade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_Misc.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_ShinyHuntTools.h" +#include "PokemonSwSh_ShinyHuntUnattended-IoATrade.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +ShinyHuntUnattendedIoATrade_Descriptor::ShinyHuntUnattendedIoATrade_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntUnattendedIoATrade", + STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - IoA Trade", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-IoATrade.md", + "Hunt for shiny Isle of Armor trade. Stop when a shiny is found.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +ShinyHuntUnattendedIoATrade::ShinyHuntUnattendedIoATrade() + : START_TO_RUN_DELAY0( + "Start to Run Delay:
This needs to be carefully calibrated.", + LockMode::LOCK_WHILE_RUNNING, + "10080 ms" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , FLY_DURATION0( + "Fly Duration:", + LockMode::LOCK_WHILE_RUNNING, + "6400 ms" + ) + , MOVE_DURATION0( + "Move to Beartic Duration:", + LockMode::LOCK_WHILE_RUNNING, + "2400 ms" + ) + , MASH_TO_TRADE_DELAY0( + "Mash to Trade Delay:
Time to perform the trade.", + LockMode::LOCK_WHILE_RUNNING, + "30 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(START_TO_RUN_DELAY0); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(FLY_DURATION0); + PA_ADD_OPTION(MOVE_DURATION0); + PA_ADD_OPTION(MASH_TO_TRADE_DELAY0); +} + +void ShinyHuntUnattendedIoATrade::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + for (uint32_t c = 0; ; c++){ + env.log("Starting Trade: " + tostr_u_commas(c + 1)); + + pbf_press_button(context, BUTTON_A, 10, 100); + pbf_press_button(context, BUTTON_A, 10, 60); + pbf_press_button(context, BUTTON_A, 10, 100); + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_press_button(context, BUTTON_A, 80ms, GameSettings::instance().POKEMON_TO_BOX_DELAY0); + pbf_press_dpad(context, DPAD_LEFT, 10, 10); + pbf_mash_button(context, BUTTON_A, MASH_TO_TRADE_DELAY0); + + if (true){ + // Enter box system. + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_dpad(context, DPAD_RIGHT, 10, 10); + pbf_press_button(context, BUTTON_A, 80ms, GameSettings::instance().MENU_TO_POKEMON_DELAY0); + + // Move item from 2nd party member to 1st. + pbf_press_button(context, BUTTON_X, 10, 50); + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + pbf_press_dpad(context, DPAD_UP, 10, 50); + pbf_press_button(context, BUTTON_A, 10, 50); + + // Back out to menu. + // Prepend each B press by a DOWN press so that the B gets + // swallowed while in the summary. + IoA_backout(context, GameSettings::instance().POKEMON_TO_MENU_DELAY0); + + // Enter map. + pbf_press_dpad(context, DPAD_LEFT, 10, 0); + pbf_move_left_joystick(context, 128, 255, 10, 0); + }else{ + pbf_press_dpad(context, DPAD_DOWN, 10, 50); + } + pbf_press_button(context, BUTTON_A, 10, 350); + + // Fly to Route 10. + pbf_press_button(context, BUTTON_L, 10, 100); + pbf_press_button(context, BUTTON_L, 10, 100); + pbf_press_dpad(context, DPAD_RIGHT, 15, 10); + pbf_press_dpad(context, DPAD_DOWN, 30, 10); + pbf_mash_button(context, BUTTON_A, FLY_DURATION0); + + // Move to Beartic. + pbf_move_left_joystick(context, 240, 0, MOVE_DURATION0, 0ms); + + pbf_wait(context, START_TO_RUN_DELAY0); + + // Run away. + run_away_with_lights(context); + + // Enter Pokemon menu if shiny. + enter_summary(context, false); + + // Conditional close game. + close_game_if_overworld( + env.console, + context, + TOUCH_DATE_INTERVAL.ok_to_touch_now(), + 0 + ); + + start_game_from_home_with_inference(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 0, 0, false); + } + +// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h index 4fc02c478d..6ff40d54b4 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-IoATrade.h @@ -1,49 +1,49 @@ -/* ShinyHuntUnattended-IoATrade - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedIoATrade_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedIoATrade_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntUnattendedIoATrade_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntUnattendedIoATrade_Descriptor(); -}; - - - -class ShinyHuntUnattendedIoATrade : public SingleSwitchProgramInstance{ -public: - ShinyHuntUnattendedIoATrade(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - MillisecondsOption START_TO_RUN_DELAY0; - SectionDividerOption m_advanced_options; - MillisecondsOption FLY_DURATION0; - MillisecondsOption MOVE_DURATION0; - MillisecondsOption MASH_TO_TRADE_DELAY0; -}; - - -} -} -} -#endif +/* ShinyHuntUnattended-IoATrade + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedIoATrade_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedIoATrade_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntUnattendedIoATrade_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntUnattendedIoATrade_Descriptor(); +}; + + + +class ShinyHuntUnattendedIoATrade : public SingleSwitchProgramInstance{ +public: + ShinyHuntUnattendedIoATrade(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + MillisecondsOption START_TO_RUN_DELAY0; + SectionDividerOption m_advanced_options; + MillisecondsOption FLY_DURATION0; + MillisecondsOption MOVE_DURATION0; + MillisecondsOption MASH_TO_TRADE_DELAY0; +}; + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp index 2de16f250f..2e97a44273 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.cpp @@ -1,129 +1,129 @@ -/* ShinyHuntUnattended-Regi - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_ShinyHuntTools.h" -#include "PokemonSwSh_ShinyHunt-Regi.h" -#include "PokemonSwSh_ShinyHuntUnattended-Regi.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -ShinyHuntUnattendedRegi_Descriptor::ShinyHuntUnattendedRegi_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntUnattendedRegi", - STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Regi", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-Regi.md", - "Hunt for shiny Regis. Stop when a shiny is found.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -ShinyHuntUnattendedRegi::ShinyHuntUnattendedRegi() - : START_TO_RUN_DELAY0( - "Start to Run Delay:
This needs to be carefully calibrated.", - LockMode::LOCK_WHILE_RUNNING, - "15920 ms" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , CORRECTION_INTERVAL( - "Correction Interval:
Periodically leave the building to fix broken lights. Zero disables these corrections.", - LockMode::LOCK_WHILE_RUNNING, - 20 - ) - , TRANSITION_DELAY0( - "Transition Delay:
Time to enter/exit the building.", - LockMode::LOCK_WHILE_RUNNING, - "5000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(START_TO_RUN_DELAY0); - PA_ADD_OPTION(REGI_NAME); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(CORRECTION_INTERVAL); - PA_ADD_OPTION(TRANSITION_DELAY0); -} - - - -void ShinyHuntUnattendedRegi::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - uint16_t correct_count = 0; - for (uint32_t c = 0; ; c++){ - // Auto-correction. - bool correct = CORRECTION_INTERVAL > 0 && correct_count >= CORRECTION_INTERVAL; - move_to_corner(env.console, context, correct, TRANSITION_DELAY0); - if (correct){ - correct_count = 0; - } - - // Touch the date. - if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ - env.log("Touching date to prevent rollover."); - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - } - - - // Do the light puzzle. - run_regi_light_puzzle(env.console, context, REGI_NAME, c); - - pbf_press_button(context, BUTTON_A, 10, 100); - pbf_press_button(context, BUTTON_A, 10, 100); - Milliseconds start_to_run_delay = START_TO_RUN_DELAY0; - if (start_to_run_delay >= 4000ms){ - // Extra A press to fix A parity if the lights were messed up. - pbf_press_button(context, BUTTON_A, 80ms, 4000ms); - pbf_press_button(context, BUTTON_A, 80ms, start_to_run_delay - 4000ms); - }else{ - pbf_press_button(context, BUTTON_A, 80ms, start_to_run_delay); - } - - // Run away if not shiny. - run_away_with_lights(context); - - // Enter Pokemon menu if shiny. - enter_summary(context, true); - - correct_count++; - } - -// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); -// end_program_callback(env.console); -// end_program_loop(env.console); -} - - -} -} -} - - - +/* ShinyHuntUnattended-Regi + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_ShinyHuntTools.h" +#include "PokemonSwSh_ShinyHunt-Regi.h" +#include "PokemonSwSh_ShinyHuntUnattended-Regi.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +ShinyHuntUnattendedRegi_Descriptor::ShinyHuntUnattendedRegi_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntUnattendedRegi", + STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Regi", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-Regi.md", + "Hunt for shiny Regis. Stop when a shiny is found.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +ShinyHuntUnattendedRegi::ShinyHuntUnattendedRegi() + : START_TO_RUN_DELAY0( + "Start to Run Delay:
This needs to be carefully calibrated.", + LockMode::LOCK_WHILE_RUNNING, + "15920 ms" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , CORRECTION_INTERVAL( + "Correction Interval:
Periodically leave the building to fix broken lights. Zero disables these corrections.", + LockMode::LOCK_WHILE_RUNNING, + 20 + ) + , TRANSITION_DELAY0( + "Transition Delay:
Time to enter/exit the building.", + LockMode::LOCK_WHILE_RUNNING, + "5000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(START_TO_RUN_DELAY0); + PA_ADD_OPTION(REGI_NAME); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(CORRECTION_INTERVAL); + PA_ADD_OPTION(TRANSITION_DELAY0); +} + + + +void ShinyHuntUnattendedRegi::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 200); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + uint16_t correct_count = 0; + for (uint32_t c = 0; ; c++){ + // Auto-correction. + bool correct = CORRECTION_INTERVAL > 0 && correct_count >= CORRECTION_INTERVAL; + move_to_corner(env.console, context, correct, TRANSITION_DELAY0); + if (correct){ + correct_count = 0; + } + + // Touch the date. + if (TOUCH_DATE_INTERVAL.ok_to_touch_now()){ + env.log("Touching date to prevent rollover."); + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + touch_date_from_home(env.console, context, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + } + + + // Do the light puzzle. + run_regi_light_puzzle(env.console, context, REGI_NAME, c); + + pbf_press_button(context, BUTTON_A, 10, 100); + pbf_press_button(context, BUTTON_A, 10, 100); + Milliseconds start_to_run_delay = START_TO_RUN_DELAY0; + if (start_to_run_delay >= 4000ms){ + // Extra A press to fix A parity if the lights were messed up. + pbf_press_button(context, BUTTON_A, 80ms, 4000ms); + pbf_press_button(context, BUTTON_A, 80ms, start_to_run_delay - 4000ms); + }else{ + pbf_press_button(context, BUTTON_A, 80ms, start_to_run_delay); + } + + // Run away if not shiny. + run_away_with_lights(context); + + // Enter Pokemon menu if shiny. + enter_summary(context, true); + + correct_count++; + } + +// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); +// end_program_callback(env.console); +// end_program_loop(env.console); +} + + +} +} +} + + + diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h index 206097fb9f..574498554d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regi.h @@ -1,50 +1,50 @@ -/* ShinyHuntUnattended-Regi - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegi_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegi_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" -#include "PokemonSwSh/Options/PokemonSwSh_RegiSelector.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntUnattendedRegi_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntUnattendedRegi_Descriptor(); -}; - - - -class ShinyHuntUnattendedRegi : public SingleSwitchProgramInstance{ -public: - ShinyHuntUnattendedRegi(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - MillisecondsOption START_TO_RUN_DELAY0; - RegiSelectorOption REGI_NAME; - SectionDividerOption m_advanced_options; - SimpleIntegerOption CORRECTION_INTERVAL; - MillisecondsOption TRANSITION_DELAY0; -}; - -} -} -} -#endif +/* ShinyHuntUnattended-Regi + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegi_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegi_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" +#include "PokemonSwSh/Options/PokemonSwSh_RegiSelector.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntUnattendedRegi_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntUnattendedRegi_Descriptor(); +}; + + + +class ShinyHuntUnattendedRegi : public SingleSwitchProgramInstance{ +public: + ShinyHuntUnattendedRegi(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + MillisecondsOption START_TO_RUN_DELAY0; + RegiSelectorOption REGI_NAME; + SectionDividerOption m_advanced_options; + SimpleIntegerOption CORRECTION_INTERVAL; + MillisecondsOption TRANSITION_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp index ed4df32bc8..35f83d868f 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.cpp @@ -1,124 +1,124 @@ -/* ShinyHuntUnattended-Regigigas2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_ShinyHuntTools.h" -#include "PokemonSwSh_ShinyHuntUnattended-Regigigas2.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -ShinyHuntUnattendedRegigigas2_Descriptor::ShinyHuntUnattendedRegigigas2_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntUnattendedRegigigas2", - STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Regigigas2", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-Regigigas2.md", - "A new version of the Regigigas program that is faster.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -ShinyHuntUnattendedRegigigas2::ShinyHuntUnattendedRegigigas2() - : REVERSAL_PP( - "Reversal PP:
The amount of Reversal PP you are saved with.", - LockMode::LOCK_WHILE_RUNNING, - 24 - ) - , START_TO_ATTACK_DELAY0( - "Start to Attack Delay:
This needs to be carefully calibrated.", - LockMode::LOCK_WHILE_RUNNING, - "30000 ms" - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , ATTACK_TO_CATCH_DELAY0( - "Attack to Catch Delay:
Increase this if you seem to be catching Regigigas very often.", - LockMode::LOCK_WHILE_RUNNING, - "9000 ms" - ) - , CATCH_TO_OVERWORLD_DELAY0( - "Catch to Overworld Delay:", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TOUCH_DATE_INTERVAL); - - PA_ADD_OPTION(REVERSAL_PP); - PA_ADD_OPTION(START_TO_ATTACK_DELAY0); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(ATTACK_TO_CATCH_DELAY0); - PA_ADD_OPTION(CATCH_TO_OVERWORLD_DELAY0); -} - -void ShinyHuntUnattendedRegigigas2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - uint32_t encounter = 0; - while (true){ - for (uint8_t pp = REVERSAL_PP; pp > 0; pp--){ - env.log("Starting Regigigas Encounter: " + tostr_u_commas(++encounter)); - - pbf_press_button(context, BUTTON_A, 10, 3 * TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - pbf_press_button(context, BUTTON_A, 80ms, START_TO_ATTACK_DELAY0); - -// set_leds(context, true); - pbf_press_button(context, BUTTON_A, 10, 2 * TICKS_PER_SECOND); -// set_leds(context, false); - - // Enter Pokemon menu if shiny. - pbf_press_dpad(context, DPAD_DOWN, 10, 0); - pbf_mash_button(context, BUTTON_A, 2 * TICKS_PER_SECOND); - - pbf_press_dpad(context, DPAD_DOWN, 10, 0); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - pbf_press_dpad(context, DPAD_DOWN, 10, 0); - pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); - - pbf_wait(context, ATTACK_TO_CATCH_DELAY0); - pbf_press_dpad(context, DPAD_DOWN, 10, 0); - pbf_press_button(context, BUTTON_A, 80ms, CATCH_TO_OVERWORLD_DELAY0); - } - - // Conditional close game. - close_game_if_overworld( - env.console, - context, - TOUCH_DATE_INTERVAL.ok_to_touch_now(), - 0 - ); - - start_game_from_home_with_inference(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 0, 0, false); - } - - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); -} - - - -} -} -} +/* ShinyHuntUnattended-Regigigas2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_ShinyHuntTools.h" +#include "PokemonSwSh_ShinyHuntUnattended-Regigigas2.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +ShinyHuntUnattendedRegigigas2_Descriptor::ShinyHuntUnattendedRegigigas2_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntUnattendedRegigigas2", + STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Regigigas2", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-Regigigas2.md", + "A new version of the Regigigas program that is faster.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +ShinyHuntUnattendedRegigigas2::ShinyHuntUnattendedRegigigas2() + : REVERSAL_PP( + "Reversal PP:
The amount of Reversal PP you are saved with.", + LockMode::LOCK_WHILE_RUNNING, + 24 + ) + , START_TO_ATTACK_DELAY0( + "Start to Attack Delay:
This needs to be carefully calibrated.", + LockMode::LOCK_WHILE_RUNNING, + "30000 ms" + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , ATTACK_TO_CATCH_DELAY0( + "Attack to Catch Delay:
Increase this if you seem to be catching Regigigas very often.", + LockMode::LOCK_WHILE_RUNNING, + "9000 ms" + ) + , CATCH_TO_OVERWORLD_DELAY0( + "Catch to Overworld Delay:", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TOUCH_DATE_INTERVAL); + + PA_ADD_OPTION(REVERSAL_PP); + PA_ADD_OPTION(START_TO_ATTACK_DELAY0); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(ATTACK_TO_CATCH_DELAY0); + PA_ADD_OPTION(CATCH_TO_OVERWORLD_DELAY0); +} + +void ShinyHuntUnattendedRegigigas2::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_back_out(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 500); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + uint32_t encounter = 0; + while (true){ + for (uint8_t pp = REVERSAL_PP; pp > 0; pp--){ + env.log("Starting Regigigas Encounter: " + tostr_u_commas(++encounter)); + + pbf_press_button(context, BUTTON_A, 10, 3 * TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + pbf_press_button(context, BUTTON_A, 80ms, START_TO_ATTACK_DELAY0); + +// set_leds(context, true); + pbf_press_button(context, BUTTON_A, 10, 2 * TICKS_PER_SECOND); +// set_leds(context, false); + + // Enter Pokemon menu if shiny. + pbf_press_dpad(context, DPAD_DOWN, 10, 0); + pbf_mash_button(context, BUTTON_A, 2 * TICKS_PER_SECOND); + + pbf_press_dpad(context, DPAD_DOWN, 10, 0); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + pbf_press_dpad(context, DPAD_DOWN, 10, 0); + pbf_press_button(context, BUTTON_A, 10, TICKS_PER_SECOND); + + pbf_wait(context, ATTACK_TO_CATCH_DELAY0); + pbf_press_dpad(context, DPAD_DOWN, 10, 0); + pbf_press_button(context, BUTTON_A, 80ms, CATCH_TO_OVERWORLD_DELAY0); + } + + // Conditional close game. + close_game_if_overworld( + env.console, + context, + TOUCH_DATE_INTERVAL.ok_to_touch_now(), + 0 + ); + + start_game_from_home_with_inference(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST, 0, 0, false); + } + + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h index 52c80a7177..de9716293c 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-Regigigas2.h @@ -1,49 +1,49 @@ -/* ShinyHuntUnattended-Regigigas2 - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegigigas2_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegigigas2_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/SimpleIntegerOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntUnattendedRegigigas2_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntUnattendedRegigigas2_Descriptor(); -}; - - - -class ShinyHuntUnattendedRegigigas2 : public SingleSwitchProgramInstance{ -public: - ShinyHuntUnattendedRegigigas2(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TouchDateIntervalOption TOUCH_DATE_INTERVAL; - - SimpleIntegerOption REVERSAL_PP; - MillisecondsOption START_TO_ATTACK_DELAY0; - SectionDividerOption m_advanced_options; - MillisecondsOption ATTACK_TO_CATCH_DELAY0; - MillisecondsOption CATCH_TO_OVERWORLD_DELAY0; -}; - -} -} -} -#endif +/* ShinyHuntUnattended-Regigigas2 + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegigigas2_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedRegigigas2_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/SimpleIntegerOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntUnattendedRegigigas2_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntUnattendedRegigigas2_Descriptor(); +}; + + + +class ShinyHuntUnattendedRegigigas2 : public SingleSwitchProgramInstance{ +public: + ShinyHuntUnattendedRegigigas2(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TouchDateIntervalOption TOUCH_DATE_INTERVAL; + + SimpleIntegerOption REVERSAL_PP; + MillisecondsOption START_TO_ATTACK_DELAY0; + SectionDividerOption m_advanced_options; + MillisecondsOption ATTACK_TO_CATCH_DELAY0; + MillisecondsOption CATCH_TO_OVERWORLD_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp index 6458a2735b..654d8cf501 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.cpp @@ -1,117 +1,117 @@ -/* ShinyHuntUnattended-StrongSpawn - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh_ShinyHuntTools.h" -#include "PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -ShinyHuntUnattendedStrongSpawn_Descriptor::ShinyHuntUnattendedStrongSpawn_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntUnattendedStrongSpawn", - STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Strong Spawn", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-StrongSpawn.md", - "Hunt for shiny strong spawns. Stop when a shiny is found.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - - -ShinyHuntUnattendedStrongSpawn::ShinyHuntUnattendedStrongSpawn() - : ENTER_GAME_TO_RUN_DELAY0( - "Enter Game to Run Delay:
This needs to be carefully calibrated.", - LockMode::LOCK_WHILE_RUNNING, - "18240 ms" - ) - , START_GAME_WAIT_DELAY0( - "Start Game Wait Delay:
Decrease this if your game starts quickly.", - LockMode::LOCK_WHILE_RUNNING, - "20 s" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(ENTER_GAME_TO_RUN_DELAY0); - PA_ADD_OPTION(START_GAME_WAIT_DELAY0); -} - - - -void ShinyHuntUnattendedStrongSpawn::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); - } - - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - for (uint32_t c = 0; ; c++){ - - // If the update menu isn't there, these will get swallowed by the opening - // animation for the select user menu. - if (ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST){ - pbf_press_button(context, BUTTON_A, 5, 35); // Choose game - pbf_press_dpad(context, DPAD_UP, 5, 0); // Skip the update window. - } - - pbf_press_button(context, BUTTON_A, 10, 180); // Enter select user menu. - pbf_press_button(context, BUTTON_A, 10, 10); // Enter game - - // Switch to mashing ZR instead of A to get into the game. - // Mash your way into the game. - Milliseconds duration = GameSettings::instance().START_GAME_MASH0; - if (ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET){ - // Need to wait a bit longer for the internet check. - duration += ConsoleSettings::instance().START_GAME_INTERNET_CHECK_DELAY0; - } - pbf_mash_button(context, BUTTON_ZR, duration); - - // Wait for game to start. - pbf_wait(context, START_GAME_WAIT_DELAY0); - - // Enter game. - env.log("Starting Encounter: " + tostr_u_commas(c + 1)); - pbf_press_button(context, BUTTON_A, 80ms, ENTER_GAME_TO_RUN_DELAY0); - - // Run away. - run_away_with_lights(context); - - // Enter Pokemon menu if shiny. - enter_summary(context, false); - - // Touch the date and conditional close game. - if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ - last_touch += PERIOD; - close_game_if_overworld(env.console, context, false, TIME_ROLLBACK_HOURS); - }else{ - close_game_if_overworld(env.console, context, false, 0); - } - - } - -// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); -} - - -} -} -} +/* ShinyHuntUnattended-StrongSpawn + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_Superscalar.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh_ShinyHuntTools.h" +#include "PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +ShinyHuntUnattendedStrongSpawn_Descriptor::ShinyHuntUnattendedStrongSpawn_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntUnattendedStrongSpawn", + STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Strong Spawn", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-StrongSpawn.md", + "Hunt for shiny strong spawns. Stop when a shiny is found.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + + +ShinyHuntUnattendedStrongSpawn::ShinyHuntUnattendedStrongSpawn() + : ENTER_GAME_TO_RUN_DELAY0( + "Enter Game to Run Delay:
This needs to be carefully calibrated.", + LockMode::LOCK_WHILE_RUNNING, + "18240 ms" + ) + , START_GAME_WAIT_DELAY0( + "Start Game Wait Delay:
Decrease this if your game starts quickly.", + LockMode::LOCK_WHILE_RUNNING, + "20 s" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(ENTER_GAME_TO_RUN_DELAY0); + PA_ADD_OPTION(START_GAME_WAIT_DELAY0); +} + + + +void ShinyHuntUnattendedStrongSpawn::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + ssf_press_button(context, BUTTON_HOME, GameSettings::instance().GAME_TO_HOME_DELAY_FAST0, 160ms); + } + + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + for (uint32_t c = 0; ; c++){ + + // If the update menu isn't there, these will get swallowed by the opening + // animation for the select user menu. + if (ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST){ + pbf_press_button(context, BUTTON_A, 5, 35); // Choose game + pbf_press_dpad(context, DPAD_UP, 5, 0); // Skip the update window. + } + + pbf_press_button(context, BUTTON_A, 10, 180); // Enter select user menu. + pbf_press_button(context, BUTTON_A, 10, 10); // Enter game + + // Switch to mashing ZR instead of A to get into the game. + // Mash your way into the game. + Milliseconds duration = GameSettings::instance().START_GAME_MASH0; + if (ConsoleSettings::instance().START_GAME_REQUIRES_INTERNET){ + // Need to wait a bit longer for the internet check. + duration += ConsoleSettings::instance().START_GAME_INTERNET_CHECK_DELAY0; + } + pbf_mash_button(context, BUTTON_ZR, duration); + + // Wait for game to start. + pbf_wait(context, START_GAME_WAIT_DELAY0); + + // Enter game. + env.log("Starting Encounter: " + tostr_u_commas(c + 1)); + pbf_press_button(context, BUTTON_A, 80ms, ENTER_GAME_TO_RUN_DELAY0); + + // Run away. + run_away_with_lights(context); + + // Enter Pokemon menu if shiny. + enter_summary(context, false); + + // Touch the date and conditional close game. + if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ + last_touch += PERIOD; + close_game_if_overworld(env.console, context, false, TIME_ROLLBACK_HOURS); + }else{ + close_game_if_overworld(env.console, context, false, 0); + } + + } + +// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); +} + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h index ddb96b9748..8948c3e48d 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-StrongSpawn.h @@ -1,44 +1,44 @@ -/* ShinyHuntUnattended-StrongSpawn - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedStrongSpawn_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedStrongSpawn_H - -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntUnattendedStrongSpawn_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntUnattendedStrongSpawn_Descriptor(); -}; - - - -class ShinyHuntUnattendedStrongSpawn : public SingleSwitchProgramInstance{ -public: - ShinyHuntUnattendedStrongSpawn(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrClosedOption START_LOCATION; - TimeRollbackHoursOption TIME_ROLLBACK_HOURS; - - MillisecondsOption ENTER_GAME_TO_RUN_DELAY0; - MillisecondsOption START_GAME_WAIT_DELAY0; -}; - -} -} -} -#endif +/* ShinyHuntUnattended-StrongSpawn + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedStrongSpawn_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedStrongSpawn_H + +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntUnattendedStrongSpawn_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntUnattendedStrongSpawn_Descriptor(); +}; + + + +class ShinyHuntUnattendedStrongSpawn : public SingleSwitchProgramInstance{ +public: + ShinyHuntUnattendedStrongSpawn(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrClosedOption START_LOCATION; + TimeRollbackHoursOption TIME_ROLLBACK_HOURS; + + MillisecondsOption ENTER_GAME_TO_RUN_DELAY0; + MillisecondsOption START_GAME_WAIT_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp index de6f2f2e8e..9751940fc8 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.cpp @@ -1,112 +1,112 @@ -/* ShinyHuntUnattended-SwordsOfJustice - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" -#include "NintendoSwitch/NintendoSwitch_Settings.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/PokemonSwSh_Settings.h" -#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" -#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" -#include "PokemonSwSh_ShinyHuntTools.h" -#include "PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - using namespace Pokemon; - - -ShinyHuntUnattendedSwordsOfJustice_Descriptor::ShinyHuntUnattendedSwordsOfJustice_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyHuntUnattendedSwordsOfJustice", - STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Swords Of Justice", - "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-SwordsOfJustice.md", - "Hunt for shiny SOJs. Stop when a shiny is found.", - FeedbackType::NONE, - AllowCommandsWhenRunning::DISABLE_COMMANDS, - {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} - ) -{} - - -ShinyHuntUnattendedSwordsOfJustice::ShinyHuntUnattendedSwordsOfJustice() - : EXIT_CAMP_TO_RUN_DELAY0( - "Exit Camp to Run Delay:
This needs to be carefully calibrated.", - LockMode::LOCK_WHILE_RUNNING, - "15120 ms" - ) - , AIRPLANE_MODE( - "Airplane Mode:
Enable if airplane mode is on.", - LockMode::LOCK_WHILE_RUNNING, - false - ) - , m_advanced_options( - "Advanced Options: You should not need to touch anything below here." - ) - , ENTER_CAMP_DELAY0( - "Enter Camp Delay:", - LockMode::LOCK_WHILE_RUNNING, - "8000 ms" - ) -{ - PA_ADD_OPTION(START_LOCATION); - PA_ADD_OPTION(TIME_ROLLBACK_HOURS); - - PA_ADD_OPTION(EXIT_CAMP_TO_RUN_DELAY0); - PA_ADD_OPTION(AIRPLANE_MODE); - PA_ADD_STATIC(m_advanced_options); - PA_ADD_OPTION(ENTER_CAMP_DELAY0); -} - - - -void ShinyHuntUnattendedSwordsOfJustice::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - if (START_LOCATION.start_in_grip_menu()){ - grip_menu_connect_go_home(context); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - }else{ - pbf_press_button(context, BUTTON_B, 5, 5); - } - - WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); - WallClock last_touch = current_time(); - for (uint32_t c = 0; ; c++){ - // Touch the date. - if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ - pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); - rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); - resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); - last_touch += PERIOD; - } - - // Trigger encounter. - pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); - pbf_press_button(context, BUTTON_A, 80ms, ENTER_CAMP_DELAY0); - if (AIRPLANE_MODE){ - pbf_press_button(context, BUTTON_A, 10, 100); - pbf_press_button(context, BUTTON_A, 10, 100); - } - pbf_press_button(context, BUTTON_X, 10, 50); - pbf_press_dpad(context, DPAD_LEFT, 10, 10); - env.log("Starting Encounter: " + tostr_u_commas(c + 1)); - pbf_press_button(context, BUTTON_A, 80ms, EXIT_CAMP_TO_RUN_DELAY0); - - // Run away if not shiny. - run_away_with_lights(context); - - // Enter Pokemon menu if shiny. - enter_summary(context, false); - } - -// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); -} - - - -} -} -} +/* ShinyHuntUnattended-SwordsOfJustice + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "NintendoSwitch/Commands/NintendoSwitch_Commands_PushButtons.h" +#include "NintendoSwitch/NintendoSwitch_Settings.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/PokemonSwSh_Settings.h" +#include "PokemonSwSh/Commands/PokemonSwSh_Commands_DateSpam.h" +#include "PokemonSwSh/Programs/PokemonSwSh_GameEntry.h" +#include "PokemonSwSh_ShinyHuntTools.h" +#include "PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + using namespace Pokemon; + + +ShinyHuntUnattendedSwordsOfJustice_Descriptor::ShinyHuntUnattendedSwordsOfJustice_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyHuntUnattendedSwordsOfJustice", + STRING_POKEMON + " SwSh", "Shiny Hunt Unattended - Swords Of Justice", + "ComputerControl/blob/master/Wiki/Programs/PokemonSwSh/ShinyHuntUnattended-SwordsOfJustice.md", + "Hunt for shiny SOJs. Stop when a shiny is found.", + FeedbackType::NONE, + AllowCommandsWhenRunning::DISABLE_COMMANDS, + {SerialPABotBase::OLD_NINTENDO_SWITCH_DEFAULT_REQUIREMENTS} + ) +{} + + +ShinyHuntUnattendedSwordsOfJustice::ShinyHuntUnattendedSwordsOfJustice() + : EXIT_CAMP_TO_RUN_DELAY0( + "Exit Camp to Run Delay:
This needs to be carefully calibrated.", + LockMode::LOCK_WHILE_RUNNING, + "15120 ms" + ) + , AIRPLANE_MODE( + "Airplane Mode:
Enable if airplane mode is on.", + LockMode::LOCK_WHILE_RUNNING, + false + ) + , m_advanced_options( + "Advanced Options: You should not need to touch anything below here." + ) + , ENTER_CAMP_DELAY0( + "Enter Camp Delay:", + LockMode::LOCK_WHILE_RUNNING, + "8000 ms" + ) +{ + PA_ADD_OPTION(START_LOCATION); + PA_ADD_OPTION(TIME_ROLLBACK_HOURS); + + PA_ADD_OPTION(EXIT_CAMP_TO_RUN_DELAY0); + PA_ADD_OPTION(AIRPLANE_MODE); + PA_ADD_STATIC(m_advanced_options); + PA_ADD_OPTION(ENTER_CAMP_DELAY0); +} + + + +void ShinyHuntUnattendedSwordsOfJustice::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + if (START_LOCATION.start_in_grip_menu()){ + grip_menu_connect_go_home(context); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + }else{ + pbf_press_button(context, BUTTON_B, 5, 5); + } + + WallDuration PERIOD = std::chrono::hours(TIME_ROLLBACK_HOURS); + WallClock last_touch = current_time(); + for (uint32_t c = 0; ; c++){ + // Touch the date. + if (TIME_ROLLBACK_HOURS > 0 && current_time() - last_touch >= PERIOD){ + pbf_press_button(context, BUTTON_HOME, 160ms, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE0); + rollback_hours_from_home(env.console, context, TIME_ROLLBACK_HOURS, ConsoleSettings::instance().SETTINGS_TO_HOME_DELAY0); + resume_game_no_interact(env.console, context, ConsoleSettings::instance().TOLERATE_SYSTEM_UPDATE_MENU_FAST); + last_touch += PERIOD; + } + + // Trigger encounter. + pbf_press_button(context, BUTTON_X, 80ms, GameSettings::instance().OVERWORLD_TO_MENU_DELAY0); + pbf_press_button(context, BUTTON_A, 80ms, ENTER_CAMP_DELAY0); + if (AIRPLANE_MODE){ + pbf_press_button(context, BUTTON_A, 10, 100); + pbf_press_button(context, BUTTON_A, 10, 100); + } + pbf_press_button(context, BUTTON_X, 10, 50); + pbf_press_dpad(context, DPAD_LEFT, 10, 10); + env.log("Starting Encounter: " + tostr_u_commas(c + 1)); + pbf_press_button(context, BUTTON_A, 80ms, EXIT_CAMP_TO_RUN_DELAY0); + + // Run away if not shiny. + run_away_with_lights(context); + + // Enter Pokemon menu if shiny. + enter_summary(context, false); + } + +// pbf_press_button(context, BUTTON_HOME, 10, GameSettings::instance().GAME_TO_HOME_DELAY_SAFE); +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h index 274923e79b..3354ac89c6 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/ShinyHuntUnattended/PokemonSwSh_ShinyHuntUnattended-SwordsOfJustice.h @@ -1,48 +1,48 @@ -/* ShinyHuntUnattended-SwordsOfJustice - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedSwordsOfJustice_H -#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedSwordsOfJustice_H - -#include "Common/Cpp/Options/StaticTextOption.h" -#include "Common/Cpp/Options/BooleanCheckBoxOption.h" -#include "Common/Cpp/Options/TimeDurationOption.h" -#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" -#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -class ShinyHuntUnattendedSwordsOfJustice_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyHuntUnattendedSwordsOfJustice_Descriptor(); -}; - - - -class ShinyHuntUnattendedSwordsOfJustice : public SingleSwitchProgramInstance{ -public: - ShinyHuntUnattendedSwordsOfJustice(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - StartInGripOrGameOption START_LOCATION; - TimeRollbackHoursOption TIME_ROLLBACK_HOURS; - - MillisecondsOption EXIT_CAMP_TO_RUN_DELAY0; - BooleanCheckBoxOption AIRPLANE_MODE; - SectionDividerOption m_advanced_options; - MillisecondsOption ENTER_CAMP_DELAY0; -}; - -} -} -} -#endif +/* ShinyHuntUnattended-SwordsOfJustice + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedSwordsOfJustice_H +#define PokemonAutomation_PokemonSwSh_ShinyHuntUnattendedSwordsOfJustice_H + +#include "Common/Cpp/Options/StaticTextOption.h" +#include "Common/Cpp/Options/BooleanCheckBoxOption.h" +#include "Common/Cpp/Options/TimeDurationOption.h" +#include "NintendoSwitch/Options/NintendoSwitch_StartInGripMenuOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" +#include "PokemonSwSh/Options/PokemonSwSh_DateToucher.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +class ShinyHuntUnattendedSwordsOfJustice_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyHuntUnattendedSwordsOfJustice_Descriptor(); +}; + + + +class ShinyHuntUnattendedSwordsOfJustice : public SingleSwitchProgramInstance{ +public: + ShinyHuntUnattendedSwordsOfJustice(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + StartInGripOrGameOption START_LOCATION; + TimeRollbackHoursOption TIME_ROLLBACK_HOURS; + + MillisecondsOption EXIT_CAMP_TO_RUN_DELAY0; + BooleanCheckBoxOption AIRPLANE_MODE; + SectionDividerOption m_advanced_options; + MillisecondsOption ENTER_CAMP_DELAY0; +}; + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.cpp b/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.cpp index d684a2c6e6..c2eefe86f9 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.cpp @@ -1,61 +1,61 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/PrettyPrint.h" -#include "Pokemon/Pokemon_Strings.h" -#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" -#include "PokemonSwSh_ShinyEncounterTester.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -ShinyEncounterTester_Descriptor::ShinyEncounterTester_Descriptor() - : SingleSwitchProgramDescriptor( - "PokemonSwSh:ShinyEncounterTester", - STRING_POKEMON + " SwSh", "Shiny Encounter Tester", - "", - "Test the shiny encounter detector. Start this program just before an encounter.", - FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, - {}, - FasterIfTickPrecise::NOT_FASTER - ) -{} - - - -ShinyEncounterTester::ShinyEncounterTester() - : ENCOUNTER_TYPE( - "Encounter Type:", - { - {EncounterType::Wild, "wild", "Wild Encounter"}, - {EncounterType::Raid, "raid", "Raid Den"}, - }, - LockMode::LOCK_WHILE_RUNNING, - EncounterType::Wild - ) -{ - PA_ADD_OPTION(ENCOUNTER_TYPE); -} - - -void ShinyEncounterTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ - ShinyDetectionResult result = detect_shiny_battle( - env.console, context, - ENCOUNTER_TYPE == EncounterType::Wild ? SHINY_BATTLE_REGULAR : SHINY_BATTLE_RAID, - std::chrono::seconds(30) - ); - result.get_best_screenshot().save(now_to_filestring() + ".png"); -} - - - - - -} -} -} +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/PrettyPrint.h" +#include "Pokemon/Pokemon_Strings.h" +#include "PokemonSwSh/Inference/ShinyDetection/PokemonSwSh_ShinyEncounterDetector.h" +#include "PokemonSwSh_ShinyEncounterTester.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +ShinyEncounterTester_Descriptor::ShinyEncounterTester_Descriptor() + : SingleSwitchProgramDescriptor( + "PokemonSwSh:ShinyEncounterTester", + STRING_POKEMON + " SwSh", "Shiny Encounter Tester", + "", + "Test the shiny encounter detector. Start this program just before an encounter.", + FeedbackType::REQUIRED, AllowCommandsWhenRunning::ENABLE_COMMANDS, + {}, + FasterIfTickPrecise::NOT_FASTER + ) +{} + + + +ShinyEncounterTester::ShinyEncounterTester() + : ENCOUNTER_TYPE( + "Encounter Type:", + { + {EncounterType::Wild, "wild", "Wild Encounter"}, + {EncounterType::Raid, "raid", "Raid Den"}, + }, + LockMode::LOCK_WHILE_RUNNING, + EncounterType::Wild + ) +{ + PA_ADD_OPTION(ENCOUNTER_TYPE); +} + + +void ShinyEncounterTester::program(SingleSwitchProgramEnvironment& env, ProControllerContext& context){ + ShinyDetectionResult result = detect_shiny_battle( + env.console, context, + ENCOUNTER_TYPE == EncounterType::Wild ? SHINY_BATTLE_REGULAR : SHINY_BATTLE_RAID, + std::chrono::seconds(30) + ); + result.get_best_screenshot().save(now_to_filestring() + ".png"); +} + + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h b/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h index ce97d9e1dc..b82448fa49 100644 --- a/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h +++ b/SerialPrograms/Source/PokemonSwSh/Programs/TestPrograms/PokemonSwSh_ShinyEncounterTester.h @@ -1,42 +1,42 @@ -/* Shiny Encounter Detector - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Options/EnumDropdownOption.h" -#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - -class ShinyEncounterTester_Descriptor : public SingleSwitchProgramDescriptor{ -public: - ShinyEncounterTester_Descriptor(); -}; - - - -class ShinyEncounterTester : public SingleSwitchProgramInstance{ -public: - ShinyEncounterTester(); - - virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; - -private: - enum class EncounterType{ - Wild, - Raid, - }; - EnumDropdownOption ENCOUNTER_TYPE; -}; - - - - -} -} -} +/* Shiny Encounter Detector + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Options/EnumDropdownOption.h" +#include "NintendoSwitch/NintendoSwitch_SingleSwitchProgram.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + +class ShinyEncounterTester_Descriptor : public SingleSwitchProgramDescriptor{ +public: + ShinyEncounterTester_Descriptor(); +}; + + + +class ShinyEncounterTester : public SingleSwitchProgramInstance{ +public: + ShinyEncounterTester(); + + virtual void program(SingleSwitchProgramEnvironment& env, ProControllerContext& context) override; + +private: + enum class EncounterType{ + Wild, + Raid, + }; + EnumDropdownOption ENCOUNTER_TYPE; +}; + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp index 77aa6cc8a9..bed61cca1b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.cpp @@ -1,53 +1,53 @@ -/* Daily Highlight Database - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/Logging/Logger.h" -#include "PokemonSwSh_DailyHighlightDatabase.h" - -namespace PokemonAutomation { -namespace NintendoSwitch { -namespace PokemonSwSh { - - - -DailyHighlightDatabase::DailyHighlightDatabase(const char* resource_path) { - std::string filepath = RESOURCE_PATH() + resource_path; - JsonValue json = load_json_file(filepath); - JsonObject& root = json.to_object_throw(filepath); - - for (auto& item : root) { - const std::string& slug = item.first; - JsonObject& obj = item.second.to_object_throw(filepath); - - uint16_t min = (uint16_t)obj.get_integer_throw("min", filepath); - uint16_t max = (uint16_t)obj.get_integer_throw("max", filepath); - m_slug_to_range[slug] = std::pair(min, max); - - std::string display_name = obj.get_string_throw("display_name", filepath); - StringSelectEntry string_select_entry(slug, display_name); - m_stringselect_database.add_entry(string_select_entry); - } -} - -std::pair DailyHighlightDatabase::get_range_for_slug(const std::string& slug) const { - auto iter = m_slug_to_range.find(slug); - if (iter == m_slug_to_range.end()) { - throw InternalProgramError( - nullptr, - PA_CURRENT_FUNCTION, - std::string("Invalid daily highlight slug: " + slug) - ); - } - return iter->second; -} - - - -} -} -} +/* Daily Highlight Database + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/Logging/Logger.h" +#include "PokemonSwSh_DailyHighlightDatabase.h" + +namespace PokemonAutomation { +namespace NintendoSwitch { +namespace PokemonSwSh { + + + +DailyHighlightDatabase::DailyHighlightDatabase(const char* resource_path) { + std::string filepath = RESOURCE_PATH() + resource_path; + JsonValue json = load_json_file(filepath); + JsonObject& root = json.to_object_throw(filepath); + + for (auto& item : root) { + const std::string& slug = item.first; + JsonObject& obj = item.second.to_object_throw(filepath); + + uint16_t min = (uint16_t)obj.get_integer_throw("min", filepath); + uint16_t max = (uint16_t)obj.get_integer_throw("max", filepath); + m_slug_to_range[slug] = std::pair(min, max); + + std::string display_name = obj.get_string_throw("display_name", filepath); + StringSelectEntry string_select_entry(slug, display_name); + m_stringselect_database.add_entry(string_select_entry); + } +} + +std::pair DailyHighlightDatabase::get_range_for_slug(const std::string& slug) const { + auto iter = m_slug_to_range.find(slug); + if (iter == m_slug_to_range.end()) { + throw InternalProgramError( + nullptr, + PA_CURRENT_FUNCTION, + std::string("Invalid daily highlight slug: " + slug) + ); + } + return iter->second; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h index e7219fce37..5c9052744b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_DailyHighlightDatabase.h @@ -1,38 +1,38 @@ -/* Daily Highlight Database - * - * From: https://github.com/PokemonAutomation/Arduino-Source - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H -#define PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H - -#include -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation { -namespace NintendoSwitch { -namespace PokemonSwSh { - - -class DailyHighlightDatabase { -public: - DailyHighlightDatabase(const char* resource_path); - - std::pair get_range_for_slug(const std::string& slug) const; - const StringSelectDatabase& database() const { - return m_stringselect_database; - } - -private: - std::map> m_slug_to_range; - StringSelectDatabase m_stringselect_database; -}; - - - - -} -} -} -#endif +/* Daily Highlight Database + * + * From: https://github.com/PokemonAutomation/Arduino-Source + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H +#define PokemonAutomation_PokemonSwSh_DailyHighlightDatabase_H + +#include +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation { +namespace NintendoSwitch { +namespace PokemonSwSh { + + +class DailyHighlightDatabase { +public: + DailyHighlightDatabase(const char* resource_path); + + std::pair get_range_for_slug(const std::string& slug) const; + const StringSelectDatabase& database() const { + return m_stringselect_database; + } + +private: + std::map> m_slug_to_range; + StringSelectDatabase m_stringselect_database; +}; + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.cpp index 95d04e52e0..1f7923fe03 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.cpp @@ -1,277 +1,277 @@ -/* Pokemon Sword/Shield Max Lair Rentals - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include -#include "Common/Cpp/Exceptions.h" -#include "Common/Cpp/Json/JsonValue.h" -#include "Common/Cpp/Json/JsonArray.h" -#include "Common/Cpp/Json/JsonObject.h" -#include "CommonFramework/Globals.h" -#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonSwSh_MaxLairDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - - - - -struct MaxLairSlugsDatabase{ - std::map m_slugs; - - static MaxLairSlugsDatabase& instance(){ - static MaxLairSlugsDatabase data; - return data; - } - - MaxLairSlugsDatabase(){ - std::string path = RESOURCE_PATH() + "PokemonSwSh/MaxLairSlugMap.json"; - JsonValue json = load_json_file(path); - JsonObject& root = json.to_object_throw(path); - - for (auto& item0 : root){ - const std::string& maxlair_slug = item0.first; - JsonObject& obj = item0.second.to_object_throw(path); - MaxLairSlugs slugs; - for (auto& item1 : obj.get_array_throw("OCR", path)){ - std::string& slug = item1.to_string_throw(path); - if (!slugs.name_slug.empty()){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Multiple names specified for MaxLair slug.", std::move(path)); - } - slugs.name_slug = std::move(slug); - } - for (auto& item1 : obj.get_array_throw("Sprite", path)){ - std::string& slug = item1.to_string_throw(path); - slugs.sprite_slugs.insert(std::move(slug)); - } - m_slugs[maxlair_slug] = std::move(slugs); - } - } -}; - - - -const std::map& maxlair_slugs(){ - return MaxLairSlugsDatabase::instance().m_slugs; -} -const MaxLairSlugs& get_maxlair_slugs(const std::string& slug){ - const MaxLairSlugsDatabase& database = MaxLairSlugsDatabase::instance(); - auto iter = database.m_slugs.find(slug); - if (iter == database.m_slugs.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Max Lair slug: " + slug); - } - return iter->second; -} - - - - - -MoveCategory parse_category_slug(const std::string& slug){ - static const std::map database{ - {"status", MoveCategory::STATUS}, - {"physical", MoveCategory::PHYSICAL}, - {"special", MoveCategory::SPECIAL}, - }; - auto iter = database.find(slug); - if (iter == database.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Move Category: " + slug); - } - return iter->second; -} - -PokemonType parse_type_slug(const std::string& slug){ - static const std::map database{ - {"normal", PokemonType::NORMAL}, - {"fire", PokemonType::FIRE}, - {"fighting", PokemonType::FIGHTING}, - {"water", PokemonType::WATER}, - {"flying", PokemonType::FLYING}, - {"grass", PokemonType::GRASS}, - {"poison", PokemonType::POISON}, - {"electric", PokemonType::ELECTRIC}, - {"ground", PokemonType::GROUND}, - {"psychic", PokemonType::PSYCHIC}, - {"rock", PokemonType::ROCK}, - {"ice", PokemonType::ICE}, - {"bug", PokemonType::BUG,}, - {"dragon", PokemonType::DRAGON}, - {"ghost", PokemonType::GHOST}, - {"dark", PokemonType::DARK}, - {"steel", PokemonType::STEEL}, - {"fairy", PokemonType::FAIRY}, - }; - auto iter = database.find(slug); - if (iter == database.end()){ - return PokemonType::NONE; - } - return iter->second; -} - -MaxLairMove parse_move(JsonObject&& obj, const std::string& path){ - MaxLairMove move; - move.slug = obj.get_string_throw("move", path); - move.category = parse_category_slug(obj.get_string_throw("category", path)); - move.type = parse_type_slug(obj.get_string_throw("type", path)); - move.base_power = (uint8_t)obj.get_integer_throw("base_power", path); - move.accuracy = obj.get_double_throw("accuracy", path); - move.PP = (uint8_t)obj.get_integer_throw("PP", path); - move.spread = obj.get_boolean_throw("spread", path); - move.correction_factor = obj.get_double_throw("correction_factor", path); - move.effective_power = obj.get_double_throw("effective_power", path); - return move; -} - - -std::map build_maxlair_mon_database(const std::string& path){ - std::string filepath = RESOURCE_PATH() + path; - JsonValue json = load_json_file(filepath); - JsonObject& root = json.to_object_throw(filepath); - - std::map database; - - for (auto& item : root){ - const std::string& slug = item.first; - JsonObject& obj = item.second.to_object_throw(filepath); - - MaxLairMon& mon = database[slug]; - mon.species = slug; - mon.type[0] = PokemonType::NONE; - mon.type[1] = PokemonType::NONE; - { - JsonArray& array = obj.get_array_throw("type", filepath); - if (array.size() >= 1){ - std::string& str = array[0].to_string_throw(filepath); - mon.type[0] = parse_type_slug(str); - } - if (array.size() >= 2){ - std::string& str = array[1].to_string_throw(filepath); - mon.type[1] = parse_type_slug(str); - } - } - { - std::string& str = obj.get_string_throw("ability", filepath); - mon.ability = std::move(str); - } - { - JsonArray& array = obj.get_array_throw("base_stats", filepath); - if (array.size() != 6){ - throw FileException(nullptr, PA_CURRENT_FUNCTION, "Base stats should contain 6 elements: " + slug, std::move(filepath)); - } - for (int c = 0; c < 6; c++){ - mon.base_stats[c] = (uint8_t)array[c].to_integer_throw(filepath); - } - } - { - JsonArray& array = obj.get_array_throw("moves", filepath); - size_t stop = std::min(5, array.size()); - for (size_t c = 0; c < stop; c++){ - JsonObject& move = array[c].to_object_throw(filepath); - mon.moves[c] = parse_move(std::move(move), filepath); - } - } - { - JsonArray& array = obj.get_array_throw("max_moves", filepath); - size_t stop = std::min(5, array.size()); - for (size_t c = 0; c < stop; c++){ - JsonObject& move = array[c].to_object_throw(filepath); - mon.max_moves[c] = parse_move(std::move(move), filepath); - } - } - } - - return database; -} - - - - -struct MaxLairDatabase{ - std::map m_rentals; - std::map m_bosses; - - std::map m_bosses_by_dex; - - static MaxLairDatabase& instance(){ - static MaxLairDatabase data; - return data; - } - - MaxLairDatabase() - : m_rentals(build_maxlair_mon_database("PokemonSwSh/MaxLairRentals.json")) - , m_bosses(build_maxlair_mon_database("PokemonSwSh/MaxLairBosses.json")) - { - const std::map& national_dex = SLUGS_TO_NATIONAL_DEX(); - - for (const auto& item : m_bosses){ - const MaxLairSlugs& slugs = get_maxlair_slugs(item.first); - auto iter = national_dex.find(slugs.name_slug); - if (iter == national_dex.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found in national dex: " + slugs.name_slug); - } - m_bosses_by_dex[iter->second] = item.first; - } - -#if 0 - for (const auto& item : m_bosses_by_dex){ - const MaxLairSlugs& slugs = get_maxlair_slugs(item.second); - cout << item.first << " : " - << item.second << " : " - << get_pokemon_name(slugs.name_slug).display_name().toStdString() << endl; - } -#endif - } -}; - - - - -const std::map& all_bosses_by_dex(){ - const MaxLairDatabase& database = MaxLairDatabase::instance(); - return database.m_bosses_by_dex; -} -bool is_boss(const std::string& slug){ - const MaxLairDatabase& database = MaxLairDatabase::instance(); - auto iter = database.m_bosses.find(slug); - return iter != database.m_bosses.end(); -} -const MaxLairMon& get_maxlair_mon(const std::string& slug){ - const MaxLairDatabase& database = MaxLairDatabase::instance(); - auto iter0 = database.m_rentals.find(slug); - if (iter0 != database.m_rentals.end()){ - return iter0->second; - } - auto iter1 = database.m_bosses.find(slug); - if (iter1 != database.m_bosses.end()){ - return iter1->second; - } - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Species Slug: " + slug); -} -const MaxLairMon* get_maxlair_mon_nothrow(const std::string& slug){ - const MaxLairDatabase& database = MaxLairDatabase::instance(); - auto iter0 = database.m_rentals.find(slug); - if (iter0 != database.m_rentals.end()){ - return &iter0->second; - } - auto iter1 = database.m_bosses.find(slug); - if (iter1 != database.m_bosses.end()){ - return &iter1->second; - } - return nullptr; -} - - - - - -} -} -} -} +/* Pokemon Sword/Shield Max Lair Rentals + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include +#include "Common/Cpp/Exceptions.h" +#include "Common/Cpp/Json/JsonValue.h" +#include "Common/Cpp/Json/JsonArray.h" +#include "Common/Cpp/Json/JsonObject.h" +#include "CommonFramework/Globals.h" +#include "Pokemon/Resources/Pokemon_PokemonSlugs.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonSwSh_MaxLairDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + + + + +struct MaxLairSlugsDatabase{ + std::map m_slugs; + + static MaxLairSlugsDatabase& instance(){ + static MaxLairSlugsDatabase data; + return data; + } + + MaxLairSlugsDatabase(){ + std::string path = RESOURCE_PATH() + "PokemonSwSh/MaxLairSlugMap.json"; + JsonValue json = load_json_file(path); + JsonObject& root = json.to_object_throw(path); + + for (auto& item0 : root){ + const std::string& maxlair_slug = item0.first; + JsonObject& obj = item0.second.to_object_throw(path); + MaxLairSlugs slugs; + for (auto& item1 : obj.get_array_throw("OCR", path)){ + std::string& slug = item1.to_string_throw(path); + if (!slugs.name_slug.empty()){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Multiple names specified for MaxLair slug.", std::move(path)); + } + slugs.name_slug = std::move(slug); + } + for (auto& item1 : obj.get_array_throw("Sprite", path)){ + std::string& slug = item1.to_string_throw(path); + slugs.sprite_slugs.insert(std::move(slug)); + } + m_slugs[maxlair_slug] = std::move(slugs); + } + } +}; + + + +const std::map& maxlair_slugs(){ + return MaxLairSlugsDatabase::instance().m_slugs; +} +const MaxLairSlugs& get_maxlair_slugs(const std::string& slug){ + const MaxLairSlugsDatabase& database = MaxLairSlugsDatabase::instance(); + auto iter = database.m_slugs.find(slug); + if (iter == database.m_slugs.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Max Lair slug: " + slug); + } + return iter->second; +} + + + + + +MoveCategory parse_category_slug(const std::string& slug){ + static const std::map database{ + {"status", MoveCategory::STATUS}, + {"physical", MoveCategory::PHYSICAL}, + {"special", MoveCategory::SPECIAL}, + }; + auto iter = database.find(slug); + if (iter == database.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Move Category: " + slug); + } + return iter->second; +} + +PokemonType parse_type_slug(const std::string& slug){ + static const std::map database{ + {"normal", PokemonType::NORMAL}, + {"fire", PokemonType::FIRE}, + {"fighting", PokemonType::FIGHTING}, + {"water", PokemonType::WATER}, + {"flying", PokemonType::FLYING}, + {"grass", PokemonType::GRASS}, + {"poison", PokemonType::POISON}, + {"electric", PokemonType::ELECTRIC}, + {"ground", PokemonType::GROUND}, + {"psychic", PokemonType::PSYCHIC}, + {"rock", PokemonType::ROCK}, + {"ice", PokemonType::ICE}, + {"bug", PokemonType::BUG,}, + {"dragon", PokemonType::DRAGON}, + {"ghost", PokemonType::GHOST}, + {"dark", PokemonType::DARK}, + {"steel", PokemonType::STEEL}, + {"fairy", PokemonType::FAIRY}, + }; + auto iter = database.find(slug); + if (iter == database.end()){ + return PokemonType::NONE; + } + return iter->second; +} + +MaxLairMove parse_move(JsonObject&& obj, const std::string& path){ + MaxLairMove move; + move.slug = obj.get_string_throw("move", path); + move.category = parse_category_slug(obj.get_string_throw("category", path)); + move.type = parse_type_slug(obj.get_string_throw("type", path)); + move.base_power = (uint8_t)obj.get_integer_throw("base_power", path); + move.accuracy = obj.get_double_throw("accuracy", path); + move.PP = (uint8_t)obj.get_integer_throw("PP", path); + move.spread = obj.get_boolean_throw("spread", path); + move.correction_factor = obj.get_double_throw("correction_factor", path); + move.effective_power = obj.get_double_throw("effective_power", path); + return move; +} + + +std::map build_maxlair_mon_database(const std::string& path){ + std::string filepath = RESOURCE_PATH() + path; + JsonValue json = load_json_file(filepath); + JsonObject& root = json.to_object_throw(filepath); + + std::map database; + + for (auto& item : root){ + const std::string& slug = item.first; + JsonObject& obj = item.second.to_object_throw(filepath); + + MaxLairMon& mon = database[slug]; + mon.species = slug; + mon.type[0] = PokemonType::NONE; + mon.type[1] = PokemonType::NONE; + { + JsonArray& array = obj.get_array_throw("type", filepath); + if (array.size() >= 1){ + std::string& str = array[0].to_string_throw(filepath); + mon.type[0] = parse_type_slug(str); + } + if (array.size() >= 2){ + std::string& str = array[1].to_string_throw(filepath); + mon.type[1] = parse_type_slug(str); + } + } + { + std::string& str = obj.get_string_throw("ability", filepath); + mon.ability = std::move(str); + } + { + JsonArray& array = obj.get_array_throw("base_stats", filepath); + if (array.size() != 6){ + throw FileException(nullptr, PA_CURRENT_FUNCTION, "Base stats should contain 6 elements: " + slug, std::move(filepath)); + } + for (int c = 0; c < 6; c++){ + mon.base_stats[c] = (uint8_t)array[c].to_integer_throw(filepath); + } + } + { + JsonArray& array = obj.get_array_throw("moves", filepath); + size_t stop = std::min(5, array.size()); + for (size_t c = 0; c < stop; c++){ + JsonObject& move = array[c].to_object_throw(filepath); + mon.moves[c] = parse_move(std::move(move), filepath); + } + } + { + JsonArray& array = obj.get_array_throw("max_moves", filepath); + size_t stop = std::min(5, array.size()); + for (size_t c = 0; c < stop; c++){ + JsonObject& move = array[c].to_object_throw(filepath); + mon.max_moves[c] = parse_move(std::move(move), filepath); + } + } + } + + return database; +} + + + + +struct MaxLairDatabase{ + std::map m_rentals; + std::map m_bosses; + + std::map m_bosses_by_dex; + + static MaxLairDatabase& instance(){ + static MaxLairDatabase data; + return data; + } + + MaxLairDatabase() + : m_rentals(build_maxlair_mon_database("PokemonSwSh/MaxLairRentals.json")) + , m_bosses(build_maxlair_mon_database("PokemonSwSh/MaxLairBosses.json")) + { + const std::map& national_dex = SLUGS_TO_NATIONAL_DEX(); + + for (const auto& item : m_bosses){ + const MaxLairSlugs& slugs = get_maxlair_slugs(item.first); + auto iter = national_dex.find(slugs.name_slug); + if (iter == national_dex.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Slug not found in national dex: " + slugs.name_slug); + } + m_bosses_by_dex[iter->second] = item.first; + } + +#if 0 + for (const auto& item : m_bosses_by_dex){ + const MaxLairSlugs& slugs = get_maxlair_slugs(item.second); + cout << item.first << " : " + << item.second << " : " + << get_pokemon_name(slugs.name_slug).display_name().toStdString() << endl; + } +#endif + } +}; + + + + +const std::map& all_bosses_by_dex(){ + const MaxLairDatabase& database = MaxLairDatabase::instance(); + return database.m_bosses_by_dex; +} +bool is_boss(const std::string& slug){ + const MaxLairDatabase& database = MaxLairDatabase::instance(); + auto iter = database.m_bosses.find(slug); + return iter != database.m_bosses.end(); +} +const MaxLairMon& get_maxlair_mon(const std::string& slug){ + const MaxLairDatabase& database = MaxLairDatabase::instance(); + auto iter0 = database.m_rentals.find(slug); + if (iter0 != database.m_rentals.end()){ + return iter0->second; + } + auto iter1 = database.m_bosses.find(slug); + if (iter1 != database.m_bosses.end()){ + return iter1->second; + } + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Species Slug: " + slug); +} +const MaxLairMon* get_maxlair_mon_nothrow(const std::string& slug){ + const MaxLairDatabase& database = MaxLairDatabase::instance(); + auto iter0 = database.m_rentals.find(slug); + if (iter0 != database.m_rentals.end()){ + return &iter0->second; + } + auto iter1 = database.m_bosses.find(slug); + if (iter1 != database.m_bosses.end()){ + return &iter1->second; + } + return nullptr; +} + + + + + +} +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h index 1f6fbe76ff..d764ba0164 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_MaxLairDatabase.h @@ -1,70 +1,70 @@ -/* Pokemon Sword/Shield Max Lair Rentals - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_MaxLairRentals_H -#define PokemonAutomation_PokemonSwSh_MaxLairRentals_H - -#include -#include -#include -#include "Pokemon/Pokemon_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ -namespace MaxLairInternal{ - -using namespace Pokemon; - - - -// Max Lair slug mappings with respect to name and sprite slugs. -struct MaxLairSlugs{ - std::string name_slug; - std::set sprite_slugs; -}; -const std::map& maxlair_slugs(); -const MaxLairSlugs& get_maxlair_slugs(const std::string& slug); - - - -struct MaxLairMove{ - std::string slug; - MoveCategory category; - PokemonType type; - uint8_t base_power; - double accuracy; - uint8_t PP; - bool spread; - - double correction_factor; - double effective_power; -}; - -struct MaxLairMon{ - std::string species; - PokemonType type[2]; - std::string ability; - uint8_t base_stats[6]; - - MaxLairMove moves[5]; - MaxLairMove max_moves[5]; -}; - -const std::map& all_bosses_by_dex(); -bool is_boss(const std::string& slug); - -const MaxLairMon& get_maxlair_mon(const std::string& slug); -const MaxLairMon* get_maxlair_mon_nothrow(const std::string& slug); - - - - -} -} -} -} -#endif +/* Pokemon Sword/Shield Max Lair Rentals + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_MaxLairRentals_H +#define PokemonAutomation_PokemonSwSh_MaxLairRentals_H + +#include +#include +#include +#include "Pokemon/Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ +namespace MaxLairInternal{ + +using namespace Pokemon; + + + +// Max Lair slug mappings with respect to name and sprite slugs. +struct MaxLairSlugs{ + std::string name_slug; + std::set sprite_slugs; +}; +const std::map& maxlair_slugs(); +const MaxLairSlugs& get_maxlair_slugs(const std::string& slug); + + + +struct MaxLairMove{ + std::string slug; + MoveCategory category; + PokemonType type; + uint8_t base_power; + double accuracy; + uint8_t PP; + bool spread; + + double correction_factor; + double effective_power; +}; + +struct MaxLairMon{ + std::string species; + PokemonType type[2]; + std::string ability; + uint8_t base_stats[6]; + + MaxLairMove moves[5]; + MaxLairMove max_moves[5]; +}; + +const std::map& all_bosses_by_dex(); +bool is_boss(const std::string& slug); + +const MaxLairMon& get_maxlair_mon(const std::string& slug); +const MaxLairMon* get_maxlair_mon_nothrow(const std::string& slug); + + + + +} +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.cpp index 2534e9a6f8..f16806f8c1 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.cpp @@ -1,68 +1,68 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "CommonFramework/Logging/Logger.h" -#include "Pokemon/Resources/Pokemon_PokemonNames.h" -#include "PokemonSwSh_PokemonSprites.h" -#include "PokemonSwSh_NameDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -std::set make_ALL_POKEMON_SLUGS(){ - std::vector list = load_pokemon_slug_json_list("PokemonSwSh/Pokedex-Combined.json"); - return std::set(list.begin(), list.end()); -} - -const std::set& ALL_POKEMON_SLUGS(){ - static std::set database = make_ALL_POKEMON_SLUGS(); - return database; -} - - -StringSelectDatabase make_name_database(const std::vector& slugs){ - const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); - - StringSelectDatabase database; - for (const std::string& slug : slugs){ - const PokemonNames& name = get_pokemon_name(slug); - const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); - if (sprite){ - database.add_entry(StringSelectEntry( - slug, - name.display_name(), - sprite->icon - )); - }else{ - global_logger_tagged().log("No sprite for: " + slug); - database.add_entry(StringSelectEntry( - slug, - name.display_name() - )); - } - } - return database; -} -StringSelectDatabase make_name_database(const char* json_file_slugs){ - return make_name_database(load_pokemon_slug_json_list(json_file_slugs)); -} - - -const StringSelectDatabase& COMBINED_DEX_NAMES(){ - static const StringSelectDatabase database = make_name_database("PokemonSwSh/Pokedex-Combined.json"); - return database; -} - - - - -} -} -} +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "CommonFramework/Logging/Logger.h" +#include "Pokemon/Resources/Pokemon_PokemonNames.h" +#include "PokemonSwSh_PokemonSprites.h" +#include "PokemonSwSh_NameDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +std::set make_ALL_POKEMON_SLUGS(){ + std::vector list = load_pokemon_slug_json_list("PokemonSwSh/Pokedex-Combined.json"); + return std::set(list.begin(), list.end()); +} + +const std::set& ALL_POKEMON_SLUGS(){ + static std::set database = make_ALL_POKEMON_SLUGS(); + return database; +} + + +StringSelectDatabase make_name_database(const std::vector& slugs){ + const SpriteDatabase& sprites = ALL_POKEMON_SPRITES(); + + StringSelectDatabase database; + for (const std::string& slug : slugs){ + const PokemonNames& name = get_pokemon_name(slug); + const SpriteDatabase::Sprite* sprite = sprites.get_nothrow(slug); + if (sprite){ + database.add_entry(StringSelectEntry( + slug, + name.display_name(), + sprite->icon + )); + }else{ + global_logger_tagged().log("No sprite for: " + slug); + database.add_entry(StringSelectEntry( + slug, + name.display_name() + )); + } + } + return database; +} +StringSelectDatabase make_name_database(const char* json_file_slugs){ + return make_name_database(load_pokemon_slug_json_list(json_file_slugs)); +} + + +const StringSelectDatabase& COMBINED_DEX_NAMES(){ + static const StringSelectDatabase database = make_name_database("PokemonSwSh/Pokedex-Combined.json"); + return database; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h index 56636948af..f3fd81c29e 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_NameDatabase.h @@ -1,30 +1,30 @@ -/* Name Database - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_NameDatabase_H -#define PokemonAutomation_PokemonSwSh_NameDatabase_H - -#include -#include "CommonTools/Options/StringSelectOption.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -const std::set& ALL_POKEMON_SLUGS(); - -StringSelectDatabase make_name_database(const std::vector& slugs); -StringSelectDatabase make_name_database(const char* json_file_slugs); - -const StringSelectDatabase& COMBINED_DEX_NAMES(); - - - - -} -} -} -#endif +/* Name Database + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_NameDatabase_H +#define PokemonAutomation_PokemonSwSh_NameDatabase_H + +#include +#include "CommonTools/Options/StringSelectOption.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +const std::set& ALL_POKEMON_SLUGS(); + +StringSelectDatabase make_name_database(const std::vector& slugs); +StringSelectDatabase make_name_database(const char* json_file_slugs); + +const StringSelectDatabase& COMBINED_DEX_NAMES(); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.cpp index cd2d684588..4302f3247b 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.cpp @@ -1,23 +1,23 @@ -/* Pokemon Sword/Shield Pokeball Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_PokeballSprites.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const SpriteDatabase& ALL_POKEBALL_SPRITES(){ - static const SpriteDatabase database("PokemonSwSh/PokeballSprites.png", "PokemonSwSh/PokeballSprites.json"); - return database; -} - - - -} -} -} +/* Pokemon Sword/Shield Pokeball Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_PokeballSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const SpriteDatabase& ALL_POKEBALL_SPRITES(){ + static const SpriteDatabase database("PokemonSwSh/PokeballSprites.png", "PokemonSwSh/PokeballSprites.json"); + return database; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h index 745576b63a..541c933c53 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokeballSprites.h @@ -1,24 +1,24 @@ -/* Pokemon Sword/Shield Pokeball Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_PokeballSprites_H -#define PokemonAutomation_PokemonSwSh_PokeballSprites_H - -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const SpriteDatabase& ALL_POKEBALL_SPRITES(); - - - -} -} -} -#endif +/* Pokemon Sword/Shield Pokeball Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_PokeballSprites_H +#define PokemonAutomation_PokemonSwSh_PokeballSprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const SpriteDatabase& ALL_POKEBALL_SPRITES(); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.cpp index 0fe7cc5cfd..67af286600 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.cpp @@ -1,27 +1,27 @@ -/* Pokemon Sword/Shield Pokemon Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "PokemonSwSh_PokemonSprites.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const SpriteDatabase& ALL_POKEMON_SPRITES(){ - static const SpriteDatabase database("PokemonSwSh/PokemonSprites.png", "PokemonSwSh/PokemonSprites.json"); - return database; -} -const SpriteDatabase& ALL_POKEMON_SILHOUETTES(){ - static const SpriteDatabase database("PokemonSwSh/PokemonSilhouettes.png", "PokemonSwSh/PokemonSprites.json"); - return database; -} - - - -} -} -} +/* Pokemon Sword/Shield Pokemon Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "PokemonSwSh_PokemonSprites.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const SpriteDatabase& ALL_POKEMON_SPRITES(){ + static const SpriteDatabase database("PokemonSwSh/PokemonSprites.png", "PokemonSwSh/PokemonSprites.json"); + return database; +} +const SpriteDatabase& ALL_POKEMON_SILHOUETTES(){ + static const SpriteDatabase database("PokemonSwSh/PokemonSilhouettes.png", "PokemonSwSh/PokemonSprites.json"); + return database; +} + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h index ddc4a2cda0..0316fac4bb 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_PokemonSprites.h @@ -1,25 +1,25 @@ -/* Pokemon Sword/Shield Pokemon Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_PokemonSprites_H -#define PokemonAutomation_PokemonSwSh_PokemonSprites_H - -#include "CommonTools/Resources/SpriteDatabase.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const SpriteDatabase& ALL_POKEMON_SPRITES(); -const SpriteDatabase& ALL_POKEMON_SILHOUETTES(); - - - -} -} -} -#endif +/* Pokemon Sword/Shield Pokemon Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_PokemonSprites_H +#define PokemonAutomation_PokemonSwSh_PokemonSprites_H + +#include "CommonTools/Resources/SpriteDatabase.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const SpriteDatabase& ALL_POKEMON_SPRITES(); +const SpriteDatabase& ALL_POKEMON_SILHOUETTES(); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.cpp index de5b3514ad..d6e70c5600 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.cpp @@ -1,117 +1,117 @@ -/* Pokemon Sword/Shield Type Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include -#include "Common/Cpp/Exceptions.h" -#include "PokemonSwSh_TypeMatchup.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - -const std::map> TYPE_EFFECTIVENESS{ - {PokemonType::NORMAL, { - {PokemonType::ROCK, 0.5}, {PokemonType::STEEL, 0.5}, - {PokemonType::GHOST, 0.0}, - }}, - {PokemonType::FIRE, { - {PokemonType::BUG, 2.0}, {PokemonType::STEEL, 2.0}, {PokemonType::GRASS, 2.0}, {PokemonType::ICE, 2.0}, - {PokemonType::ROCK, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::WATER, 0.5}, {PokemonType::DRAGON, 0.5}, - }}, - {PokemonType::FIGHTING, { - {PokemonType::NORMAL, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::STEEL, 2.0}, {PokemonType::ICE, 2.0}, {PokemonType::DARK, 2.0}, - {PokemonType::FLYING, 0.5}, {PokemonType::POISON, 0.5}, {PokemonType::BUG, 0.5}, {PokemonType::PSYCHIC, 0.5}, {PokemonType::FAIRY, 0.5}, - {PokemonType::GHOST, 0.0}, - }}, - {PokemonType::WATER, { - {PokemonType::GROUND, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::FIRE, 2.0}, - {PokemonType::WATER, 0.5}, {PokemonType::GRASS, 0.5}, {PokemonType::DRAGON, 0.5}, - }}, - {PokemonType::FLYING, { - {PokemonType::FIGHTING, 2.0}, {PokemonType::BUG, 2.0}, {PokemonType::GRASS, 2.0}, - {PokemonType::ROCK, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::ELECTRIC, 0.5}, - }}, - {PokemonType::GRASS, { - {PokemonType::GROUND, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::WATER, 2.0}, - {PokemonType::FLYING, 0.5}, {PokemonType::POISON, 0.5}, {PokemonType::BUG, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::GRASS, 0.5}, {PokemonType::DRAGON, 0.5}, - }}, - {PokemonType::POISON, { - {PokemonType::GRASS, 2.0}, {PokemonType::FAIRY, 2.0}, - {PokemonType::POISON, 0.5}, {PokemonType::GROUND, 0.5}, {PokemonType::ROCK, 0.5}, {PokemonType::GHOST, 0.5}, - {PokemonType::STEEL, 0.0}, - }}, - {PokemonType::ELECTRIC, { - {PokemonType::FLYING, 2.0}, {PokemonType::WATER, 2.0}, - {PokemonType::GRASS, 0.5}, {PokemonType::ELECTRIC, 0.5}, {PokemonType::DRAGON, 0.5}, - {PokemonType::GROUND, 0.0}, - }}, - {PokemonType::GROUND, { - {PokemonType::POISON, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::STEEL, 2.0}, {PokemonType::FIRE, 2.0}, {PokemonType::ELECTRIC, 2.0}, - {PokemonType::BUG, 0.5}, {PokemonType::GRASS, 0.5}, - {PokemonType::FLYING, 0.0}, - }}, - {PokemonType::PSYCHIC, { - {PokemonType::FIGHTING, 2.0}, {PokemonType::POISON, 2.0}, - {PokemonType::STEEL, 0.5}, {PokemonType::PSYCHIC, 0.5}, - {PokemonType::DARK, 0.0}, - }}, - {PokemonType::ROCK, { - {PokemonType::FLYING, 2.0}, {PokemonType::BUG, 2.0}, {PokemonType::FIRE, 2.0}, {PokemonType::ICE, 2.0}, - {PokemonType::FIGHTING, 0.5}, {PokemonType::GROUND, 0.5}, {PokemonType::STEEL, 0.5}, - }}, - {PokemonType::ICE, { - {PokemonType::FLYING, 2.0}, {PokemonType::GROUND, 2.0}, {PokemonType::GRASS, 2.0}, {PokemonType::DRAGON, 2.0}, - {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::WATER, 0.5}, {PokemonType::ICE, 0.5}, - }}, - {PokemonType::BUG, { - {PokemonType::GRASS, 2.0}, {PokemonType::PSYCHIC, 2.0}, {PokemonType::DARK, 2.0}, - {PokemonType::FIGHTING, 0.5}, {PokemonType::FLYING, 0.5}, {PokemonType::POISON, 0.5}, {PokemonType::GHOST, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::FAIRY, 0.5}, - }}, - {PokemonType::DRAGON, { - {PokemonType::DRAGON, 2.0}, - {PokemonType::STEEL, 0.5}, - {PokemonType::FAIRY, 0.0}, - }}, - {PokemonType::GHOST, { - {PokemonType::GHOST, 2.0}, {PokemonType::PSYCHIC, 2.0}, - {PokemonType::DARK, 0.5}, - {PokemonType::NORMAL, 0.0}, - }}, - {PokemonType::DARK, { - {PokemonType::GHOST, 2.0}, {PokemonType::PSYCHIC, 2.0}, - {PokemonType::FIGHTING, 0.5}, {PokemonType::DARK, 0.5}, {PokemonType::FAIRY, 0.5}, - }}, - {PokemonType::STEEL, { - {PokemonType::ICE, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::FAIRY, 2.0}, - {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::WATER, 0.5}, {PokemonType::ELECTRIC, 0.5}, - }}, - {PokemonType::FAIRY, { - {PokemonType::FIGHTING, 2.0}, {PokemonType::DRAGON, 2.0}, {PokemonType::DARK, 2.0}, - {PokemonType::POISON, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, - }}, -}; - -double type_multiplier(PokemonType attack_type, PokemonType defend_type0, PokemonType defend_type1){ - auto iter = TYPE_EFFECTIVENESS.find(attack_type); - if (iter == TYPE_EFFECTIVENESS.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Type Enum: " + std::to_string((int)attack_type)); - } - double multiplier = 1.0; - const std::map& overrides = iter->second; - auto iter0 = overrides.find(defend_type0); - if (iter0 != overrides.end()) multiplier *= iter0->second; - auto iter1 = overrides.find(defend_type1); - if (iter1 != overrides.end()) multiplier *= iter1->second; - return multiplier; -} - - - - -} -} -} +/* Pokemon Sword/Shield Type Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include +#include "Common/Cpp/Exceptions.h" +#include "PokemonSwSh_TypeMatchup.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + +const std::map> TYPE_EFFECTIVENESS{ + {PokemonType::NORMAL, { + {PokemonType::ROCK, 0.5}, {PokemonType::STEEL, 0.5}, + {PokemonType::GHOST, 0.0}, + }}, + {PokemonType::FIRE, { + {PokemonType::BUG, 2.0}, {PokemonType::STEEL, 2.0}, {PokemonType::GRASS, 2.0}, {PokemonType::ICE, 2.0}, + {PokemonType::ROCK, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::WATER, 0.5}, {PokemonType::DRAGON, 0.5}, + }}, + {PokemonType::FIGHTING, { + {PokemonType::NORMAL, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::STEEL, 2.0}, {PokemonType::ICE, 2.0}, {PokemonType::DARK, 2.0}, + {PokemonType::FLYING, 0.5}, {PokemonType::POISON, 0.5}, {PokemonType::BUG, 0.5}, {PokemonType::PSYCHIC, 0.5}, {PokemonType::FAIRY, 0.5}, + {PokemonType::GHOST, 0.0}, + }}, + {PokemonType::WATER, { + {PokemonType::GROUND, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::FIRE, 2.0}, + {PokemonType::WATER, 0.5}, {PokemonType::GRASS, 0.5}, {PokemonType::DRAGON, 0.5}, + }}, + {PokemonType::FLYING, { + {PokemonType::FIGHTING, 2.0}, {PokemonType::BUG, 2.0}, {PokemonType::GRASS, 2.0}, + {PokemonType::ROCK, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::ELECTRIC, 0.5}, + }}, + {PokemonType::GRASS, { + {PokemonType::GROUND, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::WATER, 2.0}, + {PokemonType::FLYING, 0.5}, {PokemonType::POISON, 0.5}, {PokemonType::BUG, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::GRASS, 0.5}, {PokemonType::DRAGON, 0.5}, + }}, + {PokemonType::POISON, { + {PokemonType::GRASS, 2.0}, {PokemonType::FAIRY, 2.0}, + {PokemonType::POISON, 0.5}, {PokemonType::GROUND, 0.5}, {PokemonType::ROCK, 0.5}, {PokemonType::GHOST, 0.5}, + {PokemonType::STEEL, 0.0}, + }}, + {PokemonType::ELECTRIC, { + {PokemonType::FLYING, 2.0}, {PokemonType::WATER, 2.0}, + {PokemonType::GRASS, 0.5}, {PokemonType::ELECTRIC, 0.5}, {PokemonType::DRAGON, 0.5}, + {PokemonType::GROUND, 0.0}, + }}, + {PokemonType::GROUND, { + {PokemonType::POISON, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::STEEL, 2.0}, {PokemonType::FIRE, 2.0}, {PokemonType::ELECTRIC, 2.0}, + {PokemonType::BUG, 0.5}, {PokemonType::GRASS, 0.5}, + {PokemonType::FLYING, 0.0}, + }}, + {PokemonType::PSYCHIC, { + {PokemonType::FIGHTING, 2.0}, {PokemonType::POISON, 2.0}, + {PokemonType::STEEL, 0.5}, {PokemonType::PSYCHIC, 0.5}, + {PokemonType::DARK, 0.0}, + }}, + {PokemonType::ROCK, { + {PokemonType::FLYING, 2.0}, {PokemonType::BUG, 2.0}, {PokemonType::FIRE, 2.0}, {PokemonType::ICE, 2.0}, + {PokemonType::FIGHTING, 0.5}, {PokemonType::GROUND, 0.5}, {PokemonType::STEEL, 0.5}, + }}, + {PokemonType::ICE, { + {PokemonType::FLYING, 2.0}, {PokemonType::GROUND, 2.0}, {PokemonType::GRASS, 2.0}, {PokemonType::DRAGON, 2.0}, + {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::WATER, 0.5}, {PokemonType::ICE, 0.5}, + }}, + {PokemonType::BUG, { + {PokemonType::GRASS, 2.0}, {PokemonType::PSYCHIC, 2.0}, {PokemonType::DARK, 2.0}, + {PokemonType::FIGHTING, 0.5}, {PokemonType::FLYING, 0.5}, {PokemonType::POISON, 0.5}, {PokemonType::GHOST, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::FAIRY, 0.5}, + }}, + {PokemonType::DRAGON, { + {PokemonType::DRAGON, 2.0}, + {PokemonType::STEEL, 0.5}, + {PokemonType::FAIRY, 0.0}, + }}, + {PokemonType::GHOST, { + {PokemonType::GHOST, 2.0}, {PokemonType::PSYCHIC, 2.0}, + {PokemonType::DARK, 0.5}, + {PokemonType::NORMAL, 0.0}, + }}, + {PokemonType::DARK, { + {PokemonType::GHOST, 2.0}, {PokemonType::PSYCHIC, 2.0}, + {PokemonType::FIGHTING, 0.5}, {PokemonType::DARK, 0.5}, {PokemonType::FAIRY, 0.5}, + }}, + {PokemonType::STEEL, { + {PokemonType::ICE, 2.0}, {PokemonType::ROCK, 2.0}, {PokemonType::FAIRY, 2.0}, + {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, {PokemonType::WATER, 0.5}, {PokemonType::ELECTRIC, 0.5}, + }}, + {PokemonType::FAIRY, { + {PokemonType::FIGHTING, 2.0}, {PokemonType::DRAGON, 2.0}, {PokemonType::DARK, 2.0}, + {PokemonType::POISON, 0.5}, {PokemonType::STEEL, 0.5}, {PokemonType::FIRE, 0.5}, + }}, +}; + +double type_multiplier(PokemonType attack_type, PokemonType defend_type0, PokemonType defend_type1){ + auto iter = TYPE_EFFECTIVENESS.find(attack_type); + if (iter == TYPE_EFFECTIVENESS.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid Type Enum: " + std::to_string((int)attack_type)); + } + double multiplier = 1.0; + const std::map& overrides = iter->second; + auto iter0 = overrides.find(defend_type0); + if (iter0 != overrides.end()) multiplier *= iter0->second; + auto iter1 = overrides.find(defend_type1); + if (iter1 != overrides.end()) multiplier *= iter1->second; + return multiplier; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h index 778c7a267d..11b7cbb859 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeMatchup.h @@ -1,26 +1,26 @@ -/* Pokemon Sword/Shield Type Matchup - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TypeMatchup_H -#define PokemonAutomation_PokemonSwSh_TypeMatchup_H - -#include "Pokemon/Pokemon_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -double type_multiplier(PokemonType attack_type, PokemonType defend_type0, PokemonType defend_type1); - - - -} -} -} -#endif +/* Pokemon Sword/Shield Type Matchup + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TypeMatchup_H +#define PokemonAutomation_PokemonSwSh_TypeMatchup_H + +#include "Pokemon/Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +double type_multiplier(PokemonType attack_type, PokemonType defend_type0, PokemonType defend_type1); + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.cpp b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.cpp index 2b97f6066a..f0812ca856 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.cpp +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.cpp @@ -1,111 +1,111 @@ -/* Pokemon Sword/Shield Type Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "CommonFramework/Globals.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTools/ImageStats.h" -#include "CommonTools/Images/BinaryImage_FilterRgb32.h" -#include "PokemonSwSh_TypeSprites.h" - -//#include -//using std::cout; -//using std::endl; - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Kernels; -using namespace Kernels::Waterfill; - - - - -struct TypeSpriteDatabase{ - std::map m_type_map; - - static TypeSpriteDatabase& instance(){ - static TypeSpriteDatabase data; - return data; - } - - TypeSpriteDatabase(){ - for (const auto& item : POKEMON_TYPE_SLUGS()){ - if (item.first == PokemonType::NONE){ - continue; - } - m_type_map.emplace(item.first, item.second); - } - } - -}; - - - - - - -TypeSprite::TypeSprite(const std::string& slug) - : m_slug(slug) -{ - ImageRGB32 sprite(RESOURCE_PATH() + "PokemonSwSh/Types/" + slug + ".png"); - - // Set all non-255 alphas to zero. - size_t words = sprite.bytes_per_row() / sizeof(uint32_t); - uint32_t* ptr = sprite.data(); - for (size_t r = 0; r < sprite.height(); r++){ - for (size_t c = 0; c < sprite.width(); c++){ -// cout << qAlpha(sprite.pixel(c, r)) << " "; - uint32_t pixel = ptr[c]; - if ((pixel >> 24) != 0xff){ - ptr[c] = 0; - } - } -// cout << endl; - ptr += words; - } - - // Compute white objects. - PackedBinaryMatrix matrix = compress_rgb32_to_binary_min(sprite, 224, 224, 224); - - std::vector objects = find_objects_inplace(matrix, 10); - - WaterfillObject object; - for (const WaterfillObject& item : objects){ -// cout << item.center_x() << "," << item.center_y() << endl; - object.merge_assume_no_overlap(item); - } - -// sprite.save("symbol-" + std::to_string(slug) + ".png"); - m_matcher.reset( - new ImageMatch::WeightedExactImageMatcher( - sprite.sub_image(object.min_x, object.min_y, object.width(), object.height()).copy(), - ImageMatch::WeightedExactImageMatcher::InverseStddevWeight{1, 64} - ) - ); -} - - -const TypeSprite& get_type_sprite(PokemonType type){ - const TypeSpriteDatabase& database = TypeSpriteDatabase::instance(); - auto it = database.m_type_map.find(type); - if (it == database.m_type_map.end()){ - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid type enum."); - } - return it->second; -} -const std::map& all_type_sprites(){ - return TypeSpriteDatabase::instance().m_type_map; -} - - - - -} -} -} +/* Pokemon Sword/Shield Type Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "CommonFramework/Globals.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTools/ImageStats.h" +#include "CommonTools/Images/BinaryImage_FilterRgb32.h" +#include "PokemonSwSh_TypeSprites.h" + +//#include +//using std::cout; +//using std::endl; + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Kernels; +using namespace Kernels::Waterfill; + + + + +struct TypeSpriteDatabase{ + std::map m_type_map; + + static TypeSpriteDatabase& instance(){ + static TypeSpriteDatabase data; + return data; + } + + TypeSpriteDatabase(){ + for (const auto& item : POKEMON_TYPE_SLUGS()){ + if (item.first == PokemonType::NONE){ + continue; + } + m_type_map.emplace(item.first, item.second); + } + } + +}; + + + + + + +TypeSprite::TypeSprite(const std::string& slug) + : m_slug(slug) +{ + ImageRGB32 sprite(RESOURCE_PATH() + "PokemonSwSh/Types/" + slug + ".png"); + + // Set all non-255 alphas to zero. + size_t words = sprite.bytes_per_row() / sizeof(uint32_t); + uint32_t* ptr = sprite.data(); + for (size_t r = 0; r < sprite.height(); r++){ + for (size_t c = 0; c < sprite.width(); c++){ +// cout << qAlpha(sprite.pixel(c, r)) << " "; + uint32_t pixel = ptr[c]; + if ((pixel >> 24) != 0xff){ + ptr[c] = 0; + } + } +// cout << endl; + ptr += words; + } + + // Compute white objects. + PackedBinaryMatrix matrix = compress_rgb32_to_binary_min(sprite, 224, 224, 224); + + std::vector objects = find_objects_inplace(matrix, 10); + + WaterfillObject object; + for (const WaterfillObject& item : objects){ +// cout << item.center_x() << "," << item.center_y() << endl; + object.merge_assume_no_overlap(item); + } + +// sprite.save("symbol-" + std::to_string(slug) + ".png"); + m_matcher.reset( + new ImageMatch::WeightedExactImageMatcher( + sprite.sub_image(object.min_x, object.min_y, object.width(), object.height()).copy(), + ImageMatch::WeightedExactImageMatcher::InverseStddevWeight{1, 64} + ) + ); +} + + +const TypeSprite& get_type_sprite(PokemonType type){ + const TypeSpriteDatabase& database = TypeSpriteDatabase::instance(); + auto it = database.m_type_map.find(type); + if (it == database.m_type_map.end()){ + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Invalid type enum."); + } + return it->second; +} +const std::map& all_type_sprites(){ + return TypeSpriteDatabase::instance().m_type_map; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h index ba410934d8..55fc32eda5 100644 --- a/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h +++ b/SerialPrograms/Source/PokemonSwSh/Resources/PokemonSwSh_TypeSprites.h @@ -1,49 +1,49 @@ -/* Pokemon Sword/Shield Type Sprites - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_PokemonSwSh_TypeSprites_H -#define PokemonAutomation_PokemonSwSh_TypeSprites_H - -#include -#include -#include "CommonTools/ImageMatch/ExactImageMatcher.h" -#include "Pokemon/Pokemon_Types.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class TypeSprite{ -public: - const std::string& slug() const{ return m_slug; } -// const ImageRGB32& sprite() const{ return m_sprite; } - - const ImageMatch::WeightedExactImageMatcher& matcher() const{ return *m_matcher; } - -public: -// friend struct TypeSpriteDatabase; - TypeSprite(const std::string& slug); - -private: - std::string m_slug; - - std::unique_ptr m_matcher; -}; - - -const TypeSprite& get_type_sprite(PokemonType type); -const std::map& all_type_sprites(); - - - - -} -} -} -#endif +/* Pokemon Sword/Shield Type Sprites + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_PokemonSwSh_TypeSprites_H +#define PokemonAutomation_PokemonSwSh_TypeSprites_H + +#include +#include +#include "CommonTools/ImageMatch/ExactImageMatcher.h" +#include "Pokemon/Pokemon_Types.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class TypeSprite{ +public: + const std::string& slug() const{ return m_slug; } +// const ImageRGB32& sprite() const{ return m_sprite; } + + const ImageMatch::WeightedExactImageMatcher& matcher() const{ return *m_matcher; } + +public: +// friend struct TypeSpriteDatabase; + TypeSprite(const std::string& slug); + +private: + std::string m_slug; + + std::unique_ptr m_matcher; +}; + + +const TypeSprite& get_type_sprite(PokemonType type); +const std::map& all_type_sprites(); + + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.cpp b/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.cpp index fcddeba451..816f3ad0b8 100644 --- a/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.cpp +++ b/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.cpp @@ -1,93 +1,93 @@ -/* Shiny Hunt Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#include "Common/Cpp/Exceptions.h" -#include "ShinyHuntTracker.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - - - - -ShinyHuntTracker::ShinyHuntTracker(bool shiny_types) - : m_encounters(m_stats["Encounters"]) - , m_caught(m_stats["Caught"]) - , m_errors(m_stats["Errors"]) - , m_unknown_shinies(m_stats[shiny_types ? "Unknown Shinies" : "Shinies"]) - , m_star_shinies(m_stats["Star Shinies"]) - , m_square_shinies(m_stats["Square Shinies"]) -{ - m_display_order.emplace_back("Encounters"); - m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); - if (shiny_types){ - m_display_order.emplace_back("Star Shinies", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Square Shinies", HIDDEN_IF_ZERO); - m_display_order.emplace_back("Unknown Shinies", HIDDEN_IF_ZERO); - }else{ - m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); - } - m_display_order.emplace_back("Caught", HIDDEN_IF_ZERO); -} -ShinyHuntTracker::ShinyHuntTracker(bool shiny_types, std::map aliases) - : ShinyHuntTracker(shiny_types) -{ - m_aliases = std::move(aliases); -} - -void ShinyHuntTracker::operator+=(ShinyType detection){ - switch (detection){ - case ShinyType::UNKNOWN: - m_errors++; - break; - case ShinyType::NOT_SHINY: - m_encounters++; - break; - case ShinyType::MAYBE_SHINY: - throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add a MAYBE_SHINY to stats."); - case ShinyType::UNKNOWN_SHINY: - m_encounters++; - m_unknown_shinies++; - break; - case ShinyType::STAR_SHINY: - m_encounters++; - m_star_shinies++; - break; - case ShinyType::SQUARE_SHINY: - m_encounters++; - m_square_shinies++; - break; - } -} -void ShinyHuntTracker::add_non_shiny(){ - m_encounters++; -} -void ShinyHuntTracker::add_error(){ - m_errors++; -} -void ShinyHuntTracker::add_unknown_shiny(){ - m_encounters++; - m_unknown_shinies++; -} -void ShinyHuntTracker::add_star_shiny(){ - m_encounters++; - m_star_shinies++; -} -void ShinyHuntTracker::add_square_shiny(){ - m_encounters++; - m_square_shinies++; -} -void ShinyHuntTracker::add_caught(){ - m_caught++; -} - - - - -} -} -} +/* Shiny Hunt Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#include "Common/Cpp/Exceptions.h" +#include "ShinyHuntTracker.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + + + + +ShinyHuntTracker::ShinyHuntTracker(bool shiny_types) + : m_encounters(m_stats["Encounters"]) + , m_caught(m_stats["Caught"]) + , m_errors(m_stats["Errors"]) + , m_unknown_shinies(m_stats[shiny_types ? "Unknown Shinies" : "Shinies"]) + , m_star_shinies(m_stats["Star Shinies"]) + , m_square_shinies(m_stats["Square Shinies"]) +{ + m_display_order.emplace_back("Encounters"); + m_display_order.emplace_back("Errors", HIDDEN_IF_ZERO); + if (shiny_types){ + m_display_order.emplace_back("Star Shinies", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Square Shinies", HIDDEN_IF_ZERO); + m_display_order.emplace_back("Unknown Shinies", HIDDEN_IF_ZERO); + }else{ + m_display_order.emplace_back("Shinies", HIDDEN_IF_ZERO); + } + m_display_order.emplace_back("Caught", HIDDEN_IF_ZERO); +} +ShinyHuntTracker::ShinyHuntTracker(bool shiny_types, std::map aliases) + : ShinyHuntTracker(shiny_types) +{ + m_aliases = std::move(aliases); +} + +void ShinyHuntTracker::operator+=(ShinyType detection){ + switch (detection){ + case ShinyType::UNKNOWN: + m_errors++; + break; + case ShinyType::NOT_SHINY: + m_encounters++; + break; + case ShinyType::MAYBE_SHINY: + throw InternalProgramError(nullptr, PA_CURRENT_FUNCTION, "Attempted to add a MAYBE_SHINY to stats."); + case ShinyType::UNKNOWN_SHINY: + m_encounters++; + m_unknown_shinies++; + break; + case ShinyType::STAR_SHINY: + m_encounters++; + m_star_shinies++; + break; + case ShinyType::SQUARE_SHINY: + m_encounters++; + m_square_shinies++; + break; + } +} +void ShinyHuntTracker::add_non_shiny(){ + m_encounters++; +} +void ShinyHuntTracker::add_error(){ + m_errors++; +} +void ShinyHuntTracker::add_unknown_shiny(){ + m_encounters++; + m_unknown_shinies++; +} +void ShinyHuntTracker::add_star_shiny(){ + m_encounters++; + m_star_shinies++; +} +void ShinyHuntTracker::add_square_shiny(){ + m_encounters++; + m_square_shinies++; +} +void ShinyHuntTracker::add_caught(){ + m_caught++; +} + + + + +} +} +} diff --git a/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.h b/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.h index 60b15f9ee0..94db80c79d 100644 --- a/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.h +++ b/SerialPrograms/Source/PokemonSwSh/ShinyHuntTracker.h @@ -1,50 +1,50 @@ -/* Shiny Hunt Tracker - * - * From: https://github.com/PokemonAutomation/ - * - */ - -#ifndef PokemonAutomation_ShinyHuntTracker_H -#define PokemonAutomation_ShinyHuntTracker_H - -#include "CommonFramework/ProgramStats/StatsTracking.h" -#include "Pokemon/Pokemon_DataTypes.h" - -namespace PokemonAutomation{ -namespace NintendoSwitch{ -namespace PokemonSwSh{ - -using namespace Pokemon; - - -class ShinyHuntTracker : public StatsTracker{ -public: - ShinyHuntTracker(bool shiny_types); - ShinyHuntTracker(bool shiny_types, std::map aliases); - - uint64_t encounters() const{ return m_encounters.load(std::memory_order_relaxed); } - - void operator+=(ShinyType detection); - void add_non_shiny(); - void add_error(); - void add_unknown_shiny(); - void add_star_shiny(); - void add_square_shiny(); - void add_caught(); - -private: - std::atomic& m_encounters; - std::atomic& m_caught; - std::atomic& m_errors; - - std::atomic& m_unknown_shinies; - std::atomic& m_star_shinies; - std::atomic& m_square_shinies; -}; - - - -} -} -} -#endif +/* Shiny Hunt Tracker + * + * From: https://github.com/PokemonAutomation/ + * + */ + +#ifndef PokemonAutomation_ShinyHuntTracker_H +#define PokemonAutomation_ShinyHuntTracker_H + +#include "CommonFramework/ProgramStats/StatsTracking.h" +#include "Pokemon/Pokemon_DataTypes.h" + +namespace PokemonAutomation{ +namespace NintendoSwitch{ +namespace PokemonSwSh{ + +using namespace Pokemon; + + +class ShinyHuntTracker : public StatsTracker{ +public: + ShinyHuntTracker(bool shiny_types); + ShinyHuntTracker(bool shiny_types, std::map aliases); + + uint64_t encounters() const{ return m_encounters.load(std::memory_order_relaxed); } + + void operator+=(ShinyType detection); + void add_non_shiny(); + void add_error(); + void add_unknown_shiny(); + void add_star_shiny(); + void add_square_shiny(); + void add_caught(); + +private: + std::atomic& m_encounters; + std::atomic& m_caught; + std::atomic& m_errors; + + std::atomic& m_unknown_shinies; + std::atomic& m_star_shinies; + std::atomic& m_square_shinies; +}; + + + +} +} +} +#endif diff --git a/SerialPrograms/Source/Tests/CommandLineTests.cpp b/SerialPrograms/Source/Tests/CommandLineTests.cpp index 79e66a8c94..9049396e73 100644 --- a/SerialPrograms/Source/Tests/CommandLineTests.cpp +++ b/SerialPrograms/Source/Tests/CommandLineTests.cpp @@ -1,297 +1,297 @@ -/* Command Line Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "CommandLineTests.h" -#include "Common/Cpp/Exceptions.h" -#include "CommonFramework/GlobalSettingsPanel.h" -#include "PokemonLA_Tests.h" -#include "TestMap.h" -#include -#include -#include - -#include -#include -#include -#include -#include -#include -using std::cout; -using std::cerr; -using std::endl; - -namespace PokemonAutomation{ - - -// CommandLineTests/ <- root test folder -// - PokemonLA/ <- test space to organize tests -// - BattleMenuDetector/ <- test object, name of the class/function/file to test -// - IngoBattleDayTime_True.png <- test file - -namespace{ - -void print_equals(){ - cout << "===========================================" << endl; -} - -#define RETURN_IF_NOT_ZERO(statement) \ - do { \ - int _ret = (statement); \ - if (_ret != 0){ \ - return _ret; \ - } \ - } while (0) - -#define RETURN_IF_TEST_FAILED(test_func, file_path, num_passed) \ - do { \ - int _ret = 0; \ - try{ \ - _ret = test_func(file_path); \ - } catch (const std::exception& e) { \ - cout << "Test: " << (file_path) << " threw exception: " << e.what() << endl; \ - } catch (const Exception& e) {\ - cout << "Test: " << (file_path) << " threw " << e.name() << ": <<<" << e.message() << ">>>" << endl; \ - } \ - if (_ret > 0) {\ - print_equals(); \ - cout << "Test: " << (file_path) << " failed." << endl; \ - return _ret; \ - }else if (_ret == 0){ \ - num_passed++; \ - } \ - } while (0) - -bool skip_ignored_path(const QString& file_path, const std::vector& ignore_list){ - for(const auto& path_prefix : ignore_list){ - if (file_path.startsWith(path_prefix)){ - cout << "* Skip ignored path " << file_path.toStdString() << endl; - return true; - } - } - return false; -} - -int run_test_obj_dir(TestFunction test_func, const QString& directory_path, size_t& num_passed, const std::vector& ignore_list){ - QDirIterator file_iter(directory_path, QDir::Filter::Files, QDirIterator::IteratorFlag::Subdirectories); - - bool first_test_file = true; - while (file_iter.hasNext()){ - if (first_test_file == false){ - cout << "-------------------------------------------" << endl; - } - first_test_file = false; - - const QString next_file = file_iter.next(); - - // If filename starts with _, its considered a "hidden" file so skip it. - const QFileInfo file_info(next_file); - if (file_info.fileName().startsWith('_')){ - continue; - } - const std::string file_path = next_file.toStdString(); - - // Check ignore list to determine whether to skip the test - if (skip_ignored_path(next_file, ignore_list)){ - continue; - } - - // Call the function to do the actual test: - cout << file_path << endl; - RETURN_IF_TEST_FAILED(test_func, file_path, num_passed); - } - - return 0; -} - -// Run the tests inside a folder representing a "test object". -// It is usually defined as one detector, e.g. CommandLineTests/PokemonLA/BattleMenuDetector/ -int run_test_obj(const std::string& test_space, const QFileInfo& obj_info, size_t& num_passed, const std::vector& ignore_list){ - const std::string test_name = obj_info.fileName().toStdString(); - if (test_name == "." || test_name == ".."){ - return 0; - } - - print_equals(); - const TestFunction test_func = find_test_function(test_space, test_name); - if (test_func == nullptr){ - // No corresponding test code, skip the folder. - return 0; - } - - if (skip_ignored_path(obj_info.filePath(), ignore_list)){ - return 0; - } - - cout << "Testing " << test_name << ":" << endl; - - // Recursively get test filenames, like: - // ./CommandLineTests/PokemonLA/BattleMenuDetector/IngoBattleMenuDayTime_True.png - return run_test_obj_dir(test_func, obj_info.filePath(), num_passed, ignore_list); -} - -// Run the tests inside a folder representing a "test space". -// It is usually defined as one pokemon game, e.g. CommandLineTests/PokemonLA/ -int run_test_space(const QFileInfo& space_info, size_t& num_passed, const std::vector& ignore_list){ - QDir sub_dir(space_info.filePath()); - if (!sub_dir.exists()){ - cerr << "Error: cannot access " << space_info.filePath().toStdString() << endl; - return 1; - } - - if (skip_ignored_path(space_info.fileName(), ignore_list)){ - return 0; - } - - sub_dir.setFilter(QDir::Filter::Dirs); - // test_space e.g "PokemonLA". It's like the namespace. - const std::string test_space = space_info.fileName().toStdString(); - if (test_space == "." || test_space == ".."){ - return 0; - } - - // Look for sub-sub-folders as test object names, e.g. - // ./CommandLineTests/PokemonLA/BattleMenuDetector/ - const QFileInfoList obj_list = sub_dir.entryInfoList(); - for(const QFileInfo& obj_info : obj_list){ - RETURN_IF_NOT_ZERO(run_test_obj(test_space, obj_info, num_passed, ignore_list)); - } - - return 0; -} - - - - -} // end of anonymous namespace - - - -int run_command_line_tests(){ - const auto& root_folder_name = GlobalSettings::instance().COMMAND_LINE_TEST_FOLDER; - - QDir test_root_dir(root_folder_name.c_str()); - if (!test_root_dir.exists()){ - cerr << "Error: command line test folder " << root_folder_name << " does not exist." << endl; - return 1; - } - - QFileInfo test_root_info(root_folder_name.c_str()); - cout << "Looking for tests under test root folder: " << root_folder_name << endl; - - size_t num_passed = 0; - - const auto& selected_test_list = GlobalSettings::instance().COMMAND_LINE_TEST_LIST; - - // The ignore list will be used to skip path. - // The ignore list functions as path prefixes when determining which path to skip. - std::vector ignore_list; - for(const std::string& ignore_path : GlobalSettings::instance().COMMAND_LINE_IGNORE_LIST){ - QString path_cleaned = QDir::cleanPath(QString::fromStdString(root_folder_name + "/" + ignore_path)); - // Remove the trailing '/' or '\\' to make sure it can match the input path - // without the trailing '/' or '\\'. - if (path_cleaned.endsWith('/') || path_cleaned.endsWith('\\')){ - path_cleaned.chop(1); - } - ignore_list.emplace_back(std::move(path_cleaned)); - } - - // Run all tests - if (selected_test_list.size() == 0){ - // Look for sub-folders, e.g. - // ./CommandLineTests/PokemonLA/ - // ./CommandLineTests/PokemonSwSh/ - test_root_dir.setFilter(QDir::Filter::Dirs); - const QFileInfoList sub_dir_list = test_root_dir.entryInfoList(); - for(const QFileInfo& sub_dir_info : sub_dir_list){ - RETURN_IF_NOT_ZERO(run_test_space(sub_dir_info, num_passed, ignore_list)); - } - }else{ - // Only run on selected tests - for(const std::string& test_path : selected_test_list){ - const std::string full_path = root_folder_name + "/" + test_path; - const QString full_path_cleaned = QDir::cleanPath(QString::fromStdString(full_path)); - - if (full_path_cleaned.size() == 0){ - cerr << "Error: empty path found in TEST_LIST" << endl; - return 1; - } - - if (skip_ignored_path(full_path_cleaned, ignore_list)){ - continue; - } - - QFileInfo selected_path_info(full_path_cleaned); - - if (selected_path_info.exists() == false){ - cerr << "Error: path " << full_path << " in TEST_LIST does not exist." << endl; - return 1; - } - - std::list path_components; - { - QString path = full_path_cleaned; - QFileInfo cur_info(path); - while(cur_info != test_root_info){ - path_components.push_front(cur_info.fileName()); - // Go upper one level of folder: - path = cur_info.path(); - cur_info = QFileInfo(path); - } - } - // If full_path is "CommandLineTest/PokemonLA/DialogueEllipseDetector/macOS_bright/WendyNight_True.png", then - // path_components contains: - // - PokemonLA - // - DialogueEllipseDetector - // - macOS_bright - // - WendyNight_True.png - if (path_components.size() == 0){ - cerr << "Error: cannot parse " << full_path << ". Empty path in TEST_LIST?" << endl; - return 1; - } - - QDir cur_dir(root_folder_name.c_str()); - - auto it = path_components.begin(); - std::string test_space = it->toStdString(); - QFileInfo test_space_info(cur_dir.filePath(*it)); - cur_dir = QDir(test_space_info.filePath()); - if (path_components.size() == 1){ - RETURN_IF_NOT_ZERO(run_test_space(test_space_info, num_passed, ignore_list)); - continue; - } - - it++; - std::string test_name = it->toStdString(); - QFileInfo test_obj_info(cur_dir.filePath(*it)); - if (path_components.size() == 2){ - RETURN_IF_NOT_ZERO(run_test_obj(test_space, test_obj_info, num_passed, ignore_list)); - continue; - } - - const auto test_func = find_test_function(test_space, test_name); - if (test_func == nullptr){ - return 2; - } - - print_equals(); - if (selected_path_info.isFile()){ - // Call the function to do the actual test: - RETURN_IF_TEST_FAILED(test_func, full_path_cleaned.toStdString(), num_passed); - }else{ - // selected_path_info is a directory, go through each file recursively in the directory - RETURN_IF_NOT_ZERO(run_test_obj_dir(test_func, full_path_cleaned, num_passed, ignore_list)); - } - } // end selected_test_list - } - - print_equals(); - cout << num_passed << " test" << (num_passed > 1 ? "s" : "") << " passed" << std::endl; - return 0; -} - - +/* Command Line Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "CommandLineTests.h" +#include "Common/Cpp/Exceptions.h" +#include "CommonFramework/GlobalSettingsPanel.h" +#include "PokemonLA_Tests.h" +#include "TestMap.h" +#include +#include +#include + +#include +#include +#include +#include +#include +#include +using std::cout; +using std::cerr; +using std::endl; + +namespace PokemonAutomation{ + + +// CommandLineTests/ <- root test folder +// - PokemonLA/ <- test space to organize tests +// - BattleMenuDetector/ <- test object, name of the class/function/file to test +// - IngoBattleDayTime_True.png <- test file + +namespace{ + +void print_equals(){ + cout << "===========================================" << endl; +} + +#define RETURN_IF_NOT_ZERO(statement) \ + do { \ + int _ret = (statement); \ + if (_ret != 0){ \ + return _ret; \ + } \ + } while (0) + +#define RETURN_IF_TEST_FAILED(test_func, file_path, num_passed) \ + do { \ + int _ret = 0; \ + try{ \ + _ret = test_func(file_path); \ + } catch (const std::exception& e) { \ + cout << "Test: " << (file_path) << " threw exception: " << e.what() << endl; \ + } catch (const Exception& e) {\ + cout << "Test: " << (file_path) << " threw " << e.name() << ": <<<" << e.message() << ">>>" << endl; \ + } \ + if (_ret > 0) {\ + print_equals(); \ + cout << "Test: " << (file_path) << " failed." << endl; \ + return _ret; \ + }else if (_ret == 0){ \ + num_passed++; \ + } \ + } while (0) + +bool skip_ignored_path(const QString& file_path, const std::vector& ignore_list){ + for(const auto& path_prefix : ignore_list){ + if (file_path.startsWith(path_prefix)){ + cout << "* Skip ignored path " << file_path.toStdString() << endl; + return true; + } + } + return false; +} + +int run_test_obj_dir(TestFunction test_func, const QString& directory_path, size_t& num_passed, const std::vector& ignore_list){ + QDirIterator file_iter(directory_path, QDir::Filter::Files, QDirIterator::IteratorFlag::Subdirectories); + + bool first_test_file = true; + while (file_iter.hasNext()){ + if (first_test_file == false){ + cout << "-------------------------------------------" << endl; + } + first_test_file = false; + + const QString next_file = file_iter.next(); + + // If filename starts with _, its considered a "hidden" file so skip it. + const QFileInfo file_info(next_file); + if (file_info.fileName().startsWith('_')){ + continue; + } + const std::string file_path = next_file.toStdString(); + + // Check ignore list to determine whether to skip the test + if (skip_ignored_path(next_file, ignore_list)){ + continue; + } + + // Call the function to do the actual test: + cout << file_path << endl; + RETURN_IF_TEST_FAILED(test_func, file_path, num_passed); + } + + return 0; +} + +// Run the tests inside a folder representing a "test object". +// It is usually defined as one detector, e.g. CommandLineTests/PokemonLA/BattleMenuDetector/ +int run_test_obj(const std::string& test_space, const QFileInfo& obj_info, size_t& num_passed, const std::vector& ignore_list){ + const std::string test_name = obj_info.fileName().toStdString(); + if (test_name == "." || test_name == ".."){ + return 0; + } + + print_equals(); + const TestFunction test_func = find_test_function(test_space, test_name); + if (test_func == nullptr){ + // No corresponding test code, skip the folder. + return 0; + } + + if (skip_ignored_path(obj_info.filePath(), ignore_list)){ + return 0; + } + + cout << "Testing " << test_name << ":" << endl; + + // Recursively get test filenames, like: + // ./CommandLineTests/PokemonLA/BattleMenuDetector/IngoBattleMenuDayTime_True.png + return run_test_obj_dir(test_func, obj_info.filePath(), num_passed, ignore_list); +} + +// Run the tests inside a folder representing a "test space". +// It is usually defined as one pokemon game, e.g. CommandLineTests/PokemonLA/ +int run_test_space(const QFileInfo& space_info, size_t& num_passed, const std::vector& ignore_list){ + QDir sub_dir(space_info.filePath()); + if (!sub_dir.exists()){ + cerr << "Error: cannot access " << space_info.filePath().toStdString() << endl; + return 1; + } + + if (skip_ignored_path(space_info.fileName(), ignore_list)){ + return 0; + } + + sub_dir.setFilter(QDir::Filter::Dirs); + // test_space e.g "PokemonLA". It's like the namespace. + const std::string test_space = space_info.fileName().toStdString(); + if (test_space == "." || test_space == ".."){ + return 0; + } + + // Look for sub-sub-folders as test object names, e.g. + // ./CommandLineTests/PokemonLA/BattleMenuDetector/ + const QFileInfoList obj_list = sub_dir.entryInfoList(); + for(const QFileInfo& obj_info : obj_list){ + RETURN_IF_NOT_ZERO(run_test_obj(test_space, obj_info, num_passed, ignore_list)); + } + + return 0; +} + + + + +} // end of anonymous namespace + + + +int run_command_line_tests(){ + const auto& root_folder_name = GlobalSettings::instance().COMMAND_LINE_TEST_FOLDER; + + QDir test_root_dir(root_folder_name.c_str()); + if (!test_root_dir.exists()){ + cerr << "Error: command line test folder " << root_folder_name << " does not exist." << endl; + return 1; + } + + QFileInfo test_root_info(root_folder_name.c_str()); + cout << "Looking for tests under test root folder: " << root_folder_name << endl; + + size_t num_passed = 0; + + const auto& selected_test_list = GlobalSettings::instance().COMMAND_LINE_TEST_LIST; + + // The ignore list will be used to skip path. + // The ignore list functions as path prefixes when determining which path to skip. + std::vector ignore_list; + for(const std::string& ignore_path : GlobalSettings::instance().COMMAND_LINE_IGNORE_LIST){ + QString path_cleaned = QDir::cleanPath(QString::fromStdString(root_folder_name + "/" + ignore_path)); + // Remove the trailing '/' or '\\' to make sure it can match the input path + // without the trailing '/' or '\\'. + if (path_cleaned.endsWith('/') || path_cleaned.endsWith('\\')){ + path_cleaned.chop(1); + } + ignore_list.emplace_back(std::move(path_cleaned)); + } + + // Run all tests + if (selected_test_list.size() == 0){ + // Look for sub-folders, e.g. + // ./CommandLineTests/PokemonLA/ + // ./CommandLineTests/PokemonSwSh/ + test_root_dir.setFilter(QDir::Filter::Dirs); + const QFileInfoList sub_dir_list = test_root_dir.entryInfoList(); + for(const QFileInfo& sub_dir_info : sub_dir_list){ + RETURN_IF_NOT_ZERO(run_test_space(sub_dir_info, num_passed, ignore_list)); + } + }else{ + // Only run on selected tests + for(const std::string& test_path : selected_test_list){ + const std::string full_path = root_folder_name + "/" + test_path; + const QString full_path_cleaned = QDir::cleanPath(QString::fromStdString(full_path)); + + if (full_path_cleaned.size() == 0){ + cerr << "Error: empty path found in TEST_LIST" << endl; + return 1; + } + + if (skip_ignored_path(full_path_cleaned, ignore_list)){ + continue; + } + + QFileInfo selected_path_info(full_path_cleaned); + + if (selected_path_info.exists() == false){ + cerr << "Error: path " << full_path << " in TEST_LIST does not exist." << endl; + return 1; + } + + std::list path_components; + { + QString path = full_path_cleaned; + QFileInfo cur_info(path); + while(cur_info != test_root_info){ + path_components.push_front(cur_info.fileName()); + // Go upper one level of folder: + path = cur_info.path(); + cur_info = QFileInfo(path); + } + } + // If full_path is "CommandLineTest/PokemonLA/DialogueEllipseDetector/macOS_bright/WendyNight_True.png", then + // path_components contains: + // - PokemonLA + // - DialogueEllipseDetector + // - macOS_bright + // - WendyNight_True.png + if (path_components.size() == 0){ + cerr << "Error: cannot parse " << full_path << ". Empty path in TEST_LIST?" << endl; + return 1; + } + + QDir cur_dir(root_folder_name.c_str()); + + auto it = path_components.begin(); + std::string test_space = it->toStdString(); + QFileInfo test_space_info(cur_dir.filePath(*it)); + cur_dir = QDir(test_space_info.filePath()); + if (path_components.size() == 1){ + RETURN_IF_NOT_ZERO(run_test_space(test_space_info, num_passed, ignore_list)); + continue; + } + + it++; + std::string test_name = it->toStdString(); + QFileInfo test_obj_info(cur_dir.filePath(*it)); + if (path_components.size() == 2){ + RETURN_IF_NOT_ZERO(run_test_obj(test_space, test_obj_info, num_passed, ignore_list)); + continue; + } + + const auto test_func = find_test_function(test_space, test_name); + if (test_func == nullptr){ + return 2; + } + + print_equals(); + if (selected_path_info.isFile()){ + // Call the function to do the actual test: + RETURN_IF_TEST_FAILED(test_func, full_path_cleaned.toStdString(), num_passed); + }else{ + // selected_path_info is a directory, go through each file recursively in the directory + RETURN_IF_NOT_ZERO(run_test_obj_dir(test_func, full_path_cleaned, num_passed, ignore_list)); + } + } // end selected_test_list + } + + print_equals(); + cout << num_passed << " test" << (num_passed > 1 ? "s" : "") << " passed" << std::endl; + return 0; +} + + } \ No newline at end of file diff --git a/SerialPrograms/Source/Tests/CommandLineTests.h b/SerialPrograms/Source/Tests/CommandLineTests.h index 58e5e6403b..ee56b93dfd 100644 --- a/SerialPrograms/Source/Tests/CommandLineTests.h +++ b/SerialPrograms/Source/Tests/CommandLineTests.h @@ -1,102 +1,102 @@ -/* Command Line Tests - * - * From: https://github.com/PokemonAutomation/ - * - * Explanation of the command line test framework - * - * Goals: - * - * - To build a unit test-like framework to ensure correctness of the various inference methods. - * - To allow efficient iterations during development of a new inference method without the need to launch GUI and click buttons. - * - * - * How to use the test folder: - * - * Enable the command line test mode by changing the SerialPrograms-Settings.json field: - * "20-GlobalSettings": "COMMAND_LINE_TESTS": "RUN" to true. - * In this mode, the program does not launch GUI. Instead it looks for a local folder which path is specified by the json field: - * "20-GlobalSettings": "COMMAND_LINE_TESTS": "FOLDER" - * and run tests inside it. - * The folder is structured as: - * ../CommandLineTests/ <- root test folder - * - PokemonLA/ <- test space, sub-folder to organize tests, e.g. by which games the inferences are used in - * - BattleMenuDetector/ <- test object, name of the class/function/file to test - * - IngoBattleDayTime_True.png <- test file for BattleMenuDetector - * - IngoBattleNightTime_True.png <- test file for BattleMenuDetector - * - PokemonBDSP/ <- another test space for inferences in another game - * - DialogDetector/ <- test object, this time it's DialogDetector for BDSP - * - Win_Mirabox/ <- can have more folders under test object to organize test files, e.g by OS and capture card - * - FetchEggDayTime_True.png <- test file for DialogDetector - * - * The test framework will go to each test object's folder and use its path to determine which test object to call. - * For example, if the path is CommandLineTest/PokemonLA/BattleMenuDetector/, the program will test the code in - * Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h. - * - * You can also selectively run some of the tests by setting - * "20-GlobalSettings": "COMMAND_LINE_TESTS": "TEST_LIST" as a list of strings. - * Each string will be a relative path. It can be any of: - * - "PokemonBDSP" - * - "PokemonBDSP/DialogDetector" - * - "PokemonBDSP/DialogDetector/Win_Mirabox" - * - "PokemonBDSP/DialogDetector/Win_Mirabox/FetchEggDayTime_True.png" - * This gives the flexibility to test the code for a game, a detector, a detector on a capture card or a detector on a particular image/audio/video. - * - * If you have put some test files for experimental code in a folder and later decide to not run that code for a while, you can use - * "20-GlobalSettings": "COMMAND_LINE_TESTS": "IGNORE_LIST" as a list of strings to skip the paths to those tests. - * Each string in the list serves as a prefix to the test path that the test framework uses to filter out paths. - * - * Those "hidden" files are useful for storing some metadata in the folder, or serving as an extra file in case some tests need more than one test files. - * - * How to add new test code: - * - * The test framework calls TestMap.h: find_test_function(test_space, test_obj_name) to find the test function related to a test path. - * For example, given a path PokemonLA/BattleMenuDetector/IngoBattleDayTime_True.png, by extracting test_space as "PokemonLA" and test_obj_name as - * "BattleMenuDetector" from the path, find_test_function() returns the code that runs - * Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h:BattleMenuDetector. - * - * Internally, find_test_function() searches in a map: TestMap.cpp:std::map TEST_MAP to get the correct test function. - * The key of the map in the above example is "PokemonLA_BattleMenuDetector" (we use "_" to connect test space and test obj name). The value of the - * map is TestFunction = std::function. - * Each implemented TestFunction needs to: - * - Check the test file path to see if the file is the desired data format (e.g. visual inference test checks for image files and audio inference test - * checks for audio files). If the file is not desired, simply return a negative integer to tell the caller that this file is skipped. - * - Run the test code on the file, if the the file format is desired. If test succeeds, return 0, otherwise return a positive integer to tell the caller - * the test failed. - * - While running the test code, we also need to know the target test code output (or the content in golden files) so that we can know whether the test is - * successful or not. For simple tasks like testing battle menu detector, the target of each test image is a single bool, indicating whether the current - * image represents a screenshot with battle menu. So we can embed the target output into the test file name: IngoBattleDayTime_True.png. - * For more complex outputs, like detecting how many or where some objects are on the screen, or where the shiny sound is in the audio file, it would - * need a very long filename to store them. So we chose to store those outputs in a golden file. - * - * To avoid implementing the above logic of skipping files and finding target outputs in every TestFunction, we add helper functions like - * TestMap.h:int screen_bool_detector_helper(ScreenBoolDetectorFunction test_func, const std::string& test_path) - * screen_bool_detector_helper helps implement visual inference test with single bool as output (just like BattleMenuDetector). - * It implements skipping non-image files and parse filename to get target output bool. - * It then calls ScreenBoolDetectorFunction = std::function test_func which will be implemented by the test developer - * to call the actual inference code and check its result against the target bool. - * - * So in order to implement a test for, let's say, BattleMenuDetector: - * - Implement a ScreenBoolDetectorFunction, test_pokemonLA_BattleMenuDetector() that calls the detector code and compares the result with the target bool. - * The implementation is written in PokemonLA_Tests.cpp. - * - Write the function declaration in PokemonLA_Tests.h - * - Add a new entry to TestMap.cpp:TEST_MAP by utilizing screen_bool_detector_helper: - * {"PokemonLA_BattleMenuDetector", std::bind(screen_bool_detector_helper, test_pokemonLA_BattleMenuDetector, _1)} - */ - - -#ifndef PokemonAutomation_Tests_CommandLineTests_H -#define PokemonAutomation_Tests_CommandLineTests_H - - -namespace PokemonAutomation{ - - -// Called by main() to run tests on command line, without launching any GUI. -// This function is only called when GlobalSettings::COMMAND_LINE_TEST_MODE is true. -// Return 0 if all tests are passed. -int run_command_line_tests(); - - - -} -#endif +/* Command Line Tests + * + * From: https://github.com/PokemonAutomation/ + * + * Explanation of the command line test framework + * + * Goals: + * + * - To build a unit test-like framework to ensure correctness of the various inference methods. + * - To allow efficient iterations during development of a new inference method without the need to launch GUI and click buttons. + * + * + * How to use the test folder: + * + * Enable the command line test mode by changing the SerialPrograms-Settings.json field: + * "20-GlobalSettings": "COMMAND_LINE_TESTS": "RUN" to true. + * In this mode, the program does not launch GUI. Instead it looks for a local folder which path is specified by the json field: + * "20-GlobalSettings": "COMMAND_LINE_TESTS": "FOLDER" + * and run tests inside it. + * The folder is structured as: + * ../CommandLineTests/ <- root test folder + * - PokemonLA/ <- test space, sub-folder to organize tests, e.g. by which games the inferences are used in + * - BattleMenuDetector/ <- test object, name of the class/function/file to test + * - IngoBattleDayTime_True.png <- test file for BattleMenuDetector + * - IngoBattleNightTime_True.png <- test file for BattleMenuDetector + * - PokemonBDSP/ <- another test space for inferences in another game + * - DialogDetector/ <- test object, this time it's DialogDetector for BDSP + * - Win_Mirabox/ <- can have more folders under test object to organize test files, e.g by OS and capture card + * - FetchEggDayTime_True.png <- test file for DialogDetector + * + * The test framework will go to each test object's folder and use its path to determine which test object to call. + * For example, if the path is CommandLineTest/PokemonLA/BattleMenuDetector/, the program will test the code in + * Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h. + * + * You can also selectively run some of the tests by setting + * "20-GlobalSettings": "COMMAND_LINE_TESTS": "TEST_LIST" as a list of strings. + * Each string will be a relative path. It can be any of: + * - "PokemonBDSP" + * - "PokemonBDSP/DialogDetector" + * - "PokemonBDSP/DialogDetector/Win_Mirabox" + * - "PokemonBDSP/DialogDetector/Win_Mirabox/FetchEggDayTime_True.png" + * This gives the flexibility to test the code for a game, a detector, a detector on a capture card or a detector on a particular image/audio/video. + * + * If you have put some test files for experimental code in a folder and later decide to not run that code for a while, you can use + * "20-GlobalSettings": "COMMAND_LINE_TESTS": "IGNORE_LIST" as a list of strings to skip the paths to those tests. + * Each string in the list serves as a prefix to the test path that the test framework uses to filter out paths. + * + * Those "hidden" files are useful for storing some metadata in the folder, or serving as an extra file in case some tests need more than one test files. + * + * How to add new test code: + * + * The test framework calls TestMap.h: find_test_function(test_space, test_obj_name) to find the test function related to a test path. + * For example, given a path PokemonLA/BattleMenuDetector/IngoBattleDayTime_True.png, by extracting test_space as "PokemonLA" and test_obj_name as + * "BattleMenuDetector" from the path, find_test_function() returns the code that runs + * Source/PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h:BattleMenuDetector. + * + * Internally, find_test_function() searches in a map: TestMap.cpp:std::map TEST_MAP to get the correct test function. + * The key of the map in the above example is "PokemonLA_BattleMenuDetector" (we use "_" to connect test space and test obj name). The value of the + * map is TestFunction = std::function. + * Each implemented TestFunction needs to: + * - Check the test file path to see if the file is the desired data format (e.g. visual inference test checks for image files and audio inference test + * checks for audio files). If the file is not desired, simply return a negative integer to tell the caller that this file is skipped. + * - Run the test code on the file, if the the file format is desired. If test succeeds, return 0, otherwise return a positive integer to tell the caller + * the test failed. + * - While running the test code, we also need to know the target test code output (or the content in golden files) so that we can know whether the test is + * successful or not. For simple tasks like testing battle menu detector, the target of each test image is a single bool, indicating whether the current + * image represents a screenshot with battle menu. So we can embed the target output into the test file name: IngoBattleDayTime_True.png. + * For more complex outputs, like detecting how many or where some objects are on the screen, or where the shiny sound is in the audio file, it would + * need a very long filename to store them. So we chose to store those outputs in a golden file. + * + * To avoid implementing the above logic of skipping files and finding target outputs in every TestFunction, we add helper functions like + * TestMap.h:int screen_bool_detector_helper(ScreenBoolDetectorFunction test_func, const std::string& test_path) + * screen_bool_detector_helper helps implement visual inference test with single bool as output (just like BattleMenuDetector). + * It implements skipping non-image files and parse filename to get target output bool. + * It then calls ScreenBoolDetectorFunction = std::function test_func which will be implemented by the test developer + * to call the actual inference code and check its result against the target bool. + * + * So in order to implement a test for, let's say, BattleMenuDetector: + * - Implement a ScreenBoolDetectorFunction, test_pokemonLA_BattleMenuDetector() that calls the detector code and compares the result with the target bool. + * The implementation is written in PokemonLA_Tests.cpp. + * - Write the function declaration in PokemonLA_Tests.h + * - Add a new entry to TestMap.cpp:TEST_MAP by utilizing screen_bool_detector_helper: + * {"PokemonLA_BattleMenuDetector", std::bind(screen_bool_detector_helper, test_pokemonLA_BattleMenuDetector, _1)} + */ + + +#ifndef PokemonAutomation_Tests_CommandLineTests_H +#define PokemonAutomation_Tests_CommandLineTests_H + + +namespace PokemonAutomation{ + + +// Called by main() to run tests on command line, without launching any GUI. +// This function is only called when GlobalSettings::COMMAND_LINE_TEST_MODE is true. +// Return 0 if all tests are passed. +int run_command_line_tests(); + + + +} +#endif diff --git a/SerialPrograms/Source/Tests/CommonFramework_Tests.cpp b/SerialPrograms/Source/Tests/CommonFramework_Tests.cpp index 7122d959eb..5c32914009 100644 --- a/SerialPrograms/Source/Tests/CommonFramework_Tests.cpp +++ b/SerialPrograms/Source/Tests/CommonFramework_Tests.cpp @@ -1,32 +1,32 @@ -/* Common Framework Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonTools/VisualDetectors/BlackBorderDetector.h" -#include "CommonFramework_Tests.h" -#include "TestUtils.h" - - -//#include -//using std::cout; -//using std::cerr; -//using std::endl; - -namespace PokemonAutomation{ - -int test_CommonFramework_BlackBorderDetector(const ImageViewRGB32& image, bool target){ - BlackBorderDetector detector; - - bool result = detector.detect(image); - - TEST_RESULT_EQUAL(result, target); - - return 0; -} - - -} +/* Common Framework Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonTools/VisualDetectors/BlackBorderDetector.h" +#include "CommonFramework_Tests.h" +#include "TestUtils.h" + + +//#include +//using std::cout; +//using std::cerr; +//using std::endl; + +namespace PokemonAutomation{ + +int test_CommonFramework_BlackBorderDetector(const ImageViewRGB32& image, bool target){ + BlackBorderDetector detector; + + bool result = detector.detect(image); + + TEST_RESULT_EQUAL(result, target); + + return 0; +} + + +} diff --git a/SerialPrograms/Source/Tests/CommonFramework_Tests.h b/SerialPrograms/Source/Tests/CommonFramework_Tests.h index dcbe39d4c5..548c6d01a1 100644 --- a/SerialPrograms/Source/Tests/CommonFramework_Tests.h +++ b/SerialPrograms/Source/Tests/CommonFramework_Tests.h @@ -1,20 +1,20 @@ -/* Common Framework Tests - * - * From: https://github.com/PokemonAutomation/ - * - * - */ - - -#ifndef PokemonAutomation_Tests_CommonFramework_Tests_H -#define PokemonAutomation_Tests_CommonFramework_Tests_H - -namespace PokemonAutomation{ - -class ImageViewRGB32; - -int test_CommonFramework_BlackBorderDetector(const ImageViewRGB32& image, bool target); - -} - -#endif +/* Common Framework Tests + * + * From: https://github.com/PokemonAutomation/ + * + * + */ + + +#ifndef PokemonAutomation_Tests_CommonFramework_Tests_H +#define PokemonAutomation_Tests_CommonFramework_Tests_H + +namespace PokemonAutomation{ + +class ImageViewRGB32; + +int test_CommonFramework_BlackBorderDetector(const ImageViewRGB32& image, bool target); + +} + +#endif diff --git a/SerialPrograms/Source/Tests/Kernels_Tests.cpp b/SerialPrograms/Source/Tests/Kernels_Tests.cpp index 2cadd79687..27bb1ea34e 100644 --- a/SerialPrograms/Source/Tests/Kernels_Tests.cpp +++ b/SerialPrograms/Source/Tests/Kernels_Tests.cpp @@ -1,995 +1,995 @@ -/* Kernels Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "Common/Compiler.h" -#include "Common/Cpp/Color.h" -#include "Common/Cpp/CpuId/CpuId.h" -#include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTypes/BinaryImage.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" -#ifdef PA_AutoDispatch_arm64_20_M1 - #include "Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h" - #include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" - #include "Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h" -#endif -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h" -#include "Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h" -#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" -#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h" -#include "Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h" -#include "Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h" -#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h" -#include "Kernels/Waterfill/Kernels_Waterfill.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h" -#include "Kernels/Waterfill/Kernels_Waterfill_Routines.h" -#include "Kernels_Tests.h" -#include "TestUtils.h" - -#include -#include -using std::cout; -using std::cerr; -using std::endl; -using std::flush; - -namespace PokemonAutomation{ - -using namespace Kernels; - -namespace Kernels{} - -namespace{ - - - -} - -int test_binary_matrix_tile(); - - -int test_kernels_ImageScaleBrightness(const ImageViewRGB32& image){ - ImageRGB32 new_image = image.copy(); - - int num_iterations = 500; - auto time_start = current_time(); - for(int i = 0; i < num_iterations; i++){ - scale_brightness(new_image.width(), new_image.height(), new_image.data(), new_image.bytes_per_row(), 1.2f, 1.3f, 0.5f); - // break; - } - auto time_end = current_time(); - const auto ms = std::chrono::duration_cast(time_end - time_start).count(); - cout << "Time: " << ms << " ms, " << ms / 1000. << " s" << endl; - - // new_image.save("./output.png"); - - return 0; -} - - -int test_kernels_BinaryMatrix(const ImageViewRGB32& image){ - - if (test_binary_matrix_tile() != 0){ - return 1; - } - - const size_t width = image.width(), height = image.height(); - - const Color min_color(0, 0, 0), max_color(63, 63, 63); - const uint32_t mins = uint32_t(min_color), maxs = uint32_t(max_color); - - auto binary_matrix = make_PackedBinaryMatrix(get_BinaryMatrixType(), width, height); - - auto time_start = current_time(); - compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), *binary_matrix, mins, maxs - ); - auto time_end = current_time(); - size_t ns = std::chrono::duration_cast(time_end - time_start).count(); - double ms = ns / 1000000.; - cout << "One binary matrix creation. time: " << ms << " ms" << endl; - - size_t error_count = 0; - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - const Color color(image.pixel(x, y)); - bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); - in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); - in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); - in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); - - const bool v_default = binary_matrix->get(x, y); - - if (error_count < 10){ - if (v_default != in_range){ - cout << "Error: matrix (" << x << ", " << y << ") got " - << v_default << " but GT is " << in_range << endl; - ++error_count; - } - } - } - } - if (error_count){ - return 1; - } - - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), *binary_matrix, mins, maxs - ); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, average creation impl. time: " << ms / (double)num_iters << " ms" << endl; - - // cout << binary_matrix->dump() << flush; - - return 0; -} - -int test_kernels_FilterRGB32Range(const ImageViewRGB32& image){ - const size_t width = image.width(), height = image.height(); - cout << "Testing filter_rgb32_range(), image size " << width << " x " << height << endl; - - Color min_color(0, 0, 0); - Color max_color(63, 63, 63); - // Color max_color(238, 24, 42); - - const uint32_t mins = uint32_t(min_color); - const uint32_t maxs = uint32_t(max_color); - - ImageRGB32 image_out(image.width(), image.height()); - ImageRGB32 image_out_2(image.width(), image.height()); - size_t pixels_in_range = 0; - - const bool replace_color_within_range = true; - auto time_start = current_time(); - // auto new_image = filter_rgb32_range(image, mins, maxs, COLOR_WHITE, replace_color_within_range); - pixels_in_range = Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out.data(), image_out.bytes_per_row(), - (uint32_t)COLOR_WHITE, replace_color_within_range, - mins, maxs - ); - auto time_end = current_time(); - auto ns = std::chrono::duration_cast(time_end - time_start).count(); - auto ms = ns / 1000000.; - cout << "One filter time: " << ms << " ms" << endl; - - size_t pixels_in_range_2 = Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out_2.data(), image_out_2.bytes_per_row(), - (uint32_t)COLOR_WHITE, !replace_color_within_range, - mins, maxs - ); - - TEST_RESULT_EQUAL(pixels_in_range, pixels_in_range_2); - - size_t actual_num_pixels_in_range = 0; - size_t error_count = 0; - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - const Color color(image.pixel(x, y)); - const Color new_color(image_out.pixel(x, y)); - const Color new_color_2(image_out_2.pixel(x, y)); - bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); - in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); - in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); - in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); - actual_num_pixels_in_range += in_range; - if (error_count < 10){ - // Print first 10 errors: - if (in_range && new_color != COLOR_WHITE){ - cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be in range but not found by the function" << endl; - ++error_count; - }else if (in_range == false && new_color != color){ - cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should not be changed by the function" << endl; - ++error_count; - } - - if (in_range && new_color_2 != color){ - cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should not be changed by the function" << endl; - ++error_count; - }else if (in_range == false && new_color_2 != COLOR_WHITE){ - cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should not be in range but not found by the function" << endl; - ++error_count; - } - } - } - } - cout << "Found " << actual_num_pixels_in_range << " pixels in range" << endl; - if (pixels_in_range != actual_num_pixels_in_range){ - cout << "Error: wrong pixels in range: " << pixels_in_range << " actual: " << actual_num_pixels_in_range << endl; - return 1; - } - - if (error_count){ - return 1; - } - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - Kernels::filter_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out.data(), image_out.bytes_per_row(), - (uint32_t)COLOR_WHITE, replace_color_within_range, - mins, maxs - ); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; - - return 0; -} - - -int test_kernels_FilterRGB32Euclidean(const ImageViewRGB32& image){ - const size_t width = image.width(); - const size_t height = image.height(); - cout << "Testing test_kernels_FilterRGB32Euclidean(), image size " << width << " x " << height << endl; - - Color middle_color = Color(image.pixel(width/2, height/2)); - cout << "Expected color: " << middle_color.to_string() << endl; - - double max_dist = 50.0; - size_t max_dist2 = size_t(max_dist * max_dist); - - ImageRGB32 image_out(image.width(), image.height()); - ImageRGB32 image_out_2(image.width(), image.height()); - size_t pixels_in_range = 0; - - const bool replace_color_within_range = true; - auto time_start = current_time(); - pixels_in_range = Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out.data(), image_out.bytes_per_row(), - (uint32_t)COLOR_WHITE, replace_color_within_range, - uint32_t(middle_color), max_dist - ); - auto time_end = current_time(); - auto ns = std::chrono::duration_cast(time_end - time_start).count(); - auto ms = ns / 1000000.; - cout << "One filter time: " << ms << " ms" << endl; - - size_t pixels_in_range_2 = Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out_2.data(), image_out_2.bytes_per_row(), - (uint32_t)COLOR_WHITE, !replace_color_within_range, - uint32_t(middle_color), max_dist - ); - - TEST_RESULT_EQUAL(pixels_in_range, pixels_in_range_2); - - size_t actual_num_pixels_in_range = 0; - size_t error_count = 0; - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - const Color color(image.pixel(x, y)); - const Color new_color(image_out.pixel(x, y)); - const Color new_color_2(image_out_2.pixel(x, y)); - int red_dif = (color.red() - middle_color.red()); - int green_dif = (color.green() - middle_color.green()); - int blue_dif = (color.blue() - middle_color.blue()); - size_t color_dist2 = red_dif * red_dif + green_dif * green_dif + blue_dif * blue_dif; - bool in_range = color_dist2 <= max_dist2; - actual_num_pixels_in_range += in_range; - if (error_count < 10){ - // Print first 10 errors: - if (in_range && new_color != COLOR_WHITE){ - cout << "Error: wrong filter result: old color " << color.to_string() - << ", (x,y) = (" << x << ", " << y << ")" - << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 - << ", should be in range but not found by the function" << endl; - ++error_count; - }else if (in_range == false && new_color != color){ - cout << "Error: wrong filter result: old color " << color.to_string() - << ", (x,y) = (" << x << ", " << y << ")" - << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 - << ", should not be changed by the function" << endl; - ++error_count; - } - - if (in_range && new_color_2 != color){ - cout << "Error: wrong inverse filter result: old color " << color.to_string() - << ", (x,y) = (" << x << ", " << y << ")" - << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 - << ", should not be changed by the function" << endl; - ++error_count; - }else if (in_range == false && new_color_2 != COLOR_WHITE){ - cout << "Error: wrong inverse filter result: old color " << color.to_string() - << ", (x,y) = (" << x << ", " << y << ")" - << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 - << ", should not be in range but not found by the function" << endl; - ++error_count; - } - } - } - } - cout << "Found " << actual_num_pixels_in_range << " pixels in range" << endl; - if (pixels_in_range != actual_num_pixels_in_range){ - cout << "Error: wrong pixels in range: " << pixels_in_range << " actual: " << actual_num_pixels_in_range << endl; - return 1; - } - - if (error_count){ - return 1; - } - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - pixels_in_range = Kernels::filter_rgb32_euclidean( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out.data(), image_out.bytes_per_row(), - (uint32_t)COLOR_WHITE, replace_color_within_range, - uint32_t(middle_color), max_dist - ); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; - - return 0; -} - -int test_kernels_ToBlackWhiteRGB32Range(const ImageViewRGB32& image){ - const size_t width = image.width(); - const size_t height = image.height(); - cout << "Testing to_black_white_rgb32_range(), image size " << width << " x " << height << endl; - - Color min_color(0, 0, 0); - // Color min_color(0); - - Color max_color(63, 63, 63); - // Color max_color(255, 255, 255); - // Color max_color(238, 24, 42); - cout << "min color: " << min_color.to_string() << " max color: " << max_color.to_string() << endl; - - const uint32_t mins = uint32_t(min_color); - const uint32_t maxs = uint32_t(max_color); - - ImageRGB32 image_out(image.width(), image.height()); - ImageRGB32 image_out_2(image.width(), image.height()); - size_t pixels_in_range = 0; - - const bool in_range_black = true; - auto time_start = current_time(); - // auto new_image = filter_rgb32_range(image, mins, maxs, COLOR_WHITE, replace_color_within_range); - pixels_in_range = Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out.data(), image_out.bytes_per_row(), - in_range_black, - mins, maxs - ); - auto time_end = current_time(); - auto ns = std::chrono::duration_cast(time_end - time_start).count(); - auto ms = ns / 1000000.; - cout << "One filter time: " << ms << " ms" << endl; - - size_t pixels_in_range_2 = Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out_2.data(), image_out_2.bytes_per_row(), - !in_range_black, - mins, maxs - ); - - TEST_RESULT_EQUAL(pixels_in_range, pixels_in_range_2); - - size_t actual_num_pixels_in_range = 0; - size_t error_count = 0; - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - const Color color(image.pixel(x, y)); - const Color new_color(image_out.pixel(x, y)); - const Color new_color_2(image_out_2.pixel(x, y)); - bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); - in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); - in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); - in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); - actual_num_pixels_in_range += in_range; - if (error_count < 10){ - // Print first 10 errors: - if (in_range && new_color != COLOR_BLACK){ - cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be black due to in range but not so" << endl; - ++error_count; - }else if (in_range == false && new_color != COLOR_WHITE){ - cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be white due to out of range but not so" << endl; - ++error_count; - } - - if (in_range && new_color_2 != COLOR_WHITE){ - cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be white due to in range but not so" << endl; - ++error_count; - }else if (in_range == false && new_color_2 != COLOR_BLACK){ - cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be black due to out of range but not so" << endl; - ++error_count; - } - } - } - } - cout << "Found " << actual_num_pixels_in_range << " pixels in range" << endl; - if (pixels_in_range != actual_num_pixels_in_range){ - cout << "Error: wrong pixels in range: " << pixels_in_range << " actual: " << actual_num_pixels_in_range << endl; - return 1; - } - - if (error_count){ - return 1; - } - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - Kernels::to_blackwhite_rgb32_range( - image.data(), image.bytes_per_row(), image.width(), image.height(), - image_out.data(), image_out.bytes_per_row(), - in_range_black, - mins, maxs - ); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; - - return 0; -} - -int test_kernels_FilterByMask(const ImageViewRGB32& image){ - const size_t width = image.width(), height = image.height(); - cout << "Image width " << width << " height " << height << endl; - - const Color min_color(0, 0, 0), max_color(63, 63, 63); - const uint32_t mins = uint32_t(min_color), maxs = uint32_t(max_color); - - auto binary_matrix = make_PackedBinaryMatrix(get_BinaryMatrixType(), width, height); - compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), *binary_matrix, mins, maxs - ); - ImageRGB32 new_image = image.copy(); - ImageRGB32 new_image_2 = image.copy(); - - Color replacement_color = COLOR_WHITE; - bool replace_zero_bits = true; - - auto time_start = current_time(); - filter_by_mask(*binary_matrix, new_image.data(), new_image.bytes_per_row(), uint32_t(replacement_color), replace_zero_bits); - auto time_end = current_time(); - auto ns = std::chrono::duration_cast(time_end - time_start).count(); - auto ms = ns / 1000000.; - cout << "One Filter by mask call. time: " << ms << " ms" << endl; - - filter_by_mask(*binary_matrix, new_image_2.data(), new_image_2.bytes_per_row(), uint32_t(replacement_color), !replace_zero_bits); - - size_t error_count = 0; - - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - const Color color(image.pixel(x, y)); - const Color new_color(new_image.pixel(x, y)); - const Color new_color_2(new_image_2.pixel(x, y)); - bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); - in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); - in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); - in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); - - if (error_count <= 10){ - if (in_range && new_color != color){ - cout << "Error: wrong filter(replace_zero_bits) result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should not be changed due to being one bit but not so" << endl; - ++error_count; - }else if (!in_range && new_color != replacement_color){ - cout << "Error: wrong filter(replace_zero_bits) result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be changed due to being zero bit but not so" << endl; - ++error_count; - } - - if (in_range && new_color_2 != replacement_color){ - cout << "Error: wrong filter(replace_one_bits) result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should be changed due to being one bit but not so" << endl; - ++error_count; - }else if (!in_range && new_color_2 != color){ - cout << "Error: wrong filter(replace_one_bits) result: old color " << color.to_string() << ", (x,y) = " - << x << ", " << y << ", should not be changed due to being zero bit but not so" << endl; - ++error_count; - } - } - } - } - - if (error_count){ - return 1; - } - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - filter_by_mask(*binary_matrix, new_image.data(), new_image.bytes_per_row(), uint32_t(replacement_color), replace_zero_bits); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; - - return 0; -} - -int test_kernels_CompressRGB32ToBinaryEuclidean(const ImageViewRGB32& image){ - const size_t width = image.width(); - const size_t height = image.height(); - cout << "Testing test_kernels_CompressRGB32ToBinaryEuclidean(), image size " << width << " x " << height << endl; - - Color middle_color = Color(image.pixel(width/2, height/2)); - cout << "Expected color: " << middle_color.to_string() << endl; - - double max_dist = 50.0; - size_t max_dist2 = size_t(max_dist * max_dist); - - PackedBinaryMatrix matrix(image.width(), image.height()); - - auto time_start = current_time(); - Kernels::compress_rgb32_to_binary_euclidean( - image.data(), image.bytes_per_row(), matrix, - uint32_t(middle_color), max_dist - ); - auto time_end = current_time(); - auto ns = std::chrono::duration_cast(time_end - time_start).count(); - auto ms = ns / 1000000.; - cout << "One filter time: " << ms << " ms" << endl; - - size_t error_count = 0; - for (size_t y = 0; y < height; y++){ - for (size_t x = 0; x < width; x++){ - const Color color(image.pixel(x, y)); - int red_dif = (color.red() - middle_color.red()); - int green_dif = (color.green() - middle_color.green()); - int blue_dif = (color.blue() - middle_color.blue()); - size_t color_dist2 = red_dif * red_dif + green_dif * green_dif + blue_dif * blue_dif; - bool in_range = color_dist2 <= max_dist2; - if (error_count < 10){ - // Print first 10 errors: - if (in_range && matrix.get(x, y) == false){ - cout << "Error: wrong filter result: old color " << color.to_string() - << ", (x,y) = (" << x << ", " << y << ")" - << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 - << ", should be in range but not set on matrix" << endl; - ++error_count; - }else if (in_range == false && matrix.get(x, y) == true){ - cout << "Error: wrong filter result: old color " << color.to_string() - << ", (x,y) = (" << x << ", " << y << ")" - << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 - << ", should not be in range but set on matrix" << endl; - ++error_count; - } - } - } - } - if (error_count){ - return 1; - } - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - Kernels::compress_rgb32_to_binary_euclidean( - image.data(), image.bytes_per_row(), matrix, - uint32_t(middle_color), max_dist - ); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; - - return 0; -} - - - - -int test_kernels_Waterfill(const ImageViewRGB32& image){ - const size_t width = image.width(); - const size_t height = image.height(); - cout << "Testing test_kernels_Waterfill(), image size " << width << " x " << height << endl; - - PackedBinaryMatrix matrix(width, height); - uint32_t mins = combine_rgb(0, 0, 0); - // uint32_t maxs = combine_rgb(255, 255, 255); - uint32_t maxs = combine_rgb(63, 63, 63); - Kernels::compress_rgb32_to_binary_range( - image.data(), image.bytes_per_row(), - matrix, mins, maxs - ); - - PackedBinaryMatrix source_matrix = matrix.copy(); - - PackedBinaryMatrix gt_matrix = matrix.copy(); - Kernels::PackedBinaryMatrix_IB& gt_matrix_ib = gt_matrix; - - size_t min_area = 10; - std::vector gt_objects; - bool gt_computed = false; - -#ifdef PA_AutoDispatch_arm64_20_M1 - if (CPU_CAPABILITY_CURRENT.OK_M1){ - using Waterfill_64x8_Default = Kernels::Waterfill::Waterfill_64xH_Default; - gt_objects = Kernels::Waterfill::find_objects_inplace( - static_cast(gt_matrix_ib).get(), - min_area - ); - gt_computed = true; - } -#endif - if (gt_computed == false){ - using Waterfill_64x4_Default = Kernels::Waterfill::Waterfill_64xH_Default; - gt_objects = Kernels::Waterfill::find_objects_inplace( - static_cast(gt_matrix_ib).get(), - min_area - ); - } - cout << "num objects: " << gt_objects.size() << endl; - - auto time_start = current_time(); - std::vector objects = Kernels::Waterfill::find_objects_inplace(matrix, min_area); - auto time_end = current_time(); - auto ns = std::chrono::duration_cast(time_end - time_start).count(); - auto ms = ns / 1000000.; - cout << "One waterfill time: " << ms << " ms" << endl; - - for(size_t i = 0; i < objects.size(); ++i){ - TEST_RESULT_COMPONENT_EQUAL(objects[i].area, gt_objects[i].area, "object " + std::to_string(i) + " area"); - TEST_RESULT_COMPONENT_EQUAL(objects[i].min_x, gt_objects[i].min_x, "object " + std::to_string(i) + " min_x"); - TEST_RESULT_COMPONENT_EQUAL(objects[i].min_y, gt_objects[i].min_y, "object " + std::to_string(i) + " min_y"); - TEST_RESULT_COMPONENT_EQUAL(objects[i].max_x, gt_objects[i].max_x, "object " + std::to_string(i) + " max_x"); - TEST_RESULT_COMPONENT_EQUAL(objects[i].max_y, gt_objects[i].max_y, "object " + std::to_string(i) + " max_y"); - } - - // We try to wait for three seconds: - const size_t num_iters = size_t(3000 / ms); - time_start = current_time(); - for(size_t i = 0; i < num_iters; i++){ - matrix = source_matrix.copy(); - objects = Kernels::Waterfill::find_objects_inplace(matrix, min_area); - } - time_end = current_time(); - ms = (double)std::chrono::duration_cast(time_end - time_start).count(); - cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; - - - - return 0; -} - -// Additional tests on binary matrix tile implementation -template int test_binary_matrix_tile_t(){ - size_t num_iters = 100000; - size_t sum = 0; - WallClock time_start, time_end; - size_t ns = 0; - double ms = 0; - - Tile tile; - // BinaryTile_64x8_arm64_NEON tile; - // BinaryTile_64xH_Default<8, BinaryMatrixType::arm64x8_x64_NEON> tile; - for(size_t height = 0; height < tile.HEIGHT; ++height){ - for(size_t width = 0; width < tile.WIDTH; ++width){ - tile.set_zero(); - tile.set_ones(width, height); - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - bool gt = y < height && x < width; - if (gt != tile.get_bit(x, y)){ - cout << "Tile::set_ones(width = " << width << ", height = " << height << "), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be " << gt << endl; - return 1; - } - } - } - } - } - - sum = 0; - time_start = current_time(); - for(size_t i = 0; i < num_iters; ++i){ - tile.set_ones(32, 4); - sum += tile.row(0) + tile.row(1) + tile.row(2) + tile.row(3); - } - time_end = current_time(); - ns = std::chrono::duration_cast(time_end - time_start).count(); - ms = ns / 1000000.; - cout << "Execution enforcer: " << sum << endl; - cout << "Running " << num_iters << " iters, Tile::set_ones() time: " << ms / num_iters << " ms" << endl; - - for(size_t height = 0; height < tile.HEIGHT; ++height){ - for(size_t width = 0; width < tile.WIDTH; ++width){ - tile.set_ones(); - tile.clear_padding(width, height); - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - bool gt = y < height && x < width; - if (gt != tile.get_bit(x, y)){ - cout << "Tile::clear_padding(width = " << width << ", height = " << height << "), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be " << gt << endl; - return 1; - } - } - } - } - } - sum = 0; - time_start = current_time(); - for(size_t i = 0; i < num_iters; ++i){ - tile.clear_padding(32, 4); - sum += tile.row(0) + tile.row(1) + tile.row(2) + tile.row(3); - } - time_end = current_time(); - ns = std::chrono::duration_cast(time_end - time_start).count(); - ms = ns / 1000000.; - cout << "Execution enforcer: " << sum << endl; - cout << "Running " << num_iters << " iters, Tile::clear_padding() time: " << ms / num_iters << " ms" << endl; - - tile.set_ones(35, 3); - tile.invert(); - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - bool gt = !(x < 35 && y < 3); - if (gt != tile.get_bit(x, y)){ - cout << "Tile::invert(), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be " << gt << endl; - return 1; - } - } - } - - auto tile2 = tile; - tile.set_ones(35, 3); - tile2.set_ones(13, 6); - tile.andnot(tile2); - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - bool gt = !(x < 13 && y < 6) && (x < 35 && y < 3); - if (gt != tile.get_bit(x, y)){ - cout << "Tile::andnot(), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be " << gt << endl; - return 1; - } - } - } - - tile.set_ones(35, 3); - { - uint64_t top_row = tile.top(); - for(size_t x = 0; x < tile.WIDTH; ++x){ - uint64_t bit = ((top_row >> x) & 1); - uint64_t gt = uint64_t(x < 35); - if (bit != gt){ - cout << "Tile::top(), tile (x = " << - x << "), wrong bit. Should be " << gt << endl; - return 1; - } - } - } - { - tile.set_zero(); - uint64_t& top_row = tile.top(); - top_row = 0xFFFFFFFFFFFFFFFF; - uint64_t top = tile.top(); - for(size_t x = 0; x < tile.WIDTH; ++x){ - uint64_t bit = ((top >> x) & 1); - if (bit != 1){ - cout << "& Tile::top(), tile (x = " << - x << "), wrong bit. Should be 1" << endl; - return 1; - } - } - } - { - tile.set_zero(); - uint64_t& bottom_row = tile.bottom(); - bottom_row = 0xFFFFFFFFFFFFFFFF; - uint64_t bottom = tile.bottom(); - for(size_t x = 0; x < tile.WIDTH; ++x){ - uint64_t bit = ((bottom >> x) & 1); - if (bit != 1){ - cout << "& Tile::bottom(), tile (x = " << - x << "), wrong bit. Should be 1" << endl; - return 1; - } - } - } - tile.set_zero(); - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - tile.set_bit(x, y); - if (1 != tile.get_bit(x, y)){ - cout << "Tile::set_bit(), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be 1" << endl; - return 1; - } - tile.set_bit(x, y, 1); - if (1 != tile.get_bit(x, y)){ - cout << "Tile::set_bit(), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be 1" << endl; - return 1; - } - tile.set_bit(x, y, 0); - if (0 != tile.get_bit(x, y)){ - cout << "Tile::set_bit(), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be 0" << endl; - return 1; - } - } - } - - std::srand(0); - auto src_tile = tile; - auto dst_tile = tile; - for(size_t num_tests = 0; num_tests < 30; ++num_tests){ - src_tile.set_zero(); - dst_tile.set_zero(); - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - src_tile.set_bit(x, y, std::rand() % 2); - dst_tile.set_bit(x, y, std::rand() % 2); - } - } - - auto test_copy_to_shift = [&](size_t shift_x, size_t shift_y, const std::string& function_name, - std::function gt_test, - std::function get_src_bit_test){ - // check against GT - for(size_t y = 0; y < tile.HEIGHT; ++y){ - for(size_t x = 0; x < tile.WIDTH; ++x){ - bool gt = false; - if (gt_test(shift_x, shift_y, x, y)){ - gt = dst_tile.get_bit(x, y) || get_src_bit_test(shift_x, shift_y, x, y); - // cout << "set the source bit with ||" << endl; - }else{ - // cout << "Use the original dest bit" << endl; - gt = dst_tile.get_bit(x, y); - } - if (tile.get_bit(x, y) != gt){ - cout << "Tile::" << function_name << "(shift_x=" << shift_x << ", shift_y=" << shift_y << "), tile (x = " << - x << ", y = " << y << "), wrong bit. Should be " << gt << endl; - cout << src_tile.dump() << endl; - cout << dst_tile.dump() << endl; - cout << tile.dump() << endl; - return 1; - } - } - } - return 0; - }; - - for(size_t shift_y = 0; shift_y < tile.HEIGHT; ++shift_y){ - for(size_t shift_x = 0; shift_x < tile.WIDTH; ++shift_x){ - tile = dst_tile; - src_tile.copy_to_shift_pp(tile, shift_x, shift_y); - auto gt_test_pp = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ - return x + shift_x < tile.WIDTH && y + shift_y < tile.HEIGHT; - }; - auto get_src_bit_test_pp = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ - return src_tile.get_bit(x + shift_x, y + shift_y); - }; - if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_pp", gt_test_pp, get_src_bit_test_pp) != 0){ - return 1; - } - - tile = dst_tile; - src_tile.copy_to_shift_np(tile, shift_x, shift_y); - auto gt_test_np = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ - return x >= shift_x && y + shift_y < tile.HEIGHT; - }; - auto get_src_bit_test_np = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ - return src_tile.get_bit(x - shift_x, y + shift_y); - }; - if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_np", gt_test_np, get_src_bit_test_np) != 0){ - return 1; - } - - tile = dst_tile; - src_tile.copy_to_shift_pn(tile, shift_x, shift_y); - auto gt_test_pn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ - return x + shift_x < tile.WIDTH && y >= shift_y; - }; - auto get_src_bit_test_pn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ - return src_tile.get_bit(x + shift_x, y - shift_y); - }; - if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_pn", gt_test_pn, get_src_bit_test_pn) != 0){ - return 1; - } - - tile = dst_tile; - src_tile.copy_to_shift_nn(tile, shift_x, shift_y); - auto gt_test_nn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ - return x >= shift_x && y >= shift_y; - }; - auto get_src_bit_test_nn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ - return src_tile.get_bit(x - shift_x, y - shift_y); - }; - if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_nn", gt_test_nn, get_src_bit_test_nn) != 0){ - return 1; - } - } - } - } - - cout << "Tile tests passed" << endl; - return 0; -} - -int test_binary_matrix_tile(){ -#ifdef PA_AutoDispatch_arm64_20_M1 - if (test_binary_matrix_tile_t() != 0){ - return 1; - } - - for(size_t num_bytes = 0; num_bytes <= 16; ++num_bytes){ - PartialWordAccess_arm64_NEON partial(num_bytes); - - uint8_t buffer[48]; - for(int i = 0; i < 48; i++){ - buffer[i] = 99; - } - for(uint8_t i = 0; i < 16; i++){ - buffer[i+16] = i; - } - - // uint8x16_t x = partial.load(buffer+16); - uint8x16_t x = partial.load_int_no_read_past_end(buffer+16); - for(size_t i = 0; i < num_bytes; ++i){ - if (x[i] != buffer[i+16]){ - cout << "Error: PartialWordAccess_arm64_NEON(" << num_bytes << ")::load_int_no_read_past_end(), i = " << i << " is " << int(x[i]) - << ", but should be " << int(buffer[i+16]) << endl; - return 1; - } - } - x = partial.load_int_no_read_before_ptr(buffer+16); - for(size_t i = 0; i < num_bytes; ++i){ - if (x[i] != buffer[i+16]){ - cout << "Error: PartialWordAccess_arm64_NEON(" << num_bytes << ")::load_int_no_read_before_ptr(), i = " << i << " is " << int(x[i]) - << ", but should be " << int(buffer[i+16]) << endl; - return 1; - } - } - for(int i = 0; i < 48; i++){ - buffer[i] = 99; - } - partial.store_int_no_past_end(buffer+16, x); - for(size_t i = 0; i < num_bytes; ++i){ - if (x[i] != buffer[i+16]){ - cout << "Error: PartialWordAccess_arm64_NEON(" << num_bytes << ")::store_int_no_past_end(), i = " << i << " is " << int(buffer[i+16]) - << ", but should be " << int(x[i+16]) << endl; - return 1; - } - } - } -#endif - return 0; -} - -} +/* Kernels Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "Common/Compiler.h" +#include "Common/Cpp/Color.h" +#include "Common/Cpp/CpuId/CpuId.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/BinaryImage.h" +#include "CommonFramework/ImageTools/ImageBoxes.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix.h" +#ifdef PA_AutoDispatch_arm64_20_M1 + #include "Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x8_arm64_NEON.h" + #include "Kernels/PartialWordAccess/Kernels_PartialWordAccess_arm64_NEON.h" + #include "Kernels/Waterfill/Kernels_Waterfill_Core_64x8_arm64_NEON.h" +#endif +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrix_Arch_64xH_Default.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64x4_Default.h" +#include "Kernels/BinaryMatrix/Kernels_BinaryMatrixTile_64xH_Default.h" +#include "Kernels/BinaryImageFilters/Kernels_BinaryImage_BasicFilters.h" +#include "Kernels/ImageFilters/Kernels_ImageFilter_Basic.h" +#include "Kernels/ImageFilters/RGB32_Range/Kernels_ImageFilter_RGB32_Range.h" +#include "Kernels/ImageFilters/RGB32_EuclideanDistance/Kernels_ImageFilter_RGB32_Euclidean.h" +#include "Kernels/ImageScaleBrightness/Kernels_ImageScaleBrightness.h" +#include "Kernels/Waterfill/Kernels_Waterfill.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Session.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Core_64xH_Default.h" +#include "Kernels/Waterfill/Kernels_Waterfill_Routines.h" +#include "Kernels_Tests.h" +#include "TestUtils.h" + +#include +#include +using std::cout; +using std::cerr; +using std::endl; +using std::flush; + +namespace PokemonAutomation{ + +using namespace Kernels; + +namespace Kernels{} + +namespace{ + + + +} + +int test_binary_matrix_tile(); + + +int test_kernels_ImageScaleBrightness(const ImageViewRGB32& image){ + ImageRGB32 new_image = image.copy(); + + int num_iterations = 500; + auto time_start = current_time(); + for(int i = 0; i < num_iterations; i++){ + scale_brightness(new_image.width(), new_image.height(), new_image.data(), new_image.bytes_per_row(), 1.2f, 1.3f, 0.5f); + // break; + } + auto time_end = current_time(); + const auto ms = std::chrono::duration_cast(time_end - time_start).count(); + cout << "Time: " << ms << " ms, " << ms / 1000. << " s" << endl; + + // new_image.save("./output.png"); + + return 0; +} + + +int test_kernels_BinaryMatrix(const ImageViewRGB32& image){ + + if (test_binary_matrix_tile() != 0){ + return 1; + } + + const size_t width = image.width(), height = image.height(); + + const Color min_color(0, 0, 0), max_color(63, 63, 63); + const uint32_t mins = uint32_t(min_color), maxs = uint32_t(max_color); + + auto binary_matrix = make_PackedBinaryMatrix(get_BinaryMatrixType(), width, height); + + auto time_start = current_time(); + compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), *binary_matrix, mins, maxs + ); + auto time_end = current_time(); + size_t ns = std::chrono::duration_cast(time_end - time_start).count(); + double ms = ns / 1000000.; + cout << "One binary matrix creation. time: " << ms << " ms" << endl; + + size_t error_count = 0; + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + const Color color(image.pixel(x, y)); + bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); + in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); + in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); + in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); + + const bool v_default = binary_matrix->get(x, y); + + if (error_count < 10){ + if (v_default != in_range){ + cout << "Error: matrix (" << x << ", " << y << ") got " + << v_default << " but GT is " << in_range << endl; + ++error_count; + } + } + } + } + if (error_count){ + return 1; + } + + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), *binary_matrix, mins, maxs + ); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, average creation impl. time: " << ms / (double)num_iters << " ms" << endl; + + // cout << binary_matrix->dump() << flush; + + return 0; +} + +int test_kernels_FilterRGB32Range(const ImageViewRGB32& image){ + const size_t width = image.width(), height = image.height(); + cout << "Testing filter_rgb32_range(), image size " << width << " x " << height << endl; + + Color min_color(0, 0, 0); + Color max_color(63, 63, 63); + // Color max_color(238, 24, 42); + + const uint32_t mins = uint32_t(min_color); + const uint32_t maxs = uint32_t(max_color); + + ImageRGB32 image_out(image.width(), image.height()); + ImageRGB32 image_out_2(image.width(), image.height()); + size_t pixels_in_range = 0; + + const bool replace_color_within_range = true; + auto time_start = current_time(); + // auto new_image = filter_rgb32_range(image, mins, maxs, COLOR_WHITE, replace_color_within_range); + pixels_in_range = Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out.data(), image_out.bytes_per_row(), + (uint32_t)COLOR_WHITE, replace_color_within_range, + mins, maxs + ); + auto time_end = current_time(); + auto ns = std::chrono::duration_cast(time_end - time_start).count(); + auto ms = ns / 1000000.; + cout << "One filter time: " << ms << " ms" << endl; + + size_t pixels_in_range_2 = Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out_2.data(), image_out_2.bytes_per_row(), + (uint32_t)COLOR_WHITE, !replace_color_within_range, + mins, maxs + ); + + TEST_RESULT_EQUAL(pixels_in_range, pixels_in_range_2); + + size_t actual_num_pixels_in_range = 0; + size_t error_count = 0; + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + const Color color(image.pixel(x, y)); + const Color new_color(image_out.pixel(x, y)); + const Color new_color_2(image_out_2.pixel(x, y)); + bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); + in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); + in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); + in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); + actual_num_pixels_in_range += in_range; + if (error_count < 10){ + // Print first 10 errors: + if (in_range && new_color != COLOR_WHITE){ + cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be in range but not found by the function" << endl; + ++error_count; + }else if (in_range == false && new_color != color){ + cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should not be changed by the function" << endl; + ++error_count; + } + + if (in_range && new_color_2 != color){ + cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should not be changed by the function" << endl; + ++error_count; + }else if (in_range == false && new_color_2 != COLOR_WHITE){ + cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should not be in range but not found by the function" << endl; + ++error_count; + } + } + } + } + cout << "Found " << actual_num_pixels_in_range << " pixels in range" << endl; + if (pixels_in_range != actual_num_pixels_in_range){ + cout << "Error: wrong pixels in range: " << pixels_in_range << " actual: " << actual_num_pixels_in_range << endl; + return 1; + } + + if (error_count){ + return 1; + } + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + Kernels::filter_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out.data(), image_out.bytes_per_row(), + (uint32_t)COLOR_WHITE, replace_color_within_range, + mins, maxs + ); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; + + return 0; +} + + +int test_kernels_FilterRGB32Euclidean(const ImageViewRGB32& image){ + const size_t width = image.width(); + const size_t height = image.height(); + cout << "Testing test_kernels_FilterRGB32Euclidean(), image size " << width << " x " << height << endl; + + Color middle_color = Color(image.pixel(width/2, height/2)); + cout << "Expected color: " << middle_color.to_string() << endl; + + double max_dist = 50.0; + size_t max_dist2 = size_t(max_dist * max_dist); + + ImageRGB32 image_out(image.width(), image.height()); + ImageRGB32 image_out_2(image.width(), image.height()); + size_t pixels_in_range = 0; + + const bool replace_color_within_range = true; + auto time_start = current_time(); + pixels_in_range = Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out.data(), image_out.bytes_per_row(), + (uint32_t)COLOR_WHITE, replace_color_within_range, + uint32_t(middle_color), max_dist + ); + auto time_end = current_time(); + auto ns = std::chrono::duration_cast(time_end - time_start).count(); + auto ms = ns / 1000000.; + cout << "One filter time: " << ms << " ms" << endl; + + size_t pixels_in_range_2 = Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out_2.data(), image_out_2.bytes_per_row(), + (uint32_t)COLOR_WHITE, !replace_color_within_range, + uint32_t(middle_color), max_dist + ); + + TEST_RESULT_EQUAL(pixels_in_range, pixels_in_range_2); + + size_t actual_num_pixels_in_range = 0; + size_t error_count = 0; + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + const Color color(image.pixel(x, y)); + const Color new_color(image_out.pixel(x, y)); + const Color new_color_2(image_out_2.pixel(x, y)); + int red_dif = (color.red() - middle_color.red()); + int green_dif = (color.green() - middle_color.green()); + int blue_dif = (color.blue() - middle_color.blue()); + size_t color_dist2 = red_dif * red_dif + green_dif * green_dif + blue_dif * blue_dif; + bool in_range = color_dist2 <= max_dist2; + actual_num_pixels_in_range += in_range; + if (error_count < 10){ + // Print first 10 errors: + if (in_range && new_color != COLOR_WHITE){ + cout << "Error: wrong filter result: old color " << color.to_string() + << ", (x,y) = (" << x << ", " << y << ")" + << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 + << ", should be in range but not found by the function" << endl; + ++error_count; + }else if (in_range == false && new_color != color){ + cout << "Error: wrong filter result: old color " << color.to_string() + << ", (x,y) = (" << x << ", " << y << ")" + << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 + << ", should not be changed by the function" << endl; + ++error_count; + } + + if (in_range && new_color_2 != color){ + cout << "Error: wrong inverse filter result: old color " << color.to_string() + << ", (x,y) = (" << x << ", " << y << ")" + << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 + << ", should not be changed by the function" << endl; + ++error_count; + }else if (in_range == false && new_color_2 != COLOR_WHITE){ + cout << "Error: wrong inverse filter result: old color " << color.to_string() + << ", (x,y) = (" << x << ", " << y << ")" + << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 + << ", should not be in range but not found by the function" << endl; + ++error_count; + } + } + } + } + cout << "Found " << actual_num_pixels_in_range << " pixels in range" << endl; + if (pixels_in_range != actual_num_pixels_in_range){ + cout << "Error: wrong pixels in range: " << pixels_in_range << " actual: " << actual_num_pixels_in_range << endl; + return 1; + } + + if (error_count){ + return 1; + } + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + pixels_in_range = Kernels::filter_rgb32_euclidean( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out.data(), image_out.bytes_per_row(), + (uint32_t)COLOR_WHITE, replace_color_within_range, + uint32_t(middle_color), max_dist + ); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; + + return 0; +} + +int test_kernels_ToBlackWhiteRGB32Range(const ImageViewRGB32& image){ + const size_t width = image.width(); + const size_t height = image.height(); + cout << "Testing to_black_white_rgb32_range(), image size " << width << " x " << height << endl; + + Color min_color(0, 0, 0); + // Color min_color(0); + + Color max_color(63, 63, 63); + // Color max_color(255, 255, 255); + // Color max_color(238, 24, 42); + cout << "min color: " << min_color.to_string() << " max color: " << max_color.to_string() << endl; + + const uint32_t mins = uint32_t(min_color); + const uint32_t maxs = uint32_t(max_color); + + ImageRGB32 image_out(image.width(), image.height()); + ImageRGB32 image_out_2(image.width(), image.height()); + size_t pixels_in_range = 0; + + const bool in_range_black = true; + auto time_start = current_time(); + // auto new_image = filter_rgb32_range(image, mins, maxs, COLOR_WHITE, replace_color_within_range); + pixels_in_range = Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out.data(), image_out.bytes_per_row(), + in_range_black, + mins, maxs + ); + auto time_end = current_time(); + auto ns = std::chrono::duration_cast(time_end - time_start).count(); + auto ms = ns / 1000000.; + cout << "One filter time: " << ms << " ms" << endl; + + size_t pixels_in_range_2 = Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out_2.data(), image_out_2.bytes_per_row(), + !in_range_black, + mins, maxs + ); + + TEST_RESULT_EQUAL(pixels_in_range, pixels_in_range_2); + + size_t actual_num_pixels_in_range = 0; + size_t error_count = 0; + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + const Color color(image.pixel(x, y)); + const Color new_color(image_out.pixel(x, y)); + const Color new_color_2(image_out_2.pixel(x, y)); + bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); + in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); + in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); + in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); + actual_num_pixels_in_range += in_range; + if (error_count < 10){ + // Print first 10 errors: + if (in_range && new_color != COLOR_BLACK){ + cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be black due to in range but not so" << endl; + ++error_count; + }else if (in_range == false && new_color != COLOR_WHITE){ + cout << "Error: wrong filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be white due to out of range but not so" << endl; + ++error_count; + } + + if (in_range && new_color_2 != COLOR_WHITE){ + cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be white due to in range but not so" << endl; + ++error_count; + }else if (in_range == false && new_color_2 != COLOR_BLACK){ + cout << "Error: wrong inverse filter result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be black due to out of range but not so" << endl; + ++error_count; + } + } + } + } + cout << "Found " << actual_num_pixels_in_range << " pixels in range" << endl; + if (pixels_in_range != actual_num_pixels_in_range){ + cout << "Error: wrong pixels in range: " << pixels_in_range << " actual: " << actual_num_pixels_in_range << endl; + return 1; + } + + if (error_count){ + return 1; + } + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + Kernels::to_blackwhite_rgb32_range( + image.data(), image.bytes_per_row(), image.width(), image.height(), + image_out.data(), image_out.bytes_per_row(), + in_range_black, + mins, maxs + ); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; + + return 0; +} + +int test_kernels_FilterByMask(const ImageViewRGB32& image){ + const size_t width = image.width(), height = image.height(); + cout << "Image width " << width << " height " << height << endl; + + const Color min_color(0, 0, 0), max_color(63, 63, 63); + const uint32_t mins = uint32_t(min_color), maxs = uint32_t(max_color); + + auto binary_matrix = make_PackedBinaryMatrix(get_BinaryMatrixType(), width, height); + compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), *binary_matrix, mins, maxs + ); + ImageRGB32 new_image = image.copy(); + ImageRGB32 new_image_2 = image.copy(); + + Color replacement_color = COLOR_WHITE; + bool replace_zero_bits = true; + + auto time_start = current_time(); + filter_by_mask(*binary_matrix, new_image.data(), new_image.bytes_per_row(), uint32_t(replacement_color), replace_zero_bits); + auto time_end = current_time(); + auto ns = std::chrono::duration_cast(time_end - time_start).count(); + auto ms = ns / 1000000.; + cout << "One Filter by mask call. time: " << ms << " ms" << endl; + + filter_by_mask(*binary_matrix, new_image_2.data(), new_image_2.bytes_per_row(), uint32_t(replacement_color), !replace_zero_bits); + + size_t error_count = 0; + + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + const Color color(image.pixel(x, y)); + const Color new_color(new_image.pixel(x, y)); + const Color new_color_2(new_image_2.pixel(x, y)); + bool in_range = (min_color.alpha() <= color.alpha() && color.alpha() <= max_color.alpha()); + in_range = in_range && (min_color.red() <= color.red() && color.red() <= max_color.red()); + in_range = in_range && (min_color.green() <= color.green() && color.green() <= max_color.green()); + in_range = in_range && (min_color.blue() <= color.blue() && color.blue() <= max_color.blue()); + + if (error_count <= 10){ + if (in_range && new_color != color){ + cout << "Error: wrong filter(replace_zero_bits) result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should not be changed due to being one bit but not so" << endl; + ++error_count; + }else if (!in_range && new_color != replacement_color){ + cout << "Error: wrong filter(replace_zero_bits) result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be changed due to being zero bit but not so" << endl; + ++error_count; + } + + if (in_range && new_color_2 != replacement_color){ + cout << "Error: wrong filter(replace_one_bits) result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should be changed due to being one bit but not so" << endl; + ++error_count; + }else if (!in_range && new_color_2 != color){ + cout << "Error: wrong filter(replace_one_bits) result: old color " << color.to_string() << ", (x,y) = " + << x << ", " << y << ", should not be changed due to being zero bit but not so" << endl; + ++error_count; + } + } + } + } + + if (error_count){ + return 1; + } + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + filter_by_mask(*binary_matrix, new_image.data(), new_image.bytes_per_row(), uint32_t(replacement_color), replace_zero_bits); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; + + return 0; +} + +int test_kernels_CompressRGB32ToBinaryEuclidean(const ImageViewRGB32& image){ + const size_t width = image.width(); + const size_t height = image.height(); + cout << "Testing test_kernels_CompressRGB32ToBinaryEuclidean(), image size " << width << " x " << height << endl; + + Color middle_color = Color(image.pixel(width/2, height/2)); + cout << "Expected color: " << middle_color.to_string() << endl; + + double max_dist = 50.0; + size_t max_dist2 = size_t(max_dist * max_dist); + + PackedBinaryMatrix matrix(image.width(), image.height()); + + auto time_start = current_time(); + Kernels::compress_rgb32_to_binary_euclidean( + image.data(), image.bytes_per_row(), matrix, + uint32_t(middle_color), max_dist + ); + auto time_end = current_time(); + auto ns = std::chrono::duration_cast(time_end - time_start).count(); + auto ms = ns / 1000000.; + cout << "One filter time: " << ms << " ms" << endl; + + size_t error_count = 0; + for (size_t y = 0; y < height; y++){ + for (size_t x = 0; x < width; x++){ + const Color color(image.pixel(x, y)); + int red_dif = (color.red() - middle_color.red()); + int green_dif = (color.green() - middle_color.green()); + int blue_dif = (color.blue() - middle_color.blue()); + size_t color_dist2 = red_dif * red_dif + green_dif * green_dif + blue_dif * blue_dif; + bool in_range = color_dist2 <= max_dist2; + if (error_count < 10){ + // Print first 10 errors: + if (in_range && matrix.get(x, y) == false){ + cout << "Error: wrong filter result: old color " << color.to_string() + << ", (x,y) = (" << x << ", " << y << ")" + << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 + << ", should be in range but not set on matrix" << endl; + ++error_count; + }else if (in_range == false && matrix.get(x, y) == true){ + cout << "Error: wrong filter result: old color " << color.to_string() + << ", (x,y) = (" << x << ", " << y << ")" + << ", dist2 " << color_dist2 << ", max dist2 " << max_dist2 + << ", should not be in range but set on matrix" << endl; + ++error_count; + } + } + } + } + if (error_count){ + return 1; + } + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + Kernels::compress_rgb32_to_binary_euclidean( + image.data(), image.bytes_per_row(), matrix, + uint32_t(middle_color), max_dist + ); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; + + return 0; +} + + + + +int test_kernels_Waterfill(const ImageViewRGB32& image){ + const size_t width = image.width(); + const size_t height = image.height(); + cout << "Testing test_kernels_Waterfill(), image size " << width << " x " << height << endl; + + PackedBinaryMatrix matrix(width, height); + uint32_t mins = combine_rgb(0, 0, 0); + // uint32_t maxs = combine_rgb(255, 255, 255); + uint32_t maxs = combine_rgb(63, 63, 63); + Kernels::compress_rgb32_to_binary_range( + image.data(), image.bytes_per_row(), + matrix, mins, maxs + ); + + PackedBinaryMatrix source_matrix = matrix.copy(); + + PackedBinaryMatrix gt_matrix = matrix.copy(); + Kernels::PackedBinaryMatrix_IB& gt_matrix_ib = gt_matrix; + + size_t min_area = 10; + std::vector gt_objects; + bool gt_computed = false; + +#ifdef PA_AutoDispatch_arm64_20_M1 + if (CPU_CAPABILITY_CURRENT.OK_M1){ + using Waterfill_64x8_Default = Kernels::Waterfill::Waterfill_64xH_Default; + gt_objects = Kernels::Waterfill::find_objects_inplace( + static_cast(gt_matrix_ib).get(), + min_area + ); + gt_computed = true; + } +#endif + if (gt_computed == false){ + using Waterfill_64x4_Default = Kernels::Waterfill::Waterfill_64xH_Default; + gt_objects = Kernels::Waterfill::find_objects_inplace( + static_cast(gt_matrix_ib).get(), + min_area + ); + } + cout << "num objects: " << gt_objects.size() << endl; + + auto time_start = current_time(); + std::vector objects = Kernels::Waterfill::find_objects_inplace(matrix, min_area); + auto time_end = current_time(); + auto ns = std::chrono::duration_cast(time_end - time_start).count(); + auto ms = ns / 1000000.; + cout << "One waterfill time: " << ms << " ms" << endl; + + for(size_t i = 0; i < objects.size(); ++i){ + TEST_RESULT_COMPONENT_EQUAL(objects[i].area, gt_objects[i].area, "object " + std::to_string(i) + " area"); + TEST_RESULT_COMPONENT_EQUAL(objects[i].min_x, gt_objects[i].min_x, "object " + std::to_string(i) + " min_x"); + TEST_RESULT_COMPONENT_EQUAL(objects[i].min_y, gt_objects[i].min_y, "object " + std::to_string(i) + " min_y"); + TEST_RESULT_COMPONENT_EQUAL(objects[i].max_x, gt_objects[i].max_x, "object " + std::to_string(i) + " max_x"); + TEST_RESULT_COMPONENT_EQUAL(objects[i].max_y, gt_objects[i].max_y, "object " + std::to_string(i) + " max_y"); + } + + // We try to wait for three seconds: + const size_t num_iters = size_t(3000 / ms); + time_start = current_time(); + for(size_t i = 0; i < num_iters; i++){ + matrix = source_matrix.copy(); + objects = Kernels::Waterfill::find_objects_inplace(matrix, min_area); + } + time_end = current_time(); + ms = (double)std::chrono::duration_cast(time_end - time_start).count(); + cout << "Running " << num_iters << " iters, avg filter time: " << ms / num_iters << " ms" << endl; + + + + return 0; +} + +// Additional tests on binary matrix tile implementation +template int test_binary_matrix_tile_t(){ + size_t num_iters = 100000; + size_t sum = 0; + WallClock time_start, time_end; + size_t ns = 0; + double ms = 0; + + Tile tile; + // BinaryTile_64x8_arm64_NEON tile; + // BinaryTile_64xH_Default<8, BinaryMatrixType::arm64x8_x64_NEON> tile; + for(size_t height = 0; height < tile.HEIGHT; ++height){ + for(size_t width = 0; width < tile.WIDTH; ++width){ + tile.set_zero(); + tile.set_ones(width, height); + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + bool gt = y < height && x < width; + if (gt != tile.get_bit(x, y)){ + cout << "Tile::set_ones(width = " << width << ", height = " << height << "), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be " << gt << endl; + return 1; + } + } + } + } + } + + sum = 0; + time_start = current_time(); + for(size_t i = 0; i < num_iters; ++i){ + tile.set_ones(32, 4); + sum += tile.row(0) + tile.row(1) + tile.row(2) + tile.row(3); + } + time_end = current_time(); + ns = std::chrono::duration_cast(time_end - time_start).count(); + ms = ns / 1000000.; + cout << "Execution enforcer: " << sum << endl; + cout << "Running " << num_iters << " iters, Tile::set_ones() time: " << ms / num_iters << " ms" << endl; + + for(size_t height = 0; height < tile.HEIGHT; ++height){ + for(size_t width = 0; width < tile.WIDTH; ++width){ + tile.set_ones(); + tile.clear_padding(width, height); + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + bool gt = y < height && x < width; + if (gt != tile.get_bit(x, y)){ + cout << "Tile::clear_padding(width = " << width << ", height = " << height << "), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be " << gt << endl; + return 1; + } + } + } + } + } + sum = 0; + time_start = current_time(); + for(size_t i = 0; i < num_iters; ++i){ + tile.clear_padding(32, 4); + sum += tile.row(0) + tile.row(1) + tile.row(2) + tile.row(3); + } + time_end = current_time(); + ns = std::chrono::duration_cast(time_end - time_start).count(); + ms = ns / 1000000.; + cout << "Execution enforcer: " << sum << endl; + cout << "Running " << num_iters << " iters, Tile::clear_padding() time: " << ms / num_iters << " ms" << endl; + + tile.set_ones(35, 3); + tile.invert(); + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + bool gt = !(x < 35 && y < 3); + if (gt != tile.get_bit(x, y)){ + cout << "Tile::invert(), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be " << gt << endl; + return 1; + } + } + } + + auto tile2 = tile; + tile.set_ones(35, 3); + tile2.set_ones(13, 6); + tile.andnot(tile2); + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + bool gt = !(x < 13 && y < 6) && (x < 35 && y < 3); + if (gt != tile.get_bit(x, y)){ + cout << "Tile::andnot(), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be " << gt << endl; + return 1; + } + } + } + + tile.set_ones(35, 3); + { + uint64_t top_row = tile.top(); + for(size_t x = 0; x < tile.WIDTH; ++x){ + uint64_t bit = ((top_row >> x) & 1); + uint64_t gt = uint64_t(x < 35); + if (bit != gt){ + cout << "Tile::top(), tile (x = " << + x << "), wrong bit. Should be " << gt << endl; + return 1; + } + } + } + { + tile.set_zero(); + uint64_t& top_row = tile.top(); + top_row = 0xFFFFFFFFFFFFFFFF; + uint64_t top = tile.top(); + for(size_t x = 0; x < tile.WIDTH; ++x){ + uint64_t bit = ((top >> x) & 1); + if (bit != 1){ + cout << "& Tile::top(), tile (x = " << + x << "), wrong bit. Should be 1" << endl; + return 1; + } + } + } + { + tile.set_zero(); + uint64_t& bottom_row = tile.bottom(); + bottom_row = 0xFFFFFFFFFFFFFFFF; + uint64_t bottom = tile.bottom(); + for(size_t x = 0; x < tile.WIDTH; ++x){ + uint64_t bit = ((bottom >> x) & 1); + if (bit != 1){ + cout << "& Tile::bottom(), tile (x = " << + x << "), wrong bit. Should be 1" << endl; + return 1; + } + } + } + tile.set_zero(); + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + tile.set_bit(x, y); + if (1 != tile.get_bit(x, y)){ + cout << "Tile::set_bit(), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be 1" << endl; + return 1; + } + tile.set_bit(x, y, 1); + if (1 != tile.get_bit(x, y)){ + cout << "Tile::set_bit(), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be 1" << endl; + return 1; + } + tile.set_bit(x, y, 0); + if (0 != tile.get_bit(x, y)){ + cout << "Tile::set_bit(), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be 0" << endl; + return 1; + } + } + } + + std::srand(0); + auto src_tile = tile; + auto dst_tile = tile; + for(size_t num_tests = 0; num_tests < 30; ++num_tests){ + src_tile.set_zero(); + dst_tile.set_zero(); + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + src_tile.set_bit(x, y, std::rand() % 2); + dst_tile.set_bit(x, y, std::rand() % 2); + } + } + + auto test_copy_to_shift = [&](size_t shift_x, size_t shift_y, const std::string& function_name, + std::function gt_test, + std::function get_src_bit_test){ + // check against GT + for(size_t y = 0; y < tile.HEIGHT; ++y){ + for(size_t x = 0; x < tile.WIDTH; ++x){ + bool gt = false; + if (gt_test(shift_x, shift_y, x, y)){ + gt = dst_tile.get_bit(x, y) || get_src_bit_test(shift_x, shift_y, x, y); + // cout << "set the source bit with ||" << endl; + }else{ + // cout << "Use the original dest bit" << endl; + gt = dst_tile.get_bit(x, y); + } + if (tile.get_bit(x, y) != gt){ + cout << "Tile::" << function_name << "(shift_x=" << shift_x << ", shift_y=" << shift_y << "), tile (x = " << + x << ", y = " << y << "), wrong bit. Should be " << gt << endl; + cout << src_tile.dump() << endl; + cout << dst_tile.dump() << endl; + cout << tile.dump() << endl; + return 1; + } + } + } + return 0; + }; + + for(size_t shift_y = 0; shift_y < tile.HEIGHT; ++shift_y){ + for(size_t shift_x = 0; shift_x < tile.WIDTH; ++shift_x){ + tile = dst_tile; + src_tile.copy_to_shift_pp(tile, shift_x, shift_y); + auto gt_test_pp = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ + return x + shift_x < tile.WIDTH && y + shift_y < tile.HEIGHT; + }; + auto get_src_bit_test_pp = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ + return src_tile.get_bit(x + shift_x, y + shift_y); + }; + if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_pp", gt_test_pp, get_src_bit_test_pp) != 0){ + return 1; + } + + tile = dst_tile; + src_tile.copy_to_shift_np(tile, shift_x, shift_y); + auto gt_test_np = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ + return x >= shift_x && y + shift_y < tile.HEIGHT; + }; + auto get_src_bit_test_np = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ + return src_tile.get_bit(x - shift_x, y + shift_y); + }; + if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_np", gt_test_np, get_src_bit_test_np) != 0){ + return 1; + } + + tile = dst_tile; + src_tile.copy_to_shift_pn(tile, shift_x, shift_y); + auto gt_test_pn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ + return x + shift_x < tile.WIDTH && y >= shift_y; + }; + auto get_src_bit_test_pn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ + return src_tile.get_bit(x + shift_x, y - shift_y); + }; + if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_pn", gt_test_pn, get_src_bit_test_pn) != 0){ + return 1; + } + + tile = dst_tile; + src_tile.copy_to_shift_nn(tile, shift_x, shift_y); + auto gt_test_nn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y) -> bool{ + return x >= shift_x && y >= shift_y; + }; + auto get_src_bit_test_nn = [&](size_t shift_x, size_t shift_y, size_t x, size_t y){ + return src_tile.get_bit(x - shift_x, y - shift_y); + }; + if (test_copy_to_shift(shift_x, shift_y, "copy_to_shift_nn", gt_test_nn, get_src_bit_test_nn) != 0){ + return 1; + } + } + } + } + + cout << "Tile tests passed" << endl; + return 0; +} + +int test_binary_matrix_tile(){ +#ifdef PA_AutoDispatch_arm64_20_M1 + if (test_binary_matrix_tile_t() != 0){ + return 1; + } + + for(size_t num_bytes = 0; num_bytes <= 16; ++num_bytes){ + PartialWordAccess_arm64_NEON partial(num_bytes); + + uint8_t buffer[48]; + for(int i = 0; i < 48; i++){ + buffer[i] = 99; + } + for(uint8_t i = 0; i < 16; i++){ + buffer[i+16] = i; + } + + // uint8x16_t x = partial.load(buffer+16); + uint8x16_t x = partial.load_int_no_read_past_end(buffer+16); + for(size_t i = 0; i < num_bytes; ++i){ + if (x[i] != buffer[i+16]){ + cout << "Error: PartialWordAccess_arm64_NEON(" << num_bytes << ")::load_int_no_read_past_end(), i = " << i << " is " << int(x[i]) + << ", but should be " << int(buffer[i+16]) << endl; + return 1; + } + } + x = partial.load_int_no_read_before_ptr(buffer+16); + for(size_t i = 0; i < num_bytes; ++i){ + if (x[i] != buffer[i+16]){ + cout << "Error: PartialWordAccess_arm64_NEON(" << num_bytes << ")::load_int_no_read_before_ptr(), i = " << i << " is " << int(x[i]) + << ", but should be " << int(buffer[i+16]) << endl; + return 1; + } + } + for(int i = 0; i < 48; i++){ + buffer[i] = 99; + } + partial.store_int_no_past_end(buffer+16, x); + for(size_t i = 0; i < num_bytes; ++i){ + if (x[i] != buffer[i+16]){ + cout << "Error: PartialWordAccess_arm64_NEON(" << num_bytes << ")::store_int_no_past_end(), i = " << i << " is " << int(buffer[i+16]) + << ", but should be " << int(x[i+16]) << endl; + return 1; + } + } + } +#endif + return 0; +} + +} diff --git a/SerialPrograms/Source/Tests/Kernels_Tests.h b/SerialPrograms/Source/Tests/Kernels_Tests.h index 6cf4bd66a3..28f80fe59b 100644 --- a/SerialPrograms/Source/Tests/Kernels_Tests.h +++ b/SerialPrograms/Source/Tests/Kernels_Tests.h @@ -1,37 +1,37 @@ -/* Kernels Tests - * - * From: https://github.com/PokemonAutomation/ - * - * - */ - - -#ifndef PokemonAutomation_Tests_Kernels_Tests_H -#define PokemonAutomation_Tests_Kernels_Tests_H - -namespace PokemonAutomation{ - -class ImageViewRGB32; - -int test_kernels_ImageScaleBrightness(const ImageViewRGB32& image); - -int test_kernels_BinaryMatrix(const ImageViewRGB32& image); - -int test_kernels_FilterRGB32Range(const ImageViewRGB32& image); - -int test_kernels_FilterRGB32Euclidean(const ImageViewRGB32& image); - -int test_kernels_FilterRGB32Euclidean(const ImageViewRGB32& image); - -int test_kernels_ToBlackWhiteRGB32Range(const ImageViewRGB32& image); - -int test_kernels_FilterByMask(const ImageViewRGB32& image); - -int test_kernels_CompressRGB32ToBinaryEuclidean(const ImageViewRGB32& image); - -int test_kernels_Waterfill(const ImageViewRGB32& image); - - -} - -#endif +/* Kernels Tests + * + * From: https://github.com/PokemonAutomation/ + * + * + */ + + +#ifndef PokemonAutomation_Tests_Kernels_Tests_H +#define PokemonAutomation_Tests_Kernels_Tests_H + +namespace PokemonAutomation{ + +class ImageViewRGB32; + +int test_kernels_ImageScaleBrightness(const ImageViewRGB32& image); + +int test_kernels_BinaryMatrix(const ImageViewRGB32& image); + +int test_kernels_FilterRGB32Range(const ImageViewRGB32& image); + +int test_kernels_FilterRGB32Euclidean(const ImageViewRGB32& image); + +int test_kernels_FilterRGB32Euclidean(const ImageViewRGB32& image); + +int test_kernels_ToBlackWhiteRGB32Range(const ImageViewRGB32& image); + +int test_kernels_FilterByMask(const ImageViewRGB32& image); + +int test_kernels_CompressRGB32ToBinaryEuclidean(const ImageViewRGB32& image); + +int test_kernels_Waterfill(const ImageViewRGB32& image); + + +} + +#endif diff --git a/SerialPrograms/Source/Tests/NintendoSwitch_Tests.cpp b/SerialPrograms/Source/Tests/NintendoSwitch_Tests.cpp index fbe872804b..71718f4b50 100644 --- a/SerialPrograms/Source/Tests/NintendoSwitch_Tests.cpp +++ b/SerialPrograms/Source/Tests/NintendoSwitch_Tests.cpp @@ -1,47 +1,47 @@ -/* NintendoSwitch Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "Common/Compiler.h" -#include "Common/Cpp/Time.h" -#include "CommonFramework/ImageTypes/ImageRGB32.h" -#include "CommonFramework/ImageTypes/ImageViewRGB32.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" -#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" -#include "NintendoSwitch_Tests.h" -#include "TestUtils.h" - -#include -using std::cout; -using std::cerr; -using std::endl; - -namespace PokemonAutomation{ - -using namespace NintendoSwitch; - -// using namespace NintendoSwitch::PokemonLA; -int test_NintendoSwitch_UpdatePopupDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - DummyBotBase botbase(logger); - SerialPABotBase::SerialPABotBase_Connection connection(logger, nullptr, {}); - SerialPABotBase_PokkenController controller(logger, connection); - DummyVideoFeed video_feed; - DummyVideoOverlay video_overlay; - DummyAudioFeed audio_feed; - StreamHistorySession history(logger); - - ConsoleHandle console(0, logger, controller, video_feed, video_overlay, audio_feed, history); - UpdatePopupDetector detector(console); - bool result = detector.detect(image); - TEST_RESULT_EQUAL(result, target); - return 0; -} - - - -} +/* NintendoSwitch Tests + * + * From: https://github.com/PokemonAutomation/ + * + */ + + +#include "Common/Compiler.h" +#include "Common/Cpp/Time.h" +#include "CommonFramework/ImageTypes/ImageRGB32.h" +#include "CommonFramework/ImageTypes/ImageViewRGB32.h" +#include "CommonFramework/Recording/StreamHistorySession.h" +#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" +#include "NintendoSwitch/Inference/NintendoSwitch_UpdatePopupDetector.h" +#include "NintendoSwitch_Tests.h" +#include "TestUtils.h" + +#include +using std::cout; +using std::cerr; +using std::endl; + +namespace PokemonAutomation{ + +using namespace NintendoSwitch; + +// using namespace NintendoSwitch::PokemonLA; +int test_NintendoSwitch_UpdatePopupDetector(const ImageViewRGB32& image, bool target){ + auto& logger = global_logger_command_line(); + DummyBotBase botbase(logger); + SerialPABotBase::SerialPABotBase_Connection connection(logger, nullptr, {}); + SerialPABotBase_PokkenController controller(logger, connection); + DummyVideoFeed video_feed; + DummyVideoOverlay video_overlay; + DummyAudioFeed audio_feed; + StreamHistorySession history(logger); + + ConsoleHandle console(0, logger, controller, video_feed, video_overlay, audio_feed, history); + UpdatePopupDetector detector(console); + bool result = detector.detect(image); + TEST_RESULT_EQUAL(result, target); + return 0; +} + + + +} diff --git a/SerialPrograms/Source/Tests/NintendoSwitch_Tests.h b/SerialPrograms/Source/Tests/NintendoSwitch_Tests.h index 684d7a5912..02dff2da1c 100644 --- a/SerialPrograms/Source/Tests/NintendoSwitch_Tests.h +++ b/SerialPrograms/Source/Tests/NintendoSwitch_Tests.h @@ -1,20 +1,20 @@ -/* Nintendo Switch Tests - * - * From: https://github.com/PokemonAutomation/ - * - * - */ - - -#ifndef PokemonAutomation_Tests_NintendoSwitch_Tests_H -#define PokemonAutomation_Tests_NintendoSwitch_Tests_H - -namespace PokemonAutomation{ - -class ImageViewRGB32; - -int test_NintendoSwitch_UpdatePopupDetector(const ImageViewRGB32& image, bool target); - -} - -#endif +/* Nintendo Switch Tests + * + * From: https://github.com/PokemonAutomation/ + * + * + */ + + +#ifndef PokemonAutomation_Tests_NintendoSwitch_Tests_H +#define PokemonAutomation_Tests_NintendoSwitch_Tests_H + +namespace PokemonAutomation{ + +class ImageViewRGB32; + +int test_NintendoSwitch_UpdatePopupDetector(const ImageViewRGB32& image, bool target); + +} + +#endif diff --git a/SerialPrograms/Source/Tests/PokemonLA_Tests.cpp b/SerialPrograms/Source/Tests/PokemonLA_Tests.cpp index 626183d22c..7da621e7fb 100644 --- a/SerialPrograms/Source/Tests/PokemonLA_Tests.cpp +++ b/SerialPrograms/Source/Tests/PokemonLA_Tests.cpp @@ -1,689 +1,689 @@ -/* PokemonLA Tests - * - * From: https://github.com/PokemonAutomation/ - * - */ - - -#include "Common/Compiler.h" -#include "PokemonLA_Tests.h" -#include "TestUtils.h" -#include "CommonFramework/Language.h" -#include "CommonFramework/ImageTools/ImageBoxes.h" -#include "CommonFramework/Recording/StreamHistorySession.h" -#include "Controllers/ControllerCapability.h" -#include "NintendoSwitch/Controllers/SerialPABotBase/NintendoSwitch_SerialPABotBase_PokkenController.h" -#include "NintendoSwitch/NintendoSwitch_ConsoleHandle.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleMenuDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattlePokemonSwitchDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleSpriteWatcher.h" -#include "PokemonLA/Inference/Objects/PokemonLA_DialogueYellowArrowDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_MMOQuestionMarkDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_TransparentDialogueDetector.h" -#include "PokemonLA/Inference/Battles/PokemonLA_BattleStartDetector.h" -#include "PokemonLA/Inference/Objects/PokemonLA_BattleSpriteArrowDetector.h" -#include "PokemonLA/Inference/PokemonLA_BerryTreeDetector.h" -#include "PokemonLA/Inference/PokemonLA_BlackOutDetector.h" -#include "PokemonLA/Inference/PokemonLA_DialogDetector.h" -#include "PokemonLA/Inference/PokemonLA_StatusInfoScreenDetector.h" -#include "PokemonLA/Inference/PokemonLA_WildPokemonFocusDetector.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapMarkerLocator.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapZoomLevelReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapMissionTabReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_MapWeatherAndTimeReader.h" -#include "PokemonLA/Inference/Map/PokemonLA_PokemonMapSpriteReader.h" -#include "PokemonLA/Inference/Objects/PokemonLA_FlagTracker.h" -#include "PokemonLA/Inference/Sounds/PokemonLA_ShinySoundDetector.h" -#include "PokemonLA/Programs/PokemonLA_GameSave.h" -#include "PokemonLA/PokemonLA_Locations.h" -#include "PokemonLA/PokemonLA_WeatherAndTime.h" - -#include -#include -#include -#include -#include -#include -#include -#include -using std::cout; -using std::cerr; -using std::endl; - -namespace PokemonAutomation{ - -using namespace NintendoSwitch; -using namespace NintendoSwitch::PokemonLA; - -int test_pokemonLA_BattleMenuDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const bool stop_on_detected = true; - BattleMenuDetector detector(logger, overlay, stop_on_detected); - - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_BattlePokemonSwitchDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const bool stop_on_detected = true; - BattlePokemonSwitchDetector detector(logger, overlay, stop_on_detected); - - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_TransparentDialogueDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const bool stop_on_detected = true; - TransparentDialogueDetector detector(logger, overlay, stop_on_detected); - - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_EventDialogDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const bool stop_on_detected = true; - EventDialogDetector detector(logger, overlay, stop_on_detected); - - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_DialogueYellowArrowDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const bool stop_on_detected = true; - DialogueYellowArrowDetector detector(logger, overlay, stop_on_detected); - - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_BlackOutDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - - BlackOutDetector detector(logger, overlay); - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_BattleStartDetector(const ImageViewRGB32& image, bool target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - - BattleStartDetector detector(logger, overlay); - bool result = detector.process_frame(image, current_time()); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_MMOQuestionMarkDetector(const ImageViewRGB32& image, const std::vector& keywords){ - bool hisui_kw_found = false; - std::array target_hisui_region_has_MMO = {false}; - - bool region_kw_found = false; - int target_num_MMOs_on_region_map = -1; - int target_region_index = -1; - - for(size_t keyword_index = 0; keyword_index < keywords.size(); keyword_index++){ - const std::string& word = keywords[keyword_index]; - if (hisui_kw_found == false && word == "Hisui"){ - hisui_kw_found = true; - continue; - } - if (region_kw_found == false && word == "Region"){ - region_kw_found = true; - continue; - } - - if (hisui_kw_found){ - // We have found the "Hisui" keyword. So the next words will be the index of the region on the Hisui map - // that has MMO. - try{ - int region = std::stoi(word); - if (region < 0 || region > 4){ - cerr << "Error: wrong region number, must be [0, 4] but got " << region << endl; - return 1; - } - target_hisui_region_has_MMO[region] = true; - } catch(std::exception&){ - cerr << "Error: keyword must be a region number, ranging in [0, 4], but got " << word << endl; - return 1; - } - }else if (region_kw_found){ - // Found "Region" keyword, read a number as how many MMOs on the region map, and a region name. - if (target_region_index < 0){ - for(size_t index = 0; index < 5; index++){ - if (word == WILD_REGION_SHORT_NAMES[index]){ - target_region_index = (int)index; - break; - } - } - if (target_region_index >= 0){ - continue; - } - } - if (target_num_MMOs_on_region_map < 0){ - try{ - int num_MMOs = std::stoi(word); - if (num_MMOs < 0){ - cerr << "Error: wrong number " << num_MMOs << ", must be non-negative" << endl; - return 1; - } - target_num_MMOs_on_region_map = num_MMOs; - } catch(std::exception&){} - } - } - } - - if (hisui_kw_found == false && region_kw_found == false){ - cerr << "Error: need keyword \"Hisui\" or \"Region\" in filename/" << endl; - return 1; - } - - auto& logger = global_logger_command_line(); - MMOQuestionMarkDetector detector(logger); - - if (hisui_kw_found){ - const auto region_has_MMO = detector.detect_MMO_on_hisui_map(image); - - for(size_t i = 0; i < 5; i++){ - const bool result = region_has_MMO[i]; - const bool target = target_hisui_region_has_MMO[i]; - if (result != target){ - cerr << "Error: " << __func__ << " result on region " << i << " is " << result << " but should be " << target << "." << endl; - return 1; - } - } - }else{ // Region keyword found - if (target_region_index < 0 || target_num_MMOs_on_region_map < 0){ - cerr << "Error: need a region name and a number of MMOs in the filename (e.g. image-Fieldlands_5.png)." << endl; - } - const auto results = detector.detect_MMOs_on_region_map(image); - TEST_RESULT_EQUAL((int)results.size(), target_num_MMOs_on_region_map); - } - - return 0; -} - -int read_pokemon_info_from_words(const std::vector& keywords, Language& language, PokemonDetails& details){ - // the last five keywords should be: - - if (keywords.size() < 5){ - cerr << "Error: not enough number of keywords in the filename to generate PokemonDetails. Found only " << keywords.size() << "." << endl; - return 1; - } - - language = language_code_to_enum(keywords[keywords.size()-5]); - if (language == Language::None || language == Language::EndOfList){ - cerr << "Error: language keyword " << keywords[keywords.size()-5] << " is wrong." << endl; - return 1; - } - - const std::string& pokemon_slug = keywords[keywords.size()-4]; - details.name_candidates.insert(pokemon_slug); - - const std::string& shiny_word = keywords[keywords.size()-3]; - if (shiny_word == "Shiny"){ - details.is_shiny = true; - }else if (shiny_word == "NotShiny"){ - details.is_shiny = false; - }else{ - cerr << "Error: shiny keyword " << shiny_word << " is wrong. Must be \"Shiny\" or \"NotShiny\"." << endl; - return 1; - } - - const std::string& alpha_word = keywords[keywords.size()-2]; - if (alpha_word == "Alpha"){ - details.is_alpha = true; - }else if (alpha_word == "NotAlpha"){ - details.is_alpha = false; - }else{ - cerr << "Error: alpha keyword " << alpha_word << " is wrong. Must be \"Alpha\" or \"NotAlpha\"." << endl; - return 1; - } - - const std::string& gender_word = keywords[keywords.size()-1]; - if (gender_word == "Male"){ - details.gender = Gender::Male; - }else if (gender_word == "Female"){ - details.gender = Gender::Female; - }else if (gender_word == "Genderless"){ - details.gender = Gender::Genderless; - }else{ - cerr << "Error: gender keyword " << gender_word << " is wrong. Must be \"Male\", \"Female\" or \"Genderless\"." << endl; - return 1; - } - - return 0; -} - -int test_pokemon_details(const PokemonDetails& details, const PokemonDetails& target){ - TEST_RESULT_COMPONENT_EQUAL(details.is_shiny, target.is_shiny, "shiny"); - TEST_RESULT_COMPONENT_EQUAL(details.is_alpha, target.is_alpha, "alpha"); - TEST_RESULT_COMPONENT_EQUAL_WITH_PRINT_FUNC(details.gender, target.gender, "gender", get_gender_str); - - const std::string& pokemon_slug = *target.name_candidates.begin(); - bool found_name = false; - for(const auto& slg : details.name_candidates){ - if (slg == pokemon_slug){ - found_name = true; - break; - } - } - if (found_name == false){ - cerr << "Error: " << __func__ << " name result is "; - for(const auto& slg : details.name_candidates){ - cerr << slg << ", "; - } - cerr << "but should be " << pokemon_slug << "." << endl; - return 1; - } - - return 0; -} - -int test_pokemonLA_StatusInfoScreenDetector(const ImageViewRGB32& image, const std::vector& keywords){ - // the last five keywords should be: - Language language = Language::None; - PokemonDetails target; - - int ret = read_pokemon_info_from_words(keywords, language, target); - if (ret != 0){ - return ret; - } - - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - const PokemonDetails details = read_status_info(logger, overlay, image, language); - - return test_pokemon_details(details, target); -} - -int test_pokemonLA_WildPokemonFocusDetector(const ImageViewRGB32& image, const std::vector& keywords){ - // two keywords: - if (keywords.size() < 2){ - cerr << "Error: not enough number of keywords in the filename. Found only " << keywords.size() << "." << endl; - return 1; - } - - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - - WildPokemonFocusDetector detector(logger, overlay); - bool result_has_focus = detector.process_frame(image, current_time()); - - auto check_can_change_focus = [&](const std::string& word) -> int { - bool result_can_change = detect_change_focus(logger, overlay, image); - bool target_can_change = false; - if (parse_bool(word, target_can_change) == false){ - cerr << "Error: True/False keyword " << word << " is wrong. Must be \"True\" or \"False\"." << endl; - return 1; - } - TEST_RESULT_EQUAL(result_can_change, target_can_change); - return 0; - }; - - bool target_has_focus = false; - if (parse_bool(keywords[keywords.size()-2], target_has_focus) == true){ - TEST_RESULT_EQUAL(result_has_focus, target_has_focus); - - return check_can_change_focus(keywords[keywords.size()-1]); - } - - // Or seven keywords: - // the last seven keywords should be: - if (keywords.size() < 7){ - cerr << "Error: not enough number of keywords in the filename. Found only " << keywords.size() << "." << endl; - return 1; - } - - if (parse_bool(keywords[keywords.size()-7], target_has_focus) == false){ - cerr << "Error: True/False keyword " << keywords[keywords.size()-7] << " is wrong. Must be \"True\" or \"False\"." << endl; - return 1; - } - - TEST_RESULT_EQUAL(result_has_focus, target_has_focus); - - if (result_has_focus){ - int ret = check_can_change_focus(keywords[keywords.size()-6]); - if (ret != 0){ - return ret; - } - - Language language = Language::None; - PokemonDetails target_info; - ret = read_pokemon_info_from_words(keywords, language, target_info); - if (ret != 0){ - return ret; - } - - const auto info = read_focused_wild_pokemon_info(logger, overlay, image, language); - - return test_pokemon_details(info, target_info); - } - - return 0; -} - - -int test_pokemonLA_BattleSpriteWatcher(const ImageViewRGB32& image, const std::vector& keywords){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - - std::vector target; - for(auto it = keywords.rbegin(); it != keywords.rend(); it++){ - const auto& word = *it; - if (word == "0"){ - target.push_back(false); - }else if (word == "1"){ - target.push_back(true); - }else{ - break; - } - } - target.resize(MAX_WILD_POKEMON_IN_MULTI_BATTLE, false); - - BattleSpriteWatcher watcher(logger, overlay); - - watcher.process_frame(image, current_time()); - - auto result = watcher.sprites_appeared(); - - for(size_t i = 0; i < MAX_WILD_POKEMON_IN_MULTI_BATTLE; i++){ - if (result[i] != target[i]){ - cerr << "Error: in test_pokemonLA_BattleSpriteWatcher sprite " << i << " has " << result[i] << ", but should be " << target[i] << endl; - return 1; - } - } - - return 0; -} - - -int test_pokemonLA_MapMarkerLocator(const ImageViewRGB32& image, float target_angle, float threshold){ - float angle = get_orientation_on_map(image); - TEST_RESULT_APPROXIMATE(angle, target_angle, threshold); - return 0; -} - -int test_pokemonLA_MapZoomLevelReader(const ImageViewRGB32& image, int target){ - int zoom = read_map_zoom_level(image); - TEST_RESULT_EQUAL(zoom, target); - return 0; -} - -int test_pokemonLA_BattleSpriteArrowDetector(const ImageViewRGB32& image, int target){ - auto& logger = global_logger_command_line(); - auto overlay = DummyVideoOverlay(); - - const size_t target_index = target; - for(size_t sprite_index = 0; sprite_index < MAX_WILD_POKEMON_IN_MULTI_BATTLE; sprite_index++){ - BattleSpriteArrowDetector detector(logger, overlay, sprite_index, std::chrono::milliseconds(0), true); - bool result = detector.process_frame(image, current_time()); - if (sprite_index != target_index && result){ - cerr << "Error: in test_pokemonLA_BattleSpriteArrowDetector detected arrow at sprite index " << sprite_index - << " but should be at sprite index " << target << endl; - return 1; - }else if (sprite_index == target_index && result == false){ - cerr << "Error: in test_pokemonLA_BattleSpriteArrowDetector failed to detect arrow at sprite index " << sprite_index << endl; - return 1; - } - } - - return 0; -} - -int test_pokemonLA_MapMissionTabReader(const ImageViewRGB32& image, bool target){ - bool result = is_map_mission_tab_raised(image); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -int test_pokemonLA_BerryTreeDetector(const ImageViewRGB32& image){ - BerryTreeDetector detector; - - detector.process_frame(image, current_time()); - - return 0; -} - -int test_pokemonLA_SaveScreenDetector(const ImageViewRGB32& image, const std::vector& keywords){ - // two keywords: - if (keywords.size() < 2){ - cerr << "Error: not enough number of keywords in the filename. Found only " << keywords.size() << "." << endl; - return 1; - } - - bool target_save_tab = false; - if (parse_bool(keywords[keywords.size()-2], target_save_tab) == false){ - cerr << "Error: True/False keyword " << keywords[keywords.size()-2] << " is wrong. Must be \"True\" or \"False\"." << endl; - return 1; - } - bool target_save_disabled = false; - if (parse_bool(keywords[keywords.size()-1], target_save_disabled) == false){ - cerr << "Error: True/False keyword " << keywords[keywords.size()-1] << " is wrong. Must be \"True\" or \"False\"." << endl; - return 1; - } - - bool save_tab = save_tab_selected(image); - bool save_disabled = save_tab_disabled(image); - - TEST_RESULT_COMPONENT_EQUAL(save_tab, target_save_tab, "save tab"); - TEST_RESULT_COMPONENT_EQUAL(save_disabled, target_save_disabled, "save disabled"); - - return 0; -} - - -int test_pokemonLA_shinySoundDetector(const std::vector& spectrums, bool target){ - auto& logger = global_logger_command_line(); - DummyBotBase botbase(logger); - SerialPABotBase::SerialPABotBase_Connection connection(logger, nullptr, {}); - SerialPABotBase_PokkenController controller(logger, connection); - DummyVideoFeed video_feed; - DummyVideoOverlay video_overlay; - DummyAudioFeed audio_feed; - StreamHistorySession history(logger); - - ConsoleHandle console(0, logger, controller, video_feed, video_overlay, audio_feed, history); - ShinySoundDetector detector(console, [&](float error_coefficient) -> bool{ - return true; - }); - - bool result = detector.process_spectrums(spectrums, audio_feed); - TEST_RESULT_EQUAL(result, target); - return 0; -} - -// Load an image with MMO question marks from an MMO event, with filename -// Load an image with MMO question marks revealed by Munchlax to show each pokemon sprite from the same MMO event, with filename <_XXX.png> -// Load a text file with each line the pokemon in the MMO event, with filename <_XXX.txt>. If more than one pokemon of the same species appears, -// add a number as the number of appearance at end of that line. -int test_pokemonLA_MMOSpriteMatcher(const std::string& filepath){ - auto& logger = global_logger_command_line(); - const QString full_path(QString::fromStdString(filepath)); - const QFileInfo fileinfo(full_path); - const QString filename = fileinfo.fileName(); - const QDir parent_dir = fileinfo.dir(); - - const std::string base_name = fileinfo.baseName().toStdString(); - - const std::vector filename_words = parse_words(base_name); - MapRegion region = MapRegion::NONE; - for(const std::string& word : filename_words){ - if (word == "Fieldlands"){ - region = MapRegion::FIELDLANDS; - break; - }else if (word == "Mirelands"){ - region = MapRegion::MIRELANDS; - break; - }else if (word == "Coastlands"){ - region = MapRegion::COASTLANDS; - break; - }else if (word == "Highlands"){ - region = MapRegion::HIGHLANDS; - break; - }else if (word == "Icelands"){ - region = MapRegion::ICELANDS; - break; - } - } - if (region == MapRegion::NONE){ - cout << "Error: filename should contain a region name (e.g. \"Fieldlands\")." << endl; - return 1; - } - - const QString mmo_revealed_image_path = parent_dir.filePath("_" + filename); - const QString mmo_revealed_txt_path = parent_dir.filePath("_" + fileinfo.baseName() + ".txt"); - - ImageRGB32 question_mark_image(filepath); - ImageRGB32 sprite_image(mmo_revealed_image_path.toStdString()); - - if (!question_mark_image){ - cerr << "Error: cannot load MMO question mark image file " << filepath << endl; - return 1; - } - if (!sprite_image){ - cerr << "Error: cannot load MMO revealed sprites image file " << mmo_revealed_image_path.toStdString() << endl; - return 1; - } - - std::vector target_sprites; - if (load_slug_list(mmo_revealed_txt_path.toStdString(), target_sprites) == false){ - return 1; - } - - cout << "Target sprites: " << target_sprites.size() << " total" << endl; - for(const auto& slug : target_sprites){ - cout << "- " << slug << endl; - } - - MMOQuestionMarkDetector detector(logger); - - std::vector quest_results = detector.detect_MMOs_on_region_map(question_mark_image); - std::sort(quest_results.begin(), quest_results.end(), [](const ImagePixelBox& a, const ImagePixelBox& b) -> bool { - if (a.center_y() < b.center_y()){ - return true; - } - if (a.center_y() > b.center_y()){ - return false; - } - return a.center_x() < b.center_x(); - }); - - cout << "Detect MMO question marks:" << endl; - for(const auto& box : quest_results){ - cout << "- " << box.center_x() << ", " << box.center_y() << " " << box.width() << " x " << box.height() << endl; - } - - if (quest_results.size() != target_sprites.size()){ - cerr << "Error: the number of MMO question marks detected is not correct: " << quest_results.size() << " should be " << - target_sprites.size() << endl; - return 1; - } - - // static int count = 0; - ImageRGB32 output_sprite = sprite_image.copy(); - ImageRGB32 output_quest = question_mark_image.copy(); - std::vector new_boxes; - for (size_t i = 0; i < quest_results.size(); i++){ - auto box = quest_results[i]; - draw_box(output_quest, box, combine_rgb(255, 0, 0)); - draw_box(output_sprite, box, combine_rgb(255, 0, 0)); - - pxint_t radius = (pxint_t)((box.width() + box.height()) / 4 + 0.5); - pxint_t center_x = (pxint_t)box.center_x(); - pxint_t center_y = (pxint_t)box.center_y(); - auto new_box = ImagePixelBox(center_x - radius, center_y - radius, center_x + radius, center_y + radius); - new_boxes.push_back(new_box); - - // std::ostringstream os; - // os << "test_sprite_" << count << "_" << std::setfill('0') << std::setw(2) << i << ".png"; - // std::string sprite_filename = os.str(); - // extract_box_reference(sprite_image, new_box).save(sprite_filename); - } - // output_quest.save("test_MMO_question_mark_detection_" + std::to_string(count) + ".png"); - // output_sprite.save("test_sprite_detection_" + std::to_string(count) + ".png"); - - size_t success_count = 0; - for (size_t i = 0; i < quest_results.size(); i++){ - // XXX - // if (i != 9){ - // continue; - // } - cout << "--------------------------------------------------------------------" << endl; - cout << i << ": Target slug: " << target_sprites[i] << endl; - - bool debug_mode = false; - auto result = match_sprite_on_map(logger, sprite_image, new_boxes[i], region, debug_mode); - if (result.slug == target_sprites[i]){ - success_count++; - cout << "Match SUCCESS" << endl; - }else{ - cout << "Match FAILURE" << endl; - } - } - - if (success_count == target_sprites.size()){ - cout << "ALL SUCCESS" << endl; - }else{ - cout << "FAILURE: " << target_sprites.size() - success_count << "/" << target_sprites.size() << endl; - return 1; - } - // count++; - - return 0; -} - -int test_pokemonLA_MapWeatherAndTimeReader(const ImageViewRGB32& image, const std::vector& keywords){ - // two keywords: